From solipsis at pitrou.net Sat May 1 00:38:47 2010 From: solipsis at pitrou.net (solipsis at pitrou.net) Date: Sat, 1 May 2010 00:38:47 +0200 (CEST) Subject: [Python-checkins] Daily py3k reference leaks (r80666): sum=0 Message-ID: <20100430223847.6A6D61770A@ns6635.ovh.net> py3k results for svn r80666 (hg cset e2c69a035101) -------------------------------------------------- Command line was: ['./python', '-m', 'test.regrtest', '-uall', '-R', '3:3:/home/antoine/py3k/refleaks/reflogzf5yMM', '-x'] From python-checkins at python.org Sat May 1 01:02:48 2010 From: python-checkins at python.org (jeffrey.yasskin) Date: Sat, 1 May 2010 01:02:48 +0200 (CEST) Subject: [Python-checkins] r80668 - in sandbox/trunk/2to3/lib2to3: fixes/fix_operator.py main.py patcomp.py pgen2/tokenize.py pytree.py refactor.py tests/test_parser.py tests/test_pytree.py tests/test_refactor.py Message-ID: <20100430230248.35B06EEA13@mail.python.org> Author: jeffrey.yasskin Date: Sat May 1 01:02:47 2010 New Revision: 80668 Log: Make 2to3 run under Python 2.5 so that the benchmark suite at http://hg.python.org/benchmarks/ can use it and still run on implementations that haven't gotten to 2.6 yet. Fixes issue 8566. Modified: sandbox/trunk/2to3/lib2to3/fixes/fix_operator.py sandbox/trunk/2to3/lib2to3/main.py sandbox/trunk/2to3/lib2to3/patcomp.py sandbox/trunk/2to3/lib2to3/pgen2/tokenize.py sandbox/trunk/2to3/lib2to3/pytree.py sandbox/trunk/2to3/lib2to3/refactor.py sandbox/trunk/2to3/lib2to3/tests/test_parser.py sandbox/trunk/2to3/lib2to3/tests/test_pytree.py sandbox/trunk/2to3/lib2to3/tests/test_refactor.py Modified: sandbox/trunk/2to3/lib2to3/fixes/fix_operator.py ============================================================================== --- sandbox/trunk/2to3/lib2to3/fixes/fix_operator.py (original) +++ sandbox/trunk/2to3/lib2to3/fixes/fix_operator.py Sat May 1 01:02:47 2010 @@ -14,10 +14,10 @@ func = "'(' func=any ')'" PATTERN = """ power< module='operator' - trailer< '.' {methods} > trailer< {func} > > + trailer< '.' %(methods)s > trailer< %(func)s > > | - power< {methods} trailer< {func} > > - """.format(methods=methods, func=func) + power< %(methods)s trailer< %(func)s > > + """ % dict(methods=methods, func=func) def transform(self, node, results): method = results["method"][0] Modified: sandbox/trunk/2to3/lib2to3/main.py ============================================================================== --- sandbox/trunk/2to3/lib2to3/main.py (original) +++ sandbox/trunk/2to3/lib2to3/main.py Sat May 1 01:02:47 2010 @@ -2,6 +2,8 @@ Main program for 2to3. """ +from __future__ import with_statement + import sys import os import difflib Modified: sandbox/trunk/2to3/lib2to3/patcomp.py ============================================================================== --- sandbox/trunk/2to3/lib2to3/patcomp.py (original) +++ sandbox/trunk/2to3/lib2to3/patcomp.py Sat May 1 01:02:47 2010 @@ -57,7 +57,7 @@ tokens = tokenize_wrapper(input) try: root = self.driver.parse_tokens(tokens, debug=debug) - except parse.ParseError as e: + except parse.ParseError, e: raise PatternSyntaxError(str(e)) return self.compile_node(root) Modified: sandbox/trunk/2to3/lib2to3/pgen2/tokenize.py ============================================================================== --- sandbox/trunk/2to3/lib2to3/pgen2/tokenize.py (original) +++ sandbox/trunk/2to3/lib2to3/pgen2/tokenize.py Sat May 1 01:02:47 2010 @@ -38,6 +38,13 @@ "generate_tokens", "untokenize"] del token +try: + bytes +except NameError: + # Support bytes type in Python <= 2.5, so 2to3 turns itself into + # valid Python 3 code. + bytes = str + def group(*choices): return '(' + '|'.join(choices) + ')' def any(*choices): return group(*choices) + '*' def maybe(*choices): return group(*choices) + '?' @@ -265,7 +272,7 @@ try: return readline() except StopIteration: - return b'' + return bytes() def find_cookie(line): try: Modified: sandbox/trunk/2to3/lib2to3/pytree.py ============================================================================== --- sandbox/trunk/2to3/lib2to3/pytree.py (original) +++ sandbox/trunk/2to3/lib2to3/pytree.py Sat May 1 01:02:47 2010 @@ -289,8 +289,7 @@ for node in child.post_order(): yield node - @property - def prefix(self): + def _prefix_getter(self): """ The whitespace and comments preceding this node in the input. """ @@ -298,11 +297,12 @@ return "" return self.children[0].prefix - @prefix.setter - def prefix(self, prefix): + def _prefix_setter(self, prefix): if self.children: self.children[0].prefix = prefix + prefix = property(_prefix_getter, _prefix_setter) + def set_child(self, i, child): """ Equivalent to 'node.children[i] = child'. This method also sets the @@ -390,18 +390,17 @@ """Return a pre-order iterator for the tree.""" yield self - @property - def prefix(self): + def _prefix_getter(self): """ The whitespace and comments preceding this token in the input. """ return self._prefix - @prefix.setter - def prefix(self, prefix): + def _prefix_setter(self, prefix): self.changed() self._prefix = prefix + prefix = property(_prefix_getter, _prefix_setter) def convert(gr, raw_node): """ Modified: sandbox/trunk/2to3/lib2to3/refactor.py ============================================================================== --- sandbox/trunk/2to3/lib2to3/refactor.py (original) +++ sandbox/trunk/2to3/lib2to3/refactor.py Sat May 1 01:02:47 2010 @@ -8,6 +8,8 @@ provides infrastructure to write your own refactoring tool. """ +from __future__ import with_statement + __author__ = "Guido van Rossum " @@ -126,7 +128,7 @@ have_docstring = False gen = tokenize.generate_tokens(StringIO.StringIO(source).readline) def advance(): - tok = next(gen) + tok = gen.next() return tok[0], tok[1] ignore = frozenset((token.NEWLINE, tokenize.NL, token.COMMENT)) features = set() Modified: sandbox/trunk/2to3/lib2to3/tests/test_parser.py ============================================================================== --- sandbox/trunk/2to3/lib2to3/tests/test_parser.py (original) +++ sandbox/trunk/2to3/lib2to3/tests/test_parser.py Sat May 1 01:02:47 2010 @@ -6,13 +6,14 @@ test_grammar.py files from both Python 2 and Python 3. """ +from __future__ import with_statement + # Testing imports from . import support from .support import driver, test_dir # Python imports import os -import io import sys # Local imports @@ -156,8 +157,9 @@ encoding = tokenize.detect_encoding(fp.readline)[0] self.assertTrue(encoding is not None, "can't detect encoding for %s" % filepath) - with io.open(filepath, "r", encoding=encoding) as fp: + with open(filepath, "r") as fp: source = fp.read() + source = source.decode(encoding) tree = driver.parse_string(source) new = unicode(tree) if diff(filepath, new, encoding): @@ -203,9 +205,9 @@ def diff(fn, result, encoding): - f = io.open("@", "w", encoding=encoding) + f = open("@", "w") try: - f.write(result) + f.write(result.encode(encoding)) finally: f.close() try: Modified: sandbox/trunk/2to3/lib2to3/tests/test_pytree.py ============================================================================== --- sandbox/trunk/2to3/lib2to3/tests/test_pytree.py (original) +++ sandbox/trunk/2to3/lib2to3/tests/test_pytree.py Sat May 1 01:02:47 2010 @@ -9,6 +9,9 @@ especially when debugging a test. """ +from __future__ import with_statement + +import sys import warnings # Testing imports @@ -28,20 +31,22 @@ """Unit tests for nodes (Base, Leaf, Node).""" - def test_deprecated_prefix_methods(self): - l = pytree.Leaf(100, "foo") - with warnings.catch_warnings(record=True) as w: - warnings.simplefilter("always", DeprecationWarning) - self.assertEqual(l.get_prefix(), "") - l.set_prefix("hi") - self.assertEqual(l.prefix, "hi") - self.assertEqual(len(w), 2) - for warning in w: - self.assertTrue(warning.category is DeprecationWarning) - self.assertEqual(str(w[0].message), "get_prefix() is deprecated; " \ - "use the prefix property") - self.assertEqual(str(w[1].message), "set_prefix() is deprecated; " \ - "use the prefix property") + if sys.version_info >= (2,6): + # warnings.catch_warnings is new in 2.6. + def test_deprecated_prefix_methods(self): + l = pytree.Leaf(100, "foo") + with warnings.catch_warnings(record=True) as w: + warnings.simplefilter("always", DeprecationWarning) + self.assertEqual(l.get_prefix(), "") + l.set_prefix("hi") + self.assertEqual(l.prefix, "hi") + self.assertEqual(len(w), 2) + for warning in w: + self.assertTrue(warning.category is DeprecationWarning) + self.assertEqual(str(w[0].message), "get_prefix() is deprecated; " \ + "use the prefix property") + self.assertEqual(str(w[1].message), "set_prefix() is deprecated; " \ + "use the prefix property") def test_instantiate_base(self): if __debug__: Modified: sandbox/trunk/2to3/lib2to3/tests/test_refactor.py ============================================================================== --- sandbox/trunk/2to3/lib2to3/tests/test_refactor.py (original) +++ sandbox/trunk/2to3/lib2to3/tests/test_refactor.py Sat May 1 01:02:47 2010 @@ -2,6 +2,8 @@ Unit tests for refactor.py. """ +from __future__ import with_statement + import sys import os import codecs From python-checkins at python.org Sat May 1 01:08:48 2010 From: python-checkins at python.org (antoine.pitrou) Date: Sat, 1 May 2010 01:08:48 +0200 (CEST) Subject: [Python-checkins] r80669 - in python/trunk: Lib/test/test_multiprocessing.py Lib/test/test_smtplib.py Misc/NEWS Message-ID: <20100430230848.BD728EE988@mail.python.org> Author: antoine.pitrou Date: Sat May 1 01:08:48 2010 New Revision: 80669 Log: Issue #8576: Remove use of find_unused_port() in test_smtplib and test_multiprocessing. Patch by Paul Moore. Modified: python/trunk/Lib/test/test_multiprocessing.py python/trunk/Lib/test/test_smtplib.py python/trunk/Misc/NEWS Modified: python/trunk/Lib/test/test_multiprocessing.py ============================================================================== --- python/trunk/Lib/test/test_multiprocessing.py (original) +++ python/trunk/Lib/test/test_multiprocessing.py Sat May 1 01:08:48 2010 @@ -1262,9 +1262,9 @@ def test_rapid_restart(self): authkey = os.urandom(32) - port = test_support.find_unused_port() manager = QueueManager( - address=('localhost', port), authkey=authkey, serializer=SERIALIZER) + address=('localhost', 0), authkey=authkey, serializer=SERIALIZER) + addr = manager.get_server().address manager.start() p = self.Process(target=self._putter, args=(manager.address, authkey)) @@ -1274,7 +1274,7 @@ del queue manager.shutdown() manager = QueueManager( - address=('localhost', port), authkey=authkey, serializer=SERIALIZER) + address=addr, authkey=authkey, serializer=SERIALIZER) manager.start() manager.shutdown() Modified: python/trunk/Lib/test/test_smtplib.py ============================================================================== --- python/trunk/Lib/test/test_smtplib.py (original) +++ python/trunk/Lib/test/test_smtplib.py Sat May 1 01:08:48 2010 @@ -155,8 +155,10 @@ self._threads = test_support.threading_setup() self.serv_evt = threading.Event() self.client_evt = threading.Event() - self.port = test_support.find_unused_port() - self.serv = smtpd.DebuggingServer((HOST, self.port), ('nowhere', -1)) + # Pick a random unused port by passing 0 for the port number + self.serv = smtpd.DebuggingServer((HOST, 0), ('nowhere', -1)) + # Keep a note of what port was assigned + self.port = self.serv.socket.getsockname()[1] serv_args = (self.serv, self.serv_evt, self.client_evt) self.thread = threading.Thread(target=debugging_server, args=serv_args) self.thread.start() @@ -392,8 +394,10 @@ self._threads = test_support.threading_setup() self.serv_evt = threading.Event() self.client_evt = threading.Event() - self.port = test_support.find_unused_port() - self.serv = SimSMTPServer((HOST, self.port), ('nowhere', -1)) + # Pick a random unused port by passing 0 for the port number + self.serv = SimSMTPServer((HOST, 0), ('nowhere', -1)) + # Keep a note of what port was assigned + self.port = self.serv.socket.getsockname()[1] serv_args = (self.serv, self.serv_evt, self.client_evt) self.thread = threading.Thread(target=debugging_server, args=serv_args) self.thread.start() Modified: python/trunk/Misc/NEWS ============================================================================== --- python/trunk/Misc/NEWS (original) +++ python/trunk/Misc/NEWS Sat May 1 01:08:48 2010 @@ -134,6 +134,9 @@ Tests ----- +- Issue #8576: Remove use of find_unused_port() in test_smtplib and + test_multiprocessing. Patch by Paul Moore. + - Issue #7449: Fix many tests to support Python compiled without thread support. Patches written by Jerry Seutter. From python-checkins at python.org Sat May 1 01:10:44 2010 From: python-checkins at python.org (antoine.pitrou) Date: Sat, 1 May 2010 01:10:44 +0200 (CEST) Subject: [Python-checkins] r80670 - in python/branches/release26-maint: Lib/test/test_multiprocessing.py Lib/test/test_smtplib.py Misc/NEWS Message-ID: <20100430231044.45031EE9E9@mail.python.org> Author: antoine.pitrou Date: Sat May 1 01:10:44 2010 New Revision: 80670 Log: Merged revisions 80669 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r80669 | antoine.pitrou | 2010-05-01 01:08:48 +0200 (sam., 01 mai 2010) | 4 lines Issue #8576: Remove use of find_unused_port() in test_smtplib and test_multiprocessing. Patch by Paul Moore. ........ Modified: python/branches/release26-maint/ (props changed) python/branches/release26-maint/Lib/test/test_multiprocessing.py python/branches/release26-maint/Lib/test/test_smtplib.py python/branches/release26-maint/Misc/NEWS Modified: python/branches/release26-maint/Lib/test/test_multiprocessing.py ============================================================================== --- python/branches/release26-maint/Lib/test/test_multiprocessing.py (original) +++ python/branches/release26-maint/Lib/test/test_multiprocessing.py Sat May 1 01:10:44 2010 @@ -1205,9 +1205,9 @@ def test_rapid_restart(self): authkey = os.urandom(32) - port = test_support.find_unused_port() manager = QueueManager( - address=('localhost', port), authkey=authkey, serializer=SERIALIZER) + address=('localhost', 0), authkey=authkey, serializer=SERIALIZER) + addr = manager.get_server().address manager.start() p = self.Process(target=self._putter, args=(manager.address, authkey)) @@ -1217,7 +1217,7 @@ del queue manager.shutdown() manager = QueueManager( - address=('localhost', port), authkey=authkey, serializer=SERIALIZER) + address=addr, authkey=authkey, serializer=SERIALIZER) manager.start() manager.shutdown() Modified: python/branches/release26-maint/Lib/test/test_smtplib.py ============================================================================== --- python/branches/release26-maint/Lib/test/test_smtplib.py (original) +++ python/branches/release26-maint/Lib/test/test_smtplib.py Sat May 1 01:10:44 2010 @@ -144,8 +144,10 @@ self.serv_evt = threading.Event() self.client_evt = threading.Event() - self.port = test_support.find_unused_port() - self.serv = smtpd.DebuggingServer((HOST, self.port), ('nowhere', -1)) + # Pick a random unused port by passing 0 for the port number + self.serv = smtpd.DebuggingServer((HOST, 0), ('nowhere', -1)) + # Keep a note of what port was assigned + self.port = self.serv.socket.getsockname()[1] serv_args = (self.serv, self.serv_evt, self.client_evt) threading.Thread(target=debugging_server, args=serv_args).start() @@ -371,8 +373,10 @@ def setUp(self): self.serv_evt = threading.Event() self.client_evt = threading.Event() - self.port = test_support.find_unused_port() - self.serv = SimSMTPServer((HOST, self.port), ('nowhere', -1)) + # Pick a random unused port by passing 0 for the port number + self.serv = SimSMTPServer((HOST, 0), ('nowhere', -1)) + # Keep a note of what port was assigned + self.port = self.serv.socket.getsockname()[1] serv_args = (self.serv, self.serv_evt, self.client_evt) threading.Thread(target=debugging_server, args=serv_args).start() Modified: python/branches/release26-maint/Misc/NEWS ============================================================================== --- python/branches/release26-maint/Misc/NEWS (original) +++ python/branches/release26-maint/Misc/NEWS Sat May 1 01:10:44 2010 @@ -140,6 +140,9 @@ Tests ----- +- Issue #8576: Remove use of find_unused_port() in test_smtplib and + test_multiprocessing. Patch by Paul Moore. + - Issue #7027: regrtest.py keeps a reference to the encodings.ascii module as a workaround to #7140 bug From python-checkins at python.org Sat May 1 01:20:15 2010 From: python-checkins at python.org (antoine.pitrou) Date: Sat, 1 May 2010 01:20:15 +0200 (CEST) Subject: [Python-checkins] r80671 - in python/branches/py3k: Lib/test/test_multiprocessing.py Lib/test/test_smtplib.py Misc/NEWS Message-ID: <20100430232015.C498AEEA25@mail.python.org> Author: antoine.pitrou Date: Sat May 1 01:20:15 2010 New Revision: 80671 Log: Merged revisions 80669 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r80669 | antoine.pitrou | 2010-05-01 01:08:48 +0200 (sam., 01 mai 2010) | 4 lines Issue #8576: Remove use of find_unused_port() in test_smtplib and test_multiprocessing. Patch by Paul Moore. ........ Modified: python/branches/py3k/ (props changed) python/branches/py3k/Lib/test/test_multiprocessing.py python/branches/py3k/Lib/test/test_smtplib.py python/branches/py3k/Misc/NEWS Modified: python/branches/py3k/Lib/test/test_multiprocessing.py ============================================================================== --- python/branches/py3k/Lib/test/test_multiprocessing.py (original) +++ python/branches/py3k/Lib/test/test_multiprocessing.py Sat May 1 01:20:15 2010 @@ -1256,9 +1256,9 @@ def test_rapid_restart(self): authkey = os.urandom(32) - port = test.support.find_unused_port() manager = QueueManager( - address=('localhost', port), authkey=authkey, serializer=SERIALIZER) + address=('localhost', 0), authkey=authkey, serializer=SERIALIZER) + addr = manager.get_server().address manager.start() p = self.Process(target=self._putter, args=(manager.address, authkey)) @@ -1268,7 +1268,7 @@ del queue manager.shutdown() manager = QueueManager( - address=('localhost', port), authkey=authkey, serializer=SERIALIZER) + address=addr, authkey=authkey, serializer=SERIALIZER) manager.start() manager.shutdown() Modified: python/branches/py3k/Lib/test/test_smtplib.py ============================================================================== --- python/branches/py3k/Lib/test/test_smtplib.py (original) +++ python/branches/py3k/Lib/test/test_smtplib.py Sat May 1 01:20:15 2010 @@ -163,8 +163,10 @@ self._threads = support.threading_setup() self.serv_evt = threading.Event() self.client_evt = threading.Event() - self.port = support.find_unused_port() - self.serv = smtpd.DebuggingServer((HOST, self.port), ('nowhere', -1)) + # Pick a random unused port by passing 0 for the port number + self.serv = smtpd.DebuggingServer((HOST, 0), ('nowhere', -1)) + # Keep a note of what port was assigned + self.port = self.serv.socket.getsockname()[1] serv_args = (self.serv, self.serv_evt, self.client_evt) self.thread = threading.Thread(target=debugging_server, args=serv_args) self.thread.start() @@ -400,8 +402,10 @@ self._threads = support.threading_setup() self.serv_evt = threading.Event() self.client_evt = threading.Event() - self.port = support.find_unused_port() - self.serv = SimSMTPServer((HOST, self.port), ('nowhere', -1)) + # Pick a random unused port by passing 0 for the port number + self.serv = SimSMTPServer((HOST, 0), ('nowhere', -1)) + # Keep a note of what port was assigned + self.port = self.serv.socket.getsockname()[1] serv_args = (self.serv, self.serv_evt, self.client_evt) self.thread = threading.Thread(target=debugging_server, args=serv_args) self.thread.start() Modified: python/branches/py3k/Misc/NEWS ============================================================================== --- python/branches/py3k/Misc/NEWS (original) +++ python/branches/py3k/Misc/NEWS Sat May 1 01:20:15 2010 @@ -1198,6 +1198,9 @@ Tests ----- +- Issue #8576: Remove use of find_unused_port() in test_smtplib and + test_multiprocessing. Patch by Paul Moore. + - Issue #7449: Fix many tests to support Python compiled without thread support. Patches written by Jerry Seutter. From python-checkins at python.org Sat May 1 01:23:38 2010 From: python-checkins at python.org (antoine.pitrou) Date: Sat, 1 May 2010 01:23:38 +0200 (CEST) Subject: [Python-checkins] r80672 - in python/branches/release31-maint: Lib/test/test_multiprocessing.py Lib/test/test_smtplib.py Misc/NEWS Message-ID: <20100430232338.708B7EEA18@mail.python.org> Author: antoine.pitrou Date: Sat May 1 01:23:38 2010 New Revision: 80672 Log: Merged revisions 80671 via svnmerge from svn+ssh://pythondev at svn.python.org/python/branches/py3k ................ r80671 | antoine.pitrou | 2010-05-01 01:20:15 +0200 (sam., 01 mai 2010) | 10 lines Merged revisions 80669 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r80669 | antoine.pitrou | 2010-05-01 01:08:48 +0200 (sam., 01 mai 2010) | 4 lines Issue #8576: Remove use of find_unused_port() in test_smtplib and test_multiprocessing. Patch by Paul Moore. ........ ................ Modified: python/branches/release31-maint/ (props changed) python/branches/release31-maint/Lib/test/test_multiprocessing.py python/branches/release31-maint/Lib/test/test_smtplib.py python/branches/release31-maint/Misc/NEWS Modified: python/branches/release31-maint/Lib/test/test_multiprocessing.py ============================================================================== --- python/branches/release31-maint/Lib/test/test_multiprocessing.py (original) +++ python/branches/release31-maint/Lib/test/test_multiprocessing.py Sat May 1 01:23:38 2010 @@ -1221,9 +1221,9 @@ def test_rapid_restart(self): authkey = os.urandom(32) - port = test.support.find_unused_port() manager = QueueManager( - address=('localhost', port), authkey=authkey, serializer=SERIALIZER) + address=('localhost', 0), authkey=authkey, serializer=SERIALIZER) + addr = manager.get_server().address manager.start() p = self.Process(target=self._putter, args=(manager.address, authkey)) @@ -1233,7 +1233,7 @@ del queue manager.shutdown() manager = QueueManager( - address=('localhost', port), authkey=authkey, serializer=SERIALIZER) + address=addr, authkey=authkey, serializer=SERIALIZER) manager.start() manager.shutdown() Modified: python/branches/release31-maint/Lib/test/test_smtplib.py ============================================================================== --- python/branches/release31-maint/Lib/test/test_smtplib.py (original) +++ python/branches/release31-maint/Lib/test/test_smtplib.py Sat May 1 01:23:38 2010 @@ -152,8 +152,10 @@ self.serv_evt = threading.Event() self.client_evt = threading.Event() - self.port = support.find_unused_port() - self.serv = smtpd.DebuggingServer((HOST, self.port), ('nowhere', -1)) + # Pick a random unused port by passing 0 for the port number + self.serv = smtpd.DebuggingServer((HOST, 0), ('nowhere', -1)) + # Keep a note of what port was assigned + self.port = self.serv.socket.getsockname()[1] serv_args = (self.serv, self.serv_evt, self.client_evt) threading.Thread(target=debugging_server, args=serv_args).start() @@ -379,8 +381,10 @@ def setUp(self): self.serv_evt = threading.Event() self.client_evt = threading.Event() - self.port = support.find_unused_port() - self.serv = SimSMTPServer((HOST, self.port), ('nowhere', -1)) + # Pick a random unused port by passing 0 for the port number + self.serv = SimSMTPServer((HOST, 0), ('nowhere', -1)) + # Keep a note of what port was assigned + self.port = self.serv.socket.getsockname()[1] serv_args = (self.serv, self.serv_evt, self.client_evt) threading.Thread(target=debugging_server, args=serv_args).start() Modified: python/branches/release31-maint/Misc/NEWS ============================================================================== --- python/branches/release31-maint/Misc/NEWS (original) +++ python/branches/release31-maint/Misc/NEWS Sat May 1 01:23:38 2010 @@ -137,6 +137,9 @@ Tests ----- +- Issue #8576: Remove use of find_unused_port() in test_smtplib and + test_multiprocessing. Patch by Paul Moore. + - Issue #8531: Skip test_ascii_formatd if ctypes module is missing - Issue #3864: Skip three test_signal tests on freebsd6 because they fail From python-checkins at python.org Sat May 1 01:29:59 2010 From: python-checkins at python.org (jeffrey.yasskin) Date: Sat, 1 May 2010 01:29:59 +0200 (CEST) Subject: [Python-checkins] r80673 - peps/trunk/pep-0291.txt Message-ID: <20100430232959.4707FEE988@mail.python.org> Author: jeffrey.yasskin Date: Sat May 1 01:29:59 2010 New Revision: 80673 Log: Mark 2to3 as compatible with python-2.5 per the discussion in issue 8566. Modified: peps/trunk/pep-0291.txt Modified: peps/trunk/pep-0291.txt ============================================================================== --- peps/trunk/pep-0291.txt (original) +++ peps/trunk/pep-0291.txt Sat May 1 01:29:59 2010 @@ -82,16 +82,19 @@ 2.4 with statement, conditional expressions, combined try/except/finally, relative imports, - yield expressions or generator.throw/send/close() + yield expressions or generator.throw/send/close(), + plus all features below - 2.5 ??? + 2.5 with statement without from __future__ import, + io module, str.format(), except as, + bytes, b'' literals, property.setter/deleter Backward Compatible Packages, Modules, and Tools Package/Module Maintainer(s) Python Version Notes -------------- ------------- -------------- ----- - 2to3 Benjamin Peterson 2.6 + 2to3 Benjamin Peterson 2.5 bsddb Greg Smith 2.1 Barry Warsaw compiler Jeremy Hylton 2.1 From python-checkins at python.org Sat May 1 03:19:16 2010 From: python-checkins at python.org (andrew.kuchling) Date: Sat, 1 May 2010 03:19:16 +0200 (CEST) Subject: [Python-checkins] r80674 - python/trunk/Doc/whatsnew/2.7.rst Message-ID: <20100501011916.9842CEE9AD@mail.python.org> Author: andrew.kuchling Date: Sat May 1 03:19:16 2010 New Revision: 80674 Log: Add various items Modified: python/trunk/Doc/whatsnew/2.7.rst Modified: python/trunk/Doc/whatsnew/2.7.rst ============================================================================== --- python/trunk/Doc/whatsnew/2.7.rst (original) +++ python/trunk/Doc/whatsnew/2.7.rst Sat May 1 03:19:16 2010 @@ -8,7 +8,7 @@ .. Fix accents on Kristjan Valur Jonsson, Fuerstenau -.. Big jobs: ElementTree 1.3, pep 391, sysconfig +.. Big jobs: ElementTree 1.3, pep 391, sysconfig, memoryview .. unittest test discovery .. hyperlink all the methods & functions. @@ -615,6 +615,10 @@ (Contributed by Amaury Forgeot d'Arc, after a suggestion by George Sakkis; :issue:`5982`.) +* When a restricted set of attributes were set using ``__slots__``, + deleting an unset attribute would not raise :exc:`AttributeError` + as you would expect. Fixed by Benjamin Peterson; :issue:`7604`.) + * A new encoding named "cp720", used primarily for Arabic text, is now supported. (Contributed by Alexander Belchenko and Amaury Forgeot d'Arc; :issue:`1616979`.) @@ -1012,6 +1016,13 @@ giving the source address that will be used for the connection. (Contributed by Eldon Ziegler; :issue:`3972`.) +* The :mod:`ihooks` module now supports relative imports. Note that + :mod:`ihooks` is an older module used to support customizing imports, + superseded by the :mod:`imputil` module added in Python 2.0. + (Relative import support added by Neil Schemenauer.) + + .. revision 75423 + * The :mod:`imaplib` module now supports IPv6 addresses. (Contributed by Derek Morr; :issue:`1655`.) @@ -1314,6 +1325,12 @@ * The :class:`~UserDict.UserDict` class is now a new-style class. (Changed by Benjamin Peterson.) +* New class: the :class:`~weakref.WeakSet` class in the :mod:`weakref` + module is a set that only holds weak references to its elements; elements + will be removed once there are no references pointing to them. + (Originally implemented in Python 3.x by Raymond Hettinger, and backported + to 2.7 by Michael Foord.) + * The ElementTree library, :mod:`xml.etree`, no longer escapes ampersands and angle brackets when outputting an XML processing instruction (which looks like ````) @@ -1677,6 +1694,11 @@ .. XXX these macros don't seem to be described in the c-api docs. +* Removed function: :cmacro:`PyEval_CallObject` is now only available + as a macro. A function version was being kept around to preserve + ABI linking compatibility, but that was in 1997; it can certainly be + deleted. (Removed by Antoine Pitrou; :issue:`8276`.) + * New format codes: the :cfunc:`PyFormat_FromString`, :cfunc:`PyFormat_FromStringV`, and :cfunc:`PyErr_Format` now accepts ``%lld`` and ``%llu`` format codes for displaying values of @@ -1855,10 +1877,9 @@ affects new-style classes (derived from :class:`object`) and C extension types. (:issue:`6101`.) -* The :meth:`readline` method of :class:`StringIO` objects now does - nothing when a negative length is requested, as other file-like - objects do. (:issue:`7348`). - +* When a restricted set of attributes were set using ``__slots__``, + deleting an unset attribute would not raise :exc:`AttributeError` + as you would expect. Fixed by Benjamin Peterson; :issue:`7604`.) In the standard library: @@ -1880,6 +1901,10 @@ or comment (which looks like ``). (Patch by Neil Muller; :issue:`2746`.) +* The :meth:`readline` method of :class:`StringIO` objects now does + nothing when a negative length is requested, as other file-like + objects do. (:issue:`7348`). + * The :mod:`syslog` module will now use the value of ``sys.argv[0]`` as the identifier instead of the previous default value of ``'python'``. (Changed by Sean Reifschneider; :issue:`8451`.) From ncoghlan at gmail.com Sat May 1 06:05:10 2010 From: ncoghlan at gmail.com (Nick Coghlan) Date: Sat, 01 May 2010 14:05:10 +1000 Subject: [Python-checkins] r80674 - python/trunk/Doc/whatsnew/2.7.rst In-Reply-To: <20100501011916.9842CEE9AD@mail.python.org> References: <20100501011916.9842CEE9AD@mail.python.org> Message-ID: <4BDBA876.8040806@gmail.com> andrew.kuchling wrote: > @@ -615,6 +615,10 @@ > (Contributed by Amaury Forgeot d'Arc, after a suggestion by > George Sakkis; :issue:`5982`.) > > +* When a restricted set of attributes were set using ``__slots__``, > + deleting an unset attribute would not raise :exc:`AttributeError` > + as you would expect. Fixed by Benjamin Peterson; :issue:`7604`.) > + > * A new encoding named "cp720", used primarily for Arabic text, is now > supported. (Contributed by Alexander Belchenko and Amaury Forgeot > d'Arc; :issue:`1616979`.) > @@ -1855,10 +1877,9 @@ > affects new-style classes (derived from :class:`object`) and C extension > types. (:issue:`6101`.) > > -* The :meth:`readline` method of :class:`StringIO` objects now does > - nothing when a negative length is requested, as other file-like > - objects do. (:issue:`7348`). > - > +* When a restricted set of attributes were set using ``__slots__``, > + deleting an unset attribute would not raise :exc:`AttributeError` > + as you would expect. Fixed by Benjamin Peterson; :issue:`7604`.) I doubt you meant to add this twice. Cheers, Nick. -- Nick Coghlan | ncoghlan at gmail.com | Brisbane, Australia --------------------------------------------------------------- From python-checkins at python.org Sat May 1 10:01:56 2010 From: python-checkins at python.org (senthil.kumaran) Date: Sat, 1 May 2010 10:01:56 +0200 (CEST) Subject: [Python-checkins] r80675 - in python/trunk/Lib: test/test_urllibnet.py urllib.py Message-ID: <20100501080156.623F4EEA5F@mail.python.org> Author: senthil.kumaran Date: Sat May 1 10:01:56 2010 New Revision: 80675 Log: Fix issue8582: urllib.urlretrieve fails with ValueError: Invalid format string Modified: python/trunk/Lib/test/test_urllibnet.py python/trunk/Lib/urllib.py Modified: python/trunk/Lib/test/test_urllibnet.py ============================================================================== --- python/trunk/Lib/test/test_urllibnet.py (original) +++ python/trunk/Lib/test/test_urllibnet.py Sat May 1 10:01:56 2010 @@ -7,6 +7,8 @@ import urllib import sys import os +import time + mimetools = test_support.import_module("mimetools", deprecated=True) @@ -178,6 +180,17 @@ self.assertIsInstance(header, mimetools.Message, "header is not an instance of mimetools.Message") + def test_data_header(self): + logo = "http://www.python.org/community/logos/python-logo-master-v3-TM.png" + file_location, fileheaders = self.urlretrieve(logo) + os.unlink(file_location) + datevalue = fileheaders.getheader('Date') + dateformat = '%a, %d %b %Y %H:%M:%S GMT' + try: + time.strptime(datevalue, dateformat) + except ValueError: + self.fail('Date value not in %r format', dateformat) + def test_main(): Modified: python/trunk/Lib/urllib.py ============================================================================== --- python/trunk/Lib/urllib.py (original) +++ python/trunk/Lib/urllib.py Sat May 1 10:01:56 2010 @@ -588,7 +588,7 @@ else: encoding = '' msg = [] - msg.append('Date: %s'%time.strftime('%a, %d %b %Y %T GMT', + msg.append('Date: %s'%time.strftime('%a, %d %b %Y %H:%M:%S GMT', time.gmtime(time.time()))) msg.append('Content-type: %s' % type) if encoding == 'base64': From python-checkins at python.org Sat May 1 10:06:38 2010 From: python-checkins at python.org (senthil.kumaran) Date: Sat, 1 May 2010 10:06:38 +0200 (CEST) Subject: [Python-checkins] r80676 - in python/branches/release26-maint: Lib/test/test_urllibnet.py Lib/urllib.py Message-ID: <20100501080638.A6B1BEEA11@mail.python.org> Author: senthil.kumaran Date: Sat May 1 10:06:38 2010 New Revision: 80676 Log: Merged revisions 80675 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r80675 | senthil.kumaran | 2010-05-01 13:31:56 +0530 (Sat, 01 May 2010) | 3 lines Fix issue8582: urllib.urlretrieve fails with ValueError: Invalid format string ........ Modified: python/branches/release26-maint/ (props changed) python/branches/release26-maint/Lib/test/test_urllibnet.py python/branches/release26-maint/Lib/urllib.py Modified: python/branches/release26-maint/Lib/test/test_urllibnet.py ============================================================================== --- python/branches/release26-maint/Lib/test/test_urllibnet.py (original) +++ python/branches/release26-maint/Lib/test/test_urllibnet.py Sat May 1 10:06:38 2010 @@ -8,6 +8,7 @@ import sys import os import mimetools +import time def _open_with_retry(func, host, *args, **kwargs): @@ -178,6 +179,16 @@ self.assert_(isinstance(header, mimetools.Message), "header is not an instance of mimetools.Message") + def test_data_header(self): + logo = "http://www.python.org/community/logos/python-logo-master-v3-TM.png" + file_location, fileheaders = self.urlretrieve(logo) + os.unlink(file_location) + datevalue = fileheaders.getheader('Date') + dateformat = '%a, %d %b %Y %H:%M:%S GMT' + try: + time.strptime(datevalue, dateformat) + except ValueError: + self.fail('Date value not in %r format', dateformat) def test_main(): Modified: python/branches/release26-maint/Lib/urllib.py ============================================================================== --- python/branches/release26-maint/Lib/urllib.py (original) +++ python/branches/release26-maint/Lib/urllib.py Sat May 1 10:06:38 2010 @@ -592,7 +592,7 @@ else: encoding = '' msg = [] - msg.append('Date: %s'%time.strftime('%a, %d %b %Y %T GMT', + msg.append('Date: %s'%time.strftime('%a, %d %b %Y %H:%M:%S GMT', time.gmtime(time.time()))) msg.append('Content-type: %s' % type) if encoding == 'base64': From python-checkins at python.org Sat May 1 10:29:18 2010 From: python-checkins at python.org (senthil.kumaran) Date: Sat, 1 May 2010 10:29:18 +0200 (CEST) Subject: [Python-checkins] r80677 - in python/branches/py3k: Lib/test/test_urllibnet.py Lib/urllib/request.py Message-ID: <20100501082918.9BC8AEE993@mail.python.org> Author: senthil.kumaran Date: Sat May 1 10:29:18 2010 New Revision: 80677 Log: Merged revisions 80675 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r80675 | senthil.kumaran | 2010-05-01 13:31:56 +0530 (Sat, 01 May 2010) | 3 lines Fix issue8582: urllib.urlretrieve fails with ValueError: Invalid format string ........ Modified: python/branches/py3k/ (props changed) python/branches/py3k/Lib/test/test_urllibnet.py python/branches/py3k/Lib/urllib/request.py Modified: python/branches/py3k/Lib/test/test_urllibnet.py ============================================================================== --- python/branches/py3k/Lib/test/test_urllibnet.py (original) +++ python/branches/py3k/Lib/test/test_urllibnet.py Sat May 1 10:29:18 2010 @@ -8,6 +8,7 @@ import sys import os import email.message +import time def _open_with_retry(func, host, *args, **kwargs): @@ -180,6 +181,16 @@ self.assertIsInstance(header, email.message.Message, "header is not an instance of email.message.Message") + def test_data_header(self): + logo = "http://www.python.org/community/logos/python-logo-master-v3-TM.png" + file_location, fileheaders = self.urlretrieve(logo) + os.unlink(file_location) + datevalue = fileheaders.get('Date') + dateformat = '%a, %d %b %Y %H:%M:%S GMT' + try: + time.strptime(datevalue, dateformat) + except ValueError: + self.fail('Date value not in %r format', dateformat) def test_main(): Modified: python/branches/py3k/Lib/urllib/request.py ============================================================================== --- python/branches/py3k/Lib/urllib/request.py (original) +++ python/branches/py3k/Lib/urllib/request.py Sat May 1 10:29:18 2010 @@ -1779,7 +1779,7 @@ else: encoding = '' msg = [] - msg.append('Date: %s'%time.strftime('%a, %d %b %Y %T GMT', + msg.append('Date: %s'%time.strftime('%a, %d %b %Y %H:%M:%S GMT', time.gmtime(time.time()))) msg.append('Content-type: %s' % type) if encoding == 'base64': From python-checkins at python.org Sat May 1 10:32:23 2010 From: python-checkins at python.org (senthil.kumaran) Date: Sat, 1 May 2010 10:32:23 +0200 (CEST) Subject: [Python-checkins] r80678 - in python/branches/release31-maint: Lib/test/test_urllibnet.py Lib/urllib/request.py Message-ID: <20100501083223.E0646EE993@mail.python.org> Author: senthil.kumaran Date: Sat May 1 10:32:23 2010 New Revision: 80678 Log: Merged revisions 80677 via svnmerge from svn+ssh://pythondev at svn.python.org/python/branches/py3k ................ r80677 | senthil.kumaran | 2010-05-01 13:59:18 +0530 (Sat, 01 May 2010) | 9 lines Merged revisions 80675 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r80675 | senthil.kumaran | 2010-05-01 13:31:56 +0530 (Sat, 01 May 2010) | 3 lines Fix issue8582: urllib.urlretrieve fails with ValueError: Invalid format string ........ ................ Modified: python/branches/release31-maint/ (props changed) python/branches/release31-maint/Lib/test/test_urllibnet.py python/branches/release31-maint/Lib/urllib/request.py Modified: python/branches/release31-maint/Lib/test/test_urllibnet.py ============================================================================== --- python/branches/release31-maint/Lib/test/test_urllibnet.py (original) +++ python/branches/release31-maint/Lib/test/test_urllibnet.py Sat May 1 10:32:23 2010 @@ -8,6 +8,7 @@ import sys import os import email.message +import time def _open_with_retry(func, host, *args, **kwargs): @@ -180,6 +181,16 @@ self.assertTrue(isinstance(header, email.message.Message), "header is not an instance of email.message.Message") + def test_data_header(self): + logo = "http://www.python.org/community/logos/python-logo-master-v3-TM.png" + file_location, fileheaders = self.urlretrieve(logo) + os.unlink(file_location) + datevalue = fileheaders.get('Date') + dateformat = '%a, %d %b %Y %H:%M:%S GMT' + try: + time.strptime(datevalue, dateformat) + except ValueError: + self.fail('Date value not in %r format', dateformat) def test_main(): Modified: python/branches/release31-maint/Lib/urllib/request.py ============================================================================== --- python/branches/release31-maint/Lib/urllib/request.py (original) +++ python/branches/release31-maint/Lib/urllib/request.py Sat May 1 10:32:23 2010 @@ -1781,7 +1781,7 @@ else: encoding = '' msg = [] - msg.append('Date: %s'%time.strftime('%a, %d %b %Y %T GMT', + msg.append('Date: %s'%time.strftime('%a, %d %b %Y %H:%M:%S GMT', time.gmtime(time.time()))) msg.append('Content-type: %s' % type) if encoding == 'base64': From python-checkins at python.org Sat May 1 11:40:48 2010 From: python-checkins at python.org (georg.brandl) Date: Sat, 1 May 2010 11:40:48 +0200 (CEST) Subject: [Python-checkins] r80679 - peps/trunk/pep-3148.txt Message-ID: <20100501094048.2B5BBEEB0A@mail.python.org> Author: georg.brandl Date: Sat May 1 11:40:47 2010 New Revision: 80679 Log: Apply updates sent to PEPs list by Brian Quinlan. Modified: peps/trunk/pep-3148.txt Modified: peps/trunk/pep-3148.txt ============================================================================== --- peps/trunk/pep-3148.txt (original) +++ peps/trunk/pep-3148.txt Sat May 1 11:40:47 2010 @@ -149,6 +149,9 @@ passed to `ProcessPoolExecutor.submit` must be serializeable according to the same limitations as the multiprocessing module. +Calling `Executor` or `Future` methods from within a callable submitted to a +`ProcessPoolExecutor` will result in deadlock. + `__init__(max_workers)` Executes calls asynchronously using a pool of a most *max_workers* @@ -215,11 +218,11 @@ Return `True` if the call was successfully cancelled. -`Future.running()` +`running()` Return `True` if the call is currently being executed and cannot be cancelled. -`Future.done()` +`done()` Return `True` if the call was successfully cancelled or finished running. @@ -248,6 +251,25 @@ If the call completed without raising then ``None`` is returned. +`add_done_callback(fn)` + +Attaches a function *fn* to the future that will be called when the future is +cancelled or finishes running. *fn* will be called with the future as its only +argument. + +If the future has already completed or been cancelled then *fn* will be called +immediately. If the same function is added several times then it will still only +be called once. + +NOTE: This method can be used to create adapters from Futures to Twisted +Deferreds. + +`remove_done_callback(fn)` + +Removes the function *fn*, which was previously attached to the future using +`add_done_callback`. `KeyError` is raised if the function was not previously +attached. + Internal Future Methods ^^^^^^^^^^^^^^^^^^^^^^^ @@ -284,14 +306,10 @@ `wait(fs, timeout=None, return_when=ALL_COMPLETED)` -Wait for the `Future` instances in the given sequence to complete. Returns a -named 2-tuple of sets. The first set, named "finished", contains the futures -that completed (finished or were cancelled) before the wait completed. The -second set, named "not_finished", contains uncompleted futures. - -This method should always be called using keyword arguments, which are: - -*fs* is the sequence of Future instances that should be waited on. +Wait for the `Future` instances given by *fs* to complete. Returns a named +2-tuple of sets. The first set, named "finished", contains the futures that +completed (finished or were cancelled) before the wait completed. The second +set, named "not_finished", contains uncompleted futures. *timeout* can be used to control the maximum number of seconds to wait before returning. If timeout is not specified or None then there is no limit to the @@ -313,11 +331,11 @@ `as_completed(fs, timeout=None)` -Returns an iterator over the Future instances given by *fs* that yields futures -as they complete (finished or were cancelled). Any futures that completed -before `as_completed()` was called will be yielded first. The returned iterator -raises a `TimeoutError` if `__next__()` is called and the result isn't available -after *timeout* seconds from the original call to `as_completed()`. If +Returns an iterator over the `Future` instances given by *fs* that yields +futures as they complete (finished or were cancelled). Any futures that +completed before `as_completed()` was called will be yielded first. The returned +iterator raises a `TimeoutError` if `__next__()` is called and the result isn't +available after *timeout* seconds from the original call to `as_completed()`. If *timeout* is not specified or `None` then there is no limit to the wait time. ========= @@ -351,13 +369,14 @@ operation is eagerly evaluated asynchronously, and execution would only block if the proxy object were used before the operation completed. -Anh Hai Trinh proposed a simpler but more limited API concept [5]_. +Anh Hai Trinh proposed a simpler but more limited API concept [5]_ and the API +has been discussed in some detail on stdlib-sig [6]_. ======================== Reference Implementation ======================== -The reference implementation [6]_ contains a complete implementation of the +The reference implementation [7]_ contains a complete implementation of the proposed design. It has been tested on Linux and Mac OS X. ========== @@ -385,6 +404,10 @@ `http://www.mail-archive.com/stdlib-sig at python.org/msg00480.html` .. [6] + A discussion of the proposed API on stdlib-sig + `http://mail.python.org/pipermail/stdlib-sig/2009-November/000731.html` + +.. [7] Reference `futures` implementation `http://code.google.com/p/pythonfutures/source/browse/#svn/branches/feedback` From python-checkins at python.org Sat May 1 11:58:11 2010 From: python-checkins at python.org (georg.brandl) Date: Sat, 1 May 2010 11:58:11 +0200 (CEST) Subject: [Python-checkins] r80680 - peps/trunk/pep-3148.txt Message-ID: <20100501095811.9DF66EE993@mail.python.org> Author: georg.brandl Date: Sat May 1 11:58:11 2010 New Revision: 80680 Log: Rewrap according to PEP standards; indent documentation for API elements for better clarity. Modified: peps/trunk/pep-3148.txt Modified: peps/trunk/pep-3148.txt ============================================================================== --- peps/trunk/pep-3148.txt (original) +++ peps/trunk/pep-3148.txt Sat May 1 11:58:11 2010 @@ -14,20 +14,20 @@ Abstract ======== -This PEP proposes a design for a package that facilitates the evaluation of -callables using threads and processes. +This PEP proposes a design for a package that facilitates the +evaluation of callables using threads and processes. ========== Motivation ========== -Python currently has powerful primitives to construct multi-threaded and -multi-process applications but parallelizing simple operations requires a lot of -work i.e. explicitly launching processes/threads, constructing a work/results -queue, and waiting for completion or some other termination condition (e.g. -failure, timeout). It is also difficult to design an application with a global -process/thread limit when each component invents its own parallel execution -strategy. +Python currently has powerful primitives to construct multi-threaded +and multi-process applications but parallelizing simple operations +requires a lot of work i.e. explicitly launching processes/threads, +constructing a work/results queue, and waiting for completion or some +other termination condition (e.g. failure, timeout). It is also +difficult to design an application with a global process/thread limit +when each component invents its own parallel execution strategy. ============= Specification @@ -95,10 +95,10 @@ Interface --------- -The proposed package provides two core classes: `Executor` and `Future`. -An `Executor` receives asynchronous work requests (in terms of a callable and -its arguments) and returns a `Future` to represent the execution of that -work request. +The proposed package provides two core classes: `Executor` and +`Future`. An `Executor` receives asynchronous work requests (in terms +of a callable and its arguments) and returns a `Future` to represent +the execution of that work request. Executor '''''''' @@ -106,68 +106,70 @@ `Executor` is an abstract class that provides methods to execute calls asynchronously. -`submit(fn, *args, **kwargs)` +``submit(fn, *args, **kwargs)`` -Schedules the callable to be executed as fn(*\*args*, *\*\*kwargs*) and returns -a `Future` instance representing the execution of the function. + Schedules the callable to be executed as ``fn(*args, **kwargs)`` + and returns a `Future` instance representing the execution of the + function. + + This is an abstract method and must be implemented by Executor + subclasses. + +``map(func, *iterables, timeout=None)`` + + Equivalent to ``map(func, *iterables)`` but executed + asynchronously and possibly out-of-order. The returned iterator + raises a `TimeoutError` if `__next__()` is called and the result + isn't available after *timeout* seconds from the original call to + `map()`. If *timeout* is not specified or `None` then there is no + limit to the wait time. If a call raises an exception then that + exception will be raised when its value is retrieved from the + iterator. + +``shutdown(wait=True)`` + + Signal the executor that it should free any resources that it is + using when the currently pending futures are done executing. + Calls to `Executor.submit` and `Executor.map` and made after + shutdown will raise `RuntimeError`. + + If wait is `True` then the executor will not return until all the + pending futures are done executing and the resources associated + with the executor have been freed. -This is an abstract method and must be implemented by Executor subclasses. +| ``__enter__()`` +| ``__exit__(exc_type, exc_val, exc_tb)`` -`map(func, *iterables, timeout=None)` - -Equivalent to map(*func*, *\*iterables*) but executed asynchronously and -possibly out-of-order. The returned iterator raises a `TimeoutError` if -`__next__()` is called and the result isn't available after *timeout* seconds -from the original call to `map()`. If *timeout* is not specified or -``None`` then there is no limit to the wait time. If a call raises an exception -then that exception will be raised when its value is retrieved from the -iterator. - -`shutdown(wait=True)` - -Signal the executor that it should free any resources that it is using when -the currently pending futures are done executing. Calls to -`Executor.submit` and `Executor.map` and made after shutdown will raise -`RuntimeError`. - -If wait is `True` then the executor will not return until all the pending -futures are done executing and the resources associated with the executor -have been freed. - -`__enter__()` -`__exit__(exc_type, exc_val, exc_tb)` - -When using an executor as a context manager, `__exit__` will call -`Executor.shutdown(wait=True)`. + When using an executor as a context manager, `__exit__` will call + ``Executor.shutdown(wait=True)``. ProcessPoolExecutor ''''''''''''''''''' -The `ProcessPoolExecutor` class is an `Executor` subclass that uses a pool of -processes to execute calls asynchronously. The callable objects and arguments -passed to `ProcessPoolExecutor.submit` must be serializeable according to the -same limitations as the multiprocessing module. - -Calling `Executor` or `Future` methods from within a callable submitted to a -`ProcessPoolExecutor` will result in deadlock. - -`__init__(max_workers)` - -Executes calls asynchronously using a pool of a most *max_workers* -processes. If *max_workers* is ``None`` or not given then as many worker -processes will be created as the machine has processors. +The `ProcessPoolExecutor` class is an `Executor` subclass that uses a +pool of processes to execute calls asynchronously. The callable +objects and arguments passed to `ProcessPoolExecutor.submit` must be +serializeable according to the same limitations as the multiprocessing +module. + +Calling `Executor` or `Future` methods from within a callable +submitted to a `ProcessPoolExecutor` will result in deadlock. + +``__init__(max_workers)`` + + Executes calls asynchronously using a pool of a most *max_workers* + processes. If *max_workers* is ``None`` or not given then as many + worker processes will be created as the machine has processors. ThreadPoolExecutor '''''''''''''''''' -The `ThreadPoolExecutor` class is an `Executor` subclass that uses a pool of -threads to execute calls asynchronously. - -Deadlock can occur when the callable associated with a `Future` waits on -the results of another `Future`. For example: +The `ThreadPoolExecutor` class is an `Executor` subclass that uses a +pool of threads to execute calls asynchronously. -:: +Deadlock can occur when the callable associated with a `Future` waits +on the results of another `Future`. For example:: import time def wait_on_b(): @@ -185,9 +187,7 @@ a = executor.submit(wait_on_b) b = executor.submit(wait_on_a) -And: - -:: +And:: def wait_on_future(): f = executor.submit(pow, 5, 2) @@ -198,186 +198,200 @@ executor = ThreadPoolExecutor(max_workers=1) executor.submit(wait_on_future) -`__init__(max_workers)` +``__init__(max_workers)`` -Executes calls asynchronously using a pool of at most *max_workers* threads. + Executes calls asynchronously using a pool of at most + *max_workers* threads. Future Objects '''''''''''''' -The `Future` class encapsulates the asynchronous execution of a function -or method call. `Future` instances are returned by `Executor.submit`. - -`cancel()` - -Attempt to cancel the call. If the call is currently being executed then -it cannot be cancelled and the method will return `False`, otherwise the call -will be cancelled and the method will return `True`. - -`cancelled()` - -Return `True` if the call was successfully cancelled. - -`running()` - -Return `True` if the call is currently being executed and cannot be cancelled. - -`done()` - -Return `True` if the call was successfully cancelled or finished running. - -`result(timeout=None)` - -Return the value returned by the call. If the call hasn't yet completed then -this method will wait up to *timeout* seconds. If the call hasn't completed -in *timeout* seconds then a `TimeoutError` will be raised. If *timeout* -is not specified or ``None`` then there is no limit to the wait time. - -If the future is cancelled before completing then `CancelledError` will -be raised. - -If the call raised then this method will raise the same exception. - -`exception(timeout=None)` - -Return the exception raised by the call. If the call hasn't yet completed -then this method will wait up to *timeout* seconds. If the call hasn't -completed in *timeout* seconds then a `TimeoutError` will be raised. -If *timeout* is not specified or ``None`` then there is no limit to the wait -time. - -If the future is cancelled before completing then `CancelledError` will -be raised. - -If the call completed without raising then ``None`` is returned. - -`add_done_callback(fn)` - -Attaches a function *fn* to the future that will be called when the future is -cancelled or finishes running. *fn* will be called with the future as its only -argument. - -If the future has already completed or been cancelled then *fn* will be called -immediately. If the same function is added several times then it will still only -be called once. - -NOTE: This method can be used to create adapters from Futures to Twisted -Deferreds. - -`remove_done_callback(fn)` - -Removes the function *fn*, which was previously attached to the future using -`add_done_callback`. `KeyError` is raised if the function was not previously -attached. +The `Future` class encapsulates the asynchronous execution of a +function or method call. `Future` instances are returned by +`Executor.submit`. + +``cancel()`` + + Attempt to cancel the call. If the call is currently being + executed then it cannot be cancelled and the method will return + `False`, otherwise the call will be cancelled and the method will + return `True`. + +``cancelled()`` + + Return `True` if the call was successfully cancelled. + +``running()`` + + Return `True` if the call is currently being executed and cannot + be cancelled. + +``done()`` + + Return `True` if the call was successfully cancelled or finished + running. + +``result(timeout=None)`` + + Return the value returned by the call. If the call hasn't yet + completed then this method will wait up to *timeout* seconds. If + the call hasn't completed in *timeout* seconds then a + `TimeoutError` will be raised. If *timeout* is not specified or + `None` then there is no limit to the wait time. + + If the future is cancelled before completing then `CancelledError` + will be raised. + + If the call raised then this method will raise the same exception. + +``exception(timeout=None)`` + + Return the exception raised by the call. If the call hasn't yet + completed then this method will wait up to *timeout* seconds. If + the call hasn't completed in *timeout* seconds then a + `TimeoutError` will be raised. If *timeout* is not specified or + ``None`` then there is no limit to the wait time. + + If the future is cancelled before completing then `CancelledError` + will be raised. + + If the call completed without raising then `None` is returned. + +``add_done_callback(fn)`` + + Attaches a function *fn* to the future that will be called when + the future is cancelled or finishes running. *fn* will be called + with the future as its only argument. + + If the future has already completed or been cancelled then *fn* + will be called immediately. If the same function is added several + times then it will still only be called once. + + NOTE: This method can be used to create adapters from Futures to + Twisted Deferreds. + +``remove_done_callback(fn)`` + + Removes the function *fn*, which was previously attached to the + future using `add_done_callback`. `KeyError` is raised if the + function was not previously attached. Internal Future Methods ^^^^^^^^^^^^^^^^^^^^^^^ -The following `Future` methods are meant for use in unit tests and `Executor` -implementations. - -`set_running_or_notify_cancel()` - -Should be called by `Executor` implementations before executing the work -associated with the `Future`. - -If the method returns `False` then the `Future` was cancelled i.e. -`Future.cancel` was called and returned `True`. Any threads waiting on the -`Future` completing (i.e. through `as_completed()` or `wait()`) will be woken -up. +The following `Future` methods are meant for use in unit tests and +`Executor` implementations. -If the method returns `True` then the `Future` was not cancelled and has been -put in the running state i.e. calls to `Future.running()` will return `True`. +``set_running_or_notify_cancel()`` -This method can only be called once and cannot be called after -`Future.set_result()` or `Future.set_exception()` have been called. + Should be called by `Executor` implementations before executing + the work associated with the `Future`. + + If the method returns `False` then the `Future` was cancelled, + i.e. `Future.cancel` was called and returned `True`. Any threads + waiting on the `Future` completing (i.e. through `as_completed()` + or `wait()`) will be woken up. + + If the method returns `True` then the `Future` was not cancelled + and has been put in the running state, i.e. calls to + `Future.running()` will return `True`. + + This method can only be called once and cannot be called after + `Future.set_result()` or `Future.set_exception()` have been + called. -`set_result(result)` +``set_result(result)`` -Sets the result of the work associated with the `Future`. + Sets the result of the work associated with the `Future`. -`set_exception(exception)` +``set_exception(exception)`` -Sets the result of the work associated with the `Future` to the given -`Exception`. + Sets the result of the work associated with the `Future` to the + given `Exception`. Module Functions '''''''''''''''' -`wait(fs, timeout=None, return_when=ALL_COMPLETED)` +``wait(fs, timeout=None, return_when=ALL_COMPLETED)`` -Wait for the `Future` instances given by *fs* to complete. Returns a named -2-tuple of sets. The first set, named "finished", contains the futures that -completed (finished or were cancelled) before the wait completed. The second -set, named "not_finished", contains uncompleted futures. - -*timeout* can be used to control the maximum number of seconds to wait before -returning. If timeout is not specified or None then there is no limit to the -wait time. - -*return_when* indicates when the method should return. It must be one of the -following constants: - -============================= ================================================== - Constant Description -============================= ================================================== -`FIRST_COMPLETED` The method will return when any future finishes or - is cancelled. -`FIRST_EXCEPTION` The method will return when any future finishes by - raising an exception. If not future raises an - exception then it is equivalent to ALL_COMPLETED. -`ALL_COMPLETED` The method will return when all calls finish. -============================= ================================================== - -`as_completed(fs, timeout=None)` - -Returns an iterator over the `Future` instances given by *fs* that yields -futures as they complete (finished or were cancelled). Any futures that -completed before `as_completed()` was called will be yielded first. The returned -iterator raises a `TimeoutError` if `__next__()` is called and the result isn't -available after *timeout* seconds from the original call to `as_completed()`. If -*timeout* is not specified or `None` then there is no limit to the wait time. + Wait for the `Future` instances given by *fs* to complete. + Returns a named 2-tuple of sets. The first set, named "finished", + contains the futures that completed (finished or were cancelled) + before the wait completed. The second set, named "not_finished", + contains uncompleted futures. + + *timeout* can be used to control the maximum number of seconds to + wait before returning. If timeout is not specified or None then + there is no limit to the wait time. + + *return_when* indicates when the method should return. It must be + one of the following constants: + + ============================= ================================================== + Constant Description + ============================= ================================================== + `FIRST_COMPLETED` The method will return when any future finishes or + is cancelled. + `FIRST_EXCEPTION` The method will return when any future finishes by + raising an exception. If not future raises an + exception then it is equivalent to ALL_COMPLETED. + `ALL_COMPLETED` The method will return when all calls finish. + ============================= ================================================== + +``as_completed(fs, timeout=None)`` + + Returns an iterator over the `Future` instances given by *fs* that + yields futures as they complete (finished or were cancelled). Any + futures that completed before `as_completed()` was called will be + yielded first. The returned iterator raises a `TimeoutError` if + `__next__()` is called and the result isn't available after + *timeout* seconds from the original call to `as_completed()`. If + *timeout* is not specified or `None` then there is no limit to the + wait time. ========= Rationale ========= -The proposed design of this module was heavily influenced by the the Java -java.util.concurrent package [1]_. The conceptual basis of the module, as in -Java, is the Future class, which represents the progress and result of an -asynchronous computation. The Future class makes little commitment to the -evaluation mode being used e.g. it can be be used to represent lazy or eager -evaluation, for evaluation using threads, processes or remote procedure call. +The proposed design of this module was heavily influenced by the the +Java java.util.concurrent package [1]_. The conceptual basis of the +module, as in Java, is the Future class, which represents the progress +and result of an asynchronous computation. The Future class makes +little commitment to the evaluation mode being used e.g. it can be be +used to represent lazy or eager evaluation, for evaluation using +threads, processes or remote procedure call. Futures are created by concrete implementations of the Executor class -(called ExecutorService in Java). The reference implementation provides -classes that use either a process a thread pool to eagerly evaluate -computations. +(called ExecutorService in Java). The reference implementation +provides classes that use either a process a thread pool to eagerly +evaluate computations. Futures have already been seen in Python as part of a popular Python -cookbook recipe [2]_ and have discussed on the Python-3000 mailing list [3]_. +cookbook recipe [2]_ and have discussed on the Python-3000 mailing +list [3]_. -The proposed design is explicit i.e. it requires that clients be aware that -they are consuming Futures. It would be possible to design a module that -would return proxy objects (in the style of `weakref`) that could be used -transparently. It is possible to build a proxy implementation on top of -the proposed explicit mechanism. - -The proposed design does not introduce any changes to Python language syntax -or semantics. Special syntax could be introduced [4]_ to mark function and -method calls as asynchronous. A proxy result would be returned while the -operation is eagerly evaluated asynchronously, and execution would only -block if the proxy object were used before the operation completed. +The proposed design is explicit, i.e. it requires that clients be +aware that they are consuming Futures. It would be possible to design +a module that would return proxy objects (in the style of `weakref`) +that could be used transparently. It is possible to build a proxy +implementation on top of the proposed explicit mechanism. + +The proposed design does not introduce any changes to Python language +syntax or semantics. Special syntax could be introduced [4]_ to mark +function and method calls as asynchronous. A proxy result would be +returned while the operation is eagerly evaluated asynchronously, and +execution would only block if the proxy object were used before the +operation completed. -Anh Hai Trinh proposed a simpler but more limited API concept [5]_ and the API -has been discussed in some detail on stdlib-sig [6]_. +Anh Hai Trinh proposed a simpler but more limited API concept [5]_ and +the API has been discussed in some detail on stdlib-sig [6]_. ======================== Reference Implementation ======================== -The reference implementation [7]_ contains a complete implementation of the -proposed design. It has been tested on Linux and Mac OS X. +The reference implementation [7]_ contains a complete implementation +of the proposed design. It has been tested on Linux and Mac OS X. ========== References From nnorwitz at gmail.com Sat May 1 12:57:06 2010 From: nnorwitz at gmail.com (Neal Norwitz) Date: Sat, 1 May 2010 06:57:06 -0400 Subject: [Python-checkins] Python Regression Test Failures refleak (1) Message-ID: <20100501105706.GA25895@kbk-i386-bb.psfb.org> More important issues: ---------------------- test_ctypes leaked [0, 0, 83] references, sum=83 Less important issues: ---------------------- From python-checkins at python.org Sat May 1 13:46:20 2010 From: python-checkins at python.org (mark.dickinson) Date: Sat, 1 May 2010 13:46:20 +0200 (CEST) Subject: [Python-checkins] r80681 - python/trunk/Lib/test/test_decimal.py Message-ID: <20100501114620.866C0EEAFE@mail.python.org> Author: mark.dickinson Date: Sat May 1 13:46:20 2010 New Revision: 80681 Log: Fix incorrect use of a list as the target of an 'except' clause in test_decimal.py. Modified: python/trunk/Lib/test/test_decimal.py Modified: python/trunk/Lib/test/test_decimal.py ============================================================================== --- python/trunk/Lib/test/test_decimal.py (original) +++ python/trunk/Lib/test/test_decimal.py Sat May 1 13:46:20 2010 @@ -40,7 +40,7 @@ threading = None # Useful Test Constant -Signals = getcontext().flags.keys() +Signals = tuple(getcontext().flags.keys()) # Tests are built around these assumed context defaults. # test_main() restores the original context. From python-checkins at python.org Sat May 1 13:56:48 2010 From: python-checkins at python.org (mark.dickinson) Date: Sat, 1 May 2010 13:56:48 +0200 (CEST) Subject: [Python-checkins] r80682 - in python/branches/release26-maint: Lib/test/test_decimal.py Message-ID: <20100501115648.2CFD8EE995@mail.python.org> Author: mark.dickinson Date: Sat May 1 13:56:48 2010 New Revision: 80682 Log: Merged revisions 80681 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r80681 | mark.dickinson | 2010-05-01 12:46:20 +0100 (Sat, 01 May 2010) | 2 lines Fix incorrect use of a list as the target of an 'except' clause in test_decimal.py. ........ Modified: python/branches/release26-maint/ (props changed) python/branches/release26-maint/Lib/test/test_decimal.py Modified: python/branches/release26-maint/Lib/test/test_decimal.py ============================================================================== --- python/branches/release26-maint/Lib/test/test_decimal.py (original) +++ python/branches/release26-maint/Lib/test/test_decimal.py Sat May 1 13:56:48 2010 @@ -40,7 +40,7 @@ threading = None # Useful Test Constant -Signals = getcontext().flags.keys() +Signals = tuple(getcontext().flags.keys()) # Tests are built around these assumed context defaults. # test_main() restores the original context. From python-checkins at python.org Sat May 1 13:59:03 2010 From: python-checkins at python.org (mark.dickinson) Date: Sat, 1 May 2010 13:59:03 +0200 (CEST) Subject: [Python-checkins] r80683 - python/branches/py3k Message-ID: <20100501115903.CDF05EE9FF@mail.python.org> Author: mark.dickinson Date: Sat May 1 13:59:03 2010 New Revision: 80683 Log: Recorded merge of revisions 80681 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r80681 | mark.dickinson | 2010-05-01 12:46:20 +0100 (Sat, 01 May 2010) | 2 lines Fix incorrect use of a list as the target of an 'except' clause in test_decimal.py. ........ Modified: python/branches/py3k/ (props changed) From amk at amk.ca Sat May 1 14:02:31 2010 From: amk at amk.ca (A.M. Kuchling) Date: Sat, 1 May 2010 08:02:31 -0400 Subject: [Python-checkins] r80674 - python/trunk/Doc/whatsnew/2.7.rst In-Reply-To: <4BDBA876.8040806@gmail.com> References: <20100501011916.9842CEE9AD@mail.python.org> <4BDBA876.8040806@gmail.com> Message-ID: <20100501120231.GA36665@andrew-kuchlings-macbook.local> On Sat, May 01, 2010 at 02:05:10PM +1000, Nick Coghlan wrote: > I doubt you meant to add this twice. No, I actually did; the second copy is in the 'Porting to Python 2.7' section that lists changes in behaviour that might break code. --amk From python-checkins at python.org Sat May 1 14:05:52 2010 From: python-checkins at python.org (andrew.kuchling) Date: Sat, 1 May 2010 14:05:52 +0200 (CEST) Subject: [Python-checkins] r80684 - python/trunk/Doc/library/stdtypes.rst Message-ID: <20100501120552.88EBFEEAE3@mail.python.org> Author: andrew.kuchling Date: Sat May 1 14:05:52 2010 New Revision: 80684 Log: Minor grammar fix Modified: python/trunk/Doc/library/stdtypes.rst Modified: python/trunk/Doc/library/stdtypes.rst ============================================================================== --- python/trunk/Doc/library/stdtypes.rst (original) +++ python/trunk/Doc/library/stdtypes.rst Sat May 1 14:05:52 2010 @@ -2590,7 +2590,7 @@ File "", line 1, in ValueError: cannot modify size of memoryview object - Notice how the size of the memoryview object can not be changed. + Notice how the size of the memoryview object cannot be changed. :class:`memoryview` has two methods: From python-checkins at python.org Sat May 1 14:06:51 2010 From: python-checkins at python.org (andrew.kuchling) Date: Sat, 1 May 2010 14:06:51 +0200 (CEST) Subject: [Python-checkins] r80685 - python/trunk/Doc/whatsnew/2.7.rst Message-ID: <20100501120651.E5646EEB52@mail.python.org> Author: andrew.kuchling Date: Sat May 1 14:06:51 2010 New Revision: 80685 Log: Describe memoryview Modified: python/trunk/Doc/whatsnew/2.7.rst Modified: python/trunk/Doc/whatsnew/2.7.rst ============================================================================== --- python/trunk/Doc/whatsnew/2.7.rst (original) +++ python/trunk/Doc/whatsnew/2.7.rst Sat May 1 14:06:51 2010 @@ -8,7 +8,7 @@ .. Fix accents on Kristjan Valur Jonsson, Fuerstenau -.. Big jobs: ElementTree 1.3, pep 391, sysconfig, memoryview +.. Big jobs: ElementTree 1.3, pep 391, sysconfig .. unittest test discovery .. hyperlink all the methods & functions. @@ -435,6 +435,58 @@ Backported to 2.7 by Alexandre Vassalotti; :issue:`1967`. +PEP 3137: The memoryview Object +==================================================== + +The :class:`memoryview` object provides a view of another object's +memory content that matches the :class:`bytes` type's interface. + + >>> import string + >>> m = memoryview(string.letters) + >>> m + + >>> len(m) # Returns length of underlying object + 52 + >>> m[0], m[25], m[26] # Indexing returns one byte + ('a', 'z', 'A') + >>> m2 = m[0:26] # Slicing returns another memoryview + >>> m2 + + +The content of the view can be converted to a string of bytes or to +a list of integers: + + >>> m2.tobytes() + 'abcdefghijklmnopqrstuvwxyz' + >>> m2.tolist() + [97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122] + >>> + +:class:`memoryview` objects allow modifying the underlying object if +it's a mutable object. + + >>> m2[0] = 75 + Traceback (most recent call last): + File "", line 1, in + TypeError: cannot modify read-only memory + >>> b = bytearray(string.letters) # Creating a mutable object + >>> b + bytearray(b'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ') + >>> mb = memoryview(b) + >>> mb[0] = '*' # Assign to view, changing the bytearray. + >>> b[0:5] # The bytearray has been changed. + bytearray(b'*bcde') + >>> + +.. seealso:: + + :pep:`3137` - Immutable Bytes and Mutable Buffer + PEP written by Guido van Rossum. + Implemented by Travis Oliphant. + Backported to 2.7 by Antoine Pitrou; :issue:`2396`. + + + Other Language Changes ====================== From python-checkins at python.org Sat May 1 14:16:40 2010 From: python-checkins at python.org (antoine.pitrou) Date: Sat, 1 May 2010 14:16:40 +0200 (CEST) Subject: [Python-checkins] r80686 - python/trunk/Doc/whatsnew/2.7.rst Message-ID: <20100501121640.053EFEE9FF@mail.python.org> Author: antoine.pitrou Date: Sat May 1 14:16:39 2010 New Revision: 80686 Log: Fix attribution. Travis didn't do much and he did a bad work. (yes, this is a sensitive subject, sorry) Modified: python/trunk/Doc/whatsnew/2.7.rst Modified: python/trunk/Doc/whatsnew/2.7.rst ============================================================================== --- python/trunk/Doc/whatsnew/2.7.rst (original) +++ python/trunk/Doc/whatsnew/2.7.rst Sat May 1 14:16:39 2010 @@ -482,7 +482,7 @@ :pep:`3137` - Immutable Bytes and Mutable Buffer PEP written by Guido van Rossum. - Implemented by Travis Oliphant. + Implemented by Travis Oliphant, Antoine Pitrou and others. Backported to 2.7 by Antoine Pitrou; :issue:`2396`. From python-checkins at python.org Sat May 1 17:16:58 2010 From: python-checkins at python.org (jean-paul.calderone) Date: Sat, 1 May 2010 17:16:58 +0200 (CEST) Subject: [Python-checkins] r80687 - in python/branches/signalfd-issue8407: Doc/library/signal.rst Misc/NEWS Modules/signalmodule.c configure configure.in pyconfig.h.in Message-ID: <20100501151658.590FBEEB64@mail.python.org> Author: jean-paul.calderone Date: Sat May 1 17:16:57 2010 New Revision: 80687 Log: Document, add necessary build stuff, expose (but not yet test) SFD_* Modified: python/branches/signalfd-issue8407/Doc/library/signal.rst python/branches/signalfd-issue8407/Misc/NEWS python/branches/signalfd-issue8407/Modules/signalmodule.c python/branches/signalfd-issue8407/configure python/branches/signalfd-issue8407/configure.in python/branches/signalfd-issue8407/pyconfig.h.in Modified: python/branches/signalfd-issue8407/Doc/library/signal.rst ============================================================================== --- python/branches/signalfd-issue8407/Doc/library/signal.rst (original) +++ python/branches/signalfd-issue8407/Doc/library/signal.rst Sat May 1 17:16:57 2010 @@ -14,9 +14,6 @@ underlying implementation), with the exception of the handler for :const:`SIGCHLD`, which follows the underlying implementation. -* There is no way to "block" signals temporarily from critical sections (since - this is not supported by all Unix flavors). - * Although Python signal handlers are called asynchronously as far as the Python user is concerned, they can only occur between the "atomic" instructions of the Python interpreter. This means that signals arriving during long calculations @@ -113,6 +110,35 @@ in user and kernel space. SIGPROF is delivered upon expiration. +.. data:: SIG_BLOCK + + A possible value for the *how* parameter to :func:`sigprocmask` + indicating that signals are to be blocked. + + +.. data:: SIG_UNBLOCK + + A possible value for the *how* parameter to :func:`sigprocmask` + indicating that signals are to be unblocked. + + +.. data:: SIG_SETMASK + + A possible value for the *how* parameter to :func:`sigprocmask` + indicating that the signal mask is to be replaced. + + +.. data:: SFD_CLOEXEC + + A possible flag in the *flags* parameter to :func:`signalfd` which causes + the new file descriptor to be marked as close-on-exec. + +.. data:: SFD_NONBLOCK + + A possible flag in the *flags* parameter to :func:`signalfd` which causes + the new file description to be set non-blocking. + + The :mod:`signal` module defines one exception: .. exception:: ItimerError @@ -231,6 +257,46 @@ attribute descriptions in the :mod:`inspect` module). +.. function:: signalfd(fd, mask[, flags]) + + Create a new file descriptor on which to receive signals or modify the + mask of such a file descriptor previously created by this function. + Availability: Linux (See the manpage :manpage:`signalfd(2)` for further + information). + + If *fd* is ``-1``, a new file descriptor will be created. Otherwise, + *fd* must be a file descriptor previously returned by this function. + + *mask* is a list of signal numbers which will trigger data on this file + descriptor. + + *flags* is a bitvector which may include any :const:`signal.SFD_*` flag. + + .. versionadded:: X.Y + + +.. function:: sigprocmask(how, mask) + + Set the signal mask for the process. The old signal mask is returned. + Availability: Unix (See the Unix man page :manpage:`sigprocmask(2)`.) + + If *how* is :const:`signal.SIG_BLOCK`, the signals in the mask are added + to the set of blocked signals. + + If *how* is :const:`signal.SIG_UNBLOCK`, the signals in the mask are + removed from the set of blocked signals. + + If *how* is :const:`signal.SIG_SETMASK`, the signals in the mask are set + as blocked and the signals not in the mask are set as unblocked. + + *mask* is a list of signal numbers (eg :const:`signal.SIGUSR1`). + + The behavior of this function in a multi-threaded program is unspecified. + See :func:`thread.sigmask` for multi-threaded uses. XXX + + .. versionadded:: X.Y + + .. _signal-example: Example Modified: python/branches/signalfd-issue8407/Misc/NEWS ============================================================================== --- python/branches/signalfd-issue8407/Misc/NEWS (original) +++ python/branches/signalfd-issue8407/Misc/NEWS Sat May 1 17:16:57 2010 @@ -1286,6 +1286,11 @@ Library ------- +- Issue #8407: The signal module gains the ``signalfd()`` and + ``sigprocmask(2)`` functions providing access to the signalfd(2) and + sigprocmask(2) system calls respectively on Linux systems which implement + them. + - Add count() and reverse() methods to collections.deque(). - Fix variations of extending deques: d.extend(d) d.extendleft(d) d+=d Modified: python/branches/signalfd-issue8407/Modules/signalmodule.c ============================================================================== --- python/branches/signalfd-issue8407/Modules/signalmodule.c (original) +++ python/branches/signalfd-issue8407/Modules/signalmodule.c Sat May 1 17:16:57 2010 @@ -946,6 +946,18 @@ Py_DECREF(x); #endif +#ifdef SFD_CLOEXEC + x = PyLong_FromLong(SFD_CLOEXEC); + PyDict_SetItemString(d, "SFD_CLOEXEC", x); + Py_DECREF(x); +#endif + +#ifdef SFD_NONBLOCK + x = PyLong_FromLong(SFD_NONBLOCK); + PyDict_SetItemString(d, "SFD_NONBLOCK", x); + Py_DECREF(x); +#endif + #ifdef CTRL_C_EVENT x = PyInt_FromLong(CTRL_C_EVENT); PyDict_SetItemString(d, "CTRL_C_EVENT", x); Modified: python/branches/signalfd-issue8407/configure ============================================================================== --- python/branches/signalfd-issue8407/configure (original) +++ python/branches/signalfd-issue8407/configure Sat May 1 17:16:57 2010 @@ -18290,7 +18290,7 @@ setlocale setregid setreuid setsid setpgid setpgrp setuid setvbuf snprintf \ setlocale setregid setreuid setresuid setresgid \ setsid setpgid setpgrp setuid setvbuf snprintf \ - sigaction siginterrupt sigrelse strftime \ + sigaction siginterrupt signalfd sigprocmask sigrelse strftime \ sysconf tcgetpgrp tcsetpgrp tempnam timegm times tmpfile tmpnam tmpnam_r \ truncate uname unsetenv utimes waitpid wait3 wait4 wcscoll _getpty do Modified: python/branches/signalfd-issue8407/configure.in ============================================================================== --- python/branches/signalfd-issue8407/configure.in (original) +++ python/branches/signalfd-issue8407/configure.in Sat May 1 17:16:57 2010 @@ -2662,7 +2662,7 @@ setlocale setregid setreuid setsid setpgid setpgrp setuid setvbuf snprintf \ setlocale setregid setreuid setresuid setresgid \ setsid setpgid setpgrp setuid setvbuf snprintf \ - sigaction siginterrupt sigrelse strftime \ + sigaction siginterrupt signalfd sigprocmask sigrelse strftime \ sysconf tcgetpgrp tcsetpgrp tempnam timegm times tmpfile tmpnam tmpnam_r \ truncate uname unsetenv utimes waitpid wait3 wait4 wcscoll _getpty) Modified: python/branches/signalfd-issue8407/pyconfig.h.in ============================================================================== --- python/branches/signalfd-issue8407/pyconfig.h.in (original) +++ python/branches/signalfd-issue8407/pyconfig.h.in Sat May 1 17:16:57 2010 @@ -619,6 +619,12 @@ /* Define to 1 if you have the header file. */ #undef HAVE_SIGNAL_H +/* Define to 1 if you have the `signalfd' function. */ +#undef HAVE_SIGNALFD + +/* Define to 1 if you have the `sigprocmask' function. */ +#undef HAVE_SIGPROCMASK + /* Define to 1 if you have the `sigrelse' function. */ #undef HAVE_SIGRELSE From python-checkins at python.org Sat May 1 20:04:27 2010 From: python-checkins at python.org (giampaolo.rodola) Date: Sat, 1 May 2010 20:04:27 +0200 (CEST) Subject: [Python-checkins] r80688 - python/branches/py3k/Misc/maintainers.rst Message-ID: <20100501180427.9569CC8B8@mail.python.org> Author: giampaolo.rodola Date: Sat May 1 20:04:27 2010 New Revision: 80688 Log: add myself to Misc/maintainers.rst for asyncore, asynchat and ssl modules and networking interest area Modified: python/branches/py3k/Misc/maintainers.rst Modified: python/branches/py3k/Misc/maintainers.rst ============================================================================== --- python/branches/py3k/Misc/maintainers.rst (original) +++ python/branches/py3k/Misc/maintainers.rst Sat May 1 20:04:27 2010 @@ -48,8 +48,8 @@ argparse bethard array ast -asynchat josiahcarlson -asyncore josiahcarlson +asynchat josiahcarlson, giampaolo.rodola +asyncore josiahcarlson, giampaolo.rodola atexit audioop base64 @@ -187,7 +187,7 @@ socketserver spwd sqlite3 ghaering -ssl janssen, pitrou +ssl janssen, pitrou, giampaolo.rodola stat string stringprep @@ -280,7 +280,7 @@ locale lemburg, loewis mathematics mark.dickinson, eric.smith, lemburg memory management tim_one, lemburg -networking +networking giampaolo.rodola packaging tarek, lemburg py3 transition benjamin.peterson release management tarek, lemburg, benjamin.peterson, barry, loewis, From python-checkins at python.org Sat May 1 20:07:41 2010 From: python-checkins at python.org (giampaolo.rodola) Date: Sat, 1 May 2010 20:07:41 +0200 (CEST) Subject: [Python-checkins] r80689 - in python/branches/release31-maint: Misc/maintainers.rst Message-ID: <20100501180741.EB293E6AC@mail.python.org> Author: giampaolo.rodola Date: Sat May 1 20:07:41 2010 New Revision: 80689 Log: Merged revisions 80688 via svnmerge from svn+ssh://pythondev at svn.python.org/python/branches/py3k ........ r80688 | giampaolo.rodola | 2010-05-01 20:04:27 +0200 (sab, 01 mag 2010) | 1 line add myself to Misc/maintainers.rst for asyncore, asynchat and ssl modules and networking interest area ........ Modified: python/branches/release31-maint/ (props changed) python/branches/release31-maint/Misc/maintainers.rst Modified: python/branches/release31-maint/Misc/maintainers.rst ============================================================================== --- python/branches/release31-maint/Misc/maintainers.rst (original) +++ python/branches/release31-maint/Misc/maintainers.rst Sat May 1 20:07:41 2010 @@ -48,8 +48,8 @@ argparse bethard array ast -asynchat josiahcarlson -asyncore josiahcarlson +asynchat josiahcarlson, giampaolo.rodola +asyncore josiahcarlson, giampaolo.rodola atexit audioop base64 @@ -187,7 +187,7 @@ socketserver spwd sqlite3 ghaering -ssl janssen, pitrou +ssl janssen, pitrou, giampaolo.rodola stat string stringprep @@ -280,7 +280,7 @@ locale lemburg, loewis mathematics mark.dickinson, eric.smith, lemburg memory management tim_one, lemburg -networking +networking giampaolo.rodola packaging tarek, lemburg py3 transition benjamin.peterson release management tarek, lemburg, benjamin.peterson, barry, loewis, From python-checkins at python.org Sat May 1 22:26:58 2010 From: python-checkins at python.org (antoine.pitrou) Date: Sat, 1 May 2010 22:26:58 +0200 (CEST) Subject: [Python-checkins] r80690 - python/trunk/Lib/test/test_ssl.py Message-ID: <20100501202658.8D469E1D5@mail.python.org> Author: antoine.pitrou Date: Sat May 1 22:26:58 2010 New Revision: 80690 Log: Remove duplicate test Modified: python/trunk/Lib/test/test_ssl.py Modified: python/trunk/Lib/test/test_ssl.py ============================================================================== --- python/trunk/Lib/test/test_ssl.py (original) +++ python/trunk/Lib/test/test_ssl.py Sat May 1 22:26:58 2010 @@ -54,27 +54,6 @@ else: raise - def test_connect(self): - if not test_support.is_resource_enabled('network'): - return - s = ssl.wrap_socket(socket.socket(socket.AF_INET), - cert_reqs=ssl.CERT_NONE) - s.connect(("svn.python.org", 443)) - c = s.getpeercert() - if c: - self.fail("Peer cert %s shouldn't be here!") - s.close() - - # this should fail because we have no verification certs - s = ssl.wrap_socket(socket.socket(socket.AF_INET), - cert_reqs=ssl.CERT_REQUIRED) - try: - s.connect(("svn.python.org", 443)) - except ssl.SSLError: - pass - finally: - s.close() - def test_constants(self): ssl.PROTOCOL_SSLv2 ssl.PROTOCOL_SSLv23 From python-checkins at python.org Sat May 1 22:28:45 2010 From: python-checkins at python.org (antoine.pitrou) Date: Sat, 1 May 2010 22:28:45 +0200 (CEST) Subject: [Python-checkins] r80691 - in python/branches/release26-maint: Lib/test/test_ssl.py Message-ID: <20100501202845.478DDE1D5@mail.python.org> Author: antoine.pitrou Date: Sat May 1 22:28:45 2010 New Revision: 80691 Log: Merged revisions 80690 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r80690 | antoine.pitrou | 2010-05-01 22:26:58 +0200 (sam., 01 mai 2010) | 3 lines Remove duplicate test ........ Modified: python/branches/release26-maint/ (props changed) python/branches/release26-maint/Lib/test/test_ssl.py Modified: python/branches/release26-maint/Lib/test/test_ssl.py ============================================================================== --- python/branches/release26-maint/Lib/test/test_ssl.py (original) +++ python/branches/release26-maint/Lib/test/test_ssl.py Sat May 1 22:28:45 2010 @@ -57,27 +57,6 @@ else: raise - def test_connect(self): - if not test_support.is_resource_enabled('network'): - return - s = ssl.wrap_socket(socket.socket(socket.AF_INET), - cert_reqs=ssl.CERT_NONE) - s.connect(("svn.python.org", 443)) - c = s.getpeercert() - if c: - self.fail("Peer cert %s shouldn't be here!") - s.close() - - # this should fail because we have no verification certs - s = ssl.wrap_socket(socket.socket(socket.AF_INET), - cert_reqs=ssl.CERT_REQUIRED) - try: - s.connect(("svn.python.org", 443)) - except ssl.SSLError: - pass - finally: - s.close() - def test_constants(self): ssl.PROTOCOL_SSLv2 ssl.PROTOCOL_SSLv23 From python-checkins at python.org Sat May 1 22:29:38 2010 From: python-checkins at python.org (antoine.pitrou) Date: Sat, 1 May 2010 22:29:38 +0200 (CEST) Subject: [Python-checkins] r80692 - in python/branches/py3k: Lib/test/test_ssl.py Message-ID: <20100501202938.4FE01E7A3@mail.python.org> Author: antoine.pitrou Date: Sat May 1 22:29:38 2010 New Revision: 80692 Log: Merged revisions 80690 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r80690 | antoine.pitrou | 2010-05-01 22:26:58 +0200 (sam., 01 mai 2010) | 3 lines Remove duplicate test ........ Modified: python/branches/py3k/ (props changed) python/branches/py3k/Lib/test/test_ssl.py Modified: python/branches/py3k/Lib/test/test_ssl.py ============================================================================== --- python/branches/py3k/Lib/test/test_ssl.py (original) +++ python/branches/py3k/Lib/test/test_ssl.py Sat May 1 22:29:38 2010 @@ -36,27 +36,6 @@ class BasicTests(unittest.TestCase): - def test_connect(self): - if not support.is_resource_enabled('network'): - return - s = ssl.wrap_socket(socket.socket(socket.AF_INET), - cert_reqs=ssl.CERT_NONE) - s.connect(("svn.python.org", 443)) - c = s.getpeercert() - if c: - self.fail("Peer cert %s shouldn't be here!") - s.close() - - # this should fail because we have no verification certs - s = ssl.wrap_socket(socket.socket(socket.AF_INET), - cert_reqs=ssl.CERT_REQUIRED) - try: - s.connect(("svn.python.org", 443)) - except ssl.SSLError: - pass - finally: - s.close() - def test_constants(self): ssl.PROTOCOL_SSLv2 ssl.PROTOCOL_SSLv23 From python-checkins at python.org Sat May 1 22:33:30 2010 From: python-checkins at python.org (antoine.pitrou) Date: Sat, 1 May 2010 22:33:30 +0200 (CEST) Subject: [Python-checkins] r80693 - in python/branches/release31-maint: Lib/test/test_ssl.py Message-ID: <20100501203330.8CF41E2DC@mail.python.org> Author: antoine.pitrou Date: Sat May 1 22:33:30 2010 New Revision: 80693 Log: Merged revisions 80692 via svnmerge from svn+ssh://pythondev at svn.python.org/python/branches/py3k ................ r80692 | antoine.pitrou | 2010-05-01 22:29:38 +0200 (sam., 01 mai 2010) | 9 lines Merged revisions 80690 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r80690 | antoine.pitrou | 2010-05-01 22:26:58 +0200 (sam., 01 mai 2010) | 3 lines Remove duplicate test ........ ................ Modified: python/branches/release31-maint/ (props changed) python/branches/release31-maint/Lib/test/test_ssl.py Modified: python/branches/release31-maint/Lib/test/test_ssl.py ============================================================================== --- python/branches/release31-maint/Lib/test/test_ssl.py (original) +++ python/branches/release31-maint/Lib/test/test_ssl.py Sat May 1 22:33:30 2010 @@ -39,27 +39,6 @@ class BasicTests(unittest.TestCase): - def test_connect(self): - if not support.is_resource_enabled('network'): - return - s = ssl.wrap_socket(socket.socket(socket.AF_INET), - cert_reqs=ssl.CERT_NONE) - s.connect(("svn.python.org", 443)) - c = s.getpeercert() - if c: - self.fail("Peer cert %s shouldn't be here!") - s.close() - - # this should fail because we have no verification certs - s = ssl.wrap_socket(socket.socket(socket.AF_INET), - cert_reqs=ssl.CERT_REQUIRED) - try: - s.connect(("svn.python.org", 443)) - except ssl.SSLError: - pass - finally: - s.close() - def test_constants(self): ssl.PROTOCOL_SSLv2 ssl.PROTOCOL_SSLv23 From solipsis at pitrou.net Sun May 2 00:39:16 2010 From: solipsis at pitrou.net (solipsis at pitrou.net) Date: Sun, 2 May 2010 00:39:16 +0200 (CEST) Subject: [Python-checkins] Daily py3k reference leaks (r80692): sum=0 Message-ID: <20100501223916.D16591770A@ns6635.ovh.net> py3k results for svn r80692 (hg cset 2e516d720372) -------------------------------------------------- Command line was: ['./python', '-m', 'test.regrtest', '-uall', '-R', '3:3:/home/antoine/py3k/refleaks/reflogM3twPU', '-x'] From ncoghlan at gmail.com Sun May 2 05:40:48 2010 From: ncoghlan at gmail.com (Nick Coghlan) Date: Sun, 02 May 2010 13:40:48 +1000 Subject: [Python-checkins] r80674 - python/trunk/Doc/whatsnew/2.7.rst In-Reply-To: <20100501120231.GA36665@andrew-kuchlings-macbook.local> References: <20100501011916.9842CEE9AD@mail.python.org> <4BDBA876.8040806@gmail.com> <20100501120231.GA36665@andrew-kuchlings-macbook.local> Message-ID: <4BDCF440.8010504@gmail.com> A.M. Kuchling wrote: > On Sat, May 01, 2010 at 02:05:10PM +1000, Nick Coghlan wrote: >> I doubt you meant to add this twice. > > No, I actually did; the second copy is in the 'Porting to Python 2.7' > section that lists changes in behaviour that might break code. Ah, no worries then - the joys of the lack of overall context when reading only a diff :) Cheers, Nick. -- Nick Coghlan | ncoghlan at gmail.com | Brisbane, Australia --------------------------------------------------------------- From python-checkins at python.org Sun May 2 11:37:08 2010 From: python-checkins at python.org (victor.stinner) Date: Sun, 2 May 2010 11:37:08 +0200 (CEST) Subject: [Python-checkins] r80694 - in python/branches/py3k: Lib/test/regrtest.py Lib/test/support.py Misc/NEWS Message-ID: <20100502093708.B18C0FD8E@mail.python.org> Author: victor.stinner Date: Sun May 2 11:37:08 2010 New Revision: 80694 Log: Issue #8533: Write tracebacks and failed tests to sys.stderr instead of sys.stdout to avoid UnicodeEncodeError (use backslashreplace error handler) Modified: python/branches/py3k/Lib/test/regrtest.py python/branches/py3k/Lib/test/support.py python/branches/py3k/Misc/NEWS Modified: python/branches/py3k/Lib/test/regrtest.py ============================================================================== --- python/branches/py3k/Lib/test/regrtest.py (original) +++ python/branches/py3k/Lib/test/regrtest.py Sun May 2 11:37:08 2010 @@ -939,8 +939,8 @@ print("test", test, "crashed --", str(type) + ":", value) sys.stdout.flush() if verbose or debug: - traceback.print_exc(file=sys.stdout) - sys.stdout.flush() + traceback.print_exc(file=sys.stderr) + sys.stderr.flush() return FAILED, test_time else: if refleak: Modified: python/branches/py3k/Lib/test/support.py ============================================================================== --- python/branches/py3k/Lib/test/support.py (original) +++ python/branches/py3k/Lib/test/support.py Sun May 2 11:37:08 2010 @@ -1020,7 +1020,7 @@ def _run_suite(suite): """Run tests from a unittest.TestSuite-derived class.""" if verbose: - runner = unittest.TextTestRunner(sys.stdout, verbosity=2) + runner = unittest.TextTestRunner(sys.stderr, verbosity=2) else: runner = BasicTestRunner() Modified: python/branches/py3k/Misc/NEWS ============================================================================== --- python/branches/py3k/Misc/NEWS (original) +++ python/branches/py3k/Misc/NEWS Sun May 2 11:37:08 2010 @@ -1198,6 +1198,9 @@ Tests ----- +- Issue #8533: Write tracebacks and failed tests to sys.stderr instead of + sys.stdout to avoid UnicodeEncodeError (use backslashreplace error handler) + - Issue #8576: Remove use of find_unused_port() in test_smtplib and test_multiprocessing. Patch by Paul Moore. From python-checkins at python.org Sun May 2 11:38:43 2010 From: python-checkins at python.org (mark.dickinson) Date: Sun, 2 May 2010 11:38:43 +0200 (CEST) Subject: [Python-checkins] r80695 - python/trunk/Objects/intobject.c Message-ID: <20100502093843.56783FB42@mail.python.org> Author: mark.dickinson Date: Sun May 2 11:38:43 2010 New Revision: 80695 Log: Improve error message from nb_int returning a non-integer, in various PyInt_As* functions: Modified: python/trunk/Objects/intobject.c Modified: python/trunk/Objects/intobject.c ============================================================================== --- python/trunk/Objects/intobject.c (original) +++ python/trunk/Objects/intobject.c Sun May 2 11:38:43 2010 @@ -178,7 +178,7 @@ { Py_DECREF(io); PyErr_SetString(PyExc_TypeError, - "nb_int should return int object"); + "__int__ method should return an integer"); return -1; } } @@ -236,7 +236,7 @@ { Py_DECREF(io); PyErr_SetString(PyExc_TypeError, - "nb_int should return int object"); + "__int__ method should return an integer"); return -1; } } @@ -281,7 +281,7 @@ { Py_DECREF(io); PyErr_SetString(PyExc_TypeError, - "nb_int should return int object"); + "__int__ method should return an integer"); return (unsigned long)-1; } } @@ -326,7 +326,7 @@ { Py_DECREF(io); PyErr_SetString(PyExc_TypeError, - "nb_int should return int object"); + "__int__ method should return an integer"); return (unsigned PY_LONG_LONG)-1; } } From python-checkins at python.org Sun May 2 11:39:15 2010 From: python-checkins at python.org (mark.dickinson) Date: Sun, 2 May 2010 11:39:15 +0200 (CEST) Subject: [Python-checkins] r80696 - python/branches/release26-maint Message-ID: <20100502093915.1BCAFFD90@mail.python.org> Author: mark.dickinson Date: Sun May 2 11:39:14 2010 New Revision: 80696 Log: Blocked revisions 80695 via svnmerge ........ r80695 | mark.dickinson | 2010-05-02 10:38:43 +0100 (Sun, 02 May 2010) | 2 lines Improve error message from nb_int returning a non-integer, in various PyInt_As* functions: ........ Modified: python/branches/release26-maint/ (props changed) From python-checkins at python.org Sun May 2 11:40:10 2010 From: python-checkins at python.org (mark.dickinson) Date: Sun, 2 May 2010 11:40:10 +0200 (CEST) Subject: [Python-checkins] r80697 - python/branches/py3k Message-ID: <20100502094010.83A55D4FC@mail.python.org> Author: mark.dickinson Date: Sun May 2 11:40:10 2010 New Revision: 80697 Log: Blocked revisions 80695 via svnmerge ........ r80695 | mark.dickinson | 2010-05-02 10:38:43 +0100 (Sun, 02 May 2010) | 2 lines Improve error message from nb_int returning a non-integer, in various PyInt_As* functions: ........ Modified: python/branches/py3k/ (props changed) From python-checkins at python.org Sun May 2 11:48:21 2010 From: python-checkins at python.org (ronald.oussoren) Date: Sun, 2 May 2010 11:48:21 +0200 (CEST) Subject: [Python-checkins] r80698 - in python/trunk: Lib/webbrowser.py Misc/NEWS Message-ID: <20100502094821.6628BFAE4@mail.python.org> Author: ronald.oussoren Date: Sun May 2 11:48:21 2010 New Revision: 80698 Log: For for issue #7192: with this patch webbrowser.get("firefox") works on OSX Modified: python/trunk/Lib/webbrowser.py python/trunk/Misc/NEWS Modified: python/trunk/Lib/webbrowser.py ============================================================================== --- python/trunk/Lib/webbrowser.py (original) +++ python/trunk/Lib/webbrowser.py Sun May 2 11:48:21 2010 @@ -599,9 +599,35 @@ rc = osapipe.close() return not rc + class MacOSXOSAScript(BaseBrowser): + def __init__(self, name): + self._name = name + + def open(self, url, new=0, autoraise=True): + if self._name == 'default': + script = 'open location "%s"' % url.replace('"', '%22') # opens in default browser + else: + script = ''' + tell application "%s" + activate + open location "%s" + end + '''%(self._name, url.replace('"', '%22')) + + osapipe = os.popen("osascript", "w") + if osapipe is None: + return False + + osapipe.write(script) + rc = osapipe.close() + return not rc + + # Don't clear _tryorder or _browsers since OS X can use above Unix support # (but we prefer using the OS X specific stuff) - register("MacOSX", None, MacOSX('default'), -1) + register("MacOSX", None, MacOSXOSAScript('default'), -1) + register("safari", None, MacOSXOSAScript('safari'), -1) + register("firefox", None, MacOSXOSAScript('firefox'), -1) # Modified: python/trunk/Misc/NEWS ============================================================================== --- python/trunk/Misc/NEWS (original) +++ python/trunk/Misc/NEWS Sun May 2 11:48:21 2010 @@ -31,6 +31,9 @@ Library ------- +- Issue #7192: webbrowser.get("firefox") now wors on Mac OS X, as does + webbrowser.get("safari"). + - Issue #8577: distutils.sysconfig.get_python_inc() now makes a difference between the build dir and the source dir when looking for "python.h" or "Include". From python-checkins at python.org Sun May 2 11:54:36 2010 From: python-checkins at python.org (ronald.oussoren) Date: Sun, 2 May 2010 11:54:36 +0200 (CEST) Subject: [Python-checkins] r80699 - in python/branches/py3k: Lib/webbrowser.py Misc/NEWS Message-ID: <20100502095436.1535AF750@mail.python.org> Author: ronald.oussoren Date: Sun May 2 11:54:35 2010 New Revision: 80699 Log: Merged revisions 80698 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r80698 | ronald.oussoren | 2010-05-02 11:48:21 +0200 (Sun, 02 May 2010) | 3 lines For for issue #7192: with this patch webbrowser.get("firefox") works on OSX ........ Modified: python/branches/py3k/ (props changed) python/branches/py3k/Lib/webbrowser.py python/branches/py3k/Misc/NEWS Modified: python/branches/py3k/Lib/webbrowser.py ============================================================================== --- python/branches/py3k/Lib/webbrowser.py (original) +++ python/branches/py3k/Lib/webbrowser.py Sun May 2 11:54:35 2010 @@ -600,9 +600,35 @@ rc = osapipe.close() return not rc + class MacOSXOSAScript(BaseBrowser): + def __init__(self, name): + self._name = name + + def open(self, url, new=0, autoraise=True): + if self._name == 'default': + script = 'open location "%s"' % url.replace('"', '%22') # opens in default browser + else: + script = ''' + tell application "%s" + activate + open location "%s" + end + '''%(self._name, url.replace('"', '%22')) + + osapipe = os.popen("osascript", "w") + if osapipe is None: + return False + + osapipe.write(script) + rc = osapipe.close() + return not rc + + # Don't clear _tryorder or _browsers since OS X can use above Unix support # (but we prefer using the OS X specific stuff) - register("MacOSX", None, MacOSX('default'), -1) + register("safari", None, MacOSXOSAScript('safari'), -1) + register("firefox", None, MacOSXOSAScript('firefox'), -1) + register("MacOSX", None, MacOSXOSAScript('default'), -1) # Modified: python/branches/py3k/Misc/NEWS ============================================================================== --- python/branches/py3k/Misc/NEWS (original) +++ python/branches/py3k/Misc/NEWS Sun May 2 11:54:35 2010 @@ -345,6 +345,9 @@ Library ------- +- Issue #7192: webbrowser.get("firefox") now wors on Mac OS X, as does + webbrowser.get("safari"). + - Issue #8464: tarfile no longer creates files with execute permissions set when mode="w|" is used. From python-checkins at python.org Sun May 2 11:55:57 2010 From: python-checkins at python.org (ronald.oussoren) Date: Sun, 2 May 2010 11:55:57 +0200 (CEST) Subject: [Python-checkins] r80700 - python/trunk/Lib/webbrowser.py Message-ID: <20100502095557.72E19E95D@mail.python.org> Author: ronald.oussoren Date: Sun May 2 11:55:57 2010 New Revision: 80700 Log: Small update to r80698 to ensure that webbrowser.open uses the default browser. Modified: python/trunk/Lib/webbrowser.py Modified: python/trunk/Lib/webbrowser.py ============================================================================== --- python/trunk/Lib/webbrowser.py (original) +++ python/trunk/Lib/webbrowser.py Sun May 2 11:55:57 2010 @@ -625,9 +625,9 @@ # Don't clear _tryorder or _browsers since OS X can use above Unix support # (but we prefer using the OS X specific stuff) - register("MacOSX", None, MacOSXOSAScript('default'), -1) register("safari", None, MacOSXOSAScript('safari'), -1) register("firefox", None, MacOSXOSAScript('firefox'), -1) + register("MacOSX", None, MacOSXOSAScript('default'), -1) # From python-checkins at python.org Sun May 2 18:45:12 2010 From: python-checkins at python.org (benjamin.peterson) Date: Sun, 2 May 2010 18:45:12 +0200 (CEST) Subject: [Python-checkins] r80701 - in python/branches/release26-maint: configure configure.in Message-ID: <20100502164512.BEB06DD77@mail.python.org> Author: benjamin.peterson Date: Sun May 2 18:45:11 2010 New Revision: 80701 Log: Merged revisions 78962,78964 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r78962 | benjamin.peterson | 2010-03-14 09:24:31 -0500 (Sun, 14 Mar 2010) | 1 line fix freebsd linking #7705 ........ r78964 | benjamin.peterson | 2010-03-14 10:06:14 -0500 (Sun, 14 Mar 2010) | 1 line fix quotes ........ Modified: python/branches/release26-maint/ (props changed) python/branches/release26-maint/configure python/branches/release26-maint/configure.in Modified: python/branches/release26-maint/configure ============================================================================== --- python/branches/release26-maint/configure (original) +++ python/branches/release26-maint/configure Sun May 2 18:45:11 2010 @@ -1,12 +1,12 @@ #! /bin/sh -# From configure.in Revision: 80193 . +# From configure.in Revision: 80575 . # Guess values for system-dependent variables and create Makefiles. -# Generated by GNU Autoconf 2.61 for python 2.6. +# Generated by GNU Autoconf 2.63 for python 2.6. # # Report bugs to . # # Copyright (C) 1992, 1993, 1994, 1995, 1996, 1998, 1999, 2000, 2001, -# 2002, 2003, 2004, 2005, 2006 Free Software Foundation, Inc. +# 2002, 2003, 2004, 2005, 2006, 2007, 2008 Free Software Foundation, Inc. # This configure script is free software; the Free Software Foundation # gives unlimited permission to copy, distribute and modify it. ## --------------------- ## @@ -18,7 +18,7 @@ if test -n "${ZSH_VERSION+set}" && (emulate sh) >/dev/null 2>&1; then emulate sh NULLCMD=: - # Zsh 3.x and 4.x performs word splitting on ${1+"$@"}, which + # Pre-4.2 versions of Zsh do word splitting on ${1+"$@"}, which # is contrary to our usage. Disable this feature. alias -g '${1+"$@"}'='"$@"' setopt NO_GLOB_SUBST @@ -40,17 +40,45 @@ as_cr_digits='0123456789' as_cr_alnum=$as_cr_Letters$as_cr_digits -# The user is always right. -if test "${PATH_SEPARATOR+set}" != set; then - echo "#! /bin/sh" >conf$$.sh - echo "exit 0" >>conf$$.sh - chmod +x conf$$.sh - if (PATH="/nonexistent;."; conf$$.sh) >/dev/null 2>&1; then - PATH_SEPARATOR=';' +as_nl=' +' +export as_nl +# Printing a long string crashes Solaris 7 /usr/bin/printf. +as_echo='\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\' +as_echo=$as_echo$as_echo$as_echo$as_echo$as_echo +as_echo=$as_echo$as_echo$as_echo$as_echo$as_echo$as_echo +if (test "X`printf %s $as_echo`" = "X$as_echo") 2>/dev/null; then + as_echo='printf %s\n' + as_echo_n='printf %s' +else + if test "X`(/usr/ucb/echo -n -n $as_echo) 2>/dev/null`" = "X-n $as_echo"; then + as_echo_body='eval /usr/ucb/echo -n "$1$as_nl"' + as_echo_n='/usr/ucb/echo -n' else - PATH_SEPARATOR=: + as_echo_body='eval expr "X$1" : "X\\(.*\\)"' + as_echo_n_body='eval + arg=$1; + case $arg in + *"$as_nl"*) + expr "X$arg" : "X\\(.*\\)$as_nl"; + arg=`expr "X$arg" : ".*$as_nl\\(.*\\)"`;; + esac; + expr "X$arg" : "X\\(.*\\)" | tr -d "$as_nl" + ' + export as_echo_n_body + as_echo_n='sh -c $as_echo_n_body as_echo' fi - rm -f conf$$.sh + export as_echo_body + as_echo='sh -c $as_echo_body as_echo' +fi + +# The user is always right. +if test "${PATH_SEPARATOR+set}" != set; then + PATH_SEPARATOR=: + (PATH='/bin;/bin'; FPATH=$PATH; sh -c :) >/dev/null 2>&1 && { + (PATH='/bin:/bin'; FPATH=$PATH; sh -c :) >/dev/null 2>&1 || + PATH_SEPARATOR=';' + } fi # Support unset when possible. @@ -66,8 +94,6 @@ # there to prevent editors from complaining about space-tab. # (If _AS_PATH_WALK were called with IFS unset, it would disable word # splitting by setting IFS to empty value.) -as_nl=' -' IFS=" "" $as_nl" # Find who we are. Look in the path if we contain no directory separator. @@ -90,7 +116,7 @@ as_myself=$0 fi if test ! -f "$as_myself"; then - echo "$as_myself: error: cannot find myself; rerun with an absolute file name" >&2 + $as_echo "$as_myself: error: cannot find myself; rerun with an absolute file name" >&2 { (exit 1); exit 1; } fi @@ -103,17 +129,10 @@ PS4='+ ' # NLS nuisances. -for as_var in \ - LANG LANGUAGE LC_ADDRESS LC_ALL LC_COLLATE LC_CTYPE LC_IDENTIFICATION \ - LC_MEASUREMENT LC_MESSAGES LC_MONETARY LC_NAME LC_NUMERIC LC_PAPER \ - LC_TELEPHONE LC_TIME -do - if (set +x; test -z "`(eval $as_var=C; export $as_var) 2>&1`"); then - eval $as_var=C; export $as_var - else - ($as_unset $as_var) >/dev/null 2>&1 && $as_unset $as_var - fi -done +LC_ALL=C +export LC_ALL +LANGUAGE=C +export LANGUAGE # Required to use basename. if expr a : '\(a\)' >/dev/null 2>&1 && @@ -135,7 +154,7 @@ $as_expr X/"$0" : '.*/\([^/][^/]*\)/*$' \| \ X"$0" : 'X\(//\)$' \| \ X"$0" : 'X\(/\)' \| . 2>/dev/null || -echo X/"$0" | +$as_echo X/"$0" | sed '/^.*\/\([^/][^/]*\)\/*$/{ s//\1/ q @@ -161,7 +180,7 @@ as_have_required=no fi - if test $as_have_required = yes && (eval ": + if test $as_have_required = yes && (eval ": (as_func_return () { (exit \$1) } @@ -243,7 +262,7 @@ if test -n "${ZSH_VERSION+set}" && (emulate sh) >/dev/null 2>&1; then emulate sh NULLCMD=: - # Zsh 3.x and 4.x performs word splitting on ${1+"$@"}, which + # Pre-4.2 versions of Zsh do word splitting on ${1+"$@"}, which # is contrary to our usage. Disable this feature. alias -g '${1+"$@"}'='"$@"' setopt NO_GLOB_SUBST @@ -264,7 +283,7 @@ if test -n "${ZSH_VERSION+set}" && (emulate sh) >/dev/null 2>&1; then emulate sh NULLCMD=: - # Zsh 3.x and 4.x performs word splitting on ${1+"$@"}, which + # Pre-4.2 versions of Zsh do word splitting on ${1+"$@"}, which # is contrary to our usage. Disable this feature. alias -g '${1+"$@"}'='"$@"' setopt NO_GLOB_SUBST @@ -344,10 +363,10 @@ if test "x$CONFIG_SHELL" != x; then for as_var in BASH_ENV ENV - do ($as_unset $as_var) >/dev/null 2>&1 && $as_unset $as_var - done - export CONFIG_SHELL - exec "$CONFIG_SHELL" "$as_myself" ${1+"$@"} + do ($as_unset $as_var) >/dev/null 2>&1 && $as_unset $as_var + done + export CONFIG_SHELL + exec "$CONFIG_SHELL" "$as_myself" ${1+"$@"} fi @@ -416,9 +435,10 @@ test \$exitcode = 0") || { echo No shell found that supports shell functions. - echo Please tell autoconf at gnu.org about your system, - echo including any error possibly output before this - echo message + echo Please tell bug-autoconf at gnu.org about your system, + echo including any error possibly output before this message. + echo This can help us improve future autoconf versions. + echo Configuration will now proceed without shell functions. } @@ -454,7 +474,7 @@ s/-\n.*// ' >$as_me.lineno && chmod +x "$as_me.lineno" || - { echo "$as_me: error: cannot create $as_me.lineno; rerun with a POSIX shell" >&2 + { $as_echo "$as_me: error: cannot create $as_me.lineno; rerun with a POSIX shell" >&2 { (exit 1); exit 1; }; } # Don't try to exec as it changes $[0], causing all sort of problems @@ -482,7 +502,6 @@ *) ECHO_N='-n';; esac - if expr a : '\(a\)' >/dev/null 2>&1 && test "X`expr 00001 : '.*\(...\)'`" = X001; then as_expr=expr @@ -495,19 +514,22 @@ rm -f conf$$.dir/conf$$.file else rm -f conf$$.dir - mkdir conf$$.dir + mkdir conf$$.dir 2>/dev/null fi -echo >conf$$.file -if ln -s conf$$.file conf$$ 2>/dev/null; then - as_ln_s='ln -s' - # ... but there are two gotchas: - # 1) On MSYS, both `ln -s file dir' and `ln file dir' fail. - # 2) DJGPP < 2.04 has no symlinks; `ln -s' creates a wrapper executable. - # In both cases, we have to default to `cp -p'. - ln -s conf$$.file conf$$.dir 2>/dev/null && test ! -f conf$$.exe || +if (echo >conf$$.file) 2>/dev/null; then + if ln -s conf$$.file conf$$ 2>/dev/null; then + as_ln_s='ln -s' + # ... but there are two gotchas: + # 1) On MSYS, both `ln -s file dir' and `ln file dir' fail. + # 2) DJGPP < 2.04 has no symlinks; `ln -s' creates a wrapper executable. + # In both cases, we have to default to `cp -p'. + ln -s conf$$.file conf$$.dir 2>/dev/null && test ! -f conf$$.exe || + as_ln_s='cp -p' + elif ln conf$$.file conf$$ 2>/dev/null; then + as_ln_s=ln + else as_ln_s='cp -p' -elif ln conf$$.file conf$$ 2>/dev/null; then - as_ln_s=ln + fi else as_ln_s='cp -p' fi @@ -532,10 +554,10 @@ as_test_x=' eval sh -c '\'' if test -d "$1"; then - test -d "$1/."; + test -d "$1/."; else case $1 in - -*)set "./$1";; + -*)set "./$1";; esac; case `ls -ld'$as_ls_L_option' "$1" 2>/dev/null` in ???[sx]*):;;*)false;;esac;fi @@ -616,128 +638,158 @@ # include #endif" -ac_subst_vars='SHELL -PATH_SEPARATOR -PACKAGE_NAME -PACKAGE_TARNAME -PACKAGE_VERSION -PACKAGE_STRING -PACKAGE_BUGREPORT -exec_prefix -prefix -program_transform_name -bindir -sbindir -libexecdir -datarootdir -datadir -sysconfdir -sharedstatedir -localstatedir -includedir -oldincludedir -docdir -infodir -htmldir -dvidir -pdfdir -psdir -libdir -localedir -mandir -DEFS -ECHO_C -ECHO_N -ECHO_T -LIBS -build_alias -host_alias -target_alias -VERSION -SOVERSION -CONFIG_ARGS -UNIVERSALSDK -ARCH_RUN_32BIT -LIPO_32BIT_FLAGS -LIPO_64BIT_FLAGS -PYTHONFRAMEWORK -PYTHONFRAMEWORKIDENTIFIER -PYTHONFRAMEWORKDIR -PYTHONFRAMEWORKPREFIX -PYTHONFRAMEWORKINSTALLDIR -FRAMEWORKINSTALLFIRST -FRAMEWORKINSTALLLAST -FRAMEWORKALTINSTALLFIRST -FRAMEWORKALTINSTALLLAST -FRAMEWORKUNIXTOOLSPREFIX -MACHDEP -SGI_ABI -EXTRAPLATDIR -EXTRAMACHDEPPATH -CONFIGURE_MACOSX_DEPLOYMENT_TARGET -EXPORT_MACOSX_DEPLOYMENT_TARGET -CC -CFLAGS -LDFLAGS -CPPFLAGS -ac_ct_CC -EXEEXT -OBJEXT -CXX -MAINCC -CPP -GREP -EGREP -BUILDEXEEXT -LIBRARY -LDLIBRARY -DLLLIBRARY -BLDLIBRARY -LDLIBRARYDIR -INSTSONAME -RUNSHARED -LINKCC -RANLIB -AR -SVNVERSION -INSTALL_PROGRAM -INSTALL_SCRIPT -INSTALL_DATA -LN -OPT -BASECFLAGS -UNIVERSAL_ARCH_FLAGS -OTHER_LIBTOOL_OPT -LIBTOOL_CRUFT -SO -LDSHARED -BLDSHARED -CCSHARED -LINKFORSHARED -CFLAGSFORSHARED -SHLIBS -USE_SIGNAL_MODULE -SIGNAL_OBJS -USE_THREAD_MODULE -LDLAST -THREADOBJ -DLINCLDIR -DYNLOADFILE -MACHDEP_OBJS -TRUE -LIBOBJS -HAVE_GETHOSTBYNAME_R_6_ARG -HAVE_GETHOSTBYNAME_R_5_ARG -HAVE_GETHOSTBYNAME_R_3_ARG -HAVE_GETHOSTBYNAME_R -HAVE_GETHOSTBYNAME -LIBM -LIBC -UNICODE_OBJS -THREADHEADERS +ac_subst_vars='LTLIBOBJS SRCDIRS -LTLIBOBJS' +THREADHEADERS +UNICODE_OBJS +LIBC +LIBM +HAVE_GETHOSTBYNAME +HAVE_GETHOSTBYNAME_R +HAVE_GETHOSTBYNAME_R_3_ARG +HAVE_GETHOSTBYNAME_R_5_ARG +HAVE_GETHOSTBYNAME_R_6_ARG +LIBOBJS +TRUE +MACHDEP_OBJS +DYNLOADFILE +DLINCLDIR +THREADOBJ +LDLAST +USE_THREAD_MODULE +SIGNAL_OBJS +USE_SIGNAL_MODULE +SHLIBS +CFLAGSFORSHARED +LINKFORSHARED +CCSHARED +BLDSHARED +LDSHARED +SO +LIBTOOL_CRUFT +OTHER_LIBTOOL_OPT +UNIVERSAL_ARCH_FLAGS +BASECFLAGS +OPT +LN +INSTALL_DATA +INSTALL_SCRIPT +INSTALL_PROGRAM +SVNVERSION +AR +RANLIB +LINKCC +RUNSHARED +INSTSONAME +LDLIBRARYDIR +BLDLIBRARY +DLLLIBRARY +LDLIBRARY +LIBRARY +BUILDEXEEXT +EGREP +GREP +CPP +MAINCC +CXX +OBJEXT +EXEEXT +ac_ct_CC +CPPFLAGS +LDFLAGS +CFLAGS +CC +EXPORT_MACOSX_DEPLOYMENT_TARGET +CONFIGURE_MACOSX_DEPLOYMENT_TARGET +EXTRAMACHDEPPATH +EXTRAPLATDIR +SGI_ABI +MACHDEP +FRAMEWORKUNIXTOOLSPREFIX +FRAMEWORKALTINSTALLLAST +FRAMEWORKALTINSTALLFIRST +FRAMEWORKINSTALLLAST +FRAMEWORKINSTALLFIRST +PYTHONFRAMEWORKINSTALLDIR +PYTHONFRAMEWORKPREFIX +PYTHONFRAMEWORKDIR +PYTHONFRAMEWORKIDENTIFIER +PYTHONFRAMEWORK +LIPO_64BIT_FLAGS +LIPO_32BIT_FLAGS +ARCH_RUN_32BIT +UNIVERSALSDK +CONFIG_ARGS +SOVERSION +VERSION +target_alias +host_alias +build_alias +LIBS +ECHO_T +ECHO_N +ECHO_C +DEFS +mandir +localedir +libdir +psdir +pdfdir +dvidir +htmldir +infodir +docdir +oldincludedir +includedir +localstatedir +sharedstatedir +sysconfdir +datadir +datarootdir +libexecdir +sbindir +bindir +program_transform_name +prefix +exec_prefix +PACKAGE_BUGREPORT +PACKAGE_STRING +PACKAGE_VERSION +PACKAGE_TARNAME +PACKAGE_NAME +PATH_SEPARATOR +SHELL' ac_subst_files='' +ac_user_opts=' +enable_option_checking +enable_universalsdk +with_universal_archs +with_framework_name +enable_framework +with_gcc +with_cxx_main +with_suffix +enable_shared +enable_profiling +with_pydebug +enable_toolbox_glue +with_libs +with_system_ffi +with_signal_module +with_dec_threads +with_threads +with_thread +with_pth +enable_ipv6 +with_doc_strings +with_tsc +with_pymalloc +with_wctype_functions +with_fpectl +with_libm +with_libc +enable_unicode +' ac_precious_vars='build_alias host_alias target_alias @@ -752,6 +804,8 @@ # Initialize some variables set by options. ac_init_help= ac_init_version=false +ac_unrecognized_opts= +ac_unrecognized_sep= # The variables have the same names as the options, with # dashes changed to underlines. cache_file=/dev/null @@ -850,13 +904,21 @@ datarootdir=$ac_optarg ;; -disable-* | --disable-*) - ac_feature=`expr "x$ac_option" : 'x-*disable-\(.*\)'` + ac_useropt=`expr "x$ac_option" : 'x-*disable-\(.*\)'` # Reject names that are not valid shell variable names. - expr "x$ac_feature" : ".*[^-._$as_cr_alnum]" >/dev/null && - { echo "$as_me: error: invalid feature name: $ac_feature" >&2 + expr "x$ac_useropt" : ".*[^-+._$as_cr_alnum]" >/dev/null && + { $as_echo "$as_me: error: invalid feature name: $ac_useropt" >&2 { (exit 1); exit 1; }; } - ac_feature=`echo $ac_feature | sed 's/[-.]/_/g'` - eval enable_$ac_feature=no ;; + ac_useropt_orig=$ac_useropt + ac_useropt=`$as_echo "$ac_useropt" | sed 's/[-+.]/_/g'` + case $ac_user_opts in + *" +"enable_$ac_useropt" +"*) ;; + *) ac_unrecognized_opts="$ac_unrecognized_opts$ac_unrecognized_sep--disable-$ac_useropt_orig" + ac_unrecognized_sep=', ';; + esac + eval enable_$ac_useropt=no ;; -docdir | --docdir | --docdi | --doc | --do) ac_prev=docdir ;; @@ -869,13 +931,21 @@ dvidir=$ac_optarg ;; -enable-* | --enable-*) - ac_feature=`expr "x$ac_option" : 'x-*enable-\([^=]*\)'` + ac_useropt=`expr "x$ac_option" : 'x-*enable-\([^=]*\)'` # Reject names that are not valid shell variable names. - expr "x$ac_feature" : ".*[^-._$as_cr_alnum]" >/dev/null && - { echo "$as_me: error: invalid feature name: $ac_feature" >&2 + expr "x$ac_useropt" : ".*[^-+._$as_cr_alnum]" >/dev/null && + { $as_echo "$as_me: error: invalid feature name: $ac_useropt" >&2 { (exit 1); exit 1; }; } - ac_feature=`echo $ac_feature | sed 's/[-.]/_/g'` - eval enable_$ac_feature=\$ac_optarg ;; + ac_useropt_orig=$ac_useropt + ac_useropt=`$as_echo "$ac_useropt" | sed 's/[-+.]/_/g'` + case $ac_user_opts in + *" +"enable_$ac_useropt" +"*) ;; + *) ac_unrecognized_opts="$ac_unrecognized_opts$ac_unrecognized_sep--enable-$ac_useropt_orig" + ac_unrecognized_sep=', ';; + esac + eval enable_$ac_useropt=\$ac_optarg ;; -exec-prefix | --exec_prefix | --exec-prefix | --exec-prefi \ | --exec-pref | --exec-pre | --exec-pr | --exec-p | --exec- \ @@ -1066,22 +1136,38 @@ ac_init_version=: ;; -with-* | --with-*) - ac_package=`expr "x$ac_option" : 'x-*with-\([^=]*\)'` + ac_useropt=`expr "x$ac_option" : 'x-*with-\([^=]*\)'` # Reject names that are not valid shell variable names. - expr "x$ac_package" : ".*[^-._$as_cr_alnum]" >/dev/null && - { echo "$as_me: error: invalid package name: $ac_package" >&2 + expr "x$ac_useropt" : ".*[^-+._$as_cr_alnum]" >/dev/null && + { $as_echo "$as_me: error: invalid package name: $ac_useropt" >&2 { (exit 1); exit 1; }; } - ac_package=`echo $ac_package | sed 's/[-.]/_/g'` - eval with_$ac_package=\$ac_optarg ;; + ac_useropt_orig=$ac_useropt + ac_useropt=`$as_echo "$ac_useropt" | sed 's/[-+.]/_/g'` + case $ac_user_opts in + *" +"with_$ac_useropt" +"*) ;; + *) ac_unrecognized_opts="$ac_unrecognized_opts$ac_unrecognized_sep--with-$ac_useropt_orig" + ac_unrecognized_sep=', ';; + esac + eval with_$ac_useropt=\$ac_optarg ;; -without-* | --without-*) - ac_package=`expr "x$ac_option" : 'x-*without-\(.*\)'` + ac_useropt=`expr "x$ac_option" : 'x-*without-\(.*\)'` # Reject names that are not valid shell variable names. - expr "x$ac_package" : ".*[^-._$as_cr_alnum]" >/dev/null && - { echo "$as_me: error: invalid package name: $ac_package" >&2 + expr "x$ac_useropt" : ".*[^-+._$as_cr_alnum]" >/dev/null && + { $as_echo "$as_me: error: invalid package name: $ac_useropt" >&2 { (exit 1); exit 1; }; } - ac_package=`echo $ac_package | sed 's/[-.]/_/g'` - eval with_$ac_package=no ;; + ac_useropt_orig=$ac_useropt + ac_useropt=`$as_echo "$ac_useropt" | sed 's/[-+.]/_/g'` + case $ac_user_opts in + *" +"with_$ac_useropt" +"*) ;; + *) ac_unrecognized_opts="$ac_unrecognized_opts$ac_unrecognized_sep--without-$ac_useropt_orig" + ac_unrecognized_sep=', ';; + esac + eval with_$ac_useropt=no ;; --x) # Obsolete; use --with-x. @@ -1101,7 +1187,7 @@ | --x-librar=* | --x-libra=* | --x-libr=* | --x-lib=* | --x-li=* | --x-l=*) x_libraries=$ac_optarg ;; - -*) { echo "$as_me: error: unrecognized option: $ac_option + -*) { $as_echo "$as_me: error: unrecognized option: $ac_option Try \`$0 --help' for more information." >&2 { (exit 1); exit 1; }; } ;; @@ -1110,16 +1196,16 @@ ac_envvar=`expr "x$ac_option" : 'x\([^=]*\)='` # Reject names that are not valid shell variable names. expr "x$ac_envvar" : ".*[^_$as_cr_alnum]" >/dev/null && - { echo "$as_me: error: invalid variable name: $ac_envvar" >&2 + { $as_echo "$as_me: error: invalid variable name: $ac_envvar" >&2 { (exit 1); exit 1; }; } eval $ac_envvar=\$ac_optarg export $ac_envvar ;; *) # FIXME: should be removed in autoconf 3.0. - echo "$as_me: WARNING: you should use --build, --host, --target" >&2 + $as_echo "$as_me: WARNING: you should use --build, --host, --target" >&2 expr "x$ac_option" : ".*[^-._$as_cr_alnum]" >/dev/null && - echo "$as_me: WARNING: invalid host type: $ac_option" >&2 + $as_echo "$as_me: WARNING: invalid host type: $ac_option" >&2 : ${build_alias=$ac_option} ${host_alias=$ac_option} ${target_alias=$ac_option} ;; @@ -1128,22 +1214,38 @@ if test -n "$ac_prev"; then ac_option=--`echo $ac_prev | sed 's/_/-/g'` - { echo "$as_me: error: missing argument to $ac_option" >&2 + { $as_echo "$as_me: error: missing argument to $ac_option" >&2 { (exit 1); exit 1; }; } fi -# Be sure to have absolute directory names. +if test -n "$ac_unrecognized_opts"; then + case $enable_option_checking in + no) ;; + fatal) { $as_echo "$as_me: error: unrecognized options: $ac_unrecognized_opts" >&2 + { (exit 1); exit 1; }; } ;; + *) $as_echo "$as_me: WARNING: unrecognized options: $ac_unrecognized_opts" >&2 ;; + esac +fi + +# Check all directory arguments for consistency. for ac_var in exec_prefix prefix bindir sbindir libexecdir datarootdir \ datadir sysconfdir sharedstatedir localstatedir includedir \ oldincludedir docdir infodir htmldir dvidir pdfdir psdir \ libdir localedir mandir do eval ac_val=\$$ac_var + # Remove trailing slashes. + case $ac_val in + */ ) + ac_val=`expr "X$ac_val" : 'X\(.*[^/]\)' \| "X$ac_val" : 'X\(.*\)'` + eval $ac_var=\$ac_val;; + esac + # Be sure to have absolute directory names. case $ac_val in [\\/$]* | ?:[\\/]* ) continue;; NONE | '' ) case $ac_var in *prefix ) continue;; esac;; esac - { echo "$as_me: error: expected an absolute directory name for --$ac_var: $ac_val" >&2 + { $as_echo "$as_me: error: expected an absolute directory name for --$ac_var: $ac_val" >&2 { (exit 1); exit 1; }; } done @@ -1158,7 +1260,7 @@ if test "x$host_alias" != x; then if test "x$build_alias" = x; then cross_compiling=maybe - echo "$as_me: WARNING: If you wanted to set the --build type, don't use --host. + $as_echo "$as_me: WARNING: If you wanted to set the --build type, don't use --host. If a cross compiler is detected then cross compile mode will be used." >&2 elif test "x$build_alias" != "x$host_alias"; then cross_compiling=yes @@ -1174,10 +1276,10 @@ ac_pwd=`pwd` && test -n "$ac_pwd" && ac_ls_di=`ls -di .` && ac_pwd_ls_di=`cd "$ac_pwd" && ls -di .` || - { echo "$as_me: error: Working directory cannot be determined" >&2 + { $as_echo "$as_me: error: working directory cannot be determined" >&2 { (exit 1); exit 1; }; } test "X$ac_ls_di" = "X$ac_pwd_ls_di" || - { echo "$as_me: error: pwd does not report name of working directory" >&2 + { $as_echo "$as_me: error: pwd does not report name of working directory" >&2 { (exit 1); exit 1; }; } @@ -1185,12 +1287,12 @@ if test -z "$srcdir"; then ac_srcdir_defaulted=yes # Try the directory containing this script, then the parent directory. - ac_confdir=`$as_dirname -- "$0" || -$as_expr X"$0" : 'X\(.*[^/]\)//*[^/][^/]*/*$' \| \ - X"$0" : 'X\(//\)[^/]' \| \ - X"$0" : 'X\(//\)$' \| \ - X"$0" : 'X\(/\)' \| . 2>/dev/null || -echo X"$0" | + ac_confdir=`$as_dirname -- "$as_myself" || +$as_expr X"$as_myself" : 'X\(.*[^/]\)//*[^/][^/]*/*$' \| \ + X"$as_myself" : 'X\(//\)[^/]' \| \ + X"$as_myself" : 'X\(//\)$' \| \ + X"$as_myself" : 'X\(/\)' \| . 2>/dev/null || +$as_echo X"$as_myself" | sed '/^X\(.*[^/]\)\/\/*[^/][^/]*\/*$/{ s//\1/ q @@ -1217,12 +1319,12 @@ fi if test ! -r "$srcdir/$ac_unique_file"; then test "$ac_srcdir_defaulted" = yes && srcdir="$ac_confdir or .." - { echo "$as_me: error: cannot find sources ($ac_unique_file) in $srcdir" >&2 + { $as_echo "$as_me: error: cannot find sources ($ac_unique_file) in $srcdir" >&2 { (exit 1); exit 1; }; } fi ac_msg="sources are in $srcdir, but \`cd $srcdir' does not work" ac_abs_confdir=`( - cd "$srcdir" && test -r "./$ac_unique_file" || { echo "$as_me: error: $ac_msg" >&2 + cd "$srcdir" && test -r "./$ac_unique_file" || { $as_echo "$as_me: error: $ac_msg" >&2 { (exit 1); exit 1; }; } pwd)` # When building in place, set srcdir=. @@ -1271,9 +1373,9 @@ Installation directories: --prefix=PREFIX install architecture-independent files in PREFIX - [$ac_default_prefix] + [$ac_default_prefix] --exec-prefix=EPREFIX install architecture-dependent files in EPREFIX - [PREFIX] + [PREFIX] By default, \`make install' will install all the files in \`$ac_default_prefix/bin', \`$ac_default_prefix/lib' etc. You can specify @@ -1283,25 +1385,25 @@ For better control, use the options below. Fine tuning of the installation directories: - --bindir=DIR user executables [EPREFIX/bin] - --sbindir=DIR system admin executables [EPREFIX/sbin] - --libexecdir=DIR program executables [EPREFIX/libexec] - --sysconfdir=DIR read-only single-machine data [PREFIX/etc] - --sharedstatedir=DIR modifiable architecture-independent data [PREFIX/com] - --localstatedir=DIR modifiable single-machine data [PREFIX/var] - --libdir=DIR object code libraries [EPREFIX/lib] - --includedir=DIR C header files [PREFIX/include] - --oldincludedir=DIR C header files for non-gcc [/usr/include] - --datarootdir=DIR read-only arch.-independent data root [PREFIX/share] - --datadir=DIR read-only architecture-independent data [DATAROOTDIR] - --infodir=DIR info documentation [DATAROOTDIR/info] - --localedir=DIR locale-dependent data [DATAROOTDIR/locale] - --mandir=DIR man documentation [DATAROOTDIR/man] - --docdir=DIR documentation root [DATAROOTDIR/doc/python] - --htmldir=DIR html documentation [DOCDIR] - --dvidir=DIR dvi documentation [DOCDIR] - --pdfdir=DIR pdf documentation [DOCDIR] - --psdir=DIR ps documentation [DOCDIR] + --bindir=DIR user executables [EPREFIX/bin] + --sbindir=DIR system admin executables [EPREFIX/sbin] + --libexecdir=DIR program executables [EPREFIX/libexec] + --sysconfdir=DIR read-only single-machine data [PREFIX/etc] + --sharedstatedir=DIR modifiable architecture-independent data [PREFIX/com] + --localstatedir=DIR modifiable single-machine data [PREFIX/var] + --libdir=DIR object code libraries [EPREFIX/lib] + --includedir=DIR C header files [PREFIX/include] + --oldincludedir=DIR C header files for non-gcc [/usr/include] + --datarootdir=DIR read-only arch.-independent data root [PREFIX/share] + --datadir=DIR read-only architecture-independent data [DATAROOTDIR] + --infodir=DIR info documentation [DATAROOTDIR/info] + --localedir=DIR locale-dependent data [DATAROOTDIR/locale] + --mandir=DIR man documentation [DATAROOTDIR/man] + --docdir=DIR documentation root [DATAROOTDIR/doc/python] + --htmldir=DIR html documentation [DOCDIR] + --dvidir=DIR dvi documentation [DOCDIR] + --pdfdir=DIR pdf documentation [DOCDIR] + --psdir=DIR ps documentation [DOCDIR] _ACEOF cat <<\_ACEOF @@ -1315,6 +1417,7 @@ cat <<\_ACEOF Optional Features: + --disable-option-checking ignore unrecognized --enable/--with options --disable-FEATURE do not include FEATURE (same as --enable-FEATURE=no) --enable-FEATURE[=ARG] include FEATURE [ARG=yes] --enable-universalsdk[=SDKDIR] @@ -1382,15 +1485,17 @@ if test "$ac_init_help" = "recursive"; then # If there are subdirs, report their specific --help. for ac_dir in : $ac_subdirs_all; do test "x$ac_dir" = x: && continue - test -d "$ac_dir" || continue + test -d "$ac_dir" || + { cd "$srcdir" && ac_pwd=`pwd` && srcdir=. && test -d "$ac_dir"; } || + continue ac_builddir=. case "$ac_dir" in .) ac_dir_suffix= ac_top_builddir_sub=. ac_top_build_prefix= ;; *) - ac_dir_suffix=/`echo "$ac_dir" | sed 's,^\.[\\/],,'` + ac_dir_suffix=/`$as_echo "$ac_dir" | sed 's|^\.[\\/]||'` # A ".." for each directory in $ac_dir_suffix. - ac_top_builddir_sub=`echo "$ac_dir_suffix" | sed 's,/[^\\/]*,/..,g;s,/,,'` + ac_top_builddir_sub=`$as_echo "$ac_dir_suffix" | sed 's|/[^\\/]*|/..|g;s|/||'` case $ac_top_builddir_sub in "") ac_top_builddir_sub=. ac_top_build_prefix= ;; *) ac_top_build_prefix=$ac_top_builddir_sub/ ;; @@ -1426,7 +1531,7 @@ echo && $SHELL "$ac_srcdir/configure" --help=recursive else - echo "$as_me: WARNING: no configuration information is in $ac_dir" >&2 + $as_echo "$as_me: WARNING: no configuration information is in $ac_dir" >&2 fi || ac_status=$? cd "$ac_pwd" || { ac_status=$?; break; } done @@ -1436,10 +1541,10 @@ if $ac_init_version; then cat <<\_ACEOF python configure 2.6 -generated by GNU Autoconf 2.61 +generated by GNU Autoconf 2.63 Copyright (C) 1992, 1993, 1994, 1995, 1996, 1998, 1999, 2000, 2001, -2002, 2003, 2004, 2005, 2006 Free Software Foundation, Inc. +2002, 2003, 2004, 2005, 2006, 2007, 2008 Free Software Foundation, Inc. This configure script is free software; the Free Software Foundation gives unlimited permission to copy, distribute and modify it. _ACEOF @@ -1450,7 +1555,7 @@ running configure, to aid debugging if configure makes a mistake. It was created by python $as_me 2.6, which was -generated by GNU Autoconf 2.61. Invocation command line was +generated by GNU Autoconf 2.63. Invocation command line was $ $0 $@ @@ -1486,7 +1591,7 @@ do IFS=$as_save_IFS test -z "$as_dir" && as_dir=. - echo "PATH: $as_dir" + $as_echo "PATH: $as_dir" done IFS=$as_save_IFS @@ -1521,7 +1626,7 @@ | -silent | --silent | --silen | --sile | --sil) continue ;; *\'*) - ac_arg=`echo "$ac_arg" | sed "s/'/'\\\\\\\\''/g"` ;; + ac_arg=`$as_echo "$ac_arg" | sed "s/'/'\\\\\\\\''/g"` ;; esac case $ac_pass in 1) ac_configure_args0="$ac_configure_args0 '$ac_arg'" ;; @@ -1573,11 +1678,12 @@ case $ac_val in #( *${as_nl}*) case $ac_var in #( - *_cv_*) { echo "$as_me:$LINENO: WARNING: Cache variable $ac_var contains a newline." >&5 -echo "$as_me: WARNING: Cache variable $ac_var contains a newline." >&2;} ;; + *_cv_*) { $as_echo "$as_me:$LINENO: WARNING: cache variable $ac_var contains a newline" >&5 +$as_echo "$as_me: WARNING: cache variable $ac_var contains a newline" >&2;} ;; esac case $ac_var in #( _ | IFS | as_nl) ;; #( + BASH_ARGV | BASH_SOURCE) eval $ac_var= ;; #( *) $as_unset $ac_var ;; esac ;; esac @@ -1607,9 +1713,9 @@ do eval ac_val=\$$ac_var case $ac_val in - *\'\''*) ac_val=`echo "$ac_val" | sed "s/'\''/'\''\\\\\\\\'\'''\''/g"`;; + *\'\''*) ac_val=`$as_echo "$ac_val" | sed "s/'\''/'\''\\\\\\\\'\'''\''/g"`;; esac - echo "$ac_var='\''$ac_val'\''" + $as_echo "$ac_var='\''$ac_val'\''" done | sort echo @@ -1624,9 +1730,9 @@ do eval ac_val=\$$ac_var case $ac_val in - *\'\''*) ac_val=`echo "$ac_val" | sed "s/'\''/'\''\\\\\\\\'\'''\''/g"`;; + *\'\''*) ac_val=`$as_echo "$ac_val" | sed "s/'\''/'\''\\\\\\\\'\'''\''/g"`;; esac - echo "$ac_var='\''$ac_val'\''" + $as_echo "$ac_var='\''$ac_val'\''" done | sort echo fi @@ -1642,8 +1748,8 @@ echo fi test "$ac_signal" != 0 && - echo "$as_me: caught signal $ac_signal" - echo "$as_me: exit $exit_status" + $as_echo "$as_me: caught signal $ac_signal" + $as_echo "$as_me: exit $exit_status" } >&5 rm -f core *.core core.conftest.* && rm -f -r conftest* confdefs* conf$$* $ac_clean_files && @@ -1685,21 +1791,24 @@ # Let the site file select an alternate cache file if it wants to. -# Prefer explicitly selected file to automatically selected ones. +# Prefer an explicitly selected file to automatically selected ones. +ac_site_file1=NONE +ac_site_file2=NONE if test -n "$CONFIG_SITE"; then - set x "$CONFIG_SITE" + ac_site_file1=$CONFIG_SITE elif test "x$prefix" != xNONE; then - set x "$prefix/share/config.site" "$prefix/etc/config.site" + ac_site_file1=$prefix/share/config.site + ac_site_file2=$prefix/etc/config.site else - set x "$ac_default_prefix/share/config.site" \ - "$ac_default_prefix/etc/config.site" + ac_site_file1=$ac_default_prefix/share/config.site + ac_site_file2=$ac_default_prefix/etc/config.site fi -shift -for ac_site_file +for ac_site_file in "$ac_site_file1" "$ac_site_file2" do + test "x$ac_site_file" = xNONE && continue if test -r "$ac_site_file"; then - { echo "$as_me:$LINENO: loading site script $ac_site_file" >&5 -echo "$as_me: loading site script $ac_site_file" >&6;} + { $as_echo "$as_me:$LINENO: loading site script $ac_site_file" >&5 +$as_echo "$as_me: loading site script $ac_site_file" >&6;} sed 's/^/| /' "$ac_site_file" >&5 . "$ac_site_file" fi @@ -1709,16 +1818,16 @@ # Some versions of bash will fail to source /dev/null (special # files actually), so we avoid doing that. if test -f "$cache_file"; then - { echo "$as_me:$LINENO: loading cache $cache_file" >&5 -echo "$as_me: loading cache $cache_file" >&6;} + { $as_echo "$as_me:$LINENO: loading cache $cache_file" >&5 +$as_echo "$as_me: loading cache $cache_file" >&6;} case $cache_file in [\\/]* | ?:[\\/]* ) . "$cache_file";; *) . "./$cache_file";; esac fi else - { echo "$as_me:$LINENO: creating cache $cache_file" >&5 -echo "$as_me: creating cache $cache_file" >&6;} + { $as_echo "$as_me:$LINENO: creating cache $cache_file" >&5 +$as_echo "$as_me: creating cache $cache_file" >&6;} >$cache_file fi @@ -1732,29 +1841,38 @@ eval ac_new_val=\$ac_env_${ac_var}_value case $ac_old_set,$ac_new_set in set,) - { echo "$as_me:$LINENO: error: \`$ac_var' was set to \`$ac_old_val' in the previous run" >&5 -echo "$as_me: error: \`$ac_var' was set to \`$ac_old_val' in the previous run" >&2;} + { $as_echo "$as_me:$LINENO: error: \`$ac_var' was set to \`$ac_old_val' in the previous run" >&5 +$as_echo "$as_me: error: \`$ac_var' was set to \`$ac_old_val' in the previous run" >&2;} ac_cache_corrupted=: ;; ,set) - { echo "$as_me:$LINENO: error: \`$ac_var' was not set in the previous run" >&5 -echo "$as_me: error: \`$ac_var' was not set in the previous run" >&2;} + { $as_echo "$as_me:$LINENO: error: \`$ac_var' was not set in the previous run" >&5 +$as_echo "$as_me: error: \`$ac_var' was not set in the previous run" >&2;} ac_cache_corrupted=: ;; ,);; *) if test "x$ac_old_val" != "x$ac_new_val"; then - { echo "$as_me:$LINENO: error: \`$ac_var' has changed since the previous run:" >&5 -echo "$as_me: error: \`$ac_var' has changed since the previous run:" >&2;} - { echo "$as_me:$LINENO: former value: $ac_old_val" >&5 -echo "$as_me: former value: $ac_old_val" >&2;} - { echo "$as_me:$LINENO: current value: $ac_new_val" >&5 -echo "$as_me: current value: $ac_new_val" >&2;} - ac_cache_corrupted=: + # differences in whitespace do not lead to failure. + ac_old_val_w=`echo x $ac_old_val` + ac_new_val_w=`echo x $ac_new_val` + if test "$ac_old_val_w" != "$ac_new_val_w"; then + { $as_echo "$as_me:$LINENO: error: \`$ac_var' has changed since the previous run:" >&5 +$as_echo "$as_me: error: \`$ac_var' has changed since the previous run:" >&2;} + ac_cache_corrupted=: + else + { $as_echo "$as_me:$LINENO: warning: ignoring whitespace changes in \`$ac_var' since the previous run:" >&5 +$as_echo "$as_me: warning: ignoring whitespace changes in \`$ac_var' since the previous run:" >&2;} + eval $ac_var=\$ac_old_val + fi + { $as_echo "$as_me:$LINENO: former value: \`$ac_old_val'" >&5 +$as_echo "$as_me: former value: \`$ac_old_val'" >&2;} + { $as_echo "$as_me:$LINENO: current value: \`$ac_new_val'" >&5 +$as_echo "$as_me: current value: \`$ac_new_val'" >&2;} fi;; esac # Pass precious variables to config.status. if test "$ac_new_set" = set; then case $ac_new_val in - *\'*) ac_arg=$ac_var=`echo "$ac_new_val" | sed "s/'/'\\\\\\\\''/g"` ;; + *\'*) ac_arg=$ac_var=`$as_echo "$ac_new_val" | sed "s/'/'\\\\\\\\''/g"` ;; *) ac_arg=$ac_var=$ac_new_val ;; esac case " $ac_configure_args " in @@ -1764,10 +1882,12 @@ fi done if $ac_cache_corrupted; then - { echo "$as_me:$LINENO: error: changes in the environment can compromise the build" >&5 -echo "$as_me: error: changes in the environment can compromise the build" >&2;} - { { echo "$as_me:$LINENO: error: run \`make distclean' and/or \`rm $cache_file' and start over" >&5 -echo "$as_me: error: run \`make distclean' and/or \`rm $cache_file' and start over" >&2;} + { $as_echo "$as_me:$LINENO: error: in \`$ac_pwd':" >&5 +$as_echo "$as_me: error: in \`$ac_pwd':" >&2;} + { $as_echo "$as_me:$LINENO: error: changes in the environment can compromise the build" >&5 +$as_echo "$as_me: error: changes in the environment can compromise the build" >&2;} + { { $as_echo "$as_me:$LINENO: error: run \`make distclean' and/or \`rm $cache_file' and start over" >&5 +$as_echo "$as_me: error: run \`make distclean' and/or \`rm $cache_file' and start over" >&2;} { (exit 1); exit 1; }; } fi @@ -1873,8 +1993,8 @@ CONFIG_ARGS="$ac_configure_args" -{ echo "$as_me:$LINENO: checking for --enable-universalsdk" >&5 -echo $ECHO_N "checking for --enable-universalsdk... $ECHO_C" >&6; } +{ $as_echo "$as_me:$LINENO: checking for --enable-universalsdk" >&5 +$as_echo_n "checking for --enable-universalsdk... " >&6; } # Check whether --enable-universalsdk was given. if test "${enable_universalsdk+set}" = set; then enableval=$enable_universalsdk; @@ -1896,8 +2016,8 @@ UNIVERSALSDK=$enableval if test ! -d "${UNIVERSALSDK}" then - { { echo "$as_me:$LINENO: error: --enable-universalsdk specifies non-existing SDK: ${UNIVERSALSDK}" >&5 -echo "$as_me: error: --enable-universalsdk specifies non-existing SDK: ${UNIVERSALSDK}" >&2;} + { { $as_echo "$as_me:$LINENO: error: --enable-universalsdk specifies non-existing SDK: ${UNIVERSALSDK}" >&5 +$as_echo "$as_me: error: --enable-universalsdk specifies non-existing SDK: ${UNIVERSALSDK}" >&2;} { (exit 1); exit 1; }; } fi ;; @@ -1913,11 +2033,11 @@ if test -n "${UNIVERSALSDK}" then - { echo "$as_me:$LINENO: result: ${UNIVERSALSDK}" >&5 -echo "${ECHO_T}${UNIVERSALSDK}" >&6; } + { $as_echo "$as_me:$LINENO: result: ${UNIVERSALSDK}" >&5 +$as_echo "${UNIVERSALSDK}" >&6; } else - { echo "$as_me:$LINENO: result: no" >&5 -echo "${ECHO_T}no" >&6; } + { $as_echo "$as_me:$LINENO: result: no" >&5 +$as_echo "no" >&6; } fi @@ -1926,27 +2046,27 @@ UNIVERSAL_ARCHS="32-bit" -{ echo "$as_me:$LINENO: checking for --with-universal-archs" >&5 -echo $ECHO_N "checking for --with-universal-archs... $ECHO_C" >&6; } +{ $as_echo "$as_me:$LINENO: checking for --with-universal-archs" >&5 +$as_echo_n "checking for --with-universal-archs... " >&6; } # Check whether --with-universal-archs was given. if test "${with_universal_archs+set}" = set; then withval=$with_universal_archs; - { echo "$as_me:$LINENO: result: $withval" >&5 -echo "${ECHO_T}$withval" >&6; } + { $as_echo "$as_me:$LINENO: result: $withval" >&5 +$as_echo "$withval" >&6; } UNIVERSAL_ARCHS="$withval" if test "${enable_universalsdk}" ; then : else - { { echo "$as_me:$LINENO: error: --with-universal-archs without --enable-universalsdk. See Mac/README" >&5 -echo "$as_me: error: --with-universal-archs without --enable-universalsdk. See Mac/README" >&2;} + { { $as_echo "$as_me:$LINENO: error: --with-universal-archs without --enable-universalsdk. See Mac/README" >&5 +$as_echo "$as_me: error: --with-universal-archs without --enable-universalsdk. See Mac/README" >&2;} { (exit 1); exit 1; }; } fi else - { echo "$as_me:$LINENO: result: 32-bit" >&5 -echo "${ECHO_T}32-bit" >&6; } + { $as_echo "$as_me:$LINENO: result: 32-bit" >&5 +$as_echo "32-bit" >&6; } fi @@ -1960,8 +2080,8 @@ if test "${enable_framework}"; then : else - { { echo "$as_me:$LINENO: error: --with-framework-name without --enable-framework. See Mac/README" >&5 -echo "$as_me: error: --with-framework-name without --enable-framework. See Mac/README" >&2;} + { { $as_echo "$as_me:$LINENO: error: --with-framework-name without --enable-framework. See Mac/README" >&5 +$as_echo "$as_me: error: --with-framework-name without --enable-framework. See Mac/README" >&2;} { (exit 1); exit 1; }; } fi PYTHONFRAMEWORK=${withval} @@ -2079,8 +2199,8 @@ ## # Set name for machine-dependent library files -{ echo "$as_me:$LINENO: checking MACHDEP" >&5 -echo $ECHO_N "checking MACHDEP... $ECHO_C" >&6; } +{ $as_echo "$as_me:$LINENO: checking MACHDEP" >&5 +$as_echo_n "checking MACHDEP... " >&6; } if test -z "$MACHDEP" then ac_sys_system=`uname -s` @@ -2257,14 +2377,14 @@ LDFLAGS="$SGI_ABI $LDFLAGS" MACHDEP=`echo "${MACHDEP}${SGI_ABI}" | sed 's/ *//g'` fi -{ echo "$as_me:$LINENO: result: $MACHDEP" >&5 -echo "${ECHO_T}$MACHDEP" >&6; } +{ $as_echo "$as_me:$LINENO: result: $MACHDEP" >&5 +$as_echo "$MACHDEP" >&6; } # And add extra plat-mac for darwin -{ echo "$as_me:$LINENO: checking EXTRAPLATDIR" >&5 -echo $ECHO_N "checking EXTRAPLATDIR... $ECHO_C" >&6; } +{ $as_echo "$as_me:$LINENO: checking EXTRAPLATDIR" >&5 +$as_echo_n "checking EXTRAPLATDIR... " >&6; } if test -z "$EXTRAPLATDIR" then case $MACHDEP in @@ -2278,8 +2398,8 @@ ;; esac fi -{ echo "$as_me:$LINENO: result: $EXTRAPLATDIR" >&5 -echo "${ECHO_T}$EXTRAPLATDIR" >&6; } +{ $as_echo "$as_me:$LINENO: result: $EXTRAPLATDIR" >&5 +$as_echo "$EXTRAPLATDIR" >&6; } # Record the configure-time value of MACOSX_DEPLOYMENT_TARGET, # it may influence the way we can build extensions, so distutils @@ -2289,11 +2409,11 @@ CONFIGURE_MACOSX_DEPLOYMENT_TARGET= EXPORT_MACOSX_DEPLOYMENT_TARGET='#' -{ echo "$as_me:$LINENO: checking machine type as reported by uname -m" >&5 -echo $ECHO_N "checking machine type as reported by uname -m... $ECHO_C" >&6; } +{ $as_echo "$as_me:$LINENO: checking machine type as reported by uname -m" >&5 +$as_echo_n "checking machine type as reported by uname -m... " >&6; } ac_sys_machine=`uname -m` -{ echo "$as_me:$LINENO: result: $ac_sys_machine" >&5 -echo "${ECHO_T}$ac_sys_machine" >&6; } +{ $as_echo "$as_me:$LINENO: result: $ac_sys_machine" >&5 +$as_echo "$ac_sys_machine" >&6; } # checks for alternative programs @@ -2305,8 +2425,8 @@ # XXX shouldn't some/most/all of this code be merged with the stuff later # on that fiddles with OPT and BASECFLAGS? -{ echo "$as_me:$LINENO: checking for --without-gcc" >&5 -echo $ECHO_N "checking for --without-gcc... $ECHO_C" >&6; } +{ $as_echo "$as_me:$LINENO: checking for --without-gcc" >&5 +$as_echo_n "checking for --without-gcc... " >&6; } # Check whether --with-gcc was given. if test "${with_gcc+set}" = set; then @@ -2339,8 +2459,8 @@ OPT="$OPT -O" ;; *) - { { echo "$as_me:$LINENO: error: Unknown BeOS platform \"$BE_HOST_CPU\"" >&5 -echo "$as_me: error: Unknown BeOS platform \"$BE_HOST_CPU\"" >&2;} + { { $as_echo "$as_me:$LINENO: error: Unknown BeOS platform \"$BE_HOST_CPU\"" >&5 +$as_echo "$as_me: error: Unknown BeOS platform \"$BE_HOST_CPU\"" >&2;} { (exit 1); exit 1; }; } ;; esac @@ -2354,15 +2474,15 @@ esac fi -{ echo "$as_me:$LINENO: result: $without_gcc" >&5 -echo "${ECHO_T}$without_gcc" >&6; } +{ $as_echo "$as_me:$LINENO: result: $without_gcc" >&5 +$as_echo "$without_gcc" >&6; } # If the user switches compilers, we can't believe the cache if test ! -z "$ac_cv_prog_CC" -a ! -z "$CC" -a "$CC" != "$ac_cv_prog_CC" then - { { echo "$as_me:$LINENO: error: cached CC is different -- throw away $cache_file + { { $as_echo "$as_me:$LINENO: error: cached CC is different -- throw away $cache_file (it is also a good idea to do 'make clean' before compiling)" >&5 -echo "$as_me: error: cached CC is different -- throw away $cache_file +$as_echo "$as_me: error: cached CC is different -- throw away $cache_file (it is also a good idea to do 'make clean' before compiling)" >&2;} { (exit 1); exit 1; }; } fi @@ -2375,10 +2495,10 @@ if test -n "$ac_tool_prefix"; then # Extract the first word of "${ac_tool_prefix}gcc", so it can be a program name with args. set dummy ${ac_tool_prefix}gcc; ac_word=$2 -{ echo "$as_me:$LINENO: checking for $ac_word" >&5 -echo $ECHO_N "checking for $ac_word... $ECHO_C" >&6; } +{ $as_echo "$as_me:$LINENO: checking for $ac_word" >&5 +$as_echo_n "checking for $ac_word... " >&6; } if test "${ac_cv_prog_CC+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 + $as_echo_n "(cached) " >&6 else if test -n "$CC"; then ac_cv_prog_CC="$CC" # Let the user override the test. @@ -2391,7 +2511,7 @@ for ac_exec_ext in '' $ac_executable_extensions; do if { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_test_x "$as_dir/$ac_word$ac_exec_ext"; }; then ac_cv_prog_CC="${ac_tool_prefix}gcc" - echo "$as_me:$LINENO: found $as_dir/$ac_word$ac_exec_ext" >&5 + $as_echo "$as_me:$LINENO: found $as_dir/$ac_word$ac_exec_ext" >&5 break 2 fi done @@ -2402,11 +2522,11 @@ fi CC=$ac_cv_prog_CC if test -n "$CC"; then - { echo "$as_me:$LINENO: result: $CC" >&5 -echo "${ECHO_T}$CC" >&6; } + { $as_echo "$as_me:$LINENO: result: $CC" >&5 +$as_echo "$CC" >&6; } else - { echo "$as_me:$LINENO: result: no" >&5 -echo "${ECHO_T}no" >&6; } + { $as_echo "$as_me:$LINENO: result: no" >&5 +$as_echo "no" >&6; } fi @@ -2415,10 +2535,10 @@ ac_ct_CC=$CC # Extract the first word of "gcc", so it can be a program name with args. set dummy gcc; ac_word=$2 -{ echo "$as_me:$LINENO: checking for $ac_word" >&5 -echo $ECHO_N "checking for $ac_word... $ECHO_C" >&6; } +{ $as_echo "$as_me:$LINENO: checking for $ac_word" >&5 +$as_echo_n "checking for $ac_word... " >&6; } if test "${ac_cv_prog_ac_ct_CC+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 + $as_echo_n "(cached) " >&6 else if test -n "$ac_ct_CC"; then ac_cv_prog_ac_ct_CC="$ac_ct_CC" # Let the user override the test. @@ -2431,7 +2551,7 @@ for ac_exec_ext in '' $ac_executable_extensions; do if { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_test_x "$as_dir/$ac_word$ac_exec_ext"; }; then ac_cv_prog_ac_ct_CC="gcc" - echo "$as_me:$LINENO: found $as_dir/$ac_word$ac_exec_ext" >&5 + $as_echo "$as_me:$LINENO: found $as_dir/$ac_word$ac_exec_ext" >&5 break 2 fi done @@ -2442,11 +2562,11 @@ fi ac_ct_CC=$ac_cv_prog_ac_ct_CC if test -n "$ac_ct_CC"; then - { echo "$as_me:$LINENO: result: $ac_ct_CC" >&5 -echo "${ECHO_T}$ac_ct_CC" >&6; } + { $as_echo "$as_me:$LINENO: result: $ac_ct_CC" >&5 +$as_echo "$ac_ct_CC" >&6; } else - { echo "$as_me:$LINENO: result: no" >&5 -echo "${ECHO_T}no" >&6; } + { $as_echo "$as_me:$LINENO: result: no" >&5 +$as_echo "no" >&6; } fi if test "x$ac_ct_CC" = x; then @@ -2454,12 +2574,8 @@ else case $cross_compiling:$ac_tool_warned in yes:) -{ echo "$as_me:$LINENO: WARNING: In the future, Autoconf will not detect cross-tools -whose name does not start with the host triplet. If you think this -configuration is useful to you, please write to autoconf at gnu.org." >&5 -echo "$as_me: WARNING: In the future, Autoconf will not detect cross-tools -whose name does not start with the host triplet. If you think this -configuration is useful to you, please write to autoconf at gnu.org." >&2;} +{ $as_echo "$as_me:$LINENO: WARNING: using cross tools not prefixed with host triplet" >&5 +$as_echo "$as_me: WARNING: using cross tools not prefixed with host triplet" >&2;} ac_tool_warned=yes ;; esac CC=$ac_ct_CC @@ -2472,10 +2588,10 @@ if test -n "$ac_tool_prefix"; then # Extract the first word of "${ac_tool_prefix}cc", so it can be a program name with args. set dummy ${ac_tool_prefix}cc; ac_word=$2 -{ echo "$as_me:$LINENO: checking for $ac_word" >&5 -echo $ECHO_N "checking for $ac_word... $ECHO_C" >&6; } +{ $as_echo "$as_me:$LINENO: checking for $ac_word" >&5 +$as_echo_n "checking for $ac_word... " >&6; } if test "${ac_cv_prog_CC+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 + $as_echo_n "(cached) " >&6 else if test -n "$CC"; then ac_cv_prog_CC="$CC" # Let the user override the test. @@ -2488,7 +2604,7 @@ for ac_exec_ext in '' $ac_executable_extensions; do if { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_test_x "$as_dir/$ac_word$ac_exec_ext"; }; then ac_cv_prog_CC="${ac_tool_prefix}cc" - echo "$as_me:$LINENO: found $as_dir/$ac_word$ac_exec_ext" >&5 + $as_echo "$as_me:$LINENO: found $as_dir/$ac_word$ac_exec_ext" >&5 break 2 fi done @@ -2499,11 +2615,11 @@ fi CC=$ac_cv_prog_CC if test -n "$CC"; then - { echo "$as_me:$LINENO: result: $CC" >&5 -echo "${ECHO_T}$CC" >&6; } + { $as_echo "$as_me:$LINENO: result: $CC" >&5 +$as_echo "$CC" >&6; } else - { echo "$as_me:$LINENO: result: no" >&5 -echo "${ECHO_T}no" >&6; } + { $as_echo "$as_me:$LINENO: result: no" >&5 +$as_echo "no" >&6; } fi @@ -2512,10 +2628,10 @@ if test -z "$CC"; then # Extract the first word of "cc", so it can be a program name with args. set dummy cc; ac_word=$2 -{ echo "$as_me:$LINENO: checking for $ac_word" >&5 -echo $ECHO_N "checking for $ac_word... $ECHO_C" >&6; } +{ $as_echo "$as_me:$LINENO: checking for $ac_word" >&5 +$as_echo_n "checking for $ac_word... " >&6; } if test "${ac_cv_prog_CC+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 + $as_echo_n "(cached) " >&6 else if test -n "$CC"; then ac_cv_prog_CC="$CC" # Let the user override the test. @@ -2533,7 +2649,7 @@ continue fi ac_cv_prog_CC="cc" - echo "$as_me:$LINENO: found $as_dir/$ac_word$ac_exec_ext" >&5 + $as_echo "$as_me:$LINENO: found $as_dir/$ac_word$ac_exec_ext" >&5 break 2 fi done @@ -2556,11 +2672,11 @@ fi CC=$ac_cv_prog_CC if test -n "$CC"; then - { echo "$as_me:$LINENO: result: $CC" >&5 -echo "${ECHO_T}$CC" >&6; } + { $as_echo "$as_me:$LINENO: result: $CC" >&5 +$as_echo "$CC" >&6; } else - { echo "$as_me:$LINENO: result: no" >&5 -echo "${ECHO_T}no" >&6; } + { $as_echo "$as_me:$LINENO: result: no" >&5 +$as_echo "no" >&6; } fi @@ -2571,10 +2687,10 @@ do # Extract the first word of "$ac_tool_prefix$ac_prog", so it can be a program name with args. set dummy $ac_tool_prefix$ac_prog; ac_word=$2 -{ echo "$as_me:$LINENO: checking for $ac_word" >&5 -echo $ECHO_N "checking for $ac_word... $ECHO_C" >&6; } +{ $as_echo "$as_me:$LINENO: checking for $ac_word" >&5 +$as_echo_n "checking for $ac_word... " >&6; } if test "${ac_cv_prog_CC+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 + $as_echo_n "(cached) " >&6 else if test -n "$CC"; then ac_cv_prog_CC="$CC" # Let the user override the test. @@ -2587,7 +2703,7 @@ for ac_exec_ext in '' $ac_executable_extensions; do if { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_test_x "$as_dir/$ac_word$ac_exec_ext"; }; then ac_cv_prog_CC="$ac_tool_prefix$ac_prog" - echo "$as_me:$LINENO: found $as_dir/$ac_word$ac_exec_ext" >&5 + $as_echo "$as_me:$LINENO: found $as_dir/$ac_word$ac_exec_ext" >&5 break 2 fi done @@ -2598,11 +2714,11 @@ fi CC=$ac_cv_prog_CC if test -n "$CC"; then - { echo "$as_me:$LINENO: result: $CC" >&5 -echo "${ECHO_T}$CC" >&6; } + { $as_echo "$as_me:$LINENO: result: $CC" >&5 +$as_echo "$CC" >&6; } else - { echo "$as_me:$LINENO: result: no" >&5 -echo "${ECHO_T}no" >&6; } + { $as_echo "$as_me:$LINENO: result: no" >&5 +$as_echo "no" >&6; } fi @@ -2615,10 +2731,10 @@ do # Extract the first word of "$ac_prog", so it can be a program name with args. set dummy $ac_prog; ac_word=$2 -{ echo "$as_me:$LINENO: checking for $ac_word" >&5 -echo $ECHO_N "checking for $ac_word... $ECHO_C" >&6; } +{ $as_echo "$as_me:$LINENO: checking for $ac_word" >&5 +$as_echo_n "checking for $ac_word... " >&6; } if test "${ac_cv_prog_ac_ct_CC+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 + $as_echo_n "(cached) " >&6 else if test -n "$ac_ct_CC"; then ac_cv_prog_ac_ct_CC="$ac_ct_CC" # Let the user override the test. @@ -2631,7 +2747,7 @@ for ac_exec_ext in '' $ac_executable_extensions; do if { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_test_x "$as_dir/$ac_word$ac_exec_ext"; }; then ac_cv_prog_ac_ct_CC="$ac_prog" - echo "$as_me:$LINENO: found $as_dir/$ac_word$ac_exec_ext" >&5 + $as_echo "$as_me:$LINENO: found $as_dir/$ac_word$ac_exec_ext" >&5 break 2 fi done @@ -2642,11 +2758,11 @@ fi ac_ct_CC=$ac_cv_prog_ac_ct_CC if test -n "$ac_ct_CC"; then - { echo "$as_me:$LINENO: result: $ac_ct_CC" >&5 -echo "${ECHO_T}$ac_ct_CC" >&6; } + { $as_echo "$as_me:$LINENO: result: $ac_ct_CC" >&5 +$as_echo "$ac_ct_CC" >&6; } else - { echo "$as_me:$LINENO: result: no" >&5 -echo "${ECHO_T}no" >&6; } + { $as_echo "$as_me:$LINENO: result: no" >&5 +$as_echo "no" >&6; } fi @@ -2658,12 +2774,8 @@ else case $cross_compiling:$ac_tool_warned in yes:) -{ echo "$as_me:$LINENO: WARNING: In the future, Autoconf will not detect cross-tools -whose name does not start with the host triplet. If you think this -configuration is useful to you, please write to autoconf at gnu.org." >&5 -echo "$as_me: WARNING: In the future, Autoconf will not detect cross-tools -whose name does not start with the host triplet. If you think this -configuration is useful to you, please write to autoconf at gnu.org." >&2;} +{ $as_echo "$as_me:$LINENO: WARNING: using cross tools not prefixed with host triplet" >&5 +$as_echo "$as_me: WARNING: using cross tools not prefixed with host triplet" >&2;} ac_tool_warned=yes ;; esac CC=$ac_ct_CC @@ -2673,44 +2785,50 @@ fi -test -z "$CC" && { { echo "$as_me:$LINENO: error: no acceptable C compiler found in \$PATH +test -z "$CC" && { { $as_echo "$as_me:$LINENO: error: in \`$ac_pwd':" >&5 +$as_echo "$as_me: error: in \`$ac_pwd':" >&2;} +{ { $as_echo "$as_me:$LINENO: error: no acceptable C compiler found in \$PATH See \`config.log' for more details." >&5 -echo "$as_me: error: no acceptable C compiler found in \$PATH +$as_echo "$as_me: error: no acceptable C compiler found in \$PATH See \`config.log' for more details." >&2;} - { (exit 1); exit 1; }; } + { (exit 1); exit 1; }; }; } # Provide some information about the compiler. -echo "$as_me:$LINENO: checking for C compiler version" >&5 -ac_compiler=`set X $ac_compile; echo $2` +$as_echo "$as_me:$LINENO: checking for C compiler version" >&5 +set X $ac_compile +ac_compiler=$2 { (ac_try="$ac_compiler --version >&5" case "(($ac_try" in *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_compiler --version >&5") 2>&5 ac_status=$? - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } { (ac_try="$ac_compiler -v >&5" case "(($ac_try" in *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_compiler -v >&5") 2>&5 ac_status=$? - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } { (ac_try="$ac_compiler -V >&5" case "(($ac_try" in *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_compiler -V >&5") 2>&5 ac_status=$? - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } cat >conftest.$ac_ext <<_ACEOF @@ -2729,27 +2847,22 @@ } _ACEOF ac_clean_files_save=$ac_clean_files -ac_clean_files="$ac_clean_files a.out a.exe b.out" +ac_clean_files="$ac_clean_files a.out a.out.dSYM a.exe b.out" # Try to create an executable without -o first, disregard a.out. # It will help us diagnose broken compilers, and finding out an intuition # of exeext. -{ echo "$as_me:$LINENO: checking for C compiler default output file name" >&5 -echo $ECHO_N "checking for C compiler default output file name... $ECHO_C" >&6; } -ac_link_default=`echo "$ac_link" | sed 's/ -o *conftest[^ ]*//'` -# -# List of possible output files, starting from the most likely. -# The algorithm is not robust to junk in `.', hence go to wildcards (a.*) -# only as a last resort. b.out is created by i960 compilers. -ac_files='a_out.exe a.exe conftest.exe a.out conftest a.* conftest.* b.out' -# -# The IRIX 6 linker writes into existing files which may not be -# executable, retaining their permissions. Remove them first so a -# subsequent execution test works. +{ $as_echo "$as_me:$LINENO: checking for C compiler default output file name" >&5 +$as_echo_n "checking for C compiler default output file name... " >&6; } +ac_link_default=`$as_echo "$ac_link" | sed 's/ -o *conftest[^ ]*//'` + +# The possible output files: +ac_files="a.out conftest.exe conftest a.exe a_out.exe b.out conftest.*" + ac_rmfiles= for ac_file in $ac_files do case $ac_file in - *.$ac_ext | *.xcoff | *.tds | *.d | *.pdb | *.xSYM | *.bb | *.bbg | *.map | *.inf | *.o | *.obj ) ;; + *.$ac_ext | *.xcoff | *.tds | *.d | *.pdb | *.xSYM | *.bb | *.bbg | *.map | *.inf | *.dSYM | *.o | *.obj ) ;; * ) ac_rmfiles="$ac_rmfiles $ac_file";; esac done @@ -2760,10 +2873,11 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_link_default") 2>&5 ac_status=$? - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); }; then # Autoconf-2.13 could set the ac_cv_exeext variable to `no'. # So ignore a value of `no', otherwise this would lead to `EXEEXT = no' @@ -2774,7 +2888,7 @@ do test -f "$ac_file" || continue case $ac_file in - *.$ac_ext | *.xcoff | *.tds | *.d | *.pdb | *.xSYM | *.bb | *.bbg | *.map | *.inf | *.o | *.obj ) + *.$ac_ext | *.xcoff | *.tds | *.d | *.pdb | *.xSYM | *.bb | *.bbg | *.map | *.inf | *.dSYM | *.o | *.obj ) ;; [ab].out ) # We found the default executable, but exeext='' is most @@ -2801,25 +2915,27 @@ ac_file='' fi -{ echo "$as_me:$LINENO: result: $ac_file" >&5 -echo "${ECHO_T}$ac_file" >&6; } +{ $as_echo "$as_me:$LINENO: result: $ac_file" >&5 +$as_echo "$ac_file" >&6; } if test -z "$ac_file"; then - echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 -{ { echo "$as_me:$LINENO: error: C compiler cannot create executables +{ { $as_echo "$as_me:$LINENO: error: in \`$ac_pwd':" >&5 +$as_echo "$as_me: error: in \`$ac_pwd':" >&2;} +{ { $as_echo "$as_me:$LINENO: error: C compiler cannot create executables See \`config.log' for more details." >&5 -echo "$as_me: error: C compiler cannot create executables +$as_echo "$as_me: error: C compiler cannot create executables See \`config.log' for more details." >&2;} - { (exit 77); exit 77; }; } + { (exit 77); exit 77; }; }; } fi ac_exeext=$ac_cv_exeext # Check that the compiler produces executables we can run. If not, either # the compiler is broken, or we cross compile. -{ echo "$as_me:$LINENO: checking whether the C compiler works" >&5 -echo $ECHO_N "checking whether the C compiler works... $ECHO_C" >&6; } +{ $as_echo "$as_me:$LINENO: checking whether the C compiler works" >&5 +$as_echo_n "checking whether the C compiler works... " >&6; } # FIXME: These cross compiler hacks should be removed for Autoconf 3.0 # If not cross compiling, check that we can run a simple program. if test "$cross_compiling" != yes; then @@ -2828,49 +2944,53 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_try") 2>&5 ac_status=$? - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); }; }; then cross_compiling=no else if test "$cross_compiling" = maybe; then cross_compiling=yes else - { { echo "$as_me:$LINENO: error: cannot run C compiled programs. + { { $as_echo "$as_me:$LINENO: error: in \`$ac_pwd':" >&5 +$as_echo "$as_me: error: in \`$ac_pwd':" >&2;} +{ { $as_echo "$as_me:$LINENO: error: cannot run C compiled programs. If you meant to cross compile, use \`--host'. See \`config.log' for more details." >&5 -echo "$as_me: error: cannot run C compiled programs. +$as_echo "$as_me: error: cannot run C compiled programs. If you meant to cross compile, use \`--host'. See \`config.log' for more details." >&2;} - { (exit 1); exit 1; }; } + { (exit 1); exit 1; }; }; } fi fi fi -{ echo "$as_me:$LINENO: result: yes" >&5 -echo "${ECHO_T}yes" >&6; } +{ $as_echo "$as_me:$LINENO: result: yes" >&5 +$as_echo "yes" >&6; } -rm -f a.out a.exe conftest$ac_cv_exeext b.out +rm -f -r a.out a.out.dSYM a.exe conftest$ac_cv_exeext b.out ac_clean_files=$ac_clean_files_save # Check that the compiler produces executables we can run. If not, either # the compiler is broken, or we cross compile. -{ echo "$as_me:$LINENO: checking whether we are cross compiling" >&5 -echo $ECHO_N "checking whether we are cross compiling... $ECHO_C" >&6; } -{ echo "$as_me:$LINENO: result: $cross_compiling" >&5 -echo "${ECHO_T}$cross_compiling" >&6; } +{ $as_echo "$as_me:$LINENO: checking whether we are cross compiling" >&5 +$as_echo_n "checking whether we are cross compiling... " >&6; } +{ $as_echo "$as_me:$LINENO: result: $cross_compiling" >&5 +$as_echo "$cross_compiling" >&6; } -{ echo "$as_me:$LINENO: checking for suffix of executables" >&5 -echo $ECHO_N "checking for suffix of executables... $ECHO_C" >&6; } +{ $as_echo "$as_me:$LINENO: checking for suffix of executables" >&5 +$as_echo_n "checking for suffix of executables... " >&6; } if { (ac_try="$ac_link" case "(($ac_try" in *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_link") 2>&5 ac_status=$? - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); }; then # If both `conftest.exe' and `conftest' are `present' (well, observable) # catch `conftest.exe'. For instance with Cygwin, `ls conftest' will @@ -2879,31 +2999,33 @@ for ac_file in conftest.exe conftest conftest.*; do test -f "$ac_file" || continue case $ac_file in - *.$ac_ext | *.xcoff | *.tds | *.d | *.pdb | *.xSYM | *.bb | *.bbg | *.map | *.inf | *.o | *.obj ) ;; + *.$ac_ext | *.xcoff | *.tds | *.d | *.pdb | *.xSYM | *.bb | *.bbg | *.map | *.inf | *.dSYM | *.o | *.obj ) ;; *.* ) ac_cv_exeext=`expr "$ac_file" : '[^.]*\(\..*\)'` break;; * ) break;; esac done else - { { echo "$as_me:$LINENO: error: cannot compute suffix of executables: cannot compile and link + { { $as_echo "$as_me:$LINENO: error: in \`$ac_pwd':" >&5 +$as_echo "$as_me: error: in \`$ac_pwd':" >&2;} +{ { $as_echo "$as_me:$LINENO: error: cannot compute suffix of executables: cannot compile and link See \`config.log' for more details." >&5 -echo "$as_me: error: cannot compute suffix of executables: cannot compile and link +$as_echo "$as_me: error: cannot compute suffix of executables: cannot compile and link See \`config.log' for more details." >&2;} - { (exit 1); exit 1; }; } + { (exit 1); exit 1; }; }; } fi rm -f conftest$ac_cv_exeext -{ echo "$as_me:$LINENO: result: $ac_cv_exeext" >&5 -echo "${ECHO_T}$ac_cv_exeext" >&6; } +{ $as_echo "$as_me:$LINENO: result: $ac_cv_exeext" >&5 +$as_echo "$ac_cv_exeext" >&6; } rm -f conftest.$ac_ext EXEEXT=$ac_cv_exeext ac_exeext=$EXEEXT -{ echo "$as_me:$LINENO: checking for suffix of object files" >&5 -echo $ECHO_N "checking for suffix of object files... $ECHO_C" >&6; } +{ $as_echo "$as_me:$LINENO: checking for suffix of object files" >&5 +$as_echo_n "checking for suffix of object files... " >&6; } if test "${ac_cv_objext+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 + $as_echo_n "(cached) " >&6 else cat >conftest.$ac_ext <<_ACEOF /* confdefs.h. */ @@ -2926,40 +3048,43 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_compile") 2>&5 ac_status=$? - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); }; then for ac_file in conftest.o conftest.obj conftest.*; do test -f "$ac_file" || continue; case $ac_file in - *.$ac_ext | *.xcoff | *.tds | *.d | *.pdb | *.xSYM | *.bb | *.bbg | *.map | *.inf ) ;; + *.$ac_ext | *.xcoff | *.tds | *.d | *.pdb | *.xSYM | *.bb | *.bbg | *.map | *.inf | *.dSYM ) ;; *) ac_cv_objext=`expr "$ac_file" : '.*\.\(.*\)'` break;; esac done else - echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 -{ { echo "$as_me:$LINENO: error: cannot compute suffix of object files: cannot compile +{ { $as_echo "$as_me:$LINENO: error: in \`$ac_pwd':" >&5 +$as_echo "$as_me: error: in \`$ac_pwd':" >&2;} +{ { $as_echo "$as_me:$LINENO: error: cannot compute suffix of object files: cannot compile See \`config.log' for more details." >&5 -echo "$as_me: error: cannot compute suffix of object files: cannot compile +$as_echo "$as_me: error: cannot compute suffix of object files: cannot compile See \`config.log' for more details." >&2;} - { (exit 1); exit 1; }; } + { (exit 1); exit 1; }; }; } fi rm -f conftest.$ac_cv_objext conftest.$ac_ext fi -{ echo "$as_me:$LINENO: result: $ac_cv_objext" >&5 -echo "${ECHO_T}$ac_cv_objext" >&6; } +{ $as_echo "$as_me:$LINENO: result: $ac_cv_objext" >&5 +$as_echo "$ac_cv_objext" >&6; } OBJEXT=$ac_cv_objext ac_objext=$OBJEXT -{ echo "$as_me:$LINENO: checking whether we are using the GNU C compiler" >&5 -echo $ECHO_N "checking whether we are using the GNU C compiler... $ECHO_C" >&6; } +{ $as_echo "$as_me:$LINENO: checking whether we are using the GNU C compiler" >&5 +$as_echo_n "checking whether we are using the GNU C compiler... " >&6; } if test "${ac_cv_c_compiler_gnu+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 + $as_echo_n "(cached) " >&6 else cat >conftest.$ac_ext <<_ACEOF /* confdefs.h. */ @@ -2985,20 +3110,21 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_compile") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { test -z "$ac_c_werror_flag" || test ! -s conftest.err } && test -s conftest.$ac_objext; then ac_compiler_gnu=yes else - echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 ac_compiler_gnu=no @@ -3008,15 +3134,19 @@ ac_cv_c_compiler_gnu=$ac_compiler_gnu fi -{ echo "$as_me:$LINENO: result: $ac_cv_c_compiler_gnu" >&5 -echo "${ECHO_T}$ac_cv_c_compiler_gnu" >&6; } -GCC=`test $ac_compiler_gnu = yes && echo yes` +{ $as_echo "$as_me:$LINENO: result: $ac_cv_c_compiler_gnu" >&5 +$as_echo "$ac_cv_c_compiler_gnu" >&6; } +if test $ac_compiler_gnu = yes; then + GCC=yes +else + GCC= +fi ac_test_CFLAGS=${CFLAGS+set} ac_save_CFLAGS=$CFLAGS -{ echo "$as_me:$LINENO: checking whether $CC accepts -g" >&5 -echo $ECHO_N "checking whether $CC accepts -g... $ECHO_C" >&6; } +{ $as_echo "$as_me:$LINENO: checking whether $CC accepts -g" >&5 +$as_echo_n "checking whether $CC accepts -g... " >&6; } if test "${ac_cv_prog_cc_g+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 + $as_echo_n "(cached) " >&6 else ac_save_c_werror_flag=$ac_c_werror_flag ac_c_werror_flag=yes @@ -3043,20 +3173,21 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_compile") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { test -z "$ac_c_werror_flag" || test ! -s conftest.err } && test -s conftest.$ac_objext; then ac_cv_prog_cc_g=yes else - echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 CFLAGS="" @@ -3081,20 +3212,21 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_compile") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { test -z "$ac_c_werror_flag" || test ! -s conftest.err } && test -s conftest.$ac_objext; then : else - echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 ac_c_werror_flag=$ac_save_c_werror_flag @@ -3120,20 +3252,21 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_compile") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { test -z "$ac_c_werror_flag" || test ! -s conftest.err } && test -s conftest.$ac_objext; then ac_cv_prog_cc_g=yes else - echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 @@ -3148,8 +3281,8 @@ rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext ac_c_werror_flag=$ac_save_c_werror_flag fi -{ echo "$as_me:$LINENO: result: $ac_cv_prog_cc_g" >&5 -echo "${ECHO_T}$ac_cv_prog_cc_g" >&6; } +{ $as_echo "$as_me:$LINENO: result: $ac_cv_prog_cc_g" >&5 +$as_echo "$ac_cv_prog_cc_g" >&6; } if test "$ac_test_CFLAGS" = set; then CFLAGS=$ac_save_CFLAGS elif test $ac_cv_prog_cc_g = yes; then @@ -3165,10 +3298,10 @@ CFLAGS= fi fi -{ echo "$as_me:$LINENO: checking for $CC option to accept ISO C89" >&5 -echo $ECHO_N "checking for $CC option to accept ISO C89... $ECHO_C" >&6; } +{ $as_echo "$as_me:$LINENO: checking for $CC option to accept ISO C89" >&5 +$as_echo_n "checking for $CC option to accept ISO C89... " >&6; } if test "${ac_cv_prog_cc_c89+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 + $as_echo_n "(cached) " >&6 else ac_cv_prog_cc_c89=no ac_save_CC=$CC @@ -3239,20 +3372,21 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_compile") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { test -z "$ac_c_werror_flag" || test ! -s conftest.err } && test -s conftest.$ac_objext; then ac_cv_prog_cc_c89=$ac_arg else - echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 @@ -3268,15 +3402,15 @@ # AC_CACHE_VAL case "x$ac_cv_prog_cc_c89" in x) - { echo "$as_me:$LINENO: result: none needed" >&5 -echo "${ECHO_T}none needed" >&6; } ;; + { $as_echo "$as_me:$LINENO: result: none needed" >&5 +$as_echo "none needed" >&6; } ;; xno) - { echo "$as_me:$LINENO: result: unsupported" >&5 -echo "${ECHO_T}unsupported" >&6; } ;; + { $as_echo "$as_me:$LINENO: result: unsupported" >&5 +$as_echo "unsupported" >&6; } ;; *) CC="$CC $ac_cv_prog_cc_c89" - { echo "$as_me:$LINENO: result: $ac_cv_prog_cc_c89" >&5 -echo "${ECHO_T}$ac_cv_prog_cc_c89" >&6; } ;; + { $as_echo "$as_me:$LINENO: result: $ac_cv_prog_cc_c89" >&5 +$as_echo "$ac_cv_prog_cc_c89" >&6; } ;; esac @@ -3289,8 +3423,8 @@ -{ echo "$as_me:$LINENO: checking for --with-cxx-main=" >&5 -echo $ECHO_N "checking for --with-cxx-main=... $ECHO_C" >&6; } +{ $as_echo "$as_me:$LINENO: checking for --with-cxx-main=" >&5 +$as_echo_n "checking for --with-cxx-main=... " >&6; } # Check whether --with-cxx_main was given. if test "${with_cxx_main+set}" = set; then @@ -3315,8 +3449,8 @@ fi -{ echo "$as_me:$LINENO: result: $with_cxx_main" >&5 -echo "${ECHO_T}$with_cxx_main" >&6; } +{ $as_echo "$as_me:$LINENO: result: $with_cxx_main" >&5 +$as_echo "$with_cxx_main" >&6; } preset_cxx="$CXX" if test -z "$CXX" @@ -3324,10 +3458,10 @@ case "$CC" in gcc) # Extract the first word of "g++", so it can be a program name with args. set dummy g++; ac_word=$2 -{ echo "$as_me:$LINENO: checking for $ac_word" >&5 -echo $ECHO_N "checking for $ac_word... $ECHO_C" >&6; } +{ $as_echo "$as_me:$LINENO: checking for $ac_word" >&5 +$as_echo_n "checking for $ac_word... " >&6; } if test "${ac_cv_path_CXX+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 + $as_echo_n "(cached) " >&6 else case $CXX in [\\/]* | ?:[\\/]*) @@ -3342,7 +3476,7 @@ for ac_exec_ext in '' $ac_executable_extensions; do if { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_test_x "$as_dir/$ac_word$ac_exec_ext"; }; then ac_cv_path_CXX="$as_dir/$ac_word$ac_exec_ext" - echo "$as_me:$LINENO: found $as_dir/$ac_word$ac_exec_ext" >&5 + $as_echo "$as_me:$LINENO: found $as_dir/$ac_word$ac_exec_ext" >&5 break 2 fi done @@ -3355,20 +3489,20 @@ fi CXX=$ac_cv_path_CXX if test -n "$CXX"; then - { echo "$as_me:$LINENO: result: $CXX" >&5 -echo "${ECHO_T}$CXX" >&6; } + { $as_echo "$as_me:$LINENO: result: $CXX" >&5 +$as_echo "$CXX" >&6; } else - { echo "$as_me:$LINENO: result: no" >&5 -echo "${ECHO_T}no" >&6; } + { $as_echo "$as_me:$LINENO: result: no" >&5 +$as_echo "no" >&6; } fi ;; cc) # Extract the first word of "c++", so it can be a program name with args. set dummy c++; ac_word=$2 -{ echo "$as_me:$LINENO: checking for $ac_word" >&5 -echo $ECHO_N "checking for $ac_word... $ECHO_C" >&6; } +{ $as_echo "$as_me:$LINENO: checking for $ac_word" >&5 +$as_echo_n "checking for $ac_word... " >&6; } if test "${ac_cv_path_CXX+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 + $as_echo_n "(cached) " >&6 else case $CXX in [\\/]* | ?:[\\/]*) @@ -3383,7 +3517,7 @@ for ac_exec_ext in '' $ac_executable_extensions; do if { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_test_x "$as_dir/$ac_word$ac_exec_ext"; }; then ac_cv_path_CXX="$as_dir/$ac_word$ac_exec_ext" - echo "$as_me:$LINENO: found $as_dir/$ac_word$ac_exec_ext" >&5 + $as_echo "$as_me:$LINENO: found $as_dir/$ac_word$ac_exec_ext" >&5 break 2 fi done @@ -3396,11 +3530,11 @@ fi CXX=$ac_cv_path_CXX if test -n "$CXX"; then - { echo "$as_me:$LINENO: result: $CXX" >&5 -echo "${ECHO_T}$CXX" >&6; } + { $as_echo "$as_me:$LINENO: result: $CXX" >&5 +$as_echo "$CXX" >&6; } else - { echo "$as_me:$LINENO: result: no" >&5 -echo "${ECHO_T}no" >&6; } + { $as_echo "$as_me:$LINENO: result: no" >&5 +$as_echo "no" >&6; } fi ;; @@ -3416,10 +3550,10 @@ do # Extract the first word of "$ac_prog", so it can be a program name with args. set dummy $ac_prog; ac_word=$2 -{ echo "$as_me:$LINENO: checking for $ac_word" >&5 -echo $ECHO_N "checking for $ac_word... $ECHO_C" >&6; } +{ $as_echo "$as_me:$LINENO: checking for $ac_word" >&5 +$as_echo_n "checking for $ac_word... " >&6; } if test "${ac_cv_prog_CXX+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 + $as_echo_n "(cached) " >&6 else if test -n "$CXX"; then ac_cv_prog_CXX="$CXX" # Let the user override the test. @@ -3432,7 +3566,7 @@ for ac_exec_ext in '' $ac_executable_extensions; do if { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_test_x "$as_dir/$ac_word$ac_exec_ext"; }; then ac_cv_prog_CXX="$ac_prog" - echo "$as_me:$LINENO: found $as_dir/$ac_word$ac_exec_ext" >&5 + $as_echo "$as_me:$LINENO: found $as_dir/$ac_word$ac_exec_ext" >&5 break 2 fi done @@ -3443,11 +3577,11 @@ fi CXX=$ac_cv_prog_CXX if test -n "$CXX"; then - { echo "$as_me:$LINENO: result: $CXX" >&5 -echo "${ECHO_T}$CXX" >&6; } + { $as_echo "$as_me:$LINENO: result: $CXX" >&5 +$as_echo "$CXX" >&6; } else - { echo "$as_me:$LINENO: result: no" >&5 -echo "${ECHO_T}no" >&6; } + { $as_echo "$as_me:$LINENO: result: no" >&5 +$as_echo "no" >&6; } fi @@ -3462,12 +3596,12 @@ fi if test "$preset_cxx" != "$CXX" then - { echo "$as_me:$LINENO: WARNING: + { $as_echo "$as_me:$LINENO: WARNING: By default, distutils will build C++ extension modules with \"$CXX\". If this is not intended, then set CXX on the configure command line. " >&5 -echo "$as_me: WARNING: +$as_echo "$as_me: WARNING: By default, distutils will build C++ extension modules with \"$CXX\". If this is not intended, then set CXX on the configure command line. @@ -3482,15 +3616,15 @@ ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5' ac_link='$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5' ac_compiler_gnu=$ac_cv_c_compiler_gnu -{ echo "$as_me:$LINENO: checking how to run the C preprocessor" >&5 -echo $ECHO_N "checking how to run the C preprocessor... $ECHO_C" >&6; } +{ $as_echo "$as_me:$LINENO: checking how to run the C preprocessor" >&5 +$as_echo_n "checking how to run the C preprocessor... " >&6; } # On Suns, sometimes $CPP names a directory. if test -n "$CPP" && test -d "$CPP"; then CPP= fi if test -z "$CPP"; then if test "${ac_cv_prog_CPP+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 + $as_echo_n "(cached) " >&6 else # Double quotes because CPP needs to be expanded for CPP in "$CC -E" "$CC -E -traditional-cpp" "/lib/cpp" @@ -3522,20 +3656,21 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_cpp conftest.$ac_ext") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } >/dev/null && { test -z "$ac_c_preproc_warn_flag$ac_c_werror_flag" || test ! -s conftest.err }; then : else - echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 # Broken: fails on valid input. @@ -3559,13 +3694,14 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_cpp conftest.$ac_ext") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } >/dev/null && { test -z "$ac_c_preproc_warn_flag$ac_c_werror_flag" || test ! -s conftest.err @@ -3573,7 +3709,7 @@ # Broken: success on invalid input. continue else - echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 # Passes both tests. @@ -3598,8 +3734,8 @@ else ac_cv_prog_CPP=$CPP fi -{ echo "$as_me:$LINENO: result: $CPP" >&5 -echo "${ECHO_T}$CPP" >&6; } +{ $as_echo "$as_me:$LINENO: result: $CPP" >&5 +$as_echo "$CPP" >&6; } ac_preproc_ok=false for ac_c_preproc_warn_flag in '' yes do @@ -3627,20 +3763,21 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_cpp conftest.$ac_ext") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } >/dev/null && { test -z "$ac_c_preproc_warn_flag$ac_c_werror_flag" || test ! -s conftest.err }; then : else - echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 # Broken: fails on valid input. @@ -3664,13 +3801,14 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_cpp conftest.$ac_ext") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } >/dev/null && { test -z "$ac_c_preproc_warn_flag$ac_c_werror_flag" || test ! -s conftest.err @@ -3678,7 +3816,7 @@ # Broken: success on invalid input. continue else - echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 # Passes both tests. @@ -3694,11 +3832,13 @@ if $ac_preproc_ok; then : else - { { echo "$as_me:$LINENO: error: C preprocessor \"$CPP\" fails sanity check + { { $as_echo "$as_me:$LINENO: error: in \`$ac_pwd':" >&5 +$as_echo "$as_me: error: in \`$ac_pwd':" >&2;} +{ { $as_echo "$as_me:$LINENO: error: C preprocessor \"$CPP\" fails sanity check See \`config.log' for more details." >&5 -echo "$as_me: error: C preprocessor \"$CPP\" fails sanity check +$as_echo "$as_me: error: C preprocessor \"$CPP\" fails sanity check See \`config.log' for more details." >&2;} - { (exit 1); exit 1; }; } + { (exit 1); exit 1; }; }; } fi ac_ext=c @@ -3708,42 +3848,37 @@ ac_compiler_gnu=$ac_cv_c_compiler_gnu -{ echo "$as_me:$LINENO: checking for grep that handles long lines and -e" >&5 -echo $ECHO_N "checking for grep that handles long lines and -e... $ECHO_C" >&6; } -if test "${ac_cv_path_GREP+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 -else - # Extract the first word of "grep ggrep" to use in msg output -if test -z "$GREP"; then -set dummy grep ggrep; ac_prog_name=$2 +{ $as_echo "$as_me:$LINENO: checking for grep that handles long lines and -e" >&5 +$as_echo_n "checking for grep that handles long lines and -e... " >&6; } if test "${ac_cv_path_GREP+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 + $as_echo_n "(cached) " >&6 else + if test -z "$GREP"; then ac_path_GREP_found=false -# Loop through the user's path and test for each of PROGNAME-LIST -as_save_IFS=$IFS; IFS=$PATH_SEPARATOR + # Loop through the user's path and test for each of PROGNAME-LIST + as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $PATH$PATH_SEPARATOR/usr/xpg4/bin do IFS=$as_save_IFS test -z "$as_dir" && as_dir=. for ac_prog in grep ggrep; do - for ac_exec_ext in '' $ac_executable_extensions; do - ac_path_GREP="$as_dir/$ac_prog$ac_exec_ext" - { test -f "$ac_path_GREP" && $as_test_x "$ac_path_GREP"; } || continue - # Check for GNU ac_path_GREP and select it if it is found. + for ac_exec_ext in '' $ac_executable_extensions; do + ac_path_GREP="$as_dir/$ac_prog$ac_exec_ext" + { test -f "$ac_path_GREP" && $as_test_x "$ac_path_GREP"; } || continue +# Check for GNU ac_path_GREP and select it if it is found. # Check for GNU $ac_path_GREP case `"$ac_path_GREP" --version 2>&1` in *GNU*) ac_cv_path_GREP="$ac_path_GREP" ac_path_GREP_found=:;; *) ac_count=0 - echo $ECHO_N "0123456789$ECHO_C" >"conftest.in" + $as_echo_n 0123456789 >"conftest.in" while : do cat "conftest.in" "conftest.in" >"conftest.tmp" mv "conftest.tmp" "conftest.in" cp "conftest.in" "conftest.nl" - echo 'GREP' >> "conftest.nl" + $as_echo 'GREP' >> "conftest.nl" "$ac_path_GREP" -e 'GREP$' -e '-(cannot match)-' < "conftest.nl" >"conftest.out" 2>/dev/null || break diff "conftest.out" "conftest.nl" >/dev/null 2>&1 || break ac_count=`expr $ac_count + 1` @@ -3758,145 +3893,578 @@ rm -f conftest.in conftest.tmp conftest.nl conftest.out;; esac + $ac_path_GREP_found && break 3 + done + done +done +IFS=$as_save_IFS + if test -z "$ac_cv_path_GREP"; then + { { $as_echo "$as_me:$LINENO: error: no acceptable grep could be found in $PATH$PATH_SEPARATOR/usr/xpg4/bin" >&5 +$as_echo "$as_me: error: no acceptable grep could be found in $PATH$PATH_SEPARATOR/usr/xpg4/bin" >&2;} + { (exit 1); exit 1; }; } + fi +else + ac_cv_path_GREP=$GREP +fi + +fi +{ $as_echo "$as_me:$LINENO: result: $ac_cv_path_GREP" >&5 +$as_echo "$ac_cv_path_GREP" >&6; } + GREP="$ac_cv_path_GREP" + + +{ $as_echo "$as_me:$LINENO: checking for egrep" >&5 +$as_echo_n "checking for egrep... " >&6; } +if test "${ac_cv_path_EGREP+set}" = set; then + $as_echo_n "(cached) " >&6 +else + if echo a | $GREP -E '(a|b)' >/dev/null 2>&1 + then ac_cv_path_EGREP="$GREP -E" + else + if test -z "$EGREP"; then + ac_path_EGREP_found=false + # Loop through the user's path and test for each of PROGNAME-LIST + as_save_IFS=$IFS; IFS=$PATH_SEPARATOR +for as_dir in $PATH$PATH_SEPARATOR/usr/xpg4/bin +do + IFS=$as_save_IFS + test -z "$as_dir" && as_dir=. + for ac_prog in egrep; do + for ac_exec_ext in '' $ac_executable_extensions; do + ac_path_EGREP="$as_dir/$ac_prog$ac_exec_ext" + { test -f "$ac_path_EGREP" && $as_test_x "$ac_path_EGREP"; } || continue +# Check for GNU ac_path_EGREP and select it if it is found. + # Check for GNU $ac_path_EGREP +case `"$ac_path_EGREP" --version 2>&1` in +*GNU*) + ac_cv_path_EGREP="$ac_path_EGREP" ac_path_EGREP_found=:;; +*) + ac_count=0 + $as_echo_n 0123456789 >"conftest.in" + while : + do + cat "conftest.in" "conftest.in" >"conftest.tmp" + mv "conftest.tmp" "conftest.in" + cp "conftest.in" "conftest.nl" + $as_echo 'EGREP' >> "conftest.nl" + "$ac_path_EGREP" 'EGREP$' < "conftest.nl" >"conftest.out" 2>/dev/null || break + diff "conftest.out" "conftest.nl" >/dev/null 2>&1 || break + ac_count=`expr $ac_count + 1` + if test $ac_count -gt ${ac_path_EGREP_max-0}; then + # Best one so far, save it but keep looking for a better one + ac_cv_path_EGREP="$ac_path_EGREP" + ac_path_EGREP_max=$ac_count + fi + # 10*(2^10) chars as input seems more than enough + test $ac_count -gt 10 && break + done + rm -f conftest.in conftest.tmp conftest.nl conftest.out;; +esac + + $ac_path_EGREP_found && break 3 + done + done +done +IFS=$as_save_IFS + if test -z "$ac_cv_path_EGREP"; then + { { $as_echo "$as_me:$LINENO: error: no acceptable egrep could be found in $PATH$PATH_SEPARATOR/usr/xpg4/bin" >&5 +$as_echo "$as_me: error: no acceptable egrep could be found in $PATH$PATH_SEPARATOR/usr/xpg4/bin" >&2;} + { (exit 1); exit 1; }; } + fi +else + ac_cv_path_EGREP=$EGREP +fi + + fi +fi +{ $as_echo "$as_me:$LINENO: result: $ac_cv_path_EGREP" >&5 +$as_echo "$ac_cv_path_EGREP" >&6; } + EGREP="$ac_cv_path_EGREP" + + +{ $as_echo "$as_me:$LINENO: checking for ANSI C header files" >&5 +$as_echo_n "checking for ANSI C header files... " >&6; } +if test "${ac_cv_header_stdc+set}" = set; then + $as_echo_n "(cached) " >&6 +else + cat >conftest.$ac_ext <<_ACEOF +/* confdefs.h. */ +_ACEOF +cat confdefs.h >>conftest.$ac_ext +cat >>conftest.$ac_ext <<_ACEOF +/* end confdefs.h. */ +#include +#include +#include +#include + +int +main () +{ + + ; + return 0; +} +_ACEOF +rm -f conftest.$ac_objext +if { (ac_try="$ac_compile" +case "(($ac_try" in + *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; + *) ac_try_echo=$ac_try;; +esac +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 + (eval "$ac_compile") 2>conftest.er1 + ac_status=$? + grep -v '^ *+' conftest.er1 >conftest.err + rm -f conftest.er1 + cat conftest.err >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 + (exit $ac_status); } && { + test -z "$ac_c_werror_flag" || + test ! -s conftest.err + } && test -s conftest.$ac_objext; then + ac_cv_header_stdc=yes +else + $as_echo "$as_me: failed program was:" >&5 +sed 's/^/| /' conftest.$ac_ext >&5 + + ac_cv_header_stdc=no +fi + +rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext + +if test $ac_cv_header_stdc = yes; then + # SunOS 4.x string.h does not declare mem*, contrary to ANSI. + cat >conftest.$ac_ext <<_ACEOF +/* confdefs.h. */ +_ACEOF +cat confdefs.h >>conftest.$ac_ext +cat >>conftest.$ac_ext <<_ACEOF +/* end confdefs.h. */ +#include + +_ACEOF +if (eval "$ac_cpp conftest.$ac_ext") 2>&5 | + $EGREP "memchr" >/dev/null 2>&1; then + : +else + ac_cv_header_stdc=no +fi +rm -f conftest* + +fi + +if test $ac_cv_header_stdc = yes; then + # ISC 2.0.2 stdlib.h does not declare free, contrary to ANSI. + cat >conftest.$ac_ext <<_ACEOF +/* confdefs.h. */ +_ACEOF +cat confdefs.h >>conftest.$ac_ext +cat >>conftest.$ac_ext <<_ACEOF +/* end confdefs.h. */ +#include + +_ACEOF +if (eval "$ac_cpp conftest.$ac_ext") 2>&5 | + $EGREP "free" >/dev/null 2>&1; then + : +else + ac_cv_header_stdc=no +fi +rm -f conftest* + +fi + +if test $ac_cv_header_stdc = yes; then + # /bin/cc in Irix-4.0.5 gets non-ANSI ctype macros unless using -ansi. + if test "$cross_compiling" = yes; then + : +else + cat >conftest.$ac_ext <<_ACEOF +/* confdefs.h. */ +_ACEOF +cat confdefs.h >>conftest.$ac_ext +cat >>conftest.$ac_ext <<_ACEOF +/* end confdefs.h. */ +#include +#include +#if ((' ' & 0x0FF) == 0x020) +# define ISLOWER(c) ('a' <= (c) && (c) <= 'z') +# define TOUPPER(c) (ISLOWER(c) ? 'A' + ((c) - 'a') : (c)) +#else +# define ISLOWER(c) \ + (('a' <= (c) && (c) <= 'i') \ + || ('j' <= (c) && (c) <= 'r') \ + || ('s' <= (c) && (c) <= 'z')) +# define TOUPPER(c) (ISLOWER(c) ? ((c) | 0x40) : (c)) +#endif + +#define XOR(e, f) (((e) && !(f)) || (!(e) && (f))) +int +main () +{ + int i; + for (i = 0; i < 256; i++) + if (XOR (islower (i), ISLOWER (i)) + || toupper (i) != TOUPPER (i)) + return 2; + return 0; +} +_ACEOF +rm -f conftest$ac_exeext +if { (ac_try="$ac_link" +case "(($ac_try" in + *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; + *) ac_try_echo=$ac_try;; +esac +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 + (eval "$ac_link") 2>&5 + ac_status=$? + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 + (exit $ac_status); } && { ac_try='./conftest$ac_exeext' + { (case "(($ac_try" in + *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; + *) ac_try_echo=$ac_try;; +esac +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 + (eval "$ac_try") 2>&5 + ac_status=$? + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 + (exit $ac_status); }; }; then + : +else + $as_echo "$as_me: program exited with status $ac_status" >&5 +$as_echo "$as_me: failed program was:" >&5 +sed 's/^/| /' conftest.$ac_ext >&5 + +( exit $ac_status ) +ac_cv_header_stdc=no +fi +rm -rf conftest.dSYM +rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext conftest.$ac_objext conftest.$ac_ext +fi + + +fi +fi +{ $as_echo "$as_me:$LINENO: result: $ac_cv_header_stdc" >&5 +$as_echo "$ac_cv_header_stdc" >&6; } +if test $ac_cv_header_stdc = yes; then + +cat >>confdefs.h <<\_ACEOF +#define STDC_HEADERS 1 +_ACEOF + +fi + +# On IRIX 5.3, sys/types and inttypes.h are conflicting. + + + + + + + + + +for ac_header in sys/types.h sys/stat.h stdlib.h string.h memory.h strings.h \ + inttypes.h stdint.h unistd.h +do +as_ac_Header=`$as_echo "ac_cv_header_$ac_header" | $as_tr_sh` +{ $as_echo "$as_me:$LINENO: checking for $ac_header" >&5 +$as_echo_n "checking for $ac_header... " >&6; } +if { as_var=$as_ac_Header; eval "test \"\${$as_var+set}\" = set"; }; then + $as_echo_n "(cached) " >&6 +else + cat >conftest.$ac_ext <<_ACEOF +/* confdefs.h. */ +_ACEOF +cat confdefs.h >>conftest.$ac_ext +cat >>conftest.$ac_ext <<_ACEOF +/* end confdefs.h. */ +$ac_includes_default + +#include <$ac_header> +_ACEOF +rm -f conftest.$ac_objext +if { (ac_try="$ac_compile" +case "(($ac_try" in + *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; + *) ac_try_echo=$ac_try;; +esac +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 + (eval "$ac_compile") 2>conftest.er1 + ac_status=$? + grep -v '^ *+' conftest.er1 >conftest.err + rm -f conftest.er1 + cat conftest.err >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 + (exit $ac_status); } && { + test -z "$ac_c_werror_flag" || + test ! -s conftest.err + } && test -s conftest.$ac_objext; then + eval "$as_ac_Header=yes" +else + $as_echo "$as_me: failed program was:" >&5 +sed 's/^/| /' conftest.$ac_ext >&5 + + eval "$as_ac_Header=no" +fi + +rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext +fi +ac_res=`eval 'as_val=${'$as_ac_Header'} + $as_echo "$as_val"'` + { $as_echo "$as_me:$LINENO: result: $ac_res" >&5 +$as_echo "$ac_res" >&6; } +as_val=`eval 'as_val=${'$as_ac_Header'} + $as_echo "$as_val"'` + if test "x$as_val" = x""yes; then + cat >>confdefs.h <<_ACEOF +#define `$as_echo "HAVE_$ac_header" | $as_tr_cpp` 1 +_ACEOF + +fi + +done + + + + if test "${ac_cv_header_minix_config_h+set}" = set; then + { $as_echo "$as_me:$LINENO: checking for minix/config.h" >&5 +$as_echo_n "checking for minix/config.h... " >&6; } +if test "${ac_cv_header_minix_config_h+set}" = set; then + $as_echo_n "(cached) " >&6 +fi +{ $as_echo "$as_me:$LINENO: result: $ac_cv_header_minix_config_h" >&5 +$as_echo "$ac_cv_header_minix_config_h" >&6; } +else + # Is the header compilable? +{ $as_echo "$as_me:$LINENO: checking minix/config.h usability" >&5 +$as_echo_n "checking minix/config.h usability... " >&6; } +cat >conftest.$ac_ext <<_ACEOF +/* confdefs.h. */ +_ACEOF +cat confdefs.h >>conftest.$ac_ext +cat >>conftest.$ac_ext <<_ACEOF +/* end confdefs.h. */ +$ac_includes_default +#include +_ACEOF +rm -f conftest.$ac_objext +if { (ac_try="$ac_compile" +case "(($ac_try" in + *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; + *) ac_try_echo=$ac_try;; +esac +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 + (eval "$ac_compile") 2>conftest.er1 + ac_status=$? + grep -v '^ *+' conftest.er1 >conftest.err + rm -f conftest.er1 + cat conftest.err >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 + (exit $ac_status); } && { + test -z "$ac_c_werror_flag" || + test ! -s conftest.err + } && test -s conftest.$ac_objext; then + ac_header_compiler=yes +else + $as_echo "$as_me: failed program was:" >&5 +sed 's/^/| /' conftest.$ac_ext >&5 - $ac_path_GREP_found && break 3 - done -done + ac_header_compiler=no +fi -done -IFS=$as_save_IFS +rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext +{ $as_echo "$as_me:$LINENO: result: $ac_header_compiler" >&5 +$as_echo "$ac_header_compiler" >&6; } +# Is the header present? +{ $as_echo "$as_me:$LINENO: checking minix/config.h presence" >&5 +$as_echo_n "checking minix/config.h presence... " >&6; } +cat >conftest.$ac_ext <<_ACEOF +/* confdefs.h. */ +_ACEOF +cat confdefs.h >>conftest.$ac_ext +cat >>conftest.$ac_ext <<_ACEOF +/* end confdefs.h. */ +#include +_ACEOF +if { (ac_try="$ac_cpp conftest.$ac_ext" +case "(($ac_try" in + *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; + *) ac_try_echo=$ac_try;; +esac +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 + (eval "$ac_cpp conftest.$ac_ext") 2>conftest.er1 + ac_status=$? + grep -v '^ *+' conftest.er1 >conftest.err + rm -f conftest.er1 + cat conftest.err >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 + (exit $ac_status); } >/dev/null && { + test -z "$ac_c_preproc_warn_flag$ac_c_werror_flag" || + test ! -s conftest.err + }; then + ac_header_preproc=yes +else + $as_echo "$as_me: failed program was:" >&5 +sed 's/^/| /' conftest.$ac_ext >&5 + ac_header_preproc=no fi -GREP="$ac_cv_path_GREP" -if test -z "$GREP"; then - { { echo "$as_me:$LINENO: error: no acceptable $ac_prog_name could be found in $PATH$PATH_SEPARATOR/usr/xpg4/bin" >&5 -echo "$as_me: error: no acceptable $ac_prog_name could be found in $PATH$PATH_SEPARATOR/usr/xpg4/bin" >&2;} - { (exit 1); exit 1; }; } -fi +rm -f conftest.err conftest.$ac_ext +{ $as_echo "$as_me:$LINENO: result: $ac_header_preproc" >&5 +$as_echo "$ac_header_preproc" >&6; } +# So? What about this header? +case $ac_header_compiler:$ac_header_preproc:$ac_c_preproc_warn_flag in + yes:no: ) + { $as_echo "$as_me:$LINENO: WARNING: minix/config.h: accepted by the compiler, rejected by the preprocessor!" >&5 +$as_echo "$as_me: WARNING: minix/config.h: accepted by the compiler, rejected by the preprocessor!" >&2;} + { $as_echo "$as_me:$LINENO: WARNING: minix/config.h: proceeding with the compiler's result" >&5 +$as_echo "$as_me: WARNING: minix/config.h: proceeding with the compiler's result" >&2;} + ac_header_preproc=yes + ;; + no:yes:* ) + { $as_echo "$as_me:$LINENO: WARNING: minix/config.h: present but cannot be compiled" >&5 +$as_echo "$as_me: WARNING: minix/config.h: present but cannot be compiled" >&2;} + { $as_echo "$as_me:$LINENO: WARNING: minix/config.h: check for missing prerequisite headers?" >&5 +$as_echo "$as_me: WARNING: minix/config.h: check for missing prerequisite headers?" >&2;} + { $as_echo "$as_me:$LINENO: WARNING: minix/config.h: see the Autoconf documentation" >&5 +$as_echo "$as_me: WARNING: minix/config.h: see the Autoconf documentation" >&2;} + { $as_echo "$as_me:$LINENO: WARNING: minix/config.h: section \"Present But Cannot Be Compiled\"" >&5 +$as_echo "$as_me: WARNING: minix/config.h: section \"Present But Cannot Be Compiled\"" >&2;} + { $as_echo "$as_me:$LINENO: WARNING: minix/config.h: proceeding with the preprocessor's result" >&5 +$as_echo "$as_me: WARNING: minix/config.h: proceeding with the preprocessor's result" >&2;} + { $as_echo "$as_me:$LINENO: WARNING: minix/config.h: in the future, the compiler will take precedence" >&5 +$as_echo "$as_me: WARNING: minix/config.h: in the future, the compiler will take precedence" >&2;} + ( cat <<\_ASBOX +## ------------------------------------------------ ## +## Report this to http://www.python.org/python-bugs ## +## ------------------------------------------------ ## +_ASBOX + ) | sed "s/^/$as_me: WARNING: /" >&2 + ;; +esac +{ $as_echo "$as_me:$LINENO: checking for minix/config.h" >&5 +$as_echo_n "checking for minix/config.h... " >&6; } +if test "${ac_cv_header_minix_config_h+set}" = set; then + $as_echo_n "(cached) " >&6 else - ac_cv_path_GREP=$GREP + ac_cv_header_minix_config_h=$ac_header_preproc fi - +{ $as_echo "$as_me:$LINENO: result: $ac_cv_header_minix_config_h" >&5 +$as_echo "$ac_cv_header_minix_config_h" >&6; } fi -{ echo "$as_me:$LINENO: result: $ac_cv_path_GREP" >&5 -echo "${ECHO_T}$ac_cv_path_GREP" >&6; } - GREP="$ac_cv_path_GREP" - - -{ echo "$as_me:$LINENO: checking for egrep" >&5 -echo $ECHO_N "checking for egrep... $ECHO_C" >&6; } -if test "${ac_cv_path_EGREP+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 -else - if echo a | $GREP -E '(a|b)' >/dev/null 2>&1 - then ac_cv_path_EGREP="$GREP -E" - else - # Extract the first word of "egrep" to use in msg output -if test -z "$EGREP"; then -set dummy egrep; ac_prog_name=$2 -if test "${ac_cv_path_EGREP+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 +if test "x$ac_cv_header_minix_config_h" = x""yes; then + MINIX=yes else - ac_path_EGREP_found=false -# Loop through the user's path and test for each of PROGNAME-LIST -as_save_IFS=$IFS; IFS=$PATH_SEPARATOR -for as_dir in $PATH$PATH_SEPARATOR/usr/xpg4/bin -do - IFS=$as_save_IFS - test -z "$as_dir" && as_dir=. - for ac_prog in egrep; do - for ac_exec_ext in '' $ac_executable_extensions; do - ac_path_EGREP="$as_dir/$ac_prog$ac_exec_ext" - { test -f "$ac_path_EGREP" && $as_test_x "$ac_path_EGREP"; } || continue - # Check for GNU ac_path_EGREP and select it if it is found. - # Check for GNU $ac_path_EGREP -case `"$ac_path_EGREP" --version 2>&1` in -*GNU*) - ac_cv_path_EGREP="$ac_path_EGREP" ac_path_EGREP_found=:;; -*) - ac_count=0 - echo $ECHO_N "0123456789$ECHO_C" >"conftest.in" - while : - do - cat "conftest.in" "conftest.in" >"conftest.tmp" - mv "conftest.tmp" "conftest.in" - cp "conftest.in" "conftest.nl" - echo 'EGREP' >> "conftest.nl" - "$ac_path_EGREP" 'EGREP$' < "conftest.nl" >"conftest.out" 2>/dev/null || break - diff "conftest.out" "conftest.nl" >/dev/null 2>&1 || break - ac_count=`expr $ac_count + 1` - if test $ac_count -gt ${ac_path_EGREP_max-0}; then - # Best one so far, save it but keep looking for a better one - ac_cv_path_EGREP="$ac_path_EGREP" - ac_path_EGREP_max=$ac_count - fi - # 10*(2^10) chars as input seems more than enough - test $ac_count -gt 10 && break - done - rm -f conftest.in conftest.tmp conftest.nl conftest.out;; -esac - + MINIX= +fi - $ac_path_EGREP_found && break 3 - done -done -done -IFS=$as_save_IFS + if test "$MINIX" = yes; then +cat >>confdefs.h <<\_ACEOF +#define _POSIX_SOURCE 1 +_ACEOF -fi -EGREP="$ac_cv_path_EGREP" -if test -z "$EGREP"; then - { { echo "$as_me:$LINENO: error: no acceptable $ac_prog_name could be found in $PATH$PATH_SEPARATOR/usr/xpg4/bin" >&5 -echo "$as_me: error: no acceptable $ac_prog_name could be found in $PATH$PATH_SEPARATOR/usr/xpg4/bin" >&2;} - { (exit 1); exit 1; }; } -fi +cat >>confdefs.h <<\_ACEOF +#define _POSIX_1_SOURCE 2 +_ACEOF -else - ac_cv_path_EGREP=$EGREP -fi +cat >>confdefs.h <<\_ACEOF +#define _MINIX 1 +_ACEOF - fi -fi -{ echo "$as_me:$LINENO: result: $ac_cv_path_EGREP" >&5 -echo "${ECHO_T}$ac_cv_path_EGREP" >&6; } - EGREP="$ac_cv_path_EGREP" + fi -{ echo "$as_me:$LINENO: checking for AIX" >&5 -echo $ECHO_N "checking for AIX... $ECHO_C" >&6; } -cat >conftest.$ac_ext <<_ACEOF + { $as_echo "$as_me:$LINENO: checking whether it is safe to define __EXTENSIONS__" >&5 +$as_echo_n "checking whether it is safe to define __EXTENSIONS__... " >&6; } +if test "${ac_cv_safe_to_define___extensions__+set}" = set; then + $as_echo_n "(cached) " >&6 +else + cat >conftest.$ac_ext <<_ACEOF /* confdefs.h. */ _ACEOF cat confdefs.h >>conftest.$ac_ext cat >>conftest.$ac_ext <<_ACEOF /* end confdefs.h. */ -#ifdef _AIX - yes -#endif +# define __EXTENSIONS__ 1 + $ac_includes_default +int +main () +{ + + ; + return 0; +} _ACEOF -if (eval "$ac_cpp conftest.$ac_ext") 2>&5 | - $EGREP "yes" >/dev/null 2>&1; then - { echo "$as_me:$LINENO: result: yes" >&5 -echo "${ECHO_T}yes" >&6; } -cat >>confdefs.h <<\_ACEOF +rm -f conftest.$ac_objext +if { (ac_try="$ac_compile" +case "(($ac_try" in + *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; + *) ac_try_echo=$ac_try;; +esac +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 + (eval "$ac_compile") 2>conftest.er1 + ac_status=$? + grep -v '^ *+' conftest.er1 >conftest.err + rm -f conftest.er1 + cat conftest.err >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 + (exit $ac_status); } && { + test -z "$ac_c_werror_flag" || + test ! -s conftest.err + } && test -s conftest.$ac_objext; then + ac_cv_safe_to_define___extensions__=yes +else + $as_echo "$as_me: failed program was:" >&5 +sed 's/^/| /' conftest.$ac_ext >&5 + + ac_cv_safe_to_define___extensions__=no +fi + +rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext +fi +{ $as_echo "$as_me:$LINENO: result: $ac_cv_safe_to_define___extensions__" >&5 +$as_echo "$ac_cv_safe_to_define___extensions__" >&6; } + test $ac_cv_safe_to_define___extensions__ = yes && + cat >>confdefs.h <<\_ACEOF +#define __EXTENSIONS__ 1 +_ACEOF + + cat >>confdefs.h <<\_ACEOF #define _ALL_SOURCE 1 _ACEOF -else - { echo "$as_me:$LINENO: result: no" >&5 -echo "${ECHO_T}no" >&6; } -fi -rm -f conftest* + cat >>confdefs.h <<\_ACEOF +#define _GNU_SOURCE 1 +_ACEOF + + cat >>confdefs.h <<\_ACEOF +#define _POSIX_PTHREAD_SEMANTICS 1 +_ACEOF + + cat >>confdefs.h <<\_ACEOF +#define _TANDEM_SOURCE 1 +_ACEOF @@ -3909,8 +4477,8 @@ esac -{ echo "$as_me:$LINENO: checking for --with-suffix" >&5 -echo $ECHO_N "checking for --with-suffix... $ECHO_C" >&6; } +{ $as_echo "$as_me:$LINENO: checking for --with-suffix" >&5 +$as_echo_n "checking for --with-suffix... " >&6; } # Check whether --with-suffix was given. if test "${with_suffix+set}" = set; then @@ -3922,26 +4490,26 @@ esac fi -{ echo "$as_me:$LINENO: result: $EXEEXT" >&5 -echo "${ECHO_T}$EXEEXT" >&6; } +{ $as_echo "$as_me:$LINENO: result: $EXEEXT" >&5 +$as_echo "$EXEEXT" >&6; } # Test whether we're running on a non-case-sensitive system, in which # case we give a warning if no ext is given -{ echo "$as_me:$LINENO: checking for case-insensitive build directory" >&5 -echo $ECHO_N "checking for case-insensitive build directory... $ECHO_C" >&6; } +{ $as_echo "$as_me:$LINENO: checking for case-insensitive build directory" >&5 +$as_echo_n "checking for case-insensitive build directory... " >&6; } if test ! -d CaseSensitiveTestDir; then mkdir CaseSensitiveTestDir fi if test -d casesensitivetestdir then - { echo "$as_me:$LINENO: result: yes" >&5 -echo "${ECHO_T}yes" >&6; } + { $as_echo "$as_me:$LINENO: result: yes" >&5 +$as_echo "yes" >&6; } BUILDEXEEXT=.exe else - { echo "$as_me:$LINENO: result: no" >&5 -echo "${ECHO_T}no" >&6; } + { $as_echo "$as_me:$LINENO: result: no" >&5 +$as_echo "no" >&6; } BUILDEXEEXT=$EXEEXT fi rmdir CaseSensitiveTestDir @@ -3974,14 +4542,14 @@ -{ echo "$as_me:$LINENO: checking LIBRARY" >&5 -echo $ECHO_N "checking LIBRARY... $ECHO_C" >&6; } +{ $as_echo "$as_me:$LINENO: checking LIBRARY" >&5 +$as_echo_n "checking LIBRARY... " >&6; } if test -z "$LIBRARY" then LIBRARY='libpython$(VERSION).a' fi -{ echo "$as_me:$LINENO: result: $LIBRARY" >&5 -echo "${ECHO_T}$LIBRARY" >&6; } +{ $as_echo "$as_me:$LINENO: result: $LIBRARY" >&5 +$as_echo "$LIBRARY" >&6; } # LDLIBRARY is the name of the library to link against (as opposed to the # name of the library into which to insert object files). BLDLIBRARY is also @@ -4016,8 +4584,8 @@ # This is altered for AIX in order to build the export list before # linking. -{ echo "$as_me:$LINENO: checking LINKCC" >&5 -echo $ECHO_N "checking LINKCC... $ECHO_C" >&6; } +{ $as_echo "$as_me:$LINENO: checking LINKCC" >&5 +$as_echo_n "checking LINKCC... " >&6; } if test -z "$LINKCC" then LINKCC='$(PURIFY) $(MAINCC)' @@ -4037,11 +4605,11 @@ LINKCC=qcc;; esac fi -{ echo "$as_me:$LINENO: result: $LINKCC" >&5 -echo "${ECHO_T}$LINKCC" >&6; } +{ $as_echo "$as_me:$LINENO: result: $LINKCC" >&5 +$as_echo "$LINKCC" >&6; } -{ echo "$as_me:$LINENO: checking for --enable-shared" >&5 -echo $ECHO_N "checking for --enable-shared... $ECHO_C" >&6; } +{ $as_echo "$as_me:$LINENO: checking for --enable-shared" >&5 +$as_echo_n "checking for --enable-shared... " >&6; } # Check whether --enable-shared was given. if test "${enable_shared+set}" = set; then enableval=$enable_shared; @@ -4057,11 +4625,11 @@ enable_shared="no";; esac fi -{ echo "$as_me:$LINENO: result: $enable_shared" >&5 -echo "${ECHO_T}$enable_shared" >&6; } +{ $as_echo "$as_me:$LINENO: result: $enable_shared" >&5 +$as_echo "$enable_shared" >&6; } -{ echo "$as_me:$LINENO: checking for --enable-profiling" >&5 -echo $ECHO_N "checking for --enable-profiling... $ECHO_C" >&6; } +{ $as_echo "$as_me:$LINENO: checking for --enable-profiling" >&5 +$as_echo_n "checking for --enable-profiling... " >&6; } # Check whether --enable-profiling was given. if test "${enable_profiling+set}" = set; then enableval=$enable_profiling; ac_save_cc="$CC" @@ -4083,29 +4651,32 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_link") 2>&5 ac_status=$? - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { ac_try='./conftest$ac_exeext' { (case "(($ac_try" in *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_try") 2>&5 ac_status=$? - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); }; }; then ac_enable_profiling="yes" else - echo "$as_me: program exited with status $ac_status" >&5 -echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: program exited with status $ac_status" >&5 +$as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 ( exit $ac_status ) ac_enable_profiling="no" fi +rm -rf conftest.dSYM rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext conftest.$ac_objext conftest.$ac_ext fi @@ -4113,8 +4684,8 @@ CC="$ac_save_cc" fi -{ echo "$as_me:$LINENO: result: $ac_enable_profiling" >&5 -echo "${ECHO_T}$ac_enable_profiling" >&6; } +{ $as_echo "$as_me:$LINENO: result: $ac_enable_profiling" >&5 +$as_echo "$ac_enable_profiling" >&6; } case "$ac_enable_profiling" in "yes") @@ -4123,8 +4694,8 @@ ;; esac -{ echo "$as_me:$LINENO: checking LDLIBRARY" >&5 -echo $ECHO_N "checking LDLIBRARY... $ECHO_C" >&6; } +{ $as_echo "$as_me:$LINENO: checking LDLIBRARY" >&5 +$as_echo_n "checking LDLIBRARY... " >&6; } # MacOSX framework builds need more magic. LDLIBRARY is the dynamic # library that we build, but we do not want to link against it (we @@ -4211,16 +4782,16 @@ esac fi -{ echo "$as_me:$LINENO: result: $LDLIBRARY" >&5 -echo "${ECHO_T}$LDLIBRARY" >&6; } +{ $as_echo "$as_me:$LINENO: result: $LDLIBRARY" >&5 +$as_echo "$LDLIBRARY" >&6; } if test -n "$ac_tool_prefix"; then # Extract the first word of "${ac_tool_prefix}ranlib", so it can be a program name with args. set dummy ${ac_tool_prefix}ranlib; ac_word=$2 -{ echo "$as_me:$LINENO: checking for $ac_word" >&5 -echo $ECHO_N "checking for $ac_word... $ECHO_C" >&6; } +{ $as_echo "$as_me:$LINENO: checking for $ac_word" >&5 +$as_echo_n "checking for $ac_word... " >&6; } if test "${ac_cv_prog_RANLIB+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 + $as_echo_n "(cached) " >&6 else if test -n "$RANLIB"; then ac_cv_prog_RANLIB="$RANLIB" # Let the user override the test. @@ -4233,7 +4804,7 @@ for ac_exec_ext in '' $ac_executable_extensions; do if { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_test_x "$as_dir/$ac_word$ac_exec_ext"; }; then ac_cv_prog_RANLIB="${ac_tool_prefix}ranlib" - echo "$as_me:$LINENO: found $as_dir/$ac_word$ac_exec_ext" >&5 + $as_echo "$as_me:$LINENO: found $as_dir/$ac_word$ac_exec_ext" >&5 break 2 fi done @@ -4244,11 +4815,11 @@ fi RANLIB=$ac_cv_prog_RANLIB if test -n "$RANLIB"; then - { echo "$as_me:$LINENO: result: $RANLIB" >&5 -echo "${ECHO_T}$RANLIB" >&6; } + { $as_echo "$as_me:$LINENO: result: $RANLIB" >&5 +$as_echo "$RANLIB" >&6; } else - { echo "$as_me:$LINENO: result: no" >&5 -echo "${ECHO_T}no" >&6; } + { $as_echo "$as_me:$LINENO: result: no" >&5 +$as_echo "no" >&6; } fi @@ -4257,10 +4828,10 @@ ac_ct_RANLIB=$RANLIB # Extract the first word of "ranlib", so it can be a program name with args. set dummy ranlib; ac_word=$2 -{ echo "$as_me:$LINENO: checking for $ac_word" >&5 -echo $ECHO_N "checking for $ac_word... $ECHO_C" >&6; } +{ $as_echo "$as_me:$LINENO: checking for $ac_word" >&5 +$as_echo_n "checking for $ac_word... " >&6; } if test "${ac_cv_prog_ac_ct_RANLIB+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 + $as_echo_n "(cached) " >&6 else if test -n "$ac_ct_RANLIB"; then ac_cv_prog_ac_ct_RANLIB="$ac_ct_RANLIB" # Let the user override the test. @@ -4273,7 +4844,7 @@ for ac_exec_ext in '' $ac_executable_extensions; do if { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_test_x "$as_dir/$ac_word$ac_exec_ext"; }; then ac_cv_prog_ac_ct_RANLIB="ranlib" - echo "$as_me:$LINENO: found $as_dir/$ac_word$ac_exec_ext" >&5 + $as_echo "$as_me:$LINENO: found $as_dir/$ac_word$ac_exec_ext" >&5 break 2 fi done @@ -4284,11 +4855,11 @@ fi ac_ct_RANLIB=$ac_cv_prog_ac_ct_RANLIB if test -n "$ac_ct_RANLIB"; then - { echo "$as_me:$LINENO: result: $ac_ct_RANLIB" >&5 -echo "${ECHO_T}$ac_ct_RANLIB" >&6; } + { $as_echo "$as_me:$LINENO: result: $ac_ct_RANLIB" >&5 +$as_echo "$ac_ct_RANLIB" >&6; } else - { echo "$as_me:$LINENO: result: no" >&5 -echo "${ECHO_T}no" >&6; } + { $as_echo "$as_me:$LINENO: result: no" >&5 +$as_echo "no" >&6; } fi if test "x$ac_ct_RANLIB" = x; then @@ -4296,12 +4867,8 @@ else case $cross_compiling:$ac_tool_warned in yes:) -{ echo "$as_me:$LINENO: WARNING: In the future, Autoconf will not detect cross-tools -whose name does not start with the host triplet. If you think this -configuration is useful to you, please write to autoconf at gnu.org." >&5 -echo "$as_me: WARNING: In the future, Autoconf will not detect cross-tools -whose name does not start with the host triplet. If you think this -configuration is useful to you, please write to autoconf at gnu.org." >&2;} +{ $as_echo "$as_me:$LINENO: WARNING: using cross tools not prefixed with host triplet" >&5 +$as_echo "$as_me: WARNING: using cross tools not prefixed with host triplet" >&2;} ac_tool_warned=yes ;; esac RANLIB=$ac_ct_RANLIB @@ -4315,10 +4882,10 @@ do # Extract the first word of "$ac_prog", so it can be a program name with args. set dummy $ac_prog; ac_word=$2 -{ echo "$as_me:$LINENO: checking for $ac_word" >&5 -echo $ECHO_N "checking for $ac_word... $ECHO_C" >&6; } +{ $as_echo "$as_me:$LINENO: checking for $ac_word" >&5 +$as_echo_n "checking for $ac_word... " >&6; } if test "${ac_cv_prog_AR+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 + $as_echo_n "(cached) " >&6 else if test -n "$AR"; then ac_cv_prog_AR="$AR" # Let the user override the test. @@ -4331,7 +4898,7 @@ for ac_exec_ext in '' $ac_executable_extensions; do if { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_test_x "$as_dir/$ac_word$ac_exec_ext"; }; then ac_cv_prog_AR="$ac_prog" - echo "$as_me:$LINENO: found $as_dir/$ac_word$ac_exec_ext" >&5 + $as_echo "$as_me:$LINENO: found $as_dir/$ac_word$ac_exec_ext" >&5 break 2 fi done @@ -4342,11 +4909,11 @@ fi AR=$ac_cv_prog_AR if test -n "$AR"; then - { echo "$as_me:$LINENO: result: $AR" >&5 -echo "${ECHO_T}$AR" >&6; } + { $as_echo "$as_me:$LINENO: result: $AR" >&5 +$as_echo "$AR" >&6; } else - { echo "$as_me:$LINENO: result: no" >&5 -echo "${ECHO_T}no" >&6; } + { $as_echo "$as_me:$LINENO: result: no" >&5 +$as_echo "no" >&6; } fi @@ -4358,10 +4925,10 @@ # Extract the first word of "svnversion", so it can be a program name with args. set dummy svnversion; ac_word=$2 -{ echo "$as_me:$LINENO: checking for $ac_word" >&5 -echo $ECHO_N "checking for $ac_word... $ECHO_C" >&6; } +{ $as_echo "$as_me:$LINENO: checking for $ac_word" >&5 +$as_echo_n "checking for $ac_word... " >&6; } if test "${ac_cv_prog_SVNVERSION+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 + $as_echo_n "(cached) " >&6 else if test -n "$SVNVERSION"; then ac_cv_prog_SVNVERSION="$SVNVERSION" # Let the user override the test. @@ -4374,7 +4941,7 @@ for ac_exec_ext in '' $ac_executable_extensions; do if { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_test_x "$as_dir/$ac_word$ac_exec_ext"; }; then ac_cv_prog_SVNVERSION="found" - echo "$as_me:$LINENO: found $as_dir/$ac_word$ac_exec_ext" >&5 + $as_echo "$as_me:$LINENO: found $as_dir/$ac_word$ac_exec_ext" >&5 break 2 fi done @@ -4386,11 +4953,11 @@ fi SVNVERSION=$ac_cv_prog_SVNVERSION if test -n "$SVNVERSION"; then - { echo "$as_me:$LINENO: result: $SVNVERSION" >&5 -echo "${ECHO_T}$SVNVERSION" >&6; } + { $as_echo "$as_me:$LINENO: result: $SVNVERSION" >&5 +$as_echo "$SVNVERSION" >&6; } else - { echo "$as_me:$LINENO: result: no" >&5 -echo "${ECHO_T}no" >&6; } + { $as_echo "$as_me:$LINENO: result: no" >&5 +$as_echo "no" >&6; } fi @@ -4426,8 +4993,8 @@ fi done if test -z "$ac_aux_dir"; then - { { echo "$as_me:$LINENO: error: cannot find install-sh or install.sh in \"$srcdir\" \"$srcdir/..\" \"$srcdir/../..\"" >&5 -echo "$as_me: error: cannot find install-sh or install.sh in \"$srcdir\" \"$srcdir/..\" \"$srcdir/../..\"" >&2;} + { { $as_echo "$as_me:$LINENO: error: cannot find install-sh or install.sh in \"$srcdir\" \"$srcdir/..\" \"$srcdir/../..\"" >&5 +$as_echo "$as_me: error: cannot find install-sh or install.sh in \"$srcdir\" \"$srcdir/..\" \"$srcdir/../..\"" >&2;} { (exit 1); exit 1; }; } fi @@ -4453,11 +5020,12 @@ # SVR4 /usr/ucb/install, which tries to use the nonexistent group "staff" # OS/2's system install, which has a completely different semantic # ./install, which can be erroneously created by make from ./install.sh. -{ echo "$as_me:$LINENO: checking for a BSD-compatible install" >&5 -echo $ECHO_N "checking for a BSD-compatible install... $ECHO_C" >&6; } +# Reject install programs that cannot install multiple files. +{ $as_echo "$as_me:$LINENO: checking for a BSD-compatible install" >&5 +$as_echo_n "checking for a BSD-compatible install... " >&6; } if test -z "$INSTALL"; then if test "${ac_cv_path_install+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 + $as_echo_n "(cached) " >&6 else as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $PATH @@ -4486,17 +5054,29 @@ # program-specific install script used by HP pwplus--don't use. : else - ac_cv_path_install="$as_dir/$ac_prog$ac_exec_ext -c" - break 3 + rm -rf conftest.one conftest.two conftest.dir + echo one > conftest.one + echo two > conftest.two + mkdir conftest.dir + if "$as_dir/$ac_prog$ac_exec_ext" -c conftest.one conftest.two "`pwd`/conftest.dir" && + test -s conftest.one && test -s conftest.two && + test -s conftest.dir/conftest.one && + test -s conftest.dir/conftest.two + then + ac_cv_path_install="$as_dir/$ac_prog$ac_exec_ext -c" + break 3 + fi fi fi done done ;; esac + done IFS=$as_save_IFS +rm -rf conftest.one conftest.two conftest.dir fi if test "${ac_cv_path_install+set}" = set; then @@ -4509,8 +5089,8 @@ INSTALL=$ac_install_sh fi fi -{ echo "$as_me:$LINENO: result: $INSTALL" >&5 -echo "${ECHO_T}$INSTALL" >&6; } +{ $as_echo "$as_me:$LINENO: result: $INSTALL" >&5 +$as_echo "$INSTALL" >&6; } # Use test -z because SunOS4 sh mishandles braces in ${var-val}. # It thinks the first close brace ends the variable substitution. @@ -4533,8 +5113,8 @@ fi # Check for --with-pydebug -{ echo "$as_me:$LINENO: checking for --with-pydebug" >&5 -echo $ECHO_N "checking for --with-pydebug... $ECHO_C" >&6; } +{ $as_echo "$as_me:$LINENO: checking for --with-pydebug" >&5 +$as_echo_n "checking for --with-pydebug... " >&6; } # Check whether --with-pydebug was given. if test "${with_pydebug+set}" = set; then @@ -4546,15 +5126,15 @@ #define Py_DEBUG 1 _ACEOF - { echo "$as_me:$LINENO: result: yes" >&5 -echo "${ECHO_T}yes" >&6; }; + { $as_echo "$as_me:$LINENO: result: yes" >&5 +$as_echo "yes" >&6; }; Py_DEBUG='true' -else { echo "$as_me:$LINENO: result: no" >&5 -echo "${ECHO_T}no" >&6; }; Py_DEBUG='false' +else { $as_echo "$as_me:$LINENO: result: no" >&5 +$as_echo "no" >&6; }; Py_DEBUG='false' fi else - { echo "$as_me:$LINENO: result: no" >&5 -echo "${ECHO_T}no" >&6; } + { $as_echo "$as_me:$LINENO: result: no" >&5 +$as_echo "no" >&6; } fi @@ -4632,8 +5212,8 @@ # Python violates C99 rules, by casting between incompatible # pointer types. GCC may generate bad code as a result of that, # so use -fno-strict-aliasing if supported. - { echo "$as_me:$LINENO: checking whether $CC accepts -fno-strict-aliasing" >&5 -echo $ECHO_N "checking whether $CC accepts -fno-strict-aliasing... $ECHO_C" >&6; } + { $as_echo "$as_me:$LINENO: checking whether $CC accepts -fno-strict-aliasing" >&5 +$as_echo_n "checking whether $CC accepts -fno-strict-aliasing... " >&6; } ac_save_cc="$CC" CC="$CC -fno-strict-aliasing" if test "$cross_compiling" = yes; then @@ -4653,36 +5233,39 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_link") 2>&5 ac_status=$? - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { ac_try='./conftest$ac_exeext' { (case "(($ac_try" in *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_try") 2>&5 ac_status=$? - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); }; }; then ac_cv_no_strict_aliasing_ok=yes else - echo "$as_me: program exited with status $ac_status" >&5 -echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: program exited with status $ac_status" >&5 +$as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 ( exit $ac_status ) ac_cv_no_strict_aliasing_ok=no fi +rm -rf conftest.dSYM rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext conftest.$ac_objext conftest.$ac_ext fi CC="$ac_save_cc" - { echo "$as_me:$LINENO: result: $ac_cv_no_strict_aliasing_ok" >&5 -echo "${ECHO_T}$ac_cv_no_strict_aliasing_ok" >&6; } + { $as_echo "$as_me:$LINENO: result: $ac_cv_no_strict_aliasing_ok" >&5 +$as_echo "$ac_cv_no_strict_aliasing_ok" >&6; } if test $ac_cv_no_strict_aliasing_ok = yes then BASECFLAGS="$BASECFLAGS -fno-strict-aliasing" @@ -4708,8 +5291,8 @@ if test "${CC}" = gcc then - { echo "$as_me:$LINENO: checking which compiler should be used" >&5 -echo $ECHO_N "checking which compiler should be used... $ECHO_C" >&6; } + { $as_echo "$as_me:$LINENO: checking which compiler should be used" >&5 +$as_echo_n "checking which compiler should be used... " >&6; } case "${UNIVERSALSDK}" in */MacOSX10.4u.sdk) # Build using 10.4 SDK, force usage of gcc when the @@ -4719,8 +5302,8 @@ CPP=cpp-4.0 ;; esac - { echo "$as_me:$LINENO: result: $CC" >&5 -echo "${ECHO_T}$CC" >&6; } + { $as_echo "$as_me:$LINENO: result: $CC" >&5 +$as_echo "$CC" >&6; } fi @@ -4753,8 +5336,8 @@ LIPO_64BIT_FLAGS="-extract x86_64" else - { { echo "$as_me:$LINENO: error: proper usage is --with-universal-arch=32-bit|64-bit|all|intel|3-way" >&5 -echo "$as_me: error: proper usage is --with-universal-arch=32-bit|64-bit|all|intel|3-way" >&2;} + { { $as_echo "$as_me:$LINENO: error: proper usage is --with-universal-arch=32-bit|64-bit|all|intel|3-way" >&5 +$as_echo "$as_me: error: proper usage is --with-universal-arch=32-bit|64-bit|all|intel|3-way" >&2;} { (exit 1); exit 1; }; } fi @@ -4848,10 +5431,10 @@ ac_cv_opt_olimit_ok=no fi -{ echo "$as_me:$LINENO: checking whether $CC accepts -OPT:Olimit=0" >&5 -echo $ECHO_N "checking whether $CC accepts -OPT:Olimit=0... $ECHO_C" >&6; } +{ $as_echo "$as_me:$LINENO: checking whether $CC accepts -OPT:Olimit=0" >&5 +$as_echo_n "checking whether $CC accepts -OPT:Olimit=0... " >&6; } if test "${ac_cv_opt_olimit_ok+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 + $as_echo_n "(cached) " >&6 else ac_save_cc="$CC" CC="$CC -OPT:Olimit=0" @@ -4872,29 +5455,32 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_link") 2>&5 ac_status=$? - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { ac_try='./conftest$ac_exeext' { (case "(($ac_try" in *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_try") 2>&5 ac_status=$? - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); }; }; then ac_cv_opt_olimit_ok=yes else - echo "$as_me: program exited with status $ac_status" >&5 -echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: program exited with status $ac_status" >&5 +$as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 ( exit $ac_status ) ac_cv_opt_olimit_ok=no fi +rm -rf conftest.dSYM rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext conftest.$ac_objext conftest.$ac_ext fi @@ -4902,8 +5488,8 @@ CC="$ac_save_cc" fi -{ echo "$as_me:$LINENO: result: $ac_cv_opt_olimit_ok" >&5 -echo "${ECHO_T}$ac_cv_opt_olimit_ok" >&6; } +{ $as_echo "$as_me:$LINENO: result: $ac_cv_opt_olimit_ok" >&5 +$as_echo "$ac_cv_opt_olimit_ok" >&6; } if test $ac_cv_opt_olimit_ok = yes; then case $ac_sys_system in # XXX is this branch needed? On MacOSX 10.2.2 the result of the @@ -4916,10 +5502,10 @@ ;; esac else - { echo "$as_me:$LINENO: checking whether $CC accepts -Olimit 1500" >&5 -echo $ECHO_N "checking whether $CC accepts -Olimit 1500... $ECHO_C" >&6; } + { $as_echo "$as_me:$LINENO: checking whether $CC accepts -Olimit 1500" >&5 +$as_echo_n "checking whether $CC accepts -Olimit 1500... " >&6; } if test "${ac_cv_olimit_ok+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 + $as_echo_n "(cached) " >&6 else ac_save_cc="$CC" CC="$CC -Olimit 1500" @@ -4940,29 +5526,32 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_link") 2>&5 ac_status=$? - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { ac_try='./conftest$ac_exeext' { (case "(($ac_try" in *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_try") 2>&5 ac_status=$? - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); }; }; then ac_cv_olimit_ok=yes else - echo "$as_me: program exited with status $ac_status" >&5 -echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: program exited with status $ac_status" >&5 +$as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 ( exit $ac_status ) ac_cv_olimit_ok=no fi +rm -rf conftest.dSYM rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext conftest.$ac_objext conftest.$ac_ext fi @@ -4970,8 +5559,8 @@ CC="$ac_save_cc" fi - { echo "$as_me:$LINENO: result: $ac_cv_olimit_ok" >&5 -echo "${ECHO_T}$ac_cv_olimit_ok" >&6; } + { $as_echo "$as_me:$LINENO: result: $ac_cv_olimit_ok" >&5 +$as_echo "$ac_cv_olimit_ok" >&6; } if test $ac_cv_olimit_ok = yes; then BASECFLAGS="$BASECFLAGS -Olimit 1500" fi @@ -4980,8 +5569,8 @@ # Check whether GCC supports PyArg_ParseTuple format if test "$GCC" = "yes" then - { echo "$as_me:$LINENO: checking whether gcc supports ParseTuple __format__" >&5 -echo $ECHO_N "checking whether gcc supports ParseTuple __format__... $ECHO_C" >&6; } + { $as_echo "$as_me:$LINENO: checking whether gcc supports ParseTuple __format__" >&5 +$as_echo_n "checking whether gcc supports ParseTuple __format__... " >&6; } save_CFLAGS=$CFLAGS CFLAGS="$CFLAGS -Werror" cat >conftest.$ac_ext <<_ACEOF @@ -5007,13 +5596,14 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_compile") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { test -z "$ac_c_werror_flag" || test ! -s conftest.err @@ -5023,14 +5613,14 @@ #define HAVE_ATTRIBUTE_FORMAT_PARSETUPLE 1 _ACEOF - { echo "$as_me:$LINENO: result: yes" >&5 -echo "${ECHO_T}yes" >&6; } + { $as_echo "$as_me:$LINENO: result: yes" >&5 +$as_echo "yes" >&6; } else - echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 - { echo "$as_me:$LINENO: result: no" >&5 -echo "${ECHO_T}no" >&6; } + { $as_echo "$as_me:$LINENO: result: no" >&5 +$as_echo "no" >&6; } fi @@ -5043,10 +5633,10 @@ # complain if unaccepted options are passed (e.g. gcc on Mac OS X). # So we have to see first whether pthreads are available without # options before we can check whether -Kpthread improves anything. -{ echo "$as_me:$LINENO: checking whether pthreads are available without options" >&5 -echo $ECHO_N "checking whether pthreads are available without options... $ECHO_C" >&6; } +{ $as_echo "$as_me:$LINENO: checking whether pthreads are available without options" >&5 +$as_echo_n "checking whether pthreads are available without options... " >&6; } if test "${ac_cv_pthread_is_default+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 + $as_echo_n "(cached) " >&6 else if test "$cross_compiling" = yes; then ac_cv_pthread_is_default=no @@ -5077,19 +5667,21 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_link") 2>&5 ac_status=$? - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { ac_try='./conftest$ac_exeext' { (case "(($ac_try" in *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_try") 2>&5 ac_status=$? - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); }; }; then ac_cv_pthread_is_default=yes @@ -5097,13 +5689,14 @@ ac_cv_pthread=no else - echo "$as_me: program exited with status $ac_status" >&5 -echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: program exited with status $ac_status" >&5 +$as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 ( exit $ac_status ) ac_cv_pthread_is_default=no fi +rm -rf conftest.dSYM rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext conftest.$ac_objext conftest.$ac_ext fi @@ -5111,8 +5704,8 @@ fi -{ echo "$as_me:$LINENO: result: $ac_cv_pthread_is_default" >&5 -echo "${ECHO_T}$ac_cv_pthread_is_default" >&6; } +{ $as_echo "$as_me:$LINENO: result: $ac_cv_pthread_is_default" >&5 +$as_echo "$ac_cv_pthread_is_default" >&6; } if test $ac_cv_pthread_is_default = yes @@ -5124,10 +5717,10 @@ # Some compilers won't report that they do not support -Kpthread, # so we need to run a program to see whether it really made the # function available. -{ echo "$as_me:$LINENO: checking whether $CC accepts -Kpthread" >&5 -echo $ECHO_N "checking whether $CC accepts -Kpthread... $ECHO_C" >&6; } +{ $as_echo "$as_me:$LINENO: checking whether $CC accepts -Kpthread" >&5 +$as_echo_n "checking whether $CC accepts -Kpthread... " >&6; } if test "${ac_cv_kpthread+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 + $as_echo_n "(cached) " >&6 else ac_save_cc="$CC" CC="$CC -Kpthread" @@ -5160,29 +5753,32 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_link") 2>&5 ac_status=$? - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { ac_try='./conftest$ac_exeext' { (case "(($ac_try" in *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_try") 2>&5 ac_status=$? - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); }; }; then ac_cv_kpthread=yes else - echo "$as_me: program exited with status $ac_status" >&5 -echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: program exited with status $ac_status" >&5 +$as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 ( exit $ac_status ) ac_cv_kpthread=no fi +rm -rf conftest.dSYM rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext conftest.$ac_objext conftest.$ac_ext fi @@ -5190,8 +5786,8 @@ CC="$ac_save_cc" fi -{ echo "$as_me:$LINENO: result: $ac_cv_kpthread" >&5 -echo "${ECHO_T}$ac_cv_kpthread" >&6; } +{ $as_echo "$as_me:$LINENO: result: $ac_cv_kpthread" >&5 +$as_echo "$ac_cv_kpthread" >&6; } fi if test $ac_cv_kpthread = no -a $ac_cv_pthread_is_default = no @@ -5201,10 +5797,10 @@ # Some compilers won't report that they do not support -Kthread, # so we need to run a program to see whether it really made the # function available. -{ echo "$as_me:$LINENO: checking whether $CC accepts -Kthread" >&5 -echo $ECHO_N "checking whether $CC accepts -Kthread... $ECHO_C" >&6; } +{ $as_echo "$as_me:$LINENO: checking whether $CC accepts -Kthread" >&5 +$as_echo_n "checking whether $CC accepts -Kthread... " >&6; } if test "${ac_cv_kthread+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 + $as_echo_n "(cached) " >&6 else ac_save_cc="$CC" CC="$CC -Kthread" @@ -5237,29 +5833,32 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_link") 2>&5 ac_status=$? - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { ac_try='./conftest$ac_exeext' { (case "(($ac_try" in *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_try") 2>&5 ac_status=$? - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); }; }; then ac_cv_kthread=yes else - echo "$as_me: program exited with status $ac_status" >&5 -echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: program exited with status $ac_status" >&5 +$as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 ( exit $ac_status ) ac_cv_kthread=no fi +rm -rf conftest.dSYM rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext conftest.$ac_objext conftest.$ac_ext fi @@ -5267,8 +5866,8 @@ CC="$ac_save_cc" fi -{ echo "$as_me:$LINENO: result: $ac_cv_kthread" >&5 -echo "${ECHO_T}$ac_cv_kthread" >&6; } +{ $as_echo "$as_me:$LINENO: result: $ac_cv_kthread" >&5 +$as_echo "$ac_cv_kthread" >&6; } fi if test $ac_cv_kthread = no -a $ac_cv_pthread_is_default = no @@ -5278,10 +5877,10 @@ # Some compilers won't report that they do not support -pthread, # so we need to run a program to see whether it really made the # function available. -{ echo "$as_me:$LINENO: checking whether $CC accepts -pthread" >&5 -echo $ECHO_N "checking whether $CC accepts -pthread... $ECHO_C" >&6; } +{ $as_echo "$as_me:$LINENO: checking whether $CC accepts -pthread" >&5 +$as_echo_n "checking whether $CC accepts -pthread... " >&6; } if test "${ac_cv_thread+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 + $as_echo_n "(cached) " >&6 else ac_save_cc="$CC" CC="$CC -pthread" @@ -5314,29 +5913,32 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_link") 2>&5 ac_status=$? - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { ac_try='./conftest$ac_exeext' { (case "(($ac_try" in *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_try") 2>&5 ac_status=$? - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); }; }; then ac_cv_pthread=yes else - echo "$as_me: program exited with status $ac_status" >&5 -echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: program exited with status $ac_status" >&5 +$as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 ( exit $ac_status ) ac_cv_pthread=no fi +rm -rf conftest.dSYM rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext conftest.$ac_objext conftest.$ac_ext fi @@ -5344,8 +5946,8 @@ CC="$ac_save_cc" fi -{ echo "$as_me:$LINENO: result: $ac_cv_pthread" >&5 -echo "${ECHO_T}$ac_cv_pthread" >&6; } +{ $as_echo "$as_me:$LINENO: result: $ac_cv_pthread" >&5 +$as_echo "$ac_cv_pthread" >&6; } fi # If we have set a CC compiler flag for thread support then @@ -5353,8 +5955,8 @@ ac_cv_cxx_thread=no if test ! -z "$CXX" then -{ echo "$as_me:$LINENO: checking whether $CXX also accepts flags for thread support" >&5 -echo $ECHO_N "checking whether $CXX also accepts flags for thread support... $ECHO_C" >&6; } +{ $as_echo "$as_me:$LINENO: checking whether $CXX also accepts flags for thread support" >&5 +$as_echo_n "checking whether $CXX also accepts flags for thread support... " >&6; } ac_save_cxx="$CXX" if test "$ac_cv_kpthread" = "yes" @@ -5384,17 +5986,17 @@ fi rm -fr conftest* fi -{ echo "$as_me:$LINENO: result: $ac_cv_cxx_thread" >&5 -echo "${ECHO_T}$ac_cv_cxx_thread" >&6; } +{ $as_echo "$as_me:$LINENO: result: $ac_cv_cxx_thread" >&5 +$as_echo "$ac_cv_cxx_thread" >&6; } fi CXX="$ac_save_cxx" # checks for header files -{ echo "$as_me:$LINENO: checking for ANSI C header files" >&5 -echo $ECHO_N "checking for ANSI C header files... $ECHO_C" >&6; } +{ $as_echo "$as_me:$LINENO: checking for ANSI C header files" >&5 +$as_echo_n "checking for ANSI C header files... " >&6; } if test "${ac_cv_header_stdc+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 + $as_echo_n "(cached) " >&6 else cat >conftest.$ac_ext <<_ACEOF /* confdefs.h. */ @@ -5421,20 +6023,21 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_compile") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { test -z "$ac_c_werror_flag" || test ! -s conftest.err } && test -s conftest.$ac_objext; then ac_cv_header_stdc=yes else - echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 ac_cv_header_stdc=no @@ -5503,136 +6106,70 @@ #else # define ISLOWER(c) \ (('a' <= (c) && (c) <= 'i') \ - || ('j' <= (c) && (c) <= 'r') \ - || ('s' <= (c) && (c) <= 'z')) -# define TOUPPER(c) (ISLOWER(c) ? ((c) | 0x40) : (c)) -#endif - -#define XOR(e, f) (((e) && !(f)) || (!(e) && (f))) -int -main () -{ - int i; - for (i = 0; i < 256; i++) - if (XOR (islower (i), ISLOWER (i)) - || toupper (i) != TOUPPER (i)) - return 2; - return 0; -} -_ACEOF -rm -f conftest$ac_exeext -if { (ac_try="$ac_link" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_link") 2>&5 - ac_status=$? - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { ac_try='./conftest$ac_exeext' - { (case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_try") 2>&5 - ac_status=$? - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); }; }; then - : -else - echo "$as_me: program exited with status $ac_status" >&5 -echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - -( exit $ac_status ) -ac_cv_header_stdc=no -fi -rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext conftest.$ac_objext conftest.$ac_ext -fi - - -fi -fi -{ echo "$as_me:$LINENO: result: $ac_cv_header_stdc" >&5 -echo "${ECHO_T}$ac_cv_header_stdc" >&6; } -if test $ac_cv_header_stdc = yes; then - -cat >>confdefs.h <<\_ACEOF -#define STDC_HEADERS 1 -_ACEOF - -fi - -# On IRIX 5.3, sys/types and inttypes.h are conflicting. - - - - - - - - - -for ac_header in sys/types.h sys/stat.h stdlib.h string.h memory.h strings.h \ - inttypes.h stdint.h unistd.h -do -as_ac_Header=`echo "ac_cv_header_$ac_header" | $as_tr_sh` -{ echo "$as_me:$LINENO: checking for $ac_header" >&5 -echo $ECHO_N "checking for $ac_header... $ECHO_C" >&6; } -if { as_var=$as_ac_Header; eval "test \"\${$as_var+set}\" = set"; }; then - echo $ECHO_N "(cached) $ECHO_C" >&6 -else - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -$ac_includes_default + || ('j' <= (c) && (c) <= 'r') \ + || ('s' <= (c) && (c) <= 'z')) +# define TOUPPER(c) (ISLOWER(c) ? ((c) | 0x40) : (c)) +#endif -#include <$ac_header> +#define XOR(e, f) (((e) && !(f)) || (!(e) && (f))) +int +main () +{ + int i; + for (i = 0; i < 256; i++) + if (XOR (islower (i), ISLOWER (i)) + || toupper (i) != TOUPPER (i)) + return 2; + return 0; +} _ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" +rm -f conftest$ac_exeext +if { (ac_try="$ac_link" case "(($ac_try" in *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_compile") 2>conftest.er1 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 + (eval "$ac_link") 2>&5 ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - eval "$as_ac_Header=yes" + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 + (exit $ac_status); } && { ac_try='./conftest$ac_exeext' + { (case "(($ac_try" in + *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; + *) ac_try_echo=$ac_try;; +esac +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 + (eval "$ac_try") 2>&5 + ac_status=$? + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 + (exit $ac_status); }; }; then + : else - echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: program exited with status $ac_status" >&5 +$as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 - eval "$as_ac_Header=no" +( exit $ac_status ) +ac_cv_header_stdc=no fi - -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext +rm -rf conftest.dSYM +rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext conftest.$ac_objext conftest.$ac_ext fi -ac_res=`eval echo '${'$as_ac_Header'}'` - { echo "$as_me:$LINENO: result: $ac_res" >&5 -echo "${ECHO_T}$ac_res" >&6; } -if test `eval echo '${'$as_ac_Header'}'` = yes; then - cat >>confdefs.h <<_ACEOF -#define `echo "HAVE_$ac_header" | $as_tr_cpp` 1 -_ACEOF + fi +fi +{ $as_echo "$as_me:$LINENO: result: $ac_cv_header_stdc" >&5 +$as_echo "$ac_cv_header_stdc" >&6; } +if test $ac_cv_header_stdc = yes; then -done +cat >>confdefs.h <<\_ACEOF +#define STDC_HEADERS 1 +_ACEOF +fi @@ -5701,20 +6238,21 @@ sys/resource.h netpacket/packet.h sysexits.h bluetooth.h \ bluetooth/bluetooth.h linux/tipc.h do -as_ac_Header=`echo "ac_cv_header_$ac_header" | $as_tr_sh` +as_ac_Header=`$as_echo "ac_cv_header_$ac_header" | $as_tr_sh` if { as_var=$as_ac_Header; eval "test \"\${$as_var+set}\" = set"; }; then - { echo "$as_me:$LINENO: checking for $ac_header" >&5 -echo $ECHO_N "checking for $ac_header... $ECHO_C" >&6; } + { $as_echo "$as_me:$LINENO: checking for $ac_header" >&5 +$as_echo_n "checking for $ac_header... " >&6; } if { as_var=$as_ac_Header; eval "test \"\${$as_var+set}\" = set"; }; then - echo $ECHO_N "(cached) $ECHO_C" >&6 + $as_echo_n "(cached) " >&6 fi -ac_res=`eval echo '${'$as_ac_Header'}'` - { echo "$as_me:$LINENO: result: $ac_res" >&5 -echo "${ECHO_T}$ac_res" >&6; } +ac_res=`eval 'as_val=${'$as_ac_Header'} + $as_echo "$as_val"'` + { $as_echo "$as_me:$LINENO: result: $ac_res" >&5 +$as_echo "$ac_res" >&6; } else # Is the header compilable? -{ echo "$as_me:$LINENO: checking $ac_header usability" >&5 -echo $ECHO_N "checking $ac_header usability... $ECHO_C" >&6; } +{ $as_echo "$as_me:$LINENO: checking $ac_header usability" >&5 +$as_echo_n "checking $ac_header usability... " >&6; } cat >conftest.$ac_ext <<_ACEOF /* confdefs.h. */ _ACEOF @@ -5730,32 +6268,33 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_compile") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { test -z "$ac_c_werror_flag" || test ! -s conftest.err } && test -s conftest.$ac_objext; then ac_header_compiler=yes else - echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 ac_header_compiler=no fi rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext -{ echo "$as_me:$LINENO: result: $ac_header_compiler" >&5 -echo "${ECHO_T}$ac_header_compiler" >&6; } +{ $as_echo "$as_me:$LINENO: result: $ac_header_compiler" >&5 +$as_echo "$ac_header_compiler" >&6; } # Is the header present? -{ echo "$as_me:$LINENO: checking $ac_header presence" >&5 -echo $ECHO_N "checking $ac_header presence... $ECHO_C" >&6; } +{ $as_echo "$as_me:$LINENO: checking $ac_header presence" >&5 +$as_echo_n "checking $ac_header presence... " >&6; } cat >conftest.$ac_ext <<_ACEOF /* confdefs.h. */ _ACEOF @@ -5769,51 +6308,52 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_cpp conftest.$ac_ext") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } >/dev/null && { test -z "$ac_c_preproc_warn_flag$ac_c_werror_flag" || test ! -s conftest.err }; then ac_header_preproc=yes else - echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 ac_header_preproc=no fi rm -f conftest.err conftest.$ac_ext -{ echo "$as_me:$LINENO: result: $ac_header_preproc" >&5 -echo "${ECHO_T}$ac_header_preproc" >&6; } +{ $as_echo "$as_me:$LINENO: result: $ac_header_preproc" >&5 +$as_echo "$ac_header_preproc" >&6; } # So? What about this header? case $ac_header_compiler:$ac_header_preproc:$ac_c_preproc_warn_flag in yes:no: ) - { echo "$as_me:$LINENO: WARNING: $ac_header: accepted by the compiler, rejected by the preprocessor!" >&5 -echo "$as_me: WARNING: $ac_header: accepted by the compiler, rejected by the preprocessor!" >&2;} - { echo "$as_me:$LINENO: WARNING: $ac_header: proceeding with the compiler's result" >&5 -echo "$as_me: WARNING: $ac_header: proceeding with the compiler's result" >&2;} + { $as_echo "$as_me:$LINENO: WARNING: $ac_header: accepted by the compiler, rejected by the preprocessor!" >&5 +$as_echo "$as_me: WARNING: $ac_header: accepted by the compiler, rejected by the preprocessor!" >&2;} + { $as_echo "$as_me:$LINENO: WARNING: $ac_header: proceeding with the compiler's result" >&5 +$as_echo "$as_me: WARNING: $ac_header: proceeding with the compiler's result" >&2;} ac_header_preproc=yes ;; no:yes:* ) - { echo "$as_me:$LINENO: WARNING: $ac_header: present but cannot be compiled" >&5 -echo "$as_me: WARNING: $ac_header: present but cannot be compiled" >&2;} - { echo "$as_me:$LINENO: WARNING: $ac_header: check for missing prerequisite headers?" >&5 -echo "$as_me: WARNING: $ac_header: check for missing prerequisite headers?" >&2;} - { echo "$as_me:$LINENO: WARNING: $ac_header: see the Autoconf documentation" >&5 -echo "$as_me: WARNING: $ac_header: see the Autoconf documentation" >&2;} - { echo "$as_me:$LINENO: WARNING: $ac_header: section \"Present But Cannot Be Compiled\"" >&5 -echo "$as_me: WARNING: $ac_header: section \"Present But Cannot Be Compiled\"" >&2;} - { echo "$as_me:$LINENO: WARNING: $ac_header: proceeding with the preprocessor's result" >&5 -echo "$as_me: WARNING: $ac_header: proceeding with the preprocessor's result" >&2;} - { echo "$as_me:$LINENO: WARNING: $ac_header: in the future, the compiler will take precedence" >&5 -echo "$as_me: WARNING: $ac_header: in the future, the compiler will take precedence" >&2;} + { $as_echo "$as_me:$LINENO: WARNING: $ac_header: present but cannot be compiled" >&5 +$as_echo "$as_me: WARNING: $ac_header: present but cannot be compiled" >&2;} + { $as_echo "$as_me:$LINENO: WARNING: $ac_header: check for missing prerequisite headers?" >&5 +$as_echo "$as_me: WARNING: $ac_header: check for missing prerequisite headers?" >&2;} + { $as_echo "$as_me:$LINENO: WARNING: $ac_header: see the Autoconf documentation" >&5 +$as_echo "$as_me: WARNING: $ac_header: see the Autoconf documentation" >&2;} + { $as_echo "$as_me:$LINENO: WARNING: $ac_header: section \"Present But Cannot Be Compiled\"" >&5 +$as_echo "$as_me: WARNING: $ac_header: section \"Present But Cannot Be Compiled\"" >&2;} + { $as_echo "$as_me:$LINENO: WARNING: $ac_header: proceeding with the preprocessor's result" >&5 +$as_echo "$as_me: WARNING: $ac_header: proceeding with the preprocessor's result" >&2;} + { $as_echo "$as_me:$LINENO: WARNING: $ac_header: in the future, the compiler will take precedence" >&5 +$as_echo "$as_me: WARNING: $ac_header: in the future, the compiler will take precedence" >&2;} ( cat <<\_ASBOX ## ------------------------------------------------ ## ## Report this to http://www.python.org/python-bugs ## @@ -5822,21 +6362,24 @@ ) | sed "s/^/$as_me: WARNING: /" >&2 ;; esac -{ echo "$as_me:$LINENO: checking for $ac_header" >&5 -echo $ECHO_N "checking for $ac_header... $ECHO_C" >&6; } +{ $as_echo "$as_me:$LINENO: checking for $ac_header" >&5 +$as_echo_n "checking for $ac_header... " >&6; } if { as_var=$as_ac_Header; eval "test \"\${$as_var+set}\" = set"; }; then - echo $ECHO_N "(cached) $ECHO_C" >&6 + $as_echo_n "(cached) " >&6 else eval "$as_ac_Header=\$ac_header_preproc" fi -ac_res=`eval echo '${'$as_ac_Header'}'` - { echo "$as_me:$LINENO: result: $ac_res" >&5 -echo "${ECHO_T}$ac_res" >&6; } +ac_res=`eval 'as_val=${'$as_ac_Header'} + $as_echo "$as_val"'` + { $as_echo "$as_me:$LINENO: result: $ac_res" >&5 +$as_echo "$ac_res" >&6; } fi -if test `eval echo '${'$as_ac_Header'}'` = yes; then +as_val=`eval 'as_val=${'$as_ac_Header'} + $as_echo "$as_val"'` + if test "x$as_val" = x""yes; then cat >>confdefs.h <<_ACEOF -#define `echo "HAVE_$ac_header" | $as_tr_cpp` 1 +#define `$as_echo "HAVE_$ac_header" | $as_tr_cpp` 1 _ACEOF fi @@ -5850,11 +6393,11 @@ ac_header_dirent=no for ac_hdr in dirent.h sys/ndir.h sys/dir.h ndir.h; do - as_ac_Header=`echo "ac_cv_header_dirent_$ac_hdr" | $as_tr_sh` -{ echo "$as_me:$LINENO: checking for $ac_hdr that defines DIR" >&5 -echo $ECHO_N "checking for $ac_hdr that defines DIR... $ECHO_C" >&6; } + as_ac_Header=`$as_echo "ac_cv_header_dirent_$ac_hdr" | $as_tr_sh` +{ $as_echo "$as_me:$LINENO: checking for $ac_hdr that defines DIR" >&5 +$as_echo_n "checking for $ac_hdr that defines DIR... " >&6; } if { as_var=$as_ac_Header; eval "test \"\${$as_var+set}\" = set"; }; then - echo $ECHO_N "(cached) $ECHO_C" >&6 + $as_echo_n "(cached) " >&6 else cat >conftest.$ac_ext <<_ACEOF /* confdefs.h. */ @@ -5880,20 +6423,21 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_compile") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { test -z "$ac_c_werror_flag" || test ! -s conftest.err } && test -s conftest.$ac_objext; then eval "$as_ac_Header=yes" else - echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 eval "$as_ac_Header=no" @@ -5901,12 +6445,15 @@ rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext fi -ac_res=`eval echo '${'$as_ac_Header'}'` - { echo "$as_me:$LINENO: result: $ac_res" >&5 -echo "${ECHO_T}$ac_res" >&6; } -if test `eval echo '${'$as_ac_Header'}'` = yes; then +ac_res=`eval 'as_val=${'$as_ac_Header'} + $as_echo "$as_val"'` + { $as_echo "$as_me:$LINENO: result: $ac_res" >&5 +$as_echo "$ac_res" >&6; } +as_val=`eval 'as_val=${'$as_ac_Header'} + $as_echo "$as_val"'` + if test "x$as_val" = x""yes; then cat >>confdefs.h <<_ACEOF -#define `echo "HAVE_$ac_hdr" | $as_tr_cpp` 1 +#define `$as_echo "HAVE_$ac_hdr" | $as_tr_cpp` 1 _ACEOF ac_header_dirent=$ac_hdr; break @@ -5915,10 +6462,10 @@ done # Two versions of opendir et al. are in -ldir and -lx on SCO Xenix. if test $ac_header_dirent = dirent.h; then - { echo "$as_me:$LINENO: checking for library containing opendir" >&5 -echo $ECHO_N "checking for library containing opendir... $ECHO_C" >&6; } + { $as_echo "$as_me:$LINENO: checking for library containing opendir" >&5 +$as_echo_n "checking for library containing opendir... " >&6; } if test "${ac_cv_search_opendir+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 + $as_echo_n "(cached) " >&6 else ac_func_search_save_LIBS=$LIBS cat >conftest.$ac_ext <<_ACEOF @@ -5956,26 +6503,30 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_link") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { test -z "$ac_c_werror_flag" || test ! -s conftest.err - } && test -s conftest$ac_exeext && - $as_test_x conftest$ac_exeext; then + } && test -s conftest$ac_exeext && { + test "$cross_compiling" = yes || + $as_test_x conftest$ac_exeext + }; then ac_cv_search_opendir=$ac_res else - echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 fi +rm -rf conftest.dSYM rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \ conftest$ac_exeext if test "${ac_cv_search_opendir+set}" = set; then @@ -5990,8 +6541,8 @@ rm conftest.$ac_ext LIBS=$ac_func_search_save_LIBS fi -{ echo "$as_me:$LINENO: result: $ac_cv_search_opendir" >&5 -echo "${ECHO_T}$ac_cv_search_opendir" >&6; } +{ $as_echo "$as_me:$LINENO: result: $ac_cv_search_opendir" >&5 +$as_echo "$ac_cv_search_opendir" >&6; } ac_res=$ac_cv_search_opendir if test "$ac_res" != no; then test "$ac_res" = "none required" || LIBS="$ac_res $LIBS" @@ -5999,10 +6550,10 @@ fi else - { echo "$as_me:$LINENO: checking for library containing opendir" >&5 -echo $ECHO_N "checking for library containing opendir... $ECHO_C" >&6; } + { $as_echo "$as_me:$LINENO: checking for library containing opendir" >&5 +$as_echo_n "checking for library containing opendir... " >&6; } if test "${ac_cv_search_opendir+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 + $as_echo_n "(cached) " >&6 else ac_func_search_save_LIBS=$LIBS cat >conftest.$ac_ext <<_ACEOF @@ -6040,26 +6591,30 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_link") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { test -z "$ac_c_werror_flag" || test ! -s conftest.err - } && test -s conftest$ac_exeext && - $as_test_x conftest$ac_exeext; then + } && test -s conftest$ac_exeext && { + test "$cross_compiling" = yes || + $as_test_x conftest$ac_exeext + }; then ac_cv_search_opendir=$ac_res else - echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 fi +rm -rf conftest.dSYM rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \ conftest$ac_exeext if test "${ac_cv_search_opendir+set}" = set; then @@ -6074,8 +6629,8 @@ rm conftest.$ac_ext LIBS=$ac_func_search_save_LIBS fi -{ echo "$as_me:$LINENO: result: $ac_cv_search_opendir" >&5 -echo "${ECHO_T}$ac_cv_search_opendir" >&6; } +{ $as_echo "$as_me:$LINENO: result: $ac_cv_search_opendir" >&5 +$as_echo "$ac_cv_search_opendir" >&6; } ac_res=$ac_cv_search_opendir if test "$ac_res" != no; then test "$ac_res" = "none required" || LIBS="$ac_res $LIBS" @@ -6084,10 +6639,10 @@ fi -{ echo "$as_me:$LINENO: checking whether sys/types.h defines makedev" >&5 -echo $ECHO_N "checking whether sys/types.h defines makedev... $ECHO_C" >&6; } +{ $as_echo "$as_me:$LINENO: checking whether sys/types.h defines makedev" >&5 +$as_echo_n "checking whether sys/types.h defines makedev... " >&6; } if test "${ac_cv_header_sys_types_h_makedev+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 + $as_echo_n "(cached) " >&6 else cat >conftest.$ac_ext <<_ACEOF /* confdefs.h. */ @@ -6110,46 +6665,50 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_link") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { test -z "$ac_c_werror_flag" || test ! -s conftest.err - } && test -s conftest$ac_exeext && - $as_test_x conftest$ac_exeext; then + } && test -s conftest$ac_exeext && { + test "$cross_compiling" = yes || + $as_test_x conftest$ac_exeext + }; then ac_cv_header_sys_types_h_makedev=yes else - echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 ac_cv_header_sys_types_h_makedev=no fi +rm -rf conftest.dSYM rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \ conftest$ac_exeext conftest.$ac_ext fi -{ echo "$as_me:$LINENO: result: $ac_cv_header_sys_types_h_makedev" >&5 -echo "${ECHO_T}$ac_cv_header_sys_types_h_makedev" >&6; } +{ $as_echo "$as_me:$LINENO: result: $ac_cv_header_sys_types_h_makedev" >&5 +$as_echo "$ac_cv_header_sys_types_h_makedev" >&6; } if test $ac_cv_header_sys_types_h_makedev = no; then if test "${ac_cv_header_sys_mkdev_h+set}" = set; then - { echo "$as_me:$LINENO: checking for sys/mkdev.h" >&5 -echo $ECHO_N "checking for sys/mkdev.h... $ECHO_C" >&6; } + { $as_echo "$as_me:$LINENO: checking for sys/mkdev.h" >&5 +$as_echo_n "checking for sys/mkdev.h... " >&6; } if test "${ac_cv_header_sys_mkdev_h+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 + $as_echo_n "(cached) " >&6 fi -{ echo "$as_me:$LINENO: result: $ac_cv_header_sys_mkdev_h" >&5 -echo "${ECHO_T}$ac_cv_header_sys_mkdev_h" >&6; } +{ $as_echo "$as_me:$LINENO: result: $ac_cv_header_sys_mkdev_h" >&5 +$as_echo "$ac_cv_header_sys_mkdev_h" >&6; } else # Is the header compilable? -{ echo "$as_me:$LINENO: checking sys/mkdev.h usability" >&5 -echo $ECHO_N "checking sys/mkdev.h usability... $ECHO_C" >&6; } +{ $as_echo "$as_me:$LINENO: checking sys/mkdev.h usability" >&5 +$as_echo_n "checking sys/mkdev.h usability... " >&6; } cat >conftest.$ac_ext <<_ACEOF /* confdefs.h. */ _ACEOF @@ -6165,32 +6724,33 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_compile") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { test -z "$ac_c_werror_flag" || test ! -s conftest.err } && test -s conftest.$ac_objext; then ac_header_compiler=yes else - echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 ac_header_compiler=no fi rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext -{ echo "$as_me:$LINENO: result: $ac_header_compiler" >&5 -echo "${ECHO_T}$ac_header_compiler" >&6; } +{ $as_echo "$as_me:$LINENO: result: $ac_header_compiler" >&5 +$as_echo "$ac_header_compiler" >&6; } # Is the header present? -{ echo "$as_me:$LINENO: checking sys/mkdev.h presence" >&5 -echo $ECHO_N "checking sys/mkdev.h presence... $ECHO_C" >&6; } +{ $as_echo "$as_me:$LINENO: checking sys/mkdev.h presence" >&5 +$as_echo_n "checking sys/mkdev.h presence... " >&6; } cat >conftest.$ac_ext <<_ACEOF /* confdefs.h. */ _ACEOF @@ -6204,51 +6764,52 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_cpp conftest.$ac_ext") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } >/dev/null && { test -z "$ac_c_preproc_warn_flag$ac_c_werror_flag" || test ! -s conftest.err }; then ac_header_preproc=yes else - echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 ac_header_preproc=no fi rm -f conftest.err conftest.$ac_ext -{ echo "$as_me:$LINENO: result: $ac_header_preproc" >&5 -echo "${ECHO_T}$ac_header_preproc" >&6; } +{ $as_echo "$as_me:$LINENO: result: $ac_header_preproc" >&5 +$as_echo "$ac_header_preproc" >&6; } # So? What about this header? case $ac_header_compiler:$ac_header_preproc:$ac_c_preproc_warn_flag in yes:no: ) - { echo "$as_me:$LINENO: WARNING: sys/mkdev.h: accepted by the compiler, rejected by the preprocessor!" >&5 -echo "$as_me: WARNING: sys/mkdev.h: accepted by the compiler, rejected by the preprocessor!" >&2;} - { echo "$as_me:$LINENO: WARNING: sys/mkdev.h: proceeding with the compiler's result" >&5 -echo "$as_me: WARNING: sys/mkdev.h: proceeding with the compiler's result" >&2;} + { $as_echo "$as_me:$LINENO: WARNING: sys/mkdev.h: accepted by the compiler, rejected by the preprocessor!" >&5 +$as_echo "$as_me: WARNING: sys/mkdev.h: accepted by the compiler, rejected by the preprocessor!" >&2;} + { $as_echo "$as_me:$LINENO: WARNING: sys/mkdev.h: proceeding with the compiler's result" >&5 +$as_echo "$as_me: WARNING: sys/mkdev.h: proceeding with the compiler's result" >&2;} ac_header_preproc=yes ;; no:yes:* ) - { echo "$as_me:$LINENO: WARNING: sys/mkdev.h: present but cannot be compiled" >&5 -echo "$as_me: WARNING: sys/mkdev.h: present but cannot be compiled" >&2;} - { echo "$as_me:$LINENO: WARNING: sys/mkdev.h: check for missing prerequisite headers?" >&5 -echo "$as_me: WARNING: sys/mkdev.h: check for missing prerequisite headers?" >&2;} - { echo "$as_me:$LINENO: WARNING: sys/mkdev.h: see the Autoconf documentation" >&5 -echo "$as_me: WARNING: sys/mkdev.h: see the Autoconf documentation" >&2;} - { echo "$as_me:$LINENO: WARNING: sys/mkdev.h: section \"Present But Cannot Be Compiled\"" >&5 -echo "$as_me: WARNING: sys/mkdev.h: section \"Present But Cannot Be Compiled\"" >&2;} - { echo "$as_me:$LINENO: WARNING: sys/mkdev.h: proceeding with the preprocessor's result" >&5 -echo "$as_me: WARNING: sys/mkdev.h: proceeding with the preprocessor's result" >&2;} - { echo "$as_me:$LINENO: WARNING: sys/mkdev.h: in the future, the compiler will take precedence" >&5 -echo "$as_me: WARNING: sys/mkdev.h: in the future, the compiler will take precedence" >&2;} + { $as_echo "$as_me:$LINENO: WARNING: sys/mkdev.h: present but cannot be compiled" >&5 +$as_echo "$as_me: WARNING: sys/mkdev.h: present but cannot be compiled" >&2;} + { $as_echo "$as_me:$LINENO: WARNING: sys/mkdev.h: check for missing prerequisite headers?" >&5 +$as_echo "$as_me: WARNING: sys/mkdev.h: check for missing prerequisite headers?" >&2;} + { $as_echo "$as_me:$LINENO: WARNING: sys/mkdev.h: see the Autoconf documentation" >&5 +$as_echo "$as_me: WARNING: sys/mkdev.h: see the Autoconf documentation" >&2;} + { $as_echo "$as_me:$LINENO: WARNING: sys/mkdev.h: section \"Present But Cannot Be Compiled\"" >&5 +$as_echo "$as_me: WARNING: sys/mkdev.h: section \"Present But Cannot Be Compiled\"" >&2;} + { $as_echo "$as_me:$LINENO: WARNING: sys/mkdev.h: proceeding with the preprocessor's result" >&5 +$as_echo "$as_me: WARNING: sys/mkdev.h: proceeding with the preprocessor's result" >&2;} + { $as_echo "$as_me:$LINENO: WARNING: sys/mkdev.h: in the future, the compiler will take precedence" >&5 +$as_echo "$as_me: WARNING: sys/mkdev.h: in the future, the compiler will take precedence" >&2;} ( cat <<\_ASBOX ## ------------------------------------------------ ## ## Report this to http://www.python.org/python-bugs ## @@ -6257,18 +6818,18 @@ ) | sed "s/^/$as_me: WARNING: /" >&2 ;; esac -{ echo "$as_me:$LINENO: checking for sys/mkdev.h" >&5 -echo $ECHO_N "checking for sys/mkdev.h... $ECHO_C" >&6; } +{ $as_echo "$as_me:$LINENO: checking for sys/mkdev.h" >&5 +$as_echo_n "checking for sys/mkdev.h... " >&6; } if test "${ac_cv_header_sys_mkdev_h+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 + $as_echo_n "(cached) " >&6 else ac_cv_header_sys_mkdev_h=$ac_header_preproc fi -{ echo "$as_me:$LINENO: result: $ac_cv_header_sys_mkdev_h" >&5 -echo "${ECHO_T}$ac_cv_header_sys_mkdev_h" >&6; } +{ $as_echo "$as_me:$LINENO: result: $ac_cv_header_sys_mkdev_h" >&5 +$as_echo "$ac_cv_header_sys_mkdev_h" >&6; } fi -if test $ac_cv_header_sys_mkdev_h = yes; then +if test "x$ac_cv_header_sys_mkdev_h" = x""yes; then cat >>confdefs.h <<\_ACEOF #define MAJOR_IN_MKDEV 1 @@ -6280,17 +6841,17 @@ if test $ac_cv_header_sys_mkdev_h = no; then if test "${ac_cv_header_sys_sysmacros_h+set}" = set; then - { echo "$as_me:$LINENO: checking for sys/sysmacros.h" >&5 -echo $ECHO_N "checking for sys/sysmacros.h... $ECHO_C" >&6; } + { $as_echo "$as_me:$LINENO: checking for sys/sysmacros.h" >&5 +$as_echo_n "checking for sys/sysmacros.h... " >&6; } if test "${ac_cv_header_sys_sysmacros_h+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 + $as_echo_n "(cached) " >&6 fi -{ echo "$as_me:$LINENO: result: $ac_cv_header_sys_sysmacros_h" >&5 -echo "${ECHO_T}$ac_cv_header_sys_sysmacros_h" >&6; } +{ $as_echo "$as_me:$LINENO: result: $ac_cv_header_sys_sysmacros_h" >&5 +$as_echo "$ac_cv_header_sys_sysmacros_h" >&6; } else # Is the header compilable? -{ echo "$as_me:$LINENO: checking sys/sysmacros.h usability" >&5 -echo $ECHO_N "checking sys/sysmacros.h usability... $ECHO_C" >&6; } +{ $as_echo "$as_me:$LINENO: checking sys/sysmacros.h usability" >&5 +$as_echo_n "checking sys/sysmacros.h usability... " >&6; } cat >conftest.$ac_ext <<_ACEOF /* confdefs.h. */ _ACEOF @@ -6306,32 +6867,33 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_compile") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { test -z "$ac_c_werror_flag" || test ! -s conftest.err } && test -s conftest.$ac_objext; then ac_header_compiler=yes else - echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 ac_header_compiler=no fi rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext -{ echo "$as_me:$LINENO: result: $ac_header_compiler" >&5 -echo "${ECHO_T}$ac_header_compiler" >&6; } +{ $as_echo "$as_me:$LINENO: result: $ac_header_compiler" >&5 +$as_echo "$ac_header_compiler" >&6; } # Is the header present? -{ echo "$as_me:$LINENO: checking sys/sysmacros.h presence" >&5 -echo $ECHO_N "checking sys/sysmacros.h presence... $ECHO_C" >&6; } +{ $as_echo "$as_me:$LINENO: checking sys/sysmacros.h presence" >&5 +$as_echo_n "checking sys/sysmacros.h presence... " >&6; } cat >conftest.$ac_ext <<_ACEOF /* confdefs.h. */ _ACEOF @@ -6345,51 +6907,52 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_cpp conftest.$ac_ext") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } >/dev/null && { test -z "$ac_c_preproc_warn_flag$ac_c_werror_flag" || test ! -s conftest.err }; then ac_header_preproc=yes else - echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 ac_header_preproc=no fi rm -f conftest.err conftest.$ac_ext -{ echo "$as_me:$LINENO: result: $ac_header_preproc" >&5 -echo "${ECHO_T}$ac_header_preproc" >&6; } +{ $as_echo "$as_me:$LINENO: result: $ac_header_preproc" >&5 +$as_echo "$ac_header_preproc" >&6; } # So? What about this header? case $ac_header_compiler:$ac_header_preproc:$ac_c_preproc_warn_flag in yes:no: ) - { echo "$as_me:$LINENO: WARNING: sys/sysmacros.h: accepted by the compiler, rejected by the preprocessor!" >&5 -echo "$as_me: WARNING: sys/sysmacros.h: accepted by the compiler, rejected by the preprocessor!" >&2;} - { echo "$as_me:$LINENO: WARNING: sys/sysmacros.h: proceeding with the compiler's result" >&5 -echo "$as_me: WARNING: sys/sysmacros.h: proceeding with the compiler's result" >&2;} + { $as_echo "$as_me:$LINENO: WARNING: sys/sysmacros.h: accepted by the compiler, rejected by the preprocessor!" >&5 +$as_echo "$as_me: WARNING: sys/sysmacros.h: accepted by the compiler, rejected by the preprocessor!" >&2;} + { $as_echo "$as_me:$LINENO: WARNING: sys/sysmacros.h: proceeding with the compiler's result" >&5 +$as_echo "$as_me: WARNING: sys/sysmacros.h: proceeding with the compiler's result" >&2;} ac_header_preproc=yes ;; no:yes:* ) - { echo "$as_me:$LINENO: WARNING: sys/sysmacros.h: present but cannot be compiled" >&5 -echo "$as_me: WARNING: sys/sysmacros.h: present but cannot be compiled" >&2;} - { echo "$as_me:$LINENO: WARNING: sys/sysmacros.h: check for missing prerequisite headers?" >&5 -echo "$as_me: WARNING: sys/sysmacros.h: check for missing prerequisite headers?" >&2;} - { echo "$as_me:$LINENO: WARNING: sys/sysmacros.h: see the Autoconf documentation" >&5 -echo "$as_me: WARNING: sys/sysmacros.h: see the Autoconf documentation" >&2;} - { echo "$as_me:$LINENO: WARNING: sys/sysmacros.h: section \"Present But Cannot Be Compiled\"" >&5 -echo "$as_me: WARNING: sys/sysmacros.h: section \"Present But Cannot Be Compiled\"" >&2;} - { echo "$as_me:$LINENO: WARNING: sys/sysmacros.h: proceeding with the preprocessor's result" >&5 -echo "$as_me: WARNING: sys/sysmacros.h: proceeding with the preprocessor's result" >&2;} - { echo "$as_me:$LINENO: WARNING: sys/sysmacros.h: in the future, the compiler will take precedence" >&5 -echo "$as_me: WARNING: sys/sysmacros.h: in the future, the compiler will take precedence" >&2;} + { $as_echo "$as_me:$LINENO: WARNING: sys/sysmacros.h: present but cannot be compiled" >&5 +$as_echo "$as_me: WARNING: sys/sysmacros.h: present but cannot be compiled" >&2;} + { $as_echo "$as_me:$LINENO: WARNING: sys/sysmacros.h: check for missing prerequisite headers?" >&5 +$as_echo "$as_me: WARNING: sys/sysmacros.h: check for missing prerequisite headers?" >&2;} + { $as_echo "$as_me:$LINENO: WARNING: sys/sysmacros.h: see the Autoconf documentation" >&5 +$as_echo "$as_me: WARNING: sys/sysmacros.h: see the Autoconf documentation" >&2;} + { $as_echo "$as_me:$LINENO: WARNING: sys/sysmacros.h: section \"Present But Cannot Be Compiled\"" >&5 +$as_echo "$as_me: WARNING: sys/sysmacros.h: section \"Present But Cannot Be Compiled\"" >&2;} + { $as_echo "$as_me:$LINENO: WARNING: sys/sysmacros.h: proceeding with the preprocessor's result" >&5 +$as_echo "$as_me: WARNING: sys/sysmacros.h: proceeding with the preprocessor's result" >&2;} + { $as_echo "$as_me:$LINENO: WARNING: sys/sysmacros.h: in the future, the compiler will take precedence" >&5 +$as_echo "$as_me: WARNING: sys/sysmacros.h: in the future, the compiler will take precedence" >&2;} ( cat <<\_ASBOX ## ------------------------------------------------ ## ## Report this to http://www.python.org/python-bugs ## @@ -6398,18 +6961,18 @@ ) | sed "s/^/$as_me: WARNING: /" >&2 ;; esac -{ echo "$as_me:$LINENO: checking for sys/sysmacros.h" >&5 -echo $ECHO_N "checking for sys/sysmacros.h... $ECHO_C" >&6; } +{ $as_echo "$as_me:$LINENO: checking for sys/sysmacros.h" >&5 +$as_echo_n "checking for sys/sysmacros.h... " >&6; } if test "${ac_cv_header_sys_sysmacros_h+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 + $as_echo_n "(cached) " >&6 else ac_cv_header_sys_sysmacros_h=$ac_header_preproc fi -{ echo "$as_me:$LINENO: result: $ac_cv_header_sys_sysmacros_h" >&5 -echo "${ECHO_T}$ac_cv_header_sys_sysmacros_h" >&6; } +{ $as_echo "$as_me:$LINENO: result: $ac_cv_header_sys_sysmacros_h" >&5 +$as_echo "$ac_cv_header_sys_sysmacros_h" >&6; } fi -if test $ac_cv_header_sys_sysmacros_h = yes; then +if test "x$ac_cv_header_sys_sysmacros_h" = x""yes; then cat >>confdefs.h <<\_ACEOF #define MAJOR_IN_SYSMACROS 1 @@ -6426,11 +6989,11 @@ for ac_header in term.h do -as_ac_Header=`echo "ac_cv_header_$ac_header" | $as_tr_sh` -{ echo "$as_me:$LINENO: checking for $ac_header" >&5 -echo $ECHO_N "checking for $ac_header... $ECHO_C" >&6; } +as_ac_Header=`$as_echo "ac_cv_header_$ac_header" | $as_tr_sh` +{ $as_echo "$as_me:$LINENO: checking for $ac_header" >&5 +$as_echo_n "checking for $ac_header... " >&6; } if { as_var=$as_ac_Header; eval "test \"\${$as_var+set}\" = set"; }; then - echo $ECHO_N "(cached) $ECHO_C" >&6 + $as_echo_n "(cached) " >&6 else cat >conftest.$ac_ext <<_ACEOF /* confdefs.h. */ @@ -6452,20 +7015,21 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_compile") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { test -z "$ac_c_werror_flag" || test ! -s conftest.err } && test -s conftest.$ac_objext; then eval "$as_ac_Header=yes" else - echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 eval "$as_ac_Header=no" @@ -6473,12 +7037,15 @@ rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext fi -ac_res=`eval echo '${'$as_ac_Header'}'` - { echo "$as_me:$LINENO: result: $ac_res" >&5 -echo "${ECHO_T}$ac_res" >&6; } -if test `eval echo '${'$as_ac_Header'}'` = yes; then +ac_res=`eval 'as_val=${'$as_ac_Header'} + $as_echo "$as_val"'` + { $as_echo "$as_me:$LINENO: result: $ac_res" >&5 +$as_echo "$ac_res" >&6; } +as_val=`eval 'as_val=${'$as_ac_Header'} + $as_echo "$as_val"'` + if test "x$as_val" = x""yes; then cat >>confdefs.h <<_ACEOF -#define `echo "HAVE_$ac_header" | $as_tr_cpp` 1 +#define `$as_echo "HAVE_$ac_header" | $as_tr_cpp` 1 _ACEOF fi @@ -6490,11 +7057,11 @@ for ac_header in linux/netlink.h do -as_ac_Header=`echo "ac_cv_header_$ac_header" | $as_tr_sh` -{ echo "$as_me:$LINENO: checking for $ac_header" >&5 -echo $ECHO_N "checking for $ac_header... $ECHO_C" >&6; } +as_ac_Header=`$as_echo "ac_cv_header_$ac_header" | $as_tr_sh` +{ $as_echo "$as_me:$LINENO: checking for $ac_header" >&5 +$as_echo_n "checking for $ac_header... " >&6; } if { as_var=$as_ac_Header; eval "test \"\${$as_var+set}\" = set"; }; then - echo $ECHO_N "(cached) $ECHO_C" >&6 + $as_echo_n "(cached) " >&6 else cat >conftest.$ac_ext <<_ACEOF /* confdefs.h. */ @@ -6519,20 +7086,21 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_compile") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { test -z "$ac_c_werror_flag" || test ! -s conftest.err } && test -s conftest.$ac_objext; then eval "$as_ac_Header=yes" else - echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 eval "$as_ac_Header=no" @@ -6540,12 +7108,15 @@ rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext fi -ac_res=`eval echo '${'$as_ac_Header'}'` - { echo "$as_me:$LINENO: result: $ac_res" >&5 -echo "${ECHO_T}$ac_res" >&6; } -if test `eval echo '${'$as_ac_Header'}'` = yes; then +ac_res=`eval 'as_val=${'$as_ac_Header'} + $as_echo "$as_val"'` + { $as_echo "$as_me:$LINENO: result: $ac_res" >&5 +$as_echo "$ac_res" >&6; } +as_val=`eval 'as_val=${'$as_ac_Header'} + $as_echo "$as_val"'` + if test "x$as_val" = x""yes; then cat >>confdefs.h <<_ACEOF -#define `echo "HAVE_$ac_header" | $as_tr_cpp` 1 +#define `$as_echo "HAVE_$ac_header" | $as_tr_cpp` 1 _ACEOF fi @@ -6555,8 +7126,8 @@ # checks for typedefs was_it_defined=no -{ echo "$as_me:$LINENO: checking for clock_t in time.h" >&5 -echo $ECHO_N "checking for clock_t in time.h... $ECHO_C" >&6; } +{ $as_echo "$as_me:$LINENO: checking for clock_t in time.h" >&5 +$as_echo_n "checking for clock_t in time.h... " >&6; } cat >conftest.$ac_ext <<_ACEOF /* confdefs.h. */ _ACEOF @@ -6580,12 +7151,12 @@ fi rm -f conftest* -{ echo "$as_me:$LINENO: result: $was_it_defined" >&5 -echo "${ECHO_T}$was_it_defined" >&6; } +{ $as_echo "$as_me:$LINENO: result: $was_it_defined" >&5 +$as_echo "$was_it_defined" >&6; } # Check whether using makedev requires defining _OSF_SOURCE -{ echo "$as_me:$LINENO: checking for makedev" >&5 -echo $ECHO_N "checking for makedev... $ECHO_C" >&6; } +{ $as_echo "$as_me:$LINENO: checking for makedev" >&5 +$as_echo_n "checking for makedev... " >&6; } cat >conftest.$ac_ext <<_ACEOF /* confdefs.h. */ _ACEOF @@ -6614,26 +7185,30 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_link") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { test -z "$ac_c_werror_flag" || test ! -s conftest.err - } && test -s conftest$ac_exeext && - $as_test_x conftest$ac_exeext; then + } && test -s conftest$ac_exeext && { + test "$cross_compiling" = yes || + $as_test_x conftest$ac_exeext + }; then ac_cv_has_makedev=yes else - echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 ac_cv_has_makedev=no fi +rm -rf conftest.dSYM rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \ conftest$ac_exeext conftest.$ac_ext if test "$ac_cv_has_makedev" = "no"; then @@ -6662,26 +7237,30 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_link") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { test -z "$ac_c_werror_flag" || test ! -s conftest.err - } && test -s conftest$ac_exeext && - $as_test_x conftest$ac_exeext; then + } && test -s conftest$ac_exeext && { + test "$cross_compiling" = yes || + $as_test_x conftest$ac_exeext + }; then ac_cv_has_makedev=yes else - echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 ac_cv_has_makedev=no fi +rm -rf conftest.dSYM rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \ conftest$ac_exeext conftest.$ac_ext if test "$ac_cv_has_makedev" = "yes"; then @@ -6692,8 +7271,8 @@ fi fi -{ echo "$as_me:$LINENO: result: $ac_cv_has_makedev" >&5 -echo "${ECHO_T}$ac_cv_has_makedev" >&6; } +{ $as_echo "$as_me:$LINENO: result: $ac_cv_has_makedev" >&5 +$as_echo "$ac_cv_has_makedev" >&6; } if test "$ac_cv_has_makedev" = "yes"; then cat >>confdefs.h <<\_ACEOF @@ -6710,8 +7289,8 @@ # work-around, disable LFS on such configurations use_lfs=yes -{ echo "$as_me:$LINENO: checking Solaris LFS bug" >&5 -echo $ECHO_N "checking Solaris LFS bug... $ECHO_C" >&6; } +{ $as_echo "$as_me:$LINENO: checking Solaris LFS bug" >&5 +$as_echo_n "checking Solaris LFS bug... " >&6; } cat >conftest.$ac_ext <<_ACEOF /* confdefs.h. */ _ACEOF @@ -6737,28 +7316,29 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_compile") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { test -z "$ac_c_werror_flag" || test ! -s conftest.err } && test -s conftest.$ac_objext; then sol_lfs_bug=no else - echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 sol_lfs_bug=yes fi rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext -{ echo "$as_me:$LINENO: result: $sol_lfs_bug" >&5 -echo "${ECHO_T}$sol_lfs_bug" >&6; } +{ $as_echo "$as_me:$LINENO: result: $sol_lfs_bug" >&5 +$as_echo "$sol_lfs_bug" >&6; } if test "$sol_lfs_bug" = "yes"; then use_lfs=no fi @@ -6786,26 +7366,58 @@ EOF # Type availability checks -{ echo "$as_me:$LINENO: checking for mode_t" >&5 -echo $ECHO_N "checking for mode_t... $ECHO_C" >&6; } +{ $as_echo "$as_me:$LINENO: checking for mode_t" >&5 +$as_echo_n "checking for mode_t... " >&6; } if test "${ac_cv_type_mode_t+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 + $as_echo_n "(cached) " >&6 else - cat >conftest.$ac_ext <<_ACEOF + ac_cv_type_mode_t=no +cat >conftest.$ac_ext <<_ACEOF /* confdefs.h. */ _ACEOF cat confdefs.h >>conftest.$ac_ext cat >>conftest.$ac_ext <<_ACEOF /* end confdefs.h. */ $ac_includes_default -typedef mode_t ac__type_new_; int main () { -if ((ac__type_new_ *) 0) - return 0; -if (sizeof (ac__type_new_)) +if (sizeof (mode_t)) + return 0; + ; return 0; +} +_ACEOF +rm -f conftest.$ac_objext +if { (ac_try="$ac_compile" +case "(($ac_try" in + *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; + *) ac_try_echo=$ac_try;; +esac +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 + (eval "$ac_compile") 2>conftest.er1 + ac_status=$? + grep -v '^ *+' conftest.er1 >conftest.err + rm -f conftest.er1 + cat conftest.err >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 + (exit $ac_status); } && { + test -z "$ac_c_werror_flag" || + test ! -s conftest.err + } && test -s conftest.$ac_objext; then + cat >conftest.$ac_ext <<_ACEOF +/* confdefs.h. */ +_ACEOF +cat confdefs.h >>conftest.$ac_ext +cat >>conftest.$ac_ext <<_ACEOF +/* end confdefs.h. */ +$ac_includes_default +int +main () +{ +if (sizeof ((mode_t))) + return 0; ; return 0; } @@ -6816,30 +7428,39 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_compile") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { test -z "$ac_c_werror_flag" || test ! -s conftest.err } && test -s conftest.$ac_objext; then - ac_cv_type_mode_t=yes + : +else + $as_echo "$as_me: failed program was:" >&5 +sed 's/^/| /' conftest.$ac_ext >&5 + + ac_cv_type_mode_t=yes +fi + +rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext else - echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 - ac_cv_type_mode_t=no + fi rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext fi -{ echo "$as_me:$LINENO: result: $ac_cv_type_mode_t" >&5 -echo "${ECHO_T}$ac_cv_type_mode_t" >&6; } -if test $ac_cv_type_mode_t = yes; then +{ $as_echo "$as_me:$LINENO: result: $ac_cv_type_mode_t" >&5 +$as_echo "$ac_cv_type_mode_t" >&6; } +if test "x$ac_cv_type_mode_t" = x""yes; then : else @@ -6849,26 +7470,58 @@ fi -{ echo "$as_me:$LINENO: checking for off_t" >&5 -echo $ECHO_N "checking for off_t... $ECHO_C" >&6; } +{ $as_echo "$as_me:$LINENO: checking for off_t" >&5 +$as_echo_n "checking for off_t... " >&6; } if test "${ac_cv_type_off_t+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 + $as_echo_n "(cached) " >&6 else - cat >conftest.$ac_ext <<_ACEOF + ac_cv_type_off_t=no +cat >conftest.$ac_ext <<_ACEOF /* confdefs.h. */ _ACEOF cat confdefs.h >>conftest.$ac_ext cat >>conftest.$ac_ext <<_ACEOF /* end confdefs.h. */ $ac_includes_default -typedef off_t ac__type_new_; int main () { -if ((ac__type_new_ *) 0) - return 0; -if (sizeof (ac__type_new_)) +if (sizeof (off_t)) + return 0; + ; return 0; +} +_ACEOF +rm -f conftest.$ac_objext +if { (ac_try="$ac_compile" +case "(($ac_try" in + *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; + *) ac_try_echo=$ac_try;; +esac +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 + (eval "$ac_compile") 2>conftest.er1 + ac_status=$? + grep -v '^ *+' conftest.er1 >conftest.err + rm -f conftest.er1 + cat conftest.err >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 + (exit $ac_status); } && { + test -z "$ac_c_werror_flag" || + test ! -s conftest.err + } && test -s conftest.$ac_objext; then + cat >conftest.$ac_ext <<_ACEOF +/* confdefs.h. */ +_ACEOF +cat confdefs.h >>conftest.$ac_ext +cat >>conftest.$ac_ext <<_ACEOF +/* end confdefs.h. */ +$ac_includes_default +int +main () +{ +if (sizeof ((off_t))) + return 0; ; return 0; } @@ -6879,30 +7532,39 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_compile") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { test -z "$ac_c_werror_flag" || test ! -s conftest.err } && test -s conftest.$ac_objext; then - ac_cv_type_off_t=yes + : +else + $as_echo "$as_me: failed program was:" >&5 +sed 's/^/| /' conftest.$ac_ext >&5 + + ac_cv_type_off_t=yes +fi + +rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext else - echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 - ac_cv_type_off_t=no + fi rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext fi -{ echo "$as_me:$LINENO: result: $ac_cv_type_off_t" >&5 -echo "${ECHO_T}$ac_cv_type_off_t" >&6; } -if test $ac_cv_type_off_t = yes; then +{ $as_echo "$as_me:$LINENO: result: $ac_cv_type_off_t" >&5 +$as_echo "$ac_cv_type_off_t" >&6; } +if test "x$ac_cv_type_off_t" = x""yes; then : else @@ -6912,26 +7574,58 @@ fi -{ echo "$as_me:$LINENO: checking for pid_t" >&5 -echo $ECHO_N "checking for pid_t... $ECHO_C" >&6; } +{ $as_echo "$as_me:$LINENO: checking for pid_t" >&5 +$as_echo_n "checking for pid_t... " >&6; } if test "${ac_cv_type_pid_t+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 + $as_echo_n "(cached) " >&6 else - cat >conftest.$ac_ext <<_ACEOF + ac_cv_type_pid_t=no +cat >conftest.$ac_ext <<_ACEOF /* confdefs.h. */ _ACEOF cat confdefs.h >>conftest.$ac_ext cat >>conftest.$ac_ext <<_ACEOF /* end confdefs.h. */ $ac_includes_default -typedef pid_t ac__type_new_; int main () { -if ((ac__type_new_ *) 0) - return 0; -if (sizeof (ac__type_new_)) +if (sizeof (pid_t)) + return 0; + ; return 0; +} +_ACEOF +rm -f conftest.$ac_objext +if { (ac_try="$ac_compile" +case "(($ac_try" in + *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; + *) ac_try_echo=$ac_try;; +esac +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 + (eval "$ac_compile") 2>conftest.er1 + ac_status=$? + grep -v '^ *+' conftest.er1 >conftest.err + rm -f conftest.er1 + cat conftest.err >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 + (exit $ac_status); } && { + test -z "$ac_c_werror_flag" || + test ! -s conftest.err + } && test -s conftest.$ac_objext; then + cat >conftest.$ac_ext <<_ACEOF +/* confdefs.h. */ +_ACEOF +cat confdefs.h >>conftest.$ac_ext +cat >>conftest.$ac_ext <<_ACEOF +/* end confdefs.h. */ +$ac_includes_default +int +main () +{ +if (sizeof ((pid_t))) + return 0; ; return 0; } @@ -6942,30 +7636,39 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_compile") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { test -z "$ac_c_werror_flag" || test ! -s conftest.err } && test -s conftest.$ac_objext; then - ac_cv_type_pid_t=yes + : +else + $as_echo "$as_me: failed program was:" >&5 +sed 's/^/| /' conftest.$ac_ext >&5 + + ac_cv_type_pid_t=yes +fi + +rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext else - echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 - ac_cv_type_pid_t=no + fi rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext fi -{ echo "$as_me:$LINENO: result: $ac_cv_type_pid_t" >&5 -echo "${ECHO_T}$ac_cv_type_pid_t" >&6; } -if test $ac_cv_type_pid_t = yes; then +{ $as_echo "$as_me:$LINENO: result: $ac_cv_type_pid_t" >&5 +$as_echo "$ac_cv_type_pid_t" >&6; } +if test "x$ac_cv_type_pid_t" = x""yes; then : else @@ -6975,10 +7678,10 @@ fi -{ echo "$as_me:$LINENO: checking return type of signal handlers" >&5 -echo $ECHO_N "checking return type of signal handlers... $ECHO_C" >&6; } +{ $as_echo "$as_me:$LINENO: checking return type of signal handlers" >&5 +$as_echo_n "checking return type of signal handlers... " >&6; } if test "${ac_cv_type_signal+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 + $as_echo_n "(cached) " >&6 else cat >conftest.$ac_ext <<_ACEOF /* confdefs.h. */ @@ -7003,20 +7706,21 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_compile") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { test -z "$ac_c_werror_flag" || test ! -s conftest.err } && test -s conftest.$ac_objext; then ac_cv_type_signal=int else - echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 ac_cv_type_signal=void @@ -7024,34 +7728,66 @@ rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext fi -{ echo "$as_me:$LINENO: result: $ac_cv_type_signal" >&5 -echo "${ECHO_T}$ac_cv_type_signal" >&6; } +{ $as_echo "$as_me:$LINENO: result: $ac_cv_type_signal" >&5 +$as_echo "$ac_cv_type_signal" >&6; } cat >>confdefs.h <<_ACEOF #define RETSIGTYPE $ac_cv_type_signal _ACEOF -{ echo "$as_me:$LINENO: checking for size_t" >&5 -echo $ECHO_N "checking for size_t... $ECHO_C" >&6; } +{ $as_echo "$as_me:$LINENO: checking for size_t" >&5 +$as_echo_n "checking for size_t... " >&6; } if test "${ac_cv_type_size_t+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 + $as_echo_n "(cached) " >&6 else - cat >conftest.$ac_ext <<_ACEOF + ac_cv_type_size_t=no +cat >conftest.$ac_ext <<_ACEOF /* confdefs.h. */ _ACEOF cat confdefs.h >>conftest.$ac_ext cat >>conftest.$ac_ext <<_ACEOF /* end confdefs.h. */ $ac_includes_default -typedef size_t ac__type_new_; int main () { -if ((ac__type_new_ *) 0) - return 0; -if (sizeof (ac__type_new_)) +if (sizeof (size_t)) + return 0; + ; return 0; +} +_ACEOF +rm -f conftest.$ac_objext +if { (ac_try="$ac_compile" +case "(($ac_try" in + *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; + *) ac_try_echo=$ac_try;; +esac +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 + (eval "$ac_compile") 2>conftest.er1 + ac_status=$? + grep -v '^ *+' conftest.er1 >conftest.err + rm -f conftest.er1 + cat conftest.err >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 + (exit $ac_status); } && { + test -z "$ac_c_werror_flag" || + test ! -s conftest.err + } && test -s conftest.$ac_objext; then + cat >conftest.$ac_ext <<_ACEOF +/* confdefs.h. */ +_ACEOF +cat confdefs.h >>conftest.$ac_ext +cat >>conftest.$ac_ext <<_ACEOF +/* end confdefs.h. */ +$ac_includes_default +int +main () +{ +if (sizeof ((size_t))) + return 0; ; return 0; } @@ -7062,30 +7798,39 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_compile") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { test -z "$ac_c_werror_flag" || test ! -s conftest.err } && test -s conftest.$ac_objext; then - ac_cv_type_size_t=yes + : +else + $as_echo "$as_me: failed program was:" >&5 +sed 's/^/| /' conftest.$ac_ext >&5 + + ac_cv_type_size_t=yes +fi + +rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext else - echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 - ac_cv_type_size_t=no + fi rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext fi -{ echo "$as_me:$LINENO: result: $ac_cv_type_size_t" >&5 -echo "${ECHO_T}$ac_cv_type_size_t" >&6; } -if test $ac_cv_type_size_t = yes; then +{ $as_echo "$as_me:$LINENO: result: $ac_cv_type_size_t" >&5 +$as_echo "$ac_cv_type_size_t" >&6; } +if test "x$ac_cv_type_size_t" = x""yes; then : else @@ -7095,10 +7840,10 @@ fi -{ echo "$as_me:$LINENO: checking for uid_t in sys/types.h" >&5 -echo $ECHO_N "checking for uid_t in sys/types.h... $ECHO_C" >&6; } +{ $as_echo "$as_me:$LINENO: checking for uid_t in sys/types.h" >&5 +$as_echo_n "checking for uid_t in sys/types.h... " >&6; } if test "${ac_cv_type_uid_t+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 + $as_echo_n "(cached) " >&6 else cat >conftest.$ac_ext <<_ACEOF /* confdefs.h. */ @@ -7118,8 +7863,8 @@ rm -f conftest* fi -{ echo "$as_me:$LINENO: result: $ac_cv_type_uid_t" >&5 -echo "${ECHO_T}$ac_cv_type_uid_t" >&6; } +{ $as_echo "$as_me:$LINENO: result: $ac_cv_type_uid_t" >&5 +$as_echo "$ac_cv_type_uid_t" >&6; } if test $ac_cv_type_uid_t = no; then cat >>confdefs.h <<\_ACEOF @@ -7133,26 +7878,24 @@ fi -{ echo "$as_me:$LINENO: checking for ssize_t" >&5 -echo $ECHO_N "checking for ssize_t... $ECHO_C" >&6; } +{ $as_echo "$as_me:$LINENO: checking for ssize_t" >&5 +$as_echo_n "checking for ssize_t... " >&6; } if test "${ac_cv_type_ssize_t+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 + $as_echo_n "(cached) " >&6 else - cat >conftest.$ac_ext <<_ACEOF + ac_cv_type_ssize_t=no +cat >conftest.$ac_ext <<_ACEOF /* confdefs.h. */ _ACEOF cat confdefs.h >>conftest.$ac_ext cat >>conftest.$ac_ext <<_ACEOF /* end confdefs.h. */ $ac_includes_default -typedef ssize_t ac__type_new_; int main () { -if ((ac__type_new_ *) 0) - return 0; -if (sizeof (ac__type_new_)) - return 0; +if (sizeof (ssize_t)) + return 0; ; return 0; } @@ -7163,45 +7906,18 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_compile") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { test -z "$ac_c_werror_flag" || test ! -s conftest.err } && test -s conftest.$ac_objext; then - ac_cv_type_ssize_t=yes -else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - ac_cv_type_ssize_t=no -fi - -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext -fi -{ echo "$as_me:$LINENO: result: $ac_cv_type_ssize_t" >&5 -echo "${ECHO_T}$ac_cv_type_ssize_t" >&6; } -if test $ac_cv_type_ssize_t = yes; then - -cat >>confdefs.h <<\_ACEOF -#define HAVE_SSIZE_T 1 -_ACEOF - -fi - - -# Sizes of various common basic types -# ANSI C requires sizeof(char) == 1, so no need to check it -{ echo "$as_me:$LINENO: checking for int" >&5 -echo $ECHO_N "checking for int... $ECHO_C" >&6; } -if test "${ac_cv_type_int+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 -else cat >conftest.$ac_ext <<_ACEOF /* confdefs.h. */ _ACEOF @@ -7209,14 +7925,11 @@ cat >>conftest.$ac_ext <<_ACEOF /* end confdefs.h. */ $ac_includes_default -typedef int ac__type_new_; int main () { -if ((ac__type_new_ *) 0) - return 0; -if (sizeof (ac__type_new_)) - return 0; +if (sizeof ((ssize_t))) + return 0; ; return 0; } @@ -7227,38 +7940,57 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_compile") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { test -z "$ac_c_werror_flag" || test ! -s conftest.err } && test -s conftest.$ac_objext; then - ac_cv_type_int=yes + : +else + $as_echo "$as_me: failed program was:" >&5 +sed 's/^/| /' conftest.$ac_ext >&5 + + ac_cv_type_ssize_t=yes +fi + +rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext else - echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 - ac_cv_type_int=no + +fi + +rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext +fi +{ $as_echo "$as_me:$LINENO: result: $ac_cv_type_ssize_t" >&5 +$as_echo "$ac_cv_type_ssize_t" >&6; } +if test "x$ac_cv_type_ssize_t" = x""yes; then + +cat >>confdefs.h <<\_ACEOF +#define HAVE_SSIZE_T 1 +_ACEOF + fi -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext -fi -{ echo "$as_me:$LINENO: result: $ac_cv_type_int" >&5 -echo "${ECHO_T}$ac_cv_type_int" >&6; } +# Sizes of various common basic types +# ANSI C requires sizeof(char) == 1, so no need to check it # The cast to long int works around a bug in the HP C Compiler # version HP92453-01 B.11.11.23709.GP, which incorrectly rejects # declarations like `int a3[[(sizeof (unsigned char)) >= 0]];'. # This bug is HP SR number 8606223364. -{ echo "$as_me:$LINENO: checking size of int" >&5 -echo $ECHO_N "checking size of int... $ECHO_C" >&6; } +{ $as_echo "$as_me:$LINENO: checking size of int" >&5 +$as_echo_n "checking size of int... " >&6; } if test "${ac_cv_sizeof_int+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 + $as_echo_n "(cached) " >&6 else if test "$cross_compiling" = yes; then # Depending upon the size, compute the lo and hi bounds. @@ -7269,11 +8001,10 @@ cat >>conftest.$ac_ext <<_ACEOF /* end confdefs.h. */ $ac_includes_default - typedef int ac__type_sizeof_; int main () { -static int test_array [1 - 2 * !(((long int) (sizeof (ac__type_sizeof_))) >= 0)]; +static int test_array [1 - 2 * !(((long int) (sizeof (int))) >= 0)]; test_array [0] = 0 ; @@ -7286,13 +8017,14 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_compile") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { test -z "$ac_c_werror_flag" || test ! -s conftest.err @@ -7306,11 +8038,10 @@ cat >>conftest.$ac_ext <<_ACEOF /* end confdefs.h. */ $ac_includes_default - typedef int ac__type_sizeof_; int main () { -static int test_array [1 - 2 * !(((long int) (sizeof (ac__type_sizeof_))) <= $ac_mid)]; +static int test_array [1 - 2 * !(((long int) (sizeof (int))) <= $ac_mid)]; test_array [0] = 0 ; @@ -7323,20 +8054,21 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_compile") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { test -z "$ac_c_werror_flag" || test ! -s conftest.err } && test -s conftest.$ac_objext; then ac_hi=$ac_mid; break else - echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 ac_lo=`expr $ac_mid + 1` @@ -7350,7 +8082,7 @@ rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext done else - echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 cat >conftest.$ac_ext <<_ACEOF @@ -7360,11 +8092,10 @@ cat >>conftest.$ac_ext <<_ACEOF /* end confdefs.h. */ $ac_includes_default - typedef int ac__type_sizeof_; int main () { -static int test_array [1 - 2 * !(((long int) (sizeof (ac__type_sizeof_))) < 0)]; +static int test_array [1 - 2 * !(((long int) (sizeof (int))) < 0)]; test_array [0] = 0 ; @@ -7377,13 +8108,14 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_compile") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { test -z "$ac_c_werror_flag" || test ! -s conftest.err @@ -7397,11 +8129,10 @@ cat >>conftest.$ac_ext <<_ACEOF /* end confdefs.h. */ $ac_includes_default - typedef int ac__type_sizeof_; int main () { -static int test_array [1 - 2 * !(((long int) (sizeof (ac__type_sizeof_))) >= $ac_mid)]; +static int test_array [1 - 2 * !(((long int) (sizeof (int))) >= $ac_mid)]; test_array [0] = 0 ; @@ -7414,20 +8145,21 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_compile") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { test -z "$ac_c_werror_flag" || test ! -s conftest.err } && test -s conftest.$ac_objext; then ac_lo=$ac_mid; break else - echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 ac_hi=`expr '(' $ac_mid ')' - 1` @@ -7441,7 +8173,7 @@ rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext done else - echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 ac_lo= ac_hi= @@ -7461,11 +8193,10 @@ cat >>conftest.$ac_ext <<_ACEOF /* end confdefs.h. */ $ac_includes_default - typedef int ac__type_sizeof_; int main () { -static int test_array [1 - 2 * !(((long int) (sizeof (ac__type_sizeof_))) <= $ac_mid)]; +static int test_array [1 - 2 * !(((long int) (sizeof (int))) <= $ac_mid)]; test_array [0] = 0 ; @@ -7478,20 +8209,21 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_compile") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { test -z "$ac_c_werror_flag" || test ! -s conftest.err } && test -s conftest.$ac_objext; then ac_hi=$ac_mid else - echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 ac_lo=`expr '(' $ac_mid ')' + 1` @@ -7502,11 +8234,13 @@ case $ac_lo in ?*) ac_cv_sizeof_int=$ac_lo;; '') if test "$ac_cv_type_int" = yes; then - { { echo "$as_me:$LINENO: error: cannot compute sizeof (int) + { { $as_echo "$as_me:$LINENO: error: in \`$ac_pwd':" >&5 +$as_echo "$as_me: error: in \`$ac_pwd':" >&2;} +{ { $as_echo "$as_me:$LINENO: error: cannot compute sizeof (int) See \`config.log' for more details." >&5 -echo "$as_me: error: cannot compute sizeof (int) +$as_echo "$as_me: error: cannot compute sizeof (int) See \`config.log' for more details." >&2;} - { (exit 77); exit 77; }; } + { (exit 77); exit 77; }; }; } else ac_cv_sizeof_int=0 fi ;; @@ -7519,9 +8253,8 @@ cat >>conftest.$ac_ext <<_ACEOF /* end confdefs.h. */ $ac_includes_default - typedef int ac__type_sizeof_; -static long int longval () { return (long int) (sizeof (ac__type_sizeof_)); } -static unsigned long int ulongval () { return (long int) (sizeof (ac__type_sizeof_)); } +static long int longval () { return (long int) (sizeof (int)); } +static unsigned long int ulongval () { return (long int) (sizeof (int)); } #include #include int @@ -7531,20 +8264,22 @@ FILE *f = fopen ("conftest.val", "w"); if (! f) return 1; - if (((long int) (sizeof (ac__type_sizeof_))) < 0) + if (((long int) (sizeof (int))) < 0) { long int i = longval (); - if (i != ((long int) (sizeof (ac__type_sizeof_)))) + if (i != ((long int) (sizeof (int)))) return 1; - fprintf (f, "%ld\n", i); + fprintf (f, "%ld", i); } else { unsigned long int i = ulongval (); - if (i != ((long int) (sizeof (ac__type_sizeof_)))) + if (i != ((long int) (sizeof (int)))) return 1; - fprintf (f, "%lu\n", i); + fprintf (f, "%lu", i); } + /* Do not output a trailing newline, as this causes \r\n confusion + on some platforms. */ return ferror (f) || fclose (f) != 0; ; @@ -7557,43 +8292,48 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_link") 2>&5 ac_status=$? - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { ac_try='./conftest$ac_exeext' { (case "(($ac_try" in *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_try") 2>&5 ac_status=$? - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); }; }; then ac_cv_sizeof_int=`cat conftest.val` else - echo "$as_me: program exited with status $ac_status" >&5 -echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: program exited with status $ac_status" >&5 +$as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 ( exit $ac_status ) if test "$ac_cv_type_int" = yes; then - { { echo "$as_me:$LINENO: error: cannot compute sizeof (int) + { { $as_echo "$as_me:$LINENO: error: in \`$ac_pwd':" >&5 +$as_echo "$as_me: error: in \`$ac_pwd':" >&2;} +{ { $as_echo "$as_me:$LINENO: error: cannot compute sizeof (int) See \`config.log' for more details." >&5 -echo "$as_me: error: cannot compute sizeof (int) +$as_echo "$as_me: error: cannot compute sizeof (int) See \`config.log' for more details." >&2;} - { (exit 77); exit 77; }; } + { (exit 77); exit 77; }; }; } else ac_cv_sizeof_int=0 fi fi +rm -rf conftest.dSYM rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext conftest.$ac_objext conftest.$ac_ext fi rm -f conftest.val fi -{ echo "$as_me:$LINENO: result: $ac_cv_sizeof_int" >&5 -echo "${ECHO_T}$ac_cv_sizeof_int" >&6; } +{ $as_echo "$as_me:$LINENO: result: $ac_cv_sizeof_int" >&5 +$as_echo "$ac_cv_sizeof_int" >&6; } @@ -7602,68 +8342,14 @@ _ACEOF -{ echo "$as_me:$LINENO: checking for long" >&5 -echo $ECHO_N "checking for long... $ECHO_C" >&6; } -if test "${ac_cv_type_long+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 -else - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -$ac_includes_default -typedef long ac__type_new_; -int -main () -{ -if ((ac__type_new_ *) 0) - return 0; -if (sizeof (ac__type_new_)) - return 0; - ; - return 0; -} -_ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - ac_cv_type_long=yes -else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - ac_cv_type_long=no -fi - -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext -fi -{ echo "$as_me:$LINENO: result: $ac_cv_type_long" >&5 -echo "${ECHO_T}$ac_cv_type_long" >&6; } - # The cast to long int works around a bug in the HP C Compiler # version HP92453-01 B.11.11.23709.GP, which incorrectly rejects # declarations like `int a3[[(sizeof (unsigned char)) >= 0]];'. # This bug is HP SR number 8606223364. -{ echo "$as_me:$LINENO: checking size of long" >&5 -echo $ECHO_N "checking size of long... $ECHO_C" >&6; } +{ $as_echo "$as_me:$LINENO: checking size of long" >&5 +$as_echo_n "checking size of long... " >&6; } if test "${ac_cv_sizeof_long+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 + $as_echo_n "(cached) " >&6 else if test "$cross_compiling" = yes; then # Depending upon the size, compute the lo and hi bounds. @@ -7674,11 +8360,10 @@ cat >>conftest.$ac_ext <<_ACEOF /* end confdefs.h. */ $ac_includes_default - typedef long ac__type_sizeof_; int main () { -static int test_array [1 - 2 * !(((long int) (sizeof (ac__type_sizeof_))) >= 0)]; +static int test_array [1 - 2 * !(((long int) (sizeof (long))) >= 0)]; test_array [0] = 0 ; @@ -7691,13 +8376,14 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_compile") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { test -z "$ac_c_werror_flag" || test ! -s conftest.err @@ -7711,11 +8397,10 @@ cat >>conftest.$ac_ext <<_ACEOF /* end confdefs.h. */ $ac_includes_default - typedef long ac__type_sizeof_; int main () { -static int test_array [1 - 2 * !(((long int) (sizeof (ac__type_sizeof_))) <= $ac_mid)]; +static int test_array [1 - 2 * !(((long int) (sizeof (long))) <= $ac_mid)]; test_array [0] = 0 ; @@ -7728,20 +8413,21 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_compile") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { test -z "$ac_c_werror_flag" || test ! -s conftest.err } && test -s conftest.$ac_objext; then ac_hi=$ac_mid; break else - echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 ac_lo=`expr $ac_mid + 1` @@ -7755,7 +8441,7 @@ rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext done else - echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 cat >conftest.$ac_ext <<_ACEOF @@ -7765,11 +8451,10 @@ cat >>conftest.$ac_ext <<_ACEOF /* end confdefs.h. */ $ac_includes_default - typedef long ac__type_sizeof_; int main () { -static int test_array [1 - 2 * !(((long int) (sizeof (ac__type_sizeof_))) < 0)]; +static int test_array [1 - 2 * !(((long int) (sizeof (long))) < 0)]; test_array [0] = 0 ; @@ -7782,13 +8467,14 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_compile") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { test -z "$ac_c_werror_flag" || test ! -s conftest.err @@ -7802,11 +8488,10 @@ cat >>conftest.$ac_ext <<_ACEOF /* end confdefs.h. */ $ac_includes_default - typedef long ac__type_sizeof_; int main () { -static int test_array [1 - 2 * !(((long int) (sizeof (ac__type_sizeof_))) >= $ac_mid)]; +static int test_array [1 - 2 * !(((long int) (sizeof (long))) >= $ac_mid)]; test_array [0] = 0 ; @@ -7819,20 +8504,21 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_compile") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { test -z "$ac_c_werror_flag" || test ! -s conftest.err } && test -s conftest.$ac_objext; then ac_lo=$ac_mid; break else - echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 ac_hi=`expr '(' $ac_mid ')' - 1` @@ -7846,7 +8532,7 @@ rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext done else - echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 ac_lo= ac_hi= @@ -7866,11 +8552,10 @@ cat >>conftest.$ac_ext <<_ACEOF /* end confdefs.h. */ $ac_includes_default - typedef long ac__type_sizeof_; int main () { -static int test_array [1 - 2 * !(((long int) (sizeof (ac__type_sizeof_))) <= $ac_mid)]; +static int test_array [1 - 2 * !(((long int) (sizeof (long))) <= $ac_mid)]; test_array [0] = 0 ; @@ -7883,20 +8568,21 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_compile") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { test -z "$ac_c_werror_flag" || test ! -s conftest.err } && test -s conftest.$ac_objext; then ac_hi=$ac_mid else - echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 ac_lo=`expr '(' $ac_mid ')' + 1` @@ -7907,11 +8593,13 @@ case $ac_lo in ?*) ac_cv_sizeof_long=$ac_lo;; '') if test "$ac_cv_type_long" = yes; then - { { echo "$as_me:$LINENO: error: cannot compute sizeof (long) + { { $as_echo "$as_me:$LINENO: error: in \`$ac_pwd':" >&5 +$as_echo "$as_me: error: in \`$ac_pwd':" >&2;} +{ { $as_echo "$as_me:$LINENO: error: cannot compute sizeof (long) See \`config.log' for more details." >&5 -echo "$as_me: error: cannot compute sizeof (long) +$as_echo "$as_me: error: cannot compute sizeof (long) See \`config.log' for more details." >&2;} - { (exit 77); exit 77; }; } + { (exit 77); exit 77; }; }; } else ac_cv_sizeof_long=0 fi ;; @@ -7924,9 +8612,8 @@ cat >>conftest.$ac_ext <<_ACEOF /* end confdefs.h. */ $ac_includes_default - typedef long ac__type_sizeof_; -static long int longval () { return (long int) (sizeof (ac__type_sizeof_)); } -static unsigned long int ulongval () { return (long int) (sizeof (ac__type_sizeof_)); } +static long int longval () { return (long int) (sizeof (long)); } +static unsigned long int ulongval () { return (long int) (sizeof (long)); } #include #include int @@ -7936,20 +8623,22 @@ FILE *f = fopen ("conftest.val", "w"); if (! f) return 1; - if (((long int) (sizeof (ac__type_sizeof_))) < 0) + if (((long int) (sizeof (long))) < 0) { long int i = longval (); - if (i != ((long int) (sizeof (ac__type_sizeof_)))) + if (i != ((long int) (sizeof (long)))) return 1; - fprintf (f, "%ld\n", i); + fprintf (f, "%ld", i); } else { unsigned long int i = ulongval (); - if (i != ((long int) (sizeof (ac__type_sizeof_)))) + if (i != ((long int) (sizeof (long)))) return 1; - fprintf (f, "%lu\n", i); + fprintf (f, "%lu", i); } + /* Do not output a trailing newline, as this causes \r\n confusion + on some platforms. */ return ferror (f) || fclose (f) != 0; ; @@ -7962,43 +8651,48 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_link") 2>&5 ac_status=$? - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { ac_try='./conftest$ac_exeext' { (case "(($ac_try" in *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_try") 2>&5 ac_status=$? - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); }; }; then ac_cv_sizeof_long=`cat conftest.val` else - echo "$as_me: program exited with status $ac_status" >&5 -echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: program exited with status $ac_status" >&5 +$as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 ( exit $ac_status ) if test "$ac_cv_type_long" = yes; then - { { echo "$as_me:$LINENO: error: cannot compute sizeof (long) + { { $as_echo "$as_me:$LINENO: error: in \`$ac_pwd':" >&5 +$as_echo "$as_me: error: in \`$ac_pwd':" >&2;} +{ { $as_echo "$as_me:$LINENO: error: cannot compute sizeof (long) See \`config.log' for more details." >&5 -echo "$as_me: error: cannot compute sizeof (long) +$as_echo "$as_me: error: cannot compute sizeof (long) See \`config.log' for more details." >&2;} - { (exit 77); exit 77; }; } + { (exit 77); exit 77; }; }; } else ac_cv_sizeof_long=0 fi fi +rm -rf conftest.dSYM rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext conftest.$ac_objext conftest.$ac_ext fi rm -f conftest.val fi -{ echo "$as_me:$LINENO: result: $ac_cv_sizeof_long" >&5 -echo "${ECHO_T}$ac_cv_sizeof_long" >&6; } +{ $as_echo "$as_me:$LINENO: result: $ac_cv_sizeof_long" >&5 +$as_echo "$ac_cv_sizeof_long" >&6; } @@ -8007,68 +8701,14 @@ _ACEOF -{ echo "$as_me:$LINENO: checking for void *" >&5 -echo $ECHO_N "checking for void *... $ECHO_C" >&6; } -if test "${ac_cv_type_void_p+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 -else - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -$ac_includes_default -typedef void * ac__type_new_; -int -main () -{ -if ((ac__type_new_ *) 0) - return 0; -if (sizeof (ac__type_new_)) - return 0; - ; - return 0; -} -_ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - ac_cv_type_void_p=yes -else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - ac_cv_type_void_p=no -fi - -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext -fi -{ echo "$as_me:$LINENO: result: $ac_cv_type_void_p" >&5 -echo "${ECHO_T}$ac_cv_type_void_p" >&6; } - # The cast to long int works around a bug in the HP C Compiler # version HP92453-01 B.11.11.23709.GP, which incorrectly rejects # declarations like `int a3[[(sizeof (unsigned char)) >= 0]];'. # This bug is HP SR number 8606223364. -{ echo "$as_me:$LINENO: checking size of void *" >&5 -echo $ECHO_N "checking size of void *... $ECHO_C" >&6; } +{ $as_echo "$as_me:$LINENO: checking size of void *" >&5 +$as_echo_n "checking size of void *... " >&6; } if test "${ac_cv_sizeof_void_p+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 + $as_echo_n "(cached) " >&6 else if test "$cross_compiling" = yes; then # Depending upon the size, compute the lo and hi bounds. @@ -8079,11 +8719,10 @@ cat >>conftest.$ac_ext <<_ACEOF /* end confdefs.h. */ $ac_includes_default - typedef void * ac__type_sizeof_; int main () { -static int test_array [1 - 2 * !(((long int) (sizeof (ac__type_sizeof_))) >= 0)]; +static int test_array [1 - 2 * !(((long int) (sizeof (void *))) >= 0)]; test_array [0] = 0 ; @@ -8096,13 +8735,14 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_compile") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { test -z "$ac_c_werror_flag" || test ! -s conftest.err @@ -8116,11 +8756,10 @@ cat >>conftest.$ac_ext <<_ACEOF /* end confdefs.h. */ $ac_includes_default - typedef void * ac__type_sizeof_; int main () { -static int test_array [1 - 2 * !(((long int) (sizeof (ac__type_sizeof_))) <= $ac_mid)]; +static int test_array [1 - 2 * !(((long int) (sizeof (void *))) <= $ac_mid)]; test_array [0] = 0 ; @@ -8133,20 +8772,21 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_compile") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { test -z "$ac_c_werror_flag" || test ! -s conftest.err } && test -s conftest.$ac_objext; then ac_hi=$ac_mid; break else - echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 ac_lo=`expr $ac_mid + 1` @@ -8160,7 +8800,7 @@ rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext done else - echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 cat >conftest.$ac_ext <<_ACEOF @@ -8170,11 +8810,10 @@ cat >>conftest.$ac_ext <<_ACEOF /* end confdefs.h. */ $ac_includes_default - typedef void * ac__type_sizeof_; int main () { -static int test_array [1 - 2 * !(((long int) (sizeof (ac__type_sizeof_))) < 0)]; +static int test_array [1 - 2 * !(((long int) (sizeof (void *))) < 0)]; test_array [0] = 0 ; @@ -8187,13 +8826,14 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_compile") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { test -z "$ac_c_werror_flag" || test ! -s conftest.err @@ -8207,11 +8847,10 @@ cat >>conftest.$ac_ext <<_ACEOF /* end confdefs.h. */ $ac_includes_default - typedef void * ac__type_sizeof_; int main () { -static int test_array [1 - 2 * !(((long int) (sizeof (ac__type_sizeof_))) >= $ac_mid)]; +static int test_array [1 - 2 * !(((long int) (sizeof (void *))) >= $ac_mid)]; test_array [0] = 0 ; @@ -8224,20 +8863,21 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_compile") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { test -z "$ac_c_werror_flag" || test ! -s conftest.err } && test -s conftest.$ac_objext; then ac_lo=$ac_mid; break else - echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 ac_hi=`expr '(' $ac_mid ')' - 1` @@ -8251,7 +8891,7 @@ rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext done else - echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 ac_lo= ac_hi= @@ -8271,11 +8911,10 @@ cat >>conftest.$ac_ext <<_ACEOF /* end confdefs.h. */ $ac_includes_default - typedef void * ac__type_sizeof_; int main () { -static int test_array [1 - 2 * !(((long int) (sizeof (ac__type_sizeof_))) <= $ac_mid)]; +static int test_array [1 - 2 * !(((long int) (sizeof (void *))) <= $ac_mid)]; test_array [0] = 0 ; @@ -8288,20 +8927,21 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_compile") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { test -z "$ac_c_werror_flag" || test ! -s conftest.err } && test -s conftest.$ac_objext; then ac_hi=$ac_mid else - echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 ac_lo=`expr '(' $ac_mid ')' + 1` @@ -8312,11 +8952,13 @@ case $ac_lo in ?*) ac_cv_sizeof_void_p=$ac_lo;; '') if test "$ac_cv_type_void_p" = yes; then - { { echo "$as_me:$LINENO: error: cannot compute sizeof (void *) + { { $as_echo "$as_me:$LINENO: error: in \`$ac_pwd':" >&5 +$as_echo "$as_me: error: in \`$ac_pwd':" >&2;} +{ { $as_echo "$as_me:$LINENO: error: cannot compute sizeof (void *) See \`config.log' for more details." >&5 -echo "$as_me: error: cannot compute sizeof (void *) +$as_echo "$as_me: error: cannot compute sizeof (void *) See \`config.log' for more details." >&2;} - { (exit 77); exit 77; }; } + { (exit 77); exit 77; }; }; } else ac_cv_sizeof_void_p=0 fi ;; @@ -8329,9 +8971,8 @@ cat >>conftest.$ac_ext <<_ACEOF /* end confdefs.h. */ $ac_includes_default - typedef void * ac__type_sizeof_; -static long int longval () { return (long int) (sizeof (ac__type_sizeof_)); } -static unsigned long int ulongval () { return (long int) (sizeof (ac__type_sizeof_)); } +static long int longval () { return (long int) (sizeof (void *)); } +static unsigned long int ulongval () { return (long int) (sizeof (void *)); } #include #include int @@ -8341,20 +8982,22 @@ FILE *f = fopen ("conftest.val", "w"); if (! f) return 1; - if (((long int) (sizeof (ac__type_sizeof_))) < 0) + if (((long int) (sizeof (void *))) < 0) { long int i = longval (); - if (i != ((long int) (sizeof (ac__type_sizeof_)))) + if (i != ((long int) (sizeof (void *)))) return 1; - fprintf (f, "%ld\n", i); + fprintf (f, "%ld", i); } else { unsigned long int i = ulongval (); - if (i != ((long int) (sizeof (ac__type_sizeof_)))) + if (i != ((long int) (sizeof (void *)))) return 1; - fprintf (f, "%lu\n", i); + fprintf (f, "%lu", i); } + /* Do not output a trailing newline, as this causes \r\n confusion + on some platforms. */ return ferror (f) || fclose (f) != 0; ; @@ -8367,43 +9010,48 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_link") 2>&5 ac_status=$? - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { ac_try='./conftest$ac_exeext' { (case "(($ac_try" in *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_try") 2>&5 ac_status=$? - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); }; }; then ac_cv_sizeof_void_p=`cat conftest.val` else - echo "$as_me: program exited with status $ac_status" >&5 -echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: program exited with status $ac_status" >&5 +$as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 ( exit $ac_status ) if test "$ac_cv_type_void_p" = yes; then - { { echo "$as_me:$LINENO: error: cannot compute sizeof (void *) + { { $as_echo "$as_me:$LINENO: error: in \`$ac_pwd':" >&5 +$as_echo "$as_me: error: in \`$ac_pwd':" >&2;} +{ { $as_echo "$as_me:$LINENO: error: cannot compute sizeof (void *) See \`config.log' for more details." >&5 -echo "$as_me: error: cannot compute sizeof (void *) +$as_echo "$as_me: error: cannot compute sizeof (void *) See \`config.log' for more details." >&2;} - { (exit 77); exit 77; }; } + { (exit 77); exit 77; }; }; } else ac_cv_sizeof_void_p=0 fi fi +rm -rf conftest.dSYM rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext conftest.$ac_objext conftest.$ac_ext fi rm -f conftest.val fi -{ echo "$as_me:$LINENO: result: $ac_cv_sizeof_void_p" >&5 -echo "${ECHO_T}$ac_cv_sizeof_void_p" >&6; } +{ $as_echo "$as_me:$LINENO: result: $ac_cv_sizeof_void_p" >&5 +$as_echo "$ac_cv_sizeof_void_p" >&6; } @@ -8412,68 +9060,14 @@ _ACEOF -{ echo "$as_me:$LINENO: checking for short" >&5 -echo $ECHO_N "checking for short... $ECHO_C" >&6; } -if test "${ac_cv_type_short+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 -else - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -$ac_includes_default -typedef short ac__type_new_; -int -main () -{ -if ((ac__type_new_ *) 0) - return 0; -if (sizeof (ac__type_new_)) - return 0; - ; - return 0; -} -_ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - ac_cv_type_short=yes -else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - ac_cv_type_short=no -fi - -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext -fi -{ echo "$as_me:$LINENO: result: $ac_cv_type_short" >&5 -echo "${ECHO_T}$ac_cv_type_short" >&6; } - # The cast to long int works around a bug in the HP C Compiler # version HP92453-01 B.11.11.23709.GP, which incorrectly rejects # declarations like `int a3[[(sizeof (unsigned char)) >= 0]];'. # This bug is HP SR number 8606223364. -{ echo "$as_me:$LINENO: checking size of short" >&5 -echo $ECHO_N "checking size of short... $ECHO_C" >&6; } +{ $as_echo "$as_me:$LINENO: checking size of short" >&5 +$as_echo_n "checking size of short... " >&6; } if test "${ac_cv_sizeof_short+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 + $as_echo_n "(cached) " >&6 else if test "$cross_compiling" = yes; then # Depending upon the size, compute the lo and hi bounds. @@ -8484,11 +9078,10 @@ cat >>conftest.$ac_ext <<_ACEOF /* end confdefs.h. */ $ac_includes_default - typedef short ac__type_sizeof_; int main () { -static int test_array [1 - 2 * !(((long int) (sizeof (ac__type_sizeof_))) >= 0)]; +static int test_array [1 - 2 * !(((long int) (sizeof (short))) >= 0)]; test_array [0] = 0 ; @@ -8501,13 +9094,14 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_compile") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { test -z "$ac_c_werror_flag" || test ! -s conftest.err @@ -8521,11 +9115,10 @@ cat >>conftest.$ac_ext <<_ACEOF /* end confdefs.h. */ $ac_includes_default - typedef short ac__type_sizeof_; int main () { -static int test_array [1 - 2 * !(((long int) (sizeof (ac__type_sizeof_))) <= $ac_mid)]; +static int test_array [1 - 2 * !(((long int) (sizeof (short))) <= $ac_mid)]; test_array [0] = 0 ; @@ -8538,20 +9131,21 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_compile") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { test -z "$ac_c_werror_flag" || test ! -s conftest.err } && test -s conftest.$ac_objext; then ac_hi=$ac_mid; break else - echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 ac_lo=`expr $ac_mid + 1` @@ -8565,7 +9159,7 @@ rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext done else - echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 cat >conftest.$ac_ext <<_ACEOF @@ -8575,11 +9169,10 @@ cat >>conftest.$ac_ext <<_ACEOF /* end confdefs.h. */ $ac_includes_default - typedef short ac__type_sizeof_; int main () { -static int test_array [1 - 2 * !(((long int) (sizeof (ac__type_sizeof_))) < 0)]; +static int test_array [1 - 2 * !(((long int) (sizeof (short))) < 0)]; test_array [0] = 0 ; @@ -8592,13 +9185,14 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_compile") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { test -z "$ac_c_werror_flag" || test ! -s conftest.err @@ -8612,11 +9206,10 @@ cat >>conftest.$ac_ext <<_ACEOF /* end confdefs.h. */ $ac_includes_default - typedef short ac__type_sizeof_; int main () { -static int test_array [1 - 2 * !(((long int) (sizeof (ac__type_sizeof_))) >= $ac_mid)]; +static int test_array [1 - 2 * !(((long int) (sizeof (short))) >= $ac_mid)]; test_array [0] = 0 ; @@ -8629,20 +9222,21 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_compile") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { test -z "$ac_c_werror_flag" || test ! -s conftest.err } && test -s conftest.$ac_objext; then ac_lo=$ac_mid; break else - echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 ac_hi=`expr '(' $ac_mid ')' - 1` @@ -8656,7 +9250,7 @@ rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext done else - echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 ac_lo= ac_hi= @@ -8676,11 +9270,10 @@ cat >>conftest.$ac_ext <<_ACEOF /* end confdefs.h. */ $ac_includes_default - typedef short ac__type_sizeof_; int main () { -static int test_array [1 - 2 * !(((long int) (sizeof (ac__type_sizeof_))) <= $ac_mid)]; +static int test_array [1 - 2 * !(((long int) (sizeof (short))) <= $ac_mid)]; test_array [0] = 0 ; @@ -8693,20 +9286,21 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_compile") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { test -z "$ac_c_werror_flag" || test ! -s conftest.err } && test -s conftest.$ac_objext; then ac_hi=$ac_mid else - echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 ac_lo=`expr '(' $ac_mid ')' + 1` @@ -8717,11 +9311,13 @@ case $ac_lo in ?*) ac_cv_sizeof_short=$ac_lo;; '') if test "$ac_cv_type_short" = yes; then - { { echo "$as_me:$LINENO: error: cannot compute sizeof (short) + { { $as_echo "$as_me:$LINENO: error: in \`$ac_pwd':" >&5 +$as_echo "$as_me: error: in \`$ac_pwd':" >&2;} +{ { $as_echo "$as_me:$LINENO: error: cannot compute sizeof (short) See \`config.log' for more details." >&5 -echo "$as_me: error: cannot compute sizeof (short) +$as_echo "$as_me: error: cannot compute sizeof (short) See \`config.log' for more details." >&2;} - { (exit 77); exit 77; }; } + { (exit 77); exit 77; }; }; } else ac_cv_sizeof_short=0 fi ;; @@ -8734,9 +9330,8 @@ cat >>conftest.$ac_ext <<_ACEOF /* end confdefs.h. */ $ac_includes_default - typedef short ac__type_sizeof_; -static long int longval () { return (long int) (sizeof (ac__type_sizeof_)); } -static unsigned long int ulongval () { return (long int) (sizeof (ac__type_sizeof_)); } +static long int longval () { return (long int) (sizeof (short)); } +static unsigned long int ulongval () { return (long int) (sizeof (short)); } #include #include int @@ -8746,20 +9341,22 @@ FILE *f = fopen ("conftest.val", "w"); if (! f) return 1; - if (((long int) (sizeof (ac__type_sizeof_))) < 0) + if (((long int) (sizeof (short))) < 0) { long int i = longval (); - if (i != ((long int) (sizeof (ac__type_sizeof_)))) + if (i != ((long int) (sizeof (short)))) return 1; - fprintf (f, "%ld\n", i); + fprintf (f, "%ld", i); } else { unsigned long int i = ulongval (); - if (i != ((long int) (sizeof (ac__type_sizeof_)))) + if (i != ((long int) (sizeof (short)))) return 1; - fprintf (f, "%lu\n", i); + fprintf (f, "%lu", i); } + /* Do not output a trailing newline, as this causes \r\n confusion + on some platforms. */ return ferror (f) || fclose (f) != 0; ; @@ -8772,43 +9369,48 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_link") 2>&5 ac_status=$? - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { ac_try='./conftest$ac_exeext' { (case "(($ac_try" in *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_try") 2>&5 ac_status=$? - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); }; }; then ac_cv_sizeof_short=`cat conftest.val` else - echo "$as_me: program exited with status $ac_status" >&5 -echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: program exited with status $ac_status" >&5 +$as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 ( exit $ac_status ) if test "$ac_cv_type_short" = yes; then - { { echo "$as_me:$LINENO: error: cannot compute sizeof (short) + { { $as_echo "$as_me:$LINENO: error: in \`$ac_pwd':" >&5 +$as_echo "$as_me: error: in \`$ac_pwd':" >&2;} +{ { $as_echo "$as_me:$LINENO: error: cannot compute sizeof (short) See \`config.log' for more details." >&5 -echo "$as_me: error: cannot compute sizeof (short) +$as_echo "$as_me: error: cannot compute sizeof (short) See \`config.log' for more details." >&2;} - { (exit 77); exit 77; }; } + { (exit 77); exit 77; }; }; } else ac_cv_sizeof_short=0 fi fi +rm -rf conftest.dSYM rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext conftest.$ac_objext conftest.$ac_ext fi rm -f conftest.val fi -{ echo "$as_me:$LINENO: result: $ac_cv_sizeof_short" >&5 -echo "${ECHO_T}$ac_cv_sizeof_short" >&6; } +{ $as_echo "$as_me:$LINENO: result: $ac_cv_sizeof_short" >&5 +$as_echo "$ac_cv_sizeof_short" >&6; } @@ -8817,68 +9419,14 @@ _ACEOF -{ echo "$as_me:$LINENO: checking for float" >&5 -echo $ECHO_N "checking for float... $ECHO_C" >&6; } -if test "${ac_cv_type_float+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 -else - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -$ac_includes_default -typedef float ac__type_new_; -int -main () -{ -if ((ac__type_new_ *) 0) - return 0; -if (sizeof (ac__type_new_)) - return 0; - ; - return 0; -} -_ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - ac_cv_type_float=yes -else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - ac_cv_type_float=no -fi - -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext -fi -{ echo "$as_me:$LINENO: result: $ac_cv_type_float" >&5 -echo "${ECHO_T}$ac_cv_type_float" >&6; } - # The cast to long int works around a bug in the HP C Compiler # version HP92453-01 B.11.11.23709.GP, which incorrectly rejects # declarations like `int a3[[(sizeof (unsigned char)) >= 0]];'. # This bug is HP SR number 8606223364. -{ echo "$as_me:$LINENO: checking size of float" >&5 -echo $ECHO_N "checking size of float... $ECHO_C" >&6; } +{ $as_echo "$as_me:$LINENO: checking size of float" >&5 +$as_echo_n "checking size of float... " >&6; } if test "${ac_cv_sizeof_float+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 + $as_echo_n "(cached) " >&6 else if test "$cross_compiling" = yes; then # Depending upon the size, compute the lo and hi bounds. @@ -8889,11 +9437,10 @@ cat >>conftest.$ac_ext <<_ACEOF /* end confdefs.h. */ $ac_includes_default - typedef float ac__type_sizeof_; int main () { -static int test_array [1 - 2 * !(((long int) (sizeof (ac__type_sizeof_))) >= 0)]; +static int test_array [1 - 2 * !(((long int) (sizeof (float))) >= 0)]; test_array [0] = 0 ; @@ -8906,13 +9453,14 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_compile") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { test -z "$ac_c_werror_flag" || test ! -s conftest.err @@ -8926,11 +9474,10 @@ cat >>conftest.$ac_ext <<_ACEOF /* end confdefs.h. */ $ac_includes_default - typedef float ac__type_sizeof_; int main () { -static int test_array [1 - 2 * !(((long int) (sizeof (ac__type_sizeof_))) <= $ac_mid)]; +static int test_array [1 - 2 * !(((long int) (sizeof (float))) <= $ac_mid)]; test_array [0] = 0 ; @@ -8943,20 +9490,21 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_compile") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { test -z "$ac_c_werror_flag" || test ! -s conftest.err } && test -s conftest.$ac_objext; then ac_hi=$ac_mid; break else - echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 ac_lo=`expr $ac_mid + 1` @@ -8970,7 +9518,7 @@ rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext done else - echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 cat >conftest.$ac_ext <<_ACEOF @@ -8980,11 +9528,10 @@ cat >>conftest.$ac_ext <<_ACEOF /* end confdefs.h. */ $ac_includes_default - typedef float ac__type_sizeof_; int main () { -static int test_array [1 - 2 * !(((long int) (sizeof (ac__type_sizeof_))) < 0)]; +static int test_array [1 - 2 * !(((long int) (sizeof (float))) < 0)]; test_array [0] = 0 ; @@ -8997,13 +9544,14 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_compile") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { test -z "$ac_c_werror_flag" || test ! -s conftest.err @@ -9017,11 +9565,10 @@ cat >>conftest.$ac_ext <<_ACEOF /* end confdefs.h. */ $ac_includes_default - typedef float ac__type_sizeof_; int main () { -static int test_array [1 - 2 * !(((long int) (sizeof (ac__type_sizeof_))) >= $ac_mid)]; +static int test_array [1 - 2 * !(((long int) (sizeof (float))) >= $ac_mid)]; test_array [0] = 0 ; @@ -9034,20 +9581,21 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_compile") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { test -z "$ac_c_werror_flag" || test ! -s conftest.err } && test -s conftest.$ac_objext; then ac_lo=$ac_mid; break else - echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 ac_hi=`expr '(' $ac_mid ')' - 1` @@ -9061,7 +9609,7 @@ rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext done else - echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 ac_lo= ac_hi= @@ -9081,11 +9629,10 @@ cat >>conftest.$ac_ext <<_ACEOF /* end confdefs.h. */ $ac_includes_default - typedef float ac__type_sizeof_; int main () { -static int test_array [1 - 2 * !(((long int) (sizeof (ac__type_sizeof_))) <= $ac_mid)]; +static int test_array [1 - 2 * !(((long int) (sizeof (float))) <= $ac_mid)]; test_array [0] = 0 ; @@ -9098,20 +9645,21 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_compile") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { test -z "$ac_c_werror_flag" || test ! -s conftest.err } && test -s conftest.$ac_objext; then ac_hi=$ac_mid else - echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 ac_lo=`expr '(' $ac_mid ')' + 1` @@ -9122,11 +9670,13 @@ case $ac_lo in ?*) ac_cv_sizeof_float=$ac_lo;; '') if test "$ac_cv_type_float" = yes; then - { { echo "$as_me:$LINENO: error: cannot compute sizeof (float) + { { $as_echo "$as_me:$LINENO: error: in \`$ac_pwd':" >&5 +$as_echo "$as_me: error: in \`$ac_pwd':" >&2;} +{ { $as_echo "$as_me:$LINENO: error: cannot compute sizeof (float) See \`config.log' for more details." >&5 -echo "$as_me: error: cannot compute sizeof (float) +$as_echo "$as_me: error: cannot compute sizeof (float) See \`config.log' for more details." >&2;} - { (exit 77); exit 77; }; } + { (exit 77); exit 77; }; }; } else ac_cv_sizeof_float=0 fi ;; @@ -9139,9 +9689,8 @@ cat >>conftest.$ac_ext <<_ACEOF /* end confdefs.h. */ $ac_includes_default - typedef float ac__type_sizeof_; -static long int longval () { return (long int) (sizeof (ac__type_sizeof_)); } -static unsigned long int ulongval () { return (long int) (sizeof (ac__type_sizeof_)); } +static long int longval () { return (long int) (sizeof (float)); } +static unsigned long int ulongval () { return (long int) (sizeof (float)); } #include #include int @@ -9151,20 +9700,22 @@ FILE *f = fopen ("conftest.val", "w"); if (! f) return 1; - if (((long int) (sizeof (ac__type_sizeof_))) < 0) + if (((long int) (sizeof (float))) < 0) { long int i = longval (); - if (i != ((long int) (sizeof (ac__type_sizeof_)))) + if (i != ((long int) (sizeof (float)))) return 1; - fprintf (f, "%ld\n", i); + fprintf (f, "%ld", i); } else { unsigned long int i = ulongval (); - if (i != ((long int) (sizeof (ac__type_sizeof_)))) + if (i != ((long int) (sizeof (float)))) return 1; - fprintf (f, "%lu\n", i); + fprintf (f, "%lu", i); } + /* Do not output a trailing newline, as this causes \r\n confusion + on some platforms. */ return ferror (f) || fclose (f) != 0; ; @@ -9177,43 +9728,48 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_link") 2>&5 ac_status=$? - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { ac_try='./conftest$ac_exeext' { (case "(($ac_try" in *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_try") 2>&5 ac_status=$? - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); }; }; then ac_cv_sizeof_float=`cat conftest.val` else - echo "$as_me: program exited with status $ac_status" >&5 -echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: program exited with status $ac_status" >&5 +$as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 ( exit $ac_status ) if test "$ac_cv_type_float" = yes; then - { { echo "$as_me:$LINENO: error: cannot compute sizeof (float) + { { $as_echo "$as_me:$LINENO: error: in \`$ac_pwd':" >&5 +$as_echo "$as_me: error: in \`$ac_pwd':" >&2;} +{ { $as_echo "$as_me:$LINENO: error: cannot compute sizeof (float) See \`config.log' for more details." >&5 -echo "$as_me: error: cannot compute sizeof (float) +$as_echo "$as_me: error: cannot compute sizeof (float) See \`config.log' for more details." >&2;} - { (exit 77); exit 77; }; } + { (exit 77); exit 77; }; }; } else ac_cv_sizeof_float=0 fi fi +rm -rf conftest.dSYM rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext conftest.$ac_objext conftest.$ac_ext fi rm -f conftest.val fi -{ echo "$as_me:$LINENO: result: $ac_cv_sizeof_float" >&5 -echo "${ECHO_T}$ac_cv_sizeof_float" >&6; } +{ $as_echo "$as_me:$LINENO: result: $ac_cv_sizeof_float" >&5 +$as_echo "$ac_cv_sizeof_float" >&6; } @@ -9222,68 +9778,14 @@ _ACEOF -{ echo "$as_me:$LINENO: checking for double" >&5 -echo $ECHO_N "checking for double... $ECHO_C" >&6; } -if test "${ac_cv_type_double+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 -else - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -$ac_includes_default -typedef double ac__type_new_; -int -main () -{ -if ((ac__type_new_ *) 0) - return 0; -if (sizeof (ac__type_new_)) - return 0; - ; - return 0; -} -_ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - ac_cv_type_double=yes -else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - ac_cv_type_double=no -fi - -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext -fi -{ echo "$as_me:$LINENO: result: $ac_cv_type_double" >&5 -echo "${ECHO_T}$ac_cv_type_double" >&6; } - # The cast to long int works around a bug in the HP C Compiler # version HP92453-01 B.11.11.23709.GP, which incorrectly rejects # declarations like `int a3[[(sizeof (unsigned char)) >= 0]];'. # This bug is HP SR number 8606223364. -{ echo "$as_me:$LINENO: checking size of double" >&5 -echo $ECHO_N "checking size of double... $ECHO_C" >&6; } +{ $as_echo "$as_me:$LINENO: checking size of double" >&5 +$as_echo_n "checking size of double... " >&6; } if test "${ac_cv_sizeof_double+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 + $as_echo_n "(cached) " >&6 else if test "$cross_compiling" = yes; then # Depending upon the size, compute the lo and hi bounds. @@ -9294,11 +9796,10 @@ cat >>conftest.$ac_ext <<_ACEOF /* end confdefs.h. */ $ac_includes_default - typedef double ac__type_sizeof_; int main () { -static int test_array [1 - 2 * !(((long int) (sizeof (ac__type_sizeof_))) >= 0)]; +static int test_array [1 - 2 * !(((long int) (sizeof (double))) >= 0)]; test_array [0] = 0 ; @@ -9311,13 +9812,14 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_compile") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { test -z "$ac_c_werror_flag" || test ! -s conftest.err @@ -9331,11 +9833,10 @@ cat >>conftest.$ac_ext <<_ACEOF /* end confdefs.h. */ $ac_includes_default - typedef double ac__type_sizeof_; int main () { -static int test_array [1 - 2 * !(((long int) (sizeof (ac__type_sizeof_))) <= $ac_mid)]; +static int test_array [1 - 2 * !(((long int) (sizeof (double))) <= $ac_mid)]; test_array [0] = 0 ; @@ -9348,20 +9849,21 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_compile") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { test -z "$ac_c_werror_flag" || test ! -s conftest.err } && test -s conftest.$ac_objext; then ac_hi=$ac_mid; break else - echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 ac_lo=`expr $ac_mid + 1` @@ -9375,7 +9877,7 @@ rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext done else - echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 cat >conftest.$ac_ext <<_ACEOF @@ -9385,11 +9887,10 @@ cat >>conftest.$ac_ext <<_ACEOF /* end confdefs.h. */ $ac_includes_default - typedef double ac__type_sizeof_; int main () { -static int test_array [1 - 2 * !(((long int) (sizeof (ac__type_sizeof_))) < 0)]; +static int test_array [1 - 2 * !(((long int) (sizeof (double))) < 0)]; test_array [0] = 0 ; @@ -9402,13 +9903,14 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_compile") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { test -z "$ac_c_werror_flag" || test ! -s conftest.err @@ -9422,11 +9924,10 @@ cat >>conftest.$ac_ext <<_ACEOF /* end confdefs.h. */ $ac_includes_default - typedef double ac__type_sizeof_; int main () { -static int test_array [1 - 2 * !(((long int) (sizeof (ac__type_sizeof_))) >= $ac_mid)]; +static int test_array [1 - 2 * !(((long int) (sizeof (double))) >= $ac_mid)]; test_array [0] = 0 ; @@ -9439,20 +9940,21 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_compile") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { test -z "$ac_c_werror_flag" || test ! -s conftest.err } && test -s conftest.$ac_objext; then ac_lo=$ac_mid; break else - echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 ac_hi=`expr '(' $ac_mid ')' - 1` @@ -9466,7 +9968,7 @@ rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext done else - echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 ac_lo= ac_hi= @@ -9486,11 +9988,10 @@ cat >>conftest.$ac_ext <<_ACEOF /* end confdefs.h. */ $ac_includes_default - typedef double ac__type_sizeof_; int main () { -static int test_array [1 - 2 * !(((long int) (sizeof (ac__type_sizeof_))) <= $ac_mid)]; +static int test_array [1 - 2 * !(((long int) (sizeof (double))) <= $ac_mid)]; test_array [0] = 0 ; @@ -9503,20 +10004,21 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_compile") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { test -z "$ac_c_werror_flag" || test ! -s conftest.err } && test -s conftest.$ac_objext; then ac_hi=$ac_mid else - echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 ac_lo=`expr '(' $ac_mid ')' + 1` @@ -9527,11 +10029,13 @@ case $ac_lo in ?*) ac_cv_sizeof_double=$ac_lo;; '') if test "$ac_cv_type_double" = yes; then - { { echo "$as_me:$LINENO: error: cannot compute sizeof (double) + { { $as_echo "$as_me:$LINENO: error: in \`$ac_pwd':" >&5 +$as_echo "$as_me: error: in \`$ac_pwd':" >&2;} +{ { $as_echo "$as_me:$LINENO: error: cannot compute sizeof (double) See \`config.log' for more details." >&5 -echo "$as_me: error: cannot compute sizeof (double) +$as_echo "$as_me: error: cannot compute sizeof (double) See \`config.log' for more details." >&2;} - { (exit 77); exit 77; }; } + { (exit 77); exit 77; }; }; } else ac_cv_sizeof_double=0 fi ;; @@ -9544,9 +10048,8 @@ cat >>conftest.$ac_ext <<_ACEOF /* end confdefs.h. */ $ac_includes_default - typedef double ac__type_sizeof_; -static long int longval () { return (long int) (sizeof (ac__type_sizeof_)); } -static unsigned long int ulongval () { return (long int) (sizeof (ac__type_sizeof_)); } +static long int longval () { return (long int) (sizeof (double)); } +static unsigned long int ulongval () { return (long int) (sizeof (double)); } #include #include int @@ -9556,20 +10059,22 @@ FILE *f = fopen ("conftest.val", "w"); if (! f) return 1; - if (((long int) (sizeof (ac__type_sizeof_))) < 0) + if (((long int) (sizeof (double))) < 0) { long int i = longval (); - if (i != ((long int) (sizeof (ac__type_sizeof_)))) + if (i != ((long int) (sizeof (double)))) return 1; - fprintf (f, "%ld\n", i); + fprintf (f, "%ld", i); } else { unsigned long int i = ulongval (); - if (i != ((long int) (sizeof (ac__type_sizeof_)))) + if (i != ((long int) (sizeof (double)))) return 1; - fprintf (f, "%lu\n", i); + fprintf (f, "%lu", i); } + /* Do not output a trailing newline, as this causes \r\n confusion + on some platforms. */ return ferror (f) || fclose (f) != 0; ; @@ -9582,113 +10087,64 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_link") 2>&5 ac_status=$? - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { ac_try='./conftest$ac_exeext' - { (case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_try") 2>&5 - ac_status=$? - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); }; }; then - ac_cv_sizeof_double=`cat conftest.val` -else - echo "$as_me: program exited with status $ac_status" >&5 -echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - -( exit $ac_status ) -if test "$ac_cv_type_double" = yes; then - { { echo "$as_me:$LINENO: error: cannot compute sizeof (double) -See \`config.log' for more details." >&5 -echo "$as_me: error: cannot compute sizeof (double) -See \`config.log' for more details." >&2;} - { (exit 77); exit 77; }; } - else - ac_cv_sizeof_double=0 - fi -fi -rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext conftest.$ac_objext conftest.$ac_ext -fi -rm -f conftest.val -fi -{ echo "$as_me:$LINENO: result: $ac_cv_sizeof_double" >&5 -echo "${ECHO_T}$ac_cv_sizeof_double" >&6; } - - - -cat >>confdefs.h <<_ACEOF -#define SIZEOF_DOUBLE $ac_cv_sizeof_double -_ACEOF - - -{ echo "$as_me:$LINENO: checking for fpos_t" >&5 -echo $ECHO_N "checking for fpos_t... $ECHO_C" >&6; } -if test "${ac_cv_type_fpos_t+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 -else - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -$ac_includes_default -typedef fpos_t ac__type_new_; -int -main () -{ -if ((ac__type_new_ *) 0) - return 0; -if (sizeof (ac__type_new_)) - return 0; - ; - return 0; -} -_ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in + { (case "(($ac_try" in *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_compile") 2>conftest.er1 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 + (eval "$ac_try") 2>&5 ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - ac_cv_type_fpos_t=yes + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 + (exit $ac_status); }; }; then + ac_cv_sizeof_double=`cat conftest.val` else - echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: program exited with status $ac_status" >&5 +$as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 - ac_cv_type_fpos_t=no +( exit $ac_status ) +if test "$ac_cv_type_double" = yes; then + { { $as_echo "$as_me:$LINENO: error: in \`$ac_pwd':" >&5 +$as_echo "$as_me: error: in \`$ac_pwd':" >&2;} +{ { $as_echo "$as_me:$LINENO: error: cannot compute sizeof (double) +See \`config.log' for more details." >&5 +$as_echo "$as_me: error: cannot compute sizeof (double) +See \`config.log' for more details." >&2;} + { (exit 77); exit 77; }; }; } + else + ac_cv_sizeof_double=0 + fi fi - -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext +rm -rf conftest.dSYM +rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext conftest.$ac_objext conftest.$ac_ext +fi +rm -f conftest.val fi -{ echo "$as_me:$LINENO: result: $ac_cv_type_fpos_t" >&5 -echo "${ECHO_T}$ac_cv_type_fpos_t" >&6; } +{ $as_echo "$as_me:$LINENO: result: $ac_cv_sizeof_double" >&5 +$as_echo "$ac_cv_sizeof_double" >&6; } + + + +cat >>confdefs.h <<_ACEOF +#define SIZEOF_DOUBLE $ac_cv_sizeof_double +_ACEOF + # The cast to long int works around a bug in the HP C Compiler # version HP92453-01 B.11.11.23709.GP, which incorrectly rejects # declarations like `int a3[[(sizeof (unsigned char)) >= 0]];'. # This bug is HP SR number 8606223364. -{ echo "$as_me:$LINENO: checking size of fpos_t" >&5 -echo $ECHO_N "checking size of fpos_t... $ECHO_C" >&6; } +{ $as_echo "$as_me:$LINENO: checking size of fpos_t" >&5 +$as_echo_n "checking size of fpos_t... " >&6; } if test "${ac_cv_sizeof_fpos_t+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 + $as_echo_n "(cached) " >&6 else if test "$cross_compiling" = yes; then # Depending upon the size, compute the lo and hi bounds. @@ -9699,11 +10155,10 @@ cat >>conftest.$ac_ext <<_ACEOF /* end confdefs.h. */ $ac_includes_default - typedef fpos_t ac__type_sizeof_; int main () { -static int test_array [1 - 2 * !(((long int) (sizeof (ac__type_sizeof_))) >= 0)]; +static int test_array [1 - 2 * !(((long int) (sizeof (fpos_t))) >= 0)]; test_array [0] = 0 ; @@ -9716,13 +10171,14 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_compile") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { test -z "$ac_c_werror_flag" || test ! -s conftest.err @@ -9736,11 +10192,10 @@ cat >>conftest.$ac_ext <<_ACEOF /* end confdefs.h. */ $ac_includes_default - typedef fpos_t ac__type_sizeof_; int main () { -static int test_array [1 - 2 * !(((long int) (sizeof (ac__type_sizeof_))) <= $ac_mid)]; +static int test_array [1 - 2 * !(((long int) (sizeof (fpos_t))) <= $ac_mid)]; test_array [0] = 0 ; @@ -9753,20 +10208,21 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_compile") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { test -z "$ac_c_werror_flag" || test ! -s conftest.err } && test -s conftest.$ac_objext; then ac_hi=$ac_mid; break else - echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 ac_lo=`expr $ac_mid + 1` @@ -9780,7 +10236,7 @@ rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext done else - echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 cat >conftest.$ac_ext <<_ACEOF @@ -9790,11 +10246,10 @@ cat >>conftest.$ac_ext <<_ACEOF /* end confdefs.h. */ $ac_includes_default - typedef fpos_t ac__type_sizeof_; int main () { -static int test_array [1 - 2 * !(((long int) (sizeof (ac__type_sizeof_))) < 0)]; +static int test_array [1 - 2 * !(((long int) (sizeof (fpos_t))) < 0)]; test_array [0] = 0 ; @@ -9807,13 +10262,14 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_compile") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { test -z "$ac_c_werror_flag" || test ! -s conftest.err @@ -9827,11 +10283,10 @@ cat >>conftest.$ac_ext <<_ACEOF /* end confdefs.h. */ $ac_includes_default - typedef fpos_t ac__type_sizeof_; int main () { -static int test_array [1 - 2 * !(((long int) (sizeof (ac__type_sizeof_))) >= $ac_mid)]; +static int test_array [1 - 2 * !(((long int) (sizeof (fpos_t))) >= $ac_mid)]; test_array [0] = 0 ; @@ -9844,20 +10299,21 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_compile") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { test -z "$ac_c_werror_flag" || test ! -s conftest.err } && test -s conftest.$ac_objext; then ac_lo=$ac_mid; break else - echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 ac_hi=`expr '(' $ac_mid ')' - 1` @@ -9871,7 +10327,7 @@ rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext done else - echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 ac_lo= ac_hi= @@ -9891,11 +10347,10 @@ cat >>conftest.$ac_ext <<_ACEOF /* end confdefs.h. */ $ac_includes_default - typedef fpos_t ac__type_sizeof_; int main () { -static int test_array [1 - 2 * !(((long int) (sizeof (ac__type_sizeof_))) <= $ac_mid)]; +static int test_array [1 - 2 * !(((long int) (sizeof (fpos_t))) <= $ac_mid)]; test_array [0] = 0 ; @@ -9908,20 +10363,21 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_compile") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { test -z "$ac_c_werror_flag" || test ! -s conftest.err } && test -s conftest.$ac_objext; then ac_hi=$ac_mid else - echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 ac_lo=`expr '(' $ac_mid ')' + 1` @@ -9932,11 +10388,13 @@ case $ac_lo in ?*) ac_cv_sizeof_fpos_t=$ac_lo;; '') if test "$ac_cv_type_fpos_t" = yes; then - { { echo "$as_me:$LINENO: error: cannot compute sizeof (fpos_t) + { { $as_echo "$as_me:$LINENO: error: in \`$ac_pwd':" >&5 +$as_echo "$as_me: error: in \`$ac_pwd':" >&2;} +{ { $as_echo "$as_me:$LINENO: error: cannot compute sizeof (fpos_t) See \`config.log' for more details." >&5 -echo "$as_me: error: cannot compute sizeof (fpos_t) +$as_echo "$as_me: error: cannot compute sizeof (fpos_t) See \`config.log' for more details." >&2;} - { (exit 77); exit 77; }; } + { (exit 77); exit 77; }; }; } else ac_cv_sizeof_fpos_t=0 fi ;; @@ -9949,9 +10407,8 @@ cat >>conftest.$ac_ext <<_ACEOF /* end confdefs.h. */ $ac_includes_default - typedef fpos_t ac__type_sizeof_; -static long int longval () { return (long int) (sizeof (ac__type_sizeof_)); } -static unsigned long int ulongval () { return (long int) (sizeof (ac__type_sizeof_)); } +static long int longval () { return (long int) (sizeof (fpos_t)); } +static unsigned long int ulongval () { return (long int) (sizeof (fpos_t)); } #include #include int @@ -9961,20 +10418,22 @@ FILE *f = fopen ("conftest.val", "w"); if (! f) return 1; - if (((long int) (sizeof (ac__type_sizeof_))) < 0) + if (((long int) (sizeof (fpos_t))) < 0) { long int i = longval (); - if (i != ((long int) (sizeof (ac__type_sizeof_)))) + if (i != ((long int) (sizeof (fpos_t)))) return 1; - fprintf (f, "%ld\n", i); + fprintf (f, "%ld", i); } else { unsigned long int i = ulongval (); - if (i != ((long int) (sizeof (ac__type_sizeof_)))) + if (i != ((long int) (sizeof (fpos_t)))) return 1; - fprintf (f, "%lu\n", i); + fprintf (f, "%lu", i); } + /* Do not output a trailing newline, as this causes \r\n confusion + on some platforms. */ return ferror (f) || fclose (f) != 0; ; @@ -9987,43 +10446,48 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_link") 2>&5 ac_status=$? - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { ac_try='./conftest$ac_exeext' { (case "(($ac_try" in *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_try") 2>&5 ac_status=$? - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); }; }; then ac_cv_sizeof_fpos_t=`cat conftest.val` else - echo "$as_me: program exited with status $ac_status" >&5 -echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: program exited with status $ac_status" >&5 +$as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 ( exit $ac_status ) if test "$ac_cv_type_fpos_t" = yes; then - { { echo "$as_me:$LINENO: error: cannot compute sizeof (fpos_t) + { { $as_echo "$as_me:$LINENO: error: in \`$ac_pwd':" >&5 +$as_echo "$as_me: error: in \`$ac_pwd':" >&2;} +{ { $as_echo "$as_me:$LINENO: error: cannot compute sizeof (fpos_t) See \`config.log' for more details." >&5 -echo "$as_me: error: cannot compute sizeof (fpos_t) +$as_echo "$as_me: error: cannot compute sizeof (fpos_t) See \`config.log' for more details." >&2;} - { (exit 77); exit 77; }; } + { (exit 77); exit 77; }; }; } else ac_cv_sizeof_fpos_t=0 fi fi +rm -rf conftest.dSYM rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext conftest.$ac_objext conftest.$ac_ext fi rm -f conftest.val fi -{ echo "$as_me:$LINENO: result: $ac_cv_sizeof_fpos_t" >&5 -echo "${ECHO_T}$ac_cv_sizeof_fpos_t" >&6; } +{ $as_echo "$as_me:$LINENO: result: $ac_cv_sizeof_fpos_t" >&5 +$as_echo "$ac_cv_sizeof_fpos_t" >&6; } @@ -10032,68 +10496,14 @@ _ACEOF -{ echo "$as_me:$LINENO: checking for size_t" >&5 -echo $ECHO_N "checking for size_t... $ECHO_C" >&6; } -if test "${ac_cv_type_size_t+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 -else - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -$ac_includes_default -typedef size_t ac__type_new_; -int -main () -{ -if ((ac__type_new_ *) 0) - return 0; -if (sizeof (ac__type_new_)) - return 0; - ; - return 0; -} -_ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - ac_cv_type_size_t=yes -else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - ac_cv_type_size_t=no -fi - -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext -fi -{ echo "$as_me:$LINENO: result: $ac_cv_type_size_t" >&5 -echo "${ECHO_T}$ac_cv_type_size_t" >&6; } - # The cast to long int works around a bug in the HP C Compiler # version HP92453-01 B.11.11.23709.GP, which incorrectly rejects # declarations like `int a3[[(sizeof (unsigned char)) >= 0]];'. # This bug is HP SR number 8606223364. -{ echo "$as_me:$LINENO: checking size of size_t" >&5 -echo $ECHO_N "checking size of size_t... $ECHO_C" >&6; } +{ $as_echo "$as_me:$LINENO: checking size of size_t" >&5 +$as_echo_n "checking size of size_t... " >&6; } if test "${ac_cv_sizeof_size_t+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 + $as_echo_n "(cached) " >&6 else if test "$cross_compiling" = yes; then # Depending upon the size, compute the lo and hi bounds. @@ -10104,11 +10514,10 @@ cat >>conftest.$ac_ext <<_ACEOF /* end confdefs.h. */ $ac_includes_default - typedef size_t ac__type_sizeof_; int main () { -static int test_array [1 - 2 * !(((long int) (sizeof (ac__type_sizeof_))) >= 0)]; +static int test_array [1 - 2 * !(((long int) (sizeof (size_t))) >= 0)]; test_array [0] = 0 ; @@ -10121,13 +10530,14 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_compile") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { test -z "$ac_c_werror_flag" || test ! -s conftest.err @@ -10141,11 +10551,10 @@ cat >>conftest.$ac_ext <<_ACEOF /* end confdefs.h. */ $ac_includes_default - typedef size_t ac__type_sizeof_; int main () { -static int test_array [1 - 2 * !(((long int) (sizeof (ac__type_sizeof_))) <= $ac_mid)]; +static int test_array [1 - 2 * !(((long int) (sizeof (size_t))) <= $ac_mid)]; test_array [0] = 0 ; @@ -10158,20 +10567,21 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_compile") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { test -z "$ac_c_werror_flag" || test ! -s conftest.err } && test -s conftest.$ac_objext; then ac_hi=$ac_mid; break else - echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 ac_lo=`expr $ac_mid + 1` @@ -10185,7 +10595,7 @@ rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext done else - echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 cat >conftest.$ac_ext <<_ACEOF @@ -10195,11 +10605,10 @@ cat >>conftest.$ac_ext <<_ACEOF /* end confdefs.h. */ $ac_includes_default - typedef size_t ac__type_sizeof_; int main () { -static int test_array [1 - 2 * !(((long int) (sizeof (ac__type_sizeof_))) < 0)]; +static int test_array [1 - 2 * !(((long int) (sizeof (size_t))) < 0)]; test_array [0] = 0 ; @@ -10212,13 +10621,14 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_compile") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { test -z "$ac_c_werror_flag" || test ! -s conftest.err @@ -10232,11 +10642,10 @@ cat >>conftest.$ac_ext <<_ACEOF /* end confdefs.h. */ $ac_includes_default - typedef size_t ac__type_sizeof_; int main () { -static int test_array [1 - 2 * !(((long int) (sizeof (ac__type_sizeof_))) >= $ac_mid)]; +static int test_array [1 - 2 * !(((long int) (sizeof (size_t))) >= $ac_mid)]; test_array [0] = 0 ; @@ -10249,20 +10658,21 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_compile") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { test -z "$ac_c_werror_flag" || test ! -s conftest.err } && test -s conftest.$ac_objext; then ac_lo=$ac_mid; break else - echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 ac_hi=`expr '(' $ac_mid ')' - 1` @@ -10276,7 +10686,7 @@ rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext done else - echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 ac_lo= ac_hi= @@ -10296,11 +10706,10 @@ cat >>conftest.$ac_ext <<_ACEOF /* end confdefs.h. */ $ac_includes_default - typedef size_t ac__type_sizeof_; int main () { -static int test_array [1 - 2 * !(((long int) (sizeof (ac__type_sizeof_))) <= $ac_mid)]; +static int test_array [1 - 2 * !(((long int) (sizeof (size_t))) <= $ac_mid)]; test_array [0] = 0 ; @@ -10313,20 +10722,21 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_compile") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { test -z "$ac_c_werror_flag" || test ! -s conftest.err } && test -s conftest.$ac_objext; then ac_hi=$ac_mid else - echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 ac_lo=`expr '(' $ac_mid ')' + 1` @@ -10337,11 +10747,13 @@ case $ac_lo in ?*) ac_cv_sizeof_size_t=$ac_lo;; '') if test "$ac_cv_type_size_t" = yes; then - { { echo "$as_me:$LINENO: error: cannot compute sizeof (size_t) + { { $as_echo "$as_me:$LINENO: error: in \`$ac_pwd':" >&5 +$as_echo "$as_me: error: in \`$ac_pwd':" >&2;} +{ { $as_echo "$as_me:$LINENO: error: cannot compute sizeof (size_t) See \`config.log' for more details." >&5 -echo "$as_me: error: cannot compute sizeof (size_t) +$as_echo "$as_me: error: cannot compute sizeof (size_t) See \`config.log' for more details." >&2;} - { (exit 77); exit 77; }; } + { (exit 77); exit 77; }; }; } else ac_cv_sizeof_size_t=0 fi ;; @@ -10354,9 +10766,8 @@ cat >>conftest.$ac_ext <<_ACEOF /* end confdefs.h. */ $ac_includes_default - typedef size_t ac__type_sizeof_; -static long int longval () { return (long int) (sizeof (ac__type_sizeof_)); } -static unsigned long int ulongval () { return (long int) (sizeof (ac__type_sizeof_)); } +static long int longval () { return (long int) (sizeof (size_t)); } +static unsigned long int ulongval () { return (long int) (sizeof (size_t)); } #include #include int @@ -10366,20 +10777,22 @@ FILE *f = fopen ("conftest.val", "w"); if (! f) return 1; - if (((long int) (sizeof (ac__type_sizeof_))) < 0) + if (((long int) (sizeof (size_t))) < 0) { long int i = longval (); - if (i != ((long int) (sizeof (ac__type_sizeof_)))) + if (i != ((long int) (sizeof (size_t)))) return 1; - fprintf (f, "%ld\n", i); + fprintf (f, "%ld", i); } else { unsigned long int i = ulongval (); - if (i != ((long int) (sizeof (ac__type_sizeof_)))) + if (i != ((long int) (sizeof (size_t)))) return 1; - fprintf (f, "%lu\n", i); + fprintf (f, "%lu", i); } + /* Do not output a trailing newline, as this causes \r\n confusion + on some platforms. */ return ferror (f) || fclose (f) != 0; ; @@ -10392,43 +10805,48 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_link") 2>&5 ac_status=$? - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { ac_try='./conftest$ac_exeext' { (case "(($ac_try" in *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_try") 2>&5 ac_status=$? - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); }; }; then ac_cv_sizeof_size_t=`cat conftest.val` else - echo "$as_me: program exited with status $ac_status" >&5 -echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: program exited with status $ac_status" >&5 +$as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 ( exit $ac_status ) if test "$ac_cv_type_size_t" = yes; then - { { echo "$as_me:$LINENO: error: cannot compute sizeof (size_t) + { { $as_echo "$as_me:$LINENO: error: in \`$ac_pwd':" >&5 +$as_echo "$as_me: error: in \`$ac_pwd':" >&2;} +{ { $as_echo "$as_me:$LINENO: error: cannot compute sizeof (size_t) See \`config.log' for more details." >&5 -echo "$as_me: error: cannot compute sizeof (size_t) +$as_echo "$as_me: error: cannot compute sizeof (size_t) See \`config.log' for more details." >&2;} - { (exit 77); exit 77; }; } + { (exit 77); exit 77; }; }; } else ac_cv_sizeof_size_t=0 fi fi +rm -rf conftest.dSYM rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext conftest.$ac_objext conftest.$ac_ext fi rm -f conftest.val fi -{ echo "$as_me:$LINENO: result: $ac_cv_sizeof_size_t" >&5 -echo "${ECHO_T}$ac_cv_sizeof_size_t" >&6; } +{ $as_echo "$as_me:$LINENO: result: $ac_cv_sizeof_size_t" >&5 +$as_echo "$ac_cv_sizeof_size_t" >&6; } @@ -10437,68 +10855,14 @@ _ACEOF -{ echo "$as_me:$LINENO: checking for pid_t" >&5 -echo $ECHO_N "checking for pid_t... $ECHO_C" >&6; } -if test "${ac_cv_type_pid_t+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 -else - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -$ac_includes_default -typedef pid_t ac__type_new_; -int -main () -{ -if ((ac__type_new_ *) 0) - return 0; -if (sizeof (ac__type_new_)) - return 0; - ; - return 0; -} -_ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - ac_cv_type_pid_t=yes -else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - ac_cv_type_pid_t=no -fi - -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext -fi -{ echo "$as_me:$LINENO: result: $ac_cv_type_pid_t" >&5 -echo "${ECHO_T}$ac_cv_type_pid_t" >&6; } - # The cast to long int works around a bug in the HP C Compiler # version HP92453-01 B.11.11.23709.GP, which incorrectly rejects # declarations like `int a3[[(sizeof (unsigned char)) >= 0]];'. # This bug is HP SR number 8606223364. -{ echo "$as_me:$LINENO: checking size of pid_t" >&5 -echo $ECHO_N "checking size of pid_t... $ECHO_C" >&6; } +{ $as_echo "$as_me:$LINENO: checking size of pid_t" >&5 +$as_echo_n "checking size of pid_t... " >&6; } if test "${ac_cv_sizeof_pid_t+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 + $as_echo_n "(cached) " >&6 else if test "$cross_compiling" = yes; then # Depending upon the size, compute the lo and hi bounds. @@ -10509,11 +10873,10 @@ cat >>conftest.$ac_ext <<_ACEOF /* end confdefs.h. */ $ac_includes_default - typedef pid_t ac__type_sizeof_; int main () { -static int test_array [1 - 2 * !(((long int) (sizeof (ac__type_sizeof_))) >= 0)]; +static int test_array [1 - 2 * !(((long int) (sizeof (pid_t))) >= 0)]; test_array [0] = 0 ; @@ -10526,13 +10889,14 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_compile") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { test -z "$ac_c_werror_flag" || test ! -s conftest.err @@ -10546,11 +10910,10 @@ cat >>conftest.$ac_ext <<_ACEOF /* end confdefs.h. */ $ac_includes_default - typedef pid_t ac__type_sizeof_; int main () { -static int test_array [1 - 2 * !(((long int) (sizeof (ac__type_sizeof_))) <= $ac_mid)]; +static int test_array [1 - 2 * !(((long int) (sizeof (pid_t))) <= $ac_mid)]; test_array [0] = 0 ; @@ -10563,20 +10926,21 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_compile") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { test -z "$ac_c_werror_flag" || test ! -s conftest.err } && test -s conftest.$ac_objext; then ac_hi=$ac_mid; break else - echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 ac_lo=`expr $ac_mid + 1` @@ -10590,7 +10954,7 @@ rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext done else - echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 cat >conftest.$ac_ext <<_ACEOF @@ -10600,11 +10964,10 @@ cat >>conftest.$ac_ext <<_ACEOF /* end confdefs.h. */ $ac_includes_default - typedef pid_t ac__type_sizeof_; int main () { -static int test_array [1 - 2 * !(((long int) (sizeof (ac__type_sizeof_))) < 0)]; +static int test_array [1 - 2 * !(((long int) (sizeof (pid_t))) < 0)]; test_array [0] = 0 ; @@ -10617,13 +10980,14 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_compile") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { test -z "$ac_c_werror_flag" || test ! -s conftest.err @@ -10637,11 +11001,10 @@ cat >>conftest.$ac_ext <<_ACEOF /* end confdefs.h. */ $ac_includes_default - typedef pid_t ac__type_sizeof_; int main () { -static int test_array [1 - 2 * !(((long int) (sizeof (ac__type_sizeof_))) >= $ac_mid)]; +static int test_array [1 - 2 * !(((long int) (sizeof (pid_t))) >= $ac_mid)]; test_array [0] = 0 ; @@ -10654,20 +11017,21 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_compile") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { test -z "$ac_c_werror_flag" || test ! -s conftest.err } && test -s conftest.$ac_objext; then ac_lo=$ac_mid; break else - echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 ac_hi=`expr '(' $ac_mid ')' - 1` @@ -10681,7 +11045,7 @@ rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext done else - echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 ac_lo= ac_hi= @@ -10701,11 +11065,10 @@ cat >>conftest.$ac_ext <<_ACEOF /* end confdefs.h. */ $ac_includes_default - typedef pid_t ac__type_sizeof_; int main () { -static int test_array [1 - 2 * !(((long int) (sizeof (ac__type_sizeof_))) <= $ac_mid)]; +static int test_array [1 - 2 * !(((long int) (sizeof (pid_t))) <= $ac_mid)]; test_array [0] = 0 ; @@ -10718,20 +11081,21 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_compile") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { test -z "$ac_c_werror_flag" || test ! -s conftest.err } && test -s conftest.$ac_objext; then ac_hi=$ac_mid else - echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 ac_lo=`expr '(' $ac_mid ')' + 1` @@ -10742,11 +11106,13 @@ case $ac_lo in ?*) ac_cv_sizeof_pid_t=$ac_lo;; '') if test "$ac_cv_type_pid_t" = yes; then - { { echo "$as_me:$LINENO: error: cannot compute sizeof (pid_t) + { { $as_echo "$as_me:$LINENO: error: in \`$ac_pwd':" >&5 +$as_echo "$as_me: error: in \`$ac_pwd':" >&2;} +{ { $as_echo "$as_me:$LINENO: error: cannot compute sizeof (pid_t) See \`config.log' for more details." >&5 -echo "$as_me: error: cannot compute sizeof (pid_t) +$as_echo "$as_me: error: cannot compute sizeof (pid_t) See \`config.log' for more details." >&2;} - { (exit 77); exit 77; }; } + { (exit 77); exit 77; }; }; } else ac_cv_sizeof_pid_t=0 fi ;; @@ -10759,9 +11125,8 @@ cat >>conftest.$ac_ext <<_ACEOF /* end confdefs.h. */ $ac_includes_default - typedef pid_t ac__type_sizeof_; -static long int longval () { return (long int) (sizeof (ac__type_sizeof_)); } -static unsigned long int ulongval () { return (long int) (sizeof (ac__type_sizeof_)); } +static long int longval () { return (long int) (sizeof (pid_t)); } +static unsigned long int ulongval () { return (long int) (sizeof (pid_t)); } #include #include int @@ -10771,20 +11136,22 @@ FILE *f = fopen ("conftest.val", "w"); if (! f) return 1; - if (((long int) (sizeof (ac__type_sizeof_))) < 0) + if (((long int) (sizeof (pid_t))) < 0) { long int i = longval (); - if (i != ((long int) (sizeof (ac__type_sizeof_)))) + if (i != ((long int) (sizeof (pid_t)))) return 1; - fprintf (f, "%ld\n", i); + fprintf (f, "%ld", i); } else { unsigned long int i = ulongval (); - if (i != ((long int) (sizeof (ac__type_sizeof_)))) + if (i != ((long int) (sizeof (pid_t)))) return 1; - fprintf (f, "%lu\n", i); + fprintf (f, "%lu", i); } + /* Do not output a trailing newline, as this causes \r\n confusion + on some platforms. */ return ferror (f) || fclose (f) != 0; ; @@ -10797,43 +11164,48 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_link") 2>&5 ac_status=$? - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { ac_try='./conftest$ac_exeext' { (case "(($ac_try" in *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_try") 2>&5 ac_status=$? - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); }; }; then ac_cv_sizeof_pid_t=`cat conftest.val` else - echo "$as_me: program exited with status $ac_status" >&5 -echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: program exited with status $ac_status" >&5 +$as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 ( exit $ac_status ) if test "$ac_cv_type_pid_t" = yes; then - { { echo "$as_me:$LINENO: error: cannot compute sizeof (pid_t) + { { $as_echo "$as_me:$LINENO: error: in \`$ac_pwd':" >&5 +$as_echo "$as_me: error: in \`$ac_pwd':" >&2;} +{ { $as_echo "$as_me:$LINENO: error: cannot compute sizeof (pid_t) See \`config.log' for more details." >&5 -echo "$as_me: error: cannot compute sizeof (pid_t) +$as_echo "$as_me: error: cannot compute sizeof (pid_t) See \`config.log' for more details." >&2;} - { (exit 77); exit 77; }; } + { (exit 77); exit 77; }; }; } else ac_cv_sizeof_pid_t=0 fi fi +rm -rf conftest.dSYM rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext conftest.$ac_objext conftest.$ac_ext fi rm -f conftest.val fi -{ echo "$as_me:$LINENO: result: $ac_cv_sizeof_pid_t" >&5 -echo "${ECHO_T}$ac_cv_sizeof_pid_t" >&6; } +{ $as_echo "$as_me:$LINENO: result: $ac_cv_sizeof_pid_t" >&5 +$as_echo "$ac_cv_sizeof_pid_t" >&6; } @@ -10843,8 +11215,8 @@ -{ echo "$as_me:$LINENO: checking for long long support" >&5 -echo $ECHO_N "checking for long long support... $ECHO_C" >&6; } +{ $as_echo "$as_me:$LINENO: checking for long long support" >&5 +$as_echo_n "checking for long long support... " >&6; } have_long_long=no cat >conftest.$ac_ext <<_ACEOF /* confdefs.h. */ @@ -10867,13 +11239,14 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_compile") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { test -z "$ac_c_werror_flag" || test ! -s conftest.err @@ -10887,78 +11260,24 @@ have_long_long=yes else - echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 fi rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext -{ echo "$as_me:$LINENO: result: $have_long_long" >&5 -echo "${ECHO_T}$have_long_long" >&6; } +{ $as_echo "$as_me:$LINENO: result: $have_long_long" >&5 +$as_echo "$have_long_long" >&6; } if test "$have_long_long" = yes ; then -{ echo "$as_me:$LINENO: checking for long long" >&5 -echo $ECHO_N "checking for long long... $ECHO_C" >&6; } -if test "${ac_cv_type_long_long+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 -else - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -$ac_includes_default -typedef long long ac__type_new_; -int -main () -{ -if ((ac__type_new_ *) 0) - return 0; -if (sizeof (ac__type_new_)) - return 0; - ; - return 0; -} -_ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - ac_cv_type_long_long=yes -else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - ac_cv_type_long_long=no -fi - -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext -fi -{ echo "$as_me:$LINENO: result: $ac_cv_type_long_long" >&5 -echo "${ECHO_T}$ac_cv_type_long_long" >&6; } - # The cast to long int works around a bug in the HP C Compiler # version HP92453-01 B.11.11.23709.GP, which incorrectly rejects # declarations like `int a3[[(sizeof (unsigned char)) >= 0]];'. # This bug is HP SR number 8606223364. -{ echo "$as_me:$LINENO: checking size of long long" >&5 -echo $ECHO_N "checking size of long long... $ECHO_C" >&6; } +{ $as_echo "$as_me:$LINENO: checking size of long long" >&5 +$as_echo_n "checking size of long long... " >&6; } if test "${ac_cv_sizeof_long_long+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 + $as_echo_n "(cached) " >&6 else if test "$cross_compiling" = yes; then # Depending upon the size, compute the lo and hi bounds. @@ -10969,11 +11288,10 @@ cat >>conftest.$ac_ext <<_ACEOF /* end confdefs.h. */ $ac_includes_default - typedef long long ac__type_sizeof_; int main () { -static int test_array [1 - 2 * !(((long int) (sizeof (ac__type_sizeof_))) >= 0)]; +static int test_array [1 - 2 * !(((long int) (sizeof (long long))) >= 0)]; test_array [0] = 0 ; @@ -10986,13 +11304,14 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_compile") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { test -z "$ac_c_werror_flag" || test ! -s conftest.err @@ -11006,11 +11325,10 @@ cat >>conftest.$ac_ext <<_ACEOF /* end confdefs.h. */ $ac_includes_default - typedef long long ac__type_sizeof_; int main () { -static int test_array [1 - 2 * !(((long int) (sizeof (ac__type_sizeof_))) <= $ac_mid)]; +static int test_array [1 - 2 * !(((long int) (sizeof (long long))) <= $ac_mid)]; test_array [0] = 0 ; @@ -11023,20 +11341,21 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_compile") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { test -z "$ac_c_werror_flag" || test ! -s conftest.err } && test -s conftest.$ac_objext; then ac_hi=$ac_mid; break else - echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 ac_lo=`expr $ac_mid + 1` @@ -11050,7 +11369,7 @@ rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext done else - echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 cat >conftest.$ac_ext <<_ACEOF @@ -11060,11 +11379,10 @@ cat >>conftest.$ac_ext <<_ACEOF /* end confdefs.h. */ $ac_includes_default - typedef long long ac__type_sizeof_; int main () { -static int test_array [1 - 2 * !(((long int) (sizeof (ac__type_sizeof_))) < 0)]; +static int test_array [1 - 2 * !(((long int) (sizeof (long long))) < 0)]; test_array [0] = 0 ; @@ -11077,13 +11395,14 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_compile") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { test -z "$ac_c_werror_flag" || test ! -s conftest.err @@ -11097,11 +11416,10 @@ cat >>conftest.$ac_ext <<_ACEOF /* end confdefs.h. */ $ac_includes_default - typedef long long ac__type_sizeof_; int main () { -static int test_array [1 - 2 * !(((long int) (sizeof (ac__type_sizeof_))) >= $ac_mid)]; +static int test_array [1 - 2 * !(((long int) (sizeof (long long))) >= $ac_mid)]; test_array [0] = 0 ; @@ -11114,20 +11432,21 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_compile") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { test -z "$ac_c_werror_flag" || test ! -s conftest.err } && test -s conftest.$ac_objext; then ac_lo=$ac_mid; break else - echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 ac_hi=`expr '(' $ac_mid ')' - 1` @@ -11141,7 +11460,7 @@ rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext done else - echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 ac_lo= ac_hi= @@ -11161,11 +11480,10 @@ cat >>conftest.$ac_ext <<_ACEOF /* end confdefs.h. */ $ac_includes_default - typedef long long ac__type_sizeof_; int main () { -static int test_array [1 - 2 * !(((long int) (sizeof (ac__type_sizeof_))) <= $ac_mid)]; +static int test_array [1 - 2 * !(((long int) (sizeof (long long))) <= $ac_mid)]; test_array [0] = 0 ; @@ -11178,20 +11496,21 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_compile") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { test -z "$ac_c_werror_flag" || test ! -s conftest.err } && test -s conftest.$ac_objext; then ac_hi=$ac_mid else - echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 ac_lo=`expr '(' $ac_mid ')' + 1` @@ -11202,11 +11521,13 @@ case $ac_lo in ?*) ac_cv_sizeof_long_long=$ac_lo;; '') if test "$ac_cv_type_long_long" = yes; then - { { echo "$as_me:$LINENO: error: cannot compute sizeof (long long) + { { $as_echo "$as_me:$LINENO: error: in \`$ac_pwd':" >&5 +$as_echo "$as_me: error: in \`$ac_pwd':" >&2;} +{ { $as_echo "$as_me:$LINENO: error: cannot compute sizeof (long long) See \`config.log' for more details." >&5 -echo "$as_me: error: cannot compute sizeof (long long) +$as_echo "$as_me: error: cannot compute sizeof (long long) See \`config.log' for more details." >&2;} - { (exit 77); exit 77; }; } + { (exit 77); exit 77; }; }; } else ac_cv_sizeof_long_long=0 fi ;; @@ -11219,9 +11540,8 @@ cat >>conftest.$ac_ext <<_ACEOF /* end confdefs.h. */ $ac_includes_default - typedef long long ac__type_sizeof_; -static long int longval () { return (long int) (sizeof (ac__type_sizeof_)); } -static unsigned long int ulongval () { return (long int) (sizeof (ac__type_sizeof_)); } +static long int longval () { return (long int) (sizeof (long long)); } +static unsigned long int ulongval () { return (long int) (sizeof (long long)); } #include #include int @@ -11231,20 +11551,22 @@ FILE *f = fopen ("conftest.val", "w"); if (! f) return 1; - if (((long int) (sizeof (ac__type_sizeof_))) < 0) + if (((long int) (sizeof (long long))) < 0) { long int i = longval (); - if (i != ((long int) (sizeof (ac__type_sizeof_)))) + if (i != ((long int) (sizeof (long long)))) return 1; - fprintf (f, "%ld\n", i); + fprintf (f, "%ld", i); } else { unsigned long int i = ulongval (); - if (i != ((long int) (sizeof (ac__type_sizeof_)))) + if (i != ((long int) (sizeof (long long)))) return 1; - fprintf (f, "%lu\n", i); + fprintf (f, "%lu", i); } + /* Do not output a trailing newline, as this causes \r\n confusion + on some platforms. */ return ferror (f) || fclose (f) != 0; ; @@ -11257,43 +11579,48 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_link") 2>&5 ac_status=$? - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { ac_try='./conftest$ac_exeext' { (case "(($ac_try" in *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_try") 2>&5 ac_status=$? - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); }; }; then ac_cv_sizeof_long_long=`cat conftest.val` else - echo "$as_me: program exited with status $ac_status" >&5 -echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: program exited with status $ac_status" >&5 +$as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 ( exit $ac_status ) if test "$ac_cv_type_long_long" = yes; then - { { echo "$as_me:$LINENO: error: cannot compute sizeof (long long) + { { $as_echo "$as_me:$LINENO: error: in \`$ac_pwd':" >&5 +$as_echo "$as_me: error: in \`$ac_pwd':" >&2;} +{ { $as_echo "$as_me:$LINENO: error: cannot compute sizeof (long long) See \`config.log' for more details." >&5 -echo "$as_me: error: cannot compute sizeof (long long) +$as_echo "$as_me: error: cannot compute sizeof (long long) See \`config.log' for more details." >&2;} - { (exit 77); exit 77; }; } + { (exit 77); exit 77; }; }; } else ac_cv_sizeof_long_long=0 fi fi +rm -rf conftest.dSYM rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext conftest.$ac_objext conftest.$ac_ext fi rm -f conftest.val fi -{ echo "$as_me:$LINENO: result: $ac_cv_sizeof_long_long" >&5 -echo "${ECHO_T}$ac_cv_sizeof_long_long" >&6; } +{ $as_echo "$as_me:$LINENO: result: $ac_cv_sizeof_long_long" >&5 +$as_echo "$ac_cv_sizeof_long_long" >&6; } @@ -11304,8 +11631,8 @@ fi -{ echo "$as_me:$LINENO: checking for long double support" >&5 -echo $ECHO_N "checking for long double support... $ECHO_C" >&6; } +{ $as_echo "$as_me:$LINENO: checking for long double support" >&5 +$as_echo_n "checking for long double support... " >&6; } have_long_double=no cat >conftest.$ac_ext <<_ACEOF /* confdefs.h. */ @@ -11328,13 +11655,14 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_compile") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { test -z "$ac_c_werror_flag" || test ! -s conftest.err @@ -11348,78 +11676,24 @@ have_long_double=yes else - echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 fi rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext -{ echo "$as_me:$LINENO: result: $have_long_double" >&5 -echo "${ECHO_T}$have_long_double" >&6; } +{ $as_echo "$as_me:$LINENO: result: $have_long_double" >&5 +$as_echo "$have_long_double" >&6; } if test "$have_long_double" = yes ; then -{ echo "$as_me:$LINENO: checking for long double" >&5 -echo $ECHO_N "checking for long double... $ECHO_C" >&6; } -if test "${ac_cv_type_long_double+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 -else - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -$ac_includes_default -typedef long double ac__type_new_; -int -main () -{ -if ((ac__type_new_ *) 0) - return 0; -if (sizeof (ac__type_new_)) - return 0; - ; - return 0; -} -_ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - ac_cv_type_long_double=yes -else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - ac_cv_type_long_double=no -fi - -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext -fi -{ echo "$as_me:$LINENO: result: $ac_cv_type_long_double" >&5 -echo "${ECHO_T}$ac_cv_type_long_double" >&6; } - # The cast to long int works around a bug in the HP C Compiler # version HP92453-01 B.11.11.23709.GP, which incorrectly rejects # declarations like `int a3[[(sizeof (unsigned char)) >= 0]];'. # This bug is HP SR number 8606223364. -{ echo "$as_me:$LINENO: checking size of long double" >&5 -echo $ECHO_N "checking size of long double... $ECHO_C" >&6; } +{ $as_echo "$as_me:$LINENO: checking size of long double" >&5 +$as_echo_n "checking size of long double... " >&6; } if test "${ac_cv_sizeof_long_double+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 + $as_echo_n "(cached) " >&6 else if test "$cross_compiling" = yes; then # Depending upon the size, compute the lo and hi bounds. @@ -11430,11 +11704,10 @@ cat >>conftest.$ac_ext <<_ACEOF /* end confdefs.h. */ $ac_includes_default - typedef long double ac__type_sizeof_; int main () { -static int test_array [1 - 2 * !(((long int) (sizeof (ac__type_sizeof_))) >= 0)]; +static int test_array [1 - 2 * !(((long int) (sizeof (long double))) >= 0)]; test_array [0] = 0 ; @@ -11447,13 +11720,14 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_compile") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { test -z "$ac_c_werror_flag" || test ! -s conftest.err @@ -11467,11 +11741,10 @@ cat >>conftest.$ac_ext <<_ACEOF /* end confdefs.h. */ $ac_includes_default - typedef long double ac__type_sizeof_; int main () { -static int test_array [1 - 2 * !(((long int) (sizeof (ac__type_sizeof_))) <= $ac_mid)]; +static int test_array [1 - 2 * !(((long int) (sizeof (long double))) <= $ac_mid)]; test_array [0] = 0 ; @@ -11484,20 +11757,21 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_compile") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { test -z "$ac_c_werror_flag" || test ! -s conftest.err } && test -s conftest.$ac_objext; then ac_hi=$ac_mid; break else - echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 ac_lo=`expr $ac_mid + 1` @@ -11511,7 +11785,7 @@ rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext done else - echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 cat >conftest.$ac_ext <<_ACEOF @@ -11521,11 +11795,10 @@ cat >>conftest.$ac_ext <<_ACEOF /* end confdefs.h. */ $ac_includes_default - typedef long double ac__type_sizeof_; int main () { -static int test_array [1 - 2 * !(((long int) (sizeof (ac__type_sizeof_))) < 0)]; +static int test_array [1 - 2 * !(((long int) (sizeof (long double))) < 0)]; test_array [0] = 0 ; @@ -11538,13 +11811,14 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_compile") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { test -z "$ac_c_werror_flag" || test ! -s conftest.err @@ -11558,11 +11832,10 @@ cat >>conftest.$ac_ext <<_ACEOF /* end confdefs.h. */ $ac_includes_default - typedef long double ac__type_sizeof_; int main () { -static int test_array [1 - 2 * !(((long int) (sizeof (ac__type_sizeof_))) >= $ac_mid)]; +static int test_array [1 - 2 * !(((long int) (sizeof (long double))) >= $ac_mid)]; test_array [0] = 0 ; @@ -11575,20 +11848,21 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_compile") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { test -z "$ac_c_werror_flag" || test ! -s conftest.err } && test -s conftest.$ac_objext; then ac_lo=$ac_mid; break else - echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 ac_hi=`expr '(' $ac_mid ')' - 1` @@ -11602,7 +11876,7 @@ rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext done else - echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 ac_lo= ac_hi= @@ -11622,11 +11896,10 @@ cat >>conftest.$ac_ext <<_ACEOF /* end confdefs.h. */ $ac_includes_default - typedef long double ac__type_sizeof_; int main () { -static int test_array [1 - 2 * !(((long int) (sizeof (ac__type_sizeof_))) <= $ac_mid)]; +static int test_array [1 - 2 * !(((long int) (sizeof (long double))) <= $ac_mid)]; test_array [0] = 0 ; @@ -11639,20 +11912,21 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_compile") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { test -z "$ac_c_werror_flag" || test ! -s conftest.err } && test -s conftest.$ac_objext; then ac_hi=$ac_mid else - echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 ac_lo=`expr '(' $ac_mid ')' + 1` @@ -11663,11 +11937,13 @@ case $ac_lo in ?*) ac_cv_sizeof_long_double=$ac_lo;; '') if test "$ac_cv_type_long_double" = yes; then - { { echo "$as_me:$LINENO: error: cannot compute sizeof (long double) + { { $as_echo "$as_me:$LINENO: error: in \`$ac_pwd':" >&5 +$as_echo "$as_me: error: in \`$ac_pwd':" >&2;} +{ { $as_echo "$as_me:$LINENO: error: cannot compute sizeof (long double) See \`config.log' for more details." >&5 -echo "$as_me: error: cannot compute sizeof (long double) +$as_echo "$as_me: error: cannot compute sizeof (long double) See \`config.log' for more details." >&2;} - { (exit 77); exit 77; }; } + { (exit 77); exit 77; }; }; } else ac_cv_sizeof_long_double=0 fi ;; @@ -11680,9 +11956,8 @@ cat >>conftest.$ac_ext <<_ACEOF /* end confdefs.h. */ $ac_includes_default - typedef long double ac__type_sizeof_; -static long int longval () { return (long int) (sizeof (ac__type_sizeof_)); } -static unsigned long int ulongval () { return (long int) (sizeof (ac__type_sizeof_)); } +static long int longval () { return (long int) (sizeof (long double)); } +static unsigned long int ulongval () { return (long int) (sizeof (long double)); } #include #include int @@ -11692,20 +11967,22 @@ FILE *f = fopen ("conftest.val", "w"); if (! f) return 1; - if (((long int) (sizeof (ac__type_sizeof_))) < 0) + if (((long int) (sizeof (long double))) < 0) { long int i = longval (); - if (i != ((long int) (sizeof (ac__type_sizeof_)))) + if (i != ((long int) (sizeof (long double)))) return 1; - fprintf (f, "%ld\n", i); + fprintf (f, "%ld", i); } else { unsigned long int i = ulongval (); - if (i != ((long int) (sizeof (ac__type_sizeof_)))) + if (i != ((long int) (sizeof (long double)))) return 1; - fprintf (f, "%lu\n", i); + fprintf (f, "%lu", i); } + /* Do not output a trailing newline, as this causes \r\n confusion + on some platforms. */ return ferror (f) || fclose (f) != 0; ; @@ -11718,43 +11995,48 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_link") 2>&5 ac_status=$? - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { ac_try='./conftest$ac_exeext' { (case "(($ac_try" in *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_try") 2>&5 ac_status=$? - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); }; }; then ac_cv_sizeof_long_double=`cat conftest.val` else - echo "$as_me: program exited with status $ac_status" >&5 -echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: program exited with status $ac_status" >&5 +$as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 ( exit $ac_status ) if test "$ac_cv_type_long_double" = yes; then - { { echo "$as_me:$LINENO: error: cannot compute sizeof (long double) + { { $as_echo "$as_me:$LINENO: error: in \`$ac_pwd':" >&5 +$as_echo "$as_me: error: in \`$ac_pwd':" >&2;} +{ { $as_echo "$as_me:$LINENO: error: cannot compute sizeof (long double) See \`config.log' for more details." >&5 -echo "$as_me: error: cannot compute sizeof (long double) +$as_echo "$as_me: error: cannot compute sizeof (long double) See \`config.log' for more details." >&2;} - { (exit 77); exit 77; }; } + { (exit 77); exit 77; }; }; } else ac_cv_sizeof_long_double=0 fi fi +rm -rf conftest.dSYM rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext conftest.$ac_objext conftest.$ac_ext fi rm -f conftest.val fi -{ echo "$as_me:$LINENO: result: $ac_cv_sizeof_long_double" >&5 -echo "${ECHO_T}$ac_cv_sizeof_long_double" >&6; } +{ $as_echo "$as_me:$LINENO: result: $ac_cv_sizeof_long_double" >&5 +$as_echo "$ac_cv_sizeof_long_double" >&6; } @@ -11765,8 +12047,8 @@ fi -{ echo "$as_me:$LINENO: checking for _Bool support" >&5 -echo $ECHO_N "checking for _Bool support... $ECHO_C" >&6; } +{ $as_echo "$as_me:$LINENO: checking for _Bool support" >&5 +$as_echo_n "checking for _Bool support... " >&6; } have_c99_bool=no cat >conftest.$ac_ext <<_ACEOF /* confdefs.h. */ @@ -11789,13 +12071,14 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_compile") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { test -z "$ac_c_werror_flag" || test ! -s conftest.err @@ -11809,78 +12092,24 @@ have_c99_bool=yes else - echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 fi rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext -{ echo "$as_me:$LINENO: result: $have_c99_bool" >&5 -echo "${ECHO_T}$have_c99_bool" >&6; } +{ $as_echo "$as_me:$LINENO: result: $have_c99_bool" >&5 +$as_echo "$have_c99_bool" >&6; } if test "$have_c99_bool" = yes ; then -{ echo "$as_me:$LINENO: checking for _Bool" >&5 -echo $ECHO_N "checking for _Bool... $ECHO_C" >&6; } -if test "${ac_cv_type__Bool+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 -else - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -$ac_includes_default -typedef _Bool ac__type_new_; -int -main () -{ -if ((ac__type_new_ *) 0) - return 0; -if (sizeof (ac__type_new_)) - return 0; - ; - return 0; -} -_ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - ac_cv_type__Bool=yes -else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - ac_cv_type__Bool=no -fi - -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext -fi -{ echo "$as_me:$LINENO: result: $ac_cv_type__Bool" >&5 -echo "${ECHO_T}$ac_cv_type__Bool" >&6; } - # The cast to long int works around a bug in the HP C Compiler # version HP92453-01 B.11.11.23709.GP, which incorrectly rejects # declarations like `int a3[[(sizeof (unsigned char)) >= 0]];'. # This bug is HP SR number 8606223364. -{ echo "$as_me:$LINENO: checking size of _Bool" >&5 -echo $ECHO_N "checking size of _Bool... $ECHO_C" >&6; } +{ $as_echo "$as_me:$LINENO: checking size of _Bool" >&5 +$as_echo_n "checking size of _Bool... " >&6; } if test "${ac_cv_sizeof__Bool+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 + $as_echo_n "(cached) " >&6 else if test "$cross_compiling" = yes; then # Depending upon the size, compute the lo and hi bounds. @@ -11891,11 +12120,10 @@ cat >>conftest.$ac_ext <<_ACEOF /* end confdefs.h. */ $ac_includes_default - typedef _Bool ac__type_sizeof_; int main () { -static int test_array [1 - 2 * !(((long int) (sizeof (ac__type_sizeof_))) >= 0)]; +static int test_array [1 - 2 * !(((long int) (sizeof (_Bool))) >= 0)]; test_array [0] = 0 ; @@ -11908,13 +12136,14 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_compile") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { test -z "$ac_c_werror_flag" || test ! -s conftest.err @@ -11928,11 +12157,10 @@ cat >>conftest.$ac_ext <<_ACEOF /* end confdefs.h. */ $ac_includes_default - typedef _Bool ac__type_sizeof_; int main () { -static int test_array [1 - 2 * !(((long int) (sizeof (ac__type_sizeof_))) <= $ac_mid)]; +static int test_array [1 - 2 * !(((long int) (sizeof (_Bool))) <= $ac_mid)]; test_array [0] = 0 ; @@ -11945,20 +12173,21 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_compile") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { test -z "$ac_c_werror_flag" || test ! -s conftest.err } && test -s conftest.$ac_objext; then ac_hi=$ac_mid; break else - echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 ac_lo=`expr $ac_mid + 1` @@ -11972,7 +12201,7 @@ rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext done else - echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 cat >conftest.$ac_ext <<_ACEOF @@ -11982,11 +12211,10 @@ cat >>conftest.$ac_ext <<_ACEOF /* end confdefs.h. */ $ac_includes_default - typedef _Bool ac__type_sizeof_; int main () { -static int test_array [1 - 2 * !(((long int) (sizeof (ac__type_sizeof_))) < 0)]; +static int test_array [1 - 2 * !(((long int) (sizeof (_Bool))) < 0)]; test_array [0] = 0 ; @@ -11999,13 +12227,14 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_compile") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { test -z "$ac_c_werror_flag" || test ! -s conftest.err @@ -12019,11 +12248,10 @@ cat >>conftest.$ac_ext <<_ACEOF /* end confdefs.h. */ $ac_includes_default - typedef _Bool ac__type_sizeof_; int main () { -static int test_array [1 - 2 * !(((long int) (sizeof (ac__type_sizeof_))) >= $ac_mid)]; +static int test_array [1 - 2 * !(((long int) (sizeof (_Bool))) >= $ac_mid)]; test_array [0] = 0 ; @@ -12036,20 +12264,21 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_compile") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { test -z "$ac_c_werror_flag" || test ! -s conftest.err } && test -s conftest.$ac_objext; then ac_lo=$ac_mid; break else - echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 ac_hi=`expr '(' $ac_mid ')' - 1` @@ -12063,7 +12292,7 @@ rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext done else - echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 ac_lo= ac_hi= @@ -12083,11 +12312,10 @@ cat >>conftest.$ac_ext <<_ACEOF /* end confdefs.h. */ $ac_includes_default - typedef _Bool ac__type_sizeof_; int main () { -static int test_array [1 - 2 * !(((long int) (sizeof (ac__type_sizeof_))) <= $ac_mid)]; +static int test_array [1 - 2 * !(((long int) (sizeof (_Bool))) <= $ac_mid)]; test_array [0] = 0 ; @@ -12100,20 +12328,21 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_compile") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { test -z "$ac_c_werror_flag" || test ! -s conftest.err } && test -s conftest.$ac_objext; then ac_hi=$ac_mid else - echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 ac_lo=`expr '(' $ac_mid ')' + 1` @@ -12124,11 +12353,13 @@ case $ac_lo in ?*) ac_cv_sizeof__Bool=$ac_lo;; '') if test "$ac_cv_type__Bool" = yes; then - { { echo "$as_me:$LINENO: error: cannot compute sizeof (_Bool) + { { $as_echo "$as_me:$LINENO: error: in \`$ac_pwd':" >&5 +$as_echo "$as_me: error: in \`$ac_pwd':" >&2;} +{ { $as_echo "$as_me:$LINENO: error: cannot compute sizeof (_Bool) See \`config.log' for more details." >&5 -echo "$as_me: error: cannot compute sizeof (_Bool) +$as_echo "$as_me: error: cannot compute sizeof (_Bool) See \`config.log' for more details." >&2;} - { (exit 77); exit 77; }; } + { (exit 77); exit 77; }; }; } else ac_cv_sizeof__Bool=0 fi ;; @@ -12141,9 +12372,8 @@ cat >>conftest.$ac_ext <<_ACEOF /* end confdefs.h. */ $ac_includes_default - typedef _Bool ac__type_sizeof_; -static long int longval () { return (long int) (sizeof (ac__type_sizeof_)); } -static unsigned long int ulongval () { return (long int) (sizeof (ac__type_sizeof_)); } +static long int longval () { return (long int) (sizeof (_Bool)); } +static unsigned long int ulongval () { return (long int) (sizeof (_Bool)); } #include #include int @@ -12153,20 +12383,22 @@ FILE *f = fopen ("conftest.val", "w"); if (! f) return 1; - if (((long int) (sizeof (ac__type_sizeof_))) < 0) + if (((long int) (sizeof (_Bool))) < 0) { long int i = longval (); - if (i != ((long int) (sizeof (ac__type_sizeof_)))) + if (i != ((long int) (sizeof (_Bool)))) return 1; - fprintf (f, "%ld\n", i); + fprintf (f, "%ld", i); } else { unsigned long int i = ulongval (); - if (i != ((long int) (sizeof (ac__type_sizeof_)))) + if (i != ((long int) (sizeof (_Bool)))) return 1; - fprintf (f, "%lu\n", i); + fprintf (f, "%lu", i); } + /* Do not output a trailing newline, as this causes \r\n confusion + on some platforms. */ return ferror (f) || fclose (f) != 0; ; @@ -12179,43 +12411,48 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_link") 2>&5 ac_status=$? - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { ac_try='./conftest$ac_exeext' { (case "(($ac_try" in *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_try") 2>&5 ac_status=$? - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); }; }; then ac_cv_sizeof__Bool=`cat conftest.val` else - echo "$as_me: program exited with status $ac_status" >&5 -echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: program exited with status $ac_status" >&5 +$as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 ( exit $ac_status ) if test "$ac_cv_type__Bool" = yes; then - { { echo "$as_me:$LINENO: error: cannot compute sizeof (_Bool) + { { $as_echo "$as_me:$LINENO: error: in \`$ac_pwd':" >&5 +$as_echo "$as_me: error: in \`$ac_pwd':" >&2;} +{ { $as_echo "$as_me:$LINENO: error: cannot compute sizeof (_Bool) See \`config.log' for more details." >&5 -echo "$as_me: error: cannot compute sizeof (_Bool) +$as_echo "$as_me: error: cannot compute sizeof (_Bool) See \`config.log' for more details." >&2;} - { (exit 77); exit 77; }; } + { (exit 77); exit 77; }; }; } else ac_cv_sizeof__Bool=0 fi fi +rm -rf conftest.dSYM rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext conftest.$ac_objext conftest.$ac_ext fi rm -f conftest.val fi -{ echo "$as_me:$LINENO: result: $ac_cv_sizeof__Bool" >&5 -echo "${ECHO_T}$ac_cv_sizeof__Bool" >&6; } +{ $as_echo "$as_me:$LINENO: result: $ac_cv_sizeof__Bool" >&5 +$as_echo "$ac_cv_sizeof__Bool" >&6; } @@ -12226,12 +12463,13 @@ fi -{ echo "$as_me:$LINENO: checking for uintptr_t" >&5 -echo $ECHO_N "checking for uintptr_t... $ECHO_C" >&6; } +{ $as_echo "$as_me:$LINENO: checking for uintptr_t" >&5 +$as_echo_n "checking for uintptr_t... " >&6; } if test "${ac_cv_type_uintptr_t+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 + $as_echo_n "(cached) " >&6 else - cat >conftest.$ac_ext <<_ACEOF + ac_cv_type_uintptr_t=no +cat >conftest.$ac_ext <<_ACEOF /* confdefs.h. */ _ACEOF cat confdefs.h >>conftest.$ac_ext @@ -12241,14 +12479,11 @@ #include #endif -typedef uintptr_t ac__type_new_; int main () { -if ((ac__type_new_ *) 0) - return 0; -if (sizeof (ac__type_new_)) - return 0; +if (sizeof (uintptr_t)) + return 0; ; return 0; } @@ -12259,55 +12494,33 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_compile") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - ac_cv_type_uintptr_t=yes -else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - ac_cv_type_uintptr_t=no -fi - -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext -fi -{ echo "$as_me:$LINENO: result: $ac_cv_type_uintptr_t" >&5 -echo "${ECHO_T}$ac_cv_type_uintptr_t" >&6; } -if test $ac_cv_type_uintptr_t = yes; then - -cat >>confdefs.h <<_ACEOF -#define HAVE_UINTPTR_T 1 -_ACEOF - -{ echo "$as_me:$LINENO: checking for uintptr_t" >&5 -echo $ECHO_N "checking for uintptr_t... $ECHO_C" >&6; } -if test "${ac_cv_type_uintptr_t+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 -else + cat conftest.err >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 + (exit $ac_status); } && { + test -z "$ac_c_werror_flag" || + test ! -s conftest.err + } && test -s conftest.$ac_objext; then cat >conftest.$ac_ext <<_ACEOF /* confdefs.h. */ _ACEOF cat confdefs.h >>conftest.$ac_ext cat >>conftest.$ac_ext <<_ACEOF /* end confdefs.h. */ -$ac_includes_default -typedef uintptr_t ac__type_new_; +#ifdef HAVE_STDINT_H + #include + #endif + int main () { -if ((ac__type_new_ *) 0) - return 0; -if (sizeof (ac__type_new_)) - return 0; +if (sizeof ((uintptr_t))) + return 0; ; return 0; } @@ -12318,38 +12531,52 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_compile") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { test -z "$ac_c_werror_flag" || test ! -s conftest.err } && test -s conftest.$ac_objext; then - ac_cv_type_uintptr_t=yes + : +else + $as_echo "$as_me: failed program was:" >&5 +sed 's/^/| /' conftest.$ac_ext >&5 + + ac_cv_type_uintptr_t=yes +fi + +rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext else - echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 - ac_cv_type_uintptr_t=no + fi rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext fi -{ echo "$as_me:$LINENO: result: $ac_cv_type_uintptr_t" >&5 -echo "${ECHO_T}$ac_cv_type_uintptr_t" >&6; } +{ $as_echo "$as_me:$LINENO: result: $ac_cv_type_uintptr_t" >&5 +$as_echo "$ac_cv_type_uintptr_t" >&6; } +if test "x$ac_cv_type_uintptr_t" = x""yes; then + +cat >>confdefs.h <<_ACEOF +#define HAVE_UINTPTR_T 1 +_ACEOF # The cast to long int works around a bug in the HP C Compiler # version HP92453-01 B.11.11.23709.GP, which incorrectly rejects # declarations like `int a3[[(sizeof (unsigned char)) >= 0]];'. # This bug is HP SR number 8606223364. -{ echo "$as_me:$LINENO: checking size of uintptr_t" >&5 -echo $ECHO_N "checking size of uintptr_t... $ECHO_C" >&6; } +{ $as_echo "$as_me:$LINENO: checking size of uintptr_t" >&5 +$as_echo_n "checking size of uintptr_t... " >&6; } if test "${ac_cv_sizeof_uintptr_t+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 + $as_echo_n "(cached) " >&6 else if test "$cross_compiling" = yes; then # Depending upon the size, compute the lo and hi bounds. @@ -12360,11 +12587,10 @@ cat >>conftest.$ac_ext <<_ACEOF /* end confdefs.h. */ $ac_includes_default - typedef uintptr_t ac__type_sizeof_; int main () { -static int test_array [1 - 2 * !(((long int) (sizeof (ac__type_sizeof_))) >= 0)]; +static int test_array [1 - 2 * !(((long int) (sizeof (uintptr_t))) >= 0)]; test_array [0] = 0 ; @@ -12377,13 +12603,14 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_compile") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { test -z "$ac_c_werror_flag" || test ! -s conftest.err @@ -12397,11 +12624,10 @@ cat >>conftest.$ac_ext <<_ACEOF /* end confdefs.h. */ $ac_includes_default - typedef uintptr_t ac__type_sizeof_; int main () { -static int test_array [1 - 2 * !(((long int) (sizeof (ac__type_sizeof_))) <= $ac_mid)]; +static int test_array [1 - 2 * !(((long int) (sizeof (uintptr_t))) <= $ac_mid)]; test_array [0] = 0 ; @@ -12414,20 +12640,21 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_compile") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { test -z "$ac_c_werror_flag" || test ! -s conftest.err } && test -s conftest.$ac_objext; then ac_hi=$ac_mid; break else - echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 ac_lo=`expr $ac_mid + 1` @@ -12441,7 +12668,7 @@ rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext done else - echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 cat >conftest.$ac_ext <<_ACEOF @@ -12451,11 +12678,10 @@ cat >>conftest.$ac_ext <<_ACEOF /* end confdefs.h. */ $ac_includes_default - typedef uintptr_t ac__type_sizeof_; int main () { -static int test_array [1 - 2 * !(((long int) (sizeof (ac__type_sizeof_))) < 0)]; +static int test_array [1 - 2 * !(((long int) (sizeof (uintptr_t))) < 0)]; test_array [0] = 0 ; @@ -12468,13 +12694,14 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_compile") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { test -z "$ac_c_werror_flag" || test ! -s conftest.err @@ -12488,11 +12715,10 @@ cat >>conftest.$ac_ext <<_ACEOF /* end confdefs.h. */ $ac_includes_default - typedef uintptr_t ac__type_sizeof_; int main () { -static int test_array [1 - 2 * !(((long int) (sizeof (ac__type_sizeof_))) >= $ac_mid)]; +static int test_array [1 - 2 * !(((long int) (sizeof (uintptr_t))) >= $ac_mid)]; test_array [0] = 0 ; @@ -12505,20 +12731,21 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_compile") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { test -z "$ac_c_werror_flag" || test ! -s conftest.err } && test -s conftest.$ac_objext; then ac_lo=$ac_mid; break else - echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 ac_hi=`expr '(' $ac_mid ')' - 1` @@ -12532,7 +12759,7 @@ rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext done else - echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 ac_lo= ac_hi= @@ -12552,11 +12779,10 @@ cat >>conftest.$ac_ext <<_ACEOF /* end confdefs.h. */ $ac_includes_default - typedef uintptr_t ac__type_sizeof_; int main () { -static int test_array [1 - 2 * !(((long int) (sizeof (ac__type_sizeof_))) <= $ac_mid)]; +static int test_array [1 - 2 * !(((long int) (sizeof (uintptr_t))) <= $ac_mid)]; test_array [0] = 0 ; @@ -12569,20 +12795,21 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_compile") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { test -z "$ac_c_werror_flag" || test ! -s conftest.err } && test -s conftest.$ac_objext; then ac_hi=$ac_mid else - echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 ac_lo=`expr '(' $ac_mid ')' + 1` @@ -12593,11 +12820,13 @@ case $ac_lo in ?*) ac_cv_sizeof_uintptr_t=$ac_lo;; '') if test "$ac_cv_type_uintptr_t" = yes; then - { { echo "$as_me:$LINENO: error: cannot compute sizeof (uintptr_t) + { { $as_echo "$as_me:$LINENO: error: in \`$ac_pwd':" >&5 +$as_echo "$as_me: error: in \`$ac_pwd':" >&2;} +{ { $as_echo "$as_me:$LINENO: error: cannot compute sizeof (uintptr_t) See \`config.log' for more details." >&5 -echo "$as_me: error: cannot compute sizeof (uintptr_t) +$as_echo "$as_me: error: cannot compute sizeof (uintptr_t) See \`config.log' for more details." >&2;} - { (exit 77); exit 77; }; } + { (exit 77); exit 77; }; }; } else ac_cv_sizeof_uintptr_t=0 fi ;; @@ -12610,9 +12839,8 @@ cat >>conftest.$ac_ext <<_ACEOF /* end confdefs.h. */ $ac_includes_default - typedef uintptr_t ac__type_sizeof_; -static long int longval () { return (long int) (sizeof (ac__type_sizeof_)); } -static unsigned long int ulongval () { return (long int) (sizeof (ac__type_sizeof_)); } +static long int longval () { return (long int) (sizeof (uintptr_t)); } +static unsigned long int ulongval () { return (long int) (sizeof (uintptr_t)); } #include #include int @@ -12622,20 +12850,22 @@ FILE *f = fopen ("conftest.val", "w"); if (! f) return 1; - if (((long int) (sizeof (ac__type_sizeof_))) < 0) + if (((long int) (sizeof (uintptr_t))) < 0) { long int i = longval (); - if (i != ((long int) (sizeof (ac__type_sizeof_)))) + if (i != ((long int) (sizeof (uintptr_t)))) return 1; - fprintf (f, "%ld\n", i); + fprintf (f, "%ld", i); } else { unsigned long int i = ulongval (); - if (i != ((long int) (sizeof (ac__type_sizeof_)))) + if (i != ((long int) (sizeof (uintptr_t)))) return 1; - fprintf (f, "%lu\n", i); + fprintf (f, "%lu", i); } + /* Do not output a trailing newline, as this causes \r\n confusion + on some platforms. */ return ferror (f) || fclose (f) != 0; ; @@ -12648,43 +12878,48 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_link") 2>&5 ac_status=$? - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { ac_try='./conftest$ac_exeext' { (case "(($ac_try" in *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_try") 2>&5 ac_status=$? - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); }; }; then ac_cv_sizeof_uintptr_t=`cat conftest.val` else - echo "$as_me: program exited with status $ac_status" >&5 -echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: program exited with status $ac_status" >&5 +$as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 ( exit $ac_status ) if test "$ac_cv_type_uintptr_t" = yes; then - { { echo "$as_me:$LINENO: error: cannot compute sizeof (uintptr_t) + { { $as_echo "$as_me:$LINENO: error: in \`$ac_pwd':" >&5 +$as_echo "$as_me: error: in \`$ac_pwd':" >&2;} +{ { $as_echo "$as_me:$LINENO: error: cannot compute sizeof (uintptr_t) See \`config.log' for more details." >&5 -echo "$as_me: error: cannot compute sizeof (uintptr_t) +$as_echo "$as_me: error: cannot compute sizeof (uintptr_t) See \`config.log' for more details." >&2;} - { (exit 77); exit 77; }; } + { (exit 77); exit 77; }; }; } else ac_cv_sizeof_uintptr_t=0 fi fi +rm -rf conftest.dSYM rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext conftest.$ac_objext conftest.$ac_ext fi rm -f conftest.val fi -{ echo "$as_me:$LINENO: result: $ac_cv_sizeof_uintptr_t" >&5 -echo "${ECHO_T}$ac_cv_sizeof_uintptr_t" >&6; } +{ $as_echo "$as_me:$LINENO: result: $ac_cv_sizeof_uintptr_t" >&5 +$as_echo "$ac_cv_sizeof_uintptr_t" >&6; } @@ -12698,10 +12933,10 @@ # Hmph. AC_CHECK_SIZEOF() doesn't include . -{ echo "$as_me:$LINENO: checking size of off_t" >&5 -echo $ECHO_N "checking size of off_t... $ECHO_C" >&6; } +{ $as_echo "$as_me:$LINENO: checking size of off_t" >&5 +$as_echo_n "checking size of off_t... " >&6; } if test "${ac_cv_sizeof_off_t+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 + $as_echo_n "(cached) " >&6 else if test "$cross_compiling" = yes; then ac_cv_sizeof_off_t=4 @@ -12728,29 +12963,32 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_link") 2>&5 ac_status=$? - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { ac_try='./conftest$ac_exeext' { (case "(($ac_try" in *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_try") 2>&5 ac_status=$? - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); }; }; then ac_cv_sizeof_off_t=`cat conftestval` else - echo "$as_me: program exited with status $ac_status" >&5 -echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: program exited with status $ac_status" >&5 +$as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 ( exit $ac_status ) ac_cv_sizeof_off_t=0 fi +rm -rf conftest.dSYM rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext conftest.$ac_objext conftest.$ac_ext fi @@ -12758,16 +12996,16 @@ fi -{ echo "$as_me:$LINENO: result: $ac_cv_sizeof_off_t" >&5 -echo "${ECHO_T}$ac_cv_sizeof_off_t" >&6; } +{ $as_echo "$as_me:$LINENO: result: $ac_cv_sizeof_off_t" >&5 +$as_echo "$ac_cv_sizeof_off_t" >&6; } cat >>confdefs.h <<_ACEOF #define SIZEOF_OFF_T $ac_cv_sizeof_off_t _ACEOF -{ echo "$as_me:$LINENO: checking whether to enable large file support" >&5 -echo $ECHO_N "checking whether to enable large file support... $ECHO_C" >&6; } +{ $as_echo "$as_me:$LINENO: checking whether to enable large file support" >&5 +$as_echo_n "checking whether to enable large file support... " >&6; } if test "$have_long_long" = yes then if test "$ac_cv_sizeof_off_t" -gt "$ac_cv_sizeof_long" -a \ @@ -12777,22 +13015,22 @@ #define HAVE_LARGEFILE_SUPPORT 1 _ACEOF - { echo "$as_me:$LINENO: result: yes" >&5 -echo "${ECHO_T}yes" >&6; } + { $as_echo "$as_me:$LINENO: result: yes" >&5 +$as_echo "yes" >&6; } else - { echo "$as_me:$LINENO: result: no" >&5 -echo "${ECHO_T}no" >&6; } + { $as_echo "$as_me:$LINENO: result: no" >&5 +$as_echo "no" >&6; } fi else - { echo "$as_me:$LINENO: result: no" >&5 -echo "${ECHO_T}no" >&6; } + { $as_echo "$as_me:$LINENO: result: no" >&5 +$as_echo "no" >&6; } fi # AC_CHECK_SIZEOF() doesn't include . -{ echo "$as_me:$LINENO: checking size of time_t" >&5 -echo $ECHO_N "checking size of time_t... $ECHO_C" >&6; } +{ $as_echo "$as_me:$LINENO: checking size of time_t" >&5 +$as_echo_n "checking size of time_t... " >&6; } if test "${ac_cv_sizeof_time_t+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 + $as_echo_n "(cached) " >&6 else if test "$cross_compiling" = yes; then ac_cv_sizeof_time_t=4 @@ -12819,29 +13057,32 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_link") 2>&5 ac_status=$? - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { ac_try='./conftest$ac_exeext' { (case "(($ac_try" in *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_try") 2>&5 ac_status=$? - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); }; }; then ac_cv_sizeof_time_t=`cat conftestval` else - echo "$as_me: program exited with status $ac_status" >&5 -echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: program exited with status $ac_status" >&5 +$as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 ( exit $ac_status ) ac_cv_sizeof_time_t=0 fi +rm -rf conftest.dSYM rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext conftest.$ac_objext conftest.$ac_ext fi @@ -12849,8 +13090,8 @@ fi -{ echo "$as_me:$LINENO: result: $ac_cv_sizeof_time_t" >&5 -echo "${ECHO_T}$ac_cv_sizeof_time_t" >&6; } +{ $as_echo "$as_me:$LINENO: result: $ac_cv_sizeof_time_t" >&5 +$as_echo "$ac_cv_sizeof_time_t" >&6; } cat >>confdefs.h <<_ACEOF #define SIZEOF_TIME_T $ac_cv_sizeof_time_t @@ -12867,8 +13108,8 @@ elif test "$ac_cv_pthread" = "yes" then CC="$CC -pthread" fi -{ echo "$as_me:$LINENO: checking for pthread_t" >&5 -echo $ECHO_N "checking for pthread_t... $ECHO_C" >&6; } +{ $as_echo "$as_me:$LINENO: checking for pthread_t" >&5 +$as_echo_n "checking for pthread_t... " >&6; } have_pthread_t=no cat >conftest.$ac_ext <<_ACEOF /* confdefs.h. */ @@ -12891,34 +13132,35 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_compile") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { test -z "$ac_c_werror_flag" || test ! -s conftest.err } && test -s conftest.$ac_objext; then have_pthread_t=yes else - echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 fi rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext -{ echo "$as_me:$LINENO: result: $have_pthread_t" >&5 -echo "${ECHO_T}$have_pthread_t" >&6; } +{ $as_echo "$as_me:$LINENO: result: $have_pthread_t" >&5 +$as_echo "$have_pthread_t" >&6; } if test "$have_pthread_t" = yes ; then # AC_CHECK_SIZEOF() doesn't include . - { echo "$as_me:$LINENO: checking size of pthread_t" >&5 -echo $ECHO_N "checking size of pthread_t... $ECHO_C" >&6; } + { $as_echo "$as_me:$LINENO: checking size of pthread_t" >&5 +$as_echo_n "checking size of pthread_t... " >&6; } if test "${ac_cv_sizeof_pthread_t+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 + $as_echo_n "(cached) " >&6 else if test "$cross_compiling" = yes; then ac_cv_sizeof_pthread_t=4 @@ -12945,29 +13187,32 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_link") 2>&5 ac_status=$? - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { ac_try='./conftest$ac_exeext' { (case "(($ac_try" in *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_try") 2>&5 ac_status=$? - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); }; }; then ac_cv_sizeof_pthread_t=`cat conftestval` else - echo "$as_me: program exited with status $ac_status" >&5 -echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: program exited with status $ac_status" >&5 +$as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 ( exit $ac_status ) ac_cv_sizeof_pthread_t=0 fi +rm -rf conftest.dSYM rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext conftest.$ac_objext conftest.$ac_ext fi @@ -12975,8 +13220,8 @@ fi - { echo "$as_me:$LINENO: result: $ac_cv_sizeof_pthread_t" >&5 -echo "${ECHO_T}$ac_cv_sizeof_pthread_t" >&6; } + { $as_echo "$as_me:$LINENO: result: $ac_cv_sizeof_pthread_t" >&5 +$as_echo "$ac_cv_sizeof_pthread_t" >&6; } cat >>confdefs.h <<_ACEOF #define SIZEOF_PTHREAD_T $ac_cv_sizeof_pthread_t @@ -12985,8 +13230,8 @@ fi CC="$ac_save_cc" -{ echo "$as_me:$LINENO: checking for --enable-toolbox-glue" >&5 -echo $ECHO_N "checking for --enable-toolbox-glue... $ECHO_C" >&6; } +{ $as_echo "$as_me:$LINENO: checking for --enable-toolbox-glue" >&5 +$as_echo_n "checking for --enable-toolbox-glue... " >&6; } # Check whether --enable-toolbox-glue was given. if test "${enable_toolbox_glue+set}" = set; then enableval=$enable_toolbox_glue; @@ -13017,8 +13262,8 @@ extra_undefs="" ;; esac -{ echo "$as_me:$LINENO: result: $enable_toolbox_glue" >&5 -echo "${ECHO_T}$enable_toolbox_glue" >&6; } +{ $as_echo "$as_me:$LINENO: result: $enable_toolbox_glue" >&5 +$as_echo "$enable_toolbox_glue" >&6; } @@ -13079,29 +13324,32 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_link") 2>&5 ac_status=$? - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { ac_try='./conftest$ac_exeext' { (case "(($ac_try" in *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_try") 2>&5 ac_status=$? - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); }; }; then ac_osx_32bit=yes else - echo "$as_me: program exited with status $ac_status" >&5 -echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: program exited with status $ac_status" >&5 +$as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 ( exit $ac_status ) ac_osx_32bit=no fi +rm -rf conftest.dSYM rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext conftest.$ac_objext conftest.$ac_ext fi @@ -13116,8 +13364,8 @@ MACOSX_DEFAULT_ARCH="ppc" ;; *) - { { echo "$as_me:$LINENO: error: Unexpected output of 'arch' on OSX" >&5 -echo "$as_me: error: Unexpected output of 'arch' on OSX" >&2;} + { { $as_echo "$as_me:$LINENO: error: Unexpected output of 'arch' on OSX" >&5 +$as_echo "$as_me: error: Unexpected output of 'arch' on OSX" >&2;} { (exit 1); exit 1; }; } ;; esac @@ -13130,8 +13378,8 @@ MACOSX_DEFAULT_ARCH="ppc64" ;; *) - { { echo "$as_me:$LINENO: error: Unexpected output of 'arch' on OSX" >&5 -echo "$as_me: error: Unexpected output of 'arch' on OSX" >&2;} + { { $as_echo "$as_me:$LINENO: error: Unexpected output of 'arch' on OSX" >&5 +$as_echo "$as_me: error: Unexpected output of 'arch' on OSX" >&2;} { (exit 1); exit 1; }; } ;; esac @@ -13144,8 +13392,8 @@ LIBTOOL_CRUFT=$LIBTOOL_CRUFT' -compatibility_version $(VERSION) -current_version $(VERSION)';; esac -{ echo "$as_me:$LINENO: checking for --enable-framework" >&5 -echo $ECHO_N "checking for --enable-framework... $ECHO_C" >&6; } +{ $as_echo "$as_me:$LINENO: checking for --enable-framework" >&5 +$as_echo_n "checking for --enable-framework... " >&6; } if test "$enable_framework" then BASECFLAGS="$BASECFLAGS -fno-common -dynamic" @@ -13156,21 +13404,21 @@ #define WITH_NEXT_FRAMEWORK 1 _ACEOF - { echo "$as_me:$LINENO: result: yes" >&5 -echo "${ECHO_T}yes" >&6; } + { $as_echo "$as_me:$LINENO: result: yes" >&5 +$as_echo "yes" >&6; } if test $enable_shared = "yes" then - { { echo "$as_me:$LINENO: error: Specifying both --enable-shared and --enable-framework is not supported, use only --enable-framework instead. See Mac/README." >&5 -echo "$as_me: error: Specifying both --enable-shared and --enable-framework is not supported, use only --enable-framework instead. See Mac/README." >&2;} + { { $as_echo "$as_me:$LINENO: error: Specifying both --enable-shared and --enable-framework is not supported, use only --enable-framework instead. See Mac/README." >&5 +$as_echo "$as_me: error: Specifying both --enable-shared and --enable-framework is not supported, use only --enable-framework instead. See Mac/README." >&2;} { (exit 1); exit 1; }; } fi else - { echo "$as_me:$LINENO: result: no" >&5 -echo "${ECHO_T}no" >&6; } + { $as_echo "$as_me:$LINENO: result: no" >&5 +$as_echo "no" >&6; } fi -{ echo "$as_me:$LINENO: checking for dyld" >&5 -echo $ECHO_N "checking for dyld... $ECHO_C" >&6; } +{ $as_echo "$as_me:$LINENO: checking for dyld" >&5 +$as_echo_n "checking for dyld... " >&6; } case $ac_sys_system/$ac_sys_release in Darwin/*) @@ -13178,12 +13426,12 @@ #define WITH_DYLD 1 _ACEOF - { echo "$as_me:$LINENO: result: always on for Darwin" >&5 -echo "${ECHO_T}always on for Darwin" >&6; } + { $as_echo "$as_me:$LINENO: result: always on for Darwin" >&5 +$as_echo "always on for Darwin" >&6; } ;; *) - { echo "$as_me:$LINENO: result: no" >&5 -echo "${ECHO_T}no" >&6; } + { $as_echo "$as_me:$LINENO: result: no" >&5 +$as_echo "no" >&6; } ;; esac @@ -13195,8 +13443,8 @@ # SO is the extension of shared libraries `(including the dot!) # -- usually .so, .sl on HP-UX, .dll on Cygwin -{ echo "$as_me:$LINENO: checking SO" >&5 -echo $ECHO_N "checking SO... $ECHO_C" >&6; } +{ $as_echo "$as_me:$LINENO: checking SO" >&5 +$as_echo_n "checking SO... " >&6; } if test -z "$SO" then case $ac_sys_system in @@ -13221,8 +13469,8 @@ echo '=====================================================================' sleep 10 fi -{ echo "$as_me:$LINENO: result: $SO" >&5 -echo "${ECHO_T}$SO" >&6; } +{ $as_echo "$as_me:$LINENO: result: $SO" >&5 +$as_echo "$SO" >&6; } cat >>confdefs.h <<_ACEOF @@ -13233,8 +13481,8 @@ # -- "cc -G" on SunOS 5.x, "ld -shared" on IRIX 5 # (Shared libraries in this instance are shared modules to be loaded into # Python, as opposed to building Python itself as a shared library.) -{ echo "$as_me:$LINENO: checking LDSHARED" >&5 -echo $ECHO_N "checking LDSHARED... $ECHO_C" >&6; } +{ $as_echo "$as_me:$LINENO: checking LDSHARED" >&5 +$as_echo_n "checking LDSHARED... " >&6; } if test -z "$LDSHARED" then case $ac_sys_system/$ac_sys_release in @@ -13309,7 +13557,7 @@ FreeBSD*) if [ "`$CC -dM -E - &5 -echo "${ECHO_T}$LDSHARED" >&6; } +{ $as_echo "$as_me:$LINENO: result: $LDSHARED" >&5 +$as_echo "$LDSHARED" >&6; } BLDSHARED=${BLDSHARED-$LDSHARED} # CCSHARED are the C *flags* used to create objects to go into a shared # library (module) -- this is only needed for a few systems -{ echo "$as_me:$LINENO: checking CCSHARED" >&5 -echo $ECHO_N "checking CCSHARED... $ECHO_C" >&6; } +{ $as_echo "$as_me:$LINENO: checking CCSHARED" >&5 +$as_echo_n "checking CCSHARED... " >&6; } if test -z "$CCSHARED" then case $ac_sys_system/$ac_sys_release in @@ -13381,12 +13629,12 @@ atheos*) CCSHARED="-fPIC";; esac fi -{ echo "$as_me:$LINENO: result: $CCSHARED" >&5 -echo "${ECHO_T}$CCSHARED" >&6; } +{ $as_echo "$as_me:$LINENO: result: $CCSHARED" >&5 +$as_echo "$CCSHARED" >&6; } # LINKFORSHARED are the flags passed to the $(CC) command that links # the python executable -- this is only needed for a few systems -{ echo "$as_me:$LINENO: checking LINKFORSHARED" >&5 -echo $ECHO_N "checking LINKFORSHARED... $ECHO_C" >&6; } +{ $as_echo "$as_me:$LINENO: checking LINKFORSHARED" >&5 +$as_echo_n "checking LINKFORSHARED... " >&6; } if test -z "$LINKFORSHARED" then case $ac_sys_system/$ac_sys_release in @@ -13441,13 +13689,13 @@ LINKFORSHARED='-Wl,-E -N 2048K';; esac fi -{ echo "$as_me:$LINENO: result: $LINKFORSHARED" >&5 -echo "${ECHO_T}$LINKFORSHARED" >&6; } +{ $as_echo "$as_me:$LINENO: result: $LINKFORSHARED" >&5 +$as_echo "$LINKFORSHARED" >&6; } -{ echo "$as_me:$LINENO: checking CFLAGSFORSHARED" >&5 -echo $ECHO_N "checking CFLAGSFORSHARED... $ECHO_C" >&6; } +{ $as_echo "$as_me:$LINENO: checking CFLAGSFORSHARED" >&5 +$as_echo_n "checking CFLAGSFORSHARED... " >&6; } if test ! "$LIBRARY" = "$LDLIBRARY" then case $ac_sys_system in @@ -13459,8 +13707,8 @@ CFLAGSFORSHARED='$(CCSHARED)' esac fi -{ echo "$as_me:$LINENO: result: $CFLAGSFORSHARED" >&5 -echo "${ECHO_T}$CFLAGSFORSHARED" >&6; } +{ $as_echo "$as_me:$LINENO: result: $CFLAGSFORSHARED" >&5 +$as_echo "$CFLAGSFORSHARED" >&6; } # SHLIBS are libraries (except -lc and -lm) to link to the python shared # library (with --enable-shared). @@ -13471,22 +13719,22 @@ # don't need to link LIBS explicitly. The default should be only changed # on systems where this approach causes problems. -{ echo "$as_me:$LINENO: checking SHLIBS" >&5 -echo $ECHO_N "checking SHLIBS... $ECHO_C" >&6; } +{ $as_echo "$as_me:$LINENO: checking SHLIBS" >&5 +$as_echo_n "checking SHLIBS... " >&6; } case "$ac_sys_system" in *) SHLIBS='$(LIBS)';; esac -{ echo "$as_me:$LINENO: result: $SHLIBS" >&5 -echo "${ECHO_T}$SHLIBS" >&6; } +{ $as_echo "$as_me:$LINENO: result: $SHLIBS" >&5 +$as_echo "$SHLIBS" >&6; } # checks for libraries -{ echo "$as_me:$LINENO: checking for dlopen in -ldl" >&5 -echo $ECHO_N "checking for dlopen in -ldl... $ECHO_C" >&6; } +{ $as_echo "$as_me:$LINENO: checking for dlopen in -ldl" >&5 +$as_echo_n "checking for dlopen in -ldl... " >&6; } if test "${ac_cv_lib_dl_dlopen+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 + $as_echo_n "(cached) " >&6 else ac_check_lib_save_LIBS=$LIBS LIBS="-ldl $LIBS" @@ -13518,33 +13766,37 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_link") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { test -z "$ac_c_werror_flag" || test ! -s conftest.err - } && test -s conftest$ac_exeext && - $as_test_x conftest$ac_exeext; then + } && test -s conftest$ac_exeext && { + test "$cross_compiling" = yes || + $as_test_x conftest$ac_exeext + }; then ac_cv_lib_dl_dlopen=yes else - echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 ac_cv_lib_dl_dlopen=no fi +rm -rf conftest.dSYM rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \ conftest$ac_exeext conftest.$ac_ext LIBS=$ac_check_lib_save_LIBS fi -{ echo "$as_me:$LINENO: result: $ac_cv_lib_dl_dlopen" >&5 -echo "${ECHO_T}$ac_cv_lib_dl_dlopen" >&6; } -if test $ac_cv_lib_dl_dlopen = yes; then +{ $as_echo "$as_me:$LINENO: result: $ac_cv_lib_dl_dlopen" >&5 +$as_echo "$ac_cv_lib_dl_dlopen" >&6; } +if test "x$ac_cv_lib_dl_dlopen" = x""yes; then cat >>confdefs.h <<_ACEOF #define HAVE_LIBDL 1 _ACEOF @@ -13554,10 +13806,10 @@ fi # Dynamic linking for SunOS/Solaris and SYSV -{ echo "$as_me:$LINENO: checking for shl_load in -ldld" >&5 -echo $ECHO_N "checking for shl_load in -ldld... $ECHO_C" >&6; } +{ $as_echo "$as_me:$LINENO: checking for shl_load in -ldld" >&5 +$as_echo_n "checking for shl_load in -ldld... " >&6; } if test "${ac_cv_lib_dld_shl_load+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 + $as_echo_n "(cached) " >&6 else ac_check_lib_save_LIBS=$LIBS LIBS="-ldld $LIBS" @@ -13589,33 +13841,37 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_link") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { test -z "$ac_c_werror_flag" || test ! -s conftest.err - } && test -s conftest$ac_exeext && - $as_test_x conftest$ac_exeext; then + } && test -s conftest$ac_exeext && { + test "$cross_compiling" = yes || + $as_test_x conftest$ac_exeext + }; then ac_cv_lib_dld_shl_load=yes else - echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 ac_cv_lib_dld_shl_load=no fi +rm -rf conftest.dSYM rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \ conftest$ac_exeext conftest.$ac_ext LIBS=$ac_check_lib_save_LIBS fi -{ echo "$as_me:$LINENO: result: $ac_cv_lib_dld_shl_load" >&5 -echo "${ECHO_T}$ac_cv_lib_dld_shl_load" >&6; } -if test $ac_cv_lib_dld_shl_load = yes; then +{ $as_echo "$as_me:$LINENO: result: $ac_cv_lib_dld_shl_load" >&5 +$as_echo "$ac_cv_lib_dld_shl_load" >&6; } +if test "x$ac_cv_lib_dld_shl_load" = x""yes; then cat >>confdefs.h <<_ACEOF #define HAVE_LIBDLD 1 _ACEOF @@ -13627,10 +13883,10 @@ # only check for sem_init if thread support is requested if test "$with_threads" = "yes" -o -z "$with_threads"; then - { echo "$as_me:$LINENO: checking for library containing sem_init" >&5 -echo $ECHO_N "checking for library containing sem_init... $ECHO_C" >&6; } + { $as_echo "$as_me:$LINENO: checking for library containing sem_init" >&5 +$as_echo_n "checking for library containing sem_init... " >&6; } if test "${ac_cv_search_sem_init+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 + $as_echo_n "(cached) " >&6 else ac_func_search_save_LIBS=$LIBS cat >conftest.$ac_ext <<_ACEOF @@ -13668,26 +13924,30 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_link") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { test -z "$ac_c_werror_flag" || test ! -s conftest.err - } && test -s conftest$ac_exeext && - $as_test_x conftest$ac_exeext; then + } && test -s conftest$ac_exeext && { + test "$cross_compiling" = yes || + $as_test_x conftest$ac_exeext + }; then ac_cv_search_sem_init=$ac_res else - echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 fi +rm -rf conftest.dSYM rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \ conftest$ac_exeext if test "${ac_cv_search_sem_init+set}" = set; then @@ -13702,8 +13962,8 @@ rm conftest.$ac_ext LIBS=$ac_func_search_save_LIBS fi -{ echo "$as_me:$LINENO: result: $ac_cv_search_sem_init" >&5 -echo "${ECHO_T}$ac_cv_search_sem_init" >&6; } +{ $as_echo "$as_me:$LINENO: result: $ac_cv_search_sem_init" >&5 +$as_echo "$ac_cv_search_sem_init" >&6; } ac_res=$ac_cv_search_sem_init if test "$ac_res" != no; then test "$ac_res" = "none required" || LIBS="$ac_res $LIBS" @@ -13715,10 +13975,10 @@ fi # check if we need libintl for locale functions -{ echo "$as_me:$LINENO: checking for textdomain in -lintl" >&5 -echo $ECHO_N "checking for textdomain in -lintl... $ECHO_C" >&6; } +{ $as_echo "$as_me:$LINENO: checking for textdomain in -lintl" >&5 +$as_echo_n "checking for textdomain in -lintl... " >&6; } if test "${ac_cv_lib_intl_textdomain+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 + $as_echo_n "(cached) " >&6 else ac_check_lib_save_LIBS=$LIBS LIBS="-lintl $LIBS" @@ -13750,33 +14010,37 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_link") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { test -z "$ac_c_werror_flag" || test ! -s conftest.err - } && test -s conftest$ac_exeext && - $as_test_x conftest$ac_exeext; then + } && test -s conftest$ac_exeext && { + test "$cross_compiling" = yes || + $as_test_x conftest$ac_exeext + }; then ac_cv_lib_intl_textdomain=yes else - echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 ac_cv_lib_intl_textdomain=no fi +rm -rf conftest.dSYM rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \ conftest$ac_exeext conftest.$ac_ext LIBS=$ac_check_lib_save_LIBS fi -{ echo "$as_me:$LINENO: result: $ac_cv_lib_intl_textdomain" >&5 -echo "${ECHO_T}$ac_cv_lib_intl_textdomain" >&6; } -if test $ac_cv_lib_intl_textdomain = yes; then +{ $as_echo "$as_me:$LINENO: result: $ac_cv_lib_intl_textdomain" >&5 +$as_echo "$ac_cv_lib_intl_textdomain" >&6; } +if test "x$ac_cv_lib_intl_textdomain" = x""yes; then cat >>confdefs.h <<\_ACEOF #define WITH_LIBINTL 1 @@ -13787,8 +14051,8 @@ # checks for system dependent C++ extensions support case "$ac_sys_system" in - AIX*) { echo "$as_me:$LINENO: checking for genuine AIX C++ extensions support" >&5 -echo $ECHO_N "checking for genuine AIX C++ extensions support... $ECHO_C" >&6; } + AIX*) { $as_echo "$as_me:$LINENO: checking for genuine AIX C++ extensions support" >&5 +$as_echo_n "checking for genuine AIX C++ extensions support... " >&6; } cat >conftest.$ac_ext <<_ACEOF /* confdefs.h. */ _ACEOF @@ -13810,33 +14074,37 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_link") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { test -z "$ac_c_werror_flag" || test ! -s conftest.err - } && test -s conftest$ac_exeext && - $as_test_x conftest$ac_exeext; then + } && test -s conftest$ac_exeext && { + test "$cross_compiling" = yes || + $as_test_x conftest$ac_exeext + }; then cat >>confdefs.h <<\_ACEOF #define AIX_GENUINE_CPLUSPLUS 1 _ACEOF - { echo "$as_me:$LINENO: result: yes" >&5 -echo "${ECHO_T}yes" >&6; } + { $as_echo "$as_me:$LINENO: result: yes" >&5 +$as_echo "yes" >&6; } else - echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 - { echo "$as_me:$LINENO: result: no" >&5 -echo "${ECHO_T}no" >&6; } + { $as_echo "$as_me:$LINENO: result: no" >&5 +$as_echo "no" >&6; } fi +rm -rf conftest.dSYM rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \ conftest$ac_exeext conftest.$ac_ext;; *) ;; @@ -13844,10 +14112,10 @@ # Most SVR4 platforms (e.g. Solaris) need -lsocket and -lnsl. # BeOS' sockets are stashed in libnet. -{ echo "$as_me:$LINENO: checking for t_open in -lnsl" >&5 -echo $ECHO_N "checking for t_open in -lnsl... $ECHO_C" >&6; } +{ $as_echo "$as_me:$LINENO: checking for t_open in -lnsl" >&5 +$as_echo_n "checking for t_open in -lnsl... " >&6; } if test "${ac_cv_lib_nsl_t_open+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 + $as_echo_n "(cached) " >&6 else ac_check_lib_save_LIBS=$LIBS LIBS="-lnsl $LIBS" @@ -13879,40 +14147,44 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_link") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { test -z "$ac_c_werror_flag" || test ! -s conftest.err - } && test -s conftest$ac_exeext && - $as_test_x conftest$ac_exeext; then + } && test -s conftest$ac_exeext && { + test "$cross_compiling" = yes || + $as_test_x conftest$ac_exeext + }; then ac_cv_lib_nsl_t_open=yes else - echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 ac_cv_lib_nsl_t_open=no fi +rm -rf conftest.dSYM rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \ conftest$ac_exeext conftest.$ac_ext LIBS=$ac_check_lib_save_LIBS fi -{ echo "$as_me:$LINENO: result: $ac_cv_lib_nsl_t_open" >&5 -echo "${ECHO_T}$ac_cv_lib_nsl_t_open" >&6; } -if test $ac_cv_lib_nsl_t_open = yes; then +{ $as_echo "$as_me:$LINENO: result: $ac_cv_lib_nsl_t_open" >&5 +$as_echo "$ac_cv_lib_nsl_t_open" >&6; } +if test "x$ac_cv_lib_nsl_t_open" = x""yes; then LIBS="-lnsl $LIBS" fi # SVR4 -{ echo "$as_me:$LINENO: checking for socket in -lsocket" >&5 -echo $ECHO_N "checking for socket in -lsocket... $ECHO_C" >&6; } +{ $as_echo "$as_me:$LINENO: checking for socket in -lsocket" >&5 +$as_echo_n "checking for socket in -lsocket... " >&6; } if test "${ac_cv_lib_socket_socket+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 + $as_echo_n "(cached) " >&6 else ac_check_lib_save_LIBS=$LIBS LIBS="-lsocket $LIBS $LIBS" @@ -13944,43 +14216,47 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_link") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { test -z "$ac_c_werror_flag" || test ! -s conftest.err - } && test -s conftest$ac_exeext && - $as_test_x conftest$ac_exeext; then + } && test -s conftest$ac_exeext && { + test "$cross_compiling" = yes || + $as_test_x conftest$ac_exeext + }; then ac_cv_lib_socket_socket=yes else - echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 ac_cv_lib_socket_socket=no fi +rm -rf conftest.dSYM rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \ conftest$ac_exeext conftest.$ac_ext LIBS=$ac_check_lib_save_LIBS fi -{ echo "$as_me:$LINENO: result: $ac_cv_lib_socket_socket" >&5 -echo "${ECHO_T}$ac_cv_lib_socket_socket" >&6; } -if test $ac_cv_lib_socket_socket = yes; then +{ $as_echo "$as_me:$LINENO: result: $ac_cv_lib_socket_socket" >&5 +$as_echo "$ac_cv_lib_socket_socket" >&6; } +if test "x$ac_cv_lib_socket_socket" = x""yes; then LIBS="-lsocket $LIBS" fi # SVR4 sockets case "$ac_sys_system" in BeOS*) -{ echo "$as_me:$LINENO: checking for socket in -lnet" >&5 -echo $ECHO_N "checking for socket in -lnet... $ECHO_C" >&6; } +{ $as_echo "$as_me:$LINENO: checking for socket in -lnet" >&5 +$as_echo_n "checking for socket in -lnet... " >&6; } if test "${ac_cv_lib_net_socket+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 + $as_echo_n "(cached) " >&6 else ac_check_lib_save_LIBS=$LIBS LIBS="-lnet $LIBS $LIBS" @@ -14012,58 +14288,62 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_link") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { test -z "$ac_c_werror_flag" || test ! -s conftest.err - } && test -s conftest$ac_exeext && - $as_test_x conftest$ac_exeext; then + } && test -s conftest$ac_exeext && { + test "$cross_compiling" = yes || + $as_test_x conftest$ac_exeext + }; then ac_cv_lib_net_socket=yes else - echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 ac_cv_lib_net_socket=no fi +rm -rf conftest.dSYM rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \ conftest$ac_exeext conftest.$ac_ext LIBS=$ac_check_lib_save_LIBS fi -{ echo "$as_me:$LINENO: result: $ac_cv_lib_net_socket" >&5 -echo "${ECHO_T}$ac_cv_lib_net_socket" >&6; } -if test $ac_cv_lib_net_socket = yes; then +{ $as_echo "$as_me:$LINENO: result: $ac_cv_lib_net_socket" >&5 +$as_echo "$ac_cv_lib_net_socket" >&6; } +if test "x$ac_cv_lib_net_socket" = x""yes; then LIBS="-lnet $LIBS" fi # BeOS ;; esac -{ echo "$as_me:$LINENO: checking for --with-libs" >&5 -echo $ECHO_N "checking for --with-libs... $ECHO_C" >&6; } +{ $as_echo "$as_me:$LINENO: checking for --with-libs" >&5 +$as_echo_n "checking for --with-libs... " >&6; } # Check whether --with-libs was given. if test "${with_libs+set}" = set; then withval=$with_libs; -{ echo "$as_me:$LINENO: result: $withval" >&5 -echo "${ECHO_T}$withval" >&6; } +{ $as_echo "$as_me:$LINENO: result: $withval" >&5 +$as_echo "$withval" >&6; } LIBS="$withval $LIBS" else - { echo "$as_me:$LINENO: result: no" >&5 -echo "${ECHO_T}no" >&6; } + { $as_echo "$as_me:$LINENO: result: no" >&5 +$as_echo "no" >&6; } fi # Check for use of the system libffi library -{ echo "$as_me:$LINENO: checking for --with-system-ffi" >&5 -echo $ECHO_N "checking for --with-system-ffi... $ECHO_C" >&6; } +{ $as_echo "$as_me:$LINENO: checking for --with-system-ffi" >&5 +$as_echo_n "checking for --with-system-ffi... " >&6; } # Check whether --with-system_ffi was given. if test "${with_system_ffi+set}" = set; then @@ -14071,14 +14351,14 @@ fi -{ echo "$as_me:$LINENO: result: $with_system_ffi" >&5 -echo "${ECHO_T}$with_system_ffi" >&6; } +{ $as_echo "$as_me:$LINENO: result: $with_system_ffi" >&5 +$as_echo "$with_system_ffi" >&6; } # Determine if signalmodule should be used. -{ echo "$as_me:$LINENO: checking for --with-signal-module" >&5 -echo $ECHO_N "checking for --with-signal-module... $ECHO_C" >&6; } +{ $as_echo "$as_me:$LINENO: checking for --with-signal-module" >&5 +$as_echo_n "checking for --with-signal-module... " >&6; } # Check whether --with-signal-module was given. if test "${with_signal_module+set}" = set; then @@ -14089,8 +14369,8 @@ if test -z "$with_signal_module" then with_signal_module="yes" fi -{ echo "$as_me:$LINENO: result: $with_signal_module" >&5 -echo "${ECHO_T}$with_signal_module" >&6; } +{ $as_echo "$as_me:$LINENO: result: $with_signal_module" >&5 +$as_echo "$with_signal_module" >&6; } if test "${with_signal_module}" = "yes"; then USE_SIGNAL_MODULE="" @@ -14104,22 +14384,22 @@ USE_THREAD_MODULE="" -{ echo "$as_me:$LINENO: checking for --with-dec-threads" >&5 -echo $ECHO_N "checking for --with-dec-threads... $ECHO_C" >&6; } +{ $as_echo "$as_me:$LINENO: checking for --with-dec-threads" >&5 +$as_echo_n "checking for --with-dec-threads... " >&6; } # Check whether --with-dec-threads was given. if test "${with_dec_threads+set}" = set; then withval=$with_dec_threads; -{ echo "$as_me:$LINENO: result: $withval" >&5 -echo "${ECHO_T}$withval" >&6; } +{ $as_echo "$as_me:$LINENO: result: $withval" >&5 +$as_echo "$withval" >&6; } LDLAST=-threads if test "${with_thread+set}" != set; then with_thread="$withval"; fi else - { echo "$as_me:$LINENO: result: no" >&5 -echo "${ECHO_T}no" >&6; } + { $as_echo "$as_me:$LINENO: result: no" >&5 +$as_echo "no" >&6; } fi @@ -14132,8 +14412,8 @@ -{ echo "$as_me:$LINENO: checking for --with-threads" >&5 -echo $ECHO_N "checking for --with-threads... $ECHO_C" >&6; } +{ $as_echo "$as_me:$LINENO: checking for --with-threads" >&5 +$as_echo_n "checking for --with-threads... " >&6; } # Check whether --with-threads was given. if test "${with_threads+set}" = set; then @@ -14152,8 +14432,8 @@ if test -z "$with_threads" then with_threads="yes" fi -{ echo "$as_me:$LINENO: result: $with_threads" >&5 -echo "${ECHO_T}$with_threads" >&6; } +{ $as_echo "$as_me:$LINENO: result: $with_threads" >&5 +$as_echo "$with_threads" >&6; } if test "$with_threads" = "no" @@ -14219,8 +14499,8 @@ # According to the POSIX spec, a pthreads implementation must # define _POSIX_THREADS in unistd.h. Some apparently don't # (e.g. gnu pth with pthread emulation) - { echo "$as_me:$LINENO: checking for _POSIX_THREADS in unistd.h" >&5 -echo $ECHO_N "checking for _POSIX_THREADS in unistd.h... $ECHO_C" >&6; } + { $as_echo "$as_me:$LINENO: checking for _POSIX_THREADS in unistd.h" >&5 +$as_echo_n "checking for _POSIX_THREADS in unistd.h... " >&6; } cat >conftest.$ac_ext <<_ACEOF /* confdefs.h. */ _ACEOF @@ -14242,25 +14522,25 @@ fi rm -f conftest* - { echo "$as_me:$LINENO: result: $unistd_defines_pthreads" >&5 -echo "${ECHO_T}$unistd_defines_pthreads" >&6; } + { $as_echo "$as_me:$LINENO: result: $unistd_defines_pthreads" >&5 +$as_echo "$unistd_defines_pthreads" >&6; } cat >>confdefs.h <<\_ACEOF #define _REENTRANT 1 _ACEOF if test "${ac_cv_header_cthreads_h+set}" = set; then - { echo "$as_me:$LINENO: checking for cthreads.h" >&5 -echo $ECHO_N "checking for cthreads.h... $ECHO_C" >&6; } + { $as_echo "$as_me:$LINENO: checking for cthreads.h" >&5 +$as_echo_n "checking for cthreads.h... " >&6; } if test "${ac_cv_header_cthreads_h+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 + $as_echo_n "(cached) " >&6 fi -{ echo "$as_me:$LINENO: result: $ac_cv_header_cthreads_h" >&5 -echo "${ECHO_T}$ac_cv_header_cthreads_h" >&6; } +{ $as_echo "$as_me:$LINENO: result: $ac_cv_header_cthreads_h" >&5 +$as_echo "$ac_cv_header_cthreads_h" >&6; } else # Is the header compilable? -{ echo "$as_me:$LINENO: checking cthreads.h usability" >&5 -echo $ECHO_N "checking cthreads.h usability... $ECHO_C" >&6; } +{ $as_echo "$as_me:$LINENO: checking cthreads.h usability" >&5 +$as_echo_n "checking cthreads.h usability... " >&6; } cat >conftest.$ac_ext <<_ACEOF /* confdefs.h. */ _ACEOF @@ -14276,32 +14556,33 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_compile") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { test -z "$ac_c_werror_flag" || test ! -s conftest.err } && test -s conftest.$ac_objext; then ac_header_compiler=yes else - echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 ac_header_compiler=no fi rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext -{ echo "$as_me:$LINENO: result: $ac_header_compiler" >&5 -echo "${ECHO_T}$ac_header_compiler" >&6; } +{ $as_echo "$as_me:$LINENO: result: $ac_header_compiler" >&5 +$as_echo "$ac_header_compiler" >&6; } # Is the header present? -{ echo "$as_me:$LINENO: checking cthreads.h presence" >&5 -echo $ECHO_N "checking cthreads.h presence... $ECHO_C" >&6; } +{ $as_echo "$as_me:$LINENO: checking cthreads.h presence" >&5 +$as_echo_n "checking cthreads.h presence... " >&6; } cat >conftest.$ac_ext <<_ACEOF /* confdefs.h. */ _ACEOF @@ -14315,51 +14596,52 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_cpp conftest.$ac_ext") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } >/dev/null && { test -z "$ac_c_preproc_warn_flag$ac_c_werror_flag" || test ! -s conftest.err }; then ac_header_preproc=yes else - echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 ac_header_preproc=no fi rm -f conftest.err conftest.$ac_ext -{ echo "$as_me:$LINENO: result: $ac_header_preproc" >&5 -echo "${ECHO_T}$ac_header_preproc" >&6; } +{ $as_echo "$as_me:$LINENO: result: $ac_header_preproc" >&5 +$as_echo "$ac_header_preproc" >&6; } # So? What about this header? case $ac_header_compiler:$ac_header_preproc:$ac_c_preproc_warn_flag in yes:no: ) - { echo "$as_me:$LINENO: WARNING: cthreads.h: accepted by the compiler, rejected by the preprocessor!" >&5 -echo "$as_me: WARNING: cthreads.h: accepted by the compiler, rejected by the preprocessor!" >&2;} - { echo "$as_me:$LINENO: WARNING: cthreads.h: proceeding with the compiler's result" >&5 -echo "$as_me: WARNING: cthreads.h: proceeding with the compiler's result" >&2;} + { $as_echo "$as_me:$LINENO: WARNING: cthreads.h: accepted by the compiler, rejected by the preprocessor!" >&5 +$as_echo "$as_me: WARNING: cthreads.h: accepted by the compiler, rejected by the preprocessor!" >&2;} + { $as_echo "$as_me:$LINENO: WARNING: cthreads.h: proceeding with the compiler's result" >&5 +$as_echo "$as_me: WARNING: cthreads.h: proceeding with the compiler's result" >&2;} ac_header_preproc=yes ;; no:yes:* ) - { echo "$as_me:$LINENO: WARNING: cthreads.h: present but cannot be compiled" >&5 -echo "$as_me: WARNING: cthreads.h: present but cannot be compiled" >&2;} - { echo "$as_me:$LINENO: WARNING: cthreads.h: check for missing prerequisite headers?" >&5 -echo "$as_me: WARNING: cthreads.h: check for missing prerequisite headers?" >&2;} - { echo "$as_me:$LINENO: WARNING: cthreads.h: see the Autoconf documentation" >&5 -echo "$as_me: WARNING: cthreads.h: see the Autoconf documentation" >&2;} - { echo "$as_me:$LINENO: WARNING: cthreads.h: section \"Present But Cannot Be Compiled\"" >&5 -echo "$as_me: WARNING: cthreads.h: section \"Present But Cannot Be Compiled\"" >&2;} - { echo "$as_me:$LINENO: WARNING: cthreads.h: proceeding with the preprocessor's result" >&5 -echo "$as_me: WARNING: cthreads.h: proceeding with the preprocessor's result" >&2;} - { echo "$as_me:$LINENO: WARNING: cthreads.h: in the future, the compiler will take precedence" >&5 -echo "$as_me: WARNING: cthreads.h: in the future, the compiler will take precedence" >&2;} + { $as_echo "$as_me:$LINENO: WARNING: cthreads.h: present but cannot be compiled" >&5 +$as_echo "$as_me: WARNING: cthreads.h: present but cannot be compiled" >&2;} + { $as_echo "$as_me:$LINENO: WARNING: cthreads.h: check for missing prerequisite headers?" >&5 +$as_echo "$as_me: WARNING: cthreads.h: check for missing prerequisite headers?" >&2;} + { $as_echo "$as_me:$LINENO: WARNING: cthreads.h: see the Autoconf documentation" >&5 +$as_echo "$as_me: WARNING: cthreads.h: see the Autoconf documentation" >&2;} + { $as_echo "$as_me:$LINENO: WARNING: cthreads.h: section \"Present But Cannot Be Compiled\"" >&5 +$as_echo "$as_me: WARNING: cthreads.h: section \"Present But Cannot Be Compiled\"" >&2;} + { $as_echo "$as_me:$LINENO: WARNING: cthreads.h: proceeding with the preprocessor's result" >&5 +$as_echo "$as_me: WARNING: cthreads.h: proceeding with the preprocessor's result" >&2;} + { $as_echo "$as_me:$LINENO: WARNING: cthreads.h: in the future, the compiler will take precedence" >&5 +$as_echo "$as_me: WARNING: cthreads.h: in the future, the compiler will take precedence" >&2;} ( cat <<\_ASBOX ## ------------------------------------------------ ## ## Report this to http://www.python.org/python-bugs ## @@ -14368,18 +14650,18 @@ ) | sed "s/^/$as_me: WARNING: /" >&2 ;; esac -{ echo "$as_me:$LINENO: checking for cthreads.h" >&5 -echo $ECHO_N "checking for cthreads.h... $ECHO_C" >&6; } +{ $as_echo "$as_me:$LINENO: checking for cthreads.h" >&5 +$as_echo_n "checking for cthreads.h... " >&6; } if test "${ac_cv_header_cthreads_h+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 + $as_echo_n "(cached) " >&6 else ac_cv_header_cthreads_h=$ac_header_preproc fi -{ echo "$as_me:$LINENO: result: $ac_cv_header_cthreads_h" >&5 -echo "${ECHO_T}$ac_cv_header_cthreads_h" >&6; } +{ $as_echo "$as_me:$LINENO: result: $ac_cv_header_cthreads_h" >&5 +$as_echo "$ac_cv_header_cthreads_h" >&6; } fi -if test $ac_cv_header_cthreads_h = yes; then +if test "x$ac_cv_header_cthreads_h" = x""yes; then cat >>confdefs.h <<\_ACEOF #define WITH_THREAD 1 _ACEOF @@ -14398,17 +14680,17 @@ else if test "${ac_cv_header_mach_cthreads_h+set}" = set; then - { echo "$as_me:$LINENO: checking for mach/cthreads.h" >&5 -echo $ECHO_N "checking for mach/cthreads.h... $ECHO_C" >&6; } + { $as_echo "$as_me:$LINENO: checking for mach/cthreads.h" >&5 +$as_echo_n "checking for mach/cthreads.h... " >&6; } if test "${ac_cv_header_mach_cthreads_h+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 + $as_echo_n "(cached) " >&6 fi -{ echo "$as_me:$LINENO: result: $ac_cv_header_mach_cthreads_h" >&5 -echo "${ECHO_T}$ac_cv_header_mach_cthreads_h" >&6; } +{ $as_echo "$as_me:$LINENO: result: $ac_cv_header_mach_cthreads_h" >&5 +$as_echo "$ac_cv_header_mach_cthreads_h" >&6; } else # Is the header compilable? -{ echo "$as_me:$LINENO: checking mach/cthreads.h usability" >&5 -echo $ECHO_N "checking mach/cthreads.h usability... $ECHO_C" >&6; } +{ $as_echo "$as_me:$LINENO: checking mach/cthreads.h usability" >&5 +$as_echo_n "checking mach/cthreads.h usability... " >&6; } cat >conftest.$ac_ext <<_ACEOF /* confdefs.h. */ _ACEOF @@ -14424,32 +14706,33 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_compile") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { test -z "$ac_c_werror_flag" || test ! -s conftest.err } && test -s conftest.$ac_objext; then ac_header_compiler=yes else - echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 ac_header_compiler=no fi rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext -{ echo "$as_me:$LINENO: result: $ac_header_compiler" >&5 -echo "${ECHO_T}$ac_header_compiler" >&6; } +{ $as_echo "$as_me:$LINENO: result: $ac_header_compiler" >&5 +$as_echo "$ac_header_compiler" >&6; } # Is the header present? -{ echo "$as_me:$LINENO: checking mach/cthreads.h presence" >&5 -echo $ECHO_N "checking mach/cthreads.h presence... $ECHO_C" >&6; } +{ $as_echo "$as_me:$LINENO: checking mach/cthreads.h presence" >&5 +$as_echo_n "checking mach/cthreads.h presence... " >&6; } cat >conftest.$ac_ext <<_ACEOF /* confdefs.h. */ _ACEOF @@ -14463,51 +14746,52 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_cpp conftest.$ac_ext") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } >/dev/null && { test -z "$ac_c_preproc_warn_flag$ac_c_werror_flag" || test ! -s conftest.err }; then ac_header_preproc=yes else - echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 ac_header_preproc=no fi rm -f conftest.err conftest.$ac_ext -{ echo "$as_me:$LINENO: result: $ac_header_preproc" >&5 -echo "${ECHO_T}$ac_header_preproc" >&6; } +{ $as_echo "$as_me:$LINENO: result: $ac_header_preproc" >&5 +$as_echo "$ac_header_preproc" >&6; } # So? What about this header? case $ac_header_compiler:$ac_header_preproc:$ac_c_preproc_warn_flag in yes:no: ) - { echo "$as_me:$LINENO: WARNING: mach/cthreads.h: accepted by the compiler, rejected by the preprocessor!" >&5 -echo "$as_me: WARNING: mach/cthreads.h: accepted by the compiler, rejected by the preprocessor!" >&2;} - { echo "$as_me:$LINENO: WARNING: mach/cthreads.h: proceeding with the compiler's result" >&5 -echo "$as_me: WARNING: mach/cthreads.h: proceeding with the compiler's result" >&2;} + { $as_echo "$as_me:$LINENO: WARNING: mach/cthreads.h: accepted by the compiler, rejected by the preprocessor!" >&5 +$as_echo "$as_me: WARNING: mach/cthreads.h: accepted by the compiler, rejected by the preprocessor!" >&2;} + { $as_echo "$as_me:$LINENO: WARNING: mach/cthreads.h: proceeding with the compiler's result" >&5 +$as_echo "$as_me: WARNING: mach/cthreads.h: proceeding with the compiler's result" >&2;} ac_header_preproc=yes ;; no:yes:* ) - { echo "$as_me:$LINENO: WARNING: mach/cthreads.h: present but cannot be compiled" >&5 -echo "$as_me: WARNING: mach/cthreads.h: present but cannot be compiled" >&2;} - { echo "$as_me:$LINENO: WARNING: mach/cthreads.h: check for missing prerequisite headers?" >&5 -echo "$as_me: WARNING: mach/cthreads.h: check for missing prerequisite headers?" >&2;} - { echo "$as_me:$LINENO: WARNING: mach/cthreads.h: see the Autoconf documentation" >&5 -echo "$as_me: WARNING: mach/cthreads.h: see the Autoconf documentation" >&2;} - { echo "$as_me:$LINENO: WARNING: mach/cthreads.h: section \"Present But Cannot Be Compiled\"" >&5 -echo "$as_me: WARNING: mach/cthreads.h: section \"Present But Cannot Be Compiled\"" >&2;} - { echo "$as_me:$LINENO: WARNING: mach/cthreads.h: proceeding with the preprocessor's result" >&5 -echo "$as_me: WARNING: mach/cthreads.h: proceeding with the preprocessor's result" >&2;} - { echo "$as_me:$LINENO: WARNING: mach/cthreads.h: in the future, the compiler will take precedence" >&5 -echo "$as_me: WARNING: mach/cthreads.h: in the future, the compiler will take precedence" >&2;} + { $as_echo "$as_me:$LINENO: WARNING: mach/cthreads.h: present but cannot be compiled" >&5 +$as_echo "$as_me: WARNING: mach/cthreads.h: present but cannot be compiled" >&2;} + { $as_echo "$as_me:$LINENO: WARNING: mach/cthreads.h: check for missing prerequisite headers?" >&5 +$as_echo "$as_me: WARNING: mach/cthreads.h: check for missing prerequisite headers?" >&2;} + { $as_echo "$as_me:$LINENO: WARNING: mach/cthreads.h: see the Autoconf documentation" >&5 +$as_echo "$as_me: WARNING: mach/cthreads.h: see the Autoconf documentation" >&2;} + { $as_echo "$as_me:$LINENO: WARNING: mach/cthreads.h: section \"Present But Cannot Be Compiled\"" >&5 +$as_echo "$as_me: WARNING: mach/cthreads.h: section \"Present But Cannot Be Compiled\"" >&2;} + { $as_echo "$as_me:$LINENO: WARNING: mach/cthreads.h: proceeding with the preprocessor's result" >&5 +$as_echo "$as_me: WARNING: mach/cthreads.h: proceeding with the preprocessor's result" >&2;} + { $as_echo "$as_me:$LINENO: WARNING: mach/cthreads.h: in the future, the compiler will take precedence" >&5 +$as_echo "$as_me: WARNING: mach/cthreads.h: in the future, the compiler will take precedence" >&2;} ( cat <<\_ASBOX ## ------------------------------------------------ ## ## Report this to http://www.python.org/python-bugs ## @@ -14516,18 +14800,18 @@ ) | sed "s/^/$as_me: WARNING: /" >&2 ;; esac -{ echo "$as_me:$LINENO: checking for mach/cthreads.h" >&5 -echo $ECHO_N "checking for mach/cthreads.h... $ECHO_C" >&6; } +{ $as_echo "$as_me:$LINENO: checking for mach/cthreads.h" >&5 +$as_echo_n "checking for mach/cthreads.h... " >&6; } if test "${ac_cv_header_mach_cthreads_h+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 + $as_echo_n "(cached) " >&6 else ac_cv_header_mach_cthreads_h=$ac_header_preproc fi -{ echo "$as_me:$LINENO: result: $ac_cv_header_mach_cthreads_h" >&5 -echo "${ECHO_T}$ac_cv_header_mach_cthreads_h" >&6; } +{ $as_echo "$as_me:$LINENO: result: $ac_cv_header_mach_cthreads_h" >&5 +$as_echo "$ac_cv_header_mach_cthreads_h" >&6; } fi -if test $ac_cv_header_mach_cthreads_h = yes; then +if test "x$ac_cv_header_mach_cthreads_h" = x""yes; then cat >>confdefs.h <<\_ACEOF #define WITH_THREAD 1 _ACEOF @@ -14544,13 +14828,13 @@ THREADOBJ="Python/thread.o" else - { echo "$as_me:$LINENO: checking for --with-pth" >&5 -echo $ECHO_N "checking for --with-pth... $ECHO_C" >&6; } + { $as_echo "$as_me:$LINENO: checking for --with-pth" >&5 +$as_echo_n "checking for --with-pth... " >&6; } # Check whether --with-pth was given. if test "${with_pth+set}" = set; then - withval=$with_pth; { echo "$as_me:$LINENO: result: $withval" >&5 -echo "${ECHO_T}$withval" >&6; } + withval=$with_pth; { $as_echo "$as_me:$LINENO: result: $withval" >&5 +$as_echo "$withval" >&6; } cat >>confdefs.h <<\_ACEOF #define WITH_THREAD 1 _ACEOF @@ -14563,16 +14847,16 @@ LIBS="-lpth $LIBS" THREADOBJ="Python/thread.o" else - { echo "$as_me:$LINENO: result: no" >&5 -echo "${ECHO_T}no" >&6; } + { $as_echo "$as_me:$LINENO: result: no" >&5 +$as_echo "no" >&6; } # Just looking for pthread_create in libpthread is not enough: # on HP/UX, pthread.h renames pthread_create to a different symbol name. # So we really have to include pthread.h, and then link. _libs=$LIBS LIBS="$LIBS -lpthread" - { echo "$as_me:$LINENO: checking for pthread_create in -lpthread" >&5 -echo $ECHO_N "checking for pthread_create in -lpthread... $ECHO_C" >&6; } + { $as_echo "$as_me:$LINENO: checking for pthread_create in -lpthread" >&5 +$as_echo_n "checking for pthread_create in -lpthread... " >&6; } cat >conftest.$ac_ext <<_ACEOF /* confdefs.h. */ _ACEOF @@ -14597,21 +14881,24 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_link") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { test -z "$ac_c_werror_flag" || test ! -s conftest.err - } && test -s conftest$ac_exeext && - $as_test_x conftest$ac_exeext; then + } && test -s conftest$ac_exeext && { + test "$cross_compiling" = yes || + $as_test_x conftest$ac_exeext + }; then - { echo "$as_me:$LINENO: result: yes" >&5 -echo "${ECHO_T}yes" >&6; } + { $as_echo "$as_me:$LINENO: result: yes" >&5 +$as_echo "yes" >&6; } cat >>confdefs.h <<\_ACEOF #define WITH_THREAD 1 _ACEOF @@ -14619,15 +14906,15 @@ posix_threads=yes THREADOBJ="Python/thread.o" else - echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 LIBS=$_libs - { echo "$as_me:$LINENO: checking for pthread_detach" >&5 -echo $ECHO_N "checking for pthread_detach... $ECHO_C" >&6; } + { $as_echo "$as_me:$LINENO: checking for pthread_detach" >&5 +$as_echo_n "checking for pthread_detach... " >&6; } if test "${ac_cv_func_pthread_detach+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 + $as_echo_n "(cached) " >&6 else cat >conftest.$ac_ext <<_ACEOF /* confdefs.h. */ @@ -14680,32 +14967,36 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_link") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { test -z "$ac_c_werror_flag" || test ! -s conftest.err - } && test -s conftest$ac_exeext && - $as_test_x conftest$ac_exeext; then + } && test -s conftest$ac_exeext && { + test "$cross_compiling" = yes || + $as_test_x conftest$ac_exeext + }; then ac_cv_func_pthread_detach=yes else - echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 ac_cv_func_pthread_detach=no fi +rm -rf conftest.dSYM rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \ conftest$ac_exeext conftest.$ac_ext fi -{ echo "$as_me:$LINENO: result: $ac_cv_func_pthread_detach" >&5 -echo "${ECHO_T}$ac_cv_func_pthread_detach" >&6; } -if test $ac_cv_func_pthread_detach = yes; then +{ $as_echo "$as_me:$LINENO: result: $ac_cv_func_pthread_detach" >&5 +$as_echo "$ac_cv_func_pthread_detach" >&6; } +if test "x$ac_cv_func_pthread_detach" = x""yes; then cat >>confdefs.h <<\_ACEOF #define WITH_THREAD 1 _ACEOF @@ -14715,17 +15006,17 @@ else if test "${ac_cv_header_atheos_threads_h+set}" = set; then - { echo "$as_me:$LINENO: checking for atheos/threads.h" >&5 -echo $ECHO_N "checking for atheos/threads.h... $ECHO_C" >&6; } + { $as_echo "$as_me:$LINENO: checking for atheos/threads.h" >&5 +$as_echo_n "checking for atheos/threads.h... " >&6; } if test "${ac_cv_header_atheos_threads_h+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 + $as_echo_n "(cached) " >&6 fi -{ echo "$as_me:$LINENO: result: $ac_cv_header_atheos_threads_h" >&5 -echo "${ECHO_T}$ac_cv_header_atheos_threads_h" >&6; } +{ $as_echo "$as_me:$LINENO: result: $ac_cv_header_atheos_threads_h" >&5 +$as_echo "$ac_cv_header_atheos_threads_h" >&6; } else # Is the header compilable? -{ echo "$as_me:$LINENO: checking atheos/threads.h usability" >&5 -echo $ECHO_N "checking atheos/threads.h usability... $ECHO_C" >&6; } +{ $as_echo "$as_me:$LINENO: checking atheos/threads.h usability" >&5 +$as_echo_n "checking atheos/threads.h usability... " >&6; } cat >conftest.$ac_ext <<_ACEOF /* confdefs.h. */ _ACEOF @@ -14741,32 +15032,33 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_compile") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { test -z "$ac_c_werror_flag" || test ! -s conftest.err } && test -s conftest.$ac_objext; then ac_header_compiler=yes else - echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 ac_header_compiler=no fi rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext -{ echo "$as_me:$LINENO: result: $ac_header_compiler" >&5 -echo "${ECHO_T}$ac_header_compiler" >&6; } +{ $as_echo "$as_me:$LINENO: result: $ac_header_compiler" >&5 +$as_echo "$ac_header_compiler" >&6; } # Is the header present? -{ echo "$as_me:$LINENO: checking atheos/threads.h presence" >&5 -echo $ECHO_N "checking atheos/threads.h presence... $ECHO_C" >&6; } +{ $as_echo "$as_me:$LINENO: checking atheos/threads.h presence" >&5 +$as_echo_n "checking atheos/threads.h presence... " >&6; } cat >conftest.$ac_ext <<_ACEOF /* confdefs.h. */ _ACEOF @@ -14780,51 +15072,52 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_cpp conftest.$ac_ext") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } >/dev/null && { test -z "$ac_c_preproc_warn_flag$ac_c_werror_flag" || test ! -s conftest.err }; then ac_header_preproc=yes else - echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 ac_header_preproc=no fi rm -f conftest.err conftest.$ac_ext -{ echo "$as_me:$LINENO: result: $ac_header_preproc" >&5 -echo "${ECHO_T}$ac_header_preproc" >&6; } +{ $as_echo "$as_me:$LINENO: result: $ac_header_preproc" >&5 +$as_echo "$ac_header_preproc" >&6; } # So? What about this header? case $ac_header_compiler:$ac_header_preproc:$ac_c_preproc_warn_flag in yes:no: ) - { echo "$as_me:$LINENO: WARNING: atheos/threads.h: accepted by the compiler, rejected by the preprocessor!" >&5 -echo "$as_me: WARNING: atheos/threads.h: accepted by the compiler, rejected by the preprocessor!" >&2;} - { echo "$as_me:$LINENO: WARNING: atheos/threads.h: proceeding with the compiler's result" >&5 -echo "$as_me: WARNING: atheos/threads.h: proceeding with the compiler's result" >&2;} + { $as_echo "$as_me:$LINENO: WARNING: atheos/threads.h: accepted by the compiler, rejected by the preprocessor!" >&5 +$as_echo "$as_me: WARNING: atheos/threads.h: accepted by the compiler, rejected by the preprocessor!" >&2;} + { $as_echo "$as_me:$LINENO: WARNING: atheos/threads.h: proceeding with the compiler's result" >&5 +$as_echo "$as_me: WARNING: atheos/threads.h: proceeding with the compiler's result" >&2;} ac_header_preproc=yes ;; no:yes:* ) - { echo "$as_me:$LINENO: WARNING: atheos/threads.h: present but cannot be compiled" >&5 -echo "$as_me: WARNING: atheos/threads.h: present but cannot be compiled" >&2;} - { echo "$as_me:$LINENO: WARNING: atheos/threads.h: check for missing prerequisite headers?" >&5 -echo "$as_me: WARNING: atheos/threads.h: check for missing prerequisite headers?" >&2;} - { echo "$as_me:$LINENO: WARNING: atheos/threads.h: see the Autoconf documentation" >&5 -echo "$as_me: WARNING: atheos/threads.h: see the Autoconf documentation" >&2;} - { echo "$as_me:$LINENO: WARNING: atheos/threads.h: section \"Present But Cannot Be Compiled\"" >&5 -echo "$as_me: WARNING: atheos/threads.h: section \"Present But Cannot Be Compiled\"" >&2;} - { echo "$as_me:$LINENO: WARNING: atheos/threads.h: proceeding with the preprocessor's result" >&5 -echo "$as_me: WARNING: atheos/threads.h: proceeding with the preprocessor's result" >&2;} - { echo "$as_me:$LINENO: WARNING: atheos/threads.h: in the future, the compiler will take precedence" >&5 -echo "$as_me: WARNING: atheos/threads.h: in the future, the compiler will take precedence" >&2;} + { $as_echo "$as_me:$LINENO: WARNING: atheos/threads.h: present but cannot be compiled" >&5 +$as_echo "$as_me: WARNING: atheos/threads.h: present but cannot be compiled" >&2;} + { $as_echo "$as_me:$LINENO: WARNING: atheos/threads.h: check for missing prerequisite headers?" >&5 +$as_echo "$as_me: WARNING: atheos/threads.h: check for missing prerequisite headers?" >&2;} + { $as_echo "$as_me:$LINENO: WARNING: atheos/threads.h: see the Autoconf documentation" >&5 +$as_echo "$as_me: WARNING: atheos/threads.h: see the Autoconf documentation" >&2;} + { $as_echo "$as_me:$LINENO: WARNING: atheos/threads.h: section \"Present But Cannot Be Compiled\"" >&5 +$as_echo "$as_me: WARNING: atheos/threads.h: section \"Present But Cannot Be Compiled\"" >&2;} + { $as_echo "$as_me:$LINENO: WARNING: atheos/threads.h: proceeding with the preprocessor's result" >&5 +$as_echo "$as_me: WARNING: atheos/threads.h: proceeding with the preprocessor's result" >&2;} + { $as_echo "$as_me:$LINENO: WARNING: atheos/threads.h: in the future, the compiler will take precedence" >&5 +$as_echo "$as_me: WARNING: atheos/threads.h: in the future, the compiler will take precedence" >&2;} ( cat <<\_ASBOX ## ------------------------------------------------ ## ## Report this to http://www.python.org/python-bugs ## @@ -14833,18 +15126,18 @@ ) | sed "s/^/$as_me: WARNING: /" >&2 ;; esac -{ echo "$as_me:$LINENO: checking for atheos/threads.h" >&5 -echo $ECHO_N "checking for atheos/threads.h... $ECHO_C" >&6; } +{ $as_echo "$as_me:$LINENO: checking for atheos/threads.h" >&5 +$as_echo_n "checking for atheos/threads.h... " >&6; } if test "${ac_cv_header_atheos_threads_h+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 + $as_echo_n "(cached) " >&6 else ac_cv_header_atheos_threads_h=$ac_header_preproc fi -{ echo "$as_me:$LINENO: result: $ac_cv_header_atheos_threads_h" >&5 -echo "${ECHO_T}$ac_cv_header_atheos_threads_h" >&6; } +{ $as_echo "$as_me:$LINENO: result: $ac_cv_header_atheos_threads_h" >&5 +$as_echo "$ac_cv_header_atheos_threads_h" >&6; } fi -if test $ac_cv_header_atheos_threads_h = yes; then +if test "x$ac_cv_header_atheos_threads_h" = x""yes; then cat >>confdefs.h <<\_ACEOF #define WITH_THREAD 1 _ACEOF @@ -14858,17 +15151,17 @@ else if test "${ac_cv_header_kernel_OS_h+set}" = set; then - { echo "$as_me:$LINENO: checking for kernel/OS.h" >&5 -echo $ECHO_N "checking for kernel/OS.h... $ECHO_C" >&6; } + { $as_echo "$as_me:$LINENO: checking for kernel/OS.h" >&5 +$as_echo_n "checking for kernel/OS.h... " >&6; } if test "${ac_cv_header_kernel_OS_h+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 + $as_echo_n "(cached) " >&6 fi -{ echo "$as_me:$LINENO: result: $ac_cv_header_kernel_OS_h" >&5 -echo "${ECHO_T}$ac_cv_header_kernel_OS_h" >&6; } +{ $as_echo "$as_me:$LINENO: result: $ac_cv_header_kernel_OS_h" >&5 +$as_echo "$ac_cv_header_kernel_OS_h" >&6; } else # Is the header compilable? -{ echo "$as_me:$LINENO: checking kernel/OS.h usability" >&5 -echo $ECHO_N "checking kernel/OS.h usability... $ECHO_C" >&6; } +{ $as_echo "$as_me:$LINENO: checking kernel/OS.h usability" >&5 +$as_echo_n "checking kernel/OS.h usability... " >&6; } cat >conftest.$ac_ext <<_ACEOF /* confdefs.h. */ _ACEOF @@ -14884,32 +15177,33 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_compile") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { test -z "$ac_c_werror_flag" || test ! -s conftest.err } && test -s conftest.$ac_objext; then ac_header_compiler=yes else - echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 ac_header_compiler=no fi rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext -{ echo "$as_me:$LINENO: result: $ac_header_compiler" >&5 -echo "${ECHO_T}$ac_header_compiler" >&6; } +{ $as_echo "$as_me:$LINENO: result: $ac_header_compiler" >&5 +$as_echo "$ac_header_compiler" >&6; } # Is the header present? -{ echo "$as_me:$LINENO: checking kernel/OS.h presence" >&5 -echo $ECHO_N "checking kernel/OS.h presence... $ECHO_C" >&6; } +{ $as_echo "$as_me:$LINENO: checking kernel/OS.h presence" >&5 +$as_echo_n "checking kernel/OS.h presence... " >&6; } cat >conftest.$ac_ext <<_ACEOF /* confdefs.h. */ _ACEOF @@ -14923,51 +15217,52 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_cpp conftest.$ac_ext") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } >/dev/null && { test -z "$ac_c_preproc_warn_flag$ac_c_werror_flag" || test ! -s conftest.err }; then ac_header_preproc=yes else - echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 ac_header_preproc=no fi rm -f conftest.err conftest.$ac_ext -{ echo "$as_me:$LINENO: result: $ac_header_preproc" >&5 -echo "${ECHO_T}$ac_header_preproc" >&6; } +{ $as_echo "$as_me:$LINENO: result: $ac_header_preproc" >&5 +$as_echo "$ac_header_preproc" >&6; } # So? What about this header? case $ac_header_compiler:$ac_header_preproc:$ac_c_preproc_warn_flag in yes:no: ) - { echo "$as_me:$LINENO: WARNING: kernel/OS.h: accepted by the compiler, rejected by the preprocessor!" >&5 -echo "$as_me: WARNING: kernel/OS.h: accepted by the compiler, rejected by the preprocessor!" >&2;} - { echo "$as_me:$LINENO: WARNING: kernel/OS.h: proceeding with the compiler's result" >&5 -echo "$as_me: WARNING: kernel/OS.h: proceeding with the compiler's result" >&2;} + { $as_echo "$as_me:$LINENO: WARNING: kernel/OS.h: accepted by the compiler, rejected by the preprocessor!" >&5 +$as_echo "$as_me: WARNING: kernel/OS.h: accepted by the compiler, rejected by the preprocessor!" >&2;} + { $as_echo "$as_me:$LINENO: WARNING: kernel/OS.h: proceeding with the compiler's result" >&5 +$as_echo "$as_me: WARNING: kernel/OS.h: proceeding with the compiler's result" >&2;} ac_header_preproc=yes ;; no:yes:* ) - { echo "$as_me:$LINENO: WARNING: kernel/OS.h: present but cannot be compiled" >&5 -echo "$as_me: WARNING: kernel/OS.h: present but cannot be compiled" >&2;} - { echo "$as_me:$LINENO: WARNING: kernel/OS.h: check for missing prerequisite headers?" >&5 -echo "$as_me: WARNING: kernel/OS.h: check for missing prerequisite headers?" >&2;} - { echo "$as_me:$LINENO: WARNING: kernel/OS.h: see the Autoconf documentation" >&5 -echo "$as_me: WARNING: kernel/OS.h: see the Autoconf documentation" >&2;} - { echo "$as_me:$LINENO: WARNING: kernel/OS.h: section \"Present But Cannot Be Compiled\"" >&5 -echo "$as_me: WARNING: kernel/OS.h: section \"Present But Cannot Be Compiled\"" >&2;} - { echo "$as_me:$LINENO: WARNING: kernel/OS.h: proceeding with the preprocessor's result" >&5 -echo "$as_me: WARNING: kernel/OS.h: proceeding with the preprocessor's result" >&2;} - { echo "$as_me:$LINENO: WARNING: kernel/OS.h: in the future, the compiler will take precedence" >&5 -echo "$as_me: WARNING: kernel/OS.h: in the future, the compiler will take precedence" >&2;} + { $as_echo "$as_me:$LINENO: WARNING: kernel/OS.h: present but cannot be compiled" >&5 +$as_echo "$as_me: WARNING: kernel/OS.h: present but cannot be compiled" >&2;} + { $as_echo "$as_me:$LINENO: WARNING: kernel/OS.h: check for missing prerequisite headers?" >&5 +$as_echo "$as_me: WARNING: kernel/OS.h: check for missing prerequisite headers?" >&2;} + { $as_echo "$as_me:$LINENO: WARNING: kernel/OS.h: see the Autoconf documentation" >&5 +$as_echo "$as_me: WARNING: kernel/OS.h: see the Autoconf documentation" >&2;} + { $as_echo "$as_me:$LINENO: WARNING: kernel/OS.h: section \"Present But Cannot Be Compiled\"" >&5 +$as_echo "$as_me: WARNING: kernel/OS.h: section \"Present But Cannot Be Compiled\"" >&2;} + { $as_echo "$as_me:$LINENO: WARNING: kernel/OS.h: proceeding with the preprocessor's result" >&5 +$as_echo "$as_me: WARNING: kernel/OS.h: proceeding with the preprocessor's result" >&2;} + { $as_echo "$as_me:$LINENO: WARNING: kernel/OS.h: in the future, the compiler will take precedence" >&5 +$as_echo "$as_me: WARNING: kernel/OS.h: in the future, the compiler will take precedence" >&2;} ( cat <<\_ASBOX ## ------------------------------------------------ ## ## Report this to http://www.python.org/python-bugs ## @@ -14976,18 +15271,18 @@ ) | sed "s/^/$as_me: WARNING: /" >&2 ;; esac -{ echo "$as_me:$LINENO: checking for kernel/OS.h" >&5 -echo $ECHO_N "checking for kernel/OS.h... $ECHO_C" >&6; } +{ $as_echo "$as_me:$LINENO: checking for kernel/OS.h" >&5 +$as_echo_n "checking for kernel/OS.h... " >&6; } if test "${ac_cv_header_kernel_OS_h+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 + $as_echo_n "(cached) " >&6 else ac_cv_header_kernel_OS_h=$ac_header_preproc fi -{ echo "$as_me:$LINENO: result: $ac_cv_header_kernel_OS_h" >&5 -echo "${ECHO_T}$ac_cv_header_kernel_OS_h" >&6; } +{ $as_echo "$as_me:$LINENO: result: $ac_cv_header_kernel_OS_h" >&5 +$as_echo "$ac_cv_header_kernel_OS_h" >&6; } fi -if test $ac_cv_header_kernel_OS_h = yes; then +if test "x$ac_cv_header_kernel_OS_h" = x""yes; then cat >>confdefs.h <<\_ACEOF #define WITH_THREAD 1 _ACEOF @@ -15000,10 +15295,10 @@ THREADOBJ="Python/thread.o" else - { echo "$as_me:$LINENO: checking for pthread_create in -lpthreads" >&5 -echo $ECHO_N "checking for pthread_create in -lpthreads... $ECHO_C" >&6; } + { $as_echo "$as_me:$LINENO: checking for pthread_create in -lpthreads" >&5 +$as_echo_n "checking for pthread_create in -lpthreads... " >&6; } if test "${ac_cv_lib_pthreads_pthread_create+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 + $as_echo_n "(cached) " >&6 else ac_check_lib_save_LIBS=$LIBS LIBS="-lpthreads $LIBS" @@ -15035,33 +15330,37 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_link") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { test -z "$ac_c_werror_flag" || test ! -s conftest.err - } && test -s conftest$ac_exeext && - $as_test_x conftest$ac_exeext; then + } && test -s conftest$ac_exeext && { + test "$cross_compiling" = yes || + $as_test_x conftest$ac_exeext + }; then ac_cv_lib_pthreads_pthread_create=yes else - echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 ac_cv_lib_pthreads_pthread_create=no fi +rm -rf conftest.dSYM rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \ conftest$ac_exeext conftest.$ac_ext LIBS=$ac_check_lib_save_LIBS fi -{ echo "$as_me:$LINENO: result: $ac_cv_lib_pthreads_pthread_create" >&5 -echo "${ECHO_T}$ac_cv_lib_pthreads_pthread_create" >&6; } -if test $ac_cv_lib_pthreads_pthread_create = yes; then +{ $as_echo "$as_me:$LINENO: result: $ac_cv_lib_pthreads_pthread_create" >&5 +$as_echo "$ac_cv_lib_pthreads_pthread_create" >&6; } +if test "x$ac_cv_lib_pthreads_pthread_create" = x""yes; then cat >>confdefs.h <<\_ACEOF #define WITH_THREAD 1 _ACEOF @@ -15071,10 +15370,10 @@ THREADOBJ="Python/thread.o" else - { echo "$as_me:$LINENO: checking for pthread_create in -lc_r" >&5 -echo $ECHO_N "checking for pthread_create in -lc_r... $ECHO_C" >&6; } + { $as_echo "$as_me:$LINENO: checking for pthread_create in -lc_r" >&5 +$as_echo_n "checking for pthread_create in -lc_r... " >&6; } if test "${ac_cv_lib_c_r_pthread_create+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 + $as_echo_n "(cached) " >&6 else ac_check_lib_save_LIBS=$LIBS LIBS="-lc_r $LIBS" @@ -15106,33 +15405,37 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_link") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { test -z "$ac_c_werror_flag" || test ! -s conftest.err - } && test -s conftest$ac_exeext && - $as_test_x conftest$ac_exeext; then + } && test -s conftest$ac_exeext && { + test "$cross_compiling" = yes || + $as_test_x conftest$ac_exeext + }; then ac_cv_lib_c_r_pthread_create=yes else - echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 ac_cv_lib_c_r_pthread_create=no fi +rm -rf conftest.dSYM rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \ conftest$ac_exeext conftest.$ac_ext LIBS=$ac_check_lib_save_LIBS fi -{ echo "$as_me:$LINENO: result: $ac_cv_lib_c_r_pthread_create" >&5 -echo "${ECHO_T}$ac_cv_lib_c_r_pthread_create" >&6; } -if test $ac_cv_lib_c_r_pthread_create = yes; then +{ $as_echo "$as_me:$LINENO: result: $ac_cv_lib_c_r_pthread_create" >&5 +$as_echo "$ac_cv_lib_c_r_pthread_create" >&6; } +if test "x$ac_cv_lib_c_r_pthread_create" = x""yes; then cat >>confdefs.h <<\_ACEOF #define WITH_THREAD 1 _ACEOF @@ -15142,10 +15445,10 @@ THREADOBJ="Python/thread.o" else - { echo "$as_me:$LINENO: checking for __pthread_create_system in -lpthread" >&5 -echo $ECHO_N "checking for __pthread_create_system in -lpthread... $ECHO_C" >&6; } + { $as_echo "$as_me:$LINENO: checking for __pthread_create_system in -lpthread" >&5 +$as_echo_n "checking for __pthread_create_system in -lpthread... " >&6; } if test "${ac_cv_lib_pthread___pthread_create_system+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 + $as_echo_n "(cached) " >&6 else ac_check_lib_save_LIBS=$LIBS LIBS="-lpthread $LIBS" @@ -15177,33 +15480,37 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_link") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { test -z "$ac_c_werror_flag" || test ! -s conftest.err - } && test -s conftest$ac_exeext && - $as_test_x conftest$ac_exeext; then + } && test -s conftest$ac_exeext && { + test "$cross_compiling" = yes || + $as_test_x conftest$ac_exeext + }; then ac_cv_lib_pthread___pthread_create_system=yes else - echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 ac_cv_lib_pthread___pthread_create_system=no fi +rm -rf conftest.dSYM rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \ conftest$ac_exeext conftest.$ac_ext LIBS=$ac_check_lib_save_LIBS fi -{ echo "$as_me:$LINENO: result: $ac_cv_lib_pthread___pthread_create_system" >&5 -echo "${ECHO_T}$ac_cv_lib_pthread___pthread_create_system" >&6; } -if test $ac_cv_lib_pthread___pthread_create_system = yes; then +{ $as_echo "$as_me:$LINENO: result: $ac_cv_lib_pthread___pthread_create_system" >&5 +$as_echo "$ac_cv_lib_pthread___pthread_create_system" >&6; } +if test "x$ac_cv_lib_pthread___pthread_create_system" = x""yes; then cat >>confdefs.h <<\_ACEOF #define WITH_THREAD 1 _ACEOF @@ -15213,10 +15520,10 @@ THREADOBJ="Python/thread.o" else - { echo "$as_me:$LINENO: checking for pthread_create in -lcma" >&5 -echo $ECHO_N "checking for pthread_create in -lcma... $ECHO_C" >&6; } + { $as_echo "$as_me:$LINENO: checking for pthread_create in -lcma" >&5 +$as_echo_n "checking for pthread_create in -lcma... " >&6; } if test "${ac_cv_lib_cma_pthread_create+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 + $as_echo_n "(cached) " >&6 else ac_check_lib_save_LIBS=$LIBS LIBS="-lcma $LIBS" @@ -15248,33 +15555,37 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_link") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { test -z "$ac_c_werror_flag" || test ! -s conftest.err - } && test -s conftest$ac_exeext && - $as_test_x conftest$ac_exeext; then + } && test -s conftest$ac_exeext && { + test "$cross_compiling" = yes || + $as_test_x conftest$ac_exeext + }; then ac_cv_lib_cma_pthread_create=yes else - echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 ac_cv_lib_cma_pthread_create=no fi +rm -rf conftest.dSYM rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \ conftest$ac_exeext conftest.$ac_ext LIBS=$ac_check_lib_save_LIBS fi -{ echo "$as_me:$LINENO: result: $ac_cv_lib_cma_pthread_create" >&5 -echo "${ECHO_T}$ac_cv_lib_cma_pthread_create" >&6; } -if test $ac_cv_lib_cma_pthread_create = yes; then +{ $as_echo "$as_me:$LINENO: result: $ac_cv_lib_cma_pthread_create" >&5 +$as_echo "$ac_cv_lib_cma_pthread_create" >&6; } +if test "x$ac_cv_lib_cma_pthread_create" = x""yes; then cat >>confdefs.h <<\_ACEOF #define WITH_THREAD 1 _ACEOF @@ -15304,6 +15615,7 @@ fi +rm -rf conftest.dSYM rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \ conftest$ac_exeext conftest.$ac_ext fi @@ -15315,10 +15627,10 @@ - { echo "$as_me:$LINENO: checking for usconfig in -lmpc" >&5 -echo $ECHO_N "checking for usconfig in -lmpc... $ECHO_C" >&6; } + { $as_echo "$as_me:$LINENO: checking for usconfig in -lmpc" >&5 +$as_echo_n "checking for usconfig in -lmpc... " >&6; } if test "${ac_cv_lib_mpc_usconfig+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 + $as_echo_n "(cached) " >&6 else ac_check_lib_save_LIBS=$LIBS LIBS="-lmpc $LIBS" @@ -15350,33 +15662,37 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_link") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { test -z "$ac_c_werror_flag" || test ! -s conftest.err - } && test -s conftest$ac_exeext && - $as_test_x conftest$ac_exeext; then + } && test -s conftest$ac_exeext && { + test "$cross_compiling" = yes || + $as_test_x conftest$ac_exeext + }; then ac_cv_lib_mpc_usconfig=yes else - echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 ac_cv_lib_mpc_usconfig=no fi +rm -rf conftest.dSYM rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \ conftest$ac_exeext conftest.$ac_ext LIBS=$ac_check_lib_save_LIBS fi -{ echo "$as_me:$LINENO: result: $ac_cv_lib_mpc_usconfig" >&5 -echo "${ECHO_T}$ac_cv_lib_mpc_usconfig" >&6; } -if test $ac_cv_lib_mpc_usconfig = yes; then +{ $as_echo "$as_me:$LINENO: result: $ac_cv_lib_mpc_usconfig" >&5 +$as_echo "$ac_cv_lib_mpc_usconfig" >&6; } +if test "x$ac_cv_lib_mpc_usconfig" = x""yes; then cat >>confdefs.h <<\_ACEOF #define WITH_THREAD 1 _ACEOF @@ -15388,10 +15704,10 @@ if test "$posix_threads" != "yes"; then - { echo "$as_me:$LINENO: checking for thr_create in -lthread" >&5 -echo $ECHO_N "checking for thr_create in -lthread... $ECHO_C" >&6; } + { $as_echo "$as_me:$LINENO: checking for thr_create in -lthread" >&5 +$as_echo_n "checking for thr_create in -lthread... " >&6; } if test "${ac_cv_lib_thread_thr_create+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 + $as_echo_n "(cached) " >&6 else ac_check_lib_save_LIBS=$LIBS LIBS="-lthread $LIBS" @@ -15423,33 +15739,37 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_link") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { test -z "$ac_c_werror_flag" || test ! -s conftest.err - } && test -s conftest$ac_exeext && - $as_test_x conftest$ac_exeext; then + } && test -s conftest$ac_exeext && { + test "$cross_compiling" = yes || + $as_test_x conftest$ac_exeext + }; then ac_cv_lib_thread_thr_create=yes else - echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 ac_cv_lib_thread_thr_create=no fi +rm -rf conftest.dSYM rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \ conftest$ac_exeext conftest.$ac_ext LIBS=$ac_check_lib_save_LIBS fi -{ echo "$as_me:$LINENO: result: $ac_cv_lib_thread_thr_create" >&5 -echo "${ECHO_T}$ac_cv_lib_thread_thr_create" >&6; } -if test $ac_cv_lib_thread_thr_create = yes; then +{ $as_echo "$as_me:$LINENO: result: $ac_cv_lib_thread_thr_create" >&5 +$as_echo "$ac_cv_lib_thread_thr_create" >&6; } +if test "x$ac_cv_lib_thread_thr_create" = x""yes; then cat >>confdefs.h <<\_ACEOF #define WITH_THREAD 1 _ACEOF @@ -15502,10 +15822,10 @@ ;; esac - { echo "$as_me:$LINENO: checking if PTHREAD_SCOPE_SYSTEM is supported" >&5 -echo $ECHO_N "checking if PTHREAD_SCOPE_SYSTEM is supported... $ECHO_C" >&6; } + { $as_echo "$as_me:$LINENO: checking if PTHREAD_SCOPE_SYSTEM is supported" >&5 +$as_echo_n "checking if PTHREAD_SCOPE_SYSTEM is supported... " >&6; } if test "${ac_cv_pthread_system_supported+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 + $as_echo_n "(cached) " >&6 else if test "$cross_compiling" = yes; then ac_cv_pthread_system_supported=no @@ -15535,29 +15855,32 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_link") 2>&5 ac_status=$? - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { ac_try='./conftest$ac_exeext' { (case "(($ac_try" in *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_try") 2>&5 ac_status=$? - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); }; }; then ac_cv_pthread_system_supported=yes else - echo "$as_me: program exited with status $ac_status" >&5 -echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: program exited with status $ac_status" >&5 +$as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 ( exit $ac_status ) ac_cv_pthread_system_supported=no fi +rm -rf conftest.dSYM rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext conftest.$ac_objext conftest.$ac_ext fi @@ -15565,8 +15888,8 @@ fi - { echo "$as_me:$LINENO: result: $ac_cv_pthread_system_supported" >&5 -echo "${ECHO_T}$ac_cv_pthread_system_supported" >&6; } + { $as_echo "$as_me:$LINENO: result: $ac_cv_pthread_system_supported" >&5 +$as_echo "$ac_cv_pthread_system_supported" >&6; } if test "$ac_cv_pthread_system_supported" = "yes"; then cat >>confdefs.h <<\_ACEOF @@ -15577,11 +15900,11 @@ for ac_func in pthread_sigmask do -as_ac_var=`echo "ac_cv_func_$ac_func" | $as_tr_sh` -{ echo "$as_me:$LINENO: checking for $ac_func" >&5 -echo $ECHO_N "checking for $ac_func... $ECHO_C" >&6; } +as_ac_var=`$as_echo "ac_cv_func_$ac_func" | $as_tr_sh` +{ $as_echo "$as_me:$LINENO: checking for $ac_func" >&5 +$as_echo_n "checking for $ac_func... " >&6; } if { as_var=$as_ac_var; eval "test \"\${$as_var+set}\" = set"; }; then - echo $ECHO_N "(cached) $ECHO_C" >&6 + $as_echo_n "(cached) " >&6 else cat >conftest.$ac_ext <<_ACEOF /* confdefs.h. */ @@ -15634,35 +15957,42 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_link") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { test -z "$ac_c_werror_flag" || test ! -s conftest.err - } && test -s conftest$ac_exeext && - $as_test_x conftest$ac_exeext; then + } && test -s conftest$ac_exeext && { + test "$cross_compiling" = yes || + $as_test_x conftest$ac_exeext + }; then eval "$as_ac_var=yes" else - echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 eval "$as_ac_var=no" fi +rm -rf conftest.dSYM rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \ conftest$ac_exeext conftest.$ac_ext fi -ac_res=`eval echo '${'$as_ac_var'}'` - { echo "$as_me:$LINENO: result: $ac_res" >&5 -echo "${ECHO_T}$ac_res" >&6; } -if test `eval echo '${'$as_ac_var'}'` = yes; then +ac_res=`eval 'as_val=${'$as_ac_var'} + $as_echo "$as_val"'` + { $as_echo "$as_me:$LINENO: result: $ac_res" >&5 +$as_echo "$ac_res" >&6; } +as_val=`eval 'as_val=${'$as_ac_var'} + $as_echo "$as_val"'` + if test "x$as_val" = x""yes; then cat >>confdefs.h <<_ACEOF -#define `echo "HAVE_$ac_func" | $as_tr_cpp` 1 +#define `$as_echo "HAVE_$ac_func" | $as_tr_cpp` 1 _ACEOF case $ac_sys_system in CYGWIN*) @@ -15682,18 +16012,18 @@ # Check for enable-ipv6 -{ echo "$as_me:$LINENO: checking if --enable-ipv6 is specified" >&5 -echo $ECHO_N "checking if --enable-ipv6 is specified... $ECHO_C" >&6; } +{ $as_echo "$as_me:$LINENO: checking if --enable-ipv6 is specified" >&5 +$as_echo_n "checking if --enable-ipv6 is specified... " >&6; } # Check whether --enable-ipv6 was given. if test "${enable_ipv6+set}" = set; then enableval=$enable_ipv6; case "$enableval" in no) - { echo "$as_me:$LINENO: result: no" >&5 -echo "${ECHO_T}no" >&6; } + { $as_echo "$as_me:$LINENO: result: no" >&5 +$as_echo "no" >&6; } ipv6=no ;; - *) { echo "$as_me:$LINENO: result: yes" >&5 -echo "${ECHO_T}yes" >&6; } + *) { $as_echo "$as_me:$LINENO: result: yes" >&5 +$as_echo "yes" >&6; } cat >>confdefs.h <<\_ACEOF #define ENABLE_IPV6 1 _ACEOF @@ -15704,8 +16034,8 @@ else if test "$cross_compiling" = yes; then - { echo "$as_me:$LINENO: result: no" >&5 -echo "${ECHO_T}no" >&6; } + { $as_echo "$as_me:$LINENO: result: no" >&5 +$as_echo "no" >&6; } ipv6=no else @@ -15733,41 +16063,44 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_link") 2>&5 ac_status=$? - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { ac_try='./conftest$ac_exeext' { (case "(($ac_try" in *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_try") 2>&5 ac_status=$? - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); }; }; then - { echo "$as_me:$LINENO: result: yes" >&5 -echo "${ECHO_T}yes" >&6; } + { $as_echo "$as_me:$LINENO: result: yes" >&5 +$as_echo "yes" >&6; } ipv6=yes else - echo "$as_me: program exited with status $ac_status" >&5 -echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: program exited with status $ac_status" >&5 +$as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 ( exit $ac_status ) -{ echo "$as_me:$LINENO: result: no" >&5 -echo "${ECHO_T}no" >&6; } +{ $as_echo "$as_me:$LINENO: result: no" >&5 +$as_echo "no" >&6; } ipv6=no fi +rm -rf conftest.dSYM rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext conftest.$ac_objext conftest.$ac_ext fi if test "$ipv6" = "yes"; then - { echo "$as_me:$LINENO: checking if RFC2553 API is available" >&5 -echo $ECHO_N "checking if RFC2553 API is available... $ECHO_C" >&6; } + { $as_echo "$as_me:$LINENO: checking if RFC2553 API is available" >&5 +$as_echo_n "checking if RFC2553 API is available... " >&6; } cat >conftest.$ac_ext <<_ACEOF /* confdefs.h. */ _ACEOF @@ -15791,26 +16124,27 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_compile") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { test -z "$ac_c_werror_flag" || test ! -s conftest.err } && test -s conftest.$ac_objext; then - { echo "$as_me:$LINENO: result: yes" >&5 -echo "${ECHO_T}yes" >&6; } + { $as_echo "$as_me:$LINENO: result: yes" >&5 +$as_echo "yes" >&6; } ipv6=yes else - echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 - { echo "$as_me:$LINENO: result: no" >&5 -echo "${ECHO_T}no" >&6; } + { $as_echo "$as_me:$LINENO: result: no" >&5 +$as_echo "no" >&6; } ipv6=no fi @@ -15832,8 +16166,8 @@ ipv6trylibc=no if test "$ipv6" = "yes"; then - { echo "$as_me:$LINENO: checking ipv6 stack type" >&5 -echo $ECHO_N "checking ipv6 stack type... $ECHO_C" >&6; } + { $as_echo "$as_me:$LINENO: checking ipv6 stack type" >&5 +$as_echo_n "checking ipv6 stack type... " >&6; } for i in inria kame linux-glibc linux-inet6 solaris toshiba v6d zeta; do case $i in @@ -15989,8 +16323,8 @@ break fi done - { echo "$as_me:$LINENO: result: $ipv6type" >&5 -echo "${ECHO_T}$ipv6type" >&6; } + { $as_echo "$as_me:$LINENO: result: $ipv6type" >&5 +$as_echo "$ipv6type" >&6; } fi if test "$ipv6" = "yes" -a "$ipv6lib" != "none"; then @@ -16009,8 +16343,8 @@ fi fi -{ echo "$as_me:$LINENO: checking for OSX 10.5 SDK or later" >&5 -echo $ECHO_N "checking for OSX 10.5 SDK or later... $ECHO_C" >&6; } +{ $as_echo "$as_me:$LINENO: checking for OSX 10.5 SDK or later" >&5 +$as_echo_n "checking for OSX 10.5 SDK or later... " >&6; } cat >conftest.$ac_ext <<_ACEOF /* confdefs.h. */ _ACEOF @@ -16032,13 +16366,14 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_compile") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { test -z "$ac_c_werror_flag" || test ! -s conftest.err @@ -16048,22 +16383,22 @@ #define HAVE_OSX105_SDK 1 _ACEOF - { echo "$as_me:$LINENO: result: yes" >&5 -echo "${ECHO_T}yes" >&6; } + { $as_echo "$as_me:$LINENO: result: yes" >&5 +$as_echo "yes" >&6; } else - echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 - { echo "$as_me:$LINENO: result: no" >&5 -echo "${ECHO_T}no" >&6; } + { $as_echo "$as_me:$LINENO: result: no" >&5 +$as_echo "no" >&6; } fi rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext # Check for --with-doc-strings -{ echo "$as_me:$LINENO: checking for --with-doc-strings" >&5 -echo $ECHO_N "checking for --with-doc-strings... $ECHO_C" >&6; } +{ $as_echo "$as_me:$LINENO: checking for --with-doc-strings" >&5 +$as_echo_n "checking for --with-doc-strings... " >&6; } # Check whether --with-doc-strings was given. if test "${with_doc_strings+set}" = set; then @@ -16082,12 +16417,12 @@ _ACEOF fi -{ echo "$as_me:$LINENO: result: $with_doc_strings" >&5 -echo "${ECHO_T}$with_doc_strings" >&6; } +{ $as_echo "$as_me:$LINENO: result: $with_doc_strings" >&5 +$as_echo "$with_doc_strings" >&6; } # Check for Python-specific malloc support -{ echo "$as_me:$LINENO: checking for --with-tsc" >&5 -echo $ECHO_N "checking for --with-tsc... $ECHO_C" >&6; } +{ $as_echo "$as_me:$LINENO: checking for --with-tsc" >&5 +$as_echo_n "checking for --with-tsc... " >&6; } # Check whether --with-tsc was given. if test "${with_tsc+set}" = set; then @@ -16099,20 +16434,20 @@ #define WITH_TSC 1 _ACEOF - { echo "$as_me:$LINENO: result: yes" >&5 -echo "${ECHO_T}yes" >&6; } -else { echo "$as_me:$LINENO: result: no" >&5 -echo "${ECHO_T}no" >&6; } + { $as_echo "$as_me:$LINENO: result: yes" >&5 +$as_echo "yes" >&6; } +else { $as_echo "$as_me:$LINENO: result: no" >&5 +$as_echo "no" >&6; } fi else - { echo "$as_me:$LINENO: result: no" >&5 -echo "${ECHO_T}no" >&6; } + { $as_echo "$as_me:$LINENO: result: no" >&5 +$as_echo "no" >&6; } fi # Check for Python-specific malloc support -{ echo "$as_me:$LINENO: checking for --with-pymalloc" >&5 -echo $ECHO_N "checking for --with-pymalloc... $ECHO_C" >&6; } +{ $as_echo "$as_me:$LINENO: checking for --with-pymalloc" >&5 +$as_echo_n "checking for --with-pymalloc... " >&6; } # Check whether --with-pymalloc was given. if test "${with_pymalloc+set}" = set; then @@ -16131,12 +16466,12 @@ _ACEOF fi -{ echo "$as_me:$LINENO: result: $with_pymalloc" >&5 -echo "${ECHO_T}$with_pymalloc" >&6; } +{ $as_echo "$as_me:$LINENO: result: $with_pymalloc" >&5 +$as_echo "$with_pymalloc" >&6; } # Check for --with-wctype-functions -{ echo "$as_me:$LINENO: checking for --with-wctype-functions" >&5 -echo $ECHO_N "checking for --with-wctype-functions... $ECHO_C" >&6; } +{ $as_echo "$as_me:$LINENO: checking for --with-wctype-functions" >&5 +$as_echo_n "checking for --with-wctype-functions... " >&6; } # Check whether --with-wctype-functions was given. if test "${with_wctype_functions+set}" = set; then @@ -16148,14 +16483,14 @@ #define WANT_WCTYPE_FUNCTIONS 1 _ACEOF - { echo "$as_me:$LINENO: result: yes" >&5 -echo "${ECHO_T}yes" >&6; } -else { echo "$as_me:$LINENO: result: no" >&5 -echo "${ECHO_T}no" >&6; } + { $as_echo "$as_me:$LINENO: result: yes" >&5 +$as_echo "yes" >&6; } +else { $as_echo "$as_me:$LINENO: result: no" >&5 +$as_echo "no" >&6; } fi else - { echo "$as_me:$LINENO: result: no" >&5 -echo "${ECHO_T}no" >&6; } + { $as_echo "$as_me:$LINENO: result: no" >&5 +$as_echo "no" >&6; } fi @@ -16168,11 +16503,11 @@ for ac_func in dlopen do -as_ac_var=`echo "ac_cv_func_$ac_func" | $as_tr_sh` -{ echo "$as_me:$LINENO: checking for $ac_func" >&5 -echo $ECHO_N "checking for $ac_func... $ECHO_C" >&6; } +as_ac_var=`$as_echo "ac_cv_func_$ac_func" | $as_tr_sh` +{ $as_echo "$as_me:$LINENO: checking for $ac_func" >&5 +$as_echo_n "checking for $ac_func... " >&6; } if { as_var=$as_ac_var; eval "test \"\${$as_var+set}\" = set"; }; then - echo $ECHO_N "(cached) $ECHO_C" >&6 + $as_echo_n "(cached) " >&6 else cat >conftest.$ac_ext <<_ACEOF /* confdefs.h. */ @@ -16225,35 +16560,42 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_link") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { test -z "$ac_c_werror_flag" || test ! -s conftest.err - } && test -s conftest$ac_exeext && - $as_test_x conftest$ac_exeext; then + } && test -s conftest$ac_exeext && { + test "$cross_compiling" = yes || + $as_test_x conftest$ac_exeext + }; then eval "$as_ac_var=yes" else - echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 eval "$as_ac_var=no" fi +rm -rf conftest.dSYM rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \ conftest$ac_exeext conftest.$ac_ext fi -ac_res=`eval echo '${'$as_ac_var'}'` - { echo "$as_me:$LINENO: result: $ac_res" >&5 -echo "${ECHO_T}$ac_res" >&6; } -if test `eval echo '${'$as_ac_var'}'` = yes; then +ac_res=`eval 'as_val=${'$as_ac_var'} + $as_echo "$as_val"'` + { $as_echo "$as_me:$LINENO: result: $ac_res" >&5 +$as_echo "$ac_res" >&6; } +as_val=`eval 'as_val=${'$as_ac_var'} + $as_echo "$as_val"'` + if test "x$as_val" = x""yes; then cat >>confdefs.h <<_ACEOF -#define `echo "HAVE_$ac_func" | $as_tr_cpp` 1 +#define `$as_echo "HAVE_$ac_func" | $as_tr_cpp` 1 _ACEOF fi @@ -16263,8 +16605,8 @@ # DYNLOADFILE specifies which dynload_*.o file we will use for dynamic # loading of modules. -{ echo "$as_me:$LINENO: checking DYNLOADFILE" >&5 -echo $ECHO_N "checking DYNLOADFILE... $ECHO_C" >&6; } +{ $as_echo "$as_me:$LINENO: checking DYNLOADFILE" >&5 +$as_echo_n "checking DYNLOADFILE... " >&6; } if test -z "$DYNLOADFILE" then case $ac_sys_system/$ac_sys_release in @@ -16289,8 +16631,8 @@ ;; esac fi -{ echo "$as_me:$LINENO: result: $DYNLOADFILE" >&5 -echo "${ECHO_T}$DYNLOADFILE" >&6; } +{ $as_echo "$as_me:$LINENO: result: $DYNLOADFILE" >&5 +$as_echo "$DYNLOADFILE" >&6; } if test "$DYNLOADFILE" != "dynload_stub.o" then @@ -16303,16 +16645,16 @@ # MACHDEP_OBJS can be set to platform-specific object files needed by Python -{ echo "$as_me:$LINENO: checking MACHDEP_OBJS" >&5 -echo $ECHO_N "checking MACHDEP_OBJS... $ECHO_C" >&6; } +{ $as_echo "$as_me:$LINENO: checking MACHDEP_OBJS" >&5 +$as_echo_n "checking MACHDEP_OBJS... " >&6; } if test -z "$MACHDEP_OBJS" then MACHDEP_OBJS=$extra_machdep_objs else MACHDEP_OBJS="$MACHDEP_OBJS $extra_machdep_objs" fi -{ echo "$as_me:$LINENO: result: MACHDEP_OBJS" >&5 -echo "${ECHO_T}MACHDEP_OBJS" >&6; } +{ $as_echo "$as_me:$LINENO: result: MACHDEP_OBJS" >&5 +$as_echo "MACHDEP_OBJS" >&6; } # checks for library functions @@ -16409,11 +16751,11 @@ sysconf tcgetpgrp tcsetpgrp tempnam timegm times tmpfile tmpnam tmpnam_r \ truncate uname unsetenv utimes waitpid wait3 wait4 wcscoll _getpty do -as_ac_var=`echo "ac_cv_func_$ac_func" | $as_tr_sh` -{ echo "$as_me:$LINENO: checking for $ac_func" >&5 -echo $ECHO_N "checking for $ac_func... $ECHO_C" >&6; } +as_ac_var=`$as_echo "ac_cv_func_$ac_func" | $as_tr_sh` +{ $as_echo "$as_me:$LINENO: checking for $ac_func" >&5 +$as_echo_n "checking for $ac_func... " >&6; } if { as_var=$as_ac_var; eval "test \"\${$as_var+set}\" = set"; }; then - echo $ECHO_N "(cached) $ECHO_C" >&6 + $as_echo_n "(cached) " >&6 else cat >conftest.$ac_ext <<_ACEOF /* confdefs.h. */ @@ -16466,35 +16808,42 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_link") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { test -z "$ac_c_werror_flag" || test ! -s conftest.err - } && test -s conftest$ac_exeext && - $as_test_x conftest$ac_exeext; then + } && test -s conftest$ac_exeext && { + test "$cross_compiling" = yes || + $as_test_x conftest$ac_exeext + }; then eval "$as_ac_var=yes" else - echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 eval "$as_ac_var=no" fi +rm -rf conftest.dSYM rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \ conftest$ac_exeext conftest.$ac_ext fi -ac_res=`eval echo '${'$as_ac_var'}'` - { echo "$as_me:$LINENO: result: $ac_res" >&5 -echo "${ECHO_T}$ac_res" >&6; } -if test `eval echo '${'$as_ac_var'}'` = yes; then +ac_res=`eval 'as_val=${'$as_ac_var'} + $as_echo "$as_val"'` + { $as_echo "$as_me:$LINENO: result: $ac_res" >&5 +$as_echo "$ac_res" >&6; } +as_val=`eval 'as_val=${'$as_ac_var'} + $as_echo "$as_val"'` + if test "x$as_val" = x""yes; then cat >>confdefs.h <<_ACEOF -#define `echo "HAVE_$ac_func" | $as_tr_cpp` 1 +#define `$as_echo "HAVE_$ac_func" | $as_tr_cpp` 1 _ACEOF fi @@ -16503,8 +16852,8 @@ # For some functions, having a definition is not sufficient, since # we want to take their address. -{ echo "$as_me:$LINENO: checking for chroot" >&5 -echo $ECHO_N "checking for chroot... $ECHO_C" >&6; } +{ $as_echo "$as_me:$LINENO: checking for chroot" >&5 +$as_echo_n "checking for chroot... " >&6; } cat >conftest.$ac_ext <<_ACEOF /* confdefs.h. */ _ACEOF @@ -16526,13 +16875,14 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_compile") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { test -z "$ac_c_werror_flag" || test ! -s conftest.err @@ -16542,20 +16892,20 @@ #define HAVE_CHROOT 1 _ACEOF - { echo "$as_me:$LINENO: result: yes" >&5 -echo "${ECHO_T}yes" >&6; } + { $as_echo "$as_me:$LINENO: result: yes" >&5 +$as_echo "yes" >&6; } else - echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 - { echo "$as_me:$LINENO: result: no" >&5 -echo "${ECHO_T}no" >&6; } + { $as_echo "$as_me:$LINENO: result: no" >&5 +$as_echo "no" >&6; } fi rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext -{ echo "$as_me:$LINENO: checking for link" >&5 -echo $ECHO_N "checking for link... $ECHO_C" >&6; } +{ $as_echo "$as_me:$LINENO: checking for link" >&5 +$as_echo_n "checking for link... " >&6; } cat >conftest.$ac_ext <<_ACEOF /* confdefs.h. */ _ACEOF @@ -16577,13 +16927,14 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_compile") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { test -z "$ac_c_werror_flag" || test ! -s conftest.err @@ -16593,20 +16944,20 @@ #define HAVE_LINK 1 _ACEOF - { echo "$as_me:$LINENO: result: yes" >&5 -echo "${ECHO_T}yes" >&6; } + { $as_echo "$as_me:$LINENO: result: yes" >&5 +$as_echo "yes" >&6; } else - echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 - { echo "$as_me:$LINENO: result: no" >&5 -echo "${ECHO_T}no" >&6; } + { $as_echo "$as_me:$LINENO: result: no" >&5 +$as_echo "no" >&6; } fi rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext -{ echo "$as_me:$LINENO: checking for symlink" >&5 -echo $ECHO_N "checking for symlink... $ECHO_C" >&6; } +{ $as_echo "$as_me:$LINENO: checking for symlink" >&5 +$as_echo_n "checking for symlink... " >&6; } cat >conftest.$ac_ext <<_ACEOF /* confdefs.h. */ _ACEOF @@ -16628,13 +16979,14 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_compile") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { test -z "$ac_c_werror_flag" || test ! -s conftest.err @@ -16644,20 +16996,20 @@ #define HAVE_SYMLINK 1 _ACEOF - { echo "$as_me:$LINENO: result: yes" >&5 -echo "${ECHO_T}yes" >&6; } + { $as_echo "$as_me:$LINENO: result: yes" >&5 +$as_echo "yes" >&6; } else - echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 - { echo "$as_me:$LINENO: result: no" >&5 -echo "${ECHO_T}no" >&6; } + { $as_echo "$as_me:$LINENO: result: no" >&5 +$as_echo "no" >&6; } fi rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext -{ echo "$as_me:$LINENO: checking for fchdir" >&5 -echo $ECHO_N "checking for fchdir... $ECHO_C" >&6; } +{ $as_echo "$as_me:$LINENO: checking for fchdir" >&5 +$as_echo_n "checking for fchdir... " >&6; } cat >conftest.$ac_ext <<_ACEOF /* confdefs.h. */ _ACEOF @@ -16679,13 +17031,14 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_compile") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { test -z "$ac_c_werror_flag" || test ! -s conftest.err @@ -16695,20 +17048,20 @@ #define HAVE_FCHDIR 1 _ACEOF - { echo "$as_me:$LINENO: result: yes" >&5 -echo "${ECHO_T}yes" >&6; } + { $as_echo "$as_me:$LINENO: result: yes" >&5 +$as_echo "yes" >&6; } else - echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 - { echo "$as_me:$LINENO: result: no" >&5 -echo "${ECHO_T}no" >&6; } + { $as_echo "$as_me:$LINENO: result: no" >&5 +$as_echo "no" >&6; } fi rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext -{ echo "$as_me:$LINENO: checking for fsync" >&5 -echo $ECHO_N "checking for fsync... $ECHO_C" >&6; } +{ $as_echo "$as_me:$LINENO: checking for fsync" >&5 +$as_echo_n "checking for fsync... " >&6; } cat >conftest.$ac_ext <<_ACEOF /* confdefs.h. */ _ACEOF @@ -16730,13 +17083,14 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_compile") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { test -z "$ac_c_werror_flag" || test ! -s conftest.err @@ -16746,20 +17100,20 @@ #define HAVE_FSYNC 1 _ACEOF - { echo "$as_me:$LINENO: result: yes" >&5 -echo "${ECHO_T}yes" >&6; } + { $as_echo "$as_me:$LINENO: result: yes" >&5 +$as_echo "yes" >&6; } else - echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 - { echo "$as_me:$LINENO: result: no" >&5 -echo "${ECHO_T}no" >&6; } + { $as_echo "$as_me:$LINENO: result: no" >&5 +$as_echo "no" >&6; } fi rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext -{ echo "$as_me:$LINENO: checking for fdatasync" >&5 -echo $ECHO_N "checking for fdatasync... $ECHO_C" >&6; } +{ $as_echo "$as_me:$LINENO: checking for fdatasync" >&5 +$as_echo_n "checking for fdatasync... " >&6; } cat >conftest.$ac_ext <<_ACEOF /* confdefs.h. */ _ACEOF @@ -16781,13 +17135,14 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_compile") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { test -z "$ac_c_werror_flag" || test ! -s conftest.err @@ -16797,20 +17152,20 @@ #define HAVE_FDATASYNC 1 _ACEOF - { echo "$as_me:$LINENO: result: yes" >&5 -echo "${ECHO_T}yes" >&6; } + { $as_echo "$as_me:$LINENO: result: yes" >&5 +$as_echo "yes" >&6; } else - echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 - { echo "$as_me:$LINENO: result: no" >&5 -echo "${ECHO_T}no" >&6; } + { $as_echo "$as_me:$LINENO: result: no" >&5 +$as_echo "no" >&6; } fi rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext -{ echo "$as_me:$LINENO: checking for epoll" >&5 -echo $ECHO_N "checking for epoll... $ECHO_C" >&6; } +{ $as_echo "$as_me:$LINENO: checking for epoll" >&5 +$as_echo_n "checking for epoll... " >&6; } cat >conftest.$ac_ext <<_ACEOF /* confdefs.h. */ _ACEOF @@ -16832,13 +17187,14 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_compile") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { test -z "$ac_c_werror_flag" || test ! -s conftest.err @@ -16848,20 +17204,20 @@ #define HAVE_EPOLL 1 _ACEOF - { echo "$as_me:$LINENO: result: yes" >&5 -echo "${ECHO_T}yes" >&6; } + { $as_echo "$as_me:$LINENO: result: yes" >&5 +$as_echo "yes" >&6; } else - echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 - { echo "$as_me:$LINENO: result: no" >&5 -echo "${ECHO_T}no" >&6; } + { $as_echo "$as_me:$LINENO: result: no" >&5 +$as_echo "no" >&6; } fi rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext -{ echo "$as_me:$LINENO: checking for kqueue" >&5 -echo $ECHO_N "checking for kqueue... $ECHO_C" >&6; } +{ $as_echo "$as_me:$LINENO: checking for kqueue" >&5 +$as_echo_n "checking for kqueue... " >&6; } cat >conftest.$ac_ext <<_ACEOF /* confdefs.h. */ _ACEOF @@ -16886,13 +17242,14 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_compile") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { test -z "$ac_c_werror_flag" || test ! -s conftest.err @@ -16902,14 +17259,14 @@ #define HAVE_KQUEUE 1 _ACEOF - { echo "$as_me:$LINENO: result: yes" >&5 -echo "${ECHO_T}yes" >&6; } + { $as_echo "$as_me:$LINENO: result: yes" >&5 +$as_echo "yes" >&6; } else - echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 - { echo "$as_me:$LINENO: result: no" >&5 -echo "${ECHO_T}no" >&6; } + { $as_echo "$as_me:$LINENO: result: no" >&5 +$as_echo "no" >&6; } fi @@ -16920,8 +17277,8 @@ # address to avoid compiler warnings and potential miscompilations # because of the missing prototypes. -{ echo "$as_me:$LINENO: checking for ctermid_r" >&5 -echo $ECHO_N "checking for ctermid_r... $ECHO_C" >&6; } +{ $as_echo "$as_me:$LINENO: checking for ctermid_r" >&5 +$as_echo_n "checking for ctermid_r... " >&6; } cat >conftest.$ac_ext <<_ACEOF /* confdefs.h. */ _ACEOF @@ -16946,13 +17303,14 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_compile") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { test -z "$ac_c_werror_flag" || test ! -s conftest.err @@ -16962,21 +17320,21 @@ #define HAVE_CTERMID_R 1 _ACEOF - { echo "$as_me:$LINENO: result: yes" >&5 -echo "${ECHO_T}yes" >&6; } + { $as_echo "$as_me:$LINENO: result: yes" >&5 +$as_echo "yes" >&6; } else - echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 - { echo "$as_me:$LINENO: result: no" >&5 -echo "${ECHO_T}no" >&6; } + { $as_echo "$as_me:$LINENO: result: no" >&5 +$as_echo "no" >&6; } fi rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext -{ echo "$as_me:$LINENO: checking for flock" >&5 -echo $ECHO_N "checking for flock... $ECHO_C" >&6; } +{ $as_echo "$as_me:$LINENO: checking for flock" >&5 +$as_echo_n "checking for flock... " >&6; } cat >conftest.$ac_ext <<_ACEOF /* confdefs.h. */ _ACEOF @@ -17001,13 +17359,14 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_compile") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { test -z "$ac_c_werror_flag" || test ! -s conftest.err @@ -17017,21 +17376,21 @@ #define HAVE_FLOCK 1 _ACEOF - { echo "$as_me:$LINENO: result: yes" >&5 -echo "${ECHO_T}yes" >&6; } + { $as_echo "$as_me:$LINENO: result: yes" >&5 +$as_echo "yes" >&6; } else - echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 - { echo "$as_me:$LINENO: result: no" >&5 -echo "${ECHO_T}no" >&6; } + { $as_echo "$as_me:$LINENO: result: no" >&5 +$as_echo "no" >&6; } fi rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext -{ echo "$as_me:$LINENO: checking for getpagesize" >&5 -echo $ECHO_N "checking for getpagesize... $ECHO_C" >&6; } +{ $as_echo "$as_me:$LINENO: checking for getpagesize" >&5 +$as_echo_n "checking for getpagesize... " >&6; } cat >conftest.$ac_ext <<_ACEOF /* confdefs.h. */ _ACEOF @@ -17056,13 +17415,14 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_compile") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { test -z "$ac_c_werror_flag" || test ! -s conftest.err @@ -17072,14 +17432,14 @@ #define HAVE_GETPAGESIZE 1 _ACEOF - { echo "$as_me:$LINENO: result: yes" >&5 -echo "${ECHO_T}yes" >&6; } + { $as_echo "$as_me:$LINENO: result: yes" >&5 +$as_echo "yes" >&6; } else - echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 - { echo "$as_me:$LINENO: result: no" >&5 -echo "${ECHO_T}no" >&6; } + { $as_echo "$as_me:$LINENO: result: no" >&5 +$as_echo "no" >&6; } fi @@ -17089,10 +17449,10 @@ do # Extract the first word of "$ac_prog", so it can be a program name with args. set dummy $ac_prog; ac_word=$2 -{ echo "$as_me:$LINENO: checking for $ac_word" >&5 -echo $ECHO_N "checking for $ac_word... $ECHO_C" >&6; } +{ $as_echo "$as_me:$LINENO: checking for $ac_word" >&5 +$as_echo_n "checking for $ac_word... " >&6; } if test "${ac_cv_prog_TRUE+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 + $as_echo_n "(cached) " >&6 else if test -n "$TRUE"; then ac_cv_prog_TRUE="$TRUE" # Let the user override the test. @@ -17105,7 +17465,7 @@ for ac_exec_ext in '' $ac_executable_extensions; do if { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_test_x "$as_dir/$ac_word$ac_exec_ext"; }; then ac_cv_prog_TRUE="$ac_prog" - echo "$as_me:$LINENO: found $as_dir/$ac_word$ac_exec_ext" >&5 + $as_echo "$as_me:$LINENO: found $as_dir/$ac_word$ac_exec_ext" >&5 break 2 fi done @@ -17116,11 +17476,11 @@ fi TRUE=$ac_cv_prog_TRUE if test -n "$TRUE"; then - { echo "$as_me:$LINENO: result: $TRUE" >&5 -echo "${ECHO_T}$TRUE" >&6; } + { $as_echo "$as_me:$LINENO: result: $TRUE" >&5 +$as_echo "$TRUE" >&6; } else - { echo "$as_me:$LINENO: result: no" >&5 -echo "${ECHO_T}no" >&6; } + { $as_echo "$as_me:$LINENO: result: no" >&5 +$as_echo "no" >&6; } fi @@ -17129,10 +17489,10 @@ test -n "$TRUE" || TRUE="/bin/true" -{ echo "$as_me:$LINENO: checking for inet_aton in -lc" >&5 -echo $ECHO_N "checking for inet_aton in -lc... $ECHO_C" >&6; } +{ $as_echo "$as_me:$LINENO: checking for inet_aton in -lc" >&5 +$as_echo_n "checking for inet_aton in -lc... " >&6; } if test "${ac_cv_lib_c_inet_aton+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 + $as_echo_n "(cached) " >&6 else ac_check_lib_save_LIBS=$LIBS LIBS="-lc $LIBS" @@ -17164,40 +17524,44 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_link") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { test -z "$ac_c_werror_flag" || test ! -s conftest.err - } && test -s conftest$ac_exeext && - $as_test_x conftest$ac_exeext; then + } && test -s conftest$ac_exeext && { + test "$cross_compiling" = yes || + $as_test_x conftest$ac_exeext + }; then ac_cv_lib_c_inet_aton=yes else - echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 ac_cv_lib_c_inet_aton=no fi +rm -rf conftest.dSYM rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \ conftest$ac_exeext conftest.$ac_ext LIBS=$ac_check_lib_save_LIBS fi -{ echo "$as_me:$LINENO: result: $ac_cv_lib_c_inet_aton" >&5 -echo "${ECHO_T}$ac_cv_lib_c_inet_aton" >&6; } -if test $ac_cv_lib_c_inet_aton = yes; then +{ $as_echo "$as_me:$LINENO: result: $ac_cv_lib_c_inet_aton" >&5 +$as_echo "$ac_cv_lib_c_inet_aton" >&6; } +if test "x$ac_cv_lib_c_inet_aton" = x""yes; then $ac_cv_prog_TRUE else -{ echo "$as_me:$LINENO: checking for inet_aton in -lresolv" >&5 -echo $ECHO_N "checking for inet_aton in -lresolv... $ECHO_C" >&6; } +{ $as_echo "$as_me:$LINENO: checking for inet_aton in -lresolv" >&5 +$as_echo_n "checking for inet_aton in -lresolv... " >&6; } if test "${ac_cv_lib_resolv_inet_aton+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 + $as_echo_n "(cached) " >&6 else ac_check_lib_save_LIBS=$LIBS LIBS="-lresolv $LIBS" @@ -17229,33 +17593,37 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_link") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { test -z "$ac_c_werror_flag" || test ! -s conftest.err - } && test -s conftest$ac_exeext && - $as_test_x conftest$ac_exeext; then + } && test -s conftest$ac_exeext && { + test "$cross_compiling" = yes || + $as_test_x conftest$ac_exeext + }; then ac_cv_lib_resolv_inet_aton=yes else - echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 ac_cv_lib_resolv_inet_aton=no fi +rm -rf conftest.dSYM rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \ conftest$ac_exeext conftest.$ac_ext LIBS=$ac_check_lib_save_LIBS fi -{ echo "$as_me:$LINENO: result: $ac_cv_lib_resolv_inet_aton" >&5 -echo "${ECHO_T}$ac_cv_lib_resolv_inet_aton" >&6; } -if test $ac_cv_lib_resolv_inet_aton = yes; then +{ $as_echo "$as_me:$LINENO: result: $ac_cv_lib_resolv_inet_aton" >&5 +$as_echo "$ac_cv_lib_resolv_inet_aton" >&6; } +if test "x$ac_cv_lib_resolv_inet_aton" = x""yes; then cat >>confdefs.h <<_ACEOF #define HAVE_LIBRESOLV 1 _ACEOF @@ -17270,10 +17638,10 @@ # On Tru64, chflags seems to be present, but calling it will # exit Python -{ echo "$as_me:$LINENO: checking for chflags" >&5 -echo $ECHO_N "checking for chflags... $ECHO_C" >&6; } +{ $as_echo "$as_me:$LINENO: checking for chflags" >&5 +$as_echo_n "checking for chflags... " >&6; } if test "${ac_cv_have_chflags+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 + $as_echo_n "(cached) " >&6 else if test "$cross_compiling" = yes; then ac_cv_have_chflags=cross @@ -17301,42 +17669,45 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_link") 2>&5 ac_status=$? - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { ac_try='./conftest$ac_exeext' { (case "(($ac_try" in *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_try") 2>&5 ac_status=$? - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); }; }; then ac_cv_have_chflags=yes else - echo "$as_me: program exited with status $ac_status" >&5 -echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: program exited with status $ac_status" >&5 +$as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 ( exit $ac_status ) ac_cv_have_chflags=no fi +rm -rf conftest.dSYM rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext conftest.$ac_objext conftest.$ac_ext fi fi -{ echo "$as_me:$LINENO: result: $ac_cv_have_chflags" >&5 -echo "${ECHO_T}$ac_cv_have_chflags" >&6; } +{ $as_echo "$as_me:$LINENO: result: $ac_cv_have_chflags" >&5 +$as_echo "$ac_cv_have_chflags" >&6; } if test "$ac_cv_have_chflags" = cross ; then - { echo "$as_me:$LINENO: checking for chflags" >&5 -echo $ECHO_N "checking for chflags... $ECHO_C" >&6; } + { $as_echo "$as_me:$LINENO: checking for chflags" >&5 +$as_echo_n "checking for chflags... " >&6; } if test "${ac_cv_func_chflags+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 + $as_echo_n "(cached) " >&6 else cat >conftest.$ac_ext <<_ACEOF /* confdefs.h. */ @@ -17389,32 +17760,36 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_link") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { test -z "$ac_c_werror_flag" || test ! -s conftest.err - } && test -s conftest$ac_exeext && - $as_test_x conftest$ac_exeext; then + } && test -s conftest$ac_exeext && { + test "$cross_compiling" = yes || + $as_test_x conftest$ac_exeext + }; then ac_cv_func_chflags=yes else - echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 ac_cv_func_chflags=no fi +rm -rf conftest.dSYM rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \ conftest$ac_exeext conftest.$ac_ext fi -{ echo "$as_me:$LINENO: result: $ac_cv_func_chflags" >&5 -echo "${ECHO_T}$ac_cv_func_chflags" >&6; } -if test $ac_cv_func_chflags = yes; then +{ $as_echo "$as_me:$LINENO: result: $ac_cv_func_chflags" >&5 +$as_echo "$ac_cv_func_chflags" >&6; } +if test "x$ac_cv_func_chflags" = x""yes; then ac_cv_have_chflags="yes" else ac_cv_have_chflags="no" @@ -17429,10 +17804,10 @@ fi -{ echo "$as_me:$LINENO: checking for lchflags" >&5 -echo $ECHO_N "checking for lchflags... $ECHO_C" >&6; } +{ $as_echo "$as_me:$LINENO: checking for lchflags" >&5 +$as_echo_n "checking for lchflags... " >&6; } if test "${ac_cv_have_lchflags+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 + $as_echo_n "(cached) " >&6 else if test "$cross_compiling" = yes; then ac_cv_have_lchflags=cross @@ -17460,42 +17835,45 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_link") 2>&5 ac_status=$? - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { ac_try='./conftest$ac_exeext' { (case "(($ac_try" in *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_try") 2>&5 ac_status=$? - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); }; }; then ac_cv_have_lchflags=yes else - echo "$as_me: program exited with status $ac_status" >&5 -echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: program exited with status $ac_status" >&5 +$as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 ( exit $ac_status ) ac_cv_have_lchflags=no fi +rm -rf conftest.dSYM rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext conftest.$ac_objext conftest.$ac_ext fi fi -{ echo "$as_me:$LINENO: result: $ac_cv_have_lchflags" >&5 -echo "${ECHO_T}$ac_cv_have_lchflags" >&6; } +{ $as_echo "$as_me:$LINENO: result: $ac_cv_have_lchflags" >&5 +$as_echo "$ac_cv_have_lchflags" >&6; } if test "$ac_cv_have_lchflags" = cross ; then - { echo "$as_me:$LINENO: checking for lchflags" >&5 -echo $ECHO_N "checking for lchflags... $ECHO_C" >&6; } + { $as_echo "$as_me:$LINENO: checking for lchflags" >&5 +$as_echo_n "checking for lchflags... " >&6; } if test "${ac_cv_func_lchflags+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 + $as_echo_n "(cached) " >&6 else cat >conftest.$ac_ext <<_ACEOF /* confdefs.h. */ @@ -17548,32 +17926,36 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_link") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { test -z "$ac_c_werror_flag" || test ! -s conftest.err - } && test -s conftest$ac_exeext && - $as_test_x conftest$ac_exeext; then + } && test -s conftest$ac_exeext && { + test "$cross_compiling" = yes || + $as_test_x conftest$ac_exeext + }; then ac_cv_func_lchflags=yes else - echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 ac_cv_func_lchflags=no fi +rm -rf conftest.dSYM rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \ conftest$ac_exeext conftest.$ac_ext fi -{ echo "$as_me:$LINENO: result: $ac_cv_func_lchflags" >&5 -echo "${ECHO_T}$ac_cv_func_lchflags" >&6; } -if test $ac_cv_func_lchflags = yes; then +{ $as_echo "$as_me:$LINENO: result: $ac_cv_func_lchflags" >&5 +$as_echo "$ac_cv_func_lchflags" >&6; } +if test "x$ac_cv_func_lchflags" = x""yes; then ac_cv_have_lchflags="yes" else ac_cv_have_lchflags="no" @@ -17597,10 +17979,10 @@ ;; esac -{ echo "$as_me:$LINENO: checking for inflateCopy in -lz" >&5 -echo $ECHO_N "checking for inflateCopy in -lz... $ECHO_C" >&6; } +{ $as_echo "$as_me:$LINENO: checking for inflateCopy in -lz" >&5 +$as_echo_n "checking for inflateCopy in -lz... " >&6; } if test "${ac_cv_lib_z_inflateCopy+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 + $as_echo_n "(cached) " >&6 else ac_check_lib_save_LIBS=$LIBS LIBS="-lz $LIBS" @@ -17632,33 +18014,37 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_link") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { test -z "$ac_c_werror_flag" || test ! -s conftest.err - } && test -s conftest$ac_exeext && - $as_test_x conftest$ac_exeext; then + } && test -s conftest$ac_exeext && { + test "$cross_compiling" = yes || + $as_test_x conftest$ac_exeext + }; then ac_cv_lib_z_inflateCopy=yes else - echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 ac_cv_lib_z_inflateCopy=no fi +rm -rf conftest.dSYM rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \ conftest$ac_exeext conftest.$ac_ext LIBS=$ac_check_lib_save_LIBS fi -{ echo "$as_me:$LINENO: result: $ac_cv_lib_z_inflateCopy" >&5 -echo "${ECHO_T}$ac_cv_lib_z_inflateCopy" >&6; } -if test $ac_cv_lib_z_inflateCopy = yes; then +{ $as_echo "$as_me:$LINENO: result: $ac_cv_lib_z_inflateCopy" >&5 +$as_echo "$ac_cv_lib_z_inflateCopy" >&6; } +if test "x$ac_cv_lib_z_inflateCopy" = x""yes; then cat >>confdefs.h <<\_ACEOF #define HAVE_ZLIB_COPY 1 @@ -17674,8 +18060,8 @@ ;; esac -{ echo "$as_me:$LINENO: checking for hstrerror" >&5 -echo $ECHO_N "checking for hstrerror... $ECHO_C" >&6; } +{ $as_echo "$as_me:$LINENO: checking for hstrerror" >&5 +$as_echo_n "checking for hstrerror... " >&6; } cat >conftest.$ac_ext <<_ACEOF /* confdefs.h. */ _ACEOF @@ -17700,39 +18086,43 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_link") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { test -z "$ac_c_werror_flag" || test ! -s conftest.err - } && test -s conftest$ac_exeext && - $as_test_x conftest$ac_exeext; then + } && test -s conftest$ac_exeext && { + test "$cross_compiling" = yes || + $as_test_x conftest$ac_exeext + }; then cat >>confdefs.h <<\_ACEOF #define HAVE_HSTRERROR 1 _ACEOF - { echo "$as_me:$LINENO: result: yes" >&5 -echo "${ECHO_T}yes" >&6; } + { $as_echo "$as_me:$LINENO: result: yes" >&5 +$as_echo "yes" >&6; } else - echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 - { echo "$as_me:$LINENO: result: no" >&5 -echo "${ECHO_T}no" >&6; } + { $as_echo "$as_me:$LINENO: result: no" >&5 +$as_echo "no" >&6; } fi +rm -rf conftest.dSYM rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \ conftest$ac_exeext conftest.$ac_ext -{ echo "$as_me:$LINENO: checking for inet_aton" >&5 -echo $ECHO_N "checking for inet_aton... $ECHO_C" >&6; } +{ $as_echo "$as_me:$LINENO: checking for inet_aton" >&5 +$as_echo_n "checking for inet_aton... " >&6; } cat >conftest.$ac_ext <<_ACEOF /* confdefs.h. */ _ACEOF @@ -17760,39 +18150,43 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_link") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { test -z "$ac_c_werror_flag" || test ! -s conftest.err - } && test -s conftest$ac_exeext && - $as_test_x conftest$ac_exeext; then + } && test -s conftest$ac_exeext && { + test "$cross_compiling" = yes || + $as_test_x conftest$ac_exeext + }; then cat >>confdefs.h <<\_ACEOF #define HAVE_INET_ATON 1 _ACEOF - { echo "$as_me:$LINENO: result: yes" >&5 -echo "${ECHO_T}yes" >&6; } + { $as_echo "$as_me:$LINENO: result: yes" >&5 +$as_echo "yes" >&6; } else - echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 - { echo "$as_me:$LINENO: result: no" >&5 -echo "${ECHO_T}no" >&6; } + { $as_echo "$as_me:$LINENO: result: no" >&5 +$as_echo "no" >&6; } fi +rm -rf conftest.dSYM rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \ conftest$ac_exeext conftest.$ac_ext -{ echo "$as_me:$LINENO: checking for inet_pton" >&5 -echo $ECHO_N "checking for inet_pton... $ECHO_C" >&6; } +{ $as_echo "$as_me:$LINENO: checking for inet_pton" >&5 +$as_echo_n "checking for inet_pton... " >&6; } cat >conftest.$ac_ext <<_ACEOF /* confdefs.h. */ _ACEOF @@ -17820,13 +18214,14 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_compile") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { test -z "$ac_c_werror_flag" || test ! -s conftest.err @@ -17836,22 +18231,22 @@ #define HAVE_INET_PTON 1 _ACEOF - { echo "$as_me:$LINENO: result: yes" >&5 -echo "${ECHO_T}yes" >&6; } + { $as_echo "$as_me:$LINENO: result: yes" >&5 +$as_echo "yes" >&6; } else - echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 - { echo "$as_me:$LINENO: result: no" >&5 -echo "${ECHO_T}no" >&6; } + { $as_echo "$as_me:$LINENO: result: no" >&5 +$as_echo "no" >&6; } fi rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext # On some systems, setgroups is in unistd.h, on others, in grp.h -{ echo "$as_me:$LINENO: checking for setgroups" >&5 -echo $ECHO_N "checking for setgroups... $ECHO_C" >&6; } +{ $as_echo "$as_me:$LINENO: checking for setgroups" >&5 +$as_echo_n "checking for setgroups... " >&6; } cat >conftest.$ac_ext <<_ACEOF /* confdefs.h. */ _ACEOF @@ -17879,13 +18274,14 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_compile") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { test -z "$ac_c_werror_flag" || test ! -s conftest.err @@ -17895,14 +18291,14 @@ #define HAVE_SETGROUPS 1 _ACEOF - { echo "$as_me:$LINENO: result: yes" >&5 -echo "${ECHO_T}yes" >&6; } + { $as_echo "$as_me:$LINENO: result: yes" >&5 +$as_echo "yes" >&6; } else - echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 - { echo "$as_me:$LINENO: result: no" >&5 -echo "${ECHO_T}no" >&6; } + { $as_echo "$as_me:$LINENO: result: no" >&5 +$as_echo "no" >&6; } fi @@ -17913,11 +18309,11 @@ for ac_func in openpty do -as_ac_var=`echo "ac_cv_func_$ac_func" | $as_tr_sh` -{ echo "$as_me:$LINENO: checking for $ac_func" >&5 -echo $ECHO_N "checking for $ac_func... $ECHO_C" >&6; } +as_ac_var=`$as_echo "ac_cv_func_$ac_func" | $as_tr_sh` +{ $as_echo "$as_me:$LINENO: checking for $ac_func" >&5 +$as_echo_n "checking for $ac_func... " >&6; } if { as_var=$as_ac_var; eval "test \"\${$as_var+set}\" = set"; }; then - echo $ECHO_N "(cached) $ECHO_C" >&6 + $as_echo_n "(cached) " >&6 else cat >conftest.$ac_ext <<_ACEOF /* confdefs.h. */ @@ -17970,42 +18366,49 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_link") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { test -z "$ac_c_werror_flag" || test ! -s conftest.err - } && test -s conftest$ac_exeext && - $as_test_x conftest$ac_exeext; then + } && test -s conftest$ac_exeext && { + test "$cross_compiling" = yes || + $as_test_x conftest$ac_exeext + }; then eval "$as_ac_var=yes" else - echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 eval "$as_ac_var=no" fi +rm -rf conftest.dSYM rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \ conftest$ac_exeext conftest.$ac_ext fi -ac_res=`eval echo '${'$as_ac_var'}'` - { echo "$as_me:$LINENO: result: $ac_res" >&5 -echo "${ECHO_T}$ac_res" >&6; } -if test `eval echo '${'$as_ac_var'}'` = yes; then +ac_res=`eval 'as_val=${'$as_ac_var'} + $as_echo "$as_val"'` + { $as_echo "$as_me:$LINENO: result: $ac_res" >&5 +$as_echo "$ac_res" >&6; } +as_val=`eval 'as_val=${'$as_ac_var'} + $as_echo "$as_val"'` + if test "x$as_val" = x""yes; then cat >>confdefs.h <<_ACEOF -#define `echo "HAVE_$ac_func" | $as_tr_cpp` 1 +#define `$as_echo "HAVE_$ac_func" | $as_tr_cpp` 1 _ACEOF else - { echo "$as_me:$LINENO: checking for openpty in -lutil" >&5 -echo $ECHO_N "checking for openpty in -lutil... $ECHO_C" >&6; } + { $as_echo "$as_me:$LINENO: checking for openpty in -lutil" >&5 +$as_echo_n "checking for openpty in -lutil... " >&6; } if test "${ac_cv_lib_util_openpty+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 + $as_echo_n "(cached) " >&6 else ac_check_lib_save_LIBS=$LIBS LIBS="-lutil $LIBS" @@ -18037,42 +18440,46 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_link") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { test -z "$ac_c_werror_flag" || test ! -s conftest.err - } && test -s conftest$ac_exeext && - $as_test_x conftest$ac_exeext; then + } && test -s conftest$ac_exeext && { + test "$cross_compiling" = yes || + $as_test_x conftest$ac_exeext + }; then ac_cv_lib_util_openpty=yes else - echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 ac_cv_lib_util_openpty=no fi +rm -rf conftest.dSYM rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \ conftest$ac_exeext conftest.$ac_ext LIBS=$ac_check_lib_save_LIBS fi -{ echo "$as_me:$LINENO: result: $ac_cv_lib_util_openpty" >&5 -echo "${ECHO_T}$ac_cv_lib_util_openpty" >&6; } -if test $ac_cv_lib_util_openpty = yes; then +{ $as_echo "$as_me:$LINENO: result: $ac_cv_lib_util_openpty" >&5 +$as_echo "$ac_cv_lib_util_openpty" >&6; } +if test "x$ac_cv_lib_util_openpty" = x""yes; then cat >>confdefs.h <<\_ACEOF #define HAVE_OPENPTY 1 _ACEOF LIBS="$LIBS -lutil" else - { echo "$as_me:$LINENO: checking for openpty in -lbsd" >&5 -echo $ECHO_N "checking for openpty in -lbsd... $ECHO_C" >&6; } + { $as_echo "$as_me:$LINENO: checking for openpty in -lbsd" >&5 +$as_echo_n "checking for openpty in -lbsd... " >&6; } if test "${ac_cv_lib_bsd_openpty+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 + $as_echo_n "(cached) " >&6 else ac_check_lib_save_LIBS=$LIBS LIBS="-lbsd $LIBS" @@ -18104,33 +18511,37 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_link") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { test -z "$ac_c_werror_flag" || test ! -s conftest.err - } && test -s conftest$ac_exeext && - $as_test_x conftest$ac_exeext; then + } && test -s conftest$ac_exeext && { + test "$cross_compiling" = yes || + $as_test_x conftest$ac_exeext + }; then ac_cv_lib_bsd_openpty=yes else - echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 ac_cv_lib_bsd_openpty=no fi +rm -rf conftest.dSYM rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \ conftest$ac_exeext conftest.$ac_ext LIBS=$ac_check_lib_save_LIBS fi -{ echo "$as_me:$LINENO: result: $ac_cv_lib_bsd_openpty" >&5 -echo "${ECHO_T}$ac_cv_lib_bsd_openpty" >&6; } -if test $ac_cv_lib_bsd_openpty = yes; then +{ $as_echo "$as_me:$LINENO: result: $ac_cv_lib_bsd_openpty" >&5 +$as_echo "$ac_cv_lib_bsd_openpty" >&6; } +if test "x$ac_cv_lib_bsd_openpty" = x""yes; then cat >>confdefs.h <<\_ACEOF #define HAVE_OPENPTY 1 _ACEOF @@ -18147,11 +18558,11 @@ for ac_func in forkpty do -as_ac_var=`echo "ac_cv_func_$ac_func" | $as_tr_sh` -{ echo "$as_me:$LINENO: checking for $ac_func" >&5 -echo $ECHO_N "checking for $ac_func... $ECHO_C" >&6; } +as_ac_var=`$as_echo "ac_cv_func_$ac_func" | $as_tr_sh` +{ $as_echo "$as_me:$LINENO: checking for $ac_func" >&5 +$as_echo_n "checking for $ac_func... " >&6; } if { as_var=$as_ac_var; eval "test \"\${$as_var+set}\" = set"; }; then - echo $ECHO_N "(cached) $ECHO_C" >&6 + $as_echo_n "(cached) " >&6 else cat >conftest.$ac_ext <<_ACEOF /* confdefs.h. */ @@ -18204,42 +18615,49 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_link") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { test -z "$ac_c_werror_flag" || test ! -s conftest.err - } && test -s conftest$ac_exeext && - $as_test_x conftest$ac_exeext; then + } && test -s conftest$ac_exeext && { + test "$cross_compiling" = yes || + $as_test_x conftest$ac_exeext + }; then eval "$as_ac_var=yes" else - echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 eval "$as_ac_var=no" fi +rm -rf conftest.dSYM rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \ conftest$ac_exeext conftest.$ac_ext fi -ac_res=`eval echo '${'$as_ac_var'}'` - { echo "$as_me:$LINENO: result: $ac_res" >&5 -echo "${ECHO_T}$ac_res" >&6; } -if test `eval echo '${'$as_ac_var'}'` = yes; then +ac_res=`eval 'as_val=${'$as_ac_var'} + $as_echo "$as_val"'` + { $as_echo "$as_me:$LINENO: result: $ac_res" >&5 +$as_echo "$ac_res" >&6; } +as_val=`eval 'as_val=${'$as_ac_var'} + $as_echo "$as_val"'` + if test "x$as_val" = x""yes; then cat >>confdefs.h <<_ACEOF -#define `echo "HAVE_$ac_func" | $as_tr_cpp` 1 +#define `$as_echo "HAVE_$ac_func" | $as_tr_cpp` 1 _ACEOF else - { echo "$as_me:$LINENO: checking for forkpty in -lutil" >&5 -echo $ECHO_N "checking for forkpty in -lutil... $ECHO_C" >&6; } + { $as_echo "$as_me:$LINENO: checking for forkpty in -lutil" >&5 +$as_echo_n "checking for forkpty in -lutil... " >&6; } if test "${ac_cv_lib_util_forkpty+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 + $as_echo_n "(cached) " >&6 else ac_check_lib_save_LIBS=$LIBS LIBS="-lutil $LIBS" @@ -18271,42 +18689,46 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_link") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { test -z "$ac_c_werror_flag" || test ! -s conftest.err - } && test -s conftest$ac_exeext && - $as_test_x conftest$ac_exeext; then + } && test -s conftest$ac_exeext && { + test "$cross_compiling" = yes || + $as_test_x conftest$ac_exeext + }; then ac_cv_lib_util_forkpty=yes else - echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 ac_cv_lib_util_forkpty=no fi +rm -rf conftest.dSYM rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \ conftest$ac_exeext conftest.$ac_ext LIBS=$ac_check_lib_save_LIBS fi -{ echo "$as_me:$LINENO: result: $ac_cv_lib_util_forkpty" >&5 -echo "${ECHO_T}$ac_cv_lib_util_forkpty" >&6; } -if test $ac_cv_lib_util_forkpty = yes; then +{ $as_echo "$as_me:$LINENO: result: $ac_cv_lib_util_forkpty" >&5 +$as_echo "$ac_cv_lib_util_forkpty" >&6; } +if test "x$ac_cv_lib_util_forkpty" = x""yes; then cat >>confdefs.h <<\_ACEOF #define HAVE_FORKPTY 1 _ACEOF LIBS="$LIBS -lutil" else - { echo "$as_me:$LINENO: checking for forkpty in -lbsd" >&5 -echo $ECHO_N "checking for forkpty in -lbsd... $ECHO_C" >&6; } + { $as_echo "$as_me:$LINENO: checking for forkpty in -lbsd" >&5 +$as_echo_n "checking for forkpty in -lbsd... " >&6; } if test "${ac_cv_lib_bsd_forkpty+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 + $as_echo_n "(cached) " >&6 else ac_check_lib_save_LIBS=$LIBS LIBS="-lbsd $LIBS" @@ -18338,33 +18760,37 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_link") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { test -z "$ac_c_werror_flag" || test ! -s conftest.err - } && test -s conftest$ac_exeext && - $as_test_x conftest$ac_exeext; then + } && test -s conftest$ac_exeext && { + test "$cross_compiling" = yes || + $as_test_x conftest$ac_exeext + }; then ac_cv_lib_bsd_forkpty=yes else - echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 ac_cv_lib_bsd_forkpty=no fi +rm -rf conftest.dSYM rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \ conftest$ac_exeext conftest.$ac_ext LIBS=$ac_check_lib_save_LIBS fi -{ echo "$as_me:$LINENO: result: $ac_cv_lib_bsd_forkpty" >&5 -echo "${ECHO_T}$ac_cv_lib_bsd_forkpty" >&6; } -if test $ac_cv_lib_bsd_forkpty = yes; then +{ $as_echo "$as_me:$LINENO: result: $ac_cv_lib_bsd_forkpty" >&5 +$as_echo "$ac_cv_lib_bsd_forkpty" >&6; } +if test "x$ac_cv_lib_bsd_forkpty" = x""yes; then cat >>confdefs.h <<\_ACEOF #define HAVE_FORKPTY 1 _ACEOF @@ -18383,11 +18809,11 @@ for ac_func in memmove do -as_ac_var=`echo "ac_cv_func_$ac_func" | $as_tr_sh` -{ echo "$as_me:$LINENO: checking for $ac_func" >&5 -echo $ECHO_N "checking for $ac_func... $ECHO_C" >&6; } +as_ac_var=`$as_echo "ac_cv_func_$ac_func" | $as_tr_sh` +{ $as_echo "$as_me:$LINENO: checking for $ac_func" >&5 +$as_echo_n "checking for $ac_func... " >&6; } if { as_var=$as_ac_var; eval "test \"\${$as_var+set}\" = set"; }; then - echo $ECHO_N "(cached) $ECHO_C" >&6 + $as_echo_n "(cached) " >&6 else cat >conftest.$ac_ext <<_ACEOF /* confdefs.h. */ @@ -18440,35 +18866,42 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_link") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { test -z "$ac_c_werror_flag" || test ! -s conftest.err - } && test -s conftest$ac_exeext && - $as_test_x conftest$ac_exeext; then + } && test -s conftest$ac_exeext && { + test "$cross_compiling" = yes || + $as_test_x conftest$ac_exeext + }; then eval "$as_ac_var=yes" else - echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 eval "$as_ac_var=no" fi +rm -rf conftest.dSYM rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \ conftest$ac_exeext conftest.$ac_ext fi -ac_res=`eval echo '${'$as_ac_var'}'` - { echo "$as_me:$LINENO: result: $ac_res" >&5 -echo "${ECHO_T}$ac_res" >&6; } -if test `eval echo '${'$as_ac_var'}'` = yes; then +ac_res=`eval 'as_val=${'$as_ac_var'} + $as_echo "$as_val"'` + { $as_echo "$as_me:$LINENO: result: $ac_res" >&5 +$as_echo "$ac_res" >&6; } +as_val=`eval 'as_val=${'$as_ac_var'} + $as_echo "$as_val"'` + if test "x$as_val" = x""yes; then cat >>confdefs.h <<_ACEOF -#define `echo "HAVE_$ac_func" | $as_tr_cpp` 1 +#define `$as_echo "HAVE_$ac_func" | $as_tr_cpp` 1 _ACEOF fi @@ -18484,11 +18917,11 @@ for ac_func in fseek64 fseeko fstatvfs ftell64 ftello statvfs do -as_ac_var=`echo "ac_cv_func_$ac_func" | $as_tr_sh` -{ echo "$as_me:$LINENO: checking for $ac_func" >&5 -echo $ECHO_N "checking for $ac_func... $ECHO_C" >&6; } +as_ac_var=`$as_echo "ac_cv_func_$ac_func" | $as_tr_sh` +{ $as_echo "$as_me:$LINENO: checking for $ac_func" >&5 +$as_echo_n "checking for $ac_func... " >&6; } if { as_var=$as_ac_var; eval "test \"\${$as_var+set}\" = set"; }; then - echo $ECHO_N "(cached) $ECHO_C" >&6 + $as_echo_n "(cached) " >&6 else cat >conftest.$ac_ext <<_ACEOF /* confdefs.h. */ @@ -18541,35 +18974,42 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_link") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { test -z "$ac_c_werror_flag" || test ! -s conftest.err - } && test -s conftest$ac_exeext && - $as_test_x conftest$ac_exeext; then + } && test -s conftest$ac_exeext && { + test "$cross_compiling" = yes || + $as_test_x conftest$ac_exeext + }; then eval "$as_ac_var=yes" else - echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 eval "$as_ac_var=no" fi +rm -rf conftest.dSYM rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \ conftest$ac_exeext conftest.$ac_ext fi -ac_res=`eval echo '${'$as_ac_var'}'` - { echo "$as_me:$LINENO: result: $ac_res" >&5 -echo "${ECHO_T}$ac_res" >&6; } -if test `eval echo '${'$as_ac_var'}'` = yes; then +ac_res=`eval 'as_val=${'$as_ac_var'} + $as_echo "$as_val"'` + { $as_echo "$as_me:$LINENO: result: $ac_res" >&5 +$as_echo "$ac_res" >&6; } +as_val=`eval 'as_val=${'$as_ac_var'} + $as_echo "$as_val"'` + if test "x$as_val" = x""yes; then cat >>confdefs.h <<_ACEOF -#define `echo "HAVE_$ac_func" | $as_tr_cpp` 1 +#define `$as_echo "HAVE_$ac_func" | $as_tr_cpp` 1 _ACEOF fi @@ -18581,11 +19021,11 @@ for ac_func in dup2 getcwd strdup do -as_ac_var=`echo "ac_cv_func_$ac_func" | $as_tr_sh` -{ echo "$as_me:$LINENO: checking for $ac_func" >&5 -echo $ECHO_N "checking for $ac_func... $ECHO_C" >&6; } +as_ac_var=`$as_echo "ac_cv_func_$ac_func" | $as_tr_sh` +{ $as_echo "$as_me:$LINENO: checking for $ac_func" >&5 +$as_echo_n "checking for $ac_func... " >&6; } if { as_var=$as_ac_var; eval "test \"\${$as_var+set}\" = set"; }; then - echo $ECHO_N "(cached) $ECHO_C" >&6 + $as_echo_n "(cached) " >&6 else cat >conftest.$ac_ext <<_ACEOF /* confdefs.h. */ @@ -18638,35 +19078,42 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_link") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { test -z "$ac_c_werror_flag" || test ! -s conftest.err - } && test -s conftest$ac_exeext && - $as_test_x conftest$ac_exeext; then + } && test -s conftest$ac_exeext && { + test "$cross_compiling" = yes || + $as_test_x conftest$ac_exeext + }; then eval "$as_ac_var=yes" else - echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 eval "$as_ac_var=no" fi +rm -rf conftest.dSYM rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \ conftest$ac_exeext conftest.$ac_ext fi -ac_res=`eval echo '${'$as_ac_var'}'` - { echo "$as_me:$LINENO: result: $ac_res" >&5 -echo "${ECHO_T}$ac_res" >&6; } -if test `eval echo '${'$as_ac_var'}'` = yes; then +ac_res=`eval 'as_val=${'$as_ac_var'} + $as_echo "$as_val"'` + { $as_echo "$as_me:$LINENO: result: $ac_res" >&5 +$as_echo "$ac_res" >&6; } +as_val=`eval 'as_val=${'$as_ac_var'} + $as_echo "$as_val"'` + if test "x$as_val" = x""yes; then cat >>confdefs.h <<_ACEOF -#define `echo "HAVE_$ac_func" | $as_tr_cpp` 1 +#define `$as_echo "HAVE_$ac_func" | $as_tr_cpp` 1 _ACEOF else @@ -18683,11 +19130,11 @@ for ac_func in getpgrp do -as_ac_var=`echo "ac_cv_func_$ac_func" | $as_tr_sh` -{ echo "$as_me:$LINENO: checking for $ac_func" >&5 -echo $ECHO_N "checking for $ac_func... $ECHO_C" >&6; } +as_ac_var=`$as_echo "ac_cv_func_$ac_func" | $as_tr_sh` +{ $as_echo "$as_me:$LINENO: checking for $ac_func" >&5 +$as_echo_n "checking for $ac_func... " >&6; } if { as_var=$as_ac_var; eval "test \"\${$as_var+set}\" = set"; }; then - echo $ECHO_N "(cached) $ECHO_C" >&6 + $as_echo_n "(cached) " >&6 else cat >conftest.$ac_ext <<_ACEOF /* confdefs.h. */ @@ -18740,35 +19187,42 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_link") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { test -z "$ac_c_werror_flag" || test ! -s conftest.err - } && test -s conftest$ac_exeext && - $as_test_x conftest$ac_exeext; then + } && test -s conftest$ac_exeext && { + test "$cross_compiling" = yes || + $as_test_x conftest$ac_exeext + }; then eval "$as_ac_var=yes" else - echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 eval "$as_ac_var=no" fi +rm -rf conftest.dSYM rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \ conftest$ac_exeext conftest.$ac_ext fi -ac_res=`eval echo '${'$as_ac_var'}'` - { echo "$as_me:$LINENO: result: $ac_res" >&5 -echo "${ECHO_T}$ac_res" >&6; } -if test `eval echo '${'$as_ac_var'}'` = yes; then +ac_res=`eval 'as_val=${'$as_ac_var'} + $as_echo "$as_val"'` + { $as_echo "$as_me:$LINENO: result: $ac_res" >&5 +$as_echo "$ac_res" >&6; } +as_val=`eval 'as_val=${'$as_ac_var'} + $as_echo "$as_val"'` + if test "x$as_val" = x""yes; then cat >>confdefs.h <<_ACEOF -#define `echo "HAVE_$ac_func" | $as_tr_cpp` 1 +#define `$as_echo "HAVE_$ac_func" | $as_tr_cpp` 1 _ACEOF cat >conftest.$ac_ext <<_ACEOF /* confdefs.h. */ @@ -18791,13 +19245,14 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_compile") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { test -z "$ac_c_werror_flag" || test ! -s conftest.err @@ -18809,7 +19264,7 @@ else - echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 @@ -18823,11 +19278,11 @@ for ac_func in setpgrp do -as_ac_var=`echo "ac_cv_func_$ac_func" | $as_tr_sh` -{ echo "$as_me:$LINENO: checking for $ac_func" >&5 -echo $ECHO_N "checking for $ac_func... $ECHO_C" >&6; } +as_ac_var=`$as_echo "ac_cv_func_$ac_func" | $as_tr_sh` +{ $as_echo "$as_me:$LINENO: checking for $ac_func" >&5 +$as_echo_n "checking for $ac_func... " >&6; } if { as_var=$as_ac_var; eval "test \"\${$as_var+set}\" = set"; }; then - echo $ECHO_N "(cached) $ECHO_C" >&6 + $as_echo_n "(cached) " >&6 else cat >conftest.$ac_ext <<_ACEOF /* confdefs.h. */ @@ -18880,35 +19335,42 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_link") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { test -z "$ac_c_werror_flag" || test ! -s conftest.err - } && test -s conftest$ac_exeext && - $as_test_x conftest$ac_exeext; then + } && test -s conftest$ac_exeext && { + test "$cross_compiling" = yes || + $as_test_x conftest$ac_exeext + }; then eval "$as_ac_var=yes" else - echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 eval "$as_ac_var=no" fi +rm -rf conftest.dSYM rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \ conftest$ac_exeext conftest.$ac_ext fi -ac_res=`eval echo '${'$as_ac_var'}'` - { echo "$as_me:$LINENO: result: $ac_res" >&5 -echo "${ECHO_T}$ac_res" >&6; } -if test `eval echo '${'$as_ac_var'}'` = yes; then +ac_res=`eval 'as_val=${'$as_ac_var'} + $as_echo "$as_val"'` + { $as_echo "$as_me:$LINENO: result: $ac_res" >&5 +$as_echo "$ac_res" >&6; } +as_val=`eval 'as_val=${'$as_ac_var'} + $as_echo "$as_val"'` + if test "x$as_val" = x""yes; then cat >>confdefs.h <<_ACEOF -#define `echo "HAVE_$ac_func" | $as_tr_cpp` 1 +#define `$as_echo "HAVE_$ac_func" | $as_tr_cpp` 1 _ACEOF cat >conftest.$ac_ext <<_ACEOF /* confdefs.h. */ @@ -18931,13 +19393,14 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_compile") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { test -z "$ac_c_werror_flag" || test ! -s conftest.err @@ -18949,7 +19412,7 @@ else - echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 @@ -18963,11 +19426,11 @@ for ac_func in gettimeofday do -as_ac_var=`echo "ac_cv_func_$ac_func" | $as_tr_sh` -{ echo "$as_me:$LINENO: checking for $ac_func" >&5 -echo $ECHO_N "checking for $ac_func... $ECHO_C" >&6; } +as_ac_var=`$as_echo "ac_cv_func_$ac_func" | $as_tr_sh` +{ $as_echo "$as_me:$LINENO: checking for $ac_func" >&5 +$as_echo_n "checking for $ac_func... " >&6; } if { as_var=$as_ac_var; eval "test \"\${$as_var+set}\" = set"; }; then - echo $ECHO_N "(cached) $ECHO_C" >&6 + $as_echo_n "(cached) " >&6 else cat >conftest.$ac_ext <<_ACEOF /* confdefs.h. */ @@ -19020,35 +19483,42 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_link") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { test -z "$ac_c_werror_flag" || test ! -s conftest.err - } && test -s conftest$ac_exeext && - $as_test_x conftest$ac_exeext; then + } && test -s conftest$ac_exeext && { + test "$cross_compiling" = yes || + $as_test_x conftest$ac_exeext + }; then eval "$as_ac_var=yes" else - echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 eval "$as_ac_var=no" fi +rm -rf conftest.dSYM rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \ conftest$ac_exeext conftest.$ac_ext fi -ac_res=`eval echo '${'$as_ac_var'}'` - { echo "$as_me:$LINENO: result: $ac_res" >&5 -echo "${ECHO_T}$ac_res" >&6; } -if test `eval echo '${'$as_ac_var'}'` = yes; then +ac_res=`eval 'as_val=${'$as_ac_var'} + $as_echo "$as_val"'` + { $as_echo "$as_me:$LINENO: result: $ac_res" >&5 +$as_echo "$ac_res" >&6; } +as_val=`eval 'as_val=${'$as_ac_var'} + $as_echo "$as_val"'` + if test "x$as_val" = x""yes; then cat >>confdefs.h <<_ACEOF -#define `echo "HAVE_$ac_func" | $as_tr_cpp` 1 +#define `$as_echo "HAVE_$ac_func" | $as_tr_cpp` 1 _ACEOF cat >conftest.$ac_ext <<_ACEOF /* confdefs.h. */ @@ -19071,20 +19541,21 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_compile") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { test -z "$ac_c_werror_flag" || test ! -s conftest.err } && test -s conftest.$ac_objext; then : else - echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 @@ -19101,8 +19572,8 @@ done -{ echo "$as_me:$LINENO: checking for major" >&5 -echo $ECHO_N "checking for major... $ECHO_C" >&6; } +{ $as_echo "$as_me:$LINENO: checking for major" >&5 +$as_echo_n "checking for major... " >&6; } cat >conftest.$ac_ext <<_ACEOF /* confdefs.h. */ _ACEOF @@ -19134,44 +19605,48 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_link") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { test -z "$ac_c_werror_flag" || test ! -s conftest.err - } && test -s conftest$ac_exeext && - $as_test_x conftest$ac_exeext; then + } && test -s conftest$ac_exeext && { + test "$cross_compiling" = yes || + $as_test_x conftest$ac_exeext + }; then cat >>confdefs.h <<\_ACEOF #define HAVE_DEVICE_MACROS 1 _ACEOF - { echo "$as_me:$LINENO: result: yes" >&5 -echo "${ECHO_T}yes" >&6; } + { $as_echo "$as_me:$LINENO: result: yes" >&5 +$as_echo "yes" >&6; } else - echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 - { echo "$as_me:$LINENO: result: no" >&5 -echo "${ECHO_T}no" >&6; } + { $as_echo "$as_me:$LINENO: result: no" >&5 +$as_echo "no" >&6; } fi +rm -rf conftest.dSYM rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \ conftest$ac_exeext conftest.$ac_ext # On OSF/1 V5.1, getaddrinfo is available, but a define # for [no]getaddrinfo in netdb.h. -{ echo "$as_me:$LINENO: checking for getaddrinfo" >&5 -echo $ECHO_N "checking for getaddrinfo... $ECHO_C" >&6; } +{ $as_echo "$as_me:$LINENO: checking for getaddrinfo" >&5 +$as_echo_n "checking for getaddrinfo... " >&6; } cat >conftest.$ac_ext <<_ACEOF /* confdefs.h. */ _ACEOF @@ -19200,26 +19675,29 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_link") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { test -z "$ac_c_werror_flag" || test ! -s conftest.err - } && test -s conftest$ac_exeext && - $as_test_x conftest$ac_exeext; then + } && test -s conftest$ac_exeext && { + test "$cross_compiling" = yes || + $as_test_x conftest$ac_exeext + }; then -{ echo "$as_me:$LINENO: result: yes" >&5 -echo "${ECHO_T}yes" >&6; } -{ echo "$as_me:$LINENO: checking getaddrinfo bug" >&5 -echo $ECHO_N "checking getaddrinfo bug... $ECHO_C" >&6; } +{ $as_echo "$as_me:$LINENO: result: yes" >&5 +$as_echo "yes" >&6; } +{ $as_echo "$as_me:$LINENO: checking getaddrinfo bug" >&5 +$as_echo_n "checking getaddrinfo bug... " >&6; } if test "$cross_compiling" = yes; then - { echo "$as_me:$LINENO: result: buggy" >&5 -echo "${ECHO_T}buggy" >&6; } + { $as_echo "$as_me:$LINENO: result: buggy" >&5 +$as_echo "buggy" >&6; } buggygetaddrinfo=yes else cat >conftest.$ac_ext <<_ACEOF @@ -19322,48 +19800,52 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_link") 2>&5 ac_status=$? - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { ac_try='./conftest$ac_exeext' { (case "(($ac_try" in *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_try") 2>&5 ac_status=$? - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); }; }; then - { echo "$as_me:$LINENO: result: good" >&5 -echo "${ECHO_T}good" >&6; } + { $as_echo "$as_me:$LINENO: result: good" >&5 +$as_echo "good" >&6; } buggygetaddrinfo=no else - echo "$as_me: program exited with status $ac_status" >&5 -echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: program exited with status $ac_status" >&5 +$as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 ( exit $ac_status ) -{ echo "$as_me:$LINENO: result: buggy" >&5 -echo "${ECHO_T}buggy" >&6; } +{ $as_echo "$as_me:$LINENO: result: buggy" >&5 +$as_echo "buggy" >&6; } buggygetaddrinfo=yes fi +rm -rf conftest.dSYM rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext conftest.$ac_objext conftest.$ac_ext fi else - echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 -{ echo "$as_me:$LINENO: result: no" >&5 -echo "${ECHO_T}no" >&6; } +{ $as_echo "$as_me:$LINENO: result: no" >&5 +$as_echo "no" >&6; } buggygetaddrinfo=yes fi +rm -rf conftest.dSYM rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \ conftest$ac_exeext conftest.$ac_ext @@ -19383,11 +19865,11 @@ for ac_func in getnameinfo do -as_ac_var=`echo "ac_cv_func_$ac_func" | $as_tr_sh` -{ echo "$as_me:$LINENO: checking for $ac_func" >&5 -echo $ECHO_N "checking for $ac_func... $ECHO_C" >&6; } +as_ac_var=`$as_echo "ac_cv_func_$ac_func" | $as_tr_sh` +{ $as_echo "$as_me:$LINENO: checking for $ac_func" >&5 +$as_echo_n "checking for $ac_func... " >&6; } if { as_var=$as_ac_var; eval "test \"\${$as_var+set}\" = set"; }; then - echo $ECHO_N "(cached) $ECHO_C" >&6 + $as_echo_n "(cached) " >&6 else cat >conftest.$ac_ext <<_ACEOF /* confdefs.h. */ @@ -19440,35 +19922,42 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_link") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { test -z "$ac_c_werror_flag" || test ! -s conftest.err - } && test -s conftest$ac_exeext && - $as_test_x conftest$ac_exeext; then + } && test -s conftest$ac_exeext && { + test "$cross_compiling" = yes || + $as_test_x conftest$ac_exeext + }; then eval "$as_ac_var=yes" else - echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 eval "$as_ac_var=no" fi +rm -rf conftest.dSYM rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \ conftest$ac_exeext conftest.$ac_ext fi -ac_res=`eval echo '${'$as_ac_var'}'` - { echo "$as_me:$LINENO: result: $ac_res" >&5 -echo "${ECHO_T}$ac_res" >&6; } -if test `eval echo '${'$as_ac_var'}'` = yes; then +ac_res=`eval 'as_val=${'$as_ac_var'} + $as_echo "$as_val"'` + { $as_echo "$as_me:$LINENO: result: $ac_res" >&5 +$as_echo "$ac_res" >&6; } +as_val=`eval 'as_val=${'$as_ac_var'} + $as_echo "$as_val"'` + if test "x$as_val" = x""yes; then cat >>confdefs.h <<_ACEOF -#define `echo "HAVE_$ac_func" | $as_tr_cpp` 1 +#define `$as_echo "HAVE_$ac_func" | $as_tr_cpp` 1 _ACEOF fi @@ -19476,10 +19965,10 @@ # checks for structures -{ echo "$as_me:$LINENO: checking whether time.h and sys/time.h may both be included" >&5 -echo $ECHO_N "checking whether time.h and sys/time.h may both be included... $ECHO_C" >&6; } +{ $as_echo "$as_me:$LINENO: checking whether time.h and sys/time.h may both be included" >&5 +$as_echo_n "checking whether time.h and sys/time.h may both be included... " >&6; } if test "${ac_cv_header_time+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 + $as_echo_n "(cached) " >&6 else cat >conftest.$ac_ext <<_ACEOF /* confdefs.h. */ @@ -19506,20 +19995,21 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_compile") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { test -z "$ac_c_werror_flag" || test ! -s conftest.err } && test -s conftest.$ac_objext; then ac_cv_header_time=yes else - echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 ac_cv_header_time=no @@ -19527,8 +20017,8 @@ rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext fi -{ echo "$as_me:$LINENO: result: $ac_cv_header_time" >&5 -echo "${ECHO_T}$ac_cv_header_time" >&6; } +{ $as_echo "$as_me:$LINENO: result: $ac_cv_header_time" >&5 +$as_echo "$ac_cv_header_time" >&6; } if test $ac_cv_header_time = yes; then cat >>confdefs.h <<\_ACEOF @@ -19537,10 +20027,10 @@ fi -{ echo "$as_me:$LINENO: checking whether struct tm is in sys/time.h or time.h" >&5 -echo $ECHO_N "checking whether struct tm is in sys/time.h or time.h... $ECHO_C" >&6; } +{ $as_echo "$as_me:$LINENO: checking whether struct tm is in sys/time.h or time.h" >&5 +$as_echo_n "checking whether struct tm is in sys/time.h or time.h... " >&6; } if test "${ac_cv_struct_tm+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 + $as_echo_n "(cached) " >&6 else cat >conftest.$ac_ext <<_ACEOF /* confdefs.h. */ @@ -19556,7 +20046,7 @@ { struct tm tm; int *p = &tm.tm_sec; - return !p; + return !p; ; return 0; } @@ -19567,20 +20057,21 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_compile") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { test -z "$ac_c_werror_flag" || test ! -s conftest.err } && test -s conftest.$ac_objext; then ac_cv_struct_tm=time.h else - echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 ac_cv_struct_tm=sys/time.h @@ -19588,8 +20079,8 @@ rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext fi -{ echo "$as_me:$LINENO: result: $ac_cv_struct_tm" >&5 -echo "${ECHO_T}$ac_cv_struct_tm" >&6; } +{ $as_echo "$as_me:$LINENO: result: $ac_cv_struct_tm" >&5 +$as_echo "$ac_cv_struct_tm" >&6; } if test $ac_cv_struct_tm = sys/time.h; then cat >>confdefs.h <<\_ACEOF @@ -19598,10 +20089,10 @@ fi -{ echo "$as_me:$LINENO: checking for struct tm.tm_zone" >&5 -echo $ECHO_N "checking for struct tm.tm_zone... $ECHO_C" >&6; } +{ $as_echo "$as_me:$LINENO: checking for struct tm.tm_zone" >&5 +$as_echo_n "checking for struct tm.tm_zone... " >&6; } if test "${ac_cv_member_struct_tm_tm_zone+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 + $as_echo_n "(cached) " >&6 else cat >conftest.$ac_ext <<_ACEOF /* confdefs.h. */ @@ -19629,20 +20120,21 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_compile") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { test -z "$ac_c_werror_flag" || test ! -s conftest.err } && test -s conftest.$ac_objext; then ac_cv_member_struct_tm_tm_zone=yes else - echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 cat >conftest.$ac_ext <<_ACEOF @@ -19671,20 +20163,21 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_compile") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { test -z "$ac_c_werror_flag" || test ! -s conftest.err } && test -s conftest.$ac_objext; then ac_cv_member_struct_tm_tm_zone=yes else - echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 ac_cv_member_struct_tm_tm_zone=no @@ -19695,9 +20188,9 @@ rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext fi -{ echo "$as_me:$LINENO: result: $ac_cv_member_struct_tm_tm_zone" >&5 -echo "${ECHO_T}$ac_cv_member_struct_tm_tm_zone" >&6; } -if test $ac_cv_member_struct_tm_tm_zone = yes; then +{ $as_echo "$as_me:$LINENO: result: $ac_cv_member_struct_tm_tm_zone" >&5 +$as_echo "$ac_cv_member_struct_tm_tm_zone" >&6; } +if test "x$ac_cv_member_struct_tm_tm_zone" = x""yes; then cat >>confdefs.h <<_ACEOF #define HAVE_STRUCT_TM_TM_ZONE 1 @@ -19713,10 +20206,10 @@ _ACEOF else - { echo "$as_me:$LINENO: checking whether tzname is declared" >&5 -echo $ECHO_N "checking whether tzname is declared... $ECHO_C" >&6; } + { $as_echo "$as_me:$LINENO: checking whether tzname is declared" >&5 +$as_echo_n "checking whether tzname is declared... " >&6; } if test "${ac_cv_have_decl_tzname+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 + $as_echo_n "(cached) " >&6 else cat >conftest.$ac_ext <<_ACEOF /* confdefs.h. */ @@ -19743,20 +20236,21 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_compile") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { test -z "$ac_c_werror_flag" || test ! -s conftest.err } && test -s conftest.$ac_objext; then ac_cv_have_decl_tzname=yes else - echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 ac_cv_have_decl_tzname=no @@ -19764,9 +20258,9 @@ rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext fi -{ echo "$as_me:$LINENO: result: $ac_cv_have_decl_tzname" >&5 -echo "${ECHO_T}$ac_cv_have_decl_tzname" >&6; } -if test $ac_cv_have_decl_tzname = yes; then +{ $as_echo "$as_me:$LINENO: result: $ac_cv_have_decl_tzname" >&5 +$as_echo "$ac_cv_have_decl_tzname" >&6; } +if test "x$ac_cv_have_decl_tzname" = x""yes; then cat >>confdefs.h <<_ACEOF #define HAVE_DECL_TZNAME 1 @@ -19782,10 +20276,10 @@ fi - { echo "$as_me:$LINENO: checking for tzname" >&5 -echo $ECHO_N "checking for tzname... $ECHO_C" >&6; } + { $as_echo "$as_me:$LINENO: checking for tzname" >&5 +$as_echo_n "checking for tzname... " >&6; } if test "${ac_cv_var_tzname+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 + $as_echo_n "(cached) " >&6 else cat >conftest.$ac_ext <<_ACEOF /* confdefs.h. */ @@ -19812,31 +20306,35 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_link") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { test -z "$ac_c_werror_flag" || test ! -s conftest.err - } && test -s conftest$ac_exeext && - $as_test_x conftest$ac_exeext; then + } && test -s conftest$ac_exeext && { + test "$cross_compiling" = yes || + $as_test_x conftest$ac_exeext + }; then ac_cv_var_tzname=yes else - echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 ac_cv_var_tzname=no fi +rm -rf conftest.dSYM rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \ conftest$ac_exeext conftest.$ac_ext fi -{ echo "$as_me:$LINENO: result: $ac_cv_var_tzname" >&5 -echo "${ECHO_T}$ac_cv_var_tzname" >&6; } +{ $as_echo "$as_me:$LINENO: result: $ac_cv_var_tzname" >&5 +$as_echo "$ac_cv_var_tzname" >&6; } if test $ac_cv_var_tzname = yes; then cat >>confdefs.h <<\_ACEOF @@ -19846,10 +20344,10 @@ fi fi -{ echo "$as_me:$LINENO: checking for struct stat.st_rdev" >&5 -echo $ECHO_N "checking for struct stat.st_rdev... $ECHO_C" >&6; } +{ $as_echo "$as_me:$LINENO: checking for struct stat.st_rdev" >&5 +$as_echo_n "checking for struct stat.st_rdev... " >&6; } if test "${ac_cv_member_struct_stat_st_rdev+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 + $as_echo_n "(cached) " >&6 else cat >conftest.$ac_ext <<_ACEOF /* confdefs.h. */ @@ -19874,20 +20372,21 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_compile") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { test -z "$ac_c_werror_flag" || test ! -s conftest.err } && test -s conftest.$ac_objext; then ac_cv_member_struct_stat_st_rdev=yes else - echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 cat >conftest.$ac_ext <<_ACEOF @@ -19913,20 +20412,21 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_compile") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { test -z "$ac_c_werror_flag" || test ! -s conftest.err } && test -s conftest.$ac_objext; then ac_cv_member_struct_stat_st_rdev=yes else - echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 ac_cv_member_struct_stat_st_rdev=no @@ -19937,9 +20437,9 @@ rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext fi -{ echo "$as_me:$LINENO: result: $ac_cv_member_struct_stat_st_rdev" >&5 -echo "${ECHO_T}$ac_cv_member_struct_stat_st_rdev" >&6; } -if test $ac_cv_member_struct_stat_st_rdev = yes; then +{ $as_echo "$as_me:$LINENO: result: $ac_cv_member_struct_stat_st_rdev" >&5 +$as_echo "$ac_cv_member_struct_stat_st_rdev" >&6; } +if test "x$ac_cv_member_struct_stat_st_rdev" = x""yes; then cat >>confdefs.h <<_ACEOF #define HAVE_STRUCT_STAT_ST_RDEV 1 @@ -19948,10 +20448,10 @@ fi -{ echo "$as_me:$LINENO: checking for struct stat.st_blksize" >&5 -echo $ECHO_N "checking for struct stat.st_blksize... $ECHO_C" >&6; } +{ $as_echo "$as_me:$LINENO: checking for struct stat.st_blksize" >&5 +$as_echo_n "checking for struct stat.st_blksize... " >&6; } if test "${ac_cv_member_struct_stat_st_blksize+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 + $as_echo_n "(cached) " >&6 else cat >conftest.$ac_ext <<_ACEOF /* confdefs.h. */ @@ -19976,20 +20476,21 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_compile") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { test -z "$ac_c_werror_flag" || test ! -s conftest.err } && test -s conftest.$ac_objext; then ac_cv_member_struct_stat_st_blksize=yes else - echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 cat >conftest.$ac_ext <<_ACEOF @@ -20015,20 +20516,21 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_compile") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { test -z "$ac_c_werror_flag" || test ! -s conftest.err } && test -s conftest.$ac_objext; then ac_cv_member_struct_stat_st_blksize=yes else - echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 ac_cv_member_struct_stat_st_blksize=no @@ -20039,9 +20541,9 @@ rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext fi -{ echo "$as_me:$LINENO: result: $ac_cv_member_struct_stat_st_blksize" >&5 -echo "${ECHO_T}$ac_cv_member_struct_stat_st_blksize" >&6; } -if test $ac_cv_member_struct_stat_st_blksize = yes; then +{ $as_echo "$as_me:$LINENO: result: $ac_cv_member_struct_stat_st_blksize" >&5 +$as_echo "$ac_cv_member_struct_stat_st_blksize" >&6; } +if test "x$ac_cv_member_struct_stat_st_blksize" = x""yes; then cat >>confdefs.h <<_ACEOF #define HAVE_STRUCT_STAT_ST_BLKSIZE 1 @@ -20050,10 +20552,10 @@ fi -{ echo "$as_me:$LINENO: checking for struct stat.st_flags" >&5 -echo $ECHO_N "checking for struct stat.st_flags... $ECHO_C" >&6; } +{ $as_echo "$as_me:$LINENO: checking for struct stat.st_flags" >&5 +$as_echo_n "checking for struct stat.st_flags... " >&6; } if test "${ac_cv_member_struct_stat_st_flags+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 + $as_echo_n "(cached) " >&6 else cat >conftest.$ac_ext <<_ACEOF /* confdefs.h. */ @@ -20078,20 +20580,21 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_compile") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { test -z "$ac_c_werror_flag" || test ! -s conftest.err } && test -s conftest.$ac_objext; then ac_cv_member_struct_stat_st_flags=yes else - echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 cat >conftest.$ac_ext <<_ACEOF @@ -20117,20 +20620,21 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_compile") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { test -z "$ac_c_werror_flag" || test ! -s conftest.err } && test -s conftest.$ac_objext; then ac_cv_member_struct_stat_st_flags=yes else - echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 ac_cv_member_struct_stat_st_flags=no @@ -20141,9 +20645,9 @@ rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext fi -{ echo "$as_me:$LINENO: result: $ac_cv_member_struct_stat_st_flags" >&5 -echo "${ECHO_T}$ac_cv_member_struct_stat_st_flags" >&6; } -if test $ac_cv_member_struct_stat_st_flags = yes; then +{ $as_echo "$as_me:$LINENO: result: $ac_cv_member_struct_stat_st_flags" >&5 +$as_echo "$ac_cv_member_struct_stat_st_flags" >&6; } +if test "x$ac_cv_member_struct_stat_st_flags" = x""yes; then cat >>confdefs.h <<_ACEOF #define HAVE_STRUCT_STAT_ST_FLAGS 1 @@ -20152,10 +20656,10 @@ fi -{ echo "$as_me:$LINENO: checking for struct stat.st_gen" >&5 -echo $ECHO_N "checking for struct stat.st_gen... $ECHO_C" >&6; } +{ $as_echo "$as_me:$LINENO: checking for struct stat.st_gen" >&5 +$as_echo_n "checking for struct stat.st_gen... " >&6; } if test "${ac_cv_member_struct_stat_st_gen+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 + $as_echo_n "(cached) " >&6 else cat >conftest.$ac_ext <<_ACEOF /* confdefs.h. */ @@ -20180,20 +20684,21 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_compile") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { test -z "$ac_c_werror_flag" || test ! -s conftest.err } && test -s conftest.$ac_objext; then ac_cv_member_struct_stat_st_gen=yes else - echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 cat >conftest.$ac_ext <<_ACEOF @@ -20219,20 +20724,21 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_compile") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { test -z "$ac_c_werror_flag" || test ! -s conftest.err } && test -s conftest.$ac_objext; then ac_cv_member_struct_stat_st_gen=yes else - echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 ac_cv_member_struct_stat_st_gen=no @@ -20243,9 +20749,9 @@ rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext fi -{ echo "$as_me:$LINENO: result: $ac_cv_member_struct_stat_st_gen" >&5 -echo "${ECHO_T}$ac_cv_member_struct_stat_st_gen" >&6; } -if test $ac_cv_member_struct_stat_st_gen = yes; then +{ $as_echo "$as_me:$LINENO: result: $ac_cv_member_struct_stat_st_gen" >&5 +$as_echo "$ac_cv_member_struct_stat_st_gen" >&6; } +if test "x$ac_cv_member_struct_stat_st_gen" = x""yes; then cat >>confdefs.h <<_ACEOF #define HAVE_STRUCT_STAT_ST_GEN 1 @@ -20254,10 +20760,10 @@ fi -{ echo "$as_me:$LINENO: checking for struct stat.st_birthtime" >&5 -echo $ECHO_N "checking for struct stat.st_birthtime... $ECHO_C" >&6; } +{ $as_echo "$as_me:$LINENO: checking for struct stat.st_birthtime" >&5 +$as_echo_n "checking for struct stat.st_birthtime... " >&6; } if test "${ac_cv_member_struct_stat_st_birthtime+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 + $as_echo_n "(cached) " >&6 else cat >conftest.$ac_ext <<_ACEOF /* confdefs.h. */ @@ -20282,20 +20788,21 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_compile") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { test -z "$ac_c_werror_flag" || test ! -s conftest.err } && test -s conftest.$ac_objext; then ac_cv_member_struct_stat_st_birthtime=yes else - echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 cat >conftest.$ac_ext <<_ACEOF @@ -20321,20 +20828,21 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_compile") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { test -z "$ac_c_werror_flag" || test ! -s conftest.err } && test -s conftest.$ac_objext; then ac_cv_member_struct_stat_st_birthtime=yes else - echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 ac_cv_member_struct_stat_st_birthtime=no @@ -20345,9 +20853,9 @@ rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext fi -{ echo "$as_me:$LINENO: result: $ac_cv_member_struct_stat_st_birthtime" >&5 -echo "${ECHO_T}$ac_cv_member_struct_stat_st_birthtime" >&6; } -if test $ac_cv_member_struct_stat_st_birthtime = yes; then +{ $as_echo "$as_me:$LINENO: result: $ac_cv_member_struct_stat_st_birthtime" >&5 +$as_echo "$ac_cv_member_struct_stat_st_birthtime" >&6; } +if test "x$ac_cv_member_struct_stat_st_birthtime" = x""yes; then cat >>confdefs.h <<_ACEOF #define HAVE_STRUCT_STAT_ST_BIRTHTIME 1 @@ -20356,10 +20864,10 @@ fi -{ echo "$as_me:$LINENO: checking for struct stat.st_blocks" >&5 -echo $ECHO_N "checking for struct stat.st_blocks... $ECHO_C" >&6; } +{ $as_echo "$as_me:$LINENO: checking for struct stat.st_blocks" >&5 +$as_echo_n "checking for struct stat.st_blocks... " >&6; } if test "${ac_cv_member_struct_stat_st_blocks+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 + $as_echo_n "(cached) " >&6 else cat >conftest.$ac_ext <<_ACEOF /* confdefs.h. */ @@ -20384,20 +20892,21 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_compile") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { test -z "$ac_c_werror_flag" || test ! -s conftest.err } && test -s conftest.$ac_objext; then ac_cv_member_struct_stat_st_blocks=yes else - echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 cat >conftest.$ac_ext <<_ACEOF @@ -20423,20 +20932,21 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_compile") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { test -z "$ac_c_werror_flag" || test ! -s conftest.err } && test -s conftest.$ac_objext; then ac_cv_member_struct_stat_st_blocks=yes else - echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 ac_cv_member_struct_stat_st_blocks=no @@ -20447,9 +20957,9 @@ rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext fi -{ echo "$as_me:$LINENO: result: $ac_cv_member_struct_stat_st_blocks" >&5 -echo "${ECHO_T}$ac_cv_member_struct_stat_st_blocks" >&6; } -if test $ac_cv_member_struct_stat_st_blocks = yes; then +{ $as_echo "$as_me:$LINENO: result: $ac_cv_member_struct_stat_st_blocks" >&5 +$as_echo "$ac_cv_member_struct_stat_st_blocks" >&6; } +if test "x$ac_cv_member_struct_stat_st_blocks" = x""yes; then cat >>confdefs.h <<_ACEOF #define HAVE_STRUCT_STAT_ST_BLOCKS 1 @@ -20471,10 +20981,10 @@ -{ echo "$as_me:$LINENO: checking for time.h that defines altzone" >&5 -echo $ECHO_N "checking for time.h that defines altzone... $ECHO_C" >&6; } +{ $as_echo "$as_me:$LINENO: checking for time.h that defines altzone" >&5 +$as_echo_n "checking for time.h that defines altzone... " >&6; } if test "${ac_cv_header_time_altzone+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 + $as_echo_n "(cached) " >&6 else cat >conftest.$ac_ext <<_ACEOF /* confdefs.h. */ @@ -20497,20 +21007,21 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_compile") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { test -z "$ac_c_werror_flag" || test ! -s conftest.err } && test -s conftest.$ac_objext; then ac_cv_header_time_altzone=yes else - echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 ac_cv_header_time_altzone=no @@ -20519,8 +21030,8 @@ rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext fi -{ echo "$as_me:$LINENO: result: $ac_cv_header_time_altzone" >&5 -echo "${ECHO_T}$ac_cv_header_time_altzone" >&6; } +{ $as_echo "$as_me:$LINENO: result: $ac_cv_header_time_altzone" >&5 +$as_echo "$ac_cv_header_time_altzone" >&6; } if test $ac_cv_header_time_altzone = yes; then cat >>confdefs.h <<\_ACEOF @@ -20530,8 +21041,8 @@ fi was_it_defined=no -{ echo "$as_me:$LINENO: checking whether sys/select.h and sys/time.h may both be included" >&5 -echo $ECHO_N "checking whether sys/select.h and sys/time.h may both be included... $ECHO_C" >&6; } +{ $as_echo "$as_me:$LINENO: checking whether sys/select.h and sys/time.h may both be included" >&5 +$as_echo_n "checking whether sys/select.h and sys/time.h may both be included... " >&6; } cat >conftest.$ac_ext <<_ACEOF /* confdefs.h. */ _ACEOF @@ -20557,13 +21068,14 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_compile") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { test -z "$ac_c_werror_flag" || test ! -s conftest.err @@ -20577,20 +21089,20 @@ was_it_defined=yes else - echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 fi rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext -{ echo "$as_me:$LINENO: result: $was_it_defined" >&5 -echo "${ECHO_T}$was_it_defined" >&6; } +{ $as_echo "$as_me:$LINENO: result: $was_it_defined" >&5 +$as_echo "$was_it_defined" >&6; } -{ echo "$as_me:$LINENO: checking for addrinfo" >&5 -echo $ECHO_N "checking for addrinfo... $ECHO_C" >&6; } +{ $as_echo "$as_me:$LINENO: checking for addrinfo" >&5 +$as_echo_n "checking for addrinfo... " >&6; } if test "${ac_cv_struct_addrinfo+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 + $as_echo_n "(cached) " >&6 else cat >conftest.$ac_ext <<_ACEOF /* confdefs.h. */ @@ -20614,20 +21126,21 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_compile") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { test -z "$ac_c_werror_flag" || test ! -s conftest.err } && test -s conftest.$ac_objext; then ac_cv_struct_addrinfo=yes else - echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 ac_cv_struct_addrinfo=no @@ -20636,8 +21149,8 @@ rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext fi -{ echo "$as_me:$LINENO: result: $ac_cv_struct_addrinfo" >&5 -echo "${ECHO_T}$ac_cv_struct_addrinfo" >&6; } +{ $as_echo "$as_me:$LINENO: result: $ac_cv_struct_addrinfo" >&5 +$as_echo "$ac_cv_struct_addrinfo" >&6; } if test $ac_cv_struct_addrinfo = yes; then cat >>confdefs.h <<\_ACEOF @@ -20646,10 +21159,10 @@ fi -{ echo "$as_me:$LINENO: checking for sockaddr_storage" >&5 -echo $ECHO_N "checking for sockaddr_storage... $ECHO_C" >&6; } +{ $as_echo "$as_me:$LINENO: checking for sockaddr_storage" >&5 +$as_echo_n "checking for sockaddr_storage... " >&6; } if test "${ac_cv_struct_sockaddr_storage+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 + $as_echo_n "(cached) " >&6 else cat >conftest.$ac_ext <<_ACEOF /* confdefs.h. */ @@ -20674,20 +21187,21 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_compile") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { test -z "$ac_c_werror_flag" || test ! -s conftest.err } && test -s conftest.$ac_objext; then ac_cv_struct_sockaddr_storage=yes else - echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 ac_cv_struct_sockaddr_storage=no @@ -20696,8 +21210,8 @@ rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext fi -{ echo "$as_me:$LINENO: result: $ac_cv_struct_sockaddr_storage" >&5 -echo "${ECHO_T}$ac_cv_struct_sockaddr_storage" >&6; } +{ $as_echo "$as_me:$LINENO: result: $ac_cv_struct_sockaddr_storage" >&5 +$as_echo "$ac_cv_struct_sockaddr_storage" >&6; } if test $ac_cv_struct_sockaddr_storage = yes; then cat >>confdefs.h <<\_ACEOF @@ -20709,10 +21223,10 @@ # checks for compiler characteristics -{ echo "$as_me:$LINENO: checking whether char is unsigned" >&5 -echo $ECHO_N "checking whether char is unsigned... $ECHO_C" >&6; } +{ $as_echo "$as_me:$LINENO: checking whether char is unsigned" >&5 +$as_echo_n "checking whether char is unsigned... " >&6; } if test "${ac_cv_c_char_unsigned+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 + $as_echo_n "(cached) " >&6 else cat >conftest.$ac_ext <<_ACEOF /* confdefs.h. */ @@ -20737,20 +21251,21 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_compile") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { test -z "$ac_c_werror_flag" || test ! -s conftest.err } && test -s conftest.$ac_objext; then ac_cv_c_char_unsigned=no else - echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 ac_cv_c_char_unsigned=yes @@ -20758,8 +21273,8 @@ rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext fi -{ echo "$as_me:$LINENO: result: $ac_cv_c_char_unsigned" >&5 -echo "${ECHO_T}$ac_cv_c_char_unsigned" >&6; } +{ $as_echo "$as_me:$LINENO: result: $ac_cv_c_char_unsigned" >&5 +$as_echo "$ac_cv_c_char_unsigned" >&6; } if test $ac_cv_c_char_unsigned = yes && test "$GCC" != yes; then cat >>confdefs.h <<\_ACEOF #define __CHAR_UNSIGNED__ 1 @@ -20767,10 +21282,10 @@ fi -{ echo "$as_me:$LINENO: checking for an ANSI C-conforming const" >&5 -echo $ECHO_N "checking for an ANSI C-conforming const... $ECHO_C" >&6; } +{ $as_echo "$as_me:$LINENO: checking for an ANSI C-conforming const" >&5 +$as_echo_n "checking for an ANSI C-conforming const... " >&6; } if test "${ac_cv_c_const+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 + $as_echo_n "(cached) " >&6 else cat >conftest.$ac_ext <<_ACEOF /* confdefs.h. */ @@ -20842,20 +21357,21 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_compile") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { test -z "$ac_c_werror_flag" || test ! -s conftest.err } && test -s conftest.$ac_objext; then ac_cv_c_const=yes else - echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 ac_cv_c_const=no @@ -20863,20 +21379,20 @@ rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext fi -{ echo "$as_me:$LINENO: result: $ac_cv_c_const" >&5 -echo "${ECHO_T}$ac_cv_c_const" >&6; } +{ $as_echo "$as_me:$LINENO: result: $ac_cv_c_const" >&5 +$as_echo "$ac_cv_c_const" >&6; } if test $ac_cv_c_const = no; then cat >>confdefs.h <<\_ACEOF -#define const +#define const /**/ _ACEOF fi works=no -{ echo "$as_me:$LINENO: checking for working volatile" >&5 -echo $ECHO_N "checking for working volatile... $ECHO_C" >&6; } +{ $as_echo "$as_me:$LINENO: checking for working volatile" >&5 +$as_echo_n "checking for working volatile... " >&6; } cat >conftest.$ac_ext <<_ACEOF /* confdefs.h. */ _ACEOF @@ -20898,37 +21414,38 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_compile") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { test -z "$ac_c_werror_flag" || test ! -s conftest.err } && test -s conftest.$ac_objext; then works=yes else - echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 cat >>confdefs.h <<\_ACEOF -#define volatile +#define volatile /**/ _ACEOF fi rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext -{ echo "$as_me:$LINENO: result: $works" >&5 -echo "${ECHO_T}$works" >&6; } +{ $as_echo "$as_me:$LINENO: result: $works" >&5 +$as_echo "$works" >&6; } works=no -{ echo "$as_me:$LINENO: checking for working signed char" >&5 -echo $ECHO_N "checking for working signed char... $ECHO_C" >&6; } +{ $as_echo "$as_me:$LINENO: checking for working signed char" >&5 +$as_echo_n "checking for working signed char... " >&6; } cat >conftest.$ac_ext <<_ACEOF /* confdefs.h. */ _ACEOF @@ -20950,37 +21467,38 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_compile") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { test -z "$ac_c_werror_flag" || test ! -s conftest.err } && test -s conftest.$ac_objext; then works=yes else - echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 cat >>confdefs.h <<\_ACEOF -#define signed +#define signed /**/ _ACEOF fi rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext -{ echo "$as_me:$LINENO: result: $works" >&5 -echo "${ECHO_T}$works" >&6; } +{ $as_echo "$as_me:$LINENO: result: $works" >&5 +$as_echo "$works" >&6; } have_prototypes=no -{ echo "$as_me:$LINENO: checking for prototypes" >&5 -echo $ECHO_N "checking for prototypes... $ECHO_C" >&6; } +{ $as_echo "$as_me:$LINENO: checking for prototypes" >&5 +$as_echo_n "checking for prototypes... " >&6; } cat >conftest.$ac_ext <<_ACEOF /* confdefs.h. */ _ACEOF @@ -21002,13 +21520,14 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_compile") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { test -z "$ac_c_werror_flag" || test ! -s conftest.err @@ -21022,19 +21541,19 @@ have_prototypes=yes else - echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 fi rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext -{ echo "$as_me:$LINENO: result: $have_prototypes" >&5 -echo "${ECHO_T}$have_prototypes" >&6; } +{ $as_echo "$as_me:$LINENO: result: $have_prototypes" >&5 +$as_echo "$have_prototypes" >&6; } works=no -{ echo "$as_me:$LINENO: checking for variable length prototypes and stdarg.h" >&5 -echo $ECHO_N "checking for variable length prototypes and stdarg.h... $ECHO_C" >&6; } +{ $as_echo "$as_me:$LINENO: checking for variable length prototypes and stdarg.h" >&5 +$as_echo_n "checking for variable length prototypes and stdarg.h... " >&6; } cat >conftest.$ac_ext <<_ACEOF /* confdefs.h. */ _ACEOF @@ -21066,13 +21585,14 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_compile") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { test -z "$ac_c_werror_flag" || test ! -s conftest.err @@ -21086,19 +21606,19 @@ works=yes else - echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 fi rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext -{ echo "$as_me:$LINENO: result: $works" >&5 -echo "${ECHO_T}$works" >&6; } +{ $as_echo "$as_me:$LINENO: result: $works" >&5 +$as_echo "$works" >&6; } # check for socketpair -{ echo "$as_me:$LINENO: checking for socketpair" >&5 -echo $ECHO_N "checking for socketpair... $ECHO_C" >&6; } +{ $as_echo "$as_me:$LINENO: checking for socketpair" >&5 +$as_echo_n "checking for socketpair... " >&6; } cat >conftest.$ac_ext <<_ACEOF /* confdefs.h. */ _ACEOF @@ -21123,13 +21643,14 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_compile") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { test -z "$ac_c_werror_flag" || test ! -s conftest.err @@ -21139,22 +21660,22 @@ #define HAVE_SOCKETPAIR 1 _ACEOF - { echo "$as_me:$LINENO: result: yes" >&5 -echo "${ECHO_T}yes" >&6; } + { $as_echo "$as_me:$LINENO: result: yes" >&5 +$as_echo "yes" >&6; } else - echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 - { echo "$as_me:$LINENO: result: no" >&5 -echo "${ECHO_T}no" >&6; } + { $as_echo "$as_me:$LINENO: result: no" >&5 +$as_echo "no" >&6; } fi rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext # check if sockaddr has sa_len member -{ echo "$as_me:$LINENO: checking if sockaddr has sa_len member" >&5 -echo $ECHO_N "checking if sockaddr has sa_len member... $ECHO_C" >&6; } +{ $as_echo "$as_me:$LINENO: checking if sockaddr has sa_len member" >&5 +$as_echo_n "checking if sockaddr has sa_len member... " >&6; } cat >conftest.$ac_ext <<_ACEOF /* confdefs.h. */ _ACEOF @@ -21178,37 +21699,38 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_compile") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { test -z "$ac_c_werror_flag" || test ! -s conftest.err } && test -s conftest.$ac_objext; then - { echo "$as_me:$LINENO: result: yes" >&5 -echo "${ECHO_T}yes" >&6; } + { $as_echo "$as_me:$LINENO: result: yes" >&5 +$as_echo "yes" >&6; } cat >>confdefs.h <<\_ACEOF #define HAVE_SOCKADDR_SA_LEN 1 _ACEOF else - echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 - { echo "$as_me:$LINENO: result: no" >&5 -echo "${ECHO_T}no" >&6; } + { $as_echo "$as_me:$LINENO: result: no" >&5 +$as_echo "no" >&6; } fi rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext va_list_is_array=no -{ echo "$as_me:$LINENO: checking whether va_list is an array" >&5 -echo $ECHO_N "checking whether va_list is an array... $ECHO_C" >&6; } +{ $as_echo "$as_me:$LINENO: checking whether va_list is an array" >&5 +$as_echo_n "checking whether va_list is an array... " >&6; } cat >conftest.$ac_ext <<_ACEOF /* confdefs.h. */ _ACEOF @@ -21236,20 +21758,21 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_compile") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { test -z "$ac_c_werror_flag" || test ! -s conftest.err } && test -s conftest.$ac_objext; then : else - echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 @@ -21263,17 +21786,17 @@ fi rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext -{ echo "$as_me:$LINENO: result: $va_list_is_array" >&5 -echo "${ECHO_T}$va_list_is_array" >&6; } +{ $as_echo "$as_me:$LINENO: result: $va_list_is_array" >&5 +$as_echo "$va_list_is_array" >&6; } # sigh -- gethostbyname_r is a mess; it can have 3, 5 or 6 arguments :-( -{ echo "$as_me:$LINENO: checking for gethostbyname_r" >&5 -echo $ECHO_N "checking for gethostbyname_r... $ECHO_C" >&6; } +{ $as_echo "$as_me:$LINENO: checking for gethostbyname_r" >&5 +$as_echo_n "checking for gethostbyname_r... " >&6; } if test "${ac_cv_func_gethostbyname_r+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 + $as_echo_n "(cached) " >&6 else cat >conftest.$ac_ext <<_ACEOF /* confdefs.h. */ @@ -21326,39 +21849,43 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_link") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { test -z "$ac_c_werror_flag" || test ! -s conftest.err - } && test -s conftest$ac_exeext && - $as_test_x conftest$ac_exeext; then + } && test -s conftest$ac_exeext && { + test "$cross_compiling" = yes || + $as_test_x conftest$ac_exeext + }; then ac_cv_func_gethostbyname_r=yes else - echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 ac_cv_func_gethostbyname_r=no fi +rm -rf conftest.dSYM rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \ conftest$ac_exeext conftest.$ac_ext fi -{ echo "$as_me:$LINENO: result: $ac_cv_func_gethostbyname_r" >&5 -echo "${ECHO_T}$ac_cv_func_gethostbyname_r" >&6; } -if test $ac_cv_func_gethostbyname_r = yes; then +{ $as_echo "$as_me:$LINENO: result: $ac_cv_func_gethostbyname_r" >&5 +$as_echo "$ac_cv_func_gethostbyname_r" >&6; } +if test "x$ac_cv_func_gethostbyname_r" = x""yes; then cat >>confdefs.h <<\_ACEOF #define HAVE_GETHOSTBYNAME_R 1 _ACEOF - { echo "$as_me:$LINENO: checking gethostbyname_r with 6 args" >&5 -echo $ECHO_N "checking gethostbyname_r with 6 args... $ECHO_C" >&6; } + { $as_echo "$as_me:$LINENO: checking gethostbyname_r with 6 args" >&5 +$as_echo_n "checking gethostbyname_r with 6 args... " >&6; } OLD_CFLAGS=$CFLAGS CFLAGS="$CFLAGS $MY_CPPFLAGS $MY_THREAD_CPPFLAGS $MY_CFLAGS" cat >conftest.$ac_ext <<_ACEOF @@ -21392,13 +21919,14 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_compile") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { test -z "$ac_c_werror_flag" || test ! -s conftest.err @@ -21413,18 +21941,18 @@ #define HAVE_GETHOSTBYNAME_R_6_ARG 1 _ACEOF - { echo "$as_me:$LINENO: result: yes" >&5 -echo "${ECHO_T}yes" >&6; } + { $as_echo "$as_me:$LINENO: result: yes" >&5 +$as_echo "yes" >&6; } else - echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 - { echo "$as_me:$LINENO: result: no" >&5 -echo "${ECHO_T}no" >&6; } - { echo "$as_me:$LINENO: checking gethostbyname_r with 5 args" >&5 -echo $ECHO_N "checking gethostbyname_r with 5 args... $ECHO_C" >&6; } + { $as_echo "$as_me:$LINENO: result: no" >&5 +$as_echo "no" >&6; } + { $as_echo "$as_me:$LINENO: checking gethostbyname_r with 5 args" >&5 +$as_echo_n "checking gethostbyname_r with 5 args... " >&6; } cat >conftest.$ac_ext <<_ACEOF /* confdefs.h. */ _ACEOF @@ -21456,13 +21984,14 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_compile") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { test -z "$ac_c_werror_flag" || test ! -s conftest.err @@ -21477,18 +22006,18 @@ #define HAVE_GETHOSTBYNAME_R_5_ARG 1 _ACEOF - { echo "$as_me:$LINENO: result: yes" >&5 -echo "${ECHO_T}yes" >&6; } + { $as_echo "$as_me:$LINENO: result: yes" >&5 +$as_echo "yes" >&6; } else - echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 - { echo "$as_me:$LINENO: result: no" >&5 -echo "${ECHO_T}no" >&6; } - { echo "$as_me:$LINENO: checking gethostbyname_r with 3 args" >&5 -echo $ECHO_N "checking gethostbyname_r with 3 args... $ECHO_C" >&6; } + { $as_echo "$as_me:$LINENO: result: no" >&5 +$as_echo "no" >&6; } + { $as_echo "$as_me:$LINENO: checking gethostbyname_r with 3 args" >&5 +$as_echo_n "checking gethostbyname_r with 3 args... " >&6; } cat >conftest.$ac_ext <<_ACEOF /* confdefs.h. */ _ACEOF @@ -21518,13 +22047,14 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_compile") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { test -z "$ac_c_werror_flag" || test ! -s conftest.err @@ -21539,16 +22069,16 @@ #define HAVE_GETHOSTBYNAME_R_3_ARG 1 _ACEOF - { echo "$as_me:$LINENO: result: yes" >&5 -echo "${ECHO_T}yes" >&6; } + { $as_echo "$as_me:$LINENO: result: yes" >&5 +$as_echo "yes" >&6; } else - echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 - { echo "$as_me:$LINENO: result: no" >&5 -echo "${ECHO_T}no" >&6; } + { $as_echo "$as_me:$LINENO: result: no" >&5 +$as_echo "no" >&6; } fi @@ -21568,11 +22098,11 @@ for ac_func in gethostbyname do -as_ac_var=`echo "ac_cv_func_$ac_func" | $as_tr_sh` -{ echo "$as_me:$LINENO: checking for $ac_func" >&5 -echo $ECHO_N "checking for $ac_func... $ECHO_C" >&6; } +as_ac_var=`$as_echo "ac_cv_func_$ac_func" | $as_tr_sh` +{ $as_echo "$as_me:$LINENO: checking for $ac_func" >&5 +$as_echo_n "checking for $ac_func... " >&6; } if { as_var=$as_ac_var; eval "test \"\${$as_var+set}\" = set"; }; then - echo $ECHO_N "(cached) $ECHO_C" >&6 + $as_echo_n "(cached) " >&6 else cat >conftest.$ac_ext <<_ACEOF /* confdefs.h. */ @@ -21625,35 +22155,42 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_link") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { test -z "$ac_c_werror_flag" || test ! -s conftest.err - } && test -s conftest$ac_exeext && - $as_test_x conftest$ac_exeext; then + } && test -s conftest$ac_exeext && { + test "$cross_compiling" = yes || + $as_test_x conftest$ac_exeext + }; then eval "$as_ac_var=yes" else - echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 eval "$as_ac_var=no" fi +rm -rf conftest.dSYM rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \ conftest$ac_exeext conftest.$ac_ext fi -ac_res=`eval echo '${'$as_ac_var'}'` - { echo "$as_me:$LINENO: result: $ac_res" >&5 -echo "${ECHO_T}$ac_res" >&6; } -if test `eval echo '${'$as_ac_var'}'` = yes; then +ac_res=`eval 'as_val=${'$as_ac_var'} + $as_echo "$as_val"'` + { $as_echo "$as_me:$LINENO: result: $ac_res" >&5 +$as_echo "$ac_res" >&6; } +as_val=`eval 'as_val=${'$as_ac_var'} + $as_echo "$as_val"'` + if test "x$as_val" = x""yes; then cat >>confdefs.h <<_ACEOF -#define `echo "HAVE_$ac_func" | $as_tr_cpp` 1 +#define `$as_echo "HAVE_$ac_func" | $as_tr_cpp` 1 _ACEOF fi @@ -21672,10 +22209,10 @@ # (none yet) # Linux requires this for correct f.p. operations -{ echo "$as_me:$LINENO: checking for __fpu_control" >&5 -echo $ECHO_N "checking for __fpu_control... $ECHO_C" >&6; } +{ $as_echo "$as_me:$LINENO: checking for __fpu_control" >&5 +$as_echo_n "checking for __fpu_control... " >&6; } if test "${ac_cv_func___fpu_control+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 + $as_echo_n "(cached) " >&6 else cat >conftest.$ac_ext <<_ACEOF /* confdefs.h. */ @@ -21728,39 +22265,43 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_link") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { test -z "$ac_c_werror_flag" || test ! -s conftest.err - } && test -s conftest$ac_exeext && - $as_test_x conftest$ac_exeext; then + } && test -s conftest$ac_exeext && { + test "$cross_compiling" = yes || + $as_test_x conftest$ac_exeext + }; then ac_cv_func___fpu_control=yes else - echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 ac_cv_func___fpu_control=no fi +rm -rf conftest.dSYM rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \ conftest$ac_exeext conftest.$ac_ext fi -{ echo "$as_me:$LINENO: result: $ac_cv_func___fpu_control" >&5 -echo "${ECHO_T}$ac_cv_func___fpu_control" >&6; } -if test $ac_cv_func___fpu_control = yes; then +{ $as_echo "$as_me:$LINENO: result: $ac_cv_func___fpu_control" >&5 +$as_echo "$ac_cv_func___fpu_control" >&6; } +if test "x$ac_cv_func___fpu_control" = x""yes; then : else -{ echo "$as_me:$LINENO: checking for __fpu_control in -lieee" >&5 -echo $ECHO_N "checking for __fpu_control in -lieee... $ECHO_C" >&6; } +{ $as_echo "$as_me:$LINENO: checking for __fpu_control in -lieee" >&5 +$as_echo_n "checking for __fpu_control in -lieee... " >&6; } if test "${ac_cv_lib_ieee___fpu_control+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 + $as_echo_n "(cached) " >&6 else ac_check_lib_save_LIBS=$LIBS LIBS="-lieee $LIBS" @@ -21792,33 +22333,37 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_link") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { test -z "$ac_c_werror_flag" || test ! -s conftest.err - } && test -s conftest$ac_exeext && - $as_test_x conftest$ac_exeext; then + } && test -s conftest$ac_exeext && { + test "$cross_compiling" = yes || + $as_test_x conftest$ac_exeext + }; then ac_cv_lib_ieee___fpu_control=yes else - echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 ac_cv_lib_ieee___fpu_control=no fi +rm -rf conftest.dSYM rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \ conftest$ac_exeext conftest.$ac_ext LIBS=$ac_check_lib_save_LIBS fi -{ echo "$as_me:$LINENO: result: $ac_cv_lib_ieee___fpu_control" >&5 -echo "${ECHO_T}$ac_cv_lib_ieee___fpu_control" >&6; } -if test $ac_cv_lib_ieee___fpu_control = yes; then +{ $as_echo "$as_me:$LINENO: result: $ac_cv_lib_ieee___fpu_control" >&5 +$as_echo "$ac_cv_lib_ieee___fpu_control" >&6; } +if test "x$ac_cv_lib_ieee___fpu_control" = x""yes; then cat >>confdefs.h <<_ACEOF #define HAVE_LIBIEEE 1 _ACEOF @@ -21832,8 +22377,8 @@ # Check for --with-fpectl -{ echo "$as_me:$LINENO: checking for --with-fpectl" >&5 -echo $ECHO_N "checking for --with-fpectl... $ECHO_C" >&6; } +{ $as_echo "$as_me:$LINENO: checking for --with-fpectl" >&5 +$as_echo_n "checking for --with-fpectl... " >&6; } # Check whether --with-fpectl was given. if test "${with_fpectl+set}" = set; then @@ -21845,14 +22390,14 @@ #define WANT_SIGFPE_HANDLER 1 _ACEOF - { echo "$as_me:$LINENO: result: yes" >&5 -echo "${ECHO_T}yes" >&6; } -else { echo "$as_me:$LINENO: result: no" >&5 -echo "${ECHO_T}no" >&6; } + { $as_echo "$as_me:$LINENO: result: yes" >&5 +$as_echo "yes" >&6; } +else { $as_echo "$as_me:$LINENO: result: no" >&5 +$as_echo "no" >&6; } fi else - { echo "$as_me:$LINENO: result: no" >&5 -echo "${ECHO_T}no" >&6; } + { $as_echo "$as_me:$LINENO: result: no" >&5 +$as_echo "no" >&6; } fi @@ -21863,53 +22408,53 @@ BeOS) ;; *) LIBM=-lm esac -{ echo "$as_me:$LINENO: checking for --with-libm=STRING" >&5 -echo $ECHO_N "checking for --with-libm=STRING... $ECHO_C" >&6; } +{ $as_echo "$as_me:$LINENO: checking for --with-libm=STRING" >&5 +$as_echo_n "checking for --with-libm=STRING... " >&6; } # Check whether --with-libm was given. if test "${with_libm+set}" = set; then withval=$with_libm; if test "$withval" = no then LIBM= - { echo "$as_me:$LINENO: result: force LIBM empty" >&5 -echo "${ECHO_T}force LIBM empty" >&6; } + { $as_echo "$as_me:$LINENO: result: force LIBM empty" >&5 +$as_echo "force LIBM empty" >&6; } elif test "$withval" != yes then LIBM=$withval - { echo "$as_me:$LINENO: result: set LIBM=\"$withval\"" >&5 -echo "${ECHO_T}set LIBM=\"$withval\"" >&6; } -else { { echo "$as_me:$LINENO: error: proper usage is --with-libm=STRING" >&5 -echo "$as_me: error: proper usage is --with-libm=STRING" >&2;} + { $as_echo "$as_me:$LINENO: result: set LIBM=\"$withval\"" >&5 +$as_echo "set LIBM=\"$withval\"" >&6; } +else { { $as_echo "$as_me:$LINENO: error: proper usage is --with-libm=STRING" >&5 +$as_echo "$as_me: error: proper usage is --with-libm=STRING" >&2;} { (exit 1); exit 1; }; } fi else - { echo "$as_me:$LINENO: result: default LIBM=\"$LIBM\"" >&5 -echo "${ECHO_T}default LIBM=\"$LIBM\"" >&6; } + { $as_echo "$as_me:$LINENO: result: default LIBM=\"$LIBM\"" >&5 +$as_echo "default LIBM=\"$LIBM\"" >&6; } fi # check for --with-libc=... -{ echo "$as_me:$LINENO: checking for --with-libc=STRING" >&5 -echo $ECHO_N "checking for --with-libc=STRING... $ECHO_C" >&6; } +{ $as_echo "$as_me:$LINENO: checking for --with-libc=STRING" >&5 +$as_echo_n "checking for --with-libc=STRING... " >&6; } # Check whether --with-libc was given. if test "${with_libc+set}" = set; then withval=$with_libc; if test "$withval" = no then LIBC= - { echo "$as_me:$LINENO: result: force LIBC empty" >&5 -echo "${ECHO_T}force LIBC empty" >&6; } + { $as_echo "$as_me:$LINENO: result: force LIBC empty" >&5 +$as_echo "force LIBC empty" >&6; } elif test "$withval" != yes then LIBC=$withval - { echo "$as_me:$LINENO: result: set LIBC=\"$withval\"" >&5 -echo "${ECHO_T}set LIBC=\"$withval\"" >&6; } -else { { echo "$as_me:$LINENO: error: proper usage is --with-libc=STRING" >&5 -echo "$as_me: error: proper usage is --with-libc=STRING" >&2;} + { $as_echo "$as_me:$LINENO: result: set LIBC=\"$withval\"" >&5 +$as_echo "set LIBC=\"$withval\"" >&6; } +else { { $as_echo "$as_me:$LINENO: error: proper usage is --with-libc=STRING" >&5 +$as_echo "$as_me: error: proper usage is --with-libc=STRING" >&2;} { (exit 1); exit 1; }; } fi else - { echo "$as_me:$LINENO: result: default LIBC=\"$LIBC\"" >&5 -echo "${ECHO_T}default LIBC=\"$LIBC\"" >&6; } + { $as_echo "$as_me:$LINENO: result: default LIBC=\"$LIBC\"" >&5 +$as_echo "default LIBC=\"$LIBC\"" >&6; } fi @@ -21925,10 +22470,10 @@ # IEEE 754 platforms. On IEEE 754, test should return 1 if rounding # mode is round-to-nearest and double rounding issues are present, and # 0 otherwise. See http://bugs.python.org/issue2937 for more info. -{ echo "$as_me:$LINENO: checking for x87-style double rounding" >&5 -echo $ECHO_N "checking for x87-style double rounding... $ECHO_C" >&6; } +{ $as_echo "$as_me:$LINENO: checking for x87-style double rounding" >&5 +$as_echo_n "checking for x87-style double rounding... " >&6; } if test "${ac_cv_x87_double_rounding+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 + $as_echo_n "(cached) " >&6 else if test "$cross_compiling" = yes; then @@ -21967,37 +22512,40 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_link") 2>&5 ac_status=$? - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { ac_try='./conftest$ac_exeext' { (case "(($ac_try" in *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_try") 2>&5 ac_status=$? - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); }; }; then ac_cv_x87_double_rounding=no else - echo "$as_me: program exited with status $ac_status" >&5 -echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: program exited with status $ac_status" >&5 +$as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 ( exit $ac_status ) ac_cv_x87_double_rounding=yes fi +rm -rf conftest.dSYM rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext conftest.$ac_objext conftest.$ac_ext fi fi -{ echo "$as_me:$LINENO: result: $ac_cv_x87_double_rounding" >&5 -echo "${ECHO_T}$ac_cv_x87_double_rounding" >&6; } +{ $as_echo "$as_me:$LINENO: result: $ac_cv_x87_double_rounding" >&5 +$as_echo "$ac_cv_x87_double_rounding" >&6; } if test "$ac_cv_x87_double_rounding" = yes then @@ -22010,10 +22558,10 @@ # On FreeBSD 6.2, it appears that tanh(-0.) returns 0. instead of # -0. on some architectures. -{ echo "$as_me:$LINENO: checking whether tanh preserves the sign of zero" >&5 -echo $ECHO_N "checking whether tanh preserves the sign of zero... $ECHO_C" >&6; } +{ $as_echo "$as_me:$LINENO: checking whether tanh preserves the sign of zero" >&5 +$as_echo_n "checking whether tanh preserves the sign of zero... " >&6; } if test "${ac_cv_tanh_preserves_zero_sign+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 + $as_echo_n "(cached) " >&6 else if test "$cross_compiling" = yes; then @@ -22044,37 +22592,40 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_link") 2>&5 ac_status=$? - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { ac_try='./conftest$ac_exeext' { (case "(($ac_try" in *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_try") 2>&5 ac_status=$? - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); }; }; then ac_cv_tanh_preserves_zero_sign=yes else - echo "$as_me: program exited with status $ac_status" >&5 -echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: program exited with status $ac_status" >&5 +$as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 ( exit $ac_status ) ac_cv_tanh_preserves_zero_sign=no fi +rm -rf conftest.dSYM rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext conftest.$ac_objext conftest.$ac_ext fi fi -{ echo "$as_me:$LINENO: result: $ac_cv_tanh_preserves_zero_sign" >&5 -echo "${ECHO_T}$ac_cv_tanh_preserves_zero_sign" >&6; } +{ $as_echo "$as_me:$LINENO: result: $ac_cv_tanh_preserves_zero_sign" >&5 +$as_echo "$ac_cv_tanh_preserves_zero_sign" >&6; } if test "$ac_cv_tanh_preserves_zero_sign" = yes then @@ -22094,11 +22645,11 @@ for ac_func in acosh asinh atanh copysign expm1 finite hypot log1p do -as_ac_var=`echo "ac_cv_func_$ac_func" | $as_tr_sh` -{ echo "$as_me:$LINENO: checking for $ac_func" >&5 -echo $ECHO_N "checking for $ac_func... $ECHO_C" >&6; } +as_ac_var=`$as_echo "ac_cv_func_$ac_func" | $as_tr_sh` +{ $as_echo "$as_me:$LINENO: checking for $ac_func" >&5 +$as_echo_n "checking for $ac_func... " >&6; } if { as_var=$as_ac_var; eval "test \"\${$as_var+set}\" = set"; }; then - echo $ECHO_N "(cached) $ECHO_C" >&6 + $as_echo_n "(cached) " >&6 else cat >conftest.$ac_ext <<_ACEOF /* confdefs.h. */ @@ -22151,44 +22702,51 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_link") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { test -z "$ac_c_werror_flag" || test ! -s conftest.err - } && test -s conftest$ac_exeext && - $as_test_x conftest$ac_exeext; then + } && test -s conftest$ac_exeext && { + test "$cross_compiling" = yes || + $as_test_x conftest$ac_exeext + }; then eval "$as_ac_var=yes" else - echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 eval "$as_ac_var=no" fi +rm -rf conftest.dSYM rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \ conftest$ac_exeext conftest.$ac_ext fi -ac_res=`eval echo '${'$as_ac_var'}'` - { echo "$as_me:$LINENO: result: $ac_res" >&5 -echo "${ECHO_T}$ac_res" >&6; } -if test `eval echo '${'$as_ac_var'}'` = yes; then +ac_res=`eval 'as_val=${'$as_ac_var'} + $as_echo "$as_val"'` + { $as_echo "$as_me:$LINENO: result: $ac_res" >&5 +$as_echo "$ac_res" >&6; } +as_val=`eval 'as_val=${'$as_ac_var'} + $as_echo "$as_val"'` + if test "x$as_val" = x""yes; then cat >>confdefs.h <<_ACEOF -#define `echo "HAVE_$ac_func" | $as_tr_cpp` 1 +#define `$as_echo "HAVE_$ac_func" | $as_tr_cpp` 1 _ACEOF fi done -{ echo "$as_me:$LINENO: checking whether isinf is declared" >&5 -echo $ECHO_N "checking whether isinf is declared... $ECHO_C" >&6; } +{ $as_echo "$as_me:$LINENO: checking whether isinf is declared" >&5 +$as_echo_n "checking whether isinf is declared... " >&6; } if test "${ac_cv_have_decl_isinf+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 + $as_echo_n "(cached) " >&6 else cat >conftest.$ac_ext <<_ACEOF /* confdefs.h. */ @@ -22215,20 +22773,21 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_compile") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { test -z "$ac_c_werror_flag" || test ! -s conftest.err } && test -s conftest.$ac_objext; then ac_cv_have_decl_isinf=yes else - echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 ac_cv_have_decl_isinf=no @@ -22236,9 +22795,9 @@ rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext fi -{ echo "$as_me:$LINENO: result: $ac_cv_have_decl_isinf" >&5 -echo "${ECHO_T}$ac_cv_have_decl_isinf" >&6; } -if test $ac_cv_have_decl_isinf = yes; then +{ $as_echo "$as_me:$LINENO: result: $ac_cv_have_decl_isinf" >&5 +$as_echo "$ac_cv_have_decl_isinf" >&6; } +if test "x$ac_cv_have_decl_isinf" = x""yes; then cat >>confdefs.h <<_ACEOF #define HAVE_DECL_ISINF 1 @@ -22252,10 +22811,10 @@ fi -{ echo "$as_me:$LINENO: checking whether isnan is declared" >&5 -echo $ECHO_N "checking whether isnan is declared... $ECHO_C" >&6; } +{ $as_echo "$as_me:$LINENO: checking whether isnan is declared" >&5 +$as_echo_n "checking whether isnan is declared... " >&6; } if test "${ac_cv_have_decl_isnan+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 + $as_echo_n "(cached) " >&6 else cat >conftest.$ac_ext <<_ACEOF /* confdefs.h. */ @@ -22282,20 +22841,21 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_compile") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { test -z "$ac_c_werror_flag" || test ! -s conftest.err } && test -s conftest.$ac_objext; then ac_cv_have_decl_isnan=yes else - echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 ac_cv_have_decl_isnan=no @@ -22303,9 +22863,9 @@ rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext fi -{ echo "$as_me:$LINENO: result: $ac_cv_have_decl_isnan" >&5 -echo "${ECHO_T}$ac_cv_have_decl_isnan" >&6; } -if test $ac_cv_have_decl_isnan = yes; then +{ $as_echo "$as_me:$LINENO: result: $ac_cv_have_decl_isnan" >&5 +$as_echo "$ac_cv_have_decl_isnan" >&6; } +if test "x$ac_cv_have_decl_isnan" = x""yes; then cat >>confdefs.h <<_ACEOF #define HAVE_DECL_ISNAN 1 @@ -22319,10 +22879,10 @@ fi -{ echo "$as_me:$LINENO: checking whether isfinite is declared" >&5 -echo $ECHO_N "checking whether isfinite is declared... $ECHO_C" >&6; } +{ $as_echo "$as_me:$LINENO: checking whether isfinite is declared" >&5 +$as_echo_n "checking whether isfinite is declared... " >&6; } if test "${ac_cv_have_decl_isfinite+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 + $as_echo_n "(cached) " >&6 else cat >conftest.$ac_ext <<_ACEOF /* confdefs.h. */ @@ -22349,20 +22909,21 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_compile") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { test -z "$ac_c_werror_flag" || test ! -s conftest.err } && test -s conftest.$ac_objext; then ac_cv_have_decl_isfinite=yes else - echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 ac_cv_have_decl_isfinite=no @@ -22370,9 +22931,9 @@ rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext fi -{ echo "$as_me:$LINENO: result: $ac_cv_have_decl_isfinite" >&5 -echo "${ECHO_T}$ac_cv_have_decl_isfinite" >&6; } -if test $ac_cv_have_decl_isfinite = yes; then +{ $as_echo "$as_me:$LINENO: result: $ac_cv_have_decl_isfinite" >&5 +$as_echo "$ac_cv_have_decl_isfinite" >&6; } +if test "x$ac_cv_have_decl_isfinite" = x""yes; then cat >>confdefs.h <<_ACEOF #define HAVE_DECL_ISFINITE 1 @@ -22393,17 +22954,17 @@ # check for wchar.h if test "${ac_cv_header_wchar_h+set}" = set; then - { echo "$as_me:$LINENO: checking for wchar.h" >&5 -echo $ECHO_N "checking for wchar.h... $ECHO_C" >&6; } + { $as_echo "$as_me:$LINENO: checking for wchar.h" >&5 +$as_echo_n "checking for wchar.h... " >&6; } if test "${ac_cv_header_wchar_h+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 + $as_echo_n "(cached) " >&6 fi -{ echo "$as_me:$LINENO: result: $ac_cv_header_wchar_h" >&5 -echo "${ECHO_T}$ac_cv_header_wchar_h" >&6; } +{ $as_echo "$as_me:$LINENO: result: $ac_cv_header_wchar_h" >&5 +$as_echo "$ac_cv_header_wchar_h" >&6; } else # Is the header compilable? -{ echo "$as_me:$LINENO: checking wchar.h usability" >&5 -echo $ECHO_N "checking wchar.h usability... $ECHO_C" >&6; } +{ $as_echo "$as_me:$LINENO: checking wchar.h usability" >&5 +$as_echo_n "checking wchar.h usability... " >&6; } cat >conftest.$ac_ext <<_ACEOF /* confdefs.h. */ _ACEOF @@ -22419,32 +22980,33 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_compile") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { test -z "$ac_c_werror_flag" || test ! -s conftest.err } && test -s conftest.$ac_objext; then ac_header_compiler=yes else - echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 ac_header_compiler=no fi rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext -{ echo "$as_me:$LINENO: result: $ac_header_compiler" >&5 -echo "${ECHO_T}$ac_header_compiler" >&6; } +{ $as_echo "$as_me:$LINENO: result: $ac_header_compiler" >&5 +$as_echo "$ac_header_compiler" >&6; } # Is the header present? -{ echo "$as_me:$LINENO: checking wchar.h presence" >&5 -echo $ECHO_N "checking wchar.h presence... $ECHO_C" >&6; } +{ $as_echo "$as_me:$LINENO: checking wchar.h presence" >&5 +$as_echo_n "checking wchar.h presence... " >&6; } cat >conftest.$ac_ext <<_ACEOF /* confdefs.h. */ _ACEOF @@ -22458,51 +23020,52 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_cpp conftest.$ac_ext") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } >/dev/null && { test -z "$ac_c_preproc_warn_flag$ac_c_werror_flag" || test ! -s conftest.err }; then ac_header_preproc=yes else - echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 ac_header_preproc=no fi rm -f conftest.err conftest.$ac_ext -{ echo "$as_me:$LINENO: result: $ac_header_preproc" >&5 -echo "${ECHO_T}$ac_header_preproc" >&6; } +{ $as_echo "$as_me:$LINENO: result: $ac_header_preproc" >&5 +$as_echo "$ac_header_preproc" >&6; } # So? What about this header? case $ac_header_compiler:$ac_header_preproc:$ac_c_preproc_warn_flag in yes:no: ) - { echo "$as_me:$LINENO: WARNING: wchar.h: accepted by the compiler, rejected by the preprocessor!" >&5 -echo "$as_me: WARNING: wchar.h: accepted by the compiler, rejected by the preprocessor!" >&2;} - { echo "$as_me:$LINENO: WARNING: wchar.h: proceeding with the compiler's result" >&5 -echo "$as_me: WARNING: wchar.h: proceeding with the compiler's result" >&2;} + { $as_echo "$as_me:$LINENO: WARNING: wchar.h: accepted by the compiler, rejected by the preprocessor!" >&5 +$as_echo "$as_me: WARNING: wchar.h: accepted by the compiler, rejected by the preprocessor!" >&2;} + { $as_echo "$as_me:$LINENO: WARNING: wchar.h: proceeding with the compiler's result" >&5 +$as_echo "$as_me: WARNING: wchar.h: proceeding with the compiler's result" >&2;} ac_header_preproc=yes ;; no:yes:* ) - { echo "$as_me:$LINENO: WARNING: wchar.h: present but cannot be compiled" >&5 -echo "$as_me: WARNING: wchar.h: present but cannot be compiled" >&2;} - { echo "$as_me:$LINENO: WARNING: wchar.h: check for missing prerequisite headers?" >&5 -echo "$as_me: WARNING: wchar.h: check for missing prerequisite headers?" >&2;} - { echo "$as_me:$LINENO: WARNING: wchar.h: see the Autoconf documentation" >&5 -echo "$as_me: WARNING: wchar.h: see the Autoconf documentation" >&2;} - { echo "$as_me:$LINENO: WARNING: wchar.h: section \"Present But Cannot Be Compiled\"" >&5 -echo "$as_me: WARNING: wchar.h: section \"Present But Cannot Be Compiled\"" >&2;} - { echo "$as_me:$LINENO: WARNING: wchar.h: proceeding with the preprocessor's result" >&5 -echo "$as_me: WARNING: wchar.h: proceeding with the preprocessor's result" >&2;} - { echo "$as_me:$LINENO: WARNING: wchar.h: in the future, the compiler will take precedence" >&5 -echo "$as_me: WARNING: wchar.h: in the future, the compiler will take precedence" >&2;} + { $as_echo "$as_me:$LINENO: WARNING: wchar.h: present but cannot be compiled" >&5 +$as_echo "$as_me: WARNING: wchar.h: present but cannot be compiled" >&2;} + { $as_echo "$as_me:$LINENO: WARNING: wchar.h: check for missing prerequisite headers?" >&5 +$as_echo "$as_me: WARNING: wchar.h: check for missing prerequisite headers?" >&2;} + { $as_echo "$as_me:$LINENO: WARNING: wchar.h: see the Autoconf documentation" >&5 +$as_echo "$as_me: WARNING: wchar.h: see the Autoconf documentation" >&2;} + { $as_echo "$as_me:$LINENO: WARNING: wchar.h: section \"Present But Cannot Be Compiled\"" >&5 +$as_echo "$as_me: WARNING: wchar.h: section \"Present But Cannot Be Compiled\"" >&2;} + { $as_echo "$as_me:$LINENO: WARNING: wchar.h: proceeding with the preprocessor's result" >&5 +$as_echo "$as_me: WARNING: wchar.h: proceeding with the preprocessor's result" >&2;} + { $as_echo "$as_me:$LINENO: WARNING: wchar.h: in the future, the compiler will take precedence" >&5 +$as_echo "$as_me: WARNING: wchar.h: in the future, the compiler will take precedence" >&2;} ( cat <<\_ASBOX ## ------------------------------------------------ ## ## Report this to http://www.python.org/python-bugs ## @@ -22511,18 +23074,18 @@ ) | sed "s/^/$as_me: WARNING: /" >&2 ;; esac -{ echo "$as_me:$LINENO: checking for wchar.h" >&5 -echo $ECHO_N "checking for wchar.h... $ECHO_C" >&6; } +{ $as_echo "$as_me:$LINENO: checking for wchar.h" >&5 +$as_echo_n "checking for wchar.h... " >&6; } if test "${ac_cv_header_wchar_h+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 + $as_echo_n "(cached) " >&6 else ac_cv_header_wchar_h=$ac_header_preproc fi -{ echo "$as_me:$LINENO: result: $ac_cv_header_wchar_h" >&5 -echo "${ECHO_T}$ac_cv_header_wchar_h" >&6; } +{ $as_echo "$as_me:$LINENO: result: $ac_cv_header_wchar_h" >&5 +$as_echo "$ac_cv_header_wchar_h" >&6; } fi -if test $ac_cv_header_wchar_h = yes; then +if test "x$ac_cv_header_wchar_h" = x""yes; then cat >>confdefs.h <<\_ACEOF @@ -22541,69 +23104,14 @@ # determine wchar_t size if test "$wchar_h" = yes then - { echo "$as_me:$LINENO: checking for wchar_t" >&5 -echo $ECHO_N "checking for wchar_t... $ECHO_C" >&6; } -if test "${ac_cv_type_wchar_t+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 -else - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -#include - -typedef wchar_t ac__type_new_; -int -main () -{ -if ((ac__type_new_ *) 0) - return 0; -if (sizeof (ac__type_new_)) - return 0; - ; - return 0; -} -_ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - ac_cv_type_wchar_t=yes -else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - ac_cv_type_wchar_t=no -fi - -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext -fi -{ echo "$as_me:$LINENO: result: $ac_cv_type_wchar_t" >&5 -echo "${ECHO_T}$ac_cv_type_wchar_t" >&6; } - -# The cast to long int works around a bug in the HP C Compiler + # The cast to long int works around a bug in the HP C Compiler # version HP92453-01 B.11.11.23709.GP, which incorrectly rejects # declarations like `int a3[[(sizeof (unsigned char)) >= 0]];'. # This bug is HP SR number 8606223364. -{ echo "$as_me:$LINENO: checking size of wchar_t" >&5 -echo $ECHO_N "checking size of wchar_t... $ECHO_C" >&6; } +{ $as_echo "$as_me:$LINENO: checking size of wchar_t" >&5 +$as_echo_n "checking size of wchar_t... " >&6; } if test "${ac_cv_sizeof_wchar_t+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 + $as_echo_n "(cached) " >&6 else if test "$cross_compiling" = yes; then # Depending upon the size, compute the lo and hi bounds. @@ -22615,11 +23123,10 @@ /* end confdefs.h. */ #include - typedef wchar_t ac__type_sizeof_; int main () { -static int test_array [1 - 2 * !(((long int) (sizeof (ac__type_sizeof_))) >= 0)]; +static int test_array [1 - 2 * !(((long int) (sizeof (wchar_t))) >= 0)]; test_array [0] = 0 ; @@ -22632,13 +23139,14 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_compile") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { test -z "$ac_c_werror_flag" || test ! -s conftest.err @@ -22653,11 +23161,10 @@ /* end confdefs.h. */ #include - typedef wchar_t ac__type_sizeof_; int main () { -static int test_array [1 - 2 * !(((long int) (sizeof (ac__type_sizeof_))) <= $ac_mid)]; +static int test_array [1 - 2 * !(((long int) (sizeof (wchar_t))) <= $ac_mid)]; test_array [0] = 0 ; @@ -22670,20 +23177,21 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_compile") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { test -z "$ac_c_werror_flag" || test ! -s conftest.err } && test -s conftest.$ac_objext; then ac_hi=$ac_mid; break else - echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 ac_lo=`expr $ac_mid + 1` @@ -22697,7 +23205,7 @@ rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext done else - echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 cat >conftest.$ac_ext <<_ACEOF @@ -22708,11 +23216,10 @@ /* end confdefs.h. */ #include - typedef wchar_t ac__type_sizeof_; int main () { -static int test_array [1 - 2 * !(((long int) (sizeof (ac__type_sizeof_))) < 0)]; +static int test_array [1 - 2 * !(((long int) (sizeof (wchar_t))) < 0)]; test_array [0] = 0 ; @@ -22725,13 +23232,14 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_compile") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { test -z "$ac_c_werror_flag" || test ! -s conftest.err @@ -22746,11 +23254,10 @@ /* end confdefs.h. */ #include - typedef wchar_t ac__type_sizeof_; int main () { -static int test_array [1 - 2 * !(((long int) (sizeof (ac__type_sizeof_))) >= $ac_mid)]; +static int test_array [1 - 2 * !(((long int) (sizeof (wchar_t))) >= $ac_mid)]; test_array [0] = 0 ; @@ -22763,20 +23270,21 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_compile") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { test -z "$ac_c_werror_flag" || test ! -s conftest.err } && test -s conftest.$ac_objext; then ac_lo=$ac_mid; break else - echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 ac_hi=`expr '(' $ac_mid ')' - 1` @@ -22790,7 +23298,7 @@ rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext done else - echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 ac_lo= ac_hi= @@ -22811,11 +23319,10 @@ /* end confdefs.h. */ #include - typedef wchar_t ac__type_sizeof_; int main () { -static int test_array [1 - 2 * !(((long int) (sizeof (ac__type_sizeof_))) <= $ac_mid)]; +static int test_array [1 - 2 * !(((long int) (sizeof (wchar_t))) <= $ac_mid)]; test_array [0] = 0 ; @@ -22828,20 +23335,21 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_compile") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { test -z "$ac_c_werror_flag" || test ! -s conftest.err } && test -s conftest.$ac_objext; then ac_hi=$ac_mid else - echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 ac_lo=`expr '(' $ac_mid ')' + 1` @@ -22852,11 +23360,13 @@ case $ac_lo in ?*) ac_cv_sizeof_wchar_t=$ac_lo;; '') if test "$ac_cv_type_wchar_t" = yes; then - { { echo "$as_me:$LINENO: error: cannot compute sizeof (wchar_t) + { { $as_echo "$as_me:$LINENO: error: in \`$ac_pwd':" >&5 +$as_echo "$as_me: error: in \`$ac_pwd':" >&2;} +{ { $as_echo "$as_me:$LINENO: error: cannot compute sizeof (wchar_t) See \`config.log' for more details." >&5 -echo "$as_me: error: cannot compute sizeof (wchar_t) +$as_echo "$as_me: error: cannot compute sizeof (wchar_t) See \`config.log' for more details." >&2;} - { (exit 77); exit 77; }; } + { (exit 77); exit 77; }; }; } else ac_cv_sizeof_wchar_t=0 fi ;; @@ -22870,9 +23380,8 @@ /* end confdefs.h. */ #include - typedef wchar_t ac__type_sizeof_; -static long int longval () { return (long int) (sizeof (ac__type_sizeof_)); } -static unsigned long int ulongval () { return (long int) (sizeof (ac__type_sizeof_)); } +static long int longval () { return (long int) (sizeof (wchar_t)); } +static unsigned long int ulongval () { return (long int) (sizeof (wchar_t)); } #include #include int @@ -22882,20 +23391,22 @@ FILE *f = fopen ("conftest.val", "w"); if (! f) return 1; - if (((long int) (sizeof (ac__type_sizeof_))) < 0) + if (((long int) (sizeof (wchar_t))) < 0) { long int i = longval (); - if (i != ((long int) (sizeof (ac__type_sizeof_)))) + if (i != ((long int) (sizeof (wchar_t)))) return 1; - fprintf (f, "%ld\n", i); + fprintf (f, "%ld", i); } else { unsigned long int i = ulongval (); - if (i != ((long int) (sizeof (ac__type_sizeof_)))) + if (i != ((long int) (sizeof (wchar_t)))) return 1; - fprintf (f, "%lu\n", i); + fprintf (f, "%lu", i); } + /* Do not output a trailing newline, as this causes \r\n confusion + on some platforms. */ return ferror (f) || fclose (f) != 0; ; @@ -22908,43 +23419,48 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_link") 2>&5 ac_status=$? - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { ac_try='./conftest$ac_exeext' { (case "(($ac_try" in *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_try") 2>&5 ac_status=$? - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); }; }; then ac_cv_sizeof_wchar_t=`cat conftest.val` else - echo "$as_me: program exited with status $ac_status" >&5 -echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: program exited with status $ac_status" >&5 +$as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 ( exit $ac_status ) if test "$ac_cv_type_wchar_t" = yes; then - { { echo "$as_me:$LINENO: error: cannot compute sizeof (wchar_t) + { { $as_echo "$as_me:$LINENO: error: in \`$ac_pwd':" >&5 +$as_echo "$as_me: error: in \`$ac_pwd':" >&2;} +{ { $as_echo "$as_me:$LINENO: error: cannot compute sizeof (wchar_t) See \`config.log' for more details." >&5 -echo "$as_me: error: cannot compute sizeof (wchar_t) +$as_echo "$as_me: error: cannot compute sizeof (wchar_t) See \`config.log' for more details." >&2;} - { (exit 77); exit 77; }; } + { (exit 77); exit 77; }; }; } else ac_cv_sizeof_wchar_t=0 fi fi +rm -rf conftest.dSYM rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext conftest.$ac_objext conftest.$ac_ext fi rm -f conftest.val fi -{ echo "$as_me:$LINENO: result: $ac_cv_sizeof_wchar_t" >&5 -echo "${ECHO_T}$ac_cv_sizeof_wchar_t" >&6; } +{ $as_echo "$as_me:$LINENO: result: $ac_cv_sizeof_wchar_t" >&5 +$as_echo "$ac_cv_sizeof_wchar_t" >&6; } @@ -22955,8 +23471,8 @@ fi -{ echo "$as_me:$LINENO: checking for UCS-4 tcl" >&5 -echo $ECHO_N "checking for UCS-4 tcl... $ECHO_C" >&6; } +{ $as_echo "$as_me:$LINENO: checking for UCS-4 tcl" >&5 +$as_echo_n "checking for UCS-4 tcl... " >&6; } have_ucs4_tcl=no cat >conftest.$ac_ext <<_ACEOF /* confdefs.h. */ @@ -22983,13 +23499,14 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_compile") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { test -z "$ac_c_werror_flag" || test ! -s conftest.err @@ -23003,24 +23520,24 @@ have_ucs4_tcl=yes else - echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 fi rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext -{ echo "$as_me:$LINENO: result: $have_ucs4_tcl" >&5 -echo "${ECHO_T}$have_ucs4_tcl" >&6; } +{ $as_echo "$as_me:$LINENO: result: $have_ucs4_tcl" >&5 +$as_echo "$have_ucs4_tcl" >&6; } # check whether wchar_t is signed or not if test "$wchar_h" = yes then # check whether wchar_t is signed or not - { echo "$as_me:$LINENO: checking whether wchar_t is signed" >&5 -echo $ECHO_N "checking whether wchar_t is signed... $ECHO_C" >&6; } + { $as_echo "$as_me:$LINENO: checking whether wchar_t is signed" >&5 +$as_echo_n "checking whether wchar_t is signed... " >&6; } if test "${ac_cv_wchar_t_signed+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 + $as_echo_n "(cached) " >&6 else if test "$cross_compiling" = yes; then @@ -23047,41 +23564,44 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_link") 2>&5 ac_status=$? - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { ac_try='./conftest$ac_exeext' { (case "(($ac_try" in *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_try") 2>&5 ac_status=$? - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); }; }; then ac_cv_wchar_t_signed=yes else - echo "$as_me: program exited with status $ac_status" >&5 -echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: program exited with status $ac_status" >&5 +$as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 ( exit $ac_status ) ac_cv_wchar_t_signed=no fi +rm -rf conftest.dSYM rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext conftest.$ac_objext conftest.$ac_ext fi fi - { echo "$as_me:$LINENO: result: $ac_cv_wchar_t_signed" >&5 -echo "${ECHO_T}$ac_cv_wchar_t_signed" >&6; } + { $as_echo "$as_me:$LINENO: result: $ac_cv_wchar_t_signed" >&5 +$as_echo "$ac_cv_wchar_t_signed" >&6; } fi -{ echo "$as_me:$LINENO: checking what type to use for unicode" >&5 -echo $ECHO_N "checking what type to use for unicode... $ECHO_C" >&6; } +{ $as_echo "$as_me:$LINENO: checking what type to use for unicode" >&5 +$as_echo_n "checking what type to use for unicode... " >&6; } # Check whether --enable-unicode was given. if test "${enable_unicode+set}" = set; then enableval=$enable_unicode; @@ -23116,8 +23636,8 @@ _ACEOF ;; -*) { { echo "$as_me:$LINENO: error: invalid value for --enable-unicode. Use either ucs2 or ucs4 (lowercase)." >&5 -echo "$as_me: error: invalid value for --enable-unicode. Use either ucs2 or ucs4 (lowercase)." >&2;} +*) { { $as_echo "$as_me:$LINENO: error: invalid value for --enable-unicode. Use either ucs2 or ucs4 (lowercase)." >&5 +$as_echo "$as_me: error: invalid value for --enable-unicode. Use either ucs2 or ucs4 (lowercase)." >&2;} { (exit 1); exit 1; }; } ;; esac @@ -23128,74 +23648,220 @@ if test "$enable_unicode" = "no" then UNICODE_OBJS="" - { echo "$as_me:$LINENO: result: not used" >&5 -echo "${ECHO_T}not used" >&6; } + { $as_echo "$as_me:$LINENO: result: not used" >&5 +$as_echo "not used" >&6; } +else + UNICODE_OBJS="Objects/unicodeobject.o Objects/unicodectype.o" + +cat >>confdefs.h <<\_ACEOF +#define Py_USING_UNICODE 1 +_ACEOF + + + # wchar_t is only usable if it maps to an unsigned type + if test "$unicode_size" = "$ac_cv_sizeof_wchar_t" \ + -a "$ac_cv_wchar_t_signed" = "no" + then + PY_UNICODE_TYPE="wchar_t" + +cat >>confdefs.h <<\_ACEOF +#define HAVE_USABLE_WCHAR_T 1 +_ACEOF + + cat >>confdefs.h <<\_ACEOF +#define PY_UNICODE_TYPE wchar_t +_ACEOF + + elif test "$ac_cv_sizeof_short" = "$unicode_size" + then + PY_UNICODE_TYPE="unsigned short" + cat >>confdefs.h <<\_ACEOF +#define PY_UNICODE_TYPE unsigned short +_ACEOF + + elif test "$ac_cv_sizeof_long" = "$unicode_size" + then + PY_UNICODE_TYPE="unsigned long" + cat >>confdefs.h <<\_ACEOF +#define PY_UNICODE_TYPE unsigned long +_ACEOF + + else + PY_UNICODE_TYPE="no type found" + fi + { $as_echo "$as_me:$LINENO: result: $PY_UNICODE_TYPE" >&5 +$as_echo "$PY_UNICODE_TYPE" >&6; } +fi + +# check for endianness + + { $as_echo "$as_me:$LINENO: checking whether byte ordering is bigendian" >&5 +$as_echo_n "checking whether byte ordering is bigendian... " >&6; } +if test "${ac_cv_c_bigendian+set}" = set; then + $as_echo_n "(cached) " >&6 +else + ac_cv_c_bigendian=unknown + # See if we're dealing with a universal compiler. + cat >conftest.$ac_ext <<_ACEOF +/* confdefs.h. */ +_ACEOF +cat confdefs.h >>conftest.$ac_ext +cat >>conftest.$ac_ext <<_ACEOF +/* end confdefs.h. */ +#ifndef __APPLE_CC__ + not a universal capable compiler + #endif + typedef int dummy; + +_ACEOF +rm -f conftest.$ac_objext +if { (ac_try="$ac_compile" +case "(($ac_try" in + *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; + *) ac_try_echo=$ac_try;; +esac +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 + (eval "$ac_compile") 2>conftest.er1 + ac_status=$? + grep -v '^ *+' conftest.er1 >conftest.err + rm -f conftest.er1 + cat conftest.err >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 + (exit $ac_status); } && { + test -z "$ac_c_werror_flag" || + test ! -s conftest.err + } && test -s conftest.$ac_objext; then + + # Check for potential -arch flags. It is not universal unless + # there are some -arch flags. Note that *ppc* also matches + # ppc64. This check is also rather less than ideal. + case "${CC} ${CFLAGS} ${CPPFLAGS} ${LDFLAGS}" in #( + *-arch*ppc*|*-arch*i386*|*-arch*x86_64*) ac_cv_c_bigendian=universal;; + esac +else + $as_echo "$as_me: failed program was:" >&5 +sed 's/^/| /' conftest.$ac_ext >&5 + + +fi + +rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext + if test $ac_cv_c_bigendian = unknown; then + # See if sys/param.h defines the BYTE_ORDER macro. + cat >conftest.$ac_ext <<_ACEOF +/* confdefs.h. */ +_ACEOF +cat confdefs.h >>conftest.$ac_ext +cat >>conftest.$ac_ext <<_ACEOF +/* end confdefs.h. */ +#include + #include + +int +main () +{ +#if ! (defined BYTE_ORDER && defined BIG_ENDIAN \ + && defined LITTLE_ENDIAN && BYTE_ORDER && BIG_ENDIAN \ + && LITTLE_ENDIAN) + bogus endian macros + #endif + + ; + return 0; +} +_ACEOF +rm -f conftest.$ac_objext +if { (ac_try="$ac_compile" +case "(($ac_try" in + *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; + *) ac_try_echo=$ac_try;; +esac +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 + (eval "$ac_compile") 2>conftest.er1 + ac_status=$? + grep -v '^ *+' conftest.er1 >conftest.err + rm -f conftest.er1 + cat conftest.err >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 + (exit $ac_status); } && { + test -z "$ac_c_werror_flag" || + test ! -s conftest.err + } && test -s conftest.$ac_objext; then + # It does; now see whether it defined to BIG_ENDIAN or not. + cat >conftest.$ac_ext <<_ACEOF +/* confdefs.h. */ +_ACEOF +cat confdefs.h >>conftest.$ac_ext +cat >>conftest.$ac_ext <<_ACEOF +/* end confdefs.h. */ +#include + #include + +int +main () +{ +#if BYTE_ORDER != BIG_ENDIAN + not big endian + #endif + + ; + return 0; +} +_ACEOF +rm -f conftest.$ac_objext +if { (ac_try="$ac_compile" +case "(($ac_try" in + *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; + *) ac_try_echo=$ac_try;; +esac +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 + (eval "$ac_compile") 2>conftest.er1 + ac_status=$? + grep -v '^ *+' conftest.er1 >conftest.err + rm -f conftest.er1 + cat conftest.err >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 + (exit $ac_status); } && { + test -z "$ac_c_werror_flag" || + test ! -s conftest.err + } && test -s conftest.$ac_objext; then + ac_cv_c_bigendian=yes else - UNICODE_OBJS="Objects/unicodeobject.o Objects/unicodectype.o" - -cat >>confdefs.h <<\_ACEOF -#define Py_USING_UNICODE 1 -_ACEOF - - - # wchar_t is only usable if it maps to an unsigned type - if test "$unicode_size" = "$ac_cv_sizeof_wchar_t" \ - -a "$ac_cv_wchar_t_signed" = "no" - then - PY_UNICODE_TYPE="wchar_t" - -cat >>confdefs.h <<\_ACEOF -#define HAVE_USABLE_WCHAR_T 1 -_ACEOF + $as_echo "$as_me: failed program was:" >&5 +sed 's/^/| /' conftest.$ac_ext >&5 - cat >>confdefs.h <<\_ACEOF -#define PY_UNICODE_TYPE wchar_t -_ACEOF + ac_cv_c_bigendian=no +fi - elif test "$ac_cv_sizeof_short" = "$unicode_size" - then - PY_UNICODE_TYPE="unsigned short" - cat >>confdefs.h <<\_ACEOF -#define PY_UNICODE_TYPE unsigned short -_ACEOF +rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext +else + $as_echo "$as_me: failed program was:" >&5 +sed 's/^/| /' conftest.$ac_ext >&5 - elif test "$ac_cv_sizeof_long" = "$unicode_size" - then - PY_UNICODE_TYPE="unsigned long" - cat >>confdefs.h <<\_ACEOF -#define PY_UNICODE_TYPE unsigned long -_ACEOF - else - PY_UNICODE_TYPE="no type found" - fi - { echo "$as_me:$LINENO: result: $PY_UNICODE_TYPE" >&5 -echo "${ECHO_T}$PY_UNICODE_TYPE" >&6; } fi -# check for endianness -{ echo "$as_me:$LINENO: checking whether byte ordering is bigendian" >&5 -echo $ECHO_N "checking whether byte ordering is bigendian... $ECHO_C" >&6; } -if test "${ac_cv_c_bigendian+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 -else - # See if sys/param.h defines the BYTE_ORDER macro. -cat >conftest.$ac_ext <<_ACEOF +rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext + fi + if test $ac_cv_c_bigendian = unknown; then + # See if defines _LITTLE_ENDIAN or _BIG_ENDIAN (e.g., Solaris). + cat >conftest.$ac_ext <<_ACEOF /* confdefs.h. */ _ACEOF cat confdefs.h >>conftest.$ac_ext cat >>conftest.$ac_ext <<_ACEOF /* end confdefs.h. */ -#include -#include +#include int main () { -#if ! (defined BYTE_ORDER && defined BIG_ENDIAN && defined LITTLE_ENDIAN \ - && BYTE_ORDER && BIG_ENDIAN && LITTLE_ENDIAN) - bogus endian macros -#endif +#if ! (defined _LITTLE_ENDIAN || defined _BIG_ENDIAN) + bogus endian macros + #endif ; return 0; @@ -23207,33 +23873,33 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_compile") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { test -z "$ac_c_werror_flag" || test ! -s conftest.err } && test -s conftest.$ac_objext; then - # It does; now see whether it defined to BIG_ENDIAN or not. -cat >conftest.$ac_ext <<_ACEOF + # It does; now see whether it defined to _BIG_ENDIAN or not. + cat >conftest.$ac_ext <<_ACEOF /* confdefs.h. */ _ACEOF cat confdefs.h >>conftest.$ac_ext cat >>conftest.$ac_ext <<_ACEOF /* end confdefs.h. */ -#include -#include +#include int main () { -#if BYTE_ORDER != BIG_ENDIAN - not big endian -#endif +#ifndef _BIG_ENDIAN + not big endian + #endif ; return 0; @@ -23245,20 +23911,21 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_compile") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { test -z "$ac_c_werror_flag" || test ! -s conftest.err } && test -s conftest.$ac_objext; then ac_cv_c_bigendian=yes else - echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 ac_cv_c_bigendian=no @@ -23266,29 +23933,44 @@ rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext else - echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 - # It does not; compile a test program. -if test "$cross_compiling" = yes; then - # try to guess the endianness by grepping values into an object file - ac_cv_c_bigendian=unknown - cat >conftest.$ac_ext <<_ACEOF + +fi + +rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext + fi + if test $ac_cv_c_bigendian = unknown; then + # Compile a test program. + if test "$cross_compiling" = yes; then + # Try to guess by grepping values from an object file. + cat >conftest.$ac_ext <<_ACEOF /* confdefs.h. */ _ACEOF cat confdefs.h >>conftest.$ac_ext cat >>conftest.$ac_ext <<_ACEOF /* end confdefs.h. */ -short int ascii_mm[] = { 0x4249, 0x4765, 0x6E44, 0x6961, 0x6E53, 0x7953, 0 }; -short int ascii_ii[] = { 0x694C, 0x5454, 0x656C, 0x6E45, 0x6944, 0x6E61, 0 }; -void _ascii () { char *s = (char *) ascii_mm; s = (char *) ascii_ii; } -short int ebcdic_ii[] = { 0x89D3, 0xE3E3, 0x8593, 0x95C5, 0x89C4, 0x9581, 0 }; -short int ebcdic_mm[] = { 0xC2C9, 0xC785, 0x95C4, 0x8981, 0x95E2, 0xA8E2, 0 }; -void _ebcdic () { char *s = (char *) ebcdic_mm; s = (char *) ebcdic_ii; } +short int ascii_mm[] = + { 0x4249, 0x4765, 0x6E44, 0x6961, 0x6E53, 0x7953, 0 }; + short int ascii_ii[] = + { 0x694C, 0x5454, 0x656C, 0x6E45, 0x6944, 0x6E61, 0 }; + int use_ascii (int i) { + return ascii_mm[i] + ascii_ii[i]; + } + short int ebcdic_ii[] = + { 0x89D3, 0xE3E3, 0x8593, 0x95C5, 0x89C4, 0x9581, 0 }; + short int ebcdic_mm[] = + { 0xC2C9, 0xC785, 0x95C4, 0x8981, 0x95E2, 0xA8E2, 0 }; + int use_ebcdic (int i) { + return ebcdic_mm[i] + ebcdic_ii[i]; + } + extern int foo; + int main () { - _ascii (); _ebcdic (); +return use_ascii (foo) == use_ebcdic (foo); ; return 0; } @@ -23299,30 +23981,31 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_compile") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { test -z "$ac_c_werror_flag" || test ! -s conftest.err } && test -s conftest.$ac_objext; then - if grep BIGenDianSyS conftest.$ac_objext >/dev/null ; then - ac_cv_c_bigendian=yes -fi -if grep LiTTleEnDian conftest.$ac_objext >/dev/null ; then - if test "$ac_cv_c_bigendian" = unknown; then - ac_cv_c_bigendian=no - else - # finding both strings is unlikely to happen, but who knows? - ac_cv_c_bigendian=unknown - fi -fi + if grep BIGenDianSyS conftest.$ac_objext >/dev/null; then + ac_cv_c_bigendian=yes + fi + if grep LiTTleEnDian conftest.$ac_objext >/dev/null ; then + if test "$ac_cv_c_bigendian" = unknown; then + ac_cv_c_bigendian=no + else + # finding both strings is unlikely to happen, but who knows? + ac_cv_c_bigendian=unknown + fi + fi else - echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 @@ -23341,14 +24024,14 @@ main () { - /* Are we little or big endian? From Harbison&Steele. */ - union - { - long int l; - char c[sizeof (long int)]; - } u; - u.l = 1; - return u.c[sizeof (long int) - 1] == 1; + /* Are we little or big endian? From Harbison&Steele. */ + union + { + long int l; + char c[sizeof (long int)]; + } u; + u.l = 1; + return u.c[sizeof (long int) - 1] == 1; ; return 0; @@ -23360,63 +24043,70 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_link") 2>&5 ac_status=$? - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { ac_try='./conftest$ac_exeext' { (case "(($ac_try" in *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_try") 2>&5 ac_status=$? - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); }; }; then ac_cv_c_bigendian=no else - echo "$as_me: program exited with status $ac_status" >&5 -echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: program exited with status $ac_status" >&5 +$as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 ( exit $ac_status ) ac_cv_c_bigendian=yes fi +rm -rf conftest.dSYM rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext conftest.$ac_objext conftest.$ac_ext fi + fi fi - -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext -fi -{ echo "$as_me:$LINENO: result: $ac_cv_c_bigendian" >&5 -echo "${ECHO_T}$ac_cv_c_bigendian" >&6; } -case $ac_cv_c_bigendian in - yes) +{ $as_echo "$as_me:$LINENO: result: $ac_cv_c_bigendian" >&5 +$as_echo "$ac_cv_c_bigendian" >&6; } + case $ac_cv_c_bigendian in #( + yes) + cat >>confdefs.h <<\_ACEOF +#define WORDS_BIGENDIAN 1 +_ACEOF +;; #( + no) + ;; #( + universal) cat >>confdefs.h <<\_ACEOF -#define WORDS_BIGENDIAN 1 +#define AC_APPLE_UNIVERSAL_BUILD 1 _ACEOF - ;; - no) - ;; - *) - { { echo "$as_me:$LINENO: error: unknown endianness -presetting ac_cv_c_bigendian=no (or yes) will help" >&5 -echo "$as_me: error: unknown endianness -presetting ac_cv_c_bigendian=no (or yes) will help" >&2;} + + ;; #( + *) + { { $as_echo "$as_me:$LINENO: error: unknown endianness + presetting ac_cv_c_bigendian=no (or yes) will help" >&5 +$as_echo "$as_me: error: unknown endianness + presetting ac_cv_c_bigendian=no (or yes) will help" >&2;} { (exit 1); exit 1; }; } ;; -esac + esac # Check whether right shifting a negative integer extends the sign bit # or fills with zeros (like the Cray J90, according to Tim Peters). -{ echo "$as_me:$LINENO: checking whether right shift extends the sign bit" >&5 -echo $ECHO_N "checking whether right shift extends the sign bit... $ECHO_C" >&6; } +{ $as_echo "$as_me:$LINENO: checking whether right shift extends the sign bit" >&5 +$as_echo_n "checking whether right shift extends the sign bit... " >&6; } if test "${ac_cv_rshift_extends_sign+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 + $as_echo_n "(cached) " >&6 else if test "$cross_compiling" = yes; then @@ -23441,37 +24131,40 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_link") 2>&5 ac_status=$? - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { ac_try='./conftest$ac_exeext' { (case "(($ac_try" in *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_try") 2>&5 ac_status=$? - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); }; }; then ac_cv_rshift_extends_sign=yes else - echo "$as_me: program exited with status $ac_status" >&5 -echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: program exited with status $ac_status" >&5 +$as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 ( exit $ac_status ) ac_cv_rshift_extends_sign=no fi +rm -rf conftest.dSYM rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext conftest.$ac_objext conftest.$ac_ext fi fi -{ echo "$as_me:$LINENO: result: $ac_cv_rshift_extends_sign" >&5 -echo "${ECHO_T}$ac_cv_rshift_extends_sign" >&6; } +{ $as_echo "$as_me:$LINENO: result: $ac_cv_rshift_extends_sign" >&5 +$as_echo "$ac_cv_rshift_extends_sign" >&6; } if test "$ac_cv_rshift_extends_sign" = no then @@ -23482,10 +24175,10 @@ fi # check for getc_unlocked and related locking functions -{ echo "$as_me:$LINENO: checking for getc_unlocked() and friends" >&5 -echo $ECHO_N "checking for getc_unlocked() and friends... $ECHO_C" >&6; } +{ $as_echo "$as_me:$LINENO: checking for getc_unlocked() and friends" >&5 +$as_echo_n "checking for getc_unlocked() and friends... " >&6; } if test "${ac_cv_have_getc_unlocked+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 + $as_echo_n "(cached) " >&6 else cat >conftest.$ac_ext <<_ACEOF @@ -23514,32 +24207,36 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_link") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { test -z "$ac_c_werror_flag" || test ! -s conftest.err - } && test -s conftest$ac_exeext && - $as_test_x conftest$ac_exeext; then + } && test -s conftest$ac_exeext && { + test "$cross_compiling" = yes || + $as_test_x conftest$ac_exeext + }; then ac_cv_have_getc_unlocked=yes else - echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 ac_cv_have_getc_unlocked=no fi +rm -rf conftest.dSYM rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \ conftest$ac_exeext conftest.$ac_ext fi -{ echo "$as_me:$LINENO: result: $ac_cv_have_getc_unlocked" >&5 -echo "${ECHO_T}$ac_cv_have_getc_unlocked" >&6; } +{ $as_echo "$as_me:$LINENO: result: $ac_cv_have_getc_unlocked" >&5 +$as_echo "$ac_cv_have_getc_unlocked" >&6; } if test "$ac_cv_have_getc_unlocked" = yes then @@ -23557,8 +24254,8 @@ # library. NOTE: Keep the precedence of listed libraries synchronised # with setup.py. py_cv_lib_readline=no -{ echo "$as_me:$LINENO: checking how to link readline libs" >&5 -echo $ECHO_N "checking how to link readline libs... $ECHO_C" >&6; } +{ $as_echo "$as_me:$LINENO: checking how to link readline libs" >&5 +$as_echo_n "checking how to link readline libs... " >&6; } for py_libtermcap in "" ncursesw ncurses curses termcap; do if test -z "$py_libtermcap"; then READLINE_LIBS="-lreadline" @@ -23594,26 +24291,30 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_link") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { test -z "$ac_c_werror_flag" || test ! -s conftest.err - } && test -s conftest$ac_exeext && - $as_test_x conftest$ac_exeext; then + } && test -s conftest$ac_exeext && { + test "$cross_compiling" = yes || + $as_test_x conftest$ac_exeext + }; then py_cv_lib_readline=yes else - echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 fi +rm -rf conftest.dSYM rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \ conftest$ac_exeext conftest.$ac_ext if test $py_cv_lib_readline = yes; then @@ -23623,11 +24324,11 @@ # Uncomment this line if you want to use READINE_LIBS in Makefile or scripts #AC_SUBST([READLINE_LIBS]) if test $py_cv_lib_readline = no; then - { echo "$as_me:$LINENO: result: none" >&5 -echo "${ECHO_T}none" >&6; } + { $as_echo "$as_me:$LINENO: result: none" >&5 +$as_echo "none" >&6; } else - { echo "$as_me:$LINENO: result: $READLINE_LIBS" >&5 -echo "${ECHO_T}$READLINE_LIBS" >&6; } + { $as_echo "$as_me:$LINENO: result: $READLINE_LIBS" >&5 +$as_echo "$READLINE_LIBS" >&6; } cat >>confdefs.h <<\_ACEOF #define HAVE_LIBREADLINE 1 @@ -23636,10 +24337,10 @@ fi # check for readline 2.1 -{ echo "$as_me:$LINENO: checking for rl_callback_handler_install in -lreadline" >&5 -echo $ECHO_N "checking for rl_callback_handler_install in -lreadline... $ECHO_C" >&6; } +{ $as_echo "$as_me:$LINENO: checking for rl_callback_handler_install in -lreadline" >&5 +$as_echo_n "checking for rl_callback_handler_install in -lreadline... " >&6; } if test "${ac_cv_lib_readline_rl_callback_handler_install+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 + $as_echo_n "(cached) " >&6 else ac_check_lib_save_LIBS=$LIBS LIBS="-lreadline $READLINE_LIBS $LIBS" @@ -23671,33 +24372,37 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_link") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { test -z "$ac_c_werror_flag" || test ! -s conftest.err - } && test -s conftest$ac_exeext && - $as_test_x conftest$ac_exeext; then + } && test -s conftest$ac_exeext && { + test "$cross_compiling" = yes || + $as_test_x conftest$ac_exeext + }; then ac_cv_lib_readline_rl_callback_handler_install=yes else - echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 ac_cv_lib_readline_rl_callback_handler_install=no fi +rm -rf conftest.dSYM rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \ conftest$ac_exeext conftest.$ac_ext LIBS=$ac_check_lib_save_LIBS fi -{ echo "$as_me:$LINENO: result: $ac_cv_lib_readline_rl_callback_handler_install" >&5 -echo "${ECHO_T}$ac_cv_lib_readline_rl_callback_handler_install" >&6; } -if test $ac_cv_lib_readline_rl_callback_handler_install = yes; then +{ $as_echo "$as_me:$LINENO: result: $ac_cv_lib_readline_rl_callback_handler_install" >&5 +$as_echo "$ac_cv_lib_readline_rl_callback_handler_install" >&6; } +if test "x$ac_cv_lib_readline_rl_callback_handler_install" = x""yes; then cat >>confdefs.h <<\_ACEOF #define HAVE_RL_CALLBACK 1 @@ -23720,20 +24425,21 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_cpp conftest.$ac_ext") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } >/dev/null && { test -z "$ac_c_preproc_warn_flag$ac_c_werror_flag" || test ! -s conftest.err }; then have_readline=yes else - echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 have_readline=no @@ -23783,10 +24489,10 @@ fi # check for readline 4.0 -{ echo "$as_me:$LINENO: checking for rl_pre_input_hook in -lreadline" >&5 -echo $ECHO_N "checking for rl_pre_input_hook in -lreadline... $ECHO_C" >&6; } +{ $as_echo "$as_me:$LINENO: checking for rl_pre_input_hook in -lreadline" >&5 +$as_echo_n "checking for rl_pre_input_hook in -lreadline... " >&6; } if test "${ac_cv_lib_readline_rl_pre_input_hook+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 + $as_echo_n "(cached) " >&6 else ac_check_lib_save_LIBS=$LIBS LIBS="-lreadline $READLINE_LIBS $LIBS" @@ -23818,33 +24524,37 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_link") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { test -z "$ac_c_werror_flag" || test ! -s conftest.err - } && test -s conftest$ac_exeext && - $as_test_x conftest$ac_exeext; then + } && test -s conftest$ac_exeext && { + test "$cross_compiling" = yes || + $as_test_x conftest$ac_exeext + }; then ac_cv_lib_readline_rl_pre_input_hook=yes else - echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 ac_cv_lib_readline_rl_pre_input_hook=no fi +rm -rf conftest.dSYM rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \ conftest$ac_exeext conftest.$ac_ext LIBS=$ac_check_lib_save_LIBS fi -{ echo "$as_me:$LINENO: result: $ac_cv_lib_readline_rl_pre_input_hook" >&5 -echo "${ECHO_T}$ac_cv_lib_readline_rl_pre_input_hook" >&6; } -if test $ac_cv_lib_readline_rl_pre_input_hook = yes; then +{ $as_echo "$as_me:$LINENO: result: $ac_cv_lib_readline_rl_pre_input_hook" >&5 +$as_echo "$ac_cv_lib_readline_rl_pre_input_hook" >&6; } +if test "x$ac_cv_lib_readline_rl_pre_input_hook" = x""yes; then cat >>confdefs.h <<\_ACEOF #define HAVE_RL_PRE_INPUT_HOOK 1 @@ -23854,10 +24564,10 @@ # also in 4.0 -{ echo "$as_me:$LINENO: checking for rl_completion_display_matches_hook in -lreadline" >&5 -echo $ECHO_N "checking for rl_completion_display_matches_hook in -lreadline... $ECHO_C" >&6; } +{ $as_echo "$as_me:$LINENO: checking for rl_completion_display_matches_hook in -lreadline" >&5 +$as_echo_n "checking for rl_completion_display_matches_hook in -lreadline... " >&6; } if test "${ac_cv_lib_readline_rl_completion_display_matches_hook+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 + $as_echo_n "(cached) " >&6 else ac_check_lib_save_LIBS=$LIBS LIBS="-lreadline $READLINE_LIBS $LIBS" @@ -23889,33 +24599,37 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_link") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { test -z "$ac_c_werror_flag" || test ! -s conftest.err - } && test -s conftest$ac_exeext && - $as_test_x conftest$ac_exeext; then + } && test -s conftest$ac_exeext && { + test "$cross_compiling" = yes || + $as_test_x conftest$ac_exeext + }; then ac_cv_lib_readline_rl_completion_display_matches_hook=yes else - echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 ac_cv_lib_readline_rl_completion_display_matches_hook=no fi +rm -rf conftest.dSYM rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \ conftest$ac_exeext conftest.$ac_ext LIBS=$ac_check_lib_save_LIBS fi -{ echo "$as_me:$LINENO: result: $ac_cv_lib_readline_rl_completion_display_matches_hook" >&5 -echo "${ECHO_T}$ac_cv_lib_readline_rl_completion_display_matches_hook" >&6; } -if test $ac_cv_lib_readline_rl_completion_display_matches_hook = yes; then +{ $as_echo "$as_me:$LINENO: result: $ac_cv_lib_readline_rl_completion_display_matches_hook" >&5 +$as_echo "$ac_cv_lib_readline_rl_completion_display_matches_hook" >&6; } +if test "x$ac_cv_lib_readline_rl_completion_display_matches_hook" = x""yes; then cat >>confdefs.h <<\_ACEOF #define HAVE_RL_COMPLETION_DISPLAY_MATCHES_HOOK 1 @@ -23925,10 +24639,10 @@ # check for readline 4.2 -{ echo "$as_me:$LINENO: checking for rl_completion_matches in -lreadline" >&5 -echo $ECHO_N "checking for rl_completion_matches in -lreadline... $ECHO_C" >&6; } +{ $as_echo "$as_me:$LINENO: checking for rl_completion_matches in -lreadline" >&5 +$as_echo_n "checking for rl_completion_matches in -lreadline... " >&6; } if test "${ac_cv_lib_readline_rl_completion_matches+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 + $as_echo_n "(cached) " >&6 else ac_check_lib_save_LIBS=$LIBS LIBS="-lreadline $READLINE_LIBS $LIBS" @@ -23960,33 +24674,37 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_link") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { test -z "$ac_c_werror_flag" || test ! -s conftest.err - } && test -s conftest$ac_exeext && - $as_test_x conftest$ac_exeext; then + } && test -s conftest$ac_exeext && { + test "$cross_compiling" = yes || + $as_test_x conftest$ac_exeext + }; then ac_cv_lib_readline_rl_completion_matches=yes else - echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 ac_cv_lib_readline_rl_completion_matches=no fi +rm -rf conftest.dSYM rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \ conftest$ac_exeext conftest.$ac_ext LIBS=$ac_check_lib_save_LIBS fi -{ echo "$as_me:$LINENO: result: $ac_cv_lib_readline_rl_completion_matches" >&5 -echo "${ECHO_T}$ac_cv_lib_readline_rl_completion_matches" >&6; } -if test $ac_cv_lib_readline_rl_completion_matches = yes; then +{ $as_echo "$as_me:$LINENO: result: $ac_cv_lib_readline_rl_completion_matches" >&5 +$as_echo "$ac_cv_lib_readline_rl_completion_matches" >&6; } +if test "x$ac_cv_lib_readline_rl_completion_matches" = x""yes; then cat >>confdefs.h <<\_ACEOF #define HAVE_RL_COMPLETION_MATCHES 1 @@ -24009,20 +24727,21 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_cpp conftest.$ac_ext") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } >/dev/null && { test -z "$ac_c_preproc_warn_flag$ac_c_werror_flag" || test ! -s conftest.err }; then have_readline=yes else - echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 have_readline=no @@ -24055,10 +24774,10 @@ # End of readline checks: restore LIBS LIBS=$LIBS_no_readline -{ echo "$as_me:$LINENO: checking for broken nice()" >&5 -echo $ECHO_N "checking for broken nice()... $ECHO_C" >&6; } +{ $as_echo "$as_me:$LINENO: checking for broken nice()" >&5 +$as_echo_n "checking for broken nice()... " >&6; } if test "${ac_cv_broken_nice+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 + $as_echo_n "(cached) " >&6 else if test "$cross_compiling" = yes; then @@ -24086,37 +24805,40 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_link") 2>&5 ac_status=$? - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { ac_try='./conftest$ac_exeext' { (case "(($ac_try" in *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_try") 2>&5 ac_status=$? - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); }; }; then ac_cv_broken_nice=yes else - echo "$as_me: program exited with status $ac_status" >&5 -echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: program exited with status $ac_status" >&5 +$as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 ( exit $ac_status ) ac_cv_broken_nice=no fi +rm -rf conftest.dSYM rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext conftest.$ac_objext conftest.$ac_ext fi fi -{ echo "$as_me:$LINENO: result: $ac_cv_broken_nice" >&5 -echo "${ECHO_T}$ac_cv_broken_nice" >&6; } +{ $as_echo "$as_me:$LINENO: result: $ac_cv_broken_nice" >&5 +$as_echo "$ac_cv_broken_nice" >&6; } if test "$ac_cv_broken_nice" = yes then @@ -24126,8 +24848,8 @@ fi -{ echo "$as_me:$LINENO: checking for broken poll()" >&5 -echo $ECHO_N "checking for broken poll()... $ECHO_C" >&6; } +{ $as_echo "$as_me:$LINENO: checking for broken poll()" >&5 +$as_echo_n "checking for broken poll()... " >&6; } if test "$cross_compiling" = yes; then ac_cv_broken_poll=no else @@ -24169,35 +24891,38 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_link") 2>&5 ac_status=$? - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { ac_try='./conftest$ac_exeext' { (case "(($ac_try" in *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_try") 2>&5 ac_status=$? - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); }; }; then ac_cv_broken_poll=yes else - echo "$as_me: program exited with status $ac_status" >&5 -echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: program exited with status $ac_status" >&5 +$as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 ( exit $ac_status ) ac_cv_broken_poll=no fi +rm -rf conftest.dSYM rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext conftest.$ac_objext conftest.$ac_ext fi -{ echo "$as_me:$LINENO: result: $ac_cv_broken_poll" >&5 -echo "${ECHO_T}$ac_cv_broken_poll" >&6; } +{ $as_echo "$as_me:$LINENO: result: $ac_cv_broken_poll" >&5 +$as_echo "$ac_cv_broken_poll" >&6; } if test "$ac_cv_broken_poll" = yes then @@ -24210,10 +24935,10 @@ # 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[] -{ echo "$as_me:$LINENO: checking for struct tm.tm_zone" >&5 -echo $ECHO_N "checking for struct tm.tm_zone... $ECHO_C" >&6; } +{ $as_echo "$as_me:$LINENO: checking for struct tm.tm_zone" >&5 +$as_echo_n "checking for struct tm.tm_zone... " >&6; } if test "${ac_cv_member_struct_tm_tm_zone+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 + $as_echo_n "(cached) " >&6 else cat >conftest.$ac_ext <<_ACEOF /* confdefs.h. */ @@ -24241,20 +24966,21 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_compile") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { test -z "$ac_c_werror_flag" || test ! -s conftest.err } && test -s conftest.$ac_objext; then ac_cv_member_struct_tm_tm_zone=yes else - echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 cat >conftest.$ac_ext <<_ACEOF @@ -24283,20 +25009,21 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_compile") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { test -z "$ac_c_werror_flag" || test ! -s conftest.err } && test -s conftest.$ac_objext; then ac_cv_member_struct_tm_tm_zone=yes else - echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 ac_cv_member_struct_tm_tm_zone=no @@ -24307,9 +25034,9 @@ rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext fi -{ echo "$as_me:$LINENO: result: $ac_cv_member_struct_tm_tm_zone" >&5 -echo "${ECHO_T}$ac_cv_member_struct_tm_tm_zone" >&6; } -if test $ac_cv_member_struct_tm_tm_zone = yes; then +{ $as_echo "$as_me:$LINENO: result: $ac_cv_member_struct_tm_tm_zone" >&5 +$as_echo "$ac_cv_member_struct_tm_tm_zone" >&6; } +if test "x$ac_cv_member_struct_tm_tm_zone" = x""yes; then cat >>confdefs.h <<_ACEOF #define HAVE_STRUCT_TM_TM_ZONE 1 @@ -24325,10 +25052,10 @@ _ACEOF else - { echo "$as_me:$LINENO: checking whether tzname is declared" >&5 -echo $ECHO_N "checking whether tzname is declared... $ECHO_C" >&6; } + { $as_echo "$as_me:$LINENO: checking whether tzname is declared" >&5 +$as_echo_n "checking whether tzname is declared... " >&6; } if test "${ac_cv_have_decl_tzname+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 + $as_echo_n "(cached) " >&6 else cat >conftest.$ac_ext <<_ACEOF /* confdefs.h. */ @@ -24355,20 +25082,21 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_compile") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { test -z "$ac_c_werror_flag" || test ! -s conftest.err } && test -s conftest.$ac_objext; then ac_cv_have_decl_tzname=yes else - echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 ac_cv_have_decl_tzname=no @@ -24376,9 +25104,9 @@ rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext fi -{ echo "$as_me:$LINENO: result: $ac_cv_have_decl_tzname" >&5 -echo "${ECHO_T}$ac_cv_have_decl_tzname" >&6; } -if test $ac_cv_have_decl_tzname = yes; then +{ $as_echo "$as_me:$LINENO: result: $ac_cv_have_decl_tzname" >&5 +$as_echo "$ac_cv_have_decl_tzname" >&6; } +if test "x$ac_cv_have_decl_tzname" = x""yes; then cat >>confdefs.h <<_ACEOF #define HAVE_DECL_TZNAME 1 @@ -24394,10 +25122,10 @@ fi - { echo "$as_me:$LINENO: checking for tzname" >&5 -echo $ECHO_N "checking for tzname... $ECHO_C" >&6; } + { $as_echo "$as_me:$LINENO: checking for tzname" >&5 +$as_echo_n "checking for tzname... " >&6; } if test "${ac_cv_var_tzname+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 + $as_echo_n "(cached) " >&6 else cat >conftest.$ac_ext <<_ACEOF /* confdefs.h. */ @@ -24424,31 +25152,35 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_link") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { test -z "$ac_c_werror_flag" || test ! -s conftest.err - } && test -s conftest$ac_exeext && - $as_test_x conftest$ac_exeext; then + } && test -s conftest$ac_exeext && { + test "$cross_compiling" = yes || + $as_test_x conftest$ac_exeext + }; then ac_cv_var_tzname=yes else - echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 ac_cv_var_tzname=no fi +rm -rf conftest.dSYM rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \ conftest$ac_exeext conftest.$ac_ext fi -{ echo "$as_me:$LINENO: result: $ac_cv_var_tzname" >&5 -echo "${ECHO_T}$ac_cv_var_tzname" >&6; } +{ $as_echo "$as_me:$LINENO: result: $ac_cv_var_tzname" >&5 +$as_echo "$ac_cv_var_tzname" >&6; } if test $ac_cv_var_tzname = yes; then cat >>confdefs.h <<\_ACEOF @@ -24460,10 +25192,10 @@ # check tzset(3) exists and works like we expect it to -{ echo "$as_me:$LINENO: checking for working tzset()" >&5 -echo $ECHO_N "checking for working tzset()... $ECHO_C" >&6; } +{ $as_echo "$as_me:$LINENO: checking for working tzset()" >&5 +$as_echo_n "checking for working tzset()... " >&6; } if test "${ac_cv_working_tzset+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 + $as_echo_n "(cached) " >&6 else if test "$cross_compiling" = yes; then @@ -24546,37 +25278,40 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_link") 2>&5 ac_status=$? - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { ac_try='./conftest$ac_exeext' { (case "(($ac_try" in *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_try") 2>&5 ac_status=$? - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); }; }; then ac_cv_working_tzset=yes else - echo "$as_me: program exited with status $ac_status" >&5 -echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: program exited with status $ac_status" >&5 +$as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 ( exit $ac_status ) ac_cv_working_tzset=no fi +rm -rf conftest.dSYM rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext conftest.$ac_objext conftest.$ac_ext fi fi -{ echo "$as_me:$LINENO: result: $ac_cv_working_tzset" >&5 -echo "${ECHO_T}$ac_cv_working_tzset" >&6; } +{ $as_echo "$as_me:$LINENO: result: $ac_cv_working_tzset" >&5 +$as_echo "$ac_cv_working_tzset" >&6; } if test "$ac_cv_working_tzset" = yes then @@ -24587,10 +25322,10 @@ fi # Look for subsecond timestamps in struct stat -{ echo "$as_me:$LINENO: checking for tv_nsec in struct stat" >&5 -echo $ECHO_N "checking for tv_nsec in struct stat... $ECHO_C" >&6; } +{ $as_echo "$as_me:$LINENO: checking for tv_nsec in struct stat" >&5 +$as_echo_n "checking for tv_nsec in struct stat... " >&6; } if test "${ac_cv_stat_tv_nsec+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 + $as_echo_n "(cached) " >&6 else cat >conftest.$ac_ext <<_ACEOF /* confdefs.h. */ @@ -24616,20 +25351,21 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_compile") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { test -z "$ac_c_werror_flag" || test ! -s conftest.err } && test -s conftest.$ac_objext; then ac_cv_stat_tv_nsec=yes else - echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 ac_cv_stat_tv_nsec=no @@ -24638,8 +25374,8 @@ rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext fi -{ echo "$as_me:$LINENO: result: $ac_cv_stat_tv_nsec" >&5 -echo "${ECHO_T}$ac_cv_stat_tv_nsec" >&6; } +{ $as_echo "$as_me:$LINENO: result: $ac_cv_stat_tv_nsec" >&5 +$as_echo "$ac_cv_stat_tv_nsec" >&6; } if test "$ac_cv_stat_tv_nsec" = yes then @@ -24650,10 +25386,10 @@ fi # Look for BSD style subsecond timestamps in struct stat -{ echo "$as_me:$LINENO: checking for tv_nsec2 in struct stat" >&5 -echo $ECHO_N "checking for tv_nsec2 in struct stat... $ECHO_C" >&6; } +{ $as_echo "$as_me:$LINENO: checking for tv_nsec2 in struct stat" >&5 +$as_echo_n "checking for tv_nsec2 in struct stat... " >&6; } if test "${ac_cv_stat_tv_nsec2+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 + $as_echo_n "(cached) " >&6 else cat >conftest.$ac_ext <<_ACEOF /* confdefs.h. */ @@ -24679,20 +25415,21 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_compile") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { test -z "$ac_c_werror_flag" || test ! -s conftest.err } && test -s conftest.$ac_objext; then ac_cv_stat_tv_nsec2=yes else - echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 ac_cv_stat_tv_nsec2=no @@ -24701,8 +25438,8 @@ rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext fi -{ echo "$as_me:$LINENO: result: $ac_cv_stat_tv_nsec2" >&5 -echo "${ECHO_T}$ac_cv_stat_tv_nsec2" >&6; } +{ $as_echo "$as_me:$LINENO: result: $ac_cv_stat_tv_nsec2" >&5 +$as_echo "$ac_cv_stat_tv_nsec2" >&6; } if test "$ac_cv_stat_tv_nsec2" = yes then @@ -24713,10 +25450,10 @@ fi # On HP/UX 11.0, mvwdelch is a block with a return statement -{ echo "$as_me:$LINENO: checking whether mvwdelch is an expression" >&5 -echo $ECHO_N "checking whether mvwdelch is an expression... $ECHO_C" >&6; } +{ $as_echo "$as_me:$LINENO: checking whether mvwdelch is an expression" >&5 +$as_echo_n "checking whether mvwdelch is an expression... " >&6; } if test "${ac_cv_mvwdelch_is_expression+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 + $as_echo_n "(cached) " >&6 else cat >conftest.$ac_ext <<_ACEOF /* confdefs.h. */ @@ -24742,20 +25479,21 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_compile") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { test -z "$ac_c_werror_flag" || test ! -s conftest.err } && test -s conftest.$ac_objext; then ac_cv_mvwdelch_is_expression=yes else - echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 ac_cv_mvwdelch_is_expression=no @@ -24764,8 +25502,8 @@ rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext fi -{ echo "$as_me:$LINENO: result: $ac_cv_mvwdelch_is_expression" >&5 -echo "${ECHO_T}$ac_cv_mvwdelch_is_expression" >&6; } +{ $as_echo "$as_me:$LINENO: result: $ac_cv_mvwdelch_is_expression" >&5 +$as_echo "$ac_cv_mvwdelch_is_expression" >&6; } if test "$ac_cv_mvwdelch_is_expression" = yes then @@ -24776,10 +25514,10 @@ fi -{ echo "$as_me:$LINENO: checking whether WINDOW has _flags" >&5 -echo $ECHO_N "checking whether WINDOW has _flags... $ECHO_C" >&6; } +{ $as_echo "$as_me:$LINENO: checking whether WINDOW has _flags" >&5 +$as_echo_n "checking whether WINDOW has _flags... " >&6; } if test "${ac_cv_window_has_flags+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 + $as_echo_n "(cached) " >&6 else cat >conftest.$ac_ext <<_ACEOF /* confdefs.h. */ @@ -24805,20 +25543,21 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_compile") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { test -z "$ac_c_werror_flag" || test ! -s conftest.err } && test -s conftest.$ac_objext; then ac_cv_window_has_flags=yes else - echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 ac_cv_window_has_flags=no @@ -24827,8 +25566,8 @@ rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext fi -{ echo "$as_me:$LINENO: result: $ac_cv_window_has_flags" >&5 -echo "${ECHO_T}$ac_cv_window_has_flags" >&6; } +{ $as_echo "$as_me:$LINENO: result: $ac_cv_window_has_flags" >&5 +$as_echo "$ac_cv_window_has_flags" >&6; } if test "$ac_cv_window_has_flags" = yes @@ -24840,8 +25579,8 @@ fi -{ echo "$as_me:$LINENO: checking for is_term_resized" >&5 -echo $ECHO_N "checking for is_term_resized... $ECHO_C" >&6; } +{ $as_echo "$as_me:$LINENO: checking for is_term_resized" >&5 +$as_echo_n "checking for is_term_resized... " >&6; } cat >conftest.$ac_ext <<_ACEOF /* confdefs.h. */ _ACEOF @@ -24863,13 +25602,14 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_compile") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { test -z "$ac_c_werror_flag" || test ! -s conftest.err @@ -24879,21 +25619,21 @@ #define HAVE_CURSES_IS_TERM_RESIZED 1 _ACEOF - { echo "$as_me:$LINENO: result: yes" >&5 -echo "${ECHO_T}yes" >&6; } + { $as_echo "$as_me:$LINENO: result: yes" >&5 +$as_echo "yes" >&6; } else - echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 - { echo "$as_me:$LINENO: result: no" >&5 -echo "${ECHO_T}no" >&6; } + { $as_echo "$as_me:$LINENO: result: no" >&5 +$as_echo "no" >&6; } fi rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext -{ echo "$as_me:$LINENO: checking for resize_term" >&5 -echo $ECHO_N "checking for resize_term... $ECHO_C" >&6; } +{ $as_echo "$as_me:$LINENO: checking for resize_term" >&5 +$as_echo_n "checking for resize_term... " >&6; } cat >conftest.$ac_ext <<_ACEOF /* confdefs.h. */ _ACEOF @@ -24915,13 +25655,14 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_compile") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { test -z "$ac_c_werror_flag" || test ! -s conftest.err @@ -24931,21 +25672,21 @@ #define HAVE_CURSES_RESIZE_TERM 1 _ACEOF - { echo "$as_me:$LINENO: result: yes" >&5 -echo "${ECHO_T}yes" >&6; } + { $as_echo "$as_me:$LINENO: result: yes" >&5 +$as_echo "yes" >&6; } else - echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 - { echo "$as_me:$LINENO: result: no" >&5 -echo "${ECHO_T}no" >&6; } + { $as_echo "$as_me:$LINENO: result: no" >&5 +$as_echo "no" >&6; } fi rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext -{ echo "$as_me:$LINENO: checking for resizeterm" >&5 -echo $ECHO_N "checking for resizeterm... $ECHO_C" >&6; } +{ $as_echo "$as_me:$LINENO: checking for resizeterm" >&5 +$as_echo_n "checking for resizeterm... " >&6; } cat >conftest.$ac_ext <<_ACEOF /* confdefs.h. */ _ACEOF @@ -24967,13 +25708,14 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_compile") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { test -z "$ac_c_werror_flag" || test ! -s conftest.err @@ -24983,61 +25725,63 @@ #define HAVE_CURSES_RESIZETERM 1 _ACEOF - { echo "$as_me:$LINENO: result: yes" >&5 -echo "${ECHO_T}yes" >&6; } + { $as_echo "$as_me:$LINENO: result: yes" >&5 +$as_echo "yes" >&6; } else - echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 - { echo "$as_me:$LINENO: result: no" >&5 -echo "${ECHO_T}no" >&6; } + { $as_echo "$as_me:$LINENO: result: no" >&5 +$as_echo "no" >&6; } fi rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext -{ echo "$as_me:$LINENO: checking for /dev/ptmx" >&5 -echo $ECHO_N "checking for /dev/ptmx... $ECHO_C" >&6; } +{ $as_echo "$as_me:$LINENO: checking for /dev/ptmx" >&5 +$as_echo_n "checking for /dev/ptmx... " >&6; } if test -r /dev/ptmx then - { echo "$as_me:$LINENO: result: yes" >&5 -echo "${ECHO_T}yes" >&6; } + { $as_echo "$as_me:$LINENO: result: yes" >&5 +$as_echo "yes" >&6; } cat >>confdefs.h <<\_ACEOF #define HAVE_DEV_PTMX 1 _ACEOF else - { echo "$as_me:$LINENO: result: no" >&5 -echo "${ECHO_T}no" >&6; } + { $as_echo "$as_me:$LINENO: result: no" >&5 +$as_echo "no" >&6; } fi -{ echo "$as_me:$LINENO: checking for /dev/ptc" >&5 -echo $ECHO_N "checking for /dev/ptc... $ECHO_C" >&6; } +{ $as_echo "$as_me:$LINENO: checking for /dev/ptc" >&5 +$as_echo_n "checking for /dev/ptc... " >&6; } if test -r /dev/ptc then - { echo "$as_me:$LINENO: result: yes" >&5 -echo "${ECHO_T}yes" >&6; } + { $as_echo "$as_me:$LINENO: result: yes" >&5 +$as_echo "yes" >&6; } cat >>confdefs.h <<\_ACEOF #define HAVE_DEV_PTC 1 _ACEOF else - { echo "$as_me:$LINENO: result: no" >&5 -echo "${ECHO_T}no" >&6; } + { $as_echo "$as_me:$LINENO: result: no" >&5 +$as_echo "no" >&6; } fi -{ echo "$as_me:$LINENO: checking for %zd printf() format support" >&5 -echo $ECHO_N "checking for %zd printf() format support... $ECHO_C" >&6; } +{ $as_echo "$as_me:$LINENO: checking for %zd printf() format support" >&5 +$as_echo_n "checking for %zd printf() format support... " >&6; } if test "$cross_compiling" = yes; then - { { echo "$as_me:$LINENO: error: cannot run test program while cross compiling + { { $as_echo "$as_me:$LINENO: error: in \`$ac_pwd':" >&5 +$as_echo "$as_me: error: in \`$ac_pwd':" >&2;} +{ { $as_echo "$as_me:$LINENO: error: cannot run test program while cross compiling See \`config.log' for more details." >&5 -echo "$as_me: error: cannot run test program while cross compiling +$as_echo "$as_me: error: cannot run test program while cross compiling See \`config.log' for more details." >&2;} - { (exit 1); exit 1; }; } + { (exit 1); exit 1; }; }; } else cat >conftest.$ac_ext <<_ACEOF /* confdefs.h. */ @@ -25086,47 +25830,51 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_link") 2>&5 ac_status=$? - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { ac_try='./conftest$ac_exeext' { (case "(($ac_try" in *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_try") 2>&5 ac_status=$? - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); }; }; then - { echo "$as_me:$LINENO: result: yes" >&5 -echo "${ECHO_T}yes" >&6; } + { $as_echo "$as_me:$LINENO: result: yes" >&5 +$as_echo "yes" >&6; } cat >>confdefs.h <<\_ACEOF #define PY_FORMAT_SIZE_T "z" _ACEOF else - echo "$as_me: program exited with status $ac_status" >&5 -echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: program exited with status $ac_status" >&5 +$as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 ( exit $ac_status ) -{ echo "$as_me:$LINENO: result: no" >&5 -echo "${ECHO_T}no" >&6; } +{ $as_echo "$as_me:$LINENO: result: no" >&5 +$as_echo "no" >&6; } fi +rm -rf conftest.dSYM rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext conftest.$ac_objext conftest.$ac_ext fi -{ echo "$as_me:$LINENO: checking for socklen_t" >&5 -echo $ECHO_N "checking for socklen_t... $ECHO_C" >&6; } +{ $as_echo "$as_me:$LINENO: checking for socklen_t" >&5 +$as_echo_n "checking for socklen_t... " >&6; } if test "${ac_cv_type_socklen_t+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 + $as_echo_n "(cached) " >&6 else - cat >conftest.$ac_ext <<_ACEOF + ac_cv_type_socklen_t=no +cat >conftest.$ac_ext <<_ACEOF /* confdefs.h. */ _ACEOF cat confdefs.h >>conftest.$ac_ext @@ -25141,14 +25889,53 @@ #endif -typedef socklen_t ac__type_new_; int main () { -if ((ac__type_new_ *) 0) - return 0; -if (sizeof (ac__type_new_)) +if (sizeof (socklen_t)) + return 0; + ; return 0; +} +_ACEOF +rm -f conftest.$ac_objext +if { (ac_try="$ac_compile" +case "(($ac_try" in + *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; + *) ac_try_echo=$ac_try;; +esac +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 + (eval "$ac_compile") 2>conftest.er1 + ac_status=$? + grep -v '^ *+' conftest.er1 >conftest.err + rm -f conftest.er1 + cat conftest.err >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 + (exit $ac_status); } && { + test -z "$ac_c_werror_flag" || + test ! -s conftest.err + } && test -s conftest.$ac_objext; then + cat >conftest.$ac_ext <<_ACEOF +/* confdefs.h. */ +_ACEOF +cat confdefs.h >>conftest.$ac_ext +cat >>conftest.$ac_ext <<_ACEOF +/* end confdefs.h. */ + +#ifdef HAVE_SYS_TYPES_H +#include +#endif +#ifdef HAVE_SYS_SOCKET_H +#include +#endif + + +int +main () +{ +if (sizeof ((socklen_t))) + return 0; ; return 0; } @@ -25159,30 +25946,39 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_compile") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { test -z "$ac_c_werror_flag" || test ! -s conftest.err } && test -s conftest.$ac_objext; then - ac_cv_type_socklen_t=yes + : +else + $as_echo "$as_me: failed program was:" >&5 +sed 's/^/| /' conftest.$ac_ext >&5 + + ac_cv_type_socklen_t=yes +fi + +rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext else - echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 - ac_cv_type_socklen_t=no + fi rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext fi -{ echo "$as_me:$LINENO: result: $ac_cv_type_socklen_t" >&5 -echo "${ECHO_T}$ac_cv_type_socklen_t" >&6; } -if test $ac_cv_type_socklen_t = yes; then +{ $as_echo "$as_me:$LINENO: result: $ac_cv_type_socklen_t" >&5 +$as_echo "$ac_cv_type_socklen_t" >&6; } +if test "x$ac_cv_type_socklen_t" = x""yes; then : else @@ -25209,15 +26005,15 @@ SRCDIRS="Parser Grammar Objects Python Modules Mac" -{ echo "$as_me:$LINENO: checking for build directories" >&5 -echo $ECHO_N "checking for build directories... $ECHO_C" >&6; } +{ $as_echo "$as_me:$LINENO: checking for build directories" >&5 +$as_echo_n "checking for build directories... " >&6; } for dir in $SRCDIRS; do if test ! -d $dir; then mkdir $dir fi done -{ echo "$as_me:$LINENO: result: done" >&5 -echo "${ECHO_T}done" >&6; } +{ $as_echo "$as_me:$LINENO: result: done" >&5 +$as_echo "done" >&6; } # generate output files ac_config_files="$ac_config_files Makefile.pre Modules/Setup.config" @@ -25249,11 +26045,12 @@ case $ac_val in #( *${as_nl}*) case $ac_var in #( - *_cv_*) { echo "$as_me:$LINENO: WARNING: Cache variable $ac_var contains a newline." >&5 -echo "$as_me: WARNING: Cache variable $ac_var contains a newline." >&2;} ;; + *_cv_*) { $as_echo "$as_me:$LINENO: WARNING: cache variable $ac_var contains a newline" >&5 +$as_echo "$as_me: WARNING: cache variable $ac_var contains a newline" >&2;} ;; esac case $ac_var in #( _ | IFS | as_nl) ;; #( + BASH_ARGV | BASH_SOURCE) eval $ac_var= ;; #( *) $as_unset $ac_var ;; esac ;; esac @@ -25286,12 +26083,12 @@ if diff "$cache_file" confcache >/dev/null 2>&1; then :; else if test -w "$cache_file"; then test "x$cache_file" != "x/dev/null" && - { echo "$as_me:$LINENO: updating cache $cache_file" >&5 -echo "$as_me: updating cache $cache_file" >&6;} + { $as_echo "$as_me:$LINENO: updating cache $cache_file" >&5 +$as_echo "$as_me: updating cache $cache_file" >&6;} cat confcache >$cache_file else - { echo "$as_me:$LINENO: not updating unwritable cache $cache_file" >&5 -echo "$as_me: not updating unwritable cache $cache_file" >&6;} + { $as_echo "$as_me:$LINENO: not updating unwritable cache $cache_file" >&5 +$as_echo "$as_me: not updating unwritable cache $cache_file" >&6;} fi fi rm -f confcache @@ -25307,7 +26104,7 @@ for ac_i in : $LIBOBJS; do test "x$ac_i" = x: && continue # 1. Remove the extension, and $U if already installed. ac_script='s/\$U\././;s/\.o$//;s/\.obj$//' - ac_i=`echo "$ac_i" | sed "$ac_script"` + ac_i=`$as_echo "$ac_i" | sed "$ac_script"` # 2. Prepend LIBOBJDIR. When used with automake>=1.10 LIBOBJDIR # will be set to the directory where LIBOBJS objects are built. ac_libobjs="$ac_libobjs \${LIBOBJDIR}$ac_i\$U.$ac_objext" @@ -25319,12 +26116,14 @@ + : ${CONFIG_STATUS=./config.status} +ac_write_fail=0 ac_clean_files_save=$ac_clean_files ac_clean_files="$ac_clean_files $CONFIG_STATUS" -{ echo "$as_me:$LINENO: creating $CONFIG_STATUS" >&5 -echo "$as_me: creating $CONFIG_STATUS" >&6;} -cat >$CONFIG_STATUS <<_ACEOF +{ $as_echo "$as_me:$LINENO: creating $CONFIG_STATUS" >&5 +$as_echo "$as_me: creating $CONFIG_STATUS" >&6;} +cat >$CONFIG_STATUS <<_ACEOF || ac_write_fail=1 #! $SHELL # Generated by $as_me. # Run this file to recreate the current configuration. @@ -25337,7 +26136,7 @@ SHELL=\${CONFIG_SHELL-$SHELL} _ACEOF -cat >>$CONFIG_STATUS <<\_ACEOF +cat >>$CONFIG_STATUS <<\_ACEOF || ac_write_fail=1 ## --------------------- ## ## M4sh Initialization. ## ## --------------------- ## @@ -25347,7 +26146,7 @@ if test -n "${ZSH_VERSION+set}" && (emulate sh) >/dev/null 2>&1; then emulate sh NULLCMD=: - # Zsh 3.x and 4.x performs word splitting on ${1+"$@"}, which + # Pre-4.2 versions of Zsh do word splitting on ${1+"$@"}, which # is contrary to our usage. Disable this feature. alias -g '${1+"$@"}'='"$@"' setopt NO_GLOB_SUBST @@ -25369,17 +26168,45 @@ as_cr_digits='0123456789' as_cr_alnum=$as_cr_Letters$as_cr_digits -# The user is always right. -if test "${PATH_SEPARATOR+set}" != set; then - echo "#! /bin/sh" >conf$$.sh - echo "exit 0" >>conf$$.sh - chmod +x conf$$.sh - if (PATH="/nonexistent;."; conf$$.sh) >/dev/null 2>&1; then - PATH_SEPARATOR=';' +as_nl=' +' +export as_nl +# Printing a long string crashes Solaris 7 /usr/bin/printf. +as_echo='\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\' +as_echo=$as_echo$as_echo$as_echo$as_echo$as_echo +as_echo=$as_echo$as_echo$as_echo$as_echo$as_echo$as_echo +if (test "X`printf %s $as_echo`" = "X$as_echo") 2>/dev/null; then + as_echo='printf %s\n' + as_echo_n='printf %s' +else + if test "X`(/usr/ucb/echo -n -n $as_echo) 2>/dev/null`" = "X-n $as_echo"; then + as_echo_body='eval /usr/ucb/echo -n "$1$as_nl"' + as_echo_n='/usr/ucb/echo -n' else - PATH_SEPARATOR=: + as_echo_body='eval expr "X$1" : "X\\(.*\\)"' + as_echo_n_body='eval + arg=$1; + case $arg in + *"$as_nl"*) + expr "X$arg" : "X\\(.*\\)$as_nl"; + arg=`expr "X$arg" : ".*$as_nl\\(.*\\)"`;; + esac; + expr "X$arg" : "X\\(.*\\)" | tr -d "$as_nl" + ' + export as_echo_n_body + as_echo_n='sh -c $as_echo_n_body as_echo' fi - rm -f conf$$.sh + export as_echo_body + as_echo='sh -c $as_echo_body as_echo' +fi + +# The user is always right. +if test "${PATH_SEPARATOR+set}" != set; then + PATH_SEPARATOR=: + (PATH='/bin;/bin'; FPATH=$PATH; sh -c :) >/dev/null 2>&1 && { + (PATH='/bin:/bin'; FPATH=$PATH; sh -c :) >/dev/null 2>&1 || + PATH_SEPARATOR=';' + } fi # Support unset when possible. @@ -25395,8 +26222,6 @@ # there to prevent editors from complaining about space-tab. # (If _AS_PATH_WALK were called with IFS unset, it would disable word # splitting by setting IFS to empty value.) -as_nl=' -' IFS=" "" $as_nl" # Find who we are. Look in the path if we contain no directory separator. @@ -25419,7 +26244,7 @@ as_myself=$0 fi if test ! -f "$as_myself"; then - echo "$as_myself: error: cannot find myself; rerun with an absolute file name" >&2 + $as_echo "$as_myself: error: cannot find myself; rerun with an absolute file name" >&2 { (exit 1); exit 1; } fi @@ -25432,17 +26257,10 @@ PS4='+ ' # NLS nuisances. -for as_var in \ - LANG LANGUAGE LC_ADDRESS LC_ALL LC_COLLATE LC_CTYPE LC_IDENTIFICATION \ - LC_MEASUREMENT LC_MESSAGES LC_MONETARY LC_NAME LC_NUMERIC LC_PAPER \ - LC_TELEPHONE LC_TIME -do - if (set +x; test -z "`(eval $as_var=C; export $as_var) 2>&1`"); then - eval $as_var=C; export $as_var - else - ($as_unset $as_var) >/dev/null 2>&1 && $as_unset $as_var - fi -done +LC_ALL=C +export LC_ALL +LANGUAGE=C +export LANGUAGE # Required to use basename. if expr a : '\(a\)' >/dev/null 2>&1 && @@ -25464,7 +26282,7 @@ $as_expr X/"$0" : '.*/\([^/][^/]*\)/*$' \| \ X"$0" : 'X\(//\)$' \| \ X"$0" : 'X\(/\)' \| . 2>/dev/null || -echo X/"$0" | +$as_echo X/"$0" | sed '/^.*\/\([^/][^/]*\)\/*$/{ s//\1/ q @@ -25515,7 +26333,7 @@ s/-\n.*// ' >$as_me.lineno && chmod +x "$as_me.lineno" || - { echo "$as_me: error: cannot create $as_me.lineno; rerun with a POSIX shell" >&2 + { $as_echo "$as_me: error: cannot create $as_me.lineno; rerun with a POSIX shell" >&2 { (exit 1); exit 1; }; } # Don't try to exec as it changes $[0], causing all sort of problems @@ -25543,7 +26361,6 @@ *) ECHO_N='-n';; esac - if expr a : '\(a\)' >/dev/null 2>&1 && test "X`expr 00001 : '.*\(...\)'`" = X001; then as_expr=expr @@ -25556,19 +26373,22 @@ rm -f conf$$.dir/conf$$.file else rm -f conf$$.dir - mkdir conf$$.dir + mkdir conf$$.dir 2>/dev/null fi -echo >conf$$.file -if ln -s conf$$.file conf$$ 2>/dev/null; then - as_ln_s='ln -s' - # ... but there are two gotchas: - # 1) On MSYS, both `ln -s file dir' and `ln file dir' fail. - # 2) DJGPP < 2.04 has no symlinks; `ln -s' creates a wrapper executable. - # In both cases, we have to default to `cp -p'. - ln -s conf$$.file conf$$.dir 2>/dev/null && test ! -f conf$$.exe || +if (echo >conf$$.file) 2>/dev/null; then + if ln -s conf$$.file conf$$ 2>/dev/null; then + as_ln_s='ln -s' + # ... but there are two gotchas: + # 1) On MSYS, both `ln -s file dir' and `ln file dir' fail. + # 2) DJGPP < 2.04 has no symlinks; `ln -s' creates a wrapper executable. + # In both cases, we have to default to `cp -p'. + ln -s conf$$.file conf$$.dir 2>/dev/null && test ! -f conf$$.exe || + as_ln_s='cp -p' + elif ln conf$$.file conf$$ 2>/dev/null; then + as_ln_s=ln + else as_ln_s='cp -p' -elif ln conf$$.file conf$$ 2>/dev/null; then - as_ln_s=ln + fi else as_ln_s='cp -p' fi @@ -25593,10 +26413,10 @@ as_test_x=' eval sh -c '\'' if test -d "$1"; then - test -d "$1/."; + test -d "$1/."; else case $1 in - -*)set "./$1";; + -*)set "./$1";; esac; case `ls -ld'$as_ls_L_option' "$1" 2>/dev/null` in ???[sx]*):;;*)false;;esac;fi @@ -25619,7 +26439,7 @@ # values after options handling. ac_log=" This file was extended by python $as_me 2.6, which was -generated by GNU Autoconf 2.61. Invocation command line was +generated by GNU Autoconf 2.63. Invocation command line was CONFIG_FILES = $CONFIG_FILES CONFIG_HEADERS = $CONFIG_HEADERS @@ -25632,29 +26452,39 @@ _ACEOF -cat >>$CONFIG_STATUS <<_ACEOF +case $ac_config_files in *" +"*) set x $ac_config_files; shift; ac_config_files=$*;; +esac + +case $ac_config_headers in *" +"*) set x $ac_config_headers; shift; ac_config_headers=$*;; +esac + + +cat >>$CONFIG_STATUS <<_ACEOF || ac_write_fail=1 # Files that config.status was made for. config_files="$ac_config_files" config_headers="$ac_config_headers" _ACEOF -cat >>$CONFIG_STATUS <<\_ACEOF +cat >>$CONFIG_STATUS <<\_ACEOF || ac_write_fail=1 ac_cs_usage="\ \`$as_me' instantiates files from templates according to the current configuration. -Usage: $0 [OPTIONS] [FILE]... +Usage: $0 [OPTION]... [FILE]... -h, --help print this help, then exit -V, --version print version number and configuration settings, then exit - -q, --quiet do not print progress messages + -q, --quiet, --silent + do not print progress messages -d, --debug don't remove temporary files --recheck update $as_me by reconfiguring in the same conditions - --file=FILE[:TEMPLATE] - instantiate the configuration file FILE - --header=FILE[:TEMPLATE] - instantiate the configuration header FILE + --file=FILE[:TEMPLATE] + instantiate the configuration file FILE + --header=FILE[:TEMPLATE] + instantiate the configuration header FILE Configuration files: $config_files @@ -25665,24 +26495,24 @@ Report bugs to ." _ACEOF -cat >>$CONFIG_STATUS <<_ACEOF +cat >>$CONFIG_STATUS <<_ACEOF || ac_write_fail=1 ac_cs_version="\\ python config.status 2.6 -configured by $0, generated by GNU Autoconf 2.61, - with options \\"`echo "$ac_configure_args" | sed 's/^ //; s/[\\""\`\$]/\\\\&/g'`\\" +configured by $0, generated by GNU Autoconf 2.63, + with options \\"`$as_echo "$ac_configure_args" | sed 's/^ //; s/[\\""\`\$]/\\\\&/g'`\\" -Copyright (C) 2006 Free Software Foundation, Inc. +Copyright (C) 2008 Free Software Foundation, Inc. This config.status script is free software; the Free Software Foundation gives unlimited permission to copy, distribute and modify it." ac_pwd='$ac_pwd' srcdir='$srcdir' INSTALL='$INSTALL' +test -n "\$AWK" || AWK=awk _ACEOF -cat >>$CONFIG_STATUS <<\_ACEOF -# If no file are specified by the user, then we need to provide default -# value. By we need to know if files were specified by the user. +cat >>$CONFIG_STATUS <<\_ACEOF || ac_write_fail=1 +# The default lists apply if the user does not specify any file. ac_need_defaults=: while test $# != 0 do @@ -25704,30 +26534,36 @@ -recheck | --recheck | --rechec | --reche | --rech | --rec | --re | --r) ac_cs_recheck=: ;; --version | --versio | --versi | --vers | --ver | --ve | --v | -V ) - echo "$ac_cs_version"; exit ;; + $as_echo "$ac_cs_version"; exit ;; --debug | --debu | --deb | --de | --d | -d ) debug=: ;; --file | --fil | --fi | --f ) $ac_shift - CONFIG_FILES="$CONFIG_FILES $ac_optarg" + case $ac_optarg in + *\'*) ac_optarg=`$as_echo "$ac_optarg" | sed "s/'/'\\\\\\\\''/g"` ;; + esac + CONFIG_FILES="$CONFIG_FILES '$ac_optarg'" ac_need_defaults=false;; --header | --heade | --head | --hea ) $ac_shift - CONFIG_HEADERS="$CONFIG_HEADERS $ac_optarg" + case $ac_optarg in + *\'*) ac_optarg=`$as_echo "$ac_optarg" | sed "s/'/'\\\\\\\\''/g"` ;; + esac + CONFIG_HEADERS="$CONFIG_HEADERS '$ac_optarg'" ac_need_defaults=false;; --he | --h) # Conflict between --help and --header - { echo "$as_me: error: ambiguous option: $1 + { $as_echo "$as_me: error: ambiguous option: $1 Try \`$0 --help' for more information." >&2 { (exit 1); exit 1; }; };; --help | --hel | -h ) - echo "$ac_cs_usage"; exit ;; + $as_echo "$ac_cs_usage"; exit ;; -q | -quiet | --quiet | --quie | --qui | --qu | --q \ | -silent | --silent | --silen | --sile | --sil | --si | --s) ac_cs_silent=: ;; # This is an error. - -*) { echo "$as_me: error: unrecognized option: $1 + -*) { $as_echo "$as_me: error: unrecognized option: $1 Try \`$0 --help' for more information." >&2 { (exit 1); exit 1; }; } ;; @@ -25746,30 +26582,32 @@ fi _ACEOF -cat >>$CONFIG_STATUS <<_ACEOF +cat >>$CONFIG_STATUS <<_ACEOF || ac_write_fail=1 if \$ac_cs_recheck; then - echo "running CONFIG_SHELL=$SHELL $SHELL $0 "$ac_configure_args \$ac_configure_extra_args " --no-create --no-recursion" >&6 - CONFIG_SHELL=$SHELL + set X '$SHELL' '$0' $ac_configure_args \$ac_configure_extra_args --no-create --no-recursion + shift + \$as_echo "running CONFIG_SHELL=$SHELL \$*" >&6 + CONFIG_SHELL='$SHELL' export CONFIG_SHELL - exec $SHELL "$0"$ac_configure_args \$ac_configure_extra_args --no-create --no-recursion + exec "\$@" fi _ACEOF -cat >>$CONFIG_STATUS <<\_ACEOF +cat >>$CONFIG_STATUS <<\_ACEOF || ac_write_fail=1 exec 5>>config.log { echo sed 'h;s/./-/g;s/^.../## /;s/...$/ ##/;p;x;p;x' <<_ASBOX ## Running $as_me. ## _ASBOX - echo "$ac_log" + $as_echo "$ac_log" } >&5 _ACEOF -cat >>$CONFIG_STATUS <<_ACEOF +cat >>$CONFIG_STATUS <<_ACEOF || ac_write_fail=1 _ACEOF -cat >>$CONFIG_STATUS <<\_ACEOF +cat >>$CONFIG_STATUS <<\_ACEOF || ac_write_fail=1 # Handling of arguments. for ac_config_target in $ac_config_targets @@ -25784,8 +26622,8 @@ "Makefile.pre") CONFIG_FILES="$CONFIG_FILES Makefile.pre" ;; "Modules/Setup.config") CONFIG_FILES="$CONFIG_FILES Modules/Setup.config" ;; - *) { { echo "$as_me:$LINENO: error: invalid argument: $ac_config_target" >&5 -echo "$as_me: error: invalid argument: $ac_config_target" >&2;} + *) { { $as_echo "$as_me:$LINENO: error: invalid argument: $ac_config_target" >&5 +$as_echo "$as_me: error: invalid argument: $ac_config_target" >&2;} { (exit 1); exit 1; }; };; esac done @@ -25825,227 +26663,145 @@ (umask 077 && mkdir "$tmp") } || { - echo "$me: cannot create a temporary directory in ." >&2 + $as_echo "$as_me: cannot create a temporary directory in ." >&2 { (exit 1); exit 1; } } -# -# Set up the sed scripts for CONFIG_FILES section. -# - -# No need to generate the scripts if there are no CONFIG_FILES. -# This happens for instance when ./config.status config.h +# Set up the scripts for CONFIG_FILES section. +# No need to generate them if there are no CONFIG_FILES. +# This happens for instance with `./config.status config.h'. if test -n "$CONFIG_FILES"; then -_ACEOF +ac_cr=' +' +ac_cs_awk_cr=`$AWK 'BEGIN { print "a\rb" }' /dev/null` +if test "$ac_cs_awk_cr" = "a${ac_cr}b"; then + ac_cs_awk_cr='\\r' +else + ac_cs_awk_cr=$ac_cr +fi + +echo 'BEGIN {' >"$tmp/subs1.awk" && +_ACEOF +{ + echo "cat >conf$$subs.awk <<_ACEOF" && + echo "$ac_subst_vars" | sed 's/.*/&!$&$ac_delim/' && + echo "_ACEOF" +} >conf$$subs.sh || + { { $as_echo "$as_me:$LINENO: error: could not make $CONFIG_STATUS" >&5 +$as_echo "$as_me: error: could not make $CONFIG_STATUS" >&2;} + { (exit 1); exit 1; }; } +ac_delim_num=`echo "$ac_subst_vars" | grep -c '$'` ac_delim='%!_!# ' for ac_last_try in false false false false false :; do - cat >conf$$subs.sed <<_ACEOF -SHELL!$SHELL$ac_delim -PATH_SEPARATOR!$PATH_SEPARATOR$ac_delim -PACKAGE_NAME!$PACKAGE_NAME$ac_delim -PACKAGE_TARNAME!$PACKAGE_TARNAME$ac_delim -PACKAGE_VERSION!$PACKAGE_VERSION$ac_delim -PACKAGE_STRING!$PACKAGE_STRING$ac_delim -PACKAGE_BUGREPORT!$PACKAGE_BUGREPORT$ac_delim -exec_prefix!$exec_prefix$ac_delim -prefix!$prefix$ac_delim -program_transform_name!$program_transform_name$ac_delim -bindir!$bindir$ac_delim -sbindir!$sbindir$ac_delim -libexecdir!$libexecdir$ac_delim -datarootdir!$datarootdir$ac_delim -datadir!$datadir$ac_delim -sysconfdir!$sysconfdir$ac_delim -sharedstatedir!$sharedstatedir$ac_delim -localstatedir!$localstatedir$ac_delim -includedir!$includedir$ac_delim -oldincludedir!$oldincludedir$ac_delim -docdir!$docdir$ac_delim -infodir!$infodir$ac_delim -htmldir!$htmldir$ac_delim -dvidir!$dvidir$ac_delim -pdfdir!$pdfdir$ac_delim -psdir!$psdir$ac_delim -libdir!$libdir$ac_delim -localedir!$localedir$ac_delim -mandir!$mandir$ac_delim -DEFS!$DEFS$ac_delim -ECHO_C!$ECHO_C$ac_delim -ECHO_N!$ECHO_N$ac_delim -ECHO_T!$ECHO_T$ac_delim -LIBS!$LIBS$ac_delim -build_alias!$build_alias$ac_delim -host_alias!$host_alias$ac_delim -target_alias!$target_alias$ac_delim -VERSION!$VERSION$ac_delim -SOVERSION!$SOVERSION$ac_delim -CONFIG_ARGS!$CONFIG_ARGS$ac_delim -UNIVERSALSDK!$UNIVERSALSDK$ac_delim -ARCH_RUN_32BIT!$ARCH_RUN_32BIT$ac_delim -LIPO_32BIT_FLAGS!$LIPO_32BIT_FLAGS$ac_delim -LIPO_64BIT_FLAGS!$LIPO_64BIT_FLAGS$ac_delim -PYTHONFRAMEWORK!$PYTHONFRAMEWORK$ac_delim -PYTHONFRAMEWORKIDENTIFIER!$PYTHONFRAMEWORKIDENTIFIER$ac_delim -PYTHONFRAMEWORKDIR!$PYTHONFRAMEWORKDIR$ac_delim -PYTHONFRAMEWORKPREFIX!$PYTHONFRAMEWORKPREFIX$ac_delim -PYTHONFRAMEWORKINSTALLDIR!$PYTHONFRAMEWORKINSTALLDIR$ac_delim -FRAMEWORKINSTALLFIRST!$FRAMEWORKINSTALLFIRST$ac_delim -FRAMEWORKINSTALLLAST!$FRAMEWORKINSTALLLAST$ac_delim -FRAMEWORKALTINSTALLFIRST!$FRAMEWORKALTINSTALLFIRST$ac_delim -FRAMEWORKALTINSTALLLAST!$FRAMEWORKALTINSTALLLAST$ac_delim -FRAMEWORKUNIXTOOLSPREFIX!$FRAMEWORKUNIXTOOLSPREFIX$ac_delim -MACHDEP!$MACHDEP$ac_delim -SGI_ABI!$SGI_ABI$ac_delim -EXTRAPLATDIR!$EXTRAPLATDIR$ac_delim -EXTRAMACHDEPPATH!$EXTRAMACHDEPPATH$ac_delim -CONFIGURE_MACOSX_DEPLOYMENT_TARGET!$CONFIGURE_MACOSX_DEPLOYMENT_TARGET$ac_delim -EXPORT_MACOSX_DEPLOYMENT_TARGET!$EXPORT_MACOSX_DEPLOYMENT_TARGET$ac_delim -CC!$CC$ac_delim -CFLAGS!$CFLAGS$ac_delim -LDFLAGS!$LDFLAGS$ac_delim -CPPFLAGS!$CPPFLAGS$ac_delim -ac_ct_CC!$ac_ct_CC$ac_delim -EXEEXT!$EXEEXT$ac_delim -OBJEXT!$OBJEXT$ac_delim -CXX!$CXX$ac_delim -MAINCC!$MAINCC$ac_delim -CPP!$CPP$ac_delim -GREP!$GREP$ac_delim -EGREP!$EGREP$ac_delim -BUILDEXEEXT!$BUILDEXEEXT$ac_delim -LIBRARY!$LIBRARY$ac_delim -LDLIBRARY!$LDLIBRARY$ac_delim -DLLLIBRARY!$DLLLIBRARY$ac_delim -BLDLIBRARY!$BLDLIBRARY$ac_delim -LDLIBRARYDIR!$LDLIBRARYDIR$ac_delim -INSTSONAME!$INSTSONAME$ac_delim -RUNSHARED!$RUNSHARED$ac_delim -LINKCC!$LINKCC$ac_delim -RANLIB!$RANLIB$ac_delim -AR!$AR$ac_delim -SVNVERSION!$SVNVERSION$ac_delim -INSTALL_PROGRAM!$INSTALL_PROGRAM$ac_delim -INSTALL_SCRIPT!$INSTALL_SCRIPT$ac_delim -INSTALL_DATA!$INSTALL_DATA$ac_delim -LN!$LN$ac_delim -OPT!$OPT$ac_delim -BASECFLAGS!$BASECFLAGS$ac_delim -UNIVERSAL_ARCH_FLAGS!$UNIVERSAL_ARCH_FLAGS$ac_delim -OTHER_LIBTOOL_OPT!$OTHER_LIBTOOL_OPT$ac_delim -LIBTOOL_CRUFT!$LIBTOOL_CRUFT$ac_delim -SO!$SO$ac_delim -LDSHARED!$LDSHARED$ac_delim -BLDSHARED!$BLDSHARED$ac_delim -CCSHARED!$CCSHARED$ac_delim -_ACEOF + . ./conf$$subs.sh || + { { $as_echo "$as_me:$LINENO: error: could not make $CONFIG_STATUS" >&5 +$as_echo "$as_me: error: could not make $CONFIG_STATUS" >&2;} + { (exit 1); exit 1; }; } - if test `sed -n "s/.*$ac_delim\$/X/p" conf$$subs.sed | grep -c X` = 97; then + ac_delim_n=`sed -n "s/.*$ac_delim\$/X/p" conf$$subs.awk | grep -c X` + if test $ac_delim_n = $ac_delim_num; then break elif $ac_last_try; then - { { echo "$as_me:$LINENO: error: could not make $CONFIG_STATUS" >&5 -echo "$as_me: error: could not make $CONFIG_STATUS" >&2;} + { { $as_echo "$as_me:$LINENO: error: could not make $CONFIG_STATUS" >&5 +$as_echo "$as_me: error: could not make $CONFIG_STATUS" >&2;} { (exit 1); exit 1; }; } else ac_delim="$ac_delim!$ac_delim _$ac_delim!! " fi done +rm -f conf$$subs.sh -ac_eof=`sed -n '/^CEOF[0-9]*$/s/CEOF/0/p' conf$$subs.sed` -if test -n "$ac_eof"; then - ac_eof=`echo "$ac_eof" | sort -nru | sed 1q` - ac_eof=`expr $ac_eof + 1` -fi - -cat >>$CONFIG_STATUS <<_ACEOF -cat >"\$tmp/subs-1.sed" <<\CEOF$ac_eof -/@[a-zA-Z_][a-zA-Z_0-9]*@/!b -_ACEOF -sed ' -s/[,\\&]/\\&/g; s/@/@|#_!!_#|/g -s/^/s,@/; s/!/@,|#_!!_#|/ -:n -t n -s/'"$ac_delim"'$/,g/; t -s/$/\\/; p -N; s/^.*\n//; s/[,\\&]/\\&/g; s/@/@|#_!!_#|/g; b n -' >>$CONFIG_STATUS >$CONFIG_STATUS <<_ACEOF -CEOF$ac_eof +cat >>$CONFIG_STATUS <<_ACEOF || ac_write_fail=1 +cat >>"\$tmp/subs1.awk" <<\\_ACAWK && _ACEOF +sed -n ' +h +s/^/S["/; s/!.*/"]=/ +p +g +s/^[^!]*!// +:repl +t repl +s/'"$ac_delim"'$// +t delim +:nl +h +s/\(.\{148\}\).*/\1/ +t more1 +s/["\\]/\\&/g; s/^/"/; s/$/\\n"\\/ +p +n +b repl +:more1 +s/["\\]/\\&/g; s/^/"/; s/$/"\\/ +p +g +s/.\{148\}// +t nl +:delim +h +s/\(.\{148\}\).*/\1/ +t more2 +s/["\\]/\\&/g; s/^/"/; s/$/"/ +p +b +:more2 +s/["\\]/\\&/g; s/^/"/; s/$/"\\/ +p +g +s/.\{148\}// +t delim +' >$CONFIG_STATUS || ac_write_fail=1 +rm -f conf$$subs.awk +cat >>$CONFIG_STATUS <<_ACEOF || ac_write_fail=1 +_ACAWK +cat >>"\$tmp/subs1.awk" <<_ACAWK && + for (key in S) S_is_set[key] = 1 + FS = "" + +} +{ + line = $ 0 + nfields = split(line, field, "@") + substed = 0 + len = length(field[1]) + for (i = 2; i < nfields; i++) { + key = field[i] + keylen = length(key) + if (S_is_set[key]) { + value = S[key] + line = substr(line, 1, len) "" value "" substr(line, len + keylen + 3) + len += length(value) + length(field[++i]) + substed = 1 + } else + len += 1 + keylen + } + print line +} -ac_delim='%!_!# ' -for ac_last_try in false false false false false :; do - cat >conf$$subs.sed <<_ACEOF -LINKFORSHARED!$LINKFORSHARED$ac_delim -CFLAGSFORSHARED!$CFLAGSFORSHARED$ac_delim -SHLIBS!$SHLIBS$ac_delim -USE_SIGNAL_MODULE!$USE_SIGNAL_MODULE$ac_delim -SIGNAL_OBJS!$SIGNAL_OBJS$ac_delim -USE_THREAD_MODULE!$USE_THREAD_MODULE$ac_delim -LDLAST!$LDLAST$ac_delim -THREADOBJ!$THREADOBJ$ac_delim -DLINCLDIR!$DLINCLDIR$ac_delim -DYNLOADFILE!$DYNLOADFILE$ac_delim -MACHDEP_OBJS!$MACHDEP_OBJS$ac_delim -TRUE!$TRUE$ac_delim -LIBOBJS!$LIBOBJS$ac_delim -HAVE_GETHOSTBYNAME_R_6_ARG!$HAVE_GETHOSTBYNAME_R_6_ARG$ac_delim -HAVE_GETHOSTBYNAME_R_5_ARG!$HAVE_GETHOSTBYNAME_R_5_ARG$ac_delim -HAVE_GETHOSTBYNAME_R_3_ARG!$HAVE_GETHOSTBYNAME_R_3_ARG$ac_delim -HAVE_GETHOSTBYNAME_R!$HAVE_GETHOSTBYNAME_R$ac_delim -HAVE_GETHOSTBYNAME!$HAVE_GETHOSTBYNAME$ac_delim -LIBM!$LIBM$ac_delim -LIBC!$LIBC$ac_delim -UNICODE_OBJS!$UNICODE_OBJS$ac_delim -THREADHEADERS!$THREADHEADERS$ac_delim -SRCDIRS!$SRCDIRS$ac_delim -LTLIBOBJS!$LTLIBOBJS$ac_delim +_ACAWK _ACEOF - - if test `sed -n "s/.*$ac_delim\$/X/p" conf$$subs.sed | grep -c X` = 24; then - break - elif $ac_last_try; then - { { echo "$as_me:$LINENO: error: could not make $CONFIG_STATUS" >&5 -echo "$as_me: error: could not make $CONFIG_STATUS" >&2;} +cat >>$CONFIG_STATUS <<\_ACEOF || ac_write_fail=1 +if sed "s/$ac_cr//" < /dev/null > /dev/null 2>&1; then + sed "s/$ac_cr\$//; s/$ac_cr/$ac_cs_awk_cr/g" +else + cat +fi < "$tmp/subs1.awk" > "$tmp/subs.awk" \ + || { { $as_echo "$as_me:$LINENO: error: could not setup config files machinery" >&5 +$as_echo "$as_me: error: could not setup config files machinery" >&2;} { (exit 1); exit 1; }; } - else - ac_delim="$ac_delim!$ac_delim _$ac_delim!! " - fi -done - -ac_eof=`sed -n '/^CEOF[0-9]*$/s/CEOF/0/p' conf$$subs.sed` -if test -n "$ac_eof"; then - ac_eof=`echo "$ac_eof" | sort -nru | sed 1q` - ac_eof=`expr $ac_eof + 1` -fi - -cat >>$CONFIG_STATUS <<_ACEOF -cat >"\$tmp/subs-2.sed" <<\CEOF$ac_eof -/@[a-zA-Z_][a-zA-Z_0-9]*@/!b end -_ACEOF -sed ' -s/[,\\&]/\\&/g; s/@/@|#_!!_#|/g -s/^/s,@/; s/!/@,|#_!!_#|/ -:n -t n -s/'"$ac_delim"'$/,g/; t -s/$/\\/; p -N; s/^.*\n//; s/[,\\&]/\\&/g; s/@/@|#_!!_#|/g; b n -' >>$CONFIG_STATUS >$CONFIG_STATUS <<_ACEOF -:end -s/|#_!!_#|//g -CEOF$ac_eof _ACEOF - # VPATH may cause trouble with some makes, so we remove $(srcdir), # ${srcdir} and @srcdir@ from VPATH if srcdir is ".", strip leading and # trailing colons and then remove the whole line if VPATH becomes empty @@ -26061,19 +26817,133 @@ }' fi -cat >>$CONFIG_STATUS <<\_ACEOF +cat >>$CONFIG_STATUS <<\_ACEOF || ac_write_fail=1 fi # test -n "$CONFIG_FILES" +# Set up the scripts for CONFIG_HEADERS section. +# No need to generate them if there are no CONFIG_HEADERS. +# This happens for instance with `./config.status Makefile'. +if test -n "$CONFIG_HEADERS"; then +cat >"$tmp/defines.awk" <<\_ACAWK || +BEGIN { +_ACEOF + +# Transform confdefs.h into an awk script `defines.awk', embedded as +# here-document in config.status, that substitutes the proper values into +# config.h.in to produce config.h. + +# Create a delimiter string that does not exist in confdefs.h, to ease +# handling of long lines. +ac_delim='%!_!# ' +for ac_last_try in false false :; do + ac_t=`sed -n "/$ac_delim/p" confdefs.h` + if test -z "$ac_t"; then + break + elif $ac_last_try; then + { { $as_echo "$as_me:$LINENO: error: could not make $CONFIG_HEADERS" >&5 +$as_echo "$as_me: error: could not make $CONFIG_HEADERS" >&2;} + { (exit 1); exit 1; }; } + else + ac_delim="$ac_delim!$ac_delim _$ac_delim!! " + fi +done + +# For the awk script, D is an array of macro values keyed by name, +# likewise P contains macro parameters if any. Preserve backslash +# newline sequences. + +ac_word_re=[_$as_cr_Letters][_$as_cr_alnum]* +sed -n ' +s/.\{148\}/&'"$ac_delim"'/g +t rset +:rset +s/^[ ]*#[ ]*define[ ][ ]*/ / +t def +d +:def +s/\\$// +t bsnl +s/["\\]/\\&/g +s/^ \('"$ac_word_re"'\)\(([^()]*)\)[ ]*\(.*\)/P["\1"]="\2"\ +D["\1"]=" \3"/p +s/^ \('"$ac_word_re"'\)[ ]*\(.*\)/D["\1"]=" \2"/p +d +:bsnl +s/["\\]/\\&/g +s/^ \('"$ac_word_re"'\)\(([^()]*)\)[ ]*\(.*\)/P["\1"]="\2"\ +D["\1"]=" \3\\\\\\n"\\/p +t cont +s/^ \('"$ac_word_re"'\)[ ]*\(.*\)/D["\1"]=" \2\\\\\\n"\\/p +t cont +d +:cont +n +s/.\{148\}/&'"$ac_delim"'/g +t clear +:clear +s/\\$// +t bsnlc +s/["\\]/\\&/g; s/^/"/; s/$/"/p +d +:bsnlc +s/["\\]/\\&/g; s/^/"/; s/$/\\\\\\n"\\/p +b cont +' >$CONFIG_STATUS || ac_write_fail=1 + +cat >>$CONFIG_STATUS <<_ACEOF || ac_write_fail=1 + for (key in D) D_is_set[key] = 1 + FS = "" +} +/^[\t ]*#[\t ]*(define|undef)[\t ]+$ac_word_re([\t (]|\$)/ { + line = \$ 0 + split(line, arg, " ") + if (arg[1] == "#") { + defundef = arg[2] + mac1 = arg[3] + } else { + defundef = substr(arg[1], 2) + mac1 = arg[2] + } + split(mac1, mac2, "(") #) + macro = mac2[1] + prefix = substr(line, 1, index(line, defundef) - 1) + if (D_is_set[macro]) { + # Preserve the white space surrounding the "#". + print prefix "define", macro P[macro] D[macro] + next + } else { + # Replace #undef with comments. This is necessary, for example, + # in the case of _POSIX_SOURCE, which is predefined and required + # on some systems where configure will not decide to define it. + if (defundef == "undef") { + print "/*", prefix defundef, macro, "*/" + next + } + } +} +{ print } +_ACAWK +_ACEOF +cat >>$CONFIG_STATUS <<\_ACEOF || ac_write_fail=1 + { { $as_echo "$as_me:$LINENO: error: could not setup config headers machinery" >&5 +$as_echo "$as_me: error: could not setup config headers machinery" >&2;} + { (exit 1); exit 1; }; } +fi # test -n "$CONFIG_HEADERS" + -for ac_tag in :F $CONFIG_FILES :H $CONFIG_HEADERS +eval set X " :F $CONFIG_FILES :H $CONFIG_HEADERS " +shift +for ac_tag do case $ac_tag in :[FHLC]) ac_mode=$ac_tag; continue;; esac case $ac_mode$ac_tag in :[FHL]*:*);; - :L* | :C*:*) { { echo "$as_me:$LINENO: error: Invalid tag $ac_tag." >&5 -echo "$as_me: error: Invalid tag $ac_tag." >&2;} + :L* | :C*:*) { { $as_echo "$as_me:$LINENO: error: invalid tag $ac_tag" >&5 +$as_echo "$as_me: error: invalid tag $ac_tag" >&2;} { (exit 1); exit 1; }; };; :[FH]-) ac_tag=-:-;; :[FH]*) ac_tag=$ac_tag:$ac_tag.in;; @@ -26102,26 +26972,38 @@ [\\/$]*) false;; *) test -f "$srcdir/$ac_f" && ac_f="$srcdir/$ac_f";; esac || - { { echo "$as_me:$LINENO: error: cannot find input file: $ac_f" >&5 -echo "$as_me: error: cannot find input file: $ac_f" >&2;} + { { $as_echo "$as_me:$LINENO: error: cannot find input file: $ac_f" >&5 +$as_echo "$as_me: error: cannot find input file: $ac_f" >&2;} { (exit 1); exit 1; }; };; esac - ac_file_inputs="$ac_file_inputs $ac_f" + case $ac_f in *\'*) ac_f=`$as_echo "$ac_f" | sed "s/'/'\\\\\\\\''/g"`;; esac + ac_file_inputs="$ac_file_inputs '$ac_f'" done # Let's still pretend it is `configure' which instantiates (i.e., don't # use $as_me), people would be surprised to read: # /* config.h. Generated by config.status. */ - configure_input="Generated from "`IFS=: - echo $* | sed 's|^[^:]*/||;s|:[^:]*/|, |g'`" by configure." + configure_input='Generated from '` + $as_echo "$*" | sed 's|^[^:]*/||;s|:[^:]*/|, |g' + `' by configure.' if test x"$ac_file" != x-; then configure_input="$ac_file. $configure_input" - { echo "$as_me:$LINENO: creating $ac_file" >&5 -echo "$as_me: creating $ac_file" >&6;} + { $as_echo "$as_me:$LINENO: creating $ac_file" >&5 +$as_echo "$as_me: creating $ac_file" >&6;} fi + # Neutralize special characters interpreted by sed in replacement strings. + case $configure_input in #( + *\&* | *\|* | *\\* ) + ac_sed_conf_input=`$as_echo "$configure_input" | + sed 's/[\\\\&|]/\\\\&/g'`;; #( + *) ac_sed_conf_input=$configure_input;; + esac case $ac_tag in - *:-:* | *:-) cat >"$tmp/stdin";; + *:-:* | *:-) cat >"$tmp/stdin" \ + || { { $as_echo "$as_me:$LINENO: error: could not create $ac_file" >&5 +$as_echo "$as_me: error: could not create $ac_file" >&2;} + { (exit 1); exit 1; }; } ;; esac ;; esac @@ -26131,7 +27013,7 @@ X"$ac_file" : 'X\(//\)[^/]' \| \ X"$ac_file" : 'X\(//\)$' \| \ X"$ac_file" : 'X\(/\)' \| . 2>/dev/null || -echo X"$ac_file" | +$as_echo X"$ac_file" | sed '/^X\(.*[^/]\)\/\/*[^/][^/]*\/*$/{ s//\1/ q @@ -26157,7 +27039,7 @@ as_dirs= while :; do case $as_dir in #( - *\'*) as_qdir=`echo "$as_dir" | sed "s/'/'\\\\\\\\''/g"`;; #( + *\'*) as_qdir=`$as_echo "$as_dir" | sed "s/'/'\\\\\\\\''/g"`;; #'( *) as_qdir=$as_dir;; esac as_dirs="'$as_qdir' $as_dirs" @@ -26166,7 +27048,7 @@ X"$as_dir" : 'X\(//\)[^/]' \| \ X"$as_dir" : 'X\(//\)$' \| \ X"$as_dir" : 'X\(/\)' \| . 2>/dev/null || -echo X"$as_dir" | +$as_echo X"$as_dir" | sed '/^X\(.*[^/]\)\/\/*[^/][^/]*\/*$/{ s//\1/ q @@ -26187,17 +27069,17 @@ test -d "$as_dir" && break done test -z "$as_dirs" || eval "mkdir $as_dirs" - } || test -d "$as_dir" || { { echo "$as_me:$LINENO: error: cannot create directory $as_dir" >&5 -echo "$as_me: error: cannot create directory $as_dir" >&2;} + } || test -d "$as_dir" || { { $as_echo "$as_me:$LINENO: error: cannot create directory $as_dir" >&5 +$as_echo "$as_me: error: cannot create directory $as_dir" >&2;} { (exit 1); exit 1; }; }; } ac_builddir=. case "$ac_dir" in .) ac_dir_suffix= ac_top_builddir_sub=. ac_top_build_prefix= ;; *) - ac_dir_suffix=/`echo "$ac_dir" | sed 's,^\.[\\/],,'` + ac_dir_suffix=/`$as_echo "$ac_dir" | sed 's|^\.[\\/]||'` # A ".." for each directory in $ac_dir_suffix. - ac_top_builddir_sub=`echo "$ac_dir_suffix" | sed 's,/[^\\/]*,/..,g;s,/,,'` + ac_top_builddir_sub=`$as_echo "$ac_dir_suffix" | sed 's|/[^\\/]*|/..|g;s|/||'` case $ac_top_builddir_sub in "") ac_top_builddir_sub=. ac_top_build_prefix= ;; *) ac_top_build_prefix=$ac_top_builddir_sub/ ;; @@ -26237,12 +27119,13 @@ esac _ACEOF -cat >>$CONFIG_STATUS <<\_ACEOF +cat >>$CONFIG_STATUS <<\_ACEOF || ac_write_fail=1 # If the template does not know about datarootdir, expand it. # FIXME: This hack should be removed a few years after 2.60. ac_datarootdir_hack=; ac_datarootdir_seen= -case `sed -n '/datarootdir/ { +ac_sed_dataroot=' +/datarootdir/ { p q } @@ -26251,13 +27134,14 @@ /@infodir@/p /@localedir@/p /@mandir@/p -' $ac_file_inputs` in +' +case `eval "sed -n \"\$ac_sed_dataroot\" $ac_file_inputs"` in *datarootdir*) ac_datarootdir_seen=yes;; *@datadir@*|*@docdir@*|*@infodir@*|*@localedir@*|*@mandir@*) - { echo "$as_me:$LINENO: WARNING: $ac_file_inputs seems to ignore the --datarootdir setting" >&5 -echo "$as_me: WARNING: $ac_file_inputs seems to ignore the --datarootdir setting" >&2;} + { $as_echo "$as_me:$LINENO: WARNING: $ac_file_inputs seems to ignore the --datarootdir setting" >&5 +$as_echo "$as_me: WARNING: $ac_file_inputs seems to ignore the --datarootdir setting" >&2;} _ACEOF -cat >>$CONFIG_STATUS <<_ACEOF +cat >>$CONFIG_STATUS <<_ACEOF || ac_write_fail=1 ac_datarootdir_hack=' s&@datadir@&$datadir&g s&@docdir@&$docdir&g @@ -26271,15 +27155,16 @@ # Neutralize VPATH when `$srcdir' = `.'. # Shell code in configure.ac might set extrasub. # FIXME: do we really want to maintain this feature? -cat >>$CONFIG_STATUS <<_ACEOF - sed "$ac_vpsub +cat >>$CONFIG_STATUS <<_ACEOF || ac_write_fail=1 +ac_sed_extra="$ac_vpsub $extrasub _ACEOF -cat >>$CONFIG_STATUS <<\_ACEOF +cat >>$CONFIG_STATUS <<\_ACEOF || ac_write_fail=1 :t /@[a-zA-Z_][a-zA-Z_0-9]*@/!b -s&@configure_input@&$configure_input&;t t +s|@configure_input@|$ac_sed_conf_input|;t t s&@top_builddir@&$ac_top_builddir_sub&;t t +s&@top_build_prefix@&$ac_top_build_prefix&;t t s&@srcdir@&$ac_srcdir&;t t s&@abs_srcdir@&$ac_abs_srcdir&;t t s&@top_srcdir@&$ac_top_srcdir&;t t @@ -26289,119 +27174,58 @@ s&@abs_top_builddir@&$ac_abs_top_builddir&;t t s&@INSTALL@&$ac_INSTALL&;t t $ac_datarootdir_hack -" $ac_file_inputs | sed -f "$tmp/subs-1.sed" | sed -f "$tmp/subs-2.sed" >$tmp/out +" +eval sed \"\$ac_sed_extra\" "$ac_file_inputs" | $AWK -f "$tmp/subs.awk" >$tmp/out \ + || { { $as_echo "$as_me:$LINENO: error: could not create $ac_file" >&5 +$as_echo "$as_me: error: could not create $ac_file" >&2;} + { (exit 1); exit 1; }; } test -z "$ac_datarootdir_hack$ac_datarootdir_seen" && { ac_out=`sed -n '/\${datarootdir}/p' "$tmp/out"`; test -n "$ac_out"; } && { ac_out=`sed -n '/^[ ]*datarootdir[ ]*:*=/p' "$tmp/out"`; test -z "$ac_out"; } && - { echo "$as_me:$LINENO: WARNING: $ac_file contains a reference to the variable \`datarootdir' + { $as_echo "$as_me:$LINENO: WARNING: $ac_file contains a reference to the variable \`datarootdir' which seems to be undefined. Please make sure it is defined." >&5 -echo "$as_me: WARNING: $ac_file contains a reference to the variable \`datarootdir' +$as_echo "$as_me: WARNING: $ac_file contains a reference to the variable \`datarootdir' which seems to be undefined. Please make sure it is defined." >&2;} rm -f "$tmp/stdin" case $ac_file in - -) cat "$tmp/out"; rm -f "$tmp/out";; - *) rm -f "$ac_file"; mv "$tmp/out" $ac_file;; - esac + -) cat "$tmp/out" && rm -f "$tmp/out";; + *) rm -f "$ac_file" && mv "$tmp/out" "$ac_file";; + esac \ + || { { $as_echo "$as_me:$LINENO: error: could not create $ac_file" >&5 +$as_echo "$as_me: error: could not create $ac_file" >&2;} + { (exit 1); exit 1; }; } ;; :H) # # CONFIG_HEADER # -_ACEOF - -# Transform confdefs.h into a sed script `conftest.defines', that -# substitutes the proper values into config.h.in to produce config.h. -rm -f conftest.defines conftest.tail -# First, append a space to every undef/define line, to ease matching. -echo 's/$/ /' >conftest.defines -# Then, protect against being on the right side of a sed subst, or in -# an unquoted here document, in config.status. If some macros were -# called several times there might be several #defines for the same -# symbol, which is useless. But do not sort them, since the last -# AC_DEFINE must be honored. -ac_word_re=[_$as_cr_Letters][_$as_cr_alnum]* -# These sed commands are passed to sed as "A NAME B PARAMS C VALUE D", where -# NAME is the cpp macro being defined, VALUE is the value it is being given. -# PARAMS is the parameter list in the macro definition--in most cases, it's -# just an empty string. -ac_dA='s,^\\([ #]*\\)[^ ]*\\([ ]*' -ac_dB='\\)[ (].*,\\1define\\2' -ac_dC=' ' -ac_dD=' ,' - -uniq confdefs.h | - sed -n ' - t rset - :rset - s/^[ ]*#[ ]*define[ ][ ]*// - t ok - d - :ok - s/[\\&,]/\\&/g - s/^\('"$ac_word_re"'\)\(([^()]*)\)[ ]*\(.*\)/ '"$ac_dA"'\1'"$ac_dB"'\2'"${ac_dC}"'\3'"$ac_dD"'/p - s/^\('"$ac_word_re"'\)[ ]*\(.*\)/'"$ac_dA"'\1'"$ac_dB$ac_dC"'\2'"$ac_dD"'/p - ' >>conftest.defines - -# Remove the space that was appended to ease matching. -# Then replace #undef with comments. This is necessary, for -# example, in the case of _POSIX_SOURCE, which is predefined and required -# on some systems where configure will not decide to define it. -# (The regexp can be short, since the line contains either #define or #undef.) -echo 's/ $// -s,^[ #]*u.*,/* & */,' >>conftest.defines - -# Break up conftest.defines: -ac_max_sed_lines=50 - -# First sed command is: sed -f defines.sed $ac_file_inputs >"$tmp/out1" -# Second one is: sed -f defines.sed "$tmp/out1" >"$tmp/out2" -# Third one will be: sed -f defines.sed "$tmp/out2" >"$tmp/out1" -# et cetera. -ac_in='$ac_file_inputs' -ac_out='"$tmp/out1"' -ac_nxt='"$tmp/out2"' - -while : -do - # Write a here document: - cat >>$CONFIG_STATUS <<_ACEOF - # First, check the format of the line: - cat >"\$tmp/defines.sed" <<\\CEOF -/^[ ]*#[ ]*undef[ ][ ]*$ac_word_re[ ]*\$/b def -/^[ ]*#[ ]*define[ ][ ]*$ac_word_re[( ]/b def -b -:def -_ACEOF - sed ${ac_max_sed_lines}q conftest.defines >>$CONFIG_STATUS - echo 'CEOF - sed -f "$tmp/defines.sed"' "$ac_in >$ac_out" >>$CONFIG_STATUS - ac_in=$ac_out; ac_out=$ac_nxt; ac_nxt=$ac_in - sed 1,${ac_max_sed_lines}d conftest.defines >conftest.tail - grep . conftest.tail >/dev/null || break - rm -f conftest.defines - mv conftest.tail conftest.defines -done -rm -f conftest.defines conftest.tail - -echo "ac_result=$ac_in" >>$CONFIG_STATUS -cat >>$CONFIG_STATUS <<\_ACEOF if test x"$ac_file" != x-; then - echo "/* $configure_input */" >"$tmp/config.h" - cat "$ac_result" >>"$tmp/config.h" - if diff $ac_file "$tmp/config.h" >/dev/null 2>&1; then - { echo "$as_me:$LINENO: $ac_file is unchanged" >&5 -echo "$as_me: $ac_file is unchanged" >&6;} + { + $as_echo "/* $configure_input */" \ + && eval '$AWK -f "$tmp/defines.awk"' "$ac_file_inputs" + } >"$tmp/config.h" \ + || { { $as_echo "$as_me:$LINENO: error: could not create $ac_file" >&5 +$as_echo "$as_me: error: could not create $ac_file" >&2;} + { (exit 1); exit 1; }; } + if diff "$ac_file" "$tmp/config.h" >/dev/null 2>&1; then + { $as_echo "$as_me:$LINENO: $ac_file is unchanged" >&5 +$as_echo "$as_me: $ac_file is unchanged" >&6;} else - rm -f $ac_file - mv "$tmp/config.h" $ac_file + rm -f "$ac_file" + mv "$tmp/config.h" "$ac_file" \ + || { { $as_echo "$as_me:$LINENO: error: could not create $ac_file" >&5 +$as_echo "$as_me: error: could not create $ac_file" >&2;} + { (exit 1); exit 1; }; } fi else - echo "/* $configure_input */" - cat "$ac_result" + $as_echo "/* $configure_input */" \ + && eval '$AWK -f "$tmp/defines.awk"' "$ac_file_inputs" \ + || { { $as_echo "$as_me:$LINENO: error: could not create -" >&5 +$as_echo "$as_me: error: could not create -" >&2;} + { (exit 1); exit 1; }; } fi - rm -f "$tmp/out12" ;; @@ -26415,6 +27239,11 @@ chmod +x $CONFIG_STATUS ac_clean_files=$ac_clean_files_save +test $ac_write_fail = 0 || + { { $as_echo "$as_me:$LINENO: error: write failure creating $CONFIG_STATUS" >&5 +$as_echo "$as_me: error: write failure creating $CONFIG_STATUS" >&2;} + { (exit 1); exit 1; }; } + # configure is writing to config.log, and then calls config.status. # config.status does its own redirection, appending to config.log. @@ -26436,6 +27265,10 @@ # would make configure fail if this is the last instruction. $ac_cs_success || { (exit 1); exit 1; } fi +if test -n "$ac_unrecognized_opts" && test "$enable_option_checking" != no; then + { $as_echo "$as_me:$LINENO: WARNING: unrecognized options: $ac_unrecognized_opts" >&5 +$as_echo "$as_me: WARNING: unrecognized options: $ac_unrecognized_opts" >&2;} +fi echo "creating Modules/Setup" @@ -26457,12 +27290,12 @@ case $ac_sys_system in BeOS) - { echo "$as_me:$LINENO: WARNING: + { $as_echo "$as_me:$LINENO: WARNING: Support for BeOS is deprecated as of Python 2.6. See PEP 11 for the gory details. " >&5 -echo "$as_me: WARNING: +$as_echo "$as_me: WARNING: Support for BeOS is deprecated as of Python 2.6. See PEP 11 for the gory details. Modified: python/branches/release26-maint/configure.in ============================================================================== --- python/branches/release26-maint/configure.in (original) +++ python/branches/release26-maint/configure.in Sun May 2 18:45:11 2010 @@ -1834,7 +1834,7 @@ FreeBSD*) if [[ "`$CC -dM -E - Author: benjamin.peterson Date: Sun May 2 18:45:41 2010 New Revision: 80702 Log: Merged revisions 78965 via svnmerge from svn+ssh://pythondev at svn.python.org/python/branches/py3k ................ r78965 | benjamin.peterson | 2010-03-14 10:18:25 -0500 (Sun, 14 Mar 2010) | 13 lines Merged revisions 78962,78964 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r78962 | benjamin.peterson | 2010-03-14 09:24:31 -0500 (Sun, 14 Mar 2010) | 1 line fix freebsd linking #7705 ........ r78964 | benjamin.peterson | 2010-03-14 10:06:14 -0500 (Sun, 14 Mar 2010) | 1 line fix quotes ........ ................ Modified: python/branches/release31-maint/ (props changed) python/branches/release31-maint/configure python/branches/release31-maint/configure.in Modified: python/branches/release31-maint/configure ============================================================================== --- python/branches/release31-maint/configure (original) +++ python/branches/release31-maint/configure Sun May 2 18:45:41 2010 @@ -1,12 +1,12 @@ #! /bin/sh -# From configure.in Revision: 80192 . +# From configure.in Revision: 80577 . # Guess values for system-dependent variables and create Makefiles. -# Generated by GNU Autoconf 2.61 for python 3.1. +# Generated by GNU Autoconf 2.63 for python 3.1. # # Report bugs to . # # Copyright (C) 1992, 1993, 1994, 1995, 1996, 1998, 1999, 2000, 2001, -# 2002, 2003, 2004, 2005, 2006 Free Software Foundation, Inc. +# 2002, 2003, 2004, 2005, 2006, 2007, 2008 Free Software Foundation, Inc. # This configure script is free software; the Free Software Foundation # gives unlimited permission to copy, distribute and modify it. ## --------------------- ## @@ -18,7 +18,7 @@ if test -n "${ZSH_VERSION+set}" && (emulate sh) >/dev/null 2>&1; then emulate sh NULLCMD=: - # Zsh 3.x and 4.x performs word splitting on ${1+"$@"}, which + # Pre-4.2 versions of Zsh do word splitting on ${1+"$@"}, which # is contrary to our usage. Disable this feature. alias -g '${1+"$@"}'='"$@"' setopt NO_GLOB_SUBST @@ -40,17 +40,45 @@ as_cr_digits='0123456789' as_cr_alnum=$as_cr_Letters$as_cr_digits -# The user is always right. -if test "${PATH_SEPARATOR+set}" != set; then - echo "#! /bin/sh" >conf$$.sh - echo "exit 0" >>conf$$.sh - chmod +x conf$$.sh - if (PATH="/nonexistent;."; conf$$.sh) >/dev/null 2>&1; then - PATH_SEPARATOR=';' +as_nl=' +' +export as_nl +# Printing a long string crashes Solaris 7 /usr/bin/printf. +as_echo='\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\' +as_echo=$as_echo$as_echo$as_echo$as_echo$as_echo +as_echo=$as_echo$as_echo$as_echo$as_echo$as_echo$as_echo +if (test "X`printf %s $as_echo`" = "X$as_echo") 2>/dev/null; then + as_echo='printf %s\n' + as_echo_n='printf %s' +else + if test "X`(/usr/ucb/echo -n -n $as_echo) 2>/dev/null`" = "X-n $as_echo"; then + as_echo_body='eval /usr/ucb/echo -n "$1$as_nl"' + as_echo_n='/usr/ucb/echo -n' else - PATH_SEPARATOR=: + as_echo_body='eval expr "X$1" : "X\\(.*\\)"' + as_echo_n_body='eval + arg=$1; + case $arg in + *"$as_nl"*) + expr "X$arg" : "X\\(.*\\)$as_nl"; + arg=`expr "X$arg" : ".*$as_nl\\(.*\\)"`;; + esac; + expr "X$arg" : "X\\(.*\\)" | tr -d "$as_nl" + ' + export as_echo_n_body + as_echo_n='sh -c $as_echo_n_body as_echo' fi - rm -f conf$$.sh + export as_echo_body + as_echo='sh -c $as_echo_body as_echo' +fi + +# The user is always right. +if test "${PATH_SEPARATOR+set}" != set; then + PATH_SEPARATOR=: + (PATH='/bin;/bin'; FPATH=$PATH; sh -c :) >/dev/null 2>&1 && { + (PATH='/bin:/bin'; FPATH=$PATH; sh -c :) >/dev/null 2>&1 || + PATH_SEPARATOR=';' + } fi # Support unset when possible. @@ -66,8 +94,6 @@ # there to prevent editors from complaining about space-tab. # (If _AS_PATH_WALK were called with IFS unset, it would disable word # splitting by setting IFS to empty value.) -as_nl=' -' IFS=" "" $as_nl" # Find who we are. Look in the path if we contain no directory separator. @@ -90,7 +116,7 @@ as_myself=$0 fi if test ! -f "$as_myself"; then - echo "$as_myself: error: cannot find myself; rerun with an absolute file name" >&2 + $as_echo "$as_myself: error: cannot find myself; rerun with an absolute file name" >&2 { (exit 1); exit 1; } fi @@ -103,17 +129,10 @@ PS4='+ ' # NLS nuisances. -for as_var in \ - LANG LANGUAGE LC_ADDRESS LC_ALL LC_COLLATE LC_CTYPE LC_IDENTIFICATION \ - LC_MEASUREMENT LC_MESSAGES LC_MONETARY LC_NAME LC_NUMERIC LC_PAPER \ - LC_TELEPHONE LC_TIME -do - if (set +x; test -z "`(eval $as_var=C; export $as_var) 2>&1`"); then - eval $as_var=C; export $as_var - else - ($as_unset $as_var) >/dev/null 2>&1 && $as_unset $as_var - fi -done +LC_ALL=C +export LC_ALL +LANGUAGE=C +export LANGUAGE # Required to use basename. if expr a : '\(a\)' >/dev/null 2>&1 && @@ -135,7 +154,7 @@ $as_expr X/"$0" : '.*/\([^/][^/]*\)/*$' \| \ X"$0" : 'X\(//\)$' \| \ X"$0" : 'X\(/\)' \| . 2>/dev/null || -echo X/"$0" | +$as_echo X/"$0" | sed '/^.*\/\([^/][^/]*\)\/*$/{ s//\1/ q @@ -161,7 +180,7 @@ as_have_required=no fi - if test $as_have_required = yes && (eval ": + if test $as_have_required = yes && (eval ": (as_func_return () { (exit \$1) } @@ -243,7 +262,7 @@ if test -n "${ZSH_VERSION+set}" && (emulate sh) >/dev/null 2>&1; then emulate sh NULLCMD=: - # Zsh 3.x and 4.x performs word splitting on ${1+"$@"}, which + # Pre-4.2 versions of Zsh do word splitting on ${1+"$@"}, which # is contrary to our usage. Disable this feature. alias -g '${1+"$@"}'='"$@"' setopt NO_GLOB_SUBST @@ -264,7 +283,7 @@ if test -n "${ZSH_VERSION+set}" && (emulate sh) >/dev/null 2>&1; then emulate sh NULLCMD=: - # Zsh 3.x and 4.x performs word splitting on ${1+"$@"}, which + # Pre-4.2 versions of Zsh do word splitting on ${1+"$@"}, which # is contrary to our usage. Disable this feature. alias -g '${1+"$@"}'='"$@"' setopt NO_GLOB_SUBST @@ -344,10 +363,10 @@ if test "x$CONFIG_SHELL" != x; then for as_var in BASH_ENV ENV - do ($as_unset $as_var) >/dev/null 2>&1 && $as_unset $as_var - done - export CONFIG_SHELL - exec "$CONFIG_SHELL" "$as_myself" ${1+"$@"} + do ($as_unset $as_var) >/dev/null 2>&1 && $as_unset $as_var + done + export CONFIG_SHELL + exec "$CONFIG_SHELL" "$as_myself" ${1+"$@"} fi @@ -416,9 +435,10 @@ test \$exitcode = 0") || { echo No shell found that supports shell functions. - echo Please tell autoconf at gnu.org about your system, - echo including any error possibly output before this - echo message + echo Please tell bug-autoconf at gnu.org about your system, + echo including any error possibly output before this message. + echo This can help us improve future autoconf versions. + echo Configuration will now proceed without shell functions. } @@ -454,7 +474,7 @@ s/-\n.*// ' >$as_me.lineno && chmod +x "$as_me.lineno" || - { echo "$as_me: error: cannot create $as_me.lineno; rerun with a POSIX shell" >&2 + { $as_echo "$as_me: error: cannot create $as_me.lineno; rerun with a POSIX shell" >&2 { (exit 1); exit 1; }; } # Don't try to exec as it changes $[0], causing all sort of problems @@ -482,7 +502,6 @@ *) ECHO_N='-n';; esac - if expr a : '\(a\)' >/dev/null 2>&1 && test "X`expr 00001 : '.*\(...\)'`" = X001; then as_expr=expr @@ -495,19 +514,22 @@ rm -f conf$$.dir/conf$$.file else rm -f conf$$.dir - mkdir conf$$.dir + mkdir conf$$.dir 2>/dev/null fi -echo >conf$$.file -if ln -s conf$$.file conf$$ 2>/dev/null; then - as_ln_s='ln -s' - # ... but there are two gotchas: - # 1) On MSYS, both `ln -s file dir' and `ln file dir' fail. - # 2) DJGPP < 2.04 has no symlinks; `ln -s' creates a wrapper executable. - # In both cases, we have to default to `cp -p'. - ln -s conf$$.file conf$$.dir 2>/dev/null && test ! -f conf$$.exe || +if (echo >conf$$.file) 2>/dev/null; then + if ln -s conf$$.file conf$$ 2>/dev/null; then + as_ln_s='ln -s' + # ... but there are two gotchas: + # 1) On MSYS, both `ln -s file dir' and `ln file dir' fail. + # 2) DJGPP < 2.04 has no symlinks; `ln -s' creates a wrapper executable. + # In both cases, we have to default to `cp -p'. + ln -s conf$$.file conf$$.dir 2>/dev/null && test ! -f conf$$.exe || + as_ln_s='cp -p' + elif ln conf$$.file conf$$ 2>/dev/null; then + as_ln_s=ln + else as_ln_s='cp -p' -elif ln conf$$.file conf$$ 2>/dev/null; then - as_ln_s=ln + fi else as_ln_s='cp -p' fi @@ -532,10 +554,10 @@ as_test_x=' eval sh -c '\'' if test -d "$1"; then - test -d "$1/."; + test -d "$1/."; else case $1 in - -*)set "./$1";; + -*)set "./$1";; esac; case `ls -ld'$as_ls_L_option' "$1" 2>/dev/null` in ???[sx]*):;;*)false;;esac;fi @@ -616,127 +638,159 @@ # include #endif" -ac_subst_vars='SHELL -PATH_SEPARATOR -PACKAGE_NAME -PACKAGE_TARNAME -PACKAGE_VERSION -PACKAGE_STRING -PACKAGE_BUGREPORT -exec_prefix -prefix -program_transform_name -bindir -sbindir -libexecdir -datarootdir -datadir -sysconfdir -sharedstatedir -localstatedir -includedir -oldincludedir -docdir -infodir -htmldir -dvidir -pdfdir -psdir -libdir -localedir -mandir -DEFS -ECHO_C -ECHO_N -ECHO_T -LIBS -build_alias -host_alias -target_alias -VERSION -SOVERSION -CONFIG_ARGS -UNIVERSALSDK -ARCH_RUN_32BIT -LIPO_32BIT_FLAGS -LIPO_64BIT_FLAGS -PYTHONFRAMEWORK -PYTHONFRAMEWORKIDENTIFIER -PYTHONFRAMEWORKDIR -PYTHONFRAMEWORKPREFIX -PYTHONFRAMEWORKINSTALLDIR -FRAMEWORKINSTALLFIRST -FRAMEWORKINSTALLLAST -FRAMEWORKALTINSTALLFIRST -FRAMEWORKALTINSTALLLAST -FRAMEWORKUNIXTOOLSPREFIX -MACHDEP -SGI_ABI -CONFIGURE_MACOSX_DEPLOYMENT_TARGET -EXPORT_MACOSX_DEPLOYMENT_TARGET -CC -CFLAGS -LDFLAGS -CPPFLAGS -ac_ct_CC -EXEEXT -OBJEXT -CXX -MAINCC -CPP -GREP -EGREP -BUILDEXEEXT -LIBRARY -LDLIBRARY -DLLLIBRARY -BLDLIBRARY -LDLIBRARYDIR -INSTSONAME -RUNSHARED -LINKCC -GNULD -RANLIB -AR -ARFLAGS -SVNVERSION -INSTALL_PROGRAM -INSTALL_SCRIPT -INSTALL_DATA -LN -OPT -BASECFLAGS -UNIVERSAL_ARCH_FLAGS -OTHER_LIBTOOL_OPT -LIBTOOL_CRUFT -SO -LDSHARED -BLDSHARED -CCSHARED -LINKFORSHARED -CFLAGSFORSHARED -SHLIBS -USE_SIGNAL_MODULE -SIGNAL_OBJS -USE_THREAD_MODULE -LDLAST -THREADOBJ -DLINCLDIR -DYNLOADFILE -MACHDEP_OBJS -TRUE -LIBOBJS -HAVE_GETHOSTBYNAME_R_6_ARG -HAVE_GETHOSTBYNAME_R_5_ARG -HAVE_GETHOSTBYNAME_R_3_ARG -HAVE_GETHOSTBYNAME_R -HAVE_GETHOSTBYNAME -LIBM -LIBC -THREADHEADERS +ac_subst_vars='LTLIBOBJS SRCDIRS -LTLIBOBJS' +THREADHEADERS +LIBC +LIBM +HAVE_GETHOSTBYNAME +HAVE_GETHOSTBYNAME_R +HAVE_GETHOSTBYNAME_R_3_ARG +HAVE_GETHOSTBYNAME_R_5_ARG +HAVE_GETHOSTBYNAME_R_6_ARG +LIBOBJS +TRUE +MACHDEP_OBJS +DYNLOADFILE +DLINCLDIR +THREADOBJ +LDLAST +USE_THREAD_MODULE +SIGNAL_OBJS +USE_SIGNAL_MODULE +SHLIBS +CFLAGSFORSHARED +LINKFORSHARED +CCSHARED +BLDSHARED +LDSHARED +SO +LIBTOOL_CRUFT +OTHER_LIBTOOL_OPT +UNIVERSAL_ARCH_FLAGS +BASECFLAGS +OPT +LN +INSTALL_DATA +INSTALL_SCRIPT +INSTALL_PROGRAM +SVNVERSION +ARFLAGS +AR +RANLIB +GNULD +LINKCC +RUNSHARED +INSTSONAME +LDLIBRARYDIR +BLDLIBRARY +DLLLIBRARY +LDLIBRARY +LIBRARY +BUILDEXEEXT +EGREP +GREP +CPP +MAINCC +CXX +OBJEXT +EXEEXT +ac_ct_CC +CPPFLAGS +LDFLAGS +CFLAGS +CC +EXPORT_MACOSX_DEPLOYMENT_TARGET +CONFIGURE_MACOSX_DEPLOYMENT_TARGET +SGI_ABI +MACHDEP +FRAMEWORKUNIXTOOLSPREFIX +FRAMEWORKALTINSTALLLAST +FRAMEWORKALTINSTALLFIRST +FRAMEWORKINSTALLLAST +FRAMEWORKINSTALLFIRST +PYTHONFRAMEWORKINSTALLDIR +PYTHONFRAMEWORKPREFIX +PYTHONFRAMEWORKDIR +PYTHONFRAMEWORKIDENTIFIER +PYTHONFRAMEWORK +LIPO_64BIT_FLAGS +LIPO_32BIT_FLAGS +ARCH_RUN_32BIT +UNIVERSALSDK +CONFIG_ARGS +SOVERSION +VERSION +target_alias +host_alias +build_alias +LIBS +ECHO_T +ECHO_N +ECHO_C +DEFS +mandir +localedir +libdir +psdir +pdfdir +dvidir +htmldir +infodir +docdir +oldincludedir +includedir +localstatedir +sharedstatedir +sysconfdir +datadir +datarootdir +libexecdir +sbindir +bindir +program_transform_name +prefix +exec_prefix +PACKAGE_BUGREPORT +PACKAGE_STRING +PACKAGE_VERSION +PACKAGE_TARNAME +PACKAGE_NAME +PATH_SEPARATOR +SHELL' ac_subst_files='' +ac_user_opts=' +enable_option_checking +enable_universalsdk +with_universal_archs +with_framework_name +enable_framework +with_gcc +with_cxx_main +with_suffix +enable_shared +enable_profiling +with_pydebug +with_libs +with_system_ffi +with_dbmliborder +with_signal_module +with_dec_threads +with_threads +with_thread +with_pth +enable_ipv6 +with_doc_strings +with_tsc +with_pymalloc +with_wctype_functions +with_fpectl +with_libm +with_libc +enable_big_digits +with_wide_unicode +with_computed_gotos +' ac_precious_vars='build_alias host_alias target_alias @@ -751,6 +805,8 @@ # Initialize some variables set by options. ac_init_help= ac_init_version=false +ac_unrecognized_opts= +ac_unrecognized_sep= # The variables have the same names as the options, with # dashes changed to underlines. cache_file=/dev/null @@ -849,13 +905,21 @@ datarootdir=$ac_optarg ;; -disable-* | --disable-*) - ac_feature=`expr "x$ac_option" : 'x-*disable-\(.*\)'` + ac_useropt=`expr "x$ac_option" : 'x-*disable-\(.*\)'` # Reject names that are not valid shell variable names. - expr "x$ac_feature" : ".*[^-._$as_cr_alnum]" >/dev/null && - { echo "$as_me: error: invalid feature name: $ac_feature" >&2 + expr "x$ac_useropt" : ".*[^-+._$as_cr_alnum]" >/dev/null && + { $as_echo "$as_me: error: invalid feature name: $ac_useropt" >&2 { (exit 1); exit 1; }; } - ac_feature=`echo $ac_feature | sed 's/[-.]/_/g'` - eval enable_$ac_feature=no ;; + ac_useropt_orig=$ac_useropt + ac_useropt=`$as_echo "$ac_useropt" | sed 's/[-+.]/_/g'` + case $ac_user_opts in + *" +"enable_$ac_useropt" +"*) ;; + *) ac_unrecognized_opts="$ac_unrecognized_opts$ac_unrecognized_sep--disable-$ac_useropt_orig" + ac_unrecognized_sep=', ';; + esac + eval enable_$ac_useropt=no ;; -docdir | --docdir | --docdi | --doc | --do) ac_prev=docdir ;; @@ -868,13 +932,21 @@ dvidir=$ac_optarg ;; -enable-* | --enable-*) - ac_feature=`expr "x$ac_option" : 'x-*enable-\([^=]*\)'` + ac_useropt=`expr "x$ac_option" : 'x-*enable-\([^=]*\)'` # Reject names that are not valid shell variable names. - expr "x$ac_feature" : ".*[^-._$as_cr_alnum]" >/dev/null && - { echo "$as_me: error: invalid feature name: $ac_feature" >&2 + expr "x$ac_useropt" : ".*[^-+._$as_cr_alnum]" >/dev/null && + { $as_echo "$as_me: error: invalid feature name: $ac_useropt" >&2 { (exit 1); exit 1; }; } - ac_feature=`echo $ac_feature | sed 's/[-.]/_/g'` - eval enable_$ac_feature=\$ac_optarg ;; + ac_useropt_orig=$ac_useropt + ac_useropt=`$as_echo "$ac_useropt" | sed 's/[-+.]/_/g'` + case $ac_user_opts in + *" +"enable_$ac_useropt" +"*) ;; + *) ac_unrecognized_opts="$ac_unrecognized_opts$ac_unrecognized_sep--enable-$ac_useropt_orig" + ac_unrecognized_sep=', ';; + esac + eval enable_$ac_useropt=\$ac_optarg ;; -exec-prefix | --exec_prefix | --exec-prefix | --exec-prefi \ | --exec-pref | --exec-pre | --exec-pr | --exec-p | --exec- \ @@ -1065,22 +1137,38 @@ ac_init_version=: ;; -with-* | --with-*) - ac_package=`expr "x$ac_option" : 'x-*with-\([^=]*\)'` + ac_useropt=`expr "x$ac_option" : 'x-*with-\([^=]*\)'` # Reject names that are not valid shell variable names. - expr "x$ac_package" : ".*[^-._$as_cr_alnum]" >/dev/null && - { echo "$as_me: error: invalid package name: $ac_package" >&2 + expr "x$ac_useropt" : ".*[^-+._$as_cr_alnum]" >/dev/null && + { $as_echo "$as_me: error: invalid package name: $ac_useropt" >&2 { (exit 1); exit 1; }; } - ac_package=`echo $ac_package | sed 's/[-.]/_/g'` - eval with_$ac_package=\$ac_optarg ;; + ac_useropt_orig=$ac_useropt + ac_useropt=`$as_echo "$ac_useropt" | sed 's/[-+.]/_/g'` + case $ac_user_opts in + *" +"with_$ac_useropt" +"*) ;; + *) ac_unrecognized_opts="$ac_unrecognized_opts$ac_unrecognized_sep--with-$ac_useropt_orig" + ac_unrecognized_sep=', ';; + esac + eval with_$ac_useropt=\$ac_optarg ;; -without-* | --without-*) - ac_package=`expr "x$ac_option" : 'x-*without-\(.*\)'` + ac_useropt=`expr "x$ac_option" : 'x-*without-\(.*\)'` # Reject names that are not valid shell variable names. - expr "x$ac_package" : ".*[^-._$as_cr_alnum]" >/dev/null && - { echo "$as_me: error: invalid package name: $ac_package" >&2 + expr "x$ac_useropt" : ".*[^-+._$as_cr_alnum]" >/dev/null && + { $as_echo "$as_me: error: invalid package name: $ac_useropt" >&2 { (exit 1); exit 1; }; } - ac_package=`echo $ac_package | sed 's/[-.]/_/g'` - eval with_$ac_package=no ;; + ac_useropt_orig=$ac_useropt + ac_useropt=`$as_echo "$ac_useropt" | sed 's/[-+.]/_/g'` + case $ac_user_opts in + *" +"with_$ac_useropt" +"*) ;; + *) ac_unrecognized_opts="$ac_unrecognized_opts$ac_unrecognized_sep--without-$ac_useropt_orig" + ac_unrecognized_sep=', ';; + esac + eval with_$ac_useropt=no ;; --x) # Obsolete; use --with-x. @@ -1100,7 +1188,7 @@ | --x-librar=* | --x-libra=* | --x-libr=* | --x-lib=* | --x-li=* | --x-l=*) x_libraries=$ac_optarg ;; - -*) { echo "$as_me: error: unrecognized option: $ac_option + -*) { $as_echo "$as_me: error: unrecognized option: $ac_option Try \`$0 --help' for more information." >&2 { (exit 1); exit 1; }; } ;; @@ -1109,16 +1197,16 @@ ac_envvar=`expr "x$ac_option" : 'x\([^=]*\)='` # Reject names that are not valid shell variable names. expr "x$ac_envvar" : ".*[^_$as_cr_alnum]" >/dev/null && - { echo "$as_me: error: invalid variable name: $ac_envvar" >&2 + { $as_echo "$as_me: error: invalid variable name: $ac_envvar" >&2 { (exit 1); exit 1; }; } eval $ac_envvar=\$ac_optarg export $ac_envvar ;; *) # FIXME: should be removed in autoconf 3.0. - echo "$as_me: WARNING: you should use --build, --host, --target" >&2 + $as_echo "$as_me: WARNING: you should use --build, --host, --target" >&2 expr "x$ac_option" : ".*[^-._$as_cr_alnum]" >/dev/null && - echo "$as_me: WARNING: invalid host type: $ac_option" >&2 + $as_echo "$as_me: WARNING: invalid host type: $ac_option" >&2 : ${build_alias=$ac_option} ${host_alias=$ac_option} ${target_alias=$ac_option} ;; @@ -1127,22 +1215,38 @@ if test -n "$ac_prev"; then ac_option=--`echo $ac_prev | sed 's/_/-/g'` - { echo "$as_me: error: missing argument to $ac_option" >&2 + { $as_echo "$as_me: error: missing argument to $ac_option" >&2 { (exit 1); exit 1; }; } fi -# Be sure to have absolute directory names. +if test -n "$ac_unrecognized_opts"; then + case $enable_option_checking in + no) ;; + fatal) { $as_echo "$as_me: error: unrecognized options: $ac_unrecognized_opts" >&2 + { (exit 1); exit 1; }; } ;; + *) $as_echo "$as_me: WARNING: unrecognized options: $ac_unrecognized_opts" >&2 ;; + esac +fi + +# Check all directory arguments for consistency. for ac_var in exec_prefix prefix bindir sbindir libexecdir datarootdir \ datadir sysconfdir sharedstatedir localstatedir includedir \ oldincludedir docdir infodir htmldir dvidir pdfdir psdir \ libdir localedir mandir do eval ac_val=\$$ac_var + # Remove trailing slashes. + case $ac_val in + */ ) + ac_val=`expr "X$ac_val" : 'X\(.*[^/]\)' \| "X$ac_val" : 'X\(.*\)'` + eval $ac_var=\$ac_val;; + esac + # Be sure to have absolute directory names. case $ac_val in [\\/$]* | ?:[\\/]* ) continue;; NONE | '' ) case $ac_var in *prefix ) continue;; esac;; esac - { echo "$as_me: error: expected an absolute directory name for --$ac_var: $ac_val" >&2 + { $as_echo "$as_me: error: expected an absolute directory name for --$ac_var: $ac_val" >&2 { (exit 1); exit 1; }; } done @@ -1157,7 +1261,7 @@ if test "x$host_alias" != x; then if test "x$build_alias" = x; then cross_compiling=maybe - echo "$as_me: WARNING: If you wanted to set the --build type, don't use --host. + $as_echo "$as_me: WARNING: If you wanted to set the --build type, don't use --host. If a cross compiler is detected then cross compile mode will be used." >&2 elif test "x$build_alias" != "x$host_alias"; then cross_compiling=yes @@ -1173,10 +1277,10 @@ ac_pwd=`pwd` && test -n "$ac_pwd" && ac_ls_di=`ls -di .` && ac_pwd_ls_di=`cd "$ac_pwd" && ls -di .` || - { echo "$as_me: error: Working directory cannot be determined" >&2 + { $as_echo "$as_me: error: working directory cannot be determined" >&2 { (exit 1); exit 1; }; } test "X$ac_ls_di" = "X$ac_pwd_ls_di" || - { echo "$as_me: error: pwd does not report name of working directory" >&2 + { $as_echo "$as_me: error: pwd does not report name of working directory" >&2 { (exit 1); exit 1; }; } @@ -1184,12 +1288,12 @@ if test -z "$srcdir"; then ac_srcdir_defaulted=yes # Try the directory containing this script, then the parent directory. - ac_confdir=`$as_dirname -- "$0" || -$as_expr X"$0" : 'X\(.*[^/]\)//*[^/][^/]*/*$' \| \ - X"$0" : 'X\(//\)[^/]' \| \ - X"$0" : 'X\(//\)$' \| \ - X"$0" : 'X\(/\)' \| . 2>/dev/null || -echo X"$0" | + ac_confdir=`$as_dirname -- "$as_myself" || +$as_expr X"$as_myself" : 'X\(.*[^/]\)//*[^/][^/]*/*$' \| \ + X"$as_myself" : 'X\(//\)[^/]' \| \ + X"$as_myself" : 'X\(//\)$' \| \ + X"$as_myself" : 'X\(/\)' \| . 2>/dev/null || +$as_echo X"$as_myself" | sed '/^X\(.*[^/]\)\/\/*[^/][^/]*\/*$/{ s//\1/ q @@ -1216,12 +1320,12 @@ fi if test ! -r "$srcdir/$ac_unique_file"; then test "$ac_srcdir_defaulted" = yes && srcdir="$ac_confdir or .." - { echo "$as_me: error: cannot find sources ($ac_unique_file) in $srcdir" >&2 + { $as_echo "$as_me: error: cannot find sources ($ac_unique_file) in $srcdir" >&2 { (exit 1); exit 1; }; } fi ac_msg="sources are in $srcdir, but \`cd $srcdir' does not work" ac_abs_confdir=`( - cd "$srcdir" && test -r "./$ac_unique_file" || { echo "$as_me: error: $ac_msg" >&2 + cd "$srcdir" && test -r "./$ac_unique_file" || { $as_echo "$as_me: error: $ac_msg" >&2 { (exit 1); exit 1; }; } pwd)` # When building in place, set srcdir=. @@ -1270,9 +1374,9 @@ Installation directories: --prefix=PREFIX install architecture-independent files in PREFIX - [$ac_default_prefix] + [$ac_default_prefix] --exec-prefix=EPREFIX install architecture-dependent files in EPREFIX - [PREFIX] + [PREFIX] By default, \`make install' will install all the files in \`$ac_default_prefix/bin', \`$ac_default_prefix/lib' etc. You can specify @@ -1282,25 +1386,25 @@ For better control, use the options below. Fine tuning of the installation directories: - --bindir=DIR user executables [EPREFIX/bin] - --sbindir=DIR system admin executables [EPREFIX/sbin] - --libexecdir=DIR program executables [EPREFIX/libexec] - --sysconfdir=DIR read-only single-machine data [PREFIX/etc] - --sharedstatedir=DIR modifiable architecture-independent data [PREFIX/com] - --localstatedir=DIR modifiable single-machine data [PREFIX/var] - --libdir=DIR object code libraries [EPREFIX/lib] - --includedir=DIR C header files [PREFIX/include] - --oldincludedir=DIR C header files for non-gcc [/usr/include] - --datarootdir=DIR read-only arch.-independent data root [PREFIX/share] - --datadir=DIR read-only architecture-independent data [DATAROOTDIR] - --infodir=DIR info documentation [DATAROOTDIR/info] - --localedir=DIR locale-dependent data [DATAROOTDIR/locale] - --mandir=DIR man documentation [DATAROOTDIR/man] - --docdir=DIR documentation root [DATAROOTDIR/doc/python] - --htmldir=DIR html documentation [DOCDIR] - --dvidir=DIR dvi documentation [DOCDIR] - --pdfdir=DIR pdf documentation [DOCDIR] - --psdir=DIR ps documentation [DOCDIR] + --bindir=DIR user executables [EPREFIX/bin] + --sbindir=DIR system admin executables [EPREFIX/sbin] + --libexecdir=DIR program executables [EPREFIX/libexec] + --sysconfdir=DIR read-only single-machine data [PREFIX/etc] + --sharedstatedir=DIR modifiable architecture-independent data [PREFIX/com] + --localstatedir=DIR modifiable single-machine data [PREFIX/var] + --libdir=DIR object code libraries [EPREFIX/lib] + --includedir=DIR C header files [PREFIX/include] + --oldincludedir=DIR C header files for non-gcc [/usr/include] + --datarootdir=DIR read-only arch.-independent data root [PREFIX/share] + --datadir=DIR read-only architecture-independent data [DATAROOTDIR] + --infodir=DIR info documentation [DATAROOTDIR/info] + --localedir=DIR locale-dependent data [DATAROOTDIR/locale] + --mandir=DIR man documentation [DATAROOTDIR/man] + --docdir=DIR documentation root [DATAROOTDIR/doc/python] + --htmldir=DIR html documentation [DOCDIR] + --dvidir=DIR dvi documentation [DOCDIR] + --pdfdir=DIR pdf documentation [DOCDIR] + --psdir=DIR ps documentation [DOCDIR] _ACEOF cat <<\_ACEOF @@ -1314,6 +1418,7 @@ cat <<\_ACEOF Optional Features: + --disable-option-checking ignore unrecognized --enable/--with options --disable-FEATURE do not include FEATURE (same as --enable-FEATURE=no) --enable-FEATURE[=ARG] include FEATURE [ARG=yes] --enable-universalsdk[=SDKDIR] @@ -1387,15 +1492,17 @@ if test "$ac_init_help" = "recursive"; then # If there are subdirs, report their specific --help. for ac_dir in : $ac_subdirs_all; do test "x$ac_dir" = x: && continue - test -d "$ac_dir" || continue + test -d "$ac_dir" || + { cd "$srcdir" && ac_pwd=`pwd` && srcdir=. && test -d "$ac_dir"; } || + continue ac_builddir=. case "$ac_dir" in .) ac_dir_suffix= ac_top_builddir_sub=. ac_top_build_prefix= ;; *) - ac_dir_suffix=/`echo "$ac_dir" | sed 's,^\.[\\/],,'` + ac_dir_suffix=/`$as_echo "$ac_dir" | sed 's|^\.[\\/]||'` # A ".." for each directory in $ac_dir_suffix. - ac_top_builddir_sub=`echo "$ac_dir_suffix" | sed 's,/[^\\/]*,/..,g;s,/,,'` + ac_top_builddir_sub=`$as_echo "$ac_dir_suffix" | sed 's|/[^\\/]*|/..|g;s|/||'` case $ac_top_builddir_sub in "") ac_top_builddir_sub=. ac_top_build_prefix= ;; *) ac_top_build_prefix=$ac_top_builddir_sub/ ;; @@ -1431,7 +1538,7 @@ echo && $SHELL "$ac_srcdir/configure" --help=recursive else - echo "$as_me: WARNING: no configuration information is in $ac_dir" >&2 + $as_echo "$as_me: WARNING: no configuration information is in $ac_dir" >&2 fi || ac_status=$? cd "$ac_pwd" || { ac_status=$?; break; } done @@ -1441,10 +1548,10 @@ if $ac_init_version; then cat <<\_ACEOF python configure 3.1 -generated by GNU Autoconf 2.61 +generated by GNU Autoconf 2.63 Copyright (C) 1992, 1993, 1994, 1995, 1996, 1998, 1999, 2000, 2001, -2002, 2003, 2004, 2005, 2006 Free Software Foundation, Inc. +2002, 2003, 2004, 2005, 2006, 2007, 2008 Free Software Foundation, Inc. This configure script is free software; the Free Software Foundation gives unlimited permission to copy, distribute and modify it. _ACEOF @@ -1455,7 +1562,7 @@ running configure, to aid debugging if configure makes a mistake. It was created by python $as_me 3.1, which was -generated by GNU Autoconf 2.61. Invocation command line was +generated by GNU Autoconf 2.63. Invocation command line was $ $0 $@ @@ -1491,7 +1598,7 @@ do IFS=$as_save_IFS test -z "$as_dir" && as_dir=. - echo "PATH: $as_dir" + $as_echo "PATH: $as_dir" done IFS=$as_save_IFS @@ -1526,7 +1633,7 @@ | -silent | --silent | --silen | --sile | --sil) continue ;; *\'*) - ac_arg=`echo "$ac_arg" | sed "s/'/'\\\\\\\\''/g"` ;; + ac_arg=`$as_echo "$ac_arg" | sed "s/'/'\\\\\\\\''/g"` ;; esac case $ac_pass in 1) ac_configure_args0="$ac_configure_args0 '$ac_arg'" ;; @@ -1578,11 +1685,12 @@ case $ac_val in #( *${as_nl}*) case $ac_var in #( - *_cv_*) { echo "$as_me:$LINENO: WARNING: Cache variable $ac_var contains a newline." >&5 -echo "$as_me: WARNING: Cache variable $ac_var contains a newline." >&2;} ;; + *_cv_*) { $as_echo "$as_me:$LINENO: WARNING: cache variable $ac_var contains a newline" >&5 +$as_echo "$as_me: WARNING: cache variable $ac_var contains a newline" >&2;} ;; esac case $ac_var in #( _ | IFS | as_nl) ;; #( + BASH_ARGV | BASH_SOURCE) eval $ac_var= ;; #( *) $as_unset $ac_var ;; esac ;; esac @@ -1612,9 +1720,9 @@ do eval ac_val=\$$ac_var case $ac_val in - *\'\''*) ac_val=`echo "$ac_val" | sed "s/'\''/'\''\\\\\\\\'\'''\''/g"`;; + *\'\''*) ac_val=`$as_echo "$ac_val" | sed "s/'\''/'\''\\\\\\\\'\'''\''/g"`;; esac - echo "$ac_var='\''$ac_val'\''" + $as_echo "$ac_var='\''$ac_val'\''" done | sort echo @@ -1629,9 +1737,9 @@ do eval ac_val=\$$ac_var case $ac_val in - *\'\''*) ac_val=`echo "$ac_val" | sed "s/'\''/'\''\\\\\\\\'\'''\''/g"`;; + *\'\''*) ac_val=`$as_echo "$ac_val" | sed "s/'\''/'\''\\\\\\\\'\'''\''/g"`;; esac - echo "$ac_var='\''$ac_val'\''" + $as_echo "$ac_var='\''$ac_val'\''" done | sort echo fi @@ -1647,8 +1755,8 @@ echo fi test "$ac_signal" != 0 && - echo "$as_me: caught signal $ac_signal" - echo "$as_me: exit $exit_status" + $as_echo "$as_me: caught signal $ac_signal" + $as_echo "$as_me: exit $exit_status" } >&5 rm -f core *.core core.conftest.* && rm -f -r conftest* confdefs* conf$$* $ac_clean_files && @@ -1690,21 +1798,24 @@ # Let the site file select an alternate cache file if it wants to. -# Prefer explicitly selected file to automatically selected ones. +# Prefer an explicitly selected file to automatically selected ones. +ac_site_file1=NONE +ac_site_file2=NONE if test -n "$CONFIG_SITE"; then - set x "$CONFIG_SITE" + ac_site_file1=$CONFIG_SITE elif test "x$prefix" != xNONE; then - set x "$prefix/share/config.site" "$prefix/etc/config.site" + ac_site_file1=$prefix/share/config.site + ac_site_file2=$prefix/etc/config.site else - set x "$ac_default_prefix/share/config.site" \ - "$ac_default_prefix/etc/config.site" + ac_site_file1=$ac_default_prefix/share/config.site + ac_site_file2=$ac_default_prefix/etc/config.site fi -shift -for ac_site_file +for ac_site_file in "$ac_site_file1" "$ac_site_file2" do + test "x$ac_site_file" = xNONE && continue if test -r "$ac_site_file"; then - { echo "$as_me:$LINENO: loading site script $ac_site_file" >&5 -echo "$as_me: loading site script $ac_site_file" >&6;} + { $as_echo "$as_me:$LINENO: loading site script $ac_site_file" >&5 +$as_echo "$as_me: loading site script $ac_site_file" >&6;} sed 's/^/| /' "$ac_site_file" >&5 . "$ac_site_file" fi @@ -1714,16 +1825,16 @@ # Some versions of bash will fail to source /dev/null (special # files actually), so we avoid doing that. if test -f "$cache_file"; then - { echo "$as_me:$LINENO: loading cache $cache_file" >&5 -echo "$as_me: loading cache $cache_file" >&6;} + { $as_echo "$as_me:$LINENO: loading cache $cache_file" >&5 +$as_echo "$as_me: loading cache $cache_file" >&6;} case $cache_file in [\\/]* | ?:[\\/]* ) . "$cache_file";; *) . "./$cache_file";; esac fi else - { echo "$as_me:$LINENO: creating cache $cache_file" >&5 -echo "$as_me: creating cache $cache_file" >&6;} + { $as_echo "$as_me:$LINENO: creating cache $cache_file" >&5 +$as_echo "$as_me: creating cache $cache_file" >&6;} >$cache_file fi @@ -1737,29 +1848,38 @@ eval ac_new_val=\$ac_env_${ac_var}_value case $ac_old_set,$ac_new_set in set,) - { echo "$as_me:$LINENO: error: \`$ac_var' was set to \`$ac_old_val' in the previous run" >&5 -echo "$as_me: error: \`$ac_var' was set to \`$ac_old_val' in the previous run" >&2;} + { $as_echo "$as_me:$LINENO: error: \`$ac_var' was set to \`$ac_old_val' in the previous run" >&5 +$as_echo "$as_me: error: \`$ac_var' was set to \`$ac_old_val' in the previous run" >&2;} ac_cache_corrupted=: ;; ,set) - { echo "$as_me:$LINENO: error: \`$ac_var' was not set in the previous run" >&5 -echo "$as_me: error: \`$ac_var' was not set in the previous run" >&2;} + { $as_echo "$as_me:$LINENO: error: \`$ac_var' was not set in the previous run" >&5 +$as_echo "$as_me: error: \`$ac_var' was not set in the previous run" >&2;} ac_cache_corrupted=: ;; ,);; *) if test "x$ac_old_val" != "x$ac_new_val"; then - { echo "$as_me:$LINENO: error: \`$ac_var' has changed since the previous run:" >&5 -echo "$as_me: error: \`$ac_var' has changed since the previous run:" >&2;} - { echo "$as_me:$LINENO: former value: $ac_old_val" >&5 -echo "$as_me: former value: $ac_old_val" >&2;} - { echo "$as_me:$LINENO: current value: $ac_new_val" >&5 -echo "$as_me: current value: $ac_new_val" >&2;} - ac_cache_corrupted=: + # differences in whitespace do not lead to failure. + ac_old_val_w=`echo x $ac_old_val` + ac_new_val_w=`echo x $ac_new_val` + if test "$ac_old_val_w" != "$ac_new_val_w"; then + { $as_echo "$as_me:$LINENO: error: \`$ac_var' has changed since the previous run:" >&5 +$as_echo "$as_me: error: \`$ac_var' has changed since the previous run:" >&2;} + ac_cache_corrupted=: + else + { $as_echo "$as_me:$LINENO: warning: ignoring whitespace changes in \`$ac_var' since the previous run:" >&5 +$as_echo "$as_me: warning: ignoring whitespace changes in \`$ac_var' since the previous run:" >&2;} + eval $ac_var=\$ac_old_val + fi + { $as_echo "$as_me:$LINENO: former value: \`$ac_old_val'" >&5 +$as_echo "$as_me: former value: \`$ac_old_val'" >&2;} + { $as_echo "$as_me:$LINENO: current value: \`$ac_new_val'" >&5 +$as_echo "$as_me: current value: \`$ac_new_val'" >&2;} fi;; esac # Pass precious variables to config.status. if test "$ac_new_set" = set; then case $ac_new_val in - *\'*) ac_arg=$ac_var=`echo "$ac_new_val" | sed "s/'/'\\\\\\\\''/g"` ;; + *\'*) ac_arg=$ac_var=`$as_echo "$ac_new_val" | sed "s/'/'\\\\\\\\''/g"` ;; *) ac_arg=$ac_var=$ac_new_val ;; esac case " $ac_configure_args " in @@ -1769,10 +1889,12 @@ fi done if $ac_cache_corrupted; then - { echo "$as_me:$LINENO: error: changes in the environment can compromise the build" >&5 -echo "$as_me: error: changes in the environment can compromise the build" >&2;} - { { echo "$as_me:$LINENO: error: run \`make distclean' and/or \`rm $cache_file' and start over" >&5 -echo "$as_me: error: run \`make distclean' and/or \`rm $cache_file' and start over" >&2;} + { $as_echo "$as_me:$LINENO: error: in \`$ac_pwd':" >&5 +$as_echo "$as_me: error: in \`$ac_pwd':" >&2;} + { $as_echo "$as_me:$LINENO: error: changes in the environment can compromise the build" >&5 +$as_echo "$as_me: error: changes in the environment can compromise the build" >&2;} + { { $as_echo "$as_me:$LINENO: error: run \`make distclean' and/or \`rm $cache_file' and start over" >&5 +$as_echo "$as_me: error: run \`make distclean' and/or \`rm $cache_file' and start over" >&2;} { (exit 1); exit 1; }; } fi @@ -1883,8 +2005,8 @@ CONFIG_ARGS="$ac_configure_args" -{ echo "$as_me:$LINENO: checking for --enable-universalsdk" >&5 -echo $ECHO_N "checking for --enable-universalsdk... $ECHO_C" >&6; } +{ $as_echo "$as_me:$LINENO: checking for --enable-universalsdk" >&5 +$as_echo_n "checking for --enable-universalsdk... " >&6; } # Check whether --enable-universalsdk was given. if test "${enable_universalsdk+set}" = set; then enableval=$enable_universalsdk; @@ -1906,8 +2028,8 @@ UNIVERSALSDK=$enableval if test ! -d "${UNIVERSALSDK}" then - { { echo "$as_me:$LINENO: error: --enable-universalsdk specifies non-existing SDK: ${UNIVERSALSDK}" >&5 -echo "$as_me: error: --enable-universalsdk specifies non-existing SDK: ${UNIVERSALSDK}" >&2;} + { { $as_echo "$as_me:$LINENO: error: --enable-universalsdk specifies non-existing SDK: ${UNIVERSALSDK}" >&5 +$as_echo "$as_me: error: --enable-universalsdk specifies non-existing SDK: ${UNIVERSALSDK}" >&2;} { (exit 1); exit 1; }; } fi ;; @@ -1923,11 +2045,11 @@ if test -n "${UNIVERSALSDK}" then - { echo "$as_me:$LINENO: result: ${UNIVERSALSDK}" >&5 -echo "${ECHO_T}${UNIVERSALSDK}" >&6; } + { $as_echo "$as_me:$LINENO: result: ${UNIVERSALSDK}" >&5 +$as_echo "${UNIVERSALSDK}" >&6; } else - { echo "$as_me:$LINENO: result: no" >&5 -echo "${ECHO_T}no" >&6; } + { $as_echo "$as_me:$LINENO: result: no" >&5 +$as_echo "no" >&6; } fi @@ -1936,20 +2058,20 @@ UNIVERSAL_ARCHS="32-bit" -{ echo "$as_me:$LINENO: checking for --with-universal-archs" >&5 -echo $ECHO_N "checking for --with-universal-archs... $ECHO_C" >&6; } +{ $as_echo "$as_me:$LINENO: checking for --with-universal-archs" >&5 +$as_echo_n "checking for --with-universal-archs... " >&6; } # Check whether --with-universal-archs was given. if test "${with_universal_archs+set}" = set; then withval=$with_universal_archs; - { echo "$as_me:$LINENO: result: $withval" >&5 -echo "${ECHO_T}$withval" >&6; } + { $as_echo "$as_me:$LINENO: result: $withval" >&5 +$as_echo "$withval" >&6; } UNIVERSAL_ARCHS="$withval" else - { echo "$as_me:$LINENO: result: 32-bit" >&5 -echo "${ECHO_T}32-bit" >&6; } + { $as_echo "$as_me:$LINENO: result: 32-bit" >&5 +$as_echo "32-bit" >&6; } fi @@ -2073,8 +2195,8 @@ ## # Set name for machine-dependent library files -{ echo "$as_me:$LINENO: checking MACHDEP" >&5 -echo $ECHO_N "checking MACHDEP... $ECHO_C" >&6; } +{ $as_echo "$as_me:$LINENO: checking MACHDEP" >&5 +$as_echo_n "checking MACHDEP... " >&6; } if test -z "$MACHDEP" then ac_sys_system=`uname -s` @@ -2251,8 +2373,8 @@ LDFLAGS="$SGI_ABI $LDFLAGS" MACHDEP=`echo "${MACHDEP}${SGI_ABI}" | sed 's/ *//g'` fi -{ echo "$as_me:$LINENO: result: $MACHDEP" >&5 -echo "${ECHO_T}$MACHDEP" >&6; } +{ $as_echo "$as_me:$LINENO: result: $MACHDEP" >&5 +$as_echo "$MACHDEP" >&6; } # Record the configure-time value of MACOSX_DEPLOYMENT_TARGET, # it may influence the way we can build extensions, so distutils @@ -2262,11 +2384,11 @@ CONFIGURE_MACOSX_DEPLOYMENT_TARGET= EXPORT_MACOSX_DEPLOYMENT_TARGET='#' -{ echo "$as_me:$LINENO: checking machine type as reported by uname -m" >&5 -echo $ECHO_N "checking machine type as reported by uname -m... $ECHO_C" >&6; } +{ $as_echo "$as_me:$LINENO: checking machine type as reported by uname -m" >&5 +$as_echo_n "checking machine type as reported by uname -m... " >&6; } ac_sys_machine=`uname -m` -{ echo "$as_me:$LINENO: result: $ac_sys_machine" >&5 -echo "${ECHO_T}$ac_sys_machine" >&6; } +{ $as_echo "$as_me:$LINENO: result: $ac_sys_machine" >&5 +$as_echo "$ac_sys_machine" >&6; } # checks for alternative programs @@ -2278,8 +2400,8 @@ # XXX shouldn't some/most/all of this code be merged with the stuff later # on that fiddles with OPT and BASECFLAGS? -{ echo "$as_me:$LINENO: checking for --without-gcc" >&5 -echo $ECHO_N "checking for --without-gcc... $ECHO_C" >&6; } +{ $as_echo "$as_me:$LINENO: checking for --without-gcc" >&5 +$as_echo_n "checking for --without-gcc... " >&6; } # Check whether --with-gcc was given. if test "${with_gcc+set}" = set; then @@ -2301,15 +2423,15 @@ esac fi -{ echo "$as_me:$LINENO: result: $without_gcc" >&5 -echo "${ECHO_T}$without_gcc" >&6; } +{ $as_echo "$as_me:$LINENO: result: $without_gcc" >&5 +$as_echo "$without_gcc" >&6; } # If the user switches compilers, we can't believe the cache if test ! -z "$ac_cv_prog_CC" -a ! -z "$CC" -a "$CC" != "$ac_cv_prog_CC" then - { { echo "$as_me:$LINENO: error: cached CC is different -- throw away $cache_file + { { $as_echo "$as_me:$LINENO: error: cached CC is different -- throw away $cache_file (it is also a good idea to do 'make clean' before compiling)" >&5 -echo "$as_me: error: cached CC is different -- throw away $cache_file +$as_echo "$as_me: error: cached CC is different -- throw away $cache_file (it is also a good idea to do 'make clean' before compiling)" >&2;} { (exit 1); exit 1; }; } fi @@ -2322,10 +2444,10 @@ if test -n "$ac_tool_prefix"; then # Extract the first word of "${ac_tool_prefix}gcc", so it can be a program name with args. set dummy ${ac_tool_prefix}gcc; ac_word=$2 -{ echo "$as_me:$LINENO: checking for $ac_word" >&5 -echo $ECHO_N "checking for $ac_word... $ECHO_C" >&6; } +{ $as_echo "$as_me:$LINENO: checking for $ac_word" >&5 +$as_echo_n "checking for $ac_word... " >&6; } if test "${ac_cv_prog_CC+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 + $as_echo_n "(cached) " >&6 else if test -n "$CC"; then ac_cv_prog_CC="$CC" # Let the user override the test. @@ -2338,7 +2460,7 @@ for ac_exec_ext in '' $ac_executable_extensions; do if { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_test_x "$as_dir/$ac_word$ac_exec_ext"; }; then ac_cv_prog_CC="${ac_tool_prefix}gcc" - echo "$as_me:$LINENO: found $as_dir/$ac_word$ac_exec_ext" >&5 + $as_echo "$as_me:$LINENO: found $as_dir/$ac_word$ac_exec_ext" >&5 break 2 fi done @@ -2349,11 +2471,11 @@ fi CC=$ac_cv_prog_CC if test -n "$CC"; then - { echo "$as_me:$LINENO: result: $CC" >&5 -echo "${ECHO_T}$CC" >&6; } + { $as_echo "$as_me:$LINENO: result: $CC" >&5 +$as_echo "$CC" >&6; } else - { echo "$as_me:$LINENO: result: no" >&5 -echo "${ECHO_T}no" >&6; } + { $as_echo "$as_me:$LINENO: result: no" >&5 +$as_echo "no" >&6; } fi @@ -2362,10 +2484,10 @@ ac_ct_CC=$CC # Extract the first word of "gcc", so it can be a program name with args. set dummy gcc; ac_word=$2 -{ echo "$as_me:$LINENO: checking for $ac_word" >&5 -echo $ECHO_N "checking for $ac_word... $ECHO_C" >&6; } +{ $as_echo "$as_me:$LINENO: checking for $ac_word" >&5 +$as_echo_n "checking for $ac_word... " >&6; } if test "${ac_cv_prog_ac_ct_CC+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 + $as_echo_n "(cached) " >&6 else if test -n "$ac_ct_CC"; then ac_cv_prog_ac_ct_CC="$ac_ct_CC" # Let the user override the test. @@ -2378,7 +2500,7 @@ for ac_exec_ext in '' $ac_executable_extensions; do if { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_test_x "$as_dir/$ac_word$ac_exec_ext"; }; then ac_cv_prog_ac_ct_CC="gcc" - echo "$as_me:$LINENO: found $as_dir/$ac_word$ac_exec_ext" >&5 + $as_echo "$as_me:$LINENO: found $as_dir/$ac_word$ac_exec_ext" >&5 break 2 fi done @@ -2389,11 +2511,11 @@ fi ac_ct_CC=$ac_cv_prog_ac_ct_CC if test -n "$ac_ct_CC"; then - { echo "$as_me:$LINENO: result: $ac_ct_CC" >&5 -echo "${ECHO_T}$ac_ct_CC" >&6; } + { $as_echo "$as_me:$LINENO: result: $ac_ct_CC" >&5 +$as_echo "$ac_ct_CC" >&6; } else - { echo "$as_me:$LINENO: result: no" >&5 -echo "${ECHO_T}no" >&6; } + { $as_echo "$as_me:$LINENO: result: no" >&5 +$as_echo "no" >&6; } fi if test "x$ac_ct_CC" = x; then @@ -2401,12 +2523,8 @@ else case $cross_compiling:$ac_tool_warned in yes:) -{ echo "$as_me:$LINENO: WARNING: In the future, Autoconf will not detect cross-tools -whose name does not start with the host triplet. If you think this -configuration is useful to you, please write to autoconf at gnu.org." >&5 -echo "$as_me: WARNING: In the future, Autoconf will not detect cross-tools -whose name does not start with the host triplet. If you think this -configuration is useful to you, please write to autoconf at gnu.org." >&2;} +{ $as_echo "$as_me:$LINENO: WARNING: using cross tools not prefixed with host triplet" >&5 +$as_echo "$as_me: WARNING: using cross tools not prefixed with host triplet" >&2;} ac_tool_warned=yes ;; esac CC=$ac_ct_CC @@ -2419,10 +2537,10 @@ if test -n "$ac_tool_prefix"; then # Extract the first word of "${ac_tool_prefix}cc", so it can be a program name with args. set dummy ${ac_tool_prefix}cc; ac_word=$2 -{ echo "$as_me:$LINENO: checking for $ac_word" >&5 -echo $ECHO_N "checking for $ac_word... $ECHO_C" >&6; } +{ $as_echo "$as_me:$LINENO: checking for $ac_word" >&5 +$as_echo_n "checking for $ac_word... " >&6; } if test "${ac_cv_prog_CC+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 + $as_echo_n "(cached) " >&6 else if test -n "$CC"; then ac_cv_prog_CC="$CC" # Let the user override the test. @@ -2435,7 +2553,7 @@ for ac_exec_ext in '' $ac_executable_extensions; do if { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_test_x "$as_dir/$ac_word$ac_exec_ext"; }; then ac_cv_prog_CC="${ac_tool_prefix}cc" - echo "$as_me:$LINENO: found $as_dir/$ac_word$ac_exec_ext" >&5 + $as_echo "$as_me:$LINENO: found $as_dir/$ac_word$ac_exec_ext" >&5 break 2 fi done @@ -2446,11 +2564,11 @@ fi CC=$ac_cv_prog_CC if test -n "$CC"; then - { echo "$as_me:$LINENO: result: $CC" >&5 -echo "${ECHO_T}$CC" >&6; } + { $as_echo "$as_me:$LINENO: result: $CC" >&5 +$as_echo "$CC" >&6; } else - { echo "$as_me:$LINENO: result: no" >&5 -echo "${ECHO_T}no" >&6; } + { $as_echo "$as_me:$LINENO: result: no" >&5 +$as_echo "no" >&6; } fi @@ -2459,10 +2577,10 @@ if test -z "$CC"; then # Extract the first word of "cc", so it can be a program name with args. set dummy cc; ac_word=$2 -{ echo "$as_me:$LINENO: checking for $ac_word" >&5 -echo $ECHO_N "checking for $ac_word... $ECHO_C" >&6; } +{ $as_echo "$as_me:$LINENO: checking for $ac_word" >&5 +$as_echo_n "checking for $ac_word... " >&6; } if test "${ac_cv_prog_CC+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 + $as_echo_n "(cached) " >&6 else if test -n "$CC"; then ac_cv_prog_CC="$CC" # Let the user override the test. @@ -2480,7 +2598,7 @@ continue fi ac_cv_prog_CC="cc" - echo "$as_me:$LINENO: found $as_dir/$ac_word$ac_exec_ext" >&5 + $as_echo "$as_me:$LINENO: found $as_dir/$ac_word$ac_exec_ext" >&5 break 2 fi done @@ -2503,11 +2621,11 @@ fi CC=$ac_cv_prog_CC if test -n "$CC"; then - { echo "$as_me:$LINENO: result: $CC" >&5 -echo "${ECHO_T}$CC" >&6; } + { $as_echo "$as_me:$LINENO: result: $CC" >&5 +$as_echo "$CC" >&6; } else - { echo "$as_me:$LINENO: result: no" >&5 -echo "${ECHO_T}no" >&6; } + { $as_echo "$as_me:$LINENO: result: no" >&5 +$as_echo "no" >&6; } fi @@ -2518,10 +2636,10 @@ do # Extract the first word of "$ac_tool_prefix$ac_prog", so it can be a program name with args. set dummy $ac_tool_prefix$ac_prog; ac_word=$2 -{ echo "$as_me:$LINENO: checking for $ac_word" >&5 -echo $ECHO_N "checking for $ac_word... $ECHO_C" >&6; } +{ $as_echo "$as_me:$LINENO: checking for $ac_word" >&5 +$as_echo_n "checking for $ac_word... " >&6; } if test "${ac_cv_prog_CC+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 + $as_echo_n "(cached) " >&6 else if test -n "$CC"; then ac_cv_prog_CC="$CC" # Let the user override the test. @@ -2534,7 +2652,7 @@ for ac_exec_ext in '' $ac_executable_extensions; do if { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_test_x "$as_dir/$ac_word$ac_exec_ext"; }; then ac_cv_prog_CC="$ac_tool_prefix$ac_prog" - echo "$as_me:$LINENO: found $as_dir/$ac_word$ac_exec_ext" >&5 + $as_echo "$as_me:$LINENO: found $as_dir/$ac_word$ac_exec_ext" >&5 break 2 fi done @@ -2545,11 +2663,11 @@ fi CC=$ac_cv_prog_CC if test -n "$CC"; then - { echo "$as_me:$LINENO: result: $CC" >&5 -echo "${ECHO_T}$CC" >&6; } + { $as_echo "$as_me:$LINENO: result: $CC" >&5 +$as_echo "$CC" >&6; } else - { echo "$as_me:$LINENO: result: no" >&5 -echo "${ECHO_T}no" >&6; } + { $as_echo "$as_me:$LINENO: result: no" >&5 +$as_echo "no" >&6; } fi @@ -2562,10 +2680,10 @@ do # Extract the first word of "$ac_prog", so it can be a program name with args. set dummy $ac_prog; ac_word=$2 -{ echo "$as_me:$LINENO: checking for $ac_word" >&5 -echo $ECHO_N "checking for $ac_word... $ECHO_C" >&6; } +{ $as_echo "$as_me:$LINENO: checking for $ac_word" >&5 +$as_echo_n "checking for $ac_word... " >&6; } if test "${ac_cv_prog_ac_ct_CC+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 + $as_echo_n "(cached) " >&6 else if test -n "$ac_ct_CC"; then ac_cv_prog_ac_ct_CC="$ac_ct_CC" # Let the user override the test. @@ -2578,7 +2696,7 @@ for ac_exec_ext in '' $ac_executable_extensions; do if { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_test_x "$as_dir/$ac_word$ac_exec_ext"; }; then ac_cv_prog_ac_ct_CC="$ac_prog" - echo "$as_me:$LINENO: found $as_dir/$ac_word$ac_exec_ext" >&5 + $as_echo "$as_me:$LINENO: found $as_dir/$ac_word$ac_exec_ext" >&5 break 2 fi done @@ -2589,11 +2707,11 @@ fi ac_ct_CC=$ac_cv_prog_ac_ct_CC if test -n "$ac_ct_CC"; then - { echo "$as_me:$LINENO: result: $ac_ct_CC" >&5 -echo "${ECHO_T}$ac_ct_CC" >&6; } + { $as_echo "$as_me:$LINENO: result: $ac_ct_CC" >&5 +$as_echo "$ac_ct_CC" >&6; } else - { echo "$as_me:$LINENO: result: no" >&5 -echo "${ECHO_T}no" >&6; } + { $as_echo "$as_me:$LINENO: result: no" >&5 +$as_echo "no" >&6; } fi @@ -2605,12 +2723,8 @@ else case $cross_compiling:$ac_tool_warned in yes:) -{ echo "$as_me:$LINENO: WARNING: In the future, Autoconf will not detect cross-tools -whose name does not start with the host triplet. If you think this -configuration is useful to you, please write to autoconf at gnu.org." >&5 -echo "$as_me: WARNING: In the future, Autoconf will not detect cross-tools -whose name does not start with the host triplet. If you think this -configuration is useful to you, please write to autoconf at gnu.org." >&2;} +{ $as_echo "$as_me:$LINENO: WARNING: using cross tools not prefixed with host triplet" >&5 +$as_echo "$as_me: WARNING: using cross tools not prefixed with host triplet" >&2;} ac_tool_warned=yes ;; esac CC=$ac_ct_CC @@ -2620,44 +2734,50 @@ fi -test -z "$CC" && { { echo "$as_me:$LINENO: error: no acceptable C compiler found in \$PATH +test -z "$CC" && { { $as_echo "$as_me:$LINENO: error: in \`$ac_pwd':" >&5 +$as_echo "$as_me: error: in \`$ac_pwd':" >&2;} +{ { $as_echo "$as_me:$LINENO: error: no acceptable C compiler found in \$PATH See \`config.log' for more details." >&5 -echo "$as_me: error: no acceptable C compiler found in \$PATH +$as_echo "$as_me: error: no acceptable C compiler found in \$PATH See \`config.log' for more details." >&2;} - { (exit 1); exit 1; }; } + { (exit 1); exit 1; }; }; } # Provide some information about the compiler. -echo "$as_me:$LINENO: checking for C compiler version" >&5 -ac_compiler=`set X $ac_compile; echo $2` +$as_echo "$as_me:$LINENO: checking for C compiler version" >&5 +set X $ac_compile +ac_compiler=$2 { (ac_try="$ac_compiler --version >&5" case "(($ac_try" in *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_compiler --version >&5") 2>&5 ac_status=$? - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } { (ac_try="$ac_compiler -v >&5" case "(($ac_try" in *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_compiler -v >&5") 2>&5 ac_status=$? - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } { (ac_try="$ac_compiler -V >&5" case "(($ac_try" in *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_compiler -V >&5") 2>&5 ac_status=$? - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } cat >conftest.$ac_ext <<_ACEOF @@ -2676,27 +2796,22 @@ } _ACEOF ac_clean_files_save=$ac_clean_files -ac_clean_files="$ac_clean_files a.out a.exe b.out" +ac_clean_files="$ac_clean_files a.out a.out.dSYM a.exe b.out" # Try to create an executable without -o first, disregard a.out. # It will help us diagnose broken compilers, and finding out an intuition # of exeext. -{ echo "$as_me:$LINENO: checking for C compiler default output file name" >&5 -echo $ECHO_N "checking for C compiler default output file name... $ECHO_C" >&6; } -ac_link_default=`echo "$ac_link" | sed 's/ -o *conftest[^ ]*//'` -# -# List of possible output files, starting from the most likely. -# The algorithm is not robust to junk in `.', hence go to wildcards (a.*) -# only as a last resort. b.out is created by i960 compilers. -ac_files='a_out.exe a.exe conftest.exe a.out conftest a.* conftest.* b.out' -# -# The IRIX 6 linker writes into existing files which may not be -# executable, retaining their permissions. Remove them first so a -# subsequent execution test works. +{ $as_echo "$as_me:$LINENO: checking for C compiler default output file name" >&5 +$as_echo_n "checking for C compiler default output file name... " >&6; } +ac_link_default=`$as_echo "$ac_link" | sed 's/ -o *conftest[^ ]*//'` + +# The possible output files: +ac_files="a.out conftest.exe conftest a.exe a_out.exe b.out conftest.*" + ac_rmfiles= for ac_file in $ac_files do case $ac_file in - *.$ac_ext | *.xcoff | *.tds | *.d | *.pdb | *.xSYM | *.bb | *.bbg | *.map | *.inf | *.o | *.obj ) ;; + *.$ac_ext | *.xcoff | *.tds | *.d | *.pdb | *.xSYM | *.bb | *.bbg | *.map | *.inf | *.dSYM | *.o | *.obj ) ;; * ) ac_rmfiles="$ac_rmfiles $ac_file";; esac done @@ -2707,10 +2822,11 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_link_default") 2>&5 ac_status=$? - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); }; then # Autoconf-2.13 could set the ac_cv_exeext variable to `no'. # So ignore a value of `no', otherwise this would lead to `EXEEXT = no' @@ -2721,7 +2837,7 @@ do test -f "$ac_file" || continue case $ac_file in - *.$ac_ext | *.xcoff | *.tds | *.d | *.pdb | *.xSYM | *.bb | *.bbg | *.map | *.inf | *.o | *.obj ) + *.$ac_ext | *.xcoff | *.tds | *.d | *.pdb | *.xSYM | *.bb | *.bbg | *.map | *.inf | *.dSYM | *.o | *.obj ) ;; [ab].out ) # We found the default executable, but exeext='' is most @@ -2748,25 +2864,27 @@ ac_file='' fi -{ echo "$as_me:$LINENO: result: $ac_file" >&5 -echo "${ECHO_T}$ac_file" >&6; } +{ $as_echo "$as_me:$LINENO: result: $ac_file" >&5 +$as_echo "$ac_file" >&6; } if test -z "$ac_file"; then - echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 -{ { echo "$as_me:$LINENO: error: C compiler cannot create executables +{ { $as_echo "$as_me:$LINENO: error: in \`$ac_pwd':" >&5 +$as_echo "$as_me: error: in \`$ac_pwd':" >&2;} +{ { $as_echo "$as_me:$LINENO: error: C compiler cannot create executables See \`config.log' for more details." >&5 -echo "$as_me: error: C compiler cannot create executables +$as_echo "$as_me: error: C compiler cannot create executables See \`config.log' for more details." >&2;} - { (exit 77); exit 77; }; } + { (exit 77); exit 77; }; }; } fi ac_exeext=$ac_cv_exeext # Check that the compiler produces executables we can run. If not, either # the compiler is broken, or we cross compile. -{ echo "$as_me:$LINENO: checking whether the C compiler works" >&5 -echo $ECHO_N "checking whether the C compiler works... $ECHO_C" >&6; } +{ $as_echo "$as_me:$LINENO: checking whether the C compiler works" >&5 +$as_echo_n "checking whether the C compiler works... " >&6; } # FIXME: These cross compiler hacks should be removed for Autoconf 3.0 # If not cross compiling, check that we can run a simple program. if test "$cross_compiling" != yes; then @@ -2775,49 +2893,53 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_try") 2>&5 ac_status=$? - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); }; }; then cross_compiling=no else if test "$cross_compiling" = maybe; then cross_compiling=yes else - { { echo "$as_me:$LINENO: error: cannot run C compiled programs. + { { $as_echo "$as_me:$LINENO: error: in \`$ac_pwd':" >&5 +$as_echo "$as_me: error: in \`$ac_pwd':" >&2;} +{ { $as_echo "$as_me:$LINENO: error: cannot run C compiled programs. If you meant to cross compile, use \`--host'. See \`config.log' for more details." >&5 -echo "$as_me: error: cannot run C compiled programs. +$as_echo "$as_me: error: cannot run C compiled programs. If you meant to cross compile, use \`--host'. See \`config.log' for more details." >&2;} - { (exit 1); exit 1; }; } + { (exit 1); exit 1; }; }; } fi fi fi -{ echo "$as_me:$LINENO: result: yes" >&5 -echo "${ECHO_T}yes" >&6; } +{ $as_echo "$as_me:$LINENO: result: yes" >&5 +$as_echo "yes" >&6; } -rm -f a.out a.exe conftest$ac_cv_exeext b.out +rm -f -r a.out a.out.dSYM a.exe conftest$ac_cv_exeext b.out ac_clean_files=$ac_clean_files_save # Check that the compiler produces executables we can run. If not, either # the compiler is broken, or we cross compile. -{ echo "$as_me:$LINENO: checking whether we are cross compiling" >&5 -echo $ECHO_N "checking whether we are cross compiling... $ECHO_C" >&6; } -{ echo "$as_me:$LINENO: result: $cross_compiling" >&5 -echo "${ECHO_T}$cross_compiling" >&6; } +{ $as_echo "$as_me:$LINENO: checking whether we are cross compiling" >&5 +$as_echo_n "checking whether we are cross compiling... " >&6; } +{ $as_echo "$as_me:$LINENO: result: $cross_compiling" >&5 +$as_echo "$cross_compiling" >&6; } -{ echo "$as_me:$LINENO: checking for suffix of executables" >&5 -echo $ECHO_N "checking for suffix of executables... $ECHO_C" >&6; } +{ $as_echo "$as_me:$LINENO: checking for suffix of executables" >&5 +$as_echo_n "checking for suffix of executables... " >&6; } if { (ac_try="$ac_link" case "(($ac_try" in *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_link") 2>&5 ac_status=$? - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); }; then # If both `conftest.exe' and `conftest' are `present' (well, observable) # catch `conftest.exe'. For instance with Cygwin, `ls conftest' will @@ -2826,31 +2948,33 @@ for ac_file in conftest.exe conftest conftest.*; do test -f "$ac_file" || continue case $ac_file in - *.$ac_ext | *.xcoff | *.tds | *.d | *.pdb | *.xSYM | *.bb | *.bbg | *.map | *.inf | *.o | *.obj ) ;; + *.$ac_ext | *.xcoff | *.tds | *.d | *.pdb | *.xSYM | *.bb | *.bbg | *.map | *.inf | *.dSYM | *.o | *.obj ) ;; *.* ) ac_cv_exeext=`expr "$ac_file" : '[^.]*\(\..*\)'` break;; * ) break;; esac done else - { { echo "$as_me:$LINENO: error: cannot compute suffix of executables: cannot compile and link + { { $as_echo "$as_me:$LINENO: error: in \`$ac_pwd':" >&5 +$as_echo "$as_me: error: in \`$ac_pwd':" >&2;} +{ { $as_echo "$as_me:$LINENO: error: cannot compute suffix of executables: cannot compile and link See \`config.log' for more details." >&5 -echo "$as_me: error: cannot compute suffix of executables: cannot compile and link +$as_echo "$as_me: error: cannot compute suffix of executables: cannot compile and link See \`config.log' for more details." >&2;} - { (exit 1); exit 1; }; } + { (exit 1); exit 1; }; }; } fi rm -f conftest$ac_cv_exeext -{ echo "$as_me:$LINENO: result: $ac_cv_exeext" >&5 -echo "${ECHO_T}$ac_cv_exeext" >&6; } +{ $as_echo "$as_me:$LINENO: result: $ac_cv_exeext" >&5 +$as_echo "$ac_cv_exeext" >&6; } rm -f conftest.$ac_ext EXEEXT=$ac_cv_exeext ac_exeext=$EXEEXT -{ echo "$as_me:$LINENO: checking for suffix of object files" >&5 -echo $ECHO_N "checking for suffix of object files... $ECHO_C" >&6; } +{ $as_echo "$as_me:$LINENO: checking for suffix of object files" >&5 +$as_echo_n "checking for suffix of object files... " >&6; } if test "${ac_cv_objext+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 + $as_echo_n "(cached) " >&6 else cat >conftest.$ac_ext <<_ACEOF /* confdefs.h. */ @@ -2873,40 +2997,43 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_compile") 2>&5 ac_status=$? - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); }; then for ac_file in conftest.o conftest.obj conftest.*; do test -f "$ac_file" || continue; case $ac_file in - *.$ac_ext | *.xcoff | *.tds | *.d | *.pdb | *.xSYM | *.bb | *.bbg | *.map | *.inf ) ;; + *.$ac_ext | *.xcoff | *.tds | *.d | *.pdb | *.xSYM | *.bb | *.bbg | *.map | *.inf | *.dSYM ) ;; *) ac_cv_objext=`expr "$ac_file" : '.*\.\(.*\)'` break;; esac done else - echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 -{ { echo "$as_me:$LINENO: error: cannot compute suffix of object files: cannot compile +{ { $as_echo "$as_me:$LINENO: error: in \`$ac_pwd':" >&5 +$as_echo "$as_me: error: in \`$ac_pwd':" >&2;} +{ { $as_echo "$as_me:$LINENO: error: cannot compute suffix of object files: cannot compile See \`config.log' for more details." >&5 -echo "$as_me: error: cannot compute suffix of object files: cannot compile +$as_echo "$as_me: error: cannot compute suffix of object files: cannot compile See \`config.log' for more details." >&2;} - { (exit 1); exit 1; }; } + { (exit 1); exit 1; }; }; } fi rm -f conftest.$ac_cv_objext conftest.$ac_ext fi -{ echo "$as_me:$LINENO: result: $ac_cv_objext" >&5 -echo "${ECHO_T}$ac_cv_objext" >&6; } +{ $as_echo "$as_me:$LINENO: result: $ac_cv_objext" >&5 +$as_echo "$ac_cv_objext" >&6; } OBJEXT=$ac_cv_objext ac_objext=$OBJEXT -{ echo "$as_me:$LINENO: checking whether we are using the GNU C compiler" >&5 -echo $ECHO_N "checking whether we are using the GNU C compiler... $ECHO_C" >&6; } +{ $as_echo "$as_me:$LINENO: checking whether we are using the GNU C compiler" >&5 +$as_echo_n "checking whether we are using the GNU C compiler... " >&6; } if test "${ac_cv_c_compiler_gnu+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 + $as_echo_n "(cached) " >&6 else cat >conftest.$ac_ext <<_ACEOF /* confdefs.h. */ @@ -2932,20 +3059,21 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_compile") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { test -z "$ac_c_werror_flag" || test ! -s conftest.err } && test -s conftest.$ac_objext; then ac_compiler_gnu=yes else - echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 ac_compiler_gnu=no @@ -2955,15 +3083,19 @@ ac_cv_c_compiler_gnu=$ac_compiler_gnu fi -{ echo "$as_me:$LINENO: result: $ac_cv_c_compiler_gnu" >&5 -echo "${ECHO_T}$ac_cv_c_compiler_gnu" >&6; } -GCC=`test $ac_compiler_gnu = yes && echo yes` +{ $as_echo "$as_me:$LINENO: result: $ac_cv_c_compiler_gnu" >&5 +$as_echo "$ac_cv_c_compiler_gnu" >&6; } +if test $ac_compiler_gnu = yes; then + GCC=yes +else + GCC= +fi ac_test_CFLAGS=${CFLAGS+set} ac_save_CFLAGS=$CFLAGS -{ echo "$as_me:$LINENO: checking whether $CC accepts -g" >&5 -echo $ECHO_N "checking whether $CC accepts -g... $ECHO_C" >&6; } +{ $as_echo "$as_me:$LINENO: checking whether $CC accepts -g" >&5 +$as_echo_n "checking whether $CC accepts -g... " >&6; } if test "${ac_cv_prog_cc_g+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 + $as_echo_n "(cached) " >&6 else ac_save_c_werror_flag=$ac_c_werror_flag ac_c_werror_flag=yes @@ -2990,20 +3122,21 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_compile") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { test -z "$ac_c_werror_flag" || test ! -s conftest.err } && test -s conftest.$ac_objext; then ac_cv_prog_cc_g=yes else - echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 CFLAGS="" @@ -3028,20 +3161,21 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_compile") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { test -z "$ac_c_werror_flag" || test ! -s conftest.err } && test -s conftest.$ac_objext; then : else - echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 ac_c_werror_flag=$ac_save_c_werror_flag @@ -3067,20 +3201,21 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_compile") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { test -z "$ac_c_werror_flag" || test ! -s conftest.err } && test -s conftest.$ac_objext; then ac_cv_prog_cc_g=yes else - echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 @@ -3095,8 +3230,8 @@ rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext ac_c_werror_flag=$ac_save_c_werror_flag fi -{ echo "$as_me:$LINENO: result: $ac_cv_prog_cc_g" >&5 -echo "${ECHO_T}$ac_cv_prog_cc_g" >&6; } +{ $as_echo "$as_me:$LINENO: result: $ac_cv_prog_cc_g" >&5 +$as_echo "$ac_cv_prog_cc_g" >&6; } if test "$ac_test_CFLAGS" = set; then CFLAGS=$ac_save_CFLAGS elif test $ac_cv_prog_cc_g = yes; then @@ -3112,10 +3247,10 @@ CFLAGS= fi fi -{ echo "$as_me:$LINENO: checking for $CC option to accept ISO C89" >&5 -echo $ECHO_N "checking for $CC option to accept ISO C89... $ECHO_C" >&6; } +{ $as_echo "$as_me:$LINENO: checking for $CC option to accept ISO C89" >&5 +$as_echo_n "checking for $CC option to accept ISO C89... " >&6; } if test "${ac_cv_prog_cc_c89+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 + $as_echo_n "(cached) " >&6 else ac_cv_prog_cc_c89=no ac_save_CC=$CC @@ -3186,20 +3321,21 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_compile") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { test -z "$ac_c_werror_flag" || test ! -s conftest.err } && test -s conftest.$ac_objext; then ac_cv_prog_cc_c89=$ac_arg else - echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 @@ -3215,15 +3351,15 @@ # AC_CACHE_VAL case "x$ac_cv_prog_cc_c89" in x) - { echo "$as_me:$LINENO: result: none needed" >&5 -echo "${ECHO_T}none needed" >&6; } ;; + { $as_echo "$as_me:$LINENO: result: none needed" >&5 +$as_echo "none needed" >&6; } ;; xno) - { echo "$as_me:$LINENO: result: unsupported" >&5 -echo "${ECHO_T}unsupported" >&6; } ;; + { $as_echo "$as_me:$LINENO: result: unsupported" >&5 +$as_echo "unsupported" >&6; } ;; *) CC="$CC $ac_cv_prog_cc_c89" - { echo "$as_me:$LINENO: result: $ac_cv_prog_cc_c89" >&5 -echo "${ECHO_T}$ac_cv_prog_cc_c89" >&6; } ;; + { $as_echo "$as_me:$LINENO: result: $ac_cv_prog_cc_c89" >&5 +$as_echo "$ac_cv_prog_cc_c89" >&6; } ;; esac @@ -3236,8 +3372,8 @@ -{ echo "$as_me:$LINENO: checking for --with-cxx-main=" >&5 -echo $ECHO_N "checking for --with-cxx-main=... $ECHO_C" >&6; } +{ $as_echo "$as_me:$LINENO: checking for --with-cxx-main=" >&5 +$as_echo_n "checking for --with-cxx-main=... " >&6; } # Check whether --with-cxx_main was given. if test "${with_cxx_main+set}" = set; then @@ -3262,8 +3398,8 @@ fi -{ echo "$as_me:$LINENO: result: $with_cxx_main" >&5 -echo "${ECHO_T}$with_cxx_main" >&6; } +{ $as_echo "$as_me:$LINENO: result: $with_cxx_main" >&5 +$as_echo "$with_cxx_main" >&6; } preset_cxx="$CXX" if test -z "$CXX" @@ -3271,10 +3407,10 @@ case "$CC" in gcc) # Extract the first word of "g++", so it can be a program name with args. set dummy g++; ac_word=$2 -{ echo "$as_me:$LINENO: checking for $ac_word" >&5 -echo $ECHO_N "checking for $ac_word... $ECHO_C" >&6; } +{ $as_echo "$as_me:$LINENO: checking for $ac_word" >&5 +$as_echo_n "checking for $ac_word... " >&6; } if test "${ac_cv_path_CXX+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 + $as_echo_n "(cached) " >&6 else case $CXX in [\\/]* | ?:[\\/]*) @@ -3289,7 +3425,7 @@ for ac_exec_ext in '' $ac_executable_extensions; do if { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_test_x "$as_dir/$ac_word$ac_exec_ext"; }; then ac_cv_path_CXX="$as_dir/$ac_word$ac_exec_ext" - echo "$as_me:$LINENO: found $as_dir/$ac_word$ac_exec_ext" >&5 + $as_echo "$as_me:$LINENO: found $as_dir/$ac_word$ac_exec_ext" >&5 break 2 fi done @@ -3302,20 +3438,20 @@ fi CXX=$ac_cv_path_CXX if test -n "$CXX"; then - { echo "$as_me:$LINENO: result: $CXX" >&5 -echo "${ECHO_T}$CXX" >&6; } + { $as_echo "$as_me:$LINENO: result: $CXX" >&5 +$as_echo "$CXX" >&6; } else - { echo "$as_me:$LINENO: result: no" >&5 -echo "${ECHO_T}no" >&6; } + { $as_echo "$as_me:$LINENO: result: no" >&5 +$as_echo "no" >&6; } fi ;; cc) # Extract the first word of "c++", so it can be a program name with args. set dummy c++; ac_word=$2 -{ echo "$as_me:$LINENO: checking for $ac_word" >&5 -echo $ECHO_N "checking for $ac_word... $ECHO_C" >&6; } +{ $as_echo "$as_me:$LINENO: checking for $ac_word" >&5 +$as_echo_n "checking for $ac_word... " >&6; } if test "${ac_cv_path_CXX+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 + $as_echo_n "(cached) " >&6 else case $CXX in [\\/]* | ?:[\\/]*) @@ -3330,7 +3466,7 @@ for ac_exec_ext in '' $ac_executable_extensions; do if { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_test_x "$as_dir/$ac_word$ac_exec_ext"; }; then ac_cv_path_CXX="$as_dir/$ac_word$ac_exec_ext" - echo "$as_me:$LINENO: found $as_dir/$ac_word$ac_exec_ext" >&5 + $as_echo "$as_me:$LINENO: found $as_dir/$ac_word$ac_exec_ext" >&5 break 2 fi done @@ -3343,11 +3479,11 @@ fi CXX=$ac_cv_path_CXX if test -n "$CXX"; then - { echo "$as_me:$LINENO: result: $CXX" >&5 -echo "${ECHO_T}$CXX" >&6; } + { $as_echo "$as_me:$LINENO: result: $CXX" >&5 +$as_echo "$CXX" >&6; } else - { echo "$as_me:$LINENO: result: no" >&5 -echo "${ECHO_T}no" >&6; } + { $as_echo "$as_me:$LINENO: result: no" >&5 +$as_echo "no" >&6; } fi ;; @@ -3363,10 +3499,10 @@ do # Extract the first word of "$ac_prog", so it can be a program name with args. set dummy $ac_prog; ac_word=$2 -{ echo "$as_me:$LINENO: checking for $ac_word" >&5 -echo $ECHO_N "checking for $ac_word... $ECHO_C" >&6; } +{ $as_echo "$as_me:$LINENO: checking for $ac_word" >&5 +$as_echo_n "checking for $ac_word... " >&6; } if test "${ac_cv_prog_CXX+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 + $as_echo_n "(cached) " >&6 else if test -n "$CXX"; then ac_cv_prog_CXX="$CXX" # Let the user override the test. @@ -3379,7 +3515,7 @@ for ac_exec_ext in '' $ac_executable_extensions; do if { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_test_x "$as_dir/$ac_word$ac_exec_ext"; }; then ac_cv_prog_CXX="$ac_prog" - echo "$as_me:$LINENO: found $as_dir/$ac_word$ac_exec_ext" >&5 + $as_echo "$as_me:$LINENO: found $as_dir/$ac_word$ac_exec_ext" >&5 break 2 fi done @@ -3390,11 +3526,11 @@ fi CXX=$ac_cv_prog_CXX if test -n "$CXX"; then - { echo "$as_me:$LINENO: result: $CXX" >&5 -echo "${ECHO_T}$CXX" >&6; } + { $as_echo "$as_me:$LINENO: result: $CXX" >&5 +$as_echo "$CXX" >&6; } else - { echo "$as_me:$LINENO: result: no" >&5 -echo "${ECHO_T}no" >&6; } + { $as_echo "$as_me:$LINENO: result: no" >&5 +$as_echo "no" >&6; } fi @@ -3409,12 +3545,12 @@ fi if test "$preset_cxx" != "$CXX" then - { echo "$as_me:$LINENO: WARNING: + { $as_echo "$as_me:$LINENO: WARNING: By default, distutils will build C++ extension modules with \"$CXX\". If this is not intended, then set CXX on the configure command line. " >&5 -echo "$as_me: WARNING: +$as_echo "$as_me: WARNING: By default, distutils will build C++ extension modules with \"$CXX\". If this is not intended, then set CXX on the configure command line. @@ -3429,15 +3565,15 @@ ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5' ac_link='$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5' ac_compiler_gnu=$ac_cv_c_compiler_gnu -{ echo "$as_me:$LINENO: checking how to run the C preprocessor" >&5 -echo $ECHO_N "checking how to run the C preprocessor... $ECHO_C" >&6; } +{ $as_echo "$as_me:$LINENO: checking how to run the C preprocessor" >&5 +$as_echo_n "checking how to run the C preprocessor... " >&6; } # On Suns, sometimes $CPP names a directory. if test -n "$CPP" && test -d "$CPP"; then CPP= fi if test -z "$CPP"; then if test "${ac_cv_prog_CPP+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 + $as_echo_n "(cached) " >&6 else # Double quotes because CPP needs to be expanded for CPP in "$CC -E" "$CC -E -traditional-cpp" "/lib/cpp" @@ -3469,20 +3605,21 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_cpp conftest.$ac_ext") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } >/dev/null && { test -z "$ac_c_preproc_warn_flag$ac_c_werror_flag" || test ! -s conftest.err }; then : else - echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 # Broken: fails on valid input. @@ -3506,13 +3643,14 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_cpp conftest.$ac_ext") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } >/dev/null && { test -z "$ac_c_preproc_warn_flag$ac_c_werror_flag" || test ! -s conftest.err @@ -3520,7 +3658,7 @@ # Broken: success on invalid input. continue else - echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 # Passes both tests. @@ -3545,8 +3683,8 @@ else ac_cv_prog_CPP=$CPP fi -{ echo "$as_me:$LINENO: result: $CPP" >&5 -echo "${ECHO_T}$CPP" >&6; } +{ $as_echo "$as_me:$LINENO: result: $CPP" >&5 +$as_echo "$CPP" >&6; } ac_preproc_ok=false for ac_c_preproc_warn_flag in '' yes do @@ -3574,20 +3712,21 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_cpp conftest.$ac_ext") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } >/dev/null && { test -z "$ac_c_preproc_warn_flag$ac_c_werror_flag" || test ! -s conftest.err }; then : else - echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 # Broken: fails on valid input. @@ -3611,13 +3750,14 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_cpp conftest.$ac_ext") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } >/dev/null && { test -z "$ac_c_preproc_warn_flag$ac_c_werror_flag" || test ! -s conftest.err @@ -3625,7 +3765,7 @@ # Broken: success on invalid input. continue else - echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 # Passes both tests. @@ -3641,11 +3781,13 @@ if $ac_preproc_ok; then : else - { { echo "$as_me:$LINENO: error: C preprocessor \"$CPP\" fails sanity check + { { $as_echo "$as_me:$LINENO: error: in \`$ac_pwd':" >&5 +$as_echo "$as_me: error: in \`$ac_pwd':" >&2;} +{ { $as_echo "$as_me:$LINENO: error: C preprocessor \"$CPP\" fails sanity check See \`config.log' for more details." >&5 -echo "$as_me: error: C preprocessor \"$CPP\" fails sanity check +$as_echo "$as_me: error: C preprocessor \"$CPP\" fails sanity check See \`config.log' for more details." >&2;} - { (exit 1); exit 1; }; } + { (exit 1); exit 1; }; }; } fi ac_ext=c @@ -3655,42 +3797,37 @@ ac_compiler_gnu=$ac_cv_c_compiler_gnu -{ echo "$as_me:$LINENO: checking for grep that handles long lines and -e" >&5 -echo $ECHO_N "checking for grep that handles long lines and -e... $ECHO_C" >&6; } +{ $as_echo "$as_me:$LINENO: checking for grep that handles long lines and -e" >&5 +$as_echo_n "checking for grep that handles long lines and -e... " >&6; } if test "${ac_cv_path_GREP+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 -else - # Extract the first word of "grep ggrep" to use in msg output -if test -z "$GREP"; then -set dummy grep ggrep; ac_prog_name=$2 -if test "${ac_cv_path_GREP+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 + $as_echo_n "(cached) " >&6 else + if test -z "$GREP"; then ac_path_GREP_found=false -# Loop through the user's path and test for each of PROGNAME-LIST -as_save_IFS=$IFS; IFS=$PATH_SEPARATOR + # Loop through the user's path and test for each of PROGNAME-LIST + as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $PATH$PATH_SEPARATOR/usr/xpg4/bin do IFS=$as_save_IFS test -z "$as_dir" && as_dir=. for ac_prog in grep ggrep; do - for ac_exec_ext in '' $ac_executable_extensions; do - ac_path_GREP="$as_dir/$ac_prog$ac_exec_ext" - { test -f "$ac_path_GREP" && $as_test_x "$ac_path_GREP"; } || continue - # Check for GNU ac_path_GREP and select it if it is found. + for ac_exec_ext in '' $ac_executable_extensions; do + ac_path_GREP="$as_dir/$ac_prog$ac_exec_ext" + { test -f "$ac_path_GREP" && $as_test_x "$ac_path_GREP"; } || continue +# Check for GNU ac_path_GREP and select it if it is found. # Check for GNU $ac_path_GREP case `"$ac_path_GREP" --version 2>&1` in *GNU*) ac_cv_path_GREP="$ac_path_GREP" ac_path_GREP_found=:;; *) ac_count=0 - echo $ECHO_N "0123456789$ECHO_C" >"conftest.in" + $as_echo_n 0123456789 >"conftest.in" while : do cat "conftest.in" "conftest.in" >"conftest.tmp" mv "conftest.tmp" "conftest.in" cp "conftest.in" "conftest.nl" - echo 'GREP' >> "conftest.nl" + $as_echo 'GREP' >> "conftest.nl" "$ac_path_GREP" -e 'GREP$' -e '-(cannot match)-' < "conftest.nl" >"conftest.out" 2>/dev/null || break diff "conftest.out" "conftest.nl" >/dev/null 2>&1 || break ac_count=`expr $ac_count + 1` @@ -3705,74 +3842,60 @@ rm -f conftest.in conftest.tmp conftest.nl conftest.out;; esac - - $ac_path_GREP_found && break 3 + $ac_path_GREP_found && break 3 + done done done - -done IFS=$as_save_IFS - - -fi - -GREP="$ac_cv_path_GREP" -if test -z "$GREP"; then - { { echo "$as_me:$LINENO: error: no acceptable $ac_prog_name could be found in $PATH$PATH_SEPARATOR/usr/xpg4/bin" >&5 -echo "$as_me: error: no acceptable $ac_prog_name could be found in $PATH$PATH_SEPARATOR/usr/xpg4/bin" >&2;} + if test -z "$ac_cv_path_GREP"; then + { { $as_echo "$as_me:$LINENO: error: no acceptable grep could be found in $PATH$PATH_SEPARATOR/usr/xpg4/bin" >&5 +$as_echo "$as_me: error: no acceptable grep could be found in $PATH$PATH_SEPARATOR/usr/xpg4/bin" >&2;} { (exit 1); exit 1; }; } -fi - + fi else ac_cv_path_GREP=$GREP fi - fi -{ echo "$as_me:$LINENO: result: $ac_cv_path_GREP" >&5 -echo "${ECHO_T}$ac_cv_path_GREP" >&6; } +{ $as_echo "$as_me:$LINENO: result: $ac_cv_path_GREP" >&5 +$as_echo "$ac_cv_path_GREP" >&6; } GREP="$ac_cv_path_GREP" -{ echo "$as_me:$LINENO: checking for egrep" >&5 -echo $ECHO_N "checking for egrep... $ECHO_C" >&6; } +{ $as_echo "$as_me:$LINENO: checking for egrep" >&5 +$as_echo_n "checking for egrep... " >&6; } if test "${ac_cv_path_EGREP+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 + $as_echo_n "(cached) " >&6 else if echo a | $GREP -E '(a|b)' >/dev/null 2>&1 then ac_cv_path_EGREP="$GREP -E" else - # Extract the first word of "egrep" to use in msg output -if test -z "$EGREP"; then -set dummy egrep; ac_prog_name=$2 -if test "${ac_cv_path_EGREP+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 -else + if test -z "$EGREP"; then ac_path_EGREP_found=false -# Loop through the user's path and test for each of PROGNAME-LIST -as_save_IFS=$IFS; IFS=$PATH_SEPARATOR + # Loop through the user's path and test for each of PROGNAME-LIST + as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $PATH$PATH_SEPARATOR/usr/xpg4/bin do IFS=$as_save_IFS test -z "$as_dir" && as_dir=. for ac_prog in egrep; do - for ac_exec_ext in '' $ac_executable_extensions; do - ac_path_EGREP="$as_dir/$ac_prog$ac_exec_ext" - { test -f "$ac_path_EGREP" && $as_test_x "$ac_path_EGREP"; } || continue - # Check for GNU ac_path_EGREP and select it if it is found. + for ac_exec_ext in '' $ac_executable_extensions; do + ac_path_EGREP="$as_dir/$ac_prog$ac_exec_ext" + { test -f "$ac_path_EGREP" && $as_test_x "$ac_path_EGREP"; } || continue +# Check for GNU ac_path_EGREP and select it if it is found. # Check for GNU $ac_path_EGREP case `"$ac_path_EGREP" --version 2>&1` in *GNU*) ac_cv_path_EGREP="$ac_path_EGREP" ac_path_EGREP_found=:;; *) ac_count=0 - echo $ECHO_N "0123456789$ECHO_C" >"conftest.in" + $as_echo_n 0123456789 >"conftest.in" while : do cat "conftest.in" "conftest.in" >"conftest.tmp" mv "conftest.tmp" "conftest.in" cp "conftest.in" "conftest.nl" - echo 'EGREP' >> "conftest.nl" + $as_echo 'EGREP' >> "conftest.nl" "$ac_path_EGREP" 'EGREP$' < "conftest.nl" >"conftest.out" 2>/dev/null || break diff "conftest.out" "conftest.nl" >/dev/null 2>&1 || break ac_count=`expr $ac_count + 1` @@ -3787,63 +3910,510 @@ rm -f conftest.in conftest.tmp conftest.nl conftest.out;; esac - - $ac_path_EGREP_found && break 3 + $ac_path_EGREP_found && break 3 + done done done +IFS=$as_save_IFS + if test -z "$ac_cv_path_EGREP"; then + { { $as_echo "$as_me:$LINENO: error: no acceptable egrep could be found in $PATH$PATH_SEPARATOR/usr/xpg4/bin" >&5 +$as_echo "$as_me: error: no acceptable egrep could be found in $PATH$PATH_SEPARATOR/usr/xpg4/bin" >&2;} + { (exit 1); exit 1; }; } + fi +else + ac_cv_path_EGREP=$EGREP +fi + + fi +fi +{ $as_echo "$as_me:$LINENO: result: $ac_cv_path_EGREP" >&5 +$as_echo "$ac_cv_path_EGREP" >&6; } + EGREP="$ac_cv_path_EGREP" + + +{ $as_echo "$as_me:$LINENO: checking for ANSI C header files" >&5 +$as_echo_n "checking for ANSI C header files... " >&6; } +if test "${ac_cv_header_stdc+set}" = set; then + $as_echo_n "(cached) " >&6 +else + cat >conftest.$ac_ext <<_ACEOF +/* confdefs.h. */ +_ACEOF +cat confdefs.h >>conftest.$ac_ext +cat >>conftest.$ac_ext <<_ACEOF +/* end confdefs.h. */ +#include +#include +#include +#include + +int +main () +{ + + ; + return 0; +} +_ACEOF +rm -f conftest.$ac_objext +if { (ac_try="$ac_compile" +case "(($ac_try" in + *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; + *) ac_try_echo=$ac_try;; +esac +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 + (eval "$ac_compile") 2>conftest.er1 + ac_status=$? + grep -v '^ *+' conftest.er1 >conftest.err + rm -f conftest.er1 + cat conftest.err >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 + (exit $ac_status); } && { + test -z "$ac_c_werror_flag" || + test ! -s conftest.err + } && test -s conftest.$ac_objext; then + ac_cv_header_stdc=yes +else + $as_echo "$as_me: failed program was:" >&5 +sed 's/^/| /' conftest.$ac_ext >&5 + + ac_cv_header_stdc=no +fi + +rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext + +if test $ac_cv_header_stdc = yes; then + # SunOS 4.x string.h does not declare mem*, contrary to ANSI. + cat >conftest.$ac_ext <<_ACEOF +/* confdefs.h. */ +_ACEOF +cat confdefs.h >>conftest.$ac_ext +cat >>conftest.$ac_ext <<_ACEOF +/* end confdefs.h. */ +#include + +_ACEOF +if (eval "$ac_cpp conftest.$ac_ext") 2>&5 | + $EGREP "memchr" >/dev/null 2>&1; then + : +else + ac_cv_header_stdc=no +fi +rm -f conftest* + +fi + +if test $ac_cv_header_stdc = yes; then + # ISC 2.0.2 stdlib.h does not declare free, contrary to ANSI. + cat >conftest.$ac_ext <<_ACEOF +/* confdefs.h. */ +_ACEOF +cat confdefs.h >>conftest.$ac_ext +cat >>conftest.$ac_ext <<_ACEOF +/* end confdefs.h. */ +#include + +_ACEOF +if (eval "$ac_cpp conftest.$ac_ext") 2>&5 | + $EGREP "free" >/dev/null 2>&1; then + : +else + ac_cv_header_stdc=no +fi +rm -f conftest* + +fi + +if test $ac_cv_header_stdc = yes; then + # /bin/cc in Irix-4.0.5 gets non-ANSI ctype macros unless using -ansi. + if test "$cross_compiling" = yes; then + : +else + cat >conftest.$ac_ext <<_ACEOF +/* confdefs.h. */ +_ACEOF +cat confdefs.h >>conftest.$ac_ext +cat >>conftest.$ac_ext <<_ACEOF +/* end confdefs.h. */ +#include +#include +#if ((' ' & 0x0FF) == 0x020) +# define ISLOWER(c) ('a' <= (c) && (c) <= 'z') +# define TOUPPER(c) (ISLOWER(c) ? 'A' + ((c) - 'a') : (c)) +#else +# define ISLOWER(c) \ + (('a' <= (c) && (c) <= 'i') \ + || ('j' <= (c) && (c) <= 'r') \ + || ('s' <= (c) && (c) <= 'z')) +# define TOUPPER(c) (ISLOWER(c) ? ((c) | 0x40) : (c)) +#endif + +#define XOR(e, f) (((e) && !(f)) || (!(e) && (f))) +int +main () +{ + int i; + for (i = 0; i < 256; i++) + if (XOR (islower (i), ISLOWER (i)) + || toupper (i) != TOUPPER (i)) + return 2; + return 0; +} +_ACEOF +rm -f conftest$ac_exeext +if { (ac_try="$ac_link" +case "(($ac_try" in + *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; + *) ac_try_echo=$ac_try;; +esac +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 + (eval "$ac_link") 2>&5 + ac_status=$? + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 + (exit $ac_status); } && { ac_try='./conftest$ac_exeext' + { (case "(($ac_try" in + *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; + *) ac_try_echo=$ac_try;; +esac +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 + (eval "$ac_try") 2>&5 + ac_status=$? + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 + (exit $ac_status); }; }; then + : +else + $as_echo "$as_me: program exited with status $ac_status" >&5 +$as_echo "$as_me: failed program was:" >&5 +sed 's/^/| /' conftest.$ac_ext >&5 + +( exit $ac_status ) +ac_cv_header_stdc=no +fi +rm -rf conftest.dSYM +rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext conftest.$ac_objext conftest.$ac_ext +fi + + +fi +fi +{ $as_echo "$as_me:$LINENO: result: $ac_cv_header_stdc" >&5 +$as_echo "$ac_cv_header_stdc" >&6; } +if test $ac_cv_header_stdc = yes; then + +cat >>confdefs.h <<\_ACEOF +#define STDC_HEADERS 1 +_ACEOF + +fi + +# On IRIX 5.3, sys/types and inttypes.h are conflicting. + + + + + + + + + +for ac_header in sys/types.h sys/stat.h stdlib.h string.h memory.h strings.h \ + inttypes.h stdint.h unistd.h +do +as_ac_Header=`$as_echo "ac_cv_header_$ac_header" | $as_tr_sh` +{ $as_echo "$as_me:$LINENO: checking for $ac_header" >&5 +$as_echo_n "checking for $ac_header... " >&6; } +if { as_var=$as_ac_Header; eval "test \"\${$as_var+set}\" = set"; }; then + $as_echo_n "(cached) " >&6 +else + cat >conftest.$ac_ext <<_ACEOF +/* confdefs.h. */ +_ACEOF +cat confdefs.h >>conftest.$ac_ext +cat >>conftest.$ac_ext <<_ACEOF +/* end confdefs.h. */ +$ac_includes_default + +#include <$ac_header> +_ACEOF +rm -f conftest.$ac_objext +if { (ac_try="$ac_compile" +case "(($ac_try" in + *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; + *) ac_try_echo=$ac_try;; +esac +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 + (eval "$ac_compile") 2>conftest.er1 + ac_status=$? + grep -v '^ *+' conftest.er1 >conftest.err + rm -f conftest.er1 + cat conftest.err >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 + (exit $ac_status); } && { + test -z "$ac_c_werror_flag" || + test ! -s conftest.err + } && test -s conftest.$ac_objext; then + eval "$as_ac_Header=yes" +else + $as_echo "$as_me: failed program was:" >&5 +sed 's/^/| /' conftest.$ac_ext >&5 + + eval "$as_ac_Header=no" +fi + +rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext +fi +ac_res=`eval 'as_val=${'$as_ac_Header'} + $as_echo "$as_val"'` + { $as_echo "$as_me:$LINENO: result: $ac_res" >&5 +$as_echo "$ac_res" >&6; } +as_val=`eval 'as_val=${'$as_ac_Header'} + $as_echo "$as_val"'` + if test "x$as_val" = x""yes; then + cat >>confdefs.h <<_ACEOF +#define `$as_echo "HAVE_$ac_header" | $as_tr_cpp` 1 +_ACEOF + +fi done -IFS=$as_save_IFS + + if test "${ac_cv_header_minix_config_h+set}" = set; then + { $as_echo "$as_me:$LINENO: checking for minix/config.h" >&5 +$as_echo_n "checking for minix/config.h... " >&6; } +if test "${ac_cv_header_minix_config_h+set}" = set; then + $as_echo_n "(cached) " >&6 +fi +{ $as_echo "$as_me:$LINENO: result: $ac_cv_header_minix_config_h" >&5 +$as_echo "$ac_cv_header_minix_config_h" >&6; } +else + # Is the header compilable? +{ $as_echo "$as_me:$LINENO: checking minix/config.h usability" >&5 +$as_echo_n "checking minix/config.h usability... " >&6; } +cat >conftest.$ac_ext <<_ACEOF +/* confdefs.h. */ +_ACEOF +cat confdefs.h >>conftest.$ac_ext +cat >>conftest.$ac_ext <<_ACEOF +/* end confdefs.h. */ +$ac_includes_default +#include +_ACEOF +rm -f conftest.$ac_objext +if { (ac_try="$ac_compile" +case "(($ac_try" in + *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; + *) ac_try_echo=$ac_try;; +esac +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 + (eval "$ac_compile") 2>conftest.er1 + ac_status=$? + grep -v '^ *+' conftest.er1 >conftest.err + rm -f conftest.er1 + cat conftest.err >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 + (exit $ac_status); } && { + test -z "$ac_c_werror_flag" || + test ! -s conftest.err + } && test -s conftest.$ac_objext; then + ac_header_compiler=yes +else + $as_echo "$as_me: failed program was:" >&5 +sed 's/^/| /' conftest.$ac_ext >&5 + + ac_header_compiler=no +fi + +rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext +{ $as_echo "$as_me:$LINENO: result: $ac_header_compiler" >&5 +$as_echo "$ac_header_compiler" >&6; } + +# Is the header present? +{ $as_echo "$as_me:$LINENO: checking minix/config.h presence" >&5 +$as_echo_n "checking minix/config.h presence... " >&6; } +cat >conftest.$ac_ext <<_ACEOF +/* confdefs.h. */ +_ACEOF +cat confdefs.h >>conftest.$ac_ext +cat >>conftest.$ac_ext <<_ACEOF +/* end confdefs.h. */ +#include +_ACEOF +if { (ac_try="$ac_cpp conftest.$ac_ext" +case "(($ac_try" in + *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; + *) ac_try_echo=$ac_try;; +esac +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 + (eval "$ac_cpp conftest.$ac_ext") 2>conftest.er1 + ac_status=$? + grep -v '^ *+' conftest.er1 >conftest.err + rm -f conftest.er1 + cat conftest.err >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 + (exit $ac_status); } >/dev/null && { + test -z "$ac_c_preproc_warn_flag$ac_c_werror_flag" || + test ! -s conftest.err + }; then + ac_header_preproc=yes +else + $as_echo "$as_me: failed program was:" >&5 +sed 's/^/| /' conftest.$ac_ext >&5 + + ac_header_preproc=no fi -EGREP="$ac_cv_path_EGREP" -if test -z "$EGREP"; then - { { echo "$as_me:$LINENO: error: no acceptable $ac_prog_name could be found in $PATH$PATH_SEPARATOR/usr/xpg4/bin" >&5 -echo "$as_me: error: no acceptable $ac_prog_name could be found in $PATH$PATH_SEPARATOR/usr/xpg4/bin" >&2;} - { (exit 1); exit 1; }; } +rm -f conftest.err conftest.$ac_ext +{ $as_echo "$as_me:$LINENO: result: $ac_header_preproc" >&5 +$as_echo "$ac_header_preproc" >&6; } + +# So? What about this header? +case $ac_header_compiler:$ac_header_preproc:$ac_c_preproc_warn_flag in + yes:no: ) + { $as_echo "$as_me:$LINENO: WARNING: minix/config.h: accepted by the compiler, rejected by the preprocessor!" >&5 +$as_echo "$as_me: WARNING: minix/config.h: accepted by the compiler, rejected by the preprocessor!" >&2;} + { $as_echo "$as_me:$LINENO: WARNING: minix/config.h: proceeding with the compiler's result" >&5 +$as_echo "$as_me: WARNING: minix/config.h: proceeding with the compiler's result" >&2;} + ac_header_preproc=yes + ;; + no:yes:* ) + { $as_echo "$as_me:$LINENO: WARNING: minix/config.h: present but cannot be compiled" >&5 +$as_echo "$as_me: WARNING: minix/config.h: present but cannot be compiled" >&2;} + { $as_echo "$as_me:$LINENO: WARNING: minix/config.h: check for missing prerequisite headers?" >&5 +$as_echo "$as_me: WARNING: minix/config.h: check for missing prerequisite headers?" >&2;} + { $as_echo "$as_me:$LINENO: WARNING: minix/config.h: see the Autoconf documentation" >&5 +$as_echo "$as_me: WARNING: minix/config.h: see the Autoconf documentation" >&2;} + { $as_echo "$as_me:$LINENO: WARNING: minix/config.h: section \"Present But Cannot Be Compiled\"" >&5 +$as_echo "$as_me: WARNING: minix/config.h: section \"Present But Cannot Be Compiled\"" >&2;} + { $as_echo "$as_me:$LINENO: WARNING: minix/config.h: proceeding with the preprocessor's result" >&5 +$as_echo "$as_me: WARNING: minix/config.h: proceeding with the preprocessor's result" >&2;} + { $as_echo "$as_me:$LINENO: WARNING: minix/config.h: in the future, the compiler will take precedence" >&5 +$as_echo "$as_me: WARNING: minix/config.h: in the future, the compiler will take precedence" >&2;} + ( cat <<\_ASBOX +## -------------------------------------- ## +## Report this to http://bugs.python.org/ ## +## -------------------------------------- ## +_ASBOX + ) | sed "s/^/$as_me: WARNING: /" >&2 + ;; +esac +{ $as_echo "$as_me:$LINENO: checking for minix/config.h" >&5 +$as_echo_n "checking for minix/config.h... " >&6; } +if test "${ac_cv_header_minix_config_h+set}" = set; then + $as_echo_n "(cached) " >&6 +else + ac_cv_header_minix_config_h=$ac_header_preproc fi +{ $as_echo "$as_me:$LINENO: result: $ac_cv_header_minix_config_h" >&5 +$as_echo "$ac_cv_header_minix_config_h" >&6; } +fi +if test "x$ac_cv_header_minix_config_h" = x""yes; then + MINIX=yes +else + MINIX= +fi + + + if test "$MINIX" = yes; then + +cat >>confdefs.h <<\_ACEOF +#define _POSIX_SOURCE 1 +_ACEOF + + +cat >>confdefs.h <<\_ACEOF +#define _POSIX_1_SOURCE 2 +_ACEOF + + +cat >>confdefs.h <<\_ACEOF +#define _MINIX 1 +_ACEOF + + fi + + + + { $as_echo "$as_me:$LINENO: checking whether it is safe to define __EXTENSIONS__" >&5 +$as_echo_n "checking whether it is safe to define __EXTENSIONS__... " >&6; } +if test "${ac_cv_safe_to_define___extensions__+set}" = set; then + $as_echo_n "(cached) " >&6 +else + cat >conftest.$ac_ext <<_ACEOF +/* confdefs.h. */ +_ACEOF +cat confdefs.h >>conftest.$ac_ext +cat >>conftest.$ac_ext <<_ACEOF +/* end confdefs.h. */ + +# define __EXTENSIONS__ 1 + $ac_includes_default +int +main () +{ + + ; + return 0; +} +_ACEOF +rm -f conftest.$ac_objext +if { (ac_try="$ac_compile" +case "(($ac_try" in + *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; + *) ac_try_echo=$ac_try;; +esac +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 + (eval "$ac_compile") 2>conftest.er1 + ac_status=$? + grep -v '^ *+' conftest.er1 >conftest.err + rm -f conftest.er1 + cat conftest.err >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 + (exit $ac_status); } && { + test -z "$ac_c_werror_flag" || + test ! -s conftest.err + } && test -s conftest.$ac_objext; then + ac_cv_safe_to_define___extensions__=yes else - ac_cv_path_EGREP=$EGREP -fi - + $as_echo "$as_me: failed program was:" >&5 +sed 's/^/| /' conftest.$ac_ext >&5 - fi + ac_cv_safe_to_define___extensions__=no fi -{ echo "$as_me:$LINENO: result: $ac_cv_path_EGREP" >&5 -echo "${ECHO_T}$ac_cv_path_EGREP" >&6; } - EGREP="$ac_cv_path_EGREP" - +rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext +fi +{ $as_echo "$as_me:$LINENO: result: $ac_cv_safe_to_define___extensions__" >&5 +$as_echo "$ac_cv_safe_to_define___extensions__" >&6; } + test $ac_cv_safe_to_define___extensions__ = yes && + cat >>confdefs.h <<\_ACEOF +#define __EXTENSIONS__ 1 +_ACEOF -{ echo "$as_me:$LINENO: checking for AIX" >&5 -echo $ECHO_N "checking for AIX... $ECHO_C" >&6; } -cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ + cat >>confdefs.h <<\_ACEOF +#define _ALL_SOURCE 1 _ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -#ifdef _AIX - yes -#endif + cat >>confdefs.h <<\_ACEOF +#define _GNU_SOURCE 1 _ACEOF -if (eval "$ac_cpp conftest.$ac_ext") 2>&5 | - $EGREP "yes" >/dev/null 2>&1; then - { echo "$as_me:$LINENO: result: yes" >&5 -echo "${ECHO_T}yes" >&6; } -cat >>confdefs.h <<\_ACEOF -#define _ALL_SOURCE 1 + + cat >>confdefs.h <<\_ACEOF +#define _POSIX_PTHREAD_SEMANTICS 1 _ACEOF -else - { echo "$as_me:$LINENO: result: no" >&5 -echo "${ECHO_T}no" >&6; } -fi -rm -f conftest* + cat >>confdefs.h <<\_ACEOF +#define _TANDEM_SOURCE 1 +_ACEOF @@ -3856,8 +4426,8 @@ esac -{ echo "$as_me:$LINENO: checking for --with-suffix" >&5 -echo $ECHO_N "checking for --with-suffix... $ECHO_C" >&6; } +{ $as_echo "$as_me:$LINENO: checking for --with-suffix" >&5 +$as_echo_n "checking for --with-suffix... " >&6; } # Check whether --with-suffix was given. if test "${with_suffix+set}" = set; then @@ -3869,26 +4439,26 @@ esac fi -{ echo "$as_me:$LINENO: result: $EXEEXT" >&5 -echo "${ECHO_T}$EXEEXT" >&6; } +{ $as_echo "$as_me:$LINENO: result: $EXEEXT" >&5 +$as_echo "$EXEEXT" >&6; } # Test whether we're running on a non-case-sensitive system, in which # case we give a warning if no ext is given -{ echo "$as_me:$LINENO: checking for case-insensitive build directory" >&5 -echo $ECHO_N "checking for case-insensitive build directory... $ECHO_C" >&6; } +{ $as_echo "$as_me:$LINENO: checking for case-insensitive build directory" >&5 +$as_echo_n "checking for case-insensitive build directory... " >&6; } if test ! -d CaseSensitiveTestDir; then mkdir CaseSensitiveTestDir fi if test -d casesensitivetestdir then - { echo "$as_me:$LINENO: result: yes" >&5 -echo "${ECHO_T}yes" >&6; } + { $as_echo "$as_me:$LINENO: result: yes" >&5 +$as_echo "yes" >&6; } BUILDEXEEXT=.exe else - { echo "$as_me:$LINENO: result: no" >&5 -echo "${ECHO_T}no" >&6; } + { $as_echo "$as_me:$LINENO: result: no" >&5 +$as_echo "no" >&6; } BUILDEXEEXT=$EXEEXT fi rmdir CaseSensitiveTestDir @@ -3917,14 +4487,14 @@ -{ echo "$as_me:$LINENO: checking LIBRARY" >&5 -echo $ECHO_N "checking LIBRARY... $ECHO_C" >&6; } +{ $as_echo "$as_me:$LINENO: checking LIBRARY" >&5 +$as_echo_n "checking LIBRARY... " >&6; } if test -z "$LIBRARY" then LIBRARY='libpython$(VERSION).a' fi -{ echo "$as_me:$LINENO: result: $LIBRARY" >&5 -echo "${ECHO_T}$LIBRARY" >&6; } +{ $as_echo "$as_me:$LINENO: result: $LIBRARY" >&5 +$as_echo "$LIBRARY" >&6; } # LDLIBRARY is the name of the library to link against (as opposed to the # name of the library into which to insert object files). BLDLIBRARY is also @@ -3959,8 +4529,8 @@ # This is altered for AIX in order to build the export list before # linking. -{ echo "$as_me:$LINENO: checking LINKCC" >&5 -echo $ECHO_N "checking LINKCC... $ECHO_C" >&6; } +{ $as_echo "$as_me:$LINENO: checking LINKCC" >&5 +$as_echo_n "checking LINKCC... " >&6; } if test -z "$LINKCC" then LINKCC='$(PURIFY) $(MAINCC)' @@ -3978,8 +4548,8 @@ LINKCC=qcc;; esac fi -{ echo "$as_me:$LINENO: result: $LINKCC" >&5 -echo "${ECHO_T}$LINKCC" >&6; } +{ $as_echo "$as_me:$LINENO: result: $LINKCC" >&5 +$as_echo "$LINKCC" >&6; } # GNULD is set to "yes" if the GNU linker is used. If this goes wrong # make sure we default having it set to "no": this is used by @@ -3987,8 +4557,8 @@ # to linker command lines, and failing to detect GNU ld simply results # in the same bahaviour as before. -{ echo "$as_me:$LINENO: checking for GNU ld" >&5 -echo $ECHO_N "checking for GNU ld... $ECHO_C" >&6; } +{ $as_echo "$as_me:$LINENO: checking for GNU ld" >&5 +$as_echo_n "checking for GNU ld... " >&6; } ac_prog=ld if test "$GCC" = yes; then ac_prog=`$CC -print-prog-name=ld` @@ -3999,11 +4569,11 @@ *) GNULD=no;; esac -{ echo "$as_me:$LINENO: result: $GNULD" >&5 -echo "${ECHO_T}$GNULD" >&6; } +{ $as_echo "$as_me:$LINENO: result: $GNULD" >&5 +$as_echo "$GNULD" >&6; } -{ echo "$as_me:$LINENO: checking for --enable-shared" >&5 -echo $ECHO_N "checking for --enable-shared... $ECHO_C" >&6; } +{ $as_echo "$as_me:$LINENO: checking for --enable-shared" >&5 +$as_echo_n "checking for --enable-shared... " >&6; } # Check whether --enable-shared was given. if test "${enable_shared+set}" = set; then enableval=$enable_shared; @@ -4019,11 +4589,11 @@ enable_shared="no";; esac fi -{ echo "$as_me:$LINENO: result: $enable_shared" >&5 -echo "${ECHO_T}$enable_shared" >&6; } +{ $as_echo "$as_me:$LINENO: result: $enable_shared" >&5 +$as_echo "$enable_shared" >&6; } -{ echo "$as_me:$LINENO: checking for --enable-profiling" >&5 -echo $ECHO_N "checking for --enable-profiling... $ECHO_C" >&6; } +{ $as_echo "$as_me:$LINENO: checking for --enable-profiling" >&5 +$as_echo_n "checking for --enable-profiling... " >&6; } # Check whether --enable-profiling was given. if test "${enable_profiling+set}" = set; then enableval=$enable_profiling; ac_save_cc="$CC" @@ -4045,29 +4615,32 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_link") 2>&5 ac_status=$? - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { ac_try='./conftest$ac_exeext' { (case "(($ac_try" in *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_try") 2>&5 ac_status=$? - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); }; }; then ac_enable_profiling="yes" else - echo "$as_me: program exited with status $ac_status" >&5 -echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: program exited with status $ac_status" >&5 +$as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 ( exit $ac_status ) ac_enable_profiling="no" fi +rm -rf conftest.dSYM rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext conftest.$ac_objext conftest.$ac_ext fi @@ -4075,8 +4648,8 @@ CC="$ac_save_cc" fi -{ echo "$as_me:$LINENO: result: $ac_enable_profiling" >&5 -echo "${ECHO_T}$ac_enable_profiling" >&6; } +{ $as_echo "$as_me:$LINENO: result: $ac_enable_profiling" >&5 +$as_echo "$ac_enable_profiling" >&6; } case "$ac_enable_profiling" in "yes") @@ -4085,8 +4658,8 @@ ;; esac -{ echo "$as_me:$LINENO: checking LDLIBRARY" >&5 -echo $ECHO_N "checking LDLIBRARY... $ECHO_C" >&6; } +{ $as_echo "$as_me:$LINENO: checking LDLIBRARY" >&5 +$as_echo_n "checking LDLIBRARY... " >&6; } # MacOSX framework builds need more magic. LDLIBRARY is the dynamic # library that we build, but we do not want to link against it (we @@ -4170,16 +4743,16 @@ esac fi -{ echo "$as_me:$LINENO: result: $LDLIBRARY" >&5 -echo "${ECHO_T}$LDLIBRARY" >&6; } +{ $as_echo "$as_me:$LINENO: result: $LDLIBRARY" >&5 +$as_echo "$LDLIBRARY" >&6; } if test -n "$ac_tool_prefix"; then # Extract the first word of "${ac_tool_prefix}ranlib", so it can be a program name with args. set dummy ${ac_tool_prefix}ranlib; ac_word=$2 -{ echo "$as_me:$LINENO: checking for $ac_word" >&5 -echo $ECHO_N "checking for $ac_word... $ECHO_C" >&6; } +{ $as_echo "$as_me:$LINENO: checking for $ac_word" >&5 +$as_echo_n "checking for $ac_word... " >&6; } if test "${ac_cv_prog_RANLIB+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 + $as_echo_n "(cached) " >&6 else if test -n "$RANLIB"; then ac_cv_prog_RANLIB="$RANLIB" # Let the user override the test. @@ -4192,7 +4765,7 @@ for ac_exec_ext in '' $ac_executable_extensions; do if { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_test_x "$as_dir/$ac_word$ac_exec_ext"; }; then ac_cv_prog_RANLIB="${ac_tool_prefix}ranlib" - echo "$as_me:$LINENO: found $as_dir/$ac_word$ac_exec_ext" >&5 + $as_echo "$as_me:$LINENO: found $as_dir/$ac_word$ac_exec_ext" >&5 break 2 fi done @@ -4203,11 +4776,11 @@ fi RANLIB=$ac_cv_prog_RANLIB if test -n "$RANLIB"; then - { echo "$as_me:$LINENO: result: $RANLIB" >&5 -echo "${ECHO_T}$RANLIB" >&6; } + { $as_echo "$as_me:$LINENO: result: $RANLIB" >&5 +$as_echo "$RANLIB" >&6; } else - { echo "$as_me:$LINENO: result: no" >&5 -echo "${ECHO_T}no" >&6; } + { $as_echo "$as_me:$LINENO: result: no" >&5 +$as_echo "no" >&6; } fi @@ -4216,10 +4789,10 @@ ac_ct_RANLIB=$RANLIB # Extract the first word of "ranlib", so it can be a program name with args. set dummy ranlib; ac_word=$2 -{ echo "$as_me:$LINENO: checking for $ac_word" >&5 -echo $ECHO_N "checking for $ac_word... $ECHO_C" >&6; } +{ $as_echo "$as_me:$LINENO: checking for $ac_word" >&5 +$as_echo_n "checking for $ac_word... " >&6; } if test "${ac_cv_prog_ac_ct_RANLIB+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 + $as_echo_n "(cached) " >&6 else if test -n "$ac_ct_RANLIB"; then ac_cv_prog_ac_ct_RANLIB="$ac_ct_RANLIB" # Let the user override the test. @@ -4232,7 +4805,7 @@ for ac_exec_ext in '' $ac_executable_extensions; do if { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_test_x "$as_dir/$ac_word$ac_exec_ext"; }; then ac_cv_prog_ac_ct_RANLIB="ranlib" - echo "$as_me:$LINENO: found $as_dir/$ac_word$ac_exec_ext" >&5 + $as_echo "$as_me:$LINENO: found $as_dir/$ac_word$ac_exec_ext" >&5 break 2 fi done @@ -4243,11 +4816,11 @@ fi ac_ct_RANLIB=$ac_cv_prog_ac_ct_RANLIB if test -n "$ac_ct_RANLIB"; then - { echo "$as_me:$LINENO: result: $ac_ct_RANLIB" >&5 -echo "${ECHO_T}$ac_ct_RANLIB" >&6; } + { $as_echo "$as_me:$LINENO: result: $ac_ct_RANLIB" >&5 +$as_echo "$ac_ct_RANLIB" >&6; } else - { echo "$as_me:$LINENO: result: no" >&5 -echo "${ECHO_T}no" >&6; } + { $as_echo "$as_me:$LINENO: result: no" >&5 +$as_echo "no" >&6; } fi if test "x$ac_ct_RANLIB" = x; then @@ -4255,12 +4828,8 @@ else case $cross_compiling:$ac_tool_warned in yes:) -{ echo "$as_me:$LINENO: WARNING: In the future, Autoconf will not detect cross-tools -whose name does not start with the host triplet. If you think this -configuration is useful to you, please write to autoconf at gnu.org." >&5 -echo "$as_me: WARNING: In the future, Autoconf will not detect cross-tools -whose name does not start with the host triplet. If you think this -configuration is useful to you, please write to autoconf at gnu.org." >&2;} +{ $as_echo "$as_me:$LINENO: WARNING: using cross tools not prefixed with host triplet" >&5 +$as_echo "$as_me: WARNING: using cross tools not prefixed with host triplet" >&2;} ac_tool_warned=yes ;; esac RANLIB=$ac_ct_RANLIB @@ -4274,10 +4843,10 @@ do # Extract the first word of "$ac_prog", so it can be a program name with args. set dummy $ac_prog; ac_word=$2 -{ echo "$as_me:$LINENO: checking for $ac_word" >&5 -echo $ECHO_N "checking for $ac_word... $ECHO_C" >&6; } +{ $as_echo "$as_me:$LINENO: checking for $ac_word" >&5 +$as_echo_n "checking for $ac_word... " >&6; } if test "${ac_cv_prog_AR+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 + $as_echo_n "(cached) " >&6 else if test -n "$AR"; then ac_cv_prog_AR="$AR" # Let the user override the test. @@ -4290,7 +4859,7 @@ for ac_exec_ext in '' $ac_executable_extensions; do if { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_test_x "$as_dir/$ac_word$ac_exec_ext"; }; then ac_cv_prog_AR="$ac_prog" - echo "$as_me:$LINENO: found $as_dir/$ac_word$ac_exec_ext" >&5 + $as_echo "$as_me:$LINENO: found $as_dir/$ac_word$ac_exec_ext" >&5 break 2 fi done @@ -4301,11 +4870,11 @@ fi AR=$ac_cv_prog_AR if test -n "$AR"; then - { echo "$as_me:$LINENO: result: $AR" >&5 -echo "${ECHO_T}$AR" >&6; } + { $as_echo "$as_me:$LINENO: result: $AR" >&5 +$as_echo "$AR" >&6; } else - { echo "$as_me:$LINENO: result: no" >&5 -echo "${ECHO_T}no" >&6; } + { $as_echo "$as_me:$LINENO: result: no" >&5 +$as_echo "no" >&6; } fi @@ -4324,10 +4893,10 @@ # Extract the first word of "svnversion", so it can be a program name with args. set dummy svnversion; ac_word=$2 -{ echo "$as_me:$LINENO: checking for $ac_word" >&5 -echo $ECHO_N "checking for $ac_word... $ECHO_C" >&6; } +{ $as_echo "$as_me:$LINENO: checking for $ac_word" >&5 +$as_echo_n "checking for $ac_word... " >&6; } if test "${ac_cv_prog_SVNVERSION+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 + $as_echo_n "(cached) " >&6 else if test -n "$SVNVERSION"; then ac_cv_prog_SVNVERSION="$SVNVERSION" # Let the user override the test. @@ -4340,7 +4909,7 @@ for ac_exec_ext in '' $ac_executable_extensions; do if { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_test_x "$as_dir/$ac_word$ac_exec_ext"; }; then ac_cv_prog_SVNVERSION="found" - echo "$as_me:$LINENO: found $as_dir/$ac_word$ac_exec_ext" >&5 + $as_echo "$as_me:$LINENO: found $as_dir/$ac_word$ac_exec_ext" >&5 break 2 fi done @@ -4352,11 +4921,11 @@ fi SVNVERSION=$ac_cv_prog_SVNVERSION if test -n "$SVNVERSION"; then - { echo "$as_me:$LINENO: result: $SVNVERSION" >&5 -echo "${ECHO_T}$SVNVERSION" >&6; } + { $as_echo "$as_me:$LINENO: result: $SVNVERSION" >&5 +$as_echo "$SVNVERSION" >&6; } else - { echo "$as_me:$LINENO: result: no" >&5 -echo "${ECHO_T}no" >&6; } + { $as_echo "$as_me:$LINENO: result: no" >&5 +$as_echo "no" >&6; } fi @@ -4392,8 +4961,8 @@ fi done if test -z "$ac_aux_dir"; then - { { echo "$as_me:$LINENO: error: cannot find install-sh or install.sh in \"$srcdir\" \"$srcdir/..\" \"$srcdir/../..\"" >&5 -echo "$as_me: error: cannot find install-sh or install.sh in \"$srcdir\" \"$srcdir/..\" \"$srcdir/../..\"" >&2;} + { { $as_echo "$as_me:$LINENO: error: cannot find install-sh or install.sh in \"$srcdir\" \"$srcdir/..\" \"$srcdir/../..\"" >&5 +$as_echo "$as_me: error: cannot find install-sh or install.sh in \"$srcdir\" \"$srcdir/..\" \"$srcdir/../..\"" >&2;} { (exit 1); exit 1; }; } fi @@ -4419,11 +4988,12 @@ # SVR4 /usr/ucb/install, which tries to use the nonexistent group "staff" # OS/2's system install, which has a completely different semantic # ./install, which can be erroneously created by make from ./install.sh. -{ echo "$as_me:$LINENO: checking for a BSD-compatible install" >&5 -echo $ECHO_N "checking for a BSD-compatible install... $ECHO_C" >&6; } +# Reject install programs that cannot install multiple files. +{ $as_echo "$as_me:$LINENO: checking for a BSD-compatible install" >&5 +$as_echo_n "checking for a BSD-compatible install... " >&6; } if test -z "$INSTALL"; then if test "${ac_cv_path_install+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 + $as_echo_n "(cached) " >&6 else as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $PATH @@ -4452,17 +5022,29 @@ # program-specific install script used by HP pwplus--don't use. : else - ac_cv_path_install="$as_dir/$ac_prog$ac_exec_ext -c" - break 3 + rm -rf conftest.one conftest.two conftest.dir + echo one > conftest.one + echo two > conftest.two + mkdir conftest.dir + if "$as_dir/$ac_prog$ac_exec_ext" -c conftest.one conftest.two "`pwd`/conftest.dir" && + test -s conftest.one && test -s conftest.two && + test -s conftest.dir/conftest.one && + test -s conftest.dir/conftest.two + then + ac_cv_path_install="$as_dir/$ac_prog$ac_exec_ext -c" + break 3 + fi fi fi done done ;; esac + done IFS=$as_save_IFS +rm -rf conftest.one conftest.two conftest.dir fi if test "${ac_cv_path_install+set}" = set; then @@ -4475,8 +5057,8 @@ INSTALL=$ac_install_sh fi fi -{ echo "$as_me:$LINENO: result: $INSTALL" >&5 -echo "${ECHO_T}$INSTALL" >&6; } +{ $as_echo "$as_me:$LINENO: result: $INSTALL" >&5 +$as_echo "$INSTALL" >&6; } # Use test -z because SunOS4 sh mishandles braces in ${var-val}. # It thinks the first close brace ends the variable substitution. @@ -4498,8 +5080,8 @@ fi # Check for --with-pydebug -{ echo "$as_me:$LINENO: checking for --with-pydebug" >&5 -echo $ECHO_N "checking for --with-pydebug... $ECHO_C" >&6; } +{ $as_echo "$as_me:$LINENO: checking for --with-pydebug" >&5 +$as_echo_n "checking for --with-pydebug... " >&6; } # Check whether --with-pydebug was given. if test "${with_pydebug+set}" = set; then @@ -4511,15 +5093,15 @@ #define Py_DEBUG 1 _ACEOF - { echo "$as_me:$LINENO: result: yes" >&5 -echo "${ECHO_T}yes" >&6; }; + { $as_echo "$as_me:$LINENO: result: yes" >&5 +$as_echo "yes" >&6; }; Py_DEBUG='true' -else { echo "$as_me:$LINENO: result: no" >&5 -echo "${ECHO_T}no" >&6; }; Py_DEBUG='false' +else { $as_echo "$as_me:$LINENO: result: no" >&5 +$as_echo "no" >&6; }; Py_DEBUG='false' fi else - { echo "$as_me:$LINENO: result: no" >&5 -echo "${ECHO_T}no" >&6; } + { $as_echo "$as_me:$LINENO: result: no" >&5 +$as_echo "no" >&6; } fi @@ -4588,8 +5170,8 @@ # Python violates C99 rules, by casting between incompatible # pointer types. GCC may generate bad code as a result of that, # so use -fno-strict-aliasing if supported. - { echo "$as_me:$LINENO: checking whether $CC accepts -fno-strict-aliasing" >&5 -echo $ECHO_N "checking whether $CC accepts -fno-strict-aliasing... $ECHO_C" >&6; } + { $as_echo "$as_me:$LINENO: checking whether $CC accepts -fno-strict-aliasing" >&5 +$as_echo_n "checking whether $CC accepts -fno-strict-aliasing... " >&6; } ac_save_cc="$CC" CC="$CC -fno-strict-aliasing" if test "$cross_compiling" = yes; then @@ -4609,36 +5191,39 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_link") 2>&5 ac_status=$? - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { ac_try='./conftest$ac_exeext' { (case "(($ac_try" in *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_try") 2>&5 ac_status=$? - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); }; }; then ac_cv_no_strict_aliasing_ok=yes else - echo "$as_me: program exited with status $ac_status" >&5 -echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: program exited with status $ac_status" >&5 +$as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 ( exit $ac_status ) ac_cv_no_strict_aliasing_ok=no fi +rm -rf conftest.dSYM rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext conftest.$ac_objext conftest.$ac_ext fi CC="$ac_save_cc" - { echo "$as_me:$LINENO: result: $ac_cv_no_strict_aliasing_ok" >&5 -echo "${ECHO_T}$ac_cv_no_strict_aliasing_ok" >&6; } + { $as_echo "$as_me:$LINENO: result: $ac_cv_no_strict_aliasing_ok" >&5 +$as_echo "$ac_cv_no_strict_aliasing_ok" >&6; } if test $ac_cv_no_strict_aliasing_ok = yes then BASECFLAGS="$BASECFLAGS -fno-strict-aliasing" @@ -4663,8 +5248,8 @@ # used to be here, but non-Apple gcc doesn't accept them. if test "${CC}" = gcc then - { echo "$as_me:$LINENO: checking which compiler should be used" >&5 -echo $ECHO_N "checking which compiler should be used... $ECHO_C" >&6; } + { $as_echo "$as_me:$LINENO: checking which compiler should be used" >&5 +$as_echo_n "checking which compiler should be used... " >&6; } case "${UNIVERSALSDK}" in */MacOSX10.4u.sdk) # Build using 10.4 SDK, force usage of gcc when the @@ -4674,8 +5259,8 @@ CPP=cpp-4.0 ;; esac - { echo "$as_me:$LINENO: result: $CC" >&5 -echo "${ECHO_T}$CC" >&6; } + { $as_echo "$as_me:$LINENO: result: $CC" >&5 +$as_echo "$CC" >&6; } fi @@ -4708,8 +5293,8 @@ LIPO_64BIT_FLAGS="-extract x86_64" else - { { echo "$as_me:$LINENO: error: proper usage is --with-universal-arch=32-bit|64-bit|all|intel|3-way" >&5 -echo "$as_me: error: proper usage is --with-universal-arch=32-bit|64-bit|all|intel|3-way" >&2;} + { { $as_echo "$as_me:$LINENO: error: proper usage is --with-universal-arch=32-bit|64-bit|all|intel|3-way" >&5 +$as_echo "$as_me: error: proper usage is --with-universal-arch=32-bit|64-bit|all|intel|3-way" >&2;} { (exit 1); exit 1; }; } fi @@ -4804,10 +5389,10 @@ ac_cv_opt_olimit_ok=no fi -{ echo "$as_me:$LINENO: checking whether $CC accepts -OPT:Olimit=0" >&5 -echo $ECHO_N "checking whether $CC accepts -OPT:Olimit=0... $ECHO_C" >&6; } +{ $as_echo "$as_me:$LINENO: checking whether $CC accepts -OPT:Olimit=0" >&5 +$as_echo_n "checking whether $CC accepts -OPT:Olimit=0... " >&6; } if test "${ac_cv_opt_olimit_ok+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 + $as_echo_n "(cached) " >&6 else ac_save_cc="$CC" CC="$CC -OPT:Olimit=0" @@ -4828,29 +5413,32 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_link") 2>&5 ac_status=$? - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { ac_try='./conftest$ac_exeext' { (case "(($ac_try" in *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_try") 2>&5 ac_status=$? - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); }; }; then ac_cv_opt_olimit_ok=yes else - echo "$as_me: program exited with status $ac_status" >&5 -echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: program exited with status $ac_status" >&5 +$as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 ( exit $ac_status ) ac_cv_opt_olimit_ok=no fi +rm -rf conftest.dSYM rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext conftest.$ac_objext conftest.$ac_ext fi @@ -4858,8 +5446,8 @@ CC="$ac_save_cc" fi -{ echo "$as_me:$LINENO: result: $ac_cv_opt_olimit_ok" >&5 -echo "${ECHO_T}$ac_cv_opt_olimit_ok" >&6; } +{ $as_echo "$as_me:$LINENO: result: $ac_cv_opt_olimit_ok" >&5 +$as_echo "$ac_cv_opt_olimit_ok" >&6; } if test $ac_cv_opt_olimit_ok = yes; then case $ac_sys_system in # XXX is this branch needed? On MacOSX 10.2.2 the result of the @@ -4872,10 +5460,10 @@ ;; esac else - { echo "$as_me:$LINENO: checking whether $CC accepts -Olimit 1500" >&5 -echo $ECHO_N "checking whether $CC accepts -Olimit 1500... $ECHO_C" >&6; } + { $as_echo "$as_me:$LINENO: checking whether $CC accepts -Olimit 1500" >&5 +$as_echo_n "checking whether $CC accepts -Olimit 1500... " >&6; } if test "${ac_cv_olimit_ok+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 + $as_echo_n "(cached) " >&6 else ac_save_cc="$CC" CC="$CC -Olimit 1500" @@ -4896,29 +5484,32 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_link") 2>&5 ac_status=$? - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { ac_try='./conftest$ac_exeext' { (case "(($ac_try" in *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_try") 2>&5 ac_status=$? - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); }; }; then ac_cv_olimit_ok=yes else - echo "$as_me: program exited with status $ac_status" >&5 -echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: program exited with status $ac_status" >&5 +$as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 ( exit $ac_status ) ac_cv_olimit_ok=no fi +rm -rf conftest.dSYM rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext conftest.$ac_objext conftest.$ac_ext fi @@ -4926,8 +5517,8 @@ CC="$ac_save_cc" fi - { echo "$as_me:$LINENO: result: $ac_cv_olimit_ok" >&5 -echo "${ECHO_T}$ac_cv_olimit_ok" >&6; } + { $as_echo "$as_me:$LINENO: result: $ac_cv_olimit_ok" >&5 +$as_echo "$ac_cv_olimit_ok" >&6; } if test $ac_cv_olimit_ok = yes; then BASECFLAGS="$BASECFLAGS -Olimit 1500" fi @@ -4936,8 +5527,8 @@ # Check whether GCC supports PyArg_ParseTuple format if test "$GCC" = "yes" then - { echo "$as_me:$LINENO: checking whether gcc supports ParseTuple __format__" >&5 -echo $ECHO_N "checking whether gcc supports ParseTuple __format__... $ECHO_C" >&6; } + { $as_echo "$as_me:$LINENO: checking whether gcc supports ParseTuple __format__" >&5 +$as_echo_n "checking whether gcc supports ParseTuple __format__... " >&6; } save_CFLAGS=$CFLAGS CFLAGS="$CFLAGS -Werror" cat >conftest.$ac_ext <<_ACEOF @@ -4963,13 +5554,14 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_compile") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { test -z "$ac_c_werror_flag" || test ! -s conftest.err @@ -4979,14 +5571,14 @@ #define HAVE_ATTRIBUTE_FORMAT_PARSETUPLE 1 _ACEOF - { echo "$as_me:$LINENO: result: yes" >&5 -echo "${ECHO_T}yes" >&6; } + { $as_echo "$as_me:$LINENO: result: yes" >&5 +$as_echo "yes" >&6; } else - echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 - { echo "$as_me:$LINENO: result: no" >&5 -echo "${ECHO_T}no" >&6; } + { $as_echo "$as_me:$LINENO: result: no" >&5 +$as_echo "no" >&6; } fi @@ -4999,10 +5591,10 @@ # complain if unaccepted options are passed (e.g. gcc on Mac OS X). # So we have to see first whether pthreads are available without # options before we can check whether -Kpthread improves anything. -{ echo "$as_me:$LINENO: checking whether pthreads are available without options" >&5 -echo $ECHO_N "checking whether pthreads are available without options... $ECHO_C" >&6; } +{ $as_echo "$as_me:$LINENO: checking whether pthreads are available without options" >&5 +$as_echo_n "checking whether pthreads are available without options... " >&6; } if test "${ac_cv_pthread_is_default+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 + $as_echo_n "(cached) " >&6 else if test "$cross_compiling" = yes; then ac_cv_pthread_is_default=no @@ -5033,19 +5625,21 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_link") 2>&5 ac_status=$? - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { ac_try='./conftest$ac_exeext' { (case "(($ac_try" in *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_try") 2>&5 ac_status=$? - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); }; }; then ac_cv_pthread_is_default=yes @@ -5053,13 +5647,14 @@ ac_cv_pthread=no else - echo "$as_me: program exited with status $ac_status" >&5 -echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: program exited with status $ac_status" >&5 +$as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 ( exit $ac_status ) ac_cv_pthread_is_default=no fi +rm -rf conftest.dSYM rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext conftest.$ac_objext conftest.$ac_ext fi @@ -5067,8 +5662,8 @@ fi -{ echo "$as_me:$LINENO: result: $ac_cv_pthread_is_default" >&5 -echo "${ECHO_T}$ac_cv_pthread_is_default" >&6; } +{ $as_echo "$as_me:$LINENO: result: $ac_cv_pthread_is_default" >&5 +$as_echo "$ac_cv_pthread_is_default" >&6; } if test $ac_cv_pthread_is_default = yes @@ -5080,10 +5675,10 @@ # Some compilers won't report that they do not support -Kpthread, # so we need to run a program to see whether it really made the # function available. -{ echo "$as_me:$LINENO: checking whether $CC accepts -Kpthread" >&5 -echo $ECHO_N "checking whether $CC accepts -Kpthread... $ECHO_C" >&6; } +{ $as_echo "$as_me:$LINENO: checking whether $CC accepts -Kpthread" >&5 +$as_echo_n "checking whether $CC accepts -Kpthread... " >&6; } if test "${ac_cv_kpthread+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 + $as_echo_n "(cached) " >&6 else ac_save_cc="$CC" CC="$CC -Kpthread" @@ -5116,29 +5711,32 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_link") 2>&5 ac_status=$? - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { ac_try='./conftest$ac_exeext' { (case "(($ac_try" in *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_try") 2>&5 ac_status=$? - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); }; }; then ac_cv_kpthread=yes else - echo "$as_me: program exited with status $ac_status" >&5 -echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: program exited with status $ac_status" >&5 +$as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 ( exit $ac_status ) ac_cv_kpthread=no fi +rm -rf conftest.dSYM rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext conftest.$ac_objext conftest.$ac_ext fi @@ -5146,8 +5744,8 @@ CC="$ac_save_cc" fi -{ echo "$as_me:$LINENO: result: $ac_cv_kpthread" >&5 -echo "${ECHO_T}$ac_cv_kpthread" >&6; } +{ $as_echo "$as_me:$LINENO: result: $ac_cv_kpthread" >&5 +$as_echo "$ac_cv_kpthread" >&6; } fi if test $ac_cv_kpthread = no -a $ac_cv_pthread_is_default = no @@ -5157,10 +5755,10 @@ # Some compilers won't report that they do not support -Kthread, # so we need to run a program to see whether it really made the # function available. -{ echo "$as_me:$LINENO: checking whether $CC accepts -Kthread" >&5 -echo $ECHO_N "checking whether $CC accepts -Kthread... $ECHO_C" >&6; } +{ $as_echo "$as_me:$LINENO: checking whether $CC accepts -Kthread" >&5 +$as_echo_n "checking whether $CC accepts -Kthread... " >&6; } if test "${ac_cv_kthread+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 + $as_echo_n "(cached) " >&6 else ac_save_cc="$CC" CC="$CC -Kthread" @@ -5193,29 +5791,32 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_link") 2>&5 ac_status=$? - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { ac_try='./conftest$ac_exeext' { (case "(($ac_try" in *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_try") 2>&5 ac_status=$? - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); }; }; then ac_cv_kthread=yes else - echo "$as_me: program exited with status $ac_status" >&5 -echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: program exited with status $ac_status" >&5 +$as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 ( exit $ac_status ) ac_cv_kthread=no fi +rm -rf conftest.dSYM rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext conftest.$ac_objext conftest.$ac_ext fi @@ -5223,8 +5824,8 @@ CC="$ac_save_cc" fi -{ echo "$as_me:$LINENO: result: $ac_cv_kthread" >&5 -echo "${ECHO_T}$ac_cv_kthread" >&6; } +{ $as_echo "$as_me:$LINENO: result: $ac_cv_kthread" >&5 +$as_echo "$ac_cv_kthread" >&6; } fi if test $ac_cv_kthread = no -a $ac_cv_pthread_is_default = no @@ -5234,10 +5835,10 @@ # Some compilers won't report that they do not support -pthread, # so we need to run a program to see whether it really made the # function available. -{ echo "$as_me:$LINENO: checking whether $CC accepts -pthread" >&5 -echo $ECHO_N "checking whether $CC accepts -pthread... $ECHO_C" >&6; } +{ $as_echo "$as_me:$LINENO: checking whether $CC accepts -pthread" >&5 +$as_echo_n "checking whether $CC accepts -pthread... " >&6; } if test "${ac_cv_thread+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 + $as_echo_n "(cached) " >&6 else ac_save_cc="$CC" CC="$CC -pthread" @@ -5270,29 +5871,32 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_link") 2>&5 ac_status=$? - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { ac_try='./conftest$ac_exeext' { (case "(($ac_try" in *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_try") 2>&5 ac_status=$? - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); }; }; then ac_cv_pthread=yes else - echo "$as_me: program exited with status $ac_status" >&5 -echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: program exited with status $ac_status" >&5 +$as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 ( exit $ac_status ) ac_cv_pthread=no fi +rm -rf conftest.dSYM rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext conftest.$ac_objext conftest.$ac_ext fi @@ -5300,8 +5904,8 @@ CC="$ac_save_cc" fi -{ echo "$as_me:$LINENO: result: $ac_cv_pthread" >&5 -echo "${ECHO_T}$ac_cv_pthread" >&6; } +{ $as_echo "$as_me:$LINENO: result: $ac_cv_pthread" >&5 +$as_echo "$ac_cv_pthread" >&6; } fi # If we have set a CC compiler flag for thread support then @@ -5309,8 +5913,8 @@ ac_cv_cxx_thread=no if test ! -z "$CXX" then -{ echo "$as_me:$LINENO: checking whether $CXX also accepts flags for thread support" >&5 -echo $ECHO_N "checking whether $CXX also accepts flags for thread support... $ECHO_C" >&6; } +{ $as_echo "$as_me:$LINENO: checking whether $CXX also accepts flags for thread support" >&5 +$as_echo_n "checking whether $CXX also accepts flags for thread support... " >&6; } ac_save_cxx="$CXX" if test "$ac_cv_kpthread" = "yes" @@ -5340,17 +5944,17 @@ fi rm -fr conftest* fi -{ echo "$as_me:$LINENO: result: $ac_cv_cxx_thread" >&5 -echo "${ECHO_T}$ac_cv_cxx_thread" >&6; } +{ $as_echo "$as_me:$LINENO: result: $ac_cv_cxx_thread" >&5 +$as_echo "$ac_cv_cxx_thread" >&6; } fi CXX="$ac_save_cxx" # checks for header files -{ echo "$as_me:$LINENO: checking for ANSI C header files" >&5 -echo $ECHO_N "checking for ANSI C header files... $ECHO_C" >&6; } +{ $as_echo "$as_me:$LINENO: checking for ANSI C header files" >&5 +$as_echo_n "checking for ANSI C header files... " >&6; } if test "${ac_cv_header_stdc+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 + $as_echo_n "(cached) " >&6 else cat >conftest.$ac_ext <<_ACEOF /* confdefs.h. */ @@ -5377,20 +5981,21 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_compile") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { test -z "$ac_c_werror_flag" || test ! -s conftest.err } && test -s conftest.$ac_objext; then ac_cv_header_stdc=yes else - echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 ac_cv_header_stdc=no @@ -5482,37 +6087,40 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_link") 2>&5 ac_status=$? - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { ac_try='./conftest$ac_exeext' { (case "(($ac_try" in *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_try") 2>&5 ac_status=$? - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); }; }; then : else - echo "$as_me: program exited with status $ac_status" >&5 -echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: program exited with status $ac_status" >&5 +$as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 ( exit $ac_status ) ac_cv_header_stdc=no fi +rm -rf conftest.dSYM rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext conftest.$ac_objext conftest.$ac_ext fi fi fi -{ echo "$as_me:$LINENO: result: $ac_cv_header_stdc" >&5 -echo "${ECHO_T}$ac_cv_header_stdc" >&6; } +{ $as_echo "$as_me:$LINENO: result: $ac_cv_header_stdc" >&5 +$as_echo "$ac_cv_header_stdc" >&6; } if test $ac_cv_header_stdc = yes; then cat >>confdefs.h <<\_ACEOF @@ -5521,75 +6129,6 @@ fi -# On IRIX 5.3, sys/types and inttypes.h are conflicting. - - - - - - - - - -for ac_header in sys/types.h sys/stat.h stdlib.h string.h memory.h strings.h \ - inttypes.h stdint.h unistd.h -do -as_ac_Header=`echo "ac_cv_header_$ac_header" | $as_tr_sh` -{ echo "$as_me:$LINENO: checking for $ac_header" >&5 -echo $ECHO_N "checking for $ac_header... $ECHO_C" >&6; } -if { as_var=$as_ac_Header; eval "test \"\${$as_var+set}\" = set"; }; then - echo $ECHO_N "(cached) $ECHO_C" >&6 -else - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -$ac_includes_default - -#include <$ac_header> -_ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - eval "$as_ac_Header=yes" -else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - eval "$as_ac_Header=no" -fi - -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext -fi -ac_res=`eval echo '${'$as_ac_Header'}'` - { echo "$as_me:$LINENO: result: $ac_res" >&5 -echo "${ECHO_T}$ac_res" >&6; } -if test `eval echo '${'$as_ac_Header'}'` = yes; then - cat >>confdefs.h <<_ACEOF -#define `echo "HAVE_$ac_header" | $as_tr_cpp` 1 -_ACEOF - -fi - -done - - @@ -5657,20 +6196,21 @@ sys/resource.h netpacket/packet.h sysexits.h bluetooth.h \ bluetooth/bluetooth.h linux/tipc.h do -as_ac_Header=`echo "ac_cv_header_$ac_header" | $as_tr_sh` +as_ac_Header=`$as_echo "ac_cv_header_$ac_header" | $as_tr_sh` if { as_var=$as_ac_Header; eval "test \"\${$as_var+set}\" = set"; }; then - { echo "$as_me:$LINENO: checking for $ac_header" >&5 -echo $ECHO_N "checking for $ac_header... $ECHO_C" >&6; } + { $as_echo "$as_me:$LINENO: checking for $ac_header" >&5 +$as_echo_n "checking for $ac_header... " >&6; } if { as_var=$as_ac_Header; eval "test \"\${$as_var+set}\" = set"; }; then - echo $ECHO_N "(cached) $ECHO_C" >&6 + $as_echo_n "(cached) " >&6 fi -ac_res=`eval echo '${'$as_ac_Header'}'` - { echo "$as_me:$LINENO: result: $ac_res" >&5 -echo "${ECHO_T}$ac_res" >&6; } +ac_res=`eval 'as_val=${'$as_ac_Header'} + $as_echo "$as_val"'` + { $as_echo "$as_me:$LINENO: result: $ac_res" >&5 +$as_echo "$ac_res" >&6; } else # Is the header compilable? -{ echo "$as_me:$LINENO: checking $ac_header usability" >&5 -echo $ECHO_N "checking $ac_header usability... $ECHO_C" >&6; } +{ $as_echo "$as_me:$LINENO: checking $ac_header usability" >&5 +$as_echo_n "checking $ac_header usability... " >&6; } cat >conftest.$ac_ext <<_ACEOF /* confdefs.h. */ _ACEOF @@ -5686,32 +6226,33 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_compile") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { test -z "$ac_c_werror_flag" || test ! -s conftest.err } && test -s conftest.$ac_objext; then ac_header_compiler=yes else - echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 ac_header_compiler=no fi rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext -{ echo "$as_me:$LINENO: result: $ac_header_compiler" >&5 -echo "${ECHO_T}$ac_header_compiler" >&6; } +{ $as_echo "$as_me:$LINENO: result: $ac_header_compiler" >&5 +$as_echo "$ac_header_compiler" >&6; } # Is the header present? -{ echo "$as_me:$LINENO: checking $ac_header presence" >&5 -echo $ECHO_N "checking $ac_header presence... $ECHO_C" >&6; } +{ $as_echo "$as_me:$LINENO: checking $ac_header presence" >&5 +$as_echo_n "checking $ac_header presence... " >&6; } cat >conftest.$ac_ext <<_ACEOF /* confdefs.h. */ _ACEOF @@ -5725,51 +6266,52 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_cpp conftest.$ac_ext") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } >/dev/null && { test -z "$ac_c_preproc_warn_flag$ac_c_werror_flag" || test ! -s conftest.err }; then ac_header_preproc=yes else - echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 ac_header_preproc=no fi rm -f conftest.err conftest.$ac_ext -{ echo "$as_me:$LINENO: result: $ac_header_preproc" >&5 -echo "${ECHO_T}$ac_header_preproc" >&6; } +{ $as_echo "$as_me:$LINENO: result: $ac_header_preproc" >&5 +$as_echo "$ac_header_preproc" >&6; } # So? What about this header? case $ac_header_compiler:$ac_header_preproc:$ac_c_preproc_warn_flag in yes:no: ) - { echo "$as_me:$LINENO: WARNING: $ac_header: accepted by the compiler, rejected by the preprocessor!" >&5 -echo "$as_me: WARNING: $ac_header: accepted by the compiler, rejected by the preprocessor!" >&2;} - { echo "$as_me:$LINENO: WARNING: $ac_header: proceeding with the compiler's result" >&5 -echo "$as_me: WARNING: $ac_header: proceeding with the compiler's result" >&2;} + { $as_echo "$as_me:$LINENO: WARNING: $ac_header: accepted by the compiler, rejected by the preprocessor!" >&5 +$as_echo "$as_me: WARNING: $ac_header: accepted by the compiler, rejected by the preprocessor!" >&2;} + { $as_echo "$as_me:$LINENO: WARNING: $ac_header: proceeding with the compiler's result" >&5 +$as_echo "$as_me: WARNING: $ac_header: proceeding with the compiler's result" >&2;} ac_header_preproc=yes ;; no:yes:* ) - { echo "$as_me:$LINENO: WARNING: $ac_header: present but cannot be compiled" >&5 -echo "$as_me: WARNING: $ac_header: present but cannot be compiled" >&2;} - { echo "$as_me:$LINENO: WARNING: $ac_header: check for missing prerequisite headers?" >&5 -echo "$as_me: WARNING: $ac_header: check for missing prerequisite headers?" >&2;} - { echo "$as_me:$LINENO: WARNING: $ac_header: see the Autoconf documentation" >&5 -echo "$as_me: WARNING: $ac_header: see the Autoconf documentation" >&2;} - { echo "$as_me:$LINENO: WARNING: $ac_header: section \"Present But Cannot Be Compiled\"" >&5 -echo "$as_me: WARNING: $ac_header: section \"Present But Cannot Be Compiled\"" >&2;} - { echo "$as_me:$LINENO: WARNING: $ac_header: proceeding with the preprocessor's result" >&5 -echo "$as_me: WARNING: $ac_header: proceeding with the preprocessor's result" >&2;} - { echo "$as_me:$LINENO: WARNING: $ac_header: in the future, the compiler will take precedence" >&5 -echo "$as_me: WARNING: $ac_header: in the future, the compiler will take precedence" >&2;} + { $as_echo "$as_me:$LINENO: WARNING: $ac_header: present but cannot be compiled" >&5 +$as_echo "$as_me: WARNING: $ac_header: present but cannot be compiled" >&2;} + { $as_echo "$as_me:$LINENO: WARNING: $ac_header: check for missing prerequisite headers?" >&5 +$as_echo "$as_me: WARNING: $ac_header: check for missing prerequisite headers?" >&2;} + { $as_echo "$as_me:$LINENO: WARNING: $ac_header: see the Autoconf documentation" >&5 +$as_echo "$as_me: WARNING: $ac_header: see the Autoconf documentation" >&2;} + { $as_echo "$as_me:$LINENO: WARNING: $ac_header: section \"Present But Cannot Be Compiled\"" >&5 +$as_echo "$as_me: WARNING: $ac_header: section \"Present But Cannot Be Compiled\"" >&2;} + { $as_echo "$as_me:$LINENO: WARNING: $ac_header: proceeding with the preprocessor's result" >&5 +$as_echo "$as_me: WARNING: $ac_header: proceeding with the preprocessor's result" >&2;} + { $as_echo "$as_me:$LINENO: WARNING: $ac_header: in the future, the compiler will take precedence" >&5 +$as_echo "$as_me: WARNING: $ac_header: in the future, the compiler will take precedence" >&2;} ( cat <<\_ASBOX ## -------------------------------------- ## ## Report this to http://bugs.python.org/ ## @@ -5778,21 +6320,24 @@ ) | sed "s/^/$as_me: WARNING: /" >&2 ;; esac -{ echo "$as_me:$LINENO: checking for $ac_header" >&5 -echo $ECHO_N "checking for $ac_header... $ECHO_C" >&6; } +{ $as_echo "$as_me:$LINENO: checking for $ac_header" >&5 +$as_echo_n "checking for $ac_header... " >&6; } if { as_var=$as_ac_Header; eval "test \"\${$as_var+set}\" = set"; }; then - echo $ECHO_N "(cached) $ECHO_C" >&6 + $as_echo_n "(cached) " >&6 else eval "$as_ac_Header=\$ac_header_preproc" fi -ac_res=`eval echo '${'$as_ac_Header'}'` - { echo "$as_me:$LINENO: result: $ac_res" >&5 -echo "${ECHO_T}$ac_res" >&6; } +ac_res=`eval 'as_val=${'$as_ac_Header'} + $as_echo "$as_val"'` + { $as_echo "$as_me:$LINENO: result: $ac_res" >&5 +$as_echo "$ac_res" >&6; } fi -if test `eval echo '${'$as_ac_Header'}'` = yes; then +as_val=`eval 'as_val=${'$as_ac_Header'} + $as_echo "$as_val"'` + if test "x$as_val" = x""yes; then cat >>confdefs.h <<_ACEOF -#define `echo "HAVE_$ac_header" | $as_tr_cpp` 1 +#define `$as_echo "HAVE_$ac_header" | $as_tr_cpp` 1 _ACEOF fi @@ -5806,11 +6351,11 @@ ac_header_dirent=no for ac_hdr in dirent.h sys/ndir.h sys/dir.h ndir.h; do - as_ac_Header=`echo "ac_cv_header_dirent_$ac_hdr" | $as_tr_sh` -{ echo "$as_me:$LINENO: checking for $ac_hdr that defines DIR" >&5 -echo $ECHO_N "checking for $ac_hdr that defines DIR... $ECHO_C" >&6; } + as_ac_Header=`$as_echo "ac_cv_header_dirent_$ac_hdr" | $as_tr_sh` +{ $as_echo "$as_me:$LINENO: checking for $ac_hdr that defines DIR" >&5 +$as_echo_n "checking for $ac_hdr that defines DIR... " >&6; } if { as_var=$as_ac_Header; eval "test \"\${$as_var+set}\" = set"; }; then - echo $ECHO_N "(cached) $ECHO_C" >&6 + $as_echo_n "(cached) " >&6 else cat >conftest.$ac_ext <<_ACEOF /* confdefs.h. */ @@ -5836,20 +6381,21 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_compile") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { test -z "$ac_c_werror_flag" || test ! -s conftest.err } && test -s conftest.$ac_objext; then eval "$as_ac_Header=yes" else - echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 eval "$as_ac_Header=no" @@ -5857,12 +6403,15 @@ rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext fi -ac_res=`eval echo '${'$as_ac_Header'}'` - { echo "$as_me:$LINENO: result: $ac_res" >&5 -echo "${ECHO_T}$ac_res" >&6; } -if test `eval echo '${'$as_ac_Header'}'` = yes; then +ac_res=`eval 'as_val=${'$as_ac_Header'} + $as_echo "$as_val"'` + { $as_echo "$as_me:$LINENO: result: $ac_res" >&5 +$as_echo "$ac_res" >&6; } +as_val=`eval 'as_val=${'$as_ac_Header'} + $as_echo "$as_val"'` + if test "x$as_val" = x""yes; then cat >>confdefs.h <<_ACEOF -#define `echo "HAVE_$ac_hdr" | $as_tr_cpp` 1 +#define `$as_echo "HAVE_$ac_hdr" | $as_tr_cpp` 1 _ACEOF ac_header_dirent=$ac_hdr; break @@ -5871,10 +6420,10 @@ done # Two versions of opendir et al. are in -ldir and -lx on SCO Xenix. if test $ac_header_dirent = dirent.h; then - { echo "$as_me:$LINENO: checking for library containing opendir" >&5 -echo $ECHO_N "checking for library containing opendir... $ECHO_C" >&6; } + { $as_echo "$as_me:$LINENO: checking for library containing opendir" >&5 +$as_echo_n "checking for library containing opendir... " >&6; } if test "${ac_cv_search_opendir+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 + $as_echo_n "(cached) " >&6 else ac_func_search_save_LIBS=$LIBS cat >conftest.$ac_ext <<_ACEOF @@ -5912,26 +6461,30 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_link") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { test -z "$ac_c_werror_flag" || test ! -s conftest.err - } && test -s conftest$ac_exeext && - $as_test_x conftest$ac_exeext; then + } && test -s conftest$ac_exeext && { + test "$cross_compiling" = yes || + $as_test_x conftest$ac_exeext + }; then ac_cv_search_opendir=$ac_res else - echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 fi +rm -rf conftest.dSYM rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \ conftest$ac_exeext if test "${ac_cv_search_opendir+set}" = set; then @@ -5946,8 +6499,8 @@ rm conftest.$ac_ext LIBS=$ac_func_search_save_LIBS fi -{ echo "$as_me:$LINENO: result: $ac_cv_search_opendir" >&5 -echo "${ECHO_T}$ac_cv_search_opendir" >&6; } +{ $as_echo "$as_me:$LINENO: result: $ac_cv_search_opendir" >&5 +$as_echo "$ac_cv_search_opendir" >&6; } ac_res=$ac_cv_search_opendir if test "$ac_res" != no; then test "$ac_res" = "none required" || LIBS="$ac_res $LIBS" @@ -5955,10 +6508,10 @@ fi else - { echo "$as_me:$LINENO: checking for library containing opendir" >&5 -echo $ECHO_N "checking for library containing opendir... $ECHO_C" >&6; } + { $as_echo "$as_me:$LINENO: checking for library containing opendir" >&5 +$as_echo_n "checking for library containing opendir... " >&6; } if test "${ac_cv_search_opendir+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 + $as_echo_n "(cached) " >&6 else ac_func_search_save_LIBS=$LIBS cat >conftest.$ac_ext <<_ACEOF @@ -5996,26 +6549,30 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_link") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { test -z "$ac_c_werror_flag" || test ! -s conftest.err - } && test -s conftest$ac_exeext && - $as_test_x conftest$ac_exeext; then + } && test -s conftest$ac_exeext && { + test "$cross_compiling" = yes || + $as_test_x conftest$ac_exeext + }; then ac_cv_search_opendir=$ac_res else - echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 fi +rm -rf conftest.dSYM rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \ conftest$ac_exeext if test "${ac_cv_search_opendir+set}" = set; then @@ -6030,8 +6587,8 @@ rm conftest.$ac_ext LIBS=$ac_func_search_save_LIBS fi -{ echo "$as_me:$LINENO: result: $ac_cv_search_opendir" >&5 -echo "${ECHO_T}$ac_cv_search_opendir" >&6; } +{ $as_echo "$as_me:$LINENO: result: $ac_cv_search_opendir" >&5 +$as_echo "$ac_cv_search_opendir" >&6; } ac_res=$ac_cv_search_opendir if test "$ac_res" != no; then test "$ac_res" = "none required" || LIBS="$ac_res $LIBS" @@ -6040,10 +6597,10 @@ fi -{ echo "$as_me:$LINENO: checking whether sys/types.h defines makedev" >&5 -echo $ECHO_N "checking whether sys/types.h defines makedev... $ECHO_C" >&6; } +{ $as_echo "$as_me:$LINENO: checking whether sys/types.h defines makedev" >&5 +$as_echo_n "checking whether sys/types.h defines makedev... " >&6; } if test "${ac_cv_header_sys_types_h_makedev+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 + $as_echo_n "(cached) " >&6 else cat >conftest.$ac_ext <<_ACEOF /* confdefs.h. */ @@ -6066,46 +6623,50 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_link") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { test -z "$ac_c_werror_flag" || test ! -s conftest.err - } && test -s conftest$ac_exeext && - $as_test_x conftest$ac_exeext; then + } && test -s conftest$ac_exeext && { + test "$cross_compiling" = yes || + $as_test_x conftest$ac_exeext + }; then ac_cv_header_sys_types_h_makedev=yes else - echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 ac_cv_header_sys_types_h_makedev=no fi +rm -rf conftest.dSYM rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \ conftest$ac_exeext conftest.$ac_ext fi -{ echo "$as_me:$LINENO: result: $ac_cv_header_sys_types_h_makedev" >&5 -echo "${ECHO_T}$ac_cv_header_sys_types_h_makedev" >&6; } +{ $as_echo "$as_me:$LINENO: result: $ac_cv_header_sys_types_h_makedev" >&5 +$as_echo "$ac_cv_header_sys_types_h_makedev" >&6; } if test $ac_cv_header_sys_types_h_makedev = no; then if test "${ac_cv_header_sys_mkdev_h+set}" = set; then - { echo "$as_me:$LINENO: checking for sys/mkdev.h" >&5 -echo $ECHO_N "checking for sys/mkdev.h... $ECHO_C" >&6; } + { $as_echo "$as_me:$LINENO: checking for sys/mkdev.h" >&5 +$as_echo_n "checking for sys/mkdev.h... " >&6; } if test "${ac_cv_header_sys_mkdev_h+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 + $as_echo_n "(cached) " >&6 fi -{ echo "$as_me:$LINENO: result: $ac_cv_header_sys_mkdev_h" >&5 -echo "${ECHO_T}$ac_cv_header_sys_mkdev_h" >&6; } +{ $as_echo "$as_me:$LINENO: result: $ac_cv_header_sys_mkdev_h" >&5 +$as_echo "$ac_cv_header_sys_mkdev_h" >&6; } else # Is the header compilable? -{ echo "$as_me:$LINENO: checking sys/mkdev.h usability" >&5 -echo $ECHO_N "checking sys/mkdev.h usability... $ECHO_C" >&6; } +{ $as_echo "$as_me:$LINENO: checking sys/mkdev.h usability" >&5 +$as_echo_n "checking sys/mkdev.h usability... " >&6; } cat >conftest.$ac_ext <<_ACEOF /* confdefs.h. */ _ACEOF @@ -6121,32 +6682,33 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_compile") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { test -z "$ac_c_werror_flag" || test ! -s conftest.err } && test -s conftest.$ac_objext; then ac_header_compiler=yes else - echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 ac_header_compiler=no fi rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext -{ echo "$as_me:$LINENO: result: $ac_header_compiler" >&5 -echo "${ECHO_T}$ac_header_compiler" >&6; } +{ $as_echo "$as_me:$LINENO: result: $ac_header_compiler" >&5 +$as_echo "$ac_header_compiler" >&6; } # Is the header present? -{ echo "$as_me:$LINENO: checking sys/mkdev.h presence" >&5 -echo $ECHO_N "checking sys/mkdev.h presence... $ECHO_C" >&6; } +{ $as_echo "$as_me:$LINENO: checking sys/mkdev.h presence" >&5 +$as_echo_n "checking sys/mkdev.h presence... " >&6; } cat >conftest.$ac_ext <<_ACEOF /* confdefs.h. */ _ACEOF @@ -6160,51 +6722,52 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_cpp conftest.$ac_ext") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } >/dev/null && { test -z "$ac_c_preproc_warn_flag$ac_c_werror_flag" || test ! -s conftest.err }; then ac_header_preproc=yes else - echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 ac_header_preproc=no fi rm -f conftest.err conftest.$ac_ext -{ echo "$as_me:$LINENO: result: $ac_header_preproc" >&5 -echo "${ECHO_T}$ac_header_preproc" >&6; } +{ $as_echo "$as_me:$LINENO: result: $ac_header_preproc" >&5 +$as_echo "$ac_header_preproc" >&6; } # So? What about this header? case $ac_header_compiler:$ac_header_preproc:$ac_c_preproc_warn_flag in yes:no: ) - { echo "$as_me:$LINENO: WARNING: sys/mkdev.h: accepted by the compiler, rejected by the preprocessor!" >&5 -echo "$as_me: WARNING: sys/mkdev.h: accepted by the compiler, rejected by the preprocessor!" >&2;} - { echo "$as_me:$LINENO: WARNING: sys/mkdev.h: proceeding with the compiler's result" >&5 -echo "$as_me: WARNING: sys/mkdev.h: proceeding with the compiler's result" >&2;} + { $as_echo "$as_me:$LINENO: WARNING: sys/mkdev.h: accepted by the compiler, rejected by the preprocessor!" >&5 +$as_echo "$as_me: WARNING: sys/mkdev.h: accepted by the compiler, rejected by the preprocessor!" >&2;} + { $as_echo "$as_me:$LINENO: WARNING: sys/mkdev.h: proceeding with the compiler's result" >&5 +$as_echo "$as_me: WARNING: sys/mkdev.h: proceeding with the compiler's result" >&2;} ac_header_preproc=yes ;; no:yes:* ) - { echo "$as_me:$LINENO: WARNING: sys/mkdev.h: present but cannot be compiled" >&5 -echo "$as_me: WARNING: sys/mkdev.h: present but cannot be compiled" >&2;} - { echo "$as_me:$LINENO: WARNING: sys/mkdev.h: check for missing prerequisite headers?" >&5 -echo "$as_me: WARNING: sys/mkdev.h: check for missing prerequisite headers?" >&2;} - { echo "$as_me:$LINENO: WARNING: sys/mkdev.h: see the Autoconf documentation" >&5 -echo "$as_me: WARNING: sys/mkdev.h: see the Autoconf documentation" >&2;} - { echo "$as_me:$LINENO: WARNING: sys/mkdev.h: section \"Present But Cannot Be Compiled\"" >&5 -echo "$as_me: WARNING: sys/mkdev.h: section \"Present But Cannot Be Compiled\"" >&2;} - { echo "$as_me:$LINENO: WARNING: sys/mkdev.h: proceeding with the preprocessor's result" >&5 -echo "$as_me: WARNING: sys/mkdev.h: proceeding with the preprocessor's result" >&2;} - { echo "$as_me:$LINENO: WARNING: sys/mkdev.h: in the future, the compiler will take precedence" >&5 -echo "$as_me: WARNING: sys/mkdev.h: in the future, the compiler will take precedence" >&2;} + { $as_echo "$as_me:$LINENO: WARNING: sys/mkdev.h: present but cannot be compiled" >&5 +$as_echo "$as_me: WARNING: sys/mkdev.h: present but cannot be compiled" >&2;} + { $as_echo "$as_me:$LINENO: WARNING: sys/mkdev.h: check for missing prerequisite headers?" >&5 +$as_echo "$as_me: WARNING: sys/mkdev.h: check for missing prerequisite headers?" >&2;} + { $as_echo "$as_me:$LINENO: WARNING: sys/mkdev.h: see the Autoconf documentation" >&5 +$as_echo "$as_me: WARNING: sys/mkdev.h: see the Autoconf documentation" >&2;} + { $as_echo "$as_me:$LINENO: WARNING: sys/mkdev.h: section \"Present But Cannot Be Compiled\"" >&5 +$as_echo "$as_me: WARNING: sys/mkdev.h: section \"Present But Cannot Be Compiled\"" >&2;} + { $as_echo "$as_me:$LINENO: WARNING: sys/mkdev.h: proceeding with the preprocessor's result" >&5 +$as_echo "$as_me: WARNING: sys/mkdev.h: proceeding with the preprocessor's result" >&2;} + { $as_echo "$as_me:$LINENO: WARNING: sys/mkdev.h: in the future, the compiler will take precedence" >&5 +$as_echo "$as_me: WARNING: sys/mkdev.h: in the future, the compiler will take precedence" >&2;} ( cat <<\_ASBOX ## -------------------------------------- ## ## Report this to http://bugs.python.org/ ## @@ -6213,18 +6776,18 @@ ) | sed "s/^/$as_me: WARNING: /" >&2 ;; esac -{ echo "$as_me:$LINENO: checking for sys/mkdev.h" >&5 -echo $ECHO_N "checking for sys/mkdev.h... $ECHO_C" >&6; } +{ $as_echo "$as_me:$LINENO: checking for sys/mkdev.h" >&5 +$as_echo_n "checking for sys/mkdev.h... " >&6; } if test "${ac_cv_header_sys_mkdev_h+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 + $as_echo_n "(cached) " >&6 else ac_cv_header_sys_mkdev_h=$ac_header_preproc fi -{ echo "$as_me:$LINENO: result: $ac_cv_header_sys_mkdev_h" >&5 -echo "${ECHO_T}$ac_cv_header_sys_mkdev_h" >&6; } +{ $as_echo "$as_me:$LINENO: result: $ac_cv_header_sys_mkdev_h" >&5 +$as_echo "$ac_cv_header_sys_mkdev_h" >&6; } fi -if test $ac_cv_header_sys_mkdev_h = yes; then +if test "x$ac_cv_header_sys_mkdev_h" = x""yes; then cat >>confdefs.h <<\_ACEOF #define MAJOR_IN_MKDEV 1 @@ -6236,17 +6799,17 @@ if test $ac_cv_header_sys_mkdev_h = no; then if test "${ac_cv_header_sys_sysmacros_h+set}" = set; then - { echo "$as_me:$LINENO: checking for sys/sysmacros.h" >&5 -echo $ECHO_N "checking for sys/sysmacros.h... $ECHO_C" >&6; } + { $as_echo "$as_me:$LINENO: checking for sys/sysmacros.h" >&5 +$as_echo_n "checking for sys/sysmacros.h... " >&6; } if test "${ac_cv_header_sys_sysmacros_h+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 + $as_echo_n "(cached) " >&6 fi -{ echo "$as_me:$LINENO: result: $ac_cv_header_sys_sysmacros_h" >&5 -echo "${ECHO_T}$ac_cv_header_sys_sysmacros_h" >&6; } +{ $as_echo "$as_me:$LINENO: result: $ac_cv_header_sys_sysmacros_h" >&5 +$as_echo "$ac_cv_header_sys_sysmacros_h" >&6; } else # Is the header compilable? -{ echo "$as_me:$LINENO: checking sys/sysmacros.h usability" >&5 -echo $ECHO_N "checking sys/sysmacros.h usability... $ECHO_C" >&6; } +{ $as_echo "$as_me:$LINENO: checking sys/sysmacros.h usability" >&5 +$as_echo_n "checking sys/sysmacros.h usability... " >&6; } cat >conftest.$ac_ext <<_ACEOF /* confdefs.h. */ _ACEOF @@ -6262,32 +6825,33 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_compile") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { test -z "$ac_c_werror_flag" || test ! -s conftest.err } && test -s conftest.$ac_objext; then ac_header_compiler=yes else - echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 ac_header_compiler=no fi rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext -{ echo "$as_me:$LINENO: result: $ac_header_compiler" >&5 -echo "${ECHO_T}$ac_header_compiler" >&6; } +{ $as_echo "$as_me:$LINENO: result: $ac_header_compiler" >&5 +$as_echo "$ac_header_compiler" >&6; } # Is the header present? -{ echo "$as_me:$LINENO: checking sys/sysmacros.h presence" >&5 -echo $ECHO_N "checking sys/sysmacros.h presence... $ECHO_C" >&6; } +{ $as_echo "$as_me:$LINENO: checking sys/sysmacros.h presence" >&5 +$as_echo_n "checking sys/sysmacros.h presence... " >&6; } cat >conftest.$ac_ext <<_ACEOF /* confdefs.h. */ _ACEOF @@ -6301,51 +6865,52 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_cpp conftest.$ac_ext") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } >/dev/null && { test -z "$ac_c_preproc_warn_flag$ac_c_werror_flag" || test ! -s conftest.err }; then ac_header_preproc=yes else - echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 ac_header_preproc=no fi rm -f conftest.err conftest.$ac_ext -{ echo "$as_me:$LINENO: result: $ac_header_preproc" >&5 -echo "${ECHO_T}$ac_header_preproc" >&6; } +{ $as_echo "$as_me:$LINENO: result: $ac_header_preproc" >&5 +$as_echo "$ac_header_preproc" >&6; } # So? What about this header? case $ac_header_compiler:$ac_header_preproc:$ac_c_preproc_warn_flag in yes:no: ) - { echo "$as_me:$LINENO: WARNING: sys/sysmacros.h: accepted by the compiler, rejected by the preprocessor!" >&5 -echo "$as_me: WARNING: sys/sysmacros.h: accepted by the compiler, rejected by the preprocessor!" >&2;} - { echo "$as_me:$LINENO: WARNING: sys/sysmacros.h: proceeding with the compiler's result" >&5 -echo "$as_me: WARNING: sys/sysmacros.h: proceeding with the compiler's result" >&2;} + { $as_echo "$as_me:$LINENO: WARNING: sys/sysmacros.h: accepted by the compiler, rejected by the preprocessor!" >&5 +$as_echo "$as_me: WARNING: sys/sysmacros.h: accepted by the compiler, rejected by the preprocessor!" >&2;} + { $as_echo "$as_me:$LINENO: WARNING: sys/sysmacros.h: proceeding with the compiler's result" >&5 +$as_echo "$as_me: WARNING: sys/sysmacros.h: proceeding with the compiler's result" >&2;} ac_header_preproc=yes ;; no:yes:* ) - { echo "$as_me:$LINENO: WARNING: sys/sysmacros.h: present but cannot be compiled" >&5 -echo "$as_me: WARNING: sys/sysmacros.h: present but cannot be compiled" >&2;} - { echo "$as_me:$LINENO: WARNING: sys/sysmacros.h: check for missing prerequisite headers?" >&5 -echo "$as_me: WARNING: sys/sysmacros.h: check for missing prerequisite headers?" >&2;} - { echo "$as_me:$LINENO: WARNING: sys/sysmacros.h: see the Autoconf documentation" >&5 -echo "$as_me: WARNING: sys/sysmacros.h: see the Autoconf documentation" >&2;} - { echo "$as_me:$LINENO: WARNING: sys/sysmacros.h: section \"Present But Cannot Be Compiled\"" >&5 -echo "$as_me: WARNING: sys/sysmacros.h: section \"Present But Cannot Be Compiled\"" >&2;} - { echo "$as_me:$LINENO: WARNING: sys/sysmacros.h: proceeding with the preprocessor's result" >&5 -echo "$as_me: WARNING: sys/sysmacros.h: proceeding with the preprocessor's result" >&2;} - { echo "$as_me:$LINENO: WARNING: sys/sysmacros.h: in the future, the compiler will take precedence" >&5 -echo "$as_me: WARNING: sys/sysmacros.h: in the future, the compiler will take precedence" >&2;} + { $as_echo "$as_me:$LINENO: WARNING: sys/sysmacros.h: present but cannot be compiled" >&5 +$as_echo "$as_me: WARNING: sys/sysmacros.h: present but cannot be compiled" >&2;} + { $as_echo "$as_me:$LINENO: WARNING: sys/sysmacros.h: check for missing prerequisite headers?" >&5 +$as_echo "$as_me: WARNING: sys/sysmacros.h: check for missing prerequisite headers?" >&2;} + { $as_echo "$as_me:$LINENO: WARNING: sys/sysmacros.h: see the Autoconf documentation" >&5 +$as_echo "$as_me: WARNING: sys/sysmacros.h: see the Autoconf documentation" >&2;} + { $as_echo "$as_me:$LINENO: WARNING: sys/sysmacros.h: section \"Present But Cannot Be Compiled\"" >&5 +$as_echo "$as_me: WARNING: sys/sysmacros.h: section \"Present But Cannot Be Compiled\"" >&2;} + { $as_echo "$as_me:$LINENO: WARNING: sys/sysmacros.h: proceeding with the preprocessor's result" >&5 +$as_echo "$as_me: WARNING: sys/sysmacros.h: proceeding with the preprocessor's result" >&2;} + { $as_echo "$as_me:$LINENO: WARNING: sys/sysmacros.h: in the future, the compiler will take precedence" >&5 +$as_echo "$as_me: WARNING: sys/sysmacros.h: in the future, the compiler will take precedence" >&2;} ( cat <<\_ASBOX ## -------------------------------------- ## ## Report this to http://bugs.python.org/ ## @@ -6354,18 +6919,18 @@ ) | sed "s/^/$as_me: WARNING: /" >&2 ;; esac -{ echo "$as_me:$LINENO: checking for sys/sysmacros.h" >&5 -echo $ECHO_N "checking for sys/sysmacros.h... $ECHO_C" >&6; } +{ $as_echo "$as_me:$LINENO: checking for sys/sysmacros.h" >&5 +$as_echo_n "checking for sys/sysmacros.h... " >&6; } if test "${ac_cv_header_sys_sysmacros_h+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 + $as_echo_n "(cached) " >&6 else ac_cv_header_sys_sysmacros_h=$ac_header_preproc fi -{ echo "$as_me:$LINENO: result: $ac_cv_header_sys_sysmacros_h" >&5 -echo "${ECHO_T}$ac_cv_header_sys_sysmacros_h" >&6; } +{ $as_echo "$as_me:$LINENO: result: $ac_cv_header_sys_sysmacros_h" >&5 +$as_echo "$ac_cv_header_sys_sysmacros_h" >&6; } fi -if test $ac_cv_header_sys_sysmacros_h = yes; then +if test "x$ac_cv_header_sys_sysmacros_h" = x""yes; then cat >>confdefs.h <<\_ACEOF #define MAJOR_IN_SYSMACROS 1 @@ -6382,11 +6947,11 @@ for ac_header in term.h do -as_ac_Header=`echo "ac_cv_header_$ac_header" | $as_tr_sh` -{ echo "$as_me:$LINENO: checking for $ac_header" >&5 -echo $ECHO_N "checking for $ac_header... $ECHO_C" >&6; } +as_ac_Header=`$as_echo "ac_cv_header_$ac_header" | $as_tr_sh` +{ $as_echo "$as_me:$LINENO: checking for $ac_header" >&5 +$as_echo_n "checking for $ac_header... " >&6; } if { as_var=$as_ac_Header; eval "test \"\${$as_var+set}\" = set"; }; then - echo $ECHO_N "(cached) $ECHO_C" >&6 + $as_echo_n "(cached) " >&6 else cat >conftest.$ac_ext <<_ACEOF /* confdefs.h. */ @@ -6408,20 +6973,21 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_compile") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { test -z "$ac_c_werror_flag" || test ! -s conftest.err } && test -s conftest.$ac_objext; then eval "$as_ac_Header=yes" else - echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 eval "$as_ac_Header=no" @@ -6429,12 +6995,15 @@ rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext fi -ac_res=`eval echo '${'$as_ac_Header'}'` - { echo "$as_me:$LINENO: result: $ac_res" >&5 -echo "${ECHO_T}$ac_res" >&6; } -if test `eval echo '${'$as_ac_Header'}'` = yes; then +ac_res=`eval 'as_val=${'$as_ac_Header'} + $as_echo "$as_val"'` + { $as_echo "$as_me:$LINENO: result: $ac_res" >&5 +$as_echo "$ac_res" >&6; } +as_val=`eval 'as_val=${'$as_ac_Header'} + $as_echo "$as_val"'` + if test "x$as_val" = x""yes; then cat >>confdefs.h <<_ACEOF -#define `echo "HAVE_$ac_header" | $as_tr_cpp` 1 +#define `$as_echo "HAVE_$ac_header" | $as_tr_cpp` 1 _ACEOF fi @@ -6446,11 +7015,11 @@ for ac_header in linux/netlink.h do -as_ac_Header=`echo "ac_cv_header_$ac_header" | $as_tr_sh` -{ echo "$as_me:$LINENO: checking for $ac_header" >&5 -echo $ECHO_N "checking for $ac_header... $ECHO_C" >&6; } +as_ac_Header=`$as_echo "ac_cv_header_$ac_header" | $as_tr_sh` +{ $as_echo "$as_me:$LINENO: checking for $ac_header" >&5 +$as_echo_n "checking for $ac_header... " >&6; } if { as_var=$as_ac_Header; eval "test \"\${$as_var+set}\" = set"; }; then - echo $ECHO_N "(cached) $ECHO_C" >&6 + $as_echo_n "(cached) " >&6 else cat >conftest.$ac_ext <<_ACEOF /* confdefs.h. */ @@ -6475,20 +7044,21 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_compile") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { test -z "$ac_c_werror_flag" || test ! -s conftest.err } && test -s conftest.$ac_objext; then eval "$as_ac_Header=yes" else - echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 eval "$as_ac_Header=no" @@ -6496,12 +7066,15 @@ rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext fi -ac_res=`eval echo '${'$as_ac_Header'}'` - { echo "$as_me:$LINENO: result: $ac_res" >&5 -echo "${ECHO_T}$ac_res" >&6; } -if test `eval echo '${'$as_ac_Header'}'` = yes; then +ac_res=`eval 'as_val=${'$as_ac_Header'} + $as_echo "$as_val"'` + { $as_echo "$as_me:$LINENO: result: $ac_res" >&5 +$as_echo "$ac_res" >&6; } +as_val=`eval 'as_val=${'$as_ac_Header'} + $as_echo "$as_val"'` + if test "x$as_val" = x""yes; then cat >>confdefs.h <<_ACEOF -#define `echo "HAVE_$ac_header" | $as_tr_cpp` 1 +#define `$as_echo "HAVE_$ac_header" | $as_tr_cpp` 1 _ACEOF fi @@ -6511,8 +7084,8 @@ # checks for typedefs was_it_defined=no -{ echo "$as_me:$LINENO: checking for clock_t in time.h" >&5 -echo $ECHO_N "checking for clock_t in time.h... $ECHO_C" >&6; } +{ $as_echo "$as_me:$LINENO: checking for clock_t in time.h" >&5 +$as_echo_n "checking for clock_t in time.h... " >&6; } cat >conftest.$ac_ext <<_ACEOF /* confdefs.h. */ _ACEOF @@ -6536,12 +7109,12 @@ fi rm -f conftest* -{ echo "$as_me:$LINENO: result: $was_it_defined" >&5 -echo "${ECHO_T}$was_it_defined" >&6; } +{ $as_echo "$as_me:$LINENO: result: $was_it_defined" >&5 +$as_echo "$was_it_defined" >&6; } # Check whether using makedev requires defining _OSF_SOURCE -{ echo "$as_me:$LINENO: checking for makedev" >&5 -echo $ECHO_N "checking for makedev... $ECHO_C" >&6; } +{ $as_echo "$as_me:$LINENO: checking for makedev" >&5 +$as_echo_n "checking for makedev... " >&6; } cat >conftest.$ac_ext <<_ACEOF /* confdefs.h. */ _ACEOF @@ -6570,26 +7143,30 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_link") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { test -z "$ac_c_werror_flag" || test ! -s conftest.err - } && test -s conftest$ac_exeext && - $as_test_x conftest$ac_exeext; then + } && test -s conftest$ac_exeext && { + test "$cross_compiling" = yes || + $as_test_x conftest$ac_exeext + }; then ac_cv_has_makedev=yes else - echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 ac_cv_has_makedev=no fi +rm -rf conftest.dSYM rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \ conftest$ac_exeext conftest.$ac_ext if test "$ac_cv_has_makedev" = "no"; then @@ -6618,26 +7195,30 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_link") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { test -z "$ac_c_werror_flag" || test ! -s conftest.err - } && test -s conftest$ac_exeext && - $as_test_x conftest$ac_exeext; then + } && test -s conftest$ac_exeext && { + test "$cross_compiling" = yes || + $as_test_x conftest$ac_exeext + }; then ac_cv_has_makedev=yes else - echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 ac_cv_has_makedev=no fi +rm -rf conftest.dSYM rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \ conftest$ac_exeext conftest.$ac_ext if test "$ac_cv_has_makedev" = "yes"; then @@ -6648,8 +7229,8 @@ fi fi -{ echo "$as_me:$LINENO: result: $ac_cv_has_makedev" >&5 -echo "${ECHO_T}$ac_cv_has_makedev" >&6; } +{ $as_echo "$as_me:$LINENO: result: $ac_cv_has_makedev" >&5 +$as_echo "$ac_cv_has_makedev" >&6; } if test "$ac_cv_has_makedev" = "yes"; then cat >>confdefs.h <<\_ACEOF @@ -6666,8 +7247,8 @@ # work-around, disable LFS on such configurations use_lfs=yes -{ echo "$as_me:$LINENO: checking Solaris LFS bug" >&5 -echo $ECHO_N "checking Solaris LFS bug... $ECHO_C" >&6; } +{ $as_echo "$as_me:$LINENO: checking Solaris LFS bug" >&5 +$as_echo_n "checking Solaris LFS bug... " >&6; } cat >conftest.$ac_ext <<_ACEOF /* confdefs.h. */ _ACEOF @@ -6693,28 +7274,29 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_compile") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { test -z "$ac_c_werror_flag" || test ! -s conftest.err } && test -s conftest.$ac_objext; then sol_lfs_bug=no else - echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 sol_lfs_bug=yes fi rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext -{ echo "$as_me:$LINENO: result: $sol_lfs_bug" >&5 -echo "${ECHO_T}$sol_lfs_bug" >&6; } +{ $as_echo "$as_me:$LINENO: result: $sol_lfs_bug" >&5 +$as_echo "$sol_lfs_bug" >&6; } if test "$sol_lfs_bug" = "yes"; then use_lfs=no fi @@ -6742,26 +7324,58 @@ EOF # Type availability checks -{ echo "$as_me:$LINENO: checking for mode_t" >&5 -echo $ECHO_N "checking for mode_t... $ECHO_C" >&6; } +{ $as_echo "$as_me:$LINENO: checking for mode_t" >&5 +$as_echo_n "checking for mode_t... " >&6; } if test "${ac_cv_type_mode_t+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 + $as_echo_n "(cached) " >&6 else - cat >conftest.$ac_ext <<_ACEOF + ac_cv_type_mode_t=no +cat >conftest.$ac_ext <<_ACEOF /* confdefs.h. */ _ACEOF cat confdefs.h >>conftest.$ac_ext cat >>conftest.$ac_ext <<_ACEOF /* end confdefs.h. */ $ac_includes_default -typedef mode_t ac__type_new_; int main () { -if ((ac__type_new_ *) 0) - return 0; -if (sizeof (ac__type_new_)) +if (sizeof (mode_t)) + return 0; + ; return 0; +} +_ACEOF +rm -f conftest.$ac_objext +if { (ac_try="$ac_compile" +case "(($ac_try" in + *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; + *) ac_try_echo=$ac_try;; +esac +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 + (eval "$ac_compile") 2>conftest.er1 + ac_status=$? + grep -v '^ *+' conftest.er1 >conftest.err + rm -f conftest.er1 + cat conftest.err >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 + (exit $ac_status); } && { + test -z "$ac_c_werror_flag" || + test ! -s conftest.err + } && test -s conftest.$ac_objext; then + cat >conftest.$ac_ext <<_ACEOF +/* confdefs.h. */ +_ACEOF +cat confdefs.h >>conftest.$ac_ext +cat >>conftest.$ac_ext <<_ACEOF +/* end confdefs.h. */ +$ac_includes_default +int +main () +{ +if (sizeof ((mode_t))) + return 0; ; return 0; } @@ -6772,30 +7386,39 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_compile") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { test -z "$ac_c_werror_flag" || test ! -s conftest.err } && test -s conftest.$ac_objext; then - ac_cv_type_mode_t=yes + : +else + $as_echo "$as_me: failed program was:" >&5 +sed 's/^/| /' conftest.$ac_ext >&5 + + ac_cv_type_mode_t=yes +fi + +rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext else - echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 - ac_cv_type_mode_t=no + fi rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext fi -{ echo "$as_me:$LINENO: result: $ac_cv_type_mode_t" >&5 -echo "${ECHO_T}$ac_cv_type_mode_t" >&6; } -if test $ac_cv_type_mode_t = yes; then +{ $as_echo "$as_me:$LINENO: result: $ac_cv_type_mode_t" >&5 +$as_echo "$ac_cv_type_mode_t" >&6; } +if test "x$ac_cv_type_mode_t" = x""yes; then : else @@ -6805,26 +7428,58 @@ fi -{ echo "$as_me:$LINENO: checking for off_t" >&5 -echo $ECHO_N "checking for off_t... $ECHO_C" >&6; } +{ $as_echo "$as_me:$LINENO: checking for off_t" >&5 +$as_echo_n "checking for off_t... " >&6; } if test "${ac_cv_type_off_t+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 + $as_echo_n "(cached) " >&6 else - cat >conftest.$ac_ext <<_ACEOF + ac_cv_type_off_t=no +cat >conftest.$ac_ext <<_ACEOF /* confdefs.h. */ _ACEOF cat confdefs.h >>conftest.$ac_ext cat >>conftest.$ac_ext <<_ACEOF /* end confdefs.h. */ $ac_includes_default -typedef off_t ac__type_new_; int main () { -if ((ac__type_new_ *) 0) - return 0; -if (sizeof (ac__type_new_)) +if (sizeof (off_t)) + return 0; + ; return 0; +} +_ACEOF +rm -f conftest.$ac_objext +if { (ac_try="$ac_compile" +case "(($ac_try" in + *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; + *) ac_try_echo=$ac_try;; +esac +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 + (eval "$ac_compile") 2>conftest.er1 + ac_status=$? + grep -v '^ *+' conftest.er1 >conftest.err + rm -f conftest.er1 + cat conftest.err >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 + (exit $ac_status); } && { + test -z "$ac_c_werror_flag" || + test ! -s conftest.err + } && test -s conftest.$ac_objext; then + cat >conftest.$ac_ext <<_ACEOF +/* confdefs.h. */ +_ACEOF +cat confdefs.h >>conftest.$ac_ext +cat >>conftest.$ac_ext <<_ACEOF +/* end confdefs.h. */ +$ac_includes_default +int +main () +{ +if (sizeof ((off_t))) + return 0; ; return 0; } @@ -6835,30 +7490,39 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_compile") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { test -z "$ac_c_werror_flag" || test ! -s conftest.err } && test -s conftest.$ac_objext; then - ac_cv_type_off_t=yes + : +else + $as_echo "$as_me: failed program was:" >&5 +sed 's/^/| /' conftest.$ac_ext >&5 + + ac_cv_type_off_t=yes +fi + +rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext else - echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 - ac_cv_type_off_t=no + fi rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext fi -{ echo "$as_me:$LINENO: result: $ac_cv_type_off_t" >&5 -echo "${ECHO_T}$ac_cv_type_off_t" >&6; } -if test $ac_cv_type_off_t = yes; then +{ $as_echo "$as_me:$LINENO: result: $ac_cv_type_off_t" >&5 +$as_echo "$ac_cv_type_off_t" >&6; } +if test "x$ac_cv_type_off_t" = x""yes; then : else @@ -6868,26 +7532,58 @@ fi -{ echo "$as_me:$LINENO: checking for pid_t" >&5 -echo $ECHO_N "checking for pid_t... $ECHO_C" >&6; } +{ $as_echo "$as_me:$LINENO: checking for pid_t" >&5 +$as_echo_n "checking for pid_t... " >&6; } if test "${ac_cv_type_pid_t+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 + $as_echo_n "(cached) " >&6 else - cat >conftest.$ac_ext <<_ACEOF + ac_cv_type_pid_t=no +cat >conftest.$ac_ext <<_ACEOF /* confdefs.h. */ _ACEOF cat confdefs.h >>conftest.$ac_ext cat >>conftest.$ac_ext <<_ACEOF /* end confdefs.h. */ $ac_includes_default -typedef pid_t ac__type_new_; int main () { -if ((ac__type_new_ *) 0) - return 0; -if (sizeof (ac__type_new_)) +if (sizeof (pid_t)) + return 0; + ; return 0; +} +_ACEOF +rm -f conftest.$ac_objext +if { (ac_try="$ac_compile" +case "(($ac_try" in + *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; + *) ac_try_echo=$ac_try;; +esac +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 + (eval "$ac_compile") 2>conftest.er1 + ac_status=$? + grep -v '^ *+' conftest.er1 >conftest.err + rm -f conftest.er1 + cat conftest.err >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 + (exit $ac_status); } && { + test -z "$ac_c_werror_flag" || + test ! -s conftest.err + } && test -s conftest.$ac_objext; then + cat >conftest.$ac_ext <<_ACEOF +/* confdefs.h. */ +_ACEOF +cat confdefs.h >>conftest.$ac_ext +cat >>conftest.$ac_ext <<_ACEOF +/* end confdefs.h. */ +$ac_includes_default +int +main () +{ +if (sizeof ((pid_t))) + return 0; ; return 0; } @@ -6898,30 +7594,39 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_compile") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { test -z "$ac_c_werror_flag" || test ! -s conftest.err } && test -s conftest.$ac_objext; then - ac_cv_type_pid_t=yes + : else - echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 - ac_cv_type_pid_t=no + ac_cv_type_pid_t=yes fi rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext +else + $as_echo "$as_me: failed program was:" >&5 +sed 's/^/| /' conftest.$ac_ext >&5 + + fi -{ echo "$as_me:$LINENO: result: $ac_cv_type_pid_t" >&5 -echo "${ECHO_T}$ac_cv_type_pid_t" >&6; } -if test $ac_cv_type_pid_t = yes; then + +rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext +fi +{ $as_echo "$as_me:$LINENO: result: $ac_cv_type_pid_t" >&5 +$as_echo "$ac_cv_type_pid_t" >&6; } +if test "x$ac_cv_type_pid_t" = x""yes; then : else @@ -6931,10 +7636,10 @@ fi -{ echo "$as_me:$LINENO: checking return type of signal handlers" >&5 -echo $ECHO_N "checking return type of signal handlers... $ECHO_C" >&6; } +{ $as_echo "$as_me:$LINENO: checking return type of signal handlers" >&5 +$as_echo_n "checking return type of signal handlers... " >&6; } if test "${ac_cv_type_signal+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 + $as_echo_n "(cached) " >&6 else cat >conftest.$ac_ext <<_ACEOF /* confdefs.h. */ @@ -6959,20 +7664,21 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_compile") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { test -z "$ac_c_werror_flag" || test ! -s conftest.err } && test -s conftest.$ac_objext; then ac_cv_type_signal=int else - echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 ac_cv_type_signal=void @@ -6980,19 +7686,54 @@ rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext fi -{ echo "$as_me:$LINENO: result: $ac_cv_type_signal" >&5 -echo "${ECHO_T}$ac_cv_type_signal" >&6; } +{ $as_echo "$as_me:$LINENO: result: $ac_cv_type_signal" >&5 +$as_echo "$ac_cv_type_signal" >&6; } cat >>confdefs.h <<_ACEOF #define RETSIGTYPE $ac_cv_type_signal _ACEOF -{ echo "$as_me:$LINENO: checking for size_t" >&5 -echo $ECHO_N "checking for size_t... $ECHO_C" >&6; } +{ $as_echo "$as_me:$LINENO: checking for size_t" >&5 +$as_echo_n "checking for size_t... " >&6; } if test "${ac_cv_type_size_t+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 + $as_echo_n "(cached) " >&6 else + ac_cv_type_size_t=no +cat >conftest.$ac_ext <<_ACEOF +/* confdefs.h. */ +_ACEOF +cat confdefs.h >>conftest.$ac_ext +cat >>conftest.$ac_ext <<_ACEOF +/* end confdefs.h. */ +$ac_includes_default +int +main () +{ +if (sizeof (size_t)) + return 0; + ; + return 0; +} +_ACEOF +rm -f conftest.$ac_objext +if { (ac_try="$ac_compile" +case "(($ac_try" in + *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; + *) ac_try_echo=$ac_try;; +esac +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 + (eval "$ac_compile") 2>conftest.er1 + ac_status=$? + grep -v '^ *+' conftest.er1 >conftest.err + rm -f conftest.er1 + cat conftest.err >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 + (exit $ac_status); } && { + test -z "$ac_c_werror_flag" || + test ! -s conftest.err + } && test -s conftest.$ac_objext; then cat >conftest.$ac_ext <<_ACEOF /* confdefs.h. */ _ACEOF @@ -7000,14 +7741,11 @@ cat >>conftest.$ac_ext <<_ACEOF /* end confdefs.h. */ $ac_includes_default -typedef size_t ac__type_new_; int main () { -if ((ac__type_new_ *) 0) - return 0; -if (sizeof (ac__type_new_)) - return 0; +if (sizeof ((size_t))) + return 0; ; return 0; } @@ -7018,30 +7756,39 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_compile") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { test -z "$ac_c_werror_flag" || test ! -s conftest.err } && test -s conftest.$ac_objext; then - ac_cv_type_size_t=yes + : +else + $as_echo "$as_me: failed program was:" >&5 +sed 's/^/| /' conftest.$ac_ext >&5 + + ac_cv_type_size_t=yes +fi + +rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext else - echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 - ac_cv_type_size_t=no + fi rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext fi -{ echo "$as_me:$LINENO: result: $ac_cv_type_size_t" >&5 -echo "${ECHO_T}$ac_cv_type_size_t" >&6; } -if test $ac_cv_type_size_t = yes; then +{ $as_echo "$as_me:$LINENO: result: $ac_cv_type_size_t" >&5 +$as_echo "$ac_cv_type_size_t" >&6; } +if test "x$ac_cv_type_size_t" = x""yes; then : else @@ -7051,10 +7798,10 @@ fi -{ echo "$as_me:$LINENO: checking for uid_t in sys/types.h" >&5 -echo $ECHO_N "checking for uid_t in sys/types.h... $ECHO_C" >&6; } +{ $as_echo "$as_me:$LINENO: checking for uid_t in sys/types.h" >&5 +$as_echo_n "checking for uid_t in sys/types.h... " >&6; } if test "${ac_cv_type_uid_t+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 + $as_echo_n "(cached) " >&6 else cat >conftest.$ac_ext <<_ACEOF /* confdefs.h. */ @@ -7074,8 +7821,8 @@ rm -f conftest* fi -{ echo "$as_me:$LINENO: result: $ac_cv_type_uid_t" >&5 -echo "${ECHO_T}$ac_cv_type_uid_t" >&6; } +{ $as_echo "$as_me:$LINENO: result: $ac_cv_type_uid_t" >&5 +$as_echo "$ac_cv_type_uid_t" >&6; } if test $ac_cv_type_uid_t = no; then cat >>confdefs.h <<\_ACEOF @@ -7090,10 +7837,10 @@ fi - { echo "$as_me:$LINENO: checking for uint32_t" >&5 -echo $ECHO_N "checking for uint32_t... $ECHO_C" >&6; } + { $as_echo "$as_me:$LINENO: checking for uint32_t" >&5 +$as_echo_n "checking for uint32_t... " >&6; } if test "${ac_cv_c_uint32_t+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 + $as_echo_n "(cached) " >&6 else ac_cv_c_uint32_t=no for ac_type in 'uint32_t' 'unsigned int' 'unsigned long int' \ @@ -7121,13 +7868,14 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_compile") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { test -z "$ac_c_werror_flag" || test ! -s conftest.err @@ -7138,7 +7886,7 @@ esac else - echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 @@ -7148,8 +7896,8 @@ test "$ac_cv_c_uint32_t" != no && break done fi -{ echo "$as_me:$LINENO: result: $ac_cv_c_uint32_t" >&5 -echo "${ECHO_T}$ac_cv_c_uint32_t" >&6; } +{ $as_echo "$as_me:$LINENO: result: $ac_cv_c_uint32_t" >&5 +$as_echo "$ac_cv_c_uint32_t" >&6; } case $ac_cv_c_uint32_t in #( no|yes) ;; #( *) @@ -7166,10 +7914,10 @@ esac - { echo "$as_me:$LINENO: checking for uint64_t" >&5 -echo $ECHO_N "checking for uint64_t... $ECHO_C" >&6; } + { $as_echo "$as_me:$LINENO: checking for uint64_t" >&5 +$as_echo_n "checking for uint64_t... " >&6; } if test "${ac_cv_c_uint64_t+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 + $as_echo_n "(cached) " >&6 else ac_cv_c_uint64_t=no for ac_type in 'uint64_t' 'unsigned int' 'unsigned long int' \ @@ -7197,13 +7945,14 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_compile") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { test -z "$ac_c_werror_flag" || test ! -s conftest.err @@ -7214,7 +7963,7 @@ esac else - echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 @@ -7224,8 +7973,8 @@ test "$ac_cv_c_uint64_t" != no && break done fi -{ echo "$as_me:$LINENO: result: $ac_cv_c_uint64_t" >&5 -echo "${ECHO_T}$ac_cv_c_uint64_t" >&6; } +{ $as_echo "$as_me:$LINENO: result: $ac_cv_c_uint64_t" >&5 +$as_echo "$ac_cv_c_uint64_t" >&6; } case $ac_cv_c_uint64_t in #( no|yes) ;; #( *) @@ -7242,10 +7991,10 @@ esac - { echo "$as_me:$LINENO: checking for int32_t" >&5 -echo $ECHO_N "checking for int32_t... $ECHO_C" >&6; } + { $as_echo "$as_me:$LINENO: checking for int32_t" >&5 +$as_echo_n "checking for int32_t... " >&6; } if test "${ac_cv_c_int32_t+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 + $as_echo_n "(cached) " >&6 else ac_cv_c_int32_t=no for ac_type in 'int32_t' 'int' 'long int' \ @@ -7273,13 +8022,14 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_compile") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { test -z "$ac_c_werror_flag" || test ! -s conftest.err @@ -7295,7 +8045,7 @@ main () { static int test_array [1 - 2 * !(($ac_type) (((($ac_type) 1 << (32 - 2)) - 1) * 2 + 1) - < ($ac_type) (((($ac_type) 1 << (32 - 2)) - 1) * 2 + 2))]; + < ($ac_type) (((($ac_type) 1 << (32 - 2)) - 1) * 2 + 2))]; test_array [0] = 0 ; @@ -7308,20 +8058,21 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_compile") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { test -z "$ac_c_werror_flag" || test ! -s conftest.err } && test -s conftest.$ac_objext; then : else - echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 case $ac_type in @@ -7333,7 +8084,7 @@ rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext else - echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 @@ -7343,8 +8094,8 @@ test "$ac_cv_c_int32_t" != no && break done fi -{ echo "$as_me:$LINENO: result: $ac_cv_c_int32_t" >&5 -echo "${ECHO_T}$ac_cv_c_int32_t" >&6; } +{ $as_echo "$as_me:$LINENO: result: $ac_cv_c_int32_t" >&5 +$as_echo "$ac_cv_c_int32_t" >&6; } case $ac_cv_c_int32_t in #( no|yes) ;; #( *) @@ -7356,10 +8107,10 @@ esac - { echo "$as_me:$LINENO: checking for int64_t" >&5 -echo $ECHO_N "checking for int64_t... $ECHO_C" >&6; } + { $as_echo "$as_me:$LINENO: checking for int64_t" >&5 +$as_echo_n "checking for int64_t... " >&6; } if test "${ac_cv_c_int64_t+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 + $as_echo_n "(cached) " >&6 else ac_cv_c_int64_t=no for ac_type in 'int64_t' 'int' 'long int' \ @@ -7387,13 +8138,14 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_compile") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { test -z "$ac_c_werror_flag" || test ! -s conftest.err @@ -7409,7 +8161,7 @@ main () { static int test_array [1 - 2 * !(($ac_type) (((($ac_type) 1 << (64 - 2)) - 1) * 2 + 1) - < ($ac_type) (((($ac_type) 1 << (64 - 2)) - 1) * 2 + 2))]; + < ($ac_type) (((($ac_type) 1 << (64 - 2)) - 1) * 2 + 2))]; test_array [0] = 0 ; @@ -7422,20 +8174,21 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_compile") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { test -z "$ac_c_werror_flag" || test ! -s conftest.err } && test -s conftest.$ac_objext; then : else - echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 case $ac_type in @@ -7447,7 +8200,7 @@ rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext else - echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 @@ -7457,8 +8210,8 @@ test "$ac_cv_c_int64_t" != no && break done fi -{ echo "$as_me:$LINENO: result: $ac_cv_c_int64_t" >&5 -echo "${ECHO_T}$ac_cv_c_int64_t" >&6; } +{ $as_echo "$as_me:$LINENO: result: $ac_cv_c_int64_t" >&5 +$as_echo "$ac_cv_c_int64_t" >&6; } case $ac_cv_c_int64_t in #( no|yes) ;; #( *) @@ -7469,26 +8222,24 @@ ;; esac -{ echo "$as_me:$LINENO: checking for ssize_t" >&5 -echo $ECHO_N "checking for ssize_t... $ECHO_C" >&6; } +{ $as_echo "$as_me:$LINENO: checking for ssize_t" >&5 +$as_echo_n "checking for ssize_t... " >&6; } if test "${ac_cv_type_ssize_t+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 + $as_echo_n "(cached) " >&6 else - cat >conftest.$ac_ext <<_ACEOF + ac_cv_type_ssize_t=no +cat >conftest.$ac_ext <<_ACEOF /* confdefs.h. */ _ACEOF cat confdefs.h >>conftest.$ac_ext cat >>conftest.$ac_ext <<_ACEOF /* end confdefs.h. */ $ac_includes_default -typedef ssize_t ac__type_new_; int main () { -if ((ac__type_new_ *) 0) - return 0; -if (sizeof (ac__type_new_)) - return 0; +if (sizeof (ssize_t)) + return 0; ; return 0; } @@ -7499,45 +8250,18 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_compile") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { test -z "$ac_c_werror_flag" || test ! -s conftest.err } && test -s conftest.$ac_objext; then - ac_cv_type_ssize_t=yes -else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - ac_cv_type_ssize_t=no -fi - -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext -fi -{ echo "$as_me:$LINENO: result: $ac_cv_type_ssize_t" >&5 -echo "${ECHO_T}$ac_cv_type_ssize_t" >&6; } -if test $ac_cv_type_ssize_t = yes; then - -cat >>confdefs.h <<\_ACEOF -#define HAVE_SSIZE_T 1 -_ACEOF - -fi - - -# Sizes of various common basic types -# ANSI C requires sizeof(char) == 1, so no need to check it -{ echo "$as_me:$LINENO: checking for int" >&5 -echo $ECHO_N "checking for int... $ECHO_C" >&6; } -if test "${ac_cv_type_int+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 -else cat >conftest.$ac_ext <<_ACEOF /* confdefs.h. */ _ACEOF @@ -7545,14 +8269,11 @@ cat >>conftest.$ac_ext <<_ACEOF /* end confdefs.h. */ $ac_includes_default -typedef int ac__type_new_; int main () { -if ((ac__type_new_ *) 0) - return 0; -if (sizeof (ac__type_new_)) - return 0; +if (sizeof ((ssize_t))) + return 0; ; return 0; } @@ -7563,38 +8284,57 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_compile") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { test -z "$ac_c_werror_flag" || test ! -s conftest.err } && test -s conftest.$ac_objext; then - ac_cv_type_int=yes + : +else + $as_echo "$as_me: failed program was:" >&5 +sed 's/^/| /' conftest.$ac_ext >&5 + + ac_cv_type_ssize_t=yes +fi + +rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext else - echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 - ac_cv_type_int=no + fi rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext fi -{ echo "$as_me:$LINENO: result: $ac_cv_type_int" >&5 -echo "${ECHO_T}$ac_cv_type_int" >&6; } +{ $as_echo "$as_me:$LINENO: result: $ac_cv_type_ssize_t" >&5 +$as_echo "$ac_cv_type_ssize_t" >&6; } +if test "x$ac_cv_type_ssize_t" = x""yes; then + +cat >>confdefs.h <<\_ACEOF +#define HAVE_SSIZE_T 1 +_ACEOF + +fi + +# Sizes of various common basic types +# ANSI C requires sizeof(char) == 1, so no need to check it # The cast to long int works around a bug in the HP C Compiler # version HP92453-01 B.11.11.23709.GP, which incorrectly rejects # declarations like `int a3[[(sizeof (unsigned char)) >= 0]];'. # This bug is HP SR number 8606223364. -{ echo "$as_me:$LINENO: checking size of int" >&5 -echo $ECHO_N "checking size of int... $ECHO_C" >&6; } +{ $as_echo "$as_me:$LINENO: checking size of int" >&5 +$as_echo_n "checking size of int... " >&6; } if test "${ac_cv_sizeof_int+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 + $as_echo_n "(cached) " >&6 else if test "$cross_compiling" = yes; then # Depending upon the size, compute the lo and hi bounds. @@ -7605,11 +8345,10 @@ cat >>conftest.$ac_ext <<_ACEOF /* end confdefs.h. */ $ac_includes_default - typedef int ac__type_sizeof_; int main () { -static int test_array [1 - 2 * !(((long int) (sizeof (ac__type_sizeof_))) >= 0)]; +static int test_array [1 - 2 * !(((long int) (sizeof (int))) >= 0)]; test_array [0] = 0 ; @@ -7622,13 +8361,14 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_compile") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { test -z "$ac_c_werror_flag" || test ! -s conftest.err @@ -7642,11 +8382,10 @@ cat >>conftest.$ac_ext <<_ACEOF /* end confdefs.h. */ $ac_includes_default - typedef int ac__type_sizeof_; int main () { -static int test_array [1 - 2 * !(((long int) (sizeof (ac__type_sizeof_))) <= $ac_mid)]; +static int test_array [1 - 2 * !(((long int) (sizeof (int))) <= $ac_mid)]; test_array [0] = 0 ; @@ -7659,20 +8398,21 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_compile") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { test -z "$ac_c_werror_flag" || test ! -s conftest.err } && test -s conftest.$ac_objext; then ac_hi=$ac_mid; break else - echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 ac_lo=`expr $ac_mid + 1` @@ -7686,7 +8426,7 @@ rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext done else - echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 cat >conftest.$ac_ext <<_ACEOF @@ -7696,11 +8436,10 @@ cat >>conftest.$ac_ext <<_ACEOF /* end confdefs.h. */ $ac_includes_default - typedef int ac__type_sizeof_; int main () { -static int test_array [1 - 2 * !(((long int) (sizeof (ac__type_sizeof_))) < 0)]; +static int test_array [1 - 2 * !(((long int) (sizeof (int))) < 0)]; test_array [0] = 0 ; @@ -7713,13 +8452,14 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_compile") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { test -z "$ac_c_werror_flag" || test ! -s conftest.err @@ -7733,11 +8473,10 @@ cat >>conftest.$ac_ext <<_ACEOF /* end confdefs.h. */ $ac_includes_default - typedef int ac__type_sizeof_; int main () { -static int test_array [1 - 2 * !(((long int) (sizeof (ac__type_sizeof_))) >= $ac_mid)]; +static int test_array [1 - 2 * !(((long int) (sizeof (int))) >= $ac_mid)]; test_array [0] = 0 ; @@ -7750,20 +8489,21 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_compile") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { test -z "$ac_c_werror_flag" || test ! -s conftest.err } && test -s conftest.$ac_objext; then ac_lo=$ac_mid; break else - echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 ac_hi=`expr '(' $ac_mid ')' - 1` @@ -7777,7 +8517,7 @@ rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext done else - echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 ac_lo= ac_hi= @@ -7797,11 +8537,10 @@ cat >>conftest.$ac_ext <<_ACEOF /* end confdefs.h. */ $ac_includes_default - typedef int ac__type_sizeof_; int main () { -static int test_array [1 - 2 * !(((long int) (sizeof (ac__type_sizeof_))) <= $ac_mid)]; +static int test_array [1 - 2 * !(((long int) (sizeof (int))) <= $ac_mid)]; test_array [0] = 0 ; @@ -7814,20 +8553,21 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_compile") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { test -z "$ac_c_werror_flag" || test ! -s conftest.err } && test -s conftest.$ac_objext; then ac_hi=$ac_mid else - echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 ac_lo=`expr '(' $ac_mid ')' + 1` @@ -7838,11 +8578,13 @@ case $ac_lo in ?*) ac_cv_sizeof_int=$ac_lo;; '') if test "$ac_cv_type_int" = yes; then - { { echo "$as_me:$LINENO: error: cannot compute sizeof (int) + { { $as_echo "$as_me:$LINENO: error: in \`$ac_pwd':" >&5 +$as_echo "$as_me: error: in \`$ac_pwd':" >&2;} +{ { $as_echo "$as_me:$LINENO: error: cannot compute sizeof (int) See \`config.log' for more details." >&5 -echo "$as_me: error: cannot compute sizeof (int) +$as_echo "$as_me: error: cannot compute sizeof (int) See \`config.log' for more details." >&2;} - { (exit 77); exit 77; }; } + { (exit 77); exit 77; }; }; } else ac_cv_sizeof_int=0 fi ;; @@ -7855,9 +8597,8 @@ cat >>conftest.$ac_ext <<_ACEOF /* end confdefs.h. */ $ac_includes_default - typedef int ac__type_sizeof_; -static long int longval () { return (long int) (sizeof (ac__type_sizeof_)); } -static unsigned long int ulongval () { return (long int) (sizeof (ac__type_sizeof_)); } +static long int longval () { return (long int) (sizeof (int)); } +static unsigned long int ulongval () { return (long int) (sizeof (int)); } #include #include int @@ -7867,20 +8608,22 @@ FILE *f = fopen ("conftest.val", "w"); if (! f) return 1; - if (((long int) (sizeof (ac__type_sizeof_))) < 0) + if (((long int) (sizeof (int))) < 0) { long int i = longval (); - if (i != ((long int) (sizeof (ac__type_sizeof_)))) + if (i != ((long int) (sizeof (int)))) return 1; - fprintf (f, "%ld\n", i); + fprintf (f, "%ld", i); } else { unsigned long int i = ulongval (); - if (i != ((long int) (sizeof (ac__type_sizeof_)))) + if (i != ((long int) (sizeof (int)))) return 1; - fprintf (f, "%lu\n", i); + fprintf (f, "%lu", i); } + /* Do not output a trailing newline, as this causes \r\n confusion + on some platforms. */ return ferror (f) || fclose (f) != 0; ; @@ -7893,43 +8636,48 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_link") 2>&5 ac_status=$? - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { ac_try='./conftest$ac_exeext' { (case "(($ac_try" in *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_try") 2>&5 ac_status=$? - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); }; }; then ac_cv_sizeof_int=`cat conftest.val` else - echo "$as_me: program exited with status $ac_status" >&5 -echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: program exited with status $ac_status" >&5 +$as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 ( exit $ac_status ) if test "$ac_cv_type_int" = yes; then - { { echo "$as_me:$LINENO: error: cannot compute sizeof (int) + { { $as_echo "$as_me:$LINENO: error: in \`$ac_pwd':" >&5 +$as_echo "$as_me: error: in \`$ac_pwd':" >&2;} +{ { $as_echo "$as_me:$LINENO: error: cannot compute sizeof (int) See \`config.log' for more details." >&5 -echo "$as_me: error: cannot compute sizeof (int) +$as_echo "$as_me: error: cannot compute sizeof (int) See \`config.log' for more details." >&2;} - { (exit 77); exit 77; }; } + { (exit 77); exit 77; }; }; } else ac_cv_sizeof_int=0 fi fi +rm -rf conftest.dSYM rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext conftest.$ac_objext conftest.$ac_ext fi rm -f conftest.val fi -{ echo "$as_me:$LINENO: result: $ac_cv_sizeof_int" >&5 -echo "${ECHO_T}$ac_cv_sizeof_int" >&6; } +{ $as_echo "$as_me:$LINENO: result: $ac_cv_sizeof_int" >&5 +$as_echo "$ac_cv_sizeof_int" >&6; } @@ -7938,68 +8686,14 @@ _ACEOF -{ echo "$as_me:$LINENO: checking for long" >&5 -echo $ECHO_N "checking for long... $ECHO_C" >&6; } -if test "${ac_cv_type_long+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 -else - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -$ac_includes_default -typedef long ac__type_new_; -int -main () -{ -if ((ac__type_new_ *) 0) - return 0; -if (sizeof (ac__type_new_)) - return 0; - ; - return 0; -} -_ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - ac_cv_type_long=yes -else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - ac_cv_type_long=no -fi - -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext -fi -{ echo "$as_me:$LINENO: result: $ac_cv_type_long" >&5 -echo "${ECHO_T}$ac_cv_type_long" >&6; } - # The cast to long int works around a bug in the HP C Compiler # version HP92453-01 B.11.11.23709.GP, which incorrectly rejects # declarations like `int a3[[(sizeof (unsigned char)) >= 0]];'. # This bug is HP SR number 8606223364. -{ echo "$as_me:$LINENO: checking size of long" >&5 -echo $ECHO_N "checking size of long... $ECHO_C" >&6; } +{ $as_echo "$as_me:$LINENO: checking size of long" >&5 +$as_echo_n "checking size of long... " >&6; } if test "${ac_cv_sizeof_long+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 + $as_echo_n "(cached) " >&6 else if test "$cross_compiling" = yes; then # Depending upon the size, compute the lo and hi bounds. @@ -8010,11 +8704,10 @@ cat >>conftest.$ac_ext <<_ACEOF /* end confdefs.h. */ $ac_includes_default - typedef long ac__type_sizeof_; int main () { -static int test_array [1 - 2 * !(((long int) (sizeof (ac__type_sizeof_))) >= 0)]; +static int test_array [1 - 2 * !(((long int) (sizeof (long))) >= 0)]; test_array [0] = 0 ; @@ -8027,13 +8720,14 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_compile") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { test -z "$ac_c_werror_flag" || test ! -s conftest.err @@ -8047,11 +8741,10 @@ cat >>conftest.$ac_ext <<_ACEOF /* end confdefs.h. */ $ac_includes_default - typedef long ac__type_sizeof_; int main () { -static int test_array [1 - 2 * !(((long int) (sizeof (ac__type_sizeof_))) <= $ac_mid)]; +static int test_array [1 - 2 * !(((long int) (sizeof (long))) <= $ac_mid)]; test_array [0] = 0 ; @@ -8064,20 +8757,21 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_compile") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { test -z "$ac_c_werror_flag" || test ! -s conftest.err } && test -s conftest.$ac_objext; then ac_hi=$ac_mid; break else - echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 ac_lo=`expr $ac_mid + 1` @@ -8091,7 +8785,7 @@ rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext done else - echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 cat >conftest.$ac_ext <<_ACEOF @@ -8101,11 +8795,10 @@ cat >>conftest.$ac_ext <<_ACEOF /* end confdefs.h. */ $ac_includes_default - typedef long ac__type_sizeof_; int main () { -static int test_array [1 - 2 * !(((long int) (sizeof (ac__type_sizeof_))) < 0)]; +static int test_array [1 - 2 * !(((long int) (sizeof (long))) < 0)]; test_array [0] = 0 ; @@ -8118,13 +8811,14 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_compile") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { test -z "$ac_c_werror_flag" || test ! -s conftest.err @@ -8138,11 +8832,10 @@ cat >>conftest.$ac_ext <<_ACEOF /* end confdefs.h. */ $ac_includes_default - typedef long ac__type_sizeof_; int main () { -static int test_array [1 - 2 * !(((long int) (sizeof (ac__type_sizeof_))) >= $ac_mid)]; +static int test_array [1 - 2 * !(((long int) (sizeof (long))) >= $ac_mid)]; test_array [0] = 0 ; @@ -8155,20 +8848,21 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_compile") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { test -z "$ac_c_werror_flag" || test ! -s conftest.err } && test -s conftest.$ac_objext; then ac_lo=$ac_mid; break else - echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 ac_hi=`expr '(' $ac_mid ')' - 1` @@ -8182,7 +8876,7 @@ rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext done else - echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 ac_lo= ac_hi= @@ -8202,11 +8896,10 @@ cat >>conftest.$ac_ext <<_ACEOF /* end confdefs.h. */ $ac_includes_default - typedef long ac__type_sizeof_; int main () { -static int test_array [1 - 2 * !(((long int) (sizeof (ac__type_sizeof_))) <= $ac_mid)]; +static int test_array [1 - 2 * !(((long int) (sizeof (long))) <= $ac_mid)]; test_array [0] = 0 ; @@ -8219,20 +8912,21 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_compile") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { test -z "$ac_c_werror_flag" || test ! -s conftest.err } && test -s conftest.$ac_objext; then ac_hi=$ac_mid else - echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 ac_lo=`expr '(' $ac_mid ')' + 1` @@ -8243,11 +8937,13 @@ case $ac_lo in ?*) ac_cv_sizeof_long=$ac_lo;; '') if test "$ac_cv_type_long" = yes; then - { { echo "$as_me:$LINENO: error: cannot compute sizeof (long) + { { $as_echo "$as_me:$LINENO: error: in \`$ac_pwd':" >&5 +$as_echo "$as_me: error: in \`$ac_pwd':" >&2;} +{ { $as_echo "$as_me:$LINENO: error: cannot compute sizeof (long) See \`config.log' for more details." >&5 -echo "$as_me: error: cannot compute sizeof (long) +$as_echo "$as_me: error: cannot compute sizeof (long) See \`config.log' for more details." >&2;} - { (exit 77); exit 77; }; } + { (exit 77); exit 77; }; }; } else ac_cv_sizeof_long=0 fi ;; @@ -8260,9 +8956,8 @@ cat >>conftest.$ac_ext <<_ACEOF /* end confdefs.h. */ $ac_includes_default - typedef long ac__type_sizeof_; -static long int longval () { return (long int) (sizeof (ac__type_sizeof_)); } -static unsigned long int ulongval () { return (long int) (sizeof (ac__type_sizeof_)); } +static long int longval () { return (long int) (sizeof (long)); } +static unsigned long int ulongval () { return (long int) (sizeof (long)); } #include #include int @@ -8272,20 +8967,22 @@ FILE *f = fopen ("conftest.val", "w"); if (! f) return 1; - if (((long int) (sizeof (ac__type_sizeof_))) < 0) + if (((long int) (sizeof (long))) < 0) { long int i = longval (); - if (i != ((long int) (sizeof (ac__type_sizeof_)))) + if (i != ((long int) (sizeof (long)))) return 1; - fprintf (f, "%ld\n", i); + fprintf (f, "%ld", i); } else { unsigned long int i = ulongval (); - if (i != ((long int) (sizeof (ac__type_sizeof_)))) + if (i != ((long int) (sizeof (long)))) return 1; - fprintf (f, "%lu\n", i); + fprintf (f, "%lu", i); } + /* Do not output a trailing newline, as this causes \r\n confusion + on some platforms. */ return ferror (f) || fclose (f) != 0; ; @@ -8298,43 +8995,48 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_link") 2>&5 ac_status=$? - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { ac_try='./conftest$ac_exeext' { (case "(($ac_try" in *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_try") 2>&5 ac_status=$? - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); }; }; then ac_cv_sizeof_long=`cat conftest.val` else - echo "$as_me: program exited with status $ac_status" >&5 -echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: program exited with status $ac_status" >&5 +$as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 ( exit $ac_status ) if test "$ac_cv_type_long" = yes; then - { { echo "$as_me:$LINENO: error: cannot compute sizeof (long) + { { $as_echo "$as_me:$LINENO: error: in \`$ac_pwd':" >&5 +$as_echo "$as_me: error: in \`$ac_pwd':" >&2;} +{ { $as_echo "$as_me:$LINENO: error: cannot compute sizeof (long) See \`config.log' for more details." >&5 -echo "$as_me: error: cannot compute sizeof (long) +$as_echo "$as_me: error: cannot compute sizeof (long) See \`config.log' for more details." >&2;} - { (exit 77); exit 77; }; } + { (exit 77); exit 77; }; }; } else ac_cv_sizeof_long=0 fi fi +rm -rf conftest.dSYM rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext conftest.$ac_objext conftest.$ac_ext fi rm -f conftest.val fi -{ echo "$as_me:$LINENO: result: $ac_cv_sizeof_long" >&5 -echo "${ECHO_T}$ac_cv_sizeof_long" >&6; } +{ $as_echo "$as_me:$LINENO: result: $ac_cv_sizeof_long" >&5 +$as_echo "$ac_cv_sizeof_long" >&6; } @@ -8343,68 +9045,14 @@ _ACEOF -{ echo "$as_me:$LINENO: checking for void *" >&5 -echo $ECHO_N "checking for void *... $ECHO_C" >&6; } -if test "${ac_cv_type_void_p+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 -else - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -$ac_includes_default -typedef void * ac__type_new_; -int -main () -{ -if ((ac__type_new_ *) 0) - return 0; -if (sizeof (ac__type_new_)) - return 0; - ; - return 0; -} -_ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - ac_cv_type_void_p=yes -else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - ac_cv_type_void_p=no -fi - -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext -fi -{ echo "$as_me:$LINENO: result: $ac_cv_type_void_p" >&5 -echo "${ECHO_T}$ac_cv_type_void_p" >&6; } - # The cast to long int works around a bug in the HP C Compiler # version HP92453-01 B.11.11.23709.GP, which incorrectly rejects # declarations like `int a3[[(sizeof (unsigned char)) >= 0]];'. # This bug is HP SR number 8606223364. -{ echo "$as_me:$LINENO: checking size of void *" >&5 -echo $ECHO_N "checking size of void *... $ECHO_C" >&6; } +{ $as_echo "$as_me:$LINENO: checking size of void *" >&5 +$as_echo_n "checking size of void *... " >&6; } if test "${ac_cv_sizeof_void_p+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 + $as_echo_n "(cached) " >&6 else if test "$cross_compiling" = yes; then # Depending upon the size, compute the lo and hi bounds. @@ -8415,11 +9063,10 @@ cat >>conftest.$ac_ext <<_ACEOF /* end confdefs.h. */ $ac_includes_default - typedef void * ac__type_sizeof_; int main () { -static int test_array [1 - 2 * !(((long int) (sizeof (ac__type_sizeof_))) >= 0)]; +static int test_array [1 - 2 * !(((long int) (sizeof (void *))) >= 0)]; test_array [0] = 0 ; @@ -8432,13 +9079,14 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_compile") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { test -z "$ac_c_werror_flag" || test ! -s conftest.err @@ -8452,11 +9100,10 @@ cat >>conftest.$ac_ext <<_ACEOF /* end confdefs.h. */ $ac_includes_default - typedef void * ac__type_sizeof_; int main () { -static int test_array [1 - 2 * !(((long int) (sizeof (ac__type_sizeof_))) <= $ac_mid)]; +static int test_array [1 - 2 * !(((long int) (sizeof (void *))) <= $ac_mid)]; test_array [0] = 0 ; @@ -8469,20 +9116,21 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_compile") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { test -z "$ac_c_werror_flag" || test ! -s conftest.err } && test -s conftest.$ac_objext; then ac_hi=$ac_mid; break else - echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 ac_lo=`expr $ac_mid + 1` @@ -8496,7 +9144,7 @@ rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext done else - echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 cat >conftest.$ac_ext <<_ACEOF @@ -8506,11 +9154,10 @@ cat >>conftest.$ac_ext <<_ACEOF /* end confdefs.h. */ $ac_includes_default - typedef void * ac__type_sizeof_; int main () { -static int test_array [1 - 2 * !(((long int) (sizeof (ac__type_sizeof_))) < 0)]; +static int test_array [1 - 2 * !(((long int) (sizeof (void *))) < 0)]; test_array [0] = 0 ; @@ -8523,13 +9170,14 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_compile") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { test -z "$ac_c_werror_flag" || test ! -s conftest.err @@ -8543,11 +9191,10 @@ cat >>conftest.$ac_ext <<_ACEOF /* end confdefs.h. */ $ac_includes_default - typedef void * ac__type_sizeof_; int main () { -static int test_array [1 - 2 * !(((long int) (sizeof (ac__type_sizeof_))) >= $ac_mid)]; +static int test_array [1 - 2 * !(((long int) (sizeof (void *))) >= $ac_mid)]; test_array [0] = 0 ; @@ -8560,20 +9207,21 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_compile") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { test -z "$ac_c_werror_flag" || test ! -s conftest.err } && test -s conftest.$ac_objext; then ac_lo=$ac_mid; break else - echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 ac_hi=`expr '(' $ac_mid ')' - 1` @@ -8587,7 +9235,7 @@ rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext done else - echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 ac_lo= ac_hi= @@ -8607,11 +9255,10 @@ cat >>conftest.$ac_ext <<_ACEOF /* end confdefs.h. */ $ac_includes_default - typedef void * ac__type_sizeof_; int main () { -static int test_array [1 - 2 * !(((long int) (sizeof (ac__type_sizeof_))) <= $ac_mid)]; +static int test_array [1 - 2 * !(((long int) (sizeof (void *))) <= $ac_mid)]; test_array [0] = 0 ; @@ -8624,20 +9271,21 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_compile") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { test -z "$ac_c_werror_flag" || test ! -s conftest.err } && test -s conftest.$ac_objext; then ac_hi=$ac_mid else - echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 ac_lo=`expr '(' $ac_mid ')' + 1` @@ -8648,11 +9296,13 @@ case $ac_lo in ?*) ac_cv_sizeof_void_p=$ac_lo;; '') if test "$ac_cv_type_void_p" = yes; then - { { echo "$as_me:$LINENO: error: cannot compute sizeof (void *) + { { $as_echo "$as_me:$LINENO: error: in \`$ac_pwd':" >&5 +$as_echo "$as_me: error: in \`$ac_pwd':" >&2;} +{ { $as_echo "$as_me:$LINENO: error: cannot compute sizeof (void *) See \`config.log' for more details." >&5 -echo "$as_me: error: cannot compute sizeof (void *) +$as_echo "$as_me: error: cannot compute sizeof (void *) See \`config.log' for more details." >&2;} - { (exit 77); exit 77; }; } + { (exit 77); exit 77; }; }; } else ac_cv_sizeof_void_p=0 fi ;; @@ -8665,9 +9315,8 @@ cat >>conftest.$ac_ext <<_ACEOF /* end confdefs.h. */ $ac_includes_default - typedef void * ac__type_sizeof_; -static long int longval () { return (long int) (sizeof (ac__type_sizeof_)); } -static unsigned long int ulongval () { return (long int) (sizeof (ac__type_sizeof_)); } +static long int longval () { return (long int) (sizeof (void *)); } +static unsigned long int ulongval () { return (long int) (sizeof (void *)); } #include #include int @@ -8677,20 +9326,22 @@ FILE *f = fopen ("conftest.val", "w"); if (! f) return 1; - if (((long int) (sizeof (ac__type_sizeof_))) < 0) + if (((long int) (sizeof (void *))) < 0) { long int i = longval (); - if (i != ((long int) (sizeof (ac__type_sizeof_)))) + if (i != ((long int) (sizeof (void *)))) return 1; - fprintf (f, "%ld\n", i); + fprintf (f, "%ld", i); } else { unsigned long int i = ulongval (); - if (i != ((long int) (sizeof (ac__type_sizeof_)))) + if (i != ((long int) (sizeof (void *)))) return 1; - fprintf (f, "%lu\n", i); + fprintf (f, "%lu", i); } + /* Do not output a trailing newline, as this causes \r\n confusion + on some platforms. */ return ferror (f) || fclose (f) != 0; ; @@ -8703,43 +9354,48 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_link") 2>&5 ac_status=$? - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { ac_try='./conftest$ac_exeext' { (case "(($ac_try" in *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_try") 2>&5 ac_status=$? - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); }; }; then ac_cv_sizeof_void_p=`cat conftest.val` else - echo "$as_me: program exited with status $ac_status" >&5 -echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: program exited with status $ac_status" >&5 +$as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 ( exit $ac_status ) if test "$ac_cv_type_void_p" = yes; then - { { echo "$as_me:$LINENO: error: cannot compute sizeof (void *) + { { $as_echo "$as_me:$LINENO: error: in \`$ac_pwd':" >&5 +$as_echo "$as_me: error: in \`$ac_pwd':" >&2;} +{ { $as_echo "$as_me:$LINENO: error: cannot compute sizeof (void *) See \`config.log' for more details." >&5 -echo "$as_me: error: cannot compute sizeof (void *) +$as_echo "$as_me: error: cannot compute sizeof (void *) See \`config.log' for more details." >&2;} - { (exit 77); exit 77; }; } + { (exit 77); exit 77; }; }; } else ac_cv_sizeof_void_p=0 fi fi +rm -rf conftest.dSYM rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext conftest.$ac_objext conftest.$ac_ext fi rm -f conftest.val fi -{ echo "$as_me:$LINENO: result: $ac_cv_sizeof_void_p" >&5 -echo "${ECHO_T}$ac_cv_sizeof_void_p" >&6; } +{ $as_echo "$as_me:$LINENO: result: $ac_cv_sizeof_void_p" >&5 +$as_echo "$ac_cv_sizeof_void_p" >&6; } @@ -8748,68 +9404,14 @@ _ACEOF -{ echo "$as_me:$LINENO: checking for short" >&5 -echo $ECHO_N "checking for short... $ECHO_C" >&6; } -if test "${ac_cv_type_short+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 -else - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -$ac_includes_default -typedef short ac__type_new_; -int -main () -{ -if ((ac__type_new_ *) 0) - return 0; -if (sizeof (ac__type_new_)) - return 0; - ; - return 0; -} -_ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - ac_cv_type_short=yes -else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - ac_cv_type_short=no -fi - -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext -fi -{ echo "$as_me:$LINENO: result: $ac_cv_type_short" >&5 -echo "${ECHO_T}$ac_cv_type_short" >&6; } - # The cast to long int works around a bug in the HP C Compiler # version HP92453-01 B.11.11.23709.GP, which incorrectly rejects # declarations like `int a3[[(sizeof (unsigned char)) >= 0]];'. # This bug is HP SR number 8606223364. -{ echo "$as_me:$LINENO: checking size of short" >&5 -echo $ECHO_N "checking size of short... $ECHO_C" >&6; } +{ $as_echo "$as_me:$LINENO: checking size of short" >&5 +$as_echo_n "checking size of short... " >&6; } if test "${ac_cv_sizeof_short+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 + $as_echo_n "(cached) " >&6 else if test "$cross_compiling" = yes; then # Depending upon the size, compute the lo and hi bounds. @@ -8820,11 +9422,10 @@ cat >>conftest.$ac_ext <<_ACEOF /* end confdefs.h. */ $ac_includes_default - typedef short ac__type_sizeof_; int main () { -static int test_array [1 - 2 * !(((long int) (sizeof (ac__type_sizeof_))) >= 0)]; +static int test_array [1 - 2 * !(((long int) (sizeof (short))) >= 0)]; test_array [0] = 0 ; @@ -8837,13 +9438,14 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_compile") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { test -z "$ac_c_werror_flag" || test ! -s conftest.err @@ -8857,11 +9459,10 @@ cat >>conftest.$ac_ext <<_ACEOF /* end confdefs.h. */ $ac_includes_default - typedef short ac__type_sizeof_; int main () { -static int test_array [1 - 2 * !(((long int) (sizeof (ac__type_sizeof_))) <= $ac_mid)]; +static int test_array [1 - 2 * !(((long int) (sizeof (short))) <= $ac_mid)]; test_array [0] = 0 ; @@ -8874,20 +9475,21 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_compile") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { test -z "$ac_c_werror_flag" || test ! -s conftest.err } && test -s conftest.$ac_objext; then ac_hi=$ac_mid; break else - echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 ac_lo=`expr $ac_mid + 1` @@ -8901,7 +9503,7 @@ rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext done else - echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 cat >conftest.$ac_ext <<_ACEOF @@ -8911,11 +9513,10 @@ cat >>conftest.$ac_ext <<_ACEOF /* end confdefs.h. */ $ac_includes_default - typedef short ac__type_sizeof_; int main () { -static int test_array [1 - 2 * !(((long int) (sizeof (ac__type_sizeof_))) < 0)]; +static int test_array [1 - 2 * !(((long int) (sizeof (short))) < 0)]; test_array [0] = 0 ; @@ -8928,13 +9529,14 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_compile") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { test -z "$ac_c_werror_flag" || test ! -s conftest.err @@ -8948,11 +9550,10 @@ cat >>conftest.$ac_ext <<_ACEOF /* end confdefs.h. */ $ac_includes_default - typedef short ac__type_sizeof_; int main () { -static int test_array [1 - 2 * !(((long int) (sizeof (ac__type_sizeof_))) >= $ac_mid)]; +static int test_array [1 - 2 * !(((long int) (sizeof (short))) >= $ac_mid)]; test_array [0] = 0 ; @@ -8965,20 +9566,21 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_compile") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { test -z "$ac_c_werror_flag" || test ! -s conftest.err } && test -s conftest.$ac_objext; then ac_lo=$ac_mid; break else - echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 ac_hi=`expr '(' $ac_mid ')' - 1` @@ -8992,7 +9594,7 @@ rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext done else - echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 ac_lo= ac_hi= @@ -9012,11 +9614,10 @@ cat >>conftest.$ac_ext <<_ACEOF /* end confdefs.h. */ $ac_includes_default - typedef short ac__type_sizeof_; int main () { -static int test_array [1 - 2 * !(((long int) (sizeof (ac__type_sizeof_))) <= $ac_mid)]; +static int test_array [1 - 2 * !(((long int) (sizeof (short))) <= $ac_mid)]; test_array [0] = 0 ; @@ -9029,20 +9630,21 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_compile") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { test -z "$ac_c_werror_flag" || test ! -s conftest.err } && test -s conftest.$ac_objext; then ac_hi=$ac_mid else - echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 ac_lo=`expr '(' $ac_mid ')' + 1` @@ -9053,11 +9655,13 @@ case $ac_lo in ?*) ac_cv_sizeof_short=$ac_lo;; '') if test "$ac_cv_type_short" = yes; then - { { echo "$as_me:$LINENO: error: cannot compute sizeof (short) + { { $as_echo "$as_me:$LINENO: error: in \`$ac_pwd':" >&5 +$as_echo "$as_me: error: in \`$ac_pwd':" >&2;} +{ { $as_echo "$as_me:$LINENO: error: cannot compute sizeof (short) See \`config.log' for more details." >&5 -echo "$as_me: error: cannot compute sizeof (short) +$as_echo "$as_me: error: cannot compute sizeof (short) See \`config.log' for more details." >&2;} - { (exit 77); exit 77; }; } + { (exit 77); exit 77; }; }; } else ac_cv_sizeof_short=0 fi ;; @@ -9070,9 +9674,8 @@ cat >>conftest.$ac_ext <<_ACEOF /* end confdefs.h. */ $ac_includes_default - typedef short ac__type_sizeof_; -static long int longval () { return (long int) (sizeof (ac__type_sizeof_)); } -static unsigned long int ulongval () { return (long int) (sizeof (ac__type_sizeof_)); } +static long int longval () { return (long int) (sizeof (short)); } +static unsigned long int ulongval () { return (long int) (sizeof (short)); } #include #include int @@ -9082,20 +9685,22 @@ FILE *f = fopen ("conftest.val", "w"); if (! f) return 1; - if (((long int) (sizeof (ac__type_sizeof_))) < 0) + if (((long int) (sizeof (short))) < 0) { long int i = longval (); - if (i != ((long int) (sizeof (ac__type_sizeof_)))) + if (i != ((long int) (sizeof (short)))) return 1; - fprintf (f, "%ld\n", i); + fprintf (f, "%ld", i); } else { unsigned long int i = ulongval (); - if (i != ((long int) (sizeof (ac__type_sizeof_)))) + if (i != ((long int) (sizeof (short)))) return 1; - fprintf (f, "%lu\n", i); + fprintf (f, "%lu", i); } + /* Do not output a trailing newline, as this causes \r\n confusion + on some platforms. */ return ferror (f) || fclose (f) != 0; ; @@ -9108,43 +9713,48 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_link") 2>&5 ac_status=$? - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { ac_try='./conftest$ac_exeext' { (case "(($ac_try" in *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_try") 2>&5 ac_status=$? - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); }; }; then ac_cv_sizeof_short=`cat conftest.val` else - echo "$as_me: program exited with status $ac_status" >&5 -echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: program exited with status $ac_status" >&5 +$as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 ( exit $ac_status ) if test "$ac_cv_type_short" = yes; then - { { echo "$as_me:$LINENO: error: cannot compute sizeof (short) + { { $as_echo "$as_me:$LINENO: error: in \`$ac_pwd':" >&5 +$as_echo "$as_me: error: in \`$ac_pwd':" >&2;} +{ { $as_echo "$as_me:$LINENO: error: cannot compute sizeof (short) See \`config.log' for more details." >&5 -echo "$as_me: error: cannot compute sizeof (short) +$as_echo "$as_me: error: cannot compute sizeof (short) See \`config.log' for more details." >&2;} - { (exit 77); exit 77; }; } + { (exit 77); exit 77; }; }; } else ac_cv_sizeof_short=0 fi fi +rm -rf conftest.dSYM rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext conftest.$ac_objext conftest.$ac_ext fi rm -f conftest.val fi -{ echo "$as_me:$LINENO: result: $ac_cv_sizeof_short" >&5 -echo "${ECHO_T}$ac_cv_sizeof_short" >&6; } +{ $as_echo "$as_me:$LINENO: result: $ac_cv_sizeof_short" >&5 +$as_echo "$ac_cv_sizeof_short" >&6; } @@ -9153,68 +9763,14 @@ _ACEOF -{ echo "$as_me:$LINENO: checking for float" >&5 -echo $ECHO_N "checking for float... $ECHO_C" >&6; } -if test "${ac_cv_type_float+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 -else - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -$ac_includes_default -typedef float ac__type_new_; -int -main () -{ -if ((ac__type_new_ *) 0) - return 0; -if (sizeof (ac__type_new_)) - return 0; - ; - return 0; -} -_ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - ac_cv_type_float=yes -else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - ac_cv_type_float=no -fi - -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext -fi -{ echo "$as_me:$LINENO: result: $ac_cv_type_float" >&5 -echo "${ECHO_T}$ac_cv_type_float" >&6; } - # The cast to long int works around a bug in the HP C Compiler # version HP92453-01 B.11.11.23709.GP, which incorrectly rejects # declarations like `int a3[[(sizeof (unsigned char)) >= 0]];'. # This bug is HP SR number 8606223364. -{ echo "$as_me:$LINENO: checking size of float" >&5 -echo $ECHO_N "checking size of float... $ECHO_C" >&6; } +{ $as_echo "$as_me:$LINENO: checking size of float" >&5 +$as_echo_n "checking size of float... " >&6; } if test "${ac_cv_sizeof_float+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 + $as_echo_n "(cached) " >&6 else if test "$cross_compiling" = yes; then # Depending upon the size, compute the lo and hi bounds. @@ -9225,11 +9781,10 @@ cat >>conftest.$ac_ext <<_ACEOF /* end confdefs.h. */ $ac_includes_default - typedef float ac__type_sizeof_; int main () { -static int test_array [1 - 2 * !(((long int) (sizeof (ac__type_sizeof_))) >= 0)]; +static int test_array [1 - 2 * !(((long int) (sizeof (float))) >= 0)]; test_array [0] = 0 ; @@ -9242,13 +9797,14 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_compile") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { test -z "$ac_c_werror_flag" || test ! -s conftest.err @@ -9262,11 +9818,10 @@ cat >>conftest.$ac_ext <<_ACEOF /* end confdefs.h. */ $ac_includes_default - typedef float ac__type_sizeof_; int main () { -static int test_array [1 - 2 * !(((long int) (sizeof (ac__type_sizeof_))) <= $ac_mid)]; +static int test_array [1 - 2 * !(((long int) (sizeof (float))) <= $ac_mid)]; test_array [0] = 0 ; @@ -9279,20 +9834,21 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_compile") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { test -z "$ac_c_werror_flag" || test ! -s conftest.err } && test -s conftest.$ac_objext; then ac_hi=$ac_mid; break else - echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 ac_lo=`expr $ac_mid + 1` @@ -9306,7 +9862,7 @@ rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext done else - echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 cat >conftest.$ac_ext <<_ACEOF @@ -9316,11 +9872,10 @@ cat >>conftest.$ac_ext <<_ACEOF /* end confdefs.h. */ $ac_includes_default - typedef float ac__type_sizeof_; int main () { -static int test_array [1 - 2 * !(((long int) (sizeof (ac__type_sizeof_))) < 0)]; +static int test_array [1 - 2 * !(((long int) (sizeof (float))) < 0)]; test_array [0] = 0 ; @@ -9333,13 +9888,14 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_compile") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { test -z "$ac_c_werror_flag" || test ! -s conftest.err @@ -9353,11 +9909,10 @@ cat >>conftest.$ac_ext <<_ACEOF /* end confdefs.h. */ $ac_includes_default - typedef float ac__type_sizeof_; int main () { -static int test_array [1 - 2 * !(((long int) (sizeof (ac__type_sizeof_))) >= $ac_mid)]; +static int test_array [1 - 2 * !(((long int) (sizeof (float))) >= $ac_mid)]; test_array [0] = 0 ; @@ -9370,20 +9925,21 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_compile") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { test -z "$ac_c_werror_flag" || test ! -s conftest.err } && test -s conftest.$ac_objext; then ac_lo=$ac_mid; break else - echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 ac_hi=`expr '(' $ac_mid ')' - 1` @@ -9397,7 +9953,7 @@ rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext done else - echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 ac_lo= ac_hi= @@ -9417,11 +9973,10 @@ cat >>conftest.$ac_ext <<_ACEOF /* end confdefs.h. */ $ac_includes_default - typedef float ac__type_sizeof_; int main () { -static int test_array [1 - 2 * !(((long int) (sizeof (ac__type_sizeof_))) <= $ac_mid)]; +static int test_array [1 - 2 * !(((long int) (sizeof (float))) <= $ac_mid)]; test_array [0] = 0 ; @@ -9434,20 +9989,21 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_compile") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { test -z "$ac_c_werror_flag" || test ! -s conftest.err } && test -s conftest.$ac_objext; then ac_hi=$ac_mid else - echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 ac_lo=`expr '(' $ac_mid ')' + 1` @@ -9458,11 +10014,13 @@ case $ac_lo in ?*) ac_cv_sizeof_float=$ac_lo;; '') if test "$ac_cv_type_float" = yes; then - { { echo "$as_me:$LINENO: error: cannot compute sizeof (float) + { { $as_echo "$as_me:$LINENO: error: in \`$ac_pwd':" >&5 +$as_echo "$as_me: error: in \`$ac_pwd':" >&2;} +{ { $as_echo "$as_me:$LINENO: error: cannot compute sizeof (float) See \`config.log' for more details." >&5 -echo "$as_me: error: cannot compute sizeof (float) +$as_echo "$as_me: error: cannot compute sizeof (float) See \`config.log' for more details." >&2;} - { (exit 77); exit 77; }; } + { (exit 77); exit 77; }; }; } else ac_cv_sizeof_float=0 fi ;; @@ -9475,9 +10033,8 @@ cat >>conftest.$ac_ext <<_ACEOF /* end confdefs.h. */ $ac_includes_default - typedef float ac__type_sizeof_; -static long int longval () { return (long int) (sizeof (ac__type_sizeof_)); } -static unsigned long int ulongval () { return (long int) (sizeof (ac__type_sizeof_)); } +static long int longval () { return (long int) (sizeof (float)); } +static unsigned long int ulongval () { return (long int) (sizeof (float)); } #include #include int @@ -9487,20 +10044,22 @@ FILE *f = fopen ("conftest.val", "w"); if (! f) return 1; - if (((long int) (sizeof (ac__type_sizeof_))) < 0) + if (((long int) (sizeof (float))) < 0) { long int i = longval (); - if (i != ((long int) (sizeof (ac__type_sizeof_)))) + if (i != ((long int) (sizeof (float)))) return 1; - fprintf (f, "%ld\n", i); + fprintf (f, "%ld", i); } else { unsigned long int i = ulongval (); - if (i != ((long int) (sizeof (ac__type_sizeof_)))) + if (i != ((long int) (sizeof (float)))) return 1; - fprintf (f, "%lu\n", i); + fprintf (f, "%lu", i); } + /* Do not output a trailing newline, as this causes \r\n confusion + on some platforms. */ return ferror (f) || fclose (f) != 0; ; @@ -9513,113 +10072,64 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_link") 2>&5 ac_status=$? - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { ac_try='./conftest$ac_exeext' { (case "(($ac_try" in *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_try") 2>&5 ac_status=$? - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); }; }; then ac_cv_sizeof_float=`cat conftest.val` else - echo "$as_me: program exited with status $ac_status" >&5 -echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: program exited with status $ac_status" >&5 +$as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 ( exit $ac_status ) if test "$ac_cv_type_float" = yes; then - { { echo "$as_me:$LINENO: error: cannot compute sizeof (float) + { { $as_echo "$as_me:$LINENO: error: in \`$ac_pwd':" >&5 +$as_echo "$as_me: error: in \`$ac_pwd':" >&2;} +{ { $as_echo "$as_me:$LINENO: error: cannot compute sizeof (float) See \`config.log' for more details." >&5 -echo "$as_me: error: cannot compute sizeof (float) +$as_echo "$as_me: error: cannot compute sizeof (float) See \`config.log' for more details." >&2;} - { (exit 77); exit 77; }; } + { (exit 77); exit 77; }; }; } else ac_cv_sizeof_float=0 fi fi +rm -rf conftest.dSYM rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext conftest.$ac_objext conftest.$ac_ext fi rm -f conftest.val fi -{ echo "$as_me:$LINENO: result: $ac_cv_sizeof_float" >&5 -echo "${ECHO_T}$ac_cv_sizeof_float" >&6; } - +{ $as_echo "$as_me:$LINENO: result: $ac_cv_sizeof_float" >&5 +$as_echo "$ac_cv_sizeof_float" >&6; } -cat >>confdefs.h <<_ACEOF -#define SIZEOF_FLOAT $ac_cv_sizeof_float -_ACEOF - - -{ echo "$as_me:$LINENO: checking for double" >&5 -echo $ECHO_N "checking for double... $ECHO_C" >&6; } -if test "${ac_cv_type_double+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 -else - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -$ac_includes_default -typedef double ac__type_new_; -int -main () -{ -if ((ac__type_new_ *) 0) - return 0; -if (sizeof (ac__type_new_)) - return 0; - ; - return 0; -} -_ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - ac_cv_type_double=yes -else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - ac_cv_type_double=no -fi -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext -fi -{ echo "$as_me:$LINENO: result: $ac_cv_type_double" >&5 -echo "${ECHO_T}$ac_cv_type_double" >&6; } +cat >>confdefs.h <<_ACEOF +#define SIZEOF_FLOAT $ac_cv_sizeof_float +_ACEOF + # The cast to long int works around a bug in the HP C Compiler # version HP92453-01 B.11.11.23709.GP, which incorrectly rejects # declarations like `int a3[[(sizeof (unsigned char)) >= 0]];'. # This bug is HP SR number 8606223364. -{ echo "$as_me:$LINENO: checking size of double" >&5 -echo $ECHO_N "checking size of double... $ECHO_C" >&6; } +{ $as_echo "$as_me:$LINENO: checking size of double" >&5 +$as_echo_n "checking size of double... " >&6; } if test "${ac_cv_sizeof_double+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 + $as_echo_n "(cached) " >&6 else if test "$cross_compiling" = yes; then # Depending upon the size, compute the lo and hi bounds. @@ -9630,11 +10140,10 @@ cat >>conftest.$ac_ext <<_ACEOF /* end confdefs.h. */ $ac_includes_default - typedef double ac__type_sizeof_; int main () { -static int test_array [1 - 2 * !(((long int) (sizeof (ac__type_sizeof_))) >= 0)]; +static int test_array [1 - 2 * !(((long int) (sizeof (double))) >= 0)]; test_array [0] = 0 ; @@ -9647,13 +10156,14 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_compile") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { test -z "$ac_c_werror_flag" || test ! -s conftest.err @@ -9667,11 +10177,10 @@ cat >>conftest.$ac_ext <<_ACEOF /* end confdefs.h. */ $ac_includes_default - typedef double ac__type_sizeof_; int main () { -static int test_array [1 - 2 * !(((long int) (sizeof (ac__type_sizeof_))) <= $ac_mid)]; +static int test_array [1 - 2 * !(((long int) (sizeof (double))) <= $ac_mid)]; test_array [0] = 0 ; @@ -9684,20 +10193,21 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_compile") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { test -z "$ac_c_werror_flag" || test ! -s conftest.err } && test -s conftest.$ac_objext; then ac_hi=$ac_mid; break else - echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 ac_lo=`expr $ac_mid + 1` @@ -9711,7 +10221,7 @@ rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext done else - echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 cat >conftest.$ac_ext <<_ACEOF @@ -9721,11 +10231,10 @@ cat >>conftest.$ac_ext <<_ACEOF /* end confdefs.h. */ $ac_includes_default - typedef double ac__type_sizeof_; int main () { -static int test_array [1 - 2 * !(((long int) (sizeof (ac__type_sizeof_))) < 0)]; +static int test_array [1 - 2 * !(((long int) (sizeof (double))) < 0)]; test_array [0] = 0 ; @@ -9738,13 +10247,14 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_compile") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { test -z "$ac_c_werror_flag" || test ! -s conftest.err @@ -9758,11 +10268,10 @@ cat >>conftest.$ac_ext <<_ACEOF /* end confdefs.h. */ $ac_includes_default - typedef double ac__type_sizeof_; int main () { -static int test_array [1 - 2 * !(((long int) (sizeof (ac__type_sizeof_))) >= $ac_mid)]; +static int test_array [1 - 2 * !(((long int) (sizeof (double))) >= $ac_mid)]; test_array [0] = 0 ; @@ -9775,20 +10284,21 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_compile") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { test -z "$ac_c_werror_flag" || test ! -s conftest.err } && test -s conftest.$ac_objext; then ac_lo=$ac_mid; break else - echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 ac_hi=`expr '(' $ac_mid ')' - 1` @@ -9802,7 +10312,7 @@ rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext done else - echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 ac_lo= ac_hi= @@ -9822,11 +10332,10 @@ cat >>conftest.$ac_ext <<_ACEOF /* end confdefs.h. */ $ac_includes_default - typedef double ac__type_sizeof_; int main () { -static int test_array [1 - 2 * !(((long int) (sizeof (ac__type_sizeof_))) <= $ac_mid)]; +static int test_array [1 - 2 * !(((long int) (sizeof (double))) <= $ac_mid)]; test_array [0] = 0 ; @@ -9839,20 +10348,21 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_compile") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { test -z "$ac_c_werror_flag" || test ! -s conftest.err } && test -s conftest.$ac_objext; then ac_hi=$ac_mid else - echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 ac_lo=`expr '(' $ac_mid ')' + 1` @@ -9863,11 +10373,13 @@ case $ac_lo in ?*) ac_cv_sizeof_double=$ac_lo;; '') if test "$ac_cv_type_double" = yes; then - { { echo "$as_me:$LINENO: error: cannot compute sizeof (double) + { { $as_echo "$as_me:$LINENO: error: in \`$ac_pwd':" >&5 +$as_echo "$as_me: error: in \`$ac_pwd':" >&2;} +{ { $as_echo "$as_me:$LINENO: error: cannot compute sizeof (double) See \`config.log' for more details." >&5 -echo "$as_me: error: cannot compute sizeof (double) +$as_echo "$as_me: error: cannot compute sizeof (double) See \`config.log' for more details." >&2;} - { (exit 77); exit 77; }; } + { (exit 77); exit 77; }; }; } else ac_cv_sizeof_double=0 fi ;; @@ -9880,9 +10392,8 @@ cat >>conftest.$ac_ext <<_ACEOF /* end confdefs.h. */ $ac_includes_default - typedef double ac__type_sizeof_; -static long int longval () { return (long int) (sizeof (ac__type_sizeof_)); } -static unsigned long int ulongval () { return (long int) (sizeof (ac__type_sizeof_)); } +static long int longval () { return (long int) (sizeof (double)); } +static unsigned long int ulongval () { return (long int) (sizeof (double)); } #include #include int @@ -9892,20 +10403,22 @@ FILE *f = fopen ("conftest.val", "w"); if (! f) return 1; - if (((long int) (sizeof (ac__type_sizeof_))) < 0) + if (((long int) (sizeof (double))) < 0) { long int i = longval (); - if (i != ((long int) (sizeof (ac__type_sizeof_)))) + if (i != ((long int) (sizeof (double)))) return 1; - fprintf (f, "%ld\n", i); + fprintf (f, "%ld", i); } else { unsigned long int i = ulongval (); - if (i != ((long int) (sizeof (ac__type_sizeof_)))) + if (i != ((long int) (sizeof (double)))) return 1; - fprintf (f, "%lu\n", i); + fprintf (f, "%lu", i); } + /* Do not output a trailing newline, as this causes \r\n confusion + on some platforms. */ return ferror (f) || fclose (f) != 0; ; @@ -9918,43 +10431,48 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_link") 2>&5 ac_status=$? - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { ac_try='./conftest$ac_exeext' { (case "(($ac_try" in *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_try") 2>&5 ac_status=$? - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); }; }; then ac_cv_sizeof_double=`cat conftest.val` else - echo "$as_me: program exited with status $ac_status" >&5 -echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: program exited with status $ac_status" >&5 +$as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 ( exit $ac_status ) if test "$ac_cv_type_double" = yes; then - { { echo "$as_me:$LINENO: error: cannot compute sizeof (double) + { { $as_echo "$as_me:$LINENO: error: in \`$ac_pwd':" >&5 +$as_echo "$as_me: error: in \`$ac_pwd':" >&2;} +{ { $as_echo "$as_me:$LINENO: error: cannot compute sizeof (double) See \`config.log' for more details." >&5 -echo "$as_me: error: cannot compute sizeof (double) +$as_echo "$as_me: error: cannot compute sizeof (double) See \`config.log' for more details." >&2;} - { (exit 77); exit 77; }; } + { (exit 77); exit 77; }; }; } else ac_cv_sizeof_double=0 fi fi +rm -rf conftest.dSYM rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext conftest.$ac_objext conftest.$ac_ext fi rm -f conftest.val fi -{ echo "$as_me:$LINENO: result: $ac_cv_sizeof_double" >&5 -echo "${ECHO_T}$ac_cv_sizeof_double" >&6; } +{ $as_echo "$as_me:$LINENO: result: $ac_cv_sizeof_double" >&5 +$as_echo "$ac_cv_sizeof_double" >&6; } @@ -9963,68 +10481,14 @@ _ACEOF -{ echo "$as_me:$LINENO: checking for fpos_t" >&5 -echo $ECHO_N "checking for fpos_t... $ECHO_C" >&6; } -if test "${ac_cv_type_fpos_t+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 -else - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -$ac_includes_default -typedef fpos_t ac__type_new_; -int -main () -{ -if ((ac__type_new_ *) 0) - return 0; -if (sizeof (ac__type_new_)) - return 0; - ; - return 0; -} -_ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - ac_cv_type_fpos_t=yes -else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - ac_cv_type_fpos_t=no -fi - -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext -fi -{ echo "$as_me:$LINENO: result: $ac_cv_type_fpos_t" >&5 -echo "${ECHO_T}$ac_cv_type_fpos_t" >&6; } - # The cast to long int works around a bug in the HP C Compiler # version HP92453-01 B.11.11.23709.GP, which incorrectly rejects # declarations like `int a3[[(sizeof (unsigned char)) >= 0]];'. # This bug is HP SR number 8606223364. -{ echo "$as_me:$LINENO: checking size of fpos_t" >&5 -echo $ECHO_N "checking size of fpos_t... $ECHO_C" >&6; } +{ $as_echo "$as_me:$LINENO: checking size of fpos_t" >&5 +$as_echo_n "checking size of fpos_t... " >&6; } if test "${ac_cv_sizeof_fpos_t+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 + $as_echo_n "(cached) " >&6 else if test "$cross_compiling" = yes; then # Depending upon the size, compute the lo and hi bounds. @@ -10035,11 +10499,10 @@ cat >>conftest.$ac_ext <<_ACEOF /* end confdefs.h. */ $ac_includes_default - typedef fpos_t ac__type_sizeof_; int main () { -static int test_array [1 - 2 * !(((long int) (sizeof (ac__type_sizeof_))) >= 0)]; +static int test_array [1 - 2 * !(((long int) (sizeof (fpos_t))) >= 0)]; test_array [0] = 0 ; @@ -10052,13 +10515,14 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_compile") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { test -z "$ac_c_werror_flag" || test ! -s conftest.err @@ -10072,11 +10536,10 @@ cat >>conftest.$ac_ext <<_ACEOF /* end confdefs.h. */ $ac_includes_default - typedef fpos_t ac__type_sizeof_; int main () { -static int test_array [1 - 2 * !(((long int) (sizeof (ac__type_sizeof_))) <= $ac_mid)]; +static int test_array [1 - 2 * !(((long int) (sizeof (fpos_t))) <= $ac_mid)]; test_array [0] = 0 ; @@ -10089,20 +10552,21 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_compile") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { test -z "$ac_c_werror_flag" || test ! -s conftest.err } && test -s conftest.$ac_objext; then ac_hi=$ac_mid; break else - echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 ac_lo=`expr $ac_mid + 1` @@ -10116,7 +10580,7 @@ rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext done else - echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 cat >conftest.$ac_ext <<_ACEOF @@ -10126,11 +10590,10 @@ cat >>conftest.$ac_ext <<_ACEOF /* end confdefs.h. */ $ac_includes_default - typedef fpos_t ac__type_sizeof_; int main () { -static int test_array [1 - 2 * !(((long int) (sizeof (ac__type_sizeof_))) < 0)]; +static int test_array [1 - 2 * !(((long int) (sizeof (fpos_t))) < 0)]; test_array [0] = 0 ; @@ -10143,13 +10606,14 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_compile") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { test -z "$ac_c_werror_flag" || test ! -s conftest.err @@ -10163,11 +10627,10 @@ cat >>conftest.$ac_ext <<_ACEOF /* end confdefs.h. */ $ac_includes_default - typedef fpos_t ac__type_sizeof_; int main () { -static int test_array [1 - 2 * !(((long int) (sizeof (ac__type_sizeof_))) >= $ac_mid)]; +static int test_array [1 - 2 * !(((long int) (sizeof (fpos_t))) >= $ac_mid)]; test_array [0] = 0 ; @@ -10180,20 +10643,21 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_compile") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { test -z "$ac_c_werror_flag" || test ! -s conftest.err } && test -s conftest.$ac_objext; then ac_lo=$ac_mid; break else - echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 ac_hi=`expr '(' $ac_mid ')' - 1` @@ -10207,7 +10671,7 @@ rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext done else - echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 ac_lo= ac_hi= @@ -10227,11 +10691,10 @@ cat >>conftest.$ac_ext <<_ACEOF /* end confdefs.h. */ $ac_includes_default - typedef fpos_t ac__type_sizeof_; int main () { -static int test_array [1 - 2 * !(((long int) (sizeof (ac__type_sizeof_))) <= $ac_mid)]; +static int test_array [1 - 2 * !(((long int) (sizeof (fpos_t))) <= $ac_mid)]; test_array [0] = 0 ; @@ -10244,20 +10707,21 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_compile") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { test -z "$ac_c_werror_flag" || test ! -s conftest.err } && test -s conftest.$ac_objext; then ac_hi=$ac_mid else - echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 ac_lo=`expr '(' $ac_mid ')' + 1` @@ -10268,11 +10732,13 @@ case $ac_lo in ?*) ac_cv_sizeof_fpos_t=$ac_lo;; '') if test "$ac_cv_type_fpos_t" = yes; then - { { echo "$as_me:$LINENO: error: cannot compute sizeof (fpos_t) + { { $as_echo "$as_me:$LINENO: error: in \`$ac_pwd':" >&5 +$as_echo "$as_me: error: in \`$ac_pwd':" >&2;} +{ { $as_echo "$as_me:$LINENO: error: cannot compute sizeof (fpos_t) See \`config.log' for more details." >&5 -echo "$as_me: error: cannot compute sizeof (fpos_t) +$as_echo "$as_me: error: cannot compute sizeof (fpos_t) See \`config.log' for more details." >&2;} - { (exit 77); exit 77; }; } + { (exit 77); exit 77; }; }; } else ac_cv_sizeof_fpos_t=0 fi ;; @@ -10285,9 +10751,8 @@ cat >>conftest.$ac_ext <<_ACEOF /* end confdefs.h. */ $ac_includes_default - typedef fpos_t ac__type_sizeof_; -static long int longval () { return (long int) (sizeof (ac__type_sizeof_)); } -static unsigned long int ulongval () { return (long int) (sizeof (ac__type_sizeof_)); } +static long int longval () { return (long int) (sizeof (fpos_t)); } +static unsigned long int ulongval () { return (long int) (sizeof (fpos_t)); } #include #include int @@ -10297,20 +10762,22 @@ FILE *f = fopen ("conftest.val", "w"); if (! f) return 1; - if (((long int) (sizeof (ac__type_sizeof_))) < 0) + if (((long int) (sizeof (fpos_t))) < 0) { long int i = longval (); - if (i != ((long int) (sizeof (ac__type_sizeof_)))) + if (i != ((long int) (sizeof (fpos_t)))) return 1; - fprintf (f, "%ld\n", i); + fprintf (f, "%ld", i); } else { unsigned long int i = ulongval (); - if (i != ((long int) (sizeof (ac__type_sizeof_)))) + if (i != ((long int) (sizeof (fpos_t)))) return 1; - fprintf (f, "%lu\n", i); + fprintf (f, "%lu", i); } + /* Do not output a trailing newline, as this causes \r\n confusion + on some platforms. */ return ferror (f) || fclose (f) != 0; ; @@ -10323,43 +10790,48 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_link") 2>&5 ac_status=$? - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { ac_try='./conftest$ac_exeext' { (case "(($ac_try" in *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_try") 2>&5 ac_status=$? - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); }; }; then ac_cv_sizeof_fpos_t=`cat conftest.val` else - echo "$as_me: program exited with status $ac_status" >&5 -echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: program exited with status $ac_status" >&5 +$as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 ( exit $ac_status ) if test "$ac_cv_type_fpos_t" = yes; then - { { echo "$as_me:$LINENO: error: cannot compute sizeof (fpos_t) + { { $as_echo "$as_me:$LINENO: error: in \`$ac_pwd':" >&5 +$as_echo "$as_me: error: in \`$ac_pwd':" >&2;} +{ { $as_echo "$as_me:$LINENO: error: cannot compute sizeof (fpos_t) See \`config.log' for more details." >&5 -echo "$as_me: error: cannot compute sizeof (fpos_t) +$as_echo "$as_me: error: cannot compute sizeof (fpos_t) See \`config.log' for more details." >&2;} - { (exit 77); exit 77; }; } + { (exit 77); exit 77; }; }; } else ac_cv_sizeof_fpos_t=0 fi fi +rm -rf conftest.dSYM rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext conftest.$ac_objext conftest.$ac_ext fi rm -f conftest.val fi -{ echo "$as_me:$LINENO: result: $ac_cv_sizeof_fpos_t" >&5 -echo "${ECHO_T}$ac_cv_sizeof_fpos_t" >&6; } +{ $as_echo "$as_me:$LINENO: result: $ac_cv_sizeof_fpos_t" >&5 +$as_echo "$ac_cv_sizeof_fpos_t" >&6; } @@ -10368,68 +10840,14 @@ _ACEOF -{ echo "$as_me:$LINENO: checking for size_t" >&5 -echo $ECHO_N "checking for size_t... $ECHO_C" >&6; } -if test "${ac_cv_type_size_t+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 -else - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -$ac_includes_default -typedef size_t ac__type_new_; -int -main () -{ -if ((ac__type_new_ *) 0) - return 0; -if (sizeof (ac__type_new_)) - return 0; - ; - return 0; -} -_ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - ac_cv_type_size_t=yes -else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - ac_cv_type_size_t=no -fi - -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext -fi -{ echo "$as_me:$LINENO: result: $ac_cv_type_size_t" >&5 -echo "${ECHO_T}$ac_cv_type_size_t" >&6; } - # The cast to long int works around a bug in the HP C Compiler # version HP92453-01 B.11.11.23709.GP, which incorrectly rejects # declarations like `int a3[[(sizeof (unsigned char)) >= 0]];'. # This bug is HP SR number 8606223364. -{ echo "$as_me:$LINENO: checking size of size_t" >&5 -echo $ECHO_N "checking size of size_t... $ECHO_C" >&6; } +{ $as_echo "$as_me:$LINENO: checking size of size_t" >&5 +$as_echo_n "checking size of size_t... " >&6; } if test "${ac_cv_sizeof_size_t+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 + $as_echo_n "(cached) " >&6 else if test "$cross_compiling" = yes; then # Depending upon the size, compute the lo and hi bounds. @@ -10440,11 +10858,10 @@ cat >>conftest.$ac_ext <<_ACEOF /* end confdefs.h. */ $ac_includes_default - typedef size_t ac__type_sizeof_; int main () { -static int test_array [1 - 2 * !(((long int) (sizeof (ac__type_sizeof_))) >= 0)]; +static int test_array [1 - 2 * !(((long int) (sizeof (size_t))) >= 0)]; test_array [0] = 0 ; @@ -10457,13 +10874,14 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_compile") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { test -z "$ac_c_werror_flag" || test ! -s conftest.err @@ -10477,11 +10895,10 @@ cat >>conftest.$ac_ext <<_ACEOF /* end confdefs.h. */ $ac_includes_default - typedef size_t ac__type_sizeof_; int main () { -static int test_array [1 - 2 * !(((long int) (sizeof (ac__type_sizeof_))) <= $ac_mid)]; +static int test_array [1 - 2 * !(((long int) (sizeof (size_t))) <= $ac_mid)]; test_array [0] = 0 ; @@ -10494,20 +10911,21 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_compile") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { test -z "$ac_c_werror_flag" || test ! -s conftest.err } && test -s conftest.$ac_objext; then ac_hi=$ac_mid; break else - echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 ac_lo=`expr $ac_mid + 1` @@ -10521,7 +10939,7 @@ rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext done else - echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 cat >conftest.$ac_ext <<_ACEOF @@ -10531,11 +10949,10 @@ cat >>conftest.$ac_ext <<_ACEOF /* end confdefs.h. */ $ac_includes_default - typedef size_t ac__type_sizeof_; int main () { -static int test_array [1 - 2 * !(((long int) (sizeof (ac__type_sizeof_))) < 0)]; +static int test_array [1 - 2 * !(((long int) (sizeof (size_t))) < 0)]; test_array [0] = 0 ; @@ -10548,13 +10965,14 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_compile") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { test -z "$ac_c_werror_flag" || test ! -s conftest.err @@ -10568,11 +10986,10 @@ cat >>conftest.$ac_ext <<_ACEOF /* end confdefs.h. */ $ac_includes_default - typedef size_t ac__type_sizeof_; int main () { -static int test_array [1 - 2 * !(((long int) (sizeof (ac__type_sizeof_))) >= $ac_mid)]; +static int test_array [1 - 2 * !(((long int) (sizeof (size_t))) >= $ac_mid)]; test_array [0] = 0 ; @@ -10585,20 +11002,21 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_compile") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { test -z "$ac_c_werror_flag" || test ! -s conftest.err } && test -s conftest.$ac_objext; then ac_lo=$ac_mid; break else - echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 ac_hi=`expr '(' $ac_mid ')' - 1` @@ -10612,7 +11030,7 @@ rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext done else - echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 ac_lo= ac_hi= @@ -10632,11 +11050,10 @@ cat >>conftest.$ac_ext <<_ACEOF /* end confdefs.h. */ $ac_includes_default - typedef size_t ac__type_sizeof_; int main () { -static int test_array [1 - 2 * !(((long int) (sizeof (ac__type_sizeof_))) <= $ac_mid)]; +static int test_array [1 - 2 * !(((long int) (sizeof (size_t))) <= $ac_mid)]; test_array [0] = 0 ; @@ -10649,20 +11066,21 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_compile") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { test -z "$ac_c_werror_flag" || test ! -s conftest.err } && test -s conftest.$ac_objext; then ac_hi=$ac_mid else - echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 ac_lo=`expr '(' $ac_mid ')' + 1` @@ -10673,11 +11091,13 @@ case $ac_lo in ?*) ac_cv_sizeof_size_t=$ac_lo;; '') if test "$ac_cv_type_size_t" = yes; then - { { echo "$as_me:$LINENO: error: cannot compute sizeof (size_t) + { { $as_echo "$as_me:$LINENO: error: in \`$ac_pwd':" >&5 +$as_echo "$as_me: error: in \`$ac_pwd':" >&2;} +{ { $as_echo "$as_me:$LINENO: error: cannot compute sizeof (size_t) See \`config.log' for more details." >&5 -echo "$as_me: error: cannot compute sizeof (size_t) +$as_echo "$as_me: error: cannot compute sizeof (size_t) See \`config.log' for more details." >&2;} - { (exit 77); exit 77; }; } + { (exit 77); exit 77; }; }; } else ac_cv_sizeof_size_t=0 fi ;; @@ -10690,9 +11110,8 @@ cat >>conftest.$ac_ext <<_ACEOF /* end confdefs.h. */ $ac_includes_default - typedef size_t ac__type_sizeof_; -static long int longval () { return (long int) (sizeof (ac__type_sizeof_)); } -static unsigned long int ulongval () { return (long int) (sizeof (ac__type_sizeof_)); } +static long int longval () { return (long int) (sizeof (size_t)); } +static unsigned long int ulongval () { return (long int) (sizeof (size_t)); } #include #include int @@ -10702,20 +11121,22 @@ FILE *f = fopen ("conftest.val", "w"); if (! f) return 1; - if (((long int) (sizeof (ac__type_sizeof_))) < 0) + if (((long int) (sizeof (size_t))) < 0) { long int i = longval (); - if (i != ((long int) (sizeof (ac__type_sizeof_)))) + if (i != ((long int) (sizeof (size_t)))) return 1; - fprintf (f, "%ld\n", i); + fprintf (f, "%ld", i); } else { unsigned long int i = ulongval (); - if (i != ((long int) (sizeof (ac__type_sizeof_)))) + if (i != ((long int) (sizeof (size_t)))) return 1; - fprintf (f, "%lu\n", i); + fprintf (f, "%lu", i); } + /* Do not output a trailing newline, as this causes \r\n confusion + on some platforms. */ return ferror (f) || fclose (f) != 0; ; @@ -10728,43 +11149,48 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_link") 2>&5 ac_status=$? - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { ac_try='./conftest$ac_exeext' { (case "(($ac_try" in *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_try") 2>&5 ac_status=$? - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); }; }; then ac_cv_sizeof_size_t=`cat conftest.val` else - echo "$as_me: program exited with status $ac_status" >&5 -echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: program exited with status $ac_status" >&5 +$as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 ( exit $ac_status ) if test "$ac_cv_type_size_t" = yes; then - { { echo "$as_me:$LINENO: error: cannot compute sizeof (size_t) + { { $as_echo "$as_me:$LINENO: error: in \`$ac_pwd':" >&5 +$as_echo "$as_me: error: in \`$ac_pwd':" >&2;} +{ { $as_echo "$as_me:$LINENO: error: cannot compute sizeof (size_t) See \`config.log' for more details." >&5 -echo "$as_me: error: cannot compute sizeof (size_t) +$as_echo "$as_me: error: cannot compute sizeof (size_t) See \`config.log' for more details." >&2;} - { (exit 77); exit 77; }; } + { (exit 77); exit 77; }; }; } else ac_cv_sizeof_size_t=0 fi fi +rm -rf conftest.dSYM rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext conftest.$ac_objext conftest.$ac_ext fi rm -f conftest.val fi -{ echo "$as_me:$LINENO: result: $ac_cv_sizeof_size_t" >&5 -echo "${ECHO_T}$ac_cv_sizeof_size_t" >&6; } +{ $as_echo "$as_me:$LINENO: result: $ac_cv_sizeof_size_t" >&5 +$as_echo "$ac_cv_sizeof_size_t" >&6; } @@ -10773,68 +11199,14 @@ _ACEOF -{ echo "$as_me:$LINENO: checking for pid_t" >&5 -echo $ECHO_N "checking for pid_t... $ECHO_C" >&6; } -if test "${ac_cv_type_pid_t+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 -else - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -$ac_includes_default -typedef pid_t ac__type_new_; -int -main () -{ -if ((ac__type_new_ *) 0) - return 0; -if (sizeof (ac__type_new_)) - return 0; - ; - return 0; -} -_ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - ac_cv_type_pid_t=yes -else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - ac_cv_type_pid_t=no -fi - -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext -fi -{ echo "$as_me:$LINENO: result: $ac_cv_type_pid_t" >&5 -echo "${ECHO_T}$ac_cv_type_pid_t" >&6; } - # The cast to long int works around a bug in the HP C Compiler # version HP92453-01 B.11.11.23709.GP, which incorrectly rejects # declarations like `int a3[[(sizeof (unsigned char)) >= 0]];'. # This bug is HP SR number 8606223364. -{ echo "$as_me:$LINENO: checking size of pid_t" >&5 -echo $ECHO_N "checking size of pid_t... $ECHO_C" >&6; } +{ $as_echo "$as_me:$LINENO: checking size of pid_t" >&5 +$as_echo_n "checking size of pid_t... " >&6; } if test "${ac_cv_sizeof_pid_t+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 + $as_echo_n "(cached) " >&6 else if test "$cross_compiling" = yes; then # Depending upon the size, compute the lo and hi bounds. @@ -10845,11 +11217,10 @@ cat >>conftest.$ac_ext <<_ACEOF /* end confdefs.h. */ $ac_includes_default - typedef pid_t ac__type_sizeof_; int main () { -static int test_array [1 - 2 * !(((long int) (sizeof (ac__type_sizeof_))) >= 0)]; +static int test_array [1 - 2 * !(((long int) (sizeof (pid_t))) >= 0)]; test_array [0] = 0 ; @@ -10862,13 +11233,14 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_compile") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { test -z "$ac_c_werror_flag" || test ! -s conftest.err @@ -10882,11 +11254,10 @@ cat >>conftest.$ac_ext <<_ACEOF /* end confdefs.h. */ $ac_includes_default - typedef pid_t ac__type_sizeof_; int main () { -static int test_array [1 - 2 * !(((long int) (sizeof (ac__type_sizeof_))) <= $ac_mid)]; +static int test_array [1 - 2 * !(((long int) (sizeof (pid_t))) <= $ac_mid)]; test_array [0] = 0 ; @@ -10899,20 +11270,21 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_compile") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { test -z "$ac_c_werror_flag" || test ! -s conftest.err } && test -s conftest.$ac_objext; then ac_hi=$ac_mid; break else - echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 ac_lo=`expr $ac_mid + 1` @@ -10926,7 +11298,7 @@ rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext done else - echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 cat >conftest.$ac_ext <<_ACEOF @@ -10936,11 +11308,10 @@ cat >>conftest.$ac_ext <<_ACEOF /* end confdefs.h. */ $ac_includes_default - typedef pid_t ac__type_sizeof_; int main () { -static int test_array [1 - 2 * !(((long int) (sizeof (ac__type_sizeof_))) < 0)]; +static int test_array [1 - 2 * !(((long int) (sizeof (pid_t))) < 0)]; test_array [0] = 0 ; @@ -10953,13 +11324,14 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_compile") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { test -z "$ac_c_werror_flag" || test ! -s conftest.err @@ -10973,11 +11345,10 @@ cat >>conftest.$ac_ext <<_ACEOF /* end confdefs.h. */ $ac_includes_default - typedef pid_t ac__type_sizeof_; int main () { -static int test_array [1 - 2 * !(((long int) (sizeof (ac__type_sizeof_))) >= $ac_mid)]; +static int test_array [1 - 2 * !(((long int) (sizeof (pid_t))) >= $ac_mid)]; test_array [0] = 0 ; @@ -10990,20 +11361,21 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_compile") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { test -z "$ac_c_werror_flag" || test ! -s conftest.err } && test -s conftest.$ac_objext; then ac_lo=$ac_mid; break else - echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 ac_hi=`expr '(' $ac_mid ')' - 1` @@ -11017,7 +11389,7 @@ rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext done else - echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 ac_lo= ac_hi= @@ -11037,11 +11409,10 @@ cat >>conftest.$ac_ext <<_ACEOF /* end confdefs.h. */ $ac_includes_default - typedef pid_t ac__type_sizeof_; int main () { -static int test_array [1 - 2 * !(((long int) (sizeof (ac__type_sizeof_))) <= $ac_mid)]; +static int test_array [1 - 2 * !(((long int) (sizeof (pid_t))) <= $ac_mid)]; test_array [0] = 0 ; @@ -11054,20 +11425,21 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_compile") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { test -z "$ac_c_werror_flag" || test ! -s conftest.err } && test -s conftest.$ac_objext; then ac_hi=$ac_mid else - echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 ac_lo=`expr '(' $ac_mid ')' + 1` @@ -11078,11 +11450,13 @@ case $ac_lo in ?*) ac_cv_sizeof_pid_t=$ac_lo;; '') if test "$ac_cv_type_pid_t" = yes; then - { { echo "$as_me:$LINENO: error: cannot compute sizeof (pid_t) + { { $as_echo "$as_me:$LINENO: error: in \`$ac_pwd':" >&5 +$as_echo "$as_me: error: in \`$ac_pwd':" >&2;} +{ { $as_echo "$as_me:$LINENO: error: cannot compute sizeof (pid_t) See \`config.log' for more details." >&5 -echo "$as_me: error: cannot compute sizeof (pid_t) +$as_echo "$as_me: error: cannot compute sizeof (pid_t) See \`config.log' for more details." >&2;} - { (exit 77); exit 77; }; } + { (exit 77); exit 77; }; }; } else ac_cv_sizeof_pid_t=0 fi ;; @@ -11095,9 +11469,8 @@ cat >>conftest.$ac_ext <<_ACEOF /* end confdefs.h. */ $ac_includes_default - typedef pid_t ac__type_sizeof_; -static long int longval () { return (long int) (sizeof (ac__type_sizeof_)); } -static unsigned long int ulongval () { return (long int) (sizeof (ac__type_sizeof_)); } +static long int longval () { return (long int) (sizeof (pid_t)); } +static unsigned long int ulongval () { return (long int) (sizeof (pid_t)); } #include #include int @@ -11107,20 +11480,22 @@ FILE *f = fopen ("conftest.val", "w"); if (! f) return 1; - if (((long int) (sizeof (ac__type_sizeof_))) < 0) + if (((long int) (sizeof (pid_t))) < 0) { long int i = longval (); - if (i != ((long int) (sizeof (ac__type_sizeof_)))) + if (i != ((long int) (sizeof (pid_t)))) return 1; - fprintf (f, "%ld\n", i); + fprintf (f, "%ld", i); } else { unsigned long int i = ulongval (); - if (i != ((long int) (sizeof (ac__type_sizeof_)))) + if (i != ((long int) (sizeof (pid_t)))) return 1; - fprintf (f, "%lu\n", i); + fprintf (f, "%lu", i); } + /* Do not output a trailing newline, as this causes \r\n confusion + on some platforms. */ return ferror (f) || fclose (f) != 0; ; @@ -11133,43 +11508,48 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_link") 2>&5 ac_status=$? - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { ac_try='./conftest$ac_exeext' { (case "(($ac_try" in *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_try") 2>&5 ac_status=$? - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); }; }; then ac_cv_sizeof_pid_t=`cat conftest.val` else - echo "$as_me: program exited with status $ac_status" >&5 -echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: program exited with status $ac_status" >&5 +$as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 ( exit $ac_status ) if test "$ac_cv_type_pid_t" = yes; then - { { echo "$as_me:$LINENO: error: cannot compute sizeof (pid_t) + { { $as_echo "$as_me:$LINENO: error: in \`$ac_pwd':" >&5 +$as_echo "$as_me: error: in \`$ac_pwd':" >&2;} +{ { $as_echo "$as_me:$LINENO: error: cannot compute sizeof (pid_t) See \`config.log' for more details." >&5 -echo "$as_me: error: cannot compute sizeof (pid_t) +$as_echo "$as_me: error: cannot compute sizeof (pid_t) See \`config.log' for more details." >&2;} - { (exit 77); exit 77; }; } + { (exit 77); exit 77; }; }; } else ac_cv_sizeof_pid_t=0 fi fi +rm -rf conftest.dSYM rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext conftest.$ac_objext conftest.$ac_ext fi rm -f conftest.val fi -{ echo "$as_me:$LINENO: result: $ac_cv_sizeof_pid_t" >&5 -echo "${ECHO_T}$ac_cv_sizeof_pid_t" >&6; } +{ $as_echo "$as_me:$LINENO: result: $ac_cv_sizeof_pid_t" >&5 +$as_echo "$ac_cv_sizeof_pid_t" >&6; } @@ -11179,8 +11559,8 @@ -{ echo "$as_me:$LINENO: checking for long long support" >&5 -echo $ECHO_N "checking for long long support... $ECHO_C" >&6; } +{ $as_echo "$as_me:$LINENO: checking for long long support" >&5 +$as_echo_n "checking for long long support... " >&6; } have_long_long=no cat >conftest.$ac_ext <<_ACEOF /* confdefs.h. */ @@ -11203,13 +11583,14 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_compile") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { test -z "$ac_c_werror_flag" || test ! -s conftest.err @@ -11223,78 +11604,24 @@ have_long_long=yes else - echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 fi rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext -{ echo "$as_me:$LINENO: result: $have_long_long" >&5 -echo "${ECHO_T}$have_long_long" >&6; } +{ $as_echo "$as_me:$LINENO: result: $have_long_long" >&5 +$as_echo "$have_long_long" >&6; } if test "$have_long_long" = yes ; then -{ echo "$as_me:$LINENO: checking for long long" >&5 -echo $ECHO_N "checking for long long... $ECHO_C" >&6; } -if test "${ac_cv_type_long_long+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 -else - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -$ac_includes_default -typedef long long ac__type_new_; -int -main () -{ -if ((ac__type_new_ *) 0) - return 0; -if (sizeof (ac__type_new_)) - return 0; - ; - return 0; -} -_ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - ac_cv_type_long_long=yes -else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - ac_cv_type_long_long=no -fi - -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext -fi -{ echo "$as_me:$LINENO: result: $ac_cv_type_long_long" >&5 -echo "${ECHO_T}$ac_cv_type_long_long" >&6; } - # The cast to long int works around a bug in the HP C Compiler # version HP92453-01 B.11.11.23709.GP, which incorrectly rejects # declarations like `int a3[[(sizeof (unsigned char)) >= 0]];'. # This bug is HP SR number 8606223364. -{ echo "$as_me:$LINENO: checking size of long long" >&5 -echo $ECHO_N "checking size of long long... $ECHO_C" >&6; } +{ $as_echo "$as_me:$LINENO: checking size of long long" >&5 +$as_echo_n "checking size of long long... " >&6; } if test "${ac_cv_sizeof_long_long+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 + $as_echo_n "(cached) " >&6 else if test "$cross_compiling" = yes; then # Depending upon the size, compute the lo and hi bounds. @@ -11305,11 +11632,10 @@ cat >>conftest.$ac_ext <<_ACEOF /* end confdefs.h. */ $ac_includes_default - typedef long long ac__type_sizeof_; int main () { -static int test_array [1 - 2 * !(((long int) (sizeof (ac__type_sizeof_))) >= 0)]; +static int test_array [1 - 2 * !(((long int) (sizeof (long long))) >= 0)]; test_array [0] = 0 ; @@ -11322,13 +11648,14 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_compile") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { test -z "$ac_c_werror_flag" || test ! -s conftest.err @@ -11342,11 +11669,10 @@ cat >>conftest.$ac_ext <<_ACEOF /* end confdefs.h. */ $ac_includes_default - typedef long long ac__type_sizeof_; int main () { -static int test_array [1 - 2 * !(((long int) (sizeof (ac__type_sizeof_))) <= $ac_mid)]; +static int test_array [1 - 2 * !(((long int) (sizeof (long long))) <= $ac_mid)]; test_array [0] = 0 ; @@ -11359,20 +11685,21 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_compile") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { test -z "$ac_c_werror_flag" || test ! -s conftest.err } && test -s conftest.$ac_objext; then ac_hi=$ac_mid; break else - echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 ac_lo=`expr $ac_mid + 1` @@ -11386,7 +11713,7 @@ rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext done else - echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 cat >conftest.$ac_ext <<_ACEOF @@ -11396,11 +11723,10 @@ cat >>conftest.$ac_ext <<_ACEOF /* end confdefs.h. */ $ac_includes_default - typedef long long ac__type_sizeof_; int main () { -static int test_array [1 - 2 * !(((long int) (sizeof (ac__type_sizeof_))) < 0)]; +static int test_array [1 - 2 * !(((long int) (sizeof (long long))) < 0)]; test_array [0] = 0 ; @@ -11413,13 +11739,14 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_compile") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { test -z "$ac_c_werror_flag" || test ! -s conftest.err @@ -11433,11 +11760,10 @@ cat >>conftest.$ac_ext <<_ACEOF /* end confdefs.h. */ $ac_includes_default - typedef long long ac__type_sizeof_; int main () { -static int test_array [1 - 2 * !(((long int) (sizeof (ac__type_sizeof_))) >= $ac_mid)]; +static int test_array [1 - 2 * !(((long int) (sizeof (long long))) >= $ac_mid)]; test_array [0] = 0 ; @@ -11450,20 +11776,21 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_compile") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { test -z "$ac_c_werror_flag" || test ! -s conftest.err } && test -s conftest.$ac_objext; then ac_lo=$ac_mid; break else - echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 ac_hi=`expr '(' $ac_mid ')' - 1` @@ -11477,7 +11804,7 @@ rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext done else - echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 ac_lo= ac_hi= @@ -11497,11 +11824,10 @@ cat >>conftest.$ac_ext <<_ACEOF /* end confdefs.h. */ $ac_includes_default - typedef long long ac__type_sizeof_; int main () { -static int test_array [1 - 2 * !(((long int) (sizeof (ac__type_sizeof_))) <= $ac_mid)]; +static int test_array [1 - 2 * !(((long int) (sizeof (long long))) <= $ac_mid)]; test_array [0] = 0 ; @@ -11514,20 +11840,21 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_compile") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { test -z "$ac_c_werror_flag" || test ! -s conftest.err } && test -s conftest.$ac_objext; then ac_hi=$ac_mid else - echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 ac_lo=`expr '(' $ac_mid ')' + 1` @@ -11538,11 +11865,13 @@ case $ac_lo in ?*) ac_cv_sizeof_long_long=$ac_lo;; '') if test "$ac_cv_type_long_long" = yes; then - { { echo "$as_me:$LINENO: error: cannot compute sizeof (long long) + { { $as_echo "$as_me:$LINENO: error: in \`$ac_pwd':" >&5 +$as_echo "$as_me: error: in \`$ac_pwd':" >&2;} +{ { $as_echo "$as_me:$LINENO: error: cannot compute sizeof (long long) See \`config.log' for more details." >&5 -echo "$as_me: error: cannot compute sizeof (long long) +$as_echo "$as_me: error: cannot compute sizeof (long long) See \`config.log' for more details." >&2;} - { (exit 77); exit 77; }; } + { (exit 77); exit 77; }; }; } else ac_cv_sizeof_long_long=0 fi ;; @@ -11555,9 +11884,8 @@ cat >>conftest.$ac_ext <<_ACEOF /* end confdefs.h. */ $ac_includes_default - typedef long long ac__type_sizeof_; -static long int longval () { return (long int) (sizeof (ac__type_sizeof_)); } -static unsigned long int ulongval () { return (long int) (sizeof (ac__type_sizeof_)); } +static long int longval () { return (long int) (sizeof (long long)); } +static unsigned long int ulongval () { return (long int) (sizeof (long long)); } #include #include int @@ -11567,20 +11895,22 @@ FILE *f = fopen ("conftest.val", "w"); if (! f) return 1; - if (((long int) (sizeof (ac__type_sizeof_))) < 0) + if (((long int) (sizeof (long long))) < 0) { long int i = longval (); - if (i != ((long int) (sizeof (ac__type_sizeof_)))) + if (i != ((long int) (sizeof (long long)))) return 1; - fprintf (f, "%ld\n", i); + fprintf (f, "%ld", i); } else { unsigned long int i = ulongval (); - if (i != ((long int) (sizeof (ac__type_sizeof_)))) + if (i != ((long int) (sizeof (long long)))) return 1; - fprintf (f, "%lu\n", i); + fprintf (f, "%lu", i); } + /* Do not output a trailing newline, as this causes \r\n confusion + on some platforms. */ return ferror (f) || fclose (f) != 0; ; @@ -11593,43 +11923,48 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_link") 2>&5 ac_status=$? - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { ac_try='./conftest$ac_exeext' { (case "(($ac_try" in *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_try") 2>&5 ac_status=$? - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); }; }; then ac_cv_sizeof_long_long=`cat conftest.val` else - echo "$as_me: program exited with status $ac_status" >&5 -echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: program exited with status $ac_status" >&5 +$as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 ( exit $ac_status ) if test "$ac_cv_type_long_long" = yes; then - { { echo "$as_me:$LINENO: error: cannot compute sizeof (long long) + { { $as_echo "$as_me:$LINENO: error: in \`$ac_pwd':" >&5 +$as_echo "$as_me: error: in \`$ac_pwd':" >&2;} +{ { $as_echo "$as_me:$LINENO: error: cannot compute sizeof (long long) See \`config.log' for more details." >&5 -echo "$as_me: error: cannot compute sizeof (long long) +$as_echo "$as_me: error: cannot compute sizeof (long long) See \`config.log' for more details." >&2;} - { (exit 77); exit 77; }; } + { (exit 77); exit 77; }; }; } else ac_cv_sizeof_long_long=0 fi fi +rm -rf conftest.dSYM rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext conftest.$ac_objext conftest.$ac_ext fi rm -f conftest.val fi -{ echo "$as_me:$LINENO: result: $ac_cv_sizeof_long_long" >&5 -echo "${ECHO_T}$ac_cv_sizeof_long_long" >&6; } +{ $as_echo "$as_me:$LINENO: result: $ac_cv_sizeof_long_long" >&5 +$as_echo "$ac_cv_sizeof_long_long" >&6; } @@ -11640,8 +11975,8 @@ fi -{ echo "$as_me:$LINENO: checking for long double support" >&5 -echo $ECHO_N "checking for long double support... $ECHO_C" >&6; } +{ $as_echo "$as_me:$LINENO: checking for long double support" >&5 +$as_echo_n "checking for long double support... " >&6; } have_long_double=no cat >conftest.$ac_ext <<_ACEOF /* confdefs.h. */ @@ -11664,13 +11999,14 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_compile") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { test -z "$ac_c_werror_flag" || test ! -s conftest.err @@ -11684,78 +12020,24 @@ have_long_double=yes else - echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 fi rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext -{ echo "$as_me:$LINENO: result: $have_long_double" >&5 -echo "${ECHO_T}$have_long_double" >&6; } +{ $as_echo "$as_me:$LINENO: result: $have_long_double" >&5 +$as_echo "$have_long_double" >&6; } if test "$have_long_double" = yes ; then -{ echo "$as_me:$LINENO: checking for long double" >&5 -echo $ECHO_N "checking for long double... $ECHO_C" >&6; } -if test "${ac_cv_type_long_double+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 -else - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -$ac_includes_default -typedef long double ac__type_new_; -int -main () -{ -if ((ac__type_new_ *) 0) - return 0; -if (sizeof (ac__type_new_)) - return 0; - ; - return 0; -} -_ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - ac_cv_type_long_double=yes -else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - ac_cv_type_long_double=no -fi - -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext -fi -{ echo "$as_me:$LINENO: result: $ac_cv_type_long_double" >&5 -echo "${ECHO_T}$ac_cv_type_long_double" >&6; } - # The cast to long int works around a bug in the HP C Compiler # version HP92453-01 B.11.11.23709.GP, which incorrectly rejects # declarations like `int a3[[(sizeof (unsigned char)) >= 0]];'. # This bug is HP SR number 8606223364. -{ echo "$as_me:$LINENO: checking size of long double" >&5 -echo $ECHO_N "checking size of long double... $ECHO_C" >&6; } +{ $as_echo "$as_me:$LINENO: checking size of long double" >&5 +$as_echo_n "checking size of long double... " >&6; } if test "${ac_cv_sizeof_long_double+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 + $as_echo_n "(cached) " >&6 else if test "$cross_compiling" = yes; then # Depending upon the size, compute the lo and hi bounds. @@ -11766,11 +12048,10 @@ cat >>conftest.$ac_ext <<_ACEOF /* end confdefs.h. */ $ac_includes_default - typedef long double ac__type_sizeof_; int main () { -static int test_array [1 - 2 * !(((long int) (sizeof (ac__type_sizeof_))) >= 0)]; +static int test_array [1 - 2 * !(((long int) (sizeof (long double))) >= 0)]; test_array [0] = 0 ; @@ -11783,13 +12064,14 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_compile") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { test -z "$ac_c_werror_flag" || test ! -s conftest.err @@ -11803,11 +12085,10 @@ cat >>conftest.$ac_ext <<_ACEOF /* end confdefs.h. */ $ac_includes_default - typedef long double ac__type_sizeof_; int main () { -static int test_array [1 - 2 * !(((long int) (sizeof (ac__type_sizeof_))) <= $ac_mid)]; +static int test_array [1 - 2 * !(((long int) (sizeof (long double))) <= $ac_mid)]; test_array [0] = 0 ; @@ -11820,20 +12101,21 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_compile") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { test -z "$ac_c_werror_flag" || test ! -s conftest.err } && test -s conftest.$ac_objext; then ac_hi=$ac_mid; break else - echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 ac_lo=`expr $ac_mid + 1` @@ -11847,7 +12129,7 @@ rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext done else - echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 cat >conftest.$ac_ext <<_ACEOF @@ -11857,11 +12139,10 @@ cat >>conftest.$ac_ext <<_ACEOF /* end confdefs.h. */ $ac_includes_default - typedef long double ac__type_sizeof_; int main () { -static int test_array [1 - 2 * !(((long int) (sizeof (ac__type_sizeof_))) < 0)]; +static int test_array [1 - 2 * !(((long int) (sizeof (long double))) < 0)]; test_array [0] = 0 ; @@ -11874,13 +12155,14 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_compile") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { test -z "$ac_c_werror_flag" || test ! -s conftest.err @@ -11894,11 +12176,10 @@ cat >>conftest.$ac_ext <<_ACEOF /* end confdefs.h. */ $ac_includes_default - typedef long double ac__type_sizeof_; int main () { -static int test_array [1 - 2 * !(((long int) (sizeof (ac__type_sizeof_))) >= $ac_mid)]; +static int test_array [1 - 2 * !(((long int) (sizeof (long double))) >= $ac_mid)]; test_array [0] = 0 ; @@ -11911,20 +12192,21 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_compile") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { test -z "$ac_c_werror_flag" || test ! -s conftest.err } && test -s conftest.$ac_objext; then ac_lo=$ac_mid; break else - echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 ac_hi=`expr '(' $ac_mid ')' - 1` @@ -11938,7 +12220,7 @@ rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext done else - echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 ac_lo= ac_hi= @@ -11958,11 +12240,10 @@ cat >>conftest.$ac_ext <<_ACEOF /* end confdefs.h. */ $ac_includes_default - typedef long double ac__type_sizeof_; int main () { -static int test_array [1 - 2 * !(((long int) (sizeof (ac__type_sizeof_))) <= $ac_mid)]; +static int test_array [1 - 2 * !(((long int) (sizeof (long double))) <= $ac_mid)]; test_array [0] = 0 ; @@ -11975,20 +12256,21 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_compile") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { test -z "$ac_c_werror_flag" || test ! -s conftest.err } && test -s conftest.$ac_objext; then ac_hi=$ac_mid else - echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 ac_lo=`expr '(' $ac_mid ')' + 1` @@ -11999,11 +12281,13 @@ case $ac_lo in ?*) ac_cv_sizeof_long_double=$ac_lo;; '') if test "$ac_cv_type_long_double" = yes; then - { { echo "$as_me:$LINENO: error: cannot compute sizeof (long double) + { { $as_echo "$as_me:$LINENO: error: in \`$ac_pwd':" >&5 +$as_echo "$as_me: error: in \`$ac_pwd':" >&2;} +{ { $as_echo "$as_me:$LINENO: error: cannot compute sizeof (long double) See \`config.log' for more details." >&5 -echo "$as_me: error: cannot compute sizeof (long double) +$as_echo "$as_me: error: cannot compute sizeof (long double) See \`config.log' for more details." >&2;} - { (exit 77); exit 77; }; } + { (exit 77); exit 77; }; }; } else ac_cv_sizeof_long_double=0 fi ;; @@ -12016,9 +12300,8 @@ cat >>conftest.$ac_ext <<_ACEOF /* end confdefs.h. */ $ac_includes_default - typedef long double ac__type_sizeof_; -static long int longval () { return (long int) (sizeof (ac__type_sizeof_)); } -static unsigned long int ulongval () { return (long int) (sizeof (ac__type_sizeof_)); } +static long int longval () { return (long int) (sizeof (long double)); } +static unsigned long int ulongval () { return (long int) (sizeof (long double)); } #include #include int @@ -12028,20 +12311,22 @@ FILE *f = fopen ("conftest.val", "w"); if (! f) return 1; - if (((long int) (sizeof (ac__type_sizeof_))) < 0) + if (((long int) (sizeof (long double))) < 0) { long int i = longval (); - if (i != ((long int) (sizeof (ac__type_sizeof_)))) + if (i != ((long int) (sizeof (long double)))) return 1; - fprintf (f, "%ld\n", i); + fprintf (f, "%ld", i); } else { unsigned long int i = ulongval (); - if (i != ((long int) (sizeof (ac__type_sizeof_)))) + if (i != ((long int) (sizeof (long double)))) return 1; - fprintf (f, "%lu\n", i); + fprintf (f, "%lu", i); } + /* Do not output a trailing newline, as this causes \r\n confusion + on some platforms. */ return ferror (f) || fclose (f) != 0; ; @@ -12054,128 +12339,73 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_link") 2>&5 ac_status=$? - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { ac_try='./conftest$ac_exeext' { (case "(($ac_try" in *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_try") 2>&5 ac_status=$? - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); }; }; then ac_cv_sizeof_long_double=`cat conftest.val` else - echo "$as_me: program exited with status $ac_status" >&5 -echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: program exited with status $ac_status" >&5 +$as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 ( exit $ac_status ) if test "$ac_cv_type_long_double" = yes; then - { { echo "$as_me:$LINENO: error: cannot compute sizeof (long double) + { { $as_echo "$as_me:$LINENO: error: in \`$ac_pwd':" >&5 +$as_echo "$as_me: error: in \`$ac_pwd':" >&2;} +{ { $as_echo "$as_me:$LINENO: error: cannot compute sizeof (long double) See \`config.log' for more details." >&5 -echo "$as_me: error: cannot compute sizeof (long double) +$as_echo "$as_me: error: cannot compute sizeof (long double) See \`config.log' for more details." >&2;} - { (exit 77); exit 77; }; } + { (exit 77); exit 77; }; }; } else ac_cv_sizeof_long_double=0 fi fi +rm -rf conftest.dSYM rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext conftest.$ac_objext conftest.$ac_ext fi rm -f conftest.val fi -{ echo "$as_me:$LINENO: result: $ac_cv_sizeof_long_double" >&5 -echo "${ECHO_T}$ac_cv_sizeof_long_double" >&6; } - - - -cat >>confdefs.h <<_ACEOF -#define SIZEOF_LONG_DOUBLE $ac_cv_sizeof_long_double -_ACEOF - - -fi - - -{ echo "$as_me:$LINENO: checking for _Bool support" >&5 -echo $ECHO_N "checking for _Bool support... $ECHO_C" >&6; } -have_c99_bool=no -cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ - -int -main () -{ -_Bool x; x = (_Bool)0; - ; - return 0; -} -_ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - +{ $as_echo "$as_me:$LINENO: result: $ac_cv_sizeof_long_double" >&5 +$as_echo "$ac_cv_sizeof_long_double" >&6; } -cat >>confdefs.h <<\_ACEOF -#define HAVE_C99_BOOL 1 -_ACEOF - have_c99_bool=yes -else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 +cat >>confdefs.h <<_ACEOF +#define SIZEOF_LONG_DOUBLE $ac_cv_sizeof_long_double +_ACEOF fi -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext -{ echo "$as_me:$LINENO: result: $have_c99_bool" >&5 -echo "${ECHO_T}$have_c99_bool" >&6; } -if test "$have_c99_bool" = yes ; then -{ echo "$as_me:$LINENO: checking for _Bool" >&5 -echo $ECHO_N "checking for _Bool... $ECHO_C" >&6; } -if test "${ac_cv_type__Bool+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 -else - cat >conftest.$ac_ext <<_ACEOF + +{ $as_echo "$as_me:$LINENO: checking for _Bool support" >&5 +$as_echo_n "checking for _Bool support... " >&6; } +have_c99_bool=no +cat >conftest.$ac_ext <<_ACEOF /* confdefs.h. */ _ACEOF cat confdefs.h >>conftest.$ac_ext cat >>conftest.$ac_ext <<_ACEOF /* end confdefs.h. */ -$ac_includes_default -typedef _Bool ac__type_new_; + int main () { -if ((ac__type_new_ *) 0) - return 0; -if (sizeof (ac__type_new_)) - return 0; +_Bool x; x = (_Bool)0; ; return 0; } @@ -12186,38 +12416,45 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_compile") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { test -z "$ac_c_werror_flag" || test ! -s conftest.err } && test -s conftest.$ac_objext; then - ac_cv_type__Bool=yes + + +cat >>confdefs.h <<\_ACEOF +#define HAVE_C99_BOOL 1 +_ACEOF + + have_c99_bool=yes + else - echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 - ac_cv_type__Bool=no -fi -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext fi -{ echo "$as_me:$LINENO: result: $ac_cv_type__Bool" >&5 -echo "${ECHO_T}$ac_cv_type__Bool" >&6; } +rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext +{ $as_echo "$as_me:$LINENO: result: $have_c99_bool" >&5 +$as_echo "$have_c99_bool" >&6; } +if test "$have_c99_bool" = yes ; then # The cast to long int works around a bug in the HP C Compiler # version HP92453-01 B.11.11.23709.GP, which incorrectly rejects # declarations like `int a3[[(sizeof (unsigned char)) >= 0]];'. # This bug is HP SR number 8606223364. -{ echo "$as_me:$LINENO: checking size of _Bool" >&5 -echo $ECHO_N "checking size of _Bool... $ECHO_C" >&6; } +{ $as_echo "$as_me:$LINENO: checking size of _Bool" >&5 +$as_echo_n "checking size of _Bool... " >&6; } if test "${ac_cv_sizeof__Bool+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 + $as_echo_n "(cached) " >&6 else if test "$cross_compiling" = yes; then # Depending upon the size, compute the lo and hi bounds. @@ -12228,11 +12465,10 @@ cat >>conftest.$ac_ext <<_ACEOF /* end confdefs.h. */ $ac_includes_default - typedef _Bool ac__type_sizeof_; int main () { -static int test_array [1 - 2 * !(((long int) (sizeof (ac__type_sizeof_))) >= 0)]; +static int test_array [1 - 2 * !(((long int) (sizeof (_Bool))) >= 0)]; test_array [0] = 0 ; @@ -12245,13 +12481,14 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_compile") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { test -z "$ac_c_werror_flag" || test ! -s conftest.err @@ -12265,11 +12502,10 @@ cat >>conftest.$ac_ext <<_ACEOF /* end confdefs.h. */ $ac_includes_default - typedef _Bool ac__type_sizeof_; int main () { -static int test_array [1 - 2 * !(((long int) (sizeof (ac__type_sizeof_))) <= $ac_mid)]; +static int test_array [1 - 2 * !(((long int) (sizeof (_Bool))) <= $ac_mid)]; test_array [0] = 0 ; @@ -12282,20 +12518,21 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_compile") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { test -z "$ac_c_werror_flag" || test ! -s conftest.err } && test -s conftest.$ac_objext; then ac_hi=$ac_mid; break else - echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 ac_lo=`expr $ac_mid + 1` @@ -12309,7 +12546,7 @@ rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext done else - echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 cat >conftest.$ac_ext <<_ACEOF @@ -12319,11 +12556,10 @@ cat >>conftest.$ac_ext <<_ACEOF /* end confdefs.h. */ $ac_includes_default - typedef _Bool ac__type_sizeof_; int main () { -static int test_array [1 - 2 * !(((long int) (sizeof (ac__type_sizeof_))) < 0)]; +static int test_array [1 - 2 * !(((long int) (sizeof (_Bool))) < 0)]; test_array [0] = 0 ; @@ -12336,13 +12572,14 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_compile") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { test -z "$ac_c_werror_flag" || test ! -s conftest.err @@ -12356,11 +12593,10 @@ cat >>conftest.$ac_ext <<_ACEOF /* end confdefs.h. */ $ac_includes_default - typedef _Bool ac__type_sizeof_; int main () { -static int test_array [1 - 2 * !(((long int) (sizeof (ac__type_sizeof_))) >= $ac_mid)]; +static int test_array [1 - 2 * !(((long int) (sizeof (_Bool))) >= $ac_mid)]; test_array [0] = 0 ; @@ -12373,20 +12609,21 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_compile") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { test -z "$ac_c_werror_flag" || test ! -s conftest.err } && test -s conftest.$ac_objext; then ac_lo=$ac_mid; break else - echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 ac_hi=`expr '(' $ac_mid ')' - 1` @@ -12400,7 +12637,7 @@ rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext done else - echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 ac_lo= ac_hi= @@ -12420,11 +12657,10 @@ cat >>conftest.$ac_ext <<_ACEOF /* end confdefs.h. */ $ac_includes_default - typedef _Bool ac__type_sizeof_; int main () { -static int test_array [1 - 2 * !(((long int) (sizeof (ac__type_sizeof_))) <= $ac_mid)]; +static int test_array [1 - 2 * !(((long int) (sizeof (_Bool))) <= $ac_mid)]; test_array [0] = 0 ; @@ -12437,20 +12673,21 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_compile") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { test -z "$ac_c_werror_flag" || test ! -s conftest.err } && test -s conftest.$ac_objext; then ac_hi=$ac_mid else - echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 ac_lo=`expr '(' $ac_mid ')' + 1` @@ -12461,11 +12698,13 @@ case $ac_lo in ?*) ac_cv_sizeof__Bool=$ac_lo;; '') if test "$ac_cv_type__Bool" = yes; then - { { echo "$as_me:$LINENO: error: cannot compute sizeof (_Bool) + { { $as_echo "$as_me:$LINENO: error: in \`$ac_pwd':" >&5 +$as_echo "$as_me: error: in \`$ac_pwd':" >&2;} +{ { $as_echo "$as_me:$LINENO: error: cannot compute sizeof (_Bool) See \`config.log' for more details." >&5 -echo "$as_me: error: cannot compute sizeof (_Bool) +$as_echo "$as_me: error: cannot compute sizeof (_Bool) See \`config.log' for more details." >&2;} - { (exit 77); exit 77; }; } + { (exit 77); exit 77; }; }; } else ac_cv_sizeof__Bool=0 fi ;; @@ -12478,9 +12717,8 @@ cat >>conftest.$ac_ext <<_ACEOF /* end confdefs.h. */ $ac_includes_default - typedef _Bool ac__type_sizeof_; -static long int longval () { return (long int) (sizeof (ac__type_sizeof_)); } -static unsigned long int ulongval () { return (long int) (sizeof (ac__type_sizeof_)); } +static long int longval () { return (long int) (sizeof (_Bool)); } +static unsigned long int ulongval () { return (long int) (sizeof (_Bool)); } #include #include int @@ -12490,20 +12728,22 @@ FILE *f = fopen ("conftest.val", "w"); if (! f) return 1; - if (((long int) (sizeof (ac__type_sizeof_))) < 0) + if (((long int) (sizeof (_Bool))) < 0) { long int i = longval (); - if (i != ((long int) (sizeof (ac__type_sizeof_)))) + if (i != ((long int) (sizeof (_Bool)))) return 1; - fprintf (f, "%ld\n", i); + fprintf (f, "%ld", i); } else { unsigned long int i = ulongval (); - if (i != ((long int) (sizeof (ac__type_sizeof_)))) + if (i != ((long int) (sizeof (_Bool)))) return 1; - fprintf (f, "%lu\n", i); + fprintf (f, "%lu", i); } + /* Do not output a trailing newline, as this causes \r\n confusion + on some platforms. */ return ferror (f) || fclose (f) != 0; ; @@ -12516,43 +12756,48 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_link") 2>&5 ac_status=$? - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { ac_try='./conftest$ac_exeext' { (case "(($ac_try" in *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_try") 2>&5 ac_status=$? - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); }; }; then ac_cv_sizeof__Bool=`cat conftest.val` else - echo "$as_me: program exited with status $ac_status" >&5 -echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: program exited with status $ac_status" >&5 +$as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 ( exit $ac_status ) if test "$ac_cv_type__Bool" = yes; then - { { echo "$as_me:$LINENO: error: cannot compute sizeof (_Bool) + { { $as_echo "$as_me:$LINENO: error: in \`$ac_pwd':" >&5 +$as_echo "$as_me: error: in \`$ac_pwd':" >&2;} +{ { $as_echo "$as_me:$LINENO: error: cannot compute sizeof (_Bool) See \`config.log' for more details." >&5 -echo "$as_me: error: cannot compute sizeof (_Bool) +$as_echo "$as_me: error: cannot compute sizeof (_Bool) See \`config.log' for more details." >&2;} - { (exit 77); exit 77; }; } + { (exit 77); exit 77; }; }; } else ac_cv_sizeof__Bool=0 fi fi +rm -rf conftest.dSYM rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext conftest.$ac_objext conftest.$ac_ext fi rm -f conftest.val fi -{ echo "$as_me:$LINENO: result: $ac_cv_sizeof__Bool" >&5 -echo "${ECHO_T}$ac_cv_sizeof__Bool" >&6; } +{ $as_echo "$as_me:$LINENO: result: $ac_cv_sizeof__Bool" >&5 +$as_echo "$ac_cv_sizeof__Bool" >&6; } @@ -12563,12 +12808,13 @@ fi -{ echo "$as_me:$LINENO: checking for uintptr_t" >&5 -echo $ECHO_N "checking for uintptr_t... $ECHO_C" >&6; } +{ $as_echo "$as_me:$LINENO: checking for uintptr_t" >&5 +$as_echo_n "checking for uintptr_t... " >&6; } if test "${ac_cv_type_uintptr_t+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 + $as_echo_n "(cached) " >&6 else - cat >conftest.$ac_ext <<_ACEOF + ac_cv_type_uintptr_t=no +cat >conftest.$ac_ext <<_ACEOF /* confdefs.h. */ _ACEOF cat confdefs.h >>conftest.$ac_ext @@ -12578,14 +12824,11 @@ #include #endif -typedef uintptr_t ac__type_new_; int main () { -if ((ac__type_new_ *) 0) - return 0; -if (sizeof (ac__type_new_)) - return 0; +if (sizeof (uintptr_t)) + return 0; ; return 0; } @@ -12596,55 +12839,33 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_compile") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { test -z "$ac_c_werror_flag" || test ! -s conftest.err } && test -s conftest.$ac_objext; then - ac_cv_type_uintptr_t=yes -else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - ac_cv_type_uintptr_t=no -fi - -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext -fi -{ echo "$as_me:$LINENO: result: $ac_cv_type_uintptr_t" >&5 -echo "${ECHO_T}$ac_cv_type_uintptr_t" >&6; } -if test $ac_cv_type_uintptr_t = yes; then - -cat >>confdefs.h <<_ACEOF -#define HAVE_UINTPTR_T 1 -_ACEOF - -{ echo "$as_me:$LINENO: checking for uintptr_t" >&5 -echo $ECHO_N "checking for uintptr_t... $ECHO_C" >&6; } -if test "${ac_cv_type_uintptr_t+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 -else cat >conftest.$ac_ext <<_ACEOF /* confdefs.h. */ _ACEOF cat confdefs.h >>conftest.$ac_ext cat >>conftest.$ac_ext <<_ACEOF /* end confdefs.h. */ -$ac_includes_default -typedef uintptr_t ac__type_new_; +#ifdef HAVE_STDINT_H + #include + #endif + int main () { -if ((ac__type_new_ *) 0) - return 0; -if (sizeof (ac__type_new_)) - return 0; +if (sizeof ((uintptr_t))) + return 0; ; return 0; } @@ -12655,38 +12876,52 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_compile") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { test -z "$ac_c_werror_flag" || test ! -s conftest.err } && test -s conftest.$ac_objext; then - ac_cv_type_uintptr_t=yes + : +else + $as_echo "$as_me: failed program was:" >&5 +sed 's/^/| /' conftest.$ac_ext >&5 + + ac_cv_type_uintptr_t=yes +fi + +rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext else - echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 - ac_cv_type_uintptr_t=no + fi rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext fi -{ echo "$as_me:$LINENO: result: $ac_cv_type_uintptr_t" >&5 -echo "${ECHO_T}$ac_cv_type_uintptr_t" >&6; } +{ $as_echo "$as_me:$LINENO: result: $ac_cv_type_uintptr_t" >&5 +$as_echo "$ac_cv_type_uintptr_t" >&6; } +if test "x$ac_cv_type_uintptr_t" = x""yes; then + +cat >>confdefs.h <<_ACEOF +#define HAVE_UINTPTR_T 1 +_ACEOF # The cast to long int works around a bug in the HP C Compiler # version HP92453-01 B.11.11.23709.GP, which incorrectly rejects # declarations like `int a3[[(sizeof (unsigned char)) >= 0]];'. # This bug is HP SR number 8606223364. -{ echo "$as_me:$LINENO: checking size of uintptr_t" >&5 -echo $ECHO_N "checking size of uintptr_t... $ECHO_C" >&6; } +{ $as_echo "$as_me:$LINENO: checking size of uintptr_t" >&5 +$as_echo_n "checking size of uintptr_t... " >&6; } if test "${ac_cv_sizeof_uintptr_t+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 + $as_echo_n "(cached) " >&6 else if test "$cross_compiling" = yes; then # Depending upon the size, compute the lo and hi bounds. @@ -12697,11 +12932,10 @@ cat >>conftest.$ac_ext <<_ACEOF /* end confdefs.h. */ $ac_includes_default - typedef uintptr_t ac__type_sizeof_; int main () { -static int test_array [1 - 2 * !(((long int) (sizeof (ac__type_sizeof_))) >= 0)]; +static int test_array [1 - 2 * !(((long int) (sizeof (uintptr_t))) >= 0)]; test_array [0] = 0 ; @@ -12714,13 +12948,14 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_compile") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { test -z "$ac_c_werror_flag" || test ! -s conftest.err @@ -12734,11 +12969,10 @@ cat >>conftest.$ac_ext <<_ACEOF /* end confdefs.h. */ $ac_includes_default - typedef uintptr_t ac__type_sizeof_; int main () { -static int test_array [1 - 2 * !(((long int) (sizeof (ac__type_sizeof_))) <= $ac_mid)]; +static int test_array [1 - 2 * !(((long int) (sizeof (uintptr_t))) <= $ac_mid)]; test_array [0] = 0 ; @@ -12751,20 +12985,21 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_compile") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { test -z "$ac_c_werror_flag" || test ! -s conftest.err } && test -s conftest.$ac_objext; then ac_hi=$ac_mid; break else - echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 ac_lo=`expr $ac_mid + 1` @@ -12778,7 +13013,7 @@ rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext done else - echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 cat >conftest.$ac_ext <<_ACEOF @@ -12788,11 +13023,10 @@ cat >>conftest.$ac_ext <<_ACEOF /* end confdefs.h. */ $ac_includes_default - typedef uintptr_t ac__type_sizeof_; int main () { -static int test_array [1 - 2 * !(((long int) (sizeof (ac__type_sizeof_))) < 0)]; +static int test_array [1 - 2 * !(((long int) (sizeof (uintptr_t))) < 0)]; test_array [0] = 0 ; @@ -12805,13 +13039,14 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_compile") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { test -z "$ac_c_werror_flag" || test ! -s conftest.err @@ -12825,11 +13060,10 @@ cat >>conftest.$ac_ext <<_ACEOF /* end confdefs.h. */ $ac_includes_default - typedef uintptr_t ac__type_sizeof_; int main () { -static int test_array [1 - 2 * !(((long int) (sizeof (ac__type_sizeof_))) >= $ac_mid)]; +static int test_array [1 - 2 * !(((long int) (sizeof (uintptr_t))) >= $ac_mid)]; test_array [0] = 0 ; @@ -12842,20 +13076,21 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_compile") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { test -z "$ac_c_werror_flag" || test ! -s conftest.err } && test -s conftest.$ac_objext; then ac_lo=$ac_mid; break else - echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 ac_hi=`expr '(' $ac_mid ')' - 1` @@ -12869,7 +13104,7 @@ rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext done else - echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 ac_lo= ac_hi= @@ -12889,11 +13124,10 @@ cat >>conftest.$ac_ext <<_ACEOF /* end confdefs.h. */ $ac_includes_default - typedef uintptr_t ac__type_sizeof_; int main () { -static int test_array [1 - 2 * !(((long int) (sizeof (ac__type_sizeof_))) <= $ac_mid)]; +static int test_array [1 - 2 * !(((long int) (sizeof (uintptr_t))) <= $ac_mid)]; test_array [0] = 0 ; @@ -12906,20 +13140,21 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_compile") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { test -z "$ac_c_werror_flag" || test ! -s conftest.err } && test -s conftest.$ac_objext; then ac_hi=$ac_mid else - echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 ac_lo=`expr '(' $ac_mid ')' + 1` @@ -12930,11 +13165,13 @@ case $ac_lo in ?*) ac_cv_sizeof_uintptr_t=$ac_lo;; '') if test "$ac_cv_type_uintptr_t" = yes; then - { { echo "$as_me:$LINENO: error: cannot compute sizeof (uintptr_t) + { { $as_echo "$as_me:$LINENO: error: in \`$ac_pwd':" >&5 +$as_echo "$as_me: error: in \`$ac_pwd':" >&2;} +{ { $as_echo "$as_me:$LINENO: error: cannot compute sizeof (uintptr_t) See \`config.log' for more details." >&5 -echo "$as_me: error: cannot compute sizeof (uintptr_t) +$as_echo "$as_me: error: cannot compute sizeof (uintptr_t) See \`config.log' for more details." >&2;} - { (exit 77); exit 77; }; } + { (exit 77); exit 77; }; }; } else ac_cv_sizeof_uintptr_t=0 fi ;; @@ -12947,9 +13184,8 @@ cat >>conftest.$ac_ext <<_ACEOF /* end confdefs.h. */ $ac_includes_default - typedef uintptr_t ac__type_sizeof_; -static long int longval () { return (long int) (sizeof (ac__type_sizeof_)); } -static unsigned long int ulongval () { return (long int) (sizeof (ac__type_sizeof_)); } +static long int longval () { return (long int) (sizeof (uintptr_t)); } +static unsigned long int ulongval () { return (long int) (sizeof (uintptr_t)); } #include #include int @@ -12959,20 +13195,22 @@ FILE *f = fopen ("conftest.val", "w"); if (! f) return 1; - if (((long int) (sizeof (ac__type_sizeof_))) < 0) + if (((long int) (sizeof (uintptr_t))) < 0) { long int i = longval (); - if (i != ((long int) (sizeof (ac__type_sizeof_)))) + if (i != ((long int) (sizeof (uintptr_t)))) return 1; - fprintf (f, "%ld\n", i); + fprintf (f, "%ld", i); } else { unsigned long int i = ulongval (); - if (i != ((long int) (sizeof (ac__type_sizeof_)))) + if (i != ((long int) (sizeof (uintptr_t)))) return 1; - fprintf (f, "%lu\n", i); + fprintf (f, "%lu", i); } + /* Do not output a trailing newline, as this causes \r\n confusion + on some platforms. */ return ferror (f) || fclose (f) != 0; ; @@ -12985,43 +13223,48 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_link") 2>&5 ac_status=$? - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { ac_try='./conftest$ac_exeext' { (case "(($ac_try" in *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_try") 2>&5 ac_status=$? - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); }; }; then ac_cv_sizeof_uintptr_t=`cat conftest.val` else - echo "$as_me: program exited with status $ac_status" >&5 -echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: program exited with status $ac_status" >&5 +$as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 ( exit $ac_status ) if test "$ac_cv_type_uintptr_t" = yes; then - { { echo "$as_me:$LINENO: error: cannot compute sizeof (uintptr_t) + { { $as_echo "$as_me:$LINENO: error: in \`$ac_pwd':" >&5 +$as_echo "$as_me: error: in \`$ac_pwd':" >&2;} +{ { $as_echo "$as_me:$LINENO: error: cannot compute sizeof (uintptr_t) See \`config.log' for more details." >&5 -echo "$as_me: error: cannot compute sizeof (uintptr_t) +$as_echo "$as_me: error: cannot compute sizeof (uintptr_t) See \`config.log' for more details." >&2;} - { (exit 77); exit 77; }; } + { (exit 77); exit 77; }; }; } else ac_cv_sizeof_uintptr_t=0 fi fi +rm -rf conftest.dSYM rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext conftest.$ac_objext conftest.$ac_ext fi rm -f conftest.val fi -{ echo "$as_me:$LINENO: result: $ac_cv_sizeof_uintptr_t" >&5 -echo "${ECHO_T}$ac_cv_sizeof_uintptr_t" >&6; } +{ $as_echo "$as_me:$LINENO: result: $ac_cv_sizeof_uintptr_t" >&5 +$as_echo "$ac_cv_sizeof_uintptr_t" >&6; } @@ -13035,10 +13278,10 @@ # Hmph. AC_CHECK_SIZEOF() doesn't include . -{ echo "$as_me:$LINENO: checking size of off_t" >&5 -echo $ECHO_N "checking size of off_t... $ECHO_C" >&6; } +{ $as_echo "$as_me:$LINENO: checking size of off_t" >&5 +$as_echo_n "checking size of off_t... " >&6; } if test "${ac_cv_sizeof_off_t+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 + $as_echo_n "(cached) " >&6 else if test "$cross_compiling" = yes; then ac_cv_sizeof_off_t=4 @@ -13065,29 +13308,32 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_link") 2>&5 ac_status=$? - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { ac_try='./conftest$ac_exeext' { (case "(($ac_try" in *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_try") 2>&5 ac_status=$? - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); }; }; then ac_cv_sizeof_off_t=`cat conftestval` else - echo "$as_me: program exited with status $ac_status" >&5 -echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: program exited with status $ac_status" >&5 +$as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 ( exit $ac_status ) ac_cv_sizeof_off_t=0 fi +rm -rf conftest.dSYM rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext conftest.$ac_objext conftest.$ac_ext fi @@ -13095,16 +13341,16 @@ fi -{ echo "$as_me:$LINENO: result: $ac_cv_sizeof_off_t" >&5 -echo "${ECHO_T}$ac_cv_sizeof_off_t" >&6; } +{ $as_echo "$as_me:$LINENO: result: $ac_cv_sizeof_off_t" >&5 +$as_echo "$ac_cv_sizeof_off_t" >&6; } cat >>confdefs.h <<_ACEOF #define SIZEOF_OFF_T $ac_cv_sizeof_off_t _ACEOF -{ echo "$as_me:$LINENO: checking whether to enable large file support" >&5 -echo $ECHO_N "checking whether to enable large file support... $ECHO_C" >&6; } +{ $as_echo "$as_me:$LINENO: checking whether to enable large file support" >&5 +$as_echo_n "checking whether to enable large file support... " >&6; } if test "$have_long_long" = yes then if test "$ac_cv_sizeof_off_t" -gt "$ac_cv_sizeof_long" -a \ @@ -13114,22 +13360,22 @@ #define HAVE_LARGEFILE_SUPPORT 1 _ACEOF - { echo "$as_me:$LINENO: result: yes" >&5 -echo "${ECHO_T}yes" >&6; } + { $as_echo "$as_me:$LINENO: result: yes" >&5 +$as_echo "yes" >&6; } else - { echo "$as_me:$LINENO: result: no" >&5 -echo "${ECHO_T}no" >&6; } + { $as_echo "$as_me:$LINENO: result: no" >&5 +$as_echo "no" >&6; } fi else - { echo "$as_me:$LINENO: result: no" >&5 -echo "${ECHO_T}no" >&6; } + { $as_echo "$as_me:$LINENO: result: no" >&5 +$as_echo "no" >&6; } fi # AC_CHECK_SIZEOF() doesn't include . -{ echo "$as_me:$LINENO: checking size of time_t" >&5 -echo $ECHO_N "checking size of time_t... $ECHO_C" >&6; } +{ $as_echo "$as_me:$LINENO: checking size of time_t" >&5 +$as_echo_n "checking size of time_t... " >&6; } if test "${ac_cv_sizeof_time_t+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 + $as_echo_n "(cached) " >&6 else if test "$cross_compiling" = yes; then ac_cv_sizeof_time_t=4 @@ -13156,29 +13402,32 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_link") 2>&5 ac_status=$? - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { ac_try='./conftest$ac_exeext' { (case "(($ac_try" in *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_try") 2>&5 ac_status=$? - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); }; }; then ac_cv_sizeof_time_t=`cat conftestval` else - echo "$as_me: program exited with status $ac_status" >&5 -echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: program exited with status $ac_status" >&5 +$as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 ( exit $ac_status ) ac_cv_sizeof_time_t=0 fi +rm -rf conftest.dSYM rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext conftest.$ac_objext conftest.$ac_ext fi @@ -13186,8 +13435,8 @@ fi -{ echo "$as_me:$LINENO: result: $ac_cv_sizeof_time_t" >&5 -echo "${ECHO_T}$ac_cv_sizeof_time_t" >&6; } +{ $as_echo "$as_me:$LINENO: result: $ac_cv_sizeof_time_t" >&5 +$as_echo "$ac_cv_sizeof_time_t" >&6; } cat >>confdefs.h <<_ACEOF #define SIZEOF_TIME_T $ac_cv_sizeof_time_t @@ -13204,8 +13453,8 @@ elif test "$ac_cv_pthread" = "yes" then CC="$CC -pthread" fi -{ echo "$as_me:$LINENO: checking for pthread_t" >&5 -echo $ECHO_N "checking for pthread_t... $ECHO_C" >&6; } +{ $as_echo "$as_me:$LINENO: checking for pthread_t" >&5 +$as_echo_n "checking for pthread_t... " >&6; } have_pthread_t=no cat >conftest.$ac_ext <<_ACEOF /* confdefs.h. */ @@ -13228,34 +13477,35 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_compile") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { test -z "$ac_c_werror_flag" || test ! -s conftest.err } && test -s conftest.$ac_objext; then have_pthread_t=yes else - echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 fi rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext -{ echo "$as_me:$LINENO: result: $have_pthread_t" >&5 -echo "${ECHO_T}$have_pthread_t" >&6; } +{ $as_echo "$as_me:$LINENO: result: $have_pthread_t" >&5 +$as_echo "$have_pthread_t" >&6; } if test "$have_pthread_t" = yes ; then # AC_CHECK_SIZEOF() doesn't include . - { echo "$as_me:$LINENO: checking size of pthread_t" >&5 -echo $ECHO_N "checking size of pthread_t... $ECHO_C" >&6; } + { $as_echo "$as_me:$LINENO: checking size of pthread_t" >&5 +$as_echo_n "checking size of pthread_t... " >&6; } if test "${ac_cv_sizeof_pthread_t+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 + $as_echo_n "(cached) " >&6 else if test "$cross_compiling" = yes; then ac_cv_sizeof_pthread_t=4 @@ -13282,29 +13532,32 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_link") 2>&5 ac_status=$? - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { ac_try='./conftest$ac_exeext' { (case "(($ac_try" in *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_try") 2>&5 ac_status=$? - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); }; }; then ac_cv_sizeof_pthread_t=`cat conftestval` else - echo "$as_me: program exited with status $ac_status" >&5 -echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: program exited with status $ac_status" >&5 +$as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 ( exit $ac_status ) ac_cv_sizeof_pthread_t=0 fi +rm -rf conftest.dSYM rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext conftest.$ac_objext conftest.$ac_ext fi @@ -13312,8 +13565,8 @@ fi - { echo "$as_me:$LINENO: result: $ac_cv_sizeof_pthread_t" >&5 -echo "${ECHO_T}$ac_cv_sizeof_pthread_t" >&6; } + { $as_echo "$as_me:$LINENO: result: $ac_cv_sizeof_pthread_t" >&5 +$as_echo "$ac_cv_sizeof_pthread_t" >&6; } cat >>confdefs.h <<_ACEOF #define SIZEOF_PTHREAD_T $ac_cv_sizeof_pthread_t @@ -13382,29 +13635,32 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_link") 2>&5 ac_status=$? - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { ac_try='./conftest$ac_exeext' { (case "(($ac_try" in *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_try") 2>&5 ac_status=$? - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); }; }; then ac_osx_32bit=yes else - echo "$as_me: program exited with status $ac_status" >&5 -echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: program exited with status $ac_status" >&5 +$as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 ( exit $ac_status ) ac_osx_32bit=no fi +rm -rf conftest.dSYM rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext conftest.$ac_objext conftest.$ac_ext fi @@ -13419,8 +13675,8 @@ MACOSX_DEFAULT_ARCH="ppc" ;; *) - { { echo "$as_me:$LINENO: error: Unexpected output of 'arch' on OSX" >&5 -echo "$as_me: error: Unexpected output of 'arch' on OSX" >&2;} + { { $as_echo "$as_me:$LINENO: error: Unexpected output of 'arch' on OSX" >&5 +$as_echo "$as_me: error: Unexpected output of 'arch' on OSX" >&2;} { (exit 1); exit 1; }; } ;; esac @@ -13433,8 +13689,8 @@ MACOSX_DEFAULT_ARCH="ppc64" ;; *) - { { echo "$as_me:$LINENO: error: Unexpected output of 'arch' on OSX" >&5 -echo "$as_me: error: Unexpected output of 'arch' on OSX" >&2;} + { { $as_echo "$as_me:$LINENO: error: Unexpected output of 'arch' on OSX" >&5 +$as_echo "$as_me: error: Unexpected output of 'arch' on OSX" >&2;} { (exit 1); exit 1; }; } ;; esac @@ -13447,8 +13703,8 @@ LIBTOOL_CRUFT=$LIBTOOL_CRUFT' -compatibility_version $(VERSION) -current_version $(VERSION)';; esac -{ echo "$as_me:$LINENO: checking for --enable-framework" >&5 -echo $ECHO_N "checking for --enable-framework... $ECHO_C" >&6; } +{ $as_echo "$as_me:$LINENO: checking for --enable-framework" >&5 +$as_echo_n "checking for --enable-framework... " >&6; } if test "$enable_framework" then BASECFLAGS="$BASECFLAGS -fno-common -dynamic" @@ -13459,21 +13715,21 @@ #define WITH_NEXT_FRAMEWORK 1 _ACEOF - { echo "$as_me:$LINENO: result: yes" >&5 -echo "${ECHO_T}yes" >&6; } + { $as_echo "$as_me:$LINENO: result: yes" >&5 +$as_echo "yes" >&6; } if test $enable_shared = "yes" then - { { echo "$as_me:$LINENO: error: Specifying both --enable-shared and --enable-framework is not supported, use only --enable-framework instead" >&5 -echo "$as_me: error: Specifying both --enable-shared and --enable-framework is not supported, use only --enable-framework instead" >&2;} + { { $as_echo "$as_me:$LINENO: error: Specifying both --enable-shared and --enable-framework is not supported, use only --enable-framework instead" >&5 +$as_echo "$as_me: error: Specifying both --enable-shared and --enable-framework is not supported, use only --enable-framework instead" >&2;} { (exit 1); exit 1; }; } fi else - { echo "$as_me:$LINENO: result: no" >&5 -echo "${ECHO_T}no" >&6; } + { $as_echo "$as_me:$LINENO: result: no" >&5 +$as_echo "no" >&6; } fi -{ echo "$as_me:$LINENO: checking for dyld" >&5 -echo $ECHO_N "checking for dyld... $ECHO_C" >&6; } +{ $as_echo "$as_me:$LINENO: checking for dyld" >&5 +$as_echo_n "checking for dyld... " >&6; } case $ac_sys_system/$ac_sys_release in Darwin/*) @@ -13481,12 +13737,12 @@ #define WITH_DYLD 1 _ACEOF - { echo "$as_me:$LINENO: result: always on for Darwin" >&5 -echo "${ECHO_T}always on for Darwin" >&6; } + { $as_echo "$as_me:$LINENO: result: always on for Darwin" >&5 +$as_echo "always on for Darwin" >&6; } ;; *) - { echo "$as_me:$LINENO: result: no" >&5 -echo "${ECHO_T}no" >&6; } + { $as_echo "$as_me:$LINENO: result: no" >&5 +$as_echo "no" >&6; } ;; esac @@ -13498,8 +13754,8 @@ # SO is the extension of shared libraries `(including the dot!) # -- usually .so, .sl on HP-UX, .dll on Cygwin -{ echo "$as_me:$LINENO: checking SO" >&5 -echo $ECHO_N "checking SO... $ECHO_C" >&6; } +{ $as_echo "$as_me:$LINENO: checking SO" >&5 +$as_echo_n "checking SO... " >&6; } if test -z "$SO" then case $ac_sys_system in @@ -13524,8 +13780,8 @@ echo '=====================================================================' sleep 10 fi -{ echo "$as_me:$LINENO: result: $SO" >&5 -echo "${ECHO_T}$SO" >&6; } +{ $as_echo "$as_me:$LINENO: result: $SO" >&5 +$as_echo "$SO" >&6; } cat >>confdefs.h <<_ACEOF @@ -13536,8 +13792,8 @@ # -- "cc -G" on SunOS 5.x, "ld -shared" on IRIX 5 # (Shared libraries in this instance are shared modules to be loaded into # Python, as opposed to building Python itself as a shared library.) -{ echo "$as_me:$LINENO: checking LDSHARED" >&5 -echo $ECHO_N "checking LDSHARED... $ECHO_C" >&6; } +{ $as_echo "$as_me:$LINENO: checking LDSHARED" >&5 +$as_echo_n "checking LDSHARED... " >&6; } if test -z "$LDSHARED" then case $ac_sys_system/$ac_sys_release in @@ -13608,7 +13864,7 @@ FreeBSD*) if [ "`$CC -dM -E - &5 -echo "${ECHO_T}$LDSHARED" >&6; } +{ $as_echo "$as_me:$LINENO: result: $LDSHARED" >&5 +$as_echo "$LDSHARED" >&6; } BLDSHARED=${BLDSHARED-$LDSHARED} # CCSHARED are the C *flags* used to create objects to go into a shared # library (module) -- this is only needed for a few systems -{ echo "$as_me:$LINENO: checking CCSHARED" >&5 -echo $ECHO_N "checking CCSHARED... $ECHO_C" >&6; } +{ $as_echo "$as_me:$LINENO: checking CCSHARED" >&5 +$as_echo_n "checking CCSHARED... " >&6; } if test -z "$CCSHARED" then case $ac_sys_system/$ac_sys_release in @@ -13678,12 +13934,12 @@ atheos*) CCSHARED="-fPIC";; esac fi -{ echo "$as_me:$LINENO: result: $CCSHARED" >&5 -echo "${ECHO_T}$CCSHARED" >&6; } +{ $as_echo "$as_me:$LINENO: result: $CCSHARED" >&5 +$as_echo "$CCSHARED" >&6; } # LINKFORSHARED are the flags passed to the $(CC) command that links # the python executable -- this is only needed for a few systems -{ echo "$as_me:$LINENO: checking LINKFORSHARED" >&5 -echo $ECHO_N "checking LINKFORSHARED... $ECHO_C" >&6; } +{ $as_echo "$as_me:$LINENO: checking LINKFORSHARED" >&5 +$as_echo_n "checking LINKFORSHARED... " >&6; } if test -z "$LINKFORSHARED" then case $ac_sys_system/$ac_sys_release in @@ -13730,13 +13986,13 @@ LINKFORSHARED='-Wl,-E -N 2048K';; esac fi -{ echo "$as_me:$LINENO: result: $LINKFORSHARED" >&5 -echo "${ECHO_T}$LINKFORSHARED" >&6; } +{ $as_echo "$as_me:$LINENO: result: $LINKFORSHARED" >&5 +$as_echo "$LINKFORSHARED" >&6; } -{ echo "$as_me:$LINENO: checking CFLAGSFORSHARED" >&5 -echo $ECHO_N "checking CFLAGSFORSHARED... $ECHO_C" >&6; } +{ $as_echo "$as_me:$LINENO: checking CFLAGSFORSHARED" >&5 +$as_echo_n "checking CFLAGSFORSHARED... " >&6; } if test ! "$LIBRARY" = "$LDLIBRARY" then case $ac_sys_system in @@ -13748,8 +14004,8 @@ CFLAGSFORSHARED='$(CCSHARED)' esac fi -{ echo "$as_me:$LINENO: result: $CFLAGSFORSHARED" >&5 -echo "${ECHO_T}$CFLAGSFORSHARED" >&6; } +{ $as_echo "$as_me:$LINENO: result: $CFLAGSFORSHARED" >&5 +$as_echo "$CFLAGSFORSHARED" >&6; } # SHLIBS are libraries (except -lc and -lm) to link to the python shared # library (with --enable-shared). @@ -13760,22 +14016,22 @@ # don't need to link LIBS explicitly. The default should be only changed # on systems where this approach causes problems. -{ echo "$as_me:$LINENO: checking SHLIBS" >&5 -echo $ECHO_N "checking SHLIBS... $ECHO_C" >&6; } +{ $as_echo "$as_me:$LINENO: checking SHLIBS" >&5 +$as_echo_n "checking SHLIBS... " >&6; } case "$ac_sys_system" in *) SHLIBS='$(LIBS)';; esac -{ echo "$as_me:$LINENO: result: $SHLIBS" >&5 -echo "${ECHO_T}$SHLIBS" >&6; } +{ $as_echo "$as_me:$LINENO: result: $SHLIBS" >&5 +$as_echo "$SHLIBS" >&6; } # checks for libraries -{ echo "$as_me:$LINENO: checking for dlopen in -ldl" >&5 -echo $ECHO_N "checking for dlopen in -ldl... $ECHO_C" >&6; } +{ $as_echo "$as_me:$LINENO: checking for dlopen in -ldl" >&5 +$as_echo_n "checking for dlopen in -ldl... " >&6; } if test "${ac_cv_lib_dl_dlopen+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 + $as_echo_n "(cached) " >&6 else ac_check_lib_save_LIBS=$LIBS LIBS="-ldl $LIBS" @@ -13807,33 +14063,37 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_link") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { test -z "$ac_c_werror_flag" || test ! -s conftest.err - } && test -s conftest$ac_exeext && - $as_test_x conftest$ac_exeext; then + } && test -s conftest$ac_exeext && { + test "$cross_compiling" = yes || + $as_test_x conftest$ac_exeext + }; then ac_cv_lib_dl_dlopen=yes else - echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 ac_cv_lib_dl_dlopen=no fi +rm -rf conftest.dSYM rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \ conftest$ac_exeext conftest.$ac_ext LIBS=$ac_check_lib_save_LIBS fi -{ echo "$as_me:$LINENO: result: $ac_cv_lib_dl_dlopen" >&5 -echo "${ECHO_T}$ac_cv_lib_dl_dlopen" >&6; } -if test $ac_cv_lib_dl_dlopen = yes; then +{ $as_echo "$as_me:$LINENO: result: $ac_cv_lib_dl_dlopen" >&5 +$as_echo "$ac_cv_lib_dl_dlopen" >&6; } +if test "x$ac_cv_lib_dl_dlopen" = x""yes; then cat >>confdefs.h <<_ACEOF #define HAVE_LIBDL 1 _ACEOF @@ -13843,10 +14103,10 @@ fi # Dynamic linking for SunOS/Solaris and SYSV -{ echo "$as_me:$LINENO: checking for shl_load in -ldld" >&5 -echo $ECHO_N "checking for shl_load in -ldld... $ECHO_C" >&6; } +{ $as_echo "$as_me:$LINENO: checking for shl_load in -ldld" >&5 +$as_echo_n "checking for shl_load in -ldld... " >&6; } if test "${ac_cv_lib_dld_shl_load+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 + $as_echo_n "(cached) " >&6 else ac_check_lib_save_LIBS=$LIBS LIBS="-ldld $LIBS" @@ -13878,33 +14138,37 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_link") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { test -z "$ac_c_werror_flag" || test ! -s conftest.err - } && test -s conftest$ac_exeext && - $as_test_x conftest$ac_exeext; then + } && test -s conftest$ac_exeext && { + test "$cross_compiling" = yes || + $as_test_x conftest$ac_exeext + }; then ac_cv_lib_dld_shl_load=yes else - echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 ac_cv_lib_dld_shl_load=no fi +rm -rf conftest.dSYM rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \ conftest$ac_exeext conftest.$ac_ext LIBS=$ac_check_lib_save_LIBS fi -{ echo "$as_me:$LINENO: result: $ac_cv_lib_dld_shl_load" >&5 -echo "${ECHO_T}$ac_cv_lib_dld_shl_load" >&6; } -if test $ac_cv_lib_dld_shl_load = yes; then +{ $as_echo "$as_me:$LINENO: result: $ac_cv_lib_dld_shl_load" >&5 +$as_echo "$ac_cv_lib_dld_shl_load" >&6; } +if test "x$ac_cv_lib_dld_shl_load" = x""yes; then cat >>confdefs.h <<_ACEOF #define HAVE_LIBDLD 1 _ACEOF @@ -13916,10 +14180,10 @@ # only check for sem_init if thread support is requested if test "$with_threads" = "yes" -o -z "$with_threads"; then - { echo "$as_me:$LINENO: checking for library containing sem_init" >&5 -echo $ECHO_N "checking for library containing sem_init... $ECHO_C" >&6; } + { $as_echo "$as_me:$LINENO: checking for library containing sem_init" >&5 +$as_echo_n "checking for library containing sem_init... " >&6; } if test "${ac_cv_search_sem_init+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 + $as_echo_n "(cached) " >&6 else ac_func_search_save_LIBS=$LIBS cat >conftest.$ac_ext <<_ACEOF @@ -13957,26 +14221,30 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_link") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { test -z "$ac_c_werror_flag" || test ! -s conftest.err - } && test -s conftest$ac_exeext && - $as_test_x conftest$ac_exeext; then + } && test -s conftest$ac_exeext && { + test "$cross_compiling" = yes || + $as_test_x conftest$ac_exeext + }; then ac_cv_search_sem_init=$ac_res else - echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 fi +rm -rf conftest.dSYM rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \ conftest$ac_exeext if test "${ac_cv_search_sem_init+set}" = set; then @@ -13991,8 +14259,8 @@ rm conftest.$ac_ext LIBS=$ac_func_search_save_LIBS fi -{ echo "$as_me:$LINENO: result: $ac_cv_search_sem_init" >&5 -echo "${ECHO_T}$ac_cv_search_sem_init" >&6; } +{ $as_echo "$as_me:$LINENO: result: $ac_cv_search_sem_init" >&5 +$as_echo "$ac_cv_search_sem_init" >&6; } ac_res=$ac_cv_search_sem_init if test "$ac_res" != no; then test "$ac_res" = "none required" || LIBS="$ac_res $LIBS" @@ -14004,10 +14272,10 @@ fi # check if we need libintl for locale functions -{ echo "$as_me:$LINENO: checking for textdomain in -lintl" >&5 -echo $ECHO_N "checking for textdomain in -lintl... $ECHO_C" >&6; } +{ $as_echo "$as_me:$LINENO: checking for textdomain in -lintl" >&5 +$as_echo_n "checking for textdomain in -lintl... " >&6; } if test "${ac_cv_lib_intl_textdomain+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 + $as_echo_n "(cached) " >&6 else ac_check_lib_save_LIBS=$LIBS LIBS="-lintl $LIBS" @@ -14039,33 +14307,37 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_link") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { test -z "$ac_c_werror_flag" || test ! -s conftest.err - } && test -s conftest$ac_exeext && - $as_test_x conftest$ac_exeext; then + } && test -s conftest$ac_exeext && { + test "$cross_compiling" = yes || + $as_test_x conftest$ac_exeext + }; then ac_cv_lib_intl_textdomain=yes else - echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 ac_cv_lib_intl_textdomain=no fi +rm -rf conftest.dSYM rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \ conftest$ac_exeext conftest.$ac_ext LIBS=$ac_check_lib_save_LIBS fi -{ echo "$as_me:$LINENO: result: $ac_cv_lib_intl_textdomain" >&5 -echo "${ECHO_T}$ac_cv_lib_intl_textdomain" >&6; } -if test $ac_cv_lib_intl_textdomain = yes; then +{ $as_echo "$as_me:$LINENO: result: $ac_cv_lib_intl_textdomain" >&5 +$as_echo "$ac_cv_lib_intl_textdomain" >&6; } +if test "x$ac_cv_lib_intl_textdomain" = x""yes; then cat >>confdefs.h <<\_ACEOF #define WITH_LIBINTL 1 @@ -14077,8 +14349,8 @@ # checks for system dependent C++ extensions support case "$ac_sys_system" in - AIX*) { echo "$as_me:$LINENO: checking for genuine AIX C++ extensions support" >&5 -echo $ECHO_N "checking for genuine AIX C++ extensions support... $ECHO_C" >&6; } + AIX*) { $as_echo "$as_me:$LINENO: checking for genuine AIX C++ extensions support" >&5 +$as_echo_n "checking for genuine AIX C++ extensions support... " >&6; } cat >conftest.$ac_ext <<_ACEOF /* confdefs.h. */ _ACEOF @@ -14100,43 +14372,47 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_link") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { test -z "$ac_c_werror_flag" || test ! -s conftest.err - } && test -s conftest$ac_exeext && - $as_test_x conftest$ac_exeext; then + } && test -s conftest$ac_exeext && { + test "$cross_compiling" = yes || + $as_test_x conftest$ac_exeext + }; then cat >>confdefs.h <<\_ACEOF #define AIX_GENUINE_CPLUSPLUS 1 _ACEOF - { echo "$as_me:$LINENO: result: yes" >&5 -echo "${ECHO_T}yes" >&6; } + { $as_echo "$as_me:$LINENO: result: yes" >&5 +$as_echo "yes" >&6; } else - echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 - { echo "$as_me:$LINENO: result: no" >&5 -echo "${ECHO_T}no" >&6; } + { $as_echo "$as_me:$LINENO: result: no" >&5 +$as_echo "no" >&6; } fi +rm -rf conftest.dSYM rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \ conftest$ac_exeext conftest.$ac_ext;; *) ;; esac # Most SVR4 platforms (e.g. Solaris) need -lsocket and -lnsl. -{ echo "$as_me:$LINENO: checking for t_open in -lnsl" >&5 -echo $ECHO_N "checking for t_open in -lnsl... $ECHO_C" >&6; } +{ $as_echo "$as_me:$LINENO: checking for t_open in -lnsl" >&5 +$as_echo_n "checking for t_open in -lnsl... " >&6; } if test "${ac_cv_lib_nsl_t_open+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 + $as_echo_n "(cached) " >&6 else ac_check_lib_save_LIBS=$LIBS LIBS="-lnsl $LIBS" @@ -14168,40 +14444,44 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_link") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { test -z "$ac_c_werror_flag" || test ! -s conftest.err - } && test -s conftest$ac_exeext && - $as_test_x conftest$ac_exeext; then + } && test -s conftest$ac_exeext && { + test "$cross_compiling" = yes || + $as_test_x conftest$ac_exeext + }; then ac_cv_lib_nsl_t_open=yes else - echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 ac_cv_lib_nsl_t_open=no fi +rm -rf conftest.dSYM rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \ conftest$ac_exeext conftest.$ac_ext LIBS=$ac_check_lib_save_LIBS fi -{ echo "$as_me:$LINENO: result: $ac_cv_lib_nsl_t_open" >&5 -echo "${ECHO_T}$ac_cv_lib_nsl_t_open" >&6; } -if test $ac_cv_lib_nsl_t_open = yes; then +{ $as_echo "$as_me:$LINENO: result: $ac_cv_lib_nsl_t_open" >&5 +$as_echo "$ac_cv_lib_nsl_t_open" >&6; } +if test "x$ac_cv_lib_nsl_t_open" = x""yes; then LIBS="-lnsl $LIBS" fi # SVR4 -{ echo "$as_me:$LINENO: checking for socket in -lsocket" >&5 -echo $ECHO_N "checking for socket in -lsocket... $ECHO_C" >&6; } +{ $as_echo "$as_me:$LINENO: checking for socket in -lsocket" >&5 +$as_echo_n "checking for socket in -lsocket... " >&6; } if test "${ac_cv_lib_socket_socket+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 + $as_echo_n "(cached) " >&6 else ac_check_lib_save_LIBS=$LIBS LIBS="-lsocket $LIBS $LIBS" @@ -14233,56 +14513,60 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_link") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { test -z "$ac_c_werror_flag" || test ! -s conftest.err - } && test -s conftest$ac_exeext && - $as_test_x conftest$ac_exeext; then + } && test -s conftest$ac_exeext && { + test "$cross_compiling" = yes || + $as_test_x conftest$ac_exeext + }; then ac_cv_lib_socket_socket=yes else - echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 ac_cv_lib_socket_socket=no fi +rm -rf conftest.dSYM rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \ conftest$ac_exeext conftest.$ac_ext LIBS=$ac_check_lib_save_LIBS fi -{ echo "$as_me:$LINENO: result: $ac_cv_lib_socket_socket" >&5 -echo "${ECHO_T}$ac_cv_lib_socket_socket" >&6; } -if test $ac_cv_lib_socket_socket = yes; then +{ $as_echo "$as_me:$LINENO: result: $ac_cv_lib_socket_socket" >&5 +$as_echo "$ac_cv_lib_socket_socket" >&6; } +if test "x$ac_cv_lib_socket_socket" = x""yes; then LIBS="-lsocket $LIBS" fi # SVR4 sockets -{ echo "$as_me:$LINENO: checking for --with-libs" >&5 -echo $ECHO_N "checking for --with-libs... $ECHO_C" >&6; } +{ $as_echo "$as_me:$LINENO: checking for --with-libs" >&5 +$as_echo_n "checking for --with-libs... " >&6; } # Check whether --with-libs was given. if test "${with_libs+set}" = set; then withval=$with_libs; -{ echo "$as_me:$LINENO: result: $withval" >&5 -echo "${ECHO_T}$withval" >&6; } +{ $as_echo "$as_me:$LINENO: result: $withval" >&5 +$as_echo "$withval" >&6; } LIBS="$withval $LIBS" else - { echo "$as_me:$LINENO: result: no" >&5 -echo "${ECHO_T}no" >&6; } + { $as_echo "$as_me:$LINENO: result: no" >&5 +$as_echo "no" >&6; } fi # Check for use of the system libffi library -{ echo "$as_me:$LINENO: checking for --with-system-ffi" >&5 -echo $ECHO_N "checking for --with-system-ffi... $ECHO_C" >&6; } +{ $as_echo "$as_me:$LINENO: checking for --with-system-ffi" >&5 +$as_echo_n "checking for --with-system-ffi... " >&6; } # Check whether --with-system_ffi was given. if test "${with_system_ffi+set}" = set; then @@ -14290,41 +14574,41 @@ fi -{ echo "$as_me:$LINENO: result: $with_system_ffi" >&5 -echo "${ECHO_T}$with_system_ffi" >&6; } +{ $as_echo "$as_me:$LINENO: result: $with_system_ffi" >&5 +$as_echo "$with_system_ffi" >&6; } # Check for --with-dbmliborder -{ echo "$as_me:$LINENO: checking for --with-dbmliborder" >&5 -echo $ECHO_N "checking for --with-dbmliborder... $ECHO_C" >&6; } +{ $as_echo "$as_me:$LINENO: checking for --with-dbmliborder" >&5 +$as_echo_n "checking for --with-dbmliborder... " >&6; } # Check whether --with-dbmliborder was given. if test "${with_dbmliborder+set}" = set; then withval=$with_dbmliborder; if test x$with_dbmliborder = xyes then -{ { echo "$as_me:$LINENO: error: proper usage is --with-dbmliborder=db1:db2:..." >&5 -echo "$as_me: error: proper usage is --with-dbmliborder=db1:db2:..." >&2;} +{ { $as_echo "$as_me:$LINENO: error: proper usage is --with-dbmliborder=db1:db2:..." >&5 +$as_echo "$as_me: error: proper usage is --with-dbmliborder=db1:db2:..." >&2;} { (exit 1); exit 1; }; } else for db in `echo $with_dbmliborder | sed 's/:/ /g'`; do if test x$db != xndbm && test x$db != xgdbm && test x$db != xbdb then - { { echo "$as_me:$LINENO: error: proper usage is --with-dbmliborder=db1:db2:..." >&5 -echo "$as_me: error: proper usage is --with-dbmliborder=db1:db2:..." >&2;} + { { $as_echo "$as_me:$LINENO: error: proper usage is --with-dbmliborder=db1:db2:..." >&5 +$as_echo "$as_me: error: proper usage is --with-dbmliborder=db1:db2:..." >&2;} { (exit 1); exit 1; }; } fi done fi fi -{ echo "$as_me:$LINENO: result: $with_dbmliborder" >&5 -echo "${ECHO_T}$with_dbmliborder" >&6; } +{ $as_echo "$as_me:$LINENO: result: $with_dbmliborder" >&5 +$as_echo "$with_dbmliborder" >&6; } # Determine if signalmodule should be used. -{ echo "$as_me:$LINENO: checking for --with-signal-module" >&5 -echo $ECHO_N "checking for --with-signal-module... $ECHO_C" >&6; } +{ $as_echo "$as_me:$LINENO: checking for --with-signal-module" >&5 +$as_echo_n "checking for --with-signal-module... " >&6; } # Check whether --with-signal-module was given. if test "${with_signal_module+set}" = set; then @@ -14335,8 +14619,8 @@ if test -z "$with_signal_module" then with_signal_module="yes" fi -{ echo "$as_me:$LINENO: result: $with_signal_module" >&5 -echo "${ECHO_T}$with_signal_module" >&6; } +{ $as_echo "$as_me:$LINENO: result: $with_signal_module" >&5 +$as_echo "$with_signal_module" >&6; } if test "${with_signal_module}" = "yes"; then USE_SIGNAL_MODULE="" @@ -14350,22 +14634,22 @@ USE_THREAD_MODULE="" -{ echo "$as_me:$LINENO: checking for --with-dec-threads" >&5 -echo $ECHO_N "checking for --with-dec-threads... $ECHO_C" >&6; } +{ $as_echo "$as_me:$LINENO: checking for --with-dec-threads" >&5 +$as_echo_n "checking for --with-dec-threads... " >&6; } # Check whether --with-dec-threads was given. if test "${with_dec_threads+set}" = set; then withval=$with_dec_threads; -{ echo "$as_me:$LINENO: result: $withval" >&5 -echo "${ECHO_T}$withval" >&6; } +{ $as_echo "$as_me:$LINENO: result: $withval" >&5 +$as_echo "$withval" >&6; } LDLAST=-threads if test "${with_thread+set}" != set; then with_thread="$withval"; fi else - { echo "$as_me:$LINENO: result: no" >&5 -echo "${ECHO_T}no" >&6; } + { $as_echo "$as_me:$LINENO: result: no" >&5 +$as_echo "no" >&6; } fi @@ -14378,8 +14662,8 @@ -{ echo "$as_me:$LINENO: checking for --with-threads" >&5 -echo $ECHO_N "checking for --with-threads... $ECHO_C" >&6; } +{ $as_echo "$as_me:$LINENO: checking for --with-threads" >&5 +$as_echo_n "checking for --with-threads... " >&6; } # Check whether --with-threads was given. if test "${with_threads+set}" = set; then @@ -14398,8 +14682,8 @@ if test -z "$with_threads" then with_threads="yes" fi -{ echo "$as_me:$LINENO: result: $with_threads" >&5 -echo "${ECHO_T}$with_threads" >&6; } +{ $as_echo "$as_me:$LINENO: result: $with_threads" >&5 +$as_echo "$with_threads" >&6; } if test "$with_threads" = "no" @@ -14465,8 +14749,8 @@ # According to the POSIX spec, a pthreads implementation must # define _POSIX_THREADS in unistd.h. Some apparently don't # (e.g. gnu pth with pthread emulation) - { echo "$as_me:$LINENO: checking for _POSIX_THREADS in unistd.h" >&5 -echo $ECHO_N "checking for _POSIX_THREADS in unistd.h... $ECHO_C" >&6; } + { $as_echo "$as_me:$LINENO: checking for _POSIX_THREADS in unistd.h" >&5 +$as_echo_n "checking for _POSIX_THREADS in unistd.h... " >&6; } cat >conftest.$ac_ext <<_ACEOF /* confdefs.h. */ _ACEOF @@ -14488,25 +14772,25 @@ fi rm -f conftest* - { echo "$as_me:$LINENO: result: $unistd_defines_pthreads" >&5 -echo "${ECHO_T}$unistd_defines_pthreads" >&6; } + { $as_echo "$as_me:$LINENO: result: $unistd_defines_pthreads" >&5 +$as_echo "$unistd_defines_pthreads" >&6; } cat >>confdefs.h <<\_ACEOF #define _REENTRANT 1 _ACEOF if test "${ac_cv_header_cthreads_h+set}" = set; then - { echo "$as_me:$LINENO: checking for cthreads.h" >&5 -echo $ECHO_N "checking for cthreads.h... $ECHO_C" >&6; } + { $as_echo "$as_me:$LINENO: checking for cthreads.h" >&5 +$as_echo_n "checking for cthreads.h... " >&6; } if test "${ac_cv_header_cthreads_h+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 + $as_echo_n "(cached) " >&6 fi -{ echo "$as_me:$LINENO: result: $ac_cv_header_cthreads_h" >&5 -echo "${ECHO_T}$ac_cv_header_cthreads_h" >&6; } +{ $as_echo "$as_me:$LINENO: result: $ac_cv_header_cthreads_h" >&5 +$as_echo "$ac_cv_header_cthreads_h" >&6; } else # Is the header compilable? -{ echo "$as_me:$LINENO: checking cthreads.h usability" >&5 -echo $ECHO_N "checking cthreads.h usability... $ECHO_C" >&6; } +{ $as_echo "$as_me:$LINENO: checking cthreads.h usability" >&5 +$as_echo_n "checking cthreads.h usability... " >&6; } cat >conftest.$ac_ext <<_ACEOF /* confdefs.h. */ _ACEOF @@ -14522,32 +14806,33 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_compile") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { test -z "$ac_c_werror_flag" || test ! -s conftest.err } && test -s conftest.$ac_objext; then ac_header_compiler=yes else - echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 ac_header_compiler=no fi rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext -{ echo "$as_me:$LINENO: result: $ac_header_compiler" >&5 -echo "${ECHO_T}$ac_header_compiler" >&6; } +{ $as_echo "$as_me:$LINENO: result: $ac_header_compiler" >&5 +$as_echo "$ac_header_compiler" >&6; } # Is the header present? -{ echo "$as_me:$LINENO: checking cthreads.h presence" >&5 -echo $ECHO_N "checking cthreads.h presence... $ECHO_C" >&6; } +{ $as_echo "$as_me:$LINENO: checking cthreads.h presence" >&5 +$as_echo_n "checking cthreads.h presence... " >&6; } cat >conftest.$ac_ext <<_ACEOF /* confdefs.h. */ _ACEOF @@ -14561,51 +14846,52 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_cpp conftest.$ac_ext") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } >/dev/null && { test -z "$ac_c_preproc_warn_flag$ac_c_werror_flag" || test ! -s conftest.err }; then ac_header_preproc=yes else - echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 ac_header_preproc=no fi rm -f conftest.err conftest.$ac_ext -{ echo "$as_me:$LINENO: result: $ac_header_preproc" >&5 -echo "${ECHO_T}$ac_header_preproc" >&6; } +{ $as_echo "$as_me:$LINENO: result: $ac_header_preproc" >&5 +$as_echo "$ac_header_preproc" >&6; } # So? What about this header? case $ac_header_compiler:$ac_header_preproc:$ac_c_preproc_warn_flag in yes:no: ) - { echo "$as_me:$LINENO: WARNING: cthreads.h: accepted by the compiler, rejected by the preprocessor!" >&5 -echo "$as_me: WARNING: cthreads.h: accepted by the compiler, rejected by the preprocessor!" >&2;} - { echo "$as_me:$LINENO: WARNING: cthreads.h: proceeding with the compiler's result" >&5 -echo "$as_me: WARNING: cthreads.h: proceeding with the compiler's result" >&2;} + { $as_echo "$as_me:$LINENO: WARNING: cthreads.h: accepted by the compiler, rejected by the preprocessor!" >&5 +$as_echo "$as_me: WARNING: cthreads.h: accepted by the compiler, rejected by the preprocessor!" >&2;} + { $as_echo "$as_me:$LINENO: WARNING: cthreads.h: proceeding with the compiler's result" >&5 +$as_echo "$as_me: WARNING: cthreads.h: proceeding with the compiler's result" >&2;} ac_header_preproc=yes ;; no:yes:* ) - { echo "$as_me:$LINENO: WARNING: cthreads.h: present but cannot be compiled" >&5 -echo "$as_me: WARNING: cthreads.h: present but cannot be compiled" >&2;} - { echo "$as_me:$LINENO: WARNING: cthreads.h: check for missing prerequisite headers?" >&5 -echo "$as_me: WARNING: cthreads.h: check for missing prerequisite headers?" >&2;} - { echo "$as_me:$LINENO: WARNING: cthreads.h: see the Autoconf documentation" >&5 -echo "$as_me: WARNING: cthreads.h: see the Autoconf documentation" >&2;} - { echo "$as_me:$LINENO: WARNING: cthreads.h: section \"Present But Cannot Be Compiled\"" >&5 -echo "$as_me: WARNING: cthreads.h: section \"Present But Cannot Be Compiled\"" >&2;} - { echo "$as_me:$LINENO: WARNING: cthreads.h: proceeding with the preprocessor's result" >&5 -echo "$as_me: WARNING: cthreads.h: proceeding with the preprocessor's result" >&2;} - { echo "$as_me:$LINENO: WARNING: cthreads.h: in the future, the compiler will take precedence" >&5 -echo "$as_me: WARNING: cthreads.h: in the future, the compiler will take precedence" >&2;} + { $as_echo "$as_me:$LINENO: WARNING: cthreads.h: present but cannot be compiled" >&5 +$as_echo "$as_me: WARNING: cthreads.h: present but cannot be compiled" >&2;} + { $as_echo "$as_me:$LINENO: WARNING: cthreads.h: check for missing prerequisite headers?" >&5 +$as_echo "$as_me: WARNING: cthreads.h: check for missing prerequisite headers?" >&2;} + { $as_echo "$as_me:$LINENO: WARNING: cthreads.h: see the Autoconf documentation" >&5 +$as_echo "$as_me: WARNING: cthreads.h: see the Autoconf documentation" >&2;} + { $as_echo "$as_me:$LINENO: WARNING: cthreads.h: section \"Present But Cannot Be Compiled\"" >&5 +$as_echo "$as_me: WARNING: cthreads.h: section \"Present But Cannot Be Compiled\"" >&2;} + { $as_echo "$as_me:$LINENO: WARNING: cthreads.h: proceeding with the preprocessor's result" >&5 +$as_echo "$as_me: WARNING: cthreads.h: proceeding with the preprocessor's result" >&2;} + { $as_echo "$as_me:$LINENO: WARNING: cthreads.h: in the future, the compiler will take precedence" >&5 +$as_echo "$as_me: WARNING: cthreads.h: in the future, the compiler will take precedence" >&2;} ( cat <<\_ASBOX ## -------------------------------------- ## ## Report this to http://bugs.python.org/ ## @@ -14614,18 +14900,18 @@ ) | sed "s/^/$as_me: WARNING: /" >&2 ;; esac -{ echo "$as_me:$LINENO: checking for cthreads.h" >&5 -echo $ECHO_N "checking for cthreads.h... $ECHO_C" >&6; } +{ $as_echo "$as_me:$LINENO: checking for cthreads.h" >&5 +$as_echo_n "checking for cthreads.h... " >&6; } if test "${ac_cv_header_cthreads_h+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 + $as_echo_n "(cached) " >&6 else ac_cv_header_cthreads_h=$ac_header_preproc fi -{ echo "$as_me:$LINENO: result: $ac_cv_header_cthreads_h" >&5 -echo "${ECHO_T}$ac_cv_header_cthreads_h" >&6; } +{ $as_echo "$as_me:$LINENO: result: $ac_cv_header_cthreads_h" >&5 +$as_echo "$ac_cv_header_cthreads_h" >&6; } fi -if test $ac_cv_header_cthreads_h = yes; then +if test "x$ac_cv_header_cthreads_h" = x""yes; then cat >>confdefs.h <<\_ACEOF #define WITH_THREAD 1 _ACEOF @@ -14644,17 +14930,17 @@ else if test "${ac_cv_header_mach_cthreads_h+set}" = set; then - { echo "$as_me:$LINENO: checking for mach/cthreads.h" >&5 -echo $ECHO_N "checking for mach/cthreads.h... $ECHO_C" >&6; } + { $as_echo "$as_me:$LINENO: checking for mach/cthreads.h" >&5 +$as_echo_n "checking for mach/cthreads.h... " >&6; } if test "${ac_cv_header_mach_cthreads_h+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 + $as_echo_n "(cached) " >&6 fi -{ echo "$as_me:$LINENO: result: $ac_cv_header_mach_cthreads_h" >&5 -echo "${ECHO_T}$ac_cv_header_mach_cthreads_h" >&6; } +{ $as_echo "$as_me:$LINENO: result: $ac_cv_header_mach_cthreads_h" >&5 +$as_echo "$ac_cv_header_mach_cthreads_h" >&6; } else # Is the header compilable? -{ echo "$as_me:$LINENO: checking mach/cthreads.h usability" >&5 -echo $ECHO_N "checking mach/cthreads.h usability... $ECHO_C" >&6; } +{ $as_echo "$as_me:$LINENO: checking mach/cthreads.h usability" >&5 +$as_echo_n "checking mach/cthreads.h usability... " >&6; } cat >conftest.$ac_ext <<_ACEOF /* confdefs.h. */ _ACEOF @@ -14670,32 +14956,33 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_compile") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { test -z "$ac_c_werror_flag" || test ! -s conftest.err } && test -s conftest.$ac_objext; then ac_header_compiler=yes else - echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 ac_header_compiler=no fi rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext -{ echo "$as_me:$LINENO: result: $ac_header_compiler" >&5 -echo "${ECHO_T}$ac_header_compiler" >&6; } +{ $as_echo "$as_me:$LINENO: result: $ac_header_compiler" >&5 +$as_echo "$ac_header_compiler" >&6; } # Is the header present? -{ echo "$as_me:$LINENO: checking mach/cthreads.h presence" >&5 -echo $ECHO_N "checking mach/cthreads.h presence... $ECHO_C" >&6; } +{ $as_echo "$as_me:$LINENO: checking mach/cthreads.h presence" >&5 +$as_echo_n "checking mach/cthreads.h presence... " >&6; } cat >conftest.$ac_ext <<_ACEOF /* confdefs.h. */ _ACEOF @@ -14709,51 +14996,52 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_cpp conftest.$ac_ext") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } >/dev/null && { test -z "$ac_c_preproc_warn_flag$ac_c_werror_flag" || test ! -s conftest.err }; then ac_header_preproc=yes else - echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 ac_header_preproc=no fi rm -f conftest.err conftest.$ac_ext -{ echo "$as_me:$LINENO: result: $ac_header_preproc" >&5 -echo "${ECHO_T}$ac_header_preproc" >&6; } +{ $as_echo "$as_me:$LINENO: result: $ac_header_preproc" >&5 +$as_echo "$ac_header_preproc" >&6; } # So? What about this header? case $ac_header_compiler:$ac_header_preproc:$ac_c_preproc_warn_flag in yes:no: ) - { echo "$as_me:$LINENO: WARNING: mach/cthreads.h: accepted by the compiler, rejected by the preprocessor!" >&5 -echo "$as_me: WARNING: mach/cthreads.h: accepted by the compiler, rejected by the preprocessor!" >&2;} - { echo "$as_me:$LINENO: WARNING: mach/cthreads.h: proceeding with the compiler's result" >&5 -echo "$as_me: WARNING: mach/cthreads.h: proceeding with the compiler's result" >&2;} + { $as_echo "$as_me:$LINENO: WARNING: mach/cthreads.h: accepted by the compiler, rejected by the preprocessor!" >&5 +$as_echo "$as_me: WARNING: mach/cthreads.h: accepted by the compiler, rejected by the preprocessor!" >&2;} + { $as_echo "$as_me:$LINENO: WARNING: mach/cthreads.h: proceeding with the compiler's result" >&5 +$as_echo "$as_me: WARNING: mach/cthreads.h: proceeding with the compiler's result" >&2;} ac_header_preproc=yes ;; no:yes:* ) - { echo "$as_me:$LINENO: WARNING: mach/cthreads.h: present but cannot be compiled" >&5 -echo "$as_me: WARNING: mach/cthreads.h: present but cannot be compiled" >&2;} - { echo "$as_me:$LINENO: WARNING: mach/cthreads.h: check for missing prerequisite headers?" >&5 -echo "$as_me: WARNING: mach/cthreads.h: check for missing prerequisite headers?" >&2;} - { echo "$as_me:$LINENO: WARNING: mach/cthreads.h: see the Autoconf documentation" >&5 -echo "$as_me: WARNING: mach/cthreads.h: see the Autoconf documentation" >&2;} - { echo "$as_me:$LINENO: WARNING: mach/cthreads.h: section \"Present But Cannot Be Compiled\"" >&5 -echo "$as_me: WARNING: mach/cthreads.h: section \"Present But Cannot Be Compiled\"" >&2;} - { echo "$as_me:$LINENO: WARNING: mach/cthreads.h: proceeding with the preprocessor's result" >&5 -echo "$as_me: WARNING: mach/cthreads.h: proceeding with the preprocessor's result" >&2;} - { echo "$as_me:$LINENO: WARNING: mach/cthreads.h: in the future, the compiler will take precedence" >&5 -echo "$as_me: WARNING: mach/cthreads.h: in the future, the compiler will take precedence" >&2;} + { $as_echo "$as_me:$LINENO: WARNING: mach/cthreads.h: present but cannot be compiled" >&5 +$as_echo "$as_me: WARNING: mach/cthreads.h: present but cannot be compiled" >&2;} + { $as_echo "$as_me:$LINENO: WARNING: mach/cthreads.h: check for missing prerequisite headers?" >&5 +$as_echo "$as_me: WARNING: mach/cthreads.h: check for missing prerequisite headers?" >&2;} + { $as_echo "$as_me:$LINENO: WARNING: mach/cthreads.h: see the Autoconf documentation" >&5 +$as_echo "$as_me: WARNING: mach/cthreads.h: see the Autoconf documentation" >&2;} + { $as_echo "$as_me:$LINENO: WARNING: mach/cthreads.h: section \"Present But Cannot Be Compiled\"" >&5 +$as_echo "$as_me: WARNING: mach/cthreads.h: section \"Present But Cannot Be Compiled\"" >&2;} + { $as_echo "$as_me:$LINENO: WARNING: mach/cthreads.h: proceeding with the preprocessor's result" >&5 +$as_echo "$as_me: WARNING: mach/cthreads.h: proceeding with the preprocessor's result" >&2;} + { $as_echo "$as_me:$LINENO: WARNING: mach/cthreads.h: in the future, the compiler will take precedence" >&5 +$as_echo "$as_me: WARNING: mach/cthreads.h: in the future, the compiler will take precedence" >&2;} ( cat <<\_ASBOX ## -------------------------------------- ## ## Report this to http://bugs.python.org/ ## @@ -14762,18 +15050,18 @@ ) | sed "s/^/$as_me: WARNING: /" >&2 ;; esac -{ echo "$as_me:$LINENO: checking for mach/cthreads.h" >&5 -echo $ECHO_N "checking for mach/cthreads.h... $ECHO_C" >&6; } +{ $as_echo "$as_me:$LINENO: checking for mach/cthreads.h" >&5 +$as_echo_n "checking for mach/cthreads.h... " >&6; } if test "${ac_cv_header_mach_cthreads_h+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 + $as_echo_n "(cached) " >&6 else ac_cv_header_mach_cthreads_h=$ac_header_preproc fi -{ echo "$as_me:$LINENO: result: $ac_cv_header_mach_cthreads_h" >&5 -echo "${ECHO_T}$ac_cv_header_mach_cthreads_h" >&6; } +{ $as_echo "$as_me:$LINENO: result: $ac_cv_header_mach_cthreads_h" >&5 +$as_echo "$ac_cv_header_mach_cthreads_h" >&6; } fi -if test $ac_cv_header_mach_cthreads_h = yes; then +if test "x$ac_cv_header_mach_cthreads_h" = x""yes; then cat >>confdefs.h <<\_ACEOF #define WITH_THREAD 1 _ACEOF @@ -14790,13 +15078,13 @@ THREADOBJ="Python/thread.o" else - { echo "$as_me:$LINENO: checking for --with-pth" >&5 -echo $ECHO_N "checking for --with-pth... $ECHO_C" >&6; } + { $as_echo "$as_me:$LINENO: checking for --with-pth" >&5 +$as_echo_n "checking for --with-pth... " >&6; } # Check whether --with-pth was given. if test "${with_pth+set}" = set; then - withval=$with_pth; { echo "$as_me:$LINENO: result: $withval" >&5 -echo "${ECHO_T}$withval" >&6; } + withval=$with_pth; { $as_echo "$as_me:$LINENO: result: $withval" >&5 +$as_echo "$withval" >&6; } cat >>confdefs.h <<\_ACEOF #define WITH_THREAD 1 _ACEOF @@ -14809,16 +15097,16 @@ LIBS="-lpth $LIBS" THREADOBJ="Python/thread.o" else - { echo "$as_me:$LINENO: result: no" >&5 -echo "${ECHO_T}no" >&6; } + { $as_echo "$as_me:$LINENO: result: no" >&5 +$as_echo "no" >&6; } # Just looking for pthread_create in libpthread is not enough: # on HP/UX, pthread.h renames pthread_create to a different symbol name. # So we really have to include pthread.h, and then link. _libs=$LIBS LIBS="$LIBS -lpthread" - { echo "$as_me:$LINENO: checking for pthread_create in -lpthread" >&5 -echo $ECHO_N "checking for pthread_create in -lpthread... $ECHO_C" >&6; } + { $as_echo "$as_me:$LINENO: checking for pthread_create in -lpthread" >&5 +$as_echo_n "checking for pthread_create in -lpthread... " >&6; } cat >conftest.$ac_ext <<_ACEOF /* confdefs.h. */ _ACEOF @@ -14843,21 +15131,24 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_link") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { test -z "$ac_c_werror_flag" || test ! -s conftest.err - } && test -s conftest$ac_exeext && - $as_test_x conftest$ac_exeext; then + } && test -s conftest$ac_exeext && { + test "$cross_compiling" = yes || + $as_test_x conftest$ac_exeext + }; then - { echo "$as_me:$LINENO: result: yes" >&5 -echo "${ECHO_T}yes" >&6; } + { $as_echo "$as_me:$LINENO: result: yes" >&5 +$as_echo "yes" >&6; } cat >>confdefs.h <<\_ACEOF #define WITH_THREAD 1 _ACEOF @@ -14865,15 +15156,15 @@ posix_threads=yes THREADOBJ="Python/thread.o" else - echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 LIBS=$_libs - { echo "$as_me:$LINENO: checking for pthread_detach" >&5 -echo $ECHO_N "checking for pthread_detach... $ECHO_C" >&6; } + { $as_echo "$as_me:$LINENO: checking for pthread_detach" >&5 +$as_echo_n "checking for pthread_detach... " >&6; } if test "${ac_cv_func_pthread_detach+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 + $as_echo_n "(cached) " >&6 else cat >conftest.$ac_ext <<_ACEOF /* confdefs.h. */ @@ -14926,32 +15217,36 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_link") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { test -z "$ac_c_werror_flag" || test ! -s conftest.err - } && test -s conftest$ac_exeext && - $as_test_x conftest$ac_exeext; then + } && test -s conftest$ac_exeext && { + test "$cross_compiling" = yes || + $as_test_x conftest$ac_exeext + }; then ac_cv_func_pthread_detach=yes else - echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 ac_cv_func_pthread_detach=no fi +rm -rf conftest.dSYM rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \ conftest$ac_exeext conftest.$ac_ext fi -{ echo "$as_me:$LINENO: result: $ac_cv_func_pthread_detach" >&5 -echo "${ECHO_T}$ac_cv_func_pthread_detach" >&6; } -if test $ac_cv_func_pthread_detach = yes; then +{ $as_echo "$as_me:$LINENO: result: $ac_cv_func_pthread_detach" >&5 +$as_echo "$ac_cv_func_pthread_detach" >&6; } +if test "x$ac_cv_func_pthread_detach" = x""yes; then cat >>confdefs.h <<\_ACEOF #define WITH_THREAD 1 _ACEOF @@ -14961,17 +15256,17 @@ else if test "${ac_cv_header_atheos_threads_h+set}" = set; then - { echo "$as_me:$LINENO: checking for atheos/threads.h" >&5 -echo $ECHO_N "checking for atheos/threads.h... $ECHO_C" >&6; } + { $as_echo "$as_me:$LINENO: checking for atheos/threads.h" >&5 +$as_echo_n "checking for atheos/threads.h... " >&6; } if test "${ac_cv_header_atheos_threads_h+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 + $as_echo_n "(cached) " >&6 fi -{ echo "$as_me:$LINENO: result: $ac_cv_header_atheos_threads_h" >&5 -echo "${ECHO_T}$ac_cv_header_atheos_threads_h" >&6; } +{ $as_echo "$as_me:$LINENO: result: $ac_cv_header_atheos_threads_h" >&5 +$as_echo "$ac_cv_header_atheos_threads_h" >&6; } else # Is the header compilable? -{ echo "$as_me:$LINENO: checking atheos/threads.h usability" >&5 -echo $ECHO_N "checking atheos/threads.h usability... $ECHO_C" >&6; } +{ $as_echo "$as_me:$LINENO: checking atheos/threads.h usability" >&5 +$as_echo_n "checking atheos/threads.h usability... " >&6; } cat >conftest.$ac_ext <<_ACEOF /* confdefs.h. */ _ACEOF @@ -14987,32 +15282,33 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_compile") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { test -z "$ac_c_werror_flag" || test ! -s conftest.err } && test -s conftest.$ac_objext; then ac_header_compiler=yes else - echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 ac_header_compiler=no fi rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext -{ echo "$as_me:$LINENO: result: $ac_header_compiler" >&5 -echo "${ECHO_T}$ac_header_compiler" >&6; } +{ $as_echo "$as_me:$LINENO: result: $ac_header_compiler" >&5 +$as_echo "$ac_header_compiler" >&6; } # Is the header present? -{ echo "$as_me:$LINENO: checking atheos/threads.h presence" >&5 -echo $ECHO_N "checking atheos/threads.h presence... $ECHO_C" >&6; } +{ $as_echo "$as_me:$LINENO: checking atheos/threads.h presence" >&5 +$as_echo_n "checking atheos/threads.h presence... " >&6; } cat >conftest.$ac_ext <<_ACEOF /* confdefs.h. */ _ACEOF @@ -15026,51 +15322,52 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_cpp conftest.$ac_ext") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } >/dev/null && { test -z "$ac_c_preproc_warn_flag$ac_c_werror_flag" || test ! -s conftest.err }; then ac_header_preproc=yes else - echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 ac_header_preproc=no fi rm -f conftest.err conftest.$ac_ext -{ echo "$as_me:$LINENO: result: $ac_header_preproc" >&5 -echo "${ECHO_T}$ac_header_preproc" >&6; } +{ $as_echo "$as_me:$LINENO: result: $ac_header_preproc" >&5 +$as_echo "$ac_header_preproc" >&6; } # So? What about this header? case $ac_header_compiler:$ac_header_preproc:$ac_c_preproc_warn_flag in yes:no: ) - { echo "$as_me:$LINENO: WARNING: atheos/threads.h: accepted by the compiler, rejected by the preprocessor!" >&5 -echo "$as_me: WARNING: atheos/threads.h: accepted by the compiler, rejected by the preprocessor!" >&2;} - { echo "$as_me:$LINENO: WARNING: atheos/threads.h: proceeding with the compiler's result" >&5 -echo "$as_me: WARNING: atheos/threads.h: proceeding with the compiler's result" >&2;} + { $as_echo "$as_me:$LINENO: WARNING: atheos/threads.h: accepted by the compiler, rejected by the preprocessor!" >&5 +$as_echo "$as_me: WARNING: atheos/threads.h: accepted by the compiler, rejected by the preprocessor!" >&2;} + { $as_echo "$as_me:$LINENO: WARNING: atheos/threads.h: proceeding with the compiler's result" >&5 +$as_echo "$as_me: WARNING: atheos/threads.h: proceeding with the compiler's result" >&2;} ac_header_preproc=yes ;; no:yes:* ) - { echo "$as_me:$LINENO: WARNING: atheos/threads.h: present but cannot be compiled" >&5 -echo "$as_me: WARNING: atheos/threads.h: present but cannot be compiled" >&2;} - { echo "$as_me:$LINENO: WARNING: atheos/threads.h: check for missing prerequisite headers?" >&5 -echo "$as_me: WARNING: atheos/threads.h: check for missing prerequisite headers?" >&2;} - { echo "$as_me:$LINENO: WARNING: atheos/threads.h: see the Autoconf documentation" >&5 -echo "$as_me: WARNING: atheos/threads.h: see the Autoconf documentation" >&2;} - { echo "$as_me:$LINENO: WARNING: atheos/threads.h: section \"Present But Cannot Be Compiled\"" >&5 -echo "$as_me: WARNING: atheos/threads.h: section \"Present But Cannot Be Compiled\"" >&2;} - { echo "$as_me:$LINENO: WARNING: atheos/threads.h: proceeding with the preprocessor's result" >&5 -echo "$as_me: WARNING: atheos/threads.h: proceeding with the preprocessor's result" >&2;} - { echo "$as_me:$LINENO: WARNING: atheos/threads.h: in the future, the compiler will take precedence" >&5 -echo "$as_me: WARNING: atheos/threads.h: in the future, the compiler will take precedence" >&2;} + { $as_echo "$as_me:$LINENO: WARNING: atheos/threads.h: present but cannot be compiled" >&5 +$as_echo "$as_me: WARNING: atheos/threads.h: present but cannot be compiled" >&2;} + { $as_echo "$as_me:$LINENO: WARNING: atheos/threads.h: check for missing prerequisite headers?" >&5 +$as_echo "$as_me: WARNING: atheos/threads.h: check for missing prerequisite headers?" >&2;} + { $as_echo "$as_me:$LINENO: WARNING: atheos/threads.h: see the Autoconf documentation" >&5 +$as_echo "$as_me: WARNING: atheos/threads.h: see the Autoconf documentation" >&2;} + { $as_echo "$as_me:$LINENO: WARNING: atheos/threads.h: section \"Present But Cannot Be Compiled\"" >&5 +$as_echo "$as_me: WARNING: atheos/threads.h: section \"Present But Cannot Be Compiled\"" >&2;} + { $as_echo "$as_me:$LINENO: WARNING: atheos/threads.h: proceeding with the preprocessor's result" >&5 +$as_echo "$as_me: WARNING: atheos/threads.h: proceeding with the preprocessor's result" >&2;} + { $as_echo "$as_me:$LINENO: WARNING: atheos/threads.h: in the future, the compiler will take precedence" >&5 +$as_echo "$as_me: WARNING: atheos/threads.h: in the future, the compiler will take precedence" >&2;} ( cat <<\_ASBOX ## -------------------------------------- ## ## Report this to http://bugs.python.org/ ## @@ -15079,18 +15376,18 @@ ) | sed "s/^/$as_me: WARNING: /" >&2 ;; esac -{ echo "$as_me:$LINENO: checking for atheos/threads.h" >&5 -echo $ECHO_N "checking for atheos/threads.h... $ECHO_C" >&6; } +{ $as_echo "$as_me:$LINENO: checking for atheos/threads.h" >&5 +$as_echo_n "checking for atheos/threads.h... " >&6; } if test "${ac_cv_header_atheos_threads_h+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 + $as_echo_n "(cached) " >&6 else ac_cv_header_atheos_threads_h=$ac_header_preproc fi -{ echo "$as_me:$LINENO: result: $ac_cv_header_atheos_threads_h" >&5 -echo "${ECHO_T}$ac_cv_header_atheos_threads_h" >&6; } +{ $as_echo "$as_me:$LINENO: result: $ac_cv_header_atheos_threads_h" >&5 +$as_echo "$ac_cv_header_atheos_threads_h" >&6; } fi -if test $ac_cv_header_atheos_threads_h = yes; then +if test "x$ac_cv_header_atheos_threads_h" = x""yes; then cat >>confdefs.h <<\_ACEOF #define WITH_THREAD 1 _ACEOF @@ -15103,10 +15400,10 @@ THREADOBJ="Python/thread.o" else - { echo "$as_me:$LINENO: checking for pthread_create in -lpthreads" >&5 -echo $ECHO_N "checking for pthread_create in -lpthreads... $ECHO_C" >&6; } + { $as_echo "$as_me:$LINENO: checking for pthread_create in -lpthreads" >&5 +$as_echo_n "checking for pthread_create in -lpthreads... " >&6; } if test "${ac_cv_lib_pthreads_pthread_create+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 + $as_echo_n "(cached) " >&6 else ac_check_lib_save_LIBS=$LIBS LIBS="-lpthreads $LIBS" @@ -15138,33 +15435,37 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_link") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { test -z "$ac_c_werror_flag" || test ! -s conftest.err - } && test -s conftest$ac_exeext && - $as_test_x conftest$ac_exeext; then + } && test -s conftest$ac_exeext && { + test "$cross_compiling" = yes || + $as_test_x conftest$ac_exeext + }; then ac_cv_lib_pthreads_pthread_create=yes else - echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 ac_cv_lib_pthreads_pthread_create=no fi +rm -rf conftest.dSYM rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \ conftest$ac_exeext conftest.$ac_ext LIBS=$ac_check_lib_save_LIBS fi -{ echo "$as_me:$LINENO: result: $ac_cv_lib_pthreads_pthread_create" >&5 -echo "${ECHO_T}$ac_cv_lib_pthreads_pthread_create" >&6; } -if test $ac_cv_lib_pthreads_pthread_create = yes; then +{ $as_echo "$as_me:$LINENO: result: $ac_cv_lib_pthreads_pthread_create" >&5 +$as_echo "$ac_cv_lib_pthreads_pthread_create" >&6; } +if test "x$ac_cv_lib_pthreads_pthread_create" = x""yes; then cat >>confdefs.h <<\_ACEOF #define WITH_THREAD 1 _ACEOF @@ -15174,10 +15475,10 @@ THREADOBJ="Python/thread.o" else - { echo "$as_me:$LINENO: checking for pthread_create in -lc_r" >&5 -echo $ECHO_N "checking for pthread_create in -lc_r... $ECHO_C" >&6; } + { $as_echo "$as_me:$LINENO: checking for pthread_create in -lc_r" >&5 +$as_echo_n "checking for pthread_create in -lc_r... " >&6; } if test "${ac_cv_lib_c_r_pthread_create+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 + $as_echo_n "(cached) " >&6 else ac_check_lib_save_LIBS=$LIBS LIBS="-lc_r $LIBS" @@ -15209,33 +15510,37 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_link") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { test -z "$ac_c_werror_flag" || test ! -s conftest.err - } && test -s conftest$ac_exeext && - $as_test_x conftest$ac_exeext; then + } && test -s conftest$ac_exeext && { + test "$cross_compiling" = yes || + $as_test_x conftest$ac_exeext + }; then ac_cv_lib_c_r_pthread_create=yes else - echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 ac_cv_lib_c_r_pthread_create=no fi +rm -rf conftest.dSYM rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \ conftest$ac_exeext conftest.$ac_ext LIBS=$ac_check_lib_save_LIBS fi -{ echo "$as_me:$LINENO: result: $ac_cv_lib_c_r_pthread_create" >&5 -echo "${ECHO_T}$ac_cv_lib_c_r_pthread_create" >&6; } -if test $ac_cv_lib_c_r_pthread_create = yes; then +{ $as_echo "$as_me:$LINENO: result: $ac_cv_lib_c_r_pthread_create" >&5 +$as_echo "$ac_cv_lib_c_r_pthread_create" >&6; } +if test "x$ac_cv_lib_c_r_pthread_create" = x""yes; then cat >>confdefs.h <<\_ACEOF #define WITH_THREAD 1 _ACEOF @@ -15245,10 +15550,10 @@ THREADOBJ="Python/thread.o" else - { echo "$as_me:$LINENO: checking for __pthread_create_system in -lpthread" >&5 -echo $ECHO_N "checking for __pthread_create_system in -lpthread... $ECHO_C" >&6; } + { $as_echo "$as_me:$LINENO: checking for __pthread_create_system in -lpthread" >&5 +$as_echo_n "checking for __pthread_create_system in -lpthread... " >&6; } if test "${ac_cv_lib_pthread___pthread_create_system+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 + $as_echo_n "(cached) " >&6 else ac_check_lib_save_LIBS=$LIBS LIBS="-lpthread $LIBS" @@ -15280,33 +15585,37 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_link") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { test -z "$ac_c_werror_flag" || test ! -s conftest.err - } && test -s conftest$ac_exeext && - $as_test_x conftest$ac_exeext; then + } && test -s conftest$ac_exeext && { + test "$cross_compiling" = yes || + $as_test_x conftest$ac_exeext + }; then ac_cv_lib_pthread___pthread_create_system=yes else - echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 ac_cv_lib_pthread___pthread_create_system=no fi +rm -rf conftest.dSYM rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \ conftest$ac_exeext conftest.$ac_ext LIBS=$ac_check_lib_save_LIBS fi -{ echo "$as_me:$LINENO: result: $ac_cv_lib_pthread___pthread_create_system" >&5 -echo "${ECHO_T}$ac_cv_lib_pthread___pthread_create_system" >&6; } -if test $ac_cv_lib_pthread___pthread_create_system = yes; then +{ $as_echo "$as_me:$LINENO: result: $ac_cv_lib_pthread___pthread_create_system" >&5 +$as_echo "$ac_cv_lib_pthread___pthread_create_system" >&6; } +if test "x$ac_cv_lib_pthread___pthread_create_system" = x""yes; then cat >>confdefs.h <<\_ACEOF #define WITH_THREAD 1 _ACEOF @@ -15316,10 +15625,10 @@ THREADOBJ="Python/thread.o" else - { echo "$as_me:$LINENO: checking for pthread_create in -lcma" >&5 -echo $ECHO_N "checking for pthread_create in -lcma... $ECHO_C" >&6; } + { $as_echo "$as_me:$LINENO: checking for pthread_create in -lcma" >&5 +$as_echo_n "checking for pthread_create in -lcma... " >&6; } if test "${ac_cv_lib_cma_pthread_create+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 + $as_echo_n "(cached) " >&6 else ac_check_lib_save_LIBS=$LIBS LIBS="-lcma $LIBS" @@ -15351,33 +15660,37 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_link") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { test -z "$ac_c_werror_flag" || test ! -s conftest.err - } && test -s conftest$ac_exeext && - $as_test_x conftest$ac_exeext; then + } && test -s conftest$ac_exeext && { + test "$cross_compiling" = yes || + $as_test_x conftest$ac_exeext + }; then ac_cv_lib_cma_pthread_create=yes else - echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 ac_cv_lib_cma_pthread_create=no fi +rm -rf conftest.dSYM rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \ conftest$ac_exeext conftest.$ac_ext LIBS=$ac_check_lib_save_LIBS fi -{ echo "$as_me:$LINENO: result: $ac_cv_lib_cma_pthread_create" >&5 -echo "${ECHO_T}$ac_cv_lib_cma_pthread_create" >&6; } -if test $ac_cv_lib_cma_pthread_create = yes; then +{ $as_echo "$as_me:$LINENO: result: $ac_cv_lib_cma_pthread_create" >&5 +$as_echo "$ac_cv_lib_cma_pthread_create" >&6; } +if test "x$ac_cv_lib_cma_pthread_create" = x""yes; then cat >>confdefs.h <<\_ACEOF #define WITH_THREAD 1 _ACEOF @@ -15404,6 +15717,7 @@ fi +rm -rf conftest.dSYM rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \ conftest$ac_exeext conftest.$ac_ext fi @@ -15415,10 +15729,10 @@ - { echo "$as_me:$LINENO: checking for usconfig in -lmpc" >&5 -echo $ECHO_N "checking for usconfig in -lmpc... $ECHO_C" >&6; } + { $as_echo "$as_me:$LINENO: checking for usconfig in -lmpc" >&5 +$as_echo_n "checking for usconfig in -lmpc... " >&6; } if test "${ac_cv_lib_mpc_usconfig+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 + $as_echo_n "(cached) " >&6 else ac_check_lib_save_LIBS=$LIBS LIBS="-lmpc $LIBS" @@ -15450,33 +15764,37 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_link") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { test -z "$ac_c_werror_flag" || test ! -s conftest.err - } && test -s conftest$ac_exeext && - $as_test_x conftest$ac_exeext; then + } && test -s conftest$ac_exeext && { + test "$cross_compiling" = yes || + $as_test_x conftest$ac_exeext + }; then ac_cv_lib_mpc_usconfig=yes else - echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 ac_cv_lib_mpc_usconfig=no fi +rm -rf conftest.dSYM rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \ conftest$ac_exeext conftest.$ac_ext LIBS=$ac_check_lib_save_LIBS fi -{ echo "$as_me:$LINENO: result: $ac_cv_lib_mpc_usconfig" >&5 -echo "${ECHO_T}$ac_cv_lib_mpc_usconfig" >&6; } -if test $ac_cv_lib_mpc_usconfig = yes; then +{ $as_echo "$as_me:$LINENO: result: $ac_cv_lib_mpc_usconfig" >&5 +$as_echo "$ac_cv_lib_mpc_usconfig" >&6; } +if test "x$ac_cv_lib_mpc_usconfig" = x""yes; then cat >>confdefs.h <<\_ACEOF #define WITH_THREAD 1 _ACEOF @@ -15488,10 +15806,10 @@ if test "$posix_threads" != "yes"; then - { echo "$as_me:$LINENO: checking for thr_create in -lthread" >&5 -echo $ECHO_N "checking for thr_create in -lthread... $ECHO_C" >&6; } + { $as_echo "$as_me:$LINENO: checking for thr_create in -lthread" >&5 +$as_echo_n "checking for thr_create in -lthread... " >&6; } if test "${ac_cv_lib_thread_thr_create+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 + $as_echo_n "(cached) " >&6 else ac_check_lib_save_LIBS=$LIBS LIBS="-lthread $LIBS" @@ -15523,33 +15841,37 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_link") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { test -z "$ac_c_werror_flag" || test ! -s conftest.err - } && test -s conftest$ac_exeext && - $as_test_x conftest$ac_exeext; then + } && test -s conftest$ac_exeext && { + test "$cross_compiling" = yes || + $as_test_x conftest$ac_exeext + }; then ac_cv_lib_thread_thr_create=yes else - echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 ac_cv_lib_thread_thr_create=no fi +rm -rf conftest.dSYM rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \ conftest$ac_exeext conftest.$ac_ext LIBS=$ac_check_lib_save_LIBS fi -{ echo "$as_me:$LINENO: result: $ac_cv_lib_thread_thr_create" >&5 -echo "${ECHO_T}$ac_cv_lib_thread_thr_create" >&6; } -if test $ac_cv_lib_thread_thr_create = yes; then +{ $as_echo "$as_me:$LINENO: result: $ac_cv_lib_thread_thr_create" >&5 +$as_echo "$ac_cv_lib_thread_thr_create" >&6; } +if test "x$ac_cv_lib_thread_thr_create" = x""yes; then cat >>confdefs.h <<\_ACEOF #define WITH_THREAD 1 _ACEOF @@ -15602,10 +15924,10 @@ ;; esac - { echo "$as_me:$LINENO: checking if PTHREAD_SCOPE_SYSTEM is supported" >&5 -echo $ECHO_N "checking if PTHREAD_SCOPE_SYSTEM is supported... $ECHO_C" >&6; } + { $as_echo "$as_me:$LINENO: checking if PTHREAD_SCOPE_SYSTEM is supported" >&5 +$as_echo_n "checking if PTHREAD_SCOPE_SYSTEM is supported... " >&6; } if test "${ac_cv_pthread_system_supported+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 + $as_echo_n "(cached) " >&6 else if test "$cross_compiling" = yes; then ac_cv_pthread_system_supported=no @@ -15635,29 +15957,32 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_link") 2>&5 ac_status=$? - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { ac_try='./conftest$ac_exeext' { (case "(($ac_try" in *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_try") 2>&5 ac_status=$? - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); }; }; then ac_cv_pthread_system_supported=yes else - echo "$as_me: program exited with status $ac_status" >&5 -echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: program exited with status $ac_status" >&5 +$as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 ( exit $ac_status ) ac_cv_pthread_system_supported=no fi +rm -rf conftest.dSYM rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext conftest.$ac_objext conftest.$ac_ext fi @@ -15665,8 +15990,8 @@ fi - { echo "$as_me:$LINENO: result: $ac_cv_pthread_system_supported" >&5 -echo "${ECHO_T}$ac_cv_pthread_system_supported" >&6; } + { $as_echo "$as_me:$LINENO: result: $ac_cv_pthread_system_supported" >&5 +$as_echo "$ac_cv_pthread_system_supported" >&6; } if test "$ac_cv_pthread_system_supported" = "yes"; then cat >>confdefs.h <<\_ACEOF @@ -15677,11 +16002,11 @@ for ac_func in pthread_sigmask do -as_ac_var=`echo "ac_cv_func_$ac_func" | $as_tr_sh` -{ echo "$as_me:$LINENO: checking for $ac_func" >&5 -echo $ECHO_N "checking for $ac_func... $ECHO_C" >&6; } +as_ac_var=`$as_echo "ac_cv_func_$ac_func" | $as_tr_sh` +{ $as_echo "$as_me:$LINENO: checking for $ac_func" >&5 +$as_echo_n "checking for $ac_func... " >&6; } if { as_var=$as_ac_var; eval "test \"\${$as_var+set}\" = set"; }; then - echo $ECHO_N "(cached) $ECHO_C" >&6 + $as_echo_n "(cached) " >&6 else cat >conftest.$ac_ext <<_ACEOF /* confdefs.h. */ @@ -15734,35 +16059,42 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_link") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { test -z "$ac_c_werror_flag" || test ! -s conftest.err - } && test -s conftest$ac_exeext && - $as_test_x conftest$ac_exeext; then + } && test -s conftest$ac_exeext && { + test "$cross_compiling" = yes || + $as_test_x conftest$ac_exeext + }; then eval "$as_ac_var=yes" else - echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 eval "$as_ac_var=no" fi +rm -rf conftest.dSYM rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \ conftest$ac_exeext conftest.$ac_ext fi -ac_res=`eval echo '${'$as_ac_var'}'` - { echo "$as_me:$LINENO: result: $ac_res" >&5 -echo "${ECHO_T}$ac_res" >&6; } -if test `eval echo '${'$as_ac_var'}'` = yes; then +ac_res=`eval 'as_val=${'$as_ac_var'} + $as_echo "$as_val"'` + { $as_echo "$as_me:$LINENO: result: $ac_res" >&5 +$as_echo "$ac_res" >&6; } +as_val=`eval 'as_val=${'$as_ac_var'} + $as_echo "$as_val"'` + if test "x$as_val" = x""yes; then cat >>confdefs.h <<_ACEOF -#define `echo "HAVE_$ac_func" | $as_tr_cpp` 1 +#define `$as_echo "HAVE_$ac_func" | $as_tr_cpp` 1 _ACEOF case $ac_sys_system in CYGWIN*) @@ -15782,18 +16114,18 @@ # Check for enable-ipv6 -{ echo "$as_me:$LINENO: checking if --enable-ipv6 is specified" >&5 -echo $ECHO_N "checking if --enable-ipv6 is specified... $ECHO_C" >&6; } +{ $as_echo "$as_me:$LINENO: checking if --enable-ipv6 is specified" >&5 +$as_echo_n "checking if --enable-ipv6 is specified... " >&6; } # Check whether --enable-ipv6 was given. if test "${enable_ipv6+set}" = set; then enableval=$enable_ipv6; case "$enableval" in no) - { echo "$as_me:$LINENO: result: no" >&5 -echo "${ECHO_T}no" >&6; } + { $as_echo "$as_me:$LINENO: result: no" >&5 +$as_echo "no" >&6; } ipv6=no ;; - *) { echo "$as_me:$LINENO: result: yes" >&5 -echo "${ECHO_T}yes" >&6; } + *) { $as_echo "$as_me:$LINENO: result: yes" >&5 +$as_echo "yes" >&6; } cat >>confdefs.h <<\_ACEOF #define ENABLE_IPV6 1 _ACEOF @@ -15804,8 +16136,8 @@ else if test "$cross_compiling" = yes; then - { echo "$as_me:$LINENO: result: no" >&5 -echo "${ECHO_T}no" >&6; } + { $as_echo "$as_me:$LINENO: result: no" >&5 +$as_echo "no" >&6; } ipv6=no else @@ -15833,41 +16165,44 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_link") 2>&5 ac_status=$? - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { ac_try='./conftest$ac_exeext' { (case "(($ac_try" in *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_try") 2>&5 ac_status=$? - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); }; }; then - { echo "$as_me:$LINENO: result: yes" >&5 -echo "${ECHO_T}yes" >&6; } + { $as_echo "$as_me:$LINENO: result: yes" >&5 +$as_echo "yes" >&6; } ipv6=yes else - echo "$as_me: program exited with status $ac_status" >&5 -echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: program exited with status $ac_status" >&5 +$as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 ( exit $ac_status ) -{ echo "$as_me:$LINENO: result: no" >&5 -echo "${ECHO_T}no" >&6; } +{ $as_echo "$as_me:$LINENO: result: no" >&5 +$as_echo "no" >&6; } ipv6=no fi +rm -rf conftest.dSYM rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext conftest.$ac_objext conftest.$ac_ext fi if test "$ipv6" = "yes"; then - { echo "$as_me:$LINENO: checking if RFC2553 API is available" >&5 -echo $ECHO_N "checking if RFC2553 API is available... $ECHO_C" >&6; } + { $as_echo "$as_me:$LINENO: checking if RFC2553 API is available" >&5 +$as_echo_n "checking if RFC2553 API is available... " >&6; } cat >conftest.$ac_ext <<_ACEOF /* confdefs.h. */ _ACEOF @@ -15891,26 +16226,27 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_compile") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { test -z "$ac_c_werror_flag" || test ! -s conftest.err } && test -s conftest.$ac_objext; then - { echo "$as_me:$LINENO: result: yes" >&5 -echo "${ECHO_T}yes" >&6; } + { $as_echo "$as_me:$LINENO: result: yes" >&5 +$as_echo "yes" >&6; } ipv6=yes else - echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 - { echo "$as_me:$LINENO: result: no" >&5 -echo "${ECHO_T}no" >&6; } + { $as_echo "$as_me:$LINENO: result: no" >&5 +$as_echo "no" >&6; } ipv6=no fi @@ -15932,8 +16268,8 @@ ipv6trylibc=no if test "$ipv6" = "yes"; then - { echo "$as_me:$LINENO: checking ipv6 stack type" >&5 -echo $ECHO_N "checking ipv6 stack type... $ECHO_C" >&6; } + { $as_echo "$as_me:$LINENO: checking ipv6 stack type" >&5 +$as_echo_n "checking ipv6 stack type... " >&6; } for i in inria kame linux-glibc linux-inet6 solaris toshiba v6d zeta; do case $i in @@ -16089,8 +16425,8 @@ break fi done - { echo "$as_me:$LINENO: result: $ipv6type" >&5 -echo "${ECHO_T}$ipv6type" >&6; } + { $as_echo "$as_me:$LINENO: result: $ipv6type" >&5 +$as_echo "$ipv6type" >&6; } fi if test "$ipv6" = "yes" -a "$ipv6lib" != "none"; then @@ -16109,8 +16445,8 @@ fi fi -{ echo "$as_me:$LINENO: checking for OSX 10.5 SDK or later" >&5 -echo $ECHO_N "checking for OSX 10.5 SDK or later... $ECHO_C" >&6; } +{ $as_echo "$as_me:$LINENO: checking for OSX 10.5 SDK or later" >&5 +$as_echo_n "checking for OSX 10.5 SDK or later... " >&6; } cat >conftest.$ac_ext <<_ACEOF /* confdefs.h. */ _ACEOF @@ -16132,13 +16468,14 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_compile") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { test -z "$ac_c_werror_flag" || test ! -s conftest.err @@ -16148,22 +16485,22 @@ #define HAVE_OSX105_SDK 1 _ACEOF - { echo "$as_me:$LINENO: result: yes" >&5 -echo "${ECHO_T}yes" >&6; } + { $as_echo "$as_me:$LINENO: result: yes" >&5 +$as_echo "yes" >&6; } else - echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 - { echo "$as_me:$LINENO: result: no" >&5 -echo "${ECHO_T}no" >&6; } + { $as_echo "$as_me:$LINENO: result: no" >&5 +$as_echo "no" >&6; } fi rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext # Check for --with-doc-strings -{ echo "$as_me:$LINENO: checking for --with-doc-strings" >&5 -echo $ECHO_N "checking for --with-doc-strings... $ECHO_C" >&6; } +{ $as_echo "$as_me:$LINENO: checking for --with-doc-strings" >&5 +$as_echo_n "checking for --with-doc-strings... " >&6; } # Check whether --with-doc-strings was given. if test "${with_doc_strings+set}" = set; then @@ -16182,12 +16519,12 @@ _ACEOF fi -{ echo "$as_me:$LINENO: result: $with_doc_strings" >&5 -echo "${ECHO_T}$with_doc_strings" >&6; } +{ $as_echo "$as_me:$LINENO: result: $with_doc_strings" >&5 +$as_echo "$with_doc_strings" >&6; } # Check for Python-specific malloc support -{ echo "$as_me:$LINENO: checking for --with-tsc" >&5 -echo $ECHO_N "checking for --with-tsc... $ECHO_C" >&6; } +{ $as_echo "$as_me:$LINENO: checking for --with-tsc" >&5 +$as_echo_n "checking for --with-tsc... " >&6; } # Check whether --with-tsc was given. if test "${with_tsc+set}" = set; then @@ -16199,20 +16536,20 @@ #define WITH_TSC 1 _ACEOF - { echo "$as_me:$LINENO: result: yes" >&5 -echo "${ECHO_T}yes" >&6; } -else { echo "$as_me:$LINENO: result: no" >&5 -echo "${ECHO_T}no" >&6; } + { $as_echo "$as_me:$LINENO: result: yes" >&5 +$as_echo "yes" >&6; } +else { $as_echo "$as_me:$LINENO: result: no" >&5 +$as_echo "no" >&6; } fi else - { echo "$as_me:$LINENO: result: no" >&5 -echo "${ECHO_T}no" >&6; } + { $as_echo "$as_me:$LINENO: result: no" >&5 +$as_echo "no" >&6; } fi # Check for Python-specific malloc support -{ echo "$as_me:$LINENO: checking for --with-pymalloc" >&5 -echo $ECHO_N "checking for --with-pymalloc... $ECHO_C" >&6; } +{ $as_echo "$as_me:$LINENO: checking for --with-pymalloc" >&5 +$as_echo_n "checking for --with-pymalloc... " >&6; } # Check whether --with-pymalloc was given. if test "${with_pymalloc+set}" = set; then @@ -16231,12 +16568,12 @@ _ACEOF fi -{ echo "$as_me:$LINENO: result: $with_pymalloc" >&5 -echo "${ECHO_T}$with_pymalloc" >&6; } +{ $as_echo "$as_me:$LINENO: result: $with_pymalloc" >&5 +$as_echo "$with_pymalloc" >&6; } # Check for --with-wctype-functions -{ echo "$as_me:$LINENO: checking for --with-wctype-functions" >&5 -echo $ECHO_N "checking for --with-wctype-functions... $ECHO_C" >&6; } +{ $as_echo "$as_me:$LINENO: checking for --with-wctype-functions" >&5 +$as_echo_n "checking for --with-wctype-functions... " >&6; } # Check whether --with-wctype-functions was given. if test "${with_wctype_functions+set}" = set; then @@ -16248,14 +16585,14 @@ #define WANT_WCTYPE_FUNCTIONS 1 _ACEOF - { echo "$as_me:$LINENO: result: yes" >&5 -echo "${ECHO_T}yes" >&6; } -else { echo "$as_me:$LINENO: result: no" >&5 -echo "${ECHO_T}no" >&6; } + { $as_echo "$as_me:$LINENO: result: yes" >&5 +$as_echo "yes" >&6; } +else { $as_echo "$as_me:$LINENO: result: no" >&5 +$as_echo "no" >&6; } fi else - { echo "$as_me:$LINENO: result: no" >&5 -echo "${ECHO_T}no" >&6; } + { $as_echo "$as_me:$LINENO: result: no" >&5 +$as_echo "no" >&6; } fi @@ -16268,11 +16605,11 @@ for ac_func in dlopen do -as_ac_var=`echo "ac_cv_func_$ac_func" | $as_tr_sh` -{ echo "$as_me:$LINENO: checking for $ac_func" >&5 -echo $ECHO_N "checking for $ac_func... $ECHO_C" >&6; } +as_ac_var=`$as_echo "ac_cv_func_$ac_func" | $as_tr_sh` +{ $as_echo "$as_me:$LINENO: checking for $ac_func" >&5 +$as_echo_n "checking for $ac_func... " >&6; } if { as_var=$as_ac_var; eval "test \"\${$as_var+set}\" = set"; }; then - echo $ECHO_N "(cached) $ECHO_C" >&6 + $as_echo_n "(cached) " >&6 else cat >conftest.$ac_ext <<_ACEOF /* confdefs.h. */ @@ -16325,35 +16662,42 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_link") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { test -z "$ac_c_werror_flag" || test ! -s conftest.err - } && test -s conftest$ac_exeext && - $as_test_x conftest$ac_exeext; then + } && test -s conftest$ac_exeext && { + test "$cross_compiling" = yes || + $as_test_x conftest$ac_exeext + }; then eval "$as_ac_var=yes" else - echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 eval "$as_ac_var=no" fi +rm -rf conftest.dSYM rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \ conftest$ac_exeext conftest.$ac_ext fi -ac_res=`eval echo '${'$as_ac_var'}'` - { echo "$as_me:$LINENO: result: $ac_res" >&5 -echo "${ECHO_T}$ac_res" >&6; } -if test `eval echo '${'$as_ac_var'}'` = yes; then +ac_res=`eval 'as_val=${'$as_ac_var'} + $as_echo "$as_val"'` + { $as_echo "$as_me:$LINENO: result: $ac_res" >&5 +$as_echo "$ac_res" >&6; } +as_val=`eval 'as_val=${'$as_ac_var'} + $as_echo "$as_val"'` + if test "x$as_val" = x""yes; then cat >>confdefs.h <<_ACEOF -#define `echo "HAVE_$ac_func" | $as_tr_cpp` 1 +#define `$as_echo "HAVE_$ac_func" | $as_tr_cpp` 1 _ACEOF fi @@ -16363,8 +16707,8 @@ # DYNLOADFILE specifies which dynload_*.o file we will use for dynamic # loading of modules. -{ echo "$as_me:$LINENO: checking DYNLOADFILE" >&5 -echo $ECHO_N "checking DYNLOADFILE... $ECHO_C" >&6; } +{ $as_echo "$as_me:$LINENO: checking DYNLOADFILE" >&5 +$as_echo_n "checking DYNLOADFILE... " >&6; } if test -z "$DYNLOADFILE" then case $ac_sys_system/$ac_sys_release in @@ -16388,8 +16732,8 @@ ;; esac fi -{ echo "$as_me:$LINENO: result: $DYNLOADFILE" >&5 -echo "${ECHO_T}$DYNLOADFILE" >&6; } +{ $as_echo "$as_me:$LINENO: result: $DYNLOADFILE" >&5 +$as_echo "$DYNLOADFILE" >&6; } if test "$DYNLOADFILE" != "dynload_stub.o" then @@ -16402,16 +16746,16 @@ # MACHDEP_OBJS can be set to platform-specific object files needed by Python -{ echo "$as_me:$LINENO: checking MACHDEP_OBJS" >&5 -echo $ECHO_N "checking MACHDEP_OBJS... $ECHO_C" >&6; } +{ $as_echo "$as_me:$LINENO: checking MACHDEP_OBJS" >&5 +$as_echo_n "checking MACHDEP_OBJS... " >&6; } if test -z "$MACHDEP_OBJS" then MACHDEP_OBJS=$extra_machdep_objs else MACHDEP_OBJS="$MACHDEP_OBJS $extra_machdep_objs" fi -{ echo "$as_me:$LINENO: result: MACHDEP_OBJS" >&5 -echo "${ECHO_T}MACHDEP_OBJS" >&6; } +{ $as_echo "$as_me:$LINENO: result: MACHDEP_OBJS" >&5 +$as_echo "MACHDEP_OBJS" >&6; } # checks for library functions @@ -16518,11 +16862,11 @@ truncate uname unsetenv utimes waitpid wait3 wait4 \ wcscoll wcsftime wcsxfrm _getpty do -as_ac_var=`echo "ac_cv_func_$ac_func" | $as_tr_sh` -{ echo "$as_me:$LINENO: checking for $ac_func" >&5 -echo $ECHO_N "checking for $ac_func... $ECHO_C" >&6; } +as_ac_var=`$as_echo "ac_cv_func_$ac_func" | $as_tr_sh` +{ $as_echo "$as_me:$LINENO: checking for $ac_func" >&5 +$as_echo_n "checking for $ac_func... " >&6; } if { as_var=$as_ac_var; eval "test \"\${$as_var+set}\" = set"; }; then - echo $ECHO_N "(cached) $ECHO_C" >&6 + $as_echo_n "(cached) " >&6 else cat >conftest.$ac_ext <<_ACEOF /* confdefs.h. */ @@ -16575,35 +16919,42 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_link") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { test -z "$ac_c_werror_flag" || test ! -s conftest.err - } && test -s conftest$ac_exeext && - $as_test_x conftest$ac_exeext; then + } && test -s conftest$ac_exeext && { + test "$cross_compiling" = yes || + $as_test_x conftest$ac_exeext + }; then eval "$as_ac_var=yes" else - echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 eval "$as_ac_var=no" fi +rm -rf conftest.dSYM rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \ conftest$ac_exeext conftest.$ac_ext fi -ac_res=`eval echo '${'$as_ac_var'}'` - { echo "$as_me:$LINENO: result: $ac_res" >&5 -echo "${ECHO_T}$ac_res" >&6; } -if test `eval echo '${'$as_ac_var'}'` = yes; then +ac_res=`eval 'as_val=${'$as_ac_var'} + $as_echo "$as_val"'` + { $as_echo "$as_me:$LINENO: result: $ac_res" >&5 +$as_echo "$ac_res" >&6; } +as_val=`eval 'as_val=${'$as_ac_var'} + $as_echo "$as_val"'` + if test "x$as_val" = x""yes; then cat >>confdefs.h <<_ACEOF -#define `echo "HAVE_$ac_func" | $as_tr_cpp` 1 +#define `$as_echo "HAVE_$ac_func" | $as_tr_cpp` 1 _ACEOF fi @@ -16612,8 +16963,8 @@ # For some functions, having a definition is not sufficient, since # we want to take their address. -{ echo "$as_me:$LINENO: checking for chroot" >&5 -echo $ECHO_N "checking for chroot... $ECHO_C" >&6; } +{ $as_echo "$as_me:$LINENO: checking for chroot" >&5 +$as_echo_n "checking for chroot... " >&6; } cat >conftest.$ac_ext <<_ACEOF /* confdefs.h. */ _ACEOF @@ -16635,13 +16986,14 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_compile") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { test -z "$ac_c_werror_flag" || test ! -s conftest.err @@ -16651,20 +17003,20 @@ #define HAVE_CHROOT 1 _ACEOF - { echo "$as_me:$LINENO: result: yes" >&5 -echo "${ECHO_T}yes" >&6; } + { $as_echo "$as_me:$LINENO: result: yes" >&5 +$as_echo "yes" >&6; } else - echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 - { echo "$as_me:$LINENO: result: no" >&5 -echo "${ECHO_T}no" >&6; } + { $as_echo "$as_me:$LINENO: result: no" >&5 +$as_echo "no" >&6; } fi rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext -{ echo "$as_me:$LINENO: checking for link" >&5 -echo $ECHO_N "checking for link... $ECHO_C" >&6; } +{ $as_echo "$as_me:$LINENO: checking for link" >&5 +$as_echo_n "checking for link... " >&6; } cat >conftest.$ac_ext <<_ACEOF /* confdefs.h. */ _ACEOF @@ -16686,13 +17038,14 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_compile") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { test -z "$ac_c_werror_flag" || test ! -s conftest.err @@ -16702,20 +17055,20 @@ #define HAVE_LINK 1 _ACEOF - { echo "$as_me:$LINENO: result: yes" >&5 -echo "${ECHO_T}yes" >&6; } + { $as_echo "$as_me:$LINENO: result: yes" >&5 +$as_echo "yes" >&6; } else - echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 - { echo "$as_me:$LINENO: result: no" >&5 -echo "${ECHO_T}no" >&6; } + { $as_echo "$as_me:$LINENO: result: no" >&5 +$as_echo "no" >&6; } fi rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext -{ echo "$as_me:$LINENO: checking for symlink" >&5 -echo $ECHO_N "checking for symlink... $ECHO_C" >&6; } +{ $as_echo "$as_me:$LINENO: checking for symlink" >&5 +$as_echo_n "checking for symlink... " >&6; } cat >conftest.$ac_ext <<_ACEOF /* confdefs.h. */ _ACEOF @@ -16737,13 +17090,14 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_compile") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { test -z "$ac_c_werror_flag" || test ! -s conftest.err @@ -16753,20 +17107,20 @@ #define HAVE_SYMLINK 1 _ACEOF - { echo "$as_me:$LINENO: result: yes" >&5 -echo "${ECHO_T}yes" >&6; } + { $as_echo "$as_me:$LINENO: result: yes" >&5 +$as_echo "yes" >&6; } else - echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 - { echo "$as_me:$LINENO: result: no" >&5 -echo "${ECHO_T}no" >&6; } + { $as_echo "$as_me:$LINENO: result: no" >&5 +$as_echo "no" >&6; } fi rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext -{ echo "$as_me:$LINENO: checking for fchdir" >&5 -echo $ECHO_N "checking for fchdir... $ECHO_C" >&6; } +{ $as_echo "$as_me:$LINENO: checking for fchdir" >&5 +$as_echo_n "checking for fchdir... " >&6; } cat >conftest.$ac_ext <<_ACEOF /* confdefs.h. */ _ACEOF @@ -16788,13 +17142,14 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_compile") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { test -z "$ac_c_werror_flag" || test ! -s conftest.err @@ -16804,20 +17159,20 @@ #define HAVE_FCHDIR 1 _ACEOF - { echo "$as_me:$LINENO: result: yes" >&5 -echo "${ECHO_T}yes" >&6; } + { $as_echo "$as_me:$LINENO: result: yes" >&5 +$as_echo "yes" >&6; } else - echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 - { echo "$as_me:$LINENO: result: no" >&5 -echo "${ECHO_T}no" >&6; } + { $as_echo "$as_me:$LINENO: result: no" >&5 +$as_echo "no" >&6; } fi rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext -{ echo "$as_me:$LINENO: checking for fsync" >&5 -echo $ECHO_N "checking for fsync... $ECHO_C" >&6; } +{ $as_echo "$as_me:$LINENO: checking for fsync" >&5 +$as_echo_n "checking for fsync... " >&6; } cat >conftest.$ac_ext <<_ACEOF /* confdefs.h. */ _ACEOF @@ -16839,13 +17194,14 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_compile") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { test -z "$ac_c_werror_flag" || test ! -s conftest.err @@ -16855,20 +17211,20 @@ #define HAVE_FSYNC 1 _ACEOF - { echo "$as_me:$LINENO: result: yes" >&5 -echo "${ECHO_T}yes" >&6; } + { $as_echo "$as_me:$LINENO: result: yes" >&5 +$as_echo "yes" >&6; } else - echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 - { echo "$as_me:$LINENO: result: no" >&5 -echo "${ECHO_T}no" >&6; } + { $as_echo "$as_me:$LINENO: result: no" >&5 +$as_echo "no" >&6; } fi rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext -{ echo "$as_me:$LINENO: checking for fdatasync" >&5 -echo $ECHO_N "checking for fdatasync... $ECHO_C" >&6; } +{ $as_echo "$as_me:$LINENO: checking for fdatasync" >&5 +$as_echo_n "checking for fdatasync... " >&6; } cat >conftest.$ac_ext <<_ACEOF /* confdefs.h. */ _ACEOF @@ -16890,13 +17246,14 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_compile") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { test -z "$ac_c_werror_flag" || test ! -s conftest.err @@ -16906,20 +17263,20 @@ #define HAVE_FDATASYNC 1 _ACEOF - { echo "$as_me:$LINENO: result: yes" >&5 -echo "${ECHO_T}yes" >&6; } + { $as_echo "$as_me:$LINENO: result: yes" >&5 +$as_echo "yes" >&6; } else - echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 - { echo "$as_me:$LINENO: result: no" >&5 -echo "${ECHO_T}no" >&6; } + { $as_echo "$as_me:$LINENO: result: no" >&5 +$as_echo "no" >&6; } fi rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext -{ echo "$as_me:$LINENO: checking for epoll" >&5 -echo $ECHO_N "checking for epoll... $ECHO_C" >&6; } +{ $as_echo "$as_me:$LINENO: checking for epoll" >&5 +$as_echo_n "checking for epoll... " >&6; } cat >conftest.$ac_ext <<_ACEOF /* confdefs.h. */ _ACEOF @@ -16941,13 +17298,14 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_compile") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { test -z "$ac_c_werror_flag" || test ! -s conftest.err @@ -16957,20 +17315,20 @@ #define HAVE_EPOLL 1 _ACEOF - { echo "$as_me:$LINENO: result: yes" >&5 -echo "${ECHO_T}yes" >&6; } + { $as_echo "$as_me:$LINENO: result: yes" >&5 +$as_echo "yes" >&6; } else - echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 - { echo "$as_me:$LINENO: result: no" >&5 -echo "${ECHO_T}no" >&6; } + { $as_echo "$as_me:$LINENO: result: no" >&5 +$as_echo "no" >&6; } fi rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext -{ echo "$as_me:$LINENO: checking for kqueue" >&5 -echo $ECHO_N "checking for kqueue... $ECHO_C" >&6; } +{ $as_echo "$as_me:$LINENO: checking for kqueue" >&5 +$as_echo_n "checking for kqueue... " >&6; } cat >conftest.$ac_ext <<_ACEOF /* confdefs.h. */ _ACEOF @@ -16995,13 +17353,14 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_compile") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { test -z "$ac_c_werror_flag" || test ! -s conftest.err @@ -17011,14 +17370,14 @@ #define HAVE_KQUEUE 1 _ACEOF - { echo "$as_me:$LINENO: result: yes" >&5 -echo "${ECHO_T}yes" >&6; } + { $as_echo "$as_me:$LINENO: result: yes" >&5 +$as_echo "yes" >&6; } else - echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 - { echo "$as_me:$LINENO: result: no" >&5 -echo "${ECHO_T}no" >&6; } + { $as_echo "$as_me:$LINENO: result: no" >&5 +$as_echo "no" >&6; } fi @@ -17029,8 +17388,8 @@ # address to avoid compiler warnings and potential miscompilations # because of the missing prototypes. -{ echo "$as_me:$LINENO: checking for ctermid_r" >&5 -echo $ECHO_N "checking for ctermid_r... $ECHO_C" >&6; } +{ $as_echo "$as_me:$LINENO: checking for ctermid_r" >&5 +$as_echo_n "checking for ctermid_r... " >&6; } cat >conftest.$ac_ext <<_ACEOF /* confdefs.h. */ _ACEOF @@ -17055,13 +17414,14 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_compile") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { test -z "$ac_c_werror_flag" || test ! -s conftest.err @@ -17071,21 +17431,21 @@ #define HAVE_CTERMID_R 1 _ACEOF - { echo "$as_me:$LINENO: result: yes" >&5 -echo "${ECHO_T}yes" >&6; } + { $as_echo "$as_me:$LINENO: result: yes" >&5 +$as_echo "yes" >&6; } else - echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 - { echo "$as_me:$LINENO: result: no" >&5 -echo "${ECHO_T}no" >&6; } + { $as_echo "$as_me:$LINENO: result: no" >&5 +$as_echo "no" >&6; } fi rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext -{ echo "$as_me:$LINENO: checking for flock" >&5 -echo $ECHO_N "checking for flock... $ECHO_C" >&6; } +{ $as_echo "$as_me:$LINENO: checking for flock" >&5 +$as_echo_n "checking for flock... " >&6; } cat >conftest.$ac_ext <<_ACEOF /* confdefs.h. */ _ACEOF @@ -17110,13 +17470,14 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_compile") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { test -z "$ac_c_werror_flag" || test ! -s conftest.err @@ -17126,21 +17487,21 @@ #define HAVE_FLOCK 1 _ACEOF - { echo "$as_me:$LINENO: result: yes" >&5 -echo "${ECHO_T}yes" >&6; } + { $as_echo "$as_me:$LINENO: result: yes" >&5 +$as_echo "yes" >&6; } else - echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 - { echo "$as_me:$LINENO: result: no" >&5 -echo "${ECHO_T}no" >&6; } + { $as_echo "$as_me:$LINENO: result: no" >&5 +$as_echo "no" >&6; } fi rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext -{ echo "$as_me:$LINENO: checking for getpagesize" >&5 -echo $ECHO_N "checking for getpagesize... $ECHO_C" >&6; } +{ $as_echo "$as_me:$LINENO: checking for getpagesize" >&5 +$as_echo_n "checking for getpagesize... " >&6; } cat >conftest.$ac_ext <<_ACEOF /* confdefs.h. */ _ACEOF @@ -17165,13 +17526,14 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_compile") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { test -z "$ac_c_werror_flag" || test ! -s conftest.err @@ -17181,14 +17543,14 @@ #define HAVE_GETPAGESIZE 1 _ACEOF - { echo "$as_me:$LINENO: result: yes" >&5 -echo "${ECHO_T}yes" >&6; } + { $as_echo "$as_me:$LINENO: result: yes" >&5 +$as_echo "yes" >&6; } else - echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 - { echo "$as_me:$LINENO: result: no" >&5 -echo "${ECHO_T}no" >&6; } + { $as_echo "$as_me:$LINENO: result: no" >&5 +$as_echo "no" >&6; } fi @@ -17198,10 +17560,10 @@ do # Extract the first word of "$ac_prog", so it can be a program name with args. set dummy $ac_prog; ac_word=$2 -{ echo "$as_me:$LINENO: checking for $ac_word" >&5 -echo $ECHO_N "checking for $ac_word... $ECHO_C" >&6; } +{ $as_echo "$as_me:$LINENO: checking for $ac_word" >&5 +$as_echo_n "checking for $ac_word... " >&6; } if test "${ac_cv_prog_TRUE+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 + $as_echo_n "(cached) " >&6 else if test -n "$TRUE"; then ac_cv_prog_TRUE="$TRUE" # Let the user override the test. @@ -17214,7 +17576,7 @@ for ac_exec_ext in '' $ac_executable_extensions; do if { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_test_x "$as_dir/$ac_word$ac_exec_ext"; }; then ac_cv_prog_TRUE="$ac_prog" - echo "$as_me:$LINENO: found $as_dir/$ac_word$ac_exec_ext" >&5 + $as_echo "$as_me:$LINENO: found $as_dir/$ac_word$ac_exec_ext" >&5 break 2 fi done @@ -17225,11 +17587,11 @@ fi TRUE=$ac_cv_prog_TRUE if test -n "$TRUE"; then - { echo "$as_me:$LINENO: result: $TRUE" >&5 -echo "${ECHO_T}$TRUE" >&6; } + { $as_echo "$as_me:$LINENO: result: $TRUE" >&5 +$as_echo "$TRUE" >&6; } else - { echo "$as_me:$LINENO: result: no" >&5 -echo "${ECHO_T}no" >&6; } + { $as_echo "$as_me:$LINENO: result: no" >&5 +$as_echo "no" >&6; } fi @@ -17238,10 +17600,10 @@ test -n "$TRUE" || TRUE="/bin/true" -{ echo "$as_me:$LINENO: checking for inet_aton in -lc" >&5 -echo $ECHO_N "checking for inet_aton in -lc... $ECHO_C" >&6; } +{ $as_echo "$as_me:$LINENO: checking for inet_aton in -lc" >&5 +$as_echo_n "checking for inet_aton in -lc... " >&6; } if test "${ac_cv_lib_c_inet_aton+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 + $as_echo_n "(cached) " >&6 else ac_check_lib_save_LIBS=$LIBS LIBS="-lc $LIBS" @@ -17273,40 +17635,44 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_link") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { test -z "$ac_c_werror_flag" || test ! -s conftest.err - } && test -s conftest$ac_exeext && - $as_test_x conftest$ac_exeext; then + } && test -s conftest$ac_exeext && { + test "$cross_compiling" = yes || + $as_test_x conftest$ac_exeext + }; then ac_cv_lib_c_inet_aton=yes else - echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 ac_cv_lib_c_inet_aton=no fi +rm -rf conftest.dSYM rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \ conftest$ac_exeext conftest.$ac_ext LIBS=$ac_check_lib_save_LIBS fi -{ echo "$as_me:$LINENO: result: $ac_cv_lib_c_inet_aton" >&5 -echo "${ECHO_T}$ac_cv_lib_c_inet_aton" >&6; } -if test $ac_cv_lib_c_inet_aton = yes; then +{ $as_echo "$as_me:$LINENO: result: $ac_cv_lib_c_inet_aton" >&5 +$as_echo "$ac_cv_lib_c_inet_aton" >&6; } +if test "x$ac_cv_lib_c_inet_aton" = x""yes; then $ac_cv_prog_TRUE else -{ echo "$as_me:$LINENO: checking for inet_aton in -lresolv" >&5 -echo $ECHO_N "checking for inet_aton in -lresolv... $ECHO_C" >&6; } +{ $as_echo "$as_me:$LINENO: checking for inet_aton in -lresolv" >&5 +$as_echo_n "checking for inet_aton in -lresolv... " >&6; } if test "${ac_cv_lib_resolv_inet_aton+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 + $as_echo_n "(cached) " >&6 else ac_check_lib_save_LIBS=$LIBS LIBS="-lresolv $LIBS" @@ -17338,33 +17704,37 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_link") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { test -z "$ac_c_werror_flag" || test ! -s conftest.err - } && test -s conftest$ac_exeext && - $as_test_x conftest$ac_exeext; then + } && test -s conftest$ac_exeext && { + test "$cross_compiling" = yes || + $as_test_x conftest$ac_exeext + }; then ac_cv_lib_resolv_inet_aton=yes else - echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 ac_cv_lib_resolv_inet_aton=no fi +rm -rf conftest.dSYM rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \ conftest$ac_exeext conftest.$ac_ext LIBS=$ac_check_lib_save_LIBS fi -{ echo "$as_me:$LINENO: result: $ac_cv_lib_resolv_inet_aton" >&5 -echo "${ECHO_T}$ac_cv_lib_resolv_inet_aton" >&6; } -if test $ac_cv_lib_resolv_inet_aton = yes; then +{ $as_echo "$as_me:$LINENO: result: $ac_cv_lib_resolv_inet_aton" >&5 +$as_echo "$ac_cv_lib_resolv_inet_aton" >&6; } +if test "x$ac_cv_lib_resolv_inet_aton" = x""yes; then cat >>confdefs.h <<_ACEOF #define HAVE_LIBRESOLV 1 _ACEOF @@ -17379,10 +17749,10 @@ # On Tru64, chflags seems to be present, but calling it will # exit Python -{ echo "$as_me:$LINENO: checking for chflags" >&5 -echo $ECHO_N "checking for chflags... $ECHO_C" >&6; } +{ $as_echo "$as_me:$LINENO: checking for chflags" >&5 +$as_echo_n "checking for chflags... " >&6; } if test "${ac_cv_have_chflags+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 + $as_echo_n "(cached) " >&6 else if test "$cross_compiling" = yes; then ac_cv_have_chflags=cross @@ -17410,42 +17780,45 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_link") 2>&5 ac_status=$? - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { ac_try='./conftest$ac_exeext' { (case "(($ac_try" in *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_try") 2>&5 ac_status=$? - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); }; }; then ac_cv_have_chflags=yes else - echo "$as_me: program exited with status $ac_status" >&5 -echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: program exited with status $ac_status" >&5 +$as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 ( exit $ac_status ) ac_cv_have_chflags=no fi +rm -rf conftest.dSYM rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext conftest.$ac_objext conftest.$ac_ext fi fi -{ echo "$as_me:$LINENO: result: $ac_cv_have_chflags" >&5 -echo "${ECHO_T}$ac_cv_have_chflags" >&6; } +{ $as_echo "$as_me:$LINENO: result: $ac_cv_have_chflags" >&5 +$as_echo "$ac_cv_have_chflags" >&6; } if test "$ac_cv_have_chflags" = cross ; then - { echo "$as_me:$LINENO: checking for chflags" >&5 -echo $ECHO_N "checking for chflags... $ECHO_C" >&6; } + { $as_echo "$as_me:$LINENO: checking for chflags" >&5 +$as_echo_n "checking for chflags... " >&6; } if test "${ac_cv_func_chflags+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 + $as_echo_n "(cached) " >&6 else cat >conftest.$ac_ext <<_ACEOF /* confdefs.h. */ @@ -17498,32 +17871,36 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_link") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { test -z "$ac_c_werror_flag" || test ! -s conftest.err - } && test -s conftest$ac_exeext && - $as_test_x conftest$ac_exeext; then + } && test -s conftest$ac_exeext && { + test "$cross_compiling" = yes || + $as_test_x conftest$ac_exeext + }; then ac_cv_func_chflags=yes else - echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 ac_cv_func_chflags=no fi +rm -rf conftest.dSYM rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \ conftest$ac_exeext conftest.$ac_ext fi -{ echo "$as_me:$LINENO: result: $ac_cv_func_chflags" >&5 -echo "${ECHO_T}$ac_cv_func_chflags" >&6; } -if test $ac_cv_func_chflags = yes; then +{ $as_echo "$as_me:$LINENO: result: $ac_cv_func_chflags" >&5 +$as_echo "$ac_cv_func_chflags" >&6; } +if test "x$ac_cv_func_chflags" = x""yes; then ac_cv_have_chflags="yes" else ac_cv_have_chflags="no" @@ -17538,10 +17915,10 @@ fi -{ echo "$as_me:$LINENO: checking for lchflags" >&5 -echo $ECHO_N "checking for lchflags... $ECHO_C" >&6; } +{ $as_echo "$as_me:$LINENO: checking for lchflags" >&5 +$as_echo_n "checking for lchflags... " >&6; } if test "${ac_cv_have_lchflags+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 + $as_echo_n "(cached) " >&6 else if test "$cross_compiling" = yes; then ac_cv_have_lchflags=cross @@ -17569,42 +17946,45 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_link") 2>&5 ac_status=$? - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { ac_try='./conftest$ac_exeext' { (case "(($ac_try" in *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_try") 2>&5 ac_status=$? - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); }; }; then ac_cv_have_lchflags=yes else - echo "$as_me: program exited with status $ac_status" >&5 -echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: program exited with status $ac_status" >&5 +$as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 ( exit $ac_status ) ac_cv_have_lchflags=no fi +rm -rf conftest.dSYM rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext conftest.$ac_objext conftest.$ac_ext fi fi -{ echo "$as_me:$LINENO: result: $ac_cv_have_lchflags" >&5 -echo "${ECHO_T}$ac_cv_have_lchflags" >&6; } +{ $as_echo "$as_me:$LINENO: result: $ac_cv_have_lchflags" >&5 +$as_echo "$ac_cv_have_lchflags" >&6; } if test "$ac_cv_have_lchflags" = cross ; then - { echo "$as_me:$LINENO: checking for lchflags" >&5 -echo $ECHO_N "checking for lchflags... $ECHO_C" >&6; } + { $as_echo "$as_me:$LINENO: checking for lchflags" >&5 +$as_echo_n "checking for lchflags... " >&6; } if test "${ac_cv_func_lchflags+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 + $as_echo_n "(cached) " >&6 else cat >conftest.$ac_ext <<_ACEOF /* confdefs.h. */ @@ -17657,32 +18037,36 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_link") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { test -z "$ac_c_werror_flag" || test ! -s conftest.err - } && test -s conftest$ac_exeext && - $as_test_x conftest$ac_exeext; then + } && test -s conftest$ac_exeext && { + test "$cross_compiling" = yes || + $as_test_x conftest$ac_exeext + }; then ac_cv_func_lchflags=yes else - echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 ac_cv_func_lchflags=no fi +rm -rf conftest.dSYM rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \ conftest$ac_exeext conftest.$ac_ext fi -{ echo "$as_me:$LINENO: result: $ac_cv_func_lchflags" >&5 -echo "${ECHO_T}$ac_cv_func_lchflags" >&6; } -if test $ac_cv_func_lchflags = yes; then +{ $as_echo "$as_me:$LINENO: result: $ac_cv_func_lchflags" >&5 +$as_echo "$ac_cv_func_lchflags" >&6; } +if test "x$ac_cv_func_lchflags" = x""yes; then ac_cv_have_lchflags="yes" else ac_cv_have_lchflags="no" @@ -17706,10 +18090,10 @@ ;; esac -{ echo "$as_me:$LINENO: checking for inflateCopy in -lz" >&5 -echo $ECHO_N "checking for inflateCopy in -lz... $ECHO_C" >&6; } +{ $as_echo "$as_me:$LINENO: checking for inflateCopy in -lz" >&5 +$as_echo_n "checking for inflateCopy in -lz... " >&6; } if test "${ac_cv_lib_z_inflateCopy+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 + $as_echo_n "(cached) " >&6 else ac_check_lib_save_LIBS=$LIBS LIBS="-lz $LIBS" @@ -17741,33 +18125,37 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_link") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { test -z "$ac_c_werror_flag" || test ! -s conftest.err - } && test -s conftest$ac_exeext && - $as_test_x conftest$ac_exeext; then + } && test -s conftest$ac_exeext && { + test "$cross_compiling" = yes || + $as_test_x conftest$ac_exeext + }; then ac_cv_lib_z_inflateCopy=yes else - echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 ac_cv_lib_z_inflateCopy=no fi +rm -rf conftest.dSYM rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \ conftest$ac_exeext conftest.$ac_ext LIBS=$ac_check_lib_save_LIBS fi -{ echo "$as_me:$LINENO: result: $ac_cv_lib_z_inflateCopy" >&5 -echo "${ECHO_T}$ac_cv_lib_z_inflateCopy" >&6; } -if test $ac_cv_lib_z_inflateCopy = yes; then +{ $as_echo "$as_me:$LINENO: result: $ac_cv_lib_z_inflateCopy" >&5 +$as_echo "$ac_cv_lib_z_inflateCopy" >&6; } +if test "x$ac_cv_lib_z_inflateCopy" = x""yes; then cat >>confdefs.h <<\_ACEOF #define HAVE_ZLIB_COPY 1 @@ -17783,8 +18171,8 @@ ;; esac -{ echo "$as_me:$LINENO: checking for hstrerror" >&5 -echo $ECHO_N "checking for hstrerror... $ECHO_C" >&6; } +{ $as_echo "$as_me:$LINENO: checking for hstrerror" >&5 +$as_echo_n "checking for hstrerror... " >&6; } cat >conftest.$ac_ext <<_ACEOF /* confdefs.h. */ _ACEOF @@ -17809,39 +18197,43 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_link") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { test -z "$ac_c_werror_flag" || test ! -s conftest.err - } && test -s conftest$ac_exeext && - $as_test_x conftest$ac_exeext; then + } && test -s conftest$ac_exeext && { + test "$cross_compiling" = yes || + $as_test_x conftest$ac_exeext + }; then cat >>confdefs.h <<\_ACEOF #define HAVE_HSTRERROR 1 _ACEOF - { echo "$as_me:$LINENO: result: yes" >&5 -echo "${ECHO_T}yes" >&6; } + { $as_echo "$as_me:$LINENO: result: yes" >&5 +$as_echo "yes" >&6; } else - echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 - { echo "$as_me:$LINENO: result: no" >&5 -echo "${ECHO_T}no" >&6; } + { $as_echo "$as_me:$LINENO: result: no" >&5 +$as_echo "no" >&6; } fi +rm -rf conftest.dSYM rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \ conftest$ac_exeext conftest.$ac_ext -{ echo "$as_me:$LINENO: checking for inet_aton" >&5 -echo $ECHO_N "checking for inet_aton... $ECHO_C" >&6; } +{ $as_echo "$as_me:$LINENO: checking for inet_aton" >&5 +$as_echo_n "checking for inet_aton... " >&6; } cat >conftest.$ac_ext <<_ACEOF /* confdefs.h. */ _ACEOF @@ -17869,39 +18261,43 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_link") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { test -z "$ac_c_werror_flag" || test ! -s conftest.err - } && test -s conftest$ac_exeext && - $as_test_x conftest$ac_exeext; then + } && test -s conftest$ac_exeext && { + test "$cross_compiling" = yes || + $as_test_x conftest$ac_exeext + }; then cat >>confdefs.h <<\_ACEOF #define HAVE_INET_ATON 1 _ACEOF - { echo "$as_me:$LINENO: result: yes" >&5 -echo "${ECHO_T}yes" >&6; } + { $as_echo "$as_me:$LINENO: result: yes" >&5 +$as_echo "yes" >&6; } else - echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 - { echo "$as_me:$LINENO: result: no" >&5 -echo "${ECHO_T}no" >&6; } + { $as_echo "$as_me:$LINENO: result: no" >&5 +$as_echo "no" >&6; } fi +rm -rf conftest.dSYM rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \ conftest$ac_exeext conftest.$ac_ext -{ echo "$as_me:$LINENO: checking for inet_pton" >&5 -echo $ECHO_N "checking for inet_pton... $ECHO_C" >&6; } +{ $as_echo "$as_me:$LINENO: checking for inet_pton" >&5 +$as_echo_n "checking for inet_pton... " >&6; } cat >conftest.$ac_ext <<_ACEOF /* confdefs.h. */ _ACEOF @@ -17929,13 +18325,14 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_compile") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { test -z "$ac_c_werror_flag" || test ! -s conftest.err @@ -17945,22 +18342,22 @@ #define HAVE_INET_PTON 1 _ACEOF - { echo "$as_me:$LINENO: result: yes" >&5 -echo "${ECHO_T}yes" >&6; } + { $as_echo "$as_me:$LINENO: result: yes" >&5 +$as_echo "yes" >&6; } else - echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 - { echo "$as_me:$LINENO: result: no" >&5 -echo "${ECHO_T}no" >&6; } + { $as_echo "$as_me:$LINENO: result: no" >&5 +$as_echo "no" >&6; } fi rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext # On some systems, setgroups is in unistd.h, on others, in grp.h -{ echo "$as_me:$LINENO: checking for setgroups" >&5 -echo $ECHO_N "checking for setgroups... $ECHO_C" >&6; } +{ $as_echo "$as_me:$LINENO: checking for setgroups" >&5 +$as_echo_n "checking for setgroups... " >&6; } cat >conftest.$ac_ext <<_ACEOF /* confdefs.h. */ _ACEOF @@ -17988,13 +18385,14 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_compile") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { test -z "$ac_c_werror_flag" || test ! -s conftest.err @@ -18004,14 +18402,14 @@ #define HAVE_SETGROUPS 1 _ACEOF - { echo "$as_me:$LINENO: result: yes" >&5 -echo "${ECHO_T}yes" >&6; } + { $as_echo "$as_me:$LINENO: result: yes" >&5 +$as_echo "yes" >&6; } else - echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 - { echo "$as_me:$LINENO: result: no" >&5 -echo "${ECHO_T}no" >&6; } + { $as_echo "$as_me:$LINENO: result: no" >&5 +$as_echo "no" >&6; } fi @@ -18022,11 +18420,11 @@ for ac_func in openpty do -as_ac_var=`echo "ac_cv_func_$ac_func" | $as_tr_sh` -{ echo "$as_me:$LINENO: checking for $ac_func" >&5 -echo $ECHO_N "checking for $ac_func... $ECHO_C" >&6; } +as_ac_var=`$as_echo "ac_cv_func_$ac_func" | $as_tr_sh` +{ $as_echo "$as_me:$LINENO: checking for $ac_func" >&5 +$as_echo_n "checking for $ac_func... " >&6; } if { as_var=$as_ac_var; eval "test \"\${$as_var+set}\" = set"; }; then - echo $ECHO_N "(cached) $ECHO_C" >&6 + $as_echo_n "(cached) " >&6 else cat >conftest.$ac_ext <<_ACEOF /* confdefs.h. */ @@ -18079,42 +18477,49 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_link") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { test -z "$ac_c_werror_flag" || test ! -s conftest.err - } && test -s conftest$ac_exeext && - $as_test_x conftest$ac_exeext; then + } && test -s conftest$ac_exeext && { + test "$cross_compiling" = yes || + $as_test_x conftest$ac_exeext + }; then eval "$as_ac_var=yes" else - echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 eval "$as_ac_var=no" fi +rm -rf conftest.dSYM rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \ conftest$ac_exeext conftest.$ac_ext fi -ac_res=`eval echo '${'$as_ac_var'}'` - { echo "$as_me:$LINENO: result: $ac_res" >&5 -echo "${ECHO_T}$ac_res" >&6; } -if test `eval echo '${'$as_ac_var'}'` = yes; then +ac_res=`eval 'as_val=${'$as_ac_var'} + $as_echo "$as_val"'` + { $as_echo "$as_me:$LINENO: result: $ac_res" >&5 +$as_echo "$ac_res" >&6; } +as_val=`eval 'as_val=${'$as_ac_var'} + $as_echo "$as_val"'` + if test "x$as_val" = x""yes; then cat >>confdefs.h <<_ACEOF -#define `echo "HAVE_$ac_func" | $as_tr_cpp` 1 +#define `$as_echo "HAVE_$ac_func" | $as_tr_cpp` 1 _ACEOF else - { echo "$as_me:$LINENO: checking for openpty in -lutil" >&5 -echo $ECHO_N "checking for openpty in -lutil... $ECHO_C" >&6; } + { $as_echo "$as_me:$LINENO: checking for openpty in -lutil" >&5 +$as_echo_n "checking for openpty in -lutil... " >&6; } if test "${ac_cv_lib_util_openpty+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 + $as_echo_n "(cached) " >&6 else ac_check_lib_save_LIBS=$LIBS LIBS="-lutil $LIBS" @@ -18146,42 +18551,46 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_link") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { test -z "$ac_c_werror_flag" || test ! -s conftest.err - } && test -s conftest$ac_exeext && - $as_test_x conftest$ac_exeext; then + } && test -s conftest$ac_exeext && { + test "$cross_compiling" = yes || + $as_test_x conftest$ac_exeext + }; then ac_cv_lib_util_openpty=yes else - echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 ac_cv_lib_util_openpty=no fi +rm -rf conftest.dSYM rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \ conftest$ac_exeext conftest.$ac_ext LIBS=$ac_check_lib_save_LIBS fi -{ echo "$as_me:$LINENO: result: $ac_cv_lib_util_openpty" >&5 -echo "${ECHO_T}$ac_cv_lib_util_openpty" >&6; } -if test $ac_cv_lib_util_openpty = yes; then +{ $as_echo "$as_me:$LINENO: result: $ac_cv_lib_util_openpty" >&5 +$as_echo "$ac_cv_lib_util_openpty" >&6; } +if test "x$ac_cv_lib_util_openpty" = x""yes; then cat >>confdefs.h <<\_ACEOF #define HAVE_OPENPTY 1 _ACEOF LIBS="$LIBS -lutil" else - { echo "$as_me:$LINENO: checking for openpty in -lbsd" >&5 -echo $ECHO_N "checking for openpty in -lbsd... $ECHO_C" >&6; } + { $as_echo "$as_me:$LINENO: checking for openpty in -lbsd" >&5 +$as_echo_n "checking for openpty in -lbsd... " >&6; } if test "${ac_cv_lib_bsd_openpty+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 + $as_echo_n "(cached) " >&6 else ac_check_lib_save_LIBS=$LIBS LIBS="-lbsd $LIBS" @@ -18213,33 +18622,37 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_link") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { test -z "$ac_c_werror_flag" || test ! -s conftest.err - } && test -s conftest$ac_exeext && - $as_test_x conftest$ac_exeext; then + } && test -s conftest$ac_exeext && { + test "$cross_compiling" = yes || + $as_test_x conftest$ac_exeext + }; then ac_cv_lib_bsd_openpty=yes else - echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 ac_cv_lib_bsd_openpty=no fi +rm -rf conftest.dSYM rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \ conftest$ac_exeext conftest.$ac_ext LIBS=$ac_check_lib_save_LIBS fi -{ echo "$as_me:$LINENO: result: $ac_cv_lib_bsd_openpty" >&5 -echo "${ECHO_T}$ac_cv_lib_bsd_openpty" >&6; } -if test $ac_cv_lib_bsd_openpty = yes; then +{ $as_echo "$as_me:$LINENO: result: $ac_cv_lib_bsd_openpty" >&5 +$as_echo "$ac_cv_lib_bsd_openpty" >&6; } +if test "x$ac_cv_lib_bsd_openpty" = x""yes; then cat >>confdefs.h <<\_ACEOF #define HAVE_OPENPTY 1 _ACEOF @@ -18256,11 +18669,11 @@ for ac_func in forkpty do -as_ac_var=`echo "ac_cv_func_$ac_func" | $as_tr_sh` -{ echo "$as_me:$LINENO: checking for $ac_func" >&5 -echo $ECHO_N "checking for $ac_func... $ECHO_C" >&6; } +as_ac_var=`$as_echo "ac_cv_func_$ac_func" | $as_tr_sh` +{ $as_echo "$as_me:$LINENO: checking for $ac_func" >&5 +$as_echo_n "checking for $ac_func... " >&6; } if { as_var=$as_ac_var; eval "test \"\${$as_var+set}\" = set"; }; then - echo $ECHO_N "(cached) $ECHO_C" >&6 + $as_echo_n "(cached) " >&6 else cat >conftest.$ac_ext <<_ACEOF /* confdefs.h. */ @@ -18313,42 +18726,49 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_link") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { test -z "$ac_c_werror_flag" || test ! -s conftest.err - } && test -s conftest$ac_exeext && - $as_test_x conftest$ac_exeext; then + } && test -s conftest$ac_exeext && { + test "$cross_compiling" = yes || + $as_test_x conftest$ac_exeext + }; then eval "$as_ac_var=yes" else - echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 eval "$as_ac_var=no" fi +rm -rf conftest.dSYM rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \ conftest$ac_exeext conftest.$ac_ext fi -ac_res=`eval echo '${'$as_ac_var'}'` - { echo "$as_me:$LINENO: result: $ac_res" >&5 -echo "${ECHO_T}$ac_res" >&6; } -if test `eval echo '${'$as_ac_var'}'` = yes; then +ac_res=`eval 'as_val=${'$as_ac_var'} + $as_echo "$as_val"'` + { $as_echo "$as_me:$LINENO: result: $ac_res" >&5 +$as_echo "$ac_res" >&6; } +as_val=`eval 'as_val=${'$as_ac_var'} + $as_echo "$as_val"'` + if test "x$as_val" = x""yes; then cat >>confdefs.h <<_ACEOF -#define `echo "HAVE_$ac_func" | $as_tr_cpp` 1 +#define `$as_echo "HAVE_$ac_func" | $as_tr_cpp` 1 _ACEOF else - { echo "$as_me:$LINENO: checking for forkpty in -lutil" >&5 -echo $ECHO_N "checking for forkpty in -lutil... $ECHO_C" >&6; } + { $as_echo "$as_me:$LINENO: checking for forkpty in -lutil" >&5 +$as_echo_n "checking for forkpty in -lutil... " >&6; } if test "${ac_cv_lib_util_forkpty+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 + $as_echo_n "(cached) " >&6 else ac_check_lib_save_LIBS=$LIBS LIBS="-lutil $LIBS" @@ -18380,42 +18800,46 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_link") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { test -z "$ac_c_werror_flag" || test ! -s conftest.err - } && test -s conftest$ac_exeext && - $as_test_x conftest$ac_exeext; then + } && test -s conftest$ac_exeext && { + test "$cross_compiling" = yes || + $as_test_x conftest$ac_exeext + }; then ac_cv_lib_util_forkpty=yes else - echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 ac_cv_lib_util_forkpty=no fi +rm -rf conftest.dSYM rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \ conftest$ac_exeext conftest.$ac_ext LIBS=$ac_check_lib_save_LIBS fi -{ echo "$as_me:$LINENO: result: $ac_cv_lib_util_forkpty" >&5 -echo "${ECHO_T}$ac_cv_lib_util_forkpty" >&6; } -if test $ac_cv_lib_util_forkpty = yes; then +{ $as_echo "$as_me:$LINENO: result: $ac_cv_lib_util_forkpty" >&5 +$as_echo "$ac_cv_lib_util_forkpty" >&6; } +if test "x$ac_cv_lib_util_forkpty" = x""yes; then cat >>confdefs.h <<\_ACEOF #define HAVE_FORKPTY 1 _ACEOF LIBS="$LIBS -lutil" else - { echo "$as_me:$LINENO: checking for forkpty in -lbsd" >&5 -echo $ECHO_N "checking for forkpty in -lbsd... $ECHO_C" >&6; } + { $as_echo "$as_me:$LINENO: checking for forkpty in -lbsd" >&5 +$as_echo_n "checking for forkpty in -lbsd... " >&6; } if test "${ac_cv_lib_bsd_forkpty+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 + $as_echo_n "(cached) " >&6 else ac_check_lib_save_LIBS=$LIBS LIBS="-lbsd $LIBS" @@ -18447,33 +18871,37 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_link") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { test -z "$ac_c_werror_flag" || test ! -s conftest.err - } && test -s conftest$ac_exeext && - $as_test_x conftest$ac_exeext; then + } && test -s conftest$ac_exeext && { + test "$cross_compiling" = yes || + $as_test_x conftest$ac_exeext + }; then ac_cv_lib_bsd_forkpty=yes else - echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 ac_cv_lib_bsd_forkpty=no fi +rm -rf conftest.dSYM rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \ conftest$ac_exeext conftest.$ac_ext LIBS=$ac_check_lib_save_LIBS fi -{ echo "$as_me:$LINENO: result: $ac_cv_lib_bsd_forkpty" >&5 -echo "${ECHO_T}$ac_cv_lib_bsd_forkpty" >&6; } -if test $ac_cv_lib_bsd_forkpty = yes; then +{ $as_echo "$as_me:$LINENO: result: $ac_cv_lib_bsd_forkpty" >&5 +$as_echo "$ac_cv_lib_bsd_forkpty" >&6; } +if test "x$ac_cv_lib_bsd_forkpty" = x""yes; then cat >>confdefs.h <<\_ACEOF #define HAVE_FORKPTY 1 _ACEOF @@ -18492,11 +18920,11 @@ for ac_func in memmove do -as_ac_var=`echo "ac_cv_func_$ac_func" | $as_tr_sh` -{ echo "$as_me:$LINENO: checking for $ac_func" >&5 -echo $ECHO_N "checking for $ac_func... $ECHO_C" >&6; } +as_ac_var=`$as_echo "ac_cv_func_$ac_func" | $as_tr_sh` +{ $as_echo "$as_me:$LINENO: checking for $ac_func" >&5 +$as_echo_n "checking for $ac_func... " >&6; } if { as_var=$as_ac_var; eval "test \"\${$as_var+set}\" = set"; }; then - echo $ECHO_N "(cached) $ECHO_C" >&6 + $as_echo_n "(cached) " >&6 else cat >conftest.$ac_ext <<_ACEOF /* confdefs.h. */ @@ -18549,35 +18977,42 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_link") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { test -z "$ac_c_werror_flag" || test ! -s conftest.err - } && test -s conftest$ac_exeext && - $as_test_x conftest$ac_exeext; then + } && test -s conftest$ac_exeext && { + test "$cross_compiling" = yes || + $as_test_x conftest$ac_exeext + }; then eval "$as_ac_var=yes" else - echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 eval "$as_ac_var=no" fi +rm -rf conftest.dSYM rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \ conftest$ac_exeext conftest.$ac_ext fi -ac_res=`eval echo '${'$as_ac_var'}'` - { echo "$as_me:$LINENO: result: $ac_res" >&5 -echo "${ECHO_T}$ac_res" >&6; } -if test `eval echo '${'$as_ac_var'}'` = yes; then +ac_res=`eval 'as_val=${'$as_ac_var'} + $as_echo "$as_val"'` + { $as_echo "$as_me:$LINENO: result: $ac_res" >&5 +$as_echo "$ac_res" >&6; } +as_val=`eval 'as_val=${'$as_ac_var'} + $as_echo "$as_val"'` + if test "x$as_val" = x""yes; then cat >>confdefs.h <<_ACEOF -#define `echo "HAVE_$ac_func" | $as_tr_cpp` 1 +#define `$as_echo "HAVE_$ac_func" | $as_tr_cpp` 1 _ACEOF fi @@ -18593,11 +19028,11 @@ for ac_func in fseek64 fseeko fstatvfs ftell64 ftello statvfs do -as_ac_var=`echo "ac_cv_func_$ac_func" | $as_tr_sh` -{ echo "$as_me:$LINENO: checking for $ac_func" >&5 -echo $ECHO_N "checking for $ac_func... $ECHO_C" >&6; } +as_ac_var=`$as_echo "ac_cv_func_$ac_func" | $as_tr_sh` +{ $as_echo "$as_me:$LINENO: checking for $ac_func" >&5 +$as_echo_n "checking for $ac_func... " >&6; } if { as_var=$as_ac_var; eval "test \"\${$as_var+set}\" = set"; }; then - echo $ECHO_N "(cached) $ECHO_C" >&6 + $as_echo_n "(cached) " >&6 else cat >conftest.$ac_ext <<_ACEOF /* confdefs.h. */ @@ -18650,35 +19085,42 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_link") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { test -z "$ac_c_werror_flag" || test ! -s conftest.err - } && test -s conftest$ac_exeext && - $as_test_x conftest$ac_exeext; then + } && test -s conftest$ac_exeext && { + test "$cross_compiling" = yes || + $as_test_x conftest$ac_exeext + }; then eval "$as_ac_var=yes" else - echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 eval "$as_ac_var=no" fi +rm -rf conftest.dSYM rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \ conftest$ac_exeext conftest.$ac_ext fi -ac_res=`eval echo '${'$as_ac_var'}'` - { echo "$as_me:$LINENO: result: $ac_res" >&5 -echo "${ECHO_T}$ac_res" >&6; } -if test `eval echo '${'$as_ac_var'}'` = yes; then +ac_res=`eval 'as_val=${'$as_ac_var'} + $as_echo "$as_val"'` + { $as_echo "$as_me:$LINENO: result: $ac_res" >&5 +$as_echo "$ac_res" >&6; } +as_val=`eval 'as_val=${'$as_ac_var'} + $as_echo "$as_val"'` + if test "x$as_val" = x""yes; then cat >>confdefs.h <<_ACEOF -#define `echo "HAVE_$ac_func" | $as_tr_cpp` 1 +#define `$as_echo "HAVE_$ac_func" | $as_tr_cpp` 1 _ACEOF fi @@ -18690,11 +19132,11 @@ for ac_func in dup2 getcwd strdup do -as_ac_var=`echo "ac_cv_func_$ac_func" | $as_tr_sh` -{ echo "$as_me:$LINENO: checking for $ac_func" >&5 -echo $ECHO_N "checking for $ac_func... $ECHO_C" >&6; } +as_ac_var=`$as_echo "ac_cv_func_$ac_func" | $as_tr_sh` +{ $as_echo "$as_me:$LINENO: checking for $ac_func" >&5 +$as_echo_n "checking for $ac_func... " >&6; } if { as_var=$as_ac_var; eval "test \"\${$as_var+set}\" = set"; }; then - echo $ECHO_N "(cached) $ECHO_C" >&6 + $as_echo_n "(cached) " >&6 else cat >conftest.$ac_ext <<_ACEOF /* confdefs.h. */ @@ -18747,35 +19189,42 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_link") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { test -z "$ac_c_werror_flag" || test ! -s conftest.err - } && test -s conftest$ac_exeext && - $as_test_x conftest$ac_exeext; then + } && test -s conftest$ac_exeext && { + test "$cross_compiling" = yes || + $as_test_x conftest$ac_exeext + }; then eval "$as_ac_var=yes" else - echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 eval "$as_ac_var=no" fi +rm -rf conftest.dSYM rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \ conftest$ac_exeext conftest.$ac_ext fi -ac_res=`eval echo '${'$as_ac_var'}'` - { echo "$as_me:$LINENO: result: $ac_res" >&5 -echo "${ECHO_T}$ac_res" >&6; } -if test `eval echo '${'$as_ac_var'}'` = yes; then +ac_res=`eval 'as_val=${'$as_ac_var'} + $as_echo "$as_val"'` + { $as_echo "$as_me:$LINENO: result: $ac_res" >&5 +$as_echo "$ac_res" >&6; } +as_val=`eval 'as_val=${'$as_ac_var'} + $as_echo "$as_val"'` + if test "x$as_val" = x""yes; then cat >>confdefs.h <<_ACEOF -#define `echo "HAVE_$ac_func" | $as_tr_cpp` 1 +#define `$as_echo "HAVE_$ac_func" | $as_tr_cpp` 1 _ACEOF else @@ -18792,11 +19241,11 @@ for ac_func in getpgrp do -as_ac_var=`echo "ac_cv_func_$ac_func" | $as_tr_sh` -{ echo "$as_me:$LINENO: checking for $ac_func" >&5 -echo $ECHO_N "checking for $ac_func... $ECHO_C" >&6; } +as_ac_var=`$as_echo "ac_cv_func_$ac_func" | $as_tr_sh` +{ $as_echo "$as_me:$LINENO: checking for $ac_func" >&5 +$as_echo_n "checking for $ac_func... " >&6; } if { as_var=$as_ac_var; eval "test \"\${$as_var+set}\" = set"; }; then - echo $ECHO_N "(cached) $ECHO_C" >&6 + $as_echo_n "(cached) " >&6 else cat >conftest.$ac_ext <<_ACEOF /* confdefs.h. */ @@ -18849,35 +19298,42 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_link") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { test -z "$ac_c_werror_flag" || test ! -s conftest.err - } && test -s conftest$ac_exeext && - $as_test_x conftest$ac_exeext; then + } && test -s conftest$ac_exeext && { + test "$cross_compiling" = yes || + $as_test_x conftest$ac_exeext + }; then eval "$as_ac_var=yes" else - echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 eval "$as_ac_var=no" fi +rm -rf conftest.dSYM rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \ conftest$ac_exeext conftest.$ac_ext fi -ac_res=`eval echo '${'$as_ac_var'}'` - { echo "$as_me:$LINENO: result: $ac_res" >&5 -echo "${ECHO_T}$ac_res" >&6; } -if test `eval echo '${'$as_ac_var'}'` = yes; then +ac_res=`eval 'as_val=${'$as_ac_var'} + $as_echo "$as_val"'` + { $as_echo "$as_me:$LINENO: result: $ac_res" >&5 +$as_echo "$ac_res" >&6; } +as_val=`eval 'as_val=${'$as_ac_var'} + $as_echo "$as_val"'` + if test "x$as_val" = x""yes; then cat >>confdefs.h <<_ACEOF -#define `echo "HAVE_$ac_func" | $as_tr_cpp` 1 +#define `$as_echo "HAVE_$ac_func" | $as_tr_cpp` 1 _ACEOF cat >conftest.$ac_ext <<_ACEOF /* confdefs.h. */ @@ -18900,13 +19356,14 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_compile") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { test -z "$ac_c_werror_flag" || test ! -s conftest.err @@ -18918,7 +19375,7 @@ else - echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 @@ -18932,11 +19389,11 @@ for ac_func in setpgrp do -as_ac_var=`echo "ac_cv_func_$ac_func" | $as_tr_sh` -{ echo "$as_me:$LINENO: checking for $ac_func" >&5 -echo $ECHO_N "checking for $ac_func... $ECHO_C" >&6; } +as_ac_var=`$as_echo "ac_cv_func_$ac_func" | $as_tr_sh` +{ $as_echo "$as_me:$LINENO: checking for $ac_func" >&5 +$as_echo_n "checking for $ac_func... " >&6; } if { as_var=$as_ac_var; eval "test \"\${$as_var+set}\" = set"; }; then - echo $ECHO_N "(cached) $ECHO_C" >&6 + $as_echo_n "(cached) " >&6 else cat >conftest.$ac_ext <<_ACEOF /* confdefs.h. */ @@ -18989,35 +19446,42 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_link") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { test -z "$ac_c_werror_flag" || test ! -s conftest.err - } && test -s conftest$ac_exeext && - $as_test_x conftest$ac_exeext; then + } && test -s conftest$ac_exeext && { + test "$cross_compiling" = yes || + $as_test_x conftest$ac_exeext + }; then eval "$as_ac_var=yes" else - echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 eval "$as_ac_var=no" fi +rm -rf conftest.dSYM rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \ conftest$ac_exeext conftest.$ac_ext fi -ac_res=`eval echo '${'$as_ac_var'}'` - { echo "$as_me:$LINENO: result: $ac_res" >&5 -echo "${ECHO_T}$ac_res" >&6; } -if test `eval echo '${'$as_ac_var'}'` = yes; then +ac_res=`eval 'as_val=${'$as_ac_var'} + $as_echo "$as_val"'` + { $as_echo "$as_me:$LINENO: result: $ac_res" >&5 +$as_echo "$ac_res" >&6; } +as_val=`eval 'as_val=${'$as_ac_var'} + $as_echo "$as_val"'` + if test "x$as_val" = x""yes; then cat >>confdefs.h <<_ACEOF -#define `echo "HAVE_$ac_func" | $as_tr_cpp` 1 +#define `$as_echo "HAVE_$ac_func" | $as_tr_cpp` 1 _ACEOF cat >conftest.$ac_ext <<_ACEOF /* confdefs.h. */ @@ -19040,13 +19504,14 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_compile") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { test -z "$ac_c_werror_flag" || test ! -s conftest.err @@ -19058,7 +19523,7 @@ else - echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 @@ -19072,11 +19537,11 @@ for ac_func in gettimeofday do -as_ac_var=`echo "ac_cv_func_$ac_func" | $as_tr_sh` -{ echo "$as_me:$LINENO: checking for $ac_func" >&5 -echo $ECHO_N "checking for $ac_func... $ECHO_C" >&6; } +as_ac_var=`$as_echo "ac_cv_func_$ac_func" | $as_tr_sh` +{ $as_echo "$as_me:$LINENO: checking for $ac_func" >&5 +$as_echo_n "checking for $ac_func... " >&6; } if { as_var=$as_ac_var; eval "test \"\${$as_var+set}\" = set"; }; then - echo $ECHO_N "(cached) $ECHO_C" >&6 + $as_echo_n "(cached) " >&6 else cat >conftest.$ac_ext <<_ACEOF /* confdefs.h. */ @@ -19129,35 +19594,42 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_link") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { test -z "$ac_c_werror_flag" || test ! -s conftest.err - } && test -s conftest$ac_exeext && - $as_test_x conftest$ac_exeext; then + } && test -s conftest$ac_exeext && { + test "$cross_compiling" = yes || + $as_test_x conftest$ac_exeext + }; then eval "$as_ac_var=yes" else - echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 eval "$as_ac_var=no" fi +rm -rf conftest.dSYM rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \ conftest$ac_exeext conftest.$ac_ext fi -ac_res=`eval echo '${'$as_ac_var'}'` - { echo "$as_me:$LINENO: result: $ac_res" >&5 -echo "${ECHO_T}$ac_res" >&6; } -if test `eval echo '${'$as_ac_var'}'` = yes; then +ac_res=`eval 'as_val=${'$as_ac_var'} + $as_echo "$as_val"'` + { $as_echo "$as_me:$LINENO: result: $ac_res" >&5 +$as_echo "$ac_res" >&6; } +as_val=`eval 'as_val=${'$as_ac_var'} + $as_echo "$as_val"'` + if test "x$as_val" = x""yes; then cat >>confdefs.h <<_ACEOF -#define `echo "HAVE_$ac_func" | $as_tr_cpp` 1 +#define `$as_echo "HAVE_$ac_func" | $as_tr_cpp` 1 _ACEOF cat >conftest.$ac_ext <<_ACEOF /* confdefs.h. */ @@ -19180,20 +19652,21 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_compile") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { test -z "$ac_c_werror_flag" || test ! -s conftest.err } && test -s conftest.$ac_objext; then : else - echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 @@ -19210,8 +19683,8 @@ done -{ echo "$as_me:$LINENO: checking for major" >&5 -echo $ECHO_N "checking for major... $ECHO_C" >&6; } +{ $as_echo "$as_me:$LINENO: checking for major" >&5 +$as_echo_n "checking for major... " >&6; } cat >conftest.$ac_ext <<_ACEOF /* confdefs.h. */ _ACEOF @@ -19243,44 +19716,48 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_link") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { test -z "$ac_c_werror_flag" || test ! -s conftest.err - } && test -s conftest$ac_exeext && - $as_test_x conftest$ac_exeext; then + } && test -s conftest$ac_exeext && { + test "$cross_compiling" = yes || + $as_test_x conftest$ac_exeext + }; then cat >>confdefs.h <<\_ACEOF #define HAVE_DEVICE_MACROS 1 _ACEOF - { echo "$as_me:$LINENO: result: yes" >&5 -echo "${ECHO_T}yes" >&6; } + { $as_echo "$as_me:$LINENO: result: yes" >&5 +$as_echo "yes" >&6; } else - echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 - { echo "$as_me:$LINENO: result: no" >&5 -echo "${ECHO_T}no" >&6; } + { $as_echo "$as_me:$LINENO: result: no" >&5 +$as_echo "no" >&6; } fi +rm -rf conftest.dSYM rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \ conftest$ac_exeext conftest.$ac_ext # On OSF/1 V5.1, getaddrinfo is available, but a define # for [no]getaddrinfo in netdb.h. -{ echo "$as_me:$LINENO: checking for getaddrinfo" >&5 -echo $ECHO_N "checking for getaddrinfo... $ECHO_C" >&6; } +{ $as_echo "$as_me:$LINENO: checking for getaddrinfo" >&5 +$as_echo_n "checking for getaddrinfo... " >&6; } cat >conftest.$ac_ext <<_ACEOF /* confdefs.h. */ _ACEOF @@ -19309,26 +19786,29 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_link") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { test -z "$ac_c_werror_flag" || test ! -s conftest.err - } && test -s conftest$ac_exeext && - $as_test_x conftest$ac_exeext; then + } && test -s conftest$ac_exeext && { + test "$cross_compiling" = yes || + $as_test_x conftest$ac_exeext + }; then -{ echo "$as_me:$LINENO: result: yes" >&5 -echo "${ECHO_T}yes" >&6; } -{ echo "$as_me:$LINENO: checking getaddrinfo bug" >&5 -echo $ECHO_N "checking getaddrinfo bug... $ECHO_C" >&6; } +{ $as_echo "$as_me:$LINENO: result: yes" >&5 +$as_echo "yes" >&6; } +{ $as_echo "$as_me:$LINENO: checking getaddrinfo bug" >&5 +$as_echo_n "checking getaddrinfo bug... " >&6; } if test "$cross_compiling" = yes; then - { echo "$as_me:$LINENO: result: buggy" >&5 -echo "${ECHO_T}buggy" >&6; } + { $as_echo "$as_me:$LINENO: result: buggy" >&5 +$as_echo "buggy" >&6; } buggygetaddrinfo=yes else cat >conftest.$ac_ext <<_ACEOF @@ -19431,48 +19911,52 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_link") 2>&5 ac_status=$? - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { ac_try='./conftest$ac_exeext' { (case "(($ac_try" in *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_try") 2>&5 ac_status=$? - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); }; }; then - { echo "$as_me:$LINENO: result: good" >&5 -echo "${ECHO_T}good" >&6; } + { $as_echo "$as_me:$LINENO: result: good" >&5 +$as_echo "good" >&6; } buggygetaddrinfo=no else - echo "$as_me: program exited with status $ac_status" >&5 -echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: program exited with status $ac_status" >&5 +$as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 ( exit $ac_status ) -{ echo "$as_me:$LINENO: result: buggy" >&5 -echo "${ECHO_T}buggy" >&6; } +{ $as_echo "$as_me:$LINENO: result: buggy" >&5 +$as_echo "buggy" >&6; } buggygetaddrinfo=yes fi +rm -rf conftest.dSYM rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext conftest.$ac_objext conftest.$ac_ext fi else - echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 -{ echo "$as_me:$LINENO: result: no" >&5 -echo "${ECHO_T}no" >&6; } +{ $as_echo "$as_me:$LINENO: result: no" >&5 +$as_echo "no" >&6; } buggygetaddrinfo=yes fi +rm -rf conftest.dSYM rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \ conftest$ac_exeext conftest.$ac_ext @@ -19492,11 +19976,11 @@ for ac_func in getnameinfo do -as_ac_var=`echo "ac_cv_func_$ac_func" | $as_tr_sh` -{ echo "$as_me:$LINENO: checking for $ac_func" >&5 -echo $ECHO_N "checking for $ac_func... $ECHO_C" >&6; } +as_ac_var=`$as_echo "ac_cv_func_$ac_func" | $as_tr_sh` +{ $as_echo "$as_me:$LINENO: checking for $ac_func" >&5 +$as_echo_n "checking for $ac_func... " >&6; } if { as_var=$as_ac_var; eval "test \"\${$as_var+set}\" = set"; }; then - echo $ECHO_N "(cached) $ECHO_C" >&6 + $as_echo_n "(cached) " >&6 else cat >conftest.$ac_ext <<_ACEOF /* confdefs.h. */ @@ -19549,35 +20033,42 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_link") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { test -z "$ac_c_werror_flag" || test ! -s conftest.err - } && test -s conftest$ac_exeext && - $as_test_x conftest$ac_exeext; then + } && test -s conftest$ac_exeext && { + test "$cross_compiling" = yes || + $as_test_x conftest$ac_exeext + }; then eval "$as_ac_var=yes" else - echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 eval "$as_ac_var=no" fi +rm -rf conftest.dSYM rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \ conftest$ac_exeext conftest.$ac_ext fi -ac_res=`eval echo '${'$as_ac_var'}'` - { echo "$as_me:$LINENO: result: $ac_res" >&5 -echo "${ECHO_T}$ac_res" >&6; } -if test `eval echo '${'$as_ac_var'}'` = yes; then +ac_res=`eval 'as_val=${'$as_ac_var'} + $as_echo "$as_val"'` + { $as_echo "$as_me:$LINENO: result: $ac_res" >&5 +$as_echo "$ac_res" >&6; } +as_val=`eval 'as_val=${'$as_ac_var'} + $as_echo "$as_val"'` + if test "x$as_val" = x""yes; then cat >>confdefs.h <<_ACEOF -#define `echo "HAVE_$ac_func" | $as_tr_cpp` 1 +#define `$as_echo "HAVE_$ac_func" | $as_tr_cpp` 1 _ACEOF fi @@ -19585,10 +20076,10 @@ # checks for structures -{ echo "$as_me:$LINENO: checking whether time.h and sys/time.h may both be included" >&5 -echo $ECHO_N "checking whether time.h and sys/time.h may both be included... $ECHO_C" >&6; } +{ $as_echo "$as_me:$LINENO: checking whether time.h and sys/time.h may both be included" >&5 +$as_echo_n "checking whether time.h and sys/time.h may both be included... " >&6; } if test "${ac_cv_header_time+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 + $as_echo_n "(cached) " >&6 else cat >conftest.$ac_ext <<_ACEOF /* confdefs.h. */ @@ -19615,20 +20106,21 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_compile") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { test -z "$ac_c_werror_flag" || test ! -s conftest.err } && test -s conftest.$ac_objext; then ac_cv_header_time=yes else - echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 ac_cv_header_time=no @@ -19636,8 +20128,8 @@ rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext fi -{ echo "$as_me:$LINENO: result: $ac_cv_header_time" >&5 -echo "${ECHO_T}$ac_cv_header_time" >&6; } +{ $as_echo "$as_me:$LINENO: result: $ac_cv_header_time" >&5 +$as_echo "$ac_cv_header_time" >&6; } if test $ac_cv_header_time = yes; then cat >>confdefs.h <<\_ACEOF @@ -19646,10 +20138,10 @@ fi -{ echo "$as_me:$LINENO: checking whether struct tm is in sys/time.h or time.h" >&5 -echo $ECHO_N "checking whether struct tm is in sys/time.h or time.h... $ECHO_C" >&6; } +{ $as_echo "$as_me:$LINENO: checking whether struct tm is in sys/time.h or time.h" >&5 +$as_echo_n "checking whether struct tm is in sys/time.h or time.h... " >&6; } if test "${ac_cv_struct_tm+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 + $as_echo_n "(cached) " >&6 else cat >conftest.$ac_ext <<_ACEOF /* confdefs.h. */ @@ -19665,7 +20157,7 @@ { struct tm tm; int *p = &tm.tm_sec; - return !p; + return !p; ; return 0; } @@ -19676,20 +20168,21 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_compile") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { test -z "$ac_c_werror_flag" || test ! -s conftest.err } && test -s conftest.$ac_objext; then ac_cv_struct_tm=time.h else - echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 ac_cv_struct_tm=sys/time.h @@ -19697,8 +20190,8 @@ rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext fi -{ echo "$as_me:$LINENO: result: $ac_cv_struct_tm" >&5 -echo "${ECHO_T}$ac_cv_struct_tm" >&6; } +{ $as_echo "$as_me:$LINENO: result: $ac_cv_struct_tm" >&5 +$as_echo "$ac_cv_struct_tm" >&6; } if test $ac_cv_struct_tm = sys/time.h; then cat >>confdefs.h <<\_ACEOF @@ -19707,10 +20200,10 @@ fi -{ echo "$as_me:$LINENO: checking for struct tm.tm_zone" >&5 -echo $ECHO_N "checking for struct tm.tm_zone... $ECHO_C" >&6; } +{ $as_echo "$as_me:$LINENO: checking for struct tm.tm_zone" >&5 +$as_echo_n "checking for struct tm.tm_zone... " >&6; } if test "${ac_cv_member_struct_tm_tm_zone+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 + $as_echo_n "(cached) " >&6 else cat >conftest.$ac_ext <<_ACEOF /* confdefs.h. */ @@ -19738,20 +20231,21 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_compile") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { test -z "$ac_c_werror_flag" || test ! -s conftest.err } && test -s conftest.$ac_objext; then ac_cv_member_struct_tm_tm_zone=yes else - echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 cat >conftest.$ac_ext <<_ACEOF @@ -19780,20 +20274,21 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_compile") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { test -z "$ac_c_werror_flag" || test ! -s conftest.err } && test -s conftest.$ac_objext; then ac_cv_member_struct_tm_tm_zone=yes else - echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 ac_cv_member_struct_tm_tm_zone=no @@ -19804,9 +20299,9 @@ rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext fi -{ echo "$as_me:$LINENO: result: $ac_cv_member_struct_tm_tm_zone" >&5 -echo "${ECHO_T}$ac_cv_member_struct_tm_tm_zone" >&6; } -if test $ac_cv_member_struct_tm_tm_zone = yes; then +{ $as_echo "$as_me:$LINENO: result: $ac_cv_member_struct_tm_tm_zone" >&5 +$as_echo "$ac_cv_member_struct_tm_tm_zone" >&6; } +if test "x$ac_cv_member_struct_tm_tm_zone" = x""yes; then cat >>confdefs.h <<_ACEOF #define HAVE_STRUCT_TM_TM_ZONE 1 @@ -19822,10 +20317,10 @@ _ACEOF else - { echo "$as_me:$LINENO: checking whether tzname is declared" >&5 -echo $ECHO_N "checking whether tzname is declared... $ECHO_C" >&6; } + { $as_echo "$as_me:$LINENO: checking whether tzname is declared" >&5 +$as_echo_n "checking whether tzname is declared... " >&6; } if test "${ac_cv_have_decl_tzname+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 + $as_echo_n "(cached) " >&6 else cat >conftest.$ac_ext <<_ACEOF /* confdefs.h. */ @@ -19852,20 +20347,21 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_compile") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { test -z "$ac_c_werror_flag" || test ! -s conftest.err } && test -s conftest.$ac_objext; then ac_cv_have_decl_tzname=yes else - echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 ac_cv_have_decl_tzname=no @@ -19873,9 +20369,9 @@ rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext fi -{ echo "$as_me:$LINENO: result: $ac_cv_have_decl_tzname" >&5 -echo "${ECHO_T}$ac_cv_have_decl_tzname" >&6; } -if test $ac_cv_have_decl_tzname = yes; then +{ $as_echo "$as_me:$LINENO: result: $ac_cv_have_decl_tzname" >&5 +$as_echo "$ac_cv_have_decl_tzname" >&6; } +if test "x$ac_cv_have_decl_tzname" = x""yes; then cat >>confdefs.h <<_ACEOF #define HAVE_DECL_TZNAME 1 @@ -19891,10 +20387,10 @@ fi - { echo "$as_me:$LINENO: checking for tzname" >&5 -echo $ECHO_N "checking for tzname... $ECHO_C" >&6; } + { $as_echo "$as_me:$LINENO: checking for tzname" >&5 +$as_echo_n "checking for tzname... " >&6; } if test "${ac_cv_var_tzname+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 + $as_echo_n "(cached) " >&6 else cat >conftest.$ac_ext <<_ACEOF /* confdefs.h. */ @@ -19921,31 +20417,35 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_link") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { test -z "$ac_c_werror_flag" || test ! -s conftest.err - } && test -s conftest$ac_exeext && - $as_test_x conftest$ac_exeext; then + } && test -s conftest$ac_exeext && { + test "$cross_compiling" = yes || + $as_test_x conftest$ac_exeext + }; then ac_cv_var_tzname=yes else - echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 ac_cv_var_tzname=no fi +rm -rf conftest.dSYM rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \ conftest$ac_exeext conftest.$ac_ext fi -{ echo "$as_me:$LINENO: result: $ac_cv_var_tzname" >&5 -echo "${ECHO_T}$ac_cv_var_tzname" >&6; } +{ $as_echo "$as_me:$LINENO: result: $ac_cv_var_tzname" >&5 +$as_echo "$ac_cv_var_tzname" >&6; } if test $ac_cv_var_tzname = yes; then cat >>confdefs.h <<\_ACEOF @@ -19955,10 +20455,10 @@ fi fi -{ echo "$as_me:$LINENO: checking for struct stat.st_rdev" >&5 -echo $ECHO_N "checking for struct stat.st_rdev... $ECHO_C" >&6; } +{ $as_echo "$as_me:$LINENO: checking for struct stat.st_rdev" >&5 +$as_echo_n "checking for struct stat.st_rdev... " >&6; } if test "${ac_cv_member_struct_stat_st_rdev+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 + $as_echo_n "(cached) " >&6 else cat >conftest.$ac_ext <<_ACEOF /* confdefs.h. */ @@ -19983,20 +20483,21 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_compile") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { test -z "$ac_c_werror_flag" || test ! -s conftest.err } && test -s conftest.$ac_objext; then ac_cv_member_struct_stat_st_rdev=yes else - echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 cat >conftest.$ac_ext <<_ACEOF @@ -20022,20 +20523,21 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_compile") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { test -z "$ac_c_werror_flag" || test ! -s conftest.err } && test -s conftest.$ac_objext; then ac_cv_member_struct_stat_st_rdev=yes else - echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 ac_cv_member_struct_stat_st_rdev=no @@ -20046,9 +20548,9 @@ rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext fi -{ echo "$as_me:$LINENO: result: $ac_cv_member_struct_stat_st_rdev" >&5 -echo "${ECHO_T}$ac_cv_member_struct_stat_st_rdev" >&6; } -if test $ac_cv_member_struct_stat_st_rdev = yes; then +{ $as_echo "$as_me:$LINENO: result: $ac_cv_member_struct_stat_st_rdev" >&5 +$as_echo "$ac_cv_member_struct_stat_st_rdev" >&6; } +if test "x$ac_cv_member_struct_stat_st_rdev" = x""yes; then cat >>confdefs.h <<_ACEOF #define HAVE_STRUCT_STAT_ST_RDEV 1 @@ -20057,10 +20559,10 @@ fi -{ echo "$as_me:$LINENO: checking for struct stat.st_blksize" >&5 -echo $ECHO_N "checking for struct stat.st_blksize... $ECHO_C" >&6; } +{ $as_echo "$as_me:$LINENO: checking for struct stat.st_blksize" >&5 +$as_echo_n "checking for struct stat.st_blksize... " >&6; } if test "${ac_cv_member_struct_stat_st_blksize+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 + $as_echo_n "(cached) " >&6 else cat >conftest.$ac_ext <<_ACEOF /* confdefs.h. */ @@ -20085,20 +20587,21 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_compile") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { test -z "$ac_c_werror_flag" || test ! -s conftest.err } && test -s conftest.$ac_objext; then ac_cv_member_struct_stat_st_blksize=yes else - echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 cat >conftest.$ac_ext <<_ACEOF @@ -20124,20 +20627,21 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_compile") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { test -z "$ac_c_werror_flag" || test ! -s conftest.err } && test -s conftest.$ac_objext; then ac_cv_member_struct_stat_st_blksize=yes else - echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 ac_cv_member_struct_stat_st_blksize=no @@ -20148,9 +20652,9 @@ rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext fi -{ echo "$as_me:$LINENO: result: $ac_cv_member_struct_stat_st_blksize" >&5 -echo "${ECHO_T}$ac_cv_member_struct_stat_st_blksize" >&6; } -if test $ac_cv_member_struct_stat_st_blksize = yes; then +{ $as_echo "$as_me:$LINENO: result: $ac_cv_member_struct_stat_st_blksize" >&5 +$as_echo "$ac_cv_member_struct_stat_st_blksize" >&6; } +if test "x$ac_cv_member_struct_stat_st_blksize" = x""yes; then cat >>confdefs.h <<_ACEOF #define HAVE_STRUCT_STAT_ST_BLKSIZE 1 @@ -20159,10 +20663,10 @@ fi -{ echo "$as_me:$LINENO: checking for struct stat.st_flags" >&5 -echo $ECHO_N "checking for struct stat.st_flags... $ECHO_C" >&6; } +{ $as_echo "$as_me:$LINENO: checking for struct stat.st_flags" >&5 +$as_echo_n "checking for struct stat.st_flags... " >&6; } if test "${ac_cv_member_struct_stat_st_flags+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 + $as_echo_n "(cached) " >&6 else cat >conftest.$ac_ext <<_ACEOF /* confdefs.h. */ @@ -20187,20 +20691,21 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_compile") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { test -z "$ac_c_werror_flag" || test ! -s conftest.err } && test -s conftest.$ac_objext; then ac_cv_member_struct_stat_st_flags=yes else - echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 cat >conftest.$ac_ext <<_ACEOF @@ -20226,20 +20731,21 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_compile") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { test -z "$ac_c_werror_flag" || test ! -s conftest.err } && test -s conftest.$ac_objext; then ac_cv_member_struct_stat_st_flags=yes else - echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 ac_cv_member_struct_stat_st_flags=no @@ -20250,9 +20756,9 @@ rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext fi -{ echo "$as_me:$LINENO: result: $ac_cv_member_struct_stat_st_flags" >&5 -echo "${ECHO_T}$ac_cv_member_struct_stat_st_flags" >&6; } -if test $ac_cv_member_struct_stat_st_flags = yes; then +{ $as_echo "$as_me:$LINENO: result: $ac_cv_member_struct_stat_st_flags" >&5 +$as_echo "$ac_cv_member_struct_stat_st_flags" >&6; } +if test "x$ac_cv_member_struct_stat_st_flags" = x""yes; then cat >>confdefs.h <<_ACEOF #define HAVE_STRUCT_STAT_ST_FLAGS 1 @@ -20261,10 +20767,10 @@ fi -{ echo "$as_me:$LINENO: checking for struct stat.st_gen" >&5 -echo $ECHO_N "checking for struct stat.st_gen... $ECHO_C" >&6; } +{ $as_echo "$as_me:$LINENO: checking for struct stat.st_gen" >&5 +$as_echo_n "checking for struct stat.st_gen... " >&6; } if test "${ac_cv_member_struct_stat_st_gen+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 + $as_echo_n "(cached) " >&6 else cat >conftest.$ac_ext <<_ACEOF /* confdefs.h. */ @@ -20289,20 +20795,21 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_compile") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { test -z "$ac_c_werror_flag" || test ! -s conftest.err } && test -s conftest.$ac_objext; then ac_cv_member_struct_stat_st_gen=yes else - echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 cat >conftest.$ac_ext <<_ACEOF @@ -20328,20 +20835,21 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_compile") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { test -z "$ac_c_werror_flag" || test ! -s conftest.err } && test -s conftest.$ac_objext; then ac_cv_member_struct_stat_st_gen=yes else - echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 ac_cv_member_struct_stat_st_gen=no @@ -20352,9 +20860,9 @@ rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext fi -{ echo "$as_me:$LINENO: result: $ac_cv_member_struct_stat_st_gen" >&5 -echo "${ECHO_T}$ac_cv_member_struct_stat_st_gen" >&6; } -if test $ac_cv_member_struct_stat_st_gen = yes; then +{ $as_echo "$as_me:$LINENO: result: $ac_cv_member_struct_stat_st_gen" >&5 +$as_echo "$ac_cv_member_struct_stat_st_gen" >&6; } +if test "x$ac_cv_member_struct_stat_st_gen" = x""yes; then cat >>confdefs.h <<_ACEOF #define HAVE_STRUCT_STAT_ST_GEN 1 @@ -20363,10 +20871,10 @@ fi -{ echo "$as_me:$LINENO: checking for struct stat.st_birthtime" >&5 -echo $ECHO_N "checking for struct stat.st_birthtime... $ECHO_C" >&6; } +{ $as_echo "$as_me:$LINENO: checking for struct stat.st_birthtime" >&5 +$as_echo_n "checking for struct stat.st_birthtime... " >&6; } if test "${ac_cv_member_struct_stat_st_birthtime+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 + $as_echo_n "(cached) " >&6 else cat >conftest.$ac_ext <<_ACEOF /* confdefs.h. */ @@ -20391,20 +20899,21 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_compile") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { test -z "$ac_c_werror_flag" || test ! -s conftest.err } && test -s conftest.$ac_objext; then ac_cv_member_struct_stat_st_birthtime=yes else - echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 cat >conftest.$ac_ext <<_ACEOF @@ -20430,20 +20939,21 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_compile") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { test -z "$ac_c_werror_flag" || test ! -s conftest.err } && test -s conftest.$ac_objext; then ac_cv_member_struct_stat_st_birthtime=yes else - echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 ac_cv_member_struct_stat_st_birthtime=no @@ -20454,9 +20964,9 @@ rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext fi -{ echo "$as_me:$LINENO: result: $ac_cv_member_struct_stat_st_birthtime" >&5 -echo "${ECHO_T}$ac_cv_member_struct_stat_st_birthtime" >&6; } -if test $ac_cv_member_struct_stat_st_birthtime = yes; then +{ $as_echo "$as_me:$LINENO: result: $ac_cv_member_struct_stat_st_birthtime" >&5 +$as_echo "$ac_cv_member_struct_stat_st_birthtime" >&6; } +if test "x$ac_cv_member_struct_stat_st_birthtime" = x""yes; then cat >>confdefs.h <<_ACEOF #define HAVE_STRUCT_STAT_ST_BIRTHTIME 1 @@ -20465,10 +20975,10 @@ fi -{ echo "$as_me:$LINENO: checking for struct stat.st_blocks" >&5 -echo $ECHO_N "checking for struct stat.st_blocks... $ECHO_C" >&6; } +{ $as_echo "$as_me:$LINENO: checking for struct stat.st_blocks" >&5 +$as_echo_n "checking for struct stat.st_blocks... " >&6; } if test "${ac_cv_member_struct_stat_st_blocks+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 + $as_echo_n "(cached) " >&6 else cat >conftest.$ac_ext <<_ACEOF /* confdefs.h. */ @@ -20493,20 +21003,21 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_compile") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { test -z "$ac_c_werror_flag" || test ! -s conftest.err } && test -s conftest.$ac_objext; then ac_cv_member_struct_stat_st_blocks=yes else - echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 cat >conftest.$ac_ext <<_ACEOF @@ -20532,20 +21043,21 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_compile") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { test -z "$ac_c_werror_flag" || test ! -s conftest.err } && test -s conftest.$ac_objext; then ac_cv_member_struct_stat_st_blocks=yes else - echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 ac_cv_member_struct_stat_st_blocks=no @@ -20556,9 +21068,9 @@ rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext fi -{ echo "$as_me:$LINENO: result: $ac_cv_member_struct_stat_st_blocks" >&5 -echo "${ECHO_T}$ac_cv_member_struct_stat_st_blocks" >&6; } -if test $ac_cv_member_struct_stat_st_blocks = yes; then +{ $as_echo "$as_me:$LINENO: result: $ac_cv_member_struct_stat_st_blocks" >&5 +$as_echo "$ac_cv_member_struct_stat_st_blocks" >&6; } +if test "x$ac_cv_member_struct_stat_st_blocks" = x""yes; then cat >>confdefs.h <<_ACEOF #define HAVE_STRUCT_STAT_ST_BLOCKS 1 @@ -20580,10 +21092,10 @@ -{ echo "$as_me:$LINENO: checking for time.h that defines altzone" >&5 -echo $ECHO_N "checking for time.h that defines altzone... $ECHO_C" >&6; } +{ $as_echo "$as_me:$LINENO: checking for time.h that defines altzone" >&5 +$as_echo_n "checking for time.h that defines altzone... " >&6; } if test "${ac_cv_header_time_altzone+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 + $as_echo_n "(cached) " >&6 else cat >conftest.$ac_ext <<_ACEOF /* confdefs.h. */ @@ -20606,20 +21118,21 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_compile") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { test -z "$ac_c_werror_flag" || test ! -s conftest.err } && test -s conftest.$ac_objext; then ac_cv_header_time_altzone=yes else - echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 ac_cv_header_time_altzone=no @@ -20628,8 +21141,8 @@ rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext fi -{ echo "$as_me:$LINENO: result: $ac_cv_header_time_altzone" >&5 -echo "${ECHO_T}$ac_cv_header_time_altzone" >&6; } +{ $as_echo "$as_me:$LINENO: result: $ac_cv_header_time_altzone" >&5 +$as_echo "$ac_cv_header_time_altzone" >&6; } if test $ac_cv_header_time_altzone = yes; then cat >>confdefs.h <<\_ACEOF @@ -20639,8 +21152,8 @@ fi was_it_defined=no -{ echo "$as_me:$LINENO: checking whether sys/select.h and sys/time.h may both be included" >&5 -echo $ECHO_N "checking whether sys/select.h and sys/time.h may both be included... $ECHO_C" >&6; } +{ $as_echo "$as_me:$LINENO: checking whether sys/select.h and sys/time.h may both be included" >&5 +$as_echo_n "checking whether sys/select.h and sys/time.h may both be included... " >&6; } cat >conftest.$ac_ext <<_ACEOF /* confdefs.h. */ _ACEOF @@ -20666,13 +21179,14 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_compile") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { test -z "$ac_c_werror_flag" || test ! -s conftest.err @@ -20686,20 +21200,20 @@ was_it_defined=yes else - echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 fi rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext -{ echo "$as_me:$LINENO: result: $was_it_defined" >&5 -echo "${ECHO_T}$was_it_defined" >&6; } +{ $as_echo "$as_me:$LINENO: result: $was_it_defined" >&5 +$as_echo "$was_it_defined" >&6; } -{ echo "$as_me:$LINENO: checking for addrinfo" >&5 -echo $ECHO_N "checking for addrinfo... $ECHO_C" >&6; } +{ $as_echo "$as_me:$LINENO: checking for addrinfo" >&5 +$as_echo_n "checking for addrinfo... " >&6; } if test "${ac_cv_struct_addrinfo+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 + $as_echo_n "(cached) " >&6 else cat >conftest.$ac_ext <<_ACEOF /* confdefs.h. */ @@ -20723,20 +21237,21 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_compile") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { test -z "$ac_c_werror_flag" || test ! -s conftest.err } && test -s conftest.$ac_objext; then ac_cv_struct_addrinfo=yes else - echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 ac_cv_struct_addrinfo=no @@ -20745,8 +21260,8 @@ rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext fi -{ echo "$as_me:$LINENO: result: $ac_cv_struct_addrinfo" >&5 -echo "${ECHO_T}$ac_cv_struct_addrinfo" >&6; } +{ $as_echo "$as_me:$LINENO: result: $ac_cv_struct_addrinfo" >&5 +$as_echo "$ac_cv_struct_addrinfo" >&6; } if test $ac_cv_struct_addrinfo = yes; then cat >>confdefs.h <<\_ACEOF @@ -20755,10 +21270,10 @@ fi -{ echo "$as_me:$LINENO: checking for sockaddr_storage" >&5 -echo $ECHO_N "checking for sockaddr_storage... $ECHO_C" >&6; } +{ $as_echo "$as_me:$LINENO: checking for sockaddr_storage" >&5 +$as_echo_n "checking for sockaddr_storage... " >&6; } if test "${ac_cv_struct_sockaddr_storage+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 + $as_echo_n "(cached) " >&6 else cat >conftest.$ac_ext <<_ACEOF /* confdefs.h. */ @@ -20783,20 +21298,21 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_compile") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { test -z "$ac_c_werror_flag" || test ! -s conftest.err } && test -s conftest.$ac_objext; then ac_cv_struct_sockaddr_storage=yes else - echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 ac_cv_struct_sockaddr_storage=no @@ -20805,8 +21321,8 @@ rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext fi -{ echo "$as_me:$LINENO: result: $ac_cv_struct_sockaddr_storage" >&5 -echo "${ECHO_T}$ac_cv_struct_sockaddr_storage" >&6; } +{ $as_echo "$as_me:$LINENO: result: $ac_cv_struct_sockaddr_storage" >&5 +$as_echo "$ac_cv_struct_sockaddr_storage" >&6; } if test $ac_cv_struct_sockaddr_storage = yes; then cat >>confdefs.h <<\_ACEOF @@ -20818,10 +21334,10 @@ # checks for compiler characteristics -{ echo "$as_me:$LINENO: checking whether char is unsigned" >&5 -echo $ECHO_N "checking whether char is unsigned... $ECHO_C" >&6; } +{ $as_echo "$as_me:$LINENO: checking whether char is unsigned" >&5 +$as_echo_n "checking whether char is unsigned... " >&6; } if test "${ac_cv_c_char_unsigned+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 + $as_echo_n "(cached) " >&6 else cat >conftest.$ac_ext <<_ACEOF /* confdefs.h. */ @@ -20846,20 +21362,21 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_compile") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { test -z "$ac_c_werror_flag" || test ! -s conftest.err } && test -s conftest.$ac_objext; then ac_cv_c_char_unsigned=no else - echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 ac_cv_c_char_unsigned=yes @@ -20867,8 +21384,8 @@ rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext fi -{ echo "$as_me:$LINENO: result: $ac_cv_c_char_unsigned" >&5 -echo "${ECHO_T}$ac_cv_c_char_unsigned" >&6; } +{ $as_echo "$as_me:$LINENO: result: $ac_cv_c_char_unsigned" >&5 +$as_echo "$ac_cv_c_char_unsigned" >&6; } if test $ac_cv_c_char_unsigned = yes && test "$GCC" != yes; then cat >>confdefs.h <<\_ACEOF #define __CHAR_UNSIGNED__ 1 @@ -20876,10 +21393,10 @@ fi -{ echo "$as_me:$LINENO: checking for an ANSI C-conforming const" >&5 -echo $ECHO_N "checking for an ANSI C-conforming const... $ECHO_C" >&6; } +{ $as_echo "$as_me:$LINENO: checking for an ANSI C-conforming const" >&5 +$as_echo_n "checking for an ANSI C-conforming const... " >&6; } if test "${ac_cv_c_const+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 + $as_echo_n "(cached) " >&6 else cat >conftest.$ac_ext <<_ACEOF /* confdefs.h. */ @@ -20951,20 +21468,21 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_compile") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { test -z "$ac_c_werror_flag" || test ! -s conftest.err } && test -s conftest.$ac_objext; then ac_cv_c_const=yes else - echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 ac_cv_c_const=no @@ -20972,20 +21490,20 @@ rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext fi -{ echo "$as_me:$LINENO: result: $ac_cv_c_const" >&5 -echo "${ECHO_T}$ac_cv_c_const" >&6; } +{ $as_echo "$as_me:$LINENO: result: $ac_cv_c_const" >&5 +$as_echo "$ac_cv_c_const" >&6; } if test $ac_cv_c_const = no; then cat >>confdefs.h <<\_ACEOF -#define const +#define const /**/ _ACEOF fi works=no -{ echo "$as_me:$LINENO: checking for working volatile" >&5 -echo $ECHO_N "checking for working volatile... $ECHO_C" >&6; } +{ $as_echo "$as_me:$LINENO: checking for working volatile" >&5 +$as_echo_n "checking for working volatile... " >&6; } cat >conftest.$ac_ext <<_ACEOF /* confdefs.h. */ _ACEOF @@ -21007,37 +21525,38 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_compile") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { test -z "$ac_c_werror_flag" || test ! -s conftest.err } && test -s conftest.$ac_objext; then works=yes else - echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 cat >>confdefs.h <<\_ACEOF -#define volatile +#define volatile /**/ _ACEOF fi rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext -{ echo "$as_me:$LINENO: result: $works" >&5 -echo "${ECHO_T}$works" >&6; } +{ $as_echo "$as_me:$LINENO: result: $works" >&5 +$as_echo "$works" >&6; } works=no -{ echo "$as_me:$LINENO: checking for working signed char" >&5 -echo $ECHO_N "checking for working signed char... $ECHO_C" >&6; } +{ $as_echo "$as_me:$LINENO: checking for working signed char" >&5 +$as_echo_n "checking for working signed char... " >&6; } cat >conftest.$ac_ext <<_ACEOF /* confdefs.h. */ _ACEOF @@ -21059,37 +21578,38 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_compile") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { test -z "$ac_c_werror_flag" || test ! -s conftest.err } && test -s conftest.$ac_objext; then works=yes else - echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 cat >>confdefs.h <<\_ACEOF -#define signed +#define signed /**/ _ACEOF fi rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext -{ echo "$as_me:$LINENO: result: $works" >&5 -echo "${ECHO_T}$works" >&6; } +{ $as_echo "$as_me:$LINENO: result: $works" >&5 +$as_echo "$works" >&6; } have_prototypes=no -{ echo "$as_me:$LINENO: checking for prototypes" >&5 -echo $ECHO_N "checking for prototypes... $ECHO_C" >&6; } +{ $as_echo "$as_me:$LINENO: checking for prototypes" >&5 +$as_echo_n "checking for prototypes... " >&6; } cat >conftest.$ac_ext <<_ACEOF /* confdefs.h. */ _ACEOF @@ -21111,13 +21631,14 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_compile") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { test -z "$ac_c_werror_flag" || test ! -s conftest.err @@ -21131,19 +21652,19 @@ have_prototypes=yes else - echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 fi rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext -{ echo "$as_me:$LINENO: result: $have_prototypes" >&5 -echo "${ECHO_T}$have_prototypes" >&6; } +{ $as_echo "$as_me:$LINENO: result: $have_prototypes" >&5 +$as_echo "$have_prototypes" >&6; } works=no -{ echo "$as_me:$LINENO: checking for variable length prototypes and stdarg.h" >&5 -echo $ECHO_N "checking for variable length prototypes and stdarg.h... $ECHO_C" >&6; } +{ $as_echo "$as_me:$LINENO: checking for variable length prototypes and stdarg.h" >&5 +$as_echo_n "checking for variable length prototypes and stdarg.h... " >&6; } cat >conftest.$ac_ext <<_ACEOF /* confdefs.h. */ _ACEOF @@ -21175,13 +21696,14 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_compile") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { test -z "$ac_c_werror_flag" || test ! -s conftest.err @@ -21195,19 +21717,19 @@ works=yes else - echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 fi rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext -{ echo "$as_me:$LINENO: result: $works" >&5 -echo "${ECHO_T}$works" >&6; } +{ $as_echo "$as_me:$LINENO: result: $works" >&5 +$as_echo "$works" >&6; } # check for socketpair -{ echo "$as_me:$LINENO: checking for socketpair" >&5 -echo $ECHO_N "checking for socketpair... $ECHO_C" >&6; } +{ $as_echo "$as_me:$LINENO: checking for socketpair" >&5 +$as_echo_n "checking for socketpair... " >&6; } cat >conftest.$ac_ext <<_ACEOF /* confdefs.h. */ _ACEOF @@ -21232,13 +21754,14 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_compile") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { test -z "$ac_c_werror_flag" || test ! -s conftest.err @@ -21248,22 +21771,22 @@ #define HAVE_SOCKETPAIR 1 _ACEOF - { echo "$as_me:$LINENO: result: yes" >&5 -echo "${ECHO_T}yes" >&6; } + { $as_echo "$as_me:$LINENO: result: yes" >&5 +$as_echo "yes" >&6; } else - echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 - { echo "$as_me:$LINENO: result: no" >&5 -echo "${ECHO_T}no" >&6; } + { $as_echo "$as_me:$LINENO: result: no" >&5 +$as_echo "no" >&6; } fi rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext # check if sockaddr has sa_len member -{ echo "$as_me:$LINENO: checking if sockaddr has sa_len member" >&5 -echo $ECHO_N "checking if sockaddr has sa_len member... $ECHO_C" >&6; } +{ $as_echo "$as_me:$LINENO: checking if sockaddr has sa_len member" >&5 +$as_echo_n "checking if sockaddr has sa_len member... " >&6; } cat >conftest.$ac_ext <<_ACEOF /* confdefs.h. */ _ACEOF @@ -21287,37 +21810,38 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_compile") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { test -z "$ac_c_werror_flag" || test ! -s conftest.err } && test -s conftest.$ac_objext; then - { echo "$as_me:$LINENO: result: yes" >&5 -echo "${ECHO_T}yes" >&6; } + { $as_echo "$as_me:$LINENO: result: yes" >&5 +$as_echo "yes" >&6; } cat >>confdefs.h <<\_ACEOF #define HAVE_SOCKADDR_SA_LEN 1 _ACEOF else - echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 - { echo "$as_me:$LINENO: result: no" >&5 -echo "${ECHO_T}no" >&6; } + { $as_echo "$as_me:$LINENO: result: no" >&5 +$as_echo "no" >&6; } fi rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext va_list_is_array=no -{ echo "$as_me:$LINENO: checking whether va_list is an array" >&5 -echo $ECHO_N "checking whether va_list is an array... $ECHO_C" >&6; } +{ $as_echo "$as_me:$LINENO: checking whether va_list is an array" >&5 +$as_echo_n "checking whether va_list is an array... " >&6; } cat >conftest.$ac_ext <<_ACEOF /* confdefs.h. */ _ACEOF @@ -21345,20 +21869,21 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_compile") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { test -z "$ac_c_werror_flag" || test ! -s conftest.err } && test -s conftest.$ac_objext; then : else - echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 @@ -21372,17 +21897,17 @@ fi rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext -{ echo "$as_me:$LINENO: result: $va_list_is_array" >&5 -echo "${ECHO_T}$va_list_is_array" >&6; } +{ $as_echo "$as_me:$LINENO: result: $va_list_is_array" >&5 +$as_echo "$va_list_is_array" >&6; } # sigh -- gethostbyname_r is a mess; it can have 3, 5 or 6 arguments :-( -{ echo "$as_me:$LINENO: checking for gethostbyname_r" >&5 -echo $ECHO_N "checking for gethostbyname_r... $ECHO_C" >&6; } +{ $as_echo "$as_me:$LINENO: checking for gethostbyname_r" >&5 +$as_echo_n "checking for gethostbyname_r... " >&6; } if test "${ac_cv_func_gethostbyname_r+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 + $as_echo_n "(cached) " >&6 else cat >conftest.$ac_ext <<_ACEOF /* confdefs.h. */ @@ -21435,39 +21960,43 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_link") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { test -z "$ac_c_werror_flag" || test ! -s conftest.err - } && test -s conftest$ac_exeext && - $as_test_x conftest$ac_exeext; then + } && test -s conftest$ac_exeext && { + test "$cross_compiling" = yes || + $as_test_x conftest$ac_exeext + }; then ac_cv_func_gethostbyname_r=yes else - echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 ac_cv_func_gethostbyname_r=no fi +rm -rf conftest.dSYM rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \ conftest$ac_exeext conftest.$ac_ext fi -{ echo "$as_me:$LINENO: result: $ac_cv_func_gethostbyname_r" >&5 -echo "${ECHO_T}$ac_cv_func_gethostbyname_r" >&6; } -if test $ac_cv_func_gethostbyname_r = yes; then +{ $as_echo "$as_me:$LINENO: result: $ac_cv_func_gethostbyname_r" >&5 +$as_echo "$ac_cv_func_gethostbyname_r" >&6; } +if test "x$ac_cv_func_gethostbyname_r" = x""yes; then cat >>confdefs.h <<\_ACEOF #define HAVE_GETHOSTBYNAME_R 1 _ACEOF - { echo "$as_me:$LINENO: checking gethostbyname_r with 6 args" >&5 -echo $ECHO_N "checking gethostbyname_r with 6 args... $ECHO_C" >&6; } + { $as_echo "$as_me:$LINENO: checking gethostbyname_r with 6 args" >&5 +$as_echo_n "checking gethostbyname_r with 6 args... " >&6; } OLD_CFLAGS=$CFLAGS CFLAGS="$CFLAGS $MY_CPPFLAGS $MY_THREAD_CPPFLAGS $MY_CFLAGS" cat >conftest.$ac_ext <<_ACEOF @@ -21501,13 +22030,14 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_compile") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { test -z "$ac_c_werror_flag" || test ! -s conftest.err @@ -21522,18 +22052,18 @@ #define HAVE_GETHOSTBYNAME_R_6_ARG 1 _ACEOF - { echo "$as_me:$LINENO: result: yes" >&5 -echo "${ECHO_T}yes" >&6; } + { $as_echo "$as_me:$LINENO: result: yes" >&5 +$as_echo "yes" >&6; } else - echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 - { echo "$as_me:$LINENO: result: no" >&5 -echo "${ECHO_T}no" >&6; } - { echo "$as_me:$LINENO: checking gethostbyname_r with 5 args" >&5 -echo $ECHO_N "checking gethostbyname_r with 5 args... $ECHO_C" >&6; } + { $as_echo "$as_me:$LINENO: result: no" >&5 +$as_echo "no" >&6; } + { $as_echo "$as_me:$LINENO: checking gethostbyname_r with 5 args" >&5 +$as_echo_n "checking gethostbyname_r with 5 args... " >&6; } cat >conftest.$ac_ext <<_ACEOF /* confdefs.h. */ _ACEOF @@ -21565,13 +22095,14 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_compile") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { test -z "$ac_c_werror_flag" || test ! -s conftest.err @@ -21586,18 +22117,18 @@ #define HAVE_GETHOSTBYNAME_R_5_ARG 1 _ACEOF - { echo "$as_me:$LINENO: result: yes" >&5 -echo "${ECHO_T}yes" >&6; } + { $as_echo "$as_me:$LINENO: result: yes" >&5 +$as_echo "yes" >&6; } else - echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 - { echo "$as_me:$LINENO: result: no" >&5 -echo "${ECHO_T}no" >&6; } - { echo "$as_me:$LINENO: checking gethostbyname_r with 3 args" >&5 -echo $ECHO_N "checking gethostbyname_r with 3 args... $ECHO_C" >&6; } + { $as_echo "$as_me:$LINENO: result: no" >&5 +$as_echo "no" >&6; } + { $as_echo "$as_me:$LINENO: checking gethostbyname_r with 3 args" >&5 +$as_echo_n "checking gethostbyname_r with 3 args... " >&6; } cat >conftest.$ac_ext <<_ACEOF /* confdefs.h. */ _ACEOF @@ -21627,13 +22158,14 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_compile") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { test -z "$ac_c_werror_flag" || test ! -s conftest.err @@ -21648,16 +22180,16 @@ #define HAVE_GETHOSTBYNAME_R_3_ARG 1 _ACEOF - { echo "$as_me:$LINENO: result: yes" >&5 -echo "${ECHO_T}yes" >&6; } + { $as_echo "$as_me:$LINENO: result: yes" >&5 +$as_echo "yes" >&6; } else - echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 - { echo "$as_me:$LINENO: result: no" >&5 -echo "${ECHO_T}no" >&6; } + { $as_echo "$as_me:$LINENO: result: no" >&5 +$as_echo "no" >&6; } fi @@ -21677,11 +22209,11 @@ for ac_func in gethostbyname do -as_ac_var=`echo "ac_cv_func_$ac_func" | $as_tr_sh` -{ echo "$as_me:$LINENO: checking for $ac_func" >&5 -echo $ECHO_N "checking for $ac_func... $ECHO_C" >&6; } +as_ac_var=`$as_echo "ac_cv_func_$ac_func" | $as_tr_sh` +{ $as_echo "$as_me:$LINENO: checking for $ac_func" >&5 +$as_echo_n "checking for $ac_func... " >&6; } if { as_var=$as_ac_var; eval "test \"\${$as_var+set}\" = set"; }; then - echo $ECHO_N "(cached) $ECHO_C" >&6 + $as_echo_n "(cached) " >&6 else cat >conftest.$ac_ext <<_ACEOF /* confdefs.h. */ @@ -21734,35 +22266,42 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_link") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { test -z "$ac_c_werror_flag" || test ! -s conftest.err - } && test -s conftest$ac_exeext && - $as_test_x conftest$ac_exeext; then + } && test -s conftest$ac_exeext && { + test "$cross_compiling" = yes || + $as_test_x conftest$ac_exeext + }; then eval "$as_ac_var=yes" else - echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 eval "$as_ac_var=no" fi +rm -rf conftest.dSYM rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \ conftest$ac_exeext conftest.$ac_ext fi -ac_res=`eval echo '${'$as_ac_var'}'` - { echo "$as_me:$LINENO: result: $ac_res" >&5 -echo "${ECHO_T}$ac_res" >&6; } -if test `eval echo '${'$as_ac_var'}'` = yes; then +ac_res=`eval 'as_val=${'$as_ac_var'} + $as_echo "$as_val"'` + { $as_echo "$as_me:$LINENO: result: $ac_res" >&5 +$as_echo "$ac_res" >&6; } +as_val=`eval 'as_val=${'$as_ac_var'} + $as_echo "$as_val"'` + if test "x$as_val" = x""yes; then cat >>confdefs.h <<_ACEOF -#define `echo "HAVE_$ac_func" | $as_tr_cpp` 1 +#define `$as_echo "HAVE_$ac_func" | $as_tr_cpp` 1 _ACEOF fi @@ -21781,10 +22320,10 @@ # (none yet) # Linux requires this for correct f.p. operations -{ echo "$as_me:$LINENO: checking for __fpu_control" >&5 -echo $ECHO_N "checking for __fpu_control... $ECHO_C" >&6; } +{ $as_echo "$as_me:$LINENO: checking for __fpu_control" >&5 +$as_echo_n "checking for __fpu_control... " >&6; } if test "${ac_cv_func___fpu_control+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 + $as_echo_n "(cached) " >&6 else cat >conftest.$ac_ext <<_ACEOF /* confdefs.h. */ @@ -21837,39 +22376,43 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_link") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { test -z "$ac_c_werror_flag" || test ! -s conftest.err - } && test -s conftest$ac_exeext && - $as_test_x conftest$ac_exeext; then + } && test -s conftest$ac_exeext && { + test "$cross_compiling" = yes || + $as_test_x conftest$ac_exeext + }; then ac_cv_func___fpu_control=yes else - echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 ac_cv_func___fpu_control=no fi +rm -rf conftest.dSYM rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \ conftest$ac_exeext conftest.$ac_ext fi -{ echo "$as_me:$LINENO: result: $ac_cv_func___fpu_control" >&5 -echo "${ECHO_T}$ac_cv_func___fpu_control" >&6; } -if test $ac_cv_func___fpu_control = yes; then +{ $as_echo "$as_me:$LINENO: result: $ac_cv_func___fpu_control" >&5 +$as_echo "$ac_cv_func___fpu_control" >&6; } +if test "x$ac_cv_func___fpu_control" = x""yes; then : else -{ echo "$as_me:$LINENO: checking for __fpu_control in -lieee" >&5 -echo $ECHO_N "checking for __fpu_control in -lieee... $ECHO_C" >&6; } +{ $as_echo "$as_me:$LINENO: checking for __fpu_control in -lieee" >&5 +$as_echo_n "checking for __fpu_control in -lieee... " >&6; } if test "${ac_cv_lib_ieee___fpu_control+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 + $as_echo_n "(cached) " >&6 else ac_check_lib_save_LIBS=$LIBS LIBS="-lieee $LIBS" @@ -21901,33 +22444,37 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_link") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { test -z "$ac_c_werror_flag" || test ! -s conftest.err - } && test -s conftest$ac_exeext && - $as_test_x conftest$ac_exeext; then + } && test -s conftest$ac_exeext && { + test "$cross_compiling" = yes || + $as_test_x conftest$ac_exeext + }; then ac_cv_lib_ieee___fpu_control=yes else - echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 ac_cv_lib_ieee___fpu_control=no fi +rm -rf conftest.dSYM rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \ conftest$ac_exeext conftest.$ac_ext LIBS=$ac_check_lib_save_LIBS fi -{ echo "$as_me:$LINENO: result: $ac_cv_lib_ieee___fpu_control" >&5 -echo "${ECHO_T}$ac_cv_lib_ieee___fpu_control" >&6; } -if test $ac_cv_lib_ieee___fpu_control = yes; then +{ $as_echo "$as_me:$LINENO: result: $ac_cv_lib_ieee___fpu_control" >&5 +$as_echo "$ac_cv_lib_ieee___fpu_control" >&6; } +if test "x$ac_cv_lib_ieee___fpu_control" = x""yes; then cat >>confdefs.h <<_ACEOF #define HAVE_LIBIEEE 1 _ACEOF @@ -21941,8 +22488,8 @@ # Check for --with-fpectl -{ echo "$as_me:$LINENO: checking for --with-fpectl" >&5 -echo $ECHO_N "checking for --with-fpectl... $ECHO_C" >&6; } +{ $as_echo "$as_me:$LINENO: checking for --with-fpectl" >&5 +$as_echo_n "checking for --with-fpectl... " >&6; } # Check whether --with-fpectl was given. if test "${with_fpectl+set}" = set; then @@ -21954,14 +22501,14 @@ #define WANT_SIGFPE_HANDLER 1 _ACEOF - { echo "$as_me:$LINENO: result: yes" >&5 -echo "${ECHO_T}yes" >&6; } -else { echo "$as_me:$LINENO: result: no" >&5 -echo "${ECHO_T}no" >&6; } + { $as_echo "$as_me:$LINENO: result: yes" >&5 +$as_echo "yes" >&6; } +else { $as_echo "$as_me:$LINENO: result: no" >&5 +$as_echo "no" >&6; } fi else - { echo "$as_me:$LINENO: result: no" >&5 -echo "${ECHO_T}no" >&6; } + { $as_echo "$as_me:$LINENO: result: no" >&5 +$as_echo "no" >&6; } fi @@ -21971,53 +22518,53 @@ Darwin) ;; *) LIBM=-lm esac -{ echo "$as_me:$LINENO: checking for --with-libm=STRING" >&5 -echo $ECHO_N "checking for --with-libm=STRING... $ECHO_C" >&6; } +{ $as_echo "$as_me:$LINENO: checking for --with-libm=STRING" >&5 +$as_echo_n "checking for --with-libm=STRING... " >&6; } # Check whether --with-libm was given. if test "${with_libm+set}" = set; then withval=$with_libm; if test "$withval" = no then LIBM= - { echo "$as_me:$LINENO: result: force LIBM empty" >&5 -echo "${ECHO_T}force LIBM empty" >&6; } + { $as_echo "$as_me:$LINENO: result: force LIBM empty" >&5 +$as_echo "force LIBM empty" >&6; } elif test "$withval" != yes then LIBM=$withval - { echo "$as_me:$LINENO: result: set LIBM=\"$withval\"" >&5 -echo "${ECHO_T}set LIBM=\"$withval\"" >&6; } -else { { echo "$as_me:$LINENO: error: proper usage is --with-libm=STRING" >&5 -echo "$as_me: error: proper usage is --with-libm=STRING" >&2;} + { $as_echo "$as_me:$LINENO: result: set LIBM=\"$withval\"" >&5 +$as_echo "set LIBM=\"$withval\"" >&6; } +else { { $as_echo "$as_me:$LINENO: error: proper usage is --with-libm=STRING" >&5 +$as_echo "$as_me: error: proper usage is --with-libm=STRING" >&2;} { (exit 1); exit 1; }; } fi else - { echo "$as_me:$LINENO: result: default LIBM=\"$LIBM\"" >&5 -echo "${ECHO_T}default LIBM=\"$LIBM\"" >&6; } + { $as_echo "$as_me:$LINENO: result: default LIBM=\"$LIBM\"" >&5 +$as_echo "default LIBM=\"$LIBM\"" >&6; } fi # check for --with-libc=... -{ echo "$as_me:$LINENO: checking for --with-libc=STRING" >&5 -echo $ECHO_N "checking for --with-libc=STRING... $ECHO_C" >&6; } +{ $as_echo "$as_me:$LINENO: checking for --with-libc=STRING" >&5 +$as_echo_n "checking for --with-libc=STRING... " >&6; } # Check whether --with-libc was given. if test "${with_libc+set}" = set; then withval=$with_libc; if test "$withval" = no then LIBC= - { echo "$as_me:$LINENO: result: force LIBC empty" >&5 -echo "${ECHO_T}force LIBC empty" >&6; } + { $as_echo "$as_me:$LINENO: result: force LIBC empty" >&5 +$as_echo "force LIBC empty" >&6; } elif test "$withval" != yes then LIBC=$withval - { echo "$as_me:$LINENO: result: set LIBC=\"$withval\"" >&5 -echo "${ECHO_T}set LIBC=\"$withval\"" >&6; } -else { { echo "$as_me:$LINENO: error: proper usage is --with-libc=STRING" >&5 -echo "$as_me: error: proper usage is --with-libc=STRING" >&2;} + { $as_echo "$as_me:$LINENO: result: set LIBC=\"$withval\"" >&5 +$as_echo "set LIBC=\"$withval\"" >&6; } +else { { $as_echo "$as_me:$LINENO: error: proper usage is --with-libc=STRING" >&5 +$as_echo "$as_me: error: proper usage is --with-libc=STRING" >&2;} { (exit 1); exit 1; }; } fi else - { echo "$as_me:$LINENO: result: default LIBC=\"$LIBC\"" >&5 -echo "${ECHO_T}default LIBC=\"$LIBC\"" >&6; } + { $as_echo "$as_me:$LINENO: result: default LIBC=\"$LIBC\"" >&5 +$as_echo "default LIBC=\"$LIBC\"" >&6; } fi @@ -22025,10 +22572,10 @@ # * Check for various properties of floating point * # ************************************************** -{ echo "$as_me:$LINENO: checking whether C doubles are little-endian IEEE 754 binary64" >&5 -echo $ECHO_N "checking whether C doubles are little-endian IEEE 754 binary64... $ECHO_C" >&6; } +{ $as_echo "$as_me:$LINENO: checking whether C doubles are little-endian IEEE 754 binary64" >&5 +$as_echo_n "checking whether C doubles are little-endian IEEE 754 binary64... " >&6; } if test "${ac_cv_little_endian_double+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 + $as_echo_n "(cached) " >&6 else if test "$cross_compiling" = yes; then @@ -22057,37 +22604,40 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_link") 2>&5 ac_status=$? - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { ac_try='./conftest$ac_exeext' { (case "(($ac_try" in *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_try") 2>&5 ac_status=$? - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); }; }; then ac_cv_little_endian_double=yes else - echo "$as_me: program exited with status $ac_status" >&5 -echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: program exited with status $ac_status" >&5 +$as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 ( exit $ac_status ) ac_cv_little_endian_double=no fi +rm -rf conftest.dSYM rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext conftest.$ac_objext conftest.$ac_ext fi fi -{ echo "$as_me:$LINENO: result: $ac_cv_little_endian_double" >&5 -echo "${ECHO_T}$ac_cv_little_endian_double" >&6; } +{ $as_echo "$as_me:$LINENO: result: $ac_cv_little_endian_double" >&5 +$as_echo "$ac_cv_little_endian_double" >&6; } if test "$ac_cv_little_endian_double" = yes then @@ -22097,10 +22647,10 @@ fi -{ echo "$as_me:$LINENO: checking whether C doubles are big-endian IEEE 754 binary64" >&5 -echo $ECHO_N "checking whether C doubles are big-endian IEEE 754 binary64... $ECHO_C" >&6; } +{ $as_echo "$as_me:$LINENO: checking whether C doubles are big-endian IEEE 754 binary64" >&5 +$as_echo_n "checking whether C doubles are big-endian IEEE 754 binary64... " >&6; } if test "${ac_cv_big_endian_double+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 + $as_echo_n "(cached) " >&6 else if test "$cross_compiling" = yes; then @@ -22129,37 +22679,40 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_link") 2>&5 ac_status=$? - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { ac_try='./conftest$ac_exeext' { (case "(($ac_try" in *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_try") 2>&5 ac_status=$? - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); }; }; then ac_cv_big_endian_double=yes else - echo "$as_me: program exited with status $ac_status" >&5 -echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: program exited with status $ac_status" >&5 +$as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 ( exit $ac_status ) ac_cv_big_endian_double=no fi +rm -rf conftest.dSYM rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext conftest.$ac_objext conftest.$ac_ext fi fi -{ echo "$as_me:$LINENO: result: $ac_cv_big_endian_double" >&5 -echo "${ECHO_T}$ac_cv_big_endian_double" >&6; } +{ $as_echo "$as_me:$LINENO: result: $ac_cv_big_endian_double" >&5 +$as_echo "$ac_cv_big_endian_double" >&6; } if test "$ac_cv_big_endian_double" = yes then @@ -22173,10 +22726,10 @@ # While Python doesn't currently have full support for these platforms # (see e.g., issue 1762561), we can at least make sure that float <-> string # conversions work. -{ echo "$as_me:$LINENO: checking whether C doubles are ARM mixed-endian IEEE 754 binary64" >&5 -echo $ECHO_N "checking whether C doubles are ARM mixed-endian IEEE 754 binary64... $ECHO_C" >&6; } +{ $as_echo "$as_me:$LINENO: checking whether C doubles are ARM mixed-endian IEEE 754 binary64" >&5 +$as_echo_n "checking whether C doubles are ARM mixed-endian IEEE 754 binary64... " >&6; } if test "${ac_cv_mixed_endian_double+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 + $as_echo_n "(cached) " >&6 else if test "$cross_compiling" = yes; then @@ -22205,37 +22758,40 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_link") 2>&5 ac_status=$? - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { ac_try='./conftest$ac_exeext' { (case "(($ac_try" in *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_try") 2>&5 ac_status=$? - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); }; }; then ac_cv_mixed_endian_double=yes else - echo "$as_me: program exited with status $ac_status" >&5 -echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: program exited with status $ac_status" >&5 +$as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 ( exit $ac_status ) ac_cv_mixed_endian_double=no fi +rm -rf conftest.dSYM rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext conftest.$ac_objext conftest.$ac_ext fi fi -{ echo "$as_me:$LINENO: result: $ac_cv_mixed_endian_double" >&5 -echo "${ECHO_T}$ac_cv_mixed_endian_double" >&6; } +{ $as_echo "$as_me:$LINENO: result: $ac_cv_mixed_endian_double" >&5 +$as_echo "$ac_cv_mixed_endian_double" >&6; } if test "$ac_cv_mixed_endian_double" = yes then @@ -22255,8 +22811,8 @@ then # Check that it's okay to use gcc inline assembler to get and set # x87 control word. It should be, but you never know... - { echo "$as_me:$LINENO: checking whether we can use gcc inline assembler to get and set x87 control word" >&5 -echo $ECHO_N "checking whether we can use gcc inline assembler to get and set x87 control word... $ECHO_C" >&6; } + { $as_echo "$as_me:$LINENO: checking whether we can use gcc inline assembler to get and set x87 control word" >&5 +$as_echo_n "checking whether we can use gcc inline assembler to get and set x87 control word... " >&6; } cat >conftest.$ac_ext <<_ACEOF /* confdefs.h. */ _ACEOF @@ -22282,28 +22838,29 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_compile") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { test -z "$ac_c_werror_flag" || test ! -s conftest.err } && test -s conftest.$ac_objext; then have_gcc_asm_for_x87=yes else - echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 have_gcc_asm_for_x87=no fi rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext - { echo "$as_me:$LINENO: result: $have_gcc_asm_for_x87" >&5 -echo "${ECHO_T}$have_gcc_asm_for_x87" >&6; } + { $as_echo "$as_me:$LINENO: result: $have_gcc_asm_for_x87" >&5 +$as_echo "$have_gcc_asm_for_x87" >&6; } if test "$have_gcc_asm_for_x87" = yes then @@ -22319,8 +22876,8 @@ # IEEE 754 platforms. On IEEE 754, test should return 1 if rounding # mode is round-to-nearest and double rounding issues are present, and # 0 otherwise. See http://bugs.python.org/issue2937 for more info. -{ echo "$as_me:$LINENO: checking for x87-style double rounding" >&5 -echo $ECHO_N "checking for x87-style double rounding... $ECHO_C" >&6; } +{ $as_echo "$as_me:$LINENO: checking for x87-style double rounding" >&5 +$as_echo_n "checking for x87-style double rounding... " >&6; } # $BASECFLAGS may affect the result ac_save_cc="$CC" CC="$CC $BASECFLAGS" @@ -22360,36 +22917,39 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_link") 2>&5 ac_status=$? - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { ac_try='./conftest$ac_exeext' { (case "(($ac_try" in *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_try") 2>&5 ac_status=$? - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); }; }; then ac_cv_x87_double_rounding=no else - echo "$as_me: program exited with status $ac_status" >&5 -echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: program exited with status $ac_status" >&5 +$as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 ( exit $ac_status ) ac_cv_x87_double_rounding=yes fi +rm -rf conftest.dSYM rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext conftest.$ac_objext conftest.$ac_ext fi CC="$ac_save_cc" -{ echo "$as_me:$LINENO: result: $ac_cv_x87_double_rounding" >&5 -echo "${ECHO_T}$ac_cv_x87_double_rounding" >&6; } +{ $as_echo "$as_me:$LINENO: result: $ac_cv_x87_double_rounding" >&5 +$as_echo "$ac_cv_x87_double_rounding" >&6; } if test "$ac_cv_x87_double_rounding" = yes then @@ -22408,10 +22968,10 @@ # On FreeBSD 6.2, it appears that tanh(-0.) returns 0. instead of # -0. on some architectures. -{ echo "$as_me:$LINENO: checking whether tanh preserves the sign of zero" >&5 -echo $ECHO_N "checking whether tanh preserves the sign of zero... $ECHO_C" >&6; } +{ $as_echo "$as_me:$LINENO: checking whether tanh preserves the sign of zero" >&5 +$as_echo_n "checking whether tanh preserves the sign of zero... " >&6; } if test "${ac_cv_tanh_preserves_zero_sign+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 + $as_echo_n "(cached) " >&6 else if test "$cross_compiling" = yes; then @@ -22442,37 +23002,40 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_link") 2>&5 ac_status=$? - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { ac_try='./conftest$ac_exeext' { (case "(($ac_try" in *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_try") 2>&5 ac_status=$? - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); }; }; then ac_cv_tanh_preserves_zero_sign=yes else - echo "$as_me: program exited with status $ac_status" >&5 -echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: program exited with status $ac_status" >&5 +$as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 ( exit $ac_status ) ac_cv_tanh_preserves_zero_sign=no fi +rm -rf conftest.dSYM rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext conftest.$ac_objext conftest.$ac_ext fi fi -{ echo "$as_me:$LINENO: result: $ac_cv_tanh_preserves_zero_sign" >&5 -echo "${ECHO_T}$ac_cv_tanh_preserves_zero_sign" >&6; } +{ $as_echo "$as_me:$LINENO: result: $ac_cv_tanh_preserves_zero_sign" >&5 +$as_echo "$ac_cv_tanh_preserves_zero_sign" >&6; } if test "$ac_cv_tanh_preserves_zero_sign" = yes then @@ -22493,11 +23056,11 @@ for ac_func in acosh asinh atanh copysign expm1 finite hypot log1p round do -as_ac_var=`echo "ac_cv_func_$ac_func" | $as_tr_sh` -{ echo "$as_me:$LINENO: checking for $ac_func" >&5 -echo $ECHO_N "checking for $ac_func... $ECHO_C" >&6; } +as_ac_var=`$as_echo "ac_cv_func_$ac_func" | $as_tr_sh` +{ $as_echo "$as_me:$LINENO: checking for $ac_func" >&5 +$as_echo_n "checking for $ac_func... " >&6; } if { as_var=$as_ac_var; eval "test \"\${$as_var+set}\" = set"; }; then - echo $ECHO_N "(cached) $ECHO_C" >&6 + $as_echo_n "(cached) " >&6 else cat >conftest.$ac_ext <<_ACEOF /* confdefs.h. */ @@ -22550,44 +23113,51 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_link") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { test -z "$ac_c_werror_flag" || test ! -s conftest.err - } && test -s conftest$ac_exeext && - $as_test_x conftest$ac_exeext; then + } && test -s conftest$ac_exeext && { + test "$cross_compiling" = yes || + $as_test_x conftest$ac_exeext + }; then eval "$as_ac_var=yes" else - echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 eval "$as_ac_var=no" fi +rm -rf conftest.dSYM rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \ conftest$ac_exeext conftest.$ac_ext fi -ac_res=`eval echo '${'$as_ac_var'}'` - { echo "$as_me:$LINENO: result: $ac_res" >&5 -echo "${ECHO_T}$ac_res" >&6; } -if test `eval echo '${'$as_ac_var'}'` = yes; then +ac_res=`eval 'as_val=${'$as_ac_var'} + $as_echo "$as_val"'` + { $as_echo "$as_me:$LINENO: result: $ac_res" >&5 +$as_echo "$ac_res" >&6; } +as_val=`eval 'as_val=${'$as_ac_var'} + $as_echo "$as_val"'` + if test "x$as_val" = x""yes; then cat >>confdefs.h <<_ACEOF -#define `echo "HAVE_$ac_func" | $as_tr_cpp` 1 +#define `$as_echo "HAVE_$ac_func" | $as_tr_cpp` 1 _ACEOF fi done -{ echo "$as_me:$LINENO: checking whether isinf is declared" >&5 -echo $ECHO_N "checking whether isinf is declared... $ECHO_C" >&6; } +{ $as_echo "$as_me:$LINENO: checking whether isinf is declared" >&5 +$as_echo_n "checking whether isinf is declared... " >&6; } if test "${ac_cv_have_decl_isinf+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 + $as_echo_n "(cached) " >&6 else cat >conftest.$ac_ext <<_ACEOF /* confdefs.h. */ @@ -22614,20 +23184,21 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_compile") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { test -z "$ac_c_werror_flag" || test ! -s conftest.err } && test -s conftest.$ac_objext; then ac_cv_have_decl_isinf=yes else - echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 ac_cv_have_decl_isinf=no @@ -22635,9 +23206,9 @@ rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext fi -{ echo "$as_me:$LINENO: result: $ac_cv_have_decl_isinf" >&5 -echo "${ECHO_T}$ac_cv_have_decl_isinf" >&6; } -if test $ac_cv_have_decl_isinf = yes; then +{ $as_echo "$as_me:$LINENO: result: $ac_cv_have_decl_isinf" >&5 +$as_echo "$ac_cv_have_decl_isinf" >&6; } +if test "x$ac_cv_have_decl_isinf" = x""yes; then cat >>confdefs.h <<_ACEOF #define HAVE_DECL_ISINF 1 @@ -22651,10 +23222,10 @@ fi -{ echo "$as_me:$LINENO: checking whether isnan is declared" >&5 -echo $ECHO_N "checking whether isnan is declared... $ECHO_C" >&6; } +{ $as_echo "$as_me:$LINENO: checking whether isnan is declared" >&5 +$as_echo_n "checking whether isnan is declared... " >&6; } if test "${ac_cv_have_decl_isnan+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 + $as_echo_n "(cached) " >&6 else cat >conftest.$ac_ext <<_ACEOF /* confdefs.h. */ @@ -22681,20 +23252,21 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_compile") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { test -z "$ac_c_werror_flag" || test ! -s conftest.err } && test -s conftest.$ac_objext; then ac_cv_have_decl_isnan=yes else - echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 ac_cv_have_decl_isnan=no @@ -22702,9 +23274,9 @@ rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext fi -{ echo "$as_me:$LINENO: result: $ac_cv_have_decl_isnan" >&5 -echo "${ECHO_T}$ac_cv_have_decl_isnan" >&6; } -if test $ac_cv_have_decl_isnan = yes; then +{ $as_echo "$as_me:$LINENO: result: $ac_cv_have_decl_isnan" >&5 +$as_echo "$ac_cv_have_decl_isnan" >&6; } +if test "x$ac_cv_have_decl_isnan" = x""yes; then cat >>confdefs.h <<_ACEOF #define HAVE_DECL_ISNAN 1 @@ -22718,10 +23290,10 @@ fi -{ echo "$as_me:$LINENO: checking whether isfinite is declared" >&5 -echo $ECHO_N "checking whether isfinite is declared... $ECHO_C" >&6; } +{ $as_echo "$as_me:$LINENO: checking whether isfinite is declared" >&5 +$as_echo_n "checking whether isfinite is declared... " >&6; } if test "${ac_cv_have_decl_isfinite+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 + $as_echo_n "(cached) " >&6 else cat >conftest.$ac_ext <<_ACEOF /* confdefs.h. */ @@ -22748,20 +23320,21 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_compile") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { test -z "$ac_c_werror_flag" || test ! -s conftest.err } && test -s conftest.$ac_objext; then ac_cv_have_decl_isfinite=yes else - echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 ac_cv_have_decl_isfinite=no @@ -22769,9 +23342,9 @@ rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext fi -{ echo "$as_me:$LINENO: result: $ac_cv_have_decl_isfinite" >&5 -echo "${ECHO_T}$ac_cv_have_decl_isfinite" >&6; } -if test $ac_cv_have_decl_isfinite = yes; then +{ $as_echo "$as_me:$LINENO: result: $ac_cv_have_decl_isfinite" >&5 +$as_echo "$ac_cv_have_decl_isfinite" >&6; } +if test "x$ac_cv_have_decl_isfinite" = x""yes; then cat >>confdefs.h <<_ACEOF #define HAVE_DECL_ISFINITE 1 @@ -22795,10 +23368,10 @@ # the kernel module that provides POSIX semaphores # isn't loaded by default, so an attempt to call # sem_open results in a 'Signal 12' error. -{ echo "$as_me:$LINENO: checking whether POSIX semaphores are enabled" >&5 -echo $ECHO_N "checking whether POSIX semaphores are enabled... $ECHO_C" >&6; } +{ $as_echo "$as_me:$LINENO: checking whether POSIX semaphores are enabled" >&5 +$as_echo_n "checking whether POSIX semaphores are enabled... " >&6; } if test "${ac_cv_posix_semaphores_enabled+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 + $as_echo_n "(cached) " >&6 else if test "$cross_compiling" = yes; then ac_cv_posix_semaphores_enabled=yes @@ -22834,29 +23407,32 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_link") 2>&5 ac_status=$? - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { ac_try='./conftest$ac_exeext' { (case "(($ac_try" in *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_try") 2>&5 ac_status=$? - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); }; }; then ac_cv_posix_semaphores_enabled=yes else - echo "$as_me: program exited with status $ac_status" >&5 -echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: program exited with status $ac_status" >&5 +$as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 ( exit $ac_status ) ac_cv_posix_semaphores_enabled=no fi +rm -rf conftest.dSYM rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext conftest.$ac_objext conftest.$ac_ext fi @@ -22864,8 +23440,8 @@ fi -{ echo "$as_me:$LINENO: result: $ac_cv_posix_semaphores_enabled" >&5 -echo "${ECHO_T}$ac_cv_posix_semaphores_enabled" >&6; } +{ $as_echo "$as_me:$LINENO: result: $ac_cv_posix_semaphores_enabled" >&5 +$as_echo "$ac_cv_posix_semaphores_enabled" >&6; } if test $ac_cv_posix_semaphores_enabled = no then @@ -22876,14 +23452,16 @@ fi # Multiprocessing check for broken sem_getvalue -{ echo "$as_me:$LINENO: checking for broken sem_getvalue" >&5 -echo $ECHO_N "checking for broken sem_getvalue... $ECHO_C" >&6; } +{ $as_echo "$as_me:$LINENO: checking for broken sem_getvalue" >&5 +$as_echo_n "checking for broken sem_getvalue... " >&6; } if test "$cross_compiling" = yes; then - { { echo "$as_me:$LINENO: error: cannot run test program while cross compiling + { { $as_echo "$as_me:$LINENO: error: in \`$ac_pwd':" >&5 +$as_echo "$as_me: error: in \`$ac_pwd':" >&2;} +{ { $as_echo "$as_me:$LINENO: error: cannot run test program while cross compiling See \`config.log' for more details." >&5 -echo "$as_me: error: cannot run test program while cross compiling +$as_echo "$as_me: error: cannot run test program while cross compiling See \`config.log' for more details." >&2;} - { (exit 1); exit 1; }; } + { (exit 1); exit 1; }; }; } else cat >conftest.$ac_ext <<_ACEOF /* confdefs.h. */ @@ -22921,30 +23499,32 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_link") 2>&5 ac_status=$? - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { ac_try='./conftest$ac_exeext' { (case "(($ac_try" in *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_try") 2>&5 ac_status=$? - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); }; }; then - { echo "$as_me:$LINENO: result: no" >&5 -echo "${ECHO_T}no" >&6; } + { $as_echo "$as_me:$LINENO: result: no" >&5 +$as_echo "no" >&6; } else - echo "$as_me: program exited with status $ac_status" >&5 -echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: program exited with status $ac_status" >&5 +$as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 ( exit $ac_status ) -{ echo "$as_me:$LINENO: result: yes" >&5 -echo "${ECHO_T}yes" >&6; } +{ $as_echo "$as_me:$LINENO: result: yes" >&5 +$as_echo "yes" >&6; } cat >>confdefs.h <<\_ACEOF #define HAVE_BROKEN_SEM_GETVALUE 1 @@ -22952,14 +23532,15 @@ fi +rm -rf conftest.dSYM rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext conftest.$ac_objext conftest.$ac_ext fi # determine what size digit to use for Python's longs -{ echo "$as_me:$LINENO: checking digit size for Python's longs" >&5 -echo $ECHO_N "checking digit size for Python's longs... $ECHO_C" >&6; } +{ $as_echo "$as_me:$LINENO: checking digit size for Python's longs" >&5 +$as_echo_n "checking digit size for Python's longs... " >&6; } # Check whether --enable-big-digits was given. if test "${enable_big_digits+set}" = set; then enableval=$enable_big_digits; case $enable_big_digits in @@ -22970,12 +23551,12 @@ 15|30) ;; *) - { { echo "$as_me:$LINENO: error: bad value $enable_big_digits for --enable-big-digits; value should be 15 or 30" >&5 -echo "$as_me: error: bad value $enable_big_digits for --enable-big-digits; value should be 15 or 30" >&2;} + { { $as_echo "$as_me:$LINENO: error: bad value $enable_big_digits for --enable-big-digits; value should be 15 or 30" >&5 +$as_echo "$as_me: error: bad value $enable_big_digits for --enable-big-digits; value should be 15 or 30" >&2;} { (exit 1); exit 1; }; } ;; esac -{ echo "$as_me:$LINENO: result: $enable_big_digits" >&5 -echo "${ECHO_T}$enable_big_digits" >&6; } +{ $as_echo "$as_me:$LINENO: result: $enable_big_digits" >&5 +$as_echo "$enable_big_digits" >&6; } cat >>confdefs.h <<_ACEOF #define PYLONG_BITS_IN_DIGIT $enable_big_digits @@ -22983,24 +23564,24 @@ else - { echo "$as_me:$LINENO: result: no value specified" >&5 -echo "${ECHO_T}no value specified" >&6; } + { $as_echo "$as_me:$LINENO: result: no value specified" >&5 +$as_echo "no value specified" >&6; } fi # check for wchar.h if test "${ac_cv_header_wchar_h+set}" = set; then - { echo "$as_me:$LINENO: checking for wchar.h" >&5 -echo $ECHO_N "checking for wchar.h... $ECHO_C" >&6; } + { $as_echo "$as_me:$LINENO: checking for wchar.h" >&5 +$as_echo_n "checking for wchar.h... " >&6; } if test "${ac_cv_header_wchar_h+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 + $as_echo_n "(cached) " >&6 fi -{ echo "$as_me:$LINENO: result: $ac_cv_header_wchar_h" >&5 -echo "${ECHO_T}$ac_cv_header_wchar_h" >&6; } +{ $as_echo "$as_me:$LINENO: result: $ac_cv_header_wchar_h" >&5 +$as_echo "$ac_cv_header_wchar_h" >&6; } else # Is the header compilable? -{ echo "$as_me:$LINENO: checking wchar.h usability" >&5 -echo $ECHO_N "checking wchar.h usability... $ECHO_C" >&6; } +{ $as_echo "$as_me:$LINENO: checking wchar.h usability" >&5 +$as_echo_n "checking wchar.h usability... " >&6; } cat >conftest.$ac_ext <<_ACEOF /* confdefs.h. */ _ACEOF @@ -23016,32 +23597,33 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_compile") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { test -z "$ac_c_werror_flag" || test ! -s conftest.err } && test -s conftest.$ac_objext; then ac_header_compiler=yes else - echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 ac_header_compiler=no fi rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext -{ echo "$as_me:$LINENO: result: $ac_header_compiler" >&5 -echo "${ECHO_T}$ac_header_compiler" >&6; } +{ $as_echo "$as_me:$LINENO: result: $ac_header_compiler" >&5 +$as_echo "$ac_header_compiler" >&6; } # Is the header present? -{ echo "$as_me:$LINENO: checking wchar.h presence" >&5 -echo $ECHO_N "checking wchar.h presence... $ECHO_C" >&6; } +{ $as_echo "$as_me:$LINENO: checking wchar.h presence" >&5 +$as_echo_n "checking wchar.h presence... " >&6; } cat >conftest.$ac_ext <<_ACEOF /* confdefs.h. */ _ACEOF @@ -23055,51 +23637,52 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_cpp conftest.$ac_ext") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } >/dev/null && { test -z "$ac_c_preproc_warn_flag$ac_c_werror_flag" || test ! -s conftest.err }; then ac_header_preproc=yes else - echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 ac_header_preproc=no fi rm -f conftest.err conftest.$ac_ext -{ echo "$as_me:$LINENO: result: $ac_header_preproc" >&5 -echo "${ECHO_T}$ac_header_preproc" >&6; } +{ $as_echo "$as_me:$LINENO: result: $ac_header_preproc" >&5 +$as_echo "$ac_header_preproc" >&6; } # So? What about this header? case $ac_header_compiler:$ac_header_preproc:$ac_c_preproc_warn_flag in yes:no: ) - { echo "$as_me:$LINENO: WARNING: wchar.h: accepted by the compiler, rejected by the preprocessor!" >&5 -echo "$as_me: WARNING: wchar.h: accepted by the compiler, rejected by the preprocessor!" >&2;} - { echo "$as_me:$LINENO: WARNING: wchar.h: proceeding with the compiler's result" >&5 -echo "$as_me: WARNING: wchar.h: proceeding with the compiler's result" >&2;} + { $as_echo "$as_me:$LINENO: WARNING: wchar.h: accepted by the compiler, rejected by the preprocessor!" >&5 +$as_echo "$as_me: WARNING: wchar.h: accepted by the compiler, rejected by the preprocessor!" >&2;} + { $as_echo "$as_me:$LINENO: WARNING: wchar.h: proceeding with the compiler's result" >&5 +$as_echo "$as_me: WARNING: wchar.h: proceeding with the compiler's result" >&2;} ac_header_preproc=yes ;; no:yes:* ) - { echo "$as_me:$LINENO: WARNING: wchar.h: present but cannot be compiled" >&5 -echo "$as_me: WARNING: wchar.h: present but cannot be compiled" >&2;} - { echo "$as_me:$LINENO: WARNING: wchar.h: check for missing prerequisite headers?" >&5 -echo "$as_me: WARNING: wchar.h: check for missing prerequisite headers?" >&2;} - { echo "$as_me:$LINENO: WARNING: wchar.h: see the Autoconf documentation" >&5 -echo "$as_me: WARNING: wchar.h: see the Autoconf documentation" >&2;} - { echo "$as_me:$LINENO: WARNING: wchar.h: section \"Present But Cannot Be Compiled\"" >&5 -echo "$as_me: WARNING: wchar.h: section \"Present But Cannot Be Compiled\"" >&2;} - { echo "$as_me:$LINENO: WARNING: wchar.h: proceeding with the preprocessor's result" >&5 -echo "$as_me: WARNING: wchar.h: proceeding with the preprocessor's result" >&2;} - { echo "$as_me:$LINENO: WARNING: wchar.h: in the future, the compiler will take precedence" >&5 -echo "$as_me: WARNING: wchar.h: in the future, the compiler will take precedence" >&2;} + { $as_echo "$as_me:$LINENO: WARNING: wchar.h: present but cannot be compiled" >&5 +$as_echo "$as_me: WARNING: wchar.h: present but cannot be compiled" >&2;} + { $as_echo "$as_me:$LINENO: WARNING: wchar.h: check for missing prerequisite headers?" >&5 +$as_echo "$as_me: WARNING: wchar.h: check for missing prerequisite headers?" >&2;} + { $as_echo "$as_me:$LINENO: WARNING: wchar.h: see the Autoconf documentation" >&5 +$as_echo "$as_me: WARNING: wchar.h: see the Autoconf documentation" >&2;} + { $as_echo "$as_me:$LINENO: WARNING: wchar.h: section \"Present But Cannot Be Compiled\"" >&5 +$as_echo "$as_me: WARNING: wchar.h: section \"Present But Cannot Be Compiled\"" >&2;} + { $as_echo "$as_me:$LINENO: WARNING: wchar.h: proceeding with the preprocessor's result" >&5 +$as_echo "$as_me: WARNING: wchar.h: proceeding with the preprocessor's result" >&2;} + { $as_echo "$as_me:$LINENO: WARNING: wchar.h: in the future, the compiler will take precedence" >&5 +$as_echo "$as_me: WARNING: wchar.h: in the future, the compiler will take precedence" >&2;} ( cat <<\_ASBOX ## -------------------------------------- ## ## Report this to http://bugs.python.org/ ## @@ -23108,18 +23691,18 @@ ) | sed "s/^/$as_me: WARNING: /" >&2 ;; esac -{ echo "$as_me:$LINENO: checking for wchar.h" >&5 -echo $ECHO_N "checking for wchar.h... $ECHO_C" >&6; } +{ $as_echo "$as_me:$LINENO: checking for wchar.h" >&5 +$as_echo_n "checking for wchar.h... " >&6; } if test "${ac_cv_header_wchar_h+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 + $as_echo_n "(cached) " >&6 else ac_cv_header_wchar_h=$ac_header_preproc fi -{ echo "$as_me:$LINENO: result: $ac_cv_header_wchar_h" >&5 -echo "${ECHO_T}$ac_cv_header_wchar_h" >&6; } +{ $as_echo "$as_me:$LINENO: result: $ac_cv_header_wchar_h" >&5 +$as_echo "$ac_cv_header_wchar_h" >&6; } fi -if test $ac_cv_header_wchar_h = yes; then +if test "x$ac_cv_header_wchar_h" = x""yes; then cat >>confdefs.h <<\_ACEOF @@ -23138,69 +23721,14 @@ # determine wchar_t size if test "$wchar_h" = yes then - { echo "$as_me:$LINENO: checking for wchar_t" >&5 -echo $ECHO_N "checking for wchar_t... $ECHO_C" >&6; } -if test "${ac_cv_type_wchar_t+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 -else - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -#include - -typedef wchar_t ac__type_new_; -int -main () -{ -if ((ac__type_new_ *) 0) - return 0; -if (sizeof (ac__type_new_)) - return 0; - ; - return 0; -} -_ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - ac_cv_type_wchar_t=yes -else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - ac_cv_type_wchar_t=no -fi - -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext -fi -{ echo "$as_me:$LINENO: result: $ac_cv_type_wchar_t" >&5 -echo "${ECHO_T}$ac_cv_type_wchar_t" >&6; } - -# The cast to long int works around a bug in the HP C Compiler + # The cast to long int works around a bug in the HP C Compiler # version HP92453-01 B.11.11.23709.GP, which incorrectly rejects # declarations like `int a3[[(sizeof (unsigned char)) >= 0]];'. # This bug is HP SR number 8606223364. -{ echo "$as_me:$LINENO: checking size of wchar_t" >&5 -echo $ECHO_N "checking size of wchar_t... $ECHO_C" >&6; } +{ $as_echo "$as_me:$LINENO: checking size of wchar_t" >&5 +$as_echo_n "checking size of wchar_t... " >&6; } if test "${ac_cv_sizeof_wchar_t+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 + $as_echo_n "(cached) " >&6 else if test "$cross_compiling" = yes; then # Depending upon the size, compute the lo and hi bounds. @@ -23212,11 +23740,10 @@ /* end confdefs.h. */ #include - typedef wchar_t ac__type_sizeof_; int main () { -static int test_array [1 - 2 * !(((long int) (sizeof (ac__type_sizeof_))) >= 0)]; +static int test_array [1 - 2 * !(((long int) (sizeof (wchar_t))) >= 0)]; test_array [0] = 0 ; @@ -23229,13 +23756,14 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_compile") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { test -z "$ac_c_werror_flag" || test ! -s conftest.err @@ -23250,11 +23778,10 @@ /* end confdefs.h. */ #include - typedef wchar_t ac__type_sizeof_; int main () { -static int test_array [1 - 2 * !(((long int) (sizeof (ac__type_sizeof_))) <= $ac_mid)]; +static int test_array [1 - 2 * !(((long int) (sizeof (wchar_t))) <= $ac_mid)]; test_array [0] = 0 ; @@ -23267,20 +23794,21 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_compile") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { test -z "$ac_c_werror_flag" || test ! -s conftest.err } && test -s conftest.$ac_objext; then ac_hi=$ac_mid; break else - echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 ac_lo=`expr $ac_mid + 1` @@ -23294,7 +23822,7 @@ rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext done else - echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 cat >conftest.$ac_ext <<_ACEOF @@ -23305,11 +23833,10 @@ /* end confdefs.h. */ #include - typedef wchar_t ac__type_sizeof_; int main () { -static int test_array [1 - 2 * !(((long int) (sizeof (ac__type_sizeof_))) < 0)]; +static int test_array [1 - 2 * !(((long int) (sizeof (wchar_t))) < 0)]; test_array [0] = 0 ; @@ -23322,13 +23849,14 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_compile") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { test -z "$ac_c_werror_flag" || test ! -s conftest.err @@ -23343,11 +23871,10 @@ /* end confdefs.h. */ #include - typedef wchar_t ac__type_sizeof_; int main () { -static int test_array [1 - 2 * !(((long int) (sizeof (ac__type_sizeof_))) >= $ac_mid)]; +static int test_array [1 - 2 * !(((long int) (sizeof (wchar_t))) >= $ac_mid)]; test_array [0] = 0 ; @@ -23360,20 +23887,21 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_compile") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { test -z "$ac_c_werror_flag" || test ! -s conftest.err } && test -s conftest.$ac_objext; then ac_lo=$ac_mid; break else - echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 ac_hi=`expr '(' $ac_mid ')' - 1` @@ -23387,7 +23915,7 @@ rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext done else - echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 ac_lo= ac_hi= @@ -23408,11 +23936,10 @@ /* end confdefs.h. */ #include - typedef wchar_t ac__type_sizeof_; int main () { -static int test_array [1 - 2 * !(((long int) (sizeof (ac__type_sizeof_))) <= $ac_mid)]; +static int test_array [1 - 2 * !(((long int) (sizeof (wchar_t))) <= $ac_mid)]; test_array [0] = 0 ; @@ -23425,20 +23952,21 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_compile") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { test -z "$ac_c_werror_flag" || test ! -s conftest.err } && test -s conftest.$ac_objext; then ac_hi=$ac_mid else - echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 ac_lo=`expr '(' $ac_mid ')' + 1` @@ -23449,11 +23977,13 @@ case $ac_lo in ?*) ac_cv_sizeof_wchar_t=$ac_lo;; '') if test "$ac_cv_type_wchar_t" = yes; then - { { echo "$as_me:$LINENO: error: cannot compute sizeof (wchar_t) + { { $as_echo "$as_me:$LINENO: error: in \`$ac_pwd':" >&5 +$as_echo "$as_me: error: in \`$ac_pwd':" >&2;} +{ { $as_echo "$as_me:$LINENO: error: cannot compute sizeof (wchar_t) See \`config.log' for more details." >&5 -echo "$as_me: error: cannot compute sizeof (wchar_t) +$as_echo "$as_me: error: cannot compute sizeof (wchar_t) See \`config.log' for more details." >&2;} - { (exit 77); exit 77; }; } + { (exit 77); exit 77; }; }; } else ac_cv_sizeof_wchar_t=0 fi ;; @@ -23467,9 +23997,8 @@ /* end confdefs.h. */ #include - typedef wchar_t ac__type_sizeof_; -static long int longval () { return (long int) (sizeof (ac__type_sizeof_)); } -static unsigned long int ulongval () { return (long int) (sizeof (ac__type_sizeof_)); } +static long int longval () { return (long int) (sizeof (wchar_t)); } +static unsigned long int ulongval () { return (long int) (sizeof (wchar_t)); } #include #include int @@ -23479,20 +24008,22 @@ FILE *f = fopen ("conftest.val", "w"); if (! f) return 1; - if (((long int) (sizeof (ac__type_sizeof_))) < 0) + if (((long int) (sizeof (wchar_t))) < 0) { long int i = longval (); - if (i != ((long int) (sizeof (ac__type_sizeof_)))) + if (i != ((long int) (sizeof (wchar_t)))) return 1; - fprintf (f, "%ld\n", i); + fprintf (f, "%ld", i); } else { unsigned long int i = ulongval (); - if (i != ((long int) (sizeof (ac__type_sizeof_)))) + if (i != ((long int) (sizeof (wchar_t)))) return 1; - fprintf (f, "%lu\n", i); + fprintf (f, "%lu", i); } + /* Do not output a trailing newline, as this causes \r\n confusion + on some platforms. */ return ferror (f) || fclose (f) != 0; ; @@ -23505,43 +24036,48 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_link") 2>&5 ac_status=$? - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { ac_try='./conftest$ac_exeext' { (case "(($ac_try" in *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_try") 2>&5 ac_status=$? - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); }; }; then ac_cv_sizeof_wchar_t=`cat conftest.val` else - echo "$as_me: program exited with status $ac_status" >&5 -echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: program exited with status $ac_status" >&5 +$as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 ( exit $ac_status ) if test "$ac_cv_type_wchar_t" = yes; then - { { echo "$as_me:$LINENO: error: cannot compute sizeof (wchar_t) + { { $as_echo "$as_me:$LINENO: error: in \`$ac_pwd':" >&5 +$as_echo "$as_me: error: in \`$ac_pwd':" >&2;} +{ { $as_echo "$as_me:$LINENO: error: cannot compute sizeof (wchar_t) See \`config.log' for more details." >&5 -echo "$as_me: error: cannot compute sizeof (wchar_t) +$as_echo "$as_me: error: cannot compute sizeof (wchar_t) See \`config.log' for more details." >&2;} - { (exit 77); exit 77; }; } + { (exit 77); exit 77; }; }; } else ac_cv_sizeof_wchar_t=0 fi fi +rm -rf conftest.dSYM rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext conftest.$ac_objext conftest.$ac_ext fi rm -f conftest.val fi -{ echo "$as_me:$LINENO: result: $ac_cv_sizeof_wchar_t" >&5 -echo "${ECHO_T}$ac_cv_sizeof_wchar_t" >&6; } +{ $as_echo "$as_me:$LINENO: result: $ac_cv_sizeof_wchar_t" >&5 +$as_echo "$ac_cv_sizeof_wchar_t" >&6; } @@ -23552,8 +24088,8 @@ fi -{ echo "$as_me:$LINENO: checking for UCS-4 tcl" >&5 -echo $ECHO_N "checking for UCS-4 tcl... $ECHO_C" >&6; } +{ $as_echo "$as_me:$LINENO: checking for UCS-4 tcl" >&5 +$as_echo_n "checking for UCS-4 tcl... " >&6; } have_ucs4_tcl=no cat >conftest.$ac_ext <<_ACEOF /* confdefs.h. */ @@ -23580,13 +24116,14 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_compile") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { test -z "$ac_c_werror_flag" || test ! -s conftest.err @@ -23600,24 +24137,24 @@ have_ucs4_tcl=yes else - echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 fi rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext -{ echo "$as_me:$LINENO: result: $have_ucs4_tcl" >&5 -echo "${ECHO_T}$have_ucs4_tcl" >&6; } +{ $as_echo "$as_me:$LINENO: result: $have_ucs4_tcl" >&5 +$as_echo "$have_ucs4_tcl" >&6; } # check whether wchar_t is signed or not if test "$wchar_h" = yes then # check whether wchar_t is signed or not - { echo "$as_me:$LINENO: checking whether wchar_t is signed" >&5 -echo $ECHO_N "checking whether wchar_t is signed... $ECHO_C" >&6; } + { $as_echo "$as_me:$LINENO: checking whether wchar_t is signed" >&5 +$as_echo_n "checking whether wchar_t is signed... " >&6; } if test "${ac_cv_wchar_t_signed+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 + $as_echo_n "(cached) " >&6 else if test "$cross_compiling" = yes; then @@ -23644,41 +24181,44 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_link") 2>&5 ac_status=$? - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { ac_try='./conftest$ac_exeext' { (case "(($ac_try" in *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_try") 2>&5 ac_status=$? - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); }; }; then ac_cv_wchar_t_signed=yes else - echo "$as_me: program exited with status $ac_status" >&5 -echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: program exited with status $ac_status" >&5 +$as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 ( exit $ac_status ) ac_cv_wchar_t_signed=no fi +rm -rf conftest.dSYM rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext conftest.$ac_objext conftest.$ac_ext fi fi - { echo "$as_me:$LINENO: result: $ac_cv_wchar_t_signed" >&5 -echo "${ECHO_T}$ac_cv_wchar_t_signed" >&6; } + { $as_echo "$as_me:$LINENO: result: $ac_cv_wchar_t_signed" >&5 +$as_echo "$ac_cv_wchar_t_signed" >&6; } fi -{ echo "$as_me:$LINENO: checking what type to use for str" >&5 -echo $ECHO_N "checking what type to use for str... $ECHO_C" >&6; } +{ $as_echo "$as_me:$LINENO: checking what type to use for str" >&5 +$as_echo_n "checking what type to use for str... " >&6; } # Check whether --with-wide-unicode was given. if test "${with_wide_unicode+set}" = set; then @@ -23728,49 +24268,195 @@ #define PY_UNICODE_TYPE wchar_t _ACEOF -elif test "$ac_cv_sizeof_short" = "$unicode_size" -then - PY_UNICODE_TYPE="unsigned short" - cat >>confdefs.h <<\_ACEOF -#define PY_UNICODE_TYPE unsigned short +elif test "$ac_cv_sizeof_short" = "$unicode_size" +then + PY_UNICODE_TYPE="unsigned short" + cat >>confdefs.h <<\_ACEOF +#define PY_UNICODE_TYPE unsigned short +_ACEOF + +elif test "$ac_cv_sizeof_long" = "$unicode_size" +then + PY_UNICODE_TYPE="unsigned long" + cat >>confdefs.h <<\_ACEOF +#define PY_UNICODE_TYPE unsigned long +_ACEOF + +else + PY_UNICODE_TYPE="no type found" +fi +{ $as_echo "$as_me:$LINENO: result: $PY_UNICODE_TYPE" >&5 +$as_echo "$PY_UNICODE_TYPE" >&6; } + +# check for endianness + + { $as_echo "$as_me:$LINENO: checking whether byte ordering is bigendian" >&5 +$as_echo_n "checking whether byte ordering is bigendian... " >&6; } +if test "${ac_cv_c_bigendian+set}" = set; then + $as_echo_n "(cached) " >&6 +else + ac_cv_c_bigendian=unknown + # See if we're dealing with a universal compiler. + cat >conftest.$ac_ext <<_ACEOF +/* confdefs.h. */ +_ACEOF +cat confdefs.h >>conftest.$ac_ext +cat >>conftest.$ac_ext <<_ACEOF +/* end confdefs.h. */ +#ifndef __APPLE_CC__ + not a universal capable compiler + #endif + typedef int dummy; + +_ACEOF +rm -f conftest.$ac_objext +if { (ac_try="$ac_compile" +case "(($ac_try" in + *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; + *) ac_try_echo=$ac_try;; +esac +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 + (eval "$ac_compile") 2>conftest.er1 + ac_status=$? + grep -v '^ *+' conftest.er1 >conftest.err + rm -f conftest.er1 + cat conftest.err >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 + (exit $ac_status); } && { + test -z "$ac_c_werror_flag" || + test ! -s conftest.err + } && test -s conftest.$ac_objext; then + + # Check for potential -arch flags. It is not universal unless + # there are some -arch flags. Note that *ppc* also matches + # ppc64. This check is also rather less than ideal. + case "${CC} ${CFLAGS} ${CPPFLAGS} ${LDFLAGS}" in #( + *-arch*ppc*|*-arch*i386*|*-arch*x86_64*) ac_cv_c_bigendian=universal;; + esac +else + $as_echo "$as_me: failed program was:" >&5 +sed 's/^/| /' conftest.$ac_ext >&5 + + +fi + +rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext + if test $ac_cv_c_bigendian = unknown; then + # See if sys/param.h defines the BYTE_ORDER macro. + cat >conftest.$ac_ext <<_ACEOF +/* confdefs.h. */ +_ACEOF +cat confdefs.h >>conftest.$ac_ext +cat >>conftest.$ac_ext <<_ACEOF +/* end confdefs.h. */ +#include + #include + +int +main () +{ +#if ! (defined BYTE_ORDER && defined BIG_ENDIAN \ + && defined LITTLE_ENDIAN && BYTE_ORDER && BIG_ENDIAN \ + && LITTLE_ENDIAN) + bogus endian macros + #endif + + ; + return 0; +} +_ACEOF +rm -f conftest.$ac_objext +if { (ac_try="$ac_compile" +case "(($ac_try" in + *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; + *) ac_try_echo=$ac_try;; +esac +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 + (eval "$ac_compile") 2>conftest.er1 + ac_status=$? + grep -v '^ *+' conftest.er1 >conftest.err + rm -f conftest.er1 + cat conftest.err >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 + (exit $ac_status); } && { + test -z "$ac_c_werror_flag" || + test ! -s conftest.err + } && test -s conftest.$ac_objext; then + # It does; now see whether it defined to BIG_ENDIAN or not. + cat >conftest.$ac_ext <<_ACEOF +/* confdefs.h. */ +_ACEOF +cat confdefs.h >>conftest.$ac_ext +cat >>conftest.$ac_ext <<_ACEOF +/* end confdefs.h. */ +#include + #include + +int +main () +{ +#if BYTE_ORDER != BIG_ENDIAN + not big endian + #endif + + ; + return 0; +} _ACEOF +rm -f conftest.$ac_objext +if { (ac_try="$ac_compile" +case "(($ac_try" in + *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; + *) ac_try_echo=$ac_try;; +esac +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 + (eval "$ac_compile") 2>conftest.er1 + ac_status=$? + grep -v '^ *+' conftest.er1 >conftest.err + rm -f conftest.er1 + cat conftest.err >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 + (exit $ac_status); } && { + test -z "$ac_c_werror_flag" || + test ! -s conftest.err + } && test -s conftest.$ac_objext; then + ac_cv_c_bigendian=yes +else + $as_echo "$as_me: failed program was:" >&5 +sed 's/^/| /' conftest.$ac_ext >&5 -elif test "$ac_cv_sizeof_long" = "$unicode_size" -then - PY_UNICODE_TYPE="unsigned long" - cat >>confdefs.h <<\_ACEOF -#define PY_UNICODE_TYPE unsigned long -_ACEOF + ac_cv_c_bigendian=no +fi +rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext else - PY_UNICODE_TYPE="no type found" + $as_echo "$as_me: failed program was:" >&5 +sed 's/^/| /' conftest.$ac_ext >&5 + + fi -{ echo "$as_me:$LINENO: result: $PY_UNICODE_TYPE" >&5 -echo "${ECHO_T}$PY_UNICODE_TYPE" >&6; } -# check for endianness -{ echo "$as_me:$LINENO: checking whether byte ordering is bigendian" >&5 -echo $ECHO_N "checking whether byte ordering is bigendian... $ECHO_C" >&6; } -if test "${ac_cv_c_bigendian+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 -else - # See if sys/param.h defines the BYTE_ORDER macro. -cat >conftest.$ac_ext <<_ACEOF +rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext + fi + if test $ac_cv_c_bigendian = unknown; then + # See if defines _LITTLE_ENDIAN or _BIG_ENDIAN (e.g., Solaris). + cat >conftest.$ac_ext <<_ACEOF /* confdefs.h. */ _ACEOF cat confdefs.h >>conftest.$ac_ext cat >>conftest.$ac_ext <<_ACEOF /* end confdefs.h. */ -#include -#include +#include int main () { -#if ! (defined BYTE_ORDER && defined BIG_ENDIAN && defined LITTLE_ENDIAN \ - && BYTE_ORDER && BIG_ENDIAN && LITTLE_ENDIAN) - bogus endian macros -#endif +#if ! (defined _LITTLE_ENDIAN || defined _BIG_ENDIAN) + bogus endian macros + #endif ; return 0; @@ -23782,33 +24468,33 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_compile") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { test -z "$ac_c_werror_flag" || test ! -s conftest.err } && test -s conftest.$ac_objext; then - # It does; now see whether it defined to BIG_ENDIAN or not. -cat >conftest.$ac_ext <<_ACEOF + # It does; now see whether it defined to _BIG_ENDIAN or not. + cat >conftest.$ac_ext <<_ACEOF /* confdefs.h. */ _ACEOF cat confdefs.h >>conftest.$ac_ext cat >>conftest.$ac_ext <<_ACEOF /* end confdefs.h. */ -#include -#include +#include int main () { -#if BYTE_ORDER != BIG_ENDIAN - not big endian -#endif +#ifndef _BIG_ENDIAN + not big endian + #endif ; return 0; @@ -23820,20 +24506,21 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_compile") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { test -z "$ac_c_werror_flag" || test ! -s conftest.err } && test -s conftest.$ac_objext; then ac_cv_c_bigendian=yes else - echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 ac_cv_c_bigendian=no @@ -23841,29 +24528,44 @@ rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext else - echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 - # It does not; compile a test program. -if test "$cross_compiling" = yes; then - # try to guess the endianness by grepping values into an object file - ac_cv_c_bigendian=unknown - cat >conftest.$ac_ext <<_ACEOF + +fi + +rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext + fi + if test $ac_cv_c_bigendian = unknown; then + # Compile a test program. + if test "$cross_compiling" = yes; then + # Try to guess by grepping values from an object file. + cat >conftest.$ac_ext <<_ACEOF /* confdefs.h. */ _ACEOF cat confdefs.h >>conftest.$ac_ext cat >>conftest.$ac_ext <<_ACEOF /* end confdefs.h. */ -short int ascii_mm[] = { 0x4249, 0x4765, 0x6E44, 0x6961, 0x6E53, 0x7953, 0 }; -short int ascii_ii[] = { 0x694C, 0x5454, 0x656C, 0x6E45, 0x6944, 0x6E61, 0 }; -void _ascii () { char *s = (char *) ascii_mm; s = (char *) ascii_ii; } -short int ebcdic_ii[] = { 0x89D3, 0xE3E3, 0x8593, 0x95C5, 0x89C4, 0x9581, 0 }; -short int ebcdic_mm[] = { 0xC2C9, 0xC785, 0x95C4, 0x8981, 0x95E2, 0xA8E2, 0 }; -void _ebcdic () { char *s = (char *) ebcdic_mm; s = (char *) ebcdic_ii; } +short int ascii_mm[] = + { 0x4249, 0x4765, 0x6E44, 0x6961, 0x6E53, 0x7953, 0 }; + short int ascii_ii[] = + { 0x694C, 0x5454, 0x656C, 0x6E45, 0x6944, 0x6E61, 0 }; + int use_ascii (int i) { + return ascii_mm[i] + ascii_ii[i]; + } + short int ebcdic_ii[] = + { 0x89D3, 0xE3E3, 0x8593, 0x95C5, 0x89C4, 0x9581, 0 }; + short int ebcdic_mm[] = + { 0xC2C9, 0xC785, 0x95C4, 0x8981, 0x95E2, 0xA8E2, 0 }; + int use_ebcdic (int i) { + return ebcdic_mm[i] + ebcdic_ii[i]; + } + extern int foo; + int main () { - _ascii (); _ebcdic (); +return use_ascii (foo) == use_ebcdic (foo); ; return 0; } @@ -23874,30 +24576,31 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_compile") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { test -z "$ac_c_werror_flag" || test ! -s conftest.err } && test -s conftest.$ac_objext; then - if grep BIGenDianSyS conftest.$ac_objext >/dev/null ; then - ac_cv_c_bigendian=yes -fi -if grep LiTTleEnDian conftest.$ac_objext >/dev/null ; then - if test "$ac_cv_c_bigendian" = unknown; then - ac_cv_c_bigendian=no - else - # finding both strings is unlikely to happen, but who knows? - ac_cv_c_bigendian=unknown - fi -fi + if grep BIGenDianSyS conftest.$ac_objext >/dev/null; then + ac_cv_c_bigendian=yes + fi + if grep LiTTleEnDian conftest.$ac_objext >/dev/null ; then + if test "$ac_cv_c_bigendian" = unknown; then + ac_cv_c_bigendian=no + else + # finding both strings is unlikely to happen, but who knows? + ac_cv_c_bigendian=unknown + fi + fi else - echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 @@ -23916,14 +24619,14 @@ main () { - /* Are we little or big endian? From Harbison&Steele. */ - union - { - long int l; - char c[sizeof (long int)]; - } u; - u.l = 1; - return u.c[sizeof (long int) - 1] == 1; + /* Are we little or big endian? From Harbison&Steele. */ + union + { + long int l; + char c[sizeof (long int)]; + } u; + u.l = 1; + return u.c[sizeof (long int) - 1] == 1; ; return 0; @@ -23935,63 +24638,70 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_link") 2>&5 ac_status=$? - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { ac_try='./conftest$ac_exeext' { (case "(($ac_try" in *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_try") 2>&5 ac_status=$? - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); }; }; then ac_cv_c_bigendian=no else - echo "$as_me: program exited with status $ac_status" >&5 -echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: program exited with status $ac_status" >&5 +$as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 ( exit $ac_status ) ac_cv_c_bigendian=yes fi +rm -rf conftest.dSYM rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext conftest.$ac_objext conftest.$ac_ext fi + fi fi - -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext -fi -{ echo "$as_me:$LINENO: result: $ac_cv_c_bigendian" >&5 -echo "${ECHO_T}$ac_cv_c_bigendian" >&6; } -case $ac_cv_c_bigendian in - yes) +{ $as_echo "$as_me:$LINENO: result: $ac_cv_c_bigendian" >&5 +$as_echo "$ac_cv_c_bigendian" >&6; } + case $ac_cv_c_bigendian in #( + yes) + cat >>confdefs.h <<\_ACEOF +#define WORDS_BIGENDIAN 1 +_ACEOF +;; #( + no) + ;; #( + universal) cat >>confdefs.h <<\_ACEOF -#define WORDS_BIGENDIAN 1 +#define AC_APPLE_UNIVERSAL_BUILD 1 _ACEOF - ;; - no) - ;; - *) - { { echo "$as_me:$LINENO: error: unknown endianness -presetting ac_cv_c_bigendian=no (or yes) will help" >&5 -echo "$as_me: error: unknown endianness -presetting ac_cv_c_bigendian=no (or yes) will help" >&2;} + + ;; #( + *) + { { $as_echo "$as_me:$LINENO: error: unknown endianness + presetting ac_cv_c_bigendian=no (or yes) will help" >&5 +$as_echo "$as_me: error: unknown endianness + presetting ac_cv_c_bigendian=no (or yes) will help" >&2;} { (exit 1); exit 1; }; } ;; -esac + esac # Check whether right shifting a negative integer extends the sign bit # or fills with zeros (like the Cray J90, according to Tim Peters). -{ echo "$as_me:$LINENO: checking whether right shift extends the sign bit" >&5 -echo $ECHO_N "checking whether right shift extends the sign bit... $ECHO_C" >&6; } +{ $as_echo "$as_me:$LINENO: checking whether right shift extends the sign bit" >&5 +$as_echo_n "checking whether right shift extends the sign bit... " >&6; } if test "${ac_cv_rshift_extends_sign+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 + $as_echo_n "(cached) " >&6 else if test "$cross_compiling" = yes; then @@ -24016,37 +24726,40 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_link") 2>&5 ac_status=$? - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { ac_try='./conftest$ac_exeext' { (case "(($ac_try" in *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_try") 2>&5 ac_status=$? - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); }; }; then ac_cv_rshift_extends_sign=yes else - echo "$as_me: program exited with status $ac_status" >&5 -echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: program exited with status $ac_status" >&5 +$as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 ( exit $ac_status ) ac_cv_rshift_extends_sign=no fi +rm -rf conftest.dSYM rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext conftest.$ac_objext conftest.$ac_ext fi fi -{ echo "$as_me:$LINENO: result: $ac_cv_rshift_extends_sign" >&5 -echo "${ECHO_T}$ac_cv_rshift_extends_sign" >&6; } +{ $as_echo "$as_me:$LINENO: result: $ac_cv_rshift_extends_sign" >&5 +$as_echo "$ac_cv_rshift_extends_sign" >&6; } if test "$ac_cv_rshift_extends_sign" = no then @@ -24057,10 +24770,10 @@ fi # check for getc_unlocked and related locking functions -{ echo "$as_me:$LINENO: checking for getc_unlocked() and friends" >&5 -echo $ECHO_N "checking for getc_unlocked() and friends... $ECHO_C" >&6; } +{ $as_echo "$as_me:$LINENO: checking for getc_unlocked() and friends" >&5 +$as_echo_n "checking for getc_unlocked() and friends... " >&6; } if test "${ac_cv_have_getc_unlocked+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 + $as_echo_n "(cached) " >&6 else cat >conftest.$ac_ext <<_ACEOF @@ -24089,32 +24802,36 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_link") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { test -z "$ac_c_werror_flag" || test ! -s conftest.err - } && test -s conftest$ac_exeext && - $as_test_x conftest$ac_exeext; then + } && test -s conftest$ac_exeext && { + test "$cross_compiling" = yes || + $as_test_x conftest$ac_exeext + }; then ac_cv_have_getc_unlocked=yes else - echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 ac_cv_have_getc_unlocked=no fi +rm -rf conftest.dSYM rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \ conftest$ac_exeext conftest.$ac_ext fi -{ echo "$as_me:$LINENO: result: $ac_cv_have_getc_unlocked" >&5 -echo "${ECHO_T}$ac_cv_have_getc_unlocked" >&6; } +{ $as_echo "$as_me:$LINENO: result: $ac_cv_have_getc_unlocked" >&5 +$as_echo "$ac_cv_have_getc_unlocked" >&6; } if test "$ac_cv_have_getc_unlocked" = yes then @@ -24132,8 +24849,8 @@ # library. NOTE: Keep the precedence of listed libraries synchronised # with setup.py. py_cv_lib_readline=no -{ echo "$as_me:$LINENO: checking how to link readline libs" >&5 -echo $ECHO_N "checking how to link readline libs... $ECHO_C" >&6; } +{ $as_echo "$as_me:$LINENO: checking how to link readline libs" >&5 +$as_echo_n "checking how to link readline libs... " >&6; } for py_libtermcap in "" ncursesw ncurses curses termcap; do if test -z "$py_libtermcap"; then READLINE_LIBS="-lreadline" @@ -24169,26 +24886,30 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_link") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { test -z "$ac_c_werror_flag" || test ! -s conftest.err - } && test -s conftest$ac_exeext && - $as_test_x conftest$ac_exeext; then + } && test -s conftest$ac_exeext && { + test "$cross_compiling" = yes || + $as_test_x conftest$ac_exeext + }; then py_cv_lib_readline=yes else - echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 fi +rm -rf conftest.dSYM rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \ conftest$ac_exeext conftest.$ac_ext if test $py_cv_lib_readline = yes; then @@ -24198,11 +24919,11 @@ # Uncomment this line if you want to use READINE_LIBS in Makefile or scripts #AC_SUBST([READLINE_LIBS]) if test $py_cv_lib_readline = no; then - { echo "$as_me:$LINENO: result: none" >&5 -echo "${ECHO_T}none" >&6; } + { $as_echo "$as_me:$LINENO: result: none" >&5 +$as_echo "none" >&6; } else - { echo "$as_me:$LINENO: result: $READLINE_LIBS" >&5 -echo "${ECHO_T}$READLINE_LIBS" >&6; } + { $as_echo "$as_me:$LINENO: result: $READLINE_LIBS" >&5 +$as_echo "$READLINE_LIBS" >&6; } cat >>confdefs.h <<\_ACEOF #define HAVE_LIBREADLINE 1 @@ -24211,10 +24932,10 @@ fi # check for readline 2.1 -{ echo "$as_me:$LINENO: checking for rl_callback_handler_install in -lreadline" >&5 -echo $ECHO_N "checking for rl_callback_handler_install in -lreadline... $ECHO_C" >&6; } +{ $as_echo "$as_me:$LINENO: checking for rl_callback_handler_install in -lreadline" >&5 +$as_echo_n "checking for rl_callback_handler_install in -lreadline... " >&6; } if test "${ac_cv_lib_readline_rl_callback_handler_install+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 + $as_echo_n "(cached) " >&6 else ac_check_lib_save_LIBS=$LIBS LIBS="-lreadline $READLINE_LIBS $LIBS" @@ -24246,33 +24967,37 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_link") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { test -z "$ac_c_werror_flag" || test ! -s conftest.err - } && test -s conftest$ac_exeext && - $as_test_x conftest$ac_exeext; then + } && test -s conftest$ac_exeext && { + test "$cross_compiling" = yes || + $as_test_x conftest$ac_exeext + }; then ac_cv_lib_readline_rl_callback_handler_install=yes else - echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 ac_cv_lib_readline_rl_callback_handler_install=no fi +rm -rf conftest.dSYM rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \ conftest$ac_exeext conftest.$ac_ext LIBS=$ac_check_lib_save_LIBS fi -{ echo "$as_me:$LINENO: result: $ac_cv_lib_readline_rl_callback_handler_install" >&5 -echo "${ECHO_T}$ac_cv_lib_readline_rl_callback_handler_install" >&6; } -if test $ac_cv_lib_readline_rl_callback_handler_install = yes; then +{ $as_echo "$as_me:$LINENO: result: $ac_cv_lib_readline_rl_callback_handler_install" >&5 +$as_echo "$ac_cv_lib_readline_rl_callback_handler_install" >&6; } +if test "x$ac_cv_lib_readline_rl_callback_handler_install" = x""yes; then cat >>confdefs.h <<\_ACEOF #define HAVE_RL_CALLBACK 1 @@ -24295,20 +25020,21 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_cpp conftest.$ac_ext") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } >/dev/null && { test -z "$ac_c_preproc_warn_flag$ac_c_werror_flag" || test ! -s conftest.err }; then have_readline=yes else - echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 have_readline=no @@ -24358,10 +25084,10 @@ fi # check for readline 4.0 -{ echo "$as_me:$LINENO: checking for rl_pre_input_hook in -lreadline" >&5 -echo $ECHO_N "checking for rl_pre_input_hook in -lreadline... $ECHO_C" >&6; } +{ $as_echo "$as_me:$LINENO: checking for rl_pre_input_hook in -lreadline" >&5 +$as_echo_n "checking for rl_pre_input_hook in -lreadline... " >&6; } if test "${ac_cv_lib_readline_rl_pre_input_hook+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 + $as_echo_n "(cached) " >&6 else ac_check_lib_save_LIBS=$LIBS LIBS="-lreadline $READLINE_LIBS $LIBS" @@ -24393,33 +25119,37 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_link") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { test -z "$ac_c_werror_flag" || test ! -s conftest.err - } && test -s conftest$ac_exeext && - $as_test_x conftest$ac_exeext; then + } && test -s conftest$ac_exeext && { + test "$cross_compiling" = yes || + $as_test_x conftest$ac_exeext + }; then ac_cv_lib_readline_rl_pre_input_hook=yes else - echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 ac_cv_lib_readline_rl_pre_input_hook=no fi +rm -rf conftest.dSYM rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \ conftest$ac_exeext conftest.$ac_ext LIBS=$ac_check_lib_save_LIBS fi -{ echo "$as_me:$LINENO: result: $ac_cv_lib_readline_rl_pre_input_hook" >&5 -echo "${ECHO_T}$ac_cv_lib_readline_rl_pre_input_hook" >&6; } -if test $ac_cv_lib_readline_rl_pre_input_hook = yes; then +{ $as_echo "$as_me:$LINENO: result: $ac_cv_lib_readline_rl_pre_input_hook" >&5 +$as_echo "$ac_cv_lib_readline_rl_pre_input_hook" >&6; } +if test "x$ac_cv_lib_readline_rl_pre_input_hook" = x""yes; then cat >>confdefs.h <<\_ACEOF #define HAVE_RL_PRE_INPUT_HOOK 1 @@ -24429,10 +25159,10 @@ # also in 4.0 -{ echo "$as_me:$LINENO: checking for rl_completion_display_matches_hook in -lreadline" >&5 -echo $ECHO_N "checking for rl_completion_display_matches_hook in -lreadline... $ECHO_C" >&6; } +{ $as_echo "$as_me:$LINENO: checking for rl_completion_display_matches_hook in -lreadline" >&5 +$as_echo_n "checking for rl_completion_display_matches_hook in -lreadline... " >&6; } if test "${ac_cv_lib_readline_rl_completion_display_matches_hook+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 + $as_echo_n "(cached) " >&6 else ac_check_lib_save_LIBS=$LIBS LIBS="-lreadline $READLINE_LIBS $LIBS" @@ -24464,33 +25194,37 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_link") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { test -z "$ac_c_werror_flag" || test ! -s conftest.err - } && test -s conftest$ac_exeext && - $as_test_x conftest$ac_exeext; then + } && test -s conftest$ac_exeext && { + test "$cross_compiling" = yes || + $as_test_x conftest$ac_exeext + }; then ac_cv_lib_readline_rl_completion_display_matches_hook=yes else - echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 ac_cv_lib_readline_rl_completion_display_matches_hook=no fi +rm -rf conftest.dSYM rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \ conftest$ac_exeext conftest.$ac_ext LIBS=$ac_check_lib_save_LIBS fi -{ echo "$as_me:$LINENO: result: $ac_cv_lib_readline_rl_completion_display_matches_hook" >&5 -echo "${ECHO_T}$ac_cv_lib_readline_rl_completion_display_matches_hook" >&6; } -if test $ac_cv_lib_readline_rl_completion_display_matches_hook = yes; then +{ $as_echo "$as_me:$LINENO: result: $ac_cv_lib_readline_rl_completion_display_matches_hook" >&5 +$as_echo "$ac_cv_lib_readline_rl_completion_display_matches_hook" >&6; } +if test "x$ac_cv_lib_readline_rl_completion_display_matches_hook" = x""yes; then cat >>confdefs.h <<\_ACEOF #define HAVE_RL_COMPLETION_DISPLAY_MATCHES_HOOK 1 @@ -24500,10 +25234,10 @@ # check for readline 4.2 -{ echo "$as_me:$LINENO: checking for rl_completion_matches in -lreadline" >&5 -echo $ECHO_N "checking for rl_completion_matches in -lreadline... $ECHO_C" >&6; } +{ $as_echo "$as_me:$LINENO: checking for rl_completion_matches in -lreadline" >&5 +$as_echo_n "checking for rl_completion_matches in -lreadline... " >&6; } if test "${ac_cv_lib_readline_rl_completion_matches+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 + $as_echo_n "(cached) " >&6 else ac_check_lib_save_LIBS=$LIBS LIBS="-lreadline $READLINE_LIBS $LIBS" @@ -24535,33 +25269,37 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_link") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { test -z "$ac_c_werror_flag" || test ! -s conftest.err - } && test -s conftest$ac_exeext && - $as_test_x conftest$ac_exeext; then + } && test -s conftest$ac_exeext && { + test "$cross_compiling" = yes || + $as_test_x conftest$ac_exeext + }; then ac_cv_lib_readline_rl_completion_matches=yes else - echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 ac_cv_lib_readline_rl_completion_matches=no fi +rm -rf conftest.dSYM rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \ conftest$ac_exeext conftest.$ac_ext LIBS=$ac_check_lib_save_LIBS fi -{ echo "$as_me:$LINENO: result: $ac_cv_lib_readline_rl_completion_matches" >&5 -echo "${ECHO_T}$ac_cv_lib_readline_rl_completion_matches" >&6; } -if test $ac_cv_lib_readline_rl_completion_matches = yes; then +{ $as_echo "$as_me:$LINENO: result: $ac_cv_lib_readline_rl_completion_matches" >&5 +$as_echo "$ac_cv_lib_readline_rl_completion_matches" >&6; } +if test "x$ac_cv_lib_readline_rl_completion_matches" = x""yes; then cat >>confdefs.h <<\_ACEOF #define HAVE_RL_COMPLETION_MATCHES 1 @@ -24584,20 +25322,21 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_cpp conftest.$ac_ext") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } >/dev/null && { test -z "$ac_c_preproc_warn_flag$ac_c_werror_flag" || test ! -s conftest.err }; then have_readline=yes else - echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 have_readline=no @@ -24630,10 +25369,10 @@ # End of readline checks: restore LIBS LIBS=$LIBS_no_readline -{ echo "$as_me:$LINENO: checking for broken nice()" >&5 -echo $ECHO_N "checking for broken nice()... $ECHO_C" >&6; } +{ $as_echo "$as_me:$LINENO: checking for broken nice()" >&5 +$as_echo_n "checking for broken nice()... " >&6; } if test "${ac_cv_broken_nice+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 + $as_echo_n "(cached) " >&6 else if test "$cross_compiling" = yes; then @@ -24661,37 +25400,40 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_link") 2>&5 ac_status=$? - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { ac_try='./conftest$ac_exeext' { (case "(($ac_try" in *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_try") 2>&5 ac_status=$? - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); }; }; then ac_cv_broken_nice=yes else - echo "$as_me: program exited with status $ac_status" >&5 -echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: program exited with status $ac_status" >&5 +$as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 ( exit $ac_status ) ac_cv_broken_nice=no fi +rm -rf conftest.dSYM rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext conftest.$ac_objext conftest.$ac_ext fi fi -{ echo "$as_me:$LINENO: result: $ac_cv_broken_nice" >&5 -echo "${ECHO_T}$ac_cv_broken_nice" >&6; } +{ $as_echo "$as_me:$LINENO: result: $ac_cv_broken_nice" >&5 +$as_echo "$ac_cv_broken_nice" >&6; } if test "$ac_cv_broken_nice" = yes then @@ -24701,8 +25443,8 @@ fi -{ echo "$as_me:$LINENO: checking for broken poll()" >&5 -echo $ECHO_N "checking for broken poll()... $ECHO_C" >&6; } +{ $as_echo "$as_me:$LINENO: checking for broken poll()" >&5 +$as_echo_n "checking for broken poll()... " >&6; } if test "$cross_compiling" = yes; then ac_cv_broken_poll=no else @@ -24744,35 +25486,38 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_link") 2>&5 ac_status=$? - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { ac_try='./conftest$ac_exeext' { (case "(($ac_try" in *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_try") 2>&5 ac_status=$? - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); }; }; then ac_cv_broken_poll=yes else - echo "$as_me: program exited with status $ac_status" >&5 -echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: program exited with status $ac_status" >&5 +$as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 ( exit $ac_status ) ac_cv_broken_poll=no fi +rm -rf conftest.dSYM rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext conftest.$ac_objext conftest.$ac_ext fi -{ echo "$as_me:$LINENO: result: $ac_cv_broken_poll" >&5 -echo "${ECHO_T}$ac_cv_broken_poll" >&6; } +{ $as_echo "$as_me:$LINENO: result: $ac_cv_broken_poll" >&5 +$as_echo "$ac_cv_broken_poll" >&6; } if test "$ac_cv_broken_poll" = yes then @@ -24785,10 +25530,10 @@ # 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[] -{ echo "$as_me:$LINENO: checking for struct tm.tm_zone" >&5 -echo $ECHO_N "checking for struct tm.tm_zone... $ECHO_C" >&6; } +{ $as_echo "$as_me:$LINENO: checking for struct tm.tm_zone" >&5 +$as_echo_n "checking for struct tm.tm_zone... " >&6; } if test "${ac_cv_member_struct_tm_tm_zone+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 + $as_echo_n "(cached) " >&6 else cat >conftest.$ac_ext <<_ACEOF /* confdefs.h. */ @@ -24816,20 +25561,21 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_compile") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { test -z "$ac_c_werror_flag" || test ! -s conftest.err } && test -s conftest.$ac_objext; then ac_cv_member_struct_tm_tm_zone=yes else - echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 cat >conftest.$ac_ext <<_ACEOF @@ -24858,20 +25604,21 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_compile") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { test -z "$ac_c_werror_flag" || test ! -s conftest.err } && test -s conftest.$ac_objext; then ac_cv_member_struct_tm_tm_zone=yes else - echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 ac_cv_member_struct_tm_tm_zone=no @@ -24882,9 +25629,9 @@ rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext fi -{ echo "$as_me:$LINENO: result: $ac_cv_member_struct_tm_tm_zone" >&5 -echo "${ECHO_T}$ac_cv_member_struct_tm_tm_zone" >&6; } -if test $ac_cv_member_struct_tm_tm_zone = yes; then +{ $as_echo "$as_me:$LINENO: result: $ac_cv_member_struct_tm_tm_zone" >&5 +$as_echo "$ac_cv_member_struct_tm_tm_zone" >&6; } +if test "x$ac_cv_member_struct_tm_tm_zone" = x""yes; then cat >>confdefs.h <<_ACEOF #define HAVE_STRUCT_TM_TM_ZONE 1 @@ -24900,10 +25647,10 @@ _ACEOF else - { echo "$as_me:$LINENO: checking whether tzname is declared" >&5 -echo $ECHO_N "checking whether tzname is declared... $ECHO_C" >&6; } + { $as_echo "$as_me:$LINENO: checking whether tzname is declared" >&5 +$as_echo_n "checking whether tzname is declared... " >&6; } if test "${ac_cv_have_decl_tzname+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 + $as_echo_n "(cached) " >&6 else cat >conftest.$ac_ext <<_ACEOF /* confdefs.h. */ @@ -24930,20 +25677,21 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_compile") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { test -z "$ac_c_werror_flag" || test ! -s conftest.err } && test -s conftest.$ac_objext; then ac_cv_have_decl_tzname=yes else - echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 ac_cv_have_decl_tzname=no @@ -24951,9 +25699,9 @@ rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext fi -{ echo "$as_me:$LINENO: result: $ac_cv_have_decl_tzname" >&5 -echo "${ECHO_T}$ac_cv_have_decl_tzname" >&6; } -if test $ac_cv_have_decl_tzname = yes; then +{ $as_echo "$as_me:$LINENO: result: $ac_cv_have_decl_tzname" >&5 +$as_echo "$ac_cv_have_decl_tzname" >&6; } +if test "x$ac_cv_have_decl_tzname" = x""yes; then cat >>confdefs.h <<_ACEOF #define HAVE_DECL_TZNAME 1 @@ -24969,10 +25717,10 @@ fi - { echo "$as_me:$LINENO: checking for tzname" >&5 -echo $ECHO_N "checking for tzname... $ECHO_C" >&6; } + { $as_echo "$as_me:$LINENO: checking for tzname" >&5 +$as_echo_n "checking for tzname... " >&6; } if test "${ac_cv_var_tzname+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 + $as_echo_n "(cached) " >&6 else cat >conftest.$ac_ext <<_ACEOF /* confdefs.h. */ @@ -24999,31 +25747,35 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_link") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { test -z "$ac_c_werror_flag" || test ! -s conftest.err - } && test -s conftest$ac_exeext && - $as_test_x conftest$ac_exeext; then + } && test -s conftest$ac_exeext && { + test "$cross_compiling" = yes || + $as_test_x conftest$ac_exeext + }; then ac_cv_var_tzname=yes else - echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 ac_cv_var_tzname=no fi +rm -rf conftest.dSYM rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \ conftest$ac_exeext conftest.$ac_ext fi -{ echo "$as_me:$LINENO: result: $ac_cv_var_tzname" >&5 -echo "${ECHO_T}$ac_cv_var_tzname" >&6; } +{ $as_echo "$as_me:$LINENO: result: $ac_cv_var_tzname" >&5 +$as_echo "$ac_cv_var_tzname" >&6; } if test $ac_cv_var_tzname = yes; then cat >>confdefs.h <<\_ACEOF @@ -25035,10 +25787,10 @@ # check tzset(3) exists and works like we expect it to -{ echo "$as_me:$LINENO: checking for working tzset()" >&5 -echo $ECHO_N "checking for working tzset()... $ECHO_C" >&6; } +{ $as_echo "$as_me:$LINENO: checking for working tzset()" >&5 +$as_echo_n "checking for working tzset()... " >&6; } if test "${ac_cv_working_tzset+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 + $as_echo_n "(cached) " >&6 else if test "$cross_compiling" = yes; then @@ -25121,37 +25873,40 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_link") 2>&5 ac_status=$? - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { ac_try='./conftest$ac_exeext' { (case "(($ac_try" in *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_try") 2>&5 ac_status=$? - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); }; }; then ac_cv_working_tzset=yes else - echo "$as_me: program exited with status $ac_status" >&5 -echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: program exited with status $ac_status" >&5 +$as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 ( exit $ac_status ) ac_cv_working_tzset=no fi +rm -rf conftest.dSYM rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext conftest.$ac_objext conftest.$ac_ext fi fi -{ echo "$as_me:$LINENO: result: $ac_cv_working_tzset" >&5 -echo "${ECHO_T}$ac_cv_working_tzset" >&6; } +{ $as_echo "$as_me:$LINENO: result: $ac_cv_working_tzset" >&5 +$as_echo "$ac_cv_working_tzset" >&6; } if test "$ac_cv_working_tzset" = yes then @@ -25162,10 +25917,10 @@ fi # Look for subsecond timestamps in struct stat -{ echo "$as_me:$LINENO: checking for tv_nsec in struct stat" >&5 -echo $ECHO_N "checking for tv_nsec in struct stat... $ECHO_C" >&6; } +{ $as_echo "$as_me:$LINENO: checking for tv_nsec in struct stat" >&5 +$as_echo_n "checking for tv_nsec in struct stat... " >&6; } if test "${ac_cv_stat_tv_nsec+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 + $as_echo_n "(cached) " >&6 else cat >conftest.$ac_ext <<_ACEOF /* confdefs.h. */ @@ -25191,20 +25946,21 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_compile") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { test -z "$ac_c_werror_flag" || test ! -s conftest.err } && test -s conftest.$ac_objext; then ac_cv_stat_tv_nsec=yes else - echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 ac_cv_stat_tv_nsec=no @@ -25213,8 +25969,8 @@ rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext fi -{ echo "$as_me:$LINENO: result: $ac_cv_stat_tv_nsec" >&5 -echo "${ECHO_T}$ac_cv_stat_tv_nsec" >&6; } +{ $as_echo "$as_me:$LINENO: result: $ac_cv_stat_tv_nsec" >&5 +$as_echo "$ac_cv_stat_tv_nsec" >&6; } if test "$ac_cv_stat_tv_nsec" = yes then @@ -25225,10 +25981,10 @@ fi # Look for BSD style subsecond timestamps in struct stat -{ echo "$as_me:$LINENO: checking for tv_nsec2 in struct stat" >&5 -echo $ECHO_N "checking for tv_nsec2 in struct stat... $ECHO_C" >&6; } +{ $as_echo "$as_me:$LINENO: checking for tv_nsec2 in struct stat" >&5 +$as_echo_n "checking for tv_nsec2 in struct stat... " >&6; } if test "${ac_cv_stat_tv_nsec2+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 + $as_echo_n "(cached) " >&6 else cat >conftest.$ac_ext <<_ACEOF /* confdefs.h. */ @@ -25254,20 +26010,21 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_compile") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { test -z "$ac_c_werror_flag" || test ! -s conftest.err } && test -s conftest.$ac_objext; then ac_cv_stat_tv_nsec2=yes else - echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 ac_cv_stat_tv_nsec2=no @@ -25276,8 +26033,8 @@ rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext fi -{ echo "$as_me:$LINENO: result: $ac_cv_stat_tv_nsec2" >&5 -echo "${ECHO_T}$ac_cv_stat_tv_nsec2" >&6; } +{ $as_echo "$as_me:$LINENO: result: $ac_cv_stat_tv_nsec2" >&5 +$as_echo "$ac_cv_stat_tv_nsec2" >&6; } if test "$ac_cv_stat_tv_nsec2" = yes then @@ -25288,10 +26045,10 @@ fi # On HP/UX 11.0, mvwdelch is a block with a return statement -{ echo "$as_me:$LINENO: checking whether mvwdelch is an expression" >&5 -echo $ECHO_N "checking whether mvwdelch is an expression... $ECHO_C" >&6; } +{ $as_echo "$as_me:$LINENO: checking whether mvwdelch is an expression" >&5 +$as_echo_n "checking whether mvwdelch is an expression... " >&6; } if test "${ac_cv_mvwdelch_is_expression+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 + $as_echo_n "(cached) " >&6 else cat >conftest.$ac_ext <<_ACEOF /* confdefs.h. */ @@ -25317,20 +26074,21 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_compile") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { test -z "$ac_c_werror_flag" || test ! -s conftest.err } && test -s conftest.$ac_objext; then ac_cv_mvwdelch_is_expression=yes else - echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 ac_cv_mvwdelch_is_expression=no @@ -25339,8 +26097,8 @@ rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext fi -{ echo "$as_me:$LINENO: result: $ac_cv_mvwdelch_is_expression" >&5 -echo "${ECHO_T}$ac_cv_mvwdelch_is_expression" >&6; } +{ $as_echo "$as_me:$LINENO: result: $ac_cv_mvwdelch_is_expression" >&5 +$as_echo "$ac_cv_mvwdelch_is_expression" >&6; } if test "$ac_cv_mvwdelch_is_expression" = yes then @@ -25351,10 +26109,10 @@ fi -{ echo "$as_me:$LINENO: checking whether WINDOW has _flags" >&5 -echo $ECHO_N "checking whether WINDOW has _flags... $ECHO_C" >&6; } +{ $as_echo "$as_me:$LINENO: checking whether WINDOW has _flags" >&5 +$as_echo_n "checking whether WINDOW has _flags... " >&6; } if test "${ac_cv_window_has_flags+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 + $as_echo_n "(cached) " >&6 else cat >conftest.$ac_ext <<_ACEOF /* confdefs.h. */ @@ -25380,20 +26138,21 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_compile") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { test -z "$ac_c_werror_flag" || test ! -s conftest.err } && test -s conftest.$ac_objext; then ac_cv_window_has_flags=yes else - echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 ac_cv_window_has_flags=no @@ -25402,8 +26161,8 @@ rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext fi -{ echo "$as_me:$LINENO: result: $ac_cv_window_has_flags" >&5 -echo "${ECHO_T}$ac_cv_window_has_flags" >&6; } +{ $as_echo "$as_me:$LINENO: result: $ac_cv_window_has_flags" >&5 +$as_echo "$ac_cv_window_has_flags" >&6; } if test "$ac_cv_window_has_flags" = yes @@ -25415,8 +26174,8 @@ fi -{ echo "$as_me:$LINENO: checking for is_term_resized" >&5 -echo $ECHO_N "checking for is_term_resized... $ECHO_C" >&6; } +{ $as_echo "$as_me:$LINENO: checking for is_term_resized" >&5 +$as_echo_n "checking for is_term_resized... " >&6; } cat >conftest.$ac_ext <<_ACEOF /* confdefs.h. */ _ACEOF @@ -25438,13 +26197,14 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_compile") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { test -z "$ac_c_werror_flag" || test ! -s conftest.err @@ -25454,21 +26214,21 @@ #define HAVE_CURSES_IS_TERM_RESIZED 1 _ACEOF - { echo "$as_me:$LINENO: result: yes" >&5 -echo "${ECHO_T}yes" >&6; } + { $as_echo "$as_me:$LINENO: result: yes" >&5 +$as_echo "yes" >&6; } else - echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 - { echo "$as_me:$LINENO: result: no" >&5 -echo "${ECHO_T}no" >&6; } + { $as_echo "$as_me:$LINENO: result: no" >&5 +$as_echo "no" >&6; } fi rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext -{ echo "$as_me:$LINENO: checking for resize_term" >&5 -echo $ECHO_N "checking for resize_term... $ECHO_C" >&6; } +{ $as_echo "$as_me:$LINENO: checking for resize_term" >&5 +$as_echo_n "checking for resize_term... " >&6; } cat >conftest.$ac_ext <<_ACEOF /* confdefs.h. */ _ACEOF @@ -25490,13 +26250,14 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_compile") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { test -z "$ac_c_werror_flag" || test ! -s conftest.err @@ -25506,21 +26267,21 @@ #define HAVE_CURSES_RESIZE_TERM 1 _ACEOF - { echo "$as_me:$LINENO: result: yes" >&5 -echo "${ECHO_T}yes" >&6; } + { $as_echo "$as_me:$LINENO: result: yes" >&5 +$as_echo "yes" >&6; } else - echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 - { echo "$as_me:$LINENO: result: no" >&5 -echo "${ECHO_T}no" >&6; } + { $as_echo "$as_me:$LINENO: result: no" >&5 +$as_echo "no" >&6; } fi rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext -{ echo "$as_me:$LINENO: checking for resizeterm" >&5 -echo $ECHO_N "checking for resizeterm... $ECHO_C" >&6; } +{ $as_echo "$as_me:$LINENO: checking for resizeterm" >&5 +$as_echo_n "checking for resizeterm... " >&6; } cat >conftest.$ac_ext <<_ACEOF /* confdefs.h. */ _ACEOF @@ -25542,13 +26303,14 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_compile") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { test -z "$ac_c_werror_flag" || test ! -s conftest.err @@ -25558,61 +26320,63 @@ #define HAVE_CURSES_RESIZETERM 1 _ACEOF - { echo "$as_me:$LINENO: result: yes" >&5 -echo "${ECHO_T}yes" >&6; } + { $as_echo "$as_me:$LINENO: result: yes" >&5 +$as_echo "yes" >&6; } else - echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 - { echo "$as_me:$LINENO: result: no" >&5 -echo "${ECHO_T}no" >&6; } + { $as_echo "$as_me:$LINENO: result: no" >&5 +$as_echo "no" >&6; } fi rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext -{ echo "$as_me:$LINENO: checking for /dev/ptmx" >&5 -echo $ECHO_N "checking for /dev/ptmx... $ECHO_C" >&6; } +{ $as_echo "$as_me:$LINENO: checking for /dev/ptmx" >&5 +$as_echo_n "checking for /dev/ptmx... " >&6; } if test -r /dev/ptmx then - { echo "$as_me:$LINENO: result: yes" >&5 -echo "${ECHO_T}yes" >&6; } + { $as_echo "$as_me:$LINENO: result: yes" >&5 +$as_echo "yes" >&6; } cat >>confdefs.h <<\_ACEOF #define HAVE_DEV_PTMX 1 _ACEOF else - { echo "$as_me:$LINENO: result: no" >&5 -echo "${ECHO_T}no" >&6; } + { $as_echo "$as_me:$LINENO: result: no" >&5 +$as_echo "no" >&6; } fi -{ echo "$as_me:$LINENO: checking for /dev/ptc" >&5 -echo $ECHO_N "checking for /dev/ptc... $ECHO_C" >&6; } +{ $as_echo "$as_me:$LINENO: checking for /dev/ptc" >&5 +$as_echo_n "checking for /dev/ptc... " >&6; } if test -r /dev/ptc then - { echo "$as_me:$LINENO: result: yes" >&5 -echo "${ECHO_T}yes" >&6; } + { $as_echo "$as_me:$LINENO: result: yes" >&5 +$as_echo "yes" >&6; } cat >>confdefs.h <<\_ACEOF #define HAVE_DEV_PTC 1 _ACEOF else - { echo "$as_me:$LINENO: result: no" >&5 -echo "${ECHO_T}no" >&6; } + { $as_echo "$as_me:$LINENO: result: no" >&5 +$as_echo "no" >&6; } fi -{ echo "$as_me:$LINENO: checking for %zd printf() format support" >&5 -echo $ECHO_N "checking for %zd printf() format support... $ECHO_C" >&6; } +{ $as_echo "$as_me:$LINENO: checking for %zd printf() format support" >&5 +$as_echo_n "checking for %zd printf() format support... " >&6; } if test "$cross_compiling" = yes; then - { { echo "$as_me:$LINENO: error: cannot run test program while cross compiling + { { $as_echo "$as_me:$LINENO: error: in \`$ac_pwd':" >&5 +$as_echo "$as_me: error: in \`$ac_pwd':" >&2;} +{ { $as_echo "$as_me:$LINENO: error: cannot run test program while cross compiling See \`config.log' for more details." >&5 -echo "$as_me: error: cannot run test program while cross compiling +$as_echo "$as_me: error: cannot run test program while cross compiling See \`config.log' for more details." >&2;} - { (exit 1); exit 1; }; } + { (exit 1); exit 1; }; }; } else cat >conftest.$ac_ext <<_ACEOF /* confdefs.h. */ @@ -25661,47 +26425,51 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_link") 2>&5 ac_status=$? - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { ac_try='./conftest$ac_exeext' { (case "(($ac_try" in *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_try") 2>&5 ac_status=$? - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); }; }; then - { echo "$as_me:$LINENO: result: yes" >&5 -echo "${ECHO_T}yes" >&6; } + { $as_echo "$as_me:$LINENO: result: yes" >&5 +$as_echo "yes" >&6; } cat >>confdefs.h <<\_ACEOF #define PY_FORMAT_SIZE_T "z" _ACEOF else - echo "$as_me: program exited with status $ac_status" >&5 -echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: program exited with status $ac_status" >&5 +$as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 ( exit $ac_status ) -{ echo "$as_me:$LINENO: result: no" >&5 -echo "${ECHO_T}no" >&6; } +{ $as_echo "$as_me:$LINENO: result: no" >&5 +$as_echo "no" >&6; } fi +rm -rf conftest.dSYM rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext conftest.$ac_objext conftest.$ac_ext fi -{ echo "$as_me:$LINENO: checking for socklen_t" >&5 -echo $ECHO_N "checking for socklen_t... $ECHO_C" >&6; } +{ $as_echo "$as_me:$LINENO: checking for socklen_t" >&5 +$as_echo_n "checking for socklen_t... " >&6; } if test "${ac_cv_type_socklen_t+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 + $as_echo_n "(cached) " >&6 else - cat >conftest.$ac_ext <<_ACEOF + ac_cv_type_socklen_t=no +cat >conftest.$ac_ext <<_ACEOF /* confdefs.h. */ _ACEOF cat confdefs.h >>conftest.$ac_ext @@ -25716,14 +26484,53 @@ #endif -typedef socklen_t ac__type_new_; int main () { -if ((ac__type_new_ *) 0) - return 0; -if (sizeof (ac__type_new_)) +if (sizeof (socklen_t)) + return 0; + ; return 0; +} +_ACEOF +rm -f conftest.$ac_objext +if { (ac_try="$ac_compile" +case "(($ac_try" in + *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; + *) ac_try_echo=$ac_try;; +esac +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 + (eval "$ac_compile") 2>conftest.er1 + ac_status=$? + grep -v '^ *+' conftest.er1 >conftest.err + rm -f conftest.er1 + cat conftest.err >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 + (exit $ac_status); } && { + test -z "$ac_c_werror_flag" || + test ! -s conftest.err + } && test -s conftest.$ac_objext; then + cat >conftest.$ac_ext <<_ACEOF +/* confdefs.h. */ +_ACEOF +cat confdefs.h >>conftest.$ac_ext +cat >>conftest.$ac_ext <<_ACEOF +/* end confdefs.h. */ + +#ifdef HAVE_SYS_TYPES_H +#include +#endif +#ifdef HAVE_SYS_SOCKET_H +#include +#endif + + +int +main () +{ +if (sizeof ((socklen_t))) + return 0; ; return 0; } @@ -25734,30 +26541,39 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_compile") 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { test -z "$ac_c_werror_flag" || test ! -s conftest.err } && test -s conftest.$ac_objext; then - ac_cv_type_socklen_t=yes + : +else + $as_echo "$as_me: failed program was:" >&5 +sed 's/^/| /' conftest.$ac_ext >&5 + + ac_cv_type_socklen_t=yes +fi + +rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext else - echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 - ac_cv_type_socklen_t=no + fi rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext fi -{ echo "$as_me:$LINENO: result: $ac_cv_type_socklen_t" >&5 -echo "${ECHO_T}$ac_cv_type_socklen_t" >&6; } -if test $ac_cv_type_socklen_t = yes; then +{ $as_echo "$as_me:$LINENO: result: $ac_cv_type_socklen_t" >&5 +$as_echo "$ac_cv_type_socklen_t" >&6; } +if test "x$ac_cv_type_socklen_t" = x""yes; then : else @@ -25768,8 +26584,8 @@ fi -{ echo "$as_me:$LINENO: checking for broken mbstowcs" >&5 -echo $ECHO_N "checking for broken mbstowcs... $ECHO_C" >&6; } +{ $as_echo "$as_me:$LINENO: checking for broken mbstowcs" >&5 +$as_echo_n "checking for broken mbstowcs... " >&6; } if test "$cross_compiling" = yes; then ac_cv_broken_mbstowcs=no else @@ -25795,35 +26611,38 @@ *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_link") 2>&5 ac_status=$? - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { ac_try='./conftest$ac_exeext' { (case "(($ac_try" in *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 (eval "$ac_try") 2>&5 ac_status=$? - echo "$as_me:$LINENO: \$? = $ac_status" >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); }; }; then ac_cv_broken_mbstowcs=no else - echo "$as_me: program exited with status $ac_status" >&5 -echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: program exited with status $ac_status" >&5 +$as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 ( exit $ac_status ) ac_cv_broken_mbstowcs=yes fi +rm -rf conftest.dSYM rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext conftest.$ac_objext conftest.$ac_ext fi -{ echo "$as_me:$LINENO: result: $ac_cv_broken_mbstowcs" >&5 -echo "${ECHO_T}$ac_cv_broken_mbstowcs" >&6; } +{ $as_echo "$as_me:$LINENO: result: $ac_cv_broken_mbstowcs" >&5 +$as_echo "$ac_cv_broken_mbstowcs" >&6; } if test "$ac_cv_broken_mbstowcs" = yes then @@ -25834,8 +26653,8 @@ fi # Check for --with-computed-gotos -{ echo "$as_me:$LINENO: checking for --with-computed-gotos" >&5 -echo $ECHO_N "checking for --with-computed-gotos... $ECHO_C" >&6; } +{ $as_echo "$as_me:$LINENO: checking for --with-computed-gotos" >&5 +$as_echo_n "checking for --with-computed-gotos... " >&6; } # Check whether --with-computed-gotos was given. if test "${with_computed_gotos+set}" = set; then @@ -25847,14 +26666,14 @@ #define USE_COMPUTED_GOTOS 1 _ACEOF - { echo "$as_me:$LINENO: result: yes" >&5 -echo "${ECHO_T}yes" >&6; } -else { echo "$as_me:$LINENO: result: no" >&5 -echo "${ECHO_T}no" >&6; } + { $as_echo "$as_me:$LINENO: result: yes" >&5 +$as_echo "yes" >&6; } +else { $as_echo "$as_me:$LINENO: result: no" >&5 +$as_echo "no" >&6; } fi else - { echo "$as_me:$LINENO: result: no" >&5 -echo "${ECHO_T}no" >&6; } + { $as_echo "$as_me:$LINENO: result: no" >&5 +$as_echo "no" >&6; } fi @@ -25874,15 +26693,15 @@ SRCDIRS="Parser Grammar Objects Python Modules Mac" -{ echo "$as_me:$LINENO: checking for build directories" >&5 -echo $ECHO_N "checking for build directories... $ECHO_C" >&6; } +{ $as_echo "$as_me:$LINENO: checking for build directories" >&5 +$as_echo_n "checking for build directories... " >&6; } for dir in $SRCDIRS; do if test ! -d $dir; then mkdir $dir fi done -{ echo "$as_me:$LINENO: result: done" >&5 -echo "${ECHO_T}done" >&6; } +{ $as_echo "$as_me:$LINENO: result: done" >&5 +$as_echo "done" >&6; } # generate output files ac_config_files="$ac_config_files Makefile.pre Modules/Setup.config Misc/python.pc" @@ -25914,11 +26733,12 @@ case $ac_val in #( *${as_nl}*) case $ac_var in #( - *_cv_*) { echo "$as_me:$LINENO: WARNING: Cache variable $ac_var contains a newline." >&5 -echo "$as_me: WARNING: Cache variable $ac_var contains a newline." >&2;} ;; + *_cv_*) { $as_echo "$as_me:$LINENO: WARNING: cache variable $ac_var contains a newline" >&5 +$as_echo "$as_me: WARNING: cache variable $ac_var contains a newline" >&2;} ;; esac case $ac_var in #( _ | IFS | as_nl) ;; #( + BASH_ARGV | BASH_SOURCE) eval $ac_var= ;; #( *) $as_unset $ac_var ;; esac ;; esac @@ -25951,12 +26771,12 @@ if diff "$cache_file" confcache >/dev/null 2>&1; then :; else if test -w "$cache_file"; then test "x$cache_file" != "x/dev/null" && - { echo "$as_me:$LINENO: updating cache $cache_file" >&5 -echo "$as_me: updating cache $cache_file" >&6;} + { $as_echo "$as_me:$LINENO: updating cache $cache_file" >&5 +$as_echo "$as_me: updating cache $cache_file" >&6;} cat confcache >$cache_file else - { echo "$as_me:$LINENO: not updating unwritable cache $cache_file" >&5 -echo "$as_me: not updating unwritable cache $cache_file" >&6;} + { $as_echo "$as_me:$LINENO: not updating unwritable cache $cache_file" >&5 +$as_echo "$as_me: not updating unwritable cache $cache_file" >&6;} fi fi rm -f confcache @@ -25972,7 +26792,7 @@ for ac_i in : $LIBOBJS; do test "x$ac_i" = x: && continue # 1. Remove the extension, and $U if already installed. ac_script='s/\$U\././;s/\.o$//;s/\.obj$//' - ac_i=`echo "$ac_i" | sed "$ac_script"` + ac_i=`$as_echo "$ac_i" | sed "$ac_script"` # 2. Prepend LIBOBJDIR. When used with automake>=1.10 LIBOBJDIR # will be set to the directory where LIBOBJS objects are built. ac_libobjs="$ac_libobjs \${LIBOBJDIR}$ac_i\$U.$ac_objext" @@ -25984,12 +26804,14 @@ + : ${CONFIG_STATUS=./config.status} +ac_write_fail=0 ac_clean_files_save=$ac_clean_files ac_clean_files="$ac_clean_files $CONFIG_STATUS" -{ echo "$as_me:$LINENO: creating $CONFIG_STATUS" >&5 -echo "$as_me: creating $CONFIG_STATUS" >&6;} -cat >$CONFIG_STATUS <<_ACEOF +{ $as_echo "$as_me:$LINENO: creating $CONFIG_STATUS" >&5 +$as_echo "$as_me: creating $CONFIG_STATUS" >&6;} +cat >$CONFIG_STATUS <<_ACEOF || ac_write_fail=1 #! $SHELL # Generated by $as_me. # Run this file to recreate the current configuration. @@ -26002,7 +26824,7 @@ SHELL=\${CONFIG_SHELL-$SHELL} _ACEOF -cat >>$CONFIG_STATUS <<\_ACEOF +cat >>$CONFIG_STATUS <<\_ACEOF || ac_write_fail=1 ## --------------------- ## ## M4sh Initialization. ## ## --------------------- ## @@ -26012,7 +26834,7 @@ if test -n "${ZSH_VERSION+set}" && (emulate sh) >/dev/null 2>&1; then emulate sh NULLCMD=: - # Zsh 3.x and 4.x performs word splitting on ${1+"$@"}, which + # Pre-4.2 versions of Zsh do word splitting on ${1+"$@"}, which # is contrary to our usage. Disable this feature. alias -g '${1+"$@"}'='"$@"' setopt NO_GLOB_SUBST @@ -26034,17 +26856,45 @@ as_cr_digits='0123456789' as_cr_alnum=$as_cr_Letters$as_cr_digits -# The user is always right. -if test "${PATH_SEPARATOR+set}" != set; then - echo "#! /bin/sh" >conf$$.sh - echo "exit 0" >>conf$$.sh - chmod +x conf$$.sh - if (PATH="/nonexistent;."; conf$$.sh) >/dev/null 2>&1; then - PATH_SEPARATOR=';' +as_nl=' +' +export as_nl +# Printing a long string crashes Solaris 7 /usr/bin/printf. +as_echo='\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\' +as_echo=$as_echo$as_echo$as_echo$as_echo$as_echo +as_echo=$as_echo$as_echo$as_echo$as_echo$as_echo$as_echo +if (test "X`printf %s $as_echo`" = "X$as_echo") 2>/dev/null; then + as_echo='printf %s\n' + as_echo_n='printf %s' +else + if test "X`(/usr/ucb/echo -n -n $as_echo) 2>/dev/null`" = "X-n $as_echo"; then + as_echo_body='eval /usr/ucb/echo -n "$1$as_nl"' + as_echo_n='/usr/ucb/echo -n' else - PATH_SEPARATOR=: + as_echo_body='eval expr "X$1" : "X\\(.*\\)"' + as_echo_n_body='eval + arg=$1; + case $arg in + *"$as_nl"*) + expr "X$arg" : "X\\(.*\\)$as_nl"; + arg=`expr "X$arg" : ".*$as_nl\\(.*\\)"`;; + esac; + expr "X$arg" : "X\\(.*\\)" | tr -d "$as_nl" + ' + export as_echo_n_body + as_echo_n='sh -c $as_echo_n_body as_echo' fi - rm -f conf$$.sh + export as_echo_body + as_echo='sh -c $as_echo_body as_echo' +fi + +# The user is always right. +if test "${PATH_SEPARATOR+set}" != set; then + PATH_SEPARATOR=: + (PATH='/bin;/bin'; FPATH=$PATH; sh -c :) >/dev/null 2>&1 && { + (PATH='/bin:/bin'; FPATH=$PATH; sh -c :) >/dev/null 2>&1 || + PATH_SEPARATOR=';' + } fi # Support unset when possible. @@ -26060,8 +26910,6 @@ # there to prevent editors from complaining about space-tab. # (If _AS_PATH_WALK were called with IFS unset, it would disable word # splitting by setting IFS to empty value.) -as_nl=' -' IFS=" "" $as_nl" # Find who we are. Look in the path if we contain no directory separator. @@ -26084,7 +26932,7 @@ as_myself=$0 fi if test ! -f "$as_myself"; then - echo "$as_myself: error: cannot find myself; rerun with an absolute file name" >&2 + $as_echo "$as_myself: error: cannot find myself; rerun with an absolute file name" >&2 { (exit 1); exit 1; } fi @@ -26097,17 +26945,10 @@ PS4='+ ' # NLS nuisances. -for as_var in \ - LANG LANGUAGE LC_ADDRESS LC_ALL LC_COLLATE LC_CTYPE LC_IDENTIFICATION \ - LC_MEASUREMENT LC_MESSAGES LC_MONETARY LC_NAME LC_NUMERIC LC_PAPER \ - LC_TELEPHONE LC_TIME -do - if (set +x; test -z "`(eval $as_var=C; export $as_var) 2>&1`"); then - eval $as_var=C; export $as_var - else - ($as_unset $as_var) >/dev/null 2>&1 && $as_unset $as_var - fi -done +LC_ALL=C +export LC_ALL +LANGUAGE=C +export LANGUAGE # Required to use basename. if expr a : '\(a\)' >/dev/null 2>&1 && @@ -26129,7 +26970,7 @@ $as_expr X/"$0" : '.*/\([^/][^/]*\)/*$' \| \ X"$0" : 'X\(//\)$' \| \ X"$0" : 'X\(/\)' \| . 2>/dev/null || -echo X/"$0" | +$as_echo X/"$0" | sed '/^.*\/\([^/][^/]*\)\/*$/{ s//\1/ q @@ -26180,7 +27021,7 @@ s/-\n.*// ' >$as_me.lineno && chmod +x "$as_me.lineno" || - { echo "$as_me: error: cannot create $as_me.lineno; rerun with a POSIX shell" >&2 + { $as_echo "$as_me: error: cannot create $as_me.lineno; rerun with a POSIX shell" >&2 { (exit 1); exit 1; }; } # Don't try to exec as it changes $[0], causing all sort of problems @@ -26208,7 +27049,6 @@ *) ECHO_N='-n';; esac - if expr a : '\(a\)' >/dev/null 2>&1 && test "X`expr 00001 : '.*\(...\)'`" = X001; then as_expr=expr @@ -26221,19 +27061,22 @@ rm -f conf$$.dir/conf$$.file else rm -f conf$$.dir - mkdir conf$$.dir + mkdir conf$$.dir 2>/dev/null fi -echo >conf$$.file -if ln -s conf$$.file conf$$ 2>/dev/null; then - as_ln_s='ln -s' - # ... but there are two gotchas: - # 1) On MSYS, both `ln -s file dir' and `ln file dir' fail. - # 2) DJGPP < 2.04 has no symlinks; `ln -s' creates a wrapper executable. - # In both cases, we have to default to `cp -p'. - ln -s conf$$.file conf$$.dir 2>/dev/null && test ! -f conf$$.exe || +if (echo >conf$$.file) 2>/dev/null; then + if ln -s conf$$.file conf$$ 2>/dev/null; then + as_ln_s='ln -s' + # ... but there are two gotchas: + # 1) On MSYS, both `ln -s file dir' and `ln file dir' fail. + # 2) DJGPP < 2.04 has no symlinks; `ln -s' creates a wrapper executable. + # In both cases, we have to default to `cp -p'. + ln -s conf$$.file conf$$.dir 2>/dev/null && test ! -f conf$$.exe || + as_ln_s='cp -p' + elif ln conf$$.file conf$$ 2>/dev/null; then + as_ln_s=ln + else as_ln_s='cp -p' -elif ln conf$$.file conf$$ 2>/dev/null; then - as_ln_s=ln + fi else as_ln_s='cp -p' fi @@ -26258,10 +27101,10 @@ as_test_x=' eval sh -c '\'' if test -d "$1"; then - test -d "$1/."; + test -d "$1/."; else case $1 in - -*)set "./$1";; + -*)set "./$1";; esac; case `ls -ld'$as_ls_L_option' "$1" 2>/dev/null` in ???[sx]*):;;*)false;;esac;fi @@ -26284,7 +27127,7 @@ # values after options handling. ac_log=" This file was extended by python $as_me 3.1, which was -generated by GNU Autoconf 2.61. Invocation command line was +generated by GNU Autoconf 2.63. Invocation command line was CONFIG_FILES = $CONFIG_FILES CONFIG_HEADERS = $CONFIG_HEADERS @@ -26297,29 +27140,39 @@ _ACEOF -cat >>$CONFIG_STATUS <<_ACEOF +case $ac_config_files in *" +"*) set x $ac_config_files; shift; ac_config_files=$*;; +esac + +case $ac_config_headers in *" +"*) set x $ac_config_headers; shift; ac_config_headers=$*;; +esac + + +cat >>$CONFIG_STATUS <<_ACEOF || ac_write_fail=1 # Files that config.status was made for. config_files="$ac_config_files" config_headers="$ac_config_headers" _ACEOF -cat >>$CONFIG_STATUS <<\_ACEOF +cat >>$CONFIG_STATUS <<\_ACEOF || ac_write_fail=1 ac_cs_usage="\ \`$as_me' instantiates files from templates according to the current configuration. -Usage: $0 [OPTIONS] [FILE]... +Usage: $0 [OPTION]... [FILE]... -h, --help print this help, then exit -V, --version print version number and configuration settings, then exit - -q, --quiet do not print progress messages + -q, --quiet, --silent + do not print progress messages -d, --debug don't remove temporary files --recheck update $as_me by reconfiguring in the same conditions - --file=FILE[:TEMPLATE] - instantiate the configuration file FILE - --header=FILE[:TEMPLATE] - instantiate the configuration header FILE + --file=FILE[:TEMPLATE] + instantiate the configuration file FILE + --header=FILE[:TEMPLATE] + instantiate the configuration header FILE Configuration files: $config_files @@ -26330,24 +27183,24 @@ Report bugs to ." _ACEOF -cat >>$CONFIG_STATUS <<_ACEOF +cat >>$CONFIG_STATUS <<_ACEOF || ac_write_fail=1 ac_cs_version="\\ python config.status 3.1 -configured by $0, generated by GNU Autoconf 2.61, - with options \\"`echo "$ac_configure_args" | sed 's/^ //; s/[\\""\`\$]/\\\\&/g'`\\" +configured by $0, generated by GNU Autoconf 2.63, + with options \\"`$as_echo "$ac_configure_args" | sed 's/^ //; s/[\\""\`\$]/\\\\&/g'`\\" -Copyright (C) 2006 Free Software Foundation, Inc. +Copyright (C) 2008 Free Software Foundation, Inc. This config.status script is free software; the Free Software Foundation gives unlimited permission to copy, distribute and modify it." ac_pwd='$ac_pwd' srcdir='$srcdir' INSTALL='$INSTALL' +test -n "\$AWK" || AWK=awk _ACEOF -cat >>$CONFIG_STATUS <<\_ACEOF -# If no file are specified by the user, then we need to provide default -# value. By we need to know if files were specified by the user. +cat >>$CONFIG_STATUS <<\_ACEOF || ac_write_fail=1 +# The default lists apply if the user does not specify any file. ac_need_defaults=: while test $# != 0 do @@ -26369,30 +27222,36 @@ -recheck | --recheck | --rechec | --reche | --rech | --rec | --re | --r) ac_cs_recheck=: ;; --version | --versio | --versi | --vers | --ver | --ve | --v | -V ) - echo "$ac_cs_version"; exit ;; + $as_echo "$ac_cs_version"; exit ;; --debug | --debu | --deb | --de | --d | -d ) debug=: ;; --file | --fil | --fi | --f ) $ac_shift - CONFIG_FILES="$CONFIG_FILES $ac_optarg" + case $ac_optarg in + *\'*) ac_optarg=`$as_echo "$ac_optarg" | sed "s/'/'\\\\\\\\''/g"` ;; + esac + CONFIG_FILES="$CONFIG_FILES '$ac_optarg'" ac_need_defaults=false;; --header | --heade | --head | --hea ) $ac_shift - CONFIG_HEADERS="$CONFIG_HEADERS $ac_optarg" + case $ac_optarg in + *\'*) ac_optarg=`$as_echo "$ac_optarg" | sed "s/'/'\\\\\\\\''/g"` ;; + esac + CONFIG_HEADERS="$CONFIG_HEADERS '$ac_optarg'" ac_need_defaults=false;; --he | --h) # Conflict between --help and --header - { echo "$as_me: error: ambiguous option: $1 + { $as_echo "$as_me: error: ambiguous option: $1 Try \`$0 --help' for more information." >&2 { (exit 1); exit 1; }; };; --help | --hel | -h ) - echo "$ac_cs_usage"; exit ;; + $as_echo "$ac_cs_usage"; exit ;; -q | -quiet | --quiet | --quie | --qui | --qu | --q \ | -silent | --silent | --silen | --sile | --sil | --si | --s) ac_cs_silent=: ;; # This is an error. - -*) { echo "$as_me: error: unrecognized option: $1 + -*) { $as_echo "$as_me: error: unrecognized option: $1 Try \`$0 --help' for more information." >&2 { (exit 1); exit 1; }; } ;; @@ -26411,30 +27270,32 @@ fi _ACEOF -cat >>$CONFIG_STATUS <<_ACEOF +cat >>$CONFIG_STATUS <<_ACEOF || ac_write_fail=1 if \$ac_cs_recheck; then - echo "running CONFIG_SHELL=$SHELL $SHELL $0 "$ac_configure_args \$ac_configure_extra_args " --no-create --no-recursion" >&6 - CONFIG_SHELL=$SHELL + set X '$SHELL' '$0' $ac_configure_args \$ac_configure_extra_args --no-create --no-recursion + shift + \$as_echo "running CONFIG_SHELL=$SHELL \$*" >&6 + CONFIG_SHELL='$SHELL' export CONFIG_SHELL - exec $SHELL "$0"$ac_configure_args \$ac_configure_extra_args --no-create --no-recursion + exec "\$@" fi _ACEOF -cat >>$CONFIG_STATUS <<\_ACEOF +cat >>$CONFIG_STATUS <<\_ACEOF || ac_write_fail=1 exec 5>>config.log { echo sed 'h;s/./-/g;s/^.../## /;s/...$/ ##/;p;x;p;x' <<_ASBOX ## Running $as_me. ## _ASBOX - echo "$ac_log" + $as_echo "$ac_log" } >&5 _ACEOF -cat >>$CONFIG_STATUS <<_ACEOF +cat >>$CONFIG_STATUS <<_ACEOF || ac_write_fail=1 _ACEOF -cat >>$CONFIG_STATUS <<\_ACEOF +cat >>$CONFIG_STATUS <<\_ACEOF || ac_write_fail=1 # Handling of arguments. for ac_config_target in $ac_config_targets @@ -26449,8 +27310,8 @@ "Modules/Setup.config") CONFIG_FILES="$CONFIG_FILES Modules/Setup.config" ;; "Misc/python.pc") CONFIG_FILES="$CONFIG_FILES Misc/python.pc" ;; - *) { { echo "$as_me:$LINENO: error: invalid argument: $ac_config_target" >&5 -echo "$as_me: error: invalid argument: $ac_config_target" >&2;} + *) { { $as_echo "$as_me:$LINENO: error: invalid argument: $ac_config_target" >&5 +$as_echo "$as_me: error: invalid argument: $ac_config_target" >&2;} { (exit 1); exit 1; }; };; esac done @@ -26490,226 +27351,145 @@ (umask 077 && mkdir "$tmp") } || { - echo "$me: cannot create a temporary directory in ." >&2 + $as_echo "$as_me: cannot create a temporary directory in ." >&2 { (exit 1); exit 1; } } -# -# Set up the sed scripts for CONFIG_FILES section. -# - -# No need to generate the scripts if there are no CONFIG_FILES. -# This happens for instance when ./config.status config.h +# Set up the scripts for CONFIG_FILES section. +# No need to generate them if there are no CONFIG_FILES. +# This happens for instance with `./config.status config.h'. if test -n "$CONFIG_FILES"; then -_ACEOF +ac_cr=' +' +ac_cs_awk_cr=`$AWK 'BEGIN { print "a\rb" }' /dev/null` +if test "$ac_cs_awk_cr" = "a${ac_cr}b"; then + ac_cs_awk_cr='\\r' +else + ac_cs_awk_cr=$ac_cr +fi + +echo 'BEGIN {' >"$tmp/subs1.awk" && +_ACEOF +{ + echo "cat >conf$$subs.awk <<_ACEOF" && + echo "$ac_subst_vars" | sed 's/.*/&!$&$ac_delim/' && + echo "_ACEOF" +} >conf$$subs.sh || + { { $as_echo "$as_me:$LINENO: error: could not make $CONFIG_STATUS" >&5 +$as_echo "$as_me: error: could not make $CONFIG_STATUS" >&2;} + { (exit 1); exit 1; }; } +ac_delim_num=`echo "$ac_subst_vars" | grep -c '$'` ac_delim='%!_!# ' for ac_last_try in false false false false false :; do - cat >conf$$subs.sed <<_ACEOF -SHELL!$SHELL$ac_delim -PATH_SEPARATOR!$PATH_SEPARATOR$ac_delim -PACKAGE_NAME!$PACKAGE_NAME$ac_delim -PACKAGE_TARNAME!$PACKAGE_TARNAME$ac_delim -PACKAGE_VERSION!$PACKAGE_VERSION$ac_delim -PACKAGE_STRING!$PACKAGE_STRING$ac_delim -PACKAGE_BUGREPORT!$PACKAGE_BUGREPORT$ac_delim -exec_prefix!$exec_prefix$ac_delim -prefix!$prefix$ac_delim -program_transform_name!$program_transform_name$ac_delim -bindir!$bindir$ac_delim -sbindir!$sbindir$ac_delim -libexecdir!$libexecdir$ac_delim -datarootdir!$datarootdir$ac_delim -datadir!$datadir$ac_delim -sysconfdir!$sysconfdir$ac_delim -sharedstatedir!$sharedstatedir$ac_delim -localstatedir!$localstatedir$ac_delim -includedir!$includedir$ac_delim -oldincludedir!$oldincludedir$ac_delim -docdir!$docdir$ac_delim -infodir!$infodir$ac_delim -htmldir!$htmldir$ac_delim -dvidir!$dvidir$ac_delim -pdfdir!$pdfdir$ac_delim -psdir!$psdir$ac_delim -libdir!$libdir$ac_delim -localedir!$localedir$ac_delim -mandir!$mandir$ac_delim -DEFS!$DEFS$ac_delim -ECHO_C!$ECHO_C$ac_delim -ECHO_N!$ECHO_N$ac_delim -ECHO_T!$ECHO_T$ac_delim -LIBS!$LIBS$ac_delim -build_alias!$build_alias$ac_delim -host_alias!$host_alias$ac_delim -target_alias!$target_alias$ac_delim -VERSION!$VERSION$ac_delim -SOVERSION!$SOVERSION$ac_delim -CONFIG_ARGS!$CONFIG_ARGS$ac_delim -UNIVERSALSDK!$UNIVERSALSDK$ac_delim -ARCH_RUN_32BIT!$ARCH_RUN_32BIT$ac_delim -LIPO_32BIT_FLAGS!$LIPO_32BIT_FLAGS$ac_delim -LIPO_64BIT_FLAGS!$LIPO_64BIT_FLAGS$ac_delim -PYTHONFRAMEWORK!$PYTHONFRAMEWORK$ac_delim -PYTHONFRAMEWORKIDENTIFIER!$PYTHONFRAMEWORKIDENTIFIER$ac_delim -PYTHONFRAMEWORKDIR!$PYTHONFRAMEWORKDIR$ac_delim -PYTHONFRAMEWORKPREFIX!$PYTHONFRAMEWORKPREFIX$ac_delim -PYTHONFRAMEWORKINSTALLDIR!$PYTHONFRAMEWORKINSTALLDIR$ac_delim -FRAMEWORKINSTALLFIRST!$FRAMEWORKINSTALLFIRST$ac_delim -FRAMEWORKINSTALLLAST!$FRAMEWORKINSTALLLAST$ac_delim -FRAMEWORKALTINSTALLFIRST!$FRAMEWORKALTINSTALLFIRST$ac_delim -FRAMEWORKALTINSTALLLAST!$FRAMEWORKALTINSTALLLAST$ac_delim -FRAMEWORKUNIXTOOLSPREFIX!$FRAMEWORKUNIXTOOLSPREFIX$ac_delim -MACHDEP!$MACHDEP$ac_delim -SGI_ABI!$SGI_ABI$ac_delim -CONFIGURE_MACOSX_DEPLOYMENT_TARGET!$CONFIGURE_MACOSX_DEPLOYMENT_TARGET$ac_delim -EXPORT_MACOSX_DEPLOYMENT_TARGET!$EXPORT_MACOSX_DEPLOYMENT_TARGET$ac_delim -CC!$CC$ac_delim -CFLAGS!$CFLAGS$ac_delim -LDFLAGS!$LDFLAGS$ac_delim -CPPFLAGS!$CPPFLAGS$ac_delim -ac_ct_CC!$ac_ct_CC$ac_delim -EXEEXT!$EXEEXT$ac_delim -OBJEXT!$OBJEXT$ac_delim -CXX!$CXX$ac_delim -MAINCC!$MAINCC$ac_delim -CPP!$CPP$ac_delim -GREP!$GREP$ac_delim -EGREP!$EGREP$ac_delim -BUILDEXEEXT!$BUILDEXEEXT$ac_delim -LIBRARY!$LIBRARY$ac_delim -LDLIBRARY!$LDLIBRARY$ac_delim -DLLLIBRARY!$DLLLIBRARY$ac_delim -BLDLIBRARY!$BLDLIBRARY$ac_delim -LDLIBRARYDIR!$LDLIBRARYDIR$ac_delim -INSTSONAME!$INSTSONAME$ac_delim -RUNSHARED!$RUNSHARED$ac_delim -LINKCC!$LINKCC$ac_delim -GNULD!$GNULD$ac_delim -RANLIB!$RANLIB$ac_delim -AR!$AR$ac_delim -ARFLAGS!$ARFLAGS$ac_delim -SVNVERSION!$SVNVERSION$ac_delim -INSTALL_PROGRAM!$INSTALL_PROGRAM$ac_delim -INSTALL_SCRIPT!$INSTALL_SCRIPT$ac_delim -INSTALL_DATA!$INSTALL_DATA$ac_delim -LN!$LN$ac_delim -OPT!$OPT$ac_delim -BASECFLAGS!$BASECFLAGS$ac_delim -UNIVERSAL_ARCH_FLAGS!$UNIVERSAL_ARCH_FLAGS$ac_delim -OTHER_LIBTOOL_OPT!$OTHER_LIBTOOL_OPT$ac_delim -LIBTOOL_CRUFT!$LIBTOOL_CRUFT$ac_delim -SO!$SO$ac_delim -LDSHARED!$LDSHARED$ac_delim -BLDSHARED!$BLDSHARED$ac_delim -CCSHARED!$CCSHARED$ac_delim -_ACEOF + . ./conf$$subs.sh || + { { $as_echo "$as_me:$LINENO: error: could not make $CONFIG_STATUS" >&5 +$as_echo "$as_me: error: could not make $CONFIG_STATUS" >&2;} + { (exit 1); exit 1; }; } - if test `sed -n "s/.*$ac_delim\$/X/p" conf$$subs.sed | grep -c X` = 97; then + ac_delim_n=`sed -n "s/.*$ac_delim\$/X/p" conf$$subs.awk | grep -c X` + if test $ac_delim_n = $ac_delim_num; then break elif $ac_last_try; then - { { echo "$as_me:$LINENO: error: could not make $CONFIG_STATUS" >&5 -echo "$as_me: error: could not make $CONFIG_STATUS" >&2;} + { { $as_echo "$as_me:$LINENO: error: could not make $CONFIG_STATUS" >&5 +$as_echo "$as_me: error: could not make $CONFIG_STATUS" >&2;} { (exit 1); exit 1; }; } else ac_delim="$ac_delim!$ac_delim _$ac_delim!! " fi done +rm -f conf$$subs.sh -ac_eof=`sed -n '/^CEOF[0-9]*$/s/CEOF/0/p' conf$$subs.sed` -if test -n "$ac_eof"; then - ac_eof=`echo "$ac_eof" | sort -nru | sed 1q` - ac_eof=`expr $ac_eof + 1` -fi - -cat >>$CONFIG_STATUS <<_ACEOF -cat >"\$tmp/subs-1.sed" <<\CEOF$ac_eof -/@[a-zA-Z_][a-zA-Z_0-9]*@/!b -_ACEOF -sed ' -s/[,\\&]/\\&/g; s/@/@|#_!!_#|/g -s/^/s,@/; s/!/@,|#_!!_#|/ -:n -t n -s/'"$ac_delim"'$/,g/; t -s/$/\\/; p -N; s/^.*\n//; s/[,\\&]/\\&/g; s/@/@|#_!!_#|/g; b n -' >>$CONFIG_STATUS >$CONFIG_STATUS <<_ACEOF -CEOF$ac_eof +cat >>$CONFIG_STATUS <<_ACEOF || ac_write_fail=1 +cat >>"\$tmp/subs1.awk" <<\\_ACAWK && _ACEOF +sed -n ' +h +s/^/S["/; s/!.*/"]=/ +p +g +s/^[^!]*!// +:repl +t repl +s/'"$ac_delim"'$// +t delim +:nl +h +s/\(.\{148\}\).*/\1/ +t more1 +s/["\\]/\\&/g; s/^/"/; s/$/\\n"\\/ +p +n +b repl +:more1 +s/["\\]/\\&/g; s/^/"/; s/$/"\\/ +p +g +s/.\{148\}// +t nl +:delim +h +s/\(.\{148\}\).*/\1/ +t more2 +s/["\\]/\\&/g; s/^/"/; s/$/"/ +p +b +:more2 +s/["\\]/\\&/g; s/^/"/; s/$/"\\/ +p +g +s/.\{148\}// +t delim +' >$CONFIG_STATUS || ac_write_fail=1 +rm -f conf$$subs.awk +cat >>$CONFIG_STATUS <<_ACEOF || ac_write_fail=1 +_ACAWK +cat >>"\$tmp/subs1.awk" <<_ACAWK && + for (key in S) S_is_set[key] = 1 + FS = "" + +} +{ + line = $ 0 + nfields = split(line, field, "@") + substed = 0 + len = length(field[1]) + for (i = 2; i < nfields; i++) { + key = field[i] + keylen = length(key) + if (S_is_set[key]) { + value = S[key] + line = substr(line, 1, len) "" value "" substr(line, len + keylen + 3) + len += length(value) + length(field[++i]) + substed = 1 + } else + len += 1 + keylen + } + print line +} -ac_delim='%!_!# ' -for ac_last_try in false false false false false :; do - cat >conf$$subs.sed <<_ACEOF -LINKFORSHARED!$LINKFORSHARED$ac_delim -CFLAGSFORSHARED!$CFLAGSFORSHARED$ac_delim -SHLIBS!$SHLIBS$ac_delim -USE_SIGNAL_MODULE!$USE_SIGNAL_MODULE$ac_delim -SIGNAL_OBJS!$SIGNAL_OBJS$ac_delim -USE_THREAD_MODULE!$USE_THREAD_MODULE$ac_delim -LDLAST!$LDLAST$ac_delim -THREADOBJ!$THREADOBJ$ac_delim -DLINCLDIR!$DLINCLDIR$ac_delim -DYNLOADFILE!$DYNLOADFILE$ac_delim -MACHDEP_OBJS!$MACHDEP_OBJS$ac_delim -TRUE!$TRUE$ac_delim -LIBOBJS!$LIBOBJS$ac_delim -HAVE_GETHOSTBYNAME_R_6_ARG!$HAVE_GETHOSTBYNAME_R_6_ARG$ac_delim -HAVE_GETHOSTBYNAME_R_5_ARG!$HAVE_GETHOSTBYNAME_R_5_ARG$ac_delim -HAVE_GETHOSTBYNAME_R_3_ARG!$HAVE_GETHOSTBYNAME_R_3_ARG$ac_delim -HAVE_GETHOSTBYNAME_R!$HAVE_GETHOSTBYNAME_R$ac_delim -HAVE_GETHOSTBYNAME!$HAVE_GETHOSTBYNAME$ac_delim -LIBM!$LIBM$ac_delim -LIBC!$LIBC$ac_delim -THREADHEADERS!$THREADHEADERS$ac_delim -SRCDIRS!$SRCDIRS$ac_delim -LTLIBOBJS!$LTLIBOBJS$ac_delim +_ACAWK _ACEOF - - if test `sed -n "s/.*$ac_delim\$/X/p" conf$$subs.sed | grep -c X` = 23; then - break - elif $ac_last_try; then - { { echo "$as_me:$LINENO: error: could not make $CONFIG_STATUS" >&5 -echo "$as_me: error: could not make $CONFIG_STATUS" >&2;} +cat >>$CONFIG_STATUS <<\_ACEOF || ac_write_fail=1 +if sed "s/$ac_cr//" < /dev/null > /dev/null 2>&1; then + sed "s/$ac_cr\$//; s/$ac_cr/$ac_cs_awk_cr/g" +else + cat +fi < "$tmp/subs1.awk" > "$tmp/subs.awk" \ + || { { $as_echo "$as_me:$LINENO: error: could not setup config files machinery" >&5 +$as_echo "$as_me: error: could not setup config files machinery" >&2;} { (exit 1); exit 1; }; } - else - ac_delim="$ac_delim!$ac_delim _$ac_delim!! " - fi -done - -ac_eof=`sed -n '/^CEOF[0-9]*$/s/CEOF/0/p' conf$$subs.sed` -if test -n "$ac_eof"; then - ac_eof=`echo "$ac_eof" | sort -nru | sed 1q` - ac_eof=`expr $ac_eof + 1` -fi - -cat >>$CONFIG_STATUS <<_ACEOF -cat >"\$tmp/subs-2.sed" <<\CEOF$ac_eof -/@[a-zA-Z_][a-zA-Z_0-9]*@/!b end -_ACEOF -sed ' -s/[,\\&]/\\&/g; s/@/@|#_!!_#|/g -s/^/s,@/; s/!/@,|#_!!_#|/ -:n -t n -s/'"$ac_delim"'$/,g/; t -s/$/\\/; p -N; s/^.*\n//; s/[,\\&]/\\&/g; s/@/@|#_!!_#|/g; b n -' >>$CONFIG_STATUS >$CONFIG_STATUS <<_ACEOF -:end -s/|#_!!_#|//g -CEOF$ac_eof _ACEOF - # VPATH may cause trouble with some makes, so we remove $(srcdir), # ${srcdir} and @srcdir@ from VPATH if srcdir is ".", strip leading and # trailing colons and then remove the whole line if VPATH becomes empty @@ -26725,19 +27505,133 @@ }' fi -cat >>$CONFIG_STATUS <<\_ACEOF +cat >>$CONFIG_STATUS <<\_ACEOF || ac_write_fail=1 fi # test -n "$CONFIG_FILES" +# Set up the scripts for CONFIG_HEADERS section. +# No need to generate them if there are no CONFIG_HEADERS. +# This happens for instance with `./config.status Makefile'. +if test -n "$CONFIG_HEADERS"; then +cat >"$tmp/defines.awk" <<\_ACAWK || +BEGIN { +_ACEOF + +# Transform confdefs.h into an awk script `defines.awk', embedded as +# here-document in config.status, that substitutes the proper values into +# config.h.in to produce config.h. + +# Create a delimiter string that does not exist in confdefs.h, to ease +# handling of long lines. +ac_delim='%!_!# ' +for ac_last_try in false false :; do + ac_t=`sed -n "/$ac_delim/p" confdefs.h` + if test -z "$ac_t"; then + break + elif $ac_last_try; then + { { $as_echo "$as_me:$LINENO: error: could not make $CONFIG_HEADERS" >&5 +$as_echo "$as_me: error: could not make $CONFIG_HEADERS" >&2;} + { (exit 1); exit 1; }; } + else + ac_delim="$ac_delim!$ac_delim _$ac_delim!! " + fi +done + +# For the awk script, D is an array of macro values keyed by name, +# likewise P contains macro parameters if any. Preserve backslash +# newline sequences. + +ac_word_re=[_$as_cr_Letters][_$as_cr_alnum]* +sed -n ' +s/.\{148\}/&'"$ac_delim"'/g +t rset +:rset +s/^[ ]*#[ ]*define[ ][ ]*/ / +t def +d +:def +s/\\$// +t bsnl +s/["\\]/\\&/g +s/^ \('"$ac_word_re"'\)\(([^()]*)\)[ ]*\(.*\)/P["\1"]="\2"\ +D["\1"]=" \3"/p +s/^ \('"$ac_word_re"'\)[ ]*\(.*\)/D["\1"]=" \2"/p +d +:bsnl +s/["\\]/\\&/g +s/^ \('"$ac_word_re"'\)\(([^()]*)\)[ ]*\(.*\)/P["\1"]="\2"\ +D["\1"]=" \3\\\\\\n"\\/p +t cont +s/^ \('"$ac_word_re"'\)[ ]*\(.*\)/D["\1"]=" \2\\\\\\n"\\/p +t cont +d +:cont +n +s/.\{148\}/&'"$ac_delim"'/g +t clear +:clear +s/\\$// +t bsnlc +s/["\\]/\\&/g; s/^/"/; s/$/"/p +d +:bsnlc +s/["\\]/\\&/g; s/^/"/; s/$/\\\\\\n"\\/p +b cont +' >$CONFIG_STATUS || ac_write_fail=1 + +cat >>$CONFIG_STATUS <<_ACEOF || ac_write_fail=1 + for (key in D) D_is_set[key] = 1 + FS = "" +} +/^[\t ]*#[\t ]*(define|undef)[\t ]+$ac_word_re([\t (]|\$)/ { + line = \$ 0 + split(line, arg, " ") + if (arg[1] == "#") { + defundef = arg[2] + mac1 = arg[3] + } else { + defundef = substr(arg[1], 2) + mac1 = arg[2] + } + split(mac1, mac2, "(") #) + macro = mac2[1] + prefix = substr(line, 1, index(line, defundef) - 1) + if (D_is_set[macro]) { + # Preserve the white space surrounding the "#". + print prefix "define", macro P[macro] D[macro] + next + } else { + # Replace #undef with comments. This is necessary, for example, + # in the case of _POSIX_SOURCE, which is predefined and required + # on some systems where configure will not decide to define it. + if (defundef == "undef") { + print "/*", prefix defundef, macro, "*/" + next + } + } +} +{ print } +_ACAWK +_ACEOF +cat >>$CONFIG_STATUS <<\_ACEOF || ac_write_fail=1 + { { $as_echo "$as_me:$LINENO: error: could not setup config headers machinery" >&5 +$as_echo "$as_me: error: could not setup config headers machinery" >&2;} + { (exit 1); exit 1; }; } +fi # test -n "$CONFIG_HEADERS" + -for ac_tag in :F $CONFIG_FILES :H $CONFIG_HEADERS +eval set X " :F $CONFIG_FILES :H $CONFIG_HEADERS " +shift +for ac_tag do case $ac_tag in :[FHLC]) ac_mode=$ac_tag; continue;; esac case $ac_mode$ac_tag in :[FHL]*:*);; - :L* | :C*:*) { { echo "$as_me:$LINENO: error: Invalid tag $ac_tag." >&5 -echo "$as_me: error: Invalid tag $ac_tag." >&2;} + :L* | :C*:*) { { $as_echo "$as_me:$LINENO: error: invalid tag $ac_tag" >&5 +$as_echo "$as_me: error: invalid tag $ac_tag" >&2;} { (exit 1); exit 1; }; };; :[FH]-) ac_tag=-:-;; :[FH]*) ac_tag=$ac_tag:$ac_tag.in;; @@ -26766,26 +27660,38 @@ [\\/$]*) false;; *) test -f "$srcdir/$ac_f" && ac_f="$srcdir/$ac_f";; esac || - { { echo "$as_me:$LINENO: error: cannot find input file: $ac_f" >&5 -echo "$as_me: error: cannot find input file: $ac_f" >&2;} + { { $as_echo "$as_me:$LINENO: error: cannot find input file: $ac_f" >&5 +$as_echo "$as_me: error: cannot find input file: $ac_f" >&2;} { (exit 1); exit 1; }; };; esac - ac_file_inputs="$ac_file_inputs $ac_f" + case $ac_f in *\'*) ac_f=`$as_echo "$ac_f" | sed "s/'/'\\\\\\\\''/g"`;; esac + ac_file_inputs="$ac_file_inputs '$ac_f'" done # Let's still pretend it is `configure' which instantiates (i.e., don't # use $as_me), people would be surprised to read: # /* config.h. Generated by config.status. */ - configure_input="Generated from "`IFS=: - echo $* | sed 's|^[^:]*/||;s|:[^:]*/|, |g'`" by configure." + configure_input='Generated from '` + $as_echo "$*" | sed 's|^[^:]*/||;s|:[^:]*/|, |g' + `' by configure.' if test x"$ac_file" != x-; then configure_input="$ac_file. $configure_input" - { echo "$as_me:$LINENO: creating $ac_file" >&5 -echo "$as_me: creating $ac_file" >&6;} + { $as_echo "$as_me:$LINENO: creating $ac_file" >&5 +$as_echo "$as_me: creating $ac_file" >&6;} fi + # Neutralize special characters interpreted by sed in replacement strings. + case $configure_input in #( + *\&* | *\|* | *\\* ) + ac_sed_conf_input=`$as_echo "$configure_input" | + sed 's/[\\\\&|]/\\\\&/g'`;; #( + *) ac_sed_conf_input=$configure_input;; + esac case $ac_tag in - *:-:* | *:-) cat >"$tmp/stdin";; + *:-:* | *:-) cat >"$tmp/stdin" \ + || { { $as_echo "$as_me:$LINENO: error: could not create $ac_file" >&5 +$as_echo "$as_me: error: could not create $ac_file" >&2;} + { (exit 1); exit 1; }; } ;; esac ;; esac @@ -26795,7 +27701,7 @@ X"$ac_file" : 'X\(//\)[^/]' \| \ X"$ac_file" : 'X\(//\)$' \| \ X"$ac_file" : 'X\(/\)' \| . 2>/dev/null || -echo X"$ac_file" | +$as_echo X"$ac_file" | sed '/^X\(.*[^/]\)\/\/*[^/][^/]*\/*$/{ s//\1/ q @@ -26821,7 +27727,7 @@ as_dirs= while :; do case $as_dir in #( - *\'*) as_qdir=`echo "$as_dir" | sed "s/'/'\\\\\\\\''/g"`;; #( + *\'*) as_qdir=`$as_echo "$as_dir" | sed "s/'/'\\\\\\\\''/g"`;; #'( *) as_qdir=$as_dir;; esac as_dirs="'$as_qdir' $as_dirs" @@ -26830,7 +27736,7 @@ X"$as_dir" : 'X\(//\)[^/]' \| \ X"$as_dir" : 'X\(//\)$' \| \ X"$as_dir" : 'X\(/\)' \| . 2>/dev/null || -echo X"$as_dir" | +$as_echo X"$as_dir" | sed '/^X\(.*[^/]\)\/\/*[^/][^/]*\/*$/{ s//\1/ q @@ -26851,17 +27757,17 @@ test -d "$as_dir" && break done test -z "$as_dirs" || eval "mkdir $as_dirs" - } || test -d "$as_dir" || { { echo "$as_me:$LINENO: error: cannot create directory $as_dir" >&5 -echo "$as_me: error: cannot create directory $as_dir" >&2;} + } || test -d "$as_dir" || { { $as_echo "$as_me:$LINENO: error: cannot create directory $as_dir" >&5 +$as_echo "$as_me: error: cannot create directory $as_dir" >&2;} { (exit 1); exit 1; }; }; } ac_builddir=. case "$ac_dir" in .) ac_dir_suffix= ac_top_builddir_sub=. ac_top_build_prefix= ;; *) - ac_dir_suffix=/`echo "$ac_dir" | sed 's,^\.[\\/],,'` + ac_dir_suffix=/`$as_echo "$ac_dir" | sed 's|^\.[\\/]||'` # A ".." for each directory in $ac_dir_suffix. - ac_top_builddir_sub=`echo "$ac_dir_suffix" | sed 's,/[^\\/]*,/..,g;s,/,,'` + ac_top_builddir_sub=`$as_echo "$ac_dir_suffix" | sed 's|/[^\\/]*|/..|g;s|/||'` case $ac_top_builddir_sub in "") ac_top_builddir_sub=. ac_top_build_prefix= ;; *) ac_top_build_prefix=$ac_top_builddir_sub/ ;; @@ -26901,12 +27807,13 @@ esac _ACEOF -cat >>$CONFIG_STATUS <<\_ACEOF +cat >>$CONFIG_STATUS <<\_ACEOF || ac_write_fail=1 # If the template does not know about datarootdir, expand it. # FIXME: This hack should be removed a few years after 2.60. ac_datarootdir_hack=; ac_datarootdir_seen= -case `sed -n '/datarootdir/ { +ac_sed_dataroot=' +/datarootdir/ { p q } @@ -26915,13 +27822,14 @@ /@infodir@/p /@localedir@/p /@mandir@/p -' $ac_file_inputs` in +' +case `eval "sed -n \"\$ac_sed_dataroot\" $ac_file_inputs"` in *datarootdir*) ac_datarootdir_seen=yes;; *@datadir@*|*@docdir@*|*@infodir@*|*@localedir@*|*@mandir@*) - { echo "$as_me:$LINENO: WARNING: $ac_file_inputs seems to ignore the --datarootdir setting" >&5 -echo "$as_me: WARNING: $ac_file_inputs seems to ignore the --datarootdir setting" >&2;} + { $as_echo "$as_me:$LINENO: WARNING: $ac_file_inputs seems to ignore the --datarootdir setting" >&5 +$as_echo "$as_me: WARNING: $ac_file_inputs seems to ignore the --datarootdir setting" >&2;} _ACEOF -cat >>$CONFIG_STATUS <<_ACEOF +cat >>$CONFIG_STATUS <<_ACEOF || ac_write_fail=1 ac_datarootdir_hack=' s&@datadir@&$datadir&g s&@docdir@&$docdir&g @@ -26935,15 +27843,16 @@ # Neutralize VPATH when `$srcdir' = `.'. # Shell code in configure.ac might set extrasub. # FIXME: do we really want to maintain this feature? -cat >>$CONFIG_STATUS <<_ACEOF - sed "$ac_vpsub +cat >>$CONFIG_STATUS <<_ACEOF || ac_write_fail=1 +ac_sed_extra="$ac_vpsub $extrasub _ACEOF -cat >>$CONFIG_STATUS <<\_ACEOF +cat >>$CONFIG_STATUS <<\_ACEOF || ac_write_fail=1 :t /@[a-zA-Z_][a-zA-Z_0-9]*@/!b -s&@configure_input@&$configure_input&;t t +s|@configure_input@|$ac_sed_conf_input|;t t s&@top_builddir@&$ac_top_builddir_sub&;t t +s&@top_build_prefix@&$ac_top_build_prefix&;t t s&@srcdir@&$ac_srcdir&;t t s&@abs_srcdir@&$ac_abs_srcdir&;t t s&@top_srcdir@&$ac_top_srcdir&;t t @@ -26953,119 +27862,58 @@ s&@abs_top_builddir@&$ac_abs_top_builddir&;t t s&@INSTALL@&$ac_INSTALL&;t t $ac_datarootdir_hack -" $ac_file_inputs | sed -f "$tmp/subs-1.sed" | sed -f "$tmp/subs-2.sed" >$tmp/out +" +eval sed \"\$ac_sed_extra\" "$ac_file_inputs" | $AWK -f "$tmp/subs.awk" >$tmp/out \ + || { { $as_echo "$as_me:$LINENO: error: could not create $ac_file" >&5 +$as_echo "$as_me: error: could not create $ac_file" >&2;} + { (exit 1); exit 1; }; } test -z "$ac_datarootdir_hack$ac_datarootdir_seen" && { ac_out=`sed -n '/\${datarootdir}/p' "$tmp/out"`; test -n "$ac_out"; } && { ac_out=`sed -n '/^[ ]*datarootdir[ ]*:*=/p' "$tmp/out"`; test -z "$ac_out"; } && - { echo "$as_me:$LINENO: WARNING: $ac_file contains a reference to the variable \`datarootdir' + { $as_echo "$as_me:$LINENO: WARNING: $ac_file contains a reference to the variable \`datarootdir' which seems to be undefined. Please make sure it is defined." >&5 -echo "$as_me: WARNING: $ac_file contains a reference to the variable \`datarootdir' +$as_echo "$as_me: WARNING: $ac_file contains a reference to the variable \`datarootdir' which seems to be undefined. Please make sure it is defined." >&2;} rm -f "$tmp/stdin" case $ac_file in - -) cat "$tmp/out"; rm -f "$tmp/out";; - *) rm -f "$ac_file"; mv "$tmp/out" $ac_file;; - esac + -) cat "$tmp/out" && rm -f "$tmp/out";; + *) rm -f "$ac_file" && mv "$tmp/out" "$ac_file";; + esac \ + || { { $as_echo "$as_me:$LINENO: error: could not create $ac_file" >&5 +$as_echo "$as_me: error: could not create $ac_file" >&2;} + { (exit 1); exit 1; }; } ;; :H) # # CONFIG_HEADER # -_ACEOF - -# Transform confdefs.h into a sed script `conftest.defines', that -# substitutes the proper values into config.h.in to produce config.h. -rm -f conftest.defines conftest.tail -# First, append a space to every undef/define line, to ease matching. -echo 's/$/ /' >conftest.defines -# Then, protect against being on the right side of a sed subst, or in -# an unquoted here document, in config.status. If some macros were -# called several times there might be several #defines for the same -# symbol, which is useless. But do not sort them, since the last -# AC_DEFINE must be honored. -ac_word_re=[_$as_cr_Letters][_$as_cr_alnum]* -# These sed commands are passed to sed as "A NAME B PARAMS C VALUE D", where -# NAME is the cpp macro being defined, VALUE is the value it is being given. -# PARAMS is the parameter list in the macro definition--in most cases, it's -# just an empty string. -ac_dA='s,^\\([ #]*\\)[^ ]*\\([ ]*' -ac_dB='\\)[ (].*,\\1define\\2' -ac_dC=' ' -ac_dD=' ,' - -uniq confdefs.h | - sed -n ' - t rset - :rset - s/^[ ]*#[ ]*define[ ][ ]*// - t ok - d - :ok - s/[\\&,]/\\&/g - s/^\('"$ac_word_re"'\)\(([^()]*)\)[ ]*\(.*\)/ '"$ac_dA"'\1'"$ac_dB"'\2'"${ac_dC}"'\3'"$ac_dD"'/p - s/^\('"$ac_word_re"'\)[ ]*\(.*\)/'"$ac_dA"'\1'"$ac_dB$ac_dC"'\2'"$ac_dD"'/p - ' >>conftest.defines - -# Remove the space that was appended to ease matching. -# Then replace #undef with comments. This is necessary, for -# example, in the case of _POSIX_SOURCE, which is predefined and required -# on some systems where configure will not decide to define it. -# (The regexp can be short, since the line contains either #define or #undef.) -echo 's/ $// -s,^[ #]*u.*,/* & */,' >>conftest.defines - -# Break up conftest.defines: -ac_max_sed_lines=50 - -# First sed command is: sed -f defines.sed $ac_file_inputs >"$tmp/out1" -# Second one is: sed -f defines.sed "$tmp/out1" >"$tmp/out2" -# Third one will be: sed -f defines.sed "$tmp/out2" >"$tmp/out1" -# et cetera. -ac_in='$ac_file_inputs' -ac_out='"$tmp/out1"' -ac_nxt='"$tmp/out2"' - -while : -do - # Write a here document: - cat >>$CONFIG_STATUS <<_ACEOF - # First, check the format of the line: - cat >"\$tmp/defines.sed" <<\\CEOF -/^[ ]*#[ ]*undef[ ][ ]*$ac_word_re[ ]*\$/b def -/^[ ]*#[ ]*define[ ][ ]*$ac_word_re[( ]/b def -b -:def -_ACEOF - sed ${ac_max_sed_lines}q conftest.defines >>$CONFIG_STATUS - echo 'CEOF - sed -f "$tmp/defines.sed"' "$ac_in >$ac_out" >>$CONFIG_STATUS - ac_in=$ac_out; ac_out=$ac_nxt; ac_nxt=$ac_in - sed 1,${ac_max_sed_lines}d conftest.defines >conftest.tail - grep . conftest.tail >/dev/null || break - rm -f conftest.defines - mv conftest.tail conftest.defines -done -rm -f conftest.defines conftest.tail - -echo "ac_result=$ac_in" >>$CONFIG_STATUS -cat >>$CONFIG_STATUS <<\_ACEOF if test x"$ac_file" != x-; then - echo "/* $configure_input */" >"$tmp/config.h" - cat "$ac_result" >>"$tmp/config.h" - if diff $ac_file "$tmp/config.h" >/dev/null 2>&1; then - { echo "$as_me:$LINENO: $ac_file is unchanged" >&5 -echo "$as_me: $ac_file is unchanged" >&6;} + { + $as_echo "/* $configure_input */" \ + && eval '$AWK -f "$tmp/defines.awk"' "$ac_file_inputs" + } >"$tmp/config.h" \ + || { { $as_echo "$as_me:$LINENO: error: could not create $ac_file" >&5 +$as_echo "$as_me: error: could not create $ac_file" >&2;} + { (exit 1); exit 1; }; } + if diff "$ac_file" "$tmp/config.h" >/dev/null 2>&1; then + { $as_echo "$as_me:$LINENO: $ac_file is unchanged" >&5 +$as_echo "$as_me: $ac_file is unchanged" >&6;} else - rm -f $ac_file - mv "$tmp/config.h" $ac_file + rm -f "$ac_file" + mv "$tmp/config.h" "$ac_file" \ + || { { $as_echo "$as_me:$LINENO: error: could not create $ac_file" >&5 +$as_echo "$as_me: error: could not create $ac_file" >&2;} + { (exit 1); exit 1; }; } fi else - echo "/* $configure_input */" - cat "$ac_result" + $as_echo "/* $configure_input */" \ + && eval '$AWK -f "$tmp/defines.awk"' "$ac_file_inputs" \ + || { { $as_echo "$as_me:$LINENO: error: could not create -" >&5 +$as_echo "$as_me: error: could not create -" >&2;} + { (exit 1); exit 1; }; } fi - rm -f "$tmp/out12" ;; @@ -27079,6 +27927,11 @@ chmod +x $CONFIG_STATUS ac_clean_files=$ac_clean_files_save +test $ac_write_fail = 0 || + { { $as_echo "$as_me:$LINENO: error: write failure creating $CONFIG_STATUS" >&5 +$as_echo "$as_me: error: write failure creating $CONFIG_STATUS" >&2;} + { (exit 1); exit 1; }; } + # configure is writing to config.log, and then calls config.status. # config.status does its own redirection, appending to config.log. @@ -27100,6 +27953,10 @@ # would make configure fail if this is the last instruction. $ac_cs_success || { (exit 1); exit 1; } fi +if test -n "$ac_unrecognized_opts" && test "$enable_option_checking" != no; then + { $as_echo "$as_me:$LINENO: WARNING: unrecognized options: $ac_unrecognized_opts" >&5 +$as_echo "$as_me: WARNING: unrecognized options: $ac_unrecognized_opts" >&2;} +fi echo "creating Modules/Setup" Modified: python/branches/release31-maint/configure.in ============================================================================== --- python/branches/release31-maint/configure.in (original) +++ python/branches/release31-maint/configure.in Sun May 2 18:45:41 2010 @@ -1771,7 +1771,7 @@ FreeBSD*) if [[ "`$CC -dM -E - Author: victor.stinner Date: Sun May 2 19:24:51 2010 New Revision: 80703 Log: Issue #8533: revert r80694; try a different fix: regrtest uses backslashreplace error handler for stdout to avoid UnicodeEncodeError (write non-ASCII character to stdout using ASCII encoding) Modified: python/branches/py3k/Lib/test/regrtest.py python/branches/py3k/Lib/test/support.py python/branches/py3k/Misc/NEWS Modified: python/branches/py3k/Lib/test/regrtest.py ============================================================================== --- python/branches/py3k/Lib/test/regrtest.py (original) +++ python/branches/py3k/Lib/test/regrtest.py Sun May 2 19:24:51 2010 @@ -376,6 +376,7 @@ elif o in ('-j', '--multiprocess'): use_mp = int(a) elif o == '--slaveargs': + replace_stdout() args, kwargs = json.loads(a) try: result = runtest(*args, **kwargs) @@ -514,6 +515,8 @@ else: tests = iter(selected) + replace_stdout() + if use_mp: try: from threading import Thread @@ -727,6 +730,14 @@ tests.append(modname) return stdtests + sorted(tests) +def replace_stdout(): + """Set stdout encoder error handler to backslashreplace (as stderr error + handler) to avoid UnicodeEncodeError when printing a traceback""" + stdout = sys.stdout + sys.stdout = open(stdout.fileno(), 'w', + encoding=stdout.encoding, + errors="backslashreplace") + def runtest(test, verbose, quiet, testdir=None, huntrleaks=False, debug=False, use_resources=None): """Run a single test. @@ -939,8 +950,8 @@ print("test", test, "crashed --", str(type) + ":", value) sys.stdout.flush() if verbose or debug: - traceback.print_exc(file=sys.stderr) - sys.stderr.flush() + traceback.print_exc(file=sys.stdout) + sys.stdout.flush() return FAILED, test_time else: if refleak: Modified: python/branches/py3k/Lib/test/support.py ============================================================================== --- python/branches/py3k/Lib/test/support.py (original) +++ python/branches/py3k/Lib/test/support.py Sun May 2 19:24:51 2010 @@ -1020,7 +1020,7 @@ def _run_suite(suite): """Run tests from a unittest.TestSuite-derived class.""" if verbose: - runner = unittest.TextTestRunner(sys.stderr, verbosity=2) + runner = unittest.TextTestRunner(sys.stdout, verbosity=2) else: runner = BasicTestRunner() Modified: python/branches/py3k/Misc/NEWS ============================================================================== --- python/branches/py3k/Misc/NEWS (original) +++ python/branches/py3k/Misc/NEWS Sun May 2 19:24:51 2010 @@ -1201,8 +1201,8 @@ Tests ----- -- Issue #8533: Write tracebacks and failed tests to sys.stderr instead of - sys.stdout to avoid UnicodeEncodeError (use backslashreplace error handler) +- Issue #8533: regrtest uses backslashreplace error handler for stdout to avoid + UnicodeEncodeError (write non-ASCII character to stdout using ASCII encoding) - Issue #8576: Remove use of find_unused_port() in test_smtplib and test_multiprocessing. Patch by Paul Moore. From python-checkins at python.org Sun May 2 21:51:14 2010 From: python-checkins at python.org (antoine.pitrou) Date: Sun, 2 May 2010 21:51:14 +0200 (CEST) Subject: [Python-checkins] r80704 - in python/trunk: Misc/NEWS Modules/gcmodule.c Message-ID: <20100502195114.A2471C8B8@mail.python.org> Author: antoine.pitrou Date: Sun May 2 21:51:14 2010 New Revision: 80704 Log: Issue #4687: Fix accuracy of garbage collection runtimes displayed with gc.DEBUG_STATS. Modified: python/trunk/Misc/NEWS python/trunk/Modules/gcmodule.c Modified: python/trunk/Misc/NEWS ============================================================================== --- python/trunk/Misc/NEWS (original) +++ python/trunk/Misc/NEWS Sun May 2 21:51:14 2010 @@ -31,6 +31,9 @@ Library ------- +- Issue #4687: Fix accuracy of garbage collection runtimes displayed with + gc.DEBUG_STATS. + - Issue #7192: webbrowser.get("firefox") now wors on Mac OS X, as does webbrowser.get("safari"). Modified: python/trunk/Modules/gcmodule.c ============================================================================== --- python/trunk/Modules/gcmodule.c (original) +++ python/trunk/Modules/gcmodule.c Sun May 2 21:51:14 2010 @@ -837,13 +837,13 @@ } if (debug & DEBUG_STATS) { - t1 = get_time(); PySys_WriteStderr("gc: collecting generation %d...\n", generation); PySys_WriteStderr("gc: objects in each generation:"); for (i = 0; i < NUM_GENERATIONS; i++) PySys_WriteStderr(" %" PY_FORMAT_SIZE_T "d", gc_list_size(GEN_HEAD(i))); + t1 = get_time(); PySys_WriteStderr("\n"); } From python-checkins at python.org Sun May 2 21:59:47 2010 From: python-checkins at python.org (antoine.pitrou) Date: Sun, 2 May 2010 21:59:47 +0200 (CEST) Subject: [Python-checkins] r80705 - in python/branches/py3k: Misc/NEWS Modules/gcmodule.c Message-ID: <20100502195947.53460C81E@mail.python.org> Author: antoine.pitrou Date: Sun May 2 21:59:47 2010 New Revision: 80705 Log: Merged revisions 80704 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r80704 | antoine.pitrou | 2010-05-02 21:51:14 +0200 (dim., 02 mai 2010) | 4 lines Issue #4687: Fix accuracy of garbage collection runtimes displayed with gc.DEBUG_STATS. ........ Modified: python/branches/py3k/ (props changed) python/branches/py3k/Misc/NEWS python/branches/py3k/Modules/gcmodule.c Modified: python/branches/py3k/Misc/NEWS ============================================================================== --- python/branches/py3k/Misc/NEWS (original) +++ python/branches/py3k/Misc/NEWS Sun May 2 21:59:47 2010 @@ -345,6 +345,9 @@ Library ------- +- Issue #4687: Fix accuracy of garbage collection runtimes displayed with + gc.DEBUG_STATS. + - Issue #7192: webbrowser.get("firefox") now wors on Mac OS X, as does webbrowser.get("safari"). Modified: python/branches/py3k/Modules/gcmodule.c ============================================================================== --- python/branches/py3k/Modules/gcmodule.c (original) +++ python/branches/py3k/Modules/gcmodule.c Sun May 2 21:59:47 2010 @@ -804,13 +804,13 @@ } if (debug & DEBUG_STATS) { - t1 = get_time(); PySys_WriteStderr("gc: collecting generation %d...\n", generation); PySys_WriteStderr("gc: objects in each generation:"); for (i = 0; i < NUM_GENERATIONS; i++) PySys_WriteStderr(" %" PY_FORMAT_SIZE_T "d", gc_list_size(GEN_HEAD(i))); + t1 = get_time(); PySys_WriteStderr("\n"); } From python-checkins at python.org Sun May 2 21:59:51 2010 From: python-checkins at python.org (antoine.pitrou) Date: Sun, 2 May 2010 21:59:51 +0200 (CEST) Subject: [Python-checkins] r80706 - in python/branches/release26-maint: Misc/NEWS Modules/gcmodule.c Message-ID: <20100502195951.3E709EA2A@mail.python.org> Author: antoine.pitrou Date: Sun May 2 21:59:51 2010 New Revision: 80706 Log: Merged revisions 80704 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r80704 | antoine.pitrou | 2010-05-02 21:51:14 +0200 (dim., 02 mai 2010) | 4 lines Issue #4687: Fix accuracy of garbage collection runtimes displayed with gc.DEBUG_STATS. ........ Modified: python/branches/release26-maint/ (props changed) python/branches/release26-maint/Misc/NEWS python/branches/release26-maint/Modules/gcmodule.c Modified: python/branches/release26-maint/Misc/NEWS ============================================================================== --- python/branches/release26-maint/Misc/NEWS (original) +++ python/branches/release26-maint/Misc/NEWS Sun May 2 21:59:51 2010 @@ -33,6 +33,9 @@ Library ------- +- Issue #4687: Fix accuracy of garbage collection runtimes displayed with + gc.DEBUG_STATS. + - Issue #8577: distutils.sysconfig.get_python_inc() now makes a difference between the build dir and the source dir when looking for "python.h" or "Include". Modified: python/branches/release26-maint/Modules/gcmodule.c ============================================================================== --- python/branches/release26-maint/Modules/gcmodule.c (original) +++ python/branches/release26-maint/Modules/gcmodule.c Sun May 2 21:59:51 2010 @@ -780,13 +780,13 @@ } if (debug & DEBUG_STATS) { - t1 = get_time(); PySys_WriteStderr("gc: collecting generation %d...\n", generation); PySys_WriteStderr("gc: objects in each generation:"); for (i = 0; i < NUM_GENERATIONS; i++) PySys_WriteStderr(" %" PY_FORMAT_SIZE_T "d", gc_list_size(GEN_HEAD(i))); + t1 = get_time(); PySys_WriteStderr("\n"); } From python-checkins at python.org Sun May 2 22:06:55 2010 From: python-checkins at python.org (antoine.pitrou) Date: Sun, 2 May 2010 22:06:55 +0200 (CEST) Subject: [Python-checkins] r80707 - in python/branches/release31-maint: Misc/NEWS Modules/gcmodule.c Message-ID: <20100502200655.2F060ECB6@mail.python.org> Author: antoine.pitrou Date: Sun May 2 22:06:54 2010 New Revision: 80707 Log: Merged revisions 80705 via svnmerge from svn+ssh://pythondev at svn.python.org/python/branches/py3k ................ r80705 | antoine.pitrou | 2010-05-02 21:59:47 +0200 (dim., 02 mai 2010) | 10 lines Merged revisions 80704 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r80704 | antoine.pitrou | 2010-05-02 21:51:14 +0200 (dim., 02 mai 2010) | 4 lines Issue #4687: Fix accuracy of garbage collection runtimes displayed with gc.DEBUG_STATS. ........ ................ Modified: python/branches/release31-maint/ (props changed) python/branches/release31-maint/Misc/NEWS python/branches/release31-maint/Modules/gcmodule.c Modified: python/branches/release31-maint/Misc/NEWS ============================================================================== --- python/branches/release31-maint/Misc/NEWS (original) +++ python/branches/release31-maint/Misc/NEWS Sun May 2 22:06:54 2010 @@ -40,6 +40,9 @@ Library ------- +- Issue #4687: Fix accuracy of garbage collection runtimes displayed with + gc.DEBUG_STATS. + - Issue #8464: tarfile no longer creates files with execute permissions set when mode="w|" is used. Modified: python/branches/release31-maint/Modules/gcmodule.c ============================================================================== --- python/branches/release31-maint/Modules/gcmodule.c (original) +++ python/branches/release31-maint/Modules/gcmodule.c Sun May 2 22:06:54 2010 @@ -804,13 +804,13 @@ } if (debug & DEBUG_STATS) { - t1 = get_time(); PySys_WriteStderr("gc: collecting generation %d...\n", generation); PySys_WriteStderr("gc: objects in each generation:"); for (i = 0; i < NUM_GENERATIONS; i++) PySys_WriteStderr(" %" PY_FORMAT_SIZE_T "d", gc_list_size(GEN_HEAD(i))); + t1 = get_time(); PySys_WriteStderr("\n"); } From python-checkins at python.org Sun May 2 22:39:42 2010 From: python-checkins at python.org (michael.foord) Date: Sun, 2 May 2010 22:39:42 +0200 (CEST) Subject: [Python-checkins] r80708 - python/trunk/Lib/unittest/test/test_result.py Message-ID: <20100502203942.58284C7D9@mail.python.org> Author: michael.foord Date: Sun May 2 22:39:42 2010 New Revision: 80708 Log: Fix unittest tests to not abuse traceback.format_exception Modified: python/trunk/Lib/unittest/test/test_result.py Modified: python/trunk/Lib/unittest/test/test_result.py ============================================================================== --- python/trunk/Lib/unittest/test/test_result.py (original) +++ python/trunk/Lib/unittest/test/test_result.py Sun May 2 22:39:42 2010 @@ -3,6 +3,7 @@ from StringIO import StringIO from test import test_support +import traceback import unittest @@ -361,6 +362,15 @@ runner.run(Test('testFoo')) +class MockTraceback(object): + @staticmethod + def format_exception(*_): + return ['A traceback'] + +def restore_traceback(): + unittest.result.traceback = traceback + + class TestOutputBuffering(unittest.TestCase): def setUp(self): @@ -441,6 +451,9 @@ return result def testBufferOutputAddErrorOrFailure(self): + unittest.result.traceback = MockTraceback + self.addCleanup(restore_traceback) + for message_attr, add_attr, include_error in [ ('errors', 'addError', True), ('failures', 'addFailure', False), @@ -476,7 +489,7 @@ Stderr: bar """) - expectedFullMessage = 'None\n%s%s' % (expectedOutMessage, expectedErrMessage) + expectedFullMessage = 'A traceback%s%s' % (expectedOutMessage, expectedErrMessage) self.assertIs(test, self) self.assertEqual(result._original_stdout.getvalue(), expectedOutMessage) From python-checkins at python.org Sun May 2 23:00:23 2010 From: python-checkins at python.org (michael.foord) Date: Sun, 2 May 2010 23:00:23 +0200 (CEST) Subject: [Python-checkins] r80709 - in python/branches/py3k: Lib/unittest/result.py Lib/unittest/test/test_result.py Message-ID: <20100502210023.1D779EE992@mail.python.org> Author: michael.foord Date: Sun May 2 23:00:22 2010 New Revision: 80709 Log: Merged revisions 80708 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r80708 | michael.foord | 2010-05-02 21:39:42 +0100 (Sun, 02 May 2010) | 1 line Fix unittest tests to not abuse traceback.format_exception ........ Modified: python/branches/py3k/ (props changed) python/branches/py3k/Lib/unittest/result.py python/branches/py3k/Lib/unittest/test/test_result.py Modified: python/branches/py3k/Lib/unittest/result.py ============================================================================== --- python/branches/py3k/Lib/unittest/result.py (original) +++ python/branches/py3k/Lib/unittest/result.py Sun May 2 23:00:22 2010 @@ -153,9 +153,7 @@ length = self._count_relevant_tb_levels(tb) msgLines = traceback.format_exception(exctype, value, tb, length) else: - chain = exctype is not None - msgLines = traceback.format_exception(exctype, value, tb, - chain=chain) + msgLines = traceback.format_exception(exctype, value, tb) if self.buffer: output = sys.stdout.getvalue() Modified: python/branches/py3k/Lib/unittest/test/test_result.py ============================================================================== --- python/branches/py3k/Lib/unittest/test/test_result.py (original) +++ python/branches/py3k/Lib/unittest/test/test_result.py Sun May 2 23:00:22 2010 @@ -4,6 +4,7 @@ from test import support +import traceback import unittest @@ -361,6 +362,15 @@ runner.run(Test('testFoo')) +class MockTraceback(object): + @staticmethod + def format_exception(*_): + return ['A traceback'] + +def restore_traceback(): + unittest.result.traceback = traceback + + class TestOutputBuffering(unittest.TestCase): def setUp(self): @@ -441,6 +451,9 @@ return result def testBufferOutputAddErrorOrFailure(self): + unittest.result.traceback = MockTraceback + self.addCleanup(restore_traceback) + for message_attr, add_attr, include_error in [ ('errors', 'addError', True), ('failures', 'addFailure', False), @@ -476,7 +489,8 @@ Stderr: bar """) - expectedFullMessage = 'NoneType\n%s%s' % (expectedOutMessage, expectedErrMessage) + + expectedFullMessage = 'A traceback%s%s' % (expectedOutMessage, expectedErrMessage) self.assertIs(test, self) self.assertEqual(result._original_stdout.getvalue(), expectedOutMessage) From python-checkins at python.org Sun May 2 23:51:23 2010 From: python-checkins at python.org (brett.cannon) Date: Sun, 2 May 2010 23:51:23 +0200 (CEST) Subject: [Python-checkins] r80710 - in python/trunk/Misc: NEWS Vim/python.vim Message-ID: <20100502215123.EF238EE9A1@mail.python.org> Author: brett.cannon Date: Sun May 2 23:51:23 2010 New Revision: 80710 Log: Update the Vim syntax highlight file. Modified: python/trunk/Misc/NEWS python/trunk/Misc/Vim/python.vim Modified: python/trunk/Misc/NEWS ============================================================================== --- python/trunk/Misc/NEWS (original) +++ python/trunk/Misc/NEWS Sun May 2 23:51:23 2010 @@ -157,6 +157,11 @@ - Issue #3646: It is now easily possible to install a Python framework into your home directory on MacOSX, see Mac/README for more information. +Misc +---- + +- Update the Vim syntax highlight file. + What's New in Python 2.7 beta 1? ================================ Modified: python/trunk/Misc/Vim/python.vim ============================================================================== --- python/trunk/Misc/Vim/python.vim (original) +++ python/trunk/Misc/Vim/python.vim Sun May 2 23:51:23 2010 @@ -1,4 +1,4 @@ -" Auto-generated Vim syntax file for Python (trunk: r60376M). +" Auto-generated Vim syntax file for Python (trunk: r80490). " " To use: copy or symlink to ~/.vim/syntax/python.vim @@ -63,31 +63,32 @@ if exists("python_highlight_builtins") syn keyword pythonBuiltin Ellipsis False None NotImplemented True __debug__ - syn keyword pythonBuiltin __import__ abs all any apply basestring bool - syn keyword pythonBuiltin buffer bytes callable chr classmethod cmp coerce - syn keyword pythonBuiltin compile complex copyright credits delattr dict - syn keyword pythonBuiltin dir divmod enumerate eval execfile exit file - syn keyword pythonBuiltin filter float frozenset getattr globals hasattr - syn keyword pythonBuiltin hash help hex id input int intern isinstance - syn keyword pythonBuiltin issubclass iter len license list locals long map - syn keyword pythonBuiltin max min object oct open ord pow property quit - syn keyword pythonBuiltin range raw_input reduce reload repr reversed round - syn keyword pythonBuiltin set setattr slice sorted staticmethod str sum - syn keyword pythonBuiltin super trunc tuple type unichr unicode vars xrange - syn keyword pythonBuiltin zip + syn keyword pythonBuiltin __import__ abs all any apply basestring bin bool + syn keyword pythonBuiltin buffer bytearray bytes callable chr classmethod + syn keyword pythonBuiltin cmp coerce compile complex copyright credits + syn keyword pythonBuiltin delattr dict dir divmod enumerate eval execfile + syn keyword pythonBuiltin exit file filter float format frozenset getattr + syn keyword pythonBuiltin globals hasattr hash help hex id input int intern + syn keyword pythonBuiltin isinstance issubclass iter len license list + syn keyword pythonBuiltin locals long map max memoryview min next object + syn keyword pythonBuiltin oct open ord pow print property quit range + syn keyword pythonBuiltin raw_input reduce reload repr reversed round set + syn keyword pythonBuiltin setattr slice sorted staticmethod str sum super + syn keyword pythonBuiltin tuple type unichr unicode vars xrange zip endif if exists("python_highlight_exceptions") syn keyword pythonException ArithmeticError AssertionError AttributeError - syn keyword pythonException BaseException DeprecationWarning EOFError - syn keyword pythonException EnvironmentError Exception FloatingPointError - syn keyword pythonException FutureWarning GeneratorExit IOError ImportError - syn keyword pythonException ImportWarning IndentationError IndexError - syn keyword pythonException KeyError KeyboardInterrupt LookupError - syn keyword pythonException MemoryError NameError NotImplementedError - syn keyword pythonException OSError OverflowError PendingDeprecationWarning + syn keyword pythonException BaseException BufferError BytesWarning + syn keyword pythonException DeprecationWarning EOFError EnvironmentError + syn keyword pythonException Exception FloatingPointError FutureWarning + syn keyword pythonException GeneratorExit IOError ImportError ImportWarning + syn keyword pythonException IndentationError IndexError KeyError + syn keyword pythonException KeyboardInterrupt LookupError MemoryError + syn keyword pythonException NameError NotImplementedError OSError + syn keyword pythonException OverflowError PendingDeprecationWarning syn keyword pythonException ReferenceError RuntimeError RuntimeWarning syn keyword pythonException StandardError StopIteration SyntaxError syn keyword pythonException SyntaxWarning SystemError SystemExit TabError From solipsis at pitrou.net Mon May 3 00:39:16 2010 From: solipsis at pitrou.net (solipsis at pitrou.net) Date: Mon, 3 May 2010 00:39:16 +0200 (CEST) Subject: [Python-checkins] Daily py3k reference leaks (r80709): sum=0 Message-ID: <20100502223916.8F3AB1770A@ns6635.ovh.net> py3k results for svn r80709 (hg cset 9cbd66bffbbc) -------------------------------------------------- Command line was: ['./python', '-m', 'test.regrtest', '-uall', '-R', '3:3:/home/antoine/py3k/refleaks/reflogEZn_Ld', '-x'] From python-checkins at python.org Mon May 3 10:35:56 2010 From: python-checkins at python.org (victor.stinner) Date: Mon, 3 May 2010 10:35:56 +0200 (CEST) Subject: [Python-checkins] r80711 - in python/branches/release31-maint: Lib/test/regrtest.py Misc/NEWS Message-ID: <20100503083556.A5B6FFAC9@mail.python.org> Author: victor.stinner Date: Mon May 3 10:35:56 2010 New Revision: 80711 Log: Merged revisions 80694,80703 via svnmerge from svn+ssh://pythondev at svn.python.org/python/branches/py3k ........ r80694 | victor.stinner | 2010-05-02 11:37:08 +0200 (dim., 02 mai 2010) | 3 lines Issue #8533: Write tracebacks and failed tests to sys.stderr instead of sys.stdout to avoid UnicodeEncodeError (use backslashreplace error handler) ........ r80703 | victor.stinner | 2010-05-02 19:24:51 +0200 (dim., 02 mai 2010) | 4 lines Issue #8533: revert r80694; try a different fix: regrtest uses backslashreplace error handler for stdout to avoid UnicodeEncodeError (write non-ASCII character to stdout using ASCII encoding) ........ Modified: python/branches/release31-maint/ (props changed) python/branches/release31-maint/Lib/test/regrtest.py python/branches/release31-maint/Misc/NEWS Modified: python/branches/release31-maint/Lib/test/regrtest.py ============================================================================== --- python/branches/release31-maint/Lib/test/regrtest.py (original) +++ python/branches/release31-maint/Lib/test/regrtest.py Mon May 3 10:35:56 2010 @@ -411,6 +411,7 @@ support.verbose = verbose # Tell tests to be moderately quiet support.use_resources = use_resources save_modules = sys.modules.keys() + replace_stdout() for test in tests: if not quiet: print(test) @@ -556,6 +557,14 @@ tests.sort() return stdtests + tests +def replace_stdout(): + """Set stdout encoder error handler to backslashreplace (as stderr error + handler) to avoid UnicodeEncodeError when printing a traceback""" + stdout = sys.stdout + sys.stdout = open(stdout.fileno(), 'w', + encoding=stdout.encoding, + errors="backslashreplace") + def runtest(test, generate, verbose, quiet, test_times, testdir=None, huntrleaks=False, debug=False): """Run a single test. Modified: python/branches/release31-maint/Misc/NEWS ============================================================================== --- python/branches/release31-maint/Misc/NEWS (original) +++ python/branches/release31-maint/Misc/NEWS Mon May 3 10:35:56 2010 @@ -140,6 +140,9 @@ Tests ----- +- Issue #8533: regrtest uses backslashreplace error handler for stdout to avoid + UnicodeEncodeError (write non-ASCII character to stdout using ASCII encoding) + - Issue #8576: Remove use of find_unused_port() in test_smtplib and test_multiprocessing. Patch by Paul Moore. From python-checkins at python.org Mon May 3 17:11:53 2010 From: python-checkins at python.org (vinay.sajip) Date: Mon, 3 May 2010 17:11:53 +0200 (CEST) Subject: [Python-checkins] r80712 - in python/trunk: Lib/logging/config.py Lib/test/test_logging.py Misc/NEWS Message-ID: <20100503151153.E411FE784@mail.python.org> Author: vinay.sajip Date: Mon May 3 17:11:53 2010 New Revision: 80712 Log: Issue #8576: logging updated to remove usage of find_unused_port(). Modified: python/trunk/Lib/logging/config.py python/trunk/Lib/test/test_logging.py python/trunk/Misc/NEWS Modified: python/trunk/Lib/logging/config.py ============================================================================== --- python/trunk/Lib/logging/config.py (original) +++ python/trunk/Lib/logging/config.py Mon May 3 17:11:53 2010 @@ -873,6 +873,8 @@ def run(self): server = self.rcvr(port=self.port, handler=self.hdlr, ready=self.ready) + if self.port == 0: + self.port = server.server_address[1] self.ready.set() global _listener logging._acquireLock() Modified: python/trunk/Lib/test/test_logging.py ============================================================================== --- python/trunk/Lib/test/test_logging.py (original) +++ python/trunk/Lib/test/test_logging.py Mon May 3 17:11:53 2010 @@ -38,8 +38,7 @@ import struct import sys import tempfile -from test.test_support import captured_stdout, run_with_locale, run_unittest,\ - find_unused_port +from test.test_support import captured_stdout, run_with_locale, run_unittest import textwrap import unittest import warnings @@ -1664,10 +1663,12 @@ @unittest.skipUnless(threading, 'listen() needs threading to work') def setup_via_listener(self, text): - port = find_unused_port() - t = logging.config.listen(port) + # Ask for a randomly assigned port (by using port 0) + t = logging.config.listen(0) t.start() t.ready.wait() + # Now get the port allocated + port = t.port t.ready.clear() try: sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) Modified: python/trunk/Misc/NEWS ============================================================================== --- python/trunk/Misc/NEWS (original) +++ python/trunk/Misc/NEWS Mon May 3 17:11:53 2010 @@ -31,6 +31,8 @@ Library ------- +- Issue #8576: logging updated to remove usage of find_unused_port(). + - Issue #4687: Fix accuracy of garbage collection runtimes displayed with gc.DEBUG_STATS. From python-checkins at python.org Mon May 3 17:39:57 2010 From: python-checkins at python.org (vinay.sajip) Date: Mon, 3 May 2010 17:39:57 +0200 (CEST) Subject: [Python-checkins] r80713 - in python/branches/release26-maint: Lib/logging/__init__.py Misc/NEWS Message-ID: <20100503153957.C2BC1E320@mail.python.org> Author: vinay.sajip Date: Mon May 3 17:39:57 2010 New Revision: 80713 Log: Issue #8581: logging: removed errors raised when closing handlers twice. Modified: python/branches/release26-maint/Lib/logging/__init__.py python/branches/release26-maint/Misc/NEWS Modified: python/branches/release26-maint/Lib/logging/__init__.py ============================================================================== --- python/branches/release26-maint/Lib/logging/__init__.py (original) +++ python/branches/release26-maint/Lib/logging/__init__.py Mon May 3 17:39:57 2010 @@ -702,8 +702,10 @@ #get the module data lock, as we're updating a shared structure. _acquireLock() try: #unlikely to raise an exception, but you never know... - del _handlers[self] - _handlerList.remove(self) + if self in _handlers: + del _handlers[self] + if self in _handlerList: + _handlerList.remove(self) finally: _releaseLock() Modified: python/branches/release26-maint/Misc/NEWS ============================================================================== --- python/branches/release26-maint/Misc/NEWS (original) +++ python/branches/release26-maint/Misc/NEWS Mon May 3 17:39:57 2010 @@ -33,6 +33,8 @@ Library ------- +- Issue #8581: logging: removed errors raised when closing handlers twice. + - Issue #4687: Fix accuracy of garbage collection runtimes displayed with gc.DEBUG_STATS. From python-checkins at python.org Mon May 3 17:57:24 2010 From: python-checkins at python.org (antoine.pitrou) Date: Mon, 3 May 2010 17:57:24 +0200 (CEST) Subject: [Python-checkins] r80714 - python/branches/py3k/Doc/c-api/arg.rst Message-ID: <20100503155724.2515CFBB8@mail.python.org> Author: antoine.pitrou Date: Mon May 3 17:57:23 2010 New Revision: 80714 Log: Issue #8593: Fix, reorder and improve the documentation for argument parsing Modified: python/branches/py3k/Doc/c-api/arg.rst Modified: python/branches/py3k/Doc/c-api/arg.rst ============================================================================== --- python/branches/py3k/Doc/c-api/arg.rst (original) +++ python/branches/py3k/Doc/c-api/arg.rst Mon May 3 17:57:23 2010 @@ -14,6 +14,10 @@ strings* which are used to tell the function about the expected arguments. The format strings use the same syntax for each of these functions. +----------------- +Parsing arguments +----------------- + A format string consists of zero or more "format units." A format unit describes one Python object; it is usually a single character or a parenthesized sequence of format units. With a few exceptions, a format unit that is not a @@ -23,75 +27,108 @@ the format unit; and the entry in [square] brackets is the type of the C variable(s) whose address should be passed. -``s`` (string or Unicode object) [const char \*] - Convert a Python string or Unicode object to a C pointer to a character string. - You must not provide storage for the string itself; a pointer to an existing - string is stored into the character pointer variable whose address you pass. - The C string is NUL-terminated. The Python string must not contain embedded NUL - bytes; if it does, a :exc:`TypeError` exception is raised. Unicode objects are - converted to C strings using the default encoding. If this conversion fails, a - :exc:`UnicodeError` is raised. - - Starting with Python 2.5 the type of the length argument can be - controlled by defining the macro :cmacro:`PY_SSIZE_T_CLEAN` before - including :file:`Python.h`. If the macro is defined, length is a - :ctype:`Py_ssize_t` rather than an int. - -``s*`` (string, Unicode, or any buffer compatible object) [Py_buffer] - This is similar to ``s``, but the code fills a :ctype:`Py_buffer` structure - provided by the caller. In this case the Python string may contain embedded - null bytes. Unicode objects pass back a pointer to the default encoded - string version of the object if such a conversion is possible. The - underlying buffer is locked, so that the caller can subsequently use the - buffer even inside a ``Py_BEGIN_ALLOW_THREADS`` block. **The caller is - responsible** for calling ``PyBuffer_Release`` with the structure after it - has processed the data. - -``s#`` (string, Unicode or any read buffer compatible object) [const char \*, int or :ctype:`Py_ssize_t`] - This variant on ``s`` stores into two C variables, the first one a pointer to - a character string, the second one its length. In this case the Python - string may contain embedded null bytes. Unicode objects pass back a pointer - to the default encoded string version of the object if such a conversion is - possible. All other read-buffer compatible objects pass back a reference to - the raw internal data representation. Since this format doesn't allow - writable buffer compatible objects like byte arrays, ``s*`` is to be - preferred. +Strings and buffers +------------------- - The type of the length argument (int or :ctype:`Py_ssize_t`) is controlled by +These formats do not expect you to provide raw storage for the returned string +or bytes. Also, you won't have to release any memory yourself, except with +the ``es``, ``es#``, ``et`` and ``et#`` formats. + +However, when a :ctype:`Py_buffer` structure gets filled, the underlying +buffer is locked so that the caller can subsequently use the buffer even +inside a ``Py_BEGIN_ALLOW_THREADS`` block without the risk of mutable data +being resized or destroyed. As a result, **you have to call** +:cfunc:`PyBuffer_Release` after you have finished processing the data (or +in any early abort case). + +Unless otherwise stated, buffers are not NUL-terminated. + +.. note:: + For all ``#`` variants of formats (``s#``, ``y#``, etc.), the type of + the length argument (int or :ctype:`Py_ssize_t`) is controlled by defining the macro :cmacro:`PY_SSIZE_T_CLEAN` before including - :file:`Python.h`. If the macro was defined, length is a :ctype:`Py_ssize_t` - rather than an int. This behavior will change in a future Python version to - only support :ctype:`Py_ssize_t` and drop int support. It is best to always - define :cmacro:`PY_SSIZE_T_CLEAN`. + :file:`Python.h`. If the macro was defined, length is a + :ctype:`Py_ssize_t` rather than an int. This behavior will change + in a future Python version to only support :ctype:`Py_ssize_t` and + drop int support. It is best to always define :cmacro:`PY_SSIZE_T_CLEAN`. -``y`` (bytes object) [const char \*] - This variant on ``s`` converts a Python bytes or bytearray object to a C - pointer to a character string. The bytes object must not contain embedded - NUL bytes; if it does, a :exc:`TypeError` exception is raised. -``y*`` (bytes object) [Py_buffer \*] - This is to ``s*`` as ``y`` is to ``s``. +``s`` (Unicode object) [const char \*] + Convert a Unicode object to a C pointer to a character string. + A pointer to an existing string is stored in the character pointer + variable whose address you pass. The C string is NUL-terminated. + The Python string must not contain embedded NUL bytes; if it does, + a :exc:`TypeError` exception is raised. Unicode objects are converted + to C strings using the default encoding. If this conversion fails, a + :exc:`UnicodeError` is raised. + + .. note:: + This format does not accept bytes-like objects. If you want to accept + filesystem paths and convert them to C character strings, it is + preferrable to use the ``O&`` format with :cfunc:`PyUnicode_FSConverter` + as *converter*. + +``s*`` (Unicode object or any buffer compatible object) [Py_buffer] + This format accepts Unicode objects as well as objects supporting the + buffer protocol (such as :class:`bytes` or :class:`bytearray` objects). + It fills a :ctype:`Py_buffer` structure provided by the caller. + Unicode objects are converted to C strings using the default encoding. + In this case the resulting C string may contain embedded NUL bytes. -``y#`` (bytes object) [const char \*, int] - This variant on ``s#`` stores into two C variables, the first one a pointer - to a character string, the second one its length. This only accepts bytes - objects, no byte arrays. +``s#`` (string, Unicode or any read buffer compatible object) [const char \*, int or :ctype:`Py_ssize_t`] + Like ``s*``, except that it doesn't accept mutable buffer-like objects + such as :class:`bytearray`. The result is stored into two C variables, + the first one a pointer to a C string, the second one its length. + The string may contain embedded null bytes. -``z`` (string or ``None``) [const char \*] +``z`` (Unicode object or ``None``) [const char \*] Like ``s``, but the Python object may also be ``None``, in which case the C pointer is set to *NULL*. -``z*`` (string or ``None`` or any buffer compatible object) [Py_buffer] - This is to ``s*`` as ``z`` is to ``s``. +``z*`` (Unicode object or ``None`` or any buffer compatible object) [Py_buffer] + Like ``s*``, but the Python object may also be ``None``, in which case the + ``buf`` member of the :ctype:`Py_buffer` structure is set to *NULL*. -``z#`` (string or ``None`` or any read buffer compatible object) [const char \*, int] - This is to ``s#`` as ``z`` is to ``s``. +``z#`` (Unicode object or ``None`` or any read buffer compatible object) [const char \*, int] + Like ``s#``, but the Python object may also be ``None``, in which case the C + pointer is set to *NULL*. + +``y`` (bytes object) [const char \*] + This format converts a bytes-like object to a C pointer to a character + string; it does not accept Unicode objects. The bytes buffer must not + contain embedded NUL bytes; if it does, a :exc:`TypeError` + exception is raised. + +``y*`` (any buffer compatible object) [Py_buffer \*] + This variant on ``s*`` doesn't accept Unicode objects, only objects + supporting the buffer protocol. **This is the recommended way to accept + binary data.** + +``y#`` (bytes object) [const char \*, int] + This variant on ``s#`` doesn't accept Unicode objects, only bytes-like + objects. + +``S`` (bytes object) [PyBytesObject \*] + Requires that the Python object is a :class:`bytes` object, without + attempting any conversion. Raises :exc:`TypeError` if the object is not + a bytes object. The C variable may also be declared as :ctype:`PyObject\*`. + +``Y`` (bytearray object) [PyByteArrayObject \*] + Requires that the Python object is a :class:`bytearray` object, without + attempting any conversion. Raises :exc:`TypeError` if the object is not + a bytearray object. The C variable may also be declared as :ctype:`PyObject\*`. ``u`` (Unicode object) [Py_UNICODE \*] Convert a Python Unicode object to a C pointer to a NUL-terminated buffer of - 16-bit Unicode (UTF-16) data. As with ``s``, there is no need to provide - storage for the Unicode data buffer; a pointer to the existing Unicode data is - stored into the :ctype:`Py_UNICODE` pointer variable whose address you pass. + Unicode characters. You must pass the address of a :ctype:`Py_UNICODE` + pointer variable, which will be filled with the pointer to an existing + Unicode buffer. Please note that the width of a :ctype:`Py_UNICODE` + character depends on compilation options (it is either 16 or 32 bits). + + ..note :: + Since ``u`` doesn't give you back the length of the string, and it + may contain embedded NUL characters, it is recommended to use ``u#`` + or ``U`` instead. ``u#`` (Unicode object) [Py_UNICODE \*, int] This variant on ``u`` stores into two C variables, the first one a pointer to a @@ -100,11 +137,40 @@ array. ``Z`` (Unicode or ``None``) [Py_UNICODE \*] - Like ``s``, but the Python object may also be ``None``, in which case the C - pointer is set to *NULL*. + Like ``u``, but the Python object may also be ``None``, in which case the + :ctype:`Py_UNICODE` pointer is set to *NULL*. ``Z#`` (Unicode or ``None``) [Py_UNICODE \*, int] - This is to ``u#`` as ``Z`` is to ``u``. + Like ``u#``, but the Python object may also be ``None``, in which case the + :ctype:`Py_UNICODE` pointer is set to *NULL*. + +``U`` (Unicode object) [PyUnicodeObject \*] + Requires that the Python object is a Unicode object, without attempting + any conversion. Raises :exc:`TypeError` if the object is not a Unicode + object. The C variable may also be declared as :ctype:`PyObject\*`. + +``t#`` (read-only character buffer) [char \*, int] + Like ``s#``, but accepts any object which implements the read-only buffer + interface. The :ctype:`char\*` variable is set to point to the first byte of + the buffer, and the :ctype:`int` is set to the length of the buffer. Only + single-segment buffer objects are accepted; :exc:`TypeError` is raised for all + others. + +``w`` (read-write character buffer) [char \*] + Similar to ``s``, but accepts any object which implements the read-write buffer + interface. The caller must determine the length of the buffer by other means, + or use ``w#`` instead. Only single-segment buffer objects are accepted; + :exc:`TypeError` is raised for all others. + +``w*`` (read-write byte-oriented buffer) [Py_buffer] + This is to ``w`` what ``s*`` is to ``s``. + +``w#`` (read-write character buffer) [char \*, int] + Like ``s#``, but accepts any object which implements the read-write buffer + interface. The :ctype:`char \*` variable is set to point to the first byte + of the buffer, and the :ctype:`int` is set to the length of the buffer. + Only single-segment buffer objects are accepted; :exc:`TypeError` is raised + for all others. ``es`` (string, Unicode object or character buffer compatible object) [const char \*encoding, char \*\*buffer] This variant on ``s`` is used for encoding Unicode and objects convertible to @@ -165,6 +231,9 @@ them. Instead, the implementation assumes that the string object uses the encoding passed in as parameter. +Numbers +------- + ``b`` (integer) [unsigned char] Convert a nonnegative Python integer to an unsigned tiny int, stored in a C :ctype:`unsigned char`. @@ -207,13 +276,13 @@ ``n`` (integer) [Py_ssize_t] Convert a Python integer to a C :ctype:`Py_ssize_t`. -``c`` (string of length 1) [char] - Convert a Python character, represented as a byte string of length 1, to a C - :ctype:`char`. - -``C`` (string of length 1) [int] - Convert a Python character, represented as a unicode string of length 1, to a - C :ctype:`int`. +``c`` (bytes object of length 1) [char] + Convert a Python byte, represented as a :class:`bytes` object of length 1, + to a C :ctype:`char`. + +``C`` (Unicode object of length 1) [int] + Convert a Python character, represented as a :class:`str`: object of + length 1, to a C :ctype:`int`. ``f`` (float) [float] Convert a Python floating point number to a C :ctype:`float`. @@ -224,6 +293,9 @@ ``D`` (complex) [Py_complex] Convert a Python complex number to a C :ctype:`Py_complex` structure. +Other objects +------------- + ``O`` (object) [PyObject \*] Store a Python object (without any conversion) in a C object pointer. The C program thus receives the actual object that was passed. The object's reference @@ -258,39 +330,6 @@ .. versionchanged:: 3.1 Py_CLEANUP_SUPPORTED was added. -``S`` (string) [PyStringObject \*] - Like ``O`` but requires that the Python object is a string object. Raises - :exc:`TypeError` if the object is not a string object. The C variable may also - be declared as :ctype:`PyObject\*`. - -``U`` (Unicode string) [PyUnicodeObject \*] - Like ``O`` but requires that the Python object is a Unicode object. Raises - :exc:`TypeError` if the object is not a Unicode object. The C variable may also - be declared as :ctype:`PyObject\*`. - -``t#`` (read-only character buffer) [char \*, int] - Like ``s#``, but accepts any object which implements the read-only buffer - interface. The :ctype:`char\*` variable is set to point to the first byte of - the buffer, and the :ctype:`int` is set to the length of the buffer. Only - single-segment buffer objects are accepted; :exc:`TypeError` is raised for all - others. - -``w`` (read-write character buffer) [char \*] - Similar to ``s``, but accepts any object which implements the read-write buffer - interface. The caller must determine the length of the buffer by other means, - or use ``w#`` instead. Only single-segment buffer objects are accepted; - :exc:`TypeError` is raised for all others. - -``w*`` (read-write byte-oriented buffer) [Py_buffer] - This is to ``w`` what ``s*`` is to ``s``. - -``w#`` (read-write character buffer) [char \*, int] - Like ``s#``, but accepts any object which implements the read-write buffer - interface. The :ctype:`char \*` variable is set to point to the first byte - of the buffer, and the :ctype:`int` is set to the length of the buffer. - Only single-segment buffer objects are accepted; :exc:`TypeError` is raised - for all others. - ``(items)`` (tuple) [*matching-items*] The object must be a Python sequence whose length is the number of format units in *items*. The C arguments must correspond to the individual format units in @@ -339,6 +378,8 @@ of the format units, the variables at the addresses corresponding to that and the following format units are left untouched. +API Functions +------------- .. cfunction:: int PyArg_ParseTuple(PyObject *args, const char *format, ...) @@ -424,6 +465,10 @@ PyArg_ParseTuple(args, "O|O:ref", &object, &callback) +--------------- +Building values +--------------- + .. cfunction:: PyObject* Py_BuildValue(const char *format, ...) Create a new value based on a format string similar to those accepted by the From python-checkins at python.org Mon May 3 18:07:57 2010 From: python-checkins at python.org (antoine.pitrou) Date: Mon, 3 May 2010 18:07:57 +0200 (CEST) Subject: [Python-checkins] r80715 - in python/branches/release31-maint: Doc/c-api/arg.rst Message-ID: <20100503160757.2B8C9C7A8@mail.python.org> Author: antoine.pitrou Date: Mon May 3 18:07:56 2010 New Revision: 80715 Log: Merged revisions 80714 via svnmerge from svn+ssh://pythondev at svn.python.org/python/branches/py3k ........ r80714 | antoine.pitrou | 2010-05-03 17:57:23 +0200 (lun., 03 mai 2010) | 3 lines Issue #8593: Fix, reorder and improve the documentation for argument parsing ........ Modified: python/branches/release31-maint/ (props changed) python/branches/release31-maint/Doc/c-api/arg.rst Modified: python/branches/release31-maint/Doc/c-api/arg.rst ============================================================================== --- python/branches/release31-maint/Doc/c-api/arg.rst (original) +++ python/branches/release31-maint/Doc/c-api/arg.rst Mon May 3 18:07:56 2010 @@ -14,6 +14,10 @@ strings* which are used to tell the function about the expected arguments. The format strings use the same syntax for each of these functions. +----------------- +Parsing arguments +----------------- + A format string consists of zero or more "format units." A format unit describes one Python object; it is usually a single character or a parenthesized sequence of format units. With a few exceptions, a format unit that is not a @@ -23,75 +27,108 @@ the format unit; and the entry in [square] brackets is the type of the C variable(s) whose address should be passed. -``s`` (string or Unicode object) [const char \*] - Convert a Python string or Unicode object to a C pointer to a character string. - You must not provide storage for the string itself; a pointer to an existing - string is stored into the character pointer variable whose address you pass. - The C string is NUL-terminated. The Python string must not contain embedded NUL - bytes; if it does, a :exc:`TypeError` exception is raised. Unicode objects are - converted to C strings using the default encoding. If this conversion fails, a - :exc:`UnicodeError` is raised. - - Starting with Python 2.5 the type of the length argument can be - controlled by defining the macro :cmacro:`PY_SSIZE_T_CLEAN` before - including :file:`Python.h`. If the macro is defined, length is a - :ctype:`Py_ssize_t` rather than an int. - -``s*`` (string, Unicode, or any buffer compatible object) [Py_buffer] - This is similar to ``s``, but the code fills a :ctype:`Py_buffer` structure - provided by the caller. In this case the Python string may contain embedded - null bytes. Unicode objects pass back a pointer to the default encoded - string version of the object if such a conversion is possible. The - underlying buffer is locked, so that the caller can subsequently use the - buffer even inside a ``Py_BEGIN_ALLOW_THREADS`` block. **The caller is - responsible** for calling ``PyBuffer_Release`` with the structure after it - has processed the data. - -``s#`` (string, Unicode or any read buffer compatible object) [const char \*, int or :ctype:`Py_ssize_t`] - This variant on ``s`` stores into two C variables, the first one a pointer to - a character string, the second one its length. In this case the Python - string may contain embedded null bytes. Unicode objects pass back a pointer - to the default encoded string version of the object if such a conversion is - possible. All other read-buffer compatible objects pass back a reference to - the raw internal data representation. Since this format doesn't allow - writable buffer compatible objects like byte arrays, ``s*`` is to be - preferred. +Strings and buffers +------------------- - The type of the length argument (int or :ctype:`Py_ssize_t`) is controlled by +These formats do not expect you to provide raw storage for the returned string +or bytes. Also, you won't have to release any memory yourself, except with +the ``es``, ``es#``, ``et`` and ``et#`` formats. + +However, when a :ctype:`Py_buffer` structure gets filled, the underlying +buffer is locked so that the caller can subsequently use the buffer even +inside a ``Py_BEGIN_ALLOW_THREADS`` block without the risk of mutable data +being resized or destroyed. As a result, **you have to call** +:cfunc:`PyBuffer_Release` after you have finished processing the data (or +in any early abort case). + +Unless otherwise stated, buffers are not NUL-terminated. + +.. note:: + For all ``#`` variants of formats (``s#``, ``y#``, etc.), the type of + the length argument (int or :ctype:`Py_ssize_t`) is controlled by defining the macro :cmacro:`PY_SSIZE_T_CLEAN` before including - :file:`Python.h`. If the macro was defined, length is a :ctype:`Py_ssize_t` - rather than an int. This behavior will change in a future Python version to - only support :ctype:`Py_ssize_t` and drop int support. It is best to always - define :cmacro:`PY_SSIZE_T_CLEAN`. + :file:`Python.h`. If the macro was defined, length is a + :ctype:`Py_ssize_t` rather than an int. This behavior will change + in a future Python version to only support :ctype:`Py_ssize_t` and + drop int support. It is best to always define :cmacro:`PY_SSIZE_T_CLEAN`. -``y`` (bytes object) [const char \*] - This variant on ``s`` converts a Python bytes or bytearray object to a C - pointer to a character string. The bytes object must not contain embedded - NUL bytes; if it does, a :exc:`TypeError` exception is raised. -``y*`` (bytes object) [Py_buffer \*] - This is to ``s*`` as ``y`` is to ``s``. +``s`` (Unicode object) [const char \*] + Convert a Unicode object to a C pointer to a character string. + A pointer to an existing string is stored in the character pointer + variable whose address you pass. The C string is NUL-terminated. + The Python string must not contain embedded NUL bytes; if it does, + a :exc:`TypeError` exception is raised. Unicode objects are converted + to C strings using the default encoding. If this conversion fails, a + :exc:`UnicodeError` is raised. + + .. note:: + This format does not accept bytes-like objects. If you want to accept + filesystem paths and convert them to C character strings, it is + preferrable to use the ``O&`` format with :cfunc:`PyUnicode_FSConverter` + as *converter*. + +``s*`` (Unicode object or any buffer compatible object) [Py_buffer] + This format accepts Unicode objects as well as objects supporting the + buffer protocol (such as :class:`bytes` or :class:`bytearray` objects). + It fills a :ctype:`Py_buffer` structure provided by the caller. + Unicode objects are converted to C strings using the default encoding. + In this case the resulting C string may contain embedded NUL bytes. -``y#`` (bytes object) [const char \*, int] - This variant on ``s#`` stores into two C variables, the first one a pointer - to a character string, the second one its length. This only accepts bytes - objects, no byte arrays. +``s#`` (string, Unicode or any read buffer compatible object) [const char \*, int or :ctype:`Py_ssize_t`] + Like ``s*``, except that it doesn't accept mutable buffer-like objects + such as :class:`bytearray`. The result is stored into two C variables, + the first one a pointer to a C string, the second one its length. + The string may contain embedded null bytes. -``z`` (string or ``None``) [const char \*] +``z`` (Unicode object or ``None``) [const char \*] Like ``s``, but the Python object may also be ``None``, in which case the C pointer is set to *NULL*. -``z*`` (string or ``None`` or any buffer compatible object) [Py_buffer] - This is to ``s*`` as ``z`` is to ``s``. +``z*`` (Unicode object or ``None`` or any buffer compatible object) [Py_buffer] + Like ``s*``, but the Python object may also be ``None``, in which case the + ``buf`` member of the :ctype:`Py_buffer` structure is set to *NULL*. -``z#`` (string or ``None`` or any read buffer compatible object) [const char \*, int] - This is to ``s#`` as ``z`` is to ``s``. +``z#`` (Unicode object or ``None`` or any read buffer compatible object) [const char \*, int] + Like ``s#``, but the Python object may also be ``None``, in which case the C + pointer is set to *NULL*. + +``y`` (bytes object) [const char \*] + This format converts a bytes-like object to a C pointer to a character + string; it does not accept Unicode objects. The bytes buffer must not + contain embedded NUL bytes; if it does, a :exc:`TypeError` + exception is raised. + +``y*`` (any buffer compatible object) [Py_buffer \*] + This variant on ``s*`` doesn't accept Unicode objects, only objects + supporting the buffer protocol. **This is the recommended way to accept + binary data.** + +``y#`` (bytes object) [const char \*, int] + This variant on ``s#`` doesn't accept Unicode objects, only bytes-like + objects. + +``S`` (bytes object) [PyBytesObject \*] + Requires that the Python object is a :class:`bytes` object, without + attempting any conversion. Raises :exc:`TypeError` if the object is not + a bytes object. The C variable may also be declared as :ctype:`PyObject\*`. + +``Y`` (bytearray object) [PyByteArrayObject \*] + Requires that the Python object is a :class:`bytearray` object, without + attempting any conversion. Raises :exc:`TypeError` if the object is not + a bytearray object. The C variable may also be declared as :ctype:`PyObject\*`. ``u`` (Unicode object) [Py_UNICODE \*] Convert a Python Unicode object to a C pointer to a NUL-terminated buffer of - 16-bit Unicode (UTF-16) data. As with ``s``, there is no need to provide - storage for the Unicode data buffer; a pointer to the existing Unicode data is - stored into the :ctype:`Py_UNICODE` pointer variable whose address you pass. + Unicode characters. You must pass the address of a :ctype:`Py_UNICODE` + pointer variable, which will be filled with the pointer to an existing + Unicode buffer. Please note that the width of a :ctype:`Py_UNICODE` + character depends on compilation options (it is either 16 or 32 bits). + + ..note :: + Since ``u`` doesn't give you back the length of the string, and it + may contain embedded NUL characters, it is recommended to use ``u#`` + or ``U`` instead. ``u#`` (Unicode object) [Py_UNICODE \*, int] This variant on ``u`` stores into two C variables, the first one a pointer to a @@ -100,11 +137,40 @@ array. ``Z`` (Unicode or ``None``) [Py_UNICODE \*] - Like ``s``, but the Python object may also be ``None``, in which case the C - pointer is set to *NULL*. + Like ``u``, but the Python object may also be ``None``, in which case the + :ctype:`Py_UNICODE` pointer is set to *NULL*. ``Z#`` (Unicode or ``None``) [Py_UNICODE \*, int] - This is to ``u#`` as ``Z`` is to ``u``. + Like ``u#``, but the Python object may also be ``None``, in which case the + :ctype:`Py_UNICODE` pointer is set to *NULL*. + +``U`` (Unicode object) [PyUnicodeObject \*] + Requires that the Python object is a Unicode object, without attempting + any conversion. Raises :exc:`TypeError` if the object is not a Unicode + object. The C variable may also be declared as :ctype:`PyObject\*`. + +``t#`` (read-only character buffer) [char \*, int] + Like ``s#``, but accepts any object which implements the read-only buffer + interface. The :ctype:`char\*` variable is set to point to the first byte of + the buffer, and the :ctype:`int` is set to the length of the buffer. Only + single-segment buffer objects are accepted; :exc:`TypeError` is raised for all + others. + +``w`` (read-write character buffer) [char \*] + Similar to ``s``, but accepts any object which implements the read-write buffer + interface. The caller must determine the length of the buffer by other means, + or use ``w#`` instead. Only single-segment buffer objects are accepted; + :exc:`TypeError` is raised for all others. + +``w*`` (read-write byte-oriented buffer) [Py_buffer] + This is to ``w`` what ``s*`` is to ``s``. + +``w#`` (read-write character buffer) [char \*, int] + Like ``s#``, but accepts any object which implements the read-write buffer + interface. The :ctype:`char \*` variable is set to point to the first byte + of the buffer, and the :ctype:`int` is set to the length of the buffer. + Only single-segment buffer objects are accepted; :exc:`TypeError` is raised + for all others. ``es`` (string, Unicode object or character buffer compatible object) [const char \*encoding, char \*\*buffer] This variant on ``s`` is used for encoding Unicode and objects convertible to @@ -165,6 +231,9 @@ them. Instead, the implementation assumes that the string object uses the encoding passed in as parameter. +Numbers +------- + ``b`` (integer) [unsigned char] Convert a nonnegative Python integer to an unsigned tiny int, stored in a C :ctype:`unsigned char`. @@ -207,13 +276,13 @@ ``n`` (integer) [Py_ssize_t] Convert a Python integer to a C :ctype:`Py_ssize_t`. -``c`` (string of length 1) [char] - Convert a Python character, represented as a byte string of length 1, to a C - :ctype:`char`. - -``C`` (string of length 1) [int] - Convert a Python character, represented as a unicode string of length 1, to a - C :ctype:`int`. +``c`` (bytes object of length 1) [char] + Convert a Python byte, represented as a :class:`bytes` object of length 1, + to a C :ctype:`char`. + +``C`` (Unicode object of length 1) [int] + Convert a Python character, represented as a :class:`str`: object of + length 1, to a C :ctype:`int`. ``f`` (float) [float] Convert a Python floating point number to a C :ctype:`float`. @@ -224,6 +293,9 @@ ``D`` (complex) [Py_complex] Convert a Python complex number to a C :ctype:`Py_complex` structure. +Other objects +------------- + ``O`` (object) [PyObject \*] Store a Python object (without any conversion) in a C object pointer. The C program thus receives the actual object that was passed. The object's reference @@ -258,39 +330,6 @@ .. versionchanged:: 3.1 Py_CLEANUP_SUPPORTED was added. -``S`` (string) [PyStringObject \*] - Like ``O`` but requires that the Python object is a string object. Raises - :exc:`TypeError` if the object is not a string object. The C variable may also - be declared as :ctype:`PyObject\*`. - -``U`` (Unicode string) [PyUnicodeObject \*] - Like ``O`` but requires that the Python object is a Unicode object. Raises - :exc:`TypeError` if the object is not a Unicode object. The C variable may also - be declared as :ctype:`PyObject\*`. - -``t#`` (read-only character buffer) [char \*, int] - Like ``s#``, but accepts any object which implements the read-only buffer - interface. The :ctype:`char\*` variable is set to point to the first byte of - the buffer, and the :ctype:`int` is set to the length of the buffer. Only - single-segment buffer objects are accepted; :exc:`TypeError` is raised for all - others. - -``w`` (read-write character buffer) [char \*] - Similar to ``s``, but accepts any object which implements the read-write buffer - interface. The caller must determine the length of the buffer by other means, - or use ``w#`` instead. Only single-segment buffer objects are accepted; - :exc:`TypeError` is raised for all others. - -``w*`` (read-write byte-oriented buffer) [Py_buffer] - This is to ``w`` what ``s*`` is to ``s``. - -``w#`` (read-write character buffer) [char \*, int] - Like ``s#``, but accepts any object which implements the read-write buffer - interface. The :ctype:`char \*` variable is set to point to the first byte - of the buffer, and the :ctype:`int` is set to the length of the buffer. - Only single-segment buffer objects are accepted; :exc:`TypeError` is raised - for all others. - ``(items)`` (tuple) [*matching-items*] The object must be a Python sequence whose length is the number of format units in *items*. The C arguments must correspond to the individual format units in @@ -339,6 +378,8 @@ of the format units, the variables at the addresses corresponding to that and the following format units are left untouched. +API Functions +------------- .. cfunction:: int PyArg_ParseTuple(PyObject *args, const char *format, ...) @@ -415,6 +456,10 @@ PyArg_ParseTuple(args, "O|O:ref", &object, &callback) +--------------- +Building values +--------------- + .. cfunction:: PyObject* Py_BuildValue(const char *format, ...) Create a new value based on a format string similar to those accepted by the From python-checkins at python.org Mon May 3 18:09:22 2010 From: python-checkins at python.org (jesus.cea) Date: Mon, 3 May 2010 18:09:22 +0200 (CEST) Subject: [Python-checkins] r80716 - python/trunk/Doc/library/zlib.rst Message-ID: <20100503160922.15DCDE942@mail.python.org> Author: jesus.cea Date: Mon May 3 18:09:21 2010 New Revision: 80716 Log: wbits negative was documented SEVEN years ago Modified: python/trunk/Doc/library/zlib.rst Modified: python/trunk/Doc/library/zlib.rst ============================================================================== --- python/trunk/Doc/library/zlib.rst (original) +++ python/trunk/Doc/library/zlib.rst Mon May 3 18:09:21 2010 @@ -127,9 +127,7 @@ than the size originally used to compress the stream; using a too-small value will result in an exception. The default value is therefore the highest value, 15. When *wbits* is negative, the standard - :program:`gzip` header is suppressed; this is an undocumented feature of the - zlib library, used for compatibility with :program:`unzip`'s compression file - format. + :program:`gzip` header is suppressed. *bufsize* is the initial size of the buffer used to hold decompressed data. If more space is required, the buffer size will be increased as needed, so you From python-checkins at python.org Mon May 3 18:11:45 2010 From: python-checkins at python.org (jesus.cea) Date: Mon, 3 May 2010 18:11:45 +0200 (CEST) Subject: [Python-checkins] r80717 - in python/branches/release26-maint: Doc/library/zlib.rst Message-ID: <20100503161145.677F8ECA3@mail.python.org> Author: jesus.cea Date: Mon May 3 18:11:45 2010 New Revision: 80717 Log: Merged revisions 80716 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r80716 | jesus.cea | 2010-05-03 18:09:21 +0200 (Mon, 03 May 2010) | 1 line wbits negative was documented SEVEN years ago ........ Modified: python/branches/release26-maint/ (props changed) python/branches/release26-maint/Doc/library/zlib.rst Modified: python/branches/release26-maint/Doc/library/zlib.rst ============================================================================== --- python/branches/release26-maint/Doc/library/zlib.rst (original) +++ python/branches/release26-maint/Doc/library/zlib.rst Mon May 3 18:11:45 2010 @@ -123,9 +123,7 @@ value should be between 8 and 15 for the most recent versions of the zlib library, larger values resulting in better compression at the expense of greater memory usage. The default value is 15. When *wbits* is negative, the standard - :program:`gzip` header is suppressed; this is an undocumented feature of the - zlib library, used for compatibility with :program:`unzip`'s compression file - format. + :program:`gzip` header is suppressed. *bufsize* is the initial size of the buffer used to hold decompressed data. If more space is required, the buffer size will be increased as needed, so you From python-checkins at python.org Mon May 3 18:14:59 2010 From: python-checkins at python.org (jesus.cea) Date: Mon, 3 May 2010 18:14:59 +0200 (CEST) Subject: [Python-checkins] r80718 - in python/branches/py3k: Doc/library/zlib.rst Message-ID: <20100503161459.12DDBEE983@mail.python.org> Author: jesus.cea Date: Mon May 3 18:14:58 2010 New Revision: 80718 Log: Merged revisions 80716 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r80716 | jesus.cea | 2010-05-03 18:09:21 +0200 (Mon, 03 May 2010) | 1 line wbits negative was documented SEVEN years ago ........ Modified: python/branches/py3k/ (props changed) python/branches/py3k/Doc/library/zlib.rst Modified: python/branches/py3k/Doc/library/zlib.rst ============================================================================== --- python/branches/py3k/Doc/library/zlib.rst (original) +++ python/branches/py3k/Doc/library/zlib.rst Mon May 3 18:14:58 2010 @@ -108,9 +108,7 @@ than the size originally used to compress the stream; using a too-small value will result in an exception. The default value is therefore the highest value, 15. When *wbits* is negative, the standard - :program:`gzip` header is suppressed; this is an undocumented feature of the - zlib library, used for compatibility with :program:`unzip`'s compression file - format. + :program:`gzip` header is suppressed. *bufsize* is the initial size of the buffer used to hold decompressed data. If more space is required, the buffer size will be increased as needed, so you From python-checkins at python.org Mon May 3 18:17:30 2010 From: python-checkins at python.org (jesus.cea) Date: Mon, 3 May 2010 18:17:30 +0200 (CEST) Subject: [Python-checkins] r80719 - in python/branches/release31-maint: Doc/library/zlib.rst Message-ID: <20100503161730.6404CDDB3@mail.python.org> Author: jesus.cea Date: Mon May 3 18:17:30 2010 New Revision: 80719 Log: Merged revisions 80718 via svnmerge from svn+ssh://pythondev at svn.python.org/python/branches/py3k ................ r80718 | jesus.cea | 2010-05-03 18:14:58 +0200 (Mon, 03 May 2010) | 9 lines Merged revisions 80716 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r80716 | jesus.cea | 2010-05-03 18:09:21 +0200 (Mon, 03 May 2010) | 1 line wbits negative was documented SEVEN years ago ........ ................ Modified: python/branches/release31-maint/ (props changed) python/branches/release31-maint/Doc/library/zlib.rst Modified: python/branches/release31-maint/Doc/library/zlib.rst ============================================================================== --- python/branches/release31-maint/Doc/library/zlib.rst (original) +++ python/branches/release31-maint/Doc/library/zlib.rst Mon May 3 18:17:30 2010 @@ -104,9 +104,7 @@ value should be between 8 and 15 for the most recent versions of the zlib library, larger values resulting in better compression at the expense of greater memory usage. The default value is 15. When *wbits* is negative, the standard - :program:`gzip` header is suppressed; this is an undocumented feature of the - zlib library, used for compatibility with :program:`unzip`'s compression file - format. + :program:`gzip` header is suppressed. *bufsize* is the initial size of the buffer used to hold decompressed data. If more space is required, the buffer size will be increased as needed, so you From python-checkins at python.org Mon May 3 18:25:33 2010 From: python-checkins at python.org (antoine.pitrou) Date: Mon, 3 May 2010 18:25:33 +0200 (CEST) Subject: [Python-checkins] r80720 - in python/trunk: Lib/_pyio.py Lib/test/test_io.py Misc/NEWS Modules/_io/bufferedio.c Modules/_io/bytesio.c Modules/_io/iobase.c Modules/_io/textio.c Message-ID: <20100503162533.A8AB8E726@mail.python.org> Author: antoine.pitrou Date: Mon May 3 18:25:33 2010 New Revision: 80720 Log: Issue #7865: The close() method of :mod:`io` objects should not swallow exceptions raised by the implicit flush(). Also ensure that calling close() several times is supported. Patch by Pascal Chambon. Modified: python/trunk/Lib/_pyio.py python/trunk/Lib/test/test_io.py python/trunk/Misc/NEWS python/trunk/Modules/_io/bufferedio.c python/trunk/Modules/_io/bytesio.c python/trunk/Modules/_io/iobase.c python/trunk/Modules/_io/textio.c Modified: python/trunk/Lib/_pyio.py ============================================================================== --- python/trunk/Lib/_pyio.py (original) +++ python/trunk/Lib/_pyio.py Mon May 3 18:25:33 2010 @@ -327,6 +327,7 @@ This is not implemented for read-only and non-blocking streams. """ + self._checkClosed() # XXX Should this return the number of bytes written??? __closed = False @@ -337,10 +338,7 @@ This method has no effect if the file is already closed. """ if not self.__closed: - try: - self.flush() - except IOError: - pass # If flush() fails, just give up + self.flush() self.__closed = True def __del__(self): @@ -709,14 +707,13 @@ ### Flush and close ### def flush(self): + if self.closed: + raise ValueError("flush of closed file") self.raw.flush() def close(self): - if not self.closed and self.raw is not None: - try: - self.flush() - except IOError: - pass # If flush() fails, just give up + if self.raw is not None and not self.closed: + self.flush() self.raw.close() def detach(self): @@ -1531,11 +1528,8 @@ self._telling = self._seekable def close(self): - if self.buffer is not None: - try: - self.flush() - except IOError: - pass # If flush() fails, just give up + if self.buffer is not None and not self.closed: + self.flush() self.buffer.close() @property Modified: python/trunk/Lib/test/test_io.py ============================================================================== --- python/trunk/Lib/test/test_io.py (original) +++ python/trunk/Lib/test/test_io.py Mon May 3 18:25:33 2010 @@ -541,6 +541,20 @@ with self.open(zero, "r") as f: self.assertRaises(OverflowError, f.read) + def test_flush_error_on_close(self): + f = self.open(support.TESTFN, "wb", buffering=0) + def bad_flush(): + raise IOError() + f.flush = bad_flush + self.assertRaises(IOError, f.close) # exception not swallowed + + def test_multi_close(self): + f = self.open(support.TESTFN, "wb", buffering=0) + f.close() + f.close() + f.close() + self.assertRaises(ValueError, f.flush) + class CIOTest(IOTest): pass @@ -642,6 +656,22 @@ raw.name = b"dummy" self.assertEqual(repr(b), "<%s name='dummy'>" % clsname) + def test_flush_error_on_close(self): + raw = self.MockRawIO() + def bad_flush(): + raise IOError() + raw.flush = bad_flush + b = self.tp(raw) + self.assertRaises(IOError, b.close) # exception not swallowed + + def test_multi_close(self): + raw = self.MockRawIO() + b = self.tp(raw) + b.close() + b.close() + b.close() + self.assertRaises(ValueError, b.flush) + class BufferedReaderTest(unittest.TestCase, CommonBufferedTests): read_mode = "rb" @@ -2117,6 +2147,20 @@ for n in range(20): self.assertEquals(content.count("Thread%03d\n" % n), 1) + def test_flush_error_on_close(self): + txt = self.TextIOWrapper(self.BytesIO(self.testdata), encoding="ascii") + def bad_flush(): + raise IOError() + txt.flush = bad_flush + self.assertRaises(IOError, txt.close) # exception not swallowed + + def test_multi_close(self): + txt = self.TextIOWrapper(self.BytesIO(self.testdata), encoding="ascii") + txt.close() + txt.close() + txt.close() + self.assertRaises(ValueError, txt.flush) + class CTextIOWrapperTest(TextIOWrapperTest): def test_initialization(self): Modified: python/trunk/Misc/NEWS ============================================================================== --- python/trunk/Misc/NEWS (original) +++ python/trunk/Misc/NEWS Mon May 3 18:25:33 2010 @@ -31,6 +31,10 @@ Library ------- +- Issue #7865: The close() method of :mod:`io` objects should not swallow + exceptions raised by the implicit flush(). Also ensure that calling + close() several times is supported. Patch by Pascal Chambon. + - Issue #8576: logging updated to remove usage of find_unused_port(). - Issue #4687: Fix accuracy of garbage collection runtimes displayed with Modified: python/trunk/Modules/_io/bufferedio.c ============================================================================== --- python/trunk/Modules/_io/bufferedio.c (original) +++ python/trunk/Modules/_io/bufferedio.c Mon May 3 18:25:33 2010 @@ -440,11 +440,7 @@ res = PyObject_CallMethodObjArgs((PyObject *)self, _PyIO_str_flush, NULL); ENTER_BUFFERED(self) if (res == NULL) { - /* If flush() fails, just give up */ - if (PyErr_ExceptionMatches(PyExc_IOError)) - PyErr_Clear(); - else - goto end; + goto end; } Py_XDECREF(res); Modified: python/trunk/Modules/_io/bytesio.c ============================================================================== --- python/trunk/Modules/_io/bytesio.c (original) +++ python/trunk/Modules/_io/bytesio.c Mon May 3 18:25:33 2010 @@ -169,6 +169,7 @@ static PyObject * bytesio_flush(bytesio *self) { + CHECK_CLOSED(self); Py_RETURN_NONE; } Modified: python/trunk/Modules/_io/iobase.c ============================================================================== --- python/trunk/Modules/_io/iobase.c (original) +++ python/trunk/Modules/_io/iobase.c Mon May 3 18:25:33 2010 @@ -183,11 +183,7 @@ res = PyObject_CallMethodObjArgs(self, _PyIO_str_flush, NULL); PyObject_SetAttrString(self, "__IOBase_closed", Py_True); if (res == NULL) { - /* If flush() fails, just give up */ - if (PyErr_ExceptionMatches(PyExc_IOError)) - PyErr_Clear(); - else - return NULL; + return NULL; } Py_XDECREF(res); Py_RETURN_NONE; Modified: python/trunk/Modules/_io/textio.c ============================================================================== --- python/trunk/Modules/_io/textio.c (original) +++ python/trunk/Modules/_io/textio.c Mon May 3 18:25:33 2010 @@ -2405,16 +2405,30 @@ textiowrapper_close(textio *self, PyObject *args) { PyObject *res; + int r; CHECK_INITIALIZED(self); - res = PyObject_CallMethod((PyObject *)self, "flush", NULL); - if (res == NULL) { - /* If flush() fails, just give up */ - PyErr_Clear(); + + res = textiowrapper_closed_get(self, NULL); + if (res == NULL) + return NULL; + r = PyObject_IsTrue(res); + Py_DECREF(res); + if (r < 0) + return NULL; + + if (r > 0) { + Py_RETURN_NONE; /* stream already closed */ } - else - Py_DECREF(res); + else { + res = PyObject_CallMethod((PyObject *)self, "flush", NULL); + if (res == NULL) { + return NULL; + } + else + Py_DECREF(res); - return PyObject_CallMethod(self->buffer, "close", NULL); + return PyObject_CallMethod(self->buffer, "close", NULL); + } } static PyObject * From python-checkins at python.org Mon May 3 18:48:13 2010 From: python-checkins at python.org (antoine.pitrou) Date: Mon, 3 May 2010 18:48:13 +0200 (CEST) Subject: [Python-checkins] r80721 - in python/branches/release26-maint: Lib/io.py Lib/test/test_io.py Misc/NEWS Modules/_bytesio.c Message-ID: <20100503164813.4CEB6FE04@mail.python.org> Author: antoine.pitrou Date: Mon May 3 18:48:13 2010 New Revision: 80721 Log: Merged revisions 80720 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r80720 | antoine.pitrou | 2010-05-03 18:25:33 +0200 (lun., 03 mai 2010) | 5 lines Issue #7865: The close() method of :mod:`io` objects should not swallow exceptions raised by the implicit flush(). Also ensure that calling close() several times is supported. Patch by Pascal Chambon. ........ Modified: python/branches/release26-maint/ (props changed) python/branches/release26-maint/Lib/io.py python/branches/release26-maint/Lib/test/test_io.py python/branches/release26-maint/Misc/NEWS python/branches/release26-maint/Modules/_bytesio.c Modified: python/branches/release26-maint/Lib/io.py ============================================================================== --- python/branches/release26-maint/Lib/io.py (original) +++ python/branches/release26-maint/Lib/io.py Mon May 3 18:48:13 2010 @@ -368,6 +368,9 @@ This is not implemented for read-only and non-blocking streams. """ + if self.__closed: + raise ValueError("flush of closed file") + #self._checkClosed() # XXX Should this return the number of bytes written??? __closed = False @@ -378,10 +381,7 @@ This method has no effect if the file is already closed. """ if not self.__closed: - try: - self.flush() - except IOError: - pass # If flush() fails, just give up + self.flush() self.__closed = True def __del__(self): @@ -751,10 +751,7 @@ def close(self): if not self.closed: - try: - self.flush() - except IOError: - pass # If flush() fails, just give up + self.flush() self.raw.close() ### Inquiries ### @@ -1087,6 +1084,8 @@ return self.raw.truncate(pos) def flush(self): + if self.closed: + raise ValueError("flush of closed file") with self._write_lock: self._flush_unlocked() @@ -1472,11 +1471,9 @@ self._telling = self._seekable def close(self): - try: + if not self.closed: self.flush() - except: - pass # If flush() fails, just give up - self.buffer.close() + self.buffer.close() @property def closed(self): Modified: python/branches/release26-maint/Lib/test/test_io.py ============================================================================== --- python/branches/release26-maint/Lib/test/test_io.py (original) +++ python/branches/release26-maint/Lib/test/test_io.py Mon May 3 18:48:13 2010 @@ -313,6 +313,20 @@ file = io.open(f.fileno(), "r", closefd=False) self.assertEqual(file.buffer.raw.closefd, False) + def test_flush_error_on_close(self): + f = io.open(test_support.TESTFN, "wb", buffering=0) + def bad_flush(): + raise IOError() + f.flush = bad_flush + self.assertRaises(IOError, f.close) # exception not swallowed + + def test_multi_close(self): + f = io.open(test_support.TESTFN, "wb", buffering=0) + f.close() + f.close() + f.close() + self.assertRaises(ValueError, f.flush) + class MemorySeekTestMixin: @@ -565,6 +579,22 @@ finally: test_support.unlink(test_support.TESTFN) + def test_flush_error_on_close(self): + raw = MockRawIO() + def bad_flush(): + raise IOError() + raw.flush = bad_flush + b = io.BufferedWriter(raw) + self.assertRaises(IOError, b.close) # exception not swallowed + + def test_multi_close(self): + raw = MockRawIO() + b = io.BufferedWriter(raw) + b.close() + b.close() + b.close() + self.assertRaises(ValueError, b.flush) + class BufferedRWPairTest(unittest.TestCase): @@ -1295,6 +1325,20 @@ decoder = io.IncrementalNewlineDecoder(decoder, translate=True) self.check_newline_decoder_utf8(decoder) + def test_flush_error_on_close(self): + txt = io.TextIOWrapper(io.BytesIO(self.testdata), encoding="ascii") + def bad_flush(): + raise IOError() + txt.flush = bad_flush + self.assertRaises(IOError, txt.close) # exception not swallowed + + def test_multi_close(self): + txt = io.TextIOWrapper(io.BytesIO(self.testdata), encoding="ascii") + txt.close() + txt.close() + txt.close() + self.assertRaises(ValueError, txt.flush) + # XXX Tests for open() Modified: python/branches/release26-maint/Misc/NEWS ============================================================================== --- python/branches/release26-maint/Misc/NEWS (original) +++ python/branches/release26-maint/Misc/NEWS Mon May 3 18:48:13 2010 @@ -33,6 +33,10 @@ Library ------- +- Issue #7865: The close() method of :mod:`io` objects should not swallow + exceptions raised by the implicit flush(). Also ensure that calling + close() several times is supported. Initial patch by Pascal Chambon. + - Issue #8581: logging: removed errors raised when closing handlers twice. - Issue #4687: Fix accuracy of garbage collection runtimes displayed with Modified: python/branches/release26-maint/Modules/_bytesio.c ============================================================================== --- python/branches/release26-maint/Modules/_bytesio.c (original) +++ python/branches/release26-maint/Modules/_bytesio.c Mon May 3 18:48:13 2010 @@ -163,6 +163,7 @@ static PyObject * bytesio_flush(BytesIOObject *self) { + CHECK_CLOSED(self); Py_RETURN_NONE; } From python-checkins at python.org Mon May 3 18:48:20 2010 From: python-checkins at python.org (antoine.pitrou) Date: Mon, 3 May 2010 18:48:20 +0200 (CEST) Subject: [Python-checkins] r80722 - in python/branches/py3k: Lib/_pyio.py Lib/test/test_io.py Misc/NEWS Modules/_io/bufferedio.c Modules/_io/bytesio.c Modules/_io/iobase.c Modules/_io/textio.c Message-ID: <20100503164820.5ABDDE6EE@mail.python.org> Author: antoine.pitrou Date: Mon May 3 18:48:20 2010 New Revision: 80722 Log: Merged revisions 80720 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r80720 | antoine.pitrou | 2010-05-03 18:25:33 +0200 (lun., 03 mai 2010) | 5 lines Issue #7865: The close() method of :mod:`io` objects should not swallow exceptions raised by the implicit flush(). Also ensure that calling close() several times is supported. Patch by Pascal Chambon. ........ Modified: python/branches/py3k/ (props changed) python/branches/py3k/Lib/_pyio.py python/branches/py3k/Lib/test/test_io.py python/branches/py3k/Misc/NEWS python/branches/py3k/Modules/_io/bufferedio.c python/branches/py3k/Modules/_io/bytesio.c python/branches/py3k/Modules/_io/iobase.c python/branches/py3k/Modules/_io/textio.c Modified: python/branches/py3k/Lib/_pyio.py ============================================================================== --- python/branches/py3k/Lib/_pyio.py (original) +++ python/branches/py3k/Lib/_pyio.py Mon May 3 18:48:20 2010 @@ -322,6 +322,7 @@ This is not implemented for read-only and non-blocking streams. """ + self._checkClosed() # XXX Should this return the number of bytes written??? __closed = False @@ -332,10 +333,7 @@ This method has no effect if the file is already closed. """ if not self.__closed: - try: - self.flush() - except IOError: - pass # If flush() fails, just give up + self.flush() self.__closed = True def __del__(self) -> None: @@ -702,14 +700,13 @@ ### Flush and close ### def flush(self): + if self.closed: + raise ValueError("flush of closed file") self.raw.flush() def close(self): - if not self.closed and self.raw is not None: - try: - self.flush() - except IOError: - pass # If flush() fails, just give up + if self.raw is not None and not self.closed: + self.flush() self.raw.close() def detach(self): @@ -1521,11 +1518,8 @@ self._telling = self._seekable def close(self): - if self.buffer is not None: - try: - self.flush() - except IOError: - pass # If flush() fails, just give up + if self.buffer is not None and not self.closed: + self.flush() self.buffer.close() @property Modified: python/branches/py3k/Lib/test/test_io.py ============================================================================== --- python/branches/py3k/Lib/test/test_io.py (original) +++ python/branches/py3k/Lib/test/test_io.py Mon May 3 18:48:20 2010 @@ -536,6 +536,20 @@ with self.open(zero, "r") as f: self.assertRaises(OverflowError, f.read) + def test_flush_error_on_close(self): + f = self.open(support.TESTFN, "wb", buffering=0) + def bad_flush(): + raise IOError() + f.flush = bad_flush + self.assertRaises(IOError, f.close) # exception not swallowed + + def test_multi_close(self): + f = self.open(support.TESTFN, "wb", buffering=0) + f.close() + f.close() + f.close() + self.assertRaises(ValueError, f.flush) + class CIOTest(IOTest): pass @@ -635,6 +649,22 @@ raw.name = b"dummy" self.assertEqual(repr(b), "<%s name=b'dummy'>" % clsname) + def test_flush_error_on_close(self): + raw = self.MockRawIO() + def bad_flush(): + raise IOError() + raw.flush = bad_flush + b = self.tp(raw) + self.assertRaises(IOError, b.close) # exception not swallowed + + def test_multi_close(self): + raw = self.MockRawIO() + b = self.tp(raw) + b.close() + b.close() + b.close() + self.assertRaises(ValueError, b.flush) + class BufferedReaderTest(unittest.TestCase, CommonBufferedTests): read_mode = "rb" @@ -2107,6 +2137,20 @@ for n in range(20): self.assertEquals(content.count("Thread%03d\n" % n), 1) + def test_flush_error_on_close(self): + txt = self.TextIOWrapper(self.BytesIO(self.testdata), encoding="ascii") + def bad_flush(): + raise IOError() + txt.flush = bad_flush + self.assertRaises(IOError, txt.close) # exception not swallowed + + def test_multi_close(self): + txt = self.TextIOWrapper(self.BytesIO(self.testdata), encoding="ascii") + txt.close() + txt.close() + txt.close() + self.assertRaises(ValueError, txt.flush) + class CTextIOWrapperTest(TextIOWrapperTest): def test_initialization(self): Modified: python/branches/py3k/Misc/NEWS ============================================================================== --- python/branches/py3k/Misc/NEWS (original) +++ python/branches/py3k/Misc/NEWS Mon May 3 18:48:20 2010 @@ -345,6 +345,10 @@ Library ------- +- Issue #7865: The close() method of :mod:`io` objects should not swallow + exceptions raised by the implicit flush(). Also ensure that calling + close() several times is supported. Patch by Pascal Chambon. + - Issue #4687: Fix accuracy of garbage collection runtimes displayed with gc.DEBUG_STATS. Modified: python/branches/py3k/Modules/_io/bufferedio.c ============================================================================== --- python/branches/py3k/Modules/_io/bufferedio.c (original) +++ python/branches/py3k/Modules/_io/bufferedio.c Mon May 3 18:48:20 2010 @@ -440,11 +440,7 @@ res = PyObject_CallMethodObjArgs((PyObject *)self, _PyIO_str_flush, NULL); ENTER_BUFFERED(self) if (res == NULL) { - /* If flush() fails, just give up */ - if (PyErr_ExceptionMatches(PyExc_IOError)) - PyErr_Clear(); - else - goto end; + goto end; } Py_XDECREF(res); Modified: python/branches/py3k/Modules/_io/bytesio.c ============================================================================== --- python/branches/py3k/Modules/_io/bytesio.c (original) +++ python/branches/py3k/Modules/_io/bytesio.c Mon May 3 18:48:20 2010 @@ -169,6 +169,7 @@ static PyObject * bytesio_flush(bytesio *self) { + CHECK_CLOSED(self); Py_RETURN_NONE; } Modified: python/branches/py3k/Modules/_io/iobase.c ============================================================================== --- python/branches/py3k/Modules/_io/iobase.c (original) +++ python/branches/py3k/Modules/_io/iobase.c Mon May 3 18:48:20 2010 @@ -183,11 +183,7 @@ res = PyObject_CallMethodObjArgs(self, _PyIO_str_flush, NULL); PyObject_SetAttrString(self, "__IOBase_closed", Py_True); if (res == NULL) { - /* If flush() fails, just give up */ - if (PyErr_ExceptionMatches(PyExc_IOError)) - PyErr_Clear(); - else - return NULL; + return NULL; } Py_XDECREF(res); Py_RETURN_NONE; Modified: python/branches/py3k/Modules/_io/textio.c ============================================================================== --- python/branches/py3k/Modules/_io/textio.c (original) +++ python/branches/py3k/Modules/_io/textio.c Mon May 3 18:48:20 2010 @@ -2398,16 +2398,30 @@ textiowrapper_close(textio *self, PyObject *args) { PyObject *res; + int r; CHECK_INITIALIZED(self); - res = PyObject_CallMethod((PyObject *)self, "flush", NULL); - if (res == NULL) { - /* If flush() fails, just give up */ - PyErr_Clear(); + + res = textiowrapper_closed_get(self, NULL); + if (res == NULL) + return NULL; + r = PyObject_IsTrue(res); + Py_DECREF(res); + if (r < 0) + return NULL; + + if (r > 0) { + Py_RETURN_NONE; /* stream already closed */ } - else - Py_DECREF(res); + else { + res = PyObject_CallMethod((PyObject *)self, "flush", NULL); + if (res == NULL) { + return NULL; + } + else + Py_DECREF(res); - return PyObject_CallMethod(self->buffer, "close", NULL); + return PyObject_CallMethod(self->buffer, "close", NULL); + } } static PyObject * From python-checkins at python.org Mon May 3 18:58:19 2010 From: python-checkins at python.org (antoine.pitrou) Date: Mon, 3 May 2010 18:58:19 +0200 (CEST) Subject: [Python-checkins] r80723 - in python/branches/release31-maint: Lib/_pyio.py Lib/test/test_io.py Misc/NEWS Modules/_io/bufferedio.c Modules/_io/bytesio.c Modules/_io/iobase.c Modules/_io/textio.c Message-ID: <20100503165819.50B83E49B@mail.python.org> Author: antoine.pitrou Date: Mon May 3 18:58:19 2010 New Revision: 80723 Log: Merged revisions 80722 via svnmerge from svn+ssh://pythondev at svn.python.org/python/branches/py3k ................ r80722 | antoine.pitrou | 2010-05-03 18:48:20 +0200 (lun., 03 mai 2010) | 11 lines Merged revisions 80720 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r80720 | antoine.pitrou | 2010-05-03 18:25:33 +0200 (lun., 03 mai 2010) | 5 lines Issue #7865: The close() method of :mod:`io` objects should not swallow exceptions raised by the implicit flush(). Also ensure that calling close() several times is supported. Patch by Pascal Chambon. ........ ................ Modified: python/branches/release31-maint/ (props changed) python/branches/release31-maint/Lib/_pyio.py python/branches/release31-maint/Lib/test/test_io.py python/branches/release31-maint/Misc/NEWS python/branches/release31-maint/Modules/_io/bufferedio.c python/branches/release31-maint/Modules/_io/bytesio.c python/branches/release31-maint/Modules/_io/iobase.c python/branches/release31-maint/Modules/_io/textio.c Modified: python/branches/release31-maint/Lib/_pyio.py ============================================================================== --- python/branches/release31-maint/Lib/_pyio.py (original) +++ python/branches/release31-maint/Lib/_pyio.py Mon May 3 18:58:19 2010 @@ -325,6 +325,7 @@ This is not implemented for read-only and non-blocking streams. """ + self._checkClosed() # XXX Should this return the number of bytes written??? __closed = False @@ -335,10 +336,7 @@ This method has no effect if the file is already closed. """ if not self.__closed: - try: - self.flush() - except IOError: - pass # If flush() fails, just give up + self.flush() self.__closed = True def __del__(self) -> None: @@ -705,14 +703,13 @@ ### Flush and close ### def flush(self): + if self.closed: + raise ValueError("flush of closed file") self.raw.flush() def close(self): - if not self.closed and self.raw is not None: - try: - self.flush() - except IOError: - pass # If flush() fails, just give up + if self.raw is not None and not self.closed: + self.flush() self.raw.close() def detach(self): @@ -1514,11 +1511,8 @@ self._telling = self._seekable def close(self): - if self.buffer is not None: - try: - self.flush() - except IOError: - pass # If flush() fails, just give up + if self.buffer is not None and not self.closed: + self.flush() self.buffer.close() @property Modified: python/branches/release31-maint/Lib/test/test_io.py ============================================================================== --- python/branches/release31-maint/Lib/test/test_io.py (original) +++ python/branches/release31-maint/Lib/test/test_io.py Mon May 3 18:58:19 2010 @@ -535,6 +535,20 @@ with self.open(zero, "r") as f: self.assertRaises(OverflowError, f.read) + def test_flush_error_on_close(self): + f = self.open(support.TESTFN, "wb", buffering=0) + def bad_flush(): + raise IOError() + f.flush = bad_flush + self.assertRaises(IOError, f.close) # exception not swallowed + + def test_multi_close(self): + f = self.open(support.TESTFN, "wb", buffering=0) + f.close() + f.close() + f.close() + self.assertRaises(ValueError, f.flush) + class CIOTest(IOTest): pass @@ -634,6 +648,22 @@ raw.name = b"dummy" self.assertEqual(repr(b), "<%s name=b'dummy'>" % clsname) + def test_flush_error_on_close(self): + raw = self.MockRawIO() + def bad_flush(): + raise IOError() + raw.flush = bad_flush + b = self.tp(raw) + self.assertRaises(IOError, b.close) # exception not swallowed + + def test_multi_close(self): + raw = self.MockRawIO() + b = self.tp(raw) + b.close() + b.close() + b.close() + self.assertRaises(ValueError, b.flush) + class BufferedReaderTest(unittest.TestCase, CommonBufferedTests): read_mode = "rb" @@ -2114,6 +2144,20 @@ for n in range(20): self.assertEquals(content.count("Thread%03d\n" % n), 1) + def test_flush_error_on_close(self): + txt = self.TextIOWrapper(self.BytesIO(self.testdata), encoding="ascii") + def bad_flush(): + raise IOError() + txt.flush = bad_flush + self.assertRaises(IOError, txt.close) # exception not swallowed + + def test_multi_close(self): + txt = self.TextIOWrapper(self.BytesIO(self.testdata), encoding="ascii") + txt.close() + txt.close() + txt.close() + self.assertRaises(ValueError, txt.flush) + class CTextIOWrapperTest(TextIOWrapperTest): def test_initialization(self): Modified: python/branches/release31-maint/Misc/NEWS ============================================================================== --- python/branches/release31-maint/Misc/NEWS (original) +++ python/branches/release31-maint/Misc/NEWS Mon May 3 18:58:19 2010 @@ -40,6 +40,10 @@ Library ------- +- Issue #7865: The close() method of :mod:`io` objects should not swallow + exceptions raised by the implicit flush(). Also ensure that calling + close() several times is supported. Patch by Pascal Chambon. + - Issue #4687: Fix accuracy of garbage collection runtimes displayed with gc.DEBUG_STATS. Modified: python/branches/release31-maint/Modules/_io/bufferedio.c ============================================================================== --- python/branches/release31-maint/Modules/_io/bufferedio.c (original) +++ python/branches/release31-maint/Modules/_io/bufferedio.c Mon May 3 18:58:19 2010 @@ -438,11 +438,7 @@ res = PyObject_CallMethodObjArgs((PyObject *)self, _PyIO_str_flush, NULL); ENTER_BUFFERED(self) if (res == NULL) { - /* If flush() fails, just give up */ - if (PyErr_ExceptionMatches(PyExc_IOError)) - PyErr_Clear(); - else - goto end; + goto end; } Py_XDECREF(res); Modified: python/branches/release31-maint/Modules/_io/bytesio.c ============================================================================== --- python/branches/release31-maint/Modules/_io/bytesio.c (original) +++ python/branches/release31-maint/Modules/_io/bytesio.c Mon May 3 18:58:19 2010 @@ -169,6 +169,7 @@ static PyObject * bytesio_flush(bytesio *self) { + CHECK_CLOSED(self); Py_RETURN_NONE; } Modified: python/branches/release31-maint/Modules/_io/iobase.c ============================================================================== --- python/branches/release31-maint/Modules/_io/iobase.c (original) +++ python/branches/release31-maint/Modules/_io/iobase.c Mon May 3 18:58:19 2010 @@ -183,11 +183,7 @@ res = PyObject_CallMethodObjArgs(self, _PyIO_str_flush, NULL); PyObject_SetAttrString(self, "__IOBase_closed", Py_True); if (res == NULL) { - /* If flush() fails, just give up */ - if (PyErr_ExceptionMatches(PyExc_IOError)) - PyErr_Clear(); - else - return NULL; + return NULL; } Py_XDECREF(res); Py_RETURN_NONE; Modified: python/branches/release31-maint/Modules/_io/textio.c ============================================================================== --- python/branches/release31-maint/Modules/_io/textio.c (original) +++ python/branches/release31-maint/Modules/_io/textio.c Mon May 3 18:58:19 2010 @@ -2398,16 +2398,30 @@ textiowrapper_close(textio *self, PyObject *args) { PyObject *res; + int r; CHECK_INITIALIZED(self); - res = PyObject_CallMethod((PyObject *)self, "flush", NULL); - if (res == NULL) { - /* If flush() fails, just give up */ - PyErr_Clear(); + + res = textiowrapper_closed_get(self, NULL); + if (res == NULL) + return NULL; + r = PyObject_IsTrue(res); + Py_DECREF(res); + if (r < 0) + return NULL; + + if (r > 0) { + Py_RETURN_NONE; /* stream already closed */ } - else - Py_DECREF(res); + else { + res = PyObject_CallMethod((PyObject *)self, "flush", NULL); + if (res == NULL) { + return NULL; + } + else + Py_DECREF(res); - return PyObject_CallMethod(self->buffer, "close", NULL); + return PyObject_CallMethod(self->buffer, "close", NULL); + } } static PyObject * From python-checkins at python.org Mon May 3 21:29:35 2010 From: python-checkins at python.org (jeffrey.yasskin) Date: Mon, 3 May 2010 21:29:35 +0200 (CEST) Subject: [Python-checkins] r80724 - in python/branches/py3k: Include/Python.h Include/dynamic_annotations.h Include/pyatomic.h Include/pystate.h Makefile.pre.in Objects/dictobject.c PC/VS7.1/pythoncore.vcproj PC/VS8.0/pythoncore.vcproj PC/os2emx/Makefile PCbuild/pythoncore.vcproj Python/ceval.c Python/ceval_gil.h Python/dynamic_annotations.c Python/pystate.c Python/thread_pthread.h configure configure.in Message-ID: <20100503192935.3B92DE934@mail.python.org> Author: jeffrey.yasskin Date: Mon May 3 21:29:34 2010 New Revision: 80724 Log: Make (most of) Python's tests pass under Thread Sanitizer. http://code.google.com/p/data-race-test/wiki/ThreadSanitizer is a dynamic data race detector that runs on top of valgrind. With this patch, the binaries at http://code.google.com/p/data-race-test/wiki/ThreadSanitizer#Binaries pass many but not all of the Python tests. All of regrtest still passes outside of tsan. I've implemented part of the C1x atomic types so that we can explicitly mark variables that are used across threads, and get defined behavior as compilers advance. I've added tsan's client header and implementation to the codebase in dynamic_annotations.{h,c} (docs at http://code.google.com/p/data-race-test/wiki/DynamicAnnotations). Unfortunately, I haven't been able to get helgrind and drd to give sensible error messages, even when I use their client annotations, so I'm not supporting them. Added: python/branches/py3k/Include/dynamic_annotations.h python/branches/py3k/Include/pyatomic.h python/branches/py3k/Python/dynamic_annotations.c Modified: python/branches/py3k/Include/Python.h python/branches/py3k/Include/pystate.h python/branches/py3k/Makefile.pre.in python/branches/py3k/Objects/dictobject.c python/branches/py3k/PC/VS7.1/pythoncore.vcproj python/branches/py3k/PC/VS8.0/pythoncore.vcproj python/branches/py3k/PC/os2emx/Makefile python/branches/py3k/PCbuild/pythoncore.vcproj python/branches/py3k/Python/ceval.c python/branches/py3k/Python/ceval_gil.h python/branches/py3k/Python/pystate.c python/branches/py3k/Python/thread_pthread.h python/branches/py3k/configure python/branches/py3k/configure.in Modified: python/branches/py3k/Include/Python.h ============================================================================== --- python/branches/py3k/Include/Python.h (original) +++ python/branches/py3k/Include/Python.h Mon May 3 21:29:34 2010 @@ -49,6 +49,8 @@ #include "pyport.h" +#include "pyatomic.h" + /* Debug-mode build with pymalloc implies PYMALLOC_DEBUG. * PYMALLOC_DEBUG is in error if pymalloc is not in use. */ Added: python/branches/py3k/Include/dynamic_annotations.h ============================================================================== --- (empty file) +++ python/branches/py3k/Include/dynamic_annotations.h Mon May 3 21:29:34 2010 @@ -0,0 +1,499 @@ +/* Copyright (c) 2008-2009, Google Inc. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are + * met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Neither the name of Google Inc. 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 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. + * + * --- + * Author: Kostya Serebryany + * Copied to CPython by Jeffrey Yasskin, with all macros renamed to + * start with _Py_ to avoid colliding with users embedding Python, and + * with deprecated macros removed. + */ + +/* This file defines dynamic annotations for use with dynamic analysis + tool such as valgrind, PIN, etc. + + Dynamic annotation is a source code annotation that affects + the generated code (that is, the annotation is not a comment). + Each such annotation is attached to a particular + instruction and/or to a particular object (address) in the program. + + The annotations that should be used by users are macros in all upper-case + (e.g., _Py_ANNOTATE_NEW_MEMORY). + + Actual implementation of these macros may differ depending on the + dynamic analysis tool being used. + + See http://code.google.com/p/data-race-test/ for more information. + + This file supports the following dynamic analysis tools: + - None (DYNAMIC_ANNOTATIONS_ENABLED is not defined or zero). + Macros are defined empty. + - ThreadSanitizer, Helgrind, DRD (DYNAMIC_ANNOTATIONS_ENABLED is 1). + Macros are defined as calls to non-inlinable empty functions + that are intercepted by Valgrind. */ + +#ifndef __DYNAMIC_ANNOTATIONS_H__ +#define __DYNAMIC_ANNOTATIONS_H__ + +#ifndef DYNAMIC_ANNOTATIONS_ENABLED +# define DYNAMIC_ANNOTATIONS_ENABLED 0 +#endif + +#if DYNAMIC_ANNOTATIONS_ENABLED != 0 + + /* ------------------------------------------------------------- + Annotations useful when implementing condition variables such as CondVar, + using conditional critical sections (Await/LockWhen) and when constructing + user-defined synchronization mechanisms. + + The annotations _Py_ANNOTATE_HAPPENS_BEFORE() and + _Py_ANNOTATE_HAPPENS_AFTER() can be used to define happens-before arcs in + user-defined synchronization mechanisms: the race detector will infer an + arc from the former to the latter when they share the same argument + pointer. + + Example 1 (reference counting): + + void Unref() { + _Py_ANNOTATE_HAPPENS_BEFORE(&refcount_); + if (AtomicDecrementByOne(&refcount_) == 0) { + _Py_ANNOTATE_HAPPENS_AFTER(&refcount_); + delete this; + } + } + + Example 2 (message queue): + + void MyQueue::Put(Type *e) { + MutexLock lock(&mu_); + _Py_ANNOTATE_HAPPENS_BEFORE(e); + PutElementIntoMyQueue(e); + } + + Type *MyQueue::Get() { + MutexLock lock(&mu_); + Type *e = GetElementFromMyQueue(); + _Py_ANNOTATE_HAPPENS_AFTER(e); + return e; + } + + Note: when possible, please use the existing reference counting and message + queue implementations instead of inventing new ones. */ + + /* Report that wait on the condition variable at address "cv" has succeeded + and the lock at address "lock" is held. */ + #define _Py_ANNOTATE_CONDVAR_LOCK_WAIT(cv, lock) \ + AnnotateCondVarWait(__FILE__, __LINE__, cv, lock) + + /* Report that wait on the condition variable at "cv" has succeeded. Variant + w/o lock. */ + #define _Py_ANNOTATE_CONDVAR_WAIT(cv) \ + AnnotateCondVarWait(__FILE__, __LINE__, cv, NULL) + + /* Report that we are about to signal on the condition variable at address + "cv". */ + #define _Py_ANNOTATE_CONDVAR_SIGNAL(cv) \ + AnnotateCondVarSignal(__FILE__, __LINE__, cv) + + /* Report that we are about to signal_all on the condition variable at "cv". */ + #define _Py_ANNOTATE_CONDVAR_SIGNAL_ALL(cv) \ + AnnotateCondVarSignalAll(__FILE__, __LINE__, cv) + + /* Annotations for user-defined synchronization mechanisms. */ + #define _Py_ANNOTATE_HAPPENS_BEFORE(obj) _Py_ANNOTATE_CONDVAR_SIGNAL(obj) + #define _Py_ANNOTATE_HAPPENS_AFTER(obj) _Py_ANNOTATE_CONDVAR_WAIT(obj) + + /* Report that the bytes in the range [pointer, pointer+size) are about + to be published safely. The race checker will create a happens-before + arc from the call _Py_ANNOTATE_PUBLISH_MEMORY_RANGE(pointer, size) to + subsequent accesses to this memory. + Note: this annotation may not work properly if the race detector uses + sampling, i.e. does not observe all memory accesses. + */ + #define _Py_ANNOTATE_PUBLISH_MEMORY_RANGE(pointer, size) \ + AnnotatePublishMemoryRange(__FILE__, __LINE__, pointer, size) + + /* Instruct the tool to create a happens-before arc between mu->Unlock() and + mu->Lock(). This annotation may slow down the race detector and hide real + races. Normally it is used only when it would be difficult to annotate each + of the mutex's critical sections individually using the annotations above. + This annotation makes sense only for hybrid race detectors. For pure + happens-before detectors this is a no-op. For more details see + http://code.google.com/p/data-race-test/wiki/PureHappensBeforeVsHybrid . */ + #define _Py_ANNOTATE_PURE_HAPPENS_BEFORE_MUTEX(mu) \ + AnnotateMutexIsUsedAsCondVar(__FILE__, __LINE__, mu) + + /* ------------------------------------------------------------- + Annotations useful when defining memory allocators, or when memory that + was protected in one way starts to be protected in another. */ + + /* Report that a new memory at "address" of size "size" has been allocated. + This might be used when the memory has been retrieved from a free list and + is about to be reused, or when a the locking discipline for a variable + changes. */ + #define _Py_ANNOTATE_NEW_MEMORY(address, size) \ + AnnotateNewMemory(__FILE__, __LINE__, address, size) + + /* ------------------------------------------------------------- + Annotations useful when defining FIFO queues that transfer data between + threads. */ + + /* Report that the producer-consumer queue (such as ProducerConsumerQueue) at + address "pcq" has been created. The _Py_ANNOTATE_PCQ_* annotations should + be used only for FIFO queues. For non-FIFO queues use + _Py_ANNOTATE_HAPPENS_BEFORE (for put) and _Py_ANNOTATE_HAPPENS_AFTER (for + get). */ + #define _Py_ANNOTATE_PCQ_CREATE(pcq) \ + AnnotatePCQCreate(__FILE__, __LINE__, pcq) + + /* Report that the queue at address "pcq" is about to be destroyed. */ + #define _Py_ANNOTATE_PCQ_DESTROY(pcq) \ + AnnotatePCQDestroy(__FILE__, __LINE__, pcq) + + /* Report that we are about to put an element into a FIFO queue at address + "pcq". */ + #define _Py_ANNOTATE_PCQ_PUT(pcq) \ + AnnotatePCQPut(__FILE__, __LINE__, pcq) + + /* Report that we've just got an element from a FIFO queue at address "pcq". */ + #define _Py_ANNOTATE_PCQ_GET(pcq) \ + AnnotatePCQGet(__FILE__, __LINE__, pcq) + + /* ------------------------------------------------------------- + Annotations that suppress errors. It is usually better to express the + program's synchronization using the other annotations, but these can + be used when all else fails. */ + + /* Report that we may have a benign race at "pointer", with size + "sizeof(*(pointer))". "pointer" must be a non-void* pointer. Insert at the + point where "pointer" has been allocated, preferably close to the point + where the race happens. See also _Py_ANNOTATE_BENIGN_RACE_STATIC. */ + #define _Py_ANNOTATE_BENIGN_RACE(pointer, description) \ + AnnotateBenignRaceSized(__FILE__, __LINE__, pointer, \ + sizeof(*(pointer)), description) + + /* Same as _Py_ANNOTATE_BENIGN_RACE(address, description), but applies to + the memory range [address, address+size). */ + #define _Py_ANNOTATE_BENIGN_RACE_SIZED(address, size, description) \ + AnnotateBenignRaceSized(__FILE__, __LINE__, address, size, description) + + /* Request the analysis tool to ignore all reads in the current thread + until _Py_ANNOTATE_IGNORE_READS_END is called. + Useful to ignore intentional racey reads, while still checking + other reads and all writes. + See also _Py_ANNOTATE_UNPROTECTED_READ. */ + #define _Py_ANNOTATE_IGNORE_READS_BEGIN() \ + AnnotateIgnoreReadsBegin(__FILE__, __LINE__) + + /* Stop ignoring reads. */ + #define _Py_ANNOTATE_IGNORE_READS_END() \ + AnnotateIgnoreReadsEnd(__FILE__, __LINE__) + + /* Similar to _Py_ANNOTATE_IGNORE_READS_BEGIN, but ignore writes. */ + #define _Py_ANNOTATE_IGNORE_WRITES_BEGIN() \ + AnnotateIgnoreWritesBegin(__FILE__, __LINE__) + + /* Stop ignoring writes. */ + #define _Py_ANNOTATE_IGNORE_WRITES_END() \ + AnnotateIgnoreWritesEnd(__FILE__, __LINE__) + + /* Start ignoring all memory accesses (reads and writes). */ + #define _Py_ANNOTATE_IGNORE_READS_AND_WRITES_BEGIN() \ + do {\ + _Py_ANNOTATE_IGNORE_READS_BEGIN();\ + _Py_ANNOTATE_IGNORE_WRITES_BEGIN();\ + }while(0)\ + + /* Stop ignoring all memory accesses. */ + #define _Py_ANNOTATE_IGNORE_READS_AND_WRITES_END() \ + do {\ + _Py_ANNOTATE_IGNORE_WRITES_END();\ + _Py_ANNOTATE_IGNORE_READS_END();\ + }while(0)\ + + /* Similar to _Py_ANNOTATE_IGNORE_READS_BEGIN, but ignore synchronization events: + RWLOCK* and CONDVAR*. */ + #define _Py_ANNOTATE_IGNORE_SYNC_BEGIN() \ + AnnotateIgnoreSyncBegin(__FILE__, __LINE__) + + /* Stop ignoring sync events. */ + #define _Py_ANNOTATE_IGNORE_SYNC_END() \ + AnnotateIgnoreSyncEnd(__FILE__, __LINE__) + + + /* Enable (enable!=0) or disable (enable==0) race detection for all threads. + This annotation could be useful if you want to skip expensive race analysis + during some period of program execution, e.g. during initialization. */ + #define _Py_ANNOTATE_ENABLE_RACE_DETECTION(enable) \ + AnnotateEnableRaceDetection(__FILE__, __LINE__, enable) + + /* ------------------------------------------------------------- + Annotations useful for debugging. */ + + /* Request to trace every access to "address". */ + #define _Py_ANNOTATE_TRACE_MEMORY(address) \ + AnnotateTraceMemory(__FILE__, __LINE__, address) + + /* Report the current thread name to a race detector. */ + #define _Py_ANNOTATE_THREAD_NAME(name) \ + AnnotateThreadName(__FILE__, __LINE__, name) + + /* ------------------------------------------------------------- + Annotations useful when implementing locks. They are not + normally needed by modules that merely use locks. + The "lock" argument is a pointer to the lock object. */ + + /* Report that a lock has been created at address "lock". */ + #define _Py_ANNOTATE_RWLOCK_CREATE(lock) \ + AnnotateRWLockCreate(__FILE__, __LINE__, lock) + + /* Report that the lock at address "lock" is about to be destroyed. */ + #define _Py_ANNOTATE_RWLOCK_DESTROY(lock) \ + AnnotateRWLockDestroy(__FILE__, __LINE__, lock) + + /* Report that the lock at address "lock" has been acquired. + is_w=1 for writer lock, is_w=0 for reader lock. */ + #define _Py_ANNOTATE_RWLOCK_ACQUIRED(lock, is_w) \ + AnnotateRWLockAcquired(__FILE__, __LINE__, lock, is_w) + + /* Report that the lock at address "lock" is about to be released. */ + #define _Py_ANNOTATE_RWLOCK_RELEASED(lock, is_w) \ + AnnotateRWLockReleased(__FILE__, __LINE__, lock, is_w) + + /* ------------------------------------------------------------- + Annotations useful when implementing barriers. They are not + normally needed by modules that merely use barriers. + The "barrier" argument is a pointer to the barrier object. */ + + /* Report that the "barrier" has been initialized with initial "count". + If 'reinitialization_allowed' is true, initialization is allowed to happen + multiple times w/o calling barrier_destroy() */ + #define _Py_ANNOTATE_BARRIER_INIT(barrier, count, reinitialization_allowed) \ + AnnotateBarrierInit(__FILE__, __LINE__, barrier, count, \ + reinitialization_allowed) + + /* Report that we are about to enter barrier_wait("barrier"). */ + #define _Py_ANNOTATE_BARRIER_WAIT_BEFORE(barrier) \ + AnnotateBarrierWaitBefore(__FILE__, __LINE__, barrier) + + /* Report that we just exited barrier_wait("barrier"). */ + #define _Py_ANNOTATE_BARRIER_WAIT_AFTER(barrier) \ + AnnotateBarrierWaitAfter(__FILE__, __LINE__, barrier) + + /* Report that the "barrier" has been destroyed. */ + #define _Py_ANNOTATE_BARRIER_DESTROY(barrier) \ + AnnotateBarrierDestroy(__FILE__, __LINE__, barrier) + + /* ------------------------------------------------------------- + Annotations useful for testing race detectors. */ + + /* Report that we expect a race on the variable at "address". + Use only in unit tests for a race detector. */ + #define _Py_ANNOTATE_EXPECT_RACE(address, description) \ + AnnotateExpectRace(__FILE__, __LINE__, address, description) + + /* A no-op. Insert where you like to test the interceptors. */ + #define _Py_ANNOTATE_NO_OP(arg) \ + AnnotateNoOp(__FILE__, __LINE__, arg) + + /* Force the race detector to flush its state. The actual effect depends on + * the implementation of the detector. */ + #define _Py_ANNOTATE_FLUSH_STATE() \ + AnnotateFlushState(__FILE__, __LINE__) + + +#else /* DYNAMIC_ANNOTATIONS_ENABLED == 0 */ + + #define _Py_ANNOTATE_RWLOCK_CREATE(lock) /* empty */ + #define _Py_ANNOTATE_RWLOCK_DESTROY(lock) /* empty */ + #define _Py_ANNOTATE_RWLOCK_ACQUIRED(lock, is_w) /* empty */ + #define _Py_ANNOTATE_RWLOCK_RELEASED(lock, is_w) /* empty */ + #define _Py_ANNOTATE_BARRIER_INIT(barrier, count, reinitialization_allowed) /* */ + #define _Py_ANNOTATE_BARRIER_WAIT_BEFORE(barrier) /* empty */ + #define _Py_ANNOTATE_BARRIER_WAIT_AFTER(barrier) /* empty */ + #define _Py_ANNOTATE_BARRIER_DESTROY(barrier) /* empty */ + #define _Py_ANNOTATE_CONDVAR_LOCK_WAIT(cv, lock) /* empty */ + #define _Py_ANNOTATE_CONDVAR_WAIT(cv) /* empty */ + #define _Py_ANNOTATE_CONDVAR_SIGNAL(cv) /* empty */ + #define _Py_ANNOTATE_CONDVAR_SIGNAL_ALL(cv) /* empty */ + #define _Py_ANNOTATE_HAPPENS_BEFORE(obj) /* empty */ + #define _Py_ANNOTATE_HAPPENS_AFTER(obj) /* empty */ + #define _Py_ANNOTATE_PUBLISH_MEMORY_RANGE(address, size) /* empty */ + #define _Py_ANNOTATE_UNPUBLISH_MEMORY_RANGE(address, size) /* empty */ + #define _Py_ANNOTATE_SWAP_MEMORY_RANGE(address, size) /* empty */ + #define _Py_ANNOTATE_PCQ_CREATE(pcq) /* empty */ + #define _Py_ANNOTATE_PCQ_DESTROY(pcq) /* empty */ + #define _Py_ANNOTATE_PCQ_PUT(pcq) /* empty */ + #define _Py_ANNOTATE_PCQ_GET(pcq) /* empty */ + #define _Py_ANNOTATE_NEW_MEMORY(address, size) /* empty */ + #define _Py_ANNOTATE_EXPECT_RACE(address, description) /* empty */ + #define _Py_ANNOTATE_BENIGN_RACE(address, description) /* empty */ + #define _Py_ANNOTATE_BENIGN_RACE_SIZED(address, size, description) /* empty */ + #define _Py_ANNOTATE_PURE_HAPPENS_BEFORE_MUTEX(mu) /* empty */ + #define _Py_ANNOTATE_MUTEX_IS_USED_AS_CONDVAR(mu) /* empty */ + #define _Py_ANNOTATE_TRACE_MEMORY(arg) /* empty */ + #define _Py_ANNOTATE_THREAD_NAME(name) /* empty */ + #define _Py_ANNOTATE_IGNORE_READS_BEGIN() /* empty */ + #define _Py_ANNOTATE_IGNORE_READS_END() /* empty */ + #define _Py_ANNOTATE_IGNORE_WRITES_BEGIN() /* empty */ + #define _Py_ANNOTATE_IGNORE_WRITES_END() /* empty */ + #define _Py_ANNOTATE_IGNORE_READS_AND_WRITES_BEGIN() /* empty */ + #define _Py_ANNOTATE_IGNORE_READS_AND_WRITES_END() /* empty */ + #define _Py_ANNOTATE_IGNORE_SYNC_BEGIN() /* empty */ + #define _Py_ANNOTATE_IGNORE_SYNC_END() /* empty */ + #define _Py_ANNOTATE_ENABLE_RACE_DETECTION(enable) /* empty */ + #define _Py_ANNOTATE_NO_OP(arg) /* empty */ + #define _Py_ANNOTATE_FLUSH_STATE() /* empty */ + +#endif /* DYNAMIC_ANNOTATIONS_ENABLED */ + +/* Use the macros above rather than using these functions directly. */ +#ifdef __cplusplus +extern "C" { +#endif +void AnnotateRWLockCreate(const char *file, int line, + const volatile void *lock); +void AnnotateRWLockDestroy(const char *file, int line, + const volatile void *lock); +void AnnotateRWLockAcquired(const char *file, int line, + const volatile void *lock, long is_w); +void AnnotateRWLockReleased(const char *file, int line, + const volatile void *lock, long is_w); +void AnnotateBarrierInit(const char *file, int line, + const volatile void *barrier, long count, + long reinitialization_allowed); +void AnnotateBarrierWaitBefore(const char *file, int line, + const volatile void *barrier); +void AnnotateBarrierWaitAfter(const char *file, int line, + const volatile void *barrier); +void AnnotateBarrierDestroy(const char *file, int line, + const volatile void *barrier); +void AnnotateCondVarWait(const char *file, int line, + const volatile void *cv, + const volatile void *lock); +void AnnotateCondVarSignal(const char *file, int line, + const volatile void *cv); +void AnnotateCondVarSignalAll(const char *file, int line, + const volatile void *cv); +void AnnotatePublishMemoryRange(const char *file, int line, + const volatile void *address, + long size); +void AnnotateUnpublishMemoryRange(const char *file, int line, + const volatile void *address, + long size); +void AnnotatePCQCreate(const char *file, int line, + const volatile void *pcq); +void AnnotatePCQDestroy(const char *file, int line, + const volatile void *pcq); +void AnnotatePCQPut(const char *file, int line, + const volatile void *pcq); +void AnnotatePCQGet(const char *file, int line, + const volatile void *pcq); +void AnnotateNewMemory(const char *file, int line, + const volatile void *address, + long size); +void AnnotateExpectRace(const char *file, int line, + const volatile void *address, + const char *description); +void AnnotateBenignRace(const char *file, int line, + const volatile void *address, + const char *description); +void AnnotateBenignRaceSized(const char *file, int line, + const volatile void *address, + long size, + const char *description); +void AnnotateMutexIsUsedAsCondVar(const char *file, int line, + const volatile void *mu); +void AnnotateTraceMemory(const char *file, int line, + const volatile void *arg); +void AnnotateThreadName(const char *file, int line, + const char *name); +void AnnotateIgnoreReadsBegin(const char *file, int line); +void AnnotateIgnoreReadsEnd(const char *file, int line); +void AnnotateIgnoreWritesBegin(const char *file, int line); +void AnnotateIgnoreWritesEnd(const char *file, int line); +void AnnotateEnableRaceDetection(const char *file, int line, int enable); +void AnnotateNoOp(const char *file, int line, + const volatile void *arg); +void AnnotateFlushState(const char *file, int line); + +/* Return non-zero value if running under valgrind. + + If "valgrind.h" is included into dynamic_annotations.c, + the regular valgrind mechanism will be used. + See http://valgrind.org/docs/manual/manual-core-adv.html about + RUNNING_ON_VALGRIND and other valgrind "client requests". + The file "valgrind.h" may be obtained by doing + svn co svn://svn.valgrind.org/valgrind/trunk/include + + If for some reason you can't use "valgrind.h" or want to fake valgrind, + there are two ways to make this function return non-zero: + - Use environment variable: export RUNNING_ON_VALGRIND=1 + - Make your tool intercept the function RunningOnValgrind() and + change its return value. + */ +int RunningOnValgrind(void); + +#ifdef __cplusplus +} +#endif + +#if DYNAMIC_ANNOTATIONS_ENABLED != 0 && defined(__cplusplus) + + /* _Py_ANNOTATE_UNPROTECTED_READ is the preferred way to annotate racey reads. + + Instead of doing + _Py_ANNOTATE_IGNORE_READS_BEGIN(); + ... = x; + _Py_ANNOTATE_IGNORE_READS_END(); + one can use + ... = _Py_ANNOTATE_UNPROTECTED_READ(x); */ + template + inline T _Py_ANNOTATE_UNPROTECTED_READ(const volatile T &x) { + _Py_ANNOTATE_IGNORE_READS_BEGIN(); + T res = x; + _Py_ANNOTATE_IGNORE_READS_END(); + return res; + } + /* Apply _Py_ANNOTATE_BENIGN_RACE_SIZED to a static variable. */ + #define _Py_ANNOTATE_BENIGN_RACE_STATIC(static_var, description) \ + namespace { \ + class static_var ## _annotator { \ + public: \ + static_var ## _annotator() { \ + _Py_ANNOTATE_BENIGN_RACE_SIZED(&static_var, \ + sizeof(static_var), \ + # static_var ": " description); \ + } \ + }; \ + static static_var ## _annotator the ## static_var ## _annotator;\ + } +#else /* DYNAMIC_ANNOTATIONS_ENABLED == 0 */ + + #define _Py_ANNOTATE_UNPROTECTED_READ(x) (x) + #define _Py_ANNOTATE_BENIGN_RACE_STATIC(static_var, description) /* empty */ + +#endif /* DYNAMIC_ANNOTATIONS_ENABLED */ + +#endif /* __DYNAMIC_ANNOTATIONS_H__ */ Added: python/branches/py3k/Include/pyatomic.h ============================================================================== --- (empty file) +++ python/branches/py3k/Include/pyatomic.h Mon May 3 21:29:34 2010 @@ -0,0 +1,179 @@ +#ifndef Py_ATOMIC_H +#define Py_ATOMIC_H +/* XXX: When compilers start offering a stdatomic.h with lock-free + atomic_int and atomic_address types, include that here and rewrite + the atomic operations in terms of it. */ + +#include "dynamic_annotations.h" + +#ifdef __cplusplus +extern "C" { +#endif + +/* This is modeled after the atomics interface from C1x, according to + * the draft at + * http://www.open-std.org/JTC1/SC22/wg14/www/docs/n1425.pdf. + * Operations and types are named the same except with a _Py_ prefix + * and have the same semantics. + * + * Beware, the implementations here are deep magic. + */ + +typedef enum _Py_memory_order { + _Py_memory_order_relaxed, + _Py_memory_order_acquire, + _Py_memory_order_release, + _Py_memory_order_acq_rel, + _Py_memory_order_seq_cst +} _Py_memory_order; + +typedef struct _Py_atomic_address { + void *_value; +} _Py_atomic_address; + +typedef struct _Py_atomic_int { + int _value; +} _Py_atomic_int; + +/* Only support GCC (for expression statements) and x86 (for simple + * atomic semantics) for now */ +#if defined(__GNUC__) && (defined(__i386__) || defined(__amd64)) + +static __inline__ void +_Py_atomic_signal_fence(_Py_memory_order order) +{ + if (order != _Py_memory_order_relaxed) + __asm__ volatile("":::"memory"); +} + +static __inline__ void +_Py_atomic_thread_fence(_Py_memory_order order) +{ + if (order != _Py_memory_order_relaxed) + __asm__ volatile("mfence":::"memory"); +} + +/* Tell the race checker about this operation's effects. */ +static __inline__ void +_Py_ANNOTATE_MEMORY_ORDER(const volatile void *address, _Py_memory_order order) +{ + switch(order) { + case _Py_memory_order_release: + case _Py_memory_order_acq_rel: + case _Py_memory_order_seq_cst: + _Py_ANNOTATE_HAPPENS_BEFORE(address); + break; + default: + break; + } + switch(order) { + case _Py_memory_order_acquire: + case _Py_memory_order_acq_rel: + case _Py_memory_order_seq_cst: + _Py_ANNOTATE_HAPPENS_AFTER(address); + break; + default: + break; + } +} + +#define _Py_atomic_store_explicit(ATOMIC_VAL, NEW_VAL, ORDER) \ + __extension__ ({ \ + __typeof__(ATOMIC_VAL) atomic_val = ATOMIC_VAL; \ + __typeof__(atomic_val->_value) new_val = NEW_VAL;\ + volatile __typeof__(new_val) *volatile_data = &atomic_val->_value; \ + _Py_memory_order order = ORDER; \ + _Py_ANNOTATE_MEMORY_ORDER(atomic_val, order); \ + \ + /* Perform the operation. */ \ + _Py_ANNOTATE_IGNORE_WRITES_BEGIN(); \ + switch(order) { \ + case _Py_memory_order_release: \ + _Py_atomic_signal_fence(_Py_memory_order_release); \ + /* fallthrough */ \ + case _Py_memory_order_relaxed: \ + *volatile_data = new_val; \ + break; \ + \ + case _Py_memory_order_acquire: \ + case _Py_memory_order_acq_rel: \ + case _Py_memory_order_seq_cst: \ + __asm__ volatile("xchg %0, %1" \ + : "+r"(new_val) \ + : "m"(atomic_val->_value) \ + : "memory"); \ + break; \ + } \ + _Py_ANNOTATE_IGNORE_WRITES_END(); \ + }) + +#define _Py_atomic_load_explicit(ATOMIC_VAL, ORDER) \ + __extension__ ({ \ + __typeof__(ATOMIC_VAL) atomic_val = ATOMIC_VAL; \ + __typeof__(atomic_val->_value) result; \ + volatile __typeof__(result) *volatile_data = &atomic_val->_value; \ + _Py_memory_order order = ORDER; \ + _Py_ANNOTATE_MEMORY_ORDER(atomic_val, order); \ + \ + /* Perform the operation. */ \ + _Py_ANNOTATE_IGNORE_READS_BEGIN(); \ + switch(order) { \ + case _Py_memory_order_release: \ + case _Py_memory_order_acq_rel: \ + case _Py_memory_order_seq_cst: \ + /* Loads on x86 are not releases by default, so need a */ \ + /* thread fence. */ \ + _Py_atomic_thread_fence(_Py_memory_order_release); \ + break; \ + default: \ + /* No fence */ \ + break; \ + } \ + result = *volatile_data; \ + switch(order) { \ + case _Py_memory_order_acquire: \ + case _Py_memory_order_acq_rel: \ + case _Py_memory_order_seq_cst: \ + /* Loads on x86 are automatically acquire operations so */ \ + /* can get by with just a compiler fence. */ \ + _Py_atomic_signal_fence(_Py_memory_order_acquire); \ + break; \ + default: \ + /* No fence */ \ + break; \ + } \ + _Py_ANNOTATE_IGNORE_READS_END(); \ + result; \ + }) + +#else /* !gcc x86 */ +/* Fall back to other compilers and processors by assuming that simple + volatile accesses are atomic. This is false, so people should port + this. */ +#define _Py_atomic_signal_fence(/*memory_order*/ ORDER) ((void)0) +#define _Py_atomic_thread_fence(/*memory_order*/ ORDER) ((void)0) +#define _Py_atomic_store_explicit(ATOMIC_VAL, NEW_VAL, ORDER) \ + ((ATOMIC_VAL)->_value = NEW_VAL) +#define _Py_atomic_load_explicit(ATOMIC_VAL, ORDER) \ + ((ATOMIC_VAL)->_value) + +#endif /* !gcc x86 */ + +/* Standardized shortcuts. */ +#define _Py_atomic_store(ATOMIC_VAL, NEW_VAL) \ + _Py_atomic_store_explicit(ATOMIC_VAL, NEW_VAL, _Py_memory_order_seq_cst) +#define _Py_atomic_load(ATOMIC_VAL) \ + _Py_atomic_load_explicit(ATOMIC_VAL, _Py_memory_order_seq_cst) + +/* Python-local extensions */ + +#define _Py_atomic_store_relaxed(ATOMIC_VAL, NEW_VAL) \ + _Py_atomic_store_explicit(ATOMIC_VAL, NEW_VAL, _Py_memory_order_relaxed) +#define _Py_atomic_load_relaxed(ATOMIC_VAL) \ + _Py_atomic_load_explicit(ATOMIC_VAL, _Py_memory_order_relaxed) + +#ifdef __cplusplus +} +#endif + +#endif /* Py_ATOMIC_H */ Modified: python/branches/py3k/Include/pystate.h ============================================================================== --- python/branches/py3k/Include/pystate.h (original) +++ python/branches/py3k/Include/pystate.h Mon May 3 21:29:34 2010 @@ -131,12 +131,15 @@ /* Variable and macro for in-line access to current thread state */ -PyAPI_DATA(PyThreadState *) _PyThreadState_Current; +/* Assuming the current thread holds the GIL, this is the + PyThreadState for the current thread. */ +PyAPI_DATA(_Py_atomic_address) _PyThreadState_Current; #ifdef Py_DEBUG #define PyThreadState_GET() PyThreadState_Get() #else -#define PyThreadState_GET() (_PyThreadState_Current) +#define PyThreadState_GET() \ + ((PyThreadState*)_Py_atomic_load_relaxed(&_PyThreadState_Current)) #endif typedef Modified: python/branches/py3k/Makefile.pre.in ============================================================================== --- python/branches/py3k/Makefile.pre.in (original) +++ python/branches/py3k/Makefile.pre.in Mon May 3 21:29:34 2010 @@ -238,6 +238,7 @@ PGOBJS= \ Objects/obmalloc.o \ + Python/dynamic_annotations.o \ Python/mysnprintf.o \ Python/pyctype.o \ Parser/tokenizer_pgen.o \ @@ -283,6 +284,7 @@ Python/ceval.o \ Python/compile.o \ Python/codecs.o \ + Python/dynamic_annotations.o \ Python/errors.o \ Python/frozen.o \ Python/frozenmain.o \ @@ -644,6 +646,7 @@ Include/descrobject.h \ Include/dictobject.h \ Include/dtoa.h \ + Include/dynamic_annotations.h \ Include/enumobject.h \ Include/errcode.h \ Include/eval.h \ @@ -674,6 +677,7 @@ Include/pgen.h \ Include/pgenheaders.h \ Include/pyarena.h \ + Include/pyatomic.h \ Include/pycapsule.h \ Include/pyctype.h \ Include/pydebug.h \ Modified: python/branches/py3k/Objects/dictobject.c ============================================================================== --- python/branches/py3k/Objects/dictobject.c (original) +++ python/branches/py3k/Objects/dictobject.c Mon May 3 21:29:34 2010 @@ -734,7 +734,8 @@ Let's just hope that no exception occurs then... This must be _PyThreadState_Current and not PyThreadState_GET() because in debug mode, the latter complains if tstate is NULL. */ - tstate = _PyThreadState_Current; + tstate = (PyThreadState*)_Py_atomic_load_relaxed( + &_PyThreadState_Current); if (tstate != NULL && tstate->curexc_type != NULL) { /* preserve the existing exception */ PyObject *err_type, *err_value, *err_tb; Modified: python/branches/py3k/PC/VS7.1/pythoncore.vcproj ============================================================================== --- python/branches/py3k/PC/VS7.1/pythoncore.vcproj (original) +++ python/branches/py3k/PC/VS7.1/pythoncore.vcproj Mon May 3 21:29:34 2010 @@ -508,6 +508,9 @@ RelativePath="..\..\PC\config.c"> + + + + @@ -1655,6 +1659,10 @@ > + + Modified: python/branches/py3k/PC/os2emx/Makefile ============================================================================== --- python/branches/py3k/PC/os2emx/Makefile (original) +++ python/branches/py3k/PC/os2emx/Makefile Mon May 3 21:29:34 2010 @@ -332,6 +332,7 @@ Python/ceval.c \ Python/compile.c \ Python/codecs.c \ + Python/dynamic_annotations.c \ Python/errors.c \ Python/frozen.c \ Python/frozenmain.c \ Modified: python/branches/py3k/PCbuild/pythoncore.vcproj ============================================================================== --- python/branches/py3k/PCbuild/pythoncore.vcproj (original) +++ python/branches/py3k/PCbuild/pythoncore.vcproj Mon May 3 21:29:34 2010 @@ -703,6 +703,10 @@ > + + @@ -1660,6 +1664,10 @@ > + + Modified: python/branches/py3k/Python/ceval.c ============================================================================== --- python/branches/py3k/Python/ceval.c (original) +++ python/branches/py3k/Python/ceval.c Mon May 3 21:29:34 2010 @@ -216,23 +216,46 @@ #endif +/* This can set eval_breaker to 0 even though gil_drop_request became + 1. We believe this is all right because the eval loop will release + the GIL eventually anyway. */ #define COMPUTE_EVAL_BREAKER() \ - (eval_breaker = gil_drop_request | pendingcalls_to_do | pending_async_exc) + _Py_atomic_store_relaxed( \ + &eval_breaker, \ + _Py_atomic_load_relaxed(&gil_drop_request) | \ + _Py_atomic_load_relaxed(&pendingcalls_to_do) | \ + pending_async_exc) #define SET_GIL_DROP_REQUEST() \ - do { gil_drop_request = 1; eval_breaker = 1; } while (0) + do { \ + _Py_atomic_store_relaxed(&gil_drop_request, 1); \ + _Py_atomic_store_relaxed(&eval_breaker, 1); \ + } while (0) #define RESET_GIL_DROP_REQUEST() \ - do { gil_drop_request = 0; COMPUTE_EVAL_BREAKER(); } while (0) + do { \ + _Py_atomic_store_relaxed(&gil_drop_request, 0); \ + COMPUTE_EVAL_BREAKER(); \ + } while (0) +/* Pending calls are only modified under pending_lock */ #define SIGNAL_PENDING_CALLS() \ - do { pendingcalls_to_do = 1; eval_breaker = 1; } while (0) + do { \ + _Py_atomic_store_relaxed(&pendingcalls_to_do, 1); \ + _Py_atomic_store_relaxed(&eval_breaker, 1); \ + } while (0) #define UNSIGNAL_PENDING_CALLS() \ - do { pendingcalls_to_do = 0; COMPUTE_EVAL_BREAKER(); } while (0) + do { \ + _Py_atomic_store_relaxed(&pendingcalls_to_do, 0); \ + COMPUTE_EVAL_BREAKER(); \ + } while (0) #define SIGNAL_ASYNC_EXC() \ - do { pending_async_exc = 1; eval_breaker = 1; } while (0) + do { \ + pending_async_exc = 1; \ + _Py_atomic_store_relaxed(&eval_breaker, 1); \ + } while (0) #define UNSIGNAL_ASYNC_EXC() \ do { pending_async_exc = 0; COMPUTE_EVAL_BREAKER(); } while (0) @@ -249,13 +272,14 @@ static long main_thread = 0; /* This single variable consolidates all requests to break out of the fast path in the eval loop. */ -static volatile int eval_breaker = 0; -/* Request for droppping the GIL */ -static volatile int gil_drop_request = 0; -/* Request for running pending calls */ -static volatile int pendingcalls_to_do = 0; -/* Request for looking at the `async_exc` field of the current thread state */ -static volatile int pending_async_exc = 0; +static _Py_atomic_int eval_breaker = {0}; +/* Request for dropping the GIL */ +static _Py_atomic_int gil_drop_request = {0}; +/* Request for running pending calls. */ +static _Py_atomic_int pendingcalls_to_do = {0}; +/* Request for looking at the `async_exc` field of the current thread state. + Guarded by the GIL. */ +static int pending_async_exc = 0; #include "ceval_gil.h" @@ -293,7 +317,8 @@ We therefore avoid PyThreadState_GET() which dumps a fatal error in debug mode. */ - drop_gil(_PyThreadState_Current); + drop_gil((PyThreadState*)_Py_atomic_load_relaxed( + &_PyThreadState_Current)); } void @@ -360,8 +385,8 @@ } #else -static int eval_breaker = 0; -static int gil_drop_request = 0; +static _Py_atomic_int eval_breaker = {0}; +static _Py_atomic_int gil_drop_request = {0}; static int pending_async_exc = 0; #endif /* WITH_THREAD */ @@ -1217,7 +1242,7 @@ async I/O handler); see Py_AddPendingCall() and Py_MakePendingCalls() above. */ - if (eval_breaker) { + if (_Py_atomic_load_relaxed(&eval_breaker)) { if (*next_instr == SETUP_FINALLY) { /* Make the last opcode before a try: finally: block uninterruptable. */ @@ -1227,13 +1252,13 @@ #ifdef WITH_TSC ticked = 1; #endif - if (pendingcalls_to_do) { + if (_Py_atomic_load_relaxed(&pendingcalls_to_do)) { if (Py_MakePendingCalls() < 0) { why = WHY_EXCEPTION; goto on_error; } } - if (gil_drop_request) { + if (_Py_atomic_load_relaxed(&gil_drop_request)) { #ifdef WITH_THREAD /* Give another thread a chance */ if (PyThreadState_Swap(NULL) != tstate) Modified: python/branches/py3k/Python/ceval_gil.h ============================================================================== --- python/branches/py3k/Python/ceval_gil.h (original) +++ python/branches/py3k/Python/ceval_gil.h Mon May 3 21:29:34 2010 @@ -207,14 +207,14 @@ #endif /* _POSIX_THREADS, NT_THREADS */ -/* Whether the GIL is already taken (-1 if uninitialized). This is volatile +/* Whether the GIL is already taken (-1 if uninitialized). This is atomic because it can be read without any lock taken in ceval.c. */ -static volatile int gil_locked = -1; +static _Py_atomic_int gil_locked = {-1}; /* Number of GIL switches since the beginning. */ static unsigned long gil_switch_number = 0; -/* Last thread holding / having held the GIL. This helps us know whether - anyone else was scheduled after we dropped the GIL. */ -static PyThreadState *gil_last_holder = NULL; +/* Last PyThreadState holding / having held the GIL. This helps us know + whether anyone else was scheduled after we dropped the GIL. */ +static _Py_atomic_address gil_last_holder = {NULL}; /* This condition variable allows one or several threads to wait until the GIL is released. In addition, the mutex also protects the above @@ -232,7 +232,7 @@ static int gil_created(void) { - return gil_locked >= 0; + return _Py_atomic_load_explicit(&gil_locked, _Py_memory_order_acquire) >= 0; } static void create_gil(void) @@ -245,33 +245,37 @@ #ifdef FORCE_SWITCHING COND_INIT(switch_cond); #endif - gil_locked = 0; - gil_last_holder = NULL; + _Py_atomic_store_relaxed(&gil_last_holder, NULL); + _Py_ANNOTATE_RWLOCK_CREATE(&gil_locked); + _Py_atomic_store_explicit(&gil_locked, 0, _Py_memory_order_release); } static void recreate_gil(void) { + _Py_ANNOTATE_RWLOCK_DESTROY(&gil_locked); create_gil(); } static void drop_gil(PyThreadState *tstate) { /* NOTE: tstate is allowed to be NULL. */ - if (!gil_locked) + if (!_Py_atomic_load_relaxed(&gil_locked)) Py_FatalError("drop_gil: GIL is not locked"); - if (tstate != NULL && tstate != gil_last_holder) + if (tstate != NULL && + tstate != _Py_atomic_load_relaxed(&gil_last_holder)) Py_FatalError("drop_gil: wrong thread state"); MUTEX_LOCK(gil_mutex); - gil_locked = 0; + _Py_ANNOTATE_RWLOCK_RELEASED(&gil_locked, /*is_write=*/1); + _Py_atomic_store_relaxed(&gil_locked, 0); COND_SIGNAL(gil_cond); MUTEX_UNLOCK(gil_mutex); #ifdef FORCE_SWITCHING - if (gil_drop_request && tstate != NULL) { + if (_Py_atomic_load_relaxed(&gil_drop_request) && tstate != NULL) { MUTEX_LOCK(switch_mutex); /* Not switched yet => wait */ - if (gil_last_holder == tstate) { + if (_Py_atomic_load_relaxed(&gil_last_holder) == tstate) { RESET_GIL_DROP_REQUEST(); /* NOTE: if COND_WAIT does not atomically start waiting when releasing the mutex, another thread can run through, take @@ -294,11 +298,11 @@ err = errno; MUTEX_LOCK(gil_mutex); - if (!gil_locked) + if (!_Py_atomic_load_relaxed(&gil_locked)) goto _ready; COND_RESET(gil_cond); - while (gil_locked) { + while (_Py_atomic_load_relaxed(&gil_locked)) { int timed_out = 0; unsigned long saved_switchnum; @@ -306,7 +310,9 @@ COND_TIMED_WAIT(gil_cond, gil_mutex, INTERVAL, timed_out); /* If we timed out and no switch occurred in the meantime, it is time to ask the GIL-holding thread to drop it. */ - if (timed_out && gil_locked && gil_switch_number == saved_switchnum) { + if (timed_out && + _Py_atomic_load_relaxed(&gil_locked) && + gil_switch_number == saved_switchnum) { SET_GIL_DROP_REQUEST(); } } @@ -316,17 +322,19 @@ MUTEX_LOCK(switch_mutex); #endif /* We now hold the GIL */ - gil_locked = 1; + _Py_atomic_store_relaxed(&gil_locked, 1); + _Py_ANNOTATE_RWLOCK_ACQUIRED(&gil_locked, /*is_write=*/1); - if (tstate != gil_last_holder) { - gil_last_holder = tstate; + if (tstate != _Py_atomic_load_relaxed(&gil_last_holder)) { + _Py_atomic_store_relaxed(&gil_last_holder, tstate); ++gil_switch_number; } + #ifdef FORCE_SWITCHING COND_SIGNAL(switch_cond); MUTEX_UNLOCK(switch_mutex); #endif - if (gil_drop_request) { + if (_Py_atomic_load_relaxed(&gil_drop_request)) { RESET_GIL_DROP_REQUEST(); } if (tstate->async_exc != NULL) { Added: python/branches/py3k/Python/dynamic_annotations.c ============================================================================== --- (empty file) +++ python/branches/py3k/Python/dynamic_annotations.c Mon May 3 21:29:34 2010 @@ -0,0 +1,154 @@ +/* Copyright (c) 2008-2009, Google Inc. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are + * met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Neither the name of Google Inc. 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 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. + * + * --- + * Author: Kostya Serebryany + */ + +#ifdef _MSC_VER +# include +#endif + +#ifdef __cplusplus +# error "This file should be built as pure C to avoid name mangling" +#endif + +#include +#include + +#include "dynamic_annotations.h" + +/* Each function is empty and called (via a macro) only in debug mode. + The arguments are captured by dynamic tools at runtime. */ + +#if DYNAMIC_ANNOTATIONS_ENABLED == 1 + +void AnnotateRWLockCreate(const char *file, int line, + const volatile void *lock){} +void AnnotateRWLockDestroy(const char *file, int line, + const volatile void *lock){} +void AnnotateRWLockAcquired(const char *file, int line, + const volatile void *lock, long is_w){} +void AnnotateRWLockReleased(const char *file, int line, + const volatile void *lock, long is_w){} +void AnnotateBarrierInit(const char *file, int line, + const volatile void *barrier, long count, + long reinitialization_allowed) {} +void AnnotateBarrierWaitBefore(const char *file, int line, + const volatile void *barrier) {} +void AnnotateBarrierWaitAfter(const char *file, int line, + const volatile void *barrier) {} +void AnnotateBarrierDestroy(const char *file, int line, + const volatile void *barrier) {} + +void AnnotateCondVarWait(const char *file, int line, + const volatile void *cv, + const volatile void *lock){} +void AnnotateCondVarSignal(const char *file, int line, + const volatile void *cv){} +void AnnotateCondVarSignalAll(const char *file, int line, + const volatile void *cv){} +void AnnotatePublishMemoryRange(const char *file, int line, + const volatile void *address, + long size){} +void AnnotateUnpublishMemoryRange(const char *file, int line, + const volatile void *address, + long size){} +void AnnotatePCQCreate(const char *file, int line, + const volatile void *pcq){} +void AnnotatePCQDestroy(const char *file, int line, + const volatile void *pcq){} +void AnnotatePCQPut(const char *file, int line, + const volatile void *pcq){} +void AnnotatePCQGet(const char *file, int line, + const volatile void *pcq){} +void AnnotateNewMemory(const char *file, int line, + const volatile void *mem, + long size){} +void AnnotateExpectRace(const char *file, int line, + const volatile void *mem, + const char *description){} +void AnnotateBenignRace(const char *file, int line, + const volatile void *mem, + const char *description){} +void AnnotateBenignRaceSized(const char *file, int line, + const volatile void *mem, + long size, + const char *description) {} +void AnnotateMutexIsUsedAsCondVar(const char *file, int line, + const volatile void *mu){} +void AnnotateTraceMemory(const char *file, int line, + const volatile void *arg){} +void AnnotateThreadName(const char *file, int line, + const char *name){} +void AnnotateIgnoreReadsBegin(const char *file, int line){} +void AnnotateIgnoreReadsEnd(const char *file, int line){} +void AnnotateIgnoreWritesBegin(const char *file, int line){} +void AnnotateIgnoreWritesEnd(const char *file, int line){} +void AnnotateIgnoreSyncBegin(const char *file, int line){} +void AnnotateIgnoreSyncEnd(const char *file, int line){} +void AnnotateEnableRaceDetection(const char *file, int line, int enable){} +void AnnotateNoOp(const char *file, int line, + const volatile void *arg){} +void AnnotateFlushState(const char *file, int line){} + +static int GetRunningOnValgrind(void) { +#ifdef RUNNING_ON_VALGRIND + if (RUNNING_ON_VALGRIND) return 1; +#endif + +#ifndef _MSC_VER + char *running_on_valgrind_str = getenv("RUNNING_ON_VALGRIND"); + if (running_on_valgrind_str) { + return strcmp(running_on_valgrind_str, "0") != 0; + } +#else + /* Visual Studio issues warnings if we use getenv, + * so we use GetEnvironmentVariableA instead. + */ + char value[100] = "1"; + int res = GetEnvironmentVariableA("RUNNING_ON_VALGRIND", + value, sizeof(value)); + /* value will remain "1" if res == 0 or res >= sizeof(value). The latter + * can happen only if the given value is long, in this case it can't be "0". + */ + if (res > 0 && !strcmp(value, "0")) + return 1; +#endif + return 0; +} + +/* See the comments in dynamic_annotations.h */ +int RunningOnValgrind(void) { + static volatile int running_on_valgrind = -1; + /* C doesn't have thread-safe initialization of statics, and we + don't want to depend on pthread_once here, so hack it. */ + int local_running_on_valgrind = running_on_valgrind; + if (local_running_on_valgrind == -1) + running_on_valgrind = local_running_on_valgrind = GetRunningOnValgrind(); + return local_running_on_valgrind; +} + +#endif /* DYNAMIC_ANNOTATIONS_ENABLED == 1 */ Modified: python/branches/py3k/Python/pystate.c ============================================================================== --- python/branches/py3k/Python/pystate.c (original) +++ python/branches/py3k/Python/pystate.c Mon May 3 21:29:34 2010 @@ -47,7 +47,9 @@ static PyInterpreterState *interp_head = NULL; -PyThreadState *_PyThreadState_Current = NULL; +/* Assuming the current thread holds the GIL, this is the + PyThreadState for the current thread. */ +_Py_atomic_address _PyThreadState_Current = {NULL}; PyThreadFrameGetter _PyThreadState_GetFrame = NULL; #ifdef WITH_THREAD @@ -334,7 +336,7 @@ void PyThreadState_Delete(PyThreadState *tstate) { - if (tstate == _PyThreadState_Current) + if (tstate == _Py_atomic_load_relaxed(&_PyThreadState_Current)) Py_FatalError("PyThreadState_Delete: tstate is still current"); tstate_delete_common(tstate); #ifdef WITH_THREAD @@ -348,11 +350,12 @@ void PyThreadState_DeleteCurrent() { - PyThreadState *tstate = _PyThreadState_Current; + PyThreadState *tstate = (PyThreadState*)_Py_atomic_load_relaxed( + &_PyThreadState_Current); if (tstate == NULL) Py_FatalError( "PyThreadState_DeleteCurrent: no current tstate"); - _PyThreadState_Current = NULL; + _Py_atomic_store_relaxed(&_PyThreadState_Current, NULL); tstate_delete_common(tstate); if (autoTLSkey && PyThread_get_key_value(autoTLSkey) == tstate) PyThread_delete_key_value(autoTLSkey); @@ -364,19 +367,22 @@ PyThreadState * PyThreadState_Get(void) { - if (_PyThreadState_Current == NULL) + PyThreadState *tstate = (PyThreadState*)_Py_atomic_load_relaxed( + &_PyThreadState_Current); + if (tstate == NULL) Py_FatalError("PyThreadState_Get: no current thread"); - return _PyThreadState_Current; + return tstate; } PyThreadState * PyThreadState_Swap(PyThreadState *newts) { - PyThreadState *oldts = _PyThreadState_Current; + PyThreadState *oldts = (PyThreadState*)_Py_atomic_load_relaxed( + &_PyThreadState_Current); - _PyThreadState_Current = newts; + _Py_atomic_store_relaxed(&_PyThreadState_Current, newts); /* It should not be possible for more than one thread state to be used for a thread. Check this the best we can in debug builds. @@ -405,16 +411,18 @@ PyObject * PyThreadState_GetDict(void) { - if (_PyThreadState_Current == NULL) + PyThreadState *tstate = (PyThreadState*)_Py_atomic_load_relaxed( + &_PyThreadState_Current); + if (tstate == NULL) return NULL; - if (_PyThreadState_Current->dict == NULL) { + if (tstate->dict == NULL) { PyObject *d; - _PyThreadState_Current->dict = d = PyDict_New(); + tstate->dict = d = PyDict_New(); if (d == NULL) PyErr_Clear(); } - return _PyThreadState_Current->dict; + return tstate->dict; } @@ -550,10 +558,7 @@ { /* Must be the tstate for this thread */ assert(PyGILState_GetThisThreadState()==tstate); - /* On Windows at least, simple reads and writes to 32 bit values - are atomic. - */ - return tstate == _PyThreadState_Current; + return tstate == _Py_atomic_load_relaxed(&_PyThreadState_Current); } /* Internal initialization/finalization functions called by Modified: python/branches/py3k/Python/thread_pthread.h ============================================================================== --- python/branches/py3k/Python/thread_pthread.h (original) +++ python/branches/py3k/Python/thread_pthread.h Mon May 3 21:29:34 2010 @@ -397,6 +397,12 @@ status = pthread_mutex_init(&lock->mut, pthread_mutexattr_default); CHECK_STATUS("pthread_mutex_init"); + /* Mark the pthread mutex underlying a Python mutex as + pure happens-before. We can't simply mark the + Python-level mutex as a mutex because it can be + acquired and released in different threads, which + will cause errors. */ + _Py_ANNOTATE_PURE_HAPPENS_BEFORE_MUTEX(&lock->mut); status = pthread_cond_init(&lock->lock_released, pthread_condattr_default); Modified: python/branches/py3k/configure ============================================================================== --- python/branches/py3k/configure (original) +++ python/branches/py3k/configure Mon May 3 21:29:34 2010 @@ -1,5 +1,5 @@ #! /bin/sh -# From configure.in Revision: 80648 . +# From configure.in Revision: 80666 . # Guess values for system-dependent variables and create Makefiles. # Generated by GNU Autoconf 2.65 for python 3.2. # @@ -1929,11 +1929,11 @@ cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ $ac_includes_default + enum { N = $2 / 2 - 1 }; int main () { -static int test_array [1 - 2 * !(enum { N = $2 / 2 - 1 }; - 0 < ($ac_type) ((((($ac_type) 1 << N) << N) - 1) * 2 + 1))]; +static int test_array [1 - 2 * !(0 < ($ac_type) ((((($ac_type) 1 << N) << N) - 1) * 2 + 1))]; test_array [0] = 0 ; @@ -1944,11 +1944,11 @@ cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ $ac_includes_default + enum { N = $2 / 2 - 1 }; int main () { -static int test_array [1 - 2 * !(enum { N = $2 / 2 - 1 }; - ($ac_type) ((((($ac_type) 1 << N) << N) - 1) * 2 + 1) +static int test_array [1 - 2 * !(($ac_type) ((((($ac_type) 1 << N) << N) - 1) * 2 + 1) < ($ac_type) ((((($ac_type) 1 << N) << N) - 1) * 2 + 2))]; test_array [0] = 0 @@ -9210,6 +9210,7 @@ fi + OPT="-DDYNAMIC_ANNOTATIONS_ENABLED=1 $OPT" fi # Check for --with-wctype-functions Modified: python/branches/py3k/configure.in ============================================================================== --- python/branches/py3k/configure.in (original) +++ python/branches/py3k/configure.in Mon May 3 21:29:34 2010 @@ -2515,6 +2515,7 @@ [AC_DEFINE([WITH_VALGRIND], 1, [Define if you want pymalloc to be disabled when running under valgrind])], [AC_MSG_ERROR([Valgrind support requested but headers not available])] ) + OPT="-DDYNAMIC_ANNOTATIONS_ENABLED=1 $OPT" fi # Check for --with-wctype-functions From python-checkins at python.org Mon May 3 22:21:47 2010 From: python-checkins at python.org (jesus.cea) Date: Mon, 3 May 2010 22:21:47 +0200 (CEST) Subject: [Python-checkins] r80725 - peps/trunk/pep-0011.txt Message-ID: <20100503202147.D7B0CE188@mail.python.org> Author: jesus.cea Date: Mon May 3 22:21:47 2010 New Revision: 80725 Log: OSF* goes unsupported Modified: peps/trunk/pep-0011.txt Modified: peps/trunk/pep-0011.txt ============================================================================== --- peps/trunk/pep-0011.txt (original) +++ peps/trunk/pep-0011.txt Mon May 3 22:21:47 2010 @@ -160,6 +160,10 @@ Unsupported in: Python 3.2 Code removed in: Python 3.3 + Name: OSF* systems (issue 8606) + Unsupported in: Python 3.2 + Code removed in: Python 3.3 + Platform Maintainers Cygwin Jason Tishler (jason at tishler.net) From python-checkins at python.org Mon May 3 22:55:22 2010 From: python-checkins at python.org (benjamin.peterson) Date: Mon, 3 May 2010 22:55:22 +0200 (CEST) Subject: [Python-checkins] r80726 - in python/branches/py3k: Include/dynamic_annotations.h Include/pyatomic.h Python/dynamic_annotations.c Message-ID: <20100503205522.BCEA6F95A@mail.python.org> Author: benjamin.peterson Date: Mon May 3 22:55:22 2010 New Revision: 80726 Log: set svn:eol-style to native Modified: python/branches/py3k/Include/dynamic_annotations.h (props changed) python/branches/py3k/Include/pyatomic.h (props changed) python/branches/py3k/Python/dynamic_annotations.c (props changed) From python-checkins at python.org Mon May 3 23:09:59 2010 From: python-checkins at python.org (benjamin.peterson) Date: Mon, 3 May 2010 23:09:59 +0200 (CEST) Subject: [Python-checkins] r80727 - python/branches/py3k/Python/ceval.c Message-ID: <20100503210959.F1ABAE046@mail.python.org> Author: benjamin.peterson Date: Mon May 3 23:09:59 2010 New Revision: 80727 Log: read eval_breaker with atomic api with computed gotos Modified: python/branches/py3k/Python/ceval.c Modified: python/branches/py3k/Python/ceval.c ============================================================================== --- python/branches/py3k/Python/ceval.c (original) +++ python/branches/py3k/Python/ceval.c Mon May 3 23:09:59 2010 @@ -868,7 +868,7 @@ #define DISPATCH() \ { \ - if (!eval_breaker) { \ + if (!_Py_atomic_load_relaxed(&eval_breaker)) { \ FAST_DISPATCH(); \ } \ continue; \ From python-checkins at python.org Mon May 3 23:18:48 2010 From: python-checkins at python.org (jesus.cea) Date: Mon, 3 May 2010 23:18:48 +0200 (CEST) Subject: [Python-checkins] r80728 - in python/branches/py3k: Misc/NEWS configure configure.in Message-ID: <20100503211848.520D4E367@mail.python.org> Author: jesus.cea Date: Mon May 3 23:18:48 2010 New Revision: 80728 Log: Deprecate OSF* support Modified: python/branches/py3k/Misc/NEWS python/branches/py3k/configure python/branches/py3k/configure.in Modified: python/branches/py3k/Misc/NEWS ============================================================================== --- python/branches/py3k/Misc/NEWS (original) +++ python/branches/py3k/Misc/NEWS Mon May 3 23:18:48 2010 @@ -204,6 +204,9 @@ libraries are: Mach C threads, SunOS LWP, GNU pth, Irix threads. Support code will be entirely removed in 3.3. +- Support for OSF* has been disabled. If nobody stands up, support will be + removed in 3.3. See http://bugs.python.org/issue8606 . + - Peephole constant folding had missed UNARY_POSITIVE. - Issue #1722344: threading._shutdown() is now called in Py_Finalize(), which Modified: python/branches/py3k/configure ============================================================================== --- python/branches/py3k/configure (original) +++ python/branches/py3k/configure Mon May 3 23:18:48 2010 @@ -13554,6 +13554,12 @@ +case $ac_sys_system in + OSF*) as_fn_error "OSF* systems are deprecated unless somebody volunteers. Check http://bugs.python.org/issue8606" "$LINENO" 5 ;; +esac + + + for h in `(cd $srcdir;echo Python/thread_*.h)` do THREADHEADERS="$THREADHEADERS \$(srcdir)/$h" Modified: python/branches/py3k/configure.in ============================================================================== --- python/branches/py3k/configure.in (original) +++ python/branches/py3k/configure.in Mon May 3 23:18:48 2010 @@ -4165,6 +4165,13 @@ [AC_MSG_RESULT(no)]) + +case $ac_sys_system in + OSF*) AC_MSG_ERROR(OSF* systems are deprecated unless somebody volunteers. Check http://bugs.python.org/issue8606) ;; +esac + + + AC_SUBST(THREADHEADERS) for h in `(cd $srcdir;echo Python/thread_*.h)` From python-checkins at python.org Mon May 3 23:24:58 2010 From: python-checkins at python.org (jesus.cea) Date: Mon, 3 May 2010 23:24:58 +0200 (CEST) Subject: [Python-checkins] r80729 - python/branches/release31-maint Message-ID: <20100503212458.43273DDA2@mail.python.org> Author: jesus.cea Date: Mon May 3 23:24:58 2010 New Revision: 80729 Log: Blocked revisions 80728 via svnmerge ........ r80728 | jesus.cea | 2010-05-03 23:18:48 +0200 (Mon, 03 May 2010) | 1 line Deprecate OSF* support ........ Modified: python/branches/release31-maint/ (props changed) From martin at v.loewis.de Mon May 3 23:36:05 2010 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Mon, 03 May 2010 23:36:05 +0200 Subject: [Python-checkins] r80728 - in python/branches/py3k: Misc/NEWS configure configure.in In-Reply-To: <20100503211848.520D4E367@mail.python.org> References: <20100503211848.520D4E367@mail.python.org> Message-ID: <4BDF41C5.3090401@v.loewis.de> > + OSF*) AC_MSG_ERROR(OSF* systems are deprecated unless somebody volunteers. Check http://bugs.python.org/issue8606) ;; Minor nit: it is actually not up to us to deprecate(*) OSF/1 - we just don't _support_ it anymore, in Python. Unless a native speaker (of English) would like to see that rephrased, it can stay, though (IMO). Regards, Martin (*) deprecate, verb: 2. to express disapproval of From eric at trueblade.com Mon May 3 23:40:18 2010 From: eric at trueblade.com (Eric Smith) Date: Mon, 03 May 2010 17:40:18 -0400 Subject: [Python-checkins] r80728 - in python/branches/py3k: Misc/NEWS configure configure.in In-Reply-To: <4BDF41C5.3090401@v.loewis.de> References: <20100503211848.520D4E367@mail.python.org> <4BDF41C5.3090401@v.loewis.de> Message-ID: <4BDF42C2.3060600@trueblade.com> Martin v. L?wis wrote: >> + OSF*) AC_MSG_ERROR(OSF* systems are deprecated unless somebody volunteers. Check http://bugs.python.org/issue8606) ;; > > Minor nit: it is actually not up to us to deprecate(*) OSF/1 - we just > don't _support_ it anymore, in Python. > Unless a native speaker (of English) would like to see that rephrased, > it can stay, though (IMO). Perhaps "Support for OSF* systems is ending. Check http:// ...". From ncoghlan at gmail.com Mon May 3 23:56:31 2010 From: ncoghlan at gmail.com (Nick Coghlan) Date: Tue, 04 May 2010 07:56:31 +1000 Subject: [Python-checkins] r80720 - in python/trunk: Lib/_pyio.py Lib/test/test_io.py Misc/NEWS Modules/_io/bufferedio.c Modules/_io/bytesio.c Modules/_io/iobase.c Modules/_io/textio.c In-Reply-To: <20100503162533.A8AB8E726@mail.python.org> References: <20100503162533.A8AB8E726@mail.python.org> Message-ID: <4BDF468F.60805@gmail.com> antoine.pitrou wrote: > Author: antoine.pitrou > Date: Mon May 3 18:25:33 2010 > New Revision: 80720 > > Log: > Issue #7865: The close() method of :mod:`io` objects should not swallow > exceptions raised by the implicit flush(). Also ensure that calling > close() several times is supported. Patch by Pascal Chambon. I believe silencing errors in file.close() was a conscious decision (although I may just be remembering the discussions about __del__). Either way, reverting it should be discussed on python-dev. I definitely have grave doubts about backporting this to the maintenance branches, and I'm not a particularly big fan of adding it to a release that is already in beta either. (A comment, not for close itself, but for __del__): http://mail.python.org/pipermail/python-dev/2009-February/086367.html If people want to receive the error, they can already just write: f.flush() f.close() (Given Guido's last comment in the linked email, having an explicit close() raise exceptions due to failure of the implicit flush() may be OK, but it should be discussed with a slightly wider audience regardless) Cheers, Nick. -- Nick Coghlan | ncoghlan at gmail.com | Brisbane, Australia --------------------------------------------------------------- From ncoghlan at gmail.com Tue May 4 00:00:37 2010 From: ncoghlan at gmail.com (Nick Coghlan) Date: Tue, 04 May 2010 08:00:37 +1000 Subject: [Python-checkins] r80728 - in python/branches/py3k: Misc/NEWS configure configure.in In-Reply-To: <4BDF42C2.3060600@trueblade.com> References: <20100503211848.520D4E367@mail.python.org> <4BDF41C5.3090401@v.loewis.de> <4BDF42C2.3060600@trueblade.com> Message-ID: <4BDF4785.5090505@gmail.com> Eric Smith wrote: > Martin v. L?wis wrote: >>> + OSF*) AC_MSG_ERROR(OSF* systems are deprecated unless somebody >>> volunteers. Check http://bugs.python.org/issue8606) ;; >> >> Minor nit: it is actually not up to us to deprecate(*) OSF/1 - we just >> don't _support_ it anymore, in Python. >> Unless a native speaker (of English) would like to see that rephrased, >> it can stay, though (IMO). > > Perhaps "Support for OSF* systems is ending. Check http:// ...". Jesus's basic phrasing is OK, but I agree with Martin that the word "deprecated" should be swapped for the word "unsupported". Cheers, Nick. -- Nick Coghlan | ncoghlan at gmail.com | Brisbane, Australia --------------------------------------------------------------- From nnorwitz at gmail.com Tue May 4 00:29:24 2010 From: nnorwitz at gmail.com (Neal Norwitz) Date: Mon, 3 May 2010 18:29:24 -0400 Subject: [Python-checkins] Python Regression Test Failures refleak (1) Message-ID: <20100503222924.GA27540@kbk-i386-bb.psfb.org> More important issues: ---------------------- test_bz2 leaked [0, 83, 0] references, sum=83 Less important issues: ---------------------- From solipsis at pitrou.net Tue May 4 00:40:28 2010 From: solipsis at pitrou.net (solipsis at pitrou.net) Date: Tue, 4 May 2010 00:40:28 +0200 (CEST) Subject: [Python-checkins] Daily py3k reference leaks (r80727): sum=0 Message-ID: <20100503224028.21FD01771F@ns6635.ovh.net> py3k results for svn r80727 (hg cset 91d423565b83) -------------------------------------------------- Command line was: ['./python', '-m', 'test.regrtest', '-uall', '-R', '3:3:/home/antoine/py3k/refleaks/reflogv_p5qH', '-x'] From solipsis at pitrou.net Tue May 4 01:20:38 2010 From: solipsis at pitrou.net (Antoine Pitrou) Date: Mon, 3 May 2010 23:20:38 +0000 (UTC) Subject: [Python-checkins] =?utf-8?q?r80720_-_in_python/trunk=3A_Lib/=5Fpy?= =?utf-8?q?io=2EpyLib/test/test=5Fio=2Epy_Misc/NEWS_Modules/=5Fio/b?= =?utf-8?q?ufferedio=2Ec=09Modules/=5Fio/bytesio=2EcModules/=5Fio/i?= =?utf-8?q?obase=2EcModules/=5Fio/textio=2Ec?= References: <20100503162533.A8AB8E726@mail.python.org> <4BDF468F.60805@gmail.com> Message-ID: Nick Coghlan gmail.com> writes: > > I believe silencing errors in file.close() was a conscious decision > (although I may just be remembering the discussions about __del__). Yes, I think you are remembering the discussions about __del__ :) There's no excuse for silencing errors in flush() when close() is called. These errors indicate that not everything was committed to disk and the file contents are subsequently corrupted. If the user doesn't get informed about it, we're clearly doing something wrong. (of course, these errors rarely happen in modern life - which can make them even more dangerous if silenced) > Either way, reverting it should be discussed on python-dev. I definitely > have grave doubts about backporting this to the maintenance branches, > and I'm not a particularly big fan of adding it to a release that is > already in beta either. Silencing a true and potentially critical error is a bug IMO. Moreover, we'd better establish sane semantics in the io module before it gets widespread acceptance - this was the rationale for the truncate() API change, approved by Guido (while I was a bit reluctant). Regards Antoine. From python-checkins at python.org Tue May 4 01:24:54 2010 From: python-checkins at python.org (jeffrey.yasskin) Date: Tue, 4 May 2010 01:24:54 +0200 (CEST) Subject: [Python-checkins] r80730 - in python/branches/py3k-jit: Doc/about.rst Doc/bugs.rst Doc/c-api/arg.rst Doc/documenting/index.rst Doc/documenting/style.rst Doc/howto/doanddont.rst Doc/library/argparse.rst Doc/library/asynchat.rst Doc/library/http.client.rst Doc/library/http.cookiejar.rst Doc/library/io.rst Doc/library/shutil.rst Doc/library/stdtypes.rst Doc/library/sys.rst Doc/library/syslog.rst Doc/library/unittest.rst Doc/library/winreg.rst Doc/library/zlib.rst Doc/tools/sphinxext/indexsidebar.html Doc/tools/sphinxext/layout.html Include/Python.h Include/dictobject.h Include/dynamic_annotations.h Include/modsupport.h Include/pyatomic.h Include/pystate.h Lib/_pyio.py Lib/compileall.py Lib/ctypes/test/test_errno.py Lib/http/client.py Lib/locale.py Lib/os.py Lib/shutil.py Lib/socketserver.py Lib/sqlite3/test/dbapi.py Lib/ssl.py Lib/subprocess.py Lib/tarfile.py Lib/test/fork_wait.py Lib/test/regrtest.py Lib/test/support.py Lib/test/test_asynchat.py Lib/test/test_asyncore.py Lib/test/test_bz2.py Lib/test/test_capi.py Lib/test/test_cmd.py Lib/test/test_compileall.py Lib/test/test_contextlib.py Lib/test/test_dict.py Lib/test/test_doctest.py Lib/test/test_docxmlrpc.py Lib/test/test_fork1.py Lib/test/test_ftplib.py Lib/test/test_gdb.py Lib/test/test_hashlib.py Lib/test/test_httplib.py Lib/test/test_httpservers.py Lib/test/test_io.py Lib/test/test_locale.py Lib/test/test_logging.py Lib/test/test_multiprocessing.py Lib/test/test_poplib.py Lib/test/test_queue.py Lib/test/test_shutil.py Lib/test/test_smtplib.py Lib/test/test_socket.py Lib/test/test_socketserver.py Lib/test/test_ssl.py Lib/test/test_subprocess.py Lib/test/test_sys.py Lib/test/test_tarfile.py Lib/test/test_telnetlib.py Lib/test/test_thread.py Lib/test/test_threaded_import.py Lib/test/test_threadedtempfile.py Lib/test/test_threading.py Lib/test/test_threading_local.py Lib/test/test_threadsignals.py Lib/test/test_urllib2_localnet.py Lib/test/test_urllibnet.py Lib/test/test_xmlrpc.py Lib/unittest/__init__.py Lib/unittest/result.py Lib/unittest/signals.py Lib/unittest/test/test_break.py Lib/unittest/test/test_result.py Lib/urllib/request.py Lib/webbrowser.py Mac/BuildScript/build-installer.py Mac/Makefile.in Mac/PythonLauncher/Makefile.in Mac/README Makefile.pre.in Misc/ACKS Misc/NEWS Misc/maintainers.rst Modules/_io/bufferedio.c Modules/_io/bytesio.c Modules/_io/iobase.c Modules/_io/textio.c Modules/_ssl.c Modules/bz2module.c Modules/gcmodule.c Modules/posixmodule.c Modules/socketmodule.c Modules/syslogmodule.c Objects/dictobject.c Objects/exceptions.c Objects/fileobject.c Objects/unicodeobject.c PC/VS7.1/pythoncore.vcproj PC/VS8.0/pythoncore.vcproj PC/_subprocess.c PC/os2emx/Makefile PCbuild/pythoncore.vcproj Parser/tokenizer.c Python/ceval.c Python/ceval_gil.h Python/dynamic_annotations.c Python/getargs.c Python/pystate.c Python/sysmodule.c Python/thread_pthread.h configure configure.in pyconfig.h.in Message-ID: <20100503232454.4E2E2E814@mail.python.org> Author: jeffrey.yasskin Date: Tue May 4 01:24:51 2010 New Revision: 80730 Log: Merged revisions 80390,80394,80401-80402,80404,80408-80409,80413,80416,80421,80424,80426,80429,80436,80441,80444,80447,80449-80450,80454,80456,80459,80463,80472,80474-80475,80477-80479,80481,80483,80485,80487,80489,80493,80497,80501-80502,80505,80509,80515,80517,80520-80521,80524,80528,80532,80536,80542,80545,80550-80551,80559,80562,80576,80582,80585,80587,80589,80594,80598,80600,80603,80612,80614,80618,80624,80626,80629,80633,80640,80648,80655,80659,80661,80663,80666,80671,80677,80683,80688,80692,80694,80697,80699,80703,80705,80709,80714,80718,80722,80724,80726-80728 via svnmerge from svn+ssh://pythondev at svn.python.org/python/branches/py3k ................ r80390 | georg.brandl | 2010-04-22 16:20:19 -0700 (Thu, 22 Apr 2010) | 9 lines Merged revisions 80388 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r80388 | georg.brandl | 2010-04-23 00:15:33 +0200 (Fr, 23 Apr 2010) | 1 line Add "report a bug" links in some prominent places. Make it clear that doc bugs can be mailed to docs at python.org. Clarify tracker usage. ........ ................ r80394 | antoine.pitrou | 2010-04-22 17:16:21 -0700 (Thu, 22 Apr 2010) | 15 lines Merged revisions 80392 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r80392 | antoine.pitrou | 2010-04-23 01:33:02 +0200 (ven., 23 avril 2010) | 9 lines Issue #8108: Fix the unwrap() method of SSL objects when the socket has a non-infinite timeout. Also make that method friendlier with applications wanting to continue using the socket in clear-text mode, by disabling OpenSSL's internal readahead. Thanks to Darryl Miles for guidance. Issue #8108: test_ftplib's non-blocking SSL server now has proper handling of SSL shutdowns. ........ ................ r80401 | sean.reifschneider | 2010-04-23 02:29:52 -0700 (Fri, 23 Apr 2010) | 2 lines Port of issue8451 to python3: Syslog use sys.argv[0] for ident. ................ r80402 | victor.stinner | 2010-04-23 03:56:17 -0700 (Fri, 23 Apr 2010) | 2 lines Issue #8468: bz2.BZ2File() accepts str with surrogates and bytes filenames ................ r80404 | victor.stinner | 2010-04-23 05:02:30 -0700 (Fri, 23 Apr 2010) | 4 lines Issue #8124: PySys_WriteStdout() and PySys_WriteStderr() don't execute indirectly Python signal handlers anymore because mywrite() ignores exceptions (KeyboardInterrupt). ................ r80408 | tarek.ziade | 2010-04-23 06:03:09 -0700 (Fri, 23 Apr 2010) | 1 line make sure os.symlink presence is tested before running some shutil tests -- also refactored the tests to use unittest.skipUnless ................ r80409 | tarek.ziade | 2010-04-23 06:03:50 -0700 (Fri, 23 Apr 2010) | 1 line added a note about the ignore_dangling_symlinks option ................ r80413 | victor.stinner | 2010-04-23 12:28:32 -0700 (Fri, 23 Apr 2010) | 3 lines Issue #8467: Pure Python implementation of subprocess encodes the error message using surrogatepass error handler to support surrogates in the message ................ r80416 | victor.stinner | 2010-04-23 13:33:55 -0700 (Fri, 23 Apr 2010) | 2 lines Issue #8495: test_gdb uses replace error handler when decoding utf8 output ................ r80421 | victor.stinner | 2010-04-23 14:41:56 -0700 (Fri, 23 Apr 2010) | 3 lines Issue #8391: os.execvpe() and os.getenv() supports unicode with surrogates and bytes strings for environment keys and values ................ r80424 | victor.stinner | 2010-04-23 15:55:39 -0700 (Fri, 23 Apr 2010) | 13 lines Fix test_undecodable_env of test_subproces for non-ASCII directory This test was introduced by r80421 (issue #8391). The fix: copy the environment variables instead of starting Python in an empty environement. In an empty environment, the locale is C and Python uses ASCII for the default file system encoding. The non-ASCII directory will be encoded using surrogates, but Python3 is unable to load a module or package with a filename using surrogates. See issue #8242 for more information about running Python3 with a non-ascii directory in an empty environement. ................ r80426 | antoine.pitrou | 2010-04-23 16:10:32 -0700 (Fri, 23 Apr 2010) | 13 lines Only the test is merged in. Merged revisions 80423 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r80423 | antoine.pitrou | 2010-04-24 00:54:59 +0200 (sam., 24 avril 2010) | 4 lines Issue #7943: Fix circular reference created when instantiating an SSL socket. Initial patch by P?ter Szab?. ........ ................ r80429 | antoine.pitrou | 2010-04-23 16:31:47 -0700 (Fri, 23 Apr 2010) | 13 lines Note: I'm just merging in the additional test. Merged revisions 80428 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r80428 | antoine.pitrou | 2010-04-24 01:25:45 +0200 (sam., 24 avril 2010) | 4 lines Issue #5238: Calling makefile() on an SSL object would prevent the underlying socket from being closed until all objects get truely destroyed. ........ ................ r80436 | antoine.pitrou | 2010-04-24 04:13:53 -0700 (Sat, 24 Apr 2010) | 11 lines Merged revisions 80434 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r80434 | antoine.pitrou | 2010-04-24 12:43:57 +0200 (sam., 24 avril 2010) | 5 lines Make test_makefile_close a networked test (can't read() from a non-connected socket under OS X), and skip it under Windows (where sockets can't be read() from using their fds). ........ ................ r80441 | brian.curtin | 2010-04-24 09:19:22 -0700 (Sat, 24 Apr 2010) | 13 lines Merged revisions 80439 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r80439 | brian.curtin | 2010-04-24 10:40:11 -0500 (Sat, 24 Apr 2010) | 6 lines Fix #7838. Add docstrings and privatize _subprocess implementation details. Since CREATE_NEW_* are used for the creation flags of a subprocess, they were added to __all__. The rest of the previously exposed attributes are now qualified by _subprocess.ATTR rather than importing *. ........ ................ r80444 | matthias.klose | 2010-04-24 10:04:35 -0700 (Sat, 24 Apr 2010) | 9 lines Merged revisions 80443 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r80443 | matthias.klose | 2010-04-24 18:38:36 +0200 (Sa, 24 Apr 2010) | 2 lines - Issue #8509: Fix quoting in help strings and code snippets in configure.in. ........ ................ r80447 | brian.curtin | 2010-04-24 10:21:31 -0700 (Sat, 24 Apr 2010) | 2 lines Fix #5774. Change doc to reflect that some functions have defaults but not kwargs. ................ r80449 | matthias.klose | 2010-04-24 10:59:49 -0700 (Sat, 24 Apr 2010) | 2 lines - Issue #8510: Update to autoconf2.65. ................ r80450 | benjamin.peterson | 2010-04-24 11:21:17 -0700 (Sat, 24 Apr 2010) | 6 lines prevent the dict constructor from accepting non-string keyword args #8419 This adds PyArg_ValidateKeywordArguments, which checks that keyword arguments are all strings, using an optimized method if possible. ................ r80454 | antoine.pitrou | 2010-04-24 14:26:44 -0700 (Sat, 24 Apr 2010) | 15 lines Merged revisions 80451-80452 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r80451 | antoine.pitrou | 2010-04-24 21:57:01 +0200 (sam., 24 avril 2010) | 4 lines The do_handshake() method of SSL objects now adjusts the blocking mode of the SSL structure if necessary (as other methods already do). ........ r80452 | antoine.pitrou | 2010-04-24 22:04:58 +0200 (sam., 24 avril 2010) | 4 lines Issue #5103: SSL handshake would ignore the socket timeout and block indefinitely if the other end didn't respond. ........ ................ r80456 | antoine.pitrou | 2010-04-24 15:04:40 -0700 (Sat, 24 Apr 2010) | 5 lines Issue #8524: When creating an SSL socket, the timeout value of the original socket wasn't retained (instead, a socket with a positive timeout would be turned into a non-blocking SSL socket). ................ r80459 | sean.reifschneider | 2010-04-24 23:31:55 -0700 (Sat, 24 Apr 2010) | 1 line Porting commit 80458 to python 3 ................ r80463 | georg.brandl | 2010-04-25 03:19:53 -0700 (Sun, 25 Apr 2010) | 17 lines Merged revisions 80150,80460-80461 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r80150 | r.david.murray | 2010-04-17 17:45:38 +0200 (Sa, 17 Apr 2010) | 2 lines Update link to Apple Publication Style guide. ........ r80460 | georg.brandl | 2010-04-25 12:16:00 +0200 (So, 25 Apr 2010) | 1 line #8528: fix typo. ........ r80461 | georg.brandl | 2010-04-25 12:17:27 +0200 (So, 25 Apr 2010) | 1 line #8522: use with statement instead of try-finally for file handling. ........ ................ r80472 | ezio.melotti | 2010-04-25 10:48:01 -0700 (Sun, 25 Apr 2010) | 9 lines Merged revisions 79786 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r79786 | ezio.melotti | 2010-04-05 11:02:54 +0300 (Mon, 05 Apr 2010) | 1 line Fix markup, punctuation and whitespaces in _winreg.rst. ........ ................ r80474 | matthias.klose | 2010-04-25 11:34:36 -0700 (Sun, 25 Apr 2010) | 2 lines - configure.in: Replace AC_HELP_STRING with AS_HELP_STRING ................ r80475 | matthias.klose | 2010-04-25 11:43:42 -0700 (Sun, 25 Apr 2010) | 2 lines configure.in: s/AC_AIX/AC_USE_SYSTEM_EXTENSIONS/ ................ r80477 | michael.foord | 2010-04-25 12:53:49 -0700 (Sun, 25 Apr 2010) | 9 lines Merged revisions 80476 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r80476 | michael.foord | 2010-04-25 20:02:46 +0100 (Sun, 25 Apr 2010) | 1 line Adding unittest.removeHandler function / decorator for removing the signal.SIGINT signal handler. With tests and docs. ........ ................ r80478 | matthias.klose | 2010-04-25 14:00:44 -0700 (Sun, 25 Apr 2010) | 3 lines configure.in: convert all obsolete AC_TRY_* macros to AC_*_IFELSE, only whitespace changes in generated configure (diff -uEwB). ................ r80479 | benjamin.peterson | 2010-04-25 14:03:34 -0700 (Sun, 25 Apr 2010) | 1 line add versionadded ................ r80481 | matthias.klose | 2010-04-25 14:18:48 -0700 (Sun, 25 Apr 2010) | 3 lines configure.in: Avoid autoconf warning: Assume C89 semantics that RETSIGTYPE is always void (issue #8510). ................ r80483 | matthias.klose | 2010-04-25 14:23:32 -0700 (Sun, 25 Apr 2010) | 2 lines Makefile.pre.in (autoconf): Call autoconf/autoheader with -Wall (issue #8510). ................ r80485 | benjamin.peterson | 2010-04-25 14:54:00 -0700 (Sun, 25 Apr 2010) | 1 line condense condition ................ r80487 | antoine.pitrou | 2010-04-25 15:01:43 -0700 (Sun, 25 Apr 2010) | 12 lines Merged revisions 80484 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r80484 | antoine.pitrou | 2010-04-25 23:40:32 +0200 (dim., 25 avril 2010) | 6 lines Issue #2302: Fix a race condition in SocketServer.BaseServer.shutdown, where the method could block indefinitely if called just before the event loop started running. This also fixes the occasional freezes witnessed in test_httpservers. ........ ................ r80489 | antoine.pitrou | 2010-04-25 15:19:43 -0700 (Sun, 25 Apr 2010) | 9 lines Merged revisions 80480 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r80480 | antoine.pitrou | 2010-04-25 23:15:50 +0200 (dim., 25 avril 2010) | 3 lines Replace a Lock with a better suited Event. ........ ................ r80493 | brett.cannon | 2010-04-25 15:35:57 -0700 (Sun, 25 Apr 2010) | 12 lines Blocked revisions 80492 via svnmerge ........ r80492 | brett.cannon | 2010-04-25 15:33:36 -0700 (Sun, 25 Apr 2010) | 6 lines When DeprecationWarning was silenced by default, it also silenced any use of -Q by default as well. This change fixes that by treating -Q like -3 when it comes to DeprecationWarning; using it causes the silencing to not occur. Fixes issue #7319. ........ ................ r80497 | benjamin.peterson | 2010-04-25 16:18:00 -0700 (Sun, 25 Apr 2010) | 8 lines Blocked revisions 80496 via svnmerge ........ r80496 | brett.cannon | 2010-04-25 18:11:51 -0500 (Sun, 25 Apr 2010) | 1 line Revert an accidental commit from r80492. ........ ................ r80501 | barry.warsaw | 2010-04-26 08:59:03 -0700 (Mon, 26 Apr 2010) | 8 lines Bug 8527 - multiple compileall calls produce cascading __pycache__ directories. * Patch contributed by Arfrever Frehtes Taifersar Arahesis. * Test added by Barry Also, improve Makefile's deletion of __pycache__ directories so e.g. 'make distclean' doesn't fail if no __pycache__ directories exist. ................ r80502 | barry.warsaw | 2010-04-26 09:02:14 -0700 (Mon, 26 Apr 2010) | 2 lines Ignore errors. ................ r80505 | r.david.murray | 2010-04-26 10:02:32 -0700 (Mon, 26 Apr 2010) | 9 lines Merged revisions 80503 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r80503 | r.david.murray | 2010-04-26 12:54:57 -0400 (Mon, 26 Apr 2010) | 2 lines Issue 8325: Improve regrtest --help text. ........ ................ r80509 | antoine.pitrou | 2010-04-26 10:29:05 -0700 (Mon, 26 Apr 2010) | 10 lines Merged revisions 80507 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r80507 | antoine.pitrou | 2010-04-26 19:23:33 +0200 (lun., 26 avril 2010) | 4 lines When calling getpeername() in SSLSocket.__init__, only silence exceptions caused by the "socket not connected" condition. ........ ................ r80515 | antoine.pitrou | 2010-04-26 15:17:47 -0700 (Mon, 26 Apr 2010) | 4 lines Hopefully fix sporadic Windows issue by avoiding calling getpeername() on a freshly dup'ed socket. ................ r80517 | antoine.pitrou | 2010-04-26 16:06:26 -0700 (Mon, 26 Apr 2010) | 3 lines Remove unused import ................ r80520 | michael.foord | 2010-04-26 16:41:26 -0700 (Mon, 26 Apr 2010) | 1 line Adding versionadded to several new functions in unittest documentation. ................ r80521 | r.david.murray | 2010-04-26 19:45:53 -0700 (Mon, 26 Apr 2010) | 13 lines Merged revisions 80512 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r80512 | r.david.murray | 2010-04-26 17:17:14 -0400 (Mon, 26 Apr 2010) | 7 lines Issue #6656: fix locale.format_string to handle escaped percents and mappings. Refactors format_string. Includes tests for the two problems noted in the issue, but as far as I can see there are no other tests that confirm that format_string conforms to normal % formatting rules. ........ ................ r80524 | antoine.pitrou | 2010-04-27 01:53:36 -0700 (Tue, 27 Apr 2010) | 9 lines Merged revisions 80522 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r80522 | antoine.pitrou | 2010-04-27 10:40:51 +0200 (mar., 27 avril 2010) | 3 lines Remove uses of find_unused_port() in test_ssl, and small cleanups ........ ................ r80528 | antoine.pitrou | 2010-04-27 02:56:02 -0700 (Tue, 27 Apr 2010) | 11 lines Merged revisions 80526 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r80526 | antoine.pitrou | 2010-04-27 11:51:18 +0200 (mar., 27 avril 2010) | 5 lines replace custom code with standard library functionality (HTTPServer.shutdown()) + enable test that was never run (!) + make tests faster by lowering polling timeout ........ ................ r80532 | antoine.pitrou | 2010-04-27 03:59:39 -0700 (Tue, 27 Apr 2010) | 10 lines Merged revisions 80529 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r80529 | antoine.pitrou | 2010-04-27 12:32:58 +0200 (mar., 27 avril 2010) | 4 lines Qualify or remove or bare excepts. Simplify exception handling in places. Remove uses of test_support.TestFailed. ........ ................ r80536 | antoine.pitrou | 2010-04-27 06:15:18 -0700 (Tue, 27 Apr 2010) | 9 lines Merged revisions 80534 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r80534 | antoine.pitrou | 2010-04-27 15:13:26 +0200 (mar., 27 avril 2010) | 3 lines socket.error can really happen here, and fix a possible NameError ........ ................ r80542 | antoine.pitrou | 2010-04-27 12:14:15 -0700 (Tue, 27 Apr 2010) | 10 lines Merged revisions 80540 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r80540 | antoine.pitrou | 2010-04-27 21:09:59 +0200 (mar., 27 avril 2010) | 4 lines Issue #8549: Fix compiling the _ssl extension under AIX. Patch by Sridhar Ratnakumar. ........ ................ r80545 | benjamin.peterson | 2010-04-27 14:07:21 -0700 (Tue, 27 Apr 2010) | 9 lines Merged revisions 80544 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r80544 | benjamin.peterson | 2010-04-27 16:01:54 -0500 (Tue, 27 Apr 2010) | 1 line reject None as the buffering argument like the C implementation does #8546 ........ ................ r80550 | benjamin.peterson | 2010-04-27 14:19:15 -0700 (Tue, 27 Apr 2010) | 12 lines Blocked revisions 80546-80547 via svnmerge ........ r80546 | benjamin.peterson | 2010-04-27 16:15:28 -0500 (Tue, 27 Apr 2010) | 1 line fix comment ........ r80547 | benjamin.peterson | 2010-04-27 16:17:22 -0500 (Tue, 27 Apr 2010) | 1 line fold __future__ imports ........ ................ r80551 | benjamin.peterson | 2010-04-27 14:24:03 -0700 (Tue, 27 Apr 2010) | 13 lines Merged revisions 80548-80549 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r80548 | benjamin.peterson | 2010-04-27 16:18:30 -0500 (Tue, 27 Apr 2010) | 1 line condense import ........ r80549 | benjamin.peterson | 2010-04-27 16:19:06 -0500 (Tue, 27 Apr 2010) | 1 line correct signature ........ ................ r80559 | antoine.pitrou | 2010-04-27 15:08:08 -0700 (Tue, 27 Apr 2010) | 12 lines Merged revisions 80557 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk (the bug was already fixed in py3k, just merging in the tests) ........ r80557 | antoine.pitrou | 2010-04-28 00:03:37 +0200 (mer., 28 avril 2010) | 4 lines Issue #8086: In :func:`ssl.DER_cert_to_PEM_cert()`, fix missing newline before the certificate footer. Patch by Kyle VanderBeek. ........ ................ r80562 | benjamin.peterson | 2010-04-27 15:58:50 -0700 (Tue, 27 Apr 2010) | 9 lines Merged revisions 80561 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r80561 | benjamin.peterson | 2010-04-27 17:56:31 -0500 (Tue, 27 Apr 2010) | 1 line make slice notation in (r)find docs consistent ........ ................ r80576 | jesus.cea | 2010-04-28 04:35:30 -0700 (Wed, 28 Apr 2010) | 9 lines Merged revisions 80574 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r80574 | jesus.cea | 2010-04-28 12:32:30 +0200 (Wed, 28 Apr 2010) | 1 line Issue #3928: Support 'os.mknod()' in Solaris ........ ................ r80582 | victor.stinner | 2010-04-28 10:06:46 -0700 (Wed, 28 Apr 2010) | 4 lines Use PyErr_Format() in decoding_fgets() Avoid a buffer of 500 bytes allocated on the stack. ................ r80585 | victor.stinner | 2010-04-28 10:26:19 -0700 (Wed, 28 Apr 2010) | 5 lines Don't decode/recode the unicode filename in SyntaxError_str() * Rewrite my_basename() to use unicode * Use '%U' format ................ r80587 | senthil.kumaran | 2010-04-28 10:39:48 -0700 (Wed, 28 Apr 2010) | 9 lines Merged revisions 80583 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r80583 | senthil.kumaran | 2010-04-28 22:50:43 +0530 (Wed, 28 Apr 2010) | 3 lines Fixed Issue6312 - httplib fails with HEAD requests to pages with "transfer-encoding: chunked" ........ ................ r80589 | tarek.ziade | 2010-04-28 10:51:36 -0700 (Wed, 28 Apr 2010) | 1 line #8295 : Added shutil.unpack_archive and related APIs ................ r80594 | antoine.pitrou | 2010-04-28 12:59:32 -0700 (Wed, 28 Apr 2010) | 14 lines Merged revisions 80591-80592 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r80591 | antoine.pitrou | 2010-04-28 21:53:35 +0200 (mer., 28 avril 2010) | 4 lines State clearly that truncate() doesn't move the file position, and remove a duplicate of its specification. ........ r80592 | antoine.pitrou | 2010-04-28 21:57:33 +0200 (mer., 28 avril 2010) | 3 lines Clarify and fix the documentation for IOBase.close() ........ ................ r80598 | antoine.pitrou | 2010-04-28 14:37:09 -0700 (Wed, 28 Apr 2010) | 9 lines Merged revisions 80596 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r80596 | antoine.pitrou | 2010-04-28 23:11:01 +0200 (mer., 28 avril 2010) | 3 lines Fix style issues in test_ssl ........ ................ r80600 | victor.stinner | 2010-04-28 15:31:17 -0700 (Wed, 28 Apr 2010) | 96 lines Merged revisions 80552-80556,80564-80566,80568-80571 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r80552 | victor.stinner | 2010-04-27 23:46:03 +0200 (mar., 27 avril 2010) | 3 lines Issue #7449, part 1: fix test_support.py for Python compiled without thread ........ r80553 | victor.stinner | 2010-04-27 23:47:01 +0200 (mar., 27 avril 2010) | 1 line Issue #7449, part 2: regrtest.py -j option requires thread support ........ r80554 | victor.stinner | 2010-04-27 23:51:26 +0200 (mar., 27 avril 2010) | 9 lines Issue #7449 part 3, test_doctest: import trace module in test_coverage() Import trace module fail if the threading module is missing. test_coverage() is only used if test_doctest.py is used with the -c option. This commit allows to execute the test suite without thread support. Move "import trace" in test_coverage() and use test_support.import_module('trace'). ........ r80555 | victor.stinner | 2010-04-27 23:56:26 +0200 (mar., 27 avril 2010) | 6 lines Issue #7449, part 4: skip test_multiprocessing if thread support is disabled import threading after _multiprocessing to raise a more revelant error message: "No module named _multiprocessing". _multiprocessing is not compiled without thread support. ........ r80556 | victor.stinner | 2010-04-28 00:01:24 +0200 (mer., 28 avril 2010) | 8 lines Issue #7449, part 5: split Test.test_open() of ctypes/test/test_errno.py * Split Test.test_open() in 2 functions: test_open() and test_thread_open() * Skip test_open() and test_thread_open() if we are unable to find the C library * Skip test_thread_open() if thread support is disabled * Use unittest.skipUnless(os.name == "nt", ...) on test_GetLastError() ........ r80564 | victor.stinner | 2010-04-28 00:59:35 +0200 (mer., 28 avril 2010) | 4 lines Issue #7449, part 6: fix test_hashlib for missing threading module Move @test_support.reap_thread decorator from test_main() to test_threaded_hashing(). ........ r80565 | victor.stinner | 2010-04-28 01:01:29 +0200 (mer., 28 avril 2010) | 6 lines Issue #7449, part 7: simplify threading detection in test_capi * Skip TestPendingCalls if threading module is missing * Test if threading module is present or not, instead of test the presence of _testcapi._test_thread_state ........ r80566 | victor.stinner | 2010-04-28 01:03:16 +0200 (mer., 28 avril 2010) | 4 lines Issue #7449, part 8: don't skip the whole test_asynchat if threading is missing TestFifo can be executed without the threading module ........ r80568 | victor.stinner | 2010-04-28 01:14:58 +0200 (mer., 28 avril 2010) | 6 lines Issue #7449, part 9: fix test_xmlrpclib for missing threading module * Skip testcases using threads if threading module is missing * Use "http://" instead of URL in ServerProxyTestCase if threading is missing because URL is not set in this case ........ r80569 | victor.stinner | 2010-04-28 01:33:58 +0200 (mer., 28 avril 2010) | 6 lines Partial revert of r80556 (Issue #7449, part 5, fix ctypes test) Rewrite r80556: the thread test have to be executed just after the test on libc_open() and so the test cannot be splitted in two functions (without duplicating code, and I don't want to duplicate code). ........ r80570 | victor.stinner | 2010-04-28 01:51:16 +0200 (mer., 28 avril 2010) | 8 lines Issue #7449, part 10: test_cmd imports trace module using test_support.import_module() Use test_support.import_module() instead of import to raise a SkipTest exception if the import fail. Import trace fails if the threading module is missing. See also part 3: test_doctest: import trace module in test_coverage(). ........ r80571 | victor.stinner | 2010-04-28 01:55:59 +0200 (mer., 28 avril 2010) | 6 lines Issue #7449, last part (11): fix many tests if thread support is disabled * Use try/except ImportError or test_support.import_module() to import thread and threading modules * Add @unittest.skipUnless(threading, ...) to testcases using threads ........ ................ r80603 | antoine.pitrou | 2010-04-28 15:57:15 -0700 (Wed, 28 Apr 2010) | 3 lines Fix test failure with -bb ................ r80612 | antoine.pitrou | 2010-04-29 03:11:46 -0700 (Thu, 29 Apr 2010) | 10 lines Merged revisions 80610 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r80610 | antoine.pitrou | 2010-04-29 12:05:40 +0200 (jeu., 29 avril 2010) | 4 lines Issue #7834: Fix connect() of Bluetooth L2CAP sockets with recent versions of the Linux kernel. Patch by Yaniv Aknin. ........ ................ r80614 | tarek.ziade | 2010-04-29 06:34:35 -0700 (Thu, 29 Apr 2010) | 1 line make sure shutil checks for bz2 availability before it uses it. ................ r80618 | lars.gustaebel | 2010-04-29 08:37:02 -0700 (Thu, 29 Apr 2010) | 10 lines Merged revisions 80616 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r80616 | lars.gustaebel | 2010-04-29 17:23:38 +0200 (Thu, 29 Apr 2010) | 4 lines Issue #8464: tarfile.open(name, mode="w|") no longer creates files with execute permissions set. ........ ................ r80624 | ezio.melotti | 2010-04-29 09:24:51 -0700 (Thu, 29 Apr 2010) | 9 lines Merged revisions 80620 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r80620 | ezio.melotti | 2010-04-29 18:07:20 +0200 (Thu, 29 Apr 2010) | 1 line Group the Windows entries in getfilesystemencoding doc, move the win 9x one at the bottom of the list and fix some markup. ........ ................ r80626 | barry.warsaw | 2010-04-29 11:43:10 -0700 (Thu, 29 Apr 2010) | 6 lines Bug 8563 - compileall.compile_file() creates empty __pycache__ directories in data directories where there is no source. Fix by: Arfrever Frehtes Taifersar Arahesis (Arfrever) Test by: Barry ................ r80629 | senthil.kumaran | 2010-04-29 13:02:50 -0700 (Thu, 29 Apr 2010) | 9 lines Merged revisions 80627 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r80627 | senthil.kumaran | 2010-04-30 01:16:08 +0530 (Fri, 30 Apr 2010) | 3 lines Fixing the Broken links of mechanize library. ........ ................ r80633 | giampaolo.rodola | 2010-04-29 13:45:01 -0700 (Thu, 29 Apr 2010) | 9 lines Merged revisions 80631 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r80631 | giampaolo.rodola | 2010-04-29 22:31:17 +0200 (gio, 29 apr 2010) | 1 line Fixes issue 8543 (asynchat documentation issues) ........ ................ r80640 | victor.stinner | 2010-04-29 17:22:08 -0700 (Thu, 29 Apr 2010) | 4 lines Simplify PyUnicode_FSConverter(): remove reference to PyByteArray PyByteArray is no more supported ................ r80648 | ronald.oussoren | 2010-04-30 04:41:56 -0700 (Fri, 30 Apr 2010) | 18 lines Merged revisions 80647 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r80647 | ronald.oussoren | 2010-04-30 13:20:14 +0200 (Fri, 30 Apr 2010) | 11 lines Fix for issue #3646: with this patch it is possible to do a framework install of Python in your home directory (on OSX): $ configure --enable-framework=${HOME}/Library/Frameworks $ make && make install Without this patch the framework would get installed just fine, but 'make install' would try to install the application bundles and command-line tools outside the user's home, which doesn't work for non-admin users (and is bad form anyway). ........ ................ r80655 | ronald.oussoren | 2010-04-30 08:00:26 -0700 (Fri, 30 Apr 2010) | 9 lines Merged revisions 80653 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r80653 | ronald.oussoren | 2010-04-30 16:58:39 +0200 (Fri, 30 Apr 2010) | 2 lines Fix for issue 8476 ........ ................ r80659 | ronald.oussoren | 2010-04-30 08:13:13 -0700 (Fri, 30 Apr 2010) | 10 lines Merged revisions 80657 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r80657 | ronald.oussoren | 2010-04-30 17:11:22 +0200 (Fri, 30 Apr 2010) | 3 lines Add notes about uninstalling a framework install to Mac/README. Fixes issue 7107. ........ ................ r80661 | victor.stinner | 2010-04-30 09:37:52 -0700 (Fri, 30 Apr 2010) | 6 lines PyUnicode_DecodeFSDefaultAndSize() uses surrogateescape error handler This function is only used to decode Python module filenames, but Python doesn't support surrogates in modules filenames yet. So nobody noticed this minor bug. ................ r80663 | victor.stinner | 2010-04-30 09:48:45 -0700 (Fri, 30 Apr 2010) | 4 lines PyFile_FromFd() uses PyUnicode_DecodeFSDefault() instead of PyUnicode_FromString() to support surrogates in the filename and use the right encoding ................ r80666 | marc-andre.lemburg | 2010-04-30 10:29:56 -0700 (Fri, 30 Apr 2010) | 13 lines Merged revisions 80665 via svnmerge from svn+pythonssh://pythondev at svn.python.org/python/trunk ........ r80665 | marc-andre.lemburg | 2010-04-30 19:20:14 +0200 (Fri, 30 Apr 2010) | 7 lines [issue8211] configure: ignore AC_PROG_CC hardcoded CFLAGS Only override the AC_PROG_CC determined CFLAGS if they were set by the user. This restores the default behavior in the common case of not having CFLAGS defined when running configure. ........ ................ r80671 | antoine.pitrou | 2010-04-30 16:20:15 -0700 (Fri, 30 Apr 2010) | 10 lines Merged revisions 80669 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r80669 | antoine.pitrou | 2010-05-01 01:08:48 +0200 (sam., 01 mai 2010) | 4 lines Issue #8576: Remove use of find_unused_port() in test_smtplib and test_multiprocessing. Patch by Paul Moore. ........ ................ r80677 | senthil.kumaran | 2010-05-01 01:29:18 -0700 (Sat, 01 May 2010) | 9 lines Merged revisions 80675 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r80675 | senthil.kumaran | 2010-05-01 13:31:56 +0530 (Sat, 01 May 2010) | 3 lines Fix issue8582: urllib.urlretrieve fails with ValueError: Invalid format string ........ ................ r80683 | mark.dickinson | 2010-05-01 04:59:03 -0700 (Sat, 01 May 2010) | 9 lines Recorded merge of revisions 80681 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r80681 | mark.dickinson | 2010-05-01 12:46:20 +0100 (Sat, 01 May 2010) | 2 lines Fix incorrect use of a list as the target of an 'except' clause in test_decimal.py. ........ ................ r80688 | giampaolo.rodola | 2010-05-01 11:04:27 -0700 (Sat, 01 May 2010) | 1 line add myself to Misc/maintainers.rst for asyncore, asynchat and ssl modules and networking interest area ................ r80692 | antoine.pitrou | 2010-05-01 13:29:38 -0700 (Sat, 01 May 2010) | 9 lines Merged revisions 80690 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r80690 | antoine.pitrou | 2010-05-01 22:26:58 +0200 (sam., 01 mai 2010) | 3 lines Remove duplicate test ........ ................ r80694 | victor.stinner | 2010-05-02 02:37:08 -0700 (Sun, 02 May 2010) | 3 lines Issue #8533: Write tracebacks and failed tests to sys.stderr instead of sys.stdout to avoid UnicodeEncodeError (use backslashreplace error handler) ................ r80697 | mark.dickinson | 2010-05-02 02:40:10 -0700 (Sun, 02 May 2010) | 8 lines Blocked revisions 80695 via svnmerge ........ r80695 | mark.dickinson | 2010-05-02 10:38:43 +0100 (Sun, 02 May 2010) | 2 lines Improve error message from nb_int returning a non-integer, in various PyInt_As* functions: ........ ................ r80699 | ronald.oussoren | 2010-05-02 02:54:35 -0700 (Sun, 02 May 2010) | 10 lines Merged revisions 80698 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r80698 | ronald.oussoren | 2010-05-02 11:48:21 +0200 (Sun, 02 May 2010) | 3 lines For for issue #7192: with this patch webbrowser.get("firefox") works on OSX ........ ................ r80703 | victor.stinner | 2010-05-02 10:24:51 -0700 (Sun, 02 May 2010) | 4 lines Issue #8533: revert r80694; try a different fix: regrtest uses backslashreplace error handler for stdout to avoid UnicodeEncodeError (write non-ASCII character to stdout using ASCII encoding) ................ r80705 | antoine.pitrou | 2010-05-02 12:59:47 -0700 (Sun, 02 May 2010) | 10 lines Merged revisions 80704 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r80704 | antoine.pitrou | 2010-05-02 21:51:14 +0200 (dim., 02 mai 2010) | 4 lines Issue #4687: Fix accuracy of garbage collection runtimes displayed with gc.DEBUG_STATS. ........ ................ r80709 | michael.foord | 2010-05-02 14:00:22 -0700 (Sun, 02 May 2010) | 9 lines Merged revisions 80708 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r80708 | michael.foord | 2010-05-02 21:39:42 +0100 (Sun, 02 May 2010) | 1 line Fix unittest tests to not abuse traceback.format_exception ........ ................ r80714 | antoine.pitrou | 2010-05-03 08:57:23 -0700 (Mon, 03 May 2010) | 3 lines Issue #8593: Fix, reorder and improve the documentation for argument parsing ................ r80718 | jesus.cea | 2010-05-03 09:14:58 -0700 (Mon, 03 May 2010) | 9 lines Merged revisions 80716 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r80716 | jesus.cea | 2010-05-03 18:09:21 +0200 (Mon, 03 May 2010) | 1 line wbits negative was documented SEVEN years ago ........ ................ r80722 | antoine.pitrou | 2010-05-03 09:48:20 -0700 (Mon, 03 May 2010) | 11 lines Merged revisions 80720 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r80720 | antoine.pitrou | 2010-05-03 18:25:33 +0200 (lun., 03 mai 2010) | 5 lines Issue #7865: The close() method of :mod:`io` objects should not swallow exceptions raised by the implicit flush(). Also ensure that calling close() several times is supported. Patch by Pascal Chambon. ........ ................ r80724 | jeffrey.yasskin | 2010-05-03 12:29:34 -0700 (Mon, 03 May 2010) | 19 lines Make (most of) Python's tests pass under Thread Sanitizer. http://code.google.com/p/data-race-test/wiki/ThreadSanitizer is a dynamic data race detector that runs on top of valgrind. With this patch, the binaries at http://code.google.com/p/data-race-test/wiki/ThreadSanitizer#Binaries pass many but not all of the Python tests. All of regrtest still passes outside of tsan. I've implemented part of the C1x atomic types so that we can explicitly mark variables that are used across threads, and get defined behavior as compilers advance. I've added tsan's client header and implementation to the codebase in dynamic_annotations.{h,c} (docs at http://code.google.com/p/data-race-test/wiki/DynamicAnnotations). Unfortunately, I haven't been able to get helgrind and drd to give sensible error messages, even when I use their client annotations, so I'm not supporting them. ................ r80726 | benjamin.peterson | 2010-05-03 13:55:22 -0700 (Mon, 03 May 2010) | 1 line set svn:eol-style to native ................ r80727 | benjamin.peterson | 2010-05-03 14:09:59 -0700 (Mon, 03 May 2010) | 1 line read eval_breaker with atomic api with computed gotos ................ r80728 | jesus.cea | 2010-05-03 14:18:48 -0700 (Mon, 03 May 2010) | 1 line Deprecate OSF* support ................ Added: python/branches/py3k-jit/Include/dynamic_annotations.h - copied unchanged from r80728, /python/branches/py3k/Include/dynamic_annotations.h python/branches/py3k-jit/Include/pyatomic.h - copied unchanged from r80728, /python/branches/py3k/Include/pyatomic.h python/branches/py3k-jit/Python/dynamic_annotations.c - copied unchanged from r80728, /python/branches/py3k/Python/dynamic_annotations.c Modified: python/branches/py3k-jit/ (props changed) python/branches/py3k-jit/Doc/about.rst python/branches/py3k-jit/Doc/bugs.rst python/branches/py3k-jit/Doc/c-api/arg.rst python/branches/py3k-jit/Doc/documenting/index.rst python/branches/py3k-jit/Doc/documenting/style.rst python/branches/py3k-jit/Doc/howto/doanddont.rst python/branches/py3k-jit/Doc/library/argparse.rst python/branches/py3k-jit/Doc/library/asynchat.rst python/branches/py3k-jit/Doc/library/http.client.rst python/branches/py3k-jit/Doc/library/http.cookiejar.rst python/branches/py3k-jit/Doc/library/io.rst python/branches/py3k-jit/Doc/library/shutil.rst python/branches/py3k-jit/Doc/library/stdtypes.rst python/branches/py3k-jit/Doc/library/sys.rst python/branches/py3k-jit/Doc/library/syslog.rst python/branches/py3k-jit/Doc/library/unittest.rst python/branches/py3k-jit/Doc/library/winreg.rst python/branches/py3k-jit/Doc/library/zlib.rst python/branches/py3k-jit/Doc/tools/sphinxext/indexsidebar.html python/branches/py3k-jit/Doc/tools/sphinxext/layout.html python/branches/py3k-jit/Include/Python.h python/branches/py3k-jit/Include/dictobject.h python/branches/py3k-jit/Include/modsupport.h python/branches/py3k-jit/Include/pystate.h python/branches/py3k-jit/Lib/_pyio.py python/branches/py3k-jit/Lib/compileall.py python/branches/py3k-jit/Lib/ctypes/test/test_errno.py python/branches/py3k-jit/Lib/http/client.py python/branches/py3k-jit/Lib/locale.py python/branches/py3k-jit/Lib/os.py python/branches/py3k-jit/Lib/shutil.py python/branches/py3k-jit/Lib/socketserver.py python/branches/py3k-jit/Lib/sqlite3/test/dbapi.py python/branches/py3k-jit/Lib/ssl.py python/branches/py3k-jit/Lib/subprocess.py python/branches/py3k-jit/Lib/tarfile.py python/branches/py3k-jit/Lib/test/fork_wait.py python/branches/py3k-jit/Lib/test/regrtest.py python/branches/py3k-jit/Lib/test/support.py python/branches/py3k-jit/Lib/test/test_asynchat.py python/branches/py3k-jit/Lib/test/test_asyncore.py python/branches/py3k-jit/Lib/test/test_bz2.py python/branches/py3k-jit/Lib/test/test_capi.py python/branches/py3k-jit/Lib/test/test_cmd.py python/branches/py3k-jit/Lib/test/test_compileall.py python/branches/py3k-jit/Lib/test/test_contextlib.py python/branches/py3k-jit/Lib/test/test_dict.py python/branches/py3k-jit/Lib/test/test_doctest.py python/branches/py3k-jit/Lib/test/test_docxmlrpc.py python/branches/py3k-jit/Lib/test/test_fork1.py python/branches/py3k-jit/Lib/test/test_ftplib.py python/branches/py3k-jit/Lib/test/test_gdb.py python/branches/py3k-jit/Lib/test/test_hashlib.py python/branches/py3k-jit/Lib/test/test_httplib.py python/branches/py3k-jit/Lib/test/test_httpservers.py python/branches/py3k-jit/Lib/test/test_io.py python/branches/py3k-jit/Lib/test/test_locale.py python/branches/py3k-jit/Lib/test/test_logging.py python/branches/py3k-jit/Lib/test/test_multiprocessing.py python/branches/py3k-jit/Lib/test/test_poplib.py python/branches/py3k-jit/Lib/test/test_queue.py python/branches/py3k-jit/Lib/test/test_shutil.py python/branches/py3k-jit/Lib/test/test_smtplib.py python/branches/py3k-jit/Lib/test/test_socket.py python/branches/py3k-jit/Lib/test/test_socketserver.py python/branches/py3k-jit/Lib/test/test_ssl.py python/branches/py3k-jit/Lib/test/test_subprocess.py python/branches/py3k-jit/Lib/test/test_sys.py python/branches/py3k-jit/Lib/test/test_tarfile.py python/branches/py3k-jit/Lib/test/test_telnetlib.py python/branches/py3k-jit/Lib/test/test_thread.py python/branches/py3k-jit/Lib/test/test_threaded_import.py python/branches/py3k-jit/Lib/test/test_threadedtempfile.py python/branches/py3k-jit/Lib/test/test_threading.py python/branches/py3k-jit/Lib/test/test_threading_local.py python/branches/py3k-jit/Lib/test/test_threadsignals.py python/branches/py3k-jit/Lib/test/test_urllib2_localnet.py python/branches/py3k-jit/Lib/test/test_urllibnet.py python/branches/py3k-jit/Lib/test/test_xmlrpc.py python/branches/py3k-jit/Lib/unittest/__init__.py python/branches/py3k-jit/Lib/unittest/result.py python/branches/py3k-jit/Lib/unittest/signals.py python/branches/py3k-jit/Lib/unittest/test/test_break.py python/branches/py3k-jit/Lib/unittest/test/test_result.py python/branches/py3k-jit/Lib/urllib/request.py python/branches/py3k-jit/Lib/webbrowser.py python/branches/py3k-jit/Mac/BuildScript/build-installer.py python/branches/py3k-jit/Mac/Makefile.in python/branches/py3k-jit/Mac/PythonLauncher/Makefile.in python/branches/py3k-jit/Mac/README python/branches/py3k-jit/Makefile.pre.in python/branches/py3k-jit/Misc/ACKS python/branches/py3k-jit/Misc/NEWS python/branches/py3k-jit/Misc/maintainers.rst python/branches/py3k-jit/Modules/_io/bufferedio.c python/branches/py3k-jit/Modules/_io/bytesio.c python/branches/py3k-jit/Modules/_io/iobase.c python/branches/py3k-jit/Modules/_io/textio.c python/branches/py3k-jit/Modules/_ssl.c python/branches/py3k-jit/Modules/bz2module.c python/branches/py3k-jit/Modules/gcmodule.c python/branches/py3k-jit/Modules/posixmodule.c python/branches/py3k-jit/Modules/socketmodule.c python/branches/py3k-jit/Modules/syslogmodule.c python/branches/py3k-jit/Objects/dictobject.c python/branches/py3k-jit/Objects/exceptions.c python/branches/py3k-jit/Objects/fileobject.c python/branches/py3k-jit/Objects/unicodeobject.c python/branches/py3k-jit/PC/VS7.1/pythoncore.vcproj python/branches/py3k-jit/PC/VS8.0/pythoncore.vcproj python/branches/py3k-jit/PC/_subprocess.c python/branches/py3k-jit/PC/os2emx/Makefile python/branches/py3k-jit/PCbuild/pythoncore.vcproj python/branches/py3k-jit/Parser/tokenizer.c python/branches/py3k-jit/Python/ceval.c python/branches/py3k-jit/Python/ceval_gil.h python/branches/py3k-jit/Python/getargs.c python/branches/py3k-jit/Python/pystate.c python/branches/py3k-jit/Python/sysmodule.c python/branches/py3k-jit/Python/thread_pthread.h python/branches/py3k-jit/configure python/branches/py3k-jit/configure.in python/branches/py3k-jit/pyconfig.h.in Modified: python/branches/py3k-jit/Doc/about.rst ============================================================================== --- python/branches/py3k-jit/Doc/about.rst (original) +++ python/branches/py3k-jit/Doc/about.rst Tue May 4 01:24:51 2010 @@ -3,9 +3,11 @@ ===================== -These documents are generated from `reStructuredText -`_ sources by *Sphinx*, a document processor -specifically written for the Python documentation. +These documents are generated from `reStructuredText`_ sources by `Sphinx`_, a +document processor specifically written for the Python documentation. + +.. _reStructuredText: http://docutils.sf.net/rst.html +.. _Sphinx: http://sphinx.pocoo.org/ .. In the online version of these documents, you can submit comments and suggest changes directly on the documentation pages. Modified: python/branches/py3k-jit/Doc/bugs.rst ============================================================================== --- python/branches/py3k-jit/Doc/bugs.rst (original) +++ python/branches/py3k-jit/Doc/bugs.rst Tue May 4 01:24:51 2010 @@ -1,14 +1,32 @@ .. _reporting-bugs: -************************ -Reporting Bugs in Python -************************ +************** +Reporting Bugs +************** Python is a mature programming language which has established a reputation for stability. In order to maintain this reputation, the developers would like to know of any deficiencies you find in Python. -Bug reports should be submitted via the Python Bug Tracker + +Documentation bugs +================== + +If you find a bug in this documentation or would like to propose an improvement, +please send an e-mail to docs at python.org describing the bug and where you found +it. If you have a suggestion how to fix it, include that as well. + +docs at python.org is a mailing list run by volunteers; your request will be +noticed, even if it takes a while to be processed. + +Of course, if you want a more persistent record of your issue, you can use the +issue tracker for documentation bugs as well. + + +Using the Python issue tracker +============================== + +Bug reports for Python itself should be submitted via the Python Bug Tracker (http://bugs.python.org/). The bug tracker offers a Web form which allows pertinent information to be entered and submitted to the developers. @@ -19,9 +37,6 @@ information is needed (in which case you are welcome to provide it if you can!). To do this, search the bug database using the search box on the top of the page. -In the case of documentation bugs, look at the most recent development docs at -http://docs.python.org/dev to see if the bug has been fixed. - If the problem you're reporting is not already in the bug tracker, go back to the Python Bug Tracker and log in. If you don't already have a tracker account, select the "Register" link or, if you use OpenID, one of the OpenID provider Modified: python/branches/py3k-jit/Doc/c-api/arg.rst ============================================================================== --- python/branches/py3k-jit/Doc/c-api/arg.rst (original) +++ python/branches/py3k-jit/Doc/c-api/arg.rst Tue May 4 01:24:51 2010 @@ -14,6 +14,10 @@ strings* which are used to tell the function about the expected arguments. The format strings use the same syntax for each of these functions. +----------------- +Parsing arguments +----------------- + A format string consists of zero or more "format units." A format unit describes one Python object; it is usually a single character or a parenthesized sequence of format units. With a few exceptions, a format unit that is not a @@ -23,75 +27,108 @@ the format unit; and the entry in [square] brackets is the type of the C variable(s) whose address should be passed. -``s`` (string or Unicode object) [const char \*] - Convert a Python string or Unicode object to a C pointer to a character string. - You must not provide storage for the string itself; a pointer to an existing - string is stored into the character pointer variable whose address you pass. - The C string is NUL-terminated. The Python string must not contain embedded NUL - bytes; if it does, a :exc:`TypeError` exception is raised. Unicode objects are - converted to C strings using the default encoding. If this conversion fails, a - :exc:`UnicodeError` is raised. - - Starting with Python 2.5 the type of the length argument can be - controlled by defining the macro :cmacro:`PY_SSIZE_T_CLEAN` before - including :file:`Python.h`. If the macro is defined, length is a - :ctype:`Py_ssize_t` rather than an int. - -``s*`` (string, Unicode, or any buffer compatible object) [Py_buffer] - This is similar to ``s``, but the code fills a :ctype:`Py_buffer` structure - provided by the caller. In this case the Python string may contain embedded - null bytes. Unicode objects pass back a pointer to the default encoded - string version of the object if such a conversion is possible. The - underlying buffer is locked, so that the caller can subsequently use the - buffer even inside a ``Py_BEGIN_ALLOW_THREADS`` block. **The caller is - responsible** for calling ``PyBuffer_Release`` with the structure after it - has processed the data. - -``s#`` (string, Unicode or any read buffer compatible object) [const char \*, int or :ctype:`Py_ssize_t`] - This variant on ``s`` stores into two C variables, the first one a pointer to - a character string, the second one its length. In this case the Python - string may contain embedded null bytes. Unicode objects pass back a pointer - to the default encoded string version of the object if such a conversion is - possible. All other read-buffer compatible objects pass back a reference to - the raw internal data representation. Since this format doesn't allow - writable buffer compatible objects like byte arrays, ``s*`` is to be - preferred. +Strings and buffers +------------------- - The type of the length argument (int or :ctype:`Py_ssize_t`) is controlled by +These formats do not expect you to provide raw storage for the returned string +or bytes. Also, you won't have to release any memory yourself, except with +the ``es``, ``es#``, ``et`` and ``et#`` formats. + +However, when a :ctype:`Py_buffer` structure gets filled, the underlying +buffer is locked so that the caller can subsequently use the buffer even +inside a ``Py_BEGIN_ALLOW_THREADS`` block without the risk of mutable data +being resized or destroyed. As a result, **you have to call** +:cfunc:`PyBuffer_Release` after you have finished processing the data (or +in any early abort case). + +Unless otherwise stated, buffers are not NUL-terminated. + +.. note:: + For all ``#`` variants of formats (``s#``, ``y#``, etc.), the type of + the length argument (int or :ctype:`Py_ssize_t`) is controlled by defining the macro :cmacro:`PY_SSIZE_T_CLEAN` before including - :file:`Python.h`. If the macro was defined, length is a :ctype:`Py_ssize_t` - rather than an int. This behavior will change in a future Python version to - only support :ctype:`Py_ssize_t` and drop int support. It is best to always - define :cmacro:`PY_SSIZE_T_CLEAN`. + :file:`Python.h`. If the macro was defined, length is a + :ctype:`Py_ssize_t` rather than an int. This behavior will change + in a future Python version to only support :ctype:`Py_ssize_t` and + drop int support. It is best to always define :cmacro:`PY_SSIZE_T_CLEAN`. -``y`` (bytes object) [const char \*] - This variant on ``s`` converts a Python bytes or bytearray object to a C - pointer to a character string. The bytes object must not contain embedded - NUL bytes; if it does, a :exc:`TypeError` exception is raised. -``y*`` (bytes object) [Py_buffer \*] - This is to ``s*`` as ``y`` is to ``s``. +``s`` (Unicode object) [const char \*] + Convert a Unicode object to a C pointer to a character string. + A pointer to an existing string is stored in the character pointer + variable whose address you pass. The C string is NUL-terminated. + The Python string must not contain embedded NUL bytes; if it does, + a :exc:`TypeError` exception is raised. Unicode objects are converted + to C strings using the default encoding. If this conversion fails, a + :exc:`UnicodeError` is raised. -``y#`` (bytes object) [const char \*, int] - This variant on ``s#`` stores into two C variables, the first one a pointer - to a character string, the second one its length. This only accepts bytes - objects, no byte arrays. + .. note:: + This format does not accept bytes-like objects. If you want to accept + filesystem paths and convert them to C character strings, it is + preferrable to use the ``O&`` format with :cfunc:`PyUnicode_FSConverter` + as *converter*. + +``s*`` (Unicode object or any buffer compatible object) [Py_buffer] + This format accepts Unicode objects as well as objects supporting the + buffer protocol (such as :class:`bytes` or :class:`bytearray` objects). + It fills a :ctype:`Py_buffer` structure provided by the caller. + Unicode objects are converted to C strings using the default encoding. + In this case the resulting C string may contain embedded NUL bytes. + +``s#`` (string, Unicode or any read buffer compatible object) [const char \*, int or :ctype:`Py_ssize_t`] + Like ``s*``, except that it doesn't accept mutable buffer-like objects + such as :class:`bytearray`. The result is stored into two C variables, + the first one a pointer to a C string, the second one its length. + The string may contain embedded null bytes. -``z`` (string or ``None``) [const char \*] +``z`` (Unicode object or ``None``) [const char \*] Like ``s``, but the Python object may also be ``None``, in which case the C pointer is set to *NULL*. -``z*`` (string or ``None`` or any buffer compatible object) [Py_buffer] - This is to ``s*`` as ``z`` is to ``s``. +``z*`` (Unicode object or ``None`` or any buffer compatible object) [Py_buffer] + Like ``s*``, but the Python object may also be ``None``, in which case the + ``buf`` member of the :ctype:`Py_buffer` structure is set to *NULL*. -``z#`` (string or ``None`` or any read buffer compatible object) [const char \*, int] - This is to ``s#`` as ``z`` is to ``s``. +``z#`` (Unicode object or ``None`` or any read buffer compatible object) [const char \*, int] + Like ``s#``, but the Python object may also be ``None``, in which case the C + pointer is set to *NULL*. + +``y`` (bytes object) [const char \*] + This format converts a bytes-like object to a C pointer to a character + string; it does not accept Unicode objects. The bytes buffer must not + contain embedded NUL bytes; if it does, a :exc:`TypeError` + exception is raised. + +``y*`` (any buffer compatible object) [Py_buffer \*] + This variant on ``s*`` doesn't accept Unicode objects, only objects + supporting the buffer protocol. **This is the recommended way to accept + binary data.** + +``y#`` (bytes object) [const char \*, int] + This variant on ``s#`` doesn't accept Unicode objects, only bytes-like + objects. + +``S`` (bytes object) [PyBytesObject \*] + Requires that the Python object is a :class:`bytes` object, without + attempting any conversion. Raises :exc:`TypeError` if the object is not + a bytes object. The C variable may also be declared as :ctype:`PyObject\*`. + +``Y`` (bytearray object) [PyByteArrayObject \*] + Requires that the Python object is a :class:`bytearray` object, without + attempting any conversion. Raises :exc:`TypeError` if the object is not + a bytearray object. The C variable may also be declared as :ctype:`PyObject\*`. ``u`` (Unicode object) [Py_UNICODE \*] Convert a Python Unicode object to a C pointer to a NUL-terminated buffer of - 16-bit Unicode (UTF-16) data. As with ``s``, there is no need to provide - storage for the Unicode data buffer; a pointer to the existing Unicode data is - stored into the :ctype:`Py_UNICODE` pointer variable whose address you pass. + Unicode characters. You must pass the address of a :ctype:`Py_UNICODE` + pointer variable, which will be filled with the pointer to an existing + Unicode buffer. Please note that the width of a :ctype:`Py_UNICODE` + character depends on compilation options (it is either 16 or 32 bits). + + ..note :: + Since ``u`` doesn't give you back the length of the string, and it + may contain embedded NUL characters, it is recommended to use ``u#`` + or ``U`` instead. ``u#`` (Unicode object) [Py_UNICODE \*, int] This variant on ``u`` stores into two C variables, the first one a pointer to a @@ -100,11 +137,40 @@ array. ``Z`` (Unicode or ``None``) [Py_UNICODE \*] - Like ``s``, but the Python object may also be ``None``, in which case the C - pointer is set to *NULL*. + Like ``u``, but the Python object may also be ``None``, in which case the + :ctype:`Py_UNICODE` pointer is set to *NULL*. ``Z#`` (Unicode or ``None``) [Py_UNICODE \*, int] - This is to ``u#`` as ``Z`` is to ``u``. + Like ``u#``, but the Python object may also be ``None``, in which case the + :ctype:`Py_UNICODE` pointer is set to *NULL*. + +``U`` (Unicode object) [PyUnicodeObject \*] + Requires that the Python object is a Unicode object, without attempting + any conversion. Raises :exc:`TypeError` if the object is not a Unicode + object. The C variable may also be declared as :ctype:`PyObject\*`. + +``t#`` (read-only character buffer) [char \*, int] + Like ``s#``, but accepts any object which implements the read-only buffer + interface. The :ctype:`char\*` variable is set to point to the first byte of + the buffer, and the :ctype:`int` is set to the length of the buffer. Only + single-segment buffer objects are accepted; :exc:`TypeError` is raised for all + others. + +``w`` (read-write character buffer) [char \*] + Similar to ``s``, but accepts any object which implements the read-write buffer + interface. The caller must determine the length of the buffer by other means, + or use ``w#`` instead. Only single-segment buffer objects are accepted; + :exc:`TypeError` is raised for all others. + +``w*`` (read-write byte-oriented buffer) [Py_buffer] + This is to ``w`` what ``s*`` is to ``s``. + +``w#`` (read-write character buffer) [char \*, int] + Like ``s#``, but accepts any object which implements the read-write buffer + interface. The :ctype:`char \*` variable is set to point to the first byte + of the buffer, and the :ctype:`int` is set to the length of the buffer. + Only single-segment buffer objects are accepted; :exc:`TypeError` is raised + for all others. ``es`` (string, Unicode object or character buffer compatible object) [const char \*encoding, char \*\*buffer] This variant on ``s`` is used for encoding Unicode and objects convertible to @@ -165,6 +231,9 @@ them. Instead, the implementation assumes that the string object uses the encoding passed in as parameter. +Numbers +------- + ``b`` (integer) [unsigned char] Convert a nonnegative Python integer to an unsigned tiny int, stored in a C :ctype:`unsigned char`. @@ -207,13 +276,13 @@ ``n`` (integer) [Py_ssize_t] Convert a Python integer to a C :ctype:`Py_ssize_t`. -``c`` (string of length 1) [char] - Convert a Python character, represented as a byte string of length 1, to a C - :ctype:`char`. - -``C`` (string of length 1) [int] - Convert a Python character, represented as a unicode string of length 1, to a - C :ctype:`int`. +``c`` (bytes object of length 1) [char] + Convert a Python byte, represented as a :class:`bytes` object of length 1, + to a C :ctype:`char`. + +``C`` (Unicode object of length 1) [int] + Convert a Python character, represented as a :class:`str`: object of + length 1, to a C :ctype:`int`. ``f`` (float) [float] Convert a Python floating point number to a C :ctype:`float`. @@ -224,6 +293,9 @@ ``D`` (complex) [Py_complex] Convert a Python complex number to a C :ctype:`Py_complex` structure. +Other objects +------------- + ``O`` (object) [PyObject \*] Store a Python object (without any conversion) in a C object pointer. The C program thus receives the actual object that was passed. The object's reference @@ -258,39 +330,6 @@ .. versionchanged:: 3.1 Py_CLEANUP_SUPPORTED was added. -``S`` (string) [PyStringObject \*] - Like ``O`` but requires that the Python object is a string object. Raises - :exc:`TypeError` if the object is not a string object. The C variable may also - be declared as :ctype:`PyObject\*`. - -``U`` (Unicode string) [PyUnicodeObject \*] - Like ``O`` but requires that the Python object is a Unicode object. Raises - :exc:`TypeError` if the object is not a Unicode object. The C variable may also - be declared as :ctype:`PyObject\*`. - -``t#`` (read-only character buffer) [char \*, int] - Like ``s#``, but accepts any object which implements the read-only buffer - interface. The :ctype:`char\*` variable is set to point to the first byte of - the buffer, and the :ctype:`int` is set to the length of the buffer. Only - single-segment buffer objects are accepted; :exc:`TypeError` is raised for all - others. - -``w`` (read-write character buffer) [char \*] - Similar to ``s``, but accepts any object which implements the read-write buffer - interface. The caller must determine the length of the buffer by other means, - or use ``w#`` instead. Only single-segment buffer objects are accepted; - :exc:`TypeError` is raised for all others. - -``w*`` (read-write byte-oriented buffer) [Py_buffer] - This is to ``w`` what ``s*`` is to ``s``. - -``w#`` (read-write character buffer) [char \*, int] - Like ``s#``, but accepts any object which implements the read-write buffer - interface. The :ctype:`char \*` variable is set to point to the first byte - of the buffer, and the :ctype:`int` is set to the length of the buffer. - Only single-segment buffer objects are accepted; :exc:`TypeError` is raised - for all others. - ``(items)`` (tuple) [*matching-items*] The object must be a Python sequence whose length is the number of format units in *items*. The C arguments must correspond to the individual format units in @@ -339,6 +378,8 @@ of the format units, the variables at the addresses corresponding to that and the following format units are left untouched. +API Functions +------------- .. cfunction:: int PyArg_ParseTuple(PyObject *args, const char *format, ...) @@ -366,6 +407,15 @@ va_list rather than a variable number of arguments. +.. cfunction:: int PyArg_ValidateKeywordArguments(PyObject *) + + Ensure that the keys in the keywords argument dictionary are strings. This + is only needed if :cfunc:`PyArg_ParseTupleAndKeywords` is not used, since the + latter already does this check. + + .. versionadded:: 3.2 + + .. XXX deprecated, will be removed .. cfunction:: int PyArg_Parse(PyObject *args, const char *format, ...) @@ -415,6 +465,10 @@ PyArg_ParseTuple(args, "O|O:ref", &object, &callback) +--------------- +Building values +--------------- + .. cfunction:: PyObject* Py_BuildValue(const char *format, ...) Create a new value based on a format string similar to those accepted by the Modified: python/branches/py3k-jit/Doc/documenting/index.rst ============================================================================== --- python/branches/py3k-jit/Doc/documenting/index.rst (original) +++ python/branches/py3k-jit/Doc/documenting/index.rst Tue May 4 01:24:51 2010 @@ -18,12 +18,17 @@ .. _docutils: http://docutils.sf.net/ .. _Sphinx: http://sphinx.pocoo.org/ -If you're interested in contributing to Python's documentation, there's no need -to write reStructuredText if you're not so inclined; plain text contributions -are more than welcome as well. +.. note:: + + If you're interested in contributing to Python's documentation, there's no + need to write reStructuredText if you're not so inclined; plain text + contributions are more than welcome as well. Send an e-mail to + docs at python.org or open an issue on the :ref:`tracker `. + .. toctree:: :numbered: + :maxdepth: 1 intro.rst style.rst Modified: python/branches/py3k-jit/Doc/documenting/style.rst ============================================================================== --- python/branches/py3k-jit/Doc/documenting/style.rst (original) +++ python/branches/py3k-jit/Doc/documenting/style.rst Tue May 4 01:24:51 2010 @@ -66,5 +66,5 @@ 1970s. -.. _Apple Publications Style Guide: http://developer.apple.com/documentation/UserExperience/Conceptual/APStyleGuide/APSG_2008.pdf +.. _Apple Publications Style Guide: http://developer.apple.com/mac/library/documentation/UserExperience/Conceptual/APStyleGuide/APSG_2009.pdf Modified: python/branches/py3k-jit/Doc/howto/doanddont.rst ============================================================================== --- python/branches/py3k-jit/Doc/howto/doanddont.rst (original) +++ python/branches/py3k-jit/Doc/howto/doanddont.rst Tue May 4 01:24:51 2010 @@ -199,11 +199,8 @@ and perhaps not at all in non-C implementations (e.g., Jython). :: def get_status(file): - fp = open(file) - try: + with open(file) as fp: return fp.readline() - finally: - fp.close() Using the Batteries Modified: python/branches/py3k-jit/Doc/library/argparse.rst ============================================================================== --- python/branches/py3k-jit/Doc/library/argparse.rst (original) +++ python/branches/py3k-jit/Doc/library/argparse.rst Tue May 4 01:24:51 2010 @@ -1700,7 +1700,7 @@ Originally, the argparse module had attempted to maintain compatibility with optparse. However, optparse was difficult to extend transparently, particularly with the changes required to support the new ``nargs=`` specifiers and better -usage messges. When most everything in optparse had either been copy-pasted +usage messages. When most everything in optparse had either been copy-pasted over or monkey-patched, it no longer seemed practical to try to maintain the backwards compatibility. Modified: python/branches/py3k-jit/Doc/library/asynchat.rst ============================================================================== --- python/branches/py3k-jit/Doc/library/asynchat.rst (original) +++ python/branches/py3k-jit/Doc/library/asynchat.rst Tue May 4 01:24:51 2010 @@ -80,12 +80,6 @@ :exc:`NotImplementedError` exception. -.. method:: async_chat._collect_incoming_data(data) - - Sample implementation of a data collection rutine to be used in conjunction - with :meth:`_get_data` in a user-specified :meth:`found_terminator`. - - .. method:: async_chat.discard_buffers() In emergencies this method will discard any data held in the input and/or @@ -100,49 +94,17 @@ should be available via an instance attribute. -.. method:: async_chat._get_data() - - Will return and clear the data received with the sample - :meth:`_collect_incoming_data` implementation. - - .. method:: async_chat.get_terminator() Returns the current terminator for the channel. -.. method:: async_chat.handle_close() - - Called when the channel is closed. The default method silently closes the - channel's socket. - - -.. method:: async_chat.handle_read() - - Called when a read event fires on the channel's socket in the asynchronous - loop. The default method checks for the termination condition established - by :meth:`set_terminator`, which can be either the appearance of a - particular string in the input stream or the receipt of a particular number - of characters. When the terminator is found, :meth:`handle_read` calls the - :meth:`found_terminator` method after calling :meth:`collect_incoming_data` - with any data preceding the terminating condition. - - -.. method:: async_chat.handle_write() - - Called when the application may write data to the channel. The default - method calls the :meth:`initiate_send` method, which in turn will call - :meth:`refill_buffer` to collect data from the producer fifo associated - with the channel. - - .. method:: async_chat.push(data) - Creates a :class:`simple_producer` object (*see below*) containing the data - and pushes it on to the channel's ``producer_fifo`` to ensure its - transmission. This is all you need to do to have the channel write the - data out to the network, although it is possible to use your own producers - in more complex schemes to implement encryption and chunking, for example. + Pushes data on to the channel's fifo to ensure its transmission. + This is all you need to do to have the channel write the data out to the + network, although it is possible to use your own producers in more complex + schemes to implement encryption and chunking, for example. .. method:: async_chat.push_with_producer(producer) @@ -153,20 +115,6 @@ method and send the data to the remote endpoint. -.. method:: async_chat.readable() - - Should return ``True`` for the channel to be included in the set of - channels tested by the :cfunc:`select` loop for readability. - - -.. method:: async_chat.refill_buffer() - - Refills the output buffer by calling the :meth:`more` method of the - producer at the head of the fifo. If it is exhausted then the producer is - popped off the fifo and the next producer is activated. If the current - producer is, or becomes, ``None`` then the channel is closed. - - .. method:: async_chat.set_terminator(term) Sets the terminating condition to be recognized on the channel. ``term`` @@ -191,36 +139,16 @@ by the channel after :meth:`found_terminator` is called. -.. method:: async_chat.writable() - - Should return ``True`` as long as items remain on the producer fifo, or the - channel is connected and the channel's output buffer is non-empty. - - -asynchat - Auxiliary Classes and Functions +asynchat - Auxiliary Classes ------------------------------------------ - -.. class:: simple_producer(data, buffer_size=512) - - A :class:`simple_producer` takes a chunk of data and an optional buffer - size. Repeated calls to its :meth:`more` method yield successive chunks of - the data no larger than *buffer_size*. - - - .. method:: more() - - Produces the next chunk of information from the producer, or returns the - empty string. - - .. class:: fifo(list=None) - Each channel maintains a :class:`fifo` holding data which has been pushed - by the application but not yet popped for writing to the channel. A - :class:`fifo` is a list used to hold data and/or producers until they are - required. If the *list* argument is provided then it should contain - producers or data items to be written to the channel. + A :class:`fifo` holding data which has been pushed by the application but + not yet popped for writing to the channel. A :class:`fifo` is a list used + to hold data and/or producers until they are required. If the *list* + argument is provided then it should contain producers or data items to be + written to the channel. .. method:: is_empty() @@ -244,15 +172,6 @@ If the fifo is not empty, returns ``True, first()``, deleting the popped item. Returns ``False, None`` for an empty fifo. -The :mod:`asynchat` module also defines one utility function, which may be of -use in network and textual analysis operations. - - -.. function:: find_prefix_at_end(haystack, needle) - - Returns ``True`` if string *haystack* ends with any non-empty prefix of - string *needle*. - .. _asynchat-example: Modified: python/branches/py3k-jit/Doc/library/http.client.rst ============================================================================== --- python/branches/py3k-jit/Doc/library/http.client.rst (original) +++ python/branches/py3k-jit/Doc/library/http.client.rst Tue May 4 01:24:51 2010 @@ -521,6 +521,22 @@ >>> data2 = r2.read() >>> conn.close() +Here is an example session that uses ``HEAD`` method. Note that ``HEAD`` method +never returns any data. :: + + + >>> import http.client + >>> conn = http.client.HTTPConnection("www.python.org") + >>> conn.request("HEAD","/index.html") + >>> res = conn.getresponse() + >>> print(res.status, res.reason) + 200 OK + >>> data = res.read() + >>> print(len(data)) + 0 + >>> data == b'' + True + Here is an example session that shows how to ``POST`` requests:: >>> import http.client, urllib.parse Modified: python/branches/py3k-jit/Doc/library/http.cookiejar.rst ============================================================================== --- python/branches/py3k-jit/Doc/library/http.cookiejar.rst (original) +++ python/branches/py3k-jit/Doc/library/http.cookiejar.rst Tue May 4 01:24:51 2010 @@ -108,7 +108,7 @@ :mod:`http.cookiejar` and :mod:`http.cookies` modules do not depend on each other. - http://wwwsearch.sf.net/ClientCookie/ + http://wwwsearch.sourceforge.net/mechanize/ Extensions to this module, including a class for reading Microsoft Internet Explorer cookies on Windows. @@ -295,7 +295,7 @@ The following :class:`CookieJar` subclasses are provided for reading and writing . Further :class:`CookieJar` subclasses, including one that reads Microsoft Internet Explorer cookies, are available at -http://wwwsearch.sf.net/ClientCookie/. +http://wwwsearch.sourceforge.net/mechanize/. .. class:: MozillaCookieJar(filename, delayload=None, policy=None) Modified: python/branches/py3k-jit/Doc/library/io.rst ============================================================================== --- python/branches/py3k-jit/Doc/library/io.rst (original) +++ python/branches/py3k-jit/Doc/library/io.rst Tue May 4 01:24:51 2010 @@ -56,7 +56,7 @@ classes. :func:`.open` uses the file's blksize (as obtained by :func:`os.stat`) if possible. -.. function:: open(file, mode='r', buffering=None, encoding=None, errors=None, newline=None, closefd=True) +.. function:: open(file, mode='r', buffering=-1, encoding=None, errors=None, newline=None, closefd=True) Open *file* and return a corresponding stream. If the file cannot be opened, an :exc:`IOError` is raised. @@ -240,8 +240,10 @@ Flush and close this stream. This method has no effect if the file is already closed. Once the file is closed, any operation on the file - (e.g. reading or writing) will raise an :exc:`IOError`. The internal - file descriptor isn't closed if *closefd* was False. + (e.g. reading or writing) will raise an :exc:`ValueError`. + + As a convenience, it is allowed to call this method more than once; + only the first call, however, will have an effect. .. attribute:: closed @@ -313,7 +315,9 @@ .. method:: truncate(size=None) Truncate the file to at most *size* bytes. *size* defaults to the current - file position, as returned by :meth:`tell`. + file position, as returned by :meth:`tell`. Note that the current file + position isn't changed; if you want to change it to the new end of + file, you have to :meth:`seek()` explicitly. .. method:: writable() @@ -522,11 +526,6 @@ In :class:`BytesIO`, this is the same as :meth:`read`. - .. method:: truncate([size]) - - Truncate the buffer to at most *size* bytes. *size* defaults to the - current stream position, as returned by :meth:`tell`. - .. class:: BufferedReader(raw, buffer_size=DEFAULT_BUFFER_SIZE) Modified: python/branches/py3k-jit/Doc/library/shutil.rst ============================================================================== --- python/branches/py3k-jit/Doc/library/shutil.rst (original) +++ python/branches/py3k-jit/Doc/library/shutil.rst Tue May 4 01:24:51 2010 @@ -103,7 +103,8 @@ exist, a exception will be added in the list of errors raised in a :exc:`Error` exception at the end of the copy process. You can set the optional *ignore_dangling_symlinks* flag to true if you - want to silence this exception. + want to silence this exception. Notice that this option has no effect + on platforms that don't support :func:`os.symlink`. If *ignore* is given, it must be a callable that will receive as its arguments the directory being visited by :func:`copytree`, and a list of its @@ -237,7 +238,7 @@ *base_name* is the name of the file to create, including the path, minus any format-specific extension. *format* is the archive format: one of - "zip", "tar", "bztar" or "gztar". + "zip", "tar", "bztar" (if the :mod:`bz2` module is available) or "gztar". *root_dir* is a directory that will be the root directory of the archive; i.e. we typically chdir into *root_dir* before creating the @@ -263,7 +264,7 @@ By default :mod:`shutil` provides these formats: - *gztar*: gzip'ed tar-file - - *bztar*: bzip2'ed tar-file + - *bztar*: bzip2'ed tar-file (if the :mod:`bz2` module is available.) - *tar*: uncompressed tar file - *zip*: ZIP file @@ -287,13 +288,75 @@ .. versionadded:: 3.2 -.. function:: unregister_archive_format(name) +.. function:: unregister_archive_format(name) Remove the archive format *name* from the list of supported formats. .. versionadded:: 3.2 +.. function:: unpack_archive(filename[, extract_dir[, format]]) + + Unpack an archive. *filename* is the full path of the archive. + + *extract_dir* is the name of the target directory where the archive is + unpacked. If not provided, the current working directory is used. + + *format* is the archive format: one of "zip", "tar", or "gztar". Or any + other format registered with :func:`register_unpack_format`. If not + provided, :func:`unpack_archive` will use the archive file name extension + and see if an unpacker was registered for that extension. In case none is + found, a :exc:`ValueError` is raised. + + .. versionadded:: 3.2 + + +.. function:: register_unpack_format(name, extensions, function[, extra_args[,description]]) + + Registers an unpack format. *name* is the name of the format and + *extensions* is a list of extensions corresponding to the format, like + ``.zip`` for Zip files. + + *function* is the callable that will be used to unpack archives. The + callable will receive the path of the archive, followed by the directory + the archive must be extracted to. + + When provided, *extra_args* is a sequence of ``(name, value)`` tuples that + will be passed as keywords arguments to the callable. + + *description* can be provided to describe the format, and will be returned + by the :func:`get_unpack_formats` function. + + .. versionadded:: 3.2 + + +.. function:: unregister_unpack_format(name) + + Unregister an unpack format. *name* is the name of the format. + + .. versionadded:: 3.2 + + +.. function:: get_unpack_formats() + + Return a list of all registered formats for unpacking. + Each element of the returned sequence is a tuple + ``(name, extensions, description)``. + + By default :mod:`shutil` provides these formats: + + - *gztar*: gzip'ed tar-file + - *bztar*: bzip2'ed tar-file (if the :mod:`bz2` module is available.) + - *tar*: uncompressed tar file + - *zip*: ZIP file + + You can register new formats or provide your own unpacker for any existing + formats, by using :func:`register_unpack_format`. + + .. versionadded:: 3.2 + + + Archiving example ::::::::::::::::: Modified: python/branches/py3k-jit/Doc/library/stdtypes.rst ============================================================================== --- python/branches/py3k-jit/Doc/library/stdtypes.rst (original) +++ python/branches/py3k-jit/Doc/library/stdtypes.rst Tue May 4 01:24:51 2010 @@ -912,10 +912,10 @@ .. method:: str.find(sub[, start[, end]]) - Return the lowest index in the string where substring *sub* is found, such that - *sub* is contained in the range [*start*, *end*]. Optional arguments *start* - and *end* are interpreted as in slice notation. Return ``-1`` if *sub* is not - found. + Return the lowest index in the string where substring *sub* is found, such + that *sub* is contained in the slice ``s[start:end]``. Optional arguments + *start* and *end* are interpreted as in slice notation. Return ``-1`` if + *sub* is not found. .. method:: str.format(*args, **kwargs) @@ -1082,9 +1082,9 @@ .. method:: str.rfind(sub[, start[, end]]) - Return the highest index in the string where substring *sub* is found, such that - *sub* is contained within s[start,end]. Optional arguments *start* and *end* - are interpreted as in slice notation. Return ``-1`` on failure. + Return the highest index in the string where substring *sub* is found, such + that *sub* is contained within ``s[start:end]``. Optional arguments *start* + and *end* are interpreted as in slice notation. Return ``-1`` on failure. .. method:: str.rindex(sub[, start[, end]]) Modified: python/branches/py3k-jit/Doc/library/sys.rst ============================================================================== --- python/branches/py3k-jit/Doc/library/sys.rst (original) +++ python/branches/py3k-jit/Doc/library/sys.rst Tue May 4 01:24:51 2010 @@ -302,17 +302,19 @@ file names, or ``None`` if the system default encoding is used. The result value depends on the operating system: - * On Windows 9x, the encoding is "mbcs". - - * On Mac OS X, the encoding is "utf-8". + * On Mac OS X, the encoding is ``'utf-8'``. * On Unix, the encoding is the user's preference according to the result of - nl_langinfo(CODESET), or :const:`None` if the ``nl_langinfo(CODESET)`` failed. + nl_langinfo(CODESET), or ``None`` if the ``nl_langinfo(CODESET)`` + failed. * On Windows NT+, file names are Unicode natively, so no conversion is - performed. :func:`getfilesystemencoding` still returns ``'mbcs'``, as this is - the encoding that applications should use when they explicitly want to convert - Unicode strings to byte strings that are equivalent when used as file names. + performed. :func:`getfilesystemencoding` still returns ``'mbcs'``, as + this is the encoding that applications should use when they explicitly + want to convert Unicode strings to byte strings that are equivalent when + used as file names. + + * On Windows 9x, the encoding is ``'mbcs'``. .. function:: getrefcount(object) Modified: python/branches/py3k-jit/Doc/library/syslog.rst ============================================================================== --- python/branches/py3k-jit/Doc/library/syslog.rst (original) +++ python/branches/py3k-jit/Doc/library/syslog.rst Tue May 4 01:24:51 2010 @@ -10,42 +10,66 @@ Refer to the Unix manual pages for a detailed description of the ``syslog`` facility. +This module wraps the system ``syslog`` module. A pure Python +library that can speak to a syslog server is available in +the :mod:`logging.handlers` module as :class:`SysLogHandler`. + The module defines the following functions: .. function:: syslog([priority,] message) - Send the string *message* to the system logger. A trailing newline is added if - necessary. Each message is tagged with a priority composed of a *facility* and - a *level*. The optional *priority* argument, which defaults to - :const:`LOG_INFO`, determines the message priority. If the facility is not - encoded in *priority* using logical-or (``LOG_INFO | LOG_USER``), the value - given in the :func:`openlog` call is used. - - -.. function:: openlog(ident[, logopt[, facility]]) - - Logging options other than the defaults can be set by explicitly opening the log - file with :func:`openlog` prior to calling :func:`syslog`. The defaults are - (usually) *ident* = ``'syslog'``, *logopt* = ``0``, *facility* = - :const:`LOG_USER`. The *ident* argument is a string which is prepended to every - message. The optional *logopt* argument is a bit field - see below for possible - values to combine. The optional *facility* argument sets the default facility - for messages which do not have a facility explicitly encoded. + Send the string *message* to the system logger. A trailing newline is + added if necessary. Each message is tagged with a priority composed + of a *facility* and a *level*. The optional *priority* argument, which + defaults to :const:`LOG_INFO`, determines the message priority. If the + facility is not encoded in *priority* using logical-or (``LOG_INFO | + LOG_USER``), the value given in the :func:`openlog` call is used. + + If :func:`openlog` has not been called prior to the call to + :func:'syslog', ``openlog()`` will be called with no arguments. + + +.. function:: openlog([ident[, logopt[, facility]]]) + + Logging options of subsequent :func:`syslog` calls can be set by + calling :func:`openlog`. :func:`syslog` will call :func:`openlog` + with no arguments if the log is not currently open. + + The optional *ident* keyword argument is a string which is prepended + to every message, and defaults to ''sys.argv[0]'' with leading + path components stripped. The optional *logopt* keyword argument + (default=0) is a bit field - see below for possible values to combine. + The optional *facility* keyword argument (default=:const:`LOG_USER`) + sets the default facility for messages which do not have a facility + explicitly encoded. + + .. versionchanged::3.2 + In previous versions, keyword arguments were not allowed, and *ident* + was required. The default for *ident* was dependent on the system + libraries, and often was ''python'' instead of the name of the + python program file. .. function:: closelog() - Close the log file. + Reset the syslog module values and call the system library + ''closelog()''. + + This causes the module to behave as it does when initially imported. + For example, :func:'openlog' will be called on the first :func:'syslog' + call (if :func:'openlog' hasn't already been called), and *ident* + and other :func:'openlog' parameters are reset to defaults. .. function:: setlogmask(maskpri) - Set the priority mask to *maskpri* and return the previous mask value. Calls to - :func:`syslog` with a priority level not set in *maskpri* are ignored. The - default is to log all priorities. The function ``LOG_MASK(pri)`` calculates the - mask for the individual priority *pri*. The function ``LOG_UPTO(pri)`` - calculates the mask for all priorities up to and including *pri*. + Set the priority mask to *maskpri* and return the previous mask value. + Calls to :func:`syslog` with a priority level not set in *maskpri* + are ignored. The default is to log all priorities. The function + ``LOG_MASK(pri)`` calculates the mask for the individual priority + *pri*. The function ``LOG_UPTO(pri)`` calculates the mask for all + priorities up to and including *pri*. The module defines the following constants: @@ -63,3 +87,24 @@ :const:`LOG_PID`, :const:`LOG_CONS`, :const:`LOG_NDELAY`, :const:`LOG_NOWAIT` and :const:`LOG_PERROR` if defined in ````. + +Examples +-------- + +Simple example +~~~~~~~~~~~~~~ + +A simple set of examples:: + + import syslog + + syslog.syslog('Processing started') + if error: + syslog.syslog(syslog.LOG_ERR, 'Processing started') + +An example of setting some log options, these would include the process ID +in logged messages, and write the messages to the destination facility +used for mail logging:: + + syslog.openlog(logopt=syslog.LOG_PID, facility=syslog.LOG_MAIL) + syslog.syslog('E-mail processing initiated...') Modified: python/branches/py3k-jit/Doc/library/unittest.rst ============================================================================== --- python/branches/py3k-jit/Doc/library/unittest.rst (original) +++ python/branches/py3k-jit/Doc/library/unittest.rst Tue May 4 01:24:51 2010 @@ -95,40 +95,6 @@ A special-interest-group for discussion of testing, and testing tools, in Python. -.. _unittest-test-discovery: - -Test Discovery --------------- - -.. versionadded:: 3.2 - -unittest supports simple test discovery. For a project's tests to be -compatible with test discovery they must all be importable from the top level -directory of the project; i.e. they must all be in Python packages. - -Test discovery is implemented in :meth:`TestLoader.discover`, but can also be -used from the command line. The basic command line usage is:: - - cd project_directory - python -m unittest discover - -The ``discover`` sub-command has the following options: - - -v, --verbose Verbose output - -s directory Directory to start discovery ('.' default) - -p pattern Pattern to match test files ('test*.py' default) - -t directory Top level directory of project (default to - start directory) - -The -s, -p, & -t options can be passsed in as positional arguments. The -following two command lines are equivalent:: - - python -m unittest discover -s project_directory -p '*_test.py' - python -m unittest discover project_directory '*_test.py' - -Test modules and packages can customize test loading and discovery by through -the `load_tests protocol`_. - .. _unittest-minimal-example: Basic example @@ -1904,8 +1870,17 @@ and report all the results so far. A second control-c will raise a ``KeyboardInterrupt`` in the usual way. -There are a few utility functions for framework authors to enable this -functionality within test frameworks. +The control-c handling signal handler attempts to remain compatible with code or +tests that install their own :const:`signal.SIGINT` handler. If the ``unittest`` +handler is called but *isn't* the installed :const:`signal.SIGINT` handler, +i.e. it has been replaced by the system under test and delegated to, then it +calls the default handler. This will normally be the expected behavior by code +that replaces an installed handler and delegates to it. For individual tests +that need ``unittest`` control-c handling disabled the :func:`removeHandler` +decorator can be used. + +There are a few utility functions for framework authors to enable control-c +handling functionality within test frameworks. .. function:: installHandler() @@ -1913,15 +1888,37 @@ (usually in response to the user pressing control-c) all registered results have :meth:`~TestResult.stop` called. + .. versionadded:: 3.2 + .. function:: registerResult(result) Register a :class:`TestResult` object for control-c handling. Registering a result stores a weak reference to it, so it doesn't prevent the result from being garbage collected. + Registering a :class:`TestResult` object has no side-effects if control-c + handling is not enabled, so test frameworks can unconditionally register + all results they create independently of whether or not handling is enabled. + + .. versionadded:: 3.2 + .. function:: removeResult(result) Remove a registered result. Once a result has been removed then :meth:`~TestResult.stop` will no longer be called on that result object in response to a control-c. + .. versionadded:: 3.2 + +.. function:: removeHandler(function=None) + + When called without arguments this function removes the control-c handler + if it has been installed. This function can also be used as a test decorator + to temporarily remove the handler whilst the test is being executed:: + + @unittest.removeHandler + def test_signal_handling(self): + ... + + .. versionadded:: 3.2 + Modified: python/branches/py3k-jit/Doc/library/winreg.rst ============================================================================== --- python/branches/py3k-jit/Doc/library/winreg.rst (original) +++ python/branches/py3k-jit/Doc/library/winreg.rst Tue May 4 01:24:51 2010 @@ -13,7 +13,7 @@ close them. This module exposes a very low-level interface to the Windows registry; it is -expected that in the future a new ``winreg`` module will be created offering a +expected that in the future a new ``winreg`` module will be created offering a higher-level interface to the registry API. This module offers the following functions: @@ -31,39 +31,41 @@ .. function:: ConnectRegistry(computer_name, key) - Establishes a connection to a predefined registry handle on another computer, - and returns a :dfn:`handle object` + Establishes a connection to a predefined registry handle on another computer, + and returns a :ref:`handle object `. - *computer_name* is the name of the remote computer, of the form + *computer_name* is the name of the remote computer, of the form ``r"\\computername"``. If ``None``, the local computer is used. *key* is the predefined handle to connect to. The return value is the handle of the opened key. If the function fails, a - :exc:`WindowsError` exception is raised. + :exc:`WindowsError` exception is raised. .. function:: CreateKey(key, sub_key) - Creates or opens the specified key, returning a :dfn:`handle object` + Creates or opens the specified key, returning a + :ref:`handle object `. - *key* is an already open key, or one of the predefined :const:`HKEY_\*` + *key* is an already open key, or one of the predefined :const:`HKEY_\*` constants. - *sub_key* is a string that names the key this method opens or creates. + *sub_key* is a string that names the key this method opens or creates. - If *key* is one of the predefined keys, *sub_key* may be ``None``. In that - case, the handle returned is the same key handle passed in to the function. + If *key* is one of the predefined keys, *sub_key* may be ``None``. In that + case, the handle returned is the same key handle passed in to the function. If the key already exists, this function opens the existing key. The return value is the handle of the opened key. If the function fails, a - :exc:`WindowsError` exception is raised. + :exc:`WindowsError` exception is raised. -.. function:: CreateKeyEx(key, sub_key, res=0, sam=KEY_ALL_ACCESS) +.. function:: CreateKeyEx(key, sub_key[, res[, sam]]) - Creates or opens the specified key, returning a :dfn:`handle object` + Creates or opens the specified key, returning a + :ref:`handle object `. *key* is an already open key, or one of the predefined :const:`HKEY_\*` constants. @@ -75,8 +77,8 @@ *sam* is an integer that specifies an access mask that describes the desired security access for the key. Default is :const:`KEY_ALL_ACCESS` - If *key* is one of the predefined keys, *sub_key* may be ``None``. In that - case, the handle returned is the same key handle passed in to the function. + If *key* is one of the predefined keys, *sub_key* may be ``None``. In that + case, the handle returned is the same key handle passed in to the function. If the key already exists, this function opens the existing key. @@ -99,10 +101,10 @@ *This method can not delete keys with subkeys.* If the method succeeds, the entire key, including all of its values, is removed. - If the method fails, a :exc:`WindowsError` exception is raised. + If the method fails, a :exc:`WindowsError` exception is raised. -.. function:: DeleteKeyEx(key, sub_key, sam=KEY_WOW64_64KEY, res=0) +.. function:: DeleteKeyEx(key, sub_key[, sam[, res]]) Deletes the specified key. @@ -137,7 +139,7 @@ Removes a named value from a registry key. - *key* is an already open key, or one of the predefined :const:`HKEY_\*` + *key* is an already open key, or one of the predefined :const:`HKEY_\*` constants. *value* is a string that identifies the value to remove. @@ -147,13 +149,13 @@ Enumerates subkeys of an open registry key, returning a string. - *key* is an already open key, or any one of the predefined :const:`HKEY_\*` + *key* is an already open key, or any one of the predefined :const:`HKEY_\*` constants. - *index* is an integer that identifies the index of the key to retrieve. + *index* is an integer that identifies the index of the key to retrieve. - The function retrieves the name of one subkey each time it is called. It is - typically called repeatedly until a :exc:`WindowsError` exception is + The function retrieves the name of one subkey each time it is called. It is + typically called repeatedly until a :exc:`WindowsError` exception is raised, indicating, no more values are available. @@ -161,14 +163,14 @@ Enumerates values of an open registry key, returning a tuple. - *key* is an already open key, or any one of the predefined :const:`HKEY_\*` + *key* is an already open key, or any one of the predefined :const:`HKEY_\*` constants. - *index* is an integer that identifies the index of the value to retrieve. + *index* is an integer that identifies the index of the value to retrieve. - The function retrieves the name of one subkey each time it is called. It is - typically called repeatedly, until a :exc:`WindowsError` exception is - raised, indicating no more values. + The function retrieves the name of one subkey each time it is called. It is + typically called repeatedly, until a :exc:`WindowsError` exception is + raised, indicating no more values. The result is a tuple of 3 items: @@ -198,25 +200,25 @@ Writes all the attributes of a key to the registry. - *key* is an already open key, or one of the predefined :const:`HKEY_\*` + *key* is an already open key, or one of the predefined :const:`HKEY_\*` constants. It is not necessary to call :func:`FlushKey` to change a key. Registry changes are - flushed to disk by the registry using its lazy flusher. Registry changes are - also flushed to disk at system shutdown. Unlike :func:`CloseKey`, the - :func:`FlushKey` method returns only when all the data has been written to the + flushed to disk by the registry using its lazy flusher. Registry changes are + also flushed to disk at system shutdown. Unlike :func:`CloseKey`, the + :func:`FlushKey` method returns only when all the data has been written to the registry. An application should only call :func:`FlushKey` if it requires - absolute certainty that registry changes are on disk. + absolute certainty that registry changes are on disk. .. note:: - If you don't know whether a :func:`FlushKey` call is required, it probably + If you don't know whether a :func:`FlushKey` call is required, it probably isn't. .. function:: LoadKey(key, sub_key, file_name) - Creates a subkey under the specified key and stores registration information + Creates a subkey under the specified key and stores registration information from a specified file into that subkey. *key* is an already open key, or any of the predefined :const:`HKEY_\*` @@ -230,18 +232,18 @@ A call to LoadKey() fails if the calling process does not have the :const:`SE_RESTORE_PRIVILEGE` privilege. Note that privileges are different than - permissions - see the Win32 documentation for more details. + permissions -- see the Win32 documentation for more details. - If *key* is a handle returned by :func:`ConnectRegistry`, then the path - specified in *fileName* is relative to the remote computer. + If *key* is a handle returned by :func:`ConnectRegistry`, then the path + specified in *fileName* is relative to the remote computer. - The Win32 documentation implies *key* must be in the :const:`HKEY_USER` or + The Win32 documentation implies *key* must be in the :const:`HKEY_USER` or :const:`HKEY_LOCAL_MACHINE` tree. This may or may not be true. -.. function:: OpenKey(key, sub_key, res=0, sam=KEY_READ) +.. function:: OpenKey(key, sub_key[, res[, sam]]) - Opens the specified key, returning a :dfn:`handle object` + Opens the specified key, returning a :ref:`handle object `. *key* is an already open key, or any one of the predefined :const:`HKEY_\*` constants. @@ -250,7 +252,7 @@ *res* is a reserved integer, and must be zero. The default is zero. - *sam* is an integer that specifies an access mask that describes the desired + *sam* is an integer that specifies an access mask that describes the desired security access for the key. Default is :const:`KEY_READ`. The result is a new handle to the specified key. @@ -260,15 +262,15 @@ .. function:: OpenKeyEx() - The functionality of :func:`OpenKeyEx` is provided via :func:`OpenKey`, by the - use of default arguments. + The functionality of :func:`OpenKeyEx` is provided via :func:`OpenKey`, + by the use of default arguments. .. function:: QueryInfoKey(key) Returns information about a key, as a tuple. - *key* is an already open key, or one of the predefined :const:`HKEY_\*` + *key* is an already open key, or one of the predefined :const:`HKEY_\*` constants. The result is a tuple of 3 items: @@ -290,14 +292,14 @@ .. function:: QueryValue(key, sub_key) - Retrieves the unnamed value for a key, as a string + Retrieves the unnamed value for a key, as a string. - *key* is an already open key, or one of the predefined :const:`HKEY_\*` + *key* is an already open key, or one of the predefined :const:`HKEY_\*` constants. - *sub_key* is a string that holds the name of the subkey with which the value is - associated. If this parameter is ``None`` or empty, the function retrieves the - value set by the :func:`SetValue` method for the key identified by *key*. + *sub_key* is a string that holds the name of the subkey with which the value is + associated. If this parameter is ``None`` or empty, the function retrieves the + value set by the :func:`SetValue` method for the key identified by *key*. Values in the registry have name, type, and data components. This method retrieves the data for a key's first value that has a NULL name. But the @@ -307,10 +309,10 @@ .. function:: QueryValueEx(key, value_name) - Retrieves the type and data for a specified value name associated with an open - registry key. + Retrieves the type and data for a specified value name associated with + an open registry key. - *key* is an already open key, or one of the predefined :const:`HKEY_\*` + *key* is an already open key, or one of the predefined :const:`HKEY_\*` constants. *value_name* is a string indicating the value to query. @@ -331,18 +333,18 @@ Saves the specified key, and all its subkeys to the specified file. - *key* is an already open key, or one of the predefined :const:`HKEY_\*` + *key* is an already open key, or one of the predefined :const:`HKEY_\*` constants. *file_name* is the name of the file to save registry data to. This file cannot already exist. If this filename includes an extension, it cannot be used on file allocation table (FAT) file systems by the :meth:`LoadKey`, :meth:`ReplaceKey` - or :meth:`RestoreKey` methods. + or :meth:`RestoreKey` methods. - If *key* represents a key on a remote computer, the path described by + If *key* represents a key on a remote computer, the path described by *file_name* is relative to the remote computer. The caller of this method must - possess the :const:`SeBackupPrivilege` security privilege. Note that - privileges are different than permissions - see the Win32 documentation for + possess the :const:`SeBackupPrivilege` security privilege. Note that + privileges are different than permissions -- see the Win32 documentation for more details. This function passes NULL for *security_attributes* to the API. @@ -352,10 +354,10 @@ Associates a value with a specified key. - *key* is an already open key, or one of the predefined :const:`HKEY_\*` + *key* is an already open key, or one of the predefined :const:`HKEY_\*` constants. - *sub_key* is a string that names the subkey with which the value is associated. + *sub_key* is a string that names the subkey with which the value is associated. *type* is an integer that specifies the type of the data. Currently this must be :const:`REG_SZ`, meaning only strings are supported. Use the :func:`SetValueEx` @@ -370,7 +372,7 @@ bytes) should be stored as files with the filenames stored in the configuration registry. This helps the registry perform efficiently. - The key identified by the *key* parameter must have been opened with + The key identified by the *key* parameter must have been opened with :const:`KEY_SET_VALUE` access. @@ -378,13 +380,13 @@ Stores data in the value field of an open registry key. - *key* is an already open key, or one of the predefined :const:`HKEY_\*` + *key* is an already open key, or one of the predefined :const:`HKEY_\*` constants. - *value_name* is a string that names the subkey with which the value is + *value_name* is a string that names the subkey with which the value is associated. - *type* is an integer that specifies the type of the data. This should be one + *type* is an integer that specifies the type of the data. This should be one of the following constants defined in this module: +----------------------------------+---------------------------------------------+ @@ -406,7 +408,7 @@ +----------------------------------+---------------------------------------------+ | :const:`REG_MULTI_SZ` | A sequence of null-terminated strings, | | | terminated by two null characters. (Python | - | | handles this termination automatically.) | + | | handles this termination automatically.) | +----------------------------------+---------------------------------------------+ | :const:`REG_NONE` | No defined value type. | +----------------------------------+---------------------------------------------+ @@ -415,7 +417,7 @@ | :const:`REG_SZ` | A null-terminated string. | +----------------------------------+---------------------------------------------+ - *reserved* can be anything - zero is always passed to the API. + *reserved* can be anything -- zero is always passed to the API. *value* is a string that specifies the new value. @@ -423,7 +425,7 @@ key. The key identified by the key parameter must have been opened with :const:`KEY_SET_VALUE` access. - To open the key, use the :func:`CreateKey` or :func:`OpenKey` methods. + To open the key, use the :func:`CreateKey` or :func:`OpenKey` methods. Value lengths are limited by available memory. Long values (more than 2048 bytes) should be stored as files with the filenames stored in the configuration @@ -479,14 +481,14 @@ This object wraps a Windows HKEY object, automatically closing it when the object is destroyed. To guarantee cleanup, you can call either the -:meth:`Close` method on the object, or the :func:`CloseKey` function. +:meth:`Close` method on the object, or the :func:`CloseKey` function. All registry functions in this module return one of these objects. -All registry functions in this module which accept a handle object also accept -an integer, however, use of the handle object is encouraged. +All registry functions in this module which accept a handle object also accept +an integer, however, use of the handle object is encouraged. -Handle objects provide semantics for :meth:`__bool__` - thus :: +Handle objects provide semantics for :meth:`__bool__` -- thus :: if handle: print("Yes") @@ -499,7 +501,7 @@ Handle objects can be converted to an integer (e.g., using the built-in :func:`int` function), in which case the underlying Windows handle value is -returned. You can also use the :meth:`Detach` method to return the integer +returned. You can also use the :meth:`Detach` method to return the integer handle, and also disconnect the Windows handle from the handle object. @@ -519,8 +521,8 @@ zero. After calling this function, the handle is effectively invalidated, but the - handle is not closed. You would call this function when you need the - underlying Win32 handle to exist beyond the lifetime of the handle object. + handle is not closed. You would call this function when you need the + underlying Win32 handle to exist beyond the lifetime of the handle object. .. method:: PyHKEY.__enter__() PyHKEY.__exit__(\*exc_info) Modified: python/branches/py3k-jit/Doc/library/zlib.rst ============================================================================== --- python/branches/py3k-jit/Doc/library/zlib.rst (original) +++ python/branches/py3k-jit/Doc/library/zlib.rst Tue May 4 01:24:51 2010 @@ -108,9 +108,7 @@ than the size originally used to compress the stream; using a too-small value will result in an exception. The default value is therefore the highest value, 15. When *wbits* is negative, the standard - :program:`gzip` header is suppressed; this is an undocumented feature of the - zlib library, used for compatibility with :program:`unzip`'s compression file - format. + :program:`gzip` header is suppressed. *bufsize* is the initial size of the buffer used to hold decompressed data. If more space is required, the buffer size will be increased as needed, so you Modified: python/branches/py3k-jit/Doc/tools/sphinxext/indexsidebar.html ============================================================================== --- python/branches/py3k-jit/Doc/tools/sphinxext/indexsidebar.html (original) +++ python/branches/py3k-jit/Doc/tools/sphinxext/indexsidebar.html Tue May 4 01:24:51 2010 @@ -19,4 +19,5 @@
  • Book List
  • Audio/Visual Talks
  • Other Doc Collections
  • +
  • Report a Bug
  • Modified: python/branches/py3k-jit/Doc/tools/sphinxext/layout.html ============================================================================== --- python/branches/py3k-jit/Doc/tools/sphinxext/layout.html (original) +++ python/branches/py3k-jit/Doc/tools/sphinxext/layout.html Tue May 4 01:24:51 2010 @@ -16,6 +16,18 @@ Please donate.
    Last updated on {{ last_updated|e }}. + Found a bug? +
    Created using Sphinx {{ sphinx_version|e }}. {% endblock %} +{% block sidebarsourcelink %} +{%- if show_source and has_source and sourcename %} +

    {{ _('This Page') }}

    + +{%- endif %} +{% endblock %} Modified: python/branches/py3k-jit/Include/Python.h ============================================================================== --- python/branches/py3k-jit/Include/Python.h (original) +++ python/branches/py3k-jit/Include/Python.h Tue May 4 01:24:51 2010 @@ -49,6 +49,8 @@ #include "pyport.h" +#include "pyatomic.h" + /* Debug-mode build with pymalloc implies PYMALLOC_DEBUG. * PYMALLOC_DEBUG is in error if pymalloc is not in use. */ Modified: python/branches/py3k-jit/Include/dictobject.h ============================================================================== --- python/branches/py3k-jit/Include/dictobject.h (original) +++ python/branches/py3k-jit/Include/dictobject.h Tue May 4 01:24:51 2010 @@ -126,6 +126,7 @@ PyAPI_FUNC(int) _PyDict_Contains(PyObject *mp, PyObject *key, long hash); PyAPI_FUNC(PyObject *) _PyDict_NewPresized(Py_ssize_t minused); PyAPI_FUNC(void) _PyDict_MaybeUntrack(PyObject *mp); +PyAPI_FUNC(int) _PyDict_HasOnlyStringKeys(PyObject *mp); /* PyDict_Update(mp, other) is equivalent to PyDict_Merge(mp, other, 1). */ PyAPI_FUNC(int) PyDict_Update(PyObject *mp, PyObject *other); Modified: python/branches/py3k-jit/Include/modsupport.h ============================================================================== --- python/branches/py3k-jit/Include/modsupport.h (original) +++ python/branches/py3k-jit/Include/modsupport.h Tue May 4 01:24:51 2010 @@ -27,6 +27,7 @@ PyAPI_FUNC(int) PyArg_ParseTuple(PyObject *, const char *, ...) Py_FORMAT_PARSETUPLE(PyArg_ParseTuple, 2, 3); PyAPI_FUNC(int) PyArg_ParseTupleAndKeywords(PyObject *, PyObject *, const char *, char **, ...); +PyAPI_FUNC(int) PyArg_ValidateKeywordArguments(PyObject *); PyAPI_FUNC(int) PyArg_UnpackTuple(PyObject *, const char *, Py_ssize_t, Py_ssize_t, ...); PyAPI_FUNC(PyObject *) Py_BuildValue(const char *, ...); PyAPI_FUNC(PyObject *) _Py_BuildValue_SizeT(const char *, ...); Modified: python/branches/py3k-jit/Include/pystate.h ============================================================================== --- python/branches/py3k-jit/Include/pystate.h (original) +++ python/branches/py3k-jit/Include/pystate.h Tue May 4 01:24:51 2010 @@ -131,12 +131,15 @@ /* Variable and macro for in-line access to current thread state */ -PyAPI_DATA(PyThreadState *) _PyThreadState_Current; +/* Assuming the current thread holds the GIL, this is the + PyThreadState for the current thread. */ +PyAPI_DATA(_Py_atomic_address) _PyThreadState_Current; #ifdef Py_DEBUG #define PyThreadState_GET() PyThreadState_Get() #else -#define PyThreadState_GET() (_PyThreadState_Current) +#define PyThreadState_GET() \ + ((PyThreadState*)_Py_atomic_load_relaxed(&_PyThreadState_Current)) #endif typedef Modified: python/branches/py3k-jit/Lib/_pyio.py ============================================================================== --- python/branches/py3k-jit/Lib/_pyio.py (original) +++ python/branches/py3k-jit/Lib/_pyio.py Tue May 4 01:24:51 2010 @@ -13,8 +13,7 @@ from _dummy_thread import allocate_lock as Lock import io -from io import __all__ -from io import SEEK_SET, SEEK_CUR, SEEK_END +from io import (__all__, SEEK_SET, SEEK_CUR, SEEK_END) # open() uses st_blksize whenever we can DEFAULT_BUFFER_SIZE = 8 * 1024 # bytes @@ -35,7 +34,7 @@ self.characters_written = characters_written -def open(file: (str, bytes), mode: str = "r", buffering: int = None, +def open(file: (str, bytes), mode: str = "r", buffering: int = -1, encoding: str = None, errors: str = None, newline: str = None, closefd: bool = True) -> "IOBase": @@ -150,7 +149,7 @@ raise TypeError("invalid file: %r" % file) if not isinstance(mode, str): raise TypeError("invalid mode: %r" % mode) - if buffering is not None and not isinstance(buffering, int): + if not isinstance(buffering, int): raise TypeError("invalid buffering: %r" % buffering) if encoding is not None and not isinstance(encoding, str): raise TypeError("invalid encoding: %r" % encoding) @@ -187,8 +186,6 @@ (appending and "a" or "") + (updating and "+" or ""), closefd) - if buffering is None: - buffering = -1 line_buffering = False if buffering == 1 or buffering < 0 and raw.isatty(): buffering = -1 @@ -228,7 +225,7 @@ """ def __get__(self, obj, typ): return ( - "open(file, mode='r', buffering=None, encoding=None, " + "open(file, mode='r', buffering=-1, encoding=None, " "errors=None, newline=None, closefd=True)\n\n" + open.__doc__) @@ -325,6 +322,7 @@ This is not implemented for read-only and non-blocking streams. """ + self._checkClosed() # XXX Should this return the number of bytes written??? __closed = False @@ -335,10 +333,7 @@ This method has no effect if the file is already closed. """ if not self.__closed: - try: - self.flush() - except IOError: - pass # If flush() fails, just give up + self.flush() self.__closed = True def __del__(self) -> None: @@ -705,14 +700,13 @@ ### Flush and close ### def flush(self): + if self.closed: + raise ValueError("flush of closed file") self.raw.flush() def close(self): - if not self.closed and self.raw is not None: - try: - self.flush() - except IOError: - pass # If flush() fails, just give up + if self.raw is not None and not self.closed: + self.flush() self.raw.close() def detach(self): @@ -1524,11 +1518,8 @@ self._telling = self._seekable def close(self): - if self.buffer is not None: - try: - self.flush() - except IOError: - pass # If flush() fails, just give up + if self.buffer is not None and not self.closed: + self.flush() self.buffer.close() @property Modified: python/branches/py3k-jit/Lib/compileall.py ============================================================================== --- python/branches/py3k-jit/Lib/compileall.py (original) +++ python/branches/py3k-jit/Lib/compileall.py Tue May 4 01:24:51 2010 @@ -45,6 +45,8 @@ names.sort() success = 1 for name in names: + if name == '__pycache__': + continue fullname = os.path.join(dir, name) if ddir is not None: dfile = os.path.join(ddir, name) @@ -89,13 +91,14 @@ else: cfile = imp.cache_from_source(fullname) cache_dir = os.path.dirname(cfile) - try: - os.mkdir(cache_dir) - except OSError as error: - if error.errno != errno.EEXIST: - raise head, tail = name[:-3], name[-3:] if tail == '.py': + if not legacy: + try: + os.mkdir(cache_dir) + except OSError as error: + if error.errno != errno.EEXIST: + raise if not force: try: mtime = int(os.stat(fullname).st_mtime) Modified: python/branches/py3k-jit/Lib/ctypes/test/test_errno.py ============================================================================== --- python/branches/py3k-jit/Lib/ctypes/test/test_errno.py (original) +++ python/branches/py3k-jit/Lib/ctypes/test/test_errno.py Tue May 4 01:24:51 2010 @@ -1,27 +1,31 @@ import unittest, os, errno from ctypes import * from ctypes.util import find_library -import threading +try: + import threading +except ImportError: + threading = None class Test(unittest.TestCase): def test_open(self): libc_name = find_library("c") - if libc_name is not None: - libc = CDLL(libc_name, use_errno=True) - if os.name == "nt": - libc_open = libc._open - else: - libc_open = libc.open + if libc_name is None: + raise unittest.SkipTest("Unable to find C library") + libc = CDLL(libc_name, use_errno=True) + if os.name == "nt": + libc_open = libc._open + else: + libc_open = libc.open + + libc_open.argtypes = c_char_p, c_int - libc_open.argtypes = c_char_p, c_int - - self.assertEqual(libc_open("", 0), -1) - self.assertEqual(get_errno(), errno.ENOENT) - - self.assertEqual(set_errno(32), errno.ENOENT) - self.assertEqual(get_errno(), 32) + self.assertEqual(libc_open("", 0), -1) + self.assertEqual(get_errno(), errno.ENOENT) + self.assertEqual(set_errno(32), errno.ENOENT) + self.assertEqual(get_errno(), 32) + if threading: def _worker(): set_errno(0) @@ -41,36 +45,35 @@ self.assertEqual(get_errno(), 32) set_errno(0) - if os.name == "nt": + @unittest.skipUnless(os.name == "nt", 'Test specific to Windows') + def test_GetLastError(self): + dll = WinDLL("kernel32", use_last_error=True) + GetModuleHandle = dll.GetModuleHandleA + GetModuleHandle.argtypes = [c_wchar_p] - def test_GetLastError(self): - dll = WinDLL("kernel32", use_last_error=True) - GetModuleHandle = dll.GetModuleHandleA - GetModuleHandle.argtypes = [c_wchar_p] - - self.assertEqual(0, GetModuleHandle("foo")) - self.assertEqual(get_last_error(), 126) + self.assertEqual(0, GetModuleHandle("foo")) + self.assertEqual(get_last_error(), 126) - self.assertEqual(set_last_error(32), 126) - self.assertEqual(get_last_error(), 32) + self.assertEqual(set_last_error(32), 126) + self.assertEqual(get_last_error(), 32) - def _worker(): - set_last_error(0) + def _worker(): + set_last_error(0) - dll = WinDLL("kernel32", use_last_error=False) - GetModuleHandle = dll.GetModuleHandleW - GetModuleHandle.argtypes = [c_wchar_p] - GetModuleHandle("bar") + dll = WinDLL("kernel32", use_last_error=False) + GetModuleHandle = dll.GetModuleHandleW + GetModuleHandle.argtypes = [c_wchar_p] + GetModuleHandle("bar") - self.assertEqual(get_last_error(), 0) + self.assertEqual(get_last_error(), 0) - t = threading.Thread(target=_worker) - t.start() - t.join() + t = threading.Thread(target=_worker) + t.start() + t.join() - self.assertEqual(get_last_error(), 32) + self.assertEqual(get_last_error(), 32) - set_last_error(0) + set_last_error(0) if __name__ == "__main__": unittest.main() Modified: python/branches/py3k-jit/Lib/http/client.py ============================================================================== --- python/branches/py3k-jit/Lib/http/client.py (original) +++ python/branches/py3k-jit/Lib/http/client.py Tue May 4 01:24:51 2010 @@ -487,6 +487,9 @@ if self.fp is None: return b"" + if self._method == "HEAD": + return b"" + if self.chunked: return self._read_chunked(amt) Modified: python/branches/py3k-jit/Lib/locale.py ============================================================================== --- python/branches/py3k-jit/Lib/locale.py (original) +++ python/branches/py3k-jit/Lib/locale.py Tue May 4 01:24:51 2010 @@ -227,22 +227,30 @@ percents = list(_percent_re.finditer(f)) new_f = _percent_re.sub('%s', f) - if isinstance(val, tuple): - new_val = list(val) - i = 0 - for perc in percents: - starcount = perc.group('modifiers').count('*') - new_val[i] = format(perc.group(), new_val[i], grouping, False, *new_val[i+1:i+1+starcount]) - del new_val[i+1:i+1+starcount] - i += (1 + starcount) - val = tuple(new_val) - elif isinstance(val, collections.Mapping): + if isinstance(val, collections.Mapping): + new_val = [] for perc in percents: - key = perc.group("key") - val[key] = format(perc.group(), val[key], grouping) + if perc.group()[-1]=='%': + new_val.append('%') + else: + new_val.append(format(perc.group(), val, grouping)) else: - # val is a single value - val = format(percents[0].group(), val, grouping) + if not isinstance(val, tuple): + val = (val,) + new_val = [] + i = 0 + for perc in percents: + if perc.group()[-1]=='%': + new_val.append('%') + else: + starcount = perc.group('modifiers').count('*') + new_val.append(_format(perc.group(), + val[i], + grouping, + False, + *val[i+1:i+1+starcount])) + i += (1 + starcount) + val = tuple(new_val) return new_f % val Modified: python/branches/py3k-jit/Lib/os.py ============================================================================== --- python/branches/py3k-jit/Lib/os.py (original) +++ python/branches/py3k-jit/Lib/os.py Tue May 4 01:24:51 2010 @@ -450,6 +450,8 @@ def getenv(key, default=None): """Get an environment variable, return None if it doesn't exist. The optional second argument can specify an alternate default.""" + if isinstance(key, bytes): + key = key.decode(sys.getfilesystemencoding(), "surrogateescape") return environ.get(key, default) __all__.append("getenv") Modified: python/branches/py3k-jit/Lib/shutil.py ============================================================================== --- python/branches/py3k-jit/Lib/shutil.py (original) +++ python/branches/py3k-jit/Lib/shutil.py Tue May 4 01:24:51 2010 @@ -11,6 +11,13 @@ import fnmatch import collections import errno +import tarfile + +try: + import bz2 + _BZ2_SUPPORTED = True +except ImportError: + _BZ2_SUPPORTED = False try: from pwd import getpwnam @@ -25,7 +32,9 @@ __all__ = ["copyfileobj", "copyfile", "copymode", "copystat", "copy", "copy2", "copytree", "move", "rmtree", "Error", "SpecialFileError", "ExecError", "make_archive", "get_archive_formats", - "register_archive_format", "unregister_archive_format"] + "register_archive_format", "unregister_archive_format", + "get_unpack_formats", "register_unpack_format", + "unregister_unpack_format", "unpack_archive"] class Error(EnvironmentError): pass @@ -37,6 +46,14 @@ class ExecError(EnvironmentError): """Raised when a command could not be executed""" +class ReadError(EnvironmentError): + """Raised when an archive cannot be read""" + +class RegistryError(Exception): + """Raised when a registery operation with the archiving + and unpacking registeries fails""" + + try: WindowsError except NameError: @@ -161,8 +178,8 @@ an Error exception at the end of the copy process. You can set the optional ignore_dangling_symlinks flag to true if you - want to silence this exception. - + want to silence this exception. Notice that this has no effect on + platforms that don't support os.symlink. The optional ignore argument is a callable. If given, it is called with the `src` parameter, which is the directory @@ -365,13 +382,17 @@ Returns the output filename. """ - tar_compression = {'gzip': 'gz', 'bzip2': 'bz2', None: ''} - compress_ext = {'gzip': '.gz', 'bzip2': '.bz2'} + tar_compression = {'gzip': 'gz', None: ''} + compress_ext = {'gzip': '.gz'} + + if _BZ2_SUPPORTED: + tar_compression['bzip2'] = 'bz2' + compress_ext['bzip2'] = '.bz2' # flags for compression program, each element of list will be an argument if compress is not None and compress not in compress_ext.keys(): - raise ValueError("bad value for 'compress': must be None, 'gzip', or " - "'bzip2'") + raise ValueError("bad value for 'compress', or compression format not " + "supported : {0}".format(compress)) archive_name = base_name + '.tar' + compress_ext.get(compress, '') archive_dir = os.path.dirname(archive_name) @@ -381,10 +402,7 @@ if not dry_run: os.makedirs(archive_dir) - # creating the tarball - import tarfile # late import so Python build itself doesn't break - if logger is not None: logger.info('Creating tar archive') @@ -480,6 +498,10 @@ 'zip': (_make_zipfile, [],"ZIP file") } +if _BZ2_SUPPORTED: + _ARCHIVE_FORMATS['bztar'] = (_make_tarball, [('compress', 'bzip2')], + "bzip2'ed tar-file") + def get_archive_formats(): """Returns a list of supported formats for archiving and unarchiving. @@ -567,3 +589,168 @@ os.chdir(save_cwd) return filename + + +def get_unpack_formats(): + """Returns a list of supported formats for unpacking. + + Each element of the returned sequence is a tuple + (name, extensions, description) + """ + formats = [(name, info[0], info[3]) for name, info in + _UNPACK_FORMATS.items()] + formats.sort() + return formats + +def _check_unpack_options(extensions, function, extra_args): + """Checks what gets registered as an unpacker.""" + # first make sure no other unpacker is registered for this extension + existing_extensions = {} + for name, info in _UNPACK_FORMATS.items(): + for ext in info[0]: + existing_extensions[ext] = name + + for extension in extensions: + if extension in existing_extensions: + msg = '%s is already registered for "%s"' + raise RegistryError(msg % (extension, + existing_extensions[extension])) + + if not isinstance(function, collections.Callable): + raise TypeError('The registered function must be a callable') + + +def register_unpack_format(name, extensions, function, extra_args=None, + description=''): + """Registers an unpack format. + + `name` is the name of the format. `extensions` is a list of extensions + corresponding to the format. + + `function` is the callable that will be + used to unpack archives. The callable will receive archives to unpack. + If it's unable to handle an archive, it needs to raise a ReadError + exception. + + If provided, `extra_args` is a sequence of + (name, value) tuples that will be passed as arguments to the callable. + description can be provided to describe the format, and will be returned + by the get_unpack_formats() function. + """ + if extra_args is None: + extra_args = [] + _check_unpack_options(extensions, function, extra_args) + _UNPACK_FORMATS[name] = extensions, function, extra_args, description + +def unregister_unpack_format(name): + """Removes the pack format from the registery.""" + del _UNPACK_FORMATS[name] + +def _ensure_directory(path): + """Ensure that the parent directory of `path` exists""" + dirname = os.path.dirname(path) + if not os.path.isdir(dirname): + os.makedirs(dirname) + +def _unpack_zipfile(filename, extract_dir): + """Unpack zip `filename` to `extract_dir` + """ + try: + import zipfile + except ImportError: + raise ReadError('zlib not supported, cannot unpack this archive.') + + if not zipfile.is_zipfile(filename): + raise ReadError("%s is not a zip file" % filename) + + zip = zipfile.ZipFile(filename) + try: + for info in zip.infolist(): + name = info.filename + + # don't extract absolute paths or ones with .. in them + if name.startswith('/') or '..' in name: + continue + + target = os.path.join(extract_dir, *name.split('/')) + if not target: + continue + + _ensure_directory(target) + if not name.endswith('/'): + # file + data = zip.read(info.filename) + f = open(target,'wb') + try: + f.write(data) + finally: + f.close() + del data + finally: + zip.close() + +def _unpack_tarfile(filename, extract_dir): + """Unpack tar/tar.gz/tar.bz2 `filename` to `extract_dir` + """ + try: + tarobj = tarfile.open(filename) + except tarfile.TarError: + raise ReadError( + "%s is not a compressed or uncompressed tar file" % filename) + try: + tarobj.extractall(extract_dir) + finally: + tarobj.close() + +_UNPACK_FORMATS = { + 'gztar': (['.tar.gz', '.tgz'], _unpack_tarfile, [], "gzip'ed tar-file"), + 'tar': (['.tar'], _unpack_tarfile, [], "uncompressed tar file"), + 'zip': (['.zip'], _unpack_zipfile, [], "ZIP file") + } + +if _BZ2_SUPPORTED: + _UNPACK_FORMATS['bztar'] = (['.bz2'], _unpack_tarfile, [], + "bzip2'ed tar-file") + +def _find_unpack_format(filename): + for name, info in _UNPACK_FORMATS.items(): + for extension in info[0]: + if filename.endswith(extension): + return name + return None + +def unpack_archive(filename, extract_dir=None, format=None): + """Unpack an archive. + + `filename` is the name of the archive. + + `extract_dir` is the name of the target directory, where the archive + is unpacked. If not provided, the current working directory is used. + + `format` is the archive format: one of "zip", "tar", or "gztar". Or any + other registered format. If not provided, unpack_archive will use the + filename extension and see if an unpacker was registered for that + extension. + + In case none is found, a ValueError is raised. + """ + if extract_dir is None: + extract_dir = os.getcwd() + + if format is not None: + try: + format_info = _UNPACK_FORMATS[format] + except KeyError: + raise ValueError("Unknown unpack format '{0}'".format(format)) + + func = format_info[0] + func(filename, extract_dir, **dict(format_info[1])) + else: + # we need to look at the registered unpackers supported extensions + format = _find_unpack_format(filename) + if format is None: + raise ReadError("Unknown archive format '{0}'".format(filename)) + + func = _UNPACK_FORMATS[format][1] + kwargs = dict(_UNPACK_FORMATS[format][2]) + func(filename, extract_dir, **kwargs) Modified: python/branches/py3k-jit/Lib/socketserver.py ============================================================================== --- python/branches/py3k-jit/Lib/socketserver.py (original) +++ python/branches/py3k-jit/Lib/socketserver.py Tue May 4 01:24:51 2010 @@ -198,7 +198,7 @@ self.server_address = server_address self.RequestHandlerClass = RequestHandlerClass self.__is_shut_down = threading.Event() - self.__serving = False + self.__shutdown_request = False def server_activate(self): """Called by constructor to activate the server. @@ -215,17 +215,19 @@ self.timeout. If you need to do periodic tasks, do them in another thread. """ - self.__serving = True self.__is_shut_down.clear() - while self.__serving: - # XXX: Consider using another file descriptor or - # connecting to the socket to wake this up instead of - # polling. Polling reduces our responsiveness to a - # shutdown request and wastes cpu at all other times. - r, w, e = select.select([self], [], [], poll_interval) - if r: - self._handle_request_noblock() - self.__is_shut_down.set() + try: + while not self.__shutdown_request: + # XXX: Consider using another file descriptor or + # connecting to the socket to wake this up instead of + # polling. Polling reduces our responsiveness to a + # shutdown request and wastes cpu at all other times. + r, w, e = select.select([self], [], [], poll_interval) + if self in r: + self._handle_request_noblock() + finally: + self.__shutdown_request = False + self.__is_shut_down.set() def shutdown(self): """Stops the serve_forever loop. @@ -234,7 +236,7 @@ serve_forever() is running in another thread, or it will deadlock. """ - self.__serving = False + self.__shutdown_request = True self.__is_shut_down.wait() # The distinction between handling, getting, processing and Modified: python/branches/py3k-jit/Lib/sqlite3/test/dbapi.py ============================================================================== --- python/branches/py3k-jit/Lib/sqlite3/test/dbapi.py (original) +++ python/branches/py3k-jit/Lib/sqlite3/test/dbapi.py Tue May 4 01:24:51 2010 @@ -22,8 +22,11 @@ # 3. This notice may not be removed or altered from any source distribution. import unittest -import threading import sqlite3 as sqlite +try: + import threading +except ImportError: + threading = None class ModuleTests(unittest.TestCase): def CheckAPILevel(self): @@ -460,6 +463,7 @@ except TypeError: pass + at unittest.skipUnless(threading, 'This test requires threading.') class ThreadTests(unittest.TestCase): def setUp(self): self.con = sqlite.connect(":memory:") Modified: python/branches/py3k-jit/Lib/ssl.py ============================================================================== --- python/branches/py3k-jit/Lib/ssl.py (original) +++ python/branches/py3k-jit/Lib/ssl.py Tue May 4 01:24:51 2010 @@ -82,6 +82,7 @@ from socket import socket, AF_INET, SOCK_STREAM import base64 # for DER-to-PEM translation import traceback +import errno class SSLSocket(socket): @@ -96,30 +97,35 @@ family=AF_INET, type=SOCK_STREAM, proto=0, fileno=None, suppress_ragged_eofs=True, ciphers=None): + connected = False if sock is not None: socket.__init__(self, family=sock.family, type=sock.type, proto=sock.proto, fileno=_dup(sock.fileno())) + self.settimeout(sock.gettimeout()) + # see if it's connected + try: + sock.getpeername() + except socket_error as e: + if e.errno != errno.ENOTCONN: + raise + else: + connected = True sock.close() elif fileno is not None: socket.__init__(self, fileno=fileno) else: socket.__init__(self, family=family, type=type, proto=proto) - self._closed = False - if certfile and not keyfile: keyfile = certfile - # see if it's connected - try: - socket.getpeername(self) - except socket_error: - # no, no connection yet - self._sslobj = None - else: - # yes, create the SSL object + + self._closed = False + self._sslobj = None + if connected: + # create the SSL object try: self._sslobj = _ssl.sslwrap(self, server_side, keyfile, certfile, Modified: python/branches/py3k-jit/Lib/subprocess.py ============================================================================== --- python/branches/py3k-jit/Lib/subprocess.py (original) +++ python/branches/py3k-jit/Lib/subprocess.py Tue May 4 01:24:51 2010 @@ -356,31 +356,18 @@ if mswindows: + from _subprocess import CREATE_NEW_CONSOLE, CREATE_NEW_PROCESS_GROUP import threading import msvcrt - if 0: # <-- change this to use pywin32 instead of the _subprocess driver - import pywintypes - from win32api import GetStdHandle, STD_INPUT_HANDLE, \ - STD_OUTPUT_HANDLE, STD_ERROR_HANDLE - from win32api import GetCurrentProcess, DuplicateHandle, \ - GetModuleFileName, GetVersion - from win32con import DUPLICATE_SAME_ACCESS, SW_HIDE - from win32pipe import CreatePipe - from win32process import CreateProcess, STARTUPINFO, \ - GetExitCodeProcess, STARTF_USESTDHANDLES, \ - STARTF_USESHOWWINDOW, CREATE_NEW_CONSOLE - from win32process import TerminateProcess - from win32event import WaitForSingleObject, INFINITE, WAIT_OBJECT_0 - else: - from _subprocess import * - class STARTUPINFO: - dwFlags = 0 - hStdInput = None - hStdOutput = None - hStdError = None - wShowWindow = 0 - class pywintypes: - error = IOError + import _subprocess + class STARTUPINFO: + dwFlags = 0 + hStdInput = None + hStdOutput = None + hStdError = None + wShowWindow = 0 + class pywintypes: + error = IOError else: import select _has_poll = hasattr(select, 'poll') @@ -406,6 +393,8 @@ __all__ = ["Popen", "PIPE", "STDOUT", "call", "check_call", "getstatusoutput", "getoutput", "check_output", "CalledProcessError"] +if mswindows: + __all__.extend(["CREATE_NEW_CONSOLE", "CREATE_NEW_PROCESS_GROUP"]) try: MAXFD = os.sysconf("SC_OPEN_MAX") except: @@ -770,11 +759,11 @@ errread, errwrite = -1, -1 if stdin is None: - p2cread = GetStdHandle(STD_INPUT_HANDLE) + p2cread = _subprocess.GetStdHandle(_subprocess.STD_INPUT_HANDLE) if p2cread is None: - p2cread, _ = CreatePipe(None, 0) + p2cread, _ = _subprocess.CreatePipe(None, 0) elif stdin == PIPE: - p2cread, p2cwrite = CreatePipe(None, 0) + p2cread, p2cwrite = _subprocess.CreatePipe(None, 0) elif isinstance(stdin, int): p2cread = msvcrt.get_osfhandle(stdin) else: @@ -783,11 +772,11 @@ p2cread = self._make_inheritable(p2cread) if stdout is None: - c2pwrite = GetStdHandle(STD_OUTPUT_HANDLE) + c2pwrite = _subprocess.GetStdHandle(_subprocess.STD_OUTPUT_HANDLE) if c2pwrite is None: - _, c2pwrite = CreatePipe(None, 0) + _, c2pwrite = _subprocess.CreatePipe(None, 0) elif stdout == PIPE: - c2pread, c2pwrite = CreatePipe(None, 0) + c2pread, c2pwrite = _subprocess.CreatePipe(None, 0) elif isinstance(stdout, int): c2pwrite = msvcrt.get_osfhandle(stdout) else: @@ -796,11 +785,11 @@ c2pwrite = self._make_inheritable(c2pwrite) if stderr is None: - errwrite = GetStdHandle(STD_ERROR_HANDLE) + errwrite = _subprocess.GetStdHandle(_subprocess.STD_ERROR_HANDLE) if errwrite is None: - _, errwrite = CreatePipe(None, 0) + _, errwrite = _subprocess.CreatePipe(None, 0) elif stderr == PIPE: - errread, errwrite = CreatePipe(None, 0) + errread, errwrite = _subprocess.CreatePipe(None, 0) elif stderr == STDOUT: errwrite = c2pwrite elif isinstance(stderr, int): @@ -817,14 +806,15 @@ def _make_inheritable(self, handle): """Return a duplicate of handle, which is inheritable""" - return DuplicateHandle(GetCurrentProcess(), handle, - GetCurrentProcess(), 0, 1, - DUPLICATE_SAME_ACCESS) + return _subprocess.DuplicateHandle(_subprocess.GetCurrentProcess(), + handle, _subprocess.GetCurrentProcess(), 0, 1, + _subprocess.DUPLICATE_SAME_ACCESS) def _find_w9xpopen(self): """Find and return absolut path to w9xpopen.exe""" - w9xpopen = os.path.join(os.path.dirname(GetModuleFileName(0)), + w9xpopen = os.path.join( + os.path.dirname(_subprocess.GetModuleFileName(0)), "w9xpopen.exe") if not os.path.exists(w9xpopen): # Eeek - file-not-found - possibly an embedding @@ -854,17 +844,17 @@ if startupinfo is None: startupinfo = STARTUPINFO() if None not in (p2cread, c2pwrite, errwrite): - startupinfo.dwFlags |= STARTF_USESTDHANDLES + startupinfo.dwFlags |= _subprocess.STARTF_USESTDHANDLES startupinfo.hStdInput = p2cread startupinfo.hStdOutput = c2pwrite startupinfo.hStdError = errwrite if shell: - startupinfo.dwFlags |= STARTF_USESHOWWINDOW - startupinfo.wShowWindow = SW_HIDE + startupinfo.dwFlags |= _subprocess.STARTF_USESHOWWINDOW + startupinfo.wShowWindow = _subprocess.SW_HIDE comspec = os.environ.get("COMSPEC", "cmd.exe") args = comspec + " /c " + args - if (GetVersion() >= 0x80000000 or + if (_subprocess.GetVersion() >= 0x80000000 or os.path.basename(comspec).lower() == "command.com"): # Win9x, or using command.com on NT. We need to # use the w9xpopen intermediate program. For more @@ -878,11 +868,11 @@ # use at xxx" and a hopeful warning about the # stability of your system. Cost is Ctrl+C won't # kill children. - creationflags |= CREATE_NEW_CONSOLE + creationflags |= _subprocess.CREATE_NEW_CONSOLE # Start the process try: - hp, ht, pid, tid = CreateProcess(executable, args, + hp, ht, pid, tid = _subprocess.CreateProcess(executable, args, # no special security None, None, int(not close_fds), @@ -921,8 +911,9 @@ """Check if child process has terminated. Returns returncode attribute.""" if self.returncode is None: - if WaitForSingleObject(self._handle, 0) == WAIT_OBJECT_0: - self.returncode = GetExitCodeProcess(self._handle) + if(_subprocess.WaitForSingleObject(self._handle, 0) == + _subprocess.WAIT_OBJECT_0): + self.returncode = _subprocess.GetExitCodeProcess(self._handle) return self.returncode @@ -930,8 +921,9 @@ """Wait for child process to terminate. Returns returncode attribute.""" if self.returncode is None: - WaitForSingleObject(self._handle, INFINITE) - self.returncode = GetExitCodeProcess(self._handle) + _subprocess.WaitForSingleObject(self._handle, + _subprocess.INFINITE) + self.returncode = _subprocess.GetExitCodeProcess(self._handle) return self.returncode @@ -990,7 +982,7 @@ def terminate(self): """Terminates the process """ - TerminateProcess(self._handle, 1) + _subprocess.TerminateProcess(self._handle, 1) kill = terminate @@ -1090,7 +1082,10 @@ fs_encoding = sys.getfilesystemencoding() def fs_encode(s): """Encode s for use in the env, fs or cmdline.""" - return s.encode(fs_encoding, 'surrogateescape') + if isinstance(s, bytes): + return s + else: + return s.encode(fs_encoding, 'surrogateescape') # We must avoid complex work that could involve # malloc or free in the child process to avoid @@ -1204,8 +1199,9 @@ errno = 0 message = '%s:%x:%s' % (exc_type.__name__, errno, exc_value) - os.write(errpipe_write, message.encode()) - except: + message = message.encode(errors="surrogatepass") + os.write(errpipe_write, message) + except Exception: # We MUST not allow anything odd happening # above to prevent us from exiting below. pass @@ -1255,7 +1251,7 @@ for fd in (p2cwrite, c2pread, errread): if fd != -1: os.close(fd) - err_msg = err_msg.decode() + err_msg = err_msg.decode(errors="surrogatepass") if issubclass(child_exception_type, OSError) and hex_errno: errno = int(hex_errno, 16) if errno != 0: Modified: python/branches/py3k-jit/Lib/tarfile.py ============================================================================== --- python/branches/py3k-jit/Lib/tarfile.py (original) +++ python/branches/py3k-jit/Lib/tarfile.py Tue May 4 01:24:51 2010 @@ -359,7 +359,7 @@ }[mode] if hasattr(os, "O_BINARY"): mode |= os.O_BINARY - self.fd = os.open(name, mode) + self.fd = os.open(name, mode, 0o666) def close(self): os.close(self.fd) Modified: python/branches/py3k-jit/Lib/test/fork_wait.py ============================================================================== --- python/branches/py3k-jit/Lib/test/fork_wait.py (original) +++ python/branches/py3k-jit/Lib/test/fork_wait.py Tue May 4 01:24:51 2010 @@ -1,6 +1,6 @@ """This test case provides support for checking forking and wait behavior. -To test different wait behavior, overrise the wait_impl method. +To test different wait behavior, override the wait_impl method. We want fork1() semantics -- only the forking thread survives in the child after a fork(). @@ -9,7 +9,9 @@ active threads survive in the child after a fork(); this is an error. """ -import os, sys, time, _thread, unittest +import os, sys, time, unittest +import test.support as support +_thread = support.import_module('_thread') LONGSLEEP = 2 SHORTSLEEP = 0.5 Modified: python/branches/py3k-jit/Lib/test/regrtest.py ============================================================================== --- python/branches/py3k-jit/Lib/test/regrtest.py (original) +++ python/branches/py3k-jit/Lib/test/regrtest.py Tue May 4 01:24:51 2010 @@ -1,12 +1,23 @@ #! /usr/bin/env python3 -"""Regression test. +""" +Usage: + +python -m test.regrtest [options] [test_name1 [test_name2 ...]] +python path/to/Lib/test/regrtest.py [options] [test_name1 [test_name2 ...]] + + +If no arguments or options are provided, finds all files matching +the pattern "test_*" in the Lib/test subdirectory and runs +them in alphabetical order (but see -M and -u, below, for exceptions). -This will find all modules whose name is "test_*" in the test -directory, and run them. Various command line options provide -additional facilities. +For more rigorous testing, it is useful to use the following +command line: -Command line options: +python -E -tt -Wd -3 -m test.regrtest [options] [test_name1 ...] + + +Options: -h/--help -- print this text and exit @@ -16,15 +27,15 @@ -w/--verbose2 -- re-run failed tests in verbose mode -W/--verbose3 -- re-run failed tests in verbose mode immediately -d/--debug -- print traceback for failed tests --q/--quiet -- don't print anything except if a test fails +-q/--quiet -- no output unless one or more tests fail -S/--slow -- print the slowest 10 tests Selecting tests --r/--random -- randomize test execution order +-r/--random -- randomize test execution order (see below) -f/--fromfile -- read names of tests to run from a file (see below) -x/--exclude -- arguments are tests to *exclude* --s/--single -- run only a single test (see below) +-s/--single -- single step through a set of tests (see below) -u/--use RES1,RES2,... -- specify which special resource intensive tests to run -M/--memlimit LIMIT @@ -38,36 +49,32 @@ -- search for reference leaks (needs debug build, v. slow) -j/--multiprocess PROCESSES -- run PROCESSES processes at once --T/--coverage -- turn on code coverage using the trace module +-T/--coverage -- turn on code coverage tracing using the trace module -D/--coverdir DIRECTORY -- Directory where coverage files are put -N/--nocoverdir -- Put coverage files alongside modules -t/--threshold THRESHOLD -- call gc.set_threshold(THRESHOLD) -n/--nowindows -- suppress error message boxes on Windows --F/--forever -- run the selected tests in a loop, until an error happens +-F/--forever -- run the specified tests in a loop, until an error happens + -If non-option arguments are present, they are names for tests to run, -unless -x is given, in which case they are names for tests not to run. -If no test names are given, all tests are run. +Additional Option Details: -r randomizes test execution order. You can use --randseed=int to provide a int seed value for the randomizer; this is useful for reproducing troublesome test orders. --T turns on code coverage tracing with the trace module. - --D specifies the directory where coverage files are put. - --N Put coverage files alongside modules. - --s means to run only a single test and exit. This is useful when -doing memory analysis on the Python interpreter (which tend to consume -too many resources to run the full regression test non-stop). The -file /tmp/pynexttest is read to find the next test to run. If this -file is missing, the first test_*.py file in testdir or on the command -line is used. (actually tempfile.gettempdir() is used instead of -/tmp). +-s On the first invocation of regrtest using -s, the first test file found +or the first test file given on the command line is run, and the name of +the next test is recorded in a file named pynexttest. If run from the +Python build directory, pynexttest is located in the 'build' subdirectory, +otherwise it is located in tempfile.gettempdir(). On subsequent runs, +the test in pynexttest is run, and the next test is written to pynexttest. +When the last test has been run, pynexttest is deleted. In this way it +is possible to single step through the test files. This is useful when +doing memory analysis on the Python interpreter, which process tends to +consume too many resources to run the full regression test non-stop. -S is used to continue running tests after an aborted run. It will maintain the order a standard run (ie, this assumes -r is not used). @@ -369,6 +376,7 @@ elif o in ('-j', '--multiprocess'): use_mp = int(a) elif o == '--slaveargs': + replace_stdout() args, kwargs = json.loads(a) try: result = runtest(*args, **kwargs) @@ -507,8 +515,14 @@ else: tests = iter(selected) + replace_stdout() + if use_mp: - from threading import Thread + try: + from threading import Thread + except ImportError: + print("Multiprocess option requires thread support") + sys.exit(2) from queue import Queue from subprocess import Popen, PIPE debug_output_pat = re.compile(r"\[\d+ refs\]$") @@ -716,6 +730,14 @@ tests.append(modname) return stdtests + sorted(tests) +def replace_stdout(): + """Set stdout encoder error handler to backslashreplace (as stderr error + handler) to avoid UnicodeEncodeError when printing a traceback""" + stdout = sys.stdout + sys.stdout = open(stdout.fileno(), 'w', + encoding=stdout.encoding, + errors="backslashreplace") + def runtest(test, verbose, quiet, testdir=None, huntrleaks=False, debug=False, use_resources=None): """Run a single test. Modified: python/branches/py3k-jit/Lib/test/support.py ============================================================================== --- python/branches/py3k-jit/Lib/test/support.py (original) +++ python/branches/py3k-jit/Lib/test/support.py Tue May 4 01:24:51 2010 @@ -19,6 +19,10 @@ import re import imp import time +try: + import _thread +except ImportError: + _thread = None __all__ = [ "Error", "TestFailed", "ResourceDenied", "import_module", @@ -1111,12 +1115,14 @@ # at the end of a test run. def threading_setup(): - import _thread - return _thread._count(), + if _thread: + return _thread._count(), + else: + return 1, def threading_cleanup(nb_threads): - import _thread - + if not _thread: + return _MAX_COUNT = 10 for count in range(_MAX_COUNT): n = _thread._count() @@ -1126,6 +1132,13 @@ # XXX print a warning in case of failure? def reap_threads(func): + """Use this function when threads are being used. This will + ensure that the threads are cleaned up even when the test fails. + If threading is unavailable this function does nothing. + """ + if not _thread: + return func + @functools.wraps(func) def decorator(*args): key = threading_setup() Modified: python/branches/py3k-jit/Lib/test/test_asynchat.py ============================================================================== --- python/branches/py3k-jit/Lib/test/test_asynchat.py (original) +++ python/branches/py3k-jit/Lib/test/test_asynchat.py Tue May 4 01:24:51 2010 @@ -5,96 +5,101 @@ # If this fails, the test will be skipped. thread = support.import_module('_thread') -import asyncore, asynchat, socket, threading, time +import asyncore, asynchat, socket, time import unittest import sys +try: + import threading +except ImportError: + threading = None HOST = support.HOST SERVER_QUIT = b'QUIT\n' -class echo_server(threading.Thread): - # parameter to determine the number of bytes passed back to the - # client each send - chunk_size = 1 - - def __init__(self, event): - threading.Thread.__init__(self) - self.event = event - self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) - self.port = support.bind_port(self.sock) - # This will be set if the client wants us to wait before echoing data - # back. - self.start_resend_event = None - - def run(self): - self.sock.listen(1) - self.event.set() - conn, client = self.sock.accept() - self.buffer = b"" - # collect data until quit message is seen - while SERVER_QUIT not in self.buffer: - data = conn.recv(1) - if not data: - break - self.buffer = self.buffer + data - - # remove the SERVER_QUIT message - self.buffer = self.buffer.replace(SERVER_QUIT, b'') - - if self.start_resend_event: - self.start_resend_event.wait() - - # re-send entire set of collected data - try: - # this may fail on some tests, such as test_close_when_done, since - # the client closes the channel when it's done sending - while self.buffer: - n = conn.send(self.buffer[:self.chunk_size]) - time.sleep(0.001) - self.buffer = self.buffer[n:] - except: - pass - - conn.close() - self.sock.close() - -class echo_client(asynchat.async_chat): - - def __init__(self, terminator, server_port): - asynchat.async_chat.__init__(self) - self.contents = [] - self.create_socket(socket.AF_INET, socket.SOCK_STREAM) - self.connect((HOST, server_port)) - self.set_terminator(terminator) - self.buffer = b"" - - def handle_connect(self): - pass - - if sys.platform == 'darwin': - # select.poll returns a select.POLLHUP at the end of the tests - # on darwin, so just ignore it - def handle_expt(self): - pass - - def collect_incoming_data(self, data): - self.buffer += data - - def found_terminator(self): - self.contents.append(self.buffer) - self.buffer = b"" - - -def start_echo_server(): - event = threading.Event() - s = echo_server(event) - s.start() - event.wait() - event.clear() - time.sleep(0.01) # Give server time to start accepting. - return s, event +if threading: + class echo_server(threading.Thread): + # parameter to determine the number of bytes passed back to the + # client each send + chunk_size = 1 + + def __init__(self, event): + threading.Thread.__init__(self) + self.event = event + self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) + self.port = support.bind_port(self.sock) + # This will be set if the client wants us to wait before echoing data + # back. + self.start_resend_event = None + + def run(self): + self.sock.listen(1) + self.event.set() + conn, client = self.sock.accept() + self.buffer = b"" + # collect data until quit message is seen + while SERVER_QUIT not in self.buffer: + data = conn.recv(1) + if not data: + break + self.buffer = self.buffer + data + + # remove the SERVER_QUIT message + self.buffer = self.buffer.replace(SERVER_QUIT, b'') + + if self.start_resend_event: + self.start_resend_event.wait() + + # re-send entire set of collected data + try: + # this may fail on some tests, such as test_close_when_done, since + # the client closes the channel when it's done sending + while self.buffer: + n = conn.send(self.buffer[:self.chunk_size]) + time.sleep(0.001) + self.buffer = self.buffer[n:] + except: + pass + + conn.close() + self.sock.close() + + class echo_client(asynchat.async_chat): + + def __init__(self, terminator, server_port): + asynchat.async_chat.__init__(self) + self.contents = [] + self.create_socket(socket.AF_INET, socket.SOCK_STREAM) + self.connect((HOST, server_port)) + self.set_terminator(terminator) + self.buffer = b"" + + def handle_connect(self): + pass + + if sys.platform == 'darwin': + # select.poll returns a select.POLLHUP at the end of the tests + # on darwin, so just ignore it + def handle_expt(self): + pass + + def collect_incoming_data(self, data): + self.buffer += data + + def found_terminator(self): + self.contents.append(self.buffer) + self.buffer = b"" + + def start_echo_server(): + event = threading.Event() + s = echo_server(event) + s.start() + event.wait() + event.clear() + time.sleep(0.01) # Give server time to start accepting. + return s, event + at unittest.skipUnless(threading, 'Threading required for this test.') class TestAsynchat(unittest.TestCase): usepoll = False Modified: python/branches/py3k-jit/Lib/test/test_asyncore.py ============================================================================== --- python/branches/py3k-jit/Lib/test/test_asyncore.py (original) +++ python/branches/py3k-jit/Lib/test/test_asyncore.py Tue May 4 01:24:51 2010 @@ -3,7 +3,6 @@ import select import os import socket -import threading import sys import time @@ -12,6 +11,11 @@ from io import BytesIO from io import StringIO +try: + import threading +except ImportError: + threading = None + HOST = support.HOST class dummysocket: @@ -320,6 +324,7 @@ def tearDown(self): asyncore.close_all() + @unittest.skipUnless(threading, 'Threading required for this test.') @support.reap_threads def test_send(self): evt = threading.Event() Modified: python/branches/py3k-jit/Lib/test/test_bz2.py ============================================================================== --- python/branches/py3k-jit/Lib/test/test_bz2.py (original) +++ python/branches/py3k-jit/Lib/test/test_bz2.py Tue May 4 01:24:51 2010 @@ -7,11 +7,14 @@ import os import subprocess import sys -import threading + +try: + import threading +except ImportError: + threading = None # Skip tests if the bz2 module doesn't exist. bz2 = support.import_module('bz2') - from bz2 import BZ2File, BZ2Compressor, BZ2Decompressor has_cmdline_bunzip2 = sys.platform not in ("win32", "os2emx") @@ -283,6 +286,7 @@ else: self.fail("1/0 didn't raise an exception") + @unittest.skipUnless(threading, 'Threading required for this test.') def testThreading(self): # Using a BZ2File from several threads doesn't deadlock (issue #7205). data = b"1" * 2**20 Modified: python/branches/py3k-jit/Lib/test/test_capi.py ============================================================================== --- python/branches/py3k-jit/Lib/test/test_capi.py (original) +++ python/branches/py3k-jit/Lib/test/test_capi.py Tue May 4 01:24:51 2010 @@ -6,8 +6,11 @@ import time import random import unittest -import threading from test import support +try: + import threading +except ImportError: + threading = None import _testcapi @@ -33,6 +36,7 @@ self.assertRaises(AttributeError, setattr, inst.testfunction, "attribute", "test") + at unittest.skipUnless(threading, 'Threading required for this test.') class TestPendingCalls(unittest.TestCase): def pendingcalls_submit(self, l, n): @@ -148,17 +152,10 @@ raise support.TestFailed( "Couldn't find main thread correctly in the list") - try: - _testcapi._test_thread_state - have_thread_state = True - except AttributeError: - have_thread_state = False - - if have_thread_state: + if threading: import _thread import time TestThreadState() - import threading t = threading.Thread(target=TestThreadState) t.start() t.join() Modified: python/branches/py3k-jit/Lib/test/test_cmd.py ============================================================================== --- python/branches/py3k-jit/Lib/test/test_cmd.py (original) +++ python/branches/py3k-jit/Lib/test/test_cmd.py Tue May 4 01:24:51 2010 @@ -7,9 +7,9 @@ import cmd import sys -import trace import re from io import StringIO +from test import support class samplecmdclass(cmd.Cmd): """ @@ -169,11 +169,11 @@ return True def test_main(verbose=None): - from test import support, test_cmd + from test import test_cmd support.run_doctest(test_cmd, verbose) def test_coverage(coverdir): - import trace + trace = support.import_module('trace') tracer=trace.Trace(ignoredirs=[sys.prefix, sys.exec_prefix,], trace=0, count=1) tracer.run('reload(cmd);test_main()') Modified: python/branches/py3k-jit/Lib/test/test_compileall.py ============================================================================== --- python/branches/py3k-jit/Lib/test/test_compileall.py (original) +++ python/branches/py3k-jit/Lib/test/test_compileall.py Tue May 4 01:24:51 2010 @@ -75,6 +75,18 @@ os.unlink(self.bc_path) os.unlink(self.bc_path2) + def test_no_pycache_in_non_package(self): + # Bug 8563 reported that __pycache__ directories got created by + # compile_file() for non-.py files. + data_dir = os.path.join(self.directory, 'data') + data_file = os.path.join(data_dir, 'file') + os.mkdir(data_dir) + # touch data/file + with open(data_file, 'w'): + pass + compileall.compile_file(data_file) + self.assertFalse(os.path.exists(os.path.join(data_dir, '__pycache__'))) + class EncodingTest(unittest.TestCase): """Issue 6716: compileall should escape source code when printing errors @@ -98,6 +110,7 @@ finally: sys.stdout = orig_stdout + class CommandLineTests(unittest.TestCase): """Test some aspects of compileall's CLI.""" @@ -150,6 +163,24 @@ expected.sort() self.assertEqual(sorted(os.listdir(self.pkgdir)), expected) + def test_multiple_runs(self): + # Bug 8527 reported that multiple calls produced empty + # __pycache__/__pycache__ directories. + retcode = subprocess.call( + (sys.executable, '-m', 'compileall', '-q', self.pkgdir)) + self.assertEqual(retcode, 0) + # Verify the __pycache__ directory contents. + cachedir = os.path.join(self.pkgdir, '__pycache__') + self.assertTrue(os.path.exists(cachedir)) + cachecachedir = os.path.join(cachedir, '__pycache__') + self.assertFalse(os.path.exists(cachecachedir)) + # Call compileall again. + retcode = subprocess.call( + (sys.executable, '-m', 'compileall', '-q', self.pkgdir)) + self.assertEqual(retcode, 0) + self.assertTrue(os.path.exists(cachedir)) + self.assertFalse(os.path.exists(cachecachedir)) + def test_main(): support.run_unittest( Modified: python/branches/py3k-jit/Lib/test/test_contextlib.py ============================================================================== --- python/branches/py3k-jit/Lib/test/test_contextlib.py (original) +++ python/branches/py3k-jit/Lib/test/test_contextlib.py Tue May 4 01:24:51 2010 @@ -3,9 +3,12 @@ import sys import tempfile import unittest -import threading from contextlib import * # Tests __all__ from test import support +try: + import threading +except ImportError: + threading = None class ContextManagerTestCase(unittest.TestCase): @@ -151,6 +154,7 @@ finally: support.unlink(tfn) + at unittest.skipUnless(threading, 'Threading required for this test.') class LockContextTestCase(unittest.TestCase): def boilerPlate(self, lock, locked): Modified: python/branches/py3k-jit/Lib/test/test_dict.py ============================================================================== --- python/branches/py3k-jit/Lib/test/test_dict.py (original) +++ python/branches/py3k-jit/Lib/test/test_dict.py Tue May 4 01:24:51 2010 @@ -7,6 +7,12 @@ class DictTest(unittest.TestCase): + def test_invalid_keyword_arguments(self): + with self.assertRaises(TypeError): + dict(**{1 : 2}) + with self.assertRaises(TypeError): + {}.update(**{1 : 2}) + def test_constructor(self): # calling built-in types without argument must return empty self.assertEqual(dict(), {}) Modified: python/branches/py3k-jit/Lib/test/test_doctest.py ============================================================================== --- python/branches/py3k-jit/Lib/test/test_doctest.py (original) +++ python/branches/py3k-jit/Lib/test/test_doctest.py Tue May 4 01:24:51 2010 @@ -2341,8 +2341,10 @@ from test import test_doctest support.run_doctest(test_doctest, verbosity=True) -import trace, sys, re, io +import sys, re, io + def test_coverage(coverdir): + trace = support.import_module('trace') tracer = trace.Trace(ignoredirs=[sys.prefix, sys.exec_prefix,], trace=0, count=1) tracer.run('test_main()') Modified: python/branches/py3k-jit/Lib/test/test_docxmlrpc.py ============================================================================== --- python/branches/py3k-jit/Lib/test/test_docxmlrpc.py (original) +++ python/branches/py3k-jit/Lib/test/test_docxmlrpc.py Tue May 4 01:24:51 2010 @@ -2,7 +2,7 @@ import http.client import sys from test import support -import threading +threading = support.import_module('threading') import time import socket import unittest Modified: python/branches/py3k-jit/Lib/test/test_fork1.py ============================================================================== --- python/branches/py3k-jit/Lib/test/test_fork1.py (original) +++ python/branches/py3k-jit/Lib/test/test_fork1.py Tue May 4 01:24:51 2010 @@ -6,10 +6,10 @@ import signal import sys import time -import threading from test.fork_wait import ForkWait -from test.support import run_unittest, reap_children, get_attribute +from test.support import run_unittest, reap_children, get_attribute, import_module +threading = import_module('threading') # Skip test if fork does not exist. get_attribute(os, 'fork') Modified: python/branches/py3k-jit/Lib/test/test_ftplib.py ============================================================================== --- python/branches/py3k-jit/Lib/test/test_ftplib.py (original) +++ python/branches/py3k-jit/Lib/test/test_ftplib.py Tue May 4 01:24:51 2010 @@ -4,7 +4,6 @@ # environment import ftplib -import threading import asyncore import asynchat import socket @@ -19,6 +18,7 @@ from unittest import TestCase from test import support from test.support import HOST +threading = support.import_module('threading') # the dummy data returned by server over the data channel when # RETR, LIST and NLST commands are issued @@ -28,6 +28,7 @@ class DummyDTPHandler(asynchat.async_chat): + dtp_conn_closed = False def __init__(self, conn, baseclass): asynchat.async_chat.__init__(self, conn) @@ -38,8 +39,13 @@ self.baseclass.last_received_data += self.recv(1024).decode('ascii') def handle_close(self): - self.baseclass.push('226 transfer complete') - self.close() + # XXX: this method can be called many times in a row for a single + # connection, including in clear-text (non-TLS) mode. + # (behaviour witnessed with test_data_connection) + if not self.dtp_conn_closed: + self.baseclass.push('226 transfer complete') + self.close() + self.dtp_conn_closed = True def push(self, what): super(DummyDTPHandler, self).push(what.encode('ascii')) @@ -254,6 +260,7 @@ """An asyncore.dispatcher subclass supporting TLS/SSL.""" _ssl_accepting = False + _ssl_closing = False def secure_connection(self): self.del_channel() @@ -280,15 +287,36 @@ else: self._ssl_accepting = False + def _do_ssl_shutdown(self): + self._ssl_closing = True + try: + self.socket = self.socket.unwrap() + except ssl.SSLError as err: + if err.args[0] in (ssl.SSL_ERROR_WANT_READ, + ssl.SSL_ERROR_WANT_WRITE): + return + except socket.error as err: + # Any "socket error" corresponds to a SSL_ERROR_SYSCALL return + # from OpenSSL's SSL_shutdown(), corresponding to a + # closed socket condition. See also: + # http://www.mail-archive.com/openssl-users at openssl.org/msg60710.html + pass + self._ssl_closing = False + super(SSLConnection, self).close() + def handle_read_event(self): if self._ssl_accepting: self._do_ssl_handshake() + elif self._ssl_closing: + self._do_ssl_shutdown() else: super(SSLConnection, self).handle_read_event() def handle_write_event(self): if self._ssl_accepting: self._do_ssl_handshake() + elif self._ssl_closing: + self._do_ssl_shutdown() else: super(SSLConnection, self).handle_write_event() @@ -308,7 +336,7 @@ except ssl.SSLError as err: if err.args[0] in (ssl.SSL_ERROR_WANT_READ, ssl.SSL_ERROR_WANT_WRITE): - return '' + return b'' if err.args[0] in (ssl.SSL_ERROR_EOF, ssl.SSL_ERROR_ZERO_RETURN): self.handle_close() return b'' @@ -318,12 +346,9 @@ raise def close(self): - try: - if isinstance(self.socket, ssl.SSLSocket): - if self.socket._sslobj is not None: - self.socket.unwrap() - finally: - super(SSLConnection, self).close() + if (isinstance(self.socket, ssl.SSLSocket) and + self.socket._sslobj is not None): + self._do_ssl_shutdown() class DummyTLS_DTPHandler(SSLConnection, DummyDTPHandler): @@ -606,21 +631,21 @@ sock = self.client.transfercmd('list') self.assertNotIsInstance(sock, ssl.SSLSocket) sock.close() - self.client.voidresp() + self.assertEqual(self.client.voidresp(), "226 transfer complete") # secured, after PROT P self.client.prot_p() sock = self.client.transfercmd('list') self.assertIsInstance(sock, ssl.SSLSocket) sock.close() - self.client.voidresp() + self.assertEqual(self.client.voidresp(), "226 transfer complete") # PROT C is issued, the connection must be in cleartext again self.client.prot_c() sock = self.client.transfercmd('list') self.assertNotIsInstance(sock, ssl.SSLSocket) sock.close() - self.client.voidresp() + self.assertEqual(self.client.voidresp(), "226 transfer complete") def test_login(self): # login() is supposed to implicitly secure the control connection Modified: python/branches/py3k-jit/Lib/test/test_gdb.py ============================================================================== --- python/branches/py3k-jit/Lib/test/test_gdb.py (original) +++ python/branches/py3k-jit/Lib/test/test_gdb.py Tue May 4 01:24:51 2010 @@ -59,7 +59,7 @@ out, err = subprocess.Popen( args, stdout=subprocess.PIPE, stderr=subprocess.PIPE, ).communicate() - return out.decode('utf-8'), err.decode('utf-8') + return out.decode('utf-8', 'replace'), err.decode('utf-8', 'replace') def get_stack_trace(self, source=None, script=None, breakpoint=BREAKPOINT_FN, Modified: python/branches/py3k-jit/Lib/test/test_hashlib.py ============================================================================== --- python/branches/py3k-jit/Lib/test/test_hashlib.py (original) +++ python/branches/py3k-jit/Lib/test/test_hashlib.py Tue May 4 01:24:51 2010 @@ -311,10 +311,9 @@ m = hashlib.md5(b'x' * gil_minsize) self.assertEquals(m.hexdigest(), 'cfb767f225d58469c5de3632a8803958') + @unittest.skipUnless(threading, 'Threading required for this test.') + @support.reap_threads def test_threaded_hashing(self): - if not threading: - raise unittest.SkipTest('No threading module.') - # Updating the same hash object from several threads at once # using data chunk sizes containing the same byte sequences. # @@ -349,7 +348,6 @@ self.assertEqual(expected_hash, hasher.hexdigest()) - at support.reap_threads def test_main(): support.run_unittest(HashLibTestCase) Modified: python/branches/py3k-jit/Lib/test/test_httplib.py ============================================================================== --- python/branches/py3k-jit/Lib/test/test_httplib.py (original) +++ python/branches/py3k-jit/Lib/test/test_httplib.py Tue May 4 01:24:51 2010 @@ -224,6 +224,23 @@ finally: resp.close() + def test_chunked_head(self): + chunked_start = ( + 'HTTP/1.1 200 OK\r\n' + 'Transfer-Encoding: chunked\r\n\r\n' + 'a\r\n' + 'hello world\r\n' + '1\r\n' + 'd\r\n' + ) + sock = FakeSocket(chunked_start + '0\r\n') + resp = client.HTTPResponse(sock, method="HEAD") + resp.begin() + self.assertEquals(resp.read(), b'') + self.assertEquals(resp.status, 200) + self.assertEquals(resp.reason, 'OK') + resp.close() + def test_negative_content_length(self): sock = FakeSocket( 'HTTP/1.1 200 OK\r\nContent-Length: -1\r\n\r\nHello\r\n') Modified: python/branches/py3k-jit/Lib/test/test_httpservers.py ============================================================================== --- python/branches/py3k-jit/Lib/test/test_httpservers.py (original) +++ python/branches/py3k-jit/Lib/test/test_httpservers.py Tue May 4 01:24:51 2010 @@ -15,10 +15,10 @@ import urllib.parse import http.client import tempfile -import threading import unittest from test import support +threading = support.import_module('threading') class NoLogRequestHandler: def log_message(self, *args): @@ -34,14 +34,14 @@ threading.Thread.__init__(self) self.request_handler = request_handler self.test_object = test_object - self.test_object.lock.acquire() def run(self): self.server = HTTPServer(('', 0), self.request_handler) self.test_object.PORT = self.server.socket.getsockname()[1] - self.test_object.lock.release() + self.test_object.server_started.set() + self.test_object = None try: - self.server.serve_forever() + self.server.serve_forever(0.05) finally: self.server.server_close() @@ -53,13 +53,12 @@ def setUp(self): self._threads = support.threading_setup() os.environ = support.EnvironmentVarGuard() - self.lock = threading.Lock() + self.server_started = threading.Event() self.thread = TestServerThread(self, self.request_handler) self.thread.start() - self.lock.acquire() + self.server_started.wait() def tearDown(self): - self.lock.release() self.thread.stop() os.environ.__exit__() support.threading_cleanup(*self._threads) Modified: python/branches/py3k-jit/Lib/test/test_io.py ============================================================================== --- python/branches/py3k-jit/Lib/test/test_io.py (original) +++ python/branches/py3k-jit/Lib/test/test_io.py Tue May 4 01:24:51 2010 @@ -23,7 +23,6 @@ import sys import time import array -import threading import random import unittest import weakref @@ -35,6 +34,10 @@ import codecs import io # C implementation of io import _pyio as pyio # Python implementation of io +try: + import threading +except ImportError: + threading = None def _default_chunk_size(): @@ -533,6 +536,20 @@ with self.open(zero, "r") as f: self.assertRaises(OverflowError, f.read) + def test_flush_error_on_close(self): + f = self.open(support.TESTFN, "wb", buffering=0) + def bad_flush(): + raise IOError() + f.flush = bad_flush + self.assertRaises(IOError, f.close) # exception not swallowed + + def test_multi_close(self): + f = self.open(support.TESTFN, "wb", buffering=0) + f.close() + f.close() + f.close() + self.assertRaises(ValueError, f.flush) + class CIOTest(IOTest): pass @@ -632,6 +649,22 @@ raw.name = b"dummy" self.assertEqual(repr(b), "<%s name=b'dummy'>" % clsname) + def test_flush_error_on_close(self): + raw = self.MockRawIO() + def bad_flush(): + raise IOError() + raw.flush = bad_flush + b = self.tp(raw) + self.assertRaises(IOError, b.close) # exception not swallowed + + def test_multi_close(self): + raw = self.MockRawIO() + b = self.tp(raw) + b.close() + b.close() + b.close() + self.assertRaises(ValueError, b.flush) + class BufferedReaderTest(unittest.TestCase, CommonBufferedTests): read_mode = "rb" @@ -742,6 +775,7 @@ self.assertEquals(b"abcdefg", bufio.read()) + @unittest.skipUnless(threading, 'Threading required for this test.') def test_threads(self): try: # Write out many bytes with exactly the same number of 0's, @@ -988,6 +1022,7 @@ with self.open(support.TESTFN, "rb", buffering=0) as f: self.assertEqual(f.read(), b"abc") + @unittest.skipUnless(threading, 'Threading required for this test.') def test_threads(self): try: # Write out many bytes from many threads and test they were @@ -2080,7 +2115,7 @@ with self.open(support.TESTFN, "w", errors="replace") as f: self.assertEqual(f.errors, "replace") - + @unittest.skipUnless(threading, 'Threading required for this test.') def test_threads_write(self): # Issue6750: concurrent writes could duplicate data event = threading.Event() @@ -2102,6 +2137,20 @@ for n in range(20): self.assertEquals(content.count("Thread%03d\n" % n), 1) + def test_flush_error_on_close(self): + txt = self.TextIOWrapper(self.BytesIO(self.testdata), encoding="ascii") + def bad_flush(): + raise IOError() + txt.flush = bad_flush + self.assertRaises(IOError, txt.close) # exception not swallowed + + def test_multi_close(self): + txt = self.TextIOWrapper(self.BytesIO(self.testdata), encoding="ascii") + txt.close() + txt.close() + txt.close() + self.assertRaises(ValueError, txt.flush) + class CTextIOWrapperTest(TextIOWrapperTest): def test_initialization(self): Modified: python/branches/py3k-jit/Lib/test/test_locale.py ============================================================================== --- python/branches/py3k-jit/Lib/test/test_locale.py (original) +++ python/branches/py3k-jit/Lib/test/test_locale.py Tue May 4 01:24:51 2010 @@ -236,6 +236,25 @@ self.assertRaises(ValueError, locale.format, " %f", 'foo') self.assertRaises(ValueError, locale.format, "%fg", 'foo') self.assertRaises(ValueError, locale.format, "%^g", 'foo') + self.assertRaises(ValueError, locale.format, "%f%%", 'foo') + + +class TestLocaleFormatString(unittest.TestCase): + """General tests on locale.format_string""" + + def test_percent_escape(self): + self.assertEqual(locale.format_string('%f%%', 1.0), '%f%%' % 1.0) + self.assertEqual(locale.format_string('%d %f%%d', (1, 1.0)), + '%d %f%%d' % (1, 1.0)) + self.assertEqual(locale.format_string('%(foo)s %%d', {'foo': 'bar'}), + ('%(foo)s %%d' % {'foo': 'bar'})) + + def test_mapping(self): + self.assertEqual(locale.format_string('%(foo)s bing.', {'foo': 'bar'}), + ('%(foo)s bing.' % {'foo': 'bar'})) + self.assertEqual(locale.format_string('%(foo)s', {'foo': 'bar'}), + ('%(foo)s' % {'foo': 'bar'})) + class TestNumberFormatting(BaseLocalizedTest, EnUSNumberFormatting): @@ -377,6 +396,7 @@ tests = [ TestMiscellaneous, TestFormatPatternArg, + TestLocaleFormatString, TestEnUSNumberFormatting, TestCNumberFormatting, TestFrFRNumberFormatting, Modified: python/branches/py3k-jit/Lib/test/test_logging.py ============================================================================== --- python/branches/py3k-jit/Lib/test/test_logging.py (original) +++ python/branches/py3k-jit/Lib/test/test_logging.py Tue May 4 01:24:51 2010 @@ -41,10 +41,13 @@ from test.support import captured_stdout, run_with_locale, run_unittest,\ find_unused_port import textwrap -import threading import unittest import warnings import weakref +try: + import threading +except ImportError: + threading = None class BaseTest(unittest.TestCase): @@ -765,6 +768,7 @@ self.server_close() + at unittest.skipUnless(threading, 'Threading required for this test.') class SocketHandlerTest(BaseTest): """Test for SocketHandler objects.""" @@ -1659,6 +1663,7 @@ def test_config13_failure(self): self.assertRaises(Exception, self.apply_config, self.config13) + @unittest.skipUnless(threading, 'listen() needs threading to work') def setup_via_listener(self, text): text = text.encode("utf-8") port = find_unused_port() Modified: python/branches/py3k-jit/Lib/test/test_multiprocessing.py ============================================================================== --- python/branches/py3k-jit/Lib/test/test_multiprocessing.py (original) +++ python/branches/py3k-jit/Lib/test/test_multiprocessing.py Tue May 4 01:24:51 2010 @@ -5,7 +5,6 @@ # import unittest -import threading import queue as pyqueue import time import io @@ -25,6 +24,10 @@ _multiprocessing = test.support.import_module('_multiprocessing') # Skip tests if sem_open implementation is broken. test.support.import_module('multiprocessing.synchronize') +# import threading after _multiprocessing to raise a more revelant error +# message: "No module named _multiprocessing". _multiprocessing is not compiled +# without thread support. +import threading import multiprocessing.dummy import multiprocessing.connection @@ -1253,9 +1256,9 @@ def test_rapid_restart(self): authkey = os.urandom(32) - port = test.support.find_unused_port() manager = QueueManager( - address=('localhost', port), authkey=authkey, serializer=SERIALIZER) + address=('localhost', 0), authkey=authkey, serializer=SERIALIZER) + addr = manager.get_server().address manager.start() p = self.Process(target=self._putter, args=(manager.address, authkey)) @@ -1265,7 +1268,7 @@ del queue manager.shutdown() manager = QueueManager( - address=('localhost', port), authkey=authkey, serializer=SERIALIZER) + address=addr, authkey=authkey, serializer=SERIALIZER) manager.start() manager.shutdown() Modified: python/branches/py3k-jit/Lib/test/test_poplib.py ============================================================================== --- python/branches/py3k-jit/Lib/test/test_poplib.py (original) +++ python/branches/py3k-jit/Lib/test/test_poplib.py Tue May 4 01:24:51 2010 @@ -4,15 +4,16 @@ # a real test suite import poplib -import threading import asyncore import asynchat import socket import os import time +import errno from unittest import TestCase from test import support as test_support +threading = test_support.import_module('threading') HOST = test_support.HOST PORT = 0 @@ -241,13 +242,39 @@ def __init__(self, conn): asynchat.async_chat.__init__(self, conn) ssl_socket = ssl.wrap_socket(self.socket, certfile=CERTFILE, - server_side=True) + server_side=True, + do_handshake_on_connect=False) self.del_channel() self.set_socket(ssl_socket) + # Must try handshake before calling push() + self._ssl_accepting = True + self._do_ssl_handshake() self.set_terminator(b"\r\n") self.in_buffer = [] self.push('+OK dummy pop3 server ready. ') + def _do_ssl_handshake(self): + try: + self.socket.do_handshake() + except ssl.SSLError as err: + if err.args[0] in (ssl.SSL_ERROR_WANT_READ, + ssl.SSL_ERROR_WANT_WRITE): + return + elif err.args[0] == ssl.SSL_ERROR_EOF: + return self.handle_close() + raise + except socket.error as err: + if err.args[0] == errno.ECONNABORTED: + return self.handle_close() + else: + self._ssl_accepting = False + + def handle_read(self): + if self._ssl_accepting: + self._do_ssl_handshake() + else: + DummyPOP3Handler.handle_read(self) + class TestPOP3_SSLClass(TestPOP3Class): # repeat previous tests by using poplib.POP3_SSL Modified: python/branches/py3k-jit/Lib/test/test_queue.py ============================================================================== --- python/branches/py3k-jit/Lib/test/test_queue.py (original) +++ python/branches/py3k-jit/Lib/test/test_queue.py Tue May 4 01:24:51 2010 @@ -1,10 +1,10 @@ # Some simple queue module tests, plus some failure conditions # to ensure the Queue locks remain stable. import queue -import threading import time import unittest from test import support +threading = support.import_module('threading') QUEUE_SIZE = 5 Modified: python/branches/py3k-jit/Lib/test/test_shutil.py ============================================================================== --- python/branches/py3k-jit/Lib/test/test_shutil.py (original) +++ python/branches/py3k-jit/Lib/test/test_shutil.py Tue May 4 01:24:51 2010 @@ -13,13 +13,21 @@ from distutils.spawn import find_executable, spawn from shutil import (_make_tarball, _make_zipfile, make_archive, register_archive_format, unregister_archive_format, - get_archive_formats, Error) + get_archive_formats, Error, unpack_archive, + register_unpack_format, RegistryError, + unregister_unpack_format, get_unpack_formats) import tarfile import warnings from test import support from test.support import TESTFN, check_warnings, captured_stdout +try: + import bz2 + BZ2_SUPPORTED = True +except ImportError: + BZ2_SUPPORTED = False + TESTFN2 = TESTFN + "2" try: @@ -263,35 +271,36 @@ shutil.rmtree(src_dir) shutil.rmtree(os.path.dirname(dst_dir)) - if hasattr(os, "symlink"): - def test_dont_copy_file_onto_link_to_itself(self): - # bug 851123. - os.mkdir(TESTFN) - src = os.path.join(TESTFN, 'cheese') - dst = os.path.join(TESTFN, 'shop') + @unittest.skipUnless(hasattr(os, 'symlink'), 'requires os.symlink') + def test_dont_copy_file_onto_link_to_itself(self): + # bug 851123. + os.mkdir(TESTFN) + src = os.path.join(TESTFN, 'cheese') + dst = os.path.join(TESTFN, 'shop') + try: + f = open(src, 'w') + f.write('cheddar') + f.close() + + os.link(src, dst) + self.assertRaises(shutil.Error, shutil.copyfile, src, dst) + self.assertEqual(open(src,'r').read(), 'cheddar') + os.remove(dst) + + # Using `src` here would mean we end up with a symlink pointing + # to TESTFN/TESTFN/cheese, while it should point at + # TESTFN/cheese. + os.symlink('cheese', dst) + self.assertRaises(shutil.Error, shutil.copyfile, src, dst) + self.assertEqual(open(src,'r').read(), 'cheddar') + os.remove(dst) + finally: try: - f = open(src, 'w') - f.write('cheddar') - f.close() - - os.link(src, dst) - self.assertRaises(shutil.Error, shutil.copyfile, src, dst) - self.assertEqual(open(src,'r').read(), 'cheddar') - os.remove(dst) - - # Using `src` here would mean we end up with a symlink pointing - # to TESTFN/TESTFN/cheese, while it should point at - # TESTFN/cheese. - os.symlink('cheese', dst) - self.assertRaises(shutil.Error, shutil.copyfile, src, dst) - self.assertEqual(open(src,'r').read(), 'cheddar') - os.remove(dst) - finally: - try: - shutil.rmtree(TESTFN) - except OSError: - pass + shutil.rmtree(TESTFN) + except OSError: + pass + @unittest.skipUnless(hasattr(os, 'symlink'), 'requires os.symlink') def test_rmtree_on_symlink(self): # bug 1669. os.mkdir(TESTFN) @@ -304,37 +313,38 @@ finally: shutil.rmtree(TESTFN, ignore_errors=True) - if hasattr(os, "mkfifo"): - # Issue #3002: copyfile and copytree block indefinitely on named pipes - def test_copyfile_named_pipe(self): - os.mkfifo(TESTFN) - try: - self.assertRaises(shutil.SpecialFileError, - shutil.copyfile, TESTFN, TESTFN2) - self.assertRaises(shutil.SpecialFileError, - shutil.copyfile, __file__, TESTFN) - finally: - os.remove(TESTFN) + @unittest.skipUnless(hasattr(os, 'mkfifo'), 'requires os.mkfifo') + # Issue #3002: copyfile and copytree block indefinitely on named pipes + def test_copyfile_named_pipe(self): + os.mkfifo(TESTFN) + try: + self.assertRaises(shutil.SpecialFileError, + shutil.copyfile, TESTFN, TESTFN2) + self.assertRaises(shutil.SpecialFileError, + shutil.copyfile, __file__, TESTFN) + finally: + os.remove(TESTFN) - def test_copytree_named_pipe(self): - os.mkdir(TESTFN) - try: - subdir = os.path.join(TESTFN, "subdir") - os.mkdir(subdir) - pipe = os.path.join(subdir, "mypipe") - os.mkfifo(pipe) - try: - shutil.copytree(TESTFN, TESTFN2) - except shutil.Error as e: - errors = e.args[0] - self.assertEqual(len(errors), 1) - src, dst, error_msg = errors[0] - self.assertEqual("`%s` is a named pipe" % pipe, error_msg) - else: - self.fail("shutil.Error should have been raised") - finally: - shutil.rmtree(TESTFN, ignore_errors=True) - shutil.rmtree(TESTFN2, ignore_errors=True) + @unittest.skipUnless(hasattr(os, 'mkfifo'), 'requires os.mkfifo') + def test_copytree_named_pipe(self): + os.mkdir(TESTFN) + try: + subdir = os.path.join(TESTFN, "subdir") + os.mkdir(subdir) + pipe = os.path.join(subdir, "mypipe") + os.mkfifo(pipe) + try: + shutil.copytree(TESTFN, TESTFN2) + except shutil.Error as e: + errors = e.args[0] + self.assertEqual(len(errors), 1) + src, dst, error_msg = errors[0] + self.assertEqual("`%s` is a named pipe" % pipe, error_msg) + else: + self.fail("shutil.Error should have been raised") + finally: + shutil.rmtree(TESTFN, ignore_errors=True) + shutil.rmtree(TESTFN2, ignore_errors=True) def test_copytree_special_func(self): @@ -351,6 +361,7 @@ shutil.copytree(src_dir, dst_dir, copy_function=_copy) self.assertEquals(len(copied), 2) + @unittest.skipUnless(hasattr(os, 'symlink'), 'requires os.symlink') def test_copytree_dangling_symlinks(self): # a dangling symlink raises an error at the end @@ -535,6 +546,7 @@ owner='kjhkjhkjg', group='oihohoh') self.assertTrue(os.path.exists(res)) + @unittest.skipUnless(zlib, "Requires zlib") @unittest.skipUnless(UID_GID_SUPPORT, "Requires grp and pwd support") def test_tarfile_root_owner(self): @@ -592,6 +604,61 @@ formats = [name for name, params in get_archive_formats()] self.assertNotIn('xxx', formats) + def _compare_dirs(self, dir1, dir2): + # check that dir1 and dir2 are equivalent, + # return the diff + diff = [] + for root, dirs, files in os.walk(dir1): + for file_ in files: + path = os.path.join(root, file_) + target_path = os.path.join(dir2, os.path.split(path)[-1]) + if not os.path.exists(target_path): + diff.append(file_) + return diff + + @unittest.skipUnless(zlib, "Requires zlib") + def test_unpack_archive(self): + formats = ['tar', 'gztar', 'zip'] + if BZ2_SUPPORTED: + formats.append('bztar') + + for format in formats: + tmpdir = self.mkdtemp() + base_dir, root_dir, base_name = self._create_files() + tmpdir2 = self.mkdtemp() + filename = make_archive(base_name, format, root_dir, base_dir) + + # let's try to unpack it now + unpack_archive(filename, tmpdir2) + diff = self._compare_dirs(tmpdir, tmpdir2) + self.assertEquals(diff, []) + + def test_unpack_registery(self): + + formats = get_unpack_formats() + + def _boo(filename, extract_dir, extra): + self.assertEquals(extra, 1) + self.assertEquals(filename, 'stuff.boo') + self.assertEquals(extract_dir, 'xx') + + register_unpack_format('Boo', ['.boo', '.b2'], _boo, [('extra', 1)]) + unpack_archive('stuff.boo', 'xx') + + # trying to register a .boo unpacker again + self.assertRaises(RegistryError, register_unpack_format, 'Boo2', + ['.boo'], _boo) + + # should work now + unregister_unpack_format('Boo') + register_unpack_format('Boo2', ['.boo'], _boo) + self.assertIn(('Boo2', ['.boo'], ''), get_unpack_formats()) + self.assertNotIn(('Boo', ['.boo'], ''), get_unpack_formats()) + + # let's leave a clean state + unregister_unpack_format('Boo2') + self.assertEquals(get_unpack_formats(), formats) + class TestMove(unittest.TestCase): Modified: python/branches/py3k-jit/Lib/test/test_smtplib.py ============================================================================== --- python/branches/py3k-jit/Lib/test/test_smtplib.py (original) +++ python/branches/py3k-jit/Lib/test/test_smtplib.py Tue May 4 01:24:51 2010 @@ -1,7 +1,6 @@ import asyncore import email.utils import socket -import threading import smtpd import smtplib import io @@ -9,9 +8,14 @@ import time import select -from unittest import TestCase +import unittest from test import support +try: + import threading +except ImportError: + threading = None + HOST = support.HOST if sys.platform == 'darwin': @@ -44,7 +48,8 @@ serv.close() evt.set() -class GeneralTests(TestCase): + at unittest.skipUnless(threading, 'Threading required for this test.') +class GeneralTests(unittest.TestCase): def setUp(self): self._threads = support.threading_setup() @@ -146,7 +151,8 @@ # test server times out, causing the test to fail. # Test behavior of smtpd.DebuggingServer -class DebuggingServerTests(TestCase): + at unittest.skipUnless(threading, 'Threading required for this test.') +class DebuggingServerTests(unittest.TestCase): def setUp(self): # temporarily replace sys.stdout to capture DebuggingServer output @@ -157,8 +163,10 @@ self._threads = support.threading_setup() self.serv_evt = threading.Event() self.client_evt = threading.Event() - self.port = support.find_unused_port() - self.serv = smtpd.DebuggingServer((HOST, self.port), ('nowhere', -1)) + # Pick a random unused port by passing 0 for the port number + self.serv = smtpd.DebuggingServer((HOST, 0), ('nowhere', -1)) + # Keep a note of what port was assigned + self.port = self.serv.socket.getsockname()[1] serv_args = (self.serv, self.serv_evt, self.client_evt) self.thread = threading.Thread(target=debugging_server, args=serv_args) self.thread.start() @@ -241,7 +249,7 @@ self.assertEqual(self.output.getvalue(), mexpect) -class NonConnectingTests(TestCase): +class NonConnectingTests(unittest.TestCase): def testNotConnected(self): # Test various operations on an unconnected SMTP object that @@ -262,7 +270,8 @@ # test response of client to a non-successful HELO message -class BadHELOServerTests(TestCase): + at unittest.skipUnless(threading, 'Threading required for this test.') +class BadHELOServerTests(unittest.TestCase): def setUp(self): self.old_stdout = sys.stdout @@ -386,14 +395,17 @@ # Test various SMTP & ESMTP commands/behaviors that require a simulated server # (i.e., something with more features than DebuggingServer) -class SMTPSimTests(TestCase): + at unittest.skipUnless(threading, 'Threading required for this test.') +class SMTPSimTests(unittest.TestCase): def setUp(self): self._threads = support.threading_setup() self.serv_evt = threading.Event() self.client_evt = threading.Event() - self.port = support.find_unused_port() - self.serv = SimSMTPServer((HOST, self.port), ('nowhere', -1)) + # Pick a random unused port by passing 0 for the port number + self.serv = SimSMTPServer((HOST, 0), ('nowhere', -1)) + # Keep a note of what port was assigned + self.port = self.serv.socket.getsockname()[1] serv_args = (self.serv, self.serv_evt, self.client_evt) self.thread = threading.Thread(target=debugging_server, args=serv_args) self.thread.start() Modified: python/branches/py3k-jit/Lib/test/test_socket.py ============================================================================== --- python/branches/py3k-jit/Lib/test/test_socket.py (original) +++ python/branches/py3k-jit/Lib/test/test_socket.py Tue May 4 01:24:51 2010 @@ -7,8 +7,6 @@ import io import socket import select -import _thread as thread -import threading import time import traceback import queue @@ -21,6 +19,13 @@ HOST = support.HOST MSG = b'Michael Gilfix was here\n' +try: + import _thread as thread + import threading +except ImportError: + thread = None + threading = None + class SocketTCPTest(unittest.TestCase): def setUp(self): @@ -560,6 +565,7 @@ s.ioctl(socket.SIO_KEEPALIVE_VALS, (1, 100, 100)) + at unittest.skipUnless(thread, 'Threading required for this test.') class BasicTCPTest(SocketConnectedTest): def __init__(self, methodName='runTest'): @@ -649,6 +655,7 @@ self.serv_conn.send(MSG) self.serv_conn.shutdown(2) + at unittest.skipUnless(thread, 'Threading required for this test.') class BasicUDPTest(ThreadedUDPSocketTest): def __init__(self, methodName='runTest'): @@ -677,6 +684,7 @@ def _testRecvFromNegative(self): self.cli.sendto(MSG, 0, (HOST, self.port)) + at unittest.skipUnless(thread, 'Threading required for this test.') class TCPCloserTest(ThreadedTCPSocketTest): def testClose(self): @@ -696,6 +704,7 @@ self.cli.connect((HOST, self.port)) time.sleep(1.0) + at unittest.skipUnless(thread, 'Threading required for this test.') class BasicSocketPairTest(SocketPairTest): def __init__(self, methodName='runTest'): @@ -715,6 +724,7 @@ msg = self.cli.recv(1024) self.assertEqual(msg, MSG) + at unittest.skipUnless(thread, 'Threading required for this test.') class NonBlockingTCPTests(ThreadedTCPSocketTest): def __init__(self, methodName='runTest'): @@ -783,6 +793,7 @@ time.sleep(0.1) self.cli.send(MSG) + at unittest.skipUnless(thread, 'Threading required for this test.') class FileObjectClassTestCase(SocketConnectedTest): """Unit tests for the object returned by socket.makefile() @@ -1098,6 +1109,7 @@ lambda: socket.create_connection((HOST, port)) ) + at unittest.skipUnless(thread, 'Threading required for this test.') class NetworkConnectionAttributesTest(SocketTCPTest, ThreadableTest): def __init__(self, methodName='runTest'): @@ -1160,6 +1172,7 @@ self.cli = socket.create_connection((HOST, self.port), 30) self.assertEqual(self.cli.gettimeout(), 30) + at unittest.skipUnless(thread, 'Threading required for this test.') class NetworkConnectionBehaviourTest(SocketTCPTest, ThreadableTest): def __init__(self, methodName='runTest'): @@ -1305,6 +1318,7 @@ self.assertRaises(socket.error, s.bind, address) + at unittest.skipUnless(thread, 'Threading required for this test.') class BufferIOTest(SocketConnectedTest): """ Test the buffer versions of socket.recv() and socket.send(). Modified: python/branches/py3k-jit/Lib/test/test_socketserver.py ============================================================================== --- python/branches/py3k-jit/Lib/test/test_socketserver.py (original) +++ python/branches/py3k-jit/Lib/test/test_socketserver.py Tue May 4 01:24:51 2010 @@ -9,12 +9,15 @@ import signal import socket import tempfile -import threading import unittest import socketserver import test.support from test.support import reap_children, reap_threads, verbose +try: + import threading +except ImportError: + threading = None test.support.requires("network") @@ -119,6 +122,7 @@ self.assertEquals(server.server_address, server.socket.getsockname()) return server + @unittest.skipUnless(threading, 'Threading required for this test.') @reap_threads def run_server(self, svrcls, hdlrbase, testfunc): server = self.make_server(self.pickaddr(svrcls.address_family), @@ -241,6 +245,31 @@ # socketserver.DatagramRequestHandler, # self.dgram_examine) + @reap_threads + def test_shutdown(self): + # Issue #2302: shutdown() should always succeed in making an + # other thread leave serve_forever(). + class MyServer(socketserver.TCPServer): + pass + + class MyHandler(socketserver.StreamRequestHandler): + pass + + threads = [] + for i in range(20): + s = MyServer((HOST, 0), MyHandler) + t = threading.Thread( + name='MyServer serving', + target=s.serve_forever, + kwargs={'poll_interval':0.01}) + t.daemon = True # In case this function raises. + threads.append((t, s)) + for t, s in threads: + t.start() + s.shutdown() + for t, s in threads: + t.join() + def test_main(): if imp.lock_held(): Modified: python/branches/py3k-jit/Lib/test/test_ssl.py ============================================================================== --- python/branches/py3k-jit/Lib/test/test_ssl.py (original) +++ python/branches/py3k-jit/Lib/test/test_ssl.py Tue May 4 01:24:51 2010 @@ -6,11 +6,14 @@ import socket import select import time +import gc import os +import errno import pprint import urllib.parse, urllib.request import traceback import asyncore +import weakref from http.server import HTTPServer, SimpleHTTPRequestHandler @@ -33,28 +36,7 @@ class BasicTests(unittest.TestCase): - def testSSLconnect(self): - if not support.is_resource_enabled('network'): - return - s = ssl.wrap_socket(socket.socket(socket.AF_INET), - cert_reqs=ssl.CERT_NONE) - s.connect(("svn.python.org", 443)) - c = s.getpeercert() - if c: - raise support.TestFailed("Peer cert %s shouldn't be here!") - s.close() - - # this should fail because we have no verification certs - s = ssl.wrap_socket(socket.socket(socket.AF_INET), - cert_reqs=ssl.CERT_REQUIRED) - try: - s.connect(("svn.python.org", 443)) - except ssl.SSLError: - pass - finally: - s.close() - - def testCrucialConstants(self): + def test_constants(self): ssl.PROTOCOL_SSLv2 ssl.PROTOCOL_SSLv23 ssl.PROTOCOL_SSLv3 @@ -63,7 +45,7 @@ ssl.CERT_OPTIONAL ssl.CERT_REQUIRED - def testRAND(self): + def test_random(self): v = ssl.RAND_status() if support.verbose: sys.stdout.write("\n RAND_status is %d (%s)\n" @@ -77,7 +59,7 @@ print("didn't raise TypeError") ssl.RAND_add("this is a random string", 75.0) - def testParseCert(self): + def test_parse_cert(self): # note that this uses an 'unofficial' function in _ssl.c, # provided solely for this test, to exercise the certificate # parsing code @@ -85,14 +67,17 @@ if support.verbose: sys.stdout.write("\n" + pprint.pformat(p) + "\n") - def testDERtoPEM(self): - - pem = open(SVN_PYTHON_ORG_ROOT_CERT, 'r').read() + def test_DER_to_PEM(self): + with open(SVN_PYTHON_ORG_ROOT_CERT, 'r') as f: + pem = f.read() d1 = ssl.PEM_cert_to_DER_cert(pem) p2 = ssl.DER_cert_to_PEM_cert(d1) d2 = ssl.PEM_cert_to_DER_cert(p2) - if (d1 != d2): - raise support.TestFailed("PEM-to-DER or DER-to-PEM translation failed") + self.assertEqual(d1, d2) + if not p2.startswith(ssl.PEM_HEADER + '\n'): + self.fail("DER-to-PEM didn't include correct header:\n%r\n" % p2) + if not p2.endswith('\n' + ssl.PEM_FOOTER + '\n'): + self.fail("DER-to-PEM didn't include correct footer:\n%r\n" % p2) def test_openssl_version(self): n = ssl.OPENSSL_VERSION_NUMBER @@ -138,16 +123,35 @@ with self.assertRaisesRegexp(ssl.SSLError, "No cipher can be selected"): s.connect(remote) + @support.cpython_only + def test_refcycle(self): + # Issue #7943: an SSL object doesn't create reference cycles with + # itself. + s = socket.socket(socket.AF_INET) + ss = ssl.wrap_socket(s) + wr = weakref.ref(ss) + del ss + self.assertEqual(wr(), None) + + def test_timeout(self): + # Issue #8524: when creating an SSL socket, the timeout of the + # original socket should be retained. + for timeout in (None, 0.0, 5.0): + s = socket.socket(socket.AF_INET) + s.settimeout(timeout) + ss = ssl.wrap_socket(s) + self.assertEqual(timeout, ss.gettimeout()) + class NetworkedTests(unittest.TestCase): - def testConnect(self): + def test_connect(self): s = ssl.wrap_socket(socket.socket(socket.AF_INET), cert_reqs=ssl.CERT_NONE) s.connect(("svn.python.org", 443)) c = s.getpeercert() if c: - raise support.TestFailed("Peer cert %s shouldn't be here!") + self.fail("Peer cert %s shouldn't be here!") s.close() # this should fail because we have no verification certs @@ -166,12 +170,29 @@ ca_certs=SVN_PYTHON_ORG_ROOT_CERT) try: s.connect(("svn.python.org", 443)) - except ssl.SSLError as x: - raise support.TestFailed("Unexpected exception %s" % x) finally: s.close() - def testNonBlockingHandshake(self): + @unittest.skipIf(os.name == "nt", "Can't use a socket as a file under Windows") + def test_makefile_close(self): + # Issue #5238: creating a file-like object with makefile() shouldn't + # delay closing the underlying "real socket" (here tested with its + # file descriptor, hence skipping the test under Windows). + ss = ssl.wrap_socket(socket.socket(socket.AF_INET)) + ss.connect(("svn.python.org", 443)) + fd = ss.fileno() + f = ss.makefile() + f.close() + # The fd is still open + os.read(fd, 0) + # Closing the SSL socket should close the fd too + ss.close() + gc.collect() + with self.assertRaises(OSError) as e: + os.read(fd, 0) + self.assertEqual(e.exception.errno, errno.EBADF) + + def test_non_blocking_handshake(self): s = socket.socket(socket.AF_INET) s.connect(("svn.python.org", 443)) s.setblocking(False) @@ -195,11 +216,10 @@ if support.verbose: sys.stdout.write("\nNeeded %d calls to do_handshake() to establish session.\n" % count) - def testFetchServerCert(self): - + def test_get_server_certificate(self): pem = ssl.get_server_certificate(("svn.python.org", 443)) if not pem: - raise support.TestFailed("No server certificate on svn.python.org:443!") + self.fail("No server certificate on svn.python.org:443!") return @@ -210,11 +230,11 @@ if support.verbose: sys.stdout.write("%s\n" % x) else: - raise support.TestFailed("Got server certificate %s for svn.python.org!" % pem) + self.fail("Got server certificate %s for svn.python.org!" % pem) pem = ssl.get_server_certificate(("svn.python.org", 443), ca_certs=SVN_PYTHON_ORG_ROOT_CERT) if not pem: - raise support.TestFailed("No server certificate on svn.python.org:443!") + self.fail("No server certificate on svn.python.org:443!") if support.verbose: sys.stdout.write("\nVerified certificate for svn.python.org:443 is\n%s\n" % pem) @@ -247,7 +267,6 @@ except ImportError: _have_threads = False else: - _have_threads = True class ThreadedEchoServer(threading.Thread): @@ -268,7 +287,7 @@ threading.Thread.__init__(self) self.daemon = True - def wrap_conn (self): + def wrap_conn(self): try: self.sslconn = ssl.wrap_socket(self.sock, server_side=True, certfile=self.server.certificate, @@ -276,19 +295,16 @@ ca_certs=self.server.cacerts, cert_reqs=self.server.certreqs, ciphers=self.server.ciphers) - except: + except ssl.SSLError: + # XXX Various errors can have happened here, for example + # a mismatching protocol version, an invalid certificate, + # or a low-level bug. This should be made more discriminating. if self.server.chatty: handle_error("\n server: bad connection attempt from " + repr(self.addr) + ":\n") - if not self.server.expect_bad_connects: - # here, we want to stop the server, because this shouldn't - # happen in the context of our test case - self.running = False - # normally, we'd just stop here, but for the test - # harness, we want to stop the server - self.server.stop() + self.running = False + self.server.stop() self.close() return False - else: if self.server.certreqs == ssl.CERT_REQUIRED: cert = self.sslconn.getpeercert() @@ -320,7 +336,7 @@ else: self.sock.close() - def run (self): + def run(self): self.running = True if not self.server.starttls_server: if not self.wrap_conn(): @@ -328,28 +344,28 @@ while self.running: try: msg = self.read() - amsg = (msg and str(msg, 'ASCII', 'strict')) or '' - if not msg: + stripped = msg.strip() + if not stripped: # eof, so quit this handler self.running = False self.close() - elif amsg.strip() == 'over': + elif stripped == b'over': if support.verbose and self.server.connectionchatty: sys.stdout.write(" server: client closed connection\n") self.close() return elif (self.server.starttls_server and - amsg.strip() == 'STARTTLS'): + stripped == b'STARTTLS'): if support.verbose and self.server.connectionchatty: sys.stdout.write(" server: read STARTTLS from client, sending OK...\n") - self.write("OK\n".encode("ASCII", "strict")) + self.write(b"OK\n") if not self.wrap_conn(): return elif (self.server.starttls_server and self.sslconn - and amsg.strip() == 'ENDTLS'): + and stripped == b'ENDTLS'): if support.verbose and self.server.connectionchatty: sys.stdout.write(" server: read ENDTLS from client, sending OK...\n") - self.write("OK\n".encode("ASCII", "strict")) + self.write(b"OK\n") self.sock = self.sslconn.unwrap() self.sslconn = None if support.verbose and self.server.connectionchatty: @@ -358,9 +374,9 @@ if (support.verbose and self.server.connectionchatty): ctype = (self.sslconn and "encrypted") or "unencrypted" - sys.stdout.write(" server: read %s (%s), sending back %s (%s)...\n" - % (repr(msg), ctype, repr(msg.lower()), ctype)) - self.write(amsg.lower().encode('ASCII', 'strict')) + sys.stdout.write(" server: read %r (%s), sending back %r (%s)...\n" + % (msg, ctype, msg.lower(), ctype)) + self.write(msg.lower()) except socket.error: if self.server.chatty: handle_error("Test server failure:\n") @@ -369,11 +385,9 @@ # normally, we'd just stop here, but for the test # harness, we want to stop the server self.server.stop() - except: - handle_error('') def __init__(self, certificate, ssl_version=None, - certreqs=None, cacerts=None, expect_bad_connects=False, + certreqs=None, cacerts=None, chatty=True, connectionchatty=False, starttls_server=False, ciphers=None): if ssl_version is None: @@ -385,7 +399,6 @@ self.certreqs = certreqs self.cacerts = cacerts self.ciphers = ciphers - self.expect_bad_connects = expect_bad_connects self.chatty = chatty self.connectionchatty = connectionchatty self.starttls_server = starttls_server @@ -396,12 +409,12 @@ threading.Thread.__init__(self) self.daemon = True - def start (self, flag=None): + def start(self, flag=None): self.flag = flag threading.Thread.start(self) - def run (self): - self.sock.settimeout(0.5) + def run(self): + self.sock.settimeout(0.05) self.sock.listen(5) self.active = True if self.flag: @@ -419,12 +432,9 @@ pass except KeyboardInterrupt: self.stop() - except: - if self.chatty: - handle_error("Test server failure:\n") self.sock.close() - def stop (self): + def stop(self): self.active = False class OurHTTPSServer(threading.Thread): @@ -434,12 +444,9 @@ class HTTPSServer(HTTPServer): def __init__(self, server_address, RequestHandlerClass, certfile): - HTTPServer.__init__(self, server_address, RequestHandlerClass) # we assume the certfile contains both private key and certificate self.certfile = certfile - self.active = False - self.active_lock = threading.Lock() self.allow_reuse_address = True def __str__(self): @@ -448,58 +455,14 @@ self.server_name, self.server_port)) - def get_request (self): + def get_request(self): # override this to wrap socket with SSL sock, addr = self.socket.accept() sslconn = ssl.wrap_socket(sock, server_side=True, certfile=self.certfile) return sslconn, addr - # The methods overridden below this are mainly so that we - # can run it in a thread and be able to stop it from another - # You probably wouldn't need them in other uses. - - def server_activate(self): - # We want to run this in a thread for testing purposes, - # so we override this to set timeout, so that we get - # a chance to stop the server - self.socket.settimeout(0.5) - HTTPServer.server_activate(self) - - def serve_forever(self): - # We want this to run in a thread, so we use a slightly - # modified version of "forever". - self.active = True - while 1: - try: - # We need to lock while handling the request. - # Another thread can close the socket after self.active - # has been checked and before the request is handled. - # This causes an exception when using the closed socket. - with self.active_lock: - if not self.active: - break - self.handle_request() - except socket.timeout: - pass - except KeyboardInterrupt: - self.server_close() - return - except: - sys.stdout.write(''.join(traceback.format_exception(*sys.exc_info()))) - break - time.sleep(0.1) - - def server_close(self): - # Again, we want this to run in a thread, so we need to override - # close to clear the "active" flag, so that serve_forever() will - # terminate. - with self.active_lock: - HTTPServer.server_close(self) - self.active = False - class RootedHTTPRequestHandler(SimpleHTTPRequestHandler): - # need to override translate_path to get a known root, # instead of using os.curdir, since the test could be # run from anywhere @@ -530,7 +493,6 @@ return path def log_message(self, format, *args): - # we override this to suppress logging unless "verbose" if support.verbose: @@ -544,31 +506,27 @@ def __init__(self, certfile): self.flag = None - self.active = False self.RootedHTTPRequestHandler.root = os.path.split(CERTFILE)[0] - self.port = support.find_unused_port() self.server = self.HTTPSServer( - (HOST, self.port), self.RootedHTTPRequestHandler, certfile) + (HOST, 0), self.RootedHTTPRequestHandler, certfile) + self.port = self.server.server_port threading.Thread.__init__(self) self.daemon = True def __str__(self): return "<%s %s>" % (self.__class__.__name__, self.server) - def start (self, flag=None): + def start(self, flag=None): self.flag = flag threading.Thread.start(self) - def run (self): - self.active = True + def run(self): if self.flag: self.flag.set() - self.server.serve_forever() - self.active = False + self.server.serve_forever(0.05) - def stop (self): - self.active = False - self.server.server_close() + def stop(self): + self.server.shutdown() class AsyncoreEchoServer(threading.Thread): @@ -584,11 +542,8 @@ certfile=certfile, do_handshake_on_connect=False) asyncore.dispatcher_with_send.__init__(self, self.socket) - # now we have to do the handshake - # we'll just do it the easy way, and block the connection - # till it's finished. If we were doing it right, we'd - # do this in multiple calls to handle_read... - self.do_handshake(block=True) + self._ssl_accepting = True + self._do_ssl_handshake() def readable(self): if isinstance(self.socket, ssl.SSLSocket): @@ -596,14 +551,33 @@ self.handle_read_event() return True + def _do_ssl_handshake(self): + try: + self.socket.do_handshake() + except ssl.SSLError as err: + if err.args[0] in (ssl.SSL_ERROR_WANT_READ, + ssl.SSL_ERROR_WANT_WRITE): + return + elif err.args[0] == ssl.SSL_ERROR_EOF: + return self.handle_close() + raise + except socket.error as err: + if err.args[0] == errno.ECONNABORTED: + return self.handle_close() + else: + self._ssl_accepting = False + def handle_read(self): - data = self.recv(1024) - if support.verbose: - sys.stdout.write(" server: read %s from client\n" % repr(data)) - if not data: - self.close() + if self._ssl_accepting: + self._do_ssl_handshake() else: - self.send(str(data, 'ASCII', 'strict').lower().encode('ASCII', 'strict')) + data = self.recv(1024) + if support.verbose: + sys.stdout.write(" server: read %s from client\n" % repr(data)) + if not data: + self.close() + else: + self.send(data.lower()) def handle_close(self): self.close() @@ -613,12 +587,11 @@ def handle_error(self): raise - def __init__(self, port, certfile): - self.port = port + def __init__(self, certfile): self.certfile = certfile - asyncore.dispatcher.__init__(self) - self.create_socket(socket.AF_INET, socket.SOCK_STREAM) - self.bind(('', port)) + sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) + self.port = support.bind_port(sock, '') + asyncore.dispatcher.__init__(self, sock) self.listen(5) def handle_accept(self): @@ -633,8 +606,8 @@ def __init__(self, certfile): self.flag = None self.active = False - self.port = support.find_unused_port() - self.server = self.EchoServer(self.port, certfile) + self.server = self.EchoServer(certfile) + self.port = self.server.port threading.Thread.__init__(self) self.daemon = True @@ -645,7 +618,7 @@ self.flag = flag threading.Thread.start(self) - def run (self): + def run(self): self.active = True if self.flag: self.flag.set() @@ -655,11 +628,15 @@ except: pass - def stop (self): + def stop(self): self.active = False self.server.close() - def badCertTest (certfile): + def bad_cert_test(certfile): + """ + Launch a server with CERT_REQUIRED, and check that trying to + connect to it with the given client certificate fails. + """ server = ThreadedEchoServer(CERTFILE, certreqs=ssl.CERT_REQUIRED, cacerts=CERTFILE, chatty=False, @@ -677,22 +654,23 @@ s.connect((HOST, server.port)) except ssl.SSLError as x: if support.verbose: - sys.stdout.write("\nSSLError is %s\n" % x) + sys.stdout.write("\nSSLError is %s\n" % x.args[1]) except socket.error as x: if support.verbose: - sys.stdout.write("\nsocket.error is %s\n" % x) + sys.stdout.write("\nsocket.error is %s\n" % x[1]) else: - raise support.TestFailed( - "Use of invalid cert should have failed!") + self.fail("Use of invalid cert should have failed!") finally: server.stop() server.join() - def serverParamsTest (certfile, protocol, certreqs, cacertsfile, - client_certfile, client_protocol=None, - indata="FOO\n", - ciphers=None, chatty=False, connectionchatty=False): - + def server_params_test(certfile, protocol, certreqs, cacertsfile, + client_certfile, client_protocol=None, indata=b"FOO\n", + ciphers=None, chatty=True, connectionchatty=False): + """ + Launch a server, connect a client to it and try various reads + and writes. + """ server = ThreadedEchoServer(certfile, certreqs=certreqs, ssl_version=protocol, @@ -709,36 +687,28 @@ client_protocol = protocol try: s = ssl.wrap_socket(socket.socket(), - server_side=False, certfile=client_certfile, ca_certs=cacertsfile, - cert_reqs=certreqs, ciphers=ciphers, + cert_reqs=certreqs, ssl_version=client_protocol) s.connect((HOST, server.port)) - except ssl.SSLError as x: - raise support.TestFailed("Unexpected SSL error: " + str(x)) - except Exception as x: - raise support.TestFailed("Unexpected exception: " + str(x)) - else: - bindata = indata.encode('ASCII', 'strict') - for arg in [bindata, bytearray(bindata), memoryview(bindata)]: + for arg in [indata, bytearray(indata), memoryview(indata)]: if connectionchatty: if support.verbose: sys.stdout.write( - " client: sending %s...\n" % (repr(indata))) + " client: sending %r...\n" % indata) s.write(arg) outdata = s.read() if connectionchatty: if support.verbose: - sys.stdout.write(" client: read %s\n" % repr(outdata)) - outdata = str(outdata, 'ASCII', 'strict') + sys.stdout.write(" client: read %r\n" % outdata) if outdata != indata.lower(): - raise support.TestFailed( - "bad data <<%s>> (%d) received; expected <<%s>> (%d)\n" - % (repr(outdata[:min(len(outdata),20)]), len(outdata), - repr(indata[:min(len(indata),20)].lower()), len(indata))) - s.write("over\n".encode("ASCII", "strict")) + self.fail( + "bad data <<%r>> (%d) received; expected <<%r>> (%d)\n" + % (outdata[:20], len(outdata), + indata[:20].lower(), len(indata))) + s.write(b"over\n") if connectionchatty: if support.verbose: sys.stdout.write(" client: closing connection.\n") @@ -747,22 +717,19 @@ server.stop() server.join() - def tryProtocolCombo (server_protocol, - client_protocol, - expectedToWork, - certsreqs=None): - + def try_protocol_combo(server_protocol, + client_protocol, + expect_success, + certsreqs=None): if certsreqs is None: certsreqs = ssl.CERT_NONE - - if certsreqs == ssl.CERT_NONE: - certtype = "CERT_NONE" - elif certsreqs == ssl.CERT_OPTIONAL: - certtype = "CERT_OPTIONAL" - elif certsreqs == ssl.CERT_REQUIRED: - certtype = "CERT_REQUIRED" + certtype = { + ssl.CERT_NONE: "CERT_NONE", + ssl.CERT_OPTIONAL: "CERT_OPTIONAL", + ssl.CERT_REQUIRED: "CERT_REQUIRED", + }[certsreqs] if support.verbose: - formatstr = (expectedToWork and " %s->%s %s\n") or " {%s->%s} %s\n" + formatstr = (expect_success and " %s->%s %s\n") or " {%s->%s} %s\n" sys.stdout.write(formatstr % (ssl.get_protocol_name(client_protocol), ssl.get_protocol_name(server_protocol), @@ -771,16 +738,21 @@ # NOTE: we must enable "ALL" ciphers, otherwise an SSLv23 client # will send an SSLv3 hello (rather than SSLv2) starting from # OpenSSL 1.0.0 (see issue #8322). - serverParamsTest(CERTFILE, server_protocol, certsreqs, - CERTFILE, CERTFILE, client_protocol, - ciphers="ALL", - chatty=False, connectionchatty=False) - except support.TestFailed: - if expectedToWork: + server_params_test(CERTFILE, server_protocol, certsreqs, + CERTFILE, CERTFILE, client_protocol, + ciphers="ALL", chatty=False, + connectionchatty=False) + # Protocol mismatch can result in either an SSLError, or a + # "Connection reset by peer" error. + except ssl.SSLError: + if expect_success: + raise + except socket.error as e: + if expect_success or e.errno != errno.ECONNRESET: raise else: - if not expectedToWork: - raise support.TestFailed( + if not expect_success: + self.fail( "Client protocol %s succeeded with server protocol %s!" % (ssl.get_protocol_name(client_protocol), ssl.get_protocol_name(server_protocol))) @@ -788,16 +760,15 @@ class ThreadedTests(unittest.TestCase): - def testEcho (self): - + def test_echo(self): + """Basic test of an SSL client connecting to a server""" if support.verbose: sys.stdout.write("\n") - serverParamsTest(CERTFILE, ssl.PROTOCOL_TLSv1, ssl.CERT_NONE, - CERTFILE, CERTFILE, ssl.PROTOCOL_TLSv1, - chatty=True, connectionchatty=True) - - def testReadCert(self): + server_params_test(CERTFILE, ssl.PROTOCOL_TLSv1, ssl.CERT_NONE, + CERTFILE, CERTFILE, ssl.PROTOCOL_TLSv1, + chatty=True, connectionchatty=True) + def test_getpeercert(self): if support.verbose: sys.stdout.write("\n") s2 = socket.socket() @@ -812,151 +783,148 @@ flag.wait() # try to connect try: - try: - s = ssl.wrap_socket(socket.socket(), - certfile=CERTFILE, - ca_certs=CERTFILE, - cert_reqs=ssl.CERT_REQUIRED, - ssl_version=ssl.PROTOCOL_SSLv23) - s.connect((HOST, server.port)) - except ssl.SSLError as x: - raise support.TestFailed( - "Unexpected SSL error: " + str(x)) - except Exception as x: - raise support.TestFailed( - "Unexpected exception: " + str(x)) - else: - if not s: - raise support.TestFailed( - "Can't SSL-handshake with test server") - cert = s.getpeercert() - if not cert: - raise support.TestFailed( - "Can't get peer certificate.") - cipher = s.cipher() - if support.verbose: - sys.stdout.write(pprint.pformat(cert) + '\n') - sys.stdout.write("Connection cipher is " + str(cipher) + '.\n') - if 'subject' not in cert: - raise support.TestFailed( - "No subject field in certificate: %s." % - pprint.pformat(cert)) - if ((('organizationName', 'Python Software Foundation'),) - not in cert['subject']): - raise support.TestFailed( - "Missing or invalid 'organizationName' field in certificate subject; " - "should be 'Python Software Foundation'.") - s.close() + s = ssl.wrap_socket(socket.socket(), + certfile=CERTFILE, + ca_certs=CERTFILE, + cert_reqs=ssl.CERT_REQUIRED, + ssl_version=ssl.PROTOCOL_SSLv23) + s.connect((HOST, server.port)) + cert = s.getpeercert() + self.assertTrue(cert, "Can't get peer certificate.") + cipher = s.cipher() + if support.verbose: + sys.stdout.write(pprint.pformat(cert) + '\n') + sys.stdout.write("Connection cipher is " + str(cipher) + '.\n') + if 'subject' not in cert: + self.fail("No subject field in certificate: %s." % + pprint.pformat(cert)) + if ((('organizationName', 'Python Software Foundation'),) + not in cert['subject']): + self.fail( + "Missing or invalid 'organizationName' field in certificate subject; " + "should be 'Python Software Foundation'.") + s.close() finally: server.stop() server.join() - def testNULLcert(self): - badCertTest(os.path.join(os.path.dirname(__file__) or os.curdir, - "nullcert.pem")) - def testMalformedCert(self): - badCertTest(os.path.join(os.path.dirname(__file__) or os.curdir, - "badcert.pem")) - def testWrongCert(self): - badCertTest(os.path.join(os.path.dirname(__file__) or os.curdir, - "wrongcert.pem")) - def testMalformedKey(self): - badCertTest(os.path.join(os.path.dirname(__file__) or os.curdir, - "badkey.pem")) - - def testRudeShutdown(self): - + def test_empty_cert(self): + """Connecting with an empty cert file""" + bad_cert_test(os.path.join(os.path.dirname(__file__) or os.curdir, + "nullcert.pem")) + def test_malformed_cert(self): + """Connecting with a badly formatted certificate (syntax error)""" + bad_cert_test(os.path.join(os.path.dirname(__file__) or os.curdir, + "badcert.pem")) + def test_nonexisting_cert(self): + """Connecting with a non-existing cert file""" + bad_cert_test(os.path.join(os.path.dirname(__file__) or os.curdir, + "wrongcert.pem")) + def test_malformed_key(self): + """Connecting with a badly formatted key (syntax error)""" + bad_cert_test(os.path.join(os.path.dirname(__file__) or os.curdir, + "badkey.pem")) + + def test_rude_shutdown(self): + """A brutal shutdown of an SSL server should raise an IOError + in the client when attempting handshake. + """ listener_ready = threading.Event() listener_gone = threading.Event() - port = support.find_unused_port() - # `listener` runs in a thread. It opens a socket listening on - # PORT, and sits in an accept() until the main thread connects. - # Then it rudely closes the socket, and sets Event `listener_gone` - # to let the main thread know the socket is gone. + s = socket.socket() + port = support.bind_port(s, HOST) + + # `listener` runs in a thread. It sits in an accept() until + # the main thread connects. Then it rudely closes the socket, + # and sets Event `listener_gone` to let the main thread know + # the socket is gone. def listener(): - s = socket.socket() - s.bind((HOST, port)) s.listen(5) listener_ready.set() s.accept() - s = None # reclaim the socket object, which also closes it + s.close() listener_gone.set() def connector(): listener_ready.wait() - s = socket.socket() - s.connect((HOST, port)) + c = socket.socket() + c.connect((HOST, port)) listener_gone.wait() try: - ssl_sock = ssl.wrap_socket(s) + ssl_sock = ssl.wrap_socket(c) except IOError: pass else: - raise support.TestFailed( - 'connecting to closed SSL socket should have failed') + self.fail('connecting to closed SSL socket should have failed') t = threading.Thread(target=listener) t.start() - connector() - t.join() + try: + connector() + finally: + t.join() - def testProtocolSSL2(self): + def test_protocol_sslv2(self): + """Connecting to an SSLv2 server with various client options""" if support.verbose: sys.stdout.write("\n") - tryProtocolCombo(ssl.PROTOCOL_SSLv2, ssl.PROTOCOL_SSLv2, True) - tryProtocolCombo(ssl.PROTOCOL_SSLv2, ssl.PROTOCOL_SSLv2, True, ssl.CERT_OPTIONAL) - tryProtocolCombo(ssl.PROTOCOL_SSLv2, ssl.PROTOCOL_SSLv2, True, ssl.CERT_REQUIRED) - tryProtocolCombo(ssl.PROTOCOL_SSLv2, ssl.PROTOCOL_SSLv23, True) - tryProtocolCombo(ssl.PROTOCOL_SSLv2, ssl.PROTOCOL_SSLv3, False) - tryProtocolCombo(ssl.PROTOCOL_SSLv2, ssl.PROTOCOL_TLSv1, False) + try_protocol_combo(ssl.PROTOCOL_SSLv2, ssl.PROTOCOL_SSLv2, True) + try_protocol_combo(ssl.PROTOCOL_SSLv2, ssl.PROTOCOL_SSLv2, True, ssl.CERT_OPTIONAL) + try_protocol_combo(ssl.PROTOCOL_SSLv2, ssl.PROTOCOL_SSLv2, True, ssl.CERT_REQUIRED) + try_protocol_combo(ssl.PROTOCOL_SSLv2, ssl.PROTOCOL_SSLv23, True) + try_protocol_combo(ssl.PROTOCOL_SSLv2, ssl.PROTOCOL_SSLv3, False) + try_protocol_combo(ssl.PROTOCOL_SSLv2, ssl.PROTOCOL_TLSv1, False) - def testProtocolSSL23(self): + def test_protocol_sslv23(self): + """Connecting to an SSLv23 server with various client options""" if support.verbose: sys.stdout.write("\n") try: - tryProtocolCombo(ssl.PROTOCOL_SSLv23, ssl.PROTOCOL_SSLv2, True) - except support.TestFailed as x: + try_protocol_combo(ssl.PROTOCOL_SSLv23, ssl.PROTOCOL_SSLv2, True) + except (ssl.SSLError, socket.error) as x: # this fails on some older versions of OpenSSL (0.9.7l, for instance) if support.verbose: sys.stdout.write( " SSL2 client to SSL23 server test unexpectedly failed:\n %s\n" % str(x)) - tryProtocolCombo(ssl.PROTOCOL_SSLv23, ssl.PROTOCOL_SSLv3, True) - tryProtocolCombo(ssl.PROTOCOL_SSLv23, ssl.PROTOCOL_SSLv23, True) - tryProtocolCombo(ssl.PROTOCOL_SSLv23, ssl.PROTOCOL_TLSv1, True) - - tryProtocolCombo(ssl.PROTOCOL_SSLv23, ssl.PROTOCOL_SSLv3, True, ssl.CERT_OPTIONAL) - tryProtocolCombo(ssl.PROTOCOL_SSLv23, ssl.PROTOCOL_SSLv23, True, ssl.CERT_OPTIONAL) - tryProtocolCombo(ssl.PROTOCOL_SSLv23, ssl.PROTOCOL_TLSv1, True, ssl.CERT_OPTIONAL) - - tryProtocolCombo(ssl.PROTOCOL_SSLv23, ssl.PROTOCOL_SSLv3, True, ssl.CERT_REQUIRED) - tryProtocolCombo(ssl.PROTOCOL_SSLv23, ssl.PROTOCOL_SSLv23, True, ssl.CERT_REQUIRED) - tryProtocolCombo(ssl.PROTOCOL_SSLv23, ssl.PROTOCOL_TLSv1, True, ssl.CERT_REQUIRED) + try_protocol_combo(ssl.PROTOCOL_SSLv23, ssl.PROTOCOL_SSLv3, True) + try_protocol_combo(ssl.PROTOCOL_SSLv23, ssl.PROTOCOL_SSLv23, True) + try_protocol_combo(ssl.PROTOCOL_SSLv23, ssl.PROTOCOL_TLSv1, True) + + try_protocol_combo(ssl.PROTOCOL_SSLv23, ssl.PROTOCOL_SSLv3, True, ssl.CERT_OPTIONAL) + try_protocol_combo(ssl.PROTOCOL_SSLv23, ssl.PROTOCOL_SSLv23, True, ssl.CERT_OPTIONAL) + try_protocol_combo(ssl.PROTOCOL_SSLv23, ssl.PROTOCOL_TLSv1, True, ssl.CERT_OPTIONAL) + + try_protocol_combo(ssl.PROTOCOL_SSLv23, ssl.PROTOCOL_SSLv3, True, ssl.CERT_REQUIRED) + try_protocol_combo(ssl.PROTOCOL_SSLv23, ssl.PROTOCOL_SSLv23, True, ssl.CERT_REQUIRED) + try_protocol_combo(ssl.PROTOCOL_SSLv23, ssl.PROTOCOL_TLSv1, True, ssl.CERT_REQUIRED) - def testProtocolSSL3(self): + def test_protocol_sslv3(self): + """Connecting to an SSLv3 server with various client options""" if support.verbose: sys.stdout.write("\n") - tryProtocolCombo(ssl.PROTOCOL_SSLv3, ssl.PROTOCOL_SSLv3, True) - tryProtocolCombo(ssl.PROTOCOL_SSLv3, ssl.PROTOCOL_SSLv3, True, ssl.CERT_OPTIONAL) - tryProtocolCombo(ssl.PROTOCOL_SSLv3, ssl.PROTOCOL_SSLv3, True, ssl.CERT_REQUIRED) - tryProtocolCombo(ssl.PROTOCOL_SSLv3, ssl.PROTOCOL_SSLv2, False) - tryProtocolCombo(ssl.PROTOCOL_SSLv3, ssl.PROTOCOL_SSLv23, False) - tryProtocolCombo(ssl.PROTOCOL_SSLv3, ssl.PROTOCOL_TLSv1, False) + try_protocol_combo(ssl.PROTOCOL_SSLv3, ssl.PROTOCOL_SSLv3, True) + try_protocol_combo(ssl.PROTOCOL_SSLv3, ssl.PROTOCOL_SSLv3, True, ssl.CERT_OPTIONAL) + try_protocol_combo(ssl.PROTOCOL_SSLv3, ssl.PROTOCOL_SSLv3, True, ssl.CERT_REQUIRED) + try_protocol_combo(ssl.PROTOCOL_SSLv3, ssl.PROTOCOL_SSLv2, False) + try_protocol_combo(ssl.PROTOCOL_SSLv3, ssl.PROTOCOL_SSLv23, False) + try_protocol_combo(ssl.PROTOCOL_SSLv3, ssl.PROTOCOL_TLSv1, False) - def testProtocolTLS1(self): + def test_protocol_tlsv1(self): + """Connecting to a TLSv1 server with various client options""" if support.verbose: sys.stdout.write("\n") - tryProtocolCombo(ssl.PROTOCOL_TLSv1, ssl.PROTOCOL_TLSv1, True) - tryProtocolCombo(ssl.PROTOCOL_TLSv1, ssl.PROTOCOL_TLSv1, True, ssl.CERT_OPTIONAL) - tryProtocolCombo(ssl.PROTOCOL_TLSv1, ssl.PROTOCOL_TLSv1, True, ssl.CERT_REQUIRED) - tryProtocolCombo(ssl.PROTOCOL_TLSv1, ssl.PROTOCOL_SSLv2, False) - tryProtocolCombo(ssl.PROTOCOL_TLSv1, ssl.PROTOCOL_SSLv3, False) - tryProtocolCombo(ssl.PROTOCOL_TLSv1, ssl.PROTOCOL_SSLv23, False) - - def testSTARTTLS (self): - - msgs = ("msg 1", "MSG 2", "STARTTLS", "MSG 3", "msg 4", "ENDTLS", "msg 5", "msg 6") + try_protocol_combo(ssl.PROTOCOL_TLSv1, ssl.PROTOCOL_TLSv1, True) + try_protocol_combo(ssl.PROTOCOL_TLSv1, ssl.PROTOCOL_TLSv1, True, ssl.CERT_OPTIONAL) + try_protocol_combo(ssl.PROTOCOL_TLSv1, ssl.PROTOCOL_TLSv1, True, ssl.CERT_REQUIRED) + try_protocol_combo(ssl.PROTOCOL_TLSv1, ssl.PROTOCOL_SSLv2, False) + try_protocol_combo(ssl.PROTOCOL_TLSv1, ssl.PROTOCOL_SSLv3, False) + try_protocol_combo(ssl.PROTOCOL_TLSv1, ssl.PROTOCOL_SSLv23, False) + + def test_starttls(self): + """Switching from clear text to encrypted and back again.""" + msgs = (b"msg 1", b"MSG 2", b"STARTTLS", b"MSG 3", b"msg 4", b"ENDTLS", b"msg 5", b"msg 6") server = ThreadedEchoServer(CERTFILE, ssl_version=ssl.PROTOCOL_TLSv1, @@ -970,55 +938,48 @@ # try to connect wrapped = False try: - try: - s = socket.socket() - s.setblocking(1) - s.connect((HOST, server.port)) - except Exception as x: - raise support.TestFailed("Unexpected exception: " + str(x)) - else: + s = socket.socket() + s.setblocking(1) + s.connect((HOST, server.port)) + if support.verbose: + sys.stdout.write("\n") + for indata in msgs: if support.verbose: - sys.stdout.write("\n") - for indata in msgs: - msg = indata.encode('ASCII', 'replace') + sys.stdout.write( + " client: sending %r...\n" % indata) + if wrapped: + conn.write(indata) + outdata = conn.read() + else: + s.send(indata) + outdata = s.recv(1024) + msg = outdata.strip().lower() + if indata == b"STARTTLS" and msg.startswith(b"ok"): + # STARTTLS ok, switch to secure mode if support.verbose: sys.stdout.write( - " client: sending %s...\n" % repr(msg)) - if wrapped: - conn.write(msg) - outdata = conn.read() - else: - s.send(msg) - outdata = s.recv(1024) - if (indata == "STARTTLS" and - str(outdata, 'ASCII', 'replace').strip().lower().startswith("ok")): - if support.verbose: - msg = str(outdata, 'ASCII', 'replace') - sys.stdout.write( - " client: read %s from server, starting TLS...\n" - % repr(msg)) - conn = ssl.wrap_socket(s, ssl_version=ssl.PROTOCOL_TLSv1) - wrapped = True - elif (indata == "ENDTLS" and - str(outdata, 'ASCII', 'replace').strip().lower().startswith("ok")): - if support.verbose: - msg = str(outdata, 'ASCII', 'replace') - sys.stdout.write( - " client: read %s from server, ending TLS...\n" - % repr(msg)) - s = conn.unwrap() - wrapped = False - else: - if support.verbose: - msg = str(outdata, 'ASCII', 'replace') - sys.stdout.write( - " client: read %s from server\n" % repr(msg)) - if support.verbose: - sys.stdout.write(" client: closing connection.\n") - if wrapped: - conn.write("over\n".encode("ASCII", "strict")) + " client: read %r from server, starting TLS...\n" + % msg) + conn = ssl.wrap_socket(s, ssl_version=ssl.PROTOCOL_TLSv1) + wrapped = True + elif indata == b"ENDTLS" and msg.startswith(b"ok"): + # ENDTLS ok, switch back to clear text + if support.verbose: + sys.stdout.write( + " client: read %r from server, ending TLS...\n" + % msg) + s = conn.unwrap() + wrapped = False else: - s.send("over\n".encode("ASCII", "strict")) + if support.verbose: + sys.stdout.write( + " client: read %r from server\n" % msg) + if support.verbose: + sys.stdout.write(" client: closing connection.\n") + if wrapped: + conn.write(b"over\n") + else: + s.send(b"over\n") if wrapped: conn.close() else: @@ -1027,8 +988,8 @@ server.stop() server.join() - def testSocketServer(self): - + def test_socketserver(self): + """Using a SocketServer to create and manage SSL connections.""" server = OurHTTPSServer(CERTFILE) flag = threading.Event() server.start(flag) @@ -1038,7 +999,8 @@ try: if support.verbose: sys.stdout.write('\n') - d1 = open(CERTFILE, 'rb').read() + with open(CERTFILE, 'rb') as f: + d1 = f.read() d2 = '' # now fetch the same data from the HTTPS server url = 'https://%s:%d/%s' % ( @@ -1052,17 +1014,7 @@ " client: read %d bytes from remote server '%s'\n" % (len(d2), server)) f.close() - except: - msg = ''.join(traceback.format_exception(*sys.exc_info())) - if support.verbose: - sys.stdout.write('\n' + msg) - raise support.TestFailed(msg) - else: - if not (d1 == d2): - print("d1 is", len(d1), repr(d1)) - print("d2 is", len(d2), repr(d2)) - raise support.TestFailed( - "Couldn't fetch data from HTTPS server") + self.assertEqual(d1, d2) finally: if support.verbose: sys.stdout.write('stopping server\n') @@ -1071,12 +1023,14 @@ sys.stdout.write('joining thread\n') server.join() - def testAsyncoreServer(self): + def test_asyncore_server(self): + """Check the example asyncore integration.""" + indata = "TEST MESSAGE of mixed case\n" if support.verbose: sys.stdout.write("\n") - indata="FOO\n" + indata = b"FOO\n" server = AsyncoreEchoServer(CERTFILE) flag = threading.Event() server.start(flag) @@ -1085,26 +1039,20 @@ # try to connect try: s = ssl.wrap_socket(socket.socket()) - s.connect((HOST, server.port)) - except ssl.SSLError as x: - raise support.TestFailed("Unexpected SSL error: " + str(x)) - except Exception as x: - raise support.TestFailed("Unexpected exception: " + str(x)) - else: + s.connect(('127.0.0.1', server.port)) if support.verbose: sys.stdout.write( - " client: sending %s...\n" % (repr(indata))) - s.sendall(indata.encode('ASCII', 'strict')) - outdata = s.recv() + " client: sending %r...\n" % indata) + s.write(indata) + outdata = s.read() if support.verbose: - sys.stdout.write(" client: read %s\n" % repr(outdata)) - outdata = str(outdata, 'ASCII', 'strict') + sys.stdout.write(" client: read %r\n" % outdata) if outdata != indata.lower(): - raise support.TestFailed( - "bad data <<%s>> (%d) received; expected <<%s>> (%d)\n" - % (repr(outdata[:min(len(outdata),20)]), len(outdata), - repr(indata[:min(len(indata),20)].lower()), len(indata))) - s.write("over\n".encode("ASCII", "strict")) + self.fail( + "bad data <<%r>> (%d) received; expected <<%r>> (%d)\n" + % (outdata[:20], len(outdata), + indata[:20].lower(), len(indata))) + s.write(b"over\n") if support.verbose: sys.stdout.write(" client: closing connection.\n") s.close() @@ -1112,8 +1060,8 @@ server.stop() server.join() - def testAllRecvAndSendMethods(self): - + def test_recv_send(self): + """Test recv(), send() and friends.""" if support.verbose: sys.stdout.write("\n") @@ -1128,19 +1076,14 @@ # wait for it to start flag.wait() # try to connect + s = ssl.wrap_socket(socket.socket(), + server_side=False, + certfile=CERTFILE, + ca_certs=CERTFILE, + cert_reqs=ssl.CERT_NONE, + ssl_version=ssl.PROTOCOL_TLSv1) + s.connect((HOST, server.port)) try: - s = ssl.wrap_socket(socket.socket(), - server_side=False, - certfile=CERTFILE, - ca_certs=CERTFILE, - cert_reqs=ssl.CERT_NONE, - ssl_version=ssl.PROTOCOL_TLSv1) - s.connect((HOST, server.port)) - except ssl.SSLError as x: - self.fail("Unexpected SSL error: " + str(x)) - except Exception as x: - self.fail("Unexpected exception: " + str(x)) - else: # helper methods for standardising recv* method signatures def _recv_into(): b = bytearray(b"\0"*100) @@ -1167,19 +1110,18 @@ data_prefix = "PREFIX_" for meth_name, send_meth, expect_success, args in send_methods: - indata = data_prefix + meth_name + indata = (data_prefix + meth_name).encode('ascii') try: - send_meth(indata.encode('ASCII', 'strict'), *args) + send_meth(indata, *args) outdata = s.read() - outdata = str(outdata, 'ASCII', 'strict') if outdata != indata.lower(): self.fail( "While sending with <<{name:s}>> bad data " - "<<{outdata:s}>> ({nout:d}) received; " - "expected <<{indata:s}>> ({nin:d})\n".format( - name=meth_name, outdata=repr(outdata[:20]), + "<<{outdata:r}>> ({nout:d}) received; " + "expected <<{indata:r}>> ({nin:d})\n".format( + name=meth_name, outdata=outdata[:20], nout=len(outdata), - indata=repr(indata[:20]), nin=len(indata) + indata=indata[:20], nin=len(indata) ) ) except ValueError as e: @@ -1197,19 +1139,18 @@ ) for meth_name, recv_meth, expect_success, args in recv_methods: - indata = data_prefix + meth_name + indata = (data_prefix + meth_name).encode('ascii') try: - s.send(indata.encode('ASCII', 'strict')) + s.send(indata) outdata = recv_meth(*args) - outdata = str(outdata, 'ASCII', 'strict') if outdata != indata.lower(): self.fail( "While receiving with <<{name:s}>> bad data " - "<<{outdata:s}>> ({nout:d}) received; " - "expected <<{indata:s}>> ({nin:d})\n".format( - name=meth_name, outdata=repr(outdata[:20]), + "<<{outdata:r}>> ({nout:d}) received; " + "expected <<{indata:r}>> ({nin:d})\n".format( + name=meth_name, outdata=outdata[:20], nout=len(outdata), - indata=repr(indata[:20]), nin=len(indata) + indata=indata[:20], nin=len(indata) ) ) except ValueError as e: @@ -1228,12 +1169,59 @@ # consume data s.read() - s.write("over\n".encode("ASCII", "strict")) + s.write(b"over\n") s.close() finally: server.stop() server.join() + def test_handshake_timeout(self): + # Issue #5103: SSL handshake must respect the socket timeout + server = socket.socket(socket.AF_INET) + host = "127.0.0.1" + port = support.bind_port(server) + started = threading.Event() + finish = False + + def serve(): + server.listen(5) + started.set() + conns = [] + while not finish: + r, w, e = select.select([server], [], [], 0.1) + if server in r: + # Let the socket hang around rather than having + # it closed by garbage collection. + conns.append(server.accept()[0]) + + t = threading.Thread(target=serve) + t.start() + started.wait() + + try: + try: + c = socket.socket(socket.AF_INET) + c.settimeout(0.2) + c.connect((host, port)) + # Will attempt handshake and time out + self.assertRaisesRegexp(ssl.SSLError, "timed out", + ssl.wrap_socket, c) + finally: + c.close() + try: + c = socket.socket(socket.AF_INET) + c = ssl.wrap_socket(c) + c.settimeout(0.2) + # Will attempt handshake and time out + self.assertRaisesRegexp(ssl.SSLError, "timed out", + c.connect, (host, port)) + finally: + c.close() + finally: + finish = True + t.join() + server.close() + def test_main(verbose=False): if skip_expected: @@ -1260,10 +1248,11 @@ if thread_info and support.is_resource_enabled('network'): tests.append(ThreadedTests) - support.run_unittest(*tests) - - if _have_threads: - support.threading_cleanup(*thread_info) + try: + support.run_unittest(*tests) + finally: + if _have_threads: + support.threading_cleanup(*thread_info) if __name__ == "__main__": test_main() Modified: python/branches/py3k-jit/Lib/test/test_subprocess.py ============================================================================== --- python/branches/py3k-jit/Lib/test/test_subprocess.py (original) +++ python/branches/py3k-jit/Lib/test/test_subprocess.py Tue May 4 01:24:51 2010 @@ -782,6 +782,51 @@ self.assertStderrEqual(stderr, b'') self.assertEqual(p.wait(), -signal.SIGTERM) + def test_surrogates_error_message(self): + def prepare(): + raise ValueError("surrogate:\uDCff") + + try: + subprocess.call( + [sys.executable, "-c", "pass"], + preexec_fn=prepare) + except ValueError as err: + # Pure Python implementations keeps the message + self.assertIsNone(subprocess._posixsubprocess) + self.assertEqual(str(err), "surrogate:\uDCff") + except RuntimeError as err: + # _posixsubprocess uses a default message + self.assertIsNotNone(subprocess._posixsubprocess) + self.assertEqual(str(err), "Exception occurred in preexec_fn.") + else: + self.fail("Expected ValueError or RuntimeError") + + def test_undecodable_env(self): + for key, value in (('test', 'abc\uDCFF'), ('test\uDCFF', '42')): + value_repr = repr(value).encode("ascii") + + # test str with surrogates + script = "import os; print(repr(os.getenv(%s)))" % repr(key) + env = os.environ.copy() + env[key] = value + stdout = subprocess.check_output( + [sys.executable, "-c", script], + env=env) + stdout = stdout.rstrip(b'\n\r') + self.assertEquals(stdout, value_repr) + + # test bytes + key = key.encode("ascii", "surrogateescape") + value = value.encode("ascii", "surrogateescape") + script = "import os; print(repr(os.getenv(%s)))" % repr(key) + env = os.environ.copy() + env[key] = value + stdout = subprocess.check_output( + [sys.executable, "-c", script], + env=env) + stdout = stdout.rstrip(b'\n\r') + self.assertEquals(stdout, value_repr) + @unittest.skipUnless(mswindows, "Windows specific tests") class Win32ProcessTestCase(BaseTestCase): Modified: python/branches/py3k-jit/Lib/test/test_sys.py ============================================================================== --- python/branches/py3k-jit/Lib/test/test_sys.py (original) +++ python/branches/py3k-jit/Lib/test/test_sys.py Tue May 4 01:24:51 2010 @@ -11,6 +11,10 @@ # strings to intern in test_intern() numruns = 0 +try: + import threading +except ImportError: + threading = None class SysModuleTest(unittest.TestCase): @@ -158,6 +162,7 @@ sys.setcheckinterval(n) self.assertEquals(sys.getcheckinterval(), n) + @unittest.skipUnless(threading, 'Threading required for this test.') def test_switchinterval(self): self.assertRaises(TypeError, sys.setswitchinterval) self.assertRaises(TypeError, sys.setswitchinterval, "a") Modified: python/branches/py3k-jit/Lib/test/test_tarfile.py ============================================================================== --- python/branches/py3k-jit/Lib/test/test_tarfile.py (original) +++ python/branches/py3k-jit/Lib/test/test_tarfile.py Tue May 4 01:24:51 2010 @@ -846,6 +846,24 @@ self.assertTrue(data.count(b"\0") == tarfile.RECORDSIZE, "incorrect zero padding") + def test_file_mode(self): + # Test for issue #8464: Create files with correct + # permissions. + if sys.platform == "win32" or not hasattr(os, "umask"): + return + + if os.path.exists(tmpname): + os.remove(tmpname) + + original_umask = os.umask(0o022) + try: + tar = tarfile.open(tmpname, self.mode) + tar.close() + mode = os.stat(tmpname).st_mode & 0o777 + self.assertEqual(mode, 0o644, "wrong file permissions") + finally: + os.umask(original_umask) + class GNUWriteTest(unittest.TestCase): # This testcase checks for correct creation of GNU Longname Modified: python/branches/py3k-jit/Lib/test/test_telnetlib.py ============================================================================== --- python/branches/py3k-jit/Lib/test/test_telnetlib.py (original) +++ python/branches/py3k-jit/Lib/test/test_telnetlib.py Tue May 4 01:24:51 2010 @@ -1,12 +1,12 @@ import socket import select -import threading import telnetlib import time import contextlib from unittest import TestCase from test import support +threading = support.import_module('threading') HOST = support.HOST Modified: python/branches/py3k-jit/Lib/test/test_thread.py ============================================================================== --- python/branches/py3k-jit/Lib/test/test_thread.py (original) +++ python/branches/py3k-jit/Lib/test/test_thread.py Tue May 4 01:24:51 2010 @@ -2,7 +2,7 @@ import unittest import random from test import support -import _thread as thread +thread = support.import_module('_thread') import time import sys import weakref Modified: python/branches/py3k-jit/Lib/test/test_threaded_import.py ============================================================================== --- python/branches/py3k-jit/Lib/test/test_threaded_import.py (original) +++ python/branches/py3k-jit/Lib/test/test_threaded_import.py Tue May 4 01:24:51 2010 @@ -5,9 +5,9 @@ # complains several times about module random having no attribute # randrange, and then Python hangs. -import _thread as thread import unittest -from test.support import verbose, TestFailed +from test.support import verbose, TestFailed, import_module +thread = import_module('_thread') critical_section = thread.allocate_lock() done = thread.allocate_lock() Modified: python/branches/py3k-jit/Lib/test/test_threadedtempfile.py ============================================================================== --- python/branches/py3k-jit/Lib/test/test_threadedtempfile.py (original) +++ python/branches/py3k-jit/Lib/test/test_threadedtempfile.py Tue May 4 01:24:51 2010 @@ -16,11 +16,10 @@ NUM_THREADS = 20 FILES_PER_THREAD = 50 -import _thread as thread # If this fails, we can't test this module -import threading import tempfile -from test.support import threading_setup, threading_cleanup, run_unittest +from test.support import threading_setup, threading_cleanup, run_unittest, import_module +threading = import_module('threading') import unittest import io from traceback import print_exc Modified: python/branches/py3k-jit/Lib/test/test_threading.py ============================================================================== --- python/branches/py3k-jit/Lib/test/test_threading.py (original) +++ python/branches/py3k-jit/Lib/test/test_threading.py Tue May 4 01:24:51 2010 @@ -5,8 +5,8 @@ import random import re import sys -import threading -import _thread +_thread = test.support.import_module('_thread') +threading = test.support.import_module('threading') import time import unittest import weakref Modified: python/branches/py3k-jit/Lib/test/test_threading_local.py ============================================================================== --- python/branches/py3k-jit/Lib/test/test_threading_local.py (original) +++ python/branches/py3k-jit/Lib/test/test_threading_local.py Tue May 4 01:24:51 2010 @@ -1,7 +1,7 @@ import unittest from doctest import DocTestSuite from test import support -import threading +threading = support.import_module('threading') import weakref import gc Modified: python/branches/py3k-jit/Lib/test/test_threadsignals.py ============================================================================== --- python/branches/py3k-jit/Lib/test/test_threadsignals.py (original) +++ python/branches/py3k-jit/Lib/test/test_threadsignals.py Tue May 4 01:24:51 2010 @@ -1,11 +1,11 @@ """PyUnit testing that threads honor our signal semantics""" import unittest -import _thread as thread import signal import os import sys -from test.support import run_unittest +from test.support import run_unittest, import_module +thread = import_module('_thread') if sys.platform[:3] in ('win', 'os2') or sys.platform=='riscos': raise unittest.SkipTest("Can't test signal on %s" % sys.platform) Modified: python/branches/py3k-jit/Lib/test/test_urllib2_localnet.py ============================================================================== --- python/branches/py3k-jit/Lib/test/test_urllib2_localnet.py (original) +++ python/branches/py3k-jit/Lib/test/test_urllib2_localnet.py Tue May 4 01:24:51 2010 @@ -1,13 +1,13 @@ #!/usr/bin/env python3 import email -import threading import urllib.parse import urllib.request import http.server import unittest import hashlib from test import support +threading = support.import_module('threading') # Loopback http server infrastructure Modified: python/branches/py3k-jit/Lib/test/test_urllibnet.py ============================================================================== --- python/branches/py3k-jit/Lib/test/test_urllibnet.py (original) +++ python/branches/py3k-jit/Lib/test/test_urllibnet.py Tue May 4 01:24:51 2010 @@ -8,6 +8,7 @@ import sys import os import email.message +import time def _open_with_retry(func, host, *args, **kwargs): @@ -180,6 +181,16 @@ self.assertIsInstance(header, email.message.Message, "header is not an instance of email.message.Message") + def test_data_header(self): + logo = "http://www.python.org/community/logos/python-logo-master-v3-TM.png" + file_location, fileheaders = self.urlretrieve(logo) + os.unlink(file_location) + datevalue = fileheaders.get('Date') + dateformat = '%a, %d %b %Y %H:%M:%S GMT' + try: + time.strptime(datevalue, dateformat) + except ValueError: + self.fail('Date value not in %r format', dateformat) def test_main(): Modified: python/branches/py3k-jit/Lib/test/test_xmlrpc.py ============================================================================== --- python/branches/py3k-jit/Lib/test/test_xmlrpc.py (original) +++ python/branches/py3k-jit/Lib/test/test_xmlrpc.py Tue May 4 01:24:51 2010 @@ -5,7 +5,6 @@ import unittest import xmlrpc.client as xmlrpclib import xmlrpc.server -import threading import http.client import socket import os @@ -14,6 +13,11 @@ import contextlib from test import support +try: + import threading +except ImportError: + threading = None + alist = [{'astring': 'foo at bar.baz.spam', 'afloat': 7283.43, 'anint': 2**20, @@ -399,10 +403,12 @@ return make_request_and_skip return decorator + at unittest.skipUnless(threading, 'Threading required for this test.') class BaseServerTestCase(unittest.TestCase): requestHandler = None request_count = 1 threadFunc = staticmethod(http_server) + def setUp(self): # enable traceback reporting xmlrpc.server.SimpleXMLRPCServer._send_traceback_header = True @@ -678,6 +684,9 @@ connection.putheader("Content-Encoding", "gzip") return xmlrpclib.Transport.send_content(self, connection, body) + def setUp(self): + BaseServerTestCase.setUp(self) + def test_gzip_request(self): t = self.Transport() t.encode_threshold = None @@ -714,13 +723,23 @@ #Test special attributes of the ServerProxy object 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://' + def test_close(self): - p = xmlrpclib.ServerProxy(URL) + p = xmlrpclib.ServerProxy(self.url) self.assertEqual(p('close')(), None) def test_transport(self): t = xmlrpclib.Transport() - p = xmlrpclib.ServerProxy(URL, transport=t) + p = xmlrpclib.ServerProxy(self.url, transport=t) self.assertEqual(p('transport'), t) # This is a contrived way to make a failure occur on the server side @@ -733,6 +752,7 @@ return super().get(key, failobj) + at unittest.skipUnless(threading, 'Threading required for this test.') class FailingServerTestCase(unittest.TestCase): def setUp(self): self.evt = threading.Event() Modified: python/branches/py3k-jit/Lib/unittest/__init__.py ============================================================================== --- python/branches/py3k-jit/Lib/unittest/__init__.py (original) +++ python/branches/py3k-jit/Lib/unittest/__init__.py Tue May 4 01:24:51 2010 @@ -48,7 +48,7 @@ 'TextTestRunner', 'TestLoader', 'FunctionTestCase', 'main', 'defaultTestLoader', 'SkipTest', 'skip', 'skipIf', 'skipUnless', 'expectedFailure', 'TextTestResult', 'installHandler', - 'registerResult', 'removeResult'] + 'registerResult', 'removeResult', 'removeHandler'] # Expose obsolete functions for backwards compatibility __all__.extend(['getTestCaseNames', 'makeSuite', 'findTestCases']) @@ -63,7 +63,7 @@ findTestCases) from .main import TestProgram, main from .runner import TextTestRunner, TextTestResult -from .signals import installHandler, registerResult, removeResult +from .signals import installHandler, registerResult, removeResult, removeHandler # deprecated _TextTestResult = TextTestResult Modified: python/branches/py3k-jit/Lib/unittest/result.py ============================================================================== --- python/branches/py3k-jit/Lib/unittest/result.py (original) +++ python/branches/py3k-jit/Lib/unittest/result.py Tue May 4 01:24:51 2010 @@ -153,9 +153,7 @@ length = self._count_relevant_tb_levels(tb) msgLines = traceback.format_exception(exctype, value, tb, length) else: - chain = exctype is not None - msgLines = traceback.format_exception(exctype, value, tb, - chain=chain) + msgLines = traceback.format_exception(exctype, value, tb) if self.buffer: output = sys.stdout.getvalue() Modified: python/branches/py3k-jit/Lib/unittest/signals.py ============================================================================== --- python/branches/py3k-jit/Lib/unittest/signals.py (original) +++ python/branches/py3k-jit/Lib/unittest/signals.py Tue May 4 01:24:51 2010 @@ -1,6 +1,8 @@ import signal import weakref +from functools import wraps + __unittest = True @@ -36,3 +38,20 @@ default_handler = signal.getsignal(signal.SIGINT) _interrupt_handler = _InterruptHandler(default_handler) signal.signal(signal.SIGINT, _interrupt_handler) + + +def removeHandler(method=None): + if method is not None: + @wraps(method) + def inner(*args, **kwargs): + initial = signal.getsignal(signal.SIGINT) + removeHandler() + try: + return method(*args, **kwargs) + finally: + signal.signal(signal.SIGINT, initial) + return inner + + global _interrupt_handler + if _interrupt_handler is not None: + signal.signal(signal.SIGINT, _interrupt_handler.default_handler) Modified: python/branches/py3k-jit/Lib/unittest/test/test_break.py ============================================================================== --- python/branches/py3k-jit/Lib/unittest/test/test_break.py (original) +++ python/branches/py3k-jit/Lib/unittest/test/test_break.py Tue May 4 01:24:51 2010 @@ -227,3 +227,24 @@ self.assertEqual(p.result, result) self.assertNotEqual(signal.getsignal(signal.SIGINT), default_handler) + + def testRemoveHandler(self): + default_handler = signal.getsignal(signal.SIGINT) + unittest.installHandler() + unittest.removeHandler() + self.assertEqual(signal.getsignal(signal.SIGINT), default_handler) + + # check that calling removeHandler multiple times has no ill-effect + unittest.removeHandler() + self.assertEqual(signal.getsignal(signal.SIGINT), default_handler) + + def testRemoveHandlerAsDecorator(self): + default_handler = signal.getsignal(signal.SIGINT) + unittest.installHandler() + + @unittest.removeHandler + def test(): + self.assertEqual(signal.getsignal(signal.SIGINT), default_handler) + + test() + self.assertNotEqual(signal.getsignal(signal.SIGINT), default_handler) Modified: python/branches/py3k-jit/Lib/unittest/test/test_result.py ============================================================================== --- python/branches/py3k-jit/Lib/unittest/test/test_result.py (original) +++ python/branches/py3k-jit/Lib/unittest/test/test_result.py Tue May 4 01:24:51 2010 @@ -4,6 +4,7 @@ from test import support +import traceback import unittest @@ -361,6 +362,15 @@ runner.run(Test('testFoo')) +class MockTraceback(object): + @staticmethod + def format_exception(*_): + return ['A traceback'] + +def restore_traceback(): + unittest.result.traceback = traceback + + class TestOutputBuffering(unittest.TestCase): def setUp(self): @@ -441,6 +451,9 @@ return result def testBufferOutputAddErrorOrFailure(self): + unittest.result.traceback = MockTraceback + self.addCleanup(restore_traceback) + for message_attr, add_attr, include_error in [ ('errors', 'addError', True), ('failures', 'addFailure', False), @@ -476,7 +489,8 @@ Stderr: bar """) - expectedFullMessage = 'NoneType\n%s%s' % (expectedOutMessage, expectedErrMessage) + + expectedFullMessage = 'A traceback%s%s' % (expectedOutMessage, expectedErrMessage) self.assertIs(test, self) self.assertEqual(result._original_stdout.getvalue(), expectedOutMessage) Modified: python/branches/py3k-jit/Lib/urllib/request.py ============================================================================== --- python/branches/py3k-jit/Lib/urllib/request.py (original) +++ python/branches/py3k-jit/Lib/urllib/request.py Tue May 4 01:24:51 2010 @@ -1779,7 +1779,7 @@ else: encoding = '' msg = [] - msg.append('Date: %s'%time.strftime('%a, %d %b %Y %T GMT', + msg.append('Date: %s'%time.strftime('%a, %d %b %Y %H:%M:%S GMT', time.gmtime(time.time()))) msg.append('Content-type: %s' % type) if encoding == 'base64': Modified: python/branches/py3k-jit/Lib/webbrowser.py ============================================================================== --- python/branches/py3k-jit/Lib/webbrowser.py (original) +++ python/branches/py3k-jit/Lib/webbrowser.py Tue May 4 01:24:51 2010 @@ -600,9 +600,35 @@ rc = osapipe.close() return not rc + class MacOSXOSAScript(BaseBrowser): + def __init__(self, name): + self._name = name + + def open(self, url, new=0, autoraise=True): + if self._name == 'default': + script = 'open location "%s"' % url.replace('"', '%22') # opens in default browser + else: + script = ''' + tell application "%s" + activate + open location "%s" + end + '''%(self._name, url.replace('"', '%22')) + + osapipe = os.popen("osascript", "w") + if osapipe is None: + return False + + osapipe.write(script) + rc = osapipe.close() + return not rc + + # Don't clear _tryorder or _browsers since OS X can use above Unix support # (but we prefer using the OS X specific stuff) - register("MacOSX", None, MacOSX('default'), -1) + register("safari", None, MacOSXOSAScript('safari'), -1) + register("firefox", None, MacOSXOSAScript('firefox'), -1) + register("MacOSX", None, MacOSXOSAScript('default'), -1) # Modified: python/branches/py3k-jit/Mac/BuildScript/build-installer.py ============================================================================== --- python/branches/py3k-jit/Mac/BuildScript/build-installer.py (original) +++ python/branches/py3k-jit/Mac/BuildScript/build-installer.py Tue May 4 01:24:51 2010 @@ -1111,13 +1111,14 @@ Set the custom icon for the specified file or directory. """ - toolPath = os.path.join(os.path.dirname(__file__), "seticon.app/Contents/MacOS/seticon") - dirPath = os.path.dirname(__file__) + dirPath = os.path.normpath(os.path.dirname(__file__)) + toolPath = os.path.join(dirPath, "seticon.app/Contents/MacOS/seticon") if not os.path.exists(toolPath) or os.stat(toolPath).st_mtime < os.stat(dirPath + '/seticon.m').st_mtime: # NOTE: The tool is created inside an .app bundle, otherwise it won't work due # to connections to the window server. - if not os.path.exists('seticon.app/Contents/MacOS'): - os.makedirs('seticon.app/Contents/MacOS') + appPath = os.path.join(dirPath, "seticon.app/Contents/MacOS") + if not os.path.exists(appPath): + os.makedirs(appPath) runCommand("cc -o %s %s/seticon.m -framework Cocoa"%( shellQuote(toolPath), shellQuote(dirPath))) Modified: python/branches/py3k-jit/Mac/Makefile.in ============================================================================== --- python/branches/py3k-jit/Mac/Makefile.in (original) +++ python/branches/py3k-jit/Mac/Makefile.in Tue May 4 01:24:51 2010 @@ -24,7 +24,7 @@ # These are normally glimpsed from the previous set bindir=$(prefix)/bin -PYTHONAPPSDIR=/Applications/$(PYTHONFRAMEWORK) $(VERSION) +PYTHONAPPSDIR=@FRAMEWORKINSTALLAPPSPREFIX@/$(PYTHONFRAMEWORK) $(VERSION) APPINSTALLDIR=$(prefix)/Resources/Python.app # Variables for installing the "normal" unix binaries Modified: python/branches/py3k-jit/Mac/PythonLauncher/Makefile.in ============================================================================== --- python/branches/py3k-jit/Mac/PythonLauncher/Makefile.in (original) +++ python/branches/py3k-jit/Mac/PythonLauncher/Makefile.in Tue May 4 01:24:51 2010 @@ -21,7 +21,7 @@ BUNDLEBULDER=$(srcdir)/../Tools/bundlebuilder.py -PYTHONAPPSDIR=/Applications/$(PYTHONFRAMEWORK) $(VERSION) +PYTHONAPPSDIR=@FRAMEWORKINSTALLAPPSPREFIX@/$(PYTHONFRAMEWORK) $(VERSION) OBJECTS=FileSettings.o MyAppDelegate.o MyDocument.o PreferencesWindowController.o doscript.o main.o install: Python\ Launcher.app Modified: python/branches/py3k-jit/Mac/README ============================================================================== --- python/branches/py3k-jit/Mac/README (original) +++ python/branches/py3k-jit/Mac/README Tue May 4 01:24:51 2010 @@ -5,13 +5,24 @@ This document provides a quick overview of some Mac OS X specific features in the Python distribution. -* ``--enable-framework`` +* ``--enable-framework[=DIR]`` If this argument is specified the build will create a Python.framework rather than a traditional Unix install. See the section _`Building and using a framework-based Python on Mac OS X` for more information on frameworks. + If the optional directory argument is specified the framework it installed + into that directory. This can be used to install a python framework into + your home directory:: + + $ configure --enable-framework=/Users/ronald/Library/Frameworks + $ make && make install + + This will install the framework itself in ``/Users/ronald/Library/Frameworks``, + the applications in a subdirectory of ``/Users/ronald/Applications`` and the + command-line tools in ``/Users/ronald/bin``. + * ``--with-framework-name=NAME`` Specify the name for the python framework, defaults to ``Python``. This option @@ -236,6 +247,26 @@ Python and have libaries in ``/usr/local`` that don't contain the required architectures. Temporarily move ``/usr/local`` aside to finish the build. + +Uninstalling a framework install, including the binary installer +================================================================ + +Uninstalling a framework can be done by manually removing all bits that got installed, +that's true for both installations from source and installations using the binary installer. +Sadly enough OSX does not have a central uninstaller. + +The main bit of a framework install is the framework itself, installed in +``/Library/Frameworks/Python.framework``. This can contain multiple versions +of Python, if you want to remove just one version you have to remove the +version-specific subdirectory: ``/Library/Frameworks/Python.framework/Versions/X.Y``. +If you do that, ensure that ``/Library/Frameworks/Python.framework/Versions/Current`` +is a symlink that points to an installed version of Python. + +A framework install also installs some applications in ``/Applications/Python X.Y``, + +And lastly a framework installation installs files in ``/usr/local/bin``, all of +them symbolic links to files in ``/Library/Frameworks/Python.framework/Versions/X.Y/bin``. + Odds and ends ============= @@ -246,4 +277,4 @@ files. Jack Jansen, Jack.Jansen at cwi.nl, 15-Jul-2004. - Ronald Oussoren, RonaldOussoren at mac.com, 26-May-2006 + Ronald Oussoren, RonaldOussoren at mac.com, 30-April-2010 Modified: python/branches/py3k-jit/Makefile.pre.in ============================================================================== --- python/branches/py3k-jit/Makefile.pre.in (original) +++ python/branches/py3k-jit/Makefile.pre.in Tue May 4 01:24:51 2010 @@ -238,6 +238,7 @@ PGOBJS= \ Objects/obmalloc.o \ + Python/dynamic_annotations.o \ Python/mysnprintf.o \ Python/pyctype.o \ Parser/tokenizer_pgen.o \ @@ -283,6 +284,7 @@ Python/ceval.o \ Python/compile.o \ Python/codecs.o \ + Python/dynamic_annotations.o \ Python/errors.o \ Python/frozen.o \ Python/frozenmain.o \ @@ -644,6 +646,7 @@ Include/descrobject.h \ Include/dictobject.h \ Include/dtoa.h \ + Include/dynamic_annotations.h \ Include/enumobject.h \ Include/errcode.h \ Include/eval.h \ @@ -674,6 +677,7 @@ Include/pgen.h \ Include/pgenheaders.h \ Include/pyarena.h \ + Include/pyatomic.h \ Include/pycapsule.h \ Include/pyctype.h \ Include/pydebug.h \ @@ -1170,8 +1174,8 @@ # Rebuild the configure script from configure.in; also rebuild pyconfig.h.in autoconf: - (cd $(srcdir); autoconf) - (cd $(srcdir); autoheader) + (cd $(srcdir); autoconf -Wall) + (cd $(srcdir); autoheader -Wall) # Create a tags file for vi tags:: @@ -1190,8 +1194,8 @@ # Sanitation targets -- clean leaves libraries, executables and tags # files, which clobber removes as well pycremoval: - find $(srcdir) -name '*.py[co]' -exec rm -f {} ';' - find $(srcdir) -name '__pycache__' | xargs rmdir + -find $(srcdir) -name '*.py[co]' -exec rm -f {} ';' + -find $(srcdir) -name '__pycache__' -exec rmdir {} ';' rmtestturds: -rm -f *BAD *GOOD *SKIPPED Modified: python/branches/py3k-jit/Misc/ACKS ============================================================================== --- python/branches/py3k-jit/Misc/ACKS (original) +++ python/branches/py3k-jit/Misc/ACKS Tue May 4 01:24:51 2010 @@ -15,6 +15,7 @@ Jim Ahlstrom Farhan Ahmad Nir Aides +Yaniv Aknin Jyrki Alakuijala Billy G. Allie Kevin Altis @@ -630,6 +631,7 @@ Burton Radons Brodie Rao Antti Rasinen +Sridhar Ratnakumar Eric Raymond Edward K. Ream Chris Rebert @@ -794,6 +796,7 @@ Hector Urtubia Andi Vajda Case Van Horsen +Kyle VanderBeek Atul Varma Dmitry Vasiliev Alexandre Vassalotti Modified: python/branches/py3k-jit/Misc/NEWS ============================================================================== --- python/branches/py3k-jit/Misc/NEWS (original) +++ python/branches/py3k-jit/Misc/NEWS Tue May 4 01:24:51 2010 @@ -12,6 +12,19 @@ Core and Builtins ----------------- +- PyFile_FromFd() uses PyUnicode_DecodeFSDefault() instead of + PyUnicode_FromString() to support surrogates in the filename and use the + right encoding + +- PyUnicode_DecodeFSDefaultAndSize() uses surrogateescape error handler + +- Issue #8419: Prevent the dict constructor from accepting non-string keyword + arguments. + +- Issue #8124: PySys_WriteStdout() and PySys_WriteStderr() don't execute + indirectly Python signal handlers anymore because mywrite() ignores + exceptions (KeyboardInterrupt) + - Issue #8092: Fix PyUnicode_EncodeUTF8() to support error handler producing unicode string (eg. backslashreplace) @@ -191,6 +204,9 @@ libraries are: Mach C threads, SunOS LWP, GNU pth, Irix threads. Support code will be entirely removed in 3.3. +- Support for OSF* has been disabled. If nobody stands up, support will be + removed in 3.3. See http://bugs.python.org/issue8606 . + - Peephole constant folding had missed UNARY_POSITIVE. - Issue #1722344: threading._shutdown() is now called in Py_Finalize(), which @@ -278,6 +294,9 @@ C-API ----- +- Add PyArg_ValidateKeywordArguments, which checks if all keyword arguments are + strings in an efficient manner. + - Issue #8276: PyEval_CallObject() is now only available in macro form. The function declaration, which was kept for backwards compatibility reasons, is now removed (the macro was introduced in 1997!). @@ -329,6 +348,68 @@ Library ------- +- Issue #7865: The close() method of :mod:`io` objects should not swallow + exceptions raised by the implicit flush(). Also ensure that calling + close() several times is supported. Patch by Pascal Chambon. + +- Issue #4687: Fix accuracy of garbage collection runtimes displayed with + gc.DEBUG_STATS. + +- Issue #7192: webbrowser.get("firefox") now wors on Mac OS X, as does + webbrowser.get("safari"). + +- Issue #8464: tarfile no longer creates files with execute permissions set + when mode="w|" is used. + +- Issue #7834: Fix connect() of Bluetooth L2CAP sockets with recent versions + of the Linux kernel. Patch by Yaniv Aknin. + +- Issue #8295: Added shutil.unpack_archive. + +- Issue #6312: Fixed http HEAD request when the transfer encoding is chunked. + It should correctly return an empty response now. + +- Issue #8546: Reject None given as the buffering argument to _pyio.open. + +- Issue #8549: Fix compiling the _ssl extension under AIX. Patch by + Sridhar Ratnakumar. + +- Issue #6656: fix locale.format_string to handle escaped percents + and mappings. + +- Issue #2302: Fix a race condition in SocketServer.BaseServer.shutdown, + where the method could block indefinitely if called just before the + event loop started running. This also fixes the occasional freezes + witnessed in test_httpservers. + +- Issue #8524: When creating an SSL socket, the timeout value of the + original socket wasn't retained (instead, a socket with a positive timeout + would be turned into a non-blocking SSL socket). + +- Issue #5103: SSL handshake would ignore the socket timeout and block + indefinitely if the other end didn't respond. + +- The do_handshake() method of SSL objects now adjusts the blocking mode of + the SSL structure if necessary (as other methods already do). + +- Issue #8391: os.execvpe() and os.getenv() supports unicode with surrogates + and bytes strings for environment keys and values + +- Issue #8467: Pure Python implementation of subprocess encodes the error + message using surrogatepass error handler to support surrogates in the + message + +- Issue #8468: bz2.BZ2File() accepts str with surrogates and bytes filenames + +- Issue #8451: Syslog module now uses basename(sys.argv[0]) instead of + the string "python" as the *ident*. openlog() arguments are all optional + and keywords. + +- Issue #8108: Fix the unwrap() method of SSL objects when the socket has + a non-infinite timeout. Also make that method friendlier with applications + wanting to continue using the socket in clear-text mode, by disabling + OpenSSL's internal readahead. Thanks to Darryl Miles for guidance. + - Issue #8496: make mailcap.lookup() always return a list, rather than an iterator. Patch by Gregory Nofi. @@ -1047,6 +1128,11 @@ Build ----- +- Issue #3646: It is now easily possible to install a Python framework into + your home directory on MacOSX, see Mac/README for more information. + +- Issue #3928: os.mknod() now available in Solaris, also. + - Issue #3326: Build Python without -fno-strict-aliasing when the gcc does not give false warnings. @@ -1099,6 +1185,11 @@ - python-config now supports multiple options on the same command line. +- Issue #8509: Fix quoting in help strings and code snippets in configure.in. + +- Issue #8510: Update to autoconf2.65. + + Documentation ------------ @@ -1120,8 +1211,20 @@ Tests ----- -- Issues #8279, #8330, #8437, #8480: Fix test_gdb failures, patch written by - Dave Malcolm +- Issue #8533: regrtest uses backslashreplace error handler for stdout to avoid + UnicodeEncodeError (write non-ASCII character to stdout using ASCII encoding) + +- Issue #8576: Remove use of find_unused_port() in test_smtplib and + test_multiprocessing. Patch by Paul Moore. + +- Issue #7449: Fix many tests to support Python compiled without thread + support. Patches written by Jerry Seutter. + +- Issue #8108: test_ftplib's non-blocking SSL server now has proper handling + of SSL shutdowns. + +- Issues #8279, #8330, #8437, #8480, #8495: Fix test_gdb failures, patch + written by Dave Malcolm - Issue #3864: Skip three test_signal tests on freebsd6 because they fail if any thread was previously started, most likely due to a platform bug. Modified: python/branches/py3k-jit/Misc/maintainers.rst ============================================================================== --- python/branches/py3k-jit/Misc/maintainers.rst (original) +++ python/branches/py3k-jit/Misc/maintainers.rst Tue May 4 01:24:51 2010 @@ -48,8 +48,8 @@ argparse bethard array ast -asynchat josiahcarlson -asyncore josiahcarlson +asynchat josiahcarlson, giampaolo.rodola +asyncore josiahcarlson, giampaolo.rodola atexit audioop base64 @@ -187,7 +187,7 @@ socketserver spwd sqlite3 ghaering -ssl janssen, pitrou +ssl janssen, pitrou, giampaolo.rodola stat string stringprep @@ -281,7 +281,7 @@ locale lemburg, loewis mathematics mark.dickinson, eric.smith, lemburg memory management tim_one, lemburg -networking +networking giampaolo.rodola packaging tarek, lemburg py3 transition benjamin.peterson release management tarek, lemburg, benjamin.peterson, barry, loewis, Modified: python/branches/py3k-jit/Modules/_io/bufferedio.c ============================================================================== --- python/branches/py3k-jit/Modules/_io/bufferedio.c (original) +++ python/branches/py3k-jit/Modules/_io/bufferedio.c Tue May 4 01:24:51 2010 @@ -440,11 +440,7 @@ res = PyObject_CallMethodObjArgs((PyObject *)self, _PyIO_str_flush, NULL); ENTER_BUFFERED(self) if (res == NULL) { - /* If flush() fails, just give up */ - if (PyErr_ExceptionMatches(PyExc_IOError)) - PyErr_Clear(); - else - goto end; + goto end; } Py_XDECREF(res); Modified: python/branches/py3k-jit/Modules/_io/bytesio.c ============================================================================== --- python/branches/py3k-jit/Modules/_io/bytesio.c (original) +++ python/branches/py3k-jit/Modules/_io/bytesio.c Tue May 4 01:24:51 2010 @@ -169,6 +169,7 @@ static PyObject * bytesio_flush(bytesio *self) { + CHECK_CLOSED(self); Py_RETURN_NONE; } Modified: python/branches/py3k-jit/Modules/_io/iobase.c ============================================================================== --- python/branches/py3k-jit/Modules/_io/iobase.c (original) +++ python/branches/py3k-jit/Modules/_io/iobase.c Tue May 4 01:24:51 2010 @@ -183,11 +183,7 @@ res = PyObject_CallMethodObjArgs(self, _PyIO_str_flush, NULL); PyObject_SetAttrString(self, "__IOBase_closed", Py_True); if (res == NULL) { - /* If flush() fails, just give up */ - if (PyErr_ExceptionMatches(PyExc_IOError)) - PyErr_Clear(); - else - return NULL; + return NULL; } Py_XDECREF(res); Py_RETURN_NONE; Modified: python/branches/py3k-jit/Modules/_io/textio.c ============================================================================== --- python/branches/py3k-jit/Modules/_io/textio.c (original) +++ python/branches/py3k-jit/Modules/_io/textio.c Tue May 4 01:24:51 2010 @@ -2398,16 +2398,30 @@ textiowrapper_close(textio *self, PyObject *args) { PyObject *res; + int r; CHECK_INITIALIZED(self); - res = PyObject_CallMethod((PyObject *)self, "flush", NULL); - if (res == NULL) { - /* If flush() fails, just give up */ - PyErr_Clear(); + + res = textiowrapper_closed_get(self, NULL); + if (res == NULL) + return NULL; + r = PyObject_IsTrue(res); + Py_DECREF(res); + if (r < 0) + return NULL; + + if (r > 0) { + Py_RETURN_NONE; /* stream already closed */ } - else - Py_DECREF(res); + else { + res = PyObject_CallMethod((PyObject *)self, "flush", NULL); + if (res == NULL) { + return NULL; + } + else + Py_DECREF(res); - return PyObject_CallMethod(self->buffer, "close", NULL); + return PyObject_CallMethod(self->buffer, "close", NULL); + } } static PyObject * Modified: python/branches/py3k-jit/Modules/_ssl.c ============================================================================== --- python/branches/py3k-jit/Modules/_ssl.c (original) +++ python/branches/py3k-jit/Modules/_ssl.c Tue May 4 01:24:51 2010 @@ -9,6 +9,9 @@ directly. XXX should partial writes be enabled, SSL_MODE_ENABLE_PARTIAL_WRITE? + + XXX integrate several "shutdown modes" as suggested in + http://bugs.python.org/issue8108#msg102867 ? */ #include "Python.h" @@ -63,7 +66,7 @@ PY_SSL_VERSION_SSL2, PY_SSL_VERSION_SSL3, PY_SSL_VERSION_SSL23, - PY_SSL_VERSION_TLS1, + PY_SSL_VERSION_TLS1 }; /* Include symbols from _socket module */ @@ -116,6 +119,7 @@ SSL_CTX* ctx; SSL* ssl; X509* peer_cert; + int shutdown_seen_zero; } PySSLObject; @@ -451,20 +455,25 @@ { int ret; int err; - int sockstate; + int sockstate, nonblocking; + PySocketSockObject *sock + = (PySocketSockObject *) PyWeakref_GetObject(self->Socket); + + if (((PyObject*)sock) == Py_None) { + _setSSLError("Underlying socket connection gone", + PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__); + return NULL; + } + + /* just in case the blocking state of the socket has been changed */ + nonblocking = (sock->sock_timeout >= 0.0); + BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking); + BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking); /* Actually negotiate SSL connection */ /* XXX If SSL_do_handshake() returns 0, it's also a failure. */ sockstate = 0; do { - PySocketSockObject *sock - = (PySocketSockObject *) PyWeakref_GetObject(self->Socket); - if (((PyObject*)sock) == Py_None) { - _setSSLError("Underlying socket connection gone", - PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__); - return NULL; - } - PySSL_BEGIN_ALLOW_THREADS ret = SSL_do_handshake(self->ssl); err = SSL_get_error(self->ssl, ret); @@ -1392,7 +1401,8 @@ static PyObject *PySSL_SSLshutdown(PySSLObject *self) { - int err; + int err, ssl_err, sockstate, nonblocking; + int zeros = 0; PySocketSockObject *sock = (PySocketSockObject *) PyWeakref_GetObject(self->Socket); @@ -1403,13 +1413,65 @@ return NULL; } - PySSL_BEGIN_ALLOW_THREADS - err = SSL_shutdown(self->ssl); - if (err == 0) { - /* we need to call it again to finish the shutdown */ + /* Just in case the blocking state of the socket has been changed */ + nonblocking = (sock->sock_timeout >= 0.0); + BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking); + BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking); + + while (1) { + PySSL_BEGIN_ALLOW_THREADS + /* Disable read-ahead so that unwrap can work correctly. + * Otherwise OpenSSL might read in too much data, + * eating clear text data that happens to be + * transmitted after the SSL shutdown. + * Should be safe to call repeatedly everytime this + * function is used and the shutdown_seen_zero != 0 + * condition is met. + */ + if (self->shutdown_seen_zero) + SSL_set_read_ahead(self->ssl, 0); err = SSL_shutdown(self->ssl); + PySSL_END_ALLOW_THREADS + /* If err == 1, a secure shutdown with SSL_shutdown() is complete */ + if (err > 0) + break; + if (err == 0) { + /* Don't loop endlessly; instead preserve legacy + behaviour of trying SSL_shutdown() only twice. + This looks necessary for OpenSSL < 0.9.8m */ + if (++zeros > 1) + break; + /* Shutdown was sent, now try receiving */ + self->shutdown_seen_zero = 1; + continue; + } + + /* Possibly retry shutdown until timeout or failure */ + ssl_err = SSL_get_error(self->ssl, err); + if (ssl_err == SSL_ERROR_WANT_READ) + sockstate = check_socket_and_wait_for_timeout(sock, 0); + else if (ssl_err == SSL_ERROR_WANT_WRITE) + sockstate = check_socket_and_wait_for_timeout(sock, 1); + else + break; + if (sockstate == SOCKET_HAS_TIMED_OUT) { + if (ssl_err == SSL_ERROR_WANT_READ) + PyErr_SetString(PySSLErrorObject, + "The read operation timed out"); + else + PyErr_SetString(PySSLErrorObject, + "The write operation timed out"); + return NULL; + } + else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) { + PyErr_SetString(PySSLErrorObject, + "Underlying socket too large for select()."); + return NULL; + } + else if (sockstate != SOCKET_OPERATION_OK) + /* Retain the SSL error code */ + break; } - PySSL_END_ALLOW_THREADS if (err < 0) return PySSL_SetError(self, err, __FILE__, __LINE__); Modified: python/branches/py3k-jit/Modules/bz2module.c ============================================================================== --- python/branches/py3k-jit/Modules/bz2module.c (original) +++ python/branches/py3k-jit/Modules/bz2module.c Tue May 4 01:24:51 2010 @@ -1162,6 +1162,7 @@ { static char *kwlist[] = {"filename", "mode", "buffering", "compresslevel", 0}; + PyObject *name_obj = NULL; char *name; char *mode = "r"; int buffering = -1; @@ -1171,14 +1172,17 @@ self->size = -1; - if (!PyArg_ParseTupleAndKeywords(args, kwargs, "s|sii:BZ2File", - kwlist, &name, &mode, &buffering, + if (!PyArg_ParseTupleAndKeywords(args, kwargs, "O&|sii:BZ2File", + kwlist, PyUnicode_FSConverter, &name_obj, + &mode, &buffering, &compresslevel)) return -1; + name = PyBytes_AsString(name_obj); if (compresslevel < 1 || compresslevel > 9) { PyErr_SetString(PyExc_ValueError, "compresslevel must be between 1 and 9"); + Py_DECREF(name_obj); return -1; } @@ -1202,6 +1206,7 @@ if (error) { PyErr_Format(PyExc_ValueError, "invalid mode char %c", *mode); + Py_DECREF(name_obj); return -1; } mode++; @@ -1216,6 +1221,7 @@ mode = (mode_char == 'r') ? "rb" : "wb"; self->rawfp = fopen(name, mode); + Py_DECREF(name_obj); if (self->rawfp == NULL) { PyErr_SetFromErrno(PyExc_IOError); return -1; Modified: python/branches/py3k-jit/Modules/gcmodule.c ============================================================================== --- python/branches/py3k-jit/Modules/gcmodule.c (original) +++ python/branches/py3k-jit/Modules/gcmodule.c Tue May 4 01:24:51 2010 @@ -804,13 +804,13 @@ } if (debug & DEBUG_STATS) { - t1 = get_time(); PySys_WriteStderr("gc: collecting generation %d...\n", generation); PySys_WriteStderr("gc: objects in each generation:"); for (i = 0; i < NUM_GENERATIONS; i++) PySys_WriteStderr(" %" PY_FORMAT_SIZE_T "d", gc_list_size(GEN_HEAD(i))); + t1 = get_time(); PySys_WriteStderr("\n"); } Modified: python/branches/py3k-jit/Modules/posixmodule.c ============================================================================== --- python/branches/py3k-jit/Modules/posixmodule.c (original) +++ python/branches/py3k-jit/Modules/posixmodule.c Tue May 4 01:24:51 2010 @@ -3052,6 +3052,86 @@ return posix_error(); } +static char** +parse_envlist(PyObject* env, Py_ssize_t *envc_ptr) +{ + char **envlist; + Py_ssize_t i, pos, envc; + PyObject *keys=NULL, *vals=NULL; + PyObject *key, *val, *key2, *val2; + char *p, *k, *v; + size_t len; + + i = PyMapping_Size(env); + if (i < 0) + return NULL; + envlist = PyMem_NEW(char *, i + 1); + if (envlist == NULL) { + PyErr_NoMemory(); + return NULL; + } + envc = 0; + keys = PyMapping_Keys(env); + vals = PyMapping_Values(env); + if (!keys || !vals) + goto error; + if (!PyList_Check(keys) || !PyList_Check(vals)) { + PyErr_Format(PyExc_TypeError, + "env.keys() or env.values() is not a list"); + goto error; + } + + for (pos = 0; pos < i; pos++) { + key = PyList_GetItem(keys, pos); + val = PyList_GetItem(vals, pos); + if (!key || !val) + goto error; + + if (PyUnicode_FSConverter(key, &key2) == 0) + goto error; + if (PyUnicode_FSConverter(val, &val2) == 0) { + Py_DECREF(key2); + goto error; + } + +#if defined(PYOS_OS2) + /* Omit Pseudo-Env Vars that Would Confuse Programs if Passed On */ + if (stricmp(k, "BEGINLIBPATH") != 0 && stricmp(k, "ENDLIBPATH") != 0) { +#endif + k = PyBytes_AsString(key2); + v = PyBytes_AsString(val2); + len = PyBytes_GET_SIZE(key2) + PyBytes_GET_SIZE(val2) + 2; + + p = PyMem_NEW(char, len); + if (p == NULL) { + PyErr_NoMemory(); + Py_DECREF(key2); + Py_DECREF(val2); + goto error; + } + PyOS_snprintf(p, len, "%s=%s", k, v); + envlist[envc++] = p; + Py_DECREF(key2); + Py_DECREF(val2); +#if defined(PYOS_OS2) + } +#endif + } + Py_DECREF(vals); + Py_DECREF(keys); + + envlist[envc] = 0; + *envc_ptr = envc; + return envlist; + +error: + Py_XDECREF(keys); + Py_XDECREF(vals); + while (--envc >= 0) + PyMem_DEL(envlist[envc]); + PyMem_DEL(envlist); + return NULL; +} PyDoc_STRVAR(posix_execve__doc__, "execve(path, args, env)\n\n\ @@ -3069,8 +3149,7 @@ PyObject *argv, *env; char **argvlist; char **envlist; - PyObject *key, *val, *keys=NULL, *vals=NULL; - Py_ssize_t i, pos, argc, envc; + Py_ssize_t i, argc, envc; PyObject *(*getitem)(PyObject *, Py_ssize_t); Py_ssize_t lastarg = 0; @@ -3118,63 +3197,9 @@ lastarg = argc; argvlist[argc] = NULL; - i = PyMapping_Size(env); - if (i < 0) + envlist = parse_envlist(env, &envc); + if (envlist == NULL) goto fail_1; - envlist = PyMem_NEW(char *, i + 1); - if (envlist == NULL) { - PyErr_NoMemory(); - goto fail_1; - } - envc = 0; - keys = PyMapping_Keys(env); - vals = PyMapping_Values(env); - if (!keys || !vals) - goto fail_2; - if (!PyList_Check(keys) || !PyList_Check(vals)) { - PyErr_SetString(PyExc_TypeError, - "execve(): env.keys() or env.values() is not a list"); - goto fail_2; - } - - for (pos = 0; pos < i; pos++) { - char *p, *k, *v; - size_t len; - - key = PyList_GetItem(keys, pos); - val = PyList_GetItem(vals, pos); - if (!key || !val) - goto fail_2; - - if (!PyArg_Parse( - key, - "s;execve() arg 3 contains a non-string key", - &k) || - !PyArg_Parse( - val, - "s;execve() arg 3 contains a non-string value", - &v)) - { - goto fail_2; - } - -#if defined(PYOS_OS2) - /* Omit Pseudo-Env Vars that Would Confuse Programs if Passed On */ - if (stricmp(k, "BEGINLIBPATH") != 0 && stricmp(k, "ENDLIBPATH") != 0) { -#endif - len = PyUnicode_GetSize(key) + PyUnicode_GetSize(val) + 2; - p = PyMem_NEW(char, len); - if (p == NULL) { - PyErr_NoMemory(); - goto fail_2; - } - PyOS_snprintf(p, len, "%s=%s", k, v); - envlist[envc++] = p; -#if defined(PYOS_OS2) - } -#endif - } - envlist[envc] = 0; execve(path, argvlist, envlist); @@ -3182,14 +3207,11 @@ (void) posix_error(); - fail_2: while (--envc >= 0) PyMem_DEL(envlist[envc]); PyMem_DEL(envlist); fail_1: free_string_array(argvlist, lastarg); - Py_XDECREF(vals); - Py_XDECREF(keys); fail_0: Py_DECREF(opath); return NULL; @@ -3303,8 +3325,8 @@ PyObject *argv, *env; char **argvlist; char **envlist; - PyObject *key, *val, *keys=NULL, *vals=NULL, *res=NULL; - int mode, pos, envc; + PyObject *res = NULL; + int mode, envc; Py_ssize_t argc, i; Py_intptr_t spawnval; PyObject *(*getitem)(PyObject *, Py_ssize_t); @@ -3354,55 +3376,9 @@ lastarg = argc; argvlist[argc] = NULL; - i = PyMapping_Size(env); - if (i < 0) - goto fail_1; - envlist = PyMem_NEW(char *, i + 1); - if (envlist == NULL) { - PyErr_NoMemory(); + envlist = parse_envlist(env, &envc); + if (envlist == NULL) goto fail_1; - } - envc = 0; - keys = PyMapping_Keys(env); - vals = PyMapping_Values(env); - if (!keys || !vals) - goto fail_2; - if (!PyList_Check(keys) || !PyList_Check(vals)) { - PyErr_SetString(PyExc_TypeError, - "spawnve(): env.keys() or env.values() is not a list"); - goto fail_2; - } - - for (pos = 0; pos < i; pos++) { - char *p, *k, *v; - size_t len; - - key = PyList_GetItem(keys, pos); - val = PyList_GetItem(vals, pos); - if (!key || !val) - goto fail_2; - - if (!PyArg_Parse( - key, - "s;spawnve() arg 3 contains a non-string key", - &k) || - !PyArg_Parse( - val, - "s;spawnve() arg 3 contains a non-string value", - &v)) - { - goto fail_2; - } - len = PyUnicode_GetSize(key) + PyUnicode_GetSize(val) + 2; - p = PyMem_NEW(char, len); - if (p == NULL) { - PyErr_NoMemory(); - goto fail_2; - } - PyOS_snprintf(p, len, "%s=%s", k, v); - envlist[envc++] = p; - } - envlist[envc] = 0; #if defined(PYOS_OS2) && defined(PYCC_GCC) Py_BEGIN_ALLOW_THREADS @@ -3426,14 +3402,11 @@ res = Py_BuildValue("L", (PY_LONG_LONG) spawnval); #endif - fail_2: while (--envc >= 0) PyMem_DEL(envlist[envc]); PyMem_DEL(envlist); fail_1: free_string_array(argvlist, lastarg); - Py_XDECREF(vals); - Py_XDECREF(keys); fail_0: Py_DECREF(opath); return res; @@ -3538,8 +3511,8 @@ PyObject *argv, *env; char **argvlist; char **envlist; - PyObject *key, *val, *keys=NULL, *vals=NULL, *res=NULL; - int mode, i, pos, argc, envc; + PyObject *res=NULL; + int mode, i, argc, envc; Py_intptr_t spawnval; PyObject *(*getitem)(PyObject *, Py_ssize_t); int lastarg = 0; @@ -3588,55 +3561,9 @@ lastarg = argc; argvlist[argc] = NULL; - i = PyMapping_Size(env); - if (i < 0) + envlist = parse_envlist(env, &envc); + if (envlist == NULL) goto fail_1; - envlist = PyMem_NEW(char *, i + 1); - if (envlist == NULL) { - PyErr_NoMemory(); - goto fail_1; - } - envc = 0; - keys = PyMapping_Keys(env); - vals = PyMapping_Values(env); - if (!keys || !vals) - goto fail_2; - if (!PyList_Check(keys) || !PyList_Check(vals)) { - PyErr_SetString(PyExc_TypeError, - "spawnvpe(): env.keys() or env.values() is not a list"); - goto fail_2; - } - - for (pos = 0; pos < i; pos++) { - char *p, *k, *v; - size_t len; - - key = PyList_GetItem(keys, pos); - val = PyList_GetItem(vals, pos); - if (!key || !val) - goto fail_2; - - if (!PyArg_Parse( - key, - "s;spawnvpe() arg 3 contains a non-string key", - &k) || - !PyArg_Parse( - val, - "s;spawnvpe() arg 3 contains a non-string value", - &v)) - { - goto fail_2; - } - len = PyUnicode_GetSize(key) + PyUnicode_GetSize(val) + 2; - p = PyMem_NEW(char, len); - if (p == NULL) { - PyErr_NoMemory(); - goto fail_2; - } - PyOS_snprintf(p, len, "%s=%s", k, v); - envlist[envc++] = p; - } - envlist[envc] = 0; Py_BEGIN_ALLOW_THREADS #if defined(PYCC_GCC) @@ -3651,14 +3578,11 @@ else res = Py_BuildValue("l", (long) spawnval); - fail_2: while (--envc >= 0) PyMem_DEL(envlist[envc]); PyMem_DEL(envlist); fail_1: free_string_array(argvlist, lastarg); - Py_XDECREF(vals); - Py_XDECREF(keys); fail_0: Py_DECREF(opath); return res; Modified: python/branches/py3k-jit/Modules/socketmodule.c ============================================================================== --- python/branches/py3k-jit/Modules/socketmodule.c (original) +++ python/branches/py3k-jit/Modules/socketmodule.c Tue May 4 01:24:51 2010 @@ -1290,6 +1290,7 @@ char *straddr; addr = (struct sockaddr_l2 *)addr_ret; + memset(addr, 0, sizeof(struct sockaddr_l2)); _BT_L2_MEMB(addr, family) = AF_BLUETOOTH; if (!PyArg_ParseTuple(args, "si", &straddr, &_BT_L2_MEMB(addr, psm))) { Modified: python/branches/py3k-jit/Modules/syslogmodule.c ============================================================================== --- python/branches/py3k-jit/Modules/syslogmodule.c (original) +++ python/branches/py3k-jit/Modules/syslogmodule.c Tue May 4 01:24:51 2010 @@ -26,6 +26,11 @@ Revision history: +2010/04/20 (Sean Reifschneider) + - Use basename(sys.argv[0]) for the default "ident". + - Arguments to openlog() are now keyword args and are all optional. + - syslog() calls openlog() if it hasn't already been called. + 1998/04/28 (Sean Reifschneider) - When facility not specified to syslog() method, use default from openlog() (This is how it was claimed to work in the documentation) @@ -45,37 +50,93 @@ /* syslog module */ #include "Python.h" +#include "osdefs.h" #include /* only one instance, only one syslog, so globals should be ok */ static PyObject *S_ident_o = NULL; /* identifier, held by openlog() */ +static char S_log_open = 0; + + +static PyObject * +syslog_get_argv(void) +{ + /* Figure out what to use for as the program "ident" for openlog(). + * This swallows exceptions and continues rather than failing out, + * because the syslog module can still be used because openlog(3) + * is optional. + */ + + Py_ssize_t argv_len; + PyObject *scriptobj; + char *atslash; + PyObject *argv = PySys_GetObject("argv"); + + if (argv == NULL) { + return(NULL); + } + + argv_len = PyList_Size(argv); + if (argv_len == -1) { + PyErr_Clear(); + return(NULL); + } + if (argv_len == 0) { + return(NULL); + } + + scriptobj = PyList_GetItem(argv, 0); + if (!PyUnicode_Check(scriptobj)) { + return(NULL); + } + if (PyUnicode_GET_SIZE(scriptobj) == 0) { + return(NULL); + } + + atslash = strrchr(_PyUnicode_AsString(scriptobj), SEP); + if (atslash) { + return(PyUnicode_FromString(atslash + 1)); + } else { + Py_INCREF(scriptobj); + return(scriptobj); + } + + return(NULL); +} static PyObject * -syslog_openlog(PyObject * self, PyObject * args) +syslog_openlog(PyObject * self, PyObject * args, PyObject *kwds) { long logopt = 0; long facility = LOG_USER; - PyObject *new_S_ident_o; - const char *ident; + PyObject *new_S_ident_o = NULL; + static char *keywords[] = {"ident", "logoption", "facility", 0}; - if (!PyArg_ParseTuple(args, - "U|ll;ident string [, logoption [, facility]]", - &new_S_ident_o, &logopt, &facility)) + if (!PyArg_ParseTupleAndKeywords(args, kwds, + "|Ull:openlog", keywords, &new_S_ident_o, &logopt, &facility)) return NULL; - /* This is needed because openlog() does NOT make a copy - * and syslog() later uses it.. cannot trash it. - */ + if (new_S_ident_o) { + Py_INCREF(new_S_ident_o); + } + + /* get sys.argv[0] or NULL if we can't for some reason */ + if (!new_S_ident_o) { + new_S_ident_o = syslog_get_argv(); + } + Py_XDECREF(S_ident_o); S_ident_o = new_S_ident_o; - Py_INCREF(S_ident_o); - ident = _PyUnicode_AsString(S_ident_o); - if (ident == NULL) - return NULL; - openlog(ident, logopt, facility); + /* At this point, S_ident_o should be INCREF()ed. openlog(3) does not + * make a copy, and syslog(3) later uses it. We can't garbagecollect it + * If NULL, just let openlog figure it out (probably using C argv[0]). + */ + + openlog(S_ident_o ? _PyUnicode_AsString(S_ident_o) : NULL, logopt, facility); + S_log_open = 1; Py_INCREF(Py_None); return Py_None; @@ -100,6 +161,22 @@ message = _PyUnicode_AsString(message_object); if (message == NULL) return NULL; + + /* if log is not opened, open it now */ + if (!S_log_open) { + PyObject *openargs; + + /* Continue even if PyTuple_New fails, because openlog(3) is optional. + * So, we can still do loggin in the unlikely event things are so hosed + * that we can't do this tuple. + */ + if ((openargs = PyTuple_New(0))) { + PyObject *openlog_ret = syslog_openlog(self, openargs, NULL); + Py_XDECREF(openlog_ret); + Py_DECREF(openargs); + } + } + Py_BEGIN_ALLOW_THREADS; syslog(priority, "%s", message); Py_END_ALLOW_THREADS; @@ -109,9 +186,12 @@ static PyObject * syslog_closelog(PyObject *self, PyObject *unused) { - closelog(); - Py_XDECREF(S_ident_o); - S_ident_o = NULL; + if (S_log_open) { + closelog(); + Py_XDECREF(S_ident_o); + S_ident_o = NULL; + S_log_open = 0; + } Py_INCREF(Py_None); return Py_None; } @@ -152,7 +232,7 @@ /* List of functions defined in the module */ static PyMethodDef syslog_methods[] = { - {"openlog", syslog_openlog, METH_VARARGS}, + {"openlog", (PyCFunction) syslog_openlog, METH_VARARGS | METH_KEYWORDS}, {"closelog", syslog_closelog, METH_NOARGS}, {"syslog", syslog_syslog, METH_VARARGS}, {"setlogmask", syslog_setlogmask, METH_VARARGS}, Modified: python/branches/py3k-jit/Objects/dictobject.c ============================================================================== --- python/branches/py3k-jit/Objects/dictobject.c (original) +++ python/branches/py3k-jit/Objects/dictobject.c Tue May 4 01:24:51 2010 @@ -458,6 +458,21 @@ return 0; } +int +_PyDict_HasOnlyStringKeys(PyObject *dict) +{ + Py_ssize_t pos = 0; + PyObject *key, *value; + assert(PyDict_CheckExact(dict)); + /* Shortcut */ + if (((PyDictObject *)dict)->ma_lookup == lookdict_unicode) + return 1; + while (PyDict_Next(dict, &pos, &key, &value)) + if (!PyUnicode_Check(key)) + return 0; + return 1; +} + #ifdef SHOW_TRACK_COUNT #define INCREASE_TRACK_COUNT \ (count_tracked++, count_untracked--); @@ -719,7 +734,8 @@ Let's just hope that no exception occurs then... This must be _PyThreadState_Current and not PyThreadState_GET() because in debug mode, the latter complains if tstate is NULL. */ - tstate = _PyThreadState_Current; + tstate = (PyThreadState*)_Py_atomic_load_relaxed( + &_PyThreadState_Current); if (tstate != NULL && tstate->curexc_type != NULL) { /* preserve the existing exception */ PyObject *err_type, *err_value, *err_tb; @@ -1386,8 +1402,12 @@ else result = PyDict_MergeFromSeq2(self, arg, 1); } - if (result == 0 && kwds != NULL) - result = PyDict_Merge(self, kwds, 1); + if (result == 0 && kwds != NULL) { + if (PyArg_ValidateKeywordArguments(kwds)) + result = PyDict_Merge(self, kwds, 1); + else + result = -1; + } return result; } Modified: python/branches/py3k-jit/Objects/exceptions.c ============================================================================== --- python/branches/py3k-jit/Objects/exceptions.c (original) +++ python/branches/py3k-jit/Objects/exceptions.c Tue May 4 01:24:51 2010 @@ -959,20 +959,27 @@ /* This is called "my_basename" instead of just "basename" to avoid name conflicts with glibc; basename is already prototyped if _GNU_SOURCE is defined, and Python does define that. */ -static char * -my_basename(char *name) +static PyObject* +my_basename(PyObject *name) { - char *cp = name; - char *result = name; + Py_UNICODE *unicode; + Py_ssize_t i, size, offset; - if (name == NULL) - return "???"; - while (*cp != '\0') { - if (*cp == SEP) - result = cp + 1; - ++cp; + unicode = PyUnicode_AS_UNICODE(name); + size = PyUnicode_GET_SIZE(name); + offset = 0; + for(i=0; i < size; i++) { + if (unicode[i] == SEP) + offset = i + 1; + } + if (offset != 0) { + return PyUnicode_FromUnicode( + PyUnicode_AS_UNICODE(name) + offset, + size - offset); + } else { + Py_INCREF(name); + return name; } - return result; } @@ -980,7 +987,8 @@ SyntaxError_str(PySyntaxErrorObject *self) { int have_lineno = 0; - char *filename = 0; + PyObject *filename; + PyObject *result; /* Below, we always ignore overflow errors, just printing -1. Still, we cannot allow an OverflowError to be raised, so we need to call PyLong_AsLongAndOverflow. */ @@ -990,7 +998,11 @@ lineno here */ if (self->filename && PyUnicode_Check(self->filename)) { - filename = _PyUnicode_AsString(self->filename); + filename = my_basename(self->filename); + if (filename == NULL) + return NULL; + } else { + filename = NULL; } have_lineno = (self->lineno != NULL) && PyLong_CheckExact(self->lineno); @@ -998,18 +1010,20 @@ return PyObject_Str(self->msg ? self->msg : Py_None); if (filename && have_lineno) - return PyUnicode_FromFormat("%S (%s, line %ld)", + result = PyUnicode_FromFormat("%S (%U, line %ld)", self->msg ? self->msg : Py_None, - my_basename(filename), + filename, PyLong_AsLongAndOverflow(self->lineno, &overflow)); else if (filename) - return PyUnicode_FromFormat("%S (%s)", + result = PyUnicode_FromFormat("%S (%U)", self->msg ? self->msg : Py_None, - my_basename(filename)); + filename); else /* only have_lineno */ - return PyUnicode_FromFormat("%S (line %ld)", + result = PyUnicode_FromFormat("%S (line %ld)", self->msg ? self->msg : Py_None, PyLong_AsLongAndOverflow(self->lineno, &overflow)); + Py_XDECREF(filename); + return result; } static PyMemberDef SyntaxError_members[] = { Modified: python/branches/py3k-jit/Objects/fileobject.c ============================================================================== --- python/branches/py3k-jit/Objects/fileobject.c (original) +++ python/branches/py3k-jit/Objects/fileobject.c Tue May 4 01:24:51 2010 @@ -41,7 +41,7 @@ if (stream == NULL) return NULL; if (name != NULL) { - nameobj = PyUnicode_FromString(name); + nameobj = PyUnicode_DecodeFSDefault(name); if (nameobj == NULL) PyErr_Clear(); else { Modified: python/branches/py3k-jit/Objects/unicodeobject.c ============================================================================== --- python/branches/py3k-jit/Objects/unicodeobject.c (original) +++ python/branches/py3k-jit/Objects/unicodeobject.c Tue May 4 01:24:51 2010 @@ -1600,19 +1600,19 @@ if (Py_FileSystemDefaultEncoding) { #if defined(MS_WINDOWS) && defined(HAVE_USABLE_WCHAR_T) if (strcmp(Py_FileSystemDefaultEncoding, "mbcs") == 0) { - return PyUnicode_DecodeMBCS(s, size, "replace"); + return PyUnicode_DecodeMBCS(s, size, "surrogateescape"); } #elif defined(__APPLE__) if (strcmp(Py_FileSystemDefaultEncoding, "utf-8") == 0) { - return PyUnicode_DecodeUTF8(s, size, "replace"); + return PyUnicode_DecodeUTF8(s, size, "surrogateescape"); } #endif return PyUnicode_Decode(s, size, Py_FileSystemDefaultEncoding, - "replace"); + "surrogateescape"); } else { - return PyUnicode_DecodeUTF8(s, size, "replace"); + return PyUnicode_DecodeUTF8(s, size, "surrogateescape"); } } @@ -1638,7 +1638,7 @@ arg = PyUnicode_FromObject(arg); if (!arg) return 0; - output = PyUnicode_AsEncodedObject(arg, + output = PyUnicode_AsEncodedObject(arg, Py_FileSystemDefaultEncoding, "surrogateescape"); Py_DECREF(arg); @@ -1650,14 +1650,8 @@ return 0; } } - if (PyBytes_Check(output)) { - size = PyBytes_GET_SIZE(output); - data = PyBytes_AS_STRING(output); - } - else { - size = PyByteArray_GET_SIZE(output); - data = PyByteArray_AS_STRING(output); - } + size = PyBytes_GET_SIZE(output); + data = PyBytes_AS_STRING(output); if (size != strlen(data)) { PyErr_SetString(PyExc_TypeError, "embedded NUL character"); Py_DECREF(output); @@ -6784,10 +6778,7 @@ return ((int)id[i] < (int)str[i]) ? -1 : 1; /* This check keeps Python strings that end in '\0' from comparing equal to C strings identical up to that point. */ - if (PyUnicode_GET_SIZE(uni) != i) - /* We'll say the Python string is longer. */ - return 1; - if (id[i]) + if (PyUnicode_GET_SIZE(uni) != i || id[i]) return 1; /* uni is longer */ if (str[i]) return -1; /* str is longer */ Modified: python/branches/py3k-jit/PC/VS7.1/pythoncore.vcproj ============================================================================== --- python/branches/py3k-jit/PC/VS7.1/pythoncore.vcproj (original) +++ python/branches/py3k-jit/PC/VS7.1/pythoncore.vcproj Tue May 4 01:24:51 2010 @@ -508,6 +508,9 @@ RelativePath="..\..\PC\config.c"> + + + + @@ -1655,6 +1659,10 @@ > + + Modified: python/branches/py3k-jit/PC/_subprocess.c ============================================================================== --- python/branches/py3k-jit/PC/_subprocess.c (original) +++ python/branches/py3k-jit/PC/_subprocess.c Tue May 4 01:24:51 2010 @@ -158,6 +158,13 @@ /* -------------------------------------------------------------------- */ /* windows API functions */ +PyDoc_STRVAR(GetStdHandle_doc, +"GetStdHandle(handle) -> integer\n\ +\n\ +Return a handle to the specified standard device\n\ +(STD_INPUT_HANDLE, STD_OUTPUT_HANDLE, STD_ERROR_HANDLE).\n\ +The integer associated with the handle object is returned."); + static PyObject * sp_GetStdHandle(PyObject* self, PyObject* args) { @@ -183,6 +190,11 @@ return HANDLE_TO_PYNUM(handle); } +PyDoc_STRVAR(GetCurrentProcess_doc, +"GetCurrentProcess() -> handle\n\ +\n\ +Return a handle object for the current process."); + static PyObject * sp_GetCurrentProcess(PyObject* self, PyObject* args) { @@ -192,6 +204,17 @@ return sp_handle_new(GetCurrentProcess()); } +PyDoc_STRVAR(DuplicateHandle_doc, +"DuplicateHandle(source_proc_handle, source_handle,\n\ + target_proc_handle, target_handle, access,\n\ + inherit[, options]) -> handle\n\ +\n\ +Return a duplicate handle object.\n\ +\n\ +The duplicate handle refers to the same object as the original\n\ +handle. Therefore, any changes to the object are reflected\n\ +through both handles."); + static PyObject * sp_DuplicateHandle(PyObject* self, PyObject* args) { @@ -234,6 +257,14 @@ return sp_handle_new(target_handle); } +PyDoc_STRVAR(CreatePipe_doc, +"CreatePipe(pipe_attrs, size) -> (read_handle, write_handle)\n\ +\n\ +Create an anonymous pipe, and return handles to the read and\n\ +write ends of the pipe.\n\ +\n\ +pipe_attrs is ignored internally and can be None."); + static PyObject * sp_CreatePipe(PyObject* self, PyObject* args) { @@ -369,6 +400,18 @@ return NULL; } +PyDoc_STRVAR(CreateProcess_doc, +"CreateProcess(app_name, cmd_line, proc_attrs, thread_attrs,\n\ + inherit, flags, env_mapping, curdir,\n\ + startup_info) -> (proc_handle, thread_handle,\n\ + pid, tid)\n\ +\n\ +Create a new process and its primary thread. The return\n\ +value is a tuple of the process handle, thread handle,\n\ +process ID, and thread ID.\n\ +\n\ +proc_attrs and thread_attrs are ignored internally and can be None."); + static PyObject * sp_CreateProcess(PyObject* self, PyObject* args) { @@ -445,6 +488,11 @@ pi.dwThreadId); } +PyDoc_STRVAR(TerminateProcess_doc, +"TerminateProcess(handle, exit_code) -> None\n\ +\n\ +Terminate the specified process and all of its threads."); + static PyObject * sp_TerminateProcess(PyObject* self, PyObject* args) { @@ -465,6 +513,11 @@ return Py_None; } +PyDoc_STRVAR(GetExitCodeProcess_doc, +"GetExitCodeProcess(handle) -> Exit code\n\ +\n\ +Return the termination status of the specified process."); + static PyObject * sp_GetExitCodeProcess(PyObject* self, PyObject* args) { @@ -483,6 +536,13 @@ return PyLong_FromLong(exit_code); } +PyDoc_STRVAR(WaitForSingleObject_doc, +"WaitForSingleObject(handle, timeout) -> result\n\ +\n\ +Wait until the specified object is in the signaled state or\n\ +the time-out interval elapses. The timeout value is specified\n\ +in milliseconds."); + static PyObject * sp_WaitForSingleObject(PyObject* self, PyObject* args) { @@ -505,6 +565,11 @@ return PyLong_FromLong((int) result); } +PyDoc_STRVAR(GetVersion_doc, +"GetVersion() -> version\n\ +\n\ +Return the version number of the current operating system."); + static PyObject * sp_GetVersion(PyObject* self, PyObject* args) { @@ -514,6 +579,18 @@ return PyLong_FromLong((int) GetVersion()); } +PyDoc_STRVAR(GetModuleFileName_doc, +"GetModuleFileName(module) -> path\n\ +\n\ +Return the fully-qualified path for the file that contains\n\ +the specified module. The module must have been loaded by the\n\ +current process.\n\ +\n\ +The module parameter should be a handle to the loaded module\n\ +whose path is being requested. If this parameter is 0, \n\ +GetModuleFileName retrieves the path of the executable file\n\ +of the current process."); + static PyObject * sp_GetModuleFileName(PyObject* self, PyObject* args) { @@ -535,16 +612,22 @@ } static PyMethodDef sp_functions[] = { - {"GetStdHandle", sp_GetStdHandle, METH_VARARGS}, - {"GetCurrentProcess", sp_GetCurrentProcess, METH_VARARGS}, - {"DuplicateHandle", sp_DuplicateHandle, METH_VARARGS}, - {"CreatePipe", sp_CreatePipe, METH_VARARGS}, - {"CreateProcess", sp_CreateProcess, METH_VARARGS}, - {"TerminateProcess", sp_TerminateProcess, METH_VARARGS}, - {"GetExitCodeProcess", sp_GetExitCodeProcess, METH_VARARGS}, - {"WaitForSingleObject", sp_WaitForSingleObject, METH_VARARGS}, - {"GetVersion", sp_GetVersion, METH_VARARGS}, - {"GetModuleFileName", sp_GetModuleFileName, METH_VARARGS}, + {"GetStdHandle", sp_GetStdHandle, METH_VARARGS, GetStdHandle_doc}, + {"GetCurrentProcess", sp_GetCurrentProcess, METH_VARARGS, + GetCurrentProcess_doc}, + {"DuplicateHandle", sp_DuplicateHandle, METH_VARARGS, + DuplicateHandle_doc}, + {"CreatePipe", sp_CreatePipe, METH_VARARGS, CreatePipe_doc}, + {"CreateProcess", sp_CreateProcess, METH_VARARGS, CreateProcess_doc}, + {"TerminateProcess", sp_TerminateProcess, METH_VARARGS, + TerminateProcess_doc}, + {"GetExitCodeProcess", sp_GetExitCodeProcess, METH_VARARGS, + GetExitCodeProcess_doc}, + {"WaitForSingleObject", sp_WaitForSingleObject, METH_VARARGS, + WaitForSingleObject_doc}, + {"GetVersion", sp_GetVersion, METH_VARARGS, GetVersion_doc}, + {"GetModuleFileName", sp_GetModuleFileName, METH_VARARGS, + GetModuleFileName_doc}, {NULL, NULL} }; Modified: python/branches/py3k-jit/PC/os2emx/Makefile ============================================================================== --- python/branches/py3k-jit/PC/os2emx/Makefile (original) +++ python/branches/py3k-jit/PC/os2emx/Makefile Tue May 4 01:24:51 2010 @@ -332,6 +332,7 @@ Python/ceval.c \ Python/compile.c \ Python/codecs.c \ + Python/dynamic_annotations.c \ Python/errors.c \ Python/frozen.c \ Python/frozenmain.c \ Modified: python/branches/py3k-jit/PCbuild/pythoncore.vcproj ============================================================================== --- python/branches/py3k-jit/PCbuild/pythoncore.vcproj (original) +++ python/branches/py3k-jit/PCbuild/pythoncore.vcproj Tue May 4 01:24:51 2010 @@ -703,6 +703,10 @@ > + + @@ -1660,6 +1664,10 @@ > + + Modified: python/branches/py3k-jit/Parser/tokenizer.c ============================================================================== --- python/branches/py3k-jit/Parser/tokenizer.c (original) +++ python/branches/py3k-jit/Parser/tokenizer.c Tue May 4 01:24:51 2010 @@ -580,16 +580,14 @@ } } if (badchar) { - char buf[500]; /* Need to add 1 to the line number, since this line has not been counted, yet. */ - sprintf(buf, + PyErr_Format(PyExc_SyntaxError, "Non-UTF-8 code starting with '\\x%.2x' " "in file %.200s on line %i, " "but no encoding declared; " "see http://python.org/dev/peps/pep-0263/ for details", badchar, tok->filename, tok->lineno + 1); - PyErr_SetString(PyExc_SyntaxError, buf); return error_ret(tok); } #endif Modified: python/branches/py3k-jit/Python/ceval.c ============================================================================== --- python/branches/py3k-jit/Python/ceval.c (original) +++ python/branches/py3k-jit/Python/ceval.c Tue May 4 01:24:51 2010 @@ -216,23 +216,46 @@ #endif +/* This can set eval_breaker to 0 even though gil_drop_request became + 1. We believe this is all right because the eval loop will release + the GIL eventually anyway. */ #define COMPUTE_EVAL_BREAKER() \ - (eval_breaker = gil_drop_request | pendingcalls_to_do | pending_async_exc) + _Py_atomic_store_relaxed( \ + &eval_breaker, \ + _Py_atomic_load_relaxed(&gil_drop_request) | \ + _Py_atomic_load_relaxed(&pendingcalls_to_do) | \ + pending_async_exc) #define SET_GIL_DROP_REQUEST() \ - do { gil_drop_request = 1; eval_breaker = 1; } while (0) + do { \ + _Py_atomic_store_relaxed(&gil_drop_request, 1); \ + _Py_atomic_store_relaxed(&eval_breaker, 1); \ + } while (0) #define RESET_GIL_DROP_REQUEST() \ - do { gil_drop_request = 0; COMPUTE_EVAL_BREAKER(); } while (0) + do { \ + _Py_atomic_store_relaxed(&gil_drop_request, 0); \ + COMPUTE_EVAL_BREAKER(); \ + } while (0) +/* Pending calls are only modified under pending_lock */ #define SIGNAL_PENDING_CALLS() \ - do { pendingcalls_to_do = 1; eval_breaker = 1; } while (0) + do { \ + _Py_atomic_store_relaxed(&pendingcalls_to_do, 1); \ + _Py_atomic_store_relaxed(&eval_breaker, 1); \ + } while (0) #define UNSIGNAL_PENDING_CALLS() \ - do { pendingcalls_to_do = 0; COMPUTE_EVAL_BREAKER(); } while (0) + do { \ + _Py_atomic_store_relaxed(&pendingcalls_to_do, 0); \ + COMPUTE_EVAL_BREAKER(); \ + } while (0) #define SIGNAL_ASYNC_EXC() \ - do { pending_async_exc = 1; eval_breaker = 1; } while (0) + do { \ + pending_async_exc = 1; \ + _Py_atomic_store_relaxed(&eval_breaker, 1); \ + } while (0) #define UNSIGNAL_ASYNC_EXC() \ do { pending_async_exc = 0; COMPUTE_EVAL_BREAKER(); } while (0) @@ -249,13 +272,14 @@ static long main_thread = 0; /* This single variable consolidates all requests to break out of the fast path in the eval loop. */ -static volatile int eval_breaker = 0; -/* Request for droppping the GIL */ -static volatile int gil_drop_request = 0; -/* Request for running pending calls */ -static volatile int pendingcalls_to_do = 0; -/* Request for looking at the `async_exc` field of the current thread state */ -static volatile int pending_async_exc = 0; +static _Py_atomic_int eval_breaker = {0}; +/* Request for dropping the GIL */ +static _Py_atomic_int gil_drop_request = {0}; +/* Request for running pending calls. */ +static _Py_atomic_int pendingcalls_to_do = {0}; +/* Request for looking at the `async_exc` field of the current thread state. + Guarded by the GIL. */ +static int pending_async_exc = 0; #include "ceval_gil.h" @@ -293,7 +317,8 @@ We therefore avoid PyThreadState_GET() which dumps a fatal error in debug mode. */ - drop_gil(_PyThreadState_Current); + drop_gil((PyThreadState*)_Py_atomic_load_relaxed( + &_PyThreadState_Current)); } void @@ -360,8 +385,8 @@ } #else -static int eval_breaker = 0; -static int gil_drop_request = 0; +static _Py_atomic_int eval_breaker = {0}; +static _Py_atomic_int gil_drop_request = {0}; static int pending_async_exc = 0; #endif /* WITH_THREAD */ @@ -843,7 +868,7 @@ #define DISPATCH() \ { \ - if (!eval_breaker) { \ + if (!_Py_atomic_load_relaxed(&eval_breaker)) { \ FAST_DISPATCH(); \ } \ continue; \ @@ -1217,7 +1242,7 @@ async I/O handler); see Py_AddPendingCall() and Py_MakePendingCalls() above. */ - if (eval_breaker) { + if (_Py_atomic_load_relaxed(&eval_breaker)) { if (*next_instr == SETUP_FINALLY) { /* Make the last opcode before a try: finally: block uninterruptable. */ @@ -1227,13 +1252,13 @@ #ifdef WITH_TSC ticked = 1; #endif - if (pendingcalls_to_do) { + if (_Py_atomic_load_relaxed(&pendingcalls_to_do)) { if (Py_MakePendingCalls() < 0) { why = WHY_EXCEPTION; goto on_error; } } - if (gil_drop_request) { + if (_Py_atomic_load_relaxed(&gil_drop_request)) { #ifdef WITH_THREAD /* Give another thread a chance */ if (PyThreadState_Swap(NULL) != tstate) Modified: python/branches/py3k-jit/Python/ceval_gil.h ============================================================================== --- python/branches/py3k-jit/Python/ceval_gil.h (original) +++ python/branches/py3k-jit/Python/ceval_gil.h Tue May 4 01:24:51 2010 @@ -207,14 +207,14 @@ #endif /* _POSIX_THREADS, NT_THREADS */ -/* Whether the GIL is already taken (-1 if uninitialized). This is volatile +/* Whether the GIL is already taken (-1 if uninitialized). This is atomic because it can be read without any lock taken in ceval.c. */ -static volatile int gil_locked = -1; +static _Py_atomic_int gil_locked = {-1}; /* Number of GIL switches since the beginning. */ static unsigned long gil_switch_number = 0; -/* Last thread holding / having held the GIL. This helps us know whether - anyone else was scheduled after we dropped the GIL. */ -static PyThreadState *gil_last_holder = NULL; +/* Last PyThreadState holding / having held the GIL. This helps us know + whether anyone else was scheduled after we dropped the GIL. */ +static _Py_atomic_address gil_last_holder = {NULL}; /* This condition variable allows one or several threads to wait until the GIL is released. In addition, the mutex also protects the above @@ -232,7 +232,7 @@ static int gil_created(void) { - return gil_locked >= 0; + return _Py_atomic_load_explicit(&gil_locked, _Py_memory_order_acquire) >= 0; } static void create_gil(void) @@ -245,33 +245,37 @@ #ifdef FORCE_SWITCHING COND_INIT(switch_cond); #endif - gil_locked = 0; - gil_last_holder = NULL; + _Py_atomic_store_relaxed(&gil_last_holder, NULL); + _Py_ANNOTATE_RWLOCK_CREATE(&gil_locked); + _Py_atomic_store_explicit(&gil_locked, 0, _Py_memory_order_release); } static void recreate_gil(void) { + _Py_ANNOTATE_RWLOCK_DESTROY(&gil_locked); create_gil(); } static void drop_gil(PyThreadState *tstate) { /* NOTE: tstate is allowed to be NULL. */ - if (!gil_locked) + if (!_Py_atomic_load_relaxed(&gil_locked)) Py_FatalError("drop_gil: GIL is not locked"); - if (tstate != NULL && tstate != gil_last_holder) + if (tstate != NULL && + tstate != _Py_atomic_load_relaxed(&gil_last_holder)) Py_FatalError("drop_gil: wrong thread state"); MUTEX_LOCK(gil_mutex); - gil_locked = 0; + _Py_ANNOTATE_RWLOCK_RELEASED(&gil_locked, /*is_write=*/1); + _Py_atomic_store_relaxed(&gil_locked, 0); COND_SIGNAL(gil_cond); MUTEX_UNLOCK(gil_mutex); #ifdef FORCE_SWITCHING - if (gil_drop_request && tstate != NULL) { + if (_Py_atomic_load_relaxed(&gil_drop_request) && tstate != NULL) { MUTEX_LOCK(switch_mutex); /* Not switched yet => wait */ - if (gil_last_holder == tstate) { + if (_Py_atomic_load_relaxed(&gil_last_holder) == tstate) { RESET_GIL_DROP_REQUEST(); /* NOTE: if COND_WAIT does not atomically start waiting when releasing the mutex, another thread can run through, take @@ -294,11 +298,11 @@ err = errno; MUTEX_LOCK(gil_mutex); - if (!gil_locked) + if (!_Py_atomic_load_relaxed(&gil_locked)) goto _ready; COND_RESET(gil_cond); - while (gil_locked) { + while (_Py_atomic_load_relaxed(&gil_locked)) { int timed_out = 0; unsigned long saved_switchnum; @@ -306,7 +310,9 @@ COND_TIMED_WAIT(gil_cond, gil_mutex, INTERVAL, timed_out); /* If we timed out and no switch occurred in the meantime, it is time to ask the GIL-holding thread to drop it. */ - if (timed_out && gil_locked && gil_switch_number == saved_switchnum) { + if (timed_out && + _Py_atomic_load_relaxed(&gil_locked) && + gil_switch_number == saved_switchnum) { SET_GIL_DROP_REQUEST(); } } @@ -316,17 +322,19 @@ MUTEX_LOCK(switch_mutex); #endif /* We now hold the GIL */ - gil_locked = 1; + _Py_atomic_store_relaxed(&gil_locked, 1); + _Py_ANNOTATE_RWLOCK_ACQUIRED(&gil_locked, /*is_write=*/1); - if (tstate != gil_last_holder) { - gil_last_holder = tstate; + if (tstate != _Py_atomic_load_relaxed(&gil_last_holder)) { + _Py_atomic_store_relaxed(&gil_last_holder, tstate); ++gil_switch_number; } + #ifdef FORCE_SWITCHING COND_SIGNAL(switch_cond); MUTEX_UNLOCK(switch_mutex); #endif - if (gil_drop_request) { + if (_Py_atomic_load_relaxed(&gil_drop_request)) { RESET_GIL_DROP_REQUEST(); } if (tstate->async_exc != NULL) { Modified: python/branches/py3k-jit/Python/getargs.c ============================================================================== --- python/branches/py3k-jit/Python/getargs.c (original) +++ python/branches/py3k-jit/Python/getargs.c Tue May 4 01:24:51 2010 @@ -1607,6 +1607,21 @@ return retval; } +int +PyArg_ValidateKeywordArguments(PyObject *kwargs) +{ + if (!PyDict_CheckExact(kwargs)) { + PyErr_BadInternalCall(); + return 0; + } + if (!_PyDict_HasOnlyStringKeys(kwargs)) { + PyErr_SetString(PyExc_TypeError, + "keyword arguments must be strings"); + return 0; + } + return 1; +} + #define IS_END_OF_FORMAT(c) (c == '\0' || c == ';' || c == ':') static int Modified: python/branches/py3k-jit/Python/pystate.c ============================================================================== --- python/branches/py3k-jit/Python/pystate.c (original) +++ python/branches/py3k-jit/Python/pystate.c Tue May 4 01:24:51 2010 @@ -47,7 +47,9 @@ static PyInterpreterState *interp_head = NULL; -PyThreadState *_PyThreadState_Current = NULL; +/* Assuming the current thread holds the GIL, this is the + PyThreadState for the current thread. */ +_Py_atomic_address _PyThreadState_Current = {NULL}; PyThreadFrameGetter _PyThreadState_GetFrame = NULL; #ifdef WITH_THREAD @@ -334,7 +336,7 @@ void PyThreadState_Delete(PyThreadState *tstate) { - if (tstate == _PyThreadState_Current) + if (tstate == _Py_atomic_load_relaxed(&_PyThreadState_Current)) Py_FatalError("PyThreadState_Delete: tstate is still current"); tstate_delete_common(tstate); #ifdef WITH_THREAD @@ -348,11 +350,12 @@ void PyThreadState_DeleteCurrent() { - PyThreadState *tstate = _PyThreadState_Current; + PyThreadState *tstate = (PyThreadState*)_Py_atomic_load_relaxed( + &_PyThreadState_Current); if (tstate == NULL) Py_FatalError( "PyThreadState_DeleteCurrent: no current tstate"); - _PyThreadState_Current = NULL; + _Py_atomic_store_relaxed(&_PyThreadState_Current, NULL); tstate_delete_common(tstate); if (autoTLSkey && PyThread_get_key_value(autoTLSkey) == tstate) PyThread_delete_key_value(autoTLSkey); @@ -364,19 +367,22 @@ PyThreadState * PyThreadState_Get(void) { - if (_PyThreadState_Current == NULL) + PyThreadState *tstate = (PyThreadState*)_Py_atomic_load_relaxed( + &_PyThreadState_Current); + if (tstate == NULL) Py_FatalError("PyThreadState_Get: no current thread"); - return _PyThreadState_Current; + return tstate; } PyThreadState * PyThreadState_Swap(PyThreadState *newts) { - PyThreadState *oldts = _PyThreadState_Current; + PyThreadState *oldts = (PyThreadState*)_Py_atomic_load_relaxed( + &_PyThreadState_Current); - _PyThreadState_Current = newts; + _Py_atomic_store_relaxed(&_PyThreadState_Current, newts); /* It should not be possible for more than one thread state to be used for a thread. Check this the best we can in debug builds. @@ -405,16 +411,18 @@ PyObject * PyThreadState_GetDict(void) { - if (_PyThreadState_Current == NULL) + PyThreadState *tstate = (PyThreadState*)_Py_atomic_load_relaxed( + &_PyThreadState_Current); + if (tstate == NULL) return NULL; - if (_PyThreadState_Current->dict == NULL) { + if (tstate->dict == NULL) { PyObject *d; - _PyThreadState_Current->dict = d = PyDict_New(); + tstate->dict = d = PyDict_New(); if (d == NULL) PyErr_Clear(); } - return _PyThreadState_Current->dict; + return tstate->dict; } @@ -550,10 +558,7 @@ { /* Must be the tstate for this thread */ assert(PyGILState_GetThisThreadState()==tstate); - /* On Windows at least, simple reads and writes to 32 bit values - are atomic. - */ - return tstate == _PyThreadState_Current; + return tstate == _Py_atomic_load_relaxed(&_PyThreadState_Current); } /* Internal initialization/finalization functions called by Modified: python/branches/py3k-jit/Python/sysmodule.c ============================================================================== --- python/branches/py3k-jit/Python/sysmodule.c (original) +++ python/branches/py3k-jit/Python/sysmodule.c Tue May 4 01:24:51 2010 @@ -1763,6 +1763,45 @@ Py_DECREF(av); } +/* Reimplementation of PyFile_WriteString() no calling indirectly + PyErr_CheckSignals(): avoid the call to PyObject_Str(). */ + +static int +sys_pyfile_write(const char *text, PyObject *file) +{ + PyObject *unicode = NULL, *writer = NULL, *args = NULL, *result = NULL; + int err; + + unicode = PyUnicode_FromString(text); + if (unicode == NULL) + goto error; + + writer = PyObject_GetAttrString(file, "write"); + if (writer == NULL) + goto error; + + args = PyTuple_Pack(1, unicode); + if (args == NULL) + goto error; + + result = PyEval_CallObject(writer, args); + if (result == NULL) { + goto error; + } else { + err = 0; + goto finally; + } + +error: + err = -1; +finally: + Py_XDECREF(unicode); + Py_XDECREF(writer); + Py_XDECREF(args); + Py_XDECREF(result); + return err; +} + /* APIs to write to sys.stdout or sys.stderr using a printf-like interface. Adapted from code submitted by Just van Rossum. @@ -1774,6 +1813,10 @@ there is a problem, they write to the real (C level) stdout or stderr; no exceptions are raised. + PyErr_CheckSignals() is not called to avoid the execution of the Python + signal handlers: they may raise a new exception whereas mywrite() ignores + all exceptions. + Both take a printf-style format string as their first argument followed by a variable length argument list determined by the format string. @@ -1799,13 +1842,13 @@ PyErr_Fetch(&error_type, &error_value, &error_traceback); file = PySys_GetObject(name); written = PyOS_vsnprintf(buffer, sizeof(buffer), format, va); - if (PyFile_WriteString(buffer, file) != 0) { + if (sys_pyfile_write(buffer, file) != 0) { PyErr_Clear(); fputs(buffer, fp); } if (written < 0 || (size_t)written >= sizeof(buffer)) { const char *truncated = "... truncated"; - if (PyFile_WriteString(truncated, file) != 0) { + if (sys_pyfile_write(truncated, file) != 0) { PyErr_Clear(); fputs(truncated, fp); } Modified: python/branches/py3k-jit/Python/thread_pthread.h ============================================================================== --- python/branches/py3k-jit/Python/thread_pthread.h (original) +++ python/branches/py3k-jit/Python/thread_pthread.h Tue May 4 01:24:51 2010 @@ -397,6 +397,12 @@ status = pthread_mutex_init(&lock->mut, pthread_mutexattr_default); CHECK_STATUS("pthread_mutex_init"); + /* Mark the pthread mutex underlying a Python mutex as + pure happens-before. We can't simply mark the + Python-level mutex as a mutex because it can be + acquired and released in different threads, which + will cause errors. */ + _Py_ANNOTATE_PURE_HAPPENS_BEFORE_MUTEX(&lock->mut); status = pthread_cond_init(&lock->lock_released, pthread_condattr_default); Modified: python/branches/py3k-jit/configure ============================================================================== --- python/branches/py3k-jit/configure (original) +++ python/branches/py3k-jit/configure Tue May 4 01:24:51 2010 @@ -1,63 +1,86 @@ #! /bin/sh -# From configure.in Revision: 80191 . +# From configure.in Revision: 80666 . # Guess values for system-dependent variables and create Makefiles. -# Generated by GNU Autoconf 2.61 for python 3.2. +# Generated by GNU Autoconf 2.65 for python 3.2. # # Report bugs to . # +# # Copyright (C) 1992, 1993, 1994, 1995, 1996, 1998, 1999, 2000, 2001, -# 2002, 2003, 2004, 2005, 2006 Free Software Foundation, Inc. +# 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009 Free Software Foundation, +# Inc. +# +# # This configure script is free software; the Free Software Foundation # gives unlimited permission to copy, distribute and modify it. -## --------------------- ## -## M4sh Initialization. ## -## --------------------- ## +## -------------------- ## +## M4sh Initialization. ## +## -------------------- ## # Be more Bourne compatible DUALCASE=1; export DUALCASE # for MKS sh -if test -n "${ZSH_VERSION+set}" && (emulate sh) >/dev/null 2>&1; then +if test -n "${ZSH_VERSION+set}" && (emulate sh) >/dev/null 2>&1; then : emulate sh NULLCMD=: - # Zsh 3.x and 4.x performs word splitting on ${1+"$@"}, which + # Pre-4.2 versions of Zsh do word splitting on ${1+"$@"}, which # is contrary to our usage. Disable this feature. alias -g '${1+"$@"}'='"$@"' setopt NO_GLOB_SUBST else - case `(set -o) 2>/dev/null` in - *posix*) set -o posix ;; + case `(set -o) 2>/dev/null` in #( + *posix*) : + set -o posix ;; #( + *) : + ;; esac - fi - - -# PATH needs CR -# Avoid depending upon Character Ranges. -as_cr_letters='abcdefghijklmnopqrstuvwxyz' -as_cr_LETTERS='ABCDEFGHIJKLMNOPQRSTUVWXYZ' -as_cr_Letters=$as_cr_letters$as_cr_LETTERS -as_cr_digits='0123456789' -as_cr_alnum=$as_cr_Letters$as_cr_digits - -# The user is always right. -if test "${PATH_SEPARATOR+set}" != set; then - echo "#! /bin/sh" >conf$$.sh - echo "exit 0" >>conf$$.sh - chmod +x conf$$.sh - if (PATH="/nonexistent;."; conf$$.sh) >/dev/null 2>&1; then - PATH_SEPARATOR=';' - else - PATH_SEPARATOR=: +as_nl=' +' +export as_nl +# Printing a long string crashes Solaris 7 /usr/bin/printf. +as_echo='\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\' +as_echo=$as_echo$as_echo$as_echo$as_echo$as_echo +as_echo=$as_echo$as_echo$as_echo$as_echo$as_echo$as_echo +# Prefer a ksh shell builtin over an external printf program on Solaris, +# but without wasting forks for bash or zsh. +if test -z "$BASH_VERSION$ZSH_VERSION" \ + && (test "X`print -r -- $as_echo`" = "X$as_echo") 2>/dev/null; then + as_echo='print -r --' + as_echo_n='print -rn --' +elif (test "X`printf %s $as_echo`" = "X$as_echo") 2>/dev/null; then + as_echo='printf %s\n' + as_echo_n='printf %s' +else + if test "X`(/usr/ucb/echo -n -n $as_echo) 2>/dev/null`" = "X-n $as_echo"; then + as_echo_body='eval /usr/ucb/echo -n "$1$as_nl"' + as_echo_n='/usr/ucb/echo -n' + else + as_echo_body='eval expr "X$1" : "X\\(.*\\)"' + as_echo_n_body='eval + arg=$1; + case $arg in #( + *"$as_nl"*) + expr "X$arg" : "X\\(.*\\)$as_nl"; + arg=`expr "X$arg" : ".*$as_nl\\(.*\\)"`;; + esac; + expr "X$arg" : "X\\(.*\\)" | tr -d "$as_nl" + ' + export as_echo_n_body + as_echo_n='sh -c $as_echo_n_body as_echo' fi - rm -f conf$$.sh + export as_echo_body + as_echo='sh -c $as_echo_body as_echo' fi -# Support unset when possible. -if ( (MAIL=60; unset MAIL) || exit) >/dev/null 2>&1; then - as_unset=unset -else - as_unset=false +# The user is always right. +if test "${PATH_SEPARATOR+set}" != set; then + PATH_SEPARATOR=: + (PATH='/bin;/bin'; FPATH=$PATH; sh -c :) >/dev/null 2>&1 && { + (PATH='/bin:/bin'; FPATH=$PATH; sh -c :) >/dev/null 2>&1 || + PATH_SEPARATOR=';' + } fi @@ -66,20 +89,18 @@ # there to prevent editors from complaining about space-tab. # (If _AS_PATH_WALK were called with IFS unset, it would disable word # splitting by setting IFS to empty value.) -as_nl=' -' IFS=" "" $as_nl" # Find who we are. Look in the path if we contain no directory separator. -case $0 in +case $0 in #(( *[\\/]* ) as_myself=$0 ;; *) as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $PATH do IFS=$as_save_IFS test -z "$as_dir" && as_dir=. - test -r "$as_dir/$0" && as_myself=$as_dir/$0 && break -done + test -r "$as_dir/$0" && as_myself=$as_dir/$0 && break + done IFS=$as_save_IFS ;; @@ -90,354 +111,322 @@ as_myself=$0 fi if test ! -f "$as_myself"; then - echo "$as_myself: error: cannot find myself; rerun with an absolute file name" >&2 - { (exit 1); exit 1; } + $as_echo "$as_myself: error: cannot find myself; rerun with an absolute file name" >&2 + exit 1 fi -# Work around bugs in pre-3.0 UWIN ksh. -for as_var in ENV MAIL MAILPATH -do ($as_unset $as_var) >/dev/null 2>&1 && $as_unset $as_var +# Unset variables that we do not need and which cause bugs (e.g. in +# pre-3.0 UWIN ksh). But do not cause bugs in bash 2.01; the "|| exit 1" +# suppresses any "Segmentation fault" message there. '((' could +# trigger a bug in pdksh 5.2.14. +for as_var in BASH_ENV ENV MAIL MAILPATH +do eval test x\${$as_var+set} = xset \ + && ( (unset $as_var) || exit 1) >/dev/null 2>&1 && unset $as_var || : done PS1='$ ' PS2='> ' PS4='+ ' # NLS nuisances. -for as_var in \ - LANG LANGUAGE LC_ADDRESS LC_ALL LC_COLLATE LC_CTYPE LC_IDENTIFICATION \ - LC_MEASUREMENT LC_MESSAGES LC_MONETARY LC_NAME LC_NUMERIC LC_PAPER \ - LC_TELEPHONE LC_TIME -do - if (set +x; test -z "`(eval $as_var=C; export $as_var) 2>&1`"); then - eval $as_var=C; export $as_var - else - ($as_unset $as_var) >/dev/null 2>&1 && $as_unset $as_var - fi -done - -# Required to use basename. -if expr a : '\(a\)' >/dev/null 2>&1 && - test "X`expr 00001 : '.*\(...\)'`" = X001; then - as_expr=expr -else - as_expr=false -fi - -if (basename -- /) >/dev/null 2>&1 && test "X`basename -- / 2>&1`" = "X/"; then - as_basename=basename -else - as_basename=false -fi - - -# Name of the executable. -as_me=`$as_basename -- "$0" || -$as_expr X/"$0" : '.*/\([^/][^/]*\)/*$' \| \ - X"$0" : 'X\(//\)$' \| \ - X"$0" : 'X\(/\)' \| . 2>/dev/null || -echo X/"$0" | - sed '/^.*\/\([^/][^/]*\)\/*$/{ - s//\1/ - q - } - /^X\/\(\/\/\)$/{ - s//\1/ - q - } - /^X\/\(\/\).*/{ - s//\1/ - q - } - s/.*/./; q'` +LC_ALL=C +export LC_ALL +LANGUAGE=C +export LANGUAGE # CDPATH. -$as_unset CDPATH - +(unset CDPATH) >/dev/null 2>&1 && unset CDPATH if test "x$CONFIG_SHELL" = x; then - if (eval ":") 2>/dev/null; then - as_have_required=yes + as_bourne_compatible="if test -n \"\${ZSH_VERSION+set}\" && (emulate sh) >/dev/null 2>&1; then : + emulate sh + NULLCMD=: + # Pre-4.2 versions of Zsh do word splitting on \${1+\"\$@\"}, which + # is contrary to our usage. Disable this feature. + alias -g '\${1+\"\$@\"}'='\"\$@\"' + setopt NO_GLOB_SUBST else - as_have_required=no + case \`(set -o) 2>/dev/null\` in #( + *posix*) : + set -o posix ;; #( + *) : + ;; +esac fi - - if test $as_have_required = yes && (eval ": -(as_func_return () { - (exit \$1) -} -as_func_success () { - as_func_return 0 -} -as_func_failure () { - as_func_return 1 -} -as_func_ret_success () { - return 0 -} -as_func_ret_failure () { - return 1 -} +" + as_required="as_fn_return () { (exit \$1); } +as_fn_success () { as_fn_return 0; } +as_fn_failure () { as_fn_return 1; } +as_fn_ret_success () { return 0; } +as_fn_ret_failure () { return 1; } exitcode=0 -if as_func_success; then - : -else - exitcode=1 - echo as_func_success failed. -fi - -if as_func_failure; then - exitcode=1 - echo as_func_failure succeeded. -fi - -if as_func_ret_success; then - : -else - exitcode=1 - echo as_func_ret_success failed. -fi - -if as_func_ret_failure; then - exitcode=1 - echo as_func_ret_failure succeeded. -fi - -if ( set x; as_func_ret_success y && test x = \"\$1\" ); then - : +as_fn_success || { exitcode=1; echo as_fn_success failed.; } +as_fn_failure && { exitcode=1; echo as_fn_failure succeeded.; } +as_fn_ret_success || { exitcode=1; echo as_fn_ret_success failed.; } +as_fn_ret_failure && { exitcode=1; echo as_fn_ret_failure succeeded.; } +if ( set x; as_fn_ret_success y && test x = \"\$1\" ); then : + +else + exitcode=1; echo positional parameters were not saved. +fi +test x\$exitcode = x0 || exit 1" + as_suggested=" as_lineno_1=";as_suggested=$as_suggested$LINENO;as_suggested=$as_suggested" as_lineno_1a=\$LINENO + as_lineno_2=";as_suggested=$as_suggested$LINENO;as_suggested=$as_suggested" as_lineno_2a=\$LINENO + eval 'test \"x\$as_lineno_1'\$as_run'\" != \"x\$as_lineno_2'\$as_run'\" && + test \"x\`expr \$as_lineno_1'\$as_run' + 1\`\" = \"x\$as_lineno_2'\$as_run'\"' || exit 1 +test \$(( 1 + 1 )) = 2 || exit 1" + if (eval "$as_required") 2>/dev/null; then : + as_have_required=yes else - exitcode=1 - echo positional parameters were not saved. + as_have_required=no fi + if test x$as_have_required = xyes && (eval "$as_suggested") 2>/dev/null; then : -test \$exitcode = 0) || { (exit 1); exit 1; } - -( - as_lineno_1=\$LINENO - as_lineno_2=\$LINENO - test \"x\$as_lineno_1\" != \"x\$as_lineno_2\" && - test \"x\`expr \$as_lineno_1 + 1\`\" = \"x\$as_lineno_2\") || { (exit 1); exit 1; } -") 2> /dev/null; then - : else - as_candidate_shells= - as_save_IFS=$IFS; IFS=$PATH_SEPARATOR + as_save_IFS=$IFS; IFS=$PATH_SEPARATOR +as_found=false for as_dir in /bin$PATH_SEPARATOR/usr/bin$PATH_SEPARATOR$PATH do IFS=$as_save_IFS test -z "$as_dir" && as_dir=. - case $as_dir in + as_found=: + case $as_dir in #( /*) for as_base in sh bash ksh sh5; do - as_candidate_shells="$as_candidate_shells $as_dir/$as_base" + # Try only shells that exist, to save several forks. + as_shell=$as_dir/$as_base + if { test -f "$as_shell" || test -f "$as_shell.exe"; } && + { $as_echo "$as_bourne_compatible""$as_required" | as_run=a "$as_shell"; } 2>/dev/null; then : + CONFIG_SHELL=$as_shell as_have_required=yes + if { $as_echo "$as_bourne_compatible""$as_suggested" | as_run=a "$as_shell"; } 2>/dev/null; then : + break 2 +fi +fi done;; esac + as_found=false done +$as_found || { if { test -f "$SHELL" || test -f "$SHELL.exe"; } && + { $as_echo "$as_bourne_compatible""$as_required" | as_run=a "$SHELL"; } 2>/dev/null; then : + CONFIG_SHELL=$SHELL as_have_required=yes +fi; } IFS=$as_save_IFS - for as_shell in $as_candidate_shells $SHELL; do - # Try only shells that exist, to save several forks. - if { test -f "$as_shell" || test -f "$as_shell.exe"; } && - { ("$as_shell") 2> /dev/null <<\_ASEOF -if test -n "${ZSH_VERSION+set}" && (emulate sh) >/dev/null 2>&1; then - emulate sh - NULLCMD=: - # Zsh 3.x and 4.x performs word splitting on ${1+"$@"}, which - # is contrary to our usage. Disable this feature. - alias -g '${1+"$@"}'='"$@"' - setopt NO_GLOB_SUBST -else - case `(set -o) 2>/dev/null` in - *posix*) set -o posix ;; -esac - + if test "x$CONFIG_SHELL" != x; then : + # We cannot yet assume a decent shell, so we have to provide a + # neutralization value for shells without unset; and this also + # works around shells that cannot unset nonexistent variables. + BASH_ENV=/dev/null + ENV=/dev/null + (unset BASH_ENV) >/dev/null 2>&1 && unset BASH_ENV ENV + export CONFIG_SHELL + exec "$CONFIG_SHELL" "$as_myself" ${1+"$@"} +fi + + if test x$as_have_required = xno; then : + $as_echo "$0: This script requires a shell more modern than all" + $as_echo "$0: the shells that I found on your system." + if test x${ZSH_VERSION+set} = xset ; then + $as_echo "$0: In particular, zsh $ZSH_VERSION has bugs and should" + $as_echo "$0: be upgraded to zsh 4.3.4 or later." + else + $as_echo "$0: Please tell bug-autoconf at gnu.org and +$0: http://bugs.python.org/ about your system, including +$0: any error possibly output before this message. Then +$0: install a modern shell, or manually run the script +$0: under such a shell if you do have one." + fi + exit 1 fi - - -: -_ASEOF -}; then - CONFIG_SHELL=$as_shell - as_have_required=yes - if { "$as_shell" 2> /dev/null <<\_ASEOF -if test -n "${ZSH_VERSION+set}" && (emulate sh) >/dev/null 2>&1; then - emulate sh - NULLCMD=: - # Zsh 3.x and 4.x performs word splitting on ${1+"$@"}, which - # is contrary to our usage. Disable this feature. - alias -g '${1+"$@"}'='"$@"' - setopt NO_GLOB_SUBST -else - case `(set -o) 2>/dev/null` in - *posix*) set -o posix ;; -esac - fi - - -: -(as_func_return () { - (exit $1) -} -as_func_success () { - as_func_return 0 -} -as_func_failure () { - as_func_return 1 -} -as_func_ret_success () { - return 0 -} -as_func_ret_failure () { - return 1 -} - -exitcode=0 -if as_func_success; then - : -else - exitcode=1 - echo as_func_success failed. fi +SHELL=${CONFIG_SHELL-/bin/sh} +export SHELL +# Unset more variables known to interfere with behavior of common tools. +CLICOLOR_FORCE= GREP_OPTIONS= +unset CLICOLOR_FORCE GREP_OPTIONS -if as_func_failure; then - exitcode=1 - echo as_func_failure succeeded. -fi +## --------------------- ## +## M4sh Shell Functions. ## +## --------------------- ## +# as_fn_unset VAR +# --------------- +# Portably unset VAR. +as_fn_unset () +{ + { eval $1=; unset $1;} +} +as_unset=as_fn_unset + +# as_fn_set_status STATUS +# ----------------------- +# Set $? to STATUS, without forking. +as_fn_set_status () +{ + return $1 +} # as_fn_set_status + +# as_fn_exit STATUS +# ----------------- +# Exit the shell with STATUS, even in a "trap 0" or "set -e" context. +as_fn_exit () +{ + set +e + as_fn_set_status $1 + exit $1 +} # as_fn_exit + +# as_fn_mkdir_p +# ------------- +# Create "$as_dir" as a directory, including parents if necessary. +as_fn_mkdir_p () +{ -if as_func_ret_success; then - : -else - exitcode=1 - echo as_func_ret_success failed. -fi + case $as_dir in #( + -*) as_dir=./$as_dir;; + esac + test -d "$as_dir" || eval $as_mkdir_p || { + as_dirs= + while :; do + case $as_dir in #( + *\'*) as_qdir=`$as_echo "$as_dir" | sed "s/'/'\\\\\\\\''/g"`;; #'( + *) as_qdir=$as_dir;; + esac + as_dirs="'$as_qdir' $as_dirs" + as_dir=`$as_dirname -- "$as_dir" || +$as_expr X"$as_dir" : 'X\(.*[^/]\)//*[^/][^/]*/*$' \| \ + X"$as_dir" : 'X\(//\)[^/]' \| \ + X"$as_dir" : 'X\(//\)$' \| \ + X"$as_dir" : 'X\(/\)' \| . 2>/dev/null || +$as_echo X"$as_dir" | + sed '/^X\(.*[^/]\)\/\/*[^/][^/]*\/*$/{ + s//\1/ + q + } + /^X\(\/\/\)[^/].*/{ + s//\1/ + q + } + /^X\(\/\/\)$/{ + s//\1/ + q + } + /^X\(\/\).*/{ + s//\1/ + q + } + s/.*/./; q'` + test -d "$as_dir" && break + done + test -z "$as_dirs" || eval "mkdir $as_dirs" + } || test -d "$as_dir" || as_fn_error "cannot create directory $as_dir" -if as_func_ret_failure; then - exitcode=1 - echo as_func_ret_failure succeeded. -fi -if ( set x; as_func_ret_success y && test x = "$1" ); then - : +} # as_fn_mkdir_p +# as_fn_append VAR VALUE +# ---------------------- +# Append the text in VALUE to the end of the definition contained in VAR. Take +# advantage of any shell optimizations that allow amortized linear growth over +# repeated appends, instead of the typical quadratic growth present in naive +# implementations. +if (eval "as_var=1; as_var+=2; test x\$as_var = x12") 2>/dev/null; then : + eval 'as_fn_append () + { + eval $1+=\$2 + }' else - exitcode=1 - echo positional parameters were not saved. -fi - -test $exitcode = 0) || { (exit 1); exit 1; } - -( - as_lineno_1=$LINENO - as_lineno_2=$LINENO - test "x$as_lineno_1" != "x$as_lineno_2" && - test "x`expr $as_lineno_1 + 1`" = "x$as_lineno_2") || { (exit 1); exit 1; } - -_ASEOF -}; then - break -fi - -fi - - done - - if test "x$CONFIG_SHELL" != x; then - for as_var in BASH_ENV ENV - do ($as_unset $as_var) >/dev/null 2>&1 && $as_unset $as_var - done - export CONFIG_SHELL - exec "$CONFIG_SHELL" "$as_myself" ${1+"$@"} -fi - - - if test $as_have_required = no; then - echo This script requires a shell more modern than all the - echo shells that I found on your system. Please install a - echo modern shell, or manually run the script under such a - echo shell if you do have one. - { (exit 1); exit 1; } -fi - - -fi - -fi + as_fn_append () + { + eval $1=\$$1\$2 + } +fi # as_fn_append +# as_fn_arith ARG... +# ------------------ +# Perform arithmetic evaluation on the ARGs, and store the result in the +# global $as_val. Take advantage of shells that can avoid forks. The arguments +# must be portable across $(()) and expr. +if (eval "test \$(( 1 + 1 )) = 2") 2>/dev/null; then : + eval 'as_fn_arith () + { + as_val=$(( $* )) + }' +else + as_fn_arith () + { + as_val=`expr "$@" || test $? -eq 1` + } +fi # as_fn_arith -(eval "as_func_return () { - (exit \$1) -} -as_func_success () { - as_func_return 0 -} -as_func_failure () { - as_func_return 1 -} -as_func_ret_success () { - return 0 -} -as_func_ret_failure () { - return 1 -} +# as_fn_error ERROR [LINENO LOG_FD] +# --------------------------------- +# Output "`basename $0`: error: ERROR" to stderr. If LINENO and LOG_FD are +# provided, also output the error to LOG_FD, referencing LINENO. Then exit the +# script with status $?, using 1 if that was 0. +as_fn_error () +{ + as_status=$?; test $as_status -eq 0 && as_status=1 + if test "$3"; then + as_lineno=${as_lineno-"$2"} as_lineno_stack=as_lineno_stack=$as_lineno_stack + $as_echo "$as_me:${as_lineno-$LINENO}: error: $1" >&$3 + fi + $as_echo "$as_me: error: $1" >&2 + as_fn_exit $as_status +} # as_fn_error -exitcode=0 -if as_func_success; then - : +if expr a : '\(a\)' >/dev/null 2>&1 && + test "X`expr 00001 : '.*\(...\)'`" = X001; then + as_expr=expr else - exitcode=1 - echo as_func_success failed. -fi - -if as_func_failure; then - exitcode=1 - echo as_func_failure succeeded. + as_expr=false fi -if as_func_ret_success; then - : +if (basename -- /) >/dev/null 2>&1 && test "X`basename -- / 2>&1`" = "X/"; then + as_basename=basename else - exitcode=1 - echo as_func_ret_success failed. -fi - -if as_func_ret_failure; then - exitcode=1 - echo as_func_ret_failure succeeded. + as_basename=false fi -if ( set x; as_func_ret_success y && test x = \"\$1\" ); then - : +if (as_dir=`dirname -- /` && test "X$as_dir" = X/) >/dev/null 2>&1; then + as_dirname=dirname else - exitcode=1 - echo positional parameters were not saved. + as_dirname=false fi -test \$exitcode = 0") || { - echo No shell found that supports shell functions. - echo Please tell autoconf at gnu.org about your system, - echo including any error possibly output before this - echo message -} +as_me=`$as_basename -- "$0" || +$as_expr X/"$0" : '.*/\([^/][^/]*\)/*$' \| \ + X"$0" : 'X\(//\)$' \| \ + X"$0" : 'X\(/\)' \| . 2>/dev/null || +$as_echo X/"$0" | + sed '/^.*\/\([^/][^/]*\)\/*$/{ + s//\1/ + q + } + /^X\/\(\/\/\)$/{ + s//\1/ + q + } + /^X\/\(\/\).*/{ + s//\1/ + q + } + s/.*/./; q'` +# Avoid depending upon Character Ranges. +as_cr_letters='abcdefghijklmnopqrstuvwxyz' +as_cr_LETTERS='ABCDEFGHIJKLMNOPQRSTUVWXYZ' +as_cr_Letters=$as_cr_letters$as_cr_LETTERS +as_cr_digits='0123456789' +as_cr_alnum=$as_cr_Letters$as_cr_digits - as_lineno_1=$LINENO - as_lineno_2=$LINENO - test "x$as_lineno_1" != "x$as_lineno_2" && - test "x`expr $as_lineno_1 + 1`" = "x$as_lineno_2" || { - - # Create $as_me.lineno as a copy of $as_myself, but with $LINENO - # uniformly replaced by the line number. The first 'sed' inserts a - # line-number line after each line using $LINENO; the second 'sed' - # does the real work. The second script uses 'N' to pair each - # line-number line with the line containing $LINENO, and appends - # trailing '-' during substitution so that $LINENO is not a special - # case at line end. - # (Raja R Harinath suggested sed '=', and Paul Eggert wrote the - # scripts with optimization help from Paolo Bonzini. Blame Lee - # E. McMahon (1931-1989) for sed's syntax. :-) + as_lineno_1=$LINENO as_lineno_1a=$LINENO + as_lineno_2=$LINENO as_lineno_2a=$LINENO + eval 'test "x$as_lineno_1'$as_run'" != "x$as_lineno_2'$as_run'" && + test "x`expr $as_lineno_1'$as_run' + 1`" = "x$as_lineno_2'$as_run'"' || { + # Blame Lee E. McMahon (1931-1989) for sed's syntax. :-) sed -n ' p /[$]LINENO/= @@ -454,8 +443,7 @@ s/-\n.*// ' >$as_me.lineno && chmod +x "$as_me.lineno" || - { echo "$as_me: error: cannot create $as_me.lineno; rerun with a POSIX shell" >&2 - { (exit 1); exit 1; }; } + { $as_echo "$as_me: error: cannot create $as_me.lineno; rerun with a POSIX shell" >&2; as_fn_exit 1; } # Don't try to exec as it changes $[0], causing all sort of problems # (the dirname of $[0] is not the place where we might find the @@ -465,49 +453,40 @@ exit } - -if (as_dir=`dirname -- /` && test "X$as_dir" = X/) >/dev/null 2>&1; then - as_dirname=dirname -else - as_dirname=false -fi - ECHO_C= ECHO_N= ECHO_T= -case `echo -n x` in +case `echo -n x` in #((((( -n*) - case `echo 'x\c'` in + case `echo 'xy\c'` in *c*) ECHO_T=' ';; # ECHO_T is single tab character. - *) ECHO_C='\c';; + xy) ECHO_C='\c';; + *) echo `echo ksh88 bug on AIX 6.1` > /dev/null + ECHO_T=' ';; esac;; *) ECHO_N='-n';; esac -if expr a : '\(a\)' >/dev/null 2>&1 && - test "X`expr 00001 : '.*\(...\)'`" = X001; then - as_expr=expr -else - as_expr=false -fi - rm -f conf$$ conf$$.exe conf$$.file if test -d conf$$.dir; then rm -f conf$$.dir/conf$$.file else rm -f conf$$.dir - mkdir conf$$.dir + mkdir conf$$.dir 2>/dev/null fi -echo >conf$$.file -if ln -s conf$$.file conf$$ 2>/dev/null; then - as_ln_s='ln -s' - # ... but there are two gotchas: - # 1) On MSYS, both `ln -s file dir' and `ln file dir' fail. - # 2) DJGPP < 2.04 has no symlinks; `ln -s' creates a wrapper executable. - # In both cases, we have to default to `cp -p'. - ln -s conf$$.file conf$$.dir 2>/dev/null && test ! -f conf$$.exe || +if (echo >conf$$.file) 2>/dev/null; then + if ln -s conf$$.file conf$$ 2>/dev/null; then + as_ln_s='ln -s' + # ... but there are two gotchas: + # 1) On MSYS, both `ln -s file dir' and `ln file dir' fail. + # 2) DJGPP < 2.04 has no symlinks; `ln -s' creates a wrapper executable. + # In both cases, we have to default to `cp -p'. + ln -s conf$$.file conf$$.dir 2>/dev/null && test ! -f conf$$.exe || + as_ln_s='cp -p' + elif ln conf$$.file conf$$ 2>/dev/null; then + as_ln_s=ln + else as_ln_s='cp -p' -elif ln conf$$.file conf$$ 2>/dev/null; then - as_ln_s=ln + fi else as_ln_s='cp -p' fi @@ -515,7 +494,7 @@ rmdir conf$$.dir 2>/dev/null if mkdir -p . 2>/dev/null; then - as_mkdir_p=: + as_mkdir_p='mkdir -p "$as_dir"' else test -d ./-p && rmdir ./-p as_mkdir_p=false @@ -532,12 +511,12 @@ as_test_x=' eval sh -c '\'' if test -d "$1"; then - test -d "$1/."; + test -d "$1/."; else - case $1 in - -*)set "./$1";; + case $1 in #( + -*)set "./$1";; esac; - case `ls -ld'$as_ls_L_option' "$1" 2>/dev/null` in + case `ls -ld'$as_ls_L_option' "$1" 2>/dev/null` in #(( ???[sx]*):;;*)false;;esac;fi '\'' sh ' @@ -551,8 +530,8 @@ as_tr_sh="eval sed 'y%*+%pp%;s%[^_$as_cr_alnum]%_%g'" - -exec 7<&0 &1 +test -n "$DJDIR" || exec 7<&0 &1 # Name of the host. # hostname on some systems (SVR3.2, Linux) returns a bogus exit status, @@ -570,7 +549,6 @@ subdirs= MFLAGS= MAKEFLAGS= -SHELL=${CONFIG_SHELL-/bin/sh} # Identity of this package. PACKAGE_NAME='python' @@ -578,6 +556,7 @@ PACKAGE_VERSION='3.2' PACKAGE_STRING='python 3.2' PACKAGE_BUGREPORT='http://bugs.python.org/' +PACKAGE_URL='' ac_unique_file="Include/object.h" # Factoring default headers for most tests. @@ -616,129 +595,164 @@ # include #endif" -ac_subst_vars='SHELL -PATH_SEPARATOR -PACKAGE_NAME -PACKAGE_TARNAME -PACKAGE_VERSION -PACKAGE_STRING -PACKAGE_BUGREPORT -exec_prefix -prefix -program_transform_name -bindir -sbindir -libexecdir -datarootdir -datadir -sysconfdir -sharedstatedir -localstatedir -includedir -oldincludedir -docdir -infodir -htmldir -dvidir -pdfdir -psdir -libdir -localedir -mandir -DEFS -ECHO_C -ECHO_N -ECHO_T -LIBS -build_alias -host_alias -target_alias -VERSION -SOVERSION -CONFIG_ARGS -UNIVERSALSDK -ARCH_RUN_32BIT -LIPO_32BIT_FLAGS -PYTHONFRAMEWORK -PYTHONFRAMEWORKIDENTIFIER -PYTHONFRAMEWORKDIR -PYTHONFRAMEWORKPREFIX -PYTHONFRAMEWORKINSTALLDIR -FRAMEWORKINSTALLFIRST -FRAMEWORKINSTALLLAST -FRAMEWORKALTINSTALLFIRST -FRAMEWORKALTINSTALLLAST -FRAMEWORKUNIXTOOLSPREFIX -MACHDEP -SGI_ABI -CONFIGURE_MACOSX_DEPLOYMENT_TARGET -EXPORT_MACOSX_DEPLOYMENT_TARGET -CC -CFLAGS -LDFLAGS -CPPFLAGS -ac_ct_CC -EXEEXT -OBJEXT -CXX -MAINCC -CPP -GREP -EGREP -BUILDEXEEXT -LIBRARY -LDLIBRARY -DLLLIBRARY -BLDLIBRARY -LDLIBRARYDIR -INSTSONAME -RUNSHARED -LINKCC -GNULD -RANLIB -AR -ARFLAGS -SVNVERSION -INSTALL_PROGRAM -INSTALL_SCRIPT -INSTALL_DATA -LN -OPT -BASECFLAGS -UNIVERSAL_ARCH_FLAGS -OTHER_LIBTOOL_OPT -LIBTOOL_CRUFT -SO -LDSHARED -LDCXXSHARED -BLDSHARED -CCSHARED -LINKFORSHARED -CFLAGSFORSHARED -SHLIBS -PKG_CONFIG -LIBFFI_INCLUDEDIR -USE_SIGNAL_MODULE -SIGNAL_OBJS -USE_THREAD_MODULE -LDLAST -THREADOBJ -DLINCLDIR -DYNLOADFILE -MACHDEP_OBJS -TRUE -LIBOBJS -HAVE_GETHOSTBYNAME_R_6_ARG -HAVE_GETHOSTBYNAME_R_5_ARG -HAVE_GETHOSTBYNAME_R_3_ARG -HAVE_GETHOSTBYNAME_R -HAVE_GETHOSTBYNAME -LIBM -LIBC -THREADHEADERS +ac_subst_vars='LTLIBOBJS SRCDIRS -LTLIBOBJS' +THREADHEADERS +LIBC +LIBM +HAVE_GETHOSTBYNAME +HAVE_GETHOSTBYNAME_R +HAVE_GETHOSTBYNAME_R_3_ARG +HAVE_GETHOSTBYNAME_R_5_ARG +HAVE_GETHOSTBYNAME_R_6_ARG +LIBOBJS +TRUE +MACHDEP_OBJS +DYNLOADFILE +DLINCLDIR +THREADOBJ +LDLAST +USE_THREAD_MODULE +SIGNAL_OBJS +USE_SIGNAL_MODULE +LIBFFI_INCLUDEDIR +PKG_CONFIG +SHLIBS +CFLAGSFORSHARED +LINKFORSHARED +CCSHARED +BLDSHARED +LDCXXSHARED +LDSHARED +SO +LIBTOOL_CRUFT +OTHER_LIBTOOL_OPT +UNIVERSAL_ARCH_FLAGS +BASECFLAGS +OPT +LN +INSTALL_DATA +INSTALL_SCRIPT +INSTALL_PROGRAM +SVNVERSION +ARFLAGS +AR +RANLIB +GNULD +LINKCC +RUNSHARED +INSTSONAME +LDLIBRARYDIR +BLDLIBRARY +DLLLIBRARY +LDLIBRARY +LIBRARY +BUILDEXEEXT +EGREP +GREP +CPP +MAINCC +CXX +OBJEXT +EXEEXT +ac_ct_CC +CPPFLAGS +LDFLAGS +CFLAGS +CC +EXPORT_MACOSX_DEPLOYMENT_TARGET +CONFIGURE_MACOSX_DEPLOYMENT_TARGET +SGI_ABI +MACHDEP +FRAMEWORKINSTALLAPPSPREFIX +FRAMEWORKUNIXTOOLSPREFIX +FRAMEWORKALTINSTALLLAST +FRAMEWORKALTINSTALLFIRST +FRAMEWORKINSTALLLAST +FRAMEWORKINSTALLFIRST +PYTHONFRAMEWORKINSTALLDIR +PYTHONFRAMEWORKPREFIX +PYTHONFRAMEWORKDIR +PYTHONFRAMEWORKIDENTIFIER +PYTHONFRAMEWORK +LIPO_32BIT_FLAGS +ARCH_RUN_32BIT +UNIVERSALSDK +CONFIG_ARGS +SOVERSION +VERSION +target_alias +host_alias +build_alias +LIBS +ECHO_T +ECHO_N +ECHO_C +DEFS +mandir +localedir +libdir +psdir +pdfdir +dvidir +htmldir +infodir +docdir +oldincludedir +includedir +localstatedir +sharedstatedir +sysconfdir +datadir +datarootdir +libexecdir +sbindir +bindir +program_transform_name +prefix +exec_prefix +PACKAGE_URL +PACKAGE_BUGREPORT +PACKAGE_STRING +PACKAGE_VERSION +PACKAGE_TARNAME +PACKAGE_NAME +PATH_SEPARATOR +SHELL' ac_subst_files='' +ac_user_opts=' +enable_option_checking +enable_universalsdk +with_universal_archs +with_framework_name +enable_framework +with_gcc +with_cxx_main +with_suffix +enable_shared +enable_profiling +with_pydebug +with_libs +with_system_expat +with_system_ffi +with_dbmliborder +with_signal_module +with_dec_threads +with_threads +with_thread +enable_ipv6 +with_doc_strings +with_tsc +with_pymalloc +with_valgrind +with_wctype_functions +with_fpectl +with_libm +with_libc +enable_big_digits +with_wide_unicode +with_computed_gotos +' ac_precious_vars='build_alias host_alias target_alias @@ -753,6 +767,8 @@ # Initialize some variables set by options. ac_init_help= ac_init_version=false +ac_unrecognized_opts= +ac_unrecognized_sep= # The variables have the same names as the options, with # dashes changed to underlines. cache_file=/dev/null @@ -851,13 +867,20 @@ datarootdir=$ac_optarg ;; -disable-* | --disable-*) - ac_feature=`expr "x$ac_option" : 'x-*disable-\(.*\)'` + ac_useropt=`expr "x$ac_option" : 'x-*disable-\(.*\)'` # Reject names that are not valid shell variable names. - expr "x$ac_feature" : ".*[^-._$as_cr_alnum]" >/dev/null && - { echo "$as_me: error: invalid feature name: $ac_feature" >&2 - { (exit 1); exit 1; }; } - ac_feature=`echo $ac_feature | sed 's/[-.]/_/g'` - eval enable_$ac_feature=no ;; + expr "x$ac_useropt" : ".*[^-+._$as_cr_alnum]" >/dev/null && + as_fn_error "invalid feature name: $ac_useropt" + ac_useropt_orig=$ac_useropt + ac_useropt=`$as_echo "$ac_useropt" | sed 's/[-+.]/_/g'` + case $ac_user_opts in + *" +"enable_$ac_useropt" +"*) ;; + *) ac_unrecognized_opts="$ac_unrecognized_opts$ac_unrecognized_sep--disable-$ac_useropt_orig" + ac_unrecognized_sep=', ';; + esac + eval enable_$ac_useropt=no ;; -docdir | --docdir | --docdi | --doc | --do) ac_prev=docdir ;; @@ -870,13 +893,20 @@ dvidir=$ac_optarg ;; -enable-* | --enable-*) - ac_feature=`expr "x$ac_option" : 'x-*enable-\([^=]*\)'` + ac_useropt=`expr "x$ac_option" : 'x-*enable-\([^=]*\)'` # Reject names that are not valid shell variable names. - expr "x$ac_feature" : ".*[^-._$as_cr_alnum]" >/dev/null && - { echo "$as_me: error: invalid feature name: $ac_feature" >&2 - { (exit 1); exit 1; }; } - ac_feature=`echo $ac_feature | sed 's/[-.]/_/g'` - eval enable_$ac_feature=\$ac_optarg ;; + expr "x$ac_useropt" : ".*[^-+._$as_cr_alnum]" >/dev/null && + as_fn_error "invalid feature name: $ac_useropt" + ac_useropt_orig=$ac_useropt + ac_useropt=`$as_echo "$ac_useropt" | sed 's/[-+.]/_/g'` + case $ac_user_opts in + *" +"enable_$ac_useropt" +"*) ;; + *) ac_unrecognized_opts="$ac_unrecognized_opts$ac_unrecognized_sep--enable-$ac_useropt_orig" + ac_unrecognized_sep=', ';; + esac + eval enable_$ac_useropt=\$ac_optarg ;; -exec-prefix | --exec_prefix | --exec-prefix | --exec-prefi \ | --exec-pref | --exec-pre | --exec-pr | --exec-p | --exec- \ @@ -1067,22 +1097,36 @@ ac_init_version=: ;; -with-* | --with-*) - ac_package=`expr "x$ac_option" : 'x-*with-\([^=]*\)'` + ac_useropt=`expr "x$ac_option" : 'x-*with-\([^=]*\)'` # Reject names that are not valid shell variable names. - expr "x$ac_package" : ".*[^-._$as_cr_alnum]" >/dev/null && - { echo "$as_me: error: invalid package name: $ac_package" >&2 - { (exit 1); exit 1; }; } - ac_package=`echo $ac_package | sed 's/[-.]/_/g'` - eval with_$ac_package=\$ac_optarg ;; + expr "x$ac_useropt" : ".*[^-+._$as_cr_alnum]" >/dev/null && + as_fn_error "invalid package name: $ac_useropt" + ac_useropt_orig=$ac_useropt + ac_useropt=`$as_echo "$ac_useropt" | sed 's/[-+.]/_/g'` + case $ac_user_opts in + *" +"with_$ac_useropt" +"*) ;; + *) ac_unrecognized_opts="$ac_unrecognized_opts$ac_unrecognized_sep--with-$ac_useropt_orig" + ac_unrecognized_sep=', ';; + esac + eval with_$ac_useropt=\$ac_optarg ;; -without-* | --without-*) - ac_package=`expr "x$ac_option" : 'x-*without-\(.*\)'` + ac_useropt=`expr "x$ac_option" : 'x-*without-\(.*\)'` # Reject names that are not valid shell variable names. - expr "x$ac_package" : ".*[^-._$as_cr_alnum]" >/dev/null && - { echo "$as_me: error: invalid package name: $ac_package" >&2 - { (exit 1); exit 1; }; } - ac_package=`echo $ac_package | sed 's/[-.]/_/g'` - eval with_$ac_package=no ;; + expr "x$ac_useropt" : ".*[^-+._$as_cr_alnum]" >/dev/null && + as_fn_error "invalid package name: $ac_useropt" + ac_useropt_orig=$ac_useropt + ac_useropt=`$as_echo "$ac_useropt" | sed 's/[-+.]/_/g'` + case $ac_user_opts in + *" +"with_$ac_useropt" +"*) ;; + *) ac_unrecognized_opts="$ac_unrecognized_opts$ac_unrecognized_sep--without-$ac_useropt_orig" + ac_unrecognized_sep=', ';; + esac + eval with_$ac_useropt=no ;; --x) # Obsolete; use --with-x. @@ -1102,25 +1146,25 @@ | --x-librar=* | --x-libra=* | --x-libr=* | --x-lib=* | --x-li=* | --x-l=*) x_libraries=$ac_optarg ;; - -*) { echo "$as_me: error: unrecognized option: $ac_option -Try \`$0 --help' for more information." >&2 - { (exit 1); exit 1; }; } + -*) as_fn_error "unrecognized option: \`$ac_option' +Try \`$0 --help' for more information." ;; *=*) ac_envvar=`expr "x$ac_option" : 'x\([^=]*\)='` # Reject names that are not valid shell variable names. - expr "x$ac_envvar" : ".*[^_$as_cr_alnum]" >/dev/null && - { echo "$as_me: error: invalid variable name: $ac_envvar" >&2 - { (exit 1); exit 1; }; } + case $ac_envvar in #( + '' | [0-9]* | *[!_$as_cr_alnum]* ) + as_fn_error "invalid variable name: \`$ac_envvar'" ;; + esac eval $ac_envvar=\$ac_optarg export $ac_envvar ;; *) # FIXME: should be removed in autoconf 3.0. - echo "$as_me: WARNING: you should use --build, --host, --target" >&2 + $as_echo "$as_me: WARNING: you should use --build, --host, --target" >&2 expr "x$ac_option" : ".*[^-._$as_cr_alnum]" >/dev/null && - echo "$as_me: WARNING: invalid host type: $ac_option" >&2 + $as_echo "$as_me: WARNING: invalid host type: $ac_option" >&2 : ${build_alias=$ac_option} ${host_alias=$ac_option} ${target_alias=$ac_option} ;; @@ -1129,23 +1173,36 @@ if test -n "$ac_prev"; then ac_option=--`echo $ac_prev | sed 's/_/-/g'` - { echo "$as_me: error: missing argument to $ac_option" >&2 - { (exit 1); exit 1; }; } + as_fn_error "missing argument to $ac_option" +fi + +if test -n "$ac_unrecognized_opts"; then + case $enable_option_checking in + no) ;; + fatal) as_fn_error "unrecognized options: $ac_unrecognized_opts" ;; + *) $as_echo "$as_me: WARNING: unrecognized options: $ac_unrecognized_opts" >&2 ;; + esac fi -# Be sure to have absolute directory names. +# Check all directory arguments for consistency. for ac_var in exec_prefix prefix bindir sbindir libexecdir datarootdir \ datadir sysconfdir sharedstatedir localstatedir includedir \ oldincludedir docdir infodir htmldir dvidir pdfdir psdir \ libdir localedir mandir do eval ac_val=\$$ac_var + # Remove trailing slashes. + case $ac_val in + */ ) + ac_val=`expr "X$ac_val" : 'X\(.*[^/]\)' \| "X$ac_val" : 'X\(.*\)'` + eval $ac_var=\$ac_val;; + esac + # Be sure to have absolute directory names. case $ac_val in [\\/$]* | ?:[\\/]* ) continue;; NONE | '' ) case $ac_var in *prefix ) continue;; esac;; esac - { echo "$as_me: error: expected an absolute directory name for --$ac_var: $ac_val" >&2 - { (exit 1); exit 1; }; } + as_fn_error "expected an absolute directory name for --$ac_var: $ac_val" done # There might be people who depend on the old broken behavior: `$host' @@ -1159,7 +1216,7 @@ if test "x$host_alias" != x; then if test "x$build_alias" = x; then cross_compiling=maybe - echo "$as_me: WARNING: If you wanted to set the --build type, don't use --host. + $as_echo "$as_me: WARNING: If you wanted to set the --build type, don't use --host. If a cross compiler is detected then cross compile mode will be used." >&2 elif test "x$build_alias" != "x$host_alias"; then cross_compiling=yes @@ -1175,23 +1232,21 @@ ac_pwd=`pwd` && test -n "$ac_pwd" && ac_ls_di=`ls -di .` && ac_pwd_ls_di=`cd "$ac_pwd" && ls -di .` || - { echo "$as_me: error: Working directory cannot be determined" >&2 - { (exit 1); exit 1; }; } + as_fn_error "working directory cannot be determined" test "X$ac_ls_di" = "X$ac_pwd_ls_di" || - { echo "$as_me: error: pwd does not report name of working directory" >&2 - { (exit 1); exit 1; }; } + as_fn_error "pwd does not report name of working directory" # Find the source files, if location was not specified. if test -z "$srcdir"; then ac_srcdir_defaulted=yes # Try the directory containing this script, then the parent directory. - ac_confdir=`$as_dirname -- "$0" || -$as_expr X"$0" : 'X\(.*[^/]\)//*[^/][^/]*/*$' \| \ - X"$0" : 'X\(//\)[^/]' \| \ - X"$0" : 'X\(//\)$' \| \ - X"$0" : 'X\(/\)' \| . 2>/dev/null || -echo X"$0" | + ac_confdir=`$as_dirname -- "$as_myself" || +$as_expr X"$as_myself" : 'X\(.*[^/]\)//*[^/][^/]*/*$' \| \ + X"$as_myself" : 'X\(//\)[^/]' \| \ + X"$as_myself" : 'X\(//\)$' \| \ + X"$as_myself" : 'X\(/\)' \| . 2>/dev/null || +$as_echo X"$as_myself" | sed '/^X\(.*[^/]\)\/\/*[^/][^/]*\/*$/{ s//\1/ q @@ -1218,13 +1273,11 @@ fi if test ! -r "$srcdir/$ac_unique_file"; then test "$ac_srcdir_defaulted" = yes && srcdir="$ac_confdir or .." - { echo "$as_me: error: cannot find sources ($ac_unique_file) in $srcdir" >&2 - { (exit 1); exit 1; }; } + as_fn_error "cannot find sources ($ac_unique_file) in $srcdir" fi ac_msg="sources are in $srcdir, but \`cd $srcdir' does not work" ac_abs_confdir=`( - cd "$srcdir" && test -r "./$ac_unique_file" || { echo "$as_me: error: $ac_msg" >&2 - { (exit 1); exit 1; }; } + cd "$srcdir" && test -r "./$ac_unique_file" || as_fn_error "$ac_msg" pwd)` # When building in place, set srcdir=. if test "$ac_abs_confdir" = "$ac_pwd"; then @@ -1272,9 +1325,9 @@ Installation directories: --prefix=PREFIX install architecture-independent files in PREFIX - [$ac_default_prefix] + [$ac_default_prefix] --exec-prefix=EPREFIX install architecture-dependent files in EPREFIX - [PREFIX] + [PREFIX] By default, \`make install' will install all the files in \`$ac_default_prefix/bin', \`$ac_default_prefix/lib' etc. You can specify @@ -1284,25 +1337,25 @@ For better control, use the options below. Fine tuning of the installation directories: - --bindir=DIR user executables [EPREFIX/bin] - --sbindir=DIR system admin executables [EPREFIX/sbin] - --libexecdir=DIR program executables [EPREFIX/libexec] - --sysconfdir=DIR read-only single-machine data [PREFIX/etc] - --sharedstatedir=DIR modifiable architecture-independent data [PREFIX/com] - --localstatedir=DIR modifiable single-machine data [PREFIX/var] - --libdir=DIR object code libraries [EPREFIX/lib] - --includedir=DIR C header files [PREFIX/include] - --oldincludedir=DIR C header files for non-gcc [/usr/include] - --datarootdir=DIR read-only arch.-independent data root [PREFIX/share] - --datadir=DIR read-only architecture-independent data [DATAROOTDIR] - --infodir=DIR info documentation [DATAROOTDIR/info] - --localedir=DIR locale-dependent data [DATAROOTDIR/locale] - --mandir=DIR man documentation [DATAROOTDIR/man] - --docdir=DIR documentation root [DATAROOTDIR/doc/python] - --htmldir=DIR html documentation [DOCDIR] - --dvidir=DIR dvi documentation [DOCDIR] - --pdfdir=DIR pdf documentation [DOCDIR] - --psdir=DIR ps documentation [DOCDIR] + --bindir=DIR user executables [EPREFIX/bin] + --sbindir=DIR system admin executables [EPREFIX/sbin] + --libexecdir=DIR program executables [EPREFIX/libexec] + --sysconfdir=DIR read-only single-machine data [PREFIX/etc] + --sharedstatedir=DIR modifiable architecture-independent data [PREFIX/com] + --localstatedir=DIR modifiable single-machine data [PREFIX/var] + --libdir=DIR object code libraries [EPREFIX/lib] + --includedir=DIR C header files [PREFIX/include] + --oldincludedir=DIR C header files for non-gcc [/usr/include] + --datarootdir=DIR read-only arch.-independent data root [PREFIX/share] + --datadir=DIR read-only architecture-independent data [DATAROOTDIR] + --infodir=DIR info documentation [DATAROOTDIR/info] + --localedir=DIR locale-dependent data [DATAROOTDIR/locale] + --mandir=DIR man documentation [DATAROOTDIR/man] + --docdir=DIR documentation root [DATAROOTDIR/doc/python] + --htmldir=DIR html documentation [DOCDIR] + --dvidir=DIR dvi documentation [DOCDIR] + --pdfdir=DIR pdf documentation [DOCDIR] + --psdir=DIR ps documentation [DOCDIR] _ACEOF cat <<\_ACEOF @@ -1316,6 +1369,7 @@ cat <<\_ACEOF Optional Features: + --disable-option-checking ignore unrecognized --enable/--with options --disable-FEATURE do not include FEATURE (same as --enable-FEATURE=no) --enable-FEATURE[=ARG] include FEATURE [ARG=yes] --enable-universalsdk[=SDKDIR] @@ -1327,7 +1381,7 @@ --enable-ipv6 Enable ipv6 (with ipv4) support --disable-ipv6 Disable ipv6 support --enable-big-digits[=BITS] - use big digits for Python longs [BITS=30] + use big digits for Python longs [[BITS=30]] Optional Packages: --with-PACKAGE[=ARG] use PACKAGE [ARG=yes] @@ -1376,7 +1430,7 @@ LDFLAGS linker flags, e.g. -L if you have libraries in a nonstandard directory LIBS libraries to pass to the linker, e.g. -l - CPPFLAGS C/C++/Objective C preprocessor flags, e.g. -I if + CPPFLAGS (Objective) C/C++ preprocessor flags, e.g. -I if you have headers in a nonstandard directory CPP C preprocessor @@ -1391,15 +1445,17 @@ if test "$ac_init_help" = "recursive"; then # If there are subdirs, report their specific --help. for ac_dir in : $ac_subdirs_all; do test "x$ac_dir" = x: && continue - test -d "$ac_dir" || continue + test -d "$ac_dir" || + { cd "$srcdir" && ac_pwd=`pwd` && srcdir=. && test -d "$ac_dir"; } || + continue ac_builddir=. case "$ac_dir" in .) ac_dir_suffix= ac_top_builddir_sub=. ac_top_build_prefix= ;; *) - ac_dir_suffix=/`echo "$ac_dir" | sed 's,^\.[\\/],,'` + ac_dir_suffix=/`$as_echo "$ac_dir" | sed 's|^\.[\\/]||'` # A ".." for each directory in $ac_dir_suffix. - ac_top_builddir_sub=`echo "$ac_dir_suffix" | sed 's,/[^\\/]*,/..,g;s,/,,'` + ac_top_builddir_sub=`$as_echo "$ac_dir_suffix" | sed 's|/[^\\/]*|/..|g;s|/||'` case $ac_top_builddir_sub in "") ac_top_builddir_sub=. ac_top_build_prefix= ;; *) ac_top_build_prefix=$ac_top_builddir_sub/ ;; @@ -1435,7 +1491,7 @@ echo && $SHELL "$ac_srcdir/configure" --help=recursive else - echo "$as_me: WARNING: no configuration information is in $ac_dir" >&2 + $as_echo "$as_me: WARNING: no configuration information is in $ac_dir" >&2 fi || ac_status=$? cd "$ac_pwd" || { ac_status=$?; break; } done @@ -1445,632 +1501,1464 @@ if $ac_init_version; then cat <<\_ACEOF python configure 3.2 -generated by GNU Autoconf 2.61 +generated by GNU Autoconf 2.65 -Copyright (C) 1992, 1993, 1994, 1995, 1996, 1998, 1999, 2000, 2001, -2002, 2003, 2004, 2005, 2006 Free Software Foundation, Inc. +Copyright (C) 2009 Free Software Foundation, Inc. This configure script is free software; the Free Software Foundation gives unlimited permission to copy, distribute and modify it. _ACEOF exit fi -cat >config.log <<_ACEOF -This file contains any messages produced by compilers while -running configure, to aid debugging if configure makes a mistake. -It was created by python $as_me 3.2, which was -generated by GNU Autoconf 2.61. Invocation command line was +## ------------------------ ## +## Autoconf initialization. ## +## ------------------------ ## + +# ac_fn_c_try_compile LINENO +# -------------------------- +# Try to compile conftest.$ac_ext, and return whether this succeeded. +ac_fn_c_try_compile () +{ + as_lineno=${as_lineno-"$1"} as_lineno_stack=as_lineno_stack=$as_lineno_stack + rm -f conftest.$ac_objext + if { { ac_try="$ac_compile" +case "(($ac_try" in + *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; + *) ac_try_echo=$ac_try;; +esac +eval ac_try_echo="\"\$as_me:${as_lineno-$LINENO}: $ac_try_echo\"" +$as_echo "$ac_try_echo"; } >&5 + (eval "$ac_compile") 2>conftest.err + ac_status=$? + if test -s conftest.err; then + grep -v '^ *+' conftest.err >conftest.er1 + cat conftest.er1 >&5 + mv -f conftest.er1 conftest.err + fi + $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 + test $ac_status = 0; } && { + test -z "$ac_c_werror_flag" || + test ! -s conftest.err + } && test -s conftest.$ac_objext; then : + ac_retval=0 +else + $as_echo "$as_me: failed program was:" >&5 +sed 's/^/| /' conftest.$ac_ext >&5 - $ $0 $@ + ac_retval=1 +fi + eval $as_lineno_stack; test "x$as_lineno_stack" = x && { as_lineno=; unset as_lineno;} + as_fn_set_status $ac_retval -_ACEOF -exec 5>>config.log +} # ac_fn_c_try_compile + +# ac_fn_c_try_cpp LINENO +# ---------------------- +# Try to preprocess conftest.$ac_ext, and return whether this succeeded. +ac_fn_c_try_cpp () { -cat <<_ASUNAME -## --------- ## -## Platform. ## -## --------- ## + as_lineno=${as_lineno-"$1"} as_lineno_stack=as_lineno_stack=$as_lineno_stack + if { { ac_try="$ac_cpp conftest.$ac_ext" +case "(($ac_try" in + *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; + *) ac_try_echo=$ac_try;; +esac +eval ac_try_echo="\"\$as_me:${as_lineno-$LINENO}: $ac_try_echo\"" +$as_echo "$ac_try_echo"; } >&5 + (eval "$ac_cpp conftest.$ac_ext") 2>conftest.err + ac_status=$? + if test -s conftest.err; then + grep -v '^ *+' conftest.err >conftest.er1 + cat conftest.er1 >&5 + mv -f conftest.er1 conftest.err + fi + $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 + test $ac_status = 0; } >/dev/null && { + test -z "$ac_c_preproc_warn_flag$ac_c_werror_flag" || + test ! -s conftest.err + }; then : + ac_retval=0 +else + $as_echo "$as_me: failed program was:" >&5 +sed 's/^/| /' conftest.$ac_ext >&5 -hostname = `(hostname || uname -n) 2>/dev/null | sed 1q` -uname -m = `(uname -m) 2>/dev/null || echo unknown` -uname -r = `(uname -r) 2>/dev/null || echo unknown` -uname -s = `(uname -s) 2>/dev/null || echo unknown` -uname -v = `(uname -v) 2>/dev/null || echo unknown` + ac_retval=1 +fi + eval $as_lineno_stack; test "x$as_lineno_stack" = x && { as_lineno=; unset as_lineno;} + as_fn_set_status $ac_retval -/usr/bin/uname -p = `(/usr/bin/uname -p) 2>/dev/null || echo unknown` -/bin/uname -X = `(/bin/uname -X) 2>/dev/null || echo unknown` +} # ac_fn_c_try_cpp -/bin/arch = `(/bin/arch) 2>/dev/null || echo unknown` -/usr/bin/arch -k = `(/usr/bin/arch -k) 2>/dev/null || echo unknown` -/usr/convex/getsysinfo = `(/usr/convex/getsysinfo) 2>/dev/null || echo unknown` -/usr/bin/hostinfo = `(/usr/bin/hostinfo) 2>/dev/null || echo unknown` -/bin/machine = `(/bin/machine) 2>/dev/null || echo unknown` -/usr/bin/oslevel = `(/usr/bin/oslevel) 2>/dev/null || echo unknown` -/bin/universe = `(/bin/universe) 2>/dev/null || echo unknown` +# ac_fn_c_check_header_mongrel LINENO HEADER VAR INCLUDES +# ------------------------------------------------------- +# Tests whether HEADER exists, giving a warning if it cannot be compiled using +# the include files in INCLUDES and setting the cache variable VAR +# accordingly. +ac_fn_c_check_header_mongrel () +{ + as_lineno=${as_lineno-"$1"} as_lineno_stack=as_lineno_stack=$as_lineno_stack + if { as_var=$3; eval "test \"\${$as_var+set}\" = set"; }; then : + { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $2" >&5 +$as_echo_n "checking for $2... " >&6; } +if { as_var=$3; eval "test \"\${$as_var+set}\" = set"; }; then : + $as_echo_n "(cached) " >&6 +fi +eval ac_res=\$$3 + { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_res" >&5 +$as_echo "$ac_res" >&6; } +else + # Is the header compilable? +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking $2 usability" >&5 +$as_echo_n "checking $2 usability... " >&6; } +cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ +$4 +#include <$2> +_ACEOF +if ac_fn_c_try_compile "$LINENO"; then : + ac_header_compiler=yes +else + ac_header_compiler=no +fi +rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_header_compiler" >&5 +$as_echo "$ac_header_compiler" >&6; } -_ASUNAME +# Is the header present? +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking $2 presence" >&5 +$as_echo_n "checking $2 presence... " >&6; } +cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ +#include <$2> +_ACEOF +if ac_fn_c_try_cpp "$LINENO"; then : + ac_header_preproc=yes +else + ac_header_preproc=no +fi +rm -f conftest.err conftest.$ac_ext +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_header_preproc" >&5 +$as_echo "$ac_header_preproc" >&6; } -as_save_IFS=$IFS; IFS=$PATH_SEPARATOR -for as_dir in $PATH -do - IFS=$as_save_IFS - test -z "$as_dir" && as_dir=. - echo "PATH: $as_dir" -done -IFS=$as_save_IFS +# So? What about this header? +case $ac_header_compiler:$ac_header_preproc:$ac_c_preproc_warn_flag in #(( + yes:no: ) + { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: $2: accepted by the compiler, rejected by the preprocessor!" >&5 +$as_echo "$as_me: WARNING: $2: accepted by the compiler, rejected by the preprocessor!" >&2;} + { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: $2: proceeding with the compiler's result" >&5 +$as_echo "$as_me: WARNING: $2: proceeding with the compiler's result" >&2;} + ;; + no:yes:* ) + { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: $2: present but cannot be compiled" >&5 +$as_echo "$as_me: WARNING: $2: present but cannot be compiled" >&2;} + { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: $2: check for missing prerequisite headers?" >&5 +$as_echo "$as_me: WARNING: $2: check for missing prerequisite headers?" >&2;} + { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: $2: see the Autoconf documentation" >&5 +$as_echo "$as_me: WARNING: $2: see the Autoconf documentation" >&2;} + { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: $2: section \"Present But Cannot Be Compiled\"" >&5 +$as_echo "$as_me: WARNING: $2: section \"Present But Cannot Be Compiled\"" >&2;} + { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: $2: proceeding with the compiler's result" >&5 +$as_echo "$as_me: WARNING: $2: proceeding with the compiler's result" >&2;} +( cat <<\_ASBOX +## -------------------------------------- ## +## Report this to http://bugs.python.org/ ## +## -------------------------------------- ## +_ASBOX + ) | sed "s/^/$as_me: WARNING: /" >&2 + ;; +esac + { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $2" >&5 +$as_echo_n "checking for $2... " >&6; } +if { as_var=$3; eval "test \"\${$as_var+set}\" = set"; }; then : + $as_echo_n "(cached) " >&6 +else + eval "$3=\$ac_header_compiler" +fi +eval ac_res=\$$3 + { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_res" >&5 +$as_echo "$ac_res" >&6; } +fi + eval $as_lineno_stack; test "x$as_lineno_stack" = x && { as_lineno=; unset as_lineno;} -} >&5 +} # ac_fn_c_check_header_mongrel -cat >&5 <<_ACEOF +# ac_fn_c_try_run LINENO +# ---------------------- +# Try to link conftest.$ac_ext, and return whether this succeeded. Assumes +# that executables *can* be run. +ac_fn_c_try_run () +{ + as_lineno=${as_lineno-"$1"} as_lineno_stack=as_lineno_stack=$as_lineno_stack + if { { ac_try="$ac_link" +case "(($ac_try" in + *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; + *) ac_try_echo=$ac_try;; +esac +eval ac_try_echo="\"\$as_me:${as_lineno-$LINENO}: $ac_try_echo\"" +$as_echo "$ac_try_echo"; } >&5 + (eval "$ac_link") 2>&5 + ac_status=$? + $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 + test $ac_status = 0; } && { ac_try='./conftest$ac_exeext' + { { case "(($ac_try" in + *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; + *) ac_try_echo=$ac_try;; +esac +eval ac_try_echo="\"\$as_me:${as_lineno-$LINENO}: $ac_try_echo\"" +$as_echo "$ac_try_echo"; } >&5 + (eval "$ac_try") 2>&5 + ac_status=$? + $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 + test $ac_status = 0; }; }; then : + ac_retval=0 +else + $as_echo "$as_me: program exited with status $ac_status" >&5 + $as_echo "$as_me: failed program was:" >&5 +sed 's/^/| /' conftest.$ac_ext >&5 + ac_retval=$ac_status +fi + rm -rf conftest.dSYM conftest_ipa8_conftest.oo + eval $as_lineno_stack; test "x$as_lineno_stack" = x && { as_lineno=; unset as_lineno;} + as_fn_set_status $ac_retval -## ----------- ## -## Core tests. ## -## ----------- ## +} # ac_fn_c_try_run +# ac_fn_c_check_header_compile LINENO HEADER VAR INCLUDES +# ------------------------------------------------------- +# Tests whether HEADER exists and can be compiled using the include files in +# INCLUDES, setting the cache variable VAR accordingly. +ac_fn_c_check_header_compile () +{ + as_lineno=${as_lineno-"$1"} as_lineno_stack=as_lineno_stack=$as_lineno_stack + { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $2" >&5 +$as_echo_n "checking for $2... " >&6; } +if { as_var=$3; eval "test \"\${$as_var+set}\" = set"; }; then : + $as_echo_n "(cached) " >&6 +else + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ +$4 +#include <$2> _ACEOF +if ac_fn_c_try_compile "$LINENO"; then : + eval "$3=yes" +else + eval "$3=no" +fi +rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext +fi +eval ac_res=\$$3 + { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_res" >&5 +$as_echo "$ac_res" >&6; } + eval $as_lineno_stack; test "x$as_lineno_stack" = x && { as_lineno=; unset as_lineno;} +} # ac_fn_c_check_header_compile -# Keep a trace of the command line. -# Strip out --no-create and --no-recursion so they do not pile up. -# Strip out --silent because we don't want to record it for future runs. -# Also quote any args containing shell meta-characters. -# Make two passes to allow for proper duplicate-argument suppression. -ac_configure_args= -ac_configure_args0= -ac_configure_args1= -ac_must_keep_next=false -for ac_pass in 1 2 -do - for ac_arg - do - case $ac_arg in - -no-create | --no-c* | -n | -no-recursion | --no-r*) continue ;; - -q | -quiet | --quiet | --quie | --qui | --qu | --q \ - | -silent | --silent | --silen | --sile | --sil) - continue ;; - *\'*) - ac_arg=`echo "$ac_arg" | sed "s/'/'\\\\\\\\''/g"` ;; - esac - case $ac_pass in - 1) ac_configure_args0="$ac_configure_args0 '$ac_arg'" ;; - 2) - ac_configure_args1="$ac_configure_args1 '$ac_arg'" - if test $ac_must_keep_next = true; then - ac_must_keep_next=false # Got value, back to normal. - else - case $ac_arg in - *=* | --config-cache | -C | -disable-* | --disable-* \ - | -enable-* | --enable-* | -gas | --g* | -nfp | --nf* \ - | -q | -quiet | --q* | -silent | --sil* | -v | -verb* \ - | -with-* | --with-* | -without-* | --without-* | --x) - case "$ac_configure_args0 " in - "$ac_configure_args1"*" '$ac_arg' "* ) continue ;; - esac - ;; - -* ) ac_must_keep_next=true ;; - esac - fi - ac_configure_args="$ac_configure_args '$ac_arg'" - ;; - esac - done -done -$as_unset ac_configure_args0 || test "${ac_configure_args0+set}" != set || { ac_configure_args0=; export ac_configure_args0; } -$as_unset ac_configure_args1 || test "${ac_configure_args1+set}" != set || { ac_configure_args1=; export ac_configure_args1; } +# ac_fn_c_try_link LINENO +# ----------------------- +# Try to link conftest.$ac_ext, and return whether this succeeded. +ac_fn_c_try_link () +{ + as_lineno=${as_lineno-"$1"} as_lineno_stack=as_lineno_stack=$as_lineno_stack + rm -f conftest.$ac_objext conftest$ac_exeext + if { { ac_try="$ac_link" +case "(($ac_try" in + *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; + *) ac_try_echo=$ac_try;; +esac +eval ac_try_echo="\"\$as_me:${as_lineno-$LINENO}: $ac_try_echo\"" +$as_echo "$ac_try_echo"; } >&5 + (eval "$ac_link") 2>conftest.err + ac_status=$? + if test -s conftest.err; then + grep -v '^ *+' conftest.err >conftest.er1 + cat conftest.er1 >&5 + mv -f conftest.er1 conftest.err + fi + $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 + test $ac_status = 0; } && { + test -z "$ac_c_werror_flag" || + test ! -s conftest.err + } && test -s conftest$ac_exeext && { + test "$cross_compiling" = yes || + $as_test_x conftest$ac_exeext + }; then : + ac_retval=0 +else + $as_echo "$as_me: failed program was:" >&5 +sed 's/^/| /' conftest.$ac_ext >&5 -# When interrupted or exit'd, cleanup temporary files, and complete -# config.log. We remove comments because anyway the quotes in there -# would cause problems or look ugly. -# WARNING: Use '\'' to represent an apostrophe within the trap. -# WARNING: Do not start the trap code with a newline, due to a FreeBSD 4.0 bug. -trap 'exit_status=$? - # Save into config.log some information that might help in debugging. - { - echo + ac_retval=1 +fi + # Delete the IPA/IPO (Inter Procedural Analysis/Optimization) information + # created by the PGI compiler (conftest_ipa8_conftest.oo), as it would + # interfere with the next link command; also delete a directory that is + # left behind by Apple's compiler. We do this before executing the actions. + rm -rf conftest.dSYM conftest_ipa8_conftest.oo + eval $as_lineno_stack; test "x$as_lineno_stack" = x && { as_lineno=; unset as_lineno;} + as_fn_set_status $ac_retval - cat <<\_ASBOX -## ---------------- ## -## Cache variables. ## -## ---------------- ## -_ASBOX - echo - # The following way of writing the cache mishandles newlines in values, -( - for ac_var in `(set) 2>&1 | sed -n '\''s/^\([a-zA-Z_][a-zA-Z0-9_]*\)=.*/\1/p'\''`; do - eval ac_val=\$$ac_var - case $ac_val in #( - *${as_nl}*) - case $ac_var in #( - *_cv_*) { echo "$as_me:$LINENO: WARNING: Cache variable $ac_var contains a newline." >&5 -echo "$as_me: WARNING: Cache variable $ac_var contains a newline." >&2;} ;; - esac - case $ac_var in #( - _ | IFS | as_nl) ;; #( - *) $as_unset $ac_var ;; - esac ;; - esac - done - (set) 2>&1 | - case $as_nl`(ac_space='\'' '\''; set) 2>&1` in #( - *${as_nl}ac_space=\ *) - sed -n \ - "s/'\''/'\''\\\\'\'''\''/g; - s/^\\([_$as_cr_alnum]*_cv_[_$as_cr_alnum]*\\)=\\(.*\\)/\\1='\''\\2'\''/p" - ;; #( - *) - sed -n "/^[_$as_cr_alnum]*_cv_[_$as_cr_alnum]*=/p" - ;; - esac | - sort -) - echo +} # ac_fn_c_try_link - cat <<\_ASBOX -## ----------------- ## -## Output variables. ## -## ----------------- ## -_ASBOX - echo - for ac_var in $ac_subst_vars - do - eval ac_val=\$$ac_var - case $ac_val in - *\'\''*) ac_val=`echo "$ac_val" | sed "s/'\''/'\''\\\\\\\\'\'''\''/g"`;; - esac - echo "$ac_var='\''$ac_val'\''" - done | sort - echo +# ac_fn_c_check_type LINENO TYPE VAR INCLUDES +# ------------------------------------------- +# Tests whether TYPE exists after having included INCLUDES, setting cache +# variable VAR accordingly. +ac_fn_c_check_type () +{ + as_lineno=${as_lineno-"$1"} as_lineno_stack=as_lineno_stack=$as_lineno_stack + { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $2" >&5 +$as_echo_n "checking for $2... " >&6; } +if { as_var=$3; eval "test \"\${$as_var+set}\" = set"; }; then : + $as_echo_n "(cached) " >&6 +else + eval "$3=no" + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ +$4 +int +main () +{ +if (sizeof ($2)) + return 0; + ; + return 0; +} +_ACEOF +if ac_fn_c_try_compile "$LINENO"; then : + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ +$4 +int +main () +{ +if (sizeof (($2))) + return 0; + ; + return 0; +} +_ACEOF +if ac_fn_c_try_compile "$LINENO"; then : - if test -n "$ac_subst_files"; then - cat <<\_ASBOX -## ------------------- ## -## File substitutions. ## -## ------------------- ## -_ASBOX - echo - for ac_var in $ac_subst_files - do - eval ac_val=\$$ac_var - case $ac_val in - *\'\''*) ac_val=`echo "$ac_val" | sed "s/'\''/'\''\\\\\\\\'\'''\''/g"`;; - esac - echo "$ac_var='\''$ac_val'\''" - done | sort - echo - fi - - if test -s confdefs.h; then - cat <<\_ASBOX -## ----------- ## -## confdefs.h. ## -## ----------- ## -_ASBOX - echo - cat confdefs.h - echo - fi - test "$ac_signal" != 0 && - echo "$as_me: caught signal $ac_signal" - echo "$as_me: exit $exit_status" - } >&5 - rm -f core *.core core.conftest.* && - rm -f -r conftest* confdefs* conf$$* $ac_clean_files && - exit $exit_status -' 0 -for ac_signal in 1 2 13 15; do - trap 'ac_signal='$ac_signal'; { (exit 1); exit 1; }' $ac_signal -done -ac_signal=0 +else + eval "$3=yes" +fi +rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext +fi +rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext +fi +eval ac_res=\$$3 + { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_res" >&5 +$as_echo "$ac_res" >&6; } + eval $as_lineno_stack; test "x$as_lineno_stack" = x && { as_lineno=; unset as_lineno;} -# confdefs.h avoids OS command line length limits that DEFS can exceed. -rm -f -r conftest* confdefs.h +} # ac_fn_c_check_type -# Predefined preprocessor variables. +# ac_fn_c_find_uintX_t LINENO BITS VAR +# ------------------------------------ +# Finds an unsigned integer type with width BITS, setting cache variable VAR +# accordingly. +ac_fn_c_find_uintX_t () +{ + as_lineno=${as_lineno-"$1"} as_lineno_stack=as_lineno_stack=$as_lineno_stack + { $as_echo "$as_me:${as_lineno-$LINENO}: checking for uint$2_t" >&5 +$as_echo_n "checking for uint$2_t... " >&6; } +if { as_var=$3; eval "test \"\${$as_var+set}\" = set"; }; then : + $as_echo_n "(cached) " >&6 +else + eval "$3=no" + # Order is important - never check a type that is potentially smaller + # than half of the expected target width. + for ac_type in uint$2_t 'unsigned int' 'unsigned long int' \ + 'unsigned long long int' 'unsigned short int' 'unsigned char'; do + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ +$ac_includes_default +int +main () +{ +static int test_array [1 - 2 * !((($ac_type) -1 >> ($2 / 2 - 1)) >> ($2 / 2 - 1) == 3)]; +test_array [0] = 0 -cat >>confdefs.h <<_ACEOF -#define PACKAGE_NAME "$PACKAGE_NAME" + ; + return 0; +} _ACEOF +if ac_fn_c_try_compile "$LINENO"; then : + case $ac_type in #( + uint$2_t) : + eval "$3=yes" ;; #( + *) : + eval "$3=\$ac_type" ;; +esac +fi +rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext + eval as_val=\$$3 + if test "x$as_val" = x""no; then : +else + break +fi + done +fi +eval ac_res=\$$3 + { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_res" >&5 +$as_echo "$ac_res" >&6; } + eval $as_lineno_stack; test "x$as_lineno_stack" = x && { as_lineno=; unset as_lineno;} + +} # ac_fn_c_find_uintX_t + +# ac_fn_c_find_intX_t LINENO BITS VAR +# ----------------------------------- +# Finds a signed integer type with width BITS, setting cache variable VAR +# accordingly. +ac_fn_c_find_intX_t () +{ + as_lineno=${as_lineno-"$1"} as_lineno_stack=as_lineno_stack=$as_lineno_stack + { $as_echo "$as_me:${as_lineno-$LINENO}: checking for int$2_t" >&5 +$as_echo_n "checking for int$2_t... " >&6; } +if { as_var=$3; eval "test \"\${$as_var+set}\" = set"; }; then : + $as_echo_n "(cached) " >&6 +else + eval "$3=no" + # Order is important - never check a type that is potentially smaller + # than half of the expected target width. + for ac_type in int$2_t 'int' 'long int' \ + 'long long int' 'short int' 'signed char'; do + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ +$ac_includes_default + enum { N = $2 / 2 - 1 }; +int +main () +{ +static int test_array [1 - 2 * !(0 < ($ac_type) ((((($ac_type) 1 << N) << N) - 1) * 2 + 1))]; +test_array [0] = 0 -cat >>confdefs.h <<_ACEOF -#define PACKAGE_TARNAME "$PACKAGE_TARNAME" + ; + return 0; +} _ACEOF +if ac_fn_c_try_compile "$LINENO"; then : + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ +$ac_includes_default + enum { N = $2 / 2 - 1 }; +int +main () +{ +static int test_array [1 - 2 * !(($ac_type) ((((($ac_type) 1 << N) << N) - 1) * 2 + 1) + < ($ac_type) ((((($ac_type) 1 << N) << N) - 1) * 2 + 2))]; +test_array [0] = 0 - -cat >>confdefs.h <<_ACEOF -#define PACKAGE_VERSION "$PACKAGE_VERSION" + ; + return 0; +} _ACEOF +if ac_fn_c_try_compile "$LINENO"; then : + +else + case $ac_type in #( + int$2_t) : + eval "$3=yes" ;; #( + *) : + eval "$3=\$ac_type" ;; +esac +fi +rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext +fi +rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext + eval as_val=\$$3 + if test "x$as_val" = x""no; then : +else + break +fi + done +fi +eval ac_res=\$$3 + { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_res" >&5 +$as_echo "$ac_res" >&6; } + eval $as_lineno_stack; test "x$as_lineno_stack" = x && { as_lineno=; unset as_lineno;} + +} # ac_fn_c_find_intX_t + +# ac_fn_c_compute_int LINENO EXPR VAR INCLUDES +# -------------------------------------------- +# Tries to find the compile-time value of EXPR in a program that includes +# INCLUDES, setting VAR accordingly. Returns whether the value could be +# computed +ac_fn_c_compute_int () +{ + as_lineno=${as_lineno-"$1"} as_lineno_stack=as_lineno_stack=$as_lineno_stack + if test "$cross_compiling" = yes; then + # Depending upon the size, compute the lo and hi bounds. +cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ +$4 +int +main () +{ +static int test_array [1 - 2 * !(($2) >= 0)]; +test_array [0] = 0 -cat >>confdefs.h <<_ACEOF -#define PACKAGE_STRING "$PACKAGE_STRING" + ; + return 0; +} _ACEOF +if ac_fn_c_try_compile "$LINENO"; then : + ac_lo=0 ac_mid=0 + while :; do + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ +$4 +int +main () +{ +static int test_array [1 - 2 * !(($2) <= $ac_mid)]; +test_array [0] = 0 + ; + return 0; +} +_ACEOF +if ac_fn_c_try_compile "$LINENO"; then : + ac_hi=$ac_mid; break +else + as_fn_arith $ac_mid + 1 && ac_lo=$as_val + if test $ac_lo -le $ac_mid; then + ac_lo= ac_hi= + break + fi + as_fn_arith 2 '*' $ac_mid + 1 && ac_mid=$as_val +fi +rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext + done +else + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ +$4 +int +main () +{ +static int test_array [1 - 2 * !(($2) < 0)]; +test_array [0] = 0 -cat >>confdefs.h <<_ACEOF -#define PACKAGE_BUGREPORT "$PACKAGE_BUGREPORT" + ; + return 0; +} _ACEOF +if ac_fn_c_try_compile "$LINENO"; then : + ac_hi=-1 ac_mid=-1 + while :; do + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ +$4 +int +main () +{ +static int test_array [1 - 2 * !(($2) >= $ac_mid)]; +test_array [0] = 0 + ; + return 0; +} +_ACEOF +if ac_fn_c_try_compile "$LINENO"; then : + ac_lo=$ac_mid; break +else + as_fn_arith '(' $ac_mid ')' - 1 && ac_hi=$as_val + if test $ac_mid -le $ac_hi; then + ac_lo= ac_hi= + break + fi + as_fn_arith 2 '*' $ac_mid && ac_mid=$as_val +fi +rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext + done +else + ac_lo= ac_hi= +fi +rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext +fi +rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext +# Binary search between lo and hi bounds. +while test "x$ac_lo" != "x$ac_hi"; do + as_fn_arith '(' $ac_hi - $ac_lo ')' / 2 + $ac_lo && ac_mid=$as_val + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ +$4 +int +main () +{ +static int test_array [1 - 2 * !(($2) <= $ac_mid)]; +test_array [0] = 0 -# Let the site file select an alternate cache file if it wants to. -# Prefer explicitly selected file to automatically selected ones. -if test -n "$CONFIG_SITE"; then - set x "$CONFIG_SITE" -elif test "x$prefix" != xNONE; then - set x "$prefix/share/config.site" "$prefix/etc/config.site" + ; + return 0; +} +_ACEOF +if ac_fn_c_try_compile "$LINENO"; then : + ac_hi=$ac_mid else - set x "$ac_default_prefix/share/config.site" \ - "$ac_default_prefix/etc/config.site" + as_fn_arith '(' $ac_mid ')' + 1 && ac_lo=$as_val fi -shift -for ac_site_file -do - if test -r "$ac_site_file"; then - { echo "$as_me:$LINENO: loading site script $ac_site_file" >&5 -echo "$as_me: loading site script $ac_site_file" >&6;} - sed 's/^/| /' "$ac_site_file" >&5 - . "$ac_site_file" - fi +rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext done +case $ac_lo in #(( +?*) eval "$3=\$ac_lo"; ac_retval=0 ;; +'') ac_retval=1 ;; +esac + else + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ +$4 +static long int longval () { return $2; } +static unsigned long int ulongval () { return $2; } +#include +#include +int +main () +{ -if test -r "$cache_file"; then - # Some versions of bash will fail to source /dev/null (special - # files actually), so we avoid doing that. - if test -f "$cache_file"; then - { echo "$as_me:$LINENO: loading cache $cache_file" >&5 -echo "$as_me: loading cache $cache_file" >&6;} - case $cache_file in - [\\/]* | ?:[\\/]* ) . "$cache_file";; - *) . "./$cache_file";; - esac - fi + FILE *f = fopen ("conftest.val", "w"); + if (! f) + return 1; + if (($2) < 0) + { + long int i = longval (); + if (i != ($2)) + return 1; + fprintf (f, "%ld", i); + } + else + { + unsigned long int i = ulongval (); + if (i != ($2)) + return 1; + fprintf (f, "%lu", i); + } + /* Do not output a trailing newline, as this causes \r\n confusion + on some platforms. */ + return ferror (f) || fclose (f) != 0; + + ; + return 0; +} +_ACEOF +if ac_fn_c_try_run "$LINENO"; then : + echo >>conftest.val; read $3 &5 -echo "$as_me: creating cache $cache_file" >&6;} - >$cache_file + ac_retval=1 fi +rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext \ + conftest.$ac_objext conftest.beam conftest.$ac_ext +rm -f conftest.val -# Check that the precious variables saved in the cache have kept the same -# value. -ac_cache_corrupted=false -for ac_var in $ac_precious_vars; do - eval ac_old_set=\$ac_cv_env_${ac_var}_set - eval ac_new_set=\$ac_env_${ac_var}_set - eval ac_old_val=\$ac_cv_env_${ac_var}_value - eval ac_new_val=\$ac_env_${ac_var}_value - case $ac_old_set,$ac_new_set in - set,) - { echo "$as_me:$LINENO: error: \`$ac_var' was set to \`$ac_old_val' in the previous run" >&5 -echo "$as_me: error: \`$ac_var' was set to \`$ac_old_val' in the previous run" >&2;} - ac_cache_corrupted=: ;; - ,set) - { echo "$as_me:$LINENO: error: \`$ac_var' was not set in the previous run" >&5 -echo "$as_me: error: \`$ac_var' was not set in the previous run" >&2;} - ac_cache_corrupted=: ;; - ,);; - *) - if test "x$ac_old_val" != "x$ac_new_val"; then - { echo "$as_me:$LINENO: error: \`$ac_var' has changed since the previous run:" >&5 -echo "$as_me: error: \`$ac_var' has changed since the previous run:" >&2;} - { echo "$as_me:$LINENO: former value: $ac_old_val" >&5 -echo "$as_me: former value: $ac_old_val" >&2;} - { echo "$as_me:$LINENO: current value: $ac_new_val" >&5 -echo "$as_me: current value: $ac_new_val" >&2;} - ac_cache_corrupted=: - fi;; - esac - # Pass precious variables to config.status. - if test "$ac_new_set" = set; then - case $ac_new_val in - *\'*) ac_arg=$ac_var=`echo "$ac_new_val" | sed "s/'/'\\\\\\\\''/g"` ;; - *) ac_arg=$ac_var=$ac_new_val ;; - esac - case " $ac_configure_args " in - *" '$ac_arg' "*) ;; # Avoid dups. Use of quotes ensures accuracy. - *) ac_configure_args="$ac_configure_args '$ac_arg'" ;; - esac fi -done -if $ac_cache_corrupted; then - { echo "$as_me:$LINENO: error: changes in the environment can compromise the build" >&5 -echo "$as_me: error: changes in the environment can compromise the build" >&2;} - { { echo "$as_me:$LINENO: error: run \`make distclean' and/or \`rm $cache_file' and start over" >&5 -echo "$as_me: error: run \`make distclean' and/or \`rm $cache_file' and start over" >&2;} - { (exit 1); exit 1; }; } -fi - - + eval $as_lineno_stack; test "x$as_lineno_stack" = x && { as_lineno=; unset as_lineno;} + as_fn_set_status $ac_retval +} # ac_fn_c_compute_int +# ac_fn_c_check_func LINENO FUNC VAR +# ---------------------------------- +# Tests whether FUNC exists, setting the cache variable VAR accordingly +ac_fn_c_check_func () +{ + as_lineno=${as_lineno-"$1"} as_lineno_stack=as_lineno_stack=$as_lineno_stack + { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $2" >&5 +$as_echo_n "checking for $2... " >&6; } +if { as_var=$3; eval "test \"\${$as_var+set}\" = set"; }; then : + $as_echo_n "(cached) " >&6 +else + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ +/* Define $2 to an innocuous variant, in case declares $2. + For example, HP-UX 11i declares gettimeofday. */ +#define $2 innocuous_$2 +/* System header to define __stub macros and hopefully few prototypes, + which can conflict with char $2 (); below. + Prefer to if __STDC__ is defined, since + exists even on freestanding compilers. */ +#ifdef __STDC__ +# include +#else +# include +#endif +#undef $2 +/* Override any GCC internal prototype to avoid an error. + Use char because int might match the return type of a GCC + builtin and then its argument prototype would still apply. */ +#ifdef __cplusplus +extern "C" +#endif +char $2 (); +/* The GNU C library defines this for functions which it implements + to always fail with ENOSYS. Some functions are actually named + something starting with __ and the normal name is an alias. */ +#if defined __stub_$2 || defined __stub___$2 +choke me +#endif - - - - - - - - - - - - - - - - -ac_ext=c -ac_cpp='$CPP $CPPFLAGS' -ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5' -ac_link='$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5' -ac_compiler_gnu=$ac_cv_c_compiler_gnu - - - -ac_config_headers="$ac_config_headers pyconfig.h" - - - -if test "$prefix" != "/"; then - prefix=`echo "$prefix" | sed -e 's/\/$//g'` -fi - - - - - - -# We don't use PACKAGE_ variables, and they cause conflicts -# with other autoconf-based packages that include Python.h -grep -v 'define PACKAGE_' confdefs.h.new -rm confdefs.h -mv confdefs.h.new confdefs.h - - -VERSION=3.2 - - -SOVERSION=1.0 - -# The later defininition of _XOPEN_SOURCE disables certain features -# on Linux, so we need _GNU_SOURCE to re-enable them (makedev, tm_zone). - -cat >>confdefs.h <<\_ACEOF -#define _GNU_SOURCE 1 -_ACEOF - - -# The later defininition of _XOPEN_SOURCE and _POSIX_C_SOURCE disables -# certain features on NetBSD, so we need _NETBSD_SOURCE to re-enable -# them. - -cat >>confdefs.h <<\_ACEOF -#define _NETBSD_SOURCE 1 +int +main () +{ +return $2 (); + ; + return 0; +} _ACEOF +if ac_fn_c_try_link "$LINENO"; then : + eval "$3=yes" +else + eval "$3=no" +fi +rm -f core conftest.err conftest.$ac_objext \ + conftest$ac_exeext conftest.$ac_ext +fi +eval ac_res=\$$3 + { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_res" >&5 +$as_echo "$ac_res" >&6; } + eval $as_lineno_stack; test "x$as_lineno_stack" = x && { as_lineno=; unset as_lineno;} +} # ac_fn_c_check_func -# The later defininition of _XOPEN_SOURCE and _POSIX_C_SOURCE disables -# certain features on FreeBSD, so we need __BSD_VISIBLE to re-enable -# them. - -cat >>confdefs.h <<\_ACEOF -#define __BSD_VISIBLE 1 +# ac_fn_c_check_member LINENO AGGR MEMBER VAR INCLUDES +# ---------------------------------------------------- +# Tries to find if the field MEMBER exists in type AGGR, after including +# INCLUDES, setting cache variable VAR accordingly. +ac_fn_c_check_member () +{ + as_lineno=${as_lineno-"$1"} as_lineno_stack=as_lineno_stack=$as_lineno_stack + { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $2.$3" >&5 +$as_echo_n "checking for $2.$3... " >&6; } +if { as_var=$4; eval "test \"\${$as_var+set}\" = set"; }; then : + $as_echo_n "(cached) " >&6 +else + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ +$5 +int +main () +{ +static $2 ac_aggr; +if (ac_aggr.$3) +return 0; + ; + return 0; +} _ACEOF - - -# The later defininition of _XOPEN_SOURCE and _POSIX_C_SOURCE disables -# u_int on Irix 5.3. Defining _BSD_TYPES brings it back. - -cat >>confdefs.h <<\_ACEOF -#define _BSD_TYPES 1 +if ac_fn_c_try_compile "$LINENO"; then : + eval "$4=yes" +else + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ +$5 +int +main () +{ +static $2 ac_aggr; +if (sizeof ac_aggr.$3) +return 0; + ; + return 0; +} _ACEOF +if ac_fn_c_try_compile "$LINENO"; then : + eval "$4=yes" +else + eval "$4=no" +fi +rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext +fi +rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext +fi +eval ac_res=\$$4 + { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_res" >&5 +$as_echo "$ac_res" >&6; } + eval $as_lineno_stack; test "x$as_lineno_stack" = x && { as_lineno=; unset as_lineno;} +} # ac_fn_c_check_member -# The later defininition of _XOPEN_SOURCE and _POSIX_C_SOURCE disables -# certain features on Mac OS X, so we need _DARWIN_C_SOURCE to re-enable -# them. +# ac_fn_c_check_decl LINENO SYMBOL VAR +# ------------------------------------ +# Tests whether SYMBOL is declared, setting cache variable VAR accordingly. +ac_fn_c_check_decl () +{ + as_lineno=${as_lineno-"$1"} as_lineno_stack=as_lineno_stack=$as_lineno_stack + { $as_echo "$as_me:${as_lineno-$LINENO}: checking whether $2 is declared" >&5 +$as_echo_n "checking whether $2 is declared... " >&6; } +if { as_var=$3; eval "test \"\${$as_var+set}\" = set"; }; then : + $as_echo_n "(cached) " >&6 +else + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ +$4 +int +main () +{ +#ifndef $2 + (void) $2; +#endif -cat >>confdefs.h <<\_ACEOF -#define _DARWIN_C_SOURCE 1 + ; + return 0; +} _ACEOF - - - -define_xopen_source=yes - -# Arguments passed to configure. - -CONFIG_ARGS="$ac_configure_args" - -{ echo "$as_me:$LINENO: checking for --enable-universalsdk" >&5 -echo $ECHO_N "checking for --enable-universalsdk... $ECHO_C" >&6; } -# Check whether --enable-universalsdk was given. -if test "${enable_universalsdk+set}" = set; then - enableval=$enable_universalsdk; - case $enableval in - yes) - enableval=/Developer/SDKs/MacOSX10.4u.sdk - if test ! -d "${enableval}" - then - enableval=/ - fi - ;; - esac - case $enableval in - no) - UNIVERSALSDK= - enable_universalsdk= - ;; - *) - UNIVERSALSDK=$enableval - if test ! -d "${UNIVERSALSDK}" - then - { { echo "$as_me:$LINENO: error: --enable-universalsdk specifies non-existing SDK: ${UNIVERSALSDK}" >&5 -echo "$as_me: error: --enable-universalsdk specifies non-existing SDK: ${UNIVERSALSDK}" >&2;} - { (exit 1); exit 1; }; } - fi - ;; - esac - - +if ac_fn_c_try_compile "$LINENO"; then : + eval "$3=yes" else - - UNIVERSALSDK= - enable_universalsdk= - + eval "$3=no" fi - -if test -n "${UNIVERSALSDK}" -then - { echo "$as_me:$LINENO: result: ${UNIVERSALSDK}" >&5 -echo "${ECHO_T}${UNIVERSALSDK}" >&6; } -else - { echo "$as_me:$LINENO: result: no" >&5 -echo "${ECHO_T}no" >&6; } +rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext fi +eval ac_res=\$$3 + { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_res" >&5 +$as_echo "$ac_res" >&6; } + eval $as_lineno_stack; test "x$as_lineno_stack" = x && { as_lineno=; unset as_lineno;} +} # ac_fn_c_check_decl +cat >config.log <<_ACEOF +This file contains any messages produced by compilers while +running configure, to aid debugging if configure makes a mistake. +It was created by python $as_me 3.2, which was +generated by GNU Autoconf 2.65. Invocation command line was + $ $0 $@ -UNIVERSAL_ARCHS="32-bit" - -{ echo "$as_me:$LINENO: checking for --with-universal-archs" >&5 -echo $ECHO_N "checking for --with-universal-archs... $ECHO_C" >&6; } - -# Check whether --with-universal-archs was given. -if test "${with_universal_archs+set}" = set; then - withval=$with_universal_archs; - { echo "$as_me:$LINENO: result: $withval" >&5 -echo "${ECHO_T}$withval" >&6; } - UNIVERSAL_ARCHS="$withval" +_ACEOF +exec 5>>config.log +{ +cat <<_ASUNAME +## --------- ## +## Platform. ## +## --------- ## -else +hostname = `(hostname || uname -n) 2>/dev/null | sed 1q` +uname -m = `(uname -m) 2>/dev/null || echo unknown` +uname -r = `(uname -r) 2>/dev/null || echo unknown` +uname -s = `(uname -s) 2>/dev/null || echo unknown` +uname -v = `(uname -v) 2>/dev/null || echo unknown` - { echo "$as_me:$LINENO: result: 32-bit" >&5 -echo "${ECHO_T}32-bit" >&6; } +/usr/bin/uname -p = `(/usr/bin/uname -p) 2>/dev/null || echo unknown` +/bin/uname -X = `(/bin/uname -X) 2>/dev/null || echo unknown` -fi +/bin/arch = `(/bin/arch) 2>/dev/null || echo unknown` +/usr/bin/arch -k = `(/usr/bin/arch -k) 2>/dev/null || echo unknown` +/usr/convex/getsysinfo = `(/usr/convex/getsysinfo) 2>/dev/null || echo unknown` +/usr/bin/hostinfo = `(/usr/bin/hostinfo) 2>/dev/null || echo unknown` +/bin/machine = `(/bin/machine) 2>/dev/null || echo unknown` +/usr/bin/oslevel = `(/usr/bin/oslevel) 2>/dev/null || echo unknown` +/bin/universe = `(/bin/universe) 2>/dev/null || echo unknown` +_ASUNAME +as_save_IFS=$IFS; IFS=$PATH_SEPARATOR +for as_dir in $PATH +do + IFS=$as_save_IFS + test -z "$as_dir" && as_dir=. + $as_echo "PATH: $as_dir" + done +IFS=$as_save_IFS +} >&5 +cat >&5 <<_ACEOF -# Check whether --with-framework-name was given. -if test "${with_framework_name+set}" = set; then - withval=$with_framework_name; - PYTHONFRAMEWORK=${withval} - PYTHONFRAMEWORKDIR=${withval}.framework - PYTHONFRAMEWORKIDENTIFIER=org.python.`echo $withval | tr 'A-Z' 'a-z'` -else +## ----------- ## +## Core tests. ## +## ----------- ## - PYTHONFRAMEWORK=Python - PYTHONFRAMEWORKDIR=Python.framework - PYTHONFRAMEWORKIDENTIFIER=org.python.python +_ACEOF -fi -# Check whether --enable-framework was given. -if test "${enable_framework+set}" = set; then - enableval=$enable_framework; - case $enableval in - yes) - enableval=/Library/Frameworks - esac - case $enableval in - no) - PYTHONFRAMEWORK= - PYTHONFRAMEWORKDIR=no-framework - PYTHONFRAMEWORKPREFIX= - PYTHONFRAMEWORKINSTALLDIR= - FRAMEWORKINSTALLFIRST= - FRAMEWORKINSTALLLAST= - FRAMEWORKALTINSTALLFIRST= - FRAMEWORKALTINSTALLLAST= - if test "x${prefix}" = "xNONE"; then - FRAMEWORKUNIXTOOLSPREFIX="${ac_default_prefix}" - else - FRAMEWORKUNIXTOOLSPREFIX="${prefix}" - fi - enable_framework= - ;; - *) - PYTHONFRAMEWORKPREFIX=$enableval - PYTHONFRAMEWORKINSTALLDIR=$PYTHONFRAMEWORKPREFIX/$PYTHONFRAMEWORKDIR - FRAMEWORKINSTALLFIRST="frameworkinstallstructure" - FRAMEWORKALTINSTALLFIRST="frameworkinstallstructure " - FRAMEWORKINSTALLLAST="frameworkinstallmaclib frameworkinstallapps frameworkinstallunixtools" - FRAMEWORKALTINSTALLLAST="frameworkinstallmaclib frameworkinstallapps frameworkaltinstallunixtools" +# Keep a trace of the command line. +# Strip out --no-create and --no-recursion so they do not pile up. +# Strip out --silent because we don't want to record it for future runs. +# Also quote any args containing shell meta-characters. +# Make two passes to allow for proper duplicate-argument suppression. +ac_configure_args= +ac_configure_args0= +ac_configure_args1= +ac_must_keep_next=false +for ac_pass in 1 2 +do + for ac_arg + do + case $ac_arg in + -no-create | --no-c* | -n | -no-recursion | --no-r*) continue ;; + -q | -quiet | --quiet | --quie | --qui | --qu | --q \ + | -silent | --silent | --silen | --sile | --sil) + continue ;; + *\'*) + ac_arg=`$as_echo "$ac_arg" | sed "s/'/'\\\\\\\\''/g"` ;; + esac + case $ac_pass in + 1) as_fn_append ac_configure_args0 " '$ac_arg'" ;; + 2) + as_fn_append ac_configure_args1 " '$ac_arg'" + if test $ac_must_keep_next = true; then + ac_must_keep_next=false # Got value, back to normal. + else + case $ac_arg in + *=* | --config-cache | -C | -disable-* | --disable-* \ + | -enable-* | --enable-* | -gas | --g* | -nfp | --nf* \ + | -q | -quiet | --q* | -silent | --sil* | -v | -verb* \ + | -with-* | --with-* | -without-* | --without-* | --x) + case "$ac_configure_args0 " in + "$ac_configure_args1"*" '$ac_arg' "* ) continue ;; + esac + ;; + -* ) ac_must_keep_next=true ;; + esac + fi + as_fn_append ac_configure_args " '$ac_arg'" + ;; + esac + done +done +{ ac_configure_args0=; unset ac_configure_args0;} +{ ac_configure_args1=; unset ac_configure_args1;} - if test "x${prefix}" = "xNONE" ; then - FRAMEWORKUNIXTOOLSPREFIX="${ac_default_prefix}" - else - FRAMEWORKUNIXTOOLSPREFIX="${prefix}" - fi - prefix=$PYTHONFRAMEWORKINSTALLDIR/Versions/$VERSION +# When interrupted or exit'd, cleanup temporary files, and complete +# config.log. We remove comments because anyway the quotes in there +# would cause problems or look ugly. +# WARNING: Use '\'' to represent an apostrophe within the trap. +# WARNING: Do not start the trap code with a newline, due to a FreeBSD 4.0 bug. +trap 'exit_status=$? + # Save into config.log some information that might help in debugging. + { + echo - # Add files for Mac specific code to the list of output - # files: - ac_config_files="$ac_config_files Mac/Makefile" + cat <<\_ASBOX +## ---------------- ## +## Cache variables. ## +## ---------------- ## +_ASBOX + echo + # The following way of writing the cache mishandles newlines in values, +( + for ac_var in `(set) 2>&1 | sed -n '\''s/^\([a-zA-Z_][a-zA-Z0-9_]*\)=.*/\1/p'\''`; do + eval ac_val=\$$ac_var + case $ac_val in #( + *${as_nl}*) + case $ac_var in #( + *_cv_*) { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: cache variable $ac_var contains a newline" >&5 +$as_echo "$as_me: WARNING: cache variable $ac_var contains a newline" >&2;} ;; + esac + case $ac_var in #( + _ | IFS | as_nl) ;; #( + BASH_ARGV | BASH_SOURCE) eval $ac_var= ;; #( + *) { eval $ac_var=; unset $ac_var;} ;; + esac ;; + esac + done + (set) 2>&1 | + case $as_nl`(ac_space='\'' '\''; set) 2>&1` in #( + *${as_nl}ac_space=\ *) + sed -n \ + "s/'\''/'\''\\\\'\'''\''/g; + s/^\\([_$as_cr_alnum]*_cv_[_$as_cr_alnum]*\\)=\\(.*\\)/\\1='\''\\2'\''/p" + ;; #( + *) + sed -n "/^[_$as_cr_alnum]*_cv_[_$as_cr_alnum]*=/p" + ;; + esac | + sort +) + echo - ac_config_files="$ac_config_files Mac/PythonLauncher/Makefile" + cat <<\_ASBOX +## ----------------- ## +## Output variables. ## +## ----------------- ## +_ASBOX + echo + for ac_var in $ac_subst_vars + do + eval ac_val=\$$ac_var + case $ac_val in + *\'\''*) ac_val=`$as_echo "$ac_val" | sed "s/'\''/'\''\\\\\\\\'\'''\''/g"`;; + esac + $as_echo "$ac_var='\''$ac_val'\''" + done | sort + echo - ac_config_files="$ac_config_files Mac/Resources/framework/Info.plist" + if test -n "$ac_subst_files"; then + cat <<\_ASBOX +## ------------------- ## +## File substitutions. ## +## ------------------- ## +_ASBOX + echo + for ac_var in $ac_subst_files + do + eval ac_val=\$$ac_var + case $ac_val in + *\'\''*) ac_val=`$as_echo "$ac_val" | sed "s/'\''/'\''\\\\\\\\'\'''\''/g"`;; + esac + $as_echo "$ac_var='\''$ac_val'\''" + done | sort + echo + fi - ac_config_files="$ac_config_files Mac/Resources/app/Info.plist" + if test -s confdefs.h; then + cat <<\_ASBOX +## ----------- ## +## confdefs.h. ## +## ----------- ## +_ASBOX + echo + cat confdefs.h + echo + fi + test "$ac_signal" != 0 && + $as_echo "$as_me: caught signal $ac_signal" + $as_echo "$as_me: exit $exit_status" + } >&5 + rm -f core *.core core.conftest.* && + rm -f -r conftest* confdefs* conf$$* $ac_clean_files && + exit $exit_status +' 0 +for ac_signal in 1 2 13 15; do + trap 'ac_signal='$ac_signal'; as_fn_exit 1' $ac_signal +done +ac_signal=0 - esac +# confdefs.h avoids OS command line length limits that DEFS can exceed. +rm -f -r conftest* confdefs.h -else +$as_echo "/* confdefs.h */" > confdefs.h - PYTHONFRAMEWORK= - PYTHONFRAMEWORKDIR=no-framework - PYTHONFRAMEWORKPREFIX= - PYTHONFRAMEWORKINSTALLDIR= - FRAMEWORKINSTALLFIRST= - FRAMEWORKINSTALLLAST= - FRAMEWORKALTINSTALLFIRST= - FRAMEWORKALTINSTALLLAST= - if test "x${prefix}" = "xNONE" ; then - FRAMEWORKUNIXTOOLSPREFIX="${ac_default_prefix}" - else - FRAMEWORKUNIXTOOLSPREFIX="${prefix}" - fi - enable_framework= +# Predefined preprocessor variables. +cat >>confdefs.h <<_ACEOF +#define PACKAGE_NAME "$PACKAGE_NAME" +_ACEOF -fi +cat >>confdefs.h <<_ACEOF +#define PACKAGE_TARNAME "$PACKAGE_TARNAME" +_ACEOF +cat >>confdefs.h <<_ACEOF +#define PACKAGE_VERSION "$PACKAGE_VERSION" +_ACEOF +cat >>confdefs.h <<_ACEOF +#define PACKAGE_STRING "$PACKAGE_STRING" +_ACEOF +cat >>confdefs.h <<_ACEOF +#define PACKAGE_BUGREPORT "$PACKAGE_BUGREPORT" +_ACEOF +cat >>confdefs.h <<_ACEOF +#define PACKAGE_URL "$PACKAGE_URL" +_ACEOF +# Let the site file select an alternate cache file if it wants to. +# Prefer an explicitly selected file to automatically selected ones. +ac_site_file1=NONE +ac_site_file2=NONE +if test -n "$CONFIG_SITE"; then + ac_site_file1=$CONFIG_SITE +elif test "x$prefix" != xNONE; then + ac_site_file1=$prefix/share/config.site + ac_site_file2=$prefix/etc/config.site +else + ac_site_file1=$ac_default_prefix/share/config.site + ac_site_file2=$ac_default_prefix/etc/config.site +fi +for ac_site_file in "$ac_site_file1" "$ac_site_file2" +do + test "x$ac_site_file" = xNONE && continue + if test /dev/null != "$ac_site_file" && test -r "$ac_site_file"; then + { $as_echo "$as_me:${as_lineno-$LINENO}: loading site script $ac_site_file" >&5 +$as_echo "$as_me: loading site script $ac_site_file" >&6;} + sed 's/^/| /' "$ac_site_file" >&5 + . "$ac_site_file" + fi +done +if test -r "$cache_file"; then + # Some versions of bash will fail to source /dev/null (special files + # actually), so we avoid doing that. DJGPP emulates it as a regular file. + if test /dev/null != "$cache_file" && test -f "$cache_file"; then + { $as_echo "$as_me:${as_lineno-$LINENO}: loading cache $cache_file" >&5 +$as_echo "$as_me: loading cache $cache_file" >&6;} + case $cache_file in + [\\/]* | ?:[\\/]* ) . "$cache_file";; + *) . "./$cache_file";; + esac + fi +else + { $as_echo "$as_me:${as_lineno-$LINENO}: creating cache $cache_file" >&5 +$as_echo "$as_me: creating cache $cache_file" >&6;} + >$cache_file +fi +# Check that the precious variables saved in the cache have kept the same +# value. +ac_cache_corrupted=false +for ac_var in $ac_precious_vars; do + eval ac_old_set=\$ac_cv_env_${ac_var}_set + eval ac_new_set=\$ac_env_${ac_var}_set + eval ac_old_val=\$ac_cv_env_${ac_var}_value + eval ac_new_val=\$ac_env_${ac_var}_value + case $ac_old_set,$ac_new_set in + set,) + { $as_echo "$as_me:${as_lineno-$LINENO}: error: \`$ac_var' was set to \`$ac_old_val' in the previous run" >&5 +$as_echo "$as_me: error: \`$ac_var' was set to \`$ac_old_val' in the previous run" >&2;} + ac_cache_corrupted=: ;; + ,set) + { $as_echo "$as_me:${as_lineno-$LINENO}: error: \`$ac_var' was not set in the previous run" >&5 +$as_echo "$as_me: error: \`$ac_var' was not set in the previous run" >&2;} + ac_cache_corrupted=: ;; + ,);; + *) + if test "x$ac_old_val" != "x$ac_new_val"; then + # differences in whitespace do not lead to failure. + ac_old_val_w=`echo x $ac_old_val` + ac_new_val_w=`echo x $ac_new_val` + if test "$ac_old_val_w" != "$ac_new_val_w"; then + { $as_echo "$as_me:${as_lineno-$LINENO}: error: \`$ac_var' has changed since the previous run:" >&5 +$as_echo "$as_me: error: \`$ac_var' has changed since the previous run:" >&2;} + ac_cache_corrupted=: + else + { $as_echo "$as_me:${as_lineno-$LINENO}: warning: ignoring whitespace changes in \`$ac_var' since the previous run:" >&5 +$as_echo "$as_me: warning: ignoring whitespace changes in \`$ac_var' since the previous run:" >&2;} + eval $ac_var=\$ac_old_val + fi + { $as_echo "$as_me:${as_lineno-$LINENO}: former value: \`$ac_old_val'" >&5 +$as_echo "$as_me: former value: \`$ac_old_val'" >&2;} + { $as_echo "$as_me:${as_lineno-$LINENO}: current value: \`$ac_new_val'" >&5 +$as_echo "$as_me: current value: \`$ac_new_val'" >&2;} + fi;; + esac + # Pass precious variables to config.status. + if test "$ac_new_set" = set; then + case $ac_new_val in + *\'*) ac_arg=$ac_var=`$as_echo "$ac_new_val" | sed "s/'/'\\\\\\\\''/g"` ;; + *) ac_arg=$ac_var=$ac_new_val ;; + esac + case " $ac_configure_args " in + *" '$ac_arg' "*) ;; # Avoid dups. Use of quotes ensures accuracy. + *) as_fn_append ac_configure_args " '$ac_arg'" ;; + esac + fi +done +if $ac_cache_corrupted; then + { $as_echo "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5 +$as_echo "$as_me: error: in \`$ac_pwd':" >&2;} + { $as_echo "$as_me:${as_lineno-$LINENO}: error: changes in the environment can compromise the build" >&5 +$as_echo "$as_me: error: changes in the environment can compromise the build" >&2;} + as_fn_error "run \`make distclean' and/or \`rm $cache_file' and start over" "$LINENO" 5 +fi +## -------------------- ## +## Main body of script. ## +## -------------------- ## +ac_ext=c +ac_cpp='$CPP $CPPFLAGS' +ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5' +ac_link='$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5' +ac_compiler_gnu=$ac_cv_c_compiler_gnu -##AC_ARG_WITH(dyld, -## AC_HELP_STRING(--with-dyld, -## Use (OpenStep|Rhapsody) dynamic linker)) -## -# Set name for machine-dependent library files +ac_config_headers="$ac_config_headers pyconfig.h" -{ echo "$as_me:$LINENO: checking MACHDEP" >&5 -echo $ECHO_N "checking MACHDEP... $ECHO_C" >&6; } -if test -z "$MACHDEP" -then - ac_sys_system=`uname -s` - if test "$ac_sys_system" = "AIX" \ - -o "$ac_sys_system" = "UnixWare" -o "$ac_sys_system" = "OpenUNIX"; then - ac_sys_release=`uname -v` + + +if test "$prefix" != "/"; then + prefix=`echo "$prefix" | sed -e 's/\/$//g'` +fi + + + + +# We don't use PACKAGE_ variables, and they cause conflicts +# with other autoconf-based packages that include Python.h +grep -v 'define PACKAGE_' confdefs.h.new +rm confdefs.h +mv confdefs.h.new confdefs.h + + +VERSION=3.2 + + +SOVERSION=1.0 + +# The later defininition of _XOPEN_SOURCE disables certain features +# on Linux, so we need _GNU_SOURCE to re-enable them (makedev, tm_zone). + +$as_echo "#define _GNU_SOURCE 1" >>confdefs.h + + +# The later defininition of _XOPEN_SOURCE and _POSIX_C_SOURCE disables +# certain features on NetBSD, so we need _NETBSD_SOURCE to re-enable +# them. + +$as_echo "#define _NETBSD_SOURCE 1" >>confdefs.h + + +# The later defininition of _XOPEN_SOURCE and _POSIX_C_SOURCE disables +# certain features on FreeBSD, so we need __BSD_VISIBLE to re-enable +# them. + +$as_echo "#define __BSD_VISIBLE 1" >>confdefs.h + + +# The later defininition of _XOPEN_SOURCE and _POSIX_C_SOURCE disables +# u_int on Irix 5.3. Defining _BSD_TYPES brings it back. + +$as_echo "#define _BSD_TYPES 1" >>confdefs.h + + +# The later defininition of _XOPEN_SOURCE and _POSIX_C_SOURCE disables +# certain features on Mac OS X, so we need _DARWIN_C_SOURCE to re-enable +# them. + +$as_echo "#define _DARWIN_C_SOURCE 1" >>confdefs.h + + + +define_xopen_source=yes + +# Arguments passed to configure. + +CONFIG_ARGS="$ac_configure_args" + +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for --enable-universalsdk" >&5 +$as_echo_n "checking for --enable-universalsdk... " >&6; } +# Check whether --enable-universalsdk was given. +if test "${enable_universalsdk+set}" = set; then : + enableval=$enable_universalsdk; + case $enableval in + yes) + enableval=/Developer/SDKs/MacOSX10.4u.sdk + if test ! -d "${enableval}" + then + enableval=/ + fi + ;; + esac + case $enableval in + no) + UNIVERSALSDK= + enable_universalsdk= + ;; + *) + UNIVERSALSDK=$enableval + if test ! -d "${UNIVERSALSDK}" + then + as_fn_error "--enable-universalsdk specifies non-existing SDK: ${UNIVERSALSDK}" "$LINENO" 5 + fi + ;; + esac + + +else + + UNIVERSALSDK= + enable_universalsdk= + +fi + +if test -n "${UNIVERSALSDK}" +then + { $as_echo "$as_me:${as_lineno-$LINENO}: result: ${UNIVERSALSDK}" >&5 +$as_echo "${UNIVERSALSDK}" >&6; } +else + { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 +$as_echo "no" >&6; } +fi + + + + +UNIVERSAL_ARCHS="32-bit" + +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for --with-universal-archs" >&5 +$as_echo_n "checking for --with-universal-archs... " >&6; } + +# Check whether --with-universal-archs was given. +if test "${with_universal_archs+set}" = set; then : + withval=$with_universal_archs; + { $as_echo "$as_me:${as_lineno-$LINENO}: result: $withval" >&5 +$as_echo "$withval" >&6; } + UNIVERSAL_ARCHS="$withval" + +else + + { $as_echo "$as_me:${as_lineno-$LINENO}: result: 32-bit" >&5 +$as_echo "32-bit" >&6; } + +fi + + + + + +# Check whether --with-framework-name was given. +if test "${with_framework_name+set}" = set; then : + withval=$with_framework_name; + PYTHONFRAMEWORK=${withval} + PYTHONFRAMEWORKDIR=${withval}.framework + PYTHONFRAMEWORKIDENTIFIER=org.python.`echo $withval | tr 'A-Z' 'a-z'` + +else + + PYTHONFRAMEWORK=Python + PYTHONFRAMEWORKDIR=Python.framework + PYTHONFRAMEWORKIDENTIFIER=org.python.python + +fi + +# Check whether --enable-framework was given. +if test "${enable_framework+set}" = set; then : + enableval=$enable_framework; + case $enableval in + yes) + enableval=/Library/Frameworks + esac + case $enableval in + no) + PYTHONFRAMEWORK= + PYTHONFRAMEWORKDIR=no-framework + PYTHONFRAMEWORKPREFIX= + PYTHONFRAMEWORKINSTALLDIR= + FRAMEWORKINSTALLFIRST= + FRAMEWORKINSTALLLAST= + FRAMEWORKALTINSTALLFIRST= + FRAMEWORKALTINSTALLLAST= + if test "x${prefix}" = "xNONE"; then + FRAMEWORKUNIXTOOLSPREFIX="${ac_default_prefix}" + else + FRAMEWORKUNIXTOOLSPREFIX="${prefix}" + fi + enable_framework= + ;; + *) + PYTHONFRAMEWORKPREFIX="${enableval}" + PYTHONFRAMEWORKINSTALLDIR=$PYTHONFRAMEWORKPREFIX/$PYTHONFRAMEWORKDIR + FRAMEWORKINSTALLFIRST="frameworkinstallstructure" + FRAMEWORKALTINSTALLFIRST="frameworkinstallstructure " + FRAMEWORKINSTALLLAST="frameworkinstallmaclib frameworkinstallapps frameworkinstallunixtools" + FRAMEWORKALTINSTALLLAST="frameworkinstallmaclib frameworkinstallapps frameworkaltinstallunixtools" + FRAMEWORKINSTALLAPPSPREFIX="/Applications" + + if test "x${prefix}" = "xNONE" ; then + FRAMEWORKUNIXTOOLSPREFIX="${ac_default_prefix}" + + else + FRAMEWORKUNIXTOOLSPREFIX="${prefix}" + fi + + case "${enableval}" in + /System*) + FRAMEWORKINSTALLAPPSPREFIX="/Applications" + if test "${prefix}" = "NONE" ; then + # See below + FRAMEWORKUNIXTOOLSPREFIX="/usr" + fi + ;; + + /Library*) + FRAMEWORKINSTALLAPPSPREFIX="/Applications" + ;; + + */Library/Frameworks) + MDIR="`dirname "${enableval}"`" + MDIR="`dirname "${MDIR}"`" + FRAMEWORKINSTALLAPPSPREFIX="${MDIR}/Applications" + + if test "${prefix}" = "NONE"; then + # User hasn't specified the + # --prefix option, but wants to install + # the framework in a non-default location, + # ensure that the compatibility links get + # installed relative to that prefix as well + # instead of in /usr/local. + FRAMEWORKUNIXTOOLSPREFIX="${MDIR}" + fi + ;; + + *) + FRAMEWORKINSTALLAPPSPREFIX="/Applications" + ;; + esac + + prefix=$PYTHONFRAMEWORKINSTALLDIR/Versions/$VERSION + + # Add files for Mac specific code to the list of output + # files: + ac_config_files="$ac_config_files Mac/Makefile" + + ac_config_files="$ac_config_files Mac/PythonLauncher/Makefile" + + ac_config_files="$ac_config_files Mac/Resources/framework/Info.plist" + + ac_config_files="$ac_config_files Mac/Resources/app/Info.plist" + + esac + +else + + PYTHONFRAMEWORK= + PYTHONFRAMEWORKDIR=no-framework + PYTHONFRAMEWORKPREFIX= + PYTHONFRAMEWORKINSTALLDIR= + FRAMEWORKINSTALLFIRST= + FRAMEWORKINSTALLLAST= + FRAMEWORKALTINSTALLFIRST= + FRAMEWORKALTINSTALLLAST= + if test "x${prefix}" = "xNONE" ; then + FRAMEWORKUNIXTOOLSPREFIX="${ac_default_prefix}" + else + FRAMEWORKUNIXTOOLSPREFIX="${prefix}" + fi + enable_framework= + + +fi + + + + + + + + + + + + + +##AC_ARG_WITH(dyld, +## AS_HELP_STRING([--with-dyld], +## [Use (OpenStep|Rhapsody) dynamic linker])) +## +# Set name for machine-dependent library files + +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking MACHDEP" >&5 +$as_echo_n "checking MACHDEP... " >&6; } +if test -z "$MACHDEP" +then + ac_sys_system=`uname -s` + if test "$ac_sys_system" = "AIX" \ + -o "$ac_sys_system" = "UnixWare" -o "$ac_sys_system" = "OpenUNIX"; then + ac_sys_release=`uname -v` else ac_sys_release=`uname -r` fi @@ -2109,9 +2997,7 @@ # also defined. This can be overridden by defining _BSD_SOURCE # As this has a different meaning on Linux, only define it on OpenBSD -cat >>confdefs.h <<\_ACEOF -#define _BSD_SOURCE 1 -_ACEOF +$as_echo "#define _BSD_SOURCE 1" >>confdefs.h ;; OpenBSD/4.[789]) @@ -2119,9 +3005,7 @@ # also defined. This can be overridden by defining _BSD_SOURCE # As this has a different meaning on Linux, only define it on OpenBSD -cat >>confdefs.h <<\_ACEOF -#define _BSD_SOURCE 1 -_ACEOF +$as_echo "#define _BSD_SOURCE 1" >>confdefs.h ;; # Defining _XOPEN_SOURCE on NetBSD version prior to the introduction of @@ -2184,16 +3068,12 @@ case $ac_sys_system/$ac_sys_release in SunOS/5.8|SunOS/5.9|SunOS/5.10) -cat >>confdefs.h <<\_ACEOF -#define _XOPEN_SOURCE 500 -_ACEOF +$as_echo "#define _XOPEN_SOURCE 500" >>confdefs.h ;; *) -cat >>confdefs.h <<\_ACEOF -#define _XOPEN_SOURCE 600 -_ACEOF +$as_echo "#define _XOPEN_SOURCE 600" >>confdefs.h ;; esac @@ -2209,17 +3089,13 @@ ;; *) -cat >>confdefs.h <<\_ACEOF -#define _XOPEN_SOURCE_EXTENDED 1 -_ACEOF +$as_echo "#define _XOPEN_SOURCE_EXTENDED 1" >>confdefs.h ;; esac -cat >>confdefs.h <<\_ACEOF -#define _POSIX_C_SOURCE 200112L -_ACEOF +$as_echo "#define _POSIX_C_SOURCE 200112L" >>confdefs.h fi @@ -2240,8 +3116,8 @@ LDFLAGS="$SGI_ABI $LDFLAGS" MACHDEP=`echo "${MACHDEP}${SGI_ABI}" | sed 's/ *//g'` fi -{ echo "$as_me:$LINENO: result: $MACHDEP" >&5 -echo "${ECHO_T}$MACHDEP" >&6; } +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $MACHDEP" >&5 +$as_echo "$MACHDEP" >&6; } # Record the configure-time value of MACOSX_DEPLOYMENT_TARGET, # it may influence the way we can build extensions, so distutils @@ -2251,11 +3127,11 @@ CONFIGURE_MACOSX_DEPLOYMENT_TARGET= EXPORT_MACOSX_DEPLOYMENT_TARGET='#' -{ echo "$as_me:$LINENO: checking machine type as reported by uname -m" >&5 -echo $ECHO_N "checking machine type as reported by uname -m... $ECHO_C" >&6; } +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking machine type as reported by uname -m" >&5 +$as_echo_n "checking machine type as reported by uname -m... " >&6; } ac_sys_machine=`uname -m` -{ echo "$as_me:$LINENO: result: $ac_sys_machine" >&5 -echo "${ECHO_T}$ac_sys_machine" >&6; } +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_sys_machine" >&5 +$as_echo "$ac_sys_machine" >&6; } # checks for alternative programs @@ -2267,11 +3143,11 @@ # XXX shouldn't some/most/all of this code be merged with the stuff later # on that fiddles with OPT and BASECFLAGS? -{ echo "$as_me:$LINENO: checking for --without-gcc" >&5 -echo $ECHO_N "checking for --without-gcc... $ECHO_C" >&6; } +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for --without-gcc" >&5 +$as_echo_n "checking for --without-gcc... " >&6; } # Check whether --with-gcc was given. -if test "${with_gcc+set}" = set; then +if test "${with_gcc+set}" = set; then : withval=$with_gcc; case $withval in no) CC=${CC:-cc} @@ -2290,20 +3166,19 @@ esac fi -{ echo "$as_me:$LINENO: result: $without_gcc" >&5 -echo "${ECHO_T}$without_gcc" >&6; } +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $without_gcc" >&5 +$as_echo "$without_gcc" >&6; } # If the user switches compilers, we can't believe the cache if test ! -z "$ac_cv_prog_CC" -a ! -z "$CC" -a "$CC" != "$ac_cv_prog_CC" then - { { echo "$as_me:$LINENO: error: cached CC is different -- throw away $cache_file -(it is also a good idea to do 'make clean' before compiling)" >&5 -echo "$as_me: error: cached CC is different -- throw away $cache_file -(it is also a good idea to do 'make clean' before compiling)" >&2;} - { (exit 1); exit 1; }; } + as_fn_error "cached CC is different -- throw away $cache_file +(it is also a good idea to do 'make clean' before compiling)" "$LINENO" 5 fi -save_CFLAGS=$CFLAGS +# If the user set CFLAGS, use this instead of the automatically +# determined setting +preset_cflags="$CFLAGS" ac_ext=c ac_cpp='$CPP $CPPFLAGS' ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5' @@ -2312,10 +3187,10 @@ if test -n "$ac_tool_prefix"; then # Extract the first word of "${ac_tool_prefix}gcc", so it can be a program name with args. set dummy ${ac_tool_prefix}gcc; ac_word=$2 -{ echo "$as_me:$LINENO: checking for $ac_word" >&5 -echo $ECHO_N "checking for $ac_word... $ECHO_C" >&6; } -if test "${ac_cv_prog_CC+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 +$as_echo_n "checking for $ac_word... " >&6; } +if test "${ac_cv_prog_CC+set}" = set; then : + $as_echo_n "(cached) " >&6 else if test -n "$CC"; then ac_cv_prog_CC="$CC" # Let the user override the test. @@ -2325,25 +3200,25 @@ do IFS=$as_save_IFS test -z "$as_dir" && as_dir=. - for ac_exec_ext in '' $ac_executable_extensions; do + for ac_exec_ext in '' $ac_executable_extensions; do if { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_test_x "$as_dir/$ac_word$ac_exec_ext"; }; then ac_cv_prog_CC="${ac_tool_prefix}gcc" - echo "$as_me:$LINENO: found $as_dir/$ac_word$ac_exec_ext" >&5 + $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 break 2 fi done -done + done IFS=$as_save_IFS fi fi CC=$ac_cv_prog_CC if test -n "$CC"; then - { echo "$as_me:$LINENO: result: $CC" >&5 -echo "${ECHO_T}$CC" >&6; } + { $as_echo "$as_me:${as_lineno-$LINENO}: result: $CC" >&5 +$as_echo "$CC" >&6; } else - { echo "$as_me:$LINENO: result: no" >&5 -echo "${ECHO_T}no" >&6; } + { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 +$as_echo "no" >&6; } fi @@ -2352,10 +3227,10 @@ ac_ct_CC=$CC # Extract the first word of "gcc", so it can be a program name with args. set dummy gcc; ac_word=$2 -{ echo "$as_me:$LINENO: checking for $ac_word" >&5 -echo $ECHO_N "checking for $ac_word... $ECHO_C" >&6; } -if test "${ac_cv_prog_ac_ct_CC+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 +$as_echo_n "checking for $ac_word... " >&6; } +if test "${ac_cv_prog_ac_ct_CC+set}" = set; then : + $as_echo_n "(cached) " >&6 else if test -n "$ac_ct_CC"; then ac_cv_prog_ac_ct_CC="$ac_ct_CC" # Let the user override the test. @@ -2365,25 +3240,25 @@ do IFS=$as_save_IFS test -z "$as_dir" && as_dir=. - for ac_exec_ext in '' $ac_executable_extensions; do + for ac_exec_ext in '' $ac_executable_extensions; do if { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_test_x "$as_dir/$ac_word$ac_exec_ext"; }; then ac_cv_prog_ac_ct_CC="gcc" - echo "$as_me:$LINENO: found $as_dir/$ac_word$ac_exec_ext" >&5 + $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 break 2 fi done -done + done IFS=$as_save_IFS fi fi ac_ct_CC=$ac_cv_prog_ac_ct_CC if test -n "$ac_ct_CC"; then - { echo "$as_me:$LINENO: result: $ac_ct_CC" >&5 -echo "${ECHO_T}$ac_ct_CC" >&6; } + { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_ct_CC" >&5 +$as_echo "$ac_ct_CC" >&6; } else - { echo "$as_me:$LINENO: result: no" >&5 -echo "${ECHO_T}no" >&6; } + { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 +$as_echo "no" >&6; } fi if test "x$ac_ct_CC" = x; then @@ -2391,12 +3266,8 @@ else case $cross_compiling:$ac_tool_warned in yes:) -{ echo "$as_me:$LINENO: WARNING: In the future, Autoconf will not detect cross-tools -whose name does not start with the host triplet. If you think this -configuration is useful to you, please write to autoconf at gnu.org." >&5 -echo "$as_me: WARNING: In the future, Autoconf will not detect cross-tools -whose name does not start with the host triplet. If you think this -configuration is useful to you, please write to autoconf at gnu.org." >&2;} +{ $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: using cross tools not prefixed with host triplet" >&5 +$as_echo "$as_me: WARNING: using cross tools not prefixed with host triplet" >&2;} ac_tool_warned=yes ;; esac CC=$ac_ct_CC @@ -2409,10 +3280,10 @@ if test -n "$ac_tool_prefix"; then # Extract the first word of "${ac_tool_prefix}cc", so it can be a program name with args. set dummy ${ac_tool_prefix}cc; ac_word=$2 -{ echo "$as_me:$LINENO: checking for $ac_word" >&5 -echo $ECHO_N "checking for $ac_word... $ECHO_C" >&6; } -if test "${ac_cv_prog_CC+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 +$as_echo_n "checking for $ac_word... " >&6; } +if test "${ac_cv_prog_CC+set}" = set; then : + $as_echo_n "(cached) " >&6 else if test -n "$CC"; then ac_cv_prog_CC="$CC" # Let the user override the test. @@ -2422,25 +3293,25 @@ do IFS=$as_save_IFS test -z "$as_dir" && as_dir=. - for ac_exec_ext in '' $ac_executable_extensions; do + for ac_exec_ext in '' $ac_executable_extensions; do if { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_test_x "$as_dir/$ac_word$ac_exec_ext"; }; then ac_cv_prog_CC="${ac_tool_prefix}cc" - echo "$as_me:$LINENO: found $as_dir/$ac_word$ac_exec_ext" >&5 + $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 break 2 fi done -done + done IFS=$as_save_IFS fi fi CC=$ac_cv_prog_CC if test -n "$CC"; then - { echo "$as_me:$LINENO: result: $CC" >&5 -echo "${ECHO_T}$CC" >&6; } + { $as_echo "$as_me:${as_lineno-$LINENO}: result: $CC" >&5 +$as_echo "$CC" >&6; } else - { echo "$as_me:$LINENO: result: no" >&5 -echo "${ECHO_T}no" >&6; } + { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 +$as_echo "no" >&6; } fi @@ -2449,10 +3320,10 @@ if test -z "$CC"; then # Extract the first word of "cc", so it can be a program name with args. set dummy cc; ac_word=$2 -{ echo "$as_me:$LINENO: checking for $ac_word" >&5 -echo $ECHO_N "checking for $ac_word... $ECHO_C" >&6; } -if test "${ac_cv_prog_CC+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 +$as_echo_n "checking for $ac_word... " >&6; } +if test "${ac_cv_prog_CC+set}" = set; then : + $as_echo_n "(cached) " >&6 else if test -n "$CC"; then ac_cv_prog_CC="$CC" # Let the user override the test. @@ -2463,18 +3334,18 @@ do IFS=$as_save_IFS test -z "$as_dir" && as_dir=. - for ac_exec_ext in '' $ac_executable_extensions; do + for ac_exec_ext in '' $ac_executable_extensions; do if { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_test_x "$as_dir/$ac_word$ac_exec_ext"; }; then if test "$as_dir/$ac_word$ac_exec_ext" = "/usr/ucb/cc"; then ac_prog_rejected=yes continue fi ac_cv_prog_CC="cc" - echo "$as_me:$LINENO: found $as_dir/$ac_word$ac_exec_ext" >&5 + $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 break 2 fi done -done + done IFS=$as_save_IFS if test $ac_prog_rejected = yes; then @@ -2493,11 +3364,11 @@ fi CC=$ac_cv_prog_CC if test -n "$CC"; then - { echo "$as_me:$LINENO: result: $CC" >&5 -echo "${ECHO_T}$CC" >&6; } + { $as_echo "$as_me:${as_lineno-$LINENO}: result: $CC" >&5 +$as_echo "$CC" >&6; } else - { echo "$as_me:$LINENO: result: no" >&5 -echo "${ECHO_T}no" >&6; } + { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 +$as_echo "no" >&6; } fi @@ -2508,10 +3379,10 @@ do # Extract the first word of "$ac_tool_prefix$ac_prog", so it can be a program name with args. set dummy $ac_tool_prefix$ac_prog; ac_word=$2 -{ echo "$as_me:$LINENO: checking for $ac_word" >&5 -echo $ECHO_N "checking for $ac_word... $ECHO_C" >&6; } -if test "${ac_cv_prog_CC+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 +$as_echo_n "checking for $ac_word... " >&6; } +if test "${ac_cv_prog_CC+set}" = set; then : + $as_echo_n "(cached) " >&6 else if test -n "$CC"; then ac_cv_prog_CC="$CC" # Let the user override the test. @@ -2521,25 +3392,25 @@ do IFS=$as_save_IFS test -z "$as_dir" && as_dir=. - for ac_exec_ext in '' $ac_executable_extensions; do + for ac_exec_ext in '' $ac_executable_extensions; do if { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_test_x "$as_dir/$ac_word$ac_exec_ext"; }; then ac_cv_prog_CC="$ac_tool_prefix$ac_prog" - echo "$as_me:$LINENO: found $as_dir/$ac_word$ac_exec_ext" >&5 + $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 break 2 fi done -done + done IFS=$as_save_IFS fi fi CC=$ac_cv_prog_CC if test -n "$CC"; then - { echo "$as_me:$LINENO: result: $CC" >&5 -echo "${ECHO_T}$CC" >&6; } + { $as_echo "$as_me:${as_lineno-$LINENO}: result: $CC" >&5 +$as_echo "$CC" >&6; } else - { echo "$as_me:$LINENO: result: no" >&5 -echo "${ECHO_T}no" >&6; } + { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 +$as_echo "no" >&6; } fi @@ -2552,10 +3423,10 @@ do # Extract the first word of "$ac_prog", so it can be a program name with args. set dummy $ac_prog; ac_word=$2 -{ echo "$as_me:$LINENO: checking for $ac_word" >&5 -echo $ECHO_N "checking for $ac_word... $ECHO_C" >&6; } -if test "${ac_cv_prog_ac_ct_CC+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 +$as_echo_n "checking for $ac_word... " >&6; } +if test "${ac_cv_prog_ac_ct_CC+set}" = set; then : + $as_echo_n "(cached) " >&6 else if test -n "$ac_ct_CC"; then ac_cv_prog_ac_ct_CC="$ac_ct_CC" # Let the user override the test. @@ -2565,25 +3436,25 @@ do IFS=$as_save_IFS test -z "$as_dir" && as_dir=. - for ac_exec_ext in '' $ac_executable_extensions; do + for ac_exec_ext in '' $ac_executable_extensions; do if { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_test_x "$as_dir/$ac_word$ac_exec_ext"; }; then ac_cv_prog_ac_ct_CC="$ac_prog" - echo "$as_me:$LINENO: found $as_dir/$ac_word$ac_exec_ext" >&5 + $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 break 2 fi done -done + done IFS=$as_save_IFS fi fi ac_ct_CC=$ac_cv_prog_ac_ct_CC if test -n "$ac_ct_CC"; then - { echo "$as_me:$LINENO: result: $ac_ct_CC" >&5 -echo "${ECHO_T}$ac_ct_CC" >&6; } + { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_ct_CC" >&5 +$as_echo "$ac_ct_CC" >&6; } else - { echo "$as_me:$LINENO: result: no" >&5 -echo "${ECHO_T}no" >&6; } + { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 +$as_echo "no" >&6; } fi @@ -2595,12 +3466,8 @@ else case $cross_compiling:$ac_tool_warned in yes:) -{ echo "$as_me:$LINENO: WARNING: In the future, Autoconf will not detect cross-tools -whose name does not start with the host triplet. If you think this -configuration is useful to you, please write to autoconf at gnu.org." >&5 -echo "$as_me: WARNING: In the future, Autoconf will not detect cross-tools -whose name does not start with the host triplet. If you think this -configuration is useful to you, please write to autoconf at gnu.org." >&2;} +{ $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: using cross tools not prefixed with host triplet" >&5 +$as_echo "$as_me: WARNING: using cross tools not prefixed with host triplet" >&2;} ac_tool_warned=yes ;; esac CC=$ac_ct_CC @@ -2610,51 +3477,37 @@ fi -test -z "$CC" && { { echo "$as_me:$LINENO: error: no acceptable C compiler found in \$PATH -See \`config.log' for more details." >&5 -echo "$as_me: error: no acceptable C compiler found in \$PATH -See \`config.log' for more details." >&2;} - { (exit 1); exit 1; }; } +test -z "$CC" && { { $as_echo "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5 +$as_echo "$as_me: error: in \`$ac_pwd':" >&2;} +as_fn_error "no acceptable C compiler found in \$PATH +See \`config.log' for more details." "$LINENO" 5; } # Provide some information about the compiler. -echo "$as_me:$LINENO: checking for C compiler version" >&5 -ac_compiler=`set X $ac_compile; echo $2` -{ (ac_try="$ac_compiler --version >&5" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_compiler --version >&5") 2>&5 - ac_status=$? - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } -{ (ac_try="$ac_compiler -v >&5" +$as_echo "$as_me:${as_lineno-$LINENO}: checking for C compiler version" >&5 +set X $ac_compile +ac_compiler=$2 +for ac_option in --version -v -V -qversion; do + { { ac_try="$ac_compiler $ac_option >&5" case "(($ac_try" in *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_compiler -v >&5") 2>&5 +eval ac_try_echo="\"\$as_me:${as_lineno-$LINENO}: $ac_try_echo\"" +$as_echo "$ac_try_echo"; } >&5 + (eval "$ac_compiler $ac_option >&5") 2>conftest.err ac_status=$? - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } -{ (ac_try="$ac_compiler -V >&5" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_compiler -V >&5") 2>&5 - ac_status=$? - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } + if test -s conftest.err; then + sed '10a\ +... rest of stderr output deleted ... + 10q' conftest.err >conftest.er1 + cat conftest.er1 >&5 + fi + rm -f conftest.er1 conftest.err + $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 + test $ac_status = 0; } +done -cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF +cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ int @@ -2666,42 +3519,38 @@ } _ACEOF ac_clean_files_save=$ac_clean_files -ac_clean_files="$ac_clean_files a.out a.exe b.out" +ac_clean_files="$ac_clean_files a.out a.out.dSYM a.exe b.out" # Try to create an executable without -o first, disregard a.out. # It will help us diagnose broken compilers, and finding out an intuition # of exeext. -{ echo "$as_me:$LINENO: checking for C compiler default output file name" >&5 -echo $ECHO_N "checking for C compiler default output file name... $ECHO_C" >&6; } -ac_link_default=`echo "$ac_link" | sed 's/ -o *conftest[^ ]*//'` -# -# List of possible output files, starting from the most likely. -# The algorithm is not robust to junk in `.', hence go to wildcards (a.*) -# only as a last resort. b.out is created by i960 compilers. -ac_files='a_out.exe a.exe conftest.exe a.out conftest a.* conftest.* b.out' -# -# The IRIX 6 linker writes into existing files which may not be -# executable, retaining their permissions. Remove them first so a -# subsequent execution test works. +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking whether the C compiler works" >&5 +$as_echo_n "checking whether the C compiler works... " >&6; } +ac_link_default=`$as_echo "$ac_link" | sed 's/ -o *conftest[^ ]*//'` + +# The possible output files: +ac_files="a.out conftest.exe conftest a.exe a_out.exe b.out conftest.*" + ac_rmfiles= for ac_file in $ac_files do case $ac_file in - *.$ac_ext | *.xcoff | *.tds | *.d | *.pdb | *.xSYM | *.bb | *.bbg | *.map | *.inf | *.o | *.obj ) ;; + *.$ac_ext | *.xcoff | *.tds | *.d | *.pdb | *.xSYM | *.bb | *.bbg | *.map | *.inf | *.dSYM | *.o | *.obj ) ;; * ) ac_rmfiles="$ac_rmfiles $ac_file";; esac done rm -f $ac_rmfiles -if { (ac_try="$ac_link_default" +if { { ac_try="$ac_link_default" case "(($ac_try" in *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:${as_lineno-$LINENO}: $ac_try_echo\"" +$as_echo "$ac_try_echo"; } >&5 (eval "$ac_link_default") 2>&5 ac_status=$? - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); }; then + $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 + test $ac_status = 0; }; then : # Autoconf-2.13 could set the ac_cv_exeext variable to `no'. # So ignore a value of `no', otherwise this would lead to `EXEEXT = no' # in a Makefile. We should not override ac_cv_exeext if it was cached, @@ -2711,14 +3560,14 @@ do test -f "$ac_file" || continue case $ac_file in - *.$ac_ext | *.xcoff | *.tds | *.d | *.pdb | *.xSYM | *.bb | *.bbg | *.map | *.inf | *.o | *.obj ) + *.$ac_ext | *.xcoff | *.tds | *.d | *.pdb | *.xSYM | *.bb | *.bbg | *.map | *.inf | *.dSYM | *.o | *.obj ) ;; [ab].out ) # We found the default executable, but exeext='' is most # certainly right. break;; *.* ) - if test "${ac_cv_exeext+set}" = set && test "$ac_cv_exeext" != no; + if test "${ac_cv_exeext+set}" = set && test "$ac_cv_exeext" != no; then :; else ac_cv_exeext=`expr "$ac_file" : '[^.]*\(\..*\)'` fi @@ -2737,78 +3586,42 @@ else ac_file='' fi - -{ echo "$as_me:$LINENO: result: $ac_file" >&5 -echo "${ECHO_T}$ac_file" >&6; } -if test -z "$ac_file"; then - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - -{ { echo "$as_me:$LINENO: error: C compiler cannot create executables -See \`config.log' for more details." >&5 -echo "$as_me: error: C compiler cannot create executables -See \`config.log' for more details." >&2;} - { (exit 77); exit 77; }; } -fi - +if test -z "$ac_file"; then : + { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 +$as_echo "no" >&6; } +$as_echo "$as_me: failed program was:" >&5 +sed 's/^/| /' conftest.$ac_ext >&5 + +{ { $as_echo "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5 +$as_echo "$as_me: error: in \`$ac_pwd':" >&2;} +{ as_fn_set_status 77 +as_fn_error "C compiler cannot create executables +See \`config.log' for more details." "$LINENO" 5; }; } +else + { $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +$as_echo "yes" >&6; } +fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for C compiler default output file name" >&5 +$as_echo_n "checking for C compiler default output file name... " >&6; } +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_file" >&5 +$as_echo "$ac_file" >&6; } ac_exeext=$ac_cv_exeext -# Check that the compiler produces executables we can run. If not, either -# the compiler is broken, or we cross compile. -{ echo "$as_me:$LINENO: checking whether the C compiler works" >&5 -echo $ECHO_N "checking whether the C compiler works... $ECHO_C" >&6; } -# FIXME: These cross compiler hacks should be removed for Autoconf 3.0 -# If not cross compiling, check that we can run a simple program. -if test "$cross_compiling" != yes; then - if { ac_try='./$ac_file' - { (case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_try") 2>&5 - ac_status=$? - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); }; }; then - cross_compiling=no - else - if test "$cross_compiling" = maybe; then - cross_compiling=yes - else - { { echo "$as_me:$LINENO: error: cannot run C compiled programs. -If you meant to cross compile, use \`--host'. -See \`config.log' for more details." >&5 -echo "$as_me: error: cannot run C compiled programs. -If you meant to cross compile, use \`--host'. -See \`config.log' for more details." >&2;} - { (exit 1); exit 1; }; } - fi - fi -fi -{ echo "$as_me:$LINENO: result: yes" >&5 -echo "${ECHO_T}yes" >&6; } - -rm -f a.out a.exe conftest$ac_cv_exeext b.out +rm -f -r a.out a.out.dSYM a.exe conftest$ac_cv_exeext b.out ac_clean_files=$ac_clean_files_save -# Check that the compiler produces executables we can run. If not, either -# the compiler is broken, or we cross compile. -{ echo "$as_me:$LINENO: checking whether we are cross compiling" >&5 -echo $ECHO_N "checking whether we are cross compiling... $ECHO_C" >&6; } -{ echo "$as_me:$LINENO: result: $cross_compiling" >&5 -echo "${ECHO_T}$cross_compiling" >&6; } - -{ echo "$as_me:$LINENO: checking for suffix of executables" >&5 -echo $ECHO_N "checking for suffix of executables... $ECHO_C" >&6; } -if { (ac_try="$ac_link" +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for suffix of executables" >&5 +$as_echo_n "checking for suffix of executables... " >&6; } +if { { ac_try="$ac_link" case "(($ac_try" in *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:${as_lineno-$LINENO}: $ac_try_echo\"" +$as_echo "$ac_try_echo"; } >&5 (eval "$ac_link") 2>&5 ac_status=$? - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); }; then + $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 + test $ac_status = 0; }; then : # If both `conftest.exe' and `conftest' are `present' (well, observable) # catch `conftest.exe'. For instance with Cygwin, `ls conftest' will # work properly (i.e., refer to `conftest.exe'), while it won't with @@ -2816,37 +3629,90 @@ for ac_file in conftest.exe conftest conftest.*; do test -f "$ac_file" || continue case $ac_file in - *.$ac_ext | *.xcoff | *.tds | *.d | *.pdb | *.xSYM | *.bb | *.bbg | *.map | *.inf | *.o | *.obj ) ;; + *.$ac_ext | *.xcoff | *.tds | *.d | *.pdb | *.xSYM | *.bb | *.bbg | *.map | *.inf | *.dSYM | *.o | *.obj ) ;; *.* ) ac_cv_exeext=`expr "$ac_file" : '[^.]*\(\..*\)'` break;; * ) break;; esac done else - { { echo "$as_me:$LINENO: error: cannot compute suffix of executables: cannot compile and link -See \`config.log' for more details." >&5 -echo "$as_me: error: cannot compute suffix of executables: cannot compile and link -See \`config.log' for more details." >&2;} - { (exit 1); exit 1; }; } -fi - -rm -f conftest$ac_cv_exeext -{ echo "$as_me:$LINENO: result: $ac_cv_exeext" >&5 -echo "${ECHO_T}$ac_cv_exeext" >&6; } + { { $as_echo "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5 +$as_echo "$as_me: error: in \`$ac_pwd':" >&2;} +as_fn_error "cannot compute suffix of executables: cannot compile and link +See \`config.log' for more details." "$LINENO" 5; } +fi +rm -f conftest conftest$ac_cv_exeext +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_exeext" >&5 +$as_echo "$ac_cv_exeext" >&6; } rm -f conftest.$ac_ext EXEEXT=$ac_cv_exeext ac_exeext=$EXEEXT -{ echo "$as_me:$LINENO: checking for suffix of object files" >&5 -echo $ECHO_N "checking for suffix of object files... $ECHO_C" >&6; } -if test "${ac_cv_objext+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 -else - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ +cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ +#include +int +main () +{ +FILE *f = fopen ("conftest.out", "w"); + return ferror (f) || fclose (f) != 0; + + ; + return 0; +} _ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF +ac_clean_files="$ac_clean_files conftest.out" +# Check that the compiler produces executables we can run. If not, either +# the compiler is broken, or we cross compile. +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking whether we are cross compiling" >&5 +$as_echo_n "checking whether we are cross compiling... " >&6; } +if test "$cross_compiling" != yes; then + { { ac_try="$ac_link" +case "(($ac_try" in + *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; + *) ac_try_echo=$ac_try;; +esac +eval ac_try_echo="\"\$as_me:${as_lineno-$LINENO}: $ac_try_echo\"" +$as_echo "$ac_try_echo"; } >&5 + (eval "$ac_link") 2>&5 + ac_status=$? + $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 + test $ac_status = 0; } + if { ac_try='./conftest$ac_cv_exeext' + { { case "(($ac_try" in + *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; + *) ac_try_echo=$ac_try;; +esac +eval ac_try_echo="\"\$as_me:${as_lineno-$LINENO}: $ac_try_echo\"" +$as_echo "$ac_try_echo"; } >&5 + (eval "$ac_try") 2>&5 + ac_status=$? + $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 + test $ac_status = 0; }; }; then + cross_compiling=no + else + if test "$cross_compiling" = maybe; then + cross_compiling=yes + else + { { $as_echo "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5 +$as_echo "$as_me: error: in \`$ac_pwd':" >&2;} +as_fn_error "cannot run C compiled programs. +If you meant to cross compile, use \`--host'. +See \`config.log' for more details." "$LINENO" 5; } + fi + fi +fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $cross_compiling" >&5 +$as_echo "$cross_compiling" >&6; } + +rm -f conftest.$ac_ext conftest$ac_cv_exeext conftest.out +ac_clean_files=$ac_clean_files_save +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for suffix of object files" >&5 +$as_echo_n "checking for suffix of object files... " >&6; } +if test "${ac_cv_objext+set}" = set; then : + $as_echo_n "(cached) " >&6 +else + cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ int @@ -2858,51 +3724,46 @@ } _ACEOF rm -f conftest.o conftest.obj -if { (ac_try="$ac_compile" +if { { ac_try="$ac_compile" case "(($ac_try" in *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 +eval ac_try_echo="\"\$as_me:${as_lineno-$LINENO}: $ac_try_echo\"" +$as_echo "$ac_try_echo"; } >&5 (eval "$ac_compile") 2>&5 ac_status=$? - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); }; then + $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 + test $ac_status = 0; }; then : for ac_file in conftest.o conftest.obj conftest.*; do test -f "$ac_file" || continue; case $ac_file in - *.$ac_ext | *.xcoff | *.tds | *.d | *.pdb | *.xSYM | *.bb | *.bbg | *.map | *.inf ) ;; + *.$ac_ext | *.xcoff | *.tds | *.d | *.pdb | *.xSYM | *.bb | *.bbg | *.map | *.inf | *.dSYM ) ;; *) ac_cv_objext=`expr "$ac_file" : '.*\.\(.*\)'` break;; esac done else - echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 -{ { echo "$as_me:$LINENO: error: cannot compute suffix of object files: cannot compile -See \`config.log' for more details." >&5 -echo "$as_me: error: cannot compute suffix of object files: cannot compile -See \`config.log' for more details." >&2;} - { (exit 1); exit 1; }; } +{ { $as_echo "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5 +$as_echo "$as_me: error: in \`$ac_pwd':" >&2;} +as_fn_error "cannot compute suffix of object files: cannot compile +See \`config.log' for more details." "$LINENO" 5; } fi - rm -f conftest.$ac_cv_objext conftest.$ac_ext fi -{ echo "$as_me:$LINENO: result: $ac_cv_objext" >&5 -echo "${ECHO_T}$ac_cv_objext" >&6; } +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_objext" >&5 +$as_echo "$ac_cv_objext" >&6; } OBJEXT=$ac_cv_objext ac_objext=$OBJEXT -{ echo "$as_me:$LINENO: checking whether we are using the GNU C compiler" >&5 -echo $ECHO_N "checking whether we are using the GNU C compiler... $ECHO_C" >&6; } -if test "${ac_cv_c_compiler_gnu+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking whether we are using the GNU C compiler" >&5 +$as_echo_n "checking whether we are using the GNU C compiler... " >&6; } +if test "${ac_cv_c_compiler_gnu+set}" = set; then : + $as_echo_n "(cached) " >&6 else - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF + cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ int @@ -2916,54 +3777,34 @@ return 0; } _ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then +if ac_fn_c_try_compile "$LINENO"; then : ac_compiler_gnu=yes else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - ac_compiler_gnu=no + ac_compiler_gnu=no fi - rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext ac_cv_c_compiler_gnu=$ac_compiler_gnu fi -{ echo "$as_me:$LINENO: result: $ac_cv_c_compiler_gnu" >&5 -echo "${ECHO_T}$ac_cv_c_compiler_gnu" >&6; } -GCC=`test $ac_compiler_gnu = yes && echo yes` +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_c_compiler_gnu" >&5 +$as_echo "$ac_cv_c_compiler_gnu" >&6; } +if test $ac_compiler_gnu = yes; then + GCC=yes +else + GCC= +fi ac_test_CFLAGS=${CFLAGS+set} ac_save_CFLAGS=$CFLAGS -{ echo "$as_me:$LINENO: checking whether $CC accepts -g" >&5 -echo $ECHO_N "checking whether $CC accepts -g... $ECHO_C" >&6; } -if test "${ac_cv_prog_cc_g+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking whether $CC accepts -g" >&5 +$as_echo_n "checking whether $CC accepts -g... " >&6; } +if test "${ac_cv_prog_cc_g+set}" = set; then : + $as_echo_n "(cached) " >&6 else ac_save_c_werror_flag=$ac_c_werror_flag ac_c_werror_flag=yes ac_cv_prog_cc_g=no CFLAGS="-g" - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF + cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ int @@ -2974,34 +3815,11 @@ return 0; } _ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then +if ac_fn_c_try_compile "$LINENO"; then : ac_cv_prog_cc_g=yes else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - CFLAGS="" - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF + CFLAGS="" + cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ int @@ -3012,35 +3830,12 @@ return 0; } _ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - : -else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 +if ac_fn_c_try_compile "$LINENO"; then : - ac_c_werror_flag=$ac_save_c_werror_flag +else + ac_c_werror_flag=$ac_save_c_werror_flag CFLAGS="-g" - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF + cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ int @@ -3051,42 +3846,18 @@ return 0; } _ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then +if ac_fn_c_try_compile "$LINENO"; then : ac_cv_prog_cc_g=yes -else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - fi - rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext fi - rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext fi - rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext ac_c_werror_flag=$ac_save_c_werror_flag fi -{ echo "$as_me:$LINENO: result: $ac_cv_prog_cc_g" >&5 -echo "${ECHO_T}$ac_cv_prog_cc_g" >&6; } +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_prog_cc_g" >&5 +$as_echo "$ac_cv_prog_cc_g" >&6; } if test "$ac_test_CFLAGS" = set; then CFLAGS=$ac_save_CFLAGS elif test $ac_cv_prog_cc_g = yes; then @@ -3102,18 +3873,14 @@ CFLAGS= fi fi -{ echo "$as_me:$LINENO: checking for $CC option to accept ISO C89" >&5 -echo $ECHO_N "checking for $CC option to accept ISO C89... $ECHO_C" >&6; } -if test "${ac_cv_prog_cc_c89+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $CC option to accept ISO C89" >&5 +$as_echo_n "checking for $CC option to accept ISO C89... " >&6; } +if test "${ac_cv_prog_cc_c89+set}" = set; then : + $as_echo_n "(cached) " >&6 else ac_cv_prog_cc_c89=no ac_save_CC=$CC -cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF +cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ #include #include @@ -3170,31 +3937,9 @@ -Ae "-Aa -D_HPUX_SOURCE" "-Xc -D__EXTENSIONS__" do CC="$ac_save_CC $ac_arg" - rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then + if ac_fn_c_try_compile "$LINENO"; then : ac_cv_prog_cc_c89=$ac_arg -else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - fi - rm -f core conftest.err conftest.$ac_objext test "x$ac_cv_prog_cc_c89" != "xno" && break done @@ -3205,17 +3950,19 @@ # AC_CACHE_VAL case "x$ac_cv_prog_cc_c89" in x) - { echo "$as_me:$LINENO: result: none needed" >&5 -echo "${ECHO_T}none needed" >&6; } ;; + { $as_echo "$as_me:${as_lineno-$LINENO}: result: none needed" >&5 +$as_echo "none needed" >&6; } ;; xno) - { echo "$as_me:$LINENO: result: unsupported" >&5 -echo "${ECHO_T}unsupported" >&6; } ;; + { $as_echo "$as_me:${as_lineno-$LINENO}: result: unsupported" >&5 +$as_echo "unsupported" >&6; } ;; *) CC="$CC $ac_cv_prog_cc_c89" - { echo "$as_me:$LINENO: result: $ac_cv_prog_cc_c89" >&5 -echo "${ECHO_T}$ac_cv_prog_cc_c89" >&6; } ;; + { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_prog_cc_c89" >&5 +$as_echo "$ac_cv_prog_cc_c89" >&6; } ;; esac +if test "x$ac_cv_prog_cc_c89" != xno; then : +fi ac_ext=c ac_cpp='$CPP $CPPFLAGS' @@ -3223,15 +3970,18 @@ ac_link='$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5' ac_compiler_gnu=$ac_cv_c_compiler_gnu -CFLAGS=$save_CFLAGS +if test ! -z "$preset_cflags" +then + CFLAGS=$preset_cflags +fi -{ echo "$as_me:$LINENO: checking for --with-cxx-main=" >&5 -echo $ECHO_N "checking for --with-cxx-main=... $ECHO_C" >&6; } +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for --with-cxx-main=" >&5 +$as_echo_n "checking for --with-cxx-main=... " >&6; } # Check whether --with-cxx_main was given. -if test "${with_cxx_main+set}" = set; then +if test "${with_cxx_main+set}" = set; then : withval=$with_cxx_main; case $withval in @@ -3253,8 +4003,8 @@ fi -{ echo "$as_me:$LINENO: result: $with_cxx_main" >&5 -echo "${ECHO_T}$with_cxx_main" >&6; } +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $with_cxx_main" >&5 +$as_echo "$with_cxx_main" >&6; } preset_cxx="$CXX" if test -z "$CXX" @@ -3262,10 +4012,10 @@ case "$CC" in gcc) # Extract the first word of "g++", so it can be a program name with args. set dummy g++; ac_word=$2 -{ echo "$as_me:$LINENO: checking for $ac_word" >&5 -echo $ECHO_N "checking for $ac_word... $ECHO_C" >&6; } -if test "${ac_cv_path_CXX+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 +$as_echo_n "checking for $ac_word... " >&6; } +if test "${ac_cv_path_CXX+set}" = set; then : + $as_echo_n "(cached) " >&6 else case $CXX in [\\/]* | ?:[\\/]*) @@ -3277,14 +4027,14 @@ do IFS=$as_save_IFS test -z "$as_dir" && as_dir=. - for ac_exec_ext in '' $ac_executable_extensions; do + for ac_exec_ext in '' $ac_executable_extensions; do if { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_test_x "$as_dir/$ac_word$ac_exec_ext"; }; then ac_cv_path_CXX="$as_dir/$ac_word$ac_exec_ext" - echo "$as_me:$LINENO: found $as_dir/$ac_word$ac_exec_ext" >&5 + $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 break 2 fi done -done + done IFS=$as_save_IFS test -z "$ac_cv_path_CXX" && ac_cv_path_CXX="g++" @@ -3293,20 +4043,20 @@ fi CXX=$ac_cv_path_CXX if test -n "$CXX"; then - { echo "$as_me:$LINENO: result: $CXX" >&5 -echo "${ECHO_T}$CXX" >&6; } + { $as_echo "$as_me:${as_lineno-$LINENO}: result: $CXX" >&5 +$as_echo "$CXX" >&6; } else - { echo "$as_me:$LINENO: result: no" >&5 -echo "${ECHO_T}no" >&6; } + { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 +$as_echo "no" >&6; } fi ;; cc) # Extract the first word of "c++", so it can be a program name with args. set dummy c++; ac_word=$2 -{ echo "$as_me:$LINENO: checking for $ac_word" >&5 -echo $ECHO_N "checking for $ac_word... $ECHO_C" >&6; } -if test "${ac_cv_path_CXX+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 +$as_echo_n "checking for $ac_word... " >&6; } +if test "${ac_cv_path_CXX+set}" = set; then : + $as_echo_n "(cached) " >&6 else case $CXX in [\\/]* | ?:[\\/]*) @@ -3318,14 +4068,14 @@ do IFS=$as_save_IFS test -z "$as_dir" && as_dir=. - for ac_exec_ext in '' $ac_executable_extensions; do + for ac_exec_ext in '' $ac_executable_extensions; do if { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_test_x "$as_dir/$ac_word$ac_exec_ext"; }; then ac_cv_path_CXX="$as_dir/$ac_word$ac_exec_ext" - echo "$as_me:$LINENO: found $as_dir/$ac_word$ac_exec_ext" >&5 + $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 break 2 fi done -done + done IFS=$as_save_IFS test -z "$ac_cv_path_CXX" && ac_cv_path_CXX="c++" @@ -3334,11 +4084,11 @@ fi CXX=$ac_cv_path_CXX if test -n "$CXX"; then - { echo "$as_me:$LINENO: result: $CXX" >&5 -echo "${ECHO_T}$CXX" >&6; } + { $as_echo "$as_me:${as_lineno-$LINENO}: result: $CXX" >&5 +$as_echo "$CXX" >&6; } else - { echo "$as_me:$LINENO: result: no" >&5 -echo "${ECHO_T}no" >&6; } + { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 +$as_echo "no" >&6; } fi ;; @@ -3354,10 +4104,10 @@ do # Extract the first word of "$ac_prog", so it can be a program name with args. set dummy $ac_prog; ac_word=$2 -{ echo "$as_me:$LINENO: checking for $ac_word" >&5 -echo $ECHO_N "checking for $ac_word... $ECHO_C" >&6; } -if test "${ac_cv_prog_CXX+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 +$as_echo_n "checking for $ac_word... " >&6; } +if test "${ac_cv_prog_CXX+set}" = set; then : + $as_echo_n "(cached) " >&6 else if test -n "$CXX"; then ac_cv_prog_CXX="$CXX" # Let the user override the test. @@ -3367,25 +4117,25 @@ do IFS=$as_save_IFS test -z "$as_dir" && as_dir=. - for ac_exec_ext in '' $ac_executable_extensions; do + for ac_exec_ext in '' $ac_executable_extensions; do if { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_test_x "$as_dir/$ac_word$ac_exec_ext"; }; then ac_cv_prog_CXX="$ac_prog" - echo "$as_me:$LINENO: found $as_dir/$ac_word$ac_exec_ext" >&5 + $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 break 2 fi done -done + done IFS=$as_save_IFS fi fi CXX=$ac_cv_prog_CXX if test -n "$CXX"; then - { echo "$as_me:$LINENO: result: $CXX" >&5 -echo "${ECHO_T}$CXX" >&6; } + { $as_echo "$as_me:${as_lineno-$LINENO}: result: $CXX" >&5 +$as_echo "$CXX" >&6; } else - { echo "$as_me:$LINENO: result: no" >&5 -echo "${ECHO_T}no" >&6; } + { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 +$as_echo "no" >&6; } fi @@ -3400,12 +4150,12 @@ fi if test "$preset_cxx" != "$CXX" then - { echo "$as_me:$LINENO: WARNING: + { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: By default, distutils will build C++ extension modules with \"$CXX\". If this is not intended, then set CXX on the configure command line. " >&5 -echo "$as_me: WARNING: +$as_echo "$as_me: WARNING: By default, distutils will build C++ extension modules with \"$CXX\". If this is not intended, then set CXX on the configure command line. @@ -3420,15 +4170,15 @@ ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5' ac_link='$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5' ac_compiler_gnu=$ac_cv_c_compiler_gnu -{ echo "$as_me:$LINENO: checking how to run the C preprocessor" >&5 -echo $ECHO_N "checking how to run the C preprocessor... $ECHO_C" >&6; } +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking how to run the C preprocessor" >&5 +$as_echo_n "checking how to run the C preprocessor... " >&6; } # On Suns, sometimes $CPP names a directory. if test -n "$CPP" && test -d "$CPP"; then CPP= fi if test -z "$CPP"; then - if test "${ac_cv_prog_CPP+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 + if test "${ac_cv_prog_CPP+set}" = set; then : + $as_echo_n "(cached) " >&6 else # Double quotes because CPP needs to be expanded for CPP in "$CC -E" "$CC -E -traditional-cpp" "/lib/cpp" @@ -3442,11 +4192,7 @@ # exists even on freestanding compilers. # On the NeXT, cc -E runs the code through the compiler's parser, # not just through cpp. "Syntax error" is here to catch this case. - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF + cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ #ifdef __STDC__ # include @@ -3455,76 +4201,34 @@ #endif Syntax error _ACEOF -if { (ac_try="$ac_cpp conftest.$ac_ext" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_cpp conftest.$ac_ext") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } >/dev/null && { - test -z "$ac_c_preproc_warn_flag$ac_c_werror_flag" || - test ! -s conftest.err - }; then - : -else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 +if ac_fn_c_try_cpp "$LINENO"; then : +else # Broken: fails on valid input. continue fi - rm -f conftest.err conftest.$ac_ext # OK, works on sane cases. Now check whether nonexistent headers # can be detected and how. - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF + cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ #include _ACEOF -if { (ac_try="$ac_cpp conftest.$ac_ext" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_cpp conftest.$ac_ext") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } >/dev/null && { - test -z "$ac_c_preproc_warn_flag$ac_c_werror_flag" || - test ! -s conftest.err - }; then +if ac_fn_c_try_cpp "$LINENO"; then : # Broken: success on invalid input. continue else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - # Passes both tests. ac_preproc_ok=: break fi - rm -f conftest.err conftest.$ac_ext done # Because of `break', _AC_PREPROC_IFELSE's cleaning code was skipped. rm -f conftest.err conftest.$ac_ext -if $ac_preproc_ok; then +if $ac_preproc_ok; then : break fi @@ -3536,8 +4240,8 @@ else ac_cv_prog_CPP=$CPP fi -{ echo "$as_me:$LINENO: result: $CPP" >&5 -echo "${ECHO_T}$CPP" >&6; } +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $CPP" >&5 +$as_echo "$CPP" >&6; } ac_preproc_ok=false for ac_c_preproc_warn_flag in '' yes do @@ -3547,11 +4251,7 @@ # exists even on freestanding compilers. # On the NeXT, cc -E runs the code through the compiler's parser, # not just through cpp. "Syntax error" is here to catch this case. - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF + cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ #ifdef __STDC__ # include @@ -3560,83 +4260,40 @@ #endif Syntax error _ACEOF -if { (ac_try="$ac_cpp conftest.$ac_ext" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_cpp conftest.$ac_ext") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } >/dev/null && { - test -z "$ac_c_preproc_warn_flag$ac_c_werror_flag" || - test ! -s conftest.err - }; then - : -else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 +if ac_fn_c_try_cpp "$LINENO"; then : +else # Broken: fails on valid input. continue fi - rm -f conftest.err conftest.$ac_ext # OK, works on sane cases. Now check whether nonexistent headers # can be detected and how. - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF + cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ #include _ACEOF -if { (ac_try="$ac_cpp conftest.$ac_ext" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_cpp conftest.$ac_ext") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } >/dev/null && { - test -z "$ac_c_preproc_warn_flag$ac_c_werror_flag" || - test ! -s conftest.err - }; then +if ac_fn_c_try_cpp "$LINENO"; then : # Broken: success on invalid input. continue else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - # Passes both tests. ac_preproc_ok=: break fi - rm -f conftest.err conftest.$ac_ext done # Because of `break', _AC_PREPROC_IFELSE's cleaning code was skipped. rm -f conftest.err conftest.$ac_ext -if $ac_preproc_ok; then - : +if $ac_preproc_ok; then : + else - { { echo "$as_me:$LINENO: error: C preprocessor \"$CPP\" fails sanity check -See \`config.log' for more details." >&5 -echo "$as_me: error: C preprocessor \"$CPP\" fails sanity check -See \`config.log' for more details." >&2;} - { (exit 1); exit 1; }; } + { { $as_echo "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5 +$as_echo "$as_me: error: in \`$ac_pwd':" >&2;} +as_fn_error "C preprocessor \"$CPP\" fails sanity check +See \`config.log' for more details." "$LINENO" 5; } fi ac_ext=c @@ -3646,45 +4303,40 @@ ac_compiler_gnu=$ac_cv_c_compiler_gnu -{ echo "$as_me:$LINENO: checking for grep that handles long lines and -e" >&5 -echo $ECHO_N "checking for grep that handles long lines and -e... $ECHO_C" >&6; } -if test "${ac_cv_path_GREP+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 -else - # Extract the first word of "grep ggrep" to use in msg output -if test -z "$GREP"; then -set dummy grep ggrep; ac_prog_name=$2 -if test "${ac_cv_path_GREP+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for grep that handles long lines and -e" >&5 +$as_echo_n "checking for grep that handles long lines and -e... " >&6; } +if test "${ac_cv_path_GREP+set}" = set; then : + $as_echo_n "(cached) " >&6 else + if test -z "$GREP"; then ac_path_GREP_found=false -# Loop through the user's path and test for each of PROGNAME-LIST -as_save_IFS=$IFS; IFS=$PATH_SEPARATOR + # Loop through the user's path and test for each of PROGNAME-LIST + as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $PATH$PATH_SEPARATOR/usr/xpg4/bin do IFS=$as_save_IFS test -z "$as_dir" && as_dir=. - for ac_prog in grep ggrep; do - for ac_exec_ext in '' $ac_executable_extensions; do - ac_path_GREP="$as_dir/$ac_prog$ac_exec_ext" - { test -f "$ac_path_GREP" && $as_test_x "$ac_path_GREP"; } || continue - # Check for GNU ac_path_GREP and select it if it is found. + for ac_prog in grep ggrep; do + for ac_exec_ext in '' $ac_executable_extensions; do + ac_path_GREP="$as_dir/$ac_prog$ac_exec_ext" + { test -f "$ac_path_GREP" && $as_test_x "$ac_path_GREP"; } || continue +# Check for GNU ac_path_GREP and select it if it is found. # Check for GNU $ac_path_GREP case `"$ac_path_GREP" --version 2>&1` in *GNU*) ac_cv_path_GREP="$ac_path_GREP" ac_path_GREP_found=:;; *) ac_count=0 - echo $ECHO_N "0123456789$ECHO_C" >"conftest.in" + $as_echo_n 0123456789 >"conftest.in" while : do cat "conftest.in" "conftest.in" >"conftest.tmp" mv "conftest.tmp" "conftest.in" cp "conftest.in" "conftest.nl" - echo 'GREP' >> "conftest.nl" + $as_echo 'GREP' >> "conftest.nl" "$ac_path_GREP" -e 'GREP$' -e '-(cannot match)-' < "conftest.nl" >"conftest.out" 2>/dev/null || break diff "conftest.out" "conftest.nl" >/dev/null 2>&1 || break - ac_count=`expr $ac_count + 1` + as_fn_arith $ac_count + 1 && ac_count=$as_val if test $ac_count -gt ${ac_path_GREP_max-0}; then # Best one so far, save it but keep looking for a better one ac_cv_path_GREP="$ac_path_GREP" @@ -3696,77 +4348,61 @@ rm -f conftest.in conftest.tmp conftest.nl conftest.out;; esac - - $ac_path_GREP_found && break 3 + $ac_path_GREP_found && break 3 + done + done done -done - -done IFS=$as_save_IFS - - -fi - -GREP="$ac_cv_path_GREP" -if test -z "$GREP"; then - { { echo "$as_me:$LINENO: error: no acceptable $ac_prog_name could be found in $PATH$PATH_SEPARATOR/usr/xpg4/bin" >&5 -echo "$as_me: error: no acceptable $ac_prog_name could be found in $PATH$PATH_SEPARATOR/usr/xpg4/bin" >&2;} - { (exit 1); exit 1; }; } -fi - + if test -z "$ac_cv_path_GREP"; then + as_fn_error "no acceptable grep could be found in $PATH$PATH_SEPARATOR/usr/xpg4/bin" "$LINENO" 5 + fi else ac_cv_path_GREP=$GREP fi - fi -{ echo "$as_me:$LINENO: result: $ac_cv_path_GREP" >&5 -echo "${ECHO_T}$ac_cv_path_GREP" >&6; } +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_path_GREP" >&5 +$as_echo "$ac_cv_path_GREP" >&6; } GREP="$ac_cv_path_GREP" -{ echo "$as_me:$LINENO: checking for egrep" >&5 -echo $ECHO_N "checking for egrep... $ECHO_C" >&6; } -if test "${ac_cv_path_EGREP+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for egrep" >&5 +$as_echo_n "checking for egrep... " >&6; } +if test "${ac_cv_path_EGREP+set}" = set; then : + $as_echo_n "(cached) " >&6 else if echo a | $GREP -E '(a|b)' >/dev/null 2>&1 then ac_cv_path_EGREP="$GREP -E" else - # Extract the first word of "egrep" to use in msg output -if test -z "$EGREP"; then -set dummy egrep; ac_prog_name=$2 -if test "${ac_cv_path_EGREP+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 -else + if test -z "$EGREP"; then ac_path_EGREP_found=false -# Loop through the user's path and test for each of PROGNAME-LIST -as_save_IFS=$IFS; IFS=$PATH_SEPARATOR + # Loop through the user's path and test for each of PROGNAME-LIST + as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $PATH$PATH_SEPARATOR/usr/xpg4/bin do IFS=$as_save_IFS test -z "$as_dir" && as_dir=. - for ac_prog in egrep; do - for ac_exec_ext in '' $ac_executable_extensions; do - ac_path_EGREP="$as_dir/$ac_prog$ac_exec_ext" - { test -f "$ac_path_EGREP" && $as_test_x "$ac_path_EGREP"; } || continue - # Check for GNU ac_path_EGREP and select it if it is found. + for ac_prog in egrep; do + for ac_exec_ext in '' $ac_executable_extensions; do + ac_path_EGREP="$as_dir/$ac_prog$ac_exec_ext" + { test -f "$ac_path_EGREP" && $as_test_x "$ac_path_EGREP"; } || continue +# Check for GNU ac_path_EGREP and select it if it is found. # Check for GNU $ac_path_EGREP case `"$ac_path_EGREP" --version 2>&1` in *GNU*) ac_cv_path_EGREP="$ac_path_EGREP" ac_path_EGREP_found=:;; *) ac_count=0 - echo $ECHO_N "0123456789$ECHO_C" >"conftest.in" + $as_echo_n 0123456789 >"conftest.in" while : do cat "conftest.in" "conftest.in" >"conftest.tmp" mv "conftest.tmp" "conftest.in" cp "conftest.in" "conftest.nl" - echo 'EGREP' >> "conftest.nl" + $as_echo 'EGREP' >> "conftest.nl" "$ac_path_EGREP" 'EGREP$' < "conftest.nl" >"conftest.out" 2>/dev/null || break diff "conftest.out" "conftest.nl" >/dev/null 2>&1 || break - ac_count=`expr $ac_count + 1` + as_fn_arith $ac_count + 1 && ac_count=$as_val if test $ac_count -gt ${ac_path_EGREP_max-0}; then # Best one so far, save it but keep looking for a better one ac_cv_path_EGREP="$ac_path_EGREP" @@ -3778,63 +4414,214 @@ rm -f conftest.in conftest.tmp conftest.nl conftest.out;; esac - - $ac_path_EGREP_found && break 3 + $ac_path_EGREP_found && break 3 + done + done done -done - -done IFS=$as_save_IFS - - -fi - -EGREP="$ac_cv_path_EGREP" -if test -z "$EGREP"; then - { { echo "$as_me:$LINENO: error: no acceptable $ac_prog_name could be found in $PATH$PATH_SEPARATOR/usr/xpg4/bin" >&5 -echo "$as_me: error: no acceptable $ac_prog_name could be found in $PATH$PATH_SEPARATOR/usr/xpg4/bin" >&2;} - { (exit 1); exit 1; }; } -fi - + if test -z "$ac_cv_path_EGREP"; then + as_fn_error "no acceptable egrep could be found in $PATH$PATH_SEPARATOR/usr/xpg4/bin" "$LINENO" 5 + fi else ac_cv_path_EGREP=$EGREP fi - fi fi -{ echo "$as_me:$LINENO: result: $ac_cv_path_EGREP" >&5 -echo "${ECHO_T}$ac_cv_path_EGREP" >&6; } +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_path_EGREP" >&5 +$as_echo "$ac_cv_path_EGREP" >&6; } EGREP="$ac_cv_path_EGREP" +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for ANSI C header files" >&5 +$as_echo_n "checking for ANSI C header files... " >&6; } +if test "${ac_cv_header_stdc+set}" = set; then : + $as_echo_n "(cached) " >&6 +else + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ +#include +#include +#include +#include + +int +main () +{ -{ echo "$as_me:$LINENO: checking for AIX" >&5 -echo $ECHO_N "checking for AIX... $ECHO_C" >&6; } -cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ + ; + return 0; +} _ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF +if ac_fn_c_try_compile "$LINENO"; then : + ac_cv_header_stdc=yes +else + ac_cv_header_stdc=no +fi +rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext + +if test $ac_cv_header_stdc = yes; then + # SunOS 4.x string.h does not declare mem*, contrary to ANSI. + cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ -#ifdef _AIX - yes -#endif +#include _ACEOF if (eval "$ac_cpp conftest.$ac_ext") 2>&5 | - $EGREP "yes" >/dev/null 2>&1; then - { echo "$as_me:$LINENO: result: yes" >&5 -echo "${ECHO_T}yes" >&6; } -cat >>confdefs.h <<\_ACEOF -#define _ALL_SOURCE 1 -_ACEOF + $EGREP "memchr" >/dev/null 2>&1; then : else - { echo "$as_me:$LINENO: result: no" >&5 -echo "${ECHO_T}no" >&6; } + ac_cv_header_stdc=no fi -rm -f -r conftest* +rm -f conftest* + +fi + +if test $ac_cv_header_stdc = yes; then + # ISC 2.0.2 stdlib.h does not declare free, contrary to ANSI. + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ +#include + +_ACEOF +if (eval "$ac_cpp conftest.$ac_ext") 2>&5 | + $EGREP "free" >/dev/null 2>&1; then : + +else + ac_cv_header_stdc=no +fi +rm -f conftest* + +fi + +if test $ac_cv_header_stdc = yes; then + # /bin/cc in Irix-4.0.5 gets non-ANSI ctype macros unless using -ansi. + if test "$cross_compiling" = yes; then : + : +else + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ +#include +#include +#if ((' ' & 0x0FF) == 0x020) +# define ISLOWER(c) ('a' <= (c) && (c) <= 'z') +# define TOUPPER(c) (ISLOWER(c) ? 'A' + ((c) - 'a') : (c)) +#else +# define ISLOWER(c) \ + (('a' <= (c) && (c) <= 'i') \ + || ('j' <= (c) && (c) <= 'r') \ + || ('s' <= (c) && (c) <= 'z')) +# define TOUPPER(c) (ISLOWER(c) ? ((c) | 0x40) : (c)) +#endif + +#define XOR(e, f) (((e) && !(f)) || (!(e) && (f))) +int +main () +{ + int i; + for (i = 0; i < 256; i++) + if (XOR (islower (i), ISLOWER (i)) + || toupper (i) != TOUPPER (i)) + return 2; + return 0; +} +_ACEOF +if ac_fn_c_try_run "$LINENO"; then : + +else + ac_cv_header_stdc=no +fi +rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext \ + conftest.$ac_objext conftest.beam conftest.$ac_ext +fi + +fi +fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_header_stdc" >&5 +$as_echo "$ac_cv_header_stdc" >&6; } +if test $ac_cv_header_stdc = yes; then + +$as_echo "#define STDC_HEADERS 1" >>confdefs.h + +fi + +# On IRIX 5.3, sys/types and inttypes.h are conflicting. +for ac_header in sys/types.h sys/stat.h stdlib.h string.h memory.h strings.h \ + inttypes.h stdint.h unistd.h +do : + as_ac_Header=`$as_echo "ac_cv_header_$ac_header" | $as_tr_sh` +ac_fn_c_check_header_compile "$LINENO" "$ac_header" "$as_ac_Header" "$ac_includes_default +" +eval as_val=\$$as_ac_Header + if test "x$as_val" = x""yes; then : + cat >>confdefs.h <<_ACEOF +#define `$as_echo "HAVE_$ac_header" | $as_tr_cpp` 1 +_ACEOF + +fi + +done + + + + ac_fn_c_check_header_mongrel "$LINENO" "minix/config.h" "ac_cv_header_minix_config_h" "$ac_includes_default" +if test "x$ac_cv_header_minix_config_h" = x""yes; then : + MINIX=yes +else + MINIX= +fi + + + if test "$MINIX" = yes; then + +$as_echo "#define _POSIX_SOURCE 1" >>confdefs.h + + +$as_echo "#define _POSIX_1_SOURCE 2" >>confdefs.h + + +$as_echo "#define _MINIX 1" >>confdefs.h + + fi + + + { $as_echo "$as_me:${as_lineno-$LINENO}: checking whether it is safe to define __EXTENSIONS__" >&5 +$as_echo_n "checking whether it is safe to define __EXTENSIONS__... " >&6; } +if test "${ac_cv_safe_to_define___extensions__+set}" = set; then : + $as_echo_n "(cached) " >&6 +else + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + +# define __EXTENSIONS__ 1 + $ac_includes_default +int +main () +{ + + ; + return 0; +} +_ACEOF +if ac_fn_c_try_compile "$LINENO"; then : + ac_cv_safe_to_define___extensions__=yes +else + ac_cv_safe_to_define___extensions__=no +fi +rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext +fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_safe_to_define___extensions__" >&5 +$as_echo "$ac_cv_safe_to_define___extensions__" >&6; } + test $ac_cv_safe_to_define___extensions__ = yes && + $as_echo "#define __EXTENSIONS__ 1" >>confdefs.h + + $as_echo "#define _ALL_SOURCE 1" >>confdefs.h + + $as_echo "#define _GNU_SOURCE 1" >>confdefs.h + + $as_echo "#define _POSIX_PTHREAD_SEMANTICS 1" >>confdefs.h + + $as_echo "#define _TANDEM_SOURCE 1" >>confdefs.h @@ -3847,11 +4634,11 @@ esac -{ echo "$as_me:$LINENO: checking for --with-suffix" >&5 -echo $ECHO_N "checking for --with-suffix... $ECHO_C" >&6; } +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for --with-suffix" >&5 +$as_echo_n "checking for --with-suffix... " >&6; } # Check whether --with-suffix was given. -if test "${with_suffix+set}" = set; then +if test "${with_suffix+set}" = set; then : withval=$with_suffix; case $withval in no) EXEEXT=;; @@ -3860,26 +4647,26 @@ esac fi -{ echo "$as_me:$LINENO: result: $EXEEXT" >&5 -echo "${ECHO_T}$EXEEXT" >&6; } +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $EXEEXT" >&5 +$as_echo "$EXEEXT" >&6; } # Test whether we're running on a non-case-sensitive system, in which # case we give a warning if no ext is given -{ echo "$as_me:$LINENO: checking for case-insensitive build directory" >&5 -echo $ECHO_N "checking for case-insensitive build directory... $ECHO_C" >&6; } +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for case-insensitive build directory" >&5 +$as_echo_n "checking for case-insensitive build directory... " >&6; } if test ! -d CaseSensitiveTestDir; then mkdir CaseSensitiveTestDir fi if test -d casesensitivetestdir then - { echo "$as_me:$LINENO: result: yes" >&5 -echo "${ECHO_T}yes" >&6; } + { $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +$as_echo "yes" >&6; } BUILDEXEEXT=.exe else - { echo "$as_me:$LINENO: result: no" >&5 -echo "${ECHO_T}no" >&6; } + { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 +$as_echo "no" >&6; } BUILDEXEEXT=$EXEEXT fi rmdir CaseSensitiveTestDir @@ -3896,26 +4683,18 @@ case $CC in cc|*/cc) CC="$CC -Ae";; esac;; -SunOS*) - # Some functions have a prototype only with that define, e.g. confstr - -cat >>confdefs.h <<\_ACEOF -#define __EXTENSIONS__ 1 -_ACEOF - - ;; esac -{ echo "$as_me:$LINENO: checking LIBRARY" >&5 -echo $ECHO_N "checking LIBRARY... $ECHO_C" >&6; } +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking LIBRARY" >&5 +$as_echo_n "checking LIBRARY... " >&6; } if test -z "$LIBRARY" then LIBRARY='libpython$(VERSION).a' fi -{ echo "$as_me:$LINENO: result: $LIBRARY" >&5 -echo "${ECHO_T}$LIBRARY" >&6; } +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $LIBRARY" >&5 +$as_echo "$LIBRARY" >&6; } # LDLIBRARY is the name of the library to link against (as opposed to the # name of the library into which to insert object files). BLDLIBRARY is also @@ -3950,8 +4729,8 @@ # This is altered for AIX in order to build the export list before # linking. -{ echo "$as_me:$LINENO: checking LINKCC" >&5 -echo $ECHO_N "checking LINKCC... $ECHO_C" >&6; } +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking LINKCC" >&5 +$as_echo_n "checking LINKCC... " >&6; } if test -z "$LINKCC" then LINKCC='$(PURIFY) $(MAINCC)' @@ -3969,8 +4748,8 @@ LINKCC=qcc;; esac fi -{ echo "$as_me:$LINENO: result: $LINKCC" >&5 -echo "${ECHO_T}$LINKCC" >&6; } +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $LINKCC" >&5 +$as_echo "$LINKCC" >&6; } # GNULD is set to "yes" if the GNU linker is used. If this goes wrong # make sure we default having it set to "no": this is used by @@ -3978,8 +4757,8 @@ # to linker command lines, and failing to detect GNU ld simply results # in the same bahaviour as before. -{ echo "$as_me:$LINENO: checking for GNU ld" >&5 -echo $ECHO_N "checking for GNU ld... $ECHO_C" >&6; } +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for GNU ld" >&5 +$as_echo_n "checking for GNU ld... " >&6; } ac_prog=ld if test "$GCC" = yes; then ac_prog=`$CC -print-prog-name=ld` @@ -3990,13 +4769,13 @@ *) GNULD=no;; esac -{ echo "$as_me:$LINENO: result: $GNULD" >&5 -echo "${ECHO_T}$GNULD" >&6; } +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $GNULD" >&5 +$as_echo "$GNULD" >&6; } -{ echo "$as_me:$LINENO: checking for --enable-shared" >&5 -echo $ECHO_N "checking for --enable-shared... $ECHO_C" >&6; } +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for --enable-shared" >&5 +$as_echo_n "checking for --enable-shared... " >&6; } # Check whether --enable-shared was given. -if test "${enable_shared+set}" = set; then +if test "${enable_shared+set}" = set; then : enableval=$enable_shared; fi @@ -4010,64 +4789,36 @@ enable_shared="no";; esac fi -{ echo "$as_me:$LINENO: result: $enable_shared" >&5 -echo "${ECHO_T}$enable_shared" >&6; } +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $enable_shared" >&5 +$as_echo "$enable_shared" >&6; } -{ echo "$as_me:$LINENO: checking for --enable-profiling" >&5 -echo $ECHO_N "checking for --enable-profiling... $ECHO_C" >&6; } +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for --enable-profiling" >&5 +$as_echo_n "checking for --enable-profiling... " >&6; } # Check whether --enable-profiling was given. -if test "${enable_profiling+set}" = set; then +if test "${enable_profiling+set}" = set; then : enableval=$enable_profiling; ac_save_cc="$CC" CC="$CC -pg" - if test "$cross_compiling" = yes; then + if test "$cross_compiling" = yes; then : ac_enable_profiling="no" else - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF + cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ int main() { return 0; } _ACEOF -rm -f conftest$ac_exeext -if { (ac_try="$ac_link" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_link") 2>&5 - ac_status=$? - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { ac_try='./conftest$ac_exeext' - { (case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_try") 2>&5 - ac_status=$? - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); }; }; then +if ac_fn_c_try_run "$LINENO"; then : ac_enable_profiling="yes" else - echo "$as_me: program exited with status $ac_status" >&5 -echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - -( exit $ac_status ) -ac_enable_profiling="no" + ac_enable_profiling="no" fi -rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext conftest.$ac_objext conftest.$ac_ext +rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext \ + conftest.$ac_objext conftest.beam conftest.$ac_ext fi - CC="$ac_save_cc" fi -{ echo "$as_me:$LINENO: result: $ac_enable_profiling" >&5 -echo "${ECHO_T}$ac_enable_profiling" >&6; } +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_enable_profiling" >&5 +$as_echo "$ac_enable_profiling" >&6; } case "$ac_enable_profiling" in "yes") @@ -4076,8 +4827,8 @@ ;; esac -{ echo "$as_me:$LINENO: checking LDLIBRARY" >&5 -echo $ECHO_N "checking LDLIBRARY... $ECHO_C" >&6; } +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking LDLIBRARY" >&5 +$as_echo_n "checking LDLIBRARY... " >&6; } # MacOSX framework builds need more magic. LDLIBRARY is the dynamic # library that we build, but we do not want to link against it (we @@ -4097,9 +4848,7 @@ # Other platforms follow if test $enable_shared = "yes"; then -cat >>confdefs.h <<\_ACEOF -#define Py_ENABLE_SHARED 1 -_ACEOF +$as_echo "#define Py_ENABLE_SHARED 1" >>confdefs.h case $ac_sys_system in CYGWIN*) @@ -4156,16 +4905,16 @@ esac fi -{ echo "$as_me:$LINENO: result: $LDLIBRARY" >&5 -echo "${ECHO_T}$LDLIBRARY" >&6; } +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $LDLIBRARY" >&5 +$as_echo "$LDLIBRARY" >&6; } if test -n "$ac_tool_prefix"; then # Extract the first word of "${ac_tool_prefix}ranlib", so it can be a program name with args. set dummy ${ac_tool_prefix}ranlib; ac_word=$2 -{ echo "$as_me:$LINENO: checking for $ac_word" >&5 -echo $ECHO_N "checking for $ac_word... $ECHO_C" >&6; } -if test "${ac_cv_prog_RANLIB+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 +$as_echo_n "checking for $ac_word... " >&6; } +if test "${ac_cv_prog_RANLIB+set}" = set; then : + $as_echo_n "(cached) " >&6 else if test -n "$RANLIB"; then ac_cv_prog_RANLIB="$RANLIB" # Let the user override the test. @@ -4175,25 +4924,25 @@ do IFS=$as_save_IFS test -z "$as_dir" && as_dir=. - for ac_exec_ext in '' $ac_executable_extensions; do + for ac_exec_ext in '' $ac_executable_extensions; do if { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_test_x "$as_dir/$ac_word$ac_exec_ext"; }; then ac_cv_prog_RANLIB="${ac_tool_prefix}ranlib" - echo "$as_me:$LINENO: found $as_dir/$ac_word$ac_exec_ext" >&5 + $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 break 2 fi done -done + done IFS=$as_save_IFS fi fi RANLIB=$ac_cv_prog_RANLIB if test -n "$RANLIB"; then - { echo "$as_me:$LINENO: result: $RANLIB" >&5 -echo "${ECHO_T}$RANLIB" >&6; } + { $as_echo "$as_me:${as_lineno-$LINENO}: result: $RANLIB" >&5 +$as_echo "$RANLIB" >&6; } else - { echo "$as_me:$LINENO: result: no" >&5 -echo "${ECHO_T}no" >&6; } + { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 +$as_echo "no" >&6; } fi @@ -4202,10 +4951,10 @@ ac_ct_RANLIB=$RANLIB # Extract the first word of "ranlib", so it can be a program name with args. set dummy ranlib; ac_word=$2 -{ echo "$as_me:$LINENO: checking for $ac_word" >&5 -echo $ECHO_N "checking for $ac_word... $ECHO_C" >&6; } -if test "${ac_cv_prog_ac_ct_RANLIB+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 +$as_echo_n "checking for $ac_word... " >&6; } +if test "${ac_cv_prog_ac_ct_RANLIB+set}" = set; then : + $as_echo_n "(cached) " >&6 else if test -n "$ac_ct_RANLIB"; then ac_cv_prog_ac_ct_RANLIB="$ac_ct_RANLIB" # Let the user override the test. @@ -4215,25 +4964,25 @@ do IFS=$as_save_IFS test -z "$as_dir" && as_dir=. - for ac_exec_ext in '' $ac_executable_extensions; do + for ac_exec_ext in '' $ac_executable_extensions; do if { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_test_x "$as_dir/$ac_word$ac_exec_ext"; }; then ac_cv_prog_ac_ct_RANLIB="ranlib" - echo "$as_me:$LINENO: found $as_dir/$ac_word$ac_exec_ext" >&5 + $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 break 2 fi done -done + done IFS=$as_save_IFS fi fi ac_ct_RANLIB=$ac_cv_prog_ac_ct_RANLIB if test -n "$ac_ct_RANLIB"; then - { echo "$as_me:$LINENO: result: $ac_ct_RANLIB" >&5 -echo "${ECHO_T}$ac_ct_RANLIB" >&6; } + { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_ct_RANLIB" >&5 +$as_echo "$ac_ct_RANLIB" >&6; } else - { echo "$as_me:$LINENO: result: no" >&5 -echo "${ECHO_T}no" >&6; } + { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 +$as_echo "no" >&6; } fi if test "x$ac_ct_RANLIB" = x; then @@ -4241,12 +4990,8 @@ else case $cross_compiling:$ac_tool_warned in yes:) -{ echo "$as_me:$LINENO: WARNING: In the future, Autoconf will not detect cross-tools -whose name does not start with the host triplet. If you think this -configuration is useful to you, please write to autoconf at gnu.org." >&5 -echo "$as_me: WARNING: In the future, Autoconf will not detect cross-tools -whose name does not start with the host triplet. If you think this -configuration is useful to you, please write to autoconf at gnu.org." >&2;} +{ $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: using cross tools not prefixed with host triplet" >&5 +$as_echo "$as_me: WARNING: using cross tools not prefixed with host triplet" >&2;} ac_tool_warned=yes ;; esac RANLIB=$ac_ct_RANLIB @@ -4260,10 +5005,10 @@ do # Extract the first word of "$ac_prog", so it can be a program name with args. set dummy $ac_prog; ac_word=$2 -{ echo "$as_me:$LINENO: checking for $ac_word" >&5 -echo $ECHO_N "checking for $ac_word... $ECHO_C" >&6; } -if test "${ac_cv_prog_AR+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 +$as_echo_n "checking for $ac_word... " >&6; } +if test "${ac_cv_prog_AR+set}" = set; then : + $as_echo_n "(cached) " >&6 else if test -n "$AR"; then ac_cv_prog_AR="$AR" # Let the user override the test. @@ -4273,25 +5018,25 @@ do IFS=$as_save_IFS test -z "$as_dir" && as_dir=. - for ac_exec_ext in '' $ac_executable_extensions; do + for ac_exec_ext in '' $ac_executable_extensions; do if { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_test_x "$as_dir/$ac_word$ac_exec_ext"; }; then ac_cv_prog_AR="$ac_prog" - echo "$as_me:$LINENO: found $as_dir/$ac_word$ac_exec_ext" >&5 + $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 break 2 fi done -done + done IFS=$as_save_IFS fi fi AR=$ac_cv_prog_AR if test -n "$AR"; then - { echo "$as_me:$LINENO: result: $AR" >&5 -echo "${ECHO_T}$AR" >&6; } + { $as_echo "$as_me:${as_lineno-$LINENO}: result: $AR" >&5 +$as_echo "$AR" >&6; } else - { echo "$as_me:$LINENO: result: no" >&5 -echo "${ECHO_T}no" >&6; } + { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 +$as_echo "no" >&6; } fi @@ -4310,10 +5055,10 @@ # Extract the first word of "svnversion", so it can be a program name with args. set dummy svnversion; ac_word=$2 -{ echo "$as_me:$LINENO: checking for $ac_word" >&5 -echo $ECHO_N "checking for $ac_word... $ECHO_C" >&6; } -if test "${ac_cv_prog_SVNVERSION+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 +$as_echo_n "checking for $ac_word... " >&6; } +if test "${ac_cv_prog_SVNVERSION+set}" = set; then : + $as_echo_n "(cached) " >&6 else if test -n "$SVNVERSION"; then ac_cv_prog_SVNVERSION="$SVNVERSION" # Let the user override the test. @@ -4323,14 +5068,14 @@ do IFS=$as_save_IFS test -z "$as_dir" && as_dir=. - for ac_exec_ext in '' $ac_executable_extensions; do + for ac_exec_ext in '' $ac_executable_extensions; do if { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_test_x "$as_dir/$ac_word$ac_exec_ext"; }; then ac_cv_prog_SVNVERSION="found" - echo "$as_me:$LINENO: found $as_dir/$ac_word$ac_exec_ext" >&5 + $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 break 2 fi done -done + done IFS=$as_save_IFS test -z "$ac_cv_prog_SVNVERSION" && ac_cv_prog_SVNVERSION="not-found" @@ -4338,11 +5083,11 @@ fi SVNVERSION=$ac_cv_prog_SVNVERSION if test -n "$SVNVERSION"; then - { echo "$as_me:$LINENO: result: $SVNVERSION" >&5 -echo "${ECHO_T}$SVNVERSION" >&6; } + { $as_echo "$as_me:${as_lineno-$LINENO}: result: $SVNVERSION" >&5 +$as_echo "$SVNVERSION" >&6; } else - { echo "$as_me:$LINENO: result: no" >&5 -echo "${ECHO_T}no" >&6; } + { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 +$as_echo "no" >&6; } fi @@ -4363,24 +5108,16 @@ esac ac_aux_dir= for ac_dir in "$srcdir" "$srcdir/.." "$srcdir/../.."; do - if test -f "$ac_dir/install-sh"; then - ac_aux_dir=$ac_dir - ac_install_sh="$ac_aux_dir/install-sh -c" - break - elif test -f "$ac_dir/install.sh"; then - ac_aux_dir=$ac_dir - ac_install_sh="$ac_aux_dir/install.sh -c" - break - elif test -f "$ac_dir/shtool"; then - ac_aux_dir=$ac_dir - ac_install_sh="$ac_aux_dir/shtool install -c" - break - fi + for ac_t in install-sh install.sh shtool; do + if test -f "$ac_dir/$ac_t"; then + ac_aux_dir=$ac_dir + ac_install_sh="$ac_aux_dir/$ac_t -c" + break 2 + fi + done done if test -z "$ac_aux_dir"; then - { { echo "$as_me:$LINENO: error: cannot find install-sh or install.sh in \"$srcdir\" \"$srcdir/..\" \"$srcdir/../..\"" >&5 -echo "$as_me: error: cannot find install-sh or install.sh in \"$srcdir\" \"$srcdir/..\" \"$srcdir/../..\"" >&2;} - { (exit 1); exit 1; }; } + as_fn_error "cannot find install-sh, install.sh, or shtool in \"$srcdir\" \"$srcdir/..\" \"$srcdir/../..\"" "$LINENO" 5 fi # These three variables are undocumented and unsupported, @@ -4405,22 +5142,23 @@ # SVR4 /usr/ucb/install, which tries to use the nonexistent group "staff" # OS/2's system install, which has a completely different semantic # ./install, which can be erroneously created by make from ./install.sh. -{ echo "$as_me:$LINENO: checking for a BSD-compatible install" >&5 -echo $ECHO_N "checking for a BSD-compatible install... $ECHO_C" >&6; } +# Reject install programs that cannot install multiple files. +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for a BSD-compatible install" >&5 +$as_echo_n "checking for a BSD-compatible install... " >&6; } if test -z "$INSTALL"; then -if test "${ac_cv_path_install+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 +if test "${ac_cv_path_install+set}" = set; then : + $as_echo_n "(cached) " >&6 else as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $PATH do IFS=$as_save_IFS test -z "$as_dir" && as_dir=. - # Account for people who put trailing slashes in PATH elements. -case $as_dir/ in - ./ | .// | /cC/* | \ + # Account for people who put trailing slashes in PATH elements. +case $as_dir/ in #(( + ./ | .// | /[cC]/* | \ /etc/* | /usr/sbin/* | /usr/etc/* | /sbin/* | /usr/afsws/bin/* | \ - ?:\\/os2\\/install\\/* | ?:\\/OS2\\/INSTALL\\/* | \ + ?:[\\/]os2[\\/]install[\\/]* | ?:[\\/]OS2[\\/]INSTALL[\\/]* | \ /usr/ucb/* ) ;; *) # OSF1 and SCO ODT 3.0 have their own names for install. @@ -4438,17 +5176,29 @@ # program-specific install script used by HP pwplus--don't use. : else - ac_cv_path_install="$as_dir/$ac_prog$ac_exec_ext -c" - break 3 + rm -rf conftest.one conftest.two conftest.dir + echo one > conftest.one + echo two > conftest.two + mkdir conftest.dir + if "$as_dir/$ac_prog$ac_exec_ext" -c conftest.one conftest.two "`pwd`/conftest.dir" && + test -s conftest.one && test -s conftest.two && + test -s conftest.dir/conftest.one && + test -s conftest.dir/conftest.two + then + ac_cv_path_install="$as_dir/$ac_prog$ac_exec_ext -c" + break 3 + fi fi fi done done ;; esac -done + + done IFS=$as_save_IFS +rm -rf conftest.one conftest.two conftest.dir fi if test "${ac_cv_path_install+set}" = set; then @@ -4461,8 +5211,8 @@ INSTALL=$ac_install_sh fi fi -{ echo "$as_me:$LINENO: result: $INSTALL" >&5 -echo "${ECHO_T}$INSTALL" >&6; } +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $INSTALL" >&5 +$as_echo "$INSTALL" >&6; } # Use test -z because SunOS4 sh mishandles braces in ${var-val}. # It thinks the first close brace ends the variable substitution. @@ -4483,28 +5233,26 @@ fi # Check for --with-pydebug -{ echo "$as_me:$LINENO: checking for --with-pydebug" >&5 -echo $ECHO_N "checking for --with-pydebug... $ECHO_C" >&6; } +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for --with-pydebug" >&5 +$as_echo_n "checking for --with-pydebug... " >&6; } # Check whether --with-pydebug was given. -if test "${with_pydebug+set}" = set; then +if test "${with_pydebug+set}" = set; then : withval=$with_pydebug; if test "$withval" != no then -cat >>confdefs.h <<\_ACEOF -#define Py_DEBUG 1 -_ACEOF +$as_echo "#define Py_DEBUG 1" >>confdefs.h - { echo "$as_me:$LINENO: result: yes" >&5 -echo "${ECHO_T}yes" >&6; }; + { $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +$as_echo "yes" >&6; }; Py_DEBUG='true' -else { echo "$as_me:$LINENO: result: no" >&5 -echo "${ECHO_T}no" >&6; }; Py_DEBUG='false' +else { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 +$as_echo "no" >&6; }; Py_DEBUG='false' fi else - { echo "$as_me:$LINENO: result: no" >&5 -echo "${ECHO_T}no" >&6; } + { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 +$as_echo "no" >&6; } fi @@ -4574,21 +5322,18 @@ # GCC produce warnings for legal Python code. Enable # -fno-strict-aliasing on versions of GCC that support but produce # warnings. See Issue3326 - { echo "$as_me:$LINENO: checking whether $CC accepts and needs -fno-strict-aliasing" >&5 -echo $ECHO_N "checking whether $CC accepts and needs -fno-strict-aliasing... $ECHO_C" >&6; } + { $as_echo "$as_me:${as_lineno-$LINENO}: checking whether $CC accepts and needs -fno-strict-aliasing" >&5 +$as_echo_n "checking whether $CC accepts and needs -fno-strict-aliasing... " >&6; } ac_save_cc="$CC" CC="$CC -fno-strict-aliasing" save_CFLAGS="$CFLAGS" - if test "${ac_cv_no_strict_aliasing+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 + if test "${ac_cv_no_strict_aliasing+set}" = set; then : + $as_echo_n "(cached) " >&6 else - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF + cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ + int main () { @@ -4596,33 +5341,16 @@ ; return 0; } + _ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - CC="$ac_save_cc -fstrict-aliasing" - CFLAGS="$CFLAGS -Werror -Wstrict-aliasing" - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF +if ac_fn_c_try_compile "$LINENO"; then : + + CC="$ac_save_cc -fstrict-aliasing" + CFLAGS="$CFLAGS -Werror -Wstrict-aliasing" + cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ + int main () { @@ -4630,47 +5358,31 @@ ; return 0; } + _ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - ac_cv_no_strict_aliasing=no +if ac_fn_c_try_compile "$LINENO"; then : + + ac_cv_no_strict_aliasing=no + else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - ac_cv_no_strict_aliasing=yes -fi + ac_cv_no_strict_aliasing=yes +fi rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext + else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - ac_cv_no_strict_aliasing=no -fi + ac_cv_no_strict_aliasing=no +fi rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext fi CFLAGS="$save_CFLAGS" CC="$ac_save_cc" - { echo "$as_me:$LINENO: result: $ac_cv_no_strict_aliasing" >&5 -echo "${ECHO_T}$ac_cv_no_strict_aliasing" >&6; } + { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_no_strict_aliasing" >&5 +$as_echo "$ac_cv_no_strict_aliasing" >&6; } if test $ac_cv_no_strict_aliasing = yes then BASECFLAGS="$BASECFLAGS -fno-strict-aliasing" @@ -4695,8 +5407,8 @@ # used to be here, but non-Apple gcc doesn't accept them. if test "${CC}" = gcc then - { echo "$as_me:$LINENO: checking which compiler should be used" >&5 -echo $ECHO_N "checking which compiler should be used... $ECHO_C" >&6; } + { $as_echo "$as_me:${as_lineno-$LINENO}: checking which compiler should be used" >&5 +$as_echo_n "checking which compiler should be used... " >&6; } case "${UNIVERSALSDK}" in */MacOSX10.4u.sdk) # Build using 10.4 SDK, force usage of gcc when the @@ -4706,8 +5418,8 @@ CPP=cpp-4.0 ;; esac - { echo "$as_me:$LINENO: result: $CC" >&5 -echo "${ECHO_T}$CC" >&6; } + { $as_echo "$as_me:${as_lineno-$LINENO}: result: $CC" >&5 +$as_echo "$CC" >&6; } fi @@ -4738,9 +5450,7 @@ ARCH_RUN_32BIT="/usr/bin/arch -i386 -ppc" else - { { echo "$as_me:$LINENO: error: proper usage is --with-universal-arch=32-bit|64-bit|all|intel|3-way" >&5 -echo "$as_me: error: proper usage is --with-universal-arch=32-bit|64-bit|all|intel|3-way" >&2;} - { (exit 1); exit 1; }; } + as_fn_error "proper usage is --with-universal-arch=32-bit|64-bit|all|intel|3-way" "$LINENO" 5 fi @@ -4834,18 +5544,14 @@ ac_cv_opt_olimit_ok=no fi -{ echo "$as_me:$LINENO: checking whether $CC accepts -OPT:Olimit=0" >&5 -echo $ECHO_N "checking whether $CC accepts -OPT:Olimit=0... $ECHO_C" >&6; } -if test "${ac_cv_opt_olimit_ok+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking whether $CC accepts -OPT:Olimit=0" >&5 +$as_echo_n "checking whether $CC accepts -OPT:Olimit=0... " >&6; } +if test "${ac_cv_opt_olimit_ok+set}" = set; then : + $as_echo_n "(cached) " >&6 else ac_save_cc="$CC" CC="$CC -OPT:Olimit=0" -cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF +cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ int @@ -4856,37 +5562,18 @@ return 0; } _ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then +if ac_fn_c_try_compile "$LINENO"; then : ac_cv_opt_olimit_ok=yes else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 + ac_cv_opt_olimit_ok=no - ac_cv_opt_olimit_ok=no fi - rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext CC="$ac_save_cc" fi -{ echo "$as_me:$LINENO: result: $ac_cv_opt_olimit_ok" >&5 -echo "${ECHO_T}$ac_cv_opt_olimit_ok" >&6; } +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_opt_olimit_ok" >&5 +$as_echo "$ac_cv_opt_olimit_ok" >&6; } if test $ac_cv_opt_olimit_ok = yes; then case $ac_sys_system in # XXX is this branch needed? On MacOSX 10.2.2 the result of the @@ -4899,18 +5586,14 @@ ;; esac else - { echo "$as_me:$LINENO: checking whether $CC accepts -Olimit 1500" >&5 -echo $ECHO_N "checking whether $CC accepts -Olimit 1500... $ECHO_C" >&6; } - if test "${ac_cv_olimit_ok+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 + { $as_echo "$as_me:${as_lineno-$LINENO}: checking whether $CC accepts -Olimit 1500" >&5 +$as_echo_n "checking whether $CC accepts -Olimit 1500... " >&6; } + if test "${ac_cv_olimit_ok+set}" = set; then : + $as_echo_n "(cached) " >&6 else ac_save_cc="$CC" CC="$CC -Olimit 1500" - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF + cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ int @@ -4921,37 +5604,18 @@ return 0; } _ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then +if ac_fn_c_try_compile "$LINENO"; then : ac_cv_olimit_ok=yes else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 + ac_cv_olimit_ok=no - ac_cv_olimit_ok=no fi - rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext CC="$ac_save_cc" fi - { echo "$as_me:$LINENO: result: $ac_cv_olimit_ok" >&5 -echo "${ECHO_T}$ac_cv_olimit_ok" >&6; } + { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_olimit_ok" >&5 +$as_echo "$ac_cv_olimit_ok" >&6; } if test $ac_cv_olimit_ok = yes; then BASECFLAGS="$BASECFLAGS -Olimit 1500" fi @@ -4960,19 +5624,14 @@ # Check whether GCC supports PyArg_ParseTuple format if test "$GCC" = "yes" then - { echo "$as_me:$LINENO: checking whether gcc supports ParseTuple __format__" >&5 -echo $ECHO_N "checking whether gcc supports ParseTuple __format__... $ECHO_C" >&6; } + { $as_echo "$as_me:${as_lineno-$LINENO}: checking whether gcc supports ParseTuple __format__" >&5 +$as_echo_n "checking whether gcc supports ParseTuple __format__... " >&6; } save_CFLAGS=$CFLAGS CFLAGS="$CFLAGS -Werror" - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF + cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ void f(char*,...)__attribute((format(PyArg_ParseTuple, 1, 2))); - int main () { @@ -4980,40 +5639,22 @@ ; return 0; } -_ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then -cat >>confdefs.h <<\_ACEOF -#define HAVE_ATTRIBUTE_FORMAT_PARSETUPLE 1 _ACEOF +if ac_fn_c_try_compile "$LINENO"; then : + + +$as_echo "#define HAVE_ATTRIBUTE_FORMAT_PARSETUPLE 1" >>confdefs.h + + { $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +$as_echo "yes" >&6; } - { echo "$as_me:$LINENO: result: yes" >&5 -echo "${ECHO_T}yes" >&6; } else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - { echo "$as_me:$LINENO: result: no" >&5 -echo "${ECHO_T}no" >&6; } + { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 +$as_echo "no" >&6; } fi - rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext CFLAGS=$save_CFLAGS fi @@ -5023,19 +5664,15 @@ # complain if unaccepted options are passed (e.g. gcc on Mac OS X). # So we have to see first whether pthreads are available without # options before we can check whether -Kpthread improves anything. -{ echo "$as_me:$LINENO: checking whether pthreads are available without options" >&5 -echo $ECHO_N "checking whether pthreads are available without options... $ECHO_C" >&6; } -if test "${ac_cv_pthread_is_default+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking whether pthreads are available without options" >&5 +$as_echo_n "checking whether pthreads are available without options... " >&6; } +if test "${ac_cv_pthread_is_default+set}" = set; then : + $as_echo_n "(cached) " >&6 else - if test "$cross_compiling" = yes; then + if test "$cross_compiling" = yes; then : ac_cv_pthread_is_default=no else - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF + cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ #include @@ -5051,48 +5688,24 @@ } _ACEOF -rm -f conftest$ac_exeext -if { (ac_try="$ac_link" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_link") 2>&5 - ac_status=$? - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { ac_try='./conftest$ac_exeext' - { (case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_try") 2>&5 - ac_status=$? - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); }; }; then +if ac_fn_c_try_run "$LINENO"; then : ac_cv_pthread_is_default=yes ac_cv_kthread=no ac_cv_pthread=no else - echo "$as_me: program exited with status $ac_status" >&5 -echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - -( exit $ac_status ) -ac_cv_pthread_is_default=no + ac_cv_pthread_is_default=no fi -rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext conftest.$ac_objext conftest.$ac_ext +rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext \ + conftest.$ac_objext conftest.beam conftest.$ac_ext fi - fi -{ echo "$as_me:$LINENO: result: $ac_cv_pthread_is_default" >&5 -echo "${ECHO_T}$ac_cv_pthread_is_default" >&6; } +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_pthread_is_default" >&5 +$as_echo "$ac_cv_pthread_is_default" >&6; } if test $ac_cv_pthread_is_default = yes @@ -5104,21 +5717,17 @@ # Some compilers won't report that they do not support -Kpthread, # so we need to run a program to see whether it really made the # function available. -{ echo "$as_me:$LINENO: checking whether $CC accepts -Kpthread" >&5 -echo $ECHO_N "checking whether $CC accepts -Kpthread... $ECHO_C" >&6; } -if test "${ac_cv_kpthread+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking whether $CC accepts -Kpthread" >&5 +$as_echo_n "checking whether $CC accepts -Kpthread... " >&6; } +if test "${ac_cv_kpthread+set}" = set; then : + $as_echo_n "(cached) " >&6 else ac_save_cc="$CC" CC="$CC -Kpthread" -if test "$cross_compiling" = yes; then +if test "$cross_compiling" = yes; then : ac_cv_kpthread=no else - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF + cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ #include @@ -5134,44 +5743,20 @@ } _ACEOF -rm -f conftest$ac_exeext -if { (ac_try="$ac_link" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_link") 2>&5 - ac_status=$? - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { ac_try='./conftest$ac_exeext' - { (case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_try") 2>&5 - ac_status=$? - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); }; }; then +if ac_fn_c_try_run "$LINENO"; then : ac_cv_kpthread=yes else - echo "$as_me: program exited with status $ac_status" >&5 -echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - -( exit $ac_status ) -ac_cv_kpthread=no + ac_cv_kpthread=no fi -rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext conftest.$ac_objext conftest.$ac_ext +rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext \ + conftest.$ac_objext conftest.beam conftest.$ac_ext fi - CC="$ac_save_cc" fi -{ echo "$as_me:$LINENO: result: $ac_cv_kpthread" >&5 -echo "${ECHO_T}$ac_cv_kpthread" >&6; } +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_kpthread" >&5 +$as_echo "$ac_cv_kpthread" >&6; } fi if test $ac_cv_kpthread = no -a $ac_cv_pthread_is_default = no @@ -5181,21 +5766,17 @@ # Some compilers won't report that they do not support -Kthread, # so we need to run a program to see whether it really made the # function available. -{ echo "$as_me:$LINENO: checking whether $CC accepts -Kthread" >&5 -echo $ECHO_N "checking whether $CC accepts -Kthread... $ECHO_C" >&6; } -if test "${ac_cv_kthread+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking whether $CC accepts -Kthread" >&5 +$as_echo_n "checking whether $CC accepts -Kthread... " >&6; } +if test "${ac_cv_kthread+set}" = set; then : + $as_echo_n "(cached) " >&6 else ac_save_cc="$CC" CC="$CC -Kthread" -if test "$cross_compiling" = yes; then +if test "$cross_compiling" = yes; then : ac_cv_kthread=no else - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF + cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ #include @@ -5211,44 +5792,20 @@ } _ACEOF -rm -f conftest$ac_exeext -if { (ac_try="$ac_link" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_link") 2>&5 - ac_status=$? - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { ac_try='./conftest$ac_exeext' - { (case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_try") 2>&5 - ac_status=$? - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); }; }; then +if ac_fn_c_try_run "$LINENO"; then : ac_cv_kthread=yes else - echo "$as_me: program exited with status $ac_status" >&5 -echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - -( exit $ac_status ) -ac_cv_kthread=no + ac_cv_kthread=no fi -rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext conftest.$ac_objext conftest.$ac_ext +rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext \ + conftest.$ac_objext conftest.beam conftest.$ac_ext fi - CC="$ac_save_cc" fi -{ echo "$as_me:$LINENO: result: $ac_cv_kthread" >&5 -echo "${ECHO_T}$ac_cv_kthread" >&6; } +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_kthread" >&5 +$as_echo "$ac_cv_kthread" >&6; } fi if test $ac_cv_kthread = no -a $ac_cv_pthread_is_default = no @@ -5258,21 +5815,17 @@ # Some compilers won't report that they do not support -pthread, # so we need to run a program to see whether it really made the # function available. -{ echo "$as_me:$LINENO: checking whether $CC accepts -pthread" >&5 -echo $ECHO_N "checking whether $CC accepts -pthread... $ECHO_C" >&6; } -if test "${ac_cv_thread+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking whether $CC accepts -pthread" >&5 +$as_echo_n "checking whether $CC accepts -pthread... " >&6; } +if test "${ac_cv_thread+set}" = set; then : + $as_echo_n "(cached) " >&6 else ac_save_cc="$CC" CC="$CC -pthread" -if test "$cross_compiling" = yes; then +if test "$cross_compiling" = yes; then : ac_cv_pthread=no else - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF + cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ #include @@ -5288,44 +5841,20 @@ } _ACEOF -rm -f conftest$ac_exeext -if { (ac_try="$ac_link" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_link") 2>&5 - ac_status=$? - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { ac_try='./conftest$ac_exeext' - { (case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_try") 2>&5 - ac_status=$? - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); }; }; then +if ac_fn_c_try_run "$LINENO"; then : ac_cv_pthread=yes else - echo "$as_me: program exited with status $ac_status" >&5 -echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - -( exit $ac_status ) -ac_cv_pthread=no + ac_cv_pthread=no fi -rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext conftest.$ac_objext conftest.$ac_ext +rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext \ + conftest.$ac_objext conftest.beam conftest.$ac_ext fi - CC="$ac_save_cc" fi -{ echo "$as_me:$LINENO: result: $ac_cv_pthread" >&5 -echo "${ECHO_T}$ac_cv_pthread" >&6; } +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_pthread" >&5 +$as_echo "$ac_cv_pthread" >&6; } fi # If we have set a CC compiler flag for thread support then @@ -5333,8 +5862,8 @@ ac_cv_cxx_thread=no if test ! -z "$CXX" then -{ echo "$as_me:$LINENO: checking whether $CXX also accepts flags for thread support" >&5 -echo $ECHO_N "checking whether $CXX also accepts flags for thread support... $ECHO_C" >&6; } +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking whether $CXX also accepts flags for thread support" >&5 +$as_echo_n "checking whether $CXX also accepts flags for thread support... " >&6; } ac_save_cxx="$CXX" if test "$ac_cv_kpthread" = "yes" @@ -5364,23 +5893,19 @@ fi rm -fr conftest* fi -{ echo "$as_me:$LINENO: result: $ac_cv_cxx_thread" >&5 -echo "${ECHO_T}$ac_cv_cxx_thread" >&6; } +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_cxx_thread" >&5 +$as_echo "$ac_cv_cxx_thread" >&6; } fi CXX="$ac_save_cxx" # checks for header files -{ echo "$as_me:$LINENO: checking for ANSI C header files" >&5 -echo $ECHO_N "checking for ANSI C header files... $ECHO_C" >&6; } -if test "${ac_cv_header_stdc+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for ANSI C header files" >&5 +$as_echo_n "checking for ANSI C header files... " >&6; } +if test "${ac_cv_header_stdc+set}" = set; then : + $as_echo_n "(cached) " >&6 else - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF + cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ #include #include @@ -5395,85 +5920,53 @@ return 0; } _ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then +if ac_fn_c_try_compile "$LINENO"; then : ac_cv_header_stdc=yes else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - ac_cv_header_stdc=no + ac_cv_header_stdc=no fi - rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext if test $ac_cv_header_stdc = yes; then # SunOS 4.x string.h does not declare mem*, contrary to ANSI. - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF + cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ #include _ACEOF if (eval "$ac_cpp conftest.$ac_ext") 2>&5 | - $EGREP "memchr" >/dev/null 2>&1; then - : + $EGREP "memchr" >/dev/null 2>&1; then : + else ac_cv_header_stdc=no fi -rm -f -r conftest* +rm -f conftest* fi if test $ac_cv_header_stdc = yes; then # ISC 2.0.2 stdlib.h does not declare free, contrary to ANSI. - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF + cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ #include _ACEOF if (eval "$ac_cpp conftest.$ac_ext") 2>&5 | - $EGREP "free" >/dev/null 2>&1; then - : + $EGREP "free" >/dev/null 2>&1; then : + else ac_cv_header_stdc=no fi -rm -f -r conftest* +rm -f conftest* fi if test $ac_cv_header_stdc = yes; then # /bin/cc in Irix-4.0.5 gets non-ANSI ctype macros unless using -ansi. - if test "$cross_compiling" = yes; then + if test "$cross_compiling" = yes; then : : else - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF + cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ #include #include @@ -5500,176 +5993,25 @@ return 0; } _ACEOF -rm -f conftest$ac_exeext -if { (ac_try="$ac_link" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_link") 2>&5 - ac_status=$? - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { ac_try='./conftest$ac_exeext' - { (case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_try") 2>&5 - ac_status=$? - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); }; }; then - : -else - echo "$as_me: program exited with status $ac_status" >&5 -echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 +if ac_fn_c_try_run "$LINENO"; then : -( exit $ac_status ) -ac_cv_header_stdc=no +else + ac_cv_header_stdc=no fi -rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext conftest.$ac_objext conftest.$ac_ext +rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext \ + conftest.$ac_objext conftest.beam conftest.$ac_ext fi - fi fi -{ echo "$as_me:$LINENO: result: $ac_cv_header_stdc" >&5 -echo "${ECHO_T}$ac_cv_header_stdc" >&6; } +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_header_stdc" >&5 +$as_echo "$ac_cv_header_stdc" >&6; } if test $ac_cv_header_stdc = yes; then -cat >>confdefs.h <<\_ACEOF -#define STDC_HEADERS 1 -_ACEOF - -fi - -# On IRIX 5.3, sys/types and inttypes.h are conflicting. - - - - - - - - - -for ac_header in sys/types.h sys/stat.h stdlib.h string.h memory.h strings.h \ - inttypes.h stdint.h unistd.h -do -as_ac_Header=`echo "ac_cv_header_$ac_header" | $as_tr_sh` -{ echo "$as_me:$LINENO: checking for $ac_header" >&5 -echo $ECHO_N "checking for $ac_header... $ECHO_C" >&6; } -if { as_var=$as_ac_Header; eval "test \"\${$as_var+set}\" = set"; }; then - echo $ECHO_N "(cached) $ECHO_C" >&6 -else - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -$ac_includes_default - -#include <$ac_header> -_ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - eval "$as_ac_Header=yes" -else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - eval "$as_ac_Header=no" -fi - -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext -fi -ac_res=`eval echo '${'$as_ac_Header'}'` - { echo "$as_me:$LINENO: result: $ac_res" >&5 -echo "${ECHO_T}$ac_res" >&6; } -if test `eval echo '${'$as_ac_Header'}'` = yes; then - cat >>confdefs.h <<_ACEOF -#define `echo "HAVE_$ac_header" | $as_tr_cpp` 1 -_ACEOF +$as_echo "#define STDC_HEADERS 1" >>confdefs.h fi -done - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - for ac_header in asm/types.h conio.h curses.h direct.h dlfcn.h errno.h \ fcntl.h grp.h \ ieeefp.h io.h langinfo.h libintl.h ncurses.h poll.h process.h pthread.h \ @@ -5682,167 +6024,28 @@ sys/times.h sys/types.h sys/un.h sys/utsname.h sys/wait.h pty.h libutil.h \ sys/resource.h netpacket/packet.h sysexits.h bluetooth.h \ bluetooth/bluetooth.h linux/tipc.h spawn.h util.h -do -as_ac_Header=`echo "ac_cv_header_$ac_header" | $as_tr_sh` -if { as_var=$as_ac_Header; eval "test \"\${$as_var+set}\" = set"; }; then - { echo "$as_me:$LINENO: checking for $ac_header" >&5 -echo $ECHO_N "checking for $ac_header... $ECHO_C" >&6; } -if { as_var=$as_ac_Header; eval "test \"\${$as_var+set}\" = set"; }; then - echo $ECHO_N "(cached) $ECHO_C" >&6 -fi -ac_res=`eval echo '${'$as_ac_Header'}'` - { echo "$as_me:$LINENO: result: $ac_res" >&5 -echo "${ECHO_T}$ac_res" >&6; } -else - # Is the header compilable? -{ echo "$as_me:$LINENO: checking $ac_header usability" >&5 -echo $ECHO_N "checking $ac_header usability... $ECHO_C" >&6; } -cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -$ac_includes_default -#include <$ac_header> -_ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - ac_header_compiler=yes -else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - ac_header_compiler=no -fi - -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext -{ echo "$as_me:$LINENO: result: $ac_header_compiler" >&5 -echo "${ECHO_T}$ac_header_compiler" >&6; } - -# Is the header present? -{ echo "$as_me:$LINENO: checking $ac_header presence" >&5 -echo $ECHO_N "checking $ac_header presence... $ECHO_C" >&6; } -cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -#include <$ac_header> -_ACEOF -if { (ac_try="$ac_cpp conftest.$ac_ext" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_cpp conftest.$ac_ext") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } >/dev/null && { - test -z "$ac_c_preproc_warn_flag$ac_c_werror_flag" || - test ! -s conftest.err - }; then - ac_header_preproc=yes -else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - ac_header_preproc=no -fi - -rm -f conftest.err conftest.$ac_ext -{ echo "$as_me:$LINENO: result: $ac_header_preproc" >&5 -echo "${ECHO_T}$ac_header_preproc" >&6; } - -# So? What about this header? -case $ac_header_compiler:$ac_header_preproc:$ac_c_preproc_warn_flag in - yes:no: ) - { echo "$as_me:$LINENO: WARNING: $ac_header: accepted by the compiler, rejected by the preprocessor!" >&5 -echo "$as_me: WARNING: $ac_header: accepted by the compiler, rejected by the preprocessor!" >&2;} - { echo "$as_me:$LINENO: WARNING: $ac_header: proceeding with the compiler's result" >&5 -echo "$as_me: WARNING: $ac_header: proceeding with the compiler's result" >&2;} - ac_header_preproc=yes - ;; - no:yes:* ) - { echo "$as_me:$LINENO: WARNING: $ac_header: present but cannot be compiled" >&5 -echo "$as_me: WARNING: $ac_header: present but cannot be compiled" >&2;} - { echo "$as_me:$LINENO: WARNING: $ac_header: check for missing prerequisite headers?" >&5 -echo "$as_me: WARNING: $ac_header: check for missing prerequisite headers?" >&2;} - { echo "$as_me:$LINENO: WARNING: $ac_header: see the Autoconf documentation" >&5 -echo "$as_me: WARNING: $ac_header: see the Autoconf documentation" >&2;} - { echo "$as_me:$LINENO: WARNING: $ac_header: section \"Present But Cannot Be Compiled\"" >&5 -echo "$as_me: WARNING: $ac_header: section \"Present But Cannot Be Compiled\"" >&2;} - { echo "$as_me:$LINENO: WARNING: $ac_header: proceeding with the preprocessor's result" >&5 -echo "$as_me: WARNING: $ac_header: proceeding with the preprocessor's result" >&2;} - { echo "$as_me:$LINENO: WARNING: $ac_header: in the future, the compiler will take precedence" >&5 -echo "$as_me: WARNING: $ac_header: in the future, the compiler will take precedence" >&2;} - ( cat <<\_ASBOX -## -------------------------------------- ## -## Report this to http://bugs.python.org/ ## -## -------------------------------------- ## -_ASBOX - ) | sed "s/^/$as_me: WARNING: /" >&2 - ;; -esac -{ echo "$as_me:$LINENO: checking for $ac_header" >&5 -echo $ECHO_N "checking for $ac_header... $ECHO_C" >&6; } -if { as_var=$as_ac_Header; eval "test \"\${$as_var+set}\" = set"; }; then - echo $ECHO_N "(cached) $ECHO_C" >&6 -else - eval "$as_ac_Header=\$ac_header_preproc" -fi -ac_res=`eval echo '${'$as_ac_Header'}'` - { echo "$as_me:$LINENO: result: $ac_res" >&5 -echo "${ECHO_T}$ac_res" >&6; } - -fi -if test `eval echo '${'$as_ac_Header'}'` = yes; then +do : + as_ac_Header=`$as_echo "ac_cv_header_$ac_header" | $as_tr_sh` +ac_fn_c_check_header_mongrel "$LINENO" "$ac_header" "$as_ac_Header" "$ac_includes_default" +eval as_val=\$$as_ac_Header + if test "x$as_val" = x""yes; then : cat >>confdefs.h <<_ACEOF -#define `echo "HAVE_$ac_header" | $as_tr_cpp` 1 +#define `$as_echo "HAVE_$ac_header" | $as_tr_cpp` 1 _ACEOF fi done - - - - - ac_header_dirent=no for ac_hdr in dirent.h sys/ndir.h sys/dir.h ndir.h; do - as_ac_Header=`echo "ac_cv_header_dirent_$ac_hdr" | $as_tr_sh` -{ echo "$as_me:$LINENO: checking for $ac_hdr that defines DIR" >&5 -echo $ECHO_N "checking for $ac_hdr that defines DIR... $ECHO_C" >&6; } -if { as_var=$as_ac_Header; eval "test \"\${$as_var+set}\" = set"; }; then - echo $ECHO_N "(cached) $ECHO_C" >&6 + as_ac_Header=`$as_echo "ac_cv_header_dirent_$ac_hdr" | $as_tr_sh` +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_hdr that defines DIR" >&5 +$as_echo_n "checking for $ac_hdr that defines DIR... " >&6; } +if { as_var=$as_ac_Header; eval "test \"\${$as_var+set}\" = set"; }; then : + $as_echo_n "(cached) " >&6 else - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF + cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ #include #include <$ac_hdr> @@ -5856,39 +6059,20 @@ return 0; } _ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then +if ac_fn_c_try_compile "$LINENO"; then : eval "$as_ac_Header=yes" else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - eval "$as_ac_Header=no" + eval "$as_ac_Header=no" fi - rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext fi -ac_res=`eval echo '${'$as_ac_Header'}'` - { echo "$as_me:$LINENO: result: $ac_res" >&5 -echo "${ECHO_T}$ac_res" >&6; } -if test `eval echo '${'$as_ac_Header'}'` = yes; then +eval ac_res=\$$as_ac_Header + { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_res" >&5 +$as_echo "$ac_res" >&6; } +eval as_val=\$$as_ac_Header + if test "x$as_val" = x""yes; then : cat >>confdefs.h <<_ACEOF -#define `echo "HAVE_$ac_hdr" | $as_tr_cpp` 1 +#define `$as_echo "HAVE_$ac_hdr" | $as_tr_cpp` 1 _ACEOF ac_header_dirent=$ac_hdr; break @@ -5897,17 +6081,13 @@ done # Two versions of opendir et al. are in -ldir and -lx on SCO Xenix. if test $ac_header_dirent = dirent.h; then - { echo "$as_me:$LINENO: checking for library containing opendir" >&5 -echo $ECHO_N "checking for library containing opendir... $ECHO_C" >&6; } -if test "${ac_cv_search_opendir+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 + { $as_echo "$as_me:${as_lineno-$LINENO}: checking for library containing opendir" >&5 +$as_echo_n "checking for library containing opendir... " >&6; } +if test "${ac_cv_search_opendir+set}" = set; then : + $as_echo_n "(cached) " >&6 else ac_func_search_save_LIBS=$LIBS -cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF +cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ /* Override any GCC internal prototype to avoid an error. @@ -5932,66 +6112,39 @@ ac_res=-l$ac_lib LIBS="-l$ac_lib $ac_func_search_save_LIBS" fi - rm -f conftest.$ac_objext conftest$ac_exeext -if { (ac_try="$ac_link" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_link") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest$ac_exeext && - $as_test_x conftest$ac_exeext; then + if ac_fn_c_try_link "$LINENO"; then : ac_cv_search_opendir=$ac_res -else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - fi - -rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \ - conftest$ac_exeext - if test "${ac_cv_search_opendir+set}" = set; then +rm -f core conftest.err conftest.$ac_objext \ + conftest$ac_exeext + if test "${ac_cv_search_opendir+set}" = set; then : break fi done -if test "${ac_cv_search_opendir+set}" = set; then - : +if test "${ac_cv_search_opendir+set}" = set; then : + else ac_cv_search_opendir=no fi rm conftest.$ac_ext LIBS=$ac_func_search_save_LIBS fi -{ echo "$as_me:$LINENO: result: $ac_cv_search_opendir" >&5 -echo "${ECHO_T}$ac_cv_search_opendir" >&6; } +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_search_opendir" >&5 +$as_echo "$ac_cv_search_opendir" >&6; } ac_res=$ac_cv_search_opendir -if test "$ac_res" != no; then +if test "$ac_res" != no; then : test "$ac_res" = "none required" || LIBS="$ac_res $LIBS" fi else - { echo "$as_me:$LINENO: checking for library containing opendir" >&5 -echo $ECHO_N "checking for library containing opendir... $ECHO_C" >&6; } -if test "${ac_cv_search_opendir+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 + { $as_echo "$as_me:${as_lineno-$LINENO}: checking for library containing opendir" >&5 +$as_echo_n "checking for library containing opendir... " >&6; } +if test "${ac_cv_search_opendir+set}" = set; then : + $as_echo_n "(cached) " >&6 else ac_func_search_save_LIBS=$LIBS -cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF +cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ /* Override any GCC internal prototype to avoid an error. @@ -6016,66 +6169,39 @@ ac_res=-l$ac_lib LIBS="-l$ac_lib $ac_func_search_save_LIBS" fi - rm -f conftest.$ac_objext conftest$ac_exeext -if { (ac_try="$ac_link" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_link") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest$ac_exeext && - $as_test_x conftest$ac_exeext; then + if ac_fn_c_try_link "$LINENO"; then : ac_cv_search_opendir=$ac_res -else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - fi - -rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \ - conftest$ac_exeext - if test "${ac_cv_search_opendir+set}" = set; then +rm -f core conftest.err conftest.$ac_objext \ + conftest$ac_exeext + if test "${ac_cv_search_opendir+set}" = set; then : break fi done -if test "${ac_cv_search_opendir+set}" = set; then - : +if test "${ac_cv_search_opendir+set}" = set; then : + else ac_cv_search_opendir=no fi rm conftest.$ac_ext LIBS=$ac_func_search_save_LIBS fi -{ echo "$as_me:$LINENO: result: $ac_cv_search_opendir" >&5 -echo "${ECHO_T}$ac_cv_search_opendir" >&6; } +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_search_opendir" >&5 +$as_echo "$ac_cv_search_opendir" >&6; } ac_res=$ac_cv_search_opendir -if test "$ac_res" != no; then +if test "$ac_res" != no; then : test "$ac_res" = "none required" || LIBS="$ac_res $LIBS" fi fi -{ echo "$as_me:$LINENO: checking whether sys/types.h defines makedev" >&5 -echo $ECHO_N "checking whether sys/types.h defines makedev... $ECHO_C" >&6; } -if test "${ac_cv_header_sys_types_h_makedev+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking whether sys/types.h defines makedev" >&5 +$as_echo_n "checking whether sys/types.h defines makedev... " >&6; } +if test "${ac_cv_header_sys_types_h_makedev+set}" = set; then : + $as_echo_n "(cached) " >&6 else - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF + cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ #include int @@ -6086,316 +6212,33 @@ return 0; } _ACEOF -rm -f conftest.$ac_objext conftest$ac_exeext -if { (ac_try="$ac_link" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_link") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest$ac_exeext && - $as_test_x conftest$ac_exeext; then +if ac_fn_c_try_link "$LINENO"; then : ac_cv_header_sys_types_h_makedev=yes else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - ac_cv_header_sys_types_h_makedev=no + ac_cv_header_sys_types_h_makedev=no fi - -rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \ - conftest$ac_exeext conftest.$ac_ext +rm -f core conftest.err conftest.$ac_objext \ + conftest$ac_exeext conftest.$ac_ext fi -{ echo "$as_me:$LINENO: result: $ac_cv_header_sys_types_h_makedev" >&5 -echo "${ECHO_T}$ac_cv_header_sys_types_h_makedev" >&6; } +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_header_sys_types_h_makedev" >&5 +$as_echo "$ac_cv_header_sys_types_h_makedev" >&6; } if test $ac_cv_header_sys_types_h_makedev = no; then -if test "${ac_cv_header_sys_mkdev_h+set}" = set; then - { echo "$as_me:$LINENO: checking for sys/mkdev.h" >&5 -echo $ECHO_N "checking for sys/mkdev.h... $ECHO_C" >&6; } -if test "${ac_cv_header_sys_mkdev_h+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 -fi -{ echo "$as_me:$LINENO: result: $ac_cv_header_sys_mkdev_h" >&5 -echo "${ECHO_T}$ac_cv_header_sys_mkdev_h" >&6; } -else - # Is the header compilable? -{ echo "$as_me:$LINENO: checking sys/mkdev.h usability" >&5 -echo $ECHO_N "checking sys/mkdev.h usability... $ECHO_C" >&6; } -cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -$ac_includes_default -#include -_ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - ac_header_compiler=yes -else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - ac_header_compiler=no -fi - -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext -{ echo "$as_me:$LINENO: result: $ac_header_compiler" >&5 -echo "${ECHO_T}$ac_header_compiler" >&6; } - -# Is the header present? -{ echo "$as_me:$LINENO: checking sys/mkdev.h presence" >&5 -echo $ECHO_N "checking sys/mkdev.h presence... $ECHO_C" >&6; } -cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -#include -_ACEOF -if { (ac_try="$ac_cpp conftest.$ac_ext" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_cpp conftest.$ac_ext") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } >/dev/null && { - test -z "$ac_c_preproc_warn_flag$ac_c_werror_flag" || - test ! -s conftest.err - }; then - ac_header_preproc=yes -else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - ac_header_preproc=no -fi - -rm -f conftest.err conftest.$ac_ext -{ echo "$as_me:$LINENO: result: $ac_header_preproc" >&5 -echo "${ECHO_T}$ac_header_preproc" >&6; } - -# So? What about this header? -case $ac_header_compiler:$ac_header_preproc:$ac_c_preproc_warn_flag in - yes:no: ) - { echo "$as_me:$LINENO: WARNING: sys/mkdev.h: accepted by the compiler, rejected by the preprocessor!" >&5 -echo "$as_me: WARNING: sys/mkdev.h: accepted by the compiler, rejected by the preprocessor!" >&2;} - { echo "$as_me:$LINENO: WARNING: sys/mkdev.h: proceeding with the compiler's result" >&5 -echo "$as_me: WARNING: sys/mkdev.h: proceeding with the compiler's result" >&2;} - ac_header_preproc=yes - ;; - no:yes:* ) - { echo "$as_me:$LINENO: WARNING: sys/mkdev.h: present but cannot be compiled" >&5 -echo "$as_me: WARNING: sys/mkdev.h: present but cannot be compiled" >&2;} - { echo "$as_me:$LINENO: WARNING: sys/mkdev.h: check for missing prerequisite headers?" >&5 -echo "$as_me: WARNING: sys/mkdev.h: check for missing prerequisite headers?" >&2;} - { echo "$as_me:$LINENO: WARNING: sys/mkdev.h: see the Autoconf documentation" >&5 -echo "$as_me: WARNING: sys/mkdev.h: see the Autoconf documentation" >&2;} - { echo "$as_me:$LINENO: WARNING: sys/mkdev.h: section \"Present But Cannot Be Compiled\"" >&5 -echo "$as_me: WARNING: sys/mkdev.h: section \"Present But Cannot Be Compiled\"" >&2;} - { echo "$as_me:$LINENO: WARNING: sys/mkdev.h: proceeding with the preprocessor's result" >&5 -echo "$as_me: WARNING: sys/mkdev.h: proceeding with the preprocessor's result" >&2;} - { echo "$as_me:$LINENO: WARNING: sys/mkdev.h: in the future, the compiler will take precedence" >&5 -echo "$as_me: WARNING: sys/mkdev.h: in the future, the compiler will take precedence" >&2;} - ( cat <<\_ASBOX -## -------------------------------------- ## -## Report this to http://bugs.python.org/ ## -## -------------------------------------- ## -_ASBOX - ) | sed "s/^/$as_me: WARNING: /" >&2 - ;; -esac -{ echo "$as_me:$LINENO: checking for sys/mkdev.h" >&5 -echo $ECHO_N "checking for sys/mkdev.h... $ECHO_C" >&6; } -if test "${ac_cv_header_sys_mkdev_h+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 -else - ac_cv_header_sys_mkdev_h=$ac_header_preproc -fi -{ echo "$as_me:$LINENO: result: $ac_cv_header_sys_mkdev_h" >&5 -echo "${ECHO_T}$ac_cv_header_sys_mkdev_h" >&6; } - -fi -if test $ac_cv_header_sys_mkdev_h = yes; then +ac_fn_c_check_header_mongrel "$LINENO" "sys/mkdev.h" "ac_cv_header_sys_mkdev_h" "$ac_includes_default" +if test "x$ac_cv_header_sys_mkdev_h" = x""yes; then : -cat >>confdefs.h <<\_ACEOF -#define MAJOR_IN_MKDEV 1 -_ACEOF +$as_echo "#define MAJOR_IN_MKDEV 1" >>confdefs.h fi if test $ac_cv_header_sys_mkdev_h = no; then - if test "${ac_cv_header_sys_sysmacros_h+set}" = set; then - { echo "$as_me:$LINENO: checking for sys/sysmacros.h" >&5 -echo $ECHO_N "checking for sys/sysmacros.h... $ECHO_C" >&6; } -if test "${ac_cv_header_sys_sysmacros_h+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 -fi -{ echo "$as_me:$LINENO: result: $ac_cv_header_sys_sysmacros_h" >&5 -echo "${ECHO_T}$ac_cv_header_sys_sysmacros_h" >&6; } -else - # Is the header compilable? -{ echo "$as_me:$LINENO: checking sys/sysmacros.h usability" >&5 -echo $ECHO_N "checking sys/sysmacros.h usability... $ECHO_C" >&6; } -cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -$ac_includes_default -#include -_ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - ac_header_compiler=yes -else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - ac_header_compiler=no -fi - -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext -{ echo "$as_me:$LINENO: result: $ac_header_compiler" >&5 -echo "${ECHO_T}$ac_header_compiler" >&6; } - -# Is the header present? -{ echo "$as_me:$LINENO: checking sys/sysmacros.h presence" >&5 -echo $ECHO_N "checking sys/sysmacros.h presence... $ECHO_C" >&6; } -cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -#include -_ACEOF -if { (ac_try="$ac_cpp conftest.$ac_ext" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_cpp conftest.$ac_ext") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } >/dev/null && { - test -z "$ac_c_preproc_warn_flag$ac_c_werror_flag" || - test ! -s conftest.err - }; then - ac_header_preproc=yes -else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - ac_header_preproc=no -fi - -rm -f conftest.err conftest.$ac_ext -{ echo "$as_me:$LINENO: result: $ac_header_preproc" >&5 -echo "${ECHO_T}$ac_header_preproc" >&6; } - -# So? What about this header? -case $ac_header_compiler:$ac_header_preproc:$ac_c_preproc_warn_flag in - yes:no: ) - { echo "$as_me:$LINENO: WARNING: sys/sysmacros.h: accepted by the compiler, rejected by the preprocessor!" >&5 -echo "$as_me: WARNING: sys/sysmacros.h: accepted by the compiler, rejected by the preprocessor!" >&2;} - { echo "$as_me:$LINENO: WARNING: sys/sysmacros.h: proceeding with the compiler's result" >&5 -echo "$as_me: WARNING: sys/sysmacros.h: proceeding with the compiler's result" >&2;} - ac_header_preproc=yes - ;; - no:yes:* ) - { echo "$as_me:$LINENO: WARNING: sys/sysmacros.h: present but cannot be compiled" >&5 -echo "$as_me: WARNING: sys/sysmacros.h: present but cannot be compiled" >&2;} - { echo "$as_me:$LINENO: WARNING: sys/sysmacros.h: check for missing prerequisite headers?" >&5 -echo "$as_me: WARNING: sys/sysmacros.h: check for missing prerequisite headers?" >&2;} - { echo "$as_me:$LINENO: WARNING: sys/sysmacros.h: see the Autoconf documentation" >&5 -echo "$as_me: WARNING: sys/sysmacros.h: see the Autoconf documentation" >&2;} - { echo "$as_me:$LINENO: WARNING: sys/sysmacros.h: section \"Present But Cannot Be Compiled\"" >&5 -echo "$as_me: WARNING: sys/sysmacros.h: section \"Present But Cannot Be Compiled\"" >&2;} - { echo "$as_me:$LINENO: WARNING: sys/sysmacros.h: proceeding with the preprocessor's result" >&5 -echo "$as_me: WARNING: sys/sysmacros.h: proceeding with the preprocessor's result" >&2;} - { echo "$as_me:$LINENO: WARNING: sys/sysmacros.h: in the future, the compiler will take precedence" >&5 -echo "$as_me: WARNING: sys/sysmacros.h: in the future, the compiler will take precedence" >&2;} - ( cat <<\_ASBOX -## -------------------------------------- ## -## Report this to http://bugs.python.org/ ## -## -------------------------------------- ## -_ASBOX - ) | sed "s/^/$as_me: WARNING: /" >&2 - ;; -esac -{ echo "$as_me:$LINENO: checking for sys/sysmacros.h" >&5 -echo $ECHO_N "checking for sys/sysmacros.h... $ECHO_C" >&6; } -if test "${ac_cv_header_sys_sysmacros_h+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 -else - ac_cv_header_sys_sysmacros_h=$ac_header_preproc -fi -{ echo "$as_me:$LINENO: result: $ac_cv_header_sys_sysmacros_h" >&5 -echo "${ECHO_T}$ac_cv_header_sys_sysmacros_h" >&6; } - -fi -if test $ac_cv_header_sys_sysmacros_h = yes; then + ac_fn_c_check_header_mongrel "$LINENO" "sys/sysmacros.h" "ac_cv_header_sys_sysmacros_h" "$ac_includes_default" +if test "x$ac_cv_header_sys_sysmacros_h" = x""yes; then : -cat >>confdefs.h <<\_ACEOF -#define MAJOR_IN_SYSMACROS 1 -_ACEOF +$as_echo "#define MAJOR_IN_SYSMACROS 1" >>confdefs.h fi @@ -6405,62 +6248,17 @@ # On Solaris, term.h requires curses.h - for ac_header in term.h -do -as_ac_Header=`echo "ac_cv_header_$ac_header" | $as_tr_sh` -{ echo "$as_me:$LINENO: checking for $ac_header" >&5 -echo $ECHO_N "checking for $ac_header... $ECHO_C" >&6; } -if { as_var=$as_ac_Header; eval "test \"\${$as_var+set}\" = set"; }; then - echo $ECHO_N "(cached) $ECHO_C" >&6 -else - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ - +do : + ac_fn_c_check_header_compile "$LINENO" "term.h" "ac_cv_header_term_h" " #ifdef HAVE_CURSES_H #include #endif - -#include <$ac_header> -_ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - eval "$as_ac_Header=yes" -else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - eval "$as_ac_Header=no" -fi - -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext -fi -ac_res=`eval echo '${'$as_ac_Header'}'` - { echo "$as_me:$LINENO: result: $ac_res" >&5 -echo "${ECHO_T}$ac_res" >&6; } -if test `eval echo '${'$as_ac_Header'}'` = yes; then +" +if test "x$ac_cv_header_term_h" = x""yes; then : cat >>confdefs.h <<_ACEOF -#define `echo "HAVE_$ac_header" | $as_tr_cpp` 1 +#define HAVE_TERM_H 1 _ACEOF fi @@ -6469,22 +6267,9 @@ # On Linux, netlink.h requires asm/types.h - for ac_header in linux/netlink.h -do -as_ac_Header=`echo "ac_cv_header_$ac_header" | $as_tr_sh` -{ echo "$as_me:$LINENO: checking for $ac_header" >&5 -echo $ECHO_N "checking for $ac_header... $ECHO_C" >&6; } -if { as_var=$as_ac_Header; eval "test \"\${$as_var+set}\" = set"; }; then - echo $ECHO_N "(cached) $ECHO_C" >&6 -else - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ - +do : + ac_fn_c_check_header_compile "$LINENO" "linux/netlink.h" "ac_cv_header_linux_netlink_h" " #ifdef HAVE_ASM_TYPES_H #include #endif @@ -6492,42 +6277,10 @@ #include #endif - -#include <$ac_header> -_ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - eval "$as_ac_Header=yes" -else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - eval "$as_ac_Header=no" -fi - -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext -fi -ac_res=`eval echo '${'$as_ac_Header'}'` - { echo "$as_me:$LINENO: result: $ac_res" >&5 -echo "${ECHO_T}$ac_res" >&6; } -if test `eval echo '${'$as_ac_Header'}'` = yes; then +" +if test "x$ac_cv_header_linux_netlink_h" = x""yes; then : cat >>confdefs.h <<_ACEOF -#define `echo "HAVE_$ac_header" | $as_tr_cpp` 1 +#define HAVE_LINUX_NETLINK_H 1 _ACEOF fi @@ -6537,87 +6290,62 @@ # checks for typedefs was_it_defined=no -{ echo "$as_me:$LINENO: checking for clock_t in time.h" >&5 -echo $ECHO_N "checking for clock_t in time.h... $ECHO_C" >&6; } -cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for clock_t in time.h" >&5 +$as_echo_n "checking for clock_t in time.h... " >&6; } +cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ #include _ACEOF if (eval "$ac_cpp conftest.$ac_ext") 2>&5 | - $EGREP "clock_t" >/dev/null 2>&1; then + $EGREP "clock_t" >/dev/null 2>&1; then : was_it_defined=yes else -cat >>confdefs.h <<\_ACEOF -#define clock_t long -_ACEOF +$as_echo "#define clock_t long" >>confdefs.h fi -rm -f -r conftest* +rm -f conftest* -{ echo "$as_me:$LINENO: result: $was_it_defined" >&5 -echo "${ECHO_T}$was_it_defined" >&6; } +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $was_it_defined" >&5 +$as_echo "$was_it_defined" >&6; } # Check whether using makedev requires defining _OSF_SOURCE -{ echo "$as_me:$LINENO: checking for makedev" >&5 -echo $ECHO_N "checking for makedev... $ECHO_C" >&6; } -cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for makedev" >&5 +$as_echo_n "checking for makedev... " >&6; } +cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ + +#if defined(MAJOR_IN_MKDEV) +#include +#elif defined(MAJOR_IN_SYSMACROS) +#include +#else #include +#endif + int main () { - makedev(0, 0) + + makedev(0, 0) ; return 0; } + _ACEOF -rm -f conftest.$ac_objext conftest$ac_exeext -if { (ac_try="$ac_link" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_link") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest$ac_exeext && - $as_test_x conftest$ac_exeext; then +if ac_fn_c_try_link "$LINENO"; then : ac_cv_has_makedev=yes else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - ac_cv_has_makedev=no + ac_cv_has_makedev=no fi - -rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \ - conftest$ac_exeext conftest.$ac_ext +rm -f core conftest.err conftest.$ac_objext \ + conftest$ac_exeext conftest.$ac_ext if test "$ac_cv_has_makedev" = "no"; then # we didn't link, try if _OSF_SOURCE will allow us to link - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF + cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ #define _OSF_SOURCE 1 @@ -6631,49 +6359,24 @@ return 0; } _ACEOF -rm -f conftest.$ac_objext conftest$ac_exeext -if { (ac_try="$ac_link" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_link") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest$ac_exeext && - $as_test_x conftest$ac_exeext; then +if ac_fn_c_try_link "$LINENO"; then : ac_cv_has_makedev=yes else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - ac_cv_has_makedev=no + ac_cv_has_makedev=no fi - -rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \ - conftest$ac_exeext conftest.$ac_ext +rm -f core conftest.err conftest.$ac_objext \ + conftest$ac_exeext conftest.$ac_ext if test "$ac_cv_has_makedev" = "yes"; then -cat >>confdefs.h <<\_ACEOF -#define _OSF_SOURCE 1 -_ACEOF +$as_echo "#define _OSF_SOURCE 1" >>confdefs.h fi fi -{ echo "$as_me:$LINENO: result: $ac_cv_has_makedev" >&5 -echo "${ECHO_T}$ac_cv_has_makedev" >&6; } +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_has_makedev" >&5 +$as_echo "$ac_cv_has_makedev" >&6; } if test "$ac_cv_has_makedev" = "yes"; then -cat >>confdefs.h <<\_ACEOF -#define HAVE_MAKEDEV 1 -_ACEOF +$as_echo "#define HAVE_MAKEDEV 1" >>confdefs.h fi @@ -6685,13 +6388,9 @@ # work-around, disable LFS on such configurations use_lfs=yes -{ echo "$as_me:$LINENO: checking Solaris LFS bug" >&5 -echo $ECHO_N "checking Solaris LFS bug... $ECHO_C" >&6; } -cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking Solaris LFS bug" >&5 +$as_echo_n "checking Solaris LFS bug... " >&6; } +cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ #define _LARGEFILE_SOURCE 1 @@ -6706,34 +6405,14 @@ return 0; } _ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then +if ac_fn_c_try_compile "$LINENO"; then : sol_lfs_bug=no else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - sol_lfs_bug=yes + sol_lfs_bug=yes fi - rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext -{ echo "$as_me:$LINENO: result: $sol_lfs_bug" >&5 -echo "${ECHO_T}$sol_lfs_bug" >&6; } +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $sol_lfs_bug" >&5 +$as_echo "$sol_lfs_bug" >&6; } if test "$sol_lfs_bug" = "yes"; then use_lfs=no fi @@ -6742,14 +6421,10 @@ # Two defines needed to enable largefile support on various platforms # These may affect some typedefs -cat >>confdefs.h <<\_ACEOF -#define _LARGEFILE_SOURCE 1 -_ACEOF +$as_echo "#define _LARGEFILE_SOURCE 1" >>confdefs.h -cat >>confdefs.h <<\_ACEOF -#define _FILE_OFFSET_BITS 64 -_ACEOF +$as_echo "#define _FILE_OFFSET_BITS 64" >>confdefs.h fi @@ -6761,124 +6436,20 @@ EOF # Type availability checks -{ echo "$as_me:$LINENO: checking for mode_t" >&5 -echo $ECHO_N "checking for mode_t... $ECHO_C" >&6; } -if test "${ac_cv_type_mode_t+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 +ac_fn_c_check_type "$LINENO" "mode_t" "ac_cv_type_mode_t" "$ac_includes_default" +if test "x$ac_cv_type_mode_t" = x""yes; then : + else - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -$ac_includes_default -typedef mode_t ac__type_new_; -int -main () -{ -if ((ac__type_new_ *) 0) - return 0; -if (sizeof (ac__type_new_)) - return 0; - ; - return 0; -} -_ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - ac_cv_type_mode_t=yes -else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - ac_cv_type_mode_t=no -fi - -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext -fi -{ echo "$as_me:$LINENO: result: $ac_cv_type_mode_t" >&5 -echo "${ECHO_T}$ac_cv_type_mode_t" >&6; } -if test $ac_cv_type_mode_t = yes; then - : -else - -cat >>confdefs.h <<_ACEOF -#define mode_t int + +cat >>confdefs.h <<_ACEOF +#define mode_t int _ACEOF fi -{ echo "$as_me:$LINENO: checking for off_t" >&5 -echo $ECHO_N "checking for off_t... $ECHO_C" >&6; } -if test "${ac_cv_type_off_t+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 -else - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -$ac_includes_default -typedef off_t ac__type_new_; -int -main () -{ -if ((ac__type_new_ *) 0) - return 0; -if (sizeof (ac__type_new_)) - return 0; - ; - return 0; -} -_ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - ac_cv_type_off_t=yes -else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - ac_cv_type_off_t=no -fi +ac_fn_c_check_type "$LINENO" "off_t" "ac_cv_type_off_t" "$ac_includes_default" +if test "x$ac_cv_type_off_t" = x""yes; then : -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext -fi -{ echo "$as_me:$LINENO: result: $ac_cv_type_off_t" >&5 -echo "${ECHO_T}$ac_cv_type_off_t" >&6; } -if test $ac_cv_type_off_t = yes; then - : else cat >>confdefs.h <<_ACEOF @@ -6887,61 +6458,9 @@ fi -{ echo "$as_me:$LINENO: checking for pid_t" >&5 -echo $ECHO_N "checking for pid_t... $ECHO_C" >&6; } -if test "${ac_cv_type_pid_t+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 -else - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -$ac_includes_default -typedef pid_t ac__type_new_; -int -main () -{ -if ((ac__type_new_ *) 0) - return 0; -if (sizeof (ac__type_new_)) - return 0; - ; - return 0; -} -_ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - ac_cv_type_pid_t=yes -else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - ac_cv_type_pid_t=no -fi +ac_fn_c_check_type "$LINENO" "pid_t" "ac_cv_type_pid_t" "$ac_includes_default" +if test "x$ac_cv_type_pid_t" = x""yes; then : -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext -fi -{ echo "$as_me:$LINENO: result: $ac_cv_type_pid_t" >&5 -echo "${ECHO_T}$ac_cv_type_pid_t" >&6; } -if test $ac_cv_type_pid_t = yes; then - : else cat >>confdefs.h <<_ACEOF @@ -6950,118 +6469,14 @@ fi -{ echo "$as_me:$LINENO: checking return type of signal handlers" >&5 -echo $ECHO_N "checking return type of signal handlers... $ECHO_C" >&6; } -if test "${ac_cv_type_signal+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 -else - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -#include -#include - -int -main () -{ -return *(signal (0, 0)) (0) == 1; - ; - return 0; -} -_ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - ac_cv_type_signal=int -else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - ac_cv_type_signal=void -fi - -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext -fi -{ echo "$as_me:$LINENO: result: $ac_cv_type_signal" >&5 -echo "${ECHO_T}$ac_cv_type_signal" >&6; } cat >>confdefs.h <<_ACEOF -#define RETSIGTYPE $ac_cv_type_signal -_ACEOF - - -{ echo "$as_me:$LINENO: checking for size_t" >&5 -echo $ECHO_N "checking for size_t... $ECHO_C" >&6; } -if test "${ac_cv_type_size_t+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 -else - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -$ac_includes_default -typedef size_t ac__type_new_; -int -main () -{ -if ((ac__type_new_ *) 0) - return 0; -if (sizeof (ac__type_new_)) - return 0; - ; - return 0; -} +#define RETSIGTYPE void _ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - ac_cv_type_size_t=yes -else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - ac_cv_type_size_t=no -fi +ac_fn_c_check_type "$LINENO" "size_t" "ac_cv_type_size_t" "$ac_includes_default" +if test "x$ac_cv_type_size_t" = x""yes; then : -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext -fi -{ echo "$as_me:$LINENO: result: $ac_cv_type_size_t" >&5 -echo "${ECHO_T}$ac_cv_type_size_t" >&6; } -if test $ac_cv_type_size_t = yes; then - : else cat >>confdefs.h <<_ACEOF @@ -7070,12427 +6485,1263 @@ fi -{ echo "$as_me:$LINENO: checking for uid_t in sys/types.h" >&5 -echo $ECHO_N "checking for uid_t in sys/types.h... $ECHO_C" >&6; } -if test "${ac_cv_type_uid_t+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for uid_t in sys/types.h" >&5 +$as_echo_n "checking for uid_t in sys/types.h... " >&6; } +if test "${ac_cv_type_uid_t+set}" = set; then : + $as_echo_n "(cached) " >&6 else - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF + cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ #include _ACEOF if (eval "$ac_cpp conftest.$ac_ext") 2>&5 | - $EGREP "uid_t" >/dev/null 2>&1; then + $EGREP "uid_t" >/dev/null 2>&1; then : ac_cv_type_uid_t=yes else ac_cv_type_uid_t=no fi -rm -f -r conftest* +rm -f conftest* fi -{ echo "$as_me:$LINENO: result: $ac_cv_type_uid_t" >&5 -echo "${ECHO_T}$ac_cv_type_uid_t" >&6; } +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_type_uid_t" >&5 +$as_echo "$ac_cv_type_uid_t" >&6; } if test $ac_cv_type_uid_t = no; then -cat >>confdefs.h <<\_ACEOF -#define uid_t int -_ACEOF +$as_echo "#define uid_t int" >>confdefs.h -cat >>confdefs.h <<\_ACEOF -#define gid_t int -_ACEOF +$as_echo "#define gid_t int" >>confdefs.h fi +ac_fn_c_find_uintX_t "$LINENO" "32" "ac_cv_c_uint32_t" +case $ac_cv_c_uint32_t in #( + no|yes) ;; #( + *) - { echo "$as_me:$LINENO: checking for uint32_t" >&5 -echo $ECHO_N "checking for uint32_t... $ECHO_C" >&6; } -if test "${ac_cv_c_uint32_t+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 -else - ac_cv_c_uint32_t=no - for ac_type in 'uint32_t' 'unsigned int' 'unsigned long int' \ - 'unsigned long long int' 'unsigned short int' 'unsigned char'; do - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -$ac_includes_default -int -main () -{ -static int test_array [1 - 2 * !(($ac_type) -1 >> (32 - 1) == 1)]; -test_array [0] = 0 +$as_echo "#define _UINT32_T 1" >>confdefs.h - ; - return 0; -} + +cat >>confdefs.h <<_ACEOF +#define uint32_t $ac_cv_c_uint32_t _ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - case $ac_type in - uint32_t) ac_cv_c_uint32_t=yes ;; - *) ac_cv_c_uint32_t=$ac_type ;; -esac +;; + esac -else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 +ac_fn_c_find_uintX_t "$LINENO" "64" "ac_cv_c_uint64_t" +case $ac_cv_c_uint64_t in #( + no|yes) ;; #( + *) +$as_echo "#define _UINT64_T 1" >>confdefs.h -fi -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext - test "$ac_cv_c_uint32_t" != no && break - done -fi -{ echo "$as_me:$LINENO: result: $ac_cv_c_uint32_t" >&5 -echo "${ECHO_T}$ac_cv_c_uint32_t" >&6; } - case $ac_cv_c_uint32_t in #( +cat >>confdefs.h <<_ACEOF +#define uint64_t $ac_cv_c_uint64_t +_ACEOF +;; + esac + +ac_fn_c_find_intX_t "$LINENO" "32" "ac_cv_c_int32_t" +case $ac_cv_c_int32_t in #( no|yes) ;; #( *) -cat >>confdefs.h <<\_ACEOF -#define _UINT32_T 1 +cat >>confdefs.h <<_ACEOF +#define int32_t $ac_cv_c_int32_t _ACEOF +;; +esac +ac_fn_c_find_intX_t "$LINENO" "64" "ac_cv_c_int64_t" +case $ac_cv_c_int64_t in #( + no|yes) ;; #( + *) cat >>confdefs.h <<_ACEOF -#define uint32_t $ac_cv_c_uint32_t +#define int64_t $ac_cv_c_int64_t _ACEOF ;; - esac +esac + +ac_fn_c_check_type "$LINENO" "ssize_t" "ac_cv_type_ssize_t" "$ac_includes_default" +if test "x$ac_cv_type_ssize_t" = x""yes; then : + +$as_echo "#define HAVE_SSIZE_T 1" >>confdefs.h + +fi + +# Sizes of various common basic types +# ANSI C requires sizeof(char) == 1, so no need to check it +# The cast to long int works around a bug in the HP C Compiler +# version HP92453-01 B.11.11.23709.GP, which incorrectly rejects +# declarations like `int a3[[(sizeof (unsigned char)) >= 0]];'. +# This bug is HP SR number 8606223364. +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking size of int" >&5 +$as_echo_n "checking size of int... " >&6; } +if test "${ac_cv_sizeof_int+set}" = set; then : + $as_echo_n "(cached) " >&6 +else + if ac_fn_c_compute_int "$LINENO" "(long int) (sizeof (int))" "ac_cv_sizeof_int" "$ac_includes_default"; then : - { echo "$as_me:$LINENO: checking for uint64_t" >&5 -echo $ECHO_N "checking for uint64_t... $ECHO_C" >&6; } -if test "${ac_cv_c_uint64_t+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 else - ac_cv_c_uint64_t=no - for ac_type in 'uint64_t' 'unsigned int' 'unsigned long int' \ - 'unsigned long long int' 'unsigned short int' 'unsigned char'; do - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -$ac_includes_default -int -main () -{ -static int test_array [1 - 2 * !(($ac_type) -1 >> (64 - 1) == 1)]; -test_array [0] = 0 + if test "$ac_cv_type_int" = yes; then + { { $as_echo "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5 +$as_echo "$as_me: error: in \`$ac_pwd':" >&2;} +{ as_fn_set_status 77 +as_fn_error "cannot compute sizeof (int) +See \`config.log' for more details." "$LINENO" 5; }; } + else + ac_cv_sizeof_int=0 + fi +fi - ; - return 0; -} +fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_sizeof_int" >&5 +$as_echo "$ac_cv_sizeof_int" >&6; } + + + +cat >>confdefs.h <<_ACEOF +#define SIZEOF_INT $ac_cv_sizeof_int _ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - case $ac_type in - uint64_t) ac_cv_c_uint64_t=yes ;; - *) ac_cv_c_uint64_t=$ac_type ;; -esac -else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 +# The cast to long int works around a bug in the HP C Compiler +# version HP92453-01 B.11.11.23709.GP, which incorrectly rejects +# declarations like `int a3[[(sizeof (unsigned char)) >= 0]];'. +# This bug is HP SR number 8606223364. +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking size of long" >&5 +$as_echo_n "checking size of long... " >&6; } +if test "${ac_cv_sizeof_long+set}" = set; then : + $as_echo_n "(cached) " >&6 +else + if ac_fn_c_compute_int "$LINENO" "(long int) (sizeof (long))" "ac_cv_sizeof_long" "$ac_includes_default"; then : +else + if test "$ac_cv_type_long" = yes; then + { { $as_echo "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5 +$as_echo "$as_me: error: in \`$ac_pwd':" >&2;} +{ as_fn_set_status 77 +as_fn_error "cannot compute sizeof (long) +See \`config.log' for more details." "$LINENO" 5; }; } + else + ac_cv_sizeof_long=0 + fi fi -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext - test "$ac_cv_c_uint64_t" != no && break - done fi -{ echo "$as_me:$LINENO: result: $ac_cv_c_uint64_t" >&5 -echo "${ECHO_T}$ac_cv_c_uint64_t" >&6; } - case $ac_cv_c_uint64_t in #( - no|yes) ;; #( - *) +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_sizeof_long" >&5 +$as_echo "$ac_cv_sizeof_long" >&6; } -cat >>confdefs.h <<\_ACEOF -#define _UINT64_T 1 -_ACEOF cat >>confdefs.h <<_ACEOF -#define uint64_t $ac_cv_c_uint64_t +#define SIZEOF_LONG $ac_cv_sizeof_long _ACEOF -;; - esac - { echo "$as_me:$LINENO: checking for int32_t" >&5 -echo $ECHO_N "checking for int32_t... $ECHO_C" >&6; } -if test "${ac_cv_c_int32_t+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 +# The cast to long int works around a bug in the HP C Compiler +# version HP92453-01 B.11.11.23709.GP, which incorrectly rejects +# declarations like `int a3[[(sizeof (unsigned char)) >= 0]];'. +# This bug is HP SR number 8606223364. +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking size of void *" >&5 +$as_echo_n "checking size of void *... " >&6; } +if test "${ac_cv_sizeof_void_p+set}" = set; then : + $as_echo_n "(cached) " >&6 +else + if ac_fn_c_compute_int "$LINENO" "(long int) (sizeof (void *))" "ac_cv_sizeof_void_p" "$ac_includes_default"; then : + else - ac_cv_c_int32_t=no - for ac_type in 'int32_t' 'int' 'long int' \ - 'long long int' 'short int' 'signed char'; do - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -$ac_includes_default -int -main () -{ -static int test_array [1 - 2 * !(0 < ($ac_type) (((($ac_type) 1 << (32 - 2)) - 1) * 2 + 1))]; -test_array [0] = 0 + if test "$ac_cv_type_void_p" = yes; then + { { $as_echo "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5 +$as_echo "$as_me: error: in \`$ac_pwd':" >&2;} +{ as_fn_set_status 77 +as_fn_error "cannot compute sizeof (void *) +See \`config.log' for more details." "$LINENO" 5; }; } + else + ac_cv_sizeof_void_p=0 + fi +fi - ; - return 0; -} -_ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -$ac_includes_default -int -main () -{ -static int test_array [1 - 2 * !(($ac_type) (((($ac_type) 1 << (32 - 2)) - 1) * 2 + 1) - < ($ac_type) (((($ac_type) 1 << (32 - 2)) - 1) * 2 + 2))]; -test_array [0] = 0 +fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_sizeof_void_p" >&5 +$as_echo "$ac_cv_sizeof_void_p" >&6; } - ; - return 0; -} + + +cat >>confdefs.h <<_ACEOF +#define SIZEOF_VOID_P $ac_cv_sizeof_void_p _ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - : -else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - case $ac_type in - int32_t) ac_cv_c_int32_t=yes ;; - *) ac_cv_c_int32_t=$ac_type ;; -esac -fi +# The cast to long int works around a bug in the HP C Compiler +# version HP92453-01 B.11.11.23709.GP, which incorrectly rejects +# declarations like `int a3[[(sizeof (unsigned char)) >= 0]];'. +# This bug is HP SR number 8606223364. +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking size of short" >&5 +$as_echo_n "checking size of short... " >&6; } +if test "${ac_cv_sizeof_short+set}" = set; then : + $as_echo_n "(cached) " >&6 +else + if ac_fn_c_compute_int "$LINENO" "(long int) (sizeof (short))" "ac_cv_sizeof_short" "$ac_includes_default"; then : -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 + if test "$ac_cv_type_short" = yes; then + { { $as_echo "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5 +$as_echo "$as_me: error: in \`$ac_pwd':" >&2;} +{ as_fn_set_status 77 +as_fn_error "cannot compute sizeof (short) +See \`config.log' for more details." "$LINENO" 5; }; } + else + ac_cv_sizeof_short=0 + fi +fi + +fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_sizeof_short" >&5 +$as_echo "$ac_cv_sizeof_short" >&6; } + + + +cat >>confdefs.h <<_ACEOF +#define SIZEOF_SHORT $ac_cv_sizeof_short +_ACEOF + +# The cast to long int works around a bug in the HP C Compiler +# version HP92453-01 B.11.11.23709.GP, which incorrectly rejects +# declarations like `int a3[[(sizeof (unsigned char)) >= 0]];'. +# This bug is HP SR number 8606223364. +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking size of float" >&5 +$as_echo_n "checking size of float... " >&6; } +if test "${ac_cv_sizeof_float+set}" = set; then : + $as_echo_n "(cached) " >&6 +else + if ac_fn_c_compute_int "$LINENO" "(long int) (sizeof (float))" "ac_cv_sizeof_float" "$ac_includes_default"; then : +else + if test "$ac_cv_type_float" = yes; then + { { $as_echo "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5 +$as_echo "$as_me: error: in \`$ac_pwd':" >&2;} +{ as_fn_set_status 77 +as_fn_error "cannot compute sizeof (float) +See \`config.log' for more details." "$LINENO" 5; }; } + else + ac_cv_sizeof_float=0 + fi fi -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext - test "$ac_cv_c_int32_t" != no && break - done fi -{ echo "$as_me:$LINENO: result: $ac_cv_c_int32_t" >&5 -echo "${ECHO_T}$ac_cv_c_int32_t" >&6; } - case $ac_cv_c_int32_t in #( - no|yes) ;; #( - *) +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_sizeof_float" >&5 +$as_echo "$ac_cv_sizeof_float" >&6; } + + cat >>confdefs.h <<_ACEOF -#define int32_t $ac_cv_c_int32_t +#define SIZEOF_FLOAT $ac_cv_sizeof_float _ACEOF -;; - esac - { echo "$as_me:$LINENO: checking for int64_t" >&5 -echo $ECHO_N "checking for int64_t... $ECHO_C" >&6; } -if test "${ac_cv_c_int64_t+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 +# The cast to long int works around a bug in the HP C Compiler +# version HP92453-01 B.11.11.23709.GP, which incorrectly rejects +# declarations like `int a3[[(sizeof (unsigned char)) >= 0]];'. +# This bug is HP SR number 8606223364. +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking size of double" >&5 +$as_echo_n "checking size of double... " >&6; } +if test "${ac_cv_sizeof_double+set}" = set; then : + $as_echo_n "(cached) " >&6 +else + if ac_fn_c_compute_int "$LINENO" "(long int) (sizeof (double))" "ac_cv_sizeof_double" "$ac_includes_default"; then : + else - ac_cv_c_int64_t=no - for ac_type in 'int64_t' 'int' 'long int' \ - 'long long int' 'short int' 'signed char'; do - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -$ac_includes_default -int -main () -{ -static int test_array [1 - 2 * !(0 < ($ac_type) (((($ac_type) 1 << (64 - 2)) - 1) * 2 + 1))]; -test_array [0] = 0 + if test "$ac_cv_type_double" = yes; then + { { $as_echo "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5 +$as_echo "$as_me: error: in \`$ac_pwd':" >&2;} +{ as_fn_set_status 77 +as_fn_error "cannot compute sizeof (double) +See \`config.log' for more details." "$LINENO" 5; }; } + else + ac_cv_sizeof_double=0 + fi +fi - ; - return 0; -} -_ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -$ac_includes_default -int -main () -{ -static int test_array [1 - 2 * !(($ac_type) (((($ac_type) 1 << (64 - 2)) - 1) * 2 + 1) - < ($ac_type) (((($ac_type) 1 << (64 - 2)) - 1) * 2 + 2))]; -test_array [0] = 0 +fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_sizeof_double" >&5 +$as_echo "$ac_cv_sizeof_double" >&6; } - ; - return 0; -} + + +cat >>confdefs.h <<_ACEOF +#define SIZEOF_DOUBLE $ac_cv_sizeof_double _ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - : -else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - case $ac_type in - int64_t) ac_cv_c_int64_t=yes ;; - *) ac_cv_c_int64_t=$ac_type ;; -esac -fi +# The cast to long int works around a bug in the HP C Compiler +# version HP92453-01 B.11.11.23709.GP, which incorrectly rejects +# declarations like `int a3[[(sizeof (unsigned char)) >= 0]];'. +# This bug is HP SR number 8606223364. +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking size of fpos_t" >&5 +$as_echo_n "checking size of fpos_t... " >&6; } +if test "${ac_cv_sizeof_fpos_t+set}" = set; then : + $as_echo_n "(cached) " >&6 +else + if ac_fn_c_compute_int "$LINENO" "(long int) (sizeof (fpos_t))" "ac_cv_sizeof_fpos_t" "$ac_includes_default"; then : -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 + if test "$ac_cv_type_fpos_t" = yes; then + { { $as_echo "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5 +$as_echo "$as_me: error: in \`$ac_pwd':" >&2;} +{ as_fn_set_status 77 +as_fn_error "cannot compute sizeof (fpos_t) +See \`config.log' for more details." "$LINENO" 5; }; } + else + ac_cv_sizeof_fpos_t=0 + fi +fi + +fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_sizeof_fpos_t" >&5 +$as_echo "$ac_cv_sizeof_fpos_t" >&6; } + + + +cat >>confdefs.h <<_ACEOF +#define SIZEOF_FPOS_T $ac_cv_sizeof_fpos_t +_ACEOF + +# The cast to long int works around a bug in the HP C Compiler +# version HP92453-01 B.11.11.23709.GP, which incorrectly rejects +# declarations like `int a3[[(sizeof (unsigned char)) >= 0]];'. +# This bug is HP SR number 8606223364. +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking size of size_t" >&5 +$as_echo_n "checking size of size_t... " >&6; } +if test "${ac_cv_sizeof_size_t+set}" = set; then : + $as_echo_n "(cached) " >&6 +else + if ac_fn_c_compute_int "$LINENO" "(long int) (sizeof (size_t))" "ac_cv_sizeof_size_t" "$ac_includes_default"; then : +else + if test "$ac_cv_type_size_t" = yes; then + { { $as_echo "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5 +$as_echo "$as_me: error: in \`$ac_pwd':" >&2;} +{ as_fn_set_status 77 +as_fn_error "cannot compute sizeof (size_t) +See \`config.log' for more details." "$LINENO" 5; }; } + else + ac_cv_sizeof_size_t=0 + fi fi -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext - test "$ac_cv_c_int64_t" != no && break - done fi -{ echo "$as_me:$LINENO: result: $ac_cv_c_int64_t" >&5 -echo "${ECHO_T}$ac_cv_c_int64_t" >&6; } - case $ac_cv_c_int64_t in #( - no|yes) ;; #( - *) +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_sizeof_size_t" >&5 +$as_echo "$ac_cv_sizeof_size_t" >&6; } + + cat >>confdefs.h <<_ACEOF -#define int64_t $ac_cv_c_int64_t +#define SIZEOF_SIZE_T $ac_cv_sizeof_size_t _ACEOF -;; - esac -{ echo "$as_me:$LINENO: checking for ssize_t" >&5 -echo $ECHO_N "checking for ssize_t... $ECHO_C" >&6; } -if test "${ac_cv_type_ssize_t+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 + +# The cast to long int works around a bug in the HP C Compiler +# version HP92453-01 B.11.11.23709.GP, which incorrectly rejects +# declarations like `int a3[[(sizeof (unsigned char)) >= 0]];'. +# This bug is HP SR number 8606223364. +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking size of pid_t" >&5 +$as_echo_n "checking size of pid_t... " >&6; } +if test "${ac_cv_sizeof_pid_t+set}" = set; then : + $as_echo_n "(cached) " >&6 +else + if ac_fn_c_compute_int "$LINENO" "(long int) (sizeof (pid_t))" "ac_cv_sizeof_pid_t" "$ac_includes_default"; then : + else - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ + if test "$ac_cv_type_pid_t" = yes; then + { { $as_echo "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5 +$as_echo "$as_me: error: in \`$ac_pwd':" >&2;} +{ as_fn_set_status 77 +as_fn_error "cannot compute sizeof (pid_t) +See \`config.log' for more details." "$LINENO" 5; }; } + else + ac_cv_sizeof_pid_t=0 + fi +fi + +fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_sizeof_pid_t" >&5 +$as_echo "$ac_cv_sizeof_pid_t" >&6; } + + + +cat >>confdefs.h <<_ACEOF +#define SIZEOF_PID_T $ac_cv_sizeof_pid_t _ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF + + + +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for long long support" >&5 +$as_echo_n "checking for long long support... " >&6; } +have_long_long=no +cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ -$ac_includes_default -typedef ssize_t ac__type_new_; + int main () { -if ((ac__type_new_ *) 0) - return 0; -if (sizeof (ac__type_new_)) - return 0; +long long x; x = (long long)0; ; return 0; } _ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - ac_cv_type_ssize_t=yes -else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 +if ac_fn_c_try_compile "$LINENO"; then : - ac_cv_type_ssize_t=no -fi -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext +$as_echo "#define HAVE_LONG_LONG 1" >>confdefs.h + + have_long_long=yes + fi -{ echo "$as_me:$LINENO: result: $ac_cv_type_ssize_t" >&5 -echo "${ECHO_T}$ac_cv_type_ssize_t" >&6; } -if test $ac_cv_type_ssize_t = yes; then +rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $have_long_long" >&5 +$as_echo "$have_long_long" >&6; } +if test "$have_long_long" = yes ; then +# The cast to long int works around a bug in the HP C Compiler +# version HP92453-01 B.11.11.23709.GP, which incorrectly rejects +# declarations like `int a3[[(sizeof (unsigned char)) >= 0]];'. +# This bug is HP SR number 8606223364. +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking size of long long" >&5 +$as_echo_n "checking size of long long... " >&6; } +if test "${ac_cv_sizeof_long_long+set}" = set; then : + $as_echo_n "(cached) " >&6 +else + if ac_fn_c_compute_int "$LINENO" "(long int) (sizeof (long long))" "ac_cv_sizeof_long_long" "$ac_includes_default"; then : -cat >>confdefs.h <<\_ACEOF -#define HAVE_SSIZE_T 1 -_ACEOF +else + if test "$ac_cv_type_long_long" = yes; then + { { $as_echo "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5 +$as_echo "$as_me: error: in \`$ac_pwd':" >&2;} +{ as_fn_set_status 77 +as_fn_error "cannot compute sizeof (long long) +See \`config.log' for more details." "$LINENO" 5; }; } + else + ac_cv_sizeof_long_long=0 + fi +fi fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_sizeof_long_long" >&5 +$as_echo "$ac_cv_sizeof_long_long" >&6; } -# Sizes of various common basic types -# ANSI C requires sizeof(char) == 1, so no need to check it -{ echo "$as_me:$LINENO: checking for int" >&5 -echo $ECHO_N "checking for int... $ECHO_C" >&6; } -if test "${ac_cv_type_int+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 -else - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ + +cat >>confdefs.h <<_ACEOF +#define SIZEOF_LONG_LONG $ac_cv_sizeof_long_long _ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF + + +fi + +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for long double support" >&5 +$as_echo_n "checking for long double support... " >&6; } +have_long_double=no +cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ -$ac_includes_default -typedef int ac__type_new_; + int main () { -if ((ac__type_new_ *) 0) - return 0; -if (sizeof (ac__type_new_)) - return 0; +long double x; x = (long double)0; ; return 0; } _ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - ac_cv_type_int=yes -else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 +if ac_fn_c_try_compile "$LINENO"; then : - ac_cv_type_int=no -fi -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext -fi -{ echo "$as_me:$LINENO: result: $ac_cv_type_int" >&5 -echo "${ECHO_T}$ac_cv_type_int" >&6; } +$as_echo "#define HAVE_LONG_DOUBLE 1" >>confdefs.h + + have_long_double=yes +fi +rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $have_long_double" >&5 +$as_echo "$have_long_double" >&6; } +if test "$have_long_double" = yes ; then # The cast to long int works around a bug in the HP C Compiler # version HP92453-01 B.11.11.23709.GP, which incorrectly rejects # declarations like `int a3[[(sizeof (unsigned char)) >= 0]];'. # This bug is HP SR number 8606223364. -{ echo "$as_me:$LINENO: checking size of int" >&5 -echo $ECHO_N "checking size of int... $ECHO_C" >&6; } -if test "${ac_cv_sizeof_int+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking size of long double" >&5 +$as_echo_n "checking size of long double... " >&6; } +if test "${ac_cv_sizeof_long_double+set}" = set; then : + $as_echo_n "(cached) " >&6 +else + if ac_fn_c_compute_int "$LINENO" "(long int) (sizeof (long double))" "ac_cv_sizeof_long_double" "$ac_includes_default"; then : + else - if test "$cross_compiling" = yes; then - # Depending upon the size, compute the lo and hi bounds. -cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -$ac_includes_default - typedef int ac__type_sizeof_; -int -main () -{ -static int test_array [1 - 2 * !(((long int) (sizeof (ac__type_sizeof_))) >= 0)]; -test_array [0] = 0 + if test "$ac_cv_type_long_double" = yes; then + { { $as_echo "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5 +$as_echo "$as_me: error: in \`$ac_pwd':" >&2;} +{ as_fn_set_status 77 +as_fn_error "cannot compute sizeof (long double) +See \`config.log' for more details." "$LINENO" 5; }; } + else + ac_cv_sizeof_long_double=0 + fi +fi - ; - return 0; -} -_ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - ac_lo=0 ac_mid=0 - while :; do - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -$ac_includes_default - typedef int ac__type_sizeof_; -int -main () -{ -static int test_array [1 - 2 * !(((long int) (sizeof (ac__type_sizeof_))) <= $ac_mid)]; -test_array [0] = 0 +fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_sizeof_long_double" >&5 +$as_echo "$ac_cv_sizeof_long_double" >&6; } - ; - return 0; -} + + +cat >>confdefs.h <<_ACEOF +#define SIZEOF_LONG_DOUBLE $ac_cv_sizeof_long_double _ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - ac_hi=$ac_mid; break -else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - ac_lo=`expr $ac_mid + 1` - if test $ac_lo -le $ac_mid; then - ac_lo= ac_hi= - break - fi - ac_mid=`expr 2 '*' $ac_mid + 1` + fi -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext - done -else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for _Bool support" >&5 +$as_echo_n "checking for _Bool support... " >&6; } +have_c99_bool=no +cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ -$ac_includes_default - typedef int ac__type_sizeof_; -int -main () -{ -static int test_array [1 - 2 * !(((long int) (sizeof (ac__type_sizeof_))) < 0)]; -test_array [0] = 0 - ; - return 0; -} -_ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - ac_hi=-1 ac_mid=-1 - while :; do - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -$ac_includes_default - typedef int ac__type_sizeof_; int main () { -static int test_array [1 - 2 * !(((long int) (sizeof (ac__type_sizeof_))) >= $ac_mid)]; -test_array [0] = 0 - +_Bool x; x = (_Bool)0; ; return 0; } _ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - ac_lo=$ac_mid; break -else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 +if ac_fn_c_try_compile "$LINENO"; then : - ac_hi=`expr '(' $ac_mid ')' - 1` - if test $ac_mid -le $ac_hi; then - ac_lo= ac_hi= - break - fi - ac_mid=`expr 2 '*' $ac_mid` -fi +$as_echo "#define HAVE_C99_BOOL 1" >>confdefs.h + + have_c99_bool=yes + +fi rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext - done -else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $have_c99_bool" >&5 +$as_echo "$have_c99_bool" >&6; } +if test "$have_c99_bool" = yes ; then +# The cast to long int works around a bug in the HP C Compiler +# version HP92453-01 B.11.11.23709.GP, which incorrectly rejects +# declarations like `int a3[[(sizeof (unsigned char)) >= 0]];'. +# This bug is HP SR number 8606223364. +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking size of _Bool" >&5 +$as_echo_n "checking size of _Bool... " >&6; } +if test "${ac_cv_sizeof__Bool+set}" = set; then : + $as_echo_n "(cached) " >&6 +else + if ac_fn_c_compute_int "$LINENO" "(long int) (sizeof (_Bool))" "ac_cv_sizeof__Bool" "$ac_includes_default"; then : - ac_lo= ac_hi= +else + if test "$ac_cv_type__Bool" = yes; then + { { $as_echo "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5 +$as_echo "$as_me: error: in \`$ac_pwd':" >&2;} +{ as_fn_set_status 77 +as_fn_error "cannot compute sizeof (_Bool) +See \`config.log' for more details." "$LINENO" 5; }; } + else + ac_cv_sizeof__Bool=0 + fi fi -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_sizeof__Bool" >&5 +$as_echo "$ac_cv_sizeof__Bool" >&6; } -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext -# Binary search between lo and hi bounds. -while test "x$ac_lo" != "x$ac_hi"; do - ac_mid=`expr '(' $ac_hi - $ac_lo ')' / 2 + $ac_lo` - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -$ac_includes_default - typedef int ac__type_sizeof_; -int -main () -{ -static int test_array [1 - 2 * !(((long int) (sizeof (ac__type_sizeof_))) <= $ac_mid)]; -test_array [0] = 0 - ; - return 0; -} + +cat >>confdefs.h <<_ACEOF +#define SIZEOF__BOOL $ac_cv_sizeof__Bool _ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - ac_hi=$ac_mid -else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - ac_lo=`expr '(' $ac_mid ')' + 1` + fi -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext -done -case $ac_lo in -?*) ac_cv_sizeof_int=$ac_lo;; -'') if test "$ac_cv_type_int" = yes; then - { { echo "$as_me:$LINENO: error: cannot compute sizeof (int) -See \`config.log' for more details." >&5 -echo "$as_me: error: cannot compute sizeof (int) -See \`config.log' for more details." >&2;} - { (exit 77); exit 77; }; } - else - ac_cv_sizeof_int=0 - fi ;; -esac -else - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ +ac_fn_c_check_type "$LINENO" "uintptr_t" "ac_cv_type_uintptr_t" "#ifdef HAVE_STDINT_H + #include + #endif +" +if test "x$ac_cv_type_uintptr_t" = x""yes; then : + +cat >>confdefs.h <<_ACEOF +#define HAVE_UINTPTR_T 1 _ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -$ac_includes_default - typedef int ac__type_sizeof_; -static long int longval () { return (long int) (sizeof (ac__type_sizeof_)); } -static unsigned long int ulongval () { return (long int) (sizeof (ac__type_sizeof_)); } -#include -#include -int -main () -{ - FILE *f = fopen ("conftest.val", "w"); - if (! f) - return 1; - if (((long int) (sizeof (ac__type_sizeof_))) < 0) - { - long int i = longval (); - if (i != ((long int) (sizeof (ac__type_sizeof_)))) - return 1; - fprintf (f, "%ld\n", i); - } - else - { - unsigned long int i = ulongval (); - if (i != ((long int) (sizeof (ac__type_sizeof_)))) - return 1; - fprintf (f, "%lu\n", i); - } - return ferror (f) || fclose (f) != 0; +# The cast to long int works around a bug in the HP C Compiler +# version HP92453-01 B.11.11.23709.GP, which incorrectly rejects +# declarations like `int a3[[(sizeof (unsigned char)) >= 0]];'. +# This bug is HP SR number 8606223364. +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking size of uintptr_t" >&5 +$as_echo_n "checking size of uintptr_t... " >&6; } +if test "${ac_cv_sizeof_uintptr_t+set}" = set; then : + $as_echo_n "(cached) " >&6 +else + if ac_fn_c_compute_int "$LINENO" "(long int) (sizeof (uintptr_t))" "ac_cv_sizeof_uintptr_t" "$ac_includes_default"; then : - ; - return 0; -} -_ACEOF -rm -f conftest$ac_exeext -if { (ac_try="$ac_link" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_link") 2>&5 - ac_status=$? - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { ac_try='./conftest$ac_exeext' - { (case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_try") 2>&5 - ac_status=$? - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); }; }; then - ac_cv_sizeof_int=`cat conftest.val` else - echo "$as_me: program exited with status $ac_status" >&5 -echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - -( exit $ac_status ) -if test "$ac_cv_type_int" = yes; then - { { echo "$as_me:$LINENO: error: cannot compute sizeof (int) -See \`config.log' for more details." >&5 -echo "$as_me: error: cannot compute sizeof (int) -See \`config.log' for more details." >&2;} - { (exit 77); exit 77; }; } + if test "$ac_cv_type_uintptr_t" = yes; then + { { $as_echo "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5 +$as_echo "$as_me: error: in \`$ac_pwd':" >&2;} +{ as_fn_set_status 77 +as_fn_error "cannot compute sizeof (uintptr_t) +See \`config.log' for more details." "$LINENO" 5; }; } else - ac_cv_sizeof_int=0 + ac_cv_sizeof_uintptr_t=0 fi fi -rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext conftest.$ac_objext conftest.$ac_ext -fi -rm -f conftest.val + fi -{ echo "$as_me:$LINENO: result: $ac_cv_sizeof_int" >&5 -echo "${ECHO_T}$ac_cv_sizeof_int" >&6; } +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_sizeof_uintptr_t" >&5 +$as_echo "$ac_cv_sizeof_uintptr_t" >&6; } cat >>confdefs.h <<_ACEOF -#define SIZEOF_INT $ac_cv_sizeof_int +#define SIZEOF_UINTPTR_T $ac_cv_sizeof_uintptr_t _ACEOF -{ echo "$as_me:$LINENO: checking for long" >&5 -echo $ECHO_N "checking for long... $ECHO_C" >&6; } -if test "${ac_cv_type_long+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 +fi + + +# The cast to long int works around a bug in the HP C Compiler +# version HP92453-01 B.11.11.23709.GP, which incorrectly rejects +# declarations like `int a3[[(sizeof (unsigned char)) >= 0]];'. +# This bug is HP SR number 8606223364. +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking size of off_t" >&5 +$as_echo_n "checking size of off_t... " >&6; } +if test "${ac_cv_sizeof_off_t+set}" = set; then : + $as_echo_n "(cached) " >&6 else - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -$ac_includes_default -typedef long ac__type_new_; -int -main () -{ -if ((ac__type_new_ *) 0) - return 0; -if (sizeof (ac__type_new_)) - return 0; - ; - return 0; -} -_ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - ac_cv_type_long=yes + if ac_fn_c_compute_int "$LINENO" "(long int) (sizeof (off_t))" "ac_cv_sizeof_off_t" " +#ifdef HAVE_SYS_TYPES_H +#include +#endif + +"; then : + else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 + if test "$ac_cv_type_off_t" = yes; then + { { $as_echo "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5 +$as_echo "$as_me: error: in \`$ac_pwd':" >&2;} +{ as_fn_set_status 77 +as_fn_error "cannot compute sizeof (off_t) +See \`config.log' for more details." "$LINENO" 5; }; } + else + ac_cv_sizeof_off_t=0 + fi +fi - ac_cv_type_long=no fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_sizeof_off_t" >&5 +$as_echo "$ac_cv_sizeof_off_t" >&6; } -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext + + +cat >>confdefs.h <<_ACEOF +#define SIZEOF_OFF_T $ac_cv_sizeof_off_t +_ACEOF + + + +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking whether to enable large file support" >&5 +$as_echo_n "checking whether to enable large file support... " >&6; } +if test "$have_long_long" = yes +then +if test "$ac_cv_sizeof_off_t" -gt "$ac_cv_sizeof_long" -a \ + "$ac_cv_sizeof_long_long" -ge "$ac_cv_sizeof_off_t"; then + +$as_echo "#define HAVE_LARGEFILE_SUPPORT 1" >>confdefs.h + + { $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +$as_echo "yes" >&6; } +else + { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 +$as_echo "no" >&6; } +fi +else + { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 +$as_echo "no" >&6; } fi -{ echo "$as_me:$LINENO: result: $ac_cv_type_long" >&5 -echo "${ECHO_T}$ac_cv_type_long" >&6; } # The cast to long int works around a bug in the HP C Compiler # version HP92453-01 B.11.11.23709.GP, which incorrectly rejects # declarations like `int a3[[(sizeof (unsigned char)) >= 0]];'. # This bug is HP SR number 8606223364. -{ echo "$as_me:$LINENO: checking size of long" >&5 -echo $ECHO_N "checking size of long... $ECHO_C" >&6; } -if test "${ac_cv_sizeof_long+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking size of time_t" >&5 +$as_echo_n "checking size of time_t... " >&6; } +if test "${ac_cv_sizeof_time_t+set}" = set; then : + $as_echo_n "(cached) " >&6 else - if test "$cross_compiling" = yes; then - # Depending upon the size, compute the lo and hi bounds. -cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -$ac_includes_default - typedef long ac__type_sizeof_; -int -main () -{ -static int test_array [1 - 2 * !(((long int) (sizeof (ac__type_sizeof_))) >= 0)]; -test_array [0] = 0 + if ac_fn_c_compute_int "$LINENO" "(long int) (sizeof (time_t))" "ac_cv_sizeof_time_t" " +#ifdef HAVE_SYS_TYPES_H +#include +#endif +#ifdef HAVE_TIME_H +#include +#endif - ; - return 0; -} -_ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - ac_lo=0 ac_mid=0 - while :; do - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -$ac_includes_default - typedef long ac__type_sizeof_; -int -main () -{ -static int test_array [1 - 2 * !(((long int) (sizeof (ac__type_sizeof_))) <= $ac_mid)]; -test_array [0] = 0 +"; then : - ; - return 0; -} -_ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - ac_hi=$ac_mid; break else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - ac_lo=`expr $ac_mid + 1` - if test $ac_lo -le $ac_mid; then - ac_lo= ac_hi= - break - fi - ac_mid=`expr 2 '*' $ac_mid + 1` + if test "$ac_cv_type_time_t" = yes; then + { { $as_echo "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5 +$as_echo "$as_me: error: in \`$ac_pwd':" >&2;} +{ as_fn_set_status 77 +as_fn_error "cannot compute sizeof (time_t) +See \`config.log' for more details." "$LINENO" 5; }; } + else + ac_cv_sizeof_time_t=0 + fi fi -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext - done -else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 +fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_sizeof_time_t" >&5 +$as_echo "$ac_cv_sizeof_time_t" >&6; } - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -$ac_includes_default - typedef long ac__type_sizeof_; -int -main () -{ -static int test_array [1 - 2 * !(((long int) (sizeof (ac__type_sizeof_))) < 0)]; -test_array [0] = 0 - ; - return 0; -} -_ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - ac_hi=-1 ac_mid=-1 - while :; do - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -$ac_includes_default - typedef long ac__type_sizeof_; -int -main () -{ -static int test_array [1 - 2 * !(((long int) (sizeof (ac__type_sizeof_))) >= $ac_mid)]; -test_array [0] = 0 - ; - return 0; -} +cat >>confdefs.h <<_ACEOF +#define SIZEOF_TIME_T $ac_cv_sizeof_time_t _ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - ac_lo=$ac_mid; break -else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - ac_hi=`expr '(' $ac_mid ')' - 1` - if test $ac_mid -le $ac_hi; then - ac_lo= ac_hi= - break - fi - ac_mid=`expr 2 '*' $ac_mid` -fi -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext - done -else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - ac_lo= ac_hi= -fi -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext +# if have pthread_t then define SIZEOF_PTHREAD_T +ac_save_cc="$CC" +if test "$ac_cv_kpthread" = "yes" +then CC="$CC -Kpthread" +elif test "$ac_cv_kthread" = "yes" +then CC="$CC -Kthread" +elif test "$ac_cv_pthread" = "yes" +then CC="$CC -pthread" fi -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext -# Binary search between lo and hi bounds. -while test "x$ac_lo" != "x$ac_hi"; do - ac_mid=`expr '(' $ac_hi - $ac_lo ')' / 2 + $ac_lo` - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for pthread_t" >&5 +$as_echo_n "checking for pthread_t... " >&6; } +have_pthread_t=no +cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ -$ac_includes_default - typedef long ac__type_sizeof_; + + #include int main () { -static int test_array [1 - 2 * !(((long int) (sizeof (ac__type_sizeof_))) <= $ac_mid)]; -test_array [0] = 0 - +pthread_t x; x = *(pthread_t*)0; ; return 0; } -_ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - ac_hi=$ac_mid -else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - ac_lo=`expr '(' $ac_mid ')' + 1` +_ACEOF +if ac_fn_c_try_compile "$LINENO"; then : + have_pthread_t=yes fi - rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext -done -case $ac_lo in -?*) ac_cv_sizeof_long=$ac_lo;; -'') if test "$ac_cv_type_long" = yes; then - { { echo "$as_me:$LINENO: error: cannot compute sizeof (long) -See \`config.log' for more details." >&5 -echo "$as_me: error: cannot compute sizeof (long) -See \`config.log' for more details." >&2;} - { (exit 77); exit 77; }; } - else - ac_cv_sizeof_long=0 - fi ;; -esac +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $have_pthread_t" >&5 +$as_echo "$have_pthread_t" >&6; } +if test "$have_pthread_t" = yes ; then + # The cast to long int works around a bug in the HP C Compiler +# version HP92453-01 B.11.11.23709.GP, which incorrectly rejects +# declarations like `int a3[[(sizeof (unsigned char)) >= 0]];'. +# This bug is HP SR number 8606223364. +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking size of pthread_t" >&5 +$as_echo_n "checking size of pthread_t... " >&6; } +if test "${ac_cv_sizeof_pthread_t+set}" = set; then : + $as_echo_n "(cached) " >&6 else - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -$ac_includes_default - typedef long ac__type_sizeof_; -static long int longval () { return (long int) (sizeof (ac__type_sizeof_)); } -static unsigned long int ulongval () { return (long int) (sizeof (ac__type_sizeof_)); } -#include -#include -int -main () -{ + if ac_fn_c_compute_int "$LINENO" "(long int) (sizeof (pthread_t))" "ac_cv_sizeof_pthread_t" " +#ifdef HAVE_PTHREAD_H +#include +#endif - FILE *f = fopen ("conftest.val", "w"); - if (! f) - return 1; - if (((long int) (sizeof (ac__type_sizeof_))) < 0) - { - long int i = longval (); - if (i != ((long int) (sizeof (ac__type_sizeof_)))) - return 1; - fprintf (f, "%ld\n", i); - } - else - { - unsigned long int i = ulongval (); - if (i != ((long int) (sizeof (ac__type_sizeof_)))) - return 1; - fprintf (f, "%lu\n", i); - } - return ferror (f) || fclose (f) != 0; +"; then : - ; - return 0; -} -_ACEOF -rm -f conftest$ac_exeext -if { (ac_try="$ac_link" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_link") 2>&5 - ac_status=$? - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { ac_try='./conftest$ac_exeext' - { (case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_try") 2>&5 - ac_status=$? - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); }; }; then - ac_cv_sizeof_long=`cat conftest.val` else - echo "$as_me: program exited with status $ac_status" >&5 -echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - -( exit $ac_status ) -if test "$ac_cv_type_long" = yes; then - { { echo "$as_me:$LINENO: error: cannot compute sizeof (long) -See \`config.log' for more details." >&5 -echo "$as_me: error: cannot compute sizeof (long) -See \`config.log' for more details." >&2;} - { (exit 77); exit 77; }; } + if test "$ac_cv_type_pthread_t" = yes; then + { { $as_echo "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5 +$as_echo "$as_me: error: in \`$ac_pwd':" >&2;} +{ as_fn_set_status 77 +as_fn_error "cannot compute sizeof (pthread_t) +See \`config.log' for more details." "$LINENO" 5; }; } else - ac_cv_sizeof_long=0 + ac_cv_sizeof_pthread_t=0 fi fi -rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext conftest.$ac_objext conftest.$ac_ext -fi -rm -f conftest.val + fi -{ echo "$as_me:$LINENO: result: $ac_cv_sizeof_long" >&5 -echo "${ECHO_T}$ac_cv_sizeof_long" >&6; } +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_sizeof_pthread_t" >&5 +$as_echo "$ac_cv_sizeof_pthread_t" >&6; } cat >>confdefs.h <<_ACEOF -#define SIZEOF_LONG $ac_cv_sizeof_long -_ACEOF - - -{ echo "$as_me:$LINENO: checking for void *" >&5 -echo $ECHO_N "checking for void *... $ECHO_C" >&6; } -if test "${ac_cv_type_void_p+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 -else - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -$ac_includes_default -typedef void * ac__type_new_; -int -main () -{ -if ((ac__type_new_ *) 0) - return 0; -if (sizeof (ac__type_new_)) - return 0; - ; - return 0; -} +#define SIZEOF_PTHREAD_T $ac_cv_sizeof_pthread_t _ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - ac_cv_type_void_p=yes -else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - ac_cv_type_void_p=no -fi -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext fi -{ echo "$as_me:$LINENO: result: $ac_cv_type_void_p" >&5 -echo "${ECHO_T}$ac_cv_type_void_p" >&6; } +CC="$ac_save_cc" -# The cast to long int works around a bug in the HP C Compiler -# version HP92453-01 B.11.11.23709.GP, which incorrectly rejects -# declarations like `int a3[[(sizeof (unsigned char)) >= 0]];'. -# This bug is HP SR number 8606223364. -{ echo "$as_me:$LINENO: checking size of void *" >&5 -echo $ECHO_N "checking size of void *... $ECHO_C" >&6; } -if test "${ac_cv_sizeof_void_p+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 -else - if test "$cross_compiling" = yes; then - # Depending upon the size, compute the lo and hi bounds. -cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -$ac_includes_default - typedef void * ac__type_sizeof_; -int -main () -{ -static int test_array [1 - 2 * !(((long int) (sizeof (ac__type_sizeof_))) >= 0)]; -test_array [0] = 0 - ; - return 0; -} -_ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; +case $ac_sys_system/$ac_sys_release in + Darwin/[01567]\..*) + OTHER_LIBTOOL_OPT="-prebind -seg1addr 0x10000000" + ;; + Darwin/*) + OTHER_LIBTOOL_OPT="" + ;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - ac_lo=0 ac_mid=0 - while :; do - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -$ac_includes_default - typedef void * ac__type_sizeof_; -int -main () -{ -static int test_array [1 - 2 * !(((long int) (sizeof (ac__type_sizeof_))) <= $ac_mid)]; -test_array [0] = 0 - ; - return 0; -} -_ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - ac_hi=$ac_mid; break -else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - ac_lo=`expr $ac_mid + 1` - if test $ac_lo -le $ac_mid; then - ac_lo= ac_hi= - break - fi - ac_mid=`expr 2 '*' $ac_mid + 1` -fi +ARCH_RUN_32BIT="" -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext - done +case $ac_sys_system/$ac_sys_release in + Darwin/[01567]\..*) + LIBTOOL_CRUFT="-framework System -lcc_dynamic" + if test "${enable_universalsdk}"; then + : + else + LIBTOOL_CRUFT="${LIBTOOL_CRUFT} -arch_only `/usr/bin/arch`" + fi + LIBTOOL_CRUFT=$LIBTOOL_CRUFT' -install_name $(PYTHONFRAMEWORKINSTALLDIR)/Versions/$(VERSION)/$(PYTHONFRAMEWORK)' + LIBTOOL_CRUFT=$LIBTOOL_CRUFT' -compatibility_version $(VERSION) -current_version $(VERSION)';; + Darwin/*) + gcc_version=`gcc -dumpversion` + if test ${gcc_version} '<' 4.0 + then + LIBTOOL_CRUFT="-lcc_dynamic" + else + LIBTOOL_CRUFT="" + fi + if test "$cross_compiling" = yes; then : + ac_osx_32bit=yes else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF + cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ -$ac_includes_default - typedef void * ac__type_sizeof_; -int -main () -{ -static int test_array [1 - 2 * !(((long int) (sizeof (ac__type_sizeof_))) < 0)]; -test_array [0] = 0 - ; - return 0; -} -_ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - ac_hi=-1 ac_mid=-1 - while :; do - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -$ac_includes_default - typedef void * ac__type_sizeof_; -int -main () -{ -static int test_array [1 - 2 * !(((long int) (sizeof (ac__type_sizeof_))) >= $ac_mid)]; -test_array [0] = 0 + #include + int main(int argc, char*argv[]) + { + if (sizeof(long) == 4) { + return 0; + } else { + return 1; + } + } - ; - return 0; -} _ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - ac_lo=$ac_mid; break +if ac_fn_c_try_run "$LINENO"; then : + ac_osx_32bit=yes else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - ac_hi=`expr '(' $ac_mid ')' - 1` - if test $ac_mid -le $ac_hi; then - ac_lo= ac_hi= - break - fi - ac_mid=`expr 2 '*' $ac_mid` + ac_osx_32bit=no fi - -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext - done -else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - ac_lo= ac_hi= +rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext \ + conftest.$ac_objext conftest.beam conftest.$ac_ext fi -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext -fi -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext -# Binary search between lo and hi bounds. -while test "x$ac_lo" != "x$ac_hi"; do - ac_mid=`expr '(' $ac_hi - $ac_lo ')' / 2 + $ac_lo` - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -$ac_includes_default - typedef void * ac__type_sizeof_; -int -main () -{ -static int test_array [1 - 2 * !(((long int) (sizeof (ac__type_sizeof_))) <= $ac_mid)]; -test_array [0] = 0 + if test "${ac_osx_32bit}" = "yes"; then + case `/usr/bin/arch` in + i386) + MACOSX_DEFAULT_ARCH="i386" + ;; + ppc) + MACOSX_DEFAULT_ARCH="ppc" + ;; + *) + as_fn_error "Unexpected output of 'arch' on OSX" "$LINENO" 5 + ;; + esac + else + case `/usr/bin/arch` in + i386) + MACOSX_DEFAULT_ARCH="x86_64" + ;; + ppc) + MACOSX_DEFAULT_ARCH="ppc64" + ;; + *) + as_fn_error "Unexpected output of 'arch' on OSX" "$LINENO" 5 + ;; + esac - ; - return 0; -} -_ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; + #ARCH_RUN_32BIT="true" + fi + + LIBTOOL_CRUFT=$LIBTOOL_CRUFT" -lSystem -lSystemStubs -arch_only ${MACOSX_DEFAULT_ARCH}" + LIBTOOL_CRUFT=$LIBTOOL_CRUFT' -install_name $(PYTHONFRAMEWORKINSTALLDIR)/Versions/$(VERSION)/$(PYTHONFRAMEWORK)' + LIBTOOL_CRUFT=$LIBTOOL_CRUFT' -compatibility_version $(VERSION) -current_version $(VERSION)';; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - ac_hi=$ac_mid -else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - ac_lo=`expr '(' $ac_mid ')' + 1` -fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for --enable-framework" >&5 +$as_echo_n "checking for --enable-framework... " >&6; } +if test "$enable_framework" +then + BASECFLAGS="$BASECFLAGS -fno-common -dynamic" + # -F. is needed to allow linking to the framework while + # in the build location. -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext -done -case $ac_lo in -?*) ac_cv_sizeof_void_p=$ac_lo;; -'') if test "$ac_cv_type_void_p" = yes; then - { { echo "$as_me:$LINENO: error: cannot compute sizeof (void *) -See \`config.log' for more details." >&5 -echo "$as_me: error: cannot compute sizeof (void *) -See \`config.log' for more details." >&2;} - { (exit 77); exit 77; }; } - else - ac_cv_sizeof_void_p=0 - fi ;; -esac +$as_echo "#define WITH_NEXT_FRAMEWORK 1" >>confdefs.h + + { $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +$as_echo "yes" >&6; } + if test $enable_shared = "yes" + then + as_fn_error "Specifying both --enable-shared and --enable-framework is not supported, use only --enable-framework instead" "$LINENO" 5 + fi else - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -$ac_includes_default - typedef void * ac__type_sizeof_; -static long int longval () { return (long int) (sizeof (ac__type_sizeof_)); } -static unsigned long int ulongval () { return (long int) (sizeof (ac__type_sizeof_)); } -#include -#include -int -main () -{ + { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 +$as_echo "no" >&6; } +fi - FILE *f = fopen ("conftest.val", "w"); - if (! f) - return 1; - if (((long int) (sizeof (ac__type_sizeof_))) < 0) - { - long int i = longval (); - if (i != ((long int) (sizeof (ac__type_sizeof_)))) - return 1; - fprintf (f, "%ld\n", i); - } - else - { - unsigned long int i = ulongval (); - if (i != ((long int) (sizeof (ac__type_sizeof_)))) - return 1; - fprintf (f, "%lu\n", i); - } - return ferror (f) || fclose (f) != 0; +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for dyld" >&5 +$as_echo_n "checking for dyld... " >&6; } +case $ac_sys_system/$ac_sys_release in + Darwin/*) - ; - return 0; -} -_ACEOF -rm -f conftest$ac_exeext -if { (ac_try="$ac_link" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_link") 2>&5 - ac_status=$? - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { ac_try='./conftest$ac_exeext' - { (case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; +$as_echo "#define WITH_DYLD 1" >>confdefs.h + + { $as_echo "$as_me:${as_lineno-$LINENO}: result: always on for Darwin" >&5 +$as_echo "always on for Darwin" >&6; } + ;; + *) + { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 +$as_echo "no" >&6; } + ;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_try") 2>&5 - ac_status=$? - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); }; }; then - ac_cv_sizeof_void_p=`cat conftest.val` -else - echo "$as_me: program exited with status $ac_status" >&5 -echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 -( exit $ac_status ) -if test "$ac_cv_type_void_p" = yes; then - { { echo "$as_me:$LINENO: error: cannot compute sizeof (void *) -See \`config.log' for more details." >&5 -echo "$as_me: error: cannot compute sizeof (void *) -See \`config.log' for more details." >&2;} - { (exit 77); exit 77; }; } - else - ac_cv_sizeof_void_p=0 - fi -fi -rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext conftest.$ac_objext conftest.$ac_ext -fi -rm -f conftest.val -fi -{ echo "$as_me:$LINENO: result: $ac_cv_sizeof_void_p" >&5 -echo "${ECHO_T}$ac_cv_sizeof_void_p" >&6; } +# Set info about shared libraries. + -cat >>confdefs.h <<_ACEOF -#define SIZEOF_VOID_P $ac_cv_sizeof_void_p -_ACEOF -{ echo "$as_me:$LINENO: checking for short" >&5 -echo $ECHO_N "checking for short... $ECHO_C" >&6; } -if test "${ac_cv_type_short+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 +# SO is the extension of shared libraries `(including the dot!) +# -- usually .so, .sl on HP-UX, .dll on Cygwin +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking SO" >&5 +$as_echo_n "checking SO... " >&6; } +if test -z "$SO" +then + case $ac_sys_system in + hp*|HP*) + case `uname -m` in + ia64) SO=.so;; + *) SO=.sl;; + esac + ;; + CYGWIN*) SO=.dll;; + *) SO=.so;; + esac else - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -$ac_includes_default -typedef short ac__type_new_; -int -main () -{ -if ((ac__type_new_ *) 0) - return 0; -if (sizeof (ac__type_new_)) - return 0; - ; - return 0; -} -_ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - ac_cv_type_short=yes -else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - ac_cv_type_short=no -fi - -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext + # this might also be a termcap variable, see #610332 + echo + echo '=====================================================================' + echo '+ +' + echo '+ WARNING: You have set SO in your environment. +' + echo '+ Do you really mean to change the extension for shared libraries? +' + echo '+ Continuing in 10 seconds to let you to ponder. +' + echo '+ +' + echo '=====================================================================' + sleep 10 fi -{ echo "$as_me:$LINENO: result: $ac_cv_type_short" >&5 -echo "${ECHO_T}$ac_cv_type_short" >&6; } +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $SO" >&5 +$as_echo "$SO" >&6; } -# The cast to long int works around a bug in the HP C Compiler -# version HP92453-01 B.11.11.23709.GP, which incorrectly rejects -# declarations like `int a3[[(sizeof (unsigned char)) >= 0]];'. -# This bug is HP SR number 8606223364. -{ echo "$as_me:$LINENO: checking size of short" >&5 -echo $ECHO_N "checking size of short... $ECHO_C" >&6; } -if test "${ac_cv_sizeof_short+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 -else - if test "$cross_compiling" = yes; then - # Depending upon the size, compute the lo and hi bounds. -cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -$ac_includes_default - typedef short ac__type_sizeof_; -int -main () -{ -static int test_array [1 - 2 * !(((long int) (sizeof (ac__type_sizeof_))) >= 0)]; -test_array [0] = 0 - ; - return 0; -} -_ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - ac_lo=0 ac_mid=0 - while :; do - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ +cat >>confdefs.h <<_ACEOF +#define SHLIB_EXT "$SO" _ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -$ac_includes_default - typedef short ac__type_sizeof_; -int -main () -{ -static int test_array [1 - 2 * !(((long int) (sizeof (ac__type_sizeof_))) <= $ac_mid)]; -test_array [0] = 0 - ; - return 0; -} -_ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - ac_hi=$ac_mid; break -else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 +# LDSHARED is the ld *command* used to create shared library +# -- "cc -G" on SunOS 5.x, "ld -shared" on IRIX 5 +# (Shared libraries in this instance are shared modules to be loaded into +# Python, as opposed to building Python itself as a shared library.) +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking LDSHARED" >&5 +$as_echo_n "checking LDSHARED... " >&6; } +if test -z "$LDSHARED" +then + case $ac_sys_system/$ac_sys_release in + AIX*) + BLDSHARED="\$(srcdir)/Modules/ld_so_aix \$(CC) -bI:Modules/python.exp" + LDSHARED="\$(BINLIBDEST)/config/ld_so_aix \$(CC) -bI:\$(BINLIBDEST)/config/python.exp" + ;; + IRIX/5*) LDSHARED="ld -shared";; + IRIX*/6*) LDSHARED="ld ${SGI_ABI} -shared -all";; + SunOS/5*) + if test "$GCC" = "yes" ; then + LDSHARED='$(CC) -shared' + LDCXXSHARED='$(CXX) -shared' + else + LDSHARED='$(CC) -G' + LDCXXSHARED='$(CXX) -G' + fi ;; + hp*|HP*) + if test "$GCC" = "yes" ; then + LDSHARED='$(CC) -shared' + LDCXXSHARED='$(CXX) -shared' + else + LDSHARED='ld -b' + fi ;; + OSF*) LDSHARED="ld -shared -expect_unresolved \"*\"";; + Darwin/1.3*) + LDSHARED='$(CC) $(LDFLAGS) -bundle' + LDCXXSHARED='$(CXX) $(LDFLAGS) -bundle' + if test "$enable_framework" ; then + # Link against the framework. All externals should be defined. + BLDSHARED="$LDSHARED "'$(PYTHONFRAMEWORKDIR)/Versions/$(VERSION)/$(PYTHONFRAMEWORK)' + LDSHARED="$LDSHARED "'$(PYTHONFRAMEWORKPREFIX)/$(PYTHONFRAMEWORKDIR)/Versions/$(VERSION)/$(PYTHONFRAMEWORK)' + LDCXXSHARED="$LDCXXSHARED "'$(PYTHONFRAMEWORKPREFIX)/$(PYTHONFRAMEWORKDIR)/Versions/$(VERSION)/$(PYTHONFRAMEWORK)' + else + # No framework. Ignore undefined symbols, assuming they come from Python + LDSHARED="$LDSHARED -undefined suppress" + LDCXXSHARED="$LDCXXSHARED -undefined suppress" + fi ;; + Darwin/1.4*|Darwin/5.*|Darwin/6.*) + LDSHARED='$(CC) $(LDFLAGS) -bundle' + LDCXXSHARED='$(CXX) $(LDFLAGS) -bundle' + if test "$enable_framework" ; then + # Link against the framework. All externals should be defined. + BLDSHARED="$LDSHARED "'$(PYTHONFRAMEWORKDIR)/Versions/$(VERSION)/$(PYTHONFRAMEWORK)' + LDSHARED="$LDSHARED "'$(PYTHONFRAMEWORKPREFIX)/$(PYTHONFRAMEWORKDIR)/Versions/$(VERSION)/$(PYTHONFRAMEWORK)' + LDCXXSHARED="$LDCXXSHARED "'$(PYTHONFRAMEWORKPREFIX)/$(PYTHONFRAMEWORKDIR)/Versions/$(VERSION)/$(PYTHONFRAMEWORK)' + else + # No framework, use the Python app as bundle-loader + BLDSHARED="$LDSHARED "'-bundle_loader $(BUILDPYTHON)' + LDSHARED="$LDSHARED "'-bundle_loader $(BINDIR)/python$(VERSION)$(EXE)' + LDCXXSHARED="$LDCXXSHARED "'-bundle_loader $(BINDIR)/python$(VERSION)$(EXE)' + fi ;; + Darwin/*) + # Use -undefined dynamic_lookup whenever possible (10.3 and later). + # This allows an extension to be used in any Python - ac_lo=`expr $ac_mid + 1` - if test $ac_lo -le $ac_mid; then - ac_lo= ac_hi= - break + if test ${MACOSX_DEPLOYMENT_TARGET} '>' 10.2 + then + if test "${enable_universalsdk}"; then + LDFLAGS="${UNIVERSAL_ARCH_FLAGS} -isysroot ${UNIVERSALSDK} ${LDFLAGS}" fi - ac_mid=`expr 2 '*' $ac_mid + 1` -fi - -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext - done -else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -$ac_includes_default - typedef short ac__type_sizeof_; -int -main () -{ -static int test_array [1 - 2 * !(((long int) (sizeof (ac__type_sizeof_))) < 0)]; -test_array [0] = 0 - - ; - return 0; -} -_ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - ac_hi=-1 ac_mid=-1 - while :; do - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -$ac_includes_default - typedef short ac__type_sizeof_; -int -main () -{ -static int test_array [1 - 2 * !(((long int) (sizeof (ac__type_sizeof_))) >= $ac_mid)]; -test_array [0] = 0 - - ; - return 0; -} -_ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - ac_lo=$ac_mid; break -else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - ac_hi=`expr '(' $ac_mid ')' - 1` - if test $ac_mid -le $ac_hi; then - ac_lo= ac_hi= - break + LDSHARED='$(CC) $(LDFLAGS) -bundle -undefined dynamic_lookup' + LDCXXSHARED='$(CXX) $(LDFLAGS) -bundle -undefined dynamic_lookup' + BLDSHARED="$LDSHARED" + else + LDSHARED='$(CC) $(LDFLAGS) -bundle' + LDCXXSHARED='$(CXX) $(LDFLAGS) -bundle' + if test "$enable_framework" ; then + # Link against the framework. All externals should be defined. + BLDSHARED="$LDSHARED "'$(PYTHONFRAMEWORKDIR)/Versions/$(VERSION)/$(PYTHONFRAMEWORK)' + LDSHARED="$LDSHARED "'$(PYTHONFRAMEWORKPREFIX)/$(PYTHONFRAMEWORKDIR)/Versions/$(VERSION)/$(PYTHONFRAMEWORK)' + LDCXXSHARED="$LDCXXSHARED "'$(PYTHONFRAMEWORKPREFIX)/$(PYTHONFRAMEWORKDIR)/Versions/$(VERSION)/$(PYTHONFRAMEWORK)' + else + # No framework, use the Python app as bundle-loader + BLDSHARED="$LDSHARED "'-bundle_loader $(BUILDPYTHON)' + LDSHARED="$LDSHARED "'-bundle_loader $(BINDIR)/python$(VERSION)$(EXE)' + LDCXXSHARED="$LDCXXSHARED "'-bundle_loader $(BINDIR)/python$(VERSION)$(EXE)' fi - ac_mid=`expr 2 '*' $ac_mid` -fi - -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext - done -else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - ac_lo= ac_hi= -fi - -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext -fi - -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext -# Binary search between lo and hi bounds. -while test "x$ac_lo" != "x$ac_hi"; do - ac_mid=`expr '(' $ac_hi - $ac_lo ')' / 2 + $ac_lo` - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -$ac_includes_default - typedef short ac__type_sizeof_; -int -main () -{ -static int test_array [1 - 2 * !(((long int) (sizeof (ac__type_sizeof_))) <= $ac_mid)]; -test_array [0] = 0 - - ; - return 0; -} -_ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - ac_hi=$ac_mid -else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - ac_lo=`expr '(' $ac_mid ')' + 1` -fi - -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext -done -case $ac_lo in -?*) ac_cv_sizeof_short=$ac_lo;; -'') if test "$ac_cv_type_short" = yes; then - { { echo "$as_me:$LINENO: error: cannot compute sizeof (short) -See \`config.log' for more details." >&5 -echo "$as_me: error: cannot compute sizeof (short) -See \`config.log' for more details." >&2;} - { (exit 77); exit 77; }; } - else - ac_cv_sizeof_short=0 - fi ;; -esac -else - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -$ac_includes_default - typedef short ac__type_sizeof_; -static long int longval () { return (long int) (sizeof (ac__type_sizeof_)); } -static unsigned long int ulongval () { return (long int) (sizeof (ac__type_sizeof_)); } -#include -#include -int -main () -{ - - FILE *f = fopen ("conftest.val", "w"); - if (! f) - return 1; - if (((long int) (sizeof (ac__type_sizeof_))) < 0) - { - long int i = longval (); - if (i != ((long int) (sizeof (ac__type_sizeof_)))) - return 1; - fprintf (f, "%ld\n", i); - } - else - { - unsigned long int i = ulongval (); - if (i != ((long int) (sizeof (ac__type_sizeof_)))) - return 1; - fprintf (f, "%lu\n", i); - } - return ferror (f) || fclose (f) != 0; - - ; - return 0; -} -_ACEOF -rm -f conftest$ac_exeext -if { (ac_try="$ac_link" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_link") 2>&5 - ac_status=$? - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { ac_try='./conftest$ac_exeext' - { (case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_try") 2>&5 - ac_status=$? - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); }; }; then - ac_cv_sizeof_short=`cat conftest.val` -else - echo "$as_me: program exited with status $ac_status" >&5 -echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - -( exit $ac_status ) -if test "$ac_cv_type_short" = yes; then - { { echo "$as_me:$LINENO: error: cannot compute sizeof (short) -See \`config.log' for more details." >&5 -echo "$as_me: error: cannot compute sizeof (short) -See \`config.log' for more details." >&2;} - { (exit 77); exit 77; }; } - else - ac_cv_sizeof_short=0 - fi -fi -rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext conftest.$ac_objext conftest.$ac_ext -fi -rm -f conftest.val -fi -{ echo "$as_me:$LINENO: result: $ac_cv_sizeof_short" >&5 -echo "${ECHO_T}$ac_cv_sizeof_short" >&6; } - - - -cat >>confdefs.h <<_ACEOF -#define SIZEOF_SHORT $ac_cv_sizeof_short -_ACEOF - - -{ echo "$as_me:$LINENO: checking for float" >&5 -echo $ECHO_N "checking for float... $ECHO_C" >&6; } -if test "${ac_cv_type_float+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 -else - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -$ac_includes_default -typedef float ac__type_new_; -int -main () -{ -if ((ac__type_new_ *) 0) - return 0; -if (sizeof (ac__type_new_)) - return 0; - ; - return 0; -} -_ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - ac_cv_type_float=yes -else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - ac_cv_type_float=no -fi - -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext -fi -{ echo "$as_me:$LINENO: result: $ac_cv_type_float" >&5 -echo "${ECHO_T}$ac_cv_type_float" >&6; } - -# The cast to long int works around a bug in the HP C Compiler -# version HP92453-01 B.11.11.23709.GP, which incorrectly rejects -# declarations like `int a3[[(sizeof (unsigned char)) >= 0]];'. -# This bug is HP SR number 8606223364. -{ echo "$as_me:$LINENO: checking size of float" >&5 -echo $ECHO_N "checking size of float... $ECHO_C" >&6; } -if test "${ac_cv_sizeof_float+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 -else - if test "$cross_compiling" = yes; then - # Depending upon the size, compute the lo and hi bounds. -cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -$ac_includes_default - typedef float ac__type_sizeof_; -int -main () -{ -static int test_array [1 - 2 * !(((long int) (sizeof (ac__type_sizeof_))) >= 0)]; -test_array [0] = 0 - - ; - return 0; -} -_ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - ac_lo=0 ac_mid=0 - while :; do - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -$ac_includes_default - typedef float ac__type_sizeof_; -int -main () -{ -static int test_array [1 - 2 * !(((long int) (sizeof (ac__type_sizeof_))) <= $ac_mid)]; -test_array [0] = 0 - - ; - return 0; -} -_ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - ac_hi=$ac_mid; break -else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - ac_lo=`expr $ac_mid + 1` - if test $ac_lo -le $ac_mid; then - ac_lo= ac_hi= - break - fi - ac_mid=`expr 2 '*' $ac_mid + 1` -fi - -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext - done -else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -$ac_includes_default - typedef float ac__type_sizeof_; -int -main () -{ -static int test_array [1 - 2 * !(((long int) (sizeof (ac__type_sizeof_))) < 0)]; -test_array [0] = 0 - - ; - return 0; -} -_ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - ac_hi=-1 ac_mid=-1 - while :; do - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -$ac_includes_default - typedef float ac__type_sizeof_; -int -main () -{ -static int test_array [1 - 2 * !(((long int) (sizeof (ac__type_sizeof_))) >= $ac_mid)]; -test_array [0] = 0 - - ; - return 0; -} -_ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - ac_lo=$ac_mid; break -else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - ac_hi=`expr '(' $ac_mid ')' - 1` - if test $ac_mid -le $ac_hi; then - ac_lo= ac_hi= - break - fi - ac_mid=`expr 2 '*' $ac_mid` -fi - -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext - done -else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - ac_lo= ac_hi= -fi - -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext -fi - -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext -# Binary search between lo and hi bounds. -while test "x$ac_lo" != "x$ac_hi"; do - ac_mid=`expr '(' $ac_hi - $ac_lo ')' / 2 + $ac_lo` - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -$ac_includes_default - typedef float ac__type_sizeof_; -int -main () -{ -static int test_array [1 - 2 * !(((long int) (sizeof (ac__type_sizeof_))) <= $ac_mid)]; -test_array [0] = 0 - - ; - return 0; -} -_ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - ac_hi=$ac_mid -else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - ac_lo=`expr '(' $ac_mid ')' + 1` -fi - -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext -done -case $ac_lo in -?*) ac_cv_sizeof_float=$ac_lo;; -'') if test "$ac_cv_type_float" = yes; then - { { echo "$as_me:$LINENO: error: cannot compute sizeof (float) -See \`config.log' for more details." >&5 -echo "$as_me: error: cannot compute sizeof (float) -See \`config.log' for more details." >&2;} - { (exit 77); exit 77; }; } - else - ac_cv_sizeof_float=0 - fi ;; -esac -else - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -$ac_includes_default - typedef float ac__type_sizeof_; -static long int longval () { return (long int) (sizeof (ac__type_sizeof_)); } -static unsigned long int ulongval () { return (long int) (sizeof (ac__type_sizeof_)); } -#include -#include -int -main () -{ - - FILE *f = fopen ("conftest.val", "w"); - if (! f) - return 1; - if (((long int) (sizeof (ac__type_sizeof_))) < 0) - { - long int i = longval (); - if (i != ((long int) (sizeof (ac__type_sizeof_)))) - return 1; - fprintf (f, "%ld\n", i); - } - else - { - unsigned long int i = ulongval (); - if (i != ((long int) (sizeof (ac__type_sizeof_)))) - return 1; - fprintf (f, "%lu\n", i); - } - return ferror (f) || fclose (f) != 0; - - ; - return 0; -} -_ACEOF -rm -f conftest$ac_exeext -if { (ac_try="$ac_link" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_link") 2>&5 - ac_status=$? - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { ac_try='./conftest$ac_exeext' - { (case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_try") 2>&5 - ac_status=$? - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); }; }; then - ac_cv_sizeof_float=`cat conftest.val` -else - echo "$as_me: program exited with status $ac_status" >&5 -echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - -( exit $ac_status ) -if test "$ac_cv_type_float" = yes; then - { { echo "$as_me:$LINENO: error: cannot compute sizeof (float) -See \`config.log' for more details." >&5 -echo "$as_me: error: cannot compute sizeof (float) -See \`config.log' for more details." >&2;} - { (exit 77); exit 77; }; } - else - ac_cv_sizeof_float=0 - fi -fi -rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext conftest.$ac_objext conftest.$ac_ext -fi -rm -f conftest.val -fi -{ echo "$as_me:$LINENO: result: $ac_cv_sizeof_float" >&5 -echo "${ECHO_T}$ac_cv_sizeof_float" >&6; } - - - -cat >>confdefs.h <<_ACEOF -#define SIZEOF_FLOAT $ac_cv_sizeof_float -_ACEOF - - -{ echo "$as_me:$LINENO: checking for double" >&5 -echo $ECHO_N "checking for double... $ECHO_C" >&6; } -if test "${ac_cv_type_double+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 -else - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -$ac_includes_default -typedef double ac__type_new_; -int -main () -{ -if ((ac__type_new_ *) 0) - return 0; -if (sizeof (ac__type_new_)) - return 0; - ; - return 0; -} -_ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - ac_cv_type_double=yes -else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - ac_cv_type_double=no -fi - -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext -fi -{ echo "$as_me:$LINENO: result: $ac_cv_type_double" >&5 -echo "${ECHO_T}$ac_cv_type_double" >&6; } - -# The cast to long int works around a bug in the HP C Compiler -# version HP92453-01 B.11.11.23709.GP, which incorrectly rejects -# declarations like `int a3[[(sizeof (unsigned char)) >= 0]];'. -# This bug is HP SR number 8606223364. -{ echo "$as_me:$LINENO: checking size of double" >&5 -echo $ECHO_N "checking size of double... $ECHO_C" >&6; } -if test "${ac_cv_sizeof_double+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 -else - if test "$cross_compiling" = yes; then - # Depending upon the size, compute the lo and hi bounds. -cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -$ac_includes_default - typedef double ac__type_sizeof_; -int -main () -{ -static int test_array [1 - 2 * !(((long int) (sizeof (ac__type_sizeof_))) >= 0)]; -test_array [0] = 0 - - ; - return 0; -} -_ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - ac_lo=0 ac_mid=0 - while :; do - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -$ac_includes_default - typedef double ac__type_sizeof_; -int -main () -{ -static int test_array [1 - 2 * !(((long int) (sizeof (ac__type_sizeof_))) <= $ac_mid)]; -test_array [0] = 0 - - ; - return 0; -} -_ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - ac_hi=$ac_mid; break -else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - ac_lo=`expr $ac_mid + 1` - if test $ac_lo -le $ac_mid; then - ac_lo= ac_hi= - break - fi - ac_mid=`expr 2 '*' $ac_mid + 1` -fi - -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext - done -else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -$ac_includes_default - typedef double ac__type_sizeof_; -int -main () -{ -static int test_array [1 - 2 * !(((long int) (sizeof (ac__type_sizeof_))) < 0)]; -test_array [0] = 0 - - ; - return 0; -} -_ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - ac_hi=-1 ac_mid=-1 - while :; do - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -$ac_includes_default - typedef double ac__type_sizeof_; -int -main () -{ -static int test_array [1 - 2 * !(((long int) (sizeof (ac__type_sizeof_))) >= $ac_mid)]; -test_array [0] = 0 - - ; - return 0; -} -_ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - ac_lo=$ac_mid; break -else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - ac_hi=`expr '(' $ac_mid ')' - 1` - if test $ac_mid -le $ac_hi; then - ac_lo= ac_hi= - break - fi - ac_mid=`expr 2 '*' $ac_mid` -fi - -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext - done -else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - ac_lo= ac_hi= -fi - -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext -fi - -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext -# Binary search between lo and hi bounds. -while test "x$ac_lo" != "x$ac_hi"; do - ac_mid=`expr '(' $ac_hi - $ac_lo ')' / 2 + $ac_lo` - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -$ac_includes_default - typedef double ac__type_sizeof_; -int -main () -{ -static int test_array [1 - 2 * !(((long int) (sizeof (ac__type_sizeof_))) <= $ac_mid)]; -test_array [0] = 0 - - ; - return 0; -} -_ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - ac_hi=$ac_mid -else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - ac_lo=`expr '(' $ac_mid ')' + 1` -fi - -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext -done -case $ac_lo in -?*) ac_cv_sizeof_double=$ac_lo;; -'') if test "$ac_cv_type_double" = yes; then - { { echo "$as_me:$LINENO: error: cannot compute sizeof (double) -See \`config.log' for more details." >&5 -echo "$as_me: error: cannot compute sizeof (double) -See \`config.log' for more details." >&2;} - { (exit 77); exit 77; }; } - else - ac_cv_sizeof_double=0 - fi ;; -esac -else - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -$ac_includes_default - typedef double ac__type_sizeof_; -static long int longval () { return (long int) (sizeof (ac__type_sizeof_)); } -static unsigned long int ulongval () { return (long int) (sizeof (ac__type_sizeof_)); } -#include -#include -int -main () -{ - - FILE *f = fopen ("conftest.val", "w"); - if (! f) - return 1; - if (((long int) (sizeof (ac__type_sizeof_))) < 0) - { - long int i = longval (); - if (i != ((long int) (sizeof (ac__type_sizeof_)))) - return 1; - fprintf (f, "%ld\n", i); - } - else - { - unsigned long int i = ulongval (); - if (i != ((long int) (sizeof (ac__type_sizeof_)))) - return 1; - fprintf (f, "%lu\n", i); - } - return ferror (f) || fclose (f) != 0; - - ; - return 0; -} -_ACEOF -rm -f conftest$ac_exeext -if { (ac_try="$ac_link" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_link") 2>&5 - ac_status=$? - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { ac_try='./conftest$ac_exeext' - { (case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_try") 2>&5 - ac_status=$? - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); }; }; then - ac_cv_sizeof_double=`cat conftest.val` -else - echo "$as_me: program exited with status $ac_status" >&5 -echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - -( exit $ac_status ) -if test "$ac_cv_type_double" = yes; then - { { echo "$as_me:$LINENO: error: cannot compute sizeof (double) -See \`config.log' for more details." >&5 -echo "$as_me: error: cannot compute sizeof (double) -See \`config.log' for more details." >&2;} - { (exit 77); exit 77; }; } - else - ac_cv_sizeof_double=0 - fi -fi -rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext conftest.$ac_objext conftest.$ac_ext -fi -rm -f conftest.val -fi -{ echo "$as_me:$LINENO: result: $ac_cv_sizeof_double" >&5 -echo "${ECHO_T}$ac_cv_sizeof_double" >&6; } - - - -cat >>confdefs.h <<_ACEOF -#define SIZEOF_DOUBLE $ac_cv_sizeof_double -_ACEOF - - -{ echo "$as_me:$LINENO: checking for fpos_t" >&5 -echo $ECHO_N "checking for fpos_t... $ECHO_C" >&6; } -if test "${ac_cv_type_fpos_t+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 -else - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -$ac_includes_default -typedef fpos_t ac__type_new_; -int -main () -{ -if ((ac__type_new_ *) 0) - return 0; -if (sizeof (ac__type_new_)) - return 0; - ; - return 0; -} -_ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - ac_cv_type_fpos_t=yes -else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - ac_cv_type_fpos_t=no -fi - -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext -fi -{ echo "$as_me:$LINENO: result: $ac_cv_type_fpos_t" >&5 -echo "${ECHO_T}$ac_cv_type_fpos_t" >&6; } - -# The cast to long int works around a bug in the HP C Compiler -# version HP92453-01 B.11.11.23709.GP, which incorrectly rejects -# declarations like `int a3[[(sizeof (unsigned char)) >= 0]];'. -# This bug is HP SR number 8606223364. -{ echo "$as_me:$LINENO: checking size of fpos_t" >&5 -echo $ECHO_N "checking size of fpos_t... $ECHO_C" >&6; } -if test "${ac_cv_sizeof_fpos_t+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 -else - if test "$cross_compiling" = yes; then - # Depending upon the size, compute the lo and hi bounds. -cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -$ac_includes_default - typedef fpos_t ac__type_sizeof_; -int -main () -{ -static int test_array [1 - 2 * !(((long int) (sizeof (ac__type_sizeof_))) >= 0)]; -test_array [0] = 0 - - ; - return 0; -} -_ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - ac_lo=0 ac_mid=0 - while :; do - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -$ac_includes_default - typedef fpos_t ac__type_sizeof_; -int -main () -{ -static int test_array [1 - 2 * !(((long int) (sizeof (ac__type_sizeof_))) <= $ac_mid)]; -test_array [0] = 0 - - ; - return 0; -} -_ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - ac_hi=$ac_mid; break -else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - ac_lo=`expr $ac_mid + 1` - if test $ac_lo -le $ac_mid; then - ac_lo= ac_hi= - break - fi - ac_mid=`expr 2 '*' $ac_mid + 1` -fi - -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext - done -else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -$ac_includes_default - typedef fpos_t ac__type_sizeof_; -int -main () -{ -static int test_array [1 - 2 * !(((long int) (sizeof (ac__type_sizeof_))) < 0)]; -test_array [0] = 0 - - ; - return 0; -} -_ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - ac_hi=-1 ac_mid=-1 - while :; do - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -$ac_includes_default - typedef fpos_t ac__type_sizeof_; -int -main () -{ -static int test_array [1 - 2 * !(((long int) (sizeof (ac__type_sizeof_))) >= $ac_mid)]; -test_array [0] = 0 - - ; - return 0; -} -_ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - ac_lo=$ac_mid; break -else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - ac_hi=`expr '(' $ac_mid ')' - 1` - if test $ac_mid -le $ac_hi; then - ac_lo= ac_hi= - break - fi - ac_mid=`expr 2 '*' $ac_mid` -fi - -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext - done -else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - ac_lo= ac_hi= -fi - -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext -fi - -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext -# Binary search between lo and hi bounds. -while test "x$ac_lo" != "x$ac_hi"; do - ac_mid=`expr '(' $ac_hi - $ac_lo ')' / 2 + $ac_lo` - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -$ac_includes_default - typedef fpos_t ac__type_sizeof_; -int -main () -{ -static int test_array [1 - 2 * !(((long int) (sizeof (ac__type_sizeof_))) <= $ac_mid)]; -test_array [0] = 0 - - ; - return 0; -} -_ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - ac_hi=$ac_mid -else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - ac_lo=`expr '(' $ac_mid ')' + 1` -fi - -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext -done -case $ac_lo in -?*) ac_cv_sizeof_fpos_t=$ac_lo;; -'') if test "$ac_cv_type_fpos_t" = yes; then - { { echo "$as_me:$LINENO: error: cannot compute sizeof (fpos_t) -See \`config.log' for more details." >&5 -echo "$as_me: error: cannot compute sizeof (fpos_t) -See \`config.log' for more details." >&2;} - { (exit 77); exit 77; }; } - else - ac_cv_sizeof_fpos_t=0 - fi ;; -esac -else - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -$ac_includes_default - typedef fpos_t ac__type_sizeof_; -static long int longval () { return (long int) (sizeof (ac__type_sizeof_)); } -static unsigned long int ulongval () { return (long int) (sizeof (ac__type_sizeof_)); } -#include -#include -int -main () -{ - - FILE *f = fopen ("conftest.val", "w"); - if (! f) - return 1; - if (((long int) (sizeof (ac__type_sizeof_))) < 0) - { - long int i = longval (); - if (i != ((long int) (sizeof (ac__type_sizeof_)))) - return 1; - fprintf (f, "%ld\n", i); - } - else - { - unsigned long int i = ulongval (); - if (i != ((long int) (sizeof (ac__type_sizeof_)))) - return 1; - fprintf (f, "%lu\n", i); - } - return ferror (f) || fclose (f) != 0; - - ; - return 0; -} -_ACEOF -rm -f conftest$ac_exeext -if { (ac_try="$ac_link" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_link") 2>&5 - ac_status=$? - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { ac_try='./conftest$ac_exeext' - { (case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_try") 2>&5 - ac_status=$? - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); }; }; then - ac_cv_sizeof_fpos_t=`cat conftest.val` -else - echo "$as_me: program exited with status $ac_status" >&5 -echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - -( exit $ac_status ) -if test "$ac_cv_type_fpos_t" = yes; then - { { echo "$as_me:$LINENO: error: cannot compute sizeof (fpos_t) -See \`config.log' for more details." >&5 -echo "$as_me: error: cannot compute sizeof (fpos_t) -See \`config.log' for more details." >&2;} - { (exit 77); exit 77; }; } - else - ac_cv_sizeof_fpos_t=0 - fi -fi -rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext conftest.$ac_objext conftest.$ac_ext -fi -rm -f conftest.val -fi -{ echo "$as_me:$LINENO: result: $ac_cv_sizeof_fpos_t" >&5 -echo "${ECHO_T}$ac_cv_sizeof_fpos_t" >&6; } - - - -cat >>confdefs.h <<_ACEOF -#define SIZEOF_FPOS_T $ac_cv_sizeof_fpos_t -_ACEOF - - -{ echo "$as_me:$LINENO: checking for size_t" >&5 -echo $ECHO_N "checking for size_t... $ECHO_C" >&6; } -if test "${ac_cv_type_size_t+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 -else - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -$ac_includes_default -typedef size_t ac__type_new_; -int -main () -{ -if ((ac__type_new_ *) 0) - return 0; -if (sizeof (ac__type_new_)) - return 0; - ; - return 0; -} -_ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - ac_cv_type_size_t=yes -else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - ac_cv_type_size_t=no -fi - -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext -fi -{ echo "$as_me:$LINENO: result: $ac_cv_type_size_t" >&5 -echo "${ECHO_T}$ac_cv_type_size_t" >&6; } - -# The cast to long int works around a bug in the HP C Compiler -# version HP92453-01 B.11.11.23709.GP, which incorrectly rejects -# declarations like `int a3[[(sizeof (unsigned char)) >= 0]];'. -# This bug is HP SR number 8606223364. -{ echo "$as_me:$LINENO: checking size of size_t" >&5 -echo $ECHO_N "checking size of size_t... $ECHO_C" >&6; } -if test "${ac_cv_sizeof_size_t+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 -else - if test "$cross_compiling" = yes; then - # Depending upon the size, compute the lo and hi bounds. -cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -$ac_includes_default - typedef size_t ac__type_sizeof_; -int -main () -{ -static int test_array [1 - 2 * !(((long int) (sizeof (ac__type_sizeof_))) >= 0)]; -test_array [0] = 0 - - ; - return 0; -} -_ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - ac_lo=0 ac_mid=0 - while :; do - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -$ac_includes_default - typedef size_t ac__type_sizeof_; -int -main () -{ -static int test_array [1 - 2 * !(((long int) (sizeof (ac__type_sizeof_))) <= $ac_mid)]; -test_array [0] = 0 - - ; - return 0; -} -_ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - ac_hi=$ac_mid; break -else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - ac_lo=`expr $ac_mid + 1` - if test $ac_lo -le $ac_mid; then - ac_lo= ac_hi= - break - fi - ac_mid=`expr 2 '*' $ac_mid + 1` -fi - -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext - done -else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -$ac_includes_default - typedef size_t ac__type_sizeof_; -int -main () -{ -static int test_array [1 - 2 * !(((long int) (sizeof (ac__type_sizeof_))) < 0)]; -test_array [0] = 0 - - ; - return 0; -} -_ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - ac_hi=-1 ac_mid=-1 - while :; do - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -$ac_includes_default - typedef size_t ac__type_sizeof_; -int -main () -{ -static int test_array [1 - 2 * !(((long int) (sizeof (ac__type_sizeof_))) >= $ac_mid)]; -test_array [0] = 0 - - ; - return 0; -} -_ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - ac_lo=$ac_mid; break -else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - ac_hi=`expr '(' $ac_mid ')' - 1` - if test $ac_mid -le $ac_hi; then - ac_lo= ac_hi= - break - fi - ac_mid=`expr 2 '*' $ac_mid` -fi - -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext - done -else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - ac_lo= ac_hi= -fi - -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext -fi - -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext -# Binary search between lo and hi bounds. -while test "x$ac_lo" != "x$ac_hi"; do - ac_mid=`expr '(' $ac_hi - $ac_lo ')' / 2 + $ac_lo` - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -$ac_includes_default - typedef size_t ac__type_sizeof_; -int -main () -{ -static int test_array [1 - 2 * !(((long int) (sizeof (ac__type_sizeof_))) <= $ac_mid)]; -test_array [0] = 0 - - ; - return 0; -} -_ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - ac_hi=$ac_mid -else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - ac_lo=`expr '(' $ac_mid ')' + 1` -fi - -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext -done -case $ac_lo in -?*) ac_cv_sizeof_size_t=$ac_lo;; -'') if test "$ac_cv_type_size_t" = yes; then - { { echo "$as_me:$LINENO: error: cannot compute sizeof (size_t) -See \`config.log' for more details." >&5 -echo "$as_me: error: cannot compute sizeof (size_t) -See \`config.log' for more details." >&2;} - { (exit 77); exit 77; }; } - else - ac_cv_sizeof_size_t=0 - fi ;; -esac -else - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -$ac_includes_default - typedef size_t ac__type_sizeof_; -static long int longval () { return (long int) (sizeof (ac__type_sizeof_)); } -static unsigned long int ulongval () { return (long int) (sizeof (ac__type_sizeof_)); } -#include -#include -int -main () -{ - - FILE *f = fopen ("conftest.val", "w"); - if (! f) - return 1; - if (((long int) (sizeof (ac__type_sizeof_))) < 0) - { - long int i = longval (); - if (i != ((long int) (sizeof (ac__type_sizeof_)))) - return 1; - fprintf (f, "%ld\n", i); - } - else - { - unsigned long int i = ulongval (); - if (i != ((long int) (sizeof (ac__type_sizeof_)))) - return 1; - fprintf (f, "%lu\n", i); - } - return ferror (f) || fclose (f) != 0; - - ; - return 0; -} -_ACEOF -rm -f conftest$ac_exeext -if { (ac_try="$ac_link" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_link") 2>&5 - ac_status=$? - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { ac_try='./conftest$ac_exeext' - { (case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_try") 2>&5 - ac_status=$? - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); }; }; then - ac_cv_sizeof_size_t=`cat conftest.val` -else - echo "$as_me: program exited with status $ac_status" >&5 -echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - -( exit $ac_status ) -if test "$ac_cv_type_size_t" = yes; then - { { echo "$as_me:$LINENO: error: cannot compute sizeof (size_t) -See \`config.log' for more details." >&5 -echo "$as_me: error: cannot compute sizeof (size_t) -See \`config.log' for more details." >&2;} - { (exit 77); exit 77; }; } - else - ac_cv_sizeof_size_t=0 - fi -fi -rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext conftest.$ac_objext conftest.$ac_ext -fi -rm -f conftest.val -fi -{ echo "$as_me:$LINENO: result: $ac_cv_sizeof_size_t" >&5 -echo "${ECHO_T}$ac_cv_sizeof_size_t" >&6; } - - - -cat >>confdefs.h <<_ACEOF -#define SIZEOF_SIZE_T $ac_cv_sizeof_size_t -_ACEOF - - -{ echo "$as_me:$LINENO: checking for pid_t" >&5 -echo $ECHO_N "checking for pid_t... $ECHO_C" >&6; } -if test "${ac_cv_type_pid_t+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 -else - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -$ac_includes_default -typedef pid_t ac__type_new_; -int -main () -{ -if ((ac__type_new_ *) 0) - return 0; -if (sizeof (ac__type_new_)) - return 0; - ; - return 0; -} -_ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - ac_cv_type_pid_t=yes -else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - ac_cv_type_pid_t=no -fi - -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext -fi -{ echo "$as_me:$LINENO: result: $ac_cv_type_pid_t" >&5 -echo "${ECHO_T}$ac_cv_type_pid_t" >&6; } - -# The cast to long int works around a bug in the HP C Compiler -# version HP92453-01 B.11.11.23709.GP, which incorrectly rejects -# declarations like `int a3[[(sizeof (unsigned char)) >= 0]];'. -# This bug is HP SR number 8606223364. -{ echo "$as_me:$LINENO: checking size of pid_t" >&5 -echo $ECHO_N "checking size of pid_t... $ECHO_C" >&6; } -if test "${ac_cv_sizeof_pid_t+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 -else - if test "$cross_compiling" = yes; then - # Depending upon the size, compute the lo and hi bounds. -cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -$ac_includes_default - typedef pid_t ac__type_sizeof_; -int -main () -{ -static int test_array [1 - 2 * !(((long int) (sizeof (ac__type_sizeof_))) >= 0)]; -test_array [0] = 0 - - ; - return 0; -} -_ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - ac_lo=0 ac_mid=0 - while :; do - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -$ac_includes_default - typedef pid_t ac__type_sizeof_; -int -main () -{ -static int test_array [1 - 2 * !(((long int) (sizeof (ac__type_sizeof_))) <= $ac_mid)]; -test_array [0] = 0 - - ; - return 0; -} -_ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - ac_hi=$ac_mid; break -else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - ac_lo=`expr $ac_mid + 1` - if test $ac_lo -le $ac_mid; then - ac_lo= ac_hi= - break - fi - ac_mid=`expr 2 '*' $ac_mid + 1` -fi - -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext - done -else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -$ac_includes_default - typedef pid_t ac__type_sizeof_; -int -main () -{ -static int test_array [1 - 2 * !(((long int) (sizeof (ac__type_sizeof_))) < 0)]; -test_array [0] = 0 - - ; - return 0; -} -_ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - ac_hi=-1 ac_mid=-1 - while :; do - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -$ac_includes_default - typedef pid_t ac__type_sizeof_; -int -main () -{ -static int test_array [1 - 2 * !(((long int) (sizeof (ac__type_sizeof_))) >= $ac_mid)]; -test_array [0] = 0 - - ; - return 0; -} -_ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - ac_lo=$ac_mid; break -else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - ac_hi=`expr '(' $ac_mid ')' - 1` - if test $ac_mid -le $ac_hi; then - ac_lo= ac_hi= - break - fi - ac_mid=`expr 2 '*' $ac_mid` -fi - -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext - done -else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - ac_lo= ac_hi= -fi - -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext -fi - -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext -# Binary search between lo and hi bounds. -while test "x$ac_lo" != "x$ac_hi"; do - ac_mid=`expr '(' $ac_hi - $ac_lo ')' / 2 + $ac_lo` - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -$ac_includes_default - typedef pid_t ac__type_sizeof_; -int -main () -{ -static int test_array [1 - 2 * !(((long int) (sizeof (ac__type_sizeof_))) <= $ac_mid)]; -test_array [0] = 0 - - ; - return 0; -} -_ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - ac_hi=$ac_mid -else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - ac_lo=`expr '(' $ac_mid ')' + 1` -fi - -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext -done -case $ac_lo in -?*) ac_cv_sizeof_pid_t=$ac_lo;; -'') if test "$ac_cv_type_pid_t" = yes; then - { { echo "$as_me:$LINENO: error: cannot compute sizeof (pid_t) -See \`config.log' for more details." >&5 -echo "$as_me: error: cannot compute sizeof (pid_t) -See \`config.log' for more details." >&2;} - { (exit 77); exit 77; }; } - else - ac_cv_sizeof_pid_t=0 - fi ;; -esac -else - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -$ac_includes_default - typedef pid_t ac__type_sizeof_; -static long int longval () { return (long int) (sizeof (ac__type_sizeof_)); } -static unsigned long int ulongval () { return (long int) (sizeof (ac__type_sizeof_)); } -#include -#include -int -main () -{ - - FILE *f = fopen ("conftest.val", "w"); - if (! f) - return 1; - if (((long int) (sizeof (ac__type_sizeof_))) < 0) - { - long int i = longval (); - if (i != ((long int) (sizeof (ac__type_sizeof_)))) - return 1; - fprintf (f, "%ld\n", i); - } - else - { - unsigned long int i = ulongval (); - if (i != ((long int) (sizeof (ac__type_sizeof_)))) - return 1; - fprintf (f, "%lu\n", i); - } - return ferror (f) || fclose (f) != 0; - - ; - return 0; -} -_ACEOF -rm -f conftest$ac_exeext -if { (ac_try="$ac_link" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_link") 2>&5 - ac_status=$? - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { ac_try='./conftest$ac_exeext' - { (case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_try") 2>&5 - ac_status=$? - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); }; }; then - ac_cv_sizeof_pid_t=`cat conftest.val` -else - echo "$as_me: program exited with status $ac_status" >&5 -echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - -( exit $ac_status ) -if test "$ac_cv_type_pid_t" = yes; then - { { echo "$as_me:$LINENO: error: cannot compute sizeof (pid_t) -See \`config.log' for more details." >&5 -echo "$as_me: error: cannot compute sizeof (pid_t) -See \`config.log' for more details." >&2;} - { (exit 77); exit 77; }; } - else - ac_cv_sizeof_pid_t=0 - fi -fi -rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext conftest.$ac_objext conftest.$ac_ext -fi -rm -f conftest.val -fi -{ echo "$as_me:$LINENO: result: $ac_cv_sizeof_pid_t" >&5 -echo "${ECHO_T}$ac_cv_sizeof_pid_t" >&6; } - - - -cat >>confdefs.h <<_ACEOF -#define SIZEOF_PID_T $ac_cv_sizeof_pid_t -_ACEOF - - - -{ echo "$as_me:$LINENO: checking for long long support" >&5 -echo $ECHO_N "checking for long long support... $ECHO_C" >&6; } -have_long_long=no -cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ - -int -main () -{ -long long x; x = (long long)0; - ; - return 0; -} -_ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - - -cat >>confdefs.h <<\_ACEOF -#define HAVE_LONG_LONG 1 -_ACEOF - - have_long_long=yes - -else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - -fi - -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext -{ echo "$as_me:$LINENO: result: $have_long_long" >&5 -echo "${ECHO_T}$have_long_long" >&6; } -if test "$have_long_long" = yes ; then -{ echo "$as_me:$LINENO: checking for long long" >&5 -echo $ECHO_N "checking for long long... $ECHO_C" >&6; } -if test "${ac_cv_type_long_long+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 -else - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -$ac_includes_default -typedef long long ac__type_new_; -int -main () -{ -if ((ac__type_new_ *) 0) - return 0; -if (sizeof (ac__type_new_)) - return 0; - ; - return 0; -} -_ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - ac_cv_type_long_long=yes -else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - ac_cv_type_long_long=no -fi - -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext -fi -{ echo "$as_me:$LINENO: result: $ac_cv_type_long_long" >&5 -echo "${ECHO_T}$ac_cv_type_long_long" >&6; } - -# The cast to long int works around a bug in the HP C Compiler -# version HP92453-01 B.11.11.23709.GP, which incorrectly rejects -# declarations like `int a3[[(sizeof (unsigned char)) >= 0]];'. -# This bug is HP SR number 8606223364. -{ echo "$as_me:$LINENO: checking size of long long" >&5 -echo $ECHO_N "checking size of long long... $ECHO_C" >&6; } -if test "${ac_cv_sizeof_long_long+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 -else - if test "$cross_compiling" = yes; then - # Depending upon the size, compute the lo and hi bounds. -cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -$ac_includes_default - typedef long long ac__type_sizeof_; -int -main () -{ -static int test_array [1 - 2 * !(((long int) (sizeof (ac__type_sizeof_))) >= 0)]; -test_array [0] = 0 - - ; - return 0; -} -_ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - ac_lo=0 ac_mid=0 - while :; do - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -$ac_includes_default - typedef long long ac__type_sizeof_; -int -main () -{ -static int test_array [1 - 2 * !(((long int) (sizeof (ac__type_sizeof_))) <= $ac_mid)]; -test_array [0] = 0 - - ; - return 0; -} -_ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - ac_hi=$ac_mid; break -else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - ac_lo=`expr $ac_mid + 1` - if test $ac_lo -le $ac_mid; then - ac_lo= ac_hi= - break - fi - ac_mid=`expr 2 '*' $ac_mid + 1` -fi - -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext - done -else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -$ac_includes_default - typedef long long ac__type_sizeof_; -int -main () -{ -static int test_array [1 - 2 * !(((long int) (sizeof (ac__type_sizeof_))) < 0)]; -test_array [0] = 0 - - ; - return 0; -} -_ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - ac_hi=-1 ac_mid=-1 - while :; do - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -$ac_includes_default - typedef long long ac__type_sizeof_; -int -main () -{ -static int test_array [1 - 2 * !(((long int) (sizeof (ac__type_sizeof_))) >= $ac_mid)]; -test_array [0] = 0 - - ; - return 0; -} -_ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - ac_lo=$ac_mid; break -else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - ac_hi=`expr '(' $ac_mid ')' - 1` - if test $ac_mid -le $ac_hi; then - ac_lo= ac_hi= - break - fi - ac_mid=`expr 2 '*' $ac_mid` -fi - -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext - done -else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - ac_lo= ac_hi= -fi - -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext -fi - -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext -# Binary search between lo and hi bounds. -while test "x$ac_lo" != "x$ac_hi"; do - ac_mid=`expr '(' $ac_hi - $ac_lo ')' / 2 + $ac_lo` - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -$ac_includes_default - typedef long long ac__type_sizeof_; -int -main () -{ -static int test_array [1 - 2 * !(((long int) (sizeof (ac__type_sizeof_))) <= $ac_mid)]; -test_array [0] = 0 - - ; - return 0; -} -_ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - ac_hi=$ac_mid -else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - ac_lo=`expr '(' $ac_mid ')' + 1` -fi - -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext -done -case $ac_lo in -?*) ac_cv_sizeof_long_long=$ac_lo;; -'') if test "$ac_cv_type_long_long" = yes; then - { { echo "$as_me:$LINENO: error: cannot compute sizeof (long long) -See \`config.log' for more details." >&5 -echo "$as_me: error: cannot compute sizeof (long long) -See \`config.log' for more details." >&2;} - { (exit 77); exit 77; }; } - else - ac_cv_sizeof_long_long=0 - fi ;; -esac -else - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -$ac_includes_default - typedef long long ac__type_sizeof_; -static long int longval () { return (long int) (sizeof (ac__type_sizeof_)); } -static unsigned long int ulongval () { return (long int) (sizeof (ac__type_sizeof_)); } -#include -#include -int -main () -{ - - FILE *f = fopen ("conftest.val", "w"); - if (! f) - return 1; - if (((long int) (sizeof (ac__type_sizeof_))) < 0) - { - long int i = longval (); - if (i != ((long int) (sizeof (ac__type_sizeof_)))) - return 1; - fprintf (f, "%ld\n", i); - } - else - { - unsigned long int i = ulongval (); - if (i != ((long int) (sizeof (ac__type_sizeof_)))) - return 1; - fprintf (f, "%lu\n", i); - } - return ferror (f) || fclose (f) != 0; - - ; - return 0; -} -_ACEOF -rm -f conftest$ac_exeext -if { (ac_try="$ac_link" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_link") 2>&5 - ac_status=$? - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { ac_try='./conftest$ac_exeext' - { (case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_try") 2>&5 - ac_status=$? - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); }; }; then - ac_cv_sizeof_long_long=`cat conftest.val` -else - echo "$as_me: program exited with status $ac_status" >&5 -echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - -( exit $ac_status ) -if test "$ac_cv_type_long_long" = yes; then - { { echo "$as_me:$LINENO: error: cannot compute sizeof (long long) -See \`config.log' for more details." >&5 -echo "$as_me: error: cannot compute sizeof (long long) -See \`config.log' for more details." >&2;} - { (exit 77); exit 77; }; } - else - ac_cv_sizeof_long_long=0 - fi -fi -rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext conftest.$ac_objext conftest.$ac_ext -fi -rm -f conftest.val -fi -{ echo "$as_me:$LINENO: result: $ac_cv_sizeof_long_long" >&5 -echo "${ECHO_T}$ac_cv_sizeof_long_long" >&6; } - - - -cat >>confdefs.h <<_ACEOF -#define SIZEOF_LONG_LONG $ac_cv_sizeof_long_long -_ACEOF - - -fi - -{ echo "$as_me:$LINENO: checking for long double support" >&5 -echo $ECHO_N "checking for long double support... $ECHO_C" >&6; } -have_long_double=no -cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ - -int -main () -{ -long double x; x = (long double)0; - ; - return 0; -} -_ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - - -cat >>confdefs.h <<\_ACEOF -#define HAVE_LONG_DOUBLE 1 -_ACEOF - - have_long_double=yes - -else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - -fi - -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext -{ echo "$as_me:$LINENO: result: $have_long_double" >&5 -echo "${ECHO_T}$have_long_double" >&6; } -if test "$have_long_double" = yes ; then -{ echo "$as_me:$LINENO: checking for long double" >&5 -echo $ECHO_N "checking for long double... $ECHO_C" >&6; } -if test "${ac_cv_type_long_double+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 -else - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -$ac_includes_default -typedef long double ac__type_new_; -int -main () -{ -if ((ac__type_new_ *) 0) - return 0; -if (sizeof (ac__type_new_)) - return 0; - ; - return 0; -} -_ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - ac_cv_type_long_double=yes -else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - ac_cv_type_long_double=no -fi - -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext -fi -{ echo "$as_me:$LINENO: result: $ac_cv_type_long_double" >&5 -echo "${ECHO_T}$ac_cv_type_long_double" >&6; } - -# The cast to long int works around a bug in the HP C Compiler -# version HP92453-01 B.11.11.23709.GP, which incorrectly rejects -# declarations like `int a3[[(sizeof (unsigned char)) >= 0]];'. -# This bug is HP SR number 8606223364. -{ echo "$as_me:$LINENO: checking size of long double" >&5 -echo $ECHO_N "checking size of long double... $ECHO_C" >&6; } -if test "${ac_cv_sizeof_long_double+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 -else - if test "$cross_compiling" = yes; then - # Depending upon the size, compute the lo and hi bounds. -cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -$ac_includes_default - typedef long double ac__type_sizeof_; -int -main () -{ -static int test_array [1 - 2 * !(((long int) (sizeof (ac__type_sizeof_))) >= 0)]; -test_array [0] = 0 - - ; - return 0; -} -_ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - ac_lo=0 ac_mid=0 - while :; do - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -$ac_includes_default - typedef long double ac__type_sizeof_; -int -main () -{ -static int test_array [1 - 2 * !(((long int) (sizeof (ac__type_sizeof_))) <= $ac_mid)]; -test_array [0] = 0 - - ; - return 0; -} -_ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - ac_hi=$ac_mid; break -else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - ac_lo=`expr $ac_mid + 1` - if test $ac_lo -le $ac_mid; then - ac_lo= ac_hi= - break - fi - ac_mid=`expr 2 '*' $ac_mid + 1` -fi - -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext - done -else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -$ac_includes_default - typedef long double ac__type_sizeof_; -int -main () -{ -static int test_array [1 - 2 * !(((long int) (sizeof (ac__type_sizeof_))) < 0)]; -test_array [0] = 0 - - ; - return 0; -} -_ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - ac_hi=-1 ac_mid=-1 - while :; do - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -$ac_includes_default - typedef long double ac__type_sizeof_; -int -main () -{ -static int test_array [1 - 2 * !(((long int) (sizeof (ac__type_sizeof_))) >= $ac_mid)]; -test_array [0] = 0 - - ; - return 0; -} -_ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - ac_lo=$ac_mid; break -else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - ac_hi=`expr '(' $ac_mid ')' - 1` - if test $ac_mid -le $ac_hi; then - ac_lo= ac_hi= - break - fi - ac_mid=`expr 2 '*' $ac_mid` -fi - -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext - done -else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - ac_lo= ac_hi= -fi - -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext -fi - -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext -# Binary search between lo and hi bounds. -while test "x$ac_lo" != "x$ac_hi"; do - ac_mid=`expr '(' $ac_hi - $ac_lo ')' / 2 + $ac_lo` - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -$ac_includes_default - typedef long double ac__type_sizeof_; -int -main () -{ -static int test_array [1 - 2 * !(((long int) (sizeof (ac__type_sizeof_))) <= $ac_mid)]; -test_array [0] = 0 - - ; - return 0; -} -_ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - ac_hi=$ac_mid -else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - ac_lo=`expr '(' $ac_mid ')' + 1` -fi - -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext -done -case $ac_lo in -?*) ac_cv_sizeof_long_double=$ac_lo;; -'') if test "$ac_cv_type_long_double" = yes; then - { { echo "$as_me:$LINENO: error: cannot compute sizeof (long double) -See \`config.log' for more details." >&5 -echo "$as_me: error: cannot compute sizeof (long double) -See \`config.log' for more details." >&2;} - { (exit 77); exit 77; }; } - else - ac_cv_sizeof_long_double=0 - fi ;; -esac -else - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -$ac_includes_default - typedef long double ac__type_sizeof_; -static long int longval () { return (long int) (sizeof (ac__type_sizeof_)); } -static unsigned long int ulongval () { return (long int) (sizeof (ac__type_sizeof_)); } -#include -#include -int -main () -{ - - FILE *f = fopen ("conftest.val", "w"); - if (! f) - return 1; - if (((long int) (sizeof (ac__type_sizeof_))) < 0) - { - long int i = longval (); - if (i != ((long int) (sizeof (ac__type_sizeof_)))) - return 1; - fprintf (f, "%ld\n", i); - } - else - { - unsigned long int i = ulongval (); - if (i != ((long int) (sizeof (ac__type_sizeof_)))) - return 1; - fprintf (f, "%lu\n", i); - } - return ferror (f) || fclose (f) != 0; - - ; - return 0; -} -_ACEOF -rm -f conftest$ac_exeext -if { (ac_try="$ac_link" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_link") 2>&5 - ac_status=$? - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { ac_try='./conftest$ac_exeext' - { (case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_try") 2>&5 - ac_status=$? - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); }; }; then - ac_cv_sizeof_long_double=`cat conftest.val` -else - echo "$as_me: program exited with status $ac_status" >&5 -echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - -( exit $ac_status ) -if test "$ac_cv_type_long_double" = yes; then - { { echo "$as_me:$LINENO: error: cannot compute sizeof (long double) -See \`config.log' for more details." >&5 -echo "$as_me: error: cannot compute sizeof (long double) -See \`config.log' for more details." >&2;} - { (exit 77); exit 77; }; } - else - ac_cv_sizeof_long_double=0 - fi -fi -rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext conftest.$ac_objext conftest.$ac_ext -fi -rm -f conftest.val -fi -{ echo "$as_me:$LINENO: result: $ac_cv_sizeof_long_double" >&5 -echo "${ECHO_T}$ac_cv_sizeof_long_double" >&6; } - - - -cat >>confdefs.h <<_ACEOF -#define SIZEOF_LONG_DOUBLE $ac_cv_sizeof_long_double -_ACEOF - - -fi - - -{ echo "$as_me:$LINENO: checking for _Bool support" >&5 -echo $ECHO_N "checking for _Bool support... $ECHO_C" >&6; } -have_c99_bool=no -cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ - -int -main () -{ -_Bool x; x = (_Bool)0; - ; - return 0; -} -_ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - - -cat >>confdefs.h <<\_ACEOF -#define HAVE_C99_BOOL 1 -_ACEOF - - have_c99_bool=yes - -else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - -fi - -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext -{ echo "$as_me:$LINENO: result: $have_c99_bool" >&5 -echo "${ECHO_T}$have_c99_bool" >&6; } -if test "$have_c99_bool" = yes ; then -{ echo "$as_me:$LINENO: checking for _Bool" >&5 -echo $ECHO_N "checking for _Bool... $ECHO_C" >&6; } -if test "${ac_cv_type__Bool+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 -else - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -$ac_includes_default -typedef _Bool ac__type_new_; -int -main () -{ -if ((ac__type_new_ *) 0) - return 0; -if (sizeof (ac__type_new_)) - return 0; - ; - return 0; -} -_ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - ac_cv_type__Bool=yes -else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - ac_cv_type__Bool=no -fi - -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext -fi -{ echo "$as_me:$LINENO: result: $ac_cv_type__Bool" >&5 -echo "${ECHO_T}$ac_cv_type__Bool" >&6; } - -# The cast to long int works around a bug in the HP C Compiler -# version HP92453-01 B.11.11.23709.GP, which incorrectly rejects -# declarations like `int a3[[(sizeof (unsigned char)) >= 0]];'. -# This bug is HP SR number 8606223364. -{ echo "$as_me:$LINENO: checking size of _Bool" >&5 -echo $ECHO_N "checking size of _Bool... $ECHO_C" >&6; } -if test "${ac_cv_sizeof__Bool+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 -else - if test "$cross_compiling" = yes; then - # Depending upon the size, compute the lo and hi bounds. -cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -$ac_includes_default - typedef _Bool ac__type_sizeof_; -int -main () -{ -static int test_array [1 - 2 * !(((long int) (sizeof (ac__type_sizeof_))) >= 0)]; -test_array [0] = 0 - - ; - return 0; -} -_ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - ac_lo=0 ac_mid=0 - while :; do - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -$ac_includes_default - typedef _Bool ac__type_sizeof_; -int -main () -{ -static int test_array [1 - 2 * !(((long int) (sizeof (ac__type_sizeof_))) <= $ac_mid)]; -test_array [0] = 0 - - ; - return 0; -} -_ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - ac_hi=$ac_mid; break -else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - ac_lo=`expr $ac_mid + 1` - if test $ac_lo -le $ac_mid; then - ac_lo= ac_hi= - break - fi - ac_mid=`expr 2 '*' $ac_mid + 1` -fi - -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext - done -else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -$ac_includes_default - typedef _Bool ac__type_sizeof_; -int -main () -{ -static int test_array [1 - 2 * !(((long int) (sizeof (ac__type_sizeof_))) < 0)]; -test_array [0] = 0 - - ; - return 0; -} -_ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - ac_hi=-1 ac_mid=-1 - while :; do - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -$ac_includes_default - typedef _Bool ac__type_sizeof_; -int -main () -{ -static int test_array [1 - 2 * !(((long int) (sizeof (ac__type_sizeof_))) >= $ac_mid)]; -test_array [0] = 0 - - ; - return 0; -} -_ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - ac_lo=$ac_mid; break -else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - ac_hi=`expr '(' $ac_mid ')' - 1` - if test $ac_mid -le $ac_hi; then - ac_lo= ac_hi= - break - fi - ac_mid=`expr 2 '*' $ac_mid` -fi - -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext - done -else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - ac_lo= ac_hi= -fi - -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext -fi - -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext -# Binary search between lo and hi bounds. -while test "x$ac_lo" != "x$ac_hi"; do - ac_mid=`expr '(' $ac_hi - $ac_lo ')' / 2 + $ac_lo` - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -$ac_includes_default - typedef _Bool ac__type_sizeof_; -int -main () -{ -static int test_array [1 - 2 * !(((long int) (sizeof (ac__type_sizeof_))) <= $ac_mid)]; -test_array [0] = 0 - - ; - return 0; -} -_ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - ac_hi=$ac_mid -else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - ac_lo=`expr '(' $ac_mid ')' + 1` -fi - -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext -done -case $ac_lo in -?*) ac_cv_sizeof__Bool=$ac_lo;; -'') if test "$ac_cv_type__Bool" = yes; then - { { echo "$as_me:$LINENO: error: cannot compute sizeof (_Bool) -See \`config.log' for more details." >&5 -echo "$as_me: error: cannot compute sizeof (_Bool) -See \`config.log' for more details." >&2;} - { (exit 77); exit 77; }; } - else - ac_cv_sizeof__Bool=0 - fi ;; -esac -else - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -$ac_includes_default - typedef _Bool ac__type_sizeof_; -static long int longval () { return (long int) (sizeof (ac__type_sizeof_)); } -static unsigned long int ulongval () { return (long int) (sizeof (ac__type_sizeof_)); } -#include -#include -int -main () -{ - - FILE *f = fopen ("conftest.val", "w"); - if (! f) - return 1; - if (((long int) (sizeof (ac__type_sizeof_))) < 0) - { - long int i = longval (); - if (i != ((long int) (sizeof (ac__type_sizeof_)))) - return 1; - fprintf (f, "%ld\n", i); - } - else - { - unsigned long int i = ulongval (); - if (i != ((long int) (sizeof (ac__type_sizeof_)))) - return 1; - fprintf (f, "%lu\n", i); - } - return ferror (f) || fclose (f) != 0; - - ; - return 0; -} -_ACEOF -rm -f conftest$ac_exeext -if { (ac_try="$ac_link" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_link") 2>&5 - ac_status=$? - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { ac_try='./conftest$ac_exeext' - { (case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_try") 2>&5 - ac_status=$? - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); }; }; then - ac_cv_sizeof__Bool=`cat conftest.val` -else - echo "$as_me: program exited with status $ac_status" >&5 -echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - -( exit $ac_status ) -if test "$ac_cv_type__Bool" = yes; then - { { echo "$as_me:$LINENO: error: cannot compute sizeof (_Bool) -See \`config.log' for more details." >&5 -echo "$as_me: error: cannot compute sizeof (_Bool) -See \`config.log' for more details." >&2;} - { (exit 77); exit 77; }; } - else - ac_cv_sizeof__Bool=0 - fi -fi -rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext conftest.$ac_objext conftest.$ac_ext -fi -rm -f conftest.val -fi -{ echo "$as_me:$LINENO: result: $ac_cv_sizeof__Bool" >&5 -echo "${ECHO_T}$ac_cv_sizeof__Bool" >&6; } - - - -cat >>confdefs.h <<_ACEOF -#define SIZEOF__BOOL $ac_cv_sizeof__Bool -_ACEOF - - -fi - -{ echo "$as_me:$LINENO: checking for uintptr_t" >&5 -echo $ECHO_N "checking for uintptr_t... $ECHO_C" >&6; } -if test "${ac_cv_type_uintptr_t+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 -else - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -#ifdef HAVE_STDINT_H - #include - #endif - -typedef uintptr_t ac__type_new_; -int -main () -{ -if ((ac__type_new_ *) 0) - return 0; -if (sizeof (ac__type_new_)) - return 0; - ; - return 0; -} -_ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - ac_cv_type_uintptr_t=yes -else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - ac_cv_type_uintptr_t=no -fi - -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext -fi -{ echo "$as_me:$LINENO: result: $ac_cv_type_uintptr_t" >&5 -echo "${ECHO_T}$ac_cv_type_uintptr_t" >&6; } -if test $ac_cv_type_uintptr_t = yes; then - -cat >>confdefs.h <<_ACEOF -#define HAVE_UINTPTR_T 1 -_ACEOF - -{ echo "$as_me:$LINENO: checking for uintptr_t" >&5 -echo $ECHO_N "checking for uintptr_t... $ECHO_C" >&6; } -if test "${ac_cv_type_uintptr_t+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 -else - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -$ac_includes_default -typedef uintptr_t ac__type_new_; -int -main () -{ -if ((ac__type_new_ *) 0) - return 0; -if (sizeof (ac__type_new_)) - return 0; - ; - return 0; -} -_ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - ac_cv_type_uintptr_t=yes -else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - ac_cv_type_uintptr_t=no -fi - -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext -fi -{ echo "$as_me:$LINENO: result: $ac_cv_type_uintptr_t" >&5 -echo "${ECHO_T}$ac_cv_type_uintptr_t" >&6; } - -# The cast to long int works around a bug in the HP C Compiler -# version HP92453-01 B.11.11.23709.GP, which incorrectly rejects -# declarations like `int a3[[(sizeof (unsigned char)) >= 0]];'. -# This bug is HP SR number 8606223364. -{ echo "$as_me:$LINENO: checking size of uintptr_t" >&5 -echo $ECHO_N "checking size of uintptr_t... $ECHO_C" >&6; } -if test "${ac_cv_sizeof_uintptr_t+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 -else - if test "$cross_compiling" = yes; then - # Depending upon the size, compute the lo and hi bounds. -cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -$ac_includes_default - typedef uintptr_t ac__type_sizeof_; -int -main () -{ -static int test_array [1 - 2 * !(((long int) (sizeof (ac__type_sizeof_))) >= 0)]; -test_array [0] = 0 - - ; - return 0; -} -_ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - ac_lo=0 ac_mid=0 - while :; do - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -$ac_includes_default - typedef uintptr_t ac__type_sizeof_; -int -main () -{ -static int test_array [1 - 2 * !(((long int) (sizeof (ac__type_sizeof_))) <= $ac_mid)]; -test_array [0] = 0 - - ; - return 0; -} -_ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - ac_hi=$ac_mid; break -else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - ac_lo=`expr $ac_mid + 1` - if test $ac_lo -le $ac_mid; then - ac_lo= ac_hi= - break - fi - ac_mid=`expr 2 '*' $ac_mid + 1` -fi - -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext - done -else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -$ac_includes_default - typedef uintptr_t ac__type_sizeof_; -int -main () -{ -static int test_array [1 - 2 * !(((long int) (sizeof (ac__type_sizeof_))) < 0)]; -test_array [0] = 0 - - ; - return 0; -} -_ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - ac_hi=-1 ac_mid=-1 - while :; do - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -$ac_includes_default - typedef uintptr_t ac__type_sizeof_; -int -main () -{ -static int test_array [1 - 2 * !(((long int) (sizeof (ac__type_sizeof_))) >= $ac_mid)]; -test_array [0] = 0 - - ; - return 0; -} -_ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - ac_lo=$ac_mid; break -else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - ac_hi=`expr '(' $ac_mid ')' - 1` - if test $ac_mid -le $ac_hi; then - ac_lo= ac_hi= - break - fi - ac_mid=`expr 2 '*' $ac_mid` -fi - -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext - done -else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - ac_lo= ac_hi= -fi - -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext -fi - -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext -# Binary search between lo and hi bounds. -while test "x$ac_lo" != "x$ac_hi"; do - ac_mid=`expr '(' $ac_hi - $ac_lo ')' / 2 + $ac_lo` - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -$ac_includes_default - typedef uintptr_t ac__type_sizeof_; -int -main () -{ -static int test_array [1 - 2 * !(((long int) (sizeof (ac__type_sizeof_))) <= $ac_mid)]; -test_array [0] = 0 - - ; - return 0; -} -_ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - ac_hi=$ac_mid -else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - ac_lo=`expr '(' $ac_mid ')' + 1` -fi - -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext -done -case $ac_lo in -?*) ac_cv_sizeof_uintptr_t=$ac_lo;; -'') if test "$ac_cv_type_uintptr_t" = yes; then - { { echo "$as_me:$LINENO: error: cannot compute sizeof (uintptr_t) -See \`config.log' for more details." >&5 -echo "$as_me: error: cannot compute sizeof (uintptr_t) -See \`config.log' for more details." >&2;} - { (exit 77); exit 77; }; } - else - ac_cv_sizeof_uintptr_t=0 - fi ;; -esac -else - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -$ac_includes_default - typedef uintptr_t ac__type_sizeof_; -static long int longval () { return (long int) (sizeof (ac__type_sizeof_)); } -static unsigned long int ulongval () { return (long int) (sizeof (ac__type_sizeof_)); } -#include -#include -int -main () -{ - - FILE *f = fopen ("conftest.val", "w"); - if (! f) - return 1; - if (((long int) (sizeof (ac__type_sizeof_))) < 0) - { - long int i = longval (); - if (i != ((long int) (sizeof (ac__type_sizeof_)))) - return 1; - fprintf (f, "%ld\n", i); - } - else - { - unsigned long int i = ulongval (); - if (i != ((long int) (sizeof (ac__type_sizeof_)))) - return 1; - fprintf (f, "%lu\n", i); - } - return ferror (f) || fclose (f) != 0; - - ; - return 0; -} -_ACEOF -rm -f conftest$ac_exeext -if { (ac_try="$ac_link" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_link") 2>&5 - ac_status=$? - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { ac_try='./conftest$ac_exeext' - { (case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_try") 2>&5 - ac_status=$? - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); }; }; then - ac_cv_sizeof_uintptr_t=`cat conftest.val` -else - echo "$as_me: program exited with status $ac_status" >&5 -echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - -( exit $ac_status ) -if test "$ac_cv_type_uintptr_t" = yes; then - { { echo "$as_me:$LINENO: error: cannot compute sizeof (uintptr_t) -See \`config.log' for more details." >&5 -echo "$as_me: error: cannot compute sizeof (uintptr_t) -See \`config.log' for more details." >&2;} - { (exit 77); exit 77; }; } - else - ac_cv_sizeof_uintptr_t=0 - fi -fi -rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext conftest.$ac_objext conftest.$ac_ext -fi -rm -f conftest.val -fi -{ echo "$as_me:$LINENO: result: $ac_cv_sizeof_uintptr_t" >&5 -echo "${ECHO_T}$ac_cv_sizeof_uintptr_t" >&6; } - - - -cat >>confdefs.h <<_ACEOF -#define SIZEOF_UINTPTR_T $ac_cv_sizeof_uintptr_t -_ACEOF - - -fi - - -{ echo "$as_me:$LINENO: checking for off_t" >&5 -echo $ECHO_N "checking for off_t... $ECHO_C" >&6; } -if test "${ac_cv_type_off_t+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 -else - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ - -#ifdef HAVE_SYS_TYPES_H -#include -#endif - - -typedef off_t ac__type_new_; -int -main () -{ -if ((ac__type_new_ *) 0) - return 0; -if (sizeof (ac__type_new_)) - return 0; - ; - return 0; -} -_ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - ac_cv_type_off_t=yes -else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - ac_cv_type_off_t=no -fi - -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext -fi -{ echo "$as_me:$LINENO: result: $ac_cv_type_off_t" >&5 -echo "${ECHO_T}$ac_cv_type_off_t" >&6; } - -# The cast to long int works around a bug in the HP C Compiler -# version HP92453-01 B.11.11.23709.GP, which incorrectly rejects -# declarations like `int a3[[(sizeof (unsigned char)) >= 0]];'. -# This bug is HP SR number 8606223364. -{ echo "$as_me:$LINENO: checking size of off_t" >&5 -echo $ECHO_N "checking size of off_t... $ECHO_C" >&6; } -if test "${ac_cv_sizeof_off_t+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 -else - if test "$cross_compiling" = yes; then - # Depending upon the size, compute the lo and hi bounds. -cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ - -#ifdef HAVE_SYS_TYPES_H -#include -#endif - - - typedef off_t ac__type_sizeof_; -int -main () -{ -static int test_array [1 - 2 * !(((long int) (sizeof (ac__type_sizeof_))) >= 0)]; -test_array [0] = 0 - - ; - return 0; -} -_ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - ac_lo=0 ac_mid=0 - while :; do - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ - -#ifdef HAVE_SYS_TYPES_H -#include -#endif - - - typedef off_t ac__type_sizeof_; -int -main () -{ -static int test_array [1 - 2 * !(((long int) (sizeof (ac__type_sizeof_))) <= $ac_mid)]; -test_array [0] = 0 - - ; - return 0; -} -_ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - ac_hi=$ac_mid; break -else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - ac_lo=`expr $ac_mid + 1` - if test $ac_lo -le $ac_mid; then - ac_lo= ac_hi= - break - fi - ac_mid=`expr 2 '*' $ac_mid + 1` -fi - -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext - done -else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ - -#ifdef HAVE_SYS_TYPES_H -#include -#endif - - - typedef off_t ac__type_sizeof_; -int -main () -{ -static int test_array [1 - 2 * !(((long int) (sizeof (ac__type_sizeof_))) < 0)]; -test_array [0] = 0 - - ; - return 0; -} -_ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - ac_hi=-1 ac_mid=-1 - while :; do - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ - -#ifdef HAVE_SYS_TYPES_H -#include -#endif - - - typedef off_t ac__type_sizeof_; -int -main () -{ -static int test_array [1 - 2 * !(((long int) (sizeof (ac__type_sizeof_))) >= $ac_mid)]; -test_array [0] = 0 - - ; - return 0; -} -_ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - ac_lo=$ac_mid; break -else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - ac_hi=`expr '(' $ac_mid ')' - 1` - if test $ac_mid -le $ac_hi; then - ac_lo= ac_hi= - break - fi - ac_mid=`expr 2 '*' $ac_mid` -fi - -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext - done -else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - ac_lo= ac_hi= -fi - -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext -fi - -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext -# Binary search between lo and hi bounds. -while test "x$ac_lo" != "x$ac_hi"; do - ac_mid=`expr '(' $ac_hi - $ac_lo ')' / 2 + $ac_lo` - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ - -#ifdef HAVE_SYS_TYPES_H -#include -#endif - - - typedef off_t ac__type_sizeof_; -int -main () -{ -static int test_array [1 - 2 * !(((long int) (sizeof (ac__type_sizeof_))) <= $ac_mid)]; -test_array [0] = 0 - - ; - return 0; -} -_ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - ac_hi=$ac_mid -else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - ac_lo=`expr '(' $ac_mid ')' + 1` -fi - -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext -done -case $ac_lo in -?*) ac_cv_sizeof_off_t=$ac_lo;; -'') if test "$ac_cv_type_off_t" = yes; then - { { echo "$as_me:$LINENO: error: cannot compute sizeof (off_t) -See \`config.log' for more details." >&5 -echo "$as_me: error: cannot compute sizeof (off_t) -See \`config.log' for more details." >&2;} - { (exit 77); exit 77; }; } - else - ac_cv_sizeof_off_t=0 - fi ;; -esac -else - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ - -#ifdef HAVE_SYS_TYPES_H -#include -#endif - - - typedef off_t ac__type_sizeof_; -static long int longval () { return (long int) (sizeof (ac__type_sizeof_)); } -static unsigned long int ulongval () { return (long int) (sizeof (ac__type_sizeof_)); } -#include -#include -int -main () -{ - - FILE *f = fopen ("conftest.val", "w"); - if (! f) - return 1; - if (((long int) (sizeof (ac__type_sizeof_))) < 0) - { - long int i = longval (); - if (i != ((long int) (sizeof (ac__type_sizeof_)))) - return 1; - fprintf (f, "%ld\n", i); - } - else - { - unsigned long int i = ulongval (); - if (i != ((long int) (sizeof (ac__type_sizeof_)))) - return 1; - fprintf (f, "%lu\n", i); - } - return ferror (f) || fclose (f) != 0; - - ; - return 0; -} -_ACEOF -rm -f conftest$ac_exeext -if { (ac_try="$ac_link" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_link") 2>&5 - ac_status=$? - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { ac_try='./conftest$ac_exeext' - { (case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_try") 2>&5 - ac_status=$? - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); }; }; then - ac_cv_sizeof_off_t=`cat conftest.val` -else - echo "$as_me: program exited with status $ac_status" >&5 -echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - -( exit $ac_status ) -if test "$ac_cv_type_off_t" = yes; then - { { echo "$as_me:$LINENO: error: cannot compute sizeof (off_t) -See \`config.log' for more details." >&5 -echo "$as_me: error: cannot compute sizeof (off_t) -See \`config.log' for more details." >&2;} - { (exit 77); exit 77; }; } - else - ac_cv_sizeof_off_t=0 - fi -fi -rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext conftest.$ac_objext conftest.$ac_ext -fi -rm -f conftest.val -fi -{ echo "$as_me:$LINENO: result: $ac_cv_sizeof_off_t" >&5 -echo "${ECHO_T}$ac_cv_sizeof_off_t" >&6; } - - - -cat >>confdefs.h <<_ACEOF -#define SIZEOF_OFF_T $ac_cv_sizeof_off_t -_ACEOF - - - -{ echo "$as_me:$LINENO: checking whether to enable large file support" >&5 -echo $ECHO_N "checking whether to enable large file support... $ECHO_C" >&6; } -if test "$have_long_long" = yes -then -if test "$ac_cv_sizeof_off_t" -gt "$ac_cv_sizeof_long" -a \ - "$ac_cv_sizeof_long_long" -ge "$ac_cv_sizeof_off_t"; then - -cat >>confdefs.h <<\_ACEOF -#define HAVE_LARGEFILE_SUPPORT 1 -_ACEOF - - { echo "$as_me:$LINENO: result: yes" >&5 -echo "${ECHO_T}yes" >&6; } -else - { echo "$as_me:$LINENO: result: no" >&5 -echo "${ECHO_T}no" >&6; } -fi -else - { echo "$as_me:$LINENO: result: no" >&5 -echo "${ECHO_T}no" >&6; } -fi - -{ echo "$as_me:$LINENO: checking for time_t" >&5 -echo $ECHO_N "checking for time_t... $ECHO_C" >&6; } -if test "${ac_cv_type_time_t+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 -else - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ - -#ifdef HAVE_SYS_TYPES_H -#include -#endif -#ifdef HAVE_TIME_H -#include -#endif - - -typedef time_t ac__type_new_; -int -main () -{ -if ((ac__type_new_ *) 0) - return 0; -if (sizeof (ac__type_new_)) - return 0; - ; - return 0; -} -_ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - ac_cv_type_time_t=yes -else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - ac_cv_type_time_t=no -fi - -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext -fi -{ echo "$as_me:$LINENO: result: $ac_cv_type_time_t" >&5 -echo "${ECHO_T}$ac_cv_type_time_t" >&6; } - -# The cast to long int works around a bug in the HP C Compiler -# version HP92453-01 B.11.11.23709.GP, which incorrectly rejects -# declarations like `int a3[[(sizeof (unsigned char)) >= 0]];'. -# This bug is HP SR number 8606223364. -{ echo "$as_me:$LINENO: checking size of time_t" >&5 -echo $ECHO_N "checking size of time_t... $ECHO_C" >&6; } -if test "${ac_cv_sizeof_time_t+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 -else - if test "$cross_compiling" = yes; then - # Depending upon the size, compute the lo and hi bounds. -cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ - -#ifdef HAVE_SYS_TYPES_H -#include -#endif -#ifdef HAVE_TIME_H -#include -#endif - - - typedef time_t ac__type_sizeof_; -int -main () -{ -static int test_array [1 - 2 * !(((long int) (sizeof (ac__type_sizeof_))) >= 0)]; -test_array [0] = 0 - - ; - return 0; -} -_ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - ac_lo=0 ac_mid=0 - while :; do - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ - -#ifdef HAVE_SYS_TYPES_H -#include -#endif -#ifdef HAVE_TIME_H -#include -#endif - - - typedef time_t ac__type_sizeof_; -int -main () -{ -static int test_array [1 - 2 * !(((long int) (sizeof (ac__type_sizeof_))) <= $ac_mid)]; -test_array [0] = 0 - - ; - return 0; -} -_ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - ac_hi=$ac_mid; break -else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - ac_lo=`expr $ac_mid + 1` - if test $ac_lo -le $ac_mid; then - ac_lo= ac_hi= - break - fi - ac_mid=`expr 2 '*' $ac_mid + 1` -fi - -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext - done -else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ - -#ifdef HAVE_SYS_TYPES_H -#include -#endif -#ifdef HAVE_TIME_H -#include -#endif - - - typedef time_t ac__type_sizeof_; -int -main () -{ -static int test_array [1 - 2 * !(((long int) (sizeof (ac__type_sizeof_))) < 0)]; -test_array [0] = 0 - - ; - return 0; -} -_ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - ac_hi=-1 ac_mid=-1 - while :; do - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ - -#ifdef HAVE_SYS_TYPES_H -#include -#endif -#ifdef HAVE_TIME_H -#include -#endif - - - typedef time_t ac__type_sizeof_; -int -main () -{ -static int test_array [1 - 2 * !(((long int) (sizeof (ac__type_sizeof_))) >= $ac_mid)]; -test_array [0] = 0 - - ; - return 0; -} -_ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - ac_lo=$ac_mid; break -else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - ac_hi=`expr '(' $ac_mid ')' - 1` - if test $ac_mid -le $ac_hi; then - ac_lo= ac_hi= - break - fi - ac_mid=`expr 2 '*' $ac_mid` -fi - -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext - done -else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - ac_lo= ac_hi= -fi - -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext -fi - -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext -# Binary search between lo and hi bounds. -while test "x$ac_lo" != "x$ac_hi"; do - ac_mid=`expr '(' $ac_hi - $ac_lo ')' / 2 + $ac_lo` - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ - -#ifdef HAVE_SYS_TYPES_H -#include -#endif -#ifdef HAVE_TIME_H -#include -#endif - - - typedef time_t ac__type_sizeof_; -int -main () -{ -static int test_array [1 - 2 * !(((long int) (sizeof (ac__type_sizeof_))) <= $ac_mid)]; -test_array [0] = 0 - - ; - return 0; -} -_ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - ac_hi=$ac_mid -else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - ac_lo=`expr '(' $ac_mid ')' + 1` -fi - -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext -done -case $ac_lo in -?*) ac_cv_sizeof_time_t=$ac_lo;; -'') if test "$ac_cv_type_time_t" = yes; then - { { echo "$as_me:$LINENO: error: cannot compute sizeof (time_t) -See \`config.log' for more details." >&5 -echo "$as_me: error: cannot compute sizeof (time_t) -See \`config.log' for more details." >&2;} - { (exit 77); exit 77; }; } - else - ac_cv_sizeof_time_t=0 - fi ;; -esac -else - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ - -#ifdef HAVE_SYS_TYPES_H -#include -#endif -#ifdef HAVE_TIME_H -#include -#endif - - - typedef time_t ac__type_sizeof_; -static long int longval () { return (long int) (sizeof (ac__type_sizeof_)); } -static unsigned long int ulongval () { return (long int) (sizeof (ac__type_sizeof_)); } -#include -#include -int -main () -{ - - FILE *f = fopen ("conftest.val", "w"); - if (! f) - return 1; - if (((long int) (sizeof (ac__type_sizeof_))) < 0) - { - long int i = longval (); - if (i != ((long int) (sizeof (ac__type_sizeof_)))) - return 1; - fprintf (f, "%ld\n", i); - } - else - { - unsigned long int i = ulongval (); - if (i != ((long int) (sizeof (ac__type_sizeof_)))) - return 1; - fprintf (f, "%lu\n", i); - } - return ferror (f) || fclose (f) != 0; - - ; - return 0; -} -_ACEOF -rm -f conftest$ac_exeext -if { (ac_try="$ac_link" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_link") 2>&5 - ac_status=$? - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { ac_try='./conftest$ac_exeext' - { (case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_try") 2>&5 - ac_status=$? - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); }; }; then - ac_cv_sizeof_time_t=`cat conftest.val` -else - echo "$as_me: program exited with status $ac_status" >&5 -echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - -( exit $ac_status ) -if test "$ac_cv_type_time_t" = yes; then - { { echo "$as_me:$LINENO: error: cannot compute sizeof (time_t) -See \`config.log' for more details." >&5 -echo "$as_me: error: cannot compute sizeof (time_t) -See \`config.log' for more details." >&2;} - { (exit 77); exit 77; }; } - else - ac_cv_sizeof_time_t=0 - fi -fi -rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext conftest.$ac_objext conftest.$ac_ext -fi -rm -f conftest.val -fi -{ echo "$as_me:$LINENO: result: $ac_cv_sizeof_time_t" >&5 -echo "${ECHO_T}$ac_cv_sizeof_time_t" >&6; } - - - -cat >>confdefs.h <<_ACEOF -#define SIZEOF_TIME_T $ac_cv_sizeof_time_t -_ACEOF - - - -# if have pthread_t then define SIZEOF_PTHREAD_T -ac_save_cc="$CC" -if test "$ac_cv_kpthread" = "yes" -then CC="$CC -Kpthread" -elif test "$ac_cv_kthread" = "yes" -then CC="$CC -Kthread" -elif test "$ac_cv_pthread" = "yes" -then CC="$CC -pthread" -fi - -{ echo "$as_me:$LINENO: checking for pthread_t" >&5 -echo $ECHO_N "checking for pthread_t... $ECHO_C" >&6; } -have_pthread_t=no -cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -#include -int -main () -{ -pthread_t x; x = *(pthread_t*)0; - ; - return 0; -} -_ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - have_pthread_t=yes -else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - -fi - -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext -{ echo "$as_me:$LINENO: result: $have_pthread_t" >&5 -echo "${ECHO_T}$have_pthread_t" >&6; } -if test "$have_pthread_t" = yes ; then - { echo "$as_me:$LINENO: checking for pthread_t" >&5 -echo $ECHO_N "checking for pthread_t... $ECHO_C" >&6; } -if test "${ac_cv_type_pthread_t+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 -else - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ - -#ifdef HAVE_PTHREAD_H -#include -#endif - - -typedef pthread_t ac__type_new_; -int -main () -{ -if ((ac__type_new_ *) 0) - return 0; -if (sizeof (ac__type_new_)) - return 0; - ; - return 0; -} -_ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - ac_cv_type_pthread_t=yes -else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - ac_cv_type_pthread_t=no -fi - -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext -fi -{ echo "$as_me:$LINENO: result: $ac_cv_type_pthread_t" >&5 -echo "${ECHO_T}$ac_cv_type_pthread_t" >&6; } - -# The cast to long int works around a bug in the HP C Compiler -# version HP92453-01 B.11.11.23709.GP, which incorrectly rejects -# declarations like `int a3[[(sizeof (unsigned char)) >= 0]];'. -# This bug is HP SR number 8606223364. -{ echo "$as_me:$LINENO: checking size of pthread_t" >&5 -echo $ECHO_N "checking size of pthread_t... $ECHO_C" >&6; } -if test "${ac_cv_sizeof_pthread_t+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 -else - if test "$cross_compiling" = yes; then - # Depending upon the size, compute the lo and hi bounds. -cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ - -#ifdef HAVE_PTHREAD_H -#include -#endif - - - typedef pthread_t ac__type_sizeof_; -int -main () -{ -static int test_array [1 - 2 * !(((long int) (sizeof (ac__type_sizeof_))) >= 0)]; -test_array [0] = 0 - - ; - return 0; -} -_ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - ac_lo=0 ac_mid=0 - while :; do - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ - -#ifdef HAVE_PTHREAD_H -#include -#endif - - - typedef pthread_t ac__type_sizeof_; -int -main () -{ -static int test_array [1 - 2 * !(((long int) (sizeof (ac__type_sizeof_))) <= $ac_mid)]; -test_array [0] = 0 - - ; - return 0; -} -_ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - ac_hi=$ac_mid; break -else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - ac_lo=`expr $ac_mid + 1` - if test $ac_lo -le $ac_mid; then - ac_lo= ac_hi= - break - fi - ac_mid=`expr 2 '*' $ac_mid + 1` -fi - -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext - done -else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ - -#ifdef HAVE_PTHREAD_H -#include -#endif - - - typedef pthread_t ac__type_sizeof_; -int -main () -{ -static int test_array [1 - 2 * !(((long int) (sizeof (ac__type_sizeof_))) < 0)]; -test_array [0] = 0 - - ; - return 0; -} -_ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - ac_hi=-1 ac_mid=-1 - while :; do - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ - -#ifdef HAVE_PTHREAD_H -#include -#endif - - - typedef pthread_t ac__type_sizeof_; -int -main () -{ -static int test_array [1 - 2 * !(((long int) (sizeof (ac__type_sizeof_))) >= $ac_mid)]; -test_array [0] = 0 - - ; - return 0; -} -_ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - ac_lo=$ac_mid; break -else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - ac_hi=`expr '(' $ac_mid ')' - 1` - if test $ac_mid -le $ac_hi; then - ac_lo= ac_hi= - break - fi - ac_mid=`expr 2 '*' $ac_mid` -fi - -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext - done -else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - ac_lo= ac_hi= -fi - -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext -fi - -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext -# Binary search between lo and hi bounds. -while test "x$ac_lo" != "x$ac_hi"; do - ac_mid=`expr '(' $ac_hi - $ac_lo ')' / 2 + $ac_lo` - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ - -#ifdef HAVE_PTHREAD_H -#include -#endif - - - typedef pthread_t ac__type_sizeof_; -int -main () -{ -static int test_array [1 - 2 * !(((long int) (sizeof (ac__type_sizeof_))) <= $ac_mid)]; -test_array [0] = 0 - - ; - return 0; -} -_ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - ac_hi=$ac_mid -else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - ac_lo=`expr '(' $ac_mid ')' + 1` -fi - -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext -done -case $ac_lo in -?*) ac_cv_sizeof_pthread_t=$ac_lo;; -'') if test "$ac_cv_type_pthread_t" = yes; then - { { echo "$as_me:$LINENO: error: cannot compute sizeof (pthread_t) -See \`config.log' for more details." >&5 -echo "$as_me: error: cannot compute sizeof (pthread_t) -See \`config.log' for more details." >&2;} - { (exit 77); exit 77; }; } - else - ac_cv_sizeof_pthread_t=0 - fi ;; -esac -else - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ - -#ifdef HAVE_PTHREAD_H -#include -#endif - - - typedef pthread_t ac__type_sizeof_; -static long int longval () { return (long int) (sizeof (ac__type_sizeof_)); } -static unsigned long int ulongval () { return (long int) (sizeof (ac__type_sizeof_)); } -#include -#include -int -main () -{ - - FILE *f = fopen ("conftest.val", "w"); - if (! f) - return 1; - if (((long int) (sizeof (ac__type_sizeof_))) < 0) - { - long int i = longval (); - if (i != ((long int) (sizeof (ac__type_sizeof_)))) - return 1; - fprintf (f, "%ld\n", i); - } - else - { - unsigned long int i = ulongval (); - if (i != ((long int) (sizeof (ac__type_sizeof_)))) - return 1; - fprintf (f, "%lu\n", i); - } - return ferror (f) || fclose (f) != 0; - - ; - return 0; -} -_ACEOF -rm -f conftest$ac_exeext -if { (ac_try="$ac_link" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_link") 2>&5 - ac_status=$? - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { ac_try='./conftest$ac_exeext' - { (case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_try") 2>&5 - ac_status=$? - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); }; }; then - ac_cv_sizeof_pthread_t=`cat conftest.val` -else - echo "$as_me: program exited with status $ac_status" >&5 -echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - -( exit $ac_status ) -if test "$ac_cv_type_pthread_t" = yes; then - { { echo "$as_me:$LINENO: error: cannot compute sizeof (pthread_t) -See \`config.log' for more details." >&5 -echo "$as_me: error: cannot compute sizeof (pthread_t) -See \`config.log' for more details." >&2;} - { (exit 77); exit 77; }; } - else - ac_cv_sizeof_pthread_t=0 - fi -fi -rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext conftest.$ac_objext conftest.$ac_ext -fi -rm -f conftest.val -fi -{ echo "$as_me:$LINENO: result: $ac_cv_sizeof_pthread_t" >&5 -echo "${ECHO_T}$ac_cv_sizeof_pthread_t" >&6; } - - - -cat >>confdefs.h <<_ACEOF -#define SIZEOF_PTHREAD_T $ac_cv_sizeof_pthread_t -_ACEOF - - -fi -CC="$ac_save_cc" - - -case $ac_sys_system/$ac_sys_release in - Darwin/[01567]\..*) - OTHER_LIBTOOL_OPT="-prebind -seg1addr 0x10000000" - ;; - Darwin/*) - OTHER_LIBTOOL_OPT="" - ;; -esac - - -ARCH_RUN_32BIT="" - -case $ac_sys_system/$ac_sys_release in - Darwin/[01567]\..*) - LIBTOOL_CRUFT="-framework System -lcc_dynamic" - if test "${enable_universalsdk}"; then - : - else - LIBTOOL_CRUFT="${LIBTOOL_CRUFT} -arch_only `/usr/bin/arch`" - fi - LIBTOOL_CRUFT=$LIBTOOL_CRUFT' -install_name $(PYTHONFRAMEWORKINSTALLDIR)/Versions/$(VERSION)/$(PYTHONFRAMEWORK)' - LIBTOOL_CRUFT=$LIBTOOL_CRUFT' -compatibility_version $(VERSION) -current_version $(VERSION)';; - Darwin/*) - gcc_version=`gcc -dumpversion` - if test ${gcc_version} '<' 4.0 - then - LIBTOOL_CRUFT="-lcc_dynamic" - else - LIBTOOL_CRUFT="" - fi - if test "$cross_compiling" = yes; then - ac_osx_32bit=yes -else - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ - - #include - int main(int argc, char*argv[]) - { - if (sizeof(long) == 4) { - return 0; - } else { - return 1; - } - } - -_ACEOF -rm -f conftest$ac_exeext -if { (ac_try="$ac_link" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_link") 2>&5 - ac_status=$? - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { ac_try='./conftest$ac_exeext' - { (case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_try") 2>&5 - ac_status=$? - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); }; }; then - ac_osx_32bit=yes -else - echo "$as_me: program exited with status $ac_status" >&5 -echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - -( exit $ac_status ) -ac_osx_32bit=no -fi -rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext conftest.$ac_objext conftest.$ac_ext -fi - - - - if test "${ac_osx_32bit}" = "yes"; then - case `/usr/bin/arch` in - i386) - MACOSX_DEFAULT_ARCH="i386" - ;; - ppc) - MACOSX_DEFAULT_ARCH="ppc" - ;; - *) - { { echo "$as_me:$LINENO: error: Unexpected output of 'arch' on OSX" >&5 -echo "$as_me: error: Unexpected output of 'arch' on OSX" >&2;} - { (exit 1); exit 1; }; } - ;; - esac - else - case `/usr/bin/arch` in - i386) - MACOSX_DEFAULT_ARCH="x86_64" - ;; - ppc) - MACOSX_DEFAULT_ARCH="ppc64" - ;; - *) - { { echo "$as_me:$LINENO: error: Unexpected output of 'arch' on OSX" >&5 -echo "$as_me: error: Unexpected output of 'arch' on OSX" >&2;} - { (exit 1); exit 1; }; } - ;; - esac - - #ARCH_RUN_32BIT="true" - fi - - LIBTOOL_CRUFT=$LIBTOOL_CRUFT" -lSystem -lSystemStubs -arch_only ${MACOSX_DEFAULT_ARCH}" - LIBTOOL_CRUFT=$LIBTOOL_CRUFT' -install_name $(PYTHONFRAMEWORKINSTALLDIR)/Versions/$(VERSION)/$(PYTHONFRAMEWORK)' - LIBTOOL_CRUFT=$LIBTOOL_CRUFT' -compatibility_version $(VERSION) -current_version $(VERSION)';; -esac - -{ echo "$as_me:$LINENO: checking for --enable-framework" >&5 -echo $ECHO_N "checking for --enable-framework... $ECHO_C" >&6; } -if test "$enable_framework" -then - BASECFLAGS="$BASECFLAGS -fno-common -dynamic" - # -F. is needed to allow linking to the framework while - # in the build location. - -cat >>confdefs.h <<\_ACEOF -#define WITH_NEXT_FRAMEWORK 1 -_ACEOF - - { echo "$as_me:$LINENO: result: yes" >&5 -echo "${ECHO_T}yes" >&6; } - if test $enable_shared = "yes" - then - { { echo "$as_me:$LINENO: error: Specifying both --enable-shared and --enable-framework is not supported, use only --enable-framework instead" >&5 -echo "$as_me: error: Specifying both --enable-shared and --enable-framework is not supported, use only --enable-framework instead" >&2;} - { (exit 1); exit 1; }; } - fi -else - { echo "$as_me:$LINENO: result: no" >&5 -echo "${ECHO_T}no" >&6; } -fi - -{ echo "$as_me:$LINENO: checking for dyld" >&5 -echo $ECHO_N "checking for dyld... $ECHO_C" >&6; } -case $ac_sys_system/$ac_sys_release in - Darwin/*) - -cat >>confdefs.h <<\_ACEOF -#define WITH_DYLD 1 -_ACEOF - - { echo "$as_me:$LINENO: result: always on for Darwin" >&5 -echo "${ECHO_T}always on for Darwin" >&6; } - ;; - *) - { echo "$as_me:$LINENO: result: no" >&5 -echo "${ECHO_T}no" >&6; } - ;; -esac - -# Set info about shared libraries. - - - - - - -# SO is the extension of shared libraries `(including the dot!) -# -- usually .so, .sl on HP-UX, .dll on Cygwin -{ echo "$as_me:$LINENO: checking SO" >&5 -echo $ECHO_N "checking SO... $ECHO_C" >&6; } -if test -z "$SO" -then - case $ac_sys_system in - hp*|HP*) - case `uname -m` in - ia64) SO=.so;; - *) SO=.sl;; - esac - ;; - CYGWIN*) SO=.dll;; - *) SO=.so;; - esac -else - # this might also be a termcap variable, see #610332 - echo - echo '=====================================================================' - echo '+ +' - echo '+ WARNING: You have set SO in your environment. +' - echo '+ Do you really mean to change the extension for shared libraries? +' - echo '+ Continuing in 10 seconds to let you to ponder. +' - echo '+ +' - echo '=====================================================================' - sleep 10 -fi -{ echo "$as_me:$LINENO: result: $SO" >&5 -echo "${ECHO_T}$SO" >&6; } - - -cat >>confdefs.h <<_ACEOF -#define SHLIB_EXT "$SO" -_ACEOF - -# LDSHARED is the ld *command* used to create shared library -# -- "cc -G" on SunOS 5.x, "ld -shared" on IRIX 5 -# (Shared libraries in this instance are shared modules to be loaded into -# Python, as opposed to building Python itself as a shared library.) -{ echo "$as_me:$LINENO: checking LDSHARED" >&5 -echo $ECHO_N "checking LDSHARED... $ECHO_C" >&6; } -if test -z "$LDSHARED" -then - case $ac_sys_system/$ac_sys_release in - AIX*) - BLDSHARED="\$(srcdir)/Modules/ld_so_aix \$(CC) -bI:Modules/python.exp" - LDSHARED="\$(BINLIBDEST)/config/ld_so_aix \$(CC) -bI:\$(BINLIBDEST)/config/python.exp" - ;; - IRIX/5*) LDSHARED="ld -shared";; - IRIX*/6*) LDSHARED="ld ${SGI_ABI} -shared -all";; - SunOS/5*) - if test "$GCC" = "yes" ; then - LDSHARED='$(CC) -shared' - LDCXXSHARED='$(CXX) -shared' - else - LDSHARED='$(CC) -G' - LDCXXSHARED='$(CXX) -G' - fi ;; - hp*|HP*) - if test "$GCC" = "yes" ; then - LDSHARED='$(CC) -shared' - LDCXXSHARED='$(CXX) -shared' - else - LDSHARED='ld -b' - fi ;; - OSF*) LDSHARED="ld -shared -expect_unresolved \"*\"";; - Darwin/1.3*) - LDSHARED='$(CC) $(LDFLAGS) -bundle' - LDCXXSHARED='$(CXX) $(LDFLAGS) -bundle' - if test "$enable_framework" ; then - # Link against the framework. All externals should be defined. - BLDSHARED="$LDSHARED "'$(PYTHONFRAMEWORKDIR)/Versions/$(VERSION)/$(PYTHONFRAMEWORK)' - LDSHARED="$LDSHARED "'$(PYTHONFRAMEWORKPREFIX)/$(PYTHONFRAMEWORKDIR)/Versions/$(VERSION)/$(PYTHONFRAMEWORK)' - LDCXXSHARED="$LDCXXSHARED "'$(PYTHONFRAMEWORKPREFIX)/$(PYTHONFRAMEWORKDIR)/Versions/$(VERSION)/$(PYTHONFRAMEWORK)' - else - # No framework. Ignore undefined symbols, assuming they come from Python - LDSHARED="$LDSHARED -undefined suppress" - LDCXXSHARED="$LDCXXSHARED -undefined suppress" - fi ;; - Darwin/1.4*|Darwin/5.*|Darwin/6.*) - LDSHARED='$(CC) $(LDFLAGS) -bundle' - LDCXXSHARED='$(CXX) $(LDFLAGS) -bundle' - if test "$enable_framework" ; then - # Link against the framework. All externals should be defined. - BLDSHARED="$LDSHARED "'$(PYTHONFRAMEWORKDIR)/Versions/$(VERSION)/$(PYTHONFRAMEWORK)' - LDSHARED="$LDSHARED "'$(PYTHONFRAMEWORKPREFIX)/$(PYTHONFRAMEWORKDIR)/Versions/$(VERSION)/$(PYTHONFRAMEWORK)' - LDCXXSHARED="$LDCXXSHARED "'$(PYTHONFRAMEWORKPREFIX)/$(PYTHONFRAMEWORKDIR)/Versions/$(VERSION)/$(PYTHONFRAMEWORK)' - else - # No framework, use the Python app as bundle-loader - BLDSHARED="$LDSHARED "'-bundle_loader $(BUILDPYTHON)' - LDSHARED="$LDSHARED "'-bundle_loader $(BINDIR)/python$(VERSION)$(EXE)' - LDCXXSHARED="$LDCXXSHARED "'-bundle_loader $(BINDIR)/python$(VERSION)$(EXE)' - fi ;; - Darwin/*) - # Use -undefined dynamic_lookup whenever possible (10.3 and later). - # This allows an extension to be used in any Python - - if test ${MACOSX_DEPLOYMENT_TARGET} '>' 10.2 - then - if test "${enable_universalsdk}"; then - LDFLAGS="${UNIVERSAL_ARCH_FLAGS} -isysroot ${UNIVERSALSDK} ${LDFLAGS}" - fi - LDSHARED='$(CC) $(LDFLAGS) -bundle -undefined dynamic_lookup' - LDCXXSHARED='$(CXX) $(LDFLAGS) -bundle -undefined dynamic_lookup' - BLDSHARED="$LDSHARED" - else - LDSHARED='$(CC) $(LDFLAGS) -bundle' - LDCXXSHARED='$(CXX) $(LDFLAGS) -bundle' - if test "$enable_framework" ; then - # Link against the framework. All externals should be defined. - BLDSHARED="$LDSHARED "'$(PYTHONFRAMEWORKDIR)/Versions/$(VERSION)/$(PYTHONFRAMEWORK)' - LDSHARED="$LDSHARED "'$(PYTHONFRAMEWORKPREFIX)/$(PYTHONFRAMEWORKDIR)/Versions/$(VERSION)/$(PYTHONFRAMEWORK)' - LDCXXSHARED="$LDCXXSHARED "'$(PYTHONFRAMEWORKPREFIX)/$(PYTHONFRAMEWORKDIR)/Versions/$(VERSION)/$(PYTHONFRAMEWORK)' - else - # No framework, use the Python app as bundle-loader - BLDSHARED="$LDSHARED "'-bundle_loader $(BUILDPYTHON)' - LDSHARED="$LDSHARED "'-bundle_loader $(BINDIR)/python$(VERSION)$(EXE)' - LDCXXSHARED="$LDCXXSHARED "'-bundle_loader $(BINDIR)/python$(VERSION)$(EXE)' - fi - fi - ;; - Linux*|GNU*|QNX*) - LDSHARED='$(CC) -shared' - LDCXXSHARED='$(CXX) -shared';; - BSD/OS*/4*) - LDSHARED="gcc -shared" - LDCXXSHARED="g++ -shared";; - FreeBSD*) - if [ "`$CC -dM -E - &5 -echo "${ECHO_T}$LDSHARED" >&6; } -LDCXXSHARED=${LDCXXSHARED-$LDSHARED} -BLDSHARED=${BLDSHARED-$LDSHARED} -# CCSHARED are the C *flags* used to create objects to go into a shared -# library (module) -- this is only needed for a few systems -{ echo "$as_me:$LINENO: checking CCSHARED" >&5 -echo $ECHO_N "checking CCSHARED... $ECHO_C" >&6; } -if test -z "$CCSHARED" -then - case $ac_sys_system/$ac_sys_release in - SunOS*) if test "$GCC" = yes; - then CCSHARED="-fPIC"; - elif test `uname -p` = sparc; - then CCSHARED="-xcode=pic32"; - else CCSHARED="-Kpic"; - fi;; - hp*|HP*) if test "$GCC" = yes; - then CCSHARED="-fPIC"; - else CCSHARED="+z"; - fi;; - Linux*|GNU*) CCSHARED="-fPIC";; - BSD/OS*/4*) CCSHARED="-fpic";; - FreeBSD*|NetBSD*|OpenBSD*|DragonFly*) CCSHARED="-fPIC";; - OpenUNIX*|UnixWare*) - if test "$GCC" = "yes" - then CCSHARED="-fPIC" - else CCSHARED="-KPIC" - fi;; - SCO_SV*) - if test "$GCC" = "yes" - then CCSHARED="-fPIC" - else CCSHARED="-Kpic -belf" - fi;; - IRIX*/6*) case $CC in - *gcc*) CCSHARED="-shared";; - *) CCSHARED="";; - esac;; - esac -fi -{ echo "$as_me:$LINENO: result: $CCSHARED" >&5 -echo "${ECHO_T}$CCSHARED" >&6; } -# LINKFORSHARED are the flags passed to the $(CC) command that links -# the python executable -- this is only needed for a few systems -{ echo "$as_me:$LINENO: checking LINKFORSHARED" >&5 -echo $ECHO_N "checking LINKFORSHARED... $ECHO_C" >&6; } -if test -z "$LINKFORSHARED" -then - case $ac_sys_system/$ac_sys_release in - AIX*) LINKFORSHARED='-Wl,-bE:Modules/python.exp -lld';; - hp*|HP*) - 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";; - # -u libsys_s pulls in all symbols in libsys - Darwin/*) - LINKFORSHARED="$extra_undefs -framework CoreFoundation" - if test "$enable_framework" - then - LINKFORSHARED="$LINKFORSHARED "'$(PYTHONFRAMEWORKDIR)/Versions/$(VERSION)/$(PYTHONFRAMEWORK)' - fi - LINKFORSHARED="$LINKFORSHARED";; - OpenUNIX*|UnixWare*) LINKFORSHARED="-Wl,-Bexport";; - SCO_SV*) LINKFORSHARED="-Wl,-Bexport";; - ReliantUNIX*) LINKFORSHARED="-W1 -Blargedynsym";; - FreeBSD*|NetBSD*|OpenBSD*|DragonFly*) - if [ "`$CC -dM -E - &1 | grep export-dynamic >/dev/null - then - LINKFORSHARED="-Xlinker --export-dynamic" - fi;; - esac;; - CYGWIN*) - if test $enable_shared = "no" - then - LINKFORSHARED='-Wl,--out-implib=$(LDLIBRARY)' - fi;; - QNX*) - # -Wl,-E causes the symbols to be added to the dynamic - # symbol table so that they can be found when a module - # is loaded. -N 2048K causes the stack size to be set - # to 2048 kilobytes so that the stack doesn't overflow - # when running test_compile.py. - LINKFORSHARED='-Wl,-E -N 2048K';; - esac -fi -{ echo "$as_me:$LINENO: result: $LINKFORSHARED" >&5 -echo "${ECHO_T}$LINKFORSHARED" >&6; } - - - -{ echo "$as_me:$LINENO: checking CFLAGSFORSHARED" >&5 -echo $ECHO_N "checking CFLAGSFORSHARED... $ECHO_C" >&6; } -if test ! "$LIBRARY" = "$LDLIBRARY" -then - case $ac_sys_system in - CYGWIN*) - # Cygwin needs CCSHARED when building extension DLLs - # but not when building the interpreter DLL. - CFLAGSFORSHARED='';; - *) - CFLAGSFORSHARED='$(CCSHARED)' - esac -fi -{ echo "$as_me:$LINENO: result: $CFLAGSFORSHARED" >&5 -echo "${ECHO_T}$CFLAGSFORSHARED" >&6; } - -# SHLIBS are libraries (except -lc and -lm) to link to the python shared -# library (with --enable-shared). -# For platforms on which shared libraries are not allowed to have unresolved -# symbols, this must be set to $(LIBS) (expanded by make). We do this even -# if it is not required, since it creates a dependency of the shared library -# to LIBS. This, in turn, means that applications linking the shared libpython -# don't need to link LIBS explicitly. The default should be only changed -# on systems where this approach causes problems. - -{ echo "$as_me:$LINENO: checking SHLIBS" >&5 -echo $ECHO_N "checking SHLIBS... $ECHO_C" >&6; } -case "$ac_sys_system" in - *) - SHLIBS='$(LIBS)';; -esac -{ echo "$as_me:$LINENO: result: $SHLIBS" >&5 -echo "${ECHO_T}$SHLIBS" >&6; } - - -# checks for libraries - -{ echo "$as_me:$LINENO: checking for dlopen in -ldl" >&5 -echo $ECHO_N "checking for dlopen in -ldl... $ECHO_C" >&6; } -if test "${ac_cv_lib_dl_dlopen+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 -else - ac_check_lib_save_LIBS=$LIBS -LIBS="-ldl $LIBS" -cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ - -/* Override any GCC internal prototype to avoid an error. - Use char because int might match the return type of a GCC - builtin and then its argument prototype would still apply. */ -#ifdef __cplusplus -extern "C" -#endif -char dlopen (); -int -main () -{ -return dlopen (); - ; - return 0; -} -_ACEOF -rm -f conftest.$ac_objext conftest$ac_exeext -if { (ac_try="$ac_link" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_link") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest$ac_exeext && - $as_test_x conftest$ac_exeext; then - ac_cv_lib_dl_dlopen=yes -else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - ac_cv_lib_dl_dlopen=no -fi - -rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \ - conftest$ac_exeext conftest.$ac_ext -LIBS=$ac_check_lib_save_LIBS -fi -{ echo "$as_me:$LINENO: result: $ac_cv_lib_dl_dlopen" >&5 -echo "${ECHO_T}$ac_cv_lib_dl_dlopen" >&6; } -if test $ac_cv_lib_dl_dlopen = yes; then - cat >>confdefs.h <<_ACEOF -#define HAVE_LIBDL 1 -_ACEOF - - LIBS="-ldl $LIBS" - -fi - # Dynamic linking for SunOS/Solaris and SYSV - -{ echo "$as_me:$LINENO: checking for shl_load in -ldld" >&5 -echo $ECHO_N "checking for shl_load in -ldld... $ECHO_C" >&6; } -if test "${ac_cv_lib_dld_shl_load+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 -else - ac_check_lib_save_LIBS=$LIBS -LIBS="-ldld $LIBS" -cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ - -/* Override any GCC internal prototype to avoid an error. - Use char because int might match the return type of a GCC - builtin and then its argument prototype would still apply. */ -#ifdef __cplusplus -extern "C" -#endif -char shl_load (); -int -main () -{ -return shl_load (); - ; - return 0; -} -_ACEOF -rm -f conftest.$ac_objext conftest$ac_exeext -if { (ac_try="$ac_link" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_link") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest$ac_exeext && - $as_test_x conftest$ac_exeext; then - ac_cv_lib_dld_shl_load=yes -else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - ac_cv_lib_dld_shl_load=no -fi - -rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \ - conftest$ac_exeext conftest.$ac_ext -LIBS=$ac_check_lib_save_LIBS -fi -{ echo "$as_me:$LINENO: result: $ac_cv_lib_dld_shl_load" >&5 -echo "${ECHO_T}$ac_cv_lib_dld_shl_load" >&6; } -if test $ac_cv_lib_dld_shl_load = yes; then - cat >>confdefs.h <<_ACEOF -#define HAVE_LIBDLD 1 -_ACEOF - - LIBS="-ldld $LIBS" - -fi - # Dynamic linking for HP-UX - -# only check for sem_init if thread support is requested -if test "$with_threads" = "yes" -o -z "$with_threads"; then - { echo "$as_me:$LINENO: checking for library containing sem_init" >&5 -echo $ECHO_N "checking for library containing sem_init... $ECHO_C" >&6; } -if test "${ac_cv_search_sem_init+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 -else - ac_func_search_save_LIBS=$LIBS -cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ - -/* Override any GCC internal prototype to avoid an error. - Use char because int might match the return type of a GCC - builtin and then its argument prototype would still apply. */ -#ifdef __cplusplus -extern "C" -#endif -char sem_init (); -int -main () -{ -return sem_init (); - ; - return 0; -} -_ACEOF -for ac_lib in '' pthread rt posix4; do - if test -z "$ac_lib"; then - ac_res="none required" - else - ac_res=-l$ac_lib - LIBS="-l$ac_lib $ac_func_search_save_LIBS" - fi - rm -f conftest.$ac_objext conftest$ac_exeext -if { (ac_try="$ac_link" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_link") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest$ac_exeext && - $as_test_x conftest$ac_exeext; then - ac_cv_search_sem_init=$ac_res -else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - -fi - -rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \ - conftest$ac_exeext - if test "${ac_cv_search_sem_init+set}" = set; then - break -fi -done -if test "${ac_cv_search_sem_init+set}" = set; then - : -else - ac_cv_search_sem_init=no -fi -rm conftest.$ac_ext -LIBS=$ac_func_search_save_LIBS -fi -{ echo "$as_me:$LINENO: result: $ac_cv_search_sem_init" >&5 -echo "${ECHO_T}$ac_cv_search_sem_init" >&6; } -ac_res=$ac_cv_search_sem_init -if test "$ac_res" != no; then - test "$ac_res" = "none required" || LIBS="$ac_res $LIBS" - -fi - # 'Real Time' functions on Solaris - # posix4 on Solaris 2.6 - # pthread (first!) on Linux -fi - -# check if we need libintl for locale functions -{ echo "$as_me:$LINENO: checking for textdomain in -lintl" >&5 -echo $ECHO_N "checking for textdomain in -lintl... $ECHO_C" >&6; } -if test "${ac_cv_lib_intl_textdomain+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 -else - ac_check_lib_save_LIBS=$LIBS -LIBS="-lintl $LIBS" -cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ - -/* Override any GCC internal prototype to avoid an error. - Use char because int might match the return type of a GCC - builtin and then its argument prototype would still apply. */ -#ifdef __cplusplus -extern "C" -#endif -char textdomain (); -int -main () -{ -return textdomain (); - ; - return 0; -} -_ACEOF -rm -f conftest.$ac_objext conftest$ac_exeext -if { (ac_try="$ac_link" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_link") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest$ac_exeext && - $as_test_x conftest$ac_exeext; then - ac_cv_lib_intl_textdomain=yes -else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - ac_cv_lib_intl_textdomain=no -fi - -rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \ - conftest$ac_exeext conftest.$ac_ext -LIBS=$ac_check_lib_save_LIBS -fi -{ echo "$as_me:$LINENO: result: $ac_cv_lib_intl_textdomain" >&5 -echo "${ECHO_T}$ac_cv_lib_intl_textdomain" >&6; } -if test $ac_cv_lib_intl_textdomain = yes; then - -cat >>confdefs.h <<\_ACEOF -#define WITH_LIBINTL 1 -_ACEOF - - LIBS="-lintl $LIBS" -fi - - -# checks for system dependent C++ extensions support -case "$ac_sys_system" in - AIX*) { echo "$as_me:$LINENO: checking for genuine AIX C++ extensions support" >&5 -echo $ECHO_N "checking for genuine AIX C++ extensions support... $ECHO_C" >&6; } - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -#include "/usr/lpp/xlC/include/load.h" -int -main () -{ -loadAndInit("", 0, "") - ; - return 0; -} -_ACEOF -rm -f conftest.$ac_objext conftest$ac_exeext -if { (ac_try="$ac_link" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_link") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest$ac_exeext && - $as_test_x conftest$ac_exeext; then - -cat >>confdefs.h <<\_ACEOF -#define AIX_GENUINE_CPLUSPLUS 1 -_ACEOF - - { echo "$as_me:$LINENO: result: yes" >&5 -echo "${ECHO_T}yes" >&6; } -else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - { echo "$as_me:$LINENO: result: no" >&5 -echo "${ECHO_T}no" >&6; } -fi - -rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \ - conftest$ac_exeext conftest.$ac_ext;; - *) ;; -esac - -# Most SVR4 platforms (e.g. Solaris) need -lsocket and -lnsl. -{ echo "$as_me:$LINENO: checking for t_open in -lnsl" >&5 -echo $ECHO_N "checking for t_open in -lnsl... $ECHO_C" >&6; } -if test "${ac_cv_lib_nsl_t_open+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 -else - ac_check_lib_save_LIBS=$LIBS -LIBS="-lnsl $LIBS" -cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ - -/* Override any GCC internal prototype to avoid an error. - Use char because int might match the return type of a GCC - builtin and then its argument prototype would still apply. */ -#ifdef __cplusplus -extern "C" -#endif -char t_open (); -int -main () -{ -return t_open (); - ; - return 0; -} -_ACEOF -rm -f conftest.$ac_objext conftest$ac_exeext -if { (ac_try="$ac_link" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_link") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest$ac_exeext && - $as_test_x conftest$ac_exeext; then - ac_cv_lib_nsl_t_open=yes -else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - ac_cv_lib_nsl_t_open=no -fi - -rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \ - conftest$ac_exeext conftest.$ac_ext -LIBS=$ac_check_lib_save_LIBS -fi -{ echo "$as_me:$LINENO: result: $ac_cv_lib_nsl_t_open" >&5 -echo "${ECHO_T}$ac_cv_lib_nsl_t_open" >&6; } -if test $ac_cv_lib_nsl_t_open = yes; then - LIBS="-lnsl $LIBS" -fi - # SVR4 -{ echo "$as_me:$LINENO: checking for socket in -lsocket" >&5 -echo $ECHO_N "checking for socket in -lsocket... $ECHO_C" >&6; } -if test "${ac_cv_lib_socket_socket+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 -else - ac_check_lib_save_LIBS=$LIBS -LIBS="-lsocket $LIBS $LIBS" -cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ - -/* Override any GCC internal prototype to avoid an error. - Use char because int might match the return type of a GCC - builtin and then its argument prototype would still apply. */ -#ifdef __cplusplus -extern "C" -#endif -char socket (); -int -main () -{ -return socket (); - ; - return 0; -} -_ACEOF -rm -f conftest.$ac_objext conftest$ac_exeext -if { (ac_try="$ac_link" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_link") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest$ac_exeext && - $as_test_x conftest$ac_exeext; then - ac_cv_lib_socket_socket=yes -else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - ac_cv_lib_socket_socket=no -fi - -rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \ - conftest$ac_exeext conftest.$ac_ext -LIBS=$ac_check_lib_save_LIBS -fi -{ echo "$as_me:$LINENO: result: $ac_cv_lib_socket_socket" >&5 -echo "${ECHO_T}$ac_cv_lib_socket_socket" >&6; } -if test $ac_cv_lib_socket_socket = yes; then - LIBS="-lsocket $LIBS" -fi - # SVR4 sockets - -{ echo "$as_me:$LINENO: checking for --with-libs" >&5 -echo $ECHO_N "checking for --with-libs... $ECHO_C" >&6; } - -# Check whether --with-libs was given. -if test "${with_libs+set}" = set; then - withval=$with_libs; -{ echo "$as_me:$LINENO: result: $withval" >&5 -echo "${ECHO_T}$withval" >&6; } -LIBS="$withval $LIBS" - -else - { echo "$as_me:$LINENO: result: no" >&5 -echo "${ECHO_T}no" >&6; } -fi - - -if test -n "$ac_tool_prefix"; then - # Extract the first word of "${ac_tool_prefix}pkg-config", so it can be a program name with args. -set dummy ${ac_tool_prefix}pkg-config; ac_word=$2 -{ echo "$as_me:$LINENO: checking for $ac_word" >&5 -echo $ECHO_N "checking for $ac_word... $ECHO_C" >&6; } -if test "${ac_cv_path_PKG_CONFIG+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 -else - case $PKG_CONFIG in - [\\/]* | ?:[\\/]*) - ac_cv_path_PKG_CONFIG="$PKG_CONFIG" # Let the user override the test with a path. - ;; - *) - as_save_IFS=$IFS; IFS=$PATH_SEPARATOR -for as_dir in $PATH -do - IFS=$as_save_IFS - test -z "$as_dir" && as_dir=. - for ac_exec_ext in '' $ac_executable_extensions; do - if { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_test_x "$as_dir/$ac_word$ac_exec_ext"; }; then - ac_cv_path_PKG_CONFIG="$as_dir/$ac_word$ac_exec_ext" - echo "$as_me:$LINENO: found $as_dir/$ac_word$ac_exec_ext" >&5 - break 2 - fi -done -done -IFS=$as_save_IFS - - ;; -esac -fi -PKG_CONFIG=$ac_cv_path_PKG_CONFIG -if test -n "$PKG_CONFIG"; then - { echo "$as_me:$LINENO: result: $PKG_CONFIG" >&5 -echo "${ECHO_T}$PKG_CONFIG" >&6; } -else - { echo "$as_me:$LINENO: result: no" >&5 -echo "${ECHO_T}no" >&6; } -fi - - -fi -if test -z "$ac_cv_path_PKG_CONFIG"; then - ac_pt_PKG_CONFIG=$PKG_CONFIG - # Extract the first word of "pkg-config", so it can be a program name with args. -set dummy pkg-config; ac_word=$2 -{ echo "$as_me:$LINENO: checking for $ac_word" >&5 -echo $ECHO_N "checking for $ac_word... $ECHO_C" >&6; } -if test "${ac_cv_path_ac_pt_PKG_CONFIG+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 -else - case $ac_pt_PKG_CONFIG in - [\\/]* | ?:[\\/]*) - ac_cv_path_ac_pt_PKG_CONFIG="$ac_pt_PKG_CONFIG" # Let the user override the test with a path. - ;; - *) - as_save_IFS=$IFS; IFS=$PATH_SEPARATOR -for as_dir in $PATH -do - IFS=$as_save_IFS - test -z "$as_dir" && as_dir=. - for ac_exec_ext in '' $ac_executable_extensions; do - if { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_test_x "$as_dir/$ac_word$ac_exec_ext"; }; then - ac_cv_path_ac_pt_PKG_CONFIG="$as_dir/$ac_word$ac_exec_ext" - echo "$as_me:$LINENO: found $as_dir/$ac_word$ac_exec_ext" >&5 - break 2 - fi -done -done -IFS=$as_save_IFS - - ;; -esac -fi -ac_pt_PKG_CONFIG=$ac_cv_path_ac_pt_PKG_CONFIG -if test -n "$ac_pt_PKG_CONFIG"; then - { echo "$as_me:$LINENO: result: $ac_pt_PKG_CONFIG" >&5 -echo "${ECHO_T}$ac_pt_PKG_CONFIG" >&6; } -else - { echo "$as_me:$LINENO: result: no" >&5 -echo "${ECHO_T}no" >&6; } -fi - - if test "x$ac_pt_PKG_CONFIG" = x; then - PKG_CONFIG="" - else - case $cross_compiling:$ac_tool_warned in -yes:) -{ echo "$as_me:$LINENO: WARNING: In the future, Autoconf will not detect cross-tools -whose name does not start with the host triplet. If you think this -configuration is useful to you, please write to autoconf at gnu.org." >&5 -echo "$as_me: WARNING: In the future, Autoconf will not detect cross-tools -whose name does not start with the host triplet. If you think this -configuration is useful to you, please write to autoconf at gnu.org." >&2;} -ac_tool_warned=yes ;; -esac - PKG_CONFIG=$ac_pt_PKG_CONFIG - fi -else - PKG_CONFIG="$ac_cv_path_PKG_CONFIG" -fi - - -# Check for use of the system expat library -{ echo "$as_me:$LINENO: checking for --with-system-expat" >&5 -echo $ECHO_N "checking for --with-system-expat... $ECHO_C" >&6; } - -# Check whether --with-system_expat was given. -if test "${with_system_expat+set}" = set; then - withval=$with_system_expat; -fi - - -{ echo "$as_me:$LINENO: result: $with_system_expat" >&5 -echo "${ECHO_T}$with_system_expat" >&6; } - -# Check for use of the system libffi library -{ echo "$as_me:$LINENO: checking for --with-system-ffi" >&5 -echo $ECHO_N "checking for --with-system-ffi... $ECHO_C" >&6; } - -# Check whether --with-system_ffi was given. -if test "${with_system_ffi+set}" = set; then - withval=$with_system_ffi; -fi - - -if test "$with_system_ffi" = "yes" && test -n "$PKG_CONFIG"; then - LIBFFI_INCLUDEDIR="`"$PKG_CONFIG" libffi --cflags-only-I 2>/dev/null | sed -e 's/^-I//;s/ *$//'`" -else - LIBFFI_INCLUDEDIR="" -fi - - -{ echo "$as_me:$LINENO: result: $with_system_ffi" >&5 -echo "${ECHO_T}$with_system_ffi" >&6; } - -# Check for --with-dbmliborder -{ echo "$as_me:$LINENO: checking for --with-dbmliborder" >&5 -echo $ECHO_N "checking for --with-dbmliborder... $ECHO_C" >&6; } - -# Check whether --with-dbmliborder was given. -if test "${with_dbmliborder+set}" = set; then - withval=$with_dbmliborder; -if test x$with_dbmliborder = xyes -then -{ { echo "$as_me:$LINENO: error: proper usage is --with-dbmliborder=db1:db2:..." >&5 -echo "$as_me: error: proper usage is --with-dbmliborder=db1:db2:..." >&2;} - { (exit 1); exit 1; }; } -else - for db in `echo $with_dbmliborder | sed 's/:/ /g'`; do - if test x$db != xndbm && test x$db != xgdbm && test x$db != xbdb - then - { { echo "$as_me:$LINENO: error: proper usage is --with-dbmliborder=db1:db2:..." >&5 -echo "$as_me: error: proper usage is --with-dbmliborder=db1:db2:..." >&2;} - { (exit 1); exit 1; }; } - fi - done -fi -fi - -{ echo "$as_me:$LINENO: result: $with_dbmliborder" >&5 -echo "${ECHO_T}$with_dbmliborder" >&6; } - -# Determine if signalmodule should be used. - - -{ echo "$as_me:$LINENO: checking for --with-signal-module" >&5 -echo $ECHO_N "checking for --with-signal-module... $ECHO_C" >&6; } - -# Check whether --with-signal-module was given. -if test "${with_signal_module+set}" = set; then - withval=$with_signal_module; -fi - - -if test -z "$with_signal_module" -then with_signal_module="yes" -fi -{ echo "$as_me:$LINENO: result: $with_signal_module" >&5 -echo "${ECHO_T}$with_signal_module" >&6; } - -if test "${with_signal_module}" = "yes"; then - USE_SIGNAL_MODULE="" - SIGNAL_OBJS="" -else - USE_SIGNAL_MODULE="#" - SIGNAL_OBJS="Parser/intrcheck.o Python/sigcheck.o" -fi - -# This is used to generate Setup.config - -USE_THREAD_MODULE="" - -{ echo "$as_me:$LINENO: checking for --with-dec-threads" >&5 -echo $ECHO_N "checking for --with-dec-threads... $ECHO_C" >&6; } - - -# Check whether --with-dec-threads was given. -if test "${with_dec_threads+set}" = set; then - withval=$with_dec_threads; -{ echo "$as_me:$LINENO: result: $withval" >&5 -echo "${ECHO_T}$withval" >&6; } -LDLAST=-threads -if test "${with_thread+set}" != set; then - with_thread="$withval"; -fi -else - { echo "$as_me:$LINENO: result: no" >&5 -echo "${ECHO_T}no" >&6; } -fi - - -# Templates for things AC_DEFINEd more than once. -# For a single AC_DEFINE, no template is needed. - - - - - - - -{ echo "$as_me:$LINENO: checking for --with-threads" >&5 -echo $ECHO_N "checking for --with-threads... $ECHO_C" >&6; } - -# Check whether --with-threads was given. -if test "${with_threads+set}" = set; then - withval=$with_threads; -fi - - -# --with-thread is deprecated, but check for it anyway - -# Check whether --with-thread was given. -if test "${with_thread+set}" = set; then - withval=$with_thread; with_threads=$with_thread -fi - - -if test -z "$with_threads" -then with_threads="yes" -fi -{ echo "$as_me:$LINENO: result: $with_threads" >&5 -echo "${ECHO_T}$with_threads" >&6; } - - -if test "$with_threads" = "no" -then - USE_THREAD_MODULE="#" -elif test "$ac_cv_pthread_is_default" = yes -then - cat >>confdefs.h <<\_ACEOF -#define WITH_THREAD 1 -_ACEOF - - # Defining _REENTRANT on system with POSIX threads should not hurt. - cat >>confdefs.h <<\_ACEOF -#define _REENTRANT 1 -_ACEOF - - posix_threads=yes - THREADOBJ="Python/thread.o" -elif test "$ac_cv_kpthread" = "yes" -then - CC="$CC -Kpthread" - if test "$ac_cv_cxx_thread" = "yes"; then - CXX="$CXX -Kpthread" - fi - cat >>confdefs.h <<\_ACEOF -#define WITH_THREAD 1 -_ACEOF - - posix_threads=yes - THREADOBJ="Python/thread.o" -elif test "$ac_cv_kthread" = "yes" -then - CC="$CC -Kthread" - if test "$ac_cv_cxx_thread" = "yes"; then - CXX="$CXX -Kthread" - fi - cat >>confdefs.h <<\_ACEOF -#define WITH_THREAD 1 -_ACEOF - - posix_threads=yes - THREADOBJ="Python/thread.o" -elif test "$ac_cv_pthread" = "yes" -then - CC="$CC -pthread" - if test "$ac_cv_cxx_thread" = "yes"; then - CXX="$CXX -pthread" - fi - cat >>confdefs.h <<\_ACEOF -#define WITH_THREAD 1 -_ACEOF - - posix_threads=yes - THREADOBJ="Python/thread.o" -else - if test ! -z "$with_threads" -a -d "$with_threads" - then LDFLAGS="$LDFLAGS -L$with_threads" - fi - if test ! -z "$withval" -a -d "$withval" - then LDFLAGS="$LDFLAGS -L$withval" - fi - - # According to the POSIX spec, a pthreads implementation must - # define _POSIX_THREADS in unistd.h. Some apparently don't - # (e.g. gnu pth with pthread emulation) - { echo "$as_me:$LINENO: checking for _POSIX_THREADS in unistd.h" >&5 -echo $ECHO_N "checking for _POSIX_THREADS in unistd.h... $ECHO_C" >&6; } - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ - -#include -#ifdef _POSIX_THREADS -yes -#endif - -_ACEOF -if (eval "$ac_cpp conftest.$ac_ext") 2>&5 | - $EGREP "yes" >/dev/null 2>&1; then - unistd_defines_pthreads=yes -else - unistd_defines_pthreads=no -fi -rm -f -r conftest* - - { echo "$as_me:$LINENO: result: $unistd_defines_pthreads" >&5 -echo "${ECHO_T}$unistd_defines_pthreads" >&6; } - - cat >>confdefs.h <<\_ACEOF -#define _REENTRANT 1 -_ACEOF - - if test "${ac_cv_header_cthreads_h+set}" = set; then - { echo "$as_me:$LINENO: checking for cthreads.h" >&5 -echo $ECHO_N "checking for cthreads.h... $ECHO_C" >&6; } -if test "${ac_cv_header_cthreads_h+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 -fi -{ echo "$as_me:$LINENO: result: $ac_cv_header_cthreads_h" >&5 -echo "${ECHO_T}$ac_cv_header_cthreads_h" >&6; } -else - # Is the header compilable? -{ echo "$as_me:$LINENO: checking cthreads.h usability" >&5 -echo $ECHO_N "checking cthreads.h usability... $ECHO_C" >&6; } -cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -$ac_includes_default -#include -_ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - ac_header_compiler=yes -else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - ac_header_compiler=no -fi - -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext -{ echo "$as_me:$LINENO: result: $ac_header_compiler" >&5 -echo "${ECHO_T}$ac_header_compiler" >&6; } - -# Is the header present? -{ echo "$as_me:$LINENO: checking cthreads.h presence" >&5 -echo $ECHO_N "checking cthreads.h presence... $ECHO_C" >&6; } -cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -#include -_ACEOF -if { (ac_try="$ac_cpp conftest.$ac_ext" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_cpp conftest.$ac_ext") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } >/dev/null && { - test -z "$ac_c_preproc_warn_flag$ac_c_werror_flag" || - test ! -s conftest.err - }; then - ac_header_preproc=yes -else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - ac_header_preproc=no -fi - -rm -f conftest.err conftest.$ac_ext -{ echo "$as_me:$LINENO: result: $ac_header_preproc" >&5 -echo "${ECHO_T}$ac_header_preproc" >&6; } - -# So? What about this header? -case $ac_header_compiler:$ac_header_preproc:$ac_c_preproc_warn_flag in - yes:no: ) - { echo "$as_me:$LINENO: WARNING: cthreads.h: accepted by the compiler, rejected by the preprocessor!" >&5 -echo "$as_me: WARNING: cthreads.h: accepted by the compiler, rejected by the preprocessor!" >&2;} - { echo "$as_me:$LINENO: WARNING: cthreads.h: proceeding with the compiler's result" >&5 -echo "$as_me: WARNING: cthreads.h: proceeding with the compiler's result" >&2;} - ac_header_preproc=yes - ;; - no:yes:* ) - { echo "$as_me:$LINENO: WARNING: cthreads.h: present but cannot be compiled" >&5 -echo "$as_me: WARNING: cthreads.h: present but cannot be compiled" >&2;} - { echo "$as_me:$LINENO: WARNING: cthreads.h: check for missing prerequisite headers?" >&5 -echo "$as_me: WARNING: cthreads.h: check for missing prerequisite headers?" >&2;} - { echo "$as_me:$LINENO: WARNING: cthreads.h: see the Autoconf documentation" >&5 -echo "$as_me: WARNING: cthreads.h: see the Autoconf documentation" >&2;} - { echo "$as_me:$LINENO: WARNING: cthreads.h: section \"Present But Cannot Be Compiled\"" >&5 -echo "$as_me: WARNING: cthreads.h: section \"Present But Cannot Be Compiled\"" >&2;} - { echo "$as_me:$LINENO: WARNING: cthreads.h: proceeding with the preprocessor's result" >&5 -echo "$as_me: WARNING: cthreads.h: proceeding with the preprocessor's result" >&2;} - { echo "$as_me:$LINENO: WARNING: cthreads.h: in the future, the compiler will take precedence" >&5 -echo "$as_me: WARNING: cthreads.h: in the future, the compiler will take precedence" >&2;} - ( cat <<\_ASBOX -## -------------------------------------- ## -## Report this to http://bugs.python.org/ ## -## -------------------------------------- ## -_ASBOX - ) | sed "s/^/$as_me: WARNING: /" >&2 - ;; -esac -{ echo "$as_me:$LINENO: checking for cthreads.h" >&5 -echo $ECHO_N "checking for cthreads.h... $ECHO_C" >&6; } -if test "${ac_cv_header_cthreads_h+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 -else - ac_cv_header_cthreads_h=$ac_header_preproc -fi -{ echo "$as_me:$LINENO: result: $ac_cv_header_cthreads_h" >&5 -echo "${ECHO_T}$ac_cv_header_cthreads_h" >&6; } - -fi -if test $ac_cv_header_cthreads_h = yes; then - cat >>confdefs.h <<\_ACEOF -#define WITH_THREAD 1 -_ACEOF - - cat >>confdefs.h <<\_ACEOF -#define C_THREADS 1 -_ACEOF - - -cat >>confdefs.h <<\_ACEOF -#define HURD_C_THREADS 1 -_ACEOF - - LIBS="$LIBS -lthreads" - THREADOBJ="Python/thread.o" -else - - if test "${ac_cv_header_mach_cthreads_h+set}" = set; then - { echo "$as_me:$LINENO: checking for mach/cthreads.h" >&5 -echo $ECHO_N "checking for mach/cthreads.h... $ECHO_C" >&6; } -if test "${ac_cv_header_mach_cthreads_h+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 -fi -{ echo "$as_me:$LINENO: result: $ac_cv_header_mach_cthreads_h" >&5 -echo "${ECHO_T}$ac_cv_header_mach_cthreads_h" >&6; } -else - # Is the header compilable? -{ echo "$as_me:$LINENO: checking mach/cthreads.h usability" >&5 -echo $ECHO_N "checking mach/cthreads.h usability... $ECHO_C" >&6; } -cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -$ac_includes_default -#include -_ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - ac_header_compiler=yes -else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - ac_header_compiler=no -fi - -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext -{ echo "$as_me:$LINENO: result: $ac_header_compiler" >&5 -echo "${ECHO_T}$ac_header_compiler" >&6; } - -# Is the header present? -{ echo "$as_me:$LINENO: checking mach/cthreads.h presence" >&5 -echo $ECHO_N "checking mach/cthreads.h presence... $ECHO_C" >&6; } -cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -#include -_ACEOF -if { (ac_try="$ac_cpp conftest.$ac_ext" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_cpp conftest.$ac_ext") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } >/dev/null && { - test -z "$ac_c_preproc_warn_flag$ac_c_werror_flag" || - test ! -s conftest.err - }; then - ac_header_preproc=yes -else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - ac_header_preproc=no -fi - -rm -f conftest.err conftest.$ac_ext -{ echo "$as_me:$LINENO: result: $ac_header_preproc" >&5 -echo "${ECHO_T}$ac_header_preproc" >&6; } - -# So? What about this header? -case $ac_header_compiler:$ac_header_preproc:$ac_c_preproc_warn_flag in - yes:no: ) - { echo "$as_me:$LINENO: WARNING: mach/cthreads.h: accepted by the compiler, rejected by the preprocessor!" >&5 -echo "$as_me: WARNING: mach/cthreads.h: accepted by the compiler, rejected by the preprocessor!" >&2;} - { echo "$as_me:$LINENO: WARNING: mach/cthreads.h: proceeding with the compiler's result" >&5 -echo "$as_me: WARNING: mach/cthreads.h: proceeding with the compiler's result" >&2;} - ac_header_preproc=yes - ;; - no:yes:* ) - { echo "$as_me:$LINENO: WARNING: mach/cthreads.h: present but cannot be compiled" >&5 -echo "$as_me: WARNING: mach/cthreads.h: present but cannot be compiled" >&2;} - { echo "$as_me:$LINENO: WARNING: mach/cthreads.h: check for missing prerequisite headers?" >&5 -echo "$as_me: WARNING: mach/cthreads.h: check for missing prerequisite headers?" >&2;} - { echo "$as_me:$LINENO: WARNING: mach/cthreads.h: see the Autoconf documentation" >&5 -echo "$as_me: WARNING: mach/cthreads.h: see the Autoconf documentation" >&2;} - { echo "$as_me:$LINENO: WARNING: mach/cthreads.h: section \"Present But Cannot Be Compiled\"" >&5 -echo "$as_me: WARNING: mach/cthreads.h: section \"Present But Cannot Be Compiled\"" >&2;} - { echo "$as_me:$LINENO: WARNING: mach/cthreads.h: proceeding with the preprocessor's result" >&5 -echo "$as_me: WARNING: mach/cthreads.h: proceeding with the preprocessor's result" >&2;} - { echo "$as_me:$LINENO: WARNING: mach/cthreads.h: in the future, the compiler will take precedence" >&5 -echo "$as_me: WARNING: mach/cthreads.h: in the future, the compiler will take precedence" >&2;} - ( cat <<\_ASBOX -## -------------------------------------- ## -## Report this to http://bugs.python.org/ ## -## -------------------------------------- ## -_ASBOX - ) | sed "s/^/$as_me: WARNING: /" >&2 - ;; -esac -{ echo "$as_me:$LINENO: checking for mach/cthreads.h" >&5 -echo $ECHO_N "checking for mach/cthreads.h... $ECHO_C" >&6; } -if test "${ac_cv_header_mach_cthreads_h+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 -else - ac_cv_header_mach_cthreads_h=$ac_header_preproc -fi -{ echo "$as_me:$LINENO: result: $ac_cv_header_mach_cthreads_h" >&5 -echo "${ECHO_T}$ac_cv_header_mach_cthreads_h" >&6; } - -fi -if test $ac_cv_header_mach_cthreads_h = yes; then - cat >>confdefs.h <<\_ACEOF -#define WITH_THREAD 1 -_ACEOF - - cat >>confdefs.h <<\_ACEOF -#define C_THREADS 1 -_ACEOF - - -cat >>confdefs.h <<\_ACEOF -#define MACH_C_THREADS 1 -_ACEOF - - THREADOBJ="Python/thread.o" -else - - # Just looking for pthread_create in libpthread is not enough: - # on HP/UX, pthread.h renames pthread_create to a different symbol name. - # So we really have to include pthread.h, and then link. - _libs=$LIBS - LIBS="$LIBS -lpthread" - { echo "$as_me:$LINENO: checking for pthread_create in -lpthread" >&5 -echo $ECHO_N "checking for pthread_create in -lpthread... $ECHO_C" >&6; } - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -#include - -void * start_routine (void *arg) { exit (0); } -int -main () -{ - -pthread_create (NULL, NULL, start_routine, NULL) - ; - return 0; -} -_ACEOF -rm -f conftest.$ac_objext conftest$ac_exeext -if { (ac_try="$ac_link" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_link") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest$ac_exeext && - $as_test_x conftest$ac_exeext; then - - { echo "$as_me:$LINENO: result: yes" >&5 -echo "${ECHO_T}yes" >&6; } - cat >>confdefs.h <<\_ACEOF -#define WITH_THREAD 1 -_ACEOF - - posix_threads=yes - THREADOBJ="Python/thread.o" -else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - - LIBS=$_libs - { echo "$as_me:$LINENO: checking for pthread_detach" >&5 -echo $ECHO_N "checking for pthread_detach... $ECHO_C" >&6; } -if test "${ac_cv_func_pthread_detach+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 -else - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -/* Define pthread_detach to an innocuous variant, in case declares pthread_detach. - For example, HP-UX 11i declares gettimeofday. */ -#define pthread_detach innocuous_pthread_detach - -/* System header to define __stub macros and hopefully few prototypes, - which can conflict with char pthread_detach (); below. - Prefer to if __STDC__ is defined, since - exists even on freestanding compilers. */ - -#ifdef __STDC__ -# include -#else -# include -#endif - -#undef pthread_detach - -/* Override any GCC internal prototype to avoid an error. - Use char because int might match the return type of a GCC - builtin and then its argument prototype would still apply. */ -#ifdef __cplusplus -extern "C" -#endif -char pthread_detach (); -/* The GNU C library defines this for functions which it implements - to always fail with ENOSYS. Some functions are actually named - something starting with __ and the normal name is an alias. */ -#if defined __stub_pthread_detach || defined __stub___pthread_detach -choke me -#endif - -int -main () -{ -return pthread_detach (); - ; - return 0; -} -_ACEOF -rm -f conftest.$ac_objext conftest$ac_exeext -if { (ac_try="$ac_link" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_link") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest$ac_exeext && - $as_test_x conftest$ac_exeext; then - ac_cv_func_pthread_detach=yes -else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - ac_cv_func_pthread_detach=no -fi - -rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \ - conftest$ac_exeext conftest.$ac_ext -fi -{ echo "$as_me:$LINENO: result: $ac_cv_func_pthread_detach" >&5 -echo "${ECHO_T}$ac_cv_func_pthread_detach" >&6; } -if test $ac_cv_func_pthread_detach = yes; then - cat >>confdefs.h <<\_ACEOF -#define WITH_THREAD 1 -_ACEOF - - posix_threads=yes - THREADOBJ="Python/thread.o" -else - - { echo "$as_me:$LINENO: checking for pthread_create in -lpthreads" >&5 -echo $ECHO_N "checking for pthread_create in -lpthreads... $ECHO_C" >&6; } -if test "${ac_cv_lib_pthreads_pthread_create+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 -else - ac_check_lib_save_LIBS=$LIBS -LIBS="-lpthreads $LIBS" -cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ - -/* Override any GCC internal prototype to avoid an error. - Use char because int might match the return type of a GCC - builtin and then its argument prototype would still apply. */ -#ifdef __cplusplus -extern "C" -#endif -char pthread_create (); -int -main () -{ -return pthread_create (); - ; - return 0; -} -_ACEOF -rm -f conftest.$ac_objext conftest$ac_exeext -if { (ac_try="$ac_link" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_link") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest$ac_exeext && - $as_test_x conftest$ac_exeext; then - ac_cv_lib_pthreads_pthread_create=yes -else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - ac_cv_lib_pthreads_pthread_create=no -fi - -rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \ - conftest$ac_exeext conftest.$ac_ext -LIBS=$ac_check_lib_save_LIBS -fi -{ echo "$as_me:$LINENO: result: $ac_cv_lib_pthreads_pthread_create" >&5 -echo "${ECHO_T}$ac_cv_lib_pthreads_pthread_create" >&6; } -if test $ac_cv_lib_pthreads_pthread_create = yes; then - cat >>confdefs.h <<\_ACEOF -#define WITH_THREAD 1 -_ACEOF - - posix_threads=yes - LIBS="$LIBS -lpthreads" - THREADOBJ="Python/thread.o" -else - - { echo "$as_me:$LINENO: checking for pthread_create in -lc_r" >&5 -echo $ECHO_N "checking for pthread_create in -lc_r... $ECHO_C" >&6; } -if test "${ac_cv_lib_c_r_pthread_create+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 -else - ac_check_lib_save_LIBS=$LIBS -LIBS="-lc_r $LIBS" -cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ - -/* Override any GCC internal prototype to avoid an error. - Use char because int might match the return type of a GCC - builtin and then its argument prototype would still apply. */ -#ifdef __cplusplus -extern "C" -#endif -char pthread_create (); -int -main () -{ -return pthread_create (); - ; - return 0; -} -_ACEOF -rm -f conftest.$ac_objext conftest$ac_exeext -if { (ac_try="$ac_link" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_link") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest$ac_exeext && - $as_test_x conftest$ac_exeext; then - ac_cv_lib_c_r_pthread_create=yes -else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - ac_cv_lib_c_r_pthread_create=no -fi - -rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \ - conftest$ac_exeext conftest.$ac_ext -LIBS=$ac_check_lib_save_LIBS -fi -{ echo "$as_me:$LINENO: result: $ac_cv_lib_c_r_pthread_create" >&5 -echo "${ECHO_T}$ac_cv_lib_c_r_pthread_create" >&6; } -if test $ac_cv_lib_c_r_pthread_create = yes; then - cat >>confdefs.h <<\_ACEOF -#define WITH_THREAD 1 -_ACEOF - - posix_threads=yes - LIBS="$LIBS -lc_r" - THREADOBJ="Python/thread.o" -else - - { echo "$as_me:$LINENO: checking for __pthread_create_system in -lpthread" >&5 -echo $ECHO_N "checking for __pthread_create_system in -lpthread... $ECHO_C" >&6; } -if test "${ac_cv_lib_pthread___pthread_create_system+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 -else - ac_check_lib_save_LIBS=$LIBS -LIBS="-lpthread $LIBS" -cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ - -/* Override any GCC internal prototype to avoid an error. - Use char because int might match the return type of a GCC - builtin and then its argument prototype would still apply. */ -#ifdef __cplusplus -extern "C" -#endif -char __pthread_create_system (); -int -main () -{ -return __pthread_create_system (); - ; - return 0; -} -_ACEOF -rm -f conftest.$ac_objext conftest$ac_exeext -if { (ac_try="$ac_link" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_link") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest$ac_exeext && - $as_test_x conftest$ac_exeext; then - ac_cv_lib_pthread___pthread_create_system=yes -else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - ac_cv_lib_pthread___pthread_create_system=no -fi - -rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \ - conftest$ac_exeext conftest.$ac_ext -LIBS=$ac_check_lib_save_LIBS -fi -{ echo "$as_me:$LINENO: result: $ac_cv_lib_pthread___pthread_create_system" >&5 -echo "${ECHO_T}$ac_cv_lib_pthread___pthread_create_system" >&6; } -if test $ac_cv_lib_pthread___pthread_create_system = yes; then - cat >>confdefs.h <<\_ACEOF -#define WITH_THREAD 1 -_ACEOF - - posix_threads=yes - LIBS="$LIBS -lpthread" - THREADOBJ="Python/thread.o" -else - - { echo "$as_me:$LINENO: checking for pthread_create in -lcma" >&5 -echo $ECHO_N "checking for pthread_create in -lcma... $ECHO_C" >&6; } -if test "${ac_cv_lib_cma_pthread_create+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 -else - ac_check_lib_save_LIBS=$LIBS -LIBS="-lcma $LIBS" -cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ - -/* Override any GCC internal prototype to avoid an error. - Use char because int might match the return type of a GCC - builtin and then its argument prototype would still apply. */ -#ifdef __cplusplus -extern "C" -#endif -char pthread_create (); -int -main () -{ -return pthread_create (); - ; - return 0; -} -_ACEOF -rm -f conftest.$ac_objext conftest$ac_exeext -if { (ac_try="$ac_link" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_link") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest$ac_exeext && - $as_test_x conftest$ac_exeext; then - ac_cv_lib_cma_pthread_create=yes -else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - ac_cv_lib_cma_pthread_create=no -fi - -rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \ - conftest$ac_exeext conftest.$ac_ext -LIBS=$ac_check_lib_save_LIBS -fi -{ echo "$as_me:$LINENO: result: $ac_cv_lib_cma_pthread_create" >&5 -echo "${ECHO_T}$ac_cv_lib_cma_pthread_create" >&6; } -if test $ac_cv_lib_cma_pthread_create = yes; then - cat >>confdefs.h <<\_ACEOF -#define WITH_THREAD 1 -_ACEOF - - posix_threads=yes - LIBS="$LIBS -lcma" - THREADOBJ="Python/thread.o" -else - - USE_THREAD_MODULE="#" -fi - - -fi - -fi - -fi - -fi - -fi - -rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \ - conftest$ac_exeext conftest.$ac_ext -fi - - -fi - - - - { echo "$as_me:$LINENO: checking for usconfig in -lmpc" >&5 -echo $ECHO_N "checking for usconfig in -lmpc... $ECHO_C" >&6; } -if test "${ac_cv_lib_mpc_usconfig+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 -else - ac_check_lib_save_LIBS=$LIBS -LIBS="-lmpc $LIBS" -cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ - -/* Override any GCC internal prototype to avoid an error. - Use char because int might match the return type of a GCC - builtin and then its argument prototype would still apply. */ -#ifdef __cplusplus -extern "C" -#endif -char usconfig (); -int -main () -{ -return usconfig (); - ; - return 0; -} -_ACEOF -rm -f conftest.$ac_objext conftest$ac_exeext -if { (ac_try="$ac_link" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_link") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest$ac_exeext && - $as_test_x conftest$ac_exeext; then - ac_cv_lib_mpc_usconfig=yes -else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - ac_cv_lib_mpc_usconfig=no -fi - -rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \ - conftest$ac_exeext conftest.$ac_ext -LIBS=$ac_check_lib_save_LIBS -fi -{ echo "$as_me:$LINENO: result: $ac_cv_lib_mpc_usconfig" >&5 -echo "${ECHO_T}$ac_cv_lib_mpc_usconfig" >&6; } -if test $ac_cv_lib_mpc_usconfig = yes; then - cat >>confdefs.h <<\_ACEOF -#define WITH_THREAD 1 -_ACEOF - - LIBS="$LIBS -lmpc" - THREADOBJ="Python/thread.o" - USE_THREAD_MODULE="" -fi - - - if test "$posix_threads" != "yes"; then - { echo "$as_me:$LINENO: checking for thr_create in -lthread" >&5 -echo $ECHO_N "checking for thr_create in -lthread... $ECHO_C" >&6; } -if test "${ac_cv_lib_thread_thr_create+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 -else - ac_check_lib_save_LIBS=$LIBS -LIBS="-lthread $LIBS" -cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ - -/* Override any GCC internal prototype to avoid an error. - Use char because int might match the return type of a GCC - builtin and then its argument prototype would still apply. */ -#ifdef __cplusplus -extern "C" -#endif -char thr_create (); -int -main () -{ -return thr_create (); - ; - return 0; -} -_ACEOF -rm -f conftest.$ac_objext conftest$ac_exeext -if { (ac_try="$ac_link" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_link") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest$ac_exeext && - $as_test_x conftest$ac_exeext; then - ac_cv_lib_thread_thr_create=yes -else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - ac_cv_lib_thread_thr_create=no -fi - -rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \ - conftest$ac_exeext conftest.$ac_ext -LIBS=$ac_check_lib_save_LIBS -fi -{ echo "$as_me:$LINENO: result: $ac_cv_lib_thread_thr_create" >&5 -echo "${ECHO_T}$ac_cv_lib_thread_thr_create" >&6; } -if test $ac_cv_lib_thread_thr_create = yes; then - cat >>confdefs.h <<\_ACEOF -#define WITH_THREAD 1 -_ACEOF - - LIBS="$LIBS -lthread" - THREADOBJ="Python/thread.o" - USE_THREAD_MODULE="" -fi - - fi - - if test "$USE_THREAD_MODULE" != "#" - then - # If the above checks didn't disable threads, (at least) OSF1 - # needs this '-threads' argument during linking. - case $ac_sys_system in - OSF1) LDLAST=-threads;; - esac - fi -fi - -if test "$posix_threads" = "yes"; then - if test "$unistd_defines_pthreads" = "no"; then - -cat >>confdefs.h <<\_ACEOF -#define _POSIX_THREADS 1 -_ACEOF - - fi - - # Bug 662787: Using semaphores causes unexplicable hangs on Solaris 8. - case $ac_sys_system/$ac_sys_release in - SunOS/5.6) -cat >>confdefs.h <<\_ACEOF -#define HAVE_PTHREAD_DESTRUCTOR 1 -_ACEOF - - ;; - SunOS/5.8) -cat >>confdefs.h <<\_ACEOF -#define HAVE_BROKEN_POSIX_SEMAPHORES 1 -_ACEOF - - ;; - AIX/5) -cat >>confdefs.h <<\_ACEOF -#define HAVE_BROKEN_POSIX_SEMAPHORES 1 -_ACEOF - - ;; - esac - - { echo "$as_me:$LINENO: checking if PTHREAD_SCOPE_SYSTEM is supported" >&5 -echo $ECHO_N "checking if PTHREAD_SCOPE_SYSTEM is supported... $ECHO_C" >&6; } - if test "${ac_cv_pthread_system_supported+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 -else - if test "$cross_compiling" = yes; then - ac_cv_pthread_system_supported=no -else - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -#include - void *foo(void *parm) { - return NULL; - } - main() { - pthread_attr_t attr; - pthread_t id; - if (pthread_attr_init(&attr)) exit(-1); - if (pthread_attr_setscope(&attr, PTHREAD_SCOPE_SYSTEM)) exit(-1); - if (pthread_create(&id, &attr, foo, NULL)) exit(-1); - exit(0); - } -_ACEOF -rm -f conftest$ac_exeext -if { (ac_try="$ac_link" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_link") 2>&5 - ac_status=$? - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { ac_try='./conftest$ac_exeext' - { (case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_try") 2>&5 - ac_status=$? - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); }; }; then - ac_cv_pthread_system_supported=yes -else - echo "$as_me: program exited with status $ac_status" >&5 -echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - -( exit $ac_status ) -ac_cv_pthread_system_supported=no -fi -rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext conftest.$ac_objext conftest.$ac_ext -fi - - - -fi - - { echo "$as_me:$LINENO: result: $ac_cv_pthread_system_supported" >&5 -echo "${ECHO_T}$ac_cv_pthread_system_supported" >&6; } - if test "$ac_cv_pthread_system_supported" = "yes"; then - -cat >>confdefs.h <<\_ACEOF -#define PTHREAD_SYSTEM_SCHED_SUPPORTED 1 -_ACEOF - - fi - -for ac_func in pthread_sigmask -do -as_ac_var=`echo "ac_cv_func_$ac_func" | $as_tr_sh` -{ echo "$as_me:$LINENO: checking for $ac_func" >&5 -echo $ECHO_N "checking for $ac_func... $ECHO_C" >&6; } -if { as_var=$as_ac_var; eval "test \"\${$as_var+set}\" = set"; }; then - echo $ECHO_N "(cached) $ECHO_C" >&6 -else - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -/* Define $ac_func to an innocuous variant, in case declares $ac_func. - For example, HP-UX 11i declares gettimeofday. */ -#define $ac_func innocuous_$ac_func - -/* System header to define __stub macros and hopefully few prototypes, - which can conflict with char $ac_func (); below. - Prefer to if __STDC__ is defined, since - exists even on freestanding compilers. */ - -#ifdef __STDC__ -# include -#else -# include -#endif - -#undef $ac_func - -/* Override any GCC internal prototype to avoid an error. - Use char because int might match the return type of a GCC - builtin and then its argument prototype would still apply. */ -#ifdef __cplusplus -extern "C" -#endif -char $ac_func (); -/* The GNU C library defines this for functions which it implements - to always fail with ENOSYS. Some functions are actually named - something starting with __ and the normal name is an alias. */ -#if defined __stub_$ac_func || defined __stub___$ac_func -choke me -#endif - -int -main () -{ -return $ac_func (); - ; - return 0; -} -_ACEOF -rm -f conftest.$ac_objext conftest$ac_exeext -if { (ac_try="$ac_link" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_link") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest$ac_exeext && - $as_test_x conftest$ac_exeext; then - eval "$as_ac_var=yes" -else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - eval "$as_ac_var=no" -fi - -rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \ - conftest$ac_exeext conftest.$ac_ext -fi -ac_res=`eval echo '${'$as_ac_var'}'` - { echo "$as_me:$LINENO: result: $ac_res" >&5 -echo "${ECHO_T}$ac_res" >&6; } -if test `eval echo '${'$as_ac_var'}'` = yes; then - cat >>confdefs.h <<_ACEOF -#define `echo "HAVE_$ac_func" | $as_tr_cpp` 1 -_ACEOF - case $ac_sys_system in - CYGWIN*) - -cat >>confdefs.h <<\_ACEOF -#define HAVE_BROKEN_PTHREAD_SIGMASK 1 -_ACEOF - - ;; - esac -fi -done - -fi - - -# Check for enable-ipv6 - - -{ echo "$as_me:$LINENO: checking if --enable-ipv6 is specified" >&5 -echo $ECHO_N "checking if --enable-ipv6 is specified... $ECHO_C" >&6; } -# Check whether --enable-ipv6 was given. -if test "${enable_ipv6+set}" = set; then - enableval=$enable_ipv6; case "$enableval" in - no) - { echo "$as_me:$LINENO: result: no" >&5 -echo "${ECHO_T}no" >&6; } - ipv6=no - ;; - *) { echo "$as_me:$LINENO: result: yes" >&5 -echo "${ECHO_T}yes" >&6; } - cat >>confdefs.h <<\_ACEOF -#define ENABLE_IPV6 1 -_ACEOF - - ipv6=yes - ;; - esac -else - - if test "$cross_compiling" = yes; then - { echo "$as_me:$LINENO: result: no" >&5 -echo "${ECHO_T}no" >&6; } - ipv6=no - -else - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ - /* AF_INET6 available check */ -#include -#include -main() -{ - if (socket(AF_INET6, SOCK_STREAM, 0) < 0) - exit(1); - else - exit(0); -} - -_ACEOF -rm -f conftest$ac_exeext -if { (ac_try="$ac_link" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_link") 2>&5 - ac_status=$? - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { ac_try='./conftest$ac_exeext' - { (case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_try") 2>&5 - ac_status=$? - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); }; }; then - { echo "$as_me:$LINENO: result: yes" >&5 -echo "${ECHO_T}yes" >&6; } - ipv6=yes -else - echo "$as_me: program exited with status $ac_status" >&5 -echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - -( exit $ac_status ) -{ echo "$as_me:$LINENO: result: no" >&5 -echo "${ECHO_T}no" >&6; } - ipv6=no -fi -rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext conftest.$ac_objext conftest.$ac_ext -fi - - - -if test "$ipv6" = "yes"; then - { echo "$as_me:$LINENO: checking if RFC2553 API is available" >&5 -echo $ECHO_N "checking if RFC2553 API is available... $ECHO_C" >&6; } - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -#include -#include -int -main () -{ -struct sockaddr_in6 x; -x.sin6_scope_id; - ; - return 0; -} -_ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - { echo "$as_me:$LINENO: result: yes" >&5 -echo "${ECHO_T}yes" >&6; } - ipv6=yes -else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - { echo "$as_me:$LINENO: result: no" >&5 -echo "${ECHO_T}no" >&6; } - ipv6=no -fi - -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext -fi - -if test "$ipv6" = "yes"; then - cat >>confdefs.h <<\_ACEOF -#define ENABLE_IPV6 1 -_ACEOF - -fi - -fi - - -ipv6type=unknown -ipv6lib=none -ipv6trylibc=no - -if test "$ipv6" = "yes"; then - { echo "$as_me:$LINENO: checking ipv6 stack type" >&5 -echo $ECHO_N "checking ipv6 stack type... $ECHO_C" >&6; } - for i in inria kame linux-glibc linux-inet6 solaris toshiba v6d zeta; - do - case $i in - inria) - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ - -#include -#ifdef IPV6_INRIA_VERSION -yes -#endif -_ACEOF -if (eval "$ac_cpp conftest.$ac_ext") 2>&5 | - $EGREP "yes" >/dev/null 2>&1; then - ipv6type=$i -fi -rm -f -r conftest* - - ;; - kame) - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ - -#include -#ifdef __KAME__ -yes -#endif -_ACEOF -if (eval "$ac_cpp conftest.$ac_ext") 2>&5 | - $EGREP "yes" >/dev/null 2>&1; then - ipv6type=$i; - ipv6lib=inet6 - ipv6libdir=/usr/local/v6/lib - ipv6trylibc=yes -fi -rm -f -r conftest* - - ;; - linux-glibc) - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ - -#include -#if defined(__GLIBC__) && ((__GLIBC__ == 2 && __GLIBC_MINOR__ >= 1) || (__GLIBC__ > 2)) -yes -#endif -_ACEOF -if (eval "$ac_cpp conftest.$ac_ext") 2>&5 | - $EGREP "yes" >/dev/null 2>&1; then - ipv6type=$i; - ipv6trylibc=yes -fi -rm -f -r conftest* - - ;; - linux-inet6) - if test -d /usr/inet6; then - ipv6type=$i - ipv6lib=inet6 - ipv6libdir=/usr/inet6/lib - BASECFLAGS="-I/usr/inet6/include $BASECFLAGS" - fi - ;; - solaris) - if test -f /etc/netconfig; then - if /usr/xpg4/bin/grep -q tcp6 /etc/netconfig; then - ipv6type=$i - ipv6trylibc=yes - fi - fi - ;; - toshiba) - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ - -#include -#ifdef _TOSHIBA_INET6 -yes -#endif -_ACEOF -if (eval "$ac_cpp conftest.$ac_ext") 2>&5 | - $EGREP "yes" >/dev/null 2>&1; then - ipv6type=$i; - ipv6lib=inet6; - ipv6libdir=/usr/local/v6/lib -fi -rm -f -r conftest* - - ;; - v6d) - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ - -#include -#ifdef __V6D__ -yes -#endif -_ACEOF -if (eval "$ac_cpp conftest.$ac_ext") 2>&5 | - $EGREP "yes" >/dev/null 2>&1; then - ipv6type=$i; - ipv6lib=v6; - ipv6libdir=/usr/local/v6/lib; - BASECFLAGS="-I/usr/local/v6/include $BASECFLAGS" -fi -rm -f -r conftest* - - ;; - zeta) - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ - -#include -#ifdef _ZETA_MINAMI_INET6 -yes -#endif -_ACEOF -if (eval "$ac_cpp conftest.$ac_ext") 2>&5 | - $EGREP "yes" >/dev/null 2>&1; then - ipv6type=$i; - ipv6lib=inet6; - ipv6libdir=/usr/local/v6/lib -fi -rm -f -r conftest* - - ;; - esac - if test "$ipv6type" != "unknown"; then - break - fi - done - { echo "$as_me:$LINENO: result: $ipv6type" >&5 -echo "${ECHO_T}$ipv6type" >&6; } -fi - -if test "$ipv6" = "yes" -a "$ipv6lib" != "none"; then - if test -d $ipv6libdir -a -f $ipv6libdir/lib$ipv6lib.a; then - LIBS="-L$ipv6libdir -l$ipv6lib $LIBS" - echo "using lib$ipv6lib" - else - if test $ipv6trylibc = "yes"; then - echo "using libc" - else - echo 'Fatal: no $ipv6lib library found. cannot continue.' - echo "You need to fetch lib$ipv6lib.a from appropriate" - echo 'ipv6 kit and compile beforehand.' - exit 1 - fi - fi -fi - -{ echo "$as_me:$LINENO: checking for OSX 10.5 SDK or later" >&5 -echo $ECHO_N "checking for OSX 10.5 SDK or later... $ECHO_C" >&6; } -cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -#include -int -main () -{ -FSIORefNum fRef = 0 - ; - return 0; -} -_ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - -cat >>confdefs.h <<\_ACEOF -#define HAVE_OSX105_SDK 1 -_ACEOF - - { echo "$as_me:$LINENO: result: yes" >&5 -echo "${ECHO_T}yes" >&6; } -else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - { echo "$as_me:$LINENO: result: no" >&5 -echo "${ECHO_T}no" >&6; } - -fi - -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext - -# Check for --with-doc-strings -{ echo "$as_me:$LINENO: checking for --with-doc-strings" >&5 -echo $ECHO_N "checking for --with-doc-strings... $ECHO_C" >&6; } - -# Check whether --with-doc-strings was given. -if test "${with_doc_strings+set}" = set; then - withval=$with_doc_strings; -fi - - -if test -z "$with_doc_strings" -then with_doc_strings="yes" -fi -if test "$with_doc_strings" != "no" -then - -cat >>confdefs.h <<\_ACEOF -#define WITH_DOC_STRINGS 1 -_ACEOF - -fi -{ echo "$as_me:$LINENO: result: $with_doc_strings" >&5 -echo "${ECHO_T}$with_doc_strings" >&6; } - -# Check for Python-specific malloc support -{ echo "$as_me:$LINENO: checking for --with-tsc" >&5 -echo $ECHO_N "checking for --with-tsc... $ECHO_C" >&6; } - -# Check whether --with-tsc was given. -if test "${with_tsc+set}" = set; then - withval=$with_tsc; -if test "$withval" != no -then - -cat >>confdefs.h <<\_ACEOF -#define WITH_TSC 1 -_ACEOF - - { echo "$as_me:$LINENO: result: yes" >&5 -echo "${ECHO_T}yes" >&6; } -else { echo "$as_me:$LINENO: result: no" >&5 -echo "${ECHO_T}no" >&6; } -fi -else - { echo "$as_me:$LINENO: result: no" >&5 -echo "${ECHO_T}no" >&6; } -fi - - -# Check for Python-specific malloc support -{ echo "$as_me:$LINENO: checking for --with-pymalloc" >&5 -echo $ECHO_N "checking for --with-pymalloc... $ECHO_C" >&6; } - -# Check whether --with-pymalloc was given. -if test "${with_pymalloc+set}" = set; then - withval=$with_pymalloc; -fi - - -if test -z "$with_pymalloc" -then with_pymalloc="yes" -fi -if test "$with_pymalloc" != "no" -then - -cat >>confdefs.h <<\_ACEOF -#define WITH_PYMALLOC 1 -_ACEOF - -fi -{ echo "$as_me:$LINENO: result: $with_pymalloc" >&5 -echo "${ECHO_T}$with_pymalloc" >&6; } - -# Check for Valgrind support -{ echo "$as_me:$LINENO: checking for --with-valgrind" >&5 -echo $ECHO_N "checking for --with-valgrind... $ECHO_C" >&6; } - -# Check whether --with-valgrind was given. -if test "${with_valgrind+set}" = set; then - withval=$with_valgrind; -else - with_valgrind=no -fi - -{ echo "$as_me:$LINENO: result: $with_valgrind" >&5 -echo "${ECHO_T}$with_valgrind" >&6; } -if test "$with_valgrind" != no; then - if test "${ac_cv_header_valgrind_valgrind_h+set}" = set; then - { echo "$as_me:$LINENO: checking for valgrind/valgrind.h" >&5 -echo $ECHO_N "checking for valgrind/valgrind.h... $ECHO_C" >&6; } -if test "${ac_cv_header_valgrind_valgrind_h+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 -fi -{ echo "$as_me:$LINENO: result: $ac_cv_header_valgrind_valgrind_h" >&5 -echo "${ECHO_T}$ac_cv_header_valgrind_valgrind_h" >&6; } -else - # Is the header compilable? -{ echo "$as_me:$LINENO: checking valgrind/valgrind.h usability" >&5 -echo $ECHO_N "checking valgrind/valgrind.h usability... $ECHO_C" >&6; } -cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -$ac_includes_default -#include -_ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - ac_header_compiler=yes -else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - ac_header_compiler=no -fi - -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext -{ echo "$as_me:$LINENO: result: $ac_header_compiler" >&5 -echo "${ECHO_T}$ac_header_compiler" >&6; } - -# Is the header present? -{ echo "$as_me:$LINENO: checking valgrind/valgrind.h presence" >&5 -echo $ECHO_N "checking valgrind/valgrind.h presence... $ECHO_C" >&6; } -cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -#include -_ACEOF -if { (ac_try="$ac_cpp conftest.$ac_ext" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_cpp conftest.$ac_ext") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } >/dev/null && { - test -z "$ac_c_preproc_warn_flag$ac_c_werror_flag" || - test ! -s conftest.err - }; then - ac_header_preproc=yes -else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - ac_header_preproc=no -fi - -rm -f conftest.err conftest.$ac_ext -{ echo "$as_me:$LINENO: result: $ac_header_preproc" >&5 -echo "${ECHO_T}$ac_header_preproc" >&6; } - -# So? What about this header? -case $ac_header_compiler:$ac_header_preproc:$ac_c_preproc_warn_flag in - yes:no: ) - { echo "$as_me:$LINENO: WARNING: valgrind/valgrind.h: accepted by the compiler, rejected by the preprocessor!" >&5 -echo "$as_me: WARNING: valgrind/valgrind.h: accepted by the compiler, rejected by the preprocessor!" >&2;} - { echo "$as_me:$LINENO: WARNING: valgrind/valgrind.h: proceeding with the compiler's result" >&5 -echo "$as_me: WARNING: valgrind/valgrind.h: proceeding with the compiler's result" >&2;} - ac_header_preproc=yes - ;; - no:yes:* ) - { echo "$as_me:$LINENO: WARNING: valgrind/valgrind.h: present but cannot be compiled" >&5 -echo "$as_me: WARNING: valgrind/valgrind.h: present but cannot be compiled" >&2;} - { echo "$as_me:$LINENO: WARNING: valgrind/valgrind.h: check for missing prerequisite headers?" >&5 -echo "$as_me: WARNING: valgrind/valgrind.h: check for missing prerequisite headers?" >&2;} - { echo "$as_me:$LINENO: WARNING: valgrind/valgrind.h: see the Autoconf documentation" >&5 -echo "$as_me: WARNING: valgrind/valgrind.h: see the Autoconf documentation" >&2;} - { echo "$as_me:$LINENO: WARNING: valgrind/valgrind.h: section \"Present But Cannot Be Compiled\"" >&5 -echo "$as_me: WARNING: valgrind/valgrind.h: section \"Present But Cannot Be Compiled\"" >&2;} - { echo "$as_me:$LINENO: WARNING: valgrind/valgrind.h: proceeding with the preprocessor's result" >&5 -echo "$as_me: WARNING: valgrind/valgrind.h: proceeding with the preprocessor's result" >&2;} - { echo "$as_me:$LINENO: WARNING: valgrind/valgrind.h: in the future, the compiler will take precedence" >&5 -echo "$as_me: WARNING: valgrind/valgrind.h: in the future, the compiler will take precedence" >&2;} - ( cat <<\_ASBOX -## -------------------------------------- ## -## Report this to http://bugs.python.org/ ## -## -------------------------------------- ## -_ASBOX - ) | sed "s/^/$as_me: WARNING: /" >&2 - ;; -esac -{ echo "$as_me:$LINENO: checking for valgrind/valgrind.h" >&5 -echo $ECHO_N "checking for valgrind/valgrind.h... $ECHO_C" >&6; } -if test "${ac_cv_header_valgrind_valgrind_h+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 -else - ac_cv_header_valgrind_valgrind_h=$ac_header_preproc -fi -{ echo "$as_me:$LINENO: result: $ac_cv_header_valgrind_valgrind_h" >&5 -echo "${ECHO_T}$ac_cv_header_valgrind_valgrind_h" >&6; } - -fi -if test $ac_cv_header_valgrind_valgrind_h = yes; then - -cat >>confdefs.h <<\_ACEOF -#define WITH_VALGRIND 1 -_ACEOF - -else - { { echo "$as_me:$LINENO: error: Valgrind support requested but headers not available" >&5 -echo "$as_me: error: Valgrind support requested but headers not available" >&2;} - { (exit 1); exit 1; }; } - -fi - - -fi - -# Check for --with-wctype-functions -{ echo "$as_me:$LINENO: checking for --with-wctype-functions" >&5 -echo $ECHO_N "checking for --with-wctype-functions... $ECHO_C" >&6; } - -# Check whether --with-wctype-functions was given. -if test "${with_wctype_functions+set}" = set; then - withval=$with_wctype_functions; -if test "$withval" != no -then - -cat >>confdefs.h <<\_ACEOF -#define WANT_WCTYPE_FUNCTIONS 1 -_ACEOF - - { echo "$as_me:$LINENO: result: yes" >&5 -echo "${ECHO_T}yes" >&6; } -else { echo "$as_me:$LINENO: result: no" >&5 -echo "${ECHO_T}no" >&6; } -fi -else - { echo "$as_me:$LINENO: result: no" >&5 -echo "${ECHO_T}no" >&6; } -fi - - -# -I${DLINCLDIR} is added to the compile rule for importdl.o - -DLINCLDIR=. - -# the dlopen() function means we might want to use dynload_shlib.o. some -# platforms, such as AIX, have dlopen(), but don't want to use it. - -for ac_func in dlopen -do -as_ac_var=`echo "ac_cv_func_$ac_func" | $as_tr_sh` -{ echo "$as_me:$LINENO: checking for $ac_func" >&5 -echo $ECHO_N "checking for $ac_func... $ECHO_C" >&6; } -if { as_var=$as_ac_var; eval "test \"\${$as_var+set}\" = set"; }; then - echo $ECHO_N "(cached) $ECHO_C" >&6 -else - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -/* Define $ac_func to an innocuous variant, in case declares $ac_func. - For example, HP-UX 11i declares gettimeofday. */ -#define $ac_func innocuous_$ac_func - -/* System header to define __stub macros and hopefully few prototypes, - which can conflict with char $ac_func (); below. - Prefer to if __STDC__ is defined, since - exists even on freestanding compilers. */ - -#ifdef __STDC__ -# include -#else -# include -#endif - -#undef $ac_func - -/* Override any GCC internal prototype to avoid an error. - Use char because int might match the return type of a GCC - builtin and then its argument prototype would still apply. */ -#ifdef __cplusplus -extern "C" -#endif -char $ac_func (); -/* The GNU C library defines this for functions which it implements - to always fail with ENOSYS. Some functions are actually named - something starting with __ and the normal name is an alias. */ -#if defined __stub_$ac_func || defined __stub___$ac_func -choke me -#endif - -int -main () -{ -return $ac_func (); - ; - return 0; -} -_ACEOF -rm -f conftest.$ac_objext conftest$ac_exeext -if { (ac_try="$ac_link" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_link") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest$ac_exeext && - $as_test_x conftest$ac_exeext; then - eval "$as_ac_var=yes" -else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - eval "$as_ac_var=no" -fi - -rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \ - conftest$ac_exeext conftest.$ac_ext -fi -ac_res=`eval echo '${'$as_ac_var'}'` - { echo "$as_me:$LINENO: result: $ac_res" >&5 -echo "${ECHO_T}$ac_res" >&6; } -if test `eval echo '${'$as_ac_var'}'` = yes; then - cat >>confdefs.h <<_ACEOF -#define `echo "HAVE_$ac_func" | $as_tr_cpp` 1 -_ACEOF - -fi -done - - -# DYNLOADFILE specifies which dynload_*.o file we will use for dynamic -# loading of modules. - -{ echo "$as_me:$LINENO: checking DYNLOADFILE" >&5 -echo $ECHO_N "checking DYNLOADFILE... $ECHO_C" >&6; } -if test -z "$DYNLOADFILE" -then - case $ac_sys_system/$ac_sys_release in - AIX*) # Use dynload_shlib.c and dlopen() if we have it; otherwise dynload_aix.c - if test "$ac_cv_func_dlopen" = yes - then DYNLOADFILE="dynload_shlib.o" - else DYNLOADFILE="dynload_aix.o" - fi - ;; - hp*|HP*) DYNLOADFILE="dynload_hpux.o";; - # Use dynload_next.c only on 10.2 and below, which don't have native dlopen() - Darwin/[0156]\..*) DYNLOADFILE="dynload_next.o";; - *) - # use dynload_shlib.c and dlopen() if we have it; otherwise stub - # out any dynamic loading - if test "$ac_cv_func_dlopen" = yes - then DYNLOADFILE="dynload_shlib.o" - else DYNLOADFILE="dynload_stub.o" - fi - ;; - esac -fi -{ echo "$as_me:$LINENO: result: $DYNLOADFILE" >&5 -echo "${ECHO_T}$DYNLOADFILE" >&6; } -if test "$DYNLOADFILE" != "dynload_stub.o" -then - -cat >>confdefs.h <<\_ACEOF -#define HAVE_DYNAMIC_LOADING 1 -_ACEOF - -fi - -# MACHDEP_OBJS can be set to platform-specific object files needed by Python - - -{ echo "$as_me:$LINENO: checking MACHDEP_OBJS" >&5 -echo $ECHO_N "checking MACHDEP_OBJS... $ECHO_C" >&6; } -if test -z "$MACHDEP_OBJS" -then - MACHDEP_OBJS=$extra_machdep_objs -else - MACHDEP_OBJS="$MACHDEP_OBJS $extra_machdep_objs" -fi -{ echo "$as_me:$LINENO: result: MACHDEP_OBJS" >&5 -echo "${ECHO_T}MACHDEP_OBJS" >&6; } - -# checks for library functions - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -for ac_func in alarm setitimer getitimer bind_textdomain_codeset chown \ - clock confstr ctermid execv fchmod fchown fork fpathconf ftime ftruncate \ - gai_strerror getgroups getlogin getloadavg getpeername getpgid getpid \ - getpriority getresuid getresgid getpwent getspnam getspent getsid getwd \ - initgroups kill killpg lchmod lchown lstat mbrtowc mkfifo mknod mktime \ - mremap nice pathconf pause plock poll pthread_init \ - putenv readlink realpath \ - select sem_open sem_timedwait sem_getvalue sem_unlink setegid seteuid \ - setgid \ - setlocale setregid setreuid setresuid setresgid setsid setpgid setpgrp setuid setvbuf \ - sigaction siginterrupt sigrelse snprintf strftime strlcpy \ - sysconf tcgetpgrp tcsetpgrp tempnam timegm times tmpfile tmpnam tmpnam_r \ - truncate uname unsetenv utimes waitpid wait3 wait4 \ - wcscoll wcsftime wcsxfrm _getpty -do -as_ac_var=`echo "ac_cv_func_$ac_func" | $as_tr_sh` -{ echo "$as_me:$LINENO: checking for $ac_func" >&5 -echo $ECHO_N "checking for $ac_func... $ECHO_C" >&6; } -if { as_var=$as_ac_var; eval "test \"\${$as_var+set}\" = set"; }; then - echo $ECHO_N "(cached) $ECHO_C" >&6 -else - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -/* Define $ac_func to an innocuous variant, in case declares $ac_func. - For example, HP-UX 11i declares gettimeofday. */ -#define $ac_func innocuous_$ac_func - -/* System header to define __stub macros and hopefully few prototypes, - which can conflict with char $ac_func (); below. - Prefer to if __STDC__ is defined, since - exists even on freestanding compilers. */ - -#ifdef __STDC__ -# include -#else -# include -#endif - -#undef $ac_func - -/* Override any GCC internal prototype to avoid an error. - Use char because int might match the return type of a GCC - builtin and then its argument prototype would still apply. */ -#ifdef __cplusplus -extern "C" -#endif -char $ac_func (); -/* The GNU C library defines this for functions which it implements - to always fail with ENOSYS. Some functions are actually named - something starting with __ and the normal name is an alias. */ -#if defined __stub_$ac_func || defined __stub___$ac_func -choke me -#endif - -int -main () -{ -return $ac_func (); - ; - return 0; -} -_ACEOF -rm -f conftest.$ac_objext conftest$ac_exeext -if { (ac_try="$ac_link" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_link") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest$ac_exeext && - $as_test_x conftest$ac_exeext; then - eval "$as_ac_var=yes" -else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - eval "$as_ac_var=no" -fi - -rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \ - conftest$ac_exeext conftest.$ac_ext -fi -ac_res=`eval echo '${'$as_ac_var'}'` - { echo "$as_me:$LINENO: result: $ac_res" >&5 -echo "${ECHO_T}$ac_res" >&6; } -if test `eval echo '${'$as_ac_var'}'` = yes; then - cat >>confdefs.h <<_ACEOF -#define `echo "HAVE_$ac_func" | $as_tr_cpp` 1 -_ACEOF - -fi -done - - -# For some functions, having a definition is not sufficient, since -# we want to take their address. -{ echo "$as_me:$LINENO: checking for chroot" >&5 -echo $ECHO_N "checking for chroot... $ECHO_C" >&6; } -cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -#include -int -main () -{ -void *x=chroot - ; - return 0; -} -_ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - -cat >>confdefs.h <<\_ACEOF -#define HAVE_CHROOT 1 -_ACEOF - - { echo "$as_me:$LINENO: result: yes" >&5 -echo "${ECHO_T}yes" >&6; } -else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - { echo "$as_me:$LINENO: result: no" >&5 -echo "${ECHO_T}no" >&6; } - -fi - -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext -{ echo "$as_me:$LINENO: checking for link" >&5 -echo $ECHO_N "checking for link... $ECHO_C" >&6; } -cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -#include -int -main () -{ -void *x=link - ; - return 0; -} -_ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - -cat >>confdefs.h <<\_ACEOF -#define HAVE_LINK 1 -_ACEOF - - { echo "$as_me:$LINENO: result: yes" >&5 -echo "${ECHO_T}yes" >&6; } -else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - { echo "$as_me:$LINENO: result: no" >&5 -echo "${ECHO_T}no" >&6; } - -fi - -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext -{ echo "$as_me:$LINENO: checking for symlink" >&5 -echo $ECHO_N "checking for symlink... $ECHO_C" >&6; } -cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -#include -int -main () -{ -void *x=symlink - ; - return 0; -} -_ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - -cat >>confdefs.h <<\_ACEOF -#define HAVE_SYMLINK 1 -_ACEOF - - { echo "$as_me:$LINENO: result: yes" >&5 -echo "${ECHO_T}yes" >&6; } -else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - { echo "$as_me:$LINENO: result: no" >&5 -echo "${ECHO_T}no" >&6; } - -fi - -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext -{ echo "$as_me:$LINENO: checking for fchdir" >&5 -echo $ECHO_N "checking for fchdir... $ECHO_C" >&6; } -cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -#include -int -main () -{ -void *x=fchdir - ; - return 0; -} -_ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - -cat >>confdefs.h <<\_ACEOF -#define HAVE_FCHDIR 1 -_ACEOF - - { echo "$as_me:$LINENO: result: yes" >&5 -echo "${ECHO_T}yes" >&6; } -else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - { echo "$as_me:$LINENO: result: no" >&5 -echo "${ECHO_T}no" >&6; } - -fi - -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext -{ echo "$as_me:$LINENO: checking for fsync" >&5 -echo $ECHO_N "checking for fsync... $ECHO_C" >&6; } -cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -#include -int -main () -{ -void *x=fsync - ; - return 0; -} -_ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - -cat >>confdefs.h <<\_ACEOF -#define HAVE_FSYNC 1 -_ACEOF - - { echo "$as_me:$LINENO: result: yes" >&5 -echo "${ECHO_T}yes" >&6; } -else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - { echo "$as_me:$LINENO: result: no" >&5 -echo "${ECHO_T}no" >&6; } - -fi - -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext -{ echo "$as_me:$LINENO: checking for fdatasync" >&5 -echo $ECHO_N "checking for fdatasync... $ECHO_C" >&6; } -cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -#include -int -main () -{ -void *x=fdatasync - ; - return 0; -} -_ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - -cat >>confdefs.h <<\_ACEOF -#define HAVE_FDATASYNC 1 -_ACEOF - - { echo "$as_me:$LINENO: result: yes" >&5 -echo "${ECHO_T}yes" >&6; } -else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - { echo "$as_me:$LINENO: result: no" >&5 -echo "${ECHO_T}no" >&6; } - -fi - -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext -{ echo "$as_me:$LINENO: checking for epoll" >&5 -echo $ECHO_N "checking for epoll... $ECHO_C" >&6; } -cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -#include -int -main () -{ -void *x=epoll_create - ; - return 0; -} -_ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - -cat >>confdefs.h <<\_ACEOF -#define HAVE_EPOLL 1 -_ACEOF - - { echo "$as_me:$LINENO: result: yes" >&5 -echo "${ECHO_T}yes" >&6; } -else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - { echo "$as_me:$LINENO: result: no" >&5 -echo "${ECHO_T}no" >&6; } - -fi - -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext -{ echo "$as_me:$LINENO: checking for kqueue" >&5 -echo $ECHO_N "checking for kqueue... $ECHO_C" >&6; } -cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ - -#include -#include - -int -main () -{ -int x=kqueue() - ; - return 0; -} -_ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - -cat >>confdefs.h <<\_ACEOF -#define HAVE_KQUEUE 1 -_ACEOF - - { echo "$as_me:$LINENO: result: yes" >&5 -echo "${ECHO_T}yes" >&6; } -else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - { echo "$as_me:$LINENO: result: no" >&5 -echo "${ECHO_T}no" >&6; } - -fi - -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext -# On some systems (eg. FreeBSD 5), we would find a definition of the -# functions ctermid_r, setgroups in the library, but no prototype -# (e.g. because we use _XOPEN_SOURCE). See whether we can take their -# address to avoid compiler warnings and potential miscompilations -# because of the missing prototypes. - -{ echo "$as_me:$LINENO: checking for ctermid_r" >&5 -echo $ECHO_N "checking for ctermid_r... $ECHO_C" >&6; } -cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ - -#include "confdefs.h" -#include - -int -main () -{ -void* p = ctermid_r - ; - return 0; -} -_ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - -cat >>confdefs.h <<\_ACEOF -#define HAVE_CTERMID_R 1 -_ACEOF - - { echo "$as_me:$LINENO: result: yes" >&5 -echo "${ECHO_T}yes" >&6; } -else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - { echo "$as_me:$LINENO: result: no" >&5 -echo "${ECHO_T}no" >&6; } - -fi - -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext - -{ echo "$as_me:$LINENO: checking for flock" >&5 -echo $ECHO_N "checking for flock... $ECHO_C" >&6; } -cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ - -#include "confdefs.h" -#include - -int -main () -{ -void* p = flock - ; - return 0; -} -_ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - -cat >>confdefs.h <<\_ACEOF -#define HAVE_FLOCK 1 -_ACEOF - - { echo "$as_me:$LINENO: result: yes" >&5 -echo "${ECHO_T}yes" >&6; } -else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - { echo "$as_me:$LINENO: result: no" >&5 -echo "${ECHO_T}no" >&6; } - -fi - -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext - -{ echo "$as_me:$LINENO: checking for getpagesize" >&5 -echo $ECHO_N "checking for getpagesize... $ECHO_C" >&6; } -cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ - -#include "confdefs.h" -#include - -int -main () -{ -void* p = getpagesize - ; - return 0; -} -_ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - -cat >>confdefs.h <<\_ACEOF -#define HAVE_GETPAGESIZE 1 -_ACEOF - - { echo "$as_me:$LINENO: result: yes" >&5 -echo "${ECHO_T}yes" >&6; } -else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - { echo "$as_me:$LINENO: result: no" >&5 -echo "${ECHO_T}no" >&6; } - -fi - -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext - -for ac_prog in true -do - # Extract the first word of "$ac_prog", so it can be a program name with args. -set dummy $ac_prog; ac_word=$2 -{ echo "$as_me:$LINENO: checking for $ac_word" >&5 -echo $ECHO_N "checking for $ac_word... $ECHO_C" >&6; } -if test "${ac_cv_prog_TRUE+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 -else - if test -n "$TRUE"; then - ac_cv_prog_TRUE="$TRUE" # Let the user override the test. -else -as_save_IFS=$IFS; IFS=$PATH_SEPARATOR -for as_dir in $PATH -do - IFS=$as_save_IFS - test -z "$as_dir" && as_dir=. - for ac_exec_ext in '' $ac_executable_extensions; do - if { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_test_x "$as_dir/$ac_word$ac_exec_ext"; }; then - ac_cv_prog_TRUE="$ac_prog" - echo "$as_me:$LINENO: found $as_dir/$ac_word$ac_exec_ext" >&5 - break 2 - fi -done -done -IFS=$as_save_IFS - -fi -fi -TRUE=$ac_cv_prog_TRUE -if test -n "$TRUE"; then - { echo "$as_me:$LINENO: result: $TRUE" >&5 -echo "${ECHO_T}$TRUE" >&6; } -else - { echo "$as_me:$LINENO: result: no" >&5 -echo "${ECHO_T}no" >&6; } -fi - - - test -n "$TRUE" && break -done -test -n "$TRUE" || TRUE="/bin/true" - - -{ echo "$as_me:$LINENO: checking for inet_aton in -lc" >&5 -echo $ECHO_N "checking for inet_aton in -lc... $ECHO_C" >&6; } -if test "${ac_cv_lib_c_inet_aton+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 -else - ac_check_lib_save_LIBS=$LIBS -LIBS="-lc $LIBS" -cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ - -/* Override any GCC internal prototype to avoid an error. - Use char because int might match the return type of a GCC - builtin and then its argument prototype would still apply. */ -#ifdef __cplusplus -extern "C" -#endif -char inet_aton (); -int -main () -{ -return inet_aton (); - ; - return 0; -} -_ACEOF -rm -f conftest.$ac_objext conftest$ac_exeext -if { (ac_try="$ac_link" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_link") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest$ac_exeext && - $as_test_x conftest$ac_exeext; then - ac_cv_lib_c_inet_aton=yes -else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - ac_cv_lib_c_inet_aton=no -fi - -rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \ - conftest$ac_exeext conftest.$ac_ext -LIBS=$ac_check_lib_save_LIBS -fi -{ echo "$as_me:$LINENO: result: $ac_cv_lib_c_inet_aton" >&5 -echo "${ECHO_T}$ac_cv_lib_c_inet_aton" >&6; } -if test $ac_cv_lib_c_inet_aton = yes; then - $ac_cv_prog_TRUE -else - -{ echo "$as_me:$LINENO: checking for inet_aton in -lresolv" >&5 -echo $ECHO_N "checking for inet_aton in -lresolv... $ECHO_C" >&6; } -if test "${ac_cv_lib_resolv_inet_aton+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 -else - ac_check_lib_save_LIBS=$LIBS -LIBS="-lresolv $LIBS" -cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ - -/* Override any GCC internal prototype to avoid an error. - Use char because int might match the return type of a GCC - builtin and then its argument prototype would still apply. */ -#ifdef __cplusplus -extern "C" -#endif -char inet_aton (); -int -main () -{ -return inet_aton (); - ; - return 0; -} -_ACEOF -rm -f conftest.$ac_objext conftest$ac_exeext -if { (ac_try="$ac_link" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_link") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest$ac_exeext && - $as_test_x conftest$ac_exeext; then - ac_cv_lib_resolv_inet_aton=yes -else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - ac_cv_lib_resolv_inet_aton=no -fi - -rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \ - conftest$ac_exeext conftest.$ac_ext -LIBS=$ac_check_lib_save_LIBS -fi -{ echo "$as_me:$LINENO: result: $ac_cv_lib_resolv_inet_aton" >&5 -echo "${ECHO_T}$ac_cv_lib_resolv_inet_aton" >&6; } -if test $ac_cv_lib_resolv_inet_aton = yes; then - cat >>confdefs.h <<_ACEOF -#define HAVE_LIBRESOLV 1 -_ACEOF - - LIBS="-lresolv $LIBS" - -fi - - -fi - - -# On Tru64, chflags seems to be present, but calling it will -# exit Python -{ echo "$as_me:$LINENO: checking for chflags" >&5 -echo $ECHO_N "checking for chflags... $ECHO_C" >&6; } -if test "${ac_cv_have_chflags+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 -else - if test "$cross_compiling" = yes; then - ac_cv_have_chflags=cross -else - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -[ -#include -#include -int main(int argc, char*argv[]) -{ - if(chflags(argv[0], 0) != 0) - return 1; - return 0; -} -] -_ACEOF -rm -f conftest$ac_exeext -if { (ac_try="$ac_link" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_link") 2>&5 - ac_status=$? - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { ac_try='./conftest$ac_exeext' - { (case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_try") 2>&5 - ac_status=$? - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); }; }; then - ac_cv_have_chflags=yes -else - echo "$as_me: program exited with status $ac_status" >&5 -echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - -( exit $ac_status ) -ac_cv_have_chflags=no -fi -rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext conftest.$ac_objext conftest.$ac_ext -fi - - - -fi -{ echo "$as_me:$LINENO: result: $ac_cv_have_chflags" >&5 -echo "${ECHO_T}$ac_cv_have_chflags" >&6; } -if test "$ac_cv_have_chflags" = cross ; then - { echo "$as_me:$LINENO: checking for chflags" >&5 -echo $ECHO_N "checking for chflags... $ECHO_C" >&6; } -if test "${ac_cv_func_chflags+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 -else - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -/* Define chflags to an innocuous variant, in case declares chflags. - For example, HP-UX 11i declares gettimeofday. */ -#define chflags innocuous_chflags - -/* System header to define __stub macros and hopefully few prototypes, - which can conflict with char chflags (); below. - Prefer to if __STDC__ is defined, since - exists even on freestanding compilers. */ - -#ifdef __STDC__ -# include -#else -# include -#endif - -#undef chflags - -/* Override any GCC internal prototype to avoid an error. - Use char because int might match the return type of a GCC - builtin and then its argument prototype would still apply. */ -#ifdef __cplusplus -extern "C" -#endif -char chflags (); -/* The GNU C library defines this for functions which it implements - to always fail with ENOSYS. Some functions are actually named - something starting with __ and the normal name is an alias. */ -#if defined __stub_chflags || defined __stub___chflags -choke me -#endif - -int -main () -{ -return chflags (); - ; - return 0; -} -_ACEOF -rm -f conftest.$ac_objext conftest$ac_exeext -if { (ac_try="$ac_link" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_link") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest$ac_exeext && - $as_test_x conftest$ac_exeext; then - ac_cv_func_chflags=yes -else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - ac_cv_func_chflags=no -fi - -rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \ - conftest$ac_exeext conftest.$ac_ext -fi -{ echo "$as_me:$LINENO: result: $ac_cv_func_chflags" >&5 -echo "${ECHO_T}$ac_cv_func_chflags" >&6; } -if test $ac_cv_func_chflags = yes; then - ac_cv_have_chflags="yes" -else - ac_cv_have_chflags="no" -fi - -fi -if test "$ac_cv_have_chflags" = yes ; then - -cat >>confdefs.h <<\_ACEOF -#define HAVE_CHFLAGS 1 -_ACEOF - -fi - -{ echo "$as_me:$LINENO: checking for lchflags" >&5 -echo $ECHO_N "checking for lchflags... $ECHO_C" >&6; } -if test "${ac_cv_have_lchflags+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 -else - if test "$cross_compiling" = yes; then - ac_cv_have_lchflags=cross -else - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -[ -#include -#include -int main(int argc, char*argv[]) -{ - if(lchflags(argv[0], 0) != 0) - return 1; - return 0; -} -] -_ACEOF -rm -f conftest$ac_exeext -if { (ac_try="$ac_link" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_link") 2>&5 - ac_status=$? - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { ac_try='./conftest$ac_exeext' - { (case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_try") 2>&5 - ac_status=$? - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); }; }; then - ac_cv_have_lchflags=yes -else - echo "$as_me: program exited with status $ac_status" >&5 -echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - -( exit $ac_status ) -ac_cv_have_lchflags=no -fi -rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext conftest.$ac_objext conftest.$ac_ext -fi - - - -fi -{ echo "$as_me:$LINENO: result: $ac_cv_have_lchflags" >&5 -echo "${ECHO_T}$ac_cv_have_lchflags" >&6; } -if test "$ac_cv_have_lchflags" = cross ; then - { echo "$as_me:$LINENO: checking for lchflags" >&5 -echo $ECHO_N "checking for lchflags... $ECHO_C" >&6; } -if test "${ac_cv_func_lchflags+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 -else - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -/* Define lchflags to an innocuous variant, in case declares lchflags. - For example, HP-UX 11i declares gettimeofday. */ -#define lchflags innocuous_lchflags - -/* System header to define __stub macros and hopefully few prototypes, - which can conflict with char lchflags (); below. - Prefer to if __STDC__ is defined, since - exists even on freestanding compilers. */ - -#ifdef __STDC__ -# include -#else -# include -#endif - -#undef lchflags - -/* Override any GCC internal prototype to avoid an error. - Use char because int might match the return type of a GCC - builtin and then its argument prototype would still apply. */ -#ifdef __cplusplus -extern "C" -#endif -char lchflags (); -/* The GNU C library defines this for functions which it implements - to always fail with ENOSYS. Some functions are actually named - something starting with __ and the normal name is an alias. */ -#if defined __stub_lchflags || defined __stub___lchflags -choke me -#endif - -int -main () -{ -return lchflags (); - ; - return 0; -} -_ACEOF -rm -f conftest.$ac_objext conftest$ac_exeext -if { (ac_try="$ac_link" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_link") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest$ac_exeext && - $as_test_x conftest$ac_exeext; then - ac_cv_func_lchflags=yes -else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - ac_cv_func_lchflags=no -fi - -rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \ - conftest$ac_exeext conftest.$ac_ext -fi -{ echo "$as_me:$LINENO: result: $ac_cv_func_lchflags" >&5 -echo "${ECHO_T}$ac_cv_func_lchflags" >&6; } -if test $ac_cv_func_lchflags = yes; then - ac_cv_have_lchflags="yes" -else - ac_cv_have_lchflags="no" -fi - -fi -if test "$ac_cv_have_lchflags" = yes ; then - -cat >>confdefs.h <<\_ACEOF -#define HAVE_LCHFLAGS 1 -_ACEOF - -fi - -case $ac_sys_system/$ac_sys_release in -Darwin/*) - _CUR_CFLAGS="${CFLAGS}" - _CUR_LDFLAGS="${LDFLAGS}" - CFLAGS="${CFLAGS} -Wl,-search_paths_first" - LDFLAGS="${LDFLAGS} -Wl,-search_paths_first -L/usr/local/lib" - ;; -esac - -{ echo "$as_me:$LINENO: checking for inflateCopy in -lz" >&5 -echo $ECHO_N "checking for inflateCopy in -lz... $ECHO_C" >&6; } -if test "${ac_cv_lib_z_inflateCopy+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 -else - ac_check_lib_save_LIBS=$LIBS -LIBS="-lz $LIBS" -cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ - -/* Override any GCC internal prototype to avoid an error. - Use char because int might match the return type of a GCC - builtin and then its argument prototype would still apply. */ -#ifdef __cplusplus -extern "C" -#endif -char inflateCopy (); -int -main () -{ -return inflateCopy (); - ; - return 0; -} -_ACEOF -rm -f conftest.$ac_objext conftest$ac_exeext -if { (ac_try="$ac_link" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_link") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest$ac_exeext && - $as_test_x conftest$ac_exeext; then - ac_cv_lib_z_inflateCopy=yes -else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - ac_cv_lib_z_inflateCopy=no -fi - -rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \ - conftest$ac_exeext conftest.$ac_ext -LIBS=$ac_check_lib_save_LIBS -fi -{ echo "$as_me:$LINENO: result: $ac_cv_lib_z_inflateCopy" >&5 -echo "${ECHO_T}$ac_cv_lib_z_inflateCopy" >&6; } -if test $ac_cv_lib_z_inflateCopy = yes; then - -cat >>confdefs.h <<\_ACEOF -#define HAVE_ZLIB_COPY 1 -_ACEOF - -fi - - -case $ac_sys_system/$ac_sys_release in -Darwin/*) - CFLAGS="${_CUR_CFLAGS}" - LDFLAGS="${_CUR_LDFLAGS}" - ;; -esac - -{ echo "$as_me:$LINENO: checking for hstrerror" >&5 -echo $ECHO_N "checking for hstrerror... $ECHO_C" >&6; } -cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ - -#include "confdefs.h" -#include - -int -main () -{ -void* p = hstrerror; hstrerror(0) - ; - return 0; -} -_ACEOF -rm -f conftest.$ac_objext conftest$ac_exeext -if { (ac_try="$ac_link" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_link") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest$ac_exeext && - $as_test_x conftest$ac_exeext; then - -cat >>confdefs.h <<\_ACEOF -#define HAVE_HSTRERROR 1 -_ACEOF - - { echo "$as_me:$LINENO: result: yes" >&5 -echo "${ECHO_T}yes" >&6; } -else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - { echo "$as_me:$LINENO: result: no" >&5 -echo "${ECHO_T}no" >&6; } - -fi - -rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \ - conftest$ac_exeext conftest.$ac_ext - -{ echo "$as_me:$LINENO: checking for inet_aton" >&5 -echo $ECHO_N "checking for inet_aton... $ECHO_C" >&6; } -cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ - -#include "confdefs.h" -#include -#include -#include -#include - -int -main () -{ -void* p = inet_aton;inet_aton(0,0) - ; - return 0; -} -_ACEOF -rm -f conftest.$ac_objext conftest$ac_exeext -if { (ac_try="$ac_link" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_link") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest$ac_exeext && - $as_test_x conftest$ac_exeext; then - -cat >>confdefs.h <<\_ACEOF -#define HAVE_INET_ATON 1 -_ACEOF - - { echo "$as_me:$LINENO: result: yes" >&5 -echo "${ECHO_T}yes" >&6; } -else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - { echo "$as_me:$LINENO: result: no" >&5 -echo "${ECHO_T}no" >&6; } - -fi - -rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \ - conftest$ac_exeext conftest.$ac_ext - -{ echo "$as_me:$LINENO: checking for inet_pton" >&5 -echo $ECHO_N "checking for inet_pton... $ECHO_C" >&6; } -cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ - -#include "confdefs.h" -#include -#include -#include -#include - -int -main () -{ -void* p = inet_pton - ; - return 0; -} -_ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - -cat >>confdefs.h <<\_ACEOF -#define HAVE_INET_PTON 1 -_ACEOF - - { echo "$as_me:$LINENO: result: yes" >&5 -echo "${ECHO_T}yes" >&6; } -else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - { echo "$as_me:$LINENO: result: no" >&5 -echo "${ECHO_T}no" >&6; } - + fi + ;; + Linux*|GNU*|QNX*) + LDSHARED='$(CC) -shared' + LDCXXSHARED='$(CXX) -shared';; + BSD/OS*/4*) + LDSHARED="gcc -shared" + LDCXXSHARED="g++ -shared";; + FreeBSD*) + if [ "`$CC -dM -E - &5 -echo $ECHO_N "checking for setgroups... $ECHO_C" >&6; } -cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ - -#include "confdefs.h" -#include -#ifdef HAVE_GRP_H -#include -#endif - -int -main () -{ -void* p = setgroups - ; - return 0; -} -_ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - -cat >>confdefs.h <<\_ACEOF -#define HAVE_SETGROUPS 1 -_ACEOF - - { echo "$as_me:$LINENO: result: yes" >&5 -echo "${ECHO_T}yes" >&6; } -else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - { echo "$as_me:$LINENO: result: no" >&5 -echo "${ECHO_T}no" >&6; } - +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $LDSHARED" >&5 +$as_echo "$LDSHARED" >&6; } +LDCXXSHARED=${LDCXXSHARED-$LDSHARED} +BLDSHARED=${BLDSHARED-$LDSHARED} +# CCSHARED are the C *flags* used to create objects to go into a shared +# library (module) -- this is only needed for a few systems +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking CCSHARED" >&5 +$as_echo_n "checking CCSHARED... " >&6; } +if test -z "$CCSHARED" +then + case $ac_sys_system/$ac_sys_release in + SunOS*) if test "$GCC" = yes; + then CCSHARED="-fPIC"; + elif test `uname -p` = sparc; + then CCSHARED="-xcode=pic32"; + else CCSHARED="-Kpic"; + fi;; + hp*|HP*) if test "$GCC" = yes; + then CCSHARED="-fPIC"; + else CCSHARED="+z"; + fi;; + Linux*|GNU*) CCSHARED="-fPIC";; + BSD/OS*/4*) CCSHARED="-fpic";; + FreeBSD*|NetBSD*|OpenBSD*|DragonFly*) CCSHARED="-fPIC";; + OpenUNIX*|UnixWare*) + if test "$GCC" = "yes" + then CCSHARED="-fPIC" + else CCSHARED="-KPIC" + fi;; + SCO_SV*) + if test "$GCC" = "yes" + then CCSHARED="-fPIC" + else CCSHARED="-Kpic -belf" + fi;; + IRIX*/6*) case $CC in + *gcc*) CCSHARED="-shared";; + *) CCSHARED="";; + esac;; + esac fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $CCSHARED" >&5 +$as_echo "$CCSHARED" >&6; } +# LINKFORSHARED are the flags passed to the $(CC) command that links +# the python executable -- this is only needed for a few systems +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking LINKFORSHARED" >&5 +$as_echo_n "checking LINKFORSHARED... " >&6; } +if test -z "$LINKFORSHARED" +then + case $ac_sys_system/$ac_sys_release in + AIX*) LINKFORSHARED='-Wl,-bE:Modules/python.exp -lld';; + hp*|HP*) + 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";; + # -u libsys_s pulls in all symbols in libsys + Darwin/*) + LINKFORSHARED="$extra_undefs -framework CoreFoundation" + if test "$enable_framework" + then + LINKFORSHARED="$LINKFORSHARED "'$(PYTHONFRAMEWORKDIR)/Versions/$(VERSION)/$(PYTHONFRAMEWORK)' + fi + LINKFORSHARED="$LINKFORSHARED";; + OpenUNIX*|UnixWare*) LINKFORSHARED="-Wl,-Bexport";; + SCO_SV*) LINKFORSHARED="-Wl,-Bexport";; + ReliantUNIX*) LINKFORSHARED="-W1 -Blargedynsym";; + FreeBSD*|NetBSD*|OpenBSD*|DragonFly*) + if [ "`$CC -dM -E - &1 | grep export-dynamic >/dev/null + then + LINKFORSHARED="-Xlinker --export-dynamic" + fi;; + esac;; + CYGWIN*) + if test $enable_shared = "no" + then + LINKFORSHARED='-Wl,--out-implib=$(LDLIBRARY)' + fi;; + QNX*) + # -Wl,-E causes the symbols to be added to the dynamic + # symbol table so that they can be found when a module + # is loaded. -N 2048K causes the stack size to be set + # to 2048 kilobytes so that the stack doesn't overflow + # when running test_compile.py. + LINKFORSHARED='-Wl,-E -N 2048K';; + esac +fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $LINKFORSHARED" >&5 +$as_echo "$LINKFORSHARED" >&6; } -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext - -# check for openpty and forkpty - - -for ac_func in openpty -do -as_ac_var=`echo "ac_cv_func_$ac_func" | $as_tr_sh` -{ echo "$as_me:$LINENO: checking for $ac_func" >&5 -echo $ECHO_N "checking for $ac_func... $ECHO_C" >&6; } -if { as_var=$as_ac_var; eval "test \"\${$as_var+set}\" = set"; }; then - echo $ECHO_N "(cached) $ECHO_C" >&6 -else - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -/* Define $ac_func to an innocuous variant, in case declares $ac_func. - For example, HP-UX 11i declares gettimeofday. */ -#define $ac_func innocuous_$ac_func - -/* System header to define __stub macros and hopefully few prototypes, - which can conflict with char $ac_func (); below. - Prefer to if __STDC__ is defined, since - exists even on freestanding compilers. */ - -#ifdef __STDC__ -# include -#else -# include -#endif - -#undef $ac_func - -/* Override any GCC internal prototype to avoid an error. - Use char because int might match the return type of a GCC - builtin and then its argument prototype would still apply. */ -#ifdef __cplusplus -extern "C" -#endif -char $ac_func (); -/* The GNU C library defines this for functions which it implements - to always fail with ENOSYS. Some functions are actually named - something starting with __ and the normal name is an alias. */ -#if defined __stub_$ac_func || defined __stub___$ac_func -choke me -#endif - -int -main () -{ -return $ac_func (); - ; - return 0; -} -_ACEOF -rm -f conftest.$ac_objext conftest$ac_exeext -if { (ac_try="$ac_link" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_link") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest$ac_exeext && - $as_test_x conftest$ac_exeext; then - eval "$as_ac_var=yes" -else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - eval "$as_ac_var=no" -fi -rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \ - conftest$ac_exeext conftest.$ac_ext +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking CFLAGSFORSHARED" >&5 +$as_echo_n "checking CFLAGSFORSHARED... " >&6; } +if test ! "$LIBRARY" = "$LDLIBRARY" +then + case $ac_sys_system in + CYGWIN*) + # Cygwin needs CCSHARED when building extension DLLs + # but not when building the interpreter DLL. + CFLAGSFORSHARED='';; + *) + CFLAGSFORSHARED='$(CCSHARED)' + esac fi -ac_res=`eval echo '${'$as_ac_var'}'` - { echo "$as_me:$LINENO: result: $ac_res" >&5 -echo "${ECHO_T}$ac_res" >&6; } -if test `eval echo '${'$as_ac_var'}'` = yes; then - cat >>confdefs.h <<_ACEOF -#define `echo "HAVE_$ac_func" | $as_tr_cpp` 1 -_ACEOF +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $CFLAGSFORSHARED" >&5 +$as_echo "$CFLAGSFORSHARED" >&6; } -else - { echo "$as_me:$LINENO: checking for openpty in -lutil" >&5 -echo $ECHO_N "checking for openpty in -lutil... $ECHO_C" >&6; } -if test "${ac_cv_lib_util_openpty+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 -else - ac_check_lib_save_LIBS=$LIBS -LIBS="-lutil $LIBS" -cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ +# SHLIBS are libraries (except -lc and -lm) to link to the python shared +# library (with --enable-shared). +# For platforms on which shared libraries are not allowed to have unresolved +# symbols, this must be set to $(LIBS) (expanded by make). We do this even +# if it is not required, since it creates a dependency of the shared library +# to LIBS. This, in turn, means that applications linking the shared libpython +# don't need to link LIBS explicitly. The default should be only changed +# on systems where this approach causes problems. -/* Override any GCC internal prototype to avoid an error. - Use char because int might match the return type of a GCC - builtin and then its argument prototype would still apply. */ -#ifdef __cplusplus -extern "C" -#endif -char openpty (); -int -main () -{ -return openpty (); - ; - return 0; -} -_ACEOF -rm -f conftest.$ac_objext conftest$ac_exeext -if { (ac_try="$ac_link" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking SHLIBS" >&5 +$as_echo_n "checking SHLIBS... " >&6; } +case "$ac_sys_system" in + *) + SHLIBS='$(LIBS)';; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_link") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest$ac_exeext && - $as_test_x conftest$ac_exeext; then - ac_cv_lib_util_openpty=yes -else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $SHLIBS" >&5 +$as_echo "$SHLIBS" >&6; } - ac_cv_lib_util_openpty=no -fi -rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \ - conftest$ac_exeext conftest.$ac_ext -LIBS=$ac_check_lib_save_LIBS -fi -{ echo "$as_me:$LINENO: result: $ac_cv_lib_util_openpty" >&5 -echo "${ECHO_T}$ac_cv_lib_util_openpty" >&6; } -if test $ac_cv_lib_util_openpty = yes; then - cat >>confdefs.h <<\_ACEOF -#define HAVE_OPENPTY 1 -_ACEOF - LIBS="$LIBS -lutil" -else - { echo "$as_me:$LINENO: checking for openpty in -lbsd" >&5 -echo $ECHO_N "checking for openpty in -lbsd... $ECHO_C" >&6; } -if test "${ac_cv_lib_bsd_openpty+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 +# checks for libraries +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for dlopen in -ldl" >&5 +$as_echo_n "checking for dlopen in -ldl... " >&6; } +if test "${ac_cv_lib_dl_dlopen+set}" = set; then : + $as_echo_n "(cached) " >&6 else ac_check_lib_save_LIBS=$LIBS -LIBS="-lbsd $LIBS" -cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF +LIBS="-ldl $LIBS" +cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ /* Override any GCC internal prototype to avoid an error. @@ -19499,92 +7750,44 @@ #ifdef __cplusplus extern "C" #endif -char openpty (); +char dlopen (); int main () { -return openpty (); +return dlopen (); ; return 0; } _ACEOF -rm -f conftest.$ac_objext conftest$ac_exeext -if { (ac_try="$ac_link" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_link") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest$ac_exeext && - $as_test_x conftest$ac_exeext; then - ac_cv_lib_bsd_openpty=yes +if ac_fn_c_try_link "$LINENO"; then : + ac_cv_lib_dl_dlopen=yes else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - ac_cv_lib_bsd_openpty=no + ac_cv_lib_dl_dlopen=no fi - -rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \ - conftest$ac_exeext conftest.$ac_ext +rm -f core conftest.err conftest.$ac_objext \ + conftest$ac_exeext conftest.$ac_ext LIBS=$ac_check_lib_save_LIBS fi -{ echo "$as_me:$LINENO: result: $ac_cv_lib_bsd_openpty" >&5 -echo "${ECHO_T}$ac_cv_lib_bsd_openpty" >&6; } -if test $ac_cv_lib_bsd_openpty = yes; then - cat >>confdefs.h <<\_ACEOF -#define HAVE_OPENPTY 1 +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_lib_dl_dlopen" >&5 +$as_echo "$ac_cv_lib_dl_dlopen" >&6; } +if test "x$ac_cv_lib_dl_dlopen" = x""yes; then : + cat >>confdefs.h <<_ACEOF +#define HAVE_LIBDL 1 _ACEOF - LIBS="$LIBS -lbsd" -fi - - -fi + LIBS="-ldl $LIBS" fi -done - - -for ac_func in forkpty -do -as_ac_var=`echo "ac_cv_func_$ac_func" | $as_tr_sh` -{ echo "$as_me:$LINENO: checking for $ac_func" >&5 -echo $ECHO_N "checking for $ac_func... $ECHO_C" >&6; } -if { as_var=$as_ac_var; eval "test \"\${$as_var+set}\" = set"; }; then - echo $ECHO_N "(cached) $ECHO_C" >&6 + # Dynamic linking for SunOS/Solaris and SYSV +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for shl_load in -ldld" >&5 +$as_echo_n "checking for shl_load in -ldld... " >&6; } +if test "${ac_cv_lib_dld_shl_load+set}" = set; then : + $as_echo_n "(cached) " >&6 else - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF + ac_check_lib_save_LIBS=$LIBS +LIBS="-ldld $LIBS" +cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ -/* Define $ac_func to an innocuous variant, in case declares $ac_func. - For example, HP-UX 11i declares gettimeofday. */ -#define $ac_func innocuous_$ac_func - -/* System header to define __stub macros and hopefully few prototypes, - which can conflict with char $ac_func (); below. - Prefer to if __STDC__ is defined, since - exists even on freestanding compilers. */ - -#ifdef __STDC__ -# include -#else -# include -#endif - -#undef $ac_func /* Override any GCC internal prototype to avoid an error. Use char because int might match the return type of a GCC @@ -19592,139 +7795,45 @@ #ifdef __cplusplus extern "C" #endif -char $ac_func (); -/* The GNU C library defines this for functions which it implements - to always fail with ENOSYS. Some functions are actually named - something starting with __ and the normal name is an alias. */ -#if defined __stub_$ac_func || defined __stub___$ac_func -choke me -#endif - +char shl_load (); int main () { -return $ac_func (); +return shl_load (); ; return 0; } _ACEOF -rm -f conftest.$ac_objext conftest$ac_exeext -if { (ac_try="$ac_link" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_link") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest$ac_exeext && - $as_test_x conftest$ac_exeext; then - eval "$as_ac_var=yes" +if ac_fn_c_try_link "$LINENO"; then : + ac_cv_lib_dld_shl_load=yes else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - eval "$as_ac_var=no" + ac_cv_lib_dld_shl_load=no fi - -rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \ - conftest$ac_exeext conftest.$ac_ext +rm -f core conftest.err conftest.$ac_objext \ + conftest$ac_exeext conftest.$ac_ext +LIBS=$ac_check_lib_save_LIBS fi -ac_res=`eval echo '${'$as_ac_var'}'` - { echo "$as_me:$LINENO: result: $ac_res" >&5 -echo "${ECHO_T}$ac_res" >&6; } -if test `eval echo '${'$as_ac_var'}'` = yes; then +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_lib_dld_shl_load" >&5 +$as_echo "$ac_cv_lib_dld_shl_load" >&6; } +if test "x$ac_cv_lib_dld_shl_load" = x""yes; then : cat >>confdefs.h <<_ACEOF -#define `echo "HAVE_$ac_func" | $as_tr_cpp` 1 -_ACEOF - -else - { echo "$as_me:$LINENO: checking for forkpty in -lutil" >&5 -echo $ECHO_N "checking for forkpty in -lutil... $ECHO_C" >&6; } -if test "${ac_cv_lib_util_forkpty+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 -else - ac_check_lib_save_LIBS=$LIBS -LIBS="-lutil $LIBS" -cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ +#define HAVE_LIBDLD 1 _ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -/* Override any GCC internal prototype to avoid an error. - Use char because int might match the return type of a GCC - builtin and then its argument prototype would still apply. */ -#ifdef __cplusplus -extern "C" -#endif -char forkpty (); -int -main () -{ -return forkpty (); - ; - return 0; -} -_ACEOF -rm -f conftest.$ac_objext conftest$ac_exeext -if { (ac_try="$ac_link" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_link") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest$ac_exeext && - $as_test_x conftest$ac_exeext; then - ac_cv_lib_util_forkpty=yes -else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 + LIBS="-ldld $LIBS" - ac_cv_lib_util_forkpty=no fi + # Dynamic linking for HP-UX -rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \ - conftest$ac_exeext conftest.$ac_ext -LIBS=$ac_check_lib_save_LIBS -fi -{ echo "$as_me:$LINENO: result: $ac_cv_lib_util_forkpty" >&5 -echo "${ECHO_T}$ac_cv_lib_util_forkpty" >&6; } -if test $ac_cv_lib_util_forkpty = yes; then - cat >>confdefs.h <<\_ACEOF -#define HAVE_FORKPTY 1 -_ACEOF - LIBS="$LIBS -lutil" -else - { echo "$as_me:$LINENO: checking for forkpty in -lbsd" >&5 -echo $ECHO_N "checking for forkpty in -lbsd... $ECHO_C" >&6; } -if test "${ac_cv_lib_bsd_forkpty+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 +# only check for sem_init if thread support is requested +if test "$with_threads" = "yes" -o -z "$with_threads"; then + { $as_echo "$as_me:${as_lineno-$LINENO}: checking for library containing sem_init" >&5 +$as_echo_n "checking for library containing sem_init... " >&6; } +if test "${ac_cv_search_sem_init+set}" = set; then : + $as_echo_n "(cached) " >&6 else - ac_check_lib_save_LIBS=$LIBS -LIBS="-lbsd $LIBS" -cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF + ac_func_search_save_LIBS=$LIBS +cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ /* Override any GCC internal prototype to avoid an error. @@ -19733,94 +7842,61 @@ #ifdef __cplusplus extern "C" #endif -char forkpty (); +char sem_init (); int main () { -return forkpty (); +return sem_init (); ; return 0; } _ACEOF -rm -f conftest.$ac_objext conftest$ac_exeext -if { (ac_try="$ac_link" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_link") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest$ac_exeext && - $as_test_x conftest$ac_exeext; then - ac_cv_lib_bsd_forkpty=yes -else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - ac_cv_lib_bsd_forkpty=no +for ac_lib in '' pthread rt posix4; do + if test -z "$ac_lib"; then + ac_res="none required" + else + ac_res=-l$ac_lib + LIBS="-l$ac_lib $ac_func_search_save_LIBS" + fi + if ac_fn_c_try_link "$LINENO"; then : + ac_cv_search_sem_init=$ac_res +fi +rm -f core conftest.err conftest.$ac_objext \ + conftest$ac_exeext + if test "${ac_cv_search_sem_init+set}" = set; then : + break fi +done +if test "${ac_cv_search_sem_init+set}" = set; then : -rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \ - conftest$ac_exeext conftest.$ac_ext -LIBS=$ac_check_lib_save_LIBS +else + ac_cv_search_sem_init=no fi -{ echo "$as_me:$LINENO: result: $ac_cv_lib_bsd_forkpty" >&5 -echo "${ECHO_T}$ac_cv_lib_bsd_forkpty" >&6; } -if test $ac_cv_lib_bsd_forkpty = yes; then - cat >>confdefs.h <<\_ACEOF -#define HAVE_FORKPTY 1 -_ACEOF - LIBS="$LIBS -lbsd" +rm conftest.$ac_ext +LIBS=$ac_func_search_save_LIBS fi - +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_search_sem_init" >&5 +$as_echo "$ac_cv_search_sem_init" >&6; } +ac_res=$ac_cv_search_sem_init +if test "$ac_res" != no; then : + test "$ac_res" = "none required" || LIBS="$ac_res $LIBS" fi - - + # 'Real Time' functions on Solaris + # posix4 on Solaris 2.6 + # pthread (first!) on Linux fi -done - -# Stuff for expat. - -for ac_func in memmove -do -as_ac_var=`echo "ac_cv_func_$ac_func" | $as_tr_sh` -{ echo "$as_me:$LINENO: checking for $ac_func" >&5 -echo $ECHO_N "checking for $ac_func... $ECHO_C" >&6; } -if { as_var=$as_ac_var; eval "test \"\${$as_var+set}\" = set"; }; then - echo $ECHO_N "(cached) $ECHO_C" >&6 +# check if we need libintl for locale functions +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for textdomain in -lintl" >&5 +$as_echo_n "checking for textdomain in -lintl... " >&6; } +if test "${ac_cv_lib_intl_textdomain+set}" = set; then : + $as_echo_n "(cached) " >&6 else - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF + ac_check_lib_save_LIBS=$LIBS +LIBS="-lintl $LIBS" +cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ -/* Define $ac_func to an innocuous variant, in case declares $ac_func. - For example, HP-UX 11i declares gettimeofday. */ -#define $ac_func innocuous_$ac_func - -/* System header to define __stub macros and hopefully few prototypes, - which can conflict with char $ac_func (); below. - Prefer to if __STDC__ is defined, since - exists even on freestanding compilers. */ - -#ifdef __STDC__ -# include -#else -# include -#endif - -#undef $ac_func /* Override any GCC internal prototype to avoid an error. Use char because int might match the return type of a GCC @@ -19828,100 +7904,80 @@ #ifdef __cplusplus extern "C" #endif -char $ac_func (); -/* The GNU C library defines this for functions which it implements - to always fail with ENOSYS. Some functions are actually named - something starting with __ and the normal name is an alias. */ -#if defined __stub_$ac_func || defined __stub___$ac_func -choke me -#endif - +char textdomain (); int main () { -return $ac_func (); +return textdomain (); ; return 0; } _ACEOF -rm -f conftest.$ac_objext conftest$ac_exeext -if { (ac_try="$ac_link" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_link") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest$ac_exeext && - $as_test_x conftest$ac_exeext; then - eval "$as_ac_var=yes" +if ac_fn_c_try_link "$LINENO"; then : + ac_cv_lib_intl_textdomain=yes else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - eval "$as_ac_var=no" + ac_cv_lib_intl_textdomain=no fi - -rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \ - conftest$ac_exeext conftest.$ac_ext +rm -f core conftest.err conftest.$ac_objext \ + conftest$ac_exeext conftest.$ac_ext +LIBS=$ac_check_lib_save_LIBS fi -ac_res=`eval echo '${'$as_ac_var'}'` - { echo "$as_me:$LINENO: result: $ac_res" >&5 -echo "${ECHO_T}$ac_res" >&6; } -if test `eval echo '${'$as_ac_var'}'` = yes; then - cat >>confdefs.h <<_ACEOF -#define `echo "HAVE_$ac_func" | $as_tr_cpp` 1 -_ACEOF +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_lib_intl_textdomain" >&5 +$as_echo "$ac_cv_lib_intl_textdomain" >&6; } +if test "x$ac_cv_lib_intl_textdomain" = x""yes; then : +$as_echo "#define WITH_LIBINTL 1" >>confdefs.h + + LIBS="-lintl $LIBS" fi -done -# check for long file support functions +# checks for system dependent C++ extensions support +case "$ac_sys_system" in + AIX*) { $as_echo "$as_me:${as_lineno-$LINENO}: checking for genuine AIX C++ extensions support" >&5 +$as_echo_n "checking for genuine AIX C++ extensions support... " >&6; } + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + #include "/usr/lpp/xlC/include/load.h" +int +main () +{ +loadAndInit("", 0, "") + ; + return 0; +} +_ACEOF +if ac_fn_c_try_link "$LINENO"; then : +$as_echo "#define AIX_GENUINE_CPLUSPLUS 1" >>confdefs.h + { $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +$as_echo "yes" >&6; } -for ac_func in fseek64 fseeko fstatvfs ftell64 ftello statvfs -do -as_ac_var=`echo "ac_cv_func_$ac_func" | $as_tr_sh` -{ echo "$as_me:$LINENO: checking for $ac_func" >&5 -echo $ECHO_N "checking for $ac_func... $ECHO_C" >&6; } -if { as_var=$as_ac_var; eval "test \"\${$as_var+set}\" = set"; }; then - echo $ECHO_N "(cached) $ECHO_C" >&6 else - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -/* Define $ac_func to an innocuous variant, in case declares $ac_func. - For example, HP-UX 11i declares gettimeofday. */ -#define $ac_func innocuous_$ac_func -/* System header to define __stub macros and hopefully few prototypes, - which can conflict with char $ac_func (); below. - Prefer to if __STDC__ is defined, since - exists even on freestanding compilers. */ + { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 +$as_echo "no" >&6; } -#ifdef __STDC__ -# include -#else -# include -#endif +fi +rm -f core conftest.err conftest.$ac_objext \ + conftest$ac_exeext conftest.$ac_ext;; + *) ;; +esac -#undef $ac_func +# Most SVR4 platforms (e.g. Solaris) need -lsocket and -lnsl. +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for t_open in -lnsl" >&5 +$as_echo_n "checking for t_open in -lnsl... " >&6; } +if test "${ac_cv_lib_nsl_t_open+set}" = set; then : + $as_echo_n "(cached) " >&6 +else + ac_check_lib_save_LIBS=$LIBS +LIBS="-lnsl $LIBS" +cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ /* Override any GCC internal prototype to avoid an error. Use char because int might match the return type of a GCC @@ -19929,96 +7985,39 @@ #ifdef __cplusplus extern "C" #endif -char $ac_func (); -/* The GNU C library defines this for functions which it implements - to always fail with ENOSYS. Some functions are actually named - something starting with __ and the normal name is an alias. */ -#if defined __stub_$ac_func || defined __stub___$ac_func -choke me -#endif - +char t_open (); int main () { -return $ac_func (); +return t_open (); ; return 0; } _ACEOF -rm -f conftest.$ac_objext conftest$ac_exeext -if { (ac_try="$ac_link" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_link") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest$ac_exeext && - $as_test_x conftest$ac_exeext; then - eval "$as_ac_var=yes" +if ac_fn_c_try_link "$LINENO"; then : + ac_cv_lib_nsl_t_open=yes else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - eval "$as_ac_var=no" + ac_cv_lib_nsl_t_open=no fi - -rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \ - conftest$ac_exeext conftest.$ac_ext +rm -f core conftest.err conftest.$ac_objext \ + conftest$ac_exeext conftest.$ac_ext +LIBS=$ac_check_lib_save_LIBS fi -ac_res=`eval echo '${'$as_ac_var'}'` - { echo "$as_me:$LINENO: result: $ac_res" >&5 -echo "${ECHO_T}$ac_res" >&6; } -if test `eval echo '${'$as_ac_var'}'` = yes; then - cat >>confdefs.h <<_ACEOF -#define `echo "HAVE_$ac_func" | $as_tr_cpp` 1 -_ACEOF - +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_lib_nsl_t_open" >&5 +$as_echo "$ac_cv_lib_nsl_t_open" >&6; } +if test "x$ac_cv_lib_nsl_t_open" = x""yes; then : + LIBS="-lnsl $LIBS" fi -done - - - - - -for ac_func in dup2 getcwd strdup -do -as_ac_var=`echo "ac_cv_func_$ac_func" | $as_tr_sh` -{ echo "$as_me:$LINENO: checking for $ac_func" >&5 -echo $ECHO_N "checking for $ac_func... $ECHO_C" >&6; } -if { as_var=$as_ac_var; eval "test \"\${$as_var+set}\" = set"; }; then - echo $ECHO_N "(cached) $ECHO_C" >&6 + # SVR4 +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for socket in -lsocket" >&5 +$as_echo_n "checking for socket in -lsocket... " >&6; } +if test "${ac_cv_lib_socket_socket+set}" = set; then : + $as_echo_n "(cached) " >&6 else - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF + ac_check_lib_save_LIBS=$LIBS +LIBS="-lsocket $LIBS $LIBS" +cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ -/* Define $ac_func to an innocuous variant, in case declares $ac_func. - For example, HP-UX 11i declares gettimeofday. */ -#define $ac_func innocuous_$ac_func - -/* System header to define __stub macros and hopefully few prototypes, - which can conflict with char $ac_func (); below. - Prefer to if __STDC__ is defined, since - exists even on freestanding compilers. */ - -#ifdef __STDC__ -# include -#else -# include -#endif - -#undef $ac_func /* Override any GCC internal prototype to avoid an error. Use char because int might match the return type of a GCC @@ -20026,799 +8025,476 @@ #ifdef __cplusplus extern "C" #endif -char $ac_func (); -/* The GNU C library defines this for functions which it implements - to always fail with ENOSYS. Some functions are actually named - something starting with __ and the normal name is an alias. */ -#if defined __stub_$ac_func || defined __stub___$ac_func -choke me -#endif - +char socket (); int main () { -return $ac_func (); +return socket (); ; return 0; } _ACEOF -rm -f conftest.$ac_objext conftest$ac_exeext -if { (ac_try="$ac_link" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_link") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest$ac_exeext && - $as_test_x conftest$ac_exeext; then - eval "$as_ac_var=yes" +if ac_fn_c_try_link "$LINENO"; then : + ac_cv_lib_socket_socket=yes else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - eval "$as_ac_var=no" + ac_cv_lib_socket_socket=no fi - -rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \ - conftest$ac_exeext conftest.$ac_ext +rm -f core conftest.err conftest.$ac_objext \ + conftest$ac_exeext conftest.$ac_ext +LIBS=$ac_check_lib_save_LIBS fi -ac_res=`eval echo '${'$as_ac_var'}'` - { echo "$as_me:$LINENO: result: $ac_res" >&5 -echo "${ECHO_T}$ac_res" >&6; } -if test `eval echo '${'$as_ac_var'}'` = yes; then - cat >>confdefs.h <<_ACEOF -#define `echo "HAVE_$ac_func" | $as_tr_cpp` 1 -_ACEOF - -else - case " $LIBOBJS " in - *" $ac_func.$ac_objext "* ) ;; - *) LIBOBJS="$LIBOBJS $ac_func.$ac_objext" - ;; -esac - +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_lib_socket_socket" >&5 +$as_echo "$ac_cv_lib_socket_socket" >&6; } +if test "x$ac_cv_lib_socket_socket" = x""yes; then : + LIBS="-lsocket $LIBS" fi -done + # SVR4 sockets +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for --with-libs" >&5 +$as_echo_n "checking for --with-libs... " >&6; } +# Check whether --with-libs was given. +if test "${with_libs+set}" = set; then : + withval=$with_libs; +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $withval" >&5 +$as_echo "$withval" >&6; } +LIBS="$withval $LIBS" -for ac_func in getpgrp -do -as_ac_var=`echo "ac_cv_func_$ac_func" | $as_tr_sh` -{ echo "$as_me:$LINENO: checking for $ac_func" >&5 -echo $ECHO_N "checking for $ac_func... $ECHO_C" >&6; } -if { as_var=$as_ac_var; eval "test \"\${$as_var+set}\" = set"; }; then - echo $ECHO_N "(cached) $ECHO_C" >&6 else - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -/* Define $ac_func to an innocuous variant, in case declares $ac_func. - For example, HP-UX 11i declares gettimeofday. */ -#define $ac_func innocuous_$ac_func + { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 +$as_echo "no" >&6; } +fi -/* System header to define __stub macros and hopefully few prototypes, - which can conflict with char $ac_func (); below. - Prefer to if __STDC__ is defined, since - exists even on freestanding compilers. */ -#ifdef __STDC__ -# include -#else -# include -#endif +if test -n "$ac_tool_prefix"; then + # Extract the first word of "${ac_tool_prefix}pkg-config", so it can be a program name with args. +set dummy ${ac_tool_prefix}pkg-config; ac_word=$2 +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 +$as_echo_n "checking for $ac_word... " >&6; } +if test "${ac_cv_path_PKG_CONFIG+set}" = set; then : + $as_echo_n "(cached) " >&6 +else + case $PKG_CONFIG in + [\\/]* | ?:[\\/]*) + ac_cv_path_PKG_CONFIG="$PKG_CONFIG" # Let the user override the test with a path. + ;; + *) + as_save_IFS=$IFS; IFS=$PATH_SEPARATOR +for as_dir in $PATH +do + IFS=$as_save_IFS + test -z "$as_dir" && as_dir=. + for ac_exec_ext in '' $ac_executable_extensions; do + if { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_test_x "$as_dir/$ac_word$ac_exec_ext"; }; then + ac_cv_path_PKG_CONFIG="$as_dir/$ac_word$ac_exec_ext" + $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 + break 2 + fi +done + done +IFS=$as_save_IFS -#undef $ac_func + ;; +esac +fi +PKG_CONFIG=$ac_cv_path_PKG_CONFIG +if test -n "$PKG_CONFIG"; then + { $as_echo "$as_me:${as_lineno-$LINENO}: result: $PKG_CONFIG" >&5 +$as_echo "$PKG_CONFIG" >&6; } +else + { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 +$as_echo "no" >&6; } +fi -/* Override any GCC internal prototype to avoid an error. - Use char because int might match the return type of a GCC - builtin and then its argument prototype would still apply. */ -#ifdef __cplusplus -extern "C" -#endif -char $ac_func (); -/* The GNU C library defines this for functions which it implements - to always fail with ENOSYS. Some functions are actually named - something starting with __ and the normal name is an alias. */ -#if defined __stub_$ac_func || defined __stub___$ac_func -choke me -#endif -int -main () -{ -return $ac_func (); - ; - return 0; -} -_ACEOF -rm -f conftest.$ac_objext conftest$ac_exeext -if { (ac_try="$ac_link" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; +fi +if test -z "$ac_cv_path_PKG_CONFIG"; then + ac_pt_PKG_CONFIG=$PKG_CONFIG + # Extract the first word of "pkg-config", so it can be a program name with args. +set dummy pkg-config; ac_word=$2 +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 +$as_echo_n "checking for $ac_word... " >&6; } +if test "${ac_cv_path_ac_pt_PKG_CONFIG+set}" = set; then : + $as_echo_n "(cached) " >&6 +else + case $ac_pt_PKG_CONFIG in + [\\/]* | ?:[\\/]*) + ac_cv_path_ac_pt_PKG_CONFIG="$ac_pt_PKG_CONFIG" # Let the user override the test with a path. + ;; + *) + as_save_IFS=$IFS; IFS=$PATH_SEPARATOR +for as_dir in $PATH +do + IFS=$as_save_IFS + test -z "$as_dir" && as_dir=. + for ac_exec_ext in '' $ac_executable_extensions; do + if { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_test_x "$as_dir/$ac_word$ac_exec_ext"; }; then + ac_cv_path_ac_pt_PKG_CONFIG="$as_dir/$ac_word$ac_exec_ext" + $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 + break 2 + fi +done + done +IFS=$as_save_IFS + + ;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_link") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest$ac_exeext && - $as_test_x conftest$ac_exeext; then - eval "$as_ac_var=yes" +fi +ac_pt_PKG_CONFIG=$ac_cv_path_ac_pt_PKG_CONFIG +if test -n "$ac_pt_PKG_CONFIG"; then + { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_pt_PKG_CONFIG" >&5 +$as_echo "$ac_pt_PKG_CONFIG" >&6; } else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - eval "$as_ac_var=no" + { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 +$as_echo "no" >&6; } fi -rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \ - conftest$ac_exeext conftest.$ac_ext -fi -ac_res=`eval echo '${'$as_ac_var'}'` - { echo "$as_me:$LINENO: result: $ac_res" >&5 -echo "${ECHO_T}$ac_res" >&6; } -if test `eval echo '${'$as_ac_var'}'` = yes; then - cat >>confdefs.h <<_ACEOF -#define `echo "HAVE_$ac_func" | $as_tr_cpp` 1 -_ACEOF - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -#include -int -main () -{ -getpgrp(0); - ; - return 0; -} -_ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; + if test "x$ac_pt_PKG_CONFIG" = x; then + PKG_CONFIG="" + else + case $cross_compiling:$ac_tool_warned in +yes:) +{ $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: using cross tools not prefixed with host triplet" >&5 +$as_echo "$as_me: WARNING: using cross tools not prefixed with host triplet" >&2;} +ac_tool_warned=yes ;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then + PKG_CONFIG=$ac_pt_PKG_CONFIG + fi +else + PKG_CONFIG="$ac_cv_path_PKG_CONFIG" +fi -cat >>confdefs.h <<\_ACEOF -#define GETPGRP_HAVE_ARG 1 -_ACEOF +# Check for use of the system expat library +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for --with-system-expat" >&5 +$as_echo_n "checking for --with-system-expat... " >&6; } -else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 +# Check whether --with-system_expat was given. +if test "${with_system_expat+set}" = set; then : + withval=$with_system_expat; +fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $with_system_expat" >&5 +$as_echo "$with_system_expat" >&6; } + +# Check for use of the system libffi library +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for --with-system-ffi" >&5 +$as_echo_n "checking for --with-system-ffi... " >&6; } + +# Check whether --with-system_ffi was given. +if test "${with_system_ffi+set}" = set; then : + withval=$with_system_ffi; fi -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext +if test "$with_system_ffi" = "yes" && test -n "$PKG_CONFIG"; then + LIBFFI_INCLUDEDIR="`"$PKG_CONFIG" libffi --cflags-only-I 2>/dev/null | sed -e 's/^-I//;s/ *$//'`" +else + LIBFFI_INCLUDEDIR="" fi -done -for ac_func in setpgrp -do -as_ac_var=`echo "ac_cv_func_$ac_func" | $as_tr_sh` -{ echo "$as_me:$LINENO: checking for $ac_func" >&5 -echo $ECHO_N "checking for $ac_func... $ECHO_C" >&6; } -if { as_var=$as_ac_var; eval "test \"\${$as_var+set}\" = set"; }; then - echo $ECHO_N "(cached) $ECHO_C" >&6 +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $with_system_ffi" >&5 +$as_echo "$with_system_ffi" >&6; } + +# Check for --with-dbmliborder +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for --with-dbmliborder" >&5 +$as_echo_n "checking for --with-dbmliborder... " >&6; } + +# Check whether --with-dbmliborder was given. +if test "${with_dbmliborder+set}" = set; then : + withval=$with_dbmliborder; +if test x$with_dbmliborder = xyes +then +as_fn_error "proper usage is --with-dbmliborder=db1:db2:..." "$LINENO" 5 else - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -/* Define $ac_func to an innocuous variant, in case declares $ac_func. - For example, HP-UX 11i declares gettimeofday. */ -#define $ac_func innocuous_$ac_func + for db in `echo $with_dbmliborder | sed 's/:/ /g'`; do + if test x$db != xndbm && test x$db != xgdbm && test x$db != xbdb + then + as_fn_error "proper usage is --with-dbmliborder=db1:db2:..." "$LINENO" 5 + fi + done +fi +fi -/* System header to define __stub macros and hopefully few prototypes, - which can conflict with char $ac_func (); below. - Prefer to if __STDC__ is defined, since - exists even on freestanding compilers. */ +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $with_dbmliborder" >&5 +$as_echo "$with_dbmliborder" >&6; } -#ifdef __STDC__ -# include -#else -# include -#endif +# Determine if signalmodule should be used. -#undef $ac_func -/* Override any GCC internal prototype to avoid an error. - Use char because int might match the return type of a GCC - builtin and then its argument prototype would still apply. */ -#ifdef __cplusplus -extern "C" -#endif -char $ac_func (); -/* The GNU C library defines this for functions which it implements - to always fail with ENOSYS. Some functions are actually named - something starting with __ and the normal name is an alias. */ -#if defined __stub_$ac_func || defined __stub___$ac_func -choke me -#endif +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for --with-signal-module" >&5 +$as_echo_n "checking for --with-signal-module... " >&6; } + +# Check whether --with-signal-module was given. +if test "${with_signal_module+set}" = set; then : + withval=$with_signal_module; +fi -int -main () -{ -return $ac_func (); - ; - return 0; -} -_ACEOF -rm -f conftest.$ac_objext conftest$ac_exeext -if { (ac_try="$ac_link" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_link") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest$ac_exeext && - $as_test_x conftest$ac_exeext; then - eval "$as_ac_var=yes" -else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - eval "$as_ac_var=no" +if test -z "$with_signal_module" +then with_signal_module="yes" fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $with_signal_module" >&5 +$as_echo "$with_signal_module" >&6; } -rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \ - conftest$ac_exeext conftest.$ac_ext +if test "${with_signal_module}" = "yes"; then + USE_SIGNAL_MODULE="" + SIGNAL_OBJS="" +else + USE_SIGNAL_MODULE="#" + SIGNAL_OBJS="Parser/intrcheck.o Python/sigcheck.o" fi -ac_res=`eval echo '${'$as_ac_var'}'` - { echo "$as_me:$LINENO: result: $ac_res" >&5 -echo "${ECHO_T}$ac_res" >&6; } -if test `eval echo '${'$as_ac_var'}'` = yes; then - cat >>confdefs.h <<_ACEOF -#define `echo "HAVE_$ac_func" | $as_tr_cpp` 1 -_ACEOF - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -#include -int -main () -{ -setpgrp(0,0); - ; - return 0; -} -_ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then -cat >>confdefs.h <<\_ACEOF -#define SETPGRP_HAVE_ARG 1 -_ACEOF +# This is used to generate Setup.config +USE_THREAD_MODULE="" -else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for --with-dec-threads" >&5 +$as_echo_n "checking for --with-dec-threads... " >&6; } +# Check whether --with-dec-threads was given. +if test "${with_dec_threads+set}" = set; then : + withval=$with_dec_threads; +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $withval" >&5 +$as_echo "$withval" >&6; } +LDLAST=-threads +if test "${with_thread+set}" != set; then + with_thread="$withval"; +fi +else + { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 +$as_echo "no" >&6; } fi -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext -fi -done +# Templates for things AC_DEFINEd more than once. +# For a single AC_DEFINE, no template is needed. -for ac_func in gettimeofday -do -as_ac_var=`echo "ac_cv_func_$ac_func" | $as_tr_sh` -{ echo "$as_me:$LINENO: checking for $ac_func" >&5 -echo $ECHO_N "checking for $ac_func... $ECHO_C" >&6; } -if { as_var=$as_ac_var; eval "test \"\${$as_var+set}\" = set"; }; then - echo $ECHO_N "(cached) $ECHO_C" >&6 -else - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -/* Define $ac_func to an innocuous variant, in case declares $ac_func. - For example, HP-UX 11i declares gettimeofday. */ -#define $ac_func innocuous_$ac_func -/* System header to define __stub macros and hopefully few prototypes, - which can conflict with char $ac_func (); below. - Prefer to if __STDC__ is defined, since - exists even on freestanding compilers. */ -#ifdef __STDC__ -# include -#else -# include -#endif +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for --with-threads" >&5 +$as_echo_n "checking for --with-threads... " >&6; } -#undef $ac_func +# Check whether --with-threads was given. +if test "${with_threads+set}" = set; then : + withval=$with_threads; +fi -/* Override any GCC internal prototype to avoid an error. - Use char because int might match the return type of a GCC - builtin and then its argument prototype would still apply. */ -#ifdef __cplusplus -extern "C" -#endif -char $ac_func (); -/* The GNU C library defines this for functions which it implements - to always fail with ENOSYS. Some functions are actually named - something starting with __ and the normal name is an alias. */ -#if defined __stub_$ac_func || defined __stub___$ac_func -choke me -#endif -int -main () -{ -return $ac_func (); - ; - return 0; -} -_ACEOF -rm -f conftest.$ac_objext conftest$ac_exeext -if { (ac_try="$ac_link" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_link") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest$ac_exeext && - $as_test_x conftest$ac_exeext; then - eval "$as_ac_var=yes" -else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 +# --with-thread is deprecated, but check for it anyway - eval "$as_ac_var=no" +# Check whether --with-thread was given. +if test "${with_thread+set}" = set; then : + withval=$with_thread; with_threads=$with_thread fi -rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \ - conftest$ac_exeext conftest.$ac_ext + +if test -z "$with_threads" +then with_threads="yes" fi -ac_res=`eval echo '${'$as_ac_var'}'` - { echo "$as_me:$LINENO: result: $ac_res" >&5 -echo "${ECHO_T}$ac_res" >&6; } -if test `eval echo '${'$as_ac_var'}'` = yes; then - cat >>confdefs.h <<_ACEOF -#define `echo "HAVE_$ac_func" | $as_tr_cpp` 1 -_ACEOF - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -#include -int -main () -{ -gettimeofday((struct timeval*)0,(struct timezone*)0); - ; - return 0; -} -_ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - : -else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $with_threads" >&5 +$as_echo "$with_threads" >&6; } -cat >>confdefs.h <<\_ACEOF -#define GETTIMEOFDAY_NO_TZ 1 -_ACEOF +if test "$with_threads" = "no" +then + USE_THREAD_MODULE="#" +elif test "$ac_cv_pthread_is_default" = yes +then + $as_echo "#define WITH_THREAD 1" >>confdefs.h + # Defining _REENTRANT on system with POSIX threads should not hurt. + $as_echo "#define _REENTRANT 1" >>confdefs.h -fi + posix_threads=yes + THREADOBJ="Python/thread.o" +elif test "$ac_cv_kpthread" = "yes" +then + CC="$CC -Kpthread" + if test "$ac_cv_cxx_thread" = "yes"; then + CXX="$CXX -Kpthread" + fi + $as_echo "#define WITH_THREAD 1" >>confdefs.h -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext + posix_threads=yes + THREADOBJ="Python/thread.o" +elif test "$ac_cv_kthread" = "yes" +then + CC="$CC -Kthread" + if test "$ac_cv_cxx_thread" = "yes"; then + CXX="$CXX -Kthread" + fi + $as_echo "#define WITH_THREAD 1" >>confdefs.h -fi -done + posix_threads=yes + THREADOBJ="Python/thread.o" +elif test "$ac_cv_pthread" = "yes" +then + CC="$CC -pthread" + if test "$ac_cv_cxx_thread" = "yes"; then + CXX="$CXX -pthread" + fi + $as_echo "#define WITH_THREAD 1" >>confdefs.h + posix_threads=yes + THREADOBJ="Python/thread.o" +else + if test ! -z "$with_threads" -a -d "$with_threads" + then LDFLAGS="$LDFLAGS -L$with_threads" + fi + if test ! -z "$withval" -a -d "$withval" + then LDFLAGS="$LDFLAGS -L$withval" + fi -{ echo "$as_me:$LINENO: checking for major" >&5 -echo $ECHO_N "checking for major... $ECHO_C" >&6; } -cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF + # According to the POSIX spec, a pthreads implementation must + # define _POSIX_THREADS in unistd.h. Some apparently don't + # (e.g. gnu pth with pthread emulation) + { $as_echo "$as_me:${as_lineno-$LINENO}: checking for _POSIX_THREADS in unistd.h" >&5 +$as_echo_n "checking for _POSIX_THREADS in unistd.h... " >&6; } + cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ -#if defined(MAJOR_IN_MKDEV) -#include -#elif defined(MAJOR_IN_SYSMACROS) -#include -#else -#include +#include +#ifdef _POSIX_THREADS +yes #endif -int -main () -{ +_ACEOF +if (eval "$ac_cpp conftest.$ac_ext") 2>&5 | + $EGREP "yes" >/dev/null 2>&1; then : + unistd_defines_pthreads=yes +else + unistd_defines_pthreads=no +fi +rm -f conftest* - makedev(major(0),minor(0)); + { $as_echo "$as_me:${as_lineno-$LINENO}: result: $unistd_defines_pthreads" >&5 +$as_echo "$unistd_defines_pthreads" >&6; } - ; - return 0; -} -_ACEOF -rm -f conftest.$ac_objext conftest$ac_exeext -if { (ac_try="$ac_link" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_link") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest$ac_exeext && - $as_test_x conftest$ac_exeext; then + $as_echo "#define _REENTRANT 1" >>confdefs.h + ac_fn_c_check_header_mongrel "$LINENO" "cthreads.h" "ac_cv_header_cthreads_h" "$ac_includes_default" +if test "x$ac_cv_header_cthreads_h" = x""yes; then : + $as_echo "#define WITH_THREAD 1" >>confdefs.h + + $as_echo "#define C_THREADS 1" >>confdefs.h -cat >>confdefs.h <<\_ACEOF -#define HAVE_DEVICE_MACROS 1 -_ACEOF - { echo "$as_me:$LINENO: result: yes" >&5 -echo "${ECHO_T}yes" >&6; } +$as_echo "#define HURD_C_THREADS 1" >>confdefs.h + LIBS="$LIBS -lthreads" + THREADOBJ="Python/thread.o" else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 + ac_fn_c_check_header_mongrel "$LINENO" "mach/cthreads.h" "ac_cv_header_mach_cthreads_h" "$ac_includes_default" +if test "x$ac_cv_header_mach_cthreads_h" = x""yes; then : + $as_echo "#define WITH_THREAD 1" >>confdefs.h - { echo "$as_me:$LINENO: result: no" >&5 -echo "${ECHO_T}no" >&6; } + $as_echo "#define C_THREADS 1" >>confdefs.h -fi -rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \ - conftest$ac_exeext conftest.$ac_ext +$as_echo "#define MACH_C_THREADS 1" >>confdefs.h -# On OSF/1 V5.1, getaddrinfo is available, but a define -# for [no]getaddrinfo in netdb.h. -{ echo "$as_me:$LINENO: checking for getaddrinfo" >&5 -echo $ECHO_N "checking for getaddrinfo... $ECHO_C" >&6; } -cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ + THREADOBJ="Python/thread.o" +else -#include -#include -#include -#include + # Just looking for pthread_create in libpthread is not enough: + # on HP/UX, pthread.h renames pthread_create to a different symbol name. + # So we really have to include pthread.h, and then link. + _libs=$LIBS + LIBS="$LIBS -lpthread" + { $as_echo "$as_me:${as_lineno-$LINENO}: checking for pthread_create in -lpthread" >&5 +$as_echo_n "checking for pthread_create in -lpthread... " >&6; } + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ +#include +void * start_routine (void *arg) { exit (0); } int main () { -getaddrinfo(NULL, NULL, NULL, NULL); + +pthread_create (NULL, NULL, start_routine, NULL) ; return 0; } _ACEOF -rm -f conftest.$ac_objext conftest$ac_exeext -if { (ac_try="$ac_link" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_link") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest$ac_exeext && - $as_test_x conftest$ac_exeext; then - have_getaddrinfo=yes +if ac_fn_c_try_link "$LINENO"; then : + + { $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +$as_echo "yes" >&6; } + $as_echo "#define WITH_THREAD 1" >>confdefs.h + + posix_threads=yes + THREADOBJ="Python/thread.o" else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - have_getaddrinfo=no -fi + LIBS=$_libs + ac_fn_c_check_func "$LINENO" "pthread_detach" "ac_cv_func_pthread_detach" +if test "x$ac_cv_func_pthread_detach" = x""yes; then : + $as_echo "#define WITH_THREAD 1" >>confdefs.h -rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \ - conftest$ac_exeext conftest.$ac_ext -{ echo "$as_me:$LINENO: result: $have_getaddrinfo" >&5 -echo "${ECHO_T}$have_getaddrinfo" >&6; } -if test $have_getaddrinfo = yes -then - { echo "$as_me:$LINENO: checking getaddrinfo bug" >&5 -echo $ECHO_N "checking getaddrinfo bug... $ECHO_C" >&6; } - if test "${ac_cv_buggy_getaddrinfo+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 + posix_threads=yes + THREADOBJ="Python/thread.o" else - if test "$cross_compiling" = yes; then - ac_cv_buggy_getaddrinfo=yes + + { $as_echo "$as_me:${as_lineno-$LINENO}: checking for pthread_create in -lpthreads" >&5 +$as_echo_n "checking for pthread_create in -lpthreads... " >&6; } +if test "${ac_cv_lib_pthreads_pthread_create+set}" = set; then : + $as_echo_n "(cached) " >&6 else - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF + ac_check_lib_save_LIBS=$LIBS +LIBS="-lpthreads $LIBS" +cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ -#include -#include -#include -#include -#include - -int main() +/* Override any GCC internal prototype to avoid an error. + Use char because int might match the return type of a GCC + builtin and then its argument prototype would still apply. */ +#ifdef __cplusplus +extern "C" +#endif +char pthread_create (); +int +main () { - int passive, gaierr, inet4 = 0, inet6 = 0; - struct addrinfo hints, *ai, *aitop; - char straddr[INET6_ADDRSTRLEN], strport[16]; - - for (passive = 0; passive <= 1; passive++) { - memset(&hints, 0, sizeof(hints)); - hints.ai_family = AF_UNSPEC; - hints.ai_flags = passive ? AI_PASSIVE : 0; - hints.ai_socktype = SOCK_STREAM; - hints.ai_protocol = IPPROTO_TCP; - if ((gaierr = getaddrinfo(NULL, "54321", &hints, &aitop)) != 0) { - (void)gai_strerror(gaierr); - goto bad; - } - for (ai = aitop; ai; ai = ai->ai_next) { - if (ai->ai_addr == NULL || - ai->ai_addrlen == 0 || - getnameinfo(ai->ai_addr, ai->ai_addrlen, - straddr, sizeof(straddr), strport, sizeof(strport), - NI_NUMERICHOST|NI_NUMERICSERV) != 0) { - goto bad; - } - switch (ai->ai_family) { - case AF_INET: - if (strcmp(strport, "54321") != 0) { - goto bad; - } - if (passive) { - if (strcmp(straddr, "0.0.0.0") != 0) { - goto bad; - } - } else { - if (strcmp(straddr, "127.0.0.1") != 0) { - goto bad; - } - } - inet4++; - break; - case AF_INET6: - if (strcmp(strport, "54321") != 0) { - goto bad; - } - if (passive) { - if (strcmp(straddr, "::") != 0) { - goto bad; - } - } else { - if (strcmp(straddr, "::1") != 0) { - goto bad; - } - } - inet6++; - break; - case AF_UNSPEC: - goto bad; - break; - default: - /* another family support? */ - break; - } - } - } - - if (!(inet4 == 0 || inet4 == 2)) - goto bad; - if (!(inet6 == 0 || inet6 == 2)) - goto bad; - - if (aitop) - freeaddrinfo(aitop); +return pthread_create (); + ; return 0; - - bad: - if (aitop) - freeaddrinfo(aitop); - return 1; } - _ACEOF -rm -f conftest$ac_exeext -if { (ac_try="$ac_link" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_link") 2>&5 - ac_status=$? - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { ac_try='./conftest$ac_exeext' - { (case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_try") 2>&5 - ac_status=$? - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); }; }; then - ac_cv_buggy_getaddrinfo=no +if ac_fn_c_try_link "$LINENO"; then : + ac_cv_lib_pthreads_pthread_create=yes else - echo "$as_me: program exited with status $ac_status" >&5 -echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - -( exit $ac_status ) -ac_cv_buggy_getaddrinfo=yes -fi -rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext conftest.$ac_objext conftest.$ac_ext -fi - - -fi - + ac_cv_lib_pthreads_pthread_create=no fi - -if test $have_getaddrinfo = no -o "$ac_cv_buggy_getaddrinfo" = yes -then - if test $ipv6 = yes - then - echo 'Fatal: You must get working getaddrinfo() function.' - echo ' or you can specify "--disable-ipv6"'. - exit 1 - fi -else - -cat >>confdefs.h <<\_ACEOF -#define HAVE_GETADDRINFO 1 -_ACEOF - +rm -f core conftest.err conftest.$ac_objext \ + conftest$ac_exeext conftest.$ac_ext +LIBS=$ac_check_lib_save_LIBS fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_lib_pthreads_pthread_create" >&5 +$as_echo "$ac_cv_lib_pthreads_pthread_create" >&6; } +if test "x$ac_cv_lib_pthreads_pthread_create" = x""yes; then : + $as_echo "#define WITH_THREAD 1" >>confdefs.h -for ac_func in getnameinfo -do -as_ac_var=`echo "ac_cv_func_$ac_func" | $as_tr_sh` -{ echo "$as_me:$LINENO: checking for $ac_func" >&5 -echo $ECHO_N "checking for $ac_func... $ECHO_C" >&6; } -if { as_var=$as_ac_var; eval "test \"\${$as_var+set}\" = set"; }; then - echo $ECHO_N "(cached) $ECHO_C" >&6 -else - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -/* Define $ac_func to an innocuous variant, in case declares $ac_func. - For example, HP-UX 11i declares gettimeofday. */ -#define $ac_func innocuous_$ac_func - -/* System header to define __stub macros and hopefully few prototypes, - which can conflict with char $ac_func (); below. - Prefer to if __STDC__ is defined, since - exists even on freestanding compilers. */ - -#ifdef __STDC__ -# include -#else -# include -#endif + posix_threads=yes + LIBS="$LIBS -lpthreads" + THREADOBJ="Python/thread.o" +else -#undef $ac_func + { $as_echo "$as_me:${as_lineno-$LINENO}: checking for pthread_create in -lc_r" >&5 +$as_echo_n "checking for pthread_create in -lc_r... " >&6; } +if test "${ac_cv_lib_c_r_pthread_create+set}" = set; then : + $as_echo_n "(cached) " >&6 +else + ac_check_lib_save_LIBS=$LIBS +LIBS="-lc_r $LIBS" +cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ /* Override any GCC internal prototype to avoid an error. Use char because int might match the return type of a GCC @@ -20826,4121 +8502,3569 @@ #ifdef __cplusplus extern "C" #endif -char $ac_func (); -/* The GNU C library defines this for functions which it implements - to always fail with ENOSYS. Some functions are actually named - something starting with __ and the normal name is an alias. */ -#if defined __stub_$ac_func || defined __stub___$ac_func -choke me -#endif - +char pthread_create (); int main () { -return $ac_func (); +return pthread_create (); ; return 0; } _ACEOF -rm -f conftest.$ac_objext conftest$ac_exeext -if { (ac_try="$ac_link" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_link") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest$ac_exeext && - $as_test_x conftest$ac_exeext; then - eval "$as_ac_var=yes" +if ac_fn_c_try_link "$LINENO"; then : + ac_cv_lib_c_r_pthread_create=yes else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - eval "$as_ac_var=no" -fi - -rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \ - conftest$ac_exeext conftest.$ac_ext + ac_cv_lib_c_r_pthread_create=no fi -ac_res=`eval echo '${'$as_ac_var'}'` - { echo "$as_me:$LINENO: result: $ac_res" >&5 -echo "${ECHO_T}$ac_res" >&6; } -if test `eval echo '${'$as_ac_var'}'` = yes; then - cat >>confdefs.h <<_ACEOF -#define `echo "HAVE_$ac_func" | $as_tr_cpp` 1 -_ACEOF - +rm -f core conftest.err conftest.$ac_objext \ + conftest$ac_exeext conftest.$ac_ext +LIBS=$ac_check_lib_save_LIBS fi -done +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_lib_c_r_pthread_create" >&5 +$as_echo "$ac_cv_lib_c_r_pthread_create" >&6; } +if test "x$ac_cv_lib_c_r_pthread_create" = x""yes; then : + $as_echo "#define WITH_THREAD 1" >>confdefs.h + posix_threads=yes + LIBS="$LIBS -lc_r" + THREADOBJ="Python/thread.o" +else -# checks for structures -{ echo "$as_me:$LINENO: checking whether time.h and sys/time.h may both be included" >&5 -echo $ECHO_N "checking whether time.h and sys/time.h may both be included... $ECHO_C" >&6; } -if test "${ac_cv_header_time+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 + { $as_echo "$as_me:${as_lineno-$LINENO}: checking for __pthread_create_system in -lpthread" >&5 +$as_echo_n "checking for __pthread_create_system in -lpthread... " >&6; } +if test "${ac_cv_lib_pthread___pthread_create_system+set}" = set; then : + $as_echo_n "(cached) " >&6 else - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF + ac_check_lib_save_LIBS=$LIBS +LIBS="-lpthread $LIBS" +cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ -#include -#include -#include +/* Override any GCC internal prototype to avoid an error. + Use char because int might match the return type of a GCC + builtin and then its argument prototype would still apply. */ +#ifdef __cplusplus +extern "C" +#endif +char __pthread_create_system (); int main () { -if ((struct tm *) 0) -return 0; +return __pthread_create_system (); ; return 0; } _ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - ac_cv_header_time=yes +if ac_fn_c_try_link "$LINENO"; then : + ac_cv_lib_pthread___pthread_create_system=yes else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - ac_cv_header_time=no + ac_cv_lib_pthread___pthread_create_system=no fi - -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext +rm -f core conftest.err conftest.$ac_objext \ + conftest$ac_exeext conftest.$ac_ext +LIBS=$ac_check_lib_save_LIBS fi -{ echo "$as_me:$LINENO: result: $ac_cv_header_time" >&5 -echo "${ECHO_T}$ac_cv_header_time" >&6; } -if test $ac_cv_header_time = yes; then +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_lib_pthread___pthread_create_system" >&5 +$as_echo "$ac_cv_lib_pthread___pthread_create_system" >&6; } +if test "x$ac_cv_lib_pthread___pthread_create_system" = x""yes; then : + $as_echo "#define WITH_THREAD 1" >>confdefs.h -cat >>confdefs.h <<\_ACEOF -#define TIME_WITH_SYS_TIME 1 -_ACEOF - -fi + posix_threads=yes + LIBS="$LIBS -lpthread" + THREADOBJ="Python/thread.o" +else -{ echo "$as_me:$LINENO: checking whether struct tm is in sys/time.h or time.h" >&5 -echo $ECHO_N "checking whether struct tm is in sys/time.h or time.h... $ECHO_C" >&6; } -if test "${ac_cv_struct_tm+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 + { $as_echo "$as_me:${as_lineno-$LINENO}: checking for pthread_create in -lcma" >&5 +$as_echo_n "checking for pthread_create in -lcma... " >&6; } +if test "${ac_cv_lib_cma_pthread_create+set}" = set; then : + $as_echo_n "(cached) " >&6 else - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF + ac_check_lib_save_LIBS=$LIBS +LIBS="-lcma $LIBS" +cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ -#include -#include +/* Override any GCC internal prototype to avoid an error. + Use char because int might match the return type of a GCC + builtin and then its argument prototype would still apply. */ +#ifdef __cplusplus +extern "C" +#endif +char pthread_create (); int main () { -struct tm tm; - int *p = &tm.tm_sec; - return !p; +return pthread_create (); ; return 0; } _ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - ac_cv_struct_tm=time.h +if ac_fn_c_try_link "$LINENO"; then : + ac_cv_lib_cma_pthread_create=yes +else + ac_cv_lib_cma_pthread_create=no +fi +rm -f core conftest.err conftest.$ac_objext \ + conftest$ac_exeext conftest.$ac_ext +LIBS=$ac_check_lib_save_LIBS +fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_lib_cma_pthread_create" >&5 +$as_echo "$ac_cv_lib_cma_pthread_create" >&6; } +if test "x$ac_cv_lib_cma_pthread_create" = x""yes; then : + $as_echo "#define WITH_THREAD 1" >>confdefs.h + + posix_threads=yes + LIBS="$LIBS -lcma" + THREADOBJ="Python/thread.o" else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - ac_cv_struct_tm=sys/time.h + USE_THREAD_MODULE="#" fi -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext + +fi + +fi + +fi + +fi + +fi +rm -f core conftest.err conftest.$ac_objext \ + conftest$ac_exeext conftest.$ac_ext fi -{ echo "$as_me:$LINENO: result: $ac_cv_struct_tm" >&5 -echo "${ECHO_T}$ac_cv_struct_tm" >&6; } -if test $ac_cv_struct_tm = sys/time.h; then -cat >>confdefs.h <<\_ACEOF -#define TM_IN_SYS_TIME 1 -_ACEOF fi -{ echo "$as_me:$LINENO: checking for struct tm.tm_zone" >&5 -echo $ECHO_N "checking for struct tm.tm_zone... $ECHO_C" >&6; } -if test "${ac_cv_member_struct_tm_tm_zone+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 + + + { $as_echo "$as_me:${as_lineno-$LINENO}: checking for usconfig in -lmpc" >&5 +$as_echo_n "checking for usconfig in -lmpc... " >&6; } +if test "${ac_cv_lib_mpc_usconfig+set}" = set; then : + $as_echo_n "(cached) " >&6 else - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF + ac_check_lib_save_LIBS=$LIBS +LIBS="-lmpc $LIBS" +cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ -#include -#include <$ac_cv_struct_tm> - +/* Override any GCC internal prototype to avoid an error. + Use char because int might match the return type of a GCC + builtin and then its argument prototype would still apply. */ +#ifdef __cplusplus +extern "C" +#endif +char usconfig (); int main () { -static struct tm ac_aggr; -if (ac_aggr.tm_zone) -return 0; +return usconfig (); ; return 0; } _ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - ac_cv_member_struct_tm_tm_zone=yes +if ac_fn_c_try_link "$LINENO"; then : + ac_cv_lib_mpc_usconfig=yes else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 + ac_cv_lib_mpc_usconfig=no +fi +rm -f core conftest.err conftest.$ac_objext \ + conftest$ac_exeext conftest.$ac_ext +LIBS=$ac_check_lib_save_LIBS +fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_lib_mpc_usconfig" >&5 +$as_echo "$ac_cv_lib_mpc_usconfig" >&6; } +if test "x$ac_cv_lib_mpc_usconfig" = x""yes; then : + $as_echo "#define WITH_THREAD 1" >>confdefs.h + + LIBS="$LIBS -lmpc" + THREADOBJ="Python/thread.o" + USE_THREAD_MODULE="" +fi - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -#include -#include <$ac_cv_struct_tm> + if test "$posix_threads" != "yes"; then + { $as_echo "$as_me:${as_lineno-$LINENO}: checking for thr_create in -lthread" >&5 +$as_echo_n "checking for thr_create in -lthread... " >&6; } +if test "${ac_cv_lib_thread_thr_create+set}" = set; then : + $as_echo_n "(cached) " >&6 +else + ac_check_lib_save_LIBS=$LIBS +LIBS="-lthread $LIBS" +cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ +/* Override any GCC internal prototype to avoid an error. + Use char because int might match the return type of a GCC + builtin and then its argument prototype would still apply. */ +#ifdef __cplusplus +extern "C" +#endif +char thr_create (); int main () { -static struct tm ac_aggr; -if (sizeof ac_aggr.tm_zone) -return 0; +return thr_create (); ; return 0; } _ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - ac_cv_member_struct_tm_tm_zone=yes +if ac_fn_c_try_link "$LINENO"; then : + ac_cv_lib_thread_thr_create=yes else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 + ac_cv_lib_thread_thr_create=no +fi +rm -f core conftest.err conftest.$ac_objext \ + conftest$ac_exeext conftest.$ac_ext +LIBS=$ac_check_lib_save_LIBS +fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_lib_thread_thr_create" >&5 +$as_echo "$ac_cv_lib_thread_thr_create" >&6; } +if test "x$ac_cv_lib_thread_thr_create" = x""yes; then : + $as_echo "#define WITH_THREAD 1" >>confdefs.h - ac_cv_member_struct_tm_tm_zone=no + LIBS="$LIBS -lthread" + THREADOBJ="Python/thread.o" + USE_THREAD_MODULE="" fi -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext + fi + + if test "$USE_THREAD_MODULE" != "#" + then + # If the above checks didn't disable threads, (at least) OSF1 + # needs this '-threads' argument during linking. + case $ac_sys_system in + OSF1) LDLAST=-threads;; + esac + fi fi -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext +if test "$posix_threads" = "yes"; then + if test "$unistd_defines_pthreads" = "no"; then + +$as_echo "#define _POSIX_THREADS 1" >>confdefs.h + + fi + + # Bug 662787: Using semaphores causes unexplicable hangs on Solaris 8. + case $ac_sys_system/$ac_sys_release in + SunOS/5.6) +$as_echo "#define HAVE_PTHREAD_DESTRUCTOR 1" >>confdefs.h + + ;; + SunOS/5.8) +$as_echo "#define HAVE_BROKEN_POSIX_SEMAPHORES 1" >>confdefs.h + + ;; + AIX/5) +$as_echo "#define HAVE_BROKEN_POSIX_SEMAPHORES 1" >>confdefs.h + + ;; + esac + + { $as_echo "$as_me:${as_lineno-$LINENO}: checking if PTHREAD_SCOPE_SYSTEM is supported" >&5 +$as_echo_n "checking if PTHREAD_SCOPE_SYSTEM is supported... " >&6; } + if test "${ac_cv_pthread_system_supported+set}" = set; then : + $as_echo_n "(cached) " >&6 +else + if test "$cross_compiling" = yes; then : + ac_cv_pthread_system_supported=no +else + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ +#include + void *foo(void *parm) { + return NULL; + } + main() { + pthread_attr_t attr; + pthread_t id; + if (pthread_attr_init(&attr)) exit(-1); + if (pthread_attr_setscope(&attr, PTHREAD_SCOPE_SYSTEM)) exit(-1); + if (pthread_create(&id, &attr, foo, NULL)) exit(-1); + exit(0); + } +_ACEOF +if ac_fn_c_try_run "$LINENO"; then : + ac_cv_pthread_system_supported=yes +else + ac_cv_pthread_system_supported=no +fi +rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext \ + conftest.$ac_objext conftest.beam conftest.$ac_ext fi -{ echo "$as_me:$LINENO: result: $ac_cv_member_struct_tm_tm_zone" >&5 -echo "${ECHO_T}$ac_cv_member_struct_tm_tm_zone" >&6; } -if test $ac_cv_member_struct_tm_tm_zone = yes; then -cat >>confdefs.h <<_ACEOF -#define HAVE_STRUCT_TM_TM_ZONE 1 + +fi + + { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_pthread_system_supported" >&5 +$as_echo "$ac_cv_pthread_system_supported" >&6; } + if test "$ac_cv_pthread_system_supported" = "yes"; then + +$as_echo "#define PTHREAD_SYSTEM_SCHED_SUPPORTED 1" >>confdefs.h + + fi + for ac_func in pthread_sigmask +do : + ac_fn_c_check_func "$LINENO" "pthread_sigmask" "ac_cv_func_pthread_sigmask" +if test "x$ac_cv_func_pthread_sigmask" = x""yes; then : + cat >>confdefs.h <<_ACEOF +#define HAVE_PTHREAD_SIGMASK 1 _ACEOF + case $ac_sys_system in + CYGWIN*) + +$as_echo "#define HAVE_BROKEN_PTHREAD_SIGMASK 1" >>confdefs.h + ;; + esac +fi +done fi -if test "$ac_cv_member_struct_tm_tm_zone" = yes; then -cat >>confdefs.h <<\_ACEOF -#define HAVE_TM_ZONE 1 -_ACEOF +# Check for enable-ipv6 + +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking if --enable-ipv6 is specified" >&5 +$as_echo_n "checking if --enable-ipv6 is specified... " >&6; } +# Check whether --enable-ipv6 was given. +if test "${enable_ipv6+set}" = set; then : + enableval=$enable_ipv6; case "$enableval" in + no) + { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 +$as_echo "no" >&6; } + ipv6=no + ;; + *) { $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +$as_echo "yes" >&6; } + $as_echo "#define ENABLE_IPV6 1" >>confdefs.h + ipv6=yes + ;; + esac else - { echo "$as_me:$LINENO: checking whether tzname is declared" >&5 -echo $ECHO_N "checking whether tzname is declared... $ECHO_C" >&6; } -if test "${ac_cv_have_decl_tzname+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 + + if test "$cross_compiling" = yes; then : + + { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 +$as_echo "no" >&6; } + ipv6=no + else - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF + cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ -#include - -int -main () + /* AF_INET6 available check */ +#include +#include +main() { -#ifndef tzname - (void) tzname; -#endif - - ; - return 0; + if (socket(AF_INET6, SOCK_STREAM, 0) < 0) + exit(1); + else + exit(0); } -_ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - ac_cv_have_decl_tzname=yes -else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - ac_cv_have_decl_tzname=no -fi - -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext -fi -{ echo "$as_me:$LINENO: result: $ac_cv_have_decl_tzname" >&5 -echo "${ECHO_T}$ac_cv_have_decl_tzname" >&6; } -if test $ac_cv_have_decl_tzname = yes; then -cat >>confdefs.h <<_ACEOF -#define HAVE_DECL_TZNAME 1 _ACEOF +if ac_fn_c_try_run "$LINENO"; then : + { $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +$as_echo "yes" >&6; } + ipv6=yes else - cat >>confdefs.h <<_ACEOF -#define HAVE_DECL_TZNAME 0 -_ACEOF + { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 +$as_echo "no" >&6; } + ipv6=no fi +rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext \ + conftest.$ac_objext conftest.beam conftest.$ac_ext +fi - { echo "$as_me:$LINENO: checking for tzname" >&5 -echo $ECHO_N "checking for tzname... $ECHO_C" >&6; } -if test "${ac_cv_var_tzname+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 -else - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF +if test "$ipv6" = "yes"; then + { $as_echo "$as_me:${as_lineno-$LINENO}: checking if RFC2553 API is available" >&5 +$as_echo_n "checking if RFC2553 API is available... " >&6; } + cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ -#include -#if !HAVE_DECL_TZNAME -extern char *tzname[]; -#endif + #include +#include int main () { -return tzname[0][0]; +struct sockaddr_in6 x; + x.sin6_scope_id; ; return 0; } + _ACEOF -rm -f conftest.$ac_objext conftest$ac_exeext -if { (ac_try="$ac_link" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_link") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest$ac_exeext && - $as_test_x conftest$ac_exeext; then - ac_cv_var_tzname=yes +if ac_fn_c_try_compile "$LINENO"; then : + + { $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +$as_echo "yes" >&6; } + ipv6=yes + else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - ac_cv_var_tzname=no -fi + { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 +$as_echo "no" >&6; } + ipv6=no -rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \ - conftest$ac_exeext conftest.$ac_ext fi -{ echo "$as_me:$LINENO: result: $ac_cv_var_tzname" >&5 -echo "${ECHO_T}$ac_cv_var_tzname" >&6; } - if test $ac_cv_var_tzname = yes; then +rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext +fi -cat >>confdefs.h <<\_ACEOF -#define HAVE_TZNAME 1 -_ACEOF +if test "$ipv6" = "yes"; then + $as_echo "#define ENABLE_IPV6 1" >>confdefs.h - fi fi -{ echo "$as_me:$LINENO: checking for struct stat.st_rdev" >&5 -echo $ECHO_N "checking for struct stat.st_rdev... $ECHO_C" >&6; } -if test "${ac_cv_member_struct_stat_st_rdev+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 -else - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF +fi + + +ipv6type=unknown +ipv6lib=none +ipv6trylibc=no + +if test "$ipv6" = "yes"; then + { $as_echo "$as_me:${as_lineno-$LINENO}: checking ipv6 stack type" >&5 +$as_echo_n "checking ipv6 stack type... " >&6; } + for i in inria kame linux-glibc linux-inet6 solaris toshiba v6d zeta; + do + case $i in + inria) + cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ -$ac_includes_default -int -main () -{ -static struct stat ac_aggr; -if (ac_aggr.st_rdev) -return 0; - ; - return 0; -} -_ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - ac_cv_member_struct_stat_st_rdev=yes -else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ +#include +#ifdef IPV6_INRIA_VERSION +yes +#endif _ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF +if (eval "$ac_cpp conftest.$ac_ext") 2>&5 | + $EGREP "yes" >/dev/null 2>&1; then : + ipv6type=$i +fi +rm -f conftest* + + ;; + kame) + cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ -$ac_includes_default -int -main () -{ -static struct stat ac_aggr; -if (sizeof ac_aggr.st_rdev) -return 0; - ; - return 0; -} -_ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - ac_cv_member_struct_stat_st_rdev=yes -else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - ac_cv_member_struct_stat_st_rdev=no +#include +#ifdef __KAME__ +yes +#endif +_ACEOF +if (eval "$ac_cpp conftest.$ac_ext") 2>&5 | + $EGREP "yes" >/dev/null 2>&1; then : + ipv6type=$i; + ipv6lib=inet6 + ipv6libdir=/usr/local/v6/lib + ipv6trylibc=yes fi +rm -f conftest* -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext -fi + ;; + linux-glibc) + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext +#include +#if defined(__GLIBC__) && ((__GLIBC__ == 2 && __GLIBC_MINOR__ >= 1) || (__GLIBC__ > 2)) +yes +#endif +_ACEOF +if (eval "$ac_cpp conftest.$ac_ext") 2>&5 | + $EGREP "yes" >/dev/null 2>&1; then : + ipv6type=$i; + ipv6trylibc=yes fi -{ echo "$as_me:$LINENO: result: $ac_cv_member_struct_stat_st_rdev" >&5 -echo "${ECHO_T}$ac_cv_member_struct_stat_st_rdev" >&6; } -if test $ac_cv_member_struct_stat_st_rdev = yes; then +rm -f conftest* -cat >>confdefs.h <<_ACEOF -#define HAVE_STRUCT_STAT_ST_RDEV 1 + ;; + linux-inet6) + if test -d /usr/inet6; then + ipv6type=$i + ipv6lib=inet6 + ipv6libdir=/usr/inet6/lib + BASECFLAGS="-I/usr/inet6/include $BASECFLAGS" + fi + ;; + solaris) + if test -f /etc/netconfig; then + if /usr/xpg4/bin/grep -q tcp6 /etc/netconfig; then + ipv6type=$i + ipv6trylibc=yes + fi + fi + ;; + toshiba) + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + +#include +#ifdef _TOSHIBA_INET6 +yes +#endif _ACEOF +if (eval "$ac_cpp conftest.$ac_ext") 2>&5 | + $EGREP "yes" >/dev/null 2>&1; then : + ipv6type=$i; + ipv6lib=inet6; + ipv6libdir=/usr/local/v6/lib +fi +rm -f conftest* + ;; + v6d) + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ +#include +#ifdef __V6D__ +yes +#endif +_ACEOF +if (eval "$ac_cpp conftest.$ac_ext") 2>&5 | + $EGREP "yes" >/dev/null 2>&1; then : + ipv6type=$i; + ipv6lib=v6; + ipv6libdir=/usr/local/v6/lib; + BASECFLAGS="-I/usr/local/v6/include $BASECFLAGS" fi +rm -f conftest* -{ echo "$as_me:$LINENO: checking for struct stat.st_blksize" >&5 -echo $ECHO_N "checking for struct stat.st_blksize... $ECHO_C" >&6; } -if test "${ac_cv_member_struct_stat_st_blksize+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 -else - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF + ;; + zeta) + cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ -$ac_includes_default -int -main () -{ -static struct stat ac_aggr; -if (ac_aggr.st_blksize) -return 0; - ; - return 0; -} + +#include +#ifdef _ZETA_MINAMI_INET6 +yes +#endif _ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - ac_cv_member_struct_stat_st_blksize=yes -else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 +if (eval "$ac_cpp conftest.$ac_ext") 2>&5 | + $EGREP "yes" >/dev/null 2>&1; then : + ipv6type=$i; + ipv6lib=inet6; + ipv6libdir=/usr/local/v6/lib +fi +rm -f conftest* + + ;; + esac + if test "$ipv6type" != "unknown"; then + break + fi + done + { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ipv6type" >&5 +$as_echo "$ipv6type" >&6; } +fi + +if test "$ipv6" = "yes" -a "$ipv6lib" != "none"; then + if test -d $ipv6libdir -a -f $ipv6libdir/lib$ipv6lib.a; then + LIBS="-L$ipv6libdir -l$ipv6lib $LIBS" + echo "using lib$ipv6lib" + else + if test $ipv6trylibc = "yes"; then + echo "using libc" + else + echo 'Fatal: no $ipv6lib library found. cannot continue.' + echo "You need to fetch lib$ipv6lib.a from appropriate" + echo 'ipv6 kit and compile beforehand.' + exit 1 + fi + fi +fi - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for OSX 10.5 SDK or later" >&5 +$as_echo_n "checking for OSX 10.5 SDK or later... " >&6; } +cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ -$ac_includes_default + + #include int main () { -static struct stat ac_aggr; -if (sizeof ac_aggr.st_blksize) -return 0; +FSIORefNum fRef = 0 ; return 0; } + _ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - ac_cv_member_struct_stat_st_blksize=yes +if ac_fn_c_try_compile "$LINENO"; then : + + +$as_echo "#define HAVE_OSX105_SDK 1" >>confdefs.h + + { $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +$as_echo "yes" >&6; } + else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - ac_cv_member_struct_stat_st_blksize=no -fi + { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 +$as_echo "no" >&6; } -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext fi - rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext + +# Check for --with-doc-strings +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for --with-doc-strings" >&5 +$as_echo_n "checking for --with-doc-strings... " >&6; } + +# Check whether --with-doc-strings was given. +if test "${with_doc_strings+set}" = set; then : + withval=$with_doc_strings; fi -{ echo "$as_me:$LINENO: result: $ac_cv_member_struct_stat_st_blksize" >&5 -echo "${ECHO_T}$ac_cv_member_struct_stat_st_blksize" >&6; } -if test $ac_cv_member_struct_stat_st_blksize = yes; then -cat >>confdefs.h <<_ACEOF -#define HAVE_STRUCT_STAT_ST_BLKSIZE 1 -_ACEOF +if test -z "$with_doc_strings" +then with_doc_strings="yes" +fi +if test "$with_doc_strings" != "no" +then + +$as_echo "#define WITH_DOC_STRINGS 1" >>confdefs.h fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $with_doc_strings" >&5 +$as_echo "$with_doc_strings" >&6; } + +# Check for Python-specific malloc support +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for --with-tsc" >&5 +$as_echo_n "checking for --with-tsc... " >&6; } + +# Check whether --with-tsc was given. +if test "${with_tsc+set}" = set; then : + withval=$with_tsc; +if test "$withval" != no +then -{ echo "$as_me:$LINENO: checking for struct stat.st_flags" >&5 -echo $ECHO_N "checking for struct stat.st_flags... $ECHO_C" >&6; } -if test "${ac_cv_member_struct_stat_st_flags+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 +$as_echo "#define WITH_TSC 1" >>confdefs.h + + { $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +$as_echo "yes" >&6; } +else { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 +$as_echo "no" >&6; } +fi else - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -$ac_includes_default -int -main () -{ -static struct stat ac_aggr; -if (ac_aggr.st_flags) -return 0; - ; - return 0; -} -_ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - ac_cv_member_struct_stat_st_flags=yes + { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 +$as_echo "no" >&6; } +fi + + +# Check for Python-specific malloc support +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for --with-pymalloc" >&5 +$as_echo_n "checking for --with-pymalloc... " >&6; } + +# Check whether --with-pymalloc was given. +if test "${with_pymalloc+set}" = set; then : + withval=$with_pymalloc; +fi + + +if test -z "$with_pymalloc" +then with_pymalloc="yes" +fi +if test "$with_pymalloc" != "no" +then + +$as_echo "#define WITH_PYMALLOC 1" >>confdefs.h + +fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $with_pymalloc" >&5 +$as_echo "$with_pymalloc" >&6; } + +# Check for Valgrind support +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for --with-valgrind" >&5 +$as_echo_n "checking for --with-valgrind... " >&6; } + +# Check whether --with-valgrind was given. +if test "${with_valgrind+set}" = set; then : + withval=$with_valgrind; else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 + with_valgrind=no +fi + +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $with_valgrind" >&5 +$as_echo "$with_valgrind" >&6; } +if test "$with_valgrind" != no; then + ac_fn_c_check_header_mongrel "$LINENO" "valgrind/valgrind.h" "ac_cv_header_valgrind_valgrind_h" "$ac_includes_default" +if test "x$ac_cv_header_valgrind_valgrind_h" = x""yes; then : + +$as_echo "#define WITH_VALGRIND 1" >>confdefs.h - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -$ac_includes_default -int -main () -{ -static struct stat ac_aggr; -if (sizeof ac_aggr.st_flags) -return 0; - ; - return 0; -} -_ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - ac_cv_member_struct_stat_st_flags=yes else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 + as_fn_error "Valgrind support requested but headers not available" "$LINENO" 5 - ac_cv_member_struct_stat_st_flags=no fi -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext + + OPT="-DDYNAMIC_ANNOTATIONS_ENABLED=1 $OPT" fi -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext +# Check for --with-wctype-functions +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for --with-wctype-functions" >&5 +$as_echo_n "checking for --with-wctype-functions... " >&6; } + +# Check whether --with-wctype-functions was given. +if test "${with_wctype_functions+set}" = set; then : + withval=$with_wctype_functions; +if test "$withval" != no +then + +$as_echo "#define WANT_WCTYPE_FUNCTIONS 1" >>confdefs.h + + { $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +$as_echo "yes" >&6; } +else { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 +$as_echo "no" >&6; } +fi +else + { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 +$as_echo "no" >&6; } fi -{ echo "$as_me:$LINENO: result: $ac_cv_member_struct_stat_st_flags" >&5 -echo "${ECHO_T}$ac_cv_member_struct_stat_st_flags" >&6; } -if test $ac_cv_member_struct_stat_st_flags = yes; then -cat >>confdefs.h <<_ACEOF -#define HAVE_STRUCT_STAT_ST_FLAGS 1 + +# -I${DLINCLDIR} is added to the compile rule for importdl.o + +DLINCLDIR=. + +# the dlopen() function means we might want to use dynload_shlib.o. some +# platforms, such as AIX, have dlopen(), but don't want to use it. +for ac_func in dlopen +do : + ac_fn_c_check_func "$LINENO" "dlopen" "ac_cv_func_dlopen" +if test "x$ac_cv_func_dlopen" = x""yes; then : + cat >>confdefs.h <<_ACEOF +#define HAVE_DLOPEN 1 _ACEOF +fi +done + + +# DYNLOADFILE specifies which dynload_*.o file we will use for dynamic +# loading of modules. + +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking DYNLOADFILE" >&5 +$as_echo_n "checking DYNLOADFILE... " >&6; } +if test -z "$DYNLOADFILE" +then + case $ac_sys_system/$ac_sys_release in + AIX*) # Use dynload_shlib.c and dlopen() if we have it; otherwise dynload_aix.c + if test "$ac_cv_func_dlopen" = yes + then DYNLOADFILE="dynload_shlib.o" + else DYNLOADFILE="dynload_aix.o" + fi + ;; + hp*|HP*) DYNLOADFILE="dynload_hpux.o";; + # Use dynload_next.c only on 10.2 and below, which don't have native dlopen() + Darwin/[0156]\..*) DYNLOADFILE="dynload_next.o";; + *) + # use dynload_shlib.c and dlopen() if we have it; otherwise stub + # out any dynamic loading + if test "$ac_cv_func_dlopen" = yes + then DYNLOADFILE="dynload_shlib.o" + else DYNLOADFILE="dynload_stub.o" + fi + ;; + esac +fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $DYNLOADFILE" >&5 +$as_echo "$DYNLOADFILE" >&6; } +if test "$DYNLOADFILE" != "dynload_stub.o" +then + +$as_echo "#define HAVE_DYNAMIC_LOADING 1" >>confdefs.h fi -{ echo "$as_me:$LINENO: checking for struct stat.st_gen" >&5 -echo $ECHO_N "checking for struct stat.st_gen... $ECHO_C" >&6; } -if test "${ac_cv_member_struct_stat_st_gen+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 +# MACHDEP_OBJS can be set to platform-specific object files needed by Python + + +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking MACHDEP_OBJS" >&5 +$as_echo_n "checking MACHDEP_OBJS... " >&6; } +if test -z "$MACHDEP_OBJS" +then + MACHDEP_OBJS=$extra_machdep_objs else - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ + MACHDEP_OBJS="$MACHDEP_OBJS $extra_machdep_objs" +fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: MACHDEP_OBJS" >&5 +$as_echo "MACHDEP_OBJS" >&6; } + +# checks for library functions +for ac_func in alarm setitimer getitimer bind_textdomain_codeset chown \ + clock confstr ctermid execv fchmod fchown fork fpathconf ftime ftruncate \ + gai_strerror getgroups getlogin getloadavg getpeername getpgid getpid \ + getpriority getresuid getresgid getpwent getspnam getspent getsid getwd \ + initgroups kill killpg lchmod lchown lstat mbrtowc mkfifo mknod mktime \ + mremap nice pathconf pause plock poll pthread_init \ + putenv readlink realpath \ + select sem_open sem_timedwait sem_getvalue sem_unlink setegid seteuid \ + setgid \ + setlocale setregid setreuid setresuid setresgid setsid setpgid setpgrp setuid setvbuf \ + sigaction siginterrupt sigrelse snprintf strftime strlcpy \ + sysconf tcgetpgrp tcsetpgrp tempnam timegm times tmpfile tmpnam tmpnam_r \ + truncate uname unsetenv utimes waitpid wait3 wait4 \ + wcscoll wcsftime wcsxfrm _getpty +do : + as_ac_var=`$as_echo "ac_cv_func_$ac_func" | $as_tr_sh` +ac_fn_c_check_func "$LINENO" "$ac_func" "$as_ac_var" +eval as_val=\$$as_ac_var + if test "x$as_val" = x""yes; then : + cat >>confdefs.h <<_ACEOF +#define `$as_echo "HAVE_$ac_func" | $as_tr_cpp` 1 _ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF + +fi +done + + +# For some functions, having a definition is not sufficient, since +# we want to take their address. +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for chroot" >&5 +$as_echo_n "checking for chroot... " >&6; } +cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ -$ac_includes_default +#include int main () { -static struct stat ac_aggr; -if (ac_aggr.st_gen) -return 0; +void *x=chroot ; return 0; } _ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - ac_cv_member_struct_stat_st_gen=yes +if ac_fn_c_try_compile "$LINENO"; then : + +$as_echo "#define HAVE_CHROOT 1" >>confdefs.h + + { $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +$as_echo "yes" >&6; } else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 + { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 +$as_echo "no" >&6; } - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF +fi +rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for link" >&5 +$as_echo_n "checking for link... " >&6; } +cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ -$ac_includes_default +#include int main () { -static struct stat ac_aggr; -if (sizeof ac_aggr.st_gen) -return 0; +void *x=link ; return 0; } _ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - ac_cv_member_struct_stat_st_gen=yes -else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 +if ac_fn_c_try_compile "$LINENO"; then : - ac_cv_member_struct_stat_st_gen=no -fi - -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext -fi - -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext -fi -{ echo "$as_me:$LINENO: result: $ac_cv_member_struct_stat_st_gen" >&5 -echo "${ECHO_T}$ac_cv_member_struct_stat_st_gen" >&6; } -if test $ac_cv_member_struct_stat_st_gen = yes; then - -cat >>confdefs.h <<_ACEOF -#define HAVE_STRUCT_STAT_ST_GEN 1 -_ACEOF +$as_echo "#define HAVE_LINK 1" >>confdefs.h + { $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +$as_echo "yes" >&6; } +else + { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 +$as_echo "no" >&6; } fi - -{ echo "$as_me:$LINENO: checking for struct stat.st_birthtime" >&5 -echo $ECHO_N "checking for struct stat.st_birthtime... $ECHO_C" >&6; } -if test "${ac_cv_member_struct_stat_st_birthtime+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 -else - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF +rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for symlink" >&5 +$as_echo_n "checking for symlink... " >&6; } +cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ -$ac_includes_default +#include int main () { -static struct stat ac_aggr; -if (ac_aggr.st_birthtime) -return 0; +void *x=symlink ; return 0; } _ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - ac_cv_member_struct_stat_st_birthtime=yes +if ac_fn_c_try_compile "$LINENO"; then : + +$as_echo "#define HAVE_SYMLINK 1" >>confdefs.h + + { $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +$as_echo "yes" >&6; } else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 + { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 +$as_echo "no" >&6; } - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF +fi +rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for fchdir" >&5 +$as_echo_n "checking for fchdir... " >&6; } +cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ -$ac_includes_default +#include int main () { -static struct stat ac_aggr; -if (sizeof ac_aggr.st_birthtime) -return 0; +void *x=fchdir ; return 0; } _ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - ac_cv_member_struct_stat_st_birthtime=yes -else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 +if ac_fn_c_try_compile "$LINENO"; then : - ac_cv_member_struct_stat_st_birthtime=no -fi +$as_echo "#define HAVE_FCHDIR 1" >>confdefs.h -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext -fi + { $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +$as_echo "yes" >&6; } +else + { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 +$as_echo "no" >&6; } -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext fi -{ echo "$as_me:$LINENO: result: $ac_cv_member_struct_stat_st_birthtime" >&5 -echo "${ECHO_T}$ac_cv_member_struct_stat_st_birthtime" >&6; } -if test $ac_cv_member_struct_stat_st_birthtime = yes; then - -cat >>confdefs.h <<_ACEOF -#define HAVE_STRUCT_STAT_ST_BIRTHTIME 1 +rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for fsync" >&5 +$as_echo_n "checking for fsync... " >&6; } +cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ +#include +int +main () +{ +void *x=fsync + ; + return 0; +} _ACEOF +if ac_fn_c_try_compile "$LINENO"; then : +$as_echo "#define HAVE_FSYNC 1" >>confdefs.h -fi - -{ echo "$as_me:$LINENO: checking for struct stat.st_blocks" >&5 -echo $ECHO_N "checking for struct stat.st_blocks... $ECHO_C" >&6; } -if test "${ac_cv_member_struct_stat_st_blocks+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 + { $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +$as_echo "yes" >&6; } else - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF + { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 +$as_echo "no" >&6; } + +fi +rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for fdatasync" >&5 +$as_echo_n "checking for fdatasync... " >&6; } +cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ -$ac_includes_default +#include int main () { -static struct stat ac_aggr; -if (ac_aggr.st_blocks) -return 0; +void *x=fdatasync ; return 0; } _ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - ac_cv_member_struct_stat_st_blocks=yes +if ac_fn_c_try_compile "$LINENO"; then : + +$as_echo "#define HAVE_FDATASYNC 1" >>confdefs.h + + { $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +$as_echo "yes" >&6; } else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 + { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 +$as_echo "no" >&6; } - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF +fi +rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for epoll" >&5 +$as_echo_n "checking for epoll... " >&6; } +cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ -$ac_includes_default +#include int main () { -static struct stat ac_aggr; -if (sizeof ac_aggr.st_blocks) -return 0; +void *x=epoll_create ; return 0; } _ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - ac_cv_member_struct_stat_st_blocks=yes +if ac_fn_c_try_compile "$LINENO"; then : + +$as_echo "#define HAVE_EPOLL 1" >>confdefs.h + + { $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +$as_echo "yes" >&6; } else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 + { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 +$as_echo "no" >&6; } - ac_cv_member_struct_stat_st_blocks=no fi - rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext -fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for kqueue" >&5 +$as_echo_n "checking for kqueue... " >&6; } +cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext -fi -{ echo "$as_me:$LINENO: result: $ac_cv_member_struct_stat_st_blocks" >&5 -echo "${ECHO_T}$ac_cv_member_struct_stat_st_blocks" >&6; } -if test $ac_cv_member_struct_stat_st_blocks = yes; then +#include +#include -cat >>confdefs.h <<_ACEOF -#define HAVE_STRUCT_STAT_ST_BLOCKS 1 +int +main () +{ +int x=kqueue() + ; + return 0; +} _ACEOF +if ac_fn_c_try_compile "$LINENO"; then : +$as_echo "#define HAVE_KQUEUE 1" >>confdefs.h -cat >>confdefs.h <<\_ACEOF -#define HAVE_ST_BLOCKS 1 -_ACEOF - + { $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +$as_echo "yes" >&6; } else - case " $LIBOBJS " in - *" fileblocks.$ac_objext "* ) ;; - *) LIBOBJS="$LIBOBJS fileblocks.$ac_objext" - ;; -esac + { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 +$as_echo "no" >&6; } fi +rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext +# On some systems (eg. FreeBSD 5), we would find a definition of the +# functions ctermid_r, setgroups in the library, but no prototype +# (e.g. because we use _XOPEN_SOURCE). See whether we can take their +# address to avoid compiler warnings and potential miscompilations +# because of the missing prototypes. +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for ctermid_r" >&5 +$as_echo_n "checking for ctermid_r... " >&6; } +cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ +#include "confdefs.h" +#include -{ echo "$as_me:$LINENO: checking for time.h that defines altzone" >&5 -echo $ECHO_N "checking for time.h that defines altzone... $ECHO_C" >&6; } -if test "${ac_cv_header_time_altzone+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 -else - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -#include int main () { -return altzone; +void* p = ctermid_r ; return 0; } _ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - ac_cv_header_time_altzone=yes +if ac_fn_c_try_compile "$LINENO"; then : + +$as_echo "#define HAVE_CTERMID_R 1" >>confdefs.h + + { $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +$as_echo "yes" >&6; } else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 + { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 +$as_echo "no" >&6; } - ac_cv_header_time_altzone=no fi - rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext -fi -{ echo "$as_me:$LINENO: result: $ac_cv_header_time_altzone" >&5 -echo "${ECHO_T}$ac_cv_header_time_altzone" >&6; } -if test $ac_cv_header_time_altzone = yes; then +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for flock" >&5 +$as_echo_n "checking for flock... " >&6; } +cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + +#include "confdefs.h" +#include -cat >>confdefs.h <<\_ACEOF -#define HAVE_ALTZONE 1 +int +main () +{ +void* p = flock + ; + return 0; +} _ACEOF +if ac_fn_c_try_compile "$LINENO"; then : + +$as_echo "#define HAVE_FLOCK 1" >>confdefs.h + + { $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +$as_echo "yes" >&6; } +else + { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 +$as_echo "no" >&6; } fi +rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext -was_it_defined=no -{ echo "$as_me:$LINENO: checking whether sys/select.h and sys/time.h may both be included" >&5 -echo $ECHO_N "checking whether sys/select.h and sys/time.h may both be included... $ECHO_C" >&6; } -cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for getpagesize" >&5 +$as_echo_n "checking for getpagesize... " >&6; } +cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ -#include -#include -#include +#include "confdefs.h" +#include int main () { -; +void* p = getpagesize ; return 0; } _ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then +if ac_fn_c_try_compile "$LINENO"; then : +$as_echo "#define HAVE_GETPAGESIZE 1" >>confdefs.h -cat >>confdefs.h <<\_ACEOF -#define SYS_SELECT_WITH_SYS_TIME 1 -_ACEOF + { $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +$as_echo "yes" >&6; } +else + { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 +$as_echo "no" >&6; } - was_it_defined=yes +fi +rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext +for ac_prog in true +do + # Extract the first word of "$ac_prog", so it can be a program name with args. +set dummy $ac_prog; ac_word=$2 +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 +$as_echo_n "checking for $ac_word... " >&6; } +if test "${ac_cv_prog_TRUE+set}" = set; then : + $as_echo_n "(cached) " >&6 else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - + if test -n "$TRUE"; then + ac_cv_prog_TRUE="$TRUE" # Let the user override the test. +else +as_save_IFS=$IFS; IFS=$PATH_SEPARATOR +for as_dir in $PATH +do + IFS=$as_save_IFS + test -z "$as_dir" && as_dir=. + for ac_exec_ext in '' $ac_executable_extensions; do + if { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_test_x "$as_dir/$ac_word$ac_exec_ext"; }; then + ac_cv_prog_TRUE="$ac_prog" + $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 + break 2 + fi +done + done +IFS=$as_save_IFS fi +fi +TRUE=$ac_cv_prog_TRUE +if test -n "$TRUE"; then + { $as_echo "$as_me:${as_lineno-$LINENO}: result: $TRUE" >&5 +$as_echo "$TRUE" >&6; } +else + { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 +$as_echo "no" >&6; } +fi -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext -{ echo "$as_me:$LINENO: result: $was_it_defined" >&5 -echo "${ECHO_T}$was_it_defined" >&6; } -{ echo "$as_me:$LINENO: checking for addrinfo" >&5 -echo $ECHO_N "checking for addrinfo... $ECHO_C" >&6; } -if test "${ac_cv_struct_addrinfo+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 + test -n "$TRUE" && break +done +test -n "$TRUE" || TRUE="/bin/true" + + +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for inet_aton in -lc" >&5 +$as_echo_n "checking for inet_aton in -lc... " >&6; } +if test "${ac_cv_lib_c_inet_aton+set}" = set; then : + $as_echo_n "(cached) " >&6 else - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ + ac_check_lib_save_LIBS=$LIBS +LIBS="-lc $LIBS" +cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + +/* Override any GCC internal prototype to avoid an error. + Use char because int might match the return type of a GCC + builtin and then its argument prototype would still apply. */ +#ifdef __cplusplus +extern "C" +#endif +char inet_aton (); +int +main () +{ +return inet_aton (); + ; + return 0; +} _ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF +if ac_fn_c_try_link "$LINENO"; then : + ac_cv_lib_c_inet_aton=yes +else + ac_cv_lib_c_inet_aton=no +fi +rm -f core conftest.err conftest.$ac_objext \ + conftest$ac_exeext conftest.$ac_ext +LIBS=$ac_check_lib_save_LIBS +fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_lib_c_inet_aton" >&5 +$as_echo "$ac_cv_lib_c_inet_aton" >&6; } +if test "x$ac_cv_lib_c_inet_aton" = x""yes; then : + $ac_cv_prog_TRUE +else + { $as_echo "$as_me:${as_lineno-$LINENO}: checking for inet_aton in -lresolv" >&5 +$as_echo_n "checking for inet_aton in -lresolv... " >&6; } +if test "${ac_cv_lib_resolv_inet_aton+set}" = set; then : + $as_echo_n "(cached) " >&6 +else + ac_check_lib_save_LIBS=$LIBS +LIBS="-lresolv $LIBS" +cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ -# include +/* Override any GCC internal prototype to avoid an error. + Use char because int might match the return type of a GCC + builtin and then its argument prototype would still apply. */ +#ifdef __cplusplus +extern "C" +#endif +char inet_aton (); int main () { -struct addrinfo a +return inet_aton (); ; return 0; } _ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - ac_cv_struct_addrinfo=yes +if ac_fn_c_try_link "$LINENO"; then : + ac_cv_lib_resolv_inet_aton=yes else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 + ac_cv_lib_resolv_inet_aton=no +fi +rm -f core conftest.err conftest.$ac_objext \ + conftest$ac_exeext conftest.$ac_ext +LIBS=$ac_check_lib_save_LIBS +fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_lib_resolv_inet_aton" >&5 +$as_echo "$ac_cv_lib_resolv_inet_aton" >&6; } +if test "x$ac_cv_lib_resolv_inet_aton" = x""yes; then : + cat >>confdefs.h <<_ACEOF +#define HAVE_LIBRESOLV 1 +_ACEOF - ac_cv_struct_addrinfo=no -fi + LIBS="-lresolv $LIBS" -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext fi -{ echo "$as_me:$LINENO: result: $ac_cv_struct_addrinfo" >&5 -echo "${ECHO_T}$ac_cv_struct_addrinfo" >&6; } -if test $ac_cv_struct_addrinfo = yes; then - -cat >>confdefs.h <<\_ACEOF -#define HAVE_ADDRINFO 1 -_ACEOF fi -{ echo "$as_me:$LINENO: checking for sockaddr_storage" >&5 -echo $ECHO_N "checking for sockaddr_storage... $ECHO_C" >&6; } -if test "${ac_cv_struct_sockaddr_storage+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 + +# On Tru64, chflags seems to be present, but calling it will +# exit Python +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for chflags" >&5 +$as_echo_n "checking for chflags... " >&6; } +if test "${ac_cv_have_chflags+set}" = set; then : + $as_echo_n "(cached) " >&6 else - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF + if test "$cross_compiling" = yes; then : + ac_cv_have_chflags=cross +else + cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ - -# include -# include -int -main () +[ +#include +#include +int main(int argc, char*argv[]) { -struct sockaddr_storage s - ; + if(chflags(argv[0], 0) != 0) + return 1; return 0; } +] _ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - ac_cv_struct_sockaddr_storage=yes +if ac_fn_c_try_run "$LINENO"; then : + ac_cv_have_chflags=yes else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - ac_cv_struct_sockaddr_storage=no + ac_cv_have_chflags=no fi - -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext +rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext \ + conftest.$ac_objext conftest.beam conftest.$ac_ext fi -{ echo "$as_me:$LINENO: result: $ac_cv_struct_sockaddr_storage" >&5 -echo "${ECHO_T}$ac_cv_struct_sockaddr_storage" >&6; } -if test $ac_cv_struct_sockaddr_storage = yes; then -cat >>confdefs.h <<\_ACEOF -#define HAVE_SOCKADDR_STORAGE 1 -_ACEOF +fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_have_chflags" >&5 +$as_echo "$ac_cv_have_chflags" >&6; } +if test "$ac_cv_have_chflags" = cross ; then + ac_fn_c_check_func "$LINENO" "chflags" "ac_cv_func_chflags" +if test "x$ac_cv_func_chflags" = x""yes; then : + ac_cv_have_chflags="yes" +else + ac_cv_have_chflags="no" +fi fi +if test "$ac_cv_have_chflags" = yes ; then -# checks for compiler characteristics +$as_echo "#define HAVE_CHFLAGS 1" >>confdefs.h +fi -{ echo "$as_me:$LINENO: checking whether char is unsigned" >&5 -echo $ECHO_N "checking whether char is unsigned... $ECHO_C" >&6; } -if test "${ac_cv_c_char_unsigned+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for lchflags" >&5 +$as_echo_n "checking for lchflags... " >&6; } +if test "${ac_cv_have_lchflags+set}" = set; then : + $as_echo_n "(cached) " >&6 else - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF + if test "$cross_compiling" = yes; then : + ac_cv_have_lchflags=cross +else + cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ -$ac_includes_default -int -main () +[ +#include +#include +int main(int argc, char*argv[]) { -static int test_array [1 - 2 * !(((char) -1) < 0)]; -test_array [0] = 0 - - ; + if(lchflags(argv[0], 0) != 0) + return 1; return 0; } +] _ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - ac_cv_c_char_unsigned=no +if ac_fn_c_try_run "$LINENO"; then : + ac_cv_have_lchflags=yes else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 + ac_cv_have_lchflags=no +fi +rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext \ + conftest.$ac_objext conftest.beam conftest.$ac_ext +fi + - ac_cv_c_char_unsigned=yes +fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_have_lchflags" >&5 +$as_echo "$ac_cv_have_lchflags" >&6; } +if test "$ac_cv_have_lchflags" = cross ; then + ac_fn_c_check_func "$LINENO" "lchflags" "ac_cv_func_lchflags" +if test "x$ac_cv_func_lchflags" = x""yes; then : + ac_cv_have_lchflags="yes" +else + ac_cv_have_lchflags="no" fi -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext fi -{ echo "$as_me:$LINENO: result: $ac_cv_c_char_unsigned" >&5 -echo "${ECHO_T}$ac_cv_c_char_unsigned" >&6; } -if test $ac_cv_c_char_unsigned = yes && test "$GCC" != yes; then - cat >>confdefs.h <<\_ACEOF -#define __CHAR_UNSIGNED__ 1 -_ACEOF +if test "$ac_cv_have_lchflags" = yes ; then + +$as_echo "#define HAVE_LCHFLAGS 1" >>confdefs.h fi -{ echo "$as_me:$LINENO: checking for an ANSI C-conforming const" >&5 -echo $ECHO_N "checking for an ANSI C-conforming const... $ECHO_C" >&6; } -if test "${ac_cv_c_const+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 +case $ac_sys_system/$ac_sys_release in +Darwin/*) + _CUR_CFLAGS="${CFLAGS}" + _CUR_LDFLAGS="${LDFLAGS}" + CFLAGS="${CFLAGS} -Wl,-search_paths_first" + LDFLAGS="${LDFLAGS} -Wl,-search_paths_first -L/usr/local/lib" + ;; +esac + +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for inflateCopy in -lz" >&5 +$as_echo_n "checking for inflateCopy in -lz... " >&6; } +if test "${ac_cv_lib_z_inflateCopy+set}" = set; then : + $as_echo_n "(cached) " >&6 else - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF + ac_check_lib_save_LIBS=$LIBS +LIBS="-lz $LIBS" +cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ +/* Override any GCC internal prototype to avoid an error. + Use char because int might match the return type of a GCC + builtin and then its argument prototype would still apply. */ +#ifdef __cplusplus +extern "C" +#endif +char inflateCopy (); int main () { -/* FIXME: Include the comments suggested by Paul. */ -#ifndef __cplusplus - /* Ultrix mips cc rejects this. */ - typedef int charset[2]; - const charset cs; - /* SunOS 4.1.1 cc rejects this. */ - char const *const *pcpcc; - char **ppc; - /* NEC SVR4.0.2 mips cc rejects this. */ - struct point {int x, y;}; - static struct point const zero = {0,0}; - /* AIX XL C 1.02.0.0 rejects this. - It does not let you subtract one const X* pointer from another in - an arm of an if-expression whose if-part is not a constant - expression */ - const char *g = "string"; - pcpcc = &g + (g ? g-g : 0); - /* HPUX 7.0 cc rejects these. */ - ++pcpcc; - ppc = (char**) pcpcc; - pcpcc = (char const *const *) ppc; - { /* SCO 3.2v4 cc rejects this. */ - char *t; - char const *s = 0 ? (char *) 0 : (char const *) 0; - - *t++ = 0; - if (s) return 0; - } - { /* Someone thinks the Sun supposedly-ANSI compiler will reject this. */ - int x[] = {25, 17}; - const int *foo = &x[0]; - ++foo; - } - { /* Sun SC1.0 ANSI compiler rejects this -- but not the above. */ - typedef const int *iptr; - iptr p = 0; - ++p; - } - { /* AIX XL C 1.02.0.0 rejects this saying - "k.c", line 2.27: 1506-025 (S) Operand must be a modifiable lvalue. */ - struct s { int j; const int *ap[3]; }; - struct s *b; b->j = 5; - } - { /* ULTRIX-32 V3.1 (Rev 9) vcc rejects this */ - const int foo = 10; - if (!foo) return 0; - } - return !cs[0] && !zero.x; -#endif - +return inflateCopy (); ; return 0; } _ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - ac_cv_c_const=yes +if ac_fn_c_try_link "$LINENO"; then : + ac_cv_lib_z_inflateCopy=yes else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - ac_cv_c_const=no + ac_cv_lib_z_inflateCopy=no fi - -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext +rm -f core conftest.err conftest.$ac_objext \ + conftest$ac_exeext conftest.$ac_ext +LIBS=$ac_check_lib_save_LIBS fi -{ echo "$as_me:$LINENO: result: $ac_cv_c_const" >&5 -echo "${ECHO_T}$ac_cv_c_const" >&6; } -if test $ac_cv_c_const = no; then +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_lib_z_inflateCopy" >&5 +$as_echo "$ac_cv_lib_z_inflateCopy" >&6; } +if test "x$ac_cv_lib_z_inflateCopy" = x""yes; then : -cat >>confdefs.h <<\_ACEOF -#define const -_ACEOF +$as_echo "#define HAVE_ZLIB_COPY 1" >>confdefs.h fi -works=no -{ echo "$as_me:$LINENO: checking for working volatile" >&5 -echo $ECHO_N "checking for working volatile... $ECHO_C" >&6; } -cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF +case $ac_sys_system/$ac_sys_release in +Darwin/*) + CFLAGS="${_CUR_CFLAGS}" + LDFLAGS="${_CUR_LDFLAGS}" + ;; +esac + +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for hstrerror" >&5 +$as_echo_n "checking for hstrerror... " >&6; } +cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ +#include "confdefs.h" +#include + int main () { -volatile int x; x = 0; +void* p = hstrerror; hstrerror(0) ; return 0; } _ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - works=yes -else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 +if ac_fn_c_try_link "$LINENO"; then : +$as_echo "#define HAVE_HSTRERROR 1" >>confdefs.h -cat >>confdefs.h <<\_ACEOF -#define volatile -_ACEOF - + { $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +$as_echo "yes" >&6; } +else + { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 +$as_echo "no" >&6; } fi +rm -f core conftest.err conftest.$ac_objext \ + conftest$ac_exeext conftest.$ac_ext -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext -{ echo "$as_me:$LINENO: result: $works" >&5 -echo "${ECHO_T}$works" >&6; } - -works=no -{ echo "$as_me:$LINENO: checking for working signed char" >&5 -echo $ECHO_N "checking for working signed char... $ECHO_C" >&6; } -cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for inet_aton" >&5 +$as_echo_n "checking for inet_aton... " >&6; } +cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ +#include "confdefs.h" +#include +#include +#include +#include + int main () { -signed char c; +void* p = inet_aton;inet_aton(0,0) ; return 0; } _ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - works=yes -else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - +if ac_fn_c_try_link "$LINENO"; then : -cat >>confdefs.h <<\_ACEOF -#define signed -_ACEOF +$as_echo "#define HAVE_INET_ATON 1" >>confdefs.h + { $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +$as_echo "yes" >&6; } +else + { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 +$as_echo "no" >&6; } fi +rm -f core conftest.err conftest.$ac_objext \ + conftest$ac_exeext conftest.$ac_ext -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext -{ echo "$as_me:$LINENO: result: $works" >&5 -echo "${ECHO_T}$works" >&6; } - -have_prototypes=no -{ echo "$as_me:$LINENO: checking for prototypes" >&5 -echo $ECHO_N "checking for prototypes... $ECHO_C" >&6; } -cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for inet_pton" >&5 +$as_echo_n "checking for inet_pton... " >&6; } +cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ -int foo(int x) { return 0; } + +#include "confdefs.h" +#include +#include +#include +#include + int main () { -return foo(10); +void* p = inet_pton ; - return 0; -} -_ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - - -cat >>confdefs.h <<\_ACEOF -#define HAVE_PROTOTYPES 1 + return 0; +} _ACEOF +if ac_fn_c_try_compile "$LINENO"; then : - have_prototypes=yes +$as_echo "#define HAVE_INET_PTON 1" >>confdefs.h + { $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +$as_echo "yes" >&6; } else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - + { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 +$as_echo "no" >&6; } fi - rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext -{ echo "$as_me:$LINENO: result: $have_prototypes" >&5 -echo "${ECHO_T}$have_prototypes" >&6; } -works=no -{ echo "$as_me:$LINENO: checking for variable length prototypes and stdarg.h" >&5 -echo $ECHO_N "checking for variable length prototypes and stdarg.h... $ECHO_C" >&6; } -cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF +# On some systems, setgroups is in unistd.h, on others, in grp.h +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for setgroups" >&5 +$as_echo_n "checking for setgroups... " >&6; } +cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ -#include -int foo(int x, ...) { - va_list va; - va_start(va, x); - va_arg(va, int); - va_arg(va, char *); - va_arg(va, double); - return 0; -} +#include "confdefs.h" +#include +#ifdef HAVE_GRP_H +#include +#endif int main () { -return foo(10, "", 3.14); +void* p = setgroups ; return 0; } _ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - - -cat >>confdefs.h <<\_ACEOF -#define HAVE_STDARG_PROTOTYPES 1 -_ACEOF +if ac_fn_c_try_compile "$LINENO"; then : - works=yes +$as_echo "#define HAVE_SETGROUPS 1" >>confdefs.h + { $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +$as_echo "yes" >&6; } else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - + { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 +$as_echo "no" >&6; } fi - rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext -{ echo "$as_me:$LINENO: result: $works" >&5 -echo "${ECHO_T}$works" >&6; } -# check for socketpair -{ echo "$as_me:$LINENO: checking for socketpair" >&5 -echo $ECHO_N "checking for socketpair... $ECHO_C" >&6; } -cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ +# check for openpty and forkpty + +for ac_func in openpty +do : + ac_fn_c_check_func "$LINENO" "openpty" "ac_cv_func_openpty" +if test "x$ac_cv_func_openpty" = x""yes; then : + cat >>confdefs.h <<_ACEOF +#define HAVE_OPENPTY 1 _ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -#include -#include +else + { $as_echo "$as_me:${as_lineno-$LINENO}: checking for openpty in -lutil" >&5 +$as_echo_n "checking for openpty in -lutil... " >&6; } +if test "${ac_cv_lib_util_openpty+set}" = set; then : + $as_echo_n "(cached) " >&6 +else + ac_check_lib_save_LIBS=$LIBS +LIBS="-lutil $LIBS" +cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ +/* Override any GCC internal prototype to avoid an error. + Use char because int might match the return type of a GCC + builtin and then its argument prototype would still apply. */ +#ifdef __cplusplus +extern "C" +#endif +char openpty (); int main () { -void *x=socketpair +return openpty (); ; return 0; } _ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then +if ac_fn_c_try_link "$LINENO"; then : + ac_cv_lib_util_openpty=yes +else + ac_cv_lib_util_openpty=no +fi +rm -f core conftest.err conftest.$ac_objext \ + conftest$ac_exeext conftest.$ac_ext +LIBS=$ac_check_lib_save_LIBS +fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_lib_util_openpty" >&5 +$as_echo "$ac_cv_lib_util_openpty" >&6; } +if test "x$ac_cv_lib_util_openpty" = x""yes; then : + $as_echo "#define HAVE_OPENPTY 1" >>confdefs.h + LIBS="$LIBS -lutil" +else + { $as_echo "$as_me:${as_lineno-$LINENO}: checking for openpty in -lbsd" >&5 +$as_echo_n "checking for openpty in -lbsd... " >&6; } +if test "${ac_cv_lib_bsd_openpty+set}" = set; then : + $as_echo_n "(cached) " >&6 +else + ac_check_lib_save_LIBS=$LIBS +LIBS="-lbsd $LIBS" +cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ -cat >>confdefs.h <<\_ACEOF -#define HAVE_SOCKETPAIR 1 +/* Override any GCC internal prototype to avoid an error. + Use char because int might match the return type of a GCC + builtin and then its argument prototype would still apply. */ +#ifdef __cplusplus +extern "C" +#endif +char openpty (); +int +main () +{ +return openpty (); + ; + return 0; +} _ACEOF - - { echo "$as_me:$LINENO: result: yes" >&5 -echo "${ECHO_T}yes" >&6; } +if ac_fn_c_try_link "$LINENO"; then : + ac_cv_lib_bsd_openpty=yes else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 + ac_cv_lib_bsd_openpty=no +fi +rm -f core conftest.err conftest.$ac_objext \ + conftest$ac_exeext conftest.$ac_ext +LIBS=$ac_check_lib_save_LIBS +fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_lib_bsd_openpty" >&5 +$as_echo "$ac_cv_lib_bsd_openpty" >&6; } +if test "x$ac_cv_lib_bsd_openpty" = x""yes; then : + $as_echo "#define HAVE_OPENPTY 1" >>confdefs.h + LIBS="$LIBS -lbsd" +fi - { echo "$as_me:$LINENO: result: no" >&5 -echo "${ECHO_T}no" >&6; } fi -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext -# check if sockaddr has sa_len member -{ echo "$as_me:$LINENO: checking if sockaddr has sa_len member" >&5 -echo $ECHO_N "checking if sockaddr has sa_len member... $ECHO_C" >&6; } -cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ +fi +done + +for ac_func in forkpty +do : + ac_fn_c_check_func "$LINENO" "forkpty" "ac_cv_func_forkpty" +if test "x$ac_cv_func_forkpty" = x""yes; then : + cat >>confdefs.h <<_ACEOF +#define HAVE_FORKPTY 1 _ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF + +else + { $as_echo "$as_me:${as_lineno-$LINENO}: checking for forkpty in -lutil" >&5 +$as_echo_n "checking for forkpty in -lutil... " >&6; } +if test "${ac_cv_lib_util_forkpty+set}" = set; then : + $as_echo_n "(cached) " >&6 +else + ac_check_lib_save_LIBS=$LIBS +LIBS="-lutil $LIBS" +cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ -#include -#include + +/* Override any GCC internal prototype to avoid an error. + Use char because int might match the return type of a GCC + builtin and then its argument prototype would still apply. */ +#ifdef __cplusplus +extern "C" +#endif +char forkpty (); int main () { -struct sockaddr x; -x.sa_len = 0; +return forkpty (); ; return 0; } _ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - { echo "$as_me:$LINENO: result: yes" >&5 -echo "${ECHO_T}yes" >&6; } - -cat >>confdefs.h <<\_ACEOF -#define HAVE_SOCKADDR_SA_LEN 1 -_ACEOF - +if ac_fn_c_try_link "$LINENO"; then : + ac_cv_lib_util_forkpty=yes else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - { echo "$as_me:$LINENO: result: no" >&5 -echo "${ECHO_T}no" >&6; } + ac_cv_lib_util_forkpty=no fi - -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext - -va_list_is_array=no -{ echo "$as_me:$LINENO: checking whether va_list is an array" >&5 -echo $ECHO_N "checking whether va_list is an array... $ECHO_C" >&6; } -cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF +rm -f core conftest.err conftest.$ac_objext \ + conftest$ac_exeext conftest.$ac_ext +LIBS=$ac_check_lib_save_LIBS +fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_lib_util_forkpty" >&5 +$as_echo "$ac_cv_lib_util_forkpty" >&6; } +if test "x$ac_cv_lib_util_forkpty" = x""yes; then : + $as_echo "#define HAVE_FORKPTY 1" >>confdefs.h + LIBS="$LIBS -lutil" +else + { $as_echo "$as_me:${as_lineno-$LINENO}: checking for forkpty in -lbsd" >&5 +$as_echo_n "checking for forkpty in -lbsd... " >&6; } +if test "${ac_cv_lib_bsd_forkpty+set}" = set; then : + $as_echo_n "(cached) " >&6 +else + ac_check_lib_save_LIBS=$LIBS +LIBS="-lbsd $LIBS" +cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ -#ifdef HAVE_STDARG_PROTOTYPES -#include -#else -#include +/* Override any GCC internal prototype to avoid an error. + Use char because int might match the return type of a GCC + builtin and then its argument prototype would still apply. */ +#ifdef __cplusplus +extern "C" #endif - +char forkpty (); int main () { -va_list list1, list2; list1 = list2; +return forkpty (); ; return 0; } _ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - : +if ac_fn_c_try_link "$LINENO"; then : + ac_cv_lib_bsd_forkpty=yes else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 + ac_cv_lib_bsd_forkpty=no +fi +rm -f core conftest.err conftest.$ac_objext \ + conftest$ac_exeext conftest.$ac_ext +LIBS=$ac_check_lib_save_LIBS +fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_lib_bsd_forkpty" >&5 +$as_echo "$ac_cv_lib_bsd_forkpty" >&6; } +if test "x$ac_cv_lib_bsd_forkpty" = x""yes; then : + $as_echo "#define HAVE_FORKPTY 1" >>confdefs.h + LIBS="$LIBS -lbsd" +fi +fi -cat >>confdefs.h <<\_ACEOF -#define VA_LIST_IS_ARRAY 1 -_ACEOF - va_list_is_array=yes +fi +done + + +# Stuff for expat. +for ac_func in memmove +do : + ac_fn_c_check_func "$LINENO" "memmove" "ac_cv_func_memmove" +if test "x$ac_cv_func_memmove" = x""yes; then : + cat >>confdefs.h <<_ACEOF +#define HAVE_MEMMOVE 1 +_ACEOF fi +done -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext -{ echo "$as_me:$LINENO: result: $va_list_is_array" >&5 -echo "${ECHO_T}$va_list_is_array" >&6; } -# sigh -- gethostbyname_r is a mess; it can have 3, 5 or 6 arguments :-( +# check for long file support functions +for ac_func in fseek64 fseeko fstatvfs ftell64 ftello statvfs +do : + as_ac_var=`$as_echo "ac_cv_func_$ac_func" | $as_tr_sh` +ac_fn_c_check_func "$LINENO" "$ac_func" "$as_ac_var" +eval as_val=\$$as_ac_var + if test "x$as_val" = x""yes; then : + cat >>confdefs.h <<_ACEOF +#define `$as_echo "HAVE_$ac_func" | $as_tr_cpp` 1 +_ACEOF + +fi +done +for ac_func in dup2 getcwd strdup +do : + as_ac_var=`$as_echo "ac_cv_func_$ac_func" | $as_tr_sh` +ac_fn_c_check_func "$LINENO" "$ac_func" "$as_ac_var" +eval as_val=\$$as_ac_var + if test "x$as_val" = x""yes; then : + cat >>confdefs.h <<_ACEOF +#define `$as_echo "HAVE_$ac_func" | $as_tr_cpp` 1 +_ACEOF -{ echo "$as_me:$LINENO: checking for gethostbyname_r" >&5 -echo $ECHO_N "checking for gethostbyname_r... $ECHO_C" >&6; } -if test "${ac_cv_func_gethostbyname_r+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 else - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ + case " $LIBOBJS " in + *" $ac_func.$ac_objext "* ) ;; + *) LIBOBJS="$LIBOBJS $ac_func.$ac_objext" + ;; +esac + +fi +done + + +for ac_func in getpgrp +do : + ac_fn_c_check_func "$LINENO" "getpgrp" "ac_cv_func_getpgrp" +if test "x$ac_cv_func_getpgrp" = x""yes; then : + cat >>confdefs.h <<_ACEOF +#define HAVE_GETPGRP 1 _ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF + cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ -/* Define gethostbyname_r to an innocuous variant, in case declares gethostbyname_r. - For example, HP-UX 11i declares gettimeofday. */ -#define gethostbyname_r innocuous_gethostbyname_r - -/* System header to define __stub macros and hopefully few prototypes, - which can conflict with char gethostbyname_r (); below. - Prefer to if __STDC__ is defined, since - exists even on freestanding compilers. */ +#include +int +main () +{ +getpgrp(0); + ; + return 0; +} +_ACEOF +if ac_fn_c_try_compile "$LINENO"; then : -#ifdef __STDC__ -# include -#else -# include -#endif +$as_echo "#define GETPGRP_HAVE_ARG 1" >>confdefs.h -#undef gethostbyname_r +fi +rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext -/* Override any GCC internal prototype to avoid an error. - Use char because int might match the return type of a GCC - builtin and then its argument prototype would still apply. */ -#ifdef __cplusplus -extern "C" -#endif -char gethostbyname_r (); -/* The GNU C library defines this for functions which it implements - to always fail with ENOSYS. Some functions are actually named - something starting with __ and the normal name is an alias. */ -#if defined __stub_gethostbyname_r || defined __stub___gethostbyname_r -choke me -#endif +fi +done +for ac_func in setpgrp +do : + ac_fn_c_check_func "$LINENO" "setpgrp" "ac_cv_func_setpgrp" +if test "x$ac_cv_func_setpgrp" = x""yes; then : + cat >>confdefs.h <<_ACEOF +#define HAVE_SETPGRP 1 +_ACEOF + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ +#include int main () { -return gethostbyname_r (); +setpgrp(0,0); ; return 0; } _ACEOF -rm -f conftest.$ac_objext conftest$ac_exeext -if { (ac_try="$ac_link" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_link") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest$ac_exeext && - $as_test_x conftest$ac_exeext; then - ac_cv_func_gethostbyname_r=yes -else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 +if ac_fn_c_try_compile "$LINENO"; then : - ac_cv_func_gethostbyname_r=no -fi +$as_echo "#define SETPGRP_HAVE_ARG 1" >>confdefs.h -rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \ - conftest$ac_exeext conftest.$ac_ext fi -{ echo "$as_me:$LINENO: result: $ac_cv_func_gethostbyname_r" >&5 -echo "${ECHO_T}$ac_cv_func_gethostbyname_r" >&6; } -if test $ac_cv_func_gethostbyname_r = yes; then +rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext - cat >>confdefs.h <<\_ACEOF -#define HAVE_GETHOSTBYNAME_R 1 -_ACEOF +fi +done - { echo "$as_me:$LINENO: checking gethostbyname_r with 6 args" >&5 -echo $ECHO_N "checking gethostbyname_r with 6 args... $ECHO_C" >&6; } - OLD_CFLAGS=$CFLAGS - CFLAGS="$CFLAGS $MY_CPPFLAGS $MY_THREAD_CPPFLAGS $MY_CFLAGS" - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ +for ac_func in gettimeofday +do : + ac_fn_c_check_func "$LINENO" "gettimeofday" "ac_cv_func_gettimeofday" +if test "x$ac_cv_func_gettimeofday" = x""yes; then : + cat >>confdefs.h <<_ACEOF +#define HAVE_GETTIMEOFDAY 1 _ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF + cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ - -# include - +#include int main () { - - char *name; - struct hostent *he, *res; - char buffer[2048]; - int buflen = 2048; - int h_errnop; - - (void) gethostbyname_r(name, he, buffer, buflen, &res, &h_errnop) - +gettimeofday((struct timeval*)0,(struct timezone*)0); ; return 0; } _ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then +if ac_fn_c_try_compile "$LINENO"; then : - cat >>confdefs.h <<\_ACEOF -#define HAVE_GETHOSTBYNAME_R 1 -_ACEOF +else +$as_echo "#define GETTIMEOFDAY_NO_TZ 1" >>confdefs.h -cat >>confdefs.h <<\_ACEOF -#define HAVE_GETHOSTBYNAME_R_6_ARG 1 -_ACEOF - { echo "$as_me:$LINENO: result: yes" >&5 -echo "${ECHO_T}yes" >&6; } +fi +rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext -else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 +fi +done - { echo "$as_me:$LINENO: result: no" >&5 -echo "${ECHO_T}no" >&6; } - { echo "$as_me:$LINENO: checking gethostbyname_r with 5 args" >&5 -echo $ECHO_N "checking gethostbyname_r with 5 args... $ECHO_C" >&6; } - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for major" >&5 +$as_echo_n "checking for major... " >&6; } +cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ -# include +#if defined(MAJOR_IN_MKDEV) +#include +#elif defined(MAJOR_IN_SYSMACROS) +#include +#else +#include +#endif int main () { - char *name; - struct hostent *he; - char buffer[2048]; - int buflen = 2048; - int h_errnop; - - (void) gethostbyname_r(name, he, buffer, buflen, &h_errnop) + makedev(major(0),minor(0)); ; return 0; } _ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - - cat >>confdefs.h <<\_ACEOF -#define HAVE_GETHOSTBYNAME_R 1 -_ACEOF +if ac_fn_c_try_link "$LINENO"; then : -cat >>confdefs.h <<\_ACEOF -#define HAVE_GETHOSTBYNAME_R_5_ARG 1 -_ACEOF +$as_echo "#define HAVE_DEVICE_MACROS 1" >>confdefs.h - { echo "$as_me:$LINENO: result: yes" >&5 -echo "${ECHO_T}yes" >&6; } + { $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +$as_echo "yes" >&6; } else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 + { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 +$as_echo "no" >&6; } - { echo "$as_me:$LINENO: result: no" >&5 -echo "${ECHO_T}no" >&6; } - { echo "$as_me:$LINENO: checking gethostbyname_r with 3 args" >&5 -echo $ECHO_N "checking gethostbyname_r with 3 args... $ECHO_C" >&6; } - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF +fi +rm -f core conftest.err conftest.$ac_objext \ + conftest$ac_exeext conftest.$ac_ext + +# On OSF/1 V5.1, getaddrinfo is available, but a define +# for [no]getaddrinfo in netdb.h. +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for getaddrinfo" >&5 +$as_echo_n "checking for getaddrinfo... " >&6; } +cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ -# include +#include +#include +#include +#include int main () { - - char *name; - struct hostent *he; - struct hostent_data data; - - (void) gethostbyname_r(name, he, &data); - +getaddrinfo(NULL, NULL, NULL, NULL); ; return 0; } _ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - - cat >>confdefs.h <<\_ACEOF -#define HAVE_GETHOSTBYNAME_R 1 -_ACEOF +if ac_fn_c_try_link "$LINENO"; then : + have_getaddrinfo=yes +else + have_getaddrinfo=no +fi +rm -f core conftest.err conftest.$ac_objext \ + conftest$ac_exeext conftest.$ac_ext +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $have_getaddrinfo" >&5 +$as_echo "$have_getaddrinfo" >&6; } +if test $have_getaddrinfo = yes +then + { $as_echo "$as_me:${as_lineno-$LINENO}: checking getaddrinfo bug" >&5 +$as_echo_n "checking getaddrinfo bug... " >&6; } + if test "${ac_cv_buggy_getaddrinfo+set}" = set; then : + $as_echo_n "(cached) " >&6 +else + if test "$cross_compiling" = yes; then : + ac_cv_buggy_getaddrinfo=yes +else + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ +#include +#include +#include +#include +#include -cat >>confdefs.h <<\_ACEOF -#define HAVE_GETHOSTBYNAME_R_3_ARG 1 -_ACEOF +int main() +{ + int passive, gaierr, inet4 = 0, inet6 = 0; + struct addrinfo hints, *ai, *aitop; + char straddr[INET6_ADDRSTRLEN], strport[16]; - { echo "$as_me:$LINENO: result: yes" >&5 -echo "${ECHO_T}yes" >&6; } + for (passive = 0; passive <= 1; passive++) { + memset(&hints, 0, sizeof(hints)); + hints.ai_family = AF_UNSPEC; + hints.ai_flags = passive ? AI_PASSIVE : 0; + hints.ai_socktype = SOCK_STREAM; + hints.ai_protocol = IPPROTO_TCP; + if ((gaierr = getaddrinfo(NULL, "54321", &hints, &aitop)) != 0) { + (void)gai_strerror(gaierr); + goto bad; + } + for (ai = aitop; ai; ai = ai->ai_next) { + if (ai->ai_addr == NULL || + ai->ai_addrlen == 0 || + getnameinfo(ai->ai_addr, ai->ai_addrlen, + straddr, sizeof(straddr), strport, sizeof(strport), + NI_NUMERICHOST|NI_NUMERICSERV) != 0) { + goto bad; + } + switch (ai->ai_family) { + case AF_INET: + if (strcmp(strport, "54321") != 0) { + goto bad; + } + if (passive) { + if (strcmp(straddr, "0.0.0.0") != 0) { + goto bad; + } + } else { + if (strcmp(straddr, "127.0.0.1") != 0) { + goto bad; + } + } + inet4++; + break; + case AF_INET6: + if (strcmp(strport, "54321") != 0) { + goto bad; + } + if (passive) { + if (strcmp(straddr, "::") != 0) { + goto bad; + } + } else { + if (strcmp(straddr, "::1") != 0) { + goto bad; + } + } + inet6++; + break; + case AF_UNSPEC: + goto bad; + break; + default: + /* another family support? */ + break; + } + } + } -else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 + if (!(inet4 == 0 || inet4 == 2)) + goto bad; + if (!(inet6 == 0 || inet6 == 2)) + goto bad; + if (aitop) + freeaddrinfo(aitop); + return 0; - { echo "$as_me:$LINENO: result: no" >&5 -echo "${ECHO_T}no" >&6; } + bad: + if (aitop) + freeaddrinfo(aitop); + return 1; +} +_ACEOF +if ac_fn_c_try_run "$LINENO"; then : + ac_cv_buggy_getaddrinfo=no +else + ac_cv_buggy_getaddrinfo=yes +fi +rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext \ + conftest.$ac_objext conftest.beam conftest.$ac_ext fi -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext +fi fi -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext +if test $have_getaddrinfo = no -o "$ac_cv_buggy_getaddrinfo" = yes +then + if test $ipv6 = yes + then + echo 'Fatal: You must get working getaddrinfo() function.' + echo ' or you can specify "--disable-ipv6"'. + exit 1 + fi +else -fi +$as_echo "#define HAVE_GETADDRINFO 1" >>confdefs.h -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext - CFLAGS=$OLD_CFLAGS +fi +for ac_func in getnameinfo +do : + ac_fn_c_check_func "$LINENO" "getnameinfo" "ac_cv_func_getnameinfo" +if test "x$ac_cv_func_getnameinfo" = x""yes; then : + cat >>confdefs.h <<_ACEOF +#define HAVE_GETNAMEINFO 1 +_ACEOF -else +fi +done -for ac_func in gethostbyname -do -as_ac_var=`echo "ac_cv_func_$ac_func" | $as_tr_sh` -{ echo "$as_me:$LINENO: checking for $ac_func" >&5 -echo $ECHO_N "checking for $ac_func... $ECHO_C" >&6; } -if { as_var=$as_ac_var; eval "test \"\${$as_var+set}\" = set"; }; then - echo $ECHO_N "(cached) $ECHO_C" >&6 +# checks for structures +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking whether time.h and sys/time.h may both be included" >&5 +$as_echo_n "checking whether time.h and sys/time.h may both be included... " >&6; } +if test "${ac_cv_header_time+set}" = set; then : + $as_echo_n "(cached) " >&6 else - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF + cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ -/* Define $ac_func to an innocuous variant, in case declares $ac_func. - For example, HP-UX 11i declares gettimeofday. */ -#define $ac_func innocuous_$ac_func - -/* System header to define __stub macros and hopefully few prototypes, - which can conflict with char $ac_func (); below. - Prefer to if __STDC__ is defined, since - exists even on freestanding compilers. */ +#include +#include +#include -#ifdef __STDC__ -# include -#else -# include -#endif +int +main () +{ +if ((struct tm *) 0) +return 0; + ; + return 0; +} +_ACEOF +if ac_fn_c_try_compile "$LINENO"; then : + ac_cv_header_time=yes +else + ac_cv_header_time=no +fi +rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext +fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_header_time" >&5 +$as_echo "$ac_cv_header_time" >&6; } +if test $ac_cv_header_time = yes; then -#undef $ac_func +$as_echo "#define TIME_WITH_SYS_TIME 1" >>confdefs.h -/* Override any GCC internal prototype to avoid an error. - Use char because int might match the return type of a GCC - builtin and then its argument prototype would still apply. */ -#ifdef __cplusplus -extern "C" -#endif -char $ac_func (); -/* The GNU C library defines this for functions which it implements - to always fail with ENOSYS. Some functions are actually named - something starting with __ and the normal name is an alias. */ -#if defined __stub_$ac_func || defined __stub___$ac_func -choke me -#endif +fi + +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking whether struct tm is in sys/time.h or time.h" >&5 +$as_echo_n "checking whether struct tm is in sys/time.h or time.h... " >&6; } +if test "${ac_cv_struct_tm+set}" = set; then : + $as_echo_n "(cached) " >&6 +else + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ +#include +#include int main () { -return $ac_func (); +struct tm tm; + int *p = &tm.tm_sec; + return !p; ; return 0; } _ACEOF -rm -f conftest.$ac_objext conftest$ac_exeext -if { (ac_try="$ac_link" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_link") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest$ac_exeext && - $as_test_x conftest$ac_exeext; then - eval "$as_ac_var=yes" +if ac_fn_c_try_compile "$LINENO"; then : + ac_cv_struct_tm=time.h else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - eval "$as_ac_var=no" -fi - -rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \ - conftest$ac_exeext conftest.$ac_ext + ac_cv_struct_tm=sys/time.h fi -ac_res=`eval echo '${'$as_ac_var'}'` - { echo "$as_me:$LINENO: result: $ac_res" >&5 -echo "${ECHO_T}$ac_res" >&6; } -if test `eval echo '${'$as_ac_var'}'` = yes; then - cat >>confdefs.h <<_ACEOF -#define `echo "HAVE_$ac_func" | $as_tr_cpp` 1 -_ACEOF - +rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext fi -done +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_struct_tm" >&5 +$as_echo "$ac_cv_struct_tm" >&6; } +if test $ac_cv_struct_tm = sys/time.h; then +$as_echo "#define TM_IN_SYS_TIME 1" >>confdefs.h fi +ac_fn_c_check_member "$LINENO" "struct tm" "tm_zone" "ac_cv_member_struct_tm_tm_zone" "#include +#include <$ac_cv_struct_tm> +" +if test "x$ac_cv_member_struct_tm_tm_zone" = x""yes; then : +cat >>confdefs.h <<_ACEOF +#define HAVE_STRUCT_TM_TM_ZONE 1 +_ACEOF +fi +if test "$ac_cv_member_struct_tm_tm_zone" = yes; then -# checks for system services -# (none yet) +$as_echo "#define HAVE_TM_ZONE 1" >>confdefs.h -# Linux requires this for correct f.p. operations -{ echo "$as_me:$LINENO: checking for __fpu_control" >&5 -echo $ECHO_N "checking for __fpu_control... $ECHO_C" >&6; } -if test "${ac_cv_func___fpu_control+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 else - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -/* Define __fpu_control to an innocuous variant, in case declares __fpu_control. - For example, HP-UX 11i declares gettimeofday. */ -#define __fpu_control innocuous___fpu_control - -/* System header to define __stub macros and hopefully few prototypes, - which can conflict with char __fpu_control (); below. - Prefer to if __STDC__ is defined, since - exists even on freestanding compilers. */ - -#ifdef __STDC__ -# include -#else -# include -#endif + ac_fn_c_check_decl "$LINENO" "tzname" "ac_cv_have_decl_tzname" "#include +" +if test "x$ac_cv_have_decl_tzname" = x""yes; then : + ac_have_decl=1 +else + ac_have_decl=0 +fi -#undef __fpu_control +cat >>confdefs.h <<_ACEOF +#define HAVE_DECL_TZNAME $ac_have_decl +_ACEOF -/* Override any GCC internal prototype to avoid an error. - Use char because int might match the return type of a GCC - builtin and then its argument prototype would still apply. */ -#ifdef __cplusplus -extern "C" -#endif -char __fpu_control (); -/* The GNU C library defines this for functions which it implements - to always fail with ENOSYS. Some functions are actually named - something starting with __ and the normal name is an alias. */ -#if defined __stub___fpu_control || defined __stub_____fpu_control -choke me + { $as_echo "$as_me:${as_lineno-$LINENO}: checking for tzname" >&5 +$as_echo_n "checking for tzname... " >&6; } +if test "${ac_cv_var_tzname+set}" = set; then : + $as_echo_n "(cached) " >&6 +else + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ +#include +#if !HAVE_DECL_TZNAME +extern char *tzname[]; #endif int main () { -return __fpu_control (); +return tzname[0][0]; ; return 0; } _ACEOF -rm -f conftest.$ac_objext conftest$ac_exeext -if { (ac_try="$ac_link" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_link") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest$ac_exeext && - $as_test_x conftest$ac_exeext; then - ac_cv_func___fpu_control=yes +if ac_fn_c_try_link "$LINENO"; then : + ac_cv_var_tzname=yes else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - ac_cv_func___fpu_control=no + ac_cv_var_tzname=no +fi +rm -f core conftest.err conftest.$ac_objext \ + conftest$ac_exeext conftest.$ac_ext fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_var_tzname" >&5 +$as_echo "$ac_cv_var_tzname" >&6; } + if test $ac_cv_var_tzname = yes; then + +$as_echo "#define HAVE_TZNAME 1" >>confdefs.h -rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \ - conftest$ac_exeext conftest.$ac_ext + fi fi -{ echo "$as_me:$LINENO: result: $ac_cv_func___fpu_control" >&5 -echo "${ECHO_T}$ac_cv_func___fpu_control" >&6; } -if test $ac_cv_func___fpu_control = yes; then - : -else -{ echo "$as_me:$LINENO: checking for __fpu_control in -lieee" >&5 -echo $ECHO_N "checking for __fpu_control in -lieee... $ECHO_C" >&6; } -if test "${ac_cv_lib_ieee___fpu_control+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 -else - ac_check_lib_save_LIBS=$LIBS -LIBS="-lieee $LIBS" -cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ +ac_fn_c_check_member "$LINENO" "struct stat" "st_rdev" "ac_cv_member_struct_stat_st_rdev" "$ac_includes_default" +if test "x$ac_cv_member_struct_stat_st_rdev" = x""yes; then : -/* Override any GCC internal prototype to avoid an error. - Use char because int might match the return type of a GCC - builtin and then its argument prototype would still apply. */ -#ifdef __cplusplus -extern "C" -#endif -char __fpu_control (); -int -main () -{ -return __fpu_control (); - ; - return 0; -} +cat >>confdefs.h <<_ACEOF +#define HAVE_STRUCT_STAT_ST_RDEV 1 _ACEOF -rm -f conftest.$ac_objext conftest$ac_exeext -if { (ac_try="$ac_link" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_link") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest$ac_exeext && - $as_test_x conftest$ac_exeext; then - ac_cv_lib_ieee___fpu_control=yes -else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - ac_cv_lib_ieee___fpu_control=no -fi -rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \ - conftest$ac_exeext conftest.$ac_ext -LIBS=$ac_check_lib_save_LIBS fi -{ echo "$as_me:$LINENO: result: $ac_cv_lib_ieee___fpu_control" >&5 -echo "${ECHO_T}$ac_cv_lib_ieee___fpu_control" >&6; } -if test $ac_cv_lib_ieee___fpu_control = yes; then - cat >>confdefs.h <<_ACEOF -#define HAVE_LIBIEEE 1 + +ac_fn_c_check_member "$LINENO" "struct stat" "st_blksize" "ac_cv_member_struct_stat_st_blksize" "$ac_includes_default" +if test "x$ac_cv_member_struct_stat_st_blksize" = x""yes; then : + +cat >>confdefs.h <<_ACEOF +#define HAVE_STRUCT_STAT_ST_BLKSIZE 1 _ACEOF - LIBS="-lieee $LIBS" fi +ac_fn_c_check_member "$LINENO" "struct stat" "st_flags" "ac_cv_member_struct_stat_st_flags" "$ac_includes_default" +if test "x$ac_cv_member_struct_stat_st_flags" = x""yes; then : -fi +cat >>confdefs.h <<_ACEOF +#define HAVE_STRUCT_STAT_ST_FLAGS 1 +_ACEOF -# Check for --with-fpectl -{ echo "$as_me:$LINENO: checking for --with-fpectl" >&5 -echo $ECHO_N "checking for --with-fpectl... $ECHO_C" >&6; } +fi -# Check whether --with-fpectl was given. -if test "${with_fpectl+set}" = set; then - withval=$with_fpectl; -if test "$withval" != no -then +ac_fn_c_check_member "$LINENO" "struct stat" "st_gen" "ac_cv_member_struct_stat_st_gen" "$ac_includes_default" +if test "x$ac_cv_member_struct_stat_st_gen" = x""yes; then : -cat >>confdefs.h <<\_ACEOF -#define WANT_SIGFPE_HANDLER 1 +cat >>confdefs.h <<_ACEOF +#define HAVE_STRUCT_STAT_ST_GEN 1 _ACEOF - { echo "$as_me:$LINENO: result: yes" >&5 -echo "${ECHO_T}yes" >&6; } -else { echo "$as_me:$LINENO: result: no" >&5 -echo "${ECHO_T}no" >&6; } -fi -else - { echo "$as_me:$LINENO: result: no" >&5 -echo "${ECHO_T}no" >&6; } + fi +ac_fn_c_check_member "$LINENO" "struct stat" "st_birthtime" "ac_cv_member_struct_stat_st_birthtime" "$ac_includes_default" +if test "x$ac_cv_member_struct_stat_st_birthtime" = x""yes; then : -# check for --with-libm=... +cat >>confdefs.h <<_ACEOF +#define HAVE_STRUCT_STAT_ST_BIRTHTIME 1 +_ACEOF -case $ac_sys_system in -Darwin) ;; -*) LIBM=-lm -esac -{ echo "$as_me:$LINENO: checking for --with-libm=STRING" >&5 -echo $ECHO_N "checking for --with-libm=STRING... $ECHO_C" >&6; } -# Check whether --with-libm was given. -if test "${with_libm+set}" = set; then - withval=$with_libm; -if test "$withval" = no -then LIBM= - { echo "$as_me:$LINENO: result: force LIBM empty" >&5 -echo "${ECHO_T}force LIBM empty" >&6; } -elif test "$withval" != yes -then LIBM=$withval - { echo "$as_me:$LINENO: result: set LIBM=\"$withval\"" >&5 -echo "${ECHO_T}set LIBM=\"$withval\"" >&6; } -else { { echo "$as_me:$LINENO: error: proper usage is --with-libm=STRING" >&5 -echo "$as_me: error: proper usage is --with-libm=STRING" >&2;} - { (exit 1); exit 1; }; } -fi -else - { echo "$as_me:$LINENO: result: default LIBM=\"$LIBM\"" >&5 -echo "${ECHO_T}default LIBM=\"$LIBM\"" >&6; } fi +ac_fn_c_check_member "$LINENO" "struct stat" "st_blocks" "ac_cv_member_struct_stat_st_blocks" "$ac_includes_default" +if test "x$ac_cv_member_struct_stat_st_blocks" = x""yes; then : -# check for --with-libc=... +cat >>confdefs.h <<_ACEOF +#define HAVE_STRUCT_STAT_ST_BLOCKS 1 +_ACEOF -{ echo "$as_me:$LINENO: checking for --with-libc=STRING" >&5 -echo $ECHO_N "checking for --with-libc=STRING... $ECHO_C" >&6; } -# Check whether --with-libc was given. -if test "${with_libc+set}" = set; then - withval=$with_libc; -if test "$withval" = no -then LIBC= - { echo "$as_me:$LINENO: result: force LIBC empty" >&5 -echo "${ECHO_T}force LIBC empty" >&6; } -elif test "$withval" != yes -then LIBC=$withval - { echo "$as_me:$LINENO: result: set LIBC=\"$withval\"" >&5 -echo "${ECHO_T}set LIBC=\"$withval\"" >&6; } -else { { echo "$as_me:$LINENO: error: proper usage is --with-libc=STRING" >&5 -echo "$as_me: error: proper usage is --with-libc=STRING" >&2;} - { (exit 1); exit 1; }; } -fi +$as_echo "#define HAVE_ST_BLOCKS 1" >>confdefs.h + else - { echo "$as_me:$LINENO: result: default LIBC=\"$LIBC\"" >&5 -echo "${ECHO_T}default LIBC=\"$LIBC\"" >&6; } + case " $LIBOBJS " in + *" fileblocks.$ac_objext "* ) ;; + *) LIBOBJS="$LIBOBJS fileblocks.$ac_objext" + ;; +esac + fi -# ************************************************** -# * Check for various properties of floating point * -# ************************************************** -{ echo "$as_me:$LINENO: checking whether C doubles are little-endian IEEE 754 binary64" >&5 -echo $ECHO_N "checking whether C doubles are little-endian IEEE 754 binary64... $ECHO_C" >&6; } -if test "${ac_cv_little_endian_double+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for time.h that defines altzone" >&5 +$as_echo_n "checking for time.h that defines altzone... " >&6; } +if test "${ac_cv_header_time_altzone+set}" = set; then : + $as_echo_n "(cached) " >&6 else -if test "$cross_compiling" = yes; then - ac_cv_little_endian_double=no -else - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF + cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ - -#include -int main() { - double x = 9006104071832581.0; - if (memcmp(&x, "\x05\x04\x03\x02\x01\xff\x3f\x43", 8) == 0) - return 0; - else - return 1; +#include +int +main () +{ +return altzone; + ; + return 0; } - _ACEOF -rm -f conftest$ac_exeext -if { (ac_try="$ac_link" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_link") 2>&5 - ac_status=$? - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { ac_try='./conftest$ac_exeext' - { (case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_try") 2>&5 - ac_status=$? - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); }; }; then - ac_cv_little_endian_double=yes +if ac_fn_c_try_compile "$LINENO"; then : + ac_cv_header_time_altzone=yes else - echo "$as_me: program exited with status $ac_status" >&5 -echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - -( exit $ac_status ) -ac_cv_little_endian_double=no + ac_cv_header_time_altzone=no fi -rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext conftest.$ac_objext conftest.$ac_ext +rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext + fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_header_time_altzone" >&5 +$as_echo "$ac_cv_header_time_altzone" >&6; } +if test $ac_cv_header_time_altzone = yes; then + +$as_echo "#define HAVE_ALTZONE 1" >>confdefs.h fi -{ echo "$as_me:$LINENO: result: $ac_cv_little_endian_double" >&5 -echo "${ECHO_T}$ac_cv_little_endian_double" >&6; } -if test "$ac_cv_little_endian_double" = yes -then +was_it_defined=no +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking whether sys/select.h and sys/time.h may both be included" >&5 +$as_echo_n "checking whether sys/select.h and sys/time.h may both be included... " >&6; } +cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + +#include +#include +#include -cat >>confdefs.h <<\_ACEOF -#define DOUBLE_IS_LITTLE_ENDIAN_IEEE754 1 +int +main () +{ +; + ; + return 0; +} _ACEOF +if ac_fn_c_try_compile "$LINENO"; then : -fi -{ echo "$as_me:$LINENO: checking whether C doubles are big-endian IEEE 754 binary64" >&5 -echo $ECHO_N "checking whether C doubles are big-endian IEEE 754 binary64... $ECHO_C" >&6; } -if test "${ac_cv_big_endian_double+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 -else +$as_echo "#define SYS_SELECT_WITH_SYS_TIME 1" >>confdefs.h -if test "$cross_compiling" = yes; then - ac_cv_big_endian_double=no + was_it_defined=yes + +fi +rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $was_it_defined" >&5 +$as_echo "$was_it_defined" >&6; } + +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for addrinfo" >&5 +$as_echo_n "checking for addrinfo... " >&6; } +if test "${ac_cv_struct_addrinfo+set}" = set; then : + $as_echo_n "(cached) " >&6 else - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF + cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ - -#include -int main() { - double x = 9006104071832581.0; - if (memcmp(&x, "\x43\x3f\xff\x01\x02\x03\x04\x05", 8) == 0) - return 0; - else - return 1; +#include +int +main () +{ +struct addrinfo a + ; + return 0; } - _ACEOF -rm -f conftest$ac_exeext -if { (ac_try="$ac_link" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_link") 2>&5 - ac_status=$? - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { ac_try='./conftest$ac_exeext' - { (case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_try") 2>&5 - ac_status=$? - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); }; }; then - ac_cv_big_endian_double=yes +if ac_fn_c_try_compile "$LINENO"; then : + ac_cv_struct_addrinfo=yes else - echo "$as_me: program exited with status $ac_status" >&5 -echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - -( exit $ac_status ) -ac_cv_big_endian_double=no + ac_cv_struct_addrinfo=no fi -rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext conftest.$ac_objext conftest.$ac_ext -fi - - +rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext fi -{ echo "$as_me:$LINENO: result: $ac_cv_big_endian_double" >&5 -echo "${ECHO_T}$ac_cv_big_endian_double" >&6; } -if test "$ac_cv_big_endian_double" = yes -then +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_struct_addrinfo" >&5 +$as_echo "$ac_cv_struct_addrinfo" >&6; } +if test $ac_cv_struct_addrinfo = yes; then -cat >>confdefs.h <<\_ACEOF -#define DOUBLE_IS_BIG_ENDIAN_IEEE754 1 -_ACEOF +$as_echo "#define HAVE_ADDRINFO 1" >>confdefs.h fi -# Some ARM platforms use a mixed-endian representation for doubles. -# While Python doesn't currently have full support for these platforms -# (see e.g., issue 1762561), we can at least make sure that float <-> string -# conversions work. -{ echo "$as_me:$LINENO: checking whether C doubles are ARM mixed-endian IEEE 754 binary64" >&5 -echo $ECHO_N "checking whether C doubles are ARM mixed-endian IEEE 754 binary64... $ECHO_C" >&6; } -if test "${ac_cv_mixed_endian_double+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for sockaddr_storage" >&5 +$as_echo_n "checking for sockaddr_storage... " >&6; } +if test "${ac_cv_struct_sockaddr_storage+set}" = set; then : + $as_echo_n "(cached) " >&6 else - -if test "$cross_compiling" = yes; then - ac_cv_mixed_endian_double=no -else - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF + cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ -#include -int main() { - double x = 9006104071832581.0; - if (memcmp(&x, "\x01\xff\x3f\x43\x05\x04\x03\x02", 8) == 0) - return 0; - else - return 1; +# include +# include +int +main () +{ +struct sockaddr_storage s + ; + return 0; } - _ACEOF -rm -f conftest$ac_exeext -if { (ac_try="$ac_link" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_link") 2>&5 - ac_status=$? - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { ac_try='./conftest$ac_exeext' - { (case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_try") 2>&5 - ac_status=$? - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); }; }; then - ac_cv_mixed_endian_double=yes +if ac_fn_c_try_compile "$LINENO"; then : + ac_cv_struct_sockaddr_storage=yes else - echo "$as_me: program exited with status $ac_status" >&5 -echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - -( exit $ac_status ) -ac_cv_mixed_endian_double=no -fi -rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext conftest.$ac_objext conftest.$ac_ext + ac_cv_struct_sockaddr_storage=no fi - - +rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext fi -{ echo "$as_me:$LINENO: result: $ac_cv_mixed_endian_double" >&5 -echo "${ECHO_T}$ac_cv_mixed_endian_double" >&6; } -if test "$ac_cv_mixed_endian_double" = yes -then +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_struct_sockaddr_storage" >&5 +$as_echo "$ac_cv_struct_sockaddr_storage" >&6; } +if test $ac_cv_struct_sockaddr_storage = yes; then -cat >>confdefs.h <<\_ACEOF -#define DOUBLE_IS_ARM_MIXED_ENDIAN_IEEE754 1 -_ACEOF +$as_echo "#define HAVE_SOCKADDR_STORAGE 1" >>confdefs.h fi -# The short float repr introduced in Python 3.1 requires the -# correctly-rounded string <-> double conversion functions from -# Python/dtoa.c, which in turn require that the FPU uses 53-bit -# rounding; this is a problem on x86, where the x87 FPU has a default -# rounding precision of 64 bits. For gcc/x86, we can fix this by -# using inline assembler to get and set the x87 FPU control word. - -# This inline assembler syntax may also work for suncc and icc, -# so we try it on all platforms. +# checks for compiler characteristics -{ echo "$as_me:$LINENO: checking whether we can use gcc inline assembler to get and set x87 control word" >&5 -echo $ECHO_N "checking whether we can use gcc inline assembler to get and set x87 control word... $ECHO_C" >&6; } -cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking whether char is unsigned" >&5 +$as_echo_n "checking whether char is unsigned... " >&6; } +if test "${ac_cv_c_char_unsigned+set}" = set; then : + $as_echo_n "(cached) " >&6 +else + cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ - +$ac_includes_default int main () { - - unsigned short cw; - __asm__ __volatile__ ("fnstcw %0" : "=m" (cw)); - __asm__ __volatile__ ("fldcw %0" : : "m" (cw)); +static int test_array [1 - 2 * !(((char) -1) < 0)]; +test_array [0] = 0 ; return 0; } _ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - have_gcc_asm_for_x87=yes +if ac_fn_c_try_compile "$LINENO"; then : + ac_cv_c_char_unsigned=no else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - have_gcc_asm_for_x87=no + ac_cv_c_char_unsigned=yes fi - rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext -{ echo "$as_me:$LINENO: result: $have_gcc_asm_for_x87" >&5 -echo "${ECHO_T}$have_gcc_asm_for_x87" >&6; } -if test "$have_gcc_asm_for_x87" = yes -then - -cat >>confdefs.h <<\_ACEOF -#define HAVE_GCC_ASM_FOR_X87 1 -_ACEOF +fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_c_char_unsigned" >&5 +$as_echo "$ac_cv_c_char_unsigned" >&6; } +if test $ac_cv_c_char_unsigned = yes && test "$GCC" != yes; then + $as_echo "#define __CHAR_UNSIGNED__ 1" >>confdefs.h fi -# Detect whether system arithmetic is subject to x87-style double -# rounding issues. The result of this test has little meaning on non -# IEEE 754 platforms. On IEEE 754, test should return 1 if rounding -# mode is round-to-nearest and double rounding issues are present, and -# 0 otherwise. See http://bugs.python.org/issue2937 for more info. -{ echo "$as_me:$LINENO: checking for x87-style double rounding" >&5 -echo $ECHO_N "checking for x87-style double rounding... $ECHO_C" >&6; } -# $BASECFLAGS may affect the result -ac_save_cc="$CC" -CC="$CC $BASECFLAGS" -if test "$cross_compiling" = yes; then - ac_cv_x87_double_rounding=no +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for an ANSI C-conforming const" >&5 +$as_echo_n "checking for an ANSI C-conforming const... " >&6; } +if test "${ac_cv_c_const+set}" = set; then : + $as_echo_n "(cached) " >&6 else - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF + cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ -#include -#include -int main() { - volatile double x, y, z; - /* 1./(1-2**-53) -> 1+2**-52 (correct), 1.0 (double rounding) */ - x = 0.99999999999999989; /* 1-2**-53 */ - y = 1./x; - if (y != 1.) - exit(0); - /* 1e16+2.99999 -> 1e16+2. (correct), 1e16+4. (double rounding) */ - x = 1e16; - y = 2.99999; - z = x + y; - if (z != 1e16+4.) - exit(0); - /* both tests show evidence of double rounding */ - exit(1); -} +int +main () +{ +/* FIXME: Include the comments suggested by Paul. */ +#ifndef __cplusplus + /* Ultrix mips cc rejects this. */ + typedef int charset[2]; + const charset cs; + /* SunOS 4.1.1 cc rejects this. */ + char const *const *pcpcc; + char **ppc; + /* NEC SVR4.0.2 mips cc rejects this. */ + struct point {int x, y;}; + static struct point const zero = {0,0}; + /* AIX XL C 1.02.0.0 rejects this. + It does not let you subtract one const X* pointer from another in + an arm of an if-expression whose if-part is not a constant + expression */ + const char *g = "string"; + pcpcc = &g + (g ? g-g : 0); + /* HPUX 7.0 cc rejects these. */ + ++pcpcc; + ppc = (char**) pcpcc; + pcpcc = (char const *const *) ppc; + { /* SCO 3.2v4 cc rejects this. */ + char *t; + char const *s = 0 ? (char *) 0 : (char const *) 0; + + *t++ = 0; + if (s) return 0; + } + { /* Someone thinks the Sun supposedly-ANSI compiler will reject this. */ + int x[] = {25, 17}; + const int *foo = &x[0]; + ++foo; + } + { /* Sun SC1.0 ANSI compiler rejects this -- but not the above. */ + typedef const int *iptr; + iptr p = 0; + ++p; + } + { /* AIX XL C 1.02.0.0 rejects this saying + "k.c", line 2.27: 1506-025 (S) Operand must be a modifiable lvalue. */ + struct s { int j; const int *ap[3]; }; + struct s *b; b->j = 5; + } + { /* ULTRIX-32 V3.1 (Rev 9) vcc rejects this */ + const int foo = 10; + if (!foo) return 0; + } + return !cs[0] && !zero.x; +#endif + ; + return 0; +} _ACEOF -rm -f conftest$ac_exeext -if { (ac_try="$ac_link" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_link") 2>&5 - ac_status=$? - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { ac_try='./conftest$ac_exeext' - { (case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_try") 2>&5 - ac_status=$? - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); }; }; then - ac_cv_x87_double_rounding=no +if ac_fn_c_try_compile "$LINENO"; then : + ac_cv_c_const=yes else - echo "$as_me: program exited with status $ac_status" >&5 -echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - -( exit $ac_status ) -ac_cv_x87_double_rounding=yes + ac_cv_c_const=no fi -rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext conftest.$ac_objext conftest.$ac_ext +rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_c_const" >&5 +$as_echo "$ac_cv_c_const" >&6; } +if test $ac_cv_c_const = no; then - -CC="$ac_save_cc" -{ echo "$as_me:$LINENO: result: $ac_cv_x87_double_rounding" >&5 -echo "${ECHO_T}$ac_cv_x87_double_rounding" >&6; } -if test "$ac_cv_x87_double_rounding" = yes -then - -cat >>confdefs.h <<\_ACEOF -#define X87_DOUBLE_ROUNDING 1 -_ACEOF +$as_echo "#define const /**/" >>confdefs.h fi -# ************************************ -# * Check for mathematical functions * -# ************************************ -LIBS_SAVE=$LIBS -LIBS="$LIBS $LIBM" +works=no +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for working volatile" >&5 +$as_echo_n "checking for working volatile... " >&6; } +cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ -# On FreeBSD 6.2, it appears that tanh(-0.) returns 0. instead of -# -0. on some architectures. -{ echo "$as_me:$LINENO: checking whether tanh preserves the sign of zero" >&5 -echo $ECHO_N "checking whether tanh preserves the sign of zero... $ECHO_C" >&6; } -if test "${ac_cv_tanh_preserves_zero_sign+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 +int +main () +{ +volatile int x; x = 0; + ; + return 0; +} +_ACEOF +if ac_fn_c_try_compile "$LINENO"; then : + works=yes else -if test "$cross_compiling" = yes; then - ac_cv_tanh_preserves_zero_sign=no -else - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF +$as_echo "#define volatile /**/" >>confdefs.h + + +fi +rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $works" >&5 +$as_echo "$works" >&6; } + +works=no +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for working signed char" >&5 +$as_echo_n "checking for working signed char... " >&6; } +cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ -#include -#include -int main() { - /* return 0 if either negative zeros don't exist - on this platform or if negative zeros exist - and tanh(-0.) == -0. */ - if (atan2(0., -1.) == atan2(-0., -1.) || - atan2(tanh(-0.), -1.) == atan2(-0., -1.)) exit(0); - else exit(1); +int +main () +{ +signed char c; + ; + return 0; } - _ACEOF -rm -f conftest$ac_exeext -if { (ac_try="$ac_link" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_link") 2>&5 - ac_status=$? - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { ac_try='./conftest$ac_exeext' - { (case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_try") 2>&5 - ac_status=$? - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); }; }; then - ac_cv_tanh_preserves_zero_sign=yes +if ac_fn_c_try_compile "$LINENO"; then : + works=yes else - echo "$as_me: program exited with status $ac_status" >&5 -echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 -( exit $ac_status ) -ac_cv_tanh_preserves_zero_sign=no -fi -rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext conftest.$ac_objext conftest.$ac_ext -fi +$as_echo "#define signed /**/" >>confdefs.h fi +rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $works" >&5 +$as_echo "$works" >&6; } -{ echo "$as_me:$LINENO: result: $ac_cv_tanh_preserves_zero_sign" >&5 -echo "${ECHO_T}$ac_cv_tanh_preserves_zero_sign" >&6; } -if test "$ac_cv_tanh_preserves_zero_sign" = yes -then - -cat >>confdefs.h <<\_ACEOF -#define TANH_PRESERVES_ZERO_SIGN 1 +have_prototypes=no +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for prototypes" >&5 +$as_echo_n "checking for prototypes... " >&6; } +cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ +int foo(int x) { return 0; } +int +main () +{ +return foo(10); + ; + return 0; +} _ACEOF +if ac_fn_c_try_compile "$LINENO"; then : +$as_echo "#define HAVE_PROTOTYPES 1" >>confdefs.h + + have_prototypes=yes fi +rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $have_prototypes" >&5 +$as_echo "$have_prototypes" >&6; } +works=no +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for variable length prototypes and stdarg.h" >&5 +$as_echo_n "checking for variable length prototypes and stdarg.h... " >&6; } +cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ +#include +int foo(int x, ...) { + va_list va; + va_start(va, x); + va_arg(va, int); + va_arg(va, char *); + va_arg(va, double); + return 0; +} +int +main () +{ +return foo(10, "", 3.14); + ; + return 0; +} +_ACEOF +if ac_fn_c_try_compile "$LINENO"; then : +$as_echo "#define HAVE_STDARG_PROTOTYPES 1" >>confdefs.h + works=yes +fi +rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $works" >&5 +$as_echo "$works" >&6; } +# check for socketpair +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for socketpair" >&5 +$as_echo_n "checking for socketpair... " >&6; } +cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ +#include +#include -for ac_func in acosh asinh atanh copysign erf erfc expm1 finite gamma -do -as_ac_var=`echo "ac_cv_func_$ac_func" | $as_tr_sh` -{ echo "$as_me:$LINENO: checking for $ac_func" >&5 -echo $ECHO_N "checking for $ac_func... $ECHO_C" >&6; } -if { as_var=$as_ac_var; eval "test \"\${$as_var+set}\" = set"; }; then - echo $ECHO_N "(cached) $ECHO_C" >&6 -else - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ +int +main () +{ +void *x=socketpair + ; + return 0; +} _ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF +if ac_fn_c_try_compile "$LINENO"; then : + +$as_echo "#define HAVE_SOCKETPAIR 1" >>confdefs.h + + { $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +$as_echo "yes" >&6; } +else + { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 +$as_echo "no" >&6; } + +fi +rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext + +# check if sockaddr has sa_len member +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking if sockaddr has sa_len member" >&5 +$as_echo_n "checking if sockaddr has sa_len member... " >&6; } +cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ -/* Define $ac_func to an innocuous variant, in case declares $ac_func. - For example, HP-UX 11i declares gettimeofday. */ -#define $ac_func innocuous_$ac_func +#include +#include +int +main () +{ +struct sockaddr x; +x.sa_len = 0; + ; + return 0; +} +_ACEOF +if ac_fn_c_try_compile "$LINENO"; then : + { $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +$as_echo "yes" >&6; } -/* System header to define __stub macros and hopefully few prototypes, - which can conflict with char $ac_func (); below. - Prefer to if __STDC__ is defined, since - exists even on freestanding compilers. */ +$as_echo "#define HAVE_SOCKADDR_SA_LEN 1" >>confdefs.h -#ifdef __STDC__ -# include -#else -# include -#endif +else + { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 +$as_echo "no" >&6; } -#undef $ac_func +fi +rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext -/* Override any GCC internal prototype to avoid an error. - Use char because int might match the return type of a GCC - builtin and then its argument prototype would still apply. */ -#ifdef __cplusplus -extern "C" -#endif -char $ac_func (); -/* The GNU C library defines this for functions which it implements - to always fail with ENOSYS. Some functions are actually named - something starting with __ and the normal name is an alias. */ -#if defined __stub_$ac_func || defined __stub___$ac_func -choke me +va_list_is_array=no +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking whether va_list is an array" >&5 +$as_echo_n "checking whether va_list is an array... " >&6; } +cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + +#ifdef HAVE_STDARG_PROTOTYPES +#include +#else +#include #endif int main () { -return $ac_func (); +va_list list1, list2; list1 = list2; ; return 0; } _ACEOF -rm -f conftest.$ac_objext conftest$ac_exeext -if { (ac_try="$ac_link" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_link") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest$ac_exeext && - $as_test_x conftest$ac_exeext; then - eval "$as_ac_var=yes" +if ac_fn_c_try_compile "$LINENO"; then : + else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - eval "$as_ac_var=no" -fi -rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \ - conftest$ac_exeext conftest.$ac_ext -fi -ac_res=`eval echo '${'$as_ac_var'}'` - { echo "$as_me:$LINENO: result: $ac_res" >&5 -echo "${ECHO_T}$ac_res" >&6; } -if test `eval echo '${'$as_ac_var'}'` = yes; then - cat >>confdefs.h <<_ACEOF -#define `echo "HAVE_$ac_func" | $as_tr_cpp` 1 -_ACEOF +$as_echo "#define VA_LIST_IS_ARRAY 1" >>confdefs.h + + va_list_is_array=yes fi -done +rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $va_list_is_array" >&5 +$as_echo "$va_list_is_array" >&6; } +# sigh -- gethostbyname_r is a mess; it can have 3, 5 or 6 arguments :-( +ac_fn_c_check_func "$LINENO" "gethostbyname_r" "ac_cv_func_gethostbyname_r" +if test "x$ac_cv_func_gethostbyname_r" = x""yes; then : + $as_echo "#define HAVE_GETHOSTBYNAME_R 1" >>confdefs.h + { $as_echo "$as_me:${as_lineno-$LINENO}: checking gethostbyname_r with 6 args" >&5 +$as_echo_n "checking gethostbyname_r with 6 args... " >&6; } + OLD_CFLAGS=$CFLAGS + CFLAGS="$CFLAGS $MY_CPPFLAGS $MY_THREAD_CPPFLAGS $MY_CFLAGS" + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ -for ac_func in hypot lgamma log1p round tgamma -do -as_ac_var=`echo "ac_cv_func_$ac_func" | $as_tr_sh` -{ echo "$as_me:$LINENO: checking for $ac_func" >&5 -echo $ECHO_N "checking for $ac_func... $ECHO_C" >&6; } -if { as_var=$as_ac_var; eval "test \"\${$as_var+set}\" = set"; }; then - echo $ECHO_N "(cached) $ECHO_C" >&6 -else - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ +# include + +int +main () +{ + + char *name; + struct hostent *he, *res; + char buffer[2048]; + int buflen = 2048; + int h_errnop; + + (void) gethostbyname_r(name, he, buffer, buflen, &res, &h_errnop) + + ; + return 0; +} _ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -/* Define $ac_func to an innocuous variant, in case declares $ac_func. - For example, HP-UX 11i declares gettimeofday. */ -#define $ac_func innocuous_$ac_func +if ac_fn_c_try_compile "$LINENO"; then : -/* System header to define __stub macros and hopefully few prototypes, - which can conflict with char $ac_func (); below. - Prefer to if __STDC__ is defined, since - exists even on freestanding compilers. */ + $as_echo "#define HAVE_GETHOSTBYNAME_R 1" >>confdefs.h -#ifdef __STDC__ -# include -#else -# include -#endif -#undef $ac_func +$as_echo "#define HAVE_GETHOSTBYNAME_R_6_ARG 1" >>confdefs.h -/* Override any GCC internal prototype to avoid an error. - Use char because int might match the return type of a GCC - builtin and then its argument prototype would still apply. */ -#ifdef __cplusplus -extern "C" -#endif -char $ac_func (); -/* The GNU C library defines this for functions which it implements - to always fail with ENOSYS. Some functions are actually named - something starting with __ and the normal name is an alias. */ -#if defined __stub_$ac_func || defined __stub___$ac_func -choke me -#endif + { $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +$as_echo "yes" >&6; } + +else + + { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 +$as_echo "no" >&6; } + { $as_echo "$as_me:${as_lineno-$LINENO}: checking gethostbyname_r with 5 args" >&5 +$as_echo_n "checking gethostbyname_r with 5 args... " >&6; } + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + +# include int main () { -return $ac_func (); + + char *name; + struct hostent *he; + char buffer[2048]; + int buflen = 2048; + int h_errnop; + + (void) gethostbyname_r(name, he, buffer, buflen, &h_errnop) + ; return 0; } _ACEOF -rm -f conftest.$ac_objext conftest$ac_exeext -if { (ac_try="$ac_link" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_link") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest$ac_exeext && - $as_test_x conftest$ac_exeext; then - eval "$as_ac_var=yes" -else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 +if ac_fn_c_try_compile "$LINENO"; then : - eval "$as_ac_var=no" -fi + $as_echo "#define HAVE_GETHOSTBYNAME_R 1" >>confdefs.h -rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \ - conftest$ac_exeext conftest.$ac_ext -fi -ac_res=`eval echo '${'$as_ac_var'}'` - { echo "$as_me:$LINENO: result: $ac_res" >&5 -echo "${ECHO_T}$ac_res" >&6; } -if test `eval echo '${'$as_ac_var'}'` = yes; then - cat >>confdefs.h <<_ACEOF -#define `echo "HAVE_$ac_func" | $as_tr_cpp` 1 -_ACEOF -fi -done +$as_echo "#define HAVE_GETHOSTBYNAME_R_5_ARG 1" >>confdefs.h + + { $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +$as_echo "yes" >&6; } -{ echo "$as_me:$LINENO: checking whether isinf is declared" >&5 -echo $ECHO_N "checking whether isinf is declared... $ECHO_C" >&6; } -if test "${ac_cv_have_decl_isinf+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 else - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF + + { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 +$as_echo "no" >&6; } + { $as_echo "$as_me:${as_lineno-$LINENO}: checking gethostbyname_r with 3 args" >&5 +$as_echo_n "checking gethostbyname_r with 3 args... " >&6; } + cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ -#include + +# include int main () { -#ifndef isinf - (void) isinf; -#endif + + char *name; + struct hostent *he; + struct hostent_data data; + + (void) gethostbyname_r(name, he, &data); ; return 0; } _ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - ac_cv_have_decl_isinf=yes +if ac_fn_c_try_compile "$LINENO"; then : + + $as_echo "#define HAVE_GETHOSTBYNAME_R 1" >>confdefs.h + + +$as_echo "#define HAVE_GETHOSTBYNAME_R_3_ARG 1" >>confdefs.h + + { $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +$as_echo "yes" >&6; } + else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - ac_cv_have_decl_isinf=no -fi + { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 +$as_echo "no" >&6; } -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext fi -{ echo "$as_me:$LINENO: result: $ac_cv_have_decl_isinf" >&5 -echo "${ECHO_T}$ac_cv_have_decl_isinf" >&6; } -if test $ac_cv_have_decl_isinf = yes; then +rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext -cat >>confdefs.h <<_ACEOF -#define HAVE_DECL_ISINF 1 -_ACEOF +fi +rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext +fi +rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext + CFLAGS=$OLD_CFLAGS else + + for ac_func in gethostbyname +do : + ac_fn_c_check_func "$LINENO" "gethostbyname" "ac_cv_func_gethostbyname" +if test "x$ac_cv_func_gethostbyname" = x""yes; then : cat >>confdefs.h <<_ACEOF -#define HAVE_DECL_ISINF 0 +#define HAVE_GETHOSTBYNAME 1 _ACEOF +fi +done + fi -{ echo "$as_me:$LINENO: checking whether isnan is declared" >&5 -echo $ECHO_N "checking whether isnan is declared... $ECHO_C" >&6; } -if test "${ac_cv_have_decl_isnan+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 + + + + + + + +# checks for system services +# (none yet) + +# Linux requires this for correct f.p. operations +ac_fn_c_check_func "$LINENO" "__fpu_control" "ac_cv_func___fpu_control" +if test "x$ac_cv_func___fpu_control" = x""yes; then : + else - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF + { $as_echo "$as_me:${as_lineno-$LINENO}: checking for __fpu_control in -lieee" >&5 +$as_echo_n "checking for __fpu_control in -lieee... " >&6; } +if test "${ac_cv_lib_ieee___fpu_control+set}" = set; then : + $as_echo_n "(cached) " >&6 +else + ac_check_lib_save_LIBS=$LIBS +LIBS="-lieee $LIBS" +cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ -#include +/* Override any GCC internal prototype to avoid an error. + Use char because int might match the return type of a GCC + builtin and then its argument prototype would still apply. */ +#ifdef __cplusplus +extern "C" +#endif +char __fpu_control (); int main () { -#ifndef isnan - (void) isnan; -#endif - +return __fpu_control (); ; return 0; } _ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - ac_cv_have_decl_isnan=yes +if ac_fn_c_try_link "$LINENO"; then : + ac_cv_lib_ieee___fpu_control=yes else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 + ac_cv_lib_ieee___fpu_control=no +fi +rm -f core conftest.err conftest.$ac_objext \ + conftest$ac_exeext conftest.$ac_ext +LIBS=$ac_check_lib_save_LIBS +fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_lib_ieee___fpu_control" >&5 +$as_echo "$ac_cv_lib_ieee___fpu_control" >&6; } +if test "x$ac_cv_lib_ieee___fpu_control" = x""yes; then : + cat >>confdefs.h <<_ACEOF +#define HAVE_LIBIEEE 1 +_ACEOF + + LIBS="-lieee $LIBS" - ac_cv_have_decl_isnan=no fi -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext + fi -{ echo "$as_me:$LINENO: result: $ac_cv_have_decl_isnan" >&5 -echo "${ECHO_T}$ac_cv_have_decl_isnan" >&6; } -if test $ac_cv_have_decl_isnan = yes; then -cat >>confdefs.h <<_ACEOF -#define HAVE_DECL_ISNAN 1 -_ACEOF +# Check for --with-fpectl +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for --with-fpectl" >&5 +$as_echo_n "checking for --with-fpectl... " >&6; } -else - cat >>confdefs.h <<_ACEOF -#define HAVE_DECL_ISNAN 0 -_ACEOF +# Check whether --with-fpectl was given. +if test "${with_fpectl+set}" = set; then : + withval=$with_fpectl; +if test "$withval" != no +then +$as_echo "#define WANT_SIGFPE_HANDLER 1" >>confdefs.h + { $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +$as_echo "yes" >&6; } +else { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 +$as_echo "no" >&6; } fi -{ echo "$as_me:$LINENO: checking whether isfinite is declared" >&5 -echo $ECHO_N "checking whether isfinite is declared... $ECHO_C" >&6; } -if test "${ac_cv_have_decl_isfinite+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 else - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -#include + { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 +$as_echo "no" >&6; } +fi -int -main () -{ -#ifndef isfinite - (void) isfinite; -#endif - ; - return 0; -} -_ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; +# check for --with-libm=... + +case $ac_sys_system in +Darwin) ;; +*) LIBM=-lm esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - ac_cv_have_decl_isfinite=yes -else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for --with-libm=STRING" >&5 +$as_echo_n "checking for --with-libm=STRING... " >&6; } - ac_cv_have_decl_isfinite=no +# Check whether --with-libm was given. +if test "${with_libm+set}" = set; then : + withval=$with_libm; +if test "$withval" = no +then LIBM= + { $as_echo "$as_me:${as_lineno-$LINENO}: result: force LIBM empty" >&5 +$as_echo "force LIBM empty" >&6; } +elif test "$withval" != yes +then LIBM=$withval + { $as_echo "$as_me:${as_lineno-$LINENO}: result: set LIBM=\"$withval\"" >&5 +$as_echo "set LIBM=\"$withval\"" >&6; } +else as_fn_error "proper usage is --with-libm=STRING" "$LINENO" 5 +fi +else + { $as_echo "$as_me:${as_lineno-$LINENO}: result: default LIBM=\"$LIBM\"" >&5 +$as_echo "default LIBM=\"$LIBM\"" >&6; } fi -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext + +# check for --with-libc=... + +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for --with-libc=STRING" >&5 +$as_echo_n "checking for --with-libc=STRING... " >&6; } + +# Check whether --with-libc was given. +if test "${with_libc+set}" = set; then : + withval=$with_libc; +if test "$withval" = no +then LIBC= + { $as_echo "$as_me:${as_lineno-$LINENO}: result: force LIBC empty" >&5 +$as_echo "force LIBC empty" >&6; } +elif test "$withval" != yes +then LIBC=$withval + { $as_echo "$as_me:${as_lineno-$LINENO}: result: set LIBC=\"$withval\"" >&5 +$as_echo "set LIBC=\"$withval\"" >&6; } +else as_fn_error "proper usage is --with-libc=STRING" "$LINENO" 5 +fi +else + { $as_echo "$as_me:${as_lineno-$LINENO}: result: default LIBC=\"$LIBC\"" >&5 +$as_echo "default LIBC=\"$LIBC\"" >&6; } fi -{ echo "$as_me:$LINENO: result: $ac_cv_have_decl_isfinite" >&5 -echo "${ECHO_T}$ac_cv_have_decl_isfinite" >&6; } -if test $ac_cv_have_decl_isfinite = yes; then -cat >>confdefs.h <<_ACEOF -#define HAVE_DECL_ISFINITE 1 -_ACEOF +# ************************************************** +# * Check for various properties of floating point * +# ************************************************** +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking whether C doubles are little-endian IEEE 754 binary64" >&5 +$as_echo_n "checking whether C doubles are little-endian IEEE 754 binary64... " >&6; } +if test "${ac_cv_little_endian_double+set}" = set; then : + $as_echo_n "(cached) " >&6 else - cat >>confdefs.h <<_ACEOF -#define HAVE_DECL_ISFINITE 0 -_ACEOF +if test "$cross_compiling" = yes; then : + ac_cv_little_endian_double=no +else + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + +#include +int main() { + double x = 9006104071832581.0; + if (memcmp(&x, "\x05\x04\x03\x02\x01\xff\x3f\x43", 8) == 0) + return 0; + else + return 1; +} + +_ACEOF +if ac_fn_c_try_run "$LINENO"; then : + ac_cv_little_endian_double=yes +else + ac_cv_little_endian_double=no +fi +rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext \ + conftest.$ac_objext conftest.beam conftest.$ac_ext +fi fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_little_endian_double" >&5 +$as_echo "$ac_cv_little_endian_double" >&6; } +if test "$ac_cv_little_endian_double" = yes +then +$as_echo "#define DOUBLE_IS_LITTLE_ENDIAN_IEEE754 1" >>confdefs.h -LIBS=$LIBS_SAVE +fi -# For multiprocessing module, check that sem_open -# actually works. For FreeBSD versions <= 7.2, -# the kernel module that provides POSIX semaphores -# isn't loaded by default, so an attempt to call -# sem_open results in a 'Signal 12' error. -{ echo "$as_me:$LINENO: checking whether POSIX semaphores are enabled" >&5 -echo $ECHO_N "checking whether POSIX semaphores are enabled... $ECHO_C" >&6; } -if test "${ac_cv_posix_semaphores_enabled+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking whether C doubles are big-endian IEEE 754 binary64" >&5 +$as_echo_n "checking whether C doubles are big-endian IEEE 754 binary64... " >&6; } +if test "${ac_cv_big_endian_double+set}" = set; then : + $as_echo_n "(cached) " >&6 else - if test "$cross_compiling" = yes; then - ac_cv_posix_semaphores_enabled=yes + +if test "$cross_compiling" = yes; then : + ac_cv_big_endian_double=no else - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF + cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ -#include -#include -#include -#include -#include - -int main(void) { - sem_t *a = sem_open("/autoconf", O_CREAT, S_IRUSR|S_IWUSR, 0); - if (a == SEM_FAILED) { - perror("sem_open"); - return 1; - } - sem_close(a); - sem_unlink("/autoconf"); - return 0; +#include +int main() { + double x = 9006104071832581.0; + if (memcmp(&x, "\x43\x3f\xff\x01\x02\x03\x04\x05", 8) == 0) + return 0; + else + return 1; } _ACEOF -rm -f conftest$ac_exeext -if { (ac_try="$ac_link" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_link") 2>&5 - ac_status=$? - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { ac_try='./conftest$ac_exeext' - { (case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_try") 2>&5 - ac_status=$? - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); }; }; then - ac_cv_posix_semaphores_enabled=yes +if ac_fn_c_try_run "$LINENO"; then : + ac_cv_big_endian_double=yes else - echo "$as_me: program exited with status $ac_status" >&5 -echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - -( exit $ac_status ) -ac_cv_posix_semaphores_enabled=no + ac_cv_big_endian_double=no fi -rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext conftest.$ac_objext conftest.$ac_ext +rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext \ + conftest.$ac_objext conftest.beam conftest.$ac_ext fi - - fi -{ echo "$as_me:$LINENO: result: $ac_cv_posix_semaphores_enabled" >&5 -echo "${ECHO_T}$ac_cv_posix_semaphores_enabled" >&6; } -if test $ac_cv_posix_semaphores_enabled = no +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_big_endian_double" >&5 +$as_echo "$ac_cv_big_endian_double" >&6; } +if test "$ac_cv_big_endian_double" = yes then -cat >>confdefs.h <<\_ACEOF -#define POSIX_SEMAPHORES_NOT_ENABLED 1 -_ACEOF +$as_echo "#define DOUBLE_IS_BIG_ENDIAN_IEEE754 1" >>confdefs.h fi -# Multiprocessing check for broken sem_getvalue -{ echo "$as_me:$LINENO: checking for broken sem_getvalue" >&5 -echo $ECHO_N "checking for broken sem_getvalue... $ECHO_C" >&6; } -if test "${ac_cv_broken_sem_getvalue+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 +# Some ARM platforms use a mixed-endian representation for doubles. +# While Python doesn't currently have full support for these platforms +# (see e.g., issue 1762561), we can at least make sure that float <-> string +# conversions work. +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking whether C doubles are ARM mixed-endian IEEE 754 binary64" >&5 +$as_echo_n "checking whether C doubles are ARM mixed-endian IEEE 754 binary64... " >&6; } +if test "${ac_cv_mixed_endian_double+set}" = set; then : + $as_echo_n "(cached) " >&6 else - if test "$cross_compiling" = yes; then - ac_cv_broken_sem_getvalue=yes + +if test "$cross_compiling" = yes; then : + ac_cv_mixed_endian_double=no else - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF + cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ -#include -#include -#include -#include -#include - -int main(void){ - sem_t *a = sem_open("/autocftw", O_CREAT, S_IRUSR|S_IWUSR, 0); - int count; - int res; - if(a==SEM_FAILED){ - perror("sem_open"); - return 1; - - } - res = sem_getvalue(a, &count); - sem_close(a); - sem_unlink("/autocftw"); - return res==-1 ? 1 : 0; +#include +int main() { + double x = 9006104071832581.0; + if (memcmp(&x, "\x01\xff\x3f\x43\x05\x04\x03\x02", 8) == 0) + return 0; + else + return 1; } _ACEOF -rm -f conftest$ac_exeext -if { (ac_try="$ac_link" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_link") 2>&5 - ac_status=$? - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { ac_try='./conftest$ac_exeext' - { (case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_try") 2>&5 - ac_status=$? - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); }; }; then - ac_cv_broken_sem_getvalue=no +if ac_fn_c_try_run "$LINENO"; then : + ac_cv_mixed_endian_double=yes else - echo "$as_me: program exited with status $ac_status" >&5 -echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - -( exit $ac_status ) -ac_cv_broken_sem_getvalue=yes + ac_cv_mixed_endian_double=no fi -rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext conftest.$ac_objext conftest.$ac_ext +rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext \ + conftest.$ac_objext conftest.beam conftest.$ac_ext fi - - fi -{ echo "$as_me:$LINENO: result: $ac_cv_broken_sem_getvalue" >&5 -echo "${ECHO_T}$ac_cv_broken_sem_getvalue" >&6; } -if test $ac_cv_broken_sem_getvalue = yes +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_mixed_endian_double" >&5 +$as_echo "$ac_cv_mixed_endian_double" >&6; } +if test "$ac_cv_mixed_endian_double" = yes then -cat >>confdefs.h <<\_ACEOF -#define HAVE_BROKEN_SEM_GETVALUE 1 -_ACEOF +$as_echo "#define DOUBLE_IS_ARM_MIXED_ENDIAN_IEEE754 1" >>confdefs.h fi -# determine what size digit to use for Python's longs -{ echo "$as_me:$LINENO: checking digit size for Python's longs" >&5 -echo $ECHO_N "checking digit size for Python's longs... $ECHO_C" >&6; } -# Check whether --enable-big-digits was given. -if test "${enable_big_digits+set}" = set; then - enableval=$enable_big_digits; case $enable_big_digits in -yes) - enable_big_digits=30 ;; -no) - enable_big_digits=15 ;; -15|30) - ;; -*) - { { echo "$as_me:$LINENO: error: bad value $enable_big_digits for --enable-big-digits; value should be 15 or 30" >&5 -echo "$as_me: error: bad value $enable_big_digits for --enable-big-digits; value should be 15 or 30" >&2;} - { (exit 1); exit 1; }; } ;; -esac -{ echo "$as_me:$LINENO: result: $enable_big_digits" >&5 -echo "${ECHO_T}$enable_big_digits" >&6; } +# The short float repr introduced in Python 3.1 requires the +# correctly-rounded string <-> double conversion functions from +# Python/dtoa.c, which in turn require that the FPU uses 53-bit +# rounding; this is a problem on x86, where the x87 FPU has a default +# rounding precision of 64 bits. For gcc/x86, we can fix this by +# using inline assembler to get and set the x87 FPU control word. -cat >>confdefs.h <<_ACEOF -#define PYLONG_BITS_IN_DIGIT $enable_big_digits -_ACEOF +# This inline assembler syntax may also work for suncc and icc, +# so we try it on all platforms. + +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking whether we can use gcc inline assembler to get and set x87 control word" >&5 +$as_echo_n "checking whether we can use gcc inline assembler to get and set x87 control word... " >&6; } +cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + +int +main () +{ + unsigned short cw; + __asm__ __volatile__ ("fnstcw %0" : "=m" (cw)); + __asm__ __volatile__ ("fldcw %0" : : "m" (cw)); + ; + return 0; +} +_ACEOF +if ac_fn_c_try_compile "$LINENO"; then : + have_gcc_asm_for_x87=yes else - { echo "$as_me:$LINENO: result: no value specified" >&5 -echo "${ECHO_T}no value specified" >&6; } + have_gcc_asm_for_x87=no fi +rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $have_gcc_asm_for_x87" >&5 +$as_echo "$have_gcc_asm_for_x87" >&6; } +if test "$have_gcc_asm_for_x87" = yes +then +$as_echo "#define HAVE_GCC_ASM_FOR_X87 1" >>confdefs.h -# check for wchar.h -if test "${ac_cv_header_wchar_h+set}" = set; then - { echo "$as_me:$LINENO: checking for wchar.h" >&5 -echo $ECHO_N "checking for wchar.h... $ECHO_C" >&6; } -if test "${ac_cv_header_wchar_h+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 fi -{ echo "$as_me:$LINENO: result: $ac_cv_header_wchar_h" >&5 -echo "${ECHO_T}$ac_cv_header_wchar_h" >&6; } + +# Detect whether system arithmetic is subject to x87-style double +# rounding issues. The result of this test has little meaning on non +# IEEE 754 platforms. On IEEE 754, test should return 1 if rounding +# mode is round-to-nearest and double rounding issues are present, and +# 0 otherwise. See http://bugs.python.org/issue2937 for more info. +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for x87-style double rounding" >&5 +$as_echo_n "checking for x87-style double rounding... " >&6; } +# $BASECFLAGS may affect the result +ac_save_cc="$CC" +CC="$CC $BASECFLAGS" +if test "$cross_compiling" = yes; then : + ac_cv_x87_double_rounding=no else - # Is the header compilable? -{ echo "$as_me:$LINENO: checking wchar.h usability" >&5 -echo $ECHO_N "checking wchar.h usability... $ECHO_C" >&6; } -cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF + cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ -$ac_includes_default -#include -_ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - ac_header_compiler=yes -else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - ac_header_compiler=no -fi - -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext -{ echo "$as_me:$LINENO: result: $ac_header_compiler" >&5 -echo "${ECHO_T}$ac_header_compiler" >&6; } +#include +#include +int main() { + volatile double x, y, z; + /* 1./(1-2**-53) -> 1+2**-52 (correct), 1.0 (double rounding) */ + x = 0.99999999999999989; /* 1-2**-53 */ + y = 1./x; + if (y != 1.) + exit(0); + /* 1e16+2.99999 -> 1e16+2. (correct), 1e16+4. (double rounding) */ + x = 1e16; + y = 2.99999; + z = x + y; + if (z != 1e16+4.) + exit(0); + /* both tests show evidence of double rounding */ + exit(1); +} -# Is the header present? -{ echo "$as_me:$LINENO: checking wchar.h presence" >&5 -echo $ECHO_N "checking wchar.h presence... $ECHO_C" >&6; } -cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -#include _ACEOF -if { (ac_try="$ac_cpp conftest.$ac_ext" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_cpp conftest.$ac_ext") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } >/dev/null && { - test -z "$ac_c_preproc_warn_flag$ac_c_werror_flag" || - test ! -s conftest.err - }; then - ac_header_preproc=yes +if ac_fn_c_try_run "$LINENO"; then : + ac_cv_x87_double_rounding=no else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - ac_header_preproc=no + ac_cv_x87_double_rounding=yes +fi +rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext \ + conftest.$ac_objext conftest.beam conftest.$ac_ext fi -rm -f conftest.err conftest.$ac_ext -{ echo "$as_me:$LINENO: result: $ac_header_preproc" >&5 -echo "${ECHO_T}$ac_header_preproc" >&6; } +CC="$ac_save_cc" +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_x87_double_rounding" >&5 +$as_echo "$ac_cv_x87_double_rounding" >&6; } +if test "$ac_cv_x87_double_rounding" = yes +then -# So? What about this header? -case $ac_header_compiler:$ac_header_preproc:$ac_c_preproc_warn_flag in - yes:no: ) - { echo "$as_me:$LINENO: WARNING: wchar.h: accepted by the compiler, rejected by the preprocessor!" >&5 -echo "$as_me: WARNING: wchar.h: accepted by the compiler, rejected by the preprocessor!" >&2;} - { echo "$as_me:$LINENO: WARNING: wchar.h: proceeding with the compiler's result" >&5 -echo "$as_me: WARNING: wchar.h: proceeding with the compiler's result" >&2;} - ac_header_preproc=yes - ;; - no:yes:* ) - { echo "$as_me:$LINENO: WARNING: wchar.h: present but cannot be compiled" >&5 -echo "$as_me: WARNING: wchar.h: present but cannot be compiled" >&2;} - { echo "$as_me:$LINENO: WARNING: wchar.h: check for missing prerequisite headers?" >&5 -echo "$as_me: WARNING: wchar.h: check for missing prerequisite headers?" >&2;} - { echo "$as_me:$LINENO: WARNING: wchar.h: see the Autoconf documentation" >&5 -echo "$as_me: WARNING: wchar.h: see the Autoconf documentation" >&2;} - { echo "$as_me:$LINENO: WARNING: wchar.h: section \"Present But Cannot Be Compiled\"" >&5 -echo "$as_me: WARNING: wchar.h: section \"Present But Cannot Be Compiled\"" >&2;} - { echo "$as_me:$LINENO: WARNING: wchar.h: proceeding with the preprocessor's result" >&5 -echo "$as_me: WARNING: wchar.h: proceeding with the preprocessor's result" >&2;} - { echo "$as_me:$LINENO: WARNING: wchar.h: in the future, the compiler will take precedence" >&5 -echo "$as_me: WARNING: wchar.h: in the future, the compiler will take precedence" >&2;} - ( cat <<\_ASBOX -## -------------------------------------- ## -## Report this to http://bugs.python.org/ ## -## -------------------------------------- ## -_ASBOX - ) | sed "s/^/$as_me: WARNING: /" >&2 - ;; -esac -{ echo "$as_me:$LINENO: checking for wchar.h" >&5 -echo $ECHO_N "checking for wchar.h... $ECHO_C" >&6; } -if test "${ac_cv_header_wchar_h+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 -else - ac_cv_header_wchar_h=$ac_header_preproc -fi -{ echo "$as_me:$LINENO: result: $ac_cv_header_wchar_h" >&5 -echo "${ECHO_T}$ac_cv_header_wchar_h" >&6; } +$as_echo "#define X87_DOUBLE_ROUNDING 1" >>confdefs.h fi -if test $ac_cv_header_wchar_h = yes; then +# ************************************ +# * Check for mathematical functions * +# ************************************ -cat >>confdefs.h <<\_ACEOF -#define HAVE_WCHAR_H 1 -_ACEOF - - wchar_h="yes" +LIBS_SAVE=$LIBS +LIBS="$LIBS $LIBM" +# On FreeBSD 6.2, it appears that tanh(-0.) returns 0. instead of +# -0. on some architectures. +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking whether tanh preserves the sign of zero" >&5 +$as_echo_n "checking whether tanh preserves the sign of zero... " >&6; } +if test "${ac_cv_tanh_preserves_zero_sign+set}" = set; then : + $as_echo_n "(cached) " >&6 else - wchar_h="no" - -fi - - -# determine wchar_t size -if test "$wchar_h" = yes -then - { echo "$as_me:$LINENO: checking for wchar_t" >&5 -echo $ECHO_N "checking for wchar_t... $ECHO_C" >&6; } -if test "${ac_cv_type_wchar_t+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 +if test "$cross_compiling" = yes; then : + ac_cv_tanh_preserves_zero_sign=no else - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF + cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ -#include -typedef wchar_t ac__type_new_; -int -main () -{ -if ((ac__type_new_ *) 0) - return 0; -if (sizeof (ac__type_new_)) - return 0; - ; - return 0; +#include +#include +int main() { + /* return 0 if either negative zeros don't exist + on this platform or if negative zeros exist + and tanh(-0.) == -0. */ + if (atan2(0., -1.) == atan2(-0., -1.) || + atan2(tanh(-0.), -1.) == atan2(-0., -1.)) exit(0); + else exit(1); } + _ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - ac_cv_type_wchar_t=yes +if ac_fn_c_try_run "$LINENO"; then : + ac_cv_tanh_preserves_zero_sign=yes else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 + ac_cv_tanh_preserves_zero_sign=no +fi +rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext \ + conftest.$ac_objext conftest.beam conftest.$ac_ext +fi - ac_cv_type_wchar_t=no fi -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_tanh_preserves_zero_sign" >&5 +$as_echo "$ac_cv_tanh_preserves_zero_sign" >&6; } +if test "$ac_cv_tanh_preserves_zero_sign" = yes +then + +$as_echo "#define TANH_PRESERVES_ZERO_SIGN 1" >>confdefs.h + fi -{ echo "$as_me:$LINENO: result: $ac_cv_type_wchar_t" >&5 -echo "${ECHO_T}$ac_cv_type_wchar_t" >&6; } -# The cast to long int works around a bug in the HP C Compiler -# version HP92453-01 B.11.11.23709.GP, which incorrectly rejects -# declarations like `int a3[[(sizeof (unsigned char)) >= 0]];'. -# This bug is HP SR number 8606223364. -{ echo "$as_me:$LINENO: checking size of wchar_t" >&5 -echo $ECHO_N "checking size of wchar_t... $ECHO_C" >&6; } -if test "${ac_cv_sizeof_wchar_t+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 -else - if test "$cross_compiling" = yes; then - # Depending upon the size, compute the lo and hi bounds. -cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ +for ac_func in acosh asinh atanh copysign erf erfc expm1 finite gamma +do : + as_ac_var=`$as_echo "ac_cv_func_$ac_func" | $as_tr_sh` +ac_fn_c_check_func "$LINENO" "$ac_func" "$as_ac_var" +eval as_val=\$$as_ac_var + if test "x$as_val" = x""yes; then : + cat >>confdefs.h <<_ACEOF +#define `$as_echo "HAVE_$ac_func" | $as_tr_cpp` 1 _ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -#include - typedef wchar_t ac__type_sizeof_; -int -main () -{ -static int test_array [1 - 2 * !(((long int) (sizeof (ac__type_sizeof_))) >= 0)]; -test_array [0] = 0 +fi +done - ; - return 0; -} -_ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - ac_lo=0 ac_mid=0 - while :; do - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ +for ac_func in hypot lgamma log1p round tgamma +do : + as_ac_var=`$as_echo "ac_cv_func_$ac_func" | $as_tr_sh` +ac_fn_c_check_func "$LINENO" "$ac_func" "$as_ac_var" +eval as_val=\$$as_ac_var + if test "x$as_val" = x""yes; then : + cat >>confdefs.h <<_ACEOF +#define `$as_echo "HAVE_$ac_func" | $as_tr_cpp` 1 _ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -#include - typedef wchar_t ac__type_sizeof_; -int -main () -{ -static int test_array [1 - 2 * !(((long int) (sizeof (ac__type_sizeof_))) <= $ac_mid)]; -test_array [0] = 0 +fi +done - ; - return 0; -} -_ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - ac_hi=$ac_mid; break +ac_fn_c_check_decl "$LINENO" "isinf" "ac_cv_have_decl_isinf" "#include +" +if test "x$ac_cv_have_decl_isinf" = x""yes; then : + ac_have_decl=1 else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 + ac_have_decl=0 +fi - ac_lo=`expr $ac_mid + 1` - if test $ac_lo -le $ac_mid; then - ac_lo= ac_hi= - break - fi - ac_mid=`expr 2 '*' $ac_mid + 1` +cat >>confdefs.h <<_ACEOF +#define HAVE_DECL_ISINF $ac_have_decl +_ACEOF +ac_fn_c_check_decl "$LINENO" "isnan" "ac_cv_have_decl_isnan" "#include +" +if test "x$ac_cv_have_decl_isnan" = x""yes; then : + ac_have_decl=1 +else + ac_have_decl=0 fi -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext - done +cat >>confdefs.h <<_ACEOF +#define HAVE_DECL_ISNAN $ac_have_decl +_ACEOF +ac_fn_c_check_decl "$LINENO" "isfinite" "ac_cv_have_decl_isfinite" "#include +" +if test "x$ac_cv_have_decl_isfinite" = x""yes; then : + ac_have_decl=1 else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 + ac_have_decl=0 +fi - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ +cat >>confdefs.h <<_ACEOF +#define HAVE_DECL_ISFINITE $ac_have_decl _ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -#include - typedef wchar_t ac__type_sizeof_; -int -main () -{ -static int test_array [1 - 2 * !(((long int) (sizeof (ac__type_sizeof_))) < 0)]; -test_array [0] = 0 - ; - return 0; -} -_ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - ac_hi=-1 ac_mid=-1 - while :; do - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF +LIBS=$LIBS_SAVE + +# For multiprocessing module, check that sem_open +# actually works. For FreeBSD versions <= 7.2, +# the kernel module that provides POSIX semaphores +# isn't loaded by default, so an attempt to call +# sem_open results in a 'Signal 12' error. +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking whether POSIX semaphores are enabled" >&5 +$as_echo_n "checking whether POSIX semaphores are enabled... " >&6; } +if test "${ac_cv_posix_semaphores_enabled+set}" = set; then : + $as_echo_n "(cached) " >&6 +else + if test "$cross_compiling" = yes; then : + ac_cv_posix_semaphores_enabled=yes +else + cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ -#include - typedef wchar_t ac__type_sizeof_; -int -main () -{ -static int test_array [1 - 2 * !(((long int) (sizeof (ac__type_sizeof_))) >= $ac_mid)]; -test_array [0] = 0 +#include +#include +#include +#include +#include - ; +int main(void) { + sem_t *a = sem_open("/autoconf", O_CREAT, S_IRUSR|S_IWUSR, 0); + if (a == SEM_FAILED) { + perror("sem_open"); + return 1; + } + sem_close(a); + sem_unlink("/autoconf"); return 0; } + _ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - ac_lo=$ac_mid; break +if ac_fn_c_try_run "$LINENO"; then : + ac_cv_posix_semaphores_enabled=yes else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - ac_hi=`expr '(' $ac_mid ')' - 1` - if test $ac_mid -le $ac_hi; then - ac_lo= ac_hi= - break - fi - ac_mid=`expr 2 '*' $ac_mid` + ac_cv_posix_semaphores_enabled=no +fi +rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext \ + conftest.$ac_objext conftest.beam conftest.$ac_ext fi -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext - done -else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - ac_lo= ac_hi= fi -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_posix_semaphores_enabled" >&5 +$as_echo "$ac_cv_posix_semaphores_enabled" >&6; } +if test $ac_cv_posix_semaphores_enabled = no +then + +$as_echo "#define POSIX_SEMAPHORES_NOT_ENABLED 1" >>confdefs.h + fi -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext -# Binary search between lo and hi bounds. -while test "x$ac_lo" != "x$ac_hi"; do - ac_mid=`expr '(' $ac_hi - $ac_lo ')' / 2 + $ac_lo` - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF +# Multiprocessing check for broken sem_getvalue +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for broken sem_getvalue" >&5 +$as_echo_n "checking for broken sem_getvalue... " >&6; } +if test "${ac_cv_broken_sem_getvalue+set}" = set; then : + $as_echo_n "(cached) " >&6 +else + if test "$cross_compiling" = yes; then : + ac_cv_broken_sem_getvalue=yes +else + cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ -#include - typedef wchar_t ac__type_sizeof_; -int -main () -{ -static int test_array [1 - 2 * !(((long int) (sizeof (ac__type_sizeof_))) <= $ac_mid)]; -test_array [0] = 0 +#include +#include +#include +#include +#include - ; - return 0; +int main(void){ + sem_t *a = sem_open("/autocftw", O_CREAT, S_IRUSR|S_IWUSR, 0); + int count; + int res; + if(a==SEM_FAILED){ + perror("sem_open"); + return 1; + + } + res = sem_getvalue(a, &count); + sem_close(a); + sem_unlink("/autocftw"); + return res==-1 ? 1 : 0; } + _ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - ac_hi=$ac_mid +if ac_fn_c_try_run "$LINENO"; then : + ac_cv_broken_sem_getvalue=no else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 + ac_cv_broken_sem_getvalue=yes +fi +rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext \ + conftest.$ac_objext conftest.beam conftest.$ac_ext +fi + - ac_lo=`expr '(' $ac_mid ')' + 1` fi -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext -done -case $ac_lo in -?*) ac_cv_sizeof_wchar_t=$ac_lo;; -'') if test "$ac_cv_type_wchar_t" = yes; then - { { echo "$as_me:$LINENO: error: cannot compute sizeof (wchar_t) -See \`config.log' for more details." >&5 -echo "$as_me: error: cannot compute sizeof (wchar_t) -See \`config.log' for more details." >&2;} - { (exit 77); exit 77; }; } - else - ac_cv_sizeof_wchar_t=0 - fi ;; +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_broken_sem_getvalue" >&5 +$as_echo "$ac_cv_broken_sem_getvalue" >&6; } +if test $ac_cv_broken_sem_getvalue = yes +then + +$as_echo "#define HAVE_BROKEN_SEM_GETVALUE 1" >>confdefs.h + +fi + +# determine what size digit to use for Python's longs +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking digit size for Python's longs" >&5 +$as_echo_n "checking digit size for Python's longs... " >&6; } +# Check whether --enable-big-digits was given. +if test "${enable_big_digits+set}" = set; then : + enableval=$enable_big_digits; case $enable_big_digits in +yes) + enable_big_digits=30 ;; +no) + enable_big_digits=15 ;; +15|30) + ;; +*) + as_fn_error "bad value $enable_big_digits for --enable-big-digits; value should be 15 or 30" "$LINENO" 5 ;; esac -else - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $enable_big_digits" >&5 +$as_echo "$enable_big_digits" >&6; } + +cat >>confdefs.h <<_ACEOF +#define PYLONG_BITS_IN_DIGIT $enable_big_digits _ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -#include - typedef wchar_t ac__type_sizeof_; -static long int longval () { return (long int) (sizeof (ac__type_sizeof_)); } -static unsigned long int ulongval () { return (long int) (sizeof (ac__type_sizeof_)); } -#include -#include -int -main () -{ - FILE *f = fopen ("conftest.val", "w"); - if (! f) - return 1; - if (((long int) (sizeof (ac__type_sizeof_))) < 0) - { - long int i = longval (); - if (i != ((long int) (sizeof (ac__type_sizeof_)))) - return 1; - fprintf (f, "%ld\n", i); - } - else - { - unsigned long int i = ulongval (); - if (i != ((long int) (sizeof (ac__type_sizeof_)))) - return 1; - fprintf (f, "%lu\n", i); - } - return ferror (f) || fclose (f) != 0; +else + { $as_echo "$as_me:${as_lineno-$LINENO}: result: no value specified" >&5 +$as_echo "no value specified" >&6; } +fi + + +# check for wchar.h +ac_fn_c_check_header_mongrel "$LINENO" "wchar.h" "ac_cv_header_wchar_h" "$ac_includes_default" +if test "x$ac_cv_header_wchar_h" = x""yes; then : + + +$as_echo "#define HAVE_WCHAR_H 1" >>confdefs.h + + wchar_h="yes" - ; - return 0; -} -_ACEOF -rm -f conftest$ac_exeext -if { (ac_try="$ac_link" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_link") 2>&5 - ac_status=$? - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { ac_try='./conftest$ac_exeext' - { (case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_try") 2>&5 - ac_status=$? - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); }; }; then - ac_cv_sizeof_wchar_t=`cat conftest.val` else - echo "$as_me: program exited with status $ac_status" >&5 -echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 + wchar_h="no" + +fi + + + +# determine wchar_t size +if test "$wchar_h" = yes +then + # The cast to long int works around a bug in the HP C Compiler +# version HP92453-01 B.11.11.23709.GP, which incorrectly rejects +# declarations like `int a3[[(sizeof (unsigned char)) >= 0]];'. +# This bug is HP SR number 8606223364. +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking size of wchar_t" >&5 +$as_echo_n "checking size of wchar_t... " >&6; } +if test "${ac_cv_sizeof_wchar_t+set}" = set; then : + $as_echo_n "(cached) " >&6 +else + if ac_fn_c_compute_int "$LINENO" "(long int) (sizeof (wchar_t))" "ac_cv_sizeof_wchar_t" "#include +"; then : -( exit $ac_status ) -if test "$ac_cv_type_wchar_t" = yes; then - { { echo "$as_me:$LINENO: error: cannot compute sizeof (wchar_t) -See \`config.log' for more details." >&5 -echo "$as_me: error: cannot compute sizeof (wchar_t) -See \`config.log' for more details." >&2;} - { (exit 77); exit 77; }; } +else + if test "$ac_cv_type_wchar_t" = yes; then + { { $as_echo "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5 +$as_echo "$as_me: error: in \`$ac_pwd':" >&2;} +{ as_fn_set_status 77 +as_fn_error "cannot compute sizeof (wchar_t) +See \`config.log' for more details." "$LINENO" 5; }; } else ac_cv_sizeof_wchar_t=0 fi fi -rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext conftest.$ac_objext conftest.$ac_ext -fi -rm -f conftest.val + fi -{ echo "$as_me:$LINENO: result: $ac_cv_sizeof_wchar_t" >&5 -echo "${ECHO_T}$ac_cv_sizeof_wchar_t" >&6; } +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_sizeof_wchar_t" >&5 +$as_echo "$ac_cv_sizeof_wchar_t" >&6; } @@ -24951,14 +12075,10 @@ fi -{ echo "$as_me:$LINENO: checking for UCS-4 tcl" >&5 -echo $ECHO_N "checking for UCS-4 tcl... $ECHO_C" >&6; } +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for UCS-4 tcl" >&5 +$as_echo_n "checking for UCS-4 tcl... " >&6; } have_ucs4_tcl=no -cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF +cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ #include @@ -24973,60 +12093,32 @@ return 0; } _ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then +if ac_fn_c_try_compile "$LINENO"; then : -cat >>confdefs.h <<\_ACEOF -#define HAVE_UCS4_TCL 1 -_ACEOF +$as_echo "#define HAVE_UCS4_TCL 1" >>confdefs.h have_ucs4_tcl=yes -else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - fi - rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext -{ echo "$as_me:$LINENO: result: $have_ucs4_tcl" >&5 -echo "${ECHO_T}$have_ucs4_tcl" >&6; } +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $have_ucs4_tcl" >&5 +$as_echo "$have_ucs4_tcl" >&6; } # check whether wchar_t is signed or not if test "$wchar_h" = yes then # check whether wchar_t is signed or not - { echo "$as_me:$LINENO: checking whether wchar_t is signed" >&5 -echo $ECHO_N "checking whether wchar_t is signed... $ECHO_C" >&6; } - if test "${ac_cv_wchar_t_signed+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 + { $as_echo "$as_me:${as_lineno-$LINENO}: checking whether wchar_t is signed" >&5 +$as_echo_n "checking whether wchar_t is signed... " >&6; } + if test "${ac_cv_wchar_t_signed+set}" = set; then : + $as_echo_n "(cached) " >&6 else - if test "$cross_compiling" = yes; then + if test "$cross_compiling" = yes; then : ac_cv_wchar_t_signed=yes else - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF + cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ #include @@ -25037,50 +12129,26 @@ } _ACEOF -rm -f conftest$ac_exeext -if { (ac_try="$ac_link" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_link") 2>&5 - ac_status=$? - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { ac_try='./conftest$ac_exeext' - { (case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_try") 2>&5 - ac_status=$? - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); }; }; then +if ac_fn_c_try_run "$LINENO"; then : ac_cv_wchar_t_signed=yes else - echo "$as_me: program exited with status $ac_status" >&5 -echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - -( exit $ac_status ) -ac_cv_wchar_t_signed=no + ac_cv_wchar_t_signed=no fi -rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext conftest.$ac_objext conftest.$ac_ext +rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext \ + conftest.$ac_objext conftest.beam conftest.$ac_ext fi - fi - { echo "$as_me:$LINENO: result: $ac_cv_wchar_t_signed" >&5 -echo "${ECHO_T}$ac_cv_wchar_t_signed" >&6; } + { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_wchar_t_signed" >&5 +$as_echo "$ac_cv_wchar_t_signed" >&6; } fi -{ echo "$as_me:$LINENO: checking what type to use for str" >&5 -echo $ECHO_N "checking what type to use for str... $ECHO_C" >&6; } +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking what type to use for str" >&5 +$as_echo_n "checking what type to use for str... " >&6; } # Check whether --with-wide-unicode was given. -if test "${with_wide_unicode+set}" = set; then +if test "${with_wide_unicode+set}" = set; then : withval=$with_wide_unicode; if test "$withval" != no then unicode_size="4" @@ -25098,309 +12166,279 @@ - case "$unicode_size" in - 4) cat >>confdefs.h <<\_ACEOF -#define Py_UNICODE_SIZE 4 -_ACEOF + 4) $as_echo "#define Py_UNICODE_SIZE 4" >>confdefs.h ;; - *) cat >>confdefs.h <<\_ACEOF -#define Py_UNICODE_SIZE 2 -_ACEOF + *) $as_echo "#define Py_UNICODE_SIZE 2" >>confdefs.h ;; esac - # wchar_t is only usable if it maps to an unsigned type if test "$unicode_size" = "$ac_cv_sizeof_wchar_t" \ -a "$ac_cv_wchar_t_signed" = "no" then PY_UNICODE_TYPE="wchar_t" -cat >>confdefs.h <<\_ACEOF -#define HAVE_USABLE_WCHAR_T 1 -_ACEOF +$as_echo "#define HAVE_USABLE_WCHAR_T 1" >>confdefs.h - cat >>confdefs.h <<\_ACEOF -#define PY_UNICODE_TYPE wchar_t -_ACEOF + $as_echo "#define PY_UNICODE_TYPE wchar_t" >>confdefs.h elif test "$ac_cv_sizeof_short" = "$unicode_size" then PY_UNICODE_TYPE="unsigned short" - cat >>confdefs.h <<\_ACEOF -#define PY_UNICODE_TYPE unsigned short -_ACEOF + $as_echo "#define PY_UNICODE_TYPE unsigned short" >>confdefs.h elif test "$ac_cv_sizeof_long" = "$unicode_size" then PY_UNICODE_TYPE="unsigned long" - cat >>confdefs.h <<\_ACEOF -#define PY_UNICODE_TYPE unsigned long -_ACEOF + $as_echo "#define PY_UNICODE_TYPE unsigned long" >>confdefs.h else PY_UNICODE_TYPE="no type found" fi -{ echo "$as_me:$LINENO: result: $PY_UNICODE_TYPE" >&5 -echo "${ECHO_T}$PY_UNICODE_TYPE" >&6; } +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $PY_UNICODE_TYPE" >&5 +$as_echo "$PY_UNICODE_TYPE" >&6; } # check for endianness -{ echo "$as_me:$LINENO: checking whether byte ordering is bigendian" >&5 -echo $ECHO_N "checking whether byte ordering is bigendian... $ECHO_C" >&6; } -if test "${ac_cv_c_bigendian+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 -else - # See if sys/param.h defines the BYTE_ORDER macro. -cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ + { $as_echo "$as_me:${as_lineno-$LINENO}: checking whether byte ordering is bigendian" >&5 +$as_echo_n "checking whether byte ordering is bigendian... " >&6; } +if test "${ac_cv_c_bigendian+set}" = set; then : + $as_echo_n "(cached) " >&6 +else + ac_cv_c_bigendian=unknown + # See if we're dealing with a universal compiler. + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ +#ifndef __APPLE_CC__ + not a universal capable compiler + #endif + typedef int dummy; + _ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF +if ac_fn_c_try_compile "$LINENO"; then : + + # Check for potential -arch flags. It is not universal unless + # there are at least two -arch flags with different values. + ac_arch= + ac_prev= + for ac_word in $CC $CFLAGS $CPPFLAGS $LDFLAGS; do + if test -n "$ac_prev"; then + case $ac_word in + i?86 | x86_64 | ppc | ppc64) + if test -z "$ac_arch" || test "$ac_arch" = "$ac_word"; then + ac_arch=$ac_word + else + ac_cv_c_bigendian=universal + break + fi + ;; + esac + ac_prev= + elif test "x$ac_word" = "x-arch"; then + ac_prev=arch + fi + done +fi +rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext + if test $ac_cv_c_bigendian = unknown; then + # See if sys/param.h defines the BYTE_ORDER macro. + cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ #include -#include + #include int main () { -#if ! (defined BYTE_ORDER && defined BIG_ENDIAN && defined LITTLE_ENDIAN \ - && BYTE_ORDER && BIG_ENDIAN && LITTLE_ENDIAN) - bogus endian macros -#endif +#if ! (defined BYTE_ORDER && defined BIG_ENDIAN \ + && defined LITTLE_ENDIAN && BYTE_ORDER && BIG_ENDIAN \ + && LITTLE_ENDIAN) + bogus endian macros + #endif ; return 0; } _ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then +if ac_fn_c_try_compile "$LINENO"; then : # It does; now see whether it defined to BIG_ENDIAN or not. -cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF + cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ #include -#include + #include int main () { #if BYTE_ORDER != BIG_ENDIAN - not big endian -#endif + not big endian + #endif ; return 0; } _ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then +if ac_fn_c_try_compile "$LINENO"; then : ac_cv_c_bigendian=yes else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - ac_cv_c_bigendian=no + ac_cv_c_bigendian=no fi - rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext -else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 +fi +rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext + fi + if test $ac_cv_c_bigendian = unknown; then + # See if defines _LITTLE_ENDIAN or _BIG_ENDIAN (e.g., Solaris). + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ +#include - # It does not; compile a test program. -if test "$cross_compiling" = yes; then - # try to guess the endianness by grepping values into an object file - ac_cv_c_bigendian=unknown - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ +int +main () +{ +#if ! (defined _LITTLE_ENDIAN || defined _BIG_ENDIAN) + bogus endian macros + #endif + + ; + return 0; +} _ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF +if ac_fn_c_try_compile "$LINENO"; then : + # It does; now see whether it defined to _BIG_ENDIAN or not. + cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ -short int ascii_mm[] = { 0x4249, 0x4765, 0x6E44, 0x6961, 0x6E53, 0x7953, 0 }; -short int ascii_ii[] = { 0x694C, 0x5454, 0x656C, 0x6E45, 0x6944, 0x6E61, 0 }; -void _ascii () { char *s = (char *) ascii_mm; s = (char *) ascii_ii; } -short int ebcdic_ii[] = { 0x89D3, 0xE3E3, 0x8593, 0x95C5, 0x89C4, 0x9581, 0 }; -short int ebcdic_mm[] = { 0xC2C9, 0xC785, 0x95C4, 0x8981, 0x95E2, 0xA8E2, 0 }; -void _ebcdic () { char *s = (char *) ebcdic_mm; s = (char *) ebcdic_ii; } +#include + int main () { - _ascii (); _ebcdic (); +#ifndef _BIG_ENDIAN + not big endian + #endif + ; return 0; } _ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - if grep BIGenDianSyS conftest.$ac_objext >/dev/null ; then +if ac_fn_c_try_compile "$LINENO"; then : ac_cv_c_bigendian=yes +else + ac_cv_c_bigendian=no fi -if grep LiTTleEnDian conftest.$ac_objext >/dev/null ; then - if test "$ac_cv_c_bigendian" = unknown; then - ac_cv_c_bigendian=no - else - # finding both strings is unlikely to happen, but who knows? - ac_cv_c_bigendian=unknown - fi -fi -else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - +rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext fi +rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext + fi + if test $ac_cv_c_bigendian = unknown; then + # Compile a test program. + if test "$cross_compiling" = yes; then : + # Try to guess by grepping values from an object file. + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ +short int ascii_mm[] = + { 0x4249, 0x4765, 0x6E44, 0x6961, 0x6E53, 0x7953, 0 }; + short int ascii_ii[] = + { 0x694C, 0x5454, 0x656C, 0x6E45, 0x6944, 0x6E61, 0 }; + int use_ascii (int i) { + return ascii_mm[i] + ascii_ii[i]; + } + short int ebcdic_ii[] = + { 0x89D3, 0xE3E3, 0x8593, 0x95C5, 0x89C4, 0x9581, 0 }; + short int ebcdic_mm[] = + { 0xC2C9, 0xC785, 0x95C4, 0x8981, 0x95E2, 0xA8E2, 0 }; + int use_ebcdic (int i) { + return ebcdic_mm[i] + ebcdic_ii[i]; + } + extern int foo; +int +main () +{ +return use_ascii (foo) == use_ebcdic (foo); + ; + return 0; +} +_ACEOF +if ac_fn_c_try_compile "$LINENO"; then : + if grep BIGenDianSyS conftest.$ac_objext >/dev/null; then + ac_cv_c_bigendian=yes + fi + if grep LiTTleEnDian conftest.$ac_objext >/dev/null ; then + if test "$ac_cv_c_bigendian" = unknown; then + ac_cv_c_bigendian=no + else + # finding both strings is unlikely to happen, but who knows? + ac_cv_c_bigendian=unknown + fi + fi +fi rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext else - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF + cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ $ac_includes_default int main () { - /* Are we little or big endian? From Harbison&Steele. */ - union - { - long int l; - char c[sizeof (long int)]; - } u; - u.l = 1; - return u.c[sizeof (long int) - 1] == 1; + /* Are we little or big endian? From Harbison&Steele. */ + union + { + long int l; + char c[sizeof (long int)]; + } u; + u.l = 1; + return u.c[sizeof (long int) - 1] == 1; ; return 0; } _ACEOF -rm -f conftest$ac_exeext -if { (ac_try="$ac_link" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_link") 2>&5 - ac_status=$? - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { ac_try='./conftest$ac_exeext' - { (case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_try") 2>&5 - ac_status=$? - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); }; }; then +if ac_fn_c_try_run "$LINENO"; then : ac_cv_c_bigendian=no else - echo "$as_me: program exited with status $ac_status" >&5 -echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - -( exit $ac_status ) -ac_cv_c_bigendian=yes + ac_cv_c_bigendian=yes fi -rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext conftest.$ac_objext conftest.$ac_ext +rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext \ + conftest.$ac_objext conftest.beam conftest.$ac_ext fi - + fi fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_c_bigendian" >&5 +$as_echo "$ac_cv_c_bigendian" >&6; } + case $ac_cv_c_bigendian in #( + yes) + $as_echo "#define WORDS_BIGENDIAN 1" >>confdefs.h +;; #( + no) + ;; #( + universal) -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext -fi -{ echo "$as_me:$LINENO: result: $ac_cv_c_bigendian" >&5 -echo "${ECHO_T}$ac_cv_c_bigendian" >&6; } -case $ac_cv_c_bigendian in - yes) +$as_echo "#define AC_APPLE_UNIVERSAL_BUILD 1" >>confdefs.h -cat >>confdefs.h <<\_ACEOF -#define WORDS_BIGENDIAN 1 -_ACEOF - ;; - no) - ;; - *) - { { echo "$as_me:$LINENO: error: unknown endianness -presetting ac_cv_c_bigendian=no (or yes) will help" >&5 -echo "$as_me: error: unknown endianness -presetting ac_cv_c_bigendian=no (or yes) will help" >&2;} - { (exit 1); exit 1; }; } ;; -esac + ;; #( + *) + as_fn_error "unknown endianness + presetting ac_cv_c_bigendian=no (or yes) will help" "$LINENO" 5 ;; + esac # Check whether right shifting a negative integer extends the sign bit # or fills with zeros (like the Cray J90, according to Tim Peters). -{ echo "$as_me:$LINENO: checking whether right shift extends the sign bit" >&5 -echo $ECHO_N "checking whether right shift extends the sign bit... $ECHO_C" >&6; } -if test "${ac_cv_rshift_extends_sign+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking whether right shift extends the sign bit" >&5 +$as_echo_n "checking whether right shift extends the sign bit... " >&6; } +if test "${ac_cv_rshift_extends_sign+set}" = set; then : + $as_echo_n "(cached) " >&6 else -if test "$cross_compiling" = yes; then +if test "$cross_compiling" = yes; then : ac_cv_rshift_extends_sign=yes else - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF + cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ int main() @@ -25409,64 +12447,34 @@ } _ACEOF -rm -f conftest$ac_exeext -if { (ac_try="$ac_link" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_link") 2>&5 - ac_status=$? - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { ac_try='./conftest$ac_exeext' - { (case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_try") 2>&5 - ac_status=$? - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); }; }; then +if ac_fn_c_try_run "$LINENO"; then : ac_cv_rshift_extends_sign=yes else - echo "$as_me: program exited with status $ac_status" >&5 -echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - -( exit $ac_status ) -ac_cv_rshift_extends_sign=no + ac_cv_rshift_extends_sign=no fi -rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext conftest.$ac_objext conftest.$ac_ext +rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext \ + conftest.$ac_objext conftest.beam conftest.$ac_ext fi - fi -{ echo "$as_me:$LINENO: result: $ac_cv_rshift_extends_sign" >&5 -echo "${ECHO_T}$ac_cv_rshift_extends_sign" >&6; } +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_rshift_extends_sign" >&5 +$as_echo "$ac_cv_rshift_extends_sign" >&6; } if test "$ac_cv_rshift_extends_sign" = no then -cat >>confdefs.h <<\_ACEOF -#define SIGNED_RIGHT_SHIFT_ZERO_FILLS 1 -_ACEOF +$as_echo "#define SIGNED_RIGHT_SHIFT_ZERO_FILLS 1" >>confdefs.h fi # check for getc_unlocked and related locking functions -{ echo "$as_me:$LINENO: checking for getc_unlocked() and friends" >&5 -echo $ECHO_N "checking for getc_unlocked() and friends... $ECHO_C" >&6; } -if test "${ac_cv_have_getc_unlocked+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for getc_unlocked() and friends" >&5 +$as_echo_n "checking for getc_unlocked() and friends... " >&6; } +if test "${ac_cv_have_getc_unlocked+set}" = set; then : + $as_echo_n "(cached) " >&6 else -cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF +cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ #include int @@ -25482,44 +12490,21 @@ return 0; } _ACEOF -rm -f conftest.$ac_objext conftest$ac_exeext -if { (ac_try="$ac_link" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_link") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest$ac_exeext && - $as_test_x conftest$ac_exeext; then +if ac_fn_c_try_link "$LINENO"; then : ac_cv_have_getc_unlocked=yes else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - ac_cv_have_getc_unlocked=no + ac_cv_have_getc_unlocked=no fi - -rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \ - conftest$ac_exeext conftest.$ac_ext +rm -f core conftest.err conftest.$ac_objext \ + conftest$ac_exeext conftest.$ac_ext fi -{ echo "$as_me:$LINENO: result: $ac_cv_have_getc_unlocked" >&5 -echo "${ECHO_T}$ac_cv_have_getc_unlocked" >&6; } +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_have_getc_unlocked" >&5 +$as_echo "$ac_cv_have_getc_unlocked" >&6; } if test "$ac_cv_have_getc_unlocked" = yes then -cat >>confdefs.h <<\_ACEOF -#define HAVE_GETC_UNLOCKED 1 -_ACEOF +$as_echo "#define HAVE_GETC_UNLOCKED 1" >>confdefs.h fi @@ -25531,8 +12516,8 @@ # library. NOTE: Keep the precedence of listed libraries synchronised # with setup.py. py_cv_lib_readline=no -{ echo "$as_me:$LINENO: checking how to link readline libs" >&5 -echo $ECHO_N "checking how to link readline libs... $ECHO_C" >&6; } +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking how to link readline libs" >&5 +$as_echo_n "checking how to link readline libs... " >&6; } for py_libtermcap in "" ncursesw ncurses curses termcap; do if test -z "$py_libtermcap"; then READLINE_LIBS="-lreadline" @@ -25540,11 +12525,7 @@ READLINE_LIBS="-lreadline -l$py_libtermcap" fi LIBS="$READLINE_LIBS $LIBS_no_readline" - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF + cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ /* Override any GCC internal prototype to avoid an error. @@ -25562,34 +12543,11 @@ return 0; } _ACEOF -rm -f conftest.$ac_objext conftest$ac_exeext -if { (ac_try="$ac_link" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_link") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest$ac_exeext && - $as_test_x conftest$ac_exeext; then +if ac_fn_c_try_link "$LINENO"; then : py_cv_lib_readline=yes -else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - fi - -rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \ - conftest$ac_exeext conftest.$ac_ext +rm -f core conftest.err conftest.$ac_objext \ + conftest$ac_exeext conftest.$ac_ext if test $py_cv_lib_readline = yes; then break fi @@ -25597,31 +12555,25 @@ # Uncomment this line if you want to use READINE_LIBS in Makefile or scripts #AC_SUBST([READLINE_LIBS]) if test $py_cv_lib_readline = no; then - { echo "$as_me:$LINENO: result: none" >&5 -echo "${ECHO_T}none" >&6; } + { $as_echo "$as_me:${as_lineno-$LINENO}: result: none" >&5 +$as_echo "none" >&6; } else - { echo "$as_me:$LINENO: result: $READLINE_LIBS" >&5 -echo "${ECHO_T}$READLINE_LIBS" >&6; } + { $as_echo "$as_me:${as_lineno-$LINENO}: result: $READLINE_LIBS" >&5 +$as_echo "$READLINE_LIBS" >&6; } -cat >>confdefs.h <<\_ACEOF -#define HAVE_LIBREADLINE 1 -_ACEOF +$as_echo "#define HAVE_LIBREADLINE 1" >>confdefs.h fi # check for readline 2.1 -{ echo "$as_me:$LINENO: checking for rl_callback_handler_install in -lreadline" >&5 -echo $ECHO_N "checking for rl_callback_handler_install in -lreadline... $ECHO_C" >&6; } -if test "${ac_cv_lib_readline_rl_callback_handler_install+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for rl_callback_handler_install in -lreadline" >&5 +$as_echo_n "checking for rl_callback_handler_install in -lreadline... " >&6; } +if test "${ac_cv_lib_readline_rl_callback_handler_install+set}" = set; then : + $as_echo_n "(cached) " >&6 else ac_check_lib_save_LIBS=$LIBS LIBS="-lreadline $READLINE_LIBS $LIBS" -cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF +cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ /* Override any GCC internal prototype to avoid an error. @@ -25639,136 +12591,75 @@ return 0; } _ACEOF -rm -f conftest.$ac_objext conftest$ac_exeext -if { (ac_try="$ac_link" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_link") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest$ac_exeext && - $as_test_x conftest$ac_exeext; then +if ac_fn_c_try_link "$LINENO"; then : ac_cv_lib_readline_rl_callback_handler_install=yes else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - ac_cv_lib_readline_rl_callback_handler_install=no + ac_cv_lib_readline_rl_callback_handler_install=no fi - -rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \ - conftest$ac_exeext conftest.$ac_ext +rm -f core conftest.err conftest.$ac_objext \ + conftest$ac_exeext conftest.$ac_ext LIBS=$ac_check_lib_save_LIBS fi -{ echo "$as_me:$LINENO: result: $ac_cv_lib_readline_rl_callback_handler_install" >&5 -echo "${ECHO_T}$ac_cv_lib_readline_rl_callback_handler_install" >&6; } -if test $ac_cv_lib_readline_rl_callback_handler_install = yes; then +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_lib_readline_rl_callback_handler_install" >&5 +$as_echo "$ac_cv_lib_readline_rl_callback_handler_install" >&6; } +if test "x$ac_cv_lib_readline_rl_callback_handler_install" = x""yes; then : -cat >>confdefs.h <<\_ACEOF -#define HAVE_RL_CALLBACK 1 -_ACEOF +$as_echo "#define HAVE_RL_CALLBACK 1" >>confdefs.h fi # check for readline 2.2 -cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF +cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ #include _ACEOF -if { (ac_try="$ac_cpp conftest.$ac_ext" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_cpp conftest.$ac_ext") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } >/dev/null && { - test -z "$ac_c_preproc_warn_flag$ac_c_werror_flag" || - test ! -s conftest.err - }; then +if ac_fn_c_try_cpp "$LINENO"; then : have_readline=yes else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - have_readline=no -fi +fi rm -f conftest.err conftest.$ac_ext if test $have_readline = yes then - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF + cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ #include _ACEOF if (eval "$ac_cpp conftest.$ac_ext") 2>&5 | - $EGREP "extern int rl_completion_append_character;" >/dev/null 2>&1; then + $EGREP "extern int rl_completion_append_character;" >/dev/null 2>&1; then : -cat >>confdefs.h <<\_ACEOF -#define HAVE_RL_COMPLETION_APPEND_CHARACTER 1 -_ACEOF +$as_echo "#define HAVE_RL_COMPLETION_APPEND_CHARACTER 1" >>confdefs.h fi -rm -f -r conftest* +rm -f conftest* - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF + cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ #include _ACEOF if (eval "$ac_cpp conftest.$ac_ext") 2>&5 | - $EGREP "extern int rl_completion_suppress_append;" >/dev/null 2>&1; then + $EGREP "extern int rl_completion_suppress_append;" >/dev/null 2>&1; then : -cat >>confdefs.h <<\_ACEOF -#define HAVE_RL_COMPLETION_SUPPRESS_APPEND 1 -_ACEOF +$as_echo "#define HAVE_RL_COMPLETION_SUPPRESS_APPEND 1" >>confdefs.h fi -rm -f -r conftest* +rm -f conftest* fi # check for readline 4.0 -{ echo "$as_me:$LINENO: checking for rl_pre_input_hook in -lreadline" >&5 -echo $ECHO_N "checking for rl_pre_input_hook in -lreadline... $ECHO_C" >&6; } -if test "${ac_cv_lib_readline_rl_pre_input_hook+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for rl_pre_input_hook in -lreadline" >&5 +$as_echo_n "checking for rl_pre_input_hook in -lreadline... " >&6; } +if test "${ac_cv_lib_readline_rl_pre_input_hook+set}" = set; then : + $as_echo_n "(cached) " >&6 else ac_check_lib_save_LIBS=$LIBS LIBS="-lreadline $READLINE_LIBS $LIBS" -cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF +cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ /* Override any GCC internal prototype to avoid an error. @@ -25786,60 +12677,33 @@ return 0; } _ACEOF -rm -f conftest.$ac_objext conftest$ac_exeext -if { (ac_try="$ac_link" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_link") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest$ac_exeext && - $as_test_x conftest$ac_exeext; then +if ac_fn_c_try_link "$LINENO"; then : ac_cv_lib_readline_rl_pre_input_hook=yes else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - ac_cv_lib_readline_rl_pre_input_hook=no + ac_cv_lib_readline_rl_pre_input_hook=no fi - -rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \ - conftest$ac_exeext conftest.$ac_ext +rm -f core conftest.err conftest.$ac_objext \ + conftest$ac_exeext conftest.$ac_ext LIBS=$ac_check_lib_save_LIBS fi -{ echo "$as_me:$LINENO: result: $ac_cv_lib_readline_rl_pre_input_hook" >&5 -echo "${ECHO_T}$ac_cv_lib_readline_rl_pre_input_hook" >&6; } -if test $ac_cv_lib_readline_rl_pre_input_hook = yes; then +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_lib_readline_rl_pre_input_hook" >&5 +$as_echo "$ac_cv_lib_readline_rl_pre_input_hook" >&6; } +if test "x$ac_cv_lib_readline_rl_pre_input_hook" = x""yes; then : -cat >>confdefs.h <<\_ACEOF -#define HAVE_RL_PRE_INPUT_HOOK 1 -_ACEOF +$as_echo "#define HAVE_RL_PRE_INPUT_HOOK 1" >>confdefs.h fi # also in 4.0 -{ echo "$as_me:$LINENO: checking for rl_completion_display_matches_hook in -lreadline" >&5 -echo $ECHO_N "checking for rl_completion_display_matches_hook in -lreadline... $ECHO_C" >&6; } -if test "${ac_cv_lib_readline_rl_completion_display_matches_hook+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for rl_completion_display_matches_hook in -lreadline" >&5 +$as_echo_n "checking for rl_completion_display_matches_hook in -lreadline... " >&6; } +if test "${ac_cv_lib_readline_rl_completion_display_matches_hook+set}" = set; then : + $as_echo_n "(cached) " >&6 else ac_check_lib_save_LIBS=$LIBS LIBS="-lreadline $READLINE_LIBS $LIBS" -cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF +cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ /* Override any GCC internal prototype to avoid an error. @@ -25857,60 +12721,33 @@ return 0; } _ACEOF -rm -f conftest.$ac_objext conftest$ac_exeext -if { (ac_try="$ac_link" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_link") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest$ac_exeext && - $as_test_x conftest$ac_exeext; then +if ac_fn_c_try_link "$LINENO"; then : ac_cv_lib_readline_rl_completion_display_matches_hook=yes else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - ac_cv_lib_readline_rl_completion_display_matches_hook=no + ac_cv_lib_readline_rl_completion_display_matches_hook=no fi - -rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \ - conftest$ac_exeext conftest.$ac_ext +rm -f core conftest.err conftest.$ac_objext \ + conftest$ac_exeext conftest.$ac_ext LIBS=$ac_check_lib_save_LIBS fi -{ echo "$as_me:$LINENO: result: $ac_cv_lib_readline_rl_completion_display_matches_hook" >&5 -echo "${ECHO_T}$ac_cv_lib_readline_rl_completion_display_matches_hook" >&6; } -if test $ac_cv_lib_readline_rl_completion_display_matches_hook = yes; then +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_lib_readline_rl_completion_display_matches_hook" >&5 +$as_echo "$ac_cv_lib_readline_rl_completion_display_matches_hook" >&6; } +if test "x$ac_cv_lib_readline_rl_completion_display_matches_hook" = x""yes; then : -cat >>confdefs.h <<\_ACEOF -#define HAVE_RL_COMPLETION_DISPLAY_MATCHES_HOOK 1 -_ACEOF +$as_echo "#define HAVE_RL_COMPLETION_DISPLAY_MATCHES_HOOK 1" >>confdefs.h fi # check for readline 4.2 -{ echo "$as_me:$LINENO: checking for rl_completion_matches in -lreadline" >&5 -echo $ECHO_N "checking for rl_completion_matches in -lreadline... $ECHO_C" >&6; } -if test "${ac_cv_lib_readline_rl_completion_matches+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for rl_completion_matches in -lreadline" >&5 +$as_echo_n "checking for rl_completion_matches in -lreadline... " >&6; } +if test "${ac_cv_lib_readline_rl_completion_matches+set}" = set; then : + $as_echo_n "(cached) " >&6 else ac_check_lib_save_LIBS=$LIBS LIBS="-lreadline $READLINE_LIBS $LIBS" -cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF +cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ /* Override any GCC internal prototype to avoid an error. @@ -25928,121 +12765,66 @@ return 0; } _ACEOF -rm -f conftest.$ac_objext conftest$ac_exeext -if { (ac_try="$ac_link" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_link") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest$ac_exeext && - $as_test_x conftest$ac_exeext; then +if ac_fn_c_try_link "$LINENO"; then : ac_cv_lib_readline_rl_completion_matches=yes else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - ac_cv_lib_readline_rl_completion_matches=no + ac_cv_lib_readline_rl_completion_matches=no fi - -rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \ - conftest$ac_exeext conftest.$ac_ext +rm -f core conftest.err conftest.$ac_objext \ + conftest$ac_exeext conftest.$ac_ext LIBS=$ac_check_lib_save_LIBS fi -{ echo "$as_me:$LINENO: result: $ac_cv_lib_readline_rl_completion_matches" >&5 -echo "${ECHO_T}$ac_cv_lib_readline_rl_completion_matches" >&6; } -if test $ac_cv_lib_readline_rl_completion_matches = yes; then +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_lib_readline_rl_completion_matches" >&5 +$as_echo "$ac_cv_lib_readline_rl_completion_matches" >&6; } +if test "x$ac_cv_lib_readline_rl_completion_matches" = x""yes; then : -cat >>confdefs.h <<\_ACEOF -#define HAVE_RL_COMPLETION_MATCHES 1 -_ACEOF +$as_echo "#define HAVE_RL_COMPLETION_MATCHES 1" >>confdefs.h fi # also in readline 4.2 -cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF +cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ #include _ACEOF -if { (ac_try="$ac_cpp conftest.$ac_ext" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_cpp conftest.$ac_ext") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } >/dev/null && { - test -z "$ac_c_preproc_warn_flag$ac_c_werror_flag" || - test ! -s conftest.err - }; then +if ac_fn_c_try_cpp "$LINENO"; then : have_readline=yes else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - have_readline=no -fi +fi rm -f conftest.err conftest.$ac_ext if test $have_readline = yes then - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF + cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ #include _ACEOF if (eval "$ac_cpp conftest.$ac_ext") 2>&5 | - $EGREP "extern int rl_catch_signals;" >/dev/null 2>&1; then + $EGREP "extern int rl_catch_signals;" >/dev/null 2>&1; then : -cat >>confdefs.h <<\_ACEOF -#define HAVE_RL_CATCH_SIGNAL 1 -_ACEOF +$as_echo "#define HAVE_RL_CATCH_SIGNAL 1" >>confdefs.h fi -rm -f -r conftest* +rm -f conftest* fi # End of readline checks: restore LIBS LIBS=$LIBS_no_readline -{ echo "$as_me:$LINENO: checking for broken nice()" >&5 -echo $ECHO_N "checking for broken nice()... $ECHO_C" >&6; } -if test "${ac_cv_broken_nice+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for broken nice()" >&5 +$as_echo_n "checking for broken nice()... " >&6; } +if test "${ac_cv_broken_nice+set}" = set; then : + $as_echo_n "(cached) " >&6 else -if test "$cross_compiling" = yes; then +if test "$cross_compiling" = yes; then : ac_cv_broken_nice=no else - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF + cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ int main() @@ -26054,65 +12836,35 @@ } _ACEOF -rm -f conftest$ac_exeext -if { (ac_try="$ac_link" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_link") 2>&5 - ac_status=$? - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { ac_try='./conftest$ac_exeext' - { (case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_try") 2>&5 - ac_status=$? - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); }; }; then +if ac_fn_c_try_run "$LINENO"; then : ac_cv_broken_nice=yes else - echo "$as_me: program exited with status $ac_status" >&5 -echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - -( exit $ac_status ) -ac_cv_broken_nice=no + ac_cv_broken_nice=no fi -rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext conftest.$ac_objext conftest.$ac_ext +rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext \ + conftest.$ac_objext conftest.beam conftest.$ac_ext fi - fi -{ echo "$as_me:$LINENO: result: $ac_cv_broken_nice" >&5 -echo "${ECHO_T}$ac_cv_broken_nice" >&6; } +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_broken_nice" >&5 +$as_echo "$ac_cv_broken_nice" >&6; } if test "$ac_cv_broken_nice" = yes then -cat >>confdefs.h <<\_ACEOF -#define HAVE_BROKEN_NICE 1 -_ACEOF +$as_echo "#define HAVE_BROKEN_NICE 1" >>confdefs.h fi -{ echo "$as_me:$LINENO: checking for broken poll()" >&5 -echo $ECHO_N "checking for broken poll()... $ECHO_C" >&6; } -if test "${ac_cv_broken_poll+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for broken poll()" >&5 +$as_echo_n "checking for broken poll()... " >&6; } +if test "${ac_cv_broken_poll+set}" = set; then : + $as_echo_n "(cached) " >&6 else - if test "$cross_compiling" = yes; then + if test "$cross_compiling" = yes; then : ac_cv_broken_poll=no else - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF + cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ #include @@ -26134,155 +12886,34 @@ } _ACEOF -rm -f conftest$ac_exeext -if { (ac_try="$ac_link" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_link") 2>&5 - ac_status=$? - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { ac_try='./conftest$ac_exeext' - { (case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_try") 2>&5 - ac_status=$? - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); }; }; then +if ac_fn_c_try_run "$LINENO"; then : ac_cv_broken_poll=yes else - echo "$as_me: program exited with status $ac_status" >&5 -echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - -( exit $ac_status ) -ac_cv_broken_poll=no + ac_cv_broken_poll=no fi -rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext conftest.$ac_objext conftest.$ac_ext +rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext \ + conftest.$ac_objext conftest.beam conftest.$ac_ext fi - fi -{ echo "$as_me:$LINENO: result: $ac_cv_broken_poll" >&5 -echo "${ECHO_T}$ac_cv_broken_poll" >&6; } +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_broken_poll" >&5 +$as_echo "$ac_cv_broken_poll" >&6; } if test "$ac_cv_broken_poll" = yes -then - -cat >>confdefs.h <<\_ACEOF -#define HAVE_BROKEN_POLL 1 -_ACEOF - -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[] -{ echo "$as_me:$LINENO: checking for struct tm.tm_zone" >&5 -echo $ECHO_N "checking for struct tm.tm_zone... $ECHO_C" >&6; } -if test "${ac_cv_member_struct_tm_tm_zone+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 -else - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -#include -#include <$ac_cv_struct_tm> - - -int -main () -{ -static struct tm ac_aggr; -if (ac_aggr.tm_zone) -return 0; - ; - return 0; -} -_ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - ac_cv_member_struct_tm_tm_zone=yes -else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -#include -#include <$ac_cv_struct_tm> - - -int -main () -{ -static struct tm ac_aggr; -if (sizeof ac_aggr.tm_zone) -return 0; - ; - return 0; -} -_ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - ac_cv_member_struct_tm_tm_zone=yes -else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 +then - ac_cv_member_struct_tm_tm_zone=no -fi +$as_echo "#define HAVE_BROKEN_POLL 1" >>confdefs.h -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext fi -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext -fi -{ echo "$as_me:$LINENO: result: $ac_cv_member_struct_tm_tm_zone" >&5 -echo "${ECHO_T}$ac_cv_member_struct_tm_tm_zone" >&6; } -if test $ac_cv_member_struct_tm_tm_zone = yes; then +# 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_fn_c_check_member "$LINENO" "struct tm" "tm_zone" "ac_cv_member_struct_tm_tm_zone" "#include +#include <$ac_cv_struct_tm> + +" +if test "x$ac_cv_member_struct_tm_tm_zone" = x""yes; then : cat >>confdefs.h <<_ACEOF #define HAVE_STRUCT_TM_TM_ZONE 1 @@ -26293,90 +12924,27 @@ if test "$ac_cv_member_struct_tm_tm_zone" = yes; then -cat >>confdefs.h <<\_ACEOF -#define HAVE_TM_ZONE 1 -_ACEOF +$as_echo "#define HAVE_TM_ZONE 1" >>confdefs.h else - { echo "$as_me:$LINENO: checking whether tzname is declared" >&5 -echo $ECHO_N "checking whether tzname is declared... $ECHO_C" >&6; } -if test "${ac_cv_have_decl_tzname+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 -else - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -#include - -int -main () -{ -#ifndef tzname - (void) tzname; -#endif - - ; - return 0; -} -_ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - ac_cv_have_decl_tzname=yes + ac_fn_c_check_decl "$LINENO" "tzname" "ac_cv_have_decl_tzname" "#include +" +if test "x$ac_cv_have_decl_tzname" = x""yes; then : + ac_have_decl=1 else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - ac_cv_have_decl_tzname=no + ac_have_decl=0 fi -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext -fi -{ echo "$as_me:$LINENO: result: $ac_cv_have_decl_tzname" >&5 -echo "${ECHO_T}$ac_cv_have_decl_tzname" >&6; } -if test $ac_cv_have_decl_tzname = yes; then - cat >>confdefs.h <<_ACEOF -#define HAVE_DECL_TZNAME 1 -_ACEOF - - -else - cat >>confdefs.h <<_ACEOF -#define HAVE_DECL_TZNAME 0 +#define HAVE_DECL_TZNAME $ac_have_decl _ACEOF - -fi - - - { echo "$as_me:$LINENO: checking for tzname" >&5 -echo $ECHO_N "checking for tzname... $ECHO_C" >&6; } -if test "${ac_cv_var_tzname+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 + { $as_echo "$as_me:${as_lineno-$LINENO}: checking for tzname" >&5 +$as_echo_n "checking for tzname... " >&6; } +if test "${ac_cv_var_tzname+set}" = set; then : + $as_echo_n "(cached) " >&6 else - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF + cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ #include #if !HAVE_DECL_TZNAME @@ -26391,62 +12959,35 @@ return 0; } _ACEOF -rm -f conftest.$ac_objext conftest$ac_exeext -if { (ac_try="$ac_link" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_link") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest$ac_exeext && - $as_test_x conftest$ac_exeext; then +if ac_fn_c_try_link "$LINENO"; then : ac_cv_var_tzname=yes else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - ac_cv_var_tzname=no + ac_cv_var_tzname=no fi - -rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \ - conftest$ac_exeext conftest.$ac_ext +rm -f core conftest.err conftest.$ac_objext \ + conftest$ac_exeext conftest.$ac_ext fi -{ echo "$as_me:$LINENO: result: $ac_cv_var_tzname" >&5 -echo "${ECHO_T}$ac_cv_var_tzname" >&6; } +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_var_tzname" >&5 +$as_echo "$ac_cv_var_tzname" >&6; } if test $ac_cv_var_tzname = yes; then -cat >>confdefs.h <<\_ACEOF -#define HAVE_TZNAME 1 -_ACEOF +$as_echo "#define HAVE_TZNAME 1" >>confdefs.h fi fi # check tzset(3) exists and works like we expect it to -{ echo "$as_me:$LINENO: checking for working tzset()" >&5 -echo $ECHO_N "checking for working tzset()... $ECHO_C" >&6; } -if test "${ac_cv_working_tzset+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for working tzset()" >&5 +$as_echo_n "checking for working tzset()... " >&6; } +if test "${ac_cv_working_tzset+set}" = set; then : + $as_echo_n "(cached) " >&6 else -if test "$cross_compiling" = yes; then +if test "$cross_compiling" = yes; then : ac_cv_working_tzset=no else - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF + cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ #include @@ -26513,63 +13054,33 @@ } _ACEOF -rm -f conftest$ac_exeext -if { (ac_try="$ac_link" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_link") 2>&5 - ac_status=$? - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { ac_try='./conftest$ac_exeext' - { (case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_try") 2>&5 - ac_status=$? - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); }; }; then +if ac_fn_c_try_run "$LINENO"; then : ac_cv_working_tzset=yes else - echo "$as_me: program exited with status $ac_status" >&5 -echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - -( exit $ac_status ) -ac_cv_working_tzset=no + ac_cv_working_tzset=no fi -rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext conftest.$ac_objext conftest.$ac_ext +rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext \ + conftest.$ac_objext conftest.beam conftest.$ac_ext fi - fi -{ echo "$as_me:$LINENO: result: $ac_cv_working_tzset" >&5 -echo "${ECHO_T}$ac_cv_working_tzset" >&6; } +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_working_tzset" >&5 +$as_echo "$ac_cv_working_tzset" >&6; } if test "$ac_cv_working_tzset" = yes then -cat >>confdefs.h <<\_ACEOF -#define HAVE_WORKING_TZSET 1 -_ACEOF +$as_echo "#define HAVE_WORKING_TZSET 1" >>confdefs.h fi # Look for subsecond timestamps in struct stat -{ echo "$as_me:$LINENO: checking for tv_nsec in struct stat" >&5 -echo $ECHO_N "checking for tv_nsec in struct stat... $ECHO_C" >&6; } -if test "${ac_cv_stat_tv_nsec+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for tv_nsec in struct stat" >&5 +$as_echo_n "checking for tv_nsec in struct stat... " >&6; } +if test "${ac_cv_stat_tv_nsec+set}" = set; then : + $as_echo_n "(cached) " >&6 else - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF + cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ #include int @@ -26583,56 +13094,30 @@ return 0; } _ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then +if ac_fn_c_try_compile "$LINENO"; then : ac_cv_stat_tv_nsec=yes else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - ac_cv_stat_tv_nsec=no + ac_cv_stat_tv_nsec=no fi - rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext fi -{ echo "$as_me:$LINENO: result: $ac_cv_stat_tv_nsec" >&5 -echo "${ECHO_T}$ac_cv_stat_tv_nsec" >&6; } +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_stat_tv_nsec" >&5 +$as_echo "$ac_cv_stat_tv_nsec" >&6; } if test "$ac_cv_stat_tv_nsec" = yes then -cat >>confdefs.h <<\_ACEOF -#define HAVE_STAT_TV_NSEC 1 -_ACEOF +$as_echo "#define HAVE_STAT_TV_NSEC 1" >>confdefs.h fi # Look for BSD style subsecond timestamps in struct stat -{ echo "$as_me:$LINENO: checking for tv_nsec2 in struct stat" >&5 -echo $ECHO_N "checking for tv_nsec2 in struct stat... $ECHO_C" >&6; } -if test "${ac_cv_stat_tv_nsec2+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for tv_nsec2 in struct stat" >&5 +$as_echo_n "checking for tv_nsec2 in struct stat... " >&6; } +if test "${ac_cv_stat_tv_nsec2+set}" = set; then : + $as_echo_n "(cached) " >&6 else - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF + cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ #include int @@ -26646,56 +13131,30 @@ return 0; } _ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then +if ac_fn_c_try_compile "$LINENO"; then : ac_cv_stat_tv_nsec2=yes else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - ac_cv_stat_tv_nsec2=no + ac_cv_stat_tv_nsec2=no fi - rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext fi -{ echo "$as_me:$LINENO: result: $ac_cv_stat_tv_nsec2" >&5 -echo "${ECHO_T}$ac_cv_stat_tv_nsec2" >&6; } +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_stat_tv_nsec2" >&5 +$as_echo "$ac_cv_stat_tv_nsec2" >&6; } if test "$ac_cv_stat_tv_nsec2" = yes then -cat >>confdefs.h <<\_ACEOF -#define HAVE_STAT_TV_NSEC2 1 -_ACEOF +$as_echo "#define HAVE_STAT_TV_NSEC2 1" >>confdefs.h fi # On HP/UX 11.0, mvwdelch is a block with a return statement -{ echo "$as_me:$LINENO: checking whether mvwdelch is an expression" >&5 -echo $ECHO_N "checking whether mvwdelch is an expression... $ECHO_C" >&6; } -if test "${ac_cv_mvwdelch_is_expression+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking whether mvwdelch is an expression" >&5 +$as_echo_n "checking whether mvwdelch is an expression... " >&6; } +if test "${ac_cv_mvwdelch_is_expression+set}" = set; then : + $as_echo_n "(cached) " >&6 else - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF + cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ #include int @@ -26709,56 +13168,30 @@ return 0; } _ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then +if ac_fn_c_try_compile "$LINENO"; then : ac_cv_mvwdelch_is_expression=yes else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - ac_cv_mvwdelch_is_expression=no + ac_cv_mvwdelch_is_expression=no fi - rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext fi -{ echo "$as_me:$LINENO: result: $ac_cv_mvwdelch_is_expression" >&5 -echo "${ECHO_T}$ac_cv_mvwdelch_is_expression" >&6; } +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_mvwdelch_is_expression" >&5 +$as_echo "$ac_cv_mvwdelch_is_expression" >&6; } if test "$ac_cv_mvwdelch_is_expression" = yes then -cat >>confdefs.h <<\_ACEOF -#define MVWDELCH_IS_EXPRESSION 1 -_ACEOF +$as_echo "#define MVWDELCH_IS_EXPRESSION 1" >>confdefs.h fi -{ echo "$as_me:$LINENO: checking whether WINDOW has _flags" >&5 -echo $ECHO_N "checking whether WINDOW has _flags... $ECHO_C" >&6; } -if test "${ac_cv_window_has_flags+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking whether WINDOW has _flags" >&5 +$as_echo_n "checking whether WINDOW has _flags... " >&6; } +if test "${ac_cv_window_has_flags+set}" = set; then : + $as_echo_n "(cached) " >&6 else - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF + cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ #include int @@ -26772,54 +13205,28 @@ return 0; } _ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then +if ac_fn_c_try_compile "$LINENO"; then : ac_cv_window_has_flags=yes else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - ac_cv_window_has_flags=no + ac_cv_window_has_flags=no fi - rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext fi -{ echo "$as_me:$LINENO: result: $ac_cv_window_has_flags" >&5 -echo "${ECHO_T}$ac_cv_window_has_flags" >&6; } +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_window_has_flags" >&5 +$as_echo "$ac_cv_window_has_flags" >&6; } if test "$ac_cv_window_has_flags" = yes then -cat >>confdefs.h <<\_ACEOF -#define WINDOW_HAS_FLAGS 1 -_ACEOF +$as_echo "#define WINDOW_HAS_FLAGS 1" >>confdefs.h fi -{ echo "$as_me:$LINENO: checking for is_term_resized" >&5 -echo $ECHO_N "checking for is_term_resized... $ECHO_C" >&6; } -cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for is_term_resized" >&5 +$as_echo_n "checking for is_term_resized... " >&6; } +cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ #include int @@ -26830,48 +13237,22 @@ return 0; } _ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then +if ac_fn_c_try_compile "$LINENO"; then : -cat >>confdefs.h <<\_ACEOF -#define HAVE_CURSES_IS_TERM_RESIZED 1 -_ACEOF +$as_echo "#define HAVE_CURSES_IS_TERM_RESIZED 1" >>confdefs.h - { echo "$as_me:$LINENO: result: yes" >&5 -echo "${ECHO_T}yes" >&6; } + { $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +$as_echo "yes" >&6; } else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - { echo "$as_me:$LINENO: result: no" >&5 -echo "${ECHO_T}no" >&6; } + { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 +$as_echo "no" >&6; } fi - rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext -{ echo "$as_me:$LINENO: checking for resize_term" >&5 -echo $ECHO_N "checking for resize_term... $ECHO_C" >&6; } -cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for resize_term" >&5 +$as_echo_n "checking for resize_term... " >&6; } +cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ #include int @@ -26882,48 +13263,22 @@ return 0; } _ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then +if ac_fn_c_try_compile "$LINENO"; then : -cat >>confdefs.h <<\_ACEOF -#define HAVE_CURSES_RESIZE_TERM 1 -_ACEOF +$as_echo "#define HAVE_CURSES_RESIZE_TERM 1" >>confdefs.h - { echo "$as_me:$LINENO: result: yes" >&5 -echo "${ECHO_T}yes" >&6; } + { $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +$as_echo "yes" >&6; } else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - { echo "$as_me:$LINENO: result: no" >&5 -echo "${ECHO_T}no" >&6; } + { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 +$as_echo "no" >&6; } fi - rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext -{ echo "$as_me:$LINENO: checking for resizeterm" >&5 -echo $ECHO_N "checking for resizeterm... $ECHO_C" >&6; } -cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for resizeterm" >&5 +$as_echo_n "checking for resizeterm... " >&6; } +cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ #include int @@ -26934,90 +13289,60 @@ return 0; } _ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then +if ac_fn_c_try_compile "$LINENO"; then : -cat >>confdefs.h <<\_ACEOF -#define HAVE_CURSES_RESIZETERM 1 -_ACEOF +$as_echo "#define HAVE_CURSES_RESIZETERM 1" >>confdefs.h - { echo "$as_me:$LINENO: result: yes" >&5 -echo "${ECHO_T}yes" >&6; } + { $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +$as_echo "yes" >&6; } else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - { echo "$as_me:$LINENO: result: no" >&5 -echo "${ECHO_T}no" >&6; } + { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 +$as_echo "no" >&6; } fi - rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext -{ echo "$as_me:$LINENO: checking for /dev/ptmx" >&5 -echo $ECHO_N "checking for /dev/ptmx... $ECHO_C" >&6; } +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for /dev/ptmx" >&5 +$as_echo_n "checking for /dev/ptmx... " >&6; } if test -r /dev/ptmx then - { echo "$as_me:$LINENO: result: yes" >&5 -echo "${ECHO_T}yes" >&6; } + { $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +$as_echo "yes" >&6; } -cat >>confdefs.h <<\_ACEOF -#define HAVE_DEV_PTMX 1 -_ACEOF +$as_echo "#define HAVE_DEV_PTMX 1" >>confdefs.h else - { echo "$as_me:$LINENO: result: no" >&5 -echo "${ECHO_T}no" >&6; } + { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 +$as_echo "no" >&6; } fi -{ echo "$as_me:$LINENO: checking for /dev/ptc" >&5 -echo $ECHO_N "checking for /dev/ptc... $ECHO_C" >&6; } +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for /dev/ptc" >&5 +$as_echo_n "checking for /dev/ptc... " >&6; } if test -r /dev/ptc then - { echo "$as_me:$LINENO: result: yes" >&5 -echo "${ECHO_T}yes" >&6; } + { $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +$as_echo "yes" >&6; } -cat >>confdefs.h <<\_ACEOF -#define HAVE_DEV_PTC 1 -_ACEOF +$as_echo "#define HAVE_DEV_PTC 1" >>confdefs.h else - { echo "$as_me:$LINENO: result: no" >&5 -echo "${ECHO_T}no" >&6; } + { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 +$as_echo "no" >&6; } fi if test "$have_long_long" = yes then - { echo "$as_me:$LINENO: checking for %lld and %llu printf() format support" >&5 -echo $ECHO_N "checking for %lld and %llu printf() format support... $ECHO_C" >&6; } - if test "${ac_cv_have_long_long_format+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 + { $as_echo "$as_me:${as_lineno-$LINENO}: checking for %lld and %llu printf() format support" >&5 +$as_echo_n "checking for %lld and %llu printf() format support... " >&6; } + if test "${ac_cv_have_long_long_format+set}" = set; then : + $as_echo_n "(cached) " >&6 else - if test "$cross_compiling" = yes; then + if test "$cross_compiling" = yes; then : ac_cv_have_long_long_format=no else - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF + cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ #include @@ -27051,52 +13376,26 @@ } _ACEOF -rm -f conftest$ac_exeext -if { (ac_try="$ac_link" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_link") 2>&5 - ac_status=$? - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { ac_try='./conftest$ac_exeext' - { (case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_try") 2>&5 - ac_status=$? - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); }; }; then +if ac_fn_c_try_run "$LINENO"; then : ac_cv_have_long_long_format=yes else - echo "$as_me: program exited with status $ac_status" >&5 -echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - -( exit $ac_status ) -ac_cv_have_long_long_format=no + ac_cv_have_long_long_format=no fi -rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext conftest.$ac_objext conftest.$ac_ext +rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext \ + conftest.$ac_objext conftest.beam conftest.$ac_ext fi - fi - { echo "$as_me:$LINENO: result: $ac_cv_have_long_long_format" >&5 -echo "${ECHO_T}$ac_cv_have_long_long_format" >&6; } + { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_have_long_long_format" >&5 +$as_echo "$ac_cv_have_long_long_format" >&6; } fi if test "$ac_cv_have_long_long_format" = yes then -cat >>confdefs.h <<\_ACEOF -#define PY_FORMAT_LONG_LONG "ll" -_ACEOF +$as_echo "#define PY_FORMAT_LONG_LONG \"ll\"" >>confdefs.h fi @@ -27105,20 +13404,16 @@ LIBS="$LIBS -framework CoreFoundation" fi -{ echo "$as_me:$LINENO: checking for %zd printf() format support" >&5 -echo $ECHO_N "checking for %zd printf() format support... $ECHO_C" >&6; } -if test "${ac_cv_have_size_t_format+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for %zd printf() format support" >&5 +$as_echo_n "checking for %zd printf() format support... " >&6; } +if test "${ac_cv_have_size_t_format+set}" = set; then : + $as_echo_n "(cached) " >&6 else - if test "$cross_compiling" = yes; then + if test "$cross_compiling" = yes; then : ac_cv_have_size_t_format="cross -- assuming yes" else - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF + cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ #include @@ -27157,62 +13452,25 @@ } _ACEOF -rm -f conftest$ac_exeext -if { (ac_try="$ac_link" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_link") 2>&5 - ac_status=$? - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { ac_try='./conftest$ac_exeext' - { (case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_try") 2>&5 - ac_status=$? - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); }; }; then +if ac_fn_c_try_run "$LINENO"; then : ac_cv_have_size_t_format=yes else - echo "$as_me: program exited with status $ac_status" >&5 -echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - -( exit $ac_status ) -ac_cv_have_size_t_format=no + ac_cv_have_size_t_format=no fi -rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext conftest.$ac_objext conftest.$ac_ext +rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext \ + conftest.$ac_objext conftest.beam conftest.$ac_ext fi - fi -{ echo "$as_me:$LINENO: result: $ac_cv_have_size_t_format" >&5 -echo "${ECHO_T}$ac_cv_have_size_t_format" >&6; } +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_have_size_t_format" >&5 +$as_echo "$ac_cv_have_size_t_format" >&6; } if test "$ac_cv_have_size_t_format" != no ; then -cat >>confdefs.h <<\_ACEOF -#define PY_FORMAT_SIZE_T "z" -_ACEOF +$as_echo "#define PY_FORMAT_SIZE_T \"z\"" >>confdefs.h fi -{ echo "$as_me:$LINENO: checking for socklen_t" >&5 -echo $ECHO_N "checking for socklen_t... $ECHO_C" >&6; } -if test "${ac_cv_type_socklen_t+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 -else - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ - +ac_fn_c_check_type "$LINENO" "socklen_t" "ac_cv_type_socklen_t" " #ifdef HAVE_SYS_TYPES_H #include #endif @@ -27220,72 +13478,25 @@ #include #endif +" +if test "x$ac_cv_type_socklen_t" = x""yes; then : -typedef socklen_t ac__type_new_; -int -main () -{ -if ((ac__type_new_ *) 0) - return 0; -if (sizeof (ac__type_new_)) - return 0; - ; - return 0; -} -_ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - ac_cv_type_socklen_t=yes -else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - ac_cv_type_socklen_t=no -fi - -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext -fi -{ echo "$as_me:$LINENO: result: $ac_cv_type_socklen_t" >&5 -echo "${ECHO_T}$ac_cv_type_socklen_t" >&6; } -if test $ac_cv_type_socklen_t = yes; then - : else -cat >>confdefs.h <<\_ACEOF -#define socklen_t int -_ACEOF +$as_echo "#define socklen_t int" >>confdefs.h fi -{ echo "$as_me:$LINENO: checking for broken mbstowcs" >&5 -echo $ECHO_N "checking for broken mbstowcs... $ECHO_C" >&6; } -if test "${ac_cv_broken_mbstowcs+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for broken mbstowcs" >&5 +$as_echo_n "checking for broken mbstowcs... " >&6; } +if test "${ac_cv_broken_mbstowcs+set}" = set; then : + $as_echo_n "(cached) " >&6 else - if test "$cross_compiling" = yes; then + if test "$cross_compiling" = yes; then : ac_cv_broken_mbstowcs=no else - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF + cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ #include @@ -27297,80 +13508,58 @@ } _ACEOF -rm -f conftest$ac_exeext -if { (ac_try="$ac_link" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_link") 2>&5 - ac_status=$? - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { ac_try='./conftest$ac_exeext' - { (case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_try") 2>&5 - ac_status=$? - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); }; }; then +if ac_fn_c_try_run "$LINENO"; then : ac_cv_broken_mbstowcs=no else - echo "$as_me: program exited with status $ac_status" >&5 -echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - -( exit $ac_status ) -ac_cv_broken_mbstowcs=yes + ac_cv_broken_mbstowcs=yes fi -rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext conftest.$ac_objext conftest.$ac_ext +rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext \ + conftest.$ac_objext conftest.beam conftest.$ac_ext fi - fi -{ echo "$as_me:$LINENO: result: $ac_cv_broken_mbstowcs" >&5 -echo "${ECHO_T}$ac_cv_broken_mbstowcs" >&6; } +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_broken_mbstowcs" >&5 +$as_echo "$ac_cv_broken_mbstowcs" >&6; } if test "$ac_cv_broken_mbstowcs" = yes then -cat >>confdefs.h <<\_ACEOF -#define HAVE_BROKEN_MBSTOWCS 1 -_ACEOF +$as_echo "#define HAVE_BROKEN_MBSTOWCS 1" >>confdefs.h fi # Check for --with-computed-gotos -{ echo "$as_me:$LINENO: checking for --with-computed-gotos" >&5 -echo $ECHO_N "checking for --with-computed-gotos... $ECHO_C" >&6; } +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for --with-computed-gotos" >&5 +$as_echo_n "checking for --with-computed-gotos... " >&6; } # Check whether --with-computed-gotos was given. -if test "${with_computed_gotos+set}" = set; then +if test "${with_computed_gotos+set}" = set; then : withval=$with_computed_gotos; if test "$withval" != no then -cat >>confdefs.h <<\_ACEOF -#define USE_COMPUTED_GOTOS 1 -_ACEOF +$as_echo "#define USE_COMPUTED_GOTOS 1" >>confdefs.h - { echo "$as_me:$LINENO: result: yes" >&5 -echo "${ECHO_T}yes" >&6; } -else { echo "$as_me:$LINENO: result: no" >&5 -echo "${ECHO_T}no" >&6; } + { $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +$as_echo "yes" >&6; } +else { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 +$as_echo "no" >&6; } fi else - { echo "$as_me:$LINENO: result: no" >&5 -echo "${ECHO_T}no" >&6; } + { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 +$as_echo "no" >&6; } fi +case $ac_sys_system in + OSF*) as_fn_error "OSF* systems are deprecated unless somebody volunteers. Check http://bugs.python.org/issue8606" "$LINENO" 5 ;; +esac + + + for h in `(cd $srcdir;echo Python/thread_*.h)` do THREADHEADERS="$THREADHEADERS \$(srcdir)/$h" @@ -27378,15 +13567,15 @@ SRCDIRS="Parser Grammar Objects Python Modules Mac Unittests Unittests/googletest" -{ echo "$as_me:$LINENO: checking for build directories" >&5 -echo $ECHO_N "checking for build directories... $ECHO_C" >&6; } +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for build directories" >&5 +$as_echo_n "checking for build directories... " >&6; } for dir in $SRCDIRS; do if test ! -d $dir; then mkdir -p $dir fi done -{ echo "$as_me:$LINENO: result: done" >&5 -echo "${ECHO_T}done" >&6; } +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: done" >&5 +$as_echo "done" >&6; } # generate output files ac_config_files="$ac_config_files Makefile.pre Modules/Setup.config Misc/python.pc" @@ -27418,12 +13607,13 @@ case $ac_val in #( *${as_nl}*) case $ac_var in #( - *_cv_*) { echo "$as_me:$LINENO: WARNING: Cache variable $ac_var contains a newline." >&5 -echo "$as_me: WARNING: Cache variable $ac_var contains a newline." >&2;} ;; + *_cv_*) { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: cache variable $ac_var contains a newline" >&5 +$as_echo "$as_me: WARNING: cache variable $ac_var contains a newline" >&2;} ;; esac case $ac_var in #( _ | IFS | as_nl) ;; #( - *) $as_unset $ac_var ;; + BASH_ARGV | BASH_SOURCE) eval $ac_var= ;; #( + *) { eval $ac_var=; unset $ac_var;} ;; esac ;; esac done @@ -27431,8 +13621,8 @@ (set) 2>&1 | case $as_nl`(ac_space=' '; set) 2>&1` in #( *${as_nl}ac_space=\ *) - # `set' does not quote correctly, so add quotes (double-quote - # substitution turns \\\\ into \\, and sed turns \\ into \). + # `set' does not quote correctly, so add quotes: double-quote + # substitution turns \\\\ into \\, and sed turns \\ into \. sed -n \ "s/'/'\\\\''/g; s/^\\([_$as_cr_alnum]*_cv_[_$as_cr_alnum]*\\)=\\(.*\\)/\\1='\\2'/p" @@ -27455,12 +13645,12 @@ if diff "$cache_file" confcache >/dev/null 2>&1; then :; else if test -w "$cache_file"; then test "x$cache_file" != "x/dev/null" && - { echo "$as_me:$LINENO: updating cache $cache_file" >&5 -echo "$as_me: updating cache $cache_file" >&6;} + { $as_echo "$as_me:${as_lineno-$LINENO}: updating cache $cache_file" >&5 +$as_echo "$as_me: updating cache $cache_file" >&6;} cat confcache >$cache_file else - { echo "$as_me:$LINENO: not updating unwritable cache $cache_file" >&5 -echo "$as_me: not updating unwritable cache $cache_file" >&6;} + { $as_echo "$as_me:${as_lineno-$LINENO}: not updating unwritable cache $cache_file" >&5 +$as_echo "$as_me: not updating unwritable cache $cache_file" >&6;} fi fi rm -f confcache @@ -27476,11 +13666,11 @@ for ac_i in : $LIBOBJS; do test "x$ac_i" = x: && continue # 1. Remove the extension, and $U if already installed. ac_script='s/\$U\././;s/\.o$//;s/\.obj$//' - ac_i=`echo "$ac_i" | sed "$ac_script"` + ac_i=`$as_echo "$ac_i" | sed "$ac_script"` # 2. Prepend LIBOBJDIR. When used with automake>=1.10 LIBOBJDIR # will be set to the directory where LIBOBJS objects are built. - ac_libobjs="$ac_libobjs \${LIBOBJDIR}$ac_i\$U.$ac_objext" - ac_ltlibobjs="$ac_ltlibobjs \${LIBOBJDIR}$ac_i"'$U.lo' + as_fn_append ac_libobjs " \${LIBOBJDIR}$ac_i\$U.$ac_objext" + as_fn_append ac_ltlibobjs " \${LIBOBJDIR}$ac_i"'$U.lo' done LIBOBJS=$ac_libobjs @@ -27488,12 +13678,15 @@ + : ${CONFIG_STATUS=./config.status} +ac_write_fail=0 ac_clean_files_save=$ac_clean_files ac_clean_files="$ac_clean_files $CONFIG_STATUS" -{ echo "$as_me:$LINENO: creating $CONFIG_STATUS" >&5 -echo "$as_me: creating $CONFIG_STATUS" >&6;} -cat >$CONFIG_STATUS <<_ACEOF +{ $as_echo "$as_me:${as_lineno-$LINENO}: creating $CONFIG_STATUS" >&5 +$as_echo "$as_me: creating $CONFIG_STATUS" >&6;} +as_write_fail=0 +cat >$CONFIG_STATUS <<_ASEOF || as_write_fail=1 #! $SHELL # Generated by $as_me. # Run this file to recreate the current configuration. @@ -27503,59 +13696,79 @@ debug=false ac_cs_recheck=false ac_cs_silent=false -SHELL=\${CONFIG_SHELL-$SHELL} -_ACEOF -cat >>$CONFIG_STATUS <<\_ACEOF -## --------------------- ## -## M4sh Initialization. ## -## --------------------- ## +SHELL=\${CONFIG_SHELL-$SHELL} +export SHELL +_ASEOF +cat >>$CONFIG_STATUS <<\_ASEOF || as_write_fail=1 +## -------------------- ## +## M4sh Initialization. ## +## -------------------- ## # Be more Bourne compatible DUALCASE=1; export DUALCASE # for MKS sh -if test -n "${ZSH_VERSION+set}" && (emulate sh) >/dev/null 2>&1; then +if test -n "${ZSH_VERSION+set}" && (emulate sh) >/dev/null 2>&1; then : emulate sh NULLCMD=: - # Zsh 3.x and 4.x performs word splitting on ${1+"$@"}, which + # Pre-4.2 versions of Zsh do word splitting on ${1+"$@"}, which # is contrary to our usage. Disable this feature. alias -g '${1+"$@"}'='"$@"' setopt NO_GLOB_SUBST else - case `(set -o) 2>/dev/null` in - *posix*) set -o posix ;; + case `(set -o) 2>/dev/null` in #( + *posix*) : + set -o posix ;; #( + *) : + ;; esac - fi - - -# PATH needs CR -# Avoid depending upon Character Ranges. -as_cr_letters='abcdefghijklmnopqrstuvwxyz' -as_cr_LETTERS='ABCDEFGHIJKLMNOPQRSTUVWXYZ' -as_cr_Letters=$as_cr_letters$as_cr_LETTERS -as_cr_digits='0123456789' -as_cr_alnum=$as_cr_Letters$as_cr_digits - -# The user is always right. -if test "${PATH_SEPARATOR+set}" != set; then - echo "#! /bin/sh" >conf$$.sh - echo "exit 0" >>conf$$.sh - chmod +x conf$$.sh - if (PATH="/nonexistent;."; conf$$.sh) >/dev/null 2>&1; then - PATH_SEPARATOR=';' - else - PATH_SEPARATOR=: +as_nl=' +' +export as_nl +# Printing a long string crashes Solaris 7 /usr/bin/printf. +as_echo='\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\' +as_echo=$as_echo$as_echo$as_echo$as_echo$as_echo +as_echo=$as_echo$as_echo$as_echo$as_echo$as_echo$as_echo +# Prefer a ksh shell builtin over an external printf program on Solaris, +# but without wasting forks for bash or zsh. +if test -z "$BASH_VERSION$ZSH_VERSION" \ + && (test "X`print -r -- $as_echo`" = "X$as_echo") 2>/dev/null; then + as_echo='print -r --' + as_echo_n='print -rn --' +elif (test "X`printf %s $as_echo`" = "X$as_echo") 2>/dev/null; then + as_echo='printf %s\n' + as_echo_n='printf %s' +else + if test "X`(/usr/ucb/echo -n -n $as_echo) 2>/dev/null`" = "X-n $as_echo"; then + as_echo_body='eval /usr/ucb/echo -n "$1$as_nl"' + as_echo_n='/usr/ucb/echo -n' + else + as_echo_body='eval expr "X$1" : "X\\(.*\\)"' + as_echo_n_body='eval + arg=$1; + case $arg in #( + *"$as_nl"*) + expr "X$arg" : "X\\(.*\\)$as_nl"; + arg=`expr "X$arg" : ".*$as_nl\\(.*\\)"`;; + esac; + expr "X$arg" : "X\\(.*\\)" | tr -d "$as_nl" + ' + export as_echo_n_body + as_echo_n='sh -c $as_echo_n_body as_echo' fi - rm -f conf$$.sh + export as_echo_body + as_echo='sh -c $as_echo_body as_echo' fi -# Support unset when possible. -if ( (MAIL=60; unset MAIL) || exit) >/dev/null 2>&1; then - as_unset=unset -else - as_unset=false +# The user is always right. +if test "${PATH_SEPARATOR+set}" != set; then + PATH_SEPARATOR=: + (PATH='/bin;/bin'; FPATH=$PATH; sh -c :) >/dev/null 2>&1 && { + (PATH='/bin:/bin'; FPATH=$PATH; sh -c :) >/dev/null 2>&1 || + PATH_SEPARATOR=';' + } fi @@ -27564,20 +13777,18 @@ # there to prevent editors from complaining about space-tab. # (If _AS_PATH_WALK were called with IFS unset, it would disable word # splitting by setting IFS to empty value.) -as_nl=' -' IFS=" "" $as_nl" # Find who we are. Look in the path if we contain no directory separator. -case $0 in +case $0 in #(( *[\\/]* ) as_myself=$0 ;; *) as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $PATH do IFS=$as_save_IFS test -z "$as_dir" && as_dir=. - test -r "$as_dir/$0" && as_myself=$as_dir/$0 && break -done + test -r "$as_dir/$0" && as_myself=$as_dir/$0 && break + done IFS=$as_save_IFS ;; @@ -27588,32 +13799,111 @@ as_myself=$0 fi if test ! -f "$as_myself"; then - echo "$as_myself: error: cannot find myself; rerun with an absolute file name" >&2 - { (exit 1); exit 1; } + $as_echo "$as_myself: error: cannot find myself; rerun with an absolute file name" >&2 + exit 1 fi -# Work around bugs in pre-3.0 UWIN ksh. -for as_var in ENV MAIL MAILPATH -do ($as_unset $as_var) >/dev/null 2>&1 && $as_unset $as_var +# Unset variables that we do not need and which cause bugs (e.g. in +# pre-3.0 UWIN ksh). But do not cause bugs in bash 2.01; the "|| exit 1" +# suppresses any "Segmentation fault" message there. '((' could +# trigger a bug in pdksh 5.2.14. +for as_var in BASH_ENV ENV MAIL MAILPATH +do eval test x\${$as_var+set} = xset \ + && ( (unset $as_var) || exit 1) >/dev/null 2>&1 && unset $as_var || : done PS1='$ ' PS2='> ' PS4='+ ' # NLS nuisances. -for as_var in \ - LANG LANGUAGE LC_ADDRESS LC_ALL LC_COLLATE LC_CTYPE LC_IDENTIFICATION \ - LC_MEASUREMENT LC_MESSAGES LC_MONETARY LC_NAME LC_NUMERIC LC_PAPER \ - LC_TELEPHONE LC_TIME -do - if (set +x; test -z "`(eval $as_var=C; export $as_var) 2>&1`"); then - eval $as_var=C; export $as_var - else - ($as_unset $as_var) >/dev/null 2>&1 && $as_unset $as_var - fi -done +LC_ALL=C +export LC_ALL +LANGUAGE=C +export LANGUAGE + +# CDPATH. +(unset CDPATH) >/dev/null 2>&1 && unset CDPATH + + +# as_fn_error ERROR [LINENO LOG_FD] +# --------------------------------- +# Output "`basename $0`: error: ERROR" to stderr. If LINENO and LOG_FD are +# provided, also output the error to LOG_FD, referencing LINENO. Then exit the +# script with status $?, using 1 if that was 0. +as_fn_error () +{ + as_status=$?; test $as_status -eq 0 && as_status=1 + if test "$3"; then + as_lineno=${as_lineno-"$2"} as_lineno_stack=as_lineno_stack=$as_lineno_stack + $as_echo "$as_me:${as_lineno-$LINENO}: error: $1" >&$3 + fi + $as_echo "$as_me: error: $1" >&2 + as_fn_exit $as_status +} # as_fn_error + + +# as_fn_set_status STATUS +# ----------------------- +# Set $? to STATUS, without forking. +as_fn_set_status () +{ + return $1 +} # as_fn_set_status + +# as_fn_exit STATUS +# ----------------- +# Exit the shell with STATUS, even in a "trap 0" or "set -e" context. +as_fn_exit () +{ + set +e + as_fn_set_status $1 + exit $1 +} # as_fn_exit + +# as_fn_unset VAR +# --------------- +# Portably unset VAR. +as_fn_unset () +{ + { eval $1=; unset $1;} +} +as_unset=as_fn_unset +# as_fn_append VAR VALUE +# ---------------------- +# Append the text in VALUE to the end of the definition contained in VAR. Take +# advantage of any shell optimizations that allow amortized linear growth over +# repeated appends, instead of the typical quadratic growth present in naive +# implementations. +if (eval "as_var=1; as_var+=2; test x\$as_var = x12") 2>/dev/null; then : + eval 'as_fn_append () + { + eval $1+=\$2 + }' +else + as_fn_append () + { + eval $1=\$$1\$2 + } +fi # as_fn_append + +# as_fn_arith ARG... +# ------------------ +# Perform arithmetic evaluation on the ARGs, and store the result in the +# global $as_val. Take advantage of shells that can avoid forks. The arguments +# must be portable across $(()) and expr. +if (eval "test \$(( 1 + 1 )) = 2") 2>/dev/null; then : + eval 'as_fn_arith () + { + as_val=$(( $* )) + }' +else + as_fn_arith () + { + as_val=`expr "$@" || test $? -eq 1` + } +fi # as_fn_arith + -# Required to use basename. if expr a : '\(a\)' >/dev/null 2>&1 && test "X`expr 00001 : '.*\(...\)'`" = X001; then as_expr=expr @@ -27627,13 +13917,17 @@ as_basename=false fi +if (as_dir=`dirname -- /` && test "X$as_dir" = X/) >/dev/null 2>&1; then + as_dirname=dirname +else + as_dirname=false +fi -# Name of the executable. as_me=`$as_basename -- "$0" || $as_expr X/"$0" : '.*/\([^/][^/]*\)/*$' \| \ X"$0" : 'X\(//\)$' \| \ X"$0" : 'X\(/\)' \| . 2>/dev/null || -echo X/"$0" | +$as_echo X/"$0" | sed '/^.*\/\([^/][^/]*\)\/*$/{ s//\1/ q @@ -27648,104 +13942,103 @@ } s/.*/./; q'` -# CDPATH. -$as_unset CDPATH - - - - as_lineno_1=$LINENO - as_lineno_2=$LINENO - test "x$as_lineno_1" != "x$as_lineno_2" && - test "x`expr $as_lineno_1 + 1`" = "x$as_lineno_2" || { - - # Create $as_me.lineno as a copy of $as_myself, but with $LINENO - # uniformly replaced by the line number. The first 'sed' inserts a - # line-number line after each line using $LINENO; the second 'sed' - # does the real work. The second script uses 'N' to pair each - # line-number line with the line containing $LINENO, and appends - # trailing '-' during substitution so that $LINENO is not a special - # case at line end. - # (Raja R Harinath suggested sed '=', and Paul Eggert wrote the - # scripts with optimization help from Paolo Bonzini. Blame Lee - # E. McMahon (1931-1989) for sed's syntax. :-) - sed -n ' - p - /[$]LINENO/= - ' <$as_myself | - sed ' - s/[$]LINENO.*/&-/ - t lineno - b - :lineno - N - :loop - s/[$]LINENO\([^'$as_cr_alnum'_].*\n\)\(.*\)/\2\1\2/ - t loop - s/-\n.*// - ' >$as_me.lineno && - chmod +x "$as_me.lineno" || - { echo "$as_me: error: cannot create $as_me.lineno; rerun with a POSIX shell" >&2 - { (exit 1); exit 1; }; } - - # Don't try to exec as it changes $[0], causing all sort of problems - # (the dirname of $[0] is not the place where we might find the - # original and so on. Autoconf is especially sensitive to this). - . "./$as_me.lineno" - # Exit status is that of the last command. - exit -} - - -if (as_dir=`dirname -- /` && test "X$as_dir" = X/) >/dev/null 2>&1; then - as_dirname=dirname -else - as_dirname=false -fi +# Avoid depending upon Character Ranges. +as_cr_letters='abcdefghijklmnopqrstuvwxyz' +as_cr_LETTERS='ABCDEFGHIJKLMNOPQRSTUVWXYZ' +as_cr_Letters=$as_cr_letters$as_cr_LETTERS +as_cr_digits='0123456789' +as_cr_alnum=$as_cr_Letters$as_cr_digits ECHO_C= ECHO_N= ECHO_T= -case `echo -n x` in +case `echo -n x` in #((((( -n*) - case `echo 'x\c'` in + case `echo 'xy\c'` in *c*) ECHO_T=' ';; # ECHO_T is single tab character. - *) ECHO_C='\c';; + xy) ECHO_C='\c';; + *) echo `echo ksh88 bug on AIX 6.1` > /dev/null + ECHO_T=' ';; esac;; *) ECHO_N='-n';; esac -if expr a : '\(a\)' >/dev/null 2>&1 && - test "X`expr 00001 : '.*\(...\)'`" = X001; then - as_expr=expr -else - as_expr=false -fi - rm -f conf$$ conf$$.exe conf$$.file if test -d conf$$.dir; then rm -f conf$$.dir/conf$$.file else rm -f conf$$.dir - mkdir conf$$.dir + mkdir conf$$.dir 2>/dev/null fi -echo >conf$$.file -if ln -s conf$$.file conf$$ 2>/dev/null; then - as_ln_s='ln -s' - # ... but there are two gotchas: - # 1) On MSYS, both `ln -s file dir' and `ln file dir' fail. - # 2) DJGPP < 2.04 has no symlinks; `ln -s' creates a wrapper executable. - # In both cases, we have to default to `cp -p'. - ln -s conf$$.file conf$$.dir 2>/dev/null && test ! -f conf$$.exe || +if (echo >conf$$.file) 2>/dev/null; then + if ln -s conf$$.file conf$$ 2>/dev/null; then + as_ln_s='ln -s' + # ... but there are two gotchas: + # 1) On MSYS, both `ln -s file dir' and `ln file dir' fail. + # 2) DJGPP < 2.04 has no symlinks; `ln -s' creates a wrapper executable. + # In both cases, we have to default to `cp -p'. + ln -s conf$$.file conf$$.dir 2>/dev/null && test ! -f conf$$.exe || + as_ln_s='cp -p' + elif ln conf$$.file conf$$ 2>/dev/null; then + as_ln_s=ln + else as_ln_s='cp -p' -elif ln conf$$.file conf$$ 2>/dev/null; then - as_ln_s=ln + fi else as_ln_s='cp -p' fi rm -f conf$$ conf$$.exe conf$$.dir/conf$$.file conf$$.file rmdir conf$$.dir 2>/dev/null + +# as_fn_mkdir_p +# ------------- +# Create "$as_dir" as a directory, including parents if necessary. +as_fn_mkdir_p () +{ + + case $as_dir in #( + -*) as_dir=./$as_dir;; + esac + test -d "$as_dir" || eval $as_mkdir_p || { + as_dirs= + while :; do + case $as_dir in #( + *\'*) as_qdir=`$as_echo "$as_dir" | sed "s/'/'\\\\\\\\''/g"`;; #'( + *) as_qdir=$as_dir;; + esac + as_dirs="'$as_qdir' $as_dirs" + as_dir=`$as_dirname -- "$as_dir" || +$as_expr X"$as_dir" : 'X\(.*[^/]\)//*[^/][^/]*/*$' \| \ + X"$as_dir" : 'X\(//\)[^/]' \| \ + X"$as_dir" : 'X\(//\)$' \| \ + X"$as_dir" : 'X\(/\)' \| . 2>/dev/null || +$as_echo X"$as_dir" | + sed '/^X\(.*[^/]\)\/\/*[^/][^/]*\/*$/{ + s//\1/ + q + } + /^X\(\/\/\)[^/].*/{ + s//\1/ + q + } + /^X\(\/\/\)$/{ + s//\1/ + q + } + /^X\(\/\).*/{ + s//\1/ + q + } + s/.*/./; q'` + test -d "$as_dir" && break + done + test -z "$as_dirs" || eval "mkdir $as_dirs" + } || test -d "$as_dir" || as_fn_error "cannot create directory $as_dir" + + +} # as_fn_mkdir_p if mkdir -p . 2>/dev/null; then - as_mkdir_p=: + as_mkdir_p='mkdir -p "$as_dir"' else test -d ./-p && rmdir ./-p as_mkdir_p=false @@ -27762,12 +14055,12 @@ as_test_x=' eval sh -c '\'' if test -d "$1"; then - test -d "$1/."; + test -d "$1/."; else - case $1 in - -*)set "./$1";; + case $1 in #( + -*)set "./$1";; esac; - case `ls -ld'$as_ls_L_option' "$1" 2>/dev/null` in + case `ls -ld'$as_ls_L_option' "$1" 2>/dev/null` in #(( ???[sx]*):;;*)false;;esac;fi '\'' sh ' @@ -27782,13 +14075,19 @@ exec 6>&1 +## ----------------------------------- ## +## Main body of $CONFIG_STATUS script. ## +## ----------------------------------- ## +_ASEOF +test $as_write_fail = 0 && chmod +x $CONFIG_STATUS || ac_write_fail=1 -# Save the log message, to keep $[0] and so on meaningful, and to +cat >>$CONFIG_STATUS <<\_ACEOF || ac_write_fail=1 +# Save the log message, to keep $0 and so on meaningful, and to # report actual input values of CONFIG_FILES etc. instead of their # values after options handling. ac_log=" This file was extended by python $as_me 3.2, which was -generated by GNU Autoconf 2.61. Invocation command line was +generated by GNU Autoconf 2.65. Invocation command line was CONFIG_FILES = $CONFIG_FILES CONFIG_HEADERS = $CONFIG_HEADERS @@ -27801,29 +14100,41 @@ _ACEOF -cat >>$CONFIG_STATUS <<_ACEOF +case $ac_config_files in *" +"*) set x $ac_config_files; shift; ac_config_files=$*;; +esac + +case $ac_config_headers in *" +"*) set x $ac_config_headers; shift; ac_config_headers=$*;; +esac + + +cat >>$CONFIG_STATUS <<_ACEOF || ac_write_fail=1 # Files that config.status was made for. config_files="$ac_config_files" config_headers="$ac_config_headers" _ACEOF -cat >>$CONFIG_STATUS <<\_ACEOF +cat >>$CONFIG_STATUS <<\_ACEOF || ac_write_fail=1 ac_cs_usage="\ -\`$as_me' instantiates files from templates according to the -current configuration. +\`$as_me' instantiates files and other configuration actions +from templates according to the current configuration. Unless the files +and actions are specified as TAGs, all are instantiated by default. -Usage: $0 [OPTIONS] [FILE]... +Usage: $0 [OPTION]... [TAG]... -h, --help print this help, then exit -V, --version print version number and configuration settings, then exit - -q, --quiet do not print progress messages + --config print configuration, then exit + -q, --quiet, --silent + do not print progress messages -d, --debug don't remove temporary files --recheck update $as_me by reconfiguring in the same conditions - --file=FILE[:TEMPLATE] - instantiate the configuration file FILE - --header=FILE[:TEMPLATE] - instantiate the configuration header FILE + --file=FILE[:TEMPLATE] + instantiate the configuration file FILE + --header=FILE[:TEMPLATE] + instantiate the configuration header FILE Configuration files: $config_files @@ -27831,27 +14142,28 @@ Configuration headers: $config_headers -Report bugs to ." +Report bugs to ." _ACEOF -cat >>$CONFIG_STATUS <<_ACEOF +cat >>$CONFIG_STATUS <<_ACEOF || ac_write_fail=1 +ac_cs_config="`$as_echo "$ac_configure_args" | sed 's/^ //; s/[\\""\`\$]/\\\\&/g'`" ac_cs_version="\\ python config.status 3.2 -configured by $0, generated by GNU Autoconf 2.61, - with options \\"`echo "$ac_configure_args" | sed 's/^ //; s/[\\""\`\$]/\\\\&/g'`\\" +configured by $0, generated by GNU Autoconf 2.65, + with options \\"\$ac_cs_config\\" -Copyright (C) 2006 Free Software Foundation, Inc. +Copyright (C) 2009 Free Software Foundation, Inc. This config.status script is free software; the Free Software Foundation gives unlimited permission to copy, distribute and modify it." ac_pwd='$ac_pwd' srcdir='$srcdir' INSTALL='$INSTALL' +test -n "\$AWK" || AWK=awk _ACEOF -cat >>$CONFIG_STATUS <<\_ACEOF -# If no file are specified by the user, then we need to provide default -# value. By we need to know if files were specified by the user. +cat >>$CONFIG_STATUS <<\_ACEOF || ac_write_fail=1 +# The default lists apply if the user does not specify any file. ac_need_defaults=: while test $# != 0 do @@ -27873,34 +14185,40 @@ -recheck | --recheck | --rechec | --reche | --rech | --rec | --re | --r) ac_cs_recheck=: ;; --version | --versio | --versi | --vers | --ver | --ve | --v | -V ) - echo "$ac_cs_version"; exit ;; + $as_echo "$ac_cs_version"; exit ;; + --config | --confi | --conf | --con | --co | --c ) + $as_echo "$ac_cs_config"; exit ;; --debug | --debu | --deb | --de | --d | -d ) debug=: ;; --file | --fil | --fi | --f ) $ac_shift - CONFIG_FILES="$CONFIG_FILES $ac_optarg" + case $ac_optarg in + *\'*) ac_optarg=`$as_echo "$ac_optarg" | sed "s/'/'\\\\\\\\''/g"` ;; + esac + as_fn_append CONFIG_FILES " '$ac_optarg'" ac_need_defaults=false;; --header | --heade | --head | --hea ) $ac_shift - CONFIG_HEADERS="$CONFIG_HEADERS $ac_optarg" + case $ac_optarg in + *\'*) ac_optarg=`$as_echo "$ac_optarg" | sed "s/'/'\\\\\\\\''/g"` ;; + esac + as_fn_append CONFIG_HEADERS " '$ac_optarg'" ac_need_defaults=false;; --he | --h) # Conflict between --help and --header - { echo "$as_me: error: ambiguous option: $1 -Try \`$0 --help' for more information." >&2 - { (exit 1); exit 1; }; };; + as_fn_error "ambiguous option: \`$1' +Try \`$0 --help' for more information.";; --help | --hel | -h ) - echo "$ac_cs_usage"; exit ;; + $as_echo "$ac_cs_usage"; exit ;; -q | -quiet | --quiet | --quie | --qui | --qu | --q \ | -silent | --silent | --silen | --sile | --sil | --si | --s) ac_cs_silent=: ;; # This is an error. - -*) { echo "$as_me: error: unrecognized option: $1 -Try \`$0 --help' for more information." >&2 - { (exit 1); exit 1; }; } ;; + -*) as_fn_error "unrecognized option: \`$1' +Try \`$0 --help' for more information." ;; - *) ac_config_targets="$ac_config_targets $1" + *) as_fn_append ac_config_targets " $1" ac_need_defaults=false ;; esac @@ -27915,30 +14233,32 @@ fi _ACEOF -cat >>$CONFIG_STATUS <<_ACEOF +cat >>$CONFIG_STATUS <<_ACEOF || ac_write_fail=1 if \$ac_cs_recheck; then - echo "running CONFIG_SHELL=$SHELL $SHELL $0 "$ac_configure_args \$ac_configure_extra_args " --no-create --no-recursion" >&6 - CONFIG_SHELL=$SHELL + set X '$SHELL' '$0' $ac_configure_args \$ac_configure_extra_args --no-create --no-recursion + shift + \$as_echo "running CONFIG_SHELL=$SHELL \$*" >&6 + CONFIG_SHELL='$SHELL' export CONFIG_SHELL - exec $SHELL "$0"$ac_configure_args \$ac_configure_extra_args --no-create --no-recursion + exec "\$@" fi _ACEOF -cat >>$CONFIG_STATUS <<\_ACEOF +cat >>$CONFIG_STATUS <<\_ACEOF || ac_write_fail=1 exec 5>>config.log { echo sed 'h;s/./-/g;s/^.../## /;s/...$/ ##/;p;x;p;x' <<_ASBOX ## Running $as_me. ## _ASBOX - echo "$ac_log" + $as_echo "$ac_log" } >&5 _ACEOF -cat >>$CONFIG_STATUS <<_ACEOF +cat >>$CONFIG_STATUS <<_ACEOF || ac_write_fail=1 _ACEOF -cat >>$CONFIG_STATUS <<\_ACEOF +cat >>$CONFIG_STATUS <<\_ACEOF || ac_write_fail=1 # Handling of arguments. for ac_config_target in $ac_config_targets @@ -27953,9 +14273,7 @@ "Modules/Setup.config") CONFIG_FILES="$CONFIG_FILES Modules/Setup.config" ;; "Misc/python.pc") CONFIG_FILES="$CONFIG_FILES Misc/python.pc" ;; - *) { { echo "$as_me:$LINENO: error: invalid argument: $ac_config_target" >&5 -echo "$as_me: error: invalid argument: $ac_config_target" >&2;} - { (exit 1); exit 1; }; };; + *) as_fn_error "invalid argument: \`$ac_config_target'" "$LINENO" 5;; esac done @@ -27981,7 +14299,7 @@ trap 'exit_status=$? { test -z "$tmp" || test ! -d "$tmp" || rm -fr "$tmp"; } && exit $exit_status ' 0 - trap '{ (exit 1); exit 1; }' 1 2 13 15 + trap 'as_fn_exit 1' 1 2 13 15 } # Create a (secure) tmp directory for tmp files. @@ -27992,229 +14310,139 @@ { tmp=./conf$$-$RANDOM (umask 077 && mkdir "$tmp") -} || -{ - echo "$me: cannot create a temporary directory in ." >&2 - { (exit 1); exit 1; } -} - -# -# Set up the sed scripts for CONFIG_FILES section. -# +} || as_fn_error "cannot create a temporary directory in ." "$LINENO" 5 -# No need to generate the scripts if there are no CONFIG_FILES. -# This happens for instance when ./config.status config.h +# Set up the scripts for CONFIG_FILES section. +# No need to generate them if there are no CONFIG_FILES. +# This happens for instance with `./config.status config.h'. if test -n "$CONFIG_FILES"; then -_ACEOF - - - -ac_delim='%!_!# ' -for ac_last_try in false false false false false :; do - cat >conf$$subs.sed <<_ACEOF -SHELL!$SHELL$ac_delim -PATH_SEPARATOR!$PATH_SEPARATOR$ac_delim -PACKAGE_NAME!$PACKAGE_NAME$ac_delim -PACKAGE_TARNAME!$PACKAGE_TARNAME$ac_delim -PACKAGE_VERSION!$PACKAGE_VERSION$ac_delim -PACKAGE_STRING!$PACKAGE_STRING$ac_delim -PACKAGE_BUGREPORT!$PACKAGE_BUGREPORT$ac_delim -exec_prefix!$exec_prefix$ac_delim -prefix!$prefix$ac_delim -program_transform_name!$program_transform_name$ac_delim -bindir!$bindir$ac_delim -sbindir!$sbindir$ac_delim -libexecdir!$libexecdir$ac_delim -datarootdir!$datarootdir$ac_delim -datadir!$datadir$ac_delim -sysconfdir!$sysconfdir$ac_delim -sharedstatedir!$sharedstatedir$ac_delim -localstatedir!$localstatedir$ac_delim -includedir!$includedir$ac_delim -oldincludedir!$oldincludedir$ac_delim -docdir!$docdir$ac_delim -infodir!$infodir$ac_delim -htmldir!$htmldir$ac_delim -dvidir!$dvidir$ac_delim -pdfdir!$pdfdir$ac_delim -psdir!$psdir$ac_delim -libdir!$libdir$ac_delim -localedir!$localedir$ac_delim -mandir!$mandir$ac_delim -DEFS!$DEFS$ac_delim -ECHO_C!$ECHO_C$ac_delim -ECHO_N!$ECHO_N$ac_delim -ECHO_T!$ECHO_T$ac_delim -LIBS!$LIBS$ac_delim -build_alias!$build_alias$ac_delim -host_alias!$host_alias$ac_delim -target_alias!$target_alias$ac_delim -VERSION!$VERSION$ac_delim -SOVERSION!$SOVERSION$ac_delim -CONFIG_ARGS!$CONFIG_ARGS$ac_delim -UNIVERSALSDK!$UNIVERSALSDK$ac_delim -ARCH_RUN_32BIT!$ARCH_RUN_32BIT$ac_delim -LIPO_32BIT_FLAGS!$LIPO_32BIT_FLAGS$ac_delim -PYTHONFRAMEWORK!$PYTHONFRAMEWORK$ac_delim -PYTHONFRAMEWORKIDENTIFIER!$PYTHONFRAMEWORKIDENTIFIER$ac_delim -PYTHONFRAMEWORKDIR!$PYTHONFRAMEWORKDIR$ac_delim -PYTHONFRAMEWORKPREFIX!$PYTHONFRAMEWORKPREFIX$ac_delim -PYTHONFRAMEWORKINSTALLDIR!$PYTHONFRAMEWORKINSTALLDIR$ac_delim -FRAMEWORKINSTALLFIRST!$FRAMEWORKINSTALLFIRST$ac_delim -FRAMEWORKINSTALLLAST!$FRAMEWORKINSTALLLAST$ac_delim -FRAMEWORKALTINSTALLFIRST!$FRAMEWORKALTINSTALLFIRST$ac_delim -FRAMEWORKALTINSTALLLAST!$FRAMEWORKALTINSTALLLAST$ac_delim -FRAMEWORKUNIXTOOLSPREFIX!$FRAMEWORKUNIXTOOLSPREFIX$ac_delim -MACHDEP!$MACHDEP$ac_delim -SGI_ABI!$SGI_ABI$ac_delim -CONFIGURE_MACOSX_DEPLOYMENT_TARGET!$CONFIGURE_MACOSX_DEPLOYMENT_TARGET$ac_delim -EXPORT_MACOSX_DEPLOYMENT_TARGET!$EXPORT_MACOSX_DEPLOYMENT_TARGET$ac_delim -CC!$CC$ac_delim -CFLAGS!$CFLAGS$ac_delim -LDFLAGS!$LDFLAGS$ac_delim -CPPFLAGS!$CPPFLAGS$ac_delim -ac_ct_CC!$ac_ct_CC$ac_delim -EXEEXT!$EXEEXT$ac_delim -OBJEXT!$OBJEXT$ac_delim -CXX!$CXX$ac_delim -MAINCC!$MAINCC$ac_delim -CPP!$CPP$ac_delim -GREP!$GREP$ac_delim -EGREP!$EGREP$ac_delim -BUILDEXEEXT!$BUILDEXEEXT$ac_delim -LIBRARY!$LIBRARY$ac_delim -LDLIBRARY!$LDLIBRARY$ac_delim -DLLLIBRARY!$DLLLIBRARY$ac_delim -BLDLIBRARY!$BLDLIBRARY$ac_delim -LDLIBRARYDIR!$LDLIBRARYDIR$ac_delim -INSTSONAME!$INSTSONAME$ac_delim -RUNSHARED!$RUNSHARED$ac_delim -LINKCC!$LINKCC$ac_delim -GNULD!$GNULD$ac_delim -RANLIB!$RANLIB$ac_delim -AR!$AR$ac_delim -ARFLAGS!$ARFLAGS$ac_delim -SVNVERSION!$SVNVERSION$ac_delim -INSTALL_PROGRAM!$INSTALL_PROGRAM$ac_delim -INSTALL_SCRIPT!$INSTALL_SCRIPT$ac_delim -INSTALL_DATA!$INSTALL_DATA$ac_delim -LN!$LN$ac_delim -OPT!$OPT$ac_delim -BASECFLAGS!$BASECFLAGS$ac_delim -UNIVERSAL_ARCH_FLAGS!$UNIVERSAL_ARCH_FLAGS$ac_delim -OTHER_LIBTOOL_OPT!$OTHER_LIBTOOL_OPT$ac_delim -LIBTOOL_CRUFT!$LIBTOOL_CRUFT$ac_delim -SO!$SO$ac_delim -LDSHARED!$LDSHARED$ac_delim -LDCXXSHARED!$LDCXXSHARED$ac_delim -BLDSHARED!$BLDSHARED$ac_delim -CCSHARED!$CCSHARED$ac_delim -_ACEOF - - if test `sed -n "s/.*$ac_delim\$/X/p" conf$$subs.sed | grep -c X` = 97; then - break - elif $ac_last_try; then - { { echo "$as_me:$LINENO: error: could not make $CONFIG_STATUS" >&5 -echo "$as_me: error: could not make $CONFIG_STATUS" >&2;} - { (exit 1); exit 1; }; } - else - ac_delim="$ac_delim!$ac_delim _$ac_delim!! " - fi -done -ac_eof=`sed -n '/^CEOF[0-9]*$/s/CEOF/0/p' conf$$subs.sed` -if test -n "$ac_eof"; then - ac_eof=`echo "$ac_eof" | sort -nru | sed 1q` - ac_eof=`expr $ac_eof + 1` +ac_cr=`echo X | tr X '\015'` +# On cygwin, bash can eat \r inside `` if the user requested igncr. +# But we know of no other shell where ac_cr would be empty at this +# point, so we can use a bashism as a fallback. +if test "x$ac_cr" = x; then + eval ac_cr=\$\'\\r\' +fi +ac_cs_awk_cr=`$AWK 'BEGIN { print "a\rb" }' /dev/null` +if test "$ac_cs_awk_cr" = "a${ac_cr}b"; then + ac_cs_awk_cr='\r' +else + ac_cs_awk_cr=$ac_cr fi -cat >>$CONFIG_STATUS <<_ACEOF -cat >"\$tmp/subs-1.sed" <<\CEOF$ac_eof -/@[a-zA-Z_][a-zA-Z_0-9]*@/!b -_ACEOF -sed ' -s/[,\\&]/\\&/g; s/@/@|#_!!_#|/g -s/^/s,@/; s/!/@,|#_!!_#|/ -:n -t n -s/'"$ac_delim"'$/,g/; t -s/$/\\/; p -N; s/^.*\n//; s/[,\\&]/\\&/g; s/@/@|#_!!_#|/g; b n -' >>$CONFIG_STATUS >$CONFIG_STATUS <<_ACEOF -CEOF$ac_eof +echo 'BEGIN {' >"$tmp/subs1.awk" && _ACEOF +{ + echo "cat >conf$$subs.awk <<_ACEOF" && + echo "$ac_subst_vars" | sed 's/.*/&!$&$ac_delim/' && + echo "_ACEOF" +} >conf$$subs.sh || + as_fn_error "could not make $CONFIG_STATUS" "$LINENO" 5 +ac_delim_num=`echo "$ac_subst_vars" | grep -c '$'` ac_delim='%!_!# ' for ac_last_try in false false false false false :; do - cat >conf$$subs.sed <<_ACEOF -LINKFORSHARED!$LINKFORSHARED$ac_delim -CFLAGSFORSHARED!$CFLAGSFORSHARED$ac_delim -SHLIBS!$SHLIBS$ac_delim -PKG_CONFIG!$PKG_CONFIG$ac_delim -LIBFFI_INCLUDEDIR!$LIBFFI_INCLUDEDIR$ac_delim -USE_SIGNAL_MODULE!$USE_SIGNAL_MODULE$ac_delim -SIGNAL_OBJS!$SIGNAL_OBJS$ac_delim -USE_THREAD_MODULE!$USE_THREAD_MODULE$ac_delim -LDLAST!$LDLAST$ac_delim -THREADOBJ!$THREADOBJ$ac_delim -DLINCLDIR!$DLINCLDIR$ac_delim -DYNLOADFILE!$DYNLOADFILE$ac_delim -MACHDEP_OBJS!$MACHDEP_OBJS$ac_delim -TRUE!$TRUE$ac_delim -LIBOBJS!$LIBOBJS$ac_delim -HAVE_GETHOSTBYNAME_R_6_ARG!$HAVE_GETHOSTBYNAME_R_6_ARG$ac_delim -HAVE_GETHOSTBYNAME_R_5_ARG!$HAVE_GETHOSTBYNAME_R_5_ARG$ac_delim -HAVE_GETHOSTBYNAME_R_3_ARG!$HAVE_GETHOSTBYNAME_R_3_ARG$ac_delim -HAVE_GETHOSTBYNAME_R!$HAVE_GETHOSTBYNAME_R$ac_delim -HAVE_GETHOSTBYNAME!$HAVE_GETHOSTBYNAME$ac_delim -LIBM!$LIBM$ac_delim -LIBC!$LIBC$ac_delim -THREADHEADERS!$THREADHEADERS$ac_delim -SRCDIRS!$SRCDIRS$ac_delim -LTLIBOBJS!$LTLIBOBJS$ac_delim -_ACEOF + . ./conf$$subs.sh || + as_fn_error "could not make $CONFIG_STATUS" "$LINENO" 5 - if test `sed -n "s/.*$ac_delim\$/X/p" conf$$subs.sed | grep -c X` = 25; then + ac_delim_n=`sed -n "s/.*$ac_delim\$/X/p" conf$$subs.awk | grep -c X` + if test $ac_delim_n = $ac_delim_num; then break elif $ac_last_try; then - { { echo "$as_me:$LINENO: error: could not make $CONFIG_STATUS" >&5 -echo "$as_me: error: could not make $CONFIG_STATUS" >&2;} - { (exit 1); exit 1; }; } + as_fn_error "could not make $CONFIG_STATUS" "$LINENO" 5 else ac_delim="$ac_delim!$ac_delim _$ac_delim!! " fi done +rm -f conf$$subs.sh -ac_eof=`sed -n '/^CEOF[0-9]*$/s/CEOF/0/p' conf$$subs.sed` -if test -n "$ac_eof"; then - ac_eof=`echo "$ac_eof" | sort -nru | sed 1q` - ac_eof=`expr $ac_eof + 1` -fi - -cat >>$CONFIG_STATUS <<_ACEOF -cat >"\$tmp/subs-2.sed" <<\CEOF$ac_eof -/@[a-zA-Z_][a-zA-Z_0-9]*@/!b end -_ACEOF -sed ' -s/[,\\&]/\\&/g; s/@/@|#_!!_#|/g -s/^/s,@/; s/!/@,|#_!!_#|/ -:n -t n -s/'"$ac_delim"'$/,g/; t -s/$/\\/; p -N; s/^.*\n//; s/[,\\&]/\\&/g; s/@/@|#_!!_#|/g; b n -' >>$CONFIG_STATUS >$CONFIG_STATUS <<_ACEOF -:end -s/|#_!!_#|//g -CEOF$ac_eof +cat >>$CONFIG_STATUS <<_ACEOF || ac_write_fail=1 +cat >>"\$tmp/subs1.awk" <<\\_ACAWK && _ACEOF +sed -n ' +h +s/^/S["/; s/!.*/"]=/ +p +g +s/^[^!]*!// +:repl +t repl +s/'"$ac_delim"'$// +t delim +:nl +h +s/\(.\{148\}\)..*/\1/ +t more1 +s/["\\]/\\&/g; s/^/"/; s/$/\\n"\\/ +p +n +b repl +:more1 +s/["\\]/\\&/g; s/^/"/; s/$/"\\/ +p +g +s/.\{148\}// +t nl +:delim +h +s/\(.\{148\}\)..*/\1/ +t more2 +s/["\\]/\\&/g; s/^/"/; s/$/"/ +p +b +:more2 +s/["\\]/\\&/g; s/^/"/; s/$/"\\/ +p +g +s/.\{148\}// +t delim +' >$CONFIG_STATUS || ac_write_fail=1 +rm -f conf$$subs.awk +cat >>$CONFIG_STATUS <<_ACEOF || ac_write_fail=1 +_ACAWK +cat >>"\$tmp/subs1.awk" <<_ACAWK && + for (key in S) S_is_set[key] = 1 + FS = "" + +} +{ + line = $ 0 + nfields = split(line, field, "@") + substed = 0 + len = length(field[1]) + for (i = 2; i < nfields; i++) { + key = field[i] + keylen = length(key) + if (S_is_set[key]) { + value = S[key] + line = substr(line, 1, len) "" value "" substr(line, len + keylen + 3) + len += length(value) + length(field[++i]) + substed = 1 + } else + len += 1 + keylen + } + + print line +} +_ACAWK +_ACEOF +cat >>$CONFIG_STATUS <<\_ACEOF || ac_write_fail=1 +if sed "s/$ac_cr//" < /dev/null > /dev/null 2>&1; then + sed "s/$ac_cr\$//; s/$ac_cr/$ac_cs_awk_cr/g" +else + cat +fi < "$tmp/subs1.awk" > "$tmp/subs.awk" \ + || as_fn_error "could not setup config files machinery" "$LINENO" 5 +_ACEOF # VPATH may cause trouble with some makes, so we remove $(srcdir), # ${srcdir} and @srcdir@ from VPATH if srcdir is ".", strip leading and @@ -28231,20 +14459,128 @@ }' fi -cat >>$CONFIG_STATUS <<\_ACEOF +cat >>$CONFIG_STATUS <<\_ACEOF || ac_write_fail=1 fi # test -n "$CONFIG_FILES" +# Set up the scripts for CONFIG_HEADERS section. +# No need to generate them if there are no CONFIG_HEADERS. +# This happens for instance with `./config.status Makefile'. +if test -n "$CONFIG_HEADERS"; then +cat >"$tmp/defines.awk" <<\_ACAWK || +BEGIN { +_ACEOF + +# Transform confdefs.h into an awk script `defines.awk', embedded as +# here-document in config.status, that substitutes the proper values into +# config.h.in to produce config.h. + +# Create a delimiter string that does not exist in confdefs.h, to ease +# handling of long lines. +ac_delim='%!_!# ' +for ac_last_try in false false :; do + ac_t=`sed -n "/$ac_delim/p" confdefs.h` + if test -z "$ac_t"; then + break + elif $ac_last_try; then + as_fn_error "could not make $CONFIG_HEADERS" "$LINENO" 5 + else + ac_delim="$ac_delim!$ac_delim _$ac_delim!! " + fi +done + +# For the awk script, D is an array of macro values keyed by name, +# likewise P contains macro parameters if any. Preserve backslash +# newline sequences. + +ac_word_re=[_$as_cr_Letters][_$as_cr_alnum]* +sed -n ' +s/.\{148\}/&'"$ac_delim"'/g +t rset +:rset +s/^[ ]*#[ ]*define[ ][ ]*/ / +t def +d +:def +s/\\$// +t bsnl +s/["\\]/\\&/g +s/^ \('"$ac_word_re"'\)\(([^()]*)\)[ ]*\(.*\)/P["\1"]="\2"\ +D["\1"]=" \3"/p +s/^ \('"$ac_word_re"'\)[ ]*\(.*\)/D["\1"]=" \2"/p +d +:bsnl +s/["\\]/\\&/g +s/^ \('"$ac_word_re"'\)\(([^()]*)\)[ ]*\(.*\)/P["\1"]="\2"\ +D["\1"]=" \3\\\\\\n"\\/p +t cont +s/^ \('"$ac_word_re"'\)[ ]*\(.*\)/D["\1"]=" \2\\\\\\n"\\/p +t cont +d +:cont +n +s/.\{148\}/&'"$ac_delim"'/g +t clear +:clear +s/\\$// +t bsnlc +s/["\\]/\\&/g; s/^/"/; s/$/"/p +d +:bsnlc +s/["\\]/\\&/g; s/^/"/; s/$/\\\\\\n"\\/p +b cont +' >$CONFIG_STATUS || ac_write_fail=1 + +cat >>$CONFIG_STATUS <<_ACEOF || ac_write_fail=1 + for (key in D) D_is_set[key] = 1 + FS = "" +} +/^[\t ]*#[\t ]*(define|undef)[\t ]+$ac_word_re([\t (]|\$)/ { + line = \$ 0 + split(line, arg, " ") + if (arg[1] == "#") { + defundef = arg[2] + mac1 = arg[3] + } else { + defundef = substr(arg[1], 2) + mac1 = arg[2] + } + split(mac1, mac2, "(") #) + macro = mac2[1] + prefix = substr(line, 1, index(line, defundef) - 1) + if (D_is_set[macro]) { + # Preserve the white space surrounding the "#". + print prefix "define", macro P[macro] D[macro] + next + } else { + # Replace #undef with comments. This is necessary, for example, + # in the case of _POSIX_SOURCE, which is predefined and required + # on some systems where configure will not decide to define it. + if (defundef == "undef") { + print "/*", prefix defundef, macro, "*/" + next + } + } +} +{ print } +_ACAWK +_ACEOF +cat >>$CONFIG_STATUS <<\_ACEOF || ac_write_fail=1 + as_fn_error "could not setup config headers machinery" "$LINENO" 5 +fi # test -n "$CONFIG_HEADERS" + -for ac_tag in :F $CONFIG_FILES :H $CONFIG_HEADERS +eval set X " :F $CONFIG_FILES :H $CONFIG_HEADERS " +shift +for ac_tag do case $ac_tag in :[FHLC]) ac_mode=$ac_tag; continue;; esac case $ac_mode$ac_tag in :[FHL]*:*);; - :L* | :C*:*) { { echo "$as_me:$LINENO: error: Invalid tag $ac_tag." >&5 -echo "$as_me: error: Invalid tag $ac_tag." >&2;} - { (exit 1); exit 1; }; };; + :L* | :C*:*) as_fn_error "invalid tag \`$ac_tag'" "$LINENO" 5;; :[FH]-) ac_tag=-:-;; :[FH]*) ac_tag=$ac_tag:$ac_tag.in;; esac @@ -28272,26 +14608,34 @@ [\\/$]*) false;; *) test -f "$srcdir/$ac_f" && ac_f="$srcdir/$ac_f";; esac || - { { echo "$as_me:$LINENO: error: cannot find input file: $ac_f" >&5 -echo "$as_me: error: cannot find input file: $ac_f" >&2;} - { (exit 1); exit 1; }; };; + as_fn_error "cannot find input file: \`$ac_f'" "$LINENO" 5;; esac - ac_file_inputs="$ac_file_inputs $ac_f" + case $ac_f in *\'*) ac_f=`$as_echo "$ac_f" | sed "s/'/'\\\\\\\\''/g"`;; esac + as_fn_append ac_file_inputs " '$ac_f'" done # Let's still pretend it is `configure' which instantiates (i.e., don't # use $as_me), people would be surprised to read: # /* config.h. Generated by config.status. */ - configure_input="Generated from "`IFS=: - echo $* | sed 's|^[^:]*/||;s|:[^:]*/|, |g'`" by configure." + configure_input='Generated from '` + $as_echo "$*" | sed 's|^[^:]*/||;s|:[^:]*/|, |g' + `' by configure.' if test x"$ac_file" != x-; then configure_input="$ac_file. $configure_input" - { echo "$as_me:$LINENO: creating $ac_file" >&5 -echo "$as_me: creating $ac_file" >&6;} + { $as_echo "$as_me:${as_lineno-$LINENO}: creating $ac_file" >&5 +$as_echo "$as_me: creating $ac_file" >&6;} fi + # Neutralize special characters interpreted by sed in replacement strings. + case $configure_input in #( + *\&* | *\|* | *\\* ) + ac_sed_conf_input=`$as_echo "$configure_input" | + sed 's/[\\\\&|]/\\\\&/g'`;; #( + *) ac_sed_conf_input=$configure_input;; + esac case $ac_tag in - *:-:* | *:-) cat >"$tmp/stdin";; + *:-:* | *:-) cat >"$tmp/stdin" \ + || as_fn_error "could not create $ac_file" "$LINENO" 5 ;; esac ;; esac @@ -28301,42 +14645,7 @@ X"$ac_file" : 'X\(//\)[^/]' \| \ X"$ac_file" : 'X\(//\)$' \| \ X"$ac_file" : 'X\(/\)' \| . 2>/dev/null || -echo X"$ac_file" | - sed '/^X\(.*[^/]\)\/\/*[^/][^/]*\/*$/{ - s//\1/ - q - } - /^X\(\/\/\)[^/].*/{ - s//\1/ - q - } - /^X\(\/\/\)$/{ - s//\1/ - q - } - /^X\(\/\).*/{ - s//\1/ - q - } - s/.*/./; q'` - { as_dir="$ac_dir" - case $as_dir in #( - -*) as_dir=./$as_dir;; - esac - test -d "$as_dir" || { $as_mkdir_p && mkdir -p "$as_dir"; } || { - as_dirs= - while :; do - case $as_dir in #( - *\'*) as_qdir=`echo "$as_dir" | sed "s/'/'\\\\\\\\''/g"`;; #( - *) as_qdir=$as_dir;; - esac - as_dirs="'$as_qdir' $as_dirs" - as_dir=`$as_dirname -- "$as_dir" || -$as_expr X"$as_dir" : 'X\(.*[^/]\)//*[^/][^/]*/*$' \| \ - X"$as_dir" : 'X\(//\)[^/]' \| \ - X"$as_dir" : 'X\(//\)$' \| \ - X"$as_dir" : 'X\(/\)' \| . 2>/dev/null || -echo X"$as_dir" | +$as_echo X"$ac_file" | sed '/^X\(.*[^/]\)\/\/*[^/][^/]*\/*$/{ s//\1/ q @@ -28354,20 +14663,15 @@ q } s/.*/./; q'` - test -d "$as_dir" && break - done - test -z "$as_dirs" || eval "mkdir $as_dirs" - } || test -d "$as_dir" || { { echo "$as_me:$LINENO: error: cannot create directory $as_dir" >&5 -echo "$as_me: error: cannot create directory $as_dir" >&2;} - { (exit 1); exit 1; }; }; } + as_dir="$ac_dir"; as_fn_mkdir_p ac_builddir=. case "$ac_dir" in .) ac_dir_suffix= ac_top_builddir_sub=. ac_top_build_prefix= ;; *) - ac_dir_suffix=/`echo "$ac_dir" | sed 's,^\.[\\/],,'` + ac_dir_suffix=/`$as_echo "$ac_dir" | sed 's|^\.[\\/]||'` # A ".." for each directory in $ac_dir_suffix. - ac_top_builddir_sub=`echo "$ac_dir_suffix" | sed 's,/[^\\/]*,/..,g;s,/,,'` + ac_top_builddir_sub=`$as_echo "$ac_dir_suffix" | sed 's|/[^\\/]*|/..|g;s|/||'` case $ac_top_builddir_sub in "") ac_top_builddir_sub=. ac_top_build_prefix= ;; *) ac_top_build_prefix=$ac_top_builddir_sub/ ;; @@ -28407,12 +14711,12 @@ esac _ACEOF -cat >>$CONFIG_STATUS <<\_ACEOF +cat >>$CONFIG_STATUS <<\_ACEOF || ac_write_fail=1 # If the template does not know about datarootdir, expand it. # FIXME: This hack should be removed a few years after 2.60. ac_datarootdir_hack=; ac_datarootdir_seen= - -case `sed -n '/datarootdir/ { +ac_sed_dataroot=' +/datarootdir/ { p q } @@ -28420,36 +14724,37 @@ /@docdir@/p /@infodir@/p /@localedir@/p -/@mandir@/p -' $ac_file_inputs` in +/@mandir@/p' +case `eval "sed -n \"\$ac_sed_dataroot\" $ac_file_inputs"` in *datarootdir*) ac_datarootdir_seen=yes;; *@datadir@*|*@docdir@*|*@infodir@*|*@localedir@*|*@mandir@*) - { echo "$as_me:$LINENO: WARNING: $ac_file_inputs seems to ignore the --datarootdir setting" >&5 -echo "$as_me: WARNING: $ac_file_inputs seems to ignore the --datarootdir setting" >&2;} + { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: $ac_file_inputs seems to ignore the --datarootdir setting" >&5 +$as_echo "$as_me: WARNING: $ac_file_inputs seems to ignore the --datarootdir setting" >&2;} _ACEOF -cat >>$CONFIG_STATUS <<_ACEOF +cat >>$CONFIG_STATUS <<_ACEOF || ac_write_fail=1 ac_datarootdir_hack=' s&@datadir@&$datadir&g s&@docdir@&$docdir&g s&@infodir@&$infodir&g s&@localedir@&$localedir&g s&@mandir@&$mandir&g - s&\\\${datarootdir}&$datarootdir&g' ;; + s&\\\${datarootdir}&$datarootdir&g' ;; esac _ACEOF # Neutralize VPATH when `$srcdir' = `.'. # Shell code in configure.ac might set extrasub. # FIXME: do we really want to maintain this feature? -cat >>$CONFIG_STATUS <<_ACEOF - sed "$ac_vpsub +cat >>$CONFIG_STATUS <<_ACEOF || ac_write_fail=1 +ac_sed_extra="$ac_vpsub $extrasub _ACEOF -cat >>$CONFIG_STATUS <<\_ACEOF +cat >>$CONFIG_STATUS <<\_ACEOF || ac_write_fail=1 :t /@[a-zA-Z_][a-zA-Z_0-9]*@/!b -s&@configure_input@&$configure_input&;t t +s|@configure_input@|$ac_sed_conf_input|;t t s&@top_builddir@&$ac_top_builddir_sub&;t t +s&@top_build_prefix@&$ac_top_build_prefix&;t t s&@srcdir@&$ac_srcdir&;t t s&@abs_srcdir@&$ac_abs_srcdir&;t t s&@top_srcdir@&$ac_top_srcdir&;t t @@ -28459,119 +14764,48 @@ s&@abs_top_builddir@&$ac_abs_top_builddir&;t t s&@INSTALL@&$ac_INSTALL&;t t $ac_datarootdir_hack -" $ac_file_inputs | sed -f "$tmp/subs-1.sed" | sed -f "$tmp/subs-2.sed" >$tmp/out +" +eval sed \"\$ac_sed_extra\" "$ac_file_inputs" | $AWK -f "$tmp/subs.awk" >$tmp/out \ + || as_fn_error "could not create $ac_file" "$LINENO" 5 test -z "$ac_datarootdir_hack$ac_datarootdir_seen" && { ac_out=`sed -n '/\${datarootdir}/p' "$tmp/out"`; test -n "$ac_out"; } && { ac_out=`sed -n '/^[ ]*datarootdir[ ]*:*=/p' "$tmp/out"`; test -z "$ac_out"; } && - { echo "$as_me:$LINENO: WARNING: $ac_file contains a reference to the variable \`datarootdir' + { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: $ac_file contains a reference to the variable \`datarootdir' which seems to be undefined. Please make sure it is defined." >&5 -echo "$as_me: WARNING: $ac_file contains a reference to the variable \`datarootdir' +$as_echo "$as_me: WARNING: $ac_file contains a reference to the variable \`datarootdir' which seems to be undefined. Please make sure it is defined." >&2;} rm -f "$tmp/stdin" case $ac_file in - -) cat "$tmp/out"; rm -f "$tmp/out";; - *) rm -f "$ac_file"; mv "$tmp/out" $ac_file;; - esac + -) cat "$tmp/out" && rm -f "$tmp/out";; + *) rm -f "$ac_file" && mv "$tmp/out" "$ac_file";; + esac \ + || as_fn_error "could not create $ac_file" "$LINENO" 5 ;; :H) # # CONFIG_HEADER # -_ACEOF - -# Transform confdefs.h into a sed script `conftest.defines', that -# substitutes the proper values into config.h.in to produce config.h. -rm -f conftest.defines conftest.tail -# First, append a space to every undef/define line, to ease matching. -echo 's/$/ /' >conftest.defines -# Then, protect against being on the right side of a sed subst, or in -# an unquoted here document, in config.status. If some macros were -# called several times there might be several #defines for the same -# symbol, which is useless. But do not sort them, since the last -# AC_DEFINE must be honored. -ac_word_re=[_$as_cr_Letters][_$as_cr_alnum]* -# These sed commands are passed to sed as "A NAME B PARAMS C VALUE D", where -# NAME is the cpp macro being defined, VALUE is the value it is being given. -# PARAMS is the parameter list in the macro definition--in most cases, it's -# just an empty string. -ac_dA='s,^\\([ #]*\\)[^ ]*\\([ ]*' -ac_dB='\\)[ (].*,\\1define\\2' -ac_dC=' ' -ac_dD=' ,' - -uniq confdefs.h | - sed -n ' - t rset - :rset - s/^[ ]*#[ ]*define[ ][ ]*// - t ok - d - :ok - s/[\\&,]/\\&/g - s/^\('"$ac_word_re"'\)\(([^()]*)\)[ ]*\(.*\)/ '"$ac_dA"'\1'"$ac_dB"'\2'"${ac_dC}"'\3'"$ac_dD"'/p - s/^\('"$ac_word_re"'\)[ ]*\(.*\)/'"$ac_dA"'\1'"$ac_dB$ac_dC"'\2'"$ac_dD"'/p - ' >>conftest.defines - -# Remove the space that was appended to ease matching. -# Then replace #undef with comments. This is necessary, for -# example, in the case of _POSIX_SOURCE, which is predefined and required -# on some systems where configure will not decide to define it. -# (The regexp can be short, since the line contains either #define or #undef.) -echo 's/ $// -s,^[ #]*u.*,/* & */,' >>conftest.defines - -# Break up conftest.defines: -ac_max_sed_lines=50 - -# First sed command is: sed -f defines.sed $ac_file_inputs >"$tmp/out1" -# Second one is: sed -f defines.sed "$tmp/out1" >"$tmp/out2" -# Third one will be: sed -f defines.sed "$tmp/out2" >"$tmp/out1" -# et cetera. -ac_in='$ac_file_inputs' -ac_out='"$tmp/out1"' -ac_nxt='"$tmp/out2"' - -while : -do - # Write a here document: - cat >>$CONFIG_STATUS <<_ACEOF - # First, check the format of the line: - cat >"\$tmp/defines.sed" <<\\CEOF -/^[ ]*#[ ]*undef[ ][ ]*$ac_word_re[ ]*\$/b def -/^[ ]*#[ ]*define[ ][ ]*$ac_word_re[( ]/b def -b -:def -_ACEOF - sed ${ac_max_sed_lines}q conftest.defines >>$CONFIG_STATUS - echo 'CEOF - sed -f "$tmp/defines.sed"' "$ac_in >$ac_out" >>$CONFIG_STATUS - ac_in=$ac_out; ac_out=$ac_nxt; ac_nxt=$ac_in - sed 1,${ac_max_sed_lines}d conftest.defines >conftest.tail - grep . conftest.tail >/dev/null || break - rm -f conftest.defines - mv conftest.tail conftest.defines -done -rm -f conftest.defines conftest.tail - -echo "ac_result=$ac_in" >>$CONFIG_STATUS -cat >>$CONFIG_STATUS <<\_ACEOF if test x"$ac_file" != x-; then - echo "/* $configure_input */" >"$tmp/config.h" - cat "$ac_result" >>"$tmp/config.h" - if diff $ac_file "$tmp/config.h" >/dev/null 2>&1; then - { echo "$as_me:$LINENO: $ac_file is unchanged" >&5 -echo "$as_me: $ac_file is unchanged" >&6;} + { + $as_echo "/* $configure_input */" \ + && eval '$AWK -f "$tmp/defines.awk"' "$ac_file_inputs" + } >"$tmp/config.h" \ + || as_fn_error "could not create $ac_file" "$LINENO" 5 + if diff "$ac_file" "$tmp/config.h" >/dev/null 2>&1; then + { $as_echo "$as_me:${as_lineno-$LINENO}: $ac_file is unchanged" >&5 +$as_echo "$as_me: $ac_file is unchanged" >&6;} else - rm -f $ac_file - mv "$tmp/config.h" $ac_file + rm -f "$ac_file" + mv "$tmp/config.h" "$ac_file" \ + || as_fn_error "could not create $ac_file" "$LINENO" 5 fi else - echo "/* $configure_input */" - cat "$ac_result" + $as_echo "/* $configure_input */" \ + && eval '$AWK -f "$tmp/defines.awk"' "$ac_file_inputs" \ + || as_fn_error "could not create -" "$LINENO" 5 fi - rm -f "$tmp/out12" ;; @@ -28580,11 +14814,13 @@ done # for ac_tag -{ (exit 0); exit 0; } +as_fn_exit 0 _ACEOF -chmod +x $CONFIG_STATUS ac_clean_files=$ac_clean_files_save +test $ac_write_fail = 0 || + as_fn_error "write failure creating $CONFIG_STATUS" "$LINENO" 5 + # configure is writing to config.log, and then calls config.status. # config.status does its own redirection, appending to config.log. @@ -28604,7 +14840,11 @@ exec 5>>config.log # Use ||, not &&, to avoid exiting from the if with $? = 1, which # would make configure fail if this is the last instruction. - $ac_cs_success || { (exit 1); exit 1; } + $ac_cs_success || as_fn_exit $? +fi +if test -n "$ac_unrecognized_opts" && test "$enable_option_checking" != no; then + { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: unrecognized options: $ac_unrecognized_opts" >&5 +$as_echo "$as_me: WARNING: unrecognized options: $ac_unrecognized_opts" >&2;} fi Modified: python/branches/py3k-jit/configure.in ============================================================================== --- python/branches/py3k-jit/configure.in (original) +++ python/branches/py3k-jit/configure.in Tue May 4 01:24:51 2010 @@ -1,7 +1,6 @@ dnl *********************************************** dnl * Please run autoreconf to test your changes! * dnl *********************************************** -dnl NOTE: autoconf 2.64 doesn't seem to work (use 2.61). # Set VERSION so we only need to edit in one place (i.e., here) m4_define(PYTHON_VERSION, 3.2) @@ -13,7 +12,7 @@ [], [m4_fatal([Autoconf version $1 is required for Python], 63)]) ]) -version_required(2.61) +version_required(2.65) AC_REVISION($Revision$) AC_INIT(python, PYTHON_VERSION, http://bugs.python.org/) @@ -88,7 +87,7 @@ AC_MSG_CHECKING([for --enable-universalsdk]) AC_ARG_ENABLE(universalsdk, - AC_HELP_STRING(--enable-universalsdk@<:@=SDKDIR@:>@, Build against Mac OS X 10.4u SDK (ppc/i386)), + AS_HELP_STRING([--enable-universalsdk@<:@=SDKDIR@:>@], [Build against Mac OS X 10.4u SDK (ppc/i386)]), [ case $enableval in yes) @@ -131,7 +130,7 @@ AC_SUBST(LIPO_32BIT_FLAGS) AC_MSG_CHECKING(for --with-universal-archs) AC_ARG_WITH(universal-archs, - AC_HELP_STRING(--with-universal-archs=ARCH, select architectures for universal build ("32-bit", "64-bit", "3-way", "intel" or "all")), + AS_HELP_STRING([--with-universal-archs=ARCH], [select architectures for universal build ("32-bit", "64-bit", "3-way", "intel" or "all")]), [ AC_MSG_RESULT($withval) UNIVERSAL_ARCHS="$withval" @@ -143,8 +142,8 @@ AC_ARG_WITH(framework-name, - AC_HELP_STRING(--with-framework-name=FRAMEWORK, - specify an alternate name of the framework built with --enable-framework), + AS_HELP_STRING([--with-framework-name=FRAMEWORK], + [specify an alternate name of the framework built with --enable-framework]), [ PYTHONFRAMEWORK=${withval} PYTHONFRAMEWORKDIR=${withval}.framework @@ -156,7 +155,7 @@ ]) dnl quadrigraphs "@<:@" and "@:>@" produce "[" and "]" in the output AC_ARG_ENABLE(framework, - AC_HELP_STRING(--enable-framework@<:@=INSTALLDIR@:>@, Build (MacOSX|Darwin) framework), + AS_HELP_STRING([--enable-framework@<:@=INSTALLDIR@:>@], [Build (MacOSX|Darwin) framework]), [ case $enableval in yes) @@ -180,18 +179,55 @@ enable_framework= ;; *) - PYTHONFRAMEWORKPREFIX=$enableval + PYTHONFRAMEWORKPREFIX="${enableval}" PYTHONFRAMEWORKINSTALLDIR=$PYTHONFRAMEWORKPREFIX/$PYTHONFRAMEWORKDIR FRAMEWORKINSTALLFIRST="frameworkinstallstructure" FRAMEWORKALTINSTALLFIRST="frameworkinstallstructure " FRAMEWORKINSTALLLAST="frameworkinstallmaclib frameworkinstallapps frameworkinstallunixtools" FRAMEWORKALTINSTALLLAST="frameworkinstallmaclib frameworkinstallapps frameworkaltinstallunixtools" + FRAMEWORKINSTALLAPPSPREFIX="/Applications" if test "x${prefix}" = "xNONE" ; then FRAMEWORKUNIXTOOLSPREFIX="${ac_default_prefix}" + else FRAMEWORKUNIXTOOLSPREFIX="${prefix}" fi + + case "${enableval}" in + /System*) + FRAMEWORKINSTALLAPPSPREFIX="/Applications" + if test "${prefix}" = "NONE" ; then + # See below + FRAMEWORKUNIXTOOLSPREFIX="/usr" + fi + ;; + + /Library*) + FRAMEWORKINSTALLAPPSPREFIX="/Applications" + ;; + + */Library/Frameworks) + MDIR="`dirname "${enableval}"`" + MDIR="`dirname "${MDIR}"`" + FRAMEWORKINSTALLAPPSPREFIX="${MDIR}/Applications" + + if test "${prefix}" = "NONE"; then + # User hasn't specified the + # --prefix option, but wants to install + # the framework in a non-default location, + # ensure that the compatibility links get + # installed relative to that prefix as well + # instead of in /usr/local. + FRAMEWORKUNIXTOOLSPREFIX="${MDIR}" + fi + ;; + + *) + FRAMEWORKINSTALLAPPSPREFIX="/Applications" + ;; + esac + prefix=$PYTHONFRAMEWORKINSTALLDIR/Versions/$VERSION # Add files for Mac specific code to the list of output @@ -228,10 +264,11 @@ AC_SUBST(FRAMEWORKALTINSTALLFIRST) AC_SUBST(FRAMEWORKALTINSTALLLAST) AC_SUBST(FRAMEWORKUNIXTOOLSPREFIX) +AC_SUBST(FRAMEWORKINSTALLAPPSPREFIX) ##AC_ARG_WITH(dyld, -## AC_HELP_STRING(--with-dyld, -## Use (OpenStep|Rhapsody) dynamic linker)) +## AS_HELP_STRING([--with-dyld], +## [Use (OpenStep|Rhapsody) dynamic linker])) ## # Set name for machine-dependent library files AC_SUBST(MACHDEP) @@ -417,7 +454,7 @@ # on that fiddles with OPT and BASECFLAGS? AC_MSG_CHECKING(for --without-gcc) AC_ARG_WITH(gcc, - AC_HELP_STRING(--without-gcc,never use gcc), + AS_HELP_STRING([--without-gcc], [never use gcc]), [ case $withval in no) CC=${CC:-cc} @@ -441,15 +478,20 @@ (it is also a good idea to do 'make clean' before compiling)]) fi -save_CFLAGS=$CFLAGS +# If the user set CFLAGS, use this instead of the automatically +# determined setting +preset_cflags="$CFLAGS" AC_PROG_CC -CFLAGS=$save_CFLAGS +if test ! -z "$preset_cflags" +then + CFLAGS=$preset_cflags +fi AC_SUBST(CXX) AC_SUBST(MAINCC) AC_MSG_CHECKING(for --with-cxx-main=) AC_ARG_WITH(cxx_main, - AC_HELP_STRING([--with-cxx-main=], + AS_HELP_STRING([--with-cxx-main=], [compile main() and link python executable with C++ compiler]), [ @@ -501,7 +543,7 @@ # checks for UNIX variants that set C preprocessor variables -AC_AIX +AC_USE_SYSTEM_EXTENSIONS # Check for unsupported systems case $ac_sys_system/$ac_sys_release in @@ -514,7 +556,7 @@ AC_EXEEXT AC_MSG_CHECKING(for --with-suffix) AC_ARG_WITH(suffix, - AC_HELP_STRING(--with-suffix=.exe, set executable suffix), + AS_HELP_STRING([--with-suffix=.exe], [set executable suffix]), [ case $withval in no) EXEEXT=;; @@ -553,10 +595,6 @@ case $CC in cc|*/cc) CC="$CC -Ae";; esac;; -SunOS*) - # Some functions have a prototype only with that define, e.g. confstr - AC_DEFINE(__EXTENSIONS__, 1, [Defined on Solaris to see additional function prototypes.]) - ;; esac @@ -642,7 +680,7 @@ AC_MSG_CHECKING(for --enable-shared) AC_ARG_ENABLE(shared, - AC_HELP_STRING(--enable-shared, disable/enable building shared python library)) + AS_HELP_STRING([--enable-shared], [disable/enable building shared python library])) if test -z "$enable_shared" then @@ -657,13 +695,13 @@ AC_MSG_CHECKING(for --enable-profiling) AC_ARG_ENABLE(profiling, - AC_HELP_STRING(--enable-profiling, enable C-level code profiling), + AS_HELP_STRING([--enable-profiling], [enable C-level code profiling]), [ac_save_cc="$CC" CC="$CC -pg" - AC_TRY_RUN([int main() { return 0; }], - ac_enable_profiling="yes", - ac_enable_profiling="no", - ac_enable_profiling="no") + AC_RUN_IFELSE([AC_LANG_SOURCE([[int main() { return 0; }]])], + [ac_enable_profiling="yes"], + [ac_enable_profiling="no"], + [ac_enable_profiling="no"]) CC="$ac_save_cc"]) AC_MSG_RESULT($ac_enable_profiling) @@ -793,7 +831,7 @@ # Check for --with-pydebug AC_MSG_CHECKING(for --with-pydebug) AC_ARG_WITH(pydebug, - AC_HELP_STRING(--with-pydebug, build with Py_DEBUG defined), + AS_HELP_STRING([--with-pydebug], [build with Py_DEBUG defined]), [ if test "$withval" != no then @@ -876,13 +914,24 @@ CC="$CC -fno-strict-aliasing" save_CFLAGS="$CFLAGS" AC_CACHE_VAL(ac_cv_no_strict_aliasing, - AC_TRY_COMPILE([],[int main() { return 0; }], - CC="$ac_save_cc -fstrict-aliasing" - CFLAGS="$CFLAGS -Werror -Wstrict-aliasing" - AC_TRY_COMPILE([],[void f(int **x) {} int main() { double *x; f((int **) &x); return 0; }], - ac_cv_no_strict_aliasing=no, - ac_cv_no_strict_aliasing=yes), - ac_cv_no_strict_aliasing=no)) + AC_COMPILE_IFELSE( + [ + AC_LANG_PROGRAM([[]], [[int main() { return 0; }]]) + ],[ + CC="$ac_save_cc -fstrict-aliasing" + CFLAGS="$CFLAGS -Werror -Wstrict-aliasing" + AC_COMPILE_IFELSE( + [ + AC_LANG_PROGRAM([[]], + [[void f(int **x) {} int main() { double *x; f((int **) &x); return 0; }]]) + ],[ + ac_cv_no_strict_aliasing=no + ],[ + ac_cv_no_strict_aliasing=yes + ]) + ],[ + ac_cv_no_strict_aliasing=no + ])) CFLAGS="$save_CFLAGS" CC="$ac_save_cc" AC_MSG_RESULT($ac_cv_no_strict_aliasing) @@ -1049,9 +1098,10 @@ AC_CACHE_VAL(ac_cv_opt_olimit_ok, [ac_save_cc="$CC" CC="$CC -OPT:Olimit=0" -AC_TRY_COMPILE([],[int main() { return 0; }], - ac_cv_opt_olimit_ok=yes, - ac_cv_opt_olimit_ok=no, +AC_COMPILE_IFELSE( + [AC_LANG_PROGRAM([[]], [[int main() { return 0; }]])], + [ac_cv_opt_olimit_ok=yes], + [ac_cv_opt_olimit_ok=no] ) CC="$ac_save_cc"]) AC_MSG_RESULT($ac_cv_opt_olimit_ok) @@ -1071,9 +1121,10 @@ AC_CACHE_VAL(ac_cv_olimit_ok, [ac_save_cc="$CC" CC="$CC -Olimit 1500" - AC_TRY_COMPILE([],[int main() { return 0; }], - ac_cv_olimit_ok=yes, - ac_cv_olimit_ok=no, + AC_COMPILE_IFELSE( + [AC_LANG_PROGRAM([[]], [[int main() { return 0; }]])], + [ac_cv_olimit_ok=yes], + [ac_cv_olimit_ok=no] ) CC="$ac_save_cc"]) AC_MSG_RESULT($ac_cv_olimit_ok) @@ -1088,13 +1139,15 @@ AC_MSG_CHECKING(whether gcc supports ParseTuple __format__) save_CFLAGS=$CFLAGS CFLAGS="$CFLAGS -Werror" - AC_TRY_COMPILE([ - void f(char*,...)__attribute((format(PyArg_ParseTuple, 1, 2))); - ],, - AC_DEFINE(HAVE_ATTRIBUTE_FORMAT_PARSETUPLE, 1, [Define if GCC supports __attribute__((format(PyArg_ParseTuple, 2, 3)))]) - AC_MSG_RESULT(yes), - AC_MSG_RESULT(no) - ) + AC_COMPILE_IFELSE([ + AC_LANG_PROGRAM([[void f(char*,...)__attribute((format(PyArg_ParseTuple, 1, 2)));]], [[]]) + ],[ + AC_DEFINE(HAVE_ATTRIBUTE_FORMAT_PARSETUPLE, 1, + [Define if GCC supports __attribute__((format(PyArg_ParseTuple, 2, 3)))]) + AC_MSG_RESULT(yes) + ],[ + AC_MSG_RESULT(no) + ]) CFLAGS=$save_CFLAGS fi @@ -1105,7 +1158,7 @@ # options before we can check whether -Kpthread improves anything. AC_MSG_CHECKING(whether pthreads are available without options) AC_CACHE_VAL(ac_cv_pthread_is_default, -[AC_TRY_RUN([ +[AC_RUN_IFELSE([AC_LANG_SOURCE([[ #include void* routine(void* p){return NULL;} @@ -1117,14 +1170,11 @@ (void)pthread_detach(p); return 0; } -], -[ +]])],[ ac_cv_pthread_is_default=yes ac_cv_kthread=no ac_cv_pthread=no -], - ac_cv_pthread_is_default=no, - ac_cv_pthread_is_default=no) +],[ac_cv_pthread_is_default=no],[ac_cv_pthread_is_default=no]) ]) AC_MSG_RESULT($ac_cv_pthread_is_default) @@ -1142,7 +1192,7 @@ AC_CACHE_VAL(ac_cv_kpthread, [ac_save_cc="$CC" CC="$CC -Kpthread" -AC_TRY_RUN([ +AC_RUN_IFELSE([AC_LANG_SOURCE([[ #include void* routine(void* p){return NULL;} @@ -1154,10 +1204,7 @@ (void)pthread_detach(p); return 0; } -], - ac_cv_kpthread=yes, - ac_cv_kpthread=no, - ac_cv_kpthread=no) +]])],[ac_cv_kpthread=yes],[ac_cv_kpthread=no],[ac_cv_kpthread=no]) CC="$ac_save_cc"]) AC_MSG_RESULT($ac_cv_kpthread) fi @@ -1173,7 +1220,7 @@ AC_CACHE_VAL(ac_cv_kthread, [ac_save_cc="$CC" CC="$CC -Kthread" -AC_TRY_RUN([ +AC_RUN_IFELSE([AC_LANG_SOURCE([[ #include void* routine(void* p){return NULL;} @@ -1185,10 +1232,7 @@ (void)pthread_detach(p); return 0; } -], - ac_cv_kthread=yes, - ac_cv_kthread=no, - ac_cv_kthread=no) +]])],[ac_cv_kthread=yes],[ac_cv_kthread=no],[ac_cv_kthread=no]) CC="$ac_save_cc"]) AC_MSG_RESULT($ac_cv_kthread) fi @@ -1204,7 +1248,7 @@ AC_CACHE_VAL(ac_cv_thread, [ac_save_cc="$CC" CC="$CC -pthread" -AC_TRY_RUN([ +AC_RUN_IFELSE([AC_LANG_SOURCE([[ #include void* routine(void* p){return NULL;} @@ -1216,10 +1260,7 @@ (void)pthread_detach(p); return 0; } -], - ac_cv_pthread=yes, - ac_cv_pthread=no, - ac_cv_pthread=no) +]])],[ac_cv_pthread=yes],[ac_cv_pthread=no],[ac_cv_pthread=no]) CC="$ac_save_cc"]) AC_MSG_RESULT($ac_cv_pthread) fi @@ -1265,11 +1306,11 @@ dnl # check for ANSI or K&R ("traditional") preprocessor dnl AC_MSG_CHECKING(for C preprocessor type) -dnl AC_TRY_COMPILE([ +dnl AC_COMPILE_IFELSE([AC_LANG_PROGRAM([[ dnl #define spam(name, doc) {#name, &name, #name "() -- " doc} dnl int foo; dnl struct {char *name; int *addr; char *doc;} desc = spam(foo, "something"); -dnl ], [;], cpp_type=ansi, AC_DEFINE(HAVE_OLD_CPP) cpp_type=traditional) +dnl ]], [[;]])],[cpp_type=ansi],[AC_DEFINE(HAVE_OLD_CPP) cpp_type=traditional]) dnl AC_MSG_RESULT($cpp_type) # checks for header files @@ -1316,19 +1357,26 @@ # Check whether using makedev requires defining _OSF_SOURCE AC_MSG_CHECKING(for makedev) -AC_TRY_LINK([#include ], - [ makedev(0, 0) ], - ac_cv_has_makedev=yes, - ac_cv_has_makedev=no) +AC_LINK_IFELSE([AC_LANG_PROGRAM([[ +#if defined(MAJOR_IN_MKDEV) +#include +#elif defined(MAJOR_IN_SYSMACROS) +#include +#else +#include +#endif +]], [[ + makedev(0, 0) ]]) +],[ac_cv_has_makedev=yes],[ac_cv_has_makedev=no]) if test "$ac_cv_has_makedev" = "no"; then # we didn't link, try if _OSF_SOURCE will allow us to link - AC_TRY_LINK([ + AC_LINK_IFELSE([AC_LANG_PROGRAM([[ #define _OSF_SOURCE 1 #include - ], - [ makedev(0, 0) ], - ac_cv_has_makedev=yes, - ac_cv_has_makedev=no) + ]], + [[ makedev(0, 0) ]])], + [ac_cv_has_makedev=yes], + [ac_cv_has_makedev=no]) if test "$ac_cv_has_makedev" = "yes"; then AC_DEFINE(_OSF_SOURCE, 1, [Define _OSF_SOURCE to get the makedev macro.]) fi @@ -1347,11 +1395,11 @@ use_lfs=yes AC_MSG_CHECKING(Solaris LFS bug) -AC_TRY_COMPILE([ +AC_COMPILE_IFELSE([AC_LANG_PROGRAM([[ #define _LARGEFILE_SOURCE 1 #define _FILE_OFFSET_BITS 64 #include -],struct rlimit foo;,sol_lfs_bug=no,sol_lfs_bug=yes) +]], [[struct rlimit foo;]])],[sol_lfs_bug=no],[sol_lfs_bug=yes]) AC_MSG_RESULT($sol_lfs_bug) if test "$sol_lfs_bug" = "yes"; then use_lfs=no @@ -1377,7 +1425,7 @@ AC_TYPE_MODE_T AC_TYPE_OFF_T AC_TYPE_PID_T -AC_TYPE_SIGNAL +AC_DEFINE_UNQUOTED([RETSIGTYPE],[void],[assume C89 semantics that RETSIGTYPE is always void]) AC_TYPE_SIZE_T AC_TYPE_UID_T AC_TYPE_UINT32_T @@ -1385,7 +1433,7 @@ AC_TYPE_INT32_T AC_TYPE_INT64_T AC_CHECK_TYPE(ssize_t, - AC_DEFINE(HAVE_SSIZE_T, 1, Define if your compiler provides ssize_t),,) + AC_DEFINE(HAVE_SSIZE_T, 1, [Define if your compiler provides ssize_t]),,) # Sizes of various common basic types # ANSI C requires sizeof(char) == 1, so no need to check it @@ -1401,10 +1449,10 @@ AC_MSG_CHECKING(for long long support) have_long_long=no -AC_TRY_COMPILE([], [long long x; x = (long long)0;], [ +AC_COMPILE_IFELSE([AC_LANG_PROGRAM([[]], [[long long x; x = (long long)0;]])],[ AC_DEFINE(HAVE_LONG_LONG, 1, [Define this if you have the type long long.]) have_long_long=yes -]) +],[]) AC_MSG_RESULT($have_long_long) if test "$have_long_long" = yes ; then AC_CHECK_SIZEOF(long long, 8) @@ -1412,10 +1460,10 @@ AC_MSG_CHECKING(for long double support) have_long_double=no -AC_TRY_COMPILE([], [long double x; x = (long double)0;], [ +AC_COMPILE_IFELSE([AC_LANG_PROGRAM([[]], [[long double x; x = (long double)0;]])],[ AC_DEFINE(HAVE_LONG_DOUBLE, 1, [Define this if you have the type long double.]) have_long_double=yes -]) +],[]) AC_MSG_RESULT($have_long_double) if test "$have_long_double" = yes ; then AC_CHECK_SIZEOF(long double, 16) @@ -1424,10 +1472,10 @@ AC_MSG_CHECKING(for _Bool support) have_c99_bool=no -AC_TRY_COMPILE([], [_Bool x; x = (_Bool)0;], [ +AC_COMPILE_IFELSE([AC_LANG_PROGRAM([[]], [[_Bool x; x = (_Bool)0;]])],[ AC_DEFINE(HAVE_C99_BOOL, 1, [Define this if you have the type _Bool.]) have_c99_bool=yes -]) +],[]) AC_MSG_RESULT($have_c99_bool) if test "$have_c99_bool" = yes ; then AC_CHECK_SIZEOF(_Bool, 1) @@ -1484,7 +1532,9 @@ AC_MSG_CHECKING(for pthread_t) have_pthread_t=no -AC_TRY_COMPILE([#include ], [pthread_t x; x = *(pthread_t*)0;], have_pthread_t=yes) +AC_COMPILE_IFELSE([ + AC_LANG_PROGRAM([[#include ]], [[pthread_t x; x = *(pthread_t*)0;]]) +],[have_pthread_t=yes],[]) AC_MSG_RESULT($have_pthread_t) if test "$have_pthread_t" = yes ; then AC_CHECK_SIZEOF(pthread_t, [], [ @@ -1526,7 +1576,7 @@ else LIBTOOL_CRUFT="" fi - AC_TRY_RUN([ + AC_RUN_IFELSE([AC_LANG_SOURCE([[ #include int main(int argc, char*argv[]) { @@ -1536,9 +1586,7 @@ return 1; } } - ], ac_osx_32bit=yes, - ac_osx_32bit=no, - ac_osx_32bit=yes) + ]])],[ac_osx_32bit=yes],[ac_osx_32bit=no],[ac_osx_32bit=yes]) if test "${ac_osx_32bit}" = "yes"; then case `/usr/bin/arch` in @@ -1920,13 +1968,17 @@ # checks for system dependent C++ extensions support case "$ac_sys_system" in AIX*) AC_MSG_CHECKING(for genuine AIX C++ extensions support) - AC_TRY_LINK([#include "/usr/lpp/xlC/include/load.h"], - [loadAndInit("", 0, "")], - [AC_DEFINE(AIX_GENUINE_CPLUSPLUS, 1, + AC_LINK_IFELSE([ + AC_LANG_PROGRAM([[#include "/usr/lpp/xlC/include/load.h"]], + [[loadAndInit("", 0, "")]]) + ],[ + AC_DEFINE(AIX_GENUINE_CPLUSPLUS, 1, [Define for AIX if your compiler is a genuine IBM xlC/xlC_r and you want support for AIX C++ shared extension modules.]) - AC_MSG_RESULT(yes)], - [AC_MSG_RESULT(no)]);; + AC_MSG_RESULT(yes) + ],[ + AC_MSG_RESULT(no) + ]);; *) ;; esac @@ -1936,7 +1988,7 @@ AC_MSG_CHECKING(for --with-libs) AC_ARG_WITH(libs, - AC_HELP_STRING(--with-libs='lib1 ...', link against additional libs), + AS_HELP_STRING([--with-libs='lib1 ...'], [link against additional libs]), [ AC_MSG_RESULT($withval) LIBS="$withval $LIBS" @@ -1948,14 +2000,14 @@ # Check for use of the system expat library AC_MSG_CHECKING(for --with-system-expat) AC_ARG_WITH(system_expat, - AC_HELP_STRING(--with-system-expat, build pyexpat module using an installed expat library)) + AS_HELP_STRING([--with-system-expat], [build pyexpat module using an installed expat library])) AC_MSG_RESULT($with_system_expat) # Check for use of the system libffi library AC_MSG_CHECKING(for --with-system-ffi) AC_ARG_WITH(system_ffi, - AC_HELP_STRING(--with-system-ffi, build _ctypes module using an installed ffi library)) + AS_HELP_STRING([--with-system-ffi], [build _ctypes module using an installed ffi library])) if test "$with_system_ffi" = "yes" && test -n "$PKG_CONFIG"; then LIBFFI_INCLUDEDIR="`"$PKG_CONFIG" libffi --cflags-only-I 2>/dev/null | sed -e 's/^-I//;s/ *$//'`" @@ -1969,7 +2021,7 @@ # Check for --with-dbmliborder AC_MSG_CHECKING(for --with-dbmliborder) AC_ARG_WITH(dbmliborder, - AC_HELP_STRING([--with-dbmliborder=db1:db2:...], [order to check db backends for dbm. Valid value is a colon separated string with the backend names `ndbm', `gdbm' and `bdb'.]), + AS_HELP_STRING([--with-dbmliborder=db1:db2:...], [order to check db backends for dbm. Valid value is a colon separated string with the backend names `ndbm', `gdbm' and `bdb'.]), [ if test x$with_dbmliborder = xyes then @@ -1989,7 +2041,7 @@ AC_SUBST(SIGNAL_OBJS) AC_MSG_CHECKING(for --with-signal-module) AC_ARG_WITH(signal-module, - AC_HELP_STRING(--with-signal-module, disable/enable signal module)) + AS_HELP_STRING([--with-signal-module], [disable/enable signal module])) if test -z "$with_signal_module" then with_signal_module="yes" @@ -2011,7 +2063,7 @@ AC_MSG_CHECKING(for --with-dec-threads) AC_SUBST(LDLAST) AC_ARG_WITH(dec-threads, - AC_HELP_STRING(--with-dec-threads, use DEC Alpha/OSF1 thread-safe libraries), + AS_HELP_STRING([--with-dec-threads], [use DEC Alpha/OSF1 thread-safe libraries]), [ AC_MSG_RESULT($withval) LDLAST=-threads @@ -2031,12 +2083,12 @@ AC_MSG_CHECKING(for --with-threads) dnl quadrigraphs "@<:@" and "@:>@" produce "[" and "]" in the output AC_ARG_WITH(threads, - AC_HELP_STRING(--with(out)-threads@<:@=DIRECTORY@:>@, disable/enable thread support)) + AS_HELP_STRING([--with(out)-threads@<:@=DIRECTORY@:>@], [disable/enable thread support])) # --with-thread is deprecated, but check for it anyway dnl quadrigraphs "@<:@" and "@:>@" produce "[" and "]" in the output AC_ARG_WITH(thread, - AC_HELP_STRING(--with(out)-thread@<:@=DIRECTORY@:>@, deprecated; use --with(out)-threads), + AS_HELP_STRING([--with(out)-thread@<:@=DIRECTORY@:>@], [deprecated; use --with(out)-threads]), [with_threads=$with_thread]) if test -z "$with_threads" @@ -2121,10 +2173,10 @@ _libs=$LIBS LIBS="$LIBS -lpthread" AC_MSG_CHECKING([for pthread_create in -lpthread]) - AC_TRY_LINK([#include + AC_LINK_IFELSE([AC_LANG_PROGRAM([[#include -void * start_routine (void *arg) { exit (0); }], [ -pthread_create (NULL, NULL, start_routine, NULL)], [ +void * start_routine (void *arg) { exit (0); }]], [[ +pthread_create (NULL, NULL, start_routine, NULL)]])],[ AC_MSG_RESULT(yes) AC_DEFINE(WITH_THREAD) posix_threads=yes @@ -2184,19 +2236,19 @@ # Bug 662787: Using semaphores causes unexplicable hangs on Solaris 8. case $ac_sys_system/$ac_sys_release in SunOS/5.6) AC_DEFINE(HAVE_PTHREAD_DESTRUCTOR, 1, - Defined for Solaris 2.6 bug in pthread header.) + [Defined for Solaris 2.6 bug in pthread header.]) ;; SunOS/5.8) AC_DEFINE(HAVE_BROKEN_POSIX_SEMAPHORES, 1, - Define if the Posix semaphores do not work on your system) + [Define if the Posix semaphores do not work on your system]) ;; AIX/5) AC_DEFINE(HAVE_BROKEN_POSIX_SEMAPHORES, 1, - Define if the Posix semaphores do not work on your system) + [Define if the Posix semaphores do not work on your system]) ;; esac AC_MSG_CHECKING(if PTHREAD_SCOPE_SYSTEM is supported) AC_CACHE_VAL(ac_cv_pthread_system_supported, - [AC_TRY_RUN([#include + [AC_RUN_IFELSE([AC_LANG_SOURCE([[#include void *foo(void *parm) { return NULL; } @@ -2207,10 +2259,10 @@ if (pthread_attr_setscope(&attr, PTHREAD_SCOPE_SYSTEM)) exit(-1); if (pthread_create(&id, &attr, foo, NULL)) exit(-1); exit(0); - }], - ac_cv_pthread_system_supported=yes, - ac_cv_pthread_system_supported=no, - ac_cv_pthread_system_supported=no) + }]])], + [ac_cv_pthread_system_supported=yes], + [ac_cv_pthread_system_supported=no], + [ac_cv_pthread_system_supported=no]) ]) AC_MSG_RESULT($ac_cv_pthread_system_supported) if test "$ac_cv_pthread_system_supported" = "yes"; then @@ -2245,7 +2297,7 @@ [ dnl the check does not work on cross compilation case... - AC_TRY_RUN([ /* AF_INET6 available check */ + AC_RUN_IFELSE([AC_LANG_SOURCE([[ /* AF_INET6 available check */ #include #include main() @@ -2255,25 +2307,31 @@ else exit(0); } -], +]])],[ AC_MSG_RESULT(yes) - ipv6=yes, + ipv6=yes +],[ AC_MSG_RESULT(no) - ipv6=no, + ipv6=no +],[ AC_MSG_RESULT(no) ipv6=no -) +]) if test "$ipv6" = "yes"; then AC_MSG_CHECKING(if RFC2553 API is available) - AC_TRY_COMPILE([#include -#include ], - [struct sockaddr_in6 x; -x.sin6_scope_id;], - AC_MSG_RESULT(yes) - ipv6=yes, - AC_MSG_RESULT(no, IPv6 disabled) - ipv6=no) + AC_COMPILE_IFELSE([ + AC_LANG_PROGRAM([[#include +#include ]], + [[struct sockaddr_in6 x; + x.sin6_scope_id;]]) + ],[ + AC_MSG_RESULT(yes) + ipv6=yes + ],[ + AC_MSG_RESULT(no, IPv6 disabled) + ipv6=no + ]) fi if test "$ipv6" = "yes"; then @@ -2394,16 +2452,19 @@ fi AC_MSG_CHECKING(for OSX 10.5 SDK or later) -AC_TRY_COMPILE([#include ], FSIORefNum fRef = 0, - AC_DEFINE(HAVE_OSX105_SDK, 1, Define if compiling using MacOS X 10.5 SDK or later.) - AC_MSG_RESULT(yes), +AC_COMPILE_IFELSE([ + AC_LANG_PROGRAM([[#include ]], [[FSIORefNum fRef = 0]]) +],[ + AC_DEFINE(HAVE_OSX105_SDK, 1, [Define if compiling using MacOS X 10.5 SDK or later.]) + AC_MSG_RESULT(yes) +],[ AC_MSG_RESULT(no) -) +]) # Check for --with-doc-strings AC_MSG_CHECKING(for --with-doc-strings) AC_ARG_WITH(doc-strings, - AC_HELP_STRING(--with(out)-doc-strings, disable/enable documentation strings)) + AS_HELP_STRING([--with(out)-doc-strings], [disable/enable documentation strings])) if test -z "$with_doc_strings" then with_doc_strings="yes" @@ -2418,7 +2479,7 @@ # Check for Python-specific malloc support AC_MSG_CHECKING(for --with-tsc) AC_ARG_WITH(tsc, -[ --with(out)-tsc enable/disable timestamp counter profile], [ + AS_HELP_STRING([--with(out)-tsc],[enable/disable timestamp counter profile]),[ if test "$withval" != no then AC_DEFINE(WITH_TSC, 1, @@ -2431,7 +2492,7 @@ # Check for Python-specific malloc support AC_MSG_CHECKING(for --with-pymalloc) AC_ARG_WITH(pymalloc, - AC_HELP_STRING(--with(out)-pymalloc, disable/enable specialized mallocs)) + AS_HELP_STRING([--with(out)-pymalloc], [disable/enable specialized mallocs])) if test -z "$with_pymalloc" then with_pymalloc="yes" @@ -2446,7 +2507,7 @@ # Check for Valgrind support AC_MSG_CHECKING([for --with-valgrind]) AC_ARG_WITH([valgrind], - AC_HELP_STRING([--with-valgrind], [Enable Valgrind support]),, + AS_HELP_STRING([--with-valgrind], [Enable Valgrind support]),, with_valgrind=no) AC_MSG_RESULT([$with_valgrind]) if test "$with_valgrind" != no; then @@ -2454,12 +2515,13 @@ [AC_DEFINE([WITH_VALGRIND], 1, [Define if you want pymalloc to be disabled when running under valgrind])], [AC_MSG_ERROR([Valgrind support requested but headers not available])] ) + OPT="-DDYNAMIC_ANNOTATIONS_ENABLED=1 $OPT" fi # Check for --with-wctype-functions AC_MSG_CHECKING(for --with-wctype-functions) AC_ARG_WITH(wctype-functions, - AC_HELP_STRING(--with-wctype-functions, use wctype.h functions), + AS_HELP_STRING([--with-wctype-functions], [use wctype.h functions]), [ if test "$withval" != no then @@ -2543,56 +2605,56 @@ # For some functions, having a definition is not sufficient, since # we want to take their address. AC_MSG_CHECKING(for chroot) -AC_TRY_COMPILE([#include ], void *x=chroot, - AC_DEFINE(HAVE_CHROOT, 1, Define if you have the 'chroot' function.) - AC_MSG_RESULT(yes), - AC_MSG_RESULT(no) -) +AC_COMPILE_IFELSE([AC_LANG_PROGRAM([[#include ]], [[void *x=chroot]])], + [AC_DEFINE(HAVE_CHROOT, 1, Define if you have the 'chroot' function.) + AC_MSG_RESULT(yes)], + [AC_MSG_RESULT(no) +]) AC_MSG_CHECKING(for link) -AC_TRY_COMPILE([#include ], void *x=link, - AC_DEFINE(HAVE_LINK, 1, Define if you have the 'link' function.) - AC_MSG_RESULT(yes), - AC_MSG_RESULT(no) -) +AC_COMPILE_IFELSE([AC_LANG_PROGRAM([[#include ]], [[void *x=link]])], + [AC_DEFINE(HAVE_LINK, 1, Define if you have the 'link' function.) + AC_MSG_RESULT(yes)], + [AC_MSG_RESULT(no) +]) AC_MSG_CHECKING(for symlink) -AC_TRY_COMPILE([#include ], void *x=symlink, - AC_DEFINE(HAVE_SYMLINK, 1, Define if you have the 'symlink' function.) - AC_MSG_RESULT(yes), - AC_MSG_RESULT(no) -) +AC_COMPILE_IFELSE([AC_LANG_PROGRAM([[#include ]], [[void *x=symlink]])], + [AC_DEFINE(HAVE_SYMLINK, 1, Define if you have the 'symlink' function.) + AC_MSG_RESULT(yes)], + [AC_MSG_RESULT(no) +]) AC_MSG_CHECKING(for fchdir) -AC_TRY_COMPILE([#include ], void *x=fchdir, - AC_DEFINE(HAVE_FCHDIR, 1, Define if you have the 'fchdir' function.) - AC_MSG_RESULT(yes), - AC_MSG_RESULT(no) -) +AC_COMPILE_IFELSE([AC_LANG_PROGRAM([[#include ]], [[void *x=fchdir]])], + [AC_DEFINE(HAVE_FCHDIR, 1, Define if you have the 'fchdir' function.) + AC_MSG_RESULT(yes)], + [AC_MSG_RESULT(no) +]) AC_MSG_CHECKING(for fsync) -AC_TRY_COMPILE([#include ], void *x=fsync, - AC_DEFINE(HAVE_FSYNC, 1, Define if you have the 'fsync' function.) - AC_MSG_RESULT(yes), - AC_MSG_RESULT(no) -) +AC_COMPILE_IFELSE([AC_LANG_PROGRAM([[#include ]], [[void *x=fsync]])], + [AC_DEFINE(HAVE_FSYNC, 1, Define if you have the 'fsync' function.) + AC_MSG_RESULT(yes)], + [AC_MSG_RESULT(no) +]) AC_MSG_CHECKING(for fdatasync) -AC_TRY_COMPILE([#include ], void *x=fdatasync, - AC_DEFINE(HAVE_FDATASYNC, 1, Define if you have the 'fdatasync' function.) - AC_MSG_RESULT(yes), - AC_MSG_RESULT(no) -) +AC_COMPILE_IFELSE([AC_LANG_PROGRAM([[#include ]], [[void *x=fdatasync]])], + [AC_DEFINE(HAVE_FDATASYNC, 1, Define if you have the 'fdatasync' function.) + AC_MSG_RESULT(yes)], + [AC_MSG_RESULT(no) +]) AC_MSG_CHECKING(for epoll) -AC_TRY_COMPILE([#include ], void *x=epoll_create, - AC_DEFINE(HAVE_EPOLL, 1, Define if you have the 'epoll' functions.) - AC_MSG_RESULT(yes), - AC_MSG_RESULT(no) -) +AC_COMPILE_IFELSE([AC_LANG_PROGRAM([[#include ]], [[void *x=epoll_create]])], + [AC_DEFINE(HAVE_EPOLL, 1, Define if you have the 'epoll' functions.) + AC_MSG_RESULT(yes)], + [AC_MSG_RESULT(no) +]) AC_MSG_CHECKING(for kqueue) -AC_TRY_COMPILE([ +AC_COMPILE_IFELSE([AC_LANG_PROGRAM([[ #include #include - ], int x=kqueue(), - AC_DEFINE(HAVE_KQUEUE, 1, Define if you have the 'kqueue' functions.) - AC_MSG_RESULT(yes), - AC_MSG_RESULT(no) -) + ]], [[int x=kqueue()]])], + [AC_DEFINE(HAVE_KQUEUE, 1, Define if you have the 'kqueue' functions.) + AC_MSG_RESULT(yes)], + [AC_MSG_RESULT(no) +]) # On some systems (eg. FreeBSD 5), we would find a definition of the # functions ctermid_r, setgroups in the library, but no prototype # (e.g. because we use _XOPEN_SOURCE). See whether we can take their @@ -2600,34 +2662,34 @@ # because of the missing prototypes. AC_MSG_CHECKING(for ctermid_r) -AC_TRY_COMPILE([ +AC_COMPILE_IFELSE([AC_LANG_PROGRAM([[ #include "confdefs.h" #include -], void* p = ctermid_r, - AC_DEFINE(HAVE_CTERMID_R, 1, Define if you have the 'ctermid_r' function.) - AC_MSG_RESULT(yes), - AC_MSG_RESULT(no) -) +]], [[void* p = ctermid_r]])], + [AC_DEFINE(HAVE_CTERMID_R, 1, Define if you have the 'ctermid_r' function.) + AC_MSG_RESULT(yes)], + [AC_MSG_RESULT(no) +]) AC_MSG_CHECKING(for flock) -AC_TRY_COMPILE([ +AC_COMPILE_IFELSE([AC_LANG_PROGRAM([[ #include "confdefs.h" #include -], void* p = flock, - AC_DEFINE(HAVE_FLOCK, 1, Define if you have the 'flock' function.) - AC_MSG_RESULT(yes), - AC_MSG_RESULT(no) -) +]], [[void* p = flock]])], + [AC_DEFINE(HAVE_FLOCK, 1, Define if you have the 'flock' function.) + AC_MSG_RESULT(yes)], + [AC_MSG_RESULT(no) +]) AC_MSG_CHECKING(for getpagesize) -AC_TRY_COMPILE([ +AC_COMPILE_IFELSE([AC_LANG_PROGRAM([[ #include "confdefs.h" #include -], void* p = getpagesize, - AC_DEFINE(HAVE_GETPAGESIZE, 1, Define if you have the 'getpagesize' function.) - AC_MSG_RESULT(yes), - AC_MSG_RESULT(no) -) +]], [[void* p = getpagesize]])], + [AC_DEFINE(HAVE_GETPAGESIZE, 1, Define if you have the 'getpagesize' function.) + AC_MSG_RESULT(yes)], + [AC_MSG_RESULT(no) +]) dnl check for true AC_CHECK_PROGS(TRUE, true, /bin/true) @@ -2641,7 +2703,7 @@ # On Tru64, chflags seems to be present, but calling it will # exit Python AC_CACHE_CHECK([for chflags], [ac_cv_have_chflags], [dnl -AC_TRY_RUN([[ +AC_RUN_IFELSE([AC_LANG_SOURCE([[[ #include #include int main(int argc, char*argv[]) @@ -2650,19 +2712,20 @@ return 1; return 0; } -]], ac_cv_have_chflags=yes, - ac_cv_have_chflags=no, - ac_cv_have_chflags=cross) +]]])], +[ac_cv_have_chflags=yes], +[ac_cv_have_chflags=no], +[ac_cv_have_chflags=cross]) ]) if test "$ac_cv_have_chflags" = cross ; then AC_CHECK_FUNC([chflags], [ac_cv_have_chflags="yes"], [ac_cv_have_chflags="no"]) fi if test "$ac_cv_have_chflags" = yes ; then - AC_DEFINE(HAVE_CHFLAGS, 1, Define to 1 if you have the `chflags' function.) + AC_DEFINE(HAVE_CHFLAGS, 1, [Define to 1 if you have the `chflags' function.]) fi AC_CACHE_CHECK([for lchflags], [ac_cv_have_lchflags], [dnl -AC_TRY_RUN([[ +AC_RUN_IFELSE([AC_LANG_SOURCE([[[ #include #include int main(int argc, char*argv[]) @@ -2671,15 +2734,13 @@ return 1; return 0; } -]], ac_cv_have_lchflags=yes, - ac_cv_have_lchflags=no, - ac_cv_have_lchflags=cross) +]]])],[ac_cv_have_lchflags=yes],[ac_cv_have_lchflags=no],[ac_cv_have_lchflags=cross]) ]) if test "$ac_cv_have_lchflags" = cross ; then AC_CHECK_FUNC([lchflags], [ac_cv_have_lchflags="yes"], [ac_cv_have_lchflags="no"]) fi if test "$ac_cv_have_lchflags" = yes ; then - AC_DEFINE(HAVE_LCHFLAGS, 1, Define to 1 if you have the `lchflags' function.) + AC_DEFINE(HAVE_LCHFLAGS, 1, [Define to 1 if you have the `lchflags' function.]) fi dnl Check if system zlib has *Copy() functions @@ -2702,7 +2763,7 @@ ;; esac -AC_CHECK_LIB(z, inflateCopy, AC_DEFINE(HAVE_ZLIB_COPY, 1, Define if the zlib library has inflateCopy)) +AC_CHECK_LIB(z, inflateCopy, AC_DEFINE(HAVE_ZLIB_COPY, 1, [Define if the zlib library has inflateCopy])) case $ac_sys_system/$ac_sys_release in Darwin/*) @@ -2712,55 +2773,54 @@ esac AC_MSG_CHECKING(for hstrerror) -AC_TRY_LINK([ +AC_LINK_IFELSE([AC_LANG_PROGRAM([[ #include "confdefs.h" #include -], void* p = hstrerror; hstrerror(0), - AC_DEFINE(HAVE_HSTRERROR, 1, Define if you have the 'hstrerror' function.) - AC_MSG_RESULT(yes), - AC_MSG_RESULT(no) -) +]], [[void* p = hstrerror; hstrerror(0)]])], + [AC_DEFINE(HAVE_HSTRERROR, 1, Define if you have the 'hstrerror' function.) + AC_MSG_RESULT(yes)], + [AC_MSG_RESULT(no) +]) AC_MSG_CHECKING(for inet_aton) -AC_TRY_LINK([ +AC_LINK_IFELSE([AC_LANG_PROGRAM([[ #include "confdefs.h" #include #include #include #include -], void* p = inet_aton;inet_aton(0,0), - AC_DEFINE(HAVE_INET_ATON, 1, Define if you have the 'inet_aton' function.) - AC_MSG_RESULT(yes), - AC_MSG_RESULT(no) -) +]], [[void* p = inet_aton;inet_aton(0,0)]])], + [AC_DEFINE(HAVE_INET_ATON, 1, Define if you have the 'inet_aton' function.) + AC_MSG_RESULT(yes)], + [AC_MSG_RESULT(no) +]) AC_MSG_CHECKING(for inet_pton) -AC_TRY_COMPILE([ +AC_COMPILE_IFELSE([AC_LANG_PROGRAM([[ #include "confdefs.h" #include #include #include #include -], void* p = inet_pton, - AC_DEFINE(HAVE_INET_PTON, 1, Define if you have the 'inet_pton' function.) - AC_MSG_RESULT(yes), - AC_MSG_RESULT(no) -) +]], [[void* p = inet_pton]])], + [AC_DEFINE(HAVE_INET_PTON, 1, Define if you have the 'inet_pton' function.) + AC_MSG_RESULT(yes)], + [AC_MSG_RESULT(no) +]) # On some systems, setgroups is in unistd.h, on others, in grp.h AC_MSG_CHECKING(for setgroups) -AC_TRY_COMPILE([ +AC_COMPILE_IFELSE([AC_LANG_PROGRAM([[ #include "confdefs.h" #include #ifdef HAVE_GRP_H #include #endif -], -void* p = setgroups, - AC_DEFINE(HAVE_SETGROUPS, 1, Define if you have the 'setgroups' function.) - AC_MSG_RESULT(yes), - AC_MSG_RESULT(no) -) +]], [[void* p = setgroups]])], + [AC_DEFINE(HAVE_SETGROUPS, 1, Define if you have the 'setgroups' function.) + AC_MSG_RESULT(yes)], + [AC_MSG_RESULT(no) +]) # check for openpty and forkpty @@ -2785,30 +2845,27 @@ AC_REPLACE_FUNCS(dup2 getcwd strdup) AC_CHECK_FUNCS(getpgrp, - AC_TRY_COMPILE([#include ], - [getpgrp(0);], - AC_DEFINE(GETPGRP_HAVE_ARG, 1, - [Define if getpgrp() must be called as getpgrp(0).]) - ) + AC_COMPILE_IFELSE([AC_LANG_PROGRAM([[#include ]], [[getpgrp(0);]])], + [AC_DEFINE(GETPGRP_HAVE_ARG, 1, [Define if getpgrp() must be called as getpgrp(0).])], + []) ) AC_CHECK_FUNCS(setpgrp, - AC_TRY_COMPILE([#include ], - [setpgrp(0,0);], - AC_DEFINE(SETPGRP_HAVE_ARG, 1, - [Define if setpgrp() must be called as setpgrp(0, 0).]) - ) + AC_COMPILE_IFELSE([AC_LANG_PROGRAM([[#include ]], [[setpgrp(0,0);]])], + [AC_DEFINE(SETPGRP_HAVE_ARG, 1, [Define if setpgrp() must be called as setpgrp(0, 0).])], + []) ) AC_CHECK_FUNCS(gettimeofday, - AC_TRY_COMPILE([#include ], - [gettimeofday((struct timeval*)0,(struct timezone*)0);], , - AC_DEFINE(GETTIMEOFDAY_NO_TZ, 1, - [Define if gettimeofday() does not have second (timezone) argument - This is the case on Motorola V4 (R40V4.2)]) - ) + AC_COMPILE_IFELSE([AC_LANG_PROGRAM([[#include ]], + [[gettimeofday((struct timeval*)0,(struct timezone*)0);]])], + [], + [AC_DEFINE(GETTIMEOFDAY_NO_TZ, 1, + [Define if gettimeofday() does not have second (timezone) argument + This is the case on Motorola V4 (R40V4.2)]) + ]) ) AC_MSG_CHECKING(for major, minor, and makedev) -AC_TRY_LINK([ +AC_LINK_IFELSE([AC_LANG_PROGRAM([[ #if defined(MAJOR_IN_MKDEV) #include #elif defined(MAJOR_IN_SYSMACROS) @@ -2816,9 +2873,9 @@ #else #include #endif -],[ +]], [[ makedev(major(0),minor(0)); -],[ +]])],[ AC_DEFINE(HAVE_DEVICE_MACROS, 1, [Define to 1 if you have the device macros.]) AC_MSG_RESULT(yes) @@ -2829,20 +2886,20 @@ # On OSF/1 V5.1, getaddrinfo is available, but a define # for [no]getaddrinfo in netdb.h. AC_MSG_CHECKING(for getaddrinfo) -AC_TRY_LINK([ +AC_LINK_IFELSE([AC_LANG_PROGRAM([[ #include #include #include #include -], [getaddrinfo(NULL, NULL, NULL, NULL);], -have_getaddrinfo=yes, -have_getaddrinfo=no) +]], [[getaddrinfo(NULL, NULL, NULL, NULL);]])], +[have_getaddrinfo=yes], +[have_getaddrinfo=no]) AC_MSG_RESULT($have_getaddrinfo) if test $have_getaddrinfo = yes then AC_MSG_CHECKING(getaddrinfo bug) AC_CACHE_VAL(ac_cv_buggy_getaddrinfo, - AC_TRY_RUN([[ + AC_RUN_IFELSE([AC_LANG_SOURCE([[[ #include #include #include @@ -2928,9 +2985,10 @@ freeaddrinfo(aitop); return 1; } -]], ac_cv_buggy_getaddrinfo=no, - ac_cv_buggy_getaddrinfo=yes, - ac_cv_buggy_getaddrinfo=yes)) +]]])], +[ac_cv_buggy_getaddrinfo=no], +[ac_cv_buggy_getaddrinfo=yes], +[ac_cv_buggy_getaddrinfo=yes])) fi if test $have_getaddrinfo = no -o "$ac_cv_buggy_getaddrinfo" = yes @@ -2958,10 +3016,11 @@ AC_STRUCT_ST_BLOCKS AC_MSG_CHECKING(for time.h that defines altzone) -AC_CACHE_VAL(ac_cv_header_time_altzone, -[AC_TRY_COMPILE([#include ], [return altzone;], - ac_cv_header_time_altzone=yes, - ac_cv_header_time_altzone=no)]) +AC_CACHE_VAL(ac_cv_header_time_altzone,[ + AC_COMPILE_IFELSE([AC_LANG_PROGRAM([[#include ]], [[return altzone;]])], + [ac_cv_header_time_altzone=yes], + [ac_cv_header_time_altzone=no]) + ]) AC_MSG_RESULT($ac_cv_header_time_altzone) if test $ac_cv_header_time_altzone = yes; then AC_DEFINE(HAVE_ALTZONE, 1, [Define this if your time.h defines altzone.]) @@ -2969,25 +3028,23 @@ was_it_defined=no AC_MSG_CHECKING(whether sys/select.h and sys/time.h may both be included) -AC_TRY_COMPILE([ +AC_COMPILE_IFELSE([AC_LANG_PROGRAM([[ #include #include #include -], [;], [ +]], [[;]])],[ AC_DEFINE(SYS_SELECT_WITH_SYS_TIME, 1, [Define if you can safely include both and (which you can't on SCO ODT 3.0).]) was_it_defined=yes -]) +],[]) AC_MSG_RESULT($was_it_defined) AC_MSG_CHECKING(for addrinfo) AC_CACHE_VAL(ac_cv_struct_addrinfo, -AC_TRY_COMPILE([ -# include ], - [struct addrinfo a], - ac_cv_struct_addrinfo=yes, - ac_cv_struct_addrinfo=no)) +AC_COMPILE_IFELSE([AC_LANG_PROGRAM([[#include ]], [[struct addrinfo a]])], + [ac_cv_struct_addrinfo=yes], + [ac_cv_struct_addrinfo=no])) AC_MSG_RESULT($ac_cv_struct_addrinfo) if test $ac_cv_struct_addrinfo = yes; then AC_DEFINE(HAVE_ADDRINFO, 1, [struct addrinfo (netdb.h)]) @@ -2995,12 +3052,11 @@ AC_MSG_CHECKING(for sockaddr_storage) AC_CACHE_VAL(ac_cv_struct_sockaddr_storage, -AC_TRY_COMPILE([ +AC_COMPILE_IFELSE([AC_LANG_PROGRAM([[ # include -# include ], - [struct sockaddr_storage s], - ac_cv_struct_sockaddr_storage=yes, - ac_cv_struct_sockaddr_storage=no)) +# include ]], [[struct sockaddr_storage s]])], + [ac_cv_struct_sockaddr_storage=yes], + [ac_cv_struct_sockaddr_storage=no])) AC_MSG_RESULT($ac_cv_struct_sockaddr_storage) if test $ac_cv_struct_sockaddr_storage = yes; then AC_DEFINE(HAVE_SOCKADDR_STORAGE, 1, [struct sockaddr_storage (sys/socket.h)]) @@ -3013,30 +3069,33 @@ works=no AC_MSG_CHECKING(for working volatile) -AC_TRY_COMPILE([],[volatile int x; x = 0;], works=yes, - AC_DEFINE(volatile, [], [Define to empty if the keyword does not work.]) +AC_COMPILE_IFELSE([AC_LANG_PROGRAM([[]], [[volatile int x; x = 0;]])], + [works=yes], + [AC_DEFINE(volatile, , [Define to empty if the keyword does not work.])] ) AC_MSG_RESULT($works) works=no AC_MSG_CHECKING(for working signed char) -AC_TRY_COMPILE([], [signed char c;], works=yes, - AC_DEFINE(signed, [], [Define to empty if the keyword does not work.]) +AC_COMPILE_IFELSE([AC_LANG_PROGRAM([[]], [[signed char c;]])], + [works=yes], + [AC_DEFINE(signed, , [Define to empty if the keyword does not work.])] ) AC_MSG_RESULT($works) have_prototypes=no AC_MSG_CHECKING(for prototypes) -AC_TRY_COMPILE([int foo(int x) { return 0; }], [return foo(10);],[ - AC_DEFINE(HAVE_PROTOTYPES, 1, - [Define if your compiler supports function prototype]) - have_prototypes=yes -]) +AC_COMPILE_IFELSE([AC_LANG_PROGRAM([[int foo(int x) { return 0; }]], [[return foo(10);]])], + [AC_DEFINE(HAVE_PROTOTYPES, 1, + [Define if your compiler supports function prototype]) + have_prototypes=yes], + [] +) AC_MSG_RESULT($have_prototypes) works=no AC_MSG_CHECKING(for variable length prototypes and stdarg.h) -AC_TRY_COMPILE([ +AC_COMPILE_IFELSE([AC_LANG_PROGRAM([[ #include int foo(int x, ...) { va_list va; @@ -3046,44 +3105,44 @@ va_arg(va, double); return 0; } -], [return foo(10, "", 3.14);], [ +]], [[return foo(10, "", 3.14);]])],[ AC_DEFINE(HAVE_STDARG_PROTOTYPES, 1, [Define if your compiler supports variable length function prototypes (e.g. void fprintf(FILE *, char *, ...);) *and* ]) works=yes -]) +],[]) AC_MSG_RESULT($works) # check for socketpair AC_MSG_CHECKING(for socketpair) -AC_TRY_COMPILE([ +AC_COMPILE_IFELSE([AC_LANG_PROGRAM([[ #include #include -], void *x=socketpair, - AC_DEFINE(HAVE_SOCKETPAIR, 1, Define if you have the 'socketpair' function.) - AC_MSG_RESULT(yes), - AC_MSG_RESULT(no) +]], [[void *x=socketpair]])], + [AC_DEFINE(HAVE_SOCKETPAIR, 1, [Define if you have the 'socketpair' function.]) + AC_MSG_RESULT(yes)], + [AC_MSG_RESULT(no)] ) # check if sockaddr has sa_len member AC_MSG_CHECKING(if sockaddr has sa_len member) -AC_TRY_COMPILE([#include -#include ], -[struct sockaddr x; -x.sa_len = 0;], - AC_MSG_RESULT(yes) - AC_DEFINE(HAVE_SOCKADDR_SA_LEN, 1, [Define if sockaddr has sa_len member]), - AC_MSG_RESULT(no)) +AC_COMPILE_IFELSE([AC_LANG_PROGRAM([[#include +#include ]], [[struct sockaddr x; +x.sa_len = 0;]])], + [AC_MSG_RESULT(yes) + AC_DEFINE(HAVE_SOCKADDR_SA_LEN, 1, [Define if sockaddr has sa_len member])], + [AC_MSG_RESULT(no)] +) va_list_is_array=no AC_MSG_CHECKING(whether va_list is an array) -AC_TRY_COMPILE([ +AC_COMPILE_IFELSE([AC_LANG_PROGRAM([[ #ifdef HAVE_STDARG_PROTOTYPES #include #else #include #endif -], [va_list list1, list2; list1 = list2;], , [ +]], [[va_list list1, list2; list1 = list2;]])],[],[ AC_DEFINE(VA_LIST_IS_ARRAY, 1, [Define if a va_list is an array of some kind]) va_list_is_array=yes ]) @@ -3098,9 +3157,9 @@ AC_MSG_CHECKING([gethostbyname_r with 6 args]) OLD_CFLAGS=$CFLAGS CFLAGS="$CFLAGS $MY_CPPFLAGS $MY_THREAD_CPPFLAGS $MY_CFLAGS" - AC_TRY_COMPILE([ + AC_COMPILE_IFELSE([AC_LANG_PROGRAM([[ # include - ], [ + ]], [[ char *name; struct hostent *he, *res; char buffer[2048]; @@ -3108,48 +3167,50 @@ int h_errnop; (void) gethostbyname_r(name, he, buffer, buflen, &res, &h_errnop) - ], [ + ]])],[ AC_DEFINE(HAVE_GETHOSTBYNAME_R) AC_DEFINE(HAVE_GETHOSTBYNAME_R_6_ARG, 1, [Define this if you have the 6-arg version of gethostbyname_r().]) AC_MSG_RESULT(yes) - ], [ + ],[ AC_MSG_RESULT(no) AC_MSG_CHECKING([gethostbyname_r with 5 args]) - AC_TRY_COMPILE([ -# include - ], [ - char *name; - struct hostent *he; - char buffer[2048]; - int buflen = 2048; - int h_errnop; - - (void) gethostbyname_r(name, he, buffer, buflen, &h_errnop) - ], [ - AC_DEFINE(HAVE_GETHOSTBYNAME_R) - AC_DEFINE(HAVE_GETHOSTBYNAME_R_5_ARG, 1, - [Define this if you have the 5-arg version of gethostbyname_r().]) - AC_MSG_RESULT(yes) - ], [ - AC_MSG_RESULT(no) - AC_MSG_CHECKING([gethostbyname_r with 3 args]) - AC_TRY_COMPILE([ + AC_COMPILE_IFELSE([AC_LANG_PROGRAM([[ # include - ], [ + ]], [[ char *name; struct hostent *he; - struct hostent_data data; - - (void) gethostbyname_r(name, he, &data); - ], [ + char buffer[2048]; + int buflen = 2048; + int h_errnop; + + (void) gethostbyname_r(name, he, buffer, buflen, &h_errnop) + ]])], + [ AC_DEFINE(HAVE_GETHOSTBYNAME_R) - AC_DEFINE(HAVE_GETHOSTBYNAME_R_3_ARG, 1, - [Define this if you have the 3-arg version of gethostbyname_r().]) + AC_DEFINE(HAVE_GETHOSTBYNAME_R_5_ARG, 1, + [Define this if you have the 5-arg version of gethostbyname_r().]) AC_MSG_RESULT(yes) ], [ AC_MSG_RESULT(no) - ]) + AC_MSG_CHECKING([gethostbyname_r with 3 args]) + AC_COMPILE_IFELSE([AC_LANG_PROGRAM([[ +# include + ]], [[ + char *name; + struct hostent *he; + struct hostent_data data; + + (void) gethostbyname_r(name, he, &data); + ]])], + [ + AC_DEFINE(HAVE_GETHOSTBYNAME_R) + AC_DEFINE(HAVE_GETHOSTBYNAME_R_3_ARG, 1, + [Define this if you have the 3-arg version of gethostbyname_r().]) + AC_MSG_RESULT(yes) + ], [ + AC_MSG_RESULT(no) + ]) ]) ]) CFLAGS=$OLD_CFLAGS @@ -3174,7 +3235,7 @@ # Check for --with-fpectl AC_MSG_CHECKING(for --with-fpectl) AC_ARG_WITH(fpectl, - AC_HELP_STRING(--with-fpectl, enable SIGFPE catching), + AS_HELP_STRING([--with-fpectl], [enable SIGFPE catching]), [ if test "$withval" != no then @@ -3193,7 +3254,7 @@ esac AC_MSG_CHECKING(for --with-libm=STRING) AC_ARG_WITH(libm, - AC_HELP_STRING(--with-libm=STRING, math library), + AS_HELP_STRING([--with-libm=STRING], [math library]), [ if test "$withval" = no then LIBM= @@ -3209,7 +3270,7 @@ AC_SUBST(LIBC) AC_MSG_CHECKING(for --with-libc=STRING) AC_ARG_WITH(libc, - AC_HELP_STRING(--with-libc=STRING, C library), + AS_HELP_STRING([--with-libc=STRING], [C library]), [ if test "$withval" = no then LIBC= @@ -3227,7 +3288,7 @@ AC_MSG_CHECKING(whether C doubles are little-endian IEEE 754 binary64) AC_CACHE_VAL(ac_cv_little_endian_double, [ -AC_TRY_RUN([ +AC_RUN_IFELSE([AC_LANG_SOURCE([[ #include int main() { double x = 9006104071832581.0; @@ -3236,10 +3297,10 @@ else return 1; } -], -ac_cv_little_endian_double=yes, -ac_cv_little_endian_double=no, -ac_cv_little_endian_double=no)]) +]])], +[ac_cv_little_endian_double=yes], +[ac_cv_little_endian_double=no], +[ac_cv_little_endian_double=no])]) AC_MSG_RESULT($ac_cv_little_endian_double) if test "$ac_cv_little_endian_double" = yes then @@ -3250,7 +3311,7 @@ AC_MSG_CHECKING(whether C doubles are big-endian IEEE 754 binary64) AC_CACHE_VAL(ac_cv_big_endian_double, [ -AC_TRY_RUN([ +AC_RUN_IFELSE([AC_LANG_SOURCE([[ #include int main() { double x = 9006104071832581.0; @@ -3259,10 +3320,10 @@ else return 1; } -], -ac_cv_big_endian_double=yes, -ac_cv_big_endian_double=no, -ac_cv_big_endian_double=no)]) +]])], +[ac_cv_big_endian_double=yes], +[ac_cv_big_endian_double=no], +[ac_cv_big_endian_double=no])]) AC_MSG_RESULT($ac_cv_big_endian_double) if test "$ac_cv_big_endian_double" = yes then @@ -3277,7 +3338,7 @@ # conversions work. AC_MSG_CHECKING(whether C doubles are ARM mixed-endian IEEE 754 binary64) AC_CACHE_VAL(ac_cv_mixed_endian_double, [ -AC_TRY_RUN([ +AC_RUN_IFELSE([AC_LANG_SOURCE([[ #include int main() { double x = 9006104071832581.0; @@ -3286,10 +3347,10 @@ else return 1; } -], -ac_cv_mixed_endian_double=yes, -ac_cv_mixed_endian_double=no, -ac_cv_mixed_endian_double=no)]) +]])], +[ac_cv_mixed_endian_double=yes], +[ac_cv_mixed_endian_double=no], +[ac_cv_mixed_endian_double=no])]) AC_MSG_RESULT($ac_cv_mixed_endian_double) if test "$ac_cv_mixed_endian_double" = yes then @@ -3309,12 +3370,11 @@ # so we try it on all platforms. AC_MSG_CHECKING(whether we can use gcc inline assembler to get and set x87 control word) -AC_TRY_COMPILE([], [ +AC_COMPILE_IFELSE([AC_LANG_PROGRAM([[]], [[ unsigned short cw; __asm__ __volatile__ ("fnstcw %0" : "=m" (cw)); __asm__ __volatile__ ("fldcw %0" : : "m" (cw)); -], -[have_gcc_asm_for_x87=yes], [have_gcc_asm_for_x87=no]) +]])],[have_gcc_asm_for_x87=yes],[have_gcc_asm_for_x87=no]) AC_MSG_RESULT($have_gcc_asm_for_x87) if test "$have_gcc_asm_for_x87" = yes then @@ -3331,7 +3391,7 @@ # $BASECFLAGS may affect the result ac_save_cc="$CC" CC="$CC $BASECFLAGS" -AC_TRY_RUN([ +AC_RUN_IFELSE([AC_LANG_SOURCE([[ #include #include int main() { @@ -3350,10 +3410,10 @@ /* both tests show evidence of double rounding */ exit(1); } -], -ac_cv_x87_double_rounding=no, -ac_cv_x87_double_rounding=yes, -ac_cv_x87_double_rounding=no) +]])], +[ac_cv_x87_double_rounding=no], +[ac_cv_x87_double_rounding=yes], +[ac_cv_x87_double_rounding=no]) CC="$ac_save_cc" AC_MSG_RESULT($ac_cv_x87_double_rounding) if test "$ac_cv_x87_double_rounding" = yes @@ -3373,7 +3433,7 @@ # -0. on some architectures. AC_MSG_CHECKING(whether tanh preserves the sign of zero) AC_CACHE_VAL(ac_cv_tanh_preserves_zero_sign, [ -AC_TRY_RUN([ +AC_RUN_IFELSE([AC_LANG_SOURCE([[ #include #include int main() { @@ -3384,10 +3444,10 @@ atan2(tanh(-0.), -1.) == atan2(-0., -1.)) exit(0); else exit(1); } -], -ac_cv_tanh_preserves_zero_sign=yes, -ac_cv_tanh_preserves_zero_sign=no, -ac_cv_tanh_preserves_zero_sign=no)]) +]])], +[ac_cv_tanh_preserves_zero_sign=yes], +[ac_cv_tanh_preserves_zero_sign=no], +[ac_cv_tanh_preserves_zero_sign=no])]) AC_MSG_RESULT($ac_cv_tanh_preserves_zero_sign) if test "$ac_cv_tanh_preserves_zero_sign" = yes then @@ -3408,7 +3468,7 @@ # sem_open results in a 'Signal 12' error. AC_MSG_CHECKING(whether POSIX semaphores are enabled) AC_CACHE_VAL(ac_cv_posix_semaphores_enabled, -AC_TRY_RUN([ +AC_RUN_IFELSE([AC_LANG_SOURCE([[ #include #include #include @@ -3425,9 +3485,10 @@ sem_unlink("/autoconf"); return 0; } -], ac_cv_posix_semaphores_enabled=yes, - ac_cv_posix_semaphores_enabled=no, - ac_cv_posix_semaphores_enabled=yes) +]])], +[ac_cv_posix_semaphores_enabled=yes], +[ac_cv_posix_semaphores_enabled=no], +[ac_cv_posix_semaphores_enabled=yes]) ) AC_MSG_RESULT($ac_cv_posix_semaphores_enabled) if test $ac_cv_posix_semaphores_enabled = no @@ -3439,7 +3500,7 @@ # Multiprocessing check for broken sem_getvalue AC_MSG_CHECKING(for broken sem_getvalue) AC_CACHE_VAL(ac_cv_broken_sem_getvalue, -AC_TRY_RUN([ +AC_RUN_IFELSE([AC_LANG_SOURCE([[ #include #include #include @@ -3460,9 +3521,10 @@ sem_unlink("/autocftw"); return res==-1 ? 1 : 0; } -], ac_cv_broken_sem_getvalue=no, - ac_cv_broken_sem_getvalue=yes, - ac_cv_broken_sem_getvalue=yes) +]])], +[ac_cv_broken_sem_getvalue=no], +[ac_cv_broken_sem_getvalue=yes], +[ac_cv_broken_sem_getvalue=yes]) ) AC_MSG_RESULT($ac_cv_broken_sem_getvalue) if test $ac_cv_broken_sem_getvalue = yes @@ -3474,7 +3536,7 @@ # determine what size digit to use for Python's longs AC_MSG_CHECKING([digit size for Python's longs]) AC_ARG_ENABLE(big-digits, -AC_HELP_STRING([--enable-big-digits@<:@=BITS@:>@],[use big digits for Python longs [[BITS=30]]]), +AS_HELP_STRING([--enable-big-digits@<:@=BITS@:>@],[use big digits for Python longs [[BITS=30]]]), [case $enable_big_digits in yes) enable_big_digits=30 ;; @@ -3507,14 +3569,14 @@ AC_MSG_CHECKING(for UCS-4 tcl) have_ucs4_tcl=no -AC_TRY_COMPILE([ +AC_COMPILE_IFELSE([AC_LANG_PROGRAM([[ #include #if TCL_UTF_MAX != 6 # error "NOT UCS4_TCL" -#endif], [], [ +#endif]], [[]])],[ AC_DEFINE(HAVE_UCS4_TCL, 1, [Define this if you have tcl and TCL_UTF_MAX==6]) have_ucs4_tcl=yes -]) +],[]) AC_MSG_RESULT($have_ucs4_tcl) # check whether wchar_t is signed or not @@ -3523,23 +3585,23 @@ # check whether wchar_t is signed or not AC_MSG_CHECKING(whether wchar_t is signed) AC_CACHE_VAL(ac_cv_wchar_t_signed, [ - AC_TRY_RUN([ + AC_RUN_IFELSE([AC_LANG_SOURCE([[ #include int main() { /* Success: exit code 0 */ exit((((wchar_t) -1) < ((wchar_t) 0)) ? 0 : 1); } - ], - ac_cv_wchar_t_signed=yes, - ac_cv_wchar_t_signed=no, - ac_cv_wchar_t_signed=yes)]) + ]])], + [ac_cv_wchar_t_signed=yes], + [ac_cv_wchar_t_signed=no], + [ac_cv_wchar_t_signed=yes])]) AC_MSG_RESULT($ac_cv_wchar_t_signed) fi AC_MSG_CHECKING(what type to use for str) AC_ARG_WITH(wide-unicode, - AC_HELP_STRING(--with-wide-unicode, Use 4-byte Unicode characters (default is 2 bytes)), + AS_HELP_STRING([--with-wide-unicode], [Use 4-byte Unicode characters (default is 2 bytes)]), [ if test "$withval" != no then unicode_size="4" @@ -3593,15 +3655,15 @@ # or fills with zeros (like the Cray J90, according to Tim Peters). AC_MSG_CHECKING(whether right shift extends the sign bit) AC_CACHE_VAL(ac_cv_rshift_extends_sign, [ -AC_TRY_RUN([ +AC_RUN_IFELSE([AC_LANG_SOURCE([[ int main() { exit(((-1)>>3 == -1) ? 0 : 1); } -], -ac_cv_rshift_extends_sign=yes, -ac_cv_rshift_extends_sign=no, -ac_cv_rshift_extends_sign=yes)]) +]])], +[ac_cv_rshift_extends_sign=yes], +[ac_cv_rshift_extends_sign=no], +[ac_cv_rshift_extends_sign=yes])]) AC_MSG_RESULT($ac_cv_rshift_extends_sign) if test "$ac_cv_rshift_extends_sign" = no then @@ -3613,12 +3675,12 @@ # check for getc_unlocked and related locking functions AC_MSG_CHECKING(for getc_unlocked() and friends) AC_CACHE_VAL(ac_cv_have_getc_unlocked, [ -AC_TRY_LINK([#include ],[ +AC_LINK_IFELSE([AC_LANG_PROGRAM([[#include ]], [[ FILE *f = fopen("/dev/null", "r"); flockfile(f); getc_unlocked(f); funlockfile(f); -], ac_cv_have_getc_unlocked=yes, ac_cv_have_getc_unlocked=no)]) +]])],[ac_cv_have_getc_unlocked=yes],[ac_cv_have_getc_unlocked=no])]) AC_MSG_RESULT($ac_cv_have_getc_unlocked) if test "$ac_cv_have_getc_unlocked" = yes then @@ -3665,8 +3727,10 @@ [Define if you have readline 2.1]), ,$READLINE_LIBS) # check for readline 2.2 -AC_TRY_CPP([#include ], -have_readline=yes, have_readline=no) +AC_PREPROC_IFELSE([AC_LANG_SOURCE([[#include ]])], + [have_readline=yes], + [have_readline=no] +) if test $have_readline = yes then AC_EGREP_HEADER([extern int rl_completion_append_character;], @@ -3695,8 +3759,10 @@ [Define if you have readline 4.2]), ,$READLINE_LIBS) # also in readline 4.2 -AC_TRY_CPP([#include ], -have_readline=yes, have_readline=no) +AC_PREPROC_IFELSE([AC_LANG_SOURCE([[#include ]])], + [have_readline=yes], + [have_readline=no] +) if test $have_readline = yes then AC_EGREP_HEADER([extern int rl_catch_signals;], @@ -3710,7 +3776,7 @@ AC_MSG_CHECKING(for broken nice()) AC_CACHE_VAL(ac_cv_broken_nice, [ -AC_TRY_RUN([ +AC_RUN_IFELSE([AC_LANG_SOURCE([[ int main() { int val1 = nice(1); @@ -3718,10 +3784,10 @@ exit(0); exit(1); } -], -ac_cv_broken_nice=yes, -ac_cv_broken_nice=no, -ac_cv_broken_nice=no)]) +]])], +[ac_cv_broken_nice=yes], +[ac_cv_broken_nice=no], +[ac_cv_broken_nice=no])]) AC_MSG_RESULT($ac_cv_broken_nice) if test "$ac_cv_broken_nice" = yes then @@ -3731,7 +3797,7 @@ AC_MSG_CHECKING(for broken poll()) AC_CACHE_VAL(ac_cv_broken_poll, -AC_TRY_RUN([ +AC_RUN_IFELSE([AC_LANG_SOURCE([[ #include int main() @@ -3749,10 +3815,10 @@ else return 1; } -], -ac_cv_broken_poll=yes, -ac_cv_broken_poll=no, -ac_cv_broken_poll=no)) +]])], +[ac_cv_broken_poll=yes], +[ac_cv_broken_poll=no], +[ac_cv_broken_poll=no])) AC_MSG_RESULT($ac_cv_broken_poll) if test "$ac_cv_broken_poll" = yes then @@ -3768,7 +3834,7 @@ # check tzset(3) exists and works like we expect it to AC_MSG_CHECKING(for working tzset()) AC_CACHE_VAL(ac_cv_working_tzset, [ -AC_TRY_RUN([ +AC_RUN_IFELSE([AC_LANG_SOURCE([[ #include #include #include @@ -3831,10 +3897,10 @@ exit(0); } -], -ac_cv_working_tzset=yes, -ac_cv_working_tzset=no, -ac_cv_working_tzset=no)]) +]])], +[ac_cv_working_tzset=yes], +[ac_cv_working_tzset=no], +[ac_cv_working_tzset=no])]) AC_MSG_RESULT($ac_cv_working_tzset) if test "$ac_cv_working_tzset" = yes then @@ -3845,13 +3911,12 @@ # Look for subsecond timestamps in struct stat AC_MSG_CHECKING(for tv_nsec in struct stat) AC_CACHE_VAL(ac_cv_stat_tv_nsec, -AC_TRY_COMPILE([#include ], [ +AC_COMPILE_IFELSE([AC_LANG_PROGRAM([[#include ]], [[ struct stat st; st.st_mtim.tv_nsec = 1; -], -ac_cv_stat_tv_nsec=yes, -ac_cv_stat_tv_nsec=no, -ac_cv_stat_tv_nsec=no)) +]])], +[ac_cv_stat_tv_nsec=yes], +[ac_cv_stat_tv_nsec=no])) AC_MSG_RESULT($ac_cv_stat_tv_nsec) if test "$ac_cv_stat_tv_nsec" = yes then @@ -3862,13 +3927,12 @@ # Look for BSD style subsecond timestamps in struct stat AC_MSG_CHECKING(for tv_nsec2 in struct stat) AC_CACHE_VAL(ac_cv_stat_tv_nsec2, -AC_TRY_COMPILE([#include ], [ +AC_COMPILE_IFELSE([AC_LANG_PROGRAM([[#include ]], [[ struct stat st; st.st_mtimespec.tv_nsec = 1; -], -ac_cv_stat_tv_nsec2=yes, -ac_cv_stat_tv_nsec2=no, -ac_cv_stat_tv_nsec2=no)) +]])], +[ac_cv_stat_tv_nsec2=yes], +[ac_cv_stat_tv_nsec2=no])) AC_MSG_RESULT($ac_cv_stat_tv_nsec2) if test "$ac_cv_stat_tv_nsec2" = yes then @@ -3879,12 +3943,12 @@ # On HP/UX 11.0, mvwdelch is a block with a return statement AC_MSG_CHECKING(whether mvwdelch is an expression) AC_CACHE_VAL(ac_cv_mvwdelch_is_expression, -AC_TRY_COMPILE([#include ], [ +AC_COMPILE_IFELSE([AC_LANG_PROGRAM([[#include ]], [[ int rtn; rtn = mvwdelch(0,0,0); -], ac_cv_mvwdelch_is_expression=yes, - ac_cv_mvwdelch_is_expression=no, - ac_cv_mvwdelch_is_expression=yes)) +]])], +[ac_cv_mvwdelch_is_expression=yes], +[ac_cv_mvwdelch_is_expression=no])) AC_MSG_RESULT($ac_cv_mvwdelch_is_expression) if test "$ac_cv_mvwdelch_is_expression" = yes @@ -3895,12 +3959,12 @@ AC_MSG_CHECKING(whether WINDOW has _flags) AC_CACHE_VAL(ac_cv_window_has_flags, -AC_TRY_COMPILE([#include ], [ +AC_COMPILE_IFELSE([AC_LANG_PROGRAM([[#include ]], [[ WINDOW *w; w->_flags = 0; -], ac_cv_window_has_flags=yes, - ac_cv_window_has_flags=no, - ac_cv_window_has_flags=no)) +]])], +[ac_cv_window_has_flags=yes], +[ac_cv_window_has_flags=no])) AC_MSG_RESULT($ac_cv_window_has_flags) @@ -3911,24 +3975,24 @@ fi AC_MSG_CHECKING(for is_term_resized) -AC_TRY_COMPILE([#include ], void *x=is_term_resized, - AC_DEFINE(HAVE_CURSES_IS_TERM_RESIZED, 1, Define if you have the 'is_term_resized' function.) - AC_MSG_RESULT(yes), - AC_MSG_RESULT(no) +AC_COMPILE_IFELSE([AC_LANG_PROGRAM([[#include ]], [[void *x=is_term_resized]])], + [AC_DEFINE(HAVE_CURSES_IS_TERM_RESIZED, 1, Define if you have the 'is_term_resized' function.) + AC_MSG_RESULT(yes)], + [AC_MSG_RESULT(no)] ) AC_MSG_CHECKING(for resize_term) -AC_TRY_COMPILE([#include ], void *x=resize_term, - AC_DEFINE(HAVE_CURSES_RESIZE_TERM, 1, Define if you have the 'resize_term' function.) - AC_MSG_RESULT(yes), - AC_MSG_RESULT(no) +AC_COMPILE_IFELSE([AC_LANG_PROGRAM([[#include ]], [[void *x=resize_term]])], + [AC_DEFINE(HAVE_CURSES_RESIZE_TERM, 1, Define if you have the 'resize_term' function.) + AC_MSG_RESULT(yes)], + [AC_MSG_RESULT(no)] ) AC_MSG_CHECKING(for resizeterm) -AC_TRY_COMPILE([#include ], void *x=resizeterm, - AC_DEFINE(HAVE_CURSES_RESIZETERM, 1, Define if you have the 'resizeterm' function.) - AC_MSG_RESULT(yes), - AC_MSG_RESULT(no) +AC_COMPILE_IFELSE([AC_LANG_PROGRAM([[#include ]], [[void *x=resizeterm]])], + [AC_DEFINE(HAVE_CURSES_RESIZETERM, 1, Define if you have the 'resizeterm' function.) + AC_MSG_RESULT(yes)], + [AC_MSG_RESULT(no)] ) AC_MSG_CHECKING(for /dev/ptmx) @@ -3957,7 +4021,7 @@ then AC_MSG_CHECKING(for %lld and %llu printf() format support) AC_CACHE_VAL(ac_cv_have_long_long_format, - AC_TRY_RUN([[ + AC_RUN_IFELSE([AC_LANG_SOURCE([[[ #include #include #include @@ -3987,9 +4051,10 @@ return 0; } - ]], ac_cv_have_long_long_format=yes, - ac_cv_have_long_long_format=no, - ac_cv_have_long_long_format=no) + ]]])], + [ac_cv_have_long_long_format=yes], + [ac_cv_have_long_long_format=no], + [ac_cv_have_long_long_format=no]) ) AC_MSG_RESULT($ac_cv_have_long_long_format) fi @@ -4006,7 +4071,7 @@ fi AC_CACHE_CHECK([for %zd printf() format support], ac_cv_have_size_t_format, [dnl -AC_TRY_RUN([ +AC_RUN_IFELSE([AC_LANG_SOURCE([[ #include #include #include @@ -4041,10 +4106,11 @@ return 0; } -], ac_cv_have_size_t_format=yes, - ac_cv_have_size_t_format=no, - [ac_cv_have_size_t_format="cross -- assuming yes"] -)]) +]])], + [ac_cv_have_size_t_format=yes], + [ac_cv_have_size_t_format=no], + [ac_cv_have_size_t_format="cross -- assuming yes" +])]) if test "$ac_cv_have_size_t_format" != no ; then AC_DEFINE(PY_FORMAT_SIZE_T, "z", [Define to printf format modifier for Py_ssize_t]) @@ -4052,7 +4118,7 @@ AC_CHECK_TYPE(socklen_t,, AC_DEFINE(socklen_t,int, - Define to `int' if does not define.),[ + [Define to `int' if does not define.]),[ #ifdef HAVE_SYS_TYPES_H #include #endif @@ -4063,7 +4129,7 @@ AC_MSG_CHECKING(for broken mbstowcs) AC_CACHE_VAL(ac_cv_broken_mbstowcs, -AC_TRY_RUN([ +AC_RUN_IFELSE([AC_LANG_SOURCE([[ #include int main() { size_t len = -1; @@ -4071,10 +4137,10 @@ len = mbstowcs(NULL, str, 0); return (len != 4); } -], -ac_cv_broken_mbstowcs=no, -ac_cv_broken_mbstowcs=yes, -ac_cv_broken_mbstowcs=no)) +]])], +[ac_cv_broken_mbstowcs=no], +[ac_cv_broken_mbstowcs=yes], +[ac_cv_broken_mbstowcs=no])) AC_MSG_RESULT($ac_cv_broken_mbstowcs) if test "$ac_cv_broken_mbstowcs" = yes then @@ -4086,8 +4152,8 @@ # Check for --with-computed-gotos AC_MSG_CHECKING(for --with-computed-gotos) AC_ARG_WITH(computed-gotos, - AC_HELP_STRING(--with-computed-gotos, - Use computed gotos / threaded dispatch in evaluation loop (not available on all compilers)), + AS_HELP_STRING([--with-computed-gotos], + [Use computed gotos / threaded dispatch in evaluation loop (not available on all compilers)]), [ if test "$withval" != no then @@ -4099,6 +4165,13 @@ [AC_MSG_RESULT(no)]) + +case $ac_sys_system in + OSF*) AC_MSG_ERROR(OSF* systems are deprecated unless somebody volunteers. Check http://bugs.python.org/issue8606) ;; +esac + + + AC_SUBST(THREADHEADERS) for h in `(cd $srcdir;echo Python/thread_*.h)` Modified: python/branches/py3k-jit/pyconfig.h.in ============================================================================== --- python/branches/py3k-jit/pyconfig.h.in (original) +++ python/branches/py3k-jit/pyconfig.h.in Tue May 4 01:24:51 2010 @@ -5,6 +5,9 @@ #define Py_PYCONFIG_H +/* Define if building universal (internal helper macro) */ +#undef AC_APPLE_UNIVERSAL_BUILD + /* Define for AIX if your compiler is a genuine IBM xlC/xlC_r and you want support for AIX C++ shared extension modules. */ #undef AIX_GENUINE_CPLUSPLUS @@ -675,25 +678,25 @@ /* Define to 1 if you have the header file. */ #undef HAVE_STROPTS_H -/* Define to 1 if `st_birthtime' is member of `struct stat'. */ +/* Define to 1 if `st_birthtime' is a member of `struct stat'. */ #undef HAVE_STRUCT_STAT_ST_BIRTHTIME -/* Define to 1 if `st_blksize' is member of `struct stat'. */ +/* Define to 1 if `st_blksize' is a member of `struct stat'. */ #undef HAVE_STRUCT_STAT_ST_BLKSIZE -/* Define to 1 if `st_blocks' is member of `struct stat'. */ +/* Define to 1 if `st_blocks' is a member of `struct stat'. */ #undef HAVE_STRUCT_STAT_ST_BLOCKS -/* Define to 1 if `st_flags' is member of `struct stat'. */ +/* Define to 1 if `st_flags' is a member of `struct stat'. */ #undef HAVE_STRUCT_STAT_ST_FLAGS -/* Define to 1 if `st_gen' is member of `struct stat'. */ +/* Define to 1 if `st_gen' is a member of `struct stat'. */ #undef HAVE_STRUCT_STAT_ST_GEN -/* Define to 1 if `st_rdev' is member of `struct stat'. */ +/* Define to 1 if `st_rdev' is a member of `struct stat'. */ #undef HAVE_STRUCT_STAT_ST_RDEV -/* Define to 1 if `tm_zone' is member of `struct tm'. */ +/* Define to 1 if `tm_zone' is a member of `struct tm'. */ #undef HAVE_STRUCT_TM_TM_ZONE /* Define to 1 if your `struct stat' has `st_blocks'. Deprecated, use @@ -922,6 +925,9 @@ /* Define to the one symbol short name of this package. */ #undef PACKAGE_TARNAME +/* Define to the home page for this package. */ +#undef PACKAGE_URL + /* Define to the version of this package. */ #undef PACKAGE_VERSION @@ -952,7 +958,7 @@ /* Define as the size of the unicode type. */ #undef Py_UNICODE_SIZE -/* Define as the return type of signal handlers (`int' or `void'). */ +/* assume C89 semantics that RETSIGTYPE is always void */ #undef RETSIGTYPE /* Define if setpgrp() must be called as setpgrp(0, 0). */ @@ -1034,6 +1040,28 @@ /* Define if you want to use computed gotos in ceval.c. */ #undef USE_COMPUTED_GOTOS +/* Enable extensions on AIX 3, Interix. */ +#ifndef _ALL_SOURCE +# undef _ALL_SOURCE +#endif +/* Enable GNU extensions on systems that have them. */ +#ifndef _GNU_SOURCE +# undef _GNU_SOURCE +#endif +/* Enable threading extensions on Solaris. */ +#ifndef _POSIX_PTHREAD_SEMANTICS +# undef _POSIX_PTHREAD_SEMANTICS +#endif +/* Enable extensions on HP NonStop. */ +#ifndef _TANDEM_SOURCE +# undef _TANDEM_SOURCE +#endif +/* Enable general extensions on Solaris. */ +#ifndef __EXTENSIONS__ +# undef __EXTENSIONS__ +#endif + + /* Define if a va_list is an array of some kind */ #undef VA_LIST_IS_ARRAY @@ -1074,20 +1102,21 @@ /* Define if you want pymalloc to be disabled when running under valgrind */ #undef WITH_VALGRIND -/* Define to 1 if your processor stores words with the most significant byte - first (like Motorola and SPARC, unlike Intel and VAX). */ -#undef WORDS_BIGENDIAN +/* Define WORDS_BIGENDIAN to 1 if your processor stores words with the most + significant byte first (like Motorola and SPARC, unlike Intel). */ +#if defined AC_APPLE_UNIVERSAL_BUILD +# if defined __BIG_ENDIAN__ +# define WORDS_BIGENDIAN 1 +# endif +#else +# ifndef WORDS_BIGENDIAN +# undef WORDS_BIGENDIAN +# endif +#endif /* Define if arithmetic is subject to x87-style double rounding issue */ #undef X87_DOUBLE_ROUNDING -/* Define to 1 if on AIX 3. - System headers sometimes define this. - We just want to avoid a redefinition error message. */ -#ifndef _ALL_SOURCE -# undef _ALL_SOURCE -#endif - /* Define on OpenBSD to activate all library features */ #undef _BSD_SOURCE @@ -1106,15 +1135,25 @@ /* This must be defined on some systems to enable large file support. */ #undef _LARGEFILE_SOURCE +/* Define to 1 if on MINIX. */ +#undef _MINIX + /* Define on NetBSD to activate all library features */ #undef _NETBSD_SOURCE /* Define _OSF_SOURCE to get the makedev macro. */ #undef _OSF_SOURCE +/* Define to 2 if the system does not provide POSIX.1 features except with + this defined. */ +#undef _POSIX_1_SOURCE + /* Define to activate features from IEEE Stds 1003.1-2001 */ #undef _POSIX_C_SOURCE +/* Define to 1 if you need to in order for `stat' and other things to work. */ +#undef _POSIX_SOURCE + /* Define if you have POSIX threads, and your system does not define that. */ #undef _POSIX_THREADS @@ -1122,12 +1161,12 @@ #undef _REENTRANT /* Define for Solaris 2.5.1 so the uint32_t typedef from , - , or is not used. If the typedef was allowed, the + , or is not used. If the typedef were allowed, the #define below would cause a syntax error. */ #undef _UINT32_T /* Define for Solaris 2.5.1 so the uint64_t typedef from , - , or is not used. If the typedef was allowed, the + , or is not used. If the typedef were allowed, the #define below would cause a syntax error. */ #undef _UINT64_T @@ -1145,9 +1184,6 @@ # undef __CHAR_UNSIGNED__ #endif -/* Defined on Solaris to see additional function prototypes. */ -#undef __EXTENSIONS__ - /* Define to 'long' if doesn't define. */ #undef clock_t From python-checkins at python.org Tue May 4 01:41:23 2010 From: python-checkins at python.org (brett.cannon) Date: Tue, 4 May 2010 01:41:23 +0200 (CEST) Subject: [Python-checkins] r80731 - python/trunk/Modules/_ssl.c Message-ID: <20100503234123.E3672C907@mail.python.org> Author: brett.cannon Date: Tue May 4 01:41:23 2010 New Revision: 80731 Log: Remove unneeded variable initialization. Found using Clang's static analyzer. Modified: python/trunk/Modules/_ssl.c Modified: python/trunk/Modules/_ssl.c ============================================================================== --- python/trunk/Modules/_ssl.c (original) +++ python/trunk/Modules/_ssl.c Tue May 4 01:41:23 2010 @@ -464,7 +464,6 @@ /* Actually negotiate SSL connection */ /* XXX If SSL_do_handshake() returns 0, it's also a failure. */ - sockstate = 0; do { PySSL_BEGIN_ALLOW_THREADS ret = SSL_do_handshake(self->ssl); @@ -1198,7 +1197,6 @@ goto error; } do { - err = 0; PySSL_BEGIN_ALLOW_THREADS len = SSL_write(self->ssl, buf.buf, buf.len); err = SSL_get_error(self->ssl, len); @@ -1317,7 +1315,6 @@ } } do { - err = 0; PySSL_BEGIN_ALLOW_THREADS count = SSL_read(self->ssl, PyString_AsString(buf), len); err = SSL_get_error(self->ssl, count); From python-checkins at python.org Tue May 4 01:41:51 2010 From: python-checkins at python.org (brett.cannon) Date: Tue, 4 May 2010 01:41:51 +0200 (CEST) Subject: [Python-checkins] r80732 - python/trunk/Modules/_tkinter.c Message-ID: <20100503234151.A818AC907@mail.python.org> Author: brett.cannon Date: Tue May 4 01:41:51 2010 New Revision: 80732 Log: Remove an unused variable. Found using Clang's static analyzer. Modified: python/trunk/Modules/_tkinter.c Modified: python/trunk/Modules/_tkinter.c ============================================================================== --- python/trunk/Modules/_tkinter.c (original) +++ python/trunk/Modules/_tkinter.c Tue May 4 01:41:51 2010 @@ -2049,7 +2049,7 @@ PythonCmd(ClientData clientData, Tcl_Interp *interp, int argc, char *argv[]) { PythonCmd_ClientData *data = (PythonCmd_ClientData *)clientData; - PyObject *self, *func, *arg, *res; + PyObject *func, *arg, *res; int i, rv; Tcl_Obj *obj_res; @@ -2058,7 +2058,6 @@ /* TBD: no error checking here since we know, via the * Tkapp_CreateCommand() that the client data is a two-tuple */ - self = data->self; func = data->func; /* Create argument list (argv1, ..., argvN) */ From python-checkins at python.org Tue May 4 01:42:41 2010 From: python-checkins at python.org (brett.cannon) Date: Tue, 4 May 2010 01:42:41 +0200 (CEST) Subject: [Python-checkins] r80733 - python/trunk/Modules/audioop.c Message-ID: <20100503234241.24F68C907@mail.python.org> Author: brett.cannon Date: Tue May 4 01:42:40 2010 New Revision: 80733 Log: Clean up whitespace and remove unneeded variable initialization as found by Clang. Modified: python/trunk/Modules/audioop.c Modified: python/trunk/Modules/audioop.c ============================================================================== --- python/trunk/Modules/audioop.c (original) +++ python/trunk/Modules/audioop.c Tue May 4 01:42:40 2010 @@ -286,7 +286,7 @@ 5894, 6484, 7132, 7845, 8630, 9493, 10442, 11487, 12635, 13899, 15289, 16818, 18500, 20350, 22385, 24623, 27086, 29794, 32767 }; - + #define CHARP(cp, i) ((signed char *)(cp+i)) #define SHORTP(cp, i) ((short *)(cp+i)) #define LONGP(cp, i) ((Py_Int32 *)(cp+i)) @@ -485,7 +485,7 @@ } len1 >>= 1; len2 >>= 1; - + if ( len1 < len2 ) { PyErr_SetString(AudioopError, "First sample should be longer"); return 0; @@ -498,9 +498,8 @@ best_result = result; best_j = 0; - j = 0; - for ( j=1; j<=len1-len2; j++) { + for (j=1; j<=len1-len2; j++) { aj_m1 = (double)cp1[j-1]; aj_lm1 = (double)cp1[j+len2-1]; @@ -514,11 +513,11 @@ best_result = result; best_j = j; } - + } factor = _sum2(cp1+best_j, cp2, len2) / sum_ri_2; - + return Py_BuildValue("(if)", best_j, factor); } @@ -566,7 +565,7 @@ double aj_m1, aj_lm1; double result, best_result; - if ( !PyArg_ParseTuple(args, "s#i:findmax", + if ( !PyArg_ParseTuple(args, "s#i:findmax", (char**)&cp1, &len1, &len2) ) return 0; if ( len1 & 1 ) { @@ -574,7 +573,7 @@ return 0; } len1 >>= 1; - + if ( len2 < 0 || len1 < len2 ) { PyErr_SetString(AudioopError, "Input sample should be longer"); return 0; @@ -584,9 +583,8 @@ best_result = result; best_j = 0; - j = 0; - for ( j=1; j<=len1-len2; j++) { + for (j=1; j<=len1-len2; j++) { aj_m1 = (double)cp1[j-1]; aj_lm1 = (double)cp1[j+len2-1]; @@ -596,7 +594,7 @@ best_result = result; best_j = j; } - + } return PyInt_FromLong(best_j); @@ -628,7 +626,7 @@ else if ( size == 2 ) val = (int)*SHORTP(cp, size); else if ( size == 4 ) val = (int)*LONGP(cp, size); prevdiff = val - prevval; - + for ( i=size; i> 16; j = len - i - size; - + if ( size == 1 ) *CHARP(ncp, j) = (signed char)(val >> 8); else if ( size == 2 ) *SHORTP(ncp, j) = (short)(val); else if ( size == 4 ) *LONGP(ncp, j) = (Py_Int32)(val<<16); @@ -1029,7 +1027,7 @@ PyErr_SetString(AudioopError, "Size should be 1, 2 or 4"); return 0; } - + new_len = (len/size)*size2; if (new_len < 0) { PyErr_SetString(PyExc_MemoryError, @@ -1040,7 +1038,7 @@ if ( rv == 0 ) return 0; ncp = (unsigned char *)PyString_AsString(rv); - + for ( i=0, j=0; i < len; i += size, j += size2 ) { if ( size == 1 ) val = ((int)*CHARP(cp, i)) << 8; else if ( size == 2 ) val = (int)*SHORTP(cp, i); @@ -1147,7 +1145,7 @@ } for (chan = 0; chan < nchannels; chan++) { if (!PyArg_ParseTuple(PyTuple_GetItem(samps, chan), - "ii:ratecv", &prev_i[chan], + "ii:ratecv", &prev_i[chan], &cur_i[chan])) goto exit; } @@ -1274,12 +1272,12 @@ PyErr_SetString(AudioopError, "Size should be 1, 2 or 4"); return 0; } - + rv = PyString_FromStringAndSize(NULL, len/size); if ( rv == 0 ) return 0; ncp = (unsigned char *)PyString_AsString(rv); - + for ( i=0; i < len; i += size ) { if ( size == 1 ) val = ((int)*CHARP(cp, i)) << 8; else if ( size == 2 ) val = (int)*SHORTP(cp, i); @@ -1308,7 +1306,7 @@ PyErr_SetString(AudioopError, "Size should be 1, 2 or 4"); return 0; } - + new_len = len*size; if (new_len < 0) { PyErr_SetString(PyExc_MemoryError, @@ -1319,11 +1317,11 @@ if ( rv == 0 ) return 0; ncp = (signed char *)PyString_AsString(rv); - + for ( i=0; i < new_len; i += size ) { cval = *cp++; val = st_ulaw2linear16(cval); - + if ( size == 1 ) *CHARP(ncp, i) = (signed char)(val >> 8); else if ( size == 2 ) *SHORTP(ncp, i) = (short)(val); else if ( size == 4 ) *LONGP(ncp, i) = (Py_Int32)(val<<16); @@ -1348,12 +1346,12 @@ PyErr_SetString(AudioopError, "Size should be 1, 2 or 4"); return 0; } - + rv = PyString_FromStringAndSize(NULL, len/size); if ( rv == 0 ) return 0; ncp = (unsigned char *)PyString_AsString(rv); - + for ( i=0; i < len; i += size ) { if ( size == 1 ) val = ((int)*CHARP(cp, i)) << 8; else if ( size == 2 ) val = (int)*SHORTP(cp, i); @@ -1382,7 +1380,7 @@ PyErr_SetString(AudioopError, "Size should be 1, 2 or 4"); return 0; } - + new_len = len*size; if (new_len < 0) { PyErr_SetString(PyExc_MemoryError, @@ -1393,11 +1391,11 @@ if ( rv == 0 ) return 0; ncp = (signed char *)PyString_AsString(rv); - + for ( i=0; i < new_len; i += size ) { cval = *cp++; val = st_alaw2linear16(cval); - + if ( size == 1 ) *CHARP(ncp, i) = (signed char)(val >> 8); else if ( size == 2 ) *SHORTP(ncp, i) = (short)(val); else if ( size == 4 ) *LONGP(ncp, i) = (Py_Int32)(val<<16); @@ -1418,13 +1416,13 @@ if ( !PyArg_ParseTuple(args, "s#iO:lin2adpcm", &cp, &len, &size, &state) ) return 0; - + if ( size != 1 && size != 2 && size != 4) { PyErr_SetString(AudioopError, "Size should be 1, 2 or 4"); return 0; } - + str = PyString_FromStringAndSize(NULL, len/(size*2)); if ( str == 0 ) return 0; @@ -1434,7 +1432,6 @@ if ( state == Py_None ) { /* First time, it seems. Set defaults */ valpred = 0; - step = 7; index = 0; } else if ( !PyArg_ParseTuple(state, "ii", &valpred, &index) ) return 0; @@ -1463,7 +1460,7 @@ */ delta = 0; vpdiff = (step >> 3); - + if ( diff >= step ) { delta = 4; diff -= step; @@ -1495,7 +1492,7 @@ /* Step 5 - Assemble value, update index and step values */ delta |= sign; - + index += indexTable[delta]; if ( index < 0 ) index = 0; if ( index > 88 ) index = 88; @@ -1531,16 +1528,15 @@ PyErr_SetString(AudioopError, "Size should be 1, 2 or 4"); return 0; } - + /* Decode state, should have (value, step) */ if ( state == Py_None ) { /* First time, it seems. Set defaults */ valpred = 0; - step = 7; index = 0; } else if ( !PyArg_ParseTuple(state, "ii", &valpred, &index) ) return 0; - + new_len = len*size*2; if (new_len < 0) { PyErr_SetString(PyExc_MemoryError, @@ -1554,7 +1550,7 @@ step = stepsizeTable[index]; bufferstep = 0; - + for ( i=0; i < new_len; i += size ) { /* Step 1 - get the delta value and compute next index */ if ( bufferstep ) { From python-checkins at python.org Tue May 4 01:43:49 2010 From: python-checkins at python.org (brett.cannon) Date: Tue, 4 May 2010 01:43:49 +0200 (CEST) Subject: [Python-checkins] r80734 - python/trunk/Modules/_json.c Message-ID: <20100503234349.929C5E4F3@mail.python.org> Author: brett.cannon Date: Tue May 4 01:43:49 2010 New Revision: 80734 Log: Remove unneeded variable mutation and initializations. Found using Clang's static analyzer. Modified: python/trunk/Modules/_json.c Modified: python/trunk/Modules/_json.c ============================================================================== --- python/trunk/Modules/_json.c (original) +++ python/trunk/Modules/_json.c Tue May 4 01:43:49 2010 @@ -439,7 +439,7 @@ PyObject *rval; Py_ssize_t len = PyString_GET_SIZE(pystr); Py_ssize_t begin = end - 1; - Py_ssize_t next = begin; + Py_ssize_t next; int has_unicode = 0; char *buf = PyString_AS_STRING(pystr); PyObject *chunks = PyList_New(0); @@ -644,7 +644,7 @@ PyObject *rval; Py_ssize_t len = PyUnicode_GET_SIZE(pystr); Py_ssize_t begin = end - 1; - Py_ssize_t next = begin; + Py_ssize_t next; const Py_UNICODE *buf = PyUnicode_AS_UNICODE(pystr); PyObject *chunks = PyList_New(0); if (chunks == NULL) { @@ -2178,8 +2178,9 @@ } if (s->indent != Py_None) { /* TODO: DOES NOT RUN */ - indent_level -= 1; /* + indent_level -= 1; + yield '\n' + (' ' * (_indent * _current_indent_level)) */ } @@ -2268,8 +2269,9 @@ } if (s->indent != Py_None) { /* TODO: DOES NOT RUN */ - indent_level -= 1; /* + indent_level -= 1; + yield '\n' + (' ' * (_indent * _current_indent_level)) */ } From python-checkins at python.org Tue May 4 01:44:54 2010 From: python-checkins at python.org (brett.cannon) Date: Tue, 4 May 2010 01:44:54 +0200 (CEST) Subject: [Python-checkins] r80735 - python/trunk/Modules/_bisectmodule.c Message-ID: <20100503234454.5EA1EE4F3@mail.python.org> Author: brett.cannon Date: Tue May 4 01:44:54 2010 New Revision: 80735 Log: Remove unneeded variable assignment. Found using Clang's static analyzer. Modified: python/trunk/Modules/_bisectmodule.c Modified: python/trunk/Modules/_bisectmodule.c ============================================================================== --- python/trunk/Modules/_bisectmodule.c (original) +++ python/trunk/Modules/_bisectmodule.c Tue May 4 01:44:54 2010 @@ -237,7 +237,5 @@ PyMODINIT_FUNC init_bisect(void) { - PyObject *m; - - m = Py_InitModule3("_bisect", bisect_methods, module_doc); + Py_InitModule3("_bisect", bisect_methods, module_doc); } From python-checkins at python.org Tue May 4 01:51:29 2010 From: python-checkins at python.org (brett.cannon) Date: Tue, 4 May 2010 01:51:29 +0200 (CEST) Subject: [Python-checkins] r80736 - python/trunk/Modules/_sre.c Message-ID: <20100503235129.15558F70B@mail.python.org> Author: brett.cannon Date: Tue May 4 01:51:28 2010 New Revision: 80736 Log: Remove unused variables and a variable initialization. Found using Clang's static analyzer. Modified: python/trunk/Modules/_sre.c Modified: python/trunk/Modules/_sre.c ============================================================================== --- python/trunk/Modules/_sre.c (original) +++ python/trunk/Modules/_sre.c Tue May 4 01:51:28 2010 @@ -1686,7 +1686,7 @@ if (PyUnicode_Check(string)) { /* unicode strings doesn't always support the buffer interface */ ptr = (void*) PyUnicode_AS_DATA(string); - bytes = PyUnicode_GET_DATA_SIZE(string); + /* bytes = PyUnicode_GET_DATA_SIZE(string); */ size = PyUnicode_GET_SIZE(string); charsize = sizeof(Py_UNICODE); @@ -2967,13 +2967,13 @@ <1=skip> <2=flags> <3=min> <4=max>; If SRE_INFO_PREFIX or SRE_INFO_CHARSET is in the flags, more follows. */ - SRE_CODE flags, min, max, i; + SRE_CODE flags, i; SRE_CODE *newcode; GET_SKIP; newcode = code+skip-1; GET_ARG; flags = arg; - GET_ARG; min = arg; - GET_ARG; max = arg; + GET_ARG; /* min */ + GET_ARG; /* max */ /* Check that only valid flags are present */ if ((flags & ~(SRE_INFO_PREFIX | SRE_INFO_LITERAL | @@ -2989,9 +2989,9 @@ FAIL; /* Validate the prefix */ if (flags & SRE_INFO_PREFIX) { - SRE_CODE prefix_len, prefix_skip; + SRE_CODE prefix_len; GET_ARG; prefix_len = arg; - GET_ARG; prefix_skip = arg; + GET_ARG; /* prefix skip */ /* Here comes the prefix string */ if (code+prefix_len < code || code+prefix_len > newcode) FAIL; From python-checkins at python.org Tue May 4 01:57:15 2010 From: python-checkins at python.org (brett.cannon) Date: Tue, 4 May 2010 01:57:15 +0200 (CEST) Subject: [Python-checkins] r80737 - python/trunk/Modules/bsddbmodule.c Message-ID: <20100503235715.B05D6C8D8@mail.python.org> Author: brett.cannon Date: Tue May 4 01:57:15 2010 New Revision: 80737 Log: Fix two potential uninitialization errors and an unneeded assignment. Found using Clang's static analyzer. Modified: python/trunk/Modules/bsddbmodule.c Modified: python/trunk/Modules/bsddbmodule.c ============================================================================== --- python/trunk/Modules/bsddbmodule.c (original) +++ python/trunk/Modules/bsddbmodule.c Tue May 4 01:57:15 2010 @@ -270,11 +270,12 @@ { int status; DBT krec, drec; - char *data,buf[4096]; + char *data = NULL; + char buf[4096]; int size; PyObject *result; recno_t recno; - + if (dp->di_type == DB_RECNO) { if (!PyArg_Parse(key, "i", &recno)) { PyErr_SetString(PyExc_TypeError, @@ -503,7 +504,8 @@ { int status; DBT krec, drec; - char *data,buf[4096]; + char *data = NULL; + char buf[4096]; int size; PyObject *result; recno_t recno; @@ -635,7 +637,7 @@ PyErr_SetFromErrno(BsddbError); return NULL; } - return PyInt_FromLong(status = 0); + return PyInt_FromLong(0); } static PyMethodDef bsddb_methods[] = { {"close", (PyCFunction)bsddb_close, METH_NOARGS}, From python-checkins at python.org Tue May 4 02:30:17 2010 From: python-checkins at python.org (brett.cannon) Date: Tue, 4 May 2010 02:30:17 +0200 (CEST) Subject: [Python-checkins] r80738 - python/trunk/Modules/cPickle.c Message-ID: <20100504003017.EC15AFCCB@mail.python.org> Author: brett.cannon Date: Tue May 4 02:30:17 2010 New Revision: 80738 Log: Remove a redundant string length check and variable assignment. Found with Clang's static analyzer. Modified: python/trunk/Modules/cPickle.c Modified: python/trunk/Modules/cPickle.c ============================================================================== --- python/trunk/Modules/cPickle.c (original) +++ python/trunk/Modules/cPickle.c Tue May 4 02:30:17 2010 @@ -864,7 +864,7 @@ *global_name_attr = 0, *name = 0; module = PyObject_GetAttrString(global, "__module__"); - if (module) + if (module) return module; if (PyErr_ExceptionMatches(PyExc_AttributeError)) PyErr_Clear(); @@ -903,7 +903,6 @@ like this rule. jlf */ if (!j) { - j=1; name=__main___str; } @@ -1235,9 +1234,6 @@ int i; char c_str[5]; - if ((size = PyString_Size(args)) < 0) - return -1; - if (size < 256) { c_str[0] = SHORT_BINSTRING; c_str[1] = size; From python-checkins at python.org Tue May 4 02:36:00 2010 From: python-checkins at python.org (brett.cannon) Date: Tue, 4 May 2010 02:36:00 +0200 (CEST) Subject: [Python-checkins] r80739 - python/trunk/Modules/datetimemodule.c Message-ID: <20100504003600.2E693DEE0@mail.python.org> Author: brett.cannon Date: Tue May 4 02:36:00 2010 New Revision: 80739 Log: Prevent a possible NULL de-reference and an unneeded variable assignment. Found using Clang's static analyzer. Modified: python/trunk/Modules/datetimemodule.c Modified: python/trunk/Modules/datetimemodule.c ============================================================================== --- python/trunk/Modules/datetimemodule.c (original) +++ python/trunk/Modules/datetimemodule.c Tue May 4 02:36:00 2010 @@ -1520,7 +1520,7 @@ goto Done; Py_DECREF(x1); Py_DECREF(x2); - x1 = x2 = NULL; + x2 = NULL; /* x3 has days+seconds in seconds */ x1 = PyNumber_Multiply(x3, us_per_second); /* us */ @@ -3952,7 +3952,7 @@ else good_timetuple = 0; /* follow that up with a little dose of microseconds */ - if (PyInt_Check(frac)) + if (good_timetuple && PyInt_Check(frac)) ia[6] = PyInt_AsLong(frac); else good_timetuple = 0; From python-checkins at python.org Tue May 4 02:36:36 2010 From: python-checkins at python.org (benjamin.peterson) Date: Tue, 4 May 2010 02:36:36 +0200 (CEST) Subject: [Python-checkins] r80740 - python/branches/py3k Message-ID: <20100504003636.3C650EA2A@mail.python.org> Author: benjamin.peterson Date: Tue May 4 02:36:36 2010 New Revision: 80740 Log: Blocked revisions 80738 via svnmerge ........ r80738 | brett.cannon | 2010-05-03 19:30:17 -0500 (Mon, 03 May 2010) | 4 lines Remove a redundant string length check and variable assignment. Found with Clang's static analyzer. ........ Modified: python/branches/py3k/ (props changed) From python-checkins at python.org Tue May 4 02:48:11 2010 From: python-checkins at python.org (brett.cannon) Date: Tue, 4 May 2010 02:48:11 +0200 (CEST) Subject: [Python-checkins] r80741 - python/trunk/Modules/pyexpat.c Message-ID: <20100504004811.3ACE6EB0D@mail.python.org> Author: brett.cannon Date: Tue May 4 02:48:11 2010 New Revision: 80741 Log: Fix a Py_DECREF to a Py_XDECREF. Found using Clang's static analyzer. Modified: python/trunk/Modules/pyexpat.c Modified: python/trunk/Modules/pyexpat.c ============================================================================== --- python/trunk/Modules/pyexpat.c (original) +++ python/trunk/Modules/pyexpat.c Tue May 4 02:48:11 2010 @@ -993,7 +993,7 @@ else { bytes_read = readinst(buf, BUF_SIZE, readmethod); if (bytes_read < 0) { - Py_DECREF(readmethod); + Py_XDECREF(readmethod); return NULL; } } From python-checkins at python.org Tue May 4 02:52:42 2010 From: python-checkins at python.org (brett.cannon) Date: Tue, 4 May 2010 02:52:42 +0200 (CEST) Subject: [Python-checkins] r80742 - python/trunk/Modules/readline.c Message-ID: <20100504005242.2B791E308@mail.python.org> Author: brett.cannon Date: Tue May 4 02:52:41 2010 New Revision: 80742 Log: Strip out extraneous whitespace, cast a some `const char *` to `void *` when passed to free() and make a `char *` to a `const char *` as found by Clang's static analyzer. Modified: python/trunk/Modules/readline.c Modified: python/trunk/Modules/readline.c ============================================================================== --- python/trunk/Modules/readline.c (original) +++ python/trunk/Modules/readline.c Tue May 4 02:52:41 2010 @@ -23,7 +23,7 @@ #ifdef SAVE_LOCALE # define RESTORE_LOCALE(sl) { setlocale(LC_CTYPE, sl); free(sl); } #else -# define RESTORE_LOCALE(sl) +# define RESTORE_LOCALE(sl) #endif /* GNU readline definitions */ @@ -48,13 +48,13 @@ #ifdef __APPLE__ /* * It is possible to link the readline module to the readline - * emulation library of editline/libedit. - * + * emulation library of editline/libedit. + * * On OSX this emulation library is not 100% API compatible * with the "real" readline and cannot be detected at compile-time, * hence we use a runtime check to detect if we're using libedit * - * Currently there is one know API incompatibility: + * Currently there is one know API incompatibility: * - 'get_history' has a 1-based index with GNU readline, and a 0-based * index with libedit's emulation. * - Note that replace_history and remove_history use a 0-based index @@ -378,7 +378,7 @@ } /* free memory allocated for the history entry */ if (entry->line) - free(entry->line); + free((void *)entry->line); if (entry->data) free(entry->data); free(entry); @@ -415,7 +415,7 @@ } /* free memory allocated for the old history entry */ if (old_entry->line) - free(old_entry->line); + free((void *)old_entry->line); if (old_entry->data) free(old_entry->data); free(old_entry); @@ -515,7 +515,7 @@ /* * Apple's readline emulation crashes when - * the index is out of range, therefore + * the index is out of range, therefore * test for that and fail gracefully. */ if (idx < 0 || idx >= hist_st->length) { @@ -682,7 +682,7 @@ result = 0; else { result = PyInt_AsLong(r); - if (result == -1 && PyErr_Occurred()) + if (result == -1 && PyErr_Occurred()) goto error; } Py_DECREF(r); @@ -740,7 +740,7 @@ "sOi", matches[0], m, max_length); Py_DECREF(m); m=NULL; - + if (r == NULL || (r != Py_None && PyInt_AsLong(r) == -1 && PyErr_Occurred())) { goto error; @@ -767,7 +767,7 @@ char *result = NULL; if (completer != NULL) { PyObject *r; -#ifdef WITH_THREAD +#ifdef WITH_THREAD PyGILState_STATE gilstate = PyGILState_Ensure(); #endif rl_attempted_completion_over = 1; @@ -789,7 +789,7 @@ PyErr_Clear(); Py_XDECREF(r); done: -#ifdef WITH_THREAD +#ifdef WITH_THREAD PyGILState_Release(gilstate); #endif return result; @@ -893,7 +893,7 @@ rl_callback_handler_install (prompt, rlhandler); FD_ZERO(&selectset); - + completed_input_string = not_done_reading; while (completed_input_string == not_done_reading) { @@ -902,10 +902,10 @@ while (!has_input) { struct timeval timeout = {0, 100000}; /* 0.1 seconds */ - /* [Bug #1552726] Only limit the pause if an input hook has been + /* [Bug #1552726] Only limit the pause if an input hook has been defined. */ struct timeval *timeoutp = NULL; - if (PyOS_InputHook) + if (PyOS_InputHook) timeoutp = &timeout; FD_SET(fileno(rl_instream), &selectset); /* select resets selectset if no input was available */ @@ -924,7 +924,7 @@ #endif s = PyErr_CheckSignals(); #ifdef WITH_THREAD - PyEval_SaveThread(); + PyEval_SaveThread(); #endif if (s < 0) { rl_free_line_state(); @@ -959,7 +959,7 @@ { PyOS_sighandler_t old_inthandler; char *p; - + *signal = 0; old_inthandler = PyOS_setsig(SIGINT, onintr); @@ -1004,7 +1004,7 @@ } p = readline_until_enter_or_signal(prompt, &signal); - + /* we got an interrupt signal */ if (signal) { RESTORE_LOCALE(saved_locale) @@ -1023,17 +1023,17 @@ /* we have a valid line */ n = strlen(p); if (n > 0) { - char *line; + const char *line; HISTORY_STATE *state = history_get_history_state(); if (state->length > 0) #ifdef __APPLE__ if (using_libedit_emulation) { - /* + /* * Libedit's emulation uses 0-based indexes, * the real readline uses 1-based indexes. */ line = history_get(state->length - 1)->line; - } else + } else #endif /* __APPLE__ */ line = history_get(state->length)->line; else @@ -1083,7 +1083,7 @@ using_libedit_emulation = 1; } - if (using_libedit_emulation) + if (using_libedit_emulation) m = Py_InitModule4("readline", readline_methods, doc_module_le, (PyObject *)NULL, PYTHON_API_VERSION); else From jackdied at gmail.com Tue May 4 02:55:58 2010 From: jackdied at gmail.com (Jack Diederich) Date: Mon, 3 May 2010 20:55:58 -0400 Subject: [Python-checkins] r80736 - python/trunk/Modules/_sre.c In-Reply-To: <20100503235129.15558F70B@mail.python.org> References: <20100503235129.15558F70B@mail.python.org> Message-ID: You commented out one line instead of yanking it. -Jack On Mon, May 3, 2010 at 7:51 PM, brett.cannon wrote: > Author: brett.cannon > Date: Tue May ?4 01:51:28 2010 > New Revision: 80736 > > Log: > Remove unused variables and a variable initialization. > > Found using Clang's static analyzer. > > > Modified: > ? python/trunk/Modules/_sre.c > > Modified: python/trunk/Modules/_sre.c > ============================================================================== > --- python/trunk/Modules/_sre.c (original) > +++ python/trunk/Modules/_sre.c Tue May ?4 01:51:28 2010 > @@ -1686,7 +1686,7 @@ > ? ? if (PyUnicode_Check(string)) { > ? ? ? ? /* unicode strings doesn't always support the buffer interface */ > ? ? ? ? ptr = (void*) PyUnicode_AS_DATA(string); > - ? ? ? ?bytes = PyUnicode_GET_DATA_SIZE(string); > + ? ? ? ?/* bytes = PyUnicode_GET_DATA_SIZE(string); */ > ? ? ? ? size = PyUnicode_GET_SIZE(string); > ? ? ? ? charsize = sizeof(Py_UNICODE); > > @@ -2967,13 +2967,13 @@ > ? ? ? ? ? ? ? ? ? ? <1=skip> <2=flags> <3=min> <4=max>; > ? ? ? ? ? ? ? ? ? ?If SRE_INFO_PREFIX or SRE_INFO_CHARSET is in the flags, > ? ? ? ? ? ? ? ? ? ?more follows. */ > - ? ? ? ? ? ? ? ?SRE_CODE flags, min, max, i; > + ? ? ? ? ? ? ? ?SRE_CODE flags, i; > ? ? ? ? ? ? ? ? SRE_CODE *newcode; > ? ? ? ? ? ? ? ? GET_SKIP; > ? ? ? ? ? ? ? ? newcode = code+skip-1; > ? ? ? ? ? ? ? ? GET_ARG; flags = arg; > - ? ? ? ? ? ? ? ?GET_ARG; min = arg; > - ? ? ? ? ? ? ? ?GET_ARG; max = arg; > + ? ? ? ? ? ? ? ?GET_ARG; /* min */ > + ? ? ? ? ? ? ? ?GET_ARG; /* max */ > ? ? ? ? ? ? ? ? /* Check that only valid flags are present */ > ? ? ? ? ? ? ? ? if ((flags & ~(SRE_INFO_PREFIX | > ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?SRE_INFO_LITERAL | > @@ -2989,9 +2989,9 @@ > ? ? ? ? ? ? ? ? ? ? FAIL; > ? ? ? ? ? ? ? ? /* Validate the prefix */ > ? ? ? ? ? ? ? ? if (flags & SRE_INFO_PREFIX) { > - ? ? ? ? ? ? ? ? ? ?SRE_CODE prefix_len, prefix_skip; > + ? ? ? ? ? ? ? ? ? ?SRE_CODE prefix_len; > ? ? ? ? ? ? ? ? ? ? GET_ARG; prefix_len = arg; > - ? ? ? ? ? ? ? ? ? ?GET_ARG; prefix_skip = arg; > + ? ? ? ? ? ? ? ? ? ?GET_ARG; /* prefix skip */ > ? ? ? ? ? ? ? ? ? ? /* Here comes the prefix string */ > ? ? ? ? ? ? ? ? ? ? if (code+prefix_len < code || code+prefix_len > newcode) > ? ? ? ? ? ? ? ? ? ? ? ? FAIL; > _______________________________________________ > Python-checkins mailing list > Python-checkins at python.org > http://mail.python.org/mailman/listinfo/python-checkins > From python-checkins at python.org Tue May 4 02:57:44 2010 From: python-checkins at python.org (brett.cannon) Date: Tue, 4 May 2010 02:57:44 +0200 (CEST) Subject: [Python-checkins] r80743 - python/trunk/Modules/socketmodule.c Message-ID: <20100504005744.3D73BE308@mail.python.org> Author: brett.cannon Date: Tue May 4 02:57:44 2010 New Revision: 80743 Log: Remove an unneeded variable assignment. Found using Clang's static analyzer. Modified: python/trunk/Modules/socketmodule.c Modified: python/trunk/Modules/socketmodule.c ============================================================================== --- python/trunk/Modules/socketmodule.c (original) +++ python/trunk/Modules/socketmodule.c Tue May 4 02:57:44 2010 @@ -3424,7 +3424,6 @@ return NULL; af = sa->sa_family; ap = NULL; - al = 0; switch (af) { case AF_INET: ap = (char *)&((struct sockaddr_in *)sa)->sin_addr; From brett at python.org Tue May 4 02:58:39 2010 From: brett at python.org (Brett Cannon) Date: Mon, 3 May 2010 17:58:39 -0700 Subject: [Python-checkins] r80736 - python/trunk/Modules/_sre.c In-Reply-To: References: <20100503235129.15558F70B@mail.python.org> Message-ID: On Mon, May 3, 2010 at 17:55, Jack Diederich wrote: > You commented out one line instead of yanking it. > > Did that on purpose to act as documentation for all the stuff that could have been pulled from the object. > -Jack > > On Mon, May 3, 2010 at 7:51 PM, brett.cannon > wrote: > > Author: brett.cannon > > Date: Tue May 4 01:51:28 2010 > > New Revision: 80736 > > > > Log: > > Remove unused variables and a variable initialization. > > > > Found using Clang's static analyzer. > > > > > > Modified: > > python/trunk/Modules/_sre.c > > > > Modified: python/trunk/Modules/_sre.c > > > ============================================================================== > > --- python/trunk/Modules/_sre.c (original) > > +++ python/trunk/Modules/_sre.c Tue May 4 01:51:28 2010 > > @@ -1686,7 +1686,7 @@ > > if (PyUnicode_Check(string)) { > > /* unicode strings doesn't always support the buffer interface */ > > ptr = (void*) PyUnicode_AS_DATA(string); > > - bytes = PyUnicode_GET_DATA_SIZE(string); > > + /* bytes = PyUnicode_GET_DATA_SIZE(string); */ > > size = PyUnicode_GET_SIZE(string); > > charsize = sizeof(Py_UNICODE); > > > > @@ -2967,13 +2967,13 @@ > > <1=skip> <2=flags> <3=min> <4=max>; > > If SRE_INFO_PREFIX or SRE_INFO_CHARSET is in the > flags, > > more follows. */ > > - SRE_CODE flags, min, max, i; > > + SRE_CODE flags, i; > > SRE_CODE *newcode; > > GET_SKIP; > > newcode = code+skip-1; > > GET_ARG; flags = arg; > > - GET_ARG; min = arg; > > - GET_ARG; max = arg; > > + GET_ARG; /* min */ > > + GET_ARG; /* max */ > > /* Check that only valid flags are present */ > > if ((flags & ~(SRE_INFO_PREFIX | > > SRE_INFO_LITERAL | > > @@ -2989,9 +2989,9 @@ > > FAIL; > > /* Validate the prefix */ > > if (flags & SRE_INFO_PREFIX) { > > - SRE_CODE prefix_len, prefix_skip; > > + SRE_CODE prefix_len; > > GET_ARG; prefix_len = arg; > > - GET_ARG; prefix_skip = arg; > > + GET_ARG; /* prefix skip */ > > /* Here comes the prefix string */ > > if (code+prefix_len < code || code+prefix_len > > newcode) > > FAIL; > > _______________________________________________ > > Python-checkins mailing list > > Python-checkins at python.org > > http://mail.python.org/mailman/listinfo/python-checkins > > > _______________________________________________ > Python-checkins mailing list > Python-checkins at python.org > http://mail.python.org/mailman/listinfo/python-checkins > -------------- next part -------------- An HTML attachment was scrubbed... URL: From python-checkins at python.org Tue May 4 03:01:01 2010 From: python-checkins at python.org (brett.cannon) Date: Tue, 4 May 2010 03:01:01 +0200 (CEST) Subject: [Python-checkins] r80744 - python/trunk/Modules/tkappinit.c Message-ID: <20100504010101.15DEAE784@mail.python.org> Author: brett.cannon Date: Tue May 4 03:01:00 2010 New Revision: 80744 Log: Fix some whitespace. Modified: python/trunk/Modules/tkappinit.c Modified: python/trunk/Modules/tkappinit.c ============================================================================== --- python/trunk/Modules/tkappinit.c (original) +++ python/trunk/Modules/tkappinit.c Tue May 4 03:01:00 2010 @@ -48,7 +48,7 @@ Tcl_SetVar(interp, "tclDefaultLibrary", tclLibPath, TCL_GLOBAL_ONLY); Tcl_SetVar(interp, "tcl_pkgPath", tclLibPath, TCL_GLOBAL_ONLY); } - + if (tclLibPath[0] != '\0') { Tcl_SetVar(interp, "tcl_library", tclLibPath, TCL_GLOBAL_ONLY); Tcl_SetVar(interp, "tclDefaultLibrary", tclLibPath, TCL_GLOBAL_ONLY); @@ -117,7 +117,7 @@ TkMacOSXInitAppleEvents(interp); TkMacOSXInitMenus(interp); #endif - + #ifdef WITH_MOREBUTTONS { extern Tcl_CmdProc studButtonCmd; From python-checkins at python.org Tue May 4 03:04:53 2010 From: python-checkins at python.org (brett.cannon) Date: Tue, 4 May 2010 03:04:53 +0200 (CEST) Subject: [Python-checkins] r80745 - python/trunk/Misc/NEWS Message-ID: <20100504010453.2618FEB68@mail.python.org> Author: brett.cannon Date: Tue May 4 03:04:53 2010 New Revision: 80745 Log: Mention the code clean-up thanks to Clang's static analyzer in Modules. Was not applied to modules that will not compile under OS X, dbmmodule.c, getaddrinfo.c, and getnameinfo.c. Modified: python/trunk/Misc/NEWS Modified: python/trunk/Misc/NEWS ============================================================================== --- python/trunk/Misc/NEWS (original) +++ python/trunk/Misc/NEWS Tue May 4 03:04:53 2010 @@ -141,6 +141,8 @@ Extension Modules ----------------- +- Use Clang 2.7's static analyzer to find places to clean up some code. + - Build the ossaudio extension on GNU/kFreeBSD. Tests From python-checkins at python.org Tue May 4 03:16:51 2010 From: python-checkins at python.org (brett.cannon) Date: Tue, 4 May 2010 03:16:51 +0200 (CEST) Subject: [Python-checkins] r80746 - python/trunk/Objects/unicodeobject.c Message-ID: <20100504011651.57E5CF657@mail.python.org> Author: brett.cannon Date: Tue May 4 03:16:51 2010 New Revision: 80746 Log: Remove an unneeded variable and assignment. Found using Clang's static analyzer. Modified: python/trunk/Objects/unicodeobject.c Modified: python/trunk/Objects/unicodeobject.c ============================================================================== --- python/trunk/Objects/unicodeobject.c (original) +++ python/trunk/Objects/unicodeobject.c Tue May 4 03:16:51 2010 @@ -4346,7 +4346,7 @@ if (!result) return NULL; for (i = 0; i < 256; i++) { - key = value = NULL; + value = NULL; key = PyInt_FromLong(decode[i]); value = PyInt_FromLong(i); if (!key || !value) @@ -5846,7 +5846,7 @@ } } else { - Py_ssize_t n, i, j, e; + Py_ssize_t n, i, j; Py_ssize_t product, new_size, delta; Py_UNICODE *p; @@ -5878,7 +5878,6 @@ return NULL; i = 0; p = u->str; - e = self->length - str1->length; if (str1->length > 0) { while (n-- > 0) { /* look for next match */ From python-checkins at python.org Tue May 4 03:23:36 2010 From: python-checkins at python.org (brett.cannon) Date: Tue, 4 May 2010 03:23:36 +0200 (CEST) Subject: [Python-checkins] r80747 - python/trunk/Objects/abstract.c Message-ID: <20100504012336.27177C83B@mail.python.org> Author: brett.cannon Date: Tue May 4 03:23:36 2010 New Revision: 80747 Log: Pull a NULL pointer check up to cover more cases in the function. Found using Clang's static analyzer. Modified: python/trunk/Objects/abstract.c Modified: python/trunk/Objects/abstract.c ============================================================================== --- python/trunk/Objects/abstract.c (original) +++ python/trunk/Objects/abstract.c Tue May 4 03:23:36 2010 @@ -1833,11 +1833,13 @@ int PySequence_Check(PyObject *s) { - if (s && PyInstance_Check(s)) + if (s == NULL) + return 0; + if (PyInstance_Check(s)) return PyObject_HasAttrString(s, "__getitem__"); if (PyDict_Check(s)) return 0; - return s != NULL && s->ob_type->tp_as_sequence && + return s->ob_type->tp_as_sequence && s->ob_type->tp_as_sequence->sq_item != NULL; } From python-checkins at python.org Tue May 4 03:24:22 2010 From: python-checkins at python.org (andrew.kuchling) Date: Tue, 4 May 2010 03:24:22 +0200 (CEST) Subject: [Python-checkins] r80748 - python/trunk/Doc/whatsnew/2.7.rst Message-ID: <20100504012422.91B59C83B@mail.python.org> Author: andrew.kuchling Date: Tue May 4 03:24:22 2010 New Revision: 80748 Log: Add some more items; the urlparse change is added twice Modified: python/trunk/Doc/whatsnew/2.7.rst Modified: python/trunk/Doc/whatsnew/2.7.rst ============================================================================== --- python/trunk/Doc/whatsnew/2.7.rst (original) +++ python/trunk/Doc/whatsnew/2.7.rst Tue May 4 03:24:22 2010 @@ -967,6 +967,16 @@ ``Decimal('0.1000000000000000055511151231257827021181583404541015625')``. (Implemented by Raymond Hettinger; :issue:`4796`.) + Comparing instances of :class:`Decimal` with floating-point + numbers now produces sensible results based on the numeric values + of the operands. Previously such comparisons would fall back to + Python's default rules for comparing objects, which produced arbitrary + results based on their type. Note that you still cannot combine + :class:`Decimal` and floating-point in other operations such as addition, + since you should be explicitly choosing how to convert between float and + :class:`Decimal`. + (Fixed by Mark Dickinson; :issue:`2531`.) + Most of the methods of the :class:`~decimal.Context` class now accept integers as well as :class:`~decimal.Decimal` instances; the only exceptions are the :meth:`~decimal.Context.canonical` and :meth:`~decimal.Context.is_canonical` @@ -1367,7 +1377,28 @@ and has been updated to version 5.2.0 (updated by Florent Xicluna; :issue:`8024`). -* The :mod:`urlparse` module now supports IPv6 literal addresses as defined by +* The :mod:`urlparse` module's :func:`~urlparse.urlsplit` now handles + unknown URL schemes in a fashion compliant with :rfc:`3986`: if the + URL is of the form ``"://..."``, the text before the + ``://`` is treated as the scheme, even if it's a made-up scheme that + the module doesn't know about. This change may break code that + worked around the old behaviour. For example, Python 2.6.4 or 2.5 + will return the following: + + >>> import urlparse + >>> urlparse.urlsplit('invented://host/filename?query') + ('invented', '', '//host/filename?query', '', '') + + Python 2.7 (and Python 2.6.5) will return: + + >>> import urlparse + >>> urlparse.urlsplit('invented://host/filename?query') + ('invented', 'host', '/filename?query', '', '') + + (Python 2.7 actually produces slightly different output, since it + returns a named tuple instead of a standard tuple.) + + The :mod:`urlparse` module also supports IPv6 literal addresses as defined by :rfc:`2732` (contributed by Senthil Kumaran; :issue:`2987`). :: >>> urlparse.urlparse('http://[1080::8:800:200C:417A]/foo') @@ -1871,6 +1902,13 @@ installation and a user-installed copy of the same version. (Changed by Ronald Oussoren; :issue:`4865`.) +Port-Specific Changes: FreeBSD +----------------------------------- + +* FreeBSD 7.1's :const:`SO_SETFIB` constant, used with + :func:`~socket.getsockopt`/:func:`~socket.setsockopt` to select an + alternate routing table, is now available in the :mod:`socket` + module. (Added by Kyle VanderBeek; :issue:`8235`.) Other Changes and Fixes ======================= @@ -1961,6 +1999,27 @@ identifier instead of the previous default value of ``'python'``. (Changed by Sean Reifschneider; :issue:`8451`.) +* The :mod:`urlparse` module's :func:`~urlparse.urlsplit` now handles + unknown URL schemes in a fashion compliant with :rfc:`3986`: if the + URL is of the form ``"://..."``, the text before the + ``://`` is treated as the scheme, even if it's a made-up scheme that + the module doesn't know about. This change may break code that + worked around the old behaviour. For example, Python 2.6.4 or 2.5 + will return the following: + + >>> import urlparse + >>> urlparse.urlsplit('invented://host/filename?query') + ('invented', '', '//host/filename?query', '', '') + + Python 2.7 (and Python 2.6.5) will return: + + >>> import urlparse + >>> urlparse.urlsplit('invented://host/filename?query') + ('invented', 'host', '/filename?query', '', '') + + (Python 2.7 actually produces slightly different output, since it + returns a named tuple instead of a standard tuple.) + For C extensions: * C extensions that use integer format codes with the ``PyArg_Parse*`` From python-checkins at python.org Tue May 4 05:21:51 2010 From: python-checkins at python.org (alexandre.vassalotti) Date: Tue, 4 May 2010 05:21:51 +0200 (CEST) Subject: [Python-checkins] r80749 - in python/trunk: Lib/test/test_dictviews.py Misc/NEWS Objects/dictobject.c Message-ID: <20100504032151.B952DE784@mail.python.org> Author: alexandre.vassalotti Date: Tue May 4 05:21:51 2010 New Revision: 80749 Log: Issue #8404: Fix set operations on dictionary views. Modified: python/trunk/Lib/test/test_dictviews.py python/trunk/Misc/NEWS python/trunk/Objects/dictobject.c Modified: python/trunk/Lib/test/test_dictviews.py ============================================================================== --- python/trunk/Lib/test/test_dictviews.py (original) +++ python/trunk/Lib/test/test_dictviews.py Tue May 4 05:21:51 2010 @@ -85,6 +85,67 @@ self.assertTrue(r == "dict_values(['ABC', 10])" or r == "dict_values([10, 'ABC'])") + def test_keys_set_operations(self): + d1 = {'a': 1, 'b': 2} + d2 = {'b': 3, 'c': 2} + d3 = {'d': 4, 'e': 5} + self.assertEqual(d1.viewkeys() & d1.viewkeys(), {'a', 'b'}) + self.assertEqual(d1.viewkeys() & d2.viewkeys(), {'b'}) + self.assertEqual(d1.viewkeys() & d3.viewkeys(), set()) + self.assertEqual(d1.viewkeys() & set(d1.viewkeys()), {'a', 'b'}) + self.assertEqual(d1.viewkeys() & set(d2.viewkeys()), {'b'}) + self.assertEqual(d1.viewkeys() & set(d3.viewkeys()), set()) + + self.assertEqual(d1.viewkeys() | d1.viewkeys(), {'a', 'b'}) + self.assertEqual(d1.viewkeys() | d2.viewkeys(), {'a', 'b', 'c'}) + self.assertEqual(d1.viewkeys() | d3.viewkeys(), {'a', 'b', 'd', 'e'}) + self.assertEqual(d1.viewkeys() | set(d1.viewkeys()), {'a', 'b'}) + self.assertEqual(d1.viewkeys() | set(d2.viewkeys()), {'a', 'b', 'c'}) + self.assertEqual(d1.viewkeys() | set(d3.viewkeys()), + {'a', 'b', 'd', 'e'}) + + self.assertEqual(d1.viewkeys() ^ d1.viewkeys(), set()) + self.assertEqual(d1.viewkeys() ^ d2.viewkeys(), {'a', 'c'}) + self.assertEqual(d1.viewkeys() ^ d3.viewkeys(), {'a', 'b', 'd', 'e'}) + self.assertEqual(d1.viewkeys() ^ set(d1.viewkeys()), set()) + self.assertEqual(d1.viewkeys() ^ set(d2.viewkeys()), {'a', 'c'}) + self.assertEqual(d1.viewkeys() ^ set(d3.viewkeys()), + {'a', 'b', 'd', 'e'}) + + def test_items_set_operations(self): + d1 = {'a': 1, 'b': 2} + d2 = {'a': 2, 'b': 2} + d3 = {'d': 4, 'e': 5} + self.assertEqual( + d1.viewitems() & d1.viewitems(), {('a', 1), ('b', 2)}) + self.assertEqual(d1.viewitems() & d2.viewitems(), {('b', 2)}) + self.assertEqual(d1.viewitems() & d3.viewitems(), set()) + self.assertEqual(d1.viewitems() & set(d1.viewitems()), + {('a', 1), ('b', 2)}) + self.assertEqual(d1.viewitems() & set(d2.viewitems()), {('b', 2)}) + self.assertEqual(d1.viewitems() & set(d3.viewitems()), set()) + + self.assertEqual(d1.viewitems() | d1.viewitems(), + {('a', 1), ('b', 2)}) + self.assertEqual(d1.viewitems() | d2.viewitems(), + {('a', 1), ('a', 2), ('b', 2)}) + self.assertEqual(d1.viewitems() | d3.viewitems(), + {('a', 1), ('b', 2), ('d', 4), ('e', 5)}) + self.assertEqual(d1.viewitems() | set(d1.viewitems()), + {('a', 1), ('b', 2)}) + self.assertEqual(d1.viewitems() | set(d2.viewitems()), + {('a', 1), ('a', 2), ('b', 2)}) + self.assertEqual(d1.viewitems() | set(d3.viewitems()), + {('a', 1), ('b', 2), ('d', 4), ('e', 5)}) + + self.assertEqual(d1.viewitems() ^ d1.viewitems(), set()) + self.assertEqual(d1.viewitems() ^ d2.viewitems(), + {('a', 1), ('a', 2)}) + self.assertEqual(d1.viewitems() ^ d3.viewitems(), + {('a', 1), ('b', 2), ('d', 4), ('e', 5)}) + + + def test_main(): test_support.run_unittest(DictSetTest) Modified: python/trunk/Misc/NEWS ============================================================================== --- python/trunk/Misc/NEWS (original) +++ python/trunk/Misc/NEWS Tue May 4 05:21:51 2010 @@ -28,6 +28,8 @@ - Issue #7072: isspace(0xa0) is true on Mac OS X +- Issue #8404: Fixed set operations on dictionary views. + Library ------- Modified: python/trunk/Objects/dictobject.c ============================================================================== --- python/trunk/Objects/dictobject.c (original) +++ python/trunk/Objects/dictobject.c Tue May 4 05:21:51 2010 @@ -3000,13 +3000,14 @@ 0, /*nb_add*/ (binaryfunc)dictviews_sub, /*nb_subtract*/ 0, /*nb_multiply*/ + 0, /*nb_divide*/ 0, /*nb_remainder*/ 0, /*nb_divmod*/ 0, /*nb_power*/ 0, /*nb_negative*/ 0, /*nb_positive*/ 0, /*nb_absolute*/ - 0, /*nb_bool*/ + 0, /*nb_nonzero*/ 0, /*nb_invert*/ 0, /*nb_lshift*/ 0, /*nb_rshift*/ @@ -3040,7 +3041,8 @@ PyObject_GenericGetAttr, /* tp_getattro */ 0, /* tp_setattro */ 0, /* tp_as_buffer */ - Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */ + Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC | + Py_TPFLAGS_CHECKTYPES, /* tp_flags */ 0, /* tp_doc */ (traverseproc)dictview_traverse, /* tp_traverse */ 0, /* tp_clear */ @@ -3124,7 +3126,8 @@ PyObject_GenericGetAttr, /* tp_getattro */ 0, /* tp_setattro */ 0, /* tp_as_buffer */ - Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */ + Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC | + Py_TPFLAGS_CHECKTYPES, /* tp_flags */ 0, /* tp_doc */ (traverseproc)dictview_traverse, /* tp_traverse */ 0, /* tp_clear */ From python-checkins at python.org Tue May 4 05:26:10 2010 From: python-checkins at python.org (alexandre.vassalotti) Date: Tue, 4 May 2010 05:26:10 +0200 (CEST) Subject: [Python-checkins] r80750 - python/branches/py3k Message-ID: <20100504032610.8F869EB9A@mail.python.org> Author: alexandre.vassalotti Date: Tue May 4 05:26:10 2010 New Revision: 80750 Log: Blocked revisions 80749 via svnmerge ........ r80749 | alexandre.vassalotti | 2010-05-03 20:21:51 -0700 (Mon, 03 May 2010) | 2 lines Issue #8404: Fix set operations on dictionary views. ........ Modified: python/branches/py3k/ (props changed) From python-checkins at python.org Tue May 4 05:41:50 2010 From: python-checkins at python.org (alexandre.vassalotti) Date: Tue, 4 May 2010 05:41:50 +0200 (CEST) Subject: [Python-checkins] r80751 - python/branches/py3k/Lib/test/test_dictviews.py Message-ID: <20100504034150.213D4E8FC@mail.python.org> Author: alexandre.vassalotti Date: Tue May 4 05:41:49 2010 New Revision: 80751 Log: Forward port unit tests for set operation and repr. Patch by Alexander Belopolsky. Modified: python/branches/py3k/Lib/test/test_dictviews.py Modified: python/branches/py3k/Lib/test/test_dictviews.py ============================================================================== --- python/branches/py3k/Lib/test/test_dictviews.py (original) +++ python/branches/py3k/Lib/test/test_dictviews.py Tue May 4 05:41:49 2010 @@ -69,6 +69,82 @@ self.assertEqual(set(values), {10, "ABC"}) self.assertEqual(len(values), 2) + def test_dict_repr(self): + d = {1: 10, "a": "ABC"} + self.assertIsInstance(repr(d), str) + r = repr(d.items()) + self.assertIsInstance(r, str) + self.assertTrue(r == "dict_items([('a', 'ABC'), (1, 10)])" or + r == "dict_items([(1, 10), ('a', 'ABC')])") + r = repr(d.keys()) + self.assertIsInstance(r, str) + self.assertTrue(r == "dict_keys(['a', 1])" or + r == "dict_keys([1, 'a'])") + r = repr(d.values()) + self.assertIsInstance(r, str) + self.assertTrue(r == "dict_values(['ABC', 10])" or + r == "dict_values([10, 'ABC'])") + + def test_keys_set_operations(self): + d1 = {'a': 1, 'b': 2} + d2 = {'b': 3, 'c': 2} + d3 = {'d': 4, 'e': 5} + self.assertEqual(d1.keys() & d1.keys(), {'a', 'b'}) + self.assertEqual(d1.keys() & d2.keys(), {'b'}) + self.assertEqual(d1.keys() & d3.keys(), set()) + self.assertEqual(d1.keys() & set(d1.keys()), {'a', 'b'}) + self.assertEqual(d1.keys() & set(d2.keys()), {'b'}) + self.assertEqual(d1.keys() & set(d3.keys()), set()) + + self.assertEqual(d1.keys() | d1.keys(), {'a', 'b'}) + self.assertEqual(d1.keys() | d2.keys(), {'a', 'b', 'c'}) + self.assertEqual(d1.keys() | d3.keys(), {'a', 'b', 'd', 'e'}) + self.assertEqual(d1.keys() | set(d1.keys()), {'a', 'b'}) + self.assertEqual(d1.keys() | set(d2.keys()), {'a', 'b', 'c'}) + self.assertEqual(d1.keys() | set(d3.keys()), + {'a', 'b', 'd', 'e'}) + + self.assertEqual(d1.keys() ^ d1.keys(), set()) + self.assertEqual(d1.keys() ^ d2.keys(), {'a', 'c'}) + self.assertEqual(d1.keys() ^ d3.keys(), {'a', 'b', 'd', 'e'}) + self.assertEqual(d1.keys() ^ set(d1.keys()), set()) + self.assertEqual(d1.keys() ^ set(d2.keys()), {'a', 'c'}) + self.assertEqual(d1.keys() ^ set(d3.keys()), + {'a', 'b', 'd', 'e'}) + + def test_items_set_operations(self): + d1 = {'a': 1, 'b': 2} + d2 = {'a': 2, 'b': 2} + d3 = {'d': 4, 'e': 5} + self.assertEqual( + d1.items() & d1.items(), {('a', 1), ('b', 2)}) + self.assertEqual(d1.items() & d2.items(), {('b', 2)}) + self.assertEqual(d1.items() & d3.items(), set()) + self.assertEqual(d1.items() & set(d1.items()), + {('a', 1), ('b', 2)}) + self.assertEqual(d1.items() & set(d2.items()), {('b', 2)}) + self.assertEqual(d1.items() & set(d3.items()), set()) + + self.assertEqual(d1.items() | d1.items(), + {('a', 1), ('b', 2)}) + self.assertEqual(d1.items() | d2.items(), + {('a', 1), ('a', 2), ('b', 2)}) + self.assertEqual(d1.items() | d3.items(), + {('a', 1), ('b', 2), ('d', 4), ('e', 5)}) + self.assertEqual(d1.items() | set(d1.items()), + {('a', 1), ('b', 2)}) + self.assertEqual(d1.items() | set(d2.items()), + {('a', 1), ('a', 2), ('b', 2)}) + self.assertEqual(d1.items() | set(d3.items()), + {('a', 1), ('b', 2), ('d', 4), ('e', 5)}) + + self.assertEqual(d1.items() ^ d1.items(), set()) + self.assertEqual(d1.items() ^ d2.items(), + {('a', 1), ('a', 2)}) + self.assertEqual(d1.items() ^ d3.items(), + {('a', 1), ('b', 2), ('d', 4), ('e', 5)}) + + def test_main(): support.run_unittest(DictSetTest) From victor.stinner at haypocalc.com Tue May 4 10:34:22 2010 From: victor.stinner at haypocalc.com (Victor Stinner) Date: Tue, 4 May 2010 10:34:22 +0200 Subject: [Python-checkins] r80742 - python/trunk/Modules/readline.c In-Reply-To: <20100504005242.2B791E308@mail.python.org> References: <20100504005242.2B791E308@mail.python.org> Message-ID: <201005041034.22942.victor.stinner@haypocalc.com> Le mardi 04 mai 2010 02:52:42, brett.cannon a ?crit : > Author: brett.cannon > New Revision: 80742 > > Log: > Strip out extraneous whitespace, cast a some `const char *` to `void *` > when passed to free() and make a `char *` to a `const char *` as found by > Clang's static analyzer. On my version of readline (6.1), HIST_ENTRY has no const field: typedef struct _hist_entry { char *line; char *timestamp; /* char * rather than time_t for read/write */ histdata_t data; } HIST_ENTRY; Is it different in your version of readline? > Modified: > python/trunk/Modules/readline.c > > @@ -378,7 +378,7 @@ > } > /* free memory allocated for the history entry */ > if (entry->line) > - free(entry->line); > + free((void *)entry->line); > if (entry->data) > free(entry->data); > free(entry); > @@ -415,7 +415,7 @@ > } > /* free memory allocated for the old history entry */ > if (old_entry->line) > - free(old_entry->line); > + free((void *)old_entry->line); > if (old_entry->data) > free(old_entry->data); > free(old_entry); ... > @@ -1023,17 +1023,17 @@ > /* we have a valid line */ > n = strlen(p); > if (n > 0) { > - char *line; > + const char *line; > HISTORY_STATE *state = history_get_history_state(); > if (state->length > 0) > #ifdef __APPLE__ -- Victor Stinner http://www.haypocalc.com/ From ncoghlan at gmail.com Tue May 4 10:33:05 2010 From: ncoghlan at gmail.com (Nick Coghlan) Date: Tue, 04 May 2010 18:33:05 +1000 Subject: [Python-checkins] r80720 - in python/trunk: Lib/_pyio.pyLib/test/test_io.py Misc/NEWS Modules/_io/bufferedio.c Modules/_io/bytesio.cModules/_io/iobase.cModules/_io/textio.c In-Reply-To: References: <20100503162533.A8AB8E726@mail.python.org> <4BDF468F.60805@gmail.com> Message-ID: <4BDFDBC1.2000100@gmail.com> Antoine Pitrou wrote: >> Either way, reverting it should be discussed on python-dev. I definitely >> have grave doubts about backporting this to the maintenance branches, >> and I'm not a particularly big fan of adding it to a release that is >> already in beta either. > > Silencing a true and potentially critical error is a bug IMO. > Moreover, we'd better establish sane semantics in the io module before it gets > widespread acceptance - this was the rationale for the truncate() API change, > approved by Guido (while I was a bit reluctant). I can live with that. Cheers, Nick. -- Nick Coghlan | ncoghlan at gmail.com | Brisbane, Australia --------------------------------------------------------------- From python-checkins at python.org Tue May 4 13:35:36 2010 From: python-checkins at python.org (victor.stinner) Date: Tue, 4 May 2010 13:35:36 +0200 (CEST) Subject: [Python-checkins] r80752 - python/trunk/Lib/_pyio.py Message-ID: <20100504113536.9B24EECC4@mail.python.org> Author: victor.stinner Date: Tue May 4 13:35:36 2010 New Revision: 80752 Log: _pyio: Fix TextIOWrapper constructor: os has no device_encoding() function _io module doesn't call this function which was introduced in Python3. Modified: python/trunk/Lib/_pyio.py Modified: python/trunk/Lib/_pyio.py ============================================================================== --- python/trunk/Lib/_pyio.py (original) +++ python/trunk/Lib/_pyio.py Tue May 4 13:35:36 2010 @@ -1438,17 +1438,12 @@ raise ValueError("illegal newline value: %r" % (newline,)) if encoding is None: try: - encoding = os.device_encoding(buffer.fileno()) - except (AttributeError, UnsupportedOperation): - pass - if encoding is None: - try: - import locale - except ImportError: - # Importing locale may fail if Python is being built - encoding = "ascii" - else: - encoding = locale.getpreferredencoding() + import locale + except ImportError: + # Importing locale may fail if Python is being built + encoding = "ascii" + else: + encoding = locale.getpreferredencoding() if not isinstance(encoding, basestring): raise ValueError("invalid encoding: %r" % encoding) From python-checkins at python.org Tue May 4 16:25:50 2010 From: python-checkins at python.org (mark.dickinson) Date: Tue, 4 May 2010 16:25:50 +0200 (CEST) Subject: [Python-checkins] r80753 - in python/trunk: Lib/decimal.py Lib/test/test_decimal.py Misc/NEWS Message-ID: <20100504142550.48245E95D@mail.python.org> Author: mark.dickinson Date: Tue May 4 16:25:50 2010 New Revision: 80753 Log: Issue #8567: Fix incorrect precedence of signals in Decimal module. When a Decimal operation raises multiple signals and more than one of those signals is trapped, the specification determines the order in which the signals should be handled. In many cases this order wasn't being followed, leading to the wrong Python exception being raised. This commit fixes those cases, and adds extra tests. The tests are only enabled when EXTENDEDERRORTESTS is True, since they involve rerunning each Decimal testcase several times. Modified: python/trunk/Lib/decimal.py python/trunk/Lib/test/test_decimal.py python/trunk/Misc/NEWS Modified: python/trunk/Lib/decimal.py ============================================================================== --- python/trunk/Lib/decimal.py (original) +++ python/trunk/Lib/decimal.py Tue May 4 16:25:50 2010 @@ -1664,47 +1664,53 @@ exp_min = len(self._int) + self._exp - context.prec if exp_min > Etop: # overflow: exp_min > Etop iff self.adjusted() > Emax + ans = context._raise_error(Overflow, 'above Emax', self._sign) context._raise_error(Inexact) context._raise_error(Rounded) - return context._raise_error(Overflow, 'above Emax', self._sign) + return ans + self_is_subnormal = exp_min < Etiny if self_is_subnormal: - context._raise_error(Subnormal) exp_min = Etiny # round if self has too many digits if self._exp < exp_min: - context._raise_error(Rounded) digits = len(self._int) + self._exp - exp_min if digits < 0: self = _dec_from_triple(self._sign, '1', exp_min-1) digits = 0 - this_function = getattr(self, self._pick_rounding_function[context.rounding]) - changed = this_function(digits) + rounding_method = self._pick_rounding_function[context.rounding] + changed = getattr(self, rounding_method)(digits) coeff = self._int[:digits] or '0' - if changed == 1: + if changed > 0: coeff = str(int(coeff)+1) - ans = _dec_from_triple(self._sign, coeff, exp_min) + if len(coeff) > context.prec: + coeff = coeff[:-1] + exp_min += 1 + + # check whether the rounding pushed the exponent out of range + if exp_min > Etop: + ans = context._raise_error(Overflow, 'above Emax', self._sign) + else: + ans = _dec_from_triple(self._sign, coeff, exp_min) + # raise the appropriate signals, taking care to respect + # the precedence described in the specification + if changed and self_is_subnormal: + context._raise_error(Underflow) + if self_is_subnormal: + context._raise_error(Subnormal) if changed: context._raise_error(Inexact) - if self_is_subnormal: - context._raise_error(Underflow) - if not ans: - # raise Clamped on underflow to 0 - context._raise_error(Clamped) - elif len(ans._int) == context.prec+1: - # we get here only if rescaling rounds the - # cofficient up to exactly 10**context.prec - if ans._exp < Etop: - ans = _dec_from_triple(ans._sign, - ans._int[:-1], ans._exp+1) - else: - # Inexact and Rounded have already been raised - ans = context._raise_error(Overflow, 'above Emax', - self._sign) + context._raise_error(Rounded) + if not ans: + # raise Clamped on underflow to 0 + context._raise_error(Clamped) return ans + if self_is_subnormal: + context._raise_error(Subnormal) + # fold down if _clamp == 1 and self has too few digits if context._clamp == 1 and self._exp > Etop: context._raise_error(Clamped) @@ -2239,6 +2245,7 @@ # from here on, the result always goes through the call # to _fix at the end of this function. ans = None + exact = False # crude test to catch cases of extreme overflow/underflow. If # log10(self)*other >= 10**bound and bound >= len(str(Emax)) @@ -2263,6 +2270,7 @@ ans = self._power_exact(other, context.prec + 1) if ans is not None and result_sign == 1: ans = _dec_from_triple(1, ans._int, ans._exp) + exact = True # usual case: inexact result, x**y computed directly as exp(y*log(x)) if ans is None: @@ -2285,24 +2293,55 @@ ans = _dec_from_triple(result_sign, str(coeff), exp) - # the specification says that for non-integer other we need to - # raise Inexact, even when the result is actually exact. In - # the same way, we need to raise Underflow here if the result - # is subnormal. (The call to _fix will take care of raising - # Rounded and Subnormal, as usual.) - if not other._isinteger(): - context._raise_error(Inexact) - # pad with zeros up to length context.prec+1 if necessary + # unlike exp, ln and log10, the power function respects the + # rounding mode; no need to switch to ROUND_HALF_EVEN here + + # There's a difficulty here when 'other' is not an integer and + # the result is exact. In this case, the specification + # requires that the Inexact flag be raised (in spite of + # exactness), but since the result is exact _fix won't do this + # for us. (Correspondingly, the Underflow signal should also + # be raised for subnormal results.) We can't directly raise + # these signals either before or after calling _fix, since + # that would violate the precedence for signals. So we wrap + # the ._fix call in a temporary context, and reraise + # afterwards. + if exact and not other._isinteger(): + # pad with zeros up to length context.prec+1 if necessary; this + # ensures that the Rounded signal will be raised. if len(ans._int) <= context.prec: - expdiff = context.prec+1 - len(ans._int) + expdiff = context.prec + 1 - len(ans._int) ans = _dec_from_triple(ans._sign, ans._int+'0'*expdiff, ans._exp-expdiff) - if ans.adjusted() < context.Emin: - context._raise_error(Underflow) - # unlike exp, ln and log10, the power function respects the - # rounding mode; no need to use ROUND_HALF_EVEN here - ans = ans._fix(context) + # create a copy of the current context, with cleared flags/traps + newcontext = context.copy() + newcontext.clear_flags() + for exception in _signals: + newcontext.traps[exception] = 0 + + # round in the new context + ans = ans._fix(newcontext) + + # raise Inexact, and if necessary, Underflow + newcontext._raise_error(Inexact) + if newcontext.flags[Subnormal]: + newcontext._raise_error(Underflow) + + # propagate signals to the original context; _fix could + # have raised any of Overflow, Underflow, Subnormal, + # Inexact, Rounded, Clamped. Overflow needs the correct + # arguments. Note that the order of the exceptions is + # important here. + if newcontext.flags[Overflow]: + context._raise_error(Overflow, 'above Emax', ans._sign) + for exception in Underflow, Subnormal, Inexact, Rounded, Clamped: + if newcontext.flags[exception]: + context._raise_error(exception) + + else: + ans = ans._fix(context) + return ans def __rpow__(self, other, context=None): @@ -2396,14 +2435,15 @@ 'quantize result has too many digits for current context') # raise appropriate flags + if ans and ans.adjusted() < context.Emin: + context._raise_error(Subnormal) if ans._exp > self._exp: - context._raise_error(Rounded) if ans != self: context._raise_error(Inexact) - if ans and ans.adjusted() < context.Emin: - context._raise_error(Subnormal) + context._raise_error(Rounded) - # call to fix takes care of any necessary folddown + # call to fix takes care of any necessary folddown, and + # signals Clamped if necessary ans = ans._fix(context) return ans @@ -2502,10 +2542,10 @@ context = getcontext() if rounding is None: rounding = context.rounding - context._raise_error(Rounded) ans = self._rescale(0, rounding) if ans != self: context._raise_error(Inexact) + context._raise_error(Rounded) return ans def to_integral_value(self, rounding=None, context=None): @@ -3386,13 +3426,13 @@ context._raise_error(Overflow, 'Infinite result from next_toward', ans._sign) - context._raise_error(Rounded) context._raise_error(Inexact) + context._raise_error(Rounded) elif ans.adjusted() < context.Emin: context._raise_error(Underflow) context._raise_error(Subnormal) - context._raise_error(Rounded) context._raise_error(Inexact) + context._raise_error(Rounded) # if precision == 1 then we don't raise Clamped for a # result 0E-Etiny. if not ans: Modified: python/trunk/Lib/test/test_decimal.py ============================================================================== --- python/trunk/Lib/test/test_decimal.py (original) +++ python/trunk/Lib/test/test_decimal.py Tue May 4 16:25:50 2010 @@ -42,6 +42,12 @@ # Useful Test Constant Signals = tuple(getcontext().flags.keys()) +# Signals ordered with respect to precedence: when an operation +# produces multiple signals, signals occurring later in the list +# should be handled before those occurring earlier in the list. +OrderedSignals = (Clamped, Rounded, Inexact, Subnormal, + Underflow, Overflow, DivisionByZero, InvalidOperation) + # Tests are built around these assumed context defaults. # test_main() restores the original context. def init(): @@ -352,6 +358,25 @@ else: self.fail("Did not raise %s in %s" % (error, s)) self.context.traps[error] = 0 + + # as above, but add traps cumulatively, to check precedence + ordered_errors = [e for e in OrderedSignals if e in theirexceptions] + for error in ordered_errors: + self.context.traps[error] = 1 + try: + funct(*vals) + except error: + pass + except Signals, e: + self.fail("Raised %s in %s; expected %s" % + (type(e), s, error)) + else: + self.fail("Did not raise %s in %s" % (error, s)) + # reset traps + for error in ordered_errors: + self.context.traps[error] = 0 + + if DEBUG: print "--", self.context try: Modified: python/trunk/Misc/NEWS ============================================================================== --- python/trunk/Misc/NEWS (original) +++ python/trunk/Misc/NEWS Tue May 4 16:25:50 2010 @@ -33,6 +33,12 @@ Library ------- +- Issue #8567: Fix precedence of signals in Decimal module: when a + Decimal operation raises multiple signals and more than one of those + signals is trapped, the specification determines the order in which + the signals should be handled. In many cases this order wasn't + being followed, leading to the wrong Python exception being raised. + - Issue #7865: The close() method of :mod:`io` objects should not swallow exceptions raised by the implicit flush(). Also ensure that calling close() several times is supported. Patch by Pascal Chambon. From python-checkins at python.org Tue May 4 16:30:32 2010 From: python-checkins at python.org (mark.dickinson) Date: Tue, 4 May 2010 16:30:32 +0200 (CEST) Subject: [Python-checkins] r80754 - in python/branches/release26-maint: Lib/decimal.py Lib/test/test_decimal.py Misc/NEWS Message-ID: <20100504143032.58882EE982@mail.python.org> Author: mark.dickinson Date: Tue May 4 16:30:32 2010 New Revision: 80754 Log: Merged revisions 80753 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r80753 | mark.dickinson | 2010-05-04 15:25:50 +0100 (Tue, 04 May 2010) | 10 lines Issue #8567: Fix incorrect precedence of signals in Decimal module. When a Decimal operation raises multiple signals and more than one of those signals is trapped, the specification determines the order in which the signals should be handled. In many cases this order wasn't being followed, leading to the wrong Python exception being raised. This commit fixes those cases, and adds extra tests. The tests are only enabled when EXTENDEDERRORTESTS is True, since they involve rerunning each Decimal testcase several times. ........ Modified: python/branches/release26-maint/ (props changed) python/branches/release26-maint/Lib/decimal.py python/branches/release26-maint/Lib/test/test_decimal.py python/branches/release26-maint/Misc/NEWS Modified: python/branches/release26-maint/Lib/decimal.py ============================================================================== --- python/branches/release26-maint/Lib/decimal.py (original) +++ python/branches/release26-maint/Lib/decimal.py Tue May 4 16:30:32 2010 @@ -1592,47 +1592,53 @@ exp_min = len(self._int) + self._exp - context.prec if exp_min > Etop: # overflow: exp_min > Etop iff self.adjusted() > Emax + ans = context._raise_error(Overflow, 'above Emax', self._sign) context._raise_error(Inexact) context._raise_error(Rounded) - return context._raise_error(Overflow, 'above Emax', self._sign) + return ans + self_is_subnormal = exp_min < Etiny if self_is_subnormal: - context._raise_error(Subnormal) exp_min = Etiny # round if self has too many digits if self._exp < exp_min: - context._raise_error(Rounded) digits = len(self._int) + self._exp - exp_min if digits < 0: self = _dec_from_triple(self._sign, '1', exp_min-1) digits = 0 - this_function = getattr(self, self._pick_rounding_function[context.rounding]) - changed = this_function(digits) + rounding_method = self._pick_rounding_function[context.rounding] + changed = getattr(self, rounding_method)(digits) coeff = self._int[:digits] or '0' - if changed == 1: + if changed > 0: coeff = str(int(coeff)+1) - ans = _dec_from_triple(self._sign, coeff, exp_min) + if len(coeff) > context.prec: + coeff = coeff[:-1] + exp_min += 1 + + # check whether the rounding pushed the exponent out of range + if exp_min > Etop: + ans = context._raise_error(Overflow, 'above Emax', self._sign) + else: + ans = _dec_from_triple(self._sign, coeff, exp_min) + # raise the appropriate signals, taking care to respect + # the precedence described in the specification + if changed and self_is_subnormal: + context._raise_error(Underflow) + if self_is_subnormal: + context._raise_error(Subnormal) if changed: context._raise_error(Inexact) - if self_is_subnormal: - context._raise_error(Underflow) - if not ans: - # raise Clamped on underflow to 0 - context._raise_error(Clamped) - elif len(ans._int) == context.prec+1: - # we get here only if rescaling rounds the - # cofficient up to exactly 10**context.prec - if ans._exp < Etop: - ans = _dec_from_triple(ans._sign, - ans._int[:-1], ans._exp+1) - else: - # Inexact and Rounded have already been raised - ans = context._raise_error(Overflow, 'above Emax', - self._sign) + context._raise_error(Rounded) + if not ans: + # raise Clamped on underflow to 0 + context._raise_error(Clamped) return ans + if self_is_subnormal: + context._raise_error(Subnormal) + # fold down if _clamp == 1 and self has too few digits if context._clamp == 1 and self._exp > Etop: context._raise_error(Clamped) @@ -2167,6 +2173,7 @@ # from here on, the result always goes through the call # to _fix at the end of this function. ans = None + exact = False # crude test to catch cases of extreme overflow/underflow. If # log10(self)*other >= 10**bound and bound >= len(str(Emax)) @@ -2191,6 +2198,7 @@ ans = self._power_exact(other, context.prec + 1) if ans is not None and result_sign == 1: ans = _dec_from_triple(1, ans._int, ans._exp) + exact = True # usual case: inexact result, x**y computed directly as exp(y*log(x)) if ans is None: @@ -2213,24 +2221,55 @@ ans = _dec_from_triple(result_sign, str(coeff), exp) - # the specification says that for non-integer other we need to - # raise Inexact, even when the result is actually exact. In - # the same way, we need to raise Underflow here if the result - # is subnormal. (The call to _fix will take care of raising - # Rounded and Subnormal, as usual.) - if not other._isinteger(): - context._raise_error(Inexact) - # pad with zeros up to length context.prec+1 if necessary + # unlike exp, ln and log10, the power function respects the + # rounding mode; no need to switch to ROUND_HALF_EVEN here + + # There's a difficulty here when 'other' is not an integer and + # the result is exact. In this case, the specification + # requires that the Inexact flag be raised (in spite of + # exactness), but since the result is exact _fix won't do this + # for us. (Correspondingly, the Underflow signal should also + # be raised for subnormal results.) We can't directly raise + # these signals either before or after calling _fix, since + # that would violate the precedence for signals. So we wrap + # the ._fix call in a temporary context, and reraise + # afterwards. + if exact and not other._isinteger(): + # pad with zeros up to length context.prec+1 if necessary; this + # ensures that the Rounded signal will be raised. if len(ans._int) <= context.prec: - expdiff = context.prec+1 - len(ans._int) + expdiff = context.prec + 1 - len(ans._int) ans = _dec_from_triple(ans._sign, ans._int+'0'*expdiff, ans._exp-expdiff) - if ans.adjusted() < context.Emin: - context._raise_error(Underflow) - # unlike exp, ln and log10, the power function respects the - # rounding mode; no need to use ROUND_HALF_EVEN here - ans = ans._fix(context) + # create a copy of the current context, with cleared flags/traps + newcontext = context.copy() + newcontext.clear_flags() + for exception in _signals: + newcontext.traps[exception] = 0 + + # round in the new context + ans = ans._fix(newcontext) + + # raise Inexact, and if necessary, Underflow + newcontext._raise_error(Inexact) + if newcontext.flags[Subnormal]: + newcontext._raise_error(Underflow) + + # propagate signals to the original context; _fix could + # have raised any of Overflow, Underflow, Subnormal, + # Inexact, Rounded, Clamped. Overflow needs the correct + # arguments. Note that the order of the exceptions is + # important here. + if newcontext.flags[Overflow]: + context._raise_error(Overflow, 'above Emax', ans._sign) + for exception in Underflow, Subnormal, Inexact, Rounded, Clamped: + if newcontext.flags[exception]: + context._raise_error(exception) + + else: + ans = ans._fix(context) + return ans def __rpow__(self, other, context=None): @@ -2324,14 +2363,15 @@ 'quantize result has too many digits for current context') # raise appropriate flags + if ans and ans.adjusted() < context.Emin: + context._raise_error(Subnormal) if ans._exp > self._exp: - context._raise_error(Rounded) if ans != self: context._raise_error(Inexact) - if ans and ans.adjusted() < context.Emin: - context._raise_error(Subnormal) + context._raise_error(Rounded) - # call to fix takes care of any necessary folddown + # call to fix takes care of any necessary folddown, and + # signals Clamped if necessary ans = ans._fix(context) return ans @@ -2430,10 +2470,10 @@ context = getcontext() if rounding is None: rounding = context.rounding - context._raise_error(Rounded) ans = self._rescale(0, rounding) if ans != self: context._raise_error(Inexact) + context._raise_error(Rounded) return ans def to_integral_value(self, rounding=None, context=None): @@ -3313,13 +3353,13 @@ context._raise_error(Overflow, 'Infinite result from next_toward', ans._sign) - context._raise_error(Rounded) context._raise_error(Inexact) + context._raise_error(Rounded) elif ans.adjusted() < context.Emin: context._raise_error(Underflow) context._raise_error(Subnormal) - context._raise_error(Rounded) context._raise_error(Inexact) + context._raise_error(Rounded) # if precision == 1 then we don't raise Clamped for a # result 0E-Etiny. if not ans: Modified: python/branches/release26-maint/Lib/test/test_decimal.py ============================================================================== --- python/branches/release26-maint/Lib/test/test_decimal.py (original) +++ python/branches/release26-maint/Lib/test/test_decimal.py Tue May 4 16:30:32 2010 @@ -42,6 +42,12 @@ # Useful Test Constant Signals = tuple(getcontext().flags.keys()) +# Signals ordered with respect to precedence: when an operation +# produces multiple signals, signals occurring later in the list +# should be handled before those occurring earlier in the list. +OrderedSignals = (Clamped, Rounded, Inexact, Subnormal, + Underflow, Overflow, DivisionByZero, InvalidOperation) + # Tests are built around these assumed context defaults. # test_main() restores the original context. def init(): @@ -347,6 +353,25 @@ else: self.fail("Did not raise %s in %s" % (error, s)) self.context.traps[error] = 0 + + # as above, but add traps cumulatively, to check precedence + ordered_errors = [e for e in OrderedSignals if e in theirexceptions] + for error in ordered_errors: + self.context.traps[error] = 1 + try: + funct(*vals) + except error: + pass + except Signals, e: + self.fail("Raised %s in %s; expected %s" % + (type(e), s, error)) + else: + self.fail("Did not raise %s in %s" % (error, s)) + # reset traps + for error in ordered_errors: + self.context.traps[error] = 0 + + if DEBUG: print "--", self.context try: Modified: python/branches/release26-maint/Misc/NEWS ============================================================================== --- python/branches/release26-maint/Misc/NEWS (original) +++ python/branches/release26-maint/Misc/NEWS Tue May 4 16:30:32 2010 @@ -33,6 +33,12 @@ Library ------- +- Issue #8567: Fix precedence of signals in Decimal module: when a + Decimal operation raises multiple signals and more than one of those + signals is trapped, the specification determines the order in which + the signals should be handled. In many cases this order wasn't + being followed, leading to the wrong Python exception being raised. + - Issue #7865: The close() method of :mod:`io` objects should not swallow exceptions raised by the implicit flush(). Also ensure that calling close() several times is supported. Initial patch by Pascal Chambon. From python-checkins at python.org Tue May 4 16:35:33 2010 From: python-checkins at python.org (mark.dickinson) Date: Tue, 4 May 2010 16:35:33 +0200 (CEST) Subject: [Python-checkins] r80755 - in python/branches/py3k: Lib/decimal.py Lib/test/test_decimal.py Misc/NEWS Message-ID: <20100504143533.CFE78EE982@mail.python.org> Author: mark.dickinson Date: Tue May 4 16:35:33 2010 New Revision: 80755 Log: Merged revisions 80753 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r80753 | mark.dickinson | 2010-05-04 15:25:50 +0100 (Tue, 04 May 2010) | 10 lines Issue #8567: Fix incorrect precedence of signals in Decimal module. When a Decimal operation raises multiple signals and more than one of those signals is trapped, the specification determines the order in which the signals should be handled. In many cases this order wasn't being followed, leading to the wrong Python exception being raised. This commit fixes those cases, and adds extra tests. The tests are only enabled when EXTENDEDERRORTESTS is True, since they involve rerunning each Decimal testcase several times. ........ Modified: python/branches/py3k/ (props changed) python/branches/py3k/Lib/decimal.py python/branches/py3k/Lib/test/test_decimal.py python/branches/py3k/Misc/NEWS Modified: python/branches/py3k/Lib/decimal.py ============================================================================== --- python/branches/py3k/Lib/decimal.py (original) +++ python/branches/py3k/Lib/decimal.py Tue May 4 16:35:33 2010 @@ -1655,47 +1655,53 @@ exp_min = len(self._int) + self._exp - context.prec if exp_min > Etop: # overflow: exp_min > Etop iff self.adjusted() > Emax + ans = context._raise_error(Overflow, 'above Emax', self._sign) context._raise_error(Inexact) context._raise_error(Rounded) - return context._raise_error(Overflow, 'above Emax', self._sign) + return ans + self_is_subnormal = exp_min < Etiny if self_is_subnormal: - context._raise_error(Subnormal) exp_min = Etiny # round if self has too many digits if self._exp < exp_min: - context._raise_error(Rounded) digits = len(self._int) + self._exp - exp_min if digits < 0: self = _dec_from_triple(self._sign, '1', exp_min-1) digits = 0 - this_function = getattr(self, self._pick_rounding_function[context.rounding]) - changed = this_function(digits) + rounding_method = self._pick_rounding_function[context.rounding] + changed = getattr(self, rounding_method)(digits) coeff = self._int[:digits] or '0' - if changed == 1: + if changed > 0: coeff = str(int(coeff)+1) - ans = _dec_from_triple(self._sign, coeff, exp_min) + if len(coeff) > context.prec: + coeff = coeff[:-1] + exp_min += 1 + + # check whether the rounding pushed the exponent out of range + if exp_min > Etop: + ans = context._raise_error(Overflow, 'above Emax', self._sign) + else: + ans = _dec_from_triple(self._sign, coeff, exp_min) + # raise the appropriate signals, taking care to respect + # the precedence described in the specification + if changed and self_is_subnormal: + context._raise_error(Underflow) + if self_is_subnormal: + context._raise_error(Subnormal) if changed: context._raise_error(Inexact) - if self_is_subnormal: - context._raise_error(Underflow) - if not ans: - # raise Clamped on underflow to 0 - context._raise_error(Clamped) - elif len(ans._int) == context.prec+1: - # we get here only if rescaling rounds the - # cofficient up to exactly 10**context.prec - if ans._exp < Etop: - ans = _dec_from_triple(ans._sign, - ans._int[:-1], ans._exp+1) - else: - # Inexact and Rounded have already been raised - ans = context._raise_error(Overflow, 'above Emax', - self._sign) + context._raise_error(Rounded) + if not ans: + # raise Clamped on underflow to 0 + context._raise_error(Clamped) return ans + if self_is_subnormal: + context._raise_error(Subnormal) + # fold down if _clamp == 1 and self has too few digits if context._clamp == 1 and self._exp > Etop: context._raise_error(Clamped) @@ -2322,6 +2328,7 @@ # from here on, the result always goes through the call # to _fix at the end of this function. ans = None + exact = False # crude test to catch cases of extreme overflow/underflow. If # log10(self)*other >= 10**bound and bound >= len(str(Emax)) @@ -2346,6 +2353,7 @@ ans = self._power_exact(other, context.prec + 1) if ans is not None and result_sign == 1: ans = _dec_from_triple(1, ans._int, ans._exp) + exact = True # usual case: inexact result, x**y computed directly as exp(y*log(x)) if ans is None: @@ -2368,24 +2376,55 @@ ans = _dec_from_triple(result_sign, str(coeff), exp) - # the specification says that for non-integer other we need to - # raise Inexact, even when the result is actually exact. In - # the same way, we need to raise Underflow here if the result - # is subnormal. (The call to _fix will take care of raising - # Rounded and Subnormal, as usual.) - if not other._isinteger(): - context._raise_error(Inexact) - # pad with zeros up to length context.prec+1 if necessary + # unlike exp, ln and log10, the power function respects the + # rounding mode; no need to switch to ROUND_HALF_EVEN here + + # There's a difficulty here when 'other' is not an integer and + # the result is exact. In this case, the specification + # requires that the Inexact flag be raised (in spite of + # exactness), but since the result is exact _fix won't do this + # for us. (Correspondingly, the Underflow signal should also + # be raised for subnormal results.) We can't directly raise + # these signals either before or after calling _fix, since + # that would violate the precedence for signals. So we wrap + # the ._fix call in a temporary context, and reraise + # afterwards. + if exact and not other._isinteger(): + # pad with zeros up to length context.prec+1 if necessary; this + # ensures that the Rounded signal will be raised. if len(ans._int) <= context.prec: - expdiff = context.prec+1 - len(ans._int) + expdiff = context.prec + 1 - len(ans._int) ans = _dec_from_triple(ans._sign, ans._int+'0'*expdiff, ans._exp-expdiff) - if ans.adjusted() < context.Emin: - context._raise_error(Underflow) - # unlike exp, ln and log10, the power function respects the - # rounding mode; no need to use ROUND_HALF_EVEN here - ans = ans._fix(context) + # create a copy of the current context, with cleared flags/traps + newcontext = context.copy() + newcontext.clear_flags() + for exception in _signals: + newcontext.traps[exception] = 0 + + # round in the new context + ans = ans._fix(newcontext) + + # raise Inexact, and if necessary, Underflow + newcontext._raise_error(Inexact) + if newcontext.flags[Subnormal]: + newcontext._raise_error(Underflow) + + # propagate signals to the original context; _fix could + # have raised any of Overflow, Underflow, Subnormal, + # Inexact, Rounded, Clamped. Overflow needs the correct + # arguments. Note that the order of the exceptions is + # important here. + if newcontext.flags[Overflow]: + context._raise_error(Overflow, 'above Emax', ans._sign) + for exception in Underflow, Subnormal, Inexact, Rounded, Clamped: + if newcontext.flags[exception]: + context._raise_error(exception) + + else: + ans = ans._fix(context) + return ans def __rpow__(self, other, context=None): @@ -2479,14 +2518,15 @@ 'quantize result has too many digits for current context') # raise appropriate flags + if ans and ans.adjusted() < context.Emin: + context._raise_error(Subnormal) if ans._exp > self._exp: - context._raise_error(Rounded) if ans != self: context._raise_error(Inexact) - if ans and ans.adjusted() < context.Emin: - context._raise_error(Subnormal) + context._raise_error(Rounded) - # call to fix takes care of any necessary folddown + # call to fix takes care of any necessary folddown, and + # signals Clamped if necessary ans = ans._fix(context) return ans @@ -2585,10 +2625,10 @@ context = getcontext() if rounding is None: rounding = context.rounding - context._raise_error(Rounded) ans = self._rescale(0, rounding) if ans != self: context._raise_error(Inexact) + context._raise_error(Rounded) return ans def to_integral_value(self, rounding=None, context=None): @@ -3469,13 +3509,13 @@ context._raise_error(Overflow, 'Infinite result from next_toward', ans._sign) - context._raise_error(Rounded) context._raise_error(Inexact) + context._raise_error(Rounded) elif ans.adjusted() < context.Emin: context._raise_error(Underflow) context._raise_error(Subnormal) - context._raise_error(Rounded) context._raise_error(Inexact) + context._raise_error(Rounded) # if precision == 1 then we don't raise Clamped for a # result 0E-Etiny. if not ans: Modified: python/branches/py3k/Lib/test/test_decimal.py ============================================================================== --- python/branches/py3k/Lib/test/test_decimal.py (original) +++ python/branches/py3k/Lib/test/test_decimal.py Tue May 4 16:35:33 2010 @@ -41,6 +41,12 @@ # Useful Test Constant Signals = tuple(getcontext().flags.keys()) +# Signals ordered with respect to precedence: when an operation +# produces multiple signals, signals occurring later in the list +# should be handled before those occurring earlier in the list. +OrderedSignals = (Clamped, Rounded, Inexact, Subnormal, + Underflow, Overflow, DivisionByZero, InvalidOperation) + # Tests are built around these assumed context defaults. # test_main() restores the original context. def init(): @@ -351,6 +357,25 @@ else: self.fail("Did not raise %s in %s" % (error, s)) self.context.traps[error] = 0 + + # as above, but add traps cumulatively, to check precedence + ordered_errors = [e for e in OrderedSignals if e in theirexceptions] + for error in ordered_errors: + self.context.traps[error] = 1 + try: + funct(*vals) + except error: + pass + except Signals as e: + self.fail("Raised %s in %s; expected %s" % + (type(e), s, error)) + else: + self.fail("Did not raise %s in %s" % (error, s)) + # reset traps + for error in ordered_errors: + self.context.traps[error] = 0 + + if DEBUG: print("--", self.context) try: Modified: python/branches/py3k/Misc/NEWS ============================================================================== --- python/branches/py3k/Misc/NEWS (original) +++ python/branches/py3k/Misc/NEWS Tue May 4 16:35:33 2010 @@ -348,6 +348,12 @@ Library ------- +- Issue #8567: Fix precedence of signals in Decimal module: when a + Decimal operation raises multiple signals and more than one of those + signals is trapped, the specification determines the order in which + the signals should be handled. In many cases this order wasn't + being followed, leading to the wrong Python exception being raised. + - Issue #7865: The close() method of :mod:`io` objects should not swallow exceptions raised by the implicit flush(). Also ensure that calling close() several times is supported. Patch by Pascal Chambon. From python-checkins at python.org Tue May 4 16:37:15 2010 From: python-checkins at python.org (mark.dickinson) Date: Tue, 4 May 2010 16:37:15 +0200 (CEST) Subject: [Python-checkins] r80756 - in python/branches/release31-maint: Lib/decimal.py Lib/test/test_decimal.py Misc/NEWS Message-ID: <20100504143715.05A85FC5D@mail.python.org> Author: mark.dickinson Date: Tue May 4 16:37:14 2010 New Revision: 80756 Log: Merged revisions 80755 via svnmerge from svn+ssh://pythondev at svn.python.org/python/branches/py3k ................ r80755 | mark.dickinson | 2010-05-04 15:35:33 +0100 (Tue, 04 May 2010) | 17 lines Merged revisions 80753 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r80753 | mark.dickinson | 2010-05-04 15:25:50 +0100 (Tue, 04 May 2010) | 10 lines Issue #8567: Fix incorrect precedence of signals in Decimal module. When a Decimal operation raises multiple signals and more than one of those signals is trapped, the specification determines the order in which the signals should be handled. In many cases this order wasn't being followed, leading to the wrong Python exception being raised. This commit fixes those cases, and adds extra tests. The tests are only enabled when EXTENDEDERRORTESTS is True, since they involve rerunning each Decimal testcase several times. ........ ................ Modified: python/branches/release31-maint/ (props changed) python/branches/release31-maint/Lib/decimal.py python/branches/release31-maint/Lib/test/test_decimal.py python/branches/release31-maint/Misc/NEWS Modified: python/branches/release31-maint/Lib/decimal.py ============================================================================== --- python/branches/release31-maint/Lib/decimal.py (original) +++ python/branches/release31-maint/Lib/decimal.py Tue May 4 16:37:14 2010 @@ -1626,47 +1626,53 @@ exp_min = len(self._int) + self._exp - context.prec if exp_min > Etop: # overflow: exp_min > Etop iff self.adjusted() > Emax + ans = context._raise_error(Overflow, 'above Emax', self._sign) context._raise_error(Inexact) context._raise_error(Rounded) - return context._raise_error(Overflow, 'above Emax', self._sign) + return ans + self_is_subnormal = exp_min < Etiny if self_is_subnormal: - context._raise_error(Subnormal) exp_min = Etiny # round if self has too many digits if self._exp < exp_min: - context._raise_error(Rounded) digits = len(self._int) + self._exp - exp_min if digits < 0: self = _dec_from_triple(self._sign, '1', exp_min-1) digits = 0 - this_function = getattr(self, self._pick_rounding_function[context.rounding]) - changed = this_function(digits) + rounding_method = self._pick_rounding_function[context.rounding] + changed = getattr(self, rounding_method)(digits) coeff = self._int[:digits] or '0' - if changed == 1: + if changed > 0: coeff = str(int(coeff)+1) - ans = _dec_from_triple(self._sign, coeff, exp_min) + if len(coeff) > context.prec: + coeff = coeff[:-1] + exp_min += 1 + + # check whether the rounding pushed the exponent out of range + if exp_min > Etop: + ans = context._raise_error(Overflow, 'above Emax', self._sign) + else: + ans = _dec_from_triple(self._sign, coeff, exp_min) + # raise the appropriate signals, taking care to respect + # the precedence described in the specification + if changed and self_is_subnormal: + context._raise_error(Underflow) + if self_is_subnormal: + context._raise_error(Subnormal) if changed: context._raise_error(Inexact) - if self_is_subnormal: - context._raise_error(Underflow) - if not ans: - # raise Clamped on underflow to 0 - context._raise_error(Clamped) - elif len(ans._int) == context.prec+1: - # we get here only if rescaling rounds the - # cofficient up to exactly 10**context.prec - if ans._exp < Etop: - ans = _dec_from_triple(ans._sign, - ans._int[:-1], ans._exp+1) - else: - # Inexact and Rounded have already been raised - ans = context._raise_error(Overflow, 'above Emax', - self._sign) + context._raise_error(Rounded) + if not ans: + # raise Clamped on underflow to 0 + context._raise_error(Clamped) return ans + if self_is_subnormal: + context._raise_error(Subnormal) + # fold down if _clamp == 1 and self has too few digits if context._clamp == 1 and self._exp > Etop: context._raise_error(Clamped) @@ -2293,6 +2299,7 @@ # from here on, the result always goes through the call # to _fix at the end of this function. ans = None + exact = False # crude test to catch cases of extreme overflow/underflow. If # log10(self)*other >= 10**bound and bound >= len(str(Emax)) @@ -2317,6 +2324,7 @@ ans = self._power_exact(other, context.prec + 1) if ans is not None and result_sign == 1: ans = _dec_from_triple(1, ans._int, ans._exp) + exact = True # usual case: inexact result, x**y computed directly as exp(y*log(x)) if ans is None: @@ -2339,24 +2347,55 @@ ans = _dec_from_triple(result_sign, str(coeff), exp) - # the specification says that for non-integer other we need to - # raise Inexact, even when the result is actually exact. In - # the same way, we need to raise Underflow here if the result - # is subnormal. (The call to _fix will take care of raising - # Rounded and Subnormal, as usual.) - if not other._isinteger(): - context._raise_error(Inexact) - # pad with zeros up to length context.prec+1 if necessary + # unlike exp, ln and log10, the power function respects the + # rounding mode; no need to switch to ROUND_HALF_EVEN here + + # There's a difficulty here when 'other' is not an integer and + # the result is exact. In this case, the specification + # requires that the Inexact flag be raised (in spite of + # exactness), but since the result is exact _fix won't do this + # for us. (Correspondingly, the Underflow signal should also + # be raised for subnormal results.) We can't directly raise + # these signals either before or after calling _fix, since + # that would violate the precedence for signals. So we wrap + # the ._fix call in a temporary context, and reraise + # afterwards. + if exact and not other._isinteger(): + # pad with zeros up to length context.prec+1 if necessary; this + # ensures that the Rounded signal will be raised. if len(ans._int) <= context.prec: - expdiff = context.prec+1 - len(ans._int) + expdiff = context.prec + 1 - len(ans._int) ans = _dec_from_triple(ans._sign, ans._int+'0'*expdiff, ans._exp-expdiff) - if ans.adjusted() < context.Emin: - context._raise_error(Underflow) - # unlike exp, ln and log10, the power function respects the - # rounding mode; no need to use ROUND_HALF_EVEN here - ans = ans._fix(context) + # create a copy of the current context, with cleared flags/traps + newcontext = context.copy() + newcontext.clear_flags() + for exception in _signals: + newcontext.traps[exception] = 0 + + # round in the new context + ans = ans._fix(newcontext) + + # raise Inexact, and if necessary, Underflow + newcontext._raise_error(Inexact) + if newcontext.flags[Subnormal]: + newcontext._raise_error(Underflow) + + # propagate signals to the original context; _fix could + # have raised any of Overflow, Underflow, Subnormal, + # Inexact, Rounded, Clamped. Overflow needs the correct + # arguments. Note that the order of the exceptions is + # important here. + if newcontext.flags[Overflow]: + context._raise_error(Overflow, 'above Emax', ans._sign) + for exception in Underflow, Subnormal, Inexact, Rounded, Clamped: + if newcontext.flags[exception]: + context._raise_error(exception) + + else: + ans = ans._fix(context) + return ans def __rpow__(self, other, context=None): @@ -2450,14 +2489,15 @@ 'quantize result has too many digits for current context') # raise appropriate flags + if ans and ans.adjusted() < context.Emin: + context._raise_error(Subnormal) if ans._exp > self._exp: - context._raise_error(Rounded) if ans != self: context._raise_error(Inexact) - if ans and ans.adjusted() < context.Emin: - context._raise_error(Subnormal) + context._raise_error(Rounded) - # call to fix takes care of any necessary folddown + # call to fix takes care of any necessary folddown, and + # signals Clamped if necessary ans = ans._fix(context) return ans @@ -2556,10 +2596,10 @@ context = getcontext() if rounding is None: rounding = context.rounding - context._raise_error(Rounded) ans = self._rescale(0, rounding) if ans != self: context._raise_error(Inexact) + context._raise_error(Rounded) return ans def to_integral_value(self, rounding=None, context=None): @@ -3439,13 +3479,13 @@ context._raise_error(Overflow, 'Infinite result from next_toward', ans._sign) - context._raise_error(Rounded) context._raise_error(Inexact) + context._raise_error(Rounded) elif ans.adjusted() < context.Emin: context._raise_error(Underflow) context._raise_error(Subnormal) - context._raise_error(Rounded) context._raise_error(Inexact) + context._raise_error(Rounded) # if precision == 1 then we don't raise Clamped for a # result 0E-Etiny. if not ans: Modified: python/branches/release31-maint/Lib/test/test_decimal.py ============================================================================== --- python/branches/release31-maint/Lib/test/test_decimal.py (original) +++ python/branches/release31-maint/Lib/test/test_decimal.py Tue May 4 16:37:14 2010 @@ -41,6 +41,12 @@ # Useful Test Constant Signals = tuple(getcontext().flags.keys()) +# Signals ordered with respect to precedence: when an operation +# produces multiple signals, signals occurring later in the list +# should be handled before those occurring earlier in the list. +OrderedSignals = (Clamped, Rounded, Inexact, Subnormal, + Underflow, Overflow, DivisionByZero, InvalidOperation) + # Tests are built around these assumed context defaults. # test_main() restores the original context. def init(): @@ -346,6 +352,25 @@ else: self.fail("Did not raise %s in %s" % (error, s)) self.context.traps[error] = 0 + + # as above, but add traps cumulatively, to check precedence + ordered_errors = [e for e in OrderedSignals if e in theirexceptions] + for error in ordered_errors: + self.context.traps[error] = 1 + try: + funct(*vals) + except error: + pass + except Signals as e: + self.fail("Raised %s in %s; expected %s" % + (type(e), s, error)) + else: + self.fail("Did not raise %s in %s" % (error, s)) + # reset traps + for error in ordered_errors: + self.context.traps[error] = 0 + + if DEBUG: print("--", self.context) try: Modified: python/branches/release31-maint/Misc/NEWS ============================================================================== --- python/branches/release31-maint/Misc/NEWS (original) +++ python/branches/release31-maint/Misc/NEWS Tue May 4 16:37:14 2010 @@ -40,6 +40,12 @@ Library ------- +- Issue #8567: Fix precedence of signals in Decimal module: when a + Decimal operation raises multiple signals and more than one of those + signals is trapped, the specification determines the order in which + the signals should be handled. In many cases this order wasn't + being followed, leading to the wrong Python exception being raised. + - Issue #7865: The close() method of :mod:`io` objects should not swallow exceptions raised by the implicit flush(). Also ensure that calling close() several times is supported. Patch by Pascal Chambon. From python-checkins at python.org Tue May 4 18:17:50 2010 From: python-checkins at python.org (r.david.murray) Date: Tue, 4 May 2010 18:17:50 +0200 (CEST) Subject: [Python-checkins] r80757 - python/branches/py3k Message-ID: <20100504161750.22C29EE982@mail.python.org> Author: r.david.murray Date: Tue May 4 18:17:50 2010 New Revision: 80757 Log: Recorded merge of revisions 80458 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk Sean merged this in r84059. ........ r80458 | sean.reifschneider | 2010-04-25 02:31:23 -0400 (Sun, 25 Apr 2010) | 3 lines Fixing obscure syslog corner-case when sys.argv = None, syslog() would call openlog() for every logged message. ........ Modified: python/branches/py3k/ (props changed) From python-checkins at python.org Tue May 4 18:18:25 2010 From: python-checkins at python.org (mark.dickinson) Date: Tue, 4 May 2010 18:18:25 +0200 (CEST) Subject: [Python-checkins] r80758 - in python/trunk: Lib/test/test_builtin.py Misc/NEWS Python/bltinmodule.c Message-ID: <20100504161825.ADE16EE9AE@mail.python.org> Author: mark.dickinson Date: Tue May 4 18:18:25 2010 New Revision: 80758 Log: Issue #1533: fix inconsistency in range function argument processing: any non-float non-integer argument is now converted to an integer (if possible) using its __int__ method. Previously, only small arguments were treated this way; larger arguments (those whose __int__ was outside the range of a C long) would produce a TypeError. Patch by Alexander Belopolsky (with minor modifications). Modified: python/trunk/Lib/test/test_builtin.py python/trunk/Misc/NEWS python/trunk/Python/bltinmodule.c Modified: python/trunk/Lib/test/test_builtin.py ============================================================================== --- python/trunk/Lib/test/test_builtin.py (original) +++ python/trunk/Lib/test/test_builtin.py Tue May 4 18:18:25 2010 @@ -1080,6 +1080,56 @@ self.assertRaises(OverflowError, range, -sys.maxint, sys.maxint) self.assertRaises(OverflowError, range, 0, 2*sys.maxint) + bignum = 2*sys.maxint + smallnum = 42 + # Old-style user-defined class with __int__ method + class I0: + def __init__(self, n): + self.n = int(n) + def __int__(self): + return self.n + self.assertEqual(range(I0(bignum), I0(bignum + 1)), [bignum]) + self.assertEqual(range(I0(smallnum), I0(smallnum + 1)), [smallnum]) + + # New-style user-defined class with __int__ method + class I1(object): + def __init__(self, n): + self.n = int(n) + def __int__(self): + return self.n + self.assertEqual(range(I1(bignum), I1(bignum + 1)), [bignum]) + self.assertEqual(range(I1(smallnum), I1(smallnum + 1)), [smallnum]) + + # New-style user-defined class with failing __int__ method + class IX(object): + def __int__(self): + raise RuntimeError + self.assertRaises(RuntimeError, range, IX()) + + # New-style user-defined class with invalid __int__ method + class IN(object): + def __int__(self): + return "not a number" + self.assertRaises(TypeError, range, IN()) + + # Exercise various combinations of bad arguments, to check + # refcounting logic + self.assertRaises(TypeError, range, 0.0) + + self.assertRaises(TypeError, range, 0, 0.0) + self.assertRaises(TypeError, range, 0.0, 0) + self.assertRaises(TypeError, range, 0.0, 0.0) + + self.assertRaises(TypeError, range, 0, 0, 1.0) + self.assertRaises(TypeError, range, 0, 0.0, 1) + self.assertRaises(TypeError, range, 0, 0.0, 1.0) + self.assertRaises(TypeError, range, 0.0, 0, 1) + self.assertRaises(TypeError, range, 0.0, 0, 1.0) + self.assertRaises(TypeError, range, 0.0, 0.0, 1) + self.assertRaises(TypeError, range, 0.0, 0.0, 1.0) + + + def test_input_and_raw_input(self): self.write_testfile() fp = open(TESTFN, 'r') Modified: python/trunk/Misc/NEWS ============================================================================== --- python/trunk/Misc/NEWS (original) +++ python/trunk/Misc/NEWS Tue May 4 18:18:25 2010 @@ -12,6 +12,12 @@ Core and Builtins ----------------- +- Issue #1533: fix inconsistency in range function argument + processing: any non-float non-integer argument is now converted to + an integer (if possible) using its __int__ method. Previously, only + small arguments were treated this way; larger arguments (those whose + __int__ was outside the range of a C long) would produce a TypeError. + - Issue #8202: sys.argv[0] is now set to '-m' instead of '-c' when searching for the module file to be executed with the -m command line option Modified: python/trunk/Python/bltinmodule.c ============================================================================== --- python/trunk/Python/bltinmodule.c (original) +++ python/trunk/Python/bltinmodule.c Tue May 4 18:18:25 2010 @@ -1746,15 +1746,54 @@ return -1; } +/* Helper function for handle_range_longs. If arg is int or long + object, returns it with incremented reference count. If arg is + float, raises type error. As a last resort, creates a new int by + calling arg type's nb_int method if it is defined. Returns NULL + and sets exception on error. + + Returns a new reference to an int object. */ +static PyObject * +get_range_long_argument(PyObject *arg, const char *name) +{ + PyObject *v; + PyNumberMethods *nb; + if (PyInt_Check(arg) || PyLong_Check(arg)) { + Py_INCREF(arg); + return arg; + } + if (PyFloat_Check(arg) || + (nb = Py_TYPE(arg)->tp_as_number) == NULL || + nb->nb_int == NULL) { + PyErr_Format(PyExc_TypeError, + "range() integer %s argument expected, got %s.", + name, arg->ob_type->tp_name); + return NULL; + } + v = nb->nb_int(arg); + if (v == NULL) + return NULL; + if (PyInt_Check(v) || PyLong_Check(v)) + return v; + Py_DECREF(v); + PyErr_SetString(PyExc_TypeError, + "__int__ should return int object"); + return NULL; +} + /* An extension of builtin_range() that handles the case when PyLong * arguments are given. */ static PyObject * -handle_range_longs(PyObject *self, PyObject *args) +handle_range_longs(PyObject *self, PyObject *args) { - PyObject *ilow; + PyObject *ilow = NULL; PyObject *ihigh = NULL; PyObject *istep = NULL; + PyObject *low = NULL; + PyObject *high = NULL; + PyObject *step = NULL; + PyObject *curnum = NULL; PyObject *v = NULL; long bign; @@ -1773,7 +1812,7 @@ /* Figure out which way we were called, supply defaults, and be * sure to incref everything so that the decrefs at the end - * are correct. + * are correct. NB: ilow, ihigh and istep are borrowed references. */ assert(ilow != NULL); if (ihigh == NULL) { @@ -1781,47 +1820,35 @@ ihigh = ilow; ilow = NULL; } + + /* convert ihigh if necessary */ assert(ihigh != NULL); - Py_INCREF(ihigh); + high = get_range_long_argument(ihigh, "end"); + if (high == NULL) + goto Fail; /* ihigh correct now; do ilow */ - if (ilow == NULL) - ilow = zero; - Py_INCREF(ilow); - - /* ilow and ihigh correct now; do istep */ - if (istep == NULL) { - istep = PyLong_FromLong(1L); - if (istep == NULL) - goto Fail; + if (ilow == NULL) { + Py_INCREF(zero); + low = zero; } else { - Py_INCREF(istep); - } - - if (!PyInt_Check(ilow) && !PyLong_Check(ilow)) { - PyErr_Format(PyExc_TypeError, - "range() integer start argument expected, got %s.", - ilow->ob_type->tp_name); - goto Fail; + low = get_range_long_argument(ilow, "start"); + if (low == NULL) + goto Fail; } - if (!PyInt_Check(ihigh) && !PyLong_Check(ihigh)) { - PyErr_Format(PyExc_TypeError, - "range() integer end argument expected, got %s.", - ihigh->ob_type->tp_name); + /* ilow and ihigh correct now; do istep */ + if (istep == NULL) + step = PyLong_FromLong(1); + else + step = get_range_long_argument(istep, "step"); + if (step == NULL) goto Fail; - } - if (!PyInt_Check(istep) && !PyLong_Check(istep)) { - PyErr_Format(PyExc_TypeError, - "range() integer step argument expected, got %s.", - istep->ob_type->tp_name); + if (PyObject_Cmp(step, zero, &cmp_result) == -1) goto Fail; - } - if (PyObject_Cmp(istep, zero, &cmp_result) == -1) - goto Fail; if (cmp_result == 0) { PyErr_SetString(PyExc_ValueError, "range() step argument must not be zero"); @@ -1829,13 +1856,13 @@ } if (cmp_result > 0) - bign = get_len_of_range_longs(ilow, ihigh, istep); + bign = get_len_of_range_longs(low, high, step); else { - PyObject *neg_istep = PyNumber_Negative(istep); - if (neg_istep == NULL) + PyObject *neg_step = PyNumber_Negative(step); + if (neg_step == NULL) goto Fail; - bign = get_len_of_range_longs(ihigh, ilow, neg_istep); - Py_DECREF(neg_istep); + bign = get_len_of_range_longs(high, low, neg_step); + Py_DECREF(neg_step); } n = (Py_ssize_t)bign; @@ -1849,7 +1876,7 @@ if (v == NULL) goto Fail; - curnum = ilow; + curnum = low; Py_INCREF(curnum); for (i = 0; i < n; i++) { @@ -1860,24 +1887,24 @@ PyList_SET_ITEM(v, i, w); - tmp_num = PyNumber_Add(curnum, istep); + tmp_num = PyNumber_Add(curnum, step); if (tmp_num == NULL) goto Fail; Py_DECREF(curnum); curnum = tmp_num; } - Py_DECREF(ilow); - Py_DECREF(ihigh); - Py_DECREF(istep); + Py_DECREF(low); + Py_DECREF(high); + Py_DECREF(step); Py_DECREF(zero); Py_DECREF(curnum); return v; Fail: - Py_DECREF(ilow); - Py_DECREF(ihigh); - Py_XDECREF(istep); + Py_XDECREF(low); + Py_XDECREF(high); + Py_XDECREF(step); Py_DECREF(zero); Py_XDECREF(curnum); Py_XDECREF(v); From python-checkins at python.org Tue May 4 18:19:07 2010 From: python-checkins at python.org (mark.dickinson) Date: Tue, 4 May 2010 18:19:07 +0200 (CEST) Subject: [Python-checkins] r80759 - python/trunk/Python/bltinmodule.c Message-ID: <20100504161907.1BEF0E320@mail.python.org> Author: mark.dickinson Date: Tue May 4 18:19:06 2010 New Revision: 80759 Log: Fix trailing whitespace. Modified: python/trunk/Python/bltinmodule.c Modified: python/trunk/Python/bltinmodule.c ============================================================================== --- python/trunk/Python/bltinmodule.c (original) +++ python/trunk/Python/bltinmodule.c Tue May 4 18:19:06 2010 @@ -1784,7 +1784,7 @@ /* An extension of builtin_range() that handles the case when PyLong * arguments are given. */ static PyObject * -handle_range_longs(PyObject *self, PyObject *args) +handle_range_longs(PyObject *self, PyObject *args) { PyObject *ilow = NULL; PyObject *ihigh = NULL; From python-checkins at python.org Tue May 4 18:50:06 2010 From: python-checkins at python.org (mark.dickinson) Date: Tue, 4 May 2010 18:50:06 +0200 (CEST) Subject: [Python-checkins] r80760 - python/branches/py3k Message-ID: <20100504165006.DA649C907@mail.python.org> Author: mark.dickinson Date: Tue May 4 18:50:06 2010 New Revision: 80760 Log: Blocked revisions 80758-80759 via svnmerge ........ r80758 | mark.dickinson | 2010-05-04 17:18:25 +0100 (Tue, 04 May 2010) | 9 lines Issue #1533: fix inconsistency in range function argument processing: any non-float non-integer argument is now converted to an integer (if possible) using its __int__ method. Previously, only small arguments were treated this way; larger arguments (those whose __int__ was outside the range of a C long) would produce a TypeError. Patch by Alexander Belopolsky (with minor modifications). ........ r80759 | mark.dickinson | 2010-05-04 17:19:06 +0100 (Tue, 04 May 2010) | 1 line Fix trailing whitespace. ........ Modified: python/branches/py3k/ (props changed) From python-checkins at python.org Tue May 4 20:44:42 2010 From: python-checkins at python.org (thomas.heller) Date: Tue, 4 May 2010 20:44:42 +0200 (CEST) Subject: [Python-checkins] r80761 - in python/trunk: Lib/ctypes/test/test_win32.py Misc/NEWS Modules/_ctypes/callproc.c Modules/_ctypes/libffi_msvc/LICENSE Modules/_ctypes/libffi_msvc/README Modules/_ctypes/libffi_msvc/README.ctypes Modules/_ctypes/libffi_msvc/ffi.c Modules/_ctypes/libffi_msvc/ffi.h Modules/_ctypes/libffi_msvc/ffi_common.h Modules/_ctypes/libffi_msvc/fficonfig.h Modules/_ctypes/libffi_msvc/ffitarget.h Modules/_ctypes/libffi_msvc/prep_cif.c Modules/_ctypes/libffi_msvc/types.c Modules/_ctypes/libffi_msvc/win32.c Modules/_ctypes/libffi_msvc/win64.asm PCbuild/_ctypes.vcproj Message-ID: <20100504184442.EAD79EE9B4@mail.python.org> Author: thomas.heller Date: Tue May 4 20:44:42 2010 New Revision: 80761 Log: On Windows, ctypes does no longer check the stack before and after calling a foreign function. This allows to use the unmodified libffi library. Remove most files from _ctypes/libffi_msvc, only two include files stay (updated from _ctypes/libffi/...). Other files are used in the cross-platform _ctypes/libffi directory. Removed: python/trunk/Modules/_ctypes/libffi_msvc/LICENSE python/trunk/Modules/_ctypes/libffi_msvc/README python/trunk/Modules/_ctypes/libffi_msvc/README.ctypes python/trunk/Modules/_ctypes/libffi_msvc/ffi.c python/trunk/Modules/_ctypes/libffi_msvc/ffi_common.h python/trunk/Modules/_ctypes/libffi_msvc/ffitarget.h python/trunk/Modules/_ctypes/libffi_msvc/prep_cif.c python/trunk/Modules/_ctypes/libffi_msvc/types.c python/trunk/Modules/_ctypes/libffi_msvc/win32.c python/trunk/Modules/_ctypes/libffi_msvc/win64.asm Modified: python/trunk/Lib/ctypes/test/test_win32.py python/trunk/Misc/NEWS python/trunk/Modules/_ctypes/callproc.c python/trunk/Modules/_ctypes/libffi_msvc/ffi.h python/trunk/Modules/_ctypes/libffi_msvc/fficonfig.h python/trunk/PCbuild/_ctypes.vcproj Modified: python/trunk/Lib/ctypes/test/test_win32.py ============================================================================== --- python/trunk/Lib/ctypes/test/test_win32.py (original) +++ python/trunk/Lib/ctypes/test/test_win32.py Tue May 4 20:44:42 2010 @@ -6,32 +6,6 @@ import _ctypes_test -if sys.platform == "win32" and sizeof(c_void_p) == sizeof(c_int): - # Only windows 32-bit has different calling conventions. - - class WindowsTestCase(unittest.TestCase): - def test_callconv_1(self): - # Testing stdcall function - - IsWindow = windll.user32.IsWindow - # ValueError: Procedure probably called with not enough arguments (4 bytes missing) - self.assertRaises(ValueError, IsWindow) - - # This one should succeeed... - self.assertEqual(0, IsWindow(0)) - - # ValueError: Procedure probably called with too many arguments (8 bytes in excess) - self.assertRaises(ValueError, IsWindow, 0, 0, 0) - - def test_callconv_2(self): - # Calling stdcall function as cdecl - - IsWindow = cdll.user32.IsWindow - - # ValueError: Procedure called with not enough arguments (4 bytes missing) - # or wrong calling convention - self.assertRaises(ValueError, IsWindow, None) - if sys.platform == "win32": class FunctionCallTestCase(unittest.TestCase): Modified: python/trunk/Misc/NEWS ============================================================================== --- python/trunk/Misc/NEWS (original) +++ python/trunk/Misc/NEWS Tue May 4 20:44:42 2010 @@ -159,6 +159,10 @@ - Build the ossaudio extension on GNU/kFreeBSD. +- On Windows, ctypes does no longer check the stack before and after + calling a foreign function. This allows to use the unmodified + libffi library. + Tests ----- Modified: python/trunk/Modules/_ctypes/callproc.c ============================================================================== --- python/trunk/Modules/_ctypes/callproc.c (original) +++ python/trunk/Modules/_ctypes/callproc.c Tue May 4 20:44:42 2010 @@ -771,7 +771,6 @@ ffi_cif cif; int cc; #ifdef MS_WIN32 - int delta; #ifndef DONT_USE_SEH DWORD dwExceptionCode = 0; EXCEPTION_RECORD record; @@ -822,9 +821,8 @@ #ifndef DONT_USE_SEH __try { #endif - delta = #endif - ffi_call(&cif, (void *)pProc, resmem, avalues); + ffi_call(&cif, (void *)pProc, resmem, avalues); #ifdef MS_WIN32 #ifndef DONT_USE_SEH } @@ -856,35 +854,6 @@ return -1; } #endif -#ifdef MS_WIN64 - if (delta != 0) { - PyErr_Format(PyExc_RuntimeError, - "ffi_call failed with code %d", - delta); - return -1; - } -#else - if (delta < 0) { - if (flags & FUNCFLAG_CDECL) - PyErr_Format(PyExc_ValueError, - "Procedure called with not enough " - "arguments (%d bytes missing) " - "or wrong calling convention", - -delta); - else - PyErr_Format(PyExc_ValueError, - "Procedure probably called with not enough " - "arguments (%d bytes missing)", - -delta); - return -1; - } else if (delta > 0) { - PyErr_Format(PyExc_ValueError, - "Procedure probably called with too many " - "arguments (%d bytes in excess)", - delta); - return -1; - } -#endif #endif if ((flags & FUNCFLAG_PYTHONAPI) && PyErr_Occurred()) return -1; @@ -1161,11 +1130,7 @@ } for (i = 0; i < argcount; ++i) { atypes[i] = args[i].ffi_type; - if (atypes[i]->type == FFI_TYPE_STRUCT -#ifdef _WIN64 - && atypes[i]->size <= sizeof(void *) -#endif - ) + if (atypes[i]->type == FFI_TYPE_STRUCT) avalues[i] = (void *)args[i].value.p; else avalues[i] = (void *)&args[i].value; Deleted: python/trunk/Modules/_ctypes/libffi_msvc/LICENSE ============================================================================== --- python/trunk/Modules/_ctypes/libffi_msvc/LICENSE Tue May 4 20:44:42 2010 +++ (empty file) @@ -1,20 +0,0 @@ -libffi - Copyright (c) 1996-2003 Red Hat, Inc. - -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 CYGNUS SOLUTIONS 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. Deleted: python/trunk/Modules/_ctypes/libffi_msvc/README ============================================================================== --- python/trunk/Modules/_ctypes/libffi_msvc/README Tue May 4 20:44:42 2010 +++ (empty file) @@ -1,500 +0,0 @@ -This directory contains the libffi package, which is not part of GCC but -shipped with GCC as convenience. - -Status -====== - -libffi-2.00 has not been released yet! This is a development snapshot! - -libffi-1.20 was released on October 5, 1998. Check the libffi web -page for updates: . - - -What is libffi? -=============== - -Compilers for high level languages generate code that follow certain -conventions. These conventions are necessary, in part, for separate -compilation to work. One such convention is the "calling -convention". The "calling convention" is essentially a set of -assumptions made by the compiler about where function arguments will -be found on entry to a function. A "calling convention" also specifies -where the return value for a function is found. - -Some programs may not know at the time of compilation what arguments -are to be passed to a function. For instance, an interpreter may be -told at run-time about the number and types of arguments used to call -a given function. Libffi can be used in such programs to provide a -bridge from the interpreter program to compiled code. - -The libffi library provides a portable, high level programming -interface to various calling conventions. This allows a programmer to -call any function specified by a call interface description at run -time. - -Ffi stands for Foreign Function Interface. A foreign function -interface is the popular name for the interface that allows code -written in one language to call code written in another language. The -libffi library really only provides the lowest, machine dependent -layer of a fully featured foreign function interface. A layer must -exist above libffi that handles type conversions for values passed -between the two languages. - - -Supported Platforms and Prerequisites -===================================== - -Libffi has been ported to: - - SunOS 4.1.3 & Solaris 2.x (SPARC-V8, SPARC-V9) - - Irix 5.3 & 6.2 (System V/o32 & n32) - - Intel x86 - Linux (System V ABI) - - Alpha - Linux and OSF/1 - - m68k - Linux (System V ABI) - - PowerPC - Linux (System V ABI, Darwin, AIX) - - ARM - Linux (System V ABI) - -Libffi has been tested with the egcs 1.0.2 gcc compiler. Chances are -that other versions will work. Libffi has also been built and tested -with the SGI compiler tools. - -On PowerPC, the tests failed (see the note below). - -You must use GNU make to build libffi. SGI's make will not work. -Sun's probably won't either. - -If you port libffi to another platform, please let me know! I assume -that some will be easy (x86 NetBSD), and others will be more difficult -(HP). - - -Installing libffi -================= - -[Note: before actually performing any of these installation steps, - you may wish to read the "Platform Specific Notes" below.] - -First you must configure the distribution for your particular -system. Go to the directory you wish to build libffi in and run the -"configure" program found in the root directory of the libffi source -distribution. - -You may want to tell configure where to install the libffi library and -header files. To do that, use the --prefix configure switch. Libffi -will install under /usr/local by default. - -If you want to enable extra run-time debugging checks use the the ---enable-debug configure switch. This is useful when your program dies -mysteriously while using libffi. - -Another useful configure switch is --enable-purify-safety. Using this -will add some extra code which will suppress certain warnings when you -are using Purify with libffi. Only use this switch when using -Purify, as it will slow down the library. - -Configure has many other options. Use "configure --help" to see them all. - -Once configure has finished, type "make". Note that you must be using -GNU make. SGI's make will not work. Sun's probably won't either. -You can ftp GNU make from prep.ai.mit.edu:/pub/gnu. - -To ensure that libffi is working as advertised, type "make test". - -To install the library and header files, type "make install". - - -Using libffi -============ - - The Basics - ---------- - -Libffi assumes that you have a pointer to the function you wish to -call and that you know the number and types of arguments to pass it, -as well as the return type of the function. - -The first thing you must do is create an ffi_cif object that matches -the signature of the function you wish to call. The cif in ffi_cif -stands for Call InterFace. To prepare a call interface object, use the -following function: - -ffi_status ffi_prep_cif(ffi_cif *cif, ffi_abi abi, - unsigned int nargs, - ffi_type *rtype, ffi_type **atypes); - - CIF is a pointer to the call interface object you wish - to initialize. - - ABI is an enum that specifies the calling convention - to use for the call. FFI_DEFAULT_ABI defaults - to the system's native calling convention. Other - ABI's may be used with care. They are system - specific. - - NARGS is the number of arguments this function accepts. - libffi does not yet support vararg functions. - - RTYPE is a pointer to an ffi_type structure that represents - the return type of the function. Ffi_type objects - describe the types of values. libffi provides - ffi_type objects for many of the native C types: - signed int, unsigned int, signed char, unsigned char, - etc. There is also a pointer ffi_type object and - a void ffi_type. Use &ffi_type_void for functions that - don't return values. - - ATYPES is a vector of ffi_type pointers. ARGS must be NARGS long. - If NARGS is 0, this is ignored. - - -ffi_prep_cif will return a status code that you are responsible -for checking. It will be one of the following: - - FFI_OK - All is good. - - FFI_BAD_TYPEDEF - One of the ffi_type objects that ffi_prep_cif - came across is bad. - - -Before making the call, the VALUES vector should be initialized -with pointers to the appropriate argument values. - -To call the the function using the initialized ffi_cif, use the -ffi_call function: - -void ffi_call(ffi_cif *cif, void *fn, void *rvalue, void **avalues); - - CIF is a pointer to the ffi_cif initialized specifically - for this function. - - FN is a pointer to the function you want to call. - - RVALUE is a pointer to a chunk of memory that is to hold the - result of the function call. Currently, it must be - at least one word in size (except for the n32 version - under Irix 6.x, which must be a pointer to an 8 byte - aligned value (a long long). It must also be at least - word aligned (depending on the return type, and the - system's alignment requirements). If RTYPE is - &ffi_type_void, this is ignored. If RVALUE is NULL, - the return value is discarded. - - AVALUES is a vector of void* that point to the memory locations - holding the argument values for a call. - If NARGS is 0, this is ignored. - - -If you are expecting a return value from FN it will have been stored -at RVALUE. - - - - An Example - ---------- - -Here is a trivial example that calls puts() a few times. - - #include - #include - - int main() - { - ffi_cif cif; - ffi_type *args[1]; - void *values[1]; - char *s; - int rc; - - /* Initialize the argument info vectors */ - args[0] = &ffi_type_uint; - values[0] = &s; - - /* Initialize the cif */ - if (ffi_prep_cif(&cif, FFI_DEFAULT_ABI, 1, - &ffi_type_uint, args) == FFI_OK) - { - s = "Hello World!"; - ffi_call(&cif, puts, &rc, values); - /* rc now holds the result of the call to puts */ - - /* values holds a pointer to the function's arg, so to - call puts() again all we need to do is change the - value of s */ - s = "This is cool!"; - ffi_call(&cif, puts, &rc, values); - } - - return 0; - } - - - - Aggregate Types - --------------- - -Although libffi has no special support for unions or bit-fields, it is -perfectly happy passing structures back and forth. You must first -describe the structure to libffi by creating a new ffi_type object -for it. Here is the definition of ffi_type: - - typedef struct _ffi_type - { - unsigned size; - short alignment; - short type; - struct _ffi_type **elements; - } ffi_type; - -All structures must have type set to FFI_TYPE_STRUCT. You may set -size and alignment to 0. These will be calculated and reset to the -appropriate values by ffi_prep_cif(). - -elements is a NULL terminated array of pointers to ffi_type objects -that describe the type of the structure elements. These may, in turn, -be structure elements. - -The following example initializes a ffi_type object representing the -tm struct from Linux's time.h: - - struct tm { - int tm_sec; - int tm_min; - int tm_hour; - int tm_mday; - int tm_mon; - int tm_year; - int tm_wday; - int tm_yday; - int tm_isdst; - /* Those are for future use. */ - long int __tm_gmtoff__; - __const char *__tm_zone__; - }; - - { - ffi_type tm_type; - ffi_type *tm_type_elements[12]; - int i; - - tm_type.size = tm_type.alignment = 0; - tm_type.elements = &tm_type_elements; - - for (i = 0; i < 9; i++) - tm_type_elements[i] = &ffi_type_sint; - - tm_type_elements[9] = &ffi_type_slong; - tm_type_elements[10] = &ffi_type_pointer; - tm_type_elements[11] = NULL; - - /* tm_type can now be used to represent tm argument types and - return types for ffi_prep_cif() */ - } - - - -Platform Specific Notes -======================= - - Intel x86 - --------- - -There are no known problems with the x86 port. - - Sun SPARC - SunOS 4.1.3 & Solaris 2.x - ------------------------------------- - -You must use GNU Make to build libffi on Sun platforms. - - MIPS - Irix 5.3 & 6.x - --------------------- - -Irix 6.2 and better supports three different calling conventions: o32, -n32 and n64. Currently, libffi only supports both o32 and n32 under -Irix 6.x, but only o32 under Irix 5.3. Libffi will automatically be -configured for whichever calling convention it was built for. - -By default, the configure script will try to build libffi with the GNU -development tools. To build libffi with the SGI development tools, set -the environment variable CC to either "cc -32" or "cc -n32" before -running configure under Irix 6.x (depending on whether you want an o32 -or n32 library), or just "cc" for Irix 5.3. - -With the n32 calling convention, when returning structures smaller -than 16 bytes, be sure to provide an RVALUE that is 8 byte aligned. -Here's one way of forcing this: - - double struct_storage[2]; - my_small_struct *s = (my_small_struct *) struct_storage; - /* Use s for RVALUE */ - -If you don't do this you are liable to get spurious bus errors. - -"long long" values are not supported yet. - -You must use GNU Make to build libffi on SGI platforms. - - ARM - System V ABI - ------------------ - -The ARM port was performed on a NetWinder running ARM Linux ELF -(2.0.31) and gcc 2.8.1. - - - - PowerPC System V ABI - -------------------- - -There are two `System V ABI's which libffi implements for PowerPC. -They differ only in how small structures are returned from functions. - -In the FFI_SYSV version, structures that are 8 bytes or smaller are -returned in registers. This is what GCC does when it is configured -for solaris, and is what the System V ABI I have (dated September -1995) says. - -In the FFI_GCC_SYSV version, all structures are returned the same way: -by passing a pointer as the first argument to the function. This is -what GCC does when it is configured for linux or a generic sysv -target. - -EGCS 1.0.1 (and probably other versions of EGCS/GCC) also has a -inconsistency with the SysV ABI: When a procedure is called with many -floating-point arguments, some of them get put on the stack. They are -all supposed to be stored in double-precision format, even if they are -only single-precision, but EGCS stores single-precision arguments as -single-precision anyway. This causes one test to fail (the `many -arguments' test). - - -What's With The Crazy Comments? -=============================== - -You might notice a number of cryptic comments in the code, delimited -by /*@ and @*/. These are annotations read by the program LCLint, a -tool for statically checking C programs. You can read all about it at -. - - -History -======= - -1.20 Oct-5-98 - Raffaele Sena produces ARM port. - -1.19 Oct-5-98 - Fixed x86 long double and long long return support. - m68k bug fixes from Andreas Schwab. - Patch for DU assembler compatibility for the Alpha from Richard - Henderson. - -1.18 Apr-17-98 - Bug fixes and MIPS configuration changes. - -1.17 Feb-24-98 - Bug fixes and m68k port from Andreas Schwab. PowerPC port from - Geoffrey Keating. Various bug x86, Sparc and MIPS bug fixes. - -1.16 Feb-11-98 - Richard Henderson produces Alpha port. - -1.15 Dec-4-97 - Fixed an n32 ABI bug. New libtool, auto* support. - -1.14 May-13-97 - libtool is now used to generate shared and static libraries. - Fixed a minor portability problem reported by Russ McManus - . - -1.13 Dec-2-96 - Added --enable-purify-safety to keep Purify from complaining - about certain low level code. - Sparc fix for calling functions with < 6 args. - Linux x86 a.out fix. - -1.12 Nov-22-96 - Added missing ffi_type_void, needed for supporting void return - types. Fixed test case for non MIPS machines. Cygnus Support - is now Cygnus Solutions. - -1.11 Oct-30-96 - Added notes about GNU make. - -1.10 Oct-29-96 - Added configuration fix for non GNU compilers. - -1.09 Oct-29-96 - Added --enable-debug configure switch. Clean-ups based on LCLint - feedback. ffi_mips.h is always installed. Many configuration - fixes. Fixed ffitest.c for sparc builds. - -1.08 Oct-15-96 - Fixed n32 problem. Many clean-ups. - -1.07 Oct-14-96 - Gordon Irlam rewrites v8.S again. Bug fixes. - -1.06 Oct-14-96 - Gordon Irlam improved the sparc port. - -1.05 Oct-14-96 - Interface changes based on feedback. - -1.04 Oct-11-96 - Sparc port complete (modulo struct passing bug). - -1.03 Oct-10-96 - Passing struct args, and returning struct values works for - all architectures/calling conventions. Expanded tests. - -1.02 Oct-9-96 - Added SGI n32 support. Fixed bugs in both o32 and Linux support. - Added "make test". - -1.01 Oct-8-96 - Fixed float passing bug in mips version. Restructured some - of the code. Builds cleanly with SGI tools. - -1.00 Oct-7-96 - First release. No public announcement. - - -Authors & Credits -================= - -libffi was written by Anthony Green . - -Portions of libffi were derived from Gianni Mariani's free gencall -library for Silicon Graphics machines. - -The closure mechanism was designed and implemented by Kresten Krab -Thorup. - -The Sparc port was derived from code contributed by the fine folks at -Visible Decisions Inc . Further enhancements were -made by Gordon Irlam at Cygnus Solutions . - -The Alpha port was written by Richard Henderson at Cygnus Solutions. - -Andreas Schwab ported libffi to m68k Linux and provided a number of -bug fixes. - -Geoffrey Keating ported libffi to the PowerPC. - -Raffaele Sena ported libffi to the ARM. - -Jesper Skov and Andrew Haley both did more than their fair share of -stepping through the code and tracking down bugs. - -Thanks also to Tom Tromey for bug fixes and configuration help. - -Thanks to Jim Blandy, who provided some useful feedback on the libffi -interface. - -If you have a problem, or have found a bug, please send a note to -green at cygnus.com. Deleted: python/trunk/Modules/_ctypes/libffi_msvc/README.ctypes ============================================================================== --- python/trunk/Modules/_ctypes/libffi_msvc/README.ctypes Tue May 4 20:44:42 2010 +++ (empty file) @@ -1,7 +0,0 @@ -The purpose is to hack the libffi sources so that they can be compiled -with MSVC, and to extend them so that they have the features I need -for ctypes. - -I retrieved the libffi sources from the gcc cvs repository on -2004-01-27. Then I did 'configure' in a 'build' subdirectory on a x86 -linux system, and copied the files I found useful. Deleted: python/trunk/Modules/_ctypes/libffi_msvc/ffi.c ============================================================================== --- python/trunk/Modules/_ctypes/libffi_msvc/ffi.c Tue May 4 20:44:42 2010 +++ (empty file) @@ -1,457 +0,0 @@ -/* ----------------------------------------------------------------------- - ffi.c - Copyright (c) 1996, 1998, 1999, 2001 Red Hat, Inc. - Copyright (c) 2002 Ranjit Mathew - Copyright (c) 2002 Bo Thorsen - Copyright (c) 2002 Roger Sayle - - x86 Foreign Function Interface - - 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 CYGNUS SOLUTIONS 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. - ----------------------------------------------------------------------- */ - -#include -#include - -#include - -/* ffi_prep_args is called by the assembly routine once stack space - has been allocated for the function's arguments */ - -extern void Py_FatalError(const char *msg); - -/*@-exportheader@*/ -void ffi_prep_args(char *stack, extended_cif *ecif) -/*@=exportheader@*/ -{ - register unsigned int i; - register void **p_argv; - register char *argp; - register ffi_type **p_arg; - - argp = stack; - if (ecif->cif->rtype->type == FFI_TYPE_STRUCT) - { - *(void **) argp = ecif->rvalue; - argp += sizeof(void *); - } - - p_argv = ecif->avalue; - - for (i = ecif->cif->nargs, p_arg = ecif->cif->arg_types; - i != 0; - i--, p_arg++) - { - size_t z; - - /* Align if necessary */ - if ((sizeof(void *) - 1) & (size_t) argp) - argp = (char *) ALIGN(argp, sizeof(void *)); - - z = (*p_arg)->size; - if (z < sizeof(int)) - { - z = sizeof(int); - switch ((*p_arg)->type) - { - case FFI_TYPE_SINT8: - *(signed int *) argp = (signed int)*(SINT8 *)(* p_argv); - break; - - case FFI_TYPE_UINT8: - *(unsigned int *) argp = (unsigned int)*(UINT8 *)(* p_argv); - break; - - case FFI_TYPE_SINT16: - *(signed int *) argp = (signed int)*(SINT16 *)(* p_argv); - break; - - case FFI_TYPE_UINT16: - *(unsigned int *) argp = (unsigned int)*(UINT16 *)(* p_argv); - break; - - case FFI_TYPE_SINT32: - *(signed int *) argp = (signed int)*(SINT32 *)(* p_argv); - break; - - case FFI_TYPE_UINT32: - *(unsigned int *) argp = (unsigned int)*(UINT32 *)(* p_argv); - break; - - case FFI_TYPE_STRUCT: - *(unsigned int *) argp = (unsigned int)*(UINT32 *)(* p_argv); - break; - - default: - FFI_ASSERT(0); - } - } - else - { - memcpy(argp, *p_argv, z); - } - p_argv++; - argp += z; - } - - if (argp - stack > ecif->cif->bytes) - { - Py_FatalError("FFI BUG: not enough stack space for arguments"); - } - return; -} - -/* Perform machine dependent cif processing */ -ffi_status ffi_prep_cif_machdep(ffi_cif *cif) -{ - /* Set the return type flag */ - switch (cif->rtype->type) - { - case FFI_TYPE_VOID: - case FFI_TYPE_STRUCT: - case FFI_TYPE_SINT64: - case FFI_TYPE_FLOAT: - case FFI_TYPE_DOUBLE: - case FFI_TYPE_LONGDOUBLE: - cif->flags = (unsigned) cif->rtype->type; - break; - - case FFI_TYPE_UINT64: -#ifdef _WIN64 - case FFI_TYPE_POINTER: -#endif - cif->flags = FFI_TYPE_SINT64; - break; - - default: - cif->flags = FFI_TYPE_INT; - break; - } - - return FFI_OK; -} - -#ifdef _WIN32 -extern int -ffi_call_x86(void (*)(char *, extended_cif *), - /*@out@*/ extended_cif *, - unsigned, unsigned, - /*@out@*/ unsigned *, - void (*fn)()); -#endif - -#ifdef _WIN64 -extern int -ffi_call_AMD64(void (*)(char *, extended_cif *), - /*@out@*/ extended_cif *, - unsigned, unsigned, - /*@out@*/ unsigned *, - void (*fn)()); -#endif - -int -ffi_call(/*@dependent@*/ ffi_cif *cif, - void (*fn)(), - /*@out@*/ void *rvalue, - /*@dependent@*/ void **avalue) -{ - extended_cif ecif; - - ecif.cif = cif; - ecif.avalue = avalue; - - /* If the return value is a struct and we don't have a return */ - /* value address then we need to make one */ - - if ((rvalue == NULL) && - (cif->rtype->type == FFI_TYPE_STRUCT)) - { - /*@-sysunrecog@*/ - ecif.rvalue = alloca(cif->rtype->size); - /*@=sysunrecog@*/ - } - else - ecif.rvalue = rvalue; - - - switch (cif->abi) - { -#if !defined(_WIN64) - case FFI_SYSV: - case FFI_STDCALL: - return ffi_call_x86(ffi_prep_args, &ecif, cif->bytes, - cif->flags, ecif.rvalue, fn); - break; -#else - case FFI_SYSV: - /*@-usedef@*/ - /* Function call needs at least 40 bytes stack size, on win64 AMD64 */ - return ffi_call_AMD64(ffi_prep_args, &ecif, cif->bytes ? cif->bytes : 40, - cif->flags, ecif.rvalue, fn); - /*@=usedef@*/ - break; -#endif - - default: - FFI_ASSERT(0); - break; - } - return -1; /* theller: Hrm. */ -} - - -/** private members **/ - -static void ffi_prep_incoming_args_SYSV (char *stack, void **ret, - void** args, ffi_cif* cif); -/* This function is jumped to by the trampoline */ - -#ifdef _WIN64 -void * -#else -static void __fastcall -#endif -ffi_closure_SYSV (ffi_closure *closure, int *argp) -{ - // this is our return value storage - long double res; - - // our various things... - ffi_cif *cif; - void **arg_area; - unsigned short rtype; - void *resp = (void*)&res; - void *args = &argp[1]; - - cif = closure->cif; - arg_area = (void**) alloca (cif->nargs * sizeof (void*)); - - /* this call will initialize ARG_AREA, such that each - * element in that array points to the corresponding - * value on the stack; and if the function returns - * a structure, it will re-set RESP to point to the - * structure return address. */ - - ffi_prep_incoming_args_SYSV(args, (void**)&resp, arg_area, cif); - - (closure->fun) (cif, resp, arg_area, closure->user_data); - - rtype = cif->flags; - -#if defined(_WIN32) && !defined(_WIN64) -#ifdef _MSC_VER - /* now, do a generic return based on the value of rtype */ - if (rtype == FFI_TYPE_INT) - { - _asm mov eax, resp ; - _asm mov eax, [eax] ; - } - else if (rtype == FFI_TYPE_FLOAT) - { - _asm mov eax, resp ; - _asm fld DWORD PTR [eax] ; -// asm ("flds (%0)" : : "r" (resp) : "st" ); - } - else if (rtype == FFI_TYPE_DOUBLE) - { - _asm mov eax, resp ; - _asm fld QWORD PTR [eax] ; -// asm ("fldl (%0)" : : "r" (resp) : "st", "st(1)" ); - } - else if (rtype == FFI_TYPE_LONGDOUBLE) - { -// asm ("fldt (%0)" : : "r" (resp) : "st", "st(1)" ); - } - else if (rtype == FFI_TYPE_SINT64) - { - _asm mov edx, resp ; - _asm mov eax, [edx] ; - _asm mov edx, [edx + 4] ; -// asm ("movl 0(%0),%%eax;" -// "movl 4(%0),%%edx" -// : : "r"(resp) -// : "eax", "edx"); - } -#else - /* now, do a generic return based on the value of rtype */ - if (rtype == FFI_TYPE_INT) - { - asm ("movl (%0),%%eax" : : "r" (resp) : "eax"); - } - else if (rtype == FFI_TYPE_FLOAT) - { - asm ("flds (%0)" : : "r" (resp) : "st" ); - } - else if (rtype == FFI_TYPE_DOUBLE) - { - asm ("fldl (%0)" : : "r" (resp) : "st", "st(1)" ); - } - else if (rtype == FFI_TYPE_LONGDOUBLE) - { - asm ("fldt (%0)" : : "r" (resp) : "st", "st(1)" ); - } - else if (rtype == FFI_TYPE_SINT64) - { - asm ("movl 0(%0),%%eax;" - "movl 4(%0),%%edx" - : : "r"(resp) - : "eax", "edx"); - } -#endif -#endif - -#ifdef _WIN64 - /* The result is returned in rax. This does the right thing for - result types except for floats; we have to 'mov xmm0, rax' in the - caller to correct this. - */ - return *(void **)resp; -#endif -} - -/*@-exportheader@*/ -static void -ffi_prep_incoming_args_SYSV(char *stack, void **rvalue, - void **avalue, ffi_cif *cif) -/*@=exportheader@*/ -{ - register unsigned int i; - register void **p_argv; - register char *argp; - register ffi_type **p_arg; - - argp = stack; - - if ( cif->rtype->type == FFI_TYPE_STRUCT ) { - *rvalue = *(void **) argp; - argp += 4; - } - - p_argv = avalue; - - for (i = cif->nargs, p_arg = cif->arg_types; (i != 0); i--, p_arg++) - { - size_t z; - - /* Align if necessary */ - if ((sizeof(char *) - 1) & (size_t) argp) { - argp = (char *) ALIGN(argp, sizeof(char*)); - } - - z = (*p_arg)->size; - - /* because we're little endian, this is what it turns into. */ - - *p_argv = (void*) argp; - - p_argv++; - argp += z; - } - - return; -} - -/* the cif must already be prep'ed */ -extern void ffi_closure_OUTER(); - -ffi_status -ffi_prep_closure (ffi_closure* closure, - ffi_cif* cif, - void (*fun)(ffi_cif*,void*,void**,void*), - void *user_data) -{ - short bytes; - char *tramp; -#ifdef _WIN64 - int mask; -#endif - FFI_ASSERT (cif->abi == FFI_SYSV); - - if (cif->abi == FFI_SYSV) - bytes = 0; -#if !defined(_WIN64) - else if (cif->abi == FFI_STDCALL) - bytes = cif->bytes; -#endif - else - return FFI_BAD_ABI; - - tramp = &closure->tramp[0]; - -#define BYTES(text) memcpy(tramp, text, sizeof(text)), tramp += sizeof(text)-1 -#define POINTER(x) *(void**)tramp = (void*)(x), tramp += sizeof(void*) -#define SHORT(x) *(short*)tramp = x, tramp += sizeof(short) -#define INT(x) *(int*)tramp = x, tramp += sizeof(int) - -#ifdef _WIN64 - if (cif->nargs >= 1 && - (cif->arg_types[0]->type == FFI_TYPE_FLOAT - || cif->arg_types[0]->type == FFI_TYPE_DOUBLE)) - mask |= 1; - if (cif->nargs >= 2 && - (cif->arg_types[1]->type == FFI_TYPE_FLOAT - || cif->arg_types[1]->type == FFI_TYPE_DOUBLE)) - mask |= 2; - if (cif->nargs >= 3 && - (cif->arg_types[2]->type == FFI_TYPE_FLOAT - || cif->arg_types[2]->type == FFI_TYPE_DOUBLE)) - mask |= 4; - if (cif->nargs >= 4 && - (cif->arg_types[3]->type == FFI_TYPE_FLOAT - || cif->arg_types[3]->type == FFI_TYPE_DOUBLE)) - mask |= 8; - - /* 41 BB ---- mov r11d,mask */ - BYTES("\x41\xBB"); INT(mask); - - /* 48 B8 -------- mov rax, closure */ - BYTES("\x48\xB8"); POINTER(closure); - - /* 49 BA -------- mov r10, ffi_closure_OUTER */ - BYTES("\x49\xBA"); POINTER(ffi_closure_OUTER); - - /* 41 FF E2 jmp r10 */ - BYTES("\x41\xFF\xE2"); - -#else - - /* mov ecx, closure */ - BYTES("\xb9"); POINTER(closure); - - /* mov edx, esp */ - BYTES("\x8b\xd4"); - - /* call ffi_closure_SYSV */ - BYTES("\xe8"); POINTER((char*)&ffi_closure_SYSV - (tramp + 4)); - - /* ret bytes */ - BYTES("\xc2"); - SHORT(bytes); - -#endif - - if (tramp - &closure->tramp[0] > FFI_TRAMPOLINE_SIZE) - Py_FatalError("FFI_TRAMPOLINE_SIZE too small in " __FILE__); - - closure->cif = cif; - closure->user_data = user_data; - closure->fun = fun; - - return FFI_OK; -} Modified: python/trunk/Modules/_ctypes/libffi_msvc/ffi.h ============================================================================== --- python/trunk/Modules/_ctypes/libffi_msvc/ffi.h (original) +++ python/trunk/Modules/_ctypes/libffi_msvc/ffi.h Tue May 4 20:44:42 2010 @@ -1,5 +1,5 @@ /* -----------------------------------------------------------------*-C-*- - libffi 2.00-beta - Copyright (c) 1996-2003 Red Hat, Inc. + libffi @VERSION@ - Copyright (c) 1996-2003, 2007, 2008 Red Hat, Inc. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the @@ -12,13 +12,14 @@ 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 CYGNUS SOLUTIONS 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. + 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. ----------------------------------------------------------------------- */ @@ -56,7 +57,7 @@ #endif /* Specify which architecture libffi is configured for. */ -//XXX #define X86 +/* #define @TARGET@ */ /* ---- System configuration information --------------------------------- */ @@ -64,6 +65,10 @@ #ifndef LIBFFI_ASM +#ifdef _MSC_VER +#define __attribute__(X) +#endif + #include #include @@ -79,12 +84,21 @@ # ifdef __GNUC__ # define FFI_LONG_LONG_MAX __LONG_LONG_MAX__ # endif -# ifdef _MSC_VER -# define FFI_LONG_LONG_MAX _I64_MAX -# endif # endif #endif +/* The closure code assumes that this works on pointers, i.e. a size_t */ +/* can hold a pointer. */ + +typedef struct _ffi_type +{ + size_t size; + unsigned short alignment; + unsigned short type; + struct _ffi_type **elements; +} ffi_type; + +#ifndef LIBFFI_HIDE_BASIC_TYPES #if SCHAR_MAX == 127 # define ffi_type_uchar ffi_type_uint8 # define ffi_type_schar ffi_type_sint8 @@ -115,26 +129,23 @@ #error "int size not supported" #endif -#define ffi_type_ulong ffi_type_uint64 -#define ffi_type_slong ffi_type_sint64 #if LONG_MAX == 2147483647 # if FFI_LONG_LONG_MAX != 9223372036854775807 - #error "no 64-bit data type supported" + #error "no 64-bit data type supported" # endif #elif LONG_MAX != 9223372036854775807 #error "long size not supported" #endif -/* The closure code assumes that this works on pointers, i.e. a size_t */ -/* can hold a pointer. */ - -typedef struct _ffi_type -{ - size_t size; - unsigned short alignment; - unsigned short type; - /*@null@*/ struct _ffi_type **elements; -} ffi_type; +#if LONG_MAX == 2147483647 +# define ffi_type_ulong ffi_type_uint32 +# define ffi_type_slong ffi_type_sint32 +#elif LONG_MAX == 9223372036854775807 +# define ffi_type_ulong ffi_type_uint64 +# define ffi_type_slong ffi_type_sint64 +#else + #error "long size not supported" +#endif /* These are defined in types.c */ extern ffi_type ffi_type_void; @@ -148,14 +159,19 @@ extern ffi_type ffi_type_sint64; extern ffi_type ffi_type_float; extern ffi_type ffi_type_double; -extern ffi_type ffi_type_longdouble; extern ffi_type ffi_type_pointer; +#if HAVE_LONG_DOUBLE +extern ffi_type ffi_type_longdouble; +#else +#define ffi_type_longdouble ffi_type_double +#endif +#endif /* LIBFFI_HIDE_BASIC_TYPES */ typedef enum { FFI_OK = 0, FFI_BAD_TYPEDEF, - FFI_BAD_ABI + FFI_BAD_ABI } ffi_status; typedef unsigned FFI_TYPE; @@ -163,8 +179,8 @@ typedef struct { ffi_abi abi; unsigned nargs; - /*@dependent@*/ ffi_type **arg_types; - /*@dependent@*/ ffi_type *rtype; + ffi_type **arg_types; + ffi_type *rtype; unsigned bytes; unsigned flags; #ifdef FFI_EXTRA_CIF_FIELDS @@ -174,10 +190,16 @@ /* ---- Definitions for the raw API -------------------------------------- */ -#ifdef _WIN64 -#define FFI_SIZEOF_ARG 8 -#else -#define FFI_SIZEOF_ARG 4 +#ifndef FFI_SIZEOF_ARG +# if LONG_MAX == 2147483647 +# define FFI_SIZEOF_ARG 4 +# elif LONG_MAX == 9223372036854775807 +# define FFI_SIZEOF_ARG 8 +# endif +#endif + +#ifndef FFI_SIZEOF_JAVA_RAW +# define FFI_SIZEOF_JAVA_RAW FFI_SIZEOF_ARG #endif typedef union { @@ -188,10 +210,25 @@ void* ptr; } ffi_raw; -void ffi_raw_call (/*@dependent@*/ ffi_cif *cif, - void (*fn)(), - /*@out@*/ void *rvalue, - /*@dependent@*/ ffi_raw *avalue); +#if FFI_SIZEOF_JAVA_RAW == 4 && FFI_SIZEOF_ARG == 8 +/* This is a special case for mips64/n32 ABI (and perhaps others) where + sizeof(void *) is 4 and FFI_SIZEOF_ARG is 8. */ +typedef union { + signed int sint; + unsigned int uint; + float flt; + char data[FFI_SIZEOF_JAVA_RAW]; + void* ptr; +} ffi_java_raw; +#else +typedef ffi_raw ffi_java_raw; +#endif + + +void ffi_raw_call (ffi_cif *cif, + void (*fn)(void), + void *rvalue, + ffi_raw *avalue); void ffi_ptrarray_to_raw (ffi_cif *cif, void **args, ffi_raw *raw); void ffi_raw_to_ptrarray (ffi_cif *cif, ffi_raw *raw, void **args); @@ -201,25 +238,35 @@ /* packing, even on 64-bit machines. I.e. on 64-bit machines */ /* longs and doubles are followed by an empty 64-bit word. */ -void ffi_java_raw_call (/*@dependent@*/ ffi_cif *cif, - void (*fn)(), - /*@out@*/ void *rvalue, - /*@dependent@*/ ffi_raw *avalue); +void ffi_java_raw_call (ffi_cif *cif, + void (*fn)(void), + void *rvalue, + ffi_java_raw *avalue); -void ffi_java_ptrarray_to_raw (ffi_cif *cif, void **args, ffi_raw *raw); -void ffi_java_raw_to_ptrarray (ffi_cif *cif, ffi_raw *raw, void **args); +void ffi_java_ptrarray_to_raw (ffi_cif *cif, void **args, ffi_java_raw *raw); +void ffi_java_raw_to_ptrarray (ffi_cif *cif, ffi_java_raw *raw, void **args); size_t ffi_java_raw_size (ffi_cif *cif); /* ---- Definitions for closures ----------------------------------------- */ #if FFI_CLOSURES +#ifdef _MSC_VER +__declspec(align(8)) +#endif typedef struct { char tramp[FFI_TRAMPOLINE_SIZE]; ffi_cif *cif; void (*fun)(ffi_cif*,void*,void**,void*); void *user_data; +#ifdef __GNUC__ +} ffi_closure __attribute__((aligned (8))); +#else } ffi_closure; +#endif + +void *ffi_closure_alloc (size_t size, void **code); +void ffi_closure_free (void *); ffi_status ffi_prep_closure (ffi_closure*, @@ -227,6 +274,13 @@ void (*fun)(ffi_cif*,void*,void**,void*), void *user_data); +ffi_status +ffi_prep_closure_loc (ffi_closure*, + ffi_cif *, + void (*fun)(ffi_cif*,void*,void**,void*), + void *user_data, + void*codeloc); + typedef struct { char tramp[FFI_TRAMPOLINE_SIZE]; @@ -248,6 +302,27 @@ } ffi_raw_closure; +typedef struct { + char tramp[FFI_TRAMPOLINE_SIZE]; + + ffi_cif *cif; + +#if !FFI_NATIVE_RAW_API + + /* if this is enabled, then a raw closure has the same layout + as a regular closure. We use this to install an intermediate + handler to do the transaltion, void** -> ffi_raw*. */ + + void (*translate_args)(ffi_cif*,void*,void**,void*); + void *this_closure; + +#endif + + void (*fun)(ffi_cif*,void*,ffi_java_raw*,void*); + void *user_data; + +} ffi_java_raw_closure; + ffi_status ffi_prep_raw_closure (ffi_raw_closure*, ffi_cif *cif, @@ -255,29 +330,42 @@ void *user_data); ffi_status -ffi_prep_java_raw_closure (ffi_raw_closure*, +ffi_prep_raw_closure_loc (ffi_raw_closure*, + ffi_cif *cif, + void (*fun)(ffi_cif*,void*,ffi_raw*,void*), + void *user_data, + void *codeloc); + +ffi_status +ffi_prep_java_raw_closure (ffi_java_raw_closure*, ffi_cif *cif, - void (*fun)(ffi_cif*,void*,ffi_raw*,void*), + void (*fun)(ffi_cif*,void*,ffi_java_raw*,void*), void *user_data); +ffi_status +ffi_prep_java_raw_closure_loc (ffi_java_raw_closure*, + ffi_cif *cif, + void (*fun)(ffi_cif*,void*,ffi_java_raw*,void*), + void *user_data, + void *codeloc); + #endif /* FFI_CLOSURES */ /* ---- Public interface definition -------------------------------------- */ -ffi_status ffi_prep_cif(/*@out@*/ /*@partial@*/ ffi_cif *cif, +ffi_status ffi_prep_cif(ffi_cif *cif, ffi_abi abi, - unsigned int nargs, - /*@dependent@*/ /*@out@*/ /*@partial@*/ ffi_type *rtype, - /*@dependent@*/ ffi_type **atypes); - -int -ffi_call(/*@dependent@*/ ffi_cif *cif, - void (*fn)(), - /*@out@*/ void *rvalue, - /*@dependent@*/ void **avalue); + unsigned int nargs, + ffi_type *rtype, + ffi_type **atypes); + +void ffi_call(ffi_cif *cif, + void (*fn)(void), + void *rvalue, + void **avalue); /* Useful for eliminating compiler warnings */ -#define FFI_FN(f) ((void (*)())f) +#define FFI_FN(f) ((void (*)(void))f) /* ---- Definitions shared with assembly code ---------------------------- */ @@ -288,7 +376,7 @@ #define FFI_TYPE_INT 1 #define FFI_TYPE_FLOAT 2 #define FFI_TYPE_DOUBLE 3 -#if 1 +#if HAVE_LONG_DOUBLE #define FFI_TYPE_LONGDOUBLE 4 #else #define FFI_TYPE_LONGDOUBLE FFI_TYPE_DOUBLE @@ -312,4 +400,3 @@ #endif #endif - Deleted: python/trunk/Modules/_ctypes/libffi_msvc/ffi_common.h ============================================================================== --- python/trunk/Modules/_ctypes/libffi_msvc/ffi_common.h Tue May 4 20:44:42 2010 +++ (empty file) @@ -1,77 +0,0 @@ -/* ----------------------------------------------------------------------- - ffi_common.h - Copyright (c) 1996 Red Hat, Inc. - - Common internal definitions and macros. Only necessary for building - libffi. - ----------------------------------------------------------------------- */ - -#ifndef FFI_COMMON_H -#define FFI_COMMON_H - -#ifdef __cplusplus -extern "C" { -#endif - -#include -#include - -/* Check for the existence of memcpy. */ -#if STDC_HEADERS -# include -#else -# ifndef HAVE_MEMCPY -# define memcpy(d, s, n) bcopy ((s), (d), (n)) -# endif -#endif - -#if defined(FFI_DEBUG) -#include -#endif - -#ifdef FFI_DEBUG -/*@exits@*/ void ffi_assert(/*@temp@*/ char *expr, /*@temp@*/ char *file, int line); -void ffi_stop_here(void); -void ffi_type_test(/*@temp@*/ /*@out@*/ ffi_type *a, /*@temp@*/ char *file, int line); - -#define FFI_ASSERT(x) ((x) ? (void)0 : ffi_assert(#x, __FILE__,__LINE__)) -#define FFI_ASSERT_AT(x, f, l) ((x) ? 0 : ffi_assert(#x, (f), (l))) -#define FFI_ASSERT_VALID_TYPE(x) ffi_type_test (x, __FILE__, __LINE__) -#else -#define FFI_ASSERT(x) -#define FFI_ASSERT_AT(x, f, l) -#define FFI_ASSERT_VALID_TYPE(x) -#endif - -#define ALIGN(v, a) (((((size_t) (v))-1) | ((a)-1))+1) - -/* Perform machine dependent cif processing */ -ffi_status ffi_prep_cif_machdep(ffi_cif *cif); - -/* Extended cif, used in callback from assembly routine */ -typedef struct -{ - /*@dependent@*/ ffi_cif *cif; - /*@dependent@*/ void *rvalue; - /*@dependent@*/ void **avalue; -} extended_cif; - -/* Terse sized type definitions. */ -typedef unsigned int UINT8 __attribute__((__mode__(__QI__))); -typedef signed int SINT8 __attribute__((__mode__(__QI__))); -typedef unsigned int UINT16 __attribute__((__mode__(__HI__))); -typedef signed int SINT16 __attribute__((__mode__(__HI__))); -typedef unsigned int UINT32 __attribute__((__mode__(__SI__))); -typedef signed int SINT32 __attribute__((__mode__(__SI__))); -typedef unsigned int UINT64 __attribute__((__mode__(__DI__))); -typedef signed int SINT64 __attribute__((__mode__(__DI__))); - -typedef float FLOAT32; - - -#ifdef __cplusplus -} -#endif - -#endif - - Modified: python/trunk/Modules/_ctypes/libffi_msvc/fficonfig.h ============================================================================== --- python/trunk/Modules/_ctypes/libffi_msvc/fficonfig.h (original) +++ python/trunk/Modules/_ctypes/libffi_msvc/fficonfig.h Tue May 4 20:44:42 2010 @@ -1,96 +1,186 @@ /* fficonfig.h. Originally created by configure, now hand_maintained for MSVC. */ -/* fficonfig.h. Generated automatically by configure. */ -/* fficonfig.h.in. Generated automatically from configure.in by autoheader. */ +/* fficonfig.h.in. Generated from configure.ac by autoheader. */ -/* Define this for MSVC, but not for mingw32! */ -#ifdef _MSC_VER -#define __attribute__(x) /* */ -#endif -#define alloca _alloca +/* Define if building universal (internal helper macro) */ +/* #undef AC_APPLE_UNIVERSAL_BUILD */ -/*----------------------------------------------------------------*/ +/* Define to one of `_getb67', `GETB67', `getb67' for Cray-2 and Cray-YMP + systems. This function is required for `alloca.c' support on those systems. + */ +/* #undef CRAY_STACKSEG_END */ -/* Define if using alloca.c. */ +/* Define to 1 if using `alloca.c'. */ /* #undef C_ALLOCA */ -/* Define to one of _getb67, GETB67, getb67 for Cray-2 and Cray-YMP systems. - This function is required for alloca.c support on those systems. */ -/* #undef CRAY_STACKSEG_END */ +/* Define to the flags needed for the .section .eh_frame directive. */ +/* #undef EH_FRAME_FLAGS */ -/* Define if you have alloca, as a function or macro. */ -#define HAVE_ALLOCA 1 +/* Define this if you want extra debugging. */ +/* #undef FFI_DEBUG */ -/* Define if you have and it should be used (not on Ultrix). */ -/* #define HAVE_ALLOCA_H 1 */ +/* Cannot use malloc on this target, so, we revert to alternative means */ +/* #undef FFI_MMAP_EXEC_WRIT */ -/* If using the C implementation of alloca, define if you know the - direction of stack growth for your system; otherwise it will be - automatically deduced at run-time. - STACK_DIRECTION > 0 => grows toward higher addresses - STACK_DIRECTION < 0 => grows toward lower addresses - STACK_DIRECTION = 0 => direction of growth unknown - */ -/* #undef STACK_DIRECTION */ +/* Define this is you do not want support for the raw API. */ +#define FFI_NO_RAW_API 1 -/* Define if you have the ANSI C header files. */ -#define STDC_HEADERS 1 +/* Define this is you do not want support for aggregate types. */ +/* #undef FFI_NO_STRUCTS */ -/* Define if you have the memcpy function. */ -#define HAVE_MEMCPY 1 +/* Define to 1 if you have `alloca', as a function or macro. */ +#define HAVE_ALLOCA 1 -/* Define if read-only mmap of a plain file works. */ -//#define HAVE_MMAP_FILE 1 +/* Define to 1 if you have and it should be used (not on Ultrix). + */ +/* #undef HAVE_ALLOCA_H */ -/* Define if mmap of /dev/zero works. */ -//#define HAVE_MMAP_DEV_ZERO 1 +/* Define if your assembler supports .cfi_* directives. */ +/* #undef HAVE_AS_CFI_PSEUDO_OP */ -/* Define if mmap with MAP_ANON(YMOUS) works. */ -//#define HAVE_MMAP_ANON 1 +/* Define if your assembler supports .register. */ +/* #undef HAVE_AS_REGISTER_PSEUDO_OP */ -/* The number of bytes in type double */ -#define SIZEOF_DOUBLE 8 +/* Define if your assembler and linker support unaligned PC relative relocs. + */ +/* #undef HAVE_AS_SPARC_UA_PCREL */ -/* The number of bytes in type long double */ -#define SIZEOF_LONG_DOUBLE 12 +/* Define if your assembler supports PC relative relocs. */ +/* #undef HAVE_AS_X86_PCREL */ + +/* Define to 1 if you have the header file. */ +/* #undef HAVE_DLFCN_H */ + +/* Define if __attribute__((visibility("hidden"))) is supported. */ +/* #undef HAVE_HIDDEN_VISIBILITY_ATTRIBUTE */ + +/* Define to 1 if you have the header file. */ +/* #undef HAVE_INTTYPES_H */ /* Define if you have the long double type and it is bigger than a double */ -#define HAVE_LONG_DOUBLE 1 +/* #undef HAVE_LONG_DOUBLE */ -/* whether byteorder is bigendian */ -/* #undef WORDS_BIGENDIAN */ +/* Define to 1 if you have the `memcpy' function. */ +#define HAVE_MEMCPY 1 -/* Define if the host machine stores words of multi-word integers in - big-endian order. */ -/* #undef HOST_WORDS_BIG_ENDIAN */ +/* Define to 1 if you have the header file. */ +/* #undef HAVE_MEMORY_H */ -/* 1234 = LIL_ENDIAN, 4321 = BIGENDIAN */ -#define BYTEORDER 1234 +/* Define to 1 if you have the `mmap' function. */ +/* #undef HAVE_MMAP */ -/* Define if your assembler and linker support unaligned PC relative relocs. */ -/* #undef HAVE_AS_SPARC_UA_PCREL */ +/* Define if mmap with MAP_ANON(YMOUS) works. */ +/* #undef HAVE_MMAP_ANON */ -/* Define if your assembler supports .register. */ -/* #undef HAVE_AS_REGISTER_PSEUDO_OP */ +/* Define if mmap of /dev/zero works. */ +/* #undef HAVE_MMAP_DEV_ZERO */ + +/* Define if read-only mmap of a plain file works. */ +/* #undef HAVE_MMAP_FILE */ /* Define if .eh_frame sections should be read-only. */ /* #undef HAVE_RO_EH_FRAME */ -/* Define to the flags needed for the .section .eh_frame directive. */ -/* #define EH_FRAME_FLAGS "aw" */ +/* Define to 1 if you have the header file. */ +#undef HAVE_STDINT_H -/* Define to the flags needed for the .section .eh_frame directive. */ -/* #define EH_FRAME_FLAGS "aw" */ +/* Define to 1 if you have the header file. */ +#undef HAVE_STDLIB_H -/* Define this if you want extra debugging. */ -/* #undef FFI_DEBUG */ +/* Define to 1 if you have the header file. */ +#undef HAVE_STRINGS_H -/* Define this is you do not want support for aggregate types. */ -/* #undef FFI_NO_STRUCTS */ +/* Define to 1 if you have the header file. */ +#undef HAVE_STRING_H -/* Define this is you do not want support for the raw API. */ -/* #undef FFI_NO_RAW_API */ +/* Define to 1 if you have the header file. */ +/* #undef HAVE_SYS_MMAN_H */ + +/* Define to 1 if you have the header file. */ +/* #undef HAVE_SYS_STAT_H */ + +/* Define to 1 if you have the header file. */ +/* #undef HAVE_SYS_TYPES_H */ + +/* Define to 1 if you have the header file. */ +/* #undef HAVE_UNISTD_H */ + +/* Define to the sub-directory in which libtool stores uninstalled libraries. + */ +/* #undef LT_OBJDIR */ + +/* Define to 1 if your C compiler doesn't accept -c and -o together. */ +/* #undef NO_MINUS_C_MINUS_O */ + +/* Name of package */ +/* #undef PACKAGE */ + +/* Define to the address where bug reports for this package should be sent. */ +/* #undef PACKAGE_BUGREPORT */ + +/* Define to the full name of this package. */ +/* #undef PACKAGE_NAME */ + +/* Define to the full name and version of this package. */ +/* #undef PACKAGE_STRING */ + +/* Define to the one symbol short name of this package. */ +/* #undef PACKAGE_TARNAME */ + +/* Define to the home page for this package. */ +/* #undef PACKAGE_URL */ + +/* Define to the version of this package. */ +/* #undef PACKAGE_VERSION */ -/* Define this if you are using Purify and want to suppress spurious messages. */ +/* The size of `double', as computed by sizeof. */ +#define SIZEOF_DOUBLE 8 + +/* The size of `long double', as computed by sizeof. */ +#undef SIZEOF_LONG_DOUBLE + +/* If using the C implementation of alloca, define if you know the + direction of stack growth for your system; otherwise it will be + automatically deduced at runtime. + STACK_DIRECTION > 0 => grows toward higher addresses + STACK_DIRECTION < 0 => grows toward lower addresses + STACK_DIRECTION = 0 => direction of growth unknown */ +/* #undef STACK_DIRECTION */ + +/* Define to 1 if you have the ANSI C header files. */ +#define STDC_HEADERS 1 + +/* Define this if you are using Purify and want to suppress spurious messages. + */ /* #undef USING_PURIFY */ +/* Version number of package */ +/* #undef VERSION */ + +/* Define WORDS_BIGENDIAN to 1 if your processor stores words with the most + significant byte first (like Motorola and SPARC, unlike Intel). */ +#if defined AC_APPLE_UNIVERSAL_BUILD +# if defined __BIG_ENDIAN__ +# define WORDS_BIGENDIAN 1 +# endif +#else +# ifndef WORDS_BIGENDIAN +# undef WORDS_BIGENDIAN +# endif +#endif + + +#ifdef HAVE_HIDDEN_VISIBILITY_ATTRIBUTE +#ifdef LIBFFI_ASM +#define FFI_HIDDEN(name) .hidden name +#else +#define FFI_HIDDEN __attribute__ ((visibility ("hidden"))) +#endif +#else +#ifdef LIBFFI_ASM +#define FFI_HIDDEN(name) +#else +#define FFI_HIDDEN +#endif +#endif + Deleted: python/trunk/Modules/_ctypes/libffi_msvc/ffitarget.h ============================================================================== --- python/trunk/Modules/_ctypes/libffi_msvc/ffitarget.h Tue May 4 20:44:42 2010 +++ (empty file) @@ -1,85 +0,0 @@ -/* -----------------------------------------------------------------*-C-*- - ffitarget.h - Copyright (c) 1996-2003 Red Hat, Inc. - Target configuration macros for x86 and x86-64. - - 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 CYGNUS SOLUTIONS 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. - - ----------------------------------------------------------------------- */ - -#ifndef LIBFFI_TARGET_H -#define LIBFFI_TARGET_H - -/* ---- System specific configurations ----------------------------------- */ - -#if defined (X86_64) && defined (__i386__) -#undef X86_64 -#define X86 -#endif - -/* ---- Generic type definitions ----------------------------------------- */ - -#ifndef LIBFFI_ASM -#ifndef _WIN64 -typedef unsigned long ffi_arg; -#else -typedef unsigned __int64 ffi_arg; -#endif -typedef signed long ffi_sarg; - -typedef enum ffi_abi { - FFI_FIRST_ABI = 0, - - /* ---- Intel x86 Win32 ---------- */ - FFI_SYSV, -#ifndef _WIN64 - FFI_STDCALL, -#endif - /* TODO: Add fastcall support for the sake of completeness */ - FFI_DEFAULT_ABI = FFI_SYSV, - - /* ---- Intel x86 and AMD x86-64 - */ -/* #if !defined(X86_WIN32) && (defined(__i386__) || defined(__x86_64__)) */ -/* FFI_SYSV, */ -/* FFI_UNIX64,*/ /* Unix variants all use the same ABI for x86-64 */ -/* #ifdef __i386__ */ -/* FFI_DEFAULT_ABI = FFI_SYSV, */ -/* #else */ -/* FFI_DEFAULT_ABI = FFI_UNIX64, */ -/* #endif */ -/* #endif */ - - FFI_LAST_ABI = FFI_DEFAULT_ABI + 1 -} ffi_abi; -#endif - -/* ---- Definitions for closures ----------------------------------------- */ - -#define FFI_CLOSURES 1 - -#ifdef _WIN64 -#define FFI_TRAMPOLINE_SIZE 29 -#define FFI_NATIVE_RAW_API 0 -#else -#define FFI_TRAMPOLINE_SIZE 15 -#define FFI_NATIVE_RAW_API 1 /* x86 has native raw api support */ -#endif - -#endif - Deleted: python/trunk/Modules/_ctypes/libffi_msvc/prep_cif.c ============================================================================== --- python/trunk/Modules/_ctypes/libffi_msvc/prep_cif.c Tue May 4 20:44:42 2010 +++ (empty file) @@ -1,175 +0,0 @@ -/* ----------------------------------------------------------------------- - prep_cif.c - Copyright (c) 1996, 1998 Red Hat, Inc. - - 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 CYGNUS SOLUTIONS 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. - ----------------------------------------------------------------------- */ - -#include -#include -#include - - -/* Round up to FFI_SIZEOF_ARG. */ - -#define STACK_ARG_SIZE(x) ALIGN(x, FFI_SIZEOF_ARG) - -/* Perform machine independent initialization of aggregate type - specifications. */ - -static ffi_status initialize_aggregate(/*@out@*/ ffi_type *arg) -{ - ffi_type **ptr; - - FFI_ASSERT(arg != NULL); - - /*@-usedef@*/ - - FFI_ASSERT(arg->elements != NULL); - FFI_ASSERT(arg->size == 0); - FFI_ASSERT(arg->alignment == 0); - - ptr = &(arg->elements[0]); - - while ((*ptr) != NULL) - { - if (((*ptr)->size == 0) && (initialize_aggregate((*ptr)) != FFI_OK)) - return FFI_BAD_TYPEDEF; - - /* Perform a sanity check on the argument type */ - FFI_ASSERT_VALID_TYPE(*ptr); - - arg->size = ALIGN(arg->size, (*ptr)->alignment); - arg->size += (*ptr)->size; - - arg->alignment = (arg->alignment > (*ptr)->alignment) ? - arg->alignment : (*ptr)->alignment; - - ptr++; - } - - /* Structure size includes tail padding. This is important for - structures that fit in one register on ABIs like the PowerPC64 - Linux ABI that right justify small structs in a register. - It's also needed for nested structure layout, for example - struct A { long a; char b; }; struct B { struct A x; char y; }; - should find y at an offset of 2*sizeof(long) and result in a - total size of 3*sizeof(long). */ - arg->size = ALIGN (arg->size, arg->alignment); - - if (arg->size == 0) - return FFI_BAD_TYPEDEF; - else - return FFI_OK; - - /*@=usedef@*/ -} - -/* Perform machine independent ffi_cif preparation, then call - machine dependent routine. */ - -ffi_status ffi_prep_cif(/*@out@*/ /*@partial@*/ ffi_cif *cif, - ffi_abi abi, unsigned int nargs, - /*@dependent@*/ /*@out@*/ /*@partial@*/ ffi_type *rtype, - /*@dependent@*/ ffi_type **atypes) -{ - unsigned bytes = 0; - unsigned int i; - ffi_type **ptr; - - FFI_ASSERT(cif != NULL); - FFI_ASSERT((abi > FFI_FIRST_ABI) && (abi <= FFI_DEFAULT_ABI)); - - cif->abi = abi; - cif->arg_types = atypes; - cif->nargs = nargs; - cif->rtype = rtype; - - cif->flags = 0; - - /* Initialize the return type if necessary */ - /*@-usedef@*/ - if ((cif->rtype->size == 0) && (initialize_aggregate(cif->rtype) != FFI_OK)) - return FFI_BAD_TYPEDEF; - /*@=usedef@*/ - - /* Perform a sanity check on the return type */ - FFI_ASSERT_VALID_TYPE(cif->rtype); - - /* x86-64 and s390 stack space allocation is handled in prep_machdep. */ -#if !defined M68K && !defined __x86_64__ && !defined S390 - /* Make space for the return structure pointer */ - if (cif->rtype->type == FFI_TYPE_STRUCT - /* MSVC returns small structures in registers. But we have a different - workaround: pretend int32 or int64 return type, and converting to - structure afterwards. */ -#ifdef SPARC - && (cif->abi != FFI_V9 || cif->rtype->size > 32) -#endif - ) - bytes = STACK_ARG_SIZE(sizeof(void*)); -#endif - - for (ptr = cif->arg_types, i = cif->nargs; i > 0; i--, ptr++) - { - - /* Initialize any uninitialized aggregate type definitions */ - if (((*ptr)->size == 0) && (initialize_aggregate((*ptr)) != FFI_OK)) - return FFI_BAD_TYPEDEF; - - /* Perform a sanity check on the argument type, do this - check after the initialization. */ - FFI_ASSERT_VALID_TYPE(*ptr); - -#if !defined __x86_64__ && !defined S390 -#ifdef SPARC - if (((*ptr)->type == FFI_TYPE_STRUCT - && ((*ptr)->size > 16 || cif->abi != FFI_V9)) - || ((*ptr)->type == FFI_TYPE_LONGDOUBLE - && cif->abi != FFI_V9)) - bytes += sizeof(void*); - else -#endif - { -#if !defined(_MSC_VER) && !defined(__MINGW32__) - /* Don't know if this is a libffi bug or not. At least on - Windows with MSVC, function call parameters are *not* - aligned in the same way as structure fields are, they are - only aligned in integer boundaries. - - This doesn't do any harm for cdecl functions and closures, - since the caller cleans up the stack, but it is wrong for - stdcall functions where the callee cleans. - */ - - /* Add any padding if necessary */ - if (((*ptr)->alignment - 1) & bytes) - bytes = ALIGN(bytes, (*ptr)->alignment); - -#endif - bytes += STACK_ARG_SIZE((*ptr)->size); - } -#endif - } - - cif->bytes = bytes; - - /* Perform machine dependent cif processing */ - return ffi_prep_cif_machdep(cif); -} Deleted: python/trunk/Modules/_ctypes/libffi_msvc/types.c ============================================================================== --- python/trunk/Modules/_ctypes/libffi_msvc/types.c Tue May 4 20:44:42 2010 +++ (empty file) @@ -1,104 +0,0 @@ -/* ----------------------------------------------------------------------- - types.c - Copyright (c) 1996, 1998 Red Hat, Inc. - - Predefined ffi_types needed by libffi. - - 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 CYGNUS SOLUTIONS 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. - ----------------------------------------------------------------------- */ - -#include -#include - -/* Type definitions */ - -#define FFI_INTEGRAL_TYPEDEF(n, s, a, t) ffi_type ffi_type_##n = { s, a, t, NULL } -#define FFI_AGGREGATE_TYPEDEF(n, e) ffi_type ffi_type_##n = { 0, 0, FFI_TYPE_STRUCT, e } - -/* Size and alignment are fake here. They must not be 0. */ -FFI_INTEGRAL_TYPEDEF(void, 1, 1, FFI_TYPE_VOID); - -FFI_INTEGRAL_TYPEDEF(uint8, 1, 1, FFI_TYPE_UINT8); -FFI_INTEGRAL_TYPEDEF(sint8, 1, 1, FFI_TYPE_SINT8); -FFI_INTEGRAL_TYPEDEF(uint16, 2, 2, FFI_TYPE_UINT16); -FFI_INTEGRAL_TYPEDEF(sint16, 2, 2, FFI_TYPE_SINT16); -FFI_INTEGRAL_TYPEDEF(uint32, 4, 4, FFI_TYPE_UINT32); -FFI_INTEGRAL_TYPEDEF(sint32, 4, 4, FFI_TYPE_SINT32); -FFI_INTEGRAL_TYPEDEF(float, 4, 4, FFI_TYPE_FLOAT); - -#if defined ALPHA || defined SPARC64 || defined X86_64 || defined S390X \ - || defined IA64 - -FFI_INTEGRAL_TYPEDEF(pointer, 8, 8, FFI_TYPE_POINTER); - -#else - -FFI_INTEGRAL_TYPEDEF(pointer, 4, 4, FFI_TYPE_POINTER); - -#endif - -#if defined X86 || defined X86_WIN32 || defined ARM || defined M68K - -FFI_INTEGRAL_TYPEDEF(uint64, 8, 4, FFI_TYPE_UINT64); -FFI_INTEGRAL_TYPEDEF(sint64, 8, 4, FFI_TYPE_SINT64); - -#elif defined SH - -FFI_INTEGRAL_TYPEDEF(uint64, 8, 4, FFI_TYPE_UINT64); -FFI_INTEGRAL_TYPEDEF(sint64, 8, 4, FFI_TYPE_SINT64); - -#else - -FFI_INTEGRAL_TYPEDEF(uint64, 8, 8, FFI_TYPE_UINT64); -FFI_INTEGRAL_TYPEDEF(sint64, 8, 8, FFI_TYPE_SINT64); - -#endif - - -#if defined X86 || defined X86_WIN32 || defined M68K - -FFI_INTEGRAL_TYPEDEF(double, 8, 4, FFI_TYPE_DOUBLE); -FFI_INTEGRAL_TYPEDEF(longdouble, 12, 4, FFI_TYPE_LONGDOUBLE); - -#elif defined ARM || defined SH || defined POWERPC_AIX || defined POWERPC_DARWIN - -FFI_INTEGRAL_TYPEDEF(double, 8, 4, FFI_TYPE_DOUBLE); -FFI_INTEGRAL_TYPEDEF(longdouble, 8, 4, FFI_TYPE_LONGDOUBLE); - -#elif defined SPARC - -FFI_INTEGRAL_TYPEDEF(double, 8, 8, FFI_TYPE_DOUBLE); -#ifdef SPARC64 -FFI_INTEGRAL_TYPEDEF(longdouble, 16, 16, FFI_TYPE_LONGDOUBLE); -#else -FFI_INTEGRAL_TYPEDEF(longdouble, 16, 8, FFI_TYPE_LONGDOUBLE); -#endif - -#elif defined X86_64 - -FFI_INTEGRAL_TYPEDEF(double, 8, 8, FFI_TYPE_DOUBLE); -FFI_INTEGRAL_TYPEDEF(longdouble, 16, 16, FFI_TYPE_LONGDOUBLE); - -#else - -FFI_INTEGRAL_TYPEDEF(double, 8, 8, FFI_TYPE_DOUBLE); -FFI_INTEGRAL_TYPEDEF(longdouble, 8, 8, FFI_TYPE_LONGDOUBLE); - -#endif - Deleted: python/trunk/Modules/_ctypes/libffi_msvc/win32.c ============================================================================== --- python/trunk/Modules/_ctypes/libffi_msvc/win32.c Tue May 4 20:44:42 2010 +++ (empty file) @@ -1,162 +0,0 @@ -/* ----------------------------------------------------------------------- - win32.S - Copyright (c) 1996, 1998, 2001, 2002 Red Hat, Inc. - Copyright (c) 2001 John Beniton - Copyright (c) 2002 Ranjit Mathew - - - X86 Foreign Function Interface - - 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 CYGNUS SOLUTIONS 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. - ----------------------------------------------------------------------- */ - -/* theller: almost verbatim translation from gas syntax to MSVC inline - assembler code. */ - -/* theller: ffi_call_x86 now returns an integer - the difference of the stack - pointer before and after the function call. If everything is ok, zero is - returned. If stdcall functions are passed the wrong number of arguments, - the difference will be nonzero. */ - -#include -#include - -__declspec(naked) int -ffi_call_x86(void (* prepfunc)(char *, extended_cif *), /* 8 */ - extended_cif *ecif, /* 12 */ - unsigned bytes, /* 16 */ - unsigned flags, /* 20 */ - unsigned *rvalue, /* 24 */ - void (*fn)()) /* 28 */ -{ - _asm { - push ebp - mov ebp, esp - - push esi // NEW: this register must be preserved across function calls -// XXX SAVE ESP NOW! - mov esi, esp // save stack pointer before the call - -// Make room for all of the new args. - mov ecx, [ebp+16] - sub esp, ecx // sub esp, bytes - - mov eax, esp - -// Place all of the ffi_prep_args in position - push [ebp + 12] // ecif - push eax - call [ebp + 8] // prepfunc - -// Return stack to previous state and call the function - add esp, 8 -// FIXME: Align the stack to a 128-bit boundary to avoid -// potential performance hits. - call [ebp + 28] - -// Load ecif->cif->abi - mov ecx, [ebp + 12] - mov ecx, [ecx]ecif.cif - mov ecx, [ecx]ecif.cif.abi - - cmp ecx, FFI_STDCALL - je noclean -// STDCALL: Remove the space we pushed for the args - mov ecx, [ebp + 16] - add esp, ecx -// CDECL: Caller has already cleaned the stack -noclean: -// Check that esp has the same value as before! - sub esi, esp - -// Load %ecx with the return type code - mov ecx, [ebp + 20] - -// If the return value pointer is NULL, assume no return value. -/* - Intel asm is weird. We have to explicitely specify 'DWORD PTR' in the nexr instruction, - otherwise only one BYTE will be compared (instead of a DWORD)! - */ - cmp DWORD PTR [ebp + 24], 0 - jne sc_retint - -// Even if there is no space for the return value, we are -// obliged to handle floating-point values. - cmp ecx, FFI_TYPE_FLOAT - jne sc_noretval -// fstp %st(0) - fstp st(0) - - jmp sc_epilogue - -sc_retint: - cmp ecx, FFI_TYPE_INT - jne sc_retfloat -// # Load %ecx with the pointer to storage for the return value - mov ecx, [ebp + 24] - mov [ecx + 0], eax - jmp sc_epilogue - -sc_retfloat: - cmp ecx, FFI_TYPE_FLOAT - jne sc_retdouble -// Load %ecx with the pointer to storage for the return value - mov ecx, [ebp+24] -// fstps (%ecx) - fstp DWORD PTR [ecx] - jmp sc_epilogue - -sc_retdouble: - cmp ecx, FFI_TYPE_DOUBLE - jne sc_retlongdouble -// movl 24(%ebp),%ecx - mov ecx, [ebp+24] - fstp QWORD PTR [ecx] - jmp sc_epilogue - - jmp sc_retlongdouble // avoid warning about unused label -sc_retlongdouble: - cmp ecx, FFI_TYPE_LONGDOUBLE - jne sc_retint64 -// Load %ecx with the pointer to storage for the return value - mov ecx, [ebp+24] -// fstpt (%ecx) - fstp QWORD PTR [ecx] /* XXX ??? */ - jmp sc_epilogue - -sc_retint64: - cmp ecx, FFI_TYPE_SINT64 - jne sc_retstruct -// Load %ecx with the pointer to storage for the return value - mov ecx, [ebp+24] - mov [ecx+0], eax - mov [ecx+4], edx - -sc_retstruct: -// Nothing to do! - -sc_noretval: -sc_epilogue: - mov eax, esi - pop esi // NEW restore: must be preserved across function calls - mov esp, ebp - pop ebp - ret - } -} Deleted: python/trunk/Modules/_ctypes/libffi_msvc/win64.asm ============================================================================== --- python/trunk/Modules/_ctypes/libffi_msvc/win64.asm Tue May 4 20:44:42 2010 +++ (empty file) @@ -1,156 +0,0 @@ -PUBLIC ffi_call_AMD64 - -EXTRN __chkstk:NEAR -EXTRN ffi_closure_SYSV:NEAR - -_TEXT SEGMENT - -;;; ffi_closure_OUTER will be called with these registers set: -;;; rax points to 'closure' -;;; r11 contains a bit mask that specifies which of the -;;; first four parameters are float or double -;;; -;;; It must move the parameters passed in registers to their stack location, -;;; call ffi_closure_SYSV for the actual work, then return the result. -;;; -ffi_closure_OUTER PROC FRAME - ;; save actual arguments to their stack space. - test r11, 1 - jne first_is_float - mov QWORD PTR [rsp+8], rcx - jmp second -first_is_float: - movlpd QWORD PTR [rsp+8], xmm0 - -second: - test r11, 2 - jne second_is_float - mov QWORD PTR [rsp+16], rdx - jmp third -second_is_float: - movlpd QWORD PTR [rsp+16], xmm1 - -third: - test r11, 4 - jne third_is_float - mov QWORD PTR [rsp+24], r8 - jmp forth -third_is_float: - movlpd QWORD PTR [rsp+24], xmm2 - -forth: - test r11, 8 - jne forth_is_float - mov QWORD PTR [rsp+32], r9 - jmp done -forth_is_float: - movlpd QWORD PTR [rsp+32], xmm3 - -done: -.ALLOCSTACK 40 - sub rsp, 40 -.ENDPROLOG - mov rcx, rax ; context is first parameter - mov rdx, rsp ; stack is second parameter - add rdx, 40 ; correct our own area - mov rax, ffi_closure_SYSV - call rax ; call the real closure function - ;; Here, code is missing that handles float return values - add rsp, 40 - movd xmm0, rax ; In case the closure returned a float. - ret 0 -ffi_closure_OUTER ENDP - - -;;; ffi_call_AMD64 - -stack$ = 0 -prepfunc$ = 32 -ecif$ = 40 -bytes$ = 48 -flags$ = 56 -rvalue$ = 64 -fn$ = 72 - -ffi_call_AMD64 PROC FRAME - - mov QWORD PTR [rsp+32], r9 - mov QWORD PTR [rsp+24], r8 - mov QWORD PTR [rsp+16], rdx - mov QWORD PTR [rsp+8], rcx -.PUSHREG rbp - push rbp -.ALLOCSTACK 48 - sub rsp, 48 ; 00000030H -.SETFRAME rbp, 32 - lea rbp, QWORD PTR [rsp+32] -.ENDPROLOG - - mov eax, DWORD PTR bytes$[rbp] - add rax, 15 - and rax, -16 - call __chkstk - sub rsp, rax - lea rax, QWORD PTR [rsp+32] - mov QWORD PTR stack$[rbp], rax - - mov rdx, QWORD PTR ecif$[rbp] - mov rcx, QWORD PTR stack$[rbp] - call QWORD PTR prepfunc$[rbp] - - mov rsp, QWORD PTR stack$[rbp] - - movlpd xmm3, QWORD PTR [rsp+24] - movd r9, xmm3 - - movlpd xmm2, QWORD PTR [rsp+16] - movd r8, xmm2 - - movlpd xmm1, QWORD PTR [rsp+8] - movd rdx, xmm1 - - movlpd xmm0, QWORD PTR [rsp] - movd rcx, xmm0 - - call QWORD PTR fn$[rbp] -ret_int$: - cmp DWORD PTR flags$[rbp], 1 ; FFI_TYPE_INT - jne ret_float$ - - mov rcx, QWORD PTR rvalue$[rbp] - mov DWORD PTR [rcx], eax - jmp SHORT ret_nothing$ - -ret_float$: - cmp DWORD PTR flags$[rbp], 2 ; FFI_TYPE_FLOAT - jne SHORT ret_double$ - - mov rax, QWORD PTR rvalue$[rbp] - movlpd QWORD PTR [rax], xmm0 - jmp SHORT ret_nothing$ - -ret_double$: - cmp DWORD PTR flags$[rbp], 3 ; FFI_TYPE_DOUBLE - jne SHORT ret_int64$ - - mov rax, QWORD PTR rvalue$[rbp] - movlpd QWORD PTR [rax], xmm0 - jmp SHORT ret_nothing$ - -ret_int64$: - cmp DWORD PTR flags$[rbp], 12 ; FFI_TYPE_SINT64 - jne ret_nothing$ - - mov rcx, QWORD PTR rvalue$[rbp] - mov QWORD PTR [rcx], rax - jmp SHORT ret_nothing$ - -ret_nothing$: - xor eax, eax - - lea rsp, QWORD PTR [rbp+16] - pop rbp - ret 0 -ffi_call_AMD64 ENDP -_TEXT ENDS -END Modified: python/trunk/PCbuild/_ctypes.vcproj ============================================================================== --- python/trunk/PCbuild/_ctypes.vcproj (original) +++ python/trunk/PCbuild/_ctypes.vcproj Tue May 4 20:44:42 2010 @@ -1,7 +1,7 @@ @@ -575,15 +583,27 @@ > + + + + + + + + + + + + + + + + + From python-checkins at python.org Tue May 4 20:45:27 2010 From: python-checkins at python.org (mark.dickinson) Date: Tue, 4 May 2010 20:45:27 +0200 (CEST) Subject: [Python-checkins] r80762 - python/trunk/Lib/gzip.py Message-ID: <20100504184527.7E10FFACD@mail.python.org> Author: mark.dickinson Date: Tue May 4 20:45:27 2010 New Revision: 80762 Log: Fix test_gzip failure on OS X. The failure was a result of trying to fflush a file that wasn't open for writing. Patch by Antoine Pitrou. Modified: python/trunk/Lib/gzip.py Modified: python/trunk/Lib/gzip.py ============================================================================== --- python/trunk/Lib/gzip.py (original) +++ python/trunk/Lib/gzip.py Tue May 4 20:45:27 2010 @@ -362,7 +362,7 @@ if self.mode == WRITE: # Ensure the compressor's buffer is flushed self.fileobj.write(self.compress.flush(zlib_mode)) - self.fileobj.flush() + self.fileobj.flush() def fileno(self): """Invoke the underlying file object's fileno() method. From python-checkins at python.org Tue May 4 20:46:24 2010 From: python-checkins at python.org (mark.dickinson) Date: Tue, 4 May 2010 20:46:24 +0200 (CEST) Subject: [Python-checkins] r80763 - in python/branches/release26-maint: Lib/gzip.py Message-ID: <20100504184624.4235CFA5E@mail.python.org> Author: mark.dickinson Date: Tue May 4 20:46:24 2010 New Revision: 80763 Log: Merged revisions 80762 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r80762 | mark.dickinson | 2010-05-04 19:45:27 +0100 (Tue, 04 May 2010) | 3 lines Fix test_gzip failure on OS X. The failure was a result of trying to fflush a file that wasn't open for writing. Patch by Antoine Pitrou. ........ Modified: python/branches/release26-maint/ (props changed) python/branches/release26-maint/Lib/gzip.py Modified: python/branches/release26-maint/Lib/gzip.py ============================================================================== --- python/branches/release26-maint/Lib/gzip.py (original) +++ python/branches/release26-maint/Lib/gzip.py Tue May 4 20:46:24 2010 @@ -333,7 +333,7 @@ if self.mode == WRITE: # Ensure the compressor's buffer is flushed self.fileobj.write(self.compress.flush(zlib_mode)) - self.fileobj.flush() + self.fileobj.flush() def fileno(self): """Invoke the underlying file object's fileno() method. From python-checkins at python.org Tue May 4 20:47:04 2010 From: python-checkins at python.org (mark.dickinson) Date: Tue, 4 May 2010 20:47:04 +0200 (CEST) Subject: [Python-checkins] r80764 - in python/branches/py3k: Lib/gzip.py Message-ID: <20100504184704.D3B9DEE99C@mail.python.org> Author: mark.dickinson Date: Tue May 4 20:47:04 2010 New Revision: 80764 Log: Merged revisions 80762 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r80762 | mark.dickinson | 2010-05-04 19:45:27 +0100 (Tue, 04 May 2010) | 3 lines Fix test_gzip failure on OS X. The failure was a result of trying to fflush a file that wasn't open for writing. Patch by Antoine Pitrou. ........ Modified: python/branches/py3k/ (props changed) python/branches/py3k/Lib/gzip.py Modified: python/branches/py3k/Lib/gzip.py ============================================================================== --- python/branches/py3k/Lib/gzip.py (original) +++ python/branches/py3k/Lib/gzip.py Tue May 4 20:47:04 2010 @@ -380,7 +380,7 @@ if self.mode == WRITE: # Ensure the compressor's buffer is flushed self.fileobj.write(self.compress.flush(zlib_mode)) - self.fileobj.flush() + self.fileobj.flush() def fileno(self): """Invoke the underlying file object's fileno() method. From python-checkins at python.org Tue May 4 20:47:51 2010 From: python-checkins at python.org (mark.dickinson) Date: Tue, 4 May 2010 20:47:51 +0200 (CEST) Subject: [Python-checkins] r80765 - in python/branches/release31-maint: Lib/gzip.py Message-ID: <20100504184751.01000D9C8@mail.python.org> Author: mark.dickinson Date: Tue May 4 20:47:50 2010 New Revision: 80765 Log: Merged revisions 80764 via svnmerge from svn+ssh://pythondev at svn.python.org/python/branches/py3k ................ r80764 | mark.dickinson | 2010-05-04 19:47:04 +0100 (Tue, 04 May 2010) | 10 lines Merged revisions 80762 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r80762 | mark.dickinson | 2010-05-04 19:45:27 +0100 (Tue, 04 May 2010) | 3 lines Fix test_gzip failure on OS X. The failure was a result of trying to fflush a file that wasn't open for writing. Patch by Antoine Pitrou. ........ ................ Modified: python/branches/release31-maint/ (props changed) python/branches/release31-maint/Lib/gzip.py Modified: python/branches/release31-maint/Lib/gzip.py ============================================================================== --- python/branches/release31-maint/Lib/gzip.py (original) +++ python/branches/release31-maint/Lib/gzip.py Tue May 4 20:47:50 2010 @@ -363,7 +363,7 @@ if self.mode == WRITE: # Ensure the compressor's buffer is flushed self.fileobj.write(self.compress.flush(zlib_mode)) - self.fileobj.flush() + self.fileobj.flush() def fileno(self): """Invoke the underlying file object's fileno() method. From python-checkins at python.org Tue May 4 21:08:18 2010 From: python-checkins at python.org (thomas.heller) Date: Tue, 4 May 2010 21:08:18 +0200 (CEST) Subject: [Python-checkins] r80766 - python/trunk/PCbuild/_ctypes.vcproj Message-ID: <20100504190818.8C012EE98A@mail.python.org> Author: thomas.heller Date: Tue May 4 21:08:18 2010 New Revision: 80766 Log: Remove reference to unused source file. Modified: python/trunk/PCbuild/_ctypes.vcproj Modified: python/trunk/PCbuild/_ctypes.vcproj ============================================================================== --- python/trunk/PCbuild/_ctypes.vcproj (original) +++ python/trunk/PCbuild/_ctypes.vcproj Tue May 4 21:08:18 2010 @@ -583,10 +583,6 @@ > - - Author: thomas.heller Date: Tue May 4 21:17:41 2010 New Revision: 80767 Log: Merged revisions 80761,80766 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r80761 | thomas.heller | 2010-05-04 20:44:42 +0200 (Di, 04 Mai 2010) | 8 lines On Windows, ctypes does no longer check the stack before and after calling a foreign function. This allows to use the unmodified libffi library. Remove most files from _ctypes/libffi_msvc, only two include files stay (updated from _ctypes/libffi/...). Other files are used in the cross-platform _ctypes/libffi directory. ........ r80766 | thomas.heller | 2010-05-04 21:08:18 +0200 (Di, 04 Mai 2010) | 2 lines Remove reference to unused source file. ........ Removed: python/branches/py3k/Modules/_ctypes/libffi_msvc/LICENSE python/branches/py3k/Modules/_ctypes/libffi_msvc/README python/branches/py3k/Modules/_ctypes/libffi_msvc/README.ctypes python/branches/py3k/Modules/_ctypes/libffi_msvc/ffi.c python/branches/py3k/Modules/_ctypes/libffi_msvc/ffi_common.h python/branches/py3k/Modules/_ctypes/libffi_msvc/ffitarget.h python/branches/py3k/Modules/_ctypes/libffi_msvc/prep_cif.c python/branches/py3k/Modules/_ctypes/libffi_msvc/types.c python/branches/py3k/Modules/_ctypes/libffi_msvc/win32.c python/branches/py3k/Modules/_ctypes/libffi_msvc/win64.asm Modified: python/branches/py3k/ (props changed) python/branches/py3k/Lib/ctypes/test/test_win32.py python/branches/py3k/Modules/_ctypes/callproc.c python/branches/py3k/Modules/_ctypes/libffi_msvc/ffi.h python/branches/py3k/Modules/_ctypes/libffi_msvc/fficonfig.h python/branches/py3k/PCbuild/_ctypes.vcproj Modified: python/branches/py3k/Lib/ctypes/test/test_win32.py ============================================================================== --- python/branches/py3k/Lib/ctypes/test/test_win32.py (original) +++ python/branches/py3k/Lib/ctypes/test/test_win32.py Tue May 4 21:17:41 2010 @@ -6,32 +6,6 @@ import _ctypes_test -if sys.platform == "win32" and sizeof(c_void_p) == sizeof(c_int): - # Only windows 32-bit has different calling conventions. - - class WindowsTestCase(unittest.TestCase): - def test_callconv_1(self): - # Testing stdcall function - - IsWindow = windll.user32.IsWindow - # ValueError: Procedure probably called with not enough arguments (4 bytes missing) - self.assertRaises(ValueError, IsWindow) - - # This one should succeeed... - self.assertEqual(0, IsWindow(0)) - - # ValueError: Procedure probably called with too many arguments (8 bytes in excess) - self.assertRaises(ValueError, IsWindow, 0, 0, 0) - - def test_callconv_2(self): - # Calling stdcall function as cdecl - - IsWindow = cdll.user32.IsWindow - - # ValueError: Procedure called with not enough arguments (4 bytes missing) - # or wrong calling convention - self.assertRaises(ValueError, IsWindow, None) - if sys.platform == "win32": class FunctionCallTestCase(unittest.TestCase): Modified: python/branches/py3k/Modules/_ctypes/callproc.c ============================================================================== --- python/branches/py3k/Modules/_ctypes/callproc.c (original) +++ python/branches/py3k/Modules/_ctypes/callproc.c Tue May 4 21:17:41 2010 @@ -761,7 +761,6 @@ ffi_cif cif; int cc; #ifdef MS_WIN32 - int delta; #ifndef DONT_USE_SEH DWORD dwExceptionCode = 0; EXCEPTION_RECORD record; @@ -812,9 +811,8 @@ #ifndef DONT_USE_SEH __try { #endif - delta = #endif - ffi_call(&cif, (void *)pProc, resmem, avalues); + ffi_call(&cif, (void *)pProc, resmem, avalues); #ifdef MS_WIN32 #ifndef DONT_USE_SEH } @@ -846,35 +844,6 @@ return -1; } #endif -#ifdef MS_WIN64 - if (delta != 0) { - PyErr_Format(PyExc_RuntimeError, - "ffi_call failed with code %d", - delta); - return -1; - } -#else - if (delta < 0) { - if (flags & FUNCFLAG_CDECL) - PyErr_Format(PyExc_ValueError, - "Procedure called with not enough " - "arguments (%d bytes missing) " - "or wrong calling convention", - -delta); - else - PyErr_Format(PyExc_ValueError, - "Procedure probably called with not enough " - "arguments (%d bytes missing)", - -delta); - return -1; - } else if (delta > 0) { - PyErr_Format(PyExc_ValueError, - "Procedure probably called with too many " - "arguments (%d bytes in excess)", - delta); - return -1; - } -#endif #endif if ((flags & FUNCFLAG_PYTHONAPI) && PyErr_Occurred()) return -1; @@ -1147,11 +1116,7 @@ } for (i = 0; i < argcount; ++i) { atypes[i] = args[i].ffi_type; - if (atypes[i]->type == FFI_TYPE_STRUCT -#ifdef _WIN64 - && atypes[i]->size <= sizeof(void *) -#endif - ) + if (atypes[i]->type == FFI_TYPE_STRUCT) avalues[i] = (void *)args[i].value.p; else avalues[i] = (void *)&args[i].value; Deleted: python/branches/py3k/Modules/_ctypes/libffi_msvc/LICENSE ============================================================================== --- python/branches/py3k/Modules/_ctypes/libffi_msvc/LICENSE Tue May 4 21:17:41 2010 +++ (empty file) @@ -1,20 +0,0 @@ -libffi - Copyright (c) 1996-2003 Red Hat, Inc. - -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 CYGNUS SOLUTIONS 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. Deleted: python/branches/py3k/Modules/_ctypes/libffi_msvc/README ============================================================================== --- python/branches/py3k/Modules/_ctypes/libffi_msvc/README Tue May 4 21:17:41 2010 +++ (empty file) @@ -1,500 +0,0 @@ -This directory contains the libffi package, which is not part of GCC but -shipped with GCC as convenience. - -Status -====== - -libffi-2.00 has not been released yet! This is a development snapshot! - -libffi-1.20 was released on October 5, 1998. Check the libffi web -page for updates: . - - -What is libffi? -=============== - -Compilers for high level languages generate code that follow certain -conventions. These conventions are necessary, in part, for separate -compilation to work. One such convention is the "calling -convention". The "calling convention" is essentially a set of -assumptions made by the compiler about where function arguments will -be found on entry to a function. A "calling convention" also specifies -where the return value for a function is found. - -Some programs may not know at the time of compilation what arguments -are to be passed to a function. For instance, an interpreter may be -told at run-time about the number and types of arguments used to call -a given function. Libffi can be used in such programs to provide a -bridge from the interpreter program to compiled code. - -The libffi library provides a portable, high level programming -interface to various calling conventions. This allows a programmer to -call any function specified by a call interface description at run -time. - -Ffi stands for Foreign Function Interface. A foreign function -interface is the popular name for the interface that allows code -written in one language to call code written in another language. The -libffi library really only provides the lowest, machine dependent -layer of a fully featured foreign function interface. A layer must -exist above libffi that handles type conversions for values passed -between the two languages. - - -Supported Platforms and Prerequisites -===================================== - -Libffi has been ported to: - - SunOS 4.1.3 & Solaris 2.x (SPARC-V8, SPARC-V9) - - Irix 5.3 & 6.2 (System V/o32 & n32) - - Intel x86 - Linux (System V ABI) - - Alpha - Linux and OSF/1 - - m68k - Linux (System V ABI) - - PowerPC - Linux (System V ABI, Darwin, AIX) - - ARM - Linux (System V ABI) - -Libffi has been tested with the egcs 1.0.2 gcc compiler. Chances are -that other versions will work. Libffi has also been built and tested -with the SGI compiler tools. - -On PowerPC, the tests failed (see the note below). - -You must use GNU make to build libffi. SGI's make will not work. -Sun's probably won't either. - -If you port libffi to another platform, please let me know! I assume -that some will be easy (x86 NetBSD), and others will be more difficult -(HP). - - -Installing libffi -================= - -[Note: before actually performing any of these installation steps, - you may wish to read the "Platform Specific Notes" below.] - -First you must configure the distribution for your particular -system. Go to the directory you wish to build libffi in and run the -"configure" program found in the root directory of the libffi source -distribution. - -You may want to tell configure where to install the libffi library and -header files. To do that, use the --prefix configure switch. Libffi -will install under /usr/local by default. - -If you want to enable extra run-time debugging checks use the the ---enable-debug configure switch. This is useful when your program dies -mysteriously while using libffi. - -Another useful configure switch is --enable-purify-safety. Using this -will add some extra code which will suppress certain warnings when you -are using Purify with libffi. Only use this switch when using -Purify, as it will slow down the library. - -Configure has many other options. Use "configure --help" to see them all. - -Once configure has finished, type "make". Note that you must be using -GNU make. SGI's make will not work. Sun's probably won't either. -You can ftp GNU make from prep.ai.mit.edu:/pub/gnu. - -To ensure that libffi is working as advertised, type "make test". - -To install the library and header files, type "make install". - - -Using libffi -============ - - The Basics - ---------- - -Libffi assumes that you have a pointer to the function you wish to -call and that you know the number and types of arguments to pass it, -as well as the return type of the function. - -The first thing you must do is create an ffi_cif object that matches -the signature of the function you wish to call. The cif in ffi_cif -stands for Call InterFace. To prepare a call interface object, use the -following function: - -ffi_status ffi_prep_cif(ffi_cif *cif, ffi_abi abi, - unsigned int nargs, - ffi_type *rtype, ffi_type **atypes); - - CIF is a pointer to the call interface object you wish - to initialize. - - ABI is an enum that specifies the calling convention - to use for the call. FFI_DEFAULT_ABI defaults - to the system's native calling convention. Other - ABI's may be used with care. They are system - specific. - - NARGS is the number of arguments this function accepts. - libffi does not yet support vararg functions. - - RTYPE is a pointer to an ffi_type structure that represents - the return type of the function. Ffi_type objects - describe the types of values. libffi provides - ffi_type objects for many of the native C types: - signed int, unsigned int, signed char, unsigned char, - etc. There is also a pointer ffi_type object and - a void ffi_type. Use &ffi_type_void for functions that - don't return values. - - ATYPES is a vector of ffi_type pointers. ARGS must be NARGS long. - If NARGS is 0, this is ignored. - - -ffi_prep_cif will return a status code that you are responsible -for checking. It will be one of the following: - - FFI_OK - All is good. - - FFI_BAD_TYPEDEF - One of the ffi_type objects that ffi_prep_cif - came across is bad. - - -Before making the call, the VALUES vector should be initialized -with pointers to the appropriate argument values. - -To call the the function using the initialized ffi_cif, use the -ffi_call function: - -void ffi_call(ffi_cif *cif, void *fn, void *rvalue, void **avalues); - - CIF is a pointer to the ffi_cif initialized specifically - for this function. - - FN is a pointer to the function you want to call. - - RVALUE is a pointer to a chunk of memory that is to hold the - result of the function call. Currently, it must be - at least one word in size (except for the n32 version - under Irix 6.x, which must be a pointer to an 8 byte - aligned value (a long long). It must also be at least - word aligned (depending on the return type, and the - system's alignment requirements). If RTYPE is - &ffi_type_void, this is ignored. If RVALUE is NULL, - the return value is discarded. - - AVALUES is a vector of void* that point to the memory locations - holding the argument values for a call. - If NARGS is 0, this is ignored. - - -If you are expecting a return value from FN it will have been stored -at RVALUE. - - - - An Example - ---------- - -Here is a trivial example that calls puts() a few times. - - #include - #include - - int main() - { - ffi_cif cif; - ffi_type *args[1]; - void *values[1]; - char *s; - int rc; - - /* Initialize the argument info vectors */ - args[0] = &ffi_type_uint; - values[0] = &s; - - /* Initialize the cif */ - if (ffi_prep_cif(&cif, FFI_DEFAULT_ABI, 1, - &ffi_type_uint, args) == FFI_OK) - { - s = "Hello World!"; - ffi_call(&cif, puts, &rc, values); - /* rc now holds the result of the call to puts */ - - /* values holds a pointer to the function's arg, so to - call puts() again all we need to do is change the - value of s */ - s = "This is cool!"; - ffi_call(&cif, puts, &rc, values); - } - - return 0; - } - - - - Aggregate Types - --------------- - -Although libffi has no special support for unions or bit-fields, it is -perfectly happy passing structures back and forth. You must first -describe the structure to libffi by creating a new ffi_type object -for it. Here is the definition of ffi_type: - - typedef struct _ffi_type - { - unsigned size; - short alignment; - short type; - struct _ffi_type **elements; - } ffi_type; - -All structures must have type set to FFI_TYPE_STRUCT. You may set -size and alignment to 0. These will be calculated and reset to the -appropriate values by ffi_prep_cif(). - -elements is a NULL terminated array of pointers to ffi_type objects -that describe the type of the structure elements. These may, in turn, -be structure elements. - -The following example initializes a ffi_type object representing the -tm struct from Linux's time.h: - - struct tm { - int tm_sec; - int tm_min; - int tm_hour; - int tm_mday; - int tm_mon; - int tm_year; - int tm_wday; - int tm_yday; - int tm_isdst; - /* Those are for future use. */ - long int __tm_gmtoff__; - __const char *__tm_zone__; - }; - - { - ffi_type tm_type; - ffi_type *tm_type_elements[12]; - int i; - - tm_type.size = tm_type.alignment = 0; - tm_type.elements = &tm_type_elements; - - for (i = 0; i < 9; i++) - tm_type_elements[i] = &ffi_type_sint; - - tm_type_elements[9] = &ffi_type_slong; - tm_type_elements[10] = &ffi_type_pointer; - tm_type_elements[11] = NULL; - - /* tm_type can now be used to represent tm argument types and - return types for ffi_prep_cif() */ - } - - - -Platform Specific Notes -======================= - - Intel x86 - --------- - -There are no known problems with the x86 port. - - Sun SPARC - SunOS 4.1.3 & Solaris 2.x - ------------------------------------- - -You must use GNU Make to build libffi on Sun platforms. - - MIPS - Irix 5.3 & 6.x - --------------------- - -Irix 6.2 and better supports three different calling conventions: o32, -n32 and n64. Currently, libffi only supports both o32 and n32 under -Irix 6.x, but only o32 under Irix 5.3. Libffi will automatically be -configured for whichever calling convention it was built for. - -By default, the configure script will try to build libffi with the GNU -development tools. To build libffi with the SGI development tools, set -the environment variable CC to either "cc -32" or "cc -n32" before -running configure under Irix 6.x (depending on whether you want an o32 -or n32 library), or just "cc" for Irix 5.3. - -With the n32 calling convention, when returning structures smaller -than 16 bytes, be sure to provide an RVALUE that is 8 byte aligned. -Here's one way of forcing this: - - double struct_storage[2]; - my_small_struct *s = (my_small_struct *) struct_storage; - /* Use s for RVALUE */ - -If you don't do this you are liable to get spurious bus errors. - -"long long" values are not supported yet. - -You must use GNU Make to build libffi on SGI platforms. - - ARM - System V ABI - ------------------ - -The ARM port was performed on a NetWinder running ARM Linux ELF -(2.0.31) and gcc 2.8.1. - - - - PowerPC System V ABI - -------------------- - -There are two `System V ABI's which libffi implements for PowerPC. -They differ only in how small structures are returned from functions. - -In the FFI_SYSV version, structures that are 8 bytes or smaller are -returned in registers. This is what GCC does when it is configured -for solaris, and is what the System V ABI I have (dated September -1995) says. - -In the FFI_GCC_SYSV version, all structures are returned the same way: -by passing a pointer as the first argument to the function. This is -what GCC does when it is configured for linux or a generic sysv -target. - -EGCS 1.0.1 (and probably other versions of EGCS/GCC) also has a -inconsistency with the SysV ABI: When a procedure is called with many -floating-point arguments, some of them get put on the stack. They are -all supposed to be stored in double-precision format, even if they are -only single-precision, but EGCS stores single-precision arguments as -single-precision anyway. This causes one test to fail (the `many -arguments' test). - - -What's With The Crazy Comments? -=============================== - -You might notice a number of cryptic comments in the code, delimited -by /*@ and @*/. These are annotations read by the program LCLint, a -tool for statically checking C programs. You can read all about it at -. - - -History -======= - -1.20 Oct-5-98 - Raffaele Sena produces ARM port. - -1.19 Oct-5-98 - Fixed x86 long double and long long return support. - m68k bug fixes from Andreas Schwab. - Patch for DU assembler compatibility for the Alpha from Richard - Henderson. - -1.18 Apr-17-98 - Bug fixes and MIPS configuration changes. - -1.17 Feb-24-98 - Bug fixes and m68k port from Andreas Schwab. PowerPC port from - Geoffrey Keating. Various bug x86, Sparc and MIPS bug fixes. - -1.16 Feb-11-98 - Richard Henderson produces Alpha port. - -1.15 Dec-4-97 - Fixed an n32 ABI bug. New libtool, auto* support. - -1.14 May-13-97 - libtool is now used to generate shared and static libraries. - Fixed a minor portability problem reported by Russ McManus - . - -1.13 Dec-2-96 - Added --enable-purify-safety to keep Purify from complaining - about certain low level code. - Sparc fix for calling functions with < 6 args. - Linux x86 a.out fix. - -1.12 Nov-22-96 - Added missing ffi_type_void, needed for supporting void return - types. Fixed test case for non MIPS machines. Cygnus Support - is now Cygnus Solutions. - -1.11 Oct-30-96 - Added notes about GNU make. - -1.10 Oct-29-96 - Added configuration fix for non GNU compilers. - -1.09 Oct-29-96 - Added --enable-debug configure switch. Clean-ups based on LCLint - feedback. ffi_mips.h is always installed. Many configuration - fixes. Fixed ffitest.c for sparc builds. - -1.08 Oct-15-96 - Fixed n32 problem. Many clean-ups. - -1.07 Oct-14-96 - Gordon Irlam rewrites v8.S again. Bug fixes. - -1.06 Oct-14-96 - Gordon Irlam improved the sparc port. - -1.05 Oct-14-96 - Interface changes based on feedback. - -1.04 Oct-11-96 - Sparc port complete (modulo struct passing bug). - -1.03 Oct-10-96 - Passing struct args, and returning struct values works for - all architectures/calling conventions. Expanded tests. - -1.02 Oct-9-96 - Added SGI n32 support. Fixed bugs in both o32 and Linux support. - Added "make test". - -1.01 Oct-8-96 - Fixed float passing bug in mips version. Restructured some - of the code. Builds cleanly with SGI tools. - -1.00 Oct-7-96 - First release. No public announcement. - - -Authors & Credits -================= - -libffi was written by Anthony Green . - -Portions of libffi were derived from Gianni Mariani's free gencall -library for Silicon Graphics machines. - -The closure mechanism was designed and implemented by Kresten Krab -Thorup. - -The Sparc port was derived from code contributed by the fine folks at -Visible Decisions Inc . Further enhancements were -made by Gordon Irlam at Cygnus Solutions . - -The Alpha port was written by Richard Henderson at Cygnus Solutions. - -Andreas Schwab ported libffi to m68k Linux and provided a number of -bug fixes. - -Geoffrey Keating ported libffi to the PowerPC. - -Raffaele Sena ported libffi to the ARM. - -Jesper Skov and Andrew Haley both did more than their fair share of -stepping through the code and tracking down bugs. - -Thanks also to Tom Tromey for bug fixes and configuration help. - -Thanks to Jim Blandy, who provided some useful feedback on the libffi -interface. - -If you have a problem, or have found a bug, please send a note to -green at cygnus.com. Deleted: python/branches/py3k/Modules/_ctypes/libffi_msvc/README.ctypes ============================================================================== --- python/branches/py3k/Modules/_ctypes/libffi_msvc/README.ctypes Tue May 4 21:17:41 2010 +++ (empty file) @@ -1,7 +0,0 @@ -The purpose is to hack the libffi sources so that they can be compiled -with MSVC, and to extend them so that they have the features I need -for ctypes. - -I retrieved the libffi sources from the gcc cvs repository on -2004-01-27. Then I did 'configure' in a 'build' subdirectory on a x86 -linux system, and copied the files I found useful. Deleted: python/branches/py3k/Modules/_ctypes/libffi_msvc/ffi.c ============================================================================== --- python/branches/py3k/Modules/_ctypes/libffi_msvc/ffi.c Tue May 4 21:17:41 2010 +++ (empty file) @@ -1,457 +0,0 @@ -/* ----------------------------------------------------------------------- - ffi.c - Copyright (c) 1996, 1998, 1999, 2001 Red Hat, Inc. - Copyright (c) 2002 Ranjit Mathew - Copyright (c) 2002 Bo Thorsen - Copyright (c) 2002 Roger Sayle - - x86 Foreign Function Interface - - 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 CYGNUS SOLUTIONS 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. - ----------------------------------------------------------------------- */ - -#include -#include - -#include - -/* ffi_prep_args is called by the assembly routine once stack space - has been allocated for the function's arguments */ - -extern void Py_FatalError(const char *msg); - -/*@-exportheader@*/ -void ffi_prep_args(char *stack, extended_cif *ecif) -/*@=exportheader@*/ -{ - register unsigned int i; - register void **p_argv; - register char *argp; - register ffi_type **p_arg; - - argp = stack; - if (ecif->cif->rtype->type == FFI_TYPE_STRUCT) - { - *(void **) argp = ecif->rvalue; - argp += sizeof(void *); - } - - p_argv = ecif->avalue; - - for (i = ecif->cif->nargs, p_arg = ecif->cif->arg_types; - i != 0; - i--, p_arg++) - { - size_t z; - - /* Align if necessary */ - if ((sizeof(void *) - 1) & (size_t) argp) - argp = (char *) ALIGN(argp, sizeof(void *)); - - z = (*p_arg)->size; - if (z < sizeof(int)) - { - z = sizeof(int); - switch ((*p_arg)->type) - { - case FFI_TYPE_SINT8: - *(signed int *) argp = (signed int)*(SINT8 *)(* p_argv); - break; - - case FFI_TYPE_UINT8: - *(unsigned int *) argp = (unsigned int)*(UINT8 *)(* p_argv); - break; - - case FFI_TYPE_SINT16: - *(signed int *) argp = (signed int)*(SINT16 *)(* p_argv); - break; - - case FFI_TYPE_UINT16: - *(unsigned int *) argp = (unsigned int)*(UINT16 *)(* p_argv); - break; - - case FFI_TYPE_SINT32: - *(signed int *) argp = (signed int)*(SINT32 *)(* p_argv); - break; - - case FFI_TYPE_UINT32: - *(unsigned int *) argp = (unsigned int)*(UINT32 *)(* p_argv); - break; - - case FFI_TYPE_STRUCT: - *(unsigned int *) argp = (unsigned int)*(UINT32 *)(* p_argv); - break; - - default: - FFI_ASSERT(0); - } - } - else - { - memcpy(argp, *p_argv, z); - } - p_argv++; - argp += z; - } - - if (argp - stack > ecif->cif->bytes) - { - Py_FatalError("FFI BUG: not enough stack space for arguments"); - } - return; -} - -/* Perform machine dependent cif processing */ -ffi_status ffi_prep_cif_machdep(ffi_cif *cif) -{ - /* Set the return type flag */ - switch (cif->rtype->type) - { - case FFI_TYPE_VOID: - case FFI_TYPE_STRUCT: - case FFI_TYPE_SINT64: - case FFI_TYPE_FLOAT: - case FFI_TYPE_DOUBLE: - case FFI_TYPE_LONGDOUBLE: - cif->flags = (unsigned) cif->rtype->type; - break; - - case FFI_TYPE_UINT64: -#ifdef _WIN64 - case FFI_TYPE_POINTER: -#endif - cif->flags = FFI_TYPE_SINT64; - break; - - default: - cif->flags = FFI_TYPE_INT; - break; - } - - return FFI_OK; -} - -#ifdef _WIN32 -extern int -ffi_call_x86(void (*)(char *, extended_cif *), - /*@out@*/ extended_cif *, - unsigned, unsigned, - /*@out@*/ unsigned *, - void (*fn)()); -#endif - -#ifdef _WIN64 -extern int -ffi_call_AMD64(void (*)(char *, extended_cif *), - /*@out@*/ extended_cif *, - unsigned, unsigned, - /*@out@*/ unsigned *, - void (*fn)()); -#endif - -int -ffi_call(/*@dependent@*/ ffi_cif *cif, - void (*fn)(), - /*@out@*/ void *rvalue, - /*@dependent@*/ void **avalue) -{ - extended_cif ecif; - - ecif.cif = cif; - ecif.avalue = avalue; - - /* If the return value is a struct and we don't have a return */ - /* value address then we need to make one */ - - if ((rvalue == NULL) && - (cif->rtype->type == FFI_TYPE_STRUCT)) - { - /*@-sysunrecog@*/ - ecif.rvalue = alloca(cif->rtype->size); - /*@=sysunrecog@*/ - } - else - ecif.rvalue = rvalue; - - - switch (cif->abi) - { -#if !defined(_WIN64) - case FFI_SYSV: - case FFI_STDCALL: - return ffi_call_x86(ffi_prep_args, &ecif, cif->bytes, - cif->flags, ecif.rvalue, fn); - break; -#else - case FFI_SYSV: - /*@-usedef@*/ - /* Function call needs at least 40 bytes stack size, on win64 AMD64 */ - return ffi_call_AMD64(ffi_prep_args, &ecif, cif->bytes ? cif->bytes : 40, - cif->flags, ecif.rvalue, fn); - /*@=usedef@*/ - break; -#endif - - default: - FFI_ASSERT(0); - break; - } - return -1; /* theller: Hrm. */ -} - - -/** private members **/ - -static void ffi_prep_incoming_args_SYSV (char *stack, void **ret, - void** args, ffi_cif* cif); -/* This function is jumped to by the trampoline */ - -#ifdef _WIN64 -void * -#else -static void __fastcall -#endif -ffi_closure_SYSV (ffi_closure *closure, int *argp) -{ - // this is our return value storage - long double res; - - // our various things... - ffi_cif *cif; - void **arg_area; - unsigned short rtype; - void *resp = (void*)&res; - void *args = &argp[1]; - - cif = closure->cif; - arg_area = (void**) alloca (cif->nargs * sizeof (void*)); - - /* this call will initialize ARG_AREA, such that each - * element in that array points to the corresponding - * value on the stack; and if the function returns - * a structure, it will re-set RESP to point to the - * structure return address. */ - - ffi_prep_incoming_args_SYSV(args, (void**)&resp, arg_area, cif); - - (closure->fun) (cif, resp, arg_area, closure->user_data); - - rtype = cif->flags; - -#if defined(_WIN32) && !defined(_WIN64) -#ifdef _MSC_VER - /* now, do a generic return based on the value of rtype */ - if (rtype == FFI_TYPE_INT) - { - _asm mov eax, resp ; - _asm mov eax, [eax] ; - } - else if (rtype == FFI_TYPE_FLOAT) - { - _asm mov eax, resp ; - _asm fld DWORD PTR [eax] ; -// asm ("flds (%0)" : : "r" (resp) : "st" ); - } - else if (rtype == FFI_TYPE_DOUBLE) - { - _asm mov eax, resp ; - _asm fld QWORD PTR [eax] ; -// asm ("fldl (%0)" : : "r" (resp) : "st", "st(1)" ); - } - else if (rtype == FFI_TYPE_LONGDOUBLE) - { -// asm ("fldt (%0)" : : "r" (resp) : "st", "st(1)" ); - } - else if (rtype == FFI_TYPE_SINT64) - { - _asm mov edx, resp ; - _asm mov eax, [edx] ; - _asm mov edx, [edx + 4] ; -// asm ("movl 0(%0),%%eax;" -// "movl 4(%0),%%edx" -// : : "r"(resp) -// : "eax", "edx"); - } -#else - /* now, do a generic return based on the value of rtype */ - if (rtype == FFI_TYPE_INT) - { - asm ("movl (%0),%%eax" : : "r" (resp) : "eax"); - } - else if (rtype == FFI_TYPE_FLOAT) - { - asm ("flds (%0)" : : "r" (resp) : "st" ); - } - else if (rtype == FFI_TYPE_DOUBLE) - { - asm ("fldl (%0)" : : "r" (resp) : "st", "st(1)" ); - } - else if (rtype == FFI_TYPE_LONGDOUBLE) - { - asm ("fldt (%0)" : : "r" (resp) : "st", "st(1)" ); - } - else if (rtype == FFI_TYPE_SINT64) - { - asm ("movl 0(%0),%%eax;" - "movl 4(%0),%%edx" - : : "r"(resp) - : "eax", "edx"); - } -#endif -#endif - -#ifdef _WIN64 - /* The result is returned in rax. This does the right thing for - result types except for floats; we have to 'mov xmm0, rax' in the - caller to correct this. - */ - return *(void **)resp; -#endif -} - -/*@-exportheader@*/ -static void -ffi_prep_incoming_args_SYSV(char *stack, void **rvalue, - void **avalue, ffi_cif *cif) -/*@=exportheader@*/ -{ - register unsigned int i; - register void **p_argv; - register char *argp; - register ffi_type **p_arg; - - argp = stack; - - if ( cif->rtype->type == FFI_TYPE_STRUCT ) { - *rvalue = *(void **) argp; - argp += 4; - } - - p_argv = avalue; - - for (i = cif->nargs, p_arg = cif->arg_types; (i != 0); i--, p_arg++) - { - size_t z; - - /* Align if necessary */ - if ((sizeof(char *) - 1) & (size_t) argp) { - argp = (char *) ALIGN(argp, sizeof(char*)); - } - - z = (*p_arg)->size; - - /* because we're little endian, this is what it turns into. */ - - *p_argv = (void*) argp; - - p_argv++; - argp += z; - } - - return; -} - -/* the cif must already be prep'ed */ -extern void ffi_closure_OUTER(); - -ffi_status -ffi_prep_closure (ffi_closure* closure, - ffi_cif* cif, - void (*fun)(ffi_cif*,void*,void**,void*), - void *user_data) -{ - short bytes; - char *tramp; -#ifdef _WIN64 - int mask; -#endif - FFI_ASSERT (cif->abi == FFI_SYSV); - - if (cif->abi == FFI_SYSV) - bytes = 0; -#if !defined(_WIN64) - else if (cif->abi == FFI_STDCALL) - bytes = cif->bytes; -#endif - else - return FFI_BAD_ABI; - - tramp = &closure->tramp[0]; - -#define BYTES(text) memcpy(tramp, text, sizeof(text)), tramp += sizeof(text)-1 -#define POINTER(x) *(void**)tramp = (void*)(x), tramp += sizeof(void*) -#define SHORT(x) *(short*)tramp = x, tramp += sizeof(short) -#define INT(x) *(int*)tramp = x, tramp += sizeof(int) - -#ifdef _WIN64 - if (cif->nargs >= 1 && - (cif->arg_types[0]->type == FFI_TYPE_FLOAT - || cif->arg_types[0]->type == FFI_TYPE_DOUBLE)) - mask |= 1; - if (cif->nargs >= 2 && - (cif->arg_types[1]->type == FFI_TYPE_FLOAT - || cif->arg_types[1]->type == FFI_TYPE_DOUBLE)) - mask |= 2; - if (cif->nargs >= 3 && - (cif->arg_types[2]->type == FFI_TYPE_FLOAT - || cif->arg_types[2]->type == FFI_TYPE_DOUBLE)) - mask |= 4; - if (cif->nargs >= 4 && - (cif->arg_types[3]->type == FFI_TYPE_FLOAT - || cif->arg_types[3]->type == FFI_TYPE_DOUBLE)) - mask |= 8; - - /* 41 BB ---- mov r11d,mask */ - BYTES("\x41\xBB"); INT(mask); - - /* 48 B8 -------- mov rax, closure */ - BYTES("\x48\xB8"); POINTER(closure); - - /* 49 BA -------- mov r10, ffi_closure_OUTER */ - BYTES("\x49\xBA"); POINTER(ffi_closure_OUTER); - - /* 41 FF E2 jmp r10 */ - BYTES("\x41\xFF\xE2"); - -#else - - /* mov ecx, closure */ - BYTES("\xb9"); POINTER(closure); - - /* mov edx, esp */ - BYTES("\x8b\xd4"); - - /* call ffi_closure_SYSV */ - BYTES("\xe8"); POINTER((char*)&ffi_closure_SYSV - (tramp + 4)); - - /* ret bytes */ - BYTES("\xc2"); - SHORT(bytes); - -#endif - - if (tramp - &closure->tramp[0] > FFI_TRAMPOLINE_SIZE) - Py_FatalError("FFI_TRAMPOLINE_SIZE too small in " __FILE__); - - closure->cif = cif; - closure->user_data = user_data; - closure->fun = fun; - - return FFI_OK; -} Modified: python/branches/py3k/Modules/_ctypes/libffi_msvc/ffi.h ============================================================================== --- python/branches/py3k/Modules/_ctypes/libffi_msvc/ffi.h (original) +++ python/branches/py3k/Modules/_ctypes/libffi_msvc/ffi.h Tue May 4 21:17:41 2010 @@ -1,5 +1,5 @@ /* -----------------------------------------------------------------*-C-*- - libffi 2.00-beta - Copyright (c) 1996-2003 Red Hat, Inc. + libffi @VERSION@ - Copyright (c) 1996-2003, 2007, 2008 Red Hat, Inc. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the @@ -12,13 +12,14 @@ 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 CYGNUS SOLUTIONS 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. + 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. ----------------------------------------------------------------------- */ @@ -56,7 +57,7 @@ #endif /* Specify which architecture libffi is configured for. */ -//XXX #define X86 +/* #define @TARGET@ */ /* ---- System configuration information --------------------------------- */ @@ -64,6 +65,10 @@ #ifndef LIBFFI_ASM +#ifdef _MSC_VER +#define __attribute__(X) +#endif + #include #include @@ -79,12 +84,21 @@ # ifdef __GNUC__ # define FFI_LONG_LONG_MAX __LONG_LONG_MAX__ # endif -# ifdef _MSC_VER -# define FFI_LONG_LONG_MAX _I64_MAX -# endif # endif #endif +/* The closure code assumes that this works on pointers, i.e. a size_t */ +/* can hold a pointer. */ + +typedef struct _ffi_type +{ + size_t size; + unsigned short alignment; + unsigned short type; + struct _ffi_type **elements; +} ffi_type; + +#ifndef LIBFFI_HIDE_BASIC_TYPES #if SCHAR_MAX == 127 # define ffi_type_uchar ffi_type_uint8 # define ffi_type_schar ffi_type_sint8 @@ -115,26 +129,23 @@ #error "int size not supported" #endif -#define ffi_type_ulong ffi_type_uint64 -#define ffi_type_slong ffi_type_sint64 #if LONG_MAX == 2147483647 # if FFI_LONG_LONG_MAX != 9223372036854775807 - #error "no 64-bit data type supported" + #error "no 64-bit data type supported" # endif #elif LONG_MAX != 9223372036854775807 #error "long size not supported" #endif -/* The closure code assumes that this works on pointers, i.e. a size_t */ -/* can hold a pointer. */ - -typedef struct _ffi_type -{ - size_t size; - unsigned short alignment; - unsigned short type; - /*@null@*/ struct _ffi_type **elements; -} ffi_type; +#if LONG_MAX == 2147483647 +# define ffi_type_ulong ffi_type_uint32 +# define ffi_type_slong ffi_type_sint32 +#elif LONG_MAX == 9223372036854775807 +# define ffi_type_ulong ffi_type_uint64 +# define ffi_type_slong ffi_type_sint64 +#else + #error "long size not supported" +#endif /* These are defined in types.c */ extern ffi_type ffi_type_void; @@ -148,14 +159,19 @@ extern ffi_type ffi_type_sint64; extern ffi_type ffi_type_float; extern ffi_type ffi_type_double; -extern ffi_type ffi_type_longdouble; extern ffi_type ffi_type_pointer; +#if HAVE_LONG_DOUBLE +extern ffi_type ffi_type_longdouble; +#else +#define ffi_type_longdouble ffi_type_double +#endif +#endif /* LIBFFI_HIDE_BASIC_TYPES */ typedef enum { FFI_OK = 0, FFI_BAD_TYPEDEF, - FFI_BAD_ABI + FFI_BAD_ABI } ffi_status; typedef unsigned FFI_TYPE; @@ -163,8 +179,8 @@ typedef struct { ffi_abi abi; unsigned nargs; - /*@dependent@*/ ffi_type **arg_types; - /*@dependent@*/ ffi_type *rtype; + ffi_type **arg_types; + ffi_type *rtype; unsigned bytes; unsigned flags; #ifdef FFI_EXTRA_CIF_FIELDS @@ -174,10 +190,16 @@ /* ---- Definitions for the raw API -------------------------------------- */ -#ifdef _WIN64 -#define FFI_SIZEOF_ARG 8 -#else -#define FFI_SIZEOF_ARG 4 +#ifndef FFI_SIZEOF_ARG +# if LONG_MAX == 2147483647 +# define FFI_SIZEOF_ARG 4 +# elif LONG_MAX == 9223372036854775807 +# define FFI_SIZEOF_ARG 8 +# endif +#endif + +#ifndef FFI_SIZEOF_JAVA_RAW +# define FFI_SIZEOF_JAVA_RAW FFI_SIZEOF_ARG #endif typedef union { @@ -188,10 +210,25 @@ void* ptr; } ffi_raw; -void ffi_raw_call (/*@dependent@*/ ffi_cif *cif, - void (*fn)(), - /*@out@*/ void *rvalue, - /*@dependent@*/ ffi_raw *avalue); +#if FFI_SIZEOF_JAVA_RAW == 4 && FFI_SIZEOF_ARG == 8 +/* This is a special case for mips64/n32 ABI (and perhaps others) where + sizeof(void *) is 4 and FFI_SIZEOF_ARG is 8. */ +typedef union { + signed int sint; + unsigned int uint; + float flt; + char data[FFI_SIZEOF_JAVA_RAW]; + void* ptr; +} ffi_java_raw; +#else +typedef ffi_raw ffi_java_raw; +#endif + + +void ffi_raw_call (ffi_cif *cif, + void (*fn)(void), + void *rvalue, + ffi_raw *avalue); void ffi_ptrarray_to_raw (ffi_cif *cif, void **args, ffi_raw *raw); void ffi_raw_to_ptrarray (ffi_cif *cif, ffi_raw *raw, void **args); @@ -201,25 +238,35 @@ /* packing, even on 64-bit machines. I.e. on 64-bit machines */ /* longs and doubles are followed by an empty 64-bit word. */ -void ffi_java_raw_call (/*@dependent@*/ ffi_cif *cif, - void (*fn)(), - /*@out@*/ void *rvalue, - /*@dependent@*/ ffi_raw *avalue); +void ffi_java_raw_call (ffi_cif *cif, + void (*fn)(void), + void *rvalue, + ffi_java_raw *avalue); -void ffi_java_ptrarray_to_raw (ffi_cif *cif, void **args, ffi_raw *raw); -void ffi_java_raw_to_ptrarray (ffi_cif *cif, ffi_raw *raw, void **args); +void ffi_java_ptrarray_to_raw (ffi_cif *cif, void **args, ffi_java_raw *raw); +void ffi_java_raw_to_ptrarray (ffi_cif *cif, ffi_java_raw *raw, void **args); size_t ffi_java_raw_size (ffi_cif *cif); /* ---- Definitions for closures ----------------------------------------- */ #if FFI_CLOSURES +#ifdef _MSC_VER +__declspec(align(8)) +#endif typedef struct { char tramp[FFI_TRAMPOLINE_SIZE]; ffi_cif *cif; void (*fun)(ffi_cif*,void*,void**,void*); void *user_data; +#ifdef __GNUC__ +} ffi_closure __attribute__((aligned (8))); +#else } ffi_closure; +#endif + +void *ffi_closure_alloc (size_t size, void **code); +void ffi_closure_free (void *); ffi_status ffi_prep_closure (ffi_closure*, @@ -227,6 +274,13 @@ void (*fun)(ffi_cif*,void*,void**,void*), void *user_data); +ffi_status +ffi_prep_closure_loc (ffi_closure*, + ffi_cif *, + void (*fun)(ffi_cif*,void*,void**,void*), + void *user_data, + void*codeloc); + typedef struct { char tramp[FFI_TRAMPOLINE_SIZE]; @@ -248,6 +302,27 @@ } ffi_raw_closure; +typedef struct { + char tramp[FFI_TRAMPOLINE_SIZE]; + + ffi_cif *cif; + +#if !FFI_NATIVE_RAW_API + + /* if this is enabled, then a raw closure has the same layout + as a regular closure. We use this to install an intermediate + handler to do the transaltion, void** -> ffi_raw*. */ + + void (*translate_args)(ffi_cif*,void*,void**,void*); + void *this_closure; + +#endif + + void (*fun)(ffi_cif*,void*,ffi_java_raw*,void*); + void *user_data; + +} ffi_java_raw_closure; + ffi_status ffi_prep_raw_closure (ffi_raw_closure*, ffi_cif *cif, @@ -255,29 +330,42 @@ void *user_data); ffi_status -ffi_prep_java_raw_closure (ffi_raw_closure*, +ffi_prep_raw_closure_loc (ffi_raw_closure*, + ffi_cif *cif, + void (*fun)(ffi_cif*,void*,ffi_raw*,void*), + void *user_data, + void *codeloc); + +ffi_status +ffi_prep_java_raw_closure (ffi_java_raw_closure*, ffi_cif *cif, - void (*fun)(ffi_cif*,void*,ffi_raw*,void*), + void (*fun)(ffi_cif*,void*,ffi_java_raw*,void*), void *user_data); +ffi_status +ffi_prep_java_raw_closure_loc (ffi_java_raw_closure*, + ffi_cif *cif, + void (*fun)(ffi_cif*,void*,ffi_java_raw*,void*), + void *user_data, + void *codeloc); + #endif /* FFI_CLOSURES */ /* ---- Public interface definition -------------------------------------- */ -ffi_status ffi_prep_cif(/*@out@*/ /*@partial@*/ ffi_cif *cif, +ffi_status ffi_prep_cif(ffi_cif *cif, ffi_abi abi, - unsigned int nargs, - /*@dependent@*/ /*@out@*/ /*@partial@*/ ffi_type *rtype, - /*@dependent@*/ ffi_type **atypes); - -int -ffi_call(/*@dependent@*/ ffi_cif *cif, - void (*fn)(), - /*@out@*/ void *rvalue, - /*@dependent@*/ void **avalue); + unsigned int nargs, + ffi_type *rtype, + ffi_type **atypes); + +void ffi_call(ffi_cif *cif, + void (*fn)(void), + void *rvalue, + void **avalue); /* Useful for eliminating compiler warnings */ -#define FFI_FN(f) ((void (*)())f) +#define FFI_FN(f) ((void (*)(void))f) /* ---- Definitions shared with assembly code ---------------------------- */ @@ -288,7 +376,7 @@ #define FFI_TYPE_INT 1 #define FFI_TYPE_FLOAT 2 #define FFI_TYPE_DOUBLE 3 -#if 1 +#if HAVE_LONG_DOUBLE #define FFI_TYPE_LONGDOUBLE 4 #else #define FFI_TYPE_LONGDOUBLE FFI_TYPE_DOUBLE @@ -312,4 +400,3 @@ #endif #endif - Deleted: python/branches/py3k/Modules/_ctypes/libffi_msvc/ffi_common.h ============================================================================== --- python/branches/py3k/Modules/_ctypes/libffi_msvc/ffi_common.h Tue May 4 21:17:41 2010 +++ (empty file) @@ -1,77 +0,0 @@ -/* ----------------------------------------------------------------------- - ffi_common.h - Copyright (c) 1996 Red Hat, Inc. - - Common internal definitions and macros. Only necessary for building - libffi. - ----------------------------------------------------------------------- */ - -#ifndef FFI_COMMON_H -#define FFI_COMMON_H - -#ifdef __cplusplus -extern "C" { -#endif - -#include -#include - -/* Check for the existence of memcpy. */ -#if STDC_HEADERS -# include -#else -# ifndef HAVE_MEMCPY -# define memcpy(d, s, n) bcopy ((s), (d), (n)) -# endif -#endif - -#if defined(FFI_DEBUG) -#include -#endif - -#ifdef FFI_DEBUG -/*@exits@*/ void ffi_assert(/*@temp@*/ char *expr, /*@temp@*/ char *file, int line); -void ffi_stop_here(void); -void ffi_type_test(/*@temp@*/ /*@out@*/ ffi_type *a, /*@temp@*/ char *file, int line); - -#define FFI_ASSERT(x) ((x) ? (void)0 : ffi_assert(#x, __FILE__,__LINE__)) -#define FFI_ASSERT_AT(x, f, l) ((x) ? 0 : ffi_assert(#x, (f), (l))) -#define FFI_ASSERT_VALID_TYPE(x) ffi_type_test (x, __FILE__, __LINE__) -#else -#define FFI_ASSERT(x) -#define FFI_ASSERT_AT(x, f, l) -#define FFI_ASSERT_VALID_TYPE(x) -#endif - -#define ALIGN(v, a) (((((size_t) (v))-1) | ((a)-1))+1) - -/* Perform machine dependent cif processing */ -ffi_status ffi_prep_cif_machdep(ffi_cif *cif); - -/* Extended cif, used in callback from assembly routine */ -typedef struct -{ - /*@dependent@*/ ffi_cif *cif; - /*@dependent@*/ void *rvalue; - /*@dependent@*/ void **avalue; -} extended_cif; - -/* Terse sized type definitions. */ -typedef unsigned int UINT8 __attribute__((__mode__(__QI__))); -typedef signed int SINT8 __attribute__((__mode__(__QI__))); -typedef unsigned int UINT16 __attribute__((__mode__(__HI__))); -typedef signed int SINT16 __attribute__((__mode__(__HI__))); -typedef unsigned int UINT32 __attribute__((__mode__(__SI__))); -typedef signed int SINT32 __attribute__((__mode__(__SI__))); -typedef unsigned int UINT64 __attribute__((__mode__(__DI__))); -typedef signed int SINT64 __attribute__((__mode__(__DI__))); - -typedef float FLOAT32; - - -#ifdef __cplusplus -} -#endif - -#endif - - Modified: python/branches/py3k/Modules/_ctypes/libffi_msvc/fficonfig.h ============================================================================== --- python/branches/py3k/Modules/_ctypes/libffi_msvc/fficonfig.h (original) +++ python/branches/py3k/Modules/_ctypes/libffi_msvc/fficonfig.h Tue May 4 21:17:41 2010 @@ -1,96 +1,186 @@ /* fficonfig.h. Originally created by configure, now hand_maintained for MSVC. */ -/* fficonfig.h. Generated automatically by configure. */ -/* fficonfig.h.in. Generated automatically from configure.in by autoheader. */ +/* fficonfig.h.in. Generated from configure.ac by autoheader. */ -/* Define this for MSVC, but not for mingw32! */ -#ifdef _MSC_VER -#define __attribute__(x) /* */ -#endif -#define alloca _alloca +/* Define if building universal (internal helper macro) */ +/* #undef AC_APPLE_UNIVERSAL_BUILD */ -/*----------------------------------------------------------------*/ +/* Define to one of `_getb67', `GETB67', `getb67' for Cray-2 and Cray-YMP + systems. This function is required for `alloca.c' support on those systems. + */ +/* #undef CRAY_STACKSEG_END */ -/* Define if using alloca.c. */ +/* Define to 1 if using `alloca.c'. */ /* #undef C_ALLOCA */ -/* Define to one of _getb67, GETB67, getb67 for Cray-2 and Cray-YMP systems. - This function is required for alloca.c support on those systems. */ -/* #undef CRAY_STACKSEG_END */ +/* Define to the flags needed for the .section .eh_frame directive. */ +/* #undef EH_FRAME_FLAGS */ -/* Define if you have alloca, as a function or macro. */ -#define HAVE_ALLOCA 1 +/* Define this if you want extra debugging. */ +/* #undef FFI_DEBUG */ -/* Define if you have and it should be used (not on Ultrix). */ -/* #define HAVE_ALLOCA_H 1 */ +/* Cannot use malloc on this target, so, we revert to alternative means */ +/* #undef FFI_MMAP_EXEC_WRIT */ -/* If using the C implementation of alloca, define if you know the - direction of stack growth for your system; otherwise it will be - automatically deduced at run-time. - STACK_DIRECTION > 0 => grows toward higher addresses - STACK_DIRECTION < 0 => grows toward lower addresses - STACK_DIRECTION = 0 => direction of growth unknown - */ -/* #undef STACK_DIRECTION */ +/* Define this is you do not want support for the raw API. */ +#define FFI_NO_RAW_API 1 -/* Define if you have the ANSI C header files. */ -#define STDC_HEADERS 1 +/* Define this is you do not want support for aggregate types. */ +/* #undef FFI_NO_STRUCTS */ -/* Define if you have the memcpy function. */ -#define HAVE_MEMCPY 1 +/* Define to 1 if you have `alloca', as a function or macro. */ +#define HAVE_ALLOCA 1 -/* Define if read-only mmap of a plain file works. */ -//#define HAVE_MMAP_FILE 1 +/* Define to 1 if you have and it should be used (not on Ultrix). + */ +/* #undef HAVE_ALLOCA_H */ -/* Define if mmap of /dev/zero works. */ -//#define HAVE_MMAP_DEV_ZERO 1 +/* Define if your assembler supports .cfi_* directives. */ +/* #undef HAVE_AS_CFI_PSEUDO_OP */ -/* Define if mmap with MAP_ANON(YMOUS) works. */ -//#define HAVE_MMAP_ANON 1 +/* Define if your assembler supports .register. */ +/* #undef HAVE_AS_REGISTER_PSEUDO_OP */ -/* The number of bytes in type double */ -#define SIZEOF_DOUBLE 8 +/* Define if your assembler and linker support unaligned PC relative relocs. + */ +/* #undef HAVE_AS_SPARC_UA_PCREL */ -/* The number of bytes in type long double */ -#define SIZEOF_LONG_DOUBLE 12 +/* Define if your assembler supports PC relative relocs. */ +/* #undef HAVE_AS_X86_PCREL */ + +/* Define to 1 if you have the header file. */ +/* #undef HAVE_DLFCN_H */ + +/* Define if __attribute__((visibility("hidden"))) is supported. */ +/* #undef HAVE_HIDDEN_VISIBILITY_ATTRIBUTE */ + +/* Define to 1 if you have the header file. */ +/* #undef HAVE_INTTYPES_H */ /* Define if you have the long double type and it is bigger than a double */ -#define HAVE_LONG_DOUBLE 1 +/* #undef HAVE_LONG_DOUBLE */ -/* whether byteorder is bigendian */ -/* #undef WORDS_BIGENDIAN */ +/* Define to 1 if you have the `memcpy' function. */ +#define HAVE_MEMCPY 1 -/* Define if the host machine stores words of multi-word integers in - big-endian order. */ -/* #undef HOST_WORDS_BIG_ENDIAN */ +/* Define to 1 if you have the header file. */ +/* #undef HAVE_MEMORY_H */ -/* 1234 = LIL_ENDIAN, 4321 = BIGENDIAN */ -#define BYTEORDER 1234 +/* Define to 1 if you have the `mmap' function. */ +/* #undef HAVE_MMAP */ -/* Define if your assembler and linker support unaligned PC relative relocs. */ -/* #undef HAVE_AS_SPARC_UA_PCREL */ +/* Define if mmap with MAP_ANON(YMOUS) works. */ +/* #undef HAVE_MMAP_ANON */ -/* Define if your assembler supports .register. */ -/* #undef HAVE_AS_REGISTER_PSEUDO_OP */ +/* Define if mmap of /dev/zero works. */ +/* #undef HAVE_MMAP_DEV_ZERO */ + +/* Define if read-only mmap of a plain file works. */ +/* #undef HAVE_MMAP_FILE */ /* Define if .eh_frame sections should be read-only. */ /* #undef HAVE_RO_EH_FRAME */ -/* Define to the flags needed for the .section .eh_frame directive. */ -/* #define EH_FRAME_FLAGS "aw" */ +/* Define to 1 if you have the header file. */ +#undef HAVE_STDINT_H -/* Define to the flags needed for the .section .eh_frame directive. */ -/* #define EH_FRAME_FLAGS "aw" */ +/* Define to 1 if you have the header file. */ +#undef HAVE_STDLIB_H -/* Define this if you want extra debugging. */ -/* #undef FFI_DEBUG */ +/* Define to 1 if you have the header file. */ +#undef HAVE_STRINGS_H -/* Define this is you do not want support for aggregate types. */ -/* #undef FFI_NO_STRUCTS */ +/* Define to 1 if you have the header file. */ +#undef HAVE_STRING_H -/* Define this is you do not want support for the raw API. */ -/* #undef FFI_NO_RAW_API */ +/* Define to 1 if you have the header file. */ +/* #undef HAVE_SYS_MMAN_H */ + +/* Define to 1 if you have the header file. */ +/* #undef HAVE_SYS_STAT_H */ + +/* Define to 1 if you have the header file. */ +/* #undef HAVE_SYS_TYPES_H */ + +/* Define to 1 if you have the header file. */ +/* #undef HAVE_UNISTD_H */ + +/* Define to the sub-directory in which libtool stores uninstalled libraries. + */ +/* #undef LT_OBJDIR */ + +/* Define to 1 if your C compiler doesn't accept -c and -o together. */ +/* #undef NO_MINUS_C_MINUS_O */ + +/* Name of package */ +/* #undef PACKAGE */ + +/* Define to the address where bug reports for this package should be sent. */ +/* #undef PACKAGE_BUGREPORT */ + +/* Define to the full name of this package. */ +/* #undef PACKAGE_NAME */ + +/* Define to the full name and version of this package. */ +/* #undef PACKAGE_STRING */ + +/* Define to the one symbol short name of this package. */ +/* #undef PACKAGE_TARNAME */ + +/* Define to the home page for this package. */ +/* #undef PACKAGE_URL */ + +/* Define to the version of this package. */ +/* #undef PACKAGE_VERSION */ -/* Define this if you are using Purify and want to suppress spurious messages. */ +/* The size of `double', as computed by sizeof. */ +#define SIZEOF_DOUBLE 8 + +/* The size of `long double', as computed by sizeof. */ +#undef SIZEOF_LONG_DOUBLE + +/* If using the C implementation of alloca, define if you know the + direction of stack growth for your system; otherwise it will be + automatically deduced at runtime. + STACK_DIRECTION > 0 => grows toward higher addresses + STACK_DIRECTION < 0 => grows toward lower addresses + STACK_DIRECTION = 0 => direction of growth unknown */ +/* #undef STACK_DIRECTION */ + +/* Define to 1 if you have the ANSI C header files. */ +#define STDC_HEADERS 1 + +/* Define this if you are using Purify and want to suppress spurious messages. + */ /* #undef USING_PURIFY */ +/* Version number of package */ +/* #undef VERSION */ + +/* Define WORDS_BIGENDIAN to 1 if your processor stores words with the most + significant byte first (like Motorola and SPARC, unlike Intel). */ +#if defined AC_APPLE_UNIVERSAL_BUILD +# if defined __BIG_ENDIAN__ +# define WORDS_BIGENDIAN 1 +# endif +#else +# ifndef WORDS_BIGENDIAN +# undef WORDS_BIGENDIAN +# endif +#endif + + +#ifdef HAVE_HIDDEN_VISIBILITY_ATTRIBUTE +#ifdef LIBFFI_ASM +#define FFI_HIDDEN(name) .hidden name +#else +#define FFI_HIDDEN __attribute__ ((visibility ("hidden"))) +#endif +#else +#ifdef LIBFFI_ASM +#define FFI_HIDDEN(name) +#else +#define FFI_HIDDEN +#endif +#endif + Deleted: python/branches/py3k/Modules/_ctypes/libffi_msvc/ffitarget.h ============================================================================== --- python/branches/py3k/Modules/_ctypes/libffi_msvc/ffitarget.h Tue May 4 21:17:41 2010 +++ (empty file) @@ -1,85 +0,0 @@ -/* -----------------------------------------------------------------*-C-*- - ffitarget.h - Copyright (c) 1996-2003 Red Hat, Inc. - Target configuration macros for x86 and x86-64. - - 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 CYGNUS SOLUTIONS 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. - - ----------------------------------------------------------------------- */ - -#ifndef LIBFFI_TARGET_H -#define LIBFFI_TARGET_H - -/* ---- System specific configurations ----------------------------------- */ - -#if defined (X86_64) && defined (__i386__) -#undef X86_64 -#define X86 -#endif - -/* ---- Generic type definitions ----------------------------------------- */ - -#ifndef LIBFFI_ASM -#ifndef _WIN64 -typedef unsigned long ffi_arg; -#else -typedef unsigned __int64 ffi_arg; -#endif -typedef signed long ffi_sarg; - -typedef enum ffi_abi { - FFI_FIRST_ABI = 0, - - /* ---- Intel x86 Win32 ---------- */ - FFI_SYSV, -#ifndef _WIN64 - FFI_STDCALL, -#endif - /* TODO: Add fastcall support for the sake of completeness */ - FFI_DEFAULT_ABI = FFI_SYSV, - - /* ---- Intel x86 and AMD x86-64 - */ -/* #if !defined(X86_WIN32) && (defined(__i386__) || defined(__x86_64__)) */ -/* FFI_SYSV, */ -/* FFI_UNIX64,*/ /* Unix variants all use the same ABI for x86-64 */ -/* #ifdef __i386__ */ -/* FFI_DEFAULT_ABI = FFI_SYSV, */ -/* #else */ -/* FFI_DEFAULT_ABI = FFI_UNIX64, */ -/* #endif */ -/* #endif */ - - FFI_LAST_ABI = FFI_DEFAULT_ABI + 1 -} ffi_abi; -#endif - -/* ---- Definitions for closures ----------------------------------------- */ - -#define FFI_CLOSURES 1 - -#ifdef _WIN64 -#define FFI_TRAMPOLINE_SIZE 29 -#define FFI_NATIVE_RAW_API 0 -#else -#define FFI_TRAMPOLINE_SIZE 15 -#define FFI_NATIVE_RAW_API 1 /* x86 has native raw api support */ -#endif - -#endif - Deleted: python/branches/py3k/Modules/_ctypes/libffi_msvc/prep_cif.c ============================================================================== --- python/branches/py3k/Modules/_ctypes/libffi_msvc/prep_cif.c Tue May 4 21:17:41 2010 +++ (empty file) @@ -1,175 +0,0 @@ -/* ----------------------------------------------------------------------- - prep_cif.c - Copyright (c) 1996, 1998 Red Hat, Inc. - - 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 CYGNUS SOLUTIONS 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. - ----------------------------------------------------------------------- */ - -#include -#include -#include - - -/* Round up to FFI_SIZEOF_ARG. */ - -#define STACK_ARG_SIZE(x) ALIGN(x, FFI_SIZEOF_ARG) - -/* Perform machine independent initialization of aggregate type - specifications. */ - -static ffi_status initialize_aggregate(/*@out@*/ ffi_type *arg) -{ - ffi_type **ptr; - - FFI_ASSERT(arg != NULL); - - /*@-usedef@*/ - - FFI_ASSERT(arg->elements != NULL); - FFI_ASSERT(arg->size == 0); - FFI_ASSERT(arg->alignment == 0); - - ptr = &(arg->elements[0]); - - while ((*ptr) != NULL) - { - if (((*ptr)->size == 0) && (initialize_aggregate((*ptr)) != FFI_OK)) - return FFI_BAD_TYPEDEF; - - /* Perform a sanity check on the argument type */ - FFI_ASSERT_VALID_TYPE(*ptr); - - arg->size = ALIGN(arg->size, (*ptr)->alignment); - arg->size += (*ptr)->size; - - arg->alignment = (arg->alignment > (*ptr)->alignment) ? - arg->alignment : (*ptr)->alignment; - - ptr++; - } - - /* Structure size includes tail padding. This is important for - structures that fit in one register on ABIs like the PowerPC64 - Linux ABI that right justify small structs in a register. - It's also needed for nested structure layout, for example - struct A { long a; char b; }; struct B { struct A x; char y; }; - should find y at an offset of 2*sizeof(long) and result in a - total size of 3*sizeof(long). */ - arg->size = ALIGN (arg->size, arg->alignment); - - if (arg->size == 0) - return FFI_BAD_TYPEDEF; - else - return FFI_OK; - - /*@=usedef@*/ -} - -/* Perform machine independent ffi_cif preparation, then call - machine dependent routine. */ - -ffi_status ffi_prep_cif(/*@out@*/ /*@partial@*/ ffi_cif *cif, - ffi_abi abi, unsigned int nargs, - /*@dependent@*/ /*@out@*/ /*@partial@*/ ffi_type *rtype, - /*@dependent@*/ ffi_type **atypes) -{ - unsigned bytes = 0; - unsigned int i; - ffi_type **ptr; - - FFI_ASSERT(cif != NULL); - FFI_ASSERT((abi > FFI_FIRST_ABI) && (abi <= FFI_DEFAULT_ABI)); - - cif->abi = abi; - cif->arg_types = atypes; - cif->nargs = nargs; - cif->rtype = rtype; - - cif->flags = 0; - - /* Initialize the return type if necessary */ - /*@-usedef@*/ - if ((cif->rtype->size == 0) && (initialize_aggregate(cif->rtype) != FFI_OK)) - return FFI_BAD_TYPEDEF; - /*@=usedef@*/ - - /* Perform a sanity check on the return type */ - FFI_ASSERT_VALID_TYPE(cif->rtype); - - /* x86-64 and s390 stack space allocation is handled in prep_machdep. */ -#if !defined M68K && !defined __x86_64__ && !defined S390 - /* Make space for the return structure pointer */ - if (cif->rtype->type == FFI_TYPE_STRUCT - /* MSVC returns small structures in registers. But we have a different - workaround: pretend int32 or int64 return type, and converting to - structure afterwards. */ -#ifdef SPARC - && (cif->abi != FFI_V9 || cif->rtype->size > 32) -#endif - ) - bytes = STACK_ARG_SIZE(sizeof(void*)); -#endif - - for (ptr = cif->arg_types, i = cif->nargs; i > 0; i--, ptr++) - { - - /* Initialize any uninitialized aggregate type definitions */ - if (((*ptr)->size == 0) && (initialize_aggregate((*ptr)) != FFI_OK)) - return FFI_BAD_TYPEDEF; - - /* Perform a sanity check on the argument type, do this - check after the initialization. */ - FFI_ASSERT_VALID_TYPE(*ptr); - -#if !defined __x86_64__ && !defined S390 -#ifdef SPARC - if (((*ptr)->type == FFI_TYPE_STRUCT - && ((*ptr)->size > 16 || cif->abi != FFI_V9)) - || ((*ptr)->type == FFI_TYPE_LONGDOUBLE - && cif->abi != FFI_V9)) - bytes += sizeof(void*); - else -#endif - { -#if !defined(_MSC_VER) && !defined(__MINGW32__) - /* Don't know if this is a libffi bug or not. At least on - Windows with MSVC, function call parameters are *not* - aligned in the same way as structure fields are, they are - only aligned in integer boundaries. - - This doesn't do any harm for cdecl functions and closures, - since the caller cleans up the stack, but it is wrong for - stdcall functions where the callee cleans. - */ - - /* Add any padding if necessary */ - if (((*ptr)->alignment - 1) & bytes) - bytes = ALIGN(bytes, (*ptr)->alignment); - -#endif - bytes += (unsigned)STACK_ARG_SIZE((*ptr)->size); - } -#endif - } - - cif->bytes = bytes; - - /* Perform machine dependent cif processing */ - return ffi_prep_cif_machdep(cif); -} Deleted: python/branches/py3k/Modules/_ctypes/libffi_msvc/types.c ============================================================================== --- python/branches/py3k/Modules/_ctypes/libffi_msvc/types.c Tue May 4 21:17:41 2010 +++ (empty file) @@ -1,104 +0,0 @@ -/* ----------------------------------------------------------------------- - types.c - Copyright (c) 1996, 1998 Red Hat, Inc. - - Predefined ffi_types needed by libffi. - - 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 CYGNUS SOLUTIONS 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. - ----------------------------------------------------------------------- */ - -#include -#include - -/* Type definitions */ - -#define FFI_INTEGRAL_TYPEDEF(n, s, a, t) ffi_type ffi_type_##n = { s, a, t, NULL } -#define FFI_AGGREGATE_TYPEDEF(n, e) ffi_type ffi_type_##n = { 0, 0, FFI_TYPE_STRUCT, e } - -/* Size and alignment are fake here. They must not be 0. */ -FFI_INTEGRAL_TYPEDEF(void, 1, 1, FFI_TYPE_VOID); - -FFI_INTEGRAL_TYPEDEF(uint8, 1, 1, FFI_TYPE_UINT8); -FFI_INTEGRAL_TYPEDEF(sint8, 1, 1, FFI_TYPE_SINT8); -FFI_INTEGRAL_TYPEDEF(uint16, 2, 2, FFI_TYPE_UINT16); -FFI_INTEGRAL_TYPEDEF(sint16, 2, 2, FFI_TYPE_SINT16); -FFI_INTEGRAL_TYPEDEF(uint32, 4, 4, FFI_TYPE_UINT32); -FFI_INTEGRAL_TYPEDEF(sint32, 4, 4, FFI_TYPE_SINT32); -FFI_INTEGRAL_TYPEDEF(float, 4, 4, FFI_TYPE_FLOAT); - -#if defined ALPHA || defined SPARC64 || defined X86_64 || defined S390X \ - || defined IA64 - -FFI_INTEGRAL_TYPEDEF(pointer, 8, 8, FFI_TYPE_POINTER); - -#else - -FFI_INTEGRAL_TYPEDEF(pointer, 4, 4, FFI_TYPE_POINTER); - -#endif - -#if defined X86 || defined X86_WIN32 || defined ARM || defined M68K - -FFI_INTEGRAL_TYPEDEF(uint64, 8, 4, FFI_TYPE_UINT64); -FFI_INTEGRAL_TYPEDEF(sint64, 8, 4, FFI_TYPE_SINT64); - -#elif defined SH - -FFI_INTEGRAL_TYPEDEF(uint64, 8, 4, FFI_TYPE_UINT64); -FFI_INTEGRAL_TYPEDEF(sint64, 8, 4, FFI_TYPE_SINT64); - -#else - -FFI_INTEGRAL_TYPEDEF(uint64, 8, 8, FFI_TYPE_UINT64); -FFI_INTEGRAL_TYPEDEF(sint64, 8, 8, FFI_TYPE_SINT64); - -#endif - - -#if defined X86 || defined X86_WIN32 || defined M68K - -FFI_INTEGRAL_TYPEDEF(double, 8, 4, FFI_TYPE_DOUBLE); -FFI_INTEGRAL_TYPEDEF(longdouble, 12, 4, FFI_TYPE_LONGDOUBLE); - -#elif defined ARM || defined SH || defined POWERPC_AIX || defined POWERPC_DARWIN - -FFI_INTEGRAL_TYPEDEF(double, 8, 4, FFI_TYPE_DOUBLE); -FFI_INTEGRAL_TYPEDEF(longdouble, 8, 4, FFI_TYPE_LONGDOUBLE); - -#elif defined SPARC - -FFI_INTEGRAL_TYPEDEF(double, 8, 8, FFI_TYPE_DOUBLE); -#ifdef SPARC64 -FFI_INTEGRAL_TYPEDEF(longdouble, 16, 16, FFI_TYPE_LONGDOUBLE); -#else -FFI_INTEGRAL_TYPEDEF(longdouble, 16, 8, FFI_TYPE_LONGDOUBLE); -#endif - -#elif defined X86_64 - -FFI_INTEGRAL_TYPEDEF(double, 8, 8, FFI_TYPE_DOUBLE); -FFI_INTEGRAL_TYPEDEF(longdouble, 16, 16, FFI_TYPE_LONGDOUBLE); - -#else - -FFI_INTEGRAL_TYPEDEF(double, 8, 8, FFI_TYPE_DOUBLE); -FFI_INTEGRAL_TYPEDEF(longdouble, 8, 8, FFI_TYPE_LONGDOUBLE); - -#endif - Deleted: python/branches/py3k/Modules/_ctypes/libffi_msvc/win32.c ============================================================================== --- python/branches/py3k/Modules/_ctypes/libffi_msvc/win32.c Tue May 4 21:17:41 2010 +++ (empty file) @@ -1,162 +0,0 @@ -/* ----------------------------------------------------------------------- - win32.S - Copyright (c) 1996, 1998, 2001, 2002 Red Hat, Inc. - Copyright (c) 2001 John Beniton - Copyright (c) 2002 Ranjit Mathew - - - X86 Foreign Function Interface - - 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 CYGNUS SOLUTIONS 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. - ----------------------------------------------------------------------- */ - -/* theller: almost verbatim translation from gas syntax to MSVC inline - assembler code. */ - -/* theller: ffi_call_x86 now returns an integer - the difference of the stack - pointer before and after the function call. If everything is ok, zero is - returned. If stdcall functions are passed the wrong number of arguments, - the difference will be nonzero. */ - -#include -#include - -__declspec(naked) int -ffi_call_x86(void (* prepfunc)(char *, extended_cif *), /* 8 */ - extended_cif *ecif, /* 12 */ - unsigned bytes, /* 16 */ - unsigned flags, /* 20 */ - unsigned *rvalue, /* 24 */ - void (*fn)()) /* 28 */ -{ - _asm { - push ebp - mov ebp, esp - - push esi // NEW: this register must be preserved across function calls -// XXX SAVE ESP NOW! - mov esi, esp // save stack pointer before the call - -// Make room for all of the new args. - mov ecx, [ebp+16] - sub esp, ecx // sub esp, bytes - - mov eax, esp - -// Place all of the ffi_prep_args in position - push [ebp + 12] // ecif - push eax - call [ebp + 8] // prepfunc - -// Return stack to previous state and call the function - add esp, 8 -// FIXME: Align the stack to a 128-bit boundary to avoid -// potential performance hits. - call [ebp + 28] - -// Load ecif->cif->abi - mov ecx, [ebp + 12] - mov ecx, [ecx]ecif.cif - mov ecx, [ecx]ecif.cif.abi - - cmp ecx, FFI_STDCALL - je noclean -// STDCALL: Remove the space we pushed for the args - mov ecx, [ebp + 16] - add esp, ecx -// CDECL: Caller has already cleaned the stack -noclean: -// Check that esp has the same value as before! - sub esi, esp - -// Load %ecx with the return type code - mov ecx, [ebp + 20] - -// If the return value pointer is NULL, assume no return value. -/* - Intel asm is weird. We have to explicitely specify 'DWORD PTR' in the nexr instruction, - otherwise only one BYTE will be compared (instead of a DWORD)! - */ - cmp DWORD PTR [ebp + 24], 0 - jne sc_retint - -// Even if there is no space for the return value, we are -// obliged to handle floating-point values. - cmp ecx, FFI_TYPE_FLOAT - jne sc_noretval -// fstp %st(0) - fstp st(0) - - jmp sc_epilogue - -sc_retint: - cmp ecx, FFI_TYPE_INT - jne sc_retfloat -// # Load %ecx with the pointer to storage for the return value - mov ecx, [ebp + 24] - mov [ecx + 0], eax - jmp sc_epilogue - -sc_retfloat: - cmp ecx, FFI_TYPE_FLOAT - jne sc_retdouble -// Load %ecx with the pointer to storage for the return value - mov ecx, [ebp+24] -// fstps (%ecx) - fstp DWORD PTR [ecx] - jmp sc_epilogue - -sc_retdouble: - cmp ecx, FFI_TYPE_DOUBLE - jne sc_retlongdouble -// movl 24(%ebp),%ecx - mov ecx, [ebp+24] - fstp QWORD PTR [ecx] - jmp sc_epilogue - - jmp sc_retlongdouble // avoid warning about unused label -sc_retlongdouble: - cmp ecx, FFI_TYPE_LONGDOUBLE - jne sc_retint64 -// Load %ecx with the pointer to storage for the return value - mov ecx, [ebp+24] -// fstpt (%ecx) - fstp QWORD PTR [ecx] /* XXX ??? */ - jmp sc_epilogue - -sc_retint64: - cmp ecx, FFI_TYPE_SINT64 - jne sc_retstruct -// Load %ecx with the pointer to storage for the return value - mov ecx, [ebp+24] - mov [ecx+0], eax - mov [ecx+4], edx - -sc_retstruct: -// Nothing to do! - -sc_noretval: -sc_epilogue: - mov eax, esi - pop esi // NEW restore: must be preserved across function calls - mov esp, ebp - pop ebp - ret - } -} Deleted: python/branches/py3k/Modules/_ctypes/libffi_msvc/win64.asm ============================================================================== --- python/branches/py3k/Modules/_ctypes/libffi_msvc/win64.asm Tue May 4 21:17:41 2010 +++ (empty file) @@ -1,156 +0,0 @@ -PUBLIC ffi_call_AMD64 - -EXTRN __chkstk:NEAR -EXTRN ffi_closure_SYSV:NEAR - -_TEXT SEGMENT - -;;; ffi_closure_OUTER will be called with these registers set: -;;; rax points to 'closure' -;;; r11 contains a bit mask that specifies which of the -;;; first four parameters are float or double -;;; -;;; It must move the parameters passed in registers to their stack location, -;;; call ffi_closure_SYSV for the actual work, then return the result. -;;; -ffi_closure_OUTER PROC FRAME - ;; save actual arguments to their stack space. - test r11, 1 - jne first_is_float - mov QWORD PTR [rsp+8], rcx - jmp second -first_is_float: - movlpd QWORD PTR [rsp+8], xmm0 - -second: - test r11, 2 - jne second_is_float - mov QWORD PTR [rsp+16], rdx - jmp third -second_is_float: - movlpd QWORD PTR [rsp+16], xmm1 - -third: - test r11, 4 - jne third_is_float - mov QWORD PTR [rsp+24], r8 - jmp forth -third_is_float: - movlpd QWORD PTR [rsp+24], xmm2 - -forth: - test r11, 8 - jne forth_is_float - mov QWORD PTR [rsp+32], r9 - jmp done -forth_is_float: - movlpd QWORD PTR [rsp+32], xmm3 - -done: -.ALLOCSTACK 40 - sub rsp, 40 -.ENDPROLOG - mov rcx, rax ; context is first parameter - mov rdx, rsp ; stack is second parameter - add rdx, 40 ; correct our own area - mov rax, ffi_closure_SYSV - call rax ; call the real closure function - ;; Here, code is missing that handles float return values - add rsp, 40 - movd xmm0, rax ; In case the closure returned a float. - ret 0 -ffi_closure_OUTER ENDP - - -;;; ffi_call_AMD64 - -stack$ = 0 -prepfunc$ = 32 -ecif$ = 40 -bytes$ = 48 -flags$ = 56 -rvalue$ = 64 -fn$ = 72 - -ffi_call_AMD64 PROC FRAME - - mov QWORD PTR [rsp+32], r9 - mov QWORD PTR [rsp+24], r8 - mov QWORD PTR [rsp+16], rdx - mov QWORD PTR [rsp+8], rcx -.PUSHREG rbp - push rbp -.ALLOCSTACK 48 - sub rsp, 48 ; 00000030H -.SETFRAME rbp, 32 - lea rbp, QWORD PTR [rsp+32] -.ENDPROLOG - - mov eax, DWORD PTR bytes$[rbp] - add rax, 15 - and rax, -16 - call __chkstk - sub rsp, rax - lea rax, QWORD PTR [rsp+32] - mov QWORD PTR stack$[rbp], rax - - mov rdx, QWORD PTR ecif$[rbp] - mov rcx, QWORD PTR stack$[rbp] - call QWORD PTR prepfunc$[rbp] - - mov rsp, QWORD PTR stack$[rbp] - - movlpd xmm3, QWORD PTR [rsp+24] - movd r9, xmm3 - - movlpd xmm2, QWORD PTR [rsp+16] - movd r8, xmm2 - - movlpd xmm1, QWORD PTR [rsp+8] - movd rdx, xmm1 - - movlpd xmm0, QWORD PTR [rsp] - movd rcx, xmm0 - - call QWORD PTR fn$[rbp] -ret_int$: - cmp DWORD PTR flags$[rbp], 1 ; FFI_TYPE_INT - jne ret_float$ - - mov rcx, QWORD PTR rvalue$[rbp] - mov DWORD PTR [rcx], eax - jmp SHORT ret_nothing$ - -ret_float$: - cmp DWORD PTR flags$[rbp], 2 ; FFI_TYPE_FLOAT - jne SHORT ret_double$ - - mov rax, QWORD PTR rvalue$[rbp] - movlpd QWORD PTR [rax], xmm0 - jmp SHORT ret_nothing$ - -ret_double$: - cmp DWORD PTR flags$[rbp], 3 ; FFI_TYPE_DOUBLE - jne SHORT ret_int64$ - - mov rax, QWORD PTR rvalue$[rbp] - movlpd QWORD PTR [rax], xmm0 - jmp SHORT ret_nothing$ - -ret_int64$: - cmp DWORD PTR flags$[rbp], 12 ; FFI_TYPE_SINT64 - jne ret_nothing$ - - mov rcx, QWORD PTR rvalue$[rbp] - mov QWORD PTR [rcx], rax - jmp SHORT ret_nothing$ - -ret_nothing$: - xor eax, eax - - lea rsp, QWORD PTR [rbp+16] - pop rbp - ret 0 -ffi_call_AMD64 ENDP -_TEXT ENDS -END Modified: python/branches/py3k/PCbuild/_ctypes.vcproj ============================================================================== --- python/branches/py3k/PCbuild/_ctypes.vcproj (original) +++ python/branches/py3k/PCbuild/_ctypes.vcproj Tue May 4 21:17:41 2010 @@ -1,7 +1,7 @@ @@ -575,15 +583,23 @@ > + + + + + + + + + + + + + + + From brett at python.org Tue May 4 22:03:36 2010 From: brett at python.org (Brett Cannon) Date: Tue, 4 May 2010 13:03:36 -0700 Subject: [Python-checkins] r80742 - python/trunk/Modules/readline.c In-Reply-To: <201005041034.22942.victor.stinner@haypocalc.com> References: <20100504005242.2B791E308@mail.python.org> <201005041034.22942.victor.stinner@haypocalc.com> Message-ID: On Tue, May 4, 2010 at 01:34, Victor Stinner wrote: > Le mardi 04 mai 2010 02:52:42, brett.cannon a ?crit : > > Author: brett.cannon > > New Revision: 80742 > > > > Log: > > Strip out extraneous whitespace, cast a some `const char *` to `void *` > > when passed to free() and make a `char *` to a `const char *` as found > by > > Clang's static analyzer. > > On my version of readline (6.1), HIST_ENTRY has no const field: > > typedef struct _hist_entry { > char *line; > char *timestamp; /* char * rather than time_t for read/write > */ > histdata_t data; > } HIST_ENTRY; > > Is it different in your version of readline? > I'm on OS X, so I think I might be linking against libedit. Either way the cast shouldn't harm anything as the char* pointer contents are not modified in any way by the function. Is the cast triggering a compiler warning for you? -Brett > > > Modified: > > python/trunk/Modules/readline.c > > > > @@ -378,7 +378,7 @@ > > } > > /* free memory allocated for the history entry */ > > if (entry->line) > > - free(entry->line); > > + free((void *)entry->line); > > if (entry->data) > > free(entry->data); > > free(entry); > > @@ -415,7 +415,7 @@ > > } > > /* free memory allocated for the old history entry */ > > if (old_entry->line) > > - free(old_entry->line); > > + free((void *)old_entry->line); > > if (old_entry->data) > > free(old_entry->data); > > free(old_entry); > > ... > > > @@ -1023,17 +1023,17 @@ > > /* we have a valid line */ > > n = strlen(p); > > if (n > 0) { > > - char *line; > > + const char *line; > > HISTORY_STATE *state = history_get_history_state(); > > if (state->length > 0) > > #ifdef __APPLE__ > > -- > Victor Stinner > http://www.haypocalc.com/ > _______________________________________________ > Python-checkins mailing list > Python-checkins at python.org > http://mail.python.org/mailman/listinfo/python-checkins > -------------- next part -------------- An HTML attachment was scrubbed... URL: From python-checkins at python.org Tue May 4 22:17:35 2010 From: python-checkins at python.org (antoine.pitrou) Date: Tue, 4 May 2010 22:17:35 +0200 (CEST) Subject: [Python-checkins] r80768 - in sandbox/trunk/untabify: untabify.py Message-ID: <20100504201735.6283EEE9C1@mail.python.org> Author: antoine.pitrou Date: Tue May 4 22:17:35 2010 New Revision: 80768 Log: A script un-tab-ifying C files Added: sandbox/trunk/untabify/ sandbox/trunk/untabify/untabify.py (contents, props changed) Added: sandbox/trunk/untabify/untabify.py ============================================================================== --- (empty file) +++ sandbox/trunk/untabify/untabify.py Tue May 4 22:17:35 2010 @@ -0,0 +1,167 @@ +#!/usr/bin/env python + +""" +Untabify C files, converting them from tab indent to 4-spaces indent. +Tries to take care of continuation lines, as well as vertical alignment. +Gives sufficiently good results on most files of the source tree; visual +inspection is still recommended to fix possible cosmetic breakage. + +Notes: + +- only whitespace is added/removed, therefore compilation can't be + broken. +- only run on files really using tab indent; this shouldn't be run on files + already using 4-spaces indent (use -l option to list files using tab indent) +""" + +import os +import re +import sys +import tempfile +import optparse +import itertools + + +def untabify(lines, write): + last_indent = 0 + last_outdent = 0 + last_outline = "" + for line in lines: + cr = line.find('\r') + lf = line.find('\r') + if lf == -1: + eolpos = cr + elif cr == -1: + eolpos = lf + else: + assert cr != -1 and lf != -1 + eolpos = min(cr, lf) + eol = line[eolpos:] + line = line.rstrip() + chunks = line.split("\t") + output = [] + outpos = 0 + inpos = 0 + # Count leading spaces + for n, c in enumerate(chunks): + if not c: + inpos = (inpos // 8 + 1) * 8 + outpos += 4 + continue + if not c.startswith(' '): + break + chunks[n] = c.lstrip(' ') + k = len(c) - len(chunks[n]) + inpos += k + outpos += k + if chunks[n]: + break + inpos = (inpos // 8 + 1) * 8 + outpos += 4 + # Continuation line? + if (inpos > last_indent + 8 + # labels and end-of-comments can't be continued + and not last_outline.endswith(':') + and not last_outline.endswith('*/')): + outpos = inpos + (last_outdent - last_indent) + #print "--- Continuation line inpos=%d outpos=%d" % (inpos, outpos) + indent = last_indent + outdent = last_outdent + else: + outpos = (inpos // 8) * 4 + (inpos % 8) + indent = inpos + outdent = outpos + output.append(' ' * outpos) + # Process rest of the line, fixing position of internal tabs + for c in chunks[n:-1]: + output.append(c) + outpos += len(c) + inpos += len(c) + inpos = (inpos // 8 + 1) * 8 + output.append((inpos - outpos) * " ") + outpos = inpos + output.append(chunks[-1]) + outline = "".join(output).rstrip() + if outline and not outline.startswith('#'): + # Non-empty, non-preprocessor line: + # remember indentation for detection of continuation lines + last_indent = indent + last_outdent = outdent + last_outline = outline + write(outline) + write(eol) + + +def needs_untabifying(filepath): + f = open(filepath, "rb") + try: + s = f.read(65536) + # Heuristic: we don't want a couple of lone tabs to show as false + # positives + return s.count("\n\t") + s.count("\r\t") > 5 + finally: + f.close() + +def walk_c_files(paths): + for p in paths: + if os.path.isfile(p): + yield p + for dirpath, dirnames, filenames in os.walk(p): + for fn in sorted(filenames): + if fn.endswith('.h') or fn.endswith('.c'): + yield os.path.join(dirpath, fn) + +def main(): + parser = optparse.OptionParser() + parser.add_option("-l", "--list", dest="do_list_true", + action="store_true", default=False, + help="list files needing untabifying") + parser.add_option("-n", "--list-neg", dest="do_list_false", + action="store_true", default=False, + help="list files *not* needing untabifying") + parser.add_option("-u", "--untabify", dest="do_untab", + action="store_true", default=False, + help="untabify stdin to stdout") + parser.add_option("-b", "--batch", dest="do_batch", + action="store_true", default=False, + help="untabify specified files and dirs") + options, args = parser.parse_args() + if (options.do_list_true + options.do_list_false + + options.do_untab + options.do_batch != 1): + parser.error("you must specify exactly one of -l, -n, -b and -u") + + if options.do_list_true or options.do_list_false: + if not args: + parser.error("-l and -n need a directory path") + _filter = (itertools.ifilter if options.do_list_true else + itertools.ifilterfalse) + for cfn in _filter(needs_untabifying, + walk_c_files(args)): + print cfn + return + + if options.do_batch: + if not args: + parser.error("-b needs a file or directory path") + for cfn in itertools.ifilter(needs_untabifying, + walk_c_files(args)): + fd, tmpfn = tempfile.mkstemp(dir='.') + try: + fin = open(cfn, "rb") + fout = os.fdopen(fd, "wb") + print "Untabifing %s" % cfn + try: + untabify(fin, fout.write) + finally: + fin.close() + fout.close() + os.rename(tmpfn, cfn) + except: + os.unlink(tmpfn) + + if options.do_untab: + untabify(sys.stdin, sys.stdout.write) + +if __name__ == '__main__': + main() + From python-checkins at python.org Tue May 4 22:47:05 2010 From: python-checkins at python.org (benjamin.peterson) Date: Tue, 4 May 2010 22:47:05 +0200 (CEST) Subject: [Python-checkins] r80769 - peps/trunk/pep-0373.txt Message-ID: <20100504204705.043B0EE9C3@mail.python.org> Author: benjamin.peterson Date: Tue May 4 22:47:04 2010 New Revision: 80769 Log: push releases back a week Modified: peps/trunk/pep-0373.txt Modified: peps/trunk/pep-0373.txt ============================================================================== --- peps/trunk/pep-0373.txt (original) +++ peps/trunk/pep-0373.txt Tue May 4 22:47:04 2010 @@ -41,10 +41,10 @@ - 2.7 alpha 3 2010-02-06 - 2.7 alpha 4 2010-03-06 - 2.7 beta 1 2010-04-03 -- 2.7 beta 2 2010-05-01 -- 2.7 rc1 2010-05-29 -- 2.7 rc2 2010-06-12 -- 2.7 final 2010-06-26 +- 2.7 beta 2 2010-05-08 +- 2.7 rc1 2010-06-05 +- 2.7 rc2 2010-06-19 +- 2.7 final 2010-07-03 Possible features for 2.7 From python-checkins at python.org Tue May 4 23:54:55 2010 From: python-checkins at python.org (antoine.pitrou) Date: Tue, 4 May 2010 23:54:55 +0200 (CEST) Subject: [Python-checkins] r80770 - sandbox/trunk/untabify/untabify.py Message-ID: <20100504215455.5E5F3EE9D4@mail.python.org> Author: antoine.pitrou Date: Tue May 4 23:54:55 2010 New Revision: 80770 Log: Add another fixup mode for files mixing 4-spaces and tabs Modified: sandbox/trunk/untabify/untabify.py Modified: sandbox/trunk/untabify/untabify.py ============================================================================== --- sandbox/trunk/untabify/untabify.py (original) +++ sandbox/trunk/untabify/untabify.py Tue May 4 23:54:55 2010 @@ -1,5 +1,7 @@ #!/usr/bin/env python +from __future__ import with_statement + """ Untabify C files, converting them from tab indent to 4-spaces indent. Tries to take care of continuation lines, as well as vertical alignment. @@ -12,6 +14,28 @@ broken. - only run on files really using tab indent; this shouldn't be run on files already using 4-spaces indent (use -l option to list files using tab indent) + +Recipe for conversion of the whole source tree: + + $ untabify.py -b . + # Revert copy of external lib + $ svn revert -R Modules/_ctypes/libffi* + # Revert files with mixed 4-spaces and tabs (they need separate handling) + $ BADFILES="Modules/_hashopenssl.c Modules/_curses_panel.c Modules/_bsddb.c \ + Modules/unicodedata.c Modules/shamodule.c Modules/_hotshot.c \ + Modules/pyexpat.c Modules/parsermodule.c Modules/sha256module.c \ + Modules/fpectlmodule.c Modules/md5.c Modules/getpath.c \ + Modules/sha512module.c Modules/_codecsmodule.c Modules/zlibmodule.c \ + Objects/bytes_methods.c Objects/exceptions.c \ + Objects/weakrefobject.c \ + Objects/stringlib/string_format.h \ + Python/codecs.c" + $ svn revert $BADFILES + $ untabify.py --simple-replace $BADFILES + # Revert files using chaotic indentation + $ svn revert Modules/_cursesmodule.c + # Done! + """ import os @@ -20,6 +44,7 @@ import tempfile import optparse import itertools +import contextlib def untabify(lines, write): @@ -77,6 +102,7 @@ output.append(c) outpos += len(c) inpos += len(c) + # Pad for next tab inpos = (inpos // 8 + 1) * 8 output.append((inpos - outpos) * " ") outpos = inpos @@ -91,6 +117,38 @@ write(outline) write(eol) +def replace_tabs(lines, write): + """Simply replace tabs with 8-spaces without attempting to fix/change + alignment.""" + for line in lines: + cr = line.find('\r') + lf = line.find('\r') + if lf == -1: + eolpos = cr + elif cr == -1: + eolpos = lf + else: + assert cr != -1 and lf != -1 + eolpos = min(cr, lf) + eol = line[eolpos:] + line = line.rstrip() + chunks = line.split("\t") + output = [] + outpos = 0 + inpos = 0 + for c in chunks[:-1]: + output.append(c) + outpos += len(c) + inpos += len(c) + # Pad for next tab + inpos = (inpos // 8 + 1) * 8 + output.append((inpos - outpos) * " ") + outpos = inpos + output.append(chunks[-1]) + outline = "".join(output).rstrip() + write(outline) + write(eol) + def needs_untabifying(filepath): f = open(filepath, "rb") @@ -98,7 +156,7 @@ s = f.read(65536) # Heuristic: we don't want a couple of lone tabs to show as false # positives - return s.count("\n\t") + s.count("\r\t") > 5 + return s.count("\n\t") + s.count("\r\t") > 10 finally: f.close() @@ -111,6 +169,21 @@ if fn.endswith('.h') or fn.endswith('.c'): yield os.path.join(dirpath, fn) + at contextlib.contextmanager +def rewrite_file(filepath): + fd, tmpfn = tempfile.mkstemp(dir='.') + try: + fin = open(filepath, "rb") + fout = os.fdopen(fd, "wb") + try: + yield fin, fout + finally: + fin.close() + fout.close() + os.rename(tmpfn, filepath) + except: + os.unlink(tmpfn) + def main(): parser = optparse.OptionParser() parser.add_option("-l", "--list", dest="do_list_true", @@ -125,9 +198,12 @@ parser.add_option("-b", "--batch", dest="do_batch", action="store_true", default=False, help="untabify specified files and dirs") + parser.add_option("", "--simple-replace", dest="do_replace", + action="store_true", default=False, + help="simply replace tabs with 8-spaces (for files with mixed 4-spaces and tabs)") options, args = parser.parse_args() if (options.do_list_true + options.do_list_false + - options.do_untab + options.do_batch != 1): + options.do_untab + options.do_batch + options.do_replace != 1): parser.error("you must specify exactly one of -l, -n, -b and -u") if options.do_list_true or options.do_list_false: @@ -145,19 +221,18 @@ parser.error("-b needs a file or directory path") for cfn in itertools.ifilter(needs_untabifying, walk_c_files(args)): - fd, tmpfn = tempfile.mkstemp(dir='.') - try: - fin = open(cfn, "rb") - fout = os.fdopen(fd, "wb") + with rewrite_file(cfn) as (fin, fout): print "Untabifing %s" % cfn - try: - untabify(fin, fout.write) - finally: - fin.close() - fout.close() - os.rename(tmpfn, cfn) - except: - os.unlink(tmpfn) + untabify(fin, fout.write) + + if options.do_replace: + if not args: + parser.error("--simple-replace needs a file or directory path") + for cfn in itertools.ifilter(needs_untabifying, + walk_c_files(args)): + with rewrite_file(cfn) as (fin, fout): + print "Replacing tabs in %s" % cfn + replace_tabs(fin, fout.write) if options.do_untab: untabify(sys.stdin, sys.stdout.write) From victor.stinner at haypocalc.com Wed May 5 00:17:42 2010 From: victor.stinner at haypocalc.com (Victor Stinner) Date: Wed, 5 May 2010 00:17:42 +0200 Subject: [Python-checkins] r80742 - python/trunk/Modules/readline.c In-Reply-To: References: <20100504005242.2B791E308@mail.python.org> <201005041034.22942.victor.stinner@haypocalc.com> Message-ID: <201005050017.42482.victor.stinner@haypocalc.com> Le mardi 04 mai 2010 22:03:36, vous avez ?crit : > > On my version of readline (6.1), HIST_ENTRY has no const field: > > (...) > > Is it different in your version of readline? > > I'm on OS X, so I think I might be linking against libedit. Either way the > cast shouldn't harm anything as the char* pointer contents are not modified > in any way by the function. Is the cast triggering a compiler warning for > you? Oh no, the compiler doesn't complain. I just asked because my HIST_ENTRY was different than yours. Your commit shouldn't harm anything, it's ok. -- Victor Stinner http://www.haypocalc.com/ From python-checkins at python.org Wed May 5 00:29:10 2010 From: python-checkins at python.org (michael.foord) Date: Wed, 5 May 2010 00:29:10 +0200 (CEST) Subject: [Python-checkins] r80771 - python/branches/py3k/Lib/test/support.py Message-ID: <20100504222910.467A8EE98F@mail.python.org> Author: michael.foord Date: Wed May 5 00:29:10 2010 New Revision: 80771 Log: Fix error handling removing files in test.support.unlink Modified: python/branches/py3k/Lib/test/support.py Modified: python/branches/py3k/Lib/test/support.py ============================================================================== --- python/branches/py3k/Lib/test/support.py (original) +++ python/branches/py3k/Lib/test/support.py Wed May 5 00:29:10 2010 @@ -186,7 +186,7 @@ os.unlink(filename) except OSError as error: # The filename need not exist. - if error.errno != errno.ENOENT: + if error.errno not in (errno.ENOENT, errno.ENOTDIR): raise def rmtree(path): @@ -376,6 +376,7 @@ # module name. TESTFN = "{}_{}_tmp".format(TESTFN, os.getpid()) + # Assuming sys.getfilesystemencoding()!=sys.getdefaultencoding() # TESTFN_UNICODE is a filename that can be encoded using the # file system encoding, but *not* with the default (ascii) encoding From solipsis at pitrou.net Wed May 5 00:38:55 2010 From: solipsis at pitrou.net (solipsis at pitrou.net) Date: Wed, 5 May 2010 00:38:55 +0200 (CEST) Subject: [Python-checkins] Daily py3k reference leaks (r80767): sum=0 Message-ID: <20100504223855.5F3461770A@ns6635.ovh.net> py3k results for svn r80767 (hg cset 59484908c068) -------------------------------------------------- Command line was: ['./python', '-m', 'test.regrtest', '-uall', '-R', '3:3:/home/antoine/py3k/refleaks/reflog40Dkis', '-x'] From python-checkins at python.org Wed May 5 01:31:41 2010 From: python-checkins at python.org (antoine.pitrou) Date: Wed, 5 May 2010 01:31:41 +0200 (CEST) Subject: [Python-checkins] r80772 - python/branches/py3k/Doc/whatsnew/3.2.rst Message-ID: <20100504233141.E3188EE9A0@mail.python.org> Author: antoine.pitrou Date: Wed May 5 01:31:41 2010 New Revision: 80772 Log: Add what's new entry for r80157 and r80071. Modified: python/branches/py3k/Doc/whatsnew/3.2.rst Modified: python/branches/py3k/Doc/whatsnew/3.2.rst ============================================================================== --- python/branches/py3k/Doc/whatsnew/3.2.rst (original) +++ python/branches/py3k/Doc/whatsnew/3.2.rst Wed May 5 01:31:41 2010 @@ -123,6 +123,11 @@ (Contributed by Antoine Pitrou; :issue:`3001`.) +* Regular and recursive locks now accept an optional *timeout* argument + to their ``acquire`` method. (Contributed by Antoine Pitrou; :issue:`7316`) + Similarly, :meth:`threading.Semaphore.acquire` also gains a *timeout* + argument. (Contributed by Torsten Landschoff; :issue:`850728`.) + Optimizations ============= From python-checkins at python.org Wed May 5 07:32:16 2010 From: python-checkins at python.org (senthil.kumaran) Date: Wed, 5 May 2010 07:32:16 +0200 (CEST) Subject: [Python-checkins] r80773 - python/branches/py3k/Doc/library/urllib.request.rst Message-ID: <20100505053216.78D4EEE98F@mail.python.org> Author: senthil.kumaran Date: Wed May 5 07:32:16 2010 New Revision: 80773 Log: Fix Issue8619 docfix related to urllib. Modified: python/branches/py3k/Doc/library/urllib.request.rst Modified: python/branches/py3k/Doc/library/urllib.request.rst ============================================================================== --- python/branches/py3k/Doc/library/urllib.request.rst (original) +++ python/branches/py3k/Doc/library/urllib.request.rst Wed May 5 07:32:16 2010 @@ -133,10 +133,10 @@ of the :class:`FancyURLopener` class and use it to perform their requested actions. To override this functionality, programmers can create a subclass of :class:`URLopener` or :class:`FancyURLopener`, then assign an instance of that - class to the ``urllib._urlopener`` variable before calling the desired function. - For example, applications may want to specify a different - :mailheader:`User-Agent` header than :class:`URLopener` defines. This can be - accomplished with the following code:: + class to the ``urllib.request._urlopener`` variable before calling the + desired function. For example, applications may want to specify a different + :mailheader:`User-Agent` header than :class:`URLopener` defines. + This can be accomplished with the following code:: import urllib.request From python-checkins at python.org Wed May 5 07:34:35 2010 From: python-checkins at python.org (senthil.kumaran) Date: Wed, 5 May 2010 07:34:35 +0200 (CEST) Subject: [Python-checkins] r80774 - in python/branches/release31-maint: Doc/library/urllib.request.rst Message-ID: <20100505053435.E97B9EE98F@mail.python.org> Author: senthil.kumaran Date: Wed May 5 07:34:35 2010 New Revision: 80774 Log: Merged revisions 80773 via svnmerge from svn+ssh://pythondev at svn.python.org/python/branches/py3k ........ r80773 | senthil.kumaran | 2010-05-05 11:02:16 +0530 (Wed, 05 May 2010) | 3 lines Fix Issue8619 docfix related to urllib. ........ Modified: python/branches/release31-maint/ (props changed) python/branches/release31-maint/Doc/library/urllib.request.rst Modified: python/branches/release31-maint/Doc/library/urllib.request.rst ============================================================================== --- python/branches/release31-maint/Doc/library/urllib.request.rst (original) +++ python/branches/release31-maint/Doc/library/urllib.request.rst Wed May 5 07:34:35 2010 @@ -133,10 +133,10 @@ of the :class:`FancyURLopener` class and use it to perform their requested actions. To override this functionality, programmers can create a subclass of :class:`URLopener` or :class:`FancyURLopener`, then assign an instance of that - class to the ``urllib._urlopener`` variable before calling the desired function. - For example, applications may want to specify a different - :mailheader:`User-Agent` header than :class:`URLopener` defines. This can be - accomplished with the following code:: + class to the ``urllib.request._urlopener`` variable before calling the + desired function. For example, applications may want to specify a different + :mailheader:`User-Agent` header than :class:`URLopener` defines. + This can be accomplished with the following code:: import urllib.request From python-checkins at python.org Wed May 5 09:22:18 2010 From: python-checkins at python.org (senthil.kumaran) Date: Wed, 5 May 2010 09:22:18 +0200 (CEST) Subject: [Python-checkins] r80775 - python/branches/py3k/Doc/library/urllib.request.rst Message-ID: <20100505072218.85D2DEE9A3@mail.python.org> Author: senthil.kumaran Date: Wed May 5 09:22:18 2010 New Revision: 80775 Log: Fix issue8619 - Doc fix - code example. Modified: python/branches/py3k/Doc/library/urllib.request.rst Modified: python/branches/py3k/Doc/library/urllib.request.rst ============================================================================== --- python/branches/py3k/Doc/library/urllib.request.rst (original) +++ python/branches/py3k/Doc/library/urllib.request.rst Wed May 5 09:22:18 2010 @@ -143,7 +143,7 @@ class AppURLopener(urllib.request.FancyURLopener): version = "App/1.7" - urllib._urlopener = AppURLopener() + urllib.request._urlopener = AppURLopener() .. function:: urlcleanup() From python-checkins at python.org Wed May 5 09:24:45 2010 From: python-checkins at python.org (senthil.kumaran) Date: Wed, 5 May 2010 09:24:45 +0200 (CEST) Subject: [Python-checkins] r80776 - in python/branches/release31-maint: Doc/library/urllib.request.rst Message-ID: <20100505072445.1680BEE9E8@mail.python.org> Author: senthil.kumaran Date: Wed May 5 09:24:44 2010 New Revision: 80776 Log: Merged revisions 80775 via svnmerge from svn+ssh://pythondev at svn.python.org/python/branches/py3k ........ r80775 | senthil.kumaran | 2010-05-05 12:52:18 +0530 (Wed, 05 May 2010) | 3 lines Fix issue8619 - Doc fix - code example. ........ Modified: python/branches/release31-maint/ (props changed) python/branches/release31-maint/Doc/library/urllib.request.rst Modified: python/branches/release31-maint/Doc/library/urllib.request.rst ============================================================================== --- python/branches/release31-maint/Doc/library/urllib.request.rst (original) +++ python/branches/release31-maint/Doc/library/urllib.request.rst Wed May 5 09:24:44 2010 @@ -143,7 +143,7 @@ class AppURLopener(urllib.request.FancyURLopener): version = "App/1.7" - urllib._urlopener = AppURLopener() + urllib.request._urlopener = AppURLopener() .. function:: urlcleanup() From python-checkins at python.org Wed May 5 14:40:49 2010 From: python-checkins at python.org (victor.stinner) Date: Wed, 5 May 2010 14:40:49 +0200 (CEST) Subject: [Python-checkins] r80777 - in python/trunk: Lib/test/test_traceback.py Lib/traceback.py Misc/NEWS Message-ID: <20100505124049.7E2C5EE9E8@mail.python.org> Author: victor.stinner Date: Wed May 5 14:40:49 2010 New Revision: 80777 Log: Issue #8313: traceback.format_exception_only() encodes unicode message to ASCII with backslashreplace error handler if str(value) failed Modified: python/trunk/Lib/test/test_traceback.py python/trunk/Lib/traceback.py python/trunk/Misc/NEWS Modified: python/trunk/Lib/test/test_traceback.py ============================================================================== --- python/trunk/Lib/test/test_traceback.py (original) +++ python/trunk/Lib/test/test_traceback.py Wed May 5 14:40:49 2010 @@ -159,6 +159,15 @@ err = traceback.format_exception_only(None, None) self.assertEqual(err, ['None\n']) + def test_unicode(self): + err = AssertionError('\xff') + lines = traceback.format_exception_only(type(err), err) + self.assertEqual(lines, ['AssertionError: \xff\n']) + + err = AssertionError(u'\xe9') + lines = traceback.format_exception_only(type(err), err) + self.assertEqual(lines, ['AssertionError: \\xe9\n']) + class TracebackFormatTests(unittest.TestCase): Modified: python/trunk/Lib/traceback.py ============================================================================== --- python/trunk/Lib/traceback.py (original) +++ python/trunk/Lib/traceback.py Wed May 5 14:40:49 2010 @@ -211,8 +211,14 @@ def _some_str(value): try: return str(value) - except: - return '' % type(value).__name__ + except Exception: + pass + try: + value = unicode(value) + return value.encode("ascii", "backslashreplace") + except Exception: + pass + return '' % type(value).__name__ def print_exc(limit=None, file=None): Modified: python/trunk/Misc/NEWS ============================================================================== --- python/trunk/Misc/NEWS (original) +++ python/trunk/Misc/NEWS Wed May 5 14:40:49 2010 @@ -39,6 +39,9 @@ Library ------- +- Issue #8313: traceback.format_exception_only() encodes unicode message to + ASCII with backslashreplace error handler if str(value) failed + - Issue #8567: Fix precedence of signals in Decimal module: when a Decimal operation raises multiple signals and more than one of those signals is trapped, the specification determines the order in which From python-checkins at python.org Wed May 5 14:42:20 2010 From: python-checkins at python.org (victor.stinner) Date: Wed, 5 May 2010 14:42:20 +0200 (CEST) Subject: [Python-checkins] r80778 - python/branches/py3k Message-ID: <20100505124220.57C51E2DC@mail.python.org> Author: victor.stinner Date: Wed May 5 14:42:20 2010 New Revision: 80778 Log: Blocked revisions 80777 via svnmerge ........ r80777 | victor.stinner | 2010-05-05 14:40:49 +0200 (mer., 05 mai 2010) | 3 lines Issue #8313: traceback.format_exception_only() encodes unicode message to ASCII with backslashreplace error handler if str(value) failed ........ Modified: python/branches/py3k/ (props changed) From python-checkins at python.org Wed May 5 14:45:31 2010 From: python-checkins at python.org (victor.stinner) Date: Wed, 5 May 2010 14:45:31 +0200 (CEST) Subject: [Python-checkins] r80779 - in python/branches/release26-maint: Lib/test/test_traceback.py Lib/traceback.py Misc/NEWS Message-ID: <20100505124531.6F1A2EE9E2@mail.python.org> Author: victor.stinner Date: Wed May 5 14:45:31 2010 New Revision: 80779 Log: Merged revisions 80777 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r80777 | victor.stinner | 2010-05-05 14:40:49 +0200 (mer., 05 mai 2010) | 3 lines Issue #8313: traceback.format_exception_only() encodes unicode message to ASCII with backslashreplace error handler if str(value) failed ........ Modified: python/branches/release26-maint/ (props changed) python/branches/release26-maint/Lib/test/test_traceback.py python/branches/release26-maint/Lib/traceback.py python/branches/release26-maint/Misc/NEWS Modified: python/branches/release26-maint/Lib/test/test_traceback.py ============================================================================== --- python/branches/release26-maint/Lib/test/test_traceback.py (original) +++ python/branches/release26-maint/Lib/test/test_traceback.py Wed May 5 14:45:31 2010 @@ -168,6 +168,15 @@ err = traceback.format_exception_only(None, None) self.assertEqual(err, ['None\n']) + def test_unicode(self): + err = AssertionError('\xff') + lines = traceback.format_exception_only(type(err), err) + self.assertEqual(lines, ['AssertionError: \xff\n']) + + err = AssertionError(u'\xe9') + lines = traceback.format_exception_only(type(err), err) + self.assertEqual(lines, ['AssertionError: \\xe9\n']) + class TracebackFormatTests(unittest.TestCase): Modified: python/branches/release26-maint/Lib/traceback.py ============================================================================== --- python/branches/release26-maint/Lib/traceback.py (original) +++ python/branches/release26-maint/Lib/traceback.py Wed May 5 14:45:31 2010 @@ -212,8 +212,14 @@ def _some_str(value): try: return str(value) - except: - return '' % type(value).__name__ + except Exception: + pass + try: + value = unicode(value) + return value.encode("ascii", "backslashreplace") + except Exception: + pass + return '' % type(value).__name__ def print_exc(limit=None, file=None): Modified: python/branches/release26-maint/Misc/NEWS ============================================================================== --- python/branches/release26-maint/Misc/NEWS (original) +++ python/branches/release26-maint/Misc/NEWS Wed May 5 14:45:31 2010 @@ -33,6 +33,9 @@ Library ------- +- Issue #8313: traceback.format_exception_only() encodes unicode message to + ASCII with backslashreplace error handler if str(value) failed + - Issue #8567: Fix precedence of signals in Decimal module: when a Decimal operation raises multiple signals and more than one of those signals is trapped, the specification determines the order in which From python-checkins at python.org Wed May 5 14:58:30 2010 From: python-checkins at python.org (antoine.pitrou) Date: Wed, 5 May 2010 14:58:30 +0200 (CEST) Subject: [Python-checkins] r80780 - sandbox/trunk/untabify/untabify.py Message-ID: <20100505125830.AA1E5EEA34@mail.python.org> Author: antoine.pitrou Date: Wed May 5 14:58:30 2010 New Revision: 80780 Log: Add an option to rewrite patches Modified: sandbox/trunk/untabify/untabify.py Modified: sandbox/trunk/untabify/untabify.py ============================================================================== --- sandbox/trunk/untabify/untabify.py (original) +++ sandbox/trunk/untabify/untabify.py Wed May 5 14:58:30 2010 @@ -36,6 +36,9 @@ $ svn revert Modules/_cursesmodule.c # Done! +You can also rewrite your old patches with the -p option; if there are +still conflicts when applying, use `patch -l`. + """ import os @@ -48,8 +51,8 @@ def untabify(lines, write): - last_indent = 0 - last_outdent = 0 + last_indent = -1 + last_outdent = -1 last_outline = "" for line in lines: cr = line.find('\r') @@ -84,7 +87,7 @@ inpos = (inpos // 8 + 1) * 8 outpos += 4 # Continuation line? - if (inpos > last_indent + 8 + if (last_indent >= 0 and inpos > last_indent + 8 # labels and end-of-comments can't be continued and not last_outline.endswith(':') and not last_outline.endswith('*/')): @@ -114,8 +117,7 @@ last_indent = indent last_outdent = outdent last_outline = outline - write(outline) - write(eol) + write(outline + eol) def replace_tabs(lines, write): """Simply replace tabs with 8-spaces without attempting to fix/change @@ -146,8 +148,64 @@ outpos = inpos output.append(chunks[-1]) outline = "".join(output).rstrip() - write(outline) - write(eol) + write(outline + eol) + +def passthrough(lines, write): + for l in lines: + write(l) + +def untabify_hunk(lines, write, transform_func): + if not lines: + return + chars, lines = zip(*((l[:1], l[1:]) for l in lines)) + outlines = [] + transform_func(lines, outlines.append) + for c, l in zip(chars, outlines): + write(c + l) + +def untabify_patch_fragment(lines, write, transform_func): + lines = list(lines) + if '\t' not in ''.join(lines): + passthrough(lines, write) + return + hunk_chars = ' +-' + hunk_lines = [] + for line in lines: + c = line[:1] + if c not in hunk_chars: + untabify_hunk(hunk_lines, write, transform_func) + hunk_lines = [] + write(line) + continue + hunk_lines.append(line) + untabify_hunk(hunk_lines, write, transform_func) + +def untabify_patch(lines, write, transform_func): + patch_chars = ' +-<>!@' + lines = iter(lines) + line = next(lines) + while True: + patch_transform_func = passthrough + for line in itertools.chain([line], lines): + c = line[:1] + if line[:4] in ('--- ', '+++ '): + filepath = line.split()[1] + if is_c_file(filepath): + patch_transform_func = transform_func + elif c in patch_chars: + break + write(line) + else: + break + fragment_lines = [] + for line in itertools.chain([line], lines): + c = line[:1] + if c not in patch_chars: + break + fragment_lines.append(line) + untabify_patch_fragment(fragment_lines, write, transform_func) + if c in patch_chars: + break def needs_untabifying(filepath): @@ -160,13 +218,16 @@ finally: f.close() +def is_c_file(filepath): + return filepath.endswith('.h') or filepath.endswith('.c') + def walk_c_files(paths): for p in paths: if os.path.isfile(p): yield p for dirpath, dirnames, filenames in os.walk(p): for fn in sorted(filenames): - if fn.endswith('.h') or fn.endswith('.c'): + if is_c_file(fn): yield os.path.join(dirpath, fn) @contextlib.contextmanager @@ -195,6 +256,9 @@ parser.add_option("-u", "--untabify", dest="do_untab", action="store_true", default=False, help="untabify stdin to stdout") + parser.add_option("-p", "--untabify-patch", dest="do_untab_patch", + action="store_true", default=False, + help="untabify patch (stdin to stdout)") parser.add_option("-b", "--batch", dest="do_batch", action="store_true", default=False, help="untabify specified files and dirs") @@ -203,8 +267,9 @@ help="simply replace tabs with 8-spaces (for files with mixed 4-spaces and tabs)") options, args = parser.parse_args() if (options.do_list_true + options.do_list_false + - options.do_untab + options.do_batch + options.do_replace != 1): - parser.error("you must specify exactly one of -l, -n, -b and -u") + options.do_untab + options.do_untab_patch + + options.do_batch + options.do_replace != 1): + parser.error("you must specify exactly one of -l, -n, -b, -u and -p") if options.do_list_true or options.do_list_false: if not args: @@ -236,6 +301,9 @@ if options.do_untab: untabify(sys.stdin, sys.stdout.write) + + if options.do_untab_patch: + untabify_patch(sys.stdin, sys.stdout.write, untabify) if __name__ == '__main__': main() From python-checkins at python.org Wed May 5 15:20:31 2010 From: python-checkins at python.org (ronald.oussoren) Date: Wed, 5 May 2010 15:20:31 +0200 (CEST) Subject: [Python-checkins] r80781 - python/branches/py3k/Mac/Makefile.in Message-ID: <20100505132031.CB1C1EC3E@mail.python.org> Author: ronald.oussoren Date: Wed May 5 15:20:31 2010 New Revision: 80781 Log: Small update to Mac/Makefile to ensure that we install python binaries that support all architectures in a universal build. Modified: python/branches/py3k/Mac/Makefile.in Modified: python/branches/py3k/Mac/Makefile.in ============================================================================== --- python/branches/py3k/Mac/Makefile.in (original) +++ python/branches/py3k/Mac/Makefile.in Wed May 5 15:20:31 2010 @@ -58,8 +58,8 @@ ifneq ($(LIPO_32BIT_FLAGS),) lipo $(LIPO_32BIT_FLAGS) -output $(DESTDIR)$(prefix)/bin/python$(VERSION)-32 pythonw lipo $(LIPO_32BIT_FLAGS) -output $(DESTDIR)$(prefix)/bin/pythonw$(VERSION)-32 pythonw - ln -sf pythonw$(VERSION)-32 "$(DESTDIR)$(prefix)/bin/pythonw$(VERSION)" - ln -sf python$(VERSION)-32 "$(DESTDIR)$(prefix)/bin/python$(VERSION)" + ln -sf pythonw$(VERSION)-32 "$(DESTDIR)$(prefix)/bin/pythonw3-32" + ln -sf python$(VERSION)-32 "$(DESTDIR)$(prefix)/bin/python3-32" endif # From python-checkins at python.org Wed May 5 15:30:01 2010 From: python-checkins at python.org (marc-andre.lemburg) Date: Wed, 5 May 2010 15:30:01 +0200 (CEST) Subject: [Python-checkins] r80782 - python/trunk/Misc/NEWS Message-ID: <20100505133001.52B7CEEA46@mail.python.org> Author: marc-andre.lemburg Date: Wed May 5 15:30:01 2010 New Revision: 80782 Log: Update the NEWS entry for issue #8211. Modified: python/trunk/Misc/NEWS Modified: python/trunk/Misc/NEWS ============================================================================== --- python/trunk/Misc/NEWS (original) +++ python/trunk/Misc/NEWS Wed May 5 15:30:01 2010 @@ -226,8 +226,8 @@ - Issue #8268: Old-style classes (not just instances) now support weak references. -- Issue #8211: Save/restore CFLAGS around AC_PROG_CC in configure.in, compiler - optimizations are disabled when --with-pydebug is used. +- Issue #8211: Save/restore CFLAGS around AC_PROG_CC in configure.in, in + case it is set. - Issue #1583863: An unicode subclass can now override the __unicode__ method From python-checkins at python.org Wed May 5 15:32:59 2010 From: python-checkins at python.org (marc-andre.lemburg) Date: Wed, 5 May 2010 15:32:59 +0200 (CEST) Subject: [Python-checkins] r80783 - in python/branches/py3k: Misc/NEWS Message-ID: <20100505133259.AC52DEEA36@mail.python.org> Author: marc-andre.lemburg Date: Wed May 5 15:32:59 2010 New Revision: 80783 Log: Merged revisions 80782 via svnmerge from svn+pythonssh://pythondev at svn.python.org/python/trunk ........ r80782 | marc-andre.lemburg | 2010-05-05 15:30:01 +0200 (Wed, 05 May 2010) | 3 lines Update the NEWS entry for issue #8211. ........ Modified: python/branches/py3k/ (props changed) python/branches/py3k/Misc/NEWS Modified: python/branches/py3k/Misc/NEWS ============================================================================== --- python/branches/py3k/Misc/NEWS (original) +++ python/branches/py3k/Misc/NEWS Wed May 5 15:32:59 2010 @@ -54,8 +54,8 @@ - Raise a TypeError when trying to delete a T_STRING_INPLACE struct member. -- Issue #8211: Save/restore CFLAGS around AC_PROG_CC in configure.in, compiler - optimizations are disabled when --with-pydebug is used. +- Issue #8211: Save/restore CFLAGS around AC_PROG_CC in configure.in, in + case it is set. - Issue #8226: sys.setfilesystemencoding() raises a LookupError if the encoding is unknown From python-checkins at python.org Wed May 5 16:48:37 2010 From: python-checkins at python.org (ronald.oussoren) Date: Wed, 5 May 2010 16:48:37 +0200 (CEST) Subject: [Python-checkins] r80784 - in python/trunk: Lib/test/test_uuid.py Lib/uuid.py Misc/NEWS Message-ID: <20100505144837.76D0BEEA4F@mail.python.org> Author: ronald.oussoren Date: Wed May 5 16:48:37 2010 New Revision: 80784 Log: The C function used by uuid.uuid4 is broken on OSX 10.6 in that after os.fork() the parent and child generate the same sequence of UUIDs. This patch falls back to the the Python implementation on OSX 10.6 or later. Fixes issue #8621. Modified: python/trunk/Lib/test/test_uuid.py python/trunk/Lib/uuid.py python/trunk/Misc/NEWS Modified: python/trunk/Lib/test/test_uuid.py ============================================================================== --- python/trunk/Lib/test/test_uuid.py (original) +++ python/trunk/Lib/test/test_uuid.py Wed May 5 16:48:37 2010 @@ -446,6 +446,34 @@ equal(u, uuid.UUID(v)) equal(str(u), v) + def testIssue8621(self): + import os + import sys + if os.name != 'posix': + return + + # On at least some versions of OSX uuid.uuid4 generates + # the same sequence of UUIDs in the parent and any + # children started using fork. + fds = os.pipe() + pid = os.fork() + if pid == 0: + os.close(fds[0]) + value = uuid.uuid4() + os.write(fds[1], value.hex) + sys.exit(0) + + else: + os.close(fds[1]) + parent_value = uuid.uuid4().hex + os.waitpid(pid, 0) + child_value = os.read(fds[0], 100) + + self.assertNotEqual(parent_value, child_value) + + + + def test_main(): test_support.run_unittest(TestUUID) Modified: python/trunk/Lib/uuid.py ============================================================================== --- python/trunk/Lib/uuid.py (original) +++ python/trunk/Lib/uuid.py Wed May 5 16:48:37 2010 @@ -406,6 +406,19 @@ if hasattr(lib, 'uuid_generate_time'): _uuid_generate_time = lib.uuid_generate_time + # The uuid_generate_* functions are broken on MacOS X 10.6, as noted + # in issue #8621 the function generates the same sequence of values + # in the parent process and all children created using fork (unless + # those children use exec as well). + # + # Assume that the uuid_generate functions are broken from 10.6 onward, + # the test can be adjusted when a later version is fixed. + import sys + if sys.platform == 'darwin': + import os + if int(os.uname()[2].split('.')[0]) >= 10: + _uuid_generate_random = _uuid_generate_time = None + # On Windows prior to 2000, UuidCreate gives a UUID containing the # hardware address. On Windows 2000 and later, UuidCreate makes a # random UUID and UuidCreateSequential gives a UUID containing the Modified: python/trunk/Misc/NEWS ============================================================================== --- python/trunk/Misc/NEWS (original) +++ python/trunk/Misc/NEWS Wed May 5 16:48:37 2010 @@ -39,6 +39,9 @@ Library ------- +- Issue #8621: uuid.uuid4() returned the same sequence of values in the + parent and any children created using ``os.fork`` on MacOS X 10.6. + - Issue #8313: traceback.format_exception_only() encodes unicode message to ASCII with backslashreplace error handler if str(value) failed From python-checkins at python.org Wed May 5 17:13:15 2010 From: python-checkins at python.org (ronald.oussoren) Date: Wed, 5 May 2010 17:13:15 +0200 (CEST) Subject: [Python-checkins] r80785 - in python/branches/release26-maint: Lib/test/test_uuid.py Lib/uuid.py Misc/NEWS Message-ID: <20100505151315.B52FDEE9C4@mail.python.org> Author: ronald.oussoren Date: Wed May 5 17:13:15 2010 New Revision: 80785 Log: Merged revisions 80784 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r80784 | ronald.oussoren | 2010-05-05 16:48:37 +0200 (Wed, 05 May 2010) | 9 lines The C function used by uuid.uuid4 is broken on OSX 10.6 in that after os.fork() the parent and child generate the same sequence of UUIDs. This patch falls back to the the Python implementation on OSX 10.6 or later. Fixes issue #8621. ........ Modified: python/branches/release26-maint/ (props changed) python/branches/release26-maint/Lib/test/test_uuid.py python/branches/release26-maint/Lib/uuid.py python/branches/release26-maint/Misc/NEWS Modified: python/branches/release26-maint/Lib/test/test_uuid.py ============================================================================== --- python/branches/release26-maint/Lib/test/test_uuid.py (original) +++ python/branches/release26-maint/Lib/test/test_uuid.py Wed May 5 17:13:15 2010 @@ -446,6 +446,34 @@ equal(u, uuid.UUID(v)) equal(str(u), v) + def testIssue8621(self): + import os + import sys + if os.name != 'posix': + return + + # On at least some versions of OSX uuid.uuid4 generates + # the same sequence of UUIDs in the parent and any + # children started using fork. + fds = os.pipe() + pid = os.fork() + if pid == 0: + os.close(fds[0]) + value = uuid.uuid4() + os.write(fds[1], value.hex) + os._exit(0) + + else: + os.close(fds[1]) + parent_value = uuid.uuid4().hex + os.waitpid(pid, 0) + child_value = os.read(fds[0], 100) + + self.assertNotEqual(parent_value, child_value) + + + + def test_main(): test_support.run_unittest(TestUUID) Modified: python/branches/release26-maint/Lib/uuid.py ============================================================================== --- python/branches/release26-maint/Lib/uuid.py (original) +++ python/branches/release26-maint/Lib/uuid.py Wed May 5 17:13:15 2010 @@ -406,6 +406,19 @@ if hasattr(lib, 'uuid_generate_time'): _uuid_generate_time = lib.uuid_generate_time + # The uuid_generate_* functions are broken on MacOS X 10.6, as noted + # in issue #8621 the function generates the same sequence of values + # in the parent process and all children created using fork (unless + # those children use exec as well). + # + # Assume that the uuid_generate functions are broken from 10.6 onward, + # the test can be adjusted when a later version is fixed. + import sys + if sys.platform == 'darwin': + import os + if int(os.uname()[2].split('.')[0]) >= 10: + _uuid_generate_random = _uuid_generate_time = None + # On Windows prior to 2000, UuidCreate gives a UUID containing the # hardware address. On Windows 2000 and later, UuidCreate makes a # random UUID and UuidCreateSequential gives a UUID containing the Modified: python/branches/release26-maint/Misc/NEWS ============================================================================== --- python/branches/release26-maint/Misc/NEWS (original) +++ python/branches/release26-maint/Misc/NEWS Wed May 5 17:13:15 2010 @@ -33,6 +33,9 @@ Library ------- +- Issue #8621: uuid.uuid4() returned the same sequence of values in the + parent and any children created using ``os.fork`` on MacOS X 10.6. + - Issue #8313: traceback.format_exception_only() encodes unicode message to ASCII with backslashreplace error handler if str(value) failed From python-checkins at python.org Wed May 5 17:32:33 2010 From: python-checkins at python.org (ronald.oussoren) Date: Wed, 5 May 2010 17:32:33 +0200 (CEST) Subject: [Python-checkins] r80786 - in python/branches/py3k: Lib/test/test_uuid.py Lib/uuid.py Misc/NEWS Message-ID: <20100505153233.6426FF526@mail.python.org> Author: ronald.oussoren Date: Wed May 5 17:32:33 2010 New Revision: 80786 Log: Merged revisions 80784 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r80784 | ronald.oussoren | 2010-05-05 16:48:37 +0200 (Wed, 05 May 2010) | 9 lines The C function used by uuid.uuid4 is broken on OSX 10.6 in that after os.fork() the parent and child generate the same sequence of UUIDs. This patch falls back to the the Python implementation on OSX 10.6 or later. Fixes issue #8621. ........ Modified: python/branches/py3k/ (props changed) python/branches/py3k/Lib/test/test_uuid.py python/branches/py3k/Lib/uuid.py python/branches/py3k/Misc/NEWS Modified: python/branches/py3k/Lib/test/test_uuid.py ============================================================================== --- python/branches/py3k/Lib/test/test_uuid.py (original) +++ python/branches/py3k/Lib/test/test_uuid.py Wed May 5 17:32:33 2010 @@ -457,6 +457,34 @@ equal(u, uuid.UUID(v)) equal(str(u), v) + def testIssue8621(self): + import os + import sys + if os.name != 'posix': + return + + # On at least some versions of OSX uuid.uuid4 generates + # the same sequence of UUIDs in the parent and any + # children started using fork. + fds = os.pipe() + pid = os.fork() + if pid == 0: + os.close(fds[0]) + value = uuid.uuid4() + os.write(fds[1], value.hex.encode('latin1')) + os._exit(0) + + else: + os.close(fds[1]) + parent_value = uuid.uuid4().hex + os.waitpid(pid, 0) + child_value = os.read(fds[0], 100).decode('latin1') + + self.assertNotEqual(parent_value, child_value) + + + + def test_main(): support.run_unittest(TestUUID) Modified: python/branches/py3k/Lib/uuid.py ============================================================================== --- python/branches/py3k/Lib/uuid.py (original) +++ python/branches/py3k/Lib/uuid.py Wed May 5 17:32:33 2010 @@ -427,6 +427,19 @@ if hasattr(lib, 'uuid_generate_time'): _uuid_generate_time = lib.uuid_generate_time + # The uuid_generate_* functions are broken on MacOS X 10.6, as noted + # in issue #8621 the function generates the same sequence of values + # in the parent process and all children created using fork (unless + # those children use exec as well). + # + # Assume that the uuid_generate functions are broken from 10.6 onward, + # the test can be adjusted when a later version is fixed. + import sys + if sys.platform == 'darwin': + import os + if int(os.uname()[2].split('.')[0]) >= 10: + _uuid_generate_random = _uuid_generate_time = None + # On Windows prior to 2000, UuidCreate gives a UUID containing the # hardware address. On Windows 2000 and later, UuidCreate makes a # random UUID and UuidCreateSequential gives a UUID containing the Modified: python/branches/py3k/Misc/NEWS ============================================================================== --- python/branches/py3k/Misc/NEWS (original) +++ python/branches/py3k/Misc/NEWS Wed May 5 17:32:33 2010 @@ -348,6 +348,9 @@ Library ------- +- Issue #8621: uuid.uuid4() returned the same sequence of values in the + parent and any children created using ``os.fork`` on MacOS X 10.6. + - Issue #8567: Fix precedence of signals in Decimal module: when a Decimal operation raises multiple signals and more than one of those signals is trapped, the specification determines the order in which From python-checkins at python.org Wed May 5 17:32:39 2010 From: python-checkins at python.org (ronald.oussoren) Date: Wed, 5 May 2010 17:32:39 +0200 (CEST) Subject: [Python-checkins] r80787 - python/trunk/Lib/test/test_uuid.py Message-ID: <20100505153239.EE313EE9AA@mail.python.org> Author: ronald.oussoren Date: Wed May 5 17:32:39 2010 New Revision: 80787 Log: Force exit using os._exit instead of sys.exit, this makes sure that the child does not continue testing. Modified: python/trunk/Lib/test/test_uuid.py Modified: python/trunk/Lib/test/test_uuid.py ============================================================================== --- python/trunk/Lib/test/test_uuid.py (original) +++ python/trunk/Lib/test/test_uuid.py Wed May 5 17:32:39 2010 @@ -461,7 +461,7 @@ os.close(fds[0]) value = uuid.uuid4() os.write(fds[1], value.hex) - sys.exit(0) + os._exit(0) else: os.close(fds[1]) From python-checkins at python.org Wed May 5 17:33:55 2010 From: python-checkins at python.org (ronald.oussoren) Date: Wed, 5 May 2010 17:33:55 +0200 (CEST) Subject: [Python-checkins] r80788 - in python/branches/release31-maint: Lib/test/test_uuid.py Lib/uuid.py Misc/NEWS Message-ID: <20100505153355.8D37DEE9AA@mail.python.org> Author: ronald.oussoren Date: Wed May 5 17:33:55 2010 New Revision: 80788 Log: Merged revisions 80786 via svnmerge from svn+ssh://pythondev at svn.python.org/python/branches/py3k ................ r80786 | ronald.oussoren | 2010-05-05 17:32:33 +0200 (Wed, 05 May 2010) | 16 lines Merged revisions 80784 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r80784 | ronald.oussoren | 2010-05-05 16:48:37 +0200 (Wed, 05 May 2010) | 9 lines The C function used by uuid.uuid4 is broken on OSX 10.6 in that after os.fork() the parent and child generate the same sequence of UUIDs. This patch falls back to the the Python implementation on OSX 10.6 or later. Fixes issue #8621. ........ ................ Modified: python/branches/release31-maint/ (props changed) python/branches/release31-maint/Lib/test/test_uuid.py python/branches/release31-maint/Lib/uuid.py python/branches/release31-maint/Misc/NEWS Modified: python/branches/release31-maint/Lib/test/test_uuid.py ============================================================================== --- python/branches/release31-maint/Lib/test/test_uuid.py (original) +++ python/branches/release31-maint/Lib/test/test_uuid.py Wed May 5 17:33:55 2010 @@ -451,6 +451,34 @@ equal(u, uuid.UUID(v)) equal(str(u), v) + def testIssue8621(self): + import os + import sys + if os.name != 'posix': + return + + # On at least some versions of OSX uuid.uuid4 generates + # the same sequence of UUIDs in the parent and any + # children started using fork. + fds = os.pipe() + pid = os.fork() + if pid == 0: + os.close(fds[0]) + value = uuid.uuid4() + os.write(fds[1], value.hex.encode('latin1')) + os._exit(0) + + else: + os.close(fds[1]) + parent_value = uuid.uuid4().hex + os.waitpid(pid, 0) + child_value = os.read(fds[0], 100).decode('latin1') + + self.assertNotEqual(parent_value, child_value) + + + + def test_main(): support.run_unittest(TestUUID) Modified: python/branches/release31-maint/Lib/uuid.py ============================================================================== --- python/branches/release31-maint/Lib/uuid.py (original) +++ python/branches/release31-maint/Lib/uuid.py Wed May 5 17:33:55 2010 @@ -427,6 +427,19 @@ if hasattr(lib, 'uuid_generate_time'): _uuid_generate_time = lib.uuid_generate_time + # The uuid_generate_* functions are broken on MacOS X 10.6, as noted + # in issue #8621 the function generates the same sequence of values + # in the parent process and all children created using fork (unless + # those children use exec as well). + # + # Assume that the uuid_generate functions are broken from 10.6 onward, + # the test can be adjusted when a later version is fixed. + import sys + if sys.platform == 'darwin': + import os + if int(os.uname()[2].split('.')[0]) >= 10: + _uuid_generate_random = _uuid_generate_time = None + # On Windows prior to 2000, UuidCreate gives a UUID containing the # hardware address. On Windows 2000 and later, UuidCreate makes a # random UUID and UuidCreateSequential gives a UUID containing the Modified: python/branches/release31-maint/Misc/NEWS ============================================================================== --- python/branches/release31-maint/Misc/NEWS (original) +++ python/branches/release31-maint/Misc/NEWS Wed May 5 17:33:55 2010 @@ -40,6 +40,9 @@ Library ------- +- Issue #8621: uuid.uuid4() returned the same sequence of values in the + parent and any children created using ``os.fork`` on MacOS X 10.6. + - Issue #8567: Fix precedence of signals in Decimal module: when a Decimal operation raises multiple signals and more than one of those signals is trapped, the specification determines the order in which From python-checkins at python.org Wed May 5 17:53:45 2010 From: python-checkins at python.org (antoine.pitrou) Date: Wed, 5 May 2010 17:53:45 +0200 (CEST) Subject: [Python-checkins] r80789 - python/trunk/Modules/_ssl.c Message-ID: <20100505155345.B680EEE9F6@mail.python.org> Author: antoine.pitrou Date: Wed May 5 17:53:45 2010 New Revision: 80789 Log: Untabify Modules/_ssl.c Modified: python/trunk/Modules/_ssl.c Modified: python/trunk/Modules/_ssl.c ============================================================================== --- python/trunk/Modules/_ssl.c (original) +++ python/trunk/Modules/_ssl.c Wed May 5 17:53:45 2010 @@ -19,14 +19,14 @@ #ifdef WITH_THREAD #include "pythread.h" #define PySSL_BEGIN_ALLOW_THREADS { \ - PyThreadState *_save = NULL; \ - if (_ssl_locks_count>0) {_save = PyEval_SaveThread();} -#define PySSL_BLOCK_THREADS if (_ssl_locks_count>0){PyEval_RestoreThread(_save)}; -#define PySSL_UNBLOCK_THREADS if (_ssl_locks_count>0){_save = PyEval_SaveThread()}; -#define PySSL_END_ALLOW_THREADS if (_ssl_locks_count>0){PyEval_RestoreThread(_save);} \ - } + PyThreadState *_save = NULL; \ + if (_ssl_locks_count>0) {_save = PyEval_SaveThread();} +#define PySSL_BLOCK_THREADS if (_ssl_locks_count>0){PyEval_RestoreThread(_save)}; +#define PySSL_UNBLOCK_THREADS if (_ssl_locks_count>0){_save = PyEval_SaveThread()}; +#define PySSL_END_ALLOW_THREADS if (_ssl_locks_count>0){PyEval_RestoreThread(_save);} \ + } -#else /* no WITH_THREAD */ +#else /* no WITH_THREAD */ #define PySSL_BEGIN_ALLOW_THREADS #define PySSL_BLOCK_THREADS @@ -36,36 +36,36 @@ #endif enum py_ssl_error { - /* these mirror ssl.h */ - PY_SSL_ERROR_NONE, - PY_SSL_ERROR_SSL, - PY_SSL_ERROR_WANT_READ, - PY_SSL_ERROR_WANT_WRITE, - PY_SSL_ERROR_WANT_X509_LOOKUP, - PY_SSL_ERROR_SYSCALL, /* look at error stack/return value/errno */ - PY_SSL_ERROR_ZERO_RETURN, - PY_SSL_ERROR_WANT_CONNECT, - /* start of non ssl.h errorcodes */ - PY_SSL_ERROR_EOF, /* special case of SSL_ERROR_SYSCALL */ - PY_SSL_ERROR_INVALID_ERROR_CODE + /* these mirror ssl.h */ + PY_SSL_ERROR_NONE, + PY_SSL_ERROR_SSL, + PY_SSL_ERROR_WANT_READ, + PY_SSL_ERROR_WANT_WRITE, + PY_SSL_ERROR_WANT_X509_LOOKUP, + PY_SSL_ERROR_SYSCALL, /* look at error stack/return value/errno */ + PY_SSL_ERROR_ZERO_RETURN, + PY_SSL_ERROR_WANT_CONNECT, + /* start of non ssl.h errorcodes */ + PY_SSL_ERROR_EOF, /* special case of SSL_ERROR_SYSCALL */ + PY_SSL_ERROR_INVALID_ERROR_CODE }; enum py_ssl_server_or_client { - PY_SSL_CLIENT, - PY_SSL_SERVER + PY_SSL_CLIENT, + PY_SSL_SERVER }; enum py_ssl_cert_requirements { - PY_SSL_CERT_NONE, - PY_SSL_CERT_OPTIONAL, - PY_SSL_CERT_REQUIRED + PY_SSL_CERT_NONE, + PY_SSL_CERT_OPTIONAL, + PY_SSL_CERT_REQUIRED }; enum py_ssl_version { - PY_SSL_VERSION_SSL2, - PY_SSL_VERSION_SSL3, - PY_SSL_VERSION_SSL23, - PY_SSL_VERSION_TLS1 + PY_SSL_VERSION_SSL2, + PY_SSL_VERSION_SSL3, + PY_SSL_VERSION_SSL23, + PY_SSL_VERSION_TLS1 }; /* Include symbols from _socket module */ @@ -111,14 +111,14 @@ #endif typedef struct { - PyObject_HEAD - PySocketSockObject *Socket; /* Socket on which we're layered */ - SSL_CTX* ctx; - SSL* ssl; - X509* peer_cert; - char server[X509_NAME_MAXLEN]; - char issuer[X509_NAME_MAXLEN]; - int shutdown_seen_zero; + PyObject_HEAD + PySocketSockObject *Socket; /* Socket on which we're layered */ + SSL_CTX* ctx; + SSL* ssl; + X509* peer_cert; + char server[X509_NAME_MAXLEN]; + char issuer[X509_NAME_MAXLEN]; + int shutdown_seen_zero; } PySSLObject; @@ -126,19 +126,19 @@ static PyObject *PySSL_SSLwrite(PySSLObject *self, PyObject *args); static PyObject *PySSL_SSLread(PySSLObject *self, PyObject *args); static int check_socket_and_wait_for_timeout(PySocketSockObject *s, - int writing); + int writing); static PyObject *PySSL_peercert(PySSLObject *self, PyObject *args); static PyObject *PySSL_cipher(PySSLObject *self); -#define PySSLObject_Check(v) (Py_TYPE(v) == &PySSL_Type) +#define PySSLObject_Check(v) (Py_TYPE(v) == &PySSL_Type) typedef enum { - SOCKET_IS_NONBLOCKING, - SOCKET_IS_BLOCKING, - SOCKET_HAS_TIMED_OUT, - SOCKET_HAS_BEEN_CLOSED, - SOCKET_TOO_LARGE_FOR_SELECT, - SOCKET_OPERATION_OK + SOCKET_IS_NONBLOCKING, + SOCKET_IS_BLOCKING, + SOCKET_HAS_TIMED_OUT, + SOCKET_HAS_BEEN_CLOSED, + SOCKET_TOO_LARGE_FOR_SELECT, + SOCKET_OPERATION_OK } timeout_state; /* Wrap error strings with filename and line # */ @@ -155,294 +155,294 @@ static PyObject * PySSL_SetError(PySSLObject *obj, int ret, char *filename, int lineno) { - PyObject *v; - char buf[2048]; - char *errstr; - int err; - enum py_ssl_error p = PY_SSL_ERROR_NONE; - - assert(ret <= 0); - - if (obj->ssl != NULL) { - err = SSL_get_error(obj->ssl, ret); - - switch (err) { - case SSL_ERROR_ZERO_RETURN: - errstr = "TLS/SSL connection has been closed"; - p = PY_SSL_ERROR_ZERO_RETURN; - break; - case SSL_ERROR_WANT_READ: - errstr = "The operation did not complete (read)"; - p = PY_SSL_ERROR_WANT_READ; - break; - case SSL_ERROR_WANT_WRITE: - p = PY_SSL_ERROR_WANT_WRITE; - errstr = "The operation did not complete (write)"; - break; - case SSL_ERROR_WANT_X509_LOOKUP: - p = PY_SSL_ERROR_WANT_X509_LOOKUP; - errstr = - "The operation did not complete (X509 lookup)"; - break; - case SSL_ERROR_WANT_CONNECT: - p = PY_SSL_ERROR_WANT_CONNECT; - errstr = "The operation did not complete (connect)"; - break; - case SSL_ERROR_SYSCALL: - { - unsigned long e = ERR_get_error(); - if (e == 0) { - if (ret == 0 || !obj->Socket) { - p = PY_SSL_ERROR_EOF; - errstr = - "EOF occurred in violation of protocol"; - } else if (ret == -1) { - /* underlying BIO reported an I/O error */ - return obj->Socket->errorhandler(); - } else { /* possible? */ - p = PY_SSL_ERROR_SYSCALL; - errstr = "Some I/O error occurred"; - } - } else { - p = PY_SSL_ERROR_SYSCALL; - /* XXX Protected by global interpreter lock */ - errstr = ERR_error_string(e, NULL); - } - break; - } - case SSL_ERROR_SSL: - { - unsigned long e = ERR_get_error(); - p = PY_SSL_ERROR_SSL; - if (e != 0) - /* XXX Protected by global interpreter lock */ - errstr = ERR_error_string(e, NULL); - else { /* possible? */ - errstr = - "A failure in the SSL library occurred"; - } - break; - } - default: - p = PY_SSL_ERROR_INVALID_ERROR_CODE; - errstr = "Invalid error code"; - } - } else { - errstr = ERR_error_string(ERR_peek_last_error(), NULL); - } - PyOS_snprintf(buf, sizeof(buf), "_ssl.c:%d: %s", lineno, errstr); - v = Py_BuildValue("(is)", p, buf); - if (v != NULL) { - PyErr_SetObject(PySSLErrorObject, v); - Py_DECREF(v); - } - return NULL; + PyObject *v; + char buf[2048]; + char *errstr; + int err; + enum py_ssl_error p = PY_SSL_ERROR_NONE; + + assert(ret <= 0); + + if (obj->ssl != NULL) { + err = SSL_get_error(obj->ssl, ret); + + switch (err) { + case SSL_ERROR_ZERO_RETURN: + errstr = "TLS/SSL connection has been closed"; + p = PY_SSL_ERROR_ZERO_RETURN; + break; + case SSL_ERROR_WANT_READ: + errstr = "The operation did not complete (read)"; + p = PY_SSL_ERROR_WANT_READ; + break; + case SSL_ERROR_WANT_WRITE: + p = PY_SSL_ERROR_WANT_WRITE; + errstr = "The operation did not complete (write)"; + break; + case SSL_ERROR_WANT_X509_LOOKUP: + p = PY_SSL_ERROR_WANT_X509_LOOKUP; + errstr = + "The operation did not complete (X509 lookup)"; + break; + case SSL_ERROR_WANT_CONNECT: + p = PY_SSL_ERROR_WANT_CONNECT; + errstr = "The operation did not complete (connect)"; + break; + case SSL_ERROR_SYSCALL: + { + unsigned long e = ERR_get_error(); + if (e == 0) { + if (ret == 0 || !obj->Socket) { + p = PY_SSL_ERROR_EOF; + errstr = + "EOF occurred in violation of protocol"; + } else if (ret == -1) { + /* underlying BIO reported an I/O error */ + return obj->Socket->errorhandler(); + } else { /* possible? */ + p = PY_SSL_ERROR_SYSCALL; + errstr = "Some I/O error occurred"; + } + } else { + p = PY_SSL_ERROR_SYSCALL; + /* XXX Protected by global interpreter lock */ + errstr = ERR_error_string(e, NULL); + } + break; + } + case SSL_ERROR_SSL: + { + unsigned long e = ERR_get_error(); + p = PY_SSL_ERROR_SSL; + if (e != 0) + /* XXX Protected by global interpreter lock */ + errstr = ERR_error_string(e, NULL); + else { /* possible? */ + errstr = + "A failure in the SSL library occurred"; + } + break; + } + default: + p = PY_SSL_ERROR_INVALID_ERROR_CODE; + errstr = "Invalid error code"; + } + } else { + errstr = ERR_error_string(ERR_peek_last_error(), NULL); + } + PyOS_snprintf(buf, sizeof(buf), "_ssl.c:%d: %s", lineno, errstr); + v = Py_BuildValue("(is)", p, buf); + if (v != NULL) { + PyErr_SetObject(PySSLErrorObject, v); + Py_DECREF(v); + } + return NULL; } static PyObject * _setSSLError (char *errstr, int errcode, char *filename, int lineno) { - char buf[2048]; - PyObject *v; + char buf[2048]; + PyObject *v; - if (errstr == NULL) { - errcode = ERR_peek_last_error(); - errstr = ERR_error_string(errcode, NULL); - } - PyOS_snprintf(buf, sizeof(buf), "_ssl.c:%d: %s", lineno, errstr); - v = Py_BuildValue("(is)", errcode, buf); - if (v != NULL) { - PyErr_SetObject(PySSLErrorObject, v); - Py_DECREF(v); - } - return NULL; + if (errstr == NULL) { + errcode = ERR_peek_last_error(); + errstr = ERR_error_string(errcode, NULL); + } + PyOS_snprintf(buf, sizeof(buf), "_ssl.c:%d: %s", lineno, errstr); + v = Py_BuildValue("(is)", errcode, buf); + if (v != NULL) { + PyErr_SetObject(PySSLErrorObject, v); + Py_DECREF(v); + } + return NULL; } static PySSLObject * newPySSLObject(PySocketSockObject *Sock, char *key_file, char *cert_file, - enum py_ssl_server_or_client socket_type, - enum py_ssl_cert_requirements certreq, - enum py_ssl_version proto_version, - char *cacerts_file, char *ciphers) + enum py_ssl_server_or_client socket_type, + enum py_ssl_cert_requirements certreq, + enum py_ssl_version proto_version, + char *cacerts_file, char *ciphers) { - PySSLObject *self; - char *errstr = NULL; - int ret; - int verification_mode; - - self = PyObject_New(PySSLObject, &PySSL_Type); /* Create new object */ - if (self == NULL) - return NULL; - memset(self->server, '\0', sizeof(char) * X509_NAME_MAXLEN); - memset(self->issuer, '\0', sizeof(char) * X509_NAME_MAXLEN); - self->peer_cert = NULL; - self->ssl = NULL; - self->ctx = NULL; - self->Socket = NULL; - - /* Make sure the SSL error state is initialized */ - (void) ERR_get_state(); - ERR_clear_error(); - - if ((key_file && !cert_file) || (!key_file && cert_file)) { - errstr = ERRSTR("Both the key & certificate files " - "must be specified"); - goto fail; - } - - if ((socket_type == PY_SSL_SERVER) && - ((key_file == NULL) || (cert_file == NULL))) { - errstr = ERRSTR("Both the key & certificate files " - "must be specified for server-side operation"); - goto fail; - } - - PySSL_BEGIN_ALLOW_THREADS - if (proto_version == PY_SSL_VERSION_TLS1) - self->ctx = SSL_CTX_new(TLSv1_method()); /* Set up context */ - else if (proto_version == PY_SSL_VERSION_SSL3) - self->ctx = SSL_CTX_new(SSLv3_method()); /* Set up context */ - else if (proto_version == PY_SSL_VERSION_SSL2) - self->ctx = SSL_CTX_new(SSLv2_method()); /* Set up context */ - else if (proto_version == PY_SSL_VERSION_SSL23) - self->ctx = SSL_CTX_new(SSLv23_method()); /* Set up context */ - PySSL_END_ALLOW_THREADS - - if (self->ctx == NULL) { - errstr = ERRSTR("Invalid SSL protocol variant specified."); - goto fail; - } - - if (ciphers != NULL) { - ret = SSL_CTX_set_cipher_list(self->ctx, ciphers); - if (ret == 0) { - errstr = ERRSTR("No cipher can be selected."); - goto fail; - } - } - - if (certreq != PY_SSL_CERT_NONE) { - if (cacerts_file == NULL) { - errstr = ERRSTR("No root certificates specified for " - "verification of other-side certificates."); - goto fail; - } else { - PySSL_BEGIN_ALLOW_THREADS - ret = SSL_CTX_load_verify_locations(self->ctx, - cacerts_file, - NULL); - PySSL_END_ALLOW_THREADS - if (ret != 1) { - _setSSLError(NULL, 0, __FILE__, __LINE__); - goto fail; - } - } - } - if (key_file) { - PySSL_BEGIN_ALLOW_THREADS - ret = SSL_CTX_use_PrivateKey_file(self->ctx, key_file, - SSL_FILETYPE_PEM); - PySSL_END_ALLOW_THREADS - if (ret != 1) { - _setSSLError(NULL, ret, __FILE__, __LINE__); - goto fail; - } - - PySSL_BEGIN_ALLOW_THREADS - ret = SSL_CTX_use_certificate_chain_file(self->ctx, - cert_file); - PySSL_END_ALLOW_THREADS - if (ret != 1) { - /* - fprintf(stderr, "ret is %d, errcode is %lu, %lu, with file \"%s\"\n", - ret, ERR_peek_error(), ERR_peek_last_error(), cert_file); - */ - if (ERR_peek_last_error() != 0) { - _setSSLError(NULL, ret, __FILE__, __LINE__); - goto fail; - } - } - } - - /* ssl compatibility */ - SSL_CTX_set_options(self->ctx, SSL_OP_ALL); - - verification_mode = SSL_VERIFY_NONE; - if (certreq == PY_SSL_CERT_OPTIONAL) - verification_mode = SSL_VERIFY_PEER; - else if (certreq == PY_SSL_CERT_REQUIRED) - verification_mode = (SSL_VERIFY_PEER | - SSL_VERIFY_FAIL_IF_NO_PEER_CERT); - SSL_CTX_set_verify(self->ctx, verification_mode, - NULL); /* set verify lvl */ - - PySSL_BEGIN_ALLOW_THREADS - self->ssl = SSL_new(self->ctx); /* New ssl struct */ - PySSL_END_ALLOW_THREADS - SSL_set_fd(self->ssl, Sock->sock_fd); /* Set the socket for SSL */ + PySSLObject *self; + char *errstr = NULL; + int ret; + int verification_mode; + + self = PyObject_New(PySSLObject, &PySSL_Type); /* Create new object */ + if (self == NULL) + return NULL; + memset(self->server, '\0', sizeof(char) * X509_NAME_MAXLEN); + memset(self->issuer, '\0', sizeof(char) * X509_NAME_MAXLEN); + self->peer_cert = NULL; + self->ssl = NULL; + self->ctx = NULL; + self->Socket = NULL; + + /* Make sure the SSL error state is initialized */ + (void) ERR_get_state(); + ERR_clear_error(); + + if ((key_file && !cert_file) || (!key_file && cert_file)) { + errstr = ERRSTR("Both the key & certificate files " + "must be specified"); + goto fail; + } + + if ((socket_type == PY_SSL_SERVER) && + ((key_file == NULL) || (cert_file == NULL))) { + errstr = ERRSTR("Both the key & certificate files " + "must be specified for server-side operation"); + goto fail; + } + + PySSL_BEGIN_ALLOW_THREADS + if (proto_version == PY_SSL_VERSION_TLS1) + self->ctx = SSL_CTX_new(TLSv1_method()); /* Set up context */ + else if (proto_version == PY_SSL_VERSION_SSL3) + self->ctx = SSL_CTX_new(SSLv3_method()); /* Set up context */ + else if (proto_version == PY_SSL_VERSION_SSL2) + self->ctx = SSL_CTX_new(SSLv2_method()); /* Set up context */ + else if (proto_version == PY_SSL_VERSION_SSL23) + self->ctx = SSL_CTX_new(SSLv23_method()); /* Set up context */ + PySSL_END_ALLOW_THREADS + + if (self->ctx == NULL) { + errstr = ERRSTR("Invalid SSL protocol variant specified."); + goto fail; + } + + if (ciphers != NULL) { + ret = SSL_CTX_set_cipher_list(self->ctx, ciphers); + if (ret == 0) { + errstr = ERRSTR("No cipher can be selected."); + goto fail; + } + } + + if (certreq != PY_SSL_CERT_NONE) { + if (cacerts_file == NULL) { + errstr = ERRSTR("No root certificates specified for " + "verification of other-side certificates."); + goto fail; + } else { + PySSL_BEGIN_ALLOW_THREADS + ret = SSL_CTX_load_verify_locations(self->ctx, + cacerts_file, + NULL); + PySSL_END_ALLOW_THREADS + if (ret != 1) { + _setSSLError(NULL, 0, __FILE__, __LINE__); + goto fail; + } + } + } + if (key_file) { + PySSL_BEGIN_ALLOW_THREADS + ret = SSL_CTX_use_PrivateKey_file(self->ctx, key_file, + SSL_FILETYPE_PEM); + PySSL_END_ALLOW_THREADS + if (ret != 1) { + _setSSLError(NULL, ret, __FILE__, __LINE__); + goto fail; + } + + PySSL_BEGIN_ALLOW_THREADS + ret = SSL_CTX_use_certificate_chain_file(self->ctx, + cert_file); + PySSL_END_ALLOW_THREADS + if (ret != 1) { + /* + fprintf(stderr, "ret is %d, errcode is %lu, %lu, with file \"%s\"\n", + ret, ERR_peek_error(), ERR_peek_last_error(), cert_file); + */ + if (ERR_peek_last_error() != 0) { + _setSSLError(NULL, ret, __FILE__, __LINE__); + goto fail; + } + } + } + + /* ssl compatibility */ + SSL_CTX_set_options(self->ctx, SSL_OP_ALL); + + verification_mode = SSL_VERIFY_NONE; + if (certreq == PY_SSL_CERT_OPTIONAL) + verification_mode = SSL_VERIFY_PEER; + else if (certreq == PY_SSL_CERT_REQUIRED) + verification_mode = (SSL_VERIFY_PEER | + SSL_VERIFY_FAIL_IF_NO_PEER_CERT); + SSL_CTX_set_verify(self->ctx, verification_mode, + NULL); /* set verify lvl */ + + PySSL_BEGIN_ALLOW_THREADS + self->ssl = SSL_new(self->ctx); /* New ssl struct */ + PySSL_END_ALLOW_THREADS + SSL_set_fd(self->ssl, Sock->sock_fd); /* Set the socket for SSL */ #ifdef SSL_MODE_AUTO_RETRY - SSL_set_mode(self->ssl, SSL_MODE_AUTO_RETRY); + SSL_set_mode(self->ssl, SSL_MODE_AUTO_RETRY); #endif - /* If the socket is in non-blocking mode or timeout mode, set the BIO - * to non-blocking mode (blocking is the default) - */ - if (Sock->sock_timeout >= 0.0) { - /* Set both the read and write BIO's to non-blocking mode */ - BIO_set_nbio(SSL_get_rbio(self->ssl), 1); - BIO_set_nbio(SSL_get_wbio(self->ssl), 1); - } - - PySSL_BEGIN_ALLOW_THREADS - if (socket_type == PY_SSL_CLIENT) - SSL_set_connect_state(self->ssl); - else - SSL_set_accept_state(self->ssl); - PySSL_END_ALLOW_THREADS - - self->Socket = Sock; - Py_INCREF(self->Socket); - return self; + /* If the socket is in non-blocking mode or timeout mode, set the BIO + * to non-blocking mode (blocking is the default) + */ + if (Sock->sock_timeout >= 0.0) { + /* Set both the read and write BIO's to non-blocking mode */ + BIO_set_nbio(SSL_get_rbio(self->ssl), 1); + BIO_set_nbio(SSL_get_wbio(self->ssl), 1); + } + + PySSL_BEGIN_ALLOW_THREADS + if (socket_type == PY_SSL_CLIENT) + SSL_set_connect_state(self->ssl); + else + SSL_set_accept_state(self->ssl); + PySSL_END_ALLOW_THREADS + + self->Socket = Sock; + Py_INCREF(self->Socket); + return self; fail: - if (errstr) - PyErr_SetString(PySSLErrorObject, errstr); - Py_DECREF(self); - return NULL; + if (errstr) + PyErr_SetString(PySSLErrorObject, errstr); + Py_DECREF(self); + return NULL; } static PyObject * PySSL_sslwrap(PyObject *self, PyObject *args) { - PySocketSockObject *Sock; - int server_side = 0; - int verification_mode = PY_SSL_CERT_NONE; - int protocol = PY_SSL_VERSION_SSL23; - char *key_file = NULL; - char *cert_file = NULL; - char *cacerts_file = NULL; - char *ciphers = NULL; - - if (!PyArg_ParseTuple(args, "O!i|zziizz:sslwrap", - PySocketModule.Sock_Type, - &Sock, - &server_side, - &key_file, &cert_file, - &verification_mode, &protocol, - &cacerts_file, &ciphers)) - return NULL; - - /* - fprintf(stderr, - "server_side is %d, keyfile %p, certfile %p, verify_mode %d, " - "protocol %d, certs %p\n", - server_side, key_file, cert_file, verification_mode, - protocol, cacerts_file); - */ - - return (PyObject *) newPySSLObject(Sock, key_file, cert_file, - server_side, verification_mode, - protocol, cacerts_file, - ciphers); + PySocketSockObject *Sock; + int server_side = 0; + int verification_mode = PY_SSL_CERT_NONE; + int protocol = PY_SSL_VERSION_SSL23; + char *key_file = NULL; + char *cert_file = NULL; + char *cacerts_file = NULL; + char *ciphers = NULL; + + if (!PyArg_ParseTuple(args, "O!i|zziizz:sslwrap", + PySocketModule.Sock_Type, + &Sock, + &server_side, + &key_file, &cert_file, + &verification_mode, &protocol, + &cacerts_file, &ciphers)) + return NULL; + + /* + fprintf(stderr, + "server_side is %d, keyfile %p, certfile %p, verify_mode %d, " + "protocol %d, certs %p\n", + server_side, key_file, cert_file, verification_mode, + protocol, cacerts_file); + */ + + return (PyObject *) newPySSLObject(Sock, key_file, cert_file, + server_side, verification_mode, + protocol, cacerts_file, + ciphers); } PyDoc_STRVAR(ssl_doc, @@ -453,577 +453,577 @@ static PyObject *PySSL_SSLdo_handshake(PySSLObject *self) { - int ret; - int err; - int sockstate, nonblocking; - - /* just in case the blocking state of the socket has been changed */ - nonblocking = (self->Socket->sock_timeout >= 0.0); - BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking); - BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking); - - /* Actually negotiate SSL connection */ - /* XXX If SSL_do_handshake() returns 0, it's also a failure. */ - do { - PySSL_BEGIN_ALLOW_THREADS - ret = SSL_do_handshake(self->ssl); - err = SSL_get_error(self->ssl, ret); - PySSL_END_ALLOW_THREADS - if(PyErr_CheckSignals()) { - return NULL; - } - if (err == SSL_ERROR_WANT_READ) { - sockstate = check_socket_and_wait_for_timeout(self->Socket, 0); - } else if (err == SSL_ERROR_WANT_WRITE) { - sockstate = check_socket_and_wait_for_timeout(self->Socket, 1); - } else { - sockstate = SOCKET_OPERATION_OK; - } - if (sockstate == SOCKET_HAS_TIMED_OUT) { - PyErr_SetString(PySSLErrorObject, - ERRSTR("The handshake operation timed out")); - return NULL; - } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) { - PyErr_SetString(PySSLErrorObject, - ERRSTR("Underlying socket has been closed.")); - return NULL; - } else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) { - PyErr_SetString(PySSLErrorObject, - ERRSTR("Underlying socket too large for select().")); - return NULL; - } else if (sockstate == SOCKET_IS_NONBLOCKING) { - break; - } - } while (err == SSL_ERROR_WANT_READ || err == SSL_ERROR_WANT_WRITE); - if (ret < 1) - return PySSL_SetError(self, ret, __FILE__, __LINE__); - self->ssl->debug = 1; - - if (self->peer_cert) - X509_free (self->peer_cert); - PySSL_BEGIN_ALLOW_THREADS - if ((self->peer_cert = SSL_get_peer_certificate(self->ssl))) { - X509_NAME_oneline(X509_get_subject_name(self->peer_cert), - self->server, X509_NAME_MAXLEN); - X509_NAME_oneline(X509_get_issuer_name(self->peer_cert), - self->issuer, X509_NAME_MAXLEN); - } - PySSL_END_ALLOW_THREADS + int ret; + int err; + int sockstate, nonblocking; + + /* just in case the blocking state of the socket has been changed */ + nonblocking = (self->Socket->sock_timeout >= 0.0); + BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking); + BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking); + + /* Actually negotiate SSL connection */ + /* XXX If SSL_do_handshake() returns 0, it's also a failure. */ + do { + PySSL_BEGIN_ALLOW_THREADS + ret = SSL_do_handshake(self->ssl); + err = SSL_get_error(self->ssl, ret); + PySSL_END_ALLOW_THREADS + if(PyErr_CheckSignals()) { + return NULL; + } + if (err == SSL_ERROR_WANT_READ) { + sockstate = check_socket_and_wait_for_timeout(self->Socket, 0); + } else if (err == SSL_ERROR_WANT_WRITE) { + sockstate = check_socket_and_wait_for_timeout(self->Socket, 1); + } else { + sockstate = SOCKET_OPERATION_OK; + } + if (sockstate == SOCKET_HAS_TIMED_OUT) { + PyErr_SetString(PySSLErrorObject, + ERRSTR("The handshake operation timed out")); + return NULL; + } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) { + PyErr_SetString(PySSLErrorObject, + ERRSTR("Underlying socket has been closed.")); + return NULL; + } else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) { + PyErr_SetString(PySSLErrorObject, + ERRSTR("Underlying socket too large for select().")); + return NULL; + } else if (sockstate == SOCKET_IS_NONBLOCKING) { + break; + } + } while (err == SSL_ERROR_WANT_READ || err == SSL_ERROR_WANT_WRITE); + if (ret < 1) + return PySSL_SetError(self, ret, __FILE__, __LINE__); + self->ssl->debug = 1; + + if (self->peer_cert) + X509_free (self->peer_cert); + PySSL_BEGIN_ALLOW_THREADS + if ((self->peer_cert = SSL_get_peer_certificate(self->ssl))) { + X509_NAME_oneline(X509_get_subject_name(self->peer_cert), + self->server, X509_NAME_MAXLEN); + X509_NAME_oneline(X509_get_issuer_name(self->peer_cert), + self->issuer, X509_NAME_MAXLEN); + } + PySSL_END_ALLOW_THREADS - Py_INCREF(Py_None); - return Py_None; + Py_INCREF(Py_None); + return Py_None; } static PyObject * PySSL_server(PySSLObject *self) { - return PyString_FromString(self->server); + return PyString_FromString(self->server); } static PyObject * PySSL_issuer(PySSLObject *self) { - return PyString_FromString(self->issuer); + return PyString_FromString(self->issuer); } static PyObject * _create_tuple_for_attribute (ASN1_OBJECT *name, ASN1_STRING *value) { - char namebuf[X509_NAME_MAXLEN]; - int buflen; - PyObject *name_obj; - PyObject *value_obj; - PyObject *attr; - unsigned char *valuebuf = NULL; - - buflen = OBJ_obj2txt(namebuf, sizeof(namebuf), name, 0); - if (buflen < 0) { - _setSSLError(NULL, 0, __FILE__, __LINE__); - goto fail; - } - name_obj = PyString_FromStringAndSize(namebuf, buflen); - if (name_obj == NULL) - goto fail; - - buflen = ASN1_STRING_to_UTF8(&valuebuf, value); - if (buflen < 0) { - _setSSLError(NULL, 0, __FILE__, __LINE__); - Py_DECREF(name_obj); - goto fail; - } - value_obj = PyUnicode_DecodeUTF8((char *) valuebuf, - buflen, "strict"); - OPENSSL_free(valuebuf); - if (value_obj == NULL) { - Py_DECREF(name_obj); - goto fail; - } - attr = PyTuple_New(2); - if (attr == NULL) { - Py_DECREF(name_obj); - Py_DECREF(value_obj); - goto fail; - } - PyTuple_SET_ITEM(attr, 0, name_obj); - PyTuple_SET_ITEM(attr, 1, value_obj); - return attr; + char namebuf[X509_NAME_MAXLEN]; + int buflen; + PyObject *name_obj; + PyObject *value_obj; + PyObject *attr; + unsigned char *valuebuf = NULL; + + buflen = OBJ_obj2txt(namebuf, sizeof(namebuf), name, 0); + if (buflen < 0) { + _setSSLError(NULL, 0, __FILE__, __LINE__); + goto fail; + } + name_obj = PyString_FromStringAndSize(namebuf, buflen); + if (name_obj == NULL) + goto fail; + + buflen = ASN1_STRING_to_UTF8(&valuebuf, value); + if (buflen < 0) { + _setSSLError(NULL, 0, __FILE__, __LINE__); + Py_DECREF(name_obj); + goto fail; + } + value_obj = PyUnicode_DecodeUTF8((char *) valuebuf, + buflen, "strict"); + OPENSSL_free(valuebuf); + if (value_obj == NULL) { + Py_DECREF(name_obj); + goto fail; + } + attr = PyTuple_New(2); + if (attr == NULL) { + Py_DECREF(name_obj); + Py_DECREF(value_obj); + goto fail; + } + PyTuple_SET_ITEM(attr, 0, name_obj); + PyTuple_SET_ITEM(attr, 1, value_obj); + return attr; fail: - return NULL; + return NULL; } static PyObject * _create_tuple_for_X509_NAME (X509_NAME *xname) { - PyObject *dn = NULL; /* tuple which represents the "distinguished name" */ - PyObject *rdn = NULL; /* tuple to hold a "relative distinguished name" */ - PyObject *rdnt; - PyObject *attr = NULL; /* tuple to hold an attribute */ - int entry_count = X509_NAME_entry_count(xname); - X509_NAME_ENTRY *entry; - ASN1_OBJECT *name; - ASN1_STRING *value; - int index_counter; - int rdn_level = -1; - int retcode; - - dn = PyList_New(0); - if (dn == NULL) - return NULL; - /* now create another tuple to hold the top-level RDN */ - rdn = PyList_New(0); - if (rdn == NULL) - goto fail0; - - for (index_counter = 0; - index_counter < entry_count; - index_counter++) - { - entry = X509_NAME_get_entry(xname, index_counter); - - /* check to see if we've gotten to a new RDN */ - if (rdn_level >= 0) { - if (rdn_level != entry->set) { - /* yes, new RDN */ - /* add old RDN to DN */ - rdnt = PyList_AsTuple(rdn); - Py_DECREF(rdn); - if (rdnt == NULL) - goto fail0; - retcode = PyList_Append(dn, rdnt); - Py_DECREF(rdnt); - if (retcode < 0) - goto fail0; - /* create new RDN */ - rdn = PyList_New(0); - if (rdn == NULL) - goto fail0; - } - } - rdn_level = entry->set; - - /* now add this attribute to the current RDN */ - name = X509_NAME_ENTRY_get_object(entry); - value = X509_NAME_ENTRY_get_data(entry); - attr = _create_tuple_for_attribute(name, value); - /* - fprintf(stderr, "RDN level %d, attribute %s: %s\n", - entry->set, - PyString_AS_STRING(PyTuple_GET_ITEM(attr, 0)), - PyString_AS_STRING(PyTuple_GET_ITEM(attr, 1))); - */ - if (attr == NULL) - goto fail1; - retcode = PyList_Append(rdn, attr); - Py_DECREF(attr); - if (retcode < 0) - goto fail1; - } - /* now, there's typically a dangling RDN */ - if ((rdn != NULL) && (PyList_Size(rdn) > 0)) { - rdnt = PyList_AsTuple(rdn); - Py_DECREF(rdn); - if (rdnt == NULL) - goto fail0; - retcode = PyList_Append(dn, rdnt); - Py_DECREF(rdnt); - if (retcode < 0) - goto fail0; - } - - /* convert list to tuple */ - rdnt = PyList_AsTuple(dn); - Py_DECREF(dn); - if (rdnt == NULL) - return NULL; - return rdnt; + PyObject *dn = NULL; /* tuple which represents the "distinguished name" */ + PyObject *rdn = NULL; /* tuple to hold a "relative distinguished name" */ + PyObject *rdnt; + PyObject *attr = NULL; /* tuple to hold an attribute */ + int entry_count = X509_NAME_entry_count(xname); + X509_NAME_ENTRY *entry; + ASN1_OBJECT *name; + ASN1_STRING *value; + int index_counter; + int rdn_level = -1; + int retcode; + + dn = PyList_New(0); + if (dn == NULL) + return NULL; + /* now create another tuple to hold the top-level RDN */ + rdn = PyList_New(0); + if (rdn == NULL) + goto fail0; + + for (index_counter = 0; + index_counter < entry_count; + index_counter++) + { + entry = X509_NAME_get_entry(xname, index_counter); + + /* check to see if we've gotten to a new RDN */ + if (rdn_level >= 0) { + if (rdn_level != entry->set) { + /* yes, new RDN */ + /* add old RDN to DN */ + rdnt = PyList_AsTuple(rdn); + Py_DECREF(rdn); + if (rdnt == NULL) + goto fail0; + retcode = PyList_Append(dn, rdnt); + Py_DECREF(rdnt); + if (retcode < 0) + goto fail0; + /* create new RDN */ + rdn = PyList_New(0); + if (rdn == NULL) + goto fail0; + } + } + rdn_level = entry->set; + + /* now add this attribute to the current RDN */ + name = X509_NAME_ENTRY_get_object(entry); + value = X509_NAME_ENTRY_get_data(entry); + attr = _create_tuple_for_attribute(name, value); + /* + fprintf(stderr, "RDN level %d, attribute %s: %s\n", + entry->set, + PyString_AS_STRING(PyTuple_GET_ITEM(attr, 0)), + PyString_AS_STRING(PyTuple_GET_ITEM(attr, 1))); + */ + if (attr == NULL) + goto fail1; + retcode = PyList_Append(rdn, attr); + Py_DECREF(attr); + if (retcode < 0) + goto fail1; + } + /* now, there's typically a dangling RDN */ + if ((rdn != NULL) && (PyList_Size(rdn) > 0)) { + rdnt = PyList_AsTuple(rdn); + Py_DECREF(rdn); + if (rdnt == NULL) + goto fail0; + retcode = PyList_Append(dn, rdnt); + Py_DECREF(rdnt); + if (retcode < 0) + goto fail0; + } + + /* convert list to tuple */ + rdnt = PyList_AsTuple(dn); + Py_DECREF(dn); + if (rdnt == NULL) + return NULL; + return rdnt; fail1: - Py_XDECREF(rdn); + Py_XDECREF(rdn); fail0: - Py_XDECREF(dn); - return NULL; + Py_XDECREF(dn); + return NULL; } static PyObject * _get_peer_alt_names (X509 *certificate) { - - /* this code follows the procedure outlined in - OpenSSL's crypto/x509v3/v3_prn.c:X509v3_EXT_print() - function to extract the STACK_OF(GENERAL_NAME), - then iterates through the stack to add the - names. */ - - int i, j; - PyObject *peer_alt_names = Py_None; - PyObject *v, *t; - X509_EXTENSION *ext = NULL; - GENERAL_NAMES *names = NULL; - GENERAL_NAME *name; - X509V3_EXT_METHOD *method; - BIO *biobuf = NULL; - char buf[2048]; - char *vptr; - int len; - /* Issue #2973: ASN1_item_d2i() API changed in OpenSSL 0.9.6m */ + + /* this code follows the procedure outlined in + OpenSSL's crypto/x509v3/v3_prn.c:X509v3_EXT_print() + function to extract the STACK_OF(GENERAL_NAME), + then iterates through the stack to add the + names. */ + + int i, j; + PyObject *peer_alt_names = Py_None; + PyObject *v, *t; + X509_EXTENSION *ext = NULL; + GENERAL_NAMES *names = NULL; + GENERAL_NAME *name; + X509V3_EXT_METHOD *method; + BIO *biobuf = NULL; + char buf[2048]; + char *vptr; + int len; + /* Issue #2973: ASN1_item_d2i() API changed in OpenSSL 0.9.6m */ #if OPENSSL_VERSION_NUMBER >= 0x009060dfL - const unsigned char *p; + const unsigned char *p; #else - unsigned char *p; + unsigned char *p; #endif - if (certificate == NULL) - return peer_alt_names; + if (certificate == NULL) + return peer_alt_names; - /* get a memory buffer */ - biobuf = BIO_new(BIO_s_mem()); + /* get a memory buffer */ + biobuf = BIO_new(BIO_s_mem()); + + i = 0; + while ((i = X509_get_ext_by_NID( + certificate, NID_subject_alt_name, i)) >= 0) { + + if (peer_alt_names == Py_None) { + peer_alt_names = PyList_New(0); + if (peer_alt_names == NULL) + goto fail; + } + + /* now decode the altName */ + ext = X509_get_ext(certificate, i); + if(!(method = X509V3_EXT_get(ext))) { + PyErr_SetString(PySSLErrorObject, + ERRSTR("No method for internalizing subjectAltName!")); + goto fail; + } + + p = ext->value->data; + if (method->it) + names = (GENERAL_NAMES*) (ASN1_item_d2i(NULL, + &p, + ext->value->length, + ASN1_ITEM_ptr(method->it))); + else + names = (GENERAL_NAMES*) (method->d2i(NULL, + &p, + ext->value->length)); + + for(j = 0; j < sk_GENERAL_NAME_num(names); j++) { + + /* get a rendering of each name in the set of names */ + + name = sk_GENERAL_NAME_value(names, j); + if (name->type == GEN_DIRNAME) { + + /* we special-case DirName as a tuple of tuples of attributes */ + + t = PyTuple_New(2); + if (t == NULL) { + goto fail; + } + + v = PyString_FromString("DirName"); + if (v == NULL) { + Py_DECREF(t); + goto fail; + } + PyTuple_SET_ITEM(t, 0, v); + + v = _create_tuple_for_X509_NAME (name->d.dirn); + if (v == NULL) { + Py_DECREF(t); + goto fail; + } + PyTuple_SET_ITEM(t, 1, v); + + } else { + + /* for everything else, we use the OpenSSL print form */ + + (void) BIO_reset(biobuf); + GENERAL_NAME_print(biobuf, name); + len = BIO_gets(biobuf, buf, sizeof(buf)-1); + if (len < 0) { + _setSSLError(NULL, 0, __FILE__, __LINE__); + goto fail; + } + vptr = strchr(buf, ':'); + if (vptr == NULL) + goto fail; + t = PyTuple_New(2); + if (t == NULL) + goto fail; + v = PyString_FromStringAndSize(buf, (vptr - buf)); + if (v == NULL) { + Py_DECREF(t); + goto fail; + } + PyTuple_SET_ITEM(t, 0, v); + v = PyString_FromStringAndSize((vptr + 1), (len - (vptr - buf + 1))); + if (v == NULL) { + Py_DECREF(t); + goto fail; + } + PyTuple_SET_ITEM(t, 1, v); + } + + /* and add that rendering to the list */ + + if (PyList_Append(peer_alt_names, t) < 0) { + Py_DECREF(t); + goto fail; + } + Py_DECREF(t); + } + } + BIO_free(biobuf); + if (peer_alt_names != Py_None) { + v = PyList_AsTuple(peer_alt_names); + Py_DECREF(peer_alt_names); + return v; + } else { + return peer_alt_names; + } - i = 0; - while ((i = X509_get_ext_by_NID( - certificate, NID_subject_alt_name, i)) >= 0) { - - if (peer_alt_names == Py_None) { - peer_alt_names = PyList_New(0); - if (peer_alt_names == NULL) - goto fail; - } - - /* now decode the altName */ - ext = X509_get_ext(certificate, i); - if(!(method = X509V3_EXT_get(ext))) { - PyErr_SetString(PySSLErrorObject, - ERRSTR("No method for internalizing subjectAltName!")); - goto fail; - } - - p = ext->value->data; - if (method->it) - names = (GENERAL_NAMES*) (ASN1_item_d2i(NULL, - &p, - ext->value->length, - ASN1_ITEM_ptr(method->it))); - else - names = (GENERAL_NAMES*) (method->d2i(NULL, - &p, - ext->value->length)); - - for(j = 0; j < sk_GENERAL_NAME_num(names); j++) { - - /* get a rendering of each name in the set of names */ - - name = sk_GENERAL_NAME_value(names, j); - if (name->type == GEN_DIRNAME) { - - /* we special-case DirName as a tuple of tuples of attributes */ - - t = PyTuple_New(2); - if (t == NULL) { - goto fail; - } - - v = PyString_FromString("DirName"); - if (v == NULL) { - Py_DECREF(t); - goto fail; - } - PyTuple_SET_ITEM(t, 0, v); - - v = _create_tuple_for_X509_NAME (name->d.dirn); - if (v == NULL) { - Py_DECREF(t); - goto fail; - } - PyTuple_SET_ITEM(t, 1, v); - - } else { - - /* for everything else, we use the OpenSSL print form */ - - (void) BIO_reset(biobuf); - GENERAL_NAME_print(biobuf, name); - len = BIO_gets(biobuf, buf, sizeof(buf)-1); - if (len < 0) { - _setSSLError(NULL, 0, __FILE__, __LINE__); - goto fail; - } - vptr = strchr(buf, ':'); - if (vptr == NULL) - goto fail; - t = PyTuple_New(2); - if (t == NULL) - goto fail; - v = PyString_FromStringAndSize(buf, (vptr - buf)); - if (v == NULL) { - Py_DECREF(t); - goto fail; - } - PyTuple_SET_ITEM(t, 0, v); - v = PyString_FromStringAndSize((vptr + 1), (len - (vptr - buf + 1))); - if (v == NULL) { - Py_DECREF(t); - goto fail; - } - PyTuple_SET_ITEM(t, 1, v); - } - - /* and add that rendering to the list */ - - if (PyList_Append(peer_alt_names, t) < 0) { - Py_DECREF(t); - goto fail; - } - Py_DECREF(t); - } - } - BIO_free(biobuf); - if (peer_alt_names != Py_None) { - v = PyList_AsTuple(peer_alt_names); - Py_DECREF(peer_alt_names); - return v; - } else { - return peer_alt_names; - } - fail: - if (biobuf != NULL) - BIO_free(biobuf); + if (biobuf != NULL) + BIO_free(biobuf); - if (peer_alt_names != Py_None) { - Py_XDECREF(peer_alt_names); - } + if (peer_alt_names != Py_None) { + Py_XDECREF(peer_alt_names); + } - return NULL; + return NULL; } static PyObject * _decode_certificate (X509 *certificate, int verbose) { - PyObject *retval = NULL; - BIO *biobuf = NULL; - PyObject *peer; - PyObject *peer_alt_names = NULL; - PyObject *issuer; - PyObject *version; - PyObject *sn_obj; - ASN1_INTEGER *serialNumber; - char buf[2048]; - int len; - ASN1_TIME *notBefore, *notAfter; - PyObject *pnotBefore, *pnotAfter; - - retval = PyDict_New(); - if (retval == NULL) - return NULL; - - peer = _create_tuple_for_X509_NAME( - X509_get_subject_name(certificate)); - if (peer == NULL) - goto fail0; - if (PyDict_SetItemString(retval, (const char *) "subject", peer) < 0) { - Py_DECREF(peer); - goto fail0; - } - Py_DECREF(peer); - - if (verbose) { - issuer = _create_tuple_for_X509_NAME( - X509_get_issuer_name(certificate)); - if (issuer == NULL) - goto fail0; - if (PyDict_SetItemString(retval, (const char *)"issuer", issuer) < 0) { - Py_DECREF(issuer); - goto fail0; - } - Py_DECREF(issuer); - - version = PyInt_FromLong(X509_get_version(certificate) + 1); - if (PyDict_SetItemString(retval, "version", version) < 0) { - Py_DECREF(version); - goto fail0; - } - Py_DECREF(version); - } - - /* get a memory buffer */ - biobuf = BIO_new(BIO_s_mem()); - - if (verbose) { - - (void) BIO_reset(biobuf); - serialNumber = X509_get_serialNumber(certificate); - /* should not exceed 20 octets, 160 bits, so buf is big enough */ - i2a_ASN1_INTEGER(biobuf, serialNumber); - len = BIO_gets(biobuf, buf, sizeof(buf)-1); - if (len < 0) { - _setSSLError(NULL, 0, __FILE__, __LINE__); - goto fail1; - } - sn_obj = PyString_FromStringAndSize(buf, len); - if (sn_obj == NULL) - goto fail1; - if (PyDict_SetItemString(retval, "serialNumber", sn_obj) < 0) { - Py_DECREF(sn_obj); - goto fail1; - } - Py_DECREF(sn_obj); - - (void) BIO_reset(biobuf); - notBefore = X509_get_notBefore(certificate); - ASN1_TIME_print(biobuf, notBefore); - len = BIO_gets(biobuf, buf, sizeof(buf)-1); - if (len < 0) { - _setSSLError(NULL, 0, __FILE__, __LINE__); - goto fail1; - } - pnotBefore = PyString_FromStringAndSize(buf, len); - if (pnotBefore == NULL) - goto fail1; - if (PyDict_SetItemString(retval, "notBefore", pnotBefore) < 0) { - Py_DECREF(pnotBefore); - goto fail1; - } - Py_DECREF(pnotBefore); - } - - (void) BIO_reset(biobuf); - notAfter = X509_get_notAfter(certificate); - ASN1_TIME_print(biobuf, notAfter); - len = BIO_gets(biobuf, buf, sizeof(buf)-1); - if (len < 0) { - _setSSLError(NULL, 0, __FILE__, __LINE__); - goto fail1; - } - pnotAfter = PyString_FromStringAndSize(buf, len); - if (pnotAfter == NULL) - goto fail1; - if (PyDict_SetItemString(retval, "notAfter", pnotAfter) < 0) { - Py_DECREF(pnotAfter); - goto fail1; - } - Py_DECREF(pnotAfter); - - /* Now look for subjectAltName */ - - peer_alt_names = _get_peer_alt_names(certificate); - if (peer_alt_names == NULL) - goto fail1; - else if (peer_alt_names != Py_None) { - if (PyDict_SetItemString(retval, "subjectAltName", - peer_alt_names) < 0) { - Py_DECREF(peer_alt_names); - goto fail1; - } - Py_DECREF(peer_alt_names); - } - - BIO_free(biobuf); - return retval; + PyObject *retval = NULL; + BIO *biobuf = NULL; + PyObject *peer; + PyObject *peer_alt_names = NULL; + PyObject *issuer; + PyObject *version; + PyObject *sn_obj; + ASN1_INTEGER *serialNumber; + char buf[2048]; + int len; + ASN1_TIME *notBefore, *notAfter; + PyObject *pnotBefore, *pnotAfter; + + retval = PyDict_New(); + if (retval == NULL) + return NULL; + + peer = _create_tuple_for_X509_NAME( + X509_get_subject_name(certificate)); + if (peer == NULL) + goto fail0; + if (PyDict_SetItemString(retval, (const char *) "subject", peer) < 0) { + Py_DECREF(peer); + goto fail0; + } + Py_DECREF(peer); + + if (verbose) { + issuer = _create_tuple_for_X509_NAME( + X509_get_issuer_name(certificate)); + if (issuer == NULL) + goto fail0; + if (PyDict_SetItemString(retval, (const char *)"issuer", issuer) < 0) { + Py_DECREF(issuer); + goto fail0; + } + Py_DECREF(issuer); + + version = PyInt_FromLong(X509_get_version(certificate) + 1); + if (PyDict_SetItemString(retval, "version", version) < 0) { + Py_DECREF(version); + goto fail0; + } + Py_DECREF(version); + } + + /* get a memory buffer */ + biobuf = BIO_new(BIO_s_mem()); + + if (verbose) { + + (void) BIO_reset(biobuf); + serialNumber = X509_get_serialNumber(certificate); + /* should not exceed 20 octets, 160 bits, so buf is big enough */ + i2a_ASN1_INTEGER(biobuf, serialNumber); + len = BIO_gets(biobuf, buf, sizeof(buf)-1); + if (len < 0) { + _setSSLError(NULL, 0, __FILE__, __LINE__); + goto fail1; + } + sn_obj = PyString_FromStringAndSize(buf, len); + if (sn_obj == NULL) + goto fail1; + if (PyDict_SetItemString(retval, "serialNumber", sn_obj) < 0) { + Py_DECREF(sn_obj); + goto fail1; + } + Py_DECREF(sn_obj); + + (void) BIO_reset(biobuf); + notBefore = X509_get_notBefore(certificate); + ASN1_TIME_print(biobuf, notBefore); + len = BIO_gets(biobuf, buf, sizeof(buf)-1); + if (len < 0) { + _setSSLError(NULL, 0, __FILE__, __LINE__); + goto fail1; + } + pnotBefore = PyString_FromStringAndSize(buf, len); + if (pnotBefore == NULL) + goto fail1; + if (PyDict_SetItemString(retval, "notBefore", pnotBefore) < 0) { + Py_DECREF(pnotBefore); + goto fail1; + } + Py_DECREF(pnotBefore); + } + + (void) BIO_reset(biobuf); + notAfter = X509_get_notAfter(certificate); + ASN1_TIME_print(biobuf, notAfter); + len = BIO_gets(biobuf, buf, sizeof(buf)-1); + if (len < 0) { + _setSSLError(NULL, 0, __FILE__, __LINE__); + goto fail1; + } + pnotAfter = PyString_FromStringAndSize(buf, len); + if (pnotAfter == NULL) + goto fail1; + if (PyDict_SetItemString(retval, "notAfter", pnotAfter) < 0) { + Py_DECREF(pnotAfter); + goto fail1; + } + Py_DECREF(pnotAfter); + + /* Now look for subjectAltName */ + + peer_alt_names = _get_peer_alt_names(certificate); + if (peer_alt_names == NULL) + goto fail1; + else if (peer_alt_names != Py_None) { + if (PyDict_SetItemString(retval, "subjectAltName", + peer_alt_names) < 0) { + Py_DECREF(peer_alt_names); + goto fail1; + } + Py_DECREF(peer_alt_names); + } + + BIO_free(biobuf); + return retval; fail1: - if (biobuf != NULL) - BIO_free(biobuf); + if (biobuf != NULL) + BIO_free(biobuf); fail0: - Py_XDECREF(retval); - return NULL; + Py_XDECREF(retval); + return NULL; } static PyObject * PySSL_test_decode_certificate (PyObject *mod, PyObject *args) { - PyObject *retval = NULL; - char *filename = NULL; - X509 *x=NULL; - BIO *cert; - int verbose = 1; - - if (!PyArg_ParseTuple(args, "s|i:test_decode_certificate", &filename, &verbose)) - return NULL; - - if ((cert=BIO_new(BIO_s_file())) == NULL) { - PyErr_SetString(PySSLErrorObject, "Can't malloc memory to read file"); - goto fail0; - } - - if (BIO_read_filename(cert,filename) <= 0) { - PyErr_SetString(PySSLErrorObject, "Can't open file"); - goto fail0; - } - - x = PEM_read_bio_X509_AUX(cert,NULL, NULL, NULL); - if (x == NULL) { - PyErr_SetString(PySSLErrorObject, "Error decoding PEM-encoded file"); - goto fail0; - } + PyObject *retval = NULL; + char *filename = NULL; + X509 *x=NULL; + BIO *cert; + int verbose = 1; + + if (!PyArg_ParseTuple(args, "s|i:test_decode_certificate", &filename, &verbose)) + return NULL; + + if ((cert=BIO_new(BIO_s_file())) == NULL) { + PyErr_SetString(PySSLErrorObject, "Can't malloc memory to read file"); + goto fail0; + } + + if (BIO_read_filename(cert,filename) <= 0) { + PyErr_SetString(PySSLErrorObject, "Can't open file"); + goto fail0; + } + + x = PEM_read_bio_X509_AUX(cert,NULL, NULL, NULL); + if (x == NULL) { + PyErr_SetString(PySSLErrorObject, "Error decoding PEM-encoded file"); + goto fail0; + } - retval = _decode_certificate(x, verbose); + retval = _decode_certificate(x, verbose); fail0: - - if (cert != NULL) BIO_free(cert); - return retval; + + if (cert != NULL) BIO_free(cert); + return retval; } static PyObject * PySSL_peercert(PySSLObject *self, PyObject *args) { - PyObject *retval = NULL; - int len; - int verification; - PyObject *binary_mode = Py_None; - - if (!PyArg_ParseTuple(args, "|O:peer_certificate", &binary_mode)) - return NULL; - - if (!self->peer_cert) - Py_RETURN_NONE; - - if (PyObject_IsTrue(binary_mode)) { - /* return cert in DER-encoded format */ - - unsigned char *bytes_buf = NULL; - - bytes_buf = NULL; - len = i2d_X509(self->peer_cert, &bytes_buf); - if (len < 0) { - PySSL_SetError(self, len, __FILE__, __LINE__); - return NULL; - } - retval = PyString_FromStringAndSize((const char *) bytes_buf, len); - OPENSSL_free(bytes_buf); - return retval; - - } else { - - verification = SSL_CTX_get_verify_mode(self->ctx); - if ((verification & SSL_VERIFY_PEER) == 0) - return PyDict_New(); - else - return _decode_certificate (self->peer_cert, 0); - } + PyObject *retval = NULL; + int len; + int verification; + PyObject *binary_mode = Py_None; + + if (!PyArg_ParseTuple(args, "|O:peer_certificate", &binary_mode)) + return NULL; + + if (!self->peer_cert) + Py_RETURN_NONE; + + if (PyObject_IsTrue(binary_mode)) { + /* return cert in DER-encoded format */ + + unsigned char *bytes_buf = NULL; + + bytes_buf = NULL; + len = i2d_X509(self->peer_cert, &bytes_buf); + if (len < 0) { + PySSL_SetError(self, len, __FILE__, __LINE__); + return NULL; + } + retval = PyString_FromStringAndSize((const char *) bytes_buf, len); + OPENSSL_free(bytes_buf); + return retval; + + } else { + + verification = SSL_CTX_get_verify_mode(self->ctx); + if ((verification & SSL_VERIFY_PEER) == 0) + return PyDict_New(); + else + return _decode_certificate (self->peer_cert, 0); + } } PyDoc_STRVAR(PySSL_peercert_doc, @@ -1040,60 +1040,60 @@ static PyObject *PySSL_cipher (PySSLObject *self) { - PyObject *retval, *v; - SSL_CIPHER *current; - char *cipher_name; - char *cipher_protocol; - - if (self->ssl == NULL) - return Py_None; - current = SSL_get_current_cipher(self->ssl); - if (current == NULL) - return Py_None; - - retval = PyTuple_New(3); - if (retval == NULL) - return NULL; - - cipher_name = (char *) SSL_CIPHER_get_name(current); - if (cipher_name == NULL) { - PyTuple_SET_ITEM(retval, 0, Py_None); - } else { - v = PyString_FromString(cipher_name); - if (v == NULL) - goto fail0; - PyTuple_SET_ITEM(retval, 0, v); - } - cipher_protocol = SSL_CIPHER_get_version(current); - if (cipher_protocol == NULL) { - PyTuple_SET_ITEM(retval, 1, Py_None); - } else { - v = PyString_FromString(cipher_protocol); - if (v == NULL) - goto fail0; - PyTuple_SET_ITEM(retval, 1, v); - } - v = PyInt_FromLong(SSL_CIPHER_get_bits(current, NULL)); - if (v == NULL) - goto fail0; - PyTuple_SET_ITEM(retval, 2, v); - return retval; - + PyObject *retval, *v; + SSL_CIPHER *current; + char *cipher_name; + char *cipher_protocol; + + if (self->ssl == NULL) + return Py_None; + current = SSL_get_current_cipher(self->ssl); + if (current == NULL) + return Py_None; + + retval = PyTuple_New(3); + if (retval == NULL) + return NULL; + + cipher_name = (char *) SSL_CIPHER_get_name(current); + if (cipher_name == NULL) { + PyTuple_SET_ITEM(retval, 0, Py_None); + } else { + v = PyString_FromString(cipher_name); + if (v == NULL) + goto fail0; + PyTuple_SET_ITEM(retval, 0, v); + } + cipher_protocol = SSL_CIPHER_get_version(current); + if (cipher_protocol == NULL) { + PyTuple_SET_ITEM(retval, 1, Py_None); + } else { + v = PyString_FromString(cipher_protocol); + if (v == NULL) + goto fail0; + PyTuple_SET_ITEM(retval, 1, v); + } + v = PyInt_FromLong(SSL_CIPHER_get_bits(current, NULL)); + if (v == NULL) + goto fail0; + PyTuple_SET_ITEM(retval, 2, v); + return retval; + fail0: - Py_DECREF(retval); - return NULL; + Py_DECREF(retval); + return NULL; } static void PySSL_dealloc(PySSLObject *self) { - if (self->peer_cert) /* Possible not to have one? */ - X509_free (self->peer_cert); - if (self->ssl) - SSL_free(self->ssl); - if (self->ctx) - SSL_CTX_free(self->ctx); - Py_XDECREF(self->Socket); - PyObject_Del(self); + if (self->peer_cert) /* Possible not to have one? */ + X509_free (self->peer_cert); + if (self->ssl) + SSL_free(self->ssl); + if (self->ctx) + SSL_CTX_free(self->ctx); + Py_XDECREF(self->Socket); + PyObject_Del(self); } /* If the socket has a timeout, do a select()/poll() on the socket. @@ -1104,137 +1104,137 @@ static int check_socket_and_wait_for_timeout(PySocketSockObject *s, int writing) { - fd_set fds; - struct timeval tv; - int rc; - - /* Nothing to do unless we're in timeout mode (not non-blocking) */ - if (s->sock_timeout < 0.0) - return SOCKET_IS_BLOCKING; - else if (s->sock_timeout == 0.0) - return SOCKET_IS_NONBLOCKING; - - /* Guard against closed socket */ - if (s->sock_fd < 0) - return SOCKET_HAS_BEEN_CLOSED; + fd_set fds; + struct timeval tv; + int rc; + + /* Nothing to do unless we're in timeout mode (not non-blocking) */ + if (s->sock_timeout < 0.0) + return SOCKET_IS_BLOCKING; + else if (s->sock_timeout == 0.0) + return SOCKET_IS_NONBLOCKING; + + /* Guard against closed socket */ + if (s->sock_fd < 0) + return SOCKET_HAS_BEEN_CLOSED; - /* Prefer poll, if available, since you can poll() any fd - * which can't be done with select(). */ + /* Prefer poll, if available, since you can poll() any fd + * which can't be done with select(). */ #ifdef HAVE_POLL - { - struct pollfd pollfd; - int timeout; - - pollfd.fd = s->sock_fd; - pollfd.events = writing ? POLLOUT : POLLIN; - - /* s->sock_timeout is in seconds, timeout in ms */ - timeout = (int)(s->sock_timeout * 1000 + 0.5); - PySSL_BEGIN_ALLOW_THREADS - rc = poll(&pollfd, 1, timeout); - PySSL_END_ALLOW_THREADS + { + struct pollfd pollfd; + int timeout; + + pollfd.fd = s->sock_fd; + pollfd.events = writing ? POLLOUT : POLLIN; + + /* s->sock_timeout is in seconds, timeout in ms */ + timeout = (int)(s->sock_timeout * 1000 + 0.5); + PySSL_BEGIN_ALLOW_THREADS + rc = poll(&pollfd, 1, timeout); + PySSL_END_ALLOW_THREADS - goto normal_return; - } + goto normal_return; + } #endif - /* Guard against socket too large for select*/ + /* Guard against socket too large for select*/ #ifndef Py_SOCKET_FD_CAN_BE_GE_FD_SETSIZE - if (s->sock_fd >= FD_SETSIZE) - return SOCKET_TOO_LARGE_FOR_SELECT; + if (s->sock_fd >= FD_SETSIZE) + return SOCKET_TOO_LARGE_FOR_SELECT; #endif - /* Construct the arguments to select */ - tv.tv_sec = (int)s->sock_timeout; - tv.tv_usec = (int)((s->sock_timeout - tv.tv_sec) * 1e6); - FD_ZERO(&fds); - FD_SET(s->sock_fd, &fds); - - /* See if the socket is ready */ - PySSL_BEGIN_ALLOW_THREADS - if (writing) - rc = select(s->sock_fd+1, NULL, &fds, NULL, &tv); - else - rc = select(s->sock_fd+1, &fds, NULL, NULL, &tv); - PySSL_END_ALLOW_THREADS + /* Construct the arguments to select */ + tv.tv_sec = (int)s->sock_timeout; + tv.tv_usec = (int)((s->sock_timeout - tv.tv_sec) * 1e6); + FD_ZERO(&fds); + FD_SET(s->sock_fd, &fds); + + /* See if the socket is ready */ + PySSL_BEGIN_ALLOW_THREADS + if (writing) + rc = select(s->sock_fd+1, NULL, &fds, NULL, &tv); + else + rc = select(s->sock_fd+1, &fds, NULL, NULL, &tv); + PySSL_END_ALLOW_THREADS #ifdef HAVE_POLL normal_return: #endif - /* Return SOCKET_TIMED_OUT on timeout, SOCKET_OPERATION_OK otherwise - (when we are able to write or when there's something to read) */ - return rc == 0 ? SOCKET_HAS_TIMED_OUT : SOCKET_OPERATION_OK; + /* Return SOCKET_TIMED_OUT on timeout, SOCKET_OPERATION_OK otherwise + (when we are able to write or when there's something to read) */ + return rc == 0 ? SOCKET_HAS_TIMED_OUT : SOCKET_OPERATION_OK; } static PyObject *PySSL_SSLwrite(PySSLObject *self, PyObject *args) { - Py_buffer buf; - int len; - int sockstate; - int err; - int nonblocking; - - if (!PyArg_ParseTuple(args, "s*:write", &buf)) - return NULL; - - /* just in case the blocking state of the socket has been changed */ - nonblocking = (self->Socket->sock_timeout >= 0.0); - BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking); - BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking); - - sockstate = check_socket_and_wait_for_timeout(self->Socket, 1); - if (sockstate == SOCKET_HAS_TIMED_OUT) { - PyErr_SetString(PySSLErrorObject, - "The write operation timed out"); - goto error; - } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) { - PyErr_SetString(PySSLErrorObject, - "Underlying socket has been closed."); - goto error; - } else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) { - PyErr_SetString(PySSLErrorObject, - "Underlying socket too large for select()."); - goto error; - } - do { - PySSL_BEGIN_ALLOW_THREADS - len = SSL_write(self->ssl, buf.buf, buf.len); - err = SSL_get_error(self->ssl, len); - PySSL_END_ALLOW_THREADS - if (PyErr_CheckSignals()) { - goto error; - } - if (err == SSL_ERROR_WANT_READ) { - sockstate = - check_socket_and_wait_for_timeout(self->Socket, 0); - } else if (err == SSL_ERROR_WANT_WRITE) { - sockstate = - check_socket_and_wait_for_timeout(self->Socket, 1); - } else { - sockstate = SOCKET_OPERATION_OK; - } - if (sockstate == SOCKET_HAS_TIMED_OUT) { - PyErr_SetString(PySSLErrorObject, - "The write operation timed out"); - goto error; - } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) { - PyErr_SetString(PySSLErrorObject, - "Underlying socket has been closed."); - goto error; - } else if (sockstate == SOCKET_IS_NONBLOCKING) { - break; - } - } while (err == SSL_ERROR_WANT_READ || err == SSL_ERROR_WANT_WRITE); - - PyBuffer_Release(&buf); - if (len > 0) - return PyInt_FromLong(len); - else - return PySSL_SetError(self, len, __FILE__, __LINE__); + Py_buffer buf; + int len; + int sockstate; + int err; + int nonblocking; + + if (!PyArg_ParseTuple(args, "s*:write", &buf)) + return NULL; + + /* just in case the blocking state of the socket has been changed */ + nonblocking = (self->Socket->sock_timeout >= 0.0); + BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking); + BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking); + + sockstate = check_socket_and_wait_for_timeout(self->Socket, 1); + if (sockstate == SOCKET_HAS_TIMED_OUT) { + PyErr_SetString(PySSLErrorObject, + "The write operation timed out"); + goto error; + } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) { + PyErr_SetString(PySSLErrorObject, + "Underlying socket has been closed."); + goto error; + } else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) { + PyErr_SetString(PySSLErrorObject, + "Underlying socket too large for select()."); + goto error; + } + do { + PySSL_BEGIN_ALLOW_THREADS + len = SSL_write(self->ssl, buf.buf, buf.len); + err = SSL_get_error(self->ssl, len); + PySSL_END_ALLOW_THREADS + if (PyErr_CheckSignals()) { + goto error; + } + if (err == SSL_ERROR_WANT_READ) { + sockstate = + check_socket_and_wait_for_timeout(self->Socket, 0); + } else if (err == SSL_ERROR_WANT_WRITE) { + sockstate = + check_socket_and_wait_for_timeout(self->Socket, 1); + } else { + sockstate = SOCKET_OPERATION_OK; + } + if (sockstate == SOCKET_HAS_TIMED_OUT) { + PyErr_SetString(PySSLErrorObject, + "The write operation timed out"); + goto error; + } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) { + PyErr_SetString(PySSLErrorObject, + "Underlying socket has been closed."); + goto error; + } else if (sockstate == SOCKET_IS_NONBLOCKING) { + break; + } + } while (err == SSL_ERROR_WANT_READ || err == SSL_ERROR_WANT_WRITE); + + PyBuffer_Release(&buf); + if (len > 0) + return PyInt_FromLong(len); + else + return PySSL_SetError(self, len, __FILE__, __LINE__); error: - PyBuffer_Release(&buf); - return NULL; + PyBuffer_Release(&buf); + return NULL; } PyDoc_STRVAR(PySSL_SSLwrite_doc, @@ -1245,15 +1245,15 @@ static PyObject *PySSL_SSLpending(PySSLObject *self) { - int count = 0; + int count = 0; - PySSL_BEGIN_ALLOW_THREADS - count = SSL_pending(self->ssl); - PySSL_END_ALLOW_THREADS - if (count < 0) - return PySSL_SetError(self, count, __FILE__, __LINE__); - else - return PyInt_FromLong(count); + PySSL_BEGIN_ALLOW_THREADS + count = SSL_pending(self->ssl); + PySSL_END_ALLOW_THREADS + if (count < 0) + return PySSL_SetError(self, count, __FILE__, __LINE__); + else + return PyInt_FromLong(count); } PyDoc_STRVAR(PySSL_SSLpending_doc, @@ -1264,96 +1264,96 @@ static PyObject *PySSL_SSLread(PySSLObject *self, PyObject *args) { - PyObject *buf; - int count = 0; - int len = 1024; - int sockstate; - int err; - int nonblocking; - - if (!PyArg_ParseTuple(args, "|i:read", &len)) - return NULL; - - if (!(buf = PyString_FromStringAndSize((char *) 0, len))) - return NULL; - - /* just in case the blocking state of the socket has been changed */ - nonblocking = (self->Socket->sock_timeout >= 0.0); - BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking); - BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking); - - /* first check if there are bytes ready to be read */ - PySSL_BEGIN_ALLOW_THREADS - count = SSL_pending(self->ssl); - PySSL_END_ALLOW_THREADS - - if (!count) { - sockstate = check_socket_and_wait_for_timeout(self->Socket, 0); - if (sockstate == SOCKET_HAS_TIMED_OUT) { - PyErr_SetString(PySSLErrorObject, - "The read operation timed out"); - Py_DECREF(buf); - return NULL; - } else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) { - PyErr_SetString(PySSLErrorObject, - "Underlying socket too large for select()."); - Py_DECREF(buf); - return NULL; - } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) { - if (SSL_get_shutdown(self->ssl) != - SSL_RECEIVED_SHUTDOWN) - { - Py_DECREF(buf); - PyErr_SetString(PySSLErrorObject, - "Socket closed without SSL shutdown handshake"); - return NULL; - } else { - /* should contain a zero-length string */ - _PyString_Resize(&buf, 0); - return buf; - } - } - } - do { - PySSL_BEGIN_ALLOW_THREADS - count = SSL_read(self->ssl, PyString_AsString(buf), len); - err = SSL_get_error(self->ssl, count); - PySSL_END_ALLOW_THREADS - if(PyErr_CheckSignals()) { - Py_DECREF(buf); - return NULL; - } - if (err == SSL_ERROR_WANT_READ) { - sockstate = - check_socket_and_wait_for_timeout(self->Socket, 0); - } else if (err == SSL_ERROR_WANT_WRITE) { - sockstate = - check_socket_and_wait_for_timeout(self->Socket, 1); - } else if ((err == SSL_ERROR_ZERO_RETURN) && - (SSL_get_shutdown(self->ssl) == - SSL_RECEIVED_SHUTDOWN)) - { - _PyString_Resize(&buf, 0); - return buf; - } else { - sockstate = SOCKET_OPERATION_OK; - } - if (sockstate == SOCKET_HAS_TIMED_OUT) { - PyErr_SetString(PySSLErrorObject, - "The read operation timed out"); - Py_DECREF(buf); - return NULL; - } else if (sockstate == SOCKET_IS_NONBLOCKING) { - break; - } - } while (err == SSL_ERROR_WANT_READ || err == SSL_ERROR_WANT_WRITE); - if (count <= 0) { - Py_DECREF(buf); - return PySSL_SetError(self, count, __FILE__, __LINE__); - } - if (count != len) - _PyString_Resize(&buf, count); - return buf; + PyObject *buf; + int count = 0; + int len = 1024; + int sockstate; + int err; + int nonblocking; + + if (!PyArg_ParseTuple(args, "|i:read", &len)) + return NULL; + + if (!(buf = PyString_FromStringAndSize((char *) 0, len))) + return NULL; + + /* just in case the blocking state of the socket has been changed */ + nonblocking = (self->Socket->sock_timeout >= 0.0); + BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking); + BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking); + + /* first check if there are bytes ready to be read */ + PySSL_BEGIN_ALLOW_THREADS + count = SSL_pending(self->ssl); + PySSL_END_ALLOW_THREADS + + if (!count) { + sockstate = check_socket_and_wait_for_timeout(self->Socket, 0); + if (sockstate == SOCKET_HAS_TIMED_OUT) { + PyErr_SetString(PySSLErrorObject, + "The read operation timed out"); + Py_DECREF(buf); + return NULL; + } else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) { + PyErr_SetString(PySSLErrorObject, + "Underlying socket too large for select()."); + Py_DECREF(buf); + return NULL; + } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) { + if (SSL_get_shutdown(self->ssl) != + SSL_RECEIVED_SHUTDOWN) + { + Py_DECREF(buf); + PyErr_SetString(PySSLErrorObject, + "Socket closed without SSL shutdown handshake"); + return NULL; + } else { + /* should contain a zero-length string */ + _PyString_Resize(&buf, 0); + return buf; + } + } + } + do { + PySSL_BEGIN_ALLOW_THREADS + count = SSL_read(self->ssl, PyString_AsString(buf), len); + err = SSL_get_error(self->ssl, count); + PySSL_END_ALLOW_THREADS + if(PyErr_CheckSignals()) { + Py_DECREF(buf); + return NULL; + } + if (err == SSL_ERROR_WANT_READ) { + sockstate = + check_socket_and_wait_for_timeout(self->Socket, 0); + } else if (err == SSL_ERROR_WANT_WRITE) { + sockstate = + check_socket_and_wait_for_timeout(self->Socket, 1); + } else if ((err == SSL_ERROR_ZERO_RETURN) && + (SSL_get_shutdown(self->ssl) == + SSL_RECEIVED_SHUTDOWN)) + { + _PyString_Resize(&buf, 0); + return buf; + } else { + sockstate = SOCKET_OPERATION_OK; + } + if (sockstate == SOCKET_HAS_TIMED_OUT) { + PyErr_SetString(PySSLErrorObject, + "The read operation timed out"); + Py_DECREF(buf); + return NULL; + } else if (sockstate == SOCKET_IS_NONBLOCKING) { + break; + } + } while (err == SSL_ERROR_WANT_READ || err == SSL_ERROR_WANT_WRITE); + if (count <= 0) { + Py_DECREF(buf); + return PySSL_SetError(self, count, __FILE__, __LINE__); + } + if (count != len) + _PyString_Resize(&buf, count); + return buf; } PyDoc_STRVAR(PySSL_SSLread_doc, @@ -1363,82 +1363,82 @@ static PyObject *PySSL_SSLshutdown(PySSLObject *self) { - int err, ssl_err, sockstate, nonblocking; - int zeros = 0; + int err, ssl_err, sockstate, nonblocking; + int zeros = 0; + + /* Guard against closed socket */ + if (self->Socket->sock_fd < 0) { + PyErr_SetString(PySSLErrorObject, + "Underlying socket has been closed."); + return NULL; + } + + /* Just in case the blocking state of the socket has been changed */ + nonblocking = (self->Socket->sock_timeout >= 0.0); + BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking); + BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking); + + while (1) { + PySSL_BEGIN_ALLOW_THREADS + /* Disable read-ahead so that unwrap can work correctly. + * Otherwise OpenSSL might read in too much data, + * eating clear text data that happens to be + * transmitted after the SSL shutdown. + * Should be safe to call repeatedly everytime this + * function is used and the shutdown_seen_zero != 0 + * condition is met. + */ + if (self->shutdown_seen_zero) + SSL_set_read_ahead(self->ssl, 0); + err = SSL_shutdown(self->ssl); + PySSL_END_ALLOW_THREADS + /* If err == 1, a secure shutdown with SSL_shutdown() is complete */ + if (err > 0) + break; + if (err == 0) { + /* Don't loop endlessly; instead preserve legacy + behaviour of trying SSL_shutdown() only twice. + This looks necessary for OpenSSL < 0.9.8m */ + if (++zeros > 1) + break; + /* Shutdown was sent, now try receiving */ + self->shutdown_seen_zero = 1; + continue; + } + + /* Possibly retry shutdown until timeout or failure */ + ssl_err = SSL_get_error(self->ssl, err); + if (ssl_err == SSL_ERROR_WANT_READ) + sockstate = check_socket_and_wait_for_timeout(self->Socket, 0); + else if (ssl_err == SSL_ERROR_WANT_WRITE) + sockstate = check_socket_and_wait_for_timeout(self->Socket, 1); + else + break; + if (sockstate == SOCKET_HAS_TIMED_OUT) { + if (ssl_err == SSL_ERROR_WANT_READ) + PyErr_SetString(PySSLErrorObject, + "The read operation timed out"); + else + PyErr_SetString(PySSLErrorObject, + "The write operation timed out"); + return NULL; + } + else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) { + PyErr_SetString(PySSLErrorObject, + "Underlying socket too large for select()."); + return NULL; + } + else if (sockstate != SOCKET_OPERATION_OK) + /* Retain the SSL error code */ + break; + } - /* Guard against closed socket */ - if (self->Socket->sock_fd < 0) { - PyErr_SetString(PySSLErrorObject, - "Underlying socket has been closed."); - return NULL; - } - - /* Just in case the blocking state of the socket has been changed */ - nonblocking = (self->Socket->sock_timeout >= 0.0); - BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking); - BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking); - - while (1) { - PySSL_BEGIN_ALLOW_THREADS - /* Disable read-ahead so that unwrap can work correctly. - * Otherwise OpenSSL might read in too much data, - * eating clear text data that happens to be - * transmitted after the SSL shutdown. - * Should be safe to call repeatedly everytime this - * function is used and the shutdown_seen_zero != 0 - * condition is met. - */ - if (self->shutdown_seen_zero) - SSL_set_read_ahead(self->ssl, 0); - err = SSL_shutdown(self->ssl); - PySSL_END_ALLOW_THREADS - /* If err == 1, a secure shutdown with SSL_shutdown() is complete */ - if (err > 0) - break; - if (err == 0) { - /* Don't loop endlessly; instead preserve legacy - behaviour of trying SSL_shutdown() only twice. - This looks necessary for OpenSSL < 0.9.8m */ - if (++zeros > 1) - break; - /* Shutdown was sent, now try receiving */ - self->shutdown_seen_zero = 1; - continue; - } - - /* Possibly retry shutdown until timeout or failure */ - ssl_err = SSL_get_error(self->ssl, err); - if (ssl_err == SSL_ERROR_WANT_READ) - sockstate = check_socket_and_wait_for_timeout(self->Socket, 0); - else if (ssl_err == SSL_ERROR_WANT_WRITE) - sockstate = check_socket_and_wait_for_timeout(self->Socket, 1); - else - break; - if (sockstate == SOCKET_HAS_TIMED_OUT) { - if (ssl_err == SSL_ERROR_WANT_READ) - PyErr_SetString(PySSLErrorObject, - "The read operation timed out"); - else - PyErr_SetString(PySSLErrorObject, - "The write operation timed out"); - return NULL; - } - else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) { - PyErr_SetString(PySSLErrorObject, - "Underlying socket too large for select()."); - return NULL; - } - else if (sockstate != SOCKET_OPERATION_OK) - /* Retain the SSL error code */ - break; - } - - if (err < 0) - return PySSL_SetError(self, err, __FILE__, __LINE__); - else { - Py_INCREF(self->Socket); - return (PyObject *) (self->Socket); - } + if (err < 0) + return PySSL_SetError(self, err, __FILE__, __LINE__); + else { + Py_INCREF(self->Socket); + return (PyObject *) (self->Socket); + } } PyDoc_STRVAR(PySSL_SSLshutdown_doc, @@ -1448,44 +1448,44 @@ the underlying socket object."); static PyMethodDef PySSLMethods[] = { - {"do_handshake", (PyCFunction)PySSL_SSLdo_handshake, METH_NOARGS}, - {"write", (PyCFunction)PySSL_SSLwrite, METH_VARARGS, - PySSL_SSLwrite_doc}, - {"read", (PyCFunction)PySSL_SSLread, METH_VARARGS, - PySSL_SSLread_doc}, - {"pending", (PyCFunction)PySSL_SSLpending, METH_NOARGS, - PySSL_SSLpending_doc}, - {"server", (PyCFunction)PySSL_server, METH_NOARGS}, - {"issuer", (PyCFunction)PySSL_issuer, METH_NOARGS}, - {"peer_certificate", (PyCFunction)PySSL_peercert, METH_VARARGS, - PySSL_peercert_doc}, - {"cipher", (PyCFunction)PySSL_cipher, METH_NOARGS}, - {"shutdown", (PyCFunction)PySSL_SSLshutdown, METH_NOARGS, - PySSL_SSLshutdown_doc}, - {NULL, NULL} + {"do_handshake", (PyCFunction)PySSL_SSLdo_handshake, METH_NOARGS}, + {"write", (PyCFunction)PySSL_SSLwrite, METH_VARARGS, + PySSL_SSLwrite_doc}, + {"read", (PyCFunction)PySSL_SSLread, METH_VARARGS, + PySSL_SSLread_doc}, + {"pending", (PyCFunction)PySSL_SSLpending, METH_NOARGS, + PySSL_SSLpending_doc}, + {"server", (PyCFunction)PySSL_server, METH_NOARGS}, + {"issuer", (PyCFunction)PySSL_issuer, METH_NOARGS}, + {"peer_certificate", (PyCFunction)PySSL_peercert, METH_VARARGS, + PySSL_peercert_doc}, + {"cipher", (PyCFunction)PySSL_cipher, METH_NOARGS}, + {"shutdown", (PyCFunction)PySSL_SSLshutdown, METH_NOARGS, + PySSL_SSLshutdown_doc}, + {NULL, NULL} }; static PyObject *PySSL_getattr(PySSLObject *self, char *name) { - return Py_FindMethod(PySSLMethods, (PyObject *)self, name); + return Py_FindMethod(PySSLMethods, (PyObject *)self, name); } static PyTypeObject PySSL_Type = { - PyVarObject_HEAD_INIT(NULL, 0) - "ssl.SSLContext", /*tp_name*/ - sizeof(PySSLObject), /*tp_basicsize*/ - 0, /*tp_itemsize*/ - /* methods */ - (destructor)PySSL_dealloc, /*tp_dealloc*/ - 0, /*tp_print*/ - (getattrfunc)PySSL_getattr, /*tp_getattr*/ - 0, /*tp_setattr*/ - 0, /*tp_compare*/ - 0, /*tp_repr*/ - 0, /*tp_as_number*/ - 0, /*tp_as_sequence*/ - 0, /*tp_as_mapping*/ - 0, /*tp_hash*/ + PyVarObject_HEAD_INIT(NULL, 0) + "ssl.SSLContext", /*tp_name*/ + sizeof(PySSLObject), /*tp_basicsize*/ + 0, /*tp_itemsize*/ + /* methods */ + (destructor)PySSL_dealloc, /*tp_dealloc*/ + 0, /*tp_print*/ + (getattrfunc)PySSL_getattr, /*tp_getattr*/ + 0, /*tp_setattr*/ + 0, /*tp_compare*/ + 0, /*tp_repr*/ + 0, /*tp_as_number*/ + 0, /*tp_as_sequence*/ + 0, /*tp_as_mapping*/ + 0, /*tp_hash*/ }; #ifdef HAVE_OPENSSL_RAND @@ -1499,7 +1499,7 @@ double entropy; if (!PyArg_ParseTuple(args, "s#d:RAND_add", &buf, &len, &entropy)) - return NULL; + return NULL; RAND_add(buf, len, entropy); Py_INCREF(Py_None); return Py_None; @@ -1530,15 +1530,15 @@ int bytes; if (!PyString_Check(arg)) - return PyErr_Format(PyExc_TypeError, - "RAND_egd() expected string, found %s", - Py_TYPE(arg)->tp_name); + return PyErr_Format(PyExc_TypeError, + "RAND_egd() expected string, found %s", + Py_TYPE(arg)->tp_name); bytes = RAND_egd(PyString_AS_STRING(arg)); if (bytes == -1) { - PyErr_SetString(PySSLErrorObject, - "EGD connection failed or EGD did not return " - "enough data to seed the PRNG"); - return NULL; + PyErr_SetString(PySSLErrorObject, + "EGD connection failed or EGD did not return " + "enough data to seed the PRNG"); + return NULL; } return PyInt_FromLong(bytes); } @@ -1555,19 +1555,19 @@ /* List of functions exported by this module. */ static PyMethodDef PySSL_methods[] = { - {"sslwrap", PySSL_sslwrap, - METH_VARARGS, ssl_doc}, - {"_test_decode_cert", PySSL_test_decode_certificate, - METH_VARARGS}, + {"sslwrap", PySSL_sslwrap, + METH_VARARGS, ssl_doc}, + {"_test_decode_cert", PySSL_test_decode_certificate, + METH_VARARGS}, #ifdef HAVE_OPENSSL_RAND - {"RAND_add", PySSL_RAND_add, METH_VARARGS, - PySSL_RAND_add_doc}, - {"RAND_egd", PySSL_RAND_egd, METH_O, - PySSL_RAND_egd_doc}, - {"RAND_status", (PyCFunction)PySSL_RAND_status, METH_NOARGS, - PySSL_RAND_status_doc}, + {"RAND_add", PySSL_RAND_add, METH_VARARGS, + PySSL_RAND_add_doc}, + {"RAND_egd", PySSL_RAND_egd, METH_O, + PySSL_RAND_egd_doc}, + {"RAND_status", (PyCFunction)PySSL_RAND_status, METH_NOARGS, + PySSL_RAND_status_doc}, #endif - {NULL, NULL} /* Sentinel */ + {NULL, NULL} /* Sentinel */ }; @@ -1579,64 +1579,64 @@ static PyThread_type_lock *_ssl_locks = NULL; static unsigned long _ssl_thread_id_function (void) { - return PyThread_get_thread_ident(); + return PyThread_get_thread_ident(); } static void _ssl_thread_locking_function (int mode, int n, const char *file, int line) { - /* this function is needed to perform locking on shared data - structures. (Note that OpenSSL uses a number of global data - structures that will be implicitly shared whenever multiple threads - use OpenSSL.) Multi-threaded applications will crash at random if - it is not set. - - locking_function() must be able to handle up to CRYPTO_num_locks() - different mutex locks. It sets the n-th lock if mode & CRYPTO_LOCK, and - releases it otherwise. - - file and line are the file number of the function setting the - lock. They can be useful for debugging. - */ - - if ((_ssl_locks == NULL) || - (n < 0) || ((unsigned)n >= _ssl_locks_count)) - return; - - if (mode & CRYPTO_LOCK) { - PyThread_acquire_lock(_ssl_locks[n], 1); - } else { - PyThread_release_lock(_ssl_locks[n]); - } + /* this function is needed to perform locking on shared data + structures. (Note that OpenSSL uses a number of global data + structures that will be implicitly shared whenever multiple threads + use OpenSSL.) Multi-threaded applications will crash at random if + it is not set. + + locking_function() must be able to handle up to CRYPTO_num_locks() + different mutex locks. It sets the n-th lock if mode & CRYPTO_LOCK, and + releases it otherwise. + + file and line are the file number of the function setting the + lock. They can be useful for debugging. + */ + + if ((_ssl_locks == NULL) || + (n < 0) || ((unsigned)n >= _ssl_locks_count)) + return; + + if (mode & CRYPTO_LOCK) { + PyThread_acquire_lock(_ssl_locks[n], 1); + } else { + PyThread_release_lock(_ssl_locks[n]); + } } static int _setup_ssl_threads(void) { - unsigned int i; + unsigned int i; - if (_ssl_locks == NULL) { - _ssl_locks_count = CRYPTO_num_locks(); - _ssl_locks = (PyThread_type_lock *) - malloc(sizeof(PyThread_type_lock) * _ssl_locks_count); - if (_ssl_locks == NULL) - return 0; - memset(_ssl_locks, 0, sizeof(PyThread_type_lock) * _ssl_locks_count); - for (i = 0; i < _ssl_locks_count; i++) { - _ssl_locks[i] = PyThread_allocate_lock(); - if (_ssl_locks[i] == NULL) { - unsigned int j; - for (j = 0; j < i; j++) { - PyThread_free_lock(_ssl_locks[j]); - } - free(_ssl_locks); - return 0; - } - } - CRYPTO_set_locking_callback(_ssl_thread_locking_function); - CRYPTO_set_id_callback(_ssl_thread_id_function); - } - return 1; + if (_ssl_locks == NULL) { + _ssl_locks_count = CRYPTO_num_locks(); + _ssl_locks = (PyThread_type_lock *) + malloc(sizeof(PyThread_type_lock) * _ssl_locks_count); + if (_ssl_locks == NULL) + return 0; + memset(_ssl_locks, 0, sizeof(PyThread_type_lock) * _ssl_locks_count); + for (i = 0; i < _ssl_locks_count; i++) { + _ssl_locks[i] = PyThread_allocate_lock(); + if (_ssl_locks[i] == NULL) { + unsigned int j; + for (j = 0; j < i; j++) { + PyThread_free_lock(_ssl_locks[j]); + } + free(_ssl_locks); + return 0; + } + } + CRYPTO_set_locking_callback(_ssl_thread_locking_function); + CRYPTO_set_id_callback(_ssl_thread_id_function); + } + return 1; } -#endif /* def HAVE_THREAD */ +#endif /* def HAVE_THREAD */ PyDoc_STRVAR(module_doc, "Implementation module for SSL socket operations. See the socket module\n\ @@ -1645,103 +1645,103 @@ PyMODINIT_FUNC init_ssl(void) { - PyObject *m, *d, *r; - unsigned long libver; - unsigned int major, minor, fix, patch, status; - - Py_TYPE(&PySSL_Type) = &PyType_Type; - - m = Py_InitModule3("_ssl", PySSL_methods, module_doc); - if (m == NULL) - return; - d = PyModule_GetDict(m); - - /* Load _socket module and its C API */ - if (PySocketModule_ImportModuleAndAPI()) - return; - - /* Init OpenSSL */ - SSL_load_error_strings(); - SSL_library_init(); + PyObject *m, *d, *r; + unsigned long libver; + unsigned int major, minor, fix, patch, status; + + Py_TYPE(&PySSL_Type) = &PyType_Type; + + m = Py_InitModule3("_ssl", PySSL_methods, module_doc); + if (m == NULL) + return; + d = PyModule_GetDict(m); + + /* Load _socket module and its C API */ + if (PySocketModule_ImportModuleAndAPI()) + return; + + /* Init OpenSSL */ + SSL_load_error_strings(); + SSL_library_init(); #ifdef WITH_THREAD - /* note that this will start threading if not already started */ - if (!_setup_ssl_threads()) { - return; - } + /* note that this will start threading if not already started */ + if (!_setup_ssl_threads()) { + return; + } #endif - OpenSSL_add_all_algorithms(); + OpenSSL_add_all_algorithms(); - /* Add symbols to module dict */ - PySSLErrorObject = PyErr_NewException("ssl.SSLError", - PySocketModule.error, - NULL); - if (PySSLErrorObject == NULL) - return; - if (PyDict_SetItemString(d, "SSLError", PySSLErrorObject) != 0) - return; - if (PyDict_SetItemString(d, "SSLType", - (PyObject *)&PySSL_Type) != 0) - return; - PyModule_AddIntConstant(m, "SSL_ERROR_ZERO_RETURN", - PY_SSL_ERROR_ZERO_RETURN); - PyModule_AddIntConstant(m, "SSL_ERROR_WANT_READ", - PY_SSL_ERROR_WANT_READ); - PyModule_AddIntConstant(m, "SSL_ERROR_WANT_WRITE", - PY_SSL_ERROR_WANT_WRITE); - PyModule_AddIntConstant(m, "SSL_ERROR_WANT_X509_LOOKUP", - PY_SSL_ERROR_WANT_X509_LOOKUP); - PyModule_AddIntConstant(m, "SSL_ERROR_SYSCALL", - PY_SSL_ERROR_SYSCALL); - PyModule_AddIntConstant(m, "SSL_ERROR_SSL", - PY_SSL_ERROR_SSL); - PyModule_AddIntConstant(m, "SSL_ERROR_WANT_CONNECT", - PY_SSL_ERROR_WANT_CONNECT); - /* non ssl.h errorcodes */ - PyModule_AddIntConstant(m, "SSL_ERROR_EOF", - PY_SSL_ERROR_EOF); - PyModule_AddIntConstant(m, "SSL_ERROR_INVALID_ERROR_CODE", - PY_SSL_ERROR_INVALID_ERROR_CODE); - /* cert requirements */ - PyModule_AddIntConstant(m, "CERT_NONE", - PY_SSL_CERT_NONE); - PyModule_AddIntConstant(m, "CERT_OPTIONAL", - PY_SSL_CERT_OPTIONAL); - PyModule_AddIntConstant(m, "CERT_REQUIRED", - PY_SSL_CERT_REQUIRED); - - /* protocol versions */ - PyModule_AddIntConstant(m, "PROTOCOL_SSLv2", - PY_SSL_VERSION_SSL2); - PyModule_AddIntConstant(m, "PROTOCOL_SSLv3", - PY_SSL_VERSION_SSL3); - PyModule_AddIntConstant(m, "PROTOCOL_SSLv23", - PY_SSL_VERSION_SSL23); - PyModule_AddIntConstant(m, "PROTOCOL_TLSv1", - PY_SSL_VERSION_TLS1); - - /* OpenSSL version */ - /* SSLeay() gives us the version of the library linked against, - which could be different from the headers version. - */ - libver = SSLeay(); - r = PyLong_FromUnsignedLong(libver); - if (r == NULL) - return; - if (PyModule_AddObject(m, "OPENSSL_VERSION_NUMBER", r)) - return; - status = libver & 0xF; - libver >>= 4; - patch = libver & 0xFF; - libver >>= 8; - fix = libver & 0xFF; - libver >>= 8; - minor = libver & 0xFF; - libver >>= 8; - major = libver & 0xFF; - r = Py_BuildValue("IIIII", major, minor, fix, patch, status); - if (r == NULL || PyModule_AddObject(m, "OPENSSL_VERSION_INFO", r)) - return; - r = PyString_FromString(SSLeay_version(SSLEAY_VERSION)); - if (r == NULL || PyModule_AddObject(m, "OPENSSL_VERSION", r)) - return; + /* Add symbols to module dict */ + PySSLErrorObject = PyErr_NewException("ssl.SSLError", + PySocketModule.error, + NULL); + if (PySSLErrorObject == NULL) + return; + if (PyDict_SetItemString(d, "SSLError", PySSLErrorObject) != 0) + return; + if (PyDict_SetItemString(d, "SSLType", + (PyObject *)&PySSL_Type) != 0) + return; + PyModule_AddIntConstant(m, "SSL_ERROR_ZERO_RETURN", + PY_SSL_ERROR_ZERO_RETURN); + PyModule_AddIntConstant(m, "SSL_ERROR_WANT_READ", + PY_SSL_ERROR_WANT_READ); + PyModule_AddIntConstant(m, "SSL_ERROR_WANT_WRITE", + PY_SSL_ERROR_WANT_WRITE); + PyModule_AddIntConstant(m, "SSL_ERROR_WANT_X509_LOOKUP", + PY_SSL_ERROR_WANT_X509_LOOKUP); + PyModule_AddIntConstant(m, "SSL_ERROR_SYSCALL", + PY_SSL_ERROR_SYSCALL); + PyModule_AddIntConstant(m, "SSL_ERROR_SSL", + PY_SSL_ERROR_SSL); + PyModule_AddIntConstant(m, "SSL_ERROR_WANT_CONNECT", + PY_SSL_ERROR_WANT_CONNECT); + /* non ssl.h errorcodes */ + PyModule_AddIntConstant(m, "SSL_ERROR_EOF", + PY_SSL_ERROR_EOF); + PyModule_AddIntConstant(m, "SSL_ERROR_INVALID_ERROR_CODE", + PY_SSL_ERROR_INVALID_ERROR_CODE); + /* cert requirements */ + PyModule_AddIntConstant(m, "CERT_NONE", + PY_SSL_CERT_NONE); + PyModule_AddIntConstant(m, "CERT_OPTIONAL", + PY_SSL_CERT_OPTIONAL); + PyModule_AddIntConstant(m, "CERT_REQUIRED", + PY_SSL_CERT_REQUIRED); + + /* protocol versions */ + PyModule_AddIntConstant(m, "PROTOCOL_SSLv2", + PY_SSL_VERSION_SSL2); + PyModule_AddIntConstant(m, "PROTOCOL_SSLv3", + PY_SSL_VERSION_SSL3); + PyModule_AddIntConstant(m, "PROTOCOL_SSLv23", + PY_SSL_VERSION_SSL23); + PyModule_AddIntConstant(m, "PROTOCOL_TLSv1", + PY_SSL_VERSION_TLS1); + + /* OpenSSL version */ + /* SSLeay() gives us the version of the library linked against, + which could be different from the headers version. + */ + libver = SSLeay(); + r = PyLong_FromUnsignedLong(libver); + if (r == NULL) + return; + if (PyModule_AddObject(m, "OPENSSL_VERSION_NUMBER", r)) + return; + status = libver & 0xF; + libver >>= 4; + patch = libver & 0xFF; + libver >>= 8; + fix = libver & 0xFF; + libver >>= 8; + minor = libver & 0xFF; + libver >>= 8; + major = libver & 0xFF; + r = Py_BuildValue("IIIII", major, minor, fix, patch, status); + if (r == NULL || PyModule_AddObject(m, "OPENSSL_VERSION_INFO", r)) + return; + r = PyString_FromString(SSLeay_version(SSLEAY_VERSION)); + if (r == NULL || PyModule_AddObject(m, "OPENSSL_VERSION", r)) + return; } From python-checkins at python.org Wed May 5 17:57:33 2010 From: python-checkins at python.org (antoine.pitrou) Date: Wed, 5 May 2010 17:57:33 +0200 (CEST) Subject: [Python-checkins] r80790 - in python/branches/py3k: Modules/_ssl.c Message-ID: <20100505155733.DF417EEA1E@mail.python.org> Author: antoine.pitrou Date: Wed May 5 17:57:33 2010 New Revision: 80790 Log: Merged revisions 80789 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r80789 | antoine.pitrou | 2010-05-05 17:53:45 +0200 (mer., 05 mai 2010) | 3 lines Untabify Modules/_ssl.c ........ Modified: python/branches/py3k/ (props changed) python/branches/py3k/Modules/_ssl.c Modified: python/branches/py3k/Modules/_ssl.c ============================================================================== --- python/branches/py3k/Modules/_ssl.c (original) +++ python/branches/py3k/Modules/_ssl.c Wed May 5 17:57:33 2010 @@ -19,14 +19,14 @@ #ifdef WITH_THREAD #include "pythread.h" #define PySSL_BEGIN_ALLOW_THREADS { \ - PyThreadState *_save = NULL; \ - if (_ssl_locks_count>0) {_save = PyEval_SaveThread();} -#define PySSL_BLOCK_THREADS if (_ssl_locks_count>0){PyEval_RestoreThread(_save)}; -#define PySSL_UNBLOCK_THREADS if (_ssl_locks_count>0){_save = PyEval_SaveThread()}; -#define PySSL_END_ALLOW_THREADS if (_ssl_locks_count>0){PyEval_RestoreThread(_save);} \ - } + PyThreadState *_save = NULL; \ + if (_ssl_locks_count>0) {_save = PyEval_SaveThread();} +#define PySSL_BLOCK_THREADS if (_ssl_locks_count>0){PyEval_RestoreThread(_save)}; +#define PySSL_UNBLOCK_THREADS if (_ssl_locks_count>0){_save = PyEval_SaveThread()}; +#define PySSL_END_ALLOW_THREADS if (_ssl_locks_count>0){PyEval_RestoreThread(_save);} \ + } -#else /* no WITH_THREAD */ +#else /* no WITH_THREAD */ #define PySSL_BEGIN_ALLOW_THREADS #define PySSL_BLOCK_THREADS @@ -36,37 +36,37 @@ #endif enum py_ssl_error { - /* these mirror ssl.h */ - PY_SSL_ERROR_NONE, - PY_SSL_ERROR_SSL, - PY_SSL_ERROR_WANT_READ, - PY_SSL_ERROR_WANT_WRITE, - PY_SSL_ERROR_WANT_X509_LOOKUP, - PY_SSL_ERROR_SYSCALL, /* look at error stack/return value/errno */ - PY_SSL_ERROR_ZERO_RETURN, - PY_SSL_ERROR_WANT_CONNECT, - /* start of non ssl.h errorcodes */ - PY_SSL_ERROR_EOF, /* special case of SSL_ERROR_SYSCALL */ - PY_SSL_ERROR_NO_SOCKET, /* socket has been GC'd */ - PY_SSL_ERROR_INVALID_ERROR_CODE + /* these mirror ssl.h */ + PY_SSL_ERROR_NONE, + PY_SSL_ERROR_SSL, + PY_SSL_ERROR_WANT_READ, + PY_SSL_ERROR_WANT_WRITE, + PY_SSL_ERROR_WANT_X509_LOOKUP, + PY_SSL_ERROR_SYSCALL, /* look at error stack/return value/errno */ + PY_SSL_ERROR_ZERO_RETURN, + PY_SSL_ERROR_WANT_CONNECT, + /* start of non ssl.h errorcodes */ + PY_SSL_ERROR_EOF, /* special case of SSL_ERROR_SYSCALL */ + PY_SSL_ERROR_NO_SOCKET, /* socket has been GC'd */ + PY_SSL_ERROR_INVALID_ERROR_CODE }; enum py_ssl_server_or_client { - PY_SSL_CLIENT, - PY_SSL_SERVER + PY_SSL_CLIENT, + PY_SSL_SERVER }; enum py_ssl_cert_requirements { - PY_SSL_CERT_NONE, - PY_SSL_CERT_OPTIONAL, - PY_SSL_CERT_REQUIRED + PY_SSL_CERT_NONE, + PY_SSL_CERT_OPTIONAL, + PY_SSL_CERT_REQUIRED }; enum py_ssl_version { - PY_SSL_VERSION_SSL2, - PY_SSL_VERSION_SSL3, - PY_SSL_VERSION_SSL23, - PY_SSL_VERSION_TLS1 + PY_SSL_VERSION_SSL2, + PY_SSL_VERSION_SSL3, + PY_SSL_VERSION_SSL23, + PY_SSL_VERSION_TLS1 }; /* Include symbols from _socket module */ @@ -114,12 +114,12 @@ #endif typedef struct { - PyObject_HEAD - PyObject *Socket; /* weakref to socket on which we're layered */ - SSL_CTX* ctx; - SSL* ssl; - X509* peer_cert; - int shutdown_seen_zero; + PyObject_HEAD + PyObject *Socket; /* weakref to socket on which we're layered */ + SSL_CTX* ctx; + SSL* ssl; + X509* peer_cert; + int shutdown_seen_zero; } PySSLObject; @@ -127,19 +127,19 @@ static PyObject *PySSL_SSLwrite(PySSLObject *self, PyObject *args); static PyObject *PySSL_SSLread(PySSLObject *self, PyObject *args); static int check_socket_and_wait_for_timeout(PySocketSockObject *s, - int writing); + int writing); static PyObject *PySSL_peercert(PySSLObject *self, PyObject *args); static PyObject *PySSL_cipher(PySSLObject *self); -#define PySSLObject_Check(v) (Py_TYPE(v) == &PySSL_Type) +#define PySSLObject_Check(v) (Py_TYPE(v) == &PySSL_Type) typedef enum { - SOCKET_IS_NONBLOCKING, - SOCKET_IS_BLOCKING, - SOCKET_HAS_TIMED_OUT, - SOCKET_HAS_BEEN_CLOSED, - SOCKET_TOO_LARGE_FOR_SELECT, - SOCKET_OPERATION_OK + SOCKET_IS_NONBLOCKING, + SOCKET_IS_BLOCKING, + SOCKET_HAS_TIMED_OUT, + SOCKET_HAS_BEEN_CLOSED, + SOCKET_TOO_LARGE_FOR_SELECT, + SOCKET_OPERATION_OK } timeout_state; /* Wrap error strings with filename and line # */ @@ -156,293 +156,293 @@ static PyObject * PySSL_SetError(PySSLObject *obj, int ret, char *filename, int lineno) { - PyObject *v; - char buf[2048]; - char *errstr; - int err; - enum py_ssl_error p = PY_SSL_ERROR_NONE; - - assert(ret <= 0); - - if (obj->ssl != NULL) { - err = SSL_get_error(obj->ssl, ret); - - switch (err) { - case SSL_ERROR_ZERO_RETURN: - errstr = "TLS/SSL connection has been closed"; - p = PY_SSL_ERROR_ZERO_RETURN; - break; - case SSL_ERROR_WANT_READ: - errstr = "The operation did not complete (read)"; - p = PY_SSL_ERROR_WANT_READ; - break; - case SSL_ERROR_WANT_WRITE: - p = PY_SSL_ERROR_WANT_WRITE; - errstr = "The operation did not complete (write)"; - break; - case SSL_ERROR_WANT_X509_LOOKUP: - p = PY_SSL_ERROR_WANT_X509_LOOKUP; - errstr = - "The operation did not complete (X509 lookup)"; - break; - case SSL_ERROR_WANT_CONNECT: - p = PY_SSL_ERROR_WANT_CONNECT; - errstr = "The operation did not complete (connect)"; - break; - case SSL_ERROR_SYSCALL: - { - unsigned long e = ERR_get_error(); - if (e == 0) { - PySocketSockObject *s - = (PySocketSockObject *) PyWeakref_GetObject(obj->Socket); - if (ret == 0 || (((PyObject *)s) == Py_None)) { - p = PY_SSL_ERROR_EOF; - errstr = - "EOF occurred in violation of protocol"; - } else if (ret == -1) { - /* underlying BIO reported an I/O error */ - return s->errorhandler(); - } else { /* possible? */ - p = PY_SSL_ERROR_SYSCALL; - errstr = "Some I/O error occurred"; - } - } else { - p = PY_SSL_ERROR_SYSCALL; - /* XXX Protected by global interpreter lock */ - errstr = ERR_error_string(e, NULL); - } - break; - } - case SSL_ERROR_SSL: - { - unsigned long e = ERR_get_error(); - p = PY_SSL_ERROR_SSL; - if (e != 0) - /* XXX Protected by global interpreter lock */ - errstr = ERR_error_string(e, NULL); - else { /* possible? */ - errstr = - "A failure in the SSL library occurred"; - } - break; - } - default: - p = PY_SSL_ERROR_INVALID_ERROR_CODE; - errstr = "Invalid error code"; - } - } else { - errstr = ERR_error_string(ERR_peek_last_error(), NULL); - } - PyOS_snprintf(buf, sizeof(buf), "_ssl.c:%d: %s", lineno, errstr); - v = Py_BuildValue("(is)", p, buf); - if (v != NULL) { - PyErr_SetObject(PySSLErrorObject, v); - Py_DECREF(v); - } - return NULL; + PyObject *v; + char buf[2048]; + char *errstr; + int err; + enum py_ssl_error p = PY_SSL_ERROR_NONE; + + assert(ret <= 0); + + if (obj->ssl != NULL) { + err = SSL_get_error(obj->ssl, ret); + + switch (err) { + case SSL_ERROR_ZERO_RETURN: + errstr = "TLS/SSL connection has been closed"; + p = PY_SSL_ERROR_ZERO_RETURN; + break; + case SSL_ERROR_WANT_READ: + errstr = "The operation did not complete (read)"; + p = PY_SSL_ERROR_WANT_READ; + break; + case SSL_ERROR_WANT_WRITE: + p = PY_SSL_ERROR_WANT_WRITE; + errstr = "The operation did not complete (write)"; + break; + case SSL_ERROR_WANT_X509_LOOKUP: + p = PY_SSL_ERROR_WANT_X509_LOOKUP; + errstr = + "The operation did not complete (X509 lookup)"; + break; + case SSL_ERROR_WANT_CONNECT: + p = PY_SSL_ERROR_WANT_CONNECT; + errstr = "The operation did not complete (connect)"; + break; + case SSL_ERROR_SYSCALL: + { + unsigned long e = ERR_get_error(); + if (e == 0) { + PySocketSockObject *s + = (PySocketSockObject *) PyWeakref_GetObject(obj->Socket); + if (ret == 0 || (((PyObject *)s) == Py_None)) { + p = PY_SSL_ERROR_EOF; + errstr = + "EOF occurred in violation of protocol"; + } else if (ret == -1) { + /* underlying BIO reported an I/O error */ + return s->errorhandler(); + } else { /* possible? */ + p = PY_SSL_ERROR_SYSCALL; + errstr = "Some I/O error occurred"; + } + } else { + p = PY_SSL_ERROR_SYSCALL; + /* XXX Protected by global interpreter lock */ + errstr = ERR_error_string(e, NULL); + } + break; + } + case SSL_ERROR_SSL: + { + unsigned long e = ERR_get_error(); + p = PY_SSL_ERROR_SSL; + if (e != 0) + /* XXX Protected by global interpreter lock */ + errstr = ERR_error_string(e, NULL); + else { /* possible? */ + errstr = + "A failure in the SSL library occurred"; + } + break; + } + default: + p = PY_SSL_ERROR_INVALID_ERROR_CODE; + errstr = "Invalid error code"; + } + } else { + errstr = ERR_error_string(ERR_peek_last_error(), NULL); + } + PyOS_snprintf(buf, sizeof(buf), "_ssl.c:%d: %s", lineno, errstr); + v = Py_BuildValue("(is)", p, buf); + if (v != NULL) { + PyErr_SetObject(PySSLErrorObject, v); + Py_DECREF(v); + } + return NULL; } static PyObject * _setSSLError (char *errstr, int errcode, char *filename, int lineno) { - char buf[2048]; - PyObject *v; + char buf[2048]; + PyObject *v; - if (errstr == NULL) { - errcode = ERR_peek_last_error(); - errstr = ERR_error_string(errcode, NULL); - } - PyOS_snprintf(buf, sizeof(buf), "_ssl.c:%d: %s", lineno, errstr); - v = Py_BuildValue("(is)", errcode, buf); - if (v != NULL) { - PyErr_SetObject(PySSLErrorObject, v); - Py_DECREF(v); - } - return NULL; + if (errstr == NULL) { + errcode = ERR_peek_last_error(); + errstr = ERR_error_string(errcode, NULL); + } + PyOS_snprintf(buf, sizeof(buf), "_ssl.c:%d: %s", lineno, errstr); + v = Py_BuildValue("(is)", errcode, buf); + if (v != NULL) { + PyErr_SetObject(PySSLErrorObject, v); + Py_DECREF(v); + } + return NULL; } static PySSLObject * newPySSLObject(PySocketSockObject *Sock, char *key_file, char *cert_file, - enum py_ssl_server_or_client socket_type, - enum py_ssl_cert_requirements certreq, - enum py_ssl_version proto_version, - char *cacerts_file, char *ciphers) + enum py_ssl_server_or_client socket_type, + enum py_ssl_cert_requirements certreq, + enum py_ssl_version proto_version, + char *cacerts_file, char *ciphers) { - PySSLObject *self; - char *errstr = NULL; - int ret; - int verification_mode; - - self = PyObject_New(PySSLObject, &PySSL_Type); /* Create new object */ - if (self == NULL) - return NULL; - self->peer_cert = NULL; - self->ssl = NULL; - self->ctx = NULL; - self->Socket = NULL; - - /* Make sure the SSL error state is initialized */ - (void) ERR_get_state(); - ERR_clear_error(); - - if ((key_file && !cert_file) || (!key_file && cert_file)) { - errstr = ERRSTR("Both the key & certificate files " - "must be specified"); - goto fail; - } - - if ((socket_type == PY_SSL_SERVER) && - ((key_file == NULL) || (cert_file == NULL))) { - errstr = ERRSTR("Both the key & certificate files " - "must be specified for server-side operation"); - goto fail; - } - - PySSL_BEGIN_ALLOW_THREADS - if (proto_version == PY_SSL_VERSION_TLS1) - self->ctx = SSL_CTX_new(TLSv1_method()); /* Set up context */ - else if (proto_version == PY_SSL_VERSION_SSL3) - self->ctx = SSL_CTX_new(SSLv3_method()); /* Set up context */ - else if (proto_version == PY_SSL_VERSION_SSL2) - self->ctx = SSL_CTX_new(SSLv2_method()); /* Set up context */ - else if (proto_version == PY_SSL_VERSION_SSL23) - self->ctx = SSL_CTX_new(SSLv23_method()); /* Set up context */ - PySSL_END_ALLOW_THREADS - - if (self->ctx == NULL) { - errstr = ERRSTR("Invalid SSL protocol variant specified."); - goto fail; - } - - if (ciphers != NULL) { - ret = SSL_CTX_set_cipher_list(self->ctx, ciphers); - if (ret == 0) { - errstr = ERRSTR("No cipher can be selected."); - goto fail; - } - } - - if (certreq != PY_SSL_CERT_NONE) { - if (cacerts_file == NULL) { - errstr = ERRSTR("No root certificates specified for " - "verification of other-side certificates."); - goto fail; - } else { - PySSL_BEGIN_ALLOW_THREADS - ret = SSL_CTX_load_verify_locations(self->ctx, - cacerts_file, - NULL); - PySSL_END_ALLOW_THREADS - if (ret != 1) { - _setSSLError(NULL, 0, __FILE__, __LINE__); - goto fail; - } - } - } - if (key_file) { - PySSL_BEGIN_ALLOW_THREADS - ret = SSL_CTX_use_PrivateKey_file(self->ctx, key_file, - SSL_FILETYPE_PEM); - PySSL_END_ALLOW_THREADS - if (ret != 1) { - _setSSLError(NULL, ret, __FILE__, __LINE__); - goto fail; - } - - PySSL_BEGIN_ALLOW_THREADS - ret = SSL_CTX_use_certificate_chain_file(self->ctx, - cert_file); - PySSL_END_ALLOW_THREADS - if (ret != 1) { - /* - fprintf(stderr, "ret is %d, errcode is %lu, %lu, with file \"%s\"\n", - ret, ERR_peek_error(), ERR_peek_last_error(), cert_file); - */ - if (ERR_peek_last_error() != 0) { - _setSSLError(NULL, ret, __FILE__, __LINE__); - goto fail; - } - } - } - - /* ssl compatibility */ - SSL_CTX_set_options(self->ctx, SSL_OP_ALL); - - verification_mode = SSL_VERIFY_NONE; - if (certreq == PY_SSL_CERT_OPTIONAL) - verification_mode = SSL_VERIFY_PEER; - else if (certreq == PY_SSL_CERT_REQUIRED) - verification_mode = (SSL_VERIFY_PEER | - SSL_VERIFY_FAIL_IF_NO_PEER_CERT); - SSL_CTX_set_verify(self->ctx, verification_mode, - NULL); /* set verify lvl */ - - PySSL_BEGIN_ALLOW_THREADS - self->ssl = SSL_new(self->ctx); /* New ssl struct */ - PySSL_END_ALLOW_THREADS - SSL_set_fd(self->ssl, Sock->sock_fd); /* Set the socket for SSL */ + PySSLObject *self; + char *errstr = NULL; + int ret; + int verification_mode; + + self = PyObject_New(PySSLObject, &PySSL_Type); /* Create new object */ + if (self == NULL) + return NULL; + self->peer_cert = NULL; + self->ssl = NULL; + self->ctx = NULL; + self->Socket = NULL; + + /* Make sure the SSL error state is initialized */ + (void) ERR_get_state(); + ERR_clear_error(); + + if ((key_file && !cert_file) || (!key_file && cert_file)) { + errstr = ERRSTR("Both the key & certificate files " + "must be specified"); + goto fail; + } + + if ((socket_type == PY_SSL_SERVER) && + ((key_file == NULL) || (cert_file == NULL))) { + errstr = ERRSTR("Both the key & certificate files " + "must be specified for server-side operation"); + goto fail; + } + + PySSL_BEGIN_ALLOW_THREADS + if (proto_version == PY_SSL_VERSION_TLS1) + self->ctx = SSL_CTX_new(TLSv1_method()); /* Set up context */ + else if (proto_version == PY_SSL_VERSION_SSL3) + self->ctx = SSL_CTX_new(SSLv3_method()); /* Set up context */ + else if (proto_version == PY_SSL_VERSION_SSL2) + self->ctx = SSL_CTX_new(SSLv2_method()); /* Set up context */ + else if (proto_version == PY_SSL_VERSION_SSL23) + self->ctx = SSL_CTX_new(SSLv23_method()); /* Set up context */ + PySSL_END_ALLOW_THREADS + + if (self->ctx == NULL) { + errstr = ERRSTR("Invalid SSL protocol variant specified."); + goto fail; + } + + if (ciphers != NULL) { + ret = SSL_CTX_set_cipher_list(self->ctx, ciphers); + if (ret == 0) { + errstr = ERRSTR("No cipher can be selected."); + goto fail; + } + } + + if (certreq != PY_SSL_CERT_NONE) { + if (cacerts_file == NULL) { + errstr = ERRSTR("No root certificates specified for " + "verification of other-side certificates."); + goto fail; + } else { + PySSL_BEGIN_ALLOW_THREADS + ret = SSL_CTX_load_verify_locations(self->ctx, + cacerts_file, + NULL); + PySSL_END_ALLOW_THREADS + if (ret != 1) { + _setSSLError(NULL, 0, __FILE__, __LINE__); + goto fail; + } + } + } + if (key_file) { + PySSL_BEGIN_ALLOW_THREADS + ret = SSL_CTX_use_PrivateKey_file(self->ctx, key_file, + SSL_FILETYPE_PEM); + PySSL_END_ALLOW_THREADS + if (ret != 1) { + _setSSLError(NULL, ret, __FILE__, __LINE__); + goto fail; + } + + PySSL_BEGIN_ALLOW_THREADS + ret = SSL_CTX_use_certificate_chain_file(self->ctx, + cert_file); + PySSL_END_ALLOW_THREADS + if (ret != 1) { + /* + fprintf(stderr, "ret is %d, errcode is %lu, %lu, with file \"%s\"\n", + ret, ERR_peek_error(), ERR_peek_last_error(), cert_file); + */ + if (ERR_peek_last_error() != 0) { + _setSSLError(NULL, ret, __FILE__, __LINE__); + goto fail; + } + } + } + + /* ssl compatibility */ + SSL_CTX_set_options(self->ctx, SSL_OP_ALL); + + verification_mode = SSL_VERIFY_NONE; + if (certreq == PY_SSL_CERT_OPTIONAL) + verification_mode = SSL_VERIFY_PEER; + else if (certreq == PY_SSL_CERT_REQUIRED) + verification_mode = (SSL_VERIFY_PEER | + SSL_VERIFY_FAIL_IF_NO_PEER_CERT); + SSL_CTX_set_verify(self->ctx, verification_mode, + NULL); /* set verify lvl */ + + PySSL_BEGIN_ALLOW_THREADS + self->ssl = SSL_new(self->ctx); /* New ssl struct */ + PySSL_END_ALLOW_THREADS + SSL_set_fd(self->ssl, Sock->sock_fd); /* Set the socket for SSL */ #ifdef SSL_MODE_AUTO_RETRY - SSL_set_mode(self->ssl, SSL_MODE_AUTO_RETRY); + SSL_set_mode(self->ssl, SSL_MODE_AUTO_RETRY); #endif - /* If the socket is in non-blocking mode or timeout mode, set the BIO - * to non-blocking mode (blocking is the default) - */ - if (Sock->sock_timeout >= 0.0) { - /* Set both the read and write BIO's to non-blocking mode */ - BIO_set_nbio(SSL_get_rbio(self->ssl), 1); - BIO_set_nbio(SSL_get_wbio(self->ssl), 1); - } - - PySSL_BEGIN_ALLOW_THREADS - if (socket_type == PY_SSL_CLIENT) - SSL_set_connect_state(self->ssl); - else - SSL_set_accept_state(self->ssl); - PySSL_END_ALLOW_THREADS + /* If the socket is in non-blocking mode or timeout mode, set the BIO + * to non-blocking mode (blocking is the default) + */ + if (Sock->sock_timeout >= 0.0) { + /* Set both the read and write BIO's to non-blocking mode */ + BIO_set_nbio(SSL_get_rbio(self->ssl), 1); + BIO_set_nbio(SSL_get_wbio(self->ssl), 1); + } + + PySSL_BEGIN_ALLOW_THREADS + if (socket_type == PY_SSL_CLIENT) + SSL_set_connect_state(self->ssl); + else + SSL_set_accept_state(self->ssl); + PySSL_END_ALLOW_THREADS - self->Socket = PyWeakref_NewRef((PyObject *) Sock, Py_None); - return self; + self->Socket = PyWeakref_NewRef((PyObject *) Sock, Py_None); + return self; fail: - if (errstr) - PyErr_SetString(PySSLErrorObject, errstr); - Py_DECREF(self); - return NULL; + if (errstr) + PyErr_SetString(PySSLErrorObject, errstr); + Py_DECREF(self); + return NULL; } static PyObject * PySSL_sslwrap(PyObject *self, PyObject *args) { - PySocketSockObject *Sock; - int server_side = 0; - int verification_mode = PY_SSL_CERT_NONE; - int protocol = PY_SSL_VERSION_SSL23; - char *key_file = NULL; - char *cert_file = NULL; - char *cacerts_file = NULL; - char *ciphers = NULL; - - if (!PyArg_ParseTuple(args, "O!i|zziizz:sslwrap", - PySocketModule.Sock_Type, - &Sock, - &server_side, - &key_file, &cert_file, - &verification_mode, &protocol, - &cacerts_file, &ciphers)) - return NULL; - - /* - fprintf(stderr, - "server_side is %d, keyfile %p, certfile %p, verify_mode %d, " - "protocol %d, certs %p\n", - server_side, key_file, cert_file, verification_mode, - protocol, cacerts_file); - */ - - return (PyObject *) newPySSLObject(Sock, key_file, cert_file, - server_side, verification_mode, - protocol, cacerts_file, - ciphers); + PySocketSockObject *Sock; + int server_side = 0; + int verification_mode = PY_SSL_CERT_NONE; + int protocol = PY_SSL_VERSION_SSL23; + char *key_file = NULL; + char *cert_file = NULL; + char *cacerts_file = NULL; + char *ciphers = NULL; + + if (!PyArg_ParseTuple(args, "O!i|zziizz:sslwrap", + PySocketModule.Sock_Type, + &Sock, + &server_side, + &key_file, &cert_file, + &verification_mode, &protocol, + &cacerts_file, &ciphers)) + return NULL; + + /* + fprintf(stderr, + "server_side is %d, keyfile %p, certfile %p, verify_mode %d, " + "protocol %d, certs %p\n", + server_side, key_file, cert_file, verification_mode, + protocol, cacerts_file); + */ + + return (PyObject *) newPySSLObject(Sock, key_file, cert_file, + server_side, verification_mode, + protocol, cacerts_file, + ciphers); } PyDoc_STRVAR(ssl_doc, @@ -453,580 +453,580 @@ static PyObject *PySSL_SSLdo_handshake(PySSLObject *self) { - int ret; - int err; - int sockstate, nonblocking; - PySocketSockObject *sock - = (PySocketSockObject *) PyWeakref_GetObject(self->Socket); - - if (((PyObject*)sock) == Py_None) { - _setSSLError("Underlying socket connection gone", - PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__); - return NULL; - } - - /* just in case the blocking state of the socket has been changed */ - nonblocking = (sock->sock_timeout >= 0.0); - BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking); - BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking); - - /* Actually negotiate SSL connection */ - /* XXX If SSL_do_handshake() returns 0, it's also a failure. */ - sockstate = 0; - do { - PySSL_BEGIN_ALLOW_THREADS - ret = SSL_do_handshake(self->ssl); - err = SSL_get_error(self->ssl, ret); - PySSL_END_ALLOW_THREADS - if(PyErr_CheckSignals()) { - return NULL; - } - if (err == SSL_ERROR_WANT_READ) { - sockstate = check_socket_and_wait_for_timeout(sock, 0); - } else if (err == SSL_ERROR_WANT_WRITE) { - sockstate = check_socket_and_wait_for_timeout(sock, 1); - } else { - sockstate = SOCKET_OPERATION_OK; - } - if (sockstate == SOCKET_HAS_TIMED_OUT) { - PyErr_SetString(PySSLErrorObject, - ERRSTR("The handshake operation timed out")); - return NULL; - } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) { - PyErr_SetString(PySSLErrorObject, - ERRSTR("Underlying socket has been closed.")); - return NULL; - } else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) { - PyErr_SetString(PySSLErrorObject, - ERRSTR("Underlying socket too large for select().")); - return NULL; - } else if (sockstate == SOCKET_IS_NONBLOCKING) { - break; - } - } while (err == SSL_ERROR_WANT_READ || err == SSL_ERROR_WANT_WRITE); - if (ret < 1) - return PySSL_SetError(self, ret, __FILE__, __LINE__); - self->ssl->debug = 1; + int ret; + int err; + int sockstate, nonblocking; + PySocketSockObject *sock + = (PySocketSockObject *) PyWeakref_GetObject(self->Socket); + + if (((PyObject*)sock) == Py_None) { + _setSSLError("Underlying socket connection gone", + PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__); + return NULL; + } - if (self->peer_cert) - X509_free (self->peer_cert); + /* just in case the blocking state of the socket has been changed */ + nonblocking = (sock->sock_timeout >= 0.0); + BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking); + BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking); + + /* Actually negotiate SSL connection */ + /* XXX If SSL_do_handshake() returns 0, it's also a failure. */ + sockstate = 0; + do { PySSL_BEGIN_ALLOW_THREADS - self->peer_cert = SSL_get_peer_certificate(self->ssl); - PySSL_END_ALLOW_THREADS + ret = SSL_do_handshake(self->ssl); + err = SSL_get_error(self->ssl, ret); + PySSL_END_ALLOW_THREADS + if(PyErr_CheckSignals()) { + return NULL; + } + if (err == SSL_ERROR_WANT_READ) { + sockstate = check_socket_and_wait_for_timeout(sock, 0); + } else if (err == SSL_ERROR_WANT_WRITE) { + sockstate = check_socket_and_wait_for_timeout(sock, 1); + } else { + sockstate = SOCKET_OPERATION_OK; + } + if (sockstate == SOCKET_HAS_TIMED_OUT) { + PyErr_SetString(PySSLErrorObject, + ERRSTR("The handshake operation timed out")); + return NULL; + } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) { + PyErr_SetString(PySSLErrorObject, + ERRSTR("Underlying socket has been closed.")); + return NULL; + } else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) { + PyErr_SetString(PySSLErrorObject, + ERRSTR("Underlying socket too large for select().")); + return NULL; + } else if (sockstate == SOCKET_IS_NONBLOCKING) { + break; + } + } while (err == SSL_ERROR_WANT_READ || err == SSL_ERROR_WANT_WRITE); + if (ret < 1) + return PySSL_SetError(self, ret, __FILE__, __LINE__); + self->ssl->debug = 1; + + if (self->peer_cert) + X509_free (self->peer_cert); + PySSL_BEGIN_ALLOW_THREADS + self->peer_cert = SSL_get_peer_certificate(self->ssl); + PySSL_END_ALLOW_THREADS - Py_INCREF(Py_None); - return Py_None; + Py_INCREF(Py_None); + return Py_None; } static PyObject * _create_tuple_for_attribute (ASN1_OBJECT *name, ASN1_STRING *value) { - char namebuf[X509_NAME_MAXLEN]; - int buflen; - PyObject *name_obj; - PyObject *value_obj; - PyObject *attr; - unsigned char *valuebuf = NULL; - - buflen = OBJ_obj2txt(namebuf, sizeof(namebuf), name, 0); - if (buflen < 0) { - _setSSLError(NULL, 0, __FILE__, __LINE__); - goto fail; - } - name_obj = PyUnicode_FromStringAndSize(namebuf, buflen); - if (name_obj == NULL) - goto fail; - - buflen = ASN1_STRING_to_UTF8(&valuebuf, value); - if (buflen < 0) { - _setSSLError(NULL, 0, __FILE__, __LINE__); - Py_DECREF(name_obj); - goto fail; - } - value_obj = PyUnicode_DecodeUTF8((char *) valuebuf, - buflen, "strict"); - OPENSSL_free(valuebuf); - if (value_obj == NULL) { - Py_DECREF(name_obj); - goto fail; - } - attr = PyTuple_New(2); - if (attr == NULL) { - Py_DECREF(name_obj); - Py_DECREF(value_obj); - goto fail; - } - PyTuple_SET_ITEM(attr, 0, name_obj); - PyTuple_SET_ITEM(attr, 1, value_obj); - return attr; + char namebuf[X509_NAME_MAXLEN]; + int buflen; + PyObject *name_obj; + PyObject *value_obj; + PyObject *attr; + unsigned char *valuebuf = NULL; + + buflen = OBJ_obj2txt(namebuf, sizeof(namebuf), name, 0); + if (buflen < 0) { + _setSSLError(NULL, 0, __FILE__, __LINE__); + goto fail; + } + name_obj = PyUnicode_FromStringAndSize(namebuf, buflen); + if (name_obj == NULL) + goto fail; + + buflen = ASN1_STRING_to_UTF8(&valuebuf, value); + if (buflen < 0) { + _setSSLError(NULL, 0, __FILE__, __LINE__); + Py_DECREF(name_obj); + goto fail; + } + value_obj = PyUnicode_DecodeUTF8((char *) valuebuf, + buflen, "strict"); + OPENSSL_free(valuebuf); + if (value_obj == NULL) { + Py_DECREF(name_obj); + goto fail; + } + attr = PyTuple_New(2); + if (attr == NULL) { + Py_DECREF(name_obj); + Py_DECREF(value_obj); + goto fail; + } + PyTuple_SET_ITEM(attr, 0, name_obj); + PyTuple_SET_ITEM(attr, 1, value_obj); + return attr; fail: - return NULL; + return NULL; } static PyObject * _create_tuple_for_X509_NAME (X509_NAME *xname) { - PyObject *dn = NULL; /* tuple which represents the "distinguished name" */ - PyObject *rdn = NULL; /* tuple to hold a "relative distinguished name" */ - PyObject *rdnt; - PyObject *attr = NULL; /* tuple to hold an attribute */ - int entry_count = X509_NAME_entry_count(xname); - X509_NAME_ENTRY *entry; - ASN1_OBJECT *name; - ASN1_STRING *value; - int index_counter; - int rdn_level = -1; - int retcode; - - dn = PyList_New(0); - if (dn == NULL) - return NULL; - /* now create another tuple to hold the top-level RDN */ - rdn = PyList_New(0); - if (rdn == NULL) - goto fail0; - - for (index_counter = 0; - index_counter < entry_count; - index_counter++) - { - entry = X509_NAME_get_entry(xname, index_counter); - - /* check to see if we've gotten to a new RDN */ - if (rdn_level >= 0) { - if (rdn_level != entry->set) { - /* yes, new RDN */ - /* add old RDN to DN */ - rdnt = PyList_AsTuple(rdn); - Py_DECREF(rdn); - if (rdnt == NULL) - goto fail0; - retcode = PyList_Append(dn, rdnt); - Py_DECREF(rdnt); - if (retcode < 0) - goto fail0; - /* create new RDN */ - rdn = PyList_New(0); - if (rdn == NULL) - goto fail0; - } - } - rdn_level = entry->set; - - /* now add this attribute to the current RDN */ - name = X509_NAME_ENTRY_get_object(entry); - value = X509_NAME_ENTRY_get_data(entry); - attr = _create_tuple_for_attribute(name, value); - /* - fprintf(stderr, "RDN level %d, attribute %s: %s\n", - entry->set, - PyBytes_AS_STRING(PyTuple_GET_ITEM(attr, 0)), - PyBytes_AS_STRING(PyTuple_GET_ITEM(attr, 1))); - */ - if (attr == NULL) - goto fail1; - retcode = PyList_Append(rdn, attr); - Py_DECREF(attr); - if (retcode < 0) - goto fail1; - } - /* now, there's typically a dangling RDN */ - if ((rdn != NULL) && (PyList_Size(rdn) > 0)) { - rdnt = PyList_AsTuple(rdn); - Py_DECREF(rdn); - if (rdnt == NULL) - goto fail0; - retcode = PyList_Append(dn, rdnt); - Py_DECREF(rdnt); - if (retcode < 0) - goto fail0; - } - - /* convert list to tuple */ - rdnt = PyList_AsTuple(dn); - Py_DECREF(dn); - if (rdnt == NULL) - return NULL; - return rdnt; + PyObject *dn = NULL; /* tuple which represents the "distinguished name" */ + PyObject *rdn = NULL; /* tuple to hold a "relative distinguished name" */ + PyObject *rdnt; + PyObject *attr = NULL; /* tuple to hold an attribute */ + int entry_count = X509_NAME_entry_count(xname); + X509_NAME_ENTRY *entry; + ASN1_OBJECT *name; + ASN1_STRING *value; + int index_counter; + int rdn_level = -1; + int retcode; + + dn = PyList_New(0); + if (dn == NULL) + return NULL; + /* now create another tuple to hold the top-level RDN */ + rdn = PyList_New(0); + if (rdn == NULL) + goto fail0; + + for (index_counter = 0; + index_counter < entry_count; + index_counter++) + { + entry = X509_NAME_get_entry(xname, index_counter); + + /* check to see if we've gotten to a new RDN */ + if (rdn_level >= 0) { + if (rdn_level != entry->set) { + /* yes, new RDN */ + /* add old RDN to DN */ + rdnt = PyList_AsTuple(rdn); + Py_DECREF(rdn); + if (rdnt == NULL) + goto fail0; + retcode = PyList_Append(dn, rdnt); + Py_DECREF(rdnt); + if (retcode < 0) + goto fail0; + /* create new RDN */ + rdn = PyList_New(0); + if (rdn == NULL) + goto fail0; + } + } + rdn_level = entry->set; + + /* now add this attribute to the current RDN */ + name = X509_NAME_ENTRY_get_object(entry); + value = X509_NAME_ENTRY_get_data(entry); + attr = _create_tuple_for_attribute(name, value); + /* + fprintf(stderr, "RDN level %d, attribute %s: %s\n", + entry->set, + PyBytes_AS_STRING(PyTuple_GET_ITEM(attr, 0)), + PyBytes_AS_STRING(PyTuple_GET_ITEM(attr, 1))); + */ + if (attr == NULL) + goto fail1; + retcode = PyList_Append(rdn, attr); + Py_DECREF(attr); + if (retcode < 0) + goto fail1; + } + /* now, there's typically a dangling RDN */ + if ((rdn != NULL) && (PyList_Size(rdn) > 0)) { + rdnt = PyList_AsTuple(rdn); + Py_DECREF(rdn); + if (rdnt == NULL) + goto fail0; + retcode = PyList_Append(dn, rdnt); + Py_DECREF(rdnt); + if (retcode < 0) + goto fail0; + } + + /* convert list to tuple */ + rdnt = PyList_AsTuple(dn); + Py_DECREF(dn); + if (rdnt == NULL) + return NULL; + return rdnt; fail1: - Py_XDECREF(rdn); + Py_XDECREF(rdn); fail0: - Py_XDECREF(dn); - return NULL; + Py_XDECREF(dn); + return NULL; } static PyObject * _get_peer_alt_names (X509 *certificate) { - /* this code follows the procedure outlined in - OpenSSL's crypto/x509v3/v3_prn.c:X509v3_EXT_print() - function to extract the STACK_OF(GENERAL_NAME), - then iterates through the stack to add the - names. */ - - int i, j; - PyObject *peer_alt_names = Py_None; - PyObject *v, *t; - X509_EXTENSION *ext = NULL; - GENERAL_NAMES *names = NULL; - GENERAL_NAME *name; - X509V3_EXT_METHOD *method; - BIO *biobuf = NULL; - char buf[2048]; - char *vptr; - int len; - /* Issue #2973: ASN1_item_d2i() API changed in OpenSSL 0.9.6m */ + /* this code follows the procedure outlined in + OpenSSL's crypto/x509v3/v3_prn.c:X509v3_EXT_print() + function to extract the STACK_OF(GENERAL_NAME), + then iterates through the stack to add the + names. */ + + int i, j; + PyObject *peer_alt_names = Py_None; + PyObject *v, *t; + X509_EXTENSION *ext = NULL; + GENERAL_NAMES *names = NULL; + GENERAL_NAME *name; + X509V3_EXT_METHOD *method; + BIO *biobuf = NULL; + char buf[2048]; + char *vptr; + int len; + /* Issue #2973: ASN1_item_d2i() API changed in OpenSSL 0.9.6m */ #if OPENSSL_VERSION_NUMBER >= 0x009060dfL - const unsigned char *p; + const unsigned char *p; #else - unsigned char *p; + unsigned char *p; #endif - if (certificate == NULL) - return peer_alt_names; + if (certificate == NULL) + return peer_alt_names; + + /* get a memory buffer */ + biobuf = BIO_new(BIO_s_mem()); - /* get a memory buffer */ - biobuf = BIO_new(BIO_s_mem()); + i = 0; + while ((i = X509_get_ext_by_NID( + certificate, NID_subject_alt_name, i)) >= 0) { + + if (peer_alt_names == Py_None) { + peer_alt_names = PyList_New(0); + if (peer_alt_names == NULL) + goto fail; + } + + /* now decode the altName */ + ext = X509_get_ext(certificate, i); + if(!(method = X509V3_EXT_get(ext))) { + PyErr_SetString + (PySSLErrorObject, + ERRSTR("No method for internalizing subjectAltName!")); + goto fail; + } - i = 0; - while ((i = X509_get_ext_by_NID( - certificate, NID_subject_alt_name, i)) >= 0) { - - if (peer_alt_names == Py_None) { - peer_alt_names = PyList_New(0); - if (peer_alt_names == NULL) - goto fail; - } - - /* now decode the altName */ - ext = X509_get_ext(certificate, i); - if(!(method = X509V3_EXT_get(ext))) { - PyErr_SetString - (PySSLErrorObject, - ERRSTR("No method for internalizing subjectAltName!")); - goto fail; - } - - p = ext->value->data; - if (method->it) - names = (GENERAL_NAMES*) - (ASN1_item_d2i(NULL, - &p, - ext->value->length, - ASN1_ITEM_ptr(method->it))); - else - names = (GENERAL_NAMES*) - (method->d2i(NULL, - &p, - ext->value->length)); - - for(j = 0; j < sk_GENERAL_NAME_num(names); j++) { - - /* get a rendering of each name in the set of names */ - - name = sk_GENERAL_NAME_value(names, j); - if (name->type == GEN_DIRNAME) { - - /* we special-case DirName as a tuple of - tuples of attributes */ - - t = PyTuple_New(2); - if (t == NULL) { - goto fail; - } - - v = PyUnicode_FromString("DirName"); - if (v == NULL) { - Py_DECREF(t); - goto fail; - } - PyTuple_SET_ITEM(t, 0, v); - - v = _create_tuple_for_X509_NAME (name->d.dirn); - if (v == NULL) { - Py_DECREF(t); - goto fail; - } - PyTuple_SET_ITEM(t, 1, v); - - } else { - - /* for everything else, we use the OpenSSL print form */ - - (void) BIO_reset(biobuf); - GENERAL_NAME_print(biobuf, name); - len = BIO_gets(biobuf, buf, sizeof(buf)-1); - if (len < 0) { - _setSSLError(NULL, 0, __FILE__, __LINE__); - goto fail; - } - vptr = strchr(buf, ':'); - if (vptr == NULL) - goto fail; - t = PyTuple_New(2); - if (t == NULL) - goto fail; - v = PyUnicode_FromStringAndSize(buf, (vptr - buf)); - if (v == NULL) { - Py_DECREF(t); - goto fail; - } - PyTuple_SET_ITEM(t, 0, v); - v = PyUnicode_FromStringAndSize((vptr + 1), - (len - (vptr - buf + 1))); - if (v == NULL) { - Py_DECREF(t); - goto fail; - } - PyTuple_SET_ITEM(t, 1, v); - } - - /* and add that rendering to the list */ - - if (PyList_Append(peer_alt_names, t) < 0) { - Py_DECREF(t); - goto fail; - } - Py_DECREF(t); - } - } - BIO_free(biobuf); - if (peer_alt_names != Py_None) { - v = PyList_AsTuple(peer_alt_names); - Py_DECREF(peer_alt_names); - return v; - } else { - return peer_alt_names; - } + p = ext->value->data; + if (method->it) + names = (GENERAL_NAMES*) + (ASN1_item_d2i(NULL, + &p, + ext->value->length, + ASN1_ITEM_ptr(method->it))); + else + names = (GENERAL_NAMES*) + (method->d2i(NULL, + &p, + ext->value->length)); + + for(j = 0; j < sk_GENERAL_NAME_num(names); j++) { + + /* get a rendering of each name in the set of names */ + + name = sk_GENERAL_NAME_value(names, j); + if (name->type == GEN_DIRNAME) { + + /* we special-case DirName as a tuple of + tuples of attributes */ + + t = PyTuple_New(2); + if (t == NULL) { + goto fail; + } + + v = PyUnicode_FromString("DirName"); + if (v == NULL) { + Py_DECREF(t); + goto fail; + } + PyTuple_SET_ITEM(t, 0, v); + + v = _create_tuple_for_X509_NAME (name->d.dirn); + if (v == NULL) { + Py_DECREF(t); + goto fail; + } + PyTuple_SET_ITEM(t, 1, v); + + } else { + + /* for everything else, we use the OpenSSL print form */ + + (void) BIO_reset(biobuf); + GENERAL_NAME_print(biobuf, name); + len = BIO_gets(biobuf, buf, sizeof(buf)-1); + if (len < 0) { + _setSSLError(NULL, 0, __FILE__, __LINE__); + goto fail; + } + vptr = strchr(buf, ':'); + if (vptr == NULL) + goto fail; + t = PyTuple_New(2); + if (t == NULL) + goto fail; + v = PyUnicode_FromStringAndSize(buf, (vptr - buf)); + if (v == NULL) { + Py_DECREF(t); + goto fail; + } + PyTuple_SET_ITEM(t, 0, v); + v = PyUnicode_FromStringAndSize((vptr + 1), + (len - (vptr - buf + 1))); + if (v == NULL) { + Py_DECREF(t); + goto fail; + } + PyTuple_SET_ITEM(t, 1, v); + } + + /* and add that rendering to the list */ + + if (PyList_Append(peer_alt_names, t) < 0) { + Py_DECREF(t); + goto fail; + } + Py_DECREF(t); + } + } + BIO_free(biobuf); + if (peer_alt_names != Py_None) { + v = PyList_AsTuple(peer_alt_names); + Py_DECREF(peer_alt_names); + return v; + } else { + return peer_alt_names; + } fail: - if (biobuf != NULL) - BIO_free(biobuf); + if (biobuf != NULL) + BIO_free(biobuf); - if (peer_alt_names != Py_None) { - Py_XDECREF(peer_alt_names); - } + if (peer_alt_names != Py_None) { + Py_XDECREF(peer_alt_names); + } - return NULL; + return NULL; } static PyObject * _decode_certificate (X509 *certificate, int verbose) { - PyObject *retval = NULL; - BIO *biobuf = NULL; - PyObject *peer; - PyObject *peer_alt_names = NULL; - PyObject *issuer; - PyObject *version; - PyObject *sn_obj; - ASN1_INTEGER *serialNumber; - char buf[2048]; - int len; - ASN1_TIME *notBefore, *notAfter; - PyObject *pnotBefore, *pnotAfter; - - retval = PyDict_New(); - if (retval == NULL) - return NULL; - - peer = _create_tuple_for_X509_NAME( - X509_get_subject_name(certificate)); - if (peer == NULL) - goto fail0; - if (PyDict_SetItemString(retval, (const char *) "subject", peer) < 0) { - Py_DECREF(peer); - goto fail0; - } - Py_DECREF(peer); - - if (verbose) { - issuer = _create_tuple_for_X509_NAME( - X509_get_issuer_name(certificate)); - if (issuer == NULL) - goto fail0; - if (PyDict_SetItemString(retval, (const char *)"issuer", issuer) < 0) { - Py_DECREF(issuer); - goto fail0; - } - Py_DECREF(issuer); - - version = PyLong_FromLong(X509_get_version(certificate) + 1); - if (PyDict_SetItemString(retval, "version", version) < 0) { - Py_DECREF(version); - goto fail0; - } - Py_DECREF(version); - } - - /* get a memory buffer */ - biobuf = BIO_new(BIO_s_mem()); - - if (verbose) { - - (void) BIO_reset(biobuf); - serialNumber = X509_get_serialNumber(certificate); - /* should not exceed 20 octets, 160 bits, so buf is big enough */ - i2a_ASN1_INTEGER(biobuf, serialNumber); - len = BIO_gets(biobuf, buf, sizeof(buf)-1); - if (len < 0) { - _setSSLError(NULL, 0, __FILE__, __LINE__); - goto fail1; - } - sn_obj = PyUnicode_FromStringAndSize(buf, len); - if (sn_obj == NULL) - goto fail1; - if (PyDict_SetItemString(retval, "serialNumber", sn_obj) < 0) { - Py_DECREF(sn_obj); - goto fail1; - } - Py_DECREF(sn_obj); - - (void) BIO_reset(biobuf); - notBefore = X509_get_notBefore(certificate); - ASN1_TIME_print(biobuf, notBefore); - len = BIO_gets(biobuf, buf, sizeof(buf)-1); - if (len < 0) { - _setSSLError(NULL, 0, __FILE__, __LINE__); - goto fail1; - } - pnotBefore = PyUnicode_FromStringAndSize(buf, len); - if (pnotBefore == NULL) - goto fail1; - if (PyDict_SetItemString(retval, "notBefore", pnotBefore) < 0) { - Py_DECREF(pnotBefore); - goto fail1; - } - Py_DECREF(pnotBefore); - } - - (void) BIO_reset(biobuf); - notAfter = X509_get_notAfter(certificate); - ASN1_TIME_print(biobuf, notAfter); - len = BIO_gets(biobuf, buf, sizeof(buf)-1); - if (len < 0) { - _setSSLError(NULL, 0, __FILE__, __LINE__); - goto fail1; - } - pnotAfter = PyUnicode_FromStringAndSize(buf, len); - if (pnotAfter == NULL) - goto fail1; - if (PyDict_SetItemString(retval, "notAfter", pnotAfter) < 0) { - Py_DECREF(pnotAfter); - goto fail1; - } - Py_DECREF(pnotAfter); - - /* Now look for subjectAltName */ - - peer_alt_names = _get_peer_alt_names(certificate); - if (peer_alt_names == NULL) - goto fail1; - else if (peer_alt_names != Py_None) { - if (PyDict_SetItemString(retval, "subjectAltName", - peer_alt_names) < 0) { - Py_DECREF(peer_alt_names); - goto fail1; - } - Py_DECREF(peer_alt_names); - } + PyObject *retval = NULL; + BIO *biobuf = NULL; + PyObject *peer; + PyObject *peer_alt_names = NULL; + PyObject *issuer; + PyObject *version; + PyObject *sn_obj; + ASN1_INTEGER *serialNumber; + char buf[2048]; + int len; + ASN1_TIME *notBefore, *notAfter; + PyObject *pnotBefore, *pnotAfter; + + retval = PyDict_New(); + if (retval == NULL) + return NULL; + + peer = _create_tuple_for_X509_NAME( + X509_get_subject_name(certificate)); + if (peer == NULL) + goto fail0; + if (PyDict_SetItemString(retval, (const char *) "subject", peer) < 0) { + Py_DECREF(peer); + goto fail0; + } + Py_DECREF(peer); + + if (verbose) { + issuer = _create_tuple_for_X509_NAME( + X509_get_issuer_name(certificate)); + if (issuer == NULL) + goto fail0; + if (PyDict_SetItemString(retval, (const char *)"issuer", issuer) < 0) { + Py_DECREF(issuer); + goto fail0; + } + Py_DECREF(issuer); + + version = PyLong_FromLong(X509_get_version(certificate) + 1); + if (PyDict_SetItemString(retval, "version", version) < 0) { + Py_DECREF(version); + goto fail0; + } + Py_DECREF(version); + } + + /* get a memory buffer */ + biobuf = BIO_new(BIO_s_mem()); + + if (verbose) { + + (void) BIO_reset(biobuf); + serialNumber = X509_get_serialNumber(certificate); + /* should not exceed 20 octets, 160 bits, so buf is big enough */ + i2a_ASN1_INTEGER(biobuf, serialNumber); + len = BIO_gets(biobuf, buf, sizeof(buf)-1); + if (len < 0) { + _setSSLError(NULL, 0, __FILE__, __LINE__); + goto fail1; + } + sn_obj = PyUnicode_FromStringAndSize(buf, len); + if (sn_obj == NULL) + goto fail1; + if (PyDict_SetItemString(retval, "serialNumber", sn_obj) < 0) { + Py_DECREF(sn_obj); + goto fail1; + } + Py_DECREF(sn_obj); + + (void) BIO_reset(biobuf); + notBefore = X509_get_notBefore(certificate); + ASN1_TIME_print(biobuf, notBefore); + len = BIO_gets(biobuf, buf, sizeof(buf)-1); + if (len < 0) { + _setSSLError(NULL, 0, __FILE__, __LINE__); + goto fail1; + } + pnotBefore = PyUnicode_FromStringAndSize(buf, len); + if (pnotBefore == NULL) + goto fail1; + if (PyDict_SetItemString(retval, "notBefore", pnotBefore) < 0) { + Py_DECREF(pnotBefore); + goto fail1; + } + Py_DECREF(pnotBefore); + } - BIO_free(biobuf); - return retval; + (void) BIO_reset(biobuf); + notAfter = X509_get_notAfter(certificate); + ASN1_TIME_print(biobuf, notAfter); + len = BIO_gets(biobuf, buf, sizeof(buf)-1); + if (len < 0) { + _setSSLError(NULL, 0, __FILE__, __LINE__); + goto fail1; + } + pnotAfter = PyUnicode_FromStringAndSize(buf, len); + if (pnotAfter == NULL) + goto fail1; + if (PyDict_SetItemString(retval, "notAfter", pnotAfter) < 0) { + Py_DECREF(pnotAfter); + goto fail1; + } + Py_DECREF(pnotAfter); + + /* Now look for subjectAltName */ + + peer_alt_names = _get_peer_alt_names(certificate); + if (peer_alt_names == NULL) + goto fail1; + else if (peer_alt_names != Py_None) { + if (PyDict_SetItemString(retval, "subjectAltName", + peer_alt_names) < 0) { + Py_DECREF(peer_alt_names); + goto fail1; + } + Py_DECREF(peer_alt_names); + } + + BIO_free(biobuf); + return retval; fail1: - if (biobuf != NULL) - BIO_free(biobuf); + if (biobuf != NULL) + BIO_free(biobuf); fail0: - Py_XDECREF(retval); - return NULL; + Py_XDECREF(retval); + return NULL; } static PyObject * PySSL_test_decode_certificate (PyObject *mod, PyObject *args) { - PyObject *retval = NULL; - char *filename = NULL; - X509 *x=NULL; - BIO *cert; - int verbose = 1; - - if (!PyArg_ParseTuple(args, "s|i:test_decode_certificate", - &filename, &verbose)) - return NULL; - - if ((cert=BIO_new(BIO_s_file())) == NULL) { - PyErr_SetString(PySSLErrorObject, - "Can't malloc memory to read file"); - goto fail0; - } - - if (BIO_read_filename(cert,filename) <= 0) { - PyErr_SetString(PySSLErrorObject, - "Can't open file"); - goto fail0; - } - - x = PEM_read_bio_X509_AUX(cert,NULL, NULL, NULL); - if (x == NULL) { - PyErr_SetString(PySSLErrorObject, - "Error decoding PEM-encoded file"); - goto fail0; - } + PyObject *retval = NULL; + char *filename = NULL; + X509 *x=NULL; + BIO *cert; + int verbose = 1; + + if (!PyArg_ParseTuple(args, "s|i:test_decode_certificate", + &filename, &verbose)) + return NULL; + + if ((cert=BIO_new(BIO_s_file())) == NULL) { + PyErr_SetString(PySSLErrorObject, + "Can't malloc memory to read file"); + goto fail0; + } + + if (BIO_read_filename(cert,filename) <= 0) { + PyErr_SetString(PySSLErrorObject, + "Can't open file"); + goto fail0; + } + + x = PEM_read_bio_X509_AUX(cert,NULL, NULL, NULL); + if (x == NULL) { + PyErr_SetString(PySSLErrorObject, + "Error decoding PEM-encoded file"); + goto fail0; + } - retval = _decode_certificate(x, verbose); + retval = _decode_certificate(x, verbose); fail0: - if (cert != NULL) BIO_free(cert); - return retval; + if (cert != NULL) BIO_free(cert); + return retval; } static PyObject * PySSL_peercert(PySSLObject *self, PyObject *args) { - PyObject *retval = NULL; - int len; - int verification; - PyObject *binary_mode = Py_None; - - if (!PyArg_ParseTuple(args, "|O:peer_certificate", &binary_mode)) - return NULL; - - if (!self->peer_cert) - Py_RETURN_NONE; - - if (PyObject_IsTrue(binary_mode)) { - /* return cert in DER-encoded format */ - - unsigned char *bytes_buf = NULL; - - bytes_buf = NULL; - len = i2d_X509(self->peer_cert, &bytes_buf); - if (len < 0) { - PySSL_SetError(self, len, __FILE__, __LINE__); - return NULL; - } - /* this is actually an immutable bytes sequence */ - retval = PyBytes_FromStringAndSize - ((const char *) bytes_buf, len); - OPENSSL_free(bytes_buf); - return retval; - - } else { - - verification = SSL_CTX_get_verify_mode(self->ctx); - if ((verification & SSL_VERIFY_PEER) == 0) - return PyDict_New(); - else - return _decode_certificate (self->peer_cert, 0); - } + PyObject *retval = NULL; + int len; + int verification; + PyObject *binary_mode = Py_None; + + if (!PyArg_ParseTuple(args, "|O:peer_certificate", &binary_mode)) + return NULL; + + if (!self->peer_cert) + Py_RETURN_NONE; + + if (PyObject_IsTrue(binary_mode)) { + /* return cert in DER-encoded format */ + + unsigned char *bytes_buf = NULL; + + bytes_buf = NULL; + len = i2d_X509(self->peer_cert, &bytes_buf); + if (len < 0) { + PySSL_SetError(self, len, __FILE__, __LINE__); + return NULL; + } + /* this is actually an immutable bytes sequence */ + retval = PyBytes_FromStringAndSize + ((const char *) bytes_buf, len); + OPENSSL_free(bytes_buf); + return retval; + + } else { + + verification = SSL_CTX_get_verify_mode(self->ctx); + if ((verification & SSL_VERIFY_PEER) == 0) + return PyDict_New(); + else + return _decode_certificate (self->peer_cert, 0); + } } PyDoc_STRVAR(PySSL_peercert_doc, @@ -1043,60 +1043,60 @@ static PyObject *PySSL_cipher (PySSLObject *self) { - PyObject *retval, *v; - SSL_CIPHER *current; - char *cipher_name; - char *cipher_protocol; - - if (self->ssl == NULL) - return Py_None; - current = SSL_get_current_cipher(self->ssl); - if (current == NULL) - return Py_None; - - retval = PyTuple_New(3); - if (retval == NULL) - return NULL; - - cipher_name = (char *) SSL_CIPHER_get_name(current); - if (cipher_name == NULL) { - PyTuple_SET_ITEM(retval, 0, Py_None); - } else { - v = PyUnicode_FromString(cipher_name); - if (v == NULL) - goto fail0; - PyTuple_SET_ITEM(retval, 0, v); - } - cipher_protocol = SSL_CIPHER_get_version(current); - if (cipher_protocol == NULL) { - PyTuple_SET_ITEM(retval, 1, Py_None); - } else { - v = PyUnicode_FromString(cipher_protocol); - if (v == NULL) - goto fail0; - PyTuple_SET_ITEM(retval, 1, v); - } - v = PyLong_FromLong(SSL_CIPHER_get_bits(current, NULL)); - if (v == NULL) - goto fail0; - PyTuple_SET_ITEM(retval, 2, v); - return retval; + PyObject *retval, *v; + SSL_CIPHER *current; + char *cipher_name; + char *cipher_protocol; + + if (self->ssl == NULL) + return Py_None; + current = SSL_get_current_cipher(self->ssl); + if (current == NULL) + return Py_None; + + retval = PyTuple_New(3); + if (retval == NULL) + return NULL; + + cipher_name = (char *) SSL_CIPHER_get_name(current); + if (cipher_name == NULL) { + PyTuple_SET_ITEM(retval, 0, Py_None); + } else { + v = PyUnicode_FromString(cipher_name); + if (v == NULL) + goto fail0; + PyTuple_SET_ITEM(retval, 0, v); + } + cipher_protocol = SSL_CIPHER_get_version(current); + if (cipher_protocol == NULL) { + PyTuple_SET_ITEM(retval, 1, Py_None); + } else { + v = PyUnicode_FromString(cipher_protocol); + if (v == NULL) + goto fail0; + PyTuple_SET_ITEM(retval, 1, v); + } + v = PyLong_FromLong(SSL_CIPHER_get_bits(current, NULL)); + if (v == NULL) + goto fail0; + PyTuple_SET_ITEM(retval, 2, v); + return retval; fail0: - Py_DECREF(retval); - return NULL; + Py_DECREF(retval); + return NULL; } static void PySSL_dealloc(PySSLObject *self) { - if (self->peer_cert) /* Possible not to have one? */ - X509_free (self->peer_cert); - if (self->ssl) - SSL_free(self->ssl); - if (self->ctx) - SSL_CTX_free(self->ctx); - Py_XDECREF(self->Socket); - PyObject_Del(self); + if (self->peer_cert) /* Possible not to have one? */ + X509_free (self->peer_cert); + if (self->ssl) + SSL_free(self->ssl); + if (self->ctx) + SSL_CTX_free(self->ctx); + Py_XDECREF(self->Socket); + PyObject_Del(self); } /* If the socket has a timeout, do a select()/poll() on the socket. @@ -1107,146 +1107,146 @@ static int check_socket_and_wait_for_timeout(PySocketSockObject *s, int writing) { - fd_set fds; - struct timeval tv; - int rc; - - /* Nothing to do unless we're in timeout mode (not non-blocking) */ - if (s->sock_timeout < 0.0) - return SOCKET_IS_BLOCKING; - else if (s->sock_timeout == 0.0) - return SOCKET_IS_NONBLOCKING; - - /* Guard against closed socket */ - if (s->sock_fd < 0) - return SOCKET_HAS_BEEN_CLOSED; + fd_set fds; + struct timeval tv; + int rc; + + /* Nothing to do unless we're in timeout mode (not non-blocking) */ + if (s->sock_timeout < 0.0) + return SOCKET_IS_BLOCKING; + else if (s->sock_timeout == 0.0) + return SOCKET_IS_NONBLOCKING; + + /* Guard against closed socket */ + if (s->sock_fd < 0) + return SOCKET_HAS_BEEN_CLOSED; - /* Prefer poll, if available, since you can poll() any fd - * which can't be done with select(). */ + /* Prefer poll, if available, since you can poll() any fd + * which can't be done with select(). */ #ifdef HAVE_POLL - { - struct pollfd pollfd; - int timeout; - - pollfd.fd = s->sock_fd; - pollfd.events = writing ? POLLOUT : POLLIN; - - /* s->sock_timeout is in seconds, timeout in ms */ - timeout = (int)(s->sock_timeout * 1000 + 0.5); - PySSL_BEGIN_ALLOW_THREADS - rc = poll(&pollfd, 1, timeout); - PySSL_END_ALLOW_THREADS + { + struct pollfd pollfd; + int timeout; + + pollfd.fd = s->sock_fd; + pollfd.events = writing ? POLLOUT : POLLIN; - goto normal_return; - } + /* s->sock_timeout is in seconds, timeout in ms */ + timeout = (int)(s->sock_timeout * 1000 + 0.5); + PySSL_BEGIN_ALLOW_THREADS + rc = poll(&pollfd, 1, timeout); + PySSL_END_ALLOW_THREADS + + goto normal_return; + } #endif - /* Guard against socket too large for select*/ + /* Guard against socket too large for select*/ #ifndef Py_SOCKET_FD_CAN_BE_GE_FD_SETSIZE - if (s->sock_fd >= FD_SETSIZE) - return SOCKET_TOO_LARGE_FOR_SELECT; + if (s->sock_fd >= FD_SETSIZE) + return SOCKET_TOO_LARGE_FOR_SELECT; #endif - /* Construct the arguments to select */ - tv.tv_sec = (int)s->sock_timeout; - tv.tv_usec = (int)((s->sock_timeout - tv.tv_sec) * 1e6); - FD_ZERO(&fds); - FD_SET(s->sock_fd, &fds); - - /* See if the socket is ready */ - PySSL_BEGIN_ALLOW_THREADS - if (writing) - rc = select(s->sock_fd+1, NULL, &fds, NULL, &tv); - else - rc = select(s->sock_fd+1, &fds, NULL, NULL, &tv); - PySSL_END_ALLOW_THREADS + /* Construct the arguments to select */ + tv.tv_sec = (int)s->sock_timeout; + tv.tv_usec = (int)((s->sock_timeout - tv.tv_sec) * 1e6); + FD_ZERO(&fds); + FD_SET(s->sock_fd, &fds); + + /* See if the socket is ready */ + PySSL_BEGIN_ALLOW_THREADS + if (writing) + rc = select(s->sock_fd+1, NULL, &fds, NULL, &tv); + else + rc = select(s->sock_fd+1, &fds, NULL, NULL, &tv); + PySSL_END_ALLOW_THREADS #ifdef HAVE_POLL normal_return: #endif - /* Return SOCKET_TIMED_OUT on timeout, SOCKET_OPERATION_OK otherwise - (when we are able to write or when there's something to read) */ - return rc == 0 ? SOCKET_HAS_TIMED_OUT : SOCKET_OPERATION_OK; + /* Return SOCKET_TIMED_OUT on timeout, SOCKET_OPERATION_OK otherwise + (when we are able to write or when there's something to read) */ + return rc == 0 ? SOCKET_HAS_TIMED_OUT : SOCKET_OPERATION_OK; } static PyObject *PySSL_SSLwrite(PySSLObject *self, PyObject *args) { - Py_buffer buf; - int len; - int sockstate; - int err; - int nonblocking; - PySocketSockObject *sock - = (PySocketSockObject *) PyWeakref_GetObject(self->Socket); - - if (((PyObject*)sock) == Py_None) { - _setSSLError("Underlying socket connection gone", - PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__); - return NULL; - } - - if (!PyArg_ParseTuple(args, "y*:write", &buf)) - return NULL; - - /* just in case the blocking state of the socket has been changed */ - nonblocking = (sock->sock_timeout >= 0.0); - BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking); - BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking); - - sockstate = check_socket_and_wait_for_timeout(sock, 1); - if (sockstate == SOCKET_HAS_TIMED_OUT) { - PyErr_SetString(PySSLErrorObject, - "The write operation timed out"); - goto error; - } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) { - PyErr_SetString(PySSLErrorObject, - "Underlying socket has been closed."); - goto error; - } else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) { - PyErr_SetString(PySSLErrorObject, - "Underlying socket too large for select()."); - goto error; - } - do { - err = 0; - PySSL_BEGIN_ALLOW_THREADS - len = SSL_write(self->ssl, buf.buf, buf.len); - err = SSL_get_error(self->ssl, len); - PySSL_END_ALLOW_THREADS - if (PyErr_CheckSignals()) { - goto error; - } - if (err == SSL_ERROR_WANT_READ) { - sockstate = - check_socket_and_wait_for_timeout(sock, 0); - } else if (err == SSL_ERROR_WANT_WRITE) { - sockstate = - check_socket_and_wait_for_timeout(sock, 1); - } else { - sockstate = SOCKET_OPERATION_OK; - } - if (sockstate == SOCKET_HAS_TIMED_OUT) { - PyErr_SetString(PySSLErrorObject, - "The write operation timed out"); - goto error; - } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) { - PyErr_SetString(PySSLErrorObject, - "Underlying socket has been closed."); - goto error; - } else if (sockstate == SOCKET_IS_NONBLOCKING) { - break; - } - } while (err == SSL_ERROR_WANT_READ || err == SSL_ERROR_WANT_WRITE); - - PyBuffer_Release(&buf); - if (len > 0) - return PyLong_FromLong(len); - else - return PySSL_SetError(self, len, __FILE__, __LINE__); + Py_buffer buf; + int len; + int sockstate; + int err; + int nonblocking; + PySocketSockObject *sock + = (PySocketSockObject *) PyWeakref_GetObject(self->Socket); + + if (((PyObject*)sock) == Py_None) { + _setSSLError("Underlying socket connection gone", + PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__); + return NULL; + } + + if (!PyArg_ParseTuple(args, "y*:write", &buf)) + return NULL; + + /* just in case the blocking state of the socket has been changed */ + nonblocking = (sock->sock_timeout >= 0.0); + BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking); + BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking); + + sockstate = check_socket_and_wait_for_timeout(sock, 1); + if (sockstate == SOCKET_HAS_TIMED_OUT) { + PyErr_SetString(PySSLErrorObject, + "The write operation timed out"); + goto error; + } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) { + PyErr_SetString(PySSLErrorObject, + "Underlying socket has been closed."); + goto error; + } else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) { + PyErr_SetString(PySSLErrorObject, + "Underlying socket too large for select()."); + goto error; + } + do { + err = 0; + PySSL_BEGIN_ALLOW_THREADS + len = SSL_write(self->ssl, buf.buf, buf.len); + err = SSL_get_error(self->ssl, len); + PySSL_END_ALLOW_THREADS + if (PyErr_CheckSignals()) { + goto error; + } + if (err == SSL_ERROR_WANT_READ) { + sockstate = + check_socket_and_wait_for_timeout(sock, 0); + } else if (err == SSL_ERROR_WANT_WRITE) { + sockstate = + check_socket_and_wait_for_timeout(sock, 1); + } else { + sockstate = SOCKET_OPERATION_OK; + } + if (sockstate == SOCKET_HAS_TIMED_OUT) { + PyErr_SetString(PySSLErrorObject, + "The write operation timed out"); + goto error; + } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) { + PyErr_SetString(PySSLErrorObject, + "Underlying socket has been closed."); + goto error; + } else if (sockstate == SOCKET_IS_NONBLOCKING) { + break; + } + } while (err == SSL_ERROR_WANT_READ || err == SSL_ERROR_WANT_WRITE); + + PyBuffer_Release(&buf); + if (len > 0) + return PyLong_FromLong(len); + else + return PySSL_SetError(self, len, __FILE__, __LINE__); error: - PyBuffer_Release(&buf); - return NULL; + PyBuffer_Release(&buf); + return NULL; } PyDoc_STRVAR(PySSL_SSLwrite_doc, @@ -1257,15 +1257,15 @@ static PyObject *PySSL_SSLpending(PySSLObject *self) { - int count = 0; + int count = 0; - PySSL_BEGIN_ALLOW_THREADS - count = SSL_pending(self->ssl); - PySSL_END_ALLOW_THREADS - if (count < 0) - return PySSL_SetError(self, count, __FILE__, __LINE__); - else - return PyLong_FromLong(count); + PySSL_BEGIN_ALLOW_THREADS + count = SSL_pending(self->ssl); + PySSL_END_ALLOW_THREADS + if (count < 0) + return PySSL_SetError(self, count, __FILE__, __LINE__); + else + return PyLong_FromLong(count); } PyDoc_STRVAR(PySSL_SSLpending_doc, @@ -1276,122 +1276,122 @@ static PyObject *PySSL_SSLread(PySSLObject *self, PyObject *args) { - PyObject *dest = NULL; - Py_buffer buf; - int buf_passed = 0; - int count = -1; - char *mem; - /* XXX this should use Py_ssize_t */ - int len = 1024; - int sockstate; - int err; - int nonblocking; - PySocketSockObject *sock - = (PySocketSockObject *) PyWeakref_GetObject(self->Socket); - - if (((PyObject*)sock) == Py_None) { - _setSSLError("Underlying socket connection gone", - PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__); - return NULL; - } - - if (!PyArg_ParseTuple(args, "|Oi:read", &dest, &count)) - return NULL; - if ((dest == NULL) || (dest == Py_None)) { - if (!(dest = PyByteArray_FromStringAndSize((char *) 0, len))) - return NULL; - mem = PyByteArray_AS_STRING(dest); - } else if (PyLong_Check(dest)) { - len = PyLong_AS_LONG(dest); - if (!(dest = PyByteArray_FromStringAndSize((char *) 0, len))) - return NULL; - mem = PyByteArray_AS_STRING(dest); - } else { - if (PyObject_GetBuffer(dest, &buf, PyBUF_CONTIG) < 0) - return NULL; - mem = buf.buf; - len = buf.len; - if ((count > 0) && (count <= len)) - len = count; - buf_passed = 1; - } - - /* just in case the blocking state of the socket has been changed */ - nonblocking = (sock->sock_timeout >= 0.0); - BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking); - BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking); - - /* first check if there are bytes ready to be read */ - PySSL_BEGIN_ALLOW_THREADS - count = SSL_pending(self->ssl); - PySSL_END_ALLOW_THREADS - - if (!count) { - sockstate = check_socket_and_wait_for_timeout(sock, 0); - if (sockstate == SOCKET_HAS_TIMED_OUT) { - PyErr_SetString(PySSLErrorObject, - "The read operation timed out"); - goto error; - } else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) { - PyErr_SetString(PySSLErrorObject, - "Underlying socket too large for select()."); - goto error; - } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) { - count = 0; - goto done; - } - } - do { - err = 0; - PySSL_BEGIN_ALLOW_THREADS - count = SSL_read(self->ssl, mem, len); - err = SSL_get_error(self->ssl, count); - PySSL_END_ALLOW_THREADS - if (PyErr_CheckSignals()) - goto error; - if (err == SSL_ERROR_WANT_READ) { - sockstate = - check_socket_and_wait_for_timeout(sock, 0); - } else if (err == SSL_ERROR_WANT_WRITE) { - sockstate = - check_socket_and_wait_for_timeout(sock, 1); - } else if ((err == SSL_ERROR_ZERO_RETURN) && - (SSL_get_shutdown(self->ssl) == - SSL_RECEIVED_SHUTDOWN)) - { - count = 0; - goto done; - } else { - sockstate = SOCKET_OPERATION_OK; - } - if (sockstate == SOCKET_HAS_TIMED_OUT) { - PyErr_SetString(PySSLErrorObject, - "The read operation timed out"); - goto error; - } else if (sockstate == SOCKET_IS_NONBLOCKING) { - break; - } - } while (err == SSL_ERROR_WANT_READ || err == SSL_ERROR_WANT_WRITE); - if (count <= 0) { - PySSL_SetError(self, count, __FILE__, __LINE__); - goto error; - } + PyObject *dest = NULL; + Py_buffer buf; + int buf_passed = 0; + int count = -1; + char *mem; + /* XXX this should use Py_ssize_t */ + int len = 1024; + int sockstate; + int err; + int nonblocking; + PySocketSockObject *sock + = (PySocketSockObject *) PyWeakref_GetObject(self->Socket); + + if (((PyObject*)sock) == Py_None) { + _setSSLError("Underlying socket connection gone", + PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__); + return NULL; + } + + if (!PyArg_ParseTuple(args, "|Oi:read", &dest, &count)) + return NULL; + if ((dest == NULL) || (dest == Py_None)) { + if (!(dest = PyByteArray_FromStringAndSize((char *) 0, len))) + return NULL; + mem = PyByteArray_AS_STRING(dest); + } else if (PyLong_Check(dest)) { + len = PyLong_AS_LONG(dest); + if (!(dest = PyByteArray_FromStringAndSize((char *) 0, len))) + return NULL; + mem = PyByteArray_AS_STRING(dest); + } else { + if (PyObject_GetBuffer(dest, &buf, PyBUF_CONTIG) < 0) + return NULL; + mem = buf.buf; + len = buf.len; + if ((count > 0) && (count <= len)) + len = count; + buf_passed = 1; + } + + /* just in case the blocking state of the socket has been changed */ + nonblocking = (sock->sock_timeout >= 0.0); + BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking); + BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking); + + /* first check if there are bytes ready to be read */ + PySSL_BEGIN_ALLOW_THREADS + count = SSL_pending(self->ssl); + PySSL_END_ALLOW_THREADS + + if (!count) { + sockstate = check_socket_and_wait_for_timeout(sock, 0); + if (sockstate == SOCKET_HAS_TIMED_OUT) { + PyErr_SetString(PySSLErrorObject, + "The read operation timed out"); + goto error; + } else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) { + PyErr_SetString(PySSLErrorObject, + "Underlying socket too large for select()."); + goto error; + } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) { + count = 0; + goto done; + } + } + do { + err = 0; + PySSL_BEGIN_ALLOW_THREADS + count = SSL_read(self->ssl, mem, len); + err = SSL_get_error(self->ssl, count); + PySSL_END_ALLOW_THREADS + if (PyErr_CheckSignals()) + goto error; + if (err == SSL_ERROR_WANT_READ) { + sockstate = + check_socket_and_wait_for_timeout(sock, 0); + } else if (err == SSL_ERROR_WANT_WRITE) { + sockstate = + check_socket_and_wait_for_timeout(sock, 1); + } else if ((err == SSL_ERROR_ZERO_RETURN) && + (SSL_get_shutdown(self->ssl) == + SSL_RECEIVED_SHUTDOWN)) + { + count = 0; + goto done; + } else { + sockstate = SOCKET_OPERATION_OK; + } + if (sockstate == SOCKET_HAS_TIMED_OUT) { + PyErr_SetString(PySSLErrorObject, + "The read operation timed out"); + goto error; + } else if (sockstate == SOCKET_IS_NONBLOCKING) { + break; + } + } while (err == SSL_ERROR_WANT_READ || err == SSL_ERROR_WANT_WRITE); + if (count <= 0) { + PySSL_SetError(self, count, __FILE__, __LINE__); + goto error; + } done: - if (!buf_passed) { - PyObject *res = PyBytes_FromStringAndSize(mem, count); - Py_DECREF(dest); - return res; - } else { - PyBuffer_Release(&buf); - return PyLong_FromLong(count); - } + if (!buf_passed) { + PyObject *res = PyBytes_FromStringAndSize(mem, count); + Py_DECREF(dest); + return res; + } else { + PyBuffer_Release(&buf); + return PyLong_FromLong(count); + } error: - if (!buf_passed) { - Py_DECREF(dest); - } else { - PyBuffer_Release(&buf); - } - return NULL; + if (!buf_passed) { + Py_DECREF(dest); + } else { + PyBuffer_Release(&buf); + } + return NULL; } PyDoc_STRVAR(PySSL_SSLread_doc, @@ -1401,84 +1401,84 @@ static PyObject *PySSL_SSLshutdown(PySSLObject *self) { - int err, ssl_err, sockstate, nonblocking; - int zeros = 0; - PySocketSockObject *sock - = (PySocketSockObject *) PyWeakref_GetObject(self->Socket); - - /* Guard against closed socket */ - if ((((PyObject*)sock) == Py_None) || (sock->sock_fd < 0)) { - _setSSLError("Underlying socket connection gone", - PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__); - return NULL; - } - - /* Just in case the blocking state of the socket has been changed */ - nonblocking = (sock->sock_timeout >= 0.0); - BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking); - BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking); - - while (1) { - PySSL_BEGIN_ALLOW_THREADS - /* Disable read-ahead so that unwrap can work correctly. - * Otherwise OpenSSL might read in too much data, - * eating clear text data that happens to be - * transmitted after the SSL shutdown. - * Should be safe to call repeatedly everytime this - * function is used and the shutdown_seen_zero != 0 - * condition is met. - */ - if (self->shutdown_seen_zero) - SSL_set_read_ahead(self->ssl, 0); - err = SSL_shutdown(self->ssl); - PySSL_END_ALLOW_THREADS - /* If err == 1, a secure shutdown with SSL_shutdown() is complete */ - if (err > 0) - break; - if (err == 0) { - /* Don't loop endlessly; instead preserve legacy - behaviour of trying SSL_shutdown() only twice. - This looks necessary for OpenSSL < 0.9.8m */ - if (++zeros > 1) - break; - /* Shutdown was sent, now try receiving */ - self->shutdown_seen_zero = 1; - continue; - } - - /* Possibly retry shutdown until timeout or failure */ - ssl_err = SSL_get_error(self->ssl, err); - if (ssl_err == SSL_ERROR_WANT_READ) - sockstate = check_socket_and_wait_for_timeout(sock, 0); - else if (ssl_err == SSL_ERROR_WANT_WRITE) - sockstate = check_socket_and_wait_for_timeout(sock, 1); - else - break; - if (sockstate == SOCKET_HAS_TIMED_OUT) { - if (ssl_err == SSL_ERROR_WANT_READ) - PyErr_SetString(PySSLErrorObject, - "The read operation timed out"); - else - PyErr_SetString(PySSLErrorObject, - "The write operation timed out"); - return NULL; - } - else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) { - PyErr_SetString(PySSLErrorObject, - "Underlying socket too large for select()."); - return NULL; - } - else if (sockstate != SOCKET_OPERATION_OK) - /* Retain the SSL error code */ - break; - } - - if (err < 0) - return PySSL_SetError(self, err, __FILE__, __LINE__); - else { - Py_INCREF(sock); - return (PyObject *) sock; - } + int err, ssl_err, sockstate, nonblocking; + int zeros = 0; + PySocketSockObject *sock + = (PySocketSockObject *) PyWeakref_GetObject(self->Socket); + + /* Guard against closed socket */ + if ((((PyObject*)sock) == Py_None) || (sock->sock_fd < 0)) { + _setSSLError("Underlying socket connection gone", + PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__); + return NULL; + } + + /* Just in case the blocking state of the socket has been changed */ + nonblocking = (sock->sock_timeout >= 0.0); + BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking); + BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking); + + while (1) { + PySSL_BEGIN_ALLOW_THREADS + /* Disable read-ahead so that unwrap can work correctly. + * Otherwise OpenSSL might read in too much data, + * eating clear text data that happens to be + * transmitted after the SSL shutdown. + * Should be safe to call repeatedly everytime this + * function is used and the shutdown_seen_zero != 0 + * condition is met. + */ + if (self->shutdown_seen_zero) + SSL_set_read_ahead(self->ssl, 0); + err = SSL_shutdown(self->ssl); + PySSL_END_ALLOW_THREADS + /* If err == 1, a secure shutdown with SSL_shutdown() is complete */ + if (err > 0) + break; + if (err == 0) { + /* Don't loop endlessly; instead preserve legacy + behaviour of trying SSL_shutdown() only twice. + This looks necessary for OpenSSL < 0.9.8m */ + if (++zeros > 1) + break; + /* Shutdown was sent, now try receiving */ + self->shutdown_seen_zero = 1; + continue; + } + + /* Possibly retry shutdown until timeout or failure */ + ssl_err = SSL_get_error(self->ssl, err); + if (ssl_err == SSL_ERROR_WANT_READ) + sockstate = check_socket_and_wait_for_timeout(sock, 0); + else if (ssl_err == SSL_ERROR_WANT_WRITE) + sockstate = check_socket_and_wait_for_timeout(sock, 1); + else + break; + if (sockstate == SOCKET_HAS_TIMED_OUT) { + if (ssl_err == SSL_ERROR_WANT_READ) + PyErr_SetString(PySSLErrorObject, + "The read operation timed out"); + else + PyErr_SetString(PySSLErrorObject, + "The write operation timed out"); + return NULL; + } + else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) { + PyErr_SetString(PySSLErrorObject, + "Underlying socket too large for select()."); + return NULL; + } + else if (sockstate != SOCKET_OPERATION_OK) + /* Retain the SSL error code */ + break; + } + + if (err < 0) + return PySSL_SetError(self, err, __FILE__, __LINE__); + else { + Py_INCREF(sock); + return (PyObject *) sock; + } } PyDoc_STRVAR(PySSL_SSLshutdown_doc, @@ -1489,51 +1489,51 @@ static PyMethodDef PySSLMethods[] = { - {"do_handshake", (PyCFunction)PySSL_SSLdo_handshake, METH_NOARGS}, - {"write", (PyCFunction)PySSL_SSLwrite, METH_VARARGS, - PySSL_SSLwrite_doc}, - {"read", (PyCFunction)PySSL_SSLread, METH_VARARGS, - PySSL_SSLread_doc}, - {"pending", (PyCFunction)PySSL_SSLpending, METH_NOARGS, - PySSL_SSLpending_doc}, - {"peer_certificate", (PyCFunction)PySSL_peercert, METH_VARARGS, - PySSL_peercert_doc}, - {"cipher", (PyCFunction)PySSL_cipher, METH_NOARGS}, - {"shutdown", (PyCFunction)PySSL_SSLshutdown, METH_NOARGS, - PySSL_SSLshutdown_doc}, - {NULL, NULL} + {"do_handshake", (PyCFunction)PySSL_SSLdo_handshake, METH_NOARGS}, + {"write", (PyCFunction)PySSL_SSLwrite, METH_VARARGS, + PySSL_SSLwrite_doc}, + {"read", (PyCFunction)PySSL_SSLread, METH_VARARGS, + PySSL_SSLread_doc}, + {"pending", (PyCFunction)PySSL_SSLpending, METH_NOARGS, + PySSL_SSLpending_doc}, + {"peer_certificate", (PyCFunction)PySSL_peercert, METH_VARARGS, + PySSL_peercert_doc}, + {"cipher", (PyCFunction)PySSL_cipher, METH_NOARGS}, + {"shutdown", (PyCFunction)PySSL_SSLshutdown, METH_NOARGS, + PySSL_SSLshutdown_doc}, + {NULL, NULL} }; static PyTypeObject PySSL_Type = { - PyVarObject_HEAD_INIT(NULL, 0) - "ssl.SSLContext", /*tp_name*/ - sizeof(PySSLObject), /*tp_basicsize*/ - 0, /*tp_itemsize*/ - /* methods */ - (destructor)PySSL_dealloc, /*tp_dealloc*/ - 0, /*tp_print*/ - 0, /*tp_getattr*/ - 0, /*tp_setattr*/ - 0, /*tp_reserved*/ - 0, /*tp_repr*/ - 0, /*tp_as_number*/ - 0, /*tp_as_sequence*/ - 0, /*tp_as_mapping*/ - 0, /*tp_hash*/ - 0, /*tp_call*/ - 0, /*tp_str*/ - 0, /*tp_getattro*/ - 0, /*tp_setattro*/ - 0, /*tp_as_buffer*/ - Py_TPFLAGS_DEFAULT, /*tp_flags*/ - 0, /*tp_doc*/ - 0, /*tp_traverse*/ - 0, /*tp_clear*/ - 0, /*tp_richcompare*/ - 0, /*tp_weaklistoffset*/ - 0, /*tp_iter*/ - 0, /*tp_iternext*/ - PySSLMethods, /*tp_methods*/ + PyVarObject_HEAD_INIT(NULL, 0) + "ssl.SSLContext", /*tp_name*/ + sizeof(PySSLObject), /*tp_basicsize*/ + 0, /*tp_itemsize*/ + /* methods */ + (destructor)PySSL_dealloc, /*tp_dealloc*/ + 0, /*tp_print*/ + 0, /*tp_getattr*/ + 0, /*tp_setattr*/ + 0, /*tp_reserved*/ + 0, /*tp_repr*/ + 0, /*tp_as_number*/ + 0, /*tp_as_sequence*/ + 0, /*tp_as_mapping*/ + 0, /*tp_hash*/ + 0, /*tp_call*/ + 0, /*tp_str*/ + 0, /*tp_getattro*/ + 0, /*tp_setattro*/ + 0, /*tp_as_buffer*/ + Py_TPFLAGS_DEFAULT, /*tp_flags*/ + 0, /*tp_doc*/ + 0, /*tp_traverse*/ + 0, /*tp_clear*/ + 0, /*tp_richcompare*/ + 0, /*tp_weaklistoffset*/ + 0, /*tp_iter*/ + 0, /*tp_iternext*/ + PySSLMethods, /*tp_methods*/ }; #ifdef HAVE_OPENSSL_RAND @@ -1547,7 +1547,7 @@ double entropy; if (!PyArg_ParseTuple(args, "s#d:RAND_add", &buf, &len, &entropy)) - return NULL; + return NULL; RAND_add(buf, len, entropy); Py_INCREF(Py_None); return Py_None; @@ -1578,15 +1578,15 @@ int bytes; if (!PyUnicode_Check(arg)) - return PyErr_Format(PyExc_TypeError, - "RAND_egd() expected string, found %s", - Py_TYPE(arg)->tp_name); + return PyErr_Format(PyExc_TypeError, + "RAND_egd() expected string, found %s", + Py_TYPE(arg)->tp_name); bytes = RAND_egd(_PyUnicode_AsString(arg)); if (bytes == -1) { - PyErr_SetString(PySSLErrorObject, - "EGD connection failed or EGD did not return " - "enough data to seed the PRNG"); - return NULL; + PyErr_SetString(PySSLErrorObject, + "EGD connection failed or EGD did not return " + "enough data to seed the PRNG"); + return NULL; } return PyLong_FromLong(bytes); } @@ -1605,19 +1605,19 @@ /* List of functions exported by this module. */ static PyMethodDef PySSL_methods[] = { - {"sslwrap", PySSL_sslwrap, - METH_VARARGS, ssl_doc}, - {"_test_decode_cert", PySSL_test_decode_certificate, - METH_VARARGS}, + {"sslwrap", PySSL_sslwrap, + METH_VARARGS, ssl_doc}, + {"_test_decode_cert", PySSL_test_decode_certificate, + METH_VARARGS}, #ifdef HAVE_OPENSSL_RAND - {"RAND_add", PySSL_RAND_add, METH_VARARGS, - PySSL_RAND_add_doc}, - {"RAND_egd", PySSL_RAND_egd, METH_O, - PySSL_RAND_egd_doc}, - {"RAND_status", (PyCFunction)PySSL_RAND_status, METH_NOARGS, - PySSL_RAND_status_doc}, + {"RAND_add", PySSL_RAND_add, METH_VARARGS, + PySSL_RAND_add_doc}, + {"RAND_egd", PySSL_RAND_egd, METH_O, + PySSL_RAND_egd_doc}, + {"RAND_status", (PyCFunction)PySSL_RAND_status, METH_NOARGS, + PySSL_RAND_status_doc}, #endif - {NULL, NULL} /* Sentinel */ + {NULL, NULL} /* Sentinel */ }; @@ -1629,66 +1629,66 @@ static PyThread_type_lock *_ssl_locks = NULL; static unsigned long _ssl_thread_id_function (void) { - return PyThread_get_thread_ident(); + return PyThread_get_thread_ident(); } static void _ssl_thread_locking_function - (int mode, int n, const char *file, int line) { - /* this function is needed to perform locking on shared data - structures. (Note that OpenSSL uses a number of global data - structures that will be implicitly shared whenever multiple - threads use OpenSSL.) Multi-threaded applications will - crash at random if it is not set. - - locking_function() must be able to handle up to - CRYPTO_num_locks() different mutex locks. It sets the n-th - lock if mode & CRYPTO_LOCK, and releases it otherwise. - - file and line are the file number of the function setting the - lock. They can be useful for debugging. - */ - - if ((_ssl_locks == NULL) || - (n < 0) || ((unsigned)n >= _ssl_locks_count)) - return; - - if (mode & CRYPTO_LOCK) { - PyThread_acquire_lock(_ssl_locks[n], 1); - } else { - PyThread_release_lock(_ssl_locks[n]); - } + (int mode, int n, const char *file, int line) { + /* this function is needed to perform locking on shared data + structures. (Note that OpenSSL uses a number of global data + structures that will be implicitly shared whenever multiple + threads use OpenSSL.) Multi-threaded applications will + crash at random if it is not set. + + locking_function() must be able to handle up to + CRYPTO_num_locks() different mutex locks. It sets the n-th + lock if mode & CRYPTO_LOCK, and releases it otherwise. + + file and line are the file number of the function setting the + lock. They can be useful for debugging. + */ + + if ((_ssl_locks == NULL) || + (n < 0) || ((unsigned)n >= _ssl_locks_count)) + return; + + if (mode & CRYPTO_LOCK) { + PyThread_acquire_lock(_ssl_locks[n], 1); + } else { + PyThread_release_lock(_ssl_locks[n]); + } } static int _setup_ssl_threads(void) { - unsigned int i; + unsigned int i; - if (_ssl_locks == NULL) { - _ssl_locks_count = CRYPTO_num_locks(); - _ssl_locks = (PyThread_type_lock *) - malloc(sizeof(PyThread_type_lock) * _ssl_locks_count); - if (_ssl_locks == NULL) - return 0; - memset(_ssl_locks, 0, - sizeof(PyThread_type_lock) * _ssl_locks_count); - for (i = 0; i < _ssl_locks_count; i++) { - _ssl_locks[i] = PyThread_allocate_lock(); - if (_ssl_locks[i] == NULL) { - unsigned int j; - for (j = 0; j < i; j++) { - PyThread_free_lock(_ssl_locks[j]); - } - free(_ssl_locks); - return 0; - } - } - CRYPTO_set_locking_callback(_ssl_thread_locking_function); - CRYPTO_set_id_callback(_ssl_thread_id_function); - } - return 1; + if (_ssl_locks == NULL) { + _ssl_locks_count = CRYPTO_num_locks(); + _ssl_locks = (PyThread_type_lock *) + malloc(sizeof(PyThread_type_lock) * _ssl_locks_count); + if (_ssl_locks == NULL) + return 0; + memset(_ssl_locks, 0, + sizeof(PyThread_type_lock) * _ssl_locks_count); + for (i = 0; i < _ssl_locks_count; i++) { + _ssl_locks[i] = PyThread_allocate_lock(); + if (_ssl_locks[i] == NULL) { + unsigned int j; + for (j = 0; j < i; j++) { + PyThread_free_lock(_ssl_locks[j]); + } + free(_ssl_locks); + return 0; + } + } + CRYPTO_set_locking_callback(_ssl_thread_locking_function); + CRYPTO_set_id_callback(_ssl_thread_id_function); + } + return 1; } -#endif /* def HAVE_THREAD */ +#endif /* def HAVE_THREAD */ PyDoc_STRVAR(module_doc, "Implementation module for SSL socket operations. See the socket module\n\ @@ -1696,123 +1696,123 @@ static struct PyModuleDef _sslmodule = { - PyModuleDef_HEAD_INIT, - "_ssl", - module_doc, - -1, - PySSL_methods, - NULL, - NULL, - NULL, - NULL + PyModuleDef_HEAD_INIT, + "_ssl", + module_doc, + -1, + PySSL_methods, + NULL, + NULL, + NULL, + NULL }; PyMODINIT_FUNC PyInit__ssl(void) { - PyObject *m, *d, *r; - unsigned long libver; - unsigned int major, minor, fix, patch, status; - PySocketModule_APIObject *socket_api; - - if (PyType_Ready(&PySSL_Type) < 0) - return NULL; - - m = PyModule_Create(&_sslmodule); - if (m == NULL) - return NULL; - d = PyModule_GetDict(m); - - /* Load _socket module and its C API */ - socket_api = PySocketModule_ImportModuleAndAPI(); - if (!socket_api) - return NULL; - PySocketModule = *socket_api; - - /* Init OpenSSL */ - SSL_load_error_strings(); - SSL_library_init(); + PyObject *m, *d, *r; + unsigned long libver; + unsigned int major, minor, fix, patch, status; + PySocketModule_APIObject *socket_api; + + if (PyType_Ready(&PySSL_Type) < 0) + return NULL; + + m = PyModule_Create(&_sslmodule); + if (m == NULL) + return NULL; + d = PyModule_GetDict(m); + + /* Load _socket module and its C API */ + socket_api = PySocketModule_ImportModuleAndAPI(); + if (!socket_api) + return NULL; + PySocketModule = *socket_api; + + /* Init OpenSSL */ + SSL_load_error_strings(); + SSL_library_init(); #ifdef WITH_THREAD - /* note that this will start threading if not already started */ - if (!_setup_ssl_threads()) { - return NULL; - } + /* note that this will start threading if not already started */ + if (!_setup_ssl_threads()) { + return NULL; + } #endif - OpenSSL_add_all_algorithms(); + OpenSSL_add_all_algorithms(); - /* Add symbols to module dict */ - PySSLErrorObject = PyErr_NewException("ssl.SSLError", - PySocketModule.error, - NULL); - if (PySSLErrorObject == NULL) - return NULL; - if (PyDict_SetItemString(d, "SSLError", PySSLErrorObject) != 0) - return NULL; - if (PyDict_SetItemString(d, "SSLType", - (PyObject *)&PySSL_Type) != 0) - return NULL; - PyModule_AddIntConstant(m, "SSL_ERROR_ZERO_RETURN", - PY_SSL_ERROR_ZERO_RETURN); - PyModule_AddIntConstant(m, "SSL_ERROR_WANT_READ", - PY_SSL_ERROR_WANT_READ); - PyModule_AddIntConstant(m, "SSL_ERROR_WANT_WRITE", - PY_SSL_ERROR_WANT_WRITE); - PyModule_AddIntConstant(m, "SSL_ERROR_WANT_X509_LOOKUP", - PY_SSL_ERROR_WANT_X509_LOOKUP); - PyModule_AddIntConstant(m, "SSL_ERROR_SYSCALL", - PY_SSL_ERROR_SYSCALL); - PyModule_AddIntConstant(m, "SSL_ERROR_SSL", - PY_SSL_ERROR_SSL); - PyModule_AddIntConstant(m, "SSL_ERROR_WANT_CONNECT", - PY_SSL_ERROR_WANT_CONNECT); - /* non ssl.h errorcodes */ - PyModule_AddIntConstant(m, "SSL_ERROR_EOF", - PY_SSL_ERROR_EOF); - PyModule_AddIntConstant(m, "SSL_ERROR_INVALID_ERROR_CODE", - PY_SSL_ERROR_INVALID_ERROR_CODE); - /* cert requirements */ - PyModule_AddIntConstant(m, "CERT_NONE", - PY_SSL_CERT_NONE); - PyModule_AddIntConstant(m, "CERT_OPTIONAL", - PY_SSL_CERT_OPTIONAL); - PyModule_AddIntConstant(m, "CERT_REQUIRED", - PY_SSL_CERT_REQUIRED); - - /* protocol versions */ - PyModule_AddIntConstant(m, "PROTOCOL_SSLv2", - PY_SSL_VERSION_SSL2); - PyModule_AddIntConstant(m, "PROTOCOL_SSLv3", - PY_SSL_VERSION_SSL3); - PyModule_AddIntConstant(m, "PROTOCOL_SSLv23", - PY_SSL_VERSION_SSL23); - PyModule_AddIntConstant(m, "PROTOCOL_TLSv1", - PY_SSL_VERSION_TLS1); - - /* OpenSSL version */ - /* SSLeay() gives us the version of the library linked against, - which could be different from the headers version. - */ - libver = SSLeay(); - r = PyLong_FromUnsignedLong(libver); - if (r == NULL) - return NULL; - if (PyModule_AddObject(m, "OPENSSL_VERSION_NUMBER", r)) - return NULL; - status = libver & 0xF; - libver >>= 4; - patch = libver & 0xFF; - libver >>= 8; - fix = libver & 0xFF; - libver >>= 8; - minor = libver & 0xFF; - libver >>= 8; - major = libver & 0xFF; - r = Py_BuildValue("IIIII", major, minor, fix, patch, status); - if (r == NULL || PyModule_AddObject(m, "OPENSSL_VERSION_INFO", r)) - return NULL; - r = PyUnicode_FromString(SSLeay_version(SSLEAY_VERSION)); - if (r == NULL || PyModule_AddObject(m, "OPENSSL_VERSION", r)) - return NULL; + /* Add symbols to module dict */ + PySSLErrorObject = PyErr_NewException("ssl.SSLError", + PySocketModule.error, + NULL); + if (PySSLErrorObject == NULL) + return NULL; + if (PyDict_SetItemString(d, "SSLError", PySSLErrorObject) != 0) + return NULL; + if (PyDict_SetItemString(d, "SSLType", + (PyObject *)&PySSL_Type) != 0) + return NULL; + PyModule_AddIntConstant(m, "SSL_ERROR_ZERO_RETURN", + PY_SSL_ERROR_ZERO_RETURN); + PyModule_AddIntConstant(m, "SSL_ERROR_WANT_READ", + PY_SSL_ERROR_WANT_READ); + PyModule_AddIntConstant(m, "SSL_ERROR_WANT_WRITE", + PY_SSL_ERROR_WANT_WRITE); + PyModule_AddIntConstant(m, "SSL_ERROR_WANT_X509_LOOKUP", + PY_SSL_ERROR_WANT_X509_LOOKUP); + PyModule_AddIntConstant(m, "SSL_ERROR_SYSCALL", + PY_SSL_ERROR_SYSCALL); + PyModule_AddIntConstant(m, "SSL_ERROR_SSL", + PY_SSL_ERROR_SSL); + PyModule_AddIntConstant(m, "SSL_ERROR_WANT_CONNECT", + PY_SSL_ERROR_WANT_CONNECT); + /* non ssl.h errorcodes */ + PyModule_AddIntConstant(m, "SSL_ERROR_EOF", + PY_SSL_ERROR_EOF); + PyModule_AddIntConstant(m, "SSL_ERROR_INVALID_ERROR_CODE", + PY_SSL_ERROR_INVALID_ERROR_CODE); + /* cert requirements */ + PyModule_AddIntConstant(m, "CERT_NONE", + PY_SSL_CERT_NONE); + PyModule_AddIntConstant(m, "CERT_OPTIONAL", + PY_SSL_CERT_OPTIONAL); + PyModule_AddIntConstant(m, "CERT_REQUIRED", + PY_SSL_CERT_REQUIRED); + + /* protocol versions */ + PyModule_AddIntConstant(m, "PROTOCOL_SSLv2", + PY_SSL_VERSION_SSL2); + PyModule_AddIntConstant(m, "PROTOCOL_SSLv3", + PY_SSL_VERSION_SSL3); + PyModule_AddIntConstant(m, "PROTOCOL_SSLv23", + PY_SSL_VERSION_SSL23); + PyModule_AddIntConstant(m, "PROTOCOL_TLSv1", + PY_SSL_VERSION_TLS1); + + /* OpenSSL version */ + /* SSLeay() gives us the version of the library linked against, + which could be different from the headers version. + */ + libver = SSLeay(); + r = PyLong_FromUnsignedLong(libver); + if (r == NULL) + return NULL; + if (PyModule_AddObject(m, "OPENSSL_VERSION_NUMBER", r)) + return NULL; + status = libver & 0xF; + libver >>= 4; + patch = libver & 0xFF; + libver >>= 8; + fix = libver & 0xFF; + libver >>= 8; + minor = libver & 0xFF; + libver >>= 8; + major = libver & 0xFF; + r = Py_BuildValue("IIIII", major, minor, fix, patch, status); + if (r == NULL || PyModule_AddObject(m, "OPENSSL_VERSION_INFO", r)) + return NULL; + r = PyUnicode_FromString(SSLeay_version(SSLEAY_VERSION)); + if (r == NULL || PyModule_AddObject(m, "OPENSSL_VERSION", r)) + return NULL; - return m; + return m; } From python-checkins at python.org Wed May 5 17:59:19 2010 From: python-checkins at python.org (antoine.pitrou) Date: Wed, 5 May 2010 17:59:19 +0200 (CEST) Subject: [Python-checkins] r80791 - in python/branches/release26-maint: Modules/_ssl.c Message-ID: <20100505155919.DF491EE9AA@mail.python.org> Author: antoine.pitrou Date: Wed May 5 17:59:19 2010 New Revision: 80791 Log: Merged revisions 80789 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r80789 | antoine.pitrou | 2010-05-05 17:53:45 +0200 (mer., 05 mai 2010) | 3 lines Untabify Modules/_ssl.c ........ Modified: python/branches/release26-maint/ (props changed) python/branches/release26-maint/Modules/_ssl.c Modified: python/branches/release26-maint/Modules/_ssl.c ============================================================================== --- python/branches/release26-maint/Modules/_ssl.c (original) +++ python/branches/release26-maint/Modules/_ssl.c Wed May 5 17:59:19 2010 @@ -19,14 +19,14 @@ #ifdef WITH_THREAD #include "pythread.h" #define PySSL_BEGIN_ALLOW_THREADS { \ - PyThreadState *_save = NULL; \ - if (_ssl_locks_count>0) {_save = PyEval_SaveThread();} -#define PySSL_BLOCK_THREADS if (_ssl_locks_count>0){PyEval_RestoreThread(_save)}; -#define PySSL_UNBLOCK_THREADS if (_ssl_locks_count>0){_save = PyEval_SaveThread()}; -#define PySSL_END_ALLOW_THREADS if (_ssl_locks_count>0){PyEval_RestoreThread(_save);} \ - } + PyThreadState *_save = NULL; \ + if (_ssl_locks_count>0) {_save = PyEval_SaveThread();} +#define PySSL_BLOCK_THREADS if (_ssl_locks_count>0){PyEval_RestoreThread(_save)}; +#define PySSL_UNBLOCK_THREADS if (_ssl_locks_count>0){_save = PyEval_SaveThread()}; +#define PySSL_END_ALLOW_THREADS if (_ssl_locks_count>0){PyEval_RestoreThread(_save);} \ + } -#else /* no WITH_THREAD */ +#else /* no WITH_THREAD */ #define PySSL_BEGIN_ALLOW_THREADS #define PySSL_BLOCK_THREADS @@ -36,36 +36,36 @@ #endif enum py_ssl_error { - /* these mirror ssl.h */ - PY_SSL_ERROR_NONE, - PY_SSL_ERROR_SSL, - PY_SSL_ERROR_WANT_READ, - PY_SSL_ERROR_WANT_WRITE, - PY_SSL_ERROR_WANT_X509_LOOKUP, - PY_SSL_ERROR_SYSCALL, /* look at error stack/return value/errno */ - PY_SSL_ERROR_ZERO_RETURN, - PY_SSL_ERROR_WANT_CONNECT, - /* start of non ssl.h errorcodes */ - PY_SSL_ERROR_EOF, /* special case of SSL_ERROR_SYSCALL */ - PY_SSL_ERROR_INVALID_ERROR_CODE + /* these mirror ssl.h */ + PY_SSL_ERROR_NONE, + PY_SSL_ERROR_SSL, + PY_SSL_ERROR_WANT_READ, + PY_SSL_ERROR_WANT_WRITE, + PY_SSL_ERROR_WANT_X509_LOOKUP, + PY_SSL_ERROR_SYSCALL, /* look at error stack/return value/errno */ + PY_SSL_ERROR_ZERO_RETURN, + PY_SSL_ERROR_WANT_CONNECT, + /* start of non ssl.h errorcodes */ + PY_SSL_ERROR_EOF, /* special case of SSL_ERROR_SYSCALL */ + PY_SSL_ERROR_INVALID_ERROR_CODE }; enum py_ssl_server_or_client { - PY_SSL_CLIENT, - PY_SSL_SERVER + PY_SSL_CLIENT, + PY_SSL_SERVER }; enum py_ssl_cert_requirements { - PY_SSL_CERT_NONE, - PY_SSL_CERT_OPTIONAL, - PY_SSL_CERT_REQUIRED + PY_SSL_CERT_NONE, + PY_SSL_CERT_OPTIONAL, + PY_SSL_CERT_REQUIRED }; enum py_ssl_version { - PY_SSL_VERSION_SSL2, - PY_SSL_VERSION_SSL3, - PY_SSL_VERSION_SSL23, - PY_SSL_VERSION_TLS1 + PY_SSL_VERSION_SSL2, + PY_SSL_VERSION_SSL3, + PY_SSL_VERSION_SSL23, + PY_SSL_VERSION_TLS1 }; /* Include symbols from _socket module */ @@ -111,14 +111,14 @@ #endif typedef struct { - PyObject_HEAD - PySocketSockObject *Socket; /* Socket on which we're layered */ - SSL_CTX* ctx; - SSL* ssl; - X509* peer_cert; - char server[X509_NAME_MAXLEN]; - char issuer[X509_NAME_MAXLEN]; - int shutdown_seen_zero; + PyObject_HEAD + PySocketSockObject *Socket; /* Socket on which we're layered */ + SSL_CTX* ctx; + SSL* ssl; + X509* peer_cert; + char server[X509_NAME_MAXLEN]; + char issuer[X509_NAME_MAXLEN]; + int shutdown_seen_zero; } PySSLObject; @@ -126,19 +126,19 @@ static PyObject *PySSL_SSLwrite(PySSLObject *self, PyObject *args); static PyObject *PySSL_SSLread(PySSLObject *self, PyObject *args); static int check_socket_and_wait_for_timeout(PySocketSockObject *s, - int writing); + int writing); static PyObject *PySSL_peercert(PySSLObject *self, PyObject *args); static PyObject *PySSL_cipher(PySSLObject *self); -#define PySSLObject_Check(v) (Py_TYPE(v) == &PySSL_Type) +#define PySSLObject_Check(v) (Py_TYPE(v) == &PySSL_Type) typedef enum { - SOCKET_IS_NONBLOCKING, - SOCKET_IS_BLOCKING, - SOCKET_HAS_TIMED_OUT, - SOCKET_HAS_BEEN_CLOSED, - SOCKET_TOO_LARGE_FOR_SELECT, - SOCKET_OPERATION_OK + SOCKET_IS_NONBLOCKING, + SOCKET_IS_BLOCKING, + SOCKET_HAS_TIMED_OUT, + SOCKET_HAS_BEEN_CLOSED, + SOCKET_TOO_LARGE_FOR_SELECT, + SOCKET_OPERATION_OK } timeout_state; /* Wrap error strings with filename and line # */ @@ -155,284 +155,284 @@ static PyObject * PySSL_SetError(PySSLObject *obj, int ret, char *filename, int lineno) { - PyObject *v; - char buf[2048]; - char *errstr; - int err; - enum py_ssl_error p = PY_SSL_ERROR_NONE; - - assert(ret <= 0); - - if (obj->ssl != NULL) { - err = SSL_get_error(obj->ssl, ret); - - switch (err) { - case SSL_ERROR_ZERO_RETURN: - errstr = "TLS/SSL connection has been closed"; - p = PY_SSL_ERROR_ZERO_RETURN; - break; - case SSL_ERROR_WANT_READ: - errstr = "The operation did not complete (read)"; - p = PY_SSL_ERROR_WANT_READ; - break; - case SSL_ERROR_WANT_WRITE: - p = PY_SSL_ERROR_WANT_WRITE; - errstr = "The operation did not complete (write)"; - break; - case SSL_ERROR_WANT_X509_LOOKUP: - p = PY_SSL_ERROR_WANT_X509_LOOKUP; - errstr = - "The operation did not complete (X509 lookup)"; - break; - case SSL_ERROR_WANT_CONNECT: - p = PY_SSL_ERROR_WANT_CONNECT; - errstr = "The operation did not complete (connect)"; - break; - case SSL_ERROR_SYSCALL: - { - unsigned long e = ERR_get_error(); - if (e == 0) { - if (ret == 0 || !obj->Socket) { - p = PY_SSL_ERROR_EOF; - errstr = - "EOF occurred in violation of protocol"; - } else if (ret == -1) { - /* underlying BIO reported an I/O error */ - return obj->Socket->errorhandler(); - } else { /* possible? */ - p = PY_SSL_ERROR_SYSCALL; - errstr = "Some I/O error occurred"; - } - } else { - p = PY_SSL_ERROR_SYSCALL; - /* XXX Protected by global interpreter lock */ - errstr = ERR_error_string(e, NULL); - } - break; - } - case SSL_ERROR_SSL: - { - unsigned long e = ERR_get_error(); - p = PY_SSL_ERROR_SSL; - if (e != 0) - /* XXX Protected by global interpreter lock */ - errstr = ERR_error_string(e, NULL); - else { /* possible? */ - errstr = - "A failure in the SSL library occurred"; - } - break; - } - default: - p = PY_SSL_ERROR_INVALID_ERROR_CODE; - errstr = "Invalid error code"; - } - } else { - errstr = ERR_error_string(ERR_peek_last_error(), NULL); - } - PyOS_snprintf(buf, sizeof(buf), "_ssl.c:%d: %s", lineno, errstr); - v = Py_BuildValue("(is)", p, buf); - if (v != NULL) { - PyErr_SetObject(PySSLErrorObject, v); - Py_DECREF(v); - } - return NULL; + PyObject *v; + char buf[2048]; + char *errstr; + int err; + enum py_ssl_error p = PY_SSL_ERROR_NONE; + + assert(ret <= 0); + + if (obj->ssl != NULL) { + err = SSL_get_error(obj->ssl, ret); + + switch (err) { + case SSL_ERROR_ZERO_RETURN: + errstr = "TLS/SSL connection has been closed"; + p = PY_SSL_ERROR_ZERO_RETURN; + break; + case SSL_ERROR_WANT_READ: + errstr = "The operation did not complete (read)"; + p = PY_SSL_ERROR_WANT_READ; + break; + case SSL_ERROR_WANT_WRITE: + p = PY_SSL_ERROR_WANT_WRITE; + errstr = "The operation did not complete (write)"; + break; + case SSL_ERROR_WANT_X509_LOOKUP: + p = PY_SSL_ERROR_WANT_X509_LOOKUP; + errstr = + "The operation did not complete (X509 lookup)"; + break; + case SSL_ERROR_WANT_CONNECT: + p = PY_SSL_ERROR_WANT_CONNECT; + errstr = "The operation did not complete (connect)"; + break; + case SSL_ERROR_SYSCALL: + { + unsigned long e = ERR_get_error(); + if (e == 0) { + if (ret == 0 || !obj->Socket) { + p = PY_SSL_ERROR_EOF; + errstr = + "EOF occurred in violation of protocol"; + } else if (ret == -1) { + /* underlying BIO reported an I/O error */ + return obj->Socket->errorhandler(); + } else { /* possible? */ + p = PY_SSL_ERROR_SYSCALL; + errstr = "Some I/O error occurred"; + } + } else { + p = PY_SSL_ERROR_SYSCALL; + /* XXX Protected by global interpreter lock */ + errstr = ERR_error_string(e, NULL); + } + break; + } + case SSL_ERROR_SSL: + { + unsigned long e = ERR_get_error(); + p = PY_SSL_ERROR_SSL; + if (e != 0) + /* XXX Protected by global interpreter lock */ + errstr = ERR_error_string(e, NULL); + else { /* possible? */ + errstr = + "A failure in the SSL library occurred"; + } + break; + } + default: + p = PY_SSL_ERROR_INVALID_ERROR_CODE; + errstr = "Invalid error code"; + } + } else { + errstr = ERR_error_string(ERR_peek_last_error(), NULL); + } + PyOS_snprintf(buf, sizeof(buf), "_ssl.c:%d: %s", lineno, errstr); + v = Py_BuildValue("(is)", p, buf); + if (v != NULL) { + PyErr_SetObject(PySSLErrorObject, v); + Py_DECREF(v); + } + return NULL; } static PyObject * _setSSLError (char *errstr, int errcode, char *filename, int lineno) { - char buf[2048]; - PyObject *v; + char buf[2048]; + PyObject *v; - if (errstr == NULL) { - errcode = ERR_peek_last_error(); - errstr = ERR_error_string(errcode, NULL); - } - PyOS_snprintf(buf, sizeof(buf), "_ssl.c:%d: %s", lineno, errstr); - v = Py_BuildValue("(is)", errcode, buf); - if (v != NULL) { - PyErr_SetObject(PySSLErrorObject, v); - Py_DECREF(v); - } - return NULL; + if (errstr == NULL) { + errcode = ERR_peek_last_error(); + errstr = ERR_error_string(errcode, NULL); + } + PyOS_snprintf(buf, sizeof(buf), "_ssl.c:%d: %s", lineno, errstr); + v = Py_BuildValue("(is)", errcode, buf); + if (v != NULL) { + PyErr_SetObject(PySSLErrorObject, v); + Py_DECREF(v); + } + return NULL; } static PySSLObject * newPySSLObject(PySocketSockObject *Sock, char *key_file, char *cert_file, - enum py_ssl_server_or_client socket_type, - enum py_ssl_cert_requirements certreq, - enum py_ssl_version proto_version, - char *cacerts_file) + enum py_ssl_server_or_client socket_type, + enum py_ssl_cert_requirements certreq, + enum py_ssl_version proto_version, + char *cacerts_file) { - PySSLObject *self; - char *errstr = NULL; - int ret; - int verification_mode; - - self = PyObject_New(PySSLObject, &PySSL_Type); /* Create new object */ - if (self == NULL) - return NULL; - memset(self->server, '\0', sizeof(char) * X509_NAME_MAXLEN); - memset(self->issuer, '\0', sizeof(char) * X509_NAME_MAXLEN); - self->peer_cert = NULL; - self->ssl = NULL; - self->ctx = NULL; - self->Socket = NULL; - - /* Make sure the SSL error state is initialized */ - (void) ERR_get_state(); - ERR_clear_error(); - - if ((key_file && !cert_file) || (!key_file && cert_file)) { - errstr = ERRSTR("Both the key & certificate files " - "must be specified"); - goto fail; - } - - if ((socket_type == PY_SSL_SERVER) && - ((key_file == NULL) || (cert_file == NULL))) { - errstr = ERRSTR("Both the key & certificate files " - "must be specified for server-side operation"); - goto fail; - } - - PySSL_BEGIN_ALLOW_THREADS - if (proto_version == PY_SSL_VERSION_TLS1) - self->ctx = SSL_CTX_new(TLSv1_method()); /* Set up context */ - else if (proto_version == PY_SSL_VERSION_SSL3) - self->ctx = SSL_CTX_new(SSLv3_method()); /* Set up context */ - else if (proto_version == PY_SSL_VERSION_SSL2) - self->ctx = SSL_CTX_new(SSLv2_method()); /* Set up context */ - else if (proto_version == PY_SSL_VERSION_SSL23) - self->ctx = SSL_CTX_new(SSLv23_method()); /* Set up context */ - PySSL_END_ALLOW_THREADS - - if (self->ctx == NULL) { - errstr = ERRSTR("Invalid SSL protocol variant specified."); - goto fail; - } - - if (certreq != PY_SSL_CERT_NONE) { - if (cacerts_file == NULL) { - errstr = ERRSTR("No root certificates specified for " - "verification of other-side certificates."); - goto fail; - } else { - PySSL_BEGIN_ALLOW_THREADS - ret = SSL_CTX_load_verify_locations(self->ctx, - cacerts_file, - NULL); - PySSL_END_ALLOW_THREADS - if (ret != 1) { - _setSSLError(NULL, 0, __FILE__, __LINE__); - goto fail; - } - } - } - if (key_file) { - PySSL_BEGIN_ALLOW_THREADS - ret = SSL_CTX_use_PrivateKey_file(self->ctx, key_file, - SSL_FILETYPE_PEM); - PySSL_END_ALLOW_THREADS - if (ret != 1) { - _setSSLError(NULL, ret, __FILE__, __LINE__); - goto fail; - } - - PySSL_BEGIN_ALLOW_THREADS - ret = SSL_CTX_use_certificate_chain_file(self->ctx, - cert_file); - PySSL_END_ALLOW_THREADS - if (ret != 1) { - /* - fprintf(stderr, "ret is %d, errcode is %lu, %lu, with file \"%s\"\n", - ret, ERR_peek_error(), ERR_peek_last_error(), cert_file); - */ - if (ERR_peek_last_error() != 0) { - _setSSLError(NULL, ret, __FILE__, __LINE__); - goto fail; - } - } - } - - /* ssl compatibility */ - SSL_CTX_set_options(self->ctx, SSL_OP_ALL); - - verification_mode = SSL_VERIFY_NONE; - if (certreq == PY_SSL_CERT_OPTIONAL) - verification_mode = SSL_VERIFY_PEER; - else if (certreq == PY_SSL_CERT_REQUIRED) - verification_mode = (SSL_VERIFY_PEER | - SSL_VERIFY_FAIL_IF_NO_PEER_CERT); - SSL_CTX_set_verify(self->ctx, verification_mode, - NULL); /* set verify lvl */ - - PySSL_BEGIN_ALLOW_THREADS - self->ssl = SSL_new(self->ctx); /* New ssl struct */ - PySSL_END_ALLOW_THREADS - SSL_set_fd(self->ssl, Sock->sock_fd); /* Set the socket for SSL */ + PySSLObject *self; + char *errstr = NULL; + int ret; + int verification_mode; + + self = PyObject_New(PySSLObject, &PySSL_Type); /* Create new object */ + if (self == NULL) + return NULL; + memset(self->server, '\0', sizeof(char) * X509_NAME_MAXLEN); + memset(self->issuer, '\0', sizeof(char) * X509_NAME_MAXLEN); + self->peer_cert = NULL; + self->ssl = NULL; + self->ctx = NULL; + self->Socket = NULL; + + /* Make sure the SSL error state is initialized */ + (void) ERR_get_state(); + ERR_clear_error(); + + if ((key_file && !cert_file) || (!key_file && cert_file)) { + errstr = ERRSTR("Both the key & certificate files " + "must be specified"); + goto fail; + } + + if ((socket_type == PY_SSL_SERVER) && + ((key_file == NULL) || (cert_file == NULL))) { + errstr = ERRSTR("Both the key & certificate files " + "must be specified for server-side operation"); + goto fail; + } + + PySSL_BEGIN_ALLOW_THREADS + if (proto_version == PY_SSL_VERSION_TLS1) + self->ctx = SSL_CTX_new(TLSv1_method()); /* Set up context */ + else if (proto_version == PY_SSL_VERSION_SSL3) + self->ctx = SSL_CTX_new(SSLv3_method()); /* Set up context */ + else if (proto_version == PY_SSL_VERSION_SSL2) + self->ctx = SSL_CTX_new(SSLv2_method()); /* Set up context */ + else if (proto_version == PY_SSL_VERSION_SSL23) + self->ctx = SSL_CTX_new(SSLv23_method()); /* Set up context */ + PySSL_END_ALLOW_THREADS + + if (self->ctx == NULL) { + errstr = ERRSTR("Invalid SSL protocol variant specified."); + goto fail; + } + + if (certreq != PY_SSL_CERT_NONE) { + if (cacerts_file == NULL) { + errstr = ERRSTR("No root certificates specified for " + "verification of other-side certificates."); + goto fail; + } else { + PySSL_BEGIN_ALLOW_THREADS + ret = SSL_CTX_load_verify_locations(self->ctx, + cacerts_file, + NULL); + PySSL_END_ALLOW_THREADS + if (ret != 1) { + _setSSLError(NULL, 0, __FILE__, __LINE__); + goto fail; + } + } + } + if (key_file) { + PySSL_BEGIN_ALLOW_THREADS + ret = SSL_CTX_use_PrivateKey_file(self->ctx, key_file, + SSL_FILETYPE_PEM); + PySSL_END_ALLOW_THREADS + if (ret != 1) { + _setSSLError(NULL, ret, __FILE__, __LINE__); + goto fail; + } + + PySSL_BEGIN_ALLOW_THREADS + ret = SSL_CTX_use_certificate_chain_file(self->ctx, + cert_file); + PySSL_END_ALLOW_THREADS + if (ret != 1) { + /* + fprintf(stderr, "ret is %d, errcode is %lu, %lu, with file \"%s\"\n", + ret, ERR_peek_error(), ERR_peek_last_error(), cert_file); + */ + if (ERR_peek_last_error() != 0) { + _setSSLError(NULL, ret, __FILE__, __LINE__); + goto fail; + } + } + } + + /* ssl compatibility */ + SSL_CTX_set_options(self->ctx, SSL_OP_ALL); + + verification_mode = SSL_VERIFY_NONE; + if (certreq == PY_SSL_CERT_OPTIONAL) + verification_mode = SSL_VERIFY_PEER; + else if (certreq == PY_SSL_CERT_REQUIRED) + verification_mode = (SSL_VERIFY_PEER | + SSL_VERIFY_FAIL_IF_NO_PEER_CERT); + SSL_CTX_set_verify(self->ctx, verification_mode, + NULL); /* set verify lvl */ + + PySSL_BEGIN_ALLOW_THREADS + self->ssl = SSL_new(self->ctx); /* New ssl struct */ + PySSL_END_ALLOW_THREADS + SSL_set_fd(self->ssl, Sock->sock_fd); /* Set the socket for SSL */ #ifdef SSL_MODE_AUTO_RETRY - SSL_set_mode(self->ssl, SSL_MODE_AUTO_RETRY); + SSL_set_mode(self->ssl, SSL_MODE_AUTO_RETRY); #endif - /* If the socket is in non-blocking mode or timeout mode, set the BIO - * to non-blocking mode (blocking is the default) - */ - if (Sock->sock_timeout >= 0.0) { - /* Set both the read and write BIO's to non-blocking mode */ - BIO_set_nbio(SSL_get_rbio(self->ssl), 1); - BIO_set_nbio(SSL_get_wbio(self->ssl), 1); - } - - PySSL_BEGIN_ALLOW_THREADS - if (socket_type == PY_SSL_CLIENT) - SSL_set_connect_state(self->ssl); - else - SSL_set_accept_state(self->ssl); - PySSL_END_ALLOW_THREADS - - self->Socket = Sock; - Py_INCREF(self->Socket); - return self; + /* If the socket is in non-blocking mode or timeout mode, set the BIO + * to non-blocking mode (blocking is the default) + */ + if (Sock->sock_timeout >= 0.0) { + /* Set both the read and write BIO's to non-blocking mode */ + BIO_set_nbio(SSL_get_rbio(self->ssl), 1); + BIO_set_nbio(SSL_get_wbio(self->ssl), 1); + } + + PySSL_BEGIN_ALLOW_THREADS + if (socket_type == PY_SSL_CLIENT) + SSL_set_connect_state(self->ssl); + else + SSL_set_accept_state(self->ssl); + PySSL_END_ALLOW_THREADS + + self->Socket = Sock; + Py_INCREF(self->Socket); + return self; fail: - if (errstr) - PyErr_SetString(PySSLErrorObject, errstr); - Py_DECREF(self); - return NULL; + if (errstr) + PyErr_SetString(PySSLErrorObject, errstr); + Py_DECREF(self); + return NULL; } static PyObject * PySSL_sslwrap(PyObject *self, PyObject *args) { - PySocketSockObject *Sock; - int server_side = 0; - int verification_mode = PY_SSL_CERT_NONE; - int protocol = PY_SSL_VERSION_SSL23; - char *key_file = NULL; - char *cert_file = NULL; - char *cacerts_file = NULL; - - if (!PyArg_ParseTuple(args, "O!i|zziiz:sslwrap", - PySocketModule.Sock_Type, - &Sock, - &server_side, - &key_file, &cert_file, - &verification_mode, &protocol, - &cacerts_file)) - return NULL; - - /* - fprintf(stderr, - "server_side is %d, keyfile %p, certfile %p, verify_mode %d, " - "protocol %d, certs %p\n", - server_side, key_file, cert_file, verification_mode, - protocol, cacerts_file); - */ - - return (PyObject *) newPySSLObject(Sock, key_file, cert_file, - server_side, verification_mode, - protocol, cacerts_file); + PySocketSockObject *Sock; + int server_side = 0; + int verification_mode = PY_SSL_CERT_NONE; + int protocol = PY_SSL_VERSION_SSL23; + char *key_file = NULL; + char *cert_file = NULL; + char *cacerts_file = NULL; + + if (!PyArg_ParseTuple(args, "O!i|zziiz:sslwrap", + PySocketModule.Sock_Type, + &Sock, + &server_side, + &key_file, &cert_file, + &verification_mode, &protocol, + &cacerts_file)) + return NULL; + + /* + fprintf(stderr, + "server_side is %d, keyfile %p, certfile %p, verify_mode %d, " + "protocol %d, certs %p\n", + server_side, key_file, cert_file, verification_mode, + protocol, cacerts_file); + */ + + return (PyObject *) newPySSLObject(Sock, key_file, cert_file, + server_side, verification_mode, + protocol, cacerts_file); } PyDoc_STRVAR(ssl_doc, @@ -443,573 +443,573 @@ static PyObject *PySSL_SSLdo_handshake(PySSLObject *self) { - int ret; - int err; - int sockstate, nonblocking; - - /* just in case the blocking state of the socket has been changed */ - nonblocking = (self->Socket->sock_timeout >= 0.0); - BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking); - BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking); - - /* Actually negotiate SSL connection */ - /* XXX If SSL_do_handshake() returns 0, it's also a failure. */ - sockstate = 0; - do { - PySSL_BEGIN_ALLOW_THREADS - ret = SSL_do_handshake(self->ssl); - err = SSL_get_error(self->ssl, ret); - PySSL_END_ALLOW_THREADS - if(PyErr_CheckSignals()) { - return NULL; - } - if (err == SSL_ERROR_WANT_READ) { - sockstate = check_socket_and_wait_for_timeout(self->Socket, 0); - } else if (err == SSL_ERROR_WANT_WRITE) { - sockstate = check_socket_and_wait_for_timeout(self->Socket, 1); - } else { - sockstate = SOCKET_OPERATION_OK; - } - if (sockstate == SOCKET_HAS_TIMED_OUT) { - PyErr_SetString(PySSLErrorObject, - ERRSTR("The handshake operation timed out")); - return NULL; - } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) { - PyErr_SetString(PySSLErrorObject, - ERRSTR("Underlying socket has been closed.")); - return NULL; - } else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) { - PyErr_SetString(PySSLErrorObject, - ERRSTR("Underlying socket too large for select().")); - return NULL; - } else if (sockstate == SOCKET_IS_NONBLOCKING) { - break; - } - } while (err == SSL_ERROR_WANT_READ || err == SSL_ERROR_WANT_WRITE); - if (ret < 1) - return PySSL_SetError(self, ret, __FILE__, __LINE__); - self->ssl->debug = 1; - - if (self->peer_cert) - X509_free (self->peer_cert); - PySSL_BEGIN_ALLOW_THREADS - if ((self->peer_cert = SSL_get_peer_certificate(self->ssl))) { - X509_NAME_oneline(X509_get_subject_name(self->peer_cert), - self->server, X509_NAME_MAXLEN); - X509_NAME_oneline(X509_get_issuer_name(self->peer_cert), - self->issuer, X509_NAME_MAXLEN); - } - PySSL_END_ALLOW_THREADS + int ret; + int err; + int sockstate, nonblocking; + + /* just in case the blocking state of the socket has been changed */ + nonblocking = (self->Socket->sock_timeout >= 0.0); + BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking); + BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking); + + /* Actually negotiate SSL connection */ + /* XXX If SSL_do_handshake() returns 0, it's also a failure. */ + sockstate = 0; + do { + PySSL_BEGIN_ALLOW_THREADS + ret = SSL_do_handshake(self->ssl); + err = SSL_get_error(self->ssl, ret); + PySSL_END_ALLOW_THREADS + if(PyErr_CheckSignals()) { + return NULL; + } + if (err == SSL_ERROR_WANT_READ) { + sockstate = check_socket_and_wait_for_timeout(self->Socket, 0); + } else if (err == SSL_ERROR_WANT_WRITE) { + sockstate = check_socket_and_wait_for_timeout(self->Socket, 1); + } else { + sockstate = SOCKET_OPERATION_OK; + } + if (sockstate == SOCKET_HAS_TIMED_OUT) { + PyErr_SetString(PySSLErrorObject, + ERRSTR("The handshake operation timed out")); + return NULL; + } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) { + PyErr_SetString(PySSLErrorObject, + ERRSTR("Underlying socket has been closed.")); + return NULL; + } else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) { + PyErr_SetString(PySSLErrorObject, + ERRSTR("Underlying socket too large for select().")); + return NULL; + } else if (sockstate == SOCKET_IS_NONBLOCKING) { + break; + } + } while (err == SSL_ERROR_WANT_READ || err == SSL_ERROR_WANT_WRITE); + if (ret < 1) + return PySSL_SetError(self, ret, __FILE__, __LINE__); + self->ssl->debug = 1; + + if (self->peer_cert) + X509_free (self->peer_cert); + PySSL_BEGIN_ALLOW_THREADS + if ((self->peer_cert = SSL_get_peer_certificate(self->ssl))) { + X509_NAME_oneline(X509_get_subject_name(self->peer_cert), + self->server, X509_NAME_MAXLEN); + X509_NAME_oneline(X509_get_issuer_name(self->peer_cert), + self->issuer, X509_NAME_MAXLEN); + } + PySSL_END_ALLOW_THREADS - Py_INCREF(Py_None); - return Py_None; + Py_INCREF(Py_None); + return Py_None; } static PyObject * PySSL_server(PySSLObject *self) { - return PyString_FromString(self->server); + return PyString_FromString(self->server); } static PyObject * PySSL_issuer(PySSLObject *self) { - return PyString_FromString(self->issuer); + return PyString_FromString(self->issuer); } static PyObject * _create_tuple_for_attribute (ASN1_OBJECT *name, ASN1_STRING *value) { - char namebuf[X509_NAME_MAXLEN]; - int buflen; - PyObject *name_obj; - PyObject *value_obj; - PyObject *attr; - unsigned char *valuebuf = NULL; - - buflen = OBJ_obj2txt(namebuf, sizeof(namebuf), name, 0); - if (buflen < 0) { - _setSSLError(NULL, 0, __FILE__, __LINE__); - goto fail; - } - name_obj = PyString_FromStringAndSize(namebuf, buflen); - if (name_obj == NULL) - goto fail; - - buflen = ASN1_STRING_to_UTF8(&valuebuf, value); - if (buflen < 0) { - _setSSLError(NULL, 0, __FILE__, __LINE__); - Py_DECREF(name_obj); - goto fail; - } - value_obj = PyUnicode_DecodeUTF8((char *) valuebuf, - buflen, "strict"); - OPENSSL_free(valuebuf); - if (value_obj == NULL) { - Py_DECREF(name_obj); - goto fail; - } - attr = PyTuple_New(2); - if (attr == NULL) { - Py_DECREF(name_obj); - Py_DECREF(value_obj); - goto fail; - } - PyTuple_SET_ITEM(attr, 0, name_obj); - PyTuple_SET_ITEM(attr, 1, value_obj); - return attr; + char namebuf[X509_NAME_MAXLEN]; + int buflen; + PyObject *name_obj; + PyObject *value_obj; + PyObject *attr; + unsigned char *valuebuf = NULL; + + buflen = OBJ_obj2txt(namebuf, sizeof(namebuf), name, 0); + if (buflen < 0) { + _setSSLError(NULL, 0, __FILE__, __LINE__); + goto fail; + } + name_obj = PyString_FromStringAndSize(namebuf, buflen); + if (name_obj == NULL) + goto fail; + + buflen = ASN1_STRING_to_UTF8(&valuebuf, value); + if (buflen < 0) { + _setSSLError(NULL, 0, __FILE__, __LINE__); + Py_DECREF(name_obj); + goto fail; + } + value_obj = PyUnicode_DecodeUTF8((char *) valuebuf, + buflen, "strict"); + OPENSSL_free(valuebuf); + if (value_obj == NULL) { + Py_DECREF(name_obj); + goto fail; + } + attr = PyTuple_New(2); + if (attr == NULL) { + Py_DECREF(name_obj); + Py_DECREF(value_obj); + goto fail; + } + PyTuple_SET_ITEM(attr, 0, name_obj); + PyTuple_SET_ITEM(attr, 1, value_obj); + return attr; fail: - return NULL; + return NULL; } static PyObject * _create_tuple_for_X509_NAME (X509_NAME *xname) { - PyObject *dn = NULL; /* tuple which represents the "distinguished name" */ - PyObject *rdn = NULL; /* tuple to hold a "relative distinguished name" */ - PyObject *rdnt; - PyObject *attr = NULL; /* tuple to hold an attribute */ - int entry_count = X509_NAME_entry_count(xname); - X509_NAME_ENTRY *entry; - ASN1_OBJECT *name; - ASN1_STRING *value; - int index_counter; - int rdn_level = -1; - int retcode; - - dn = PyList_New(0); - if (dn == NULL) - return NULL; - /* now create another tuple to hold the top-level RDN */ - rdn = PyList_New(0); - if (rdn == NULL) - goto fail0; - - for (index_counter = 0; - index_counter < entry_count; - index_counter++) - { - entry = X509_NAME_get_entry(xname, index_counter); - - /* check to see if we've gotten to a new RDN */ - if (rdn_level >= 0) { - if (rdn_level != entry->set) { - /* yes, new RDN */ - /* add old RDN to DN */ - rdnt = PyList_AsTuple(rdn); - Py_DECREF(rdn); - if (rdnt == NULL) - goto fail0; - retcode = PyList_Append(dn, rdnt); - Py_DECREF(rdnt); - if (retcode < 0) - goto fail0; - /* create new RDN */ - rdn = PyList_New(0); - if (rdn == NULL) - goto fail0; - } - } - rdn_level = entry->set; - - /* now add this attribute to the current RDN */ - name = X509_NAME_ENTRY_get_object(entry); - value = X509_NAME_ENTRY_get_data(entry); - attr = _create_tuple_for_attribute(name, value); - /* - fprintf(stderr, "RDN level %d, attribute %s: %s\n", - entry->set, - PyString_AS_STRING(PyTuple_GET_ITEM(attr, 0)), - PyString_AS_STRING(PyTuple_GET_ITEM(attr, 1))); - */ - if (attr == NULL) - goto fail1; - retcode = PyList_Append(rdn, attr); - Py_DECREF(attr); - if (retcode < 0) - goto fail1; - } - /* now, there's typically a dangling RDN */ - if ((rdn != NULL) && (PyList_Size(rdn) > 0)) { - rdnt = PyList_AsTuple(rdn); - Py_DECREF(rdn); - if (rdnt == NULL) - goto fail0; - retcode = PyList_Append(dn, rdnt); - Py_DECREF(rdnt); - if (retcode < 0) - goto fail0; - } - - /* convert list to tuple */ - rdnt = PyList_AsTuple(dn); - Py_DECREF(dn); - if (rdnt == NULL) - return NULL; - return rdnt; + PyObject *dn = NULL; /* tuple which represents the "distinguished name" */ + PyObject *rdn = NULL; /* tuple to hold a "relative distinguished name" */ + PyObject *rdnt; + PyObject *attr = NULL; /* tuple to hold an attribute */ + int entry_count = X509_NAME_entry_count(xname); + X509_NAME_ENTRY *entry; + ASN1_OBJECT *name; + ASN1_STRING *value; + int index_counter; + int rdn_level = -1; + int retcode; + + dn = PyList_New(0); + if (dn == NULL) + return NULL; + /* now create another tuple to hold the top-level RDN */ + rdn = PyList_New(0); + if (rdn == NULL) + goto fail0; + + for (index_counter = 0; + index_counter < entry_count; + index_counter++) + { + entry = X509_NAME_get_entry(xname, index_counter); + + /* check to see if we've gotten to a new RDN */ + if (rdn_level >= 0) { + if (rdn_level != entry->set) { + /* yes, new RDN */ + /* add old RDN to DN */ + rdnt = PyList_AsTuple(rdn); + Py_DECREF(rdn); + if (rdnt == NULL) + goto fail0; + retcode = PyList_Append(dn, rdnt); + Py_DECREF(rdnt); + if (retcode < 0) + goto fail0; + /* create new RDN */ + rdn = PyList_New(0); + if (rdn == NULL) + goto fail0; + } + } + rdn_level = entry->set; + + /* now add this attribute to the current RDN */ + name = X509_NAME_ENTRY_get_object(entry); + value = X509_NAME_ENTRY_get_data(entry); + attr = _create_tuple_for_attribute(name, value); + /* + fprintf(stderr, "RDN level %d, attribute %s: %s\n", + entry->set, + PyString_AS_STRING(PyTuple_GET_ITEM(attr, 0)), + PyString_AS_STRING(PyTuple_GET_ITEM(attr, 1))); + */ + if (attr == NULL) + goto fail1; + retcode = PyList_Append(rdn, attr); + Py_DECREF(attr); + if (retcode < 0) + goto fail1; + } + /* now, there's typically a dangling RDN */ + if ((rdn != NULL) && (PyList_Size(rdn) > 0)) { + rdnt = PyList_AsTuple(rdn); + Py_DECREF(rdn); + if (rdnt == NULL) + goto fail0; + retcode = PyList_Append(dn, rdnt); + Py_DECREF(rdnt); + if (retcode < 0) + goto fail0; + } + + /* convert list to tuple */ + rdnt = PyList_AsTuple(dn); + Py_DECREF(dn); + if (rdnt == NULL) + return NULL; + return rdnt; fail1: - Py_XDECREF(rdn); + Py_XDECREF(rdn); fail0: - Py_XDECREF(dn); - return NULL; + Py_XDECREF(dn); + return NULL; } static PyObject * _get_peer_alt_names (X509 *certificate) { - - /* this code follows the procedure outlined in - OpenSSL's crypto/x509v3/v3_prn.c:X509v3_EXT_print() - function to extract the STACK_OF(GENERAL_NAME), - then iterates through the stack to add the - names. */ - - int i, j; - PyObject *peer_alt_names = Py_None; - PyObject *v, *t; - X509_EXTENSION *ext = NULL; - GENERAL_NAMES *names = NULL; - GENERAL_NAME *name; - X509V3_EXT_METHOD *method; - BIO *biobuf = NULL; - char buf[2048]; - char *vptr; - int len; - const unsigned char *p; - - if (certificate == NULL) - return peer_alt_names; - - /* get a memory buffer */ - biobuf = BIO_new(BIO_s_mem()); - - i = 0; - while ((i = X509_get_ext_by_NID( - certificate, NID_subject_alt_name, i)) >= 0) { - - if (peer_alt_names == Py_None) { - peer_alt_names = PyList_New(0); - if (peer_alt_names == NULL) - goto fail; - } - - /* now decode the altName */ - ext = X509_get_ext(certificate, i); - if(!(method = X509V3_EXT_get(ext))) { - PyErr_SetString(PySSLErrorObject, - ERRSTR("No method for internalizing subjectAltName!")); - goto fail; - } - - p = ext->value->data; - if (method->it) - names = (GENERAL_NAMES*) (ASN1_item_d2i(NULL, - &p, - ext->value->length, - ASN1_ITEM_ptr(method->it))); - else - names = (GENERAL_NAMES*) (method->d2i(NULL, - &p, - ext->value->length)); - - for(j = 0; j < sk_GENERAL_NAME_num(names); j++) { - - /* get a rendering of each name in the set of names */ - - name = sk_GENERAL_NAME_value(names, j); - if (name->type == GEN_DIRNAME) { - - /* we special-case DirName as a tuple of tuples of attributes */ - - t = PyTuple_New(2); - if (t == NULL) { - goto fail; - } - - v = PyString_FromString("DirName"); - if (v == NULL) { - Py_DECREF(t); - goto fail; - } - PyTuple_SET_ITEM(t, 0, v); - - v = _create_tuple_for_X509_NAME (name->d.dirn); - if (v == NULL) { - Py_DECREF(t); - goto fail; - } - PyTuple_SET_ITEM(t, 1, v); - - } else { - - /* for everything else, we use the OpenSSL print form */ - - (void) BIO_reset(biobuf); - GENERAL_NAME_print(biobuf, name); - len = BIO_gets(biobuf, buf, sizeof(buf)-1); - if (len < 0) { - _setSSLError(NULL, 0, __FILE__, __LINE__); - goto fail; - } - vptr = strchr(buf, ':'); - if (vptr == NULL) - goto fail; - t = PyTuple_New(2); - if (t == NULL) - goto fail; - v = PyString_FromStringAndSize(buf, (vptr - buf)); - if (v == NULL) { - Py_DECREF(t); - goto fail; - } - PyTuple_SET_ITEM(t, 0, v); - v = PyString_FromStringAndSize((vptr + 1), (len - (vptr - buf + 1))); - if (v == NULL) { - Py_DECREF(t); - goto fail; - } - PyTuple_SET_ITEM(t, 1, v); - } - - /* and add that rendering to the list */ - - if (PyList_Append(peer_alt_names, t) < 0) { - Py_DECREF(t); - goto fail; - } - Py_DECREF(t); - } - } - BIO_free(biobuf); - if (peer_alt_names != Py_None) { - v = PyList_AsTuple(peer_alt_names); - Py_DECREF(peer_alt_names); - return v; - } else { - return peer_alt_names; - } - + + /* this code follows the procedure outlined in + OpenSSL's crypto/x509v3/v3_prn.c:X509v3_EXT_print() + function to extract the STACK_OF(GENERAL_NAME), + then iterates through the stack to add the + names. */ + + int i, j; + PyObject *peer_alt_names = Py_None; + PyObject *v, *t; + X509_EXTENSION *ext = NULL; + GENERAL_NAMES *names = NULL; + GENERAL_NAME *name; + X509V3_EXT_METHOD *method; + BIO *biobuf = NULL; + char buf[2048]; + char *vptr; + int len; + const unsigned char *p; + + if (certificate == NULL) + return peer_alt_names; + + /* get a memory buffer */ + biobuf = BIO_new(BIO_s_mem()); + + i = 0; + while ((i = X509_get_ext_by_NID( + certificate, NID_subject_alt_name, i)) >= 0) { + + if (peer_alt_names == Py_None) { + peer_alt_names = PyList_New(0); + if (peer_alt_names == NULL) + goto fail; + } + + /* now decode the altName */ + ext = X509_get_ext(certificate, i); + if(!(method = X509V3_EXT_get(ext))) { + PyErr_SetString(PySSLErrorObject, + ERRSTR("No method for internalizing subjectAltName!")); + goto fail; + } + + p = ext->value->data; + if (method->it) + names = (GENERAL_NAMES*) (ASN1_item_d2i(NULL, + &p, + ext->value->length, + ASN1_ITEM_ptr(method->it))); + else + names = (GENERAL_NAMES*) (method->d2i(NULL, + &p, + ext->value->length)); + + for(j = 0; j < sk_GENERAL_NAME_num(names); j++) { + + /* get a rendering of each name in the set of names */ + + name = sk_GENERAL_NAME_value(names, j); + if (name->type == GEN_DIRNAME) { + + /* we special-case DirName as a tuple of tuples of attributes */ + + t = PyTuple_New(2); + if (t == NULL) { + goto fail; + } + + v = PyString_FromString("DirName"); + if (v == NULL) { + Py_DECREF(t); + goto fail; + } + PyTuple_SET_ITEM(t, 0, v); + + v = _create_tuple_for_X509_NAME (name->d.dirn); + if (v == NULL) { + Py_DECREF(t); + goto fail; + } + PyTuple_SET_ITEM(t, 1, v); + + } else { + + /* for everything else, we use the OpenSSL print form */ + + (void) BIO_reset(biobuf); + GENERAL_NAME_print(biobuf, name); + len = BIO_gets(biobuf, buf, sizeof(buf)-1); + if (len < 0) { + _setSSLError(NULL, 0, __FILE__, __LINE__); + goto fail; + } + vptr = strchr(buf, ':'); + if (vptr == NULL) + goto fail; + t = PyTuple_New(2); + if (t == NULL) + goto fail; + v = PyString_FromStringAndSize(buf, (vptr - buf)); + if (v == NULL) { + Py_DECREF(t); + goto fail; + } + PyTuple_SET_ITEM(t, 0, v); + v = PyString_FromStringAndSize((vptr + 1), (len - (vptr - buf + 1))); + if (v == NULL) { + Py_DECREF(t); + goto fail; + } + PyTuple_SET_ITEM(t, 1, v); + } + + /* and add that rendering to the list */ + + if (PyList_Append(peer_alt_names, t) < 0) { + Py_DECREF(t); + goto fail; + } + Py_DECREF(t); + } + } + BIO_free(biobuf); + if (peer_alt_names != Py_None) { + v = PyList_AsTuple(peer_alt_names); + Py_DECREF(peer_alt_names); + return v; + } else { + return peer_alt_names; + } + fail: - if (biobuf != NULL) - BIO_free(biobuf); + if (biobuf != NULL) + BIO_free(biobuf); - if (peer_alt_names != Py_None) { - Py_XDECREF(peer_alt_names); - } + if (peer_alt_names != Py_None) { + Py_XDECREF(peer_alt_names); + } - return NULL; + return NULL; } static PyObject * _decode_certificate (X509 *certificate, int verbose) { - PyObject *retval = NULL; - BIO *biobuf = NULL; - PyObject *peer; - PyObject *peer_alt_names = NULL; - PyObject *issuer; - PyObject *version; - PyObject *sn_obj; - ASN1_INTEGER *serialNumber; - char buf[2048]; - int len; - ASN1_TIME *notBefore, *notAfter; - PyObject *pnotBefore, *pnotAfter; - - retval = PyDict_New(); - if (retval == NULL) - return NULL; - - peer = _create_tuple_for_X509_NAME( - X509_get_subject_name(certificate)); - if (peer == NULL) - goto fail0; - if (PyDict_SetItemString(retval, (const char *) "subject", peer) < 0) { - Py_DECREF(peer); - goto fail0; - } - Py_DECREF(peer); - - if (verbose) { - issuer = _create_tuple_for_X509_NAME( - X509_get_issuer_name(certificate)); - if (issuer == NULL) - goto fail0; - if (PyDict_SetItemString(retval, (const char *)"issuer", issuer) < 0) { - Py_DECREF(issuer); - goto fail0; - } - Py_DECREF(issuer); - - version = PyInt_FromLong(X509_get_version(certificate) + 1); - if (PyDict_SetItemString(retval, "version", version) < 0) { - Py_DECREF(version); - goto fail0; - } - Py_DECREF(version); - } - - /* get a memory buffer */ - biobuf = BIO_new(BIO_s_mem()); - - if (verbose) { - - (void) BIO_reset(biobuf); - serialNumber = X509_get_serialNumber(certificate); - /* should not exceed 20 octets, 160 bits, so buf is big enough */ - i2a_ASN1_INTEGER(biobuf, serialNumber); - len = BIO_gets(biobuf, buf, sizeof(buf)-1); - if (len < 0) { - _setSSLError(NULL, 0, __FILE__, __LINE__); - goto fail1; - } - sn_obj = PyString_FromStringAndSize(buf, len); - if (sn_obj == NULL) - goto fail1; - if (PyDict_SetItemString(retval, "serialNumber", sn_obj) < 0) { - Py_DECREF(sn_obj); - goto fail1; - } - Py_DECREF(sn_obj); - - (void) BIO_reset(biobuf); - notBefore = X509_get_notBefore(certificate); - ASN1_TIME_print(biobuf, notBefore); - len = BIO_gets(biobuf, buf, sizeof(buf)-1); - if (len < 0) { - _setSSLError(NULL, 0, __FILE__, __LINE__); - goto fail1; - } - pnotBefore = PyString_FromStringAndSize(buf, len); - if (pnotBefore == NULL) - goto fail1; - if (PyDict_SetItemString(retval, "notBefore", pnotBefore) < 0) { - Py_DECREF(pnotBefore); - goto fail1; - } - Py_DECREF(pnotBefore); - } - - (void) BIO_reset(biobuf); - notAfter = X509_get_notAfter(certificate); - ASN1_TIME_print(biobuf, notAfter); - len = BIO_gets(biobuf, buf, sizeof(buf)-1); - if (len < 0) { - _setSSLError(NULL, 0, __FILE__, __LINE__); - goto fail1; - } - pnotAfter = PyString_FromStringAndSize(buf, len); - if (pnotAfter == NULL) - goto fail1; - if (PyDict_SetItemString(retval, "notAfter", pnotAfter) < 0) { - Py_DECREF(pnotAfter); - goto fail1; - } - Py_DECREF(pnotAfter); - - /* Now look for subjectAltName */ - - peer_alt_names = _get_peer_alt_names(certificate); - if (peer_alt_names == NULL) - goto fail1; - else if (peer_alt_names != Py_None) { - if (PyDict_SetItemString(retval, "subjectAltName", - peer_alt_names) < 0) { - Py_DECREF(peer_alt_names); - goto fail1; - } - Py_DECREF(peer_alt_names); - } - - BIO_free(biobuf); - return retval; + PyObject *retval = NULL; + BIO *biobuf = NULL; + PyObject *peer; + PyObject *peer_alt_names = NULL; + PyObject *issuer; + PyObject *version; + PyObject *sn_obj; + ASN1_INTEGER *serialNumber; + char buf[2048]; + int len; + ASN1_TIME *notBefore, *notAfter; + PyObject *pnotBefore, *pnotAfter; + + retval = PyDict_New(); + if (retval == NULL) + return NULL; + + peer = _create_tuple_for_X509_NAME( + X509_get_subject_name(certificate)); + if (peer == NULL) + goto fail0; + if (PyDict_SetItemString(retval, (const char *) "subject", peer) < 0) { + Py_DECREF(peer); + goto fail0; + } + Py_DECREF(peer); + + if (verbose) { + issuer = _create_tuple_for_X509_NAME( + X509_get_issuer_name(certificate)); + if (issuer == NULL) + goto fail0; + if (PyDict_SetItemString(retval, (const char *)"issuer", issuer) < 0) { + Py_DECREF(issuer); + goto fail0; + } + Py_DECREF(issuer); + + version = PyInt_FromLong(X509_get_version(certificate) + 1); + if (PyDict_SetItemString(retval, "version", version) < 0) { + Py_DECREF(version); + goto fail0; + } + Py_DECREF(version); + } + + /* get a memory buffer */ + biobuf = BIO_new(BIO_s_mem()); + + if (verbose) { + + (void) BIO_reset(biobuf); + serialNumber = X509_get_serialNumber(certificate); + /* should not exceed 20 octets, 160 bits, so buf is big enough */ + i2a_ASN1_INTEGER(biobuf, serialNumber); + len = BIO_gets(biobuf, buf, sizeof(buf)-1); + if (len < 0) { + _setSSLError(NULL, 0, __FILE__, __LINE__); + goto fail1; + } + sn_obj = PyString_FromStringAndSize(buf, len); + if (sn_obj == NULL) + goto fail1; + if (PyDict_SetItemString(retval, "serialNumber", sn_obj) < 0) { + Py_DECREF(sn_obj); + goto fail1; + } + Py_DECREF(sn_obj); + + (void) BIO_reset(biobuf); + notBefore = X509_get_notBefore(certificate); + ASN1_TIME_print(biobuf, notBefore); + len = BIO_gets(biobuf, buf, sizeof(buf)-1); + if (len < 0) { + _setSSLError(NULL, 0, __FILE__, __LINE__); + goto fail1; + } + pnotBefore = PyString_FromStringAndSize(buf, len); + if (pnotBefore == NULL) + goto fail1; + if (PyDict_SetItemString(retval, "notBefore", pnotBefore) < 0) { + Py_DECREF(pnotBefore); + goto fail1; + } + Py_DECREF(pnotBefore); + } + + (void) BIO_reset(biobuf); + notAfter = X509_get_notAfter(certificate); + ASN1_TIME_print(biobuf, notAfter); + len = BIO_gets(biobuf, buf, sizeof(buf)-1); + if (len < 0) { + _setSSLError(NULL, 0, __FILE__, __LINE__); + goto fail1; + } + pnotAfter = PyString_FromStringAndSize(buf, len); + if (pnotAfter == NULL) + goto fail1; + if (PyDict_SetItemString(retval, "notAfter", pnotAfter) < 0) { + Py_DECREF(pnotAfter); + goto fail1; + } + Py_DECREF(pnotAfter); + + /* Now look for subjectAltName */ + + peer_alt_names = _get_peer_alt_names(certificate); + if (peer_alt_names == NULL) + goto fail1; + else if (peer_alt_names != Py_None) { + if (PyDict_SetItemString(retval, "subjectAltName", + peer_alt_names) < 0) { + Py_DECREF(peer_alt_names); + goto fail1; + } + Py_DECREF(peer_alt_names); + } + + BIO_free(biobuf); + return retval; fail1: - if (biobuf != NULL) - BIO_free(biobuf); + if (biobuf != NULL) + BIO_free(biobuf); fail0: - Py_XDECREF(retval); - return NULL; + Py_XDECREF(retval); + return NULL; } static PyObject * PySSL_test_decode_certificate (PyObject *mod, PyObject *args) { - PyObject *retval = NULL; - char *filename = NULL; - X509 *x=NULL; - BIO *cert; - int verbose = 1; - - if (!PyArg_ParseTuple(args, "s|i:test_decode_certificate", &filename, &verbose)) - return NULL; - - if ((cert=BIO_new(BIO_s_file())) == NULL) { - PyErr_SetString(PySSLErrorObject, "Can't malloc memory to read file"); - goto fail0; - } - - if (BIO_read_filename(cert,filename) <= 0) { - PyErr_SetString(PySSLErrorObject, "Can't open file"); - goto fail0; - } - - x = PEM_read_bio_X509_AUX(cert,NULL, NULL, NULL); - if (x == NULL) { - PyErr_SetString(PySSLErrorObject, "Error decoding PEM-encoded file"); - goto fail0; - } + PyObject *retval = NULL; + char *filename = NULL; + X509 *x=NULL; + BIO *cert; + int verbose = 1; + + if (!PyArg_ParseTuple(args, "s|i:test_decode_certificate", &filename, &verbose)) + return NULL; + + if ((cert=BIO_new(BIO_s_file())) == NULL) { + PyErr_SetString(PySSLErrorObject, "Can't malloc memory to read file"); + goto fail0; + } + + if (BIO_read_filename(cert,filename) <= 0) { + PyErr_SetString(PySSLErrorObject, "Can't open file"); + goto fail0; + } + + x = PEM_read_bio_X509_AUX(cert,NULL, NULL, NULL); + if (x == NULL) { + PyErr_SetString(PySSLErrorObject, "Error decoding PEM-encoded file"); + goto fail0; + } - retval = _decode_certificate(x, verbose); + retval = _decode_certificate(x, verbose); fail0: - - if (cert != NULL) BIO_free(cert); - return retval; + + if (cert != NULL) BIO_free(cert); + return retval; } static PyObject * PySSL_peercert(PySSLObject *self, PyObject *args) { - PyObject *retval = NULL; - int len; - int verification; - PyObject *binary_mode = Py_None; - - if (!PyArg_ParseTuple(args, "|O:peer_certificate", &binary_mode)) - return NULL; - - if (!self->peer_cert) - Py_RETURN_NONE; - - if (PyObject_IsTrue(binary_mode)) { - /* return cert in DER-encoded format */ - - unsigned char *bytes_buf = NULL; - - bytes_buf = NULL; - len = i2d_X509(self->peer_cert, &bytes_buf); - if (len < 0) { - PySSL_SetError(self, len, __FILE__, __LINE__); - return NULL; - } - retval = PyString_FromStringAndSize((const char *) bytes_buf, len); - OPENSSL_free(bytes_buf); - return retval; - - } else { - - verification = SSL_CTX_get_verify_mode(self->ctx); - if ((verification & SSL_VERIFY_PEER) == 0) - return PyDict_New(); - else - return _decode_certificate (self->peer_cert, 0); - } + PyObject *retval = NULL; + int len; + int verification; + PyObject *binary_mode = Py_None; + + if (!PyArg_ParseTuple(args, "|O:peer_certificate", &binary_mode)) + return NULL; + + if (!self->peer_cert) + Py_RETURN_NONE; + + if (PyObject_IsTrue(binary_mode)) { + /* return cert in DER-encoded format */ + + unsigned char *bytes_buf = NULL; + + bytes_buf = NULL; + len = i2d_X509(self->peer_cert, &bytes_buf); + if (len < 0) { + PySSL_SetError(self, len, __FILE__, __LINE__); + return NULL; + } + retval = PyString_FromStringAndSize((const char *) bytes_buf, len); + OPENSSL_free(bytes_buf); + return retval; + + } else { + + verification = SSL_CTX_get_verify_mode(self->ctx); + if ((verification & SSL_VERIFY_PEER) == 0) + return PyDict_New(); + else + return _decode_certificate (self->peer_cert, 0); + } } PyDoc_STRVAR(PySSL_peercert_doc, @@ -1026,60 +1026,60 @@ static PyObject *PySSL_cipher (PySSLObject *self) { - PyObject *retval, *v; - SSL_CIPHER *current; - char *cipher_name; - char *cipher_protocol; - - if (self->ssl == NULL) - return Py_None; - current = SSL_get_current_cipher(self->ssl); - if (current == NULL) - return Py_None; - - retval = PyTuple_New(3); - if (retval == NULL) - return NULL; - - cipher_name = (char *) SSL_CIPHER_get_name(current); - if (cipher_name == NULL) { - PyTuple_SET_ITEM(retval, 0, Py_None); - } else { - v = PyString_FromString(cipher_name); - if (v == NULL) - goto fail0; - PyTuple_SET_ITEM(retval, 0, v); - } - cipher_protocol = SSL_CIPHER_get_version(current); - if (cipher_protocol == NULL) { - PyTuple_SET_ITEM(retval, 1, Py_None); - } else { - v = PyString_FromString(cipher_protocol); - if (v == NULL) - goto fail0; - PyTuple_SET_ITEM(retval, 1, v); - } - v = PyInt_FromLong(SSL_CIPHER_get_bits(current, NULL)); - if (v == NULL) - goto fail0; - PyTuple_SET_ITEM(retval, 2, v); - return retval; - + PyObject *retval, *v; + SSL_CIPHER *current; + char *cipher_name; + char *cipher_protocol; + + if (self->ssl == NULL) + return Py_None; + current = SSL_get_current_cipher(self->ssl); + if (current == NULL) + return Py_None; + + retval = PyTuple_New(3); + if (retval == NULL) + return NULL; + + cipher_name = (char *) SSL_CIPHER_get_name(current); + if (cipher_name == NULL) { + PyTuple_SET_ITEM(retval, 0, Py_None); + } else { + v = PyString_FromString(cipher_name); + if (v == NULL) + goto fail0; + PyTuple_SET_ITEM(retval, 0, v); + } + cipher_protocol = SSL_CIPHER_get_version(current); + if (cipher_protocol == NULL) { + PyTuple_SET_ITEM(retval, 1, Py_None); + } else { + v = PyString_FromString(cipher_protocol); + if (v == NULL) + goto fail0; + PyTuple_SET_ITEM(retval, 1, v); + } + v = PyInt_FromLong(SSL_CIPHER_get_bits(current, NULL)); + if (v == NULL) + goto fail0; + PyTuple_SET_ITEM(retval, 2, v); + return retval; + fail0: - Py_DECREF(retval); - return NULL; + Py_DECREF(retval); + return NULL; } static void PySSL_dealloc(PySSLObject *self) { - if (self->peer_cert) /* Possible not to have one? */ - X509_free (self->peer_cert); - if (self->ssl) - SSL_free(self->ssl); - if (self->ctx) - SSL_CTX_free(self->ctx); - Py_XDECREF(self->Socket); - PyObject_Del(self); + if (self->peer_cert) /* Possible not to have one? */ + X509_free (self->peer_cert); + if (self->ssl) + SSL_free(self->ssl); + if (self->ctx) + SSL_CTX_free(self->ctx); + Py_XDECREF(self->Socket); + PyObject_Del(self); } /* If the socket has a timeout, do a select()/poll() on the socket. @@ -1090,133 +1090,133 @@ static int check_socket_and_wait_for_timeout(PySocketSockObject *s, int writing) { - fd_set fds; - struct timeval tv; - int rc; - - /* Nothing to do unless we're in timeout mode (not non-blocking) */ - if (s->sock_timeout < 0.0) - return SOCKET_IS_BLOCKING; - else if (s->sock_timeout == 0.0) - return SOCKET_IS_NONBLOCKING; - - /* Guard against closed socket */ - if (s->sock_fd < 0) - return SOCKET_HAS_BEEN_CLOSED; + fd_set fds; + struct timeval tv; + int rc; + + /* Nothing to do unless we're in timeout mode (not non-blocking) */ + if (s->sock_timeout < 0.0) + return SOCKET_IS_BLOCKING; + else if (s->sock_timeout == 0.0) + return SOCKET_IS_NONBLOCKING; + + /* Guard against closed socket */ + if (s->sock_fd < 0) + return SOCKET_HAS_BEEN_CLOSED; - /* Prefer poll, if available, since you can poll() any fd - * which can't be done with select(). */ + /* Prefer poll, if available, since you can poll() any fd + * which can't be done with select(). */ #ifdef HAVE_POLL - { - struct pollfd pollfd; - int timeout; - - pollfd.fd = s->sock_fd; - pollfd.events = writing ? POLLOUT : POLLIN; - - /* s->sock_timeout is in seconds, timeout in ms */ - timeout = (int)(s->sock_timeout * 1000 + 0.5); - PySSL_BEGIN_ALLOW_THREADS - rc = poll(&pollfd, 1, timeout); - PySSL_END_ALLOW_THREADS + { + struct pollfd pollfd; + int timeout; + + pollfd.fd = s->sock_fd; + pollfd.events = writing ? POLLOUT : POLLIN; + + /* s->sock_timeout is in seconds, timeout in ms */ + timeout = (int)(s->sock_timeout * 1000 + 0.5); + PySSL_BEGIN_ALLOW_THREADS + rc = poll(&pollfd, 1, timeout); + PySSL_END_ALLOW_THREADS - goto normal_return; - } + goto normal_return; + } #endif - /* Guard against socket too large for select*/ + /* Guard against socket too large for select*/ #ifndef Py_SOCKET_FD_CAN_BE_GE_FD_SETSIZE - if (s->sock_fd >= FD_SETSIZE) - return SOCKET_TOO_LARGE_FOR_SELECT; + if (s->sock_fd >= FD_SETSIZE) + return SOCKET_TOO_LARGE_FOR_SELECT; #endif - /* Construct the arguments to select */ - tv.tv_sec = (int)s->sock_timeout; - tv.tv_usec = (int)((s->sock_timeout - tv.tv_sec) * 1e6); - FD_ZERO(&fds); - FD_SET(s->sock_fd, &fds); - - /* See if the socket is ready */ - PySSL_BEGIN_ALLOW_THREADS - if (writing) - rc = select(s->sock_fd+1, NULL, &fds, NULL, &tv); - else - rc = select(s->sock_fd+1, &fds, NULL, NULL, &tv); - PySSL_END_ALLOW_THREADS + /* Construct the arguments to select */ + tv.tv_sec = (int)s->sock_timeout; + tv.tv_usec = (int)((s->sock_timeout - tv.tv_sec) * 1e6); + FD_ZERO(&fds); + FD_SET(s->sock_fd, &fds); + + /* See if the socket is ready */ + PySSL_BEGIN_ALLOW_THREADS + if (writing) + rc = select(s->sock_fd+1, NULL, &fds, NULL, &tv); + else + rc = select(s->sock_fd+1, &fds, NULL, NULL, &tv); + PySSL_END_ALLOW_THREADS #ifdef HAVE_POLL normal_return: #endif - /* Return SOCKET_TIMED_OUT on timeout, SOCKET_OPERATION_OK otherwise - (when we are able to write or when there's something to read) */ - return rc == 0 ? SOCKET_HAS_TIMED_OUT : SOCKET_OPERATION_OK; + /* Return SOCKET_TIMED_OUT on timeout, SOCKET_OPERATION_OK otherwise + (when we are able to write or when there's something to read) */ + return rc == 0 ? SOCKET_HAS_TIMED_OUT : SOCKET_OPERATION_OK; } static PyObject *PySSL_SSLwrite(PySSLObject *self, PyObject *args) { - char *data; - int len; - int count; - int sockstate; - int err; - int nonblocking; - - if (!PyArg_ParseTuple(args, "s#:write", &data, &count)) - return NULL; - - /* just in case the blocking state of the socket has been changed */ - nonblocking = (self->Socket->sock_timeout >= 0.0); - BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking); - BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking); - - sockstate = check_socket_and_wait_for_timeout(self->Socket, 1); - if (sockstate == SOCKET_HAS_TIMED_OUT) { - PyErr_SetString(PySSLErrorObject, - "The write operation timed out"); - return NULL; - } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) { - PyErr_SetString(PySSLErrorObject, - "Underlying socket has been closed."); - return NULL; - } else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) { - PyErr_SetString(PySSLErrorObject, - "Underlying socket too large for select()."); - return NULL; - } - do { - err = 0; - PySSL_BEGIN_ALLOW_THREADS - len = SSL_write(self->ssl, data, count); - err = SSL_get_error(self->ssl, len); - PySSL_END_ALLOW_THREADS - if(PyErr_CheckSignals()) { - return NULL; - } - if (err == SSL_ERROR_WANT_READ) { - sockstate = - check_socket_and_wait_for_timeout(self->Socket, 0); - } else if (err == SSL_ERROR_WANT_WRITE) { - sockstate = - check_socket_and_wait_for_timeout(self->Socket, 1); - } else { - sockstate = SOCKET_OPERATION_OK; - } - if (sockstate == SOCKET_HAS_TIMED_OUT) { - PyErr_SetString(PySSLErrorObject, - "The write operation timed out"); - return NULL; - } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) { - PyErr_SetString(PySSLErrorObject, - "Underlying socket has been closed."); - return NULL; - } else if (sockstate == SOCKET_IS_NONBLOCKING) { - break; - } - } while (err == SSL_ERROR_WANT_READ || err == SSL_ERROR_WANT_WRITE); - if (len > 0) - return PyInt_FromLong(len); - else - return PySSL_SetError(self, len, __FILE__, __LINE__); + char *data; + int len; + int count; + int sockstate; + int err; + int nonblocking; + + if (!PyArg_ParseTuple(args, "s#:write", &data, &count)) + return NULL; + + /* just in case the blocking state of the socket has been changed */ + nonblocking = (self->Socket->sock_timeout >= 0.0); + BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking); + BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking); + + sockstate = check_socket_and_wait_for_timeout(self->Socket, 1); + if (sockstate == SOCKET_HAS_TIMED_OUT) { + PyErr_SetString(PySSLErrorObject, + "The write operation timed out"); + return NULL; + } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) { + PyErr_SetString(PySSLErrorObject, + "Underlying socket has been closed."); + return NULL; + } else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) { + PyErr_SetString(PySSLErrorObject, + "Underlying socket too large for select()."); + return NULL; + } + do { + err = 0; + PySSL_BEGIN_ALLOW_THREADS + len = SSL_write(self->ssl, data, count); + err = SSL_get_error(self->ssl, len); + PySSL_END_ALLOW_THREADS + if(PyErr_CheckSignals()) { + return NULL; + } + if (err == SSL_ERROR_WANT_READ) { + sockstate = + check_socket_and_wait_for_timeout(self->Socket, 0); + } else if (err == SSL_ERROR_WANT_WRITE) { + sockstate = + check_socket_and_wait_for_timeout(self->Socket, 1); + } else { + sockstate = SOCKET_OPERATION_OK; + } + if (sockstate == SOCKET_HAS_TIMED_OUT) { + PyErr_SetString(PySSLErrorObject, + "The write operation timed out"); + return NULL; + } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) { + PyErr_SetString(PySSLErrorObject, + "Underlying socket has been closed."); + return NULL; + } else if (sockstate == SOCKET_IS_NONBLOCKING) { + break; + } + } while (err == SSL_ERROR_WANT_READ || err == SSL_ERROR_WANT_WRITE); + if (len > 0) + return PyInt_FromLong(len); + else + return PySSL_SetError(self, len, __FILE__, __LINE__); } PyDoc_STRVAR(PySSL_SSLwrite_doc, @@ -1227,15 +1227,15 @@ static PyObject *PySSL_SSLpending(PySSLObject *self) { - int count = 0; + int count = 0; - PySSL_BEGIN_ALLOW_THREADS - count = SSL_pending(self->ssl); - PySSL_END_ALLOW_THREADS - if (count < 0) - return PySSL_SetError(self, count, __FILE__, __LINE__); - else - return PyInt_FromLong(count); + PySSL_BEGIN_ALLOW_THREADS + count = SSL_pending(self->ssl); + PySSL_END_ALLOW_THREADS + if (count < 0) + return PySSL_SetError(self, count, __FILE__, __LINE__); + else + return PyInt_FromLong(count); } PyDoc_STRVAR(PySSL_SSLpending_doc, @@ -1246,97 +1246,97 @@ static PyObject *PySSL_SSLread(PySSLObject *self, PyObject *args) { - PyObject *buf; - int count = 0; - int len = 1024; - int sockstate; - int err; - int nonblocking; - - if (!PyArg_ParseTuple(args, "|i:read", &len)) - return NULL; - - if (!(buf = PyString_FromStringAndSize((char *) 0, len))) - return NULL; - - /* just in case the blocking state of the socket has been changed */ - nonblocking = (self->Socket->sock_timeout >= 0.0); - BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking); - BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking); - - /* first check if there are bytes ready to be read */ - PySSL_BEGIN_ALLOW_THREADS - count = SSL_pending(self->ssl); - PySSL_END_ALLOW_THREADS - - if (!count) { - sockstate = check_socket_and_wait_for_timeout(self->Socket, 0); - if (sockstate == SOCKET_HAS_TIMED_OUT) { - PyErr_SetString(PySSLErrorObject, - "The read operation timed out"); - Py_DECREF(buf); - return NULL; - } else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) { - PyErr_SetString(PySSLErrorObject, - "Underlying socket too large for select()."); - Py_DECREF(buf); - return NULL; - } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) { - if (SSL_get_shutdown(self->ssl) != - SSL_RECEIVED_SHUTDOWN) - { - Py_DECREF(buf); - PyErr_SetString(PySSLErrorObject, - "Socket closed without SSL shutdown handshake"); - return NULL; - } else { - /* should contain a zero-length string */ - _PyString_Resize(&buf, 0); - return buf; - } - } - } - do { - err = 0; - PySSL_BEGIN_ALLOW_THREADS - count = SSL_read(self->ssl, PyString_AsString(buf), len); - err = SSL_get_error(self->ssl, count); - PySSL_END_ALLOW_THREADS - if(PyErr_CheckSignals()) { - Py_DECREF(buf); - return NULL; - } - if (err == SSL_ERROR_WANT_READ) { - sockstate = - check_socket_and_wait_for_timeout(self->Socket, 0); - } else if (err == SSL_ERROR_WANT_WRITE) { - sockstate = - check_socket_and_wait_for_timeout(self->Socket, 1); - } else if ((err == SSL_ERROR_ZERO_RETURN) && - (SSL_get_shutdown(self->ssl) == - SSL_RECEIVED_SHUTDOWN)) - { - _PyString_Resize(&buf, 0); - return buf; - } else { - sockstate = SOCKET_OPERATION_OK; - } - if (sockstate == SOCKET_HAS_TIMED_OUT) { - PyErr_SetString(PySSLErrorObject, - "The read operation timed out"); - Py_DECREF(buf); - return NULL; - } else if (sockstate == SOCKET_IS_NONBLOCKING) { - break; - } - } while (err == SSL_ERROR_WANT_READ || err == SSL_ERROR_WANT_WRITE); - if (count <= 0) { - Py_DECREF(buf); - return PySSL_SetError(self, count, __FILE__, __LINE__); - } - if (count != len) - _PyString_Resize(&buf, count); - return buf; + PyObject *buf; + int count = 0; + int len = 1024; + int sockstate; + int err; + int nonblocking; + + if (!PyArg_ParseTuple(args, "|i:read", &len)) + return NULL; + + if (!(buf = PyString_FromStringAndSize((char *) 0, len))) + return NULL; + + /* just in case the blocking state of the socket has been changed */ + nonblocking = (self->Socket->sock_timeout >= 0.0); + BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking); + BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking); + + /* first check if there are bytes ready to be read */ + PySSL_BEGIN_ALLOW_THREADS + count = SSL_pending(self->ssl); + PySSL_END_ALLOW_THREADS + + if (!count) { + sockstate = check_socket_and_wait_for_timeout(self->Socket, 0); + if (sockstate == SOCKET_HAS_TIMED_OUT) { + PyErr_SetString(PySSLErrorObject, + "The read operation timed out"); + Py_DECREF(buf); + return NULL; + } else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) { + PyErr_SetString(PySSLErrorObject, + "Underlying socket too large for select()."); + Py_DECREF(buf); + return NULL; + } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) { + if (SSL_get_shutdown(self->ssl) != + SSL_RECEIVED_SHUTDOWN) + { + Py_DECREF(buf); + PyErr_SetString(PySSLErrorObject, + "Socket closed without SSL shutdown handshake"); + return NULL; + } else { + /* should contain a zero-length string */ + _PyString_Resize(&buf, 0); + return buf; + } + } + } + do { + err = 0; + PySSL_BEGIN_ALLOW_THREADS + count = SSL_read(self->ssl, PyString_AsString(buf), len); + err = SSL_get_error(self->ssl, count); + PySSL_END_ALLOW_THREADS + if(PyErr_CheckSignals()) { + Py_DECREF(buf); + return NULL; + } + if (err == SSL_ERROR_WANT_READ) { + sockstate = + check_socket_and_wait_for_timeout(self->Socket, 0); + } else if (err == SSL_ERROR_WANT_WRITE) { + sockstate = + check_socket_and_wait_for_timeout(self->Socket, 1); + } else if ((err == SSL_ERROR_ZERO_RETURN) && + (SSL_get_shutdown(self->ssl) == + SSL_RECEIVED_SHUTDOWN)) + { + _PyString_Resize(&buf, 0); + return buf; + } else { + sockstate = SOCKET_OPERATION_OK; + } + if (sockstate == SOCKET_HAS_TIMED_OUT) { + PyErr_SetString(PySSLErrorObject, + "The read operation timed out"); + Py_DECREF(buf); + return NULL; + } else if (sockstate == SOCKET_IS_NONBLOCKING) { + break; + } + } while (err == SSL_ERROR_WANT_READ || err == SSL_ERROR_WANT_WRITE); + if (count <= 0) { + Py_DECREF(buf); + return PySSL_SetError(self, count, __FILE__, __LINE__); + } + if (count != len) + _PyString_Resize(&buf, count); + return buf; } PyDoc_STRVAR(PySSL_SSLread_doc, @@ -1346,82 +1346,82 @@ static PyObject *PySSL_SSLshutdown(PySSLObject *self) { - int err, ssl_err, sockstate, nonblocking; - int zeros = 0; + int err, ssl_err, sockstate, nonblocking; + int zeros = 0; + + /* Guard against closed socket */ + if (self->Socket->sock_fd < 0) { + PyErr_SetString(PySSLErrorObject, + "Underlying socket has been closed."); + return NULL; + } + + /* Just in case the blocking state of the socket has been changed */ + nonblocking = (self->Socket->sock_timeout >= 0.0); + BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking); + BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking); + + while (1) { + PySSL_BEGIN_ALLOW_THREADS + /* Disable read-ahead so that unwrap can work correctly. + * Otherwise OpenSSL might read in too much data, + * eating clear text data that happens to be + * transmitted after the SSL shutdown. + * Should be safe to call repeatedly everytime this + * function is used and the shutdown_seen_zero != 0 + * condition is met. + */ + if (self->shutdown_seen_zero) + SSL_set_read_ahead(self->ssl, 0); + err = SSL_shutdown(self->ssl); + PySSL_END_ALLOW_THREADS + /* If err == 1, a secure shutdown with SSL_shutdown() is complete */ + if (err > 0) + break; + if (err == 0) { + /* Don't loop endlessly; instead preserve legacy + behaviour of trying SSL_shutdown() only twice. + This looks necessary for OpenSSL < 0.9.8m */ + if (++zeros > 1) + break; + /* Shutdown was sent, now try receiving */ + self->shutdown_seen_zero = 1; + continue; + } + + /* Possibly retry shutdown until timeout or failure */ + ssl_err = SSL_get_error(self->ssl, err); + if (ssl_err == SSL_ERROR_WANT_READ) + sockstate = check_socket_and_wait_for_timeout(self->Socket, 0); + else if (ssl_err == SSL_ERROR_WANT_WRITE) + sockstate = check_socket_and_wait_for_timeout(self->Socket, 1); + else + break; + if (sockstate == SOCKET_HAS_TIMED_OUT) { + if (ssl_err == SSL_ERROR_WANT_READ) + PyErr_SetString(PySSLErrorObject, + "The read operation timed out"); + else + PyErr_SetString(PySSLErrorObject, + "The write operation timed out"); + return NULL; + } + else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) { + PyErr_SetString(PySSLErrorObject, + "Underlying socket too large for select()."); + return NULL; + } + else if (sockstate != SOCKET_OPERATION_OK) + /* Retain the SSL error code */ + break; + } - /* Guard against closed socket */ - if (self->Socket->sock_fd < 0) { - PyErr_SetString(PySSLErrorObject, - "Underlying socket has been closed."); - return NULL; - } - - /* Just in case the blocking state of the socket has been changed */ - nonblocking = (self->Socket->sock_timeout >= 0.0); - BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking); - BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking); - - while (1) { - PySSL_BEGIN_ALLOW_THREADS - /* Disable read-ahead so that unwrap can work correctly. - * Otherwise OpenSSL might read in too much data, - * eating clear text data that happens to be - * transmitted after the SSL shutdown. - * Should be safe to call repeatedly everytime this - * function is used and the shutdown_seen_zero != 0 - * condition is met. - */ - if (self->shutdown_seen_zero) - SSL_set_read_ahead(self->ssl, 0); - err = SSL_shutdown(self->ssl); - PySSL_END_ALLOW_THREADS - /* If err == 1, a secure shutdown with SSL_shutdown() is complete */ - if (err > 0) - break; - if (err == 0) { - /* Don't loop endlessly; instead preserve legacy - behaviour of trying SSL_shutdown() only twice. - This looks necessary for OpenSSL < 0.9.8m */ - if (++zeros > 1) - break; - /* Shutdown was sent, now try receiving */ - self->shutdown_seen_zero = 1; - continue; - } - - /* Possibly retry shutdown until timeout or failure */ - ssl_err = SSL_get_error(self->ssl, err); - if (ssl_err == SSL_ERROR_WANT_READ) - sockstate = check_socket_and_wait_for_timeout(self->Socket, 0); - else if (ssl_err == SSL_ERROR_WANT_WRITE) - sockstate = check_socket_and_wait_for_timeout(self->Socket, 1); - else - break; - if (sockstate == SOCKET_HAS_TIMED_OUT) { - if (ssl_err == SSL_ERROR_WANT_READ) - PyErr_SetString(PySSLErrorObject, - "The read operation timed out"); - else - PyErr_SetString(PySSLErrorObject, - "The write operation timed out"); - return NULL; - } - else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) { - PyErr_SetString(PySSLErrorObject, - "Underlying socket too large for select()."); - return NULL; - } - else if (sockstate != SOCKET_OPERATION_OK) - /* Retain the SSL error code */ - break; - } - - if (err < 0) - return PySSL_SetError(self, err, __FILE__, __LINE__); - else { - Py_INCREF(self->Socket); - return (PyObject *) (self->Socket); - } + if (err < 0) + return PySSL_SetError(self, err, __FILE__, __LINE__); + else { + Py_INCREF(self->Socket); + return (PyObject *) (self->Socket); + } } PyDoc_STRVAR(PySSL_SSLshutdown_doc, @@ -1431,44 +1431,44 @@ the underlying socket object."); static PyMethodDef PySSLMethods[] = { - {"do_handshake", (PyCFunction)PySSL_SSLdo_handshake, METH_NOARGS}, - {"write", (PyCFunction)PySSL_SSLwrite, METH_VARARGS, - PySSL_SSLwrite_doc}, - {"read", (PyCFunction)PySSL_SSLread, METH_VARARGS, - PySSL_SSLread_doc}, - {"pending", (PyCFunction)PySSL_SSLpending, METH_NOARGS, - PySSL_SSLpending_doc}, - {"server", (PyCFunction)PySSL_server, METH_NOARGS}, - {"issuer", (PyCFunction)PySSL_issuer, METH_NOARGS}, - {"peer_certificate", (PyCFunction)PySSL_peercert, METH_VARARGS, - PySSL_peercert_doc}, - {"cipher", (PyCFunction)PySSL_cipher, METH_NOARGS}, - {"shutdown", (PyCFunction)PySSL_SSLshutdown, METH_NOARGS, - PySSL_SSLshutdown_doc}, - {NULL, NULL} + {"do_handshake", (PyCFunction)PySSL_SSLdo_handshake, METH_NOARGS}, + {"write", (PyCFunction)PySSL_SSLwrite, METH_VARARGS, + PySSL_SSLwrite_doc}, + {"read", (PyCFunction)PySSL_SSLread, METH_VARARGS, + PySSL_SSLread_doc}, + {"pending", (PyCFunction)PySSL_SSLpending, METH_NOARGS, + PySSL_SSLpending_doc}, + {"server", (PyCFunction)PySSL_server, METH_NOARGS}, + {"issuer", (PyCFunction)PySSL_issuer, METH_NOARGS}, + {"peer_certificate", (PyCFunction)PySSL_peercert, METH_VARARGS, + PySSL_peercert_doc}, + {"cipher", (PyCFunction)PySSL_cipher, METH_NOARGS}, + {"shutdown", (PyCFunction)PySSL_SSLshutdown, METH_NOARGS, + PySSL_SSLshutdown_doc}, + {NULL, NULL} }; static PyObject *PySSL_getattr(PySSLObject *self, char *name) { - return Py_FindMethod(PySSLMethods, (PyObject *)self, name); + return Py_FindMethod(PySSLMethods, (PyObject *)self, name); } static PyTypeObject PySSL_Type = { - PyVarObject_HEAD_INIT(NULL, 0) - "ssl.SSLContext", /*tp_name*/ - sizeof(PySSLObject), /*tp_basicsize*/ - 0, /*tp_itemsize*/ - /* methods */ - (destructor)PySSL_dealloc, /*tp_dealloc*/ - 0, /*tp_print*/ - (getattrfunc)PySSL_getattr, /*tp_getattr*/ - 0, /*tp_setattr*/ - 0, /*tp_compare*/ - 0, /*tp_repr*/ - 0, /*tp_as_number*/ - 0, /*tp_as_sequence*/ - 0, /*tp_as_mapping*/ - 0, /*tp_hash*/ + PyVarObject_HEAD_INIT(NULL, 0) + "ssl.SSLContext", /*tp_name*/ + sizeof(PySSLObject), /*tp_basicsize*/ + 0, /*tp_itemsize*/ + /* methods */ + (destructor)PySSL_dealloc, /*tp_dealloc*/ + 0, /*tp_print*/ + (getattrfunc)PySSL_getattr, /*tp_getattr*/ + 0, /*tp_setattr*/ + 0, /*tp_compare*/ + 0, /*tp_repr*/ + 0, /*tp_as_number*/ + 0, /*tp_as_sequence*/ + 0, /*tp_as_mapping*/ + 0, /*tp_hash*/ }; #ifdef HAVE_OPENSSL_RAND @@ -1482,7 +1482,7 @@ double entropy; if (!PyArg_ParseTuple(args, "s#d:RAND_add", &buf, &len, &entropy)) - return NULL; + return NULL; RAND_add(buf, len, entropy); Py_INCREF(Py_None); return Py_None; @@ -1513,15 +1513,15 @@ int bytes; if (!PyString_Check(arg)) - return PyErr_Format(PyExc_TypeError, - "RAND_egd() expected string, found %s", - Py_TYPE(arg)->tp_name); + return PyErr_Format(PyExc_TypeError, + "RAND_egd() expected string, found %s", + Py_TYPE(arg)->tp_name); bytes = RAND_egd(PyString_AS_STRING(arg)); if (bytes == -1) { - PyErr_SetString(PySSLErrorObject, - "EGD connection failed or EGD did not return " - "enough data to seed the PRNG"); - return NULL; + PyErr_SetString(PySSLErrorObject, + "EGD connection failed or EGD did not return " + "enough data to seed the PRNG"); + return NULL; } return PyInt_FromLong(bytes); } @@ -1538,19 +1538,19 @@ /* List of functions exported by this module. */ static PyMethodDef PySSL_methods[] = { - {"sslwrap", PySSL_sslwrap, - METH_VARARGS, ssl_doc}, - {"_test_decode_cert", PySSL_test_decode_certificate, - METH_VARARGS}, + {"sslwrap", PySSL_sslwrap, + METH_VARARGS, ssl_doc}, + {"_test_decode_cert", PySSL_test_decode_certificate, + METH_VARARGS}, #ifdef HAVE_OPENSSL_RAND - {"RAND_add", PySSL_RAND_add, METH_VARARGS, - PySSL_RAND_add_doc}, - {"RAND_egd", PySSL_RAND_egd, METH_O, - PySSL_RAND_egd_doc}, - {"RAND_status", (PyCFunction)PySSL_RAND_status, METH_NOARGS, - PySSL_RAND_status_doc}, + {"RAND_add", PySSL_RAND_add, METH_VARARGS, + PySSL_RAND_add_doc}, + {"RAND_egd", PySSL_RAND_egd, METH_O, + PySSL_RAND_egd_doc}, + {"RAND_status", (PyCFunction)PySSL_RAND_status, METH_NOARGS, + PySSL_RAND_status_doc}, #endif - {NULL, NULL} /* Sentinel */ + {NULL, NULL} /* Sentinel */ }; @@ -1562,64 +1562,64 @@ static PyThread_type_lock *_ssl_locks = NULL; static unsigned long _ssl_thread_id_function (void) { - return PyThread_get_thread_ident(); + return PyThread_get_thread_ident(); } static void _ssl_thread_locking_function (int mode, int n, const char *file, int line) { - /* this function is needed to perform locking on shared data - structures. (Note that OpenSSL uses a number of global data - structures that will be implicitly shared whenever multiple threads - use OpenSSL.) Multi-threaded applications will crash at random if - it is not set. - - locking_function() must be able to handle up to CRYPTO_num_locks() - different mutex locks. It sets the n-th lock if mode & CRYPTO_LOCK, and - releases it otherwise. - - file and line are the file number of the function setting the - lock. They can be useful for debugging. - */ - - if ((_ssl_locks == NULL) || - (n < 0) || ((unsigned)n >= _ssl_locks_count)) - return; - - if (mode & CRYPTO_LOCK) { - PyThread_acquire_lock(_ssl_locks[n], 1); - } else { - PyThread_release_lock(_ssl_locks[n]); - } + /* this function is needed to perform locking on shared data + structures. (Note that OpenSSL uses a number of global data + structures that will be implicitly shared whenever multiple threads + use OpenSSL.) Multi-threaded applications will crash at random if + it is not set. + + locking_function() must be able to handle up to CRYPTO_num_locks() + different mutex locks. It sets the n-th lock if mode & CRYPTO_LOCK, and + releases it otherwise. + + file and line are the file number of the function setting the + lock. They can be useful for debugging. + */ + + if ((_ssl_locks == NULL) || + (n < 0) || ((unsigned)n >= _ssl_locks_count)) + return; + + if (mode & CRYPTO_LOCK) { + PyThread_acquire_lock(_ssl_locks[n], 1); + } else { + PyThread_release_lock(_ssl_locks[n]); + } } static int _setup_ssl_threads(void) { - unsigned int i; + unsigned int i; - if (_ssl_locks == NULL) { - _ssl_locks_count = CRYPTO_num_locks(); - _ssl_locks = (PyThread_type_lock *) - malloc(sizeof(PyThread_type_lock) * _ssl_locks_count); - if (_ssl_locks == NULL) - return 0; - memset(_ssl_locks, 0, sizeof(PyThread_type_lock) * _ssl_locks_count); - for (i = 0; i < _ssl_locks_count; i++) { - _ssl_locks[i] = PyThread_allocate_lock(); - if (_ssl_locks[i] == NULL) { - unsigned int j; - for (j = 0; j < i; j++) { - PyThread_free_lock(_ssl_locks[j]); - } - free(_ssl_locks); - return 0; - } - } - CRYPTO_set_locking_callback(_ssl_thread_locking_function); - CRYPTO_set_id_callback(_ssl_thread_id_function); - } - return 1; + if (_ssl_locks == NULL) { + _ssl_locks_count = CRYPTO_num_locks(); + _ssl_locks = (PyThread_type_lock *) + malloc(sizeof(PyThread_type_lock) * _ssl_locks_count); + if (_ssl_locks == NULL) + return 0; + memset(_ssl_locks, 0, sizeof(PyThread_type_lock) * _ssl_locks_count); + for (i = 0; i < _ssl_locks_count; i++) { + _ssl_locks[i] = PyThread_allocate_lock(); + if (_ssl_locks[i] == NULL) { + unsigned int j; + for (j = 0; j < i; j++) { + PyThread_free_lock(_ssl_locks[j]); + } + free(_ssl_locks); + return 0; + } + } + CRYPTO_set_locking_callback(_ssl_thread_locking_function); + CRYPTO_set_id_callback(_ssl_thread_id_function); + } + return 1; } -#endif /* def HAVE_THREAD */ +#endif /* def HAVE_THREAD */ PyDoc_STRVAR(module_doc, "Implementation module for SSL socket operations. See the socket module\n\ @@ -1628,75 +1628,75 @@ PyMODINIT_FUNC init_ssl(void) { - PyObject *m, *d; + PyObject *m, *d; - Py_TYPE(&PySSL_Type) = &PyType_Type; + Py_TYPE(&PySSL_Type) = &PyType_Type; - m = Py_InitModule3("_ssl", PySSL_methods, module_doc); - if (m == NULL) - return; - d = PyModule_GetDict(m); - - /* Load _socket module and its C API */ - if (PySocketModule_ImportModuleAndAPI()) - return; - - /* Init OpenSSL */ - SSL_load_error_strings(); - SSL_library_init(); + m = Py_InitModule3("_ssl", PySSL_methods, module_doc); + if (m == NULL) + return; + d = PyModule_GetDict(m); + + /* Load _socket module and its C API */ + if (PySocketModule_ImportModuleAndAPI()) + return; + + /* Init OpenSSL */ + SSL_load_error_strings(); + SSL_library_init(); #ifdef WITH_THREAD - /* note that this will start threading if not already started */ - if (!_setup_ssl_threads()) { - return; - } + /* note that this will start threading if not already started */ + if (!_setup_ssl_threads()) { + return; + } #endif - OpenSSL_add_all_algorithms(); + OpenSSL_add_all_algorithms(); - /* Add symbols to module dict */ - PySSLErrorObject = PyErr_NewException("ssl.SSLError", - PySocketModule.error, - NULL); - if (PySSLErrorObject == NULL) - return; - if (PyDict_SetItemString(d, "SSLError", PySSLErrorObject) != 0) - return; - if (PyDict_SetItemString(d, "SSLType", - (PyObject *)&PySSL_Type) != 0) - return; - PyModule_AddIntConstant(m, "SSL_ERROR_ZERO_RETURN", - PY_SSL_ERROR_ZERO_RETURN); - PyModule_AddIntConstant(m, "SSL_ERROR_WANT_READ", - PY_SSL_ERROR_WANT_READ); - PyModule_AddIntConstant(m, "SSL_ERROR_WANT_WRITE", - PY_SSL_ERROR_WANT_WRITE); - PyModule_AddIntConstant(m, "SSL_ERROR_WANT_X509_LOOKUP", - PY_SSL_ERROR_WANT_X509_LOOKUP); - PyModule_AddIntConstant(m, "SSL_ERROR_SYSCALL", - PY_SSL_ERROR_SYSCALL); - PyModule_AddIntConstant(m, "SSL_ERROR_SSL", - PY_SSL_ERROR_SSL); - PyModule_AddIntConstant(m, "SSL_ERROR_WANT_CONNECT", - PY_SSL_ERROR_WANT_CONNECT); - /* non ssl.h errorcodes */ - PyModule_AddIntConstant(m, "SSL_ERROR_EOF", - PY_SSL_ERROR_EOF); - PyModule_AddIntConstant(m, "SSL_ERROR_INVALID_ERROR_CODE", - PY_SSL_ERROR_INVALID_ERROR_CODE); - /* cert requirements */ - PyModule_AddIntConstant(m, "CERT_NONE", - PY_SSL_CERT_NONE); - PyModule_AddIntConstant(m, "CERT_OPTIONAL", - PY_SSL_CERT_OPTIONAL); - PyModule_AddIntConstant(m, "CERT_REQUIRED", - PY_SSL_CERT_REQUIRED); - - /* protocol versions */ - PyModule_AddIntConstant(m, "PROTOCOL_SSLv2", - PY_SSL_VERSION_SSL2); - PyModule_AddIntConstant(m, "PROTOCOL_SSLv3", - PY_SSL_VERSION_SSL3); - PyModule_AddIntConstant(m, "PROTOCOL_SSLv23", - PY_SSL_VERSION_SSL23); - PyModule_AddIntConstant(m, "PROTOCOL_TLSv1", - PY_SSL_VERSION_TLS1); + /* Add symbols to module dict */ + PySSLErrorObject = PyErr_NewException("ssl.SSLError", + PySocketModule.error, + NULL); + if (PySSLErrorObject == NULL) + return; + if (PyDict_SetItemString(d, "SSLError", PySSLErrorObject) != 0) + return; + if (PyDict_SetItemString(d, "SSLType", + (PyObject *)&PySSL_Type) != 0) + return; + PyModule_AddIntConstant(m, "SSL_ERROR_ZERO_RETURN", + PY_SSL_ERROR_ZERO_RETURN); + PyModule_AddIntConstant(m, "SSL_ERROR_WANT_READ", + PY_SSL_ERROR_WANT_READ); + PyModule_AddIntConstant(m, "SSL_ERROR_WANT_WRITE", + PY_SSL_ERROR_WANT_WRITE); + PyModule_AddIntConstant(m, "SSL_ERROR_WANT_X509_LOOKUP", + PY_SSL_ERROR_WANT_X509_LOOKUP); + PyModule_AddIntConstant(m, "SSL_ERROR_SYSCALL", + PY_SSL_ERROR_SYSCALL); + PyModule_AddIntConstant(m, "SSL_ERROR_SSL", + PY_SSL_ERROR_SSL); + PyModule_AddIntConstant(m, "SSL_ERROR_WANT_CONNECT", + PY_SSL_ERROR_WANT_CONNECT); + /* non ssl.h errorcodes */ + PyModule_AddIntConstant(m, "SSL_ERROR_EOF", + PY_SSL_ERROR_EOF); + PyModule_AddIntConstant(m, "SSL_ERROR_INVALID_ERROR_CODE", + PY_SSL_ERROR_INVALID_ERROR_CODE); + /* cert requirements */ + PyModule_AddIntConstant(m, "CERT_NONE", + PY_SSL_CERT_NONE); + PyModule_AddIntConstant(m, "CERT_OPTIONAL", + PY_SSL_CERT_OPTIONAL); + PyModule_AddIntConstant(m, "CERT_REQUIRED", + PY_SSL_CERT_REQUIRED); + + /* protocol versions */ + PyModule_AddIntConstant(m, "PROTOCOL_SSLv2", + PY_SSL_VERSION_SSL2); + PyModule_AddIntConstant(m, "PROTOCOL_SSLv3", + PY_SSL_VERSION_SSL3); + PyModule_AddIntConstant(m, "PROTOCOL_SSLv23", + PY_SSL_VERSION_SSL23); + PyModule_AddIntConstant(m, "PROTOCOL_TLSv1", + PY_SSL_VERSION_TLS1); } From python-checkins at python.org Wed May 5 18:01:14 2010 From: python-checkins at python.org (antoine.pitrou) Date: Wed, 5 May 2010 18:01:14 +0200 (CEST) Subject: [Python-checkins] r80792 - in python/branches/release31-maint: Modules/_ssl.c Message-ID: <20100505160114.B68D2EEA00@mail.python.org> Author: antoine.pitrou Date: Wed May 5 18:01:14 2010 New Revision: 80792 Log: Merged revisions 80790 via svnmerge from svn+ssh://pythondev at svn.python.org/python/branches/py3k ................ r80790 | antoine.pitrou | 2010-05-05 17:57:33 +0200 (mer., 05 mai 2010) | 9 lines Merged revisions 80789 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r80789 | antoine.pitrou | 2010-05-05 17:53:45 +0200 (mer., 05 mai 2010) | 3 lines Untabify Modules/_ssl.c ........ ................ Modified: python/branches/release31-maint/ (props changed) python/branches/release31-maint/Modules/_ssl.c Modified: python/branches/release31-maint/Modules/_ssl.c ============================================================================== --- python/branches/release31-maint/Modules/_ssl.c (original) +++ python/branches/release31-maint/Modules/_ssl.c Wed May 5 18:01:14 2010 @@ -19,14 +19,14 @@ #ifdef WITH_THREAD #include "pythread.h" #define PySSL_BEGIN_ALLOW_THREADS { \ - PyThreadState *_save = NULL; \ - if (_ssl_locks_count>0) {_save = PyEval_SaveThread();} -#define PySSL_BLOCK_THREADS if (_ssl_locks_count>0){PyEval_RestoreThread(_save)}; -#define PySSL_UNBLOCK_THREADS if (_ssl_locks_count>0){_save = PyEval_SaveThread()}; -#define PySSL_END_ALLOW_THREADS if (_ssl_locks_count>0){PyEval_RestoreThread(_save);} \ - } + PyThreadState *_save = NULL; \ + if (_ssl_locks_count>0) {_save = PyEval_SaveThread();} +#define PySSL_BLOCK_THREADS if (_ssl_locks_count>0){PyEval_RestoreThread(_save)}; +#define PySSL_UNBLOCK_THREADS if (_ssl_locks_count>0){_save = PyEval_SaveThread()}; +#define PySSL_END_ALLOW_THREADS if (_ssl_locks_count>0){PyEval_RestoreThread(_save);} \ + } -#else /* no WITH_THREAD */ +#else /* no WITH_THREAD */ #define PySSL_BEGIN_ALLOW_THREADS #define PySSL_BLOCK_THREADS @@ -36,37 +36,37 @@ #endif enum py_ssl_error { - /* these mirror ssl.h */ - PY_SSL_ERROR_NONE, - PY_SSL_ERROR_SSL, - PY_SSL_ERROR_WANT_READ, - PY_SSL_ERROR_WANT_WRITE, - PY_SSL_ERROR_WANT_X509_LOOKUP, - PY_SSL_ERROR_SYSCALL, /* look at error stack/return value/errno */ - PY_SSL_ERROR_ZERO_RETURN, - PY_SSL_ERROR_WANT_CONNECT, - /* start of non ssl.h errorcodes */ - PY_SSL_ERROR_EOF, /* special case of SSL_ERROR_SYSCALL */ - PY_SSL_ERROR_NO_SOCKET, /* socket has been GC'd */ - PY_SSL_ERROR_INVALID_ERROR_CODE + /* these mirror ssl.h */ + PY_SSL_ERROR_NONE, + PY_SSL_ERROR_SSL, + PY_SSL_ERROR_WANT_READ, + PY_SSL_ERROR_WANT_WRITE, + PY_SSL_ERROR_WANT_X509_LOOKUP, + PY_SSL_ERROR_SYSCALL, /* look at error stack/return value/errno */ + PY_SSL_ERROR_ZERO_RETURN, + PY_SSL_ERROR_WANT_CONNECT, + /* start of non ssl.h errorcodes */ + PY_SSL_ERROR_EOF, /* special case of SSL_ERROR_SYSCALL */ + PY_SSL_ERROR_NO_SOCKET, /* socket has been GC'd */ + PY_SSL_ERROR_INVALID_ERROR_CODE }; enum py_ssl_server_or_client { - PY_SSL_CLIENT, - PY_SSL_SERVER + PY_SSL_CLIENT, + PY_SSL_SERVER }; enum py_ssl_cert_requirements { - PY_SSL_CERT_NONE, - PY_SSL_CERT_OPTIONAL, - PY_SSL_CERT_REQUIRED + PY_SSL_CERT_NONE, + PY_SSL_CERT_OPTIONAL, + PY_SSL_CERT_REQUIRED }; enum py_ssl_version { - PY_SSL_VERSION_SSL2, - PY_SSL_VERSION_SSL3, - PY_SSL_VERSION_SSL23, - PY_SSL_VERSION_TLS1 + PY_SSL_VERSION_SSL2, + PY_SSL_VERSION_SSL3, + PY_SSL_VERSION_SSL23, + PY_SSL_VERSION_TLS1 }; /* Include symbols from _socket module */ @@ -114,12 +114,12 @@ #endif typedef struct { - PyObject_HEAD - PyObject *Socket; /* weakref to socket on which we're layered */ - SSL_CTX* ctx; - SSL* ssl; - X509* peer_cert; - int shutdown_seen_zero; + PyObject_HEAD + PyObject *Socket; /* weakref to socket on which we're layered */ + SSL_CTX* ctx; + SSL* ssl; + X509* peer_cert; + int shutdown_seen_zero; } PySSLObject; @@ -127,19 +127,19 @@ static PyObject *PySSL_SSLwrite(PySSLObject *self, PyObject *args); static PyObject *PySSL_SSLread(PySSLObject *self, PyObject *args); static int check_socket_and_wait_for_timeout(PySocketSockObject *s, - int writing); + int writing); static PyObject *PySSL_peercert(PySSLObject *self, PyObject *args); static PyObject *PySSL_cipher(PySSLObject *self); -#define PySSLObject_Check(v) (Py_TYPE(v) == &PySSL_Type) +#define PySSLObject_Check(v) (Py_TYPE(v) == &PySSL_Type) typedef enum { - SOCKET_IS_NONBLOCKING, - SOCKET_IS_BLOCKING, - SOCKET_HAS_TIMED_OUT, - SOCKET_HAS_BEEN_CLOSED, - SOCKET_TOO_LARGE_FOR_SELECT, - SOCKET_OPERATION_OK + SOCKET_IS_NONBLOCKING, + SOCKET_IS_BLOCKING, + SOCKET_HAS_TIMED_OUT, + SOCKET_HAS_BEEN_CLOSED, + SOCKET_TOO_LARGE_FOR_SELECT, + SOCKET_OPERATION_OK } timeout_state; /* Wrap error strings with filename and line # */ @@ -156,283 +156,283 @@ static PyObject * PySSL_SetError(PySSLObject *obj, int ret, char *filename, int lineno) { - PyObject *v; - char buf[2048]; - char *errstr; - int err; - enum py_ssl_error p = PY_SSL_ERROR_NONE; - - assert(ret <= 0); - - if (obj->ssl != NULL) { - err = SSL_get_error(obj->ssl, ret); - - switch (err) { - case SSL_ERROR_ZERO_RETURN: - errstr = "TLS/SSL connection has been closed"; - p = PY_SSL_ERROR_ZERO_RETURN; - break; - case SSL_ERROR_WANT_READ: - errstr = "The operation did not complete (read)"; - p = PY_SSL_ERROR_WANT_READ; - break; - case SSL_ERROR_WANT_WRITE: - p = PY_SSL_ERROR_WANT_WRITE; - errstr = "The operation did not complete (write)"; - break; - case SSL_ERROR_WANT_X509_LOOKUP: - p = PY_SSL_ERROR_WANT_X509_LOOKUP; - errstr = - "The operation did not complete (X509 lookup)"; - break; - case SSL_ERROR_WANT_CONNECT: - p = PY_SSL_ERROR_WANT_CONNECT; - errstr = "The operation did not complete (connect)"; - break; - case SSL_ERROR_SYSCALL: - { - unsigned long e = ERR_get_error(); - if (e == 0) { - PySocketSockObject *s - = (PySocketSockObject *) PyWeakref_GetObject(obj->Socket); - if (ret == 0 || (((PyObject *)s) == Py_None)) { - p = PY_SSL_ERROR_EOF; - errstr = - "EOF occurred in violation of protocol"; - } else if (ret == -1) { - /* underlying BIO reported an I/O error */ - return s->errorhandler(); - } else { /* possible? */ - p = PY_SSL_ERROR_SYSCALL; - errstr = "Some I/O error occurred"; - } - } else { - p = PY_SSL_ERROR_SYSCALL; - /* XXX Protected by global interpreter lock */ - errstr = ERR_error_string(e, NULL); - } - break; - } - case SSL_ERROR_SSL: - { - unsigned long e = ERR_get_error(); - p = PY_SSL_ERROR_SSL; - if (e != 0) - /* XXX Protected by global interpreter lock */ - errstr = ERR_error_string(e, NULL); - else { /* possible? */ - errstr = - "A failure in the SSL library occurred"; - } - break; - } - default: - p = PY_SSL_ERROR_INVALID_ERROR_CODE; - errstr = "Invalid error code"; - } - } else { - errstr = ERR_error_string(ERR_peek_last_error(), NULL); - } - PyOS_snprintf(buf, sizeof(buf), "_ssl.c:%d: %s", lineno, errstr); - v = Py_BuildValue("(is)", p, buf); - if (v != NULL) { - PyErr_SetObject(PySSLErrorObject, v); - Py_DECREF(v); - } - return NULL; + PyObject *v; + char buf[2048]; + char *errstr; + int err; + enum py_ssl_error p = PY_SSL_ERROR_NONE; + + assert(ret <= 0); + + if (obj->ssl != NULL) { + err = SSL_get_error(obj->ssl, ret); + + switch (err) { + case SSL_ERROR_ZERO_RETURN: + errstr = "TLS/SSL connection has been closed"; + p = PY_SSL_ERROR_ZERO_RETURN; + break; + case SSL_ERROR_WANT_READ: + errstr = "The operation did not complete (read)"; + p = PY_SSL_ERROR_WANT_READ; + break; + case SSL_ERROR_WANT_WRITE: + p = PY_SSL_ERROR_WANT_WRITE; + errstr = "The operation did not complete (write)"; + break; + case SSL_ERROR_WANT_X509_LOOKUP: + p = PY_SSL_ERROR_WANT_X509_LOOKUP; + errstr = + "The operation did not complete (X509 lookup)"; + break; + case SSL_ERROR_WANT_CONNECT: + p = PY_SSL_ERROR_WANT_CONNECT; + errstr = "The operation did not complete (connect)"; + break; + case SSL_ERROR_SYSCALL: + { + unsigned long e = ERR_get_error(); + if (e == 0) { + PySocketSockObject *s + = (PySocketSockObject *) PyWeakref_GetObject(obj->Socket); + if (ret == 0 || (((PyObject *)s) == Py_None)) { + p = PY_SSL_ERROR_EOF; + errstr = + "EOF occurred in violation of protocol"; + } else if (ret == -1) { + /* underlying BIO reported an I/O error */ + return s->errorhandler(); + } else { /* possible? */ + p = PY_SSL_ERROR_SYSCALL; + errstr = "Some I/O error occurred"; + } + } else { + p = PY_SSL_ERROR_SYSCALL; + /* XXX Protected by global interpreter lock */ + errstr = ERR_error_string(e, NULL); + } + break; + } + case SSL_ERROR_SSL: + { + unsigned long e = ERR_get_error(); + p = PY_SSL_ERROR_SSL; + if (e != 0) + /* XXX Protected by global interpreter lock */ + errstr = ERR_error_string(e, NULL); + else { /* possible? */ + errstr = + "A failure in the SSL library occurred"; + } + break; + } + default: + p = PY_SSL_ERROR_INVALID_ERROR_CODE; + errstr = "Invalid error code"; + } + } else { + errstr = ERR_error_string(ERR_peek_last_error(), NULL); + } + PyOS_snprintf(buf, sizeof(buf), "_ssl.c:%d: %s", lineno, errstr); + v = Py_BuildValue("(is)", p, buf); + if (v != NULL) { + PyErr_SetObject(PySSLErrorObject, v); + Py_DECREF(v); + } + return NULL; } static PyObject * _setSSLError (char *errstr, int errcode, char *filename, int lineno) { - char buf[2048]; - PyObject *v; + char buf[2048]; + PyObject *v; - if (errstr == NULL) { - errcode = ERR_peek_last_error(); - errstr = ERR_error_string(errcode, NULL); - } - PyOS_snprintf(buf, sizeof(buf), "_ssl.c:%d: %s", lineno, errstr); - v = Py_BuildValue("(is)", errcode, buf); - if (v != NULL) { - PyErr_SetObject(PySSLErrorObject, v); - Py_DECREF(v); - } - return NULL; + if (errstr == NULL) { + errcode = ERR_peek_last_error(); + errstr = ERR_error_string(errcode, NULL); + } + PyOS_snprintf(buf, sizeof(buf), "_ssl.c:%d: %s", lineno, errstr); + v = Py_BuildValue("(is)", errcode, buf); + if (v != NULL) { + PyErr_SetObject(PySSLErrorObject, v); + Py_DECREF(v); + } + return NULL; } static PySSLObject * newPySSLObject(PySocketSockObject *Sock, char *key_file, char *cert_file, - enum py_ssl_server_or_client socket_type, - enum py_ssl_cert_requirements certreq, - enum py_ssl_version proto_version, - char *cacerts_file) + enum py_ssl_server_or_client socket_type, + enum py_ssl_cert_requirements certreq, + enum py_ssl_version proto_version, + char *cacerts_file) { - PySSLObject *self; - char *errstr = NULL; - int ret; - int verification_mode; - - self = PyObject_New(PySSLObject, &PySSL_Type); /* Create new object */ - if (self == NULL) - return NULL; - self->peer_cert = NULL; - self->ssl = NULL; - self->ctx = NULL; - self->Socket = NULL; - - /* Make sure the SSL error state is initialized */ - (void) ERR_get_state(); - ERR_clear_error(); - - if ((key_file && !cert_file) || (!key_file && cert_file)) { - errstr = ERRSTR("Both the key & certificate files " - "must be specified"); - goto fail; - } - - if ((socket_type == PY_SSL_SERVER) && - ((key_file == NULL) || (cert_file == NULL))) { - errstr = ERRSTR("Both the key & certificate files " - "must be specified for server-side operation"); - goto fail; - } - - PySSL_BEGIN_ALLOW_THREADS - if (proto_version == PY_SSL_VERSION_TLS1) - self->ctx = SSL_CTX_new(TLSv1_method()); /* Set up context */ - else if (proto_version == PY_SSL_VERSION_SSL3) - self->ctx = SSL_CTX_new(SSLv3_method()); /* Set up context */ - else if (proto_version == PY_SSL_VERSION_SSL2) - self->ctx = SSL_CTX_new(SSLv2_method()); /* Set up context */ - else if (proto_version == PY_SSL_VERSION_SSL23) - self->ctx = SSL_CTX_new(SSLv23_method()); /* Set up context */ - PySSL_END_ALLOW_THREADS - - if (self->ctx == NULL) { - errstr = ERRSTR("Invalid SSL protocol variant specified."); - goto fail; - } - - if (certreq != PY_SSL_CERT_NONE) { - if (cacerts_file == NULL) { - errstr = ERRSTR("No root certificates specified for " - "verification of other-side certificates."); - goto fail; - } else { - PySSL_BEGIN_ALLOW_THREADS - ret = SSL_CTX_load_verify_locations(self->ctx, - cacerts_file, - NULL); - PySSL_END_ALLOW_THREADS - if (ret != 1) { - _setSSLError(NULL, 0, __FILE__, __LINE__); - goto fail; - } - } - } - if (key_file) { - PySSL_BEGIN_ALLOW_THREADS - ret = SSL_CTX_use_PrivateKey_file(self->ctx, key_file, - SSL_FILETYPE_PEM); - PySSL_END_ALLOW_THREADS - if (ret != 1) { - _setSSLError(NULL, ret, __FILE__, __LINE__); - goto fail; - } - - PySSL_BEGIN_ALLOW_THREADS - ret = SSL_CTX_use_certificate_chain_file(self->ctx, - cert_file); - PySSL_END_ALLOW_THREADS - if (ret != 1) { - /* - fprintf(stderr, "ret is %d, errcode is %lu, %lu, with file \"%s\"\n", - ret, ERR_peek_error(), ERR_peek_last_error(), cert_file); - */ - if (ERR_peek_last_error() != 0) { - _setSSLError(NULL, ret, __FILE__, __LINE__); - goto fail; - } - } - } - - /* ssl compatibility */ - SSL_CTX_set_options(self->ctx, SSL_OP_ALL); - - verification_mode = SSL_VERIFY_NONE; - if (certreq == PY_SSL_CERT_OPTIONAL) - verification_mode = SSL_VERIFY_PEER; - else if (certreq == PY_SSL_CERT_REQUIRED) - verification_mode = (SSL_VERIFY_PEER | - SSL_VERIFY_FAIL_IF_NO_PEER_CERT); - SSL_CTX_set_verify(self->ctx, verification_mode, - NULL); /* set verify lvl */ - - PySSL_BEGIN_ALLOW_THREADS - self->ssl = SSL_new(self->ctx); /* New ssl struct */ - PySSL_END_ALLOW_THREADS - SSL_set_fd(self->ssl, Sock->sock_fd); /* Set the socket for SSL */ + PySSLObject *self; + char *errstr = NULL; + int ret; + int verification_mode; + + self = PyObject_New(PySSLObject, &PySSL_Type); /* Create new object */ + if (self == NULL) + return NULL; + self->peer_cert = NULL; + self->ssl = NULL; + self->ctx = NULL; + self->Socket = NULL; + + /* Make sure the SSL error state is initialized */ + (void) ERR_get_state(); + ERR_clear_error(); + + if ((key_file && !cert_file) || (!key_file && cert_file)) { + errstr = ERRSTR("Both the key & certificate files " + "must be specified"); + goto fail; + } + + if ((socket_type == PY_SSL_SERVER) && + ((key_file == NULL) || (cert_file == NULL))) { + errstr = ERRSTR("Both the key & certificate files " + "must be specified for server-side operation"); + goto fail; + } + + PySSL_BEGIN_ALLOW_THREADS + if (proto_version == PY_SSL_VERSION_TLS1) + self->ctx = SSL_CTX_new(TLSv1_method()); /* Set up context */ + else if (proto_version == PY_SSL_VERSION_SSL3) + self->ctx = SSL_CTX_new(SSLv3_method()); /* Set up context */ + else if (proto_version == PY_SSL_VERSION_SSL2) + self->ctx = SSL_CTX_new(SSLv2_method()); /* Set up context */ + else if (proto_version == PY_SSL_VERSION_SSL23) + self->ctx = SSL_CTX_new(SSLv23_method()); /* Set up context */ + PySSL_END_ALLOW_THREADS + + if (self->ctx == NULL) { + errstr = ERRSTR("Invalid SSL protocol variant specified."); + goto fail; + } + + if (certreq != PY_SSL_CERT_NONE) { + if (cacerts_file == NULL) { + errstr = ERRSTR("No root certificates specified for " + "verification of other-side certificates."); + goto fail; + } else { + PySSL_BEGIN_ALLOW_THREADS + ret = SSL_CTX_load_verify_locations(self->ctx, + cacerts_file, + NULL); + PySSL_END_ALLOW_THREADS + if (ret != 1) { + _setSSLError(NULL, 0, __FILE__, __LINE__); + goto fail; + } + } + } + if (key_file) { + PySSL_BEGIN_ALLOW_THREADS + ret = SSL_CTX_use_PrivateKey_file(self->ctx, key_file, + SSL_FILETYPE_PEM); + PySSL_END_ALLOW_THREADS + if (ret != 1) { + _setSSLError(NULL, ret, __FILE__, __LINE__); + goto fail; + } + + PySSL_BEGIN_ALLOW_THREADS + ret = SSL_CTX_use_certificate_chain_file(self->ctx, + cert_file); + PySSL_END_ALLOW_THREADS + if (ret != 1) { + /* + fprintf(stderr, "ret is %d, errcode is %lu, %lu, with file \"%s\"\n", + ret, ERR_peek_error(), ERR_peek_last_error(), cert_file); + */ + if (ERR_peek_last_error() != 0) { + _setSSLError(NULL, ret, __FILE__, __LINE__); + goto fail; + } + } + } + + /* ssl compatibility */ + SSL_CTX_set_options(self->ctx, SSL_OP_ALL); + + verification_mode = SSL_VERIFY_NONE; + if (certreq == PY_SSL_CERT_OPTIONAL) + verification_mode = SSL_VERIFY_PEER; + else if (certreq == PY_SSL_CERT_REQUIRED) + verification_mode = (SSL_VERIFY_PEER | + SSL_VERIFY_FAIL_IF_NO_PEER_CERT); + SSL_CTX_set_verify(self->ctx, verification_mode, + NULL); /* set verify lvl */ + + PySSL_BEGIN_ALLOW_THREADS + self->ssl = SSL_new(self->ctx); /* New ssl struct */ + PySSL_END_ALLOW_THREADS + SSL_set_fd(self->ssl, Sock->sock_fd); /* Set the socket for SSL */ #ifdef SSL_MODE_AUTO_RETRY - SSL_set_mode(self->ssl, SSL_MODE_AUTO_RETRY); + SSL_set_mode(self->ssl, SSL_MODE_AUTO_RETRY); #endif - /* If the socket is in non-blocking mode or timeout mode, set the BIO - * to non-blocking mode (blocking is the default) - */ - if (Sock->sock_timeout >= 0.0) { - /* Set both the read and write BIO's to non-blocking mode */ - BIO_set_nbio(SSL_get_rbio(self->ssl), 1); - BIO_set_nbio(SSL_get_wbio(self->ssl), 1); - } - - PySSL_BEGIN_ALLOW_THREADS - if (socket_type == PY_SSL_CLIENT) - SSL_set_connect_state(self->ssl); - else - SSL_set_accept_state(self->ssl); - PySSL_END_ALLOW_THREADS + /* If the socket is in non-blocking mode or timeout mode, set the BIO + * to non-blocking mode (blocking is the default) + */ + if (Sock->sock_timeout >= 0.0) { + /* Set both the read and write BIO's to non-blocking mode */ + BIO_set_nbio(SSL_get_rbio(self->ssl), 1); + BIO_set_nbio(SSL_get_wbio(self->ssl), 1); + } + + PySSL_BEGIN_ALLOW_THREADS + if (socket_type == PY_SSL_CLIENT) + SSL_set_connect_state(self->ssl); + else + SSL_set_accept_state(self->ssl); + PySSL_END_ALLOW_THREADS - self->Socket = PyWeakref_NewRef((PyObject *) Sock, Py_None); - return self; + self->Socket = PyWeakref_NewRef((PyObject *) Sock, Py_None); + return self; fail: - if (errstr) - PyErr_SetString(PySSLErrorObject, errstr); - Py_DECREF(self); - return NULL; + if (errstr) + PyErr_SetString(PySSLErrorObject, errstr); + Py_DECREF(self); + return NULL; } static PyObject * PySSL_sslwrap(PyObject *self, PyObject *args) { - PySocketSockObject *Sock; - int server_side = 0; - int verification_mode = PY_SSL_CERT_NONE; - int protocol = PY_SSL_VERSION_SSL23; - char *key_file = NULL; - char *cert_file = NULL; - char *cacerts_file = NULL; - - if (!PyArg_ParseTuple(args, "O!i|zziiz:sslwrap", - PySocketModule.Sock_Type, - &Sock, - &server_side, - &key_file, &cert_file, - &verification_mode, &protocol, - &cacerts_file)) - return NULL; - - /* - fprintf(stderr, - "server_side is %d, keyfile %p, certfile %p, verify_mode %d, " - "protocol %d, certs %p\n", - server_side, key_file, cert_file, verification_mode, - protocol, cacerts_file); - */ - - return (PyObject *) newPySSLObject(Sock, key_file, cert_file, - server_side, verification_mode, - protocol, cacerts_file); + PySocketSockObject *Sock; + int server_side = 0; + int verification_mode = PY_SSL_CERT_NONE; + int protocol = PY_SSL_VERSION_SSL23; + char *key_file = NULL; + char *cert_file = NULL; + char *cacerts_file = NULL; + + if (!PyArg_ParseTuple(args, "O!i|zziiz:sslwrap", + PySocketModule.Sock_Type, + &Sock, + &server_side, + &key_file, &cert_file, + &verification_mode, &protocol, + &cacerts_file)) + return NULL; + + /* + fprintf(stderr, + "server_side is %d, keyfile %p, certfile %p, verify_mode %d, " + "protocol %d, certs %p\n", + server_side, key_file, cert_file, verification_mode, + protocol, cacerts_file); + */ + + return (PyObject *) newPySSLObject(Sock, key_file, cert_file, + server_side, verification_mode, + protocol, cacerts_file); } PyDoc_STRVAR(ssl_doc, @@ -443,580 +443,580 @@ static PyObject *PySSL_SSLdo_handshake(PySSLObject *self) { - int ret; - int err; - int sockstate, nonblocking; - PySocketSockObject *sock - = (PySocketSockObject *) PyWeakref_GetObject(self->Socket); - - if (((PyObject*)sock) == Py_None) { - _setSSLError("Underlying socket connection gone", - PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__); - return NULL; - } - - /* just in case the blocking state of the socket has been changed */ - nonblocking = (sock->sock_timeout >= 0.0); - BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking); - BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking); - - /* Actually negotiate SSL connection */ - /* XXX If SSL_do_handshake() returns 0, it's also a failure. */ - sockstate = 0; - do { - PySSL_BEGIN_ALLOW_THREADS - ret = SSL_do_handshake(self->ssl); - err = SSL_get_error(self->ssl, ret); - PySSL_END_ALLOW_THREADS - if(PyErr_CheckSignals()) { - return NULL; - } - if (err == SSL_ERROR_WANT_READ) { - sockstate = check_socket_and_wait_for_timeout(sock, 0); - } else if (err == SSL_ERROR_WANT_WRITE) { - sockstate = check_socket_and_wait_for_timeout(sock, 1); - } else { - sockstate = SOCKET_OPERATION_OK; - } - if (sockstate == SOCKET_HAS_TIMED_OUT) { - PyErr_SetString(PySSLErrorObject, - ERRSTR("The handshake operation timed out")); - return NULL; - } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) { - PyErr_SetString(PySSLErrorObject, - ERRSTR("Underlying socket has been closed.")); - return NULL; - } else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) { - PyErr_SetString(PySSLErrorObject, - ERRSTR("Underlying socket too large for select().")); - return NULL; - } else if (sockstate == SOCKET_IS_NONBLOCKING) { - break; - } - } while (err == SSL_ERROR_WANT_READ || err == SSL_ERROR_WANT_WRITE); - if (ret < 1) - return PySSL_SetError(self, ret, __FILE__, __LINE__); - self->ssl->debug = 1; + int ret; + int err; + int sockstate, nonblocking; + PySocketSockObject *sock + = (PySocketSockObject *) PyWeakref_GetObject(self->Socket); + + if (((PyObject*)sock) == Py_None) { + _setSSLError("Underlying socket connection gone", + PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__); + return NULL; + } - if (self->peer_cert) - X509_free (self->peer_cert); + /* just in case the blocking state of the socket has been changed */ + nonblocking = (sock->sock_timeout >= 0.0); + BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking); + BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking); + + /* Actually negotiate SSL connection */ + /* XXX If SSL_do_handshake() returns 0, it's also a failure. */ + sockstate = 0; + do { PySSL_BEGIN_ALLOW_THREADS - self->peer_cert = SSL_get_peer_certificate(self->ssl); - PySSL_END_ALLOW_THREADS + ret = SSL_do_handshake(self->ssl); + err = SSL_get_error(self->ssl, ret); + PySSL_END_ALLOW_THREADS + if(PyErr_CheckSignals()) { + return NULL; + } + if (err == SSL_ERROR_WANT_READ) { + sockstate = check_socket_and_wait_for_timeout(sock, 0); + } else if (err == SSL_ERROR_WANT_WRITE) { + sockstate = check_socket_and_wait_for_timeout(sock, 1); + } else { + sockstate = SOCKET_OPERATION_OK; + } + if (sockstate == SOCKET_HAS_TIMED_OUT) { + PyErr_SetString(PySSLErrorObject, + ERRSTR("The handshake operation timed out")); + return NULL; + } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) { + PyErr_SetString(PySSLErrorObject, + ERRSTR("Underlying socket has been closed.")); + return NULL; + } else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) { + PyErr_SetString(PySSLErrorObject, + ERRSTR("Underlying socket too large for select().")); + return NULL; + } else if (sockstate == SOCKET_IS_NONBLOCKING) { + break; + } + } while (err == SSL_ERROR_WANT_READ || err == SSL_ERROR_WANT_WRITE); + if (ret < 1) + return PySSL_SetError(self, ret, __FILE__, __LINE__); + self->ssl->debug = 1; + + if (self->peer_cert) + X509_free (self->peer_cert); + PySSL_BEGIN_ALLOW_THREADS + self->peer_cert = SSL_get_peer_certificate(self->ssl); + PySSL_END_ALLOW_THREADS - Py_INCREF(Py_None); - return Py_None; + Py_INCREF(Py_None); + return Py_None; } static PyObject * _create_tuple_for_attribute (ASN1_OBJECT *name, ASN1_STRING *value) { - char namebuf[X509_NAME_MAXLEN]; - int buflen; - PyObject *name_obj; - PyObject *value_obj; - PyObject *attr; - unsigned char *valuebuf = NULL; - - buflen = OBJ_obj2txt(namebuf, sizeof(namebuf), name, 0); - if (buflen < 0) { - _setSSLError(NULL, 0, __FILE__, __LINE__); - goto fail; - } - name_obj = PyUnicode_FromStringAndSize(namebuf, buflen); - if (name_obj == NULL) - goto fail; - - buflen = ASN1_STRING_to_UTF8(&valuebuf, value); - if (buflen < 0) { - _setSSLError(NULL, 0, __FILE__, __LINE__); - Py_DECREF(name_obj); - goto fail; - } - value_obj = PyUnicode_DecodeUTF8((char *) valuebuf, - buflen, "strict"); - OPENSSL_free(valuebuf); - if (value_obj == NULL) { - Py_DECREF(name_obj); - goto fail; - } - attr = PyTuple_New(2); - if (attr == NULL) { - Py_DECREF(name_obj); - Py_DECREF(value_obj); - goto fail; - } - PyTuple_SET_ITEM(attr, 0, name_obj); - PyTuple_SET_ITEM(attr, 1, value_obj); - return attr; + char namebuf[X509_NAME_MAXLEN]; + int buflen; + PyObject *name_obj; + PyObject *value_obj; + PyObject *attr; + unsigned char *valuebuf = NULL; + + buflen = OBJ_obj2txt(namebuf, sizeof(namebuf), name, 0); + if (buflen < 0) { + _setSSLError(NULL, 0, __FILE__, __LINE__); + goto fail; + } + name_obj = PyUnicode_FromStringAndSize(namebuf, buflen); + if (name_obj == NULL) + goto fail; + + buflen = ASN1_STRING_to_UTF8(&valuebuf, value); + if (buflen < 0) { + _setSSLError(NULL, 0, __FILE__, __LINE__); + Py_DECREF(name_obj); + goto fail; + } + value_obj = PyUnicode_DecodeUTF8((char *) valuebuf, + buflen, "strict"); + OPENSSL_free(valuebuf); + if (value_obj == NULL) { + Py_DECREF(name_obj); + goto fail; + } + attr = PyTuple_New(2); + if (attr == NULL) { + Py_DECREF(name_obj); + Py_DECREF(value_obj); + goto fail; + } + PyTuple_SET_ITEM(attr, 0, name_obj); + PyTuple_SET_ITEM(attr, 1, value_obj); + return attr; fail: - return NULL; + return NULL; } static PyObject * _create_tuple_for_X509_NAME (X509_NAME *xname) { - PyObject *dn = NULL; /* tuple which represents the "distinguished name" */ - PyObject *rdn = NULL; /* tuple to hold a "relative distinguished name" */ - PyObject *rdnt; - PyObject *attr = NULL; /* tuple to hold an attribute */ - int entry_count = X509_NAME_entry_count(xname); - X509_NAME_ENTRY *entry; - ASN1_OBJECT *name; - ASN1_STRING *value; - int index_counter; - int rdn_level = -1; - int retcode; - - dn = PyList_New(0); - if (dn == NULL) - return NULL; - /* now create another tuple to hold the top-level RDN */ - rdn = PyList_New(0); - if (rdn == NULL) - goto fail0; - - for (index_counter = 0; - index_counter < entry_count; - index_counter++) - { - entry = X509_NAME_get_entry(xname, index_counter); - - /* check to see if we've gotten to a new RDN */ - if (rdn_level >= 0) { - if (rdn_level != entry->set) { - /* yes, new RDN */ - /* add old RDN to DN */ - rdnt = PyList_AsTuple(rdn); - Py_DECREF(rdn); - if (rdnt == NULL) - goto fail0; - retcode = PyList_Append(dn, rdnt); - Py_DECREF(rdnt); - if (retcode < 0) - goto fail0; - /* create new RDN */ - rdn = PyList_New(0); - if (rdn == NULL) - goto fail0; - } - } - rdn_level = entry->set; - - /* now add this attribute to the current RDN */ - name = X509_NAME_ENTRY_get_object(entry); - value = X509_NAME_ENTRY_get_data(entry); - attr = _create_tuple_for_attribute(name, value); - /* - fprintf(stderr, "RDN level %d, attribute %s: %s\n", - entry->set, - PyBytes_AS_STRING(PyTuple_GET_ITEM(attr, 0)), - PyBytes_AS_STRING(PyTuple_GET_ITEM(attr, 1))); - */ - if (attr == NULL) - goto fail1; - retcode = PyList_Append(rdn, attr); - Py_DECREF(attr); - if (retcode < 0) - goto fail1; - } - /* now, there's typically a dangling RDN */ - if ((rdn != NULL) && (PyList_Size(rdn) > 0)) { - rdnt = PyList_AsTuple(rdn); - Py_DECREF(rdn); - if (rdnt == NULL) - goto fail0; - retcode = PyList_Append(dn, rdnt); - Py_DECREF(rdnt); - if (retcode < 0) - goto fail0; - } - - /* convert list to tuple */ - rdnt = PyList_AsTuple(dn); - Py_DECREF(dn); - if (rdnt == NULL) - return NULL; - return rdnt; + PyObject *dn = NULL; /* tuple which represents the "distinguished name" */ + PyObject *rdn = NULL; /* tuple to hold a "relative distinguished name" */ + PyObject *rdnt; + PyObject *attr = NULL; /* tuple to hold an attribute */ + int entry_count = X509_NAME_entry_count(xname); + X509_NAME_ENTRY *entry; + ASN1_OBJECT *name; + ASN1_STRING *value; + int index_counter; + int rdn_level = -1; + int retcode; + + dn = PyList_New(0); + if (dn == NULL) + return NULL; + /* now create another tuple to hold the top-level RDN */ + rdn = PyList_New(0); + if (rdn == NULL) + goto fail0; + + for (index_counter = 0; + index_counter < entry_count; + index_counter++) + { + entry = X509_NAME_get_entry(xname, index_counter); + + /* check to see if we've gotten to a new RDN */ + if (rdn_level >= 0) { + if (rdn_level != entry->set) { + /* yes, new RDN */ + /* add old RDN to DN */ + rdnt = PyList_AsTuple(rdn); + Py_DECREF(rdn); + if (rdnt == NULL) + goto fail0; + retcode = PyList_Append(dn, rdnt); + Py_DECREF(rdnt); + if (retcode < 0) + goto fail0; + /* create new RDN */ + rdn = PyList_New(0); + if (rdn == NULL) + goto fail0; + } + } + rdn_level = entry->set; + + /* now add this attribute to the current RDN */ + name = X509_NAME_ENTRY_get_object(entry); + value = X509_NAME_ENTRY_get_data(entry); + attr = _create_tuple_for_attribute(name, value); + /* + fprintf(stderr, "RDN level %d, attribute %s: %s\n", + entry->set, + PyBytes_AS_STRING(PyTuple_GET_ITEM(attr, 0)), + PyBytes_AS_STRING(PyTuple_GET_ITEM(attr, 1))); + */ + if (attr == NULL) + goto fail1; + retcode = PyList_Append(rdn, attr); + Py_DECREF(attr); + if (retcode < 0) + goto fail1; + } + /* now, there's typically a dangling RDN */ + if ((rdn != NULL) && (PyList_Size(rdn) > 0)) { + rdnt = PyList_AsTuple(rdn); + Py_DECREF(rdn); + if (rdnt == NULL) + goto fail0; + retcode = PyList_Append(dn, rdnt); + Py_DECREF(rdnt); + if (retcode < 0) + goto fail0; + } + + /* convert list to tuple */ + rdnt = PyList_AsTuple(dn); + Py_DECREF(dn); + if (rdnt == NULL) + return NULL; + return rdnt; fail1: - Py_XDECREF(rdn); + Py_XDECREF(rdn); fail0: - Py_XDECREF(dn); - return NULL; + Py_XDECREF(dn); + return NULL; } static PyObject * _get_peer_alt_names (X509 *certificate) { - /* this code follows the procedure outlined in - OpenSSL's crypto/x509v3/v3_prn.c:X509v3_EXT_print() - function to extract the STACK_OF(GENERAL_NAME), - then iterates through the stack to add the - names. */ - - int i, j; - PyObject *peer_alt_names = Py_None; - PyObject *v, *t; - X509_EXTENSION *ext = NULL; - GENERAL_NAMES *names = NULL; - GENERAL_NAME *name; - X509V3_EXT_METHOD *method; - BIO *biobuf = NULL; - char buf[2048]; - char *vptr; - int len; - /* Issue #2973: ASN1_item_d2i() API changed in OpenSSL 0.9.6m */ + /* this code follows the procedure outlined in + OpenSSL's crypto/x509v3/v3_prn.c:X509v3_EXT_print() + function to extract the STACK_OF(GENERAL_NAME), + then iterates through the stack to add the + names. */ + + int i, j; + PyObject *peer_alt_names = Py_None; + PyObject *v, *t; + X509_EXTENSION *ext = NULL; + GENERAL_NAMES *names = NULL; + GENERAL_NAME *name; + X509V3_EXT_METHOD *method; + BIO *biobuf = NULL; + char buf[2048]; + char *vptr; + int len; + /* Issue #2973: ASN1_item_d2i() API changed in OpenSSL 0.9.6m */ #if OPENSSL_VERSION_NUMBER >= 0x009060dfL - const unsigned char *p; + const unsigned char *p; #else - unsigned char *p; + unsigned char *p; #endif - if (certificate == NULL) - return peer_alt_names; + if (certificate == NULL) + return peer_alt_names; + + /* get a memory buffer */ + biobuf = BIO_new(BIO_s_mem()); + + i = 0; + while ((i = X509_get_ext_by_NID( + certificate, NID_subject_alt_name, i)) >= 0) { + + if (peer_alt_names == Py_None) { + peer_alt_names = PyList_New(0); + if (peer_alt_names == NULL) + goto fail; + } - /* get a memory buffer */ - biobuf = BIO_new(BIO_s_mem()); + /* now decode the altName */ + ext = X509_get_ext(certificate, i); + if(!(method = X509V3_EXT_get(ext))) { + PyErr_SetString + (PySSLErrorObject, + ERRSTR("No method for internalizing subjectAltName!")); + goto fail; + } - i = 0; - while ((i = X509_get_ext_by_NID( - certificate, NID_subject_alt_name, i)) >= 0) { - - if (peer_alt_names == Py_None) { - peer_alt_names = PyList_New(0); - if (peer_alt_names == NULL) - goto fail; - } - - /* now decode the altName */ - ext = X509_get_ext(certificate, i); - if(!(method = X509V3_EXT_get(ext))) { - PyErr_SetString - (PySSLErrorObject, - ERRSTR("No method for internalizing subjectAltName!")); - goto fail; - } - - p = ext->value->data; - if (method->it) - names = (GENERAL_NAMES*) - (ASN1_item_d2i(NULL, - &p, - ext->value->length, - ASN1_ITEM_ptr(method->it))); - else - names = (GENERAL_NAMES*) - (method->d2i(NULL, - &p, - ext->value->length)); - - for(j = 0; j < sk_GENERAL_NAME_num(names); j++) { - - /* get a rendering of each name in the set of names */ - - name = sk_GENERAL_NAME_value(names, j); - if (name->type == GEN_DIRNAME) { - - /* we special-case DirName as a tuple of - tuples of attributes */ - - t = PyTuple_New(2); - if (t == NULL) { - goto fail; - } - - v = PyUnicode_FromString("DirName"); - if (v == NULL) { - Py_DECREF(t); - goto fail; - } - PyTuple_SET_ITEM(t, 0, v); - - v = _create_tuple_for_X509_NAME (name->d.dirn); - if (v == NULL) { - Py_DECREF(t); - goto fail; - } - PyTuple_SET_ITEM(t, 1, v); - - } else { - - /* for everything else, we use the OpenSSL print form */ - - (void) BIO_reset(biobuf); - GENERAL_NAME_print(biobuf, name); - len = BIO_gets(biobuf, buf, sizeof(buf)-1); - if (len < 0) { - _setSSLError(NULL, 0, __FILE__, __LINE__); - goto fail; - } - vptr = strchr(buf, ':'); - if (vptr == NULL) - goto fail; - t = PyTuple_New(2); - if (t == NULL) - goto fail; - v = PyUnicode_FromStringAndSize(buf, (vptr - buf)); - if (v == NULL) { - Py_DECREF(t); - goto fail; - } - PyTuple_SET_ITEM(t, 0, v); - v = PyUnicode_FromStringAndSize((vptr + 1), - (len - (vptr - buf + 1))); - if (v == NULL) { - Py_DECREF(t); - goto fail; - } - PyTuple_SET_ITEM(t, 1, v); - } - - /* and add that rendering to the list */ - - if (PyList_Append(peer_alt_names, t) < 0) { - Py_DECREF(t); - goto fail; - } - Py_DECREF(t); - } - } - BIO_free(biobuf); - if (peer_alt_names != Py_None) { - v = PyList_AsTuple(peer_alt_names); - Py_DECREF(peer_alt_names); - return v; - } else { - return peer_alt_names; - } + p = ext->value->data; + if (method->it) + names = (GENERAL_NAMES*) + (ASN1_item_d2i(NULL, + &p, + ext->value->length, + ASN1_ITEM_ptr(method->it))); + else + names = (GENERAL_NAMES*) + (method->d2i(NULL, + &p, + ext->value->length)); + + for(j = 0; j < sk_GENERAL_NAME_num(names); j++) { + + /* get a rendering of each name in the set of names */ + + name = sk_GENERAL_NAME_value(names, j); + if (name->type == GEN_DIRNAME) { + + /* we special-case DirName as a tuple of + tuples of attributes */ + + t = PyTuple_New(2); + if (t == NULL) { + goto fail; + } + + v = PyUnicode_FromString("DirName"); + if (v == NULL) { + Py_DECREF(t); + goto fail; + } + PyTuple_SET_ITEM(t, 0, v); + + v = _create_tuple_for_X509_NAME (name->d.dirn); + if (v == NULL) { + Py_DECREF(t); + goto fail; + } + PyTuple_SET_ITEM(t, 1, v); + + } else { + + /* for everything else, we use the OpenSSL print form */ + + (void) BIO_reset(biobuf); + GENERAL_NAME_print(biobuf, name); + len = BIO_gets(biobuf, buf, sizeof(buf)-1); + if (len < 0) { + _setSSLError(NULL, 0, __FILE__, __LINE__); + goto fail; + } + vptr = strchr(buf, ':'); + if (vptr == NULL) + goto fail; + t = PyTuple_New(2); + if (t == NULL) + goto fail; + v = PyUnicode_FromStringAndSize(buf, (vptr - buf)); + if (v == NULL) { + Py_DECREF(t); + goto fail; + } + PyTuple_SET_ITEM(t, 0, v); + v = PyUnicode_FromStringAndSize((vptr + 1), + (len - (vptr - buf + 1))); + if (v == NULL) { + Py_DECREF(t); + goto fail; + } + PyTuple_SET_ITEM(t, 1, v); + } + + /* and add that rendering to the list */ + + if (PyList_Append(peer_alt_names, t) < 0) { + Py_DECREF(t); + goto fail; + } + Py_DECREF(t); + } + } + BIO_free(biobuf); + if (peer_alt_names != Py_None) { + v = PyList_AsTuple(peer_alt_names); + Py_DECREF(peer_alt_names); + return v; + } else { + return peer_alt_names; + } fail: - if (biobuf != NULL) - BIO_free(biobuf); + if (biobuf != NULL) + BIO_free(biobuf); - if (peer_alt_names != Py_None) { - Py_XDECREF(peer_alt_names); - } + if (peer_alt_names != Py_None) { + Py_XDECREF(peer_alt_names); + } - return NULL; + return NULL; } static PyObject * _decode_certificate (X509 *certificate, int verbose) { - PyObject *retval = NULL; - BIO *biobuf = NULL; - PyObject *peer; - PyObject *peer_alt_names = NULL; - PyObject *issuer; - PyObject *version; - PyObject *sn_obj; - ASN1_INTEGER *serialNumber; - char buf[2048]; - int len; - ASN1_TIME *notBefore, *notAfter; - PyObject *pnotBefore, *pnotAfter; - - retval = PyDict_New(); - if (retval == NULL) - return NULL; - - peer = _create_tuple_for_X509_NAME( - X509_get_subject_name(certificate)); - if (peer == NULL) - goto fail0; - if (PyDict_SetItemString(retval, (const char *) "subject", peer) < 0) { - Py_DECREF(peer); - goto fail0; - } - Py_DECREF(peer); - - if (verbose) { - issuer = _create_tuple_for_X509_NAME( - X509_get_issuer_name(certificate)); - if (issuer == NULL) - goto fail0; - if (PyDict_SetItemString(retval, (const char *)"issuer", issuer) < 0) { - Py_DECREF(issuer); - goto fail0; - } - Py_DECREF(issuer); - - version = PyLong_FromLong(X509_get_version(certificate) + 1); - if (PyDict_SetItemString(retval, "version", version) < 0) { - Py_DECREF(version); - goto fail0; - } - Py_DECREF(version); - } - - /* get a memory buffer */ - biobuf = BIO_new(BIO_s_mem()); - - if (verbose) { - - (void) BIO_reset(biobuf); - serialNumber = X509_get_serialNumber(certificate); - /* should not exceed 20 octets, 160 bits, so buf is big enough */ - i2a_ASN1_INTEGER(biobuf, serialNumber); - len = BIO_gets(biobuf, buf, sizeof(buf)-1); - if (len < 0) { - _setSSLError(NULL, 0, __FILE__, __LINE__); - goto fail1; - } - sn_obj = PyUnicode_FromStringAndSize(buf, len); - if (sn_obj == NULL) - goto fail1; - if (PyDict_SetItemString(retval, "serialNumber", sn_obj) < 0) { - Py_DECREF(sn_obj); - goto fail1; - } - Py_DECREF(sn_obj); - - (void) BIO_reset(biobuf); - notBefore = X509_get_notBefore(certificate); - ASN1_TIME_print(biobuf, notBefore); - len = BIO_gets(biobuf, buf, sizeof(buf)-1); - if (len < 0) { - _setSSLError(NULL, 0, __FILE__, __LINE__); - goto fail1; - } - pnotBefore = PyUnicode_FromStringAndSize(buf, len); - if (pnotBefore == NULL) - goto fail1; - if (PyDict_SetItemString(retval, "notBefore", pnotBefore) < 0) { - Py_DECREF(pnotBefore); - goto fail1; - } - Py_DECREF(pnotBefore); - } - - (void) BIO_reset(biobuf); - notAfter = X509_get_notAfter(certificate); - ASN1_TIME_print(biobuf, notAfter); - len = BIO_gets(biobuf, buf, sizeof(buf)-1); - if (len < 0) { - _setSSLError(NULL, 0, __FILE__, __LINE__); - goto fail1; - } - pnotAfter = PyUnicode_FromStringAndSize(buf, len); - if (pnotAfter == NULL) - goto fail1; - if (PyDict_SetItemString(retval, "notAfter", pnotAfter) < 0) { - Py_DECREF(pnotAfter); - goto fail1; - } - Py_DECREF(pnotAfter); - - /* Now look for subjectAltName */ - - peer_alt_names = _get_peer_alt_names(certificate); - if (peer_alt_names == NULL) - goto fail1; - else if (peer_alt_names != Py_None) { - if (PyDict_SetItemString(retval, "subjectAltName", - peer_alt_names) < 0) { - Py_DECREF(peer_alt_names); - goto fail1; - } - Py_DECREF(peer_alt_names); - } + PyObject *retval = NULL; + BIO *biobuf = NULL; + PyObject *peer; + PyObject *peer_alt_names = NULL; + PyObject *issuer; + PyObject *version; + PyObject *sn_obj; + ASN1_INTEGER *serialNumber; + char buf[2048]; + int len; + ASN1_TIME *notBefore, *notAfter; + PyObject *pnotBefore, *pnotAfter; + + retval = PyDict_New(); + if (retval == NULL) + return NULL; + + peer = _create_tuple_for_X509_NAME( + X509_get_subject_name(certificate)); + if (peer == NULL) + goto fail0; + if (PyDict_SetItemString(retval, (const char *) "subject", peer) < 0) { + Py_DECREF(peer); + goto fail0; + } + Py_DECREF(peer); + + if (verbose) { + issuer = _create_tuple_for_X509_NAME( + X509_get_issuer_name(certificate)); + if (issuer == NULL) + goto fail0; + if (PyDict_SetItemString(retval, (const char *)"issuer", issuer) < 0) { + Py_DECREF(issuer); + goto fail0; + } + Py_DECREF(issuer); + + version = PyLong_FromLong(X509_get_version(certificate) + 1); + if (PyDict_SetItemString(retval, "version", version) < 0) { + Py_DECREF(version); + goto fail0; + } + Py_DECREF(version); + } + + /* get a memory buffer */ + biobuf = BIO_new(BIO_s_mem()); + + if (verbose) { + + (void) BIO_reset(biobuf); + serialNumber = X509_get_serialNumber(certificate); + /* should not exceed 20 octets, 160 bits, so buf is big enough */ + i2a_ASN1_INTEGER(biobuf, serialNumber); + len = BIO_gets(biobuf, buf, sizeof(buf)-1); + if (len < 0) { + _setSSLError(NULL, 0, __FILE__, __LINE__); + goto fail1; + } + sn_obj = PyUnicode_FromStringAndSize(buf, len); + if (sn_obj == NULL) + goto fail1; + if (PyDict_SetItemString(retval, "serialNumber", sn_obj) < 0) { + Py_DECREF(sn_obj); + goto fail1; + } + Py_DECREF(sn_obj); + + (void) BIO_reset(biobuf); + notBefore = X509_get_notBefore(certificate); + ASN1_TIME_print(biobuf, notBefore); + len = BIO_gets(biobuf, buf, sizeof(buf)-1); + if (len < 0) { + _setSSLError(NULL, 0, __FILE__, __LINE__); + goto fail1; + } + pnotBefore = PyUnicode_FromStringAndSize(buf, len); + if (pnotBefore == NULL) + goto fail1; + if (PyDict_SetItemString(retval, "notBefore", pnotBefore) < 0) { + Py_DECREF(pnotBefore); + goto fail1; + } + Py_DECREF(pnotBefore); + } + + (void) BIO_reset(biobuf); + notAfter = X509_get_notAfter(certificate); + ASN1_TIME_print(biobuf, notAfter); + len = BIO_gets(biobuf, buf, sizeof(buf)-1); + if (len < 0) { + _setSSLError(NULL, 0, __FILE__, __LINE__); + goto fail1; + } + pnotAfter = PyUnicode_FromStringAndSize(buf, len); + if (pnotAfter == NULL) + goto fail1; + if (PyDict_SetItemString(retval, "notAfter", pnotAfter) < 0) { + Py_DECREF(pnotAfter); + goto fail1; + } + Py_DECREF(pnotAfter); + + /* Now look for subjectAltName */ + + peer_alt_names = _get_peer_alt_names(certificate); + if (peer_alt_names == NULL) + goto fail1; + else if (peer_alt_names != Py_None) { + if (PyDict_SetItemString(retval, "subjectAltName", + peer_alt_names) < 0) { + Py_DECREF(peer_alt_names); + goto fail1; + } + Py_DECREF(peer_alt_names); + } - BIO_free(biobuf); - return retval; + BIO_free(biobuf); + return retval; fail1: - if (biobuf != NULL) - BIO_free(biobuf); + if (biobuf != NULL) + BIO_free(biobuf); fail0: - Py_XDECREF(retval); - return NULL; + Py_XDECREF(retval); + return NULL; } static PyObject * PySSL_test_decode_certificate (PyObject *mod, PyObject *args) { - PyObject *retval = NULL; - char *filename = NULL; - X509 *x=NULL; - BIO *cert; - int verbose = 1; - - if (!PyArg_ParseTuple(args, "s|i:test_decode_certificate", - &filename, &verbose)) - return NULL; - - if ((cert=BIO_new(BIO_s_file())) == NULL) { - PyErr_SetString(PySSLErrorObject, - "Can't malloc memory to read file"); - goto fail0; - } - - if (BIO_read_filename(cert,filename) <= 0) { - PyErr_SetString(PySSLErrorObject, - "Can't open file"); - goto fail0; - } - - x = PEM_read_bio_X509_AUX(cert,NULL, NULL, NULL); - if (x == NULL) { - PyErr_SetString(PySSLErrorObject, - "Error decoding PEM-encoded file"); - goto fail0; - } + PyObject *retval = NULL; + char *filename = NULL; + X509 *x=NULL; + BIO *cert; + int verbose = 1; + + if (!PyArg_ParseTuple(args, "s|i:test_decode_certificate", + &filename, &verbose)) + return NULL; + + if ((cert=BIO_new(BIO_s_file())) == NULL) { + PyErr_SetString(PySSLErrorObject, + "Can't malloc memory to read file"); + goto fail0; + } + + if (BIO_read_filename(cert,filename) <= 0) { + PyErr_SetString(PySSLErrorObject, + "Can't open file"); + goto fail0; + } + + x = PEM_read_bio_X509_AUX(cert,NULL, NULL, NULL); + if (x == NULL) { + PyErr_SetString(PySSLErrorObject, + "Error decoding PEM-encoded file"); + goto fail0; + } - retval = _decode_certificate(x, verbose); + retval = _decode_certificate(x, verbose); fail0: - if (cert != NULL) BIO_free(cert); - return retval; + if (cert != NULL) BIO_free(cert); + return retval; } static PyObject * PySSL_peercert(PySSLObject *self, PyObject *args) { - PyObject *retval = NULL; - int len; - int verification; - PyObject *binary_mode = Py_None; - - if (!PyArg_ParseTuple(args, "|O:peer_certificate", &binary_mode)) - return NULL; - - if (!self->peer_cert) - Py_RETURN_NONE; - - if (PyObject_IsTrue(binary_mode)) { - /* return cert in DER-encoded format */ - - unsigned char *bytes_buf = NULL; - - bytes_buf = NULL; - len = i2d_X509(self->peer_cert, &bytes_buf); - if (len < 0) { - PySSL_SetError(self, len, __FILE__, __LINE__); - return NULL; - } - /* this is actually an immutable bytes sequence */ - retval = PyBytes_FromStringAndSize - ((const char *) bytes_buf, len); - OPENSSL_free(bytes_buf); - return retval; - - } else { - - verification = SSL_CTX_get_verify_mode(self->ctx); - if ((verification & SSL_VERIFY_PEER) == 0) - return PyDict_New(); - else - return _decode_certificate (self->peer_cert, 0); - } + PyObject *retval = NULL; + int len; + int verification; + PyObject *binary_mode = Py_None; + + if (!PyArg_ParseTuple(args, "|O:peer_certificate", &binary_mode)) + return NULL; + + if (!self->peer_cert) + Py_RETURN_NONE; + + if (PyObject_IsTrue(binary_mode)) { + /* return cert in DER-encoded format */ + + unsigned char *bytes_buf = NULL; + + bytes_buf = NULL; + len = i2d_X509(self->peer_cert, &bytes_buf); + if (len < 0) { + PySSL_SetError(self, len, __FILE__, __LINE__); + return NULL; + } + /* this is actually an immutable bytes sequence */ + retval = PyBytes_FromStringAndSize + ((const char *) bytes_buf, len); + OPENSSL_free(bytes_buf); + return retval; + + } else { + + verification = SSL_CTX_get_verify_mode(self->ctx); + if ((verification & SSL_VERIFY_PEER) == 0) + return PyDict_New(); + else + return _decode_certificate (self->peer_cert, 0); + } } PyDoc_STRVAR(PySSL_peercert_doc, @@ -1033,60 +1033,60 @@ static PyObject *PySSL_cipher (PySSLObject *self) { - PyObject *retval, *v; - SSL_CIPHER *current; - char *cipher_name; - char *cipher_protocol; - - if (self->ssl == NULL) - return Py_None; - current = SSL_get_current_cipher(self->ssl); - if (current == NULL) - return Py_None; - - retval = PyTuple_New(3); - if (retval == NULL) - return NULL; - - cipher_name = (char *) SSL_CIPHER_get_name(current); - if (cipher_name == NULL) { - PyTuple_SET_ITEM(retval, 0, Py_None); - } else { - v = PyUnicode_FromString(cipher_name); - if (v == NULL) - goto fail0; - PyTuple_SET_ITEM(retval, 0, v); - } - cipher_protocol = SSL_CIPHER_get_version(current); - if (cipher_protocol == NULL) { - PyTuple_SET_ITEM(retval, 1, Py_None); - } else { - v = PyUnicode_FromString(cipher_protocol); - if (v == NULL) - goto fail0; - PyTuple_SET_ITEM(retval, 1, v); - } - v = PyLong_FromLong(SSL_CIPHER_get_bits(current, NULL)); - if (v == NULL) - goto fail0; - PyTuple_SET_ITEM(retval, 2, v); - return retval; + PyObject *retval, *v; + SSL_CIPHER *current; + char *cipher_name; + char *cipher_protocol; + + if (self->ssl == NULL) + return Py_None; + current = SSL_get_current_cipher(self->ssl); + if (current == NULL) + return Py_None; + + retval = PyTuple_New(3); + if (retval == NULL) + return NULL; + + cipher_name = (char *) SSL_CIPHER_get_name(current); + if (cipher_name == NULL) { + PyTuple_SET_ITEM(retval, 0, Py_None); + } else { + v = PyUnicode_FromString(cipher_name); + if (v == NULL) + goto fail0; + PyTuple_SET_ITEM(retval, 0, v); + } + cipher_protocol = SSL_CIPHER_get_version(current); + if (cipher_protocol == NULL) { + PyTuple_SET_ITEM(retval, 1, Py_None); + } else { + v = PyUnicode_FromString(cipher_protocol); + if (v == NULL) + goto fail0; + PyTuple_SET_ITEM(retval, 1, v); + } + v = PyLong_FromLong(SSL_CIPHER_get_bits(current, NULL)); + if (v == NULL) + goto fail0; + PyTuple_SET_ITEM(retval, 2, v); + return retval; fail0: - Py_DECREF(retval); - return NULL; + Py_DECREF(retval); + return NULL; } static void PySSL_dealloc(PySSLObject *self) { - if (self->peer_cert) /* Possible not to have one? */ - X509_free (self->peer_cert); - if (self->ssl) - SSL_free(self->ssl); - if (self->ctx) - SSL_CTX_free(self->ctx); - Py_XDECREF(self->Socket); - PyObject_Del(self); + if (self->peer_cert) /* Possible not to have one? */ + X509_free (self->peer_cert); + if (self->ssl) + SSL_free(self->ssl); + if (self->ctx) + SSL_CTX_free(self->ctx); + Py_XDECREF(self->Socket); + PyObject_Del(self); } /* If the socket has a timeout, do a select()/poll() on the socket. @@ -1097,141 +1097,141 @@ static int check_socket_and_wait_for_timeout(PySocketSockObject *s, int writing) { - fd_set fds; - struct timeval tv; - int rc; - - /* Nothing to do unless we're in timeout mode (not non-blocking) */ - if (s->sock_timeout < 0.0) - return SOCKET_IS_BLOCKING; - else if (s->sock_timeout == 0.0) - return SOCKET_IS_NONBLOCKING; - - /* Guard against closed socket */ - if (s->sock_fd < 0) - return SOCKET_HAS_BEEN_CLOSED; + fd_set fds; + struct timeval tv; + int rc; + + /* Nothing to do unless we're in timeout mode (not non-blocking) */ + if (s->sock_timeout < 0.0) + return SOCKET_IS_BLOCKING; + else if (s->sock_timeout == 0.0) + return SOCKET_IS_NONBLOCKING; + + /* Guard against closed socket */ + if (s->sock_fd < 0) + return SOCKET_HAS_BEEN_CLOSED; - /* Prefer poll, if available, since you can poll() any fd - * which can't be done with select(). */ + /* Prefer poll, if available, since you can poll() any fd + * which can't be done with select(). */ #ifdef HAVE_POLL - { - struct pollfd pollfd; - int timeout; - - pollfd.fd = s->sock_fd; - pollfd.events = writing ? POLLOUT : POLLIN; - - /* s->sock_timeout is in seconds, timeout in ms */ - timeout = (int)(s->sock_timeout * 1000 + 0.5); - PySSL_BEGIN_ALLOW_THREADS - rc = poll(&pollfd, 1, timeout); - PySSL_END_ALLOW_THREADS + { + struct pollfd pollfd; + int timeout; + + pollfd.fd = s->sock_fd; + pollfd.events = writing ? POLLOUT : POLLIN; - goto normal_return; - } + /* s->sock_timeout is in seconds, timeout in ms */ + timeout = (int)(s->sock_timeout * 1000 + 0.5); + PySSL_BEGIN_ALLOW_THREADS + rc = poll(&pollfd, 1, timeout); + PySSL_END_ALLOW_THREADS + + goto normal_return; + } #endif - /* Guard against socket too large for select*/ + /* Guard against socket too large for select*/ #ifndef Py_SOCKET_FD_CAN_BE_GE_FD_SETSIZE - if (s->sock_fd >= FD_SETSIZE) - return SOCKET_TOO_LARGE_FOR_SELECT; + if (s->sock_fd >= FD_SETSIZE) + return SOCKET_TOO_LARGE_FOR_SELECT; #endif - /* Construct the arguments to select */ - tv.tv_sec = (int)s->sock_timeout; - tv.tv_usec = (int)((s->sock_timeout - tv.tv_sec) * 1e6); - FD_ZERO(&fds); - FD_SET(s->sock_fd, &fds); - - /* See if the socket is ready */ - PySSL_BEGIN_ALLOW_THREADS - if (writing) - rc = select(s->sock_fd+1, NULL, &fds, NULL, &tv); - else - rc = select(s->sock_fd+1, &fds, NULL, NULL, &tv); - PySSL_END_ALLOW_THREADS + /* Construct the arguments to select */ + tv.tv_sec = (int)s->sock_timeout; + tv.tv_usec = (int)((s->sock_timeout - tv.tv_sec) * 1e6); + FD_ZERO(&fds); + FD_SET(s->sock_fd, &fds); + + /* See if the socket is ready */ + PySSL_BEGIN_ALLOW_THREADS + if (writing) + rc = select(s->sock_fd+1, NULL, &fds, NULL, &tv); + else + rc = select(s->sock_fd+1, &fds, NULL, NULL, &tv); + PySSL_END_ALLOW_THREADS #ifdef HAVE_POLL normal_return: #endif - /* Return SOCKET_TIMED_OUT on timeout, SOCKET_OPERATION_OK otherwise - (when we are able to write or when there's something to read) */ - return rc == 0 ? SOCKET_HAS_TIMED_OUT : SOCKET_OPERATION_OK; + /* Return SOCKET_TIMED_OUT on timeout, SOCKET_OPERATION_OK otherwise + (when we are able to write or when there's something to read) */ + return rc == 0 ? SOCKET_HAS_TIMED_OUT : SOCKET_OPERATION_OK; } static PyObject *PySSL_SSLwrite(PySSLObject *self, PyObject *args) { - char *data; - int len; - int count; - int sockstate; - int err; - int nonblocking; - PySocketSockObject *sock - = (PySocketSockObject *) PyWeakref_GetObject(self->Socket); - - if (((PyObject*)sock) == Py_None) { - _setSSLError("Underlying socket connection gone", - PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__); - return NULL; - } - - if (!PyArg_ParseTuple(args, "y#:write", &data, &count)) - return NULL; - - /* just in case the blocking state of the socket has been changed */ - nonblocking = (sock->sock_timeout >= 0.0); - BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking); - BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking); - - sockstate = check_socket_and_wait_for_timeout(sock, 1); - if (sockstate == SOCKET_HAS_TIMED_OUT) { - PyErr_SetString(PySSLErrorObject, - "The write operation timed out"); - return NULL; - } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) { - PyErr_SetString(PySSLErrorObject, - "Underlying socket has been closed."); - return NULL; - } else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) { - PyErr_SetString(PySSLErrorObject, - "Underlying socket too large for select()."); - return NULL; - } - do { - err = 0; - PySSL_BEGIN_ALLOW_THREADS - len = SSL_write(self->ssl, data, count); - err = SSL_get_error(self->ssl, len); - PySSL_END_ALLOW_THREADS - if(PyErr_CheckSignals()) { - return NULL; - } - if (err == SSL_ERROR_WANT_READ) { - sockstate = - check_socket_and_wait_for_timeout(sock, 0); - } else if (err == SSL_ERROR_WANT_WRITE) { - sockstate = - check_socket_and_wait_for_timeout(sock, 1); - } else { - sockstate = SOCKET_OPERATION_OK; - } - if (sockstate == SOCKET_HAS_TIMED_OUT) { - PyErr_SetString(PySSLErrorObject, - "The write operation timed out"); - return NULL; - } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) { - PyErr_SetString(PySSLErrorObject, - "Underlying socket has been closed."); - return NULL; - } else if (sockstate == SOCKET_IS_NONBLOCKING) { - break; - } - } while (err == SSL_ERROR_WANT_READ || err == SSL_ERROR_WANT_WRITE); - if (len > 0) - return PyLong_FromLong(len); - else - return PySSL_SetError(self, len, __FILE__, __LINE__); + char *data; + int len; + int count; + int sockstate; + int err; + int nonblocking; + PySocketSockObject *sock + = (PySocketSockObject *) PyWeakref_GetObject(self->Socket); + + if (((PyObject*)sock) == Py_None) { + _setSSLError("Underlying socket connection gone", + PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__); + return NULL; + } + + if (!PyArg_ParseTuple(args, "y#:write", &data, &count)) + return NULL; + + /* just in case the blocking state of the socket has been changed */ + nonblocking = (sock->sock_timeout >= 0.0); + BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking); + BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking); + + sockstate = check_socket_and_wait_for_timeout(sock, 1); + if (sockstate == SOCKET_HAS_TIMED_OUT) { + PyErr_SetString(PySSLErrorObject, + "The write operation timed out"); + return NULL; + } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) { + PyErr_SetString(PySSLErrorObject, + "Underlying socket has been closed."); + return NULL; + } else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) { + PyErr_SetString(PySSLErrorObject, + "Underlying socket too large for select()."); + return NULL; + } + do { + err = 0; + PySSL_BEGIN_ALLOW_THREADS + len = SSL_write(self->ssl, data, count); + err = SSL_get_error(self->ssl, len); + PySSL_END_ALLOW_THREADS + if(PyErr_CheckSignals()) { + return NULL; + } + if (err == SSL_ERROR_WANT_READ) { + sockstate = + check_socket_and_wait_for_timeout(sock, 0); + } else if (err == SSL_ERROR_WANT_WRITE) { + sockstate = + check_socket_and_wait_for_timeout(sock, 1); + } else { + sockstate = SOCKET_OPERATION_OK; + } + if (sockstate == SOCKET_HAS_TIMED_OUT) { + PyErr_SetString(PySSLErrorObject, + "The write operation timed out"); + return NULL; + } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) { + PyErr_SetString(PySSLErrorObject, + "Underlying socket has been closed."); + return NULL; + } else if (sockstate == SOCKET_IS_NONBLOCKING) { + break; + } + } while (err == SSL_ERROR_WANT_READ || err == SSL_ERROR_WANT_WRITE); + if (len > 0) + return PyLong_FromLong(len); + else + return PySSL_SetError(self, len, __FILE__, __LINE__); } PyDoc_STRVAR(PySSL_SSLwrite_doc, @@ -1242,15 +1242,15 @@ static PyObject *PySSL_SSLpending(PySSLObject *self) { - int count = 0; + int count = 0; - PySSL_BEGIN_ALLOW_THREADS - count = SSL_pending(self->ssl); - PySSL_END_ALLOW_THREADS - if (count < 0) - return PySSL_SetError(self, count, __FILE__, __LINE__); - else - return PyLong_FromLong(count); + PySSL_BEGIN_ALLOW_THREADS + count = SSL_pending(self->ssl); + PySSL_END_ALLOW_THREADS + if (count < 0) + return PySSL_SetError(self, count, __FILE__, __LINE__); + else + return PyLong_FromLong(count); } PyDoc_STRVAR(PySSL_SSLpending_doc, @@ -1261,122 +1261,122 @@ static PyObject *PySSL_SSLread(PySSLObject *self, PyObject *args) { - PyObject *dest = NULL; - Py_buffer buf; - int buf_passed = 0; - int count = -1; - char *mem; - /* XXX this should use Py_ssize_t */ - int len = 1024; - int sockstate; - int err; - int nonblocking; - PySocketSockObject *sock - = (PySocketSockObject *) PyWeakref_GetObject(self->Socket); - - if (((PyObject*)sock) == Py_None) { - _setSSLError("Underlying socket connection gone", - PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__); - return NULL; - } - - if (!PyArg_ParseTuple(args, "|Oi:read", &dest, &count)) - return NULL; - if ((dest == NULL) || (dest == Py_None)) { - if (!(dest = PyByteArray_FromStringAndSize((char *) 0, len))) - return NULL; - mem = PyByteArray_AS_STRING(dest); - } else if (PyLong_Check(dest)) { - len = PyLong_AS_LONG(dest); - if (!(dest = PyByteArray_FromStringAndSize((char *) 0, len))) - return NULL; - mem = PyByteArray_AS_STRING(dest); - } else { - if (PyObject_GetBuffer(dest, &buf, PyBUF_CONTIG) < 0) - return NULL; - mem = buf.buf; - len = buf.len; - if ((count > 0) && (count <= len)) - len = count; - buf_passed = 1; - } - - /* just in case the blocking state of the socket has been changed */ - nonblocking = (sock->sock_timeout >= 0.0); - BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking); - BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking); - - /* first check if there are bytes ready to be read */ - PySSL_BEGIN_ALLOW_THREADS - count = SSL_pending(self->ssl); - PySSL_END_ALLOW_THREADS - - if (!count) { - sockstate = check_socket_and_wait_for_timeout(sock, 0); - if (sockstate == SOCKET_HAS_TIMED_OUT) { - PyErr_SetString(PySSLErrorObject, - "The read operation timed out"); - goto error; - } else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) { - PyErr_SetString(PySSLErrorObject, - "Underlying socket too large for select()."); - goto error; - } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) { - count = 0; - goto done; - } - } - do { - err = 0; - PySSL_BEGIN_ALLOW_THREADS - count = SSL_read(self->ssl, mem, len); - err = SSL_get_error(self->ssl, count); - PySSL_END_ALLOW_THREADS - if (PyErr_CheckSignals()) - goto error; - if (err == SSL_ERROR_WANT_READ) { - sockstate = - check_socket_and_wait_for_timeout(sock, 0); - } else if (err == SSL_ERROR_WANT_WRITE) { - sockstate = - check_socket_and_wait_for_timeout(sock, 1); - } else if ((err == SSL_ERROR_ZERO_RETURN) && - (SSL_get_shutdown(self->ssl) == - SSL_RECEIVED_SHUTDOWN)) - { - count = 0; - goto done; - } else { - sockstate = SOCKET_OPERATION_OK; - } - if (sockstate == SOCKET_HAS_TIMED_OUT) { - PyErr_SetString(PySSLErrorObject, - "The read operation timed out"); - goto error; - } else if (sockstate == SOCKET_IS_NONBLOCKING) { - break; - } - } while (err == SSL_ERROR_WANT_READ || err == SSL_ERROR_WANT_WRITE); - if (count <= 0) { - PySSL_SetError(self, count, __FILE__, __LINE__); - goto error; - } + PyObject *dest = NULL; + Py_buffer buf; + int buf_passed = 0; + int count = -1; + char *mem; + /* XXX this should use Py_ssize_t */ + int len = 1024; + int sockstate; + int err; + int nonblocking; + PySocketSockObject *sock + = (PySocketSockObject *) PyWeakref_GetObject(self->Socket); + + if (((PyObject*)sock) == Py_None) { + _setSSLError("Underlying socket connection gone", + PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__); + return NULL; + } + + if (!PyArg_ParseTuple(args, "|Oi:read", &dest, &count)) + return NULL; + if ((dest == NULL) || (dest == Py_None)) { + if (!(dest = PyByteArray_FromStringAndSize((char *) 0, len))) + return NULL; + mem = PyByteArray_AS_STRING(dest); + } else if (PyLong_Check(dest)) { + len = PyLong_AS_LONG(dest); + if (!(dest = PyByteArray_FromStringAndSize((char *) 0, len))) + return NULL; + mem = PyByteArray_AS_STRING(dest); + } else { + if (PyObject_GetBuffer(dest, &buf, PyBUF_CONTIG) < 0) + return NULL; + mem = buf.buf; + len = buf.len; + if ((count > 0) && (count <= len)) + len = count; + buf_passed = 1; + } + + /* just in case the blocking state of the socket has been changed */ + nonblocking = (sock->sock_timeout >= 0.0); + BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking); + BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking); + + /* first check if there are bytes ready to be read */ + PySSL_BEGIN_ALLOW_THREADS + count = SSL_pending(self->ssl); + PySSL_END_ALLOW_THREADS + + if (!count) { + sockstate = check_socket_and_wait_for_timeout(sock, 0); + if (sockstate == SOCKET_HAS_TIMED_OUT) { + PyErr_SetString(PySSLErrorObject, + "The read operation timed out"); + goto error; + } else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) { + PyErr_SetString(PySSLErrorObject, + "Underlying socket too large for select()."); + goto error; + } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) { + count = 0; + goto done; + } + } + do { + err = 0; + PySSL_BEGIN_ALLOW_THREADS + count = SSL_read(self->ssl, mem, len); + err = SSL_get_error(self->ssl, count); + PySSL_END_ALLOW_THREADS + if (PyErr_CheckSignals()) + goto error; + if (err == SSL_ERROR_WANT_READ) { + sockstate = + check_socket_and_wait_for_timeout(sock, 0); + } else if (err == SSL_ERROR_WANT_WRITE) { + sockstate = + check_socket_and_wait_for_timeout(sock, 1); + } else if ((err == SSL_ERROR_ZERO_RETURN) && + (SSL_get_shutdown(self->ssl) == + SSL_RECEIVED_SHUTDOWN)) + { + count = 0; + goto done; + } else { + sockstate = SOCKET_OPERATION_OK; + } + if (sockstate == SOCKET_HAS_TIMED_OUT) { + PyErr_SetString(PySSLErrorObject, + "The read operation timed out"); + goto error; + } else if (sockstate == SOCKET_IS_NONBLOCKING) { + break; + } + } while (err == SSL_ERROR_WANT_READ || err == SSL_ERROR_WANT_WRITE); + if (count <= 0) { + PySSL_SetError(self, count, __FILE__, __LINE__); + goto error; + } done: - if (!buf_passed) { - PyObject *res = PyBytes_FromStringAndSize(mem, count); - Py_DECREF(dest); - return res; - } else { - PyBuffer_Release(&buf); - return PyLong_FromLong(count); - } + if (!buf_passed) { + PyObject *res = PyBytes_FromStringAndSize(mem, count); + Py_DECREF(dest); + return res; + } else { + PyBuffer_Release(&buf); + return PyLong_FromLong(count); + } error: - if (!buf_passed) { - Py_DECREF(dest); - } else { - PyBuffer_Release(&buf); - } - return NULL; + if (!buf_passed) { + Py_DECREF(dest); + } else { + PyBuffer_Release(&buf); + } + return NULL; } PyDoc_STRVAR(PySSL_SSLread_doc, @@ -1386,84 +1386,84 @@ static PyObject *PySSL_SSLshutdown(PySSLObject *self) { - int err, ssl_err, sockstate, nonblocking; - int zeros = 0; - PySocketSockObject *sock - = (PySocketSockObject *) PyWeakref_GetObject(self->Socket); - - /* Guard against closed socket */ - if ((((PyObject*)sock) == Py_None) || (sock->sock_fd < 0)) { - _setSSLError("Underlying socket connection gone", - PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__); - return NULL; - } - - /* Just in case the blocking state of the socket has been changed */ - nonblocking = (sock->sock_timeout >= 0.0); - BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking); - BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking); - - while (1) { - PySSL_BEGIN_ALLOW_THREADS - /* Disable read-ahead so that unwrap can work correctly. - * Otherwise OpenSSL might read in too much data, - * eating clear text data that happens to be - * transmitted after the SSL shutdown. - * Should be safe to call repeatedly everytime this - * function is used and the shutdown_seen_zero != 0 - * condition is met. - */ - if (self->shutdown_seen_zero) - SSL_set_read_ahead(self->ssl, 0); - err = SSL_shutdown(self->ssl); - PySSL_END_ALLOW_THREADS - /* If err == 1, a secure shutdown with SSL_shutdown() is complete */ - if (err > 0) - break; - if (err == 0) { - /* Don't loop endlessly; instead preserve legacy - behaviour of trying SSL_shutdown() only twice. - This looks necessary for OpenSSL < 0.9.8m */ - if (++zeros > 1) - break; - /* Shutdown was sent, now try receiving */ - self->shutdown_seen_zero = 1; - continue; - } - - /* Possibly retry shutdown until timeout or failure */ - ssl_err = SSL_get_error(self->ssl, err); - if (ssl_err == SSL_ERROR_WANT_READ) - sockstate = check_socket_and_wait_for_timeout(sock, 0); - else if (ssl_err == SSL_ERROR_WANT_WRITE) - sockstate = check_socket_and_wait_for_timeout(sock, 1); - else - break; - if (sockstate == SOCKET_HAS_TIMED_OUT) { - if (ssl_err == SSL_ERROR_WANT_READ) - PyErr_SetString(PySSLErrorObject, - "The read operation timed out"); - else - PyErr_SetString(PySSLErrorObject, - "The write operation timed out"); - return NULL; - } - else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) { - PyErr_SetString(PySSLErrorObject, - "Underlying socket too large for select()."); - return NULL; - } - else if (sockstate != SOCKET_OPERATION_OK) - /* Retain the SSL error code */ - break; - } - - if (err < 0) - return PySSL_SetError(self, err, __FILE__, __LINE__); - else { - Py_INCREF(sock); - return (PyObject *) sock; - } + int err, ssl_err, sockstate, nonblocking; + int zeros = 0; + PySocketSockObject *sock + = (PySocketSockObject *) PyWeakref_GetObject(self->Socket); + + /* Guard against closed socket */ + if ((((PyObject*)sock) == Py_None) || (sock->sock_fd < 0)) { + _setSSLError("Underlying socket connection gone", + PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__); + return NULL; + } + + /* Just in case the blocking state of the socket has been changed */ + nonblocking = (sock->sock_timeout >= 0.0); + BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking); + BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking); + + while (1) { + PySSL_BEGIN_ALLOW_THREADS + /* Disable read-ahead so that unwrap can work correctly. + * Otherwise OpenSSL might read in too much data, + * eating clear text data that happens to be + * transmitted after the SSL shutdown. + * Should be safe to call repeatedly everytime this + * function is used and the shutdown_seen_zero != 0 + * condition is met. + */ + if (self->shutdown_seen_zero) + SSL_set_read_ahead(self->ssl, 0); + err = SSL_shutdown(self->ssl); + PySSL_END_ALLOW_THREADS + /* If err == 1, a secure shutdown with SSL_shutdown() is complete */ + if (err > 0) + break; + if (err == 0) { + /* Don't loop endlessly; instead preserve legacy + behaviour of trying SSL_shutdown() only twice. + This looks necessary for OpenSSL < 0.9.8m */ + if (++zeros > 1) + break; + /* Shutdown was sent, now try receiving */ + self->shutdown_seen_zero = 1; + continue; + } + + /* Possibly retry shutdown until timeout or failure */ + ssl_err = SSL_get_error(self->ssl, err); + if (ssl_err == SSL_ERROR_WANT_READ) + sockstate = check_socket_and_wait_for_timeout(sock, 0); + else if (ssl_err == SSL_ERROR_WANT_WRITE) + sockstate = check_socket_and_wait_for_timeout(sock, 1); + else + break; + if (sockstate == SOCKET_HAS_TIMED_OUT) { + if (ssl_err == SSL_ERROR_WANT_READ) + PyErr_SetString(PySSLErrorObject, + "The read operation timed out"); + else + PyErr_SetString(PySSLErrorObject, + "The write operation timed out"); + return NULL; + } + else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) { + PyErr_SetString(PySSLErrorObject, + "Underlying socket too large for select()."); + return NULL; + } + else if (sockstate != SOCKET_OPERATION_OK) + /* Retain the SSL error code */ + break; + } + + if (err < 0) + return PySSL_SetError(self, err, __FILE__, __LINE__); + else { + Py_INCREF(sock); + return (PyObject *) sock; + } } PyDoc_STRVAR(PySSL_SSLshutdown_doc, @@ -1474,51 +1474,51 @@ static PyMethodDef PySSLMethods[] = { - {"do_handshake", (PyCFunction)PySSL_SSLdo_handshake, METH_NOARGS}, - {"write", (PyCFunction)PySSL_SSLwrite, METH_VARARGS, - PySSL_SSLwrite_doc}, - {"read", (PyCFunction)PySSL_SSLread, METH_VARARGS, - PySSL_SSLread_doc}, - {"pending", (PyCFunction)PySSL_SSLpending, METH_NOARGS, - PySSL_SSLpending_doc}, - {"peer_certificate", (PyCFunction)PySSL_peercert, METH_VARARGS, - PySSL_peercert_doc}, - {"cipher", (PyCFunction)PySSL_cipher, METH_NOARGS}, - {"shutdown", (PyCFunction)PySSL_SSLshutdown, METH_NOARGS, - PySSL_SSLshutdown_doc}, - {NULL, NULL} + {"do_handshake", (PyCFunction)PySSL_SSLdo_handshake, METH_NOARGS}, + {"write", (PyCFunction)PySSL_SSLwrite, METH_VARARGS, + PySSL_SSLwrite_doc}, + {"read", (PyCFunction)PySSL_SSLread, METH_VARARGS, + PySSL_SSLread_doc}, + {"pending", (PyCFunction)PySSL_SSLpending, METH_NOARGS, + PySSL_SSLpending_doc}, + {"peer_certificate", (PyCFunction)PySSL_peercert, METH_VARARGS, + PySSL_peercert_doc}, + {"cipher", (PyCFunction)PySSL_cipher, METH_NOARGS}, + {"shutdown", (PyCFunction)PySSL_SSLshutdown, METH_NOARGS, + PySSL_SSLshutdown_doc}, + {NULL, NULL} }; static PyTypeObject PySSL_Type = { - PyVarObject_HEAD_INIT(NULL, 0) - "ssl.SSLContext", /*tp_name*/ - sizeof(PySSLObject), /*tp_basicsize*/ - 0, /*tp_itemsize*/ - /* methods */ - (destructor)PySSL_dealloc, /*tp_dealloc*/ - 0, /*tp_print*/ - 0, /*tp_getattr*/ - 0, /*tp_setattr*/ - 0, /*tp_reserved*/ - 0, /*tp_repr*/ - 0, /*tp_as_number*/ - 0, /*tp_as_sequence*/ - 0, /*tp_as_mapping*/ - 0, /*tp_hash*/ - 0, /*tp_call*/ - 0, /*tp_str*/ - 0, /*tp_getattro*/ - 0, /*tp_setattro*/ - 0, /*tp_as_buffer*/ - Py_TPFLAGS_DEFAULT, /*tp_flags*/ - 0, /*tp_doc*/ - 0, /*tp_traverse*/ - 0, /*tp_clear*/ - 0, /*tp_richcompare*/ - 0, /*tp_weaklistoffset*/ - 0, /*tp_iter*/ - 0, /*tp_iternext*/ - PySSLMethods, /*tp_methods*/ + PyVarObject_HEAD_INIT(NULL, 0) + "ssl.SSLContext", /*tp_name*/ + sizeof(PySSLObject), /*tp_basicsize*/ + 0, /*tp_itemsize*/ + /* methods */ + (destructor)PySSL_dealloc, /*tp_dealloc*/ + 0, /*tp_print*/ + 0, /*tp_getattr*/ + 0, /*tp_setattr*/ + 0, /*tp_reserved*/ + 0, /*tp_repr*/ + 0, /*tp_as_number*/ + 0, /*tp_as_sequence*/ + 0, /*tp_as_mapping*/ + 0, /*tp_hash*/ + 0, /*tp_call*/ + 0, /*tp_str*/ + 0, /*tp_getattro*/ + 0, /*tp_setattro*/ + 0, /*tp_as_buffer*/ + Py_TPFLAGS_DEFAULT, /*tp_flags*/ + 0, /*tp_doc*/ + 0, /*tp_traverse*/ + 0, /*tp_clear*/ + 0, /*tp_richcompare*/ + 0, /*tp_weaklistoffset*/ + 0, /*tp_iter*/ + 0, /*tp_iternext*/ + PySSLMethods, /*tp_methods*/ }; #ifdef HAVE_OPENSSL_RAND @@ -1532,7 +1532,7 @@ double entropy; if (!PyArg_ParseTuple(args, "s#d:RAND_add", &buf, &len, &entropy)) - return NULL; + return NULL; RAND_add(buf, len, entropy); Py_INCREF(Py_None); return Py_None; @@ -1563,15 +1563,15 @@ int bytes; if (!PyUnicode_Check(arg)) - return PyErr_Format(PyExc_TypeError, - "RAND_egd() expected string, found %s", - Py_TYPE(arg)->tp_name); + return PyErr_Format(PyExc_TypeError, + "RAND_egd() expected string, found %s", + Py_TYPE(arg)->tp_name); bytes = RAND_egd(_PyUnicode_AsString(arg)); if (bytes == -1) { - PyErr_SetString(PySSLErrorObject, - "EGD connection failed or EGD did not return " - "enough data to seed the PRNG"); - return NULL; + PyErr_SetString(PySSLErrorObject, + "EGD connection failed or EGD did not return " + "enough data to seed the PRNG"); + return NULL; } return PyLong_FromLong(bytes); } @@ -1590,19 +1590,19 @@ /* List of functions exported by this module. */ static PyMethodDef PySSL_methods[] = { - {"sslwrap", PySSL_sslwrap, - METH_VARARGS, ssl_doc}, - {"_test_decode_cert", PySSL_test_decode_certificate, - METH_VARARGS}, + {"sslwrap", PySSL_sslwrap, + METH_VARARGS, ssl_doc}, + {"_test_decode_cert", PySSL_test_decode_certificate, + METH_VARARGS}, #ifdef HAVE_OPENSSL_RAND - {"RAND_add", PySSL_RAND_add, METH_VARARGS, - PySSL_RAND_add_doc}, - {"RAND_egd", PySSL_RAND_egd, METH_O, - PySSL_RAND_egd_doc}, - {"RAND_status", (PyCFunction)PySSL_RAND_status, METH_NOARGS, - PySSL_RAND_status_doc}, + {"RAND_add", PySSL_RAND_add, METH_VARARGS, + PySSL_RAND_add_doc}, + {"RAND_egd", PySSL_RAND_egd, METH_O, + PySSL_RAND_egd_doc}, + {"RAND_status", (PyCFunction)PySSL_RAND_status, METH_NOARGS, + PySSL_RAND_status_doc}, #endif - {NULL, NULL} /* Sentinel */ + {NULL, NULL} /* Sentinel */ }; @@ -1614,66 +1614,66 @@ static PyThread_type_lock *_ssl_locks = NULL; static unsigned long _ssl_thread_id_function (void) { - return PyThread_get_thread_ident(); + return PyThread_get_thread_ident(); } static void _ssl_thread_locking_function - (int mode, int n, const char *file, int line) { - /* this function is needed to perform locking on shared data - structures. (Note that OpenSSL uses a number of global data - structures that will be implicitly shared whenever multiple - threads use OpenSSL.) Multi-threaded applications will - crash at random if it is not set. - - locking_function() must be able to handle up to - CRYPTO_num_locks() different mutex locks. It sets the n-th - lock if mode & CRYPTO_LOCK, and releases it otherwise. - - file and line are the file number of the function setting the - lock. They can be useful for debugging. - */ - - if ((_ssl_locks == NULL) || - (n < 0) || ((unsigned)n >= _ssl_locks_count)) - return; - - if (mode & CRYPTO_LOCK) { - PyThread_acquire_lock(_ssl_locks[n], 1); - } else { - PyThread_release_lock(_ssl_locks[n]); - } + (int mode, int n, const char *file, int line) { + /* this function is needed to perform locking on shared data + structures. (Note that OpenSSL uses a number of global data + structures that will be implicitly shared whenever multiple + threads use OpenSSL.) Multi-threaded applications will + crash at random if it is not set. + + locking_function() must be able to handle up to + CRYPTO_num_locks() different mutex locks. It sets the n-th + lock if mode & CRYPTO_LOCK, and releases it otherwise. + + file and line are the file number of the function setting the + lock. They can be useful for debugging. + */ + + if ((_ssl_locks == NULL) || + (n < 0) || ((unsigned)n >= _ssl_locks_count)) + return; + + if (mode & CRYPTO_LOCK) { + PyThread_acquire_lock(_ssl_locks[n], 1); + } else { + PyThread_release_lock(_ssl_locks[n]); + } } static int _setup_ssl_threads(void) { - unsigned int i; + unsigned int i; - if (_ssl_locks == NULL) { - _ssl_locks_count = CRYPTO_num_locks(); - _ssl_locks = (PyThread_type_lock *) - malloc(sizeof(PyThread_type_lock) * _ssl_locks_count); - if (_ssl_locks == NULL) - return 0; - memset(_ssl_locks, 0, - sizeof(PyThread_type_lock) * _ssl_locks_count); - for (i = 0; i < _ssl_locks_count; i++) { - _ssl_locks[i] = PyThread_allocate_lock(); - if (_ssl_locks[i] == NULL) { - unsigned int j; - for (j = 0; j < i; j++) { - PyThread_free_lock(_ssl_locks[j]); - } - free(_ssl_locks); - return 0; - } - } - CRYPTO_set_locking_callback(_ssl_thread_locking_function); - CRYPTO_set_id_callback(_ssl_thread_id_function); - } - return 1; + if (_ssl_locks == NULL) { + _ssl_locks_count = CRYPTO_num_locks(); + _ssl_locks = (PyThread_type_lock *) + malloc(sizeof(PyThread_type_lock) * _ssl_locks_count); + if (_ssl_locks == NULL) + return 0; + memset(_ssl_locks, 0, + sizeof(PyThread_type_lock) * _ssl_locks_count); + for (i = 0; i < _ssl_locks_count; i++) { + _ssl_locks[i] = PyThread_allocate_lock(); + if (_ssl_locks[i] == NULL) { + unsigned int j; + for (j = 0; j < i; j++) { + PyThread_free_lock(_ssl_locks[j]); + } + free(_ssl_locks); + return 0; + } + } + CRYPTO_set_locking_callback(_ssl_thread_locking_function); + CRYPTO_set_id_callback(_ssl_thread_id_function); + } + return 1; } -#endif /* def HAVE_THREAD */ +#endif /* def HAVE_THREAD */ PyDoc_STRVAR(module_doc, "Implementation module for SSL socket operations. See the socket module\n\ @@ -1681,94 +1681,94 @@ static struct PyModuleDef _sslmodule = { - PyModuleDef_HEAD_INIT, - "_ssl", - module_doc, - -1, - PySSL_methods, - NULL, - NULL, - NULL, - NULL + PyModuleDef_HEAD_INIT, + "_ssl", + module_doc, + -1, + PySSL_methods, + NULL, + NULL, + NULL, + NULL }; PyMODINIT_FUNC PyInit__ssl(void) { - PyObject *m, *d; - PySocketModule_APIObject *socket_api; + PyObject *m, *d; + PySocketModule_APIObject *socket_api; - if (PyType_Ready(&PySSL_Type) < 0) - return NULL; + if (PyType_Ready(&PySSL_Type) < 0) + return NULL; - m = PyModule_Create(&_sslmodule); - if (m == NULL) - return NULL; - d = PyModule_GetDict(m); - - /* Load _socket module and its C API */ - socket_api = PySocketModule_ImportModuleAndAPI(); - if (!socket_api) - return NULL; - PySocketModule = *socket_api; - - /* Init OpenSSL */ - SSL_load_error_strings(); - SSL_library_init(); + m = PyModule_Create(&_sslmodule); + if (m == NULL) + return NULL; + d = PyModule_GetDict(m); + + /* Load _socket module and its C API */ + socket_api = PySocketModule_ImportModuleAndAPI(); + if (!socket_api) + return NULL; + PySocketModule = *socket_api; + + /* Init OpenSSL */ + SSL_load_error_strings(); + SSL_library_init(); #ifdef WITH_THREAD - /* note that this will start threading if not already started */ - if (!_setup_ssl_threads()) { - return NULL; - } + /* note that this will start threading if not already started */ + if (!_setup_ssl_threads()) { + return NULL; + } #endif - OpenSSL_add_all_algorithms(); + OpenSSL_add_all_algorithms(); - /* Add symbols to module dict */ - PySSLErrorObject = PyErr_NewException("ssl.SSLError", - PySocketModule.error, - NULL); - if (PySSLErrorObject == NULL) - return NULL; - if (PyDict_SetItemString(d, "SSLError", PySSLErrorObject) != 0) - return NULL; - if (PyDict_SetItemString(d, "SSLType", - (PyObject *)&PySSL_Type) != 0) - return NULL; - PyModule_AddIntConstant(m, "SSL_ERROR_ZERO_RETURN", - PY_SSL_ERROR_ZERO_RETURN); - PyModule_AddIntConstant(m, "SSL_ERROR_WANT_READ", - PY_SSL_ERROR_WANT_READ); - PyModule_AddIntConstant(m, "SSL_ERROR_WANT_WRITE", - PY_SSL_ERROR_WANT_WRITE); - PyModule_AddIntConstant(m, "SSL_ERROR_WANT_X509_LOOKUP", - PY_SSL_ERROR_WANT_X509_LOOKUP); - PyModule_AddIntConstant(m, "SSL_ERROR_SYSCALL", - PY_SSL_ERROR_SYSCALL); - PyModule_AddIntConstant(m, "SSL_ERROR_SSL", - PY_SSL_ERROR_SSL); - PyModule_AddIntConstant(m, "SSL_ERROR_WANT_CONNECT", - PY_SSL_ERROR_WANT_CONNECT); - /* non ssl.h errorcodes */ - PyModule_AddIntConstant(m, "SSL_ERROR_EOF", - PY_SSL_ERROR_EOF); - PyModule_AddIntConstant(m, "SSL_ERROR_INVALID_ERROR_CODE", - PY_SSL_ERROR_INVALID_ERROR_CODE); - /* cert requirements */ - PyModule_AddIntConstant(m, "CERT_NONE", - PY_SSL_CERT_NONE); - PyModule_AddIntConstant(m, "CERT_OPTIONAL", - PY_SSL_CERT_OPTIONAL); - PyModule_AddIntConstant(m, "CERT_REQUIRED", - PY_SSL_CERT_REQUIRED); - - /* protocol versions */ - PyModule_AddIntConstant(m, "PROTOCOL_SSLv2", - PY_SSL_VERSION_SSL2); - PyModule_AddIntConstant(m, "PROTOCOL_SSLv3", - PY_SSL_VERSION_SSL3); - PyModule_AddIntConstant(m, "PROTOCOL_SSLv23", - PY_SSL_VERSION_SSL23); - PyModule_AddIntConstant(m, "PROTOCOL_TLSv1", - PY_SSL_VERSION_TLS1); - return m; + /* Add symbols to module dict */ + PySSLErrorObject = PyErr_NewException("ssl.SSLError", + PySocketModule.error, + NULL); + if (PySSLErrorObject == NULL) + return NULL; + if (PyDict_SetItemString(d, "SSLError", PySSLErrorObject) != 0) + return NULL; + if (PyDict_SetItemString(d, "SSLType", + (PyObject *)&PySSL_Type) != 0) + return NULL; + PyModule_AddIntConstant(m, "SSL_ERROR_ZERO_RETURN", + PY_SSL_ERROR_ZERO_RETURN); + PyModule_AddIntConstant(m, "SSL_ERROR_WANT_READ", + PY_SSL_ERROR_WANT_READ); + PyModule_AddIntConstant(m, "SSL_ERROR_WANT_WRITE", + PY_SSL_ERROR_WANT_WRITE); + PyModule_AddIntConstant(m, "SSL_ERROR_WANT_X509_LOOKUP", + PY_SSL_ERROR_WANT_X509_LOOKUP); + PyModule_AddIntConstant(m, "SSL_ERROR_SYSCALL", + PY_SSL_ERROR_SYSCALL); + PyModule_AddIntConstant(m, "SSL_ERROR_SSL", + PY_SSL_ERROR_SSL); + PyModule_AddIntConstant(m, "SSL_ERROR_WANT_CONNECT", + PY_SSL_ERROR_WANT_CONNECT); + /* non ssl.h errorcodes */ + PyModule_AddIntConstant(m, "SSL_ERROR_EOF", + PY_SSL_ERROR_EOF); + PyModule_AddIntConstant(m, "SSL_ERROR_INVALID_ERROR_CODE", + PY_SSL_ERROR_INVALID_ERROR_CODE); + /* cert requirements */ + PyModule_AddIntConstant(m, "CERT_NONE", + PY_SSL_CERT_NONE); + PyModule_AddIntConstant(m, "CERT_OPTIONAL", + PY_SSL_CERT_OPTIONAL); + PyModule_AddIntConstant(m, "CERT_REQUIRED", + PY_SSL_CERT_REQUIRED); + + /* protocol versions */ + PyModule_AddIntConstant(m, "PROTOCOL_SSLv2", + PY_SSL_VERSION_SSL2); + PyModule_AddIntConstant(m, "PROTOCOL_SSLv3", + PY_SSL_VERSION_SSL3); + PyModule_AddIntConstant(m, "PROTOCOL_SSLv23", + PY_SSL_VERSION_SSL23); + PyModule_AddIntConstant(m, "PROTOCOL_TLSv1", + PY_SSL_VERSION_TLS1); + return m; } From python-checkins at python.org Wed May 5 18:15:09 2010 From: python-checkins at python.org (barry.warsaw) Date: Wed, 5 May 2010 18:15:09 +0200 (CEST) Subject: [Python-checkins] r80793 - in python/trunk/Lib: email/test/data/audiotest.au test/audiotest.au test/test_ossaudiodev.py Message-ID: <20100505161509.6DA04EE9AA@mail.python.org> Author: barry.warsaw Date: Wed May 5 18:15:09 2010 New Revision: 80793 Log: Bug 7755: audiotest.au is arguably copyrighted material, but definitely makes Debian unhappy. The actual contents of the audio clip are unimportant, so replace it with something that we know is okay. Guido likes woodpeckers. Modified: python/trunk/Lib/email/test/data/audiotest.au python/trunk/Lib/test/audiotest.au python/trunk/Lib/test/test_ossaudiodev.py Modified: python/trunk/Lib/email/test/data/audiotest.au ============================================================================== Binary files. No diff available. Modified: python/trunk/Lib/test/audiotest.au ============================================================================== Binary files. No diff available. Modified: python/trunk/Lib/test/test_ossaudiodev.py ============================================================================== --- python/trunk/Lib/test/test_ossaudiodev.py (original) +++ python/trunk/Lib/test/test_ossaudiodev.py Wed May 5 18:15:09 2010 @@ -76,7 +76,7 @@ # set parameters based on .au file headers dsp.setparameters(AFMT_S16_NE, nchannels, rate) - self.assertTrue(abs(expected_time - 2.94) < 1e-2, expected_time) + self.assertTrue(abs(expected_time - 3.51) < 1e-2, expected_time) t1 = time.time() dsp.write(data) dsp.close() From python-checkins at python.org Wed May 5 18:17:22 2010 From: python-checkins at python.org (barry.warsaw) Date: Wed, 5 May 2010 18:17:22 +0200 (CEST) Subject: [Python-checkins] r80794 - python/trunk/Misc/NEWS Message-ID: <20100505161722.B9C8FEE9A3@mail.python.org> Author: barry.warsaw Date: Wed May 5 18:17:22 2010 New Revision: 80794 Log: NEWS Modified: python/trunk/Misc/NEWS Modified: python/trunk/Misc/NEWS ============================================================================== --- python/trunk/Misc/NEWS (original) +++ python/trunk/Misc/NEWS Wed May 5 18:17:22 2010 @@ -39,6 +39,8 @@ Library ------- +- Issue #7755: Use an unencumbered audio file for tests. + - Issue #8621: uuid.uuid4() returned the same sequence of values in the parent and any children created using ``os.fork`` on MacOS X 10.6. From python-checkins at python.org Wed May 5 18:18:31 2010 From: python-checkins at python.org (barry.warsaw) Date: Wed, 5 May 2010 18:18:31 +0200 (CEST) Subject: [Python-checkins] r80795 - in python/branches/py3k: Lib/email/test/data/audiotest.au Lib/test/audiotest.au Lib/test/test_ossaudiodev.py Misc/NEWS Message-ID: <20100505161831.A28EBEE9A3@mail.python.org> Author: barry.warsaw Date: Wed May 5 18:18:31 2010 New Revision: 80795 Log: Bug 7755: audiotest.au is arguably copyrighted material, but definitely makes Debian unhappy. The actual contents of the audio clip are unimportant, so replace it with something that we know is okay. Guido likes woodpeckers. Modified: python/branches/py3k/Lib/email/test/data/audiotest.au python/branches/py3k/Lib/test/audiotest.au python/branches/py3k/Lib/test/test_ossaudiodev.py python/branches/py3k/Misc/NEWS Modified: python/branches/py3k/Lib/email/test/data/audiotest.au ============================================================================== Binary files. No diff available. Modified: python/branches/py3k/Lib/test/audiotest.au ============================================================================== Binary files. No diff available. Modified: python/branches/py3k/Lib/test/test_ossaudiodev.py ============================================================================== --- python/branches/py3k/Lib/test/test_ossaudiodev.py (original) +++ python/branches/py3k/Lib/test/test_ossaudiodev.py Wed May 5 18:18:31 2010 @@ -76,7 +76,7 @@ # set parameters based on .au file headers dsp.setparameters(AFMT_S16_NE, nchannels, rate) - self.assertTrue(abs(expected_time - 2.94) < 1e-2, expected_time) + self.assertTrue(abs(expected_time - 3.51) < 1e-2, expected_time) t1 = time.time() dsp.write(data) dsp.close() Modified: python/branches/py3k/Misc/NEWS ============================================================================== --- python/branches/py3k/Misc/NEWS (original) +++ python/branches/py3k/Misc/NEWS Wed May 5 18:18:31 2010 @@ -348,6 +348,8 @@ Library ------- +- Issue #7755: Use an unencumbered audio file for tests. + - Issue #8621: uuid.uuid4() returned the same sequence of values in the parent and any children created using ``os.fork`` on MacOS X 10.6. From python-checkins at python.org Wed May 5 18:27:30 2010 From: python-checkins at python.org (antoine.pitrou) Date: Wed, 5 May 2010 18:27:30 +0200 (CEST) Subject: [Python-checkins] r80796 - python/trunk/Modules/_io/fileio.c Message-ID: <20100505162730.4EEE1EE9A3@mail.python.org> Author: antoine.pitrou Date: Wed May 5 18:27:30 2010 New Revision: 80796 Log: Untabify Modules/_io/fileio.c Modified: python/trunk/Modules/_io/fileio.c Modified: python/trunk/Modules/_io/fileio.c ============================================================================== --- python/trunk/Modules/_io/fileio.c (original) +++ python/trunk/Modules/_io/fileio.c Wed May 5 18:27:30 2010 @@ -49,14 +49,14 @@ #endif typedef struct { - PyObject_HEAD - int fd; - unsigned int readable : 1; - unsigned int writable : 1; - signed int seekable : 2; /* -1 means unknown */ - unsigned int closefd : 1; - PyObject *weakreflist; - PyObject *dict; + PyObject_HEAD + int fd; + unsigned int readable : 1; + unsigned int writable : 1; + signed int seekable : 2; /* -1 means unknown */ + unsigned int closefd : 1; + PyObject *weakreflist; + PyObject *dict; } fileio; PyTypeObject PyFileIO_Type; @@ -66,7 +66,7 @@ int _PyFileIO_closed(PyObject *self) { - return ((fileio *)self)->fd < 0; + return ((fileio *)self)->fd < 0; } static PyObject * @@ -78,64 +78,64 @@ static int internal_close(fileio *self) { - int err = 0; - int save_errno = 0; - if (self->fd >= 0) { - int fd = self->fd; - self->fd = -1; - /* fd is accessible and someone else may have closed it */ - if (_PyVerify_fd(fd)) { - Py_BEGIN_ALLOW_THREADS - err = close(fd); - if (err < 0) - save_errno = errno; - Py_END_ALLOW_THREADS - } else { - save_errno = errno; - err = -1; - } - } - if (err < 0) { - errno = save_errno; - PyErr_SetFromErrno(PyExc_IOError); - return -1; - } - return 0; + int err = 0; + int save_errno = 0; + if (self->fd >= 0) { + int fd = self->fd; + self->fd = -1; + /* fd is accessible and someone else may have closed it */ + if (_PyVerify_fd(fd)) { + Py_BEGIN_ALLOW_THREADS + err = close(fd); + if (err < 0) + save_errno = errno; + Py_END_ALLOW_THREADS + } else { + save_errno = errno; + err = -1; + } + } + if (err < 0) { + errno = save_errno; + PyErr_SetFromErrno(PyExc_IOError); + return -1; + } + return 0; } static PyObject * fileio_close(fileio *self) { - if (!self->closefd) { - self->fd = -1; - Py_RETURN_NONE; - } - errno = internal_close(self); - if (errno < 0) - return NULL; + if (!self->closefd) { + self->fd = -1; + Py_RETURN_NONE; + } + errno = internal_close(self); + if (errno < 0) + return NULL; - return PyObject_CallMethod((PyObject*)&PyRawIOBase_Type, - "close", "O", self); + return PyObject_CallMethod((PyObject*)&PyRawIOBase_Type, + "close", "O", self); } static PyObject * fileio_new(PyTypeObject *type, PyObject *args, PyObject *kwds) { - fileio *self; + fileio *self; - assert(type != NULL && type->tp_alloc != NULL); + assert(type != NULL && type->tp_alloc != NULL); - self = (fileio *) type->tp_alloc(type, 0); - if (self != NULL) { - self->fd = -1; - self->readable = 0; - self->writable = 0; - self->seekable = -1; - self->closefd = 1; - self->weakreflist = NULL; - } + self = (fileio *) type->tp_alloc(type, 0); + if (self != NULL) { + self->fd = -1; + self->readable = 0; + self->writable = 0; + self->seekable = -1; + self->closefd = 1; + self->weakreflist = NULL; + } - return (PyObject *) self; + return (PyObject *) self; } /* On Unix, open will succeed for directories. @@ -146,535 +146,535 @@ dircheck(fileio* self, const char *name) { #if defined(HAVE_FSTAT) && defined(S_IFDIR) && defined(EISDIR) - struct stat buf; - if (self->fd < 0) - return 0; - if (fstat(self->fd, &buf) == 0 && S_ISDIR(buf.st_mode)) { - char *msg = strerror(EISDIR); - PyObject *exc; - if (internal_close(self)) - return -1; - - exc = PyObject_CallFunction(PyExc_IOError, "(iss)", - EISDIR, msg, name); - PyErr_SetObject(PyExc_IOError, exc); - Py_XDECREF(exc); - return -1; - } + struct stat buf; + if (self->fd < 0) + return 0; + if (fstat(self->fd, &buf) == 0 && S_ISDIR(buf.st_mode)) { + char *msg = strerror(EISDIR); + PyObject *exc; + if (internal_close(self)) + return -1; + + exc = PyObject_CallFunction(PyExc_IOError, "(iss)", + EISDIR, msg, name); + PyErr_SetObject(PyExc_IOError, exc); + Py_XDECREF(exc); + return -1; + } #endif - return 0; + return 0; } static int check_fd(int fd) { #if defined(HAVE_FSTAT) - struct stat buf; - if (!_PyVerify_fd(fd) || (fstat(fd, &buf) < 0 && errno == EBADF)) { - PyObject *exc; - char *msg = strerror(EBADF); - exc = PyObject_CallFunction(PyExc_OSError, "(is)", - EBADF, msg); - PyErr_SetObject(PyExc_OSError, exc); - Py_XDECREF(exc); - return -1; - } + struct stat buf; + if (!_PyVerify_fd(fd) || (fstat(fd, &buf) < 0 && errno == EBADF)) { + PyObject *exc; + char *msg = strerror(EBADF); + exc = PyObject_CallFunction(PyExc_OSError, "(is)", + EBADF, msg); + PyErr_SetObject(PyExc_OSError, exc); + Py_XDECREF(exc); + return -1; + } #endif - return 0; + return 0; } static int fileio_init(PyObject *oself, PyObject *args, PyObject *kwds) { - fileio *self = (fileio *) oself; - static char *kwlist[] = {"file", "mode", "closefd", NULL}; - const char *name = NULL; - PyObject *nameobj, *stringobj = NULL; - char *mode = "r"; - char *s; + fileio *self = (fileio *) oself; + static char *kwlist[] = {"file", "mode", "closefd", NULL}; + const char *name = NULL; + PyObject *nameobj, *stringobj = NULL; + char *mode = "r"; + char *s; #ifdef MS_WINDOWS - Py_UNICODE *widename = NULL; + Py_UNICODE *widename = NULL; #endif - int ret = 0; - int rwa = 0, plus = 0, append = 0; - int flags = 0; - int fd = -1; - int closefd = 1; - - assert(PyFileIO_Check(oself)); - if (self->fd >= 0) { - /* Have to close the existing file first. */ - if (internal_close(self) < 0) - return -1; - } - - if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|si:fileio", - kwlist, &nameobj, &mode, &closefd)) - return -1; - - if (PyFloat_Check(nameobj)) { - PyErr_SetString(PyExc_TypeError, - "integer argument expected, got float"); - return -1; - } - - fd = PyLong_AsLong(nameobj); - if (fd < 0) { - if (!PyErr_Occurred()) { - PyErr_SetString(PyExc_ValueError, - "Negative filedescriptor"); - return -1; - } - PyErr_Clear(); - } + int ret = 0; + int rwa = 0, plus = 0, append = 0; + int flags = 0; + int fd = -1; + int closefd = 1; + + assert(PyFileIO_Check(oself)); + if (self->fd >= 0) { + /* Have to close the existing file first. */ + if (internal_close(self) < 0) + return -1; + } + + if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|si:fileio", + kwlist, &nameobj, &mode, &closefd)) + return -1; + + if (PyFloat_Check(nameobj)) { + PyErr_SetString(PyExc_TypeError, + "integer argument expected, got float"); + return -1; + } + + fd = PyLong_AsLong(nameobj); + if (fd < 0) { + if (!PyErr_Occurred()) { + PyErr_SetString(PyExc_ValueError, + "Negative filedescriptor"); + return -1; + } + PyErr_Clear(); + } #ifdef MS_WINDOWS - if (PyUnicode_Check(nameobj)) - widename = PyUnicode_AS_UNICODE(nameobj); - if (widename == NULL) + if (PyUnicode_Check(nameobj)) + widename = PyUnicode_AS_UNICODE(nameobj); + if (widename == NULL) #endif - if (fd < 0) - { - if (PyBytes_Check(nameobj) || PyByteArray_Check(nameobj)) { - Py_ssize_t namelen; - if (PyObject_AsCharBuffer(nameobj, &name, &namelen) < 0) - return -1; - } - else { - PyObject *u = PyUnicode_FromObject(nameobj); - - if (u == NULL) - return -1; - - stringobj = PyUnicode_AsEncodedString( - u, Py_FileSystemDefaultEncoding, NULL); - Py_DECREF(u); - if (stringobj == NULL) - return -1; - if (!PyBytes_Check(stringobj)) { - PyErr_SetString(PyExc_TypeError, - "encoder failed to return bytes"); - goto error; - } - name = PyBytes_AS_STRING(stringobj); - } - } - - s = mode; - while (*s) { - switch (*s++) { - case 'r': - if (rwa) { - bad_mode: - PyErr_SetString(PyExc_ValueError, - "Must have exactly one of read/write/append mode"); - goto error; - } - rwa = 1; - self->readable = 1; - break; - case 'w': - if (rwa) - goto bad_mode; - rwa = 1; - self->writable = 1; - flags |= O_CREAT | O_TRUNC; - break; - case 'a': - if (rwa) - goto bad_mode; - rwa = 1; - self->writable = 1; - flags |= O_CREAT; - append = 1; - break; - case 'b': - break; - case '+': - if (plus) - goto bad_mode; - self->readable = self->writable = 1; - plus = 1; - break; - default: - PyErr_Format(PyExc_ValueError, - "invalid mode: %.200s", mode); - goto error; - } - } - - if (!rwa) - goto bad_mode; - - if (self->readable && self->writable) - flags |= O_RDWR; - else if (self->readable) - flags |= O_RDONLY; - else - flags |= O_WRONLY; + if (fd < 0) + { + if (PyBytes_Check(nameobj) || PyByteArray_Check(nameobj)) { + Py_ssize_t namelen; + if (PyObject_AsCharBuffer(nameobj, &name, &namelen) < 0) + return -1; + } + else { + PyObject *u = PyUnicode_FromObject(nameobj); + + if (u == NULL) + return -1; + + stringobj = PyUnicode_AsEncodedString( + u, Py_FileSystemDefaultEncoding, NULL); + Py_DECREF(u); + if (stringobj == NULL) + return -1; + if (!PyBytes_Check(stringobj)) { + PyErr_SetString(PyExc_TypeError, + "encoder failed to return bytes"); + goto error; + } + name = PyBytes_AS_STRING(stringobj); + } + } + + s = mode; + while (*s) { + switch (*s++) { + case 'r': + if (rwa) { + bad_mode: + PyErr_SetString(PyExc_ValueError, + "Must have exactly one of read/write/append mode"); + goto error; + } + rwa = 1; + self->readable = 1; + break; + case 'w': + if (rwa) + goto bad_mode; + rwa = 1; + self->writable = 1; + flags |= O_CREAT | O_TRUNC; + break; + case 'a': + if (rwa) + goto bad_mode; + rwa = 1; + self->writable = 1; + flags |= O_CREAT; + append = 1; + break; + case 'b': + break; + case '+': + if (plus) + goto bad_mode; + self->readable = self->writable = 1; + plus = 1; + break; + default: + PyErr_Format(PyExc_ValueError, + "invalid mode: %.200s", mode); + goto error; + } + } + + if (!rwa) + goto bad_mode; + + if (self->readable && self->writable) + flags |= O_RDWR; + else if (self->readable) + flags |= O_RDONLY; + else + flags |= O_WRONLY; #ifdef O_BINARY - flags |= O_BINARY; + flags |= O_BINARY; #endif #ifdef O_APPEND - if (append) - flags |= O_APPEND; + if (append) + flags |= O_APPEND; #endif - if (fd >= 0) { - if (check_fd(fd)) - goto error; - self->fd = fd; - self->closefd = closefd; - } - else { - self->closefd = 1; - if (!closefd) { - PyErr_SetString(PyExc_ValueError, - "Cannot use closefd=False with file name"); - goto error; - } + if (fd >= 0) { + if (check_fd(fd)) + goto error; + self->fd = fd; + self->closefd = closefd; + } + else { + self->closefd = 1; + if (!closefd) { + PyErr_SetString(PyExc_ValueError, + "Cannot use closefd=False with file name"); + goto error; + } - Py_BEGIN_ALLOW_THREADS - errno = 0; + Py_BEGIN_ALLOW_THREADS + errno = 0; #ifdef MS_WINDOWS - if (widename != NULL) - self->fd = _wopen(widename, flags, 0666); - else + if (widename != NULL) + self->fd = _wopen(widename, flags, 0666); + else #endif - self->fd = open(name, flags, 0666); - Py_END_ALLOW_THREADS - if (self->fd < 0) { + self->fd = open(name, flags, 0666); + Py_END_ALLOW_THREADS + if (self->fd < 0) { #ifdef MS_WINDOWS - if (widename != NULL) - PyErr_SetFromErrnoWithUnicodeFilename(PyExc_IOError, widename); - else + if (widename != NULL) + PyErr_SetFromErrnoWithUnicodeFilename(PyExc_IOError, widename); + else #endif - PyErr_SetFromErrnoWithFilename(PyExc_IOError, name); - goto error; - } - if(dircheck(self, name) < 0) - goto error; - } - - if (PyObject_SetAttrString((PyObject *)self, "name", nameobj) < 0) - goto error; - - if (append) { - /* For consistent behaviour, we explicitly seek to the - end of file (otherwise, it might be done only on the - first write()). */ - PyObject *pos = portable_lseek(self->fd, NULL, 2); - if (pos == NULL) - goto error; - Py_DECREF(pos); - } + PyErr_SetFromErrnoWithFilename(PyExc_IOError, name); + goto error; + } + if(dircheck(self, name) < 0) + goto error; + } + + if (PyObject_SetAttrString((PyObject *)self, "name", nameobj) < 0) + goto error; + + if (append) { + /* For consistent behaviour, we explicitly seek to the + end of file (otherwise, it might be done only on the + first write()). */ + PyObject *pos = portable_lseek(self->fd, NULL, 2); + if (pos == NULL) + goto error; + Py_DECREF(pos); + } - goto done; + goto done; error: - ret = -1; + ret = -1; done: - Py_CLEAR(stringobj); - return ret; + Py_CLEAR(stringobj); + return ret; } static int fileio_traverse(fileio *self, visitproc visit, void *arg) { - Py_VISIT(self->dict); - return 0; + Py_VISIT(self->dict); + return 0; } static int fileio_clear(fileio *self) { - Py_CLEAR(self->dict); - return 0; + Py_CLEAR(self->dict); + return 0; } static void fileio_dealloc(fileio *self) { - if (_PyIOBase_finalize((PyObject *) self) < 0) - return; - _PyObject_GC_UNTRACK(self); - if (self->weakreflist != NULL) - PyObject_ClearWeakRefs((PyObject *) self); - Py_CLEAR(self->dict); - Py_TYPE(self)->tp_free((PyObject *)self); + if (_PyIOBase_finalize((PyObject *) self) < 0) + return; + _PyObject_GC_UNTRACK(self); + if (self->weakreflist != NULL) + PyObject_ClearWeakRefs((PyObject *) self); + Py_CLEAR(self->dict); + Py_TYPE(self)->tp_free((PyObject *)self); } static PyObject * err_closed(void) { - PyErr_SetString(PyExc_ValueError, "I/O operation on closed file"); - return NULL; + PyErr_SetString(PyExc_ValueError, "I/O operation on closed file"); + return NULL; } static PyObject * err_mode(char *action) { - PyErr_Format(PyExc_ValueError, "File not open for %s", action); - return NULL; + PyErr_Format(PyExc_ValueError, "File not open for %s", action); + return NULL; } static PyObject * fileio_fileno(fileio *self) { - if (self->fd < 0) - return err_closed(); - return PyInt_FromLong((long) self->fd); + if (self->fd < 0) + return err_closed(); + return PyInt_FromLong((long) self->fd); } static PyObject * fileio_readable(fileio *self) { - if (self->fd < 0) - return err_closed(); - return PyBool_FromLong((long) self->readable); + if (self->fd < 0) + return err_closed(); + return PyBool_FromLong((long) self->readable); } static PyObject * fileio_writable(fileio *self) { - if (self->fd < 0) - return err_closed(); - return PyBool_FromLong((long) self->writable); + if (self->fd < 0) + return err_closed(); + return PyBool_FromLong((long) self->writable); } static PyObject * fileio_seekable(fileio *self) { - if (self->fd < 0) - return err_closed(); - if (self->seekable < 0) { - PyObject *pos = portable_lseek(self->fd, NULL, SEEK_CUR); - if (pos == NULL) { - PyErr_Clear(); - self->seekable = 0; - } else { - Py_DECREF(pos); - self->seekable = 1; - } - } - return PyBool_FromLong((long) self->seekable); + if (self->fd < 0) + return err_closed(); + if (self->seekable < 0) { + PyObject *pos = portable_lseek(self->fd, NULL, SEEK_CUR); + if (pos == NULL) { + PyErr_Clear(); + self->seekable = 0; + } else { + Py_DECREF(pos); + self->seekable = 1; + } + } + return PyBool_FromLong((long) self->seekable); } static PyObject * fileio_readinto(fileio *self, PyObject *args) { - Py_buffer pbuf; - Py_ssize_t n; + Py_buffer pbuf; + Py_ssize_t n; - if (self->fd < 0) - return err_closed(); - if (!self->readable) - return err_mode("reading"); - - if (!PyArg_ParseTuple(args, "w*", &pbuf)) - return NULL; - - if (_PyVerify_fd(self->fd)) { - Py_BEGIN_ALLOW_THREADS - errno = 0; - n = read(self->fd, pbuf.buf, pbuf.len); - Py_END_ALLOW_THREADS - } else - n = -1; - PyBuffer_Release(&pbuf); - if (n < 0) { - if (errno == EAGAIN) - Py_RETURN_NONE; - PyErr_SetFromErrno(PyExc_IOError); - return NULL; - } + if (self->fd < 0) + return err_closed(); + if (!self->readable) + return err_mode("reading"); + + if (!PyArg_ParseTuple(args, "w*", &pbuf)) + return NULL; + + if (_PyVerify_fd(self->fd)) { + Py_BEGIN_ALLOW_THREADS + errno = 0; + n = read(self->fd, pbuf.buf, pbuf.len); + Py_END_ALLOW_THREADS + } else + n = -1; + PyBuffer_Release(&pbuf); + if (n < 0) { + if (errno == EAGAIN) + Py_RETURN_NONE; + PyErr_SetFromErrno(PyExc_IOError); + return NULL; + } - return PyLong_FromSsize_t(n); + return PyLong_FromSsize_t(n); } static size_t new_buffersize(fileio *self, size_t currentsize) { #ifdef HAVE_FSTAT - off_t pos, end; - struct stat st; - if (fstat(self->fd, &st) == 0) { - end = st.st_size; - pos = lseek(self->fd, 0L, SEEK_CUR); - /* Files claiming a size smaller than SMALLCHUNK may - actually be streaming pseudo-files. In this case, we - apply the more aggressive algorithm below. - */ - if (end >= SMALLCHUNK && end >= pos && pos >= 0) { - /* Add 1 so if the file were to grow we'd notice. */ - return currentsize + end - pos + 1; - } - } + off_t pos, end; + struct stat st; + if (fstat(self->fd, &st) == 0) { + end = st.st_size; + pos = lseek(self->fd, 0L, SEEK_CUR); + /* Files claiming a size smaller than SMALLCHUNK may + actually be streaming pseudo-files. In this case, we + apply the more aggressive algorithm below. + */ + if (end >= SMALLCHUNK && end >= pos && pos >= 0) { + /* Add 1 so if the file were to grow we'd notice. */ + return currentsize + end - pos + 1; + } + } #endif - if (currentsize > SMALLCHUNK) { - /* Keep doubling until we reach BIGCHUNK; - then keep adding BIGCHUNK. */ - if (currentsize <= BIGCHUNK) - return currentsize + currentsize; - else - return currentsize + BIGCHUNK; - } - return currentsize + SMALLCHUNK; + if (currentsize > SMALLCHUNK) { + /* Keep doubling until we reach BIGCHUNK; + then keep adding BIGCHUNK. */ + if (currentsize <= BIGCHUNK) + return currentsize + currentsize; + else + return currentsize + BIGCHUNK; + } + return currentsize + SMALLCHUNK; } static PyObject * fileio_readall(fileio *self) { - PyObject *result; - Py_ssize_t total = 0; - int n; - - if (!_PyVerify_fd(self->fd)) - return PyErr_SetFromErrno(PyExc_IOError); - - result = PyBytes_FromStringAndSize(NULL, SMALLCHUNK); - if (result == NULL) - return NULL; - - while (1) { - size_t newsize = new_buffersize(self, total); - if (newsize > PY_SSIZE_T_MAX || newsize <= 0) { - PyErr_SetString(PyExc_OverflowError, - "unbounded read returned more bytes " - "than a Python string can hold "); - Py_DECREF(result); - return NULL; - } - - if (PyBytes_GET_SIZE(result) < (Py_ssize_t)newsize) { - if (_PyBytes_Resize(&result, newsize) < 0) { - if (total == 0) { - Py_DECREF(result); - return NULL; - } - PyErr_Clear(); - break; - } - } - Py_BEGIN_ALLOW_THREADS - errno = 0; - n = read(self->fd, - PyBytes_AS_STRING(result) + total, - newsize - total); - Py_END_ALLOW_THREADS - if (n == 0) - break; - if (n < 0) { - if (total > 0) - break; - if (errno == EAGAIN) { - Py_DECREF(result); - Py_RETURN_NONE; - } - Py_DECREF(result); - PyErr_SetFromErrno(PyExc_IOError); - return NULL; - } - total += n; - } - - if (PyBytes_GET_SIZE(result) > total) { - if (_PyBytes_Resize(&result, total) < 0) { - /* This should never happen, but just in case */ - Py_DECREF(result); - return NULL; - } - } - return result; + PyObject *result; + Py_ssize_t total = 0; + int n; + + if (!_PyVerify_fd(self->fd)) + return PyErr_SetFromErrno(PyExc_IOError); + + result = PyBytes_FromStringAndSize(NULL, SMALLCHUNK); + if (result == NULL) + return NULL; + + while (1) { + size_t newsize = new_buffersize(self, total); + if (newsize > PY_SSIZE_T_MAX || newsize <= 0) { + PyErr_SetString(PyExc_OverflowError, + "unbounded read returned more bytes " + "than a Python string can hold "); + Py_DECREF(result); + return NULL; + } + + if (PyBytes_GET_SIZE(result) < (Py_ssize_t)newsize) { + if (_PyBytes_Resize(&result, newsize) < 0) { + if (total == 0) { + Py_DECREF(result); + return NULL; + } + PyErr_Clear(); + break; + } + } + Py_BEGIN_ALLOW_THREADS + errno = 0; + n = read(self->fd, + PyBytes_AS_STRING(result) + total, + newsize - total); + Py_END_ALLOW_THREADS + if (n == 0) + break; + if (n < 0) { + if (total > 0) + break; + if (errno == EAGAIN) { + Py_DECREF(result); + Py_RETURN_NONE; + } + Py_DECREF(result); + PyErr_SetFromErrno(PyExc_IOError); + return NULL; + } + total += n; + } + + if (PyBytes_GET_SIZE(result) > total) { + if (_PyBytes_Resize(&result, total) < 0) { + /* This should never happen, but just in case */ + Py_DECREF(result); + return NULL; + } + } + return result; } static PyObject * fileio_read(fileio *self, PyObject *args) { - char *ptr; - Py_ssize_t n; - Py_ssize_t size = -1; - PyObject *bytes; - - if (self->fd < 0) - return err_closed(); - if (!self->readable) - return err_mode("reading"); - - if (!PyArg_ParseTuple(args, "|O&", &_PyIO_ConvertSsize_t, &size)) - return NULL; - - if (size < 0) { - return fileio_readall(self); - } - - bytes = PyBytes_FromStringAndSize(NULL, size); - if (bytes == NULL) - return NULL; - ptr = PyBytes_AS_STRING(bytes); - - if (_PyVerify_fd(self->fd)) { - Py_BEGIN_ALLOW_THREADS - errno = 0; - n = read(self->fd, ptr, size); - Py_END_ALLOW_THREADS - } else - n = -1; - - if (n < 0) { - Py_DECREF(bytes); - if (errno == EAGAIN) - Py_RETURN_NONE; - PyErr_SetFromErrno(PyExc_IOError); - return NULL; - } - - if (n != size) { - if (_PyBytes_Resize(&bytes, n) < 0) { - Py_DECREF(bytes); - return NULL; - } - } + char *ptr; + Py_ssize_t n; + Py_ssize_t size = -1; + PyObject *bytes; + + if (self->fd < 0) + return err_closed(); + if (!self->readable) + return err_mode("reading"); + + if (!PyArg_ParseTuple(args, "|O&", &_PyIO_ConvertSsize_t, &size)) + return NULL; + + if (size < 0) { + return fileio_readall(self); + } + + bytes = PyBytes_FromStringAndSize(NULL, size); + if (bytes == NULL) + return NULL; + ptr = PyBytes_AS_STRING(bytes); + + if (_PyVerify_fd(self->fd)) { + Py_BEGIN_ALLOW_THREADS + errno = 0; + n = read(self->fd, ptr, size); + Py_END_ALLOW_THREADS + } else + n = -1; + + if (n < 0) { + Py_DECREF(bytes); + if (errno == EAGAIN) + Py_RETURN_NONE; + PyErr_SetFromErrno(PyExc_IOError); + return NULL; + } + + if (n != size) { + if (_PyBytes_Resize(&bytes, n) < 0) { + Py_DECREF(bytes); + return NULL; + } + } - return (PyObject *) bytes; + return (PyObject *) bytes; } static PyObject * fileio_write(fileio *self, PyObject *args) { - Py_buffer pbuf; - Py_ssize_t n; + Py_buffer pbuf; + Py_ssize_t n; - if (self->fd < 0) - return err_closed(); - if (!self->writable) - return err_mode("writing"); - - if (!PyArg_ParseTuple(args, "s*", &pbuf)) - return NULL; - - if (_PyVerify_fd(self->fd)) { - Py_BEGIN_ALLOW_THREADS - errno = 0; - n = write(self->fd, pbuf.buf, pbuf.len); - Py_END_ALLOW_THREADS - } else - n = -1; - - PyBuffer_Release(&pbuf); - - if (n < 0) { - if (errno == EAGAIN) - Py_RETURN_NONE; - PyErr_SetFromErrno(PyExc_IOError); - return NULL; - } + if (self->fd < 0) + return err_closed(); + if (!self->writable) + return err_mode("writing"); + + if (!PyArg_ParseTuple(args, "s*", &pbuf)) + return NULL; + + if (_PyVerify_fd(self->fd)) { + Py_BEGIN_ALLOW_THREADS + errno = 0; + n = write(self->fd, pbuf.buf, pbuf.len); + Py_END_ALLOW_THREADS + } else + n = -1; + + PyBuffer_Release(&pbuf); + + if (n < 0) { + if (errno == EAGAIN) + Py_RETURN_NONE; + PyErr_SetFromErrno(PyExc_IOError); + return NULL; + } - return PyLong_FromSsize_t(n); + return PyLong_FromSsize_t(n); } /* XXX Windows support below is likely incomplete */ @@ -683,240 +683,240 @@ static PyObject * portable_lseek(int fd, PyObject *posobj, int whence) { - Py_off_t pos, res; + Py_off_t pos, res; #ifdef SEEK_SET - /* Turn 0, 1, 2 into SEEK_{SET,CUR,END} */ - switch (whence) { + /* Turn 0, 1, 2 into SEEK_{SET,CUR,END} */ + switch (whence) { #if SEEK_SET != 0 - case 0: whence = SEEK_SET; break; + case 0: whence = SEEK_SET; break; #endif #if SEEK_CUR != 1 - case 1: whence = SEEK_CUR; break; + case 1: whence = SEEK_CUR; break; #endif #if SEEK_END != 2 - case 2: whence = SEEK_END; break; + case 2: whence = SEEK_END; break; #endif - } + } #endif /* SEEK_SET */ - if (posobj == NULL) - pos = 0; - else { - if(PyFloat_Check(posobj)) { - PyErr_SetString(PyExc_TypeError, "an integer is required"); - return NULL; - } + if (posobj == NULL) + pos = 0; + else { + if(PyFloat_Check(posobj)) { + PyErr_SetString(PyExc_TypeError, "an integer is required"); + return NULL; + } #if defined(HAVE_LARGEFILE_SUPPORT) - pos = PyLong_AsLongLong(posobj); + pos = PyLong_AsLongLong(posobj); #else - pos = PyLong_AsLong(posobj); + pos = PyLong_AsLong(posobj); #endif - if (PyErr_Occurred()) - return NULL; - } + if (PyErr_Occurred()) + return NULL; + } - if (_PyVerify_fd(fd)) { - Py_BEGIN_ALLOW_THREADS + if (_PyVerify_fd(fd)) { + Py_BEGIN_ALLOW_THREADS #if defined(MS_WIN64) || defined(MS_WINDOWS) - res = _lseeki64(fd, pos, whence); + res = _lseeki64(fd, pos, whence); #else - res = lseek(fd, pos, whence); + res = lseek(fd, pos, whence); #endif - Py_END_ALLOW_THREADS - } else - res = -1; - if (res < 0) - return PyErr_SetFromErrno(PyExc_IOError); + Py_END_ALLOW_THREADS + } else + res = -1; + if (res < 0) + return PyErr_SetFromErrno(PyExc_IOError); #if defined(HAVE_LARGEFILE_SUPPORT) - return PyLong_FromLongLong(res); + return PyLong_FromLongLong(res); #else - return PyLong_FromLong(res); + return PyLong_FromLong(res); #endif } static PyObject * fileio_seek(fileio *self, PyObject *args) { - PyObject *posobj; - int whence = 0; + PyObject *posobj; + int whence = 0; - if (self->fd < 0) - return err_closed(); + if (self->fd < 0) + return err_closed(); - if (!PyArg_ParseTuple(args, "O|i", &posobj, &whence)) - return NULL; + if (!PyArg_ParseTuple(args, "O|i", &posobj, &whence)) + return NULL; - return portable_lseek(self->fd, posobj, whence); + return portable_lseek(self->fd, posobj, whence); } static PyObject * fileio_tell(fileio *self, PyObject *args) { - if (self->fd < 0) - return err_closed(); + if (self->fd < 0) + return err_closed(); - return portable_lseek(self->fd, NULL, 1); + return portable_lseek(self->fd, NULL, 1); } #ifdef HAVE_FTRUNCATE static PyObject * fileio_truncate(fileio *self, PyObject *args) { - PyObject *posobj = NULL; /* the new size wanted by the user */ + PyObject *posobj = NULL; /* the new size wanted by the user */ #ifndef MS_WINDOWS - Py_off_t pos; + Py_off_t pos; #endif - int ret; - int fd; + int ret; + int fd; - fd = self->fd; - if (fd < 0) - return err_closed(); - if (!self->writable) - return err_mode("writing"); - - if (!PyArg_ParseTuple(args, "|O", &posobj)) - return NULL; - - if (posobj == Py_None || posobj == NULL) { - /* Get the current position. */ - posobj = portable_lseek(fd, NULL, 1); - if (posobj == NULL) - return NULL; - } - else { - Py_INCREF(posobj); - } + fd = self->fd; + if (fd < 0) + return err_closed(); + if (!self->writable) + return err_mode("writing"); + + if (!PyArg_ParseTuple(args, "|O", &posobj)) + return NULL; + + if (posobj == Py_None || posobj == NULL) { + /* Get the current position. */ + posobj = portable_lseek(fd, NULL, 1); + if (posobj == NULL) + return NULL; + } + else { + Py_INCREF(posobj); + } #ifdef MS_WINDOWS - /* MS _chsize doesn't work if newsize doesn't fit in 32 bits, - so don't even try using it. */ - { - PyObject *oldposobj, *tempposobj; - HANDLE hFile; - - /* we save the file pointer position */ - oldposobj = portable_lseek(fd, NULL, 1); - if (oldposobj == NULL) { - Py_DECREF(posobj); - return NULL; - } - - /* we then move to the truncation position */ - tempposobj = portable_lseek(fd, posobj, 0); - if (tempposobj == NULL) { - Py_DECREF(oldposobj); - Py_DECREF(posobj); - return NULL; - } - Py_DECREF(tempposobj); - - /* Truncate. Note that this may grow the file! */ - Py_BEGIN_ALLOW_THREADS - errno = 0; - hFile = (HANDLE)_get_osfhandle(fd); - ret = hFile == (HANDLE)-1; /* testing for INVALID_HANDLE value */ - if (ret == 0) { - ret = SetEndOfFile(hFile) == 0; - if (ret) - errno = EACCES; - } - Py_END_ALLOW_THREADS - - /* we restore the file pointer position in any case */ - tempposobj = portable_lseek(fd, oldposobj, 0); - Py_DECREF(oldposobj); - if (tempposobj == NULL) { - Py_DECREF(posobj); - return NULL; - } - Py_DECREF(tempposobj); - } + /* MS _chsize doesn't work if newsize doesn't fit in 32 bits, + so don't even try using it. */ + { + PyObject *oldposobj, *tempposobj; + HANDLE hFile; + + /* we save the file pointer position */ + oldposobj = portable_lseek(fd, NULL, 1); + if (oldposobj == NULL) { + Py_DECREF(posobj); + return NULL; + } + + /* we then move to the truncation position */ + tempposobj = portable_lseek(fd, posobj, 0); + if (tempposobj == NULL) { + Py_DECREF(oldposobj); + Py_DECREF(posobj); + return NULL; + } + Py_DECREF(tempposobj); + + /* Truncate. Note that this may grow the file! */ + Py_BEGIN_ALLOW_THREADS + errno = 0; + hFile = (HANDLE)_get_osfhandle(fd); + ret = hFile == (HANDLE)-1; /* testing for INVALID_HANDLE value */ + if (ret == 0) { + ret = SetEndOfFile(hFile) == 0; + if (ret) + errno = EACCES; + } + Py_END_ALLOW_THREADS + + /* we restore the file pointer position in any case */ + tempposobj = portable_lseek(fd, oldposobj, 0); + Py_DECREF(oldposobj); + if (tempposobj == NULL) { + Py_DECREF(posobj); + return NULL; + } + Py_DECREF(tempposobj); + } #else #if defined(HAVE_LARGEFILE_SUPPORT) - pos = PyLong_AsLongLong(posobj); + pos = PyLong_AsLongLong(posobj); #else - pos = PyLong_AsLong(posobj); + pos = PyLong_AsLong(posobj); #endif - if (PyErr_Occurred()){ - Py_DECREF(posobj); - return NULL; - } - - Py_BEGIN_ALLOW_THREADS - errno = 0; - ret = ftruncate(fd, pos); - Py_END_ALLOW_THREADS + if (PyErr_Occurred()){ + Py_DECREF(posobj); + return NULL; + } + + Py_BEGIN_ALLOW_THREADS + errno = 0; + ret = ftruncate(fd, pos); + Py_END_ALLOW_THREADS #endif /* !MS_WINDOWS */ - if (ret != 0) { - Py_DECREF(posobj); - PyErr_SetFromErrno(PyExc_IOError); - return NULL; - } + if (ret != 0) { + Py_DECREF(posobj); + PyErr_SetFromErrno(PyExc_IOError); + return NULL; + } - return posobj; + return posobj; } #endif /* HAVE_FTRUNCATE */ static char * mode_string(fileio *self) { - if (self->readable) { - if (self->writable) - return "rb+"; - else - return "rb"; - } - else - return "wb"; + if (self->readable) { + if (self->writable) + return "rb+"; + else + return "rb"; + } + else + return "wb"; } static PyObject * fileio_repr(fileio *self) { - PyObject *nameobj, *res; + PyObject *nameobj, *res; - if (self->fd < 0) - return PyString_FromFormat("<_io.FileIO [closed]>"); + if (self->fd < 0) + return PyString_FromFormat("<_io.FileIO [closed]>"); - nameobj = PyObject_GetAttrString((PyObject *) self, "name"); - if (nameobj == NULL) { - if (PyErr_ExceptionMatches(PyExc_AttributeError)) - PyErr_Clear(); - else - return NULL; - res = PyString_FromFormat("<_io.FileIO fd=%d mode='%s'>", - self->fd, mode_string(self)); - } - else { - PyObject *repr = PyObject_Repr(nameobj); - Py_DECREF(nameobj); - if (repr == NULL) - return NULL; - res = PyString_FromFormat("<_io.FileIO name=%s mode='%s'>", - PyString_AS_STRING(repr), - mode_string(self)); - Py_DECREF(repr); - } - return res; + nameobj = PyObject_GetAttrString((PyObject *) self, "name"); + if (nameobj == NULL) { + if (PyErr_ExceptionMatches(PyExc_AttributeError)) + PyErr_Clear(); + else + return NULL; + res = PyString_FromFormat("<_io.FileIO fd=%d mode='%s'>", + self->fd, mode_string(self)); + } + else { + PyObject *repr = PyObject_Repr(nameobj); + Py_DECREF(nameobj); + if (repr == NULL) + return NULL; + res = PyString_FromFormat("<_io.FileIO name=%s mode='%s'>", + PyString_AS_STRING(repr), + mode_string(self)); + Py_DECREF(repr); + } + return res; } static PyObject * fileio_isatty(fileio *self) { - long res; + long res; - if (self->fd < 0) - return err_closed(); - Py_BEGIN_ALLOW_THREADS - res = isatty(self->fd); - Py_END_ALLOW_THREADS - return PyBool_FromLong(res); + if (self->fd < 0) + return err_closed(); + Py_BEGIN_ALLOW_THREADS + res = isatty(self->fd); + Py_END_ALLOW_THREADS + return PyBool_FromLong(res); } @@ -924,7 +924,7 @@ "file(name: str[, mode: str]) -> file IO object\n" "\n" "Open a file. The mode can be 'r', 'w' or 'a' for reading (default),\n" -"writing or appending. The file will be created if it doesn't exist\n" +"writing or appending. The file will be created if it doesn't exist\n" "when opened for writing or appending; it will be truncated when\n" "opened for writing. Add a '+' to the mode to allow simultaneous\n" "reading and writing."); @@ -966,14 +966,14 @@ #ifdef HAVE_FTRUNCATE PyDoc_STRVAR(truncate_doc, -"truncate([size: int]) -> None. Truncate the file to at most size bytes.\n" +"truncate([size: int]) -> None. Truncate the file to at most size bytes.\n" "\n" "Size defaults to the current file position, as returned by tell()." "The current file position is changed to the value of size."); #endif PyDoc_STRVAR(tell_doc, -"tell() -> int. Current file position"); +"tell() -> int. Current file position"); PyDoc_STRVAR(readinto_doc, "readinto() -> Same as RawIOBase.readinto()."); @@ -997,22 +997,22 @@ "writable() -> bool. True if file was opened in a write mode."); static PyMethodDef fileio_methods[] = { - {"read", (PyCFunction)fileio_read, METH_VARARGS, read_doc}, - {"readall", (PyCFunction)fileio_readall, METH_NOARGS, readall_doc}, - {"readinto", (PyCFunction)fileio_readinto, METH_VARARGS, readinto_doc}, - {"write", (PyCFunction)fileio_write, METH_VARARGS, write_doc}, - {"seek", (PyCFunction)fileio_seek, METH_VARARGS, seek_doc}, - {"tell", (PyCFunction)fileio_tell, METH_VARARGS, tell_doc}, + {"read", (PyCFunction)fileio_read, METH_VARARGS, read_doc}, + {"readall", (PyCFunction)fileio_readall, METH_NOARGS, readall_doc}, + {"readinto", (PyCFunction)fileio_readinto, METH_VARARGS, readinto_doc}, + {"write", (PyCFunction)fileio_write, METH_VARARGS, write_doc}, + {"seek", (PyCFunction)fileio_seek, METH_VARARGS, seek_doc}, + {"tell", (PyCFunction)fileio_tell, METH_VARARGS, tell_doc}, #ifdef HAVE_FTRUNCATE - {"truncate", (PyCFunction)fileio_truncate, METH_VARARGS, truncate_doc}, + {"truncate", (PyCFunction)fileio_truncate, METH_VARARGS, truncate_doc}, #endif - {"close", (PyCFunction)fileio_close, METH_NOARGS, close_doc}, - {"seekable", (PyCFunction)fileio_seekable, METH_NOARGS, seekable_doc}, - {"readable", (PyCFunction)fileio_readable, METH_NOARGS, readable_doc}, - {"writable", (PyCFunction)fileio_writable, METH_NOARGS, writable_doc}, - {"fileno", (PyCFunction)fileio_fileno, METH_NOARGS, fileno_doc}, - {"isatty", (PyCFunction)fileio_isatty, METH_NOARGS, isatty_doc}, - {NULL, NULL} /* sentinel */ + {"close", (PyCFunction)fileio_close, METH_NOARGS, close_doc}, + {"seekable", (PyCFunction)fileio_seekable, METH_NOARGS, seekable_doc}, + {"readable", (PyCFunction)fileio_readable, METH_NOARGS, readable_doc}, + {"writable", (PyCFunction)fileio_writable, METH_NOARGS, writable_doc}, + {"fileno", (PyCFunction)fileio_fileno, METH_NOARGS, fileno_doc}, + {"isatty", (PyCFunction)fileio_isatty, METH_NOARGS, isatty_doc}, + {NULL, NULL} /* sentinel */ }; /* 'closed' and 'mode' are attributes for backwards compatibility reasons. */ @@ -1020,68 +1020,68 @@ static PyObject * get_closed(fileio *self, void *closure) { - return PyBool_FromLong((long)(self->fd < 0)); + return PyBool_FromLong((long)(self->fd < 0)); } static PyObject * get_closefd(fileio *self, void *closure) { - return PyBool_FromLong((long)(self->closefd)); + return PyBool_FromLong((long)(self->closefd)); } static PyObject * get_mode(fileio *self, void *closure) { - return PyUnicode_FromString(mode_string(self)); + return PyUnicode_FromString(mode_string(self)); } static PyGetSetDef fileio_getsetlist[] = { - {"closed", (getter)get_closed, NULL, "True if the file is closed"}, - {"closefd", (getter)get_closefd, NULL, - "True if the file descriptor will be closed"}, - {"mode", (getter)get_mode, NULL, "String giving the file mode"}, - {NULL}, + {"closed", (getter)get_closed, NULL, "True if the file is closed"}, + {"closefd", (getter)get_closefd, NULL, + "True if the file descriptor will be closed"}, + {"mode", (getter)get_mode, NULL, "String giving the file mode"}, + {NULL}, }; PyTypeObject PyFileIO_Type = { - PyVarObject_HEAD_INIT(NULL, 0) - "_io.FileIO", - sizeof(fileio), - 0, - (destructor)fileio_dealloc, /* tp_dealloc */ - 0, /* tp_print */ - 0, /* tp_getattr */ - 0, /* tp_setattr */ - 0, /* tp_reserved */ - (reprfunc)fileio_repr, /* 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_BASETYPE - | Py_TPFLAGS_HAVE_GC, /* tp_flags */ - fileio_doc, /* tp_doc */ - (traverseproc)fileio_traverse, /* tp_traverse */ - (inquiry)fileio_clear, /* tp_clear */ - 0, /* tp_richcompare */ - offsetof(fileio, weakreflist), /* tp_weaklistoffset */ - 0, /* tp_iter */ - 0, /* tp_iternext */ - fileio_methods, /* tp_methods */ - 0, /* tp_members */ - fileio_getsetlist, /* tp_getset */ - 0, /* tp_base */ - 0, /* tp_dict */ - 0, /* tp_descr_get */ - 0, /* tp_descr_set */ - offsetof(fileio, dict), /* tp_dictoffset */ - fileio_init, /* tp_init */ - PyType_GenericAlloc, /* tp_alloc */ - fileio_new, /* tp_new */ - PyObject_GC_Del, /* tp_free */ + PyVarObject_HEAD_INIT(NULL, 0) + "_io.FileIO", + sizeof(fileio), + 0, + (destructor)fileio_dealloc, /* tp_dealloc */ + 0, /* tp_print */ + 0, /* tp_getattr */ + 0, /* tp_setattr */ + 0, /* tp_reserved */ + (reprfunc)fileio_repr, /* 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_BASETYPE + | Py_TPFLAGS_HAVE_GC, /* tp_flags */ + fileio_doc, /* tp_doc */ + (traverseproc)fileio_traverse, /* tp_traverse */ + (inquiry)fileio_clear, /* tp_clear */ + 0, /* tp_richcompare */ + offsetof(fileio, weakreflist), /* tp_weaklistoffset */ + 0, /* tp_iter */ + 0, /* tp_iternext */ + fileio_methods, /* tp_methods */ + 0, /* tp_members */ + fileio_getsetlist, /* tp_getset */ + 0, /* tp_base */ + 0, /* tp_dict */ + 0, /* tp_descr_get */ + 0, /* tp_descr_set */ + offsetof(fileio, dict), /* tp_dictoffset */ + fileio_init, /* tp_init */ + PyType_GenericAlloc, /* tp_alloc */ + fileio_new, /* tp_new */ + PyObject_GC_Del, /* tp_free */ }; From python-checkins at python.org Wed May 5 18:29:26 2010 From: python-checkins at python.org (antoine.pitrou) Date: Wed, 5 May 2010 18:29:26 +0200 (CEST) Subject: [Python-checkins] r80797 - in python/branches/release26-maint: Modules/_fileio.c Message-ID: <20100505162926.26FEBEE9D6@mail.python.org> Author: antoine.pitrou Date: Wed May 5 18:29:25 2010 New Revision: 80797 Log: Merged revisions 80796 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r80796 | antoine.pitrou | 2010-05-05 18:27:30 +0200 (mer., 05 mai 2010) | 3 lines Untabify Modules/_io/fileio.c ........ Modified: python/branches/release26-maint/ (props changed) python/branches/release26-maint/Modules/_fileio.c Modified: python/branches/release26-maint/Modules/_fileio.c ============================================================================== --- python/branches/release26-maint/Modules/_fileio.c (original) +++ python/branches/release26-maint/Modules/_fileio.c Wed May 5 18:29:25 2010 @@ -28,13 +28,13 @@ #endif typedef struct { - PyObject_HEAD - int fd; - unsigned int readable : 1; - unsigned int writable : 1; - signed int seekable : 2; /* -1 means unknown */ - signed int closefd : 1; - PyObject *weakreflist; + PyObject_HEAD + int fd; + unsigned int readable : 1; + unsigned int writable : 1; + signed int seekable : 2; /* -1 means unknown */ + signed int closefd : 1; + PyObject *weakreflist; } PyFileIOObject; PyTypeObject PyFileIO_Type; @@ -48,52 +48,52 @@ static int internal_close(PyFileIOObject *self) { - int save_errno = 0; - if (self->fd >= 0) { - int fd = self->fd; - self->fd = -1; - Py_BEGIN_ALLOW_THREADS - if (close(fd) < 0) - save_errno = errno; - Py_END_ALLOW_THREADS - } - return save_errno; + int save_errno = 0; + if (self->fd >= 0) { + int fd = self->fd; + self->fd = -1; + Py_BEGIN_ALLOW_THREADS + if (close(fd) < 0) + save_errno = errno; + Py_END_ALLOW_THREADS + } + return save_errno; } static PyObject * fileio_close(PyFileIOObject *self) { - if (!self->closefd) { - self->fd = -1; - Py_RETURN_NONE; - } - errno = internal_close(self); - if (errno < 0) { - PyErr_SetFromErrno(PyExc_IOError); - return NULL; - } + if (!self->closefd) { + self->fd = -1; + Py_RETURN_NONE; + } + errno = internal_close(self); + if (errno < 0) { + PyErr_SetFromErrno(PyExc_IOError); + return NULL; + } - Py_RETURN_NONE; + Py_RETURN_NONE; } static PyObject * fileio_new(PyTypeObject *type, PyObject *args, PyObject *kews) { - PyFileIOObject *self; + PyFileIOObject *self; - assert(type != NULL && type->tp_alloc != NULL); + assert(type != NULL && type->tp_alloc != NULL); - self = (PyFileIOObject *) type->tp_alloc(type, 0); - if (self != NULL) { - self->fd = -1; - self->readable = 0; - self->writable = 0; - self->seekable = -1; - self->closefd = 1; - self->weakreflist = NULL; - } + self = (PyFileIOObject *) type->tp_alloc(type, 0); + if (self != NULL) { + self->fd = -1; + self->readable = 0; + self->writable = 0; + self->seekable = -1; + self->closefd = 1; + self->weakreflist = NULL; + } - return (PyObject *) self; + return (PyObject *) self; } /* On Unix, open will succeed for directories. @@ -104,321 +104,321 @@ dircheck(PyFileIOObject* self, char *name) { #if defined(HAVE_FSTAT) && defined(S_IFDIR) && defined(EISDIR) - struct stat buf; - if (self->fd < 0) - return 0; - if (fstat(self->fd, &buf) == 0 && S_ISDIR(buf.st_mode)) { - char *msg = strerror(EISDIR); - PyObject *exc; - internal_close(self); - - exc = PyObject_CallFunction(PyExc_IOError, "(iss)", - EISDIR, msg, name); - PyErr_SetObject(PyExc_IOError, exc); - Py_XDECREF(exc); - return -1; - } + struct stat buf; + if (self->fd < 0) + return 0; + if (fstat(self->fd, &buf) == 0 && S_ISDIR(buf.st_mode)) { + char *msg = strerror(EISDIR); + PyObject *exc; + internal_close(self); + + exc = PyObject_CallFunction(PyExc_IOError, "(iss)", + EISDIR, msg, name); + PyErr_SetObject(PyExc_IOError, exc); + Py_XDECREF(exc); + return -1; + } #endif - return 0; + return 0; } static int check_fd(int fd) { #if defined(HAVE_FSTAT) - struct stat buf; - if (fstat(fd, &buf) < 0 && errno == EBADF) { - PyObject *exc; - char *msg = strerror(EBADF); - exc = PyObject_CallFunction(PyExc_OSError, "(is)", - EBADF, msg); - PyErr_SetObject(PyExc_OSError, exc); - Py_XDECREF(exc); - return -1; - } + struct stat buf; + if (fstat(fd, &buf) < 0 && errno == EBADF) { + PyObject *exc; + char *msg = strerror(EBADF); + exc = PyObject_CallFunction(PyExc_OSError, "(is)", + EBADF, msg); + PyErr_SetObject(PyExc_OSError, exc); + Py_XDECREF(exc); + return -1; + } #endif - return 0; + return 0; } static int fileio_init(PyObject *oself, PyObject *args, PyObject *kwds) { - PyFileIOObject *self = (PyFileIOObject *) oself; - static char *kwlist[] = {"file", "mode", "closefd", NULL}; - char *name = NULL; - char *mode = "r"; - char *s; + PyFileIOObject *self = (PyFileIOObject *) oself; + static char *kwlist[] = {"file", "mode", "closefd", NULL}; + char *name = NULL; + char *mode = "r"; + char *s; #ifdef MS_WINDOWS - Py_UNICODE *widename = NULL; + Py_UNICODE *widename = NULL; #endif - int ret = 0; - int rwa = 0, plus = 0, append = 0; - int flags = 0; - int fd = -1; - int closefd = 1; - - assert(PyFileIO_Check(oself)); - if (self->fd >= 0) { - /* Have to close the existing file first. */ - if (internal_close(self) < 0) - return -1; - } - - if (PyArg_ParseTupleAndKeywords(args, kwds, "i|si:fileio", - kwlist, &fd, &mode, &closefd)) { - if (fd < 0) { - PyErr_SetString(PyExc_ValueError, - "Negative filedescriptor"); - return -1; - } - if (check_fd(fd)) - return -1; - } - else { - PyErr_Clear(); + int ret = 0; + int rwa = 0, plus = 0, append = 0; + int flags = 0; + int fd = -1; + int closefd = 1; + + assert(PyFileIO_Check(oself)); + if (self->fd >= 0) { + /* Have to close the existing file first. */ + if (internal_close(self) < 0) + return -1; + } + + if (PyArg_ParseTupleAndKeywords(args, kwds, "i|si:fileio", + kwlist, &fd, &mode, &closefd)) { + if (fd < 0) { + PyErr_SetString(PyExc_ValueError, + "Negative filedescriptor"); + return -1; + } + if (check_fd(fd)) + return -1; + } + else { + PyErr_Clear(); #ifdef Py_WIN_WIDE_FILENAMES - if (GetVersion() < 0x80000000) { - /* On NT, so wide API available */ - PyObject *po; - if (PyArg_ParseTupleAndKeywords(args, kwds, "U|si:fileio", - kwlist, &po, &mode, &closefd) - ) { - widename = PyUnicode_AS_UNICODE(po); - } else { - /* Drop the argument parsing error as narrow - strings are also valid. */ - PyErr_Clear(); - } - } - if (widename == NULL) -#endif - { - if (!PyArg_ParseTupleAndKeywords(args, kwds, "et|si:fileio", - kwlist, - Py_FileSystemDefaultEncoding, - &name, &mode, &closefd)) - return -1; - } - } - - s = mode; - while (*s) { - switch (*s++) { - case 'r': - if (rwa) { - bad_mode: - PyErr_SetString(PyExc_ValueError, - "Must have exactly one of read/write/append mode"); - goto error; - } - rwa = 1; - self->readable = 1; - break; - case 'w': - if (rwa) - goto bad_mode; - rwa = 1; - self->writable = 1; - flags |= O_CREAT | O_TRUNC; - break; - case 'a': - if (rwa) - goto bad_mode; - rwa = 1; - self->writable = 1; - flags |= O_CREAT; - append = 1; - break; - case 'b': - break; - case '+': - if (plus) - goto bad_mode; - self->readable = self->writable = 1; - plus = 1; - break; - default: - PyErr_Format(PyExc_ValueError, - "invalid mode: %.200s", mode); - goto error; - } - } - - if (!rwa) - goto bad_mode; - - if (self->readable && self->writable) - flags |= O_RDWR; - else if (self->readable) - flags |= O_RDONLY; - else - flags |= O_WRONLY; + if (GetVersion() < 0x80000000) { + /* On NT, so wide API available */ + PyObject *po; + if (PyArg_ParseTupleAndKeywords(args, kwds, "U|si:fileio", + kwlist, &po, &mode, &closefd) + ) { + widename = PyUnicode_AS_UNICODE(po); + } else { + /* Drop the argument parsing error as narrow + strings are also valid. */ + PyErr_Clear(); + } + } + if (widename == NULL) +#endif + { + if (!PyArg_ParseTupleAndKeywords(args, kwds, "et|si:fileio", + kwlist, + Py_FileSystemDefaultEncoding, + &name, &mode, &closefd)) + return -1; + } + } + + s = mode; + while (*s) { + switch (*s++) { + case 'r': + if (rwa) { + bad_mode: + PyErr_SetString(PyExc_ValueError, + "Must have exactly one of read/write/append mode"); + goto error; + } + rwa = 1; + self->readable = 1; + break; + case 'w': + if (rwa) + goto bad_mode; + rwa = 1; + self->writable = 1; + flags |= O_CREAT | O_TRUNC; + break; + case 'a': + if (rwa) + goto bad_mode; + rwa = 1; + self->writable = 1; + flags |= O_CREAT; + append = 1; + break; + case 'b': + break; + case '+': + if (plus) + goto bad_mode; + self->readable = self->writable = 1; + plus = 1; + break; + default: + PyErr_Format(PyExc_ValueError, + "invalid mode: %.200s", mode); + goto error; + } + } + + if (!rwa) + goto bad_mode; + + if (self->readable && self->writable) + flags |= O_RDWR; + else if (self->readable) + flags |= O_RDONLY; + else + flags |= O_WRONLY; #ifdef O_BINARY - flags |= O_BINARY; + flags |= O_BINARY; #endif #ifdef O_APPEND - if (append) - flags |= O_APPEND; + if (append) + flags |= O_APPEND; #endif - if (fd >= 0) { - self->fd = fd; - self->closefd = closefd; - } - else { - self->closefd = 1; - if (!closefd) { - PyErr_SetString(PyExc_ValueError, - "Cannot use closefd=False with file name"); - goto error; - } + if (fd >= 0) { + self->fd = fd; + self->closefd = closefd; + } + else { + self->closefd = 1; + if (!closefd) { + PyErr_SetString(PyExc_ValueError, + "Cannot use closefd=False with file name"); + goto error; + } - Py_BEGIN_ALLOW_THREADS - errno = 0; + Py_BEGIN_ALLOW_THREADS + errno = 0; #ifdef MS_WINDOWS - if (widename != NULL) - self->fd = _wopen(widename, flags, 0666); - else -#endif - self->fd = open(name, flags, 0666); - Py_END_ALLOW_THREADS - if (self->fd < 0) { + if (widename != NULL) + self->fd = _wopen(widename, flags, 0666); + else +#endif + self->fd = open(name, flags, 0666); + Py_END_ALLOW_THREADS + if (self->fd < 0) { #ifdef MS_WINDOWS - if (widename != NULL) - PyErr_SetFromErrnoWithUnicodeFilename(PyExc_IOError, widename); - else -#endif - PyErr_SetFromErrnoWithFilename(PyExc_IOError, name); - goto error; - } - if(dircheck(self, name) < 0) - goto error; - } - - if (append) { - /* For consistent behaviour, we explicitly seek to the - end of file (otherwise, it might be done only on the - first write()). */ - PyObject *pos = portable_lseek(self->fd, NULL, 2); - if (pos == NULL) - goto error; - Py_DECREF(pos); - } + if (widename != NULL) + PyErr_SetFromErrnoWithUnicodeFilename(PyExc_IOError, widename); + else +#endif + PyErr_SetFromErrnoWithFilename(PyExc_IOError, name); + goto error; + } + if(dircheck(self, name) < 0) + goto error; + } + + if (append) { + /* For consistent behaviour, we explicitly seek to the + end of file (otherwise, it might be done only on the + first write()). */ + PyObject *pos = portable_lseek(self->fd, NULL, 2); + if (pos == NULL) + goto error; + Py_DECREF(pos); + } - goto done; + goto done; error: - ret = -1; + ret = -1; done: - PyMem_Free(name); - return ret; + PyMem_Free(name); + return ret; } static void fileio_dealloc(PyFileIOObject *self) { - if (self->weakreflist != NULL) - PyObject_ClearWeakRefs((PyObject *) self); + if (self->weakreflist != NULL) + PyObject_ClearWeakRefs((PyObject *) self); - if (self->fd >= 0 && self->closefd) { - errno = internal_close(self); - if (errno < 0) { - PySys_WriteStderr("close failed: [Errno %d] %s\n", - errno, strerror(errno)); - } - } + if (self->fd >= 0 && self->closefd) { + errno = internal_close(self); + if (errno < 0) { + PySys_WriteStderr("close failed: [Errno %d] %s\n", + errno, strerror(errno)); + } + } - Py_TYPE(self)->tp_free((PyObject *)self); + Py_TYPE(self)->tp_free((PyObject *)self); } static PyObject * err_closed(void) { - PyErr_SetString(PyExc_ValueError, "I/O operation on closed file"); - return NULL; + PyErr_SetString(PyExc_ValueError, "I/O operation on closed file"); + return NULL; } static PyObject * err_mode(char *action) { - PyErr_Format(PyExc_ValueError, "File not open for %s", action); - return NULL; + PyErr_Format(PyExc_ValueError, "File not open for %s", action); + return NULL; } static PyObject * fileio_fileno(PyFileIOObject *self) { - if (self->fd < 0) - return err_closed(); - return PyInt_FromLong((long) self->fd); + if (self->fd < 0) + return err_closed(); + return PyInt_FromLong((long) self->fd); } static PyObject * fileio_readable(PyFileIOObject *self) { - if (self->fd < 0) - return err_closed(); - return PyBool_FromLong((long) self->readable); + if (self->fd < 0) + return err_closed(); + return PyBool_FromLong((long) self->readable); } static PyObject * fileio_writable(PyFileIOObject *self) { - if (self->fd < 0) - return err_closed(); - return PyBool_FromLong((long) self->writable); + if (self->fd < 0) + return err_closed(); + return PyBool_FromLong((long) self->writable); } static PyObject * fileio_seekable(PyFileIOObject *self) { - if (self->fd < 0) - return err_closed(); - if (self->seekable < 0) { - int ret; - Py_BEGIN_ALLOW_THREADS - ret = lseek(self->fd, 0, SEEK_CUR); - Py_END_ALLOW_THREADS - if (ret < 0) - self->seekable = 0; - else - self->seekable = 1; - } - return PyBool_FromLong((long) self->seekable); + if (self->fd < 0) + return err_closed(); + if (self->seekable < 0) { + int ret; + Py_BEGIN_ALLOW_THREADS + ret = lseek(self->fd, 0, SEEK_CUR); + Py_END_ALLOW_THREADS + if (ret < 0) + self->seekable = 0; + else + self->seekable = 1; + } + return PyBool_FromLong((long) self->seekable); } static PyObject * fileio_readinto(PyFileIOObject *self, PyObject *args) { - Py_buffer pbuf; - Py_ssize_t n; + Py_buffer pbuf; + Py_ssize_t n; - if (self->fd < 0) - return err_closed(); - if (!self->readable) - return err_mode("reading"); - - if (!PyArg_ParseTuple(args, "w*", &pbuf)) - return NULL; - - Py_BEGIN_ALLOW_THREADS - errno = 0; - n = read(self->fd, pbuf.buf, pbuf.len); - Py_END_ALLOW_THREADS - PyBuffer_Release(&pbuf); - if (n < 0) { - if (errno == EAGAIN) - Py_RETURN_NONE; - PyErr_SetFromErrno(PyExc_IOError); - return NULL; - } + if (self->fd < 0) + return err_closed(); + if (!self->readable) + return err_mode("reading"); + + if (!PyArg_ParseTuple(args, "w*", &pbuf)) + return NULL; + + Py_BEGIN_ALLOW_THREADS + errno = 0; + n = read(self->fd, pbuf.buf, pbuf.len); + Py_END_ALLOW_THREADS + PyBuffer_Release(&pbuf); + if (n < 0) { + if (errno == EAGAIN) + Py_RETURN_NONE; + PyErr_SetFromErrno(PyExc_IOError); + return NULL; + } - return PyLong_FromSsize_t(n); + return PyLong_FromSsize_t(n); } #define DEFAULT_BUFFER_SIZE (8*1024) @@ -426,134 +426,134 @@ static PyObject * fileio_readall(PyFileIOObject *self) { - PyObject *result; - Py_ssize_t total = 0; - int n; - - result = PyString_FromStringAndSize(NULL, DEFAULT_BUFFER_SIZE); - if (result == NULL) - return NULL; - - while (1) { - Py_ssize_t newsize = total + DEFAULT_BUFFER_SIZE; - if (PyString_GET_SIZE(result) < newsize) { - if (_PyString_Resize(&result, newsize) < 0) { - if (total == 0) { - Py_DECREF(result); - return NULL; - } - PyErr_Clear(); - break; - } - } - Py_BEGIN_ALLOW_THREADS - errno = 0; - n = read(self->fd, - PyString_AS_STRING(result) + total, - newsize - total); - Py_END_ALLOW_THREADS - if (n == 0) - break; - if (n < 0) { - if (total > 0) - break; - if (errno == EAGAIN) { - Py_DECREF(result); - Py_RETURN_NONE; - } - Py_DECREF(result); - PyErr_SetFromErrno(PyExc_IOError); - return NULL; - } - total += n; - } - - if (PyString_GET_SIZE(result) > total) { - if (_PyString_Resize(&result, total) < 0) { - /* This should never happen, but just in case */ - Py_DECREF(result); - return NULL; - } - } - return result; + PyObject *result; + Py_ssize_t total = 0; + int n; + + result = PyString_FromStringAndSize(NULL, DEFAULT_BUFFER_SIZE); + if (result == NULL) + return NULL; + + while (1) { + Py_ssize_t newsize = total + DEFAULT_BUFFER_SIZE; + if (PyString_GET_SIZE(result) < newsize) { + if (_PyString_Resize(&result, newsize) < 0) { + if (total == 0) { + Py_DECREF(result); + return NULL; + } + PyErr_Clear(); + break; + } + } + Py_BEGIN_ALLOW_THREADS + errno = 0; + n = read(self->fd, + PyString_AS_STRING(result) + total, + newsize - total); + Py_END_ALLOW_THREADS + if (n == 0) + break; + if (n < 0) { + if (total > 0) + break; + if (errno == EAGAIN) { + Py_DECREF(result); + Py_RETURN_NONE; + } + Py_DECREF(result); + PyErr_SetFromErrno(PyExc_IOError); + return NULL; + } + total += n; + } + + if (PyString_GET_SIZE(result) > total) { + if (_PyString_Resize(&result, total) < 0) { + /* This should never happen, but just in case */ + Py_DECREF(result); + return NULL; + } + } + return result; } static PyObject * fileio_read(PyFileIOObject *self, PyObject *args) { - char *ptr; - Py_ssize_t n; - Py_ssize_t size = -1; - PyObject *bytes; - - if (self->fd < 0) - return err_closed(); - if (!self->readable) - return err_mode("reading"); - - if (!PyArg_ParseTuple(args, "|n", &size)) - return NULL; - - if (size < 0) { - return fileio_readall(self); - } - - bytes = PyString_FromStringAndSize(NULL, size); - if (bytes == NULL) - return NULL; - ptr = PyString_AS_STRING(bytes); - - Py_BEGIN_ALLOW_THREADS - errno = 0; - n = read(self->fd, ptr, size); - Py_END_ALLOW_THREADS - - if (n < 0) { - if (errno == EAGAIN) - Py_RETURN_NONE; - PyErr_SetFromErrno(PyExc_IOError); - return NULL; - } - - if (n != size) { - if (_PyString_Resize(&bytes, n) < 0) { - Py_DECREF(bytes); - return NULL; - } - } + char *ptr; + Py_ssize_t n; + Py_ssize_t size = -1; + PyObject *bytes; + + if (self->fd < 0) + return err_closed(); + if (!self->readable) + return err_mode("reading"); + + if (!PyArg_ParseTuple(args, "|n", &size)) + return NULL; + + if (size < 0) { + return fileio_readall(self); + } + + bytes = PyString_FromStringAndSize(NULL, size); + if (bytes == NULL) + return NULL; + ptr = PyString_AS_STRING(bytes); + + Py_BEGIN_ALLOW_THREADS + errno = 0; + n = read(self->fd, ptr, size); + Py_END_ALLOW_THREADS + + if (n < 0) { + if (errno == EAGAIN) + Py_RETURN_NONE; + PyErr_SetFromErrno(PyExc_IOError); + return NULL; + } + + if (n != size) { + if (_PyString_Resize(&bytes, n) < 0) { + Py_DECREF(bytes); + return NULL; + } + } - return (PyObject *) bytes; + return (PyObject *) bytes; } static PyObject * fileio_write(PyFileIOObject *self, PyObject *args) { - Py_buffer pbuf; - Py_ssize_t n; + Py_buffer pbuf; + Py_ssize_t n; - if (self->fd < 0) - return err_closed(); - if (!self->writable) - return err_mode("writing"); - - if (!PyArg_ParseTuple(args, "s*", &pbuf)) - return NULL; - - Py_BEGIN_ALLOW_THREADS - errno = 0; - n = write(self->fd, pbuf.buf, pbuf.len); - Py_END_ALLOW_THREADS - - PyBuffer_Release(&pbuf); - - if (n < 0) { - if (errno == EAGAIN) - Py_RETURN_NONE; - PyErr_SetFromErrno(PyExc_IOError); - return NULL; - } + if (self->fd < 0) + return err_closed(); + if (!self->writable) + return err_mode("writing"); + + if (!PyArg_ParseTuple(args, "s*", &pbuf)) + return NULL; + + Py_BEGIN_ALLOW_THREADS + errno = 0; + n = write(self->fd, pbuf.buf, pbuf.len); + Py_END_ALLOW_THREADS + + PyBuffer_Release(&pbuf); + + if (n < 0) { + if (errno == EAGAIN) + Py_RETURN_NONE; + PyErr_SetFromErrno(PyExc_IOError); + return NULL; + } - return PyLong_FromSsize_t(n); + return PyLong_FromSsize_t(n); } /* XXX Windows support below is likely incomplete */ @@ -568,217 +568,217 @@ static PyObject * portable_lseek(int fd, PyObject *posobj, int whence) { - Py_off_t pos, res; + Py_off_t pos, res; #ifdef SEEK_SET - /* Turn 0, 1, 2 into SEEK_{SET,CUR,END} */ - switch (whence) { + /* Turn 0, 1, 2 into SEEK_{SET,CUR,END} */ + switch (whence) { #if SEEK_SET != 0 - case 0: whence = SEEK_SET; break; + case 0: whence = SEEK_SET; break; #endif #if SEEK_CUR != 1 - case 1: whence = SEEK_CUR; break; + case 1: whence = SEEK_CUR; break; #endif #if SEEL_END != 2 - case 2: whence = SEEK_END; break; + case 2: whence = SEEK_END; break; #endif - } + } #endif /* SEEK_SET */ - if (posobj == NULL) - pos = 0; - else { - if(PyFloat_Check(posobj)) { - PyErr_SetString(PyExc_TypeError, "an integer is required"); - return NULL; - } + if (posobj == NULL) + pos = 0; + else { + if(PyFloat_Check(posobj)) { + PyErr_SetString(PyExc_TypeError, "an integer is required"); + return NULL; + } #if defined(HAVE_LARGEFILE_SUPPORT) - pos = PyLong_AsLongLong(posobj); + pos = PyLong_AsLongLong(posobj); #else - pos = PyLong_AsLong(posobj); + pos = PyLong_AsLong(posobj); #endif - if (PyErr_Occurred()) - return NULL; - } + if (PyErr_Occurred()) + return NULL; + } - Py_BEGIN_ALLOW_THREADS + Py_BEGIN_ALLOW_THREADS #if defined(MS_WIN64) || defined(MS_WINDOWS) - res = _lseeki64(fd, pos, whence); + res = _lseeki64(fd, pos, whence); #else - res = lseek(fd, pos, whence); + res = lseek(fd, pos, whence); #endif - Py_END_ALLOW_THREADS - if (res < 0) - return PyErr_SetFromErrno(PyExc_IOError); + Py_END_ALLOW_THREADS + if (res < 0) + return PyErr_SetFromErrno(PyExc_IOError); #if defined(HAVE_LARGEFILE_SUPPORT) - return PyLong_FromLongLong(res); + return PyLong_FromLongLong(res); #else - return PyLong_FromLong(res); + return PyLong_FromLong(res); #endif } static PyObject * fileio_seek(PyFileIOObject *self, PyObject *args) { - PyObject *posobj; - int whence = 0; + PyObject *posobj; + int whence = 0; - if (self->fd < 0) - return err_closed(); + if (self->fd < 0) + return err_closed(); - if (!PyArg_ParseTuple(args, "O|i", &posobj, &whence)) - return NULL; + if (!PyArg_ParseTuple(args, "O|i", &posobj, &whence)) + return NULL; - return portable_lseek(self->fd, posobj, whence); + return portable_lseek(self->fd, posobj, whence); } static PyObject * fileio_tell(PyFileIOObject *self, PyObject *args) { - if (self->fd < 0) - return err_closed(); + if (self->fd < 0) + return err_closed(); - return portable_lseek(self->fd, NULL, 1); + return portable_lseek(self->fd, NULL, 1); } #ifdef HAVE_FTRUNCATE static PyObject * fileio_truncate(PyFileIOObject *self, PyObject *args) { - PyObject *posobj = NULL; /* the new size wanted by the user */ + PyObject *posobj = NULL; /* the new size wanted by the user */ #ifndef MS_WINDOWS - Py_off_t pos; + Py_off_t pos; #endif - int ret; - int fd; + int ret; + int fd; - fd = self->fd; - if (fd < 0) - return err_closed(); - if (!self->writable) - return err_mode("writing"); - - if (!PyArg_ParseTuple(args, "|O", &posobj)) - return NULL; - - if (posobj == Py_None || posobj == NULL) { - /* Get the current position. */ - posobj = portable_lseek(fd, NULL, 1); - if (posobj == NULL) - return NULL; - } - else { - Py_INCREF(posobj); - } + fd = self->fd; + if (fd < 0) + return err_closed(); + if (!self->writable) + return err_mode("writing"); + + if (!PyArg_ParseTuple(args, "|O", &posobj)) + return NULL; + + if (posobj == Py_None || posobj == NULL) { + /* Get the current position. */ + posobj = portable_lseek(fd, NULL, 1); + if (posobj == NULL) + return NULL; + } + else { + Py_INCREF(posobj); + } #ifdef MS_WINDOWS - /* MS _chsize doesn't work if newsize doesn't fit in 32 bits, - so don't even try using it. */ - { - PyObject *oldposobj, *tempposobj; - HANDLE hFile; - - /* we save the file pointer position */ - oldposobj = portable_lseek(fd, NULL, 1); - if (oldposobj == NULL) { - Py_DECREF(posobj); - return NULL; - } - - /* we then move to the truncation position */ - tempposobj = portable_lseek(fd, posobj, 0); - if (tempposobj == NULL) { - Py_DECREF(oldposobj); - Py_DECREF(posobj); - return NULL; - } - Py_DECREF(tempposobj); - - /* Truncate. Note that this may grow the file! */ - Py_BEGIN_ALLOW_THREADS - errno = 0; - hFile = (HANDLE)_get_osfhandle(fd); - ret = hFile == (HANDLE)-1; /* testing for INVALID_HANDLE value */ - if (ret == 0) { - ret = SetEndOfFile(hFile) == 0; - if (ret) - errno = EACCES; - } - Py_END_ALLOW_THREADS - - /* we restore the file pointer position in any case */ - tempposobj = portable_lseek(fd, oldposobj, 0); - Py_DECREF(oldposobj); - if (tempposobj == NULL) { - Py_DECREF(posobj); - return NULL; - } - Py_DECREF(tempposobj); - } + /* MS _chsize doesn't work if newsize doesn't fit in 32 bits, + so don't even try using it. */ + { + PyObject *oldposobj, *tempposobj; + HANDLE hFile; + + /* we save the file pointer position */ + oldposobj = portable_lseek(fd, NULL, 1); + if (oldposobj == NULL) { + Py_DECREF(posobj); + return NULL; + } + + /* we then move to the truncation position */ + tempposobj = portable_lseek(fd, posobj, 0); + if (tempposobj == NULL) { + Py_DECREF(oldposobj); + Py_DECREF(posobj); + return NULL; + } + Py_DECREF(tempposobj); + + /* Truncate. Note that this may grow the file! */ + Py_BEGIN_ALLOW_THREADS + errno = 0; + hFile = (HANDLE)_get_osfhandle(fd); + ret = hFile == (HANDLE)-1; /* testing for INVALID_HANDLE value */ + if (ret == 0) { + ret = SetEndOfFile(hFile) == 0; + if (ret) + errno = EACCES; + } + Py_END_ALLOW_THREADS + + /* we restore the file pointer position in any case */ + tempposobj = portable_lseek(fd, oldposobj, 0); + Py_DECREF(oldposobj); + if (tempposobj == NULL) { + Py_DECREF(posobj); + return NULL; + } + Py_DECREF(tempposobj); + } #else #if defined(HAVE_LARGEFILE_SUPPORT) - pos = PyLong_AsLongLong(posobj); + pos = PyLong_AsLongLong(posobj); #else - pos = PyLong_AsLong(posobj); + pos = PyLong_AsLong(posobj); #endif - if (PyErr_Occurred()){ - Py_DECREF(posobj); - return NULL; - } - - Py_BEGIN_ALLOW_THREADS - errno = 0; - ret = ftruncate(fd, pos); - Py_END_ALLOW_THREADS + if (PyErr_Occurred()){ + Py_DECREF(posobj); + return NULL; + } + + Py_BEGIN_ALLOW_THREADS + errno = 0; + ret = ftruncate(fd, pos); + Py_END_ALLOW_THREADS #endif /* !MS_WINDOWS */ - if (ret != 0) { - Py_DECREF(posobj); - PyErr_SetFromErrno(PyExc_IOError); - return NULL; - } + if (ret != 0) { + Py_DECREF(posobj); + PyErr_SetFromErrno(PyExc_IOError); + return NULL; + } - return posobj; + return posobj; } #endif /* HAVE_FTRUNCATE */ static char * mode_string(PyFileIOObject *self) { - if (self->readable) { - if (self->writable) - return "rb+"; - else - return "rb"; - } - else - return "wb"; + if (self->readable) { + if (self->writable) + return "rb+"; + else + return "rb"; + } + else + return "wb"; } static PyObject * fileio_repr(PyFileIOObject *self) { - if (self->fd < 0) - return PyString_FromFormat("_fileio._FileIO(-1)"); + if (self->fd < 0) + return PyString_FromFormat("_fileio._FileIO(-1)"); - return PyString_FromFormat("_fileio._FileIO(%d, '%s')", - self->fd, mode_string(self)); + return PyString_FromFormat("_fileio._FileIO(%d, '%s')", + self->fd, mode_string(self)); } static PyObject * fileio_isatty(PyFileIOObject *self) { - long res; + long res; - if (self->fd < 0) - return err_closed(); - Py_BEGIN_ALLOW_THREADS - res = isatty(self->fd); - Py_END_ALLOW_THREADS - return PyBool_FromLong(res); + if (self->fd < 0) + return err_closed(); + Py_BEGIN_ALLOW_THREADS + res = isatty(self->fd); + Py_END_ALLOW_THREADS + return PyBool_FromLong(res); } @@ -786,7 +786,7 @@ "file(name: str[, mode: str]) -> file IO object\n" "\n" "Open a file. The mode can be 'r', 'w' or 'a' for reading (default),\n" -"writing or appending. The file will be created if it doesn't exist\n" +"writing or appending. The file will be created if it doesn't exist\n" "when opened for writing or appending; it will be truncated when\n" "opened for writing. Add a '+' to the mode to allow simultaneous\n" "reading and writing."); @@ -828,14 +828,14 @@ #ifdef HAVE_FTRUNCATE PyDoc_STRVAR(truncate_doc, -"truncate([size: int]) -> None. Truncate the file to at most size bytes.\n" +"truncate([size: int]) -> None. Truncate the file to at most size bytes.\n" "\n" "Size defaults to the current file position, as returned by tell()." "The current file position is changed to the value of size."); #endif PyDoc_STRVAR(tell_doc, -"tell() -> int. Current file position"); +"tell() -> int. Current file position"); PyDoc_STRVAR(readinto_doc, "readinto() -> Undocumented. Don't use this; it may go away."); @@ -859,22 +859,22 @@ "writable() -> bool. True if file was opened in a write mode."); static PyMethodDef fileio_methods[] = { - {"read", (PyCFunction)fileio_read, METH_VARARGS, read_doc}, - {"readall", (PyCFunction)fileio_readall, METH_NOARGS, readall_doc}, - {"readinto", (PyCFunction)fileio_readinto, METH_VARARGS, readinto_doc}, - {"write", (PyCFunction)fileio_write, METH_VARARGS, write_doc}, - {"seek", (PyCFunction)fileio_seek, METH_VARARGS, seek_doc}, - {"tell", (PyCFunction)fileio_tell, METH_VARARGS, tell_doc}, + {"read", (PyCFunction)fileio_read, METH_VARARGS, read_doc}, + {"readall", (PyCFunction)fileio_readall, METH_NOARGS, readall_doc}, + {"readinto", (PyCFunction)fileio_readinto, METH_VARARGS, readinto_doc}, + {"write", (PyCFunction)fileio_write, METH_VARARGS, write_doc}, + {"seek", (PyCFunction)fileio_seek, METH_VARARGS, seek_doc}, + {"tell", (PyCFunction)fileio_tell, METH_VARARGS, tell_doc}, #ifdef HAVE_FTRUNCATE - {"truncate", (PyCFunction)fileio_truncate, METH_VARARGS, truncate_doc}, + {"truncate", (PyCFunction)fileio_truncate, METH_VARARGS, truncate_doc}, #endif - {"close", (PyCFunction)fileio_close, METH_NOARGS, close_doc}, - {"seekable", (PyCFunction)fileio_seekable, METH_NOARGS, seekable_doc}, - {"readable", (PyCFunction)fileio_readable, METH_NOARGS, readable_doc}, - {"writable", (PyCFunction)fileio_writable, METH_NOARGS, writable_doc}, - {"fileno", (PyCFunction)fileio_fileno, METH_NOARGS, fileno_doc}, - {"isatty", (PyCFunction)fileio_isatty, METH_NOARGS, isatty_doc}, - {NULL, NULL} /* sentinel */ + {"close", (PyCFunction)fileio_close, METH_NOARGS, close_doc}, + {"seekable", (PyCFunction)fileio_seekable, METH_NOARGS, seekable_doc}, + {"readable", (PyCFunction)fileio_readable, METH_NOARGS, readable_doc}, + {"writable", (PyCFunction)fileio_writable, METH_NOARGS, writable_doc}, + {"fileno", (PyCFunction)fileio_fileno, METH_NOARGS, fileno_doc}, + {"isatty", (PyCFunction)fileio_isatty, METH_NOARGS, isatty_doc}, + {NULL, NULL} /* sentinel */ }; /* 'closed' and 'mode' are attributes for backwards compatibility reasons. */ @@ -882,86 +882,86 @@ static PyObject * get_closed(PyFileIOObject *self, void *closure) { - return PyBool_FromLong((long)(self->fd < 0)); + return PyBool_FromLong((long)(self->fd < 0)); } static PyObject * get_closefd(PyFileIOObject *self, void *closure) { - return PyBool_FromLong((long)(self->closefd)); + return PyBool_FromLong((long)(self->closefd)); } static PyObject * get_mode(PyFileIOObject *self, void *closure) { - return PyString_FromString(mode_string(self)); + return PyString_FromString(mode_string(self)); } static PyGetSetDef fileio_getsetlist[] = { - {"closed", (getter)get_closed, NULL, "True if the file is closed"}, - {"closefd", (getter)get_closefd, NULL, - "True if the file descriptor will be closed"}, - {"mode", (getter)get_mode, NULL, "String giving the file mode"}, - {0}, + {"closed", (getter)get_closed, NULL, "True if the file is closed"}, + {"closefd", (getter)get_closefd, NULL, + "True if the file descriptor will be closed"}, + {"mode", (getter)get_mode, NULL, "String giving the file mode"}, + {0}, }; PyTypeObject PyFileIO_Type = { - PyVarObject_HEAD_INIT(NULL, 0) - "_FileIO", - sizeof(PyFileIOObject), - 0, - (destructor)fileio_dealloc, /* tp_dealloc */ - 0, /* tp_print */ - 0, /* tp_getattr */ - 0, /* tp_setattr */ - 0, /* tp_compare */ - (reprfunc)fileio_repr, /* 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_BASETYPE, /* tp_flags */ - fileio_doc, /* tp_doc */ - 0, /* tp_traverse */ - 0, /* tp_clear */ - 0, /* tp_richcompare */ - offsetof(PyFileIOObject, weakreflist), /* tp_weaklistoffset */ - 0, /* tp_iter */ - 0, /* tp_iternext */ - fileio_methods, /* tp_methods */ - 0, /* tp_members */ - fileio_getsetlist, /* tp_getset */ - 0, /* tp_base */ - 0, /* tp_dict */ - 0, /* tp_descr_get */ - 0, /* tp_descr_set */ - 0, /* tp_dictoffset */ - fileio_init, /* tp_init */ - PyType_GenericAlloc, /* tp_alloc */ - fileio_new, /* tp_new */ - PyObject_Del, /* tp_free */ + PyVarObject_HEAD_INIT(NULL, 0) + "_FileIO", + sizeof(PyFileIOObject), + 0, + (destructor)fileio_dealloc, /* tp_dealloc */ + 0, /* tp_print */ + 0, /* tp_getattr */ + 0, /* tp_setattr */ + 0, /* tp_compare */ + (reprfunc)fileio_repr, /* 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_BASETYPE, /* tp_flags */ + fileio_doc, /* tp_doc */ + 0, /* tp_traverse */ + 0, /* tp_clear */ + 0, /* tp_richcompare */ + offsetof(PyFileIOObject, weakreflist), /* tp_weaklistoffset */ + 0, /* tp_iter */ + 0, /* tp_iternext */ + fileio_methods, /* tp_methods */ + 0, /* tp_members */ + fileio_getsetlist, /* tp_getset */ + 0, /* tp_base */ + 0, /* tp_dict */ + 0, /* tp_descr_get */ + 0, /* tp_descr_set */ + 0, /* tp_dictoffset */ + fileio_init, /* tp_init */ + PyType_GenericAlloc, /* tp_alloc */ + fileio_new, /* tp_new */ + PyObject_Del, /* tp_free */ }; static PyMethodDef module_methods[] = { - {NULL, NULL} + {NULL, NULL} }; PyMODINIT_FUNC init_fileio(void) { - PyObject *m; /* a module object */ + PyObject *m; /* a module object */ - m = Py_InitModule3("_fileio", module_methods, - "Fast implementation of io.FileIO."); - if (m == NULL) - return; - if (PyType_Ready(&PyFileIO_Type) < 0) - return; - Py_INCREF(&PyFileIO_Type); - PyModule_AddObject(m, "_FileIO", (PyObject *) &PyFileIO_Type); + m = Py_InitModule3("_fileio", module_methods, + "Fast implementation of io.FileIO."); + if (m == NULL) + return; + if (PyType_Ready(&PyFileIO_Type) < 0) + return; + Py_INCREF(&PyFileIO_Type); + PyModule_AddObject(m, "_FileIO", (PyObject *) &PyFileIO_Type); } From python-checkins at python.org Wed May 5 18:31:07 2010 From: python-checkins at python.org (antoine.pitrou) Date: Wed, 5 May 2010 18:31:07 +0200 (CEST) Subject: [Python-checkins] r80798 - in python/branches/py3k: Modules/_io/fileio.c Message-ID: <20100505163107.9EA75EE9A3@mail.python.org> Author: antoine.pitrou Date: Wed May 5 18:31:07 2010 New Revision: 80798 Log: Merged revisions 80796 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r80796 | antoine.pitrou | 2010-05-05 18:27:30 +0200 (mer., 05 mai 2010) | 3 lines Untabify Modules/_io/fileio.c ........ Modified: python/branches/py3k/ (props changed) python/branches/py3k/Modules/_io/fileio.c Modified: python/branches/py3k/Modules/_io/fileio.c ============================================================================== --- python/branches/py3k/Modules/_io/fileio.c (original) +++ python/branches/py3k/Modules/_io/fileio.c Wed May 5 18:31:07 2010 @@ -49,14 +49,14 @@ #endif typedef struct { - PyObject_HEAD - int fd; - unsigned int readable : 1; - unsigned int writable : 1; - signed int seekable : 2; /* -1 means unknown */ - unsigned int closefd : 1; - PyObject *weakreflist; - PyObject *dict; + PyObject_HEAD + int fd; + unsigned int readable : 1; + unsigned int writable : 1; + signed int seekable : 2; /* -1 means unknown */ + unsigned int closefd : 1; + PyObject *weakreflist; + PyObject *dict; } fileio; PyTypeObject PyFileIO_Type; @@ -66,7 +66,7 @@ int _PyFileIO_closed(PyObject *self) { - return ((fileio *)self)->fd < 0; + return ((fileio *)self)->fd < 0; } static PyObject * @@ -78,64 +78,64 @@ static int internal_close(fileio *self) { - int err = 0; - int save_errno = 0; - if (self->fd >= 0) { - int fd = self->fd; - self->fd = -1; - /* fd is accessible and someone else may have closed it */ - if (_PyVerify_fd(fd)) { - Py_BEGIN_ALLOW_THREADS - err = close(fd); - if (err < 0) - save_errno = errno; - Py_END_ALLOW_THREADS - } else { - save_errno = errno; - err = -1; - } - } - if (err < 0) { - errno = save_errno; - PyErr_SetFromErrno(PyExc_IOError); - return -1; - } - return 0; + int err = 0; + int save_errno = 0; + if (self->fd >= 0) { + int fd = self->fd; + self->fd = -1; + /* fd is accessible and someone else may have closed it */ + if (_PyVerify_fd(fd)) { + Py_BEGIN_ALLOW_THREADS + err = close(fd); + if (err < 0) + save_errno = errno; + Py_END_ALLOW_THREADS + } else { + save_errno = errno; + err = -1; + } + } + if (err < 0) { + errno = save_errno; + PyErr_SetFromErrno(PyExc_IOError); + return -1; + } + return 0; } static PyObject * fileio_close(fileio *self) { - if (!self->closefd) { - self->fd = -1; - Py_RETURN_NONE; - } - errno = internal_close(self); - if (errno < 0) - return NULL; + if (!self->closefd) { + self->fd = -1; + Py_RETURN_NONE; + } + errno = internal_close(self); + if (errno < 0) + return NULL; - return PyObject_CallMethod((PyObject*)&PyRawIOBase_Type, - "close", "O", self); + return PyObject_CallMethod((PyObject*)&PyRawIOBase_Type, + "close", "O", self); } static PyObject * fileio_new(PyTypeObject *type, PyObject *args, PyObject *kwds) { - fileio *self; + fileio *self; - assert(type != NULL && type->tp_alloc != NULL); + assert(type != NULL && type->tp_alloc != NULL); - self = (fileio *) type->tp_alloc(type, 0); - if (self != NULL) { - self->fd = -1; - self->readable = 0; - self->writable = 0; - self->seekable = -1; - self->closefd = 1; - self->weakreflist = NULL; - } + self = (fileio *) type->tp_alloc(type, 0); + if (self != NULL) { + self->fd = -1; + self->readable = 0; + self->writable = 0; + self->seekable = -1; + self->closefd = 1; + self->weakreflist = NULL; + } - return (PyObject *) self; + return (PyObject *) self; } /* On Unix, open will succeed for directories. @@ -146,535 +146,535 @@ dircheck(fileio* self, const char *name) { #if defined(HAVE_FSTAT) && defined(S_IFDIR) && defined(EISDIR) - struct stat buf; - if (self->fd < 0) - return 0; - if (fstat(self->fd, &buf) == 0 && S_ISDIR(buf.st_mode)) { - char *msg = strerror(EISDIR); - PyObject *exc; - if (internal_close(self)) - return -1; - - exc = PyObject_CallFunction(PyExc_IOError, "(iss)", - EISDIR, msg, name); - PyErr_SetObject(PyExc_IOError, exc); - Py_XDECREF(exc); - return -1; - } + struct stat buf; + if (self->fd < 0) + return 0; + if (fstat(self->fd, &buf) == 0 && S_ISDIR(buf.st_mode)) { + char *msg = strerror(EISDIR); + PyObject *exc; + if (internal_close(self)) + return -1; + + exc = PyObject_CallFunction(PyExc_IOError, "(iss)", + EISDIR, msg, name); + PyErr_SetObject(PyExc_IOError, exc); + Py_XDECREF(exc); + return -1; + } #endif - return 0; + return 0; } static int check_fd(int fd) { #if defined(HAVE_FSTAT) - struct stat buf; - if (!_PyVerify_fd(fd) || (fstat(fd, &buf) < 0 && errno == EBADF)) { - PyObject *exc; - char *msg = strerror(EBADF); - exc = PyObject_CallFunction(PyExc_OSError, "(is)", - EBADF, msg); - PyErr_SetObject(PyExc_OSError, exc); - Py_XDECREF(exc); - return -1; - } + struct stat buf; + if (!_PyVerify_fd(fd) || (fstat(fd, &buf) < 0 && errno == EBADF)) { + PyObject *exc; + char *msg = strerror(EBADF); + exc = PyObject_CallFunction(PyExc_OSError, "(is)", + EBADF, msg); + PyErr_SetObject(PyExc_OSError, exc); + Py_XDECREF(exc); + return -1; + } #endif - return 0; + return 0; } static int fileio_init(PyObject *oself, PyObject *args, PyObject *kwds) { - fileio *self = (fileio *) oself; - static char *kwlist[] = {"file", "mode", "closefd", NULL}; - const char *name = NULL; - PyObject *nameobj, *stringobj = NULL; - char *mode = "r"; - char *s; + fileio *self = (fileio *) oself; + static char *kwlist[] = {"file", "mode", "closefd", NULL}; + const char *name = NULL; + PyObject *nameobj, *stringobj = NULL; + char *mode = "r"; + char *s; #ifdef MS_WINDOWS - Py_UNICODE *widename = NULL; + Py_UNICODE *widename = NULL; #endif - int ret = 0; - int rwa = 0, plus = 0, append = 0; - int flags = 0; - int fd = -1; - int closefd = 1; - - assert(PyFileIO_Check(oself)); - if (self->fd >= 0) { - /* Have to close the existing file first. */ - if (internal_close(self) < 0) - return -1; - } - - if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|si:fileio", - kwlist, &nameobj, &mode, &closefd)) - return -1; - - if (PyFloat_Check(nameobj)) { - PyErr_SetString(PyExc_TypeError, - "integer argument expected, got float"); - return -1; - } - - fd = PyLong_AsLong(nameobj); - if (fd < 0) { - if (!PyErr_Occurred()) { - PyErr_SetString(PyExc_ValueError, - "Negative filedescriptor"); - return -1; - } - PyErr_Clear(); - } + int ret = 0; + int rwa = 0, plus = 0, append = 0; + int flags = 0; + int fd = -1; + int closefd = 1; + + assert(PyFileIO_Check(oself)); + if (self->fd >= 0) { + /* Have to close the existing file first. */ + if (internal_close(self) < 0) + return -1; + } + + if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|si:fileio", + kwlist, &nameobj, &mode, &closefd)) + return -1; + + if (PyFloat_Check(nameobj)) { + PyErr_SetString(PyExc_TypeError, + "integer argument expected, got float"); + return -1; + } + + fd = PyLong_AsLong(nameobj); + if (fd < 0) { + if (!PyErr_Occurred()) { + PyErr_SetString(PyExc_ValueError, + "Negative filedescriptor"); + return -1; + } + PyErr_Clear(); + } #ifdef MS_WINDOWS - if (PyUnicode_Check(nameobj)) - widename = PyUnicode_AS_UNICODE(nameobj); - if (widename == NULL) + if (PyUnicode_Check(nameobj)) + widename = PyUnicode_AS_UNICODE(nameobj); + if (widename == NULL) #endif - if (fd < 0) - { - if (PyBytes_Check(nameobj) || PyByteArray_Check(nameobj)) { - Py_ssize_t namelen; - if (PyObject_AsCharBuffer(nameobj, &name, &namelen) < 0) - return -1; - } - else { - PyObject *u = PyUnicode_FromObject(nameobj); - - if (u == NULL) - return -1; - - stringobj = PyUnicode_AsEncodedString( - u, Py_FileSystemDefaultEncoding, "surrogateescape"); - Py_DECREF(u); - if (stringobj == NULL) - return -1; - if (!PyBytes_Check(stringobj)) { - PyErr_SetString(PyExc_TypeError, - "encoder failed to return bytes"); - goto error; - } - name = PyBytes_AS_STRING(stringobj); - } - } - - s = mode; - while (*s) { - switch (*s++) { - case 'r': - if (rwa) { - bad_mode: - PyErr_SetString(PyExc_ValueError, - "Must have exactly one of read/write/append mode"); - goto error; - } - rwa = 1; - self->readable = 1; - break; - case 'w': - if (rwa) - goto bad_mode; - rwa = 1; - self->writable = 1; - flags |= O_CREAT | O_TRUNC; - break; - case 'a': - if (rwa) - goto bad_mode; - rwa = 1; - self->writable = 1; - flags |= O_CREAT; - append = 1; - break; - case 'b': - break; - case '+': - if (plus) - goto bad_mode; - self->readable = self->writable = 1; - plus = 1; - break; - default: - PyErr_Format(PyExc_ValueError, - "invalid mode: %.200s", mode); - goto error; - } - } - - if (!rwa) - goto bad_mode; - - if (self->readable && self->writable) - flags |= O_RDWR; - else if (self->readable) - flags |= O_RDONLY; - else - flags |= O_WRONLY; + if (fd < 0) + { + if (PyBytes_Check(nameobj) || PyByteArray_Check(nameobj)) { + Py_ssize_t namelen; + if (PyObject_AsCharBuffer(nameobj, &name, &namelen) < 0) + return -1; + } + else { + PyObject *u = PyUnicode_FromObject(nameobj); + + if (u == NULL) + return -1; + + stringobj = PyUnicode_AsEncodedString( + u, Py_FileSystemDefaultEncoding, "surrogateescape"); + Py_DECREF(u); + if (stringobj == NULL) + return -1; + if (!PyBytes_Check(stringobj)) { + PyErr_SetString(PyExc_TypeError, + "encoder failed to return bytes"); + goto error; + } + name = PyBytes_AS_STRING(stringobj); + } + } + + s = mode; + while (*s) { + switch (*s++) { + case 'r': + if (rwa) { + bad_mode: + PyErr_SetString(PyExc_ValueError, + "Must have exactly one of read/write/append mode"); + goto error; + } + rwa = 1; + self->readable = 1; + break; + case 'w': + if (rwa) + goto bad_mode; + rwa = 1; + self->writable = 1; + flags |= O_CREAT | O_TRUNC; + break; + case 'a': + if (rwa) + goto bad_mode; + rwa = 1; + self->writable = 1; + flags |= O_CREAT; + append = 1; + break; + case 'b': + break; + case '+': + if (plus) + goto bad_mode; + self->readable = self->writable = 1; + plus = 1; + break; + default: + PyErr_Format(PyExc_ValueError, + "invalid mode: %.200s", mode); + goto error; + } + } + + if (!rwa) + goto bad_mode; + + if (self->readable && self->writable) + flags |= O_RDWR; + else if (self->readable) + flags |= O_RDONLY; + else + flags |= O_WRONLY; #ifdef O_BINARY - flags |= O_BINARY; + flags |= O_BINARY; #endif #ifdef O_APPEND - if (append) - flags |= O_APPEND; + if (append) + flags |= O_APPEND; #endif - if (fd >= 0) { - if (check_fd(fd)) - goto error; - self->fd = fd; - self->closefd = closefd; - } - else { - self->closefd = 1; - if (!closefd) { - PyErr_SetString(PyExc_ValueError, - "Cannot use closefd=False with file name"); - goto error; - } + if (fd >= 0) { + if (check_fd(fd)) + goto error; + self->fd = fd; + self->closefd = closefd; + } + else { + self->closefd = 1; + if (!closefd) { + PyErr_SetString(PyExc_ValueError, + "Cannot use closefd=False with file name"); + goto error; + } - Py_BEGIN_ALLOW_THREADS - errno = 0; + Py_BEGIN_ALLOW_THREADS + errno = 0; #ifdef MS_WINDOWS - if (widename != NULL) - self->fd = _wopen(widename, flags, 0666); - else + if (widename != NULL) + self->fd = _wopen(widename, flags, 0666); + else #endif - self->fd = open(name, flags, 0666); - Py_END_ALLOW_THREADS - if (self->fd < 0) { + self->fd = open(name, flags, 0666); + Py_END_ALLOW_THREADS + if (self->fd < 0) { #ifdef MS_WINDOWS - if (widename != NULL) - PyErr_SetFromErrnoWithUnicodeFilename(PyExc_IOError, widename); - else + if (widename != NULL) + PyErr_SetFromErrnoWithUnicodeFilename(PyExc_IOError, widename); + else #endif - PyErr_SetFromErrnoWithFilename(PyExc_IOError, name); - goto error; - } - if(dircheck(self, name) < 0) - goto error; - } - - if (PyObject_SetAttrString((PyObject *)self, "name", nameobj) < 0) - goto error; - - if (append) { - /* For consistent behaviour, we explicitly seek to the - end of file (otherwise, it might be done only on the - first write()). */ - PyObject *pos = portable_lseek(self->fd, NULL, 2); - if (pos == NULL) - goto error; - Py_DECREF(pos); - } + PyErr_SetFromErrnoWithFilename(PyExc_IOError, name); + goto error; + } + if(dircheck(self, name) < 0) + goto error; + } + + if (PyObject_SetAttrString((PyObject *)self, "name", nameobj) < 0) + goto error; + + if (append) { + /* For consistent behaviour, we explicitly seek to the + end of file (otherwise, it might be done only on the + first write()). */ + PyObject *pos = portable_lseek(self->fd, NULL, 2); + if (pos == NULL) + goto error; + Py_DECREF(pos); + } - goto done; + goto done; error: - ret = -1; + ret = -1; done: - Py_CLEAR(stringobj); - return ret; + Py_CLEAR(stringobj); + return ret; } static int fileio_traverse(fileio *self, visitproc visit, void *arg) { - Py_VISIT(self->dict); - return 0; + Py_VISIT(self->dict); + return 0; } static int fileio_clear(fileio *self) { - Py_CLEAR(self->dict); - return 0; + Py_CLEAR(self->dict); + return 0; } static void fileio_dealloc(fileio *self) { - if (_PyIOBase_finalize((PyObject *) self) < 0) - return; - _PyObject_GC_UNTRACK(self); - if (self->weakreflist != NULL) - PyObject_ClearWeakRefs((PyObject *) self); - Py_CLEAR(self->dict); - Py_TYPE(self)->tp_free((PyObject *)self); + if (_PyIOBase_finalize((PyObject *) self) < 0) + return; + _PyObject_GC_UNTRACK(self); + if (self->weakreflist != NULL) + PyObject_ClearWeakRefs((PyObject *) self); + Py_CLEAR(self->dict); + Py_TYPE(self)->tp_free((PyObject *)self); } static PyObject * err_closed(void) { - PyErr_SetString(PyExc_ValueError, "I/O operation on closed file"); - return NULL; + PyErr_SetString(PyExc_ValueError, "I/O operation on closed file"); + return NULL; } static PyObject * err_mode(char *action) { - PyErr_Format(PyExc_ValueError, "File not open for %s", action); - return NULL; + PyErr_Format(PyExc_ValueError, "File not open for %s", action); + return NULL; } static PyObject * fileio_fileno(fileio *self) { - if (self->fd < 0) - return err_closed(); - return PyLong_FromLong((long) self->fd); + if (self->fd < 0) + return err_closed(); + return PyLong_FromLong((long) self->fd); } static PyObject * fileio_readable(fileio *self) { - if (self->fd < 0) - return err_closed(); - return PyBool_FromLong((long) self->readable); + if (self->fd < 0) + return err_closed(); + return PyBool_FromLong((long) self->readable); } static PyObject * fileio_writable(fileio *self) { - if (self->fd < 0) - return err_closed(); - return PyBool_FromLong((long) self->writable); + if (self->fd < 0) + return err_closed(); + return PyBool_FromLong((long) self->writable); } static PyObject * fileio_seekable(fileio *self) { - if (self->fd < 0) - return err_closed(); - if (self->seekable < 0) { - PyObject *pos = portable_lseek(self->fd, NULL, SEEK_CUR); - if (pos == NULL) { - PyErr_Clear(); - self->seekable = 0; - } else { - Py_DECREF(pos); - self->seekable = 1; - } - } - return PyBool_FromLong((long) self->seekable); + if (self->fd < 0) + return err_closed(); + if (self->seekable < 0) { + PyObject *pos = portable_lseek(self->fd, NULL, SEEK_CUR); + if (pos == NULL) { + PyErr_Clear(); + self->seekable = 0; + } else { + Py_DECREF(pos); + self->seekable = 1; + } + } + return PyBool_FromLong((long) self->seekable); } static PyObject * fileio_readinto(fileio *self, PyObject *args) { - Py_buffer pbuf; - Py_ssize_t n; + Py_buffer pbuf; + Py_ssize_t n; - if (self->fd < 0) - return err_closed(); - if (!self->readable) - return err_mode("reading"); - - if (!PyArg_ParseTuple(args, "w*", &pbuf)) - return NULL; - - if (_PyVerify_fd(self->fd)) { - Py_BEGIN_ALLOW_THREADS - errno = 0; - n = read(self->fd, pbuf.buf, pbuf.len); - Py_END_ALLOW_THREADS - } else - n = -1; - PyBuffer_Release(&pbuf); - if (n < 0) { - if (errno == EAGAIN) - Py_RETURN_NONE; - PyErr_SetFromErrno(PyExc_IOError); - return NULL; - } + if (self->fd < 0) + return err_closed(); + if (!self->readable) + return err_mode("reading"); + + if (!PyArg_ParseTuple(args, "w*", &pbuf)) + return NULL; + + if (_PyVerify_fd(self->fd)) { + Py_BEGIN_ALLOW_THREADS + errno = 0; + n = read(self->fd, pbuf.buf, pbuf.len); + Py_END_ALLOW_THREADS + } else + n = -1; + PyBuffer_Release(&pbuf); + if (n < 0) { + if (errno == EAGAIN) + Py_RETURN_NONE; + PyErr_SetFromErrno(PyExc_IOError); + return NULL; + } - return PyLong_FromSsize_t(n); + return PyLong_FromSsize_t(n); } static size_t new_buffersize(fileio *self, size_t currentsize) { #ifdef HAVE_FSTAT - off_t pos, end; - struct stat st; - if (fstat(self->fd, &st) == 0) { - end = st.st_size; - pos = lseek(self->fd, 0L, SEEK_CUR); - /* Files claiming a size smaller than SMALLCHUNK may - actually be streaming pseudo-files. In this case, we - apply the more aggressive algorithm below. - */ - if (end >= SMALLCHUNK && end >= pos && pos >= 0) { - /* Add 1 so if the file were to grow we'd notice. */ - return currentsize + end - pos + 1; - } - } + off_t pos, end; + struct stat st; + if (fstat(self->fd, &st) == 0) { + end = st.st_size; + pos = lseek(self->fd, 0L, SEEK_CUR); + /* Files claiming a size smaller than SMALLCHUNK may + actually be streaming pseudo-files. In this case, we + apply the more aggressive algorithm below. + */ + if (end >= SMALLCHUNK && end >= pos && pos >= 0) { + /* Add 1 so if the file were to grow we'd notice. */ + return currentsize + end - pos + 1; + } + } #endif - if (currentsize > SMALLCHUNK) { - /* Keep doubling until we reach BIGCHUNK; - then keep adding BIGCHUNK. */ - if (currentsize <= BIGCHUNK) - return currentsize + currentsize; - else - return currentsize + BIGCHUNK; - } - return currentsize + SMALLCHUNK; + if (currentsize > SMALLCHUNK) { + /* Keep doubling until we reach BIGCHUNK; + then keep adding BIGCHUNK. */ + if (currentsize <= BIGCHUNK) + return currentsize + currentsize; + else + return currentsize + BIGCHUNK; + } + return currentsize + SMALLCHUNK; } static PyObject * fileio_readall(fileio *self) { - PyObject *result; - Py_ssize_t total = 0; - int n; - - if (!_PyVerify_fd(self->fd)) - return PyErr_SetFromErrno(PyExc_IOError); - - result = PyBytes_FromStringAndSize(NULL, SMALLCHUNK); - if (result == NULL) - return NULL; - - while (1) { - size_t newsize = new_buffersize(self, total); - if (newsize > PY_SSIZE_T_MAX || newsize <= 0) { - PyErr_SetString(PyExc_OverflowError, - "unbounded read returned more bytes " - "than a Python string can hold "); - Py_DECREF(result); - return NULL; - } - - if (PyBytes_GET_SIZE(result) < (Py_ssize_t)newsize) { - if (_PyBytes_Resize(&result, newsize) < 0) { - if (total == 0) { - Py_DECREF(result); - return NULL; - } - PyErr_Clear(); - break; - } - } - Py_BEGIN_ALLOW_THREADS - errno = 0; - n = read(self->fd, - PyBytes_AS_STRING(result) + total, - newsize - total); - Py_END_ALLOW_THREADS - if (n == 0) - break; - if (n < 0) { - if (total > 0) - break; - if (errno == EAGAIN) { - Py_DECREF(result); - Py_RETURN_NONE; - } - Py_DECREF(result); - PyErr_SetFromErrno(PyExc_IOError); - return NULL; - } - total += n; - } - - if (PyBytes_GET_SIZE(result) > total) { - if (_PyBytes_Resize(&result, total) < 0) { - /* This should never happen, but just in case */ - Py_DECREF(result); - return NULL; - } - } - return result; + PyObject *result; + Py_ssize_t total = 0; + int n; + + if (!_PyVerify_fd(self->fd)) + return PyErr_SetFromErrno(PyExc_IOError); + + result = PyBytes_FromStringAndSize(NULL, SMALLCHUNK); + if (result == NULL) + return NULL; + + while (1) { + size_t newsize = new_buffersize(self, total); + if (newsize > PY_SSIZE_T_MAX || newsize <= 0) { + PyErr_SetString(PyExc_OverflowError, + "unbounded read returned more bytes " + "than a Python string can hold "); + Py_DECREF(result); + return NULL; + } + + if (PyBytes_GET_SIZE(result) < (Py_ssize_t)newsize) { + if (_PyBytes_Resize(&result, newsize) < 0) { + if (total == 0) { + Py_DECREF(result); + return NULL; + } + PyErr_Clear(); + break; + } + } + Py_BEGIN_ALLOW_THREADS + errno = 0; + n = read(self->fd, + PyBytes_AS_STRING(result) + total, + newsize - total); + Py_END_ALLOW_THREADS + if (n == 0) + break; + if (n < 0) { + if (total > 0) + break; + if (errno == EAGAIN) { + Py_DECREF(result); + Py_RETURN_NONE; + } + Py_DECREF(result); + PyErr_SetFromErrno(PyExc_IOError); + return NULL; + } + total += n; + } + + if (PyBytes_GET_SIZE(result) > total) { + if (_PyBytes_Resize(&result, total) < 0) { + /* This should never happen, but just in case */ + Py_DECREF(result); + return NULL; + } + } + return result; } static PyObject * fileio_read(fileio *self, PyObject *args) { - char *ptr; - Py_ssize_t n; - Py_ssize_t size = -1; - PyObject *bytes; - - if (self->fd < 0) - return err_closed(); - if (!self->readable) - return err_mode("reading"); - - if (!PyArg_ParseTuple(args, "|O&", &_PyIO_ConvertSsize_t, &size)) - return NULL; - - if (size < 0) { - return fileio_readall(self); - } - - bytes = PyBytes_FromStringAndSize(NULL, size); - if (bytes == NULL) - return NULL; - ptr = PyBytes_AS_STRING(bytes); - - if (_PyVerify_fd(self->fd)) { - Py_BEGIN_ALLOW_THREADS - errno = 0; - n = read(self->fd, ptr, size); - Py_END_ALLOW_THREADS - } else - n = -1; - - if (n < 0) { - Py_DECREF(bytes); - if (errno == EAGAIN) - Py_RETURN_NONE; - PyErr_SetFromErrno(PyExc_IOError); - return NULL; - } - - if (n != size) { - if (_PyBytes_Resize(&bytes, n) < 0) { - Py_DECREF(bytes); - return NULL; - } - } + char *ptr; + Py_ssize_t n; + Py_ssize_t size = -1; + PyObject *bytes; + + if (self->fd < 0) + return err_closed(); + if (!self->readable) + return err_mode("reading"); + + if (!PyArg_ParseTuple(args, "|O&", &_PyIO_ConvertSsize_t, &size)) + return NULL; + + if (size < 0) { + return fileio_readall(self); + } + + bytes = PyBytes_FromStringAndSize(NULL, size); + if (bytes == NULL) + return NULL; + ptr = PyBytes_AS_STRING(bytes); + + if (_PyVerify_fd(self->fd)) { + Py_BEGIN_ALLOW_THREADS + errno = 0; + n = read(self->fd, ptr, size); + Py_END_ALLOW_THREADS + } else + n = -1; + + if (n < 0) { + Py_DECREF(bytes); + if (errno == EAGAIN) + Py_RETURN_NONE; + PyErr_SetFromErrno(PyExc_IOError); + return NULL; + } + + if (n != size) { + if (_PyBytes_Resize(&bytes, n) < 0) { + Py_DECREF(bytes); + return NULL; + } + } - return (PyObject *) bytes; + return (PyObject *) bytes; } static PyObject * fileio_write(fileio *self, PyObject *args) { - Py_buffer pbuf; - Py_ssize_t n; + Py_buffer pbuf; + Py_ssize_t n; - if (self->fd < 0) - return err_closed(); - if (!self->writable) - return err_mode("writing"); - - if (!PyArg_ParseTuple(args, "y*", &pbuf)) - return NULL; - - if (_PyVerify_fd(self->fd)) { - Py_BEGIN_ALLOW_THREADS - errno = 0; - n = write(self->fd, pbuf.buf, pbuf.len); - Py_END_ALLOW_THREADS - } else - n = -1; - - PyBuffer_Release(&pbuf); - - if (n < 0) { - if (errno == EAGAIN) - Py_RETURN_NONE; - PyErr_SetFromErrno(PyExc_IOError); - return NULL; - } + if (self->fd < 0) + return err_closed(); + if (!self->writable) + return err_mode("writing"); + + if (!PyArg_ParseTuple(args, "y*", &pbuf)) + return NULL; + + if (_PyVerify_fd(self->fd)) { + Py_BEGIN_ALLOW_THREADS + errno = 0; + n = write(self->fd, pbuf.buf, pbuf.len); + Py_END_ALLOW_THREADS + } else + n = -1; + + PyBuffer_Release(&pbuf); + + if (n < 0) { + if (errno == EAGAIN) + Py_RETURN_NONE; + PyErr_SetFromErrno(PyExc_IOError); + return NULL; + } - return PyLong_FromSsize_t(n); + return PyLong_FromSsize_t(n); } /* XXX Windows support below is likely incomplete */ @@ -683,235 +683,235 @@ static PyObject * portable_lseek(int fd, PyObject *posobj, int whence) { - Py_off_t pos, res; + Py_off_t pos, res; #ifdef SEEK_SET - /* Turn 0, 1, 2 into SEEK_{SET,CUR,END} */ - switch (whence) { + /* Turn 0, 1, 2 into SEEK_{SET,CUR,END} */ + switch (whence) { #if SEEK_SET != 0 - case 0: whence = SEEK_SET; break; + case 0: whence = SEEK_SET; break; #endif #if SEEK_CUR != 1 - case 1: whence = SEEK_CUR; break; + case 1: whence = SEEK_CUR; break; #endif #if SEEK_END != 2 - case 2: whence = SEEK_END; break; + case 2: whence = SEEK_END; break; #endif - } + } #endif /* SEEK_SET */ - if (posobj == NULL) - pos = 0; - else { - if(PyFloat_Check(posobj)) { - PyErr_SetString(PyExc_TypeError, "an integer is required"); - return NULL; - } + if (posobj == NULL) + pos = 0; + else { + if(PyFloat_Check(posobj)) { + PyErr_SetString(PyExc_TypeError, "an integer is required"); + return NULL; + } #if defined(HAVE_LARGEFILE_SUPPORT) - pos = PyLong_AsLongLong(posobj); + pos = PyLong_AsLongLong(posobj); #else - pos = PyLong_AsLong(posobj); + pos = PyLong_AsLong(posobj); #endif - if (PyErr_Occurred()) - return NULL; - } + if (PyErr_Occurred()) + return NULL; + } - if (_PyVerify_fd(fd)) { - Py_BEGIN_ALLOW_THREADS + if (_PyVerify_fd(fd)) { + Py_BEGIN_ALLOW_THREADS #if defined(MS_WIN64) || defined(MS_WINDOWS) - res = _lseeki64(fd, pos, whence); + res = _lseeki64(fd, pos, whence); #else - res = lseek(fd, pos, whence); + res = lseek(fd, pos, whence); #endif - Py_END_ALLOW_THREADS - } else - res = -1; - if (res < 0) - return PyErr_SetFromErrno(PyExc_IOError); + Py_END_ALLOW_THREADS + } else + res = -1; + if (res < 0) + return PyErr_SetFromErrno(PyExc_IOError); #if defined(HAVE_LARGEFILE_SUPPORT) - return PyLong_FromLongLong(res); + return PyLong_FromLongLong(res); #else - return PyLong_FromLong(res); + return PyLong_FromLong(res); #endif } static PyObject * fileio_seek(fileio *self, PyObject *args) { - PyObject *posobj; - int whence = 0; + PyObject *posobj; + int whence = 0; - if (self->fd < 0) - return err_closed(); + if (self->fd < 0) + return err_closed(); - if (!PyArg_ParseTuple(args, "O|i", &posobj, &whence)) - return NULL; + if (!PyArg_ParseTuple(args, "O|i", &posobj, &whence)) + return NULL; - return portable_lseek(self->fd, posobj, whence); + return portable_lseek(self->fd, posobj, whence); } static PyObject * fileio_tell(fileio *self, PyObject *args) { - if (self->fd < 0) - return err_closed(); + if (self->fd < 0) + return err_closed(); - return portable_lseek(self->fd, NULL, 1); + return portable_lseek(self->fd, NULL, 1); } #ifdef HAVE_FTRUNCATE static PyObject * fileio_truncate(fileio *self, PyObject *args) { - PyObject *posobj = NULL; /* the new size wanted by the user */ + PyObject *posobj = NULL; /* the new size wanted by the user */ #ifndef MS_WINDOWS - Py_off_t pos; + Py_off_t pos; #endif - int ret; - int fd; + int ret; + int fd; - fd = self->fd; - if (fd < 0) - return err_closed(); - if (!self->writable) - return err_mode("writing"); - - if (!PyArg_ParseTuple(args, "|O", &posobj)) - return NULL; - - if (posobj == Py_None || posobj == NULL) { - /* Get the current position. */ - posobj = portable_lseek(fd, NULL, 1); - if (posobj == NULL) - return NULL; - } - else { - Py_INCREF(posobj); - } + fd = self->fd; + if (fd < 0) + return err_closed(); + if (!self->writable) + return err_mode("writing"); + + if (!PyArg_ParseTuple(args, "|O", &posobj)) + return NULL; + + if (posobj == Py_None || posobj == NULL) { + /* Get the current position. */ + posobj = portable_lseek(fd, NULL, 1); + if (posobj == NULL) + return NULL; + } + else { + Py_INCREF(posobj); + } #ifdef MS_WINDOWS - /* MS _chsize doesn't work if newsize doesn't fit in 32 bits, - so don't even try using it. */ - { - PyObject *oldposobj, *tempposobj; - HANDLE hFile; - - /* we save the file pointer position */ - oldposobj = portable_lseek(fd, NULL, 1); - if (oldposobj == NULL) { - Py_DECREF(posobj); - return NULL; - } - - /* we then move to the truncation position */ - tempposobj = portable_lseek(fd, posobj, 0); - if (tempposobj == NULL) { - Py_DECREF(oldposobj); - Py_DECREF(posobj); - return NULL; - } - Py_DECREF(tempposobj); - - /* Truncate. Note that this may grow the file! */ - Py_BEGIN_ALLOW_THREADS - errno = 0; - hFile = (HANDLE)_get_osfhandle(fd); - ret = hFile == (HANDLE)-1; /* testing for INVALID_HANDLE value */ - if (ret == 0) { - ret = SetEndOfFile(hFile) == 0; - if (ret) - errno = EACCES; - } - Py_END_ALLOW_THREADS - - /* we restore the file pointer position in any case */ - tempposobj = portable_lseek(fd, oldposobj, 0); - Py_DECREF(oldposobj); - if (tempposobj == NULL) { - Py_DECREF(posobj); - return NULL; - } - Py_DECREF(tempposobj); - } + /* MS _chsize doesn't work if newsize doesn't fit in 32 bits, + so don't even try using it. */ + { + PyObject *oldposobj, *tempposobj; + HANDLE hFile; + + /* we save the file pointer position */ + oldposobj = portable_lseek(fd, NULL, 1); + if (oldposobj == NULL) { + Py_DECREF(posobj); + return NULL; + } + + /* we then move to the truncation position */ + tempposobj = portable_lseek(fd, posobj, 0); + if (tempposobj == NULL) { + Py_DECREF(oldposobj); + Py_DECREF(posobj); + return NULL; + } + Py_DECREF(tempposobj); + + /* Truncate. Note that this may grow the file! */ + Py_BEGIN_ALLOW_THREADS + errno = 0; + hFile = (HANDLE)_get_osfhandle(fd); + ret = hFile == (HANDLE)-1; /* testing for INVALID_HANDLE value */ + if (ret == 0) { + ret = SetEndOfFile(hFile) == 0; + if (ret) + errno = EACCES; + } + Py_END_ALLOW_THREADS + + /* we restore the file pointer position in any case */ + tempposobj = portable_lseek(fd, oldposobj, 0); + Py_DECREF(oldposobj); + if (tempposobj == NULL) { + Py_DECREF(posobj); + return NULL; + } + Py_DECREF(tempposobj); + } #else #if defined(HAVE_LARGEFILE_SUPPORT) - pos = PyLong_AsLongLong(posobj); + pos = PyLong_AsLongLong(posobj); #else - pos = PyLong_AsLong(posobj); + pos = PyLong_AsLong(posobj); #endif - if (PyErr_Occurred()){ - Py_DECREF(posobj); - return NULL; - } - - Py_BEGIN_ALLOW_THREADS - errno = 0; - ret = ftruncate(fd, pos); - Py_END_ALLOW_THREADS + if (PyErr_Occurred()){ + Py_DECREF(posobj); + return NULL; + } + + Py_BEGIN_ALLOW_THREADS + errno = 0; + ret = ftruncate(fd, pos); + Py_END_ALLOW_THREADS #endif /* !MS_WINDOWS */ - if (ret != 0) { - Py_DECREF(posobj); - PyErr_SetFromErrno(PyExc_IOError); - return NULL; - } + if (ret != 0) { + Py_DECREF(posobj); + PyErr_SetFromErrno(PyExc_IOError); + return NULL; + } - return posobj; + return posobj; } #endif /* HAVE_FTRUNCATE */ static char * mode_string(fileio *self) { - if (self->readable) { - if (self->writable) - return "rb+"; - else - return "rb"; - } - else - return "wb"; + if (self->readable) { + if (self->writable) + return "rb+"; + else + return "rb"; + } + else + return "wb"; } static PyObject * fileio_repr(fileio *self) { - PyObject *nameobj, *res; + PyObject *nameobj, *res; - if (self->fd < 0) - return PyUnicode_FromFormat("<_io.FileIO [closed]>"); + if (self->fd < 0) + return PyUnicode_FromFormat("<_io.FileIO [closed]>"); - nameobj = PyObject_GetAttrString((PyObject *) self, "name"); - if (nameobj == NULL) { - if (PyErr_ExceptionMatches(PyExc_AttributeError)) - PyErr_Clear(); - else - return NULL; - res = PyUnicode_FromFormat("<_io.FileIO fd=%d mode='%s'>", - self->fd, mode_string(self)); - } - else { - res = PyUnicode_FromFormat("<_io.FileIO name=%R mode='%s'>", - nameobj, mode_string(self)); - Py_DECREF(nameobj); - } - return res; + nameobj = PyObject_GetAttrString((PyObject *) self, "name"); + if (nameobj == NULL) { + if (PyErr_ExceptionMatches(PyExc_AttributeError)) + PyErr_Clear(); + else + return NULL; + res = PyUnicode_FromFormat("<_io.FileIO fd=%d mode='%s'>", + self->fd, mode_string(self)); + } + else { + res = PyUnicode_FromFormat("<_io.FileIO name=%R mode='%s'>", + nameobj, mode_string(self)); + Py_DECREF(nameobj); + } + return res; } static PyObject * fileio_isatty(fileio *self) { - long res; + long res; - if (self->fd < 0) - return err_closed(); - Py_BEGIN_ALLOW_THREADS - res = isatty(self->fd); - Py_END_ALLOW_THREADS - return PyBool_FromLong(res); + if (self->fd < 0) + return err_closed(); + Py_BEGIN_ALLOW_THREADS + res = isatty(self->fd); + Py_END_ALLOW_THREADS + return PyBool_FromLong(res); } @@ -919,7 +919,7 @@ "file(name: str[, mode: str]) -> file IO object\n" "\n" "Open a file. The mode can be 'r', 'w' or 'a' for reading (default),\n" -"writing or appending. The file will be created if it doesn't exist\n" +"writing or appending. The file will be created if it doesn't exist\n" "when opened for writing or appending; it will be truncated when\n" "opened for writing. Add a '+' to the mode to allow simultaneous\n" "reading and writing."); @@ -961,14 +961,14 @@ #ifdef HAVE_FTRUNCATE PyDoc_STRVAR(truncate_doc, -"truncate([size: int]) -> None. Truncate the file to at most size bytes.\n" +"truncate([size: int]) -> None. Truncate the file to at most size bytes.\n" "\n" "Size defaults to the current file position, as returned by tell()." "The current file position is changed to the value of size."); #endif PyDoc_STRVAR(tell_doc, -"tell() -> int. Current file position"); +"tell() -> int. Current file position"); PyDoc_STRVAR(readinto_doc, "readinto() -> Same as RawIOBase.readinto()."); @@ -992,22 +992,22 @@ "writable() -> bool. True if file was opened in a write mode."); static PyMethodDef fileio_methods[] = { - {"read", (PyCFunction)fileio_read, METH_VARARGS, read_doc}, - {"readall", (PyCFunction)fileio_readall, METH_NOARGS, readall_doc}, - {"readinto", (PyCFunction)fileio_readinto, METH_VARARGS, readinto_doc}, - {"write", (PyCFunction)fileio_write, METH_VARARGS, write_doc}, - {"seek", (PyCFunction)fileio_seek, METH_VARARGS, seek_doc}, - {"tell", (PyCFunction)fileio_tell, METH_VARARGS, tell_doc}, + {"read", (PyCFunction)fileio_read, METH_VARARGS, read_doc}, + {"readall", (PyCFunction)fileio_readall, METH_NOARGS, readall_doc}, + {"readinto", (PyCFunction)fileio_readinto, METH_VARARGS, readinto_doc}, + {"write", (PyCFunction)fileio_write, METH_VARARGS, write_doc}, + {"seek", (PyCFunction)fileio_seek, METH_VARARGS, seek_doc}, + {"tell", (PyCFunction)fileio_tell, METH_VARARGS, tell_doc}, #ifdef HAVE_FTRUNCATE - {"truncate", (PyCFunction)fileio_truncate, METH_VARARGS, truncate_doc}, + {"truncate", (PyCFunction)fileio_truncate, METH_VARARGS, truncate_doc}, #endif - {"close", (PyCFunction)fileio_close, METH_NOARGS, close_doc}, - {"seekable", (PyCFunction)fileio_seekable, METH_NOARGS, seekable_doc}, - {"readable", (PyCFunction)fileio_readable, METH_NOARGS, readable_doc}, - {"writable", (PyCFunction)fileio_writable, METH_NOARGS, writable_doc}, - {"fileno", (PyCFunction)fileio_fileno, METH_NOARGS, fileno_doc}, - {"isatty", (PyCFunction)fileio_isatty, METH_NOARGS, isatty_doc}, - {NULL, NULL} /* sentinel */ + {"close", (PyCFunction)fileio_close, METH_NOARGS, close_doc}, + {"seekable", (PyCFunction)fileio_seekable, METH_NOARGS, seekable_doc}, + {"readable", (PyCFunction)fileio_readable, METH_NOARGS, readable_doc}, + {"writable", (PyCFunction)fileio_writable, METH_NOARGS, writable_doc}, + {"fileno", (PyCFunction)fileio_fileno, METH_NOARGS, fileno_doc}, + {"isatty", (PyCFunction)fileio_isatty, METH_NOARGS, isatty_doc}, + {NULL, NULL} /* sentinel */ }; /* 'closed' and 'mode' are attributes for backwards compatibility reasons. */ @@ -1015,68 +1015,68 @@ static PyObject * get_closed(fileio *self, void *closure) { - return PyBool_FromLong((long)(self->fd < 0)); + return PyBool_FromLong((long)(self->fd < 0)); } static PyObject * get_closefd(fileio *self, void *closure) { - return PyBool_FromLong((long)(self->closefd)); + return PyBool_FromLong((long)(self->closefd)); } static PyObject * get_mode(fileio *self, void *closure) { - return PyUnicode_FromString(mode_string(self)); + return PyUnicode_FromString(mode_string(self)); } static PyGetSetDef fileio_getsetlist[] = { - {"closed", (getter)get_closed, NULL, "True if the file is closed"}, - {"closefd", (getter)get_closefd, NULL, - "True if the file descriptor will be closed"}, - {"mode", (getter)get_mode, NULL, "String giving the file mode"}, - {NULL}, + {"closed", (getter)get_closed, NULL, "True if the file is closed"}, + {"closefd", (getter)get_closefd, NULL, + "True if the file descriptor will be closed"}, + {"mode", (getter)get_mode, NULL, "String giving the file mode"}, + {NULL}, }; PyTypeObject PyFileIO_Type = { - PyVarObject_HEAD_INIT(NULL, 0) - "_io.FileIO", - sizeof(fileio), - 0, - (destructor)fileio_dealloc, /* tp_dealloc */ - 0, /* tp_print */ - 0, /* tp_getattr */ - 0, /* tp_setattr */ - 0, /* tp_reserved */ - (reprfunc)fileio_repr, /* 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_BASETYPE - | Py_TPFLAGS_HAVE_GC, /* tp_flags */ - fileio_doc, /* tp_doc */ - (traverseproc)fileio_traverse, /* tp_traverse */ - (inquiry)fileio_clear, /* tp_clear */ - 0, /* tp_richcompare */ - offsetof(fileio, weakreflist), /* tp_weaklistoffset */ - 0, /* tp_iter */ - 0, /* tp_iternext */ - fileio_methods, /* tp_methods */ - 0, /* tp_members */ - fileio_getsetlist, /* tp_getset */ - 0, /* tp_base */ - 0, /* tp_dict */ - 0, /* tp_descr_get */ - 0, /* tp_descr_set */ - offsetof(fileio, dict), /* tp_dictoffset */ - fileio_init, /* tp_init */ - PyType_GenericAlloc, /* tp_alloc */ - fileio_new, /* tp_new */ - PyObject_GC_Del, /* tp_free */ + PyVarObject_HEAD_INIT(NULL, 0) + "_io.FileIO", + sizeof(fileio), + 0, + (destructor)fileio_dealloc, /* tp_dealloc */ + 0, /* tp_print */ + 0, /* tp_getattr */ + 0, /* tp_setattr */ + 0, /* tp_reserved */ + (reprfunc)fileio_repr, /* 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_BASETYPE + | Py_TPFLAGS_HAVE_GC, /* tp_flags */ + fileio_doc, /* tp_doc */ + (traverseproc)fileio_traverse, /* tp_traverse */ + (inquiry)fileio_clear, /* tp_clear */ + 0, /* tp_richcompare */ + offsetof(fileio, weakreflist), /* tp_weaklistoffset */ + 0, /* tp_iter */ + 0, /* tp_iternext */ + fileio_methods, /* tp_methods */ + 0, /* tp_members */ + fileio_getsetlist, /* tp_getset */ + 0, /* tp_base */ + 0, /* tp_dict */ + 0, /* tp_descr_get */ + 0, /* tp_descr_set */ + offsetof(fileio, dict), /* tp_dictoffset */ + fileio_init, /* tp_init */ + PyType_GenericAlloc, /* tp_alloc */ + fileio_new, /* tp_new */ + PyObject_GC_Del, /* tp_free */ }; From python-checkins at python.org Wed May 5 18:34:37 2010 From: python-checkins at python.org (antoine.pitrou) Date: Wed, 5 May 2010 18:34:37 +0200 (CEST) Subject: [Python-checkins] r80799 - in python/branches/release31-maint: Modules/_io/fileio.c Message-ID: <20100505163437.D9FDCEEA17@mail.python.org> Author: antoine.pitrou Date: Wed May 5 18:34:37 2010 New Revision: 80799 Log: Merged revisions 80798 via svnmerge from svn+ssh://pythondev at svn.python.org/python/branches/py3k ................ r80798 | antoine.pitrou | 2010-05-05 18:31:07 +0200 (mer., 05 mai 2010) | 9 lines Merged revisions 80796 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r80796 | antoine.pitrou | 2010-05-05 18:27:30 +0200 (mer., 05 mai 2010) | 3 lines Untabify Modules/_io/fileio.c ........ ................ Modified: python/branches/release31-maint/ (props changed) python/branches/release31-maint/Modules/_io/fileio.c Modified: python/branches/release31-maint/Modules/_io/fileio.c ============================================================================== --- python/branches/release31-maint/Modules/_io/fileio.c (original) +++ python/branches/release31-maint/Modules/_io/fileio.c Wed May 5 18:34:37 2010 @@ -43,14 +43,14 @@ #endif typedef struct { - PyObject_HEAD - int fd; - unsigned int readable : 1; - unsigned int writable : 1; - signed int seekable : 2; /* -1 means unknown */ - unsigned int closefd : 1; - PyObject *weakreflist; - PyObject *dict; + PyObject_HEAD + int fd; + unsigned int readable : 1; + unsigned int writable : 1; + signed int seekable : 2; /* -1 means unknown */ + unsigned int closefd : 1; + PyObject *weakreflist; + PyObject *dict; } fileio; PyTypeObject PyFileIO_Type; @@ -60,7 +60,7 @@ int _PyFileIO_closed(PyObject *self) { - return ((fileio *)self)->fd < 0; + return ((fileio *)self)->fd < 0; } static PyObject * @@ -72,64 +72,64 @@ static int internal_close(fileio *self) { - int err = 0; - int save_errno = 0; - if (self->fd >= 0) { - int fd = self->fd; - self->fd = -1; - /* fd is accessible and someone else may have closed it */ - if (_PyVerify_fd(fd)) { - Py_BEGIN_ALLOW_THREADS - err = close(fd); - if (err < 0) - save_errno = errno; - Py_END_ALLOW_THREADS - } else { - save_errno = errno; - err = -1; - } - } - if (err < 0) { - errno = save_errno; - PyErr_SetFromErrno(PyExc_IOError); - return -1; - } - return 0; + int err = 0; + int save_errno = 0; + if (self->fd >= 0) { + int fd = self->fd; + self->fd = -1; + /* fd is accessible and someone else may have closed it */ + if (_PyVerify_fd(fd)) { + Py_BEGIN_ALLOW_THREADS + err = close(fd); + if (err < 0) + save_errno = errno; + Py_END_ALLOW_THREADS + } else { + save_errno = errno; + err = -1; + } + } + if (err < 0) { + errno = save_errno; + PyErr_SetFromErrno(PyExc_IOError); + return -1; + } + return 0; } static PyObject * fileio_close(fileio *self) { - if (!self->closefd) { - self->fd = -1; - Py_RETURN_NONE; - } - errno = internal_close(self); - if (errno < 0) - return NULL; + if (!self->closefd) { + self->fd = -1; + Py_RETURN_NONE; + } + errno = internal_close(self); + if (errno < 0) + return NULL; - return PyObject_CallMethod((PyObject*)&PyRawIOBase_Type, - "close", "O", self); + return PyObject_CallMethod((PyObject*)&PyRawIOBase_Type, + "close", "O", self); } static PyObject * fileio_new(PyTypeObject *type, PyObject *args, PyObject *kwds) { - fileio *self; + fileio *self; - assert(type != NULL && type->tp_alloc != NULL); + assert(type != NULL && type->tp_alloc != NULL); - self = (fileio *) type->tp_alloc(type, 0); - if (self != NULL) { - self->fd = -1; - self->readable = 0; - self->writable = 0; - self->seekable = -1; - self->closefd = 1; - self->weakreflist = NULL; - } + self = (fileio *) type->tp_alloc(type, 0); + if (self != NULL) { + self->fd = -1; + self->readable = 0; + self->writable = 0; + self->seekable = -1; + self->closefd = 1; + self->weakreflist = NULL; + } - return (PyObject *) self; + return (PyObject *) self; } /* On Unix, open will succeed for directories. @@ -140,538 +140,538 @@ dircheck(fileio* self, const char *name) { #if defined(HAVE_FSTAT) && defined(S_IFDIR) && defined(EISDIR) - struct stat buf; - if (self->fd < 0) - return 0; - if (fstat(self->fd, &buf) == 0 && S_ISDIR(buf.st_mode)) { - char *msg = strerror(EISDIR); - PyObject *exc; - if (internal_close(self)) - return -1; - - exc = PyObject_CallFunction(PyExc_IOError, "(iss)", - EISDIR, msg, name); - PyErr_SetObject(PyExc_IOError, exc); - Py_XDECREF(exc); - return -1; - } + struct stat buf; + if (self->fd < 0) + return 0; + if (fstat(self->fd, &buf) == 0 && S_ISDIR(buf.st_mode)) { + char *msg = strerror(EISDIR); + PyObject *exc; + if (internal_close(self)) + return -1; + + exc = PyObject_CallFunction(PyExc_IOError, "(iss)", + EISDIR, msg, name); + PyErr_SetObject(PyExc_IOError, exc); + Py_XDECREF(exc); + return -1; + } #endif - return 0; + return 0; } static int check_fd(int fd) { #if defined(HAVE_FSTAT) - struct stat buf; - if (!_PyVerify_fd(fd) || (fstat(fd, &buf) < 0 && errno == EBADF)) { - PyObject *exc; - char *msg = strerror(EBADF); - exc = PyObject_CallFunction(PyExc_OSError, "(is)", - EBADF, msg); - PyErr_SetObject(PyExc_OSError, exc); - Py_XDECREF(exc); - return -1; - } + struct stat buf; + if (!_PyVerify_fd(fd) || (fstat(fd, &buf) < 0 && errno == EBADF)) { + PyObject *exc; + char *msg = strerror(EBADF); + exc = PyObject_CallFunction(PyExc_OSError, "(is)", + EBADF, msg); + PyErr_SetObject(PyExc_OSError, exc); + Py_XDECREF(exc); + return -1; + } #endif - return 0; + return 0; } static int fileio_init(PyObject *oself, PyObject *args, PyObject *kwds) { - fileio *self = (fileio *) oself; - static char *kwlist[] = {"file", "mode", "closefd", NULL}; - const char *name = NULL; - PyObject *nameobj, *stringobj = NULL; - char *mode = "r"; - char *s; + fileio *self = (fileio *) oself; + static char *kwlist[] = {"file", "mode", "closefd", NULL}; + const char *name = NULL; + PyObject *nameobj, *stringobj = NULL; + char *mode = "r"; + char *s; #ifdef MS_WINDOWS - Py_UNICODE *widename = NULL; + Py_UNICODE *widename = NULL; #endif - int ret = 0; - int rwa = 0, plus = 0, append = 0; - int flags = 0; - int fd = -1; - int closefd = 1; - - assert(PyFileIO_Check(oself)); - if (self->fd >= 0) { - /* Have to close the existing file first. */ - if (internal_close(self) < 0) - return -1; - } - - if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|si:fileio", - kwlist, &nameobj, &mode, &closefd)) - return -1; - - if (PyFloat_Check(nameobj)) { - PyErr_SetString(PyExc_TypeError, - "integer argument expected, got float"); - return -1; - } - - fd = PyLong_AsLong(nameobj); - if (fd < 0) { - if (!PyErr_Occurred()) { - PyErr_SetString(PyExc_ValueError, - "Negative filedescriptor"); - return -1; - } - PyErr_Clear(); - } + int ret = 0; + int rwa = 0, plus = 0, append = 0; + int flags = 0; + int fd = -1; + int closefd = 1; + + assert(PyFileIO_Check(oself)); + if (self->fd >= 0) { + /* Have to close the existing file first. */ + if (internal_close(self) < 0) + return -1; + } + + if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|si:fileio", + kwlist, &nameobj, &mode, &closefd)) + return -1; + + if (PyFloat_Check(nameobj)) { + PyErr_SetString(PyExc_TypeError, + "integer argument expected, got float"); + return -1; + } + + fd = PyLong_AsLong(nameobj); + if (fd < 0) { + if (!PyErr_Occurred()) { + PyErr_SetString(PyExc_ValueError, + "Negative filedescriptor"); + return -1; + } + PyErr_Clear(); + } #ifdef MS_WINDOWS - if (GetVersion() < 0x80000000) { - /* On NT, so wide API available */ - if (PyUnicode_Check(nameobj)) - widename = PyUnicode_AS_UNICODE(nameobj); - } - if (widename == NULL) + if (GetVersion() < 0x80000000) { + /* On NT, so wide API available */ + if (PyUnicode_Check(nameobj)) + widename = PyUnicode_AS_UNICODE(nameobj); + } + if (widename == NULL) #endif - if (fd < 0) - { - if (PyBytes_Check(nameobj) || PyByteArray_Check(nameobj)) { - Py_ssize_t namelen; - if (PyObject_AsCharBuffer(nameobj, &name, &namelen) < 0) - return -1; - } - else { - PyObject *u = PyUnicode_FromObject(nameobj); - - if (u == NULL) - return -1; - - stringobj = PyUnicode_AsEncodedString( - u, Py_FileSystemDefaultEncoding, "surrogateescape"); - Py_DECREF(u); - if (stringobj == NULL) - return -1; - if (!PyBytes_Check(stringobj)) { - PyErr_SetString(PyExc_TypeError, - "encoder failed to return bytes"); - goto error; - } - name = PyBytes_AS_STRING(stringobj); - } - } - - s = mode; - while (*s) { - switch (*s++) { - case 'r': - if (rwa) { - bad_mode: - PyErr_SetString(PyExc_ValueError, - "Must have exactly one of read/write/append mode"); - goto error; - } - rwa = 1; - self->readable = 1; - break; - case 'w': - if (rwa) - goto bad_mode; - rwa = 1; - self->writable = 1; - flags |= O_CREAT | O_TRUNC; - break; - case 'a': - if (rwa) - goto bad_mode; - rwa = 1; - self->writable = 1; - flags |= O_CREAT; - append = 1; - break; - case 'b': - break; - case '+': - if (plus) - goto bad_mode; - self->readable = self->writable = 1; - plus = 1; - break; - default: - PyErr_Format(PyExc_ValueError, - "invalid mode: %.200s", mode); - goto error; - } - } - - if (!rwa) - goto bad_mode; - - if (self->readable && self->writable) - flags |= O_RDWR; - else if (self->readable) - flags |= O_RDONLY; - else - flags |= O_WRONLY; + if (fd < 0) + { + if (PyBytes_Check(nameobj) || PyByteArray_Check(nameobj)) { + Py_ssize_t namelen; + if (PyObject_AsCharBuffer(nameobj, &name, &namelen) < 0) + return -1; + } + else { + PyObject *u = PyUnicode_FromObject(nameobj); + + if (u == NULL) + return -1; + + stringobj = PyUnicode_AsEncodedString( + u, Py_FileSystemDefaultEncoding, "surrogateescape"); + Py_DECREF(u); + if (stringobj == NULL) + return -1; + if (!PyBytes_Check(stringobj)) { + PyErr_SetString(PyExc_TypeError, + "encoder failed to return bytes"); + goto error; + } + name = PyBytes_AS_STRING(stringobj); + } + } + + s = mode; + while (*s) { + switch (*s++) { + case 'r': + if (rwa) { + bad_mode: + PyErr_SetString(PyExc_ValueError, + "Must have exactly one of read/write/append mode"); + goto error; + } + rwa = 1; + self->readable = 1; + break; + case 'w': + if (rwa) + goto bad_mode; + rwa = 1; + self->writable = 1; + flags |= O_CREAT | O_TRUNC; + break; + case 'a': + if (rwa) + goto bad_mode; + rwa = 1; + self->writable = 1; + flags |= O_CREAT; + append = 1; + break; + case 'b': + break; + case '+': + if (plus) + goto bad_mode; + self->readable = self->writable = 1; + plus = 1; + break; + default: + PyErr_Format(PyExc_ValueError, + "invalid mode: %.200s", mode); + goto error; + } + } + + if (!rwa) + goto bad_mode; + + if (self->readable && self->writable) + flags |= O_RDWR; + else if (self->readable) + flags |= O_RDONLY; + else + flags |= O_WRONLY; #ifdef O_BINARY - flags |= O_BINARY; + flags |= O_BINARY; #endif #ifdef O_APPEND - if (append) - flags |= O_APPEND; + if (append) + flags |= O_APPEND; #endif - if (fd >= 0) { - if (check_fd(fd)) - goto error; - self->fd = fd; - self->closefd = closefd; - } - else { - self->closefd = 1; - if (!closefd) { - PyErr_SetString(PyExc_ValueError, - "Cannot use closefd=False with file name"); - goto error; - } + if (fd >= 0) { + if (check_fd(fd)) + goto error; + self->fd = fd; + self->closefd = closefd; + } + else { + self->closefd = 1; + if (!closefd) { + PyErr_SetString(PyExc_ValueError, + "Cannot use closefd=False with file name"); + goto error; + } - Py_BEGIN_ALLOW_THREADS - errno = 0; + Py_BEGIN_ALLOW_THREADS + errno = 0; #ifdef MS_WINDOWS - if (widename != NULL) - self->fd = _wopen(widename, flags, 0666); - else + if (widename != NULL) + self->fd = _wopen(widename, flags, 0666); + else #endif - self->fd = open(name, flags, 0666); - Py_END_ALLOW_THREADS - if (self->fd < 0) { + self->fd = open(name, flags, 0666); + Py_END_ALLOW_THREADS + if (self->fd < 0) { #ifdef MS_WINDOWS - if (widename != NULL) - PyErr_SetFromErrnoWithUnicodeFilename(PyExc_IOError, widename); - else + if (widename != NULL) + PyErr_SetFromErrnoWithUnicodeFilename(PyExc_IOError, widename); + else #endif - PyErr_SetFromErrnoWithFilename(PyExc_IOError, name); - goto error; - } - if(dircheck(self, name) < 0) - goto error; - } - - if (PyObject_SetAttrString((PyObject *)self, "name", nameobj) < 0) - goto error; - - if (append) { - /* For consistent behaviour, we explicitly seek to the - end of file (otherwise, it might be done only on the - first write()). */ - PyObject *pos = portable_lseek(self->fd, NULL, 2); - if (pos == NULL) - goto error; - Py_DECREF(pos); - } + PyErr_SetFromErrnoWithFilename(PyExc_IOError, name); + goto error; + } + if(dircheck(self, name) < 0) + goto error; + } + + if (PyObject_SetAttrString((PyObject *)self, "name", nameobj) < 0) + goto error; + + if (append) { + /* For consistent behaviour, we explicitly seek to the + end of file (otherwise, it might be done only on the + first write()). */ + PyObject *pos = portable_lseek(self->fd, NULL, 2); + if (pos == NULL) + goto error; + Py_DECREF(pos); + } - goto done; + goto done; error: - ret = -1; + ret = -1; done: - Py_CLEAR(stringobj); - return ret; + Py_CLEAR(stringobj); + return ret; } static int fileio_traverse(fileio *self, visitproc visit, void *arg) { - Py_VISIT(self->dict); - return 0; + Py_VISIT(self->dict); + return 0; } static int fileio_clear(fileio *self) { - Py_CLEAR(self->dict); - return 0; + Py_CLEAR(self->dict); + return 0; } static void fileio_dealloc(fileio *self) { - if (_PyIOBase_finalize((PyObject *) self) < 0) - return; - _PyObject_GC_UNTRACK(self); - if (self->weakreflist != NULL) - PyObject_ClearWeakRefs((PyObject *) self); - Py_CLEAR(self->dict); - Py_TYPE(self)->tp_free((PyObject *)self); + if (_PyIOBase_finalize((PyObject *) self) < 0) + return; + _PyObject_GC_UNTRACK(self); + if (self->weakreflist != NULL) + PyObject_ClearWeakRefs((PyObject *) self); + Py_CLEAR(self->dict); + Py_TYPE(self)->tp_free((PyObject *)self); } static PyObject * err_closed(void) { - PyErr_SetString(PyExc_ValueError, "I/O operation on closed file"); - return NULL; + PyErr_SetString(PyExc_ValueError, "I/O operation on closed file"); + return NULL; } static PyObject * err_mode(char *action) { - PyErr_Format(PyExc_ValueError, "File not open for %s", action); - return NULL; + PyErr_Format(PyExc_ValueError, "File not open for %s", action); + return NULL; } static PyObject * fileio_fileno(fileio *self) { - if (self->fd < 0) - return err_closed(); - return PyLong_FromLong((long) self->fd); + if (self->fd < 0) + return err_closed(); + return PyLong_FromLong((long) self->fd); } static PyObject * fileio_readable(fileio *self) { - if (self->fd < 0) - return err_closed(); - return PyBool_FromLong((long) self->readable); + if (self->fd < 0) + return err_closed(); + return PyBool_FromLong((long) self->readable); } static PyObject * fileio_writable(fileio *self) { - if (self->fd < 0) - return err_closed(); - return PyBool_FromLong((long) self->writable); + if (self->fd < 0) + return err_closed(); + return PyBool_FromLong((long) self->writable); } static PyObject * fileio_seekable(fileio *self) { - if (self->fd < 0) - return err_closed(); - if (self->seekable < 0) { - PyObject *pos = portable_lseek(self->fd, NULL, SEEK_CUR); - if (pos == NULL) { - PyErr_Clear(); - self->seekable = 0; - } else { - Py_DECREF(pos); - self->seekable = 1; - } - } - return PyBool_FromLong((long) self->seekable); + if (self->fd < 0) + return err_closed(); + if (self->seekable < 0) { + PyObject *pos = portable_lseek(self->fd, NULL, SEEK_CUR); + if (pos == NULL) { + PyErr_Clear(); + self->seekable = 0; + } else { + Py_DECREF(pos); + self->seekable = 1; + } + } + return PyBool_FromLong((long) self->seekable); } static PyObject * fileio_readinto(fileio *self, PyObject *args) { - Py_buffer pbuf; - Py_ssize_t n; + Py_buffer pbuf; + Py_ssize_t n; - if (self->fd < 0) - return err_closed(); - if (!self->readable) - return err_mode("reading"); - - if (!PyArg_ParseTuple(args, "w*", &pbuf)) - return NULL; - - if (_PyVerify_fd(self->fd)) { - Py_BEGIN_ALLOW_THREADS - errno = 0; - n = read(self->fd, pbuf.buf, pbuf.len); - Py_END_ALLOW_THREADS - } else - n = -1; - PyBuffer_Release(&pbuf); - if (n < 0) { - if (errno == EAGAIN) - Py_RETURN_NONE; - PyErr_SetFromErrno(PyExc_IOError); - return NULL; - } + if (self->fd < 0) + return err_closed(); + if (!self->readable) + return err_mode("reading"); + + if (!PyArg_ParseTuple(args, "w*", &pbuf)) + return NULL; + + if (_PyVerify_fd(self->fd)) { + Py_BEGIN_ALLOW_THREADS + errno = 0; + n = read(self->fd, pbuf.buf, pbuf.len); + Py_END_ALLOW_THREADS + } else + n = -1; + PyBuffer_Release(&pbuf); + if (n < 0) { + if (errno == EAGAIN) + Py_RETURN_NONE; + PyErr_SetFromErrno(PyExc_IOError); + return NULL; + } - return PyLong_FromSsize_t(n); + return PyLong_FromSsize_t(n); } static size_t new_buffersize(fileio *self, size_t currentsize) { #ifdef HAVE_FSTAT - off_t pos, end; - struct stat st; - if (fstat(self->fd, &st) == 0) { - end = st.st_size; - pos = lseek(self->fd, 0L, SEEK_CUR); - /* Files claiming a size smaller than SMALLCHUNK may - actually be streaming pseudo-files. In this case, we - apply the more aggressive algorithm below. - */ - if (end >= SMALLCHUNK && end >= pos && pos >= 0) { - /* Add 1 so if the file were to grow we'd notice. */ - return currentsize + end - pos + 1; - } - } + off_t pos, end; + struct stat st; + if (fstat(self->fd, &st) == 0) { + end = st.st_size; + pos = lseek(self->fd, 0L, SEEK_CUR); + /* Files claiming a size smaller than SMALLCHUNK may + actually be streaming pseudo-files. In this case, we + apply the more aggressive algorithm below. + */ + if (end >= SMALLCHUNK && end >= pos && pos >= 0) { + /* Add 1 so if the file were to grow we'd notice. */ + return currentsize + end - pos + 1; + } + } #endif - if (currentsize > SMALLCHUNK) { - /* Keep doubling until we reach BIGCHUNK; - then keep adding BIGCHUNK. */ - if (currentsize <= BIGCHUNK) - return currentsize + currentsize; - else - return currentsize + BIGCHUNK; - } - return currentsize + SMALLCHUNK; + if (currentsize > SMALLCHUNK) { + /* Keep doubling until we reach BIGCHUNK; + then keep adding BIGCHUNK. */ + if (currentsize <= BIGCHUNK) + return currentsize + currentsize; + else + return currentsize + BIGCHUNK; + } + return currentsize + SMALLCHUNK; } static PyObject * fileio_readall(fileio *self) { - PyObject *result; - Py_ssize_t total = 0; - int n; - - if (!_PyVerify_fd(self->fd)) - return PyErr_SetFromErrno(PyExc_IOError); - - result = PyBytes_FromStringAndSize(NULL, SMALLCHUNK); - if (result == NULL) - return NULL; - - while (1) { - size_t newsize = new_buffersize(self, total); - if (newsize > PY_SSIZE_T_MAX || newsize <= 0) { - PyErr_SetString(PyExc_OverflowError, - "unbounded read returned more bytes " - "than a Python string can hold "); - Py_DECREF(result); - return NULL; - } - - if (PyBytes_GET_SIZE(result) < (Py_ssize_t)newsize) { - if (_PyBytes_Resize(&result, newsize) < 0) { - if (total == 0) { - Py_DECREF(result); - return NULL; - } - PyErr_Clear(); - break; - } - } - Py_BEGIN_ALLOW_THREADS - errno = 0; - n = read(self->fd, - PyBytes_AS_STRING(result) + total, - newsize - total); - Py_END_ALLOW_THREADS - if (n == 0) - break; - if (n < 0) { - if (total > 0) - break; - if (errno == EAGAIN) { - Py_DECREF(result); - Py_RETURN_NONE; - } - Py_DECREF(result); - PyErr_SetFromErrno(PyExc_IOError); - return NULL; - } - total += n; - } - - if (PyBytes_GET_SIZE(result) > total) { - if (_PyBytes_Resize(&result, total) < 0) { - /* This should never happen, but just in case */ - Py_DECREF(result); - return NULL; - } - } - return result; + PyObject *result; + Py_ssize_t total = 0; + int n; + + if (!_PyVerify_fd(self->fd)) + return PyErr_SetFromErrno(PyExc_IOError); + + result = PyBytes_FromStringAndSize(NULL, SMALLCHUNK); + if (result == NULL) + return NULL; + + while (1) { + size_t newsize = new_buffersize(self, total); + if (newsize > PY_SSIZE_T_MAX || newsize <= 0) { + PyErr_SetString(PyExc_OverflowError, + "unbounded read returned more bytes " + "than a Python string can hold "); + Py_DECREF(result); + return NULL; + } + + if (PyBytes_GET_SIZE(result) < (Py_ssize_t)newsize) { + if (_PyBytes_Resize(&result, newsize) < 0) { + if (total == 0) { + Py_DECREF(result); + return NULL; + } + PyErr_Clear(); + break; + } + } + Py_BEGIN_ALLOW_THREADS + errno = 0; + n = read(self->fd, + PyBytes_AS_STRING(result) + total, + newsize - total); + Py_END_ALLOW_THREADS + if (n == 0) + break; + if (n < 0) { + if (total > 0) + break; + if (errno == EAGAIN) { + Py_DECREF(result); + Py_RETURN_NONE; + } + Py_DECREF(result); + PyErr_SetFromErrno(PyExc_IOError); + return NULL; + } + total += n; + } + + if (PyBytes_GET_SIZE(result) > total) { + if (_PyBytes_Resize(&result, total) < 0) { + /* This should never happen, but just in case */ + Py_DECREF(result); + return NULL; + } + } + return result; } static PyObject * fileio_read(fileio *self, PyObject *args) { - char *ptr; - Py_ssize_t n; - Py_ssize_t size = -1; - PyObject *bytes; - - if (self->fd < 0) - return err_closed(); - if (!self->readable) - return err_mode("reading"); - - if (!PyArg_ParseTuple(args, "|O&", &_PyIO_ConvertSsize_t, &size)) - return NULL; - - if (size < 0) { - return fileio_readall(self); - } - - bytes = PyBytes_FromStringAndSize(NULL, size); - if (bytes == NULL) - return NULL; - ptr = PyBytes_AS_STRING(bytes); - - if (_PyVerify_fd(self->fd)) { - Py_BEGIN_ALLOW_THREADS - errno = 0; - n = read(self->fd, ptr, size); - Py_END_ALLOW_THREADS - } else - n = -1; - - if (n < 0) { - Py_DECREF(bytes); - if (errno == EAGAIN) - Py_RETURN_NONE; - PyErr_SetFromErrno(PyExc_IOError); - return NULL; - } - - if (n != size) { - if (_PyBytes_Resize(&bytes, n) < 0) { - Py_DECREF(bytes); - return NULL; - } - } + char *ptr; + Py_ssize_t n; + Py_ssize_t size = -1; + PyObject *bytes; + + if (self->fd < 0) + return err_closed(); + if (!self->readable) + return err_mode("reading"); + + if (!PyArg_ParseTuple(args, "|O&", &_PyIO_ConvertSsize_t, &size)) + return NULL; + + if (size < 0) { + return fileio_readall(self); + } + + bytes = PyBytes_FromStringAndSize(NULL, size); + if (bytes == NULL) + return NULL; + ptr = PyBytes_AS_STRING(bytes); + + if (_PyVerify_fd(self->fd)) { + Py_BEGIN_ALLOW_THREADS + errno = 0; + n = read(self->fd, ptr, size); + Py_END_ALLOW_THREADS + } else + n = -1; + + if (n < 0) { + Py_DECREF(bytes); + if (errno == EAGAIN) + Py_RETURN_NONE; + PyErr_SetFromErrno(PyExc_IOError); + return NULL; + } + + if (n != size) { + if (_PyBytes_Resize(&bytes, n) < 0) { + Py_DECREF(bytes); + return NULL; + } + } - return (PyObject *) bytes; + return (PyObject *) bytes; } static PyObject * fileio_write(fileio *self, PyObject *args) { - Py_buffer pbuf; - Py_ssize_t n; + Py_buffer pbuf; + Py_ssize_t n; - if (self->fd < 0) - return err_closed(); - if (!self->writable) - return err_mode("writing"); - - if (!PyArg_ParseTuple(args, "y*", &pbuf)) - return NULL; - - if (_PyVerify_fd(self->fd)) { - Py_BEGIN_ALLOW_THREADS - errno = 0; - n = write(self->fd, pbuf.buf, pbuf.len); - Py_END_ALLOW_THREADS - } else - n = -1; - - PyBuffer_Release(&pbuf); - - if (n < 0) { - if (errno == EAGAIN) - Py_RETURN_NONE; - PyErr_SetFromErrno(PyExc_IOError); - return NULL; - } + if (self->fd < 0) + return err_closed(); + if (!self->writable) + return err_mode("writing"); + + if (!PyArg_ParseTuple(args, "y*", &pbuf)) + return NULL; + + if (_PyVerify_fd(self->fd)) { + Py_BEGIN_ALLOW_THREADS + errno = 0; + n = write(self->fd, pbuf.buf, pbuf.len); + Py_END_ALLOW_THREADS + } else + n = -1; + + PyBuffer_Release(&pbuf); + + if (n < 0) { + if (errno == EAGAIN) + Py_RETURN_NONE; + PyErr_SetFromErrno(PyExc_IOError); + return NULL; + } - return PyLong_FromSsize_t(n); + return PyLong_FromSsize_t(n); } /* XXX Windows support below is likely incomplete */ @@ -680,235 +680,235 @@ static PyObject * portable_lseek(int fd, PyObject *posobj, int whence) { - Py_off_t pos, res; + Py_off_t pos, res; #ifdef SEEK_SET - /* Turn 0, 1, 2 into SEEK_{SET,CUR,END} */ - switch (whence) { + /* Turn 0, 1, 2 into SEEK_{SET,CUR,END} */ + switch (whence) { #if SEEK_SET != 0 - case 0: whence = SEEK_SET; break; + case 0: whence = SEEK_SET; break; #endif #if SEEK_CUR != 1 - case 1: whence = SEEK_CUR; break; + case 1: whence = SEEK_CUR; break; #endif #if SEEK_END != 2 - case 2: whence = SEEK_END; break; + case 2: whence = SEEK_END; break; #endif - } + } #endif /* SEEK_SET */ - if (posobj == NULL) - pos = 0; - else { - if(PyFloat_Check(posobj)) { - PyErr_SetString(PyExc_TypeError, "an integer is required"); - return NULL; - } + if (posobj == NULL) + pos = 0; + else { + if(PyFloat_Check(posobj)) { + PyErr_SetString(PyExc_TypeError, "an integer is required"); + return NULL; + } #if defined(HAVE_LARGEFILE_SUPPORT) - pos = PyLong_AsLongLong(posobj); + pos = PyLong_AsLongLong(posobj); #else - pos = PyLong_AsLong(posobj); + pos = PyLong_AsLong(posobj); #endif - if (PyErr_Occurred()) - return NULL; - } + if (PyErr_Occurred()) + return NULL; + } - if (_PyVerify_fd(fd)) { - Py_BEGIN_ALLOW_THREADS + if (_PyVerify_fd(fd)) { + Py_BEGIN_ALLOW_THREADS #if defined(MS_WIN64) || defined(MS_WINDOWS) - res = _lseeki64(fd, pos, whence); + res = _lseeki64(fd, pos, whence); #else - res = lseek(fd, pos, whence); + res = lseek(fd, pos, whence); #endif - Py_END_ALLOW_THREADS - } else - res = -1; - if (res < 0) - return PyErr_SetFromErrno(PyExc_IOError); + Py_END_ALLOW_THREADS + } else + res = -1; + if (res < 0) + return PyErr_SetFromErrno(PyExc_IOError); #if defined(HAVE_LARGEFILE_SUPPORT) - return PyLong_FromLongLong(res); + return PyLong_FromLongLong(res); #else - return PyLong_FromLong(res); + return PyLong_FromLong(res); #endif } static PyObject * fileio_seek(fileio *self, PyObject *args) { - PyObject *posobj; - int whence = 0; + PyObject *posobj; + int whence = 0; - if (self->fd < 0) - return err_closed(); + if (self->fd < 0) + return err_closed(); - if (!PyArg_ParseTuple(args, "O|i", &posobj, &whence)) - return NULL; + if (!PyArg_ParseTuple(args, "O|i", &posobj, &whence)) + return NULL; - return portable_lseek(self->fd, posobj, whence); + return portable_lseek(self->fd, posobj, whence); } static PyObject * fileio_tell(fileio *self, PyObject *args) { - if (self->fd < 0) - return err_closed(); + if (self->fd < 0) + return err_closed(); - return portable_lseek(self->fd, NULL, 1); + return portable_lseek(self->fd, NULL, 1); } #ifdef HAVE_FTRUNCATE static PyObject * fileio_truncate(fileio *self, PyObject *args) { - PyObject *posobj = NULL; /* the new size wanted by the user */ + PyObject *posobj = NULL; /* the new size wanted by the user */ #ifndef MS_WINDOWS - Py_off_t pos; + Py_off_t pos; #endif - int ret; - int fd; + int ret; + int fd; - fd = self->fd; - if (fd < 0) - return err_closed(); - if (!self->writable) - return err_mode("writing"); - - if (!PyArg_ParseTuple(args, "|O", &posobj)) - return NULL; - - if (posobj == Py_None || posobj == NULL) { - /* Get the current position. */ - posobj = portable_lseek(fd, NULL, 1); - if (posobj == NULL) - return NULL; - } - else { - Py_INCREF(posobj); - } + fd = self->fd; + if (fd < 0) + return err_closed(); + if (!self->writable) + return err_mode("writing"); + + if (!PyArg_ParseTuple(args, "|O", &posobj)) + return NULL; + + if (posobj == Py_None || posobj == NULL) { + /* Get the current position. */ + posobj = portable_lseek(fd, NULL, 1); + if (posobj == NULL) + return NULL; + } + else { + Py_INCREF(posobj); + } #ifdef MS_WINDOWS - /* MS _chsize doesn't work if newsize doesn't fit in 32 bits, - so don't even try using it. */ - { - PyObject *oldposobj, *tempposobj; - HANDLE hFile; - - /* we save the file pointer position */ - oldposobj = portable_lseek(fd, NULL, 1); - if (oldposobj == NULL) { - Py_DECREF(posobj); - return NULL; - } - - /* we then move to the truncation position */ - tempposobj = portable_lseek(fd, posobj, 0); - if (tempposobj == NULL) { - Py_DECREF(oldposobj); - Py_DECREF(posobj); - return NULL; - } - Py_DECREF(tempposobj); - - /* Truncate. Note that this may grow the file! */ - Py_BEGIN_ALLOW_THREADS - errno = 0; - hFile = (HANDLE)_get_osfhandle(fd); - ret = hFile == (HANDLE)-1; /* testing for INVALID_HANDLE value */ - if (ret == 0) { - ret = SetEndOfFile(hFile) == 0; - if (ret) - errno = EACCES; - } - Py_END_ALLOW_THREADS - - /* we restore the file pointer position in any case */ - tempposobj = portable_lseek(fd, oldposobj, 0); - Py_DECREF(oldposobj); - if (tempposobj == NULL) { - Py_DECREF(posobj); - return NULL; - } - Py_DECREF(tempposobj); - } + /* MS _chsize doesn't work if newsize doesn't fit in 32 bits, + so don't even try using it. */ + { + PyObject *oldposobj, *tempposobj; + HANDLE hFile; + + /* we save the file pointer position */ + oldposobj = portable_lseek(fd, NULL, 1); + if (oldposobj == NULL) { + Py_DECREF(posobj); + return NULL; + } + + /* we then move to the truncation position */ + tempposobj = portable_lseek(fd, posobj, 0); + if (tempposobj == NULL) { + Py_DECREF(oldposobj); + Py_DECREF(posobj); + return NULL; + } + Py_DECREF(tempposobj); + + /* Truncate. Note that this may grow the file! */ + Py_BEGIN_ALLOW_THREADS + errno = 0; + hFile = (HANDLE)_get_osfhandle(fd); + ret = hFile == (HANDLE)-1; /* testing for INVALID_HANDLE value */ + if (ret == 0) { + ret = SetEndOfFile(hFile) == 0; + if (ret) + errno = EACCES; + } + Py_END_ALLOW_THREADS + + /* we restore the file pointer position in any case */ + tempposobj = portable_lseek(fd, oldposobj, 0); + Py_DECREF(oldposobj); + if (tempposobj == NULL) { + Py_DECREF(posobj); + return NULL; + } + Py_DECREF(tempposobj); + } #else #if defined(HAVE_LARGEFILE_SUPPORT) - pos = PyLong_AsLongLong(posobj); + pos = PyLong_AsLongLong(posobj); #else - pos = PyLong_AsLong(posobj); + pos = PyLong_AsLong(posobj); #endif - if (PyErr_Occurred()){ - Py_DECREF(posobj); - return NULL; - } - - Py_BEGIN_ALLOW_THREADS - errno = 0; - ret = ftruncate(fd, pos); - Py_END_ALLOW_THREADS + if (PyErr_Occurred()){ + Py_DECREF(posobj); + return NULL; + } + + Py_BEGIN_ALLOW_THREADS + errno = 0; + ret = ftruncate(fd, pos); + Py_END_ALLOW_THREADS #endif /* !MS_WINDOWS */ - if (ret != 0) { - Py_DECREF(posobj); - PyErr_SetFromErrno(PyExc_IOError); - return NULL; - } + if (ret != 0) { + Py_DECREF(posobj); + PyErr_SetFromErrno(PyExc_IOError); + return NULL; + } - return posobj; + return posobj; } #endif /* HAVE_FTRUNCATE */ static char * mode_string(fileio *self) { - if (self->readable) { - if (self->writable) - return "rb+"; - else - return "rb"; - } - else - return "wb"; + if (self->readable) { + if (self->writable) + return "rb+"; + else + return "rb"; + } + else + return "wb"; } static PyObject * fileio_repr(fileio *self) { - PyObject *nameobj, *res; + PyObject *nameobj, *res; - if (self->fd < 0) - return PyUnicode_FromFormat("<_io.FileIO [closed]>"); + if (self->fd < 0) + return PyUnicode_FromFormat("<_io.FileIO [closed]>"); - nameobj = PyObject_GetAttrString((PyObject *) self, "name"); - if (nameobj == NULL) { - if (PyErr_ExceptionMatches(PyExc_AttributeError)) - PyErr_Clear(); - else - return NULL; - res = PyUnicode_FromFormat("<_io.FileIO fd=%d mode='%s'>", - self->fd, mode_string(self)); - } - else { - res = PyUnicode_FromFormat("<_io.FileIO name=%R mode='%s'>", - nameobj, mode_string(self)); - Py_DECREF(nameobj); - } - return res; + nameobj = PyObject_GetAttrString((PyObject *) self, "name"); + if (nameobj == NULL) { + if (PyErr_ExceptionMatches(PyExc_AttributeError)) + PyErr_Clear(); + else + return NULL; + res = PyUnicode_FromFormat("<_io.FileIO fd=%d mode='%s'>", + self->fd, mode_string(self)); + } + else { + res = PyUnicode_FromFormat("<_io.FileIO name=%R mode='%s'>", + nameobj, mode_string(self)); + Py_DECREF(nameobj); + } + return res; } static PyObject * fileio_isatty(fileio *self) { - long res; + long res; - if (self->fd < 0) - return err_closed(); - Py_BEGIN_ALLOW_THREADS - res = isatty(self->fd); - Py_END_ALLOW_THREADS - return PyBool_FromLong(res); + if (self->fd < 0) + return err_closed(); + Py_BEGIN_ALLOW_THREADS + res = isatty(self->fd); + Py_END_ALLOW_THREADS + return PyBool_FromLong(res); } @@ -916,7 +916,7 @@ "file(name: str[, mode: str]) -> file IO object\n" "\n" "Open a file. The mode can be 'r', 'w' or 'a' for reading (default),\n" -"writing or appending. The file will be created if it doesn't exist\n" +"writing or appending. The file will be created if it doesn't exist\n" "when opened for writing or appending; it will be truncated when\n" "opened for writing. Add a '+' to the mode to allow simultaneous\n" "reading and writing."); @@ -958,14 +958,14 @@ #ifdef HAVE_FTRUNCATE PyDoc_STRVAR(truncate_doc, -"truncate([size: int]) -> None. Truncate the file to at most size bytes.\n" +"truncate([size: int]) -> None. Truncate the file to at most size bytes.\n" "\n" "Size defaults to the current file position, as returned by tell()." "The current file position is changed to the value of size."); #endif PyDoc_STRVAR(tell_doc, -"tell() -> int. Current file position"); +"tell() -> int. Current file position"); PyDoc_STRVAR(readinto_doc, "readinto() -> Same as RawIOBase.readinto()."); @@ -989,22 +989,22 @@ "writable() -> bool. True if file was opened in a write mode."); static PyMethodDef fileio_methods[] = { - {"read", (PyCFunction)fileio_read, METH_VARARGS, read_doc}, - {"readall", (PyCFunction)fileio_readall, METH_NOARGS, readall_doc}, - {"readinto", (PyCFunction)fileio_readinto, METH_VARARGS, readinto_doc}, - {"write", (PyCFunction)fileio_write, METH_VARARGS, write_doc}, - {"seek", (PyCFunction)fileio_seek, METH_VARARGS, seek_doc}, - {"tell", (PyCFunction)fileio_tell, METH_VARARGS, tell_doc}, + {"read", (PyCFunction)fileio_read, METH_VARARGS, read_doc}, + {"readall", (PyCFunction)fileio_readall, METH_NOARGS, readall_doc}, + {"readinto", (PyCFunction)fileio_readinto, METH_VARARGS, readinto_doc}, + {"write", (PyCFunction)fileio_write, METH_VARARGS, write_doc}, + {"seek", (PyCFunction)fileio_seek, METH_VARARGS, seek_doc}, + {"tell", (PyCFunction)fileio_tell, METH_VARARGS, tell_doc}, #ifdef HAVE_FTRUNCATE - {"truncate", (PyCFunction)fileio_truncate, METH_VARARGS, truncate_doc}, + {"truncate", (PyCFunction)fileio_truncate, METH_VARARGS, truncate_doc}, #endif - {"close", (PyCFunction)fileio_close, METH_NOARGS, close_doc}, - {"seekable", (PyCFunction)fileio_seekable, METH_NOARGS, seekable_doc}, - {"readable", (PyCFunction)fileio_readable, METH_NOARGS, readable_doc}, - {"writable", (PyCFunction)fileio_writable, METH_NOARGS, writable_doc}, - {"fileno", (PyCFunction)fileio_fileno, METH_NOARGS, fileno_doc}, - {"isatty", (PyCFunction)fileio_isatty, METH_NOARGS, isatty_doc}, - {NULL, NULL} /* sentinel */ + {"close", (PyCFunction)fileio_close, METH_NOARGS, close_doc}, + {"seekable", (PyCFunction)fileio_seekable, METH_NOARGS, seekable_doc}, + {"readable", (PyCFunction)fileio_readable, METH_NOARGS, readable_doc}, + {"writable", (PyCFunction)fileio_writable, METH_NOARGS, writable_doc}, + {"fileno", (PyCFunction)fileio_fileno, METH_NOARGS, fileno_doc}, + {"isatty", (PyCFunction)fileio_isatty, METH_NOARGS, isatty_doc}, + {NULL, NULL} /* sentinel */ }; /* 'closed' and 'mode' are attributes for backwards compatibility reasons. */ @@ -1012,68 +1012,68 @@ static PyObject * get_closed(fileio *self, void *closure) { - return PyBool_FromLong((long)(self->fd < 0)); + return PyBool_FromLong((long)(self->fd < 0)); } static PyObject * get_closefd(fileio *self, void *closure) { - return PyBool_FromLong((long)(self->closefd)); + return PyBool_FromLong((long)(self->closefd)); } static PyObject * get_mode(fileio *self, void *closure) { - return PyUnicode_FromString(mode_string(self)); + return PyUnicode_FromString(mode_string(self)); } static PyGetSetDef fileio_getsetlist[] = { - {"closed", (getter)get_closed, NULL, "True if the file is closed"}, - {"closefd", (getter)get_closefd, NULL, - "True if the file descriptor will be closed"}, - {"mode", (getter)get_mode, NULL, "String giving the file mode"}, - {NULL}, + {"closed", (getter)get_closed, NULL, "True if the file is closed"}, + {"closefd", (getter)get_closefd, NULL, + "True if the file descriptor will be closed"}, + {"mode", (getter)get_mode, NULL, "String giving the file mode"}, + {NULL}, }; PyTypeObject PyFileIO_Type = { - PyVarObject_HEAD_INIT(NULL, 0) - "_io.FileIO", - sizeof(fileio), - 0, - (destructor)fileio_dealloc, /* tp_dealloc */ - 0, /* tp_print */ - 0, /* tp_getattr */ - 0, /* tp_setattr */ - 0, /* tp_reserved */ - (reprfunc)fileio_repr, /* 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_BASETYPE - | Py_TPFLAGS_HAVE_GC, /* tp_flags */ - fileio_doc, /* tp_doc */ - (traverseproc)fileio_traverse, /* tp_traverse */ - (inquiry)fileio_clear, /* tp_clear */ - 0, /* tp_richcompare */ - offsetof(fileio, weakreflist), /* tp_weaklistoffset */ - 0, /* tp_iter */ - 0, /* tp_iternext */ - fileio_methods, /* tp_methods */ - 0, /* tp_members */ - fileio_getsetlist, /* tp_getset */ - 0, /* tp_base */ - 0, /* tp_dict */ - 0, /* tp_descr_get */ - 0, /* tp_descr_set */ - offsetof(fileio, dict), /* tp_dictoffset */ - fileio_init, /* tp_init */ - PyType_GenericAlloc, /* tp_alloc */ - fileio_new, /* tp_new */ - PyObject_GC_Del, /* tp_free */ + PyVarObject_HEAD_INIT(NULL, 0) + "_io.FileIO", + sizeof(fileio), + 0, + (destructor)fileio_dealloc, /* tp_dealloc */ + 0, /* tp_print */ + 0, /* tp_getattr */ + 0, /* tp_setattr */ + 0, /* tp_reserved */ + (reprfunc)fileio_repr, /* 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_BASETYPE + | Py_TPFLAGS_HAVE_GC, /* tp_flags */ + fileio_doc, /* tp_doc */ + (traverseproc)fileio_traverse, /* tp_traverse */ + (inquiry)fileio_clear, /* tp_clear */ + 0, /* tp_richcompare */ + offsetof(fileio, weakreflist), /* tp_weaklistoffset */ + 0, /* tp_iter */ + 0, /* tp_iternext */ + fileio_methods, /* tp_methods */ + 0, /* tp_members */ + fileio_getsetlist, /* tp_getset */ + 0, /* tp_base */ + 0, /* tp_dict */ + 0, /* tp_descr_get */ + 0, /* tp_descr_set */ + offsetof(fileio, dict), /* tp_dictoffset */ + fileio_init, /* tp_init */ + PyType_GenericAlloc, /* tp_alloc */ + fileio_new, /* tp_new */ + PyObject_GC_Del, /* tp_free */ }; From python-checkins at python.org Wed May 5 19:31:03 2010 From: python-checkins at python.org (r.david.murray) Date: Wed, 5 May 2010 19:31:03 +0200 (CEST) Subject: [Python-checkins] r80800 - in python/trunk/Lib/email: encoders.py test/test_email.py Message-ID: <20100505173103.818A6EEA18@mail.python.org> Author: r.david.murray Date: Wed May 5 19:31:03 2010 New Revision: 80800 Log: Issue #7472: remove unused code from email.encoders.encode_7or8bit. Yukihiro Nakadaira noticed a typo in encode_7or8bit that was trying to special case iso-2022 codecs. It turns out that the code in question is never used, because whereas it was designed to trigger if the payload encoding was eight bit but its output encoding was 7 bit, in practice the payload is always converted to the 7bit encoding before encode_7or8bit is called. Patch by Shawat Anand. Modified: python/trunk/Lib/email/encoders.py python/trunk/Lib/email/test/test_email.py Modified: python/trunk/Lib/email/encoders.py ============================================================================== --- python/trunk/Lib/email/encoders.py (original) +++ python/trunk/Lib/email/encoders.py Wed May 5 19:31:03 2010 @@ -72,13 +72,7 @@ try: orig.encode('ascii') except UnicodeError: - # iso-2022-* is non-ASCII but still 7-bit - charset = msg.get_charset() - output_cset = charset and charset.output_charset - if output_cset and output_cset.lower().startswith('iso-2022-'): - msg['Content-Transfer-Encoding'] = '7bit' - else: - msg['Content-Transfer-Encoding'] = '8bit' + msg['Content-Transfer-Encoding'] = '8bit' else: msg['Content-Transfer-Encoding'] = '7bit' Modified: python/trunk/Lib/email/test/test_email.py ============================================================================== --- python/trunk/Lib/email/test/test_email.py (original) +++ python/trunk/Lib/email/test/test_email.py Wed May 5 19:31:03 2010 @@ -564,6 +564,13 @@ msg = MIMEText('hello \xf8 world', _charset='iso-8859-1') eq(msg['content-transfer-encoding'], 'quoted-printable') + def test_encode7or8bit(self): + # Make sure a charset whose input character set is 8bit but + # whose output character set is 7bit gets a transfer-encoding + # of 7bit. + eq = self.assertEqual + msg = email.MIMEText.MIMEText('\xca\xb8', _charset='euc-jp') + eq(msg['content-transfer-encoding'], '7bit') # Test long header wrapping From python-checkins at python.org Wed May 5 19:34:36 2010 From: python-checkins at python.org (r.david.murray) Date: Wed, 5 May 2010 19:34:36 +0200 (CEST) Subject: [Python-checkins] r80801 - python/branches/release26-maint Message-ID: <20100505173436.C557BEE9C2@mail.python.org> Author: r.david.murray Date: Wed May 5 19:34:36 2010 New Revision: 80801 Log: Blocked revisions 80800 via svnmerge ........ r80800 | r.david.murray | 2010-05-05 13:31:03 -0400 (Wed, 05 May 2010) | 9 lines Issue #7472: remove unused code from email.encoders.encode_7or8bit. Yukihiro Nakadaira noticed a typo in encode_7or8bit that was trying to special case iso-2022 codecs. It turns out that the code in question is never used, because whereas it was designed to trigger if the payload encoding was eight bit but its output encoding was 7 bit, in practice the payload is always converted to the 7bit encoding before encode_7or8bit is called. Patch by Shawat Anand. ........ Modified: python/branches/release26-maint/ (props changed) From python-checkins at python.org Wed May 5 20:29:02 2010 From: python-checkins at python.org (antoine.pitrou) Date: Wed, 5 May 2010 20:29:02 +0200 (CEST) Subject: [Python-checkins] r80802 - python/trunk/Lib/test/test_gdb.py Message-ID: <20100505182902.EAAFCEE9A3@mail.python.org> Author: antoine.pitrou Date: Wed May 5 20:29:02 2010 New Revision: 80802 Log: Issue #8600: fix test_gdb failures when gdb issues some spurious warnings. Modified: python/trunk/Lib/test/test_gdb.py Modified: python/trunk/Lib/test/test_gdb.py ============================================================================== --- python/trunk/Lib/test/test_gdb.py (original) +++ python/trunk/Lib/test/test_gdb.py Wed May 5 20:29:02 2010 @@ -119,6 +119,11 @@ # Ignore some noise on stderr due to the pending breakpoint: err = err.replace('Function "%s" not defined.\n' % breakpoint, '') + # Ignore some other noise on stderr (http://bugs.python.org/issue8600) + err = err.replace("warning: Unable to find libthread_db matching" + " inferior's thread library, thread debugging will" + " not be available.\n", + '') # Ensure no unexpected error messages: self.assertEquals(err, '') From python-checkins at python.org Wed May 5 20:30:22 2010 From: python-checkins at python.org (antoine.pitrou) Date: Wed, 5 May 2010 20:30:22 +0200 (CEST) Subject: [Python-checkins] r80803 - in python/branches/py3k: Lib/test/test_gdb.py Message-ID: <20100505183022.CD87CEE9A3@mail.python.org> Author: antoine.pitrou Date: Wed May 5 20:30:22 2010 New Revision: 80803 Log: Merged revisions 80802 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r80802 | antoine.pitrou | 2010-05-05 20:29:02 +0200 (mer., 05 mai 2010) | 3 lines Issue #8600: fix test_gdb failures when gdb issues some spurious warnings. ........ Modified: python/branches/py3k/ (props changed) python/branches/py3k/Lib/test/test_gdb.py Modified: python/branches/py3k/Lib/test/test_gdb.py ============================================================================== --- python/branches/py3k/Lib/test/test_gdb.py (original) +++ python/branches/py3k/Lib/test/test_gdb.py Wed May 5 20:30:22 2010 @@ -121,6 +121,11 @@ # Ignore some noise on stderr due to the pending breakpoint: err = err.replace('Function "%s" not defined.\n' % breakpoint, '') + # Ignore some other noise on stderr (http://bugs.python.org/issue8600) + err = err.replace("warning: Unable to find libthread_db matching" + " inferior's thread library, thread debugging will" + " not be available.\n", + '') # Ensure no unexpected error messages: self.assertEquals(err, '') From python-checkins at python.org Wed May 5 21:09:31 2010 From: python-checkins at python.org (ronald.oussoren) Date: Wed, 5 May 2010 21:09:31 +0200 (CEST) Subject: [Python-checkins] r80804 - in python/trunk: Demo/pdist/FSProxy.py Doc/library/os.rst Lib/binhex.py Lib/distutils/command/install.py Lib/distutils/file_util.py Lib/distutils/sysconfig.py Lib/distutils/util.py Lib/imputil.py Lib/plat-mac/EasyDialogs.py Lib/plat-mac/bundlebuilder.py Lib/platform.py Lib/profile.py Lib/pydoc.py Lib/tarfile.py Lib/test/regrtest.py Lib/test/test_frozen.py Lib/test/test_repr.py Lib/test/test_select.py Lib/test/test_socket.py Lib/test/test_strptime.py Lib/test/test_tempfile.py Lib/test/test_urllib2.py Lib/urllib.py Mac/scripts/BuildApplet.py Mac/scripts/zappycfiles.py Misc/BeOS-setup.py Misc/cheatsheet Tools/webchecker/wcgui.py Tools/webchecker/websucker.py setup.py Message-ID: <20100505190931.888A0EE9D7@mail.python.org> Author: ronald.oussoren Date: Wed May 5 21:09:31 2010 New Revision: 80804 Log: In a number of places code still revers to "sys.platform == 'mac'" and that is dead code because it refers to a platform that is no longer supported (and hasn't been supported for several releases). Fixes issue #7908 for the trunk. Modified: python/trunk/Demo/pdist/FSProxy.py python/trunk/Doc/library/os.rst python/trunk/Lib/binhex.py python/trunk/Lib/distutils/command/install.py python/trunk/Lib/distutils/file_util.py python/trunk/Lib/distutils/sysconfig.py python/trunk/Lib/distutils/util.py python/trunk/Lib/imputil.py python/trunk/Lib/plat-mac/EasyDialogs.py python/trunk/Lib/plat-mac/bundlebuilder.py python/trunk/Lib/platform.py python/trunk/Lib/profile.py python/trunk/Lib/pydoc.py python/trunk/Lib/tarfile.py python/trunk/Lib/test/regrtest.py python/trunk/Lib/test/test_frozen.py python/trunk/Lib/test/test_repr.py python/trunk/Lib/test/test_select.py python/trunk/Lib/test/test_socket.py python/trunk/Lib/test/test_strptime.py python/trunk/Lib/test/test_tempfile.py python/trunk/Lib/test/test_urllib2.py python/trunk/Lib/urllib.py python/trunk/Mac/scripts/BuildApplet.py python/trunk/Mac/scripts/zappycfiles.py python/trunk/Misc/BeOS-setup.py python/trunk/Misc/cheatsheet python/trunk/Tools/webchecker/wcgui.py python/trunk/Tools/webchecker/websucker.py python/trunk/setup.py Modified: python/trunk/Demo/pdist/FSProxy.py ============================================================================== --- python/trunk/Demo/pdist/FSProxy.py (original) +++ python/trunk/Demo/pdist/FSProxy.py Wed May 5 21:09:31 2010 @@ -23,12 +23,7 @@ import time import fnmatch -if os.name == 'mac': - import macfs - maxnamelen = 31 -else: - macfs = None - maxnamelen = 255 +maxnamelen = 255 skipnames = (os.curdir, os.pardir) @@ -63,16 +58,10 @@ return ignore def _hidden(self, name): - if os.name == 'mac': - return name[0] == '(' and name[-1] == ')' - else: - return name[0] == '.' + return name[0] == '.' def _hide(self, name): - if os.name == 'mac': - return '(%s)' % name - else: - return '.%s' % name + return '.%s' % name def visible(self, name): if len(name) > maxnamelen: return 0 @@ -81,18 +70,8 @@ if self._hidden(name): return 0 head, tail = os.path.split(name) if head or not tail: return 0 - if macfs: - if os.path.exists(name) and not os.path.isdir(name): - try: - fs = macfs.FSSpec(name) - c, t = fs.GetCreatorType() - if t != 'TEXT': return 0 - except macfs.error, msg: - print "***", name, msg - return 0 - else: - if os.path.islink(name): return 0 - if '\0' in open(name, 'rb').read(512): return 0 + if os.path.islink(name): return 0 + if '\0' in open(name, 'rb').read(512): return 0 for ign in self._ignore: if fnmatch.fnmatch(name, ign): return 0 return 1 Modified: python/trunk/Doc/library/os.rst ============================================================================== --- python/trunk/Doc/library/os.rst (original) +++ python/trunk/Doc/library/os.rst Wed May 5 21:09:31 2010 @@ -47,7 +47,7 @@ .. data:: name The name of the operating system dependent module imported. The following - names have currently been registered: ``'posix'``, ``'nt'``, ``'mac'``, + names have currently been registered: ``'posix'``, ``'nt'``, ``'os2'``, ``'ce'``, ``'java'``, ``'riscos'``. Modified: python/trunk/Lib/binhex.py ============================================================================== --- python/trunk/Lib/binhex.py (original) +++ python/trunk/Lib/binhex.py Wed May 5 21:09:31 2010 @@ -175,9 +175,6 @@ if type(ofp) == type(''): ofname = ofp ofp = open(ofname, 'w') - if os.name == 'mac': - fss = FSSpec(ofname) - fss.SetCreatorType('BnHq', 'TEXT') ofp.write('(This file must be converted with BinHex 4.0)\n\n:') hqxer = _Hqxcoderengine(ofp) self.ofp = _Rlecoderengine(hqxer) @@ -478,9 +475,6 @@ finfo = ifp.FInfo if not out: out = ifp.FName - if os.name == 'mac': - ofss = FSSpec(out) - out = ofss.as_pathname() ofp = open(out, 'wb') # XXXX Do translation on non-mac systems @@ -501,13 +495,6 @@ ofp.write(d) ofp.close() - if os.name == 'mac': - nfinfo = ofss.GetFInfo() - nfinfo.Creator = finfo.Creator - nfinfo.Type = finfo.Type - nfinfo.Flags = finfo.Flags - ofss.SetFInfo(nfinfo) - ifp.close() def _test(): Modified: python/trunk/Lib/distutils/command/install.py ============================================================================== --- python/trunk/Lib/distutils/command/install.py (original) +++ python/trunk/Lib/distutils/command/install.py Wed May 5 21:09:31 2010 @@ -69,20 +69,6 @@ 'scripts': '$userbase/Scripts', 'data' : '$userbase', }, - 'mac': { - 'purelib': '$base/Lib/site-packages', - 'platlib': '$base/Lib/site-packages', - 'headers': '$base/Include/$dist_name', - 'scripts': '$base/Scripts', - 'data' : '$base', - }, - 'mac_user': { - 'purelib': '$usersite', - 'platlib': '$usersite', - 'headers': '$userbase/$py_version_short/include/$dist_name', - 'scripts': '$userbase/bin', - 'data' : '$userbase', - }, 'os2': { 'purelib': '$base/Lib/site-packages', 'platlib': '$base/Lib/site-packages', Modified: python/trunk/Lib/distutils/file_util.py ============================================================================== --- python/trunk/Lib/distutils/file_util.py (original) +++ python/trunk/Lib/distutils/file_util.py Wed May 5 21:09:31 2010 @@ -133,18 +133,9 @@ if dry_run: return (dst, 1) - # On Mac OS, use the native file copy routine - if os.name == 'mac': - import macostools - try: - macostools.copy(src, dst, 0, preserve_times) - except os.error, exc: - raise DistutilsFileError( - "could not copy '%s' to '%s': %s" % (src, dst, exc[-1])) - # If linking (hard or symbolic), use the appropriate system call # (Unix only, of course, but that's the caller's responsibility) - elif link == 'hard': + if link == 'hard': if not (os.path.exists(dst) and os.path.samefile(src, dst)): os.link(src, dst) elif link == 'sym': Modified: python/trunk/Lib/distutils/sysconfig.py ============================================================================== --- python/trunk/Lib/distutils/sysconfig.py (original) +++ python/trunk/Lib/distutils/sysconfig.py Wed May 5 21:09:31 2010 @@ -88,11 +88,6 @@ return os.path.join(prefix, "include", "python" + get_python_version()) elif os.name == "nt": return os.path.join(prefix, "include") - elif os.name == "mac": - if plat_specific: - return os.path.join(prefix, "Mac", "Include") - else: - return os.path.join(prefix, "Include") elif os.name == "os2": return os.path.join(prefix, "Include") else: @@ -135,18 +130,6 @@ else: return os.path.join(prefix, "Lib", "site-packages") - elif os.name == "mac": - if plat_specific: - if standard_lib: - return os.path.join(prefix, "Lib", "lib-dynload") - else: - return os.path.join(prefix, "Lib", "site-packages") - else: - if standard_lib: - return os.path.join(prefix, "Lib") - else: - return os.path.join(prefix, "Lib", "site-packages") - elif os.name == "os2": if standard_lib: return os.path.join(prefix, "Lib") Modified: python/trunk/Lib/distutils/util.py ============================================================================== --- python/trunk/Lib/distutils/util.py (original) +++ python/trunk/Lib/distutils/util.py Wed May 5 21:09:31 2010 @@ -235,15 +235,6 @@ path = path[1:] return os.path.join(new_root, path) - elif os.name == 'mac': - if not os.path.isabs(pathname): - return os.path.join(new_root, pathname) - else: - # Chop off volume name from start of path - elements = string.split(pathname, ":", 1) - pathname = ":" + elements[1] - return os.path.join(new_root, pathname) - else: raise DistutilsPlatformError, \ "nothing known about platform '%s'" % os.name Modified: python/trunk/Lib/imputil.py ============================================================================== --- python/trunk/Lib/imputil.py (original) +++ python/trunk/Lib/imputil.py Wed May 5 21:09:31 2010 @@ -462,16 +462,6 @@ elif 'os2' in names: sep = '\\' from os2 import stat - elif 'mac' in names: - from mac import stat - def join(a, b): - if a == '': - return b - if ':' not in a: - a = ':' + a - if a[-1:] != ':': - a = a + ':' - return a + b else: raise ImportError, 'no os specific module found' Modified: python/trunk/Lib/plat-mac/EasyDialogs.py ============================================================================== --- python/trunk/Lib/plat-mac/EasyDialogs.py (original) +++ python/trunk/Lib/plat-mac/EasyDialogs.py Wed May 5 21:09:31 2010 @@ -721,16 +721,13 @@ if issubclass(tpwanted, Carbon.File.FSSpec): return tpwanted(rr.selection[0]) if issubclass(tpwanted, (str, unicode)): - if sys.platform == 'mac': - fullpath = rr.selection[0].as_pathname() - else: - # This is gross, and probably incorrect too - vrefnum, dirid, name = rr.selection[0].as_tuple() - pardir_fss = Carbon.File.FSSpec((vrefnum, dirid, '')) - pardir_fsr = Carbon.File.FSRef(pardir_fss) - pardir_path = pardir_fsr.FSRefMakePath() # This is utf-8 - name_utf8 = unicode(name, 'macroman').encode('utf8') - fullpath = os.path.join(pardir_path, name_utf8) + # This is gross, and probably incorrect too + vrefnum, dirid, name = rr.selection[0].as_tuple() + pardir_fss = Carbon.File.FSSpec((vrefnum, dirid, '')) + pardir_fsr = Carbon.File.FSRef(pardir_fss) + pardir_path = pardir_fsr.FSRefMakePath() # This is utf-8 + name_utf8 = unicode(name, 'macroman').encode('utf8') + fullpath = os.path.join(pardir_path, name_utf8) if issubclass(tpwanted, unicode): return unicode(fullpath, 'utf8') return tpwanted(fullpath) Modified: python/trunk/Lib/plat-mac/bundlebuilder.py ============================================================================== --- python/trunk/Lib/plat-mac/bundlebuilder.py (original) +++ python/trunk/Lib/plat-mac/bundlebuilder.py Wed May 5 21:09:31 2010 @@ -273,7 +273,7 @@ del __load """ -MAYMISS_MODULES = ['mac', 'os2', 'nt', 'ntpath', 'dos', 'dospath', +MAYMISS_MODULES = ['os2', 'nt', 'ntpath', 'dos', 'dospath', 'win32api', 'ce', '_winreg', 'nturl2path', 'sitecustomize', 'org.python.core', 'riscos', 'riscosenviron', 'riscospath' ] Modified: python/trunk/Lib/platform.py ============================================================================== --- python/trunk/Lib/platform.py (original) +++ python/trunk/Lib/platform.py Wed May 5 21:09:31 2010 @@ -1171,10 +1171,6 @@ if not version: version = vendor - elif os.name == 'mac': - release,(version,stage,nonrel),machine = mac_ver() - system = 'MacOS' - # System specific extensions if system == 'OpenVMS': # OpenVMS seems to have release and version mixed up Modified: python/trunk/Lib/profile.py ============================================================================== --- python/trunk/Lib/profile.py (original) +++ python/trunk/Lib/profile.py Wed May 5 21:09:31 2010 @@ -97,11 +97,6 @@ print "Documentation for the profile module can be found " print "in the Python Library Reference, section 'The Python Profiler'." -if os.name == "mac": - import MacOS - def _get_time_mac(timer=MacOS.GetTicks): - return timer() / 60.0 - if hasattr(os, "times"): def _get_time_times(timer=os.times): t = timer() @@ -178,10 +173,6 @@ self.timer = resgetrusage self.dispatcher = self.trace_dispatch self.get_time = _get_time_resource - elif os.name == 'mac': - self.timer = MacOS.GetTicks - self.dispatcher = self.trace_dispatch_mac - self.get_time = _get_time_mac elif hasattr(time, 'clock'): self.timer = self.get_time = time.clock self.dispatcher = self.trace_dispatch_i Modified: python/trunk/Lib/pydoc.py ============================================================================== --- python/trunk/Lib/pydoc.py (original) +++ python/trunk/Lib/pydoc.py Wed May 5 21:09:31 2010 @@ -2028,7 +2028,7 @@ class DocServer(BaseHTTPServer.HTTPServer): def __init__(self, port, callback): - host = (sys.platform == 'mac') and '127.0.0.1' or 'localhost' + host = 'localhost' self.address = ('', port) self.url = 'http://%s:%d/' % (host, port) self.callback = callback @@ -2145,10 +2145,6 @@ except ImportError: # pre-webbrowser.py compatibility if sys.platform == 'win32': os.system('start "%s"' % url) - elif sys.platform == 'mac': - try: import ic - except ImportError: pass - else: ic.launchurl(url) else: rc = os.system('netscape -remote "openURL(%s)" &' % url) if rc: os.system('netscape "%s" &' % url) Modified: python/trunk/Lib/tarfile.py ============================================================================== --- python/trunk/Lib/tarfile.py (original) +++ python/trunk/Lib/tarfile.py Wed May 5 21:09:31 2010 @@ -53,13 +53,6 @@ import re import operator -if sys.platform == 'mac': - # This module needs work for MacOS9, especially in the area of pathname - # handling. In many places it is assumed a simple substitution of / by the - # local os.path.sep is good enough to convert pathnames, but this does not - # work with the mac rooted:path:name versus :nonrooted:path:name syntax - raise ImportError, "tarfile does not work for platform==mac" - try: import grp, pwd except ImportError: Modified: python/trunk/Lib/test/regrtest.py ============================================================================== --- python/trunk/Lib/test/regrtest.py (original) +++ python/trunk/Lib/test/regrtest.py Wed May 5 21:09:31 2010 @@ -1156,41 +1156,6 @@ test_kqueue test_ossaudiodev """, - 'mac': - """ - test_atexit - test_bsddb - test_bsddb185 - test_bsddb3 - test_bz2 - test_commands - test_crypt - test_curses - test_dbm - test_dl - test_fcntl - test_fork1 - test_epoll - test_grp - test_ioctl - test_largefile - test_locale - test_kqueue - test_mmap - test_openpty - test_ossaudiodev - test_poll - test_popen - test_popen2 - test_posix - test_pty - test_pwd - test_resource - test_signal - test_sundry - test_tarfile - test_timing - """, 'unixware7': """ test_bsddb @@ -1477,7 +1442,7 @@ if sys.maxint == 9223372036854775807L: self.expected.add('test_imageop') - if not sys.platform in ("mac", "darwin"): + if sys.platform != "darwin": MAC_ONLY = ["test_macos", "test_macostools", "test_aepack", "test_plistlib", "test_scriptpackages", "test_applesingle"] Modified: python/trunk/Lib/test/test_frozen.py ============================================================================== --- python/trunk/Lib/test/test_frozen.py (original) +++ python/trunk/Lib/test/test_frozen.py Wed May 5 21:09:31 2010 @@ -23,13 +23,12 @@ except ImportError, x: self.fail("import __phello__.spam failed:" + str(x)) - if sys.platform != "mac": # On the Mac this import does succeed. - try: - import __phello__.foo - except ImportError: - pass - else: - self.fail("import __phello__.foo should have failed") + try: + import __phello__.foo + except ImportError: + pass + else: + self.fail("import __phello__.foo should have failed") self.assertEquals(stdout.getvalue(), 'Hello world...\nHello world...\nHello world...\n') Modified: python/trunk/Lib/test/test_repr.py ============================================================================== --- python/trunk/Lib/test/test_repr.py (original) +++ python/trunk/Lib/test/test_repr.py Wed May 5 21:09:31 2010 @@ -320,8 +320,7 @@ def test_main(): run_unittest(ReprTests) - if os.name != 'mac': - run_unittest(LongReprTest) + run_unittest(LongReprTest) if __name__ == "__main__": Modified: python/trunk/Lib/test/test_select.py ============================================================================== --- python/trunk/Lib/test/test_select.py (original) +++ python/trunk/Lib/test/test_select.py Wed May 5 21:09:31 2010 @@ -4,7 +4,7 @@ import os import sys - at unittest.skipIf(sys.platform[:3] in ('win', 'mac', 'os2', 'riscos'), + at unittest.skipIf(sys.platform[:3] in ('win', 'os2', 'riscos'), "can't easily test on this system") class SelectTestCase(unittest.TestCase): Modified: python/trunk/Lib/test/test_socket.py ============================================================================== --- python/trunk/Lib/test/test_socket.py (original) +++ python/trunk/Lib/test/test_socket.py Wed May 5 21:09:31 2010 @@ -1383,9 +1383,8 @@ def test_main(): tests = [GeneralModuleTests, BasicTCPTest, TCPCloserTest, TCPTimeoutTest, - TestExceptions, BufferIOTest, BasicTCPTest2] - if sys.platform != 'mac': - tests.extend([ BasicUDPTest, UDPTimeoutTest ]) + TestExceptions, BufferIOTest, BasicTCPTest2, BasicUDPTest, + UDPTimeoutTest ] tests.extend([ NonBlockingTCPTests, Modified: python/trunk/Lib/test/test_strptime.py ============================================================================== --- python/trunk/Lib/test/test_strptime.py (original) +++ python/trunk/Lib/test/test_strptime.py Wed May 5 21:09:31 2010 @@ -298,9 +298,6 @@ self.assertEqual(strp_output.tm_isdst, 0) strp_output = _strptime._strptime_time("GMT", "%Z") self.assertEqual(strp_output.tm_isdst, 0) - if sys.platform == "mac": - # Timezones don't really work on MacOS9 - return time_tuple = time.localtime() strf_output = time.strftime("%Z") #UTC does not have a timezone strp_output = _strptime._strptime_time(strf_output, "%Z") @@ -317,8 +314,6 @@ def test_bad_timezone(self): # Explicitly test possibility of bad timezone; # when time.tzname[0] == time.tzname[1] and time.daylight - if sys.platform == "mac": - return #MacOS9 has severely broken timezone support. tz_name = time.tzname[0] if tz_name.upper() in ("UTC", "GMT"): return Modified: python/trunk/Lib/test/test_tempfile.py ============================================================================== --- python/trunk/Lib/test/test_tempfile.py (original) +++ python/trunk/Lib/test/test_tempfile.py Wed May 5 21:09:31 2010 @@ -23,9 +23,7 @@ # TEST_FILES may need to be tweaked for systems depending on the maximum # number of files that can be opened at one time (see ulimit -n) -if sys.platform == 'mac': - TEST_FILES = 32 -elif sys.platform in ('openbsd3', 'openbsd4'): +if sys.platform in ('openbsd3', 'openbsd4'): TEST_FILES = 48 else: TEST_FILES = 100 @@ -257,7 +255,7 @@ file = self.do_create() mode = stat.S_IMODE(os.stat(file.name).st_mode) expected = 0600 - if sys.platform in ('win32', 'os2emx', 'mac'): + if sys.platform in ('win32', 'os2emx'): # There's no distinction among 'user', 'group' and 'world'; # replicate the 'user' bits. user = expected >> 6 @@ -476,7 +474,7 @@ mode = stat.S_IMODE(os.stat(dir).st_mode) mode &= 0777 # Mask off sticky bits inherited from /tmp expected = 0700 - if sys.platform in ('win32', 'os2emx', 'mac'): + if sys.platform in ('win32', 'os2emx'): # There's no distinction among 'user', 'group' and 'world'; # replicate the 'user' bits. user = expected >> 6 Modified: python/trunk/Lib/test/test_urllib2.py ============================================================================== --- python/trunk/Lib/test/test_urllib2.py (original) +++ python/trunk/Lib/test/test_urllib2.py Wed May 5 21:09:31 2010 @@ -24,9 +24,7 @@ # And more hacking to get it to work on MacOS. This assumes # urllib.pathname2url works, unfortunately... - if os.name == 'mac': - fname = '/' + fname.replace(':', '/') - elif os.name == 'riscos': + if os.name == 'riscos': import string fname = os.expand(fname) fname = fname.translate(string.maketrans("/.", "./")) Modified: python/trunk/Lib/urllib.py ============================================================================== --- python/trunk/Lib/urllib.py (original) +++ python/trunk/Lib/urllib.py Wed May 5 21:09:31 2010 @@ -42,9 +42,7 @@ MAXFTPCACHE = 10 # Trim the ftp cache beyond this size # Helper for non-unix systems -if os.name == 'mac': - from macurl2path import url2pathname, pathname2url -elif os.name == 'nt': +if os.name == 'nt': from nturl2path import url2pathname, pathname2url elif os.name == 'riscos': from rourl2path import url2pathname, pathname2url Modified: python/trunk/Mac/scripts/BuildApplet.py ============================================================================== --- python/trunk/Mac/scripts/BuildApplet.py (original) +++ python/trunk/Mac/scripts/BuildApplet.py Wed May 5 21:09:31 2010 @@ -112,9 +112,6 @@ usage() elif opt in ('-d', '--destroot'): destroot = arg - # On OS9 always be verbose - if sys.platform == 'mac' and not verbose: - verbose = 'default' # Loop over all files to be processed for filename in args: cr, tp = MacOS.GetCreatorAndType(filename) Modified: python/trunk/Mac/scripts/zappycfiles.py ============================================================================== --- python/trunk/Mac/scripts/zappycfiles.py (original) +++ python/trunk/Mac/scripts/zappycfiles.py Wed May 5 21:09:31 2010 @@ -9,15 +9,8 @@ def main(): if not sys.argv[1:]: - if os.name == 'mac': - import EasyDialogs - dir = EasyDialogs.AskFolder(message='Directory to zap pyc files in') - if not dir: - sys.exit(0) - zappyc(dir) - else: - print 'Usage: zappyc dir ...' - sys.exit(1) + print 'Usage: zappyc dir ...' + sys.exit(1) for dir in sys.argv[1:]: zappyc(dir) Modified: python/trunk/Misc/BeOS-setup.py ============================================================================== --- python/trunk/Misc/BeOS-setup.py (original) +++ python/trunk/Misc/BeOS-setup.py Wed May 5 21:09:31 2010 @@ -356,7 +356,7 @@ libraries = dblib) ) # Unix-only modules - if platform not in ['mac', 'win32']: + if platform == 'win32': # Steen Lumholt's termios module exts.append( Extension('termios', ['termios.c']) ) # Jeremy Hylton's rlimit interface Modified: python/trunk/Misc/cheatsheet ============================================================================== --- python/trunk/Misc/cheatsheet (original) +++ python/trunk/Misc/cheatsheet Wed May 5 21:09:31 2010 @@ -1390,7 +1390,7 @@ Some os variables Variable Meaning -name name of O/S-specific module (e.g. "posix", "mac", "nt") +name name of O/S-specific module (e.g. "posix", "nt") path O/S-specific module for path manipulations. On Unix, os.path.split() <=> posixpath.split() curdir string used to represent current directory ('.') Modified: python/trunk/Tools/webchecker/wcgui.py ============================================================================== --- python/trunk/Tools/webchecker/wcgui.py (original) +++ python/trunk/Tools/webchecker/wcgui.py Wed May 5 21:09:31 2010 @@ -64,12 +64,6 @@ import tktools import webchecker -# Override some for a weaker platform -if sys.platform == 'mac': - webchecker.DEFROOT = "http://grail.cnri.reston.va.us/" - webchecker.MAXPAGE = 50000 - webchecker.verbose = 4 - def main(): try: opts, args = getopt.getopt(sys.argv[1:], 't:m:qva') Modified: python/trunk/Tools/webchecker/websucker.py ============================================================================== --- python/trunk/Tools/webchecker/websucker.py (original) +++ python/trunk/Tools/webchecker/websucker.py Wed May 5 21:09:31 2010 @@ -97,8 +97,6 @@ path = path + "index.html" if os.sep != "/": path = os.sep.join(path.split("/")) - if os.name == "mac": - path = os.sep + path path = os.path.join(host, path) return path Modified: python/trunk/setup.py ============================================================================== --- python/trunk/setup.py (original) +++ python/trunk/setup.py Wed May 5 21:09:31 2010 @@ -127,7 +127,7 @@ # Platform-dependent module source and include directories incdirlist = [] platform = self.get_platform() - if platform in ('darwin', 'mac') and ("--disable-toolbox-glue" not in + if platform == 'darwin' and ("--disable-toolbox-glue" not in sysconfig.get_config_var("CONFIG_ARGS")): # Mac OS X also includes some mac-specific modules macmoddir = os.path.join(srcdir, 'Mac/Modules') @@ -160,22 +160,21 @@ if ext.name in sys.builtin_module_names: self.extensions.remove(ext) - if platform != 'mac': - # Parse Modules/Setup and Modules/Setup.local to figure out which - # modules are turned on in the file. - remove_modules = [] - for filename in ('Modules/Setup', 'Modules/Setup.local'): - input = text_file.TextFile(filename, join_lines=1) - while 1: - line = input.readline() - if not line: break - line = line.split() - remove_modules.append(line[0]) - input.close() - - for ext in self.extensions[:]: - if ext.name in remove_modules: - self.extensions.remove(ext) + # Parse Modules/Setup and Modules/Setup.local to figure out which + # modules are turned on in the file. + remove_modules = [] + for filename in ('Modules/Setup', 'Modules/Setup.local'): + input = text_file.TextFile(filename, join_lines=1) + while 1: + line = input.readline() + if not line: break + line = line.split() + remove_modules.append(line[0]) + input.close() + + for ext in self.extensions[:]: + if ext.name in remove_modules: + self.extensions.remove(ext) # When you run "make CC=altcc" or something similar, you really want # those environment variables passed into the setup.py phase. Here's @@ -397,7 +396,7 @@ # Check for MacOS X, which doesn't need libm.a at all math_libs = ['m'] - if platform in ['darwin', 'beos', 'mac']: + if platform in ['darwin', 'beos']: math_libs = [] # XXX Omitted modules: gl, pure, dl, SGI-specific modules @@ -485,19 +484,16 @@ # fcntl(2) and ioctl(2) exts.append( Extension('fcntl', ['fcntlmodule.c']) ) - if platform not in ['mac']: - # pwd(3) - exts.append( Extension('pwd', ['pwdmodule.c']) ) - # grp(3) - exts.append( Extension('grp', ['grpmodule.c']) ) - # spwd, shadow passwords - if (config_h_vars.get('HAVE_GETSPNAM', False) or - config_h_vars.get('HAVE_GETSPENT', False)): - exts.append( Extension('spwd', ['spwdmodule.c']) ) - else: - missing.append('spwd') + # pwd(3) + exts.append( Extension('pwd', ['pwdmodule.c']) ) + # grp(3) + exts.append( Extension('grp', ['grpmodule.c']) ) + # spwd, shadow passwords + if (config_h_vars.get('HAVE_GETSPNAM', False) or + config_h_vars.get('HAVE_GETSPENT', False)): + exts.append( Extension('spwd', ['spwdmodule.c']) ) else: - missing.extend(['pwd', 'grp', 'spwd']) + missing.append('spwd') # select(2); not on ancient System V exts.append( Extension('select', ['selectmodule.c']) ) @@ -510,17 +506,14 @@ exts.append( Extension('cPickle', ['cPickle.c']) ) # Memory-mapped files (also works on Win32). - if platform not in ['atheos', 'mac']: + if platform not in ['atheos']: exts.append( Extension('mmap', ['mmapmodule.c']) ) else: missing.append('mmap') # Lance Ellinghaus's syslog module - if platform not in ['mac']: - # syslog daemon interface - exts.append( Extension('syslog', ['syslogmodule.c']) ) - else: - missing.append('syslog') + # syslog daemon interface + exts.append( Extension('syslog', ['syslogmodule.c']) ) # George Neville-Neil's timing module: # Deprecated in PEP 4 http://www.python.org/peps/pep-0004.html @@ -592,16 +585,13 @@ else: missing.append('readline') - if platform not in ['mac']: - # crypt module. + # crypt module. - if self.compiler.find_library_file(lib_dirs, 'crypt'): - libs = ['crypt'] - else: - libs = [] - exts.append( Extension('crypt', ['cryptmodule.c'], libraries=libs) ) + if self.compiler.find_library_file(lib_dirs, 'crypt'): + libs = ['crypt'] else: - missing.append('crypt') + libs = [] + exts.append( Extension('crypt', ['cryptmodule.c'], libraries=libs) ) # CSV files exts.append( Extension('_csv', ['_csv.c']) ) @@ -1093,7 +1083,7 @@ missing.append('gdbm') # Unix-only modules - if platform not in ['mac', 'win32']: + if platform not in ['win32']: # Steen Lumholt's termios module exts.append( Extension('termios', ['termios.c']) ) # Jeremy Hylton's rlimit interface From python-checkins at python.org Wed May 5 21:11:21 2010 From: python-checkins at python.org (ronald.oussoren) Date: Wed, 5 May 2010 21:11:21 +0200 (CEST) Subject: [Python-checkins] r80805 - in python/branches/py3k: Demo/pdist/FSProxy.py Lib/distutils/command/install.py Lib/distutils/file_util.py Lib/distutils/util.py Lib/platform.py Lib/profile.py Lib/pydoc.py Lib/tarfile.py Lib/test/regrtest.py Lib/test/test_frozen.py Lib/test/test_reprlib.py Lib/test/test_select.py Lib/test/test_socket.py Lib/test/test_strptime.py Lib/test/test_tempfile.py Lib/test/test_urllib2.py Lib/urllib/request.py Tools/webchecker/wcgui.py Tools/webchecker/websucker.py setup.py Message-ID: <20100505191121.CF7D9EEA1E@mail.python.org> Author: ronald.oussoren Date: Wed May 5 21:11:21 2010 New Revision: 80805 Log: Remove traces of MacOS9 support. Fix for issue #7908 Modified: python/branches/py3k/Demo/pdist/FSProxy.py python/branches/py3k/Lib/distutils/command/install.py python/branches/py3k/Lib/distutils/file_util.py python/branches/py3k/Lib/distutils/util.py python/branches/py3k/Lib/platform.py python/branches/py3k/Lib/profile.py python/branches/py3k/Lib/pydoc.py python/branches/py3k/Lib/tarfile.py python/branches/py3k/Lib/test/regrtest.py python/branches/py3k/Lib/test/test_frozen.py python/branches/py3k/Lib/test/test_reprlib.py python/branches/py3k/Lib/test/test_select.py python/branches/py3k/Lib/test/test_socket.py python/branches/py3k/Lib/test/test_strptime.py python/branches/py3k/Lib/test/test_tempfile.py python/branches/py3k/Lib/test/test_urllib2.py python/branches/py3k/Lib/urllib/request.py python/branches/py3k/Tools/webchecker/wcgui.py python/branches/py3k/Tools/webchecker/websucker.py python/branches/py3k/setup.py Modified: python/branches/py3k/Demo/pdist/FSProxy.py ============================================================================== --- python/branches/py3k/Demo/pdist/FSProxy.py (original) +++ python/branches/py3k/Demo/pdist/FSProxy.py Wed May 5 21:11:21 2010 @@ -23,12 +23,7 @@ import time import fnmatch -if os.name == 'mac': - import macfs - maxnamelen = 31 -else: - macfs = None - maxnamelen = 255 +maxnamelen = 255 skipnames = (os.curdir, os.pardir) @@ -63,16 +58,10 @@ return ignore def _hidden(self, name): - if os.name == 'mac': - return name[0] == '(' and name[-1] == ')' - else: - return name[0] == '.' + return name[0] == '.' def _hide(self, name): - if os.name == 'mac': - return '(%s)' % name - else: - return '.%s' % name + return '.%s' % name def visible(self, name): if len(name) > maxnamelen: return 0 @@ -81,18 +70,8 @@ if self._hidden(name): return 0 head, tail = os.path.split(name) if head or not tail: return 0 - if macfs: - if os.path.exists(name) and not os.path.isdir(name): - try: - fs = macfs.FSSpec(name) - c, t = fs.GetCreatorType() - if t != 'TEXT': return 0 - except macfs.error as msg: - print("***", name, msg) - return 0 - else: - if os.path.islink(name): return 0 - if '\0' in open(name, 'rb').read(512): return 0 + if os.path.islink(name): return 0 + if '\0' in open(name, 'rb').read(512): return 0 for ign in self._ignore: if fnmatch.fnmatch(name, ign): return 0 return 1 Modified: python/branches/py3k/Lib/distutils/command/install.py ============================================================================== --- python/branches/py3k/Lib/distutils/command/install.py (original) +++ python/branches/py3k/Lib/distutils/command/install.py Wed May 5 21:11:21 2010 @@ -65,20 +65,6 @@ 'scripts': '$userbase/Scripts', 'data' : '$userbase', }, - 'mac': { - 'purelib': '$base/Lib/site-packages', - 'platlib': '$base/Lib/site-packages', - 'headers': '$base/Include/$dist_name', - 'scripts': '$base/Scripts', - 'data' : '$base', - }, - 'mac_user': { - 'purelib': '$usersite', - 'platlib': '$usersite', - 'headers': '$userbase/$py_version_short/include/$dist_name', - 'scripts': '$userbase/bin', - 'data' : '$userbase', - }, 'os2': { 'purelib': '$base/Lib/site-packages', 'platlib': '$base/Lib/site-packages', Modified: python/branches/py3k/Lib/distutils/file_util.py ============================================================================== --- python/branches/py3k/Lib/distutils/file_util.py (original) +++ python/branches/py3k/Lib/distutils/file_util.py Wed May 5 21:11:21 2010 @@ -132,15 +132,6 @@ if dry_run: return (dst, 1) - # On Mac OS, use the native file copy routine - if os.name == 'mac': - import macostools - try: - macostools.copy(src, dst, 0, preserve_times) - except os.error as exc: - raise DistutilsFileError( - "could not copy '%s' to '%s': %s" % (src, dst, exc.args[-1])) - # If linking (hard or symbolic), use the appropriate system call # (Unix only, of course, but that's the caller's responsibility) elif link == 'hard': Modified: python/branches/py3k/Lib/distutils/util.py ============================================================================== --- python/branches/py3k/Lib/distutils/util.py (original) +++ python/branches/py3k/Lib/distutils/util.py Wed May 5 21:11:21 2010 @@ -91,15 +91,6 @@ path = path[1:] return os.path.join(new_root, path) - elif os.name == 'mac': - if not os.path.isabs(pathname): - return os.path.join(new_root, pathname) - else: - # Chop off volume name from start of path - elements = pathname.split(":", 1) - pathname = ":" + elements[1] - return os.path.join(new_root, pathname) - else: raise DistutilsPlatformError("nothing known about " "platform '%s'" % os.name) Modified: python/branches/py3k/Lib/platform.py ============================================================================== --- python/branches/py3k/Lib/platform.py (original) +++ python/branches/py3k/Lib/platform.py Wed May 5 21:11:21 2010 @@ -1147,10 +1147,6 @@ if not version: version = vendor - elif os.name == 'mac': - release,(version,stage,nonrel),machine = mac_ver() - system = 'MacOS' - # System specific extensions if system == 'OpenVMS': # OpenVMS seems to have release and version mixed up Modified: python/branches/py3k/Lib/profile.py ============================================================================== --- python/branches/py3k/Lib/profile.py (original) +++ python/branches/py3k/Lib/profile.py Wed May 5 21:11:21 2010 @@ -92,11 +92,6 @@ else: return prof.print_stats() -if os.name == "mac": - import MacOS - def _get_time_mac(timer=MacOS.GetTicks): - return timer() / 60.0 - if hasattr(os, "times"): def _get_time_times(timer=os.times): t = timer() @@ -173,10 +168,6 @@ self.timer = resgetrusage self.dispatcher = self.trace_dispatch self.get_time = _get_time_resource - elif os.name == 'mac': - self.timer = MacOS.GetTicks - self.dispatcher = self.trace_dispatch_mac - self.get_time = _get_time_mac elif hasattr(time, 'clock'): self.timer = self.get_time = time.clock self.dispatcher = self.trace_dispatch_i Modified: python/branches/py3k/Lib/pydoc.py ============================================================================== --- python/branches/py3k/Lib/pydoc.py (original) +++ python/branches/py3k/Lib/pydoc.py Wed May 5 21:11:21 2010 @@ -2024,7 +2024,7 @@ class DocServer(http.server.HTTPServer): def __init__(self, port, callback): - host = (sys.platform == 'mac') and '127.0.0.1' or 'localhost' + host = 'localhost' self.address = ('', port) self.url = 'http://%s:%d/' % (host, port) self.callback = callback @@ -2141,10 +2141,6 @@ except ImportError: # pre-webbrowser.py compatibility if sys.platform == 'win32': os.system('start "%s"' % url) - elif sys.platform == 'mac': - try: import ic - except ImportError: pass - else: ic.launchurl(url) else: rc = os.system('netscape -remote "openURL(%s)" &' % url) if rc: os.system('netscape "%s" &' % url) Modified: python/branches/py3k/Lib/tarfile.py ============================================================================== --- python/branches/py3k/Lib/tarfile.py (original) +++ python/branches/py3k/Lib/tarfile.py Wed May 5 21:11:21 2010 @@ -50,13 +50,6 @@ import copy import re -if sys.platform == 'mac': - # This module needs work for MacOS9, especially in the area of pathname - # handling. In many places it is assumed a simple substitution of / by the - # local os.path.sep is good enough to convert pathnames, but this does not - # work with the mac rooted:path:name versus :nonrooted:path:name syntax - raise ImportError("tarfile does not work for platform==mac") - try: import grp, pwd except ImportError: Modified: python/branches/py3k/Lib/test/regrtest.py ============================================================================== --- python/branches/py3k/Lib/test/regrtest.py (original) +++ python/branches/py3k/Lib/test/regrtest.py Wed May 5 21:11:21 2010 @@ -1209,34 +1209,6 @@ test_kqueue test_ossaudiodev """, - 'mac': - """ - test_atexit - test_bz2 - test_crypt - test_curses - test_dbm - test_fcntl - test_fork1 - test_epoll - test_grp - test_ioctl - test_largefile - test_locale - test_kqueue - test_mmap - test_openpty - test_ossaudiodev - test_poll - test_popen - test_posix - test_pty - test_pwd - test_resource - test_signal - test_sundry - test_tarfile - """, 'unixware7': """ test_epoll Modified: python/branches/py3k/Lib/test/test_frozen.py ============================================================================== --- python/branches/py3k/Lib/test/test_frozen.py (original) +++ python/branches/py3k/Lib/test/test_frozen.py Wed May 5 21:11:21 2010 @@ -39,13 +39,12 @@ else: self.fail("import __phello__.foo should have failed") - if sys.platform != "mac": # On the Mac this import does succeed. - try: - import __phello__.foo - except ImportError: - pass - else: - self.fail("import __phello__.foo should have failed") + try: + import __phello__.foo + except ImportError: + pass + else: + self.fail("import __phello__.foo should have failed") del sys.modules['__hello__'] del sys.modules['__phello__'] Modified: python/branches/py3k/Lib/test/test_reprlib.py ============================================================================== --- python/branches/py3k/Lib/test/test_reprlib.py (original) +++ python/branches/py3k/Lib/test/test_reprlib.py Wed May 5 21:11:21 2010 @@ -304,8 +304,7 @@ def test_main(): run_unittest(ReprTests) - if os.name != 'mac': - run_unittest(LongReprTest) + run_unittest(LongReprTest) if __name__ == "__main__": Modified: python/branches/py3k/Lib/test/test_select.py ============================================================================== --- python/branches/py3k/Lib/test/test_select.py (original) +++ python/branches/py3k/Lib/test/test_select.py Wed May 5 21:11:21 2010 @@ -4,7 +4,7 @@ import os import sys - at unittest.skipIf(sys.platform[:3] in ('win', 'mac', 'os2', 'riscos'), + at unittest.skipIf(sys.platform[:3] in ('win', 'os2', 'riscos'), "can't easily test on this system") class SelectTestCase(unittest.TestCase): Modified: python/branches/py3k/Lib/test/test_socket.py ============================================================================== --- python/branches/py3k/Lib/test/test_socket.py (original) +++ python/branches/py3k/Lib/test/test_socket.py Wed May 5 21:11:21 2010 @@ -1465,9 +1465,7 @@ def test_main(): tests = [GeneralModuleTests, BasicTCPTest, TCPCloserTest, TCPTimeoutTest, - TestExceptions, BufferIOTest, BasicTCPTest2] - if sys.platform != 'mac': - tests.extend([ BasicUDPTest, UDPTimeoutTest ]) + TestExceptions, BufferIOTest, BasicTCPTest2, BasicUDPTest, UDPTimeoutTest ] tests.extend([ NonBlockingTCPTests, Modified: python/branches/py3k/Lib/test/test_strptime.py ============================================================================== --- python/branches/py3k/Lib/test/test_strptime.py (original) +++ python/branches/py3k/Lib/test/test_strptime.py Wed May 5 21:11:21 2010 @@ -298,9 +298,6 @@ self.assertEqual(strp_output.tm_isdst, 0) strp_output = _strptime._strptime_time("GMT", "%Z") self.assertEqual(strp_output.tm_isdst, 0) - if sys.platform == "mac": - # Timezones don't really work on MacOS9 - return time_tuple = time.localtime() strf_output = time.strftime("%Z") #UTC does not have a timezone strp_output = _strptime._strptime_time(strf_output, "%Z") @@ -317,8 +314,6 @@ def test_bad_timezone(self): # Explicitly test possibility of bad timezone; # when time.tzname[0] == time.tzname[1] and time.daylight - if sys.platform == "mac": - return #MacOS9 has severely broken timezone support. tz_name = time.tzname[0] if tz_name.upper() in ("UTC", "GMT"): return Modified: python/branches/py3k/Lib/test/test_tempfile.py ============================================================================== --- python/branches/py3k/Lib/test/test_tempfile.py (original) +++ python/branches/py3k/Lib/test/test_tempfile.py Wed May 5 21:11:21 2010 @@ -20,9 +20,7 @@ # TEST_FILES may need to be tweaked for systems depending on the maximum # number of files that can be opened at one time (see ulimit -n) -if sys.platform == 'mac': - TEST_FILES = 32 -elif sys.platform in ('openbsd3', 'openbsd4'): +if sys.platform in ('openbsd3', 'openbsd4'): TEST_FILES = 48 else: TEST_FILES = 100 @@ -265,7 +263,7 @@ file = self.do_create() mode = stat.S_IMODE(os.stat(file.name).st_mode) expected = 0o600 - if sys.platform in ('win32', 'os2emx', 'mac'): + if sys.platform in ('win32', 'os2emx'): # There's no distinction among 'user', 'group' and 'world'; # replicate the 'user' bits. user = expected >> 6 @@ -488,7 +486,7 @@ mode = stat.S_IMODE(os.stat(dir).st_mode) mode &= 0o777 # Mask off sticky bits inherited from /tmp expected = 0o700 - if sys.platform in ('win32', 'os2emx', 'mac'): + if sys.platform in ('win32', 'os2emx'): # There's no distinction among 'user', 'group' and 'world'; # replicate the 'user' bits. user = expected >> 6 Modified: python/branches/py3k/Lib/test/test_urllib2.py ============================================================================== --- python/branches/py3k/Lib/test/test_urllib2.py (original) +++ python/branches/py3k/Lib/test/test_urllib2.py Wed May 5 21:11:21 2010 @@ -22,11 +22,6 @@ # XXX Name hacking to get this to work on Windows. fname = os.path.abspath(urllib.request.__file__).replace('\\', '/') - # And more hacking to get it to work on MacOS. This assumes - # urllib.pathname2url works, unfortunately... - if os.name == 'mac': - fname = '/' + fname.replace(':', '/') - if os.name == 'nt': file_url = "file:///%s" % fname else: Modified: python/branches/py3k/Lib/urllib/request.py ============================================================================== --- python/branches/py3k/Lib/urllib/request.py (original) +++ python/branches/py3k/Lib/urllib/request.py Wed May 5 21:11:21 2010 @@ -1338,9 +1338,7 @@ MAXFTPCACHE = 10 # Trim the ftp cache beyond this size # Helper for non-unix systems -if os.name == 'mac': - from macurl2path import url2pathname, pathname2url -elif os.name == 'nt': +if os.name == 'nt': from nturl2path import url2pathname, pathname2url else: def url2pathname(pathname): Modified: python/branches/py3k/Tools/webchecker/wcgui.py ============================================================================== --- python/branches/py3k/Tools/webchecker/wcgui.py (original) +++ python/branches/py3k/Tools/webchecker/wcgui.py Wed May 5 21:11:21 2010 @@ -64,12 +64,6 @@ import tktools import webchecker -# Override some for a weaker platform -if sys.platform == 'mac': - webchecker.DEFROOT = "http://grail.cnri.reston.va.us/" - webchecker.MAXPAGE = 50000 - webchecker.verbose = 4 - def main(): try: opts, args = getopt.getopt(sys.argv[1:], 't:m:qva') Modified: python/branches/py3k/Tools/webchecker/websucker.py ============================================================================== --- python/branches/py3k/Tools/webchecker/websucker.py (original) +++ python/branches/py3k/Tools/webchecker/websucker.py Wed May 5 21:11:21 2010 @@ -97,8 +97,6 @@ path = path + "index.html" if os.sep != "/": path = os.sep.join(path.split("/")) - if os.name == "mac": - path = os.sep + path path = os.path.join(host, path) return path Modified: python/branches/py3k/setup.py ============================================================================== --- python/branches/py3k/setup.py (original) +++ python/branches/py3k/setup.py Wed May 5 21:11:21 2010 @@ -150,22 +150,21 @@ if ext.name in sys.builtin_module_names: self.extensions.remove(ext) - if platform != 'mac': - # Parse Modules/Setup and Modules/Setup.local to figure out which - # modules are turned on in the file. - remove_modules = [] - for filename in ('Modules/Setup', 'Modules/Setup.local'): - input = text_file.TextFile(filename, join_lines=1) - while 1: - line = input.readline() - if not line: break - line = line.split() - remove_modules.append(line[0]) - input.close() - - for ext in self.extensions[:]: - if ext.name in remove_modules: - self.extensions.remove(ext) + # Parse Modules/Setup and Modules/Setup.local to figure out which + # modules are turned on in the file. + remove_modules = [] + for filename in ('Modules/Setup', 'Modules/Setup.local'): + input = text_file.TextFile(filename, join_lines=1) + while 1: + line = input.readline() + if not line: break + line = line.split() + remove_modules.append(line[0]) + input.close() + + for ext in self.extensions[:]: + if ext.name in remove_modules: + self.extensions.remove(ext) # When you run "make CC=altcc" or something similar, you really want # those environment variables passed into the setup.py phase. Here's @@ -381,7 +380,7 @@ # Check for MacOS X, which doesn't need libm.a at all math_libs = ['m'] - if platform in ['darwin', 'mac']: + if platform == 'darwin': math_libs = [] # XXX Omitted modules: gl, pure, dl, SGI-specific modules @@ -441,19 +440,16 @@ # fcntl(2) and ioctl(2) exts.append( Extension('fcntl', ['fcntlmodule.c']) ) - if platform not in ['mac']: - # pwd(3) - exts.append( Extension('pwd', ['pwdmodule.c']) ) - # grp(3) - exts.append( Extension('grp', ['grpmodule.c']) ) - # spwd, shadow passwords - if (config_h_vars.get('HAVE_GETSPNAM', False) or - config_h_vars.get('HAVE_GETSPENT', False)): - exts.append( Extension('spwd', ['spwdmodule.c']) ) - else: - missing.append('spwd') + # pwd(3) + exts.append( Extension('pwd', ['pwdmodule.c']) ) + # grp(3) + exts.append( Extension('grp', ['grpmodule.c']) ) + # spwd, shadow passwords + if (config_h_vars.get('HAVE_GETSPNAM', False) or + config_h_vars.get('HAVE_GETSPENT', False)): + exts.append( Extension('spwd', ['spwdmodule.c']) ) else: - missing.extend(['pwd', 'grp', 'spwd']) + missing.append('spwd') # select(2); not on ancient System V exts.append( Extension('select', ['selectmodule.c']) ) @@ -462,17 +458,11 @@ exts.append( Extension('parser', ['parsermodule.c']) ) # Memory-mapped files (also works on Win32). - if platform not in ['mac']: - exts.append( Extension('mmap', ['mmapmodule.c']) ) - else: - missing.append('mmap') + exts.append( Extension('mmap', ['mmapmodule.c']) ) # Lance Ellinghaus's syslog module - if platform not in ['mac']: - # syslog daemon interface - exts.append( Extension('syslog', ['syslogmodule.c']) ) - else: - missing.append('syslog') + # syslog daemon interface + exts.append( Extension('syslog', ['syslogmodule.c']) ) # # Here ends the simple stuff. From here on, modules need certain @@ -532,16 +522,13 @@ else: missing.append('readline') - if platform not in ['mac']: - # crypt module. + # crypt module. - if self.compiler_obj.find_library_file(lib_dirs, 'crypt'): - libs = ['crypt'] - else: - libs = [] - exts.append( Extension('crypt', ['cryptmodule.c'], libraries=libs) ) + if self.compiler_obj.find_library_file(lib_dirs, 'crypt'): + libs = ['crypt'] else: - missing.append('crypt') + libs = [] + exts.append( Extension('crypt', ['cryptmodule.c'], libraries=libs) ) # CSV files exts.append( Extension('_csv', ['_csv.c']) ) @@ -986,7 +973,7 @@ missing.append('_gdbm') # Unix-only modules - if platform not in ['mac', 'win32']: + if platform != 'win32': # Steen Lumholt's termios module exts.append( Extension('termios', ['termios.c']) ) # Jeremy Hylton's rlimit interface From python-checkins at python.org Wed May 5 21:12:30 2010 From: python-checkins at python.org (ronald.oussoren) Date: Wed, 5 May 2010 21:12:30 +0200 (CEST) Subject: [Python-checkins] r80806 - python/branches/py3k Message-ID: <20100505191230.656F0EEA18@mail.python.org> Author: ronald.oussoren Date: Wed May 5 21:12:30 2010 New Revision: 80806 Log: Blocked revisions 80804 via svnmerge ........ r80804 | ronald.oussoren | 2010-05-05 21:09:31 +0200 (Wed, 05 May 2010) | 8 lines In a number of places code still revers to "sys.platform == 'mac'" and that is dead code because it refers to a platform that is no longer supported (and hasn't been supported for several releases). Fixes issue #7908 for the trunk. ........ Modified: python/branches/py3k/ (props changed) From python-checkins at python.org Wed May 5 22:14:27 2010 From: python-checkins at python.org (brett.cannon) Date: Wed, 5 May 2010 22:14:27 +0200 (CEST) Subject: [Python-checkins] r80807 - python/trunk/Modules/_sqlite/connection.c Message-ID: <20100505201427.5EBF1C73B@mail.python.org> Author: brett.cannon Date: Wed May 5 22:14:27 2010 New Revision: 80807 Log: Remove an unnecessary variable. Found using Clang's static analyzer. Modified: python/trunk/Modules/_sqlite/connection.c Modified: python/trunk/Modules/_sqlite/connection.c ============================================================================== --- python/trunk/Modules/_sqlite/connection.c (original) +++ python/trunk/Modules/_sqlite/connection.c Wed May 5 22:14:27 2010 @@ -745,7 +745,6 @@ { PyObject* function_result = NULL; PyObject** aggregate_instance; - PyObject* aggregate_class; #ifdef WITH_THREAD PyGILState_STATE threadstate; @@ -753,8 +752,6 @@ threadstate = PyGILState_Ensure(); #endif - aggregate_class = (PyObject*)sqlite3_user_data(context); - aggregate_instance = (PyObject**)sqlite3_aggregate_context(context, sizeof(PyObject*)); if (!*aggregate_instance) { /* this branch is executed if there was an exception in the aggregate's From python-checkins at python.org Wed May 5 22:15:15 2010 From: python-checkins at python.org (brett.cannon) Date: Wed, 5 May 2010 22:15:15 +0200 (CEST) Subject: [Python-checkins] r80808 - in python/trunk/Modules/_multiprocessing: connection.h pipe_connection.c win32_functions.c Message-ID: <20100505201515.0B784C73B@mail.python.org> Author: brett.cannon Date: Wed May 5 22:15:14 2010 New Revision: 80808 Log: Remove extraneous whitespace. Modified: python/trunk/Modules/_multiprocessing/connection.h python/trunk/Modules/_multiprocessing/pipe_connection.c python/trunk/Modules/_multiprocessing/win32_functions.c Modified: python/trunk/Modules/_multiprocessing/connection.h ============================================================================== --- python/trunk/Modules/_multiprocessing/connection.h (original) +++ python/trunk/Modules/_multiprocessing/connection.h Wed May 5 22:15:14 2010 @@ -1,5 +1,5 @@ /* - * Definition of a `Connection` type. + * Definition of a `Connection` type. * Used by `socket_connection.c` and `pipe_connection.c`. * * connection.h @@ -42,7 +42,7 @@ static char *kwlist[] = {"handle", "readable", "writable", NULL}; - if (!PyArg_ParseTupleAndKeywords(args, kwds, F_HANDLE "|ii", kwlist, + if (!PyArg_ParseTupleAndKeywords(args, kwds, F_HANDLE "|ii", kwlist, &handle, &readable, &writable)) return NULL; @@ -53,7 +53,7 @@ } if (!readable && !writable) { - PyErr_SetString(PyExc_ValueError, + PyErr_SetString(PyExc_ValueError, "either readable or writable must be true"); return NULL; } @@ -120,10 +120,10 @@ } else { if (size < 0) { PyErr_SetString(PyExc_ValueError, "size is negative"); - return NULL; + return NULL; } if (offset + size > length) { - PyErr_SetString(PyExc_ValueError, + PyErr_SetString(PyExc_ValueError, "buffer length < offset + size"); return NULL; } @@ -142,7 +142,7 @@ } static PyObject * -connection_recvbytes(ConnectionObject *self, PyObject *args) +connection_recvbytes(ConnectionObject *self, PyObject *args) { char *freeme = NULL; Py_ssize_t res, maxlength = PY_SSIZE_T_MAX; @@ -152,15 +152,15 @@ return NULL; CHECK_READABLE(self); - + if (maxlength < 0) { PyErr_SetString(PyExc_ValueError, "maxlength < 0"); return NULL; } - - res = conn_recv_string(self, self->buffer, CONNECTION_BUFFER_SIZE, + + res = conn_recv_string(self, self->buffer, CONNECTION_BUFFER_SIZE, &freeme, maxlength); - + if (res < 0) { if (res == MP_BAD_MESSAGE_LENGTH) { if ((self->flags & WRITABLE) == 0) { @@ -173,7 +173,7 @@ } } mp_SetError(PyExc_IOError, res); - } else { + } else { if (freeme == NULL) { result = PyString_FromStringAndSize(self->buffer, res); } else { @@ -181,12 +181,12 @@ PyMem_Free(freeme); } } - + return result; } static PyObject * -connection_recvbytes_into(ConnectionObject *self, PyObject *args) +connection_recvbytes_into(ConnectionObject *self, PyObject *args) { char *freeme = NULL, *buffer = NULL; Py_ssize_t res, length, offset = 0; @@ -194,8 +194,8 @@ Py_buffer pbuf; CHECK_READABLE(self); - - if (!PyArg_ParseTuple(args, "w*|" F_PY_SSIZE_T, + + if (!PyArg_ParseTuple(args, "w*|" F_PY_SSIZE_T, &pbuf, &offset)) return NULL; @@ -205,14 +205,14 @@ if (offset < 0) { PyErr_SetString(PyExc_ValueError, "negative offset"); goto _error; - } + } if (offset > length) { PyErr_SetString(PyExc_ValueError, "offset too large"); goto _error; } - res = conn_recv_string(self, buffer+offset, length-offset, + res = conn_recv_string(self, buffer+offset, length-offset, &freeme, PY_SSIZE_T_MAX); if (res < 0) { @@ -231,8 +231,8 @@ if (freeme == NULL) { result = PyInt_FromSsize_t(res); } else { - result = PyObject_CallFunction(BufferTooShort, - F_RBUFFER "#", + result = PyObject_CallFunction(BufferTooShort, + F_RBUFFER "#", freeme, res); PyMem_Free(freeme); if (result) { @@ -266,7 +266,7 @@ CHECK_WRITABLE(self); - pickled_string = PyObject_CallFunctionObjArgs(pickle_dumps, obj, + pickled_string = PyObject_CallFunctionObjArgs(pickle_dumps, obj, pickle_protocol, NULL); if (!pickled_string) goto failure; @@ -298,7 +298,7 @@ CHECK_READABLE(self); - res = conn_recv_string(self, self->buffer, CONNECTION_BUFFER_SIZE, + res = conn_recv_string(self, self->buffer, CONNECTION_BUFFER_SIZE, &freeme, PY_SSIZE_T_MAX); if (res < 0) { @@ -313,7 +313,7 @@ } } mp_SetError(PyExc_IOError, res); - } else { + } else { if (freeme == NULL) { temp = PyString_FromStringAndSize(self->buffer, res); } else { @@ -323,7 +323,7 @@ } if (temp) - result = PyObject_CallFunctionObjArgs(pickle_loads, + result = PyObject_CallFunctionObjArgs(pickle_loads, temp, NULL); Py_XDECREF(temp); return result; @@ -400,7 +400,7 @@ static char *conn_type[] = {"read-only", "write-only", "read-write"}; assert(self->flags >= 1 && self->flags <= 3); - return FROM_FORMAT("<%s %s, handle %zd>", + return FROM_FORMAT("<%s %s, handle %zd>", conn_type[self->flags - 1], CONNECTION_NAME, (Py_ssize_t)self->handle); } @@ -432,20 +432,20 @@ */ static PyMethodDef connection_methods[] = { - {"send_bytes", (PyCFunction)connection_sendbytes, METH_VARARGS, + {"send_bytes", (PyCFunction)connection_sendbytes, METH_VARARGS, "send the byte data from a readable buffer-like object"}, - {"recv_bytes", (PyCFunction)connection_recvbytes, METH_VARARGS, + {"recv_bytes", (PyCFunction)connection_recvbytes, METH_VARARGS, "receive byte data as a string"}, {"recv_bytes_into",(PyCFunction)connection_recvbytes_into,METH_VARARGS, "receive byte data into a writeable buffer-like object\n" "returns the number of bytes read"}, - {"send", (PyCFunction)connection_send_obj, METH_O, + {"send", (PyCFunction)connection_send_obj, METH_O, "send a (picklable) object"}, - {"recv", (PyCFunction)connection_recv_obj, METH_NOARGS, + {"recv", (PyCFunction)connection_recv_obj, METH_NOARGS, "receive a (picklable) object"}, - {"poll", (PyCFunction)connection_poll, METH_VARARGS, + {"poll", (PyCFunction)connection_poll, METH_VARARGS, "whether there is any input available to be read"}, {"fileno", (PyCFunction)connection_fileno, METH_NOARGS, "file descriptor or handle of the connection"}, @@ -456,11 +456,11 @@ }; static PyGetSetDef connection_getset[] = { - {"closed", (getter)connection_closed, NULL, + {"closed", (getter)connection_closed, NULL, "True if the connection is closed", NULL}, - {"readable", (getter)connection_readable, NULL, + {"readable", (getter)connection_readable, NULL, "True if the connection is readable", NULL}, - {"writable", (getter)connection_writable, NULL, + {"writable", (getter)connection_writable, NULL, "True if the connection is writable", NULL}, {NULL} }; @@ -494,7 +494,7 @@ /* tp_getattro */ 0, /* tp_setattro */ 0, /* tp_as_buffer */ 0, - /* tp_flags */ Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | + /* tp_flags */ Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_WEAKREFS, /* tp_doc */ connection_doc, /* tp_traverse */ 0, Modified: python/trunk/Modules/_multiprocessing/pipe_connection.c ============================================================================== --- python/trunk/Modules/_multiprocessing/pipe_connection.c (original) +++ python/trunk/Modules/_multiprocessing/pipe_connection.c Wed May 5 22:15:14 2010 @@ -39,7 +39,7 @@ */ static Py_ssize_t -conn_recv_string(ConnectionObject *conn, char *buffer, +conn_recv_string(ConnectionObject *conn, char *buffer, size_t buflength, char **newbuffer, size_t maxlength) { DWORD left, length, full_length, err; @@ -130,7 +130,7 @@ Sleep(delay); /* check for signals */ - Py_BLOCK_THREADS + Py_BLOCK_THREADS res = PyErr_CheckSignals(); Py_UNBLOCK_THREADS Modified: python/trunk/Modules/_multiprocessing/win32_functions.c ============================================================================== --- python/trunk/Modules/_multiprocessing/win32_functions.c (original) +++ python/trunk/Modules/_multiprocessing/win32_functions.c Wed May 5 22:15:14 2010 @@ -26,7 +26,7 @@ return NULL; Py_BEGIN_ALLOW_THREADS - success = CloseHandle(hObject); + success = CloseHandle(hObject); Py_END_ALLOW_THREADS if (!success) @@ -42,7 +42,7 @@ LPOVERLAPPED lpOverlapped; BOOL success; - if (!PyArg_ParseTuple(args, F_HANDLE F_POINTER, + if (!PyArg_ParseTuple(args, F_HANDLE F_POINTER, &hNamedPipe, &lpOverlapped)) return NULL; @@ -68,17 +68,17 @@ HANDLE hTemplateFile; HANDLE handle; - if (!PyArg_ParseTuple(args, "s" F_DWORD F_DWORD F_POINTER + if (!PyArg_ParseTuple(args, "s" F_DWORD F_DWORD F_POINTER F_DWORD F_DWORD F_HANDLE, - &lpFileName, &dwDesiredAccess, &dwShareMode, - &lpSecurityAttributes, &dwCreationDisposition, + &lpFileName, &dwDesiredAccess, &dwShareMode, + &lpSecurityAttributes, &dwCreationDisposition, &dwFlagsAndAttributes, &hTemplateFile)) return NULL; Py_BEGIN_ALLOW_THREADS - handle = CreateFile(lpFileName, dwDesiredAccess, - dwShareMode, lpSecurityAttributes, - dwCreationDisposition, + handle = CreateFile(lpFileName, dwDesiredAccess, + dwShareMode, lpSecurityAttributes, + dwCreationDisposition, dwFlagsAndAttributes, hTemplateFile); Py_END_ALLOW_THREADS @@ -101,17 +101,17 @@ LPSECURITY_ATTRIBUTES lpSecurityAttributes; HANDLE handle; - if (!PyArg_ParseTuple(args, "s" F_DWORD F_DWORD F_DWORD + if (!PyArg_ParseTuple(args, "s" F_DWORD F_DWORD F_DWORD F_DWORD F_DWORD F_DWORD F_POINTER, - &lpName, &dwOpenMode, &dwPipeMode, - &nMaxInstances, &nOutBufferSize, + &lpName, &dwOpenMode, &dwPipeMode, + &nMaxInstances, &nOutBufferSize, &nInBufferSize, &nDefaultTimeOut, &lpSecurityAttributes)) return NULL; Py_BEGIN_ALLOW_THREADS - handle = CreateNamedPipe(lpName, dwOpenMode, dwPipeMode, - nMaxInstances, nOutBufferSize, + handle = CreateNamedPipe(lpName, dwOpenMode, dwPipeMode, + nMaxInstances, nOutBufferSize, nInBufferSize, nDefaultTimeOut, lpSecurityAttributes); Py_END_ALLOW_THREADS @@ -155,11 +155,11 @@ DWORD dwProcessId; HANDLE handle; - if (!PyArg_ParseTuple(args, F_DWORD "i" F_DWORD, + if (!PyArg_ParseTuple(args, F_DWORD "i" F_DWORD, &dwDesiredAccess, &bInheritHandle, &dwProcessId)) return NULL; - handle = OpenProcess(dwDesiredAccess, bInheritHandle, dwProcessId); + handle = OpenProcess(dwDesiredAccess, bInheritHandle, dwProcessId); if (handle == NULL) return PyErr_SetFromWindowsErr(0); @@ -174,7 +174,7 @@ DWORD dwArgs[3], *pArgs[3] = {NULL, NULL, NULL}; int i; - if (!PyArg_ParseTuple(args, F_HANDLE "OOO", + if (!PyArg_ParseTuple(args, F_HANDLE "OOO", &hNamedPipe, &oArgs[0], &oArgs[1], &oArgs[2])) return NULL; From python-checkins at python.org Wed May 5 22:16:09 2010 From: python-checkins at python.org (brett.cannon) Date: Wed, 5 May 2010 22:16:09 +0200 (CEST) Subject: [Python-checkins] r80809 - python/trunk/Objects/floatobject.c Message-ID: <20100505201609.5D92EF68D2@mail.python.org> Author: brett.cannon Date: Wed May 5 22:16:09 2010 New Revision: 80809 Log: Remove an unneeded variable increment. Found using Clang's static analyzer. Modified: python/trunk/Objects/floatobject.c Modified: python/trunk/Objects/floatobject.c ============================================================================== --- python/trunk/Objects/floatobject.c (original) +++ python/trunk/Objects/floatobject.c Wed May 5 22:16:09 2010 @@ -2478,7 +2478,6 @@ /* Eighth byte */ *p = flo & 0xFF; - p += incr; /* Done */ return 0; From python-checkins at python.org Wed May 5 22:16:50 2010 From: python-checkins at python.org (brett.cannon) Date: Wed, 5 May 2010 22:16:50 +0200 (CEST) Subject: [Python-checkins] r80810 - python/trunk/Objects/obmalloc.c Message-ID: <20100505201650.C640CC8E0@mail.python.org> Author: brett.cannon Date: Wed May 5 22:16:50 2010 New Revision: 80810 Log: Remove an unneeded variable. Found using Clang's static analyzer. Modified: python/trunk/Objects/obmalloc.c Modified: python/trunk/Objects/obmalloc.c ============================================================================== --- python/trunk/Objects/obmalloc.c (original) +++ python/trunk/Objects/obmalloc.c Wed May 5 22:16:50 2010 @@ -1761,7 +1761,6 @@ * will be living in full pools -- would be a shame to miss them. */ for (i = 0; i < maxarenas; ++i) { - uint poolsinarena; uint j; uptr base = arenas[i].address; @@ -1770,7 +1769,6 @@ continue; narenas += 1; - poolsinarena = arenas[i].ntotalpools; numfreepools += arenas[i].nfreepools; /* round up to pool alignment */ From python-checkins at python.org Wed May 5 22:18:23 2010 From: python-checkins at python.org (brett.cannon) Date: Wed, 5 May 2010 22:18:23 +0200 (CEST) Subject: [Python-checkins] r80811 - python/trunk/Objects/tupleobject.c Message-ID: <20100505201823.D3EDAC8E0@mail.python.org> Author: brett.cannon Date: Wed May 5 22:18:23 2010 New Revision: 80811 Log: Remove an unneeded variable assignment. Found using Clang's static analyzer. Modified: python/trunk/Objects/tupleobject.c Modified: python/trunk/Objects/tupleobject.c ============================================================================== --- python/trunk/Objects/tupleobject.c (original) +++ python/trunk/Objects/tupleobject.c Wed May 5 22:18:23 2010 @@ -7,7 +7,7 @@ #ifndef PyTuple_MAXSAVESIZE #define PyTuple_MAXSAVESIZE 20 /* Largest tuple to save on free list */ #endif -#ifndef PyTuple_MAXFREELIST +#ifndef PyTuple_MAXFREELIST #define PyTuple_MAXFREELIST 2000 /* Maximum number of tuples of each size to save */ #endif @@ -86,7 +86,6 @@ { return PyErr_NoMemory(); } - nbytes += sizeof(PyTupleObject) - sizeof(PyObject *); op = PyObject_GC_NewVar(PyTupleObject, &PyTuple_Type, size); if (op == NULL) From python-checkins at python.org Wed May 5 22:19:26 2010 From: python-checkins at python.org (brett.cannon) Date: Wed, 5 May 2010 22:19:26 +0200 (CEST) Subject: [Python-checkins] r80812 - python/trunk/Objects/typeobject.c Message-ID: <20100505201926.F23E2C8E0@mail.python.org> Author: brett.cannon Date: Wed May 5 22:19:26 2010 New Revision: 80812 Log: Remove an unneeded assignment. Found using Clang's static analyzer. Modified: python/trunk/Objects/typeobject.c Modified: python/trunk/Objects/typeobject.c ============================================================================== --- python/trunk/Objects/typeobject.c (original) +++ python/trunk/Objects/typeobject.c Wed May 5 22:19:26 2010 @@ -38,7 +38,7 @@ { Py_ssize_t i; unsigned int cur_version_tag = next_version_tag - 1; - + for (i = 0; i < (1 << MCACHE_SIZE_EXP); i++) { method_cache[i].version = 0; Py_CLEAR(method_cache[i].name); @@ -971,7 +971,7 @@ /* Clear slots up to the nearest base with a different tp_dealloc */ base = type; - while ((basedealloc = base->tp_dealloc) == subtype_dealloc) { + while (base->tp_dealloc == subtype_dealloc) { if (Py_SIZE(base)) clear_slots(base, self); base = base->tp_base; From python-checkins at python.org Wed May 5 22:20:19 2010 From: python-checkins at python.org (brett.cannon) Date: Wed, 5 May 2010 22:20:19 +0200 (CEST) Subject: [Python-checkins] r80813 - in python/trunk/Python: ast.c ceval.c dtoa.c getcwd.c import.c Message-ID: <20100505202019.571BCEC36@mail.python.org> Author: brett.cannon Date: Wed May 5 22:20:19 2010 New Revision: 80813 Log: Remove three unneeded variable assignments. Found using Clang's static analyzer. Modified: python/trunk/Python/ast.c python/trunk/Python/ceval.c python/trunk/Python/dtoa.c python/trunk/Python/getcwd.c python/trunk/Python/import.c Modified: python/trunk/Python/ast.c ============================================================================== --- python/trunk/Python/ast.c (original) +++ python/trunk/Python/ast.c Wed May 5 22:20:19 2010 @@ -454,8 +454,8 @@ expr_name = "conditional expression"; break; default: - PyErr_Format(PyExc_SystemError, - "unexpected expression in assignment %d (line %d)", + PyErr_Format(PyExc_SystemError, + "unexpected expression in assignment %d (line %d)", e->kind, e->lineno); return 0; } @@ -470,7 +470,7 @@ } /* If the LHS is a list or tuple, we need to set the assignment - context for all the contained elements. + context for all the contained elements. */ if (s) { int i; @@ -723,7 +723,7 @@ ast_error(n, "parenthesized arg with default"); goto error; } - ast_error(n, + ast_error(n, "non-default argument follows default argument"); goto error; } @@ -762,7 +762,7 @@ if (!name) goto error; asdl_seq_SET(args, k++, name); - + } i += 2; /* the name and the comma */ if (parenthesized && Py_Py3kWarningFlag && @@ -842,15 +842,15 @@ /* decorator: '@' dotted_name [ '(' [arglist] ')' ] NEWLINE */ expr_ty d = NULL; expr_ty name_expr; - + REQ(n, decorator); REQ(CHILD(n, 0), AT); REQ(RCHILD(n, -1), NEWLINE); - + name_expr = ast_for_dotted_name(c, CHILD(n, 1)); if (!name_expr) return NULL; - + if (NCH(n) == 3) { /* No arguments */ d = name_expr; name_expr = NULL; @@ -878,12 +878,12 @@ asdl_seq* decorator_seq; expr_ty d; int i; - + REQ(n, decorators); decorator_seq = asdl_seq_new(NCH(n), c->c_arena); if (!decorator_seq) return NULL; - + for (i = 0; i < NCH(n); i++) { d = ast_for_decorator(c, CHILD(n, i)); if (!d) @@ -980,7 +980,7 @@ static expr_ty ast_for_ifexpr(struct compiling *c, const node *n) { - /* test: or_test 'if' or_test 'else' test */ + /* test: or_test 'if' or_test 'else' test */ expr_ty expression, body, orelse; assert(NCH(n) == 5); @@ -1097,9 +1097,9 @@ asdl_seq *t; expr_ty expression; node *for_ch; - + REQ(ch, list_for); - + for_ch = CHILD(ch, 1); t = ast_for_exprlist(c, for_ch, Store); if (!t) @@ -1107,7 +1107,7 @@ expression = ast_for_testlist(c, CHILD(ch, 3)); if (!expression) return NULL; - + /* Check the # of children rather than the length of t, since [x for x, in ... ] has 1 element in t, but still requires a Tuple. */ @@ -1139,11 +1139,11 @@ REQ(ch, list_iter); ch = CHILD(ch, 0); REQ(ch, list_if); - + list_for_expr = ast_for_expr(c, CHILD(ch, 1)); if (!list_for_expr) return NULL; - + asdl_seq_SET(ifs, j, list_for_expr); if (NCH(ch) == 3) ch = CHILD(ch, 2); @@ -1239,9 +1239,9 @@ asdl_seq *t; expr_ty expression, first; node *for_ch; - + REQ(n, comp_for); - + for_ch = CHILD(n, 1); t = ast_for_exprlist(c, for_ch, Store); if (!t) @@ -1265,7 +1265,7 @@ if (NCH(n) == 5) { int j, n_ifs; asdl_seq *ifs; - + n = CHILD(n, 4); n_ifs = count_comp_ifs(c, n); if (n_ifs == -1) @@ -1279,7 +1279,7 @@ REQ(n, comp_iter); n = CHILD(n, 0); REQ(n, comp_if); - + expression = ast_for_expr(c, CHILD(n, 1)); if (!expression) return NULL; @@ -1302,13 +1302,13 @@ { expr_ty elt; asdl_seq *comps; - + assert(NCH(n) > 1); - + elt = ast_for_expr(c, CHILD(n, 0)); if (!elt) return NULL; - + comps = ast_for_comprehension(c, CHILD(n, 1)); if (!comps) return NULL; @@ -1327,10 +1327,10 @@ { expr_ty key, value; asdl_seq *comps; - + assert(NCH(n) > 3); REQ(CHILD(n, 1), COLON); - + key = ast_for_expr(c, CHILD(n, 0)); if (!key) return NULL; @@ -1338,11 +1338,11 @@ value = ast_for_expr(c, CHILD(n, 2)); if (!value) return NULL; - + comps = ast_for_comprehension(c, CHILD(n, 3)); if (!comps) return NULL; - + return DictComp(key, value, comps, LINENO(n), n->n_col_offset, c->c_arena); } @@ -1367,7 +1367,7 @@ | '{' [dictmaker] '}' | '`' testlist '`' | NAME | NUMBER | STRING+ */ node *ch = CHILD(n, 0); - + switch (TYPE(ch)) { case NAME: { /* All names start in Load context, but may later be @@ -1415,20 +1415,20 @@ } case LPAR: /* some parenthesized expressions */ ch = CHILD(n, 1); - + if (TYPE(ch) == RPAR) return Tuple(NULL, Load, LINENO(n), n->n_col_offset, c->c_arena); - + if (TYPE(ch) == yield_expr) return ast_for_expr(c, ch); - + return ast_for_testlist_comp(c, ch); case LSQB: /* list (or list comprehension) */ ch = CHILD(n, 1); - + if (TYPE(ch) == RSQB) return List(NULL, Load, LINENO(n), n->n_col_offset, c->c_arena); - + REQ(ch, listmaker); if (NCH(ch) == 1 || TYPE(CHILD(ch, 1)) == COMMA) { asdl_seq *elts = seq_for_testlist(c, ch); @@ -1477,14 +1477,14 @@ keys = asdl_seq_new(size, c->c_arena); if (!keys) return NULL; - + values = asdl_seq_new(size, c->c_arena); if (!values) return NULL; - + for (i = 0; i < NCH(ch); i += 4) { expr_ty expression; - + expression = ast_for_expr(c, CHILD(ch, i)); if (!expression) return NULL; @@ -1536,10 +1536,10 @@ if (NCH(n) == 1 && TYPE(ch) == test) { /* 'step' variable hold no significance in terms of being used over other vars */ - step = ast_for_expr(c, ch); + step = ast_for_expr(c, ch); if (!step) return NULL; - + return Index(step, c->c_arena); } @@ -1573,7 +1573,7 @@ ch = CHILD(n, NCH(n) - 1); if (TYPE(ch) == sliceop) { if (NCH(ch) == 1) { - /* + /* This is an extended slice (ie "x[::]") with no expression in the step field. We set this literally to "None" in order to disambiguate it from x[:]. (The interpreter might have to call @@ -1603,7 +1603,7 @@ ast_for_binop(struct compiling *c, const node *n) { /* Must account for a sequence of expressions. - How should A op B op C by represented? + How should A op B op C by represented? BinOp(BinOp(A, op, B), op, C). */ @@ -1641,10 +1641,10 @@ if (!tmp) return NULL; - tmp_result = BinOp(result, newoperator, tmp, + tmp_result = BinOp(result, newoperator, tmp, LINENO(next_oper), next_oper->n_col_offset, c->c_arena); - if (!tmp_result) + if (!tmp_result) return NULL; result = tmp_result; } @@ -1654,7 +1654,7 @@ static expr_ty ast_for_trailer(struct compiling *c, const node *n, expr_ty left_expr) { - /* trailer: '(' [arglist] ')' | '[' subscriptlist ']' | '.' NAME + /* trailer: '(' [arglist] ')' | '[' subscriptlist ']' | '.' NAME subscriptlist: subscript (',' subscript)* [','] subscript: '.' '.' '.' | test | [test] ':' [test] [sliceop] */ @@ -1685,7 +1685,7 @@ c->c_arena); } else { - /* The grammar is ambiguous here. The ambiguity is resolved + /* The grammar is ambiguous here. The ambiguity is resolved by treating the sequence as a tuple literal if there are no slice features. */ @@ -1822,7 +1822,7 @@ { /* handle the full range of simple expressions test: or_test ['if' or_test 'else' test] | lambdef - or_test: and_test ('or' and_test)* + or_test: and_test ('or' and_test)* and_test: not_test ('and' not_test)* not_test: 'not' not_test | comparison comparison: expr (comp_op expr)* @@ -1839,7 +1839,7 @@ to explicitly allow: [ x for x in lambda: 0, lambda: 1 ] (which would be ambiguous without these extra rules) - + old_test: or_test | old_lambdef old_lambdef: 'lambda' [vararglist] ':' old_test @@ -1919,7 +1919,7 @@ if (!expression) { return NULL; } - + asdl_seq_SET(ops, i / 2, newoperator); asdl_seq_SET(cmps, i / 2, expression); } @@ -1927,7 +1927,7 @@ if (!expression) { return NULL; } - + return Compare(expression, ops, cmps, LINENO(n), n->n_col_offset, c->c_arena); } @@ -2041,7 +2041,7 @@ if (!e) return NULL; asdl_seq_SET(args, nargs++, e); - } + } else if (TYPE(CHILD(ch, 1)) == comp_for) { e = ast_for_genexp(c, ch); if (!e) @@ -2054,7 +2054,7 @@ int k; char *tmp; - /* CHILD(ch, 0) is test, but must be an identifier? */ + /* CHILD(ch, 0) is test, but must be an identifier? */ e = ast_for_expr(c, CHILD(ch, 0)); if (!e) return NULL; @@ -2173,7 +2173,7 @@ ast_for_expr_stmt(struct compiling *c, const node *n) { REQ(n, expr_stmt); - /* expr_stmt: testlist (augassign (yield_expr|testlist) + /* expr_stmt: testlist (augassign (yield_expr|testlist) | ('=' (yield_expr|testlist))*) testlist: test (',' test)* [','] augassign: '+=' | '-=' | '*=' | '/=' | '%=' | '&=' | '|=' | '^=' @@ -2248,7 +2248,7 @@ e = ast_for_testlist(c, ch); /* set context to assign */ - if (!e) + if (!e) return NULL; if (!set_context(c, e, Store, CHILD(n, i))) @@ -2329,7 +2329,7 @@ ast_for_del_stmt(struct compiling *c, const node *n) { asdl_seq *expr_list; - + /* del_stmt: 'del' exprlist */ REQ(n, del_stmt); @@ -2413,7 +2413,7 @@ expr3 = ast_for_expr(c, CHILD(ch, 5)); if (!expr3) return NULL; - + return Raise(expr1, expr2, expr3, LINENO(n), n->n_col_offset, c->c_arena); } @@ -2569,7 +2569,7 @@ int idx, ndots = 0; alias_ty mod = NULL; identifier modname = NULL; - + /* Count the number of dots (for relative imports) and check for the optional module name */ for (idx = 1; idx < NCH(n); idx++) { @@ -2715,7 +2715,7 @@ expr2 = ast_for_expr(c, CHILD(n, 3)); if (!expr2) return NULL; - + return Assert(expr1, expr2, LINENO(n), n->n_col_offset, c->c_arena); } PyErr_Format(PyExc_SystemError, @@ -2742,7 +2742,7 @@ if (TYPE(CHILD(n, 0)) == simple_stmt) { n = CHILD(n, 0); /* simple_stmt always ends with a NEWLINE, - and may have a trailing SEMI + and may have a trailing SEMI */ end = NCH(n) - 1; if (TYPE(CHILD(n, end - 1)) == SEMI) @@ -2807,10 +2807,10 @@ expression = ast_for_expr(c, CHILD(n, 1)); if (!expression) return NULL; - suite_seq = ast_for_suite(c, CHILD(n, 3)); + suite_seq = ast_for_suite(c, CHILD(n, 3)); if (!suite_seq) return NULL; - + return If(expression, suite_seq, NULL, LINENO(n), n->n_col_offset, c->c_arena); } @@ -2868,8 +2868,8 @@ if (!suite_seq2) return NULL; - asdl_seq_SET(orelse, 0, - If(expression, suite_seq, suite_seq2, + asdl_seq_SET(orelse, 0, + If(expression, suite_seq, suite_seq2, LINENO(CHILD(n, NCH(n) - 6)), CHILD(n, NCH(n) - 6)->n_col_offset, c->c_arena)); @@ -2890,7 +2890,7 @@ return NULL; asdl_seq_SET(newobj, 0, - If(expression, suite_seq, orelse, + If(expression, suite_seq, orelse, LINENO(CHILD(n, off)), CHILD(n, off)->n_col_offset, c->c_arena)); orelse = newobj; @@ -3089,7 +3089,7 @@ ast_error(n, "malformed 'try' statement"); return NULL; } - + if (n_except > 0) { int i; stmt_ty except_st; @@ -3190,7 +3190,7 @@ /* classdef: 'class' NAME ['(' testlist ')'] ':' suite */ PyObject *classname; asdl_seq *bases, *s; - + REQ(n, classdef); if (!forbidden_check(c, n, STR(CHILD(n, 1)))) @@ -3378,17 +3378,12 @@ static PyObject * decode_unicode(struct compiling *c, const char *s, size_t len, int rawmode, const char *encoding) { - PyObject *v, *u; + PyObject *v; + PyObject *u = NULL; char *buf; char *p; const char *end; - if (encoding == NULL) { - buf = (char *)s; - u = NULL; - } else if (strcmp(encoding, "iso-8859-1") == 0) { - buf = (char *)s; - u = NULL; - } else { + if (encoding != NULL && strcmp(encoding, "iso-8859-1")) { /* check for integer overflow */ if (len > PY_SIZE_MAX / 6) return NULL; @@ -3478,7 +3473,7 @@ s++; len = strlen(s); if (len > INT_MAX) { - PyErr_SetString(PyExc_OverflowError, + PyErr_SetString(PyExc_OverflowError, "string to parse is too long"); return NULL; } Modified: python/trunk/Python/ceval.c ============================================================================== --- python/trunk/Python/ceval.c (original) +++ python/trunk/Python/ceval.c Wed May 5 22:20:19 2010 @@ -2697,7 +2697,6 @@ Py_DECREF(*pfunc); *pfunc = self; na++; - n++; } else Py_INCREF(func); sp = stack_pointer; Modified: python/trunk/Python/dtoa.c ============================================================================== --- python/trunk/Python/dtoa.c (original) +++ python/trunk/Python/dtoa.c Wed May 5 22:20:19 2010 @@ -1382,7 +1382,6 @@ Bigint *b, *d; int b2, d2, dd, i, nd, nd0, odd, p2, p5; - dd = 0; /* silence compiler warning about possibly unused variable */ nd = bc->nd; nd0 = bc->nd0; p5 = nd + bc->e0; @@ -2362,7 +2361,7 @@ /* set pointers to NULL, to silence gcc compiler warnings and make cleanup easier on error */ - mlo = mhi = b = S = 0; + mlo = mhi = S = 0; s0 = 0; u.d = dd; @@ -2713,8 +2712,6 @@ * and for all and pass them and a shift to quorem, so it * can do shifts and ors to compute the numerator for q. */ - if ((i = ((s5 ? 32 - hi0bits(S->x[S->wds-1]) : 1) + s2) & 0x1f)) - i = 32 - i; #define iInc 28 i = dshift(S, s2); b2 += i; Modified: python/trunk/Python/getcwd.c ============================================================================== --- python/trunk/Python/getcwd.c (original) +++ python/trunk/Python/getcwd.c Wed May 5 22:20:19 2010 @@ -28,7 +28,7 @@ { char localbuf[MAXPATHLEN+1]; char *ret; - + if (size <= 0) { errno = EINVAL; return NULL; @@ -59,14 +59,13 @@ { FILE *fp; char *p; - int sts; if (size <= 0) { errno = EINVAL; return NULL; } if ((fp = popen(PWD_CMD, "r")) == NULL) return NULL; - if (fgets(buf, size, fp) == NULL || (sts = pclose(fp)) != 0) { + if (fgets(buf, size, fp) == NULL || pclose(fp) != 0) { errno = EACCES; /* Most likely error */ return NULL; } Modified: python/trunk/Python/import.c ============================================================================== --- python/trunk/Python/import.c (original) +++ python/trunk/Python/import.c Wed May 5 22:20:19 2010 @@ -19,7 +19,7 @@ #include #endif #ifdef __cplusplus -extern "C" { +extern "C" { #endif #ifdef MS_WINDOWS @@ -826,7 +826,7 @@ flags.cf_flags = 0; - mod = PyParser_ASTFromFile(fp, pathname, Py_file_input, 0, 0, &flags, + mod = PyParser_ASTFromFile(fp, pathname, Py_file_input, 0, 0, &flags, NULL, arena); if (mod) { co = PyAST_Compile(mod, pathname, NULL, arena); @@ -884,7 +884,7 @@ mode_t mode = srcstat->st_mode & ~S_IEXEC; #else mode_t mode = srcstat->st_mode & ~S_IXUSR & ~S_IXGRP & ~S_IXOTH; -#endif +#endif fp = open_exclusive(cpathname, mode); if (fp == NULL) { @@ -972,7 +972,7 @@ char *cpathname; PyCodeObject *co; PyObject *m; - + if (fstat(fileno(fp), &st) != 0) { PyErr_Format(PyExc_RuntimeError, "unable to get file status from '%s'", @@ -1406,7 +1406,7 @@ else { char warnstr[MAXPATHLEN+80]; sprintf(warnstr, "Not importing directory " - "'%.*s': missing __init__.py", + "'%.*s': missing __init__.py", MAXPATHLEN, buf); if (PyErr_Warn(PyExc_ImportWarning, warnstr)) { @@ -1427,7 +1427,7 @@ else { char warnstr[MAXPATHLEN+80]; sprintf(warnstr, "Not importing directory " - "'%.*s': missing __init__.py", + "'%.*s': missing __init__.py", MAXPATHLEN, buf); if (PyErr_Warn(PyExc_ImportWarning, warnstr)) { @@ -2266,7 +2266,7 @@ modname = PyDict_GetItem(globals, namestr); if (modname == NULL || !PyString_Check(modname)) return Py_None; - + modpath = PyDict_GetItem(globals, pathstr); if (modpath != NULL) { /* __path__ is set, so modname is already the package name */ @@ -2621,7 +2621,7 @@ struct filedescr *fdp; FILE *fp = NULL; PyObject *newm; - + if (modules_reloading == NULL) { Py_FatalError("PyImport_ReloadModule: " "no modules_reloading dictionary!"); From brett at python.org Wed May 5 22:22:41 2010 From: brett at python.org (Brett Cannon) Date: Wed, 5 May 2010 13:22:41 -0700 Subject: [Python-checkins] r80813 - in python/trunk/Python: ast.c ceval.c dtoa.c getcwd.c import.c In-Reply-To: <20100505202019.571BCEC36@mail.python.org> References: <20100505202019.571BCEC36@mail.python.org> Message-ID: I realize I committed too much; in the middle of reverting the files. On Wed, May 5, 2010 at 13:20, brett.cannon wrote: > Author: brett.cannon > Date: Wed May 5 22:20:19 2010 > New Revision: 80813 > > Log: > Remove three unneeded variable assignments. > > Found using Clang's static analyzer. > > > Modified: > python/trunk/Python/ast.c > python/trunk/Python/ceval.c > python/trunk/Python/dtoa.c > python/trunk/Python/getcwd.c > python/trunk/Python/import.c > > Modified: python/trunk/Python/ast.c > > ============================================================================== > --- python/trunk/Python/ast.c (original) > +++ python/trunk/Python/ast.c Wed May 5 22:20:19 2010 > @@ -454,8 +454,8 @@ > expr_name = "conditional expression"; > break; > default: > - PyErr_Format(PyExc_SystemError, > - "unexpected expression in assignment %d (line > %d)", > + PyErr_Format(PyExc_SystemError, > + "unexpected expression in assignment %d (line > %d)", > e->kind, e->lineno); > return 0; > } > @@ -470,7 +470,7 @@ > } > > /* If the LHS is a list or tuple, we need to set the assignment > - context for all the contained elements. > + context for all the contained elements. > */ > if (s) { > int i; > @@ -723,7 +723,7 @@ > ast_error(n, "parenthesized arg with default"); > goto error; > } > - ast_error(n, > + ast_error(n, > "non-default argument follows default > argument"); > goto error; > } > @@ -762,7 +762,7 @@ > if (!name) > goto error; > asdl_seq_SET(args, k++, name); > - > + > } > i += 2; /* the name and the comma */ > if (parenthesized && Py_Py3kWarningFlag && > @@ -842,15 +842,15 @@ > /* decorator: '@' dotted_name [ '(' [arglist] ')' ] NEWLINE */ > expr_ty d = NULL; > expr_ty name_expr; > - > + > REQ(n, decorator); > REQ(CHILD(n, 0), AT); > REQ(RCHILD(n, -1), NEWLINE); > - > + > name_expr = ast_for_dotted_name(c, CHILD(n, 1)); > if (!name_expr) > return NULL; > - > + > if (NCH(n) == 3) { /* No arguments */ > d = name_expr; > name_expr = NULL; > @@ -878,12 +878,12 @@ > asdl_seq* decorator_seq; > expr_ty d; > int i; > - > + > REQ(n, decorators); > decorator_seq = asdl_seq_new(NCH(n), c->c_arena); > if (!decorator_seq) > return NULL; > - > + > for (i = 0; i < NCH(n); i++) { > d = ast_for_decorator(c, CHILD(n, i)); > if (!d) > @@ -980,7 +980,7 @@ > static expr_ty > ast_for_ifexpr(struct compiling *c, const node *n) > { > - /* test: or_test 'if' or_test 'else' test */ > + /* test: or_test 'if' or_test 'else' test */ > expr_ty expression, body, orelse; > > assert(NCH(n) == 5); > @@ -1097,9 +1097,9 @@ > asdl_seq *t; > expr_ty expression; > node *for_ch; > - > + > REQ(ch, list_for); > - > + > for_ch = CHILD(ch, 1); > t = ast_for_exprlist(c, for_ch, Store); > if (!t) > @@ -1107,7 +1107,7 @@ > expression = ast_for_testlist(c, CHILD(ch, 3)); > if (!expression) > return NULL; > - > + > /* Check the # of children rather than the length of t, since > [x for x, in ... ] has 1 element in t, but still requires a > Tuple. > */ > @@ -1139,11 +1139,11 @@ > REQ(ch, list_iter); > ch = CHILD(ch, 0); > REQ(ch, list_if); > - > + > list_for_expr = ast_for_expr(c, CHILD(ch, 1)); > if (!list_for_expr) > return NULL; > - > + > asdl_seq_SET(ifs, j, list_for_expr); > if (NCH(ch) == 3) > ch = CHILD(ch, 2); > @@ -1239,9 +1239,9 @@ > asdl_seq *t; > expr_ty expression, first; > node *for_ch; > - > + > REQ(n, comp_for); > - > + > for_ch = CHILD(n, 1); > t = ast_for_exprlist(c, for_ch, Store); > if (!t) > @@ -1265,7 +1265,7 @@ > if (NCH(n) == 5) { > int j, n_ifs; > asdl_seq *ifs; > - > + > n = CHILD(n, 4); > n_ifs = count_comp_ifs(c, n); > if (n_ifs == -1) > @@ -1279,7 +1279,7 @@ > REQ(n, comp_iter); > n = CHILD(n, 0); > REQ(n, comp_if); > - > + > expression = ast_for_expr(c, CHILD(n, 1)); > if (!expression) > return NULL; > @@ -1302,13 +1302,13 @@ > { > expr_ty elt; > asdl_seq *comps; > - > + > assert(NCH(n) > 1); > - > + > elt = ast_for_expr(c, CHILD(n, 0)); > if (!elt) > return NULL; > - > + > comps = ast_for_comprehension(c, CHILD(n, 1)); > if (!comps) > return NULL; > @@ -1327,10 +1327,10 @@ > { > expr_ty key, value; > asdl_seq *comps; > - > + > assert(NCH(n) > 3); > REQ(CHILD(n, 1), COLON); > - > + > key = ast_for_expr(c, CHILD(n, 0)); > if (!key) > return NULL; > @@ -1338,11 +1338,11 @@ > value = ast_for_expr(c, CHILD(n, 2)); > if (!value) > return NULL; > - > + > comps = ast_for_comprehension(c, CHILD(n, 3)); > if (!comps) > return NULL; > - > + > return DictComp(key, value, comps, LINENO(n), n->n_col_offset, > c->c_arena); > } > > @@ -1367,7 +1367,7 @@ > | '{' [dictmaker] '}' | '`' testlist '`' | NAME | NUMBER | STRING+ > */ > node *ch = CHILD(n, 0); > - > + > switch (TYPE(ch)) { > case NAME: { > /* All names start in Load context, but may later be > @@ -1415,20 +1415,20 @@ > } > case LPAR: /* some parenthesized expressions */ > ch = CHILD(n, 1); > - > + > if (TYPE(ch) == RPAR) > return Tuple(NULL, Load, LINENO(n), n->n_col_offset, > c->c_arena); > - > + > if (TYPE(ch) == yield_expr) > return ast_for_expr(c, ch); > - > + > return ast_for_testlist_comp(c, ch); > case LSQB: /* list (or list comprehension) */ > ch = CHILD(n, 1); > - > + > if (TYPE(ch) == RSQB) > return List(NULL, Load, LINENO(n), n->n_col_offset, > c->c_arena); > - > + > REQ(ch, listmaker); > if (NCH(ch) == 1 || TYPE(CHILD(ch, 1)) == COMMA) { > asdl_seq *elts = seq_for_testlist(c, ch); > @@ -1477,14 +1477,14 @@ > keys = asdl_seq_new(size, c->c_arena); > if (!keys) > return NULL; > - > + > values = asdl_seq_new(size, c->c_arena); > if (!values) > return NULL; > - > + > for (i = 0; i < NCH(ch); i += 4) { > expr_ty expression; > - > + > expression = ast_for_expr(c, CHILD(ch, i)); > if (!expression) > return NULL; > @@ -1536,10 +1536,10 @@ > if (NCH(n) == 1 && TYPE(ch) == test) { > /* 'step' variable hold no significance in terms of being used over > other vars */ > - step = ast_for_expr(c, ch); > + step = ast_for_expr(c, ch); > if (!step) > return NULL; > - > + > return Index(step, c->c_arena); > } > > @@ -1573,7 +1573,7 @@ > ch = CHILD(n, NCH(n) - 1); > if (TYPE(ch) == sliceop) { > if (NCH(ch) == 1) { > - /* > + /* > This is an extended slice (ie "x[::]") with no expression in > the > step field. We set this literally to "None" in order to > disambiguate it from x[:]. (The interpreter might have to > call > @@ -1603,7 +1603,7 @@ > ast_for_binop(struct compiling *c, const node *n) > { > /* Must account for a sequence of expressions. > - How should A op B op C by represented? > + How should A op B op C by represented? > BinOp(BinOp(A, op, B), op, C). > */ > > @@ -1641,10 +1641,10 @@ > if (!tmp) > return NULL; > > - tmp_result = BinOp(result, newoperator, tmp, > + tmp_result = BinOp(result, newoperator, tmp, > LINENO(next_oper), > next_oper->n_col_offset, > c->c_arena); > - if (!tmp_result) > + if (!tmp_result) > return NULL; > result = tmp_result; > } > @@ -1654,7 +1654,7 @@ > static expr_ty > ast_for_trailer(struct compiling *c, const node *n, expr_ty left_expr) > { > - /* trailer: '(' [arglist] ')' | '[' subscriptlist ']' | '.' NAME > + /* trailer: '(' [arglist] ')' | '[' subscriptlist ']' | '.' NAME > subscriptlist: subscript (',' subscript)* [','] > subscript: '.' '.' '.' | test | [test] ':' [test] [sliceop] > */ > @@ -1685,7 +1685,7 @@ > c->c_arena); > } > else { > - /* The grammar is ambiguous here. The ambiguity is resolved > + /* The grammar is ambiguous here. The ambiguity is resolved > by treating the sequence as a tuple literal if there are > no slice features. > */ > @@ -1822,7 +1822,7 @@ > { > /* handle the full range of simple expressions > test: or_test ['if' or_test 'else' test] | lambdef > - or_test: and_test ('or' and_test)* > + or_test: and_test ('or' and_test)* > and_test: not_test ('and' not_test)* > not_test: 'not' not_test | comparison > comparison: expr (comp_op expr)* > @@ -1839,7 +1839,7 @@ > to explicitly allow: > [ x for x in lambda: 0, lambda: 1 ] > (which would be ambiguous without these extra rules) > - > + > old_test: or_test | old_lambdef > old_lambdef: 'lambda' [vararglist] ':' old_test > > @@ -1919,7 +1919,7 @@ > if (!expression) { > return NULL; > } > - > + > asdl_seq_SET(ops, i / 2, newoperator); > asdl_seq_SET(cmps, i / 2, expression); > } > @@ -1927,7 +1927,7 @@ > if (!expression) { > return NULL; > } > - > + > return Compare(expression, ops, cmps, LINENO(n), > n->n_col_offset, c->c_arena); > } > @@ -2041,7 +2041,7 @@ > if (!e) > return NULL; > asdl_seq_SET(args, nargs++, e); > - } > + } > else if (TYPE(CHILD(ch, 1)) == comp_for) { > e = ast_for_genexp(c, ch); > if (!e) > @@ -2054,7 +2054,7 @@ > int k; > char *tmp; > > - /* CHILD(ch, 0) is test, but must be an identifier? */ > + /* CHILD(ch, 0) is test, but must be an identifier? */ > e = ast_for_expr(c, CHILD(ch, 0)); > if (!e) > return NULL; > @@ -2173,7 +2173,7 @@ > ast_for_expr_stmt(struct compiling *c, const node *n) > { > REQ(n, expr_stmt); > - /* expr_stmt: testlist (augassign (yield_expr|testlist) > + /* expr_stmt: testlist (augassign (yield_expr|testlist) > | ('=' (yield_expr|testlist))*) > testlist: test (',' test)* [','] > augassign: '+=' | '-=' | '*=' | '/=' | '%=' | '&=' | '|=' | '^=' > @@ -2248,7 +2248,7 @@ > e = ast_for_testlist(c, ch); > > /* set context to assign */ > - if (!e) > + if (!e) > return NULL; > > if (!set_context(c, e, Store, CHILD(n, i))) > @@ -2329,7 +2329,7 @@ > ast_for_del_stmt(struct compiling *c, const node *n) > { > asdl_seq *expr_list; > - > + > /* del_stmt: 'del' exprlist */ > REQ(n, del_stmt); > > @@ -2413,7 +2413,7 @@ > expr3 = ast_for_expr(c, CHILD(ch, 5)); > if (!expr3) > return NULL; > - > + > return Raise(expr1, expr2, expr3, LINENO(n), > n->n_col_offset, > c->c_arena); > } > @@ -2569,7 +2569,7 @@ > int idx, ndots = 0; > alias_ty mod = NULL; > identifier modname = NULL; > - > + > /* Count the number of dots (for relative imports) and check for the > optional module name */ > for (idx = 1; idx < NCH(n); idx++) { > @@ -2715,7 +2715,7 @@ > expr2 = ast_for_expr(c, CHILD(n, 3)); > if (!expr2) > return NULL; > - > + > return Assert(expr1, expr2, LINENO(n), n->n_col_offset, > c->c_arena); > } > PyErr_Format(PyExc_SystemError, > @@ -2742,7 +2742,7 @@ > if (TYPE(CHILD(n, 0)) == simple_stmt) { > n = CHILD(n, 0); > /* simple_stmt always ends with a NEWLINE, > - and may have a trailing SEMI > + and may have a trailing SEMI > */ > end = NCH(n) - 1; > if (TYPE(CHILD(n, end - 1)) == SEMI) > @@ -2807,10 +2807,10 @@ > expression = ast_for_expr(c, CHILD(n, 1)); > if (!expression) > return NULL; > - suite_seq = ast_for_suite(c, CHILD(n, 3)); > + suite_seq = ast_for_suite(c, CHILD(n, 3)); > if (!suite_seq) > return NULL; > - > + > return If(expression, suite_seq, NULL, LINENO(n), n->n_col_offset, > c->c_arena); > } > @@ -2868,8 +2868,8 @@ > if (!suite_seq2) > return NULL; > > - asdl_seq_SET(orelse, 0, > - If(expression, suite_seq, suite_seq2, > + asdl_seq_SET(orelse, 0, > + If(expression, suite_seq, suite_seq2, > LINENO(CHILD(n, NCH(n) - 6)), > CHILD(n, NCH(n) - 6)->n_col_offset, > c->c_arena)); > @@ -2890,7 +2890,7 @@ > return NULL; > > asdl_seq_SET(newobj, 0, > - If(expression, suite_seq, orelse, > + If(expression, suite_seq, orelse, > LINENO(CHILD(n, off)), > CHILD(n, off)->n_col_offset, c->c_arena)); > orelse = newobj; > @@ -3089,7 +3089,7 @@ > ast_error(n, "malformed 'try' statement"); > return NULL; > } > - > + > if (n_except > 0) { > int i; > stmt_ty except_st; > @@ -3190,7 +3190,7 @@ > /* classdef: 'class' NAME ['(' testlist ')'] ':' suite */ > PyObject *classname; > asdl_seq *bases, *s; > - > + > REQ(n, classdef); > > if (!forbidden_check(c, n, STR(CHILD(n, 1)))) > @@ -3378,17 +3378,12 @@ > static PyObject * > decode_unicode(struct compiling *c, const char *s, size_t len, int > rawmode, const char *encoding) > { > - PyObject *v, *u; > + PyObject *v; > + PyObject *u = NULL; > char *buf; > char *p; > const char *end; > - if (encoding == NULL) { > - buf = (char *)s; > - u = NULL; > - } else if (strcmp(encoding, "iso-8859-1") == 0) { > - buf = (char *)s; > - u = NULL; > - } else { > + if (encoding != NULL && strcmp(encoding, "iso-8859-1")) { > /* check for integer overflow */ > if (len > PY_SIZE_MAX / 6) > return NULL; > @@ -3478,7 +3473,7 @@ > s++; > len = strlen(s); > if (len > INT_MAX) { > - PyErr_SetString(PyExc_OverflowError, > + PyErr_SetString(PyExc_OverflowError, > "string to parse is too long"); > return NULL; > } > > Modified: python/trunk/Python/ceval.c > > ============================================================================== > --- python/trunk/Python/ceval.c (original) > +++ python/trunk/Python/ceval.c Wed May 5 22:20:19 2010 > @@ -2697,7 +2697,6 @@ > Py_DECREF(*pfunc); > *pfunc = self; > na++; > - n++; > } else > Py_INCREF(func); > sp = stack_pointer; > > Modified: python/trunk/Python/dtoa.c > > ============================================================================== > --- python/trunk/Python/dtoa.c (original) > +++ python/trunk/Python/dtoa.c Wed May 5 22:20:19 2010 > @@ -1382,7 +1382,6 @@ > Bigint *b, *d; > int b2, d2, dd, i, nd, nd0, odd, p2, p5; > > - dd = 0; /* silence compiler warning about possibly unused variable */ > nd = bc->nd; > nd0 = bc->nd0; > p5 = nd + bc->e0; > @@ -2362,7 +2361,7 @@ > > /* set pointers to NULL, to silence gcc compiler warnings and make > cleanup easier on error */ > - mlo = mhi = b = S = 0; > + mlo = mhi = S = 0; > s0 = 0; > > u.d = dd; > @@ -2713,8 +2712,6 @@ > * and for all and pass them and a shift to quorem, so it > * can do shifts and ors to compute the numerator for q. > */ > - if ((i = ((s5 ? 32 - hi0bits(S->x[S->wds-1]) : 1) + s2) & 0x1f)) > - i = 32 - i; > #define iInc 28 > i = dshift(S, s2); > b2 += i; > > Modified: python/trunk/Python/getcwd.c > > ============================================================================== > --- python/trunk/Python/getcwd.c (original) > +++ python/trunk/Python/getcwd.c Wed May 5 22:20:19 2010 > @@ -28,7 +28,7 @@ > { > char localbuf[MAXPATHLEN+1]; > char *ret; > - > + > if (size <= 0) { > errno = EINVAL; > return NULL; > @@ -59,14 +59,13 @@ > { > FILE *fp; > char *p; > - int sts; > if (size <= 0) { > errno = EINVAL; > return NULL; > } > if ((fp = popen(PWD_CMD, "r")) == NULL) > return NULL; > - if (fgets(buf, size, fp) == NULL || (sts = pclose(fp)) != 0) { > + if (fgets(buf, size, fp) == NULL || pclose(fp) != 0) { > errno = EACCES; /* Most likely error */ > return NULL; > } > > Modified: python/trunk/Python/import.c > > ============================================================================== > --- python/trunk/Python/import.c (original) > +++ python/trunk/Python/import.c Wed May 5 22:20:19 2010 > @@ -19,7 +19,7 @@ > #include > #endif > #ifdef __cplusplus > -extern "C" { > +extern "C" { > #endif > > #ifdef MS_WINDOWS > @@ -826,7 +826,7 @@ > > flags.cf_flags = 0; > > - mod = PyParser_ASTFromFile(fp, pathname, Py_file_input, 0, 0, > &flags, > + mod = PyParser_ASTFromFile(fp, pathname, Py_file_input, 0, 0, > &flags, > NULL, arena); > if (mod) { > co = PyAST_Compile(mod, pathname, NULL, arena); > @@ -884,7 +884,7 @@ > mode_t mode = srcstat->st_mode & ~S_IEXEC; > #else > mode_t mode = srcstat->st_mode & ~S_IXUSR & ~S_IXGRP & ~S_IXOTH; > -#endif > +#endif > > fp = open_exclusive(cpathname, mode); > if (fp == NULL) { > @@ -972,7 +972,7 @@ > char *cpathname; > PyCodeObject *co; > PyObject *m; > - > + > if (fstat(fileno(fp), &st) != 0) { > PyErr_Format(PyExc_RuntimeError, > "unable to get file status from '%s'", > @@ -1406,7 +1406,7 @@ > else { > char warnstr[MAXPATHLEN+80]; > sprintf(warnstr, "Not importing directory " > - "'%.*s': missing __init__.py", > + "'%.*s': missing __init__.py", > MAXPATHLEN, buf); > if (PyErr_Warn(PyExc_ImportWarning, > warnstr)) { > @@ -1427,7 +1427,7 @@ > else { > char warnstr[MAXPATHLEN+80]; > sprintf(warnstr, "Not importing directory " > - "'%.*s': missing __init__.py", > + "'%.*s': missing __init__.py", > MAXPATHLEN, buf); > if (PyErr_Warn(PyExc_ImportWarning, > warnstr)) { > @@ -2266,7 +2266,7 @@ > modname = PyDict_GetItem(globals, namestr); > if (modname == NULL || !PyString_Check(modname)) > return Py_None; > - > + > modpath = PyDict_GetItem(globals, pathstr); > if (modpath != NULL) { > /* __path__ is set, so modname is already the > package name */ > @@ -2621,7 +2621,7 @@ > struct filedescr *fdp; > FILE *fp = NULL; > PyObject *newm; > - > + > if (modules_reloading == NULL) { > Py_FatalError("PyImport_ReloadModule: " > "no modules_reloading dictionary!"); > _______________________________________________ > Python-checkins mailing list > Python-checkins at python.org > http://mail.python.org/mailman/listinfo/python-checkins > -------------- next part -------------- An HTML attachment was scrubbed... URL: From python-checkins at python.org Wed May 5 22:24:30 2010 From: python-checkins at python.org (brett.cannon) Date: Wed, 5 May 2010 22:24:30 +0200 (CEST) Subject: [Python-checkins] r80814 - in python/trunk/Python: ast.c ceval.c getcwd.c import.c Message-ID: <20100505202430.E2CA4EE9A9@mail.python.org> Author: brett.cannon Date: Wed May 5 22:24:30 2010 New Revision: 80814 Log: Partially revert the over-reaching r80813. Modified: python/trunk/Python/ast.c python/trunk/Python/ceval.c python/trunk/Python/getcwd.c python/trunk/Python/import.c Modified: python/trunk/Python/ast.c ============================================================================== --- python/trunk/Python/ast.c (original) +++ python/trunk/Python/ast.c Wed May 5 22:24:30 2010 @@ -454,8 +454,8 @@ expr_name = "conditional expression"; break; default: - PyErr_Format(PyExc_SystemError, - "unexpected expression in assignment %d (line %d)", + PyErr_Format(PyExc_SystemError, + "unexpected expression in assignment %d (line %d)", e->kind, e->lineno); return 0; } @@ -470,7 +470,7 @@ } /* If the LHS is a list or tuple, we need to set the assignment - context for all the contained elements. + context for all the contained elements. */ if (s) { int i; @@ -723,7 +723,7 @@ ast_error(n, "parenthesized arg with default"); goto error; } - ast_error(n, + ast_error(n, "non-default argument follows default argument"); goto error; } @@ -762,7 +762,7 @@ if (!name) goto error; asdl_seq_SET(args, k++, name); - + } i += 2; /* the name and the comma */ if (parenthesized && Py_Py3kWarningFlag && @@ -842,15 +842,15 @@ /* decorator: '@' dotted_name [ '(' [arglist] ')' ] NEWLINE */ expr_ty d = NULL; expr_ty name_expr; - + REQ(n, decorator); REQ(CHILD(n, 0), AT); REQ(RCHILD(n, -1), NEWLINE); - + name_expr = ast_for_dotted_name(c, CHILD(n, 1)); if (!name_expr) return NULL; - + if (NCH(n) == 3) { /* No arguments */ d = name_expr; name_expr = NULL; @@ -878,12 +878,12 @@ asdl_seq* decorator_seq; expr_ty d; int i; - + REQ(n, decorators); decorator_seq = asdl_seq_new(NCH(n), c->c_arena); if (!decorator_seq) return NULL; - + for (i = 0; i < NCH(n); i++) { d = ast_for_decorator(c, CHILD(n, i)); if (!d) @@ -980,7 +980,7 @@ static expr_ty ast_for_ifexpr(struct compiling *c, const node *n) { - /* test: or_test 'if' or_test 'else' test */ + /* test: or_test 'if' or_test 'else' test */ expr_ty expression, body, orelse; assert(NCH(n) == 5); @@ -1097,9 +1097,9 @@ asdl_seq *t; expr_ty expression; node *for_ch; - + REQ(ch, list_for); - + for_ch = CHILD(ch, 1); t = ast_for_exprlist(c, for_ch, Store); if (!t) @@ -1107,7 +1107,7 @@ expression = ast_for_testlist(c, CHILD(ch, 3)); if (!expression) return NULL; - + /* Check the # of children rather than the length of t, since [x for x, in ... ] has 1 element in t, but still requires a Tuple. */ @@ -1139,11 +1139,11 @@ REQ(ch, list_iter); ch = CHILD(ch, 0); REQ(ch, list_if); - + list_for_expr = ast_for_expr(c, CHILD(ch, 1)); if (!list_for_expr) return NULL; - + asdl_seq_SET(ifs, j, list_for_expr); if (NCH(ch) == 3) ch = CHILD(ch, 2); @@ -1239,9 +1239,9 @@ asdl_seq *t; expr_ty expression, first; node *for_ch; - + REQ(n, comp_for); - + for_ch = CHILD(n, 1); t = ast_for_exprlist(c, for_ch, Store); if (!t) @@ -1265,7 +1265,7 @@ if (NCH(n) == 5) { int j, n_ifs; asdl_seq *ifs; - + n = CHILD(n, 4); n_ifs = count_comp_ifs(c, n); if (n_ifs == -1) @@ -1279,7 +1279,7 @@ REQ(n, comp_iter); n = CHILD(n, 0); REQ(n, comp_if); - + expression = ast_for_expr(c, CHILD(n, 1)); if (!expression) return NULL; @@ -1302,13 +1302,13 @@ { expr_ty elt; asdl_seq *comps; - + assert(NCH(n) > 1); - + elt = ast_for_expr(c, CHILD(n, 0)); if (!elt) return NULL; - + comps = ast_for_comprehension(c, CHILD(n, 1)); if (!comps) return NULL; @@ -1327,10 +1327,10 @@ { expr_ty key, value; asdl_seq *comps; - + assert(NCH(n) > 3); REQ(CHILD(n, 1), COLON); - + key = ast_for_expr(c, CHILD(n, 0)); if (!key) return NULL; @@ -1338,11 +1338,11 @@ value = ast_for_expr(c, CHILD(n, 2)); if (!value) return NULL; - + comps = ast_for_comprehension(c, CHILD(n, 3)); if (!comps) return NULL; - + return DictComp(key, value, comps, LINENO(n), n->n_col_offset, c->c_arena); } @@ -1367,7 +1367,7 @@ | '{' [dictmaker] '}' | '`' testlist '`' | NAME | NUMBER | STRING+ */ node *ch = CHILD(n, 0); - + switch (TYPE(ch)) { case NAME: { /* All names start in Load context, but may later be @@ -1415,20 +1415,20 @@ } case LPAR: /* some parenthesized expressions */ ch = CHILD(n, 1); - + if (TYPE(ch) == RPAR) return Tuple(NULL, Load, LINENO(n), n->n_col_offset, c->c_arena); - + if (TYPE(ch) == yield_expr) return ast_for_expr(c, ch); - + return ast_for_testlist_comp(c, ch); case LSQB: /* list (or list comprehension) */ ch = CHILD(n, 1); - + if (TYPE(ch) == RSQB) return List(NULL, Load, LINENO(n), n->n_col_offset, c->c_arena); - + REQ(ch, listmaker); if (NCH(ch) == 1 || TYPE(CHILD(ch, 1)) == COMMA) { asdl_seq *elts = seq_for_testlist(c, ch); @@ -1477,14 +1477,14 @@ keys = asdl_seq_new(size, c->c_arena); if (!keys) return NULL; - + values = asdl_seq_new(size, c->c_arena); if (!values) return NULL; - + for (i = 0; i < NCH(ch); i += 4) { expr_ty expression; - + expression = ast_for_expr(c, CHILD(ch, i)); if (!expression) return NULL; @@ -1536,10 +1536,10 @@ if (NCH(n) == 1 && TYPE(ch) == test) { /* 'step' variable hold no significance in terms of being used over other vars */ - step = ast_for_expr(c, ch); + step = ast_for_expr(c, ch); if (!step) return NULL; - + return Index(step, c->c_arena); } @@ -1573,7 +1573,7 @@ ch = CHILD(n, NCH(n) - 1); if (TYPE(ch) == sliceop) { if (NCH(ch) == 1) { - /* + /* This is an extended slice (ie "x[::]") with no expression in the step field. We set this literally to "None" in order to disambiguate it from x[:]. (The interpreter might have to call @@ -1603,7 +1603,7 @@ ast_for_binop(struct compiling *c, const node *n) { /* Must account for a sequence of expressions. - How should A op B op C by represented? + How should A op B op C by represented? BinOp(BinOp(A, op, B), op, C). */ @@ -1641,10 +1641,10 @@ if (!tmp) return NULL; - tmp_result = BinOp(result, newoperator, tmp, + tmp_result = BinOp(result, newoperator, tmp, LINENO(next_oper), next_oper->n_col_offset, c->c_arena); - if (!tmp_result) + if (!tmp_result) return NULL; result = tmp_result; } @@ -1654,7 +1654,7 @@ static expr_ty ast_for_trailer(struct compiling *c, const node *n, expr_ty left_expr) { - /* trailer: '(' [arglist] ')' | '[' subscriptlist ']' | '.' NAME + /* trailer: '(' [arglist] ')' | '[' subscriptlist ']' | '.' NAME subscriptlist: subscript (',' subscript)* [','] subscript: '.' '.' '.' | test | [test] ':' [test] [sliceop] */ @@ -1685,7 +1685,7 @@ c->c_arena); } else { - /* The grammar is ambiguous here. The ambiguity is resolved + /* The grammar is ambiguous here. The ambiguity is resolved by treating the sequence as a tuple literal if there are no slice features. */ @@ -1822,7 +1822,7 @@ { /* handle the full range of simple expressions test: or_test ['if' or_test 'else' test] | lambdef - or_test: and_test ('or' and_test)* + or_test: and_test ('or' and_test)* and_test: not_test ('and' not_test)* not_test: 'not' not_test | comparison comparison: expr (comp_op expr)* @@ -1839,7 +1839,7 @@ to explicitly allow: [ x for x in lambda: 0, lambda: 1 ] (which would be ambiguous without these extra rules) - + old_test: or_test | old_lambdef old_lambdef: 'lambda' [vararglist] ':' old_test @@ -1919,7 +1919,7 @@ if (!expression) { return NULL; } - + asdl_seq_SET(ops, i / 2, newoperator); asdl_seq_SET(cmps, i / 2, expression); } @@ -1927,7 +1927,7 @@ if (!expression) { return NULL; } - + return Compare(expression, ops, cmps, LINENO(n), n->n_col_offset, c->c_arena); } @@ -2041,7 +2041,7 @@ if (!e) return NULL; asdl_seq_SET(args, nargs++, e); - } + } else if (TYPE(CHILD(ch, 1)) == comp_for) { e = ast_for_genexp(c, ch); if (!e) @@ -2054,7 +2054,7 @@ int k; char *tmp; - /* CHILD(ch, 0) is test, but must be an identifier? */ + /* CHILD(ch, 0) is test, but must be an identifier? */ e = ast_for_expr(c, CHILD(ch, 0)); if (!e) return NULL; @@ -2173,7 +2173,7 @@ ast_for_expr_stmt(struct compiling *c, const node *n) { REQ(n, expr_stmt); - /* expr_stmt: testlist (augassign (yield_expr|testlist) + /* expr_stmt: testlist (augassign (yield_expr|testlist) | ('=' (yield_expr|testlist))*) testlist: test (',' test)* [','] augassign: '+=' | '-=' | '*=' | '/=' | '%=' | '&=' | '|=' | '^=' @@ -2248,7 +2248,7 @@ e = ast_for_testlist(c, ch); /* set context to assign */ - if (!e) + if (!e) return NULL; if (!set_context(c, e, Store, CHILD(n, i))) @@ -2329,7 +2329,7 @@ ast_for_del_stmt(struct compiling *c, const node *n) { asdl_seq *expr_list; - + /* del_stmt: 'del' exprlist */ REQ(n, del_stmt); @@ -2413,7 +2413,7 @@ expr3 = ast_for_expr(c, CHILD(ch, 5)); if (!expr3) return NULL; - + return Raise(expr1, expr2, expr3, LINENO(n), n->n_col_offset, c->c_arena); } @@ -2569,7 +2569,7 @@ int idx, ndots = 0; alias_ty mod = NULL; identifier modname = NULL; - + /* Count the number of dots (for relative imports) and check for the optional module name */ for (idx = 1; idx < NCH(n); idx++) { @@ -2715,7 +2715,7 @@ expr2 = ast_for_expr(c, CHILD(n, 3)); if (!expr2) return NULL; - + return Assert(expr1, expr2, LINENO(n), n->n_col_offset, c->c_arena); } PyErr_Format(PyExc_SystemError, @@ -2742,7 +2742,7 @@ if (TYPE(CHILD(n, 0)) == simple_stmt) { n = CHILD(n, 0); /* simple_stmt always ends with a NEWLINE, - and may have a trailing SEMI + and may have a trailing SEMI */ end = NCH(n) - 1; if (TYPE(CHILD(n, end - 1)) == SEMI) @@ -2807,10 +2807,10 @@ expression = ast_for_expr(c, CHILD(n, 1)); if (!expression) return NULL; - suite_seq = ast_for_suite(c, CHILD(n, 3)); + suite_seq = ast_for_suite(c, CHILD(n, 3)); if (!suite_seq) return NULL; - + return If(expression, suite_seq, NULL, LINENO(n), n->n_col_offset, c->c_arena); } @@ -2868,8 +2868,8 @@ if (!suite_seq2) return NULL; - asdl_seq_SET(orelse, 0, - If(expression, suite_seq, suite_seq2, + asdl_seq_SET(orelse, 0, + If(expression, suite_seq, suite_seq2, LINENO(CHILD(n, NCH(n) - 6)), CHILD(n, NCH(n) - 6)->n_col_offset, c->c_arena)); @@ -2890,7 +2890,7 @@ return NULL; asdl_seq_SET(newobj, 0, - If(expression, suite_seq, orelse, + If(expression, suite_seq, orelse, LINENO(CHILD(n, off)), CHILD(n, off)->n_col_offset, c->c_arena)); orelse = newobj; @@ -3089,7 +3089,7 @@ ast_error(n, "malformed 'try' statement"); return NULL; } - + if (n_except > 0) { int i; stmt_ty except_st; @@ -3190,7 +3190,7 @@ /* classdef: 'class' NAME ['(' testlist ')'] ':' suite */ PyObject *classname; asdl_seq *bases, *s; - + REQ(n, classdef); if (!forbidden_check(c, n, STR(CHILD(n, 1)))) @@ -3378,12 +3378,17 @@ static PyObject * decode_unicode(struct compiling *c, const char *s, size_t len, int rawmode, const char *encoding) { - PyObject *v; - PyObject *u = NULL; + PyObject *v, *u; char *buf; char *p; const char *end; - if (encoding != NULL && strcmp(encoding, "iso-8859-1")) { + if (encoding == NULL) { + buf = (char *)s; + u = NULL; + } else if (strcmp(encoding, "iso-8859-1") == 0) { + buf = (char *)s; + u = NULL; + } else { /* check for integer overflow */ if (len > PY_SIZE_MAX / 6) return NULL; @@ -3473,7 +3478,7 @@ s++; len = strlen(s); if (len > INT_MAX) { - PyErr_SetString(PyExc_OverflowError, + PyErr_SetString(PyExc_OverflowError, "string to parse is too long"); return NULL; } Modified: python/trunk/Python/ceval.c ============================================================================== --- python/trunk/Python/ceval.c (original) +++ python/trunk/Python/ceval.c Wed May 5 22:24:30 2010 @@ -2697,6 +2697,7 @@ Py_DECREF(*pfunc); *pfunc = self; na++; + n++; } else Py_INCREF(func); sp = stack_pointer; Modified: python/trunk/Python/getcwd.c ============================================================================== --- python/trunk/Python/getcwd.c (original) +++ python/trunk/Python/getcwd.c Wed May 5 22:24:30 2010 @@ -28,7 +28,7 @@ { char localbuf[MAXPATHLEN+1]; char *ret; - + if (size <= 0) { errno = EINVAL; return NULL; @@ -59,13 +59,14 @@ { FILE *fp; char *p; + int sts; if (size <= 0) { errno = EINVAL; return NULL; } if ((fp = popen(PWD_CMD, "r")) == NULL) return NULL; - if (fgets(buf, size, fp) == NULL || pclose(fp) != 0) { + if (fgets(buf, size, fp) == NULL || (sts = pclose(fp)) != 0) { errno = EACCES; /* Most likely error */ return NULL; } Modified: python/trunk/Python/import.c ============================================================================== --- python/trunk/Python/import.c (original) +++ python/trunk/Python/import.c Wed May 5 22:24:30 2010 @@ -19,7 +19,7 @@ #include #endif #ifdef __cplusplus -extern "C" { +extern "C" { #endif #ifdef MS_WINDOWS @@ -826,7 +826,7 @@ flags.cf_flags = 0; - mod = PyParser_ASTFromFile(fp, pathname, Py_file_input, 0, 0, &flags, + mod = PyParser_ASTFromFile(fp, pathname, Py_file_input, 0, 0, &flags, NULL, arena); if (mod) { co = PyAST_Compile(mod, pathname, NULL, arena); @@ -884,7 +884,7 @@ mode_t mode = srcstat->st_mode & ~S_IEXEC; #else mode_t mode = srcstat->st_mode & ~S_IXUSR & ~S_IXGRP & ~S_IXOTH; -#endif +#endif fp = open_exclusive(cpathname, mode); if (fp == NULL) { @@ -972,7 +972,7 @@ char *cpathname; PyCodeObject *co; PyObject *m; - + if (fstat(fileno(fp), &st) != 0) { PyErr_Format(PyExc_RuntimeError, "unable to get file status from '%s'", @@ -1406,7 +1406,7 @@ else { char warnstr[MAXPATHLEN+80]; sprintf(warnstr, "Not importing directory " - "'%.*s': missing __init__.py", + "'%.*s': missing __init__.py", MAXPATHLEN, buf); if (PyErr_Warn(PyExc_ImportWarning, warnstr)) { @@ -1427,7 +1427,7 @@ else { char warnstr[MAXPATHLEN+80]; sprintf(warnstr, "Not importing directory " - "'%.*s': missing __init__.py", + "'%.*s': missing __init__.py", MAXPATHLEN, buf); if (PyErr_Warn(PyExc_ImportWarning, warnstr)) { @@ -2266,7 +2266,7 @@ modname = PyDict_GetItem(globals, namestr); if (modname == NULL || !PyString_Check(modname)) return Py_None; - + modpath = PyDict_GetItem(globals, pathstr); if (modpath != NULL) { /* __path__ is set, so modname is already the package name */ @@ -2621,7 +2621,7 @@ struct filedescr *fdp; FILE *fp = NULL; PyObject *newm; - + if (modules_reloading == NULL) { Py_FatalError("PyImport_ReloadModule: " "no modules_reloading dictionary!"); From python-checkins at python.org Wed May 5 22:25:47 2010 From: python-checkins at python.org (brett.cannon) Date: Wed, 5 May 2010 22:25:47 +0200 (CEST) Subject: [Python-checkins] r80815 - python/trunk/Python/import.c Message-ID: <20100505202547.85406EE9A9@mail.python.org> Author: brett.cannon Date: Wed May 5 22:25:47 2010 New Revision: 80815 Log: Fix whitespace. Modified: python/trunk/Python/import.c Modified: python/trunk/Python/import.c ============================================================================== --- python/trunk/Python/import.c (original) +++ python/trunk/Python/import.c Wed May 5 22:25:47 2010 @@ -19,7 +19,7 @@ #include #endif #ifdef __cplusplus -extern "C" { +extern "C" { #endif #ifdef MS_WINDOWS @@ -826,7 +826,7 @@ flags.cf_flags = 0; - mod = PyParser_ASTFromFile(fp, pathname, Py_file_input, 0, 0, &flags, + mod = PyParser_ASTFromFile(fp, pathname, Py_file_input, 0, 0, &flags, NULL, arena); if (mod) { co = PyAST_Compile(mod, pathname, NULL, arena); @@ -884,7 +884,7 @@ mode_t mode = srcstat->st_mode & ~S_IEXEC; #else mode_t mode = srcstat->st_mode & ~S_IXUSR & ~S_IXGRP & ~S_IXOTH; -#endif +#endif fp = open_exclusive(cpathname, mode); if (fp == NULL) { @@ -972,7 +972,7 @@ char *cpathname; PyCodeObject *co; PyObject *m; - + if (fstat(fileno(fp), &st) != 0) { PyErr_Format(PyExc_RuntimeError, "unable to get file status from '%s'", @@ -1406,7 +1406,7 @@ else { char warnstr[MAXPATHLEN+80]; sprintf(warnstr, "Not importing directory " - "'%.*s': missing __init__.py", + "'%.*s': missing __init__.py", MAXPATHLEN, buf); if (PyErr_Warn(PyExc_ImportWarning, warnstr)) { @@ -1427,7 +1427,7 @@ else { char warnstr[MAXPATHLEN+80]; sprintf(warnstr, "Not importing directory " - "'%.*s': missing __init__.py", + "'%.*s': missing __init__.py", MAXPATHLEN, buf); if (PyErr_Warn(PyExc_ImportWarning, warnstr)) { @@ -2266,7 +2266,7 @@ modname = PyDict_GetItem(globals, namestr); if (modname == NULL || !PyString_Check(modname)) return Py_None; - + modpath = PyDict_GetItem(globals, pathstr); if (modpath != NULL) { /* __path__ is set, so modname is already the package name */ @@ -2621,7 +2621,7 @@ struct filedescr *fdp; FILE *fp = NULL; PyObject *newm; - + if (modules_reloading == NULL) { Py_FatalError("PyImport_ReloadModule: " "no modules_reloading dictionary!"); From python-checkins at python.org Wed May 5 22:26:58 2010 From: python-checkins at python.org (brett.cannon) Date: Wed, 5 May 2010 22:26:58 +0200 (CEST) Subject: [Python-checkins] r80816 - python/trunk/Python/getcwd.c Message-ID: <20100505202658.BA843EE9A9@mail.python.org> Author: brett.cannon Date: Wed May 5 22:26:58 2010 New Revision: 80816 Log: Remove an unneeded variable and fix a little whitespace. Found using Clang's static analyzer. Modified: python/trunk/Python/getcwd.c Modified: python/trunk/Python/getcwd.c ============================================================================== --- python/trunk/Python/getcwd.c (original) +++ python/trunk/Python/getcwd.c Wed May 5 22:26:58 2010 @@ -28,7 +28,7 @@ { char localbuf[MAXPATHLEN+1]; char *ret; - + if (size <= 0) { errno = EINVAL; return NULL; @@ -59,14 +59,13 @@ { FILE *fp; char *p; - int sts; if (size <= 0) { errno = EINVAL; return NULL; } if ((fp = popen(PWD_CMD, "r")) == NULL) return NULL; - if (fgets(buf, size, fp) == NULL || (sts = pclose(fp)) != 0) { + if (fgets(buf, size, fp) == NULL || pclose(fp) != 0) { errno = EACCES; /* Most likely error */ return NULL; } From python-checkins at python.org Wed May 5 22:27:49 2010 From: python-checkins at python.org (brett.cannon) Date: Wed, 5 May 2010 22:27:49 +0200 (CEST) Subject: [Python-checkins] r80817 - python/trunk/Python/ceval.c Message-ID: <20100505202749.6C43EEE9A9@mail.python.org> Author: brett.cannon Date: Wed May 5 22:27:49 2010 New Revision: 80817 Log: Remove an unneeded variable increment. Found using Clang's static analyzer. Modified: python/trunk/Python/ceval.c Modified: python/trunk/Python/ceval.c ============================================================================== --- python/trunk/Python/ceval.c (original) +++ python/trunk/Python/ceval.c Wed May 5 22:27:49 2010 @@ -2697,7 +2697,6 @@ Py_DECREF(*pfunc); *pfunc = self; na++; - n++; } else Py_INCREF(func); sp = stack_pointer; From python-checkins at python.org Wed May 5 22:30:31 2010 From: python-checkins at python.org (brett.cannon) Date: Wed, 5 May 2010 22:30:31 +0200 (CEST) Subject: [Python-checkins] r80818 - python/trunk/Python/ast.c Message-ID: <20100505203031.1CC75EE9A9@mail.python.org> Author: brett.cannon Date: Wed May 5 22:30:30 2010 New Revision: 80818 Log: Remove two unneeded branches to an 'if' statement by applying De Morgan's Law and creating a single 'if' statement along with a NULL default value for a variable. Also clean up a bunch of whitespace. Found using Clang's static analyzer. Modified: python/trunk/Python/ast.c Modified: python/trunk/Python/ast.c ============================================================================== --- python/trunk/Python/ast.c (original) +++ python/trunk/Python/ast.c Wed May 5 22:30:30 2010 @@ -454,8 +454,8 @@ expr_name = "conditional expression"; break; default: - PyErr_Format(PyExc_SystemError, - "unexpected expression in assignment %d (line %d)", + PyErr_Format(PyExc_SystemError, + "unexpected expression in assignment %d (line %d)", e->kind, e->lineno); return 0; } @@ -470,7 +470,7 @@ } /* If the LHS is a list or tuple, we need to set the assignment - context for all the contained elements. + context for all the contained elements. */ if (s) { int i; @@ -723,7 +723,7 @@ ast_error(n, "parenthesized arg with default"); goto error; } - ast_error(n, + ast_error(n, "non-default argument follows default argument"); goto error; } @@ -762,7 +762,7 @@ if (!name) goto error; asdl_seq_SET(args, k++, name); - + } i += 2; /* the name and the comma */ if (parenthesized && Py_Py3kWarningFlag && @@ -842,15 +842,15 @@ /* decorator: '@' dotted_name [ '(' [arglist] ')' ] NEWLINE */ expr_ty d = NULL; expr_ty name_expr; - + REQ(n, decorator); REQ(CHILD(n, 0), AT); REQ(RCHILD(n, -1), NEWLINE); - + name_expr = ast_for_dotted_name(c, CHILD(n, 1)); if (!name_expr) return NULL; - + if (NCH(n) == 3) { /* No arguments */ d = name_expr; name_expr = NULL; @@ -878,12 +878,12 @@ asdl_seq* decorator_seq; expr_ty d; int i; - + REQ(n, decorators); decorator_seq = asdl_seq_new(NCH(n), c->c_arena); if (!decorator_seq) return NULL; - + for (i = 0; i < NCH(n); i++) { d = ast_for_decorator(c, CHILD(n, i)); if (!d) @@ -980,7 +980,7 @@ static expr_ty ast_for_ifexpr(struct compiling *c, const node *n) { - /* test: or_test 'if' or_test 'else' test */ + /* test: or_test 'if' or_test 'else' test */ expr_ty expression, body, orelse; assert(NCH(n) == 5); @@ -1097,9 +1097,9 @@ asdl_seq *t; expr_ty expression; node *for_ch; - + REQ(ch, list_for); - + for_ch = CHILD(ch, 1); t = ast_for_exprlist(c, for_ch, Store); if (!t) @@ -1107,7 +1107,7 @@ expression = ast_for_testlist(c, CHILD(ch, 3)); if (!expression) return NULL; - + /* Check the # of children rather than the length of t, since [x for x, in ... ] has 1 element in t, but still requires a Tuple. */ @@ -1139,11 +1139,11 @@ REQ(ch, list_iter); ch = CHILD(ch, 0); REQ(ch, list_if); - + list_for_expr = ast_for_expr(c, CHILD(ch, 1)); if (!list_for_expr) return NULL; - + asdl_seq_SET(ifs, j, list_for_expr); if (NCH(ch) == 3) ch = CHILD(ch, 2); @@ -1239,9 +1239,9 @@ asdl_seq *t; expr_ty expression, first; node *for_ch; - + REQ(n, comp_for); - + for_ch = CHILD(n, 1); t = ast_for_exprlist(c, for_ch, Store); if (!t) @@ -1265,7 +1265,7 @@ if (NCH(n) == 5) { int j, n_ifs; asdl_seq *ifs; - + n = CHILD(n, 4); n_ifs = count_comp_ifs(c, n); if (n_ifs == -1) @@ -1279,7 +1279,7 @@ REQ(n, comp_iter); n = CHILD(n, 0); REQ(n, comp_if); - + expression = ast_for_expr(c, CHILD(n, 1)); if (!expression) return NULL; @@ -1302,13 +1302,13 @@ { expr_ty elt; asdl_seq *comps; - + assert(NCH(n) > 1); - + elt = ast_for_expr(c, CHILD(n, 0)); if (!elt) return NULL; - + comps = ast_for_comprehension(c, CHILD(n, 1)); if (!comps) return NULL; @@ -1327,10 +1327,10 @@ { expr_ty key, value; asdl_seq *comps; - + assert(NCH(n) > 3); REQ(CHILD(n, 1), COLON); - + key = ast_for_expr(c, CHILD(n, 0)); if (!key) return NULL; @@ -1338,11 +1338,11 @@ value = ast_for_expr(c, CHILD(n, 2)); if (!value) return NULL; - + comps = ast_for_comprehension(c, CHILD(n, 3)); if (!comps) return NULL; - + return DictComp(key, value, comps, LINENO(n), n->n_col_offset, c->c_arena); } @@ -1367,7 +1367,7 @@ | '{' [dictmaker] '}' | '`' testlist '`' | NAME | NUMBER | STRING+ */ node *ch = CHILD(n, 0); - + switch (TYPE(ch)) { case NAME: { /* All names start in Load context, but may later be @@ -1415,20 +1415,20 @@ } case LPAR: /* some parenthesized expressions */ ch = CHILD(n, 1); - + if (TYPE(ch) == RPAR) return Tuple(NULL, Load, LINENO(n), n->n_col_offset, c->c_arena); - + if (TYPE(ch) == yield_expr) return ast_for_expr(c, ch); - + return ast_for_testlist_comp(c, ch); case LSQB: /* list (or list comprehension) */ ch = CHILD(n, 1); - + if (TYPE(ch) == RSQB) return List(NULL, Load, LINENO(n), n->n_col_offset, c->c_arena); - + REQ(ch, listmaker); if (NCH(ch) == 1 || TYPE(CHILD(ch, 1)) == COMMA) { asdl_seq *elts = seq_for_testlist(c, ch); @@ -1477,14 +1477,14 @@ keys = asdl_seq_new(size, c->c_arena); if (!keys) return NULL; - + values = asdl_seq_new(size, c->c_arena); if (!values) return NULL; - + for (i = 0; i < NCH(ch); i += 4) { expr_ty expression; - + expression = ast_for_expr(c, CHILD(ch, i)); if (!expression) return NULL; @@ -1536,10 +1536,10 @@ if (NCH(n) == 1 && TYPE(ch) == test) { /* 'step' variable hold no significance in terms of being used over other vars */ - step = ast_for_expr(c, ch); + step = ast_for_expr(c, ch); if (!step) return NULL; - + return Index(step, c->c_arena); } @@ -1573,7 +1573,7 @@ ch = CHILD(n, NCH(n) - 1); if (TYPE(ch) == sliceop) { if (NCH(ch) == 1) { - /* + /* This is an extended slice (ie "x[::]") with no expression in the step field. We set this literally to "None" in order to disambiguate it from x[:]. (The interpreter might have to call @@ -1603,7 +1603,7 @@ ast_for_binop(struct compiling *c, const node *n) { /* Must account for a sequence of expressions. - How should A op B op C by represented? + How should A op B op C by represented? BinOp(BinOp(A, op, B), op, C). */ @@ -1641,10 +1641,10 @@ if (!tmp) return NULL; - tmp_result = BinOp(result, newoperator, tmp, + tmp_result = BinOp(result, newoperator, tmp, LINENO(next_oper), next_oper->n_col_offset, c->c_arena); - if (!tmp_result) + if (!tmp_result) return NULL; result = tmp_result; } @@ -1654,7 +1654,7 @@ static expr_ty ast_for_trailer(struct compiling *c, const node *n, expr_ty left_expr) { - /* trailer: '(' [arglist] ')' | '[' subscriptlist ']' | '.' NAME + /* trailer: '(' [arglist] ')' | '[' subscriptlist ']' | '.' NAME subscriptlist: subscript (',' subscript)* [','] subscript: '.' '.' '.' | test | [test] ':' [test] [sliceop] */ @@ -1685,7 +1685,7 @@ c->c_arena); } else { - /* The grammar is ambiguous here. The ambiguity is resolved + /* The grammar is ambiguous here. The ambiguity is resolved by treating the sequence as a tuple literal if there are no slice features. */ @@ -1822,7 +1822,7 @@ { /* handle the full range of simple expressions test: or_test ['if' or_test 'else' test] | lambdef - or_test: and_test ('or' and_test)* + or_test: and_test ('or' and_test)* and_test: not_test ('and' not_test)* not_test: 'not' not_test | comparison comparison: expr (comp_op expr)* @@ -1839,7 +1839,7 @@ to explicitly allow: [ x for x in lambda: 0, lambda: 1 ] (which would be ambiguous without these extra rules) - + old_test: or_test | old_lambdef old_lambdef: 'lambda' [vararglist] ':' old_test @@ -1919,7 +1919,7 @@ if (!expression) { return NULL; } - + asdl_seq_SET(ops, i / 2, newoperator); asdl_seq_SET(cmps, i / 2, expression); } @@ -1927,7 +1927,7 @@ if (!expression) { return NULL; } - + return Compare(expression, ops, cmps, LINENO(n), n->n_col_offset, c->c_arena); } @@ -2041,7 +2041,7 @@ if (!e) return NULL; asdl_seq_SET(args, nargs++, e); - } + } else if (TYPE(CHILD(ch, 1)) == comp_for) { e = ast_for_genexp(c, ch); if (!e) @@ -2054,7 +2054,7 @@ int k; char *tmp; - /* CHILD(ch, 0) is test, but must be an identifier? */ + /* CHILD(ch, 0) is test, but must be an identifier? */ e = ast_for_expr(c, CHILD(ch, 0)); if (!e) return NULL; @@ -2173,7 +2173,7 @@ ast_for_expr_stmt(struct compiling *c, const node *n) { REQ(n, expr_stmt); - /* expr_stmt: testlist (augassign (yield_expr|testlist) + /* expr_stmt: testlist (augassign (yield_expr|testlist) | ('=' (yield_expr|testlist))*) testlist: test (',' test)* [','] augassign: '+=' | '-=' | '*=' | '/=' | '%=' | '&=' | '|=' | '^=' @@ -2248,7 +2248,7 @@ e = ast_for_testlist(c, ch); /* set context to assign */ - if (!e) + if (!e) return NULL; if (!set_context(c, e, Store, CHILD(n, i))) @@ -2329,7 +2329,7 @@ ast_for_del_stmt(struct compiling *c, const node *n) { asdl_seq *expr_list; - + /* del_stmt: 'del' exprlist */ REQ(n, del_stmt); @@ -2413,7 +2413,7 @@ expr3 = ast_for_expr(c, CHILD(ch, 5)); if (!expr3) return NULL; - + return Raise(expr1, expr2, expr3, LINENO(n), n->n_col_offset, c->c_arena); } @@ -2569,7 +2569,7 @@ int idx, ndots = 0; alias_ty mod = NULL; identifier modname = NULL; - + /* Count the number of dots (for relative imports) and check for the optional module name */ for (idx = 1; idx < NCH(n); idx++) { @@ -2715,7 +2715,7 @@ expr2 = ast_for_expr(c, CHILD(n, 3)); if (!expr2) return NULL; - + return Assert(expr1, expr2, LINENO(n), n->n_col_offset, c->c_arena); } PyErr_Format(PyExc_SystemError, @@ -2742,7 +2742,7 @@ if (TYPE(CHILD(n, 0)) == simple_stmt) { n = CHILD(n, 0); /* simple_stmt always ends with a NEWLINE, - and may have a trailing SEMI + and may have a trailing SEMI */ end = NCH(n) - 1; if (TYPE(CHILD(n, end - 1)) == SEMI) @@ -2807,10 +2807,10 @@ expression = ast_for_expr(c, CHILD(n, 1)); if (!expression) return NULL; - suite_seq = ast_for_suite(c, CHILD(n, 3)); + suite_seq = ast_for_suite(c, CHILD(n, 3)); if (!suite_seq) return NULL; - + return If(expression, suite_seq, NULL, LINENO(n), n->n_col_offset, c->c_arena); } @@ -2868,8 +2868,8 @@ if (!suite_seq2) return NULL; - asdl_seq_SET(orelse, 0, - If(expression, suite_seq, suite_seq2, + asdl_seq_SET(orelse, 0, + If(expression, suite_seq, suite_seq2, LINENO(CHILD(n, NCH(n) - 6)), CHILD(n, NCH(n) - 6)->n_col_offset, c->c_arena)); @@ -2890,7 +2890,7 @@ return NULL; asdl_seq_SET(newobj, 0, - If(expression, suite_seq, orelse, + If(expression, suite_seq, orelse, LINENO(CHILD(n, off)), CHILD(n, off)->n_col_offset, c->c_arena)); orelse = newobj; @@ -3089,7 +3089,7 @@ ast_error(n, "malformed 'try' statement"); return NULL; } - + if (n_except > 0) { int i; stmt_ty except_st; @@ -3190,7 +3190,7 @@ /* classdef: 'class' NAME ['(' testlist ')'] ':' suite */ PyObject *classname; asdl_seq *bases, *s; - + REQ(n, classdef); if (!forbidden_check(c, n, STR(CHILD(n, 1)))) @@ -3378,17 +3378,12 @@ static PyObject * decode_unicode(struct compiling *c, const char *s, size_t len, int rawmode, const char *encoding) { - PyObject *v, *u; + PyObject *v; + PyObject *u = NULL; char *buf; char *p; const char *end; - if (encoding == NULL) { - buf = (char *)s; - u = NULL; - } else if (strcmp(encoding, "iso-8859-1") == 0) { - buf = (char *)s; - u = NULL; - } else { + if (encoding != NULL && strcmp(encoding, "iso-8859-1")) { /* check for integer overflow */ if (len > PY_SIZE_MAX / 6) return NULL; @@ -3478,7 +3473,7 @@ s++; len = strlen(s); if (len > INT_MAX) { - PyErr_SetString(PyExc_OverflowError, + PyErr_SetString(PyExc_OverflowError, "string to parse is too long"); return NULL; } From python-checkins at python.org Wed May 5 22:35:24 2010 From: python-checkins at python.org (brett.cannon) Date: Wed, 5 May 2010 22:35:24 +0200 (CEST) Subject: [Python-checkins] r80819 - python/trunk/Python/pystrtod.c Message-ID: <20100505203524.4CF6CEA03@mail.python.org> Author: brett.cannon Date: Wed May 5 22:35:24 2010 New Revision: 80819 Log: Remove an unnecessary variable assignment. Found using Clang's static analyzer. Modified: python/trunk/Python/pystrtod.c Modified: python/trunk/Python/pystrtod.c ============================================================================== --- python/trunk/Python/pystrtod.c (original) +++ python/trunk/Python/pystrtod.c Wed May 5 22:35:24 2010 @@ -1005,7 +1005,6 @@ /* shouldn't get here: Gay's code should always return something starting with a digit, an 'I', or 'N' */ strncpy(p, "ERR", 3); - p += 3; assert(0); } goto exit; From python-checkins at python.org Wed May 5 22:38:52 2010 From: python-checkins at python.org (brett.cannon) Date: Wed, 5 May 2010 22:38:52 +0200 (CEST) Subject: [Python-checkins] r80820 - python/trunk/Python/pythonrun.c Message-ID: <20100505203852.B5A8CEE9A9@mail.python.org> Author: brett.cannon Date: Wed May 5 22:38:52 2010 New Revision: 80820 Log: Change to a Py_XDECREF and fix some whitespace. Found using Clang's static analyzer. Modified: python/trunk/Python/pythonrun.c Modified: python/trunk/Python/pythonrun.c ============================================================================== --- python/trunk/Python/pythonrun.c (original) +++ python/trunk/Python/pythonrun.c Wed May 5 22:38:52 2010 @@ -138,7 +138,7 @@ PyThreadState *tstate; PyObject *bimod, *sysmod; char *p; - char *icodeset = NULL; /* On Windows, input codeset may theoretically + char *icodeset = NULL; /* On Windows, input codeset may theoretically differ from output codeset. */ char *codeset = NULL; char *errors = NULL; @@ -237,7 +237,7 @@ if (install_sigs) initsigs(); /* Signal handling stuff, including initintr() */ - + /* Initialize warnings. */ _PyWarnings_Init(); if (PySys_HasWarnOptions()) { @@ -339,7 +339,7 @@ sys_isatty = PyObject_CallMethod(sys_stream, "isatty", ""); if (!sys_isatty) PyErr_Clear(); - if ((overridden || + if ((overridden || (sys_isatty && PyObject_IsTrue(sys_isatty))) && PyFile_Check(sys_stream)) { if (!PyFile_SetEncodingAndErrors(sys_stream, codeset, errors)) @@ -351,7 +351,7 @@ sys_isatty = PyObject_CallMethod(sys_stream, "isatty", ""); if (!sys_isatty) PyErr_Clear(); - if((overridden || + if((overridden || (sys_isatty && PyObject_IsTrue(sys_isatty))) && PyFile_Check(sys_stream)) { if (!PyFile_SetEncodingAndErrors(sys_stream, codeset, errors)) @@ -701,7 +701,7 @@ if (bimod == NULL || PyDict_SetItemString(d, "__builtins__", bimod) != 0) Py_FatalError("can't add __builtins__ to __main__"); - Py_DECREF(bimod); + Py_XDECREF(bimod); } } @@ -1297,7 +1297,7 @@ PyArena *arena = PyArena_New(); if (arena == NULL) return NULL; - + mod = PyParser_ASTFromString(str, "", start, flags, arena); if (mod != NULL) ret = run_mod(mod, "", globals, locals, flags, arena); @@ -1314,7 +1314,7 @@ PyArena *arena = PyArena_New(); if (arena == NULL) return NULL; - + mod = PyParser_ASTFromFile(fp, filename, start, 0, 0, flags, NULL, arena); if (closeit) @@ -1804,7 +1804,7 @@ alloca(PYOS_STACK_MARGIN * sizeof(void*)); return 0; } __except (GetExceptionCode() == STATUS_STACK_OVERFLOW ? - EXCEPTION_EXECUTE_HANDLER : + EXCEPTION_EXECUTE_HANDLER : EXCEPTION_CONTINUE_SEARCH) { int errcode = _resetstkoflw(); if (errcode == 0) From python-checkins at python.org Wed May 5 22:50:03 2010 From: python-checkins at python.org (brett.cannon) Date: Wed, 5 May 2010 22:50:03 +0200 (CEST) Subject: [Python-checkins] r80821 - python/trunk/Python/strtod.c Message-ID: <20100505205003.4F915EE9AA@mail.python.org> Author: brett.cannon Date: Wed May 5 22:50:03 2010 New Revision: 80821 Log: Explicitly add stdio.h and string.h to make strtod.c work standalone. Found using Clang's static analyzer. Modified: python/trunk/Python/strtod.c Modified: python/trunk/Python/strtod.c ============================================================================== --- python/trunk/Python/strtod.c (original) +++ python/trunk/Python/strtod.c Wed May 5 22:50:03 2010 @@ -1,3 +1,6 @@ +#include +#include + #include "pyconfig.h" /* comp.sources.misc strtod(), as posted in comp.lang.tcl, @@ -14,7 +17,7 @@ Defines: double strtod (char *str, char**ptr) */ -/* This is an implementation of the strtod() function described in the +/* This is an implementation of the strtod() function described in the System V manuals, with a different name to avoid linker problems. All that str2dbl() does itself is check that the argument is well-formed and is in range. It leaves the work of conversion to atof(), which is @@ -29,7 +32,7 @@ of strtod(), and if we give this one away maybe someone will look for mistakes in it and fix them for us (:-). */ - + /* The following constants are machine-specific. MD{MIN,MAX}EXPT are integers and MD{MIN,MAX}FRAC are strings such that 0.${MDMAXFRAC}e${MDMAXEXPT} is the largest representable double, @@ -74,10 +77,10 @@ sign = 1; if (*sp == '-') sign -= 2, sp++; dotseen = 0, scale = 0; - dp = buffer; + dp = buffer; *dp++ = '0'; *dp++ = '.'; buforg = dp, buflim = buffer+48; - for (save = sp; c = *sp; sp++) + for (save = sp; (c = *sp); sp++) if (c == '.') { if (dotseen) break; dotseen++; @@ -106,7 +109,7 @@ errno = EDOM; /* what should this be? */ return ZERO; } - + while (dp > buforg && dp[-1] == '0') --dp; if (dp == buforg) *dp++ = '0'; *dp = '\0'; @@ -128,7 +131,7 @@ if ((unsigned)(c-'0') > (unsigned)('9'-'0')) break; while (c == '0') c = *sp++; for (; (unsigned)(c-'0') <= (unsigned)('9'-'0'); c = *sp++) - expt = expt*10 + c-'0'; + expt = expt*10 + c-'0'; if (esign < 0) expt = -expt; save = sp-1; } while (0); From python-checkins at python.org Wed May 5 22:53:20 2010 From: python-checkins at python.org (brett.cannon) Date: Wed, 5 May 2010 22:53:20 +0200 (CEST) Subject: [Python-checkins] r80822 - python/trunk/Python/traceback.c Message-ID: <20100505205320.3C61DC8E0@mail.python.org> Author: brett.cannon Date: Wed May 5 22:53:20 2010 New Revision: 80822 Log: Remove an unneeded variable assignment. Found using Clang's static analyzer. Modified: python/trunk/Python/traceback.c Modified: python/trunk/Python/traceback.c ============================================================================== --- python/trunk/Python/traceback.c (original) +++ python/trunk/Python/traceback.c Wed May 5 22:53:20 2010 @@ -161,7 +161,6 @@ strcpy(namebuf+len, tail); xfp = fopen(namebuf, "r" PY_STDIOTEXTMODE); if (xfp != NULL) { - filename = namebuf; break; } } From python-checkins at python.org Wed May 5 22:54:53 2010 From: python-checkins at python.org (brett.cannon) Date: Wed, 5 May 2010 22:54:53 +0200 (CEST) Subject: [Python-checkins] r80823 - python/trunk/Misc/NEWS Message-ID: <20100505205453.29DC0ECA4@mail.python.org> Author: brett.cannon Date: Wed May 5 22:54:53 2010 New Revision: 80823 Log: Mention how Clang's static anaylzer was run over Objects/ and Python/. Modified: python/trunk/Misc/NEWS Modified: python/trunk/Misc/NEWS ============================================================================== --- python/trunk/Misc/NEWS (original) +++ python/trunk/Misc/NEWS Wed May 5 22:54:53 2010 @@ -12,6 +12,8 @@ Core and Builtins ----------------- +- Run Clang 2.7's static analyzer for Objects/ and Python/ . + - Issue #1533: fix inconsistency in range function argument processing: any non-float non-integer argument is now converted to an integer (if possible) using its __int__ method. Previously, only From victor.stinner at haypocalc.com Wed May 5 22:58:51 2010 From: victor.stinner at haypocalc.com (Victor Stinner) Date: Wed, 5 May 2010 22:58:51 +0200 Subject: [Python-checkins] r80816 - python/trunk/Python/getcwd.c In-Reply-To: <20100505202658.BA843EE9A9@mail.python.org> References: <20100505202658.BA843EE9A9@mail.python.org> Message-ID: <201005052258.51480.victor.stinner@haypocalc.com> Le mercredi 05 mai 2010 22:26:58, brett.cannon a ?crit : > Author: brett.cannon > Date: Wed May 5 22:26:58 2010 > New Revision: 80816 > > Log: > Remove an unneeded variable and fix a little whitespace. Please, could you try to fix one thing by commit. I mean: one commit for the variable, and another for the whitespaces. > Found using Clang's static analyzer. Whitespaces are not related to the static analyzer. It would be better to fix all whitespaces in ONE unique commit on the whole Python project, instead of fix some whitespaces in some files. Antoine is working on a tool to uniformize the indentation (and spaces) of the C files. -- Victor Stinner http://www.haypocalc.com/ From eric at trueblade.com Wed May 5 22:58:11 2010 From: eric at trueblade.com (Eric Smith) Date: Wed, 05 May 2010 16:58:11 -0400 Subject: [Python-checkins] r80819 - python/trunk/Python/pystrtod.c In-Reply-To: <20100505203524.4CF6CEA03@mail.python.org> References: <20100505203524.4CF6CEA03@mail.python.org> Message-ID: <4BE1DBE3.2020600@trueblade.com> I dislike this change. If for some reason we ever decide to make this condition not be an error (by removing the assert) then the deleted line is needed. What's the harm of leaving it in? If any change must be made (and I don't think it does), I'd comment out both the strncpy and the increment. And put in a comment explaining why they've been commented out. Eric. brett.cannon wrote: > Author: brett.cannon > Date: Wed May 5 22:35:24 2010 > New Revision: 80819 > > Log: > Remove an unnecessary variable assignment. > > Found using Clang's static analyzer. > > > Modified: > python/trunk/Python/pystrtod.c > > Modified: python/trunk/Python/pystrtod.c > ============================================================================== > --- python/trunk/Python/pystrtod.c (original) > +++ python/trunk/Python/pystrtod.c Wed May 5 22:35:24 2010 > @@ -1005,7 +1005,6 @@ > /* shouldn't get here: Gay's code should always return > something starting with a digit, an 'I', or 'N' */ > strncpy(p, "ERR", 3); > - p += 3; > assert(0); > } > goto exit; > _______________________________________________ > Python-checkins mailing list > Python-checkins at python.org > http://mail.python.org/mailman/listinfo/python-checkins > From eric at trueblade.com Wed May 5 23:12:40 2010 From: eric at trueblade.com (Eric Smith) Date: Wed, 05 May 2010 17:12:40 -0400 Subject: [Python-checkins] r80819 - python/trunk/Python/pystrtod.c In-Reply-To: <4BE1DBE3.2020600@trueblade.com> References: <20100505203524.4CF6CEA03@mail.python.org> <4BE1DBE3.2020600@trueblade.com> Message-ID: <4BE1DF48.60609@trueblade.com> Actually, Clang must have been run with assert defined. Because if the assert is compiled out, then the assignment is needed. Eric. Eric Smith wrote: > I dislike this change. If for some reason we ever decide to make this > condition not be an error (by removing the assert) then the deleted line > is needed. What's the harm of leaving it in? > > If any change must be made (and I don't think it does), I'd comment out > both the strncpy and the increment. And put in a comment explaining why > they've been commented out. > > Eric. > > brett.cannon wrote: >> Author: brett.cannon >> Date: Wed May 5 22:35:24 2010 >> New Revision: 80819 >> >> Log: >> Remove an unnecessary variable assignment. >> >> Found using Clang's static analyzer. >> >> >> Modified: >> python/trunk/Python/pystrtod.c >> >> Modified: python/trunk/Python/pystrtod.c >> ============================================================================== >> >> --- python/trunk/Python/pystrtod.c (original) >> +++ python/trunk/Python/pystrtod.c Wed May 5 22:35:24 2010 >> @@ -1005,7 +1005,6 @@ >> /* shouldn't get here: Gay's code should always return >> something starting with a digit, an 'I', or 'N' */ >> strncpy(p, "ERR", 3); >> - p += 3; >> assert(0); >> } >> goto exit; >> _______________________________________________ >> Python-checkins mailing list >> Python-checkins at python.org >> http://mail.python.org/mailman/listinfo/python-checkins >> > > _______________________________________________ > Python-checkins mailing list > Python-checkins at python.org > http://mail.python.org/mailman/listinfo/python-checkins > From python-checkins at python.org Wed May 5 23:43:58 2010 From: python-checkins at python.org (victor.stinner) Date: Wed, 5 May 2010 23:43:58 +0200 (CEST) Subject: [Python-checkins] r80824 - in python/branches/py3k: Doc/library/tarfile.rst Lib/tarfile.py Lib/test/test_tarfile.py Misc/NEWS Message-ID: <20100505214358.072A7EE9C9@mail.python.org> Author: victor.stinner Date: Wed May 5 23:43:57 2010 New Revision: 80824 Log: Issue #8390: tarfile uses surrogateespace as the default error handler (instead of replace in read mode or strict in write mode) Modified: python/branches/py3k/Doc/library/tarfile.rst python/branches/py3k/Lib/tarfile.py python/branches/py3k/Lib/test/test_tarfile.py python/branches/py3k/Misc/NEWS Modified: python/branches/py3k/Doc/library/tarfile.rst ============================================================================== --- python/branches/py3k/Doc/library/tarfile.rst (original) +++ python/branches/py3k/Doc/library/tarfile.rst Wed May 5 23:43:57 2010 @@ -218,7 +218,7 @@ .. versionadded:: 3.2 Added support for the context manager protocol. -.. class:: TarFile(name=None, mode='r', fileobj=None, format=DEFAULT_FORMAT, tarinfo=TarInfo, dereference=False, ignore_zeros=False, encoding=ENCODING, errors=None, pax_headers=None, debug=0, errorlevel=0) +.. class:: TarFile(name=None, mode='r', fileobj=None, format=DEFAULT_FORMAT, tarinfo=TarInfo, dereference=False, ignore_zeros=False, encoding=ENCODING, errors='surrogateescape', pax_headers=None, debug=0, errorlevel=0) All following arguments are optional and can be accessed as instance attributes as well. @@ -267,6 +267,9 @@ to be handled. The default settings will work for most users. See section :ref:`tar-unicode` for in-depth information. + .. versionchanged:: 3.2 + Use ``'surrogateescape'`` as the default for the *errors* argument. + The *pax_headers* argument is an optional dictionary of strings which will be added as a pax global header if *format* is :const:`PAX_FORMAT`. @@ -449,11 +452,14 @@ a :class:`TarInfo` object. -.. method:: TarInfo.tobuf(format=DEFAULT_FORMAT, encoding=ENCODING, errors='strict') +.. method:: TarInfo.tobuf(format=DEFAULT_FORMAT, encoding=ENCODING, errors='surrogateescape') Create a string buffer from a :class:`TarInfo` object. For information on the arguments see the constructor of the :class:`TarFile` class. + .. versionchanged:: 3.2 + Use ``'surrogateescape'`` as the default for the *errors* argument. + A ``TarInfo`` object has the following public data attributes: @@ -701,11 +707,10 @@ appropriately, this conversion may fail. The *errors* argument defines how characters are treated that cannot be -converted. Possible values are listed in section :ref:`codec-base-classes`. In -read mode the default scheme is ``'replace'``. This avoids unexpected -:exc:`UnicodeError` exceptions and guarantees that an archive can always be -read. In write mode the default value for *errors* is ``'strict'``. This -ensures that name information is not altered unnoticed. +converted. Possible values are listed in section :ref:`codec-base-classes`. +The default scheme is ``'surrogateescape'`` which Python also uses for its +file system calls, see :ref:`os-filenames`. In case of writing :const:`PAX_FORMAT` archives, *encoding* is ignored because -non-ASCII metadata is stored using *UTF-8*. +non-ASCII metadata is stored using *UTF-8*. Storing surrogate characters is not +possible and will raise a :exc:`UnicodeEncodeError`. Modified: python/branches/py3k/Lib/tarfile.py ============================================================================== --- python/branches/py3k/Lib/tarfile.py (original) +++ python/branches/py3k/Lib/tarfile.py Wed May 5 23:43:57 2010 @@ -978,7 +978,7 @@ return info - def tobuf(self, format=DEFAULT_FORMAT, encoding=ENCODING, errors="strict"): + def tobuf(self, format=DEFAULT_FORMAT, encoding=ENCODING, errors="surrogateescape"): """Return a tar header as a string of 512 byte blocks. """ info = self.get_info() @@ -1490,7 +1490,7 @@ def __init__(self, name=None, mode="r", fileobj=None, format=None, tarinfo=None, dereference=None, ignore_zeros=None, encoding=None, - errors=None, pax_headers=None, debug=None, errorlevel=None): + errors="surrogateescape", pax_headers=None, debug=None, errorlevel=None): """Open an (uncompressed) tar archive `name'. `mode' is either 'r' to read from an existing archive, 'a' to append data to an existing file or 'w' to create a new file overwriting an existing one. `mode' @@ -1531,13 +1531,7 @@ self.ignore_zeros = ignore_zeros if encoding is not None: self.encoding = encoding - - if errors is not None: - self.errors = errors - elif mode == "r": - self.errors = "replace" - else: - self.errors = "strict" + self.errors = errors if pax_headers is not None and self.format == PAX_FORMAT: self.pax_headers = pax_headers Modified: python/branches/py3k/Lib/test/test_tarfile.py ============================================================================== --- python/branches/py3k/Lib/test/test_tarfile.py (original) +++ python/branches/py3k/Lib/test/test_tarfile.py Wed May 5 23:43:57 2010 @@ -1118,8 +1118,8 @@ if self.format != tarfile.PAX_FORMAT: tar = tarfile.open(tmpname, encoding="ascii") t = tar.getmember("foo") - self.assertEqual(t.uname, "\ufffd\ufffd\ufffd") - self.assertEqual(t.gname, "\ufffd\ufffd\ufffd") + self.assertEqual(t.uname, "\udce4\udcf6\udcfc") + self.assertEqual(t.gname, "\udce4\udcf6\udcfc") class GNUUnicodeTest(UstarUnicodeTest): Modified: python/branches/py3k/Misc/NEWS ============================================================================== --- python/branches/py3k/Misc/NEWS (original) +++ python/branches/py3k/Misc/NEWS Wed May 5 23:43:57 2010 @@ -348,6 +348,9 @@ Library ------- +- Issue #8390: tarfile uses surrogateespace as the default error handler + (instead of replace in read mode or strict in write mode) + - Issue #7755: Use an unencumbered audio file for tests. - Issue #8621: uuid.uuid4() returned the same sequence of values in the From python-checkins at python.org Wed May 5 23:47:39 2010 From: python-checkins at python.org (victor.stinner) Date: Wed, 5 May 2010 23:47:39 +0200 (CEST) Subject: [Python-checkins] r80825 - python/branches/release31-maint Message-ID: <20100505214739.A2F91EE9CF@mail.python.org> Author: victor.stinner Date: Wed May 5 23:47:39 2010 New Revision: 80825 Log: Blocked revisions 80824 via svnmerge ........ r80824 | victor.stinner | 2010-05-05 23:43:57 +0200 (mer., 05 mai 2010) | 3 lines Issue #8390: tarfile uses surrogateespace as the default error handler (instead of replace in read mode or strict in write mode) ........ Modified: python/branches/release31-maint/ (props changed) From python-checkins at python.org Wed May 5 23:52:39 2010 From: python-checkins at python.org (mark.dickinson) Date: Wed, 5 May 2010 23:52:39 +0200 (CEST) Subject: [Python-checkins] r80826 - python/trunk/Doc/library/numbers.rst Message-ID: <20100505215239.3EC6CEE9CF@mail.python.org> Author: mark.dickinson Date: Wed May 5 23:52:39 2010 New Revision: 80826 Log: Issue 8628: fix incorrect documentation for numbers.Complex.imag. Modified: python/trunk/Doc/library/numbers.rst Modified: python/trunk/Doc/library/numbers.rst ============================================================================== --- python/trunk/Doc/library/numbers.rst (original) +++ python/trunk/Doc/library/numbers.rst Wed May 5 23:52:39 2010 @@ -31,11 +31,11 @@ .. attribute:: real - Abstract. Retrieves the :class:`Real` component of this number. + Abstract. Retrieves the real component of this number. .. attribute:: imag - Abstract. Retrieves the :class:`Real` component of this number. + Abstract. Retrieves the imaginary component of this number. .. method:: conjugate() From python-checkins at python.org Wed May 5 23:53:32 2010 From: python-checkins at python.org (mark.dickinson) Date: Wed, 5 May 2010 23:53:32 +0200 (CEST) Subject: [Python-checkins] r80827 - in python/branches/release26-maint: Doc/library/numbers.rst Message-ID: <20100505215332.2630EEE9CF@mail.python.org> Author: mark.dickinson Date: Wed May 5 23:53:32 2010 New Revision: 80827 Log: Merged revisions 80826 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r80826 | mark.dickinson | 2010-05-05 22:52:39 +0100 (Wed, 05 May 2010) | 1 line Issue 8628: fix incorrect documentation for numbers.Complex.imag. ........ Modified: python/branches/release26-maint/ (props changed) python/branches/release26-maint/Doc/library/numbers.rst Modified: python/branches/release26-maint/Doc/library/numbers.rst ============================================================================== --- python/branches/release26-maint/Doc/library/numbers.rst (original) +++ python/branches/release26-maint/Doc/library/numbers.rst Wed May 5 23:53:32 2010 @@ -31,11 +31,11 @@ .. attribute:: real - Abstract. Retrieves the :class:`Real` component of this number. + Abstract. Retrieves the real component of this number. .. attribute:: imag - Abstract. Retrieves the :class:`Real` component of this number. + Abstract. Retrieves the imaginary component of this number. .. method:: conjugate() From python-checkins at python.org Wed May 5 23:54:19 2010 From: python-checkins at python.org (mark.dickinson) Date: Wed, 5 May 2010 23:54:19 +0200 (CEST) Subject: [Python-checkins] r80828 - in python/branches/py3k: Doc/library/numbers.rst Message-ID: <20100505215419.08E1FEE9CF@mail.python.org> Author: mark.dickinson Date: Wed May 5 23:54:18 2010 New Revision: 80828 Log: Merged revisions 80826 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r80826 | mark.dickinson | 2010-05-05 22:52:39 +0100 (Wed, 05 May 2010) | 1 line Issue 8628: fix incorrect documentation for numbers.Complex.imag. ........ Modified: python/branches/py3k/ (props changed) python/branches/py3k/Doc/library/numbers.rst Modified: python/branches/py3k/Doc/library/numbers.rst ============================================================================== --- python/branches/py3k/Doc/library/numbers.rst (original) +++ python/branches/py3k/Doc/library/numbers.rst Wed May 5 23:54:18 2010 @@ -29,11 +29,11 @@ .. attribute:: real - Abstract. Retrieves the :class:`Real` component of this number. + Abstract. Retrieves the real component of this number. .. attribute:: imag - Abstract. Retrieves the :class:`Real` component of this number. + Abstract. Retrieves the imaginary component of this number. .. method:: conjugate() From python-checkins at python.org Wed May 5 23:55:12 2010 From: python-checkins at python.org (mark.dickinson) Date: Wed, 5 May 2010 23:55:12 +0200 (CEST) Subject: [Python-checkins] r80829 - in python/branches/release31-maint: Doc/library/numbers.rst Message-ID: <20100505215512.19955EE9CF@mail.python.org> Author: mark.dickinson Date: Wed May 5 23:55:11 2010 New Revision: 80829 Log: Merged revisions 80828 via svnmerge from svn+ssh://pythondev at svn.python.org/python/branches/py3k ................ r80828 | mark.dickinson | 2010-05-05 22:54:18 +0100 (Wed, 05 May 2010) | 9 lines Merged revisions 80826 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r80826 | mark.dickinson | 2010-05-05 22:52:39 +0100 (Wed, 05 May 2010) | 1 line Issue 8628: fix incorrect documentation for numbers.Complex.imag. ........ ................ Modified: python/branches/release31-maint/ (props changed) python/branches/release31-maint/Doc/library/numbers.rst Modified: python/branches/release31-maint/Doc/library/numbers.rst ============================================================================== --- python/branches/release31-maint/Doc/library/numbers.rst (original) +++ python/branches/release31-maint/Doc/library/numbers.rst Wed May 5 23:55:11 2010 @@ -29,11 +29,11 @@ .. attribute:: real - Abstract. Retrieves the :class:`Real` component of this number. + Abstract. Retrieves the real component of this number. .. attribute:: imag - Abstract. Retrieves the :class:`Real` component of this number. + Abstract. Retrieves the imaginary component of this number. .. method:: conjugate() From python-checkins at python.org Thu May 6 00:15:31 2010 From: python-checkins at python.org (tarek.ziade) Date: Thu, 6 May 2010 00:15:31 +0200 (CEST) Subject: [Python-checkins] r80830 - in python/trunk: Lib/shutil.py Lib/test/test_shutil.py Misc/NEWS Message-ID: <20100505221531.6AD36EEA58@mail.python.org> Author: tarek.ziade Date: Thu May 6 00:15:31 2010 New Revision: 80830 Log: Fixed #4265: shutil.copyfile() was leaking file descriptors when disk fills Modified: python/trunk/Lib/shutil.py python/trunk/Lib/test/test_shutil.py python/trunk/Misc/NEWS Modified: python/trunk/Lib/shutil.py ============================================================================== --- python/trunk/Lib/shutil.py (original) +++ python/trunk/Lib/shutil.py Thu May 6 00:15:31 2010 @@ -79,15 +79,9 @@ # XXX What about other special files? (sockets, devices...) if stat.S_ISFIFO(st.st_mode): raise SpecialFileError("`%s` is a named pipe" % fn) - try: - fsrc = open(src, 'rb') - fdst = open(dst, 'wb') - copyfileobj(fsrc, fdst) - finally: - if fdst: - fdst.close() - if fsrc: - fsrc.close() + with open(src, 'rb') as fsrc: + with open(dst, 'wb') as fdst: + copyfileobj(fsrc, fdst) def copymode(src, dst): """Copy mode bits from src to dst""" Modified: python/trunk/Lib/test/test_shutil.py ============================================================================== --- python/trunk/Lib/test/test_shutil.py (original) +++ python/trunk/Lib/test/test_shutil.py Thu May 6 00:15:31 2010 @@ -696,8 +696,113 @@ finally: shutil.rmtree(TESTFN, ignore_errors=True) + +class TestCopyFile(unittest.TestCase): + + _delete = False + + class Faux(object): + _entered = False + _exited_with = None + _raised = False + def __init__(self, raise_in_exit=False, suppress_at_exit=True): + self._raise_in_exit = raise_in_exit + self._suppress_at_exit = suppress_at_exit + def read(self, *args): + return '' + def __enter__(self): + self._entered = True + def __exit__(self, exc_type, exc_val, exc_tb): + self._exited_with = exc_type, exc_val, exc_tb + if self._raise_in_exit: + self._raised = True + raise IOError("Cannot close") + return self._suppress_at_exit + + def tearDown(self): + if self._delete: + del shutil.open + + def _set_shutil_open(self, func): + shutil.open = func + self._delete = True + + def test_w_source_open_fails(self): + def _open(filename, mode='r'): + if filename == 'srcfile': + raise IOError('Cannot open "srcfile"') + assert 0 # shouldn't reach here. + + self._set_shutil_open(_open) + + self.assertRaises(IOError, shutil.copyfile, 'srcfile', 'destfile') + + def test_w_dest_open_fails(self): + + srcfile = self.Faux() + + def _open(filename, mode='r'): + if filename == 'srcfile': + return srcfile + if filename == 'destfile': + raise IOError('Cannot open "destfile"') + assert 0 # shouldn't reach here. + + self._set_shutil_open(_open) + + shutil.copyfile('srcfile', 'destfile') + self.failUnless(srcfile._entered) + self.failUnless(srcfile._exited_with[0] is IOError) + self.assertEqual(srcfile._exited_with[1].args, + ('Cannot open "destfile"',)) + + def test_w_dest_close_fails(self): + + srcfile = self.Faux() + destfile = self.Faux(True) + + def _open(filename, mode='r'): + if filename == 'srcfile': + return srcfile + if filename == 'destfile': + return destfile + assert 0 # shouldn't reach here. + + self._set_shutil_open(_open) + + shutil.copyfile('srcfile', 'destfile') + self.failUnless(srcfile._entered) + self.failUnless(destfile._entered) + self.failUnless(destfile._raised) + self.failUnless(srcfile._exited_with[0] is IOError) + self.assertEqual(srcfile._exited_with[1].args, + ('Cannot close',)) + + def test_w_source_close_fails(self): + + srcfile = self.Faux(True) + destfile = self.Faux() + + def _open(filename, mode='r'): + if filename == 'srcfile': + return srcfile + if filename == 'destfile': + return destfile + assert 0 # shouldn't reach here. + + self._set_shutil_open(_open) + + self.assertRaises(IOError, + shutil.copyfile, 'srcfile', 'destfile') + self.failUnless(srcfile._entered) + self.failUnless(destfile._entered) + self.failIf(destfile._raised) + self.failUnless(srcfile._exited_with[0] is None) + self.failUnless(srcfile._raised) + + def test_main(): - test_support.run_unittest(TestShutil, TestMove) + test_support.run_unittest(TestShutil, TestMove, TestCopyFile) if __name__ == '__main__': test_main() Modified: python/trunk/Misc/NEWS ============================================================================== --- python/trunk/Misc/NEWS (original) +++ python/trunk/Misc/NEWS Thu May 6 00:15:31 2010 @@ -41,6 +41,9 @@ Library ------- +- Issue #4265: shutil.copyfile() was leaking file descriptors when disk fills. + Patch by Tres Seaver. + - Issue #7755: Use an unencumbered audio file for tests. - Issue #8621: uuid.uuid4() returned the same sequence of values in the From python-checkins at python.org Thu May 6 00:21:13 2010 From: python-checkins at python.org (tarek.ziade) Date: Thu, 6 May 2010 00:21:13 +0200 (CEST) Subject: [Python-checkins] r80831 - in python/branches/release26-maint: Lib/shutil.py Lib/test/test_shutil.py Misc/NEWS Message-ID: <20100505222113.5F6E9DE2D@mail.python.org> Author: tarek.ziade Date: Thu May 6 00:21:13 2010 New Revision: 80831 Log: Merged revisions 80830 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r80830 | tarek.ziade | 2010-05-06 00:15:31 +0200 (Thu, 06 May 2010) | 1 line Fixed #4265: shutil.copyfile() was leaking file descriptors when disk fills ........ Modified: python/branches/release26-maint/ (props changed) python/branches/release26-maint/Lib/shutil.py python/branches/release26-maint/Lib/test/test_shutil.py python/branches/release26-maint/Misc/NEWS Modified: python/branches/release26-maint/Lib/shutil.py ============================================================================== --- python/branches/release26-maint/Lib/shutil.py (original) +++ python/branches/release26-maint/Lib/shutil.py Thu May 6 00:21:13 2010 @@ -45,19 +45,11 @@ def copyfile(src, dst): """Copy data from src to dst""" if _samefile(src, dst): - raise Error, "`%s` and `%s` are the same file" % (src, dst) + raise Error("`%s` and `%s` are the same file" % (src, dst)) - fsrc = None - fdst = None - try: - fsrc = open(src, 'rb') - fdst = open(dst, 'wb') - copyfileobj(fsrc, fdst) - finally: - if fdst: - fdst.close() - if fsrc: - fsrc.close() + with open(src, 'rb') as fsrc: + with open(dst, 'wb') as fdst: + copyfileobj(fsrc, fdst) def copymode(src, dst): """Copy mode bits from src to dst""" Modified: python/branches/release26-maint/Lib/test/test_shutil.py ============================================================================== --- python/branches/release26-maint/Lib/test/test_shutil.py (original) +++ python/branches/release26-maint/Lib/test/test_shutil.py Thu May 6 00:21:13 2010 @@ -367,8 +367,113 @@ finally: shutil.rmtree(TESTFN, ignore_errors=True) + +class TestCopyFile(unittest.TestCase): + + _delete = False + + class Faux(object): + _entered = False + _exited_with = None + _raised = False + def __init__(self, raise_in_exit=False, suppress_at_exit=True): + self._raise_in_exit = raise_in_exit + self._suppress_at_exit = suppress_at_exit + def read(self, *args): + return '' + def __enter__(self): + self._entered = True + def __exit__(self, exc_type, exc_val, exc_tb): + self._exited_with = exc_type, exc_val, exc_tb + if self._raise_in_exit: + self._raised = True + raise IOError("Cannot close") + return self._suppress_at_exit + + def tearDown(self): + if self._delete: + del shutil.open + + def _set_shutil_open(self, func): + shutil.open = func + self._delete = True + + def test_w_source_open_fails(self): + def _open(filename, mode='r'): + if filename == 'srcfile': + raise IOError('Cannot open "srcfile"') + assert 0 # shouldn't reach here. + + self._set_shutil_open(_open) + + self.assertRaises(IOError, shutil.copyfile, 'srcfile', 'destfile') + + def test_w_dest_open_fails(self): + + srcfile = self.Faux() + + def _open(filename, mode='r'): + if filename == 'srcfile': + return srcfile + if filename == 'destfile': + raise IOError('Cannot open "destfile"') + assert 0 # shouldn't reach here. + + self._set_shutil_open(_open) + + shutil.copyfile('srcfile', 'destfile') + self.failUnless(srcfile._entered) + self.failUnless(srcfile._exited_with[0] is IOError) + self.assertEqual(srcfile._exited_with[1].args, + ('Cannot open "destfile"',)) + + def test_w_dest_close_fails(self): + + srcfile = self.Faux() + destfile = self.Faux(True) + + def _open(filename, mode='r'): + if filename == 'srcfile': + return srcfile + if filename == 'destfile': + return destfile + assert 0 # shouldn't reach here. + + self._set_shutil_open(_open) + + shutil.copyfile('srcfile', 'destfile') + self.failUnless(srcfile._entered) + self.failUnless(destfile._entered) + self.failUnless(destfile._raised) + self.failUnless(srcfile._exited_with[0] is IOError) + self.assertEqual(srcfile._exited_with[1].args, + ('Cannot close',)) + + def test_w_source_close_fails(self): + + srcfile = self.Faux(True) + destfile = self.Faux() + + def _open(filename, mode='r'): + if filename == 'srcfile': + return srcfile + if filename == 'destfile': + return destfile + assert 0 # shouldn't reach here. + + self._set_shutil_open(_open) + + self.assertRaises(IOError, + shutil.copyfile, 'srcfile', 'destfile') + self.failUnless(srcfile._entered) + self.failUnless(destfile._entered) + self.failIf(destfile._raised) + self.failUnless(srcfile._exited_with[0] is None) + self.failUnless(srcfile._raised) + + def test_main(): - test_support.run_unittest(TestShutil, TestMove) + test_support.run_unittest(TestShutil, TestMove, TestCopyFile) if __name__ == '__main__': test_main() Modified: python/branches/release26-maint/Misc/NEWS ============================================================================== --- python/branches/release26-maint/Misc/NEWS (original) +++ python/branches/release26-maint/Misc/NEWS Thu May 6 00:21:13 2010 @@ -33,6 +33,9 @@ Library ------- +- Issue #4265: shutil.copyfile() was leaking file descriptors when disk fills. + Patch by Tres Seaver. + - Issue #8621: uuid.uuid4() returned the same sequence of values in the parent and any children created using ``os.fork`` on MacOS X 10.6. From python-checkins at python.org Thu May 6 00:23:59 2010 From: python-checkins at python.org (mark.dickinson) Date: Thu, 6 May 2010 00:23:59 +0200 (CEST) Subject: [Python-checkins] r80832 - in python/trunk: Misc/NEWS configure configure.in Message-ID: <20100505222359.01F2AC8D8@mail.python.org> Author: mark.dickinson Date: Thu May 6 00:23:58 2010 New Revision: 80832 Log: Issue #8625: Turn off gcc optimization in debug builds. Modified: python/trunk/Misc/NEWS python/trunk/configure python/trunk/configure.in Modified: python/trunk/Misc/NEWS ============================================================================== --- python/trunk/Misc/NEWS (original) +++ python/trunk/Misc/NEWS Thu May 6 00:23:58 2010 @@ -191,6 +191,11 @@ Build ----- +- Issue #8625: Turn off optimization in --with-pydebug builds with gcc. + (Optimization was unintentionally turned on in gcc --with-pydebug builds in + 2.7 beta1 as a result of the issue #1628484 fix, combined with autoconf's + strange choice of default CFLAGS produced by AC_PROG_CC for gcc.) + - Issue #8509: Fix quoting in help strings and code snippets in configure.in. - Issue #3646: It is now easily possible to install a Python framework into Modified: python/trunk/configure ============================================================================== --- python/trunk/configure (original) +++ python/trunk/configure Thu May 6 00:23:58 2010 @@ -1,5 +1,5 @@ #! /bin/sh -# From configure.in Revision: 80647 . +# From configure.in Revision: 80665 . # Guess values for system-dependent variables and create Makefiles. # Generated by GNU Autoconf 2.61 for python 2.7. # @@ -4659,7 +4659,7 @@ if test "$Py_DEBUG" = 'true' ; then # Optimization messes up debuggers, so turn it off for # debug builds. - OPT="-g -Wall $STRICT_PROTO" + OPT="-g -O0 -Wall $STRICT_PROTO" else OPT="-g $WRAP -O3 -Wall $STRICT_PROTO" fi Modified: python/trunk/configure.in ============================================================================== --- python/trunk/configure.in (original) +++ python/trunk/configure.in Thu May 6 00:23:58 2010 @@ -942,7 +942,7 @@ if test "$Py_DEBUG" = 'true' ; then # Optimization messes up debuggers, so turn it off for # debug builds. - OPT="-g -Wall $STRICT_PROTO" + OPT="-g -O0 -Wall $STRICT_PROTO" else OPT="-g $WRAP -O3 -Wall $STRICT_PROTO" fi From python-checkins at python.org Thu May 6 00:27:31 2010 From: python-checkins at python.org (tarek.ziade) Date: Thu, 6 May 2010 00:27:31 +0200 (CEST) Subject: [Python-checkins] r80833 - in python/branches/py3k: Lib/shutil.py Lib/test/test_shutil.py Misc/NEWS Message-ID: <20100505222731.68D1FEE9CB@mail.python.org> Author: tarek.ziade Date: Thu May 6 00:27:31 2010 New Revision: 80833 Log: Merged revisions 80830 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r80830 | tarek.ziade | 2010-05-06 00:15:31 +0200 (Thu, 06 May 2010) | 1 line Fixed #4265: shutil.copyfile() was leaking file descriptors when disk fills ........ Modified: python/branches/py3k/ (props changed) python/branches/py3k/Lib/shutil.py python/branches/py3k/Lib/test/test_shutil.py python/branches/py3k/Misc/NEWS Modified: python/branches/py3k/Lib/shutil.py ============================================================================== --- python/branches/py3k/Lib/shutil.py (original) +++ python/branches/py3k/Lib/shutil.py Thu May 6 00:27:31 2010 @@ -96,15 +96,9 @@ # XXX What about other special files? (sockets, devices...) if stat.S_ISFIFO(st.st_mode): raise SpecialFileError("`%s` is a named pipe" % fn) - try: - fsrc = open(src, 'rb') - fdst = open(dst, 'wb') - copyfileobj(fsrc, fdst) - finally: - if fdst: - fdst.close() - if fsrc: - fsrc.close() + with open(src, 'rb') as fsrc: + with open(dst, 'wb') as fdst: + copyfileobj(fsrc, fdst) def copymode(src, dst): """Copy mode bits from src to dst""" Modified: python/branches/py3k/Lib/test/test_shutil.py ============================================================================== --- python/branches/py3k/Lib/test/test_shutil.py (original) +++ python/branches/py3k/Lib/test/test_shutil.py Thu May 6 00:27:31 2010 @@ -798,8 +798,112 @@ shutil.rmtree(TESTFN, ignore_errors=True) +class TestCopyFile(unittest.TestCase): + + _delete = False + + class Faux(object): + _entered = False + _exited_with = None + _raised = False + def __init__(self, raise_in_exit=False, suppress_at_exit=True): + self._raise_in_exit = raise_in_exit + self._suppress_at_exit = suppress_at_exit + def read(self, *args): + return '' + def __enter__(self): + self._entered = True + def __exit__(self, exc_type, exc_val, exc_tb): + self._exited_with = exc_type, exc_val, exc_tb + if self._raise_in_exit: + self._raised = True + raise IOError("Cannot close") + return self._suppress_at_exit + + def tearDown(self): + if self._delete: + del shutil.open + + def _set_shutil_open(self, func): + shutil.open = func + self._delete = True + + def test_w_source_open_fails(self): + def _open(filename, mode='r'): + if filename == 'srcfile': + raise IOError('Cannot open "srcfile"') + assert 0 # shouldn't reach here. + + self._set_shutil_open(_open) + + self.assertRaises(IOError, shutil.copyfile, 'srcfile', 'destfile') + + def test_w_dest_open_fails(self): + + srcfile = self.Faux() + + def _open(filename, mode='r'): + if filename == 'srcfile': + return srcfile + if filename == 'destfile': + raise IOError('Cannot open "destfile"') + assert 0 # shouldn't reach here. + + self._set_shutil_open(_open) + + shutil.copyfile('srcfile', 'destfile') + self.assertTrue(srcfile._entered) + self.assertTrue(srcfile._exited_with[0] is IOError) + self.assertEqual(srcfile._exited_with[1].args, + ('Cannot open "destfile"',)) + + def test_w_dest_close_fails(self): + + srcfile = self.Faux() + destfile = self.Faux(True) + + def _open(filename, mode='r'): + if filename == 'srcfile': + return srcfile + if filename == 'destfile': + return destfile + assert 0 # shouldn't reach here. + + self._set_shutil_open(_open) + + shutil.copyfile('srcfile', 'destfile') + self.assertTrue(srcfile._entered) + self.assertTrue(destfile._entered) + self.assertTrue(destfile._raised) + self.assertTrue(srcfile._exited_with[0] is IOError) + self.assertEqual(srcfile._exited_with[1].args, + ('Cannot close',)) + + def test_w_source_close_fails(self): + + srcfile = self.Faux(True) + destfile = self.Faux() + + def _open(filename, mode='r'): + if filename == 'srcfile': + return srcfile + if filename == 'destfile': + return destfile + assert 0 # shouldn't reach here. + + self._set_shutil_open(_open) + + self.assertRaises(IOError, + shutil.copyfile, 'srcfile', 'destfile') + self.assertTrue(srcfile._entered) + self.assertTrue(destfile._entered) + self.assertFalse(destfile._raised) + self.assertTrue(srcfile._exited_with[0] is None) + self.assertTrue(srcfile._raised) + + def test_main(): - support.run_unittest(TestShutil, TestMove) + support.run_unittest(TestShutil, TestMove, TestCopyFile) if __name__ == '__main__': test_main() Modified: python/branches/py3k/Misc/NEWS ============================================================================== --- python/branches/py3k/Misc/NEWS (original) +++ python/branches/py3k/Misc/NEWS Thu May 6 00:27:31 2010 @@ -348,6 +348,9 @@ Library ------- +- Issue #4265: shutil.copyfile() was leaking file descriptors when disk fills. + Patch by Tres Seaver. + - Issue #8390: tarfile uses surrogateespace as the default error handler (instead of replace in read mode or strict in write mode) From python-checkins at python.org Thu May 6 00:31:37 2010 From: python-checkins at python.org (mark.dickinson) Date: Thu, 6 May 2010 00:31:37 +0200 (CEST) Subject: [Python-checkins] r80834 - in python/branches/py3k: Misc/NEWS configure configure.in Message-ID: <20100505223137.2BEFCEE9CB@mail.python.org> Author: mark.dickinson Date: Thu May 6 00:31:36 2010 New Revision: 80834 Log: Merged revisions 80832 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r80832 | mark.dickinson | 2010-05-05 23:23:58 +0100 (Wed, 05 May 2010) | 2 lines Issue #8625: Turn off gcc optimization in debug builds. ........ Modified: python/branches/py3k/ (props changed) python/branches/py3k/Misc/NEWS python/branches/py3k/configure python/branches/py3k/configure.in Modified: python/branches/py3k/Misc/NEWS ============================================================================== --- python/branches/py3k/Misc/NEWS (original) +++ python/branches/py3k/Misc/NEWS Thu May 6 00:31:36 2010 @@ -1145,6 +1145,12 @@ Build ----- +- Issue #8625: Turn off optimization in --with-pydebug builds with + gcc. (Optimization was unintentionally turned on in gcc + --with-pydebug builds as a result of the issue #1628484 fix, + combined with autoconf's strange choice of default CFLAGS produced + by AC_PROG_CC for gcc.) + - Issue #3646: It is now easily possible to install a Python framework into your home directory on MacOSX, see Mac/README for more information. Modified: python/branches/py3k/configure ============================================================================== --- python/branches/py3k/configure (original) +++ python/branches/py3k/configure Thu May 6 00:31:36 2010 @@ -1,5 +1,5 @@ #! /bin/sh -# From configure.in Revision: 80666 . +# From configure.in Revision: 80728 . # Guess values for system-dependent variables and create Makefiles. # Generated by GNU Autoconf 2.65 for python 3.2. # @@ -5288,7 +5288,7 @@ if test "$Py_DEBUG" = 'true' ; then # Optimization messes up debuggers, so turn it off for # debug builds. - OPT="-g -Wall $STRICT_PROTO" + OPT="-g -O0 -Wall $STRICT_PROTO" else OPT="-g $WRAP -O3 -Wall $STRICT_PROTO" fi @@ -13553,13 +13553,14 @@ - case $ac_sys_system in OSF*) as_fn_error "OSF* systems are deprecated unless somebody volunteers. Check http://bugs.python.org/issue8606" "$LINENO" 5 ;; esac + + for h in `(cd $srcdir;echo Python/thread_*.h)` do THREADHEADERS="$THREADHEADERS \$(srcdir)/$h" Modified: python/branches/py3k/configure.in ============================================================================== --- python/branches/py3k/configure.in (original) +++ python/branches/py3k/configure.in Thu May 6 00:31:36 2010 @@ -875,7 +875,7 @@ if test "$Py_DEBUG" = 'true' ; then # Optimization messes up debuggers, so turn it off for # debug builds. - OPT="-g -Wall $STRICT_PROTO" + OPT="-g -O0 -Wall $STRICT_PROTO" else OPT="-g $WRAP -O3 -Wall $STRICT_PROTO" fi From python-checkins at python.org Thu May 6 00:39:31 2010 From: python-checkins at python.org (tarek.ziade) Date: Thu, 6 May 2010 00:39:31 +0200 (CEST) Subject: [Python-checkins] r80835 - in python/branches/release31-maint: Lib/shutil.py Lib/test/test_shutil.py Misc/NEWS Message-ID: <20100505223931.D4EA2EE9CB@mail.python.org> Author: tarek.ziade Date: Thu May 6 00:39:31 2010 New Revision: 80835 Log: Merged revisions 80833 via svnmerge from svn+ssh://pythondev at svn.python.org/python/branches/py3k ................ r80833 | tarek.ziade | 2010-05-06 00:27:31 +0200 (Thu, 06 May 2010) | 9 lines Merged revisions 80830 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r80830 | tarek.ziade | 2010-05-06 00:15:31 +0200 (Thu, 06 May 2010) | 1 line Fixed #4265: shutil.copyfile() was leaking file descriptors when disk fills ........ ................ Modified: python/branches/release31-maint/ (props changed) python/branches/release31-maint/Lib/shutil.py python/branches/release31-maint/Lib/test/test_shutil.py python/branches/release31-maint/Misc/NEWS Modified: python/branches/release31-maint/Lib/shutil.py ============================================================================== --- python/branches/release31-maint/Lib/shutil.py (original) +++ python/branches/release31-maint/Lib/shutil.py Thu May 6 00:39:31 2010 @@ -63,15 +63,10 @@ # XXX What about other special files? (sockets, devices...) if stat.S_ISFIFO(st.st_mode): raise SpecialFileError("`%s` is a named pipe" % fn) - try: - fsrc = open(src, 'rb') - fdst = open(dst, 'wb') - copyfileobj(fsrc, fdst) - finally: - if fdst: - fdst.close() - if fsrc: - fsrc.close() + + with open(src, 'rb') as fsrc: + with open(dst, 'wb') as fdst: + copyfileobj(fsrc, fdst) def copymode(src, dst): """Copy mode bits from src to dst""" Modified: python/branches/release31-maint/Lib/test/test_shutil.py ============================================================================== --- python/branches/release31-maint/Lib/test/test_shutil.py (original) +++ python/branches/release31-maint/Lib/test/test_shutil.py Thu May 6 00:39:31 2010 @@ -415,8 +415,112 @@ finally: shutil.rmtree(TESTFN, ignore_errors=True) +class TestCopyFile(unittest.TestCase): + + _delete = False + + class Faux(object): + _entered = False + _exited_with = None + _raised = False + def __init__(self, raise_in_exit=False, suppress_at_exit=True): + self._raise_in_exit = raise_in_exit + self._suppress_at_exit = suppress_at_exit + def read(self, *args): + return '' + def __enter__(self): + self._entered = True + def __exit__(self, exc_type, exc_val, exc_tb): + self._exited_with = exc_type, exc_val, exc_tb + if self._raise_in_exit: + self._raised = True + raise IOError("Cannot close") + return self._suppress_at_exit + + def tearDown(self): + if self._delete: + del shutil.open + + def _set_shutil_open(self, func): + shutil.open = func + self._delete = True + + def test_w_source_open_fails(self): + def _open(filename, mode='r'): + if filename == 'srcfile': + raise IOError('Cannot open "srcfile"') + assert 0 # shouldn't reach here. + + self._set_shutil_open(_open) + + self.assertRaises(IOError, shutil.copyfile, 'srcfile', 'destfile') + + def test_w_dest_open_fails(self): + + srcfile = self.Faux() + + def _open(filename, mode='r'): + if filename == 'srcfile': + return srcfile + if filename == 'destfile': + raise IOError('Cannot open "destfile"') + assert 0 # shouldn't reach here. + + self._set_shutil_open(_open) + + shutil.copyfile('srcfile', 'destfile') + self.assertTrue(srcfile._entered) + self.assertTrue(srcfile._exited_with[0] is IOError) + self.assertEqual(srcfile._exited_with[1].args, + ('Cannot open "destfile"',)) + + def test_w_dest_close_fails(self): + + srcfile = self.Faux() + destfile = self.Faux(True) + + def _open(filename, mode='r'): + if filename == 'srcfile': + return srcfile + if filename == 'destfile': + return destfile + assert 0 # shouldn't reach here. + + self._set_shutil_open(_open) + + shutil.copyfile('srcfile', 'destfile') + self.assertTrue(srcfile._entered) + self.assertTrue(destfile._entered) + self.assertTrue(destfile._raised) + self.assertTrue(srcfile._exited_with[0] is IOError) + self.assertEqual(srcfile._exited_with[1].args, + ('Cannot close',)) + + def test_w_source_close_fails(self): + + srcfile = self.Faux(True) + destfile = self.Faux() + + def _open(filename, mode='r'): + if filename == 'srcfile': + return srcfile + if filename == 'destfile': + return destfile + assert 0 # shouldn't reach here. + + self._set_shutil_open(_open) + + self.assertRaises(IOError, + shutil.copyfile, 'srcfile', 'destfile') + self.assertTrue(srcfile._entered) + self.assertTrue(destfile._entered) + self.assertFalse(destfile._raised) + self.assertTrue(srcfile._exited_with[0] is None) + self.assertTrue(srcfile._raised) + + def test_main(): - support.run_unittest(TestShutil, TestMove) + support.run_unittest(TestShutil, TestMove, TestCopyFile) if __name__ == '__main__': test_main() Modified: python/branches/release31-maint/Misc/NEWS ============================================================================== --- python/branches/release31-maint/Misc/NEWS (original) +++ python/branches/release31-maint/Misc/NEWS Thu May 6 00:39:31 2010 @@ -40,6 +40,9 @@ Library ------- +- Issue #4265: shutil.copyfile() was leaking file descriptors when disk fills. + Patch by Tres Seaver. + - Issue #8621: uuid.uuid4() returned the same sequence of values in the parent and any children created using ``os.fork`` on MacOS X 10.6. From python-checkins at python.org Thu May 6 00:39:58 2010 From: python-checkins at python.org (mark.dickinson) Date: Thu, 6 May 2010 00:39:58 +0200 (CEST) Subject: [Python-checkins] r80836 - python/branches/py3k/Lib/test/test_builtin.py Message-ID: <20100505223958.3547CEE9CB@mail.python.org> Author: mark.dickinson Date: Thu May 6 00:39:58 2010 New Revision: 80836 Log: Issue #1533: Merge added trunk range tests to py3k. (The fix itself doesn't need to be merged.) Patch by Alexander Belopolsky. Modified: python/branches/py3k/Lib/test/test_builtin.py Modified: python/branches/py3k/Lib/test/test_builtin.py ============================================================================== --- python/branches/py3k/Lib/test/test_builtin.py (original) +++ python/branches/py3k/Lib/test/test_builtin.py Thu May 6 00:39:58 2010 @@ -942,8 +942,8 @@ self.assertRaises(RuntimeError, range, a, a + 1, badzero(1)) """ - # Reject floats when it would require PyLongs to represent. - # (smaller floats still accepted, but deprecated) + # Reject floats. + self.assertRaises(TypeError, range, 1., 1., 1.) self.assertRaises(TypeError, range, 1e100, 1e101, 1e101) self.assertRaises(TypeError, range, 0, "spam") @@ -954,6 +954,46 @@ self.assertRaises(OverflowError, len, range(0, sys.maxsize**10)) + bignum = 2*sys.maxsize + smallnum = 42 + + # User-defined class with an __index__ method + class I: + def __init__(self, n): + self.n = int(n) + def __index__(self): + return self.n + self.assertEqual(list(range(I(bignum), I(bignum + 1))), [bignum]) + self.assertEqual(list(range(I(smallnum), I(smallnum + 1))), [smallnum]) + + # User-defined class with a failing __index__ method + class IX: + def __index__(self): + raise RuntimeError + self.assertRaises(RuntimeError, range, IX()) + + # User-defined class with an invalid __index__ method + class IN: + def __index__(self): + return "not a number" + + self.assertRaises(TypeError, range, IN()) + # Exercise various combinations of bad arguments, to check + # refcounting logic + self.assertRaises(TypeError, range, 0.0) + + self.assertRaises(TypeError, range, 0, 0.0) + self.assertRaises(TypeError, range, 0.0, 0) + self.assertRaises(TypeError, range, 0.0, 0.0) + + self.assertRaises(TypeError, range, 0, 0, 1.0) + self.assertRaises(TypeError, range, 0, 0.0, 1) + self.assertRaises(TypeError, range, 0, 0.0, 1.0) + self.assertRaises(TypeError, range, 0.0, 0, 1) + self.assertRaises(TypeError, range, 0.0, 0, 1.0) + self.assertRaises(TypeError, range, 0.0, 0.0, 1) + self.assertRaises(TypeError, range, 0.0, 0.0, 1.0) + def test_input(self): self.write_testfile() fp = open(TESTFN, 'r') From solipsis at pitrou.net Thu May 6 00:40:44 2010 From: solipsis at pitrou.net (solipsis at pitrou.net) Date: Thu, 6 May 2010 00:40:44 +0200 (CEST) Subject: [Python-checkins] Daily py3k reference leaks (r80805): sum=0 Message-ID: <20100505224044.A26D71771F@ns6635.ovh.net> py3k results for svn r80805 (hg cset 806941d13a0a) -------------------------------------------------- Command line was: ['./python', '-m', 'test.regrtest', '-uall', '-R', '3:3:/home/antoine/py3k/refleaks/reflogqClr2A', '-x'] From python-checkins at python.org Thu May 6 00:41:25 2010 From: python-checkins at python.org (tarek.ziade) Date: Thu, 6 May 2010 00:41:25 +0200 (CEST) Subject: [Python-checkins] r80837 - python/trunk/Lib/shutil.py Message-ID: <20100505224125.659CEEE9CB@mail.python.org> Author: tarek.ziade Date: Thu May 6 00:41:25 2010 New Revision: 80837 Log: removed non needed lines Modified: python/trunk/Lib/shutil.py Modified: python/trunk/Lib/shutil.py ============================================================================== --- python/trunk/Lib/shutil.py (original) +++ python/trunk/Lib/shutil.py Thu May 6 00:41:25 2010 @@ -67,8 +67,6 @@ if _samefile(src, dst): raise Error("`%s` and `%s` are the same file" % (src, dst)) - fsrc = None - fdst = None for fn in [src, dst]: try: st = os.stat(fn) @@ -79,6 +77,7 @@ # XXX What about other special files? (sockets, devices...) if stat.S_ISFIFO(st.st_mode): raise SpecialFileError("`%s` is a named pipe" % fn) + with open(src, 'rb') as fsrc: with open(dst, 'wb') as fdst: copyfileobj(fsrc, fdst) From python-checkins at python.org Thu May 6 00:42:06 2010 From: python-checkins at python.org (tarek.ziade) Date: Thu, 6 May 2010 00:42:06 +0200 (CEST) Subject: [Python-checkins] r80838 - python/branches/release26-maint Message-ID: <20100505224206.AE920EE9AA@mail.python.org> Author: tarek.ziade Date: Thu May 6 00:42:06 2010 New Revision: 80838 Log: Blocked revisions 80837 via svnmerge ........ r80837 | tarek.ziade | 2010-05-06 00:41:25 +0200 (Thu, 06 May 2010) | 1 line removed non needed lines ........ Modified: python/branches/release26-maint/ (props changed) From python-checkins at python.org Thu May 6 00:42:52 2010 From: python-checkins at python.org (mark.dickinson) Date: Thu, 6 May 2010 00:42:52 +0200 (CEST) Subject: [Python-checkins] r80839 - python/trunk/Lib/test/test_builtin.py Message-ID: <20100505224252.2C3A7EE9AA@mail.python.org> Author: mark.dickinson Date: Thu May 6 00:42:51 2010 New Revision: 80839 Log: Issue #1533: test_range in test_builtin: fix test comment and add test for rejection of small floats. Thanks Alexander Belopolsky. Modified: python/trunk/Lib/test/test_builtin.py Modified: python/trunk/Lib/test/test_builtin.py ============================================================================== --- python/trunk/Lib/test/test_builtin.py (original) +++ python/trunk/Lib/test/test_builtin.py Thu May 6 00:42:51 2010 @@ -1070,8 +1070,8 @@ __hash__ = None # Invalid cmp makes this unhashable self.assertRaises(RuntimeError, range, a, a + 1, badzero(1)) - # Reject floats when it would require PyLongs to represent. - # (smaller floats still accepted, but deprecated) + # Reject floats. + self.assertRaises(TypeError, range, 1., 1., 1.) self.assertRaises(TypeError, range, 1e100, 1e101, 1e101) self.assertRaises(TypeError, range, 0, "spam") From python-checkins at python.org Thu May 6 00:43:04 2010 From: python-checkins at python.org (tarek.ziade) Date: Thu, 6 May 2010 00:43:04 +0200 (CEST) Subject: [Python-checkins] r80840 - in python/branches/py3k: Lib/shutil.py Message-ID: <20100505224304.D4B0BEEA08@mail.python.org> Author: tarek.ziade Date: Thu May 6 00:43:04 2010 New Revision: 80840 Log: Merged revisions 80837 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r80837 | tarek.ziade | 2010-05-06 00:41:25 +0200 (Thu, 06 May 2010) | 1 line removed non needed lines ........ Modified: python/branches/py3k/ (props changed) python/branches/py3k/Lib/shutil.py Modified: python/branches/py3k/Lib/shutil.py ============================================================================== --- python/branches/py3k/Lib/shutil.py (original) +++ python/branches/py3k/Lib/shutil.py Thu May 6 00:43:04 2010 @@ -84,8 +84,6 @@ if _samefile(src, dst): raise Error("`%s` and `%s` are the same file" % (src, dst)) - fsrc = None - fdst = None for fn in [src, dst]: try: st = os.stat(fn) @@ -96,6 +94,7 @@ # XXX What about other special files? (sockets, devices...) if stat.S_ISFIFO(st.st_mode): raise SpecialFileError("`%s` is a named pipe" % fn) + with open(src, 'rb') as fsrc: with open(dst, 'wb') as fdst: copyfileobj(fsrc, fdst) From python-checkins at python.org Thu May 6 00:44:06 2010 From: python-checkins at python.org (tarek.ziade) Date: Thu, 6 May 2010 00:44:06 +0200 (CEST) Subject: [Python-checkins] r80841 - in python/branches/release31-maint: Lib/shutil.py Message-ID: <20100505224406.EF586EE9AA@mail.python.org> Author: tarek.ziade Date: Thu May 6 00:44:06 2010 New Revision: 80841 Log: Merged revisions 80840 via svnmerge from svn+ssh://pythondev at svn.python.org/python/branches/py3k ................ r80840 | tarek.ziade | 2010-05-06 00:43:04 +0200 (Thu, 06 May 2010) | 9 lines Merged revisions 80837 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r80837 | tarek.ziade | 2010-05-06 00:41:25 +0200 (Thu, 06 May 2010) | 1 line removed non needed lines ........ ................ Modified: python/branches/release31-maint/ (props changed) python/branches/release31-maint/Lib/shutil.py Modified: python/branches/release31-maint/Lib/shutil.py ============================================================================== --- python/branches/release31-maint/Lib/shutil.py (original) +++ python/branches/release31-maint/Lib/shutil.py Thu May 6 00:44:06 2010 @@ -51,8 +51,6 @@ if _samefile(src, dst): raise Error("`%s` and `%s` are the same file" % (src, dst)) - fsrc = None - fdst = None for fn in [src, dst]: try: st = os.stat(fn) From python-checkins at python.org Thu May 6 00:44:35 2010 From: python-checkins at python.org (mark.dickinson) Date: Thu, 6 May 2010 00:44:35 +0200 (CEST) Subject: [Python-checkins] r80842 - python/branches/py3k Message-ID: <20100505224435.1F267EE9AA@mail.python.org> Author: mark.dickinson Date: Thu May 6 00:44:34 2010 New Revision: 80842 Log: Blocked revisions 80839 via svnmerge ........ r80839 | mark.dickinson | 2010-05-05 23:42:51 +0100 (Wed, 05 May 2010) | 3 lines Issue #1533: test_range in test_builtin: fix test comment and add test for rejection of small floats. Thanks Alexander Belopolsky. ........ Modified: python/branches/py3k/ (props changed) From ncoghlan at gmail.com Thu May 6 00:54:16 2010 From: ncoghlan at gmail.com (Nick Coghlan) Date: Thu, 06 May 2010 08:54:16 +1000 Subject: [Python-checkins] r80819 - python/trunk/Python/pystrtod.c In-Reply-To: <20100505203524.4CF6CEA03@mail.python.org> References: <20100505203524.4CF6CEA03@mail.python.org> Message-ID: <4BE1F718.7010202@gmail.com> brett.cannon wrote: > Modified: python/trunk/Python/pystrtod.c > ============================================================================== > --- python/trunk/Python/pystrtod.c (original) > +++ python/trunk/Python/pystrtod.c Wed May 5 22:35:24 2010 > @@ -1005,7 +1005,6 @@ > /* shouldn't get here: Gay's code should always return > something starting with a digit, an 'I', or 'N' */ > strncpy(p, "ERR", 3); > - p += 3; > assert(0); > } > goto exit; I agree with Eric that this should be kept. (And possibly switched to Py_FatalError rather than using assert(), but I would need to look at the surrounding code to be sure about that) Cheers, Nick. -- Nick Coghlan | ncoghlan at gmail.com | Brisbane, Australia --------------------------------------------------------------- From python-checkins at python.org Thu May 6 01:11:08 2010 From: python-checkins at python.org (brett.cannon) Date: Thu, 6 May 2010 01:11:08 +0200 (CEST) Subject: [Python-checkins] r80843 - python/trunk/Python/pystrtod.c Message-ID: <20100505231108.82D89EEA2B@mail.python.org> Author: brett.cannon Date: Thu May 6 01:11:08 2010 New Revision: 80843 Log: Revert a change where an expression is not needed now, but could be in the future. Modified: python/trunk/Python/pystrtod.c Modified: python/trunk/Python/pystrtod.c ============================================================================== --- python/trunk/Python/pystrtod.c (original) +++ python/trunk/Python/pystrtod.c Thu May 6 01:11:08 2010 @@ -1005,6 +1005,7 @@ /* shouldn't get here: Gay's code should always return something starting with a digit, an 'I', or 'N' */ strncpy(p, "ERR", 3); + p += 3; assert(0); } goto exit; From eric at trueblade.com Thu May 6 01:16:42 2010 From: eric at trueblade.com (Eric Smith) Date: Wed, 05 May 2010 19:16:42 -0400 Subject: [Python-checkins] r80819 - python/trunk/Python/pystrtod.c In-Reply-To: <4BE1F718.7010202@gmail.com> References: <20100505203524.4CF6CEA03@mail.python.org> <4BE1F718.7010202@gmail.com> Message-ID: <4BE1FC5A.8000005@trueblade.com> Nick Coghlan wrote: > brett.cannon wrote: >> Modified: python/trunk/Python/pystrtod.c >> ============================================================================== >> --- python/trunk/Python/pystrtod.c (original) >> +++ python/trunk/Python/pystrtod.c Wed May 5 22:35:24 2010 >> @@ -1005,7 +1005,6 @@ >> /* shouldn't get here: Gay's code should always return >> something starting with a digit, an 'I', or 'N' */ >> strncpy(p, "ERR", 3); >> - p += 3; >> assert(0); >> } >> goto exit; > > I agree with Eric that this should be kept. (And possibly switched to > Py_FatalError rather than using assert(), but I would need to look at > the surrounding code to be sure about that) I think it should stay an assert. This is a "we should never get here" situation, but if we do, we format the float as "ERR" (as a sort-of parallel to "NAN" and "INF") and keep going. I think that's better than an unexpected failure. Eric. From brett at python.org Thu May 6 01:18:19 2010 From: brett at python.org (Brett Cannon) Date: Wed, 5 May 2010 16:18:19 -0700 Subject: [Python-checkins] r80816 - python/trunk/Python/getcwd.c In-Reply-To: <201005052258.51480.victor.stinner@haypocalc.com> References: <20100505202658.BA843EE9A9@mail.python.org> <201005052258.51480.victor.stinner@haypocalc.com> Message-ID: On Wed, May 5, 2010 at 13:58, Victor Stinner wrote: > Le mercredi 05 mai 2010 22:26:58, brett.cannon a ?crit : > > Author: brett.cannon > > Date: Wed May 5 22:26:58 2010 > > New Revision: 80816 > > > > Log: > > Remove an unneeded variable and fix a little whitespace. > > Please, could you try to fix one thing by commit. I mean: one commit for > the > variable, and another for the whitespaces. > It was a choice over getting this done or having very clean commits; I chose the former obviously. Probably would have bothered had svn let me shelve changes like Hg's mq would have let me. > > > Found using Clang's static analyzer. > > Whitespaces are not related to the static analyzer. > > > It would be better to fix all whitespaces in ONE unique commit on the whole > Python project, instead of fix some whitespaces in some files. Antoine is > working on a tool to uniformize the indentation (and spaces) of the C > files. That's fine, but I believe that is being aimed at four space indents; I don't know if he is planning a separate run just to clean up extraneous whitespace. Plus that will probably only be run on py3k and not trunk. I am not going to wait when I have the whitespace staring me in the face while I am editing the code as who knows if Antoine will have the time to ever run it on 2.7. -------------- next part -------------- An HTML attachment was scrubbed... URL: From python-checkins at python.org Thu May 6 01:33:34 2010 From: python-checkins at python.org (victor.stinner) Date: Thu, 6 May 2010 01:33:34 +0200 (CEST) Subject: [Python-checkins] r80844 - python/trunk/Modules/posixmodule.c Message-ID: <20100505233334.2D4E8EEA27@mail.python.org> Author: victor.stinner Date: Thu May 6 01:33:33 2010 New Revision: 80844 Log: Untabify Modules/posixmodule.c Run Antoine Pitrou "untabify" script + manual editions (OS/2 and some continuation lines). Modified: python/trunk/Modules/posixmodule.c Modified: python/trunk/Modules/posixmodule.c ============================================================================== --- python/trunk/Modules/posixmodule.c (original) +++ python/trunk/Modules/posixmodule.c Thu May 6 01:33:33 2010 @@ -15,7 +15,7 @@ #ifdef __APPLE__ /* - * Step 1 of support for weak-linking a number of symbols existing on + * Step 1 of support for weak-linking a number of symbols existing on * OSX 10.4 and later, see the comment in the #ifdef __APPLE__ block * at the end of this file for more information. */ @@ -73,7 +73,7 @@ #endif /* HAVE_SYS_STAT_H */ #ifdef HAVE_SYS_WAIT_H -#include /* For WNOHANG */ +#include /* For WNOHANG */ #endif #ifdef HAVE_SIGNAL_H @@ -101,43 +101,43 @@ #if defined(PYCC_VACPP) && defined(PYOS_OS2) #include #else -#if defined(__WATCOMC__) && !defined(__QNX__) /* Watcom compiler */ +#if defined(__WATCOMC__) && !defined(__QNX__) /* Watcom compiler */ #define HAVE_GETCWD 1 #define HAVE_OPENDIR 1 -#define HAVE_SYSTEM 1 +#define HAVE_SYSTEM 1 #if defined(__OS2__) #define HAVE_EXECV 1 #define HAVE_WAIT 1 #endif #include #else -#ifdef __BORLANDC__ /* Borland compiler */ +#ifdef __BORLANDC__ /* Borland compiler */ #define HAVE_EXECV 1 #define HAVE_GETCWD 1 #define HAVE_OPENDIR 1 #define HAVE_PIPE 1 #define HAVE_POPEN 1 -#define HAVE_SYSTEM 1 +#define HAVE_SYSTEM 1 #define HAVE_WAIT 1 #else -#ifdef _MSC_VER /* Microsoft compiler */ +#ifdef _MSC_VER /* Microsoft compiler */ #define HAVE_GETCWD 1 -#define HAVE_SPAWNV 1 +#define HAVE_SPAWNV 1 #define HAVE_EXECV 1 #define HAVE_PIPE 1 #define HAVE_POPEN 1 -#define HAVE_SYSTEM 1 -#define HAVE_CWAIT 1 -#define HAVE_FSYNC 1 +#define HAVE_SYSTEM 1 +#define HAVE_CWAIT 1 +#define HAVE_FSYNC 1 #define fsync _commit #else #if defined(PYOS_OS2) && defined(PYCC_GCC) || defined(__VMS) /* Everything needed is defined in PC/os2emx/pyconfig.h or vms/pyconfig.h */ -#else /* all other compilers */ +#else /* all other compilers */ /* Unix functions that the configure script doesn't check for */ #define HAVE_EXECV 1 #define HAVE_FORK 1 -#if defined(__USLC__) && defined(__SCO_VERSION__) /* SCO UDK Compiler */ +#if defined(__USLC__) && defined(__SCO_VERSION__) /* SCO UDK Compiler */ #define HAVE_FORK1 1 #endif #define HAVE_GETCWD 1 @@ -152,9 +152,9 @@ #ifndef __rtems__ #define HAVE_POPEN 1 #endif -#define HAVE_SYSTEM 1 +#define HAVE_SYSTEM 1 #define HAVE_WAIT 1 -#define HAVE_TTYNAME 1 +#define HAVE_TTYNAME 1 #endif /* PYOS_OS2 && PYCC_GCC && __VMS */ #endif /* _MSC_VER */ #endif /* __BORLANDC__ */ @@ -271,9 +271,9 @@ #include "osdefs.h" #include #include -#include /* for ShellExecute() */ -#define popen _popen -#define pclose _pclose +#include /* for ShellExecute() */ +#define popen _popen +#define pclose _pclose #endif /* _MSC_VER */ #if defined(PYCC_VACPP) && defined(PYOS_OS2) @@ -341,13 +341,13 @@ /* choose the appropriate stat and fstat functions and return structs */ #undef STAT #if defined(MS_WIN64) || defined(MS_WINDOWS) -# define STAT win32_stat -# define FSTAT win32_fstat -# define STRUCT_STAT struct win32_stat -#else -# define STAT stat -# define FSTAT fstat -# define STRUCT_STAT struct stat +# define STAT win32_stat +# define FSTAT win32_fstat +# define STRUCT_STAT struct win32_stat +#else +# define STAT stat +# define FSTAT fstat +# define STRUCT_STAT struct stat #endif #if defined(MAJOR_IN_MKDEV) @@ -374,7 +374,7 @@ * as a fd and should merely raise a python exception on error. * The Microsoft CRT doesn't provide an official way to check for the * validity of a file descriptor, but we can emulate its internal behaviour - * by using the exported __pinfo data member and knowledge of the + * by using the exported __pinfo data member and knowledge of the * internal structures involved. * The structures below must be updated for each version of visual studio * according to the file internal.h in the CRT source, until MS comes @@ -386,8 +386,8 @@ * Only the first items must be present. */ typedef struct { - intptr_t osfhnd; - char osfile; + intptr_t osfhnd; + char osfile; } my_ioinfo; extern __declspec(dllimport) char * __pioinfo[]; @@ -402,52 +402,52 @@ int _PyVerify_fd(int fd) { - const int i1 = fd >> IOINFO_L2E; - const int i2 = fd & ((1 << IOINFO_L2E) - 1); - - static int sizeof_ioinfo = 0; - - /* Determine the actual size of the ioinfo structure, - * as used by the CRT loaded in memory - */ - if (sizeof_ioinfo == 0 && __pioinfo[0] != NULL) { - sizeof_ioinfo = _msize(__pioinfo[0]) / IOINFO_ARRAY_ELTS; - } - if (sizeof_ioinfo == 0) { - /* This should not happen... */ - goto fail; - } - - /* See that it isn't a special CLEAR fileno */ - if (fd != _NO_CONSOLE_FILENO) { - /* Microsoft CRT would check that 0<=fd<_nhandle but we can't do that. Instead - * we check pointer validity and other info - */ - if (0 <= i1 && i1 < IOINFO_ARRAYS && __pioinfo[i1] != NULL) { - /* finally, check that the file is open */ - my_ioinfo* info = (my_ioinfo*)(__pioinfo[i1] + i2 * sizeof_ioinfo); - if (info->osfile & FOPEN) { - return 1; - } - } - } + const int i1 = fd >> IOINFO_L2E; + const int i2 = fd & ((1 << IOINFO_L2E) - 1); + + static int sizeof_ioinfo = 0; + + /* Determine the actual size of the ioinfo structure, + * as used by the CRT loaded in memory + */ + if (sizeof_ioinfo == 0 && __pioinfo[0] != NULL) { + sizeof_ioinfo = _msize(__pioinfo[0]) / IOINFO_ARRAY_ELTS; + } + if (sizeof_ioinfo == 0) { + /* This should not happen... */ + goto fail; + } + + /* See that it isn't a special CLEAR fileno */ + if (fd != _NO_CONSOLE_FILENO) { + /* Microsoft CRT would check that 0<=fd<_nhandle but we can't do that. Instead + * we check pointer validity and other info + */ + if (0 <= i1 && i1 < IOINFO_ARRAYS && __pioinfo[i1] != NULL) { + /* finally, check that the file is open */ + my_ioinfo* info = (my_ioinfo*)(__pioinfo[i1] + i2 * sizeof_ioinfo); + if (info->osfile & FOPEN) { + return 1; + } + } + } fail: - errno = EBADF; - return 0; + errno = EBADF; + return 0; } /* the special case of checking dup2. The target fd must be in a sensible range */ static int _PyVerify_fd_dup2(int fd1, int fd2) { - if (!_PyVerify_fd(fd1)) - return 0; - if (fd2 == _NO_CONSOLE_FILENO) - return 0; - if ((unsigned)fd2 < _NHANDLE_) - return 1; - else - return 0; + if (!_PyVerify_fd(fd1)) + return 0; + if (fd2 == _NO_CONSOLE_FILENO) + return 0; + if ((unsigned)fd2 < _NHANDLE_) + return 1; + else + return 0; } #else /* dummy version. _PyVerify_fd() is already defined in fileobject.h */ @@ -468,62 +468,61 @@ static PyObject * convertenviron(void) { - PyObject *d; - char **e; - d = PyDict_New(); - if (d == NULL) - return NULL; + PyObject *d; + char **e; +#if defined(PYOS_OS2) + APIRET rc; + char buffer[1024]; /* OS/2 Provides a Documented Max of 1024 Chars */ +#endif + d = PyDict_New(); + if (d == NULL) + return NULL; #ifdef WITH_NEXT_FRAMEWORK - if (environ == NULL) - environ = *_NSGetEnviron(); + if (environ == NULL) + environ = *_NSGetEnviron(); #endif - if (environ == NULL) - return d; - /* This part ignores errors */ - for (e = environ; *e != NULL; e++) { - PyObject *k; - PyObject *v; - char *p = strchr(*e, '='); - if (p == NULL) - continue; - k = PyString_FromStringAndSize(*e, (int)(p-*e)); - if (k == NULL) { - PyErr_Clear(); - continue; - } - v = PyString_FromString(p+1); - if (v == NULL) { - PyErr_Clear(); - Py_DECREF(k); - continue; - } - if (PyDict_GetItem(d, k) == NULL) { - if (PyDict_SetItem(d, k, v) != 0) - PyErr_Clear(); - } - Py_DECREF(k); - Py_DECREF(v); - } -#if defined(PYOS_OS2) - { - APIRET rc; - char buffer[1024]; /* OS/2 Provides a Documented Max of 1024 Chars */ - - rc = DosQueryExtLIBPATH(buffer, BEGIN_LIBPATH); - if (rc == NO_ERROR) { /* (not a type, envname is NOT 'BEGIN_LIBPATH') */ - PyObject *v = PyString_FromString(buffer); - PyDict_SetItemString(d, "BEGINLIBPATH", v); - Py_DECREF(v); + if (environ == NULL) + return d; + /* This part ignores errors */ + for (e = environ; *e != NULL; e++) { + PyObject *k; + PyObject *v; + char *p = strchr(*e, '='); + if (p == NULL) + continue; + k = PyString_FromStringAndSize(*e, (int)(p-*e)); + if (k == NULL) { + PyErr_Clear(); + continue; } - rc = DosQueryExtLIBPATH(buffer, END_LIBPATH); - if (rc == NO_ERROR) { /* (not a typo, envname is NOT 'END_LIBPATH') */ - PyObject *v = PyString_FromString(buffer); - PyDict_SetItemString(d, "ENDLIBPATH", v); - Py_DECREF(v); + v = PyString_FromString(p+1); + if (v == NULL) { + PyErr_Clear(); + Py_DECREF(k); + continue; + } + if (PyDict_GetItem(d, k) == NULL) { + if (PyDict_SetItem(d, k, v) != 0) + PyErr_Clear(); } + Py_DECREF(k); + Py_DECREF(v); + } +#if defined(PYOS_OS2) + rc = DosQueryExtLIBPATH(buffer, BEGIN_LIBPATH); + if (rc == NO_ERROR) { /* (not a type, envname is NOT 'BEGIN_LIBPATH') */ + PyObject *v = PyString_FromString(buffer); + PyDict_SetItemString(d, "BEGINLIBPATH", v); + Py_DECREF(v); + } + rc = DosQueryExtLIBPATH(buffer, END_LIBPATH); + if (rc == NO_ERROR) { /* (not a typo, envname is NOT 'END_LIBPATH') */ + PyObject *v = PyString_FromString(buffer); + PyDict_SetItemString(d, "ENDLIBPATH", v); + Py_DECREF(v); } #endif - return d; + return d; } @@ -532,19 +531,19 @@ static PyObject * posix_error(void) { - return PyErr_SetFromErrno(PyExc_OSError); + return PyErr_SetFromErrno(PyExc_OSError); } static PyObject * posix_error_with_filename(char* name) { - return PyErr_SetFromErrnoWithFilename(PyExc_OSError, name); + return PyErr_SetFromErrnoWithFilename(PyExc_OSError, name); } #ifdef MS_WINDOWS static PyObject * posix_error_with_unicode_filename(Py_UNICODE* name) { - return PyErr_SetFromErrnoWithUnicodeFilename(PyExc_OSError, name); + return PyErr_SetFromErrnoWithUnicodeFilename(PyExc_OSError, name); } #endif /* MS_WINDOWS */ @@ -552,53 +551,53 @@ static PyObject * posix_error_with_allocated_filename(char* name) { - PyObject *rc = PyErr_SetFromErrnoWithFilename(PyExc_OSError, name); - PyMem_Free(name); - return rc; + PyObject *rc = PyErr_SetFromErrnoWithFilename(PyExc_OSError, name); + PyMem_Free(name); + return rc; } #ifdef MS_WINDOWS static PyObject * win32_error(char* function, char* filename) { - /* XXX We should pass the function name along in the future. - (_winreg.c also wants to pass the function name.) - This would however require an additional param to the - Windows error object, which is non-trivial. - */ - errno = GetLastError(); - if (filename) - return PyErr_SetFromWindowsErrWithFilename(errno, filename); - else - return PyErr_SetFromWindowsErr(errno); + /* XXX We should pass the function name along in the future. + (_winreg.c also wants to pass the function name.) + This would however require an additional param to the + Windows error object, which is non-trivial. + */ + errno = GetLastError(); + if (filename) + return PyErr_SetFromWindowsErrWithFilename(errno, filename); + else + return PyErr_SetFromWindowsErr(errno); } static PyObject * win32_error_unicode(char* function, Py_UNICODE* filename) { - /* XXX - see win32_error for comments on 'function' */ - errno = GetLastError(); - if (filename) - return PyErr_SetFromWindowsErrWithUnicodeFilename(errno, filename); - else - return PyErr_SetFromWindowsErr(errno); + /* XXX - see win32_error for comments on 'function' */ + errno = GetLastError(); + if (filename) + return PyErr_SetFromWindowsErrWithUnicodeFilename(errno, filename); + else + return PyErr_SetFromWindowsErr(errno); } static int convert_to_unicode(PyObject **param) { - if (PyUnicode_CheckExact(*param)) - Py_INCREF(*param); - else if (PyUnicode_Check(*param)) - /* For a Unicode subtype that's not a Unicode object, - return a true Unicode object with the same data. */ - *param = PyUnicode_FromUnicode(PyUnicode_AS_UNICODE(*param), - PyUnicode_GET_SIZE(*param)); - else - *param = PyUnicode_FromEncodedObject(*param, - Py_FileSystemDefaultEncoding, - "strict"); - return (*param) != NULL; + if (PyUnicode_CheckExact(*param)) + Py_INCREF(*param); + else if (PyUnicode_Check(*param)) + /* For a Unicode subtype that's not a Unicode object, + return a true Unicode object with the same data. */ + *param = PyUnicode_FromUnicode(PyUnicode_AS_UNICODE(*param), + PyUnicode_GET_SIZE(*param)); + else + *param = PyUnicode_FromEncodedObject(*param, + Py_FileSystemDefaultEncoding, + "strict"); + return (*param) != NULL; } #endif /* MS_WINDOWS */ @@ -607,16 +606,16 @@ /********************************************************************** * Helper Function to Trim and Format OS/2 Messages **********************************************************************/ - static void +static void os2_formatmsg(char *msgbuf, int msglen, char *reason) { msgbuf[msglen] = '\0'; /* OS/2 Doesn't Guarantee a Terminator */ if (strlen(msgbuf) > 0) { /* If Non-Empty Msg, Trim CRLF */ - char *lastc = &msgbuf[ strlen(msgbuf)-1 ]; + char *lastc = &msgbuf[ strlen(msgbuf)-1 ]; - while (lastc > msgbuf && isspace(Py_CHARMASK(*lastc))) - *lastc-- = '\0'; /* Trim Trailing Whitespace (CRLF) */ + while (lastc > msgbuf && isspace(Py_CHARMASK(*lastc))) + *lastc-- = '\0'; /* Trim Trailing Whitespace (CRLF) */ } /* Add Optional Reason Text */ @@ -637,7 +636,7 @@ * the file OSO001.MSG in the \OS2 directory hierarchy. * **********************************************************************/ - static char * +static char * os2_strerror(char *msgbuf, int msgbuflen, int errorcode, char *reason) { APIRET rc; @@ -653,7 +652,7 @@ os2_formatmsg(msgbuf, msglen, reason); else PyOS_snprintf(msgbuf, msgbuflen, - "unknown OS error #%d", errorcode); + "unknown OS error #%d", errorcode); return msgbuf; } @@ -662,7 +661,8 @@ errors are not in a global variable e.g. 'errno' nor are they congruent with posix error numbers. */ -static PyObject * os2_error(int code) +static PyObject * +os2_error(int code) { char text[1024]; PyObject *v; @@ -684,93 +684,93 @@ static PyObject * posix_fildes(PyObject *fdobj, int (*func)(int)) { - int fd; - int res; - fd = PyObject_AsFileDescriptor(fdobj); - if (fd < 0) - return NULL; - if (!_PyVerify_fd(fd)) - return posix_error(); - Py_BEGIN_ALLOW_THREADS - res = (*func)(fd); - Py_END_ALLOW_THREADS - if (res < 0) - return posix_error(); - Py_INCREF(Py_None); - return Py_None; + int fd; + int res; + fd = PyObject_AsFileDescriptor(fdobj); + if (fd < 0) + return NULL; + if (!_PyVerify_fd(fd)) + return posix_error(); + Py_BEGIN_ALLOW_THREADS + res = (*func)(fd); + Py_END_ALLOW_THREADS + if (res < 0) + return posix_error(); + Py_INCREF(Py_None); + return Py_None; } static PyObject * posix_1str(PyObject *args, char *format, int (*func)(const char*)) { - char *path1 = NULL; - int res; - if (!PyArg_ParseTuple(args, format, - Py_FileSystemDefaultEncoding, &path1)) - return NULL; - Py_BEGIN_ALLOW_THREADS - res = (*func)(path1); - Py_END_ALLOW_THREADS - if (res < 0) - return posix_error_with_allocated_filename(path1); - PyMem_Free(path1); - Py_INCREF(Py_None); - return Py_None; + char *path1 = NULL; + int res; + if (!PyArg_ParseTuple(args, format, + Py_FileSystemDefaultEncoding, &path1)) + return NULL; + Py_BEGIN_ALLOW_THREADS + res = (*func)(path1); + Py_END_ALLOW_THREADS + if (res < 0) + return posix_error_with_allocated_filename(path1); + PyMem_Free(path1); + Py_INCREF(Py_None); + return Py_None; } static PyObject * posix_2str(PyObject *args, - char *format, - int (*func)(const char *, const char *)) + char *format, + int (*func)(const char *, const char *)) { - char *path1 = NULL, *path2 = NULL; - int res; - if (!PyArg_ParseTuple(args, format, - Py_FileSystemDefaultEncoding, &path1, - Py_FileSystemDefaultEncoding, &path2)) - return NULL; - Py_BEGIN_ALLOW_THREADS - res = (*func)(path1, path2); - Py_END_ALLOW_THREADS - PyMem_Free(path1); - PyMem_Free(path2); - if (res != 0) - /* XXX how to report both path1 and path2??? */ - return posix_error(); - Py_INCREF(Py_None); - return Py_None; + char *path1 = NULL, *path2 = NULL; + int res; + if (!PyArg_ParseTuple(args, format, + Py_FileSystemDefaultEncoding, &path1, + Py_FileSystemDefaultEncoding, &path2)) + return NULL; + Py_BEGIN_ALLOW_THREADS + res = (*func)(path1, path2); + Py_END_ALLOW_THREADS + PyMem_Free(path1); + PyMem_Free(path2); + if (res != 0) + /* XXX how to report both path1 and path2??? */ + return posix_error(); + Py_INCREF(Py_None); + return Py_None; } #ifdef MS_WINDOWS static PyObject* -win32_1str(PyObject* args, char* func, - char* format, BOOL (__stdcall *funcA)(LPCSTR), - char* wformat, BOOL (__stdcall *funcW)(LPWSTR)) -{ - PyObject *uni; - char *ansi; - BOOL result; - - if (!PyArg_ParseTuple(args, wformat, &uni)) - PyErr_Clear(); - else { - Py_BEGIN_ALLOW_THREADS - result = funcW(PyUnicode_AsUnicode(uni)); - Py_END_ALLOW_THREADS - if (!result) - return win32_error_unicode(func, PyUnicode_AsUnicode(uni)); - Py_INCREF(Py_None); - return Py_None; - } - if (!PyArg_ParseTuple(args, format, &ansi)) - return NULL; - Py_BEGIN_ALLOW_THREADS - result = funcA(ansi); - Py_END_ALLOW_THREADS - if (!result) - return win32_error(func, ansi); - Py_INCREF(Py_None); - return Py_None; +win32_1str(PyObject* args, char* func, + char* format, BOOL (__stdcall *funcA)(LPCSTR), + char* wformat, BOOL (__stdcall *funcW)(LPWSTR)) +{ + PyObject *uni; + char *ansi; + BOOL result; + + if (!PyArg_ParseTuple(args, wformat, &uni)) + PyErr_Clear(); + else { + Py_BEGIN_ALLOW_THREADS + result = funcW(PyUnicode_AsUnicode(uni)); + Py_END_ALLOW_THREADS + if (!result) + return win32_error_unicode(func, PyUnicode_AsUnicode(uni)); + Py_INCREF(Py_None); + return Py_None; + } + if (!PyArg_ParseTuple(args, format, &ansi)) + return NULL; + Py_BEGIN_ALLOW_THREADS + result = funcA(ansi); + Py_END_ALLOW_THREADS + if (!result) + return win32_error(func, ansi); + Py_INCREF(Py_None); + return Py_None; } @@ -782,24 +782,24 @@ static BOOL __stdcall win32_chdir(LPCSTR path) { - char new_path[MAX_PATH+1]; - int result; - char env[4] = "=x:"; - - if(!SetCurrentDirectoryA(path)) - return FALSE; - result = GetCurrentDirectoryA(MAX_PATH+1, new_path); - if (!result) - return FALSE; - /* In the ANSI API, there should not be any paths longer - than MAX_PATH. */ - assert(result <= MAX_PATH+1); - if (strncmp(new_path, "\\\\", 2) == 0 || - strncmp(new_path, "//", 2) == 0) - /* UNC path, nothing to do. */ - return TRUE; - env[1] = new_path[0]; - return SetEnvironmentVariableA(env, new_path); + char new_path[MAX_PATH+1]; + int result; + char env[4] = "=x:"; + + if(!SetCurrentDirectoryA(path)) + return FALSE; + result = GetCurrentDirectoryA(MAX_PATH+1, new_path); + if (!result) + return FALSE; + /* In the ANSI API, there should not be any paths longer + than MAX_PATH. */ + assert(result <= MAX_PATH+1); + if (strncmp(new_path, "\\\\", 2) == 0 || + strncmp(new_path, "//", 2) == 0) + /* UNC path, nothing to do. */ + return TRUE; + env[1] = new_path[0]; + return SetEnvironmentVariableA(env, new_path); } /* The Unicode version differs from the ANSI version @@ -807,36 +807,36 @@ static BOOL __stdcall win32_wchdir(LPCWSTR path) { - wchar_t _new_path[MAX_PATH+1], *new_path = _new_path; - int result; - wchar_t env[4] = L"=x:"; - - if(!SetCurrentDirectoryW(path)) - return FALSE; - result = GetCurrentDirectoryW(MAX_PATH+1, new_path); - if (!result) - return FALSE; - if (result > MAX_PATH+1) { - new_path = malloc(result * sizeof(wchar_t)); - if (!new_path) { - SetLastError(ERROR_OUTOFMEMORY); - return FALSE; - } - result = GetCurrentDirectoryW(result, new_path); - if (!result) { - free(new_path); - return FALSE; - } - } - if (wcsncmp(new_path, L"\\\\", 2) == 0 || - wcsncmp(new_path, L"//", 2) == 0) - /* UNC path, nothing to do. */ - return TRUE; - env[1] = new_path[0]; - result = SetEnvironmentVariableW(env, new_path); - if (new_path != _new_path) - free(new_path); - return result; + wchar_t _new_path[MAX_PATH+1], *new_path = _new_path; + int result; + wchar_t env[4] = L"=x:"; + + if(!SetCurrentDirectoryW(path)) + return FALSE; + result = GetCurrentDirectoryW(MAX_PATH+1, new_path); + if (!result) + return FALSE; + if (result > MAX_PATH+1) { + new_path = malloc(result * sizeof(wchar_t)); + if (!new_path) { + SetLastError(ERROR_OUTOFMEMORY); + return FALSE; + } + result = GetCurrentDirectoryW(result, new_path); + if (!result) { + free(new_path); + return FALSE; + } + } + if (wcsncmp(new_path, L"\\\\", 2) == 0 || + wcsncmp(new_path, L"//", 2) == 0) + /* UNC path, nothing to do. */ + return TRUE; + env[1] = new_path[0]; + result = SetEnvironmentVariableW(env, new_path); + if (new_path != _new_path) + free(new_path); + return result; } #endif @@ -847,7 +847,7 @@ UTC and local time Therefore, we implement our own stat, based on the Win32 API directly. */ -#define HAVE_STAT_NSEC 1 +#define HAVE_STAT_NSEC 1 struct win32_stat{ int st_dev; @@ -871,24 +871,24 @@ static void FILE_TIME_to_time_t_nsec(FILETIME *in_ptr, int *time_out, int* nsec_out) { - /* XXX endianness. Shouldn't matter, as all Windows implementations are little-endian */ - /* Cannot simply cast and dereference in_ptr, - since it might not be aligned properly */ - __int64 in; - memcpy(&in, in_ptr, sizeof(in)); - *nsec_out = (int)(in % 10000000) * 100; /* FILETIME is in units of 100 nsec. */ - /* XXX Win32 supports time stamps past 2038; we currently don't */ - *time_out = Py_SAFE_DOWNCAST((in / 10000000) - secs_between_epochs, __int64, int); + /* XXX endianness. Shouldn't matter, as all Windows implementations are little-endian */ + /* Cannot simply cast and dereference in_ptr, + since it might not be aligned properly */ + __int64 in; + memcpy(&in, in_ptr, sizeof(in)); + *nsec_out = (int)(in % 10000000) * 100; /* FILETIME is in units of 100 nsec. */ + /* XXX Win32 supports time stamps past 2038; we currently don't */ + *time_out = Py_SAFE_DOWNCAST((in / 10000000) - secs_between_epochs, __int64, int); } static void time_t_to_FILE_TIME(int time_in, int nsec_in, FILETIME *out_ptr) { - /* XXX endianness */ - __int64 out; - out = time_in + secs_between_epochs; - out = out * 10000000 + nsec_in / 100; - memcpy(out_ptr, &out, sizeof(out)); + /* XXX endianness */ + __int64 out; + out = time_in + secs_between_epochs; + out = out * 10000000 + nsec_in / 100; + memcpy(out_ptr, &out, sizeof(out)); } /* Below, we *know* that ugo+r is 0444 */ @@ -898,193 +898,193 @@ static int attributes_to_mode(DWORD attr) { - int m = 0; - if (attr & FILE_ATTRIBUTE_DIRECTORY) - m |= _S_IFDIR | 0111; /* IFEXEC for user,group,other */ - else - m |= _S_IFREG; - if (attr & FILE_ATTRIBUTE_READONLY) - m |= 0444; - else - m |= 0666; - return m; + int m = 0; + if (attr & FILE_ATTRIBUTE_DIRECTORY) + m |= _S_IFDIR | 0111; /* IFEXEC for user,group,other */ + else + m |= _S_IFREG; + if (attr & FILE_ATTRIBUTE_READONLY) + m |= 0444; + else + m |= 0666; + return m; } static int attribute_data_to_stat(WIN32_FILE_ATTRIBUTE_DATA *info, struct win32_stat *result) { - memset(result, 0, sizeof(*result)); - result->st_mode = attributes_to_mode(info->dwFileAttributes); - result->st_size = (((__int64)info->nFileSizeHigh)<<32) + info->nFileSizeLow; - FILE_TIME_to_time_t_nsec(&info->ftCreationTime, &result->st_ctime, &result->st_ctime_nsec); - FILE_TIME_to_time_t_nsec(&info->ftLastWriteTime, &result->st_mtime, &result->st_mtime_nsec); - FILE_TIME_to_time_t_nsec(&info->ftLastAccessTime, &result->st_atime, &result->st_atime_nsec); + memset(result, 0, sizeof(*result)); + result->st_mode = attributes_to_mode(info->dwFileAttributes); + result->st_size = (((__int64)info->nFileSizeHigh)<<32) + info->nFileSizeLow; + FILE_TIME_to_time_t_nsec(&info->ftCreationTime, &result->st_ctime, &result->st_ctime_nsec); + FILE_TIME_to_time_t_nsec(&info->ftLastWriteTime, &result->st_mtime, &result->st_mtime_nsec); + FILE_TIME_to_time_t_nsec(&info->ftLastAccessTime, &result->st_atime, &result->st_atime_nsec); - return 0; + return 0; } static BOOL attributes_from_dir(LPCSTR pszFile, LPWIN32_FILE_ATTRIBUTE_DATA pfad) { - HANDLE hFindFile; - WIN32_FIND_DATAA FileData; - hFindFile = FindFirstFileA(pszFile, &FileData); - if (hFindFile == INVALID_HANDLE_VALUE) - return FALSE; - FindClose(hFindFile); - pfad->dwFileAttributes = FileData.dwFileAttributes; - pfad->ftCreationTime = FileData.ftCreationTime; - pfad->ftLastAccessTime = FileData.ftLastAccessTime; - pfad->ftLastWriteTime = FileData.ftLastWriteTime; - pfad->nFileSizeHigh = FileData.nFileSizeHigh; - pfad->nFileSizeLow = FileData.nFileSizeLow; - return TRUE; + HANDLE hFindFile; + WIN32_FIND_DATAA FileData; + hFindFile = FindFirstFileA(pszFile, &FileData); + if (hFindFile == INVALID_HANDLE_VALUE) + return FALSE; + FindClose(hFindFile); + pfad->dwFileAttributes = FileData.dwFileAttributes; + pfad->ftCreationTime = FileData.ftCreationTime; + pfad->ftLastAccessTime = FileData.ftLastAccessTime; + pfad->ftLastWriteTime = FileData.ftLastWriteTime; + pfad->nFileSizeHigh = FileData.nFileSizeHigh; + pfad->nFileSizeLow = FileData.nFileSizeLow; + return TRUE; } static BOOL attributes_from_dir_w(LPCWSTR pszFile, LPWIN32_FILE_ATTRIBUTE_DATA pfad) { - HANDLE hFindFile; - WIN32_FIND_DATAW FileData; - hFindFile = FindFirstFileW(pszFile, &FileData); - if (hFindFile == INVALID_HANDLE_VALUE) - return FALSE; - FindClose(hFindFile); - pfad->dwFileAttributes = FileData.dwFileAttributes; - pfad->ftCreationTime = FileData.ftCreationTime; - pfad->ftLastAccessTime = FileData.ftLastAccessTime; - pfad->ftLastWriteTime = FileData.ftLastWriteTime; - pfad->nFileSizeHigh = FileData.nFileSizeHigh; - pfad->nFileSizeLow = FileData.nFileSizeLow; - return TRUE; + HANDLE hFindFile; + WIN32_FIND_DATAW FileData; + hFindFile = FindFirstFileW(pszFile, &FileData); + if (hFindFile == INVALID_HANDLE_VALUE) + return FALSE; + FindClose(hFindFile); + pfad->dwFileAttributes = FileData.dwFileAttributes; + pfad->ftCreationTime = FileData.ftCreationTime; + pfad->ftLastAccessTime = FileData.ftLastAccessTime; + pfad->ftLastWriteTime = FileData.ftLastWriteTime; + pfad->nFileSizeHigh = FileData.nFileSizeHigh; + pfad->nFileSizeLow = FileData.nFileSizeLow; + return TRUE; } -static int +static int win32_stat(const char* path, struct win32_stat *result) { - WIN32_FILE_ATTRIBUTE_DATA info; - int code; - char *dot; - if (!GetFileAttributesExA(path, GetFileExInfoStandard, &info)) { - if (GetLastError() != ERROR_SHARING_VIOLATION) { - /* Protocol violation: we explicitly clear errno, instead of - setting it to a POSIX error. Callers should use GetLastError. */ - errno = 0; - return -1; - } else { - /* Could not get attributes on open file. Fall back to - reading the directory. */ - if (!attributes_from_dir(path, &info)) { - /* Very strange. This should not fail now */ - errno = 0; - return -1; - } - } - } - code = attribute_data_to_stat(&info, result); - if (code != 0) - return code; - /* Set S_IFEXEC if it is an .exe, .bat, ... */ - dot = strrchr(path, '.'); - if (dot) { - if (stricmp(dot, ".bat") == 0 || - stricmp(dot, ".cmd") == 0 || - stricmp(dot, ".exe") == 0 || - stricmp(dot, ".com") == 0) - result->st_mode |= 0111; - } - return code; + WIN32_FILE_ATTRIBUTE_DATA info; + int code; + char *dot; + if (!GetFileAttributesExA(path, GetFileExInfoStandard, &info)) { + if (GetLastError() != ERROR_SHARING_VIOLATION) { + /* Protocol violation: we explicitly clear errno, instead of + setting it to a POSIX error. Callers should use GetLastError. */ + errno = 0; + return -1; + } else { + /* Could not get attributes on open file. Fall back to + reading the directory. */ + if (!attributes_from_dir(path, &info)) { + /* Very strange. This should not fail now */ + errno = 0; + return -1; + } + } + } + code = attribute_data_to_stat(&info, result); + if (code != 0) + return code; + /* Set S_IFEXEC if it is an .exe, .bat, ... */ + dot = strrchr(path, '.'); + if (dot) { + if (stricmp(dot, ".bat") == 0 || + stricmp(dot, ".cmd") == 0 || + stricmp(dot, ".exe") == 0 || + stricmp(dot, ".com") == 0) + result->st_mode |= 0111; + } + return code; } -static int +static int win32_wstat(const wchar_t* path, struct win32_stat *result) { - int code; - const wchar_t *dot; - WIN32_FILE_ATTRIBUTE_DATA info; - if (!GetFileAttributesExW(path, GetFileExInfoStandard, &info)) { - if (GetLastError() != ERROR_SHARING_VIOLATION) { - /* Protocol violation: we explicitly clear errno, instead of - setting it to a POSIX error. Callers should use GetLastError. */ - errno = 0; - return -1; - } else { - /* Could not get attributes on open file. Fall back to - reading the directory. */ - if (!attributes_from_dir_w(path, &info)) { - /* Very strange. This should not fail now */ - errno = 0; - return -1; - } - } - } - code = attribute_data_to_stat(&info, result); - if (code < 0) - return code; - /* Set IFEXEC if it is an .exe, .bat, ... */ - dot = wcsrchr(path, '.'); - if (dot) { - if (_wcsicmp(dot, L".bat") == 0 || - _wcsicmp(dot, L".cmd") == 0 || - _wcsicmp(dot, L".exe") == 0 || - _wcsicmp(dot, L".com") == 0) - result->st_mode |= 0111; - } - return code; + int code; + const wchar_t *dot; + WIN32_FILE_ATTRIBUTE_DATA info; + if (!GetFileAttributesExW(path, GetFileExInfoStandard, &info)) { + if (GetLastError() != ERROR_SHARING_VIOLATION) { + /* Protocol violation: we explicitly clear errno, instead of + setting it to a POSIX error. Callers should use GetLastError. */ + errno = 0; + return -1; + } else { + /* Could not get attributes on open file. Fall back to + reading the directory. */ + if (!attributes_from_dir_w(path, &info)) { + /* Very strange. This should not fail now */ + errno = 0; + return -1; + } + } + } + code = attribute_data_to_stat(&info, result); + if (code < 0) + return code; + /* Set IFEXEC if it is an .exe, .bat, ... */ + dot = wcsrchr(path, '.'); + if (dot) { + if (_wcsicmp(dot, L".bat") == 0 || + _wcsicmp(dot, L".cmd") == 0 || + _wcsicmp(dot, L".exe") == 0 || + _wcsicmp(dot, L".com") == 0) + result->st_mode |= 0111; + } + return code; } static int win32_fstat(int file_number, struct win32_stat *result) { - BY_HANDLE_FILE_INFORMATION info; - HANDLE h; - int type; - - h = (HANDLE)_get_osfhandle(file_number); - - /* Protocol violation: we explicitly clear errno, instead of - setting it to a POSIX error. Callers should use GetLastError. */ - errno = 0; - - if (h == INVALID_HANDLE_VALUE) { - /* This is really a C library error (invalid file handle). - We set the Win32 error to the closes one matching. */ - SetLastError(ERROR_INVALID_HANDLE); - return -1; - } - memset(result, 0, sizeof(*result)); - - type = GetFileType(h); - if (type == FILE_TYPE_UNKNOWN) { - DWORD error = GetLastError(); - if (error != 0) { - return -1; - } - /* else: valid but unknown file */ - } - - if (type != FILE_TYPE_DISK) { - if (type == FILE_TYPE_CHAR) - result->st_mode = _S_IFCHR; - else if (type == FILE_TYPE_PIPE) - result->st_mode = _S_IFIFO; - return 0; - } - - if (!GetFileInformationByHandle(h, &info)) { - return -1; - } - - /* similar to stat() */ - result->st_mode = attributes_to_mode(info.dwFileAttributes); - result->st_size = (((__int64)info.nFileSizeHigh)<<32) + info.nFileSizeLow; - FILE_TIME_to_time_t_nsec(&info.ftCreationTime, &result->st_ctime, &result->st_ctime_nsec); - FILE_TIME_to_time_t_nsec(&info.ftLastWriteTime, &result->st_mtime, &result->st_mtime_nsec); - FILE_TIME_to_time_t_nsec(&info.ftLastAccessTime, &result->st_atime, &result->st_atime_nsec); - /* specific to fstat() */ - result->st_nlink = info.nNumberOfLinks; - result->st_ino = (((__int64)info.nFileIndexHigh)<<32) + info.nFileIndexLow; - return 0; + BY_HANDLE_FILE_INFORMATION info; + HANDLE h; + int type; + + h = (HANDLE)_get_osfhandle(file_number); + + /* Protocol violation: we explicitly clear errno, instead of + setting it to a POSIX error. Callers should use GetLastError. */ + errno = 0; + + if (h == INVALID_HANDLE_VALUE) { + /* This is really a C library error (invalid file handle). + We set the Win32 error to the closes one matching. */ + SetLastError(ERROR_INVALID_HANDLE); + return -1; + } + memset(result, 0, sizeof(*result)); + + type = GetFileType(h); + if (type == FILE_TYPE_UNKNOWN) { + DWORD error = GetLastError(); + if (error != 0) { + return -1; + } + /* else: valid but unknown file */ + } + + if (type != FILE_TYPE_DISK) { + if (type == FILE_TYPE_CHAR) + result->st_mode = _S_IFCHR; + else if (type == FILE_TYPE_PIPE) + result->st_mode = _S_IFIFO; + return 0; + } + + if (!GetFileInformationByHandle(h, &info)) { + return -1; + } + + /* similar to stat() */ + result->st_mode = attributes_to_mode(info.dwFileAttributes); + result->st_size = (((__int64)info.nFileSizeHigh)<<32) + info.nFileSizeLow; + FILE_TIME_to_time_t_nsec(&info.ftCreationTime, &result->st_ctime, &result->st_ctime_nsec); + FILE_TIME_to_time_t_nsec(&info.ftLastWriteTime, &result->st_mtime, &result->st_mtime_nsec); + FILE_TIME_to_time_t_nsec(&info.ftLastAccessTime, &result->st_atime, &result->st_atime_nsec); + /* specific to fstat() */ + result->st_nlink = info.nNumberOfLinks; + result->st_ino = (((__int64)info.nFileIndexHigh)<<32) + info.nFileIndexLow; + return 0; } #endif /* MS_WINDOWS */ @@ -1101,39 +1101,39 @@ See os.stat for more information."); static PyStructSequence_Field stat_result_fields[] = { - {"st_mode", "protection bits"}, - {"st_ino", "inode"}, - {"st_dev", "device"}, - {"st_nlink", "number of hard links"}, - {"st_uid", "user ID of owner"}, - {"st_gid", "group ID of owner"}, - {"st_size", "total size, in bytes"}, - /* The NULL is replaced with PyStructSequence_UnnamedField later. */ - {NULL, "integer time of last access"}, - {NULL, "integer time of last modification"}, - {NULL, "integer time of last change"}, - {"st_atime", "time of last access"}, - {"st_mtime", "time of last modification"}, - {"st_ctime", "time of last change"}, + {"st_mode", "protection bits"}, + {"st_ino", "inode"}, + {"st_dev", "device"}, + {"st_nlink", "number of hard links"}, + {"st_uid", "user ID of owner"}, + {"st_gid", "group ID of owner"}, + {"st_size", "total size, in bytes"}, + /* The NULL is replaced with PyStructSequence_UnnamedField later. */ + {NULL, "integer time of last access"}, + {NULL, "integer time of last modification"}, + {NULL, "integer time of last change"}, + {"st_atime", "time of last access"}, + {"st_mtime", "time of last modification"}, + {"st_ctime", "time of last change"}, #ifdef HAVE_STRUCT_STAT_ST_BLKSIZE - {"st_blksize", "blocksize for filesystem I/O"}, + {"st_blksize", "blocksize for filesystem I/O"}, #endif #ifdef HAVE_STRUCT_STAT_ST_BLOCKS - {"st_blocks", "number of blocks allocated"}, + {"st_blocks", "number of blocks allocated"}, #endif #ifdef HAVE_STRUCT_STAT_ST_RDEV - {"st_rdev", "device type (if inode device)"}, + {"st_rdev", "device type (if inode device)"}, #endif #ifdef HAVE_STRUCT_STAT_ST_FLAGS - {"st_flags", "user defined flags for file"}, + {"st_flags", "user defined flags for file"}, #endif #ifdef HAVE_STRUCT_STAT_ST_GEN - {"st_gen", "generation number"}, + {"st_gen", "generation number"}, #endif #ifdef HAVE_STRUCT_STAT_ST_BIRTHTIME - {"st_birthtime", "time of creation"}, + {"st_birthtime", "time of creation"}, #endif - {0} + {0} }; #ifdef HAVE_STRUCT_STAT_ST_BLKSIZE @@ -1173,10 +1173,10 @@ #endif static PyStructSequence_Desc stat_result_desc = { - "stat_result", /* name */ - stat_result__doc__, /* doc */ - stat_result_fields, - 10 + "stat_result", /* name */ + stat_result__doc__, /* doc */ + stat_result_fields, + 10 }; PyDoc_STRVAR(statvfs_result__doc__, @@ -1188,24 +1188,24 @@ See os.statvfs for more information."); static PyStructSequence_Field statvfs_result_fields[] = { - {"f_bsize", }, - {"f_frsize", }, - {"f_blocks", }, - {"f_bfree", }, - {"f_bavail", }, - {"f_files", }, - {"f_ffree", }, - {"f_favail", }, - {"f_flag", }, - {"f_namemax",}, - {0} + {"f_bsize", }, + {"f_frsize", }, + {"f_blocks", }, + {"f_bfree", }, + {"f_bavail", }, + {"f_files", }, + {"f_ffree", }, + {"f_favail", }, + {"f_flag", }, + {"f_namemax",}, + {0} }; static PyStructSequence_Desc statvfs_result_desc = { - "statvfs_result", /* name */ - statvfs_result__doc__, /* doc */ - statvfs_result_fields, - 10 + "statvfs_result", /* name */ + statvfs_result__doc__, /* doc */ + statvfs_result_fields, + 10 }; static int initialized; @@ -1216,23 +1216,23 @@ static PyObject * statresult_new(PyTypeObject *type, PyObject *args, PyObject *kwds) { - PyStructSequence *result; - int i; + PyStructSequence *result; + int i; - result = (PyStructSequence*)structseq_new(type, args, kwds); - if (!result) - return NULL; - /* If we have been initialized from a tuple, - st_?time might be set to None. Initialize it - from the int slots. */ - for (i = 7; i <= 9; i++) { - if (result->ob_item[i+3] == Py_None) { - Py_DECREF(Py_None); - Py_INCREF(result->ob_item[i]); - result->ob_item[i+3] = result->ob_item[i]; - } - } - return (PyObject*)result; + result = (PyStructSequence*)structseq_new(type, args, kwds); + if (!result) + return NULL; + /* If we have been initialized from a tuple, + st_?time might be set to None. Initialize it + from the int slots. */ + for (i = 7; i <= 9; i++) { + if (result->ob_item[i+3] == Py_None) { + Py_DECREF(Py_None); + Py_INCREF(result->ob_item[i]); + result->ob_item[i+3] = result->ob_item[i]; + } + } + return (PyObject*)result; } @@ -1250,36 +1250,36 @@ static PyObject* stat_float_times(PyObject* self, PyObject *args) { - int newval = -1; - if (!PyArg_ParseTuple(args, "|i:stat_float_times", &newval)) - return NULL; - if (newval == -1) - /* Return old value */ - return PyBool_FromLong(_stat_float_times); - _stat_float_times = newval; - Py_INCREF(Py_None); - return Py_None; + int newval = -1; + if (!PyArg_ParseTuple(args, "|i:stat_float_times", &newval)) + return NULL; + if (newval == -1) + /* Return old value */ + return PyBool_FromLong(_stat_float_times); + _stat_float_times = newval; + Py_INCREF(Py_None); + return Py_None; } static void fill_time(PyObject *v, int index, time_t sec, unsigned long nsec) { - PyObject *fval,*ival; + PyObject *fval,*ival; #if SIZEOF_TIME_T > SIZEOF_LONG - ival = PyLong_FromLongLong((PY_LONG_LONG)sec); + ival = PyLong_FromLongLong((PY_LONG_LONG)sec); #else - ival = PyInt_FromLong((long)sec); + ival = PyInt_FromLong((long)sec); #endif - if (!ival) - return; - if (_stat_float_times) { - fval = PyFloat_FromDouble(sec + 1e-9*nsec); - } else { - fval = ival; - Py_INCREF(fval); - } - PyStructSequence_SET_ITEM(v, index, ival); - PyStructSequence_SET_ITEM(v, index+3, fval); + if (!ival) + return; + if (_stat_float_times) { + fval = PyFloat_FromDouble(sec + 1e-9*nsec); + } else { + fval = ival; + Py_INCREF(fval); + } + PyStructSequence_SET_ITEM(v, index, ival); + PyStructSequence_SET_ITEM(v, index+3, fval); } /* pack a system stat C structure into the Python stat tuple @@ -1287,99 +1287,99 @@ static PyObject* _pystat_fromstructstat(STRUCT_STAT *st) { - unsigned long ansec, mnsec, cnsec; - PyObject *v = PyStructSequence_New(&StatResultType); - if (v == NULL) - return NULL; + unsigned long ansec, mnsec, cnsec; + PyObject *v = PyStructSequence_New(&StatResultType); + if (v == NULL) + return NULL; - PyStructSequence_SET_ITEM(v, 0, PyInt_FromLong((long)st->st_mode)); + PyStructSequence_SET_ITEM(v, 0, PyInt_FromLong((long)st->st_mode)); #ifdef HAVE_LARGEFILE_SUPPORT - PyStructSequence_SET_ITEM(v, 1, - PyLong_FromLongLong((PY_LONG_LONG)st->st_ino)); + PyStructSequence_SET_ITEM(v, 1, + PyLong_FromLongLong((PY_LONG_LONG)st->st_ino)); #else - PyStructSequence_SET_ITEM(v, 1, PyInt_FromLong((long)st->st_ino)); + PyStructSequence_SET_ITEM(v, 1, PyInt_FromLong((long)st->st_ino)); #endif #if defined(HAVE_LONG_LONG) && !defined(MS_WINDOWS) - PyStructSequence_SET_ITEM(v, 2, - PyLong_FromLongLong((PY_LONG_LONG)st->st_dev)); + PyStructSequence_SET_ITEM(v, 2, + PyLong_FromLongLong((PY_LONG_LONG)st->st_dev)); #else - PyStructSequence_SET_ITEM(v, 2, PyInt_FromLong((long)st->st_dev)); + PyStructSequence_SET_ITEM(v, 2, PyInt_FromLong((long)st->st_dev)); #endif - PyStructSequence_SET_ITEM(v, 3, PyInt_FromLong((long)st->st_nlink)); - PyStructSequence_SET_ITEM(v, 4, PyInt_FromLong((long)st->st_uid)); - PyStructSequence_SET_ITEM(v, 5, PyInt_FromLong((long)st->st_gid)); + PyStructSequence_SET_ITEM(v, 3, PyInt_FromLong((long)st->st_nlink)); + PyStructSequence_SET_ITEM(v, 4, PyInt_FromLong((long)st->st_uid)); + PyStructSequence_SET_ITEM(v, 5, PyInt_FromLong((long)st->st_gid)); #ifdef HAVE_LARGEFILE_SUPPORT - PyStructSequence_SET_ITEM(v, 6, - PyLong_FromLongLong((PY_LONG_LONG)st->st_size)); + PyStructSequence_SET_ITEM(v, 6, + PyLong_FromLongLong((PY_LONG_LONG)st->st_size)); #else - PyStructSequence_SET_ITEM(v, 6, PyInt_FromLong(st->st_size)); + PyStructSequence_SET_ITEM(v, 6, PyInt_FromLong(st->st_size)); #endif #if defined(HAVE_STAT_TV_NSEC) - ansec = st->st_atim.tv_nsec; - mnsec = st->st_mtim.tv_nsec; - cnsec = st->st_ctim.tv_nsec; + ansec = st->st_atim.tv_nsec; + mnsec = st->st_mtim.tv_nsec; + cnsec = st->st_ctim.tv_nsec; #elif defined(HAVE_STAT_TV_NSEC2) - ansec = st->st_atimespec.tv_nsec; - mnsec = st->st_mtimespec.tv_nsec; - cnsec = st->st_ctimespec.tv_nsec; + ansec = st->st_atimespec.tv_nsec; + mnsec = st->st_mtimespec.tv_nsec; + cnsec = st->st_ctimespec.tv_nsec; #elif defined(HAVE_STAT_NSEC) - ansec = st->st_atime_nsec; - mnsec = st->st_mtime_nsec; - cnsec = st->st_ctime_nsec; -#else - ansec = mnsec = cnsec = 0; -#endif - fill_time(v, 7, st->st_atime, ansec); - fill_time(v, 8, st->st_mtime, mnsec); - fill_time(v, 9, st->st_ctime, cnsec); + ansec = st->st_atime_nsec; + mnsec = st->st_mtime_nsec; + cnsec = st->st_ctime_nsec; +#else + ansec = mnsec = cnsec = 0; +#endif + fill_time(v, 7, st->st_atime, ansec); + fill_time(v, 8, st->st_mtime, mnsec); + fill_time(v, 9, st->st_ctime, cnsec); #ifdef HAVE_STRUCT_STAT_ST_BLKSIZE - PyStructSequence_SET_ITEM(v, ST_BLKSIZE_IDX, - PyInt_FromLong((long)st->st_blksize)); + PyStructSequence_SET_ITEM(v, ST_BLKSIZE_IDX, + PyInt_FromLong((long)st->st_blksize)); #endif #ifdef HAVE_STRUCT_STAT_ST_BLOCKS - PyStructSequence_SET_ITEM(v, ST_BLOCKS_IDX, - PyInt_FromLong((long)st->st_blocks)); + PyStructSequence_SET_ITEM(v, ST_BLOCKS_IDX, + PyInt_FromLong((long)st->st_blocks)); #endif #ifdef HAVE_STRUCT_STAT_ST_RDEV - PyStructSequence_SET_ITEM(v, ST_RDEV_IDX, - PyInt_FromLong((long)st->st_rdev)); + PyStructSequence_SET_ITEM(v, ST_RDEV_IDX, + PyInt_FromLong((long)st->st_rdev)); #endif #ifdef HAVE_STRUCT_STAT_ST_GEN - PyStructSequence_SET_ITEM(v, ST_GEN_IDX, - PyInt_FromLong((long)st->st_gen)); + PyStructSequence_SET_ITEM(v, ST_GEN_IDX, + PyInt_FromLong((long)st->st_gen)); #endif #ifdef HAVE_STRUCT_STAT_ST_BIRTHTIME - { - PyObject *val; - unsigned long bsec,bnsec; - bsec = (long)st->st_birthtime; + { + PyObject *val; + unsigned long bsec,bnsec; + bsec = (long)st->st_birthtime; #ifdef HAVE_STAT_TV_NSEC2 - bnsec = st->st_birthtimespec.tv_nsec; + bnsec = st->st_birthtimespec.tv_nsec; #else - bnsec = 0; + bnsec = 0; #endif - if (_stat_float_times) { - val = PyFloat_FromDouble(bsec + 1e-9*bnsec); - } else { - val = PyInt_FromLong((long)bsec); - } - PyStructSequence_SET_ITEM(v, ST_BIRTHTIME_IDX, - val); - } + if (_stat_float_times) { + val = PyFloat_FromDouble(bsec + 1e-9*bnsec); + } else { + val = PyInt_FromLong((long)bsec); + } + PyStructSequence_SET_ITEM(v, ST_BIRTHTIME_IDX, + val); + } #endif #ifdef HAVE_STRUCT_STAT_ST_FLAGS - PyStructSequence_SET_ITEM(v, ST_FLAGS_IDX, - PyInt_FromLong((long)st->st_flags)); + PyStructSequence_SET_ITEM(v, ST_FLAGS_IDX, + PyInt_FromLong((long)st->st_flags)); #endif - if (PyErr_Occurred()) { - Py_DECREF(v); - return NULL; - } + if (PyErr_Occurred()) { + Py_DECREF(v); + return NULL; + } - return v; + return v; } #ifdef MS_WINDOWS @@ -1398,108 +1398,108 @@ static BOOL IsUNCRootA(char *path, int pathlen) { - #define ISSLASH ISSLASHA + #define ISSLASH ISSLASHA - int i, share; + int i, share; - if (pathlen < 5 || !ISSLASH(path[0]) || !ISSLASH(path[1])) - /* minimum UNCRoot is \\x\y */ - return FALSE; - for (i = 2; i < pathlen ; i++) - if (ISSLASH(path[i])) break; - if (i == 2 || i == pathlen) - /* do not allow \\\SHARE or \\SERVER */ - return FALSE; - share = i+1; - for (i = share; i < pathlen; i++) - if (ISSLASH(path[i])) break; - return (i != share && (i == pathlen || i == pathlen-1)); + if (pathlen < 5 || !ISSLASH(path[0]) || !ISSLASH(path[1])) + /* minimum UNCRoot is \\x\y */ + return FALSE; + for (i = 2; i < pathlen ; i++) + if (ISSLASH(path[i])) break; + if (i == 2 || i == pathlen) + /* do not allow \\\SHARE or \\SERVER */ + return FALSE; + share = i+1; + for (i = share; i < pathlen; i++) + if (ISSLASH(path[i])) break; + return (i != share && (i == pathlen || i == pathlen-1)); - #undef ISSLASH + #undef ISSLASH } static BOOL IsUNCRootW(Py_UNICODE *path, int pathlen) { - #define ISSLASH ISSLASHW + #define ISSLASH ISSLASHW - int i, share; + int i, share; - if (pathlen < 5 || !ISSLASH(path[0]) || !ISSLASH(path[1])) - /* minimum UNCRoot is \\x\y */ - return FALSE; - for (i = 2; i < pathlen ; i++) - if (ISSLASH(path[i])) break; - if (i == 2 || i == pathlen) - /* do not allow \\\SHARE or \\SERVER */ - return FALSE; - share = i+1; - for (i = share; i < pathlen; i++) - if (ISSLASH(path[i])) break; - return (i != share && (i == pathlen || i == pathlen-1)); + if (pathlen < 5 || !ISSLASH(path[0]) || !ISSLASH(path[1])) + /* minimum UNCRoot is \\x\y */ + return FALSE; + for (i = 2; i < pathlen ; i++) + if (ISSLASH(path[i])) break; + if (i == 2 || i == pathlen) + /* do not allow \\\SHARE or \\SERVER */ + return FALSE; + share = i+1; + for (i = share; i < pathlen; i++) + if (ISSLASH(path[i])) break; + return (i != share && (i == pathlen || i == pathlen-1)); - #undef ISSLASH + #undef ISSLASH } #endif /* MS_WINDOWS */ static PyObject * posix_do_stat(PyObject *self, PyObject *args, - char *format, + char *format, #ifdef __VMS - int (*statfunc)(const char *, STRUCT_STAT *, ...), + int (*statfunc)(const char *, STRUCT_STAT *, ...), #else - int (*statfunc)(const char *, STRUCT_STAT *), + int (*statfunc)(const char *, STRUCT_STAT *), #endif - char *wformat, - int (*wstatfunc)(const Py_UNICODE *, STRUCT_STAT *)) + char *wformat, + int (*wstatfunc)(const Py_UNICODE *, STRUCT_STAT *)) { - STRUCT_STAT st; - char *path = NULL; /* pass this to stat; do not free() it */ - char *pathfree = NULL; /* this memory must be free'd */ - int res; - PyObject *result; + STRUCT_STAT st; + char *path = NULL; /* pass this to stat; do not free() it */ + char *pathfree = NULL; /* this memory must be free'd */ + int res; + PyObject *result; #ifdef MS_WINDOWS - PyUnicodeObject *po; - if (PyArg_ParseTuple(args, wformat, &po)) { - Py_UNICODE *wpath = PyUnicode_AS_UNICODE(po); - - Py_BEGIN_ALLOW_THREADS - /* PyUnicode_AS_UNICODE result OK without - thread lock as it is a simple dereference. */ - res = wstatfunc(wpath, &st); - Py_END_ALLOW_THREADS - - if (res != 0) - return win32_error_unicode("stat", wpath); - return _pystat_fromstructstat(&st); - } - /* Drop the argument parsing error as narrow strings - are also valid. */ - PyErr_Clear(); -#endif - - if (!PyArg_ParseTuple(args, format, - Py_FileSystemDefaultEncoding, &path)) - return NULL; - pathfree = path; - - Py_BEGIN_ALLOW_THREADS - res = (*statfunc)(path, &st); - Py_END_ALLOW_THREADS + PyUnicodeObject *po; + if (PyArg_ParseTuple(args, wformat, &po)) { + Py_UNICODE *wpath = PyUnicode_AS_UNICODE(po); + + Py_BEGIN_ALLOW_THREADS + /* PyUnicode_AS_UNICODE result OK without + thread lock as it is a simple dereference. */ + res = wstatfunc(wpath, &st); + Py_END_ALLOW_THREADS + + if (res != 0) + return win32_error_unicode("stat", wpath); + return _pystat_fromstructstat(&st); + } + /* Drop the argument parsing error as narrow strings + are also valid. */ + PyErr_Clear(); +#endif + + if (!PyArg_ParseTuple(args, format, + Py_FileSystemDefaultEncoding, &path)) + return NULL; + pathfree = path; + + Py_BEGIN_ALLOW_THREADS + res = (*statfunc)(path, &st); + Py_END_ALLOW_THREADS - if (res != 0) { + if (res != 0) { #ifdef MS_WINDOWS - result = win32_error("stat", pathfree); + result = win32_error("stat", pathfree); #else - result = posix_error_with_filename(pathfree); + result = posix_error_with_filename(pathfree); #endif - } - else - result = _pystat_fromstructstat(&st); + } + else + result = _pystat_fromstructstat(&st); - PyMem_Free(pathfree); - return result; + PyMem_Free(pathfree); + return result; } /* POSIX methods */ @@ -1515,50 +1515,50 @@ static PyObject * posix_access(PyObject *self, PyObject *args) { - char *path; - int mode; - + char *path; + int mode; + #ifdef MS_WINDOWS - DWORD attr; - PyUnicodeObject *po; - if (PyArg_ParseTuple(args, "Ui:access", &po, &mode)) { - Py_BEGIN_ALLOW_THREADS - /* PyUnicode_AS_UNICODE OK without thread lock as - it is a simple dereference. */ - attr = GetFileAttributesW(PyUnicode_AS_UNICODE(po)); - Py_END_ALLOW_THREADS - goto finish; - } - /* Drop the argument parsing error as narrow strings - are also valid. */ - PyErr_Clear(); - if (!PyArg_ParseTuple(args, "eti:access", - Py_FileSystemDefaultEncoding, &path, &mode)) - return NULL; - Py_BEGIN_ALLOW_THREADS - attr = GetFileAttributesA(path); - Py_END_ALLOW_THREADS - PyMem_Free(path); + DWORD attr; + PyUnicodeObject *po; + if (PyArg_ParseTuple(args, "Ui:access", &po, &mode)) { + Py_BEGIN_ALLOW_THREADS + /* PyUnicode_AS_UNICODE OK without thread lock as + it is a simple dereference. */ + attr = GetFileAttributesW(PyUnicode_AS_UNICODE(po)); + Py_END_ALLOW_THREADS + goto finish; + } + /* Drop the argument parsing error as narrow strings + are also valid. */ + PyErr_Clear(); + if (!PyArg_ParseTuple(args, "eti:access", + Py_FileSystemDefaultEncoding, &path, &mode)) + return NULL; + Py_BEGIN_ALLOW_THREADS + attr = GetFileAttributesA(path); + Py_END_ALLOW_THREADS + PyMem_Free(path); finish: - if (attr == 0xFFFFFFFF) - /* File does not exist, or cannot read attributes */ - return PyBool_FromLong(0); - /* Access is possible if either write access wasn't requested, or - the file isn't read-only, or if it's a directory, as there are - no read-only directories on Windows. */ - return PyBool_FromLong(!(mode & 2) - || !(attr & FILE_ATTRIBUTE_READONLY) - || (attr & FILE_ATTRIBUTE_DIRECTORY)); + if (attr == 0xFFFFFFFF) + /* File does not exist, or cannot read attributes */ + return PyBool_FromLong(0); + /* Access is possible if either write access wasn't requested, or + the file isn't read-only, or if it's a directory, as there are + no read-only directories on Windows. */ + return PyBool_FromLong(!(mode & 2) + || !(attr & FILE_ATTRIBUTE_READONLY) + || (attr & FILE_ATTRIBUTE_DIRECTORY)); #else /* MS_WINDOWS */ - int res; - if (!PyArg_ParseTuple(args, "eti:access", - Py_FileSystemDefaultEncoding, &path, &mode)) - return NULL; - Py_BEGIN_ALLOW_THREADS - res = access(path, mode); - Py_END_ALLOW_THREADS - PyMem_Free(path); - return PyBool_FromLong(res == 0); + int res; + if (!PyArg_ParseTuple(args, "eti:access", + Py_FileSystemDefaultEncoding, &path, &mode)) + return NULL; + Py_BEGIN_ALLOW_THREADS + res = access(path, mode); + Py_END_ALLOW_THREADS + PyMem_Free(path); + return PyBool_FromLong(res == 0); #endif /* MS_WINDOWS */ } @@ -1583,26 +1583,26 @@ static PyObject * posix_ttyname(PyObject *self, PyObject *args) { - int id; - char *ret; + int id; + char *ret; - if (!PyArg_ParseTuple(args, "i:ttyname", &id)) - return NULL; + if (!PyArg_ParseTuple(args, "i:ttyname", &id)) + return NULL; #if defined(__VMS) - /* file descriptor 0 only, the default input device (stdin) */ - if (id == 0) { - ret = ttyname(); - } - else { - ret = NULL; - } -#else - ret = ttyname(id); -#endif - if (ret == NULL) - return posix_error(); - return PyString_FromString(ret); + /* file descriptor 0 only, the default input device (stdin) */ + if (id == 0) { + ret = ttyname(); + } + else { + ret = NULL; + } +#else + ret = ttyname(id); +#endif + if (ret == NULL) + return posix_error(); + return PyString_FromString(ret); } #endif @@ -1614,17 +1614,17 @@ static PyObject * posix_ctermid(PyObject *self, PyObject *noargs) { - char *ret; - char buffer[L_ctermid]; + char *ret; + char buffer[L_ctermid]; #ifdef USE_CTERMID_R - ret = ctermid_r(buffer); + ret = ctermid_r(buffer); #else - ret = ctermid(buffer); + ret = ctermid(buffer); #endif - if (ret == NULL) - return posix_error(); - return PyString_FromString(buffer); + if (ret == NULL) + return posix_error(); + return PyString_FromString(buffer); } #endif @@ -1636,13 +1636,13 @@ posix_chdir(PyObject *self, PyObject *args) { #ifdef MS_WINDOWS - return win32_1str(args, "chdir", "s:chdir", win32_chdir, "U:chdir", win32_wchdir); + return win32_1str(args, "chdir", "s:chdir", win32_chdir, "U:chdir", win32_wchdir); #elif defined(PYOS_OS2) && defined(PYCC_GCC) - return posix_1str(args, "et:chdir", _chdir2); + return posix_1str(args, "et:chdir", _chdir2); #elif defined(__VMS) - return posix_1str(args, "et:chdir", (int (*)(const char *))chdir); + return posix_1str(args, "et:chdir", (int (*)(const char *))chdir); #else - return posix_1str(args, "et:chdir", chdir); + return posix_1str(args, "et:chdir", chdir); #endif } @@ -1655,7 +1655,7 @@ static PyObject * posix_fchdir(PyObject *self, PyObject *fdobj) { - return posix_fildes(fdobj, fchdir); + return posix_fildes(fdobj, fchdir); } #endif /* HAVE_FCHDIR */ @@ -1667,70 +1667,70 @@ static PyObject * posix_chmod(PyObject *self, PyObject *args) { - char *path = NULL; - int i; - int res; + char *path = NULL; + int i; + int res; #ifdef MS_WINDOWS - DWORD attr; - PyUnicodeObject *po; - if (PyArg_ParseTuple(args, "Ui|:chmod", &po, &i)) { - Py_BEGIN_ALLOW_THREADS - attr = GetFileAttributesW(PyUnicode_AS_UNICODE(po)); - if (attr != 0xFFFFFFFF) { - if (i & _S_IWRITE) - attr &= ~FILE_ATTRIBUTE_READONLY; - else - attr |= FILE_ATTRIBUTE_READONLY; - res = SetFileAttributesW(PyUnicode_AS_UNICODE(po), attr); - } - else - res = 0; - Py_END_ALLOW_THREADS - if (!res) - return win32_error_unicode("chmod", - PyUnicode_AS_UNICODE(po)); - Py_INCREF(Py_None); - return Py_None; - } - /* Drop the argument parsing error as narrow strings - are also valid. */ - PyErr_Clear(); - - if (!PyArg_ParseTuple(args, "eti:chmod", Py_FileSystemDefaultEncoding, - &path, &i)) - return NULL; - Py_BEGIN_ALLOW_THREADS - attr = GetFileAttributesA(path); - if (attr != 0xFFFFFFFF) { - if (i & _S_IWRITE) - attr &= ~FILE_ATTRIBUTE_READONLY; - else - attr |= FILE_ATTRIBUTE_READONLY; - res = SetFileAttributesA(path, attr); - } - else - res = 0; - Py_END_ALLOW_THREADS - if (!res) { - win32_error("chmod", path); - PyMem_Free(path); - return NULL; - } - PyMem_Free(path); - Py_INCREF(Py_None); - return Py_None; + DWORD attr; + PyUnicodeObject *po; + if (PyArg_ParseTuple(args, "Ui|:chmod", &po, &i)) { + Py_BEGIN_ALLOW_THREADS + attr = GetFileAttributesW(PyUnicode_AS_UNICODE(po)); + if (attr != 0xFFFFFFFF) { + if (i & _S_IWRITE) + attr &= ~FILE_ATTRIBUTE_READONLY; + else + attr |= FILE_ATTRIBUTE_READONLY; + res = SetFileAttributesW(PyUnicode_AS_UNICODE(po), attr); + } + else + res = 0; + Py_END_ALLOW_THREADS + if (!res) + return win32_error_unicode("chmod", + PyUnicode_AS_UNICODE(po)); + Py_INCREF(Py_None); + return Py_None; + } + /* Drop the argument parsing error as narrow strings + are also valid. */ + PyErr_Clear(); + + if (!PyArg_ParseTuple(args, "eti:chmod", Py_FileSystemDefaultEncoding, + &path, &i)) + return NULL; + Py_BEGIN_ALLOW_THREADS + attr = GetFileAttributesA(path); + if (attr != 0xFFFFFFFF) { + if (i & _S_IWRITE) + attr &= ~FILE_ATTRIBUTE_READONLY; + else + attr |= FILE_ATTRIBUTE_READONLY; + res = SetFileAttributesA(path, attr); + } + else + res = 0; + Py_END_ALLOW_THREADS + if (!res) { + win32_error("chmod", path); + PyMem_Free(path); + return NULL; + } + PyMem_Free(path); + Py_INCREF(Py_None); + return Py_None; #else /* MS_WINDOWS */ - if (!PyArg_ParseTuple(args, "eti:chmod", Py_FileSystemDefaultEncoding, - &path, &i)) - return NULL; - Py_BEGIN_ALLOW_THREADS - res = chmod(path, i); - Py_END_ALLOW_THREADS - if (res < 0) - return posix_error_with_allocated_filename(path); - PyMem_Free(path); - Py_INCREF(Py_None); - return Py_None; + if (!PyArg_ParseTuple(args, "eti:chmod", Py_FileSystemDefaultEncoding, + &path, &i)) + return NULL; + Py_BEGIN_ALLOW_THREADS + res = chmod(path, i); + Py_END_ALLOW_THREADS + if (res < 0) + return posix_error_with_allocated_filename(path); + PyMem_Free(path); + Py_INCREF(Py_None); + return Py_None; #endif } @@ -1743,15 +1743,15 @@ static PyObject * posix_fchmod(PyObject *self, PyObject *args) { - int fd, mode, res; - if (!PyArg_ParseTuple(args, "ii:fchmod", &fd, &mode)) - return NULL; - Py_BEGIN_ALLOW_THREADS - res = fchmod(fd, mode); - Py_END_ALLOW_THREADS - if (res < 0) - return posix_error(); - Py_RETURN_NONE; + int fd, mode, res; + if (!PyArg_ParseTuple(args, "ii:fchmod", &fd, &mode)) + return NULL; + Py_BEGIN_ALLOW_THREADS + res = fchmod(fd, mode); + Py_END_ALLOW_THREADS + if (res < 0) + return posix_error(); + Py_RETURN_NONE; } #endif /* HAVE_FCHMOD */ @@ -1764,19 +1764,19 @@ static PyObject * posix_lchmod(PyObject *self, PyObject *args) { - char *path = NULL; - int i; - int res; - if (!PyArg_ParseTuple(args, "eti:lchmod", Py_FileSystemDefaultEncoding, - &path, &i)) - return NULL; - Py_BEGIN_ALLOW_THREADS - res = lchmod(path, i); - Py_END_ALLOW_THREADS - if (res < 0) - return posix_error_with_allocated_filename(path); - PyMem_Free(path); - Py_RETURN_NONE; + char *path = NULL; + int i; + int res; + if (!PyArg_ParseTuple(args, "eti:lchmod", Py_FileSystemDefaultEncoding, + &path, &i)) + return NULL; + Py_BEGIN_ALLOW_THREADS + res = lchmod(path, i); + Py_END_ALLOW_THREADS + if (res < 0) + return posix_error_with_allocated_filename(path); + PyMem_Free(path); + Py_RETURN_NONE; } #endif /* HAVE_LCHMOD */ @@ -1789,20 +1789,20 @@ static PyObject * posix_chflags(PyObject *self, PyObject *args) { - char *path; - unsigned long flags; - int res; - if (!PyArg_ParseTuple(args, "etk:chflags", - Py_FileSystemDefaultEncoding, &path, &flags)) - return NULL; - Py_BEGIN_ALLOW_THREADS - res = chflags(path, flags); - Py_END_ALLOW_THREADS - if (res < 0) - return posix_error_with_allocated_filename(path); - PyMem_Free(path); - Py_INCREF(Py_None); - return Py_None; + char *path; + unsigned long flags; + int res; + if (!PyArg_ParseTuple(args, "etk:chflags", + Py_FileSystemDefaultEncoding, &path, &flags)) + return NULL; + Py_BEGIN_ALLOW_THREADS + res = chflags(path, flags); + Py_END_ALLOW_THREADS + if (res < 0) + return posix_error_with_allocated_filename(path); + PyMem_Free(path); + Py_INCREF(Py_None); + return Py_None; } #endif /* HAVE_CHFLAGS */ @@ -1815,20 +1815,20 @@ static PyObject * posix_lchflags(PyObject *self, PyObject *args) { - char *path; - unsigned long flags; - int res; - if (!PyArg_ParseTuple(args, "etk:lchflags", - Py_FileSystemDefaultEncoding, &path, &flags)) - return NULL; - Py_BEGIN_ALLOW_THREADS - res = lchflags(path, flags); - Py_END_ALLOW_THREADS - if (res < 0) - return posix_error_with_allocated_filename(path); - PyMem_Free(path); - Py_INCREF(Py_None); - return Py_None; + char *path; + unsigned long flags; + int res; + if (!PyArg_ParseTuple(args, "etk:lchflags", + Py_FileSystemDefaultEncoding, &path, &flags)) + return NULL; + Py_BEGIN_ALLOW_THREADS + res = lchflags(path, flags); + Py_END_ALLOW_THREADS + if (res < 0) + return posix_error_with_allocated_filename(path); + PyMem_Free(path); + Py_INCREF(Py_None); + return Py_None; } #endif /* HAVE_LCHFLAGS */ @@ -1840,7 +1840,7 @@ static PyObject * posix_chroot(PyObject *self, PyObject *args) { - return posix_1str(args, "et:chroot", chroot); + return posix_1str(args, "et:chroot", chroot); } #endif @@ -1883,21 +1883,21 @@ static PyObject * posix_chown(PyObject *self, PyObject *args) { - char *path = NULL; - long uid, gid; - int res; - if (!PyArg_ParseTuple(args, "etll:chown", - Py_FileSystemDefaultEncoding, &path, - &uid, &gid)) - return NULL; - Py_BEGIN_ALLOW_THREADS - res = chown(path, (uid_t) uid, (gid_t) gid); - Py_END_ALLOW_THREADS - if (res < 0) - return posix_error_with_allocated_filename(path); - PyMem_Free(path); - Py_INCREF(Py_None); - return Py_None; + char *path = NULL; + long uid, gid; + int res; + if (!PyArg_ParseTuple(args, "etll:chown", + Py_FileSystemDefaultEncoding, &path, + &uid, &gid)) + return NULL; + Py_BEGIN_ALLOW_THREADS + res = chown(path, (uid_t) uid, (gid_t) gid); + Py_END_ALLOW_THREADS + if (res < 0) + return posix_error_with_allocated_filename(path); + PyMem_Free(path); + Py_INCREF(Py_None); + return Py_None; } #endif /* HAVE_CHOWN */ @@ -1910,17 +1910,17 @@ static PyObject * posix_fchown(PyObject *self, PyObject *args) { - int fd; - long uid, gid; - int res; - if (!PyArg_ParseTuple(args, "ill:chown", &fd, &uid, &gid)) - return NULL; - Py_BEGIN_ALLOW_THREADS - res = fchown(fd, (uid_t) uid, (gid_t) gid); - Py_END_ALLOW_THREADS - if (res < 0) - return posix_error(); - Py_RETURN_NONE; + int fd; + long uid, gid; + int res; + if (!PyArg_ParseTuple(args, "ill:chown", &fd, &uid, &gid)) + return NULL; + Py_BEGIN_ALLOW_THREADS + res = fchown(fd, (uid_t) uid, (gid_t) gid); + Py_END_ALLOW_THREADS + if (res < 0) + return posix_error(); + Py_RETURN_NONE; } #endif /* HAVE_FCHOWN */ @@ -1933,21 +1933,21 @@ static PyObject * posix_lchown(PyObject *self, PyObject *args) { - char *path = NULL; - long uid, gid; - int res; - if (!PyArg_ParseTuple(args, "etll:lchown", - Py_FileSystemDefaultEncoding, &path, - &uid, &gid)) - return NULL; - Py_BEGIN_ALLOW_THREADS - res = lchown(path, (uid_t) uid, (gid_t) gid); - Py_END_ALLOW_THREADS - if (res < 0) - return posix_error_with_allocated_filename(path); - PyMem_Free(path); - Py_INCREF(Py_None); - return Py_None; + char *path = NULL; + long uid, gid; + int res; + if (!PyArg_ParseTuple(args, "etll:lchown", + Py_FileSystemDefaultEncoding, &path, + &uid, &gid)) + return NULL; + Py_BEGIN_ALLOW_THREADS + res = lchown(path, (uid_t) uid, (gid_t) gid); + Py_END_ALLOW_THREADS + if (res < 0) + return posix_error_with_allocated_filename(path); + PyMem_Free(path); + Py_INCREF(Py_None); + return Py_None; } #endif /* HAVE_LCHOWN */ @@ -1960,38 +1960,38 @@ static PyObject * posix_getcwd(PyObject *self, PyObject *noargs) { - int bufsize_incr = 1024; - int bufsize = 0; - char *tmpbuf = NULL; - char *res = NULL; - PyObject *dynamic_return; - - Py_BEGIN_ALLOW_THREADS - do { - bufsize = bufsize + bufsize_incr; - tmpbuf = malloc(bufsize); - if (tmpbuf == NULL) { - break; - } + int bufsize_incr = 1024; + int bufsize = 0; + char *tmpbuf = NULL; + char *res = NULL; + PyObject *dynamic_return; + + Py_BEGIN_ALLOW_THREADS + do { + bufsize = bufsize + bufsize_incr; + tmpbuf = malloc(bufsize); + if (tmpbuf == NULL) { + break; + } #if defined(PYOS_OS2) && defined(PYCC_GCC) - res = _getcwd2(tmpbuf, bufsize); + res = _getcwd2(tmpbuf, bufsize); #else - res = getcwd(tmpbuf, bufsize); + res = getcwd(tmpbuf, bufsize); #endif - if (res == NULL) { - free(tmpbuf); - } - } while ((res == NULL) && (errno == ERANGE)); - Py_END_ALLOW_THREADS + if (res == NULL) { + free(tmpbuf); + } + } while ((res == NULL) && (errno == ERANGE)); + Py_END_ALLOW_THREADS - if (res == NULL) - return posix_error(); + if (res == NULL) + return posix_error(); - dynamic_return = PyString_FromString(tmpbuf); - free(tmpbuf); + dynamic_return = PyString_FromString(tmpbuf); + free(tmpbuf); - return dynamic_return; + return dynamic_return; } #ifdef Py_USING_UNICODE @@ -2002,48 +2002,48 @@ static PyObject * posix_getcwdu(PyObject *self, PyObject *noargs) { - char buf[1026]; - char *res; + char buf[1026]; + char *res; #ifdef MS_WINDOWS - DWORD len; - wchar_t wbuf[1026]; - wchar_t *wbuf2 = wbuf; - PyObject *resobj; - Py_BEGIN_ALLOW_THREADS - len = GetCurrentDirectoryW(sizeof wbuf/ sizeof wbuf[0], wbuf); - /* If the buffer is large enough, len does not include the - terminating \0. If the buffer is too small, len includes - the space needed for the terminator. */ - if (len >= sizeof wbuf/ sizeof wbuf[0]) { - wbuf2 = malloc(len * sizeof(wchar_t)); - if (wbuf2) - len = GetCurrentDirectoryW(len, wbuf2); - } - Py_END_ALLOW_THREADS - if (!wbuf2) { - PyErr_NoMemory(); - return NULL; - } - if (!len) { - if (wbuf2 != wbuf) free(wbuf2); - return win32_error("getcwdu", NULL); - } - resobj = PyUnicode_FromWideChar(wbuf2, len); - if (wbuf2 != wbuf) free(wbuf2); - return resobj; + DWORD len; + wchar_t wbuf[1026]; + wchar_t *wbuf2 = wbuf; + PyObject *resobj; + Py_BEGIN_ALLOW_THREADS + len = GetCurrentDirectoryW(sizeof wbuf/ sizeof wbuf[0], wbuf); + /* If the buffer is large enough, len does not include the + terminating \0. If the buffer is too small, len includes + the space needed for the terminator. */ + if (len >= sizeof wbuf/ sizeof wbuf[0]) { + wbuf2 = malloc(len * sizeof(wchar_t)); + if (wbuf2) + len = GetCurrentDirectoryW(len, wbuf2); + } + Py_END_ALLOW_THREADS + if (!wbuf2) { + PyErr_NoMemory(); + return NULL; + } + if (!len) { + if (wbuf2 != wbuf) free(wbuf2); + return win32_error("getcwdu", NULL); + } + resobj = PyUnicode_FromWideChar(wbuf2, len); + if (wbuf2 != wbuf) free(wbuf2); + return resobj; #endif /* MS_WINDOWS */ - Py_BEGIN_ALLOW_THREADS + Py_BEGIN_ALLOW_THREADS #if defined(PYOS_OS2) && defined(PYCC_GCC) - res = _getcwd2(buf, sizeof buf); + res = _getcwd2(buf, sizeof buf); #else - res = getcwd(buf, sizeof buf); + res = getcwd(buf, sizeof buf); #endif - Py_END_ALLOW_THREADS - if (res == NULL) - return posix_error(); - return PyUnicode_Decode(buf, strlen(buf), Py_FileSystemDefaultEncoding,"strict"); + Py_END_ALLOW_THREADS + if (res == NULL) + return posix_error(); + return PyUnicode_Decode(buf, strlen(buf), Py_FileSystemDefaultEncoding,"strict"); } #endif /* Py_USING_UNICODE */ #endif /* HAVE_GETCWD */ @@ -2057,7 +2057,7 @@ static PyObject * posix_link(PyObject *self, PyObject *args) { - return posix_2str(args, "etet:link", link); + return posix_2str(args, "etet:link", link); } #endif /* HAVE_LINK */ @@ -2066,7 +2066,7 @@ "listdir(path) -> list_of_strings\n\n\ Return a list containing the names of the entries in the directory.\n\ \n\ - path: path of directory to list\n\ + path: path of directory to list\n\ \n\ The list is in arbitrary order. It does not include the special\n\ entries '.' and '..' even if they are present in the directory."); @@ -2074,155 +2074,155 @@ static PyObject * posix_listdir(PyObject *self, PyObject *args) { - /* XXX Should redo this putting the (now four) versions of opendir - in separate files instead of having them all here... */ + /* XXX Should redo this putting the (now four) versions of opendir + in separate files instead of having them all here... */ #if defined(MS_WINDOWS) && !defined(HAVE_OPENDIR) - PyObject *d, *v; - HANDLE hFindFile; - BOOL result; - WIN32_FIND_DATA FileData; - char namebuf[MAX_PATH+5]; /* Overallocate for \\*.*\0 */ - char *bufptr = namebuf; - Py_ssize_t len = sizeof(namebuf)-5; /* only claim to have space for MAX_PATH */ - - PyObject *po; - if (PyArg_ParseTuple(args, "U:listdir", &po)) { - WIN32_FIND_DATAW wFileData; - Py_UNICODE *wnamebuf; - /* Overallocate for \\*.*\0 */ - len = PyUnicode_GET_SIZE(po); - wnamebuf = malloc((len + 5) * sizeof(wchar_t)); - if (!wnamebuf) { - PyErr_NoMemory(); - return NULL; - } - wcscpy(wnamebuf, PyUnicode_AS_UNICODE(po)); - if (len > 0) { - Py_UNICODE wch = wnamebuf[len-1]; - if (wch != L'/' && wch != L'\\' && wch != L':') - wnamebuf[len++] = L'\\'; - wcscpy(wnamebuf + len, L"*.*"); - } - if ((d = PyList_New(0)) == NULL) { - free(wnamebuf); - return NULL; - } - hFindFile = FindFirstFileW(wnamebuf, &wFileData); - if (hFindFile == INVALID_HANDLE_VALUE) { - int error = GetLastError(); - if (error == ERROR_FILE_NOT_FOUND) { - free(wnamebuf); - return d; - } - Py_DECREF(d); - win32_error_unicode("FindFirstFileW", wnamebuf); - free(wnamebuf); - return NULL; - } - do { - /* Skip over . and .. */ - if (wcscmp(wFileData.cFileName, L".") != 0 && - wcscmp(wFileData.cFileName, L"..") != 0) { - v = PyUnicode_FromUnicode(wFileData.cFileName, wcslen(wFileData.cFileName)); - if (v == NULL) { - Py_DECREF(d); - d = NULL; - break; - } - if (PyList_Append(d, v) != 0) { - Py_DECREF(v); - Py_DECREF(d); - d = NULL; - break; - } - Py_DECREF(v); - } - Py_BEGIN_ALLOW_THREADS - result = FindNextFileW(hFindFile, &wFileData); - Py_END_ALLOW_THREADS - /* FindNextFile sets error to ERROR_NO_MORE_FILES if - it got to the end of the directory. */ - if (!result && GetLastError() != ERROR_NO_MORE_FILES) { - Py_DECREF(d); - win32_error_unicode("FindNextFileW", wnamebuf); - FindClose(hFindFile); - free(wnamebuf); - return NULL; - } - } while (result == TRUE); - - if (FindClose(hFindFile) == FALSE) { - Py_DECREF(d); - win32_error_unicode("FindClose", wnamebuf); - free(wnamebuf); - return NULL; - } - free(wnamebuf); - return d; - } - /* Drop the argument parsing error as narrow strings - are also valid. */ - PyErr_Clear(); - - if (!PyArg_ParseTuple(args, "et#:listdir", - Py_FileSystemDefaultEncoding, &bufptr, &len)) - return NULL; - if (len > 0) { - char ch = namebuf[len-1]; - if (ch != SEP && ch != ALTSEP && ch != ':') - namebuf[len++] = '/'; - strcpy(namebuf + len, "*.*"); - } - - if ((d = PyList_New(0)) == NULL) - return NULL; - - hFindFile = FindFirstFile(namebuf, &FileData); - if (hFindFile == INVALID_HANDLE_VALUE) { - int error = GetLastError(); - if (error == ERROR_FILE_NOT_FOUND) - return d; - Py_DECREF(d); - return win32_error("FindFirstFile", namebuf); - } - do { - /* Skip over . and .. */ - if (strcmp(FileData.cFileName, ".") != 0 && - strcmp(FileData.cFileName, "..") != 0) { - v = PyString_FromString(FileData.cFileName); - if (v == NULL) { - Py_DECREF(d); - d = NULL; - break; - } - if (PyList_Append(d, v) != 0) { - Py_DECREF(v); - Py_DECREF(d); - d = NULL; - break; - } - Py_DECREF(v); - } - Py_BEGIN_ALLOW_THREADS - result = FindNextFile(hFindFile, &FileData); - Py_END_ALLOW_THREADS - /* FindNextFile sets error to ERROR_NO_MORE_FILES if - it got to the end of the directory. */ - if (!result && GetLastError() != ERROR_NO_MORE_FILES) { - Py_DECREF(d); - win32_error("FindNextFile", namebuf); - FindClose(hFindFile); - return NULL; - } - } while (result == TRUE); - - if (FindClose(hFindFile) == FALSE) { - Py_DECREF(d); - return win32_error("FindClose", namebuf); - } + PyObject *d, *v; + HANDLE hFindFile; + BOOL result; + WIN32_FIND_DATA FileData; + char namebuf[MAX_PATH+5]; /* Overallocate for \\*.*\0 */ + char *bufptr = namebuf; + Py_ssize_t len = sizeof(namebuf)-5; /* only claim to have space for MAX_PATH */ + + PyObject *po; + if (PyArg_ParseTuple(args, "U:listdir", &po)) { + WIN32_FIND_DATAW wFileData; + Py_UNICODE *wnamebuf; + /* Overallocate for \\*.*\0 */ + len = PyUnicode_GET_SIZE(po); + wnamebuf = malloc((len + 5) * sizeof(wchar_t)); + if (!wnamebuf) { + PyErr_NoMemory(); + return NULL; + } + wcscpy(wnamebuf, PyUnicode_AS_UNICODE(po)); + if (len > 0) { + Py_UNICODE wch = wnamebuf[len-1]; + if (wch != L'/' && wch != L'\\' && wch != L':') + wnamebuf[len++] = L'\\'; + wcscpy(wnamebuf + len, L"*.*"); + } + if ((d = PyList_New(0)) == NULL) { + free(wnamebuf); + return NULL; + } + hFindFile = FindFirstFileW(wnamebuf, &wFileData); + if (hFindFile == INVALID_HANDLE_VALUE) { + int error = GetLastError(); + if (error == ERROR_FILE_NOT_FOUND) { + free(wnamebuf); + return d; + } + Py_DECREF(d); + win32_error_unicode("FindFirstFileW", wnamebuf); + free(wnamebuf); + return NULL; + } + do { + /* Skip over . and .. */ + if (wcscmp(wFileData.cFileName, L".") != 0 && + wcscmp(wFileData.cFileName, L"..") != 0) { + v = PyUnicode_FromUnicode(wFileData.cFileName, wcslen(wFileData.cFileName)); + if (v == NULL) { + Py_DECREF(d); + d = NULL; + break; + } + if (PyList_Append(d, v) != 0) { + Py_DECREF(v); + Py_DECREF(d); + d = NULL; + break; + } + Py_DECREF(v); + } + Py_BEGIN_ALLOW_THREADS + result = FindNextFileW(hFindFile, &wFileData); + Py_END_ALLOW_THREADS + /* FindNextFile sets error to ERROR_NO_MORE_FILES if + it got to the end of the directory. */ + if (!result && GetLastError() != ERROR_NO_MORE_FILES) { + Py_DECREF(d); + win32_error_unicode("FindNextFileW", wnamebuf); + FindClose(hFindFile); + free(wnamebuf); + return NULL; + } + } while (result == TRUE); + + if (FindClose(hFindFile) == FALSE) { + Py_DECREF(d); + win32_error_unicode("FindClose", wnamebuf); + free(wnamebuf); + return NULL; + } + free(wnamebuf); + return d; + } + /* Drop the argument parsing error as narrow strings + are also valid. */ + PyErr_Clear(); + + if (!PyArg_ParseTuple(args, "et#:listdir", + Py_FileSystemDefaultEncoding, &bufptr, &len)) + return NULL; + if (len > 0) { + char ch = namebuf[len-1]; + if (ch != SEP && ch != ALTSEP && ch != ':') + namebuf[len++] = '/'; + strcpy(namebuf + len, "*.*"); + } + + if ((d = PyList_New(0)) == NULL) + return NULL; + + hFindFile = FindFirstFile(namebuf, &FileData); + if (hFindFile == INVALID_HANDLE_VALUE) { + int error = GetLastError(); + if (error == ERROR_FILE_NOT_FOUND) + return d; + Py_DECREF(d); + return win32_error("FindFirstFile", namebuf); + } + do { + /* Skip over . and .. */ + if (strcmp(FileData.cFileName, ".") != 0 && + strcmp(FileData.cFileName, "..") != 0) { + v = PyString_FromString(FileData.cFileName); + if (v == NULL) { + Py_DECREF(d); + d = NULL; + break; + } + if (PyList_Append(d, v) != 0) { + Py_DECREF(v); + Py_DECREF(d); + d = NULL; + break; + } + Py_DECREF(v); + } + Py_BEGIN_ALLOW_THREADS + result = FindNextFile(hFindFile, &FileData); + Py_END_ALLOW_THREADS + /* FindNextFile sets error to ERROR_NO_MORE_FILES if + it got to the end of the directory. */ + if (!result && GetLastError() != ERROR_NO_MORE_FILES) { + Py_DECREF(d); + win32_error("FindNextFile", namebuf); + FindClose(hFindFile); + return NULL; + } + } while (result == TRUE); + + if (FindClose(hFindFile) == FALSE) { + Py_DECREF(d); + return win32_error("FindClose", namebuf); + } - return d; + return d; #elif defined(PYOS_OS2) @@ -2241,7 +2241,7 @@ if (!PyArg_ParseTuple(args, "t#:listdir", &name, &len)) return NULL; if (len >= MAX_PATH) { - PyErr_SetString(PyExc_ValueError, "path too long"); + PyErr_SetString(PyExc_ValueError, "path too long"); return NULL; } strcpy(namebuf, name); @@ -2252,7 +2252,7 @@ namebuf[len++] = SEP; strcpy(namebuf + len, "*.*"); - if ((d = PyList_New(0)) == NULL) + if ((d = PyList_New(0)) == NULL) return NULL; rc = DosFindFirst(namebuf, /* Wildcard Pattern to Match */ @@ -2297,81 +2297,81 @@ return d; #else - char *name = NULL; - PyObject *d, *v; - DIR *dirp; - struct dirent *ep; - int arg_is_unicode = 1; - - errno = 0; - if (!PyArg_ParseTuple(args, "U:listdir", &v)) { - arg_is_unicode = 0; - PyErr_Clear(); - } - if (!PyArg_ParseTuple(args, "et:listdir", Py_FileSystemDefaultEncoding, &name)) - return NULL; - if ((dirp = opendir(name)) == NULL) { - return posix_error_with_allocated_filename(name); - } - if ((d = PyList_New(0)) == NULL) { - closedir(dirp); - PyMem_Free(name); - return NULL; - } - for (;;) { - errno = 0; - Py_BEGIN_ALLOW_THREADS - ep = readdir(dirp); - Py_END_ALLOW_THREADS - if (ep == NULL) { - if (errno == 0) { - break; - } else { - closedir(dirp); - Py_DECREF(d); - return posix_error_with_allocated_filename(name); - } - } - if (ep->d_name[0] == '.' && - (NAMLEN(ep) == 1 || - (ep->d_name[1] == '.' && NAMLEN(ep) == 2))) - continue; - v = PyString_FromStringAndSize(ep->d_name, NAMLEN(ep)); - if (v == NULL) { - Py_DECREF(d); - d = NULL; - break; - } + char *name = NULL; + PyObject *d, *v; + DIR *dirp; + struct dirent *ep; + int arg_is_unicode = 1; + + errno = 0; + if (!PyArg_ParseTuple(args, "U:listdir", &v)) { + arg_is_unicode = 0; + PyErr_Clear(); + } + if (!PyArg_ParseTuple(args, "et:listdir", Py_FileSystemDefaultEncoding, &name)) + return NULL; + if ((dirp = opendir(name)) == NULL) { + return posix_error_with_allocated_filename(name); + } + if ((d = PyList_New(0)) == NULL) { + closedir(dirp); + PyMem_Free(name); + return NULL; + } + for (;;) { + errno = 0; + Py_BEGIN_ALLOW_THREADS + ep = readdir(dirp); + Py_END_ALLOW_THREADS + if (ep == NULL) { + if (errno == 0) { + break; + } else { + closedir(dirp); + Py_DECREF(d); + return posix_error_with_allocated_filename(name); + } + } + if (ep->d_name[0] == '.' && + (NAMLEN(ep) == 1 || + (ep->d_name[1] == '.' && NAMLEN(ep) == 2))) + continue; + v = PyString_FromStringAndSize(ep->d_name, NAMLEN(ep)); + if (v == NULL) { + Py_DECREF(d); + d = NULL; + break; + } #ifdef Py_USING_UNICODE - if (arg_is_unicode) { - PyObject *w; + if (arg_is_unicode) { + PyObject *w; - w = PyUnicode_FromEncodedObject(v, - Py_FileSystemDefaultEncoding, - "strict"); - if (w != NULL) { - Py_DECREF(v); - v = w; - } - else { - /* fall back to the original byte string, as - discussed in patch #683592 */ - PyErr_Clear(); - } - } -#endif - if (PyList_Append(d, v) != 0) { - Py_DECREF(v); - Py_DECREF(d); - d = NULL; - break; - } - Py_DECREF(v); - } - closedir(dirp); - PyMem_Free(name); + w = PyUnicode_FromEncodedObject(v, + Py_FileSystemDefaultEncoding, + "strict"); + if (w != NULL) { + Py_DECREF(v); + v = w; + } + else { + /* fall back to the original byte string, as + discussed in patch #683592 */ + PyErr_Clear(); + } + } +#endif + if (PyList_Append(d, v) != 0) { + Py_DECREF(v); + Py_DECREF(d); + d = NULL; + break; + } + Py_DECREF(v); + } + closedir(dirp); + PyMem_Free(name); - return d; + return d; #endif /* which OS */ } /* end of posix_listdir */ @@ -2381,53 +2381,53 @@ static PyObject * posix__getfullpathname(PyObject *self, PyObject *args) { - /* assume encoded strings won't more than double no of chars */ - char inbuf[MAX_PATH*2]; - char *inbufp = inbuf; - Py_ssize_t insize = sizeof(inbuf); - char outbuf[MAX_PATH*2]; - char *temp; - - PyUnicodeObject *po; - if (PyArg_ParseTuple(args, "U|:_getfullpathname", &po)) { - Py_UNICODE *wpath = PyUnicode_AS_UNICODE(po); - Py_UNICODE woutbuf[MAX_PATH*2], *woutbufp = woutbuf; - Py_UNICODE *wtemp; - DWORD result; - PyObject *v; - result = GetFullPathNameW(wpath, - sizeof(woutbuf)/sizeof(woutbuf[0]), - woutbuf, &wtemp); - if (result > sizeof(woutbuf)/sizeof(woutbuf[0])) { - woutbufp = malloc(result * sizeof(Py_UNICODE)); - if (!woutbufp) - return PyErr_NoMemory(); - result = GetFullPathNameW(wpath, result, woutbufp, &wtemp); - } - if (result) - v = PyUnicode_FromUnicode(woutbufp, wcslen(woutbufp)); - else - v = win32_error_unicode("GetFullPathNameW", wpath); - if (woutbufp != woutbuf) - free(woutbufp); - return v; - } - /* Drop the argument parsing error as narrow strings - are also valid. */ - PyErr_Clear(); - - if (!PyArg_ParseTuple (args, "et#:_getfullpathname", - Py_FileSystemDefaultEncoding, &inbufp, - &insize)) - return NULL; - if (!GetFullPathName(inbuf, sizeof(outbuf)/sizeof(outbuf[0]), - outbuf, &temp)) - return win32_error("GetFullPathName", inbuf); - if (PyUnicode_Check(PyTuple_GetItem(args, 0))) { - return PyUnicode_Decode(outbuf, strlen(outbuf), - Py_FileSystemDefaultEncoding, NULL); - } - return PyString_FromString(outbuf); + /* assume encoded strings won't more than double no of chars */ + char inbuf[MAX_PATH*2]; + char *inbufp = inbuf; + Py_ssize_t insize = sizeof(inbuf); + char outbuf[MAX_PATH*2]; + char *temp; + + PyUnicodeObject *po; + if (PyArg_ParseTuple(args, "U|:_getfullpathname", &po)) { + Py_UNICODE *wpath = PyUnicode_AS_UNICODE(po); + Py_UNICODE woutbuf[MAX_PATH*2], *woutbufp = woutbuf; + Py_UNICODE *wtemp; + DWORD result; + PyObject *v; + result = GetFullPathNameW(wpath, + sizeof(woutbuf)/sizeof(woutbuf[0]), + woutbuf, &wtemp); + if (result > sizeof(woutbuf)/sizeof(woutbuf[0])) { + woutbufp = malloc(result * sizeof(Py_UNICODE)); + if (!woutbufp) + return PyErr_NoMemory(); + result = GetFullPathNameW(wpath, result, woutbufp, &wtemp); + } + if (result) + v = PyUnicode_FromUnicode(woutbufp, wcslen(woutbufp)); + else + v = win32_error_unicode("GetFullPathNameW", wpath); + if (woutbufp != woutbuf) + free(woutbufp); + return v; + } + /* Drop the argument parsing error as narrow strings + are also valid. */ + PyErr_Clear(); + + if (!PyArg_ParseTuple (args, "et#:_getfullpathname", + Py_FileSystemDefaultEncoding, &inbufp, + &insize)) + return NULL; + if (!GetFullPathName(inbuf, sizeof(outbuf)/sizeof(outbuf[0]), + outbuf, &temp)) + return win32_error("GetFullPathName", inbuf); + if (PyUnicode_Check(PyTuple_GetItem(args, 0))) { + return PyUnicode_Decode(outbuf, strlen(outbuf), + Py_FileSystemDefaultEncoding, NULL); + } + return PyString_FromString(outbuf); } /* end of posix__getfullpathname */ #endif /* MS_WINDOWS */ @@ -2438,59 +2438,59 @@ static PyObject * posix_mkdir(PyObject *self, PyObject *args) { - int res; - char *path = NULL; - int mode = 0777; + int res; + char *path = NULL; + int mode = 0777; #ifdef MS_WINDOWS - PyUnicodeObject *po; - if (PyArg_ParseTuple(args, "U|i:mkdir", &po, &mode)) { - Py_BEGIN_ALLOW_THREADS - /* PyUnicode_AS_UNICODE OK without thread lock as - it is a simple dereference. */ - res = CreateDirectoryW(PyUnicode_AS_UNICODE(po), NULL); - Py_END_ALLOW_THREADS - if (!res) - return win32_error_unicode("mkdir", PyUnicode_AS_UNICODE(po)); - Py_INCREF(Py_None); - return Py_None; - } - /* Drop the argument parsing error as narrow strings - are also valid. */ - PyErr_Clear(); - if (!PyArg_ParseTuple(args, "et|i:mkdir", - Py_FileSystemDefaultEncoding, &path, &mode)) - return NULL; - Py_BEGIN_ALLOW_THREADS - /* PyUnicode_AS_UNICODE OK without thread lock as - it is a simple dereference. */ - res = CreateDirectoryA(path, NULL); - Py_END_ALLOW_THREADS - if (!res) { - win32_error("mkdir", path); - PyMem_Free(path); - return NULL; - } - PyMem_Free(path); - Py_INCREF(Py_None); - return Py_None; -#else /* MS_WINDOWS */ + PyUnicodeObject *po; + if (PyArg_ParseTuple(args, "U|i:mkdir", &po, &mode)) { + Py_BEGIN_ALLOW_THREADS + /* PyUnicode_AS_UNICODE OK without thread lock as + it is a simple dereference. */ + res = CreateDirectoryW(PyUnicode_AS_UNICODE(po), NULL); + Py_END_ALLOW_THREADS + if (!res) + return win32_error_unicode("mkdir", PyUnicode_AS_UNICODE(po)); + Py_INCREF(Py_None); + return Py_None; + } + /* Drop the argument parsing error as narrow strings + are also valid. */ + PyErr_Clear(); + if (!PyArg_ParseTuple(args, "et|i:mkdir", + Py_FileSystemDefaultEncoding, &path, &mode)) + return NULL; + Py_BEGIN_ALLOW_THREADS + /* PyUnicode_AS_UNICODE OK without thread lock as + it is a simple dereference. */ + res = CreateDirectoryA(path, NULL); + Py_END_ALLOW_THREADS + if (!res) { + win32_error("mkdir", path); + PyMem_Free(path); + return NULL; + } + PyMem_Free(path); + Py_INCREF(Py_None); + return Py_None; +#else /* MS_WINDOWS */ - if (!PyArg_ParseTuple(args, "et|i:mkdir", - Py_FileSystemDefaultEncoding, &path, &mode)) - return NULL; - Py_BEGIN_ALLOW_THREADS + if (!PyArg_ParseTuple(args, "et|i:mkdir", + Py_FileSystemDefaultEncoding, &path, &mode)) + return NULL; + Py_BEGIN_ALLOW_THREADS #if ( defined(__WATCOMC__) || defined(PYCC_VACPP) ) && !defined(__QNX__) - res = mkdir(path); + res = mkdir(path); #else - res = mkdir(path, mode); + res = mkdir(path, mode); #endif - Py_END_ALLOW_THREADS - if (res < 0) - return posix_error_with_allocated_filename(path); - PyMem_Free(path); - Py_INCREF(Py_None); - return Py_None; + Py_END_ALLOW_THREADS + if (res < 0) + return posix_error_with_allocated_filename(path); + PyMem_Free(path); + Py_INCREF(Py_None); + return Py_None; #endif /* MS_WINDOWS */ } @@ -2509,31 +2509,31 @@ static PyObject * posix_nice(PyObject *self, PyObject *args) { - int increment, value; + int increment, value; - if (!PyArg_ParseTuple(args, "i:nice", &increment)) - return NULL; + if (!PyArg_ParseTuple(args, "i:nice", &increment)) + return NULL; - /* There are two flavours of 'nice': one that returns the new - priority (as required by almost all standards out there) and the - Linux/FreeBSD/BSDI one, which returns '0' on success and advices - the use of getpriority() to get the new priority. - - If we are of the nice family that returns the new priority, we - need to clear errno before the call, and check if errno is filled - before calling posix_error() on a returnvalue of -1, because the - -1 may be the actual new priority! */ + /* There are two flavours of 'nice': one that returns the new + priority (as required by almost all standards out there) and the + Linux/FreeBSD/BSDI one, which returns '0' on success and advices + the use of getpriority() to get the new priority. + + If we are of the nice family that returns the new priority, we + need to clear errno before the call, and check if errno is filled + before calling posix_error() on a returnvalue of -1, because the + -1 may be the actual new priority! */ - errno = 0; - value = nice(increment); + errno = 0; + value = nice(increment); #if defined(HAVE_BROKEN_NICE) && defined(HAVE_GETPRIORITY) - if (value == 0) - value = getpriority(PRIO_PROCESS, 0); + if (value == 0) + value = getpriority(PRIO_PROCESS, 0); #endif - if (value == -1 && errno != 0) - /* either nice() or getpriority() returned an error */ - return posix_error(); - return PyInt_FromLong((long) value); + if (value == -1 && errno != 0) + /* either nice() or getpriority() returned an error */ + return posix_error(); + return PyInt_FromLong((long) value); } #endif /* HAVE_NICE */ @@ -2545,40 +2545,40 @@ posix_rename(PyObject *self, PyObject *args) { #ifdef MS_WINDOWS - PyObject *o1, *o2; - char *p1, *p2; - BOOL result; - if (!PyArg_ParseTuple(args, "OO:rename", &o1, &o2)) - goto error; - if (!convert_to_unicode(&o1)) - goto error; - if (!convert_to_unicode(&o2)) { - Py_DECREF(o1); - goto error; - } - Py_BEGIN_ALLOW_THREADS - result = MoveFileW(PyUnicode_AsUnicode(o1), - PyUnicode_AsUnicode(o2)); - Py_END_ALLOW_THREADS - Py_DECREF(o1); - Py_DECREF(o2); - if (!result) - return win32_error("rename", NULL); - Py_INCREF(Py_None); - return Py_None; + PyObject *o1, *o2; + char *p1, *p2; + BOOL result; + if (!PyArg_ParseTuple(args, "OO:rename", &o1, &o2)) + goto error; + if (!convert_to_unicode(&o1)) + goto error; + if (!convert_to_unicode(&o2)) { + Py_DECREF(o1); + goto error; + } + Py_BEGIN_ALLOW_THREADS + result = MoveFileW(PyUnicode_AsUnicode(o1), + PyUnicode_AsUnicode(o2)); + Py_END_ALLOW_THREADS + Py_DECREF(o1); + Py_DECREF(o2); + if (!result) + return win32_error("rename", NULL); + Py_INCREF(Py_None); + return Py_None; error: - PyErr_Clear(); - if (!PyArg_ParseTuple(args, "ss:rename", &p1, &p2)) - return NULL; - Py_BEGIN_ALLOW_THREADS - result = MoveFileA(p1, p2); - Py_END_ALLOW_THREADS - if (!result) - return win32_error("rename", NULL); - Py_INCREF(Py_None); - return Py_None; + PyErr_Clear(); + if (!PyArg_ParseTuple(args, "ss:rename", &p1, &p2)) + return NULL; + Py_BEGIN_ALLOW_THREADS + result = MoveFileA(p1, p2); + Py_END_ALLOW_THREADS + if (!result) + return win32_error("rename", NULL); + Py_INCREF(Py_None); + return Py_None; #else - return posix_2str(args, "etet:rename", rename); + return posix_2str(args, "etet:rename", rename); #endif } @@ -2591,9 +2591,9 @@ posix_rmdir(PyObject *self, PyObject *args) { #ifdef MS_WINDOWS - return win32_1str(args, "rmdir", "s:rmdir", RemoveDirectoryA, "U:rmdir", RemoveDirectoryW); + return win32_1str(args, "rmdir", "s:rmdir", RemoveDirectoryA, "U:rmdir", RemoveDirectoryW); #else - return posix_1str(args, "et:rmdir", rmdir); + return posix_1str(args, "et:rmdir", rmdir); #endif } @@ -2606,9 +2606,9 @@ posix_stat(PyObject *self, PyObject *args) { #ifdef MS_WINDOWS - return posix_do_stat(self, args, "et:stat", STAT, "U:stat", win32_wstat); + return posix_do_stat(self, args, "et:stat", STAT, "U:stat", win32_wstat); #else - return posix_do_stat(self, args, "et:stat", STAT, NULL, NULL); + return posix_do_stat(self, args, "et:stat", STAT, NULL, NULL); #endif } @@ -2621,14 +2621,14 @@ static PyObject * posix_system(PyObject *self, PyObject *args) { - char *command; - long sts; - if (!PyArg_ParseTuple(args, "s:system", &command)) - return NULL; - Py_BEGIN_ALLOW_THREADS - sts = system(command); - Py_END_ALLOW_THREADS - return PyInt_FromLong(sts); + char *command; + long sts; + if (!PyArg_ParseTuple(args, "s:system", &command)) + return NULL; + Py_BEGIN_ALLOW_THREADS + sts = system(command); + Py_END_ALLOW_THREADS + return PyInt_FromLong(sts); } #endif @@ -2640,13 +2640,13 @@ static PyObject * posix_umask(PyObject *self, PyObject *args) { - int i; - if (!PyArg_ParseTuple(args, "i:umask", &i)) - return NULL; - i = (int)umask(i); - if (i < 0) - return posix_error(); - return PyInt_FromLong((long)i); + int i; + if (!PyArg_ParseTuple(args, "i:umask", &i)) + return NULL; + i = (int)umask(i); + if (i < 0) + return posix_error(); + return PyInt_FromLong((long)i); } @@ -2662,9 +2662,9 @@ posix_unlink(PyObject *self, PyObject *args) { #ifdef MS_WINDOWS - return win32_1str(args, "remove", "s:remove", DeleteFileA, "U:remove", DeleteFileW); + return win32_1str(args, "remove", "s:remove", DeleteFileA, "U:remove", DeleteFileW); #else - return posix_1str(args, "et:remove", unlink); + return posix_1str(args, "et:remove", unlink); #endif } @@ -2677,50 +2677,50 @@ static PyObject * posix_uname(PyObject *self, PyObject *noargs) { - struct utsname u; - int res; + struct utsname u; + int res; - Py_BEGIN_ALLOW_THREADS - res = uname(&u); - Py_END_ALLOW_THREADS - if (res < 0) - return posix_error(); - return Py_BuildValue("(sssss)", - u.sysname, - u.nodename, - u.release, - u.version, - u.machine); + Py_BEGIN_ALLOW_THREADS + res = uname(&u); + Py_END_ALLOW_THREADS + if (res < 0) + return posix_error(); + return Py_BuildValue("(sssss)", + u.sysname, + u.nodename, + u.release, + u.version, + u.machine); } #endif /* HAVE_UNAME */ static int extract_time(PyObject *t, long* sec, long* usec) { - long intval; - if (PyFloat_Check(t)) { - double tval = PyFloat_AsDouble(t); - PyObject *intobj = Py_TYPE(t)->tp_as_number->nb_int(t); - if (!intobj) - return -1; - intval = PyInt_AsLong(intobj); - Py_DECREF(intobj); - if (intval == -1 && PyErr_Occurred()) - return -1; - *sec = intval; - *usec = (long)((tval - intval) * 1e6); /* can't exceed 1000000 */ - if (*usec < 0) - /* If rounding gave us a negative number, - truncate. */ - *usec = 0; - return 0; - } - intval = PyInt_AsLong(t); - if (intval == -1 && PyErr_Occurred()) - return -1; - *sec = intval; - *usec = 0; + long intval; + if (PyFloat_Check(t)) { + double tval = PyFloat_AsDouble(t); + PyObject *intobj = Py_TYPE(t)->tp_as_number->nb_int(t); + if (!intobj) + return -1; + intval = PyInt_AsLong(intobj); + Py_DECREF(intobj); + if (intval == -1 && PyErr_Occurred()) + return -1; + *sec = intval; + *usec = (long)((tval - intval) * 1e6); /* can't exceed 1000000 */ + if (*usec < 0) + /* If rounding gave us a negative number, + truncate. */ + *usec = 0; return 0; + } + intval = PyInt_AsLong(t); + if (intval == -1 && PyErr_Occurred()) + return -1; + *sec = intval; + *usec = 0; + return 0; } PyDoc_STRVAR(posix_utime__doc__, @@ -2733,153 +2733,153 @@ posix_utime(PyObject *self, PyObject *args) { #ifdef MS_WINDOWS - PyObject *arg; - PyUnicodeObject *obwpath; - wchar_t *wpath = NULL; - char *apath = NULL; - HANDLE hFile; - long atimesec, mtimesec, ausec, musec; - FILETIME atime, mtime; - PyObject *result = NULL; - - if (PyArg_ParseTuple(args, "UO|:utime", &obwpath, &arg)) { - wpath = PyUnicode_AS_UNICODE(obwpath); - Py_BEGIN_ALLOW_THREADS - hFile = CreateFileW(wpath, FILE_WRITE_ATTRIBUTES, 0, - NULL, OPEN_EXISTING, - FILE_FLAG_BACKUP_SEMANTICS, NULL); - Py_END_ALLOW_THREADS - if (hFile == INVALID_HANDLE_VALUE) - return win32_error_unicode("utime", wpath); - } else - /* Drop the argument parsing error as narrow strings - are also valid. */ - PyErr_Clear(); - - if (!wpath) { - if (!PyArg_ParseTuple(args, "etO:utime", - Py_FileSystemDefaultEncoding, &apath, &arg)) - return NULL; - Py_BEGIN_ALLOW_THREADS - hFile = CreateFileA(apath, FILE_WRITE_ATTRIBUTES, 0, - NULL, OPEN_EXISTING, - FILE_FLAG_BACKUP_SEMANTICS, NULL); - Py_END_ALLOW_THREADS - if (hFile == INVALID_HANDLE_VALUE) { - win32_error("utime", apath); - PyMem_Free(apath); - return NULL; - } - PyMem_Free(apath); - } - - if (arg == Py_None) { - SYSTEMTIME now; - GetSystemTime(&now); - if (!SystemTimeToFileTime(&now, &mtime) || - !SystemTimeToFileTime(&now, &atime)) { - win32_error("utime", NULL); - goto done; - } - } - else if (!PyTuple_Check(arg) || PyTuple_Size(arg) != 2) { - PyErr_SetString(PyExc_TypeError, - "utime() arg 2 must be a tuple (atime, mtime)"); - goto done; - } - else { - if (extract_time(PyTuple_GET_ITEM(arg, 0), - &atimesec, &ausec) == -1) - goto done; - time_t_to_FILE_TIME(atimesec, 1000*ausec, &atime); - if (extract_time(PyTuple_GET_ITEM(arg, 1), - &mtimesec, &musec) == -1) - goto done; - time_t_to_FILE_TIME(mtimesec, 1000*musec, &mtime); - } - if (!SetFileTime(hFile, NULL, &atime, &mtime)) { - /* Avoid putting the file name into the error here, - as that may confuse the user into believing that - something is wrong with the file, when it also - could be the time stamp that gives a problem. */ - win32_error("utime", NULL); - } - Py_INCREF(Py_None); - result = Py_None; + PyObject *arg; + PyUnicodeObject *obwpath; + wchar_t *wpath = NULL; + char *apath = NULL; + HANDLE hFile; + long atimesec, mtimesec, ausec, musec; + FILETIME atime, mtime; + PyObject *result = NULL; + + if (PyArg_ParseTuple(args, "UO|:utime", &obwpath, &arg)) { + wpath = PyUnicode_AS_UNICODE(obwpath); + Py_BEGIN_ALLOW_THREADS + hFile = CreateFileW(wpath, FILE_WRITE_ATTRIBUTES, 0, + NULL, OPEN_EXISTING, + FILE_FLAG_BACKUP_SEMANTICS, NULL); + Py_END_ALLOW_THREADS + if (hFile == INVALID_HANDLE_VALUE) + return win32_error_unicode("utime", wpath); + } else + /* Drop the argument parsing error as narrow strings + are also valid. */ + PyErr_Clear(); + + if (!wpath) { + if (!PyArg_ParseTuple(args, "etO:utime", + Py_FileSystemDefaultEncoding, &apath, &arg)) + return NULL; + Py_BEGIN_ALLOW_THREADS + hFile = CreateFileA(apath, FILE_WRITE_ATTRIBUTES, 0, + NULL, OPEN_EXISTING, + FILE_FLAG_BACKUP_SEMANTICS, NULL); + Py_END_ALLOW_THREADS + if (hFile == INVALID_HANDLE_VALUE) { + win32_error("utime", apath); + PyMem_Free(apath); + return NULL; + } + PyMem_Free(apath); + } + + if (arg == Py_None) { + SYSTEMTIME now; + GetSystemTime(&now); + if (!SystemTimeToFileTime(&now, &mtime) || + !SystemTimeToFileTime(&now, &atime)) { + win32_error("utime", NULL); + goto done; + } + } + else if (!PyTuple_Check(arg) || PyTuple_Size(arg) != 2) { + PyErr_SetString(PyExc_TypeError, + "utime() arg 2 must be a tuple (atime, mtime)"); + goto done; + } + else { + if (extract_time(PyTuple_GET_ITEM(arg, 0), + &atimesec, &ausec) == -1) + goto done; + time_t_to_FILE_TIME(atimesec, 1000*ausec, &atime); + if (extract_time(PyTuple_GET_ITEM(arg, 1), + &mtimesec, &musec) == -1) + goto done; + time_t_to_FILE_TIME(mtimesec, 1000*musec, &mtime); + } + if (!SetFileTime(hFile, NULL, &atime, &mtime)) { + /* Avoid putting the file name into the error here, + as that may confuse the user into believing that + something is wrong with the file, when it also + could be the time stamp that gives a problem. */ + win32_error("utime", NULL); + } + Py_INCREF(Py_None); + result = Py_None; done: - CloseHandle(hFile); - return result; + CloseHandle(hFile); + return result; #else /* MS_WINDOWS */ - char *path = NULL; - long atime, mtime, ausec, musec; - int res; - PyObject* arg; + char *path = NULL; + long atime, mtime, ausec, musec; + int res; + PyObject* arg; #if defined(HAVE_UTIMES) - struct timeval buf[2]; + struct timeval buf[2]; #define ATIME buf[0].tv_sec #define MTIME buf[1].tv_sec #elif defined(HAVE_UTIME_H) /* XXX should define struct utimbuf instead, above */ - struct utimbuf buf; + struct utimbuf buf; #define ATIME buf.actime #define MTIME buf.modtime #define UTIME_ARG &buf #else /* HAVE_UTIMES */ - time_t buf[2]; + time_t buf[2]; #define ATIME buf[0] #define MTIME buf[1] #define UTIME_ARG buf #endif /* HAVE_UTIMES */ - if (!PyArg_ParseTuple(args, "etO:utime", - Py_FileSystemDefaultEncoding, &path, &arg)) - return NULL; - if (arg == Py_None) { - /* optional time values not given */ - Py_BEGIN_ALLOW_THREADS - res = utime(path, NULL); - Py_END_ALLOW_THREADS - } - else if (!PyTuple_Check(arg) || PyTuple_Size(arg) != 2) { - PyErr_SetString(PyExc_TypeError, - "utime() arg 2 must be a tuple (atime, mtime)"); - PyMem_Free(path); - return NULL; - } - else { - if (extract_time(PyTuple_GET_ITEM(arg, 0), - &atime, &ausec) == -1) { - PyMem_Free(path); - return NULL; - } - if (extract_time(PyTuple_GET_ITEM(arg, 1), - &mtime, &musec) == -1) { - PyMem_Free(path); - return NULL; - } - ATIME = atime; - MTIME = mtime; + if (!PyArg_ParseTuple(args, "etO:utime", + Py_FileSystemDefaultEncoding, &path, &arg)) + return NULL; + if (arg == Py_None) { + /* optional time values not given */ + Py_BEGIN_ALLOW_THREADS + res = utime(path, NULL); + Py_END_ALLOW_THREADS + } + else if (!PyTuple_Check(arg) || PyTuple_Size(arg) != 2) { + PyErr_SetString(PyExc_TypeError, + "utime() arg 2 must be a tuple (atime, mtime)"); + PyMem_Free(path); + return NULL; + } + else { + if (extract_time(PyTuple_GET_ITEM(arg, 0), + &atime, &ausec) == -1) { + PyMem_Free(path); + return NULL; + } + if (extract_time(PyTuple_GET_ITEM(arg, 1), + &mtime, &musec) == -1) { + PyMem_Free(path); + return NULL; + } + ATIME = atime; + MTIME = mtime; #ifdef HAVE_UTIMES - buf[0].tv_usec = ausec; - buf[1].tv_usec = musec; - Py_BEGIN_ALLOW_THREADS - res = utimes(path, buf); - Py_END_ALLOW_THREADS -#else - Py_BEGIN_ALLOW_THREADS - res = utime(path, UTIME_ARG); - Py_END_ALLOW_THREADS + buf[0].tv_usec = ausec; + buf[1].tv_usec = musec; + Py_BEGIN_ALLOW_THREADS + res = utimes(path, buf); + Py_END_ALLOW_THREADS +#else + Py_BEGIN_ALLOW_THREADS + res = utime(path, UTIME_ARG); + Py_END_ALLOW_THREADS #endif /* HAVE_UTIMES */ - } - if (res < 0) { - return posix_error_with_allocated_filename(path); - } - PyMem_Free(path); - Py_INCREF(Py_None); - return Py_None; + } + if (res < 0) { + return posix_error_with_allocated_filename(path); + } + PyMem_Free(path); + Py_INCREF(Py_None); + return Py_None; #undef UTIME_ARG #undef ATIME #undef MTIME @@ -2896,21 +2896,21 @@ static PyObject * posix__exit(PyObject *self, PyObject *args) { - int sts; - if (!PyArg_ParseTuple(args, "i:_exit", &sts)) - return NULL; - _exit(sts); - return NULL; /* Make gcc -Wall happy */ + int sts; + if (!PyArg_ParseTuple(args, "i:_exit", &sts)) + return NULL; + _exit(sts); + return NULL; /* Make gcc -Wall happy */ } #if defined(HAVE_EXECV) || defined(HAVE_SPAWNV) static void free_string_array(char **array, Py_ssize_t count) { - Py_ssize_t i; - for (i = 0; i < count; i++) - PyMem_Free(array[i]); - PyMem_DEL(array); + Py_ssize_t i; + for (i = 0; i < count; i++) + PyMem_Free(array[i]); + PyMem_DEL(array); } #endif @@ -2920,70 +2920,70 @@ "execv(path, args)\n\n\ Execute an executable path with arguments, replacing current process.\n\ \n\ - path: path of executable file\n\ - args: tuple or list of strings"); + path: path of executable file\n\ + args: tuple or list of strings"); static PyObject * posix_execv(PyObject *self, PyObject *args) { - char *path; - PyObject *argv; - char **argvlist; - Py_ssize_t i, argc; - PyObject *(*getitem)(PyObject *, Py_ssize_t); - - /* execv has two arguments: (path, argv), where - argv is a list or tuple of strings. */ - - if (!PyArg_ParseTuple(args, "etO:execv", - Py_FileSystemDefaultEncoding, - &path, &argv)) - return NULL; - if (PyList_Check(argv)) { - argc = PyList_Size(argv); - getitem = PyList_GetItem; - } - else if (PyTuple_Check(argv)) { - argc = PyTuple_Size(argv); - getitem = PyTuple_GetItem; - } - else { - PyErr_SetString(PyExc_TypeError, "execv() arg 2 must be a tuple or list"); - PyMem_Free(path); - return NULL; - } - if (argc < 1) { - PyErr_SetString(PyExc_ValueError, "execv() arg 2 must not be empty"); - PyMem_Free(path); - return NULL; - } - - argvlist = PyMem_NEW(char *, argc+1); - if (argvlist == NULL) { - PyMem_Free(path); - return PyErr_NoMemory(); - } - for (i = 0; i < argc; i++) { - if (!PyArg_Parse((*getitem)(argv, i), "et", - Py_FileSystemDefaultEncoding, - &argvlist[i])) { - free_string_array(argvlist, i); - PyErr_SetString(PyExc_TypeError, - "execv() arg 2 must contain only strings"); - PyMem_Free(path); - return NULL; - - } - } - argvlist[argc] = NULL; - - execv(path, argvlist); - - /* If we get here it's definitely an error */ - - free_string_array(argvlist, argc); - PyMem_Free(path); - return posix_error(); + char *path; + PyObject *argv; + char **argvlist; + Py_ssize_t i, argc; + PyObject *(*getitem)(PyObject *, Py_ssize_t); + + /* execv has two arguments: (path, argv), where + argv is a list or tuple of strings. */ + + if (!PyArg_ParseTuple(args, "etO:execv", + Py_FileSystemDefaultEncoding, + &path, &argv)) + return NULL; + if (PyList_Check(argv)) { + argc = PyList_Size(argv); + getitem = PyList_GetItem; + } + else if (PyTuple_Check(argv)) { + argc = PyTuple_Size(argv); + getitem = PyTuple_GetItem; + } + else { + PyErr_SetString(PyExc_TypeError, "execv() arg 2 must be a tuple or list"); + PyMem_Free(path); + return NULL; + } + if (argc < 1) { + PyErr_SetString(PyExc_ValueError, "execv() arg 2 must not be empty"); + PyMem_Free(path); + return NULL; + } + + argvlist = PyMem_NEW(char *, argc+1); + if (argvlist == NULL) { + PyMem_Free(path); + return PyErr_NoMemory(); + } + for (i = 0; i < argc; i++) { + if (!PyArg_Parse((*getitem)(argv, i), "et", + Py_FileSystemDefaultEncoding, + &argvlist[i])) { + free_string_array(argvlist, i); + PyErr_SetString(PyExc_TypeError, + "execv() arg 2 must contain only strings"); + PyMem_Free(path); + return NULL; + + } + } + argvlist[argc] = NULL; + + execv(path, argvlist); + + /* If we get here it's definitely an error */ + + free_string_array(argvlist, argc); + PyMem_Free(path); + return posix_error(); } @@ -2991,142 +2991,142 @@ "execve(path, args, env)\n\n\ Execute a path with arguments and environment, replacing current process.\n\ \n\ - path: path of executable file\n\ - args: tuple or list of arguments\n\ - env: dictionary of strings mapping to strings"); + path: path of executable file\n\ + args: tuple or list of arguments\n\ + env: dictionary of strings mapping to strings"); static PyObject * posix_execve(PyObject *self, PyObject *args) { - char *path; - PyObject *argv, *env; - char **argvlist; - char **envlist; - PyObject *key, *val, *keys=NULL, *vals=NULL; - Py_ssize_t i, pos, argc, envc; - PyObject *(*getitem)(PyObject *, Py_ssize_t); - Py_ssize_t lastarg = 0; - - /* execve has three arguments: (path, argv, env), where - argv is a list or tuple of strings and env is a dictionary - like posix.environ. */ - - if (!PyArg_ParseTuple(args, "etOO:execve", - Py_FileSystemDefaultEncoding, - &path, &argv, &env)) - return NULL; - if (PyList_Check(argv)) { - argc = PyList_Size(argv); - getitem = PyList_GetItem; - } - else if (PyTuple_Check(argv)) { - argc = PyTuple_Size(argv); - getitem = PyTuple_GetItem; - } - else { - PyErr_SetString(PyExc_TypeError, - "execve() arg 2 must be a tuple or list"); - goto fail_0; - } - if (!PyMapping_Check(env)) { - PyErr_SetString(PyExc_TypeError, - "execve() arg 3 must be a mapping object"); - goto fail_0; - } - - argvlist = PyMem_NEW(char *, argc+1); - if (argvlist == NULL) { - PyErr_NoMemory(); - goto fail_0; - } - for (i = 0; i < argc; i++) { - if (!PyArg_Parse((*getitem)(argv, i), - "et;execve() arg 2 must contain only strings", - Py_FileSystemDefaultEncoding, - &argvlist[i])) - { - lastarg = i; - goto fail_1; - } - } - lastarg = argc; - argvlist[argc] = NULL; - - i = PyMapping_Size(env); - if (i < 0) - goto fail_1; - envlist = PyMem_NEW(char *, i + 1); - if (envlist == NULL) { - PyErr_NoMemory(); - goto fail_1; - } - envc = 0; - keys = PyMapping_Keys(env); - vals = PyMapping_Values(env); - if (!keys || !vals) - goto fail_2; - if (!PyList_Check(keys) || !PyList_Check(vals)) { - PyErr_SetString(PyExc_TypeError, - "execve(): env.keys() or env.values() is not a list"); - goto fail_2; - } - - for (pos = 0; pos < i; pos++) { - char *p, *k, *v; - size_t len; - - key = PyList_GetItem(keys, pos); - val = PyList_GetItem(vals, pos); - if (!key || !val) - goto fail_2; - - if (!PyArg_Parse( - key, - "s;execve() arg 3 contains a non-string key", - &k) || - !PyArg_Parse( - val, - "s;execve() arg 3 contains a non-string value", - &v)) - { - goto fail_2; - } + char *path; + PyObject *argv, *env; + char **argvlist; + char **envlist; + PyObject *key, *val, *keys=NULL, *vals=NULL; + Py_ssize_t i, pos, argc, envc; + PyObject *(*getitem)(PyObject *, Py_ssize_t); + Py_ssize_t lastarg = 0; + + /* execve has three arguments: (path, argv, env), where + argv is a list or tuple of strings and env is a dictionary + like posix.environ. */ + + if (!PyArg_ParseTuple(args, "etOO:execve", + Py_FileSystemDefaultEncoding, + &path, &argv, &env)) + return NULL; + if (PyList_Check(argv)) { + argc = PyList_Size(argv); + getitem = PyList_GetItem; + } + else if (PyTuple_Check(argv)) { + argc = PyTuple_Size(argv); + getitem = PyTuple_GetItem; + } + else { + PyErr_SetString(PyExc_TypeError, + "execve() arg 2 must be a tuple or list"); + goto fail_0; + } + if (!PyMapping_Check(env)) { + PyErr_SetString(PyExc_TypeError, + "execve() arg 3 must be a mapping object"); + goto fail_0; + } + + argvlist = PyMem_NEW(char *, argc+1); + if (argvlist == NULL) { + PyErr_NoMemory(); + goto fail_0; + } + for (i = 0; i < argc; i++) { + if (!PyArg_Parse((*getitem)(argv, i), + "et;execve() arg 2 must contain only strings", + Py_FileSystemDefaultEncoding, + &argvlist[i])) + { + lastarg = i; + goto fail_1; + } + } + lastarg = argc; + argvlist[argc] = NULL; + + i = PyMapping_Size(env); + if (i < 0) + goto fail_1; + envlist = PyMem_NEW(char *, i + 1); + if (envlist == NULL) { + PyErr_NoMemory(); + goto fail_1; + } + envc = 0; + keys = PyMapping_Keys(env); + vals = PyMapping_Values(env); + if (!keys || !vals) + goto fail_2; + if (!PyList_Check(keys) || !PyList_Check(vals)) { + PyErr_SetString(PyExc_TypeError, + "execve(): env.keys() or env.values() is not a list"); + goto fail_2; + } + + for (pos = 0; pos < i; pos++) { + char *p, *k, *v; + size_t len; + + key = PyList_GetItem(keys, pos); + val = PyList_GetItem(vals, pos); + if (!key || !val) + goto fail_2; + + if (!PyArg_Parse( + key, + "s;execve() arg 3 contains a non-string key", + &k) || + !PyArg_Parse( + val, + "s;execve() arg 3 contains a non-string value", + &v)) + { + goto fail_2; + } #if defined(PYOS_OS2) /* Omit Pseudo-Env Vars that Would Confuse Programs if Passed On */ if (stricmp(k, "BEGINLIBPATH") != 0 && stricmp(k, "ENDLIBPATH") != 0) { #endif - len = PyString_Size(key) + PyString_Size(val) + 2; - p = PyMem_NEW(char, len); - if (p == NULL) { - PyErr_NoMemory(); - goto fail_2; - } - PyOS_snprintf(p, len, "%s=%s", k, v); - envlist[envc++] = p; + len = PyString_Size(key) + PyString_Size(val) + 2; + p = PyMem_NEW(char, len); + if (p == NULL) { + PyErr_NoMemory(); + goto fail_2; + } + PyOS_snprintf(p, len, "%s=%s", k, v); + envlist[envc++] = p; #if defined(PYOS_OS2) - } + } #endif - } - envlist[envc] = 0; + } + envlist[envc] = 0; - execve(path, argvlist, envlist); + execve(path, argvlist, envlist); - /* If we get here it's definitely an error */ + /* If we get here it's definitely an error */ - (void) posix_error(); + (void) posix_error(); fail_2: - while (--envc >= 0) - PyMem_DEL(envlist[envc]); - PyMem_DEL(envlist); + while (--envc >= 0) + PyMem_DEL(envlist[envc]); + PyMem_DEL(envlist); fail_1: - free_string_array(argvlist, lastarg); - Py_XDECREF(vals); - Py_XDECREF(keys); + free_string_array(argvlist, lastarg); + Py_XDECREF(vals); + Py_XDECREF(keys); fail_0: - PyMem_Free(path); - return NULL; + PyMem_Free(path); + return NULL; } #endif /* HAVE_EXECV */ @@ -3136,85 +3136,85 @@ "spawnv(mode, path, args)\n\n\ Execute the program 'path' in a new process.\n\ \n\ - mode: mode of process creation\n\ - path: path of executable file\n\ - args: tuple or list of strings"); + mode: mode of process creation\n\ + path: path of executable file\n\ + args: tuple or list of strings"); static PyObject * posix_spawnv(PyObject *self, PyObject *args) { - char *path; - PyObject *argv; - char **argvlist; - int mode, i; - Py_ssize_t argc; - Py_intptr_t spawnval; - PyObject *(*getitem)(PyObject *, Py_ssize_t); - - /* spawnv has three arguments: (mode, path, argv), where - argv is a list or tuple of strings. */ - - if (!PyArg_ParseTuple(args, "ietO:spawnv", &mode, - Py_FileSystemDefaultEncoding, - &path, &argv)) - return NULL; - if (PyList_Check(argv)) { - argc = PyList_Size(argv); - getitem = PyList_GetItem; - } - else if (PyTuple_Check(argv)) { - argc = PyTuple_Size(argv); - getitem = PyTuple_GetItem; - } - else { - PyErr_SetString(PyExc_TypeError, - "spawnv() arg 2 must be a tuple or list"); - PyMem_Free(path); - return NULL; - } - - argvlist = PyMem_NEW(char *, argc+1); - if (argvlist == NULL) { - PyMem_Free(path); - return PyErr_NoMemory(); - } - for (i = 0; i < argc; i++) { - if (!PyArg_Parse((*getitem)(argv, i), "et", - Py_FileSystemDefaultEncoding, - &argvlist[i])) { - free_string_array(argvlist, i); - PyErr_SetString( - PyExc_TypeError, - "spawnv() arg 2 must contain only strings"); - PyMem_Free(path); - return NULL; - } - } - argvlist[argc] = NULL; + char *path; + PyObject *argv; + char **argvlist; + int mode, i; + Py_ssize_t argc; + Py_intptr_t spawnval; + PyObject *(*getitem)(PyObject *, Py_ssize_t); + + /* spawnv has three arguments: (mode, path, argv), where + argv is a list or tuple of strings. */ + + if (!PyArg_ParseTuple(args, "ietO:spawnv", &mode, + Py_FileSystemDefaultEncoding, + &path, &argv)) + return NULL; + if (PyList_Check(argv)) { + argc = PyList_Size(argv); + getitem = PyList_GetItem; + } + else if (PyTuple_Check(argv)) { + argc = PyTuple_Size(argv); + getitem = PyTuple_GetItem; + } + else { + PyErr_SetString(PyExc_TypeError, + "spawnv() arg 2 must be a tuple or list"); + PyMem_Free(path); + return NULL; + } + + argvlist = PyMem_NEW(char *, argc+1); + if (argvlist == NULL) { + PyMem_Free(path); + return PyErr_NoMemory(); + } + for (i = 0; i < argc; i++) { + if (!PyArg_Parse((*getitem)(argv, i), "et", + Py_FileSystemDefaultEncoding, + &argvlist[i])) { + free_string_array(argvlist, i); + PyErr_SetString( + PyExc_TypeError, + "spawnv() arg 2 must contain only strings"); + PyMem_Free(path); + return NULL; + } + } + argvlist[argc] = NULL; #if defined(PYOS_OS2) && defined(PYCC_GCC) - Py_BEGIN_ALLOW_THREADS - spawnval = spawnv(mode, path, argvlist); - Py_END_ALLOW_THREADS + Py_BEGIN_ALLOW_THREADS + spawnval = spawnv(mode, path, argvlist); + Py_END_ALLOW_THREADS #else - if (mode == _OLD_P_OVERLAY) - mode = _P_OVERLAY; + if (mode == _OLD_P_OVERLAY) + mode = _P_OVERLAY; - Py_BEGIN_ALLOW_THREADS - spawnval = _spawnv(mode, path, argvlist); - Py_END_ALLOW_THREADS + Py_BEGIN_ALLOW_THREADS + spawnval = _spawnv(mode, path, argvlist); + Py_END_ALLOW_THREADS #endif - free_string_array(argvlist, argc); - PyMem_Free(path); + free_string_array(argvlist, argc); + PyMem_Free(path); - if (spawnval == -1) - return posix_error(); - else + if (spawnval == -1) + return posix_error(); + else #if SIZEOF_LONG == SIZEOF_VOID_P - return Py_BuildValue("l", (long) spawnval); + return Py_BuildValue("l", (long) spawnval); #else - return Py_BuildValue("L", (PY_LONG_LONG) spawnval); + return Py_BuildValue("L", (PY_LONG_LONG) spawnval); #endif } @@ -3223,153 +3223,153 @@ "spawnve(mode, path, args, env)\n\n\ Execute the program 'path' in a new process.\n\ \n\ - mode: mode of process creation\n\ - path: path of executable file\n\ - args: tuple or list of arguments\n\ - env: dictionary of strings mapping to strings"); + mode: mode of process creation\n\ + path: path of executable file\n\ + args: tuple or list of arguments\n\ + env: dictionary of strings mapping to strings"); static PyObject * posix_spawnve(PyObject *self, PyObject *args) { - char *path; - PyObject *argv, *env; - char **argvlist; - char **envlist; - PyObject *key, *val, *keys=NULL, *vals=NULL, *res=NULL; - int mode, pos, envc; - Py_ssize_t argc, i; - Py_intptr_t spawnval; - PyObject *(*getitem)(PyObject *, Py_ssize_t); - Py_ssize_t lastarg = 0; - - /* spawnve has four arguments: (mode, path, argv, env), where - argv is a list or tuple of strings and env is a dictionary - like posix.environ. */ - - if (!PyArg_ParseTuple(args, "ietOO:spawnve", &mode, - Py_FileSystemDefaultEncoding, - &path, &argv, &env)) - return NULL; - if (PyList_Check(argv)) { - argc = PyList_Size(argv); - getitem = PyList_GetItem; - } - else if (PyTuple_Check(argv)) { - argc = PyTuple_Size(argv); - getitem = PyTuple_GetItem; - } - else { - PyErr_SetString(PyExc_TypeError, - "spawnve() arg 2 must be a tuple or list"); - goto fail_0; - } - if (!PyMapping_Check(env)) { - PyErr_SetString(PyExc_TypeError, - "spawnve() arg 3 must be a mapping object"); - goto fail_0; - } - - argvlist = PyMem_NEW(char *, argc+1); - if (argvlist == NULL) { - PyErr_NoMemory(); - goto fail_0; - } - for (i = 0; i < argc; i++) { - if (!PyArg_Parse((*getitem)(argv, i), - "et;spawnve() arg 2 must contain only strings", - Py_FileSystemDefaultEncoding, - &argvlist[i])) - { - lastarg = i; - goto fail_1; - } - } - lastarg = argc; - argvlist[argc] = NULL; - - i = PyMapping_Size(env); - if (i < 0) - goto fail_1; - envlist = PyMem_NEW(char *, i + 1); - if (envlist == NULL) { - PyErr_NoMemory(); - goto fail_1; - } - envc = 0; - keys = PyMapping_Keys(env); - vals = PyMapping_Values(env); - if (!keys || !vals) - goto fail_2; - if (!PyList_Check(keys) || !PyList_Check(vals)) { - PyErr_SetString(PyExc_TypeError, - "spawnve(): env.keys() or env.values() is not a list"); - goto fail_2; - } - - for (pos = 0; pos < i; pos++) { - char *p, *k, *v; - size_t len; - - key = PyList_GetItem(keys, pos); - val = PyList_GetItem(vals, pos); - if (!key || !val) - goto fail_2; - - if (!PyArg_Parse( - key, - "s;spawnve() arg 3 contains a non-string key", - &k) || - !PyArg_Parse( - val, - "s;spawnve() arg 3 contains a non-string value", - &v)) - { - goto fail_2; - } - len = PyString_Size(key) + PyString_Size(val) + 2; - p = PyMem_NEW(char, len); - if (p == NULL) { - PyErr_NoMemory(); - goto fail_2; - } - PyOS_snprintf(p, len, "%s=%s", k, v); - envlist[envc++] = p; - } - envlist[envc] = 0; + char *path; + PyObject *argv, *env; + char **argvlist; + char **envlist; + PyObject *key, *val, *keys=NULL, *vals=NULL, *res=NULL; + int mode, pos, envc; + Py_ssize_t argc, i; + Py_intptr_t spawnval; + PyObject *(*getitem)(PyObject *, Py_ssize_t); + Py_ssize_t lastarg = 0; + + /* spawnve has four arguments: (mode, path, argv, env), where + argv is a list or tuple of strings and env is a dictionary + like posix.environ. */ + + if (!PyArg_ParseTuple(args, "ietOO:spawnve", &mode, + Py_FileSystemDefaultEncoding, + &path, &argv, &env)) + return NULL; + if (PyList_Check(argv)) { + argc = PyList_Size(argv); + getitem = PyList_GetItem; + } + else if (PyTuple_Check(argv)) { + argc = PyTuple_Size(argv); + getitem = PyTuple_GetItem; + } + else { + PyErr_SetString(PyExc_TypeError, + "spawnve() arg 2 must be a tuple or list"); + goto fail_0; + } + if (!PyMapping_Check(env)) { + PyErr_SetString(PyExc_TypeError, + "spawnve() arg 3 must be a mapping object"); + goto fail_0; + } + + argvlist = PyMem_NEW(char *, argc+1); + if (argvlist == NULL) { + PyErr_NoMemory(); + goto fail_0; + } + for (i = 0; i < argc; i++) { + if (!PyArg_Parse((*getitem)(argv, i), + "et;spawnve() arg 2 must contain only strings", + Py_FileSystemDefaultEncoding, + &argvlist[i])) + { + lastarg = i; + goto fail_1; + } + } + lastarg = argc; + argvlist[argc] = NULL; + + i = PyMapping_Size(env); + if (i < 0) + goto fail_1; + envlist = PyMem_NEW(char *, i + 1); + if (envlist == NULL) { + PyErr_NoMemory(); + goto fail_1; + } + envc = 0; + keys = PyMapping_Keys(env); + vals = PyMapping_Values(env); + if (!keys || !vals) + goto fail_2; + if (!PyList_Check(keys) || !PyList_Check(vals)) { + PyErr_SetString(PyExc_TypeError, + "spawnve(): env.keys() or env.values() is not a list"); + goto fail_2; + } + + for (pos = 0; pos < i; pos++) { + char *p, *k, *v; + size_t len; + + key = PyList_GetItem(keys, pos); + val = PyList_GetItem(vals, pos); + if (!key || !val) + goto fail_2; + + if (!PyArg_Parse( + key, + "s;spawnve() arg 3 contains a non-string key", + &k) || + !PyArg_Parse( + val, + "s;spawnve() arg 3 contains a non-string value", + &v)) + { + goto fail_2; + } + len = PyString_Size(key) + PyString_Size(val) + 2; + p = PyMem_NEW(char, len); + if (p == NULL) { + PyErr_NoMemory(); + goto fail_2; + } + PyOS_snprintf(p, len, "%s=%s", k, v); + envlist[envc++] = p; + } + envlist[envc] = 0; #if defined(PYOS_OS2) && defined(PYCC_GCC) - Py_BEGIN_ALLOW_THREADS - spawnval = spawnve(mode, path, argvlist, envlist); - Py_END_ALLOW_THREADS + Py_BEGIN_ALLOW_THREADS + spawnval = spawnve(mode, path, argvlist, envlist); + Py_END_ALLOW_THREADS #else - if (mode == _OLD_P_OVERLAY) - mode = _P_OVERLAY; + if (mode == _OLD_P_OVERLAY) + mode = _P_OVERLAY; - Py_BEGIN_ALLOW_THREADS - spawnval = _spawnve(mode, path, argvlist, envlist); - Py_END_ALLOW_THREADS + Py_BEGIN_ALLOW_THREADS + spawnval = _spawnve(mode, path, argvlist, envlist); + Py_END_ALLOW_THREADS #endif - if (spawnval == -1) - (void) posix_error(); - else + if (spawnval == -1) + (void) posix_error(); + else #if SIZEOF_LONG == SIZEOF_VOID_P - res = Py_BuildValue("l", (long) spawnval); + res = Py_BuildValue("l", (long) spawnval); #else - res = Py_BuildValue("L", (PY_LONG_LONG) spawnval); + res = Py_BuildValue("L", (PY_LONG_LONG) spawnval); #endif fail_2: - while (--envc >= 0) - PyMem_DEL(envlist[envc]); - PyMem_DEL(envlist); + while (--envc >= 0) + PyMem_DEL(envlist[envc]); + PyMem_DEL(envlist); fail_1: - free_string_array(argvlist, lastarg); - Py_XDECREF(vals); - Py_XDECREF(keys); + free_string_array(argvlist, lastarg); + Py_XDECREF(vals); + Py_XDECREF(keys); fail_0: - PyMem_Free(path); - return res; + PyMem_Free(path); + return res; } /* OS/2 supports spawnvp & spawnvpe natively */ @@ -3379,76 +3379,76 @@ Execute the program 'file' in a new process, using the environment\n\ search path to find the file.\n\ \n\ - mode: mode of process creation\n\ - file: executable file name\n\ - args: tuple or list of strings"); + mode: mode of process creation\n\ + file: executable file name\n\ + args: tuple or list of strings"); static PyObject * posix_spawnvp(PyObject *self, PyObject *args) { - char *path; - PyObject *argv; - char **argvlist; - int mode, i, argc; - Py_intptr_t spawnval; - PyObject *(*getitem)(PyObject *, Py_ssize_t); - - /* spawnvp has three arguments: (mode, path, argv), where - argv is a list or tuple of strings. */ - - if (!PyArg_ParseTuple(args, "ietO:spawnvp", &mode, - Py_FileSystemDefaultEncoding, - &path, &argv)) - return NULL; - if (PyList_Check(argv)) { - argc = PyList_Size(argv); - getitem = PyList_GetItem; - } - else if (PyTuple_Check(argv)) { - argc = PyTuple_Size(argv); - getitem = PyTuple_GetItem; - } - else { - PyErr_SetString(PyExc_TypeError, - "spawnvp() arg 2 must be a tuple or list"); - PyMem_Free(path); - return NULL; - } - - argvlist = PyMem_NEW(char *, argc+1); - if (argvlist == NULL) { - PyMem_Free(path); - return PyErr_NoMemory(); - } - for (i = 0; i < argc; i++) { - if (!PyArg_Parse((*getitem)(argv, i), "et", - Py_FileSystemDefaultEncoding, - &argvlist[i])) { - free_string_array(argvlist, i); - PyErr_SetString( - PyExc_TypeError, - "spawnvp() arg 2 must contain only strings"); - PyMem_Free(path); - return NULL; - } - } - argvlist[argc] = NULL; + char *path; + PyObject *argv; + char **argvlist; + int mode, i, argc; + Py_intptr_t spawnval; + PyObject *(*getitem)(PyObject *, Py_ssize_t); + + /* spawnvp has three arguments: (mode, path, argv), where + argv is a list or tuple of strings. */ + + if (!PyArg_ParseTuple(args, "ietO:spawnvp", &mode, + Py_FileSystemDefaultEncoding, + &path, &argv)) + return NULL; + if (PyList_Check(argv)) { + argc = PyList_Size(argv); + getitem = PyList_GetItem; + } + else if (PyTuple_Check(argv)) { + argc = PyTuple_Size(argv); + getitem = PyTuple_GetItem; + } + else { + PyErr_SetString(PyExc_TypeError, + "spawnvp() arg 2 must be a tuple or list"); + PyMem_Free(path); + return NULL; + } - Py_BEGIN_ALLOW_THREADS + argvlist = PyMem_NEW(char *, argc+1); + if (argvlist == NULL) { + PyMem_Free(path); + return PyErr_NoMemory(); + } + for (i = 0; i < argc; i++) { + if (!PyArg_Parse((*getitem)(argv, i), "et", + Py_FileSystemDefaultEncoding, + &argvlist[i])) { + free_string_array(argvlist, i); + PyErr_SetString( + PyExc_TypeError, + "spawnvp() arg 2 must contain only strings"); + PyMem_Free(path); + return NULL; + } + } + argvlist[argc] = NULL; + + Py_BEGIN_ALLOW_THREADS #if defined(PYCC_GCC) - spawnval = spawnvp(mode, path, argvlist); + spawnval = spawnvp(mode, path, argvlist); #else - spawnval = _spawnvp(mode, path, argvlist); + spawnval = _spawnvp(mode, path, argvlist); #endif - Py_END_ALLOW_THREADS + Py_END_ALLOW_THREADS - free_string_array(argvlist, argc); - PyMem_Free(path); + free_string_array(argvlist, argc); + PyMem_Free(path); - if (spawnval == -1) - return posix_error(); - else - return Py_BuildValue("l", (long) spawnval); + if (spawnval == -1) + return posix_error(); + else + return Py_BuildValue("l", (long) spawnval); } @@ -3457,143 +3457,143 @@ Execute the program 'file' in a new process, using the environment\n\ search path to find the file.\n\ \n\ - mode: mode of process creation\n\ - file: executable file name\n\ - args: tuple or list of arguments\n\ - env: dictionary of strings mapping to strings"); + mode: mode of process creation\n\ + file: executable file name\n\ + args: tuple or list of arguments\n\ + env: dictionary of strings mapping to strings"); static PyObject * posix_spawnvpe(PyObject *self, PyObject *args) { - char *path; - PyObject *argv, *env; - char **argvlist; - char **envlist; - PyObject *key, *val, *keys=NULL, *vals=NULL, *res=NULL; - int mode, i, pos, argc, envc; - Py_intptr_t spawnval; - PyObject *(*getitem)(PyObject *, Py_ssize_t); - int lastarg = 0; - - /* spawnvpe has four arguments: (mode, path, argv, env), where - argv is a list or tuple of strings and env is a dictionary - like posix.environ. */ - - if (!PyArg_ParseTuple(args, "ietOO:spawnvpe", &mode, - Py_FileSystemDefaultEncoding, - &path, &argv, &env)) - return NULL; - if (PyList_Check(argv)) { - argc = PyList_Size(argv); - getitem = PyList_GetItem; - } - else if (PyTuple_Check(argv)) { - argc = PyTuple_Size(argv); - getitem = PyTuple_GetItem; - } - else { - PyErr_SetString(PyExc_TypeError, - "spawnvpe() arg 2 must be a tuple or list"); - goto fail_0; - } - if (!PyMapping_Check(env)) { - PyErr_SetString(PyExc_TypeError, - "spawnvpe() arg 3 must be a mapping object"); - goto fail_0; - } - - argvlist = PyMem_NEW(char *, argc+1); - if (argvlist == NULL) { - PyErr_NoMemory(); - goto fail_0; - } - for (i = 0; i < argc; i++) { - if (!PyArg_Parse((*getitem)(argv, i), - "et;spawnvpe() arg 2 must contain only strings", - Py_FileSystemDefaultEncoding, - &argvlist[i])) - { - lastarg = i; - goto fail_1; - } - } - lastarg = argc; - argvlist[argc] = NULL; - - i = PyMapping_Size(env); - if (i < 0) - goto fail_1; - envlist = PyMem_NEW(char *, i + 1); - if (envlist == NULL) { - PyErr_NoMemory(); - goto fail_1; - } - envc = 0; - keys = PyMapping_Keys(env); - vals = PyMapping_Values(env); - if (!keys || !vals) - goto fail_2; - if (!PyList_Check(keys) || !PyList_Check(vals)) { - PyErr_SetString(PyExc_TypeError, - "spawnvpe(): env.keys() or env.values() is not a list"); - goto fail_2; - } - - for (pos = 0; pos < i; pos++) { - char *p, *k, *v; - size_t len; - - key = PyList_GetItem(keys, pos); - val = PyList_GetItem(vals, pos); - if (!key || !val) - goto fail_2; - - if (!PyArg_Parse( - key, - "s;spawnvpe() arg 3 contains a non-string key", - &k) || - !PyArg_Parse( - val, - "s;spawnvpe() arg 3 contains a non-string value", - &v)) - { - goto fail_2; - } - len = PyString_Size(key) + PyString_Size(val) + 2; - p = PyMem_NEW(char, len); - if (p == NULL) { - PyErr_NoMemory(); - goto fail_2; - } - PyOS_snprintf(p, len, "%s=%s", k, v); - envlist[envc++] = p; - } - envlist[envc] = 0; + char *path; + PyObject *argv, *env; + char **argvlist; + char **envlist; + PyObject *key, *val, *keys=NULL, *vals=NULL, *res=NULL; + int mode, i, pos, argc, envc; + Py_intptr_t spawnval; + PyObject *(*getitem)(PyObject *, Py_ssize_t); + int lastarg = 0; + + /* spawnvpe has four arguments: (mode, path, argv, env), where + argv is a list or tuple of strings and env is a dictionary + like posix.environ. */ + + if (!PyArg_ParseTuple(args, "ietOO:spawnvpe", &mode, + Py_FileSystemDefaultEncoding, + &path, &argv, &env)) + return NULL; + if (PyList_Check(argv)) { + argc = PyList_Size(argv); + getitem = PyList_GetItem; + } + else if (PyTuple_Check(argv)) { + argc = PyTuple_Size(argv); + getitem = PyTuple_GetItem; + } + else { + PyErr_SetString(PyExc_TypeError, + "spawnvpe() arg 2 must be a tuple or list"); + goto fail_0; + } + if (!PyMapping_Check(env)) { + PyErr_SetString(PyExc_TypeError, + "spawnvpe() arg 3 must be a mapping object"); + goto fail_0; + } + + argvlist = PyMem_NEW(char *, argc+1); + if (argvlist == NULL) { + PyErr_NoMemory(); + goto fail_0; + } + for (i = 0; i < argc; i++) { + if (!PyArg_Parse((*getitem)(argv, i), + "et;spawnvpe() arg 2 must contain only strings", + Py_FileSystemDefaultEncoding, + &argvlist[i])) + { + lastarg = i; + goto fail_1; + } + } + lastarg = argc; + argvlist[argc] = NULL; + + i = PyMapping_Size(env); + if (i < 0) + goto fail_1; + envlist = PyMem_NEW(char *, i + 1); + if (envlist == NULL) { + PyErr_NoMemory(); + goto fail_1; + } + envc = 0; + keys = PyMapping_Keys(env); + vals = PyMapping_Values(env); + if (!keys || !vals) + goto fail_2; + if (!PyList_Check(keys) || !PyList_Check(vals)) { + PyErr_SetString(PyExc_TypeError, + "spawnvpe(): env.keys() or env.values() is not a list"); + goto fail_2; + } + + for (pos = 0; pos < i; pos++) { + char *p, *k, *v; + size_t len; + + key = PyList_GetItem(keys, pos); + val = PyList_GetItem(vals, pos); + if (!key || !val) + goto fail_2; + + if (!PyArg_Parse( + key, + "s;spawnvpe() arg 3 contains a non-string key", + &k) || + !PyArg_Parse( + val, + "s;spawnvpe() arg 3 contains a non-string value", + &v)) + { + goto fail_2; + } + len = PyString_Size(key) + PyString_Size(val) + 2; + p = PyMem_NEW(char, len); + if (p == NULL) { + PyErr_NoMemory(); + goto fail_2; + } + PyOS_snprintf(p, len, "%s=%s", k, v); + envlist[envc++] = p; + } + envlist[envc] = 0; - Py_BEGIN_ALLOW_THREADS + Py_BEGIN_ALLOW_THREADS #if defined(PYCC_GCC) - spawnval = spawnvpe(mode, path, argvlist, envlist); + spawnval = spawnvpe(mode, path, argvlist, envlist); #else - spawnval = _spawnvpe(mode, path, argvlist, envlist); + spawnval = _spawnvpe(mode, path, argvlist, envlist); #endif - Py_END_ALLOW_THREADS + Py_END_ALLOW_THREADS - if (spawnval == -1) - (void) posix_error(); - else - res = Py_BuildValue("l", (long) spawnval); + if (spawnval == -1) + (void) posix_error(); + else + res = Py_BuildValue("l", (long) spawnval); fail_2: - while (--envc >= 0) - PyMem_DEL(envlist[envc]); - PyMem_DEL(envlist); + while (--envc >= 0) + PyMem_DEL(envlist[envc]); + PyMem_DEL(envlist); fail_1: - free_string_array(argvlist, lastarg); - Py_XDECREF(vals); - Py_XDECREF(keys); + free_string_array(argvlist, lastarg); + Py_XDECREF(vals); + Py_XDECREF(keys); fail_0: - PyMem_Free(path); - return res; + PyMem_Free(path); + return res; } #endif /* PYOS_OS2 */ #endif /* HAVE_SPAWNV */ @@ -3609,26 +3609,26 @@ static PyObject * posix_fork1(PyObject *self, PyObject *noargs) { - pid_t pid; - int result = 0; - _PyImport_AcquireLock(); - pid = fork1(); - if (pid == 0) { - /* child: this clobbers and resets the import lock. */ - PyOS_AfterFork(); - } else { - /* parent: release the import lock. */ - result = _PyImport_ReleaseLock(); - } - if (pid == -1) - return posix_error(); - if (result < 0) { - /* Don't clobber the OSError if the fork failed. */ - PyErr_SetString(PyExc_RuntimeError, - "not holding the import lock"); - return NULL; - } - return PyLong_FromPid(pid); + pid_t pid; + int result = 0; + _PyImport_AcquireLock(); + pid = fork1(); + if (pid == 0) { + /* child: this clobbers and resets the import lock. */ + PyOS_AfterFork(); + } else { + /* parent: release the import lock. */ + result = _PyImport_ReleaseLock(); + } + if (pid == -1) + return posix_error(); + if (result < 0) { + /* Don't clobber the OSError if the fork failed. */ + PyErr_SetString(PyExc_RuntimeError, + "not holding the import lock"); + return NULL; + } + return PyLong_FromPid(pid); } #endif @@ -3642,26 +3642,26 @@ static PyObject * posix_fork(PyObject *self, PyObject *noargs) { - pid_t pid; - int result = 0; - _PyImport_AcquireLock(); - pid = fork(); - if (pid == 0) { - /* child: this clobbers and resets the import lock. */ - PyOS_AfterFork(); - } else { - /* parent: release the import lock. */ - result = _PyImport_ReleaseLock(); - } - if (pid == -1) - return posix_error(); - if (result < 0) { - /* Don't clobber the OSError if the fork failed. */ - PyErr_SetString(PyExc_RuntimeError, - "not holding the import lock"); - return NULL; - } - return PyLong_FromPid(pid); + pid_t pid; + int result = 0; + _PyImport_AcquireLock(); + pid = fork(); + if (pid == 0) { + /* child: this clobbers and resets the import lock. */ + PyOS_AfterFork(); + } else { + /* parent: release the import lock. */ + result = _PyImport_ReleaseLock(); + } + if (pid == -1) + return posix_error(); + if (result < 0) { + /* Don't clobber the OSError if the fork failed. */ + PyErr_SetString(PyExc_RuntimeError, + "not holding the import lock"); + return NULL; + } + return PyLong_FromPid(pid); } #endif @@ -3699,60 +3699,60 @@ static PyObject * posix_openpty(PyObject *self, PyObject *noargs) { - int master_fd, slave_fd; + int master_fd, slave_fd; #ifndef HAVE_OPENPTY - char * slave_name; + char * slave_name; #endif #if defined(HAVE_DEV_PTMX) && !defined(HAVE_OPENPTY) && !defined(HAVE__GETPTY) - PyOS_sighandler_t sig_saved; + PyOS_sighandler_t sig_saved; #ifdef sun - extern char *ptsname(int fildes); + extern char *ptsname(int fildes); #endif #endif #ifdef HAVE_OPENPTY - if (openpty(&master_fd, &slave_fd, NULL, NULL, NULL) != 0) - return posix_error(); + if (openpty(&master_fd, &slave_fd, NULL, NULL, NULL) != 0) + return posix_error(); #elif defined(HAVE__GETPTY) - slave_name = _getpty(&master_fd, O_RDWR, 0666, 0); - if (slave_name == NULL) - return posix_error(); - - slave_fd = open(slave_name, O_RDWR); - if (slave_fd < 0) - return posix_error(); -#else - master_fd = open(DEV_PTY_FILE, O_RDWR | O_NOCTTY); /* open master */ - if (master_fd < 0) - return posix_error(); - sig_saved = PyOS_setsig(SIGCHLD, SIG_DFL); - /* change permission of slave */ - if (grantpt(master_fd) < 0) { - PyOS_setsig(SIGCHLD, sig_saved); - return posix_error(); - } - /* unlock slave */ - if (unlockpt(master_fd) < 0) { - PyOS_setsig(SIGCHLD, sig_saved); - return posix_error(); - } - PyOS_setsig(SIGCHLD, sig_saved); - slave_name = ptsname(master_fd); /* get name of slave */ - if (slave_name == NULL) - return posix_error(); - slave_fd = open(slave_name, O_RDWR | O_NOCTTY); /* open slave */ - if (slave_fd < 0) - return posix_error(); + slave_name = _getpty(&master_fd, O_RDWR, 0666, 0); + if (slave_name == NULL) + return posix_error(); + + slave_fd = open(slave_name, O_RDWR); + if (slave_fd < 0) + return posix_error(); +#else + master_fd = open(DEV_PTY_FILE, O_RDWR | O_NOCTTY); /* open master */ + if (master_fd < 0) + return posix_error(); + sig_saved = PyOS_setsig(SIGCHLD, SIG_DFL); + /* change permission of slave */ + if (grantpt(master_fd) < 0) { + PyOS_setsig(SIGCHLD, sig_saved); + return posix_error(); + } + /* unlock slave */ + if (unlockpt(master_fd) < 0) { + PyOS_setsig(SIGCHLD, sig_saved); + return posix_error(); + } + PyOS_setsig(SIGCHLD, sig_saved); + slave_name = ptsname(master_fd); /* get name of slave */ + if (slave_name == NULL) + return posix_error(); + slave_fd = open(slave_name, O_RDWR | O_NOCTTY); /* open slave */ + if (slave_fd < 0) + return posix_error(); #if !defined(__CYGWIN__) && !defined(HAVE_DEV_PTC) - ioctl(slave_fd, I_PUSH, "ptem"); /* push ptem */ - ioctl(slave_fd, I_PUSH, "ldterm"); /* push ldterm */ + ioctl(slave_fd, I_PUSH, "ptem"); /* push ptem */ + ioctl(slave_fd, I_PUSH, "ldterm"); /* push ldterm */ #ifndef __hpux - ioctl(slave_fd, I_PUSH, "ttcompat"); /* push ttcompat */ + ioctl(slave_fd, I_PUSH, "ttcompat"); /* push ttcompat */ #endif /* __hpux */ #endif /* HAVE_CYGWIN */ #endif /* HAVE_OPENPTY */ - return Py_BuildValue("(ii)", master_fd, slave_fd); + return Py_BuildValue("(ii)", master_fd, slave_fd); } #endif /* defined(HAVE_OPENPTY) || defined(HAVE__GETPTY) || defined(HAVE_DEV_PTMX) */ @@ -3767,27 +3767,27 @@ static PyObject * posix_forkpty(PyObject *self, PyObject *noargs) { - int master_fd = -1, result = 0; - pid_t pid; + int master_fd = -1, result = 0; + pid_t pid; - _PyImport_AcquireLock(); - pid = forkpty(&master_fd, NULL, NULL, NULL); - if (pid == 0) { - /* child: this clobbers and resets the import lock. */ - PyOS_AfterFork(); - } else { - /* parent: release the import lock. */ - result = _PyImport_ReleaseLock(); - } - if (pid == -1) - return posix_error(); - if (result < 0) { - /* Don't clobber the OSError if the fork failed. */ - PyErr_SetString(PyExc_RuntimeError, - "not holding the import lock"); - return NULL; - } - return Py_BuildValue("(Ni)", PyLong_FromPid(pid), master_fd); + _PyImport_AcquireLock(); + pid = forkpty(&master_fd, NULL, NULL, NULL); + if (pid == 0) { + /* child: this clobbers and resets the import lock. */ + PyOS_AfterFork(); + } else { + /* parent: release the import lock. */ + result = _PyImport_ReleaseLock(); + } + if (pid == -1) + return posix_error(); + if (result < 0) { + /* Don't clobber the OSError if the fork failed. */ + PyErr_SetString(PyExc_RuntimeError, + "not holding the import lock"); + return NULL; + } + return Py_BuildValue("(Ni)", PyLong_FromPid(pid), master_fd); } #endif @@ -3799,7 +3799,7 @@ static PyObject * posix_getegid(PyObject *self, PyObject *noargs) { - return PyInt_FromLong((long)getegid()); + return PyInt_FromLong((long)getegid()); } #endif @@ -3812,7 +3812,7 @@ static PyObject * posix_geteuid(PyObject *self, PyObject *noargs) { - return PyInt_FromLong((long)geteuid()); + return PyInt_FromLong((long)geteuid()); } #endif @@ -3825,7 +3825,7 @@ static PyObject * posix_getgid(PyObject *self, PyObject *noargs) { - return PyInt_FromLong((long)getgid()); + return PyInt_FromLong((long)getgid()); } #endif @@ -3837,7 +3837,7 @@ static PyObject * posix_getpid(PyObject *self, PyObject *noargs) { - return PyLong_FromPid(getpid()); + return PyLong_FromPid(getpid()); } @@ -3854,30 +3854,30 @@ #ifdef NGROUPS_MAX #define MAX_GROUPS NGROUPS_MAX #else - /* defined to be 16 on Solaris7, so this should be a small number */ + /* defined to be 16 on Solaris7, so this should be a small number */ #define MAX_GROUPS 64 #endif - gid_t grouplist[MAX_GROUPS]; - int n; + gid_t grouplist[MAX_GROUPS]; + int n; - n = getgroups(MAX_GROUPS, grouplist); - if (n < 0) - posix_error(); - else { - result = PyList_New(n); - if (result != NULL) { - int i; - for (i = 0; i < n; ++i) { - PyObject *o = PyInt_FromLong((long)grouplist[i]); - if (o == NULL) { - Py_DECREF(result); - result = NULL; - break; - } - PyList_SET_ITEM(result, i, o); - } + n = getgroups(MAX_GROUPS, grouplist); + if (n < 0) + posix_error(); + else { + result = PyList_New(n); + if (result != NULL) { + int i; + for (i = 0; i < n; ++i) { + PyObject *o = PyInt_FromLong((long)grouplist[i]); + if (o == NULL) { + Py_DECREF(result); + result = NULL; + break; } + PyList_SET_ITEM(result, i, o); + } } + } return result; } @@ -3893,17 +3893,17 @@ static PyObject * posix_initgroups(PyObject *self, PyObject *args) { - char *username; - long gid; + char *username; + long gid; - if (!PyArg_ParseTuple(args, "sl:initgroups", &username, &gid)) - return NULL; + if (!PyArg_ParseTuple(args, "sl:initgroups", &username, &gid)) + return NULL; - if (initgroups(username, (gid_t) gid) == -1) - return PyErr_SetFromErrno(PyExc_OSError); + if (initgroups(username, (gid_t) gid) == -1) + return PyErr_SetFromErrno(PyExc_OSError); - Py_INCREF(Py_None); - return Py_None; + Py_INCREF(Py_None); + return Py_None; } #endif @@ -3915,13 +3915,13 @@ static PyObject * posix_getpgid(PyObject *self, PyObject *args) { - pid_t pid, pgid; - if (!PyArg_ParseTuple(args, PARSE_PID ":getpgid", &pid)) - return NULL; - pgid = getpgid(pid); - if (pgid < 0) - return posix_error(); - return PyLong_FromPid(pgid); + pid_t pid, pgid; + if (!PyArg_ParseTuple(args, PARSE_PID ":getpgid", &pid)) + return NULL; + pgid = getpgid(pid); + if (pgid < 0) + return posix_error(); + return PyLong_FromPid(pgid); } #endif /* HAVE_GETPGID */ @@ -3935,9 +3935,9 @@ posix_getpgrp(PyObject *self, PyObject *noargs) { #ifdef GETPGRP_HAVE_ARG - return PyLong_FromPid(getpgrp(0)); + return PyLong_FromPid(getpgrp(0)); #else /* GETPGRP_HAVE_ARG */ - return PyLong_FromPid(getpgrp()); + return PyLong_FromPid(getpgrp()); #endif /* GETPGRP_HAVE_ARG */ } #endif /* HAVE_GETPGRP */ @@ -3952,13 +3952,13 @@ posix_setpgrp(PyObject *self, PyObject *noargs) { #ifdef SETPGRP_HAVE_ARG - if (setpgrp(0, 0) < 0) + if (setpgrp(0, 0) < 0) #else /* SETPGRP_HAVE_ARG */ - if (setpgrp() < 0) + if (setpgrp() < 0) #endif /* SETPGRP_HAVE_ARG */ - return posix_error(); - Py_INCREF(Py_None); - return Py_None; + return posix_error(); + Py_INCREF(Py_None); + return Py_None; } #endif /* HAVE_SETPGRP */ @@ -3971,7 +3971,7 @@ static PyObject * posix_getppid(PyObject *self, PyObject *noargs) { - return PyLong_FromPid(getppid()); + return PyLong_FromPid(getppid()); } #endif @@ -3984,22 +3984,22 @@ static PyObject * posix_getlogin(PyObject *self, PyObject *noargs) { - PyObject *result = NULL; - char *name; - int old_errno = errno; + PyObject *result = NULL; + char *name; + int old_errno = errno; - errno = 0; - name = getlogin(); - if (name == NULL) { - if (errno) - posix_error(); - else - PyErr_SetString(PyExc_OSError, - "unable to determine login name"); - } + errno = 0; + name = getlogin(); + if (name == NULL) { + if (errno) + posix_error(); else - result = PyString_FromString(name); - errno = old_errno; + PyErr_SetString(PyExc_OSError, + "unable to determine login name"); + } + else + result = PyString_FromString(name); + errno = old_errno; return result; } @@ -4013,7 +4013,7 @@ static PyObject * posix_getuid(PyObject *self, PyObject *noargs) { - return PyInt_FromLong((long)getuid()); + return PyInt_FromLong((long)getuid()); } #endif @@ -4026,10 +4026,10 @@ static PyObject * posix_kill(PyObject *self, PyObject *args) { - pid_t pid; - int sig; - if (!PyArg_ParseTuple(args, PARSE_PID "i:kill", &pid, &sig)) - return NULL; + pid_t pid; + int sig; + if (!PyArg_ParseTuple(args, PARSE_PID "i:kill", &pid, &sig)) + return NULL; #if defined(PYOS_OS2) && !defined(PYCC_GCC) if (sig == XCPT_SIGNAL_INTR || sig == XCPT_SIGNAL_BREAK) { APIRET rc; @@ -4044,11 +4044,11 @@ } else return NULL; /* Unrecognized Signal Requested */ #else - if (kill(pid, sig) == -1) - return posix_error(); + if (kill(pid, sig) == -1) + return posix_error(); #endif - Py_INCREF(Py_None); - return Py_None; + Py_INCREF(Py_None); + return Py_None; } #endif @@ -4060,18 +4060,18 @@ static PyObject * posix_killpg(PyObject *self, PyObject *args) { - int sig; - pid_t pgid; - /* XXX some man pages make the `pgid` parameter an int, others - a pid_t. Since getpgrp() returns a pid_t, we assume killpg should - take the same type. Moreover, pid_t is always at least as wide as - int (else compilation of this module fails), which is safe. */ - if (!PyArg_ParseTuple(args, PARSE_PID "i:killpg", &pgid, &sig)) - return NULL; - if (killpg(pgid, sig) == -1) - return posix_error(); - Py_INCREF(Py_None); - return Py_None; + int sig; + pid_t pgid; + /* XXX some man pages make the `pgid` parameter an int, others + a pid_t. Since getpgrp() returns a pid_t, we assume killpg should + take the same type. Moreover, pid_t is always at least as wide as + int (else compilation of this module fails), which is safe. */ + if (!PyArg_ParseTuple(args, PARSE_PID "i:killpg", &pgid, &sig)) + return NULL; + if (killpg(pgid, sig) == -1) + return posix_error(); + Py_INCREF(Py_None); + return Py_None; } #endif @@ -4083,42 +4083,42 @@ static PyObject * win32_kill(PyObject *self, PyObject *args) { - PyObject *result, handle_obj; - DWORD pid, sig, err; - HANDLE handle; - - if (!PyArg_ParseTuple(args, "kk:kill", &pid, &sig)) - return NULL; - - /* Console processes which share a common console can be sent CTRL+C or - CTRL+BREAK events, provided they handle said events. */ - if (sig == CTRL_C_EVENT || sig == CTRL_BREAK_EVENT) { - if (GenerateConsoleCtrlEvent(sig, pid) == 0) { - err = GetLastError(); - return PyErr_SetFromWindowsErr(err); - } - else - Py_RETURN_NONE; - } - - /* If the signal is outside of what GenerateConsoleCtrlEvent can use, - attempt to open and terminate the process. */ - handle = OpenProcess(PROCESS_ALL_ACCESS, FALSE, pid); - if (handle == NULL) { - err = GetLastError(); - return PyErr_SetFromWindowsErr(err); - } - - if (TerminateProcess(handle, sig) == 0) { - err = GetLastError(); - result = PyErr_SetFromWindowsErr(err); - } else { - Py_INCREF(Py_None); - result = Py_None; - } + PyObject *result, handle_obj; + DWORD pid, sig, err; + HANDLE handle; + + if (!PyArg_ParseTuple(args, "kk:kill", &pid, &sig)) + return NULL; + + /* Console processes which share a common console can be sent CTRL+C or + CTRL+BREAK events, provided they handle said events. */ + if (sig == CTRL_C_EVENT || sig == CTRL_BREAK_EVENT) { + if (GenerateConsoleCtrlEvent(sig, pid) == 0) { + err = GetLastError(); + return PyErr_SetFromWindowsErr(err); + } + else + Py_RETURN_NONE; + } + + /* If the signal is outside of what GenerateConsoleCtrlEvent can use, + attempt to open and terminate the process. */ + handle = OpenProcess(PROCESS_ALL_ACCESS, FALSE, pid); + if (handle == NULL) { + err = GetLastError(); + return PyErr_SetFromWindowsErr(err); + } + + if (TerminateProcess(handle, sig) == 0) { + err = GetLastError(); + result = PyErr_SetFromWindowsErr(err); + } else { + Py_INCREF(Py_None); + result = Py_None; + } - CloseHandle(handle); - return result; + CloseHandle(handle); + return result; } #endif /* MS_WINDOWS */ @@ -4135,13 +4135,13 @@ static PyObject * posix_plock(PyObject *self, PyObject *args) { - int op; - if (!PyArg_ParseTuple(args, "i:plock", &op)) - return NULL; - if (plock(op) == -1) - return posix_error(); - Py_INCREF(Py_None); - return Py_None; + int op; + if (!PyArg_ParseTuple(args, "i:plock", &op)) + return NULL; + if (plock(op) == -1) + return posix_error(); + Py_INCREF(Py_None); + return Py_None; } #endif @@ -4156,107 +4156,107 @@ static int async_system(const char *command) { - char errormsg[256], args[1024]; - RESULTCODES rcodes; - APIRET rc; - - char *shell = getenv("COMSPEC"); - if (!shell) - shell = "cmd"; - - /* avoid overflowing the argument buffer */ - if (strlen(shell) + 3 + strlen(command) >= 1024) - return ERROR_NOT_ENOUGH_MEMORY - - args[0] = '\0'; - strcat(args, shell); - strcat(args, "/c "); - strcat(args, command); - - /* execute asynchronously, inheriting the environment */ - rc = DosExecPgm(errormsg, - sizeof(errormsg), - EXEC_ASYNC, - args, - NULL, - &rcodes, - shell); - return rc; + char errormsg[256], args[1024]; + RESULTCODES rcodes; + APIRET rc; + + char *shell = getenv("COMSPEC"); + if (!shell) + shell = "cmd"; + + /* avoid overflowing the argument buffer */ + if (strlen(shell) + 3 + strlen(command) >= 1024) + return ERROR_NOT_ENOUGH_MEMORY + + args[0] = '\0'; + strcat(args, shell); + strcat(args, "/c "); + strcat(args, command); + + /* execute asynchronously, inheriting the environment */ + rc = DosExecPgm(errormsg, + sizeof(errormsg), + EXEC_ASYNC, + args, + NULL, + &rcodes, + shell); + return rc; } static FILE * popen(const char *command, const char *mode, int pipesize, int *err) { - int oldfd, tgtfd; - HFILE pipeh[2]; - APIRET rc; - - /* mode determines which of stdin or stdout is reconnected to - * the pipe to the child - */ - if (strchr(mode, 'r') != NULL) { - tgt_fd = 1; /* stdout */ - } else if (strchr(mode, 'w')) { - tgt_fd = 0; /* stdin */ - } else { - *err = ERROR_INVALID_ACCESS; - return NULL; - } - - /* setup the pipe */ - if ((rc = DosCreatePipe(&pipeh[0], &pipeh[1], pipesize)) != NO_ERROR) { - *err = rc; - return NULL; - } - - /* prevent other threads accessing stdio */ - DosEnterCritSec(); - - /* reconnect stdio and execute child */ - oldfd = dup(tgtfd); - close(tgtfd); - if (dup2(pipeh[tgtfd], tgtfd) == 0) { - DosClose(pipeh[tgtfd]); - rc = async_system(command); - } - - /* restore stdio */ - dup2(oldfd, tgtfd); - close(oldfd); - - /* allow other threads access to stdio */ - DosExitCritSec(); - - /* if execution of child was successful return file stream */ - if (rc == NO_ERROR) - return fdopen(pipeh[1 - tgtfd], mode); - else { - DosClose(pipeh[1 - tgtfd]); - *err = rc; - return NULL; - } + int oldfd, tgtfd; + HFILE pipeh[2]; + APIRET rc; + + /* mode determines which of stdin or stdout is reconnected to + * the pipe to the child + */ + if (strchr(mode, 'r') != NULL) { + tgt_fd = 1; /* stdout */ + } else if (strchr(mode, 'w')) { + tgt_fd = 0; /* stdin */ + } else { + *err = ERROR_INVALID_ACCESS; + return NULL; + } + + /* setup the pipe */ + if ((rc = DosCreatePipe(&pipeh[0], &pipeh[1], pipesize)) != NO_ERROR) { + *err = rc; + return NULL; + } + + /* prevent other threads accessing stdio */ + DosEnterCritSec(); + + /* reconnect stdio and execute child */ + oldfd = dup(tgtfd); + close(tgtfd); + if (dup2(pipeh[tgtfd], tgtfd) == 0) { + DosClose(pipeh[tgtfd]); + rc = async_system(command); + } + + /* restore stdio */ + dup2(oldfd, tgtfd); + close(oldfd); + + /* allow other threads access to stdio */ + DosExitCritSec(); + + /* if execution of child was successful return file stream */ + if (rc == NO_ERROR) + return fdopen(pipeh[1 - tgtfd], mode); + else { + DosClose(pipeh[1 - tgtfd]); + *err = rc; + return NULL; + } } static PyObject * posix_popen(PyObject *self, PyObject *args) { - char *name; - char *mode = "r"; - int err, bufsize = -1; - FILE *fp; - PyObject *f; - if (!PyArg_ParseTuple(args, "s|si:popen", &name, &mode, &bufsize)) - return NULL; - Py_BEGIN_ALLOW_THREADS - fp = popen(name, mode, (bufsize > 0) ? bufsize : 4096, &err); - Py_END_ALLOW_THREADS - if (fp == NULL) - return os2_error(err); - - f = PyFile_FromFile(fp, name, mode, fclose); - if (f != NULL) - PyFile_SetBufSize(f, bufsize); - return f; + char *name; + char *mode = "r"; + int err, bufsize = -1; + FILE *fp; + PyObject *f; + if (!PyArg_ParseTuple(args, "s|si:popen", &name, &mode, &bufsize)) + return NULL; + Py_BEGIN_ALLOW_THREADS + fp = popen(name, mode, (bufsize > 0) ? bufsize : 4096, &err); + Py_END_ALLOW_THREADS + if (fp == NULL) + return os2_error(err); + + f = PyFile_FromFile(fp, name, mode, fclose); + if (f != NULL) + PyFile_SetBufSize(f, bufsize); + return f; } #elif defined(PYCC_GCC) @@ -4265,22 +4265,22 @@ static PyObject * posix_popen(PyObject *self, PyObject *args) { - char *name; - char *mode = "r"; - int bufsize = -1; - FILE *fp; - PyObject *f; - if (!PyArg_ParseTuple(args, "s|si:popen", &name, &mode, &bufsize)) - return NULL; - Py_BEGIN_ALLOW_THREADS - fp = popen(name, mode); - Py_END_ALLOW_THREADS - if (fp == NULL) - return posix_error(); - f = PyFile_FromFile(fp, name, mode, pclose); - if (f != NULL) - PyFile_SetBufSize(f, bufsize); - return f; + char *name; + char *mode = "r"; + int bufsize = -1; + FILE *fp; + PyObject *f; + if (!PyArg_ParseTuple(args, "s|si:popen", &name, &mode, &bufsize)) + return NULL; + Py_BEGIN_ALLOW_THREADS + fp = popen(name, mode); + Py_END_ALLOW_THREADS + if (fp == NULL) + return posix_error(); + f = PyFile_FromFile(fp, name, mode, pclose); + if (f != NULL) + PyFile_SetBufSize(f, bufsize); + return f; } /* fork() under OS/2 has lots'o'warts @@ -4314,26 +4314,26 @@ static PyObject * os2emx_popen2(PyObject *self, PyObject *args) { - PyObject *f; - int tm=0; + PyObject *f; + int tm=0; - char *cmdstring; - char *mode = "t"; - int bufsize = -1; - if (!PyArg_ParseTuple(args, "s|si:popen2", &cmdstring, &mode, &bufsize)) - return NULL; - - if (*mode == 't') - tm = O_TEXT; - else if (*mode != 'b') { - PyErr_SetString(PyExc_ValueError, "mode must be 't' or 'b'"); - return NULL; - } else - tm = O_BINARY; + char *cmdstring; + char *mode = "t"; + int bufsize = -1; + if (!PyArg_ParseTuple(args, "s|si:popen2", &cmdstring, &mode, &bufsize)) + return NULL; - f = _PyPopen(cmdstring, tm, POPEN_2, bufsize); + if (*mode == 't') + tm = O_TEXT; + else if (*mode != 'b') { + PyErr_SetString(PyExc_ValueError, "mode must be 't' or 'b'"); + return NULL; + } else + tm = O_BINARY; - return f; + f = _PyPopen(cmdstring, tm, POPEN_2, bufsize); + + return f; } /* @@ -4346,26 +4346,26 @@ static PyObject * os2emx_popen3(PyObject *self, PyObject *args) { - PyObject *f; - int tm = 0; + PyObject *f; + int tm = 0; - char *cmdstring; - char *mode = "t"; - int bufsize = -1; - if (!PyArg_ParseTuple(args, "s|si:popen3", &cmdstring, &mode, &bufsize)) - return NULL; - - if (*mode == 't') - tm = O_TEXT; - else if (*mode != 'b') { - PyErr_SetString(PyExc_ValueError, "mode must be 't' or 'b'"); - return NULL; - } else - tm = O_BINARY; + char *cmdstring; + char *mode = "t"; + int bufsize = -1; + if (!PyArg_ParseTuple(args, "s|si:popen3", &cmdstring, &mode, &bufsize)) + return NULL; - f = _PyPopen(cmdstring, tm, POPEN_3, bufsize); + if (*mode == 't') + tm = O_TEXT; + else if (*mode != 'b') { + PyErr_SetString(PyExc_ValueError, "mode must be 't' or 'b'"); + return NULL; + } else + tm = O_BINARY; + + f = _PyPopen(cmdstring, tm, POPEN_3, bufsize); - return f; + return f; } /* @@ -4378,26 +4378,26 @@ static PyObject * os2emx_popen4(PyObject *self, PyObject *args) { - PyObject *f; - int tm = 0; + PyObject *f; + int tm = 0; + + char *cmdstring; + char *mode = "t"; + int bufsize = -1; + if (!PyArg_ParseTuple(args, "s|si:popen4", &cmdstring, &mode, &bufsize)) + return NULL; - char *cmdstring; - char *mode = "t"; - int bufsize = -1; - if (!PyArg_ParseTuple(args, "s|si:popen4", &cmdstring, &mode, &bufsize)) - return NULL; - - if (*mode == 't') - tm = O_TEXT; - else if (*mode != 'b') { - PyErr_SetString(PyExc_ValueError, "mode must be 't' or 'b'"); - return NULL; - } else - tm = O_BINARY; + if (*mode == 't') + tm = O_TEXT; + else if (*mode != 'b') { + PyErr_SetString(PyExc_ValueError, "mode must be 't' or 'b'"); + return NULL; + } else + tm = O_BINARY; - f = _PyPopen(cmdstring, tm, POPEN_4, bufsize); + f = _PyPopen(cmdstring, tm, POPEN_4, bufsize); - return f; + return f; } /* a couple of structures for convenient handling of multiple @@ -4405,14 +4405,14 @@ */ struct file_ref { - int handle; - int flags; + int handle; + int flags; }; struct pipe_ref { - int rd; - int wr; + int rd; + int wr; }; /* The following code is derived from the win32 code */ @@ -4420,306 +4420,306 @@ static PyObject * _PyPopen(char *cmdstring, int mode, int n, int bufsize) { - struct file_ref stdio[3]; - struct pipe_ref p_fd[3]; - FILE *p_s[3]; - int file_count, i, pipe_err; - pid_t pipe_pid; - char *shell, *sh_name, *opt, *rd_mode, *wr_mode; - PyObject *f, *p_f[3]; - - /* file modes for subsequent fdopen's on pipe handles */ - if (mode == O_TEXT) - { - rd_mode = "rt"; - wr_mode = "wt"; - } - else - { - rd_mode = "rb"; - wr_mode = "wb"; - } - - /* prepare shell references */ - if ((shell = getenv("EMXSHELL")) == NULL) - if ((shell = getenv("COMSPEC")) == NULL) - { - errno = ENOENT; - return posix_error(); - } - - sh_name = _getname(shell); - if (stricmp(sh_name, "cmd.exe") == 0 || stricmp(sh_name, "4os2.exe") == 0) - opt = "/c"; - else - opt = "-c"; - - /* save current stdio fds + their flags, and set not inheritable */ - i = pipe_err = 0; - while (pipe_err >= 0 && i < 3) - { - pipe_err = stdio[i].handle = dup(i); - stdio[i].flags = fcntl(i, F_GETFD, 0); - fcntl(stdio[i].handle, F_SETFD, stdio[i].flags | FD_CLOEXEC); - i++; - } - if (pipe_err < 0) - { - /* didn't get them all saved - clean up and bail out */ - int saved_err = errno; - while (i-- > 0) - { - close(stdio[i].handle); - } - errno = saved_err; - return posix_error(); - } - - /* create pipe ends */ - file_count = 2; - if (n == POPEN_3) - file_count = 3; - i = pipe_err = 0; - while ((pipe_err == 0) && (i < file_count)) - pipe_err = pipe((int *)&p_fd[i++]); - if (pipe_err < 0) - { - /* didn't get them all made - clean up and bail out */ - while (i-- > 0) - { - close(p_fd[i].wr); - close(p_fd[i].rd); - } - errno = EPIPE; - return posix_error(); - } - - /* change the actual standard IO streams over temporarily, - * making the retained pipe ends non-inheritable - */ - pipe_err = 0; - - /* - stdin */ - if (dup2(p_fd[0].rd, 0) == 0) - { - close(p_fd[0].rd); - i = fcntl(p_fd[0].wr, F_GETFD, 0); - fcntl(p_fd[0].wr, F_SETFD, i | FD_CLOEXEC); - if ((p_s[0] = fdopen(p_fd[0].wr, wr_mode)) == NULL) - { - close(p_fd[0].wr); - pipe_err = -1; - } - } - else - { - pipe_err = -1; - } - - /* - stdout */ - if (pipe_err == 0) - { - if (dup2(p_fd[1].wr, 1) == 1) - { - close(p_fd[1].wr); - i = fcntl(p_fd[1].rd, F_GETFD, 0); - fcntl(p_fd[1].rd, F_SETFD, i | FD_CLOEXEC); - if ((p_s[1] = fdopen(p_fd[1].rd, rd_mode)) == NULL) - { - close(p_fd[1].rd); - pipe_err = -1; - } - } - else - { - pipe_err = -1; - } - } - - /* - stderr, as required */ - if (pipe_err == 0) - switch (n) - { - case POPEN_3: - { - if (dup2(p_fd[2].wr, 2) == 2) - { - close(p_fd[2].wr); - i = fcntl(p_fd[2].rd, F_GETFD, 0); - fcntl(p_fd[2].rd, F_SETFD, i | FD_CLOEXEC); - if ((p_s[2] = fdopen(p_fd[2].rd, rd_mode)) == NULL) - { - close(p_fd[2].rd); - pipe_err = -1; - } - } - else - { - pipe_err = -1; - } - break; - } - - case POPEN_4: - { - if (dup2(1, 2) != 2) - { - pipe_err = -1; - } - break; - } - } - - /* spawn the child process */ - if (pipe_err == 0) - { - pipe_pid = spawnlp(P_NOWAIT, shell, shell, opt, cmdstring, (char *)0); - if (pipe_pid == -1) - { - pipe_err = -1; - } - else - { - /* save the PID into the FILE structure - * NOTE: this implementation doesn't actually - * take advantage of this, but do it for - * completeness - AIM Apr01 - */ - for (i = 0; i < file_count; i++) - p_s[i]->_pid = pipe_pid; - } - } - - /* reset standard IO to normal */ - for (i = 0; i < 3; i++) - { - dup2(stdio[i].handle, i); - fcntl(i, F_SETFD, stdio[i].flags); - close(stdio[i].handle); - } - - /* if any remnant problems, clean up and bail out */ - if (pipe_err < 0) - { - for (i = 0; i < 3; i++) - { - close(p_fd[i].rd); - close(p_fd[i].wr); - } - errno = EPIPE; - return posix_error_with_filename(cmdstring); - } - - /* build tuple of file objects to return */ - if ((p_f[0] = PyFile_FromFile(p_s[0], cmdstring, wr_mode, _PyPclose)) != NULL) - PyFile_SetBufSize(p_f[0], bufsize); - if ((p_f[1] = PyFile_FromFile(p_s[1], cmdstring, rd_mode, _PyPclose)) != NULL) - PyFile_SetBufSize(p_f[1], bufsize); - if (n == POPEN_3) - { - if ((p_f[2] = PyFile_FromFile(p_s[2], cmdstring, rd_mode, _PyPclose)) != NULL) - PyFile_SetBufSize(p_f[0], bufsize); - f = PyTuple_Pack(3, p_f[0], p_f[1], p_f[2]); - } - else - f = PyTuple_Pack(2, p_f[0], p_f[1]); - - /* - * Insert the files we've created into the process dictionary - * all referencing the list with the process handle and the - * initial number of files (see description below in _PyPclose). - * Since if _PyPclose later tried to wait on a process when all - * handles weren't closed, it could create a deadlock with the - * child, we spend some energy here to try to ensure that we - * either insert all file handles into the dictionary or none - * at all. It's a little clumsy with the various popen modes - * and variable number of files involved. - */ - if (!_PyPopenProcs) - { - _PyPopenProcs = PyDict_New(); - } - - if (_PyPopenProcs) - { - PyObject *procObj, *pidObj, *intObj, *fileObj[3]; - int ins_rc[3]; - - fileObj[0] = fileObj[1] = fileObj[2] = NULL; - ins_rc[0] = ins_rc[1] = ins_rc[2] = 0; - - procObj = PyList_New(2); - pidObj = PyLong_FromPid(pipe_pid); - intObj = PyInt_FromLong((long) file_count); - - if (procObj && pidObj && intObj) - { - PyList_SetItem(procObj, 0, pidObj); - PyList_SetItem(procObj, 1, intObj); - - fileObj[0] = PyLong_FromVoidPtr(p_s[0]); - if (fileObj[0]) - { - ins_rc[0] = PyDict_SetItem(_PyPopenProcs, - fileObj[0], - procObj); - } - fileObj[1] = PyLong_FromVoidPtr(p_s[1]); - if (fileObj[1]) - { - ins_rc[1] = PyDict_SetItem(_PyPopenProcs, - fileObj[1], - procObj); - } - if (file_count >= 3) - { - fileObj[2] = PyLong_FromVoidPtr(p_s[2]); - if (fileObj[2]) - { - ins_rc[2] = PyDict_SetItem(_PyPopenProcs, - fileObj[2], - procObj); - } - } - - if (ins_rc[0] < 0 || !fileObj[0] || - ins_rc[1] < 0 || (file_count > 1 && !fileObj[1]) || - ins_rc[2] < 0 || (file_count > 2 && !fileObj[2])) - { - /* Something failed - remove any dictionary - * entries that did make it. - */ - if (!ins_rc[0] && fileObj[0]) - { - PyDict_DelItem(_PyPopenProcs, - fileObj[0]); - } - if (!ins_rc[1] && fileObj[1]) - { - PyDict_DelItem(_PyPopenProcs, - fileObj[1]); - } - if (!ins_rc[2] && fileObj[2]) - { - PyDict_DelItem(_PyPopenProcs, - fileObj[2]); - } - } - } - - /* - * Clean up our localized references for the dictionary keys - * and value since PyDict_SetItem will Py_INCREF any copies - * that got placed in the dictionary. - */ - Py_XDECREF(procObj); - Py_XDECREF(fileObj[0]); - Py_XDECREF(fileObj[1]); - Py_XDECREF(fileObj[2]); - } + struct file_ref stdio[3]; + struct pipe_ref p_fd[3]; + FILE *p_s[3]; + int file_count, i, pipe_err; + pid_t pipe_pid; + char *shell, *sh_name, *opt, *rd_mode, *wr_mode; + PyObject *f, *p_f[3]; + + /* file modes for subsequent fdopen's on pipe handles */ + if (mode == O_TEXT) + { + rd_mode = "rt"; + wr_mode = "wt"; + } + else + { + rd_mode = "rb"; + wr_mode = "wb"; + } + + /* prepare shell references */ + if ((shell = getenv("EMXSHELL")) == NULL) + if ((shell = getenv("COMSPEC")) == NULL) + { + errno = ENOENT; + return posix_error(); + } + + sh_name = _getname(shell); + if (stricmp(sh_name, "cmd.exe") == 0 || stricmp(sh_name, "4os2.exe") == 0) + opt = "/c"; + else + opt = "-c"; + + /* save current stdio fds + their flags, and set not inheritable */ + i = pipe_err = 0; + while (pipe_err >= 0 && i < 3) + { + pipe_err = stdio[i].handle = dup(i); + stdio[i].flags = fcntl(i, F_GETFD, 0); + fcntl(stdio[i].handle, F_SETFD, stdio[i].flags | FD_CLOEXEC); + i++; + } + if (pipe_err < 0) + { + /* didn't get them all saved - clean up and bail out */ + int saved_err = errno; + while (i-- > 0) + { + close(stdio[i].handle); + } + errno = saved_err; + return posix_error(); + } + + /* create pipe ends */ + file_count = 2; + if (n == POPEN_3) + file_count = 3; + i = pipe_err = 0; + while ((pipe_err == 0) && (i < file_count)) + pipe_err = pipe((int *)&p_fd[i++]); + if (pipe_err < 0) + { + /* didn't get them all made - clean up and bail out */ + while (i-- > 0) + { + close(p_fd[i].wr); + close(p_fd[i].rd); + } + errno = EPIPE; + return posix_error(); + } + + /* change the actual standard IO streams over temporarily, + * making the retained pipe ends non-inheritable + */ + pipe_err = 0; + + /* - stdin */ + if (dup2(p_fd[0].rd, 0) == 0) + { + close(p_fd[0].rd); + i = fcntl(p_fd[0].wr, F_GETFD, 0); + fcntl(p_fd[0].wr, F_SETFD, i | FD_CLOEXEC); + if ((p_s[0] = fdopen(p_fd[0].wr, wr_mode)) == NULL) + { + close(p_fd[0].wr); + pipe_err = -1; + } + } + else + { + pipe_err = -1; + } + + /* - stdout */ + if (pipe_err == 0) + { + if (dup2(p_fd[1].wr, 1) == 1) + { + close(p_fd[1].wr); + i = fcntl(p_fd[1].rd, F_GETFD, 0); + fcntl(p_fd[1].rd, F_SETFD, i | FD_CLOEXEC); + if ((p_s[1] = fdopen(p_fd[1].rd, rd_mode)) == NULL) + { + close(p_fd[1].rd); + pipe_err = -1; + } + } + else + { + pipe_err = -1; + } + } - /* Child is launched. */ - return f; + /* - stderr, as required */ + if (pipe_err == 0) + switch (n) + { + case POPEN_3: + { + if (dup2(p_fd[2].wr, 2) == 2) + { + close(p_fd[2].wr); + i = fcntl(p_fd[2].rd, F_GETFD, 0); + fcntl(p_fd[2].rd, F_SETFD, i | FD_CLOEXEC); + if ((p_s[2] = fdopen(p_fd[2].rd, rd_mode)) == NULL) + { + close(p_fd[2].rd); + pipe_err = -1; + } + } + else + { + pipe_err = -1; + } + break; + } + + case POPEN_4: + { + if (dup2(1, 2) != 2) + { + pipe_err = -1; + } + break; + } + } + + /* spawn the child process */ + if (pipe_err == 0) + { + pipe_pid = spawnlp(P_NOWAIT, shell, shell, opt, cmdstring, (char *)0); + if (pipe_pid == -1) + { + pipe_err = -1; + } + else + { + /* save the PID into the FILE structure + * NOTE: this implementation doesn't actually + * take advantage of this, but do it for + * completeness - AIM Apr01 + */ + for (i = 0; i < file_count; i++) + p_s[i]->_pid = pipe_pid; + } + } + + /* reset standard IO to normal */ + for (i = 0; i < 3; i++) + { + dup2(stdio[i].handle, i); + fcntl(i, F_SETFD, stdio[i].flags); + close(stdio[i].handle); + } + + /* if any remnant problems, clean up and bail out */ + if (pipe_err < 0) + { + for (i = 0; i < 3; i++) + { + close(p_fd[i].rd); + close(p_fd[i].wr); + } + errno = EPIPE; + return posix_error_with_filename(cmdstring); + } + + /* build tuple of file objects to return */ + if ((p_f[0] = PyFile_FromFile(p_s[0], cmdstring, wr_mode, _PyPclose)) != NULL) + PyFile_SetBufSize(p_f[0], bufsize); + if ((p_f[1] = PyFile_FromFile(p_s[1], cmdstring, rd_mode, _PyPclose)) != NULL) + PyFile_SetBufSize(p_f[1], bufsize); + if (n == POPEN_3) + { + if ((p_f[2] = PyFile_FromFile(p_s[2], cmdstring, rd_mode, _PyPclose)) != NULL) + PyFile_SetBufSize(p_f[0], bufsize); + f = PyTuple_Pack(3, p_f[0], p_f[1], p_f[2]); + } + else + f = PyTuple_Pack(2, p_f[0], p_f[1]); + + /* + * Insert the files we've created into the process dictionary + * all referencing the list with the process handle and the + * initial number of files (see description below in _PyPclose). + * Since if _PyPclose later tried to wait on a process when all + * handles weren't closed, it could create a deadlock with the + * child, we spend some energy here to try to ensure that we + * either insert all file handles into the dictionary or none + * at all. It's a little clumsy with the various popen modes + * and variable number of files involved. + */ + if (!_PyPopenProcs) + { + _PyPopenProcs = PyDict_New(); + } + + if (_PyPopenProcs) + { + PyObject *procObj, *pidObj, *intObj, *fileObj[3]; + int ins_rc[3]; + + fileObj[0] = fileObj[1] = fileObj[2] = NULL; + ins_rc[0] = ins_rc[1] = ins_rc[2] = 0; + + procObj = PyList_New(2); + pidObj = PyLong_FromPid(pipe_pid); + intObj = PyInt_FromLong((long) file_count); + + if (procObj && pidObj && intObj) + { + PyList_SetItem(procObj, 0, pidObj); + PyList_SetItem(procObj, 1, intObj); + + fileObj[0] = PyLong_FromVoidPtr(p_s[0]); + if (fileObj[0]) + { + ins_rc[0] = PyDict_SetItem(_PyPopenProcs, + fileObj[0], + procObj); + } + fileObj[1] = PyLong_FromVoidPtr(p_s[1]); + if (fileObj[1]) + { + ins_rc[1] = PyDict_SetItem(_PyPopenProcs, + fileObj[1], + procObj); + } + if (file_count >= 3) + { + fileObj[2] = PyLong_FromVoidPtr(p_s[2]); + if (fileObj[2]) + { + ins_rc[2] = PyDict_SetItem(_PyPopenProcs, + fileObj[2], + procObj); + } + } + + if (ins_rc[0] < 0 || !fileObj[0] || + ins_rc[1] < 0 || (file_count > 1 && !fileObj[1]) || + ins_rc[2] < 0 || (file_count > 2 && !fileObj[2])) + { + /* Something failed - remove any dictionary + * entries that did make it. + */ + if (!ins_rc[0] && fileObj[0]) + { + PyDict_DelItem(_PyPopenProcs, + fileObj[0]); + } + if (!ins_rc[1] && fileObj[1]) + { + PyDict_DelItem(_PyPopenProcs, + fileObj[1]); + } + if (!ins_rc[2] && fileObj[2]) + { + PyDict_DelItem(_PyPopenProcs, + fileObj[2]); + } + } + } + + /* + * Clean up our localized references for the dictionary keys + * and value since PyDict_SetItem will Py_INCREF any copies + * that got placed in the dictionary. + */ + Py_XDECREF(procObj); + Py_XDECREF(fileObj[0]); + Py_XDECREF(fileObj[1]); + Py_XDECREF(fileObj[2]); + } + + /* Child is launched. */ + return f; } /* @@ -4750,88 +4750,88 @@ static int _PyPclose(FILE *file) { - int result; - int exit_code; - pid_t pipe_pid; - PyObject *procObj, *pidObj, *intObj, *fileObj; - int file_count; + int result; + int exit_code; + pid_t pipe_pid; + PyObject *procObj, *pidObj, *intObj, *fileObj; + int file_count; #ifdef WITH_THREAD - PyGILState_STATE state; + PyGILState_STATE state; #endif - /* Close the file handle first, to ensure it can't block the - * child from exiting if it's the last handle. - */ - result = fclose(file); + /* Close the file handle first, to ensure it can't block the + * child from exiting if it's the last handle. + */ + result = fclose(file); #ifdef WITH_THREAD - state = PyGILState_Ensure(); + state = PyGILState_Ensure(); #endif - if (_PyPopenProcs) - { - if ((fileObj = PyLong_FromVoidPtr(file)) != NULL && - (procObj = PyDict_GetItem(_PyPopenProcs, - fileObj)) != NULL && - (pidObj = PyList_GetItem(procObj,0)) != NULL && - (intObj = PyList_GetItem(procObj,1)) != NULL) - { - pipe_pid = (pid_t) PyLong_AsPid(pidObj); - file_count = (int) PyInt_AsLong(intObj); - - if (file_count > 1) - { - /* Still other files referencing process */ - file_count--; - PyList_SetItem(procObj,1, - PyInt_FromLong((long) file_count)); - } - else - { - /* Last file for this process */ - if (result != EOF && - waitpid(pipe_pid, &exit_code, 0) == pipe_pid) - { - /* extract exit status */ - if (WIFEXITED(exit_code)) - { - result = WEXITSTATUS(exit_code); - } - else - { - errno = EPIPE; - result = -1; - } - } - else - { - /* Indicate failure - this will cause the file object - * to raise an I/O error and translate the last - * error code from errno. We do have a problem with - * last errors that overlap the normal errno table, - * but that's a consistent problem with the file object. - */ - result = -1; - } - } - - /* Remove this file pointer from dictionary */ - PyDict_DelItem(_PyPopenProcs, fileObj); - - if (PyDict_Size(_PyPopenProcs) == 0) - { - Py_DECREF(_PyPopenProcs); - _PyPopenProcs = NULL; - } + if (_PyPopenProcs) + { + if ((fileObj = PyLong_FromVoidPtr(file)) != NULL && + (procObj = PyDict_GetItem(_PyPopenProcs, + fileObj)) != NULL && + (pidObj = PyList_GetItem(procObj,0)) != NULL && + (intObj = PyList_GetItem(procObj,1)) != NULL) + { + pipe_pid = (pid_t) PyLong_AsPid(pidObj); + file_count = (int) PyInt_AsLong(intObj); + + if (file_count > 1) + { + /* Still other files referencing process */ + file_count--; + PyList_SetItem(procObj,1, + PyInt_FromLong((long) file_count)); + } + else + { + /* Last file for this process */ + if (result != EOF && + waitpid(pipe_pid, &exit_code, 0) == pipe_pid) + { + /* extract exit status */ + if (WIFEXITED(exit_code)) + { + result = WEXITSTATUS(exit_code); + } + else + { + errno = EPIPE; + result = -1; + } + } + else + { + /* Indicate failure - this will cause the file object + * to raise an I/O error and translate the last + * error code from errno. We do have a problem with + * last errors that overlap the normal errno table, + * but that's a consistent problem with the file object. + */ + result = -1; + } + } + + /* Remove this file pointer from dictionary */ + PyDict_DelItem(_PyPopenProcs, fileObj); - } /* if object retrieval ok */ + if (PyDict_Size(_PyPopenProcs) == 0) + { + Py_DECREF(_PyPopenProcs); + _PyPopenProcs = NULL; + } + + } /* if object retrieval ok */ - Py_XDECREF(fileObj); - } /* if _PyPopenProcs */ + Py_XDECREF(fileObj); + } /* if _PyPopenProcs */ #ifdef WITH_THREAD - PyGILState_Release(state); + PyGILState_Release(state); #endif - return result; + return result; } #endif /* PYCC_??? */ @@ -4876,36 +4876,36 @@ static PyObject * posix_popen(PyObject *self, PyObject *args) { - PyObject *f; - int tm = 0; + PyObject *f; + int tm = 0; + + char *cmdstring; + char *mode = "r"; + int bufsize = -1; + if (!PyArg_ParseTuple(args, "s|si:popen", &cmdstring, &mode, &bufsize)) + return NULL; - char *cmdstring; - char *mode = "r"; - int bufsize = -1; - if (!PyArg_ParseTuple(args, "s|si:popen", &cmdstring, &mode, &bufsize)) - return NULL; - - if (*mode == 'r') - tm = _O_RDONLY; - else if (*mode != 'w') { - PyErr_SetString(PyExc_ValueError, "popen() arg 2 must be 'r' or 'w'"); - return NULL; - } else - tm = _O_WRONLY; - - if (bufsize != -1) { - PyErr_SetString(PyExc_ValueError, "popen() arg 3 must be -1"); - return NULL; - } - - if (*(mode+1) == 't') - f = _PyPopen(cmdstring, tm | _O_TEXT, POPEN_1); - else if (*(mode+1) == 'b') - f = _PyPopen(cmdstring, tm | _O_BINARY, POPEN_1); - else - f = _PyPopen(cmdstring, tm | _O_TEXT, POPEN_1); + if (*mode == 'r') + tm = _O_RDONLY; + else if (*mode != 'w') { + PyErr_SetString(PyExc_ValueError, "popen() arg 2 must be 'r' or 'w'"); + return NULL; + } else + tm = _O_WRONLY; - return f; + if (bufsize != -1) { + PyErr_SetString(PyExc_ValueError, "popen() arg 3 must be -1"); + return NULL; + } + + if (*(mode+1) == 't') + f = _PyPopen(cmdstring, tm | _O_TEXT, POPEN_1); + else if (*(mode+1) == 'b') + f = _PyPopen(cmdstring, tm | _O_BINARY, POPEN_1); + else + f = _PyPopen(cmdstring, tm | _O_TEXT, POPEN_1); + + return f; } /* Variation on win32pipe.popen @@ -4917,31 +4917,31 @@ static PyObject * win32_popen2(PyObject *self, PyObject *args) { - PyObject *f; - int tm=0; + PyObject *f; + int tm=0; - char *cmdstring; - char *mode = "t"; - int bufsize = -1; - if (!PyArg_ParseTuple(args, "s|si:popen2", &cmdstring, &mode, &bufsize)) - return NULL; - - if (*mode == 't') - tm = _O_TEXT; - else if (*mode != 'b') { - PyErr_SetString(PyExc_ValueError, "popen2() arg 2 must be 't' or 'b'"); - return NULL; - } else - tm = _O_BINARY; - - if (bufsize != -1) { - PyErr_SetString(PyExc_ValueError, "popen2() arg 3 must be -1"); - return NULL; - } + char *cmdstring; + char *mode = "t"; + int bufsize = -1; + if (!PyArg_ParseTuple(args, "s|si:popen2", &cmdstring, &mode, &bufsize)) + return NULL; - f = _PyPopen(cmdstring, tm, POPEN_2); + if (*mode == 't') + tm = _O_TEXT; + else if (*mode != 'b') { + PyErr_SetString(PyExc_ValueError, "popen2() arg 2 must be 't' or 'b'"); + return NULL; + } else + tm = _O_BINARY; - return f; + if (bufsize != -1) { + PyErr_SetString(PyExc_ValueError, "popen2() arg 3 must be -1"); + return NULL; + } + + f = _PyPopen(cmdstring, tm, POPEN_2); + + return f; } /* @@ -4954,31 +4954,31 @@ static PyObject * win32_popen3(PyObject *self, PyObject *args) { - PyObject *f; - int tm = 0; + PyObject *f; + int tm = 0; - char *cmdstring; - char *mode = "t"; - int bufsize = -1; - if (!PyArg_ParseTuple(args, "s|si:popen3", &cmdstring, &mode, &bufsize)) - return NULL; - - if (*mode == 't') - tm = _O_TEXT; - else if (*mode != 'b') { - PyErr_SetString(PyExc_ValueError, "popen3() arg 2 must be 't' or 'b'"); - return NULL; - } else - tm = _O_BINARY; - - if (bufsize != -1) { - PyErr_SetString(PyExc_ValueError, "popen3() arg 3 must be -1"); - return NULL; - } + char *cmdstring; + char *mode = "t"; + int bufsize = -1; + if (!PyArg_ParseTuple(args, "s|si:popen3", &cmdstring, &mode, &bufsize)) + return NULL; - f = _PyPopen(cmdstring, tm, POPEN_3); + if (*mode == 't') + tm = _O_TEXT; + else if (*mode != 'b') { + PyErr_SetString(PyExc_ValueError, "popen3() arg 2 must be 't' or 'b'"); + return NULL; + } else + tm = _O_BINARY; - return f; + if (bufsize != -1) { + PyErr_SetString(PyExc_ValueError, "popen3() arg 3 must be -1"); + return NULL; + } + + f = _PyPopen(cmdstring, tm, POPEN_3); + + return f; } /* @@ -4991,186 +4991,186 @@ static PyObject * win32_popen4(PyObject *self, PyObject *args) { - PyObject *f; - int tm = 0; + PyObject *f; + int tm = 0; - char *cmdstring; - char *mode = "t"; - int bufsize = -1; - if (!PyArg_ParseTuple(args, "s|si:popen4", &cmdstring, &mode, &bufsize)) - return NULL; - - if (*mode == 't') - tm = _O_TEXT; - else if (*mode != 'b') { - PyErr_SetString(PyExc_ValueError, "popen4() arg 2 must be 't' or 'b'"); - return NULL; - } else - tm = _O_BINARY; - - if (bufsize != -1) { - PyErr_SetString(PyExc_ValueError, "popen4() arg 3 must be -1"); - return NULL; - } + char *cmdstring; + char *mode = "t"; + int bufsize = -1; + if (!PyArg_ParseTuple(args, "s|si:popen4", &cmdstring, &mode, &bufsize)) + return NULL; - f = _PyPopen(cmdstring, tm, POPEN_4); + if (*mode == 't') + tm = _O_TEXT; + else if (*mode != 'b') { + PyErr_SetString(PyExc_ValueError, "popen4() arg 2 must be 't' or 'b'"); + return NULL; + } else + tm = _O_BINARY; - return f; + if (bufsize != -1) { + PyErr_SetString(PyExc_ValueError, "popen4() arg 3 must be -1"); + return NULL; + } + + f = _PyPopen(cmdstring, tm, POPEN_4); + + return f; } static BOOL _PyPopenCreateProcess(char *cmdstring, - HANDLE hStdin, - HANDLE hStdout, - HANDLE hStderr, - HANDLE *hProcess) -{ - PROCESS_INFORMATION piProcInfo; - STARTUPINFO siStartInfo; - DWORD dwProcessFlags = 0; /* no NEW_CONSOLE by default for Ctrl+C handling */ - char *s1,*s2, *s3 = " /c "; - const char *szConsoleSpawn = "w9xpopen.exe"; - int i; - Py_ssize_t x; - - if (i = GetEnvironmentVariable("COMSPEC",NULL,0)) { - char *comshell; - - s1 = (char *)alloca(i); - if (!(x = GetEnvironmentVariable("COMSPEC", s1, i))) - /* x < i, so x fits into an integer */ - return (int)x; - - /* Explicitly check if we are using COMMAND.COM. If we are - * then use the w9xpopen hack. - */ - comshell = s1 + x; - while (comshell >= s1 && *comshell != '\\') - --comshell; - ++comshell; - - if (GetVersion() < 0x80000000 && - _stricmp(comshell, "command.com") != 0) { - /* NT/2000 and not using command.com. */ - x = i + strlen(s3) + strlen(cmdstring) + 1; - s2 = (char *)alloca(x); - ZeroMemory(s2, x); - PyOS_snprintf(s2, x, "%s%s%s", s1, s3, cmdstring); - } - else { - /* - * Oh gag, we're on Win9x or using COMMAND.COM. Use - * the workaround listed in KB: Q150956 - */ - char modulepath[_MAX_PATH]; - struct stat statinfo; - GetModuleFileName(NULL, modulepath, sizeof(modulepath)); - for (x = i = 0; modulepath[i]; i++) - if (modulepath[i] == SEP) - x = i+1; - modulepath[x] = '\0'; - /* Create the full-name to w9xpopen, so we can test it exists */ - strncat(modulepath, - szConsoleSpawn, - (sizeof(modulepath)/sizeof(modulepath[0])) - -strlen(modulepath)); - if (stat(modulepath, &statinfo) != 0) { - size_t mplen = sizeof(modulepath)/sizeof(modulepath[0]); - /* Eeek - file-not-found - possibly an embedding - situation - see if we can locate it in sys.prefix - */ - strncpy(modulepath, - Py_GetExecPrefix(), - mplen); - modulepath[mplen-1] = '\0'; - if (modulepath[strlen(modulepath)-1] != '\\') - strcat(modulepath, "\\"); - strncat(modulepath, - szConsoleSpawn, - mplen-strlen(modulepath)); - /* No where else to look - raise an easily identifiable - error, rather than leaving Windows to report - "file not found" - as the user is probably blissfully - unaware this shim EXE is used, and it will confuse them. - (well, it confused me for a while ;-) - */ - if (stat(modulepath, &statinfo) != 0) { - PyErr_Format(PyExc_RuntimeError, - "Can not locate '%s' which is needed " - "for popen to work with your shell " - "or platform.", - szConsoleSpawn); - return FALSE; - } - } - x = i + strlen(s3) + strlen(cmdstring) + 1 + - strlen(modulepath) + - strlen(szConsoleSpawn) + 1; - - s2 = (char *)alloca(x); - ZeroMemory(s2, x); - /* To maintain correct argument passing semantics, - we pass the command-line as it stands, and allow - quoting to be applied. w9xpopen.exe will then - use its argv vector, and re-quote the necessary - args for the ultimate child process. - */ - PyOS_snprintf( - s2, x, - "\"%s\" %s%s%s", - modulepath, - s1, - s3, - cmdstring); - /* Not passing CREATE_NEW_CONSOLE has been known to - cause random failures on win9x. Specifically a - dialog: - "Your program accessed mem currently in use at xxx" - and a hopeful warning about the stability of your - system. - Cost is Ctrl+C won't kill children, but anyone - who cares can have a go! - */ - dwProcessFlags |= CREATE_NEW_CONSOLE; - } - } - - /* Could be an else here to try cmd.exe / command.com in the path - Now we'll just error out.. */ - else { - PyErr_SetString(PyExc_RuntimeError, - "Cannot locate a COMSPEC environment variable to " - "use as the shell"); - return FALSE; - } - - ZeroMemory(&siStartInfo, sizeof(STARTUPINFO)); - siStartInfo.cb = sizeof(STARTUPINFO); - siStartInfo.dwFlags = STARTF_USESTDHANDLES | STARTF_USESHOWWINDOW; - siStartInfo.hStdInput = hStdin; - siStartInfo.hStdOutput = hStdout; - siStartInfo.hStdError = hStderr; - siStartInfo.wShowWindow = SW_HIDE; - - if (CreateProcess(NULL, - s2, - NULL, - NULL, - TRUE, - dwProcessFlags, - NULL, - NULL, - &siStartInfo, - &piProcInfo) ) { - /* Close the handles now so anyone waiting is woken. */ - CloseHandle(piProcInfo.hThread); - - /* Return process handle */ - *hProcess = piProcInfo.hProcess; - return TRUE; - } - win32_error("CreateProcess", s2); - return FALSE; + HANDLE hStdin, + HANDLE hStdout, + HANDLE hStderr, + HANDLE *hProcess) +{ + PROCESS_INFORMATION piProcInfo; + STARTUPINFO siStartInfo; + DWORD dwProcessFlags = 0; /* no NEW_CONSOLE by default for Ctrl+C handling */ + char *s1,*s2, *s3 = " /c "; + const char *szConsoleSpawn = "w9xpopen.exe"; + int i; + Py_ssize_t x; + + if (i = GetEnvironmentVariable("COMSPEC",NULL,0)) { + char *comshell; + + s1 = (char *)alloca(i); + if (!(x = GetEnvironmentVariable("COMSPEC", s1, i))) + /* x < i, so x fits into an integer */ + return (int)x; + + /* Explicitly check if we are using COMMAND.COM. If we are + * then use the w9xpopen hack. + */ + comshell = s1 + x; + while (comshell >= s1 && *comshell != '\\') + --comshell; + ++comshell; + + if (GetVersion() < 0x80000000 && + _stricmp(comshell, "command.com") != 0) { + /* NT/2000 and not using command.com. */ + x = i + strlen(s3) + strlen(cmdstring) + 1; + s2 = (char *)alloca(x); + ZeroMemory(s2, x); + PyOS_snprintf(s2, x, "%s%s%s", s1, s3, cmdstring); + } + else { + /* + * Oh gag, we're on Win9x or using COMMAND.COM. Use + * the workaround listed in KB: Q150956 + */ + char modulepath[_MAX_PATH]; + struct stat statinfo; + GetModuleFileName(NULL, modulepath, sizeof(modulepath)); + for (x = i = 0; modulepath[i]; i++) + if (modulepath[i] == SEP) + x = i+1; + modulepath[x] = '\0'; + /* Create the full-name to w9xpopen, so we can test it exists */ + strncat(modulepath, + szConsoleSpawn, + (sizeof(modulepath)/sizeof(modulepath[0])) + -strlen(modulepath)); + if (stat(modulepath, &statinfo) != 0) { + size_t mplen = sizeof(modulepath)/sizeof(modulepath[0]); + /* Eeek - file-not-found - possibly an embedding + situation - see if we can locate it in sys.prefix + */ + strncpy(modulepath, + Py_GetExecPrefix(), + mplen); + modulepath[mplen-1] = '\0'; + if (modulepath[strlen(modulepath)-1] != '\\') + strcat(modulepath, "\\"); + strncat(modulepath, + szConsoleSpawn, + mplen-strlen(modulepath)); + /* No where else to look - raise an easily identifiable + error, rather than leaving Windows to report + "file not found" - as the user is probably blissfully + unaware this shim EXE is used, and it will confuse them. + (well, it confused me for a while ;-) + */ + if (stat(modulepath, &statinfo) != 0) { + PyErr_Format(PyExc_RuntimeError, + "Can not locate '%s' which is needed " + "for popen to work with your shell " + "or platform.", + szConsoleSpawn); + return FALSE; + } + } + x = i + strlen(s3) + strlen(cmdstring) + 1 + + strlen(modulepath) + + strlen(szConsoleSpawn) + 1; + + s2 = (char *)alloca(x); + ZeroMemory(s2, x); + /* To maintain correct argument passing semantics, + we pass the command-line as it stands, and allow + quoting to be applied. w9xpopen.exe will then + use its argv vector, and re-quote the necessary + args for the ultimate child process. + */ + PyOS_snprintf( + s2, x, + "\"%s\" %s%s%s", + modulepath, + s1, + s3, + cmdstring); + /* Not passing CREATE_NEW_CONSOLE has been known to + cause random failures on win9x. Specifically a + dialog: + "Your program accessed mem currently in use at xxx" + and a hopeful warning about the stability of your + system. + Cost is Ctrl+C won't kill children, but anyone + who cares can have a go! + */ + dwProcessFlags |= CREATE_NEW_CONSOLE; + } + } + + /* Could be an else here to try cmd.exe / command.com in the path + Now we'll just error out.. */ + else { + PyErr_SetString(PyExc_RuntimeError, + "Cannot locate a COMSPEC environment variable to " + "use as the shell"); + return FALSE; + } + + ZeroMemory(&siStartInfo, sizeof(STARTUPINFO)); + siStartInfo.cb = sizeof(STARTUPINFO); + siStartInfo.dwFlags = STARTF_USESTDHANDLES | STARTF_USESHOWWINDOW; + siStartInfo.hStdInput = hStdin; + siStartInfo.hStdOutput = hStdout; + siStartInfo.hStdError = hStderr; + siStartInfo.wShowWindow = SW_HIDE; + + if (CreateProcess(NULL, + s2, + NULL, + NULL, + TRUE, + dwProcessFlags, + NULL, + NULL, + &siStartInfo, + &piProcInfo) ) { + /* Close the handles now so anyone waiting is woken. */ + CloseHandle(piProcInfo.hThread); + + /* Return process handle */ + *hProcess = piProcInfo.hProcess; + return TRUE; + } + win32_error("CreateProcess", s2); + return FALSE; } /* The following code is based off of KB: Q190351 */ @@ -5178,301 +5178,301 @@ static PyObject * _PyPopen(char *cmdstring, int mode, int n) { - HANDLE hChildStdinRd, hChildStdinWr, hChildStdoutRd, hChildStdoutWr, - hChildStderrRd, hChildStderrWr, hChildStdinWrDup, hChildStdoutRdDup, - hChildStderrRdDup, hProcess; /* hChildStdoutWrDup; */ - - SECURITY_ATTRIBUTES saAttr; - BOOL fSuccess; - int fd1, fd2, fd3; - FILE *f1, *f2, *f3; - long file_count; - PyObject *f; - - saAttr.nLength = sizeof(SECURITY_ATTRIBUTES); - saAttr.bInheritHandle = TRUE; - saAttr.lpSecurityDescriptor = NULL; - - if (!CreatePipe(&hChildStdinRd, &hChildStdinWr, &saAttr, 0)) - return win32_error("CreatePipe", NULL); - - /* Create new output read handle and the input write handle. Set - * the inheritance properties to FALSE. Otherwise, the child inherits - * these handles; resulting in non-closeable handles to the pipes - * being created. */ - fSuccess = DuplicateHandle(GetCurrentProcess(), hChildStdinWr, - GetCurrentProcess(), &hChildStdinWrDup, 0, - FALSE, - DUPLICATE_SAME_ACCESS); - if (!fSuccess) - return win32_error("DuplicateHandle", NULL); - - /* Close the inheritable version of ChildStdin - that we're using. */ - CloseHandle(hChildStdinWr); - - if (!CreatePipe(&hChildStdoutRd, &hChildStdoutWr, &saAttr, 0)) - return win32_error("CreatePipe", NULL); - - fSuccess = DuplicateHandle(GetCurrentProcess(), hChildStdoutRd, - GetCurrentProcess(), &hChildStdoutRdDup, 0, - FALSE, DUPLICATE_SAME_ACCESS); - if (!fSuccess) - return win32_error("DuplicateHandle", NULL); - - /* Close the inheritable version of ChildStdout - that we're using. */ - CloseHandle(hChildStdoutRd); - - if (n != POPEN_4) { - if (!CreatePipe(&hChildStderrRd, &hChildStderrWr, &saAttr, 0)) - return win32_error("CreatePipe", NULL); - fSuccess = DuplicateHandle(GetCurrentProcess(), - hChildStderrRd, - GetCurrentProcess(), - &hChildStderrRdDup, 0, - FALSE, DUPLICATE_SAME_ACCESS); - if (!fSuccess) - return win32_error("DuplicateHandle", NULL); - /* Close the inheritable version of ChildStdErr that we're using. */ - CloseHandle(hChildStderrRd); - } - - switch (n) { - case POPEN_1: - switch (mode & (_O_RDONLY | _O_TEXT | _O_BINARY | _O_WRONLY)) { - case _O_WRONLY | _O_TEXT: - /* Case for writing to child Stdin in text mode. */ - fd1 = _open_osfhandle((Py_intptr_t)hChildStdinWrDup, mode); - f1 = _fdopen(fd1, "w"); - f = PyFile_FromFile(f1, cmdstring, "w", _PyPclose); - PyFile_SetBufSize(f, 0); - /* We don't care about these pipes anymore, so close them. */ - CloseHandle(hChildStdoutRdDup); - CloseHandle(hChildStderrRdDup); - break; - - case _O_RDONLY | _O_TEXT: - /* Case for reading from child Stdout in text mode. */ - fd1 = _open_osfhandle((Py_intptr_t)hChildStdoutRdDup, mode); - f1 = _fdopen(fd1, "r"); - f = PyFile_FromFile(f1, cmdstring, "r", _PyPclose); - PyFile_SetBufSize(f, 0); - /* We don't care about these pipes anymore, so close them. */ - CloseHandle(hChildStdinWrDup); - CloseHandle(hChildStderrRdDup); - break; - - case _O_RDONLY | _O_BINARY: - /* Case for readinig from child Stdout in binary mode. */ - fd1 = _open_osfhandle((Py_intptr_t)hChildStdoutRdDup, mode); - f1 = _fdopen(fd1, "rb"); - f = PyFile_FromFile(f1, cmdstring, "rb", _PyPclose); - PyFile_SetBufSize(f, 0); - /* We don't care about these pipes anymore, so close them. */ - CloseHandle(hChildStdinWrDup); - CloseHandle(hChildStderrRdDup); - break; - - case _O_WRONLY | _O_BINARY: - /* Case for writing to child Stdin in binary mode. */ - fd1 = _open_osfhandle((Py_intptr_t)hChildStdinWrDup, mode); - f1 = _fdopen(fd1, "wb"); - f = PyFile_FromFile(f1, cmdstring, "wb", _PyPclose); - PyFile_SetBufSize(f, 0); - /* We don't care about these pipes anymore, so close them. */ - CloseHandle(hChildStdoutRdDup); - CloseHandle(hChildStderrRdDup); - break; - } - file_count = 1; - break; - - case POPEN_2: - case POPEN_4: - { - char *m1, *m2; - PyObject *p1, *p2; - - if (mode & _O_TEXT) { - m1 = "r"; - m2 = "w"; - } else { - m1 = "rb"; - m2 = "wb"; - } - - fd1 = _open_osfhandle((Py_intptr_t)hChildStdinWrDup, mode); - f1 = _fdopen(fd1, m2); - fd2 = _open_osfhandle((Py_intptr_t)hChildStdoutRdDup, mode); - f2 = _fdopen(fd2, m1); - p1 = PyFile_FromFile(f1, cmdstring, m2, _PyPclose); - PyFile_SetBufSize(p1, 0); - p2 = PyFile_FromFile(f2, cmdstring, m1, _PyPclose); - PyFile_SetBufSize(p2, 0); - - if (n != 4) - CloseHandle(hChildStderrRdDup); - - f = PyTuple_Pack(2,p1,p2); - Py_XDECREF(p1); - Py_XDECREF(p2); - file_count = 2; - break; - } - - case POPEN_3: - { - char *m1, *m2; - PyObject *p1, *p2, *p3; - - if (mode & _O_TEXT) { - m1 = "r"; - m2 = "w"; - } else { - m1 = "rb"; - m2 = "wb"; - } - - fd1 = _open_osfhandle((Py_intptr_t)hChildStdinWrDup, mode); - f1 = _fdopen(fd1, m2); - fd2 = _open_osfhandle((Py_intptr_t)hChildStdoutRdDup, mode); - f2 = _fdopen(fd2, m1); - fd3 = _open_osfhandle((Py_intptr_t)hChildStderrRdDup, mode); - f3 = _fdopen(fd3, m1); - p1 = PyFile_FromFile(f1, cmdstring, m2, _PyPclose); - p2 = PyFile_FromFile(f2, cmdstring, m1, _PyPclose); - p3 = PyFile_FromFile(f3, cmdstring, m1, _PyPclose); - PyFile_SetBufSize(p1, 0); - PyFile_SetBufSize(p2, 0); - PyFile_SetBufSize(p3, 0); - f = PyTuple_Pack(3,p1,p2,p3); - Py_XDECREF(p1); - Py_XDECREF(p2); - Py_XDECREF(p3); - file_count = 3; - break; - } - } - - if (n == POPEN_4) { - if (!_PyPopenCreateProcess(cmdstring, - hChildStdinRd, - hChildStdoutWr, - hChildStdoutWr, - &hProcess)) - return NULL; - } - else { - if (!_PyPopenCreateProcess(cmdstring, - hChildStdinRd, - hChildStdoutWr, - hChildStderrWr, - &hProcess)) - return NULL; - } - - /* - * Insert the files we've created into the process dictionary - * all referencing the list with the process handle and the - * initial number of files (see description below in _PyPclose). - * Since if _PyPclose later tried to wait on a process when all - * handles weren't closed, it could create a deadlock with the - * child, we spend some energy here to try to ensure that we - * either insert all file handles into the dictionary or none - * at all. It's a little clumsy with the various popen modes - * and variable number of files involved. - */ - if (!_PyPopenProcs) { - _PyPopenProcs = PyDict_New(); - } - - if (_PyPopenProcs) { - PyObject *procObj, *hProcessObj, *intObj, *fileObj[3]; - int ins_rc[3]; - - fileObj[0] = fileObj[1] = fileObj[2] = NULL; - ins_rc[0] = ins_rc[1] = ins_rc[2] = 0; - - procObj = PyList_New(2); - hProcessObj = PyLong_FromVoidPtr(hProcess); - intObj = PyInt_FromLong(file_count); - - if (procObj && hProcessObj && intObj) { - PyList_SetItem(procObj,0,hProcessObj); - PyList_SetItem(procObj,1,intObj); - - fileObj[0] = PyLong_FromVoidPtr(f1); - if (fileObj[0]) { - ins_rc[0] = PyDict_SetItem(_PyPopenProcs, - fileObj[0], - procObj); - } - if (file_count >= 2) { - fileObj[1] = PyLong_FromVoidPtr(f2); - if (fileObj[1]) { - ins_rc[1] = PyDict_SetItem(_PyPopenProcs, - fileObj[1], - procObj); - } - } - if (file_count >= 3) { - fileObj[2] = PyLong_FromVoidPtr(f3); - if (fileObj[2]) { - ins_rc[2] = PyDict_SetItem(_PyPopenProcs, - fileObj[2], - procObj); - } - } - - if (ins_rc[0] < 0 || !fileObj[0] || - ins_rc[1] < 0 || (file_count > 1 && !fileObj[1]) || - ins_rc[2] < 0 || (file_count > 2 && !fileObj[2])) { - /* Something failed - remove any dictionary - * entries that did make it. - */ - if (!ins_rc[0] && fileObj[0]) { - PyDict_DelItem(_PyPopenProcs, - fileObj[0]); - } - if (!ins_rc[1] && fileObj[1]) { - PyDict_DelItem(_PyPopenProcs, - fileObj[1]); - } - if (!ins_rc[2] && fileObj[2]) { - PyDict_DelItem(_PyPopenProcs, - fileObj[2]); - } - } - } - - /* - * Clean up our localized references for the dictionary keys - * and value since PyDict_SetItem will Py_INCREF any copies - * that got placed in the dictionary. - */ - Py_XDECREF(procObj); - Py_XDECREF(fileObj[0]); - Py_XDECREF(fileObj[1]); - Py_XDECREF(fileObj[2]); - } - - /* Child is launched. Close the parents copy of those pipe - * handles that only the child should have open. You need to - * make sure that no handles to the write end of the output pipe - * are maintained in this process or else the pipe will not close - * when the child process exits and the ReadFile will hang. */ - - if (!CloseHandle(hChildStdinRd)) - return win32_error("CloseHandle", NULL); + HANDLE hChildStdinRd, hChildStdinWr, hChildStdoutRd, hChildStdoutWr, + hChildStderrRd, hChildStderrWr, hChildStdinWrDup, hChildStdoutRdDup, + hChildStderrRdDup, hProcess; /* hChildStdoutWrDup; */ + + SECURITY_ATTRIBUTES saAttr; + BOOL fSuccess; + int fd1, fd2, fd3; + FILE *f1, *f2, *f3; + long file_count; + PyObject *f; + + saAttr.nLength = sizeof(SECURITY_ATTRIBUTES); + saAttr.bInheritHandle = TRUE; + saAttr.lpSecurityDescriptor = NULL; + + if (!CreatePipe(&hChildStdinRd, &hChildStdinWr, &saAttr, 0)) + return win32_error("CreatePipe", NULL); + + /* Create new output read handle and the input write handle. Set + * the inheritance properties to FALSE. Otherwise, the child inherits + * these handles; resulting in non-closeable handles to the pipes + * being created. */ + fSuccess = DuplicateHandle(GetCurrentProcess(), hChildStdinWr, + GetCurrentProcess(), &hChildStdinWrDup, 0, + FALSE, + DUPLICATE_SAME_ACCESS); + if (!fSuccess) + return win32_error("DuplicateHandle", NULL); + + /* Close the inheritable version of ChildStdin + that we're using. */ + CloseHandle(hChildStdinWr); + + if (!CreatePipe(&hChildStdoutRd, &hChildStdoutWr, &saAttr, 0)) + return win32_error("CreatePipe", NULL); + + fSuccess = DuplicateHandle(GetCurrentProcess(), hChildStdoutRd, + GetCurrentProcess(), &hChildStdoutRdDup, 0, + FALSE, DUPLICATE_SAME_ACCESS); + if (!fSuccess) + return win32_error("DuplicateHandle", NULL); + + /* Close the inheritable version of ChildStdout + that we're using. */ + CloseHandle(hChildStdoutRd); + + if (n != POPEN_4) { + if (!CreatePipe(&hChildStderrRd, &hChildStderrWr, &saAttr, 0)) + return win32_error("CreatePipe", NULL); + fSuccess = DuplicateHandle(GetCurrentProcess(), + hChildStderrRd, + GetCurrentProcess(), + &hChildStderrRdDup, 0, + FALSE, DUPLICATE_SAME_ACCESS); + if (!fSuccess) + return win32_error("DuplicateHandle", NULL); + /* Close the inheritable version of ChildStdErr that we're using. */ + CloseHandle(hChildStderrRd); + } + + switch (n) { + case POPEN_1: + switch (mode & (_O_RDONLY | _O_TEXT | _O_BINARY | _O_WRONLY)) { + case _O_WRONLY | _O_TEXT: + /* Case for writing to child Stdin in text mode. */ + fd1 = _open_osfhandle((Py_intptr_t)hChildStdinWrDup, mode); + f1 = _fdopen(fd1, "w"); + f = PyFile_FromFile(f1, cmdstring, "w", _PyPclose); + PyFile_SetBufSize(f, 0); + /* We don't care about these pipes anymore, so close them. */ + CloseHandle(hChildStdoutRdDup); + CloseHandle(hChildStderrRdDup); + break; + + case _O_RDONLY | _O_TEXT: + /* Case for reading from child Stdout in text mode. */ + fd1 = _open_osfhandle((Py_intptr_t)hChildStdoutRdDup, mode); + f1 = _fdopen(fd1, "r"); + f = PyFile_FromFile(f1, cmdstring, "r", _PyPclose); + PyFile_SetBufSize(f, 0); + /* We don't care about these pipes anymore, so close them. */ + CloseHandle(hChildStdinWrDup); + CloseHandle(hChildStderrRdDup); + break; + + case _O_RDONLY | _O_BINARY: + /* Case for readinig from child Stdout in binary mode. */ + fd1 = _open_osfhandle((Py_intptr_t)hChildStdoutRdDup, mode); + f1 = _fdopen(fd1, "rb"); + f = PyFile_FromFile(f1, cmdstring, "rb", _PyPclose); + PyFile_SetBufSize(f, 0); + /* We don't care about these pipes anymore, so close them. */ + CloseHandle(hChildStdinWrDup); + CloseHandle(hChildStderrRdDup); + break; + + case _O_WRONLY | _O_BINARY: + /* Case for writing to child Stdin in binary mode. */ + fd1 = _open_osfhandle((Py_intptr_t)hChildStdinWrDup, mode); + f1 = _fdopen(fd1, "wb"); + f = PyFile_FromFile(f1, cmdstring, "wb", _PyPclose); + PyFile_SetBufSize(f, 0); + /* We don't care about these pipes anymore, so close them. */ + CloseHandle(hChildStdoutRdDup); + CloseHandle(hChildStderrRdDup); + break; + } + file_count = 1; + break; + + case POPEN_2: + case POPEN_4: + { + char *m1, *m2; + PyObject *p1, *p2; + + if (mode & _O_TEXT) { + m1 = "r"; + m2 = "w"; + } else { + m1 = "rb"; + m2 = "wb"; + } + + fd1 = _open_osfhandle((Py_intptr_t)hChildStdinWrDup, mode); + f1 = _fdopen(fd1, m2); + fd2 = _open_osfhandle((Py_intptr_t)hChildStdoutRdDup, mode); + f2 = _fdopen(fd2, m1); + p1 = PyFile_FromFile(f1, cmdstring, m2, _PyPclose); + PyFile_SetBufSize(p1, 0); + p2 = PyFile_FromFile(f2, cmdstring, m1, _PyPclose); + PyFile_SetBufSize(p2, 0); + + if (n != 4) + CloseHandle(hChildStderrRdDup); + + f = PyTuple_Pack(2,p1,p2); + Py_XDECREF(p1); + Py_XDECREF(p2); + file_count = 2; + break; + } + + case POPEN_3: + { + char *m1, *m2; + PyObject *p1, *p2, *p3; + + if (mode & _O_TEXT) { + m1 = "r"; + m2 = "w"; + } else { + m1 = "rb"; + m2 = "wb"; + } + + fd1 = _open_osfhandle((Py_intptr_t)hChildStdinWrDup, mode); + f1 = _fdopen(fd1, m2); + fd2 = _open_osfhandle((Py_intptr_t)hChildStdoutRdDup, mode); + f2 = _fdopen(fd2, m1); + fd3 = _open_osfhandle((Py_intptr_t)hChildStderrRdDup, mode); + f3 = _fdopen(fd3, m1); + p1 = PyFile_FromFile(f1, cmdstring, m2, _PyPclose); + p2 = PyFile_FromFile(f2, cmdstring, m1, _PyPclose); + p3 = PyFile_FromFile(f3, cmdstring, m1, _PyPclose); + PyFile_SetBufSize(p1, 0); + PyFile_SetBufSize(p2, 0); + PyFile_SetBufSize(p3, 0); + f = PyTuple_Pack(3,p1,p2,p3); + Py_XDECREF(p1); + Py_XDECREF(p2); + Py_XDECREF(p3); + file_count = 3; + break; + } + } + + if (n == POPEN_4) { + if (!_PyPopenCreateProcess(cmdstring, + hChildStdinRd, + hChildStdoutWr, + hChildStdoutWr, + &hProcess)) + return NULL; + } + else { + if (!_PyPopenCreateProcess(cmdstring, + hChildStdinRd, + hChildStdoutWr, + hChildStderrWr, + &hProcess)) + return NULL; + } + + /* + * Insert the files we've created into the process dictionary + * all referencing the list with the process handle and the + * initial number of files (see description below in _PyPclose). + * Since if _PyPclose later tried to wait on a process when all + * handles weren't closed, it could create a deadlock with the + * child, we spend some energy here to try to ensure that we + * either insert all file handles into the dictionary or none + * at all. It's a little clumsy with the various popen modes + * and variable number of files involved. + */ + if (!_PyPopenProcs) { + _PyPopenProcs = PyDict_New(); + } + + if (_PyPopenProcs) { + PyObject *procObj, *hProcessObj, *intObj, *fileObj[3]; + int ins_rc[3]; + + fileObj[0] = fileObj[1] = fileObj[2] = NULL; + ins_rc[0] = ins_rc[1] = ins_rc[2] = 0; + + procObj = PyList_New(2); + hProcessObj = PyLong_FromVoidPtr(hProcess); + intObj = PyInt_FromLong(file_count); + + if (procObj && hProcessObj && intObj) { + PyList_SetItem(procObj,0,hProcessObj); + PyList_SetItem(procObj,1,intObj); + + fileObj[0] = PyLong_FromVoidPtr(f1); + if (fileObj[0]) { + ins_rc[0] = PyDict_SetItem(_PyPopenProcs, + fileObj[0], + procObj); + } + if (file_count >= 2) { + fileObj[1] = PyLong_FromVoidPtr(f2); + if (fileObj[1]) { + ins_rc[1] = PyDict_SetItem(_PyPopenProcs, + fileObj[1], + procObj); + } + } + if (file_count >= 3) { + fileObj[2] = PyLong_FromVoidPtr(f3); + if (fileObj[2]) { + ins_rc[2] = PyDict_SetItem(_PyPopenProcs, + fileObj[2], + procObj); + } + } + + if (ins_rc[0] < 0 || !fileObj[0] || + ins_rc[1] < 0 || (file_count > 1 && !fileObj[1]) || + ins_rc[2] < 0 || (file_count > 2 && !fileObj[2])) { + /* Something failed - remove any dictionary + * entries that did make it. + */ + if (!ins_rc[0] && fileObj[0]) { + PyDict_DelItem(_PyPopenProcs, + fileObj[0]); + } + if (!ins_rc[1] && fileObj[1]) { + PyDict_DelItem(_PyPopenProcs, + fileObj[1]); + } + if (!ins_rc[2] && fileObj[2]) { + PyDict_DelItem(_PyPopenProcs, + fileObj[2]); + } + } + } + + /* + * Clean up our localized references for the dictionary keys + * and value since PyDict_SetItem will Py_INCREF any copies + * that got placed in the dictionary. + */ + Py_XDECREF(procObj); + Py_XDECREF(fileObj[0]); + Py_XDECREF(fileObj[1]); + Py_XDECREF(fileObj[2]); + } + + /* Child is launched. Close the parents copy of those pipe + * handles that only the child should have open. You need to + * make sure that no handles to the write end of the output pipe + * are maintained in this process or else the pipe will not close + * when the child process exits and the ReadFile will hang. */ + + if (!CloseHandle(hChildStdinRd)) + return win32_error("CloseHandle", NULL); - if (!CloseHandle(hChildStdoutWr)) - return win32_error("CloseHandle", NULL); + if (!CloseHandle(hChildStdoutWr)) + return win32_error("CloseHandle", NULL); - if ((n != 4) && (!CloseHandle(hChildStderrWr))) - return win32_error("CloseHandle", NULL); + if ((n != 4) && (!CloseHandle(hChildStderrWr))) + return win32_error("CloseHandle", NULL); - return f; + return f; } /* @@ -5503,110 +5503,110 @@ static int _PyPclose(FILE *file) { - int result; - DWORD exit_code; - HANDLE hProcess; - PyObject *procObj, *hProcessObj, *intObj, *fileObj; - long file_count; + int result; + DWORD exit_code; + HANDLE hProcess; + PyObject *procObj, *hProcessObj, *intObj, *fileObj; + long file_count; #ifdef WITH_THREAD - PyGILState_STATE state; + PyGILState_STATE state; #endif - /* Close the file handle first, to ensure it can't block the - * child from exiting if it's the last handle. - */ - result = fclose(file); + /* Close the file handle first, to ensure it can't block the + * child from exiting if it's the last handle. + */ + result = fclose(file); #ifdef WITH_THREAD - state = PyGILState_Ensure(); + state = PyGILState_Ensure(); #endif - if (_PyPopenProcs) { - if ((fileObj = PyLong_FromVoidPtr(file)) != NULL && - (procObj = PyDict_GetItem(_PyPopenProcs, - fileObj)) != NULL && - (hProcessObj = PyList_GetItem(procObj,0)) != NULL && - (intObj = PyList_GetItem(procObj,1)) != NULL) { - - hProcess = PyLong_AsVoidPtr(hProcessObj); - file_count = PyInt_AsLong(intObj); - - if (file_count > 1) { - /* Still other files referencing process */ - file_count--; - PyList_SetItem(procObj,1, - PyInt_FromLong(file_count)); - } else { - /* Last file for this process */ - if (result != EOF && - WaitForSingleObject(hProcess, INFINITE) != WAIT_FAILED && - GetExitCodeProcess(hProcess, &exit_code)) { - /* Possible truncation here in 16-bit environments, but - * real exit codes are just the lower byte in any event. - */ - result = exit_code; - } else { - /* Indicate failure - this will cause the file object - * to raise an I/O error and translate the last Win32 - * error code from errno. We do have a problem with - * last errors that overlap the normal errno table, - * but that's a consistent problem with the file object. - */ - if (result != EOF) { - /* If the error wasn't from the fclose(), then - * set errno for the file object error handling. - */ - errno = GetLastError(); - } - result = -1; - } - - /* Free up the native handle at this point */ - CloseHandle(hProcess); - } - - /* Remove this file pointer from dictionary */ - PyDict_DelItem(_PyPopenProcs, fileObj); - - if (PyDict_Size(_PyPopenProcs) == 0) { - Py_DECREF(_PyPopenProcs); - _PyPopenProcs = NULL; - } + if (_PyPopenProcs) { + if ((fileObj = PyLong_FromVoidPtr(file)) != NULL && + (procObj = PyDict_GetItem(_PyPopenProcs, + fileObj)) != NULL && + (hProcessObj = PyList_GetItem(procObj,0)) != NULL && + (intObj = PyList_GetItem(procObj,1)) != NULL) { + + hProcess = PyLong_AsVoidPtr(hProcessObj); + file_count = PyInt_AsLong(intObj); + + if (file_count > 1) { + /* Still other files referencing process */ + file_count--; + PyList_SetItem(procObj,1, + PyInt_FromLong(file_count)); + } else { + /* Last file for this process */ + if (result != EOF && + WaitForSingleObject(hProcess, INFINITE) != WAIT_FAILED && + GetExitCodeProcess(hProcess, &exit_code)) { + /* Possible truncation here in 16-bit environments, but + * real exit codes are just the lower byte in any event. + */ + result = exit_code; + } else { + /* Indicate failure - this will cause the file object + * to raise an I/O error and translate the last Win32 + * error code from errno. We do have a problem with + * last errors that overlap the normal errno table, + * but that's a consistent problem with the file object. + */ + if (result != EOF) { + /* If the error wasn't from the fclose(), then + * set errno for the file object error handling. + */ + errno = GetLastError(); + } + result = -1; + } - } /* if object retrieval ok */ + /* Free up the native handle at this point */ + CloseHandle(hProcess); + } - Py_XDECREF(fileObj); - } /* if _PyPopenProcs */ + /* Remove this file pointer from dictionary */ + PyDict_DelItem(_PyPopenProcs, fileObj); + + if (PyDict_Size(_PyPopenProcs) == 0) { + Py_DECREF(_PyPopenProcs); + _PyPopenProcs = NULL; + } + + } /* if object retrieval ok */ + + Py_XDECREF(fileObj); + } /* if _PyPopenProcs */ #ifdef WITH_THREAD - PyGILState_Release(state); + PyGILState_Release(state); #endif - return result; + return result; } #else /* which OS? */ static PyObject * posix_popen(PyObject *self, PyObject *args) { - char *name; - char *mode = "r"; - int bufsize = -1; - FILE *fp; - PyObject *f; - if (!PyArg_ParseTuple(args, "s|si:popen", &name, &mode, &bufsize)) - return NULL; - /* Strip mode of binary or text modifiers */ - if (strcmp(mode, "rb") == 0 || strcmp(mode, "rt") == 0) - mode = "r"; - else if (strcmp(mode, "wb") == 0 || strcmp(mode, "wt") == 0) - mode = "w"; - Py_BEGIN_ALLOW_THREADS - fp = popen(name, mode); - Py_END_ALLOW_THREADS - if (fp == NULL) - return posix_error(); - f = PyFile_FromFile(fp, name, mode, pclose); - if (f != NULL) - PyFile_SetBufSize(f, bufsize); - return f; + char *name; + char *mode = "r"; + int bufsize = -1; + FILE *fp; + PyObject *f; + if (!PyArg_ParseTuple(args, "s|si:popen", &name, &mode, &bufsize)) + return NULL; + /* Strip mode of binary or text modifiers */ + if (strcmp(mode, "rb") == 0 || strcmp(mode, "rt") == 0) + mode = "r"; + else if (strcmp(mode, "wb") == 0 || strcmp(mode, "wt") == 0) + mode = "w"; + Py_BEGIN_ALLOW_THREADS + fp = popen(name, mode); + Py_END_ALLOW_THREADS + if (fp == NULL) + return posix_error(); + f = PyFile_FromFile(fp, name, mode, pclose); + if (f != NULL) + PyFile_SetBufSize(f, bufsize); + return f; } #endif /* PYOS_??? */ @@ -5621,19 +5621,19 @@ static PyObject * posix_setuid(PyObject *self, PyObject *args) { - long uid_arg; - uid_t uid; - if (!PyArg_ParseTuple(args, "l:setuid", &uid_arg)) - return NULL; - uid = uid_arg; - if (uid != uid_arg) { - PyErr_SetString(PyExc_OverflowError, "user id too big"); - return NULL; - } - if (setuid(uid) < 0) - return posix_error(); - Py_INCREF(Py_None); - return Py_None; + long uid_arg; + uid_t uid; + if (!PyArg_ParseTuple(args, "l:setuid", &uid_arg)) + return NULL; + uid = uid_arg; + if (uid != uid_arg) { + PyErr_SetString(PyExc_OverflowError, "user id too big"); + return NULL; + } + if (setuid(uid) < 0) + return posix_error(); + Py_INCREF(Py_None); + return Py_None; } #endif /* HAVE_SETUID */ @@ -5646,21 +5646,21 @@ static PyObject * posix_seteuid (PyObject *self, PyObject *args) { - long euid_arg; - uid_t euid; - if (!PyArg_ParseTuple(args, "l", &euid_arg)) - return NULL; - euid = euid_arg; - if (euid != euid_arg) { - PyErr_SetString(PyExc_OverflowError, "user id too big"); - return NULL; - } - if (seteuid(euid) < 0) { - return posix_error(); - } else { - Py_INCREF(Py_None); - return Py_None; - } + long euid_arg; + uid_t euid; + if (!PyArg_ParseTuple(args, "l", &euid_arg)) + return NULL; + euid = euid_arg; + if (euid != euid_arg) { + PyErr_SetString(PyExc_OverflowError, "user id too big"); + return NULL; + } + if (seteuid(euid) < 0) { + return posix_error(); + } else { + Py_INCREF(Py_None); + return Py_None; + } } #endif /* HAVE_SETEUID */ @@ -5672,21 +5672,21 @@ static PyObject * posix_setegid (PyObject *self, PyObject *args) { - long egid_arg; - gid_t egid; - if (!PyArg_ParseTuple(args, "l", &egid_arg)) - return NULL; - egid = egid_arg; - if (egid != egid_arg) { - PyErr_SetString(PyExc_OverflowError, "group id too big"); - return NULL; - } - if (setegid(egid) < 0) { - return posix_error(); - } else { - Py_INCREF(Py_None); - return Py_None; - } + long egid_arg; + gid_t egid; + if (!PyArg_ParseTuple(args, "l", &egid_arg)) + return NULL; + egid = egid_arg; + if (egid != egid_arg) { + PyErr_SetString(PyExc_OverflowError, "group id too big"); + return NULL; + } + if (setegid(egid) < 0) { + return posix_error(); + } else { + Py_INCREF(Py_None); + return Py_None; + } } #endif /* HAVE_SETEGID */ @@ -5698,29 +5698,29 @@ static PyObject * posix_setreuid (PyObject *self, PyObject *args) { - long ruid_arg, euid_arg; - uid_t ruid, euid; - if (!PyArg_ParseTuple(args, "ll", &ruid_arg, &euid_arg)) - return NULL; - if (ruid_arg == -1) - ruid = (uid_t)-1; /* let the compiler choose how -1 fits */ - else - ruid = ruid_arg; /* otherwise, assign from our long */ - if (euid_arg == -1) - euid = (uid_t)-1; - else - euid = euid_arg; - if ((euid_arg != -1 && euid != euid_arg) || - (ruid_arg != -1 && ruid != ruid_arg)) { - PyErr_SetString(PyExc_OverflowError, "user id too big"); - return NULL; - } - if (setreuid(ruid, euid) < 0) { - return posix_error(); - } else { - Py_INCREF(Py_None); - return Py_None; - } + long ruid_arg, euid_arg; + uid_t ruid, euid; + if (!PyArg_ParseTuple(args, "ll", &ruid_arg, &euid_arg)) + return NULL; + if (ruid_arg == -1) + ruid = (uid_t)-1; /* let the compiler choose how -1 fits */ + else + ruid = ruid_arg; /* otherwise, assign from our long */ + if (euid_arg == -1) + euid = (uid_t)-1; + else + euid = euid_arg; + if ((euid_arg != -1 && euid != euid_arg) || + (ruid_arg != -1 && ruid != ruid_arg)) { + PyErr_SetString(PyExc_OverflowError, "user id too big"); + return NULL; + } + if (setreuid(ruid, euid) < 0) { + return posix_error(); + } else { + Py_INCREF(Py_None); + return Py_None; + } } #endif /* HAVE_SETREUID */ @@ -5732,29 +5732,29 @@ static PyObject * posix_setregid (PyObject *self, PyObject *args) { - long rgid_arg, egid_arg; - gid_t rgid, egid; - if (!PyArg_ParseTuple(args, "ll", &rgid_arg, &egid_arg)) - return NULL; - if (rgid_arg == -1) - rgid = (gid_t)-1; /* let the compiler choose how -1 fits */ - else - rgid = rgid_arg; /* otherwise, assign from our long */ - if (egid_arg == -1) - egid = (gid_t)-1; - else - egid = egid_arg; - if ((egid_arg != -1 && egid != egid_arg) || - (rgid_arg != -1 && rgid != rgid_arg)) { - PyErr_SetString(PyExc_OverflowError, "group id too big"); - return NULL; - } - if (setregid(rgid, egid) < 0) { - return posix_error(); - } else { - Py_INCREF(Py_None); - return Py_None; - } + long rgid_arg, egid_arg; + gid_t rgid, egid; + if (!PyArg_ParseTuple(args, "ll", &rgid_arg, &egid_arg)) + return NULL; + if (rgid_arg == -1) + rgid = (gid_t)-1; /* let the compiler choose how -1 fits */ + else + rgid = rgid_arg; /* otherwise, assign from our long */ + if (egid_arg == -1) + egid = (gid_t)-1; + else + egid = egid_arg; + if ((egid_arg != -1 && egid != egid_arg) || + (rgid_arg != -1 && rgid != rgid_arg)) { + PyErr_SetString(PyExc_OverflowError, "group id too big"); + return NULL; + } + if (setregid(rgid, egid) < 0) { + return posix_error(); + } else { + Py_INCREF(Py_None); + return Py_None; + } } #endif /* HAVE_SETREGID */ @@ -5766,19 +5766,19 @@ static PyObject * posix_setgid(PyObject *self, PyObject *args) { - long gid_arg; - gid_t gid; - if (!PyArg_ParseTuple(args, "l:setgid", &gid_arg)) - return NULL; - gid = gid_arg; - if (gid != gid_arg) { - PyErr_SetString(PyExc_OverflowError, "group id too big"); - return NULL; - } - if (setgid(gid) < 0) - return posix_error(); - Py_INCREF(Py_None); - return Py_None; + long gid_arg; + gid_t gid; + if (!PyArg_ParseTuple(args, "l:setgid", &gid_arg)) + return NULL; + gid = gid_arg; + if (gid != gid_arg) { + PyErr_SetString(PyExc_OverflowError, "group id too big"); + return NULL; + } + if (setgid(gid) < 0) + return posix_error(); + Py_INCREF(Py_None); + return Py_None; } #endif /* HAVE_SETGID */ @@ -5790,63 +5790,63 @@ static PyObject * posix_setgroups(PyObject *self, PyObject *groups) { - int i, len; - gid_t grouplist[MAX_GROUPS]; + int i, len; + gid_t grouplist[MAX_GROUPS]; + + if (!PySequence_Check(groups)) { + PyErr_SetString(PyExc_TypeError, "setgroups argument must be a sequence"); + return NULL; + } + len = PySequence_Size(groups); + if (len > MAX_GROUPS) { + PyErr_SetString(PyExc_ValueError, "too many groups"); + return NULL; + } + for(i = 0; i < len; i++) { + PyObject *elem; + elem = PySequence_GetItem(groups, i); + if (!elem) + return NULL; + if (!PyInt_Check(elem)) { + if (!PyLong_Check(elem)) { + PyErr_SetString(PyExc_TypeError, + "groups must be integers"); + Py_DECREF(elem); + return NULL; + } else { + unsigned long x = PyLong_AsUnsignedLong(elem); + if (PyErr_Occurred()) { + PyErr_SetString(PyExc_TypeError, + "group id too big"); + Py_DECREF(elem); + return NULL; + } + grouplist[i] = x; + /* read back to see if it fits in gid_t */ + if (grouplist[i] != x) { + PyErr_SetString(PyExc_TypeError, + "group id too big"); + Py_DECREF(elem); + return NULL; + } + } + } else { + long x = PyInt_AsLong(elem); + grouplist[i] = x; + if (grouplist[i] != x) { + PyErr_SetString(PyExc_TypeError, + "group id too big"); + Py_DECREF(elem); + return NULL; + } + } + Py_DECREF(elem); + } - if (!PySequence_Check(groups)) { - PyErr_SetString(PyExc_TypeError, "setgroups argument must be a sequence"); - return NULL; - } - len = PySequence_Size(groups); - if (len > MAX_GROUPS) { - PyErr_SetString(PyExc_ValueError, "too many groups"); - return NULL; - } - for(i = 0; i < len; i++) { - PyObject *elem; - elem = PySequence_GetItem(groups, i); - if (!elem) - return NULL; - if (!PyInt_Check(elem)) { - if (!PyLong_Check(elem)) { - PyErr_SetString(PyExc_TypeError, - "groups must be integers"); - Py_DECREF(elem); - return NULL; - } else { - unsigned long x = PyLong_AsUnsignedLong(elem); - if (PyErr_Occurred()) { - PyErr_SetString(PyExc_TypeError, - "group id too big"); - Py_DECREF(elem); - return NULL; - } - grouplist[i] = x; - /* read back to see if it fits in gid_t */ - if (grouplist[i] != x) { - PyErr_SetString(PyExc_TypeError, - "group id too big"); - Py_DECREF(elem); - return NULL; - } - } - } else { - long x = PyInt_AsLong(elem); - grouplist[i] = x; - if (grouplist[i] != x) { - PyErr_SetString(PyExc_TypeError, - "group id too big"); - Py_DECREF(elem); - return NULL; - } - } - Py_DECREF(elem); - } - - if (setgroups(len, grouplist) < 0) - return posix_error(); - Py_INCREF(Py_None); - return Py_None; + if (setgroups(len, grouplist) < 0) + return posix_error(); + Py_INCREF(Py_None); + return Py_None; } #endif /* HAVE_SETGROUPS */ @@ -5854,59 +5854,59 @@ static PyObject * wait_helper(pid_t pid, int status, struct rusage *ru) { - PyObject *result; - static PyObject *struct_rusage; + PyObject *result; + static PyObject *struct_rusage; + + if (pid == -1) + return posix_error(); - if (pid == -1) - return posix_error(); + if (struct_rusage == NULL) { + PyObject *m = PyImport_ImportModuleNoBlock("resource"); + if (m == NULL) + return NULL; + struct_rusage = PyObject_GetAttrString(m, "struct_rusage"); + Py_DECREF(m); + if (struct_rusage == NULL) + return NULL; + } - if (struct_rusage == NULL) { - PyObject *m = PyImport_ImportModuleNoBlock("resource"); - if (m == NULL) - return NULL; - struct_rusage = PyObject_GetAttrString(m, "struct_rusage"); - Py_DECREF(m); - if (struct_rusage == NULL) - return NULL; - } - - /* XXX(nnorwitz): Copied (w/mods) from resource.c, there should be only one. */ - result = PyStructSequence_New((PyTypeObject*) struct_rusage); - if (!result) - return NULL; + /* XXX(nnorwitz): Copied (w/mods) from resource.c, there should be only one. */ + result = PyStructSequence_New((PyTypeObject*) struct_rusage); + if (!result) + return NULL; #ifndef doubletime #define doubletime(TV) ((double)(TV).tv_sec + (TV).tv_usec * 0.000001) #endif - PyStructSequence_SET_ITEM(result, 0, - PyFloat_FromDouble(doubletime(ru->ru_utime))); - PyStructSequence_SET_ITEM(result, 1, - PyFloat_FromDouble(doubletime(ru->ru_stime))); + PyStructSequence_SET_ITEM(result, 0, + PyFloat_FromDouble(doubletime(ru->ru_utime))); + PyStructSequence_SET_ITEM(result, 1, + PyFloat_FromDouble(doubletime(ru->ru_stime))); #define SET_INT(result, index, value)\ - PyStructSequence_SET_ITEM(result, index, PyInt_FromLong(value)) - SET_INT(result, 2, ru->ru_maxrss); - SET_INT(result, 3, ru->ru_ixrss); - SET_INT(result, 4, ru->ru_idrss); - SET_INT(result, 5, ru->ru_isrss); - SET_INT(result, 6, ru->ru_minflt); - SET_INT(result, 7, ru->ru_majflt); - SET_INT(result, 8, ru->ru_nswap); - SET_INT(result, 9, ru->ru_inblock); - SET_INT(result, 10, ru->ru_oublock); - SET_INT(result, 11, ru->ru_msgsnd); - SET_INT(result, 12, ru->ru_msgrcv); - SET_INT(result, 13, ru->ru_nsignals); - SET_INT(result, 14, ru->ru_nvcsw); - SET_INT(result, 15, ru->ru_nivcsw); + PyStructSequence_SET_ITEM(result, index, PyInt_FromLong(value)) + SET_INT(result, 2, ru->ru_maxrss); + SET_INT(result, 3, ru->ru_ixrss); + SET_INT(result, 4, ru->ru_idrss); + SET_INT(result, 5, ru->ru_isrss); + SET_INT(result, 6, ru->ru_minflt); + SET_INT(result, 7, ru->ru_majflt); + SET_INT(result, 8, ru->ru_nswap); + SET_INT(result, 9, ru->ru_inblock); + SET_INT(result, 10, ru->ru_oublock); + SET_INT(result, 11, ru->ru_msgsnd); + SET_INT(result, 12, ru->ru_msgrcv); + SET_INT(result, 13, ru->ru_nsignals); + SET_INT(result, 14, ru->ru_nvcsw); + SET_INT(result, 15, ru->ru_nivcsw); #undef SET_INT - if (PyErr_Occurred()) { - Py_DECREF(result); - return NULL; - } + if (PyErr_Occurred()) { + Py_DECREF(result); + return NULL; + } - return Py_BuildValue("NiN", PyLong_FromPid(pid), status, result); + return Py_BuildValue("NiN", PyLong_FromPid(pid), status, result); } #endif /* HAVE_WAIT3 || HAVE_WAIT4 */ @@ -5918,20 +5918,20 @@ static PyObject * posix_wait3(PyObject *self, PyObject *args) { - pid_t pid; - int options; - struct rusage ru; - WAIT_TYPE status; - WAIT_STATUS_INT(status) = 0; - - if (!PyArg_ParseTuple(args, "i:wait3", &options)) - return NULL; - - Py_BEGIN_ALLOW_THREADS - pid = wait3(&status, options, &ru); - Py_END_ALLOW_THREADS + pid_t pid; + int options; + struct rusage ru; + WAIT_TYPE status; + WAIT_STATUS_INT(status) = 0; + + if (!PyArg_ParseTuple(args, "i:wait3", &options)) + return NULL; + + Py_BEGIN_ALLOW_THREADS + pid = wait3(&status, options, &ru); + Py_END_ALLOW_THREADS - return wait_helper(pid, WAIT_STATUS_INT(status), &ru); + return wait_helper(pid, WAIT_STATUS_INT(status), &ru); } #endif /* HAVE_WAIT3 */ @@ -5943,20 +5943,20 @@ static PyObject * posix_wait4(PyObject *self, PyObject *args) { - pid_t pid; - int options; - struct rusage ru; - WAIT_TYPE status; - WAIT_STATUS_INT(status) = 0; - - if (!PyArg_ParseTuple(args, PARSE_PID "i:wait4", &pid, &options)) - return NULL; - - Py_BEGIN_ALLOW_THREADS - pid = wait4(pid, &status, options, &ru); - Py_END_ALLOW_THREADS + pid_t pid; + int options; + struct rusage ru; + WAIT_TYPE status; + WAIT_STATUS_INT(status) = 0; + + if (!PyArg_ParseTuple(args, PARSE_PID "i:wait4", &pid, &options)) + return NULL; + + Py_BEGIN_ALLOW_THREADS + pid = wait4(pid, &status, options, &ru); + Py_END_ALLOW_THREADS - return wait_helper(pid, WAIT_STATUS_INT(status), &ru); + return wait_helper(pid, WAIT_STATUS_INT(status), &ru); } #endif /* HAVE_WAIT4 */ @@ -5968,20 +5968,20 @@ static PyObject * posix_waitpid(PyObject *self, PyObject *args) { - pid_t pid; - int options; - WAIT_TYPE status; - WAIT_STATUS_INT(status) = 0; - - if (!PyArg_ParseTuple(args, PARSE_PID "i:waitpid", &pid, &options)) - return NULL; - Py_BEGIN_ALLOW_THREADS - pid = waitpid(pid, &status, options); - Py_END_ALLOW_THREADS - if (pid == -1) - return posix_error(); + pid_t pid; + int options; + WAIT_TYPE status; + WAIT_STATUS_INT(status) = 0; + + if (!PyArg_ParseTuple(args, PARSE_PID "i:waitpid", &pid, &options)) + return NULL; + Py_BEGIN_ALLOW_THREADS + pid = waitpid(pid, &status, options); + Py_END_ALLOW_THREADS + if (pid == -1) + return posix_error(); - return Py_BuildValue("Ni", PyLong_FromPid(pid), WAIT_STATUS_INT(status)); + return Py_BuildValue("Ni", PyLong_FromPid(pid), WAIT_STATUS_INT(status)); } #elif defined(HAVE_CWAIT) @@ -5994,19 +5994,19 @@ static PyObject * posix_waitpid(PyObject *self, PyObject *args) { - Py_intptr_t pid; - int status, options; + Py_intptr_t pid; + int status, options; - if (!PyArg_ParseTuple(args, PARSE_PID "i:waitpid", &pid, &options)) - return NULL; - Py_BEGIN_ALLOW_THREADS - pid = _cwait(&status, pid, options); - Py_END_ALLOW_THREADS - if (pid == -1) - return posix_error(); + if (!PyArg_ParseTuple(args, PARSE_PID "i:waitpid", &pid, &options)) + return NULL; + Py_BEGIN_ALLOW_THREADS + pid = _cwait(&status, pid, options); + Py_END_ALLOW_THREADS + if (pid == -1) + return posix_error(); - /* shift the status left a byte so this is more like the POSIX waitpid */ - return Py_BuildValue("Ni", PyLong_FromPid(pid), status << 8); + /* shift the status left a byte so this is more like the POSIX waitpid */ + return Py_BuildValue("Ni", PyLong_FromPid(pid), status << 8); } #endif /* HAVE_WAITPID || HAVE_CWAIT */ @@ -6018,17 +6018,17 @@ static PyObject * posix_wait(PyObject *self, PyObject *noargs) { - pid_t pid; - WAIT_TYPE status; - WAIT_STATUS_INT(status) = 0; - - Py_BEGIN_ALLOW_THREADS - pid = wait(&status); - Py_END_ALLOW_THREADS - if (pid == -1) - return posix_error(); + pid_t pid; + WAIT_TYPE status; + WAIT_STATUS_INT(status) = 0; + + Py_BEGIN_ALLOW_THREADS + pid = wait(&status); + Py_END_ALLOW_THREADS + if (pid == -1) + return posix_error(); - return Py_BuildValue("Ni", PyLong_FromPid(pid), WAIT_STATUS_INT(status)); + return Py_BuildValue("Ni", PyLong_FromPid(pid), WAIT_STATUS_INT(status)); } #endif @@ -6041,12 +6041,12 @@ posix_lstat(PyObject *self, PyObject *args) { #ifdef HAVE_LSTAT - return posix_do_stat(self, args, "et:lstat", lstat, NULL, NULL); + return posix_do_stat(self, args, "et:lstat", lstat, NULL, NULL); #else /* !HAVE_LSTAT */ #ifdef MS_WINDOWS - return posix_do_stat(self, args, "et:lstat", STAT, "U:lstat", win32_wstat); + return posix_do_stat(self, args, "et:lstat", STAT, "U:lstat", win32_wstat); #else - return posix_do_stat(self, args, "et:lstat", STAT, NULL, NULL); + return posix_do_stat(self, args, "et:lstat", STAT, NULL, NULL); #endif #endif /* !HAVE_LSTAT */ } @@ -6060,57 +6060,57 @@ static PyObject * posix_readlink(PyObject *self, PyObject *args) { - PyObject* v; - char buf[MAXPATHLEN]; - char *path; - int n; + PyObject* v; + char buf[MAXPATHLEN]; + char *path; + int n; #ifdef Py_USING_UNICODE - int arg_is_unicode = 0; + int arg_is_unicode = 0; #endif - if (!PyArg_ParseTuple(args, "et:readlink", - Py_FileSystemDefaultEncoding, &path)) - return NULL; + if (!PyArg_ParseTuple(args, "et:readlink", + Py_FileSystemDefaultEncoding, &path)) + return NULL; #ifdef Py_USING_UNICODE - v = PySequence_GetItem(args, 0); - if (v == NULL) { - PyMem_Free(path); - return NULL; - } - - if (PyUnicode_Check(v)) { - arg_is_unicode = 1; - } - Py_DECREF(v); -#endif - - Py_BEGIN_ALLOW_THREADS - n = readlink(path, buf, (int) sizeof buf); - Py_END_ALLOW_THREADS - if (n < 0) - return posix_error_with_allocated_filename(path); + v = PySequence_GetItem(args, 0); + if (v == NULL) { + PyMem_Free(path); + return NULL; + } + + if (PyUnicode_Check(v)) { + arg_is_unicode = 1; + } + Py_DECREF(v); +#endif + + Py_BEGIN_ALLOW_THREADS + n = readlink(path, buf, (int) sizeof buf); + Py_END_ALLOW_THREADS + if (n < 0) + return posix_error_with_allocated_filename(path); - PyMem_Free(path); - v = PyString_FromStringAndSize(buf, n); + PyMem_Free(path); + v = PyString_FromStringAndSize(buf, n); #ifdef Py_USING_UNICODE - if (arg_is_unicode) { - PyObject *w; + if (arg_is_unicode) { + PyObject *w; - w = PyUnicode_FromEncodedObject(v, - Py_FileSystemDefaultEncoding, - "strict"); - if (w != NULL) { - Py_DECREF(v); - v = w; - } - else { - /* fall back to the original byte string, as - discussed in patch #683592 */ - PyErr_Clear(); - } - } + w = PyUnicode_FromEncodedObject(v, + Py_FileSystemDefaultEncoding, + "strict"); + if (w != NULL) { + Py_DECREF(v); + v = w; + } + else { + /* fall back to the original byte string, as + discussed in patch #683592 */ + PyErr_Clear(); + } + } #endif - return v; + return v; } #endif /* HAVE_READLINK */ @@ -6123,7 +6123,7 @@ static PyObject * posix_symlink(PyObject *self, PyObject *args) { - return posix_2str(args, "etet:symlink", symlink); + return posix_2str(args, "etet:symlink", symlink); } #endif /* HAVE_SYMLINK */ @@ -6146,12 +6146,12 @@ posix_times(PyObject *self, PyObject *noargs) { /* Currently Only Uptime is Provided -- Others Later */ - return Py_BuildValue("ddddd", - (double)0 /* t.tms_utime / HZ */, - (double)0 /* t.tms_stime / HZ */, - (double)0 /* t.tms_cutime / HZ */, - (double)0 /* t.tms_cstime / HZ */, - (double)system_uptime() / 1000); + return Py_BuildValue("ddddd", + (double)0 /* t.tms_utime / HZ */, + (double)0 /* t.tms_stime / HZ */, + (double)0 /* t.tms_cutime / HZ */, + (double)0 /* t.tms_cstime / HZ */, + (double)system_uptime() / 1000); } #else /* not OS2 */ #define NEED_TICKS_PER_SECOND @@ -6159,46 +6159,46 @@ static PyObject * posix_times(PyObject *self, PyObject *noargs) { - struct tms t; - clock_t c; - errno = 0; - c = times(&t); - if (c == (clock_t) -1) - return posix_error(); - return Py_BuildValue("ddddd", - (double)t.tms_utime / ticks_per_second, - (double)t.tms_stime / ticks_per_second, - (double)t.tms_cutime / ticks_per_second, - (double)t.tms_cstime / ticks_per_second, - (double)c / ticks_per_second); + struct tms t; + clock_t c; + errno = 0; + c = times(&t); + if (c == (clock_t) -1) + return posix_error(); + return Py_BuildValue("ddddd", + (double)t.tms_utime / ticks_per_second, + (double)t.tms_stime / ticks_per_second, + (double)t.tms_cutime / ticks_per_second, + (double)t.tms_cstime / ticks_per_second, + (double)c / ticks_per_second); } #endif /* not OS2 */ #endif /* HAVE_TIMES */ #ifdef MS_WINDOWS -#define HAVE_TIMES /* so the method table will pick it up */ +#define HAVE_TIMES /* so the method table will pick it up */ static PyObject * posix_times(PyObject *self, PyObject *noargs) { - FILETIME create, exit, kernel, user; - HANDLE hProc; - hProc = GetCurrentProcess(); - GetProcessTimes(hProc, &create, &exit, &kernel, &user); - /* The fields of a FILETIME structure are the hi and lo part - of a 64-bit value expressed in 100 nanosecond units. - 1e7 is one second in such units; 1e-7 the inverse. - 429.4967296 is 2**32 / 1e7 or 2**32 * 1e-7. - */ - return Py_BuildValue( - "ddddd", - (double)(user.dwHighDateTime*429.4967296 + - user.dwLowDateTime*1e-7), - (double)(kernel.dwHighDateTime*429.4967296 + - kernel.dwLowDateTime*1e-7), - (double)0, - (double)0, - (double)0); + FILETIME create, exit, kernel, user; + HANDLE hProc; + hProc = GetCurrentProcess(); + GetProcessTimes(hProc, &create, &exit, &kernel, &user); + /* The fields of a FILETIME structure are the hi and lo part + of a 64-bit value expressed in 100 nanosecond units. + 1e7 is one second in such units; 1e-7 the inverse. + 429.4967296 is 2**32 / 1e7 or 2**32 * 1e-7. + */ + return Py_BuildValue( + "ddddd", + (double)(user.dwHighDateTime*429.4967296 + + user.dwLowDateTime*1e-7), + (double)(kernel.dwHighDateTime*429.4967296 + + kernel.dwLowDateTime*1e-7), + (double)0, + (double)0, + (double)0); } #endif /* MS_WINDOWS */ @@ -6217,14 +6217,14 @@ static PyObject * posix_getsid(PyObject *self, PyObject *args) { - pid_t pid; - int sid; - if (!PyArg_ParseTuple(args, PARSE_PID ":getsid", &pid)) - return NULL; - sid = getsid(pid); - if (sid < 0) - return posix_error(); - return PyInt_FromLong((long)sid); + pid_t pid; + int sid; + if (!PyArg_ParseTuple(args, PARSE_PID ":getsid", &pid)) + return NULL; + sid = getsid(pid); + if (sid < 0) + return posix_error(); + return PyInt_FromLong((long)sid); } #endif /* HAVE_GETSID */ @@ -6237,10 +6237,10 @@ static PyObject * posix_setsid(PyObject *self, PyObject *noargs) { - if (setsid() < 0) - return posix_error(); - Py_INCREF(Py_None); - return Py_None; + if (setsid() < 0) + return posix_error(); + Py_INCREF(Py_None); + return Py_None; } #endif /* HAVE_SETSID */ @@ -6252,14 +6252,14 @@ static PyObject * posix_setpgid(PyObject *self, PyObject *args) { - pid_t pid; - int pgrp; - if (!PyArg_ParseTuple(args, PARSE_PID "i:setpgid", &pid, &pgrp)) - return NULL; - if (setpgid(pid, pgrp) < 0) - return posix_error(); - Py_INCREF(Py_None); - return Py_None; + pid_t pid; + int pgrp; + if (!PyArg_ParseTuple(args, PARSE_PID "i:setpgid", &pid, &pgrp)) + return NULL; + if (setpgid(pid, pgrp) < 0) + return posix_error(); + Py_INCREF(Py_None); + return Py_None; } #endif /* HAVE_SETPGID */ @@ -6272,14 +6272,14 @@ static PyObject * posix_tcgetpgrp(PyObject *self, PyObject *args) { - int fd; - pid_t pgid; - if (!PyArg_ParseTuple(args, "i:tcgetpgrp", &fd)) - return NULL; - pgid = tcgetpgrp(fd); - if (pgid < 0) - return posix_error(); - return PyLong_FromPid(pgid); + int fd; + pid_t pgid; + if (!PyArg_ParseTuple(args, "i:tcgetpgrp", &fd)) + return NULL; + pgid = tcgetpgrp(fd); + if (pgid < 0) + return posix_error(); + return PyLong_FromPid(pgid); } #endif /* HAVE_TCGETPGRP */ @@ -6292,14 +6292,14 @@ static PyObject * posix_tcsetpgrp(PyObject *self, PyObject *args) { - int fd; - pid_t pgid; - if (!PyArg_ParseTuple(args, "i" PARSE_PID ":tcsetpgrp", &fd, &pgid)) - return NULL; - if (tcsetpgrp(fd, pgid) < 0) - return posix_error(); - Py_INCREF(Py_None); - return Py_None; + int fd; + pid_t pgid; + if (!PyArg_ParseTuple(args, "i" PARSE_PID ":tcsetpgrp", &fd, &pgid)) + return NULL; + if (tcsetpgrp(fd, pgid) < 0) + return posix_error(); + Py_INCREF(Py_None); + return Py_None; } #endif /* HAVE_TCSETPGRP */ @@ -6312,40 +6312,40 @@ static PyObject * posix_open(PyObject *self, PyObject *args) { - char *file = NULL; - int flag; - int mode = 0777; - int fd; + char *file = NULL; + int flag; + int mode = 0777; + int fd; #ifdef MS_WINDOWS - PyUnicodeObject *po; - if (PyArg_ParseTuple(args, "Ui|i:mkdir", &po, &flag, &mode)) { - Py_BEGIN_ALLOW_THREADS - /* PyUnicode_AS_UNICODE OK without thread - lock as it is a simple dereference. */ - fd = _wopen(PyUnicode_AS_UNICODE(po), flag, mode); - Py_END_ALLOW_THREADS - if (fd < 0) - return posix_error(); - return PyInt_FromLong((long)fd); - } - /* Drop the argument parsing error as narrow strings - are also valid. */ - PyErr_Clear(); -#endif - - if (!PyArg_ParseTuple(args, "eti|i", - Py_FileSystemDefaultEncoding, &file, - &flag, &mode)) - return NULL; - - Py_BEGIN_ALLOW_THREADS - fd = open(file, flag, mode); - Py_END_ALLOW_THREADS - if (fd < 0) - return posix_error_with_allocated_filename(file); - PyMem_Free(file); - return PyInt_FromLong((long)fd); + PyUnicodeObject *po; + if (PyArg_ParseTuple(args, "Ui|i:mkdir", &po, &flag, &mode)) { + Py_BEGIN_ALLOW_THREADS + /* PyUnicode_AS_UNICODE OK without thread + lock as it is a simple dereference. */ + fd = _wopen(PyUnicode_AS_UNICODE(po), flag, mode); + Py_END_ALLOW_THREADS + if (fd < 0) + return posix_error(); + return PyInt_FromLong((long)fd); + } + /* Drop the argument parsing error as narrow strings + are also valid. */ + PyErr_Clear(); +#endif + + if (!PyArg_ParseTuple(args, "eti|i", + Py_FileSystemDefaultEncoding, &file, + &flag, &mode)) + return NULL; + + Py_BEGIN_ALLOW_THREADS + fd = open(file, flag, mode); + Py_END_ALLOW_THREADS + if (fd < 0) + return posix_error_with_allocated_filename(file); + PyMem_Free(file); + return PyInt_FromLong((long)fd); } @@ -6356,37 +6356,37 @@ static PyObject * posix_close(PyObject *self, PyObject *args) { - int fd, res; - if (!PyArg_ParseTuple(args, "i:close", &fd)) - return NULL; - if (!_PyVerify_fd(fd)) - return posix_error(); - Py_BEGIN_ALLOW_THREADS - res = close(fd); - Py_END_ALLOW_THREADS - if (res < 0) - return posix_error(); - Py_INCREF(Py_None); - return Py_None; + int fd, res; + if (!PyArg_ParseTuple(args, "i:close", &fd)) + return NULL; + if (!_PyVerify_fd(fd)) + return posix_error(); + Py_BEGIN_ALLOW_THREADS + res = close(fd); + Py_END_ALLOW_THREADS + if (res < 0) + return posix_error(); + Py_INCREF(Py_None); + return Py_None; } -PyDoc_STRVAR(posix_closerange__doc__, +PyDoc_STRVAR(posix_closerange__doc__, "closerange(fd_low, fd_high)\n\n\ Closes all file descriptors in [fd_low, fd_high), ignoring errors."); static PyObject * posix_closerange(PyObject *self, PyObject *args) { - int fd_from, fd_to, i; - if (!PyArg_ParseTuple(args, "ii:closerange", &fd_from, &fd_to)) - return NULL; - Py_BEGIN_ALLOW_THREADS - for (i = fd_from; i < fd_to; i++) - if (_PyVerify_fd(i)) - close(i); - Py_END_ALLOW_THREADS - Py_RETURN_NONE; + int fd_from, fd_to, i; + if (!PyArg_ParseTuple(args, "ii:closerange", &fd_from, &fd_to)) + return NULL; + Py_BEGIN_ALLOW_THREADS + for (i = fd_from; i < fd_to; i++) + if (_PyVerify_fd(i)) + close(i); + Py_END_ALLOW_THREADS + Py_RETURN_NONE; } @@ -6397,17 +6397,17 @@ static PyObject * posix_dup(PyObject *self, PyObject *args) { - int fd; - if (!PyArg_ParseTuple(args, "i:dup", &fd)) - return NULL; - if (!_PyVerify_fd(fd)) - return posix_error(); - Py_BEGIN_ALLOW_THREADS - fd = dup(fd); - Py_END_ALLOW_THREADS - if (fd < 0) - return posix_error(); - return PyInt_FromLong((long)fd); + int fd; + if (!PyArg_ParseTuple(args, "i:dup", &fd)) + return NULL; + if (!_PyVerify_fd(fd)) + return posix_error(); + Py_BEGIN_ALLOW_THREADS + fd = dup(fd); + Py_END_ALLOW_THREADS + if (fd < 0) + return posix_error(); + return PyInt_FromLong((long)fd); } @@ -6418,18 +6418,18 @@ static PyObject * posix_dup2(PyObject *self, PyObject *args) { - int fd, fd2, res; - if (!PyArg_ParseTuple(args, "ii:dup2", &fd, &fd2)) - return NULL; - if (!_PyVerify_fd_dup2(fd, fd2)) - return posix_error(); - Py_BEGIN_ALLOW_THREADS - res = dup2(fd, fd2); - Py_END_ALLOW_THREADS - if (res < 0) - return posix_error(); - Py_INCREF(Py_None); - return Py_None; + int fd, fd2, res; + if (!PyArg_ParseTuple(args, "ii:dup2", &fd, &fd2)) + return NULL; + if (!_PyVerify_fd_dup2(fd, fd2)) + return posix_error(); + Py_BEGIN_ALLOW_THREADS + res = dup2(fd, fd2); + Py_END_ALLOW_THREADS + if (res < 0) + return posix_error(); + Py_INCREF(Py_None); + return Py_None; } @@ -6440,49 +6440,49 @@ static PyObject * posix_lseek(PyObject *self, PyObject *args) { - int fd, how; + int fd, how; #if defined(MS_WIN64) || defined(MS_WINDOWS) - PY_LONG_LONG pos, res; + PY_LONG_LONG pos, res; #else - off_t pos, res; + off_t pos, res; #endif - PyObject *posobj; - if (!PyArg_ParseTuple(args, "iOi:lseek", &fd, &posobj, &how)) - return NULL; + PyObject *posobj; + if (!PyArg_ParseTuple(args, "iOi:lseek", &fd, &posobj, &how)) + return NULL; #ifdef SEEK_SET - /* Turn 0, 1, 2 into SEEK_{SET,CUR,END} */ - switch (how) { - case 0: how = SEEK_SET; break; - case 1: how = SEEK_CUR; break; - case 2: how = SEEK_END; break; - } + /* Turn 0, 1, 2 into SEEK_{SET,CUR,END} */ + switch (how) { + case 0: how = SEEK_SET; break; + case 1: how = SEEK_CUR; break; + case 2: how = SEEK_END; break; + } #endif /* SEEK_END */ #if !defined(HAVE_LARGEFILE_SUPPORT) - pos = PyInt_AsLong(posobj); + pos = PyInt_AsLong(posobj); #else - pos = PyLong_Check(posobj) ? - PyLong_AsLongLong(posobj) : PyInt_AsLong(posobj); + pos = PyLong_Check(posobj) ? + PyLong_AsLongLong(posobj) : PyInt_AsLong(posobj); #endif - if (PyErr_Occurred()) - return NULL; + if (PyErr_Occurred()) + return NULL; - if (!_PyVerify_fd(fd)) - return posix_error(); - Py_BEGIN_ALLOW_THREADS + if (!_PyVerify_fd(fd)) + return posix_error(); + Py_BEGIN_ALLOW_THREADS #if defined(MS_WIN64) || defined(MS_WINDOWS) - res = _lseeki64(fd, pos, how); + res = _lseeki64(fd, pos, how); #else - res = lseek(fd, pos, how); + res = lseek(fd, pos, how); #endif - Py_END_ALLOW_THREADS - if (res < 0) - return posix_error(); + Py_END_ALLOW_THREADS + if (res < 0) + return posix_error(); #if !defined(HAVE_LARGEFILE_SUPPORT) - return PyInt_FromLong(res); + return PyInt_FromLong(res); #else - return PyLong_FromLongLong(res); + return PyLong_FromLongLong(res); #endif } @@ -6494,29 +6494,29 @@ static PyObject * posix_read(PyObject *self, PyObject *args) { - int fd, size, n; - PyObject *buffer; - if (!PyArg_ParseTuple(args, "ii:read", &fd, &size)) - return NULL; - if (size < 0) { - errno = EINVAL; - return posix_error(); - } - buffer = PyString_FromStringAndSize((char *)NULL, size); - if (buffer == NULL) - return NULL; - if (!_PyVerify_fd(fd)) - return posix_error(); - Py_BEGIN_ALLOW_THREADS - n = read(fd, PyString_AsString(buffer), size); - Py_END_ALLOW_THREADS - if (n < 0) { - Py_DECREF(buffer); - return posix_error(); - } - if (n != size) - _PyString_Resize(&buffer, n); - return buffer; + int fd, size, n; + PyObject *buffer; + if (!PyArg_ParseTuple(args, "ii:read", &fd, &size)) + return NULL; + if (size < 0) { + errno = EINVAL; + return posix_error(); + } + buffer = PyString_FromStringAndSize((char *)NULL, size); + if (buffer == NULL) + return NULL; + if (!_PyVerify_fd(fd)) + return posix_error(); + Py_BEGIN_ALLOW_THREADS + n = read(fd, PyString_AsString(buffer), size); + Py_END_ALLOW_THREADS + if (n < 0) { + Py_DECREF(buffer); + return posix_error(); + } + if (n != size) + _PyString_Resize(&buffer, n); + return buffer; } @@ -6527,21 +6527,21 @@ static PyObject * posix_write(PyObject *self, PyObject *args) { - Py_buffer pbuf; - int fd; - Py_ssize_t size; - - if (!PyArg_ParseTuple(args, "is*:write", &fd, &pbuf)) - return NULL; - if (!_PyVerify_fd(fd)) - return posix_error(); - Py_BEGIN_ALLOW_THREADS - size = write(fd, pbuf.buf, (size_t)pbuf.len); - Py_END_ALLOW_THREADS - PyBuffer_Release(&pbuf); - if (size < 0) - return posix_error(); - return PyInt_FromSsize_t(size); + Py_buffer pbuf; + int fd; + Py_ssize_t size; + + if (!PyArg_ParseTuple(args, "is*:write", &fd, &pbuf)) + return NULL; + if (!_PyVerify_fd(fd)) + return posix_error(); + Py_BEGIN_ALLOW_THREADS + size = write(fd, pbuf.buf, (size_t)pbuf.len); + Py_END_ALLOW_THREADS + PyBuffer_Release(&pbuf); + if (size < 0) + return posix_error(); + return PyInt_FromSsize_t(size); } @@ -6552,29 +6552,29 @@ static PyObject * posix_fstat(PyObject *self, PyObject *args) { - int fd; - STRUCT_STAT st; - int res; - if (!PyArg_ParseTuple(args, "i:fstat", &fd)) - return NULL; + int fd; + STRUCT_STAT st; + int res; + if (!PyArg_ParseTuple(args, "i:fstat", &fd)) + return NULL; #ifdef __VMS - /* on OpenVMS we must ensure that all bytes are written to the file */ - fsync(fd); + /* on OpenVMS we must ensure that all bytes are written to the file */ + fsync(fd); #endif - if (!_PyVerify_fd(fd)) - return posix_error(); - Py_BEGIN_ALLOW_THREADS - res = FSTAT(fd, &st); - Py_END_ALLOW_THREADS - if (res != 0) { + if (!_PyVerify_fd(fd)) + return posix_error(); + Py_BEGIN_ALLOW_THREADS + res = FSTAT(fd, &st); + Py_END_ALLOW_THREADS + if (res != 0) { #ifdef MS_WINDOWS - return win32_error("fstat", NULL); + return win32_error("fstat", NULL); #else - return posix_error(); + return posix_error(); #endif - } + } - return _pystat_fromstructstat(&st); + return _pystat_fromstructstat(&st); } @@ -6585,54 +6585,54 @@ static PyObject * posix_fdopen(PyObject *self, PyObject *args) { - int fd; - char *orgmode = "r"; - int bufsize = -1; - FILE *fp; - PyObject *f; - char *mode; - if (!PyArg_ParseTuple(args, "i|si", &fd, &orgmode, &bufsize)) - return NULL; - - /* Sanitize mode. See fileobject.c */ - mode = PyMem_MALLOC(strlen(orgmode)+3); - if (!mode) { - PyErr_NoMemory(); - return NULL; - } - strcpy(mode, orgmode); - if (_PyFile_SanitizeMode(mode)) { - PyMem_FREE(mode); - return NULL; - } - if (!_PyVerify_fd(fd)) - return posix_error(); - Py_BEGIN_ALLOW_THREADS + int fd; + char *orgmode = "r"; + int bufsize = -1; + FILE *fp; + PyObject *f; + char *mode; + if (!PyArg_ParseTuple(args, "i|si", &fd, &orgmode, &bufsize)) + return NULL; + + /* Sanitize mode. See fileobject.c */ + mode = PyMem_MALLOC(strlen(orgmode)+3); + if (!mode) { + PyErr_NoMemory(); + return NULL; + } + strcpy(mode, orgmode); + if (_PyFile_SanitizeMode(mode)) { + PyMem_FREE(mode); + return NULL; + } + if (!_PyVerify_fd(fd)) + return posix_error(); + Py_BEGIN_ALLOW_THREADS #if !defined(MS_WINDOWS) && defined(HAVE_FCNTL_H) - if (mode[0] == 'a') { - /* try to make sure the O_APPEND flag is set */ - int flags; - flags = fcntl(fd, F_GETFL); - if (flags != -1) - fcntl(fd, F_SETFL, flags | O_APPEND); - fp = fdopen(fd, mode); - if (fp == NULL && flags != -1) - /* restore old mode if fdopen failed */ - fcntl(fd, F_SETFL, flags); - } else { - fp = fdopen(fd, mode); - } -#else - fp = fdopen(fd, mode); -#endif - Py_END_ALLOW_THREADS - PyMem_FREE(mode); - if (fp == NULL) - return posix_error(); - f = PyFile_FromFile(fp, "", orgmode, fclose); - if (f != NULL) - PyFile_SetBufSize(f, bufsize); - return f; + if (mode[0] == 'a') { + /* try to make sure the O_APPEND flag is set */ + int flags; + flags = fcntl(fd, F_GETFL); + if (flags != -1) + fcntl(fd, F_SETFL, flags | O_APPEND); + fp = fdopen(fd, mode); + if (fp == NULL && flags != -1) + /* restore old mode if fdopen failed */ + fcntl(fd, F_SETFL, flags); + } else { + fp = fdopen(fd, mode); + } +#else + fp = fdopen(fd, mode); +#endif + Py_END_ALLOW_THREADS + PyMem_FREE(mode); + if (fp == NULL) + return posix_error(); + f = PyFile_FromFile(fp, "", orgmode, fclose); + if (f != NULL) + PyFile_SetBufSize(f, bufsize); + return f; } PyDoc_STRVAR(posix_isatty__doc__, @@ -6643,12 +6643,12 @@ static PyObject * posix_isatty(PyObject *self, PyObject *args) { - int fd; - if (!PyArg_ParseTuple(args, "i:isatty", &fd)) - return NULL; - if (!_PyVerify_fd(fd)) - return PyBool_FromLong(0); - return PyBool_FromLong(isatty(fd)); + int fd; + if (!PyArg_ParseTuple(args, "i:isatty", &fd)) + return NULL; + if (!_PyVerify_fd(fd)) + return PyBool_FromLong(0); + return PyBool_FromLong(isatty(fd)); } #ifdef HAVE_PIPE @@ -6663,35 +6663,35 @@ HFILE read, write; APIRET rc; - Py_BEGIN_ALLOW_THREADS + Py_BEGIN_ALLOW_THREADS rc = DosCreatePipe( &read, &write, 4096); - Py_END_ALLOW_THREADS + Py_END_ALLOW_THREADS if (rc != NO_ERROR) return os2_error(rc); return Py_BuildValue("(ii)", read, write); #else #if !defined(MS_WINDOWS) - int fds[2]; - int res; - Py_BEGIN_ALLOW_THREADS - res = pipe(fds); - Py_END_ALLOW_THREADS - if (res != 0) - return posix_error(); - return Py_BuildValue("(ii)", fds[0], fds[1]); + int fds[2]; + int res; + Py_BEGIN_ALLOW_THREADS + res = pipe(fds); + Py_END_ALLOW_THREADS + if (res != 0) + return posix_error(); + return Py_BuildValue("(ii)", fds[0], fds[1]); #else /* MS_WINDOWS */ - HANDLE read, write; - int read_fd, write_fd; - BOOL ok; - Py_BEGIN_ALLOW_THREADS - ok = CreatePipe(&read, &write, NULL, 0); - Py_END_ALLOW_THREADS - if (!ok) - return win32_error("CreatePipe", NULL); - read_fd = _open_osfhandle((Py_intptr_t)read, 0); - write_fd = _open_osfhandle((Py_intptr_t)write, 1); - return Py_BuildValue("(ii)", read_fd, write_fd); + HANDLE read, write; + int read_fd, write_fd; + BOOL ok; + Py_BEGIN_ALLOW_THREADS + ok = CreatePipe(&read, &write, NULL, 0); + Py_END_ALLOW_THREADS + if (!ok) + return win32_error("CreatePipe", NULL); + read_fd = _open_osfhandle((Py_intptr_t)read, 0); + write_fd = _open_osfhandle((Py_intptr_t)write, 1); + return Py_BuildValue("(ii)", read_fd, write_fd); #endif /* MS_WINDOWS */ #endif } @@ -6706,18 +6706,18 @@ static PyObject * posix_mkfifo(PyObject *self, PyObject *args) { - char *filename; - int mode = 0666; - int res; - if (!PyArg_ParseTuple(args, "s|i:mkfifo", &filename, &mode)) - return NULL; - Py_BEGIN_ALLOW_THREADS - res = mkfifo(filename, mode); - Py_END_ALLOW_THREADS - if (res < 0) - return posix_error(); - Py_INCREF(Py_None); - return Py_None; + char *filename; + int mode = 0666; + int res; + if (!PyArg_ParseTuple(args, "s|i:mkfifo", &filename, &mode)) + return NULL; + Py_BEGIN_ALLOW_THREADS + res = mkfifo(filename, mode); + Py_END_ALLOW_THREADS + if (res < 0) + return posix_error(); + Py_INCREF(Py_None); + return Py_None; } #endif @@ -6736,19 +6736,19 @@ static PyObject * posix_mknod(PyObject *self, PyObject *args) { - char *filename; - int mode = 0600; - int device = 0; - int res; - if (!PyArg_ParseTuple(args, "s|ii:mknod", &filename, &mode, &device)) - return NULL; - Py_BEGIN_ALLOW_THREADS - res = mknod(filename, mode, device); - Py_END_ALLOW_THREADS - if (res < 0) - return posix_error(); - Py_INCREF(Py_None); - return Py_None; + char *filename; + int mode = 0600; + int device = 0; + int res; + if (!PyArg_ParseTuple(args, "s|ii:mknod", &filename, &mode, &device)) + return NULL; + Py_BEGIN_ALLOW_THREADS + res = mknod(filename, mode, device); + Py_END_ALLOW_THREADS + if (res < 0) + return posix_error(); + Py_INCREF(Py_None); + return Py_None; } #endif @@ -6760,10 +6760,10 @@ static PyObject * posix_major(PyObject *self, PyObject *args) { - int device; - if (!PyArg_ParseTuple(args, "i:major", &device)) - return NULL; - return PyInt_FromLong((long)major(device)); + int device; + if (!PyArg_ParseTuple(args, "i:major", &device)) + return NULL; + return PyInt_FromLong((long)major(device)); } PyDoc_STRVAR(posix_minor__doc__, @@ -6773,10 +6773,10 @@ static PyObject * posix_minor(PyObject *self, PyObject *args) { - int device; - if (!PyArg_ParseTuple(args, "i:minor", &device)) - return NULL; - return PyInt_FromLong((long)minor(device)); + int device; + if (!PyArg_ParseTuple(args, "i:minor", &device)) + return NULL; + return PyInt_FromLong((long)minor(device)); } PyDoc_STRVAR(posix_makedev__doc__, @@ -6786,10 +6786,10 @@ static PyObject * posix_makedev(PyObject *self, PyObject *args) { - int major, minor; - if (!PyArg_ParseTuple(args, "ii:makedev", &major, &minor)) - return NULL; - return PyInt_FromLong((long)makedev(major, minor)); + int major, minor; + if (!PyArg_ParseTuple(args, "ii:makedev", &major, &minor)) + return NULL; + return PyInt_FromLong((long)makedev(major, minor)); } #endif /* device macros */ @@ -6802,30 +6802,30 @@ static PyObject * posix_ftruncate(PyObject *self, PyObject *args) { - int fd; - off_t length; - int res; - PyObject *lenobj; + int fd; + off_t length; + int res; + PyObject *lenobj; - if (!PyArg_ParseTuple(args, "iO:ftruncate", &fd, &lenobj)) - return NULL; + if (!PyArg_ParseTuple(args, "iO:ftruncate", &fd, &lenobj)) + return NULL; #if !defined(HAVE_LARGEFILE_SUPPORT) - length = PyInt_AsLong(lenobj); + length = PyInt_AsLong(lenobj); #else - length = PyLong_Check(lenobj) ? - PyLong_AsLongLong(lenobj) : PyInt_AsLong(lenobj); + length = PyLong_Check(lenobj) ? + PyLong_AsLongLong(lenobj) : PyInt_AsLong(lenobj); #endif - if (PyErr_Occurred()) - return NULL; + if (PyErr_Occurred()) + return NULL; - Py_BEGIN_ALLOW_THREADS - res = ftruncate(fd, length); - Py_END_ALLOW_THREADS - if (res < 0) - return posix_error(); - Py_INCREF(Py_None); - return Py_None; + Py_BEGIN_ALLOW_THREADS + res = ftruncate(fd, length); + Py_END_ALLOW_THREADS + if (res < 0) + return posix_error(); + Py_INCREF(Py_None); + return Py_None; } #endif @@ -6841,13 +6841,13 @@ static PyObject * posix_putenv(PyObject *self, PyObject *args) { - char *s1, *s2; - char *newenv; - PyObject *newstr; - size_t len; + char *s1, *s2; + char *newenv; + PyObject *newstr; + size_t len; - if (!PyArg_ParseTuple(args, "ss:putenv", &s1, &s2)) - return NULL; + if (!PyArg_ParseTuple(args, "ss:putenv", &s1, &s2)) + return NULL; #if defined(PYOS_OS2) if (stricmp(s1, "BEGINLIBPATH") == 0) { @@ -6866,38 +6866,38 @@ } else { #endif - /* XXX This can leak memory -- not easy to fix :-( */ - len = strlen(s1) + strlen(s2) + 2; - /* len includes space for a trailing \0; the size arg to - PyString_FromStringAndSize does not count that */ - newstr = PyString_FromStringAndSize(NULL, (int)len - 1); - if (newstr == NULL) - return PyErr_NoMemory(); - newenv = PyString_AS_STRING(newstr); - PyOS_snprintf(newenv, len, "%s=%s", s1, s2); - if (putenv(newenv)) { - Py_DECREF(newstr); - posix_error(); - return NULL; - } - /* Install the first arg and newstr in posix_putenv_garbage; - * this will cause previous value to be collected. This has to - * happen after the real putenv() call because the old value - * was still accessible until then. */ - if (PyDict_SetItem(posix_putenv_garbage, - PyTuple_GET_ITEM(args, 0), newstr)) { - /* really not much we can do; just leak */ - PyErr_Clear(); - } - else { - Py_DECREF(newstr); - } + /* XXX This can leak memory -- not easy to fix :-( */ + len = strlen(s1) + strlen(s2) + 2; + /* len includes space for a trailing \0; the size arg to + PyString_FromStringAndSize does not count that */ + newstr = PyString_FromStringAndSize(NULL, (int)len - 1); + if (newstr == NULL) + return PyErr_NoMemory(); + newenv = PyString_AS_STRING(newstr); + PyOS_snprintf(newenv, len, "%s=%s", s1, s2); + if (putenv(newenv)) { + Py_DECREF(newstr); + posix_error(); + return NULL; + } + /* Install the first arg and newstr in posix_putenv_garbage; + * this will cause previous value to be collected. This has to + * happen after the real putenv() call because the old value + * was still accessible until then. */ + if (PyDict_SetItem(posix_putenv_garbage, + PyTuple_GET_ITEM(args, 0), newstr)) { + /* really not much we can do; just leak */ + PyErr_Clear(); + } + else { + Py_DECREF(newstr); + } #if defined(PYOS_OS2) } #endif - Py_INCREF(Py_None); - return Py_None; + Py_INCREF(Py_None); + return Py_None; } #endif /* putenv */ @@ -6909,26 +6909,26 @@ static PyObject * posix_unsetenv(PyObject *self, PyObject *args) { - char *s1; + char *s1; - if (!PyArg_ParseTuple(args, "s:unsetenv", &s1)) - return NULL; + if (!PyArg_ParseTuple(args, "s:unsetenv", &s1)) + return NULL; - unsetenv(s1); + unsetenv(s1); - /* Remove the key from posix_putenv_garbage; - * this will cause it to be collected. This has to - * happen after the real unsetenv() call because the - * old value was still accessible until then. - */ - if (PyDict_DelItem(posix_putenv_garbage, - PyTuple_GET_ITEM(args, 0))) { - /* really not much we can do; just leak */ - PyErr_Clear(); - } + /* Remove the key from posix_putenv_garbage; + * this will cause it to be collected. This has to + * happen after the real unsetenv() call because the + * old value was still accessible until then. + */ + if (PyDict_DelItem(posix_putenv_garbage, + PyTuple_GET_ITEM(args, 0))) { + /* really not much we can do; just leak */ + PyErr_Clear(); + } - Py_INCREF(Py_None); - return Py_None; + Py_INCREF(Py_None); + return Py_None; } #endif /* unsetenv */ @@ -6939,17 +6939,17 @@ static PyObject * posix_strerror(PyObject *self, PyObject *args) { - int code; - char *message; - if (!PyArg_ParseTuple(args, "i:strerror", &code)) - return NULL; - message = strerror(code); - if (message == NULL) { - PyErr_SetString(PyExc_ValueError, - "strerror() argument out of range"); - return NULL; - } - return PyString_FromString(message); + int code; + char *message; + if (!PyArg_ParseTuple(args, "i:strerror", &code)) + return NULL; + message = strerror(code); + if (message == NULL) { + PyErr_SetString(PyExc_ValueError, + "strerror() argument out of range"); + return NULL; + } + return PyString_FromString(message); } @@ -6963,13 +6963,13 @@ static PyObject * posix_WCOREDUMP(PyObject *self, PyObject *args) { - WAIT_TYPE status; - WAIT_STATUS_INT(status) = 0; + WAIT_TYPE status; + WAIT_STATUS_INT(status) = 0; - if (!PyArg_ParseTuple(args, "i:WCOREDUMP", &WAIT_STATUS_INT(status))) - return NULL; + if (!PyArg_ParseTuple(args, "i:WCOREDUMP", &WAIT_STATUS_INT(status))) + return NULL; - return PyBool_FromLong(WCOREDUMP(status)); + return PyBool_FromLong(WCOREDUMP(status)); } #endif /* WCOREDUMP */ @@ -6982,13 +6982,13 @@ static PyObject * posix_WIFCONTINUED(PyObject *self, PyObject *args) { - WAIT_TYPE status; - WAIT_STATUS_INT(status) = 0; + WAIT_TYPE status; + WAIT_STATUS_INT(status) = 0; - if (!PyArg_ParseTuple(args, "i:WCONTINUED", &WAIT_STATUS_INT(status))) - return NULL; + if (!PyArg_ParseTuple(args, "i:WCONTINUED", &WAIT_STATUS_INT(status))) + return NULL; - return PyBool_FromLong(WIFCONTINUED(status)); + return PyBool_FromLong(WIFCONTINUED(status)); } #endif /* WIFCONTINUED */ @@ -7000,13 +7000,13 @@ static PyObject * posix_WIFSTOPPED(PyObject *self, PyObject *args) { - WAIT_TYPE status; - WAIT_STATUS_INT(status) = 0; + WAIT_TYPE status; + WAIT_STATUS_INT(status) = 0; - if (!PyArg_ParseTuple(args, "i:WIFSTOPPED", &WAIT_STATUS_INT(status))) - return NULL; + if (!PyArg_ParseTuple(args, "i:WIFSTOPPED", &WAIT_STATUS_INT(status))) + return NULL; - return PyBool_FromLong(WIFSTOPPED(status)); + return PyBool_FromLong(WIFSTOPPED(status)); } #endif /* WIFSTOPPED */ @@ -7018,13 +7018,13 @@ static PyObject * posix_WIFSIGNALED(PyObject *self, PyObject *args) { - WAIT_TYPE status; - WAIT_STATUS_INT(status) = 0; + WAIT_TYPE status; + WAIT_STATUS_INT(status) = 0; - if (!PyArg_ParseTuple(args, "i:WIFSIGNALED", &WAIT_STATUS_INT(status))) - return NULL; + if (!PyArg_ParseTuple(args, "i:WIFSIGNALED", &WAIT_STATUS_INT(status))) + return NULL; - return PyBool_FromLong(WIFSIGNALED(status)); + return PyBool_FromLong(WIFSIGNALED(status)); } #endif /* WIFSIGNALED */ @@ -7037,13 +7037,13 @@ static PyObject * posix_WIFEXITED(PyObject *self, PyObject *args) { - WAIT_TYPE status; - WAIT_STATUS_INT(status) = 0; + WAIT_TYPE status; + WAIT_STATUS_INT(status) = 0; - if (!PyArg_ParseTuple(args, "i:WIFEXITED", &WAIT_STATUS_INT(status))) - return NULL; + if (!PyArg_ParseTuple(args, "i:WIFEXITED", &WAIT_STATUS_INT(status))) + return NULL; - return PyBool_FromLong(WIFEXITED(status)); + return PyBool_FromLong(WIFEXITED(status)); } #endif /* WIFEXITED */ @@ -7055,13 +7055,13 @@ static PyObject * posix_WEXITSTATUS(PyObject *self, PyObject *args) { - WAIT_TYPE status; - WAIT_STATUS_INT(status) = 0; + WAIT_TYPE status; + WAIT_STATUS_INT(status) = 0; - if (!PyArg_ParseTuple(args, "i:WEXITSTATUS", &WAIT_STATUS_INT(status))) - return NULL; + if (!PyArg_ParseTuple(args, "i:WEXITSTATUS", &WAIT_STATUS_INT(status))) + return NULL; - return Py_BuildValue("i", WEXITSTATUS(status)); + return Py_BuildValue("i", WEXITSTATUS(status)); } #endif /* WEXITSTATUS */ @@ -7074,13 +7074,13 @@ static PyObject * posix_WTERMSIG(PyObject *self, PyObject *args) { - WAIT_TYPE status; - WAIT_STATUS_INT(status) = 0; + WAIT_TYPE status; + WAIT_STATUS_INT(status) = 0; - if (!PyArg_ParseTuple(args, "i:WTERMSIG", &WAIT_STATUS_INT(status))) - return NULL; + if (!PyArg_ParseTuple(args, "i:WTERMSIG", &WAIT_STATUS_INT(status))) + return NULL; - return Py_BuildValue("i", WTERMSIG(status)); + return Py_BuildValue("i", WTERMSIG(status)); } #endif /* WTERMSIG */ @@ -7093,13 +7093,13 @@ static PyObject * posix_WSTOPSIG(PyObject *self, PyObject *args) { - WAIT_TYPE status; - WAIT_STATUS_INT(status) = 0; + WAIT_TYPE status; + WAIT_STATUS_INT(status) = 0; - if (!PyArg_ParseTuple(args, "i:WSTOPSIG", &WAIT_STATUS_INT(status))) - return NULL; + if (!PyArg_ParseTuple(args, "i:WSTOPSIG", &WAIT_STATUS_INT(status))) + return NULL; - return Py_BuildValue("i", WSTOPSIG(status)); + return Py_BuildValue("i", WSTOPSIG(status)); } #endif /* WSTOPSIG */ @@ -7116,41 +7116,41 @@ static PyObject* _pystatvfs_fromstructstatvfs(struct statvfs st) { - PyObject *v = PyStructSequence_New(&StatVFSResultType); - if (v == NULL) - return NULL; + PyObject *v = PyStructSequence_New(&StatVFSResultType); + if (v == NULL) + return NULL; #if !defined(HAVE_LARGEFILE_SUPPORT) - PyStructSequence_SET_ITEM(v, 0, PyInt_FromLong((long) st.f_bsize)); - PyStructSequence_SET_ITEM(v, 1, PyInt_FromLong((long) st.f_frsize)); - PyStructSequence_SET_ITEM(v, 2, PyInt_FromLong((long) st.f_blocks)); - PyStructSequence_SET_ITEM(v, 3, PyInt_FromLong((long) st.f_bfree)); - PyStructSequence_SET_ITEM(v, 4, PyInt_FromLong((long) st.f_bavail)); - PyStructSequence_SET_ITEM(v, 5, PyInt_FromLong((long) st.f_files)); - PyStructSequence_SET_ITEM(v, 6, PyInt_FromLong((long) st.f_ffree)); - PyStructSequence_SET_ITEM(v, 7, PyInt_FromLong((long) st.f_favail)); - PyStructSequence_SET_ITEM(v, 8, PyInt_FromLong((long) st.f_flag)); - PyStructSequence_SET_ITEM(v, 9, PyInt_FromLong((long) st.f_namemax)); -#else - PyStructSequence_SET_ITEM(v, 0, PyInt_FromLong((long) st.f_bsize)); - PyStructSequence_SET_ITEM(v, 1, PyInt_FromLong((long) st.f_frsize)); - PyStructSequence_SET_ITEM(v, 2, - PyLong_FromLongLong((PY_LONG_LONG) st.f_blocks)); - PyStructSequence_SET_ITEM(v, 3, - PyLong_FromLongLong((PY_LONG_LONG) st.f_bfree)); - PyStructSequence_SET_ITEM(v, 4, - PyLong_FromLongLong((PY_LONG_LONG) st.f_bavail)); - PyStructSequence_SET_ITEM(v, 5, - PyLong_FromLongLong((PY_LONG_LONG) st.f_files)); - PyStructSequence_SET_ITEM(v, 6, - PyLong_FromLongLong((PY_LONG_LONG) st.f_ffree)); - PyStructSequence_SET_ITEM(v, 7, - PyLong_FromLongLong((PY_LONG_LONG) st.f_favail)); - PyStructSequence_SET_ITEM(v, 8, PyInt_FromLong((long) st.f_flag)); - PyStructSequence_SET_ITEM(v, 9, PyInt_FromLong((long) st.f_namemax)); + PyStructSequence_SET_ITEM(v, 0, PyInt_FromLong((long) st.f_bsize)); + PyStructSequence_SET_ITEM(v, 1, PyInt_FromLong((long) st.f_frsize)); + PyStructSequence_SET_ITEM(v, 2, PyInt_FromLong((long) st.f_blocks)); + PyStructSequence_SET_ITEM(v, 3, PyInt_FromLong((long) st.f_bfree)); + PyStructSequence_SET_ITEM(v, 4, PyInt_FromLong((long) st.f_bavail)); + PyStructSequence_SET_ITEM(v, 5, PyInt_FromLong((long) st.f_files)); + PyStructSequence_SET_ITEM(v, 6, PyInt_FromLong((long) st.f_ffree)); + PyStructSequence_SET_ITEM(v, 7, PyInt_FromLong((long) st.f_favail)); + PyStructSequence_SET_ITEM(v, 8, PyInt_FromLong((long) st.f_flag)); + PyStructSequence_SET_ITEM(v, 9, PyInt_FromLong((long) st.f_namemax)); +#else + PyStructSequence_SET_ITEM(v, 0, PyInt_FromLong((long) st.f_bsize)); + PyStructSequence_SET_ITEM(v, 1, PyInt_FromLong((long) st.f_frsize)); + PyStructSequence_SET_ITEM(v, 2, + PyLong_FromLongLong((PY_LONG_LONG) st.f_blocks)); + PyStructSequence_SET_ITEM(v, 3, + PyLong_FromLongLong((PY_LONG_LONG) st.f_bfree)); + PyStructSequence_SET_ITEM(v, 4, + PyLong_FromLongLong((PY_LONG_LONG) st.f_bavail)); + PyStructSequence_SET_ITEM(v, 5, + PyLong_FromLongLong((PY_LONG_LONG) st.f_files)); + PyStructSequence_SET_ITEM(v, 6, + PyLong_FromLongLong((PY_LONG_LONG) st.f_ffree)); + PyStructSequence_SET_ITEM(v, 7, + PyLong_FromLongLong((PY_LONG_LONG) st.f_favail)); + PyStructSequence_SET_ITEM(v, 8, PyInt_FromLong((long) st.f_flag)); + PyStructSequence_SET_ITEM(v, 9, PyInt_FromLong((long) st.f_namemax)); #endif - return v; + return v; } PyDoc_STRVAR(posix_fstatvfs__doc__, @@ -7160,18 +7160,18 @@ static PyObject * posix_fstatvfs(PyObject *self, PyObject *args) { - int fd, res; - struct statvfs st; + int fd, res; + struct statvfs st; - if (!PyArg_ParseTuple(args, "i:fstatvfs", &fd)) - return NULL; - Py_BEGIN_ALLOW_THREADS - res = fstatvfs(fd, &st); - Py_END_ALLOW_THREADS - if (res != 0) - return posix_error(); + if (!PyArg_ParseTuple(args, "i:fstatvfs", &fd)) + return NULL; + Py_BEGIN_ALLOW_THREADS + res = fstatvfs(fd, &st); + Py_END_ALLOW_THREADS + if (res != 0) + return posix_error(); - return _pystatvfs_fromstructstatvfs(st); + return _pystatvfs_fromstructstatvfs(st); } #endif /* HAVE_FSTATVFS && HAVE_SYS_STATVFS_H */ @@ -7186,18 +7186,18 @@ static PyObject * posix_statvfs(PyObject *self, PyObject *args) { - char *path; - int res; - struct statvfs st; - if (!PyArg_ParseTuple(args, "s:statvfs", &path)) - return NULL; - Py_BEGIN_ALLOW_THREADS - res = statvfs(path, &st); - Py_END_ALLOW_THREADS - if (res != 0) - return posix_error_with_filename(path); + char *path; + int res; + struct statvfs st; + if (!PyArg_ParseTuple(args, "s:statvfs", &path)) + return NULL; + Py_BEGIN_ALLOW_THREADS + res = statvfs(path, &st); + Py_END_ALLOW_THREADS + if (res != 0) + return posix_error_with_filename(path); - return _pystatvfs_fromstructstatvfs(st); + return _pystatvfs_fromstructstatvfs(st); } #endif /* HAVE_STATVFS */ @@ -7218,11 +7218,11 @@ char *name; if (!PyArg_ParseTuple(args, "|zz:tempnam", &dir, &pfx)) - return NULL; + return NULL; if (PyErr_Warn(PyExc_RuntimeWarning, - "tempnam is a potential security risk to your program") < 0) - return NULL; + "tempnam is a potential security risk to your program") < 0) + return NULL; #ifdef MS_WINDOWS name = _tempnam(dir, pfx); @@ -7230,7 +7230,7 @@ name = tempnam(dir, pfx); #endif if (name == NULL) - return PyErr_NoMemory(); + return PyErr_NoMemory(); result = PyString_FromString(name); free(name); return result; @@ -7250,7 +7250,7 @@ fp = tmpfile(); if (fp == NULL) - return posix_error(); + return posix_error(); return PyFile_FromFile(fp, "", "w+b", fclose); } #endif @@ -7268,8 +7268,8 @@ char *name; if (PyErr_Warn(PyExc_RuntimeWarning, - "tmpnam is a potential security risk to your program") < 0) - return NULL; + "tmpnam is a potential security risk to your program") < 0) + return NULL; #ifdef USE_TMPNAM_R name = tmpnam_r(buffer); @@ -7277,16 +7277,16 @@ name = tmpnam(buffer); #endif if (name == NULL) { - PyObject *err = Py_BuildValue("is", 0, + PyObject *err = Py_BuildValue("is", 0, #ifdef USE_TMPNAM_R - "unexpected NULL from tmpnam_r" + "unexpected NULL from tmpnam_r" #else - "unexpected NULL from tmpnam" + "unexpected NULL from tmpnam" #endif - ); - PyErr_SetObject(PyExc_OSError, err); - Py_XDECREF(err); - return NULL; + ); + PyErr_SetObject(PyExc_OSError, err); + Py_XDECREF(err); + return NULL; } return PyString_FromString(buffer); } @@ -7311,36 +7311,36 @@ static int conv_confname(PyObject *arg, int *valuep, struct constdef *table, - size_t tablesize) + size_t tablesize) { if (PyInt_Check(arg)) { - *valuep = PyInt_AS_LONG(arg); - return 1; + *valuep = PyInt_AS_LONG(arg); + return 1; } if (PyString_Check(arg)) { - /* look up the value in the table using a binary search */ - size_t lo = 0; - size_t mid; - size_t hi = tablesize; - int cmp; - char *confname = PyString_AS_STRING(arg); - while (lo < hi) { - mid = (lo + hi) / 2; - cmp = strcmp(confname, table[mid].name); - if (cmp < 0) - hi = mid; - else if (cmp > 0) - lo = mid + 1; - else { - *valuep = table[mid].value; - return 1; - } + /* look up the value in the table using a binary search */ + size_t lo = 0; + size_t mid; + size_t hi = tablesize; + int cmp; + char *confname = PyString_AS_STRING(arg); + while (lo < hi) { + mid = (lo + hi) / 2; + cmp = strcmp(confname, table[mid].name); + if (cmp < 0) + hi = mid; + else if (cmp > 0) + lo = mid + 1; + else { + *valuep = table[mid].value; + return 1; } - PyErr_SetString(PyExc_ValueError, "unrecognized configuration name"); + } + PyErr_SetString(PyExc_ValueError, "unrecognized configuration name"); } else - PyErr_SetString(PyExc_TypeError, - "configuration names must be strings or integers"); + PyErr_SetString(PyExc_TypeError, + "configuration names must be strings or integers"); return 0; } @@ -7348,55 +7348,55 @@ #if defined(HAVE_FPATHCONF) || defined(HAVE_PATHCONF) static struct constdef posix_constants_pathconf[] = { #ifdef _PC_ABI_AIO_XFER_MAX - {"PC_ABI_AIO_XFER_MAX", _PC_ABI_AIO_XFER_MAX}, + {"PC_ABI_AIO_XFER_MAX", _PC_ABI_AIO_XFER_MAX}, #endif #ifdef _PC_ABI_ASYNC_IO - {"PC_ABI_ASYNC_IO", _PC_ABI_ASYNC_IO}, + {"PC_ABI_ASYNC_IO", _PC_ABI_ASYNC_IO}, #endif #ifdef _PC_ASYNC_IO - {"PC_ASYNC_IO", _PC_ASYNC_IO}, + {"PC_ASYNC_IO", _PC_ASYNC_IO}, #endif #ifdef _PC_CHOWN_RESTRICTED - {"PC_CHOWN_RESTRICTED", _PC_CHOWN_RESTRICTED}, + {"PC_CHOWN_RESTRICTED", _PC_CHOWN_RESTRICTED}, #endif #ifdef _PC_FILESIZEBITS - {"PC_FILESIZEBITS", _PC_FILESIZEBITS}, + {"PC_FILESIZEBITS", _PC_FILESIZEBITS}, #endif #ifdef _PC_LAST - {"PC_LAST", _PC_LAST}, + {"PC_LAST", _PC_LAST}, #endif #ifdef _PC_LINK_MAX - {"PC_LINK_MAX", _PC_LINK_MAX}, + {"PC_LINK_MAX", _PC_LINK_MAX}, #endif #ifdef _PC_MAX_CANON - {"PC_MAX_CANON", _PC_MAX_CANON}, + {"PC_MAX_CANON", _PC_MAX_CANON}, #endif #ifdef _PC_MAX_INPUT - {"PC_MAX_INPUT", _PC_MAX_INPUT}, + {"PC_MAX_INPUT", _PC_MAX_INPUT}, #endif #ifdef _PC_NAME_MAX - {"PC_NAME_MAX", _PC_NAME_MAX}, + {"PC_NAME_MAX", _PC_NAME_MAX}, #endif #ifdef _PC_NO_TRUNC - {"PC_NO_TRUNC", _PC_NO_TRUNC}, + {"PC_NO_TRUNC", _PC_NO_TRUNC}, #endif #ifdef _PC_PATH_MAX - {"PC_PATH_MAX", _PC_PATH_MAX}, + {"PC_PATH_MAX", _PC_PATH_MAX}, #endif #ifdef _PC_PIPE_BUF - {"PC_PIPE_BUF", _PC_PIPE_BUF}, + {"PC_PIPE_BUF", _PC_PIPE_BUF}, #endif #ifdef _PC_PRIO_IO - {"PC_PRIO_IO", _PC_PRIO_IO}, + {"PC_PRIO_IO", _PC_PRIO_IO}, #endif #ifdef _PC_SOCK_MAXBUF - {"PC_SOCK_MAXBUF", _PC_SOCK_MAXBUF}, + {"PC_SOCK_MAXBUF", _PC_SOCK_MAXBUF}, #endif #ifdef _PC_SYNC_IO - {"PC_SYNC_IO", _PC_SYNC_IO}, + {"PC_SYNC_IO", _PC_SYNC_IO}, #endif #ifdef _PC_VDISABLE - {"PC_VDISABLE", _PC_VDISABLE}, + {"PC_VDISABLE", _PC_VDISABLE}, #endif }; @@ -7423,14 +7423,14 @@ if (PyArg_ParseTuple(args, "iO&:fpathconf", &fd, conv_path_confname, &name)) { - long limit; + long limit; - errno = 0; - limit = fpathconf(fd, name); - if (limit == -1 && errno != 0) - posix_error(); - else - result = PyInt_FromLong(limit); + errno = 0; + limit = fpathconf(fd, name); + if (limit == -1 && errno != 0) + posix_error(); + else + result = PyInt_FromLong(limit); } return result; } @@ -7452,19 +7452,19 @@ if (PyArg_ParseTuple(args, "sO&:pathconf", &path, conv_path_confname, &name)) { - long limit; + long limit; - errno = 0; - limit = pathconf(path, name); - if (limit == -1 && errno != 0) { - if (errno == EINVAL) - /* could be a path or name problem */ - posix_error(); - else - posix_error_with_filename(path); - } + errno = 0; + limit = pathconf(path, name); + if (limit == -1 && errno != 0) { + if (errno == EINVAL) + /* could be a path or name problem */ + posix_error(); else - result = PyInt_FromLong(limit); + posix_error_with_filename(path); + } + else + result = PyInt_FromLong(limit); } return result; } @@ -7473,148 +7473,148 @@ #ifdef HAVE_CONFSTR static struct constdef posix_constants_confstr[] = { #ifdef _CS_ARCHITECTURE - {"CS_ARCHITECTURE", _CS_ARCHITECTURE}, + {"CS_ARCHITECTURE", _CS_ARCHITECTURE}, #endif #ifdef _CS_HOSTNAME - {"CS_HOSTNAME", _CS_HOSTNAME}, + {"CS_HOSTNAME", _CS_HOSTNAME}, #endif #ifdef _CS_HW_PROVIDER - {"CS_HW_PROVIDER", _CS_HW_PROVIDER}, + {"CS_HW_PROVIDER", _CS_HW_PROVIDER}, #endif #ifdef _CS_HW_SERIAL - {"CS_HW_SERIAL", _CS_HW_SERIAL}, + {"CS_HW_SERIAL", _CS_HW_SERIAL}, #endif #ifdef _CS_INITTAB_NAME - {"CS_INITTAB_NAME", _CS_INITTAB_NAME}, + {"CS_INITTAB_NAME", _CS_INITTAB_NAME}, #endif #ifdef _CS_LFS64_CFLAGS - {"CS_LFS64_CFLAGS", _CS_LFS64_CFLAGS}, + {"CS_LFS64_CFLAGS", _CS_LFS64_CFLAGS}, #endif #ifdef _CS_LFS64_LDFLAGS - {"CS_LFS64_LDFLAGS", _CS_LFS64_LDFLAGS}, + {"CS_LFS64_LDFLAGS", _CS_LFS64_LDFLAGS}, #endif #ifdef _CS_LFS64_LIBS - {"CS_LFS64_LIBS", _CS_LFS64_LIBS}, + {"CS_LFS64_LIBS", _CS_LFS64_LIBS}, #endif #ifdef _CS_LFS64_LINTFLAGS - {"CS_LFS64_LINTFLAGS", _CS_LFS64_LINTFLAGS}, + {"CS_LFS64_LINTFLAGS", _CS_LFS64_LINTFLAGS}, #endif #ifdef _CS_LFS_CFLAGS - {"CS_LFS_CFLAGS", _CS_LFS_CFLAGS}, + {"CS_LFS_CFLAGS", _CS_LFS_CFLAGS}, #endif #ifdef _CS_LFS_LDFLAGS - {"CS_LFS_LDFLAGS", _CS_LFS_LDFLAGS}, + {"CS_LFS_LDFLAGS", _CS_LFS_LDFLAGS}, #endif #ifdef _CS_LFS_LIBS - {"CS_LFS_LIBS", _CS_LFS_LIBS}, + {"CS_LFS_LIBS", _CS_LFS_LIBS}, #endif #ifdef _CS_LFS_LINTFLAGS - {"CS_LFS_LINTFLAGS", _CS_LFS_LINTFLAGS}, + {"CS_LFS_LINTFLAGS", _CS_LFS_LINTFLAGS}, #endif #ifdef _CS_MACHINE - {"CS_MACHINE", _CS_MACHINE}, + {"CS_MACHINE", _CS_MACHINE}, #endif #ifdef _CS_PATH - {"CS_PATH", _CS_PATH}, + {"CS_PATH", _CS_PATH}, #endif #ifdef _CS_RELEASE - {"CS_RELEASE", _CS_RELEASE}, + {"CS_RELEASE", _CS_RELEASE}, #endif #ifdef _CS_SRPC_DOMAIN - {"CS_SRPC_DOMAIN", _CS_SRPC_DOMAIN}, + {"CS_SRPC_DOMAIN", _CS_SRPC_DOMAIN}, #endif #ifdef _CS_SYSNAME - {"CS_SYSNAME", _CS_SYSNAME}, + {"CS_SYSNAME", _CS_SYSNAME}, #endif #ifdef _CS_VERSION - {"CS_VERSION", _CS_VERSION}, + {"CS_VERSION", _CS_VERSION}, #endif #ifdef _CS_XBS5_ILP32_OFF32_CFLAGS - {"CS_XBS5_ILP32_OFF32_CFLAGS", _CS_XBS5_ILP32_OFF32_CFLAGS}, + {"CS_XBS5_ILP32_OFF32_CFLAGS", _CS_XBS5_ILP32_OFF32_CFLAGS}, #endif #ifdef _CS_XBS5_ILP32_OFF32_LDFLAGS - {"CS_XBS5_ILP32_OFF32_LDFLAGS", _CS_XBS5_ILP32_OFF32_LDFLAGS}, + {"CS_XBS5_ILP32_OFF32_LDFLAGS", _CS_XBS5_ILP32_OFF32_LDFLAGS}, #endif #ifdef _CS_XBS5_ILP32_OFF32_LIBS - {"CS_XBS5_ILP32_OFF32_LIBS", _CS_XBS5_ILP32_OFF32_LIBS}, + {"CS_XBS5_ILP32_OFF32_LIBS", _CS_XBS5_ILP32_OFF32_LIBS}, #endif #ifdef _CS_XBS5_ILP32_OFF32_LINTFLAGS - {"CS_XBS5_ILP32_OFF32_LINTFLAGS", _CS_XBS5_ILP32_OFF32_LINTFLAGS}, + {"CS_XBS5_ILP32_OFF32_LINTFLAGS", _CS_XBS5_ILP32_OFF32_LINTFLAGS}, #endif #ifdef _CS_XBS5_ILP32_OFFBIG_CFLAGS - {"CS_XBS5_ILP32_OFFBIG_CFLAGS", _CS_XBS5_ILP32_OFFBIG_CFLAGS}, + {"CS_XBS5_ILP32_OFFBIG_CFLAGS", _CS_XBS5_ILP32_OFFBIG_CFLAGS}, #endif #ifdef _CS_XBS5_ILP32_OFFBIG_LDFLAGS - {"CS_XBS5_ILP32_OFFBIG_LDFLAGS", _CS_XBS5_ILP32_OFFBIG_LDFLAGS}, + {"CS_XBS5_ILP32_OFFBIG_LDFLAGS", _CS_XBS5_ILP32_OFFBIG_LDFLAGS}, #endif #ifdef _CS_XBS5_ILP32_OFFBIG_LIBS - {"CS_XBS5_ILP32_OFFBIG_LIBS", _CS_XBS5_ILP32_OFFBIG_LIBS}, + {"CS_XBS5_ILP32_OFFBIG_LIBS", _CS_XBS5_ILP32_OFFBIG_LIBS}, #endif #ifdef _CS_XBS5_ILP32_OFFBIG_LINTFLAGS - {"CS_XBS5_ILP32_OFFBIG_LINTFLAGS", _CS_XBS5_ILP32_OFFBIG_LINTFLAGS}, + {"CS_XBS5_ILP32_OFFBIG_LINTFLAGS", _CS_XBS5_ILP32_OFFBIG_LINTFLAGS}, #endif #ifdef _CS_XBS5_LP64_OFF64_CFLAGS - {"CS_XBS5_LP64_OFF64_CFLAGS", _CS_XBS5_LP64_OFF64_CFLAGS}, + {"CS_XBS5_LP64_OFF64_CFLAGS", _CS_XBS5_LP64_OFF64_CFLAGS}, #endif #ifdef _CS_XBS5_LP64_OFF64_LDFLAGS - {"CS_XBS5_LP64_OFF64_LDFLAGS", _CS_XBS5_LP64_OFF64_LDFLAGS}, + {"CS_XBS5_LP64_OFF64_LDFLAGS", _CS_XBS5_LP64_OFF64_LDFLAGS}, #endif #ifdef _CS_XBS5_LP64_OFF64_LIBS - {"CS_XBS5_LP64_OFF64_LIBS", _CS_XBS5_LP64_OFF64_LIBS}, + {"CS_XBS5_LP64_OFF64_LIBS", _CS_XBS5_LP64_OFF64_LIBS}, #endif #ifdef _CS_XBS5_LP64_OFF64_LINTFLAGS - {"CS_XBS5_LP64_OFF64_LINTFLAGS", _CS_XBS5_LP64_OFF64_LINTFLAGS}, + {"CS_XBS5_LP64_OFF64_LINTFLAGS", _CS_XBS5_LP64_OFF64_LINTFLAGS}, #endif #ifdef _CS_XBS5_LPBIG_OFFBIG_CFLAGS - {"CS_XBS5_LPBIG_OFFBIG_CFLAGS", _CS_XBS5_LPBIG_OFFBIG_CFLAGS}, + {"CS_XBS5_LPBIG_OFFBIG_CFLAGS", _CS_XBS5_LPBIG_OFFBIG_CFLAGS}, #endif #ifdef _CS_XBS5_LPBIG_OFFBIG_LDFLAGS - {"CS_XBS5_LPBIG_OFFBIG_LDFLAGS", _CS_XBS5_LPBIG_OFFBIG_LDFLAGS}, + {"CS_XBS5_LPBIG_OFFBIG_LDFLAGS", _CS_XBS5_LPBIG_OFFBIG_LDFLAGS}, #endif #ifdef _CS_XBS5_LPBIG_OFFBIG_LIBS - {"CS_XBS5_LPBIG_OFFBIG_LIBS", _CS_XBS5_LPBIG_OFFBIG_LIBS}, + {"CS_XBS5_LPBIG_OFFBIG_LIBS", _CS_XBS5_LPBIG_OFFBIG_LIBS}, #endif #ifdef _CS_XBS5_LPBIG_OFFBIG_LINTFLAGS - {"CS_XBS5_LPBIG_OFFBIG_LINTFLAGS", _CS_XBS5_LPBIG_OFFBIG_LINTFLAGS}, + {"CS_XBS5_LPBIG_OFFBIG_LINTFLAGS", _CS_XBS5_LPBIG_OFFBIG_LINTFLAGS}, #endif #ifdef _MIPS_CS_AVAIL_PROCESSORS - {"MIPS_CS_AVAIL_PROCESSORS", _MIPS_CS_AVAIL_PROCESSORS}, + {"MIPS_CS_AVAIL_PROCESSORS", _MIPS_CS_AVAIL_PROCESSORS}, #endif #ifdef _MIPS_CS_BASE - {"MIPS_CS_BASE", _MIPS_CS_BASE}, + {"MIPS_CS_BASE", _MIPS_CS_BASE}, #endif #ifdef _MIPS_CS_HOSTID - {"MIPS_CS_HOSTID", _MIPS_CS_HOSTID}, + {"MIPS_CS_HOSTID", _MIPS_CS_HOSTID}, #endif #ifdef _MIPS_CS_HW_NAME - {"MIPS_CS_HW_NAME", _MIPS_CS_HW_NAME}, + {"MIPS_CS_HW_NAME", _MIPS_CS_HW_NAME}, #endif #ifdef _MIPS_CS_NUM_PROCESSORS - {"MIPS_CS_NUM_PROCESSORS", _MIPS_CS_NUM_PROCESSORS}, + {"MIPS_CS_NUM_PROCESSORS", _MIPS_CS_NUM_PROCESSORS}, #endif #ifdef _MIPS_CS_OSREL_MAJ - {"MIPS_CS_OSREL_MAJ", _MIPS_CS_OSREL_MAJ}, + {"MIPS_CS_OSREL_MAJ", _MIPS_CS_OSREL_MAJ}, #endif #ifdef _MIPS_CS_OSREL_MIN - {"MIPS_CS_OSREL_MIN", _MIPS_CS_OSREL_MIN}, + {"MIPS_CS_OSREL_MIN", _MIPS_CS_OSREL_MIN}, #endif #ifdef _MIPS_CS_OSREL_PATCH - {"MIPS_CS_OSREL_PATCH", _MIPS_CS_OSREL_PATCH}, + {"MIPS_CS_OSREL_PATCH", _MIPS_CS_OSREL_PATCH}, #endif #ifdef _MIPS_CS_OS_NAME - {"MIPS_CS_OS_NAME", _MIPS_CS_OS_NAME}, + {"MIPS_CS_OS_NAME", _MIPS_CS_OS_NAME}, #endif #ifdef _MIPS_CS_OS_PROVIDER - {"MIPS_CS_OS_PROVIDER", _MIPS_CS_OS_PROVIDER}, + {"MIPS_CS_OS_PROVIDER", _MIPS_CS_OS_PROVIDER}, #endif #ifdef _MIPS_CS_PROCESSORS - {"MIPS_CS_PROCESSORS", _MIPS_CS_PROCESSORS}, + {"MIPS_CS_PROCESSORS", _MIPS_CS_PROCESSORS}, #endif #ifdef _MIPS_CS_SERIAL - {"MIPS_CS_SERIAL", _MIPS_CS_SERIAL}, + {"MIPS_CS_SERIAL", _MIPS_CS_SERIAL}, #endif #ifdef _MIPS_CS_VENDOR - {"MIPS_CS_VENDOR", _MIPS_CS_VENDOR}, + {"MIPS_CS_VENDOR", _MIPS_CS_VENDOR}, #endif }; @@ -7638,28 +7638,28 @@ char buffer[256]; if (PyArg_ParseTuple(args, "O&:confstr", conv_confstr_confname, &name)) { - int len; + int len; - errno = 0; - len = confstr(name, buffer, sizeof(buffer)); - if (len == 0) { - if (errno) { - posix_error(); - } - else { - result = Py_None; - Py_INCREF(Py_None); - } + errno = 0; + len = confstr(name, buffer, sizeof(buffer)); + if (len == 0) { + if (errno) { + posix_error(); } else { - if ((unsigned int)len >= sizeof(buffer)) { - result = PyString_FromStringAndSize(NULL, len-1); - if (result != NULL) - confstr(name, PyString_AS_STRING(result), len); - } - else - result = PyString_FromStringAndSize(buffer, len-1); + result = Py_None; + Py_INCREF(Py_None); + } + } + else { + if ((unsigned int)len >= sizeof(buffer)) { + result = PyString_FromStringAndSize(NULL, len-1); + if (result != NULL) + confstr(name, PyString_AS_STRING(result), len); } + else + result = PyString_FromStringAndSize(buffer, len-1); + } } return result; } @@ -7669,496 +7669,496 @@ #ifdef HAVE_SYSCONF static struct constdef posix_constants_sysconf[] = { #ifdef _SC_2_CHAR_TERM - {"SC_2_CHAR_TERM", _SC_2_CHAR_TERM}, + {"SC_2_CHAR_TERM", _SC_2_CHAR_TERM}, #endif #ifdef _SC_2_C_BIND - {"SC_2_C_BIND", _SC_2_C_BIND}, + {"SC_2_C_BIND", _SC_2_C_BIND}, #endif #ifdef _SC_2_C_DEV - {"SC_2_C_DEV", _SC_2_C_DEV}, + {"SC_2_C_DEV", _SC_2_C_DEV}, #endif #ifdef _SC_2_C_VERSION - {"SC_2_C_VERSION", _SC_2_C_VERSION}, + {"SC_2_C_VERSION", _SC_2_C_VERSION}, #endif #ifdef _SC_2_FORT_DEV - {"SC_2_FORT_DEV", _SC_2_FORT_DEV}, + {"SC_2_FORT_DEV", _SC_2_FORT_DEV}, #endif #ifdef _SC_2_FORT_RUN - {"SC_2_FORT_RUN", _SC_2_FORT_RUN}, + {"SC_2_FORT_RUN", _SC_2_FORT_RUN}, #endif #ifdef _SC_2_LOCALEDEF - {"SC_2_LOCALEDEF", _SC_2_LOCALEDEF}, + {"SC_2_LOCALEDEF", _SC_2_LOCALEDEF}, #endif #ifdef _SC_2_SW_DEV - {"SC_2_SW_DEV", _SC_2_SW_DEV}, + {"SC_2_SW_DEV", _SC_2_SW_DEV}, #endif #ifdef _SC_2_UPE - {"SC_2_UPE", _SC_2_UPE}, + {"SC_2_UPE", _SC_2_UPE}, #endif #ifdef _SC_2_VERSION - {"SC_2_VERSION", _SC_2_VERSION}, + {"SC_2_VERSION", _SC_2_VERSION}, #endif #ifdef _SC_ABI_ASYNCHRONOUS_IO - {"SC_ABI_ASYNCHRONOUS_IO", _SC_ABI_ASYNCHRONOUS_IO}, + {"SC_ABI_ASYNCHRONOUS_IO", _SC_ABI_ASYNCHRONOUS_IO}, #endif #ifdef _SC_ACL - {"SC_ACL", _SC_ACL}, + {"SC_ACL", _SC_ACL}, #endif #ifdef _SC_AIO_LISTIO_MAX - {"SC_AIO_LISTIO_MAX", _SC_AIO_LISTIO_MAX}, + {"SC_AIO_LISTIO_MAX", _SC_AIO_LISTIO_MAX}, #endif #ifdef _SC_AIO_MAX - {"SC_AIO_MAX", _SC_AIO_MAX}, + {"SC_AIO_MAX", _SC_AIO_MAX}, #endif #ifdef _SC_AIO_PRIO_DELTA_MAX - {"SC_AIO_PRIO_DELTA_MAX", _SC_AIO_PRIO_DELTA_MAX}, + {"SC_AIO_PRIO_DELTA_MAX", _SC_AIO_PRIO_DELTA_MAX}, #endif #ifdef _SC_ARG_MAX - {"SC_ARG_MAX", _SC_ARG_MAX}, + {"SC_ARG_MAX", _SC_ARG_MAX}, #endif #ifdef _SC_ASYNCHRONOUS_IO - {"SC_ASYNCHRONOUS_IO", _SC_ASYNCHRONOUS_IO}, + {"SC_ASYNCHRONOUS_IO", _SC_ASYNCHRONOUS_IO}, #endif #ifdef _SC_ATEXIT_MAX - {"SC_ATEXIT_MAX", _SC_ATEXIT_MAX}, + {"SC_ATEXIT_MAX", _SC_ATEXIT_MAX}, #endif #ifdef _SC_AUDIT - {"SC_AUDIT", _SC_AUDIT}, + {"SC_AUDIT", _SC_AUDIT}, #endif #ifdef _SC_AVPHYS_PAGES - {"SC_AVPHYS_PAGES", _SC_AVPHYS_PAGES}, + {"SC_AVPHYS_PAGES", _SC_AVPHYS_PAGES}, #endif #ifdef _SC_BC_BASE_MAX - {"SC_BC_BASE_MAX", _SC_BC_BASE_MAX}, + {"SC_BC_BASE_MAX", _SC_BC_BASE_MAX}, #endif #ifdef _SC_BC_DIM_MAX - {"SC_BC_DIM_MAX", _SC_BC_DIM_MAX}, + {"SC_BC_DIM_MAX", _SC_BC_DIM_MAX}, #endif #ifdef _SC_BC_SCALE_MAX - {"SC_BC_SCALE_MAX", _SC_BC_SCALE_MAX}, + {"SC_BC_SCALE_MAX", _SC_BC_SCALE_MAX}, #endif #ifdef _SC_BC_STRING_MAX - {"SC_BC_STRING_MAX", _SC_BC_STRING_MAX}, + {"SC_BC_STRING_MAX", _SC_BC_STRING_MAX}, #endif #ifdef _SC_CAP - {"SC_CAP", _SC_CAP}, + {"SC_CAP", _SC_CAP}, #endif #ifdef _SC_CHARCLASS_NAME_MAX - {"SC_CHARCLASS_NAME_MAX", _SC_CHARCLASS_NAME_MAX}, + {"SC_CHARCLASS_NAME_MAX", _SC_CHARCLASS_NAME_MAX}, #endif #ifdef _SC_CHAR_BIT - {"SC_CHAR_BIT", _SC_CHAR_BIT}, + {"SC_CHAR_BIT", _SC_CHAR_BIT}, #endif #ifdef _SC_CHAR_MAX - {"SC_CHAR_MAX", _SC_CHAR_MAX}, + {"SC_CHAR_MAX", _SC_CHAR_MAX}, #endif #ifdef _SC_CHAR_MIN - {"SC_CHAR_MIN", _SC_CHAR_MIN}, + {"SC_CHAR_MIN", _SC_CHAR_MIN}, #endif #ifdef _SC_CHILD_MAX - {"SC_CHILD_MAX", _SC_CHILD_MAX}, + {"SC_CHILD_MAX", _SC_CHILD_MAX}, #endif #ifdef _SC_CLK_TCK - {"SC_CLK_TCK", _SC_CLK_TCK}, + {"SC_CLK_TCK", _SC_CLK_TCK}, #endif #ifdef _SC_COHER_BLKSZ - {"SC_COHER_BLKSZ", _SC_COHER_BLKSZ}, + {"SC_COHER_BLKSZ", _SC_COHER_BLKSZ}, #endif #ifdef _SC_COLL_WEIGHTS_MAX - {"SC_COLL_WEIGHTS_MAX", _SC_COLL_WEIGHTS_MAX}, + {"SC_COLL_WEIGHTS_MAX", _SC_COLL_WEIGHTS_MAX}, #endif #ifdef _SC_DCACHE_ASSOC - {"SC_DCACHE_ASSOC", _SC_DCACHE_ASSOC}, + {"SC_DCACHE_ASSOC", _SC_DCACHE_ASSOC}, #endif #ifdef _SC_DCACHE_BLKSZ - {"SC_DCACHE_BLKSZ", _SC_DCACHE_BLKSZ}, + {"SC_DCACHE_BLKSZ", _SC_DCACHE_BLKSZ}, #endif #ifdef _SC_DCACHE_LINESZ - {"SC_DCACHE_LINESZ", _SC_DCACHE_LINESZ}, + {"SC_DCACHE_LINESZ", _SC_DCACHE_LINESZ}, #endif #ifdef _SC_DCACHE_SZ - {"SC_DCACHE_SZ", _SC_DCACHE_SZ}, + {"SC_DCACHE_SZ", _SC_DCACHE_SZ}, #endif #ifdef _SC_DCACHE_TBLKSZ - {"SC_DCACHE_TBLKSZ", _SC_DCACHE_TBLKSZ}, + {"SC_DCACHE_TBLKSZ", _SC_DCACHE_TBLKSZ}, #endif #ifdef _SC_DELAYTIMER_MAX - {"SC_DELAYTIMER_MAX", _SC_DELAYTIMER_MAX}, + {"SC_DELAYTIMER_MAX", _SC_DELAYTIMER_MAX}, #endif #ifdef _SC_EQUIV_CLASS_MAX - {"SC_EQUIV_CLASS_MAX", _SC_EQUIV_CLASS_MAX}, + {"SC_EQUIV_CLASS_MAX", _SC_EQUIV_CLASS_MAX}, #endif #ifdef _SC_EXPR_NEST_MAX - {"SC_EXPR_NEST_MAX", _SC_EXPR_NEST_MAX}, + {"SC_EXPR_NEST_MAX", _SC_EXPR_NEST_MAX}, #endif #ifdef _SC_FSYNC - {"SC_FSYNC", _SC_FSYNC}, + {"SC_FSYNC", _SC_FSYNC}, #endif #ifdef _SC_GETGR_R_SIZE_MAX - {"SC_GETGR_R_SIZE_MAX", _SC_GETGR_R_SIZE_MAX}, + {"SC_GETGR_R_SIZE_MAX", _SC_GETGR_R_SIZE_MAX}, #endif #ifdef _SC_GETPW_R_SIZE_MAX - {"SC_GETPW_R_SIZE_MAX", _SC_GETPW_R_SIZE_MAX}, + {"SC_GETPW_R_SIZE_MAX", _SC_GETPW_R_SIZE_MAX}, #endif #ifdef _SC_ICACHE_ASSOC - {"SC_ICACHE_ASSOC", _SC_ICACHE_ASSOC}, + {"SC_ICACHE_ASSOC", _SC_ICACHE_ASSOC}, #endif #ifdef _SC_ICACHE_BLKSZ - {"SC_ICACHE_BLKSZ", _SC_ICACHE_BLKSZ}, + {"SC_ICACHE_BLKSZ", _SC_ICACHE_BLKSZ}, #endif #ifdef _SC_ICACHE_LINESZ - {"SC_ICACHE_LINESZ", _SC_ICACHE_LINESZ}, + {"SC_ICACHE_LINESZ", _SC_ICACHE_LINESZ}, #endif #ifdef _SC_ICACHE_SZ - {"SC_ICACHE_SZ", _SC_ICACHE_SZ}, + {"SC_ICACHE_SZ", _SC_ICACHE_SZ}, #endif #ifdef _SC_INF - {"SC_INF", _SC_INF}, + {"SC_INF", _SC_INF}, #endif #ifdef _SC_INT_MAX - {"SC_INT_MAX", _SC_INT_MAX}, + {"SC_INT_MAX", _SC_INT_MAX}, #endif #ifdef _SC_INT_MIN - {"SC_INT_MIN", _SC_INT_MIN}, + {"SC_INT_MIN", _SC_INT_MIN}, #endif #ifdef _SC_IOV_MAX - {"SC_IOV_MAX", _SC_IOV_MAX}, + {"SC_IOV_MAX", _SC_IOV_MAX}, #endif #ifdef _SC_IP_SECOPTS - {"SC_IP_SECOPTS", _SC_IP_SECOPTS}, + {"SC_IP_SECOPTS", _SC_IP_SECOPTS}, #endif #ifdef _SC_JOB_CONTROL - {"SC_JOB_CONTROL", _SC_JOB_CONTROL}, + {"SC_JOB_CONTROL", _SC_JOB_CONTROL}, #endif #ifdef _SC_KERN_POINTERS - {"SC_KERN_POINTERS", _SC_KERN_POINTERS}, + {"SC_KERN_POINTERS", _SC_KERN_POINTERS}, #endif #ifdef _SC_KERN_SIM - {"SC_KERN_SIM", _SC_KERN_SIM}, + {"SC_KERN_SIM", _SC_KERN_SIM}, #endif #ifdef _SC_LINE_MAX - {"SC_LINE_MAX", _SC_LINE_MAX}, + {"SC_LINE_MAX", _SC_LINE_MAX}, #endif #ifdef _SC_LOGIN_NAME_MAX - {"SC_LOGIN_NAME_MAX", _SC_LOGIN_NAME_MAX}, + {"SC_LOGIN_NAME_MAX", _SC_LOGIN_NAME_MAX}, #endif #ifdef _SC_LOGNAME_MAX - {"SC_LOGNAME_MAX", _SC_LOGNAME_MAX}, + {"SC_LOGNAME_MAX", _SC_LOGNAME_MAX}, #endif #ifdef _SC_LONG_BIT - {"SC_LONG_BIT", _SC_LONG_BIT}, + {"SC_LONG_BIT", _SC_LONG_BIT}, #endif #ifdef _SC_MAC - {"SC_MAC", _SC_MAC}, + {"SC_MAC", _SC_MAC}, #endif #ifdef _SC_MAPPED_FILES - {"SC_MAPPED_FILES", _SC_MAPPED_FILES}, + {"SC_MAPPED_FILES", _SC_MAPPED_FILES}, #endif #ifdef _SC_MAXPID - {"SC_MAXPID", _SC_MAXPID}, + {"SC_MAXPID", _SC_MAXPID}, #endif #ifdef _SC_MB_LEN_MAX - {"SC_MB_LEN_MAX", _SC_MB_LEN_MAX}, + {"SC_MB_LEN_MAX", _SC_MB_LEN_MAX}, #endif #ifdef _SC_MEMLOCK - {"SC_MEMLOCK", _SC_MEMLOCK}, + {"SC_MEMLOCK", _SC_MEMLOCK}, #endif #ifdef _SC_MEMLOCK_RANGE - {"SC_MEMLOCK_RANGE", _SC_MEMLOCK_RANGE}, + {"SC_MEMLOCK_RANGE", _SC_MEMLOCK_RANGE}, #endif #ifdef _SC_MEMORY_PROTECTION - {"SC_MEMORY_PROTECTION", _SC_MEMORY_PROTECTION}, + {"SC_MEMORY_PROTECTION", _SC_MEMORY_PROTECTION}, #endif #ifdef _SC_MESSAGE_PASSING - {"SC_MESSAGE_PASSING", _SC_MESSAGE_PASSING}, + {"SC_MESSAGE_PASSING", _SC_MESSAGE_PASSING}, #endif #ifdef _SC_MMAP_FIXED_ALIGNMENT - {"SC_MMAP_FIXED_ALIGNMENT", _SC_MMAP_FIXED_ALIGNMENT}, + {"SC_MMAP_FIXED_ALIGNMENT", _SC_MMAP_FIXED_ALIGNMENT}, #endif #ifdef _SC_MQ_OPEN_MAX - {"SC_MQ_OPEN_MAX", _SC_MQ_OPEN_MAX}, + {"SC_MQ_OPEN_MAX", _SC_MQ_OPEN_MAX}, #endif #ifdef _SC_MQ_PRIO_MAX - {"SC_MQ_PRIO_MAX", _SC_MQ_PRIO_MAX}, + {"SC_MQ_PRIO_MAX", _SC_MQ_PRIO_MAX}, #endif #ifdef _SC_NACLS_MAX - {"SC_NACLS_MAX", _SC_NACLS_MAX}, + {"SC_NACLS_MAX", _SC_NACLS_MAX}, #endif #ifdef _SC_NGROUPS_MAX - {"SC_NGROUPS_MAX", _SC_NGROUPS_MAX}, + {"SC_NGROUPS_MAX", _SC_NGROUPS_MAX}, #endif #ifdef _SC_NL_ARGMAX - {"SC_NL_ARGMAX", _SC_NL_ARGMAX}, + {"SC_NL_ARGMAX", _SC_NL_ARGMAX}, #endif #ifdef _SC_NL_LANGMAX - {"SC_NL_LANGMAX", _SC_NL_LANGMAX}, + {"SC_NL_LANGMAX", _SC_NL_LANGMAX}, #endif #ifdef _SC_NL_MSGMAX - {"SC_NL_MSGMAX", _SC_NL_MSGMAX}, + {"SC_NL_MSGMAX", _SC_NL_MSGMAX}, #endif #ifdef _SC_NL_NMAX - {"SC_NL_NMAX", _SC_NL_NMAX}, + {"SC_NL_NMAX", _SC_NL_NMAX}, #endif #ifdef _SC_NL_SETMAX - {"SC_NL_SETMAX", _SC_NL_SETMAX}, + {"SC_NL_SETMAX", _SC_NL_SETMAX}, #endif #ifdef _SC_NL_TEXTMAX - {"SC_NL_TEXTMAX", _SC_NL_TEXTMAX}, + {"SC_NL_TEXTMAX", _SC_NL_TEXTMAX}, #endif #ifdef _SC_NPROCESSORS_CONF - {"SC_NPROCESSORS_CONF", _SC_NPROCESSORS_CONF}, + {"SC_NPROCESSORS_CONF", _SC_NPROCESSORS_CONF}, #endif #ifdef _SC_NPROCESSORS_ONLN - {"SC_NPROCESSORS_ONLN", _SC_NPROCESSORS_ONLN}, + {"SC_NPROCESSORS_ONLN", _SC_NPROCESSORS_ONLN}, #endif #ifdef _SC_NPROC_CONF - {"SC_NPROC_CONF", _SC_NPROC_CONF}, + {"SC_NPROC_CONF", _SC_NPROC_CONF}, #endif #ifdef _SC_NPROC_ONLN - {"SC_NPROC_ONLN", _SC_NPROC_ONLN}, + {"SC_NPROC_ONLN", _SC_NPROC_ONLN}, #endif #ifdef _SC_NZERO - {"SC_NZERO", _SC_NZERO}, + {"SC_NZERO", _SC_NZERO}, #endif #ifdef _SC_OPEN_MAX - {"SC_OPEN_MAX", _SC_OPEN_MAX}, + {"SC_OPEN_MAX", _SC_OPEN_MAX}, #endif #ifdef _SC_PAGESIZE - {"SC_PAGESIZE", _SC_PAGESIZE}, + {"SC_PAGESIZE", _SC_PAGESIZE}, #endif #ifdef _SC_PAGE_SIZE - {"SC_PAGE_SIZE", _SC_PAGE_SIZE}, + {"SC_PAGE_SIZE", _SC_PAGE_SIZE}, #endif #ifdef _SC_PASS_MAX - {"SC_PASS_MAX", _SC_PASS_MAX}, + {"SC_PASS_MAX", _SC_PASS_MAX}, #endif #ifdef _SC_PHYS_PAGES - {"SC_PHYS_PAGES", _SC_PHYS_PAGES}, + {"SC_PHYS_PAGES", _SC_PHYS_PAGES}, #endif #ifdef _SC_PII - {"SC_PII", _SC_PII}, + {"SC_PII", _SC_PII}, #endif #ifdef _SC_PII_INTERNET - {"SC_PII_INTERNET", _SC_PII_INTERNET}, + {"SC_PII_INTERNET", _SC_PII_INTERNET}, #endif #ifdef _SC_PII_INTERNET_DGRAM - {"SC_PII_INTERNET_DGRAM", _SC_PII_INTERNET_DGRAM}, + {"SC_PII_INTERNET_DGRAM", _SC_PII_INTERNET_DGRAM}, #endif #ifdef _SC_PII_INTERNET_STREAM - {"SC_PII_INTERNET_STREAM", _SC_PII_INTERNET_STREAM}, + {"SC_PII_INTERNET_STREAM", _SC_PII_INTERNET_STREAM}, #endif #ifdef _SC_PII_OSI - {"SC_PII_OSI", _SC_PII_OSI}, + {"SC_PII_OSI", _SC_PII_OSI}, #endif #ifdef _SC_PII_OSI_CLTS - {"SC_PII_OSI_CLTS", _SC_PII_OSI_CLTS}, + {"SC_PII_OSI_CLTS", _SC_PII_OSI_CLTS}, #endif #ifdef _SC_PII_OSI_COTS - {"SC_PII_OSI_COTS", _SC_PII_OSI_COTS}, + {"SC_PII_OSI_COTS", _SC_PII_OSI_COTS}, #endif #ifdef _SC_PII_OSI_M - {"SC_PII_OSI_M", _SC_PII_OSI_M}, + {"SC_PII_OSI_M", _SC_PII_OSI_M}, #endif #ifdef _SC_PII_SOCKET - {"SC_PII_SOCKET", _SC_PII_SOCKET}, + {"SC_PII_SOCKET", _SC_PII_SOCKET}, #endif #ifdef _SC_PII_XTI - {"SC_PII_XTI", _SC_PII_XTI}, + {"SC_PII_XTI", _SC_PII_XTI}, #endif #ifdef _SC_POLL - {"SC_POLL", _SC_POLL}, + {"SC_POLL", _SC_POLL}, #endif #ifdef _SC_PRIORITIZED_IO - {"SC_PRIORITIZED_IO", _SC_PRIORITIZED_IO}, + {"SC_PRIORITIZED_IO", _SC_PRIORITIZED_IO}, #endif #ifdef _SC_PRIORITY_SCHEDULING - {"SC_PRIORITY_SCHEDULING", _SC_PRIORITY_SCHEDULING}, + {"SC_PRIORITY_SCHEDULING", _SC_PRIORITY_SCHEDULING}, #endif #ifdef _SC_REALTIME_SIGNALS - {"SC_REALTIME_SIGNALS", _SC_REALTIME_SIGNALS}, + {"SC_REALTIME_SIGNALS", _SC_REALTIME_SIGNALS}, #endif #ifdef _SC_RE_DUP_MAX - {"SC_RE_DUP_MAX", _SC_RE_DUP_MAX}, + {"SC_RE_DUP_MAX", _SC_RE_DUP_MAX}, #endif #ifdef _SC_RTSIG_MAX - {"SC_RTSIG_MAX", _SC_RTSIG_MAX}, + {"SC_RTSIG_MAX", _SC_RTSIG_MAX}, #endif #ifdef _SC_SAVED_IDS - {"SC_SAVED_IDS", _SC_SAVED_IDS}, + {"SC_SAVED_IDS", _SC_SAVED_IDS}, #endif #ifdef _SC_SCHAR_MAX - {"SC_SCHAR_MAX", _SC_SCHAR_MAX}, + {"SC_SCHAR_MAX", _SC_SCHAR_MAX}, #endif #ifdef _SC_SCHAR_MIN - {"SC_SCHAR_MIN", _SC_SCHAR_MIN}, + {"SC_SCHAR_MIN", _SC_SCHAR_MIN}, #endif #ifdef _SC_SELECT - {"SC_SELECT", _SC_SELECT}, + {"SC_SELECT", _SC_SELECT}, #endif #ifdef _SC_SEMAPHORES - {"SC_SEMAPHORES", _SC_SEMAPHORES}, + {"SC_SEMAPHORES", _SC_SEMAPHORES}, #endif #ifdef _SC_SEM_NSEMS_MAX - {"SC_SEM_NSEMS_MAX", _SC_SEM_NSEMS_MAX}, + {"SC_SEM_NSEMS_MAX", _SC_SEM_NSEMS_MAX}, #endif #ifdef _SC_SEM_VALUE_MAX - {"SC_SEM_VALUE_MAX", _SC_SEM_VALUE_MAX}, + {"SC_SEM_VALUE_MAX", _SC_SEM_VALUE_MAX}, #endif #ifdef _SC_SHARED_MEMORY_OBJECTS - {"SC_SHARED_MEMORY_OBJECTS", _SC_SHARED_MEMORY_OBJECTS}, + {"SC_SHARED_MEMORY_OBJECTS", _SC_SHARED_MEMORY_OBJECTS}, #endif #ifdef _SC_SHRT_MAX - {"SC_SHRT_MAX", _SC_SHRT_MAX}, + {"SC_SHRT_MAX", _SC_SHRT_MAX}, #endif #ifdef _SC_SHRT_MIN - {"SC_SHRT_MIN", _SC_SHRT_MIN}, + {"SC_SHRT_MIN", _SC_SHRT_MIN}, #endif #ifdef _SC_SIGQUEUE_MAX - {"SC_SIGQUEUE_MAX", _SC_SIGQUEUE_MAX}, + {"SC_SIGQUEUE_MAX", _SC_SIGQUEUE_MAX}, #endif #ifdef _SC_SIGRT_MAX - {"SC_SIGRT_MAX", _SC_SIGRT_MAX}, + {"SC_SIGRT_MAX", _SC_SIGRT_MAX}, #endif #ifdef _SC_SIGRT_MIN - {"SC_SIGRT_MIN", _SC_SIGRT_MIN}, + {"SC_SIGRT_MIN", _SC_SIGRT_MIN}, #endif #ifdef _SC_SOFTPOWER - {"SC_SOFTPOWER", _SC_SOFTPOWER}, + {"SC_SOFTPOWER", _SC_SOFTPOWER}, #endif #ifdef _SC_SPLIT_CACHE - {"SC_SPLIT_CACHE", _SC_SPLIT_CACHE}, + {"SC_SPLIT_CACHE", _SC_SPLIT_CACHE}, #endif #ifdef _SC_SSIZE_MAX - {"SC_SSIZE_MAX", _SC_SSIZE_MAX}, + {"SC_SSIZE_MAX", _SC_SSIZE_MAX}, #endif #ifdef _SC_STACK_PROT - {"SC_STACK_PROT", _SC_STACK_PROT}, + {"SC_STACK_PROT", _SC_STACK_PROT}, #endif #ifdef _SC_STREAM_MAX - {"SC_STREAM_MAX", _SC_STREAM_MAX}, + {"SC_STREAM_MAX", _SC_STREAM_MAX}, #endif #ifdef _SC_SYNCHRONIZED_IO - {"SC_SYNCHRONIZED_IO", _SC_SYNCHRONIZED_IO}, + {"SC_SYNCHRONIZED_IO", _SC_SYNCHRONIZED_IO}, #endif #ifdef _SC_THREADS - {"SC_THREADS", _SC_THREADS}, + {"SC_THREADS", _SC_THREADS}, #endif #ifdef _SC_THREAD_ATTR_STACKADDR - {"SC_THREAD_ATTR_STACKADDR", _SC_THREAD_ATTR_STACKADDR}, + {"SC_THREAD_ATTR_STACKADDR", _SC_THREAD_ATTR_STACKADDR}, #endif #ifdef _SC_THREAD_ATTR_STACKSIZE - {"SC_THREAD_ATTR_STACKSIZE", _SC_THREAD_ATTR_STACKSIZE}, + {"SC_THREAD_ATTR_STACKSIZE", _SC_THREAD_ATTR_STACKSIZE}, #endif #ifdef _SC_THREAD_DESTRUCTOR_ITERATIONS - {"SC_THREAD_DESTRUCTOR_ITERATIONS", _SC_THREAD_DESTRUCTOR_ITERATIONS}, + {"SC_THREAD_DESTRUCTOR_ITERATIONS", _SC_THREAD_DESTRUCTOR_ITERATIONS}, #endif #ifdef _SC_THREAD_KEYS_MAX - {"SC_THREAD_KEYS_MAX", _SC_THREAD_KEYS_MAX}, + {"SC_THREAD_KEYS_MAX", _SC_THREAD_KEYS_MAX}, #endif #ifdef _SC_THREAD_PRIORITY_SCHEDULING - {"SC_THREAD_PRIORITY_SCHEDULING", _SC_THREAD_PRIORITY_SCHEDULING}, + {"SC_THREAD_PRIORITY_SCHEDULING", _SC_THREAD_PRIORITY_SCHEDULING}, #endif #ifdef _SC_THREAD_PRIO_INHERIT - {"SC_THREAD_PRIO_INHERIT", _SC_THREAD_PRIO_INHERIT}, + {"SC_THREAD_PRIO_INHERIT", _SC_THREAD_PRIO_INHERIT}, #endif #ifdef _SC_THREAD_PRIO_PROTECT - {"SC_THREAD_PRIO_PROTECT", _SC_THREAD_PRIO_PROTECT}, + {"SC_THREAD_PRIO_PROTECT", _SC_THREAD_PRIO_PROTECT}, #endif #ifdef _SC_THREAD_PROCESS_SHARED - {"SC_THREAD_PROCESS_SHARED", _SC_THREAD_PROCESS_SHARED}, + {"SC_THREAD_PROCESS_SHARED", _SC_THREAD_PROCESS_SHARED}, #endif #ifdef _SC_THREAD_SAFE_FUNCTIONS - {"SC_THREAD_SAFE_FUNCTIONS", _SC_THREAD_SAFE_FUNCTIONS}, + {"SC_THREAD_SAFE_FUNCTIONS", _SC_THREAD_SAFE_FUNCTIONS}, #endif #ifdef _SC_THREAD_STACK_MIN - {"SC_THREAD_STACK_MIN", _SC_THREAD_STACK_MIN}, + {"SC_THREAD_STACK_MIN", _SC_THREAD_STACK_MIN}, #endif #ifdef _SC_THREAD_THREADS_MAX - {"SC_THREAD_THREADS_MAX", _SC_THREAD_THREADS_MAX}, + {"SC_THREAD_THREADS_MAX", _SC_THREAD_THREADS_MAX}, #endif #ifdef _SC_TIMERS - {"SC_TIMERS", _SC_TIMERS}, + {"SC_TIMERS", _SC_TIMERS}, #endif #ifdef _SC_TIMER_MAX - {"SC_TIMER_MAX", _SC_TIMER_MAX}, + {"SC_TIMER_MAX", _SC_TIMER_MAX}, #endif #ifdef _SC_TTY_NAME_MAX - {"SC_TTY_NAME_MAX", _SC_TTY_NAME_MAX}, + {"SC_TTY_NAME_MAX", _SC_TTY_NAME_MAX}, #endif #ifdef _SC_TZNAME_MAX - {"SC_TZNAME_MAX", _SC_TZNAME_MAX}, + {"SC_TZNAME_MAX", _SC_TZNAME_MAX}, #endif #ifdef _SC_T_IOV_MAX - {"SC_T_IOV_MAX", _SC_T_IOV_MAX}, + {"SC_T_IOV_MAX", _SC_T_IOV_MAX}, #endif #ifdef _SC_UCHAR_MAX - {"SC_UCHAR_MAX", _SC_UCHAR_MAX}, + {"SC_UCHAR_MAX", _SC_UCHAR_MAX}, #endif #ifdef _SC_UINT_MAX - {"SC_UINT_MAX", _SC_UINT_MAX}, + {"SC_UINT_MAX", _SC_UINT_MAX}, #endif #ifdef _SC_UIO_MAXIOV - {"SC_UIO_MAXIOV", _SC_UIO_MAXIOV}, + {"SC_UIO_MAXIOV", _SC_UIO_MAXIOV}, #endif #ifdef _SC_ULONG_MAX - {"SC_ULONG_MAX", _SC_ULONG_MAX}, + {"SC_ULONG_MAX", _SC_ULONG_MAX}, #endif #ifdef _SC_USHRT_MAX - {"SC_USHRT_MAX", _SC_USHRT_MAX}, + {"SC_USHRT_MAX", _SC_USHRT_MAX}, #endif #ifdef _SC_VERSION - {"SC_VERSION", _SC_VERSION}, + {"SC_VERSION", _SC_VERSION}, #endif #ifdef _SC_WORD_BIT - {"SC_WORD_BIT", _SC_WORD_BIT}, + {"SC_WORD_BIT", _SC_WORD_BIT}, #endif #ifdef _SC_XBS5_ILP32_OFF32 - {"SC_XBS5_ILP32_OFF32", _SC_XBS5_ILP32_OFF32}, + {"SC_XBS5_ILP32_OFF32", _SC_XBS5_ILP32_OFF32}, #endif #ifdef _SC_XBS5_ILP32_OFFBIG - {"SC_XBS5_ILP32_OFFBIG", _SC_XBS5_ILP32_OFFBIG}, + {"SC_XBS5_ILP32_OFFBIG", _SC_XBS5_ILP32_OFFBIG}, #endif #ifdef _SC_XBS5_LP64_OFF64 - {"SC_XBS5_LP64_OFF64", _SC_XBS5_LP64_OFF64}, + {"SC_XBS5_LP64_OFF64", _SC_XBS5_LP64_OFF64}, #endif #ifdef _SC_XBS5_LPBIG_OFFBIG - {"SC_XBS5_LPBIG_OFFBIG", _SC_XBS5_LPBIG_OFFBIG}, + {"SC_XBS5_LPBIG_OFFBIG", _SC_XBS5_LPBIG_OFFBIG}, #endif #ifdef _SC_XOPEN_CRYPT - {"SC_XOPEN_CRYPT", _SC_XOPEN_CRYPT}, + {"SC_XOPEN_CRYPT", _SC_XOPEN_CRYPT}, #endif #ifdef _SC_XOPEN_ENH_I18N - {"SC_XOPEN_ENH_I18N", _SC_XOPEN_ENH_I18N}, + {"SC_XOPEN_ENH_I18N", _SC_XOPEN_ENH_I18N}, #endif #ifdef _SC_XOPEN_LEGACY - {"SC_XOPEN_LEGACY", _SC_XOPEN_LEGACY}, + {"SC_XOPEN_LEGACY", _SC_XOPEN_LEGACY}, #endif #ifdef _SC_XOPEN_REALTIME - {"SC_XOPEN_REALTIME", _SC_XOPEN_REALTIME}, + {"SC_XOPEN_REALTIME", _SC_XOPEN_REALTIME}, #endif #ifdef _SC_XOPEN_REALTIME_THREADS - {"SC_XOPEN_REALTIME_THREADS", _SC_XOPEN_REALTIME_THREADS}, + {"SC_XOPEN_REALTIME_THREADS", _SC_XOPEN_REALTIME_THREADS}, #endif #ifdef _SC_XOPEN_SHM - {"SC_XOPEN_SHM", _SC_XOPEN_SHM}, + {"SC_XOPEN_SHM", _SC_XOPEN_SHM}, #endif #ifdef _SC_XOPEN_UNIX - {"SC_XOPEN_UNIX", _SC_XOPEN_UNIX}, + {"SC_XOPEN_UNIX", _SC_XOPEN_UNIX}, #endif #ifdef _SC_XOPEN_VERSION - {"SC_XOPEN_VERSION", _SC_XOPEN_VERSION}, + {"SC_XOPEN_VERSION", _SC_XOPEN_VERSION}, #endif #ifdef _SC_XOPEN_XCU_VERSION - {"SC_XOPEN_XCU_VERSION", _SC_XOPEN_XCU_VERSION}, + {"SC_XOPEN_XCU_VERSION", _SC_XOPEN_XCU_VERSION}, #endif #ifdef _SC_XOPEN_XPG2 - {"SC_XOPEN_XPG2", _SC_XOPEN_XPG2}, + {"SC_XOPEN_XPG2", _SC_XOPEN_XPG2}, #endif #ifdef _SC_XOPEN_XPG3 - {"SC_XOPEN_XPG3", _SC_XOPEN_XPG3}, + {"SC_XOPEN_XPG3", _SC_XOPEN_XPG3}, #endif #ifdef _SC_XOPEN_XPG4 - {"SC_XOPEN_XPG4", _SC_XOPEN_XPG4}, + {"SC_XOPEN_XPG4", _SC_XOPEN_XPG4}, #endif }; @@ -8181,14 +8181,14 @@ int name; if (PyArg_ParseTuple(args, "O&:sysconf", conv_sysconf_confname, &name)) { - int value; + int value; - errno = 0; - value = sysconf(name); - if (value == -1 && errno != 0) - posix_error(); - else - result = PyInt_FromLong(value); + errno = 0; + value = sysconf(name); + if (value == -1 && errno != 0) + posix_error(); + else + result = PyInt_FromLong(value); } return result; } @@ -8209,16 +8209,16 @@ cmp_constdefs(const void *v1, const void *v2) { const struct constdef *c1 = - (const struct constdef *) v1; + (const struct constdef *) v1; const struct constdef *c2 = - (const struct constdef *) v2; + (const struct constdef *) v2; return strcmp(c1->name, c2->name); } static int setup_confname_table(struct constdef *table, size_t tablesize, - char *tablename, PyObject *module) + char *tablename, PyObject *module) { PyObject *d = NULL; size_t i; @@ -8226,16 +8226,16 @@ qsort(table, tablesize, sizeof(struct constdef), cmp_constdefs); d = PyDict_New(); if (d == NULL) - return -1; + return -1; for (i=0; i < tablesize; ++i) { - PyObject *o = PyInt_FromLong(table[i].value); - if (o == NULL || PyDict_SetItemString(d, table[i].name, o) == -1) { - Py_XDECREF(o); - Py_DECREF(d); - return -1; - } - Py_DECREF(o); + PyObject *o = PyInt_FromLong(table[i].value); + if (o == NULL || PyDict_SetItemString(d, table[i].name, o) == -1) { + Py_XDECREF(o); + Py_DECREF(d); + return -1; + } + Py_DECREF(o); } return PyModule_AddObject(module, tablename, d); } @@ -8249,21 +8249,21 @@ sizeof(posix_constants_pathconf) / sizeof(struct constdef), "pathconf_names", module)) - return -1; + return -1; #endif #ifdef HAVE_CONFSTR if (setup_confname_table(posix_constants_confstr, sizeof(posix_constants_confstr) / sizeof(struct constdef), "confstr_names", module)) - return -1; + return -1; #endif #ifdef HAVE_SYSCONF if (setup_confname_table(posix_constants_sysconf, sizeof(posix_constants_sysconf) / sizeof(struct constdef), "sysconf_names", module)) - return -1; + return -1; #endif return 0; } @@ -8306,59 +8306,59 @@ static PyObject * win32_startfile(PyObject *self, PyObject *args) { - char *filepath; - char *operation = NULL; - HINSTANCE rc; - - PyObject *unipath, *woperation = NULL; - if (!PyArg_ParseTuple(args, "U|s:startfile", - &unipath, &operation)) { - PyErr_Clear(); - goto normal; - } - - if (operation) { - woperation = PyUnicode_DecodeASCII(operation, - strlen(operation), NULL); - if (!woperation) { - PyErr_Clear(); - operation = NULL; - goto normal; - } - } - - Py_BEGIN_ALLOW_THREADS - rc = ShellExecuteW((HWND)0, woperation ? PyUnicode_AS_UNICODE(woperation) : 0, - PyUnicode_AS_UNICODE(unipath), - NULL, NULL, SW_SHOWNORMAL); - Py_END_ALLOW_THREADS - - Py_XDECREF(woperation); - if (rc <= (HINSTANCE)32) { - PyObject *errval = win32_error_unicode("startfile", - PyUnicode_AS_UNICODE(unipath)); - return errval; - } - Py_INCREF(Py_None); - return Py_None; + char *filepath; + char *operation = NULL; + HINSTANCE rc; + + PyObject *unipath, *woperation = NULL; + if (!PyArg_ParseTuple(args, "U|s:startfile", + &unipath, &operation)) { + PyErr_Clear(); + goto normal; + } + + if (operation) { + woperation = PyUnicode_DecodeASCII(operation, + strlen(operation), NULL); + if (!woperation) { + PyErr_Clear(); + operation = NULL; + goto normal; + } + } + + Py_BEGIN_ALLOW_THREADS + rc = ShellExecuteW((HWND)0, woperation ? PyUnicode_AS_UNICODE(woperation) : 0, + PyUnicode_AS_UNICODE(unipath), + NULL, NULL, SW_SHOWNORMAL); + Py_END_ALLOW_THREADS + + Py_XDECREF(woperation); + if (rc <= (HINSTANCE)32) { + PyObject *errval = win32_error_unicode("startfile", + PyUnicode_AS_UNICODE(unipath)); + return errval; + } + Py_INCREF(Py_None); + return Py_None; normal: - if (!PyArg_ParseTuple(args, "et|s:startfile", - Py_FileSystemDefaultEncoding, &filepath, - &operation)) - return NULL; - Py_BEGIN_ALLOW_THREADS - rc = ShellExecute((HWND)0, operation, filepath, - NULL, NULL, SW_SHOWNORMAL); - Py_END_ALLOW_THREADS - if (rc <= (HINSTANCE)32) { - PyObject *errval = win32_error("startfile", filepath); - PyMem_Free(filepath); - return errval; - } - PyMem_Free(filepath); - Py_INCREF(Py_None); - return Py_None; + if (!PyArg_ParseTuple(args, "et|s:startfile", + Py_FileSystemDefaultEncoding, &filepath, + &operation)) + return NULL; + Py_BEGIN_ALLOW_THREADS + rc = ShellExecute((HWND)0, operation, filepath, + NULL, NULL, SW_SHOWNORMAL); + Py_END_ALLOW_THREADS + if (rc <= (HINSTANCE)32) { + PyObject *errval = win32_error("startfile", filepath); + PyMem_Free(filepath); + return errval; + } + PyMem_Free(filepath); + Py_INCREF(Py_None); + return Py_None; } #endif /* MS_WINDOWS */ @@ -8374,10 +8374,10 @@ { double loadavg[3]; if (getloadavg(loadavg, 3)!=3) { - PyErr_SetString(PyExc_OSError, "Load averages are unobtainable"); - return NULL; + PyErr_SetString(PyExc_OSError, "Load averages are unobtainable"); + return NULL; } else - return Py_BuildValue("ddd", loadavg[0], loadavg[1], loadavg[2]); + return Py_BuildValue("ddd", loadavg[0], loadavg[1], loadavg[2]); } #endif @@ -8401,59 +8401,59 @@ static PyObject* win32_urandom(PyObject *self, PyObject *args) { - int howMany; - PyObject* result; + int howMany; + PyObject* result; + + /* Read arguments */ + if (! PyArg_ParseTuple(args, "i:urandom", &howMany)) + return NULL; + if (howMany < 0) + return PyErr_Format(PyExc_ValueError, + "negative argument not allowed"); + + if (hCryptProv == 0) { + HINSTANCE hAdvAPI32 = NULL; + CRYPTACQUIRECONTEXTA pCryptAcquireContext = NULL; + + /* Obtain handle to the DLL containing CryptoAPI + This should not fail */ + hAdvAPI32 = GetModuleHandle("advapi32.dll"); + if(hAdvAPI32 == NULL) + return win32_error("GetModuleHandle", NULL); + + /* Obtain pointers to the CryptoAPI functions + This will fail on some early versions of Win95 */ + pCryptAcquireContext = (CRYPTACQUIRECONTEXTA)GetProcAddress( + hAdvAPI32, + "CryptAcquireContextA"); + if (pCryptAcquireContext == NULL) + return PyErr_Format(PyExc_NotImplementedError, + "CryptAcquireContextA not found"); + + pCryptGenRandom = (CRYPTGENRANDOM)GetProcAddress( + hAdvAPI32, "CryptGenRandom"); + if (pCryptGenRandom == NULL) + return PyErr_Format(PyExc_NotImplementedError, + "CryptGenRandom not found"); + + /* Acquire context */ + if (! pCryptAcquireContext(&hCryptProv, NULL, NULL, + PROV_RSA_FULL, CRYPT_VERIFYCONTEXT)) + return win32_error("CryptAcquireContext", NULL); + } - /* Read arguments */ - if (! PyArg_ParseTuple(args, "i:urandom", &howMany)) - return NULL; - if (howMany < 0) - return PyErr_Format(PyExc_ValueError, - "negative argument not allowed"); - - if (hCryptProv == 0) { - HINSTANCE hAdvAPI32 = NULL; - CRYPTACQUIRECONTEXTA pCryptAcquireContext = NULL; - - /* Obtain handle to the DLL containing CryptoAPI - This should not fail */ - hAdvAPI32 = GetModuleHandle("advapi32.dll"); - if(hAdvAPI32 == NULL) - return win32_error("GetModuleHandle", NULL); - - /* Obtain pointers to the CryptoAPI functions - This will fail on some early versions of Win95 */ - pCryptAcquireContext = (CRYPTACQUIRECONTEXTA)GetProcAddress( - hAdvAPI32, - "CryptAcquireContextA"); - if (pCryptAcquireContext == NULL) - return PyErr_Format(PyExc_NotImplementedError, - "CryptAcquireContextA not found"); - - pCryptGenRandom = (CRYPTGENRANDOM)GetProcAddress( - hAdvAPI32, "CryptGenRandom"); - if (pCryptGenRandom == NULL) - return PyErr_Format(PyExc_NotImplementedError, - "CryptGenRandom not found"); - - /* Acquire context */ - if (! pCryptAcquireContext(&hCryptProv, NULL, NULL, - PROV_RSA_FULL, CRYPT_VERIFYCONTEXT)) - return win32_error("CryptAcquireContext", NULL); - } - - /* Allocate bytes */ - result = PyString_FromStringAndSize(NULL, howMany); - if (result != NULL) { - /* Get random data */ - memset(PyString_AS_STRING(result), 0, howMany); /* zero seed */ - if (! pCryptGenRandom(hCryptProv, howMany, (unsigned char*) - PyString_AS_STRING(result))) { - Py_DECREF(result); - return win32_error("CryptGenRandom", NULL); - } - } - return result; + /* Allocate bytes */ + result = PyString_FromStringAndSize(NULL, howMany); + if (result != NULL) { + /* Get random data */ + memset(PyString_AS_STRING(result), 0, howMany); /* zero seed */ + if (! pCryptGenRandom(hCryptProv, howMany, (unsigned char*) + PyString_AS_STRING(result))) { + Py_DECREF(result); + return win32_error("CryptGenRandom", NULL); + } + } + return result; } #endif @@ -8467,29 +8467,29 @@ static PyObject* vms_urandom(PyObject *self, PyObject *args) { - int howMany; - PyObject* result; + int howMany; + PyObject* result; - /* Read arguments */ - if (! PyArg_ParseTuple(args, "i:urandom", &howMany)) - return NULL; - if (howMany < 0) - return PyErr_Format(PyExc_ValueError, - "negative argument not allowed"); - - /* Allocate bytes */ - result = PyString_FromStringAndSize(NULL, howMany); - if (result != NULL) { - /* Get random data */ - if (RAND_pseudo_bytes((unsigned char*) - PyString_AS_STRING(result), - howMany) < 0) { - Py_DECREF(result); - return PyErr_Format(PyExc_ValueError, - "RAND_pseudo_bytes"); - } - } - return result; + /* Read arguments */ + if (! PyArg_ParseTuple(args, "i:urandom", &howMany)) + return NULL; + if (howMany < 0) + return PyErr_Format(PyExc_ValueError, + "negative argument not allowed"); + + /* Allocate bytes */ + result = PyString_FromStringAndSize(NULL, howMany); + if (result != NULL) { + /* Get random data */ + if (RAND_pseudo_bytes((unsigned char*) + PyString_AS_STRING(result), + howMany) < 0) { + Py_DECREF(result); + return PyErr_Format(PyExc_ValueError, + "RAND_pseudo_bytes"); + } + } + return result; } #endif @@ -8501,13 +8501,13 @@ static PyObject* posix_setresuid (PyObject *self, PyObject *args) { - /* We assume uid_t is no larger than a long. */ - long ruid, euid, suid; - if (!PyArg_ParseTuple(args, "lll", &ruid, &euid, &suid)) - return NULL; - if (setresuid(ruid, euid, suid) < 0) - return posix_error(); - Py_RETURN_NONE; + /* We assume uid_t is no larger than a long. */ + long ruid, euid, suid; + if (!PyArg_ParseTuple(args, "lll", &ruid, &euid, &suid)) + return NULL; + if (setresuid(ruid, euid, suid) < 0) + return posix_error(); + Py_RETURN_NONE; } #endif @@ -8519,13 +8519,13 @@ static PyObject* posix_setresgid (PyObject *self, PyObject *args) { - /* We assume uid_t is no larger than a long. */ - long rgid, egid, sgid; - if (!PyArg_ParseTuple(args, "lll", &rgid, &egid, &sgid)) - return NULL; - if (setresgid(rgid, egid, sgid) < 0) - return posix_error(); - Py_RETURN_NONE; + /* We assume uid_t is no larger than a long. */ + long rgid, egid, sgid; + if (!PyArg_ParseTuple(args, "lll", &rgid, &egid, &sgid)) + return NULL; + if (setresgid(rgid, egid, sgid) < 0) + return posix_error(); + Py_RETURN_NONE; } #endif @@ -8537,15 +8537,15 @@ static PyObject* posix_getresuid (PyObject *self, PyObject *noargs) { - uid_t ruid, euid, suid; - long l_ruid, l_euid, l_suid; - if (getresuid(&ruid, &euid, &suid) < 0) - return posix_error(); - /* Force the values into long's as we don't know the size of uid_t. */ - l_ruid = ruid; - l_euid = euid; - l_suid = suid; - return Py_BuildValue("(lll)", l_ruid, l_euid, l_suid); + uid_t ruid, euid, suid; + long l_ruid, l_euid, l_suid; + if (getresuid(&ruid, &euid, &suid) < 0) + return posix_error(); + /* Force the values into long's as we don't know the size of uid_t. */ + l_ruid = ruid; + l_euid = euid; + l_suid = suid; + return Py_BuildValue("(lll)", l_ruid, l_euid, l_suid); } #endif @@ -8557,353 +8557,353 @@ static PyObject* posix_getresgid (PyObject *self, PyObject *noargs) { - uid_t rgid, egid, sgid; - long l_rgid, l_egid, l_sgid; - if (getresgid(&rgid, &egid, &sgid) < 0) - return posix_error(); - /* Force the values into long's as we don't know the size of uid_t. */ - l_rgid = rgid; - l_egid = egid; - l_sgid = sgid; - return Py_BuildValue("(lll)", l_rgid, l_egid, l_sgid); + uid_t rgid, egid, sgid; + long l_rgid, l_egid, l_sgid; + if (getresgid(&rgid, &egid, &sgid) < 0) + return posix_error(); + /* Force the values into long's as we don't know the size of uid_t. */ + l_rgid = rgid; + l_egid = egid; + l_sgid = sgid; + return Py_BuildValue("(lll)", l_rgid, l_egid, l_sgid); } #endif static PyMethodDef posix_methods[] = { - {"access", posix_access, METH_VARARGS, posix_access__doc__}, + {"access", posix_access, METH_VARARGS, posix_access__doc__}, #ifdef HAVE_TTYNAME - {"ttyname", posix_ttyname, METH_VARARGS, posix_ttyname__doc__}, + {"ttyname", posix_ttyname, METH_VARARGS, posix_ttyname__doc__}, #endif - {"chdir", posix_chdir, METH_VARARGS, posix_chdir__doc__}, + {"chdir", posix_chdir, METH_VARARGS, posix_chdir__doc__}, #ifdef HAVE_CHFLAGS - {"chflags", posix_chflags, METH_VARARGS, posix_chflags__doc__}, + {"chflags", posix_chflags, METH_VARARGS, posix_chflags__doc__}, #endif /* HAVE_CHFLAGS */ - {"chmod", posix_chmod, METH_VARARGS, posix_chmod__doc__}, + {"chmod", posix_chmod, METH_VARARGS, posix_chmod__doc__}, #ifdef HAVE_FCHMOD - {"fchmod", posix_fchmod, METH_VARARGS, posix_fchmod__doc__}, + {"fchmod", posix_fchmod, METH_VARARGS, posix_fchmod__doc__}, #endif /* HAVE_FCHMOD */ #ifdef HAVE_CHOWN - {"chown", posix_chown, METH_VARARGS, posix_chown__doc__}, + {"chown", posix_chown, METH_VARARGS, posix_chown__doc__}, #endif /* HAVE_CHOWN */ #ifdef HAVE_LCHMOD - {"lchmod", posix_lchmod, METH_VARARGS, posix_lchmod__doc__}, + {"lchmod", posix_lchmod, METH_VARARGS, posix_lchmod__doc__}, #endif /* HAVE_LCHMOD */ #ifdef HAVE_FCHOWN - {"fchown", posix_fchown, METH_VARARGS, posix_fchown__doc__}, + {"fchown", posix_fchown, METH_VARARGS, posix_fchown__doc__}, #endif /* HAVE_FCHOWN */ #ifdef HAVE_LCHFLAGS - {"lchflags", posix_lchflags, METH_VARARGS, posix_lchflags__doc__}, + {"lchflags", posix_lchflags, METH_VARARGS, posix_lchflags__doc__}, #endif /* HAVE_LCHFLAGS */ #ifdef HAVE_LCHOWN - {"lchown", posix_lchown, METH_VARARGS, posix_lchown__doc__}, + {"lchown", posix_lchown, METH_VARARGS, posix_lchown__doc__}, #endif /* HAVE_LCHOWN */ #ifdef HAVE_CHROOT - {"chroot", posix_chroot, METH_VARARGS, posix_chroot__doc__}, + {"chroot", posix_chroot, METH_VARARGS, posix_chroot__doc__}, #endif #ifdef HAVE_CTERMID - {"ctermid", posix_ctermid, METH_NOARGS, posix_ctermid__doc__}, + {"ctermid", posix_ctermid, METH_NOARGS, posix_ctermid__doc__}, #endif #ifdef HAVE_GETCWD - {"getcwd", posix_getcwd, METH_NOARGS, posix_getcwd__doc__}, + {"getcwd", posix_getcwd, METH_NOARGS, posix_getcwd__doc__}, #ifdef Py_USING_UNICODE - {"getcwdu", posix_getcwdu, METH_NOARGS, posix_getcwdu__doc__}, + {"getcwdu", posix_getcwdu, METH_NOARGS, posix_getcwdu__doc__}, #endif #endif #ifdef HAVE_LINK - {"link", posix_link, METH_VARARGS, posix_link__doc__}, + {"link", posix_link, METH_VARARGS, posix_link__doc__}, #endif /* HAVE_LINK */ - {"listdir", posix_listdir, METH_VARARGS, posix_listdir__doc__}, - {"lstat", posix_lstat, METH_VARARGS, posix_lstat__doc__}, - {"mkdir", posix_mkdir, METH_VARARGS, posix_mkdir__doc__}, + {"listdir", posix_listdir, METH_VARARGS, posix_listdir__doc__}, + {"lstat", posix_lstat, METH_VARARGS, posix_lstat__doc__}, + {"mkdir", posix_mkdir, METH_VARARGS, posix_mkdir__doc__}, #ifdef HAVE_NICE - {"nice", posix_nice, METH_VARARGS, posix_nice__doc__}, + {"nice", posix_nice, METH_VARARGS, posix_nice__doc__}, #endif /* HAVE_NICE */ #ifdef HAVE_READLINK - {"readlink", posix_readlink, METH_VARARGS, posix_readlink__doc__}, + {"readlink", posix_readlink, METH_VARARGS, posix_readlink__doc__}, #endif /* HAVE_READLINK */ - {"rename", posix_rename, METH_VARARGS, posix_rename__doc__}, - {"rmdir", posix_rmdir, METH_VARARGS, posix_rmdir__doc__}, - {"stat", posix_stat, METH_VARARGS, posix_stat__doc__}, - {"stat_float_times", stat_float_times, METH_VARARGS, stat_float_times__doc__}, + {"rename", posix_rename, METH_VARARGS, posix_rename__doc__}, + {"rmdir", posix_rmdir, METH_VARARGS, posix_rmdir__doc__}, + {"stat", posix_stat, METH_VARARGS, posix_stat__doc__}, + {"stat_float_times", stat_float_times, METH_VARARGS, stat_float_times__doc__}, #ifdef HAVE_SYMLINK - {"symlink", posix_symlink, METH_VARARGS, posix_symlink__doc__}, + {"symlink", posix_symlink, METH_VARARGS, posix_symlink__doc__}, #endif /* HAVE_SYMLINK */ #ifdef HAVE_SYSTEM - {"system", posix_system, METH_VARARGS, posix_system__doc__}, + {"system", posix_system, METH_VARARGS, posix_system__doc__}, #endif - {"umask", posix_umask, METH_VARARGS, posix_umask__doc__}, + {"umask", posix_umask, METH_VARARGS, posix_umask__doc__}, #ifdef HAVE_UNAME - {"uname", posix_uname, METH_NOARGS, posix_uname__doc__}, + {"uname", posix_uname, METH_NOARGS, posix_uname__doc__}, #endif /* HAVE_UNAME */ - {"unlink", posix_unlink, METH_VARARGS, posix_unlink__doc__}, - {"remove", posix_unlink, METH_VARARGS, posix_remove__doc__}, - {"utime", posix_utime, METH_VARARGS, posix_utime__doc__}, + {"unlink", posix_unlink, METH_VARARGS, posix_unlink__doc__}, + {"remove", posix_unlink, METH_VARARGS, posix_remove__doc__}, + {"utime", posix_utime, METH_VARARGS, posix_utime__doc__}, #ifdef HAVE_TIMES - {"times", posix_times, METH_NOARGS, posix_times__doc__}, + {"times", posix_times, METH_NOARGS, posix_times__doc__}, #endif /* HAVE_TIMES */ - {"_exit", posix__exit, METH_VARARGS, posix__exit__doc__}, + {"_exit", posix__exit, METH_VARARGS, posix__exit__doc__}, #ifdef HAVE_EXECV - {"execv", posix_execv, METH_VARARGS, posix_execv__doc__}, - {"execve", posix_execve, METH_VARARGS, posix_execve__doc__}, + {"execv", posix_execv, METH_VARARGS, posix_execv__doc__}, + {"execve", posix_execve, METH_VARARGS, posix_execve__doc__}, #endif /* HAVE_EXECV */ #ifdef HAVE_SPAWNV - {"spawnv", posix_spawnv, METH_VARARGS, posix_spawnv__doc__}, - {"spawnve", posix_spawnve, METH_VARARGS, posix_spawnve__doc__}, + {"spawnv", posix_spawnv, METH_VARARGS, posix_spawnv__doc__}, + {"spawnve", posix_spawnve, METH_VARARGS, posix_spawnve__doc__}, #if defined(PYOS_OS2) - {"spawnvp", posix_spawnvp, METH_VARARGS, posix_spawnvp__doc__}, - {"spawnvpe", posix_spawnvpe, METH_VARARGS, posix_spawnvpe__doc__}, + {"spawnvp", posix_spawnvp, METH_VARARGS, posix_spawnvp__doc__}, + {"spawnvpe", posix_spawnvpe, METH_VARARGS, posix_spawnvpe__doc__}, #endif /* PYOS_OS2 */ #endif /* HAVE_SPAWNV */ #ifdef HAVE_FORK1 - {"fork1", posix_fork1, METH_NOARGS, posix_fork1__doc__}, + {"fork1", posix_fork1, METH_NOARGS, posix_fork1__doc__}, #endif /* HAVE_FORK1 */ #ifdef HAVE_FORK - {"fork", posix_fork, METH_NOARGS, posix_fork__doc__}, + {"fork", posix_fork, METH_NOARGS, posix_fork__doc__}, #endif /* HAVE_FORK */ #if defined(HAVE_OPENPTY) || defined(HAVE__GETPTY) || defined(HAVE_DEV_PTMX) - {"openpty", posix_openpty, METH_NOARGS, posix_openpty__doc__}, + {"openpty", posix_openpty, METH_NOARGS, posix_openpty__doc__}, #endif /* HAVE_OPENPTY || HAVE__GETPTY || HAVE_DEV_PTMX */ #ifdef HAVE_FORKPTY - {"forkpty", posix_forkpty, METH_NOARGS, posix_forkpty__doc__}, + {"forkpty", posix_forkpty, METH_NOARGS, posix_forkpty__doc__}, #endif /* HAVE_FORKPTY */ #ifdef HAVE_GETEGID - {"getegid", posix_getegid, METH_NOARGS, posix_getegid__doc__}, + {"getegid", posix_getegid, METH_NOARGS, posix_getegid__doc__}, #endif /* HAVE_GETEGID */ #ifdef HAVE_GETEUID - {"geteuid", posix_geteuid, METH_NOARGS, posix_geteuid__doc__}, + {"geteuid", posix_geteuid, METH_NOARGS, posix_geteuid__doc__}, #endif /* HAVE_GETEUID */ #ifdef HAVE_GETGID - {"getgid", posix_getgid, METH_NOARGS, posix_getgid__doc__}, + {"getgid", posix_getgid, METH_NOARGS, posix_getgid__doc__}, #endif /* HAVE_GETGID */ #ifdef HAVE_GETGROUPS - {"getgroups", posix_getgroups, METH_NOARGS, posix_getgroups__doc__}, + {"getgroups", posix_getgroups, METH_NOARGS, posix_getgroups__doc__}, #endif - {"getpid", posix_getpid, METH_NOARGS, posix_getpid__doc__}, + {"getpid", posix_getpid, METH_NOARGS, posix_getpid__doc__}, #ifdef HAVE_GETPGRP - {"getpgrp", posix_getpgrp, METH_NOARGS, posix_getpgrp__doc__}, + {"getpgrp", posix_getpgrp, METH_NOARGS, posix_getpgrp__doc__}, #endif /* HAVE_GETPGRP */ #ifdef HAVE_GETPPID - {"getppid", posix_getppid, METH_NOARGS, posix_getppid__doc__}, + {"getppid", posix_getppid, METH_NOARGS, posix_getppid__doc__}, #endif /* HAVE_GETPPID */ #ifdef HAVE_GETUID - {"getuid", posix_getuid, METH_NOARGS, posix_getuid__doc__}, + {"getuid", posix_getuid, METH_NOARGS, posix_getuid__doc__}, #endif /* HAVE_GETUID */ #ifdef HAVE_GETLOGIN - {"getlogin", posix_getlogin, METH_NOARGS, posix_getlogin__doc__}, + {"getlogin", posix_getlogin, METH_NOARGS, posix_getlogin__doc__}, #endif #ifdef HAVE_KILL - {"kill", posix_kill, METH_VARARGS, posix_kill__doc__}, + {"kill", posix_kill, METH_VARARGS, posix_kill__doc__}, #endif /* HAVE_KILL */ #ifdef HAVE_KILLPG - {"killpg", posix_killpg, METH_VARARGS, posix_killpg__doc__}, + {"killpg", posix_killpg, METH_VARARGS, posix_killpg__doc__}, #endif /* HAVE_KILLPG */ #ifdef HAVE_PLOCK - {"plock", posix_plock, METH_VARARGS, posix_plock__doc__}, + {"plock", posix_plock, METH_VARARGS, posix_plock__doc__}, #endif /* HAVE_PLOCK */ #ifdef HAVE_POPEN - {"popen", posix_popen, METH_VARARGS, posix_popen__doc__}, + {"popen", posix_popen, METH_VARARGS, posix_popen__doc__}, #ifdef MS_WINDOWS - {"popen2", win32_popen2, METH_VARARGS}, - {"popen3", win32_popen3, METH_VARARGS}, - {"popen4", win32_popen4, METH_VARARGS}, - {"startfile", win32_startfile, METH_VARARGS, win32_startfile__doc__}, - {"kill", win32_kill, METH_VARARGS, win32_kill__doc__}, + {"popen2", win32_popen2, METH_VARARGS}, + {"popen3", win32_popen3, METH_VARARGS}, + {"popen4", win32_popen4, METH_VARARGS}, + {"startfile", win32_startfile, METH_VARARGS, win32_startfile__doc__}, + {"kill", win32_kill, METH_VARARGS, win32_kill__doc__}, #else #if defined(PYOS_OS2) && defined(PYCC_GCC) - {"popen2", os2emx_popen2, METH_VARARGS}, - {"popen3", os2emx_popen3, METH_VARARGS}, - {"popen4", os2emx_popen4, METH_VARARGS}, + {"popen2", os2emx_popen2, METH_VARARGS}, + {"popen3", os2emx_popen3, METH_VARARGS}, + {"popen4", os2emx_popen4, METH_VARARGS}, #endif #endif #endif /* HAVE_POPEN */ #ifdef HAVE_SETUID - {"setuid", posix_setuid, METH_VARARGS, posix_setuid__doc__}, + {"setuid", posix_setuid, METH_VARARGS, posix_setuid__doc__}, #endif /* HAVE_SETUID */ #ifdef HAVE_SETEUID - {"seteuid", posix_seteuid, METH_VARARGS, posix_seteuid__doc__}, + {"seteuid", posix_seteuid, METH_VARARGS, posix_seteuid__doc__}, #endif /* HAVE_SETEUID */ #ifdef HAVE_SETEGID - {"setegid", posix_setegid, METH_VARARGS, posix_setegid__doc__}, + {"setegid", posix_setegid, METH_VARARGS, posix_setegid__doc__}, #endif /* HAVE_SETEGID */ #ifdef HAVE_SETREUID - {"setreuid", posix_setreuid, METH_VARARGS, posix_setreuid__doc__}, + {"setreuid", posix_setreuid, METH_VARARGS, posix_setreuid__doc__}, #endif /* HAVE_SETREUID */ #ifdef HAVE_SETREGID - {"setregid", posix_setregid, METH_VARARGS, posix_setregid__doc__}, + {"setregid", posix_setregid, METH_VARARGS, posix_setregid__doc__}, #endif /* HAVE_SETREGID */ #ifdef HAVE_SETGID - {"setgid", posix_setgid, METH_VARARGS, posix_setgid__doc__}, + {"setgid", posix_setgid, METH_VARARGS, posix_setgid__doc__}, #endif /* HAVE_SETGID */ #ifdef HAVE_SETGROUPS - {"setgroups", posix_setgroups, METH_O, posix_setgroups__doc__}, + {"setgroups", posix_setgroups, METH_O, posix_setgroups__doc__}, #endif /* HAVE_SETGROUPS */ #ifdef HAVE_INITGROUPS - {"initgroups", posix_initgroups, METH_VARARGS, posix_initgroups__doc__}, + {"initgroups", posix_initgroups, METH_VARARGS, posix_initgroups__doc__}, #endif /* HAVE_INITGROUPS */ #ifdef HAVE_GETPGID - {"getpgid", posix_getpgid, METH_VARARGS, posix_getpgid__doc__}, + {"getpgid", posix_getpgid, METH_VARARGS, posix_getpgid__doc__}, #endif /* HAVE_GETPGID */ #ifdef HAVE_SETPGRP - {"setpgrp", posix_setpgrp, METH_NOARGS, posix_setpgrp__doc__}, + {"setpgrp", posix_setpgrp, METH_NOARGS, posix_setpgrp__doc__}, #endif /* HAVE_SETPGRP */ #ifdef HAVE_WAIT - {"wait", posix_wait, METH_NOARGS, posix_wait__doc__}, + {"wait", posix_wait, METH_NOARGS, posix_wait__doc__}, #endif /* HAVE_WAIT */ #ifdef HAVE_WAIT3 - {"wait3", posix_wait3, METH_VARARGS, posix_wait3__doc__}, + {"wait3", posix_wait3, METH_VARARGS, posix_wait3__doc__}, #endif /* HAVE_WAIT3 */ #ifdef HAVE_WAIT4 - {"wait4", posix_wait4, METH_VARARGS, posix_wait4__doc__}, + {"wait4", posix_wait4, METH_VARARGS, posix_wait4__doc__}, #endif /* HAVE_WAIT4 */ #if defined(HAVE_WAITPID) || defined(HAVE_CWAIT) - {"waitpid", posix_waitpid, METH_VARARGS, posix_waitpid__doc__}, + {"waitpid", posix_waitpid, METH_VARARGS, posix_waitpid__doc__}, #endif /* HAVE_WAITPID */ #ifdef HAVE_GETSID - {"getsid", posix_getsid, METH_VARARGS, posix_getsid__doc__}, + {"getsid", posix_getsid, METH_VARARGS, posix_getsid__doc__}, #endif /* HAVE_GETSID */ #ifdef HAVE_SETSID - {"setsid", posix_setsid, METH_NOARGS, posix_setsid__doc__}, + {"setsid", posix_setsid, METH_NOARGS, posix_setsid__doc__}, #endif /* HAVE_SETSID */ #ifdef HAVE_SETPGID - {"setpgid", posix_setpgid, METH_VARARGS, posix_setpgid__doc__}, + {"setpgid", posix_setpgid, METH_VARARGS, posix_setpgid__doc__}, #endif /* HAVE_SETPGID */ #ifdef HAVE_TCGETPGRP - {"tcgetpgrp", posix_tcgetpgrp, METH_VARARGS, posix_tcgetpgrp__doc__}, + {"tcgetpgrp", posix_tcgetpgrp, METH_VARARGS, posix_tcgetpgrp__doc__}, #endif /* HAVE_TCGETPGRP */ #ifdef HAVE_TCSETPGRP - {"tcsetpgrp", posix_tcsetpgrp, METH_VARARGS, posix_tcsetpgrp__doc__}, + {"tcsetpgrp", posix_tcsetpgrp, METH_VARARGS, posix_tcsetpgrp__doc__}, #endif /* HAVE_TCSETPGRP */ - {"open", posix_open, METH_VARARGS, posix_open__doc__}, - {"close", posix_close, METH_VARARGS, posix_close__doc__}, - {"closerange", posix_closerange, METH_VARARGS, posix_closerange__doc__}, - {"dup", posix_dup, METH_VARARGS, posix_dup__doc__}, - {"dup2", posix_dup2, METH_VARARGS, posix_dup2__doc__}, - {"lseek", posix_lseek, METH_VARARGS, posix_lseek__doc__}, - {"read", posix_read, METH_VARARGS, posix_read__doc__}, - {"write", posix_write, METH_VARARGS, posix_write__doc__}, - {"fstat", posix_fstat, METH_VARARGS, posix_fstat__doc__}, - {"fdopen", posix_fdopen, METH_VARARGS, posix_fdopen__doc__}, - {"isatty", posix_isatty, METH_VARARGS, posix_isatty__doc__}, + {"open", posix_open, METH_VARARGS, posix_open__doc__}, + {"close", posix_close, METH_VARARGS, posix_close__doc__}, + {"closerange", posix_closerange, METH_VARARGS, posix_closerange__doc__}, + {"dup", posix_dup, METH_VARARGS, posix_dup__doc__}, + {"dup2", posix_dup2, METH_VARARGS, posix_dup2__doc__}, + {"lseek", posix_lseek, METH_VARARGS, posix_lseek__doc__}, + {"read", posix_read, METH_VARARGS, posix_read__doc__}, + {"write", posix_write, METH_VARARGS, posix_write__doc__}, + {"fstat", posix_fstat, METH_VARARGS, posix_fstat__doc__}, + {"fdopen", posix_fdopen, METH_VARARGS, posix_fdopen__doc__}, + {"isatty", posix_isatty, METH_VARARGS, posix_isatty__doc__}, #ifdef HAVE_PIPE - {"pipe", posix_pipe, METH_NOARGS, posix_pipe__doc__}, + {"pipe", posix_pipe, METH_NOARGS, posix_pipe__doc__}, #endif #ifdef HAVE_MKFIFO - {"mkfifo", posix_mkfifo, METH_VARARGS, posix_mkfifo__doc__}, + {"mkfifo", posix_mkfifo, METH_VARARGS, posix_mkfifo__doc__}, #endif #if defined(HAVE_MKNOD) && defined(HAVE_MAKEDEV) - {"mknod", posix_mknod, METH_VARARGS, posix_mknod__doc__}, + {"mknod", posix_mknod, METH_VARARGS, posix_mknod__doc__}, #endif #ifdef HAVE_DEVICE_MACROS - {"major", posix_major, METH_VARARGS, posix_major__doc__}, - {"minor", posix_minor, METH_VARARGS, posix_minor__doc__}, - {"makedev", posix_makedev, METH_VARARGS, posix_makedev__doc__}, + {"major", posix_major, METH_VARARGS, posix_major__doc__}, + {"minor", posix_minor, METH_VARARGS, posix_minor__doc__}, + {"makedev", posix_makedev, METH_VARARGS, posix_makedev__doc__}, #endif #ifdef HAVE_FTRUNCATE - {"ftruncate", posix_ftruncate, METH_VARARGS, posix_ftruncate__doc__}, + {"ftruncate", posix_ftruncate, METH_VARARGS, posix_ftruncate__doc__}, #endif #ifdef HAVE_PUTENV - {"putenv", posix_putenv, METH_VARARGS, posix_putenv__doc__}, + {"putenv", posix_putenv, METH_VARARGS, posix_putenv__doc__}, #endif #ifdef HAVE_UNSETENV - {"unsetenv", posix_unsetenv, METH_VARARGS, posix_unsetenv__doc__}, + {"unsetenv", posix_unsetenv, METH_VARARGS, posix_unsetenv__doc__}, #endif - {"strerror", posix_strerror, METH_VARARGS, posix_strerror__doc__}, + {"strerror", posix_strerror, METH_VARARGS, posix_strerror__doc__}, #ifdef HAVE_FCHDIR - {"fchdir", posix_fchdir, METH_O, posix_fchdir__doc__}, + {"fchdir", posix_fchdir, METH_O, posix_fchdir__doc__}, #endif #ifdef HAVE_FSYNC - {"fsync", posix_fsync, METH_O, posix_fsync__doc__}, + {"fsync", posix_fsync, METH_O, posix_fsync__doc__}, #endif #ifdef HAVE_FDATASYNC - {"fdatasync", posix_fdatasync, METH_O, posix_fdatasync__doc__}, + {"fdatasync", posix_fdatasync, METH_O, posix_fdatasync__doc__}, #endif #ifdef HAVE_SYS_WAIT_H #ifdef WCOREDUMP - {"WCOREDUMP", posix_WCOREDUMP, METH_VARARGS, posix_WCOREDUMP__doc__}, + {"WCOREDUMP", posix_WCOREDUMP, METH_VARARGS, posix_WCOREDUMP__doc__}, #endif /* WCOREDUMP */ #ifdef WIFCONTINUED - {"WIFCONTINUED",posix_WIFCONTINUED, METH_VARARGS, posix_WIFCONTINUED__doc__}, + {"WIFCONTINUED",posix_WIFCONTINUED, METH_VARARGS, posix_WIFCONTINUED__doc__}, #endif /* WIFCONTINUED */ #ifdef WIFSTOPPED - {"WIFSTOPPED", posix_WIFSTOPPED, METH_VARARGS, posix_WIFSTOPPED__doc__}, + {"WIFSTOPPED", posix_WIFSTOPPED, METH_VARARGS, posix_WIFSTOPPED__doc__}, #endif /* WIFSTOPPED */ #ifdef WIFSIGNALED - {"WIFSIGNALED", posix_WIFSIGNALED, METH_VARARGS, posix_WIFSIGNALED__doc__}, + {"WIFSIGNALED", posix_WIFSIGNALED, METH_VARARGS, posix_WIFSIGNALED__doc__}, #endif /* WIFSIGNALED */ #ifdef WIFEXITED - {"WIFEXITED", posix_WIFEXITED, METH_VARARGS, posix_WIFEXITED__doc__}, + {"WIFEXITED", posix_WIFEXITED, METH_VARARGS, posix_WIFEXITED__doc__}, #endif /* WIFEXITED */ #ifdef WEXITSTATUS - {"WEXITSTATUS", posix_WEXITSTATUS, METH_VARARGS, posix_WEXITSTATUS__doc__}, + {"WEXITSTATUS", posix_WEXITSTATUS, METH_VARARGS, posix_WEXITSTATUS__doc__}, #endif /* WEXITSTATUS */ #ifdef WTERMSIG - {"WTERMSIG", posix_WTERMSIG, METH_VARARGS, posix_WTERMSIG__doc__}, + {"WTERMSIG", posix_WTERMSIG, METH_VARARGS, posix_WTERMSIG__doc__}, #endif /* WTERMSIG */ #ifdef WSTOPSIG - {"WSTOPSIG", posix_WSTOPSIG, METH_VARARGS, posix_WSTOPSIG__doc__}, + {"WSTOPSIG", posix_WSTOPSIG, METH_VARARGS, posix_WSTOPSIG__doc__}, #endif /* WSTOPSIG */ #endif /* HAVE_SYS_WAIT_H */ #if defined(HAVE_FSTATVFS) && defined(HAVE_SYS_STATVFS_H) - {"fstatvfs", posix_fstatvfs, METH_VARARGS, posix_fstatvfs__doc__}, + {"fstatvfs", posix_fstatvfs, METH_VARARGS, posix_fstatvfs__doc__}, #endif #if defined(HAVE_STATVFS) && defined(HAVE_SYS_STATVFS_H) - {"statvfs", posix_statvfs, METH_VARARGS, posix_statvfs__doc__}, + {"statvfs", posix_statvfs, METH_VARARGS, posix_statvfs__doc__}, #endif #ifdef HAVE_TMPFILE - {"tmpfile", posix_tmpfile, METH_NOARGS, posix_tmpfile__doc__}, + {"tmpfile", posix_tmpfile, METH_NOARGS, posix_tmpfile__doc__}, #endif #ifdef HAVE_TEMPNAM - {"tempnam", posix_tempnam, METH_VARARGS, posix_tempnam__doc__}, + {"tempnam", posix_tempnam, METH_VARARGS, posix_tempnam__doc__}, #endif #ifdef HAVE_TMPNAM - {"tmpnam", posix_tmpnam, METH_NOARGS, posix_tmpnam__doc__}, + {"tmpnam", posix_tmpnam, METH_NOARGS, posix_tmpnam__doc__}, #endif #ifdef HAVE_CONFSTR - {"confstr", posix_confstr, METH_VARARGS, posix_confstr__doc__}, + {"confstr", posix_confstr, METH_VARARGS, posix_confstr__doc__}, #endif #ifdef HAVE_SYSCONF - {"sysconf", posix_sysconf, METH_VARARGS, posix_sysconf__doc__}, + {"sysconf", posix_sysconf, METH_VARARGS, posix_sysconf__doc__}, #endif #ifdef HAVE_FPATHCONF - {"fpathconf", posix_fpathconf, METH_VARARGS, posix_fpathconf__doc__}, + {"fpathconf", posix_fpathconf, METH_VARARGS, posix_fpathconf__doc__}, #endif #ifdef HAVE_PATHCONF - {"pathconf", posix_pathconf, METH_VARARGS, posix_pathconf__doc__}, + {"pathconf", posix_pathconf, METH_VARARGS, posix_pathconf__doc__}, #endif - {"abort", posix_abort, METH_NOARGS, posix_abort__doc__}, + {"abort", posix_abort, METH_NOARGS, posix_abort__doc__}, #ifdef MS_WINDOWS - {"_getfullpathname", posix__getfullpathname, METH_VARARGS, NULL}, + {"_getfullpathname", posix__getfullpathname, METH_VARARGS, NULL}, #endif #ifdef HAVE_GETLOADAVG - {"getloadavg", posix_getloadavg, METH_NOARGS, posix_getloadavg__doc__}, + {"getloadavg", posix_getloadavg, METH_NOARGS, posix_getloadavg__doc__}, #endif #ifdef MS_WINDOWS - {"urandom", win32_urandom, METH_VARARGS, win32_urandom__doc__}, + {"urandom", win32_urandom, METH_VARARGS, win32_urandom__doc__}, #endif #ifdef __VMS - {"urandom", vms_urandom, METH_VARARGS, vms_urandom__doc__}, + {"urandom", vms_urandom, METH_VARARGS, vms_urandom__doc__}, #endif #ifdef HAVE_SETRESUID - {"setresuid", posix_setresuid, METH_VARARGS, posix_setresuid__doc__}, + {"setresuid", posix_setresuid, METH_VARARGS, posix_setresuid__doc__}, #endif #ifdef HAVE_SETRESGID - {"setresgid", posix_setresgid, METH_VARARGS, posix_setresgid__doc__}, + {"setresgid", posix_setresgid, METH_VARARGS, posix_setresgid__doc__}, #endif #ifdef HAVE_GETRESUID - {"getresuid", posix_getresuid, METH_NOARGS, posix_getresuid__doc__}, + {"getresuid", posix_getresuid, METH_NOARGS, posix_getresuid__doc__}, #endif #ifdef HAVE_GETRESGID - {"getresgid", posix_getresgid, METH_NOARGS, posix_getresgid__doc__}, + {"getresgid", posix_getresgid, METH_NOARGS, posix_getresgid__doc__}, #endif - {NULL, NULL} /* Sentinel */ + {NULL, NULL} /* Sentinel */ }; static int ins(PyObject *module, char *symbol, long value) { - return PyModule_AddIntConstant(module, symbol, value); + return PyModule_AddIntConstant(module, symbol, value); } #if defined(PYOS_OS2) @@ -8941,7 +8941,7 @@ case 50: ver = "5.00"; break; default: PyOS_snprintf(tmp, sizeof(tmp), - "%d-%d", values[QSV_VERSION_MAJOR], + "%d-%d", values[QSV_VERSION_MAJOR], values[QSV_VERSION_MINOR]); ver = &tmp[0]; } @@ -8963,221 +8963,221 @@ all_ins(PyObject *d) { #ifdef F_OK - if (ins(d, "F_OK", (long)F_OK)) return -1; + if (ins(d, "F_OK", (long)F_OK)) return -1; #endif #ifdef R_OK - if (ins(d, "R_OK", (long)R_OK)) return -1; + if (ins(d, "R_OK", (long)R_OK)) return -1; #endif #ifdef W_OK - if (ins(d, "W_OK", (long)W_OK)) return -1; + if (ins(d, "W_OK", (long)W_OK)) return -1; #endif #ifdef X_OK - if (ins(d, "X_OK", (long)X_OK)) return -1; + if (ins(d, "X_OK", (long)X_OK)) return -1; #endif #ifdef NGROUPS_MAX - if (ins(d, "NGROUPS_MAX", (long)NGROUPS_MAX)) return -1; + if (ins(d, "NGROUPS_MAX", (long)NGROUPS_MAX)) return -1; #endif #ifdef TMP_MAX - if (ins(d, "TMP_MAX", (long)TMP_MAX)) return -1; + if (ins(d, "TMP_MAX", (long)TMP_MAX)) return -1; #endif #ifdef WCONTINUED - if (ins(d, "WCONTINUED", (long)WCONTINUED)) return -1; + if (ins(d, "WCONTINUED", (long)WCONTINUED)) return -1; #endif #ifdef WNOHANG - if (ins(d, "WNOHANG", (long)WNOHANG)) return -1; + if (ins(d, "WNOHANG", (long)WNOHANG)) return -1; #endif #ifdef WUNTRACED - if (ins(d, "WUNTRACED", (long)WUNTRACED)) return -1; + if (ins(d, "WUNTRACED", (long)WUNTRACED)) return -1; #endif #ifdef O_RDONLY - if (ins(d, "O_RDONLY", (long)O_RDONLY)) return -1; + if (ins(d, "O_RDONLY", (long)O_RDONLY)) return -1; #endif #ifdef O_WRONLY - if (ins(d, "O_WRONLY", (long)O_WRONLY)) return -1; + if (ins(d, "O_WRONLY", (long)O_WRONLY)) return -1; #endif #ifdef O_RDWR - if (ins(d, "O_RDWR", (long)O_RDWR)) return -1; + if (ins(d, "O_RDWR", (long)O_RDWR)) return -1; #endif #ifdef O_NDELAY - if (ins(d, "O_NDELAY", (long)O_NDELAY)) return -1; + if (ins(d, "O_NDELAY", (long)O_NDELAY)) return -1; #endif #ifdef O_NONBLOCK - if (ins(d, "O_NONBLOCK", (long)O_NONBLOCK)) return -1; + if (ins(d, "O_NONBLOCK", (long)O_NONBLOCK)) return -1; #endif #ifdef O_APPEND - if (ins(d, "O_APPEND", (long)O_APPEND)) return -1; + if (ins(d, "O_APPEND", (long)O_APPEND)) return -1; #endif #ifdef O_DSYNC - if (ins(d, "O_DSYNC", (long)O_DSYNC)) return -1; + if (ins(d, "O_DSYNC", (long)O_DSYNC)) return -1; #endif #ifdef O_RSYNC - if (ins(d, "O_RSYNC", (long)O_RSYNC)) return -1; + if (ins(d, "O_RSYNC", (long)O_RSYNC)) return -1; #endif #ifdef O_SYNC - if (ins(d, "O_SYNC", (long)O_SYNC)) return -1; + if (ins(d, "O_SYNC", (long)O_SYNC)) return -1; #endif #ifdef O_NOCTTY - if (ins(d, "O_NOCTTY", (long)O_NOCTTY)) return -1; + if (ins(d, "O_NOCTTY", (long)O_NOCTTY)) return -1; #endif #ifdef O_CREAT - if (ins(d, "O_CREAT", (long)O_CREAT)) return -1; + if (ins(d, "O_CREAT", (long)O_CREAT)) return -1; #endif #ifdef O_EXCL - if (ins(d, "O_EXCL", (long)O_EXCL)) return -1; + if (ins(d, "O_EXCL", (long)O_EXCL)) return -1; #endif #ifdef O_TRUNC - if (ins(d, "O_TRUNC", (long)O_TRUNC)) return -1; + if (ins(d, "O_TRUNC", (long)O_TRUNC)) return -1; #endif #ifdef O_BINARY - if (ins(d, "O_BINARY", (long)O_BINARY)) return -1; + if (ins(d, "O_BINARY", (long)O_BINARY)) return -1; #endif #ifdef O_TEXT - if (ins(d, "O_TEXT", (long)O_TEXT)) return -1; + if (ins(d, "O_TEXT", (long)O_TEXT)) return -1; #endif #ifdef O_LARGEFILE - if (ins(d, "O_LARGEFILE", (long)O_LARGEFILE)) return -1; + if (ins(d, "O_LARGEFILE", (long)O_LARGEFILE)) return -1; #endif #ifdef O_SHLOCK - if (ins(d, "O_SHLOCK", (long)O_SHLOCK)) return -1; + if (ins(d, "O_SHLOCK", (long)O_SHLOCK)) return -1; #endif #ifdef O_EXLOCK - if (ins(d, "O_EXLOCK", (long)O_EXLOCK)) return -1; + if (ins(d, "O_EXLOCK", (long)O_EXLOCK)) return -1; #endif /* MS Windows */ #ifdef O_NOINHERIT - /* Don't inherit in child processes. */ - if (ins(d, "O_NOINHERIT", (long)O_NOINHERIT)) return -1; + /* Don't inherit in child processes. */ + if (ins(d, "O_NOINHERIT", (long)O_NOINHERIT)) return -1; #endif #ifdef _O_SHORT_LIVED - /* Optimize for short life (keep in memory). */ - /* MS forgot to define this one with a non-underscore form too. */ - if (ins(d, "O_SHORT_LIVED", (long)_O_SHORT_LIVED)) return -1; + /* Optimize for short life (keep in memory). */ + /* MS forgot to define this one with a non-underscore form too. */ + if (ins(d, "O_SHORT_LIVED", (long)_O_SHORT_LIVED)) return -1; #endif #ifdef O_TEMPORARY - /* Automatically delete when last handle is closed. */ - if (ins(d, "O_TEMPORARY", (long)O_TEMPORARY)) return -1; + /* Automatically delete when last handle is closed. */ + if (ins(d, "O_TEMPORARY", (long)O_TEMPORARY)) return -1; #endif #ifdef O_RANDOM - /* Optimize for random access. */ - if (ins(d, "O_RANDOM", (long)O_RANDOM)) return -1; + /* Optimize for random access. */ + if (ins(d, "O_RANDOM", (long)O_RANDOM)) return -1; #endif #ifdef O_SEQUENTIAL - /* Optimize for sequential access. */ - if (ins(d, "O_SEQUENTIAL", (long)O_SEQUENTIAL)) return -1; + /* Optimize for sequential access. */ + if (ins(d, "O_SEQUENTIAL", (long)O_SEQUENTIAL)) return -1; #endif /* GNU extensions. */ #ifdef O_ASYNC - /* Send a SIGIO signal whenever input or output - becomes available on file descriptor */ - if (ins(d, "O_ASYNC", (long)O_ASYNC)) return -1; + /* Send a SIGIO signal whenever input or output + becomes available on file descriptor */ + if (ins(d, "O_ASYNC", (long)O_ASYNC)) return -1; #endif #ifdef O_DIRECT - /* Direct disk access. */ - if (ins(d, "O_DIRECT", (long)O_DIRECT)) return -1; + /* Direct disk access. */ + if (ins(d, "O_DIRECT", (long)O_DIRECT)) return -1; #endif #ifdef O_DIRECTORY - /* Must be a directory. */ - if (ins(d, "O_DIRECTORY", (long)O_DIRECTORY)) return -1; + /* Must be a directory. */ + if (ins(d, "O_DIRECTORY", (long)O_DIRECTORY)) return -1; #endif #ifdef O_NOFOLLOW - /* Do not follow links. */ - if (ins(d, "O_NOFOLLOW", (long)O_NOFOLLOW)) return -1; + /* Do not follow links. */ + if (ins(d, "O_NOFOLLOW", (long)O_NOFOLLOW)) return -1; #endif #ifdef O_NOATIME - /* Do not update the access time. */ - if (ins(d, "O_NOATIME", (long)O_NOATIME)) return -1; + /* Do not update the access time. */ + if (ins(d, "O_NOATIME", (long)O_NOATIME)) return -1; #endif - /* These come from sysexits.h */ + /* These come from sysexits.h */ #ifdef EX_OK - if (ins(d, "EX_OK", (long)EX_OK)) return -1; + if (ins(d, "EX_OK", (long)EX_OK)) return -1; #endif /* EX_OK */ #ifdef EX_USAGE - if (ins(d, "EX_USAGE", (long)EX_USAGE)) return -1; + if (ins(d, "EX_USAGE", (long)EX_USAGE)) return -1; #endif /* EX_USAGE */ #ifdef EX_DATAERR - if (ins(d, "EX_DATAERR", (long)EX_DATAERR)) return -1; + if (ins(d, "EX_DATAERR", (long)EX_DATAERR)) return -1; #endif /* EX_DATAERR */ #ifdef EX_NOINPUT - if (ins(d, "EX_NOINPUT", (long)EX_NOINPUT)) return -1; + if (ins(d, "EX_NOINPUT", (long)EX_NOINPUT)) return -1; #endif /* EX_NOINPUT */ #ifdef EX_NOUSER - if (ins(d, "EX_NOUSER", (long)EX_NOUSER)) return -1; + if (ins(d, "EX_NOUSER", (long)EX_NOUSER)) return -1; #endif /* EX_NOUSER */ #ifdef EX_NOHOST - if (ins(d, "EX_NOHOST", (long)EX_NOHOST)) return -1; + if (ins(d, "EX_NOHOST", (long)EX_NOHOST)) return -1; #endif /* EX_NOHOST */ #ifdef EX_UNAVAILABLE - if (ins(d, "EX_UNAVAILABLE", (long)EX_UNAVAILABLE)) return -1; + if (ins(d, "EX_UNAVAILABLE", (long)EX_UNAVAILABLE)) return -1; #endif /* EX_UNAVAILABLE */ #ifdef EX_SOFTWARE - if (ins(d, "EX_SOFTWARE", (long)EX_SOFTWARE)) return -1; + if (ins(d, "EX_SOFTWARE", (long)EX_SOFTWARE)) return -1; #endif /* EX_SOFTWARE */ #ifdef EX_OSERR - if (ins(d, "EX_OSERR", (long)EX_OSERR)) return -1; + if (ins(d, "EX_OSERR", (long)EX_OSERR)) return -1; #endif /* EX_OSERR */ #ifdef EX_OSFILE - if (ins(d, "EX_OSFILE", (long)EX_OSFILE)) return -1; + if (ins(d, "EX_OSFILE", (long)EX_OSFILE)) return -1; #endif /* EX_OSFILE */ #ifdef EX_CANTCREAT - if (ins(d, "EX_CANTCREAT", (long)EX_CANTCREAT)) return -1; + if (ins(d, "EX_CANTCREAT", (long)EX_CANTCREAT)) return -1; #endif /* EX_CANTCREAT */ #ifdef EX_IOERR - if (ins(d, "EX_IOERR", (long)EX_IOERR)) return -1; + if (ins(d, "EX_IOERR", (long)EX_IOERR)) return -1; #endif /* EX_IOERR */ #ifdef EX_TEMPFAIL - if (ins(d, "EX_TEMPFAIL", (long)EX_TEMPFAIL)) return -1; + if (ins(d, "EX_TEMPFAIL", (long)EX_TEMPFAIL)) return -1; #endif /* EX_TEMPFAIL */ #ifdef EX_PROTOCOL - if (ins(d, "EX_PROTOCOL", (long)EX_PROTOCOL)) return -1; + if (ins(d, "EX_PROTOCOL", (long)EX_PROTOCOL)) return -1; #endif /* EX_PROTOCOL */ #ifdef EX_NOPERM - if (ins(d, "EX_NOPERM", (long)EX_NOPERM)) return -1; + if (ins(d, "EX_NOPERM", (long)EX_NOPERM)) return -1; #endif /* EX_NOPERM */ #ifdef EX_CONFIG - if (ins(d, "EX_CONFIG", (long)EX_CONFIG)) return -1; + if (ins(d, "EX_CONFIG", (long)EX_CONFIG)) return -1; #endif /* EX_CONFIG */ #ifdef EX_NOTFOUND - if (ins(d, "EX_NOTFOUND", (long)EX_NOTFOUND)) return -1; + if (ins(d, "EX_NOTFOUND", (long)EX_NOTFOUND)) return -1; #endif /* EX_NOTFOUND */ #ifdef HAVE_SPAWNV #if defined(PYOS_OS2) && defined(PYCC_GCC) - if (ins(d, "P_WAIT", (long)P_WAIT)) return -1; - if (ins(d, "P_NOWAIT", (long)P_NOWAIT)) return -1; - if (ins(d, "P_OVERLAY", (long)P_OVERLAY)) return -1; - if (ins(d, "P_DEBUG", (long)P_DEBUG)) return -1; - if (ins(d, "P_SESSION", (long)P_SESSION)) return -1; - if (ins(d, "P_DETACH", (long)P_DETACH)) return -1; - if (ins(d, "P_PM", (long)P_PM)) return -1; - if (ins(d, "P_DEFAULT", (long)P_DEFAULT)) return -1; - if (ins(d, "P_MINIMIZE", (long)P_MINIMIZE)) return -1; - if (ins(d, "P_MAXIMIZE", (long)P_MAXIMIZE)) return -1; - if (ins(d, "P_FULLSCREEN", (long)P_FULLSCREEN)) return -1; - if (ins(d, "P_WINDOWED", (long)P_WINDOWED)) return -1; - if (ins(d, "P_FOREGROUND", (long)P_FOREGROUND)) return -1; - if (ins(d, "P_BACKGROUND", (long)P_BACKGROUND)) return -1; - if (ins(d, "P_NOCLOSE", (long)P_NOCLOSE)) return -1; - if (ins(d, "P_NOSESSION", (long)P_NOSESSION)) return -1; - if (ins(d, "P_QUOTE", (long)P_QUOTE)) return -1; - if (ins(d, "P_TILDE", (long)P_TILDE)) return -1; - if (ins(d, "P_UNRELATED", (long)P_UNRELATED)) return -1; - if (ins(d, "P_DEBUGDESC", (long)P_DEBUGDESC)) return -1; -#else - if (ins(d, "P_WAIT", (long)_P_WAIT)) return -1; - if (ins(d, "P_NOWAIT", (long)_P_NOWAIT)) return -1; - if (ins(d, "P_OVERLAY", (long)_OLD_P_OVERLAY)) return -1; - if (ins(d, "P_NOWAITO", (long)_P_NOWAITO)) return -1; - if (ins(d, "P_DETACH", (long)_P_DETACH)) return -1; + if (ins(d, "P_WAIT", (long)P_WAIT)) return -1; + if (ins(d, "P_NOWAIT", (long)P_NOWAIT)) return -1; + if (ins(d, "P_OVERLAY", (long)P_OVERLAY)) return -1; + if (ins(d, "P_DEBUG", (long)P_DEBUG)) return -1; + if (ins(d, "P_SESSION", (long)P_SESSION)) return -1; + if (ins(d, "P_DETACH", (long)P_DETACH)) return -1; + if (ins(d, "P_PM", (long)P_PM)) return -1; + if (ins(d, "P_DEFAULT", (long)P_DEFAULT)) return -1; + if (ins(d, "P_MINIMIZE", (long)P_MINIMIZE)) return -1; + if (ins(d, "P_MAXIMIZE", (long)P_MAXIMIZE)) return -1; + if (ins(d, "P_FULLSCREEN", (long)P_FULLSCREEN)) return -1; + if (ins(d, "P_WINDOWED", (long)P_WINDOWED)) return -1; + if (ins(d, "P_FOREGROUND", (long)P_FOREGROUND)) return -1; + if (ins(d, "P_BACKGROUND", (long)P_BACKGROUND)) return -1; + if (ins(d, "P_NOCLOSE", (long)P_NOCLOSE)) return -1; + if (ins(d, "P_NOSESSION", (long)P_NOSESSION)) return -1; + if (ins(d, "P_QUOTE", (long)P_QUOTE)) return -1; + if (ins(d, "P_TILDE", (long)P_TILDE)) return -1; + if (ins(d, "P_UNRELATED", (long)P_UNRELATED)) return -1; + if (ins(d, "P_DEBUGDESC", (long)P_DEBUGDESC)) return -1; +#else + if (ins(d, "P_WAIT", (long)_P_WAIT)) return -1; + if (ins(d, "P_NOWAIT", (long)_P_NOWAIT)) return -1; + if (ins(d, "P_OVERLAY", (long)_OLD_P_OVERLAY)) return -1; + if (ins(d, "P_NOWAITO", (long)_P_NOWAITO)) return -1; + if (ins(d, "P_DETACH", (long)_P_DETACH)) return -1; #endif #endif #if defined(PYOS_OS2) - if (insertvalues(d)) return -1; + if (insertvalues(d)) return -1; #endif - return 0; + return 0; } @@ -9197,96 +9197,96 @@ PyMODINIT_FUNC INITFUNC(void) { - PyObject *m, *v; + PyObject *m, *v; - m = Py_InitModule3(MODNAME, - posix_methods, - posix__doc__); - if (m == NULL) - return; - - /* Initialize environ dictionary */ - v = convertenviron(); - Py_XINCREF(v); - if (v == NULL || PyModule_AddObject(m, "environ", v) != 0) - return; - Py_DECREF(v); + m = Py_InitModule3(MODNAME, + posix_methods, + posix__doc__); + if (m == NULL) + return; + + /* Initialize environ dictionary */ + v = convertenviron(); + Py_XINCREF(v); + if (v == NULL || PyModule_AddObject(m, "environ", v) != 0) + return; + Py_DECREF(v); - if (all_ins(m)) - return; + if (all_ins(m)) + return; - if (setup_confname_tables(m)) - return; + if (setup_confname_tables(m)) + return; - Py_INCREF(PyExc_OSError); - PyModule_AddObject(m, "error", PyExc_OSError); + Py_INCREF(PyExc_OSError); + PyModule_AddObject(m, "error", PyExc_OSError); #ifdef HAVE_PUTENV - if (posix_putenv_garbage == NULL) - posix_putenv_garbage = PyDict_New(); + if (posix_putenv_garbage == NULL) + posix_putenv_garbage = PyDict_New(); #endif - if (!initialized) { - stat_result_desc.name = MODNAME ".stat_result"; - stat_result_desc.fields[7].name = PyStructSequence_UnnamedField; - stat_result_desc.fields[8].name = PyStructSequence_UnnamedField; - stat_result_desc.fields[9].name = PyStructSequence_UnnamedField; - PyStructSequence_InitType(&StatResultType, &stat_result_desc); - structseq_new = StatResultType.tp_new; - StatResultType.tp_new = statresult_new; + if (!initialized) { + stat_result_desc.name = MODNAME ".stat_result"; + stat_result_desc.fields[7].name = PyStructSequence_UnnamedField; + stat_result_desc.fields[8].name = PyStructSequence_UnnamedField; + stat_result_desc.fields[9].name = PyStructSequence_UnnamedField; + PyStructSequence_InitType(&StatResultType, &stat_result_desc); + structseq_new = StatResultType.tp_new; + StatResultType.tp_new = statresult_new; - statvfs_result_desc.name = MODNAME ".statvfs_result"; - PyStructSequence_InitType(&StatVFSResultType, &statvfs_result_desc); + statvfs_result_desc.name = MODNAME ".statvfs_result"; + PyStructSequence_InitType(&StatVFSResultType, &statvfs_result_desc); #ifdef NEED_TICKS_PER_SECOND # if defined(HAVE_SYSCONF) && defined(_SC_CLK_TCK) - ticks_per_second = sysconf(_SC_CLK_TCK); + ticks_per_second = sysconf(_SC_CLK_TCK); # elif defined(HZ) - ticks_per_second = HZ; + ticks_per_second = HZ; # else - ticks_per_second = 60; /* magic fallback value; may be bogus */ + ticks_per_second = 60; /* magic fallback value; may be bogus */ # endif #endif - } - Py_INCREF((PyObject*) &StatResultType); - PyModule_AddObject(m, "stat_result", (PyObject*) &StatResultType); - Py_INCREF((PyObject*) &StatVFSResultType); - PyModule_AddObject(m, "statvfs_result", - (PyObject*) &StatVFSResultType); - initialized = 1; + } + Py_INCREF((PyObject*) &StatResultType); + PyModule_AddObject(m, "stat_result", (PyObject*) &StatResultType); + Py_INCREF((PyObject*) &StatVFSResultType); + PyModule_AddObject(m, "statvfs_result", + (PyObject*) &StatVFSResultType); + initialized = 1; #ifdef __APPLE__ - /* - * Step 2 of weak-linking support on Mac OS X. - * - * The code below removes functions that are not available on the - * currently active platform. - * - * This block allow one to use a python binary that was build on - * OSX 10.4 on OSX 10.3, without loosing access to new APIs on - * OSX 10.4. - */ + /* + * Step 2 of weak-linking support on Mac OS X. + * + * The code below removes functions that are not available on the + * currently active platform. + * + * This block allow one to use a python binary that was build on + * OSX 10.4 on OSX 10.3, without loosing access to new APIs on + * OSX 10.4. + */ #ifdef HAVE_FSTATVFS - if (fstatvfs == NULL) { - if (PyObject_DelAttrString(m, "fstatvfs") == -1) { - return; - } - } + if (fstatvfs == NULL) { + if (PyObject_DelAttrString(m, "fstatvfs") == -1) { + return; + } + } #endif /* HAVE_FSTATVFS */ #ifdef HAVE_STATVFS - if (statvfs == NULL) { - if (PyObject_DelAttrString(m, "statvfs") == -1) { - return; - } - } + if (statvfs == NULL) { + if (PyObject_DelAttrString(m, "statvfs") == -1) { + return; + } + } #endif /* HAVE_STATVFS */ # ifdef HAVE_LCHOWN - if (lchown == NULL) { - if (PyObject_DelAttrString(m, "lchown") == -1) { - return; - } - } + if (lchown == NULL) { + if (PyObject_DelAttrString(m, "lchown") == -1) { + return; + } + } #endif /* HAVE_LCHOWN */ From python-checkins at python.org Thu May 6 02:03:45 2010 From: python-checkins at python.org (victor.stinner) Date: Thu, 6 May 2010 02:03:45 +0200 (CEST) Subject: [Python-checkins] r80845 - python/trunk/Modules/posixmodule.c Message-ID: <20100506000345.1C200EE9AA@mail.python.org> Author: victor.stinner Date: Thu May 6 02:03:44 2010 New Revision: 80845 Log: Untabify Modules/posixmodule.c (2) Fix some more functions by hand Modified: python/trunk/Modules/posixmodule.c Modified: python/trunk/Modules/posixmodule.c ============================================================================== --- python/trunk/Modules/posixmodule.c (original) +++ python/trunk/Modules/posixmodule.c Thu May 6 02:03:44 2010 @@ -612,10 +612,10 @@ msgbuf[msglen] = '\0'; /* OS/2 Doesn't Guarantee a Terminator */ if (strlen(msgbuf) > 0) { /* If Non-Empty Msg, Trim CRLF */ - char *lastc = &msgbuf[ strlen(msgbuf)-1 ]; + char *lastc = &msgbuf[ strlen(msgbuf)-1 ]; - while (lastc > msgbuf && isspace(Py_CHARMASK(*lastc))) - *lastc-- = '\0'; /* Trim Trailing Whitespace (CRLF) */ + while (lastc > msgbuf && isspace(Py_CHARMASK(*lastc))) + *lastc-- = '\0'; /* Trim Trailing Whitespace (CRLF) */ } /* Add Optional Reason Text */ @@ -8181,14 +8181,14 @@ int name; if (PyArg_ParseTuple(args, "O&:sysconf", conv_sysconf_confname, &name)) { - int value; + int value; - errno = 0; - value = sysconf(name); - if (value == -1 && errno != 0) - posix_error(); - else - result = PyInt_FromLong(value); + errno = 0; + value = sysconf(name); + if (value == -1 && errno != 0) + posix_error(); + else + result = PyInt_FromLong(value); } return result; } From python-checkins at python.org Thu May 6 02:08:46 2010 From: python-checkins at python.org (victor.stinner) Date: Thu, 6 May 2010 02:08:46 +0200 (CEST) Subject: [Python-checkins] r80846 - in python/branches/py3k: Modules/posixmodule.c Message-ID: <20100506000846.D1A38EE9B7@mail.python.org> Author: victor.stinner Date: Thu May 6 02:08:46 2010 New Revision: 80846 Log: Recorded merge of revisions 80844-80845 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r80844 | victor.stinner | 2010-05-06 01:33:33 +0200 (jeu., 06 mai 2010) | 5 lines Untabify Modules/posixmodule.c Run Antoine Pitrou "untabify" script + manual editions (OS/2 and some continuation lines). ........ r80845 | victor.stinner | 2010-05-06 02:03:44 +0200 (jeu., 06 mai 2010) | 4 lines Untabify Modules/posixmodule.c (2) Fix some more functions by hand ........ I rewrote the patch for py3k from scratch using untabify + manual editions Modified: python/branches/py3k/ (props changed) python/branches/py3k/Modules/posixmodule.c Modified: python/branches/py3k/Modules/posixmodule.c ============================================================================== --- python/branches/py3k/Modules/posixmodule.c (original) +++ python/branches/py3k/Modules/posixmodule.c Thu May 6 02:08:46 2010 @@ -15,7 +15,7 @@ #ifdef __APPLE__ /* - * Step 1 of support for weak-linking a number of symbols existing on + * Step 1 of support for weak-linking a number of symbols existing on * OSX 10.4 and later, see the comment in the #ifdef __APPLE__ block * at the end of this file for more information. */ @@ -69,7 +69,7 @@ #endif /* HAVE_SYS_STAT_H */ #ifdef HAVE_SYS_WAIT_H -#include /* For WNOHANG */ +#include /* For WNOHANG */ #endif #ifdef HAVE_SIGNAL_H @@ -101,41 +101,41 @@ #if defined(PYCC_VACPP) && defined(PYOS_OS2) #include #else -#if defined(__WATCOMC__) && !defined(__QNX__) /* Watcom compiler */ +#if defined(__WATCOMC__) && !defined(__QNX__) /* Watcom compiler */ #define HAVE_GETCWD 1 #define HAVE_OPENDIR 1 -#define HAVE_SYSTEM 1 +#define HAVE_SYSTEM 1 #if defined(__OS2__) #define HAVE_EXECV 1 #define HAVE_WAIT 1 #endif #include #else -#ifdef __BORLANDC__ /* Borland compiler */ +#ifdef __BORLANDC__ /* Borland compiler */ #define HAVE_EXECV 1 #define HAVE_GETCWD 1 #define HAVE_OPENDIR 1 #define HAVE_PIPE 1 -#define HAVE_SYSTEM 1 +#define HAVE_SYSTEM 1 #define HAVE_WAIT 1 #else -#ifdef _MSC_VER /* Microsoft compiler */ +#ifdef _MSC_VER /* Microsoft compiler */ #define HAVE_GETCWD 1 -#define HAVE_SPAWNV 1 +#define HAVE_SPAWNV 1 #define HAVE_EXECV 1 #define HAVE_PIPE 1 -#define HAVE_SYSTEM 1 -#define HAVE_CWAIT 1 -#define HAVE_FSYNC 1 +#define HAVE_SYSTEM 1 +#define HAVE_CWAIT 1 +#define HAVE_FSYNC 1 #define fsync _commit #else #if defined(PYOS_OS2) && defined(PYCC_GCC) || defined(__VMS) /* Everything needed is defined in PC/os2emx/pyconfig.h or vms/pyconfig.h */ -#else /* all other compilers */ +#else /* all other compilers */ /* Unix functions that the configure script doesn't check for */ #define HAVE_EXECV 1 #define HAVE_FORK 1 -#if defined(__USLC__) && defined(__SCO_VERSION__) /* SCO UDK Compiler */ +#if defined(__USLC__) && defined(__SCO_VERSION__) /* SCO UDK Compiler */ #define HAVE_FORK1 1 #endif #define HAVE_GETCWD 1 @@ -147,9 +147,9 @@ #define HAVE_KILL 1 #define HAVE_OPENDIR 1 #define HAVE_PIPE 1 -#define HAVE_SYSTEM 1 +#define HAVE_SYSTEM 1 #define HAVE_WAIT 1 -#define HAVE_TTYNAME 1 +#define HAVE_TTYNAME 1 #endif /* PYOS_OS2 && PYCC_GCC && __VMS */ #endif /* _MSC_VER */ #endif /* __BORLANDC__ */ @@ -265,7 +265,7 @@ #include "osdefs.h" #include #include -#include /* for ShellExecute() */ +#include /* for ShellExecute() */ #endif /* _MSC_VER */ #if defined(PYCC_VACPP) && defined(PYOS_OS2) @@ -312,13 +312,13 @@ /* choose the appropriate stat and fstat functions and return structs */ #undef STAT #if defined(MS_WIN64) || defined(MS_WINDOWS) -# define STAT win32_stat -# define FSTAT win32_fstat -# define STRUCT_STAT struct win32_stat -#else -# define STAT stat -# define FSTAT fstat -# define STRUCT_STAT struct stat +# define STAT win32_stat +# define FSTAT win32_fstat +# define STRUCT_STAT struct win32_stat +#else +# define STAT stat +# define FSTAT fstat +# define STRUCT_STAT struct stat #endif #if defined(MAJOR_IN_MKDEV) @@ -345,7 +345,7 @@ * as a fd and should merely raise a python exception on error. * The Microsoft CRT doesn't provide an official way to check for the * validity of a file descriptor, but we can emulate its internal behaviour - * by using the exported __pinfo data member and knowledge of the + * by using the exported __pinfo data member and knowledge of the * internal structures involved. * The structures below must be updated for each version of visual studio * according to the file internal.h in the CRT source, until MS comes @@ -357,8 +357,8 @@ * Only the first items must be present. */ typedef struct { - intptr_t osfhnd; - char osfile; + intptr_t osfhnd; + char osfile; } my_ioinfo; extern __declspec(dllimport) char * __pioinfo[]; @@ -373,52 +373,52 @@ int _PyVerify_fd(int fd) { - const int i1 = fd >> IOINFO_L2E; - const int i2 = fd & ((1 << IOINFO_L2E) - 1); - - static int sizeof_ioinfo = 0; - - /* Determine the actual size of the ioinfo structure, - * as used by the CRT loaded in memory - */ - if (sizeof_ioinfo == 0 && __pioinfo[0] != NULL) { - sizeof_ioinfo = _msize(__pioinfo[0]) / IOINFO_ARRAY_ELTS; - } - if (sizeof_ioinfo == 0) { - /* This should not happen... */ - goto fail; - } - - /* See that it isn't a special CLEAR fileno */ - if (fd != _NO_CONSOLE_FILENO) { - /* Microsoft CRT would check that 0<=fd<_nhandle but we can't do that. Instead - * we check pointer validity and other info - */ - if (0 <= i1 && i1 < IOINFO_ARRAYS && __pioinfo[i1] != NULL) { - /* finally, check that the file is open */ - my_ioinfo* info = (my_ioinfo*)(__pioinfo[i1] + i2 * sizeof_ioinfo); - if (info->osfile & FOPEN) { - return 1; - } - } - } + const int i1 = fd >> IOINFO_L2E; + const int i2 = fd & ((1 << IOINFO_L2E) - 1); + + static int sizeof_ioinfo = 0; + + /* Determine the actual size of the ioinfo structure, + * as used by the CRT loaded in memory + */ + if (sizeof_ioinfo == 0 && __pioinfo[0] != NULL) { + sizeof_ioinfo = _msize(__pioinfo[0]) / IOINFO_ARRAY_ELTS; + } + if (sizeof_ioinfo == 0) { + /* This should not happen... */ + goto fail; + } + + /* See that it isn't a special CLEAR fileno */ + if (fd != _NO_CONSOLE_FILENO) { + /* Microsoft CRT would check that 0<=fd<_nhandle but we can't do that. Instead + * we check pointer validity and other info + */ + if (0 <= i1 && i1 < IOINFO_ARRAYS && __pioinfo[i1] != NULL) { + /* finally, check that the file is open */ + my_ioinfo* info = (my_ioinfo*)(__pioinfo[i1] + i2 * sizeof_ioinfo); + if (info->osfile & FOPEN) { + return 1; + } + } + } fail: - errno = EBADF; - return 0; + errno = EBADF; + return 0; } /* the special case of checking dup2. The target fd must be in a sensible range */ static int _PyVerify_fd_dup2(int fd1, int fd2) { - if (!_PyVerify_fd(fd1)) - return 0; - if (fd2 == _NO_CONSOLE_FILENO) - return 0; - if ((unsigned)fd2 < _NHANDLE_) - return 1; - else - return 0; + if (!_PyVerify_fd(fd1)) + return 0; + if (fd2 == _NO_CONSOLE_FILENO) + return 0; + if ((unsigned)fd2 < _NHANDLE_) + return 1; + else + return 0; } #else /* dummy version. _PyVerify_fd() is already defined in fileobject.h */ @@ -439,101 +439,101 @@ static PyObject * convertenviron(void) { - PyObject *d; + PyObject *d; #ifdef MS_WINDOWS - wchar_t **e; + wchar_t **e; #else - char **e; + char **e; +#endif +#if defined(PYOS_OS2) + APIRET rc; + char buffer[1024]; /* OS/2 Provides a Documented Max of 1024 Chars */ #endif - d = PyDict_New(); - if (d == NULL) - return NULL; + + d = PyDict_New(); + if (d == NULL) + return NULL; #ifdef WITH_NEXT_FRAMEWORK - if (environ == NULL) - environ = *_NSGetEnviron(); + if (environ == NULL) + environ = *_NSGetEnviron(); #endif #ifdef MS_WINDOWS - /* _wenviron must be initialized in this way if the program is started - through main() instead of wmain(). */ - _wgetenv(L""); - if (_wenviron == NULL) - return d; - /* This part ignores errors */ - for (e = _wenviron; *e != NULL; e++) { - PyObject *k; - PyObject *v; - wchar_t *p = wcschr(*e, L'='); - if (p == NULL) - continue; - k = PyUnicode_FromWideChar(*e, (Py_ssize_t)(p-*e)); - if (k == NULL) { - PyErr_Clear(); - continue; - } - v = PyUnicode_FromWideChar(p+1, wcslen(p+1)); - if (v == NULL) { - PyErr_Clear(); - Py_DECREF(k); - continue; - } - if (PyDict_GetItem(d, k) == NULL) { - if (PyDict_SetItem(d, k, v) != 0) - PyErr_Clear(); - } - Py_DECREF(k); - Py_DECREF(v); - } -#else - if (environ == NULL) - return d; - /* This part ignores errors */ - for (e = environ; *e != NULL; e++) { - PyObject *k; - PyObject *v; - char *p = strchr(*e, '='); - if (p == NULL) - continue; - k = PyUnicode_Decode(*e, (int)(p-*e), - Py_FileSystemDefaultEncoding, "surrogateescape"); - if (k == NULL) { - PyErr_Clear(); - continue; - } - v = PyUnicode_Decode(p+1, strlen(p+1), - Py_FileSystemDefaultEncoding, "surrogateescape"); - if (v == NULL) { - PyErr_Clear(); - Py_DECREF(k); - continue; - } - if (PyDict_GetItem(d, k) == NULL) { - if (PyDict_SetItem(d, k, v) != 0) - PyErr_Clear(); - } - Py_DECREF(k); - Py_DECREF(v); - } -#endif -#if defined(PYOS_OS2) - { - APIRET rc; - char buffer[1024]; /* OS/2 Provides a Documented Max of 1024 Chars */ - - rc = DosQueryExtLIBPATH(buffer, BEGIN_LIBPATH); - if (rc == NO_ERROR) { /* (not a type, envname is NOT 'BEGIN_LIBPATH') */ - PyObject *v = PyBytes_FromString(buffer); - PyDict_SetItemString(d, "BEGINLIBPATH", v); - Py_DECREF(v); + /* _wenviron must be initialized in this way if the program is started + through main() instead of wmain(). */ + _wgetenv(L""); + if (_wenviron == NULL) + return d; + /* This part ignores errors */ + for (e = _wenviron; *e != NULL; e++) { + PyObject *k; + PyObject *v; + wchar_t *p = wcschr(*e, L'='); + if (p == NULL) + continue; + k = PyUnicode_FromWideChar(*e, (Py_ssize_t)(p-*e)); + if (k == NULL) { + PyErr_Clear(); + continue; } - rc = DosQueryExtLIBPATH(buffer, END_LIBPATH); - if (rc == NO_ERROR) { /* (not a typo, envname is NOT 'END_LIBPATH') */ - PyObject *v = PyBytes_FromString(buffer); - PyDict_SetItemString(d, "ENDLIBPATH", v); - Py_DECREF(v); + v = PyUnicode_FromWideChar(p+1, wcslen(p+1)); + if (v == NULL) { + PyErr_Clear(); + Py_DECREF(k); + continue; + } + if (PyDict_GetItem(d, k) == NULL) { + if (PyDict_SetItem(d, k, v) != 0) + PyErr_Clear(); } + Py_DECREF(k); + Py_DECREF(v); + } +#else + if (environ == NULL) + return d; + /* This part ignores errors */ + for (e = environ; *e != NULL; e++) { + PyObject *k; + PyObject *v; + char *p = strchr(*e, '='); + if (p == NULL) + continue; + k = PyUnicode_Decode(*e, (int)(p-*e), + Py_FileSystemDefaultEncoding, "surrogateescape"); + if (k == NULL) { + PyErr_Clear(); + continue; + } + v = PyUnicode_Decode(p+1, strlen(p+1), + Py_FileSystemDefaultEncoding, "surrogateescape"); + if (v == NULL) { + PyErr_Clear(); + Py_DECREF(k); + continue; + } + if (PyDict_GetItem(d, k) == NULL) { + if (PyDict_SetItem(d, k, v) != 0) + PyErr_Clear(); + } + Py_DECREF(k); + Py_DECREF(v); + } +#endif +#if defined(PYOS_OS2) + rc = DosQueryExtLIBPATH(buffer, BEGIN_LIBPATH); + if (rc == NO_ERROR) { /* (not a type, envname is NOT 'BEGIN_LIBPATH') */ + PyObject *v = PyBytes_FromString(buffer); + PyDict_SetItemString(d, "BEGINLIBPATH", v); + Py_DECREF(v); + } + rc = DosQueryExtLIBPATH(buffer, END_LIBPATH); + if (rc == NO_ERROR) { /* (not a typo, envname is NOT 'END_LIBPATH') */ + PyObject *v = PyBytes_FromString(buffer); + PyDict_SetItemString(d, "ENDLIBPATH", v); + Py_DECREF(v); } #endif - return d; + return d; } /* Set a POSIX-specific error from errno, and return NULL */ @@ -541,19 +541,19 @@ static PyObject * posix_error(void) { - return PyErr_SetFromErrno(PyExc_OSError); + return PyErr_SetFromErrno(PyExc_OSError); } static PyObject * posix_error_with_filename(char* name) { - return PyErr_SetFromErrnoWithFilename(PyExc_OSError, name); + return PyErr_SetFromErrnoWithFilename(PyExc_OSError, name); } #ifdef MS_WINDOWS static PyObject * posix_error_with_unicode_filename(Py_UNICODE* name) { - return PyErr_SetFromErrnoWithUnicodeFilename(PyExc_OSError, name); + return PyErr_SetFromErrnoWithUnicodeFilename(PyExc_OSError, name); } #endif /* MS_WINDOWS */ @@ -561,54 +561,54 @@ static PyObject * posix_error_with_allocated_filename(PyObject* name) { - PyObject *rc = PyErr_SetFromErrnoWithFilename(PyExc_OSError, - PyBytes_AsString(name)); - Py_DECREF(name); - return rc; + PyObject *rc = PyErr_SetFromErrnoWithFilename(PyExc_OSError, + PyBytes_AsString(name)); + Py_DECREF(name); + return rc; } #ifdef MS_WINDOWS static PyObject * win32_error(char* function, char* filename) { - /* XXX We should pass the function name along in the future. - (winreg.c also wants to pass the function name.) - This would however require an additional param to the - Windows error object, which is non-trivial. - */ - errno = GetLastError(); - if (filename) - return PyErr_SetFromWindowsErrWithFilename(errno, filename); - else - return PyErr_SetFromWindowsErr(errno); + /* XXX We should pass the function name along in the future. + (winreg.c also wants to pass the function name.) + This would however require an additional param to the + Windows error object, which is non-trivial. + */ + errno = GetLastError(); + if (filename) + return PyErr_SetFromWindowsErrWithFilename(errno, filename); + else + return PyErr_SetFromWindowsErr(errno); } static PyObject * win32_error_unicode(char* function, Py_UNICODE* filename) { - /* XXX - see win32_error for comments on 'function' */ - errno = GetLastError(); - if (filename) - return PyErr_SetFromWindowsErrWithUnicodeFilename(errno, filename); - else - return PyErr_SetFromWindowsErr(errno); + /* XXX - see win32_error for comments on 'function' */ + errno = GetLastError(); + if (filename) + return PyErr_SetFromWindowsErrWithUnicodeFilename(errno, filename); + else + return PyErr_SetFromWindowsErr(errno); } static int convert_to_unicode(PyObject **param) { - if (PyUnicode_CheckExact(*param)) - Py_INCREF(*param); - else if (PyUnicode_Check(*param)) - /* For a Unicode subtype that's not a Unicode object, - return a true Unicode object with the same data. */ - *param = PyUnicode_FromUnicode(PyUnicode_AS_UNICODE(*param), - PyUnicode_GET_SIZE(*param)); - else - *param = PyUnicode_FromEncodedObject(*param, - Py_FileSystemDefaultEncoding, - "strict"); - return (*param) != NULL; + if (PyUnicode_CheckExact(*param)) + Py_INCREF(*param); + else if (PyUnicode_Check(*param)) + /* For a Unicode subtype that's not a Unicode object, + return a true Unicode object with the same data. */ + *param = PyUnicode_FromUnicode(PyUnicode_AS_UNICODE(*param), + PyUnicode_GET_SIZE(*param)); + else + *param = PyUnicode_FromEncodedObject(*param, + Py_FileSystemDefaultEncoding, + "strict"); + return (*param) != NULL; } #endif /* MS_WINDOWS */ @@ -617,7 +617,7 @@ /********************************************************************** * Helper Function to Trim and Format OS/2 Messages **********************************************************************/ - static void +static void os2_formatmsg(char *msgbuf, int msglen, char *reason) { msgbuf[msglen] = '\0'; /* OS/2 Doesn't Guarantee a Terminator */ @@ -647,7 +647,7 @@ * the file OSO001.MSG in the \OS2 directory hierarchy. * **********************************************************************/ - static char * +static char * os2_strerror(char *msgbuf, int msgbuflen, int errorcode, char *reason) { APIRET rc; @@ -663,7 +663,7 @@ os2_formatmsg(msgbuf, msglen, reason); else PyOS_snprintf(msgbuf, msgbuflen, - "unknown OS error #%d", errorcode); + "unknown OS error #%d", errorcode); return msgbuf; } @@ -672,7 +672,8 @@ errors are not in a global variable e.g. 'errno' nor are they congruent with posix error numbers. */ -static PyObject * os2_error(int code) +static PyObject * +os2_error(int code) { char text[1024]; PyObject *v; @@ -694,99 +695,99 @@ static PyObject * posix_fildes(PyObject *fdobj, int (*func)(int)) { - int fd; - int res; - fd = PyObject_AsFileDescriptor(fdobj); - if (fd < 0) - return NULL; - if (!_PyVerify_fd(fd)) - return posix_error(); - Py_BEGIN_ALLOW_THREADS - res = (*func)(fd); - Py_END_ALLOW_THREADS - if (res < 0) - return posix_error(); - Py_INCREF(Py_None); - return Py_None; + int fd; + int res; + fd = PyObject_AsFileDescriptor(fdobj); + if (fd < 0) + return NULL; + if (!_PyVerify_fd(fd)) + return posix_error(); + Py_BEGIN_ALLOW_THREADS + res = (*func)(fd); + Py_END_ALLOW_THREADS + if (res < 0) + return posix_error(); + Py_INCREF(Py_None); + return Py_None; } static PyObject * posix_1str(PyObject *args, char *format, int (*func)(const char*)) { - PyObject *opath1 = NULL; - char *path1; - int res; - if (!PyArg_ParseTuple(args, format, - PyUnicode_FSConverter, &opath1)) - return NULL; - path1 = PyBytes_AsString(opath1); - Py_BEGIN_ALLOW_THREADS - res = (*func)(path1); - Py_END_ALLOW_THREADS - if (res < 0) - return posix_error_with_allocated_filename(opath1); - Py_DECREF(opath1); - Py_INCREF(Py_None); - return Py_None; + PyObject *opath1 = NULL; + char *path1; + int res; + if (!PyArg_ParseTuple(args, format, + PyUnicode_FSConverter, &opath1)) + return NULL; + path1 = PyBytes_AsString(opath1); + Py_BEGIN_ALLOW_THREADS + res = (*func)(path1); + Py_END_ALLOW_THREADS + if (res < 0) + return posix_error_with_allocated_filename(opath1); + Py_DECREF(opath1); + Py_INCREF(Py_None); + return Py_None; } static PyObject * posix_2str(PyObject *args, - char *format, - int (*func)(const char *, const char *)) + char *format, + int (*func)(const char *, const char *)) { - PyObject *opath1 = NULL, *opath2 = NULL; - char *path1, *path2; - int res; - if (!PyArg_ParseTuple(args, format, - PyUnicode_FSConverter, &opath1, - PyUnicode_FSConverter, &opath2)) { - return NULL; - } - path1 = PyBytes_AsString(opath1); - path2 = PyBytes_AsString(opath2); - Py_BEGIN_ALLOW_THREADS - res = (*func)(path1, path2); - Py_END_ALLOW_THREADS - Py_DECREF(opath1); - Py_DECREF(opath2); - if (res != 0) - /* XXX how to report both path1 and path2??? */ - return posix_error(); - Py_INCREF(Py_None); - return Py_None; + PyObject *opath1 = NULL, *opath2 = NULL; + char *path1, *path2; + int res; + if (!PyArg_ParseTuple(args, format, + PyUnicode_FSConverter, &opath1, + PyUnicode_FSConverter, &opath2)) { + return NULL; + } + path1 = PyBytes_AsString(opath1); + path2 = PyBytes_AsString(opath2); + Py_BEGIN_ALLOW_THREADS + res = (*func)(path1, path2); + Py_END_ALLOW_THREADS + Py_DECREF(opath1); + Py_DECREF(opath2); + if (res != 0) + /* XXX how to report both path1 and path2??? */ + return posix_error(); + Py_INCREF(Py_None); + return Py_None; } #ifdef MS_WINDOWS static PyObject* -win32_1str(PyObject* args, char* func, - char* format, BOOL (__stdcall *funcA)(LPCSTR), - char* wformat, BOOL (__stdcall *funcW)(LPWSTR)) -{ - PyObject *uni; - char *ansi; - BOOL result; - - if (!PyArg_ParseTuple(args, wformat, &uni)) - PyErr_Clear(); - else { - Py_BEGIN_ALLOW_THREADS - result = funcW(PyUnicode_AsUnicode(uni)); - Py_END_ALLOW_THREADS - if (!result) - return win32_error_unicode(func, PyUnicode_AsUnicode(uni)); - Py_INCREF(Py_None); - return Py_None; - } - if (!PyArg_ParseTuple(args, format, &ansi)) - return NULL; - Py_BEGIN_ALLOW_THREADS - result = funcA(ansi); - Py_END_ALLOW_THREADS - if (!result) - return win32_error(func, ansi); - Py_INCREF(Py_None); - return Py_None; +win32_1str(PyObject* args, char* func, + char* format, BOOL (__stdcall *funcA)(LPCSTR), + char* wformat, BOOL (__stdcall *funcW)(LPWSTR)) +{ + PyObject *uni; + char *ansi; + BOOL result; + + if (!PyArg_ParseTuple(args, wformat, &uni)) + PyErr_Clear(); + else { + Py_BEGIN_ALLOW_THREADS + result = funcW(PyUnicode_AsUnicode(uni)); + Py_END_ALLOW_THREADS + if (!result) + return win32_error_unicode(func, PyUnicode_AsUnicode(uni)); + Py_INCREF(Py_None); + return Py_None; + } + if (!PyArg_ParseTuple(args, format, &ansi)) + return NULL; + Py_BEGIN_ALLOW_THREADS + result = funcA(ansi); + Py_END_ALLOW_THREADS + if (!result) + return win32_error(func, ansi); + Py_INCREF(Py_None); + return Py_None; } @@ -798,24 +799,24 @@ static BOOL __stdcall win32_chdir(LPCSTR path) { - char new_path[MAX_PATH+1]; - int result; - char env[4] = "=x:"; - - if(!SetCurrentDirectoryA(path)) - return FALSE; - result = GetCurrentDirectoryA(MAX_PATH+1, new_path); - if (!result) - return FALSE; - /* In the ANSI API, there should not be any paths longer - than MAX_PATH. */ - assert(result <= MAX_PATH+1); - if (strncmp(new_path, "\\\\", 2) == 0 || - strncmp(new_path, "//", 2) == 0) - /* UNC path, nothing to do. */ - return TRUE; - env[1] = new_path[0]; - return SetEnvironmentVariableA(env, new_path); + char new_path[MAX_PATH+1]; + int result; + char env[4] = "=x:"; + + if(!SetCurrentDirectoryA(path)) + return FALSE; + result = GetCurrentDirectoryA(MAX_PATH+1, new_path); + if (!result) + return FALSE; + /* In the ANSI API, there should not be any paths longer + than MAX_PATH. */ + assert(result <= MAX_PATH+1); + if (strncmp(new_path, "\\\\", 2) == 0 || + strncmp(new_path, "//", 2) == 0) + /* UNC path, nothing to do. */ + return TRUE; + env[1] = new_path[0]; + return SetEnvironmentVariableA(env, new_path); } /* The Unicode version differs from the ANSI version @@ -823,36 +824,36 @@ static BOOL __stdcall win32_wchdir(LPCWSTR path) { - wchar_t _new_path[MAX_PATH+1], *new_path = _new_path; - int result; - wchar_t env[4] = L"=x:"; - - if(!SetCurrentDirectoryW(path)) - return FALSE; - result = GetCurrentDirectoryW(MAX_PATH+1, new_path); - if (!result) - return FALSE; - if (result > MAX_PATH+1) { - new_path = malloc(result * sizeof(wchar_t)); - if (!new_path) { - SetLastError(ERROR_OUTOFMEMORY); - return FALSE; - } - result = GetCurrentDirectoryW(result, new_path); - if (!result) { - free(new_path); - return FALSE; - } - } - if (wcsncmp(new_path, L"\\\\", 2) == 0 || - wcsncmp(new_path, L"//", 2) == 0) - /* UNC path, nothing to do. */ - return TRUE; - env[1] = new_path[0]; - result = SetEnvironmentVariableW(env, new_path); - if (new_path != _new_path) - free(new_path); - return result; + wchar_t _new_path[MAX_PATH+1], *new_path = _new_path; + int result; + wchar_t env[4] = L"=x:"; + + if(!SetCurrentDirectoryW(path)) + return FALSE; + result = GetCurrentDirectoryW(MAX_PATH+1, new_path); + if (!result) + return FALSE; + if (result > MAX_PATH+1) { + new_path = malloc(result * sizeof(wchar_t)); + if (!new_path) { + SetLastError(ERROR_OUTOFMEMORY); + return FALSE; + } + result = GetCurrentDirectoryW(result, new_path); + if (!result) { + free(new_path); + return FALSE; + } + } + if (wcsncmp(new_path, L"\\\\", 2) == 0 || + wcsncmp(new_path, L"//", 2) == 0) + /* UNC path, nothing to do. */ + return TRUE; + env[1] = new_path[0]; + result = SetEnvironmentVariableW(env, new_path); + if (new_path != _new_path) + free(new_path); + return result; } #endif @@ -863,7 +864,7 @@ UTC and local time Therefore, we implement our own stat, based on the Win32 API directly. */ -#define HAVE_STAT_NSEC 1 +#define HAVE_STAT_NSEC 1 struct win32_stat{ int st_dev; @@ -887,24 +888,24 @@ static void FILE_TIME_to_time_t_nsec(FILETIME *in_ptr, int *time_out, int* nsec_out) { - /* XXX endianness. Shouldn't matter, as all Windows implementations are little-endian */ - /* Cannot simply cast and dereference in_ptr, - since it might not be aligned properly */ - __int64 in; - memcpy(&in, in_ptr, sizeof(in)); - *nsec_out = (int)(in % 10000000) * 100; /* FILETIME is in units of 100 nsec. */ - /* XXX Win32 supports time stamps past 2038; we currently don't */ - *time_out = Py_SAFE_DOWNCAST((in / 10000000) - secs_between_epochs, __int64, int); + /* XXX endianness. Shouldn't matter, as all Windows implementations are little-endian */ + /* Cannot simply cast and dereference in_ptr, + since it might not be aligned properly */ + __int64 in; + memcpy(&in, in_ptr, sizeof(in)); + *nsec_out = (int)(in % 10000000) * 100; /* FILETIME is in units of 100 nsec. */ + /* XXX Win32 supports time stamps past 2038; we currently don't */ + *time_out = Py_SAFE_DOWNCAST((in / 10000000) - secs_between_epochs, __int64, int); } static void time_t_to_FILE_TIME(int time_in, int nsec_in, FILETIME *out_ptr) { - /* XXX endianness */ - __int64 out; - out = time_in + secs_between_epochs; - out = out * 10000000 + nsec_in / 100; - memcpy(out_ptr, &out, sizeof(out)); + /* XXX endianness */ + __int64 out; + out = time_in + secs_between_epochs; + out = out * 10000000 + nsec_in / 100; + memcpy(out_ptr, &out, sizeof(out)); } /* Below, we *know* that ugo+r is 0444 */ @@ -914,193 +915,193 @@ static int attributes_to_mode(DWORD attr) { - int m = 0; - if (attr & FILE_ATTRIBUTE_DIRECTORY) - m |= _S_IFDIR | 0111; /* IFEXEC for user,group,other */ - else - m |= _S_IFREG; - if (attr & FILE_ATTRIBUTE_READONLY) - m |= 0444; - else - m |= 0666; - return m; + int m = 0; + if (attr & FILE_ATTRIBUTE_DIRECTORY) + m |= _S_IFDIR | 0111; /* IFEXEC for user,group,other */ + else + m |= _S_IFREG; + if (attr & FILE_ATTRIBUTE_READONLY) + m |= 0444; + else + m |= 0666; + return m; } static int attribute_data_to_stat(WIN32_FILE_ATTRIBUTE_DATA *info, struct win32_stat *result) { - memset(result, 0, sizeof(*result)); - result->st_mode = attributes_to_mode(info->dwFileAttributes); - result->st_size = (((__int64)info->nFileSizeHigh)<<32) + info->nFileSizeLow; - FILE_TIME_to_time_t_nsec(&info->ftCreationTime, &result->st_ctime, &result->st_ctime_nsec); - FILE_TIME_to_time_t_nsec(&info->ftLastWriteTime, &result->st_mtime, &result->st_mtime_nsec); - FILE_TIME_to_time_t_nsec(&info->ftLastAccessTime, &result->st_atime, &result->st_atime_nsec); + memset(result, 0, sizeof(*result)); + result->st_mode = attributes_to_mode(info->dwFileAttributes); + result->st_size = (((__int64)info->nFileSizeHigh)<<32) + info->nFileSizeLow; + FILE_TIME_to_time_t_nsec(&info->ftCreationTime, &result->st_ctime, &result->st_ctime_nsec); + FILE_TIME_to_time_t_nsec(&info->ftLastWriteTime, &result->st_mtime, &result->st_mtime_nsec); + FILE_TIME_to_time_t_nsec(&info->ftLastAccessTime, &result->st_atime, &result->st_atime_nsec); - return 0; + return 0; } static BOOL attributes_from_dir(LPCSTR pszFile, LPWIN32_FILE_ATTRIBUTE_DATA pfad) { - HANDLE hFindFile; - WIN32_FIND_DATAA FileData; - hFindFile = FindFirstFileA(pszFile, &FileData); - if (hFindFile == INVALID_HANDLE_VALUE) - return FALSE; - FindClose(hFindFile); - pfad->dwFileAttributes = FileData.dwFileAttributes; - pfad->ftCreationTime = FileData.ftCreationTime; - pfad->ftLastAccessTime = FileData.ftLastAccessTime; - pfad->ftLastWriteTime = FileData.ftLastWriteTime; - pfad->nFileSizeHigh = FileData.nFileSizeHigh; - pfad->nFileSizeLow = FileData.nFileSizeLow; - return TRUE; + HANDLE hFindFile; + WIN32_FIND_DATAA FileData; + hFindFile = FindFirstFileA(pszFile, &FileData); + if (hFindFile == INVALID_HANDLE_VALUE) + return FALSE; + FindClose(hFindFile); + pfad->dwFileAttributes = FileData.dwFileAttributes; + pfad->ftCreationTime = FileData.ftCreationTime; + pfad->ftLastAccessTime = FileData.ftLastAccessTime; + pfad->ftLastWriteTime = FileData.ftLastWriteTime; + pfad->nFileSizeHigh = FileData.nFileSizeHigh; + pfad->nFileSizeLow = FileData.nFileSizeLow; + return TRUE; } static BOOL attributes_from_dir_w(LPCWSTR pszFile, LPWIN32_FILE_ATTRIBUTE_DATA pfad) { - HANDLE hFindFile; - WIN32_FIND_DATAW FileData; - hFindFile = FindFirstFileW(pszFile, &FileData); - if (hFindFile == INVALID_HANDLE_VALUE) - return FALSE; - FindClose(hFindFile); - pfad->dwFileAttributes = FileData.dwFileAttributes; - pfad->ftCreationTime = FileData.ftCreationTime; - pfad->ftLastAccessTime = FileData.ftLastAccessTime; - pfad->ftLastWriteTime = FileData.ftLastWriteTime; - pfad->nFileSizeHigh = FileData.nFileSizeHigh; - pfad->nFileSizeLow = FileData.nFileSizeLow; - return TRUE; + HANDLE hFindFile; + WIN32_FIND_DATAW FileData; + hFindFile = FindFirstFileW(pszFile, &FileData); + if (hFindFile == INVALID_HANDLE_VALUE) + return FALSE; + FindClose(hFindFile); + pfad->dwFileAttributes = FileData.dwFileAttributes; + pfad->ftCreationTime = FileData.ftCreationTime; + pfad->ftLastAccessTime = FileData.ftLastAccessTime; + pfad->ftLastWriteTime = FileData.ftLastWriteTime; + pfad->nFileSizeHigh = FileData.nFileSizeHigh; + pfad->nFileSizeLow = FileData.nFileSizeLow; + return TRUE; } -static int +static int win32_stat(const char* path, struct win32_stat *result) { - WIN32_FILE_ATTRIBUTE_DATA info; - int code; - char *dot; - if (!GetFileAttributesExA(path, GetFileExInfoStandard, &info)) { - if (GetLastError() != ERROR_SHARING_VIOLATION) { - /* Protocol violation: we explicitly clear errno, instead of - setting it to a POSIX error. Callers should use GetLastError. */ - errno = 0; - return -1; - } else { - /* Could not get attributes on open file. Fall back to - reading the directory. */ - if (!attributes_from_dir(path, &info)) { - /* Very strange. This should not fail now */ - errno = 0; - return -1; - } - } - } - code = attribute_data_to_stat(&info, result); - if (code != 0) - return code; - /* Set S_IFEXEC if it is an .exe, .bat, ... */ - dot = strrchr(path, '.'); - if (dot) { - if (stricmp(dot, ".bat") == 0 || - stricmp(dot, ".cmd") == 0 || - stricmp(dot, ".exe") == 0 || - stricmp(dot, ".com") == 0) - result->st_mode |= 0111; - } - return code; + WIN32_FILE_ATTRIBUTE_DATA info; + int code; + char *dot; + if (!GetFileAttributesExA(path, GetFileExInfoStandard, &info)) { + if (GetLastError() != ERROR_SHARING_VIOLATION) { + /* Protocol violation: we explicitly clear errno, instead of + setting it to a POSIX error. Callers should use GetLastError. */ + errno = 0; + return -1; + } else { + /* Could not get attributes on open file. Fall back to + reading the directory. */ + if (!attributes_from_dir(path, &info)) { + /* Very strange. This should not fail now */ + errno = 0; + return -1; + } + } + } + code = attribute_data_to_stat(&info, result); + if (code != 0) + return code; + /* Set S_IFEXEC if it is an .exe, .bat, ... */ + dot = strrchr(path, '.'); + if (dot) { + if (stricmp(dot, ".bat") == 0 || + stricmp(dot, ".cmd") == 0 || + stricmp(dot, ".exe") == 0 || + stricmp(dot, ".com") == 0) + result->st_mode |= 0111; + } + return code; } -static int +static int win32_wstat(const wchar_t* path, struct win32_stat *result) { - int code; - const wchar_t *dot; - WIN32_FILE_ATTRIBUTE_DATA info; - if (!GetFileAttributesExW(path, GetFileExInfoStandard, &info)) { - if (GetLastError() != ERROR_SHARING_VIOLATION) { - /* Protocol violation: we explicitly clear errno, instead of - setting it to a POSIX error. Callers should use GetLastError. */ - errno = 0; - return -1; - } else { - /* Could not get attributes on open file. Fall back to - reading the directory. */ - if (!attributes_from_dir_w(path, &info)) { - /* Very strange. This should not fail now */ - errno = 0; - return -1; - } - } - } - code = attribute_data_to_stat(&info, result); - if (code < 0) - return code; - /* Set IFEXEC if it is an .exe, .bat, ... */ - dot = wcsrchr(path, '.'); - if (dot) { - if (_wcsicmp(dot, L".bat") == 0 || - _wcsicmp(dot, L".cmd") == 0 || - _wcsicmp(dot, L".exe") == 0 || - _wcsicmp(dot, L".com") == 0) - result->st_mode |= 0111; - } - return code; + int code; + const wchar_t *dot; + WIN32_FILE_ATTRIBUTE_DATA info; + if (!GetFileAttributesExW(path, GetFileExInfoStandard, &info)) { + if (GetLastError() != ERROR_SHARING_VIOLATION) { + /* Protocol violation: we explicitly clear errno, instead of + setting it to a POSIX error. Callers should use GetLastError. */ + errno = 0; + return -1; + } else { + /* Could not get attributes on open file. Fall back to + reading the directory. */ + if (!attributes_from_dir_w(path, &info)) { + /* Very strange. This should not fail now */ + errno = 0; + return -1; + } + } + } + code = attribute_data_to_stat(&info, result); + if (code < 0) + return code; + /* Set IFEXEC if it is an .exe, .bat, ... */ + dot = wcsrchr(path, '.'); + if (dot) { + if (_wcsicmp(dot, L".bat") == 0 || + _wcsicmp(dot, L".cmd") == 0 || + _wcsicmp(dot, L".exe") == 0 || + _wcsicmp(dot, L".com") == 0) + result->st_mode |= 0111; + } + return code; } static int win32_fstat(int file_number, struct win32_stat *result) { - BY_HANDLE_FILE_INFORMATION info; - HANDLE h; - int type; - - h = (HANDLE)_get_osfhandle(file_number); - - /* Protocol violation: we explicitly clear errno, instead of - setting it to a POSIX error. Callers should use GetLastError. */ - errno = 0; - - if (h == INVALID_HANDLE_VALUE) { - /* This is really a C library error (invalid file handle). - We set the Win32 error to the closes one matching. */ - SetLastError(ERROR_INVALID_HANDLE); - return -1; - } - memset(result, 0, sizeof(*result)); - - type = GetFileType(h); - if (type == FILE_TYPE_UNKNOWN) { - DWORD error = GetLastError(); - if (error != 0) { - return -1; - } - /* else: valid but unknown file */ - } - - if (type != FILE_TYPE_DISK) { - if (type == FILE_TYPE_CHAR) - result->st_mode = _S_IFCHR; - else if (type == FILE_TYPE_PIPE) - result->st_mode = _S_IFIFO; - return 0; - } - - if (!GetFileInformationByHandle(h, &info)) { - return -1; - } - - /* similar to stat() */ - result->st_mode = attributes_to_mode(info.dwFileAttributes); - result->st_size = (((__int64)info.nFileSizeHigh)<<32) + info.nFileSizeLow; - FILE_TIME_to_time_t_nsec(&info.ftCreationTime, &result->st_ctime, &result->st_ctime_nsec); - FILE_TIME_to_time_t_nsec(&info.ftLastWriteTime, &result->st_mtime, &result->st_mtime_nsec); - FILE_TIME_to_time_t_nsec(&info.ftLastAccessTime, &result->st_atime, &result->st_atime_nsec); - /* specific to fstat() */ - result->st_nlink = info.nNumberOfLinks; - result->st_ino = (((__int64)info.nFileIndexHigh)<<32) + info.nFileIndexLow; - return 0; + BY_HANDLE_FILE_INFORMATION info; + HANDLE h; + int type; + + h = (HANDLE)_get_osfhandle(file_number); + + /* Protocol violation: we explicitly clear errno, instead of + setting it to a POSIX error. Callers should use GetLastError. */ + errno = 0; + + if (h == INVALID_HANDLE_VALUE) { + /* This is really a C library error (invalid file handle). + We set the Win32 error to the closes one matching. */ + SetLastError(ERROR_INVALID_HANDLE); + return -1; + } + memset(result, 0, sizeof(*result)); + + type = GetFileType(h); + if (type == FILE_TYPE_UNKNOWN) { + DWORD error = GetLastError(); + if (error != 0) { + return -1; + } + /* else: valid but unknown file */ + } + + if (type != FILE_TYPE_DISK) { + if (type == FILE_TYPE_CHAR) + result->st_mode = _S_IFCHR; + else if (type == FILE_TYPE_PIPE) + result->st_mode = _S_IFIFO; + return 0; + } + + if (!GetFileInformationByHandle(h, &info)) { + return -1; + } + + /* similar to stat() */ + result->st_mode = attributes_to_mode(info.dwFileAttributes); + result->st_size = (((__int64)info.nFileSizeHigh)<<32) + info.nFileSizeLow; + FILE_TIME_to_time_t_nsec(&info.ftCreationTime, &result->st_ctime, &result->st_ctime_nsec); + FILE_TIME_to_time_t_nsec(&info.ftLastWriteTime, &result->st_mtime, &result->st_mtime_nsec); + FILE_TIME_to_time_t_nsec(&info.ftLastAccessTime, &result->st_atime, &result->st_atime_nsec); + /* specific to fstat() */ + result->st_nlink = info.nNumberOfLinks; + result->st_ino = (((__int64)info.nFileIndexHigh)<<32) + info.nFileIndexLow; + return 0; } #endif /* MS_WINDOWS */ @@ -1117,39 +1118,39 @@ See os.stat for more information."); static PyStructSequence_Field stat_result_fields[] = { - {"st_mode", "protection bits"}, - {"st_ino", "inode"}, - {"st_dev", "device"}, - {"st_nlink", "number of hard links"}, - {"st_uid", "user ID of owner"}, - {"st_gid", "group ID of owner"}, - {"st_size", "total size, in bytes"}, - /* The NULL is replaced with PyStructSequence_UnnamedField later. */ - {NULL, "integer time of last access"}, - {NULL, "integer time of last modification"}, - {NULL, "integer time of last change"}, - {"st_atime", "time of last access"}, - {"st_mtime", "time of last modification"}, - {"st_ctime", "time of last change"}, + {"st_mode", "protection bits"}, + {"st_ino", "inode"}, + {"st_dev", "device"}, + {"st_nlink", "number of hard links"}, + {"st_uid", "user ID of owner"}, + {"st_gid", "group ID of owner"}, + {"st_size", "total size, in bytes"}, + /* The NULL is replaced with PyStructSequence_UnnamedField later. */ + {NULL, "integer time of last access"}, + {NULL, "integer time of last modification"}, + {NULL, "integer time of last change"}, + {"st_atime", "time of last access"}, + {"st_mtime", "time of last modification"}, + {"st_ctime", "time of last change"}, #ifdef HAVE_STRUCT_STAT_ST_BLKSIZE - {"st_blksize", "blocksize for filesystem I/O"}, + {"st_blksize", "blocksize for filesystem I/O"}, #endif #ifdef HAVE_STRUCT_STAT_ST_BLOCKS - {"st_blocks", "number of blocks allocated"}, + {"st_blocks", "number of blocks allocated"}, #endif #ifdef HAVE_STRUCT_STAT_ST_RDEV - {"st_rdev", "device type (if inode device)"}, + {"st_rdev", "device type (if inode device)"}, #endif #ifdef HAVE_STRUCT_STAT_ST_FLAGS - {"st_flags", "user defined flags for file"}, + {"st_flags", "user defined flags for file"}, #endif #ifdef HAVE_STRUCT_STAT_ST_GEN - {"st_gen", "generation number"}, + {"st_gen", "generation number"}, #endif #ifdef HAVE_STRUCT_STAT_ST_BIRTHTIME - {"st_birthtime", "time of creation"}, + {"st_birthtime", "time of creation"}, #endif - {0} + {0} }; #ifdef HAVE_STRUCT_STAT_ST_BLKSIZE @@ -1189,10 +1190,10 @@ #endif static PyStructSequence_Desc stat_result_desc = { - "stat_result", /* name */ - stat_result__doc__, /* doc */ - stat_result_fields, - 10 + "stat_result", /* name */ + stat_result__doc__, /* doc */ + stat_result_fields, + 10 }; PyDoc_STRVAR(statvfs_result__doc__, @@ -1204,24 +1205,24 @@ See os.statvfs for more information."); static PyStructSequence_Field statvfs_result_fields[] = { - {"f_bsize", }, - {"f_frsize", }, - {"f_blocks", }, - {"f_bfree", }, - {"f_bavail", }, - {"f_files", }, - {"f_ffree", }, - {"f_favail", }, - {"f_flag", }, - {"f_namemax",}, - {0} + {"f_bsize", }, + {"f_frsize", }, + {"f_blocks", }, + {"f_bfree", }, + {"f_bavail", }, + {"f_files", }, + {"f_ffree", }, + {"f_favail", }, + {"f_flag", }, + {"f_namemax",}, + {0} }; static PyStructSequence_Desc statvfs_result_desc = { - "statvfs_result", /* name */ - statvfs_result__doc__, /* doc */ - statvfs_result_fields, - 10 + "statvfs_result", /* name */ + statvfs_result__doc__, /* doc */ + statvfs_result_fields, + 10 }; static int initialized; @@ -1232,23 +1233,23 @@ static PyObject * statresult_new(PyTypeObject *type, PyObject *args, PyObject *kwds) { - PyStructSequence *result; - int i; + PyStructSequence *result; + int i; - result = (PyStructSequence*)structseq_new(type, args, kwds); - if (!result) - return NULL; - /* If we have been initialized from a tuple, - st_?time might be set to None. Initialize it - from the int slots. */ - for (i = 7; i <= 9; i++) { - if (result->ob_item[i+3] == Py_None) { - Py_DECREF(Py_None); - Py_INCREF(result->ob_item[i]); - result->ob_item[i+3] = result->ob_item[i]; - } - } - return (PyObject*)result; + result = (PyStructSequence*)structseq_new(type, args, kwds); + if (!result) + return NULL; + /* If we have been initialized from a tuple, + st_?time might be set to None. Initialize it + from the int slots. */ + for (i = 7; i <= 9; i++) { + if (result->ob_item[i+3] == Py_None) { + Py_DECREF(Py_None); + Py_INCREF(result->ob_item[i]); + result->ob_item[i+3] = result->ob_item[i]; + } + } + return (PyObject*)result; } @@ -1266,36 +1267,36 @@ static PyObject* stat_float_times(PyObject* self, PyObject *args) { - int newval = -1; - if (!PyArg_ParseTuple(args, "|i:stat_float_times", &newval)) - return NULL; - if (newval == -1) - /* Return old value */ - return PyBool_FromLong(_stat_float_times); - _stat_float_times = newval; - Py_INCREF(Py_None); - return Py_None; + int newval = -1; + if (!PyArg_ParseTuple(args, "|i:stat_float_times", &newval)) + return NULL; + if (newval == -1) + /* Return old value */ + return PyBool_FromLong(_stat_float_times); + _stat_float_times = newval; + Py_INCREF(Py_None); + return Py_None; } static void fill_time(PyObject *v, int index, time_t sec, unsigned long nsec) { - PyObject *fval,*ival; + PyObject *fval,*ival; #if SIZEOF_TIME_T > SIZEOF_LONG - ival = PyLong_FromLongLong((PY_LONG_LONG)sec); + ival = PyLong_FromLongLong((PY_LONG_LONG)sec); #else - ival = PyLong_FromLong((long)sec); + ival = PyLong_FromLong((long)sec); #endif - if (!ival) - return; - if (_stat_float_times) { - fval = PyFloat_FromDouble(sec + 1e-9*nsec); - } else { - fval = ival; - Py_INCREF(fval); - } - PyStructSequence_SET_ITEM(v, index, ival); - PyStructSequence_SET_ITEM(v, index+3, fval); + if (!ival) + return; + if (_stat_float_times) { + fval = PyFloat_FromDouble(sec + 1e-9*nsec); + } else { + fval = ival; + Py_INCREF(fval); + } + PyStructSequence_SET_ITEM(v, index, ival); + PyStructSequence_SET_ITEM(v, index+3, fval); } /* pack a system stat C structure into the Python stat tuple @@ -1303,99 +1304,99 @@ static PyObject* _pystat_fromstructstat(STRUCT_STAT *st) { - unsigned long ansec, mnsec, cnsec; - PyObject *v = PyStructSequence_New(&StatResultType); - if (v == NULL) - return NULL; + unsigned long ansec, mnsec, cnsec; + PyObject *v = PyStructSequence_New(&StatResultType); + if (v == NULL) + return NULL; - PyStructSequence_SET_ITEM(v, 0, PyLong_FromLong((long)st->st_mode)); + PyStructSequence_SET_ITEM(v, 0, PyLong_FromLong((long)st->st_mode)); #ifdef HAVE_LARGEFILE_SUPPORT - PyStructSequence_SET_ITEM(v, 1, - PyLong_FromLongLong((PY_LONG_LONG)st->st_ino)); + PyStructSequence_SET_ITEM(v, 1, + PyLong_FromLongLong((PY_LONG_LONG)st->st_ino)); #else - PyStructSequence_SET_ITEM(v, 1, PyLong_FromLong((long)st->st_ino)); + PyStructSequence_SET_ITEM(v, 1, PyLong_FromLong((long)st->st_ino)); #endif #if defined(HAVE_LONG_LONG) && !defined(MS_WINDOWS) - PyStructSequence_SET_ITEM(v, 2, - PyLong_FromLongLong((PY_LONG_LONG)st->st_dev)); + PyStructSequence_SET_ITEM(v, 2, + PyLong_FromLongLong((PY_LONG_LONG)st->st_dev)); #else - PyStructSequence_SET_ITEM(v, 2, PyLong_FromLong((long)st->st_dev)); + PyStructSequence_SET_ITEM(v, 2, PyLong_FromLong((long)st->st_dev)); #endif - PyStructSequence_SET_ITEM(v, 3, PyLong_FromLong((long)st->st_nlink)); - PyStructSequence_SET_ITEM(v, 4, PyLong_FromLong((long)st->st_uid)); - PyStructSequence_SET_ITEM(v, 5, PyLong_FromLong((long)st->st_gid)); + PyStructSequence_SET_ITEM(v, 3, PyLong_FromLong((long)st->st_nlink)); + PyStructSequence_SET_ITEM(v, 4, PyLong_FromLong((long)st->st_uid)); + PyStructSequence_SET_ITEM(v, 5, PyLong_FromLong((long)st->st_gid)); #ifdef HAVE_LARGEFILE_SUPPORT - PyStructSequence_SET_ITEM(v, 6, - PyLong_FromLongLong((PY_LONG_LONG)st->st_size)); + PyStructSequence_SET_ITEM(v, 6, + PyLong_FromLongLong((PY_LONG_LONG)st->st_size)); #else - PyStructSequence_SET_ITEM(v, 6, PyLong_FromLong(st->st_size)); + PyStructSequence_SET_ITEM(v, 6, PyLong_FromLong(st->st_size)); #endif #if defined(HAVE_STAT_TV_NSEC) - ansec = st->st_atim.tv_nsec; - mnsec = st->st_mtim.tv_nsec; - cnsec = st->st_ctim.tv_nsec; + ansec = st->st_atim.tv_nsec; + mnsec = st->st_mtim.tv_nsec; + cnsec = st->st_ctim.tv_nsec; #elif defined(HAVE_STAT_TV_NSEC2) - ansec = st->st_atimespec.tv_nsec; - mnsec = st->st_mtimespec.tv_nsec; - cnsec = st->st_ctimespec.tv_nsec; + ansec = st->st_atimespec.tv_nsec; + mnsec = st->st_mtimespec.tv_nsec; + cnsec = st->st_ctimespec.tv_nsec; #elif defined(HAVE_STAT_NSEC) - ansec = st->st_atime_nsec; - mnsec = st->st_mtime_nsec; - cnsec = st->st_ctime_nsec; -#else - ansec = mnsec = cnsec = 0; -#endif - fill_time(v, 7, st->st_atime, ansec); - fill_time(v, 8, st->st_mtime, mnsec); - fill_time(v, 9, st->st_ctime, cnsec); + ansec = st->st_atime_nsec; + mnsec = st->st_mtime_nsec; + cnsec = st->st_ctime_nsec; +#else + ansec = mnsec = cnsec = 0; +#endif + fill_time(v, 7, st->st_atime, ansec); + fill_time(v, 8, st->st_mtime, mnsec); + fill_time(v, 9, st->st_ctime, cnsec); #ifdef HAVE_STRUCT_STAT_ST_BLKSIZE - PyStructSequence_SET_ITEM(v, ST_BLKSIZE_IDX, - PyLong_FromLong((long)st->st_blksize)); + PyStructSequence_SET_ITEM(v, ST_BLKSIZE_IDX, + PyLong_FromLong((long)st->st_blksize)); #endif #ifdef HAVE_STRUCT_STAT_ST_BLOCKS - PyStructSequence_SET_ITEM(v, ST_BLOCKS_IDX, - PyLong_FromLong((long)st->st_blocks)); + PyStructSequence_SET_ITEM(v, ST_BLOCKS_IDX, + PyLong_FromLong((long)st->st_blocks)); #endif #ifdef HAVE_STRUCT_STAT_ST_RDEV - PyStructSequence_SET_ITEM(v, ST_RDEV_IDX, - PyLong_FromLong((long)st->st_rdev)); + PyStructSequence_SET_ITEM(v, ST_RDEV_IDX, + PyLong_FromLong((long)st->st_rdev)); #endif #ifdef HAVE_STRUCT_STAT_ST_GEN - PyStructSequence_SET_ITEM(v, ST_GEN_IDX, - PyLong_FromLong((long)st->st_gen)); + PyStructSequence_SET_ITEM(v, ST_GEN_IDX, + PyLong_FromLong((long)st->st_gen)); #endif #ifdef HAVE_STRUCT_STAT_ST_BIRTHTIME - { - PyObject *val; - unsigned long bsec,bnsec; - bsec = (long)st->st_birthtime; + { + PyObject *val; + unsigned long bsec,bnsec; + bsec = (long)st->st_birthtime; #ifdef HAVE_STAT_TV_NSEC2 - bnsec = st->st_birthtimespec.tv_nsec; + bnsec = st->st_birthtimespec.tv_nsec; #else - bnsec = 0; + bnsec = 0; #endif - if (_stat_float_times) { - val = PyFloat_FromDouble(bsec + 1e-9*bnsec); - } else { - val = PyLong_FromLong((long)bsec); - } - PyStructSequence_SET_ITEM(v, ST_BIRTHTIME_IDX, - val); - } + if (_stat_float_times) { + val = PyFloat_FromDouble(bsec + 1e-9*bnsec); + } else { + val = PyLong_FromLong((long)bsec); + } + PyStructSequence_SET_ITEM(v, ST_BIRTHTIME_IDX, + val); + } #endif #ifdef HAVE_STRUCT_STAT_ST_FLAGS - PyStructSequence_SET_ITEM(v, ST_FLAGS_IDX, - PyLong_FromLong((long)st->st_flags)); + PyStructSequence_SET_ITEM(v, ST_FLAGS_IDX, + PyLong_FromLong((long)st->st_flags)); #endif - if (PyErr_Occurred()) { - Py_DECREF(v); - return NULL; - } + if (PyErr_Occurred()) { + Py_DECREF(v); + return NULL; + } - return v; + return v; } #ifdef MS_WINDOWS @@ -1414,107 +1415,107 @@ static BOOL IsUNCRootA(char *path, int pathlen) { - #define ISSLASH ISSLASHA + #define ISSLASH ISSLASHA - int i, share; + int i, share; - if (pathlen < 5 || !ISSLASH(path[0]) || !ISSLASH(path[1])) - /* minimum UNCRoot is \\x\y */ - return FALSE; - for (i = 2; i < pathlen ; i++) - if (ISSLASH(path[i])) break; - if (i == 2 || i == pathlen) - /* do not allow \\\SHARE or \\SERVER */ - return FALSE; - share = i+1; - for (i = share; i < pathlen; i++) - if (ISSLASH(path[i])) break; - return (i != share && (i == pathlen || i == pathlen-1)); + if (pathlen < 5 || !ISSLASH(path[0]) || !ISSLASH(path[1])) + /* minimum UNCRoot is \\x\y */ + return FALSE; + for (i = 2; i < pathlen ; i++) + if (ISSLASH(path[i])) break; + if (i == 2 || i == pathlen) + /* do not allow \\\SHARE or \\SERVER */ + return FALSE; + share = i+1; + for (i = share; i < pathlen; i++) + if (ISSLASH(path[i])) break; + return (i != share && (i == pathlen || i == pathlen-1)); - #undef ISSLASH + #undef ISSLASH } static BOOL IsUNCRootW(Py_UNICODE *path, int pathlen) { - #define ISSLASH ISSLASHW + #define ISSLASH ISSLASHW - int i, share; + int i, share; - if (pathlen < 5 || !ISSLASH(path[0]) || !ISSLASH(path[1])) - /* minimum UNCRoot is \\x\y */ - return FALSE; - for (i = 2; i < pathlen ; i++) - if (ISSLASH(path[i])) break; - if (i == 2 || i == pathlen) - /* do not allow \\\SHARE or \\SERVER */ - return FALSE; - share = i+1; - for (i = share; i < pathlen; i++) - if (ISSLASH(path[i])) break; - return (i != share && (i == pathlen || i == pathlen-1)); + if (pathlen < 5 || !ISSLASH(path[0]) || !ISSLASH(path[1])) + /* minimum UNCRoot is \\x\y */ + return FALSE; + for (i = 2; i < pathlen ; i++) + if (ISSLASH(path[i])) break; + if (i == 2 || i == pathlen) + /* do not allow \\\SHARE or \\SERVER */ + return FALSE; + share = i+1; + for (i = share; i < pathlen; i++) + if (ISSLASH(path[i])) break; + return (i != share && (i == pathlen || i == pathlen-1)); - #undef ISSLASH + #undef ISSLASH } #endif /* MS_WINDOWS */ static PyObject * posix_do_stat(PyObject *self, PyObject *args, - char *format, + char *format, #ifdef __VMS - int (*statfunc)(const char *, STRUCT_STAT *, ...), + int (*statfunc)(const char *, STRUCT_STAT *, ...), #else - int (*statfunc)(const char *, STRUCT_STAT *), + int (*statfunc)(const char *, STRUCT_STAT *), #endif - char *wformat, - int (*wstatfunc)(const Py_UNICODE *, STRUCT_STAT *)) + char *wformat, + int (*wstatfunc)(const Py_UNICODE *, STRUCT_STAT *)) { - STRUCT_STAT st; - PyObject *opath; - char *path; - int res; - PyObject *result; + STRUCT_STAT st; + PyObject *opath; + char *path; + int res; + PyObject *result; #ifdef MS_WINDOWS - PyUnicodeObject *po; - if (PyArg_ParseTuple(args, wformat, &po)) { - Py_UNICODE *wpath = PyUnicode_AS_UNICODE(po); - - Py_BEGIN_ALLOW_THREADS - /* PyUnicode_AS_UNICODE result OK without - thread lock as it is a simple dereference. */ - res = wstatfunc(wpath, &st); - Py_END_ALLOW_THREADS - - if (res != 0) - return win32_error_unicode("stat", wpath); - return _pystat_fromstructstat(&st); - } - /* Drop the argument parsing error as narrow strings - are also valid. */ - PyErr_Clear(); -#endif - - if (!PyArg_ParseTuple(args, format, - PyUnicode_FSConverter, &opath)) - return NULL; - path = PyBytes_AsString(opath); - Py_BEGIN_ALLOW_THREADS - res = (*statfunc)(path, &st); - Py_END_ALLOW_THREADS + PyUnicodeObject *po; + if (PyArg_ParseTuple(args, wformat, &po)) { + Py_UNICODE *wpath = PyUnicode_AS_UNICODE(po); + + Py_BEGIN_ALLOW_THREADS + /* PyUnicode_AS_UNICODE result OK without + thread lock as it is a simple dereference. */ + res = wstatfunc(wpath, &st); + Py_END_ALLOW_THREADS + + if (res != 0) + return win32_error_unicode("stat", wpath); + return _pystat_fromstructstat(&st); + } + /* Drop the argument parsing error as narrow strings + are also valid. */ + PyErr_Clear(); +#endif + + if (!PyArg_ParseTuple(args, format, + PyUnicode_FSConverter, &opath)) + return NULL; + path = PyBytes_AsString(opath); + Py_BEGIN_ALLOW_THREADS + res = (*statfunc)(path, &st); + Py_END_ALLOW_THREADS - if (res != 0) { + if (res != 0) { #ifdef MS_WINDOWS - result = win32_error("stat", path); + result = win32_error("stat", path); #else - result = posix_error_with_filename(path); + result = posix_error_with_filename(path); #endif - } - else - result = _pystat_fromstructstat(&st); + } + else + result = _pystat_fromstructstat(&st); - Py_DECREF(opath); - return result; + Py_DECREF(opath); + return result; } /* POSIX methods */ @@ -1530,53 +1531,53 @@ static PyObject * posix_access(PyObject *self, PyObject *args) { - PyObject *opath; - char *path; - int mode; - + PyObject *opath; + char *path; + int mode; + #ifdef MS_WINDOWS - DWORD attr; - PyUnicodeObject *po; - if (PyArg_ParseTuple(args, "Ui:access", &po, &mode)) { - Py_BEGIN_ALLOW_THREADS - /* PyUnicode_AS_UNICODE OK without thread lock as - it is a simple dereference. */ - attr = GetFileAttributesW(PyUnicode_AS_UNICODE(po)); - Py_END_ALLOW_THREADS - goto finish; - } - /* Drop the argument parsing error as narrow strings - are also valid. */ - PyErr_Clear(); - if (!PyArg_ParseTuple(args, "O&i:access", - PyUnicode_FSConverter, &opath, &mode)) - return NULL; - path = PyBytes_AsString(opath); - Py_BEGIN_ALLOW_THREADS - attr = GetFileAttributesA(path); - Py_END_ALLOW_THREADS - Py_DECREF(opath); + DWORD attr; + PyUnicodeObject *po; + if (PyArg_ParseTuple(args, "Ui:access", &po, &mode)) { + Py_BEGIN_ALLOW_THREADS + /* PyUnicode_AS_UNICODE OK without thread lock as + it is a simple dereference. */ + attr = GetFileAttributesW(PyUnicode_AS_UNICODE(po)); + Py_END_ALLOW_THREADS + goto finish; + } + /* Drop the argument parsing error as narrow strings + are also valid. */ + PyErr_Clear(); + if (!PyArg_ParseTuple(args, "O&i:access", + PyUnicode_FSConverter, &opath, &mode)) + return NULL; + path = PyBytes_AsString(opath); + Py_BEGIN_ALLOW_THREADS + attr = GetFileAttributesA(path); + Py_END_ALLOW_THREADS + Py_DECREF(opath); finish: - if (attr == 0xFFFFFFFF) - /* File does not exist, or cannot read attributes */ - return PyBool_FromLong(0); - /* Access is possible if either write access wasn't requested, or - the file isn't read-only, or if it's a directory, as there are - no read-only directories on Windows. */ - return PyBool_FromLong(!(mode & 2) - || !(attr & FILE_ATTRIBUTE_READONLY) - || (attr & FILE_ATTRIBUTE_DIRECTORY)); -#else - int res; - if (!PyArg_ParseTuple(args, "O&i:access", - PyUnicode_FSConverter, &opath, &mode)) - return NULL; - path = PyBytes_AsString(opath); - Py_BEGIN_ALLOW_THREADS - res = access(path, mode); - Py_END_ALLOW_THREADS - Py_DECREF(opath); - return PyBool_FromLong(res == 0); + if (attr == 0xFFFFFFFF) + /* File does not exist, or cannot read attributes */ + return PyBool_FromLong(0); + /* Access is possible if either write access wasn't requested, or + the file isn't read-only, or if it's a directory, as there are + no read-only directories on Windows. */ + return PyBool_FromLong(!(mode & 2) + || !(attr & FILE_ATTRIBUTE_READONLY) + || (attr & FILE_ATTRIBUTE_DIRECTORY)); +#else + int res; + if (!PyArg_ParseTuple(args, "O&i:access", + PyUnicode_FSConverter, &opath, &mode)) + return NULL; + path = PyBytes_AsString(opath); + Py_BEGIN_ALLOW_THREADS + res = access(path, mode); + Py_END_ALLOW_THREADS + Py_DECREF(opath); + return PyBool_FromLong(res == 0); #endif } @@ -1601,26 +1602,26 @@ static PyObject * posix_ttyname(PyObject *self, PyObject *args) { - int id; - char *ret; + int id; + char *ret; - if (!PyArg_ParseTuple(args, "i:ttyname", &id)) - return NULL; + if (!PyArg_ParseTuple(args, "i:ttyname", &id)) + return NULL; #if defined(__VMS) - /* file descriptor 0 only, the default input device (stdin) */ - if (id == 0) { - ret = ttyname(); - } - else { - ret = NULL; - } -#else - ret = ttyname(id); -#endif - if (ret == NULL) - return posix_error(); - return PyUnicode_FromString(ret); + /* file descriptor 0 only, the default input device (stdin) */ + if (id == 0) { + ret = ttyname(); + } + else { + ret = NULL; + } +#else + ret = ttyname(id); +#endif + if (ret == NULL) + return posix_error(); + return PyUnicode_FromString(ret); } #endif @@ -1632,17 +1633,17 @@ static PyObject * posix_ctermid(PyObject *self, PyObject *noargs) { - char *ret; - char buffer[L_ctermid]; + char *ret; + char buffer[L_ctermid]; #ifdef USE_CTERMID_R - ret = ctermid_r(buffer); + ret = ctermid_r(buffer); #else - ret = ctermid(buffer); + ret = ctermid(buffer); #endif - if (ret == NULL) - return posix_error(); - return PyUnicode_FromString(buffer); + if (ret == NULL) + return posix_error(); + return PyUnicode_FromString(buffer); } #endif @@ -1654,13 +1655,13 @@ posix_chdir(PyObject *self, PyObject *args) { #ifdef MS_WINDOWS - return win32_1str(args, "chdir", "y:chdir", win32_chdir, "U:chdir", win32_wchdir); + return win32_1str(args, "chdir", "y:chdir", win32_chdir, "U:chdir", win32_wchdir); #elif defined(PYOS_OS2) && defined(PYCC_GCC) - return posix_1str(args, "O&:chdir", _chdir2); + return posix_1str(args, "O&:chdir", _chdir2); #elif defined(__VMS) - return posix_1str(args, "O&:chdir", (int (*)(const char *))chdir); + return posix_1str(args, "O&:chdir", (int (*)(const char *))chdir); #else - return posix_1str(args, "O&:chdir", chdir); + return posix_1str(args, "O&:chdir", chdir); #endif } @@ -1673,7 +1674,7 @@ static PyObject * posix_fchdir(PyObject *self, PyObject *fdobj) { - return posix_fildes(fdobj, fchdir); + return posix_fildes(fdobj, fchdir); } #endif /* HAVE_FCHDIR */ @@ -1685,73 +1686,73 @@ static PyObject * posix_chmod(PyObject *self, PyObject *args) { - PyObject *opath = NULL; - char *path = NULL; - int i; - int res; + PyObject *opath = NULL; + char *path = NULL; + int i; + int res; #ifdef MS_WINDOWS - DWORD attr; - PyUnicodeObject *po; - if (PyArg_ParseTuple(args, "Ui|:chmod", &po, &i)) { - Py_BEGIN_ALLOW_THREADS - attr = GetFileAttributesW(PyUnicode_AS_UNICODE(po)); - if (attr != 0xFFFFFFFF) { - if (i & _S_IWRITE) - attr &= ~FILE_ATTRIBUTE_READONLY; - else - attr |= FILE_ATTRIBUTE_READONLY; - res = SetFileAttributesW(PyUnicode_AS_UNICODE(po), attr); - } - else - res = 0; - Py_END_ALLOW_THREADS - if (!res) - return win32_error_unicode("chmod", - PyUnicode_AS_UNICODE(po)); - Py_INCREF(Py_None); - return Py_None; - } - /* Drop the argument parsing error as narrow strings - are also valid. */ - PyErr_Clear(); - - if (!PyArg_ParseTuple(args, "O&i:chmod", PyUnicode_FSConverter, - &opath, &i)) - return NULL; - path = PyBytes_AsString(opath); - Py_BEGIN_ALLOW_THREADS - attr = GetFileAttributesA(path); - if (attr != 0xFFFFFFFF) { - if (i & _S_IWRITE) - attr &= ~FILE_ATTRIBUTE_READONLY; - else - attr |= FILE_ATTRIBUTE_READONLY; - res = SetFileAttributesA(path, attr); - } - else - res = 0; - Py_END_ALLOW_THREADS - if (!res) { - win32_error("chmod", path); - Py_DECREF(opath); - return NULL; - } - Py_DECREF(opath); - Py_INCREF(Py_None); - return Py_None; + DWORD attr; + PyUnicodeObject *po; + if (PyArg_ParseTuple(args, "Ui|:chmod", &po, &i)) { + Py_BEGIN_ALLOW_THREADS + attr = GetFileAttributesW(PyUnicode_AS_UNICODE(po)); + if (attr != 0xFFFFFFFF) { + if (i & _S_IWRITE) + attr &= ~FILE_ATTRIBUTE_READONLY; + else + attr |= FILE_ATTRIBUTE_READONLY; + res = SetFileAttributesW(PyUnicode_AS_UNICODE(po), attr); + } + else + res = 0; + Py_END_ALLOW_THREADS + if (!res) + return win32_error_unicode("chmod", + PyUnicode_AS_UNICODE(po)); + Py_INCREF(Py_None); + return Py_None; + } + /* Drop the argument parsing error as narrow strings + are also valid. */ + PyErr_Clear(); + + if (!PyArg_ParseTuple(args, "O&i:chmod", PyUnicode_FSConverter, + &opath, &i)) + return NULL; + path = PyBytes_AsString(opath); + Py_BEGIN_ALLOW_THREADS + attr = GetFileAttributesA(path); + if (attr != 0xFFFFFFFF) { + if (i & _S_IWRITE) + attr &= ~FILE_ATTRIBUTE_READONLY; + else + attr |= FILE_ATTRIBUTE_READONLY; + res = SetFileAttributesA(path, attr); + } + else + res = 0; + Py_END_ALLOW_THREADS + if (!res) { + win32_error("chmod", path); + Py_DECREF(opath); + return NULL; + } + Py_DECREF(opath); + Py_INCREF(Py_None); + return Py_None; #else /* MS_WINDOWS */ - if (!PyArg_ParseTuple(args, "O&i:chmod", PyUnicode_FSConverter, - &opath, &i)) - return NULL; - path = PyBytes_AsString(opath); - Py_BEGIN_ALLOW_THREADS - res = chmod(path, i); - Py_END_ALLOW_THREADS - if (res < 0) - return posix_error_with_allocated_filename(opath); - Py_DECREF(opath); - Py_INCREF(Py_None); - return Py_None; + if (!PyArg_ParseTuple(args, "O&i:chmod", PyUnicode_FSConverter, + &opath, &i)) + return NULL; + path = PyBytes_AsString(opath); + Py_BEGIN_ALLOW_THREADS + res = chmod(path, i); + Py_END_ALLOW_THREADS + if (res < 0) + return posix_error_with_allocated_filename(opath); + Py_DECREF(opath); + Py_INCREF(Py_None); + return Py_None; #endif } @@ -1764,15 +1765,15 @@ static PyObject * posix_fchmod(PyObject *self, PyObject *args) { - int fd, mode, res; - if (!PyArg_ParseTuple(args, "ii:fchmod", &fd, &mode)) - return NULL; - Py_BEGIN_ALLOW_THREADS - res = fchmod(fd, mode); - Py_END_ALLOW_THREADS - if (res < 0) - return posix_error(); - Py_RETURN_NONE; + int fd, mode, res; + if (!PyArg_ParseTuple(args, "ii:fchmod", &fd, &mode)) + return NULL; + Py_BEGIN_ALLOW_THREADS + res = fchmod(fd, mode); + Py_END_ALLOW_THREADS + if (res < 0) + return posix_error(); + Py_RETURN_NONE; } #endif /* HAVE_FCHMOD */ @@ -1785,21 +1786,21 @@ static PyObject * posix_lchmod(PyObject *self, PyObject *args) { - PyObject *opath; - char *path; - int i; - int res; - if (!PyArg_ParseTuple(args, "O&i:lchmod", PyUnicode_FSConverter, - &opath, &i)) - return NULL; - path = PyBytes_AsString(opath); - Py_BEGIN_ALLOW_THREADS - res = lchmod(path, i); - Py_END_ALLOW_THREADS - if (res < 0) - return posix_error_with_allocated_filename(opath); - Py_DECREF(opath); - Py_RETURN_NONE; + PyObject *opath; + char *path; + int i; + int res; + if (!PyArg_ParseTuple(args, "O&i:lchmod", PyUnicode_FSConverter, + &opath, &i)) + return NULL; + path = PyBytes_AsString(opath); + Py_BEGIN_ALLOW_THREADS + res = lchmod(path, i); + Py_END_ALLOW_THREADS + if (res < 0) + return posix_error_with_allocated_filename(opath); + Py_DECREF(opath); + Py_RETURN_NONE; } #endif /* HAVE_LCHMOD */ @@ -1812,22 +1813,22 @@ static PyObject * posix_chflags(PyObject *self, PyObject *args) { - PyObject *opath; - char *path; - unsigned long flags; - int res; - if (!PyArg_ParseTuple(args, "O&k:chflags", - PyUnicode_FSConverter, &opath, &flags)) - return NULL; - path = PyBytes_AsString(opath); - Py_BEGIN_ALLOW_THREADS - res = chflags(path, flags); - Py_END_ALLOW_THREADS - if (res < 0) - return posix_error_with_allocated_filename(opath); - Py_DECREF(opath); - Py_INCREF(Py_None); - return Py_None; + PyObject *opath; + char *path; + unsigned long flags; + int res; + if (!PyArg_ParseTuple(args, "O&k:chflags", + PyUnicode_FSConverter, &opath, &flags)) + return NULL; + path = PyBytes_AsString(opath); + Py_BEGIN_ALLOW_THREADS + res = chflags(path, flags); + Py_END_ALLOW_THREADS + if (res < 0) + return posix_error_with_allocated_filename(opath); + Py_DECREF(opath); + Py_INCREF(Py_None); + return Py_None; } #endif /* HAVE_CHFLAGS */ @@ -1840,22 +1841,22 @@ static PyObject * posix_lchflags(PyObject *self, PyObject *args) { - PyObject *opath; - char *path; - unsigned long flags; - int res; - if (!PyArg_ParseTuple(args, "O&k:lchflags", - PyUnicode_FSConverter, &opath, &flags)) - return NULL; - path = PyBytes_AsString(opath); - Py_BEGIN_ALLOW_THREADS - res = lchflags(path, flags); - Py_END_ALLOW_THREADS - if (res < 0) - return posix_error_with_allocated_filename(opath); - Py_DECREF(opath); - Py_INCREF(Py_None); - return Py_None; + PyObject *opath; + char *path; + unsigned long flags; + int res; + if (!PyArg_ParseTuple(args, "O&k:lchflags", + PyUnicode_FSConverter, &opath, &flags)) + return NULL; + path = PyBytes_AsString(opath); + Py_BEGIN_ALLOW_THREADS + res = lchflags(path, flags); + Py_END_ALLOW_THREADS + if (res < 0) + return posix_error_with_allocated_filename(opath); + Py_DECREF(opath); + Py_INCREF(Py_None); + return Py_None; } #endif /* HAVE_LCHFLAGS */ @@ -1867,7 +1868,7 @@ static PyObject * posix_chroot(PyObject *self, PyObject *args) { - return posix_1str(args, "O&:chroot", chroot); + return posix_1str(args, "O&:chroot", chroot); } #endif @@ -1910,23 +1911,23 @@ static PyObject * posix_chown(PyObject *self, PyObject *args) { - PyObject *opath; - char *path; - long uid, gid; - int res; - if (!PyArg_ParseTuple(args, "O&ll:chown", - PyUnicode_FSConverter, &opath, - &uid, &gid)) - return NULL; - path = PyBytes_AsString(opath); - Py_BEGIN_ALLOW_THREADS - res = chown(path, (uid_t) uid, (gid_t) gid); - Py_END_ALLOW_THREADS - if (res < 0) - return posix_error_with_allocated_filename(opath); - Py_DECREF(opath); - Py_INCREF(Py_None); - return Py_None; + PyObject *opath; + char *path; + long uid, gid; + int res; + if (!PyArg_ParseTuple(args, "O&ll:chown", + PyUnicode_FSConverter, &opath, + &uid, &gid)) + return NULL; + path = PyBytes_AsString(opath); + Py_BEGIN_ALLOW_THREADS + res = chown(path, (uid_t) uid, (gid_t) gid); + Py_END_ALLOW_THREADS + if (res < 0) + return posix_error_with_allocated_filename(opath); + Py_DECREF(opath); + Py_INCREF(Py_None); + return Py_None; } #endif /* HAVE_CHOWN */ @@ -1939,17 +1940,17 @@ static PyObject * posix_fchown(PyObject *self, PyObject *args) { - int fd; - long uid, gid; - int res; - if (!PyArg_ParseTuple(args, "ill:chown", &fd, &uid, &gid)) - return NULL; - Py_BEGIN_ALLOW_THREADS - res = fchown(fd, (uid_t) uid, (gid_t) gid); - Py_END_ALLOW_THREADS - if (res < 0) - return posix_error(); - Py_RETURN_NONE; + int fd; + long uid, gid; + int res; + if (!PyArg_ParseTuple(args, "ill:chown", &fd, &uid, &gid)) + return NULL; + Py_BEGIN_ALLOW_THREADS + res = fchown(fd, (uid_t) uid, (gid_t) gid); + Py_END_ALLOW_THREADS + if (res < 0) + return posix_error(); + Py_RETURN_NONE; } #endif /* HAVE_FCHOWN */ @@ -1962,23 +1963,23 @@ static PyObject * posix_lchown(PyObject *self, PyObject *args) { - PyObject *opath; - char *path; - long uid, gid; - int res; - if (!PyArg_ParseTuple(args, "O&ll:lchown", - PyUnicode_FSConverter, &opath, - &uid, &gid)) - return NULL; - path = PyBytes_AsString(opath); - Py_BEGIN_ALLOW_THREADS - res = lchown(path, (uid_t) uid, (gid_t) gid); - Py_END_ALLOW_THREADS - if (res < 0) - return posix_error_with_allocated_filename(opath); - Py_DECREF(opath); - Py_INCREF(Py_None); - return Py_None; + PyObject *opath; + char *path; + long uid, gid; + int res; + if (!PyArg_ParseTuple(args, "O&ll:lchown", + PyUnicode_FSConverter, &opath, + &uid, &gid)) + return NULL; + path = PyBytes_AsString(opath); + Py_BEGIN_ALLOW_THREADS + res = lchown(path, (uid_t) uid, (gid_t) gid); + Py_END_ALLOW_THREADS + if (res < 0) + return posix_error_with_allocated_filename(opath); + Py_DECREF(opath); + Py_INCREF(Py_None); + return Py_None; } #endif /* HAVE_LCHOWN */ @@ -1987,52 +1988,52 @@ static PyObject * posix_getcwd(int use_bytes) { - char buf[1026]; - char *res; + char buf[1026]; + char *res; #ifdef MS_WINDOWS - if (!use_bytes) { - wchar_t wbuf[1026]; - wchar_t *wbuf2 = wbuf; - PyObject *resobj; - DWORD len; - Py_BEGIN_ALLOW_THREADS - len = GetCurrentDirectoryW(sizeof wbuf/ sizeof wbuf[0], wbuf); - /* If the buffer is large enough, len does not include the - terminating \0. If the buffer is too small, len includes - the space needed for the terminator. */ - if (len >= sizeof wbuf/ sizeof wbuf[0]) { - wbuf2 = malloc(len * sizeof(wchar_t)); - if (wbuf2) - len = GetCurrentDirectoryW(len, wbuf2); - } - Py_END_ALLOW_THREADS - if (!wbuf2) { - PyErr_NoMemory(); - return NULL; - } - if (!len) { - if (wbuf2 != wbuf) free(wbuf2); - return win32_error("getcwdu", NULL); - } - resobj = PyUnicode_FromWideChar(wbuf2, len); - if (wbuf2 != wbuf) free(wbuf2); - return resobj; - } + if (!use_bytes) { + wchar_t wbuf[1026]; + wchar_t *wbuf2 = wbuf; + PyObject *resobj; + DWORD len; + Py_BEGIN_ALLOW_THREADS + len = GetCurrentDirectoryW(sizeof wbuf/ sizeof wbuf[0], wbuf); + /* If the buffer is large enough, len does not include the + terminating \0. If the buffer is too small, len includes + the space needed for the terminator. */ + if (len >= sizeof wbuf/ sizeof wbuf[0]) { + wbuf2 = malloc(len * sizeof(wchar_t)); + if (wbuf2) + len = GetCurrentDirectoryW(len, wbuf2); + } + Py_END_ALLOW_THREADS + if (!wbuf2) { + PyErr_NoMemory(); + return NULL; + } + if (!len) { + if (wbuf2 != wbuf) free(wbuf2); + return win32_error("getcwdu", NULL); + } + resobj = PyUnicode_FromWideChar(wbuf2, len); + if (wbuf2 != wbuf) free(wbuf2); + return resobj; + } #endif - Py_BEGIN_ALLOW_THREADS + Py_BEGIN_ALLOW_THREADS #if defined(PYOS_OS2) && defined(PYCC_GCC) - res = _getcwd2(buf, sizeof buf); + res = _getcwd2(buf, sizeof buf); #else - res = getcwd(buf, sizeof buf); + res = getcwd(buf, sizeof buf); #endif - Py_END_ALLOW_THREADS - if (res == NULL) - return posix_error(); - if (use_bytes) - return PyBytes_FromStringAndSize(buf, strlen(buf)); - return PyUnicode_Decode(buf, strlen(buf), Py_FileSystemDefaultEncoding,"surrogateescape"); + Py_END_ALLOW_THREADS + if (res == NULL) + return posix_error(); + if (use_bytes) + return PyBytes_FromStringAndSize(buf, strlen(buf)); + return PyUnicode_Decode(buf, strlen(buf), Py_FileSystemDefaultEncoding,"surrogateescape"); } PyDoc_STRVAR(posix_getcwd__doc__, @@ -2065,7 +2066,7 @@ static PyObject * posix_link(PyObject *self, PyObject *args) { - return posix_2str(args, "O&O&:link", link); + return posix_2str(args, "O&O&:link", link); } #endif /* HAVE_LINK */ @@ -2074,7 +2075,7 @@ "listdir(path) -> list_of_strings\n\n\ Return a list containing the names of the entries in the directory.\n\ \n\ - path: path of directory to list\n\ + path: path of directory to list\n\ \n\ The list is in arbitrary order. It does not include the special\n\ entries '.' and '..' even if they are present in the directory."); @@ -2082,163 +2083,163 @@ static PyObject * posix_listdir(PyObject *self, PyObject *args) { - /* XXX Should redo this putting the (now four) versions of opendir - in separate files instead of having them all here... */ + /* XXX Should redo this putting the (now four) versions of opendir + in separate files instead of having them all here... */ #if defined(MS_WINDOWS) && !defined(HAVE_OPENDIR) - PyObject *d, *v; - HANDLE hFindFile; - BOOL result; - WIN32_FIND_DATA FileData; - PyObject *opath; - char namebuf[MAX_PATH+5]; /* Overallocate for \\*.*\0 */ - char *bufptr = namebuf; - Py_ssize_t len = sizeof(namebuf)-5; /* only claim to have space for MAX_PATH */ - - PyObject *po; - if (PyArg_ParseTuple(args, "U:listdir", &po)) { - WIN32_FIND_DATAW wFileData; - Py_UNICODE *wnamebuf; - /* Overallocate for \\*.*\0 */ - len = PyUnicode_GET_SIZE(po); - wnamebuf = malloc((len + 5) * sizeof(wchar_t)); - if (!wnamebuf) { - PyErr_NoMemory(); - return NULL; - } - wcscpy(wnamebuf, PyUnicode_AS_UNICODE(po)); - if (len > 0) { - Py_UNICODE wch = wnamebuf[len-1]; - if (wch != L'/' && wch != L'\\' && wch != L':') - wnamebuf[len++] = L'\\'; - wcscpy(wnamebuf + len, L"*.*"); - } - if ((d = PyList_New(0)) == NULL) { - free(wnamebuf); - return NULL; - } - hFindFile = FindFirstFileW(wnamebuf, &wFileData); - if (hFindFile == INVALID_HANDLE_VALUE) { - int error = GetLastError(); - if (error == ERROR_FILE_NOT_FOUND) { - free(wnamebuf); - return d; - } - Py_DECREF(d); - win32_error_unicode("FindFirstFileW", wnamebuf); - free(wnamebuf); - return NULL; - } - do { - /* Skip over . and .. */ - if (wcscmp(wFileData.cFileName, L".") != 0 && - wcscmp(wFileData.cFileName, L"..") != 0) { - v = PyUnicode_FromUnicode(wFileData.cFileName, wcslen(wFileData.cFileName)); - if (v == NULL) { - Py_DECREF(d); - d = NULL; - break; - } - if (PyList_Append(d, v) != 0) { - Py_DECREF(v); - Py_DECREF(d); - d = NULL; - break; - } - Py_DECREF(v); - } - Py_BEGIN_ALLOW_THREADS - result = FindNextFileW(hFindFile, &wFileData); - Py_END_ALLOW_THREADS - /* FindNextFile sets error to ERROR_NO_MORE_FILES if - it got to the end of the directory. */ - if (!result && GetLastError() != ERROR_NO_MORE_FILES) { - Py_DECREF(d); - win32_error_unicode("FindNextFileW", wnamebuf); - FindClose(hFindFile); - free(wnamebuf); - return NULL; - } - } while (result == TRUE); - - if (FindClose(hFindFile) == FALSE) { - Py_DECREF(d); - win32_error_unicode("FindClose", wnamebuf); - free(wnamebuf); - return NULL; - } - free(wnamebuf); - return d; - } - /* Drop the argument parsing error as narrow strings - are also valid. */ - PyErr_Clear(); - - if (!PyArg_ParseTuple(args, "O&:listdir", - PyUnicode_FSConverter, &opath)) - return NULL; - if (PyBytes_GET_SIZE(opath)+1 > MAX_PATH) { - PyErr_SetString(PyExc_ValueError, "path too long"); - Py_DECREF(opath); - return NULL; - } - strcpy(namebuf, PyBytes_AsString(opath)); - len = PyObject_Size(opath); - if (len > 0) { - char ch = namebuf[len-1]; - if (ch != SEP && ch != ALTSEP && ch != ':') - namebuf[len++] = '/'; - strcpy(namebuf + len, "*.*"); - } - - if ((d = PyList_New(0)) == NULL) - return NULL; - - hFindFile = FindFirstFile(namebuf, &FileData); - if (hFindFile == INVALID_HANDLE_VALUE) { - int error = GetLastError(); - if (error == ERROR_FILE_NOT_FOUND) - return d; - Py_DECREF(d); - return win32_error("FindFirstFile", namebuf); - } - do { - /* Skip over . and .. */ - if (strcmp(FileData.cFileName, ".") != 0 && - strcmp(FileData.cFileName, "..") != 0) { - v = PyBytes_FromString(FileData.cFileName); - if (v == NULL) { - Py_DECREF(d); - d = NULL; - break; - } - if (PyList_Append(d, v) != 0) { - Py_DECREF(v); - Py_DECREF(d); - d = NULL; - break; - } - Py_DECREF(v); - } - Py_BEGIN_ALLOW_THREADS - result = FindNextFile(hFindFile, &FileData); - Py_END_ALLOW_THREADS - /* FindNextFile sets error to ERROR_NO_MORE_FILES if - it got to the end of the directory. */ - if (!result && GetLastError() != ERROR_NO_MORE_FILES) { - Py_DECREF(d); - win32_error("FindNextFile", namebuf); - FindClose(hFindFile); - return NULL; - } - } while (result == TRUE); - - if (FindClose(hFindFile) == FALSE) { - Py_DECREF(d); - return win32_error("FindClose", namebuf); - } + PyObject *d, *v; + HANDLE hFindFile; + BOOL result; + WIN32_FIND_DATA FileData; + PyObject *opath; + char namebuf[MAX_PATH+5]; /* Overallocate for \\*.*\0 */ + char *bufptr = namebuf; + Py_ssize_t len = sizeof(namebuf)-5; /* only claim to have space for MAX_PATH */ + + PyObject *po; + if (PyArg_ParseTuple(args, "U:listdir", &po)) { + WIN32_FIND_DATAW wFileData; + Py_UNICODE *wnamebuf; + /* Overallocate for \\*.*\0 */ + len = PyUnicode_GET_SIZE(po); + wnamebuf = malloc((len + 5) * sizeof(wchar_t)); + if (!wnamebuf) { + PyErr_NoMemory(); + return NULL; + } + wcscpy(wnamebuf, PyUnicode_AS_UNICODE(po)); + if (len > 0) { + Py_UNICODE wch = wnamebuf[len-1]; + if (wch != L'/' && wch != L'\\' && wch != L':') + wnamebuf[len++] = L'\\'; + wcscpy(wnamebuf + len, L"*.*"); + } + if ((d = PyList_New(0)) == NULL) { + free(wnamebuf); + return NULL; + } + hFindFile = FindFirstFileW(wnamebuf, &wFileData); + if (hFindFile == INVALID_HANDLE_VALUE) { + int error = GetLastError(); + if (error == ERROR_FILE_NOT_FOUND) { + free(wnamebuf); + return d; + } + Py_DECREF(d); + win32_error_unicode("FindFirstFileW", wnamebuf); + free(wnamebuf); + return NULL; + } + do { + /* Skip over . and .. */ + if (wcscmp(wFileData.cFileName, L".") != 0 && + wcscmp(wFileData.cFileName, L"..") != 0) { + v = PyUnicode_FromUnicode(wFileData.cFileName, wcslen(wFileData.cFileName)); + if (v == NULL) { + Py_DECREF(d); + d = NULL; + break; + } + if (PyList_Append(d, v) != 0) { + Py_DECREF(v); + Py_DECREF(d); + d = NULL; + break; + } + Py_DECREF(v); + } + Py_BEGIN_ALLOW_THREADS + result = FindNextFileW(hFindFile, &wFileData); + Py_END_ALLOW_THREADS + /* FindNextFile sets error to ERROR_NO_MORE_FILES if + it got to the end of the directory. */ + if (!result && GetLastError() != ERROR_NO_MORE_FILES) { + Py_DECREF(d); + win32_error_unicode("FindNextFileW", wnamebuf); + FindClose(hFindFile); + free(wnamebuf); + return NULL; + } + } while (result == TRUE); + + if (FindClose(hFindFile) == FALSE) { + Py_DECREF(d); + win32_error_unicode("FindClose", wnamebuf); + free(wnamebuf); + return NULL; + } + free(wnamebuf); + return d; + } + /* Drop the argument parsing error as narrow strings + are also valid. */ + PyErr_Clear(); + + if (!PyArg_ParseTuple(args, "O&:listdir", + PyUnicode_FSConverter, &opath)) + return NULL; + if (PyBytes_GET_SIZE(opath)+1 > MAX_PATH) { + PyErr_SetString(PyExc_ValueError, "path too long"); + Py_DECREF(opath); + return NULL; + } + strcpy(namebuf, PyBytes_AsString(opath)); + len = PyObject_Size(opath); + if (len > 0) { + char ch = namebuf[len-1]; + if (ch != SEP && ch != ALTSEP && ch != ':') + namebuf[len++] = '/'; + strcpy(namebuf + len, "*.*"); + } + + if ((d = PyList_New(0)) == NULL) + return NULL; + + hFindFile = FindFirstFile(namebuf, &FileData); + if (hFindFile == INVALID_HANDLE_VALUE) { + int error = GetLastError(); + if (error == ERROR_FILE_NOT_FOUND) + return d; + Py_DECREF(d); + return win32_error("FindFirstFile", namebuf); + } + do { + /* Skip over . and .. */ + if (strcmp(FileData.cFileName, ".") != 0 && + strcmp(FileData.cFileName, "..") != 0) { + v = PyBytes_FromString(FileData.cFileName); + if (v == NULL) { + Py_DECREF(d); + d = NULL; + break; + } + if (PyList_Append(d, v) != 0) { + Py_DECREF(v); + Py_DECREF(d); + d = NULL; + break; + } + Py_DECREF(v); + } + Py_BEGIN_ALLOW_THREADS + result = FindNextFile(hFindFile, &FileData); + Py_END_ALLOW_THREADS + /* FindNextFile sets error to ERROR_NO_MORE_FILES if + it got to the end of the directory. */ + if (!result && GetLastError() != ERROR_NO_MORE_FILES) { + Py_DECREF(d); + win32_error("FindNextFile", namebuf); + FindClose(hFindFile); + return NULL; + } + } while (result == TRUE); + + if (FindClose(hFindFile) == FALSE) { + Py_DECREF(d); + return win32_error("FindClose", namebuf); + } - return d; + return d; #elif defined(PYOS_OS2) @@ -2255,7 +2256,7 @@ FILEFINDBUF3 ep; APIRET rc; - if (!PyArg_ParseTuple(args, "O&:listdir", + if (!PyArg_ParseTuple(args, "O&:listdir", PyUnicode_FSConverter, &oname)) return NULL; name = PyBytes_AsString(oname); @@ -2320,82 +2321,82 @@ Py_DECREF(oname); return d; #else - PyObject *oname; - char *name; - PyObject *d, *v; - DIR *dirp; - struct dirent *ep; - int arg_is_unicode = 1; - - errno = 0; - if (!PyArg_ParseTuple(args, "U:listdir", &v)) { - arg_is_unicode = 0; - PyErr_Clear(); - } - if (!PyArg_ParseTuple(args, "O&:listdir", PyUnicode_FSConverter, &oname)) - return NULL; - name = PyBytes_AsString(oname); - if ((dirp = opendir(name)) == NULL) { - return posix_error_with_allocated_filename(oname); - } - if ((d = PyList_New(0)) == NULL) { - closedir(dirp); - Py_DECREF(oname); - return NULL; - } - for (;;) { - errno = 0; - Py_BEGIN_ALLOW_THREADS - ep = readdir(dirp); - Py_END_ALLOW_THREADS - if (ep == NULL) { - if (errno == 0) { - break; - } else { - closedir(dirp); - Py_DECREF(d); - return posix_error_with_allocated_filename(oname); - } - } - if (ep->d_name[0] == '.' && - (NAMLEN(ep) == 1 || - (ep->d_name[1] == '.' && NAMLEN(ep) == 2))) - continue; - v = PyBytes_FromStringAndSize(ep->d_name, NAMLEN(ep)); - if (v == NULL) { - Py_DECREF(d); - d = NULL; - break; - } - if (arg_is_unicode) { - PyObject *w; - - w = PyUnicode_FromEncodedObject(v, - Py_FileSystemDefaultEncoding, - "surrogateescape"); - Py_DECREF(v); - if (w != NULL) - v = w; - else { - /* Encoding failed to decode ASCII bytes. - Raise exception. */ - Py_DECREF(d); - d = NULL; - break; - } - } - if (PyList_Append(d, v) != 0) { - Py_DECREF(v); - Py_DECREF(d); - d = NULL; - break; - } - Py_DECREF(v); - } - closedir(dirp); - Py_DECREF(oname); + PyObject *oname; + char *name; + PyObject *d, *v; + DIR *dirp; + struct dirent *ep; + int arg_is_unicode = 1; + + errno = 0; + if (!PyArg_ParseTuple(args, "U:listdir", &v)) { + arg_is_unicode = 0; + PyErr_Clear(); + } + if (!PyArg_ParseTuple(args, "O&:listdir", PyUnicode_FSConverter, &oname)) + return NULL; + name = PyBytes_AsString(oname); + if ((dirp = opendir(name)) == NULL) { + return posix_error_with_allocated_filename(oname); + } + if ((d = PyList_New(0)) == NULL) { + closedir(dirp); + Py_DECREF(oname); + return NULL; + } + for (;;) { + errno = 0; + Py_BEGIN_ALLOW_THREADS + ep = readdir(dirp); + Py_END_ALLOW_THREADS + if (ep == NULL) { + if (errno == 0) { + break; + } else { + closedir(dirp); + Py_DECREF(d); + return posix_error_with_allocated_filename(oname); + } + } + if (ep->d_name[0] == '.' && + (NAMLEN(ep) == 1 || + (ep->d_name[1] == '.' && NAMLEN(ep) == 2))) + continue; + v = PyBytes_FromStringAndSize(ep->d_name, NAMLEN(ep)); + if (v == NULL) { + Py_DECREF(d); + d = NULL; + break; + } + if (arg_is_unicode) { + PyObject *w; + + w = PyUnicode_FromEncodedObject(v, + Py_FileSystemDefaultEncoding, + "surrogateescape"); + Py_DECREF(v); + if (w != NULL) + v = w; + else { + /* Encoding failed to decode ASCII bytes. + Raise exception. */ + Py_DECREF(d); + d = NULL; + break; + } + } + if (PyList_Append(d, v) != 0) { + Py_DECREF(v); + Py_DECREF(d); + d = NULL; + break; + } + Py_DECREF(v); + } + closedir(dirp); + Py_DECREF(oname); - return d; + return d; #endif /* which OS */ } /* end of posix_listdir */ @@ -2405,56 +2406,56 @@ static PyObject * posix__getfullpathname(PyObject *self, PyObject *args) { - PyObject *opath; - char *path; - char outbuf[MAX_PATH*2]; - char *temp; + PyObject *opath; + char *path; + char outbuf[MAX_PATH*2]; + char *temp; #ifdef MS_WINDOWS - PyUnicodeObject *po; - if (PyArg_ParseTuple(args, "U|:_getfullpathname", &po)) { - Py_UNICODE *wpath = PyUnicode_AS_UNICODE(po); - Py_UNICODE woutbuf[MAX_PATH*2], *woutbufp = woutbuf; - Py_UNICODE *wtemp; - DWORD result; - PyObject *v; - result = GetFullPathNameW(wpath, - sizeof(woutbuf)/sizeof(woutbuf[0]), - woutbuf, &wtemp); - if (result > sizeof(woutbuf)/sizeof(woutbuf[0])) { - woutbufp = malloc(result * sizeof(Py_UNICODE)); - if (!woutbufp) - return PyErr_NoMemory(); - result = GetFullPathNameW(wpath, result, woutbufp, &wtemp); - } - if (result) - v = PyUnicode_FromUnicode(woutbufp, wcslen(woutbufp)); - else - v = win32_error_unicode("GetFullPathNameW", wpath); - if (woutbufp != woutbuf) - free(woutbufp); - return v; - } - /* Drop the argument parsing error as narrow strings - are also valid. */ - PyErr_Clear(); - -#endif - if (!PyArg_ParseTuple (args, "O&:_getfullpathname", - PyUnicode_FSConverter, &opath)) - return NULL; - path = PyBytes_AsString(opath); - if (!GetFullPathName(path, sizeof(outbuf)/sizeof(outbuf[0]), - outbuf, &temp)) { - win32_error("GetFullPathName", path); - Py_DECREF(opath); - return NULL; - } - Py_DECREF(opath); - if (PyUnicode_Check(PyTuple_GetItem(args, 0))) { - return PyUnicode_Decode(outbuf, strlen(outbuf), - Py_FileSystemDefaultEncoding, NULL); - } - return PyBytes_FromString(outbuf); + PyUnicodeObject *po; + if (PyArg_ParseTuple(args, "U|:_getfullpathname", &po)) { + Py_UNICODE *wpath = PyUnicode_AS_UNICODE(po); + Py_UNICODE woutbuf[MAX_PATH*2], *woutbufp = woutbuf; + Py_UNICODE *wtemp; + DWORD result; + PyObject *v; + result = GetFullPathNameW(wpath, + sizeof(woutbuf)/sizeof(woutbuf[0]), + woutbuf, &wtemp); + if (result > sizeof(woutbuf)/sizeof(woutbuf[0])) { + woutbufp = malloc(result * sizeof(Py_UNICODE)); + if (!woutbufp) + return PyErr_NoMemory(); + result = GetFullPathNameW(wpath, result, woutbufp, &wtemp); + } + if (result) + v = PyUnicode_FromUnicode(woutbufp, wcslen(woutbufp)); + else + v = win32_error_unicode("GetFullPathNameW", wpath); + if (woutbufp != woutbuf) + free(woutbufp); + return v; + } + /* Drop the argument parsing error as narrow strings + are also valid. */ + PyErr_Clear(); + +#endif + if (!PyArg_ParseTuple (args, "O&:_getfullpathname", + PyUnicode_FSConverter, &opath)) + return NULL; + path = PyBytes_AsString(opath); + if (!GetFullPathName(path, sizeof(outbuf)/sizeof(outbuf[0]), + outbuf, &temp)) { + win32_error("GetFullPathName", path); + Py_DECREF(opath); + return NULL; + } + Py_DECREF(opath); + if (PyUnicode_Check(PyTuple_GetItem(args, 0))) { + return PyUnicode_Decode(outbuf, strlen(outbuf), + Py_FileSystemDefaultEncoding, NULL); + } + return PyBytes_FromString(outbuf); } /* end of posix__getfullpathname */ #endif /* MS_WINDOWS */ @@ -2465,62 +2466,62 @@ static PyObject * posix_mkdir(PyObject *self, PyObject *args) { - int res; - PyObject *opath; - char *path; - int mode = 0777; + int res; + PyObject *opath; + char *path; + int mode = 0777; #ifdef MS_WINDOWS - PyUnicodeObject *po; - if (PyArg_ParseTuple(args, "U|i:mkdir", &po, &mode)) { - Py_BEGIN_ALLOW_THREADS - /* PyUnicode_AS_UNICODE OK without thread lock as - it is a simple dereference. */ - res = CreateDirectoryW(PyUnicode_AS_UNICODE(po), NULL); - Py_END_ALLOW_THREADS - if (!res) - return win32_error_unicode("mkdir", PyUnicode_AS_UNICODE(po)); - Py_INCREF(Py_None); - return Py_None; - } - /* Drop the argument parsing error as narrow strings - are also valid. */ - PyErr_Clear(); - if (!PyArg_ParseTuple(args, "O&|i:mkdir", - PyUnicode_FSConverter, &opath, &mode)) - return NULL; - path = PyBytes_AsString(opath); - Py_BEGIN_ALLOW_THREADS - /* PyUnicode_AS_UNICODE OK without thread lock as - it is a simple dereference. */ - res = CreateDirectoryA(path, NULL); - Py_END_ALLOW_THREADS - if (!res) { - win32_error("mkdir", path); - Py_DECREF(opath); - return NULL; - } - Py_DECREF(opath); - Py_INCREF(Py_None); - return Py_None; -#else - - if (!PyArg_ParseTuple(args, "O&|i:mkdir", - PyUnicode_FSConverter, &opath, &mode)) - return NULL; - path = PyBytes_AsString(opath); - Py_BEGIN_ALLOW_THREADS + PyUnicodeObject *po; + if (PyArg_ParseTuple(args, "U|i:mkdir", &po, &mode)) { + Py_BEGIN_ALLOW_THREADS + /* PyUnicode_AS_UNICODE OK without thread lock as + it is a simple dereference. */ + res = CreateDirectoryW(PyUnicode_AS_UNICODE(po), NULL); + Py_END_ALLOW_THREADS + if (!res) + return win32_error_unicode("mkdir", PyUnicode_AS_UNICODE(po)); + Py_INCREF(Py_None); + return Py_None; + } + /* Drop the argument parsing error as narrow strings + are also valid. */ + PyErr_Clear(); + if (!PyArg_ParseTuple(args, "O&|i:mkdir", + PyUnicode_FSConverter, &opath, &mode)) + return NULL; + path = PyBytes_AsString(opath); + Py_BEGIN_ALLOW_THREADS + /* PyUnicode_AS_UNICODE OK without thread lock as + it is a simple dereference. */ + res = CreateDirectoryA(path, NULL); + Py_END_ALLOW_THREADS + if (!res) { + win32_error("mkdir", path); + Py_DECREF(opath); + return NULL; + } + Py_DECREF(opath); + Py_INCREF(Py_None); + return Py_None; +#else + + if (!PyArg_ParseTuple(args, "O&|i:mkdir", + PyUnicode_FSConverter, &opath, &mode)) + return NULL; + path = PyBytes_AsString(opath); + Py_BEGIN_ALLOW_THREADS #if ( defined(__WATCOMC__) || defined(PYCC_VACPP) ) && !defined(__QNX__) - res = mkdir(path); + res = mkdir(path); #else - res = mkdir(path, mode); + res = mkdir(path, mode); #endif - Py_END_ALLOW_THREADS - if (res < 0) - return posix_error_with_allocated_filename(opath); - Py_DECREF(opath); - Py_INCREF(Py_None); - return Py_None; + Py_END_ALLOW_THREADS + if (res < 0) + return posix_error_with_allocated_filename(opath); + Py_DECREF(opath); + Py_INCREF(Py_None); + return Py_None; #endif } @@ -2539,31 +2540,31 @@ static PyObject * posix_nice(PyObject *self, PyObject *args) { - int increment, value; + int increment, value; - if (!PyArg_ParseTuple(args, "i:nice", &increment)) - return NULL; + if (!PyArg_ParseTuple(args, "i:nice", &increment)) + return NULL; - /* There are two flavours of 'nice': one that returns the new - priority (as required by almost all standards out there) and the - Linux/FreeBSD/BSDI one, which returns '0' on success and advices - the use of getpriority() to get the new priority. - - If we are of the nice family that returns the new priority, we - need to clear errno before the call, and check if errno is filled - before calling posix_error() on a returnvalue of -1, because the - -1 may be the actual new priority! */ + /* There are two flavours of 'nice': one that returns the new + priority (as required by almost all standards out there) and the + Linux/FreeBSD/BSDI one, which returns '0' on success and advices + the use of getpriority() to get the new priority. + + If we are of the nice family that returns the new priority, we + need to clear errno before the call, and check if errno is filled + before calling posix_error() on a returnvalue of -1, because the + -1 may be the actual new priority! */ - errno = 0; - value = nice(increment); + errno = 0; + value = nice(increment); #if defined(HAVE_BROKEN_NICE) && defined(HAVE_GETPRIORITY) - if (value == 0) - value = getpriority(PRIO_PROCESS, 0); + if (value == 0) + value = getpriority(PRIO_PROCESS, 0); #endif - if (value == -1 && errno != 0) - /* either nice() or getpriority() returned an error */ - return posix_error(); - return PyLong_FromLong((long) value); + if (value == -1 && errno != 0) + /* either nice() or getpriority() returned an error */ + return posix_error(); + return PyLong_FromLong((long) value); } #endif /* HAVE_NICE */ @@ -2575,40 +2576,40 @@ posix_rename(PyObject *self, PyObject *args) { #ifdef MS_WINDOWS - PyObject *o1, *o2; - char *p1, *p2; - BOOL result; - if (!PyArg_ParseTuple(args, "OO:rename", &o1, &o2)) - goto error; - if (!convert_to_unicode(&o1)) - goto error; - if (!convert_to_unicode(&o2)) { - Py_DECREF(o1); - goto error; - } - Py_BEGIN_ALLOW_THREADS - result = MoveFileW(PyUnicode_AsUnicode(o1), - PyUnicode_AsUnicode(o2)); - Py_END_ALLOW_THREADS - Py_DECREF(o1); - Py_DECREF(o2); - if (!result) - return win32_error("rename", NULL); - Py_INCREF(Py_None); - return Py_None; + PyObject *o1, *o2; + char *p1, *p2; + BOOL result; + if (!PyArg_ParseTuple(args, "OO:rename", &o1, &o2)) + goto error; + if (!convert_to_unicode(&o1)) + goto error; + if (!convert_to_unicode(&o2)) { + Py_DECREF(o1); + goto error; + } + Py_BEGIN_ALLOW_THREADS + result = MoveFileW(PyUnicode_AsUnicode(o1), + PyUnicode_AsUnicode(o2)); + Py_END_ALLOW_THREADS + Py_DECREF(o1); + Py_DECREF(o2); + if (!result) + return win32_error("rename", NULL); + Py_INCREF(Py_None); + return Py_None; error: - PyErr_Clear(); - if (!PyArg_ParseTuple(args, "ss:rename", &p1, &p2)) - return NULL; - Py_BEGIN_ALLOW_THREADS - result = MoveFileA(p1, p2); - Py_END_ALLOW_THREADS - if (!result) - return win32_error("rename", NULL); - Py_INCREF(Py_None); - return Py_None; + PyErr_Clear(); + if (!PyArg_ParseTuple(args, "ss:rename", &p1, &p2)) + return NULL; + Py_BEGIN_ALLOW_THREADS + result = MoveFileA(p1, p2); + Py_END_ALLOW_THREADS + if (!result) + return win32_error("rename", NULL); + Py_INCREF(Py_None); + return Py_None; #else - return posix_2str(args, "O&O&:rename", rename); + return posix_2str(args, "O&O&:rename", rename); #endif } @@ -2621,9 +2622,9 @@ posix_rmdir(PyObject *self, PyObject *args) { #ifdef MS_WINDOWS - return win32_1str(args, "rmdir", "y:rmdir", RemoveDirectoryA, "U:rmdir", RemoveDirectoryW); + return win32_1str(args, "rmdir", "y:rmdir", RemoveDirectoryA, "U:rmdir", RemoveDirectoryW); #else - return posix_1str(args, "O&:rmdir", rmdir); + return posix_1str(args, "O&:rmdir", rmdir); #endif } @@ -2636,9 +2637,9 @@ posix_stat(PyObject *self, PyObject *args) { #ifdef MS_WINDOWS - return posix_do_stat(self, args, "O&:stat", STAT, "U:stat", win32_wstat); + return posix_do_stat(self, args, "O&:stat", STAT, "U:stat", win32_wstat); #else - return posix_do_stat(self, args, "O&:stat", STAT, NULL, NULL); + return posix_do_stat(self, args, "O&:stat", STAT, NULL, NULL); #endif } @@ -2651,29 +2652,29 @@ static PyObject * posix_system(PyObject *self, PyObject *args) { - long sts; + long sts; #ifdef MS_WINDOWS - wchar_t *command; - if (!PyArg_ParseTuple(args, "u:system", &command)) - return NULL; - - Py_BEGIN_ALLOW_THREADS - sts = _wsystem(command); - Py_END_ALLOW_THREADS -#else - PyObject *command_obj; - char *command; - if (!PyArg_ParseTuple(args, "O&:system", - PyUnicode_FSConverter, &command_obj)) - return NULL; - - command = PyBytes_AsString(command_obj); - Py_BEGIN_ALLOW_THREADS - sts = system(command); - Py_END_ALLOW_THREADS - Py_DECREF(command_obj); + wchar_t *command; + if (!PyArg_ParseTuple(args, "u:system", &command)) + return NULL; + + Py_BEGIN_ALLOW_THREADS + sts = _wsystem(command); + Py_END_ALLOW_THREADS +#else + PyObject *command_obj; + char *command; + if (!PyArg_ParseTuple(args, "O&:system", + PyUnicode_FSConverter, &command_obj)) + return NULL; + + command = PyBytes_AsString(command_obj); + Py_BEGIN_ALLOW_THREADS + sts = system(command); + Py_END_ALLOW_THREADS + Py_DECREF(command_obj); #endif - return PyLong_FromLong(sts); + return PyLong_FromLong(sts); } #endif @@ -2685,13 +2686,13 @@ static PyObject * posix_umask(PyObject *self, PyObject *args) { - int i; - if (!PyArg_ParseTuple(args, "i:umask", &i)) - return NULL; - i = (int)umask(i); - if (i < 0) - return posix_error(); - return PyLong_FromLong((long)i); + int i; + if (!PyArg_ParseTuple(args, "i:umask", &i)) + return NULL; + i = (int)umask(i); + if (i < 0) + return posix_error(); + return PyLong_FromLong((long)i); } @@ -2707,9 +2708,9 @@ posix_unlink(PyObject *self, PyObject *args) { #ifdef MS_WINDOWS - return win32_1str(args, "remove", "y:remove", DeleteFileA, "U:remove", DeleteFileW); + return win32_1str(args, "remove", "y:remove", DeleteFileA, "U:remove", DeleteFileW); #else - return posix_1str(args, "O&:remove", unlink); + return posix_1str(args, "O&:remove", unlink); #endif } @@ -2722,50 +2723,50 @@ static PyObject * posix_uname(PyObject *self, PyObject *noargs) { - struct utsname u; - int res; + struct utsname u; + int res; - Py_BEGIN_ALLOW_THREADS - res = uname(&u); - Py_END_ALLOW_THREADS - if (res < 0) - return posix_error(); - return Py_BuildValue("(sssss)", - u.sysname, - u.nodename, - u.release, - u.version, - u.machine); + Py_BEGIN_ALLOW_THREADS + res = uname(&u); + Py_END_ALLOW_THREADS + if (res < 0) + return posix_error(); + return Py_BuildValue("(sssss)", + u.sysname, + u.nodename, + u.release, + u.version, + u.machine); } #endif /* HAVE_UNAME */ static int extract_time(PyObject *t, long* sec, long* usec) { - long intval; - if (PyFloat_Check(t)) { - double tval = PyFloat_AsDouble(t); - PyObject *intobj = Py_TYPE(t)->tp_as_number->nb_int(t); - if (!intobj) - return -1; - intval = PyLong_AsLong(intobj); - Py_DECREF(intobj); - if (intval == -1 && PyErr_Occurred()) - return -1; - *sec = intval; - *usec = (long)((tval - intval) * 1e6); /* can't exceed 1000000 */ - if (*usec < 0) - /* If rounding gave us a negative number, - truncate. */ - *usec = 0; - return 0; - } - intval = PyLong_AsLong(t); - if (intval == -1 && PyErr_Occurred()) - return -1; - *sec = intval; - *usec = 0; + long intval; + if (PyFloat_Check(t)) { + double tval = PyFloat_AsDouble(t); + PyObject *intobj = Py_TYPE(t)->tp_as_number->nb_int(t); + if (!intobj) + return -1; + intval = PyLong_AsLong(intobj); + Py_DECREF(intobj); + if (intval == -1 && PyErr_Occurred()) + return -1; + *sec = intval; + *usec = (long)((tval - intval) * 1e6); /* can't exceed 1000000 */ + if (*usec < 0) + /* If rounding gave us a negative number, + truncate. */ + *usec = 0; return 0; + } + intval = PyLong_AsLong(t); + if (intval == -1 && PyErr_Occurred()) + return -1; + *sec = intval; + *usec = 0; + return 0; } PyDoc_STRVAR(posix_utime__doc__, @@ -2778,157 +2779,157 @@ posix_utime(PyObject *self, PyObject *args) { #ifdef MS_WINDOWS - PyObject *arg; - PyUnicodeObject *obwpath; - wchar_t *wpath = NULL; - PyObject *oapath; - char *apath; - HANDLE hFile; - long atimesec, mtimesec, ausec, musec; - FILETIME atime, mtime; - PyObject *result = NULL; - - if (PyArg_ParseTuple(args, "UO|:utime", &obwpath, &arg)) { - wpath = PyUnicode_AS_UNICODE(obwpath); - Py_BEGIN_ALLOW_THREADS - hFile = CreateFileW(wpath, FILE_WRITE_ATTRIBUTES, 0, - NULL, OPEN_EXISTING, - FILE_FLAG_BACKUP_SEMANTICS, NULL); - Py_END_ALLOW_THREADS - if (hFile == INVALID_HANDLE_VALUE) - return win32_error_unicode("utime", wpath); - } else - /* Drop the argument parsing error as narrow strings - are also valid. */ - PyErr_Clear(); - - if (!wpath) { - if (!PyArg_ParseTuple(args, "O&O:utime", - PyUnicode_FSConverter, &oapath, &arg)) - return NULL; - apath = PyBytes_AsString(oapath); - Py_BEGIN_ALLOW_THREADS - hFile = CreateFileA(apath, FILE_WRITE_ATTRIBUTES, 0, - NULL, OPEN_EXISTING, - FILE_FLAG_BACKUP_SEMANTICS, NULL); - Py_END_ALLOW_THREADS - if (hFile == INVALID_HANDLE_VALUE) { - win32_error("utime", apath); - Py_DECREF(oapath); - return NULL; - } - Py_DECREF(oapath); - } - - if (arg == Py_None) { - SYSTEMTIME now; - GetSystemTime(&now); - if (!SystemTimeToFileTime(&now, &mtime) || - !SystemTimeToFileTime(&now, &atime)) { - win32_error("utime", NULL); - goto done; - } - } - else if (!PyTuple_Check(arg) || PyTuple_Size(arg) != 2) { - PyErr_SetString(PyExc_TypeError, - "utime() arg 2 must be a tuple (atime, mtime)"); - goto done; - } - else { - if (extract_time(PyTuple_GET_ITEM(arg, 0), - &atimesec, &ausec) == -1) - goto done; - time_t_to_FILE_TIME(atimesec, 1000*ausec, &atime); - if (extract_time(PyTuple_GET_ITEM(arg, 1), - &mtimesec, &musec) == -1) - goto done; - time_t_to_FILE_TIME(mtimesec, 1000*musec, &mtime); - } - if (!SetFileTime(hFile, NULL, &atime, &mtime)) { - /* Avoid putting the file name into the error here, - as that may confuse the user into believing that - something is wrong with the file, when it also - could be the time stamp that gives a problem. */ - win32_error("utime", NULL); - } - Py_INCREF(Py_None); - result = Py_None; + PyObject *arg; + PyUnicodeObject *obwpath; + wchar_t *wpath = NULL; + PyObject *oapath; + char *apath; + HANDLE hFile; + long atimesec, mtimesec, ausec, musec; + FILETIME atime, mtime; + PyObject *result = NULL; + + if (PyArg_ParseTuple(args, "UO|:utime", &obwpath, &arg)) { + wpath = PyUnicode_AS_UNICODE(obwpath); + Py_BEGIN_ALLOW_THREADS + hFile = CreateFileW(wpath, FILE_WRITE_ATTRIBUTES, 0, + NULL, OPEN_EXISTING, + FILE_FLAG_BACKUP_SEMANTICS, NULL); + Py_END_ALLOW_THREADS + if (hFile == INVALID_HANDLE_VALUE) + return win32_error_unicode("utime", wpath); + } else + /* Drop the argument parsing error as narrow strings + are also valid. */ + PyErr_Clear(); + + if (!wpath) { + if (!PyArg_ParseTuple(args, "O&O:utime", + PyUnicode_FSConverter, &oapath, &arg)) + return NULL; + apath = PyBytes_AsString(oapath); + Py_BEGIN_ALLOW_THREADS + hFile = CreateFileA(apath, FILE_WRITE_ATTRIBUTES, 0, + NULL, OPEN_EXISTING, + FILE_FLAG_BACKUP_SEMANTICS, NULL); + Py_END_ALLOW_THREADS + if (hFile == INVALID_HANDLE_VALUE) { + win32_error("utime", apath); + Py_DECREF(oapath); + return NULL; + } + Py_DECREF(oapath); + } + + if (arg == Py_None) { + SYSTEMTIME now; + GetSystemTime(&now); + if (!SystemTimeToFileTime(&now, &mtime) || + !SystemTimeToFileTime(&now, &atime)) { + win32_error("utime", NULL); + goto done; + } + } + else if (!PyTuple_Check(arg) || PyTuple_Size(arg) != 2) { + PyErr_SetString(PyExc_TypeError, + "utime() arg 2 must be a tuple (atime, mtime)"); + goto done; + } + else { + if (extract_time(PyTuple_GET_ITEM(arg, 0), + &atimesec, &ausec) == -1) + goto done; + time_t_to_FILE_TIME(atimesec, 1000*ausec, &atime); + if (extract_time(PyTuple_GET_ITEM(arg, 1), + &mtimesec, &musec) == -1) + goto done; + time_t_to_FILE_TIME(mtimesec, 1000*musec, &mtime); + } + if (!SetFileTime(hFile, NULL, &atime, &mtime)) { + /* Avoid putting the file name into the error here, + as that may confuse the user into believing that + something is wrong with the file, when it also + could be the time stamp that gives a problem. */ + win32_error("utime", NULL); + } + Py_INCREF(Py_None); + result = Py_None; done: - CloseHandle(hFile); - return result; + CloseHandle(hFile); + return result; #else /* MS_WINDOWS */ - PyObject *opath; - char *path; - long atime, mtime, ausec, musec; - int res; - PyObject* arg; + PyObject *opath; + char *path; + long atime, mtime, ausec, musec; + int res; + PyObject* arg; #if defined(HAVE_UTIMES) - struct timeval buf[2]; + struct timeval buf[2]; #define ATIME buf[0].tv_sec #define MTIME buf[1].tv_sec #elif defined(HAVE_UTIME_H) /* XXX should define struct utimbuf instead, above */ - struct utimbuf buf; + struct utimbuf buf; #define ATIME buf.actime #define MTIME buf.modtime #define UTIME_ARG &buf #else /* HAVE_UTIMES */ - time_t buf[2]; + time_t buf[2]; #define ATIME buf[0] #define MTIME buf[1] #define UTIME_ARG buf #endif /* HAVE_UTIMES */ - if (!PyArg_ParseTuple(args, "O&O:utime", - PyUnicode_FSConverter, &opath, &arg)) - return NULL; - path = PyBytes_AsString(opath); - if (arg == Py_None) { - /* optional time values not given */ - Py_BEGIN_ALLOW_THREADS - res = utime(path, NULL); - Py_END_ALLOW_THREADS - } - else if (!PyTuple_Check(arg) || PyTuple_Size(arg) != 2) { - PyErr_SetString(PyExc_TypeError, - "utime() arg 2 must be a tuple (atime, mtime)"); - Py_DECREF(opath); - return NULL; - } - else { - if (extract_time(PyTuple_GET_ITEM(arg, 0), - &atime, &ausec) == -1) { - Py_DECREF(opath); - return NULL; - } - if (extract_time(PyTuple_GET_ITEM(arg, 1), - &mtime, &musec) == -1) { - Py_DECREF(opath); - return NULL; - } - ATIME = atime; - MTIME = mtime; + if (!PyArg_ParseTuple(args, "O&O:utime", + PyUnicode_FSConverter, &opath, &arg)) + return NULL; + path = PyBytes_AsString(opath); + if (arg == Py_None) { + /* optional time values not given */ + Py_BEGIN_ALLOW_THREADS + res = utime(path, NULL); + Py_END_ALLOW_THREADS + } + else if (!PyTuple_Check(arg) || PyTuple_Size(arg) != 2) { + PyErr_SetString(PyExc_TypeError, + "utime() arg 2 must be a tuple (atime, mtime)"); + Py_DECREF(opath); + return NULL; + } + else { + if (extract_time(PyTuple_GET_ITEM(arg, 0), + &atime, &ausec) == -1) { + Py_DECREF(opath); + return NULL; + } + if (extract_time(PyTuple_GET_ITEM(arg, 1), + &mtime, &musec) == -1) { + Py_DECREF(opath); + return NULL; + } + ATIME = atime; + MTIME = mtime; #ifdef HAVE_UTIMES - buf[0].tv_usec = ausec; - buf[1].tv_usec = musec; - Py_BEGIN_ALLOW_THREADS - res = utimes(path, buf); - Py_END_ALLOW_THREADS -#else - Py_BEGIN_ALLOW_THREADS - res = utime(path, UTIME_ARG); - Py_END_ALLOW_THREADS + buf[0].tv_usec = ausec; + buf[1].tv_usec = musec; + Py_BEGIN_ALLOW_THREADS + res = utimes(path, buf); + Py_END_ALLOW_THREADS +#else + Py_BEGIN_ALLOW_THREADS + res = utime(path, UTIME_ARG); + Py_END_ALLOW_THREADS #endif /* HAVE_UTIMES */ - } - if (res < 0) { - return posix_error_with_allocated_filename(opath); - } - Py_DECREF(opath); - Py_INCREF(Py_None); - return Py_None; + } + if (res < 0) { + return posix_error_with_allocated_filename(opath); + } + Py_DECREF(opath); + Py_INCREF(Py_None); + return Py_None; #undef UTIME_ARG #undef ATIME #undef MTIME @@ -2945,37 +2946,37 @@ static PyObject * posix__exit(PyObject *self, PyObject *args) { - int sts; - if (!PyArg_ParseTuple(args, "i:_exit", &sts)) - return NULL; - _exit(sts); - return NULL; /* Make gcc -Wall happy */ + int sts; + if (!PyArg_ParseTuple(args, "i:_exit", &sts)) + return NULL; + _exit(sts); + return NULL; /* Make gcc -Wall happy */ } #if defined(HAVE_EXECV) || defined(HAVE_SPAWNV) static void free_string_array(char **array, Py_ssize_t count) { - Py_ssize_t i; - for (i = 0; i < count; i++) - PyMem_Free(array[i]); - PyMem_DEL(array); + Py_ssize_t i; + for (i = 0; i < count; i++) + PyMem_Free(array[i]); + PyMem_DEL(array); } static int fsconvert_strdup(PyObject *o, char**out) { - PyObject *bytes; - Py_ssize_t size; - if (!PyUnicode_FSConverter(o, &bytes)) - return 0; - size = PyBytes_GET_SIZE(bytes); - *out = PyMem_Malloc(size+1); - if (!*out) - return 0; - memcpy(*out, PyBytes_AsString(bytes), size+1); - Py_DECREF(bytes); - return 1; + PyObject *bytes; + Py_ssize_t size; + if (!PyUnicode_FSConverter(o, &bytes)) + return 0; + size = PyBytes_GET_SIZE(bytes); + *out = PyMem_Malloc(size+1); + if (!*out) + return 0; + memcpy(*out, PyBytes_AsString(bytes), size+1); + Py_DECREF(bytes); + return 1; } #endif @@ -2985,236 +2986,236 @@ "execv(path, args)\n\n\ Execute an executable path with arguments, replacing current process.\n\ \n\ - path: path of executable file\n\ - args: tuple or list of strings"); + path: path of executable file\n\ + args: tuple or list of strings"); static PyObject * posix_execv(PyObject *self, PyObject *args) { - PyObject *opath; - char *path; - PyObject *argv; - char **argvlist; - Py_ssize_t i, argc; - PyObject *(*getitem)(PyObject *, Py_ssize_t); - - /* execv has two arguments: (path, argv), where - argv is a list or tuple of strings. */ - - if (!PyArg_ParseTuple(args, "O&O:execv", - PyUnicode_FSConverter, - &opath, &argv)) - return NULL; - path = PyBytes_AsString(opath); - if (PyList_Check(argv)) { - argc = PyList_Size(argv); - getitem = PyList_GetItem; - } - else if (PyTuple_Check(argv)) { - argc = PyTuple_Size(argv); - getitem = PyTuple_GetItem; - } - else { - PyErr_SetString(PyExc_TypeError, "execv() arg 2 must be a tuple or list"); - Py_DECREF(opath); - return NULL; - } - if (argc < 1) { - PyErr_SetString(PyExc_ValueError, "execv() arg 2 must not be empty"); - Py_DECREF(opath); - return NULL; - } - - argvlist = PyMem_NEW(char *, argc+1); - if (argvlist == NULL) { - Py_DECREF(opath); - return PyErr_NoMemory(); - } - for (i = 0; i < argc; i++) { - if (!fsconvert_strdup((*getitem)(argv, i), - &argvlist[i])) { - free_string_array(argvlist, i); - PyErr_SetString(PyExc_TypeError, - "execv() arg 2 must contain only strings"); - Py_DECREF(opath); - return NULL; - - } - } - argvlist[argc] = NULL; - - execv(path, argvlist); - - /* If we get here it's definitely an error */ - - free_string_array(argvlist, argc); - Py_DECREF(opath); - return posix_error(); + PyObject *opath; + char *path; + PyObject *argv; + char **argvlist; + Py_ssize_t i, argc; + PyObject *(*getitem)(PyObject *, Py_ssize_t); + + /* execv has two arguments: (path, argv), where + argv is a list or tuple of strings. */ + + if (!PyArg_ParseTuple(args, "O&O:execv", + PyUnicode_FSConverter, + &opath, &argv)) + return NULL; + path = PyBytes_AsString(opath); + if (PyList_Check(argv)) { + argc = PyList_Size(argv); + getitem = PyList_GetItem; + } + else if (PyTuple_Check(argv)) { + argc = PyTuple_Size(argv); + getitem = PyTuple_GetItem; + } + else { + PyErr_SetString(PyExc_TypeError, "execv() arg 2 must be a tuple or list"); + Py_DECREF(opath); + return NULL; + } + if (argc < 1) { + PyErr_SetString(PyExc_ValueError, "execv() arg 2 must not be empty"); + Py_DECREF(opath); + return NULL; + } + + argvlist = PyMem_NEW(char *, argc+1); + if (argvlist == NULL) { + Py_DECREF(opath); + return PyErr_NoMemory(); + } + for (i = 0; i < argc; i++) { + if (!fsconvert_strdup((*getitem)(argv, i), + &argvlist[i])) { + free_string_array(argvlist, i); + PyErr_SetString(PyExc_TypeError, + "execv() arg 2 must contain only strings"); + Py_DECREF(opath); + return NULL; + + } + } + argvlist[argc] = NULL; + + execv(path, argvlist); + + /* If we get here it's definitely an error */ + + free_string_array(argvlist, argc); + Py_DECREF(opath); + return posix_error(); } static char** parse_envlist(PyObject* env, Py_ssize_t *envc_ptr) { - char **envlist; - Py_ssize_t i, pos, envc; - PyObject *keys=NULL, *vals=NULL; - PyObject *key, *val, *key2, *val2; - char *p, *k, *v; - size_t len; - - i = PyMapping_Size(env); - if (i < 0) - return NULL; - envlist = PyMem_NEW(char *, i + 1); - if (envlist == NULL) { - PyErr_NoMemory(); - return NULL; - } - envc = 0; - keys = PyMapping_Keys(env); - vals = PyMapping_Values(env); - if (!keys || !vals) - goto error; - if (!PyList_Check(keys) || !PyList_Check(vals)) { - PyErr_Format(PyExc_TypeError, - "env.keys() or env.values() is not a list"); - goto error; - } - - for (pos = 0; pos < i; pos++) { - key = PyList_GetItem(keys, pos); - val = PyList_GetItem(vals, pos); - if (!key || !val) - goto error; - - if (PyUnicode_FSConverter(key, &key2) == 0) - goto error; - if (PyUnicode_FSConverter(val, &val2) == 0) { - Py_DECREF(key2); - goto error; - } + char **envlist; + Py_ssize_t i, pos, envc; + PyObject *keys=NULL, *vals=NULL; + PyObject *key, *val, *key2, *val2; + char *p, *k, *v; + size_t len; + + i = PyMapping_Size(env); + if (i < 0) + return NULL; + envlist = PyMem_NEW(char *, i + 1); + if (envlist == NULL) { + PyErr_NoMemory(); + return NULL; + } + envc = 0; + keys = PyMapping_Keys(env); + vals = PyMapping_Values(env); + if (!keys || !vals) + goto error; + if (!PyList_Check(keys) || !PyList_Check(vals)) { + PyErr_Format(PyExc_TypeError, + "env.keys() or env.values() is not a list"); + goto error; + } + + for (pos = 0; pos < i; pos++) { + key = PyList_GetItem(keys, pos); + val = PyList_GetItem(vals, pos); + if (!key || !val) + goto error; + + if (PyUnicode_FSConverter(key, &key2) == 0) + goto error; + if (PyUnicode_FSConverter(val, &val2) == 0) { + Py_DECREF(key2); + goto error; + } #if defined(PYOS_OS2) - /* Omit Pseudo-Env Vars that Would Confuse Programs if Passed On */ - if (stricmp(k, "BEGINLIBPATH") != 0 && stricmp(k, "ENDLIBPATH") != 0) { + /* Omit Pseudo-Env Vars that Would Confuse Programs if Passed On */ + if (stricmp(k, "BEGINLIBPATH") != 0 && stricmp(k, "ENDLIBPATH") != 0) { #endif - k = PyBytes_AsString(key2); - v = PyBytes_AsString(val2); - len = PyBytes_GET_SIZE(key2) + PyBytes_GET_SIZE(val2) + 2; - - p = PyMem_NEW(char, len); - if (p == NULL) { - PyErr_NoMemory(); - Py_DECREF(key2); - Py_DECREF(val2); - goto error; - } - PyOS_snprintf(p, len, "%s=%s", k, v); - envlist[envc++] = p; - Py_DECREF(key2); - Py_DECREF(val2); + k = PyBytes_AsString(key2); + v = PyBytes_AsString(val2); + len = PyBytes_GET_SIZE(key2) + PyBytes_GET_SIZE(val2) + 2; + + p = PyMem_NEW(char, len); + if (p == NULL) { + PyErr_NoMemory(); + Py_DECREF(key2); + Py_DECREF(val2); + goto error; + } + PyOS_snprintf(p, len, "%s=%s", k, v); + envlist[envc++] = p; + Py_DECREF(key2); + Py_DECREF(val2); #if defined(PYOS_OS2) - } + } #endif - } - Py_DECREF(vals); - Py_DECREF(keys); - - envlist[envc] = 0; - *envc_ptr = envc; - return envlist; + } + Py_DECREF(vals); + Py_DECREF(keys); + + envlist[envc] = 0; + *envc_ptr = envc; + return envlist; error: - Py_XDECREF(keys); - Py_XDECREF(vals); - while (--envc >= 0) - PyMem_DEL(envlist[envc]); - PyMem_DEL(envlist); - return NULL; + Py_XDECREF(keys); + Py_XDECREF(vals); + while (--envc >= 0) + PyMem_DEL(envlist[envc]); + PyMem_DEL(envlist); + return NULL; } PyDoc_STRVAR(posix_execve__doc__, "execve(path, args, env)\n\n\ Execute a path with arguments and environment, replacing current process.\n\ \n\ - path: path of executable file\n\ - args: tuple or list of arguments\n\ - env: dictionary of strings mapping to strings"); + path: path of executable file\n\ + args: tuple or list of arguments\n\ + env: dictionary of strings mapping to strings"); static PyObject * posix_execve(PyObject *self, PyObject *args) { - PyObject *opath; - char *path; - PyObject *argv, *env; - char **argvlist; - char **envlist; - Py_ssize_t i, argc, envc; - PyObject *(*getitem)(PyObject *, Py_ssize_t); - Py_ssize_t lastarg = 0; - - /* execve has three arguments: (path, argv, env), where - argv is a list or tuple of strings and env is a dictionary - like posix.environ. */ - - if (!PyArg_ParseTuple(args, "O&OO:execve", - PyUnicode_FSConverter, - &opath, &argv, &env)) - return NULL; - path = PyBytes_AsString(opath); - if (PyList_Check(argv)) { - argc = PyList_Size(argv); - getitem = PyList_GetItem; - } - else if (PyTuple_Check(argv)) { - argc = PyTuple_Size(argv); - getitem = PyTuple_GetItem; - } - else { - PyErr_SetString(PyExc_TypeError, - "execve() arg 2 must be a tuple or list"); - goto fail_0; - } - if (!PyMapping_Check(env)) { - PyErr_SetString(PyExc_TypeError, - "execve() arg 3 must be a mapping object"); - goto fail_0; - } - - argvlist = PyMem_NEW(char *, argc+1); - if (argvlist == NULL) { - PyErr_NoMemory(); - goto fail_0; - } - for (i = 0; i < argc; i++) { - if (!fsconvert_strdup((*getitem)(argv, i), - &argvlist[i])) - { - lastarg = i; - goto fail_1; - } - } - lastarg = argc; - argvlist[argc] = NULL; - - envlist = parse_envlist(env, &envc); - if (envlist == NULL) - goto fail_1; - - execve(path, argvlist, envlist); - - /* If we get here it's definitely an error */ - - (void) posix_error(); - - while (--envc >= 0) - PyMem_DEL(envlist[envc]); - PyMem_DEL(envlist); + PyObject *opath; + char *path; + PyObject *argv, *env; + char **argvlist; + char **envlist; + Py_ssize_t i, argc, envc; + PyObject *(*getitem)(PyObject *, Py_ssize_t); + Py_ssize_t lastarg = 0; + + /* execve has three arguments: (path, argv, env), where + argv is a list or tuple of strings and env is a dictionary + like posix.environ. */ + + if (!PyArg_ParseTuple(args, "O&OO:execve", + PyUnicode_FSConverter, + &opath, &argv, &env)) + return NULL; + path = PyBytes_AsString(opath); + if (PyList_Check(argv)) { + argc = PyList_Size(argv); + getitem = PyList_GetItem; + } + else if (PyTuple_Check(argv)) { + argc = PyTuple_Size(argv); + getitem = PyTuple_GetItem; + } + else { + PyErr_SetString(PyExc_TypeError, + "execve() arg 2 must be a tuple or list"); + goto fail_0; + } + if (!PyMapping_Check(env)) { + PyErr_SetString(PyExc_TypeError, + "execve() arg 3 must be a mapping object"); + goto fail_0; + } + + argvlist = PyMem_NEW(char *, argc+1); + if (argvlist == NULL) { + PyErr_NoMemory(); + goto fail_0; + } + for (i = 0; i < argc; i++) { + if (!fsconvert_strdup((*getitem)(argv, i), + &argvlist[i])) + { + lastarg = i; + goto fail_1; + } + } + lastarg = argc; + argvlist[argc] = NULL; + + envlist = parse_envlist(env, &envc); + if (envlist == NULL) + goto fail_1; + + execve(path, argvlist, envlist); + + /* If we get here it's definitely an error */ + + (void) posix_error(); + + while (--envc >= 0) + PyMem_DEL(envlist[envc]); + PyMem_DEL(envlist); fail_1: - free_string_array(argvlist, lastarg); + free_string_array(argvlist, lastarg); fail_0: - Py_DECREF(opath); - return NULL; + Py_DECREF(opath); + return NULL; } #endif /* HAVE_EXECV */ @@ -3224,86 +3225,86 @@ "spawnv(mode, path, args)\n\n\ Execute the program 'path' in a new process.\n\ \n\ - mode: mode of process creation\n\ - path: path of executable file\n\ - args: tuple or list of strings"); + mode: mode of process creation\n\ + path: path of executable file\n\ + args: tuple or list of strings"); static PyObject * posix_spawnv(PyObject *self, PyObject *args) { - PyObject *opath; - char *path; - PyObject *argv; - char **argvlist; - int mode, i; - Py_ssize_t argc; - Py_intptr_t spawnval; - PyObject *(*getitem)(PyObject *, Py_ssize_t); - - /* spawnv has three arguments: (mode, path, argv), where - argv is a list or tuple of strings. */ - - if (!PyArg_ParseTuple(args, "iO&O:spawnv", &mode, - PyUnicode_FSConverter, - &opath, &argv)) - return NULL; - path = PyBytes_AsString(opath); - if (PyList_Check(argv)) { - argc = PyList_Size(argv); - getitem = PyList_GetItem; - } - else if (PyTuple_Check(argv)) { - argc = PyTuple_Size(argv); - getitem = PyTuple_GetItem; - } - else { - PyErr_SetString(PyExc_TypeError, - "spawnv() arg 2 must be a tuple or list"); - Py_DECREF(opath); - return NULL; - } - - argvlist = PyMem_NEW(char *, argc+1); - if (argvlist == NULL) { - Py_DECREF(opath); - return PyErr_NoMemory(); - } - for (i = 0; i < argc; i++) { - if (!fsconvert_strdup((*getitem)(argv, i), - &argvlist[i])) { - free_string_array(argvlist, i); - PyErr_SetString( - PyExc_TypeError, - "spawnv() arg 2 must contain only strings"); - Py_DECREF(opath); - return NULL; - } - } - argvlist[argc] = NULL; + PyObject *opath; + char *path; + PyObject *argv; + char **argvlist; + int mode, i; + Py_ssize_t argc; + Py_intptr_t spawnval; + PyObject *(*getitem)(PyObject *, Py_ssize_t); + + /* spawnv has three arguments: (mode, path, argv), where + argv is a list or tuple of strings. */ + + if (!PyArg_ParseTuple(args, "iO&O:spawnv", &mode, + PyUnicode_FSConverter, + &opath, &argv)) + return NULL; + path = PyBytes_AsString(opath); + if (PyList_Check(argv)) { + argc = PyList_Size(argv); + getitem = PyList_GetItem; + } + else if (PyTuple_Check(argv)) { + argc = PyTuple_Size(argv); + getitem = PyTuple_GetItem; + } + else { + PyErr_SetString(PyExc_TypeError, + "spawnv() arg 2 must be a tuple or list"); + Py_DECREF(opath); + return NULL; + } + + argvlist = PyMem_NEW(char *, argc+1); + if (argvlist == NULL) { + Py_DECREF(opath); + return PyErr_NoMemory(); + } + for (i = 0; i < argc; i++) { + if (!fsconvert_strdup((*getitem)(argv, i), + &argvlist[i])) { + free_string_array(argvlist, i); + PyErr_SetString( + PyExc_TypeError, + "spawnv() arg 2 must contain only strings"); + Py_DECREF(opath); + return NULL; + } + } + argvlist[argc] = NULL; #if defined(PYOS_OS2) && defined(PYCC_GCC) - Py_BEGIN_ALLOW_THREADS - spawnval = spawnv(mode, path, argvlist); - Py_END_ALLOW_THREADS + Py_BEGIN_ALLOW_THREADS + spawnval = spawnv(mode, path, argvlist); + Py_END_ALLOW_THREADS #else - if (mode == _OLD_P_OVERLAY) - mode = _P_OVERLAY; + if (mode == _OLD_P_OVERLAY) + mode = _P_OVERLAY; - Py_BEGIN_ALLOW_THREADS - spawnval = _spawnv(mode, path, argvlist); - Py_END_ALLOW_THREADS + Py_BEGIN_ALLOW_THREADS + spawnval = _spawnv(mode, path, argvlist); + Py_END_ALLOW_THREADS #endif - free_string_array(argvlist, argc); - Py_DECREF(opath); + free_string_array(argvlist, argc); + Py_DECREF(opath); - if (spawnval == -1) - return posix_error(); - else + if (spawnval == -1) + return posix_error(); + else #if SIZEOF_LONG == SIZEOF_VOID_P - return Py_BuildValue("l", (long) spawnval); + return Py_BuildValue("l", (long) spawnval); #else - return Py_BuildValue("L", (PY_LONG_LONG) spawnval); + return Py_BuildValue("L", (PY_LONG_LONG) spawnval); #endif } @@ -3312,104 +3313,104 @@ "spawnve(mode, path, args, env)\n\n\ Execute the program 'path' in a new process.\n\ \n\ - mode: mode of process creation\n\ - path: path of executable file\n\ - args: tuple or list of arguments\n\ - env: dictionary of strings mapping to strings"); + mode: mode of process creation\n\ + path: path of executable file\n\ + args: tuple or list of arguments\n\ + env: dictionary of strings mapping to strings"); static PyObject * posix_spawnve(PyObject *self, PyObject *args) { - PyObject *opath; - char *path; - PyObject *argv, *env; - char **argvlist; - char **envlist; - PyObject *res = NULL; - int mode, envc; - Py_ssize_t argc, i; - Py_intptr_t spawnval; - PyObject *(*getitem)(PyObject *, Py_ssize_t); - Py_ssize_t lastarg = 0; - - /* spawnve has four arguments: (mode, path, argv, env), where - argv is a list or tuple of strings and env is a dictionary - like posix.environ. */ - - if (!PyArg_ParseTuple(args, "iO&OO:spawnve", &mode, - PyUnicode_FSConverter, - &opath, &argv, &env)) - return NULL; - path = PyBytes_AsString(opath); - if (PyList_Check(argv)) { - argc = PyList_Size(argv); - getitem = PyList_GetItem; - } - else if (PyTuple_Check(argv)) { - argc = PyTuple_Size(argv); - getitem = PyTuple_GetItem; - } - else { - PyErr_SetString(PyExc_TypeError, - "spawnve() arg 2 must be a tuple or list"); - goto fail_0; - } - if (!PyMapping_Check(env)) { - PyErr_SetString(PyExc_TypeError, - "spawnve() arg 3 must be a mapping object"); - goto fail_0; - } - - argvlist = PyMem_NEW(char *, argc+1); - if (argvlist == NULL) { - PyErr_NoMemory(); - goto fail_0; - } - for (i = 0; i < argc; i++) { - if (!fsconvert_strdup((*getitem)(argv, i), - &argvlist[i])) - { - lastarg = i; - goto fail_1; - } - } - lastarg = argc; - argvlist[argc] = NULL; - - envlist = parse_envlist(env, &envc); - if (envlist == NULL) - goto fail_1; + PyObject *opath; + char *path; + PyObject *argv, *env; + char **argvlist; + char **envlist; + PyObject *res = NULL; + int mode, envc; + Py_ssize_t argc, i; + Py_intptr_t spawnval; + PyObject *(*getitem)(PyObject *, Py_ssize_t); + Py_ssize_t lastarg = 0; + + /* spawnve has four arguments: (mode, path, argv, env), where + argv is a list or tuple of strings and env is a dictionary + like posix.environ. */ + + if (!PyArg_ParseTuple(args, "iO&OO:spawnve", &mode, + PyUnicode_FSConverter, + &opath, &argv, &env)) + return NULL; + path = PyBytes_AsString(opath); + if (PyList_Check(argv)) { + argc = PyList_Size(argv); + getitem = PyList_GetItem; + } + else if (PyTuple_Check(argv)) { + argc = PyTuple_Size(argv); + getitem = PyTuple_GetItem; + } + else { + PyErr_SetString(PyExc_TypeError, + "spawnve() arg 2 must be a tuple or list"); + goto fail_0; + } + if (!PyMapping_Check(env)) { + PyErr_SetString(PyExc_TypeError, + "spawnve() arg 3 must be a mapping object"); + goto fail_0; + } + + argvlist = PyMem_NEW(char *, argc+1); + if (argvlist == NULL) { + PyErr_NoMemory(); + goto fail_0; + } + for (i = 0; i < argc; i++) { + if (!fsconvert_strdup((*getitem)(argv, i), + &argvlist[i])) + { + lastarg = i; + goto fail_1; + } + } + lastarg = argc; + argvlist[argc] = NULL; + + envlist = parse_envlist(env, &envc); + if (envlist == NULL) + goto fail_1; #if defined(PYOS_OS2) && defined(PYCC_GCC) - Py_BEGIN_ALLOW_THREADS - spawnval = spawnve(mode, path, argvlist, envlist); - Py_END_ALLOW_THREADS + Py_BEGIN_ALLOW_THREADS + spawnval = spawnve(mode, path, argvlist, envlist); + Py_END_ALLOW_THREADS #else - if (mode == _OLD_P_OVERLAY) - mode = _P_OVERLAY; + if (mode == _OLD_P_OVERLAY) + mode = _P_OVERLAY; - Py_BEGIN_ALLOW_THREADS - spawnval = _spawnve(mode, path, argvlist, envlist); - Py_END_ALLOW_THREADS + Py_BEGIN_ALLOW_THREADS + spawnval = _spawnve(mode, path, argvlist, envlist); + Py_END_ALLOW_THREADS #endif - if (spawnval == -1) - (void) posix_error(); - else + if (spawnval == -1) + (void) posix_error(); + else #if SIZEOF_LONG == SIZEOF_VOID_P - res = Py_BuildValue("l", (long) spawnval); + res = Py_BuildValue("l", (long) spawnval); #else - res = Py_BuildValue("L", (PY_LONG_LONG) spawnval); + res = Py_BuildValue("L", (PY_LONG_LONG) spawnval); #endif - while (--envc >= 0) - PyMem_DEL(envlist[envc]); - PyMem_DEL(envlist); + while (--envc >= 0) + PyMem_DEL(envlist[envc]); + PyMem_DEL(envlist); fail_1: - free_string_array(argvlist, lastarg); + free_string_array(argvlist, lastarg); fail_0: - Py_DECREF(opath); - return res; + Py_DECREF(opath); + return res; } /* OS/2 supports spawnvp & spawnvpe natively */ @@ -3419,77 +3420,77 @@ Execute the program 'file' in a new process, using the environment\n\ search path to find the file.\n\ \n\ - mode: mode of process creation\n\ - file: executable file name\n\ - args: tuple or list of strings"); + mode: mode of process creation\n\ + file: executable file name\n\ + args: tuple or list of strings"); static PyObject * posix_spawnvp(PyObject *self, PyObject *args) { - PyObject *opath; - char *path; - PyObject *argv; - char **argvlist; - int mode, i, argc; - Py_intptr_t spawnval; - PyObject *(*getitem)(PyObject *, Py_ssize_t); - - /* spawnvp has three arguments: (mode, path, argv), where - argv is a list or tuple of strings. */ - - if (!PyArg_ParseTuple(args, "iO&O:spawnvp", &mode, - PyUnicode_FSConverter, - &opath, &argv)) - return NULL; - path = PyBytes_AsString(opath); - if (PyList_Check(argv)) { - argc = PyList_Size(argv); - getitem = PyList_GetItem; - } - else if (PyTuple_Check(argv)) { - argc = PyTuple_Size(argv); - getitem = PyTuple_GetItem; - } - else { - PyErr_SetString(PyExc_TypeError, - "spawnvp() arg 2 must be a tuple or list"); - Py_DECREF(opath); - return NULL; - } - - argvlist = PyMem_NEW(char *, argc+1); - if (argvlist == NULL) { - Py_DECREF(opath); - return PyErr_NoMemory(); - } - for (i = 0; i < argc; i++) { - if (!fsconvert_strdup((*getitem)(argv, i), - &argvlist[i])) { - free_string_array(argvlist, i); - PyErr_SetString( - PyExc_TypeError, - "spawnvp() arg 2 must contain only strings"); - Py_DECREF(opath); - return NULL; - } - } - argvlist[argc] = NULL; + PyObject *opath; + char *path; + PyObject *argv; + char **argvlist; + int mode, i, argc; + Py_intptr_t spawnval; + PyObject *(*getitem)(PyObject *, Py_ssize_t); + + /* spawnvp has three arguments: (mode, path, argv), where + argv is a list or tuple of strings. */ + + if (!PyArg_ParseTuple(args, "iO&O:spawnvp", &mode, + PyUnicode_FSConverter, + &opath, &argv)) + return NULL; + path = PyBytes_AsString(opath); + if (PyList_Check(argv)) { + argc = PyList_Size(argv); + getitem = PyList_GetItem; + } + else if (PyTuple_Check(argv)) { + argc = PyTuple_Size(argv); + getitem = PyTuple_GetItem; + } + else { + PyErr_SetString(PyExc_TypeError, + "spawnvp() arg 2 must be a tuple or list"); + Py_DECREF(opath); + return NULL; + } + + argvlist = PyMem_NEW(char *, argc+1); + if (argvlist == NULL) { + Py_DECREF(opath); + return PyErr_NoMemory(); + } + for (i = 0; i < argc; i++) { + if (!fsconvert_strdup((*getitem)(argv, i), + &argvlist[i])) { + free_string_array(argvlist, i); + PyErr_SetString( + PyExc_TypeError, + "spawnvp() arg 2 must contain only strings"); + Py_DECREF(opath); + return NULL; + } + } + argvlist[argc] = NULL; - Py_BEGIN_ALLOW_THREADS + Py_BEGIN_ALLOW_THREADS #if defined(PYCC_GCC) - spawnval = spawnvp(mode, path, argvlist); + spawnval = spawnvp(mode, path, argvlist); #else - spawnval = _spawnvp(mode, path, argvlist); + spawnval = _spawnvp(mode, path, argvlist); #endif - Py_END_ALLOW_THREADS + Py_END_ALLOW_THREADS - free_string_array(argvlist, argc); - Py_DECREF(opath); + free_string_array(argvlist, argc); + Py_DECREF(opath); - if (spawnval == -1) - return posix_error(); - else - return Py_BuildValue("l", (long) spawnval); + if (spawnval == -1) + return posix_error(); + else + return Py_BuildValue("l", (long) spawnval); } @@ -3498,94 +3499,94 @@ Execute the program 'file' in a new process, using the environment\n\ search path to find the file.\n\ \n\ - mode: mode of process creation\n\ - file: executable file name\n\ - args: tuple or list of arguments\n\ - env: dictionary of strings mapping to strings"); + mode: mode of process creation\n\ + file: executable file name\n\ + args: tuple or list of arguments\n\ + env: dictionary of strings mapping to strings"); static PyObject * posix_spawnvpe(PyObject *self, PyObject *args) { - PyObject *opath - char *path; - PyObject *argv, *env; - char **argvlist; - char **envlist; - PyObject *res=NULL; - int mode, i, argc, envc; - Py_intptr_t spawnval; - PyObject *(*getitem)(PyObject *, Py_ssize_t); - int lastarg = 0; - - /* spawnvpe has four arguments: (mode, path, argv, env), where - argv is a list or tuple of strings and env is a dictionary - like posix.environ. */ - - if (!PyArg_ParseTuple(args, "ietOO:spawnvpe", &mode, - PyUnicode_FSConverter, - &opath, &argv, &env)) - return NULL; - path = PyBytes_AsString(opath); - if (PyList_Check(argv)) { - argc = PyList_Size(argv); - getitem = PyList_GetItem; - } - else if (PyTuple_Check(argv)) { - argc = PyTuple_Size(argv); - getitem = PyTuple_GetItem; - } - else { - PyErr_SetString(PyExc_TypeError, - "spawnvpe() arg 2 must be a tuple or list"); - goto fail_0; - } - if (!PyMapping_Check(env)) { - PyErr_SetString(PyExc_TypeError, - "spawnvpe() arg 3 must be a mapping object"); - goto fail_0; - } - - argvlist = PyMem_NEW(char *, argc+1); - if (argvlist == NULL) { - PyErr_NoMemory(); - goto fail_0; - } - for (i = 0; i < argc; i++) { - if (!fsconvert_strdup((*getitem)(argv, i), - &argvlist[i])) - { - lastarg = i; - goto fail_1; - } - } - lastarg = argc; - argvlist[argc] = NULL; - - envlist = parse_envlist(env, &envc); - if (envlist == NULL) - goto fail_1; + PyObject *opath + char *path; + PyObject *argv, *env; + char **argvlist; + char **envlist; + PyObject *res=NULL; + int mode, i, argc, envc; + Py_intptr_t spawnval; + PyObject *(*getitem)(PyObject *, Py_ssize_t); + int lastarg = 0; + + /* spawnvpe has four arguments: (mode, path, argv, env), where + argv is a list or tuple of strings and env is a dictionary + like posix.environ. */ + + if (!PyArg_ParseTuple(args, "ietOO:spawnvpe", &mode, + PyUnicode_FSConverter, + &opath, &argv, &env)) + return NULL; + path = PyBytes_AsString(opath); + if (PyList_Check(argv)) { + argc = PyList_Size(argv); + getitem = PyList_GetItem; + } + else if (PyTuple_Check(argv)) { + argc = PyTuple_Size(argv); + getitem = PyTuple_GetItem; + } + else { + PyErr_SetString(PyExc_TypeError, + "spawnvpe() arg 2 must be a tuple or list"); + goto fail_0; + } + if (!PyMapping_Check(env)) { + PyErr_SetString(PyExc_TypeError, + "spawnvpe() arg 3 must be a mapping object"); + goto fail_0; + } + + argvlist = PyMem_NEW(char *, argc+1); + if (argvlist == NULL) { + PyErr_NoMemory(); + goto fail_0; + } + for (i = 0; i < argc; i++) { + if (!fsconvert_strdup((*getitem)(argv, i), + &argvlist[i])) + { + lastarg = i; + goto fail_1; + } + } + lastarg = argc; + argvlist[argc] = NULL; + + envlist = parse_envlist(env, &envc); + if (envlist == NULL) + goto fail_1; - Py_BEGIN_ALLOW_THREADS + Py_BEGIN_ALLOW_THREADS #if defined(PYCC_GCC) - spawnval = spawnvpe(mode, path, argvlist, envlist); + spawnval = spawnvpe(mode, path, argvlist, envlist); #else - spawnval = _spawnvpe(mode, path, argvlist, envlist); + spawnval = _spawnvpe(mode, path, argvlist, envlist); #endif - Py_END_ALLOW_THREADS + Py_END_ALLOW_THREADS - if (spawnval == -1) - (void) posix_error(); - else - res = Py_BuildValue("l", (long) spawnval); + if (spawnval == -1) + (void) posix_error(); + else + res = Py_BuildValue("l", (long) spawnval); - while (--envc >= 0) - PyMem_DEL(envlist[envc]); - PyMem_DEL(envlist); + while (--envc >= 0) + PyMem_DEL(envlist[envc]); + PyMem_DEL(envlist); fail_1: - free_string_array(argvlist, lastarg); + free_string_array(argvlist, lastarg); fail_0: - Py_DECREF(opath); - return res; + Py_DECREF(opath); + return res; } #endif /* PYOS_OS2 */ #endif /* HAVE_SPAWNV */ @@ -3601,26 +3602,26 @@ static PyObject * posix_fork1(PyObject *self, PyObject *noargs) { - pid_t pid; - int result = 0; - _PyImport_AcquireLock(); - pid = fork1(); - if (pid == 0) { - /* child: this clobbers and resets the import lock. */ - PyOS_AfterFork(); - } else { - /* parent: release the import lock. */ - result = _PyImport_ReleaseLock(); - } - if (pid == -1) - return posix_error(); - if (result < 0) { - /* Don't clobber the OSError if the fork failed. */ - PyErr_SetString(PyExc_RuntimeError, - "not holding the import lock"); - return NULL; - } - return PyLong_FromPid(pid); + pid_t pid; + int result = 0; + _PyImport_AcquireLock(); + pid = fork1(); + if (pid == 0) { + /* child: this clobbers and resets the import lock. */ + PyOS_AfterFork(); + } else { + /* parent: release the import lock. */ + result = _PyImport_ReleaseLock(); + } + if (pid == -1) + return posix_error(); + if (result < 0) { + /* Don't clobber the OSError if the fork failed. */ + PyErr_SetString(PyExc_RuntimeError, + "not holding the import lock"); + return NULL; + } + return PyLong_FromPid(pid); } #endif @@ -3634,26 +3635,26 @@ static PyObject * posix_fork(PyObject *self, PyObject *noargs) { - pid_t pid; - int result = 0; - _PyImport_AcquireLock(); - pid = fork(); - if (pid == 0) { - /* child: this clobbers and resets the import lock. */ - PyOS_AfterFork(); - } else { - /* parent: release the import lock. */ - result = _PyImport_ReleaseLock(); - } - if (pid == -1) - return posix_error(); - if (result < 0) { - /* Don't clobber the OSError if the fork failed. */ - PyErr_SetString(PyExc_RuntimeError, - "not holding the import lock"); - return NULL; - } - return PyLong_FromPid(pid); + pid_t pid; + int result = 0; + _PyImport_AcquireLock(); + pid = fork(); + if (pid == 0) { + /* child: this clobbers and resets the import lock. */ + PyOS_AfterFork(); + } else { + /* parent: release the import lock. */ + result = _PyImport_ReleaseLock(); + } + if (pid == -1) + return posix_error(); + if (result < 0) { + /* Don't clobber the OSError if the fork failed. */ + PyErr_SetString(PyExc_RuntimeError, + "not holding the import lock"); + return NULL; + } + return PyLong_FromPid(pid); } #endif @@ -3691,60 +3692,60 @@ static PyObject * posix_openpty(PyObject *self, PyObject *noargs) { - int master_fd, slave_fd; + int master_fd, slave_fd; #ifndef HAVE_OPENPTY - char * slave_name; + char * slave_name; #endif #if defined(HAVE_DEV_PTMX) && !defined(HAVE_OPENPTY) && !defined(HAVE__GETPTY) - PyOS_sighandler_t sig_saved; + PyOS_sighandler_t sig_saved; #ifdef sun - extern char *ptsname(int fildes); + extern char *ptsname(int fildes); #endif #endif #ifdef HAVE_OPENPTY - if (openpty(&master_fd, &slave_fd, NULL, NULL, NULL) != 0) - return posix_error(); + if (openpty(&master_fd, &slave_fd, NULL, NULL, NULL) != 0) + return posix_error(); #elif defined(HAVE__GETPTY) - slave_name = _getpty(&master_fd, O_RDWR, 0666, 0); - if (slave_name == NULL) - return posix_error(); - - slave_fd = open(slave_name, O_RDWR); - if (slave_fd < 0) - return posix_error(); -#else - master_fd = open(DEV_PTY_FILE, O_RDWR | O_NOCTTY); /* open master */ - if (master_fd < 0) - return posix_error(); - sig_saved = PyOS_setsig(SIGCHLD, SIG_DFL); - /* change permission of slave */ - if (grantpt(master_fd) < 0) { - PyOS_setsig(SIGCHLD, sig_saved); - return posix_error(); - } - /* unlock slave */ - if (unlockpt(master_fd) < 0) { - PyOS_setsig(SIGCHLD, sig_saved); - return posix_error(); - } - PyOS_setsig(SIGCHLD, sig_saved); - slave_name = ptsname(master_fd); /* get name of slave */ - if (slave_name == NULL) - return posix_error(); - slave_fd = open(slave_name, O_RDWR | O_NOCTTY); /* open slave */ - if (slave_fd < 0) - return posix_error(); + slave_name = _getpty(&master_fd, O_RDWR, 0666, 0); + if (slave_name == NULL) + return posix_error(); + + slave_fd = open(slave_name, O_RDWR); + if (slave_fd < 0) + return posix_error(); +#else + master_fd = open(DEV_PTY_FILE, O_RDWR | O_NOCTTY); /* open master */ + if (master_fd < 0) + return posix_error(); + sig_saved = PyOS_setsig(SIGCHLD, SIG_DFL); + /* change permission of slave */ + if (grantpt(master_fd) < 0) { + PyOS_setsig(SIGCHLD, sig_saved); + return posix_error(); + } + /* unlock slave */ + if (unlockpt(master_fd) < 0) { + PyOS_setsig(SIGCHLD, sig_saved); + return posix_error(); + } + PyOS_setsig(SIGCHLD, sig_saved); + slave_name = ptsname(master_fd); /* get name of slave */ + if (slave_name == NULL) + return posix_error(); + slave_fd = open(slave_name, O_RDWR | O_NOCTTY); /* open slave */ + if (slave_fd < 0) + return posix_error(); #if !defined(__CYGWIN__) && !defined(HAVE_DEV_PTC) - ioctl(slave_fd, I_PUSH, "ptem"); /* push ptem */ - ioctl(slave_fd, I_PUSH, "ldterm"); /* push ldterm */ + ioctl(slave_fd, I_PUSH, "ptem"); /* push ptem */ + ioctl(slave_fd, I_PUSH, "ldterm"); /* push ldterm */ #ifndef __hpux - ioctl(slave_fd, I_PUSH, "ttcompat"); /* push ttcompat */ + ioctl(slave_fd, I_PUSH, "ttcompat"); /* push ttcompat */ #endif /* __hpux */ #endif /* HAVE_CYGWIN */ #endif /* HAVE_OPENPTY */ - return Py_BuildValue("(ii)", master_fd, slave_fd); + return Py_BuildValue("(ii)", master_fd, slave_fd); } #endif /* defined(HAVE_OPENPTY) || defined(HAVE__GETPTY) || defined(HAVE_DEV_PTMX) */ @@ -3759,27 +3760,27 @@ static PyObject * posix_forkpty(PyObject *self, PyObject *noargs) { - int master_fd = -1, result = 0; - pid_t pid; + int master_fd = -1, result = 0; + pid_t pid; - _PyImport_AcquireLock(); - pid = forkpty(&master_fd, NULL, NULL, NULL); - if (pid == 0) { - /* child: this clobbers and resets the import lock. */ - PyOS_AfterFork(); - } else { - /* parent: release the import lock. */ - result = _PyImport_ReleaseLock(); - } - if (pid == -1) - return posix_error(); - if (result < 0) { - /* Don't clobber the OSError if the fork failed. */ - PyErr_SetString(PyExc_RuntimeError, - "not holding the import lock"); - return NULL; - } - return Py_BuildValue("(Ni)", PyLong_FromPid(pid), master_fd); + _PyImport_AcquireLock(); + pid = forkpty(&master_fd, NULL, NULL, NULL); + if (pid == 0) { + /* child: this clobbers and resets the import lock. */ + PyOS_AfterFork(); + } else { + /* parent: release the import lock. */ + result = _PyImport_ReleaseLock(); + } + if (pid == -1) + return posix_error(); + if (result < 0) { + /* Don't clobber the OSError if the fork failed. */ + PyErr_SetString(PyExc_RuntimeError, + "not holding the import lock"); + return NULL; + } + return Py_BuildValue("(Ni)", PyLong_FromPid(pid), master_fd); } #endif @@ -3791,7 +3792,7 @@ static PyObject * posix_getegid(PyObject *self, PyObject *noargs) { - return PyLong_FromLong((long)getegid()); + return PyLong_FromLong((long)getegid()); } #endif @@ -3804,7 +3805,7 @@ static PyObject * posix_geteuid(PyObject *self, PyObject *noargs) { - return PyLong_FromLong((long)geteuid()); + return PyLong_FromLong((long)geteuid()); } #endif @@ -3817,7 +3818,7 @@ static PyObject * posix_getgid(PyObject *self, PyObject *noargs) { - return PyLong_FromLong((long)getgid()); + return PyLong_FromLong((long)getgid()); } #endif @@ -3829,7 +3830,7 @@ static PyObject * posix_getpid(PyObject *self, PyObject *noargs) { - return PyLong_FromPid(getpid()); + return PyLong_FromPid(getpid()); } @@ -3846,30 +3847,30 @@ #ifdef NGROUPS_MAX #define MAX_GROUPS NGROUPS_MAX #else - /* defined to be 16 on Solaris7, so this should be a small number */ + /* defined to be 16 on Solaris7, so this should be a small number */ #define MAX_GROUPS 64 #endif - gid_t grouplist[MAX_GROUPS]; - int n; + gid_t grouplist[MAX_GROUPS]; + int n; - n = getgroups(MAX_GROUPS, grouplist); - if (n < 0) - posix_error(); - else { - result = PyList_New(n); - if (result != NULL) { - int i; - for (i = 0; i < n; ++i) { - PyObject *o = PyLong_FromLong((long)grouplist[i]); - if (o == NULL) { - Py_DECREF(result); - result = NULL; - break; - } - PyList_SET_ITEM(result, i, o); - } + n = getgroups(MAX_GROUPS, grouplist); + if (n < 0) + posix_error(); + else { + result = PyList_New(n); + if (result != NULL) { + int i; + for (i = 0; i < n; ++i) { + PyObject *o = PyLong_FromLong((long)grouplist[i]); + if (o == NULL) { + Py_DECREF(result); + result = NULL; + break; } + PyList_SET_ITEM(result, i, o); + } } + } return result; } @@ -3885,17 +3886,17 @@ static PyObject * posix_initgroups(PyObject *self, PyObject *args) { - char *username; - long gid; + char *username; + long gid; - if (!PyArg_ParseTuple(args, "sl:initgroups", &username, &gid)) - return NULL; + if (!PyArg_ParseTuple(args, "sl:initgroups", &username, &gid)) + return NULL; - if (initgroups(username, (gid_t) gid) == -1) - return PyErr_SetFromErrno(PyExc_OSError); + if (initgroups(username, (gid_t) gid) == -1) + return PyErr_SetFromErrno(PyExc_OSError); - Py_INCREF(Py_None); - return Py_None; + Py_INCREF(Py_None); + return Py_None; } #endif @@ -3907,13 +3908,13 @@ static PyObject * posix_getpgid(PyObject *self, PyObject *args) { - pid_t pid, pgid; - if (!PyArg_ParseTuple(args, _Py_PARSE_PID ":getpgid", &pid)) - return NULL; - pgid = getpgid(pid); - if (pgid < 0) - return posix_error(); - return PyLong_FromPid(pgid); + pid_t pid, pgid; + if (!PyArg_ParseTuple(args, _Py_PARSE_PID ":getpgid", &pid)) + return NULL; + pgid = getpgid(pid); + if (pgid < 0) + return posix_error(); + return PyLong_FromPid(pgid); } #endif /* HAVE_GETPGID */ @@ -3927,9 +3928,9 @@ posix_getpgrp(PyObject *self, PyObject *noargs) { #ifdef GETPGRP_HAVE_ARG - return PyLong_FromPid(getpgrp(0)); + return PyLong_FromPid(getpgrp(0)); #else /* GETPGRP_HAVE_ARG */ - return PyLong_FromPid(getpgrp()); + return PyLong_FromPid(getpgrp()); #endif /* GETPGRP_HAVE_ARG */ } #endif /* HAVE_GETPGRP */ @@ -3944,13 +3945,13 @@ posix_setpgrp(PyObject *self, PyObject *noargs) { #ifdef SETPGRP_HAVE_ARG - if (setpgrp(0, 0) < 0) + if (setpgrp(0, 0) < 0) #else /* SETPGRP_HAVE_ARG */ - if (setpgrp() < 0) + if (setpgrp() < 0) #endif /* SETPGRP_HAVE_ARG */ - return posix_error(); - Py_INCREF(Py_None); - return Py_None; + return posix_error(); + Py_INCREF(Py_None); + return Py_None; } #endif /* HAVE_SETPGRP */ @@ -3963,7 +3964,7 @@ static PyObject * posix_getppid(PyObject *self, PyObject *noargs) { - return PyLong_FromPid(getppid()); + return PyLong_FromPid(getppid()); } #endif @@ -3976,22 +3977,22 @@ static PyObject * posix_getlogin(PyObject *self, PyObject *noargs) { - PyObject *result = NULL; - char *name; - int old_errno = errno; + PyObject *result = NULL; + char *name; + int old_errno = errno; - errno = 0; - name = getlogin(); - if (name == NULL) { - if (errno) - posix_error(); - else - PyErr_SetString(PyExc_OSError, - "unable to determine login name"); - } + errno = 0; + name = getlogin(); + if (name == NULL) { + if (errno) + posix_error(); else - result = PyUnicode_FromString(name); - errno = old_errno; + PyErr_SetString(PyExc_OSError, + "unable to determine login name"); + } + else + result = PyUnicode_FromString(name); + errno = old_errno; return result; } @@ -4005,7 +4006,7 @@ static PyObject * posix_getuid(PyObject *self, PyObject *noargs) { - return PyLong_FromLong((long)getuid()); + return PyLong_FromLong((long)getuid()); } #endif @@ -4018,10 +4019,10 @@ static PyObject * posix_kill(PyObject *self, PyObject *args) { - pid_t pid; - int sig; - if (!PyArg_ParseTuple(args, _Py_PARSE_PID "i:kill", &pid, &sig)) - return NULL; + pid_t pid; + int sig; + if (!PyArg_ParseTuple(args, _Py_PARSE_PID "i:kill", &pid, &sig)) + return NULL; #if defined(PYOS_OS2) && !defined(PYCC_GCC) if (sig == XCPT_SIGNAL_INTR || sig == XCPT_SIGNAL_BREAK) { APIRET rc; @@ -4036,11 +4037,11 @@ } else return NULL; /* Unrecognized Signal Requested */ #else - if (kill(pid, sig) == -1) - return posix_error(); + if (kill(pid, sig) == -1) + return posix_error(); #endif - Py_INCREF(Py_None); - return Py_None; + Py_INCREF(Py_None); + return Py_None; } #endif @@ -4052,18 +4053,18 @@ static PyObject * posix_killpg(PyObject *self, PyObject *args) { - int sig; - pid_t pgid; - /* XXX some man pages make the `pgid` parameter an int, others - a pid_t. Since getpgrp() returns a pid_t, we assume killpg should - take the same type. Moreover, pid_t is always at least as wide as - int (else compilation of this module fails), which is safe. */ - if (!PyArg_ParseTuple(args, _Py_PARSE_PID "i:killpg", &pgid, &sig)) - return NULL; - if (killpg(pgid, sig) == -1) - return posix_error(); - Py_INCREF(Py_None); - return Py_None; + int sig; + pid_t pgid; + /* XXX some man pages make the `pgid` parameter an int, others + a pid_t. Since getpgrp() returns a pid_t, we assume killpg should + take the same type. Moreover, pid_t is always at least as wide as + int (else compilation of this module fails), which is safe. */ + if (!PyArg_ParseTuple(args, _Py_PARSE_PID "i:killpg", &pgid, &sig)) + return NULL; + if (killpg(pgid, sig) == -1) + return posix_error(); + Py_INCREF(Py_None); + return Py_None; } #endif @@ -4075,42 +4076,42 @@ static PyObject * win32_kill(PyObject *self, PyObject *args) { - PyObject *result, handle_obj; - DWORD pid, sig, err; - HANDLE handle; - - if (!PyArg_ParseTuple(args, "kk:kill", &pid, &sig)) - return NULL; - - /* Console processes which share a common console can be sent CTRL+C or - CTRL+BREAK events, provided they handle said events. */ - if (sig == CTRL_C_EVENT || sig == CTRL_BREAK_EVENT) { - if (GenerateConsoleCtrlEvent(sig, pid) == 0) { - err = GetLastError(); - PyErr_SetFromWindowsErr(err); - } - else - Py_RETURN_NONE; - } - - /* If the signal is outside of what GenerateConsoleCtrlEvent can use, - attempt to open and terminate the process. */ - handle = OpenProcess(PROCESS_ALL_ACCESS, FALSE, pid); - if (handle == NULL) { - err = GetLastError(); - return PyErr_SetFromWindowsErr(err); - } - - if (TerminateProcess(handle, sig) == 0) { - err = GetLastError(); - result = PyErr_SetFromWindowsErr(err); - } else { - Py_INCREF(Py_None); - result = Py_None; - } + PyObject *result, handle_obj; + DWORD pid, sig, err; + HANDLE handle; + + if (!PyArg_ParseTuple(args, "kk:kill", &pid, &sig)) + return NULL; + + /* Console processes which share a common console can be sent CTRL+C or + CTRL+BREAK events, provided they handle said events. */ + if (sig == CTRL_C_EVENT || sig == CTRL_BREAK_EVENT) { + if (GenerateConsoleCtrlEvent(sig, pid) == 0) { + err = GetLastError(); + PyErr_SetFromWindowsErr(err); + } + else + Py_RETURN_NONE; + } + + /* If the signal is outside of what GenerateConsoleCtrlEvent can use, + attempt to open and terminate the process. */ + handle = OpenProcess(PROCESS_ALL_ACCESS, FALSE, pid); + if (handle == NULL) { + err = GetLastError(); + return PyErr_SetFromWindowsErr(err); + } - CloseHandle(handle); - return result; + if (TerminateProcess(handle, sig) == 0) { + err = GetLastError(); + result = PyErr_SetFromWindowsErr(err); + } else { + Py_INCREF(Py_None); + result = Py_None; + } + + CloseHandle(handle); + return result; } #endif /* MS_WINDOWS */ @@ -4127,13 +4128,13 @@ static PyObject * posix_plock(PyObject *self, PyObject *args) { - int op; - if (!PyArg_ParseTuple(args, "i:plock", &op)) - return NULL; - if (plock(op) == -1) - return posix_error(); - Py_INCREF(Py_None); - return Py_None; + int op; + if (!PyArg_ParseTuple(args, "i:plock", &op)) + return NULL; + if (plock(op) == -1) + return posix_error(); + Py_INCREF(Py_None); + return Py_None; } #endif @@ -4145,19 +4146,19 @@ static PyObject * posix_setuid(PyObject *self, PyObject *args) { - long uid_arg; - uid_t uid; - if (!PyArg_ParseTuple(args, "l:setuid", &uid_arg)) - return NULL; - uid = uid_arg; - if (uid != uid_arg) { - PyErr_SetString(PyExc_OverflowError, "user id too big"); - return NULL; - } - if (setuid(uid) < 0) - return posix_error(); - Py_INCREF(Py_None); - return Py_None; + long uid_arg; + uid_t uid; + if (!PyArg_ParseTuple(args, "l:setuid", &uid_arg)) + return NULL; + uid = uid_arg; + if (uid != uid_arg) { + PyErr_SetString(PyExc_OverflowError, "user id too big"); + return NULL; + } + if (setuid(uid) < 0) + return posix_error(); + Py_INCREF(Py_None); + return Py_None; } #endif /* HAVE_SETUID */ @@ -4170,21 +4171,21 @@ static PyObject * posix_seteuid (PyObject *self, PyObject *args) { - long euid_arg; - uid_t euid; - if (!PyArg_ParseTuple(args, "l", &euid_arg)) - return NULL; - euid = euid_arg; - if (euid != euid_arg) { - PyErr_SetString(PyExc_OverflowError, "user id too big"); - return NULL; - } - if (seteuid(euid) < 0) { - return posix_error(); - } else { - Py_INCREF(Py_None); - return Py_None; - } + long euid_arg; + uid_t euid; + if (!PyArg_ParseTuple(args, "l", &euid_arg)) + return NULL; + euid = euid_arg; + if (euid != euid_arg) { + PyErr_SetString(PyExc_OverflowError, "user id too big"); + return NULL; + } + if (seteuid(euid) < 0) { + return posix_error(); + } else { + Py_INCREF(Py_None); + return Py_None; + } } #endif /* HAVE_SETEUID */ @@ -4196,21 +4197,21 @@ static PyObject * posix_setegid (PyObject *self, PyObject *args) { - long egid_arg; - gid_t egid; - if (!PyArg_ParseTuple(args, "l", &egid_arg)) - return NULL; - egid = egid_arg; - if (egid != egid_arg) { - PyErr_SetString(PyExc_OverflowError, "group id too big"); - return NULL; - } - if (setegid(egid) < 0) { - return posix_error(); - } else { - Py_INCREF(Py_None); - return Py_None; - } + long egid_arg; + gid_t egid; + if (!PyArg_ParseTuple(args, "l", &egid_arg)) + return NULL; + egid = egid_arg; + if (egid != egid_arg) { + PyErr_SetString(PyExc_OverflowError, "group id too big"); + return NULL; + } + if (setegid(egid) < 0) { + return posix_error(); + } else { + Py_INCREF(Py_None); + return Py_None; + } } #endif /* HAVE_SETEGID */ @@ -4222,29 +4223,29 @@ static PyObject * posix_setreuid (PyObject *self, PyObject *args) { - long ruid_arg, euid_arg; - uid_t ruid, euid; - if (!PyArg_ParseTuple(args, "ll", &ruid_arg, &euid_arg)) - return NULL; - if (ruid_arg == -1) - ruid = (uid_t)-1; /* let the compiler choose how -1 fits */ - else - ruid = ruid_arg; /* otherwise, assign from our long */ - if (euid_arg == -1) - euid = (uid_t)-1; - else - euid = euid_arg; - if ((euid_arg != -1 && euid != euid_arg) || - (ruid_arg != -1 && ruid != ruid_arg)) { - PyErr_SetString(PyExc_OverflowError, "user id too big"); - return NULL; - } - if (setreuid(ruid, euid) < 0) { - return posix_error(); - } else { - Py_INCREF(Py_None); - return Py_None; - } + long ruid_arg, euid_arg; + uid_t ruid, euid; + if (!PyArg_ParseTuple(args, "ll", &ruid_arg, &euid_arg)) + return NULL; + if (ruid_arg == -1) + ruid = (uid_t)-1; /* let the compiler choose how -1 fits */ + else + ruid = ruid_arg; /* otherwise, assign from our long */ + if (euid_arg == -1) + euid = (uid_t)-1; + else + euid = euid_arg; + if ((euid_arg != -1 && euid != euid_arg) || + (ruid_arg != -1 && ruid != ruid_arg)) { + PyErr_SetString(PyExc_OverflowError, "user id too big"); + return NULL; + } + if (setreuid(ruid, euid) < 0) { + return posix_error(); + } else { + Py_INCREF(Py_None); + return Py_None; + } } #endif /* HAVE_SETREUID */ @@ -4256,29 +4257,29 @@ static PyObject * posix_setregid (PyObject *self, PyObject *args) { - long rgid_arg, egid_arg; - gid_t rgid, egid; - if (!PyArg_ParseTuple(args, "ll", &rgid_arg, &egid_arg)) - return NULL; - if (rgid_arg == -1) - rgid = (gid_t)-1; /* let the compiler choose how -1 fits */ - else - rgid = rgid_arg; /* otherwise, assign from our long */ - if (egid_arg == -1) - egid = (gid_t)-1; - else - egid = egid_arg; - if ((egid_arg != -1 && egid != egid_arg) || - (rgid_arg != -1 && rgid != rgid_arg)) { - PyErr_SetString(PyExc_OverflowError, "group id too big"); - return NULL; - } - if (setregid(rgid, egid) < 0) { - return posix_error(); - } else { - Py_INCREF(Py_None); - return Py_None; - } + long rgid_arg, egid_arg; + gid_t rgid, egid; + if (!PyArg_ParseTuple(args, "ll", &rgid_arg, &egid_arg)) + return NULL; + if (rgid_arg == -1) + rgid = (gid_t)-1; /* let the compiler choose how -1 fits */ + else + rgid = rgid_arg; /* otherwise, assign from our long */ + if (egid_arg == -1) + egid = (gid_t)-1; + else + egid = egid_arg; + if ((egid_arg != -1 && egid != egid_arg) || + (rgid_arg != -1 && rgid != rgid_arg)) { + PyErr_SetString(PyExc_OverflowError, "group id too big"); + return NULL; + } + if (setregid(rgid, egid) < 0) { + return posix_error(); + } else { + Py_INCREF(Py_None); + return Py_None; + } } #endif /* HAVE_SETREGID */ @@ -4290,19 +4291,19 @@ static PyObject * posix_setgid(PyObject *self, PyObject *args) { - long gid_arg; - gid_t gid; - if (!PyArg_ParseTuple(args, "l:setgid", &gid_arg)) - return NULL; - gid = gid_arg; - if (gid != gid_arg) { - PyErr_SetString(PyExc_OverflowError, "group id too big"); - return NULL; - } - if (setgid(gid) < 0) - return posix_error(); - Py_INCREF(Py_None); - return Py_None; + long gid_arg; + gid_t gid; + if (!PyArg_ParseTuple(args, "l:setgid", &gid_arg)) + return NULL; + gid = gid_arg; + if (gid != gid_arg) { + PyErr_SetString(PyExc_OverflowError, "group id too big"); + return NULL; + } + if (setgid(gid) < 0) + return posix_error(); + Py_INCREF(Py_None); + return Py_None; } #endif /* HAVE_SETGID */ @@ -4314,52 +4315,52 @@ static PyObject * posix_setgroups(PyObject *self, PyObject *groups) { - int i, len; - gid_t grouplist[MAX_GROUPS]; + int i, len; + gid_t grouplist[MAX_GROUPS]; + + if (!PySequence_Check(groups)) { + PyErr_SetString(PyExc_TypeError, "setgroups argument must be a sequence"); + return NULL; + } + len = PySequence_Size(groups); + if (len > MAX_GROUPS) { + PyErr_SetString(PyExc_ValueError, "too many groups"); + return NULL; + } + for(i = 0; i < len; i++) { + PyObject *elem; + elem = PySequence_GetItem(groups, i); + if (!elem) + return NULL; + if (!PyLong_Check(elem)) { + PyErr_SetString(PyExc_TypeError, + "groups must be integers"); + Py_DECREF(elem); + return NULL; + } else { + unsigned long x = PyLong_AsUnsignedLong(elem); + if (PyErr_Occurred()) { + PyErr_SetString(PyExc_TypeError, + "group id too big"); + Py_DECREF(elem); + return NULL; + } + grouplist[i] = x; + /* read back the value to see if it fitted in gid_t */ + if (grouplist[i] != x) { + PyErr_SetString(PyExc_TypeError, + "group id too big"); + Py_DECREF(elem); + return NULL; + } + } + Py_DECREF(elem); + } - if (!PySequence_Check(groups)) { - PyErr_SetString(PyExc_TypeError, "setgroups argument must be a sequence"); - return NULL; - } - len = PySequence_Size(groups); - if (len > MAX_GROUPS) { - PyErr_SetString(PyExc_ValueError, "too many groups"); - return NULL; - } - for(i = 0; i < len; i++) { - PyObject *elem; - elem = PySequence_GetItem(groups, i); - if (!elem) - return NULL; - if (!PyLong_Check(elem)) { - PyErr_SetString(PyExc_TypeError, - "groups must be integers"); - Py_DECREF(elem); - return NULL; - } else { - unsigned long x = PyLong_AsUnsignedLong(elem); - if (PyErr_Occurred()) { - PyErr_SetString(PyExc_TypeError, - "group id too big"); - Py_DECREF(elem); - return NULL; - } - grouplist[i] = x; - /* read back the value to see if it fitted in gid_t */ - if (grouplist[i] != x) { - PyErr_SetString(PyExc_TypeError, - "group id too big"); - Py_DECREF(elem); - return NULL; - } - } - Py_DECREF(elem); - } - - if (setgroups(len, grouplist) < 0) - return posix_error(); - Py_INCREF(Py_None); - return Py_None; + if (setgroups(len, grouplist) < 0) + return posix_error(); + Py_INCREF(Py_None); + return Py_None; } #endif /* HAVE_SETGROUPS */ @@ -4367,59 +4368,59 @@ static PyObject * wait_helper(pid_t pid, int status, struct rusage *ru) { - PyObject *result; - static PyObject *struct_rusage; + PyObject *result; + static PyObject *struct_rusage; - if (pid == -1) - return posix_error(); + if (pid == -1) + return posix_error(); - if (struct_rusage == NULL) { - PyObject *m = PyImport_ImportModuleNoBlock("resource"); - if (m == NULL) - return NULL; - struct_rusage = PyObject_GetAttrString(m, "struct_rusage"); - Py_DECREF(m); - if (struct_rusage == NULL) - return NULL; - } - - /* XXX(nnorwitz): Copied (w/mods) from resource.c, there should be only one. */ - result = PyStructSequence_New((PyTypeObject*) struct_rusage); - if (!result) - return NULL; + if (struct_rusage == NULL) { + PyObject *m = PyImport_ImportModuleNoBlock("resource"); + if (m == NULL) + return NULL; + struct_rusage = PyObject_GetAttrString(m, "struct_rusage"); + Py_DECREF(m); + if (struct_rusage == NULL) + return NULL; + } + + /* XXX(nnorwitz): Copied (w/mods) from resource.c, there should be only one. */ + result = PyStructSequence_New((PyTypeObject*) struct_rusage); + if (!result) + return NULL; #ifndef doubletime #define doubletime(TV) ((double)(TV).tv_sec + (TV).tv_usec * 0.000001) #endif - PyStructSequence_SET_ITEM(result, 0, - PyFloat_FromDouble(doubletime(ru->ru_utime))); - PyStructSequence_SET_ITEM(result, 1, - PyFloat_FromDouble(doubletime(ru->ru_stime))); + PyStructSequence_SET_ITEM(result, 0, + PyFloat_FromDouble(doubletime(ru->ru_utime))); + PyStructSequence_SET_ITEM(result, 1, + PyFloat_FromDouble(doubletime(ru->ru_stime))); #define SET_INT(result, index, value)\ - PyStructSequence_SET_ITEM(result, index, PyLong_FromLong(value)) - SET_INT(result, 2, ru->ru_maxrss); - SET_INT(result, 3, ru->ru_ixrss); - SET_INT(result, 4, ru->ru_idrss); - SET_INT(result, 5, ru->ru_isrss); - SET_INT(result, 6, ru->ru_minflt); - SET_INT(result, 7, ru->ru_majflt); - SET_INT(result, 8, ru->ru_nswap); - SET_INT(result, 9, ru->ru_inblock); - SET_INT(result, 10, ru->ru_oublock); - SET_INT(result, 11, ru->ru_msgsnd); - SET_INT(result, 12, ru->ru_msgrcv); - SET_INT(result, 13, ru->ru_nsignals); - SET_INT(result, 14, ru->ru_nvcsw); - SET_INT(result, 15, ru->ru_nivcsw); + PyStructSequence_SET_ITEM(result, index, PyLong_FromLong(value)) + SET_INT(result, 2, ru->ru_maxrss); + SET_INT(result, 3, ru->ru_ixrss); + SET_INT(result, 4, ru->ru_idrss); + SET_INT(result, 5, ru->ru_isrss); + SET_INT(result, 6, ru->ru_minflt); + SET_INT(result, 7, ru->ru_majflt); + SET_INT(result, 8, ru->ru_nswap); + SET_INT(result, 9, ru->ru_inblock); + SET_INT(result, 10, ru->ru_oublock); + SET_INT(result, 11, ru->ru_msgsnd); + SET_INT(result, 12, ru->ru_msgrcv); + SET_INT(result, 13, ru->ru_nsignals); + SET_INT(result, 14, ru->ru_nvcsw); + SET_INT(result, 15, ru->ru_nivcsw); #undef SET_INT - if (PyErr_Occurred()) { - Py_DECREF(result); - return NULL; - } + if (PyErr_Occurred()) { + Py_DECREF(result); + return NULL; + } - return Py_BuildValue("NiN", PyLong_FromPid(pid), status, result); + return Py_BuildValue("NiN", PyLong_FromPid(pid), status, result); } #endif /* HAVE_WAIT3 || HAVE_WAIT4 */ @@ -4431,20 +4432,20 @@ static PyObject * posix_wait3(PyObject *self, PyObject *args) { - pid_t pid; - int options; - struct rusage ru; - WAIT_TYPE status; - WAIT_STATUS_INT(status) = 0; - - if (!PyArg_ParseTuple(args, "i:wait3", &options)) - return NULL; - - Py_BEGIN_ALLOW_THREADS - pid = wait3(&status, options, &ru); - Py_END_ALLOW_THREADS + pid_t pid; + int options; + struct rusage ru; + WAIT_TYPE status; + WAIT_STATUS_INT(status) = 0; + + if (!PyArg_ParseTuple(args, "i:wait3", &options)) + return NULL; + + Py_BEGIN_ALLOW_THREADS + pid = wait3(&status, options, &ru); + Py_END_ALLOW_THREADS - return wait_helper(pid, WAIT_STATUS_INT(status), &ru); + return wait_helper(pid, WAIT_STATUS_INT(status), &ru); } #endif /* HAVE_WAIT3 */ @@ -4456,20 +4457,20 @@ static PyObject * posix_wait4(PyObject *self, PyObject *args) { - pid_t pid; - int options; - struct rusage ru; - WAIT_TYPE status; - WAIT_STATUS_INT(status) = 0; - - if (!PyArg_ParseTuple(args, _Py_PARSE_PID "i:wait4", &pid, &options)) - return NULL; - - Py_BEGIN_ALLOW_THREADS - pid = wait4(pid, &status, options, &ru); - Py_END_ALLOW_THREADS + pid_t pid; + int options; + struct rusage ru; + WAIT_TYPE status; + WAIT_STATUS_INT(status) = 0; + + if (!PyArg_ParseTuple(args, _Py_PARSE_PID "i:wait4", &pid, &options)) + return NULL; - return wait_helper(pid, WAIT_STATUS_INT(status), &ru); + Py_BEGIN_ALLOW_THREADS + pid = wait4(pid, &status, options, &ru); + Py_END_ALLOW_THREADS + + return wait_helper(pid, WAIT_STATUS_INT(status), &ru); } #endif /* HAVE_WAIT4 */ @@ -4481,20 +4482,20 @@ static PyObject * posix_waitpid(PyObject *self, PyObject *args) { - pid_t pid; - int options; - WAIT_TYPE status; - WAIT_STATUS_INT(status) = 0; - - if (!PyArg_ParseTuple(args, _Py_PARSE_PID "i:waitpid", &pid, &options)) - return NULL; - Py_BEGIN_ALLOW_THREADS - pid = waitpid(pid, &status, options); - Py_END_ALLOW_THREADS - if (pid == -1) - return posix_error(); + pid_t pid; + int options; + WAIT_TYPE status; + WAIT_STATUS_INT(status) = 0; + + if (!PyArg_ParseTuple(args, _Py_PARSE_PID "i:waitpid", &pid, &options)) + return NULL; + Py_BEGIN_ALLOW_THREADS + pid = waitpid(pid, &status, options); + Py_END_ALLOW_THREADS + if (pid == -1) + return posix_error(); - return Py_BuildValue("Ni", PyLong_FromPid(pid), WAIT_STATUS_INT(status)); + return Py_BuildValue("Ni", PyLong_FromPid(pid), WAIT_STATUS_INT(status)); } #elif defined(HAVE_CWAIT) @@ -4507,19 +4508,19 @@ static PyObject * posix_waitpid(PyObject *self, PyObject *args) { - Py_intptr_t pid; - int status, options; + Py_intptr_t pid; + int status, options; - if (!PyArg_ParseTuple(args, _Py_PARSE_PID "i:waitpid", &pid, &options)) - return NULL; - Py_BEGIN_ALLOW_THREADS - pid = _cwait(&status, pid, options); - Py_END_ALLOW_THREADS - if (pid == -1) - return posix_error(); + if (!PyArg_ParseTuple(args, _Py_PARSE_PID "i:waitpid", &pid, &options)) + return NULL; + Py_BEGIN_ALLOW_THREADS + pid = _cwait(&status, pid, options); + Py_END_ALLOW_THREADS + if (pid == -1) + return posix_error(); - /* shift the status left a byte so this is more like the POSIX waitpid */ - return Py_BuildValue("Ni", PyLong_FromPid(pid), status << 8); + /* shift the status left a byte so this is more like the POSIX waitpid */ + return Py_BuildValue("Ni", PyLong_FromPid(pid), status << 8); } #endif /* HAVE_WAITPID || HAVE_CWAIT */ @@ -4531,17 +4532,17 @@ static PyObject * posix_wait(PyObject *self, PyObject *noargs) { - pid_t pid; - WAIT_TYPE status; - WAIT_STATUS_INT(status) = 0; - - Py_BEGIN_ALLOW_THREADS - pid = wait(&status); - Py_END_ALLOW_THREADS - if (pid == -1) - return posix_error(); + pid_t pid; + WAIT_TYPE status; + WAIT_STATUS_INT(status) = 0; + + Py_BEGIN_ALLOW_THREADS + pid = wait(&status); + Py_END_ALLOW_THREADS + if (pid == -1) + return posix_error(); - return Py_BuildValue("Ni", PyLong_FromPid(pid), WAIT_STATUS_INT(status)); + return Py_BuildValue("Ni", PyLong_FromPid(pid), WAIT_STATUS_INT(status)); } #endif @@ -4554,12 +4555,12 @@ posix_lstat(PyObject *self, PyObject *args) { #ifdef HAVE_LSTAT - return posix_do_stat(self, args, "O&:lstat", lstat, NULL, NULL); + return posix_do_stat(self, args, "O&:lstat", lstat, NULL, NULL); #else /* !HAVE_LSTAT */ #ifdef MS_WINDOWS - return posix_do_stat(self, args, "O&:lstat", STAT, "U:lstat", win32_wstat); + return posix_do_stat(self, args, "O&:lstat", STAT, "U:lstat", win32_wstat); #else - return posix_do_stat(self, args, "O&:lstat", STAT, NULL, NULL); + return posix_do_stat(self, args, "O&:lstat", STAT, NULL, NULL); #endif #endif /* !HAVE_LSTAT */ } @@ -4573,51 +4574,51 @@ static PyObject * posix_readlink(PyObject *self, PyObject *args) { - PyObject* v; - char buf[MAXPATHLEN]; - PyObject *opath; - char *path; - int n; - int arg_is_unicode = 0; - - if (!PyArg_ParseTuple(args, "O&:readlink", - PyUnicode_FSConverter, &opath)) - return NULL; - path = PyBytes_AsString(opath); - v = PySequence_GetItem(args, 0); - if (v == NULL) { - Py_DECREF(opath); - return NULL; - } - - if (PyUnicode_Check(v)) { - arg_is_unicode = 1; - } - Py_DECREF(v); - - Py_BEGIN_ALLOW_THREADS - n = readlink(path, buf, (int) sizeof buf); - Py_END_ALLOW_THREADS - if (n < 0) - return posix_error_with_allocated_filename(opath); - - Py_DECREF(opath); - v = PyBytes_FromStringAndSize(buf, n); - if (arg_is_unicode) { - PyObject *w; - - w = PyUnicode_FromEncodedObject(v, - Py_FileSystemDefaultEncoding, - "surrogateescape"); - if (w != NULL) { - Py_DECREF(v); - v = w; - } - else { - v = NULL; - } - } - return v; + PyObject* v; + char buf[MAXPATHLEN]; + PyObject *opath; + char *path; + int n; + int arg_is_unicode = 0; + + if (!PyArg_ParseTuple(args, "O&:readlink", + PyUnicode_FSConverter, &opath)) + return NULL; + path = PyBytes_AsString(opath); + v = PySequence_GetItem(args, 0); + if (v == NULL) { + Py_DECREF(opath); + return NULL; + } + + if (PyUnicode_Check(v)) { + arg_is_unicode = 1; + } + Py_DECREF(v); + + Py_BEGIN_ALLOW_THREADS + n = readlink(path, buf, (int) sizeof buf); + Py_END_ALLOW_THREADS + if (n < 0) + return posix_error_with_allocated_filename(opath); + + Py_DECREF(opath); + v = PyBytes_FromStringAndSize(buf, n); + if (arg_is_unicode) { + PyObject *w; + + w = PyUnicode_FromEncodedObject(v, + Py_FileSystemDefaultEncoding, + "surrogateescape"); + if (w != NULL) { + Py_DECREF(v); + v = w; + } + else { + v = NULL; + } + } + return v; } #endif /* HAVE_READLINK */ @@ -4630,7 +4631,7 @@ static PyObject * posix_symlink(PyObject *self, PyObject *args) { - return posix_2str(args, "O&O&:symlink", symlink); + return posix_2str(args, "O&O&:symlink", symlink); } #endif /* HAVE_SYMLINK */ @@ -4653,12 +4654,12 @@ posix_times(PyObject *self, PyObject *noargs) { /* Currently Only Uptime is Provided -- Others Later */ - return Py_BuildValue("ddddd", - (double)0 /* t.tms_utime / HZ */, - (double)0 /* t.tms_stime / HZ */, - (double)0 /* t.tms_cutime / HZ */, - (double)0 /* t.tms_cstime / HZ */, - (double)system_uptime() / 1000); + return Py_BuildValue("ddddd", + (double)0 /* t.tms_utime / HZ */, + (double)0 /* t.tms_stime / HZ */, + (double)0 /* t.tms_cutime / HZ */, + (double)0 /* t.tms_cstime / HZ */, + (double)system_uptime() / 1000); } #else /* not OS2 */ #define NEED_TICKS_PER_SECOND @@ -4666,46 +4667,46 @@ static PyObject * posix_times(PyObject *self, PyObject *noargs) { - struct tms t; - clock_t c; - errno = 0; - c = times(&t); - if (c == (clock_t) -1) - return posix_error(); - return Py_BuildValue("ddddd", - (double)t.tms_utime / ticks_per_second, - (double)t.tms_stime / ticks_per_second, - (double)t.tms_cutime / ticks_per_second, - (double)t.tms_cstime / ticks_per_second, - (double)c / ticks_per_second); + struct tms t; + clock_t c; + errno = 0; + c = times(&t); + if (c == (clock_t) -1) + return posix_error(); + return Py_BuildValue("ddddd", + (double)t.tms_utime / ticks_per_second, + (double)t.tms_stime / ticks_per_second, + (double)t.tms_cutime / ticks_per_second, + (double)t.tms_cstime / ticks_per_second, + (double)c / ticks_per_second); } #endif /* not OS2 */ #endif /* HAVE_TIMES */ #ifdef MS_WINDOWS -#define HAVE_TIMES /* so the method table will pick it up */ +#define HAVE_TIMES /* so the method table will pick it up */ static PyObject * posix_times(PyObject *self, PyObject *noargs) { - FILETIME create, exit, kernel, user; - HANDLE hProc; - hProc = GetCurrentProcess(); - GetProcessTimes(hProc, &create, &exit, &kernel, &user); - /* The fields of a FILETIME structure are the hi and lo part - of a 64-bit value expressed in 100 nanosecond units. - 1e7 is one second in such units; 1e-7 the inverse. - 429.4967296 is 2**32 / 1e7 or 2**32 * 1e-7. - */ - return Py_BuildValue( - "ddddd", - (double)(user.dwHighDateTime*429.4967296 + - user.dwLowDateTime*1e-7), - (double)(kernel.dwHighDateTime*429.4967296 + - kernel.dwLowDateTime*1e-7), - (double)0, - (double)0, - (double)0); + FILETIME create, exit, kernel, user; + HANDLE hProc; + hProc = GetCurrentProcess(); + GetProcessTimes(hProc, &create, &exit, &kernel, &user); + /* The fields of a FILETIME structure are the hi and lo part + of a 64-bit value expressed in 100 nanosecond units. + 1e7 is one second in such units; 1e-7 the inverse. + 429.4967296 is 2**32 / 1e7 or 2**32 * 1e-7. + */ + return Py_BuildValue( + "ddddd", + (double)(user.dwHighDateTime*429.4967296 + + user.dwLowDateTime*1e-7), + (double)(kernel.dwHighDateTime*429.4967296 + + kernel.dwLowDateTime*1e-7), + (double)0, + (double)0, + (double)0); } #endif /* MS_WINDOWS */ @@ -4724,14 +4725,14 @@ static PyObject * posix_getsid(PyObject *self, PyObject *args) { - pid_t pid; - int sid; - if (!PyArg_ParseTuple(args, _Py_PARSE_PID ":getsid", &pid)) - return NULL; - sid = getsid(pid); - if (sid < 0) - return posix_error(); - return PyLong_FromLong((long)sid); + pid_t pid; + int sid; + if (!PyArg_ParseTuple(args, _Py_PARSE_PID ":getsid", &pid)) + return NULL; + sid = getsid(pid); + if (sid < 0) + return posix_error(); + return PyLong_FromLong((long)sid); } #endif /* HAVE_GETSID */ @@ -4744,10 +4745,10 @@ static PyObject * posix_setsid(PyObject *self, PyObject *noargs) { - if (setsid() < 0) - return posix_error(); - Py_INCREF(Py_None); - return Py_None; + if (setsid() < 0) + return posix_error(); + Py_INCREF(Py_None); + return Py_None; } #endif /* HAVE_SETSID */ @@ -4759,14 +4760,14 @@ static PyObject * posix_setpgid(PyObject *self, PyObject *args) { - pid_t pid; - int pgrp; - if (!PyArg_ParseTuple(args, _Py_PARSE_PID "i:setpgid", &pid, &pgrp)) - return NULL; - if (setpgid(pid, pgrp) < 0) - return posix_error(); - Py_INCREF(Py_None); - return Py_None; + pid_t pid; + int pgrp; + if (!PyArg_ParseTuple(args, _Py_PARSE_PID "i:setpgid", &pid, &pgrp)) + return NULL; + if (setpgid(pid, pgrp) < 0) + return posix_error(); + Py_INCREF(Py_None); + return Py_None; } #endif /* HAVE_SETPGID */ @@ -4779,14 +4780,14 @@ static PyObject * posix_tcgetpgrp(PyObject *self, PyObject *args) { - int fd; - pid_t pgid; - if (!PyArg_ParseTuple(args, "i:tcgetpgrp", &fd)) - return NULL; - pgid = tcgetpgrp(fd); - if (pgid < 0) - return posix_error(); - return PyLong_FromPid(pgid); + int fd; + pid_t pgid; + if (!PyArg_ParseTuple(args, "i:tcgetpgrp", &fd)) + return NULL; + pgid = tcgetpgrp(fd); + if (pgid < 0) + return posix_error(); + return PyLong_FromPid(pgid); } #endif /* HAVE_TCGETPGRP */ @@ -4799,14 +4800,14 @@ static PyObject * posix_tcsetpgrp(PyObject *self, PyObject *args) { - int fd; - pid_t pgid; - if (!PyArg_ParseTuple(args, "i" _Py_PARSE_PID ":tcsetpgrp", &fd, &pgid)) - return NULL; - if (tcsetpgrp(fd, pgid) < 0) - return posix_error(); - Py_INCREF(Py_None); - return Py_None; + int fd; + pid_t pgid; + if (!PyArg_ParseTuple(args, "i" _Py_PARSE_PID ":tcsetpgrp", &fd, &pgid)) + return NULL; + if (tcsetpgrp(fd, pgid) < 0) + return posix_error(); + Py_INCREF(Py_None); + return Py_None; } #endif /* HAVE_TCSETPGRP */ @@ -4819,41 +4820,41 @@ static PyObject * posix_open(PyObject *self, PyObject *args) { - PyObject *ofile; - char *file; - int flag; - int mode = 0777; - int fd; + PyObject *ofile; + char *file; + int flag; + int mode = 0777; + int fd; #ifdef MS_WINDOWS - PyUnicodeObject *po; - if (PyArg_ParseTuple(args, "Ui|i:mkdir", &po, &flag, &mode)) { - Py_BEGIN_ALLOW_THREADS - /* PyUnicode_AS_UNICODE OK without thread - lock as it is a simple dereference. */ - fd = _wopen(PyUnicode_AS_UNICODE(po), flag, mode); - Py_END_ALLOW_THREADS - if (fd < 0) - return posix_error(); - return PyLong_FromLong((long)fd); - } - /* Drop the argument parsing error as narrow strings - are also valid. */ - PyErr_Clear(); -#endif - - if (!PyArg_ParseTuple(args, "O&i|i", - PyUnicode_FSConverter, &ofile, - &flag, &mode)) - return NULL; - file = PyBytes_AsString(ofile); - Py_BEGIN_ALLOW_THREADS - fd = open(file, flag, mode); - Py_END_ALLOW_THREADS - if (fd < 0) - return posix_error_with_allocated_filename(ofile); - Py_DECREF(ofile); - return PyLong_FromLong((long)fd); + PyUnicodeObject *po; + if (PyArg_ParseTuple(args, "Ui|i:mkdir", &po, &flag, &mode)) { + Py_BEGIN_ALLOW_THREADS + /* PyUnicode_AS_UNICODE OK without thread + lock as it is a simple dereference. */ + fd = _wopen(PyUnicode_AS_UNICODE(po), flag, mode); + Py_END_ALLOW_THREADS + if (fd < 0) + return posix_error(); + return PyLong_FromLong((long)fd); + } + /* Drop the argument parsing error as narrow strings + are also valid. */ + PyErr_Clear(); +#endif + + if (!PyArg_ParseTuple(args, "O&i|i", + PyUnicode_FSConverter, &ofile, + &flag, &mode)) + return NULL; + file = PyBytes_AsString(ofile); + Py_BEGIN_ALLOW_THREADS + fd = open(file, flag, mode); + Py_END_ALLOW_THREADS + if (fd < 0) + return posix_error_with_allocated_filename(ofile); + Py_DECREF(ofile); + return PyLong_FromLong((long)fd); } @@ -4864,37 +4865,37 @@ static PyObject * posix_close(PyObject *self, PyObject *args) { - int fd, res; - if (!PyArg_ParseTuple(args, "i:close", &fd)) - return NULL; - if (!_PyVerify_fd(fd)) - return posix_error(); - Py_BEGIN_ALLOW_THREADS - res = close(fd); - Py_END_ALLOW_THREADS - if (res < 0) - return posix_error(); - Py_INCREF(Py_None); - return Py_None; + int fd, res; + if (!PyArg_ParseTuple(args, "i:close", &fd)) + return NULL; + if (!_PyVerify_fd(fd)) + return posix_error(); + Py_BEGIN_ALLOW_THREADS + res = close(fd); + Py_END_ALLOW_THREADS + if (res < 0) + return posix_error(); + Py_INCREF(Py_None); + return Py_None; } -PyDoc_STRVAR(posix_closerange__doc__, +PyDoc_STRVAR(posix_closerange__doc__, "closerange(fd_low, fd_high)\n\n\ Closes all file descriptors in [fd_low, fd_high), ignoring errors."); static PyObject * posix_closerange(PyObject *self, PyObject *args) { - int fd_from, fd_to, i; - if (!PyArg_ParseTuple(args, "ii:closerange", &fd_from, &fd_to)) - return NULL; - Py_BEGIN_ALLOW_THREADS - for (i = fd_from; i < fd_to; i++) - if (_PyVerify_fd(i)) - close(i); - Py_END_ALLOW_THREADS - Py_RETURN_NONE; + int fd_from, fd_to, i; + if (!PyArg_ParseTuple(args, "ii:closerange", &fd_from, &fd_to)) + return NULL; + Py_BEGIN_ALLOW_THREADS + for (i = fd_from; i < fd_to; i++) + if (_PyVerify_fd(i)) + close(i); + Py_END_ALLOW_THREADS + Py_RETURN_NONE; } @@ -4905,17 +4906,17 @@ static PyObject * posix_dup(PyObject *self, PyObject *args) { - int fd; - if (!PyArg_ParseTuple(args, "i:dup", &fd)) - return NULL; - if (!_PyVerify_fd(fd)) - return posix_error(); - Py_BEGIN_ALLOW_THREADS - fd = dup(fd); - Py_END_ALLOW_THREADS - if (fd < 0) - return posix_error(); - return PyLong_FromLong((long)fd); + int fd; + if (!PyArg_ParseTuple(args, "i:dup", &fd)) + return NULL; + if (!_PyVerify_fd(fd)) + return posix_error(); + Py_BEGIN_ALLOW_THREADS + fd = dup(fd); + Py_END_ALLOW_THREADS + if (fd < 0) + return posix_error(); + return PyLong_FromLong((long)fd); } @@ -4926,18 +4927,18 @@ static PyObject * posix_dup2(PyObject *self, PyObject *args) { - int fd, fd2, res; - if (!PyArg_ParseTuple(args, "ii:dup2", &fd, &fd2)) - return NULL; - if (!_PyVerify_fd_dup2(fd, fd2)) - return posix_error(); - Py_BEGIN_ALLOW_THREADS - res = dup2(fd, fd2); - Py_END_ALLOW_THREADS - if (res < 0) - return posix_error(); - Py_INCREF(Py_None); - return Py_None; + int fd, fd2, res; + if (!PyArg_ParseTuple(args, "ii:dup2", &fd, &fd2)) + return NULL; + if (!_PyVerify_fd_dup2(fd, fd2)) + return posix_error(); + Py_BEGIN_ALLOW_THREADS + res = dup2(fd, fd2); + Py_END_ALLOW_THREADS + if (res < 0) + return posix_error(); + Py_INCREF(Py_None); + return Py_None; } @@ -4948,49 +4949,49 @@ static PyObject * posix_lseek(PyObject *self, PyObject *args) { - int fd, how; + int fd, how; #if defined(MS_WIN64) || defined(MS_WINDOWS) - PY_LONG_LONG pos, res; + PY_LONG_LONG pos, res; #else - off_t pos, res; + off_t pos, res; #endif - PyObject *posobj; - if (!PyArg_ParseTuple(args, "iOi:lseek", &fd, &posobj, &how)) - return NULL; + PyObject *posobj; + if (!PyArg_ParseTuple(args, "iOi:lseek", &fd, &posobj, &how)) + return NULL; #ifdef SEEK_SET - /* Turn 0, 1, 2 into SEEK_{SET,CUR,END} */ - switch (how) { - case 0: how = SEEK_SET; break; - case 1: how = SEEK_CUR; break; - case 2: how = SEEK_END; break; - } + /* Turn 0, 1, 2 into SEEK_{SET,CUR,END} */ + switch (how) { + case 0: how = SEEK_SET; break; + case 1: how = SEEK_CUR; break; + case 2: how = SEEK_END; break; + } #endif /* SEEK_END */ #if !defined(HAVE_LARGEFILE_SUPPORT) - pos = PyLong_AsLong(posobj); + pos = PyLong_AsLong(posobj); #else - pos = PyLong_Check(posobj) ? - PyLong_AsLongLong(posobj) : PyLong_AsLong(posobj); + pos = PyLong_Check(posobj) ? + PyLong_AsLongLong(posobj) : PyLong_AsLong(posobj); #endif - if (PyErr_Occurred()) - return NULL; + if (PyErr_Occurred()) + return NULL; - if (!_PyVerify_fd(fd)) - return posix_error(); - Py_BEGIN_ALLOW_THREADS + if (!_PyVerify_fd(fd)) + return posix_error(); + Py_BEGIN_ALLOW_THREADS #if defined(MS_WIN64) || defined(MS_WINDOWS) - res = _lseeki64(fd, pos, how); + res = _lseeki64(fd, pos, how); #else - res = lseek(fd, pos, how); + res = lseek(fd, pos, how); #endif - Py_END_ALLOW_THREADS - if (res < 0) - return posix_error(); + Py_END_ALLOW_THREADS + if (res < 0) + return posix_error(); #if !defined(HAVE_LARGEFILE_SUPPORT) - return PyLong_FromLong(res); + return PyLong_FromLong(res); #else - return PyLong_FromLongLong(res); + return PyLong_FromLongLong(res); #endif } @@ -5002,30 +5003,30 @@ static PyObject * posix_read(PyObject *self, PyObject *args) { - int fd, size; - Py_ssize_t n; - PyObject *buffer; - if (!PyArg_ParseTuple(args, "ii:read", &fd, &size)) - return NULL; - if (size < 0) { - errno = EINVAL; - return posix_error(); - } - buffer = PyBytes_FromStringAndSize((char *)NULL, size); - if (buffer == NULL) - return NULL; - if (!_PyVerify_fd(fd)) - return posix_error(); - Py_BEGIN_ALLOW_THREADS - n = read(fd, PyBytes_AS_STRING(buffer), size); - Py_END_ALLOW_THREADS - if (n < 0) { - Py_DECREF(buffer); - return posix_error(); - } - if (n != size) - _PyBytes_Resize(&buffer, n); - return buffer; + int fd, size; + Py_ssize_t n; + PyObject *buffer; + if (!PyArg_ParseTuple(args, "ii:read", &fd, &size)) + return NULL; + if (size < 0) { + errno = EINVAL; + return posix_error(); + } + buffer = PyBytes_FromStringAndSize((char *)NULL, size); + if (buffer == NULL) + return NULL; + if (!_PyVerify_fd(fd)) + return posix_error(); + Py_BEGIN_ALLOW_THREADS + n = read(fd, PyBytes_AS_STRING(buffer), size); + Py_END_ALLOW_THREADS + if (n < 0) { + Py_DECREF(buffer); + return posix_error(); + } + if (n != size) + _PyBytes_Resize(&buffer, n); + return buffer; } @@ -5036,21 +5037,21 @@ static PyObject * posix_write(PyObject *self, PyObject *args) { - Py_buffer pbuf; - int fd; - Py_ssize_t size; - - if (!PyArg_ParseTuple(args, "iy*:write", &fd, &pbuf)) - return NULL; - if (!_PyVerify_fd(fd)) - return posix_error(); - Py_BEGIN_ALLOW_THREADS - size = write(fd, pbuf.buf, (size_t)pbuf.len); - Py_END_ALLOW_THREADS - PyBuffer_Release(&pbuf); - if (size < 0) - return posix_error(); - return PyLong_FromSsize_t(size); + Py_buffer pbuf; + int fd; + Py_ssize_t size; + + if (!PyArg_ParseTuple(args, "iy*:write", &fd, &pbuf)) + return NULL; + if (!_PyVerify_fd(fd)) + return posix_error(); + Py_BEGIN_ALLOW_THREADS + size = write(fd, pbuf.buf, (size_t)pbuf.len); + Py_END_ALLOW_THREADS + PyBuffer_Release(&pbuf); + if (size < 0) + return posix_error(); + return PyLong_FromSsize_t(size); } @@ -5061,29 +5062,29 @@ static PyObject * posix_fstat(PyObject *self, PyObject *args) { - int fd; - STRUCT_STAT st; - int res; - if (!PyArg_ParseTuple(args, "i:fstat", &fd)) - return NULL; + int fd; + STRUCT_STAT st; + int res; + if (!PyArg_ParseTuple(args, "i:fstat", &fd)) + return NULL; #ifdef __VMS - /* on OpenVMS we must ensure that all bytes are written to the file */ - fsync(fd); + /* on OpenVMS we must ensure that all bytes are written to the file */ + fsync(fd); #endif - if (!_PyVerify_fd(fd)) - return posix_error(); - Py_BEGIN_ALLOW_THREADS - res = FSTAT(fd, &st); - Py_END_ALLOW_THREADS - if (res != 0) { + if (!_PyVerify_fd(fd)) + return posix_error(); + Py_BEGIN_ALLOW_THREADS + res = FSTAT(fd, &st); + Py_END_ALLOW_THREADS + if (res != 0) { #ifdef MS_WINDOWS - return win32_error("fstat", NULL); + return win32_error("fstat", NULL); #else - return posix_error(); + return posix_error(); #endif - } + } - return _pystat_fromstructstat(&st); + return _pystat_fromstructstat(&st); } PyDoc_STRVAR(posix_isatty__doc__, @@ -5094,12 +5095,12 @@ static PyObject * posix_isatty(PyObject *self, PyObject *args) { - int fd; - if (!PyArg_ParseTuple(args, "i:isatty", &fd)) - return NULL; - if (!_PyVerify_fd(fd)) - return PyBool_FromLong(0); - return PyBool_FromLong(isatty(fd)); + int fd; + if (!PyArg_ParseTuple(args, "i:isatty", &fd)) + return NULL; + if (!_PyVerify_fd(fd)) + return PyBool_FromLong(0); + return PyBool_FromLong(isatty(fd)); } #ifdef HAVE_PIPE @@ -5114,35 +5115,35 @@ HFILE read, write; APIRET rc; - Py_BEGIN_ALLOW_THREADS + Py_BEGIN_ALLOW_THREADS rc = DosCreatePipe( &read, &write, 4096); - Py_END_ALLOW_THREADS + Py_END_ALLOW_THREADS if (rc != NO_ERROR) return os2_error(rc); return Py_BuildValue("(ii)", read, write); #else #if !defined(MS_WINDOWS) - int fds[2]; - int res; - Py_BEGIN_ALLOW_THREADS - res = pipe(fds); - Py_END_ALLOW_THREADS - if (res != 0) - return posix_error(); - return Py_BuildValue("(ii)", fds[0], fds[1]); + int fds[2]; + int res; + Py_BEGIN_ALLOW_THREADS + res = pipe(fds); + Py_END_ALLOW_THREADS + if (res != 0) + return posix_error(); + return Py_BuildValue("(ii)", fds[0], fds[1]); #else /* MS_WINDOWS */ - HANDLE read, write; - int read_fd, write_fd; - BOOL ok; - Py_BEGIN_ALLOW_THREADS - ok = CreatePipe(&read, &write, NULL, 0); - Py_END_ALLOW_THREADS - if (!ok) - return win32_error("CreatePipe", NULL); - read_fd = _open_osfhandle((Py_intptr_t)read, 0); - write_fd = _open_osfhandle((Py_intptr_t)write, 1); - return Py_BuildValue("(ii)", read_fd, write_fd); + HANDLE read, write; + int read_fd, write_fd; + BOOL ok; + Py_BEGIN_ALLOW_THREADS + ok = CreatePipe(&read, &write, NULL, 0); + Py_END_ALLOW_THREADS + if (!ok) + return win32_error("CreatePipe", NULL); + read_fd = _open_osfhandle((Py_intptr_t)read, 0); + write_fd = _open_osfhandle((Py_intptr_t)write, 1); + return Py_BuildValue("(ii)", read_fd, write_fd); #endif /* MS_WINDOWS */ #endif } @@ -5157,18 +5158,18 @@ static PyObject * posix_mkfifo(PyObject *self, PyObject *args) { - char *filename; - int mode = 0666; - int res; - if (!PyArg_ParseTuple(args, "s|i:mkfifo", &filename, &mode)) - return NULL; - Py_BEGIN_ALLOW_THREADS - res = mkfifo(filename, mode); - Py_END_ALLOW_THREADS - if (res < 0) - return posix_error(); - Py_INCREF(Py_None); - return Py_None; + char *filename; + int mode = 0666; + int res; + if (!PyArg_ParseTuple(args, "s|i:mkfifo", &filename, &mode)) + return NULL; + Py_BEGIN_ALLOW_THREADS + res = mkfifo(filename, mode); + Py_END_ALLOW_THREADS + if (res < 0) + return posix_error(); + Py_INCREF(Py_None); + return Py_None; } #endif @@ -5187,19 +5188,19 @@ static PyObject * posix_mknod(PyObject *self, PyObject *args) { - char *filename; - int mode = 0600; - int device = 0; - int res; - if (!PyArg_ParseTuple(args, "s|ii:mknod", &filename, &mode, &device)) - return NULL; - Py_BEGIN_ALLOW_THREADS - res = mknod(filename, mode, device); - Py_END_ALLOW_THREADS - if (res < 0) - return posix_error(); - Py_INCREF(Py_None); - return Py_None; + char *filename; + int mode = 0600; + int device = 0; + int res; + if (!PyArg_ParseTuple(args, "s|ii:mknod", &filename, &mode, &device)) + return NULL; + Py_BEGIN_ALLOW_THREADS + res = mknod(filename, mode, device); + Py_END_ALLOW_THREADS + if (res < 0) + return posix_error(); + Py_INCREF(Py_None); + return Py_None; } #endif @@ -5211,10 +5212,10 @@ static PyObject * posix_major(PyObject *self, PyObject *args) { - int device; - if (!PyArg_ParseTuple(args, "i:major", &device)) - return NULL; - return PyLong_FromLong((long)major(device)); + int device; + if (!PyArg_ParseTuple(args, "i:major", &device)) + return NULL; + return PyLong_FromLong((long)major(device)); } PyDoc_STRVAR(posix_minor__doc__, @@ -5224,10 +5225,10 @@ static PyObject * posix_minor(PyObject *self, PyObject *args) { - int device; - if (!PyArg_ParseTuple(args, "i:minor", &device)) - return NULL; - return PyLong_FromLong((long)minor(device)); + int device; + if (!PyArg_ParseTuple(args, "i:minor", &device)) + return NULL; + return PyLong_FromLong((long)minor(device)); } PyDoc_STRVAR(posix_makedev__doc__, @@ -5237,10 +5238,10 @@ static PyObject * posix_makedev(PyObject *self, PyObject *args) { - int major, minor; - if (!PyArg_ParseTuple(args, "ii:makedev", &major, &minor)) - return NULL; - return PyLong_FromLong((long)makedev(major, minor)); + int major, minor; + if (!PyArg_ParseTuple(args, "ii:makedev", &major, &minor)) + return NULL; + return PyLong_FromLong((long)makedev(major, minor)); } #endif /* device macros */ @@ -5253,30 +5254,30 @@ static PyObject * posix_ftruncate(PyObject *self, PyObject *args) { - int fd; - off_t length; - int res; - PyObject *lenobj; + int fd; + off_t length; + int res; + PyObject *lenobj; - if (!PyArg_ParseTuple(args, "iO:ftruncate", &fd, &lenobj)) - return NULL; + if (!PyArg_ParseTuple(args, "iO:ftruncate", &fd, &lenobj)) + return NULL; #if !defined(HAVE_LARGEFILE_SUPPORT) - length = PyLong_AsLong(lenobj); + length = PyLong_AsLong(lenobj); #else - length = PyLong_Check(lenobj) ? - PyLong_AsLongLong(lenobj) : PyLong_AsLong(lenobj); + length = PyLong_Check(lenobj) ? + PyLong_AsLongLong(lenobj) : PyLong_AsLong(lenobj); #endif - if (PyErr_Occurred()) - return NULL; + if (PyErr_Occurred()) + return NULL; - Py_BEGIN_ALLOW_THREADS - res = ftruncate(fd, length); - Py_END_ALLOW_THREADS - if (res < 0) - return posix_error(); - Py_INCREF(Py_None); - return Py_None; + Py_BEGIN_ALLOW_THREADS + res = ftruncate(fd, length); + Py_END_ALLOW_THREADS + if (res < 0) + return posix_error(); + Py_INCREF(Py_None); + return Py_None; } #endif @@ -5293,29 +5294,29 @@ posix_putenv(PyObject *self, PyObject *args) { #ifdef MS_WINDOWS - wchar_t *s1, *s2; - wchar_t *newenv; + wchar_t *s1, *s2; + wchar_t *newenv; #else - PyObject *os1, *os2; - char *s1, *s2; - char *newenv; + PyObject *os1, *os2; + char *s1, *s2; + char *newenv; #endif - PyObject *newstr; - size_t len; + PyObject *newstr; + size_t len; #ifdef MS_WINDOWS - if (!PyArg_ParseTuple(args, - "uu:putenv", - &s1, &s2)) - return NULL; -#else - if (!PyArg_ParseTuple(args, - "O&O&:putenv", - PyUnicode_FSConverter, &os1, - PyUnicode_FSConverter, &os2)) - return NULL; - s1 = PyBytes_AsString(os1); - s2 = PyBytes_AsString(os2); + if (!PyArg_ParseTuple(args, + "uu:putenv", + &s1, &s2)) + return NULL; +#else + if (!PyArg_ParseTuple(args, + "O&O&:putenv", + PyUnicode_FSConverter, &os1, + PyUnicode_FSConverter, &os2)) + return NULL; + s1 = PyBytes_AsString(os1); + s2 = PyBytes_AsString(os2); #endif #if defined(PYOS_OS2) @@ -5334,59 +5335,59 @@ return os2_error(rc); } else { #endif - /* XXX This can leak memory -- not easy to fix :-( */ - /* len includes space for a trailing \0; the size arg to - PyBytes_FromStringAndSize does not count that */ + /* XXX This can leak memory -- not easy to fix :-( */ + /* len includes space for a trailing \0; the size arg to + PyBytes_FromStringAndSize does not count that */ #ifdef MS_WINDOWS - len = wcslen(s1) + wcslen(s2) + 2; - newstr = PyUnicode_FromUnicode(NULL, (int)len - 1); + len = wcslen(s1) + wcslen(s2) + 2; + newstr = PyUnicode_FromUnicode(NULL, (int)len - 1); #else - len = strlen(s1) + strlen(s2) + 2; - newstr = PyBytes_FromStringAndSize(NULL, (int)len - 1); + len = strlen(s1) + strlen(s2) + 2; + newstr = PyBytes_FromStringAndSize(NULL, (int)len - 1); #endif - if (newstr == NULL) - return PyErr_NoMemory(); + if (newstr == NULL) + return PyErr_NoMemory(); #ifdef MS_WINDOWS - newenv = PyUnicode_AsUnicode(newstr); - _snwprintf(newenv, len, L"%s=%s", s1, s2); - if (_wputenv(newenv)) { - Py_DECREF(newstr); - posix_error(); - return NULL; - } + newenv = PyUnicode_AsUnicode(newstr); + _snwprintf(newenv, len, L"%s=%s", s1, s2); + if (_wputenv(newenv)) { + Py_DECREF(newstr); + posix_error(); + return NULL; + } #else - newenv = PyBytes_AS_STRING(newstr); - PyOS_snprintf(newenv, len, "%s=%s", s1, s2); - if (putenv(newenv)) { - Py_DECREF(newstr); - Py_DECREF(os1); - Py_DECREF(os2); - posix_error(); - return NULL; - } + newenv = PyBytes_AS_STRING(newstr); + PyOS_snprintf(newenv, len, "%s=%s", s1, s2); + if (putenv(newenv)) { + Py_DECREF(newstr); + Py_DECREF(os1); + Py_DECREF(os2); + posix_error(); + return NULL; + } #endif - /* Install the first arg and newstr in posix_putenv_garbage; - * this will cause previous value to be collected. This has to - * happen after the real putenv() call because the old value - * was still accessible until then. */ - if (PyDict_SetItem(posix_putenv_garbage, - PyTuple_GET_ITEM(args, 0), newstr)) { - /* really not much we can do; just leak */ - PyErr_Clear(); - } - else { - Py_DECREF(newstr); - } + /* Install the first arg and newstr in posix_putenv_garbage; + * this will cause previous value to be collected. This has to + * happen after the real putenv() call because the old value + * was still accessible until then. */ + if (PyDict_SetItem(posix_putenv_garbage, + PyTuple_GET_ITEM(args, 0), newstr)) { + /* really not much we can do; just leak */ + PyErr_Clear(); + } + else { + Py_DECREF(newstr); + } #if defined(PYOS_OS2) } #endif #ifndef MS_WINDOWS - Py_DECREF(os1); - Py_DECREF(os2); + Py_DECREF(os1); + Py_DECREF(os2); #endif - Py_INCREF(Py_None); - return Py_None; + Py_INCREF(Py_None); + return Py_None; } #endif /* putenv */ @@ -5398,26 +5399,26 @@ static PyObject * posix_unsetenv(PyObject *self, PyObject *args) { - char *s1; + char *s1; - if (!PyArg_ParseTuple(args, "s:unsetenv", &s1)) - return NULL; + if (!PyArg_ParseTuple(args, "s:unsetenv", &s1)) + return NULL; - unsetenv(s1); + unsetenv(s1); - /* Remove the key from posix_putenv_garbage; - * this will cause it to be collected. This has to - * happen after the real unsetenv() call because the - * old value was still accessible until then. - */ - if (PyDict_DelItem(posix_putenv_garbage, - PyTuple_GET_ITEM(args, 0))) { - /* really not much we can do; just leak */ - PyErr_Clear(); - } + /* Remove the key from posix_putenv_garbage; + * this will cause it to be collected. This has to + * happen after the real unsetenv() call because the + * old value was still accessible until then. + */ + if (PyDict_DelItem(posix_putenv_garbage, + PyTuple_GET_ITEM(args, 0))) { + /* really not much we can do; just leak */ + PyErr_Clear(); + } - Py_INCREF(Py_None); - return Py_None; + Py_INCREF(Py_None); + return Py_None; } #endif /* unsetenv */ @@ -5428,17 +5429,17 @@ static PyObject * posix_strerror(PyObject *self, PyObject *args) { - int code; - char *message; - if (!PyArg_ParseTuple(args, "i:strerror", &code)) - return NULL; - message = strerror(code); - if (message == NULL) { - PyErr_SetString(PyExc_ValueError, - "strerror() argument out of range"); - return NULL; - } - return PyUnicode_FromString(message); + int code; + char *message; + if (!PyArg_ParseTuple(args, "i:strerror", &code)) + return NULL; + message = strerror(code); + if (message == NULL) { + PyErr_SetString(PyExc_ValueError, + "strerror() argument out of range"); + return NULL; + } + return PyUnicode_FromString(message); } @@ -5452,13 +5453,13 @@ static PyObject * posix_WCOREDUMP(PyObject *self, PyObject *args) { - WAIT_TYPE status; - WAIT_STATUS_INT(status) = 0; + WAIT_TYPE status; + WAIT_STATUS_INT(status) = 0; - if (!PyArg_ParseTuple(args, "i:WCOREDUMP", &WAIT_STATUS_INT(status))) - return NULL; + if (!PyArg_ParseTuple(args, "i:WCOREDUMP", &WAIT_STATUS_INT(status))) + return NULL; - return PyBool_FromLong(WCOREDUMP(status)); + return PyBool_FromLong(WCOREDUMP(status)); } #endif /* WCOREDUMP */ @@ -5471,13 +5472,13 @@ static PyObject * posix_WIFCONTINUED(PyObject *self, PyObject *args) { - WAIT_TYPE status; - WAIT_STATUS_INT(status) = 0; + WAIT_TYPE status; + WAIT_STATUS_INT(status) = 0; - if (!PyArg_ParseTuple(args, "i:WCONTINUED", &WAIT_STATUS_INT(status))) - return NULL; + if (!PyArg_ParseTuple(args, "i:WCONTINUED", &WAIT_STATUS_INT(status))) + return NULL; - return PyBool_FromLong(WIFCONTINUED(status)); + return PyBool_FromLong(WIFCONTINUED(status)); } #endif /* WIFCONTINUED */ @@ -5489,13 +5490,13 @@ static PyObject * posix_WIFSTOPPED(PyObject *self, PyObject *args) { - WAIT_TYPE status; - WAIT_STATUS_INT(status) = 0; + WAIT_TYPE status; + WAIT_STATUS_INT(status) = 0; - if (!PyArg_ParseTuple(args, "i:WIFSTOPPED", &WAIT_STATUS_INT(status))) - return NULL; + if (!PyArg_ParseTuple(args, "i:WIFSTOPPED", &WAIT_STATUS_INT(status))) + return NULL; - return PyBool_FromLong(WIFSTOPPED(status)); + return PyBool_FromLong(WIFSTOPPED(status)); } #endif /* WIFSTOPPED */ @@ -5507,13 +5508,13 @@ static PyObject * posix_WIFSIGNALED(PyObject *self, PyObject *args) { - WAIT_TYPE status; - WAIT_STATUS_INT(status) = 0; + WAIT_TYPE status; + WAIT_STATUS_INT(status) = 0; - if (!PyArg_ParseTuple(args, "i:WIFSIGNALED", &WAIT_STATUS_INT(status))) - return NULL; + if (!PyArg_ParseTuple(args, "i:WIFSIGNALED", &WAIT_STATUS_INT(status))) + return NULL; - return PyBool_FromLong(WIFSIGNALED(status)); + return PyBool_FromLong(WIFSIGNALED(status)); } #endif /* WIFSIGNALED */ @@ -5526,13 +5527,13 @@ static PyObject * posix_WIFEXITED(PyObject *self, PyObject *args) { - WAIT_TYPE status; - WAIT_STATUS_INT(status) = 0; + WAIT_TYPE status; + WAIT_STATUS_INT(status) = 0; - if (!PyArg_ParseTuple(args, "i:WIFEXITED", &WAIT_STATUS_INT(status))) - return NULL; + if (!PyArg_ParseTuple(args, "i:WIFEXITED", &WAIT_STATUS_INT(status))) + return NULL; - return PyBool_FromLong(WIFEXITED(status)); + return PyBool_FromLong(WIFEXITED(status)); } #endif /* WIFEXITED */ @@ -5544,13 +5545,13 @@ static PyObject * posix_WEXITSTATUS(PyObject *self, PyObject *args) { - WAIT_TYPE status; - WAIT_STATUS_INT(status) = 0; + WAIT_TYPE status; + WAIT_STATUS_INT(status) = 0; - if (!PyArg_ParseTuple(args, "i:WEXITSTATUS", &WAIT_STATUS_INT(status))) - return NULL; + if (!PyArg_ParseTuple(args, "i:WEXITSTATUS", &WAIT_STATUS_INT(status))) + return NULL; - return Py_BuildValue("i", WEXITSTATUS(status)); + return Py_BuildValue("i", WEXITSTATUS(status)); } #endif /* WEXITSTATUS */ @@ -5563,13 +5564,13 @@ static PyObject * posix_WTERMSIG(PyObject *self, PyObject *args) { - WAIT_TYPE status; - WAIT_STATUS_INT(status) = 0; + WAIT_TYPE status; + WAIT_STATUS_INT(status) = 0; - if (!PyArg_ParseTuple(args, "i:WTERMSIG", &WAIT_STATUS_INT(status))) - return NULL; + if (!PyArg_ParseTuple(args, "i:WTERMSIG", &WAIT_STATUS_INT(status))) + return NULL; - return Py_BuildValue("i", WTERMSIG(status)); + return Py_BuildValue("i", WTERMSIG(status)); } #endif /* WTERMSIG */ @@ -5582,13 +5583,13 @@ static PyObject * posix_WSTOPSIG(PyObject *self, PyObject *args) { - WAIT_TYPE status; - WAIT_STATUS_INT(status) = 0; + WAIT_TYPE status; + WAIT_STATUS_INT(status) = 0; - if (!PyArg_ParseTuple(args, "i:WSTOPSIG", &WAIT_STATUS_INT(status))) - return NULL; + if (!PyArg_ParseTuple(args, "i:WSTOPSIG", &WAIT_STATUS_INT(status))) + return NULL; - return Py_BuildValue("i", WSTOPSIG(status)); + return Py_BuildValue("i", WSTOPSIG(status)); } #endif /* WSTOPSIG */ @@ -5605,41 +5606,41 @@ static PyObject* _pystatvfs_fromstructstatvfs(struct statvfs st) { - PyObject *v = PyStructSequence_New(&StatVFSResultType); - if (v == NULL) - return NULL; + PyObject *v = PyStructSequence_New(&StatVFSResultType); + if (v == NULL) + return NULL; #if !defined(HAVE_LARGEFILE_SUPPORT) - PyStructSequence_SET_ITEM(v, 0, PyLong_FromLong((long) st.f_bsize)); - PyStructSequence_SET_ITEM(v, 1, PyLong_FromLong((long) st.f_frsize)); - PyStructSequence_SET_ITEM(v, 2, PyLong_FromLong((long) st.f_blocks)); - PyStructSequence_SET_ITEM(v, 3, PyLong_FromLong((long) st.f_bfree)); - PyStructSequence_SET_ITEM(v, 4, PyLong_FromLong((long) st.f_bavail)); - PyStructSequence_SET_ITEM(v, 5, PyLong_FromLong((long) st.f_files)); - PyStructSequence_SET_ITEM(v, 6, PyLong_FromLong((long) st.f_ffree)); - PyStructSequence_SET_ITEM(v, 7, PyLong_FromLong((long) st.f_favail)); - PyStructSequence_SET_ITEM(v, 8, PyLong_FromLong((long) st.f_flag)); - PyStructSequence_SET_ITEM(v, 9, PyLong_FromLong((long) st.f_namemax)); -#else - PyStructSequence_SET_ITEM(v, 0, PyLong_FromLong((long) st.f_bsize)); - PyStructSequence_SET_ITEM(v, 1, PyLong_FromLong((long) st.f_frsize)); - PyStructSequence_SET_ITEM(v, 2, - PyLong_FromLongLong((PY_LONG_LONG) st.f_blocks)); - PyStructSequence_SET_ITEM(v, 3, - PyLong_FromLongLong((PY_LONG_LONG) st.f_bfree)); - PyStructSequence_SET_ITEM(v, 4, - PyLong_FromLongLong((PY_LONG_LONG) st.f_bavail)); - PyStructSequence_SET_ITEM(v, 5, - PyLong_FromLongLong((PY_LONG_LONG) st.f_files)); - PyStructSequence_SET_ITEM(v, 6, - PyLong_FromLongLong((PY_LONG_LONG) st.f_ffree)); - PyStructSequence_SET_ITEM(v, 7, - PyLong_FromLongLong((PY_LONG_LONG) st.f_favail)); - PyStructSequence_SET_ITEM(v, 8, PyLong_FromLong((long) st.f_flag)); - PyStructSequence_SET_ITEM(v, 9, PyLong_FromLong((long) st.f_namemax)); + PyStructSequence_SET_ITEM(v, 0, PyLong_FromLong((long) st.f_bsize)); + PyStructSequence_SET_ITEM(v, 1, PyLong_FromLong((long) st.f_frsize)); + PyStructSequence_SET_ITEM(v, 2, PyLong_FromLong((long) st.f_blocks)); + PyStructSequence_SET_ITEM(v, 3, PyLong_FromLong((long) st.f_bfree)); + PyStructSequence_SET_ITEM(v, 4, PyLong_FromLong((long) st.f_bavail)); + PyStructSequence_SET_ITEM(v, 5, PyLong_FromLong((long) st.f_files)); + PyStructSequence_SET_ITEM(v, 6, PyLong_FromLong((long) st.f_ffree)); + PyStructSequence_SET_ITEM(v, 7, PyLong_FromLong((long) st.f_favail)); + PyStructSequence_SET_ITEM(v, 8, PyLong_FromLong((long) st.f_flag)); + PyStructSequence_SET_ITEM(v, 9, PyLong_FromLong((long) st.f_namemax)); +#else + PyStructSequence_SET_ITEM(v, 0, PyLong_FromLong((long) st.f_bsize)); + PyStructSequence_SET_ITEM(v, 1, PyLong_FromLong((long) st.f_frsize)); + PyStructSequence_SET_ITEM(v, 2, + PyLong_FromLongLong((PY_LONG_LONG) st.f_blocks)); + PyStructSequence_SET_ITEM(v, 3, + PyLong_FromLongLong((PY_LONG_LONG) st.f_bfree)); + PyStructSequence_SET_ITEM(v, 4, + PyLong_FromLongLong((PY_LONG_LONG) st.f_bavail)); + PyStructSequence_SET_ITEM(v, 5, + PyLong_FromLongLong((PY_LONG_LONG) st.f_files)); + PyStructSequence_SET_ITEM(v, 6, + PyLong_FromLongLong((PY_LONG_LONG) st.f_ffree)); + PyStructSequence_SET_ITEM(v, 7, + PyLong_FromLongLong((PY_LONG_LONG) st.f_favail)); + PyStructSequence_SET_ITEM(v, 8, PyLong_FromLong((long) st.f_flag)); + PyStructSequence_SET_ITEM(v, 9, PyLong_FromLong((long) st.f_namemax)); #endif - return v; + return v; } PyDoc_STRVAR(posix_fstatvfs__doc__, @@ -5649,18 +5650,18 @@ static PyObject * posix_fstatvfs(PyObject *self, PyObject *args) { - int fd, res; - struct statvfs st; + int fd, res; + struct statvfs st; - if (!PyArg_ParseTuple(args, "i:fstatvfs", &fd)) - return NULL; - Py_BEGIN_ALLOW_THREADS - res = fstatvfs(fd, &st); - Py_END_ALLOW_THREADS - if (res != 0) - return posix_error(); + if (!PyArg_ParseTuple(args, "i:fstatvfs", &fd)) + return NULL; + Py_BEGIN_ALLOW_THREADS + res = fstatvfs(fd, &st); + Py_END_ALLOW_THREADS + if (res != 0) + return posix_error(); - return _pystatvfs_fromstructstatvfs(st); + return _pystatvfs_fromstructstatvfs(st); } #endif /* HAVE_FSTATVFS && HAVE_SYS_STATVFS_H */ @@ -5675,18 +5676,18 @@ static PyObject * posix_statvfs(PyObject *self, PyObject *args) { - char *path; - int res; - struct statvfs st; - if (!PyArg_ParseTuple(args, "s:statvfs", &path)) - return NULL; - Py_BEGIN_ALLOW_THREADS - res = statvfs(path, &st); - Py_END_ALLOW_THREADS - if (res != 0) - return posix_error_with_filename(path); + char *path; + int res; + struct statvfs st; + if (!PyArg_ParseTuple(args, "s:statvfs", &path)) + return NULL; + Py_BEGIN_ALLOW_THREADS + res = statvfs(path, &st); + Py_END_ALLOW_THREADS + if (res != 0) + return posix_error_with_filename(path); - return _pystatvfs_fromstructstatvfs(st); + return _pystatvfs_fromstructstatvfs(st); } #endif /* HAVE_STATVFS */ @@ -5711,38 +5712,38 @@ size_t tablesize) { if (PyLong_Check(arg)) { - *valuep = PyLong_AS_LONG(arg); - return 1; + *valuep = PyLong_AS_LONG(arg); + return 1; } else { - /* look up the value in the table using a binary search */ - size_t lo = 0; - size_t mid; - size_t hi = tablesize; - int cmp; - const char *confname; - if (!PyUnicode_Check(arg)) { - PyErr_SetString(PyExc_TypeError, - "configuration names must be strings or integers"); - return 0; - } - confname = _PyUnicode_AsString(arg); - if (confname == NULL) - return 0; - while (lo < hi) { - mid = (lo + hi) / 2; - cmp = strcmp(confname, table[mid].name); - if (cmp < 0) - hi = mid; - else if (cmp > 0) - lo = mid + 1; - else { - *valuep = table[mid].value; - return 1; - } - } - PyErr_SetString(PyExc_ValueError, "unrecognized configuration name"); + /* look up the value in the table using a binary search */ + size_t lo = 0; + size_t mid; + size_t hi = tablesize; + int cmp; + const char *confname; + if (!PyUnicode_Check(arg)) { + PyErr_SetString(PyExc_TypeError, + "configuration names must be strings or integers"); + return 0; + } + confname = _PyUnicode_AsString(arg); + if (confname == NULL) return 0; + while (lo < hi) { + mid = (lo + hi) / 2; + cmp = strcmp(confname, table[mid].name); + if (cmp < 0) + hi = mid; + else if (cmp > 0) + lo = mid + 1; + else { + *valuep = table[mid].value; + return 1; + } + } + PyErr_SetString(PyExc_ValueError, "unrecognized configuration name"); + return 0; } } @@ -5750,55 +5751,55 @@ #if defined(HAVE_FPATHCONF) || defined(HAVE_PATHCONF) static struct constdef posix_constants_pathconf[] = { #ifdef _PC_ABI_AIO_XFER_MAX - {"PC_ABI_AIO_XFER_MAX", _PC_ABI_AIO_XFER_MAX}, + {"PC_ABI_AIO_XFER_MAX", _PC_ABI_AIO_XFER_MAX}, #endif #ifdef _PC_ABI_ASYNC_IO - {"PC_ABI_ASYNC_IO", _PC_ABI_ASYNC_IO}, + {"PC_ABI_ASYNC_IO", _PC_ABI_ASYNC_IO}, #endif #ifdef _PC_ASYNC_IO - {"PC_ASYNC_IO", _PC_ASYNC_IO}, + {"PC_ASYNC_IO", _PC_ASYNC_IO}, #endif #ifdef _PC_CHOWN_RESTRICTED - {"PC_CHOWN_RESTRICTED", _PC_CHOWN_RESTRICTED}, + {"PC_CHOWN_RESTRICTED", _PC_CHOWN_RESTRICTED}, #endif #ifdef _PC_FILESIZEBITS - {"PC_FILESIZEBITS", _PC_FILESIZEBITS}, + {"PC_FILESIZEBITS", _PC_FILESIZEBITS}, #endif #ifdef _PC_LAST - {"PC_LAST", _PC_LAST}, + {"PC_LAST", _PC_LAST}, #endif #ifdef _PC_LINK_MAX - {"PC_LINK_MAX", _PC_LINK_MAX}, + {"PC_LINK_MAX", _PC_LINK_MAX}, #endif #ifdef _PC_MAX_CANON - {"PC_MAX_CANON", _PC_MAX_CANON}, + {"PC_MAX_CANON", _PC_MAX_CANON}, #endif #ifdef _PC_MAX_INPUT - {"PC_MAX_INPUT", _PC_MAX_INPUT}, + {"PC_MAX_INPUT", _PC_MAX_INPUT}, #endif #ifdef _PC_NAME_MAX - {"PC_NAME_MAX", _PC_NAME_MAX}, + {"PC_NAME_MAX", _PC_NAME_MAX}, #endif #ifdef _PC_NO_TRUNC - {"PC_NO_TRUNC", _PC_NO_TRUNC}, + {"PC_NO_TRUNC", _PC_NO_TRUNC}, #endif #ifdef _PC_PATH_MAX - {"PC_PATH_MAX", _PC_PATH_MAX}, + {"PC_PATH_MAX", _PC_PATH_MAX}, #endif #ifdef _PC_PIPE_BUF - {"PC_PIPE_BUF", _PC_PIPE_BUF}, + {"PC_PIPE_BUF", _PC_PIPE_BUF}, #endif #ifdef _PC_PRIO_IO - {"PC_PRIO_IO", _PC_PRIO_IO}, + {"PC_PRIO_IO", _PC_PRIO_IO}, #endif #ifdef _PC_SOCK_MAXBUF - {"PC_SOCK_MAXBUF", _PC_SOCK_MAXBUF}, + {"PC_SOCK_MAXBUF", _PC_SOCK_MAXBUF}, #endif #ifdef _PC_SYNC_IO - {"PC_SYNC_IO", _PC_SYNC_IO}, + {"PC_SYNC_IO", _PC_SYNC_IO}, #endif #ifdef _PC_VDISABLE - {"PC_VDISABLE", _PC_VDISABLE}, + {"PC_VDISABLE", _PC_VDISABLE}, #endif }; @@ -5825,14 +5826,14 @@ if (PyArg_ParseTuple(args, "iO&:fpathconf", &fd, conv_path_confname, &name)) { - long limit; + long limit; - errno = 0; - limit = fpathconf(fd, name); - if (limit == -1 && errno != 0) - posix_error(); - else - result = PyLong_FromLong(limit); + errno = 0; + limit = fpathconf(fd, name); + if (limit == -1 && errno != 0) + posix_error(); + else + result = PyLong_FromLong(limit); } return result; } @@ -5854,19 +5855,19 @@ if (PyArg_ParseTuple(args, "sO&:pathconf", &path, conv_path_confname, &name)) { - long limit; + long limit; - errno = 0; - limit = pathconf(path, name); - if (limit == -1 && errno != 0) { - if (errno == EINVAL) - /* could be a path or name problem */ - posix_error(); - else - posix_error_with_filename(path); - } + errno = 0; + limit = pathconf(path, name); + if (limit == -1 && errno != 0) { + if (errno == EINVAL) + /* could be a path or name problem */ + posix_error(); else - result = PyLong_FromLong(limit); + posix_error_with_filename(path); + } + else + result = PyLong_FromLong(limit); } return result; } @@ -5875,154 +5876,154 @@ #ifdef HAVE_CONFSTR static struct constdef posix_constants_confstr[] = { #ifdef _CS_ARCHITECTURE - {"CS_ARCHITECTURE", _CS_ARCHITECTURE}, + {"CS_ARCHITECTURE", _CS_ARCHITECTURE}, #endif #ifdef _CS_GNU_LIBC_VERSION - {"CS_GNU_LIBC_VERSION", _CS_GNU_LIBC_VERSION}, + {"CS_GNU_LIBC_VERSION", _CS_GNU_LIBC_VERSION}, #endif #ifdef _CS_GNU_LIBPTHREAD_VERSION - {"CS_GNU_LIBPTHREAD_VERSION", _CS_GNU_LIBPTHREAD_VERSION}, + {"CS_GNU_LIBPTHREAD_VERSION", _CS_GNU_LIBPTHREAD_VERSION}, #endif #ifdef _CS_HOSTNAME - {"CS_HOSTNAME", _CS_HOSTNAME}, + {"CS_HOSTNAME", _CS_HOSTNAME}, #endif #ifdef _CS_HW_PROVIDER - {"CS_HW_PROVIDER", _CS_HW_PROVIDER}, + {"CS_HW_PROVIDER", _CS_HW_PROVIDER}, #endif #ifdef _CS_HW_SERIAL - {"CS_HW_SERIAL", _CS_HW_SERIAL}, + {"CS_HW_SERIAL", _CS_HW_SERIAL}, #endif #ifdef _CS_INITTAB_NAME - {"CS_INITTAB_NAME", _CS_INITTAB_NAME}, + {"CS_INITTAB_NAME", _CS_INITTAB_NAME}, #endif #ifdef _CS_LFS64_CFLAGS - {"CS_LFS64_CFLAGS", _CS_LFS64_CFLAGS}, + {"CS_LFS64_CFLAGS", _CS_LFS64_CFLAGS}, #endif #ifdef _CS_LFS64_LDFLAGS - {"CS_LFS64_LDFLAGS", _CS_LFS64_LDFLAGS}, + {"CS_LFS64_LDFLAGS", _CS_LFS64_LDFLAGS}, #endif #ifdef _CS_LFS64_LIBS - {"CS_LFS64_LIBS", _CS_LFS64_LIBS}, + {"CS_LFS64_LIBS", _CS_LFS64_LIBS}, #endif #ifdef _CS_LFS64_LINTFLAGS - {"CS_LFS64_LINTFLAGS", _CS_LFS64_LINTFLAGS}, + {"CS_LFS64_LINTFLAGS", _CS_LFS64_LINTFLAGS}, #endif #ifdef _CS_LFS_CFLAGS - {"CS_LFS_CFLAGS", _CS_LFS_CFLAGS}, + {"CS_LFS_CFLAGS", _CS_LFS_CFLAGS}, #endif #ifdef _CS_LFS_LDFLAGS - {"CS_LFS_LDFLAGS", _CS_LFS_LDFLAGS}, + {"CS_LFS_LDFLAGS", _CS_LFS_LDFLAGS}, #endif #ifdef _CS_LFS_LIBS - {"CS_LFS_LIBS", _CS_LFS_LIBS}, + {"CS_LFS_LIBS", _CS_LFS_LIBS}, #endif #ifdef _CS_LFS_LINTFLAGS - {"CS_LFS_LINTFLAGS", _CS_LFS_LINTFLAGS}, + {"CS_LFS_LINTFLAGS", _CS_LFS_LINTFLAGS}, #endif #ifdef _CS_MACHINE - {"CS_MACHINE", _CS_MACHINE}, + {"CS_MACHINE", _CS_MACHINE}, #endif #ifdef _CS_PATH - {"CS_PATH", _CS_PATH}, + {"CS_PATH", _CS_PATH}, #endif #ifdef _CS_RELEASE - {"CS_RELEASE", _CS_RELEASE}, + {"CS_RELEASE", _CS_RELEASE}, #endif #ifdef _CS_SRPC_DOMAIN - {"CS_SRPC_DOMAIN", _CS_SRPC_DOMAIN}, + {"CS_SRPC_DOMAIN", _CS_SRPC_DOMAIN}, #endif #ifdef _CS_SYSNAME - {"CS_SYSNAME", _CS_SYSNAME}, + {"CS_SYSNAME", _CS_SYSNAME}, #endif #ifdef _CS_VERSION - {"CS_VERSION", _CS_VERSION}, + {"CS_VERSION", _CS_VERSION}, #endif #ifdef _CS_XBS5_ILP32_OFF32_CFLAGS - {"CS_XBS5_ILP32_OFF32_CFLAGS", _CS_XBS5_ILP32_OFF32_CFLAGS}, + {"CS_XBS5_ILP32_OFF32_CFLAGS", _CS_XBS5_ILP32_OFF32_CFLAGS}, #endif #ifdef _CS_XBS5_ILP32_OFF32_LDFLAGS - {"CS_XBS5_ILP32_OFF32_LDFLAGS", _CS_XBS5_ILP32_OFF32_LDFLAGS}, + {"CS_XBS5_ILP32_OFF32_LDFLAGS", _CS_XBS5_ILP32_OFF32_LDFLAGS}, #endif #ifdef _CS_XBS5_ILP32_OFF32_LIBS - {"CS_XBS5_ILP32_OFF32_LIBS", _CS_XBS5_ILP32_OFF32_LIBS}, + {"CS_XBS5_ILP32_OFF32_LIBS", _CS_XBS5_ILP32_OFF32_LIBS}, #endif #ifdef _CS_XBS5_ILP32_OFF32_LINTFLAGS - {"CS_XBS5_ILP32_OFF32_LINTFLAGS", _CS_XBS5_ILP32_OFF32_LINTFLAGS}, + {"CS_XBS5_ILP32_OFF32_LINTFLAGS", _CS_XBS5_ILP32_OFF32_LINTFLAGS}, #endif #ifdef _CS_XBS5_ILP32_OFFBIG_CFLAGS - {"CS_XBS5_ILP32_OFFBIG_CFLAGS", _CS_XBS5_ILP32_OFFBIG_CFLAGS}, + {"CS_XBS5_ILP32_OFFBIG_CFLAGS", _CS_XBS5_ILP32_OFFBIG_CFLAGS}, #endif #ifdef _CS_XBS5_ILP32_OFFBIG_LDFLAGS - {"CS_XBS5_ILP32_OFFBIG_LDFLAGS", _CS_XBS5_ILP32_OFFBIG_LDFLAGS}, + {"CS_XBS5_ILP32_OFFBIG_LDFLAGS", _CS_XBS5_ILP32_OFFBIG_LDFLAGS}, #endif #ifdef _CS_XBS5_ILP32_OFFBIG_LIBS - {"CS_XBS5_ILP32_OFFBIG_LIBS", _CS_XBS5_ILP32_OFFBIG_LIBS}, + {"CS_XBS5_ILP32_OFFBIG_LIBS", _CS_XBS5_ILP32_OFFBIG_LIBS}, #endif #ifdef _CS_XBS5_ILP32_OFFBIG_LINTFLAGS - {"CS_XBS5_ILP32_OFFBIG_LINTFLAGS", _CS_XBS5_ILP32_OFFBIG_LINTFLAGS}, + {"CS_XBS5_ILP32_OFFBIG_LINTFLAGS", _CS_XBS5_ILP32_OFFBIG_LINTFLAGS}, #endif #ifdef _CS_XBS5_LP64_OFF64_CFLAGS - {"CS_XBS5_LP64_OFF64_CFLAGS", _CS_XBS5_LP64_OFF64_CFLAGS}, + {"CS_XBS5_LP64_OFF64_CFLAGS", _CS_XBS5_LP64_OFF64_CFLAGS}, #endif #ifdef _CS_XBS5_LP64_OFF64_LDFLAGS - {"CS_XBS5_LP64_OFF64_LDFLAGS", _CS_XBS5_LP64_OFF64_LDFLAGS}, + {"CS_XBS5_LP64_OFF64_LDFLAGS", _CS_XBS5_LP64_OFF64_LDFLAGS}, #endif #ifdef _CS_XBS5_LP64_OFF64_LIBS - {"CS_XBS5_LP64_OFF64_LIBS", _CS_XBS5_LP64_OFF64_LIBS}, + {"CS_XBS5_LP64_OFF64_LIBS", _CS_XBS5_LP64_OFF64_LIBS}, #endif #ifdef _CS_XBS5_LP64_OFF64_LINTFLAGS - {"CS_XBS5_LP64_OFF64_LINTFLAGS", _CS_XBS5_LP64_OFF64_LINTFLAGS}, + {"CS_XBS5_LP64_OFF64_LINTFLAGS", _CS_XBS5_LP64_OFF64_LINTFLAGS}, #endif #ifdef _CS_XBS5_LPBIG_OFFBIG_CFLAGS - {"CS_XBS5_LPBIG_OFFBIG_CFLAGS", _CS_XBS5_LPBIG_OFFBIG_CFLAGS}, + {"CS_XBS5_LPBIG_OFFBIG_CFLAGS", _CS_XBS5_LPBIG_OFFBIG_CFLAGS}, #endif #ifdef _CS_XBS5_LPBIG_OFFBIG_LDFLAGS - {"CS_XBS5_LPBIG_OFFBIG_LDFLAGS", _CS_XBS5_LPBIG_OFFBIG_LDFLAGS}, + {"CS_XBS5_LPBIG_OFFBIG_LDFLAGS", _CS_XBS5_LPBIG_OFFBIG_LDFLAGS}, #endif #ifdef _CS_XBS5_LPBIG_OFFBIG_LIBS - {"CS_XBS5_LPBIG_OFFBIG_LIBS", _CS_XBS5_LPBIG_OFFBIG_LIBS}, + {"CS_XBS5_LPBIG_OFFBIG_LIBS", _CS_XBS5_LPBIG_OFFBIG_LIBS}, #endif #ifdef _CS_XBS5_LPBIG_OFFBIG_LINTFLAGS - {"CS_XBS5_LPBIG_OFFBIG_LINTFLAGS", _CS_XBS5_LPBIG_OFFBIG_LINTFLAGS}, + {"CS_XBS5_LPBIG_OFFBIG_LINTFLAGS", _CS_XBS5_LPBIG_OFFBIG_LINTFLAGS}, #endif #ifdef _MIPS_CS_AVAIL_PROCESSORS - {"MIPS_CS_AVAIL_PROCESSORS", _MIPS_CS_AVAIL_PROCESSORS}, + {"MIPS_CS_AVAIL_PROCESSORS", _MIPS_CS_AVAIL_PROCESSORS}, #endif #ifdef _MIPS_CS_BASE - {"MIPS_CS_BASE", _MIPS_CS_BASE}, + {"MIPS_CS_BASE", _MIPS_CS_BASE}, #endif #ifdef _MIPS_CS_HOSTID - {"MIPS_CS_HOSTID", _MIPS_CS_HOSTID}, + {"MIPS_CS_HOSTID", _MIPS_CS_HOSTID}, #endif #ifdef _MIPS_CS_HW_NAME - {"MIPS_CS_HW_NAME", _MIPS_CS_HW_NAME}, + {"MIPS_CS_HW_NAME", _MIPS_CS_HW_NAME}, #endif #ifdef _MIPS_CS_NUM_PROCESSORS - {"MIPS_CS_NUM_PROCESSORS", _MIPS_CS_NUM_PROCESSORS}, + {"MIPS_CS_NUM_PROCESSORS", _MIPS_CS_NUM_PROCESSORS}, #endif #ifdef _MIPS_CS_OSREL_MAJ - {"MIPS_CS_OSREL_MAJ", _MIPS_CS_OSREL_MAJ}, + {"MIPS_CS_OSREL_MAJ", _MIPS_CS_OSREL_MAJ}, #endif #ifdef _MIPS_CS_OSREL_MIN - {"MIPS_CS_OSREL_MIN", _MIPS_CS_OSREL_MIN}, + {"MIPS_CS_OSREL_MIN", _MIPS_CS_OSREL_MIN}, #endif #ifdef _MIPS_CS_OSREL_PATCH - {"MIPS_CS_OSREL_PATCH", _MIPS_CS_OSREL_PATCH}, + {"MIPS_CS_OSREL_PATCH", _MIPS_CS_OSREL_PATCH}, #endif #ifdef _MIPS_CS_OS_NAME - {"MIPS_CS_OS_NAME", _MIPS_CS_OS_NAME}, + {"MIPS_CS_OS_NAME", _MIPS_CS_OS_NAME}, #endif #ifdef _MIPS_CS_OS_PROVIDER - {"MIPS_CS_OS_PROVIDER", _MIPS_CS_OS_PROVIDER}, + {"MIPS_CS_OS_PROVIDER", _MIPS_CS_OS_PROVIDER}, #endif #ifdef _MIPS_CS_PROCESSORS - {"MIPS_CS_PROCESSORS", _MIPS_CS_PROCESSORS}, + {"MIPS_CS_PROCESSORS", _MIPS_CS_PROCESSORS}, #endif #ifdef _MIPS_CS_SERIAL - {"MIPS_CS_SERIAL", _MIPS_CS_SERIAL}, + {"MIPS_CS_SERIAL", _MIPS_CS_SERIAL}, #endif #ifdef _MIPS_CS_VENDOR - {"MIPS_CS_VENDOR", _MIPS_CS_VENDOR}, + {"MIPS_CS_VENDOR", _MIPS_CS_VENDOR}, #endif }; @@ -6046,21 +6047,21 @@ char buffer[256]; if (PyArg_ParseTuple(args, "O&:confstr", conv_confstr_confname, &name)) { - int len; + int len; errno = 0; - len = confstr(name, buffer, sizeof(buffer)); - if (len == 0) { - if (errno) { - posix_error(); - } - else { - result = Py_None; - Py_INCREF(Py_None); - } + len = confstr(name, buffer, sizeof(buffer)); + if (len == 0) { + if (errno) { + posix_error(); + } + else { + result = Py_None; + Py_INCREF(Py_None); + } } else { - if ((unsigned int)len >= sizeof(buffer)) { + if ((unsigned int)len >= sizeof(buffer)) { result = PyUnicode_FromStringAndSize(NULL, len-1); if (result != NULL) confstr(name, _PyUnicode_AsString(result), len); @@ -6077,496 +6078,496 @@ #ifdef HAVE_SYSCONF static struct constdef posix_constants_sysconf[] = { #ifdef _SC_2_CHAR_TERM - {"SC_2_CHAR_TERM", _SC_2_CHAR_TERM}, + {"SC_2_CHAR_TERM", _SC_2_CHAR_TERM}, #endif #ifdef _SC_2_C_BIND - {"SC_2_C_BIND", _SC_2_C_BIND}, + {"SC_2_C_BIND", _SC_2_C_BIND}, #endif #ifdef _SC_2_C_DEV - {"SC_2_C_DEV", _SC_2_C_DEV}, + {"SC_2_C_DEV", _SC_2_C_DEV}, #endif #ifdef _SC_2_C_VERSION - {"SC_2_C_VERSION", _SC_2_C_VERSION}, + {"SC_2_C_VERSION", _SC_2_C_VERSION}, #endif #ifdef _SC_2_FORT_DEV - {"SC_2_FORT_DEV", _SC_2_FORT_DEV}, + {"SC_2_FORT_DEV", _SC_2_FORT_DEV}, #endif #ifdef _SC_2_FORT_RUN - {"SC_2_FORT_RUN", _SC_2_FORT_RUN}, + {"SC_2_FORT_RUN", _SC_2_FORT_RUN}, #endif #ifdef _SC_2_LOCALEDEF - {"SC_2_LOCALEDEF", _SC_2_LOCALEDEF}, + {"SC_2_LOCALEDEF", _SC_2_LOCALEDEF}, #endif #ifdef _SC_2_SW_DEV - {"SC_2_SW_DEV", _SC_2_SW_DEV}, + {"SC_2_SW_DEV", _SC_2_SW_DEV}, #endif #ifdef _SC_2_UPE - {"SC_2_UPE", _SC_2_UPE}, + {"SC_2_UPE", _SC_2_UPE}, #endif #ifdef _SC_2_VERSION - {"SC_2_VERSION", _SC_2_VERSION}, + {"SC_2_VERSION", _SC_2_VERSION}, #endif #ifdef _SC_ABI_ASYNCHRONOUS_IO - {"SC_ABI_ASYNCHRONOUS_IO", _SC_ABI_ASYNCHRONOUS_IO}, + {"SC_ABI_ASYNCHRONOUS_IO", _SC_ABI_ASYNCHRONOUS_IO}, #endif #ifdef _SC_ACL - {"SC_ACL", _SC_ACL}, + {"SC_ACL", _SC_ACL}, #endif #ifdef _SC_AIO_LISTIO_MAX - {"SC_AIO_LISTIO_MAX", _SC_AIO_LISTIO_MAX}, + {"SC_AIO_LISTIO_MAX", _SC_AIO_LISTIO_MAX}, #endif #ifdef _SC_AIO_MAX - {"SC_AIO_MAX", _SC_AIO_MAX}, + {"SC_AIO_MAX", _SC_AIO_MAX}, #endif #ifdef _SC_AIO_PRIO_DELTA_MAX - {"SC_AIO_PRIO_DELTA_MAX", _SC_AIO_PRIO_DELTA_MAX}, + {"SC_AIO_PRIO_DELTA_MAX", _SC_AIO_PRIO_DELTA_MAX}, #endif #ifdef _SC_ARG_MAX - {"SC_ARG_MAX", _SC_ARG_MAX}, + {"SC_ARG_MAX", _SC_ARG_MAX}, #endif #ifdef _SC_ASYNCHRONOUS_IO - {"SC_ASYNCHRONOUS_IO", _SC_ASYNCHRONOUS_IO}, + {"SC_ASYNCHRONOUS_IO", _SC_ASYNCHRONOUS_IO}, #endif #ifdef _SC_ATEXIT_MAX - {"SC_ATEXIT_MAX", _SC_ATEXIT_MAX}, + {"SC_ATEXIT_MAX", _SC_ATEXIT_MAX}, #endif #ifdef _SC_AUDIT - {"SC_AUDIT", _SC_AUDIT}, + {"SC_AUDIT", _SC_AUDIT}, #endif #ifdef _SC_AVPHYS_PAGES - {"SC_AVPHYS_PAGES", _SC_AVPHYS_PAGES}, + {"SC_AVPHYS_PAGES", _SC_AVPHYS_PAGES}, #endif #ifdef _SC_BC_BASE_MAX - {"SC_BC_BASE_MAX", _SC_BC_BASE_MAX}, + {"SC_BC_BASE_MAX", _SC_BC_BASE_MAX}, #endif #ifdef _SC_BC_DIM_MAX - {"SC_BC_DIM_MAX", _SC_BC_DIM_MAX}, + {"SC_BC_DIM_MAX", _SC_BC_DIM_MAX}, #endif #ifdef _SC_BC_SCALE_MAX - {"SC_BC_SCALE_MAX", _SC_BC_SCALE_MAX}, + {"SC_BC_SCALE_MAX", _SC_BC_SCALE_MAX}, #endif #ifdef _SC_BC_STRING_MAX - {"SC_BC_STRING_MAX", _SC_BC_STRING_MAX}, + {"SC_BC_STRING_MAX", _SC_BC_STRING_MAX}, #endif #ifdef _SC_CAP - {"SC_CAP", _SC_CAP}, + {"SC_CAP", _SC_CAP}, #endif #ifdef _SC_CHARCLASS_NAME_MAX - {"SC_CHARCLASS_NAME_MAX", _SC_CHARCLASS_NAME_MAX}, + {"SC_CHARCLASS_NAME_MAX", _SC_CHARCLASS_NAME_MAX}, #endif #ifdef _SC_CHAR_BIT - {"SC_CHAR_BIT", _SC_CHAR_BIT}, + {"SC_CHAR_BIT", _SC_CHAR_BIT}, #endif #ifdef _SC_CHAR_MAX - {"SC_CHAR_MAX", _SC_CHAR_MAX}, + {"SC_CHAR_MAX", _SC_CHAR_MAX}, #endif #ifdef _SC_CHAR_MIN - {"SC_CHAR_MIN", _SC_CHAR_MIN}, + {"SC_CHAR_MIN", _SC_CHAR_MIN}, #endif #ifdef _SC_CHILD_MAX - {"SC_CHILD_MAX", _SC_CHILD_MAX}, + {"SC_CHILD_MAX", _SC_CHILD_MAX}, #endif #ifdef _SC_CLK_TCK - {"SC_CLK_TCK", _SC_CLK_TCK}, + {"SC_CLK_TCK", _SC_CLK_TCK}, #endif #ifdef _SC_COHER_BLKSZ - {"SC_COHER_BLKSZ", _SC_COHER_BLKSZ}, + {"SC_COHER_BLKSZ", _SC_COHER_BLKSZ}, #endif #ifdef _SC_COLL_WEIGHTS_MAX - {"SC_COLL_WEIGHTS_MAX", _SC_COLL_WEIGHTS_MAX}, + {"SC_COLL_WEIGHTS_MAX", _SC_COLL_WEIGHTS_MAX}, #endif #ifdef _SC_DCACHE_ASSOC - {"SC_DCACHE_ASSOC", _SC_DCACHE_ASSOC}, + {"SC_DCACHE_ASSOC", _SC_DCACHE_ASSOC}, #endif #ifdef _SC_DCACHE_BLKSZ - {"SC_DCACHE_BLKSZ", _SC_DCACHE_BLKSZ}, + {"SC_DCACHE_BLKSZ", _SC_DCACHE_BLKSZ}, #endif #ifdef _SC_DCACHE_LINESZ - {"SC_DCACHE_LINESZ", _SC_DCACHE_LINESZ}, + {"SC_DCACHE_LINESZ", _SC_DCACHE_LINESZ}, #endif #ifdef _SC_DCACHE_SZ - {"SC_DCACHE_SZ", _SC_DCACHE_SZ}, + {"SC_DCACHE_SZ", _SC_DCACHE_SZ}, #endif #ifdef _SC_DCACHE_TBLKSZ - {"SC_DCACHE_TBLKSZ", _SC_DCACHE_TBLKSZ}, + {"SC_DCACHE_TBLKSZ", _SC_DCACHE_TBLKSZ}, #endif #ifdef _SC_DELAYTIMER_MAX - {"SC_DELAYTIMER_MAX", _SC_DELAYTIMER_MAX}, + {"SC_DELAYTIMER_MAX", _SC_DELAYTIMER_MAX}, #endif #ifdef _SC_EQUIV_CLASS_MAX - {"SC_EQUIV_CLASS_MAX", _SC_EQUIV_CLASS_MAX}, + {"SC_EQUIV_CLASS_MAX", _SC_EQUIV_CLASS_MAX}, #endif #ifdef _SC_EXPR_NEST_MAX - {"SC_EXPR_NEST_MAX", _SC_EXPR_NEST_MAX}, + {"SC_EXPR_NEST_MAX", _SC_EXPR_NEST_MAX}, #endif #ifdef _SC_FSYNC - {"SC_FSYNC", _SC_FSYNC}, + {"SC_FSYNC", _SC_FSYNC}, #endif #ifdef _SC_GETGR_R_SIZE_MAX - {"SC_GETGR_R_SIZE_MAX", _SC_GETGR_R_SIZE_MAX}, + {"SC_GETGR_R_SIZE_MAX", _SC_GETGR_R_SIZE_MAX}, #endif #ifdef _SC_GETPW_R_SIZE_MAX - {"SC_GETPW_R_SIZE_MAX", _SC_GETPW_R_SIZE_MAX}, + {"SC_GETPW_R_SIZE_MAX", _SC_GETPW_R_SIZE_MAX}, #endif #ifdef _SC_ICACHE_ASSOC - {"SC_ICACHE_ASSOC", _SC_ICACHE_ASSOC}, + {"SC_ICACHE_ASSOC", _SC_ICACHE_ASSOC}, #endif #ifdef _SC_ICACHE_BLKSZ - {"SC_ICACHE_BLKSZ", _SC_ICACHE_BLKSZ}, + {"SC_ICACHE_BLKSZ", _SC_ICACHE_BLKSZ}, #endif #ifdef _SC_ICACHE_LINESZ - {"SC_ICACHE_LINESZ", _SC_ICACHE_LINESZ}, + {"SC_ICACHE_LINESZ", _SC_ICACHE_LINESZ}, #endif #ifdef _SC_ICACHE_SZ - {"SC_ICACHE_SZ", _SC_ICACHE_SZ}, + {"SC_ICACHE_SZ", _SC_ICACHE_SZ}, #endif #ifdef _SC_INF - {"SC_INF", _SC_INF}, + {"SC_INF", _SC_INF}, #endif #ifdef _SC_INT_MAX - {"SC_INT_MAX", _SC_INT_MAX}, + {"SC_INT_MAX", _SC_INT_MAX}, #endif #ifdef _SC_INT_MIN - {"SC_INT_MIN", _SC_INT_MIN}, + {"SC_INT_MIN", _SC_INT_MIN}, #endif #ifdef _SC_IOV_MAX - {"SC_IOV_MAX", _SC_IOV_MAX}, + {"SC_IOV_MAX", _SC_IOV_MAX}, #endif #ifdef _SC_IP_SECOPTS - {"SC_IP_SECOPTS", _SC_IP_SECOPTS}, + {"SC_IP_SECOPTS", _SC_IP_SECOPTS}, #endif #ifdef _SC_JOB_CONTROL - {"SC_JOB_CONTROL", _SC_JOB_CONTROL}, + {"SC_JOB_CONTROL", _SC_JOB_CONTROL}, #endif #ifdef _SC_KERN_POINTERS - {"SC_KERN_POINTERS", _SC_KERN_POINTERS}, + {"SC_KERN_POINTERS", _SC_KERN_POINTERS}, #endif #ifdef _SC_KERN_SIM - {"SC_KERN_SIM", _SC_KERN_SIM}, + {"SC_KERN_SIM", _SC_KERN_SIM}, #endif #ifdef _SC_LINE_MAX - {"SC_LINE_MAX", _SC_LINE_MAX}, + {"SC_LINE_MAX", _SC_LINE_MAX}, #endif #ifdef _SC_LOGIN_NAME_MAX - {"SC_LOGIN_NAME_MAX", _SC_LOGIN_NAME_MAX}, + {"SC_LOGIN_NAME_MAX", _SC_LOGIN_NAME_MAX}, #endif #ifdef _SC_LOGNAME_MAX - {"SC_LOGNAME_MAX", _SC_LOGNAME_MAX}, + {"SC_LOGNAME_MAX", _SC_LOGNAME_MAX}, #endif #ifdef _SC_LONG_BIT - {"SC_LONG_BIT", _SC_LONG_BIT}, + {"SC_LONG_BIT", _SC_LONG_BIT}, #endif #ifdef _SC_MAC - {"SC_MAC", _SC_MAC}, + {"SC_MAC", _SC_MAC}, #endif #ifdef _SC_MAPPED_FILES - {"SC_MAPPED_FILES", _SC_MAPPED_FILES}, + {"SC_MAPPED_FILES", _SC_MAPPED_FILES}, #endif #ifdef _SC_MAXPID - {"SC_MAXPID", _SC_MAXPID}, + {"SC_MAXPID", _SC_MAXPID}, #endif #ifdef _SC_MB_LEN_MAX - {"SC_MB_LEN_MAX", _SC_MB_LEN_MAX}, + {"SC_MB_LEN_MAX", _SC_MB_LEN_MAX}, #endif #ifdef _SC_MEMLOCK - {"SC_MEMLOCK", _SC_MEMLOCK}, + {"SC_MEMLOCK", _SC_MEMLOCK}, #endif #ifdef _SC_MEMLOCK_RANGE - {"SC_MEMLOCK_RANGE", _SC_MEMLOCK_RANGE}, + {"SC_MEMLOCK_RANGE", _SC_MEMLOCK_RANGE}, #endif #ifdef _SC_MEMORY_PROTECTION - {"SC_MEMORY_PROTECTION", _SC_MEMORY_PROTECTION}, + {"SC_MEMORY_PROTECTION", _SC_MEMORY_PROTECTION}, #endif #ifdef _SC_MESSAGE_PASSING - {"SC_MESSAGE_PASSING", _SC_MESSAGE_PASSING}, + {"SC_MESSAGE_PASSING", _SC_MESSAGE_PASSING}, #endif #ifdef _SC_MMAP_FIXED_ALIGNMENT - {"SC_MMAP_FIXED_ALIGNMENT", _SC_MMAP_FIXED_ALIGNMENT}, + {"SC_MMAP_FIXED_ALIGNMENT", _SC_MMAP_FIXED_ALIGNMENT}, #endif #ifdef _SC_MQ_OPEN_MAX - {"SC_MQ_OPEN_MAX", _SC_MQ_OPEN_MAX}, + {"SC_MQ_OPEN_MAX", _SC_MQ_OPEN_MAX}, #endif #ifdef _SC_MQ_PRIO_MAX - {"SC_MQ_PRIO_MAX", _SC_MQ_PRIO_MAX}, + {"SC_MQ_PRIO_MAX", _SC_MQ_PRIO_MAX}, #endif #ifdef _SC_NACLS_MAX - {"SC_NACLS_MAX", _SC_NACLS_MAX}, + {"SC_NACLS_MAX", _SC_NACLS_MAX}, #endif #ifdef _SC_NGROUPS_MAX - {"SC_NGROUPS_MAX", _SC_NGROUPS_MAX}, + {"SC_NGROUPS_MAX", _SC_NGROUPS_MAX}, #endif #ifdef _SC_NL_ARGMAX - {"SC_NL_ARGMAX", _SC_NL_ARGMAX}, + {"SC_NL_ARGMAX", _SC_NL_ARGMAX}, #endif #ifdef _SC_NL_LANGMAX - {"SC_NL_LANGMAX", _SC_NL_LANGMAX}, + {"SC_NL_LANGMAX", _SC_NL_LANGMAX}, #endif #ifdef _SC_NL_MSGMAX - {"SC_NL_MSGMAX", _SC_NL_MSGMAX}, + {"SC_NL_MSGMAX", _SC_NL_MSGMAX}, #endif #ifdef _SC_NL_NMAX - {"SC_NL_NMAX", _SC_NL_NMAX}, + {"SC_NL_NMAX", _SC_NL_NMAX}, #endif #ifdef _SC_NL_SETMAX - {"SC_NL_SETMAX", _SC_NL_SETMAX}, + {"SC_NL_SETMAX", _SC_NL_SETMAX}, #endif #ifdef _SC_NL_TEXTMAX - {"SC_NL_TEXTMAX", _SC_NL_TEXTMAX}, + {"SC_NL_TEXTMAX", _SC_NL_TEXTMAX}, #endif #ifdef _SC_NPROCESSORS_CONF - {"SC_NPROCESSORS_CONF", _SC_NPROCESSORS_CONF}, + {"SC_NPROCESSORS_CONF", _SC_NPROCESSORS_CONF}, #endif #ifdef _SC_NPROCESSORS_ONLN - {"SC_NPROCESSORS_ONLN", _SC_NPROCESSORS_ONLN}, + {"SC_NPROCESSORS_ONLN", _SC_NPROCESSORS_ONLN}, #endif #ifdef _SC_NPROC_CONF - {"SC_NPROC_CONF", _SC_NPROC_CONF}, + {"SC_NPROC_CONF", _SC_NPROC_CONF}, #endif #ifdef _SC_NPROC_ONLN - {"SC_NPROC_ONLN", _SC_NPROC_ONLN}, + {"SC_NPROC_ONLN", _SC_NPROC_ONLN}, #endif #ifdef _SC_NZERO - {"SC_NZERO", _SC_NZERO}, + {"SC_NZERO", _SC_NZERO}, #endif #ifdef _SC_OPEN_MAX - {"SC_OPEN_MAX", _SC_OPEN_MAX}, + {"SC_OPEN_MAX", _SC_OPEN_MAX}, #endif #ifdef _SC_PAGESIZE - {"SC_PAGESIZE", _SC_PAGESIZE}, + {"SC_PAGESIZE", _SC_PAGESIZE}, #endif #ifdef _SC_PAGE_SIZE - {"SC_PAGE_SIZE", _SC_PAGE_SIZE}, + {"SC_PAGE_SIZE", _SC_PAGE_SIZE}, #endif #ifdef _SC_PASS_MAX - {"SC_PASS_MAX", _SC_PASS_MAX}, + {"SC_PASS_MAX", _SC_PASS_MAX}, #endif #ifdef _SC_PHYS_PAGES - {"SC_PHYS_PAGES", _SC_PHYS_PAGES}, + {"SC_PHYS_PAGES", _SC_PHYS_PAGES}, #endif #ifdef _SC_PII - {"SC_PII", _SC_PII}, + {"SC_PII", _SC_PII}, #endif #ifdef _SC_PII_INTERNET - {"SC_PII_INTERNET", _SC_PII_INTERNET}, + {"SC_PII_INTERNET", _SC_PII_INTERNET}, #endif #ifdef _SC_PII_INTERNET_DGRAM - {"SC_PII_INTERNET_DGRAM", _SC_PII_INTERNET_DGRAM}, + {"SC_PII_INTERNET_DGRAM", _SC_PII_INTERNET_DGRAM}, #endif #ifdef _SC_PII_INTERNET_STREAM - {"SC_PII_INTERNET_STREAM", _SC_PII_INTERNET_STREAM}, + {"SC_PII_INTERNET_STREAM", _SC_PII_INTERNET_STREAM}, #endif #ifdef _SC_PII_OSI - {"SC_PII_OSI", _SC_PII_OSI}, + {"SC_PII_OSI", _SC_PII_OSI}, #endif #ifdef _SC_PII_OSI_CLTS - {"SC_PII_OSI_CLTS", _SC_PII_OSI_CLTS}, + {"SC_PII_OSI_CLTS", _SC_PII_OSI_CLTS}, #endif #ifdef _SC_PII_OSI_COTS - {"SC_PII_OSI_COTS", _SC_PII_OSI_COTS}, + {"SC_PII_OSI_COTS", _SC_PII_OSI_COTS}, #endif #ifdef _SC_PII_OSI_M - {"SC_PII_OSI_M", _SC_PII_OSI_M}, + {"SC_PII_OSI_M", _SC_PII_OSI_M}, #endif #ifdef _SC_PII_SOCKET - {"SC_PII_SOCKET", _SC_PII_SOCKET}, + {"SC_PII_SOCKET", _SC_PII_SOCKET}, #endif #ifdef _SC_PII_XTI - {"SC_PII_XTI", _SC_PII_XTI}, + {"SC_PII_XTI", _SC_PII_XTI}, #endif #ifdef _SC_POLL - {"SC_POLL", _SC_POLL}, + {"SC_POLL", _SC_POLL}, #endif #ifdef _SC_PRIORITIZED_IO - {"SC_PRIORITIZED_IO", _SC_PRIORITIZED_IO}, + {"SC_PRIORITIZED_IO", _SC_PRIORITIZED_IO}, #endif #ifdef _SC_PRIORITY_SCHEDULING - {"SC_PRIORITY_SCHEDULING", _SC_PRIORITY_SCHEDULING}, + {"SC_PRIORITY_SCHEDULING", _SC_PRIORITY_SCHEDULING}, #endif #ifdef _SC_REALTIME_SIGNALS - {"SC_REALTIME_SIGNALS", _SC_REALTIME_SIGNALS}, + {"SC_REALTIME_SIGNALS", _SC_REALTIME_SIGNALS}, #endif #ifdef _SC_RE_DUP_MAX - {"SC_RE_DUP_MAX", _SC_RE_DUP_MAX}, + {"SC_RE_DUP_MAX", _SC_RE_DUP_MAX}, #endif #ifdef _SC_RTSIG_MAX - {"SC_RTSIG_MAX", _SC_RTSIG_MAX}, + {"SC_RTSIG_MAX", _SC_RTSIG_MAX}, #endif #ifdef _SC_SAVED_IDS - {"SC_SAVED_IDS", _SC_SAVED_IDS}, + {"SC_SAVED_IDS", _SC_SAVED_IDS}, #endif #ifdef _SC_SCHAR_MAX - {"SC_SCHAR_MAX", _SC_SCHAR_MAX}, + {"SC_SCHAR_MAX", _SC_SCHAR_MAX}, #endif #ifdef _SC_SCHAR_MIN - {"SC_SCHAR_MIN", _SC_SCHAR_MIN}, + {"SC_SCHAR_MIN", _SC_SCHAR_MIN}, #endif #ifdef _SC_SELECT - {"SC_SELECT", _SC_SELECT}, + {"SC_SELECT", _SC_SELECT}, #endif #ifdef _SC_SEMAPHORES - {"SC_SEMAPHORES", _SC_SEMAPHORES}, + {"SC_SEMAPHORES", _SC_SEMAPHORES}, #endif #ifdef _SC_SEM_NSEMS_MAX - {"SC_SEM_NSEMS_MAX", _SC_SEM_NSEMS_MAX}, + {"SC_SEM_NSEMS_MAX", _SC_SEM_NSEMS_MAX}, #endif #ifdef _SC_SEM_VALUE_MAX - {"SC_SEM_VALUE_MAX", _SC_SEM_VALUE_MAX}, + {"SC_SEM_VALUE_MAX", _SC_SEM_VALUE_MAX}, #endif #ifdef _SC_SHARED_MEMORY_OBJECTS - {"SC_SHARED_MEMORY_OBJECTS", _SC_SHARED_MEMORY_OBJECTS}, + {"SC_SHARED_MEMORY_OBJECTS", _SC_SHARED_MEMORY_OBJECTS}, #endif #ifdef _SC_SHRT_MAX - {"SC_SHRT_MAX", _SC_SHRT_MAX}, + {"SC_SHRT_MAX", _SC_SHRT_MAX}, #endif #ifdef _SC_SHRT_MIN - {"SC_SHRT_MIN", _SC_SHRT_MIN}, + {"SC_SHRT_MIN", _SC_SHRT_MIN}, #endif #ifdef _SC_SIGQUEUE_MAX - {"SC_SIGQUEUE_MAX", _SC_SIGQUEUE_MAX}, + {"SC_SIGQUEUE_MAX", _SC_SIGQUEUE_MAX}, #endif #ifdef _SC_SIGRT_MAX - {"SC_SIGRT_MAX", _SC_SIGRT_MAX}, + {"SC_SIGRT_MAX", _SC_SIGRT_MAX}, #endif #ifdef _SC_SIGRT_MIN - {"SC_SIGRT_MIN", _SC_SIGRT_MIN}, + {"SC_SIGRT_MIN", _SC_SIGRT_MIN}, #endif #ifdef _SC_SOFTPOWER - {"SC_SOFTPOWER", _SC_SOFTPOWER}, + {"SC_SOFTPOWER", _SC_SOFTPOWER}, #endif #ifdef _SC_SPLIT_CACHE - {"SC_SPLIT_CACHE", _SC_SPLIT_CACHE}, + {"SC_SPLIT_CACHE", _SC_SPLIT_CACHE}, #endif #ifdef _SC_SSIZE_MAX - {"SC_SSIZE_MAX", _SC_SSIZE_MAX}, + {"SC_SSIZE_MAX", _SC_SSIZE_MAX}, #endif #ifdef _SC_STACK_PROT - {"SC_STACK_PROT", _SC_STACK_PROT}, + {"SC_STACK_PROT", _SC_STACK_PROT}, #endif #ifdef _SC_STREAM_MAX - {"SC_STREAM_MAX", _SC_STREAM_MAX}, + {"SC_STREAM_MAX", _SC_STREAM_MAX}, #endif #ifdef _SC_SYNCHRONIZED_IO - {"SC_SYNCHRONIZED_IO", _SC_SYNCHRONIZED_IO}, + {"SC_SYNCHRONIZED_IO", _SC_SYNCHRONIZED_IO}, #endif #ifdef _SC_THREADS - {"SC_THREADS", _SC_THREADS}, + {"SC_THREADS", _SC_THREADS}, #endif #ifdef _SC_THREAD_ATTR_STACKADDR - {"SC_THREAD_ATTR_STACKADDR", _SC_THREAD_ATTR_STACKADDR}, + {"SC_THREAD_ATTR_STACKADDR", _SC_THREAD_ATTR_STACKADDR}, #endif #ifdef _SC_THREAD_ATTR_STACKSIZE - {"SC_THREAD_ATTR_STACKSIZE", _SC_THREAD_ATTR_STACKSIZE}, + {"SC_THREAD_ATTR_STACKSIZE", _SC_THREAD_ATTR_STACKSIZE}, #endif #ifdef _SC_THREAD_DESTRUCTOR_ITERATIONS - {"SC_THREAD_DESTRUCTOR_ITERATIONS", _SC_THREAD_DESTRUCTOR_ITERATIONS}, + {"SC_THREAD_DESTRUCTOR_ITERATIONS", _SC_THREAD_DESTRUCTOR_ITERATIONS}, #endif #ifdef _SC_THREAD_KEYS_MAX - {"SC_THREAD_KEYS_MAX", _SC_THREAD_KEYS_MAX}, + {"SC_THREAD_KEYS_MAX", _SC_THREAD_KEYS_MAX}, #endif #ifdef _SC_THREAD_PRIORITY_SCHEDULING - {"SC_THREAD_PRIORITY_SCHEDULING", _SC_THREAD_PRIORITY_SCHEDULING}, + {"SC_THREAD_PRIORITY_SCHEDULING", _SC_THREAD_PRIORITY_SCHEDULING}, #endif #ifdef _SC_THREAD_PRIO_INHERIT - {"SC_THREAD_PRIO_INHERIT", _SC_THREAD_PRIO_INHERIT}, + {"SC_THREAD_PRIO_INHERIT", _SC_THREAD_PRIO_INHERIT}, #endif #ifdef _SC_THREAD_PRIO_PROTECT - {"SC_THREAD_PRIO_PROTECT", _SC_THREAD_PRIO_PROTECT}, + {"SC_THREAD_PRIO_PROTECT", _SC_THREAD_PRIO_PROTECT}, #endif #ifdef _SC_THREAD_PROCESS_SHARED - {"SC_THREAD_PROCESS_SHARED", _SC_THREAD_PROCESS_SHARED}, + {"SC_THREAD_PROCESS_SHARED", _SC_THREAD_PROCESS_SHARED}, #endif #ifdef _SC_THREAD_SAFE_FUNCTIONS - {"SC_THREAD_SAFE_FUNCTIONS", _SC_THREAD_SAFE_FUNCTIONS}, + {"SC_THREAD_SAFE_FUNCTIONS", _SC_THREAD_SAFE_FUNCTIONS}, #endif #ifdef _SC_THREAD_STACK_MIN - {"SC_THREAD_STACK_MIN", _SC_THREAD_STACK_MIN}, + {"SC_THREAD_STACK_MIN", _SC_THREAD_STACK_MIN}, #endif #ifdef _SC_THREAD_THREADS_MAX - {"SC_THREAD_THREADS_MAX", _SC_THREAD_THREADS_MAX}, + {"SC_THREAD_THREADS_MAX", _SC_THREAD_THREADS_MAX}, #endif #ifdef _SC_TIMERS - {"SC_TIMERS", _SC_TIMERS}, + {"SC_TIMERS", _SC_TIMERS}, #endif #ifdef _SC_TIMER_MAX - {"SC_TIMER_MAX", _SC_TIMER_MAX}, + {"SC_TIMER_MAX", _SC_TIMER_MAX}, #endif #ifdef _SC_TTY_NAME_MAX - {"SC_TTY_NAME_MAX", _SC_TTY_NAME_MAX}, + {"SC_TTY_NAME_MAX", _SC_TTY_NAME_MAX}, #endif #ifdef _SC_TZNAME_MAX - {"SC_TZNAME_MAX", _SC_TZNAME_MAX}, + {"SC_TZNAME_MAX", _SC_TZNAME_MAX}, #endif #ifdef _SC_T_IOV_MAX - {"SC_T_IOV_MAX", _SC_T_IOV_MAX}, + {"SC_T_IOV_MAX", _SC_T_IOV_MAX}, #endif #ifdef _SC_UCHAR_MAX - {"SC_UCHAR_MAX", _SC_UCHAR_MAX}, + {"SC_UCHAR_MAX", _SC_UCHAR_MAX}, #endif #ifdef _SC_UINT_MAX - {"SC_UINT_MAX", _SC_UINT_MAX}, + {"SC_UINT_MAX", _SC_UINT_MAX}, #endif #ifdef _SC_UIO_MAXIOV - {"SC_UIO_MAXIOV", _SC_UIO_MAXIOV}, + {"SC_UIO_MAXIOV", _SC_UIO_MAXIOV}, #endif #ifdef _SC_ULONG_MAX - {"SC_ULONG_MAX", _SC_ULONG_MAX}, + {"SC_ULONG_MAX", _SC_ULONG_MAX}, #endif #ifdef _SC_USHRT_MAX - {"SC_USHRT_MAX", _SC_USHRT_MAX}, + {"SC_USHRT_MAX", _SC_USHRT_MAX}, #endif #ifdef _SC_VERSION - {"SC_VERSION", _SC_VERSION}, + {"SC_VERSION", _SC_VERSION}, #endif #ifdef _SC_WORD_BIT - {"SC_WORD_BIT", _SC_WORD_BIT}, + {"SC_WORD_BIT", _SC_WORD_BIT}, #endif #ifdef _SC_XBS5_ILP32_OFF32 - {"SC_XBS5_ILP32_OFF32", _SC_XBS5_ILP32_OFF32}, + {"SC_XBS5_ILP32_OFF32", _SC_XBS5_ILP32_OFF32}, #endif #ifdef _SC_XBS5_ILP32_OFFBIG - {"SC_XBS5_ILP32_OFFBIG", _SC_XBS5_ILP32_OFFBIG}, + {"SC_XBS5_ILP32_OFFBIG", _SC_XBS5_ILP32_OFFBIG}, #endif #ifdef _SC_XBS5_LP64_OFF64 - {"SC_XBS5_LP64_OFF64", _SC_XBS5_LP64_OFF64}, + {"SC_XBS5_LP64_OFF64", _SC_XBS5_LP64_OFF64}, #endif #ifdef _SC_XBS5_LPBIG_OFFBIG - {"SC_XBS5_LPBIG_OFFBIG", _SC_XBS5_LPBIG_OFFBIG}, + {"SC_XBS5_LPBIG_OFFBIG", _SC_XBS5_LPBIG_OFFBIG}, #endif #ifdef _SC_XOPEN_CRYPT - {"SC_XOPEN_CRYPT", _SC_XOPEN_CRYPT}, + {"SC_XOPEN_CRYPT", _SC_XOPEN_CRYPT}, #endif #ifdef _SC_XOPEN_ENH_I18N - {"SC_XOPEN_ENH_I18N", _SC_XOPEN_ENH_I18N}, + {"SC_XOPEN_ENH_I18N", _SC_XOPEN_ENH_I18N}, #endif #ifdef _SC_XOPEN_LEGACY - {"SC_XOPEN_LEGACY", _SC_XOPEN_LEGACY}, + {"SC_XOPEN_LEGACY", _SC_XOPEN_LEGACY}, #endif #ifdef _SC_XOPEN_REALTIME - {"SC_XOPEN_REALTIME", _SC_XOPEN_REALTIME}, + {"SC_XOPEN_REALTIME", _SC_XOPEN_REALTIME}, #endif #ifdef _SC_XOPEN_REALTIME_THREADS - {"SC_XOPEN_REALTIME_THREADS", _SC_XOPEN_REALTIME_THREADS}, + {"SC_XOPEN_REALTIME_THREADS", _SC_XOPEN_REALTIME_THREADS}, #endif #ifdef _SC_XOPEN_SHM - {"SC_XOPEN_SHM", _SC_XOPEN_SHM}, + {"SC_XOPEN_SHM", _SC_XOPEN_SHM}, #endif #ifdef _SC_XOPEN_UNIX - {"SC_XOPEN_UNIX", _SC_XOPEN_UNIX}, + {"SC_XOPEN_UNIX", _SC_XOPEN_UNIX}, #endif #ifdef _SC_XOPEN_VERSION - {"SC_XOPEN_VERSION", _SC_XOPEN_VERSION}, + {"SC_XOPEN_VERSION", _SC_XOPEN_VERSION}, #endif #ifdef _SC_XOPEN_XCU_VERSION - {"SC_XOPEN_XCU_VERSION", _SC_XOPEN_XCU_VERSION}, + {"SC_XOPEN_XCU_VERSION", _SC_XOPEN_XCU_VERSION}, #endif #ifdef _SC_XOPEN_XPG2 - {"SC_XOPEN_XPG2", _SC_XOPEN_XPG2}, + {"SC_XOPEN_XPG2", _SC_XOPEN_XPG2}, #endif #ifdef _SC_XOPEN_XPG3 - {"SC_XOPEN_XPG3", _SC_XOPEN_XPG3}, + {"SC_XOPEN_XPG3", _SC_XOPEN_XPG3}, #endif #ifdef _SC_XOPEN_XPG4 - {"SC_XOPEN_XPG4", _SC_XOPEN_XPG4}, + {"SC_XOPEN_XPG4", _SC_XOPEN_XPG4}, #endif }; @@ -6617,16 +6618,16 @@ cmp_constdefs(const void *v1, const void *v2) { const struct constdef *c1 = - (const struct constdef *) v1; + (const struct constdef *) v1; const struct constdef *c2 = - (const struct constdef *) v2; + (const struct constdef *) v2; return strcmp(c1->name, c2->name); } static int setup_confname_table(struct constdef *table, size_t tablesize, - char *tablename, PyObject *module) + char *tablename, PyObject *module) { PyObject *d = NULL; size_t i; @@ -6634,16 +6635,16 @@ qsort(table, tablesize, sizeof(struct constdef), cmp_constdefs); d = PyDict_New(); if (d == NULL) - return -1; + return -1; for (i=0; i < tablesize; ++i) { - PyObject *o = PyLong_FromLong(table[i].value); - if (o == NULL || PyDict_SetItemString(d, table[i].name, o) == -1) { - Py_XDECREF(o); - Py_DECREF(d); - return -1; - } - Py_DECREF(o); + PyObject *o = PyLong_FromLong(table[i].value); + if (o == NULL || PyDict_SetItemString(d, table[i].name, o) == -1) { + Py_XDECREF(o); + Py_DECREF(d); + return -1; + } + Py_DECREF(o); } return PyModule_AddObject(module, tablename, d); } @@ -6657,21 +6658,21 @@ sizeof(posix_constants_pathconf) / sizeof(struct constdef), "pathconf_names", module)) - return -1; + return -1; #endif #ifdef HAVE_CONFSTR if (setup_confname_table(posix_constants_confstr, sizeof(posix_constants_confstr) / sizeof(struct constdef), "confstr_names", module)) - return -1; + return -1; #endif #ifdef HAVE_SYSCONF if (setup_confname_table(posix_constants_sysconf, sizeof(posix_constants_sysconf) / sizeof(struct constdef), "sysconf_names", module)) - return -1; + return -1; #endif return 0; } @@ -6714,61 +6715,61 @@ static PyObject * win32_startfile(PyObject *self, PyObject *args) { - PyObject *ofilepath; - char *filepath; - char *operation = NULL; - HINSTANCE rc; - - PyObject *unipath, *woperation = NULL; - if (!PyArg_ParseTuple(args, "U|s:startfile", - &unipath, &operation)) { - PyErr_Clear(); - goto normal; - } - - if (operation) { - woperation = PyUnicode_DecodeASCII(operation, - strlen(operation), NULL); - if (!woperation) { - PyErr_Clear(); - operation = NULL; - goto normal; - } - } - - Py_BEGIN_ALLOW_THREADS - rc = ShellExecuteW((HWND)0, woperation ? PyUnicode_AS_UNICODE(woperation) : 0, - PyUnicode_AS_UNICODE(unipath), - NULL, NULL, SW_SHOWNORMAL); - Py_END_ALLOW_THREADS - - Py_XDECREF(woperation); - if (rc <= (HINSTANCE)32) { - PyObject *errval = win32_error_unicode("startfile", - PyUnicode_AS_UNICODE(unipath)); - return errval; - } - Py_INCREF(Py_None); - return Py_None; + PyObject *ofilepath; + char *filepath; + char *operation = NULL; + HINSTANCE rc; + + PyObject *unipath, *woperation = NULL; + if (!PyArg_ParseTuple(args, "U|s:startfile", + &unipath, &operation)) { + PyErr_Clear(); + goto normal; + } + + if (operation) { + woperation = PyUnicode_DecodeASCII(operation, + strlen(operation), NULL); + if (!woperation) { + PyErr_Clear(); + operation = NULL; + goto normal; + } + } + + Py_BEGIN_ALLOW_THREADS + rc = ShellExecuteW((HWND)0, woperation ? PyUnicode_AS_UNICODE(woperation) : 0, + PyUnicode_AS_UNICODE(unipath), + NULL, NULL, SW_SHOWNORMAL); + Py_END_ALLOW_THREADS + + Py_XDECREF(woperation); + if (rc <= (HINSTANCE)32) { + PyObject *errval = win32_error_unicode("startfile", + PyUnicode_AS_UNICODE(unipath)); + return errval; + } + Py_INCREF(Py_None); + return Py_None; normal: - if (!PyArg_ParseTuple(args, "O&|s:startfile", - PyUnicode_FSConverter, &ofilepath, - &operation)) - return NULL; - filepath = PyBytes_AsString(ofilepath); - Py_BEGIN_ALLOW_THREADS - rc = ShellExecute((HWND)0, operation, filepath, - NULL, NULL, SW_SHOWNORMAL); - Py_END_ALLOW_THREADS - if (rc <= (HINSTANCE)32) { - PyObject *errval = win32_error("startfile", filepath); - Py_DECREF(ofilepath); - return errval; - } - Py_DECREF(ofilepath); - Py_INCREF(Py_None); - return Py_None; + if (!PyArg_ParseTuple(args, "O&|s:startfile", + PyUnicode_FSConverter, &ofilepath, + &operation)) + return NULL; + filepath = PyBytes_AsString(ofilepath); + Py_BEGIN_ALLOW_THREADS + rc = ShellExecute((HWND)0, operation, filepath, + NULL, NULL, SW_SHOWNORMAL); + Py_END_ALLOW_THREADS + if (rc <= (HINSTANCE)32) { + PyObject *errval = win32_error("startfile", filepath); + Py_DECREF(ofilepath); + return errval; + } + Py_DECREF(ofilepath); + Py_INCREF(Py_None); + return Py_None; } #endif @@ -6784,10 +6785,10 @@ { double loadavg[3]; if (getloadavg(loadavg, 3)!=3) { - PyErr_SetString(PyExc_OSError, "Load averages are unobtainable"); - return NULL; + PyErr_SetString(PyExc_OSError, "Load averages are unobtainable"); + return NULL; } else - return Py_BuildValue("ddd", loadavg[0], loadavg[1], loadavg[2]); + return Py_BuildValue("ddd", loadavg[0], loadavg[1], loadavg[2]); } #endif @@ -6811,59 +6812,59 @@ static PyObject* win32_urandom(PyObject *self, PyObject *args) { - int howMany; - PyObject* result; + int howMany; + PyObject* result; + + /* Read arguments */ + if (! PyArg_ParseTuple(args, "i:urandom", &howMany)) + return NULL; + if (howMany < 0) + return PyErr_Format(PyExc_ValueError, + "negative argument not allowed"); + + if (hCryptProv == 0) { + HINSTANCE hAdvAPI32 = NULL; + CRYPTACQUIRECONTEXTA pCryptAcquireContext = NULL; + + /* Obtain handle to the DLL containing CryptoAPI + This should not fail */ + hAdvAPI32 = GetModuleHandle("advapi32.dll"); + if(hAdvAPI32 == NULL) + return win32_error("GetModuleHandle", NULL); + + /* Obtain pointers to the CryptoAPI functions + This will fail on some early versions of Win95 */ + pCryptAcquireContext = (CRYPTACQUIRECONTEXTA)GetProcAddress( + hAdvAPI32, + "CryptAcquireContextA"); + if (pCryptAcquireContext == NULL) + return PyErr_Format(PyExc_NotImplementedError, + "CryptAcquireContextA not found"); + + pCryptGenRandom = (CRYPTGENRANDOM)GetProcAddress( + hAdvAPI32, "CryptGenRandom"); + if (pCryptGenRandom == NULL) + return PyErr_Format(PyExc_NotImplementedError, + "CryptGenRandom not found"); + + /* Acquire context */ + if (! pCryptAcquireContext(&hCryptProv, NULL, NULL, + PROV_RSA_FULL, CRYPT_VERIFYCONTEXT)) + return win32_error("CryptAcquireContext", NULL); + } - /* Read arguments */ - if (! PyArg_ParseTuple(args, "i:urandom", &howMany)) - return NULL; - if (howMany < 0) - return PyErr_Format(PyExc_ValueError, - "negative argument not allowed"); - - if (hCryptProv == 0) { - HINSTANCE hAdvAPI32 = NULL; - CRYPTACQUIRECONTEXTA pCryptAcquireContext = NULL; - - /* Obtain handle to the DLL containing CryptoAPI - This should not fail */ - hAdvAPI32 = GetModuleHandle("advapi32.dll"); - if(hAdvAPI32 == NULL) - return win32_error("GetModuleHandle", NULL); - - /* Obtain pointers to the CryptoAPI functions - This will fail on some early versions of Win95 */ - pCryptAcquireContext = (CRYPTACQUIRECONTEXTA)GetProcAddress( - hAdvAPI32, - "CryptAcquireContextA"); - if (pCryptAcquireContext == NULL) - return PyErr_Format(PyExc_NotImplementedError, - "CryptAcquireContextA not found"); - - pCryptGenRandom = (CRYPTGENRANDOM)GetProcAddress( - hAdvAPI32, "CryptGenRandom"); - if (pCryptGenRandom == NULL) - return PyErr_Format(PyExc_NotImplementedError, - "CryptGenRandom not found"); - - /* Acquire context */ - if (! pCryptAcquireContext(&hCryptProv, NULL, NULL, - PROV_RSA_FULL, CRYPT_VERIFYCONTEXT)) - return win32_error("CryptAcquireContext", NULL); - } - - /* Allocate bytes */ - result = PyBytes_FromStringAndSize(NULL, howMany); - if (result != NULL) { - /* Get random data */ - memset(PyBytes_AS_STRING(result), 0, howMany); /* zero seed */ - if (! pCryptGenRandom(hCryptProv, howMany, (unsigned char*) - PyBytes_AS_STRING(result))) { - Py_DECREF(result); - return win32_error("CryptGenRandom", NULL); - } - } - return result; + /* Allocate bytes */ + result = PyBytes_FromStringAndSize(NULL, howMany); + if (result != NULL) { + /* Get random data */ + memset(PyBytes_AS_STRING(result), 0, howMany); /* zero seed */ + if (! pCryptGenRandom(hCryptProv, howMany, (unsigned char*) + PyBytes_AS_STRING(result))) { + Py_DECREF(result); + return win32_error("CryptGenRandom", NULL); + } + } + return result; } #endif @@ -6875,33 +6876,33 @@ static PyObject * device_encoding(PyObject *self, PyObject *args) { - int fd; - if (!PyArg_ParseTuple(args, "i:device_encoding", &fd)) - return NULL; - if (!_PyVerify_fd(fd) || !isatty(fd)) { - Py_INCREF(Py_None); - return Py_None; - } + int fd; + if (!PyArg_ParseTuple(args, "i:device_encoding", &fd)) + return NULL; + if (!_PyVerify_fd(fd) || !isatty(fd)) { + Py_INCREF(Py_None); + return Py_None; + } #if defined(MS_WINDOWS) || defined(MS_WIN64) - if (fd == 0) { - char buf[100]; - sprintf(buf, "cp%d", GetConsoleCP()); - return PyUnicode_FromString(buf); - } - if (fd == 1 || fd == 2) { - char buf[100]; - sprintf(buf, "cp%d", GetConsoleOutputCP()); - return PyUnicode_FromString(buf); - } + if (fd == 0) { + char buf[100]; + sprintf(buf, "cp%d", GetConsoleCP()); + return PyUnicode_FromString(buf); + } + if (fd == 1 || fd == 2) { + char buf[100]; + sprintf(buf, "cp%d", GetConsoleOutputCP()); + return PyUnicode_FromString(buf); + } #elif defined(CODESET) - { - char *codeset = nl_langinfo(CODESET); - if (codeset != NULL && codeset[0] != 0) - return PyUnicode_FromString(codeset); - } + { + char *codeset = nl_langinfo(CODESET); + if (codeset != NULL && codeset[0] != 0) + return PyUnicode_FromString(codeset); + } #endif - Py_INCREF(Py_None); - return Py_None; + Py_INCREF(Py_None); + return Py_None; } #ifdef __VMS @@ -6914,29 +6915,29 @@ static PyObject* vms_urandom(PyObject *self, PyObject *args) { - int howMany; - PyObject* result; + int howMany; + PyObject* result; - /* Read arguments */ - if (! PyArg_ParseTuple(args, "i:urandom", &howMany)) - return NULL; - if (howMany < 0) - return PyErr_Format(PyExc_ValueError, - "negative argument not allowed"); - - /* Allocate bytes */ - result = PyBytes_FromStringAndSize(NULL, howMany); - if (result != NULL) { - /* Get random data */ - if (RAND_pseudo_bytes((unsigned char*) - PyBytes_AS_STRING(result), - howMany) < 0) { - Py_DECREF(result); - return PyErr_Format(PyExc_ValueError, - "RAND_pseudo_bytes"); - } - } - return result; + /* Read arguments */ + if (! PyArg_ParseTuple(args, "i:urandom", &howMany)) + return NULL; + if (howMany < 0) + return PyErr_Format(PyExc_ValueError, + "negative argument not allowed"); + + /* Allocate bytes */ + result = PyBytes_FromStringAndSize(NULL, howMany); + if (result != NULL) { + /* Get random data */ + if (RAND_pseudo_bytes((unsigned char*) + PyBytes_AS_STRING(result), + howMany) < 0) { + Py_DECREF(result); + return PyErr_Format(PyExc_ValueError, + "RAND_pseudo_bytes"); + } + } + return result; } #endif @@ -6948,13 +6949,13 @@ static PyObject* posix_setresuid (PyObject *self, PyObject *args) { - /* We assume uid_t is no larger than a long. */ - long ruid, euid, suid; - if (!PyArg_ParseTuple(args, "lll", &ruid, &euid, &suid)) - return NULL; - if (setresuid(ruid, euid, suid) < 0) - return posix_error(); - Py_RETURN_NONE; + /* We assume uid_t is no larger than a long. */ + long ruid, euid, suid; + if (!PyArg_ParseTuple(args, "lll", &ruid, &euid, &suid)) + return NULL; + if (setresuid(ruid, euid, suid) < 0) + return posix_error(); + Py_RETURN_NONE; } #endif @@ -6966,13 +6967,13 @@ static PyObject* posix_setresgid (PyObject *self, PyObject *args) { - /* We assume uid_t is no larger than a long. */ - long rgid, egid, sgid; - if (!PyArg_ParseTuple(args, "lll", &rgid, &egid, &sgid)) - return NULL; - if (setresgid(rgid, egid, sgid) < 0) - return posix_error(); - Py_RETURN_NONE; + /* We assume uid_t is no larger than a long. */ + long rgid, egid, sgid; + if (!PyArg_ParseTuple(args, "lll", &rgid, &egid, &sgid)) + return NULL; + if (setresgid(rgid, egid, sgid) < 0) + return posix_error(); + Py_RETURN_NONE; } #endif @@ -6984,15 +6985,15 @@ static PyObject* posix_getresuid (PyObject *self, PyObject *noargs) { - uid_t ruid, euid, suid; - long l_ruid, l_euid, l_suid; - if (getresuid(&ruid, &euid, &suid) < 0) - return posix_error(); - /* Force the values into long's as we don't know the size of uid_t. */ - l_ruid = ruid; - l_euid = euid; - l_suid = suid; - return Py_BuildValue("(lll)", l_ruid, l_euid, l_suid); + uid_t ruid, euid, suid; + long l_ruid, l_euid, l_suid; + if (getresuid(&ruid, &euid, &suid) < 0) + return posix_error(); + /* Force the values into long's as we don't know the size of uid_t. */ + l_ruid = ruid; + l_euid = euid; + l_suid = suid; + return Py_BuildValue("(lll)", l_ruid, l_euid, l_suid); } #endif @@ -7004,332 +7005,332 @@ static PyObject* posix_getresgid (PyObject *self, PyObject *noargs) { - uid_t rgid, egid, sgid; - long l_rgid, l_egid, l_sgid; - if (getresgid(&rgid, &egid, &sgid) < 0) - return posix_error(); - /* Force the values into long's as we don't know the size of uid_t. */ - l_rgid = rgid; - l_egid = egid; - l_sgid = sgid; - return Py_BuildValue("(lll)", l_rgid, l_egid, l_sgid); + uid_t rgid, egid, sgid; + long l_rgid, l_egid, l_sgid; + if (getresgid(&rgid, &egid, &sgid) < 0) + return posix_error(); + /* Force the values into long's as we don't know the size of uid_t. */ + l_rgid = rgid; + l_egid = egid; + l_sgid = sgid; + return Py_BuildValue("(lll)", l_rgid, l_egid, l_sgid); } #endif static PyMethodDef posix_methods[] = { - {"access", posix_access, METH_VARARGS, posix_access__doc__}, + {"access", posix_access, METH_VARARGS, posix_access__doc__}, #ifdef HAVE_TTYNAME - {"ttyname", posix_ttyname, METH_VARARGS, posix_ttyname__doc__}, + {"ttyname", posix_ttyname, METH_VARARGS, posix_ttyname__doc__}, #endif - {"chdir", posix_chdir, METH_VARARGS, posix_chdir__doc__}, + {"chdir", posix_chdir, METH_VARARGS, posix_chdir__doc__}, #ifdef HAVE_CHFLAGS - {"chflags", posix_chflags, METH_VARARGS, posix_chflags__doc__}, + {"chflags", posix_chflags, METH_VARARGS, posix_chflags__doc__}, #endif /* HAVE_CHFLAGS */ - {"chmod", posix_chmod, METH_VARARGS, posix_chmod__doc__}, + {"chmod", posix_chmod, METH_VARARGS, posix_chmod__doc__}, #ifdef HAVE_FCHMOD - {"fchmod", posix_fchmod, METH_VARARGS, posix_fchmod__doc__}, + {"fchmod", posix_fchmod, METH_VARARGS, posix_fchmod__doc__}, #endif /* HAVE_FCHMOD */ #ifdef HAVE_CHOWN - {"chown", posix_chown, METH_VARARGS, posix_chown__doc__}, + {"chown", posix_chown, METH_VARARGS, posix_chown__doc__}, #endif /* HAVE_CHOWN */ #ifdef HAVE_LCHMOD - {"lchmod", posix_lchmod, METH_VARARGS, posix_lchmod__doc__}, + {"lchmod", posix_lchmod, METH_VARARGS, posix_lchmod__doc__}, #endif /* HAVE_LCHMOD */ #ifdef HAVE_FCHOWN - {"fchown", posix_fchown, METH_VARARGS, posix_fchown__doc__}, + {"fchown", posix_fchown, METH_VARARGS, posix_fchown__doc__}, #endif /* HAVE_FCHOWN */ #ifdef HAVE_LCHFLAGS - {"lchflags", posix_lchflags, METH_VARARGS, posix_lchflags__doc__}, + {"lchflags", posix_lchflags, METH_VARARGS, posix_lchflags__doc__}, #endif /* HAVE_LCHFLAGS */ #ifdef HAVE_LCHOWN - {"lchown", posix_lchown, METH_VARARGS, posix_lchown__doc__}, + {"lchown", posix_lchown, METH_VARARGS, posix_lchown__doc__}, #endif /* HAVE_LCHOWN */ #ifdef HAVE_CHROOT - {"chroot", posix_chroot, METH_VARARGS, posix_chroot__doc__}, + {"chroot", posix_chroot, METH_VARARGS, posix_chroot__doc__}, #endif #ifdef HAVE_CTERMID - {"ctermid", posix_ctermid, METH_NOARGS, posix_ctermid__doc__}, + {"ctermid", posix_ctermid, METH_NOARGS, posix_ctermid__doc__}, #endif #ifdef HAVE_GETCWD - {"getcwd", (PyCFunction)posix_getcwd_unicode, - METH_NOARGS, posix_getcwd__doc__}, - {"getcwdb", (PyCFunction)posix_getcwd_bytes, - METH_NOARGS, posix_getcwdb__doc__}, + {"getcwd", (PyCFunction)posix_getcwd_unicode, + METH_NOARGS, posix_getcwd__doc__}, + {"getcwdb", (PyCFunction)posix_getcwd_bytes, + METH_NOARGS, posix_getcwdb__doc__}, #endif #ifdef HAVE_LINK - {"link", posix_link, METH_VARARGS, posix_link__doc__}, + {"link", posix_link, METH_VARARGS, posix_link__doc__}, #endif /* HAVE_LINK */ - {"listdir", posix_listdir, METH_VARARGS, posix_listdir__doc__}, - {"lstat", posix_lstat, METH_VARARGS, posix_lstat__doc__}, - {"mkdir", posix_mkdir, METH_VARARGS, posix_mkdir__doc__}, + {"listdir", posix_listdir, METH_VARARGS, posix_listdir__doc__}, + {"lstat", posix_lstat, METH_VARARGS, posix_lstat__doc__}, + {"mkdir", posix_mkdir, METH_VARARGS, posix_mkdir__doc__}, #ifdef HAVE_NICE - {"nice", posix_nice, METH_VARARGS, posix_nice__doc__}, + {"nice", posix_nice, METH_VARARGS, posix_nice__doc__}, #endif /* HAVE_NICE */ #ifdef HAVE_READLINK - {"readlink", posix_readlink, METH_VARARGS, posix_readlink__doc__}, + {"readlink", posix_readlink, METH_VARARGS, posix_readlink__doc__}, #endif /* HAVE_READLINK */ - {"rename", posix_rename, METH_VARARGS, posix_rename__doc__}, - {"rmdir", posix_rmdir, METH_VARARGS, posix_rmdir__doc__}, - {"stat", posix_stat, METH_VARARGS, posix_stat__doc__}, - {"stat_float_times", stat_float_times, METH_VARARGS, stat_float_times__doc__}, + {"rename", posix_rename, METH_VARARGS, posix_rename__doc__}, + {"rmdir", posix_rmdir, METH_VARARGS, posix_rmdir__doc__}, + {"stat", posix_stat, METH_VARARGS, posix_stat__doc__}, + {"stat_float_times", stat_float_times, METH_VARARGS, stat_float_times__doc__}, #ifdef HAVE_SYMLINK - {"symlink", posix_symlink, METH_VARARGS, posix_symlink__doc__}, + {"symlink", posix_symlink, METH_VARARGS, posix_symlink__doc__}, #endif /* HAVE_SYMLINK */ #ifdef HAVE_SYSTEM - {"system", posix_system, METH_VARARGS, posix_system__doc__}, + {"system", posix_system, METH_VARARGS, posix_system__doc__}, #endif - {"umask", posix_umask, METH_VARARGS, posix_umask__doc__}, + {"umask", posix_umask, METH_VARARGS, posix_umask__doc__}, #ifdef HAVE_UNAME - {"uname", posix_uname, METH_NOARGS, posix_uname__doc__}, + {"uname", posix_uname, METH_NOARGS, posix_uname__doc__}, #endif /* HAVE_UNAME */ - {"unlink", posix_unlink, METH_VARARGS, posix_unlink__doc__}, - {"remove", posix_unlink, METH_VARARGS, posix_remove__doc__}, - {"utime", posix_utime, METH_VARARGS, posix_utime__doc__}, + {"unlink", posix_unlink, METH_VARARGS, posix_unlink__doc__}, + {"remove", posix_unlink, METH_VARARGS, posix_remove__doc__}, + {"utime", posix_utime, METH_VARARGS, posix_utime__doc__}, #ifdef HAVE_TIMES - {"times", posix_times, METH_NOARGS, posix_times__doc__}, + {"times", posix_times, METH_NOARGS, posix_times__doc__}, #endif /* HAVE_TIMES */ - {"_exit", posix__exit, METH_VARARGS, posix__exit__doc__}, + {"_exit", posix__exit, METH_VARARGS, posix__exit__doc__}, #ifdef HAVE_EXECV - {"execv", posix_execv, METH_VARARGS, posix_execv__doc__}, - {"execve", posix_execve, METH_VARARGS, posix_execve__doc__}, + {"execv", posix_execv, METH_VARARGS, posix_execv__doc__}, + {"execve", posix_execve, METH_VARARGS, posix_execve__doc__}, #endif /* HAVE_EXECV */ #ifdef HAVE_SPAWNV - {"spawnv", posix_spawnv, METH_VARARGS, posix_spawnv__doc__}, - {"spawnve", posix_spawnve, METH_VARARGS, posix_spawnve__doc__}, + {"spawnv", posix_spawnv, METH_VARARGS, posix_spawnv__doc__}, + {"spawnve", posix_spawnve, METH_VARARGS, posix_spawnve__doc__}, #if defined(PYOS_OS2) - {"spawnvp", posix_spawnvp, METH_VARARGS, posix_spawnvp__doc__}, - {"spawnvpe", posix_spawnvpe, METH_VARARGS, posix_spawnvpe__doc__}, + {"spawnvp", posix_spawnvp, METH_VARARGS, posix_spawnvp__doc__}, + {"spawnvpe", posix_spawnvpe, METH_VARARGS, posix_spawnvpe__doc__}, #endif /* PYOS_OS2 */ #endif /* HAVE_SPAWNV */ #ifdef HAVE_FORK1 - {"fork1", posix_fork1, METH_NOARGS, posix_fork1__doc__}, + {"fork1", posix_fork1, METH_NOARGS, posix_fork1__doc__}, #endif /* HAVE_FORK1 */ #ifdef HAVE_FORK - {"fork", posix_fork, METH_NOARGS, posix_fork__doc__}, + {"fork", posix_fork, METH_NOARGS, posix_fork__doc__}, #endif /* HAVE_FORK */ #if defined(HAVE_OPENPTY) || defined(HAVE__GETPTY) || defined(HAVE_DEV_PTMX) - {"openpty", posix_openpty, METH_NOARGS, posix_openpty__doc__}, + {"openpty", posix_openpty, METH_NOARGS, posix_openpty__doc__}, #endif /* HAVE_OPENPTY || HAVE__GETPTY || HAVE_DEV_PTMX */ #ifdef HAVE_FORKPTY - {"forkpty", posix_forkpty, METH_NOARGS, posix_forkpty__doc__}, + {"forkpty", posix_forkpty, METH_NOARGS, posix_forkpty__doc__}, #endif /* HAVE_FORKPTY */ #ifdef HAVE_GETEGID - {"getegid", posix_getegid, METH_NOARGS, posix_getegid__doc__}, + {"getegid", posix_getegid, METH_NOARGS, posix_getegid__doc__}, #endif /* HAVE_GETEGID */ #ifdef HAVE_GETEUID - {"geteuid", posix_geteuid, METH_NOARGS, posix_geteuid__doc__}, + {"geteuid", posix_geteuid, METH_NOARGS, posix_geteuid__doc__}, #endif /* HAVE_GETEUID */ #ifdef HAVE_GETGID - {"getgid", posix_getgid, METH_NOARGS, posix_getgid__doc__}, + {"getgid", posix_getgid, METH_NOARGS, posix_getgid__doc__}, #endif /* HAVE_GETGID */ #ifdef HAVE_GETGROUPS - {"getgroups", posix_getgroups, METH_NOARGS, posix_getgroups__doc__}, + {"getgroups", posix_getgroups, METH_NOARGS, posix_getgroups__doc__}, #endif - {"getpid", posix_getpid, METH_NOARGS, posix_getpid__doc__}, + {"getpid", posix_getpid, METH_NOARGS, posix_getpid__doc__}, #ifdef HAVE_GETPGRP - {"getpgrp", posix_getpgrp, METH_NOARGS, posix_getpgrp__doc__}, + {"getpgrp", posix_getpgrp, METH_NOARGS, posix_getpgrp__doc__}, #endif /* HAVE_GETPGRP */ #ifdef HAVE_GETPPID - {"getppid", posix_getppid, METH_NOARGS, posix_getppid__doc__}, + {"getppid", posix_getppid, METH_NOARGS, posix_getppid__doc__}, #endif /* HAVE_GETPPID */ #ifdef HAVE_GETUID - {"getuid", posix_getuid, METH_NOARGS, posix_getuid__doc__}, + {"getuid", posix_getuid, METH_NOARGS, posix_getuid__doc__}, #endif /* HAVE_GETUID */ #ifdef HAVE_GETLOGIN - {"getlogin", posix_getlogin, METH_NOARGS, posix_getlogin__doc__}, + {"getlogin", posix_getlogin, METH_NOARGS, posix_getlogin__doc__}, #endif #ifdef HAVE_KILL - {"kill", posix_kill, METH_VARARGS, posix_kill__doc__}, + {"kill", posix_kill, METH_VARARGS, posix_kill__doc__}, #endif /* HAVE_KILL */ #ifdef HAVE_KILLPG - {"killpg", posix_killpg, METH_VARARGS, posix_killpg__doc__}, + {"killpg", posix_killpg, METH_VARARGS, posix_killpg__doc__}, #endif /* HAVE_KILLPG */ #ifdef HAVE_PLOCK - {"plock", posix_plock, METH_VARARGS, posix_plock__doc__}, + {"plock", posix_plock, METH_VARARGS, posix_plock__doc__}, #endif /* HAVE_PLOCK */ #ifdef MS_WINDOWS - {"startfile", win32_startfile, METH_VARARGS, win32_startfile__doc__}, - {"kill", win32_kill, METH_VARARGS, win32_kill__doc__}, + {"startfile", win32_startfile, METH_VARARGS, win32_startfile__doc__}, + {"kill", win32_kill, METH_VARARGS, win32_kill__doc__}, #endif #ifdef HAVE_SETUID - {"setuid", posix_setuid, METH_VARARGS, posix_setuid__doc__}, + {"setuid", posix_setuid, METH_VARARGS, posix_setuid__doc__}, #endif /* HAVE_SETUID */ #ifdef HAVE_SETEUID - {"seteuid", posix_seteuid, METH_VARARGS, posix_seteuid__doc__}, + {"seteuid", posix_seteuid, METH_VARARGS, posix_seteuid__doc__}, #endif /* HAVE_SETEUID */ #ifdef HAVE_SETEGID - {"setegid", posix_setegid, METH_VARARGS, posix_setegid__doc__}, + {"setegid", posix_setegid, METH_VARARGS, posix_setegid__doc__}, #endif /* HAVE_SETEGID */ #ifdef HAVE_SETREUID - {"setreuid", posix_setreuid, METH_VARARGS, posix_setreuid__doc__}, + {"setreuid", posix_setreuid, METH_VARARGS, posix_setreuid__doc__}, #endif /* HAVE_SETREUID */ #ifdef HAVE_SETREGID - {"setregid", posix_setregid, METH_VARARGS, posix_setregid__doc__}, + {"setregid", posix_setregid, METH_VARARGS, posix_setregid__doc__}, #endif /* HAVE_SETREGID */ #ifdef HAVE_SETGID - {"setgid", posix_setgid, METH_VARARGS, posix_setgid__doc__}, + {"setgid", posix_setgid, METH_VARARGS, posix_setgid__doc__}, #endif /* HAVE_SETGID */ #ifdef HAVE_SETGROUPS - {"setgroups", posix_setgroups, METH_O, posix_setgroups__doc__}, + {"setgroups", posix_setgroups, METH_O, posix_setgroups__doc__}, #endif /* HAVE_SETGROUPS */ #ifdef HAVE_INITGROUPS - {"initgroups", posix_initgroups, METH_VARARGS, posix_initgroups__doc__}, + {"initgroups", posix_initgroups, METH_VARARGS, posix_initgroups__doc__}, #endif /* HAVE_INITGROUPS */ #ifdef HAVE_GETPGID - {"getpgid", posix_getpgid, METH_VARARGS, posix_getpgid__doc__}, + {"getpgid", posix_getpgid, METH_VARARGS, posix_getpgid__doc__}, #endif /* HAVE_GETPGID */ #ifdef HAVE_SETPGRP - {"setpgrp", posix_setpgrp, METH_NOARGS, posix_setpgrp__doc__}, + {"setpgrp", posix_setpgrp, METH_NOARGS, posix_setpgrp__doc__}, #endif /* HAVE_SETPGRP */ #ifdef HAVE_WAIT - {"wait", posix_wait, METH_NOARGS, posix_wait__doc__}, + {"wait", posix_wait, METH_NOARGS, posix_wait__doc__}, #endif /* HAVE_WAIT */ #ifdef HAVE_WAIT3 - {"wait3", posix_wait3, METH_VARARGS, posix_wait3__doc__}, + {"wait3", posix_wait3, METH_VARARGS, posix_wait3__doc__}, #endif /* HAVE_WAIT3 */ #ifdef HAVE_WAIT4 - {"wait4", posix_wait4, METH_VARARGS, posix_wait4__doc__}, + {"wait4", posix_wait4, METH_VARARGS, posix_wait4__doc__}, #endif /* HAVE_WAIT4 */ #if defined(HAVE_WAITPID) || defined(HAVE_CWAIT) - {"waitpid", posix_waitpid, METH_VARARGS, posix_waitpid__doc__}, + {"waitpid", posix_waitpid, METH_VARARGS, posix_waitpid__doc__}, #endif /* HAVE_WAITPID */ #ifdef HAVE_GETSID - {"getsid", posix_getsid, METH_VARARGS, posix_getsid__doc__}, + {"getsid", posix_getsid, METH_VARARGS, posix_getsid__doc__}, #endif /* HAVE_GETSID */ #ifdef HAVE_SETSID - {"setsid", posix_setsid, METH_NOARGS, posix_setsid__doc__}, + {"setsid", posix_setsid, METH_NOARGS, posix_setsid__doc__}, #endif /* HAVE_SETSID */ #ifdef HAVE_SETPGID - {"setpgid", posix_setpgid, METH_VARARGS, posix_setpgid__doc__}, + {"setpgid", posix_setpgid, METH_VARARGS, posix_setpgid__doc__}, #endif /* HAVE_SETPGID */ #ifdef HAVE_TCGETPGRP - {"tcgetpgrp", posix_tcgetpgrp, METH_VARARGS, posix_tcgetpgrp__doc__}, + {"tcgetpgrp", posix_tcgetpgrp, METH_VARARGS, posix_tcgetpgrp__doc__}, #endif /* HAVE_TCGETPGRP */ #ifdef HAVE_TCSETPGRP - {"tcsetpgrp", posix_tcsetpgrp, METH_VARARGS, posix_tcsetpgrp__doc__}, + {"tcsetpgrp", posix_tcsetpgrp, METH_VARARGS, posix_tcsetpgrp__doc__}, #endif /* HAVE_TCSETPGRP */ - {"open", posix_open, METH_VARARGS, posix_open__doc__}, - {"close", posix_close, METH_VARARGS, posix_close__doc__}, - {"closerange", posix_closerange, METH_VARARGS, posix_closerange__doc__}, - {"device_encoding", device_encoding, METH_VARARGS, device_encoding__doc__}, - {"dup", posix_dup, METH_VARARGS, posix_dup__doc__}, - {"dup2", posix_dup2, METH_VARARGS, posix_dup2__doc__}, - {"lseek", posix_lseek, METH_VARARGS, posix_lseek__doc__}, - {"read", posix_read, METH_VARARGS, posix_read__doc__}, - {"write", posix_write, METH_VARARGS, posix_write__doc__}, - {"fstat", posix_fstat, METH_VARARGS, posix_fstat__doc__}, - {"isatty", posix_isatty, METH_VARARGS, posix_isatty__doc__}, + {"open", posix_open, METH_VARARGS, posix_open__doc__}, + {"close", posix_close, METH_VARARGS, posix_close__doc__}, + {"closerange", posix_closerange, METH_VARARGS, posix_closerange__doc__}, + {"device_encoding", device_encoding, METH_VARARGS, device_encoding__doc__}, + {"dup", posix_dup, METH_VARARGS, posix_dup__doc__}, + {"dup2", posix_dup2, METH_VARARGS, posix_dup2__doc__}, + {"lseek", posix_lseek, METH_VARARGS, posix_lseek__doc__}, + {"read", posix_read, METH_VARARGS, posix_read__doc__}, + {"write", posix_write, METH_VARARGS, posix_write__doc__}, + {"fstat", posix_fstat, METH_VARARGS, posix_fstat__doc__}, + {"isatty", posix_isatty, METH_VARARGS, posix_isatty__doc__}, #ifdef HAVE_PIPE - {"pipe", posix_pipe, METH_NOARGS, posix_pipe__doc__}, + {"pipe", posix_pipe, METH_NOARGS, posix_pipe__doc__}, #endif #ifdef HAVE_MKFIFO - {"mkfifo", posix_mkfifo, METH_VARARGS, posix_mkfifo__doc__}, + {"mkfifo", posix_mkfifo, METH_VARARGS, posix_mkfifo__doc__}, #endif #if defined(HAVE_MKNOD) && defined(HAVE_MAKEDEV) - {"mknod", posix_mknod, METH_VARARGS, posix_mknod__doc__}, + {"mknod", posix_mknod, METH_VARARGS, posix_mknod__doc__}, #endif #ifdef HAVE_DEVICE_MACROS - {"major", posix_major, METH_VARARGS, posix_major__doc__}, - {"minor", posix_minor, METH_VARARGS, posix_minor__doc__}, - {"makedev", posix_makedev, METH_VARARGS, posix_makedev__doc__}, + {"major", posix_major, METH_VARARGS, posix_major__doc__}, + {"minor", posix_minor, METH_VARARGS, posix_minor__doc__}, + {"makedev", posix_makedev, METH_VARARGS, posix_makedev__doc__}, #endif #ifdef HAVE_FTRUNCATE - {"ftruncate", posix_ftruncate, METH_VARARGS, posix_ftruncate__doc__}, + {"ftruncate", posix_ftruncate, METH_VARARGS, posix_ftruncate__doc__}, #endif #ifdef HAVE_PUTENV - {"putenv", posix_putenv, METH_VARARGS, posix_putenv__doc__}, + {"putenv", posix_putenv, METH_VARARGS, posix_putenv__doc__}, #endif #ifdef HAVE_UNSETENV - {"unsetenv", posix_unsetenv, METH_VARARGS, posix_unsetenv__doc__}, + {"unsetenv", posix_unsetenv, METH_VARARGS, posix_unsetenv__doc__}, #endif - {"strerror", posix_strerror, METH_VARARGS, posix_strerror__doc__}, + {"strerror", posix_strerror, METH_VARARGS, posix_strerror__doc__}, #ifdef HAVE_FCHDIR - {"fchdir", posix_fchdir, METH_O, posix_fchdir__doc__}, + {"fchdir", posix_fchdir, METH_O, posix_fchdir__doc__}, #endif #ifdef HAVE_FSYNC - {"fsync", posix_fsync, METH_O, posix_fsync__doc__}, + {"fsync", posix_fsync, METH_O, posix_fsync__doc__}, #endif #ifdef HAVE_FDATASYNC - {"fdatasync", posix_fdatasync, METH_O, posix_fdatasync__doc__}, + {"fdatasync", posix_fdatasync, METH_O, posix_fdatasync__doc__}, #endif #ifdef HAVE_SYS_WAIT_H #ifdef WCOREDUMP - {"WCOREDUMP", posix_WCOREDUMP, METH_VARARGS, posix_WCOREDUMP__doc__}, + {"WCOREDUMP", posix_WCOREDUMP, METH_VARARGS, posix_WCOREDUMP__doc__}, #endif /* WCOREDUMP */ #ifdef WIFCONTINUED - {"WIFCONTINUED",posix_WIFCONTINUED, METH_VARARGS, posix_WIFCONTINUED__doc__}, + {"WIFCONTINUED",posix_WIFCONTINUED, METH_VARARGS, posix_WIFCONTINUED__doc__}, #endif /* WIFCONTINUED */ #ifdef WIFSTOPPED - {"WIFSTOPPED", posix_WIFSTOPPED, METH_VARARGS, posix_WIFSTOPPED__doc__}, + {"WIFSTOPPED", posix_WIFSTOPPED, METH_VARARGS, posix_WIFSTOPPED__doc__}, #endif /* WIFSTOPPED */ #ifdef WIFSIGNALED - {"WIFSIGNALED", posix_WIFSIGNALED, METH_VARARGS, posix_WIFSIGNALED__doc__}, + {"WIFSIGNALED", posix_WIFSIGNALED, METH_VARARGS, posix_WIFSIGNALED__doc__}, #endif /* WIFSIGNALED */ #ifdef WIFEXITED - {"WIFEXITED", posix_WIFEXITED, METH_VARARGS, posix_WIFEXITED__doc__}, + {"WIFEXITED", posix_WIFEXITED, METH_VARARGS, posix_WIFEXITED__doc__}, #endif /* WIFEXITED */ #ifdef WEXITSTATUS - {"WEXITSTATUS", posix_WEXITSTATUS, METH_VARARGS, posix_WEXITSTATUS__doc__}, + {"WEXITSTATUS", posix_WEXITSTATUS, METH_VARARGS, posix_WEXITSTATUS__doc__}, #endif /* WEXITSTATUS */ #ifdef WTERMSIG - {"WTERMSIG", posix_WTERMSIG, METH_VARARGS, posix_WTERMSIG__doc__}, + {"WTERMSIG", posix_WTERMSIG, METH_VARARGS, posix_WTERMSIG__doc__}, #endif /* WTERMSIG */ #ifdef WSTOPSIG - {"WSTOPSIG", posix_WSTOPSIG, METH_VARARGS, posix_WSTOPSIG__doc__}, + {"WSTOPSIG", posix_WSTOPSIG, METH_VARARGS, posix_WSTOPSIG__doc__}, #endif /* WSTOPSIG */ #endif /* HAVE_SYS_WAIT_H */ #if defined(HAVE_FSTATVFS) && defined(HAVE_SYS_STATVFS_H) - {"fstatvfs", posix_fstatvfs, METH_VARARGS, posix_fstatvfs__doc__}, + {"fstatvfs", posix_fstatvfs, METH_VARARGS, posix_fstatvfs__doc__}, #endif #if defined(HAVE_STATVFS) && defined(HAVE_SYS_STATVFS_H) - {"statvfs", posix_statvfs, METH_VARARGS, posix_statvfs__doc__}, + {"statvfs", posix_statvfs, METH_VARARGS, posix_statvfs__doc__}, #endif #ifdef HAVE_CONFSTR - {"confstr", posix_confstr, METH_VARARGS, posix_confstr__doc__}, + {"confstr", posix_confstr, METH_VARARGS, posix_confstr__doc__}, #endif #ifdef HAVE_SYSCONF - {"sysconf", posix_sysconf, METH_VARARGS, posix_sysconf__doc__}, + {"sysconf", posix_sysconf, METH_VARARGS, posix_sysconf__doc__}, #endif #ifdef HAVE_FPATHCONF - {"fpathconf", posix_fpathconf, METH_VARARGS, posix_fpathconf__doc__}, + {"fpathconf", posix_fpathconf, METH_VARARGS, posix_fpathconf__doc__}, #endif #ifdef HAVE_PATHCONF - {"pathconf", posix_pathconf, METH_VARARGS, posix_pathconf__doc__}, + {"pathconf", posix_pathconf, METH_VARARGS, posix_pathconf__doc__}, #endif - {"abort", posix_abort, METH_NOARGS, posix_abort__doc__}, + {"abort", posix_abort, METH_NOARGS, posix_abort__doc__}, #ifdef MS_WINDOWS - {"_getfullpathname", posix__getfullpathname, METH_VARARGS, NULL}, + {"_getfullpathname", posix__getfullpathname, METH_VARARGS, NULL}, #endif #ifdef HAVE_GETLOADAVG - {"getloadavg", posix_getloadavg, METH_NOARGS, posix_getloadavg__doc__}, + {"getloadavg", posix_getloadavg, METH_NOARGS, posix_getloadavg__doc__}, #endif #ifdef MS_WINDOWS - {"urandom", win32_urandom, METH_VARARGS, win32_urandom__doc__}, + {"urandom", win32_urandom, METH_VARARGS, win32_urandom__doc__}, #endif #ifdef __VMS - {"urandom", vms_urandom, METH_VARARGS, vms_urandom__doc__}, + {"urandom", vms_urandom, METH_VARARGS, vms_urandom__doc__}, #endif #ifdef HAVE_SETRESUID - {"setresuid", posix_setresuid, METH_VARARGS, posix_setresuid__doc__}, + {"setresuid", posix_setresuid, METH_VARARGS, posix_setresuid__doc__}, #endif #ifdef HAVE_SETRESGID - {"setresgid", posix_setresgid, METH_VARARGS, posix_setresgid__doc__}, + {"setresgid", posix_setresgid, METH_VARARGS, posix_setresgid__doc__}, #endif #ifdef HAVE_GETRESUID - {"getresuid", posix_getresuid, METH_NOARGS, posix_getresuid__doc__}, + {"getresuid", posix_getresuid, METH_NOARGS, posix_getresuid__doc__}, #endif #ifdef HAVE_GETRESGID - {"getresgid", posix_getresgid, METH_NOARGS, posix_getresgid__doc__}, + {"getresgid", posix_getresgid, METH_NOARGS, posix_getresgid__doc__}, #endif - {NULL, NULL} /* Sentinel */ + {NULL, NULL} /* Sentinel */ }; static int ins(PyObject *module, char *symbol, long value) { - return PyModule_AddIntConstant(module, symbol, value); + return PyModule_AddIntConstant(module, symbol, value); } #if defined(PYOS_OS2) @@ -7367,7 +7368,7 @@ case 50: ver = "5.00"; break; default: PyOS_snprintf(tmp, sizeof(tmp), - "%d-%d", values[QSV_VERSION_MAJOR], + "%d-%d", values[QSV_VERSION_MAJOR], values[QSV_VERSION_MINOR]); ver = &tmp[0]; } @@ -7389,221 +7390,221 @@ all_ins(PyObject *d) { #ifdef F_OK - if (ins(d, "F_OK", (long)F_OK)) return -1; + if (ins(d, "F_OK", (long)F_OK)) return -1; #endif #ifdef R_OK - if (ins(d, "R_OK", (long)R_OK)) return -1; + if (ins(d, "R_OK", (long)R_OK)) return -1; #endif #ifdef W_OK - if (ins(d, "W_OK", (long)W_OK)) return -1; + if (ins(d, "W_OK", (long)W_OK)) return -1; #endif #ifdef X_OK - if (ins(d, "X_OK", (long)X_OK)) return -1; + if (ins(d, "X_OK", (long)X_OK)) return -1; #endif #ifdef NGROUPS_MAX - if (ins(d, "NGROUPS_MAX", (long)NGROUPS_MAX)) return -1; + if (ins(d, "NGROUPS_MAX", (long)NGROUPS_MAX)) return -1; #endif #ifdef TMP_MAX - if (ins(d, "TMP_MAX", (long)TMP_MAX)) return -1; + if (ins(d, "TMP_MAX", (long)TMP_MAX)) return -1; #endif #ifdef WCONTINUED - if (ins(d, "WCONTINUED", (long)WCONTINUED)) return -1; + if (ins(d, "WCONTINUED", (long)WCONTINUED)) return -1; #endif #ifdef WNOHANG - if (ins(d, "WNOHANG", (long)WNOHANG)) return -1; + if (ins(d, "WNOHANG", (long)WNOHANG)) return -1; #endif #ifdef WUNTRACED - if (ins(d, "WUNTRACED", (long)WUNTRACED)) return -1; + if (ins(d, "WUNTRACED", (long)WUNTRACED)) return -1; #endif #ifdef O_RDONLY - if (ins(d, "O_RDONLY", (long)O_RDONLY)) return -1; + if (ins(d, "O_RDONLY", (long)O_RDONLY)) return -1; #endif #ifdef O_WRONLY - if (ins(d, "O_WRONLY", (long)O_WRONLY)) return -1; + if (ins(d, "O_WRONLY", (long)O_WRONLY)) return -1; #endif #ifdef O_RDWR - if (ins(d, "O_RDWR", (long)O_RDWR)) return -1; + if (ins(d, "O_RDWR", (long)O_RDWR)) return -1; #endif #ifdef O_NDELAY - if (ins(d, "O_NDELAY", (long)O_NDELAY)) return -1; + if (ins(d, "O_NDELAY", (long)O_NDELAY)) return -1; #endif #ifdef O_NONBLOCK - if (ins(d, "O_NONBLOCK", (long)O_NONBLOCK)) return -1; + if (ins(d, "O_NONBLOCK", (long)O_NONBLOCK)) return -1; #endif #ifdef O_APPEND - if (ins(d, "O_APPEND", (long)O_APPEND)) return -1; + if (ins(d, "O_APPEND", (long)O_APPEND)) return -1; #endif #ifdef O_DSYNC - if (ins(d, "O_DSYNC", (long)O_DSYNC)) return -1; + if (ins(d, "O_DSYNC", (long)O_DSYNC)) return -1; #endif #ifdef O_RSYNC - if (ins(d, "O_RSYNC", (long)O_RSYNC)) return -1; + if (ins(d, "O_RSYNC", (long)O_RSYNC)) return -1; #endif #ifdef O_SYNC - if (ins(d, "O_SYNC", (long)O_SYNC)) return -1; + if (ins(d, "O_SYNC", (long)O_SYNC)) return -1; #endif #ifdef O_NOCTTY - if (ins(d, "O_NOCTTY", (long)O_NOCTTY)) return -1; + if (ins(d, "O_NOCTTY", (long)O_NOCTTY)) return -1; #endif #ifdef O_CREAT - if (ins(d, "O_CREAT", (long)O_CREAT)) return -1; + if (ins(d, "O_CREAT", (long)O_CREAT)) return -1; #endif #ifdef O_EXCL - if (ins(d, "O_EXCL", (long)O_EXCL)) return -1; + if (ins(d, "O_EXCL", (long)O_EXCL)) return -1; #endif #ifdef O_TRUNC - if (ins(d, "O_TRUNC", (long)O_TRUNC)) return -1; + if (ins(d, "O_TRUNC", (long)O_TRUNC)) return -1; #endif #ifdef O_BINARY - if (ins(d, "O_BINARY", (long)O_BINARY)) return -1; + if (ins(d, "O_BINARY", (long)O_BINARY)) return -1; #endif #ifdef O_TEXT - if (ins(d, "O_TEXT", (long)O_TEXT)) return -1; + if (ins(d, "O_TEXT", (long)O_TEXT)) return -1; #endif #ifdef O_LARGEFILE - if (ins(d, "O_LARGEFILE", (long)O_LARGEFILE)) return -1; + if (ins(d, "O_LARGEFILE", (long)O_LARGEFILE)) return -1; #endif #ifdef O_SHLOCK - if (ins(d, "O_SHLOCK", (long)O_SHLOCK)) return -1; + if (ins(d, "O_SHLOCK", (long)O_SHLOCK)) return -1; #endif #ifdef O_EXLOCK - if (ins(d, "O_EXLOCK", (long)O_EXLOCK)) return -1; + if (ins(d, "O_EXLOCK", (long)O_EXLOCK)) return -1; #endif /* MS Windows */ #ifdef O_NOINHERIT - /* Don't inherit in child processes. */ - if (ins(d, "O_NOINHERIT", (long)O_NOINHERIT)) return -1; + /* Don't inherit in child processes. */ + if (ins(d, "O_NOINHERIT", (long)O_NOINHERIT)) return -1; #endif #ifdef _O_SHORT_LIVED - /* Optimize for short life (keep in memory). */ - /* MS forgot to define this one with a non-underscore form too. */ - if (ins(d, "O_SHORT_LIVED", (long)_O_SHORT_LIVED)) return -1; + /* Optimize for short life (keep in memory). */ + /* MS forgot to define this one with a non-underscore form too. */ + if (ins(d, "O_SHORT_LIVED", (long)_O_SHORT_LIVED)) return -1; #endif #ifdef O_TEMPORARY - /* Automatically delete when last handle is closed. */ - if (ins(d, "O_TEMPORARY", (long)O_TEMPORARY)) return -1; + /* Automatically delete when last handle is closed. */ + if (ins(d, "O_TEMPORARY", (long)O_TEMPORARY)) return -1; #endif #ifdef O_RANDOM - /* Optimize for random access. */ - if (ins(d, "O_RANDOM", (long)O_RANDOM)) return -1; + /* Optimize for random access. */ + if (ins(d, "O_RANDOM", (long)O_RANDOM)) return -1; #endif #ifdef O_SEQUENTIAL - /* Optimize for sequential access. */ - if (ins(d, "O_SEQUENTIAL", (long)O_SEQUENTIAL)) return -1; + /* Optimize for sequential access. */ + if (ins(d, "O_SEQUENTIAL", (long)O_SEQUENTIAL)) return -1; #endif /* GNU extensions. */ #ifdef O_ASYNC - /* Send a SIGIO signal whenever input or output - becomes available on file descriptor */ - if (ins(d, "O_ASYNC", (long)O_ASYNC)) return -1; + /* Send a SIGIO signal whenever input or output + becomes available on file descriptor */ + if (ins(d, "O_ASYNC", (long)O_ASYNC)) return -1; #endif #ifdef O_DIRECT - /* Direct disk access. */ - if (ins(d, "O_DIRECT", (long)O_DIRECT)) return -1; + /* Direct disk access. */ + if (ins(d, "O_DIRECT", (long)O_DIRECT)) return -1; #endif #ifdef O_DIRECTORY - /* Must be a directory. */ - if (ins(d, "O_DIRECTORY", (long)O_DIRECTORY)) return -1; + /* Must be a directory. */ + if (ins(d, "O_DIRECTORY", (long)O_DIRECTORY)) return -1; #endif #ifdef O_NOFOLLOW - /* Do not follow links. */ - if (ins(d, "O_NOFOLLOW", (long)O_NOFOLLOW)) return -1; + /* Do not follow links. */ + if (ins(d, "O_NOFOLLOW", (long)O_NOFOLLOW)) return -1; #endif #ifdef O_NOATIME - /* Do not update the access time. */ - if (ins(d, "O_NOATIME", (long)O_NOATIME)) return -1; + /* Do not update the access time. */ + if (ins(d, "O_NOATIME", (long)O_NOATIME)) return -1; #endif - /* These come from sysexits.h */ + /* These come from sysexits.h */ #ifdef EX_OK - if (ins(d, "EX_OK", (long)EX_OK)) return -1; + if (ins(d, "EX_OK", (long)EX_OK)) return -1; #endif /* EX_OK */ #ifdef EX_USAGE - if (ins(d, "EX_USAGE", (long)EX_USAGE)) return -1; + if (ins(d, "EX_USAGE", (long)EX_USAGE)) return -1; #endif /* EX_USAGE */ #ifdef EX_DATAERR - if (ins(d, "EX_DATAERR", (long)EX_DATAERR)) return -1; + if (ins(d, "EX_DATAERR", (long)EX_DATAERR)) return -1; #endif /* EX_DATAERR */ #ifdef EX_NOINPUT - if (ins(d, "EX_NOINPUT", (long)EX_NOINPUT)) return -1; + if (ins(d, "EX_NOINPUT", (long)EX_NOINPUT)) return -1; #endif /* EX_NOINPUT */ #ifdef EX_NOUSER - if (ins(d, "EX_NOUSER", (long)EX_NOUSER)) return -1; + if (ins(d, "EX_NOUSER", (long)EX_NOUSER)) return -1; #endif /* EX_NOUSER */ #ifdef EX_NOHOST - if (ins(d, "EX_NOHOST", (long)EX_NOHOST)) return -1; + if (ins(d, "EX_NOHOST", (long)EX_NOHOST)) return -1; #endif /* EX_NOHOST */ #ifdef EX_UNAVAILABLE - if (ins(d, "EX_UNAVAILABLE", (long)EX_UNAVAILABLE)) return -1; + if (ins(d, "EX_UNAVAILABLE", (long)EX_UNAVAILABLE)) return -1; #endif /* EX_UNAVAILABLE */ #ifdef EX_SOFTWARE - if (ins(d, "EX_SOFTWARE", (long)EX_SOFTWARE)) return -1; + if (ins(d, "EX_SOFTWARE", (long)EX_SOFTWARE)) return -1; #endif /* EX_SOFTWARE */ #ifdef EX_OSERR - if (ins(d, "EX_OSERR", (long)EX_OSERR)) return -1; + if (ins(d, "EX_OSERR", (long)EX_OSERR)) return -1; #endif /* EX_OSERR */ #ifdef EX_OSFILE - if (ins(d, "EX_OSFILE", (long)EX_OSFILE)) return -1; + if (ins(d, "EX_OSFILE", (long)EX_OSFILE)) return -1; #endif /* EX_OSFILE */ #ifdef EX_CANTCREAT - if (ins(d, "EX_CANTCREAT", (long)EX_CANTCREAT)) return -1; + if (ins(d, "EX_CANTCREAT", (long)EX_CANTCREAT)) return -1; #endif /* EX_CANTCREAT */ #ifdef EX_IOERR - if (ins(d, "EX_IOERR", (long)EX_IOERR)) return -1; + if (ins(d, "EX_IOERR", (long)EX_IOERR)) return -1; #endif /* EX_IOERR */ #ifdef EX_TEMPFAIL - if (ins(d, "EX_TEMPFAIL", (long)EX_TEMPFAIL)) return -1; + if (ins(d, "EX_TEMPFAIL", (long)EX_TEMPFAIL)) return -1; #endif /* EX_TEMPFAIL */ #ifdef EX_PROTOCOL - if (ins(d, "EX_PROTOCOL", (long)EX_PROTOCOL)) return -1; + if (ins(d, "EX_PROTOCOL", (long)EX_PROTOCOL)) return -1; #endif /* EX_PROTOCOL */ #ifdef EX_NOPERM - if (ins(d, "EX_NOPERM", (long)EX_NOPERM)) return -1; + if (ins(d, "EX_NOPERM", (long)EX_NOPERM)) return -1; #endif /* EX_NOPERM */ #ifdef EX_CONFIG - if (ins(d, "EX_CONFIG", (long)EX_CONFIG)) return -1; + if (ins(d, "EX_CONFIG", (long)EX_CONFIG)) return -1; #endif /* EX_CONFIG */ #ifdef EX_NOTFOUND - if (ins(d, "EX_NOTFOUND", (long)EX_NOTFOUND)) return -1; + if (ins(d, "EX_NOTFOUND", (long)EX_NOTFOUND)) return -1; #endif /* EX_NOTFOUND */ #ifdef HAVE_SPAWNV #if defined(PYOS_OS2) && defined(PYCC_GCC) - if (ins(d, "P_WAIT", (long)P_WAIT)) return -1; - if (ins(d, "P_NOWAIT", (long)P_NOWAIT)) return -1; - if (ins(d, "P_OVERLAY", (long)P_OVERLAY)) return -1; - if (ins(d, "P_DEBUG", (long)P_DEBUG)) return -1; - if (ins(d, "P_SESSION", (long)P_SESSION)) return -1; - if (ins(d, "P_DETACH", (long)P_DETACH)) return -1; - if (ins(d, "P_PM", (long)P_PM)) return -1; - if (ins(d, "P_DEFAULT", (long)P_DEFAULT)) return -1; - if (ins(d, "P_MINIMIZE", (long)P_MINIMIZE)) return -1; - if (ins(d, "P_MAXIMIZE", (long)P_MAXIMIZE)) return -1; - if (ins(d, "P_FULLSCREEN", (long)P_FULLSCREEN)) return -1; - if (ins(d, "P_WINDOWED", (long)P_WINDOWED)) return -1; - if (ins(d, "P_FOREGROUND", (long)P_FOREGROUND)) return -1; - if (ins(d, "P_BACKGROUND", (long)P_BACKGROUND)) return -1; - if (ins(d, "P_NOCLOSE", (long)P_NOCLOSE)) return -1; - if (ins(d, "P_NOSESSION", (long)P_NOSESSION)) return -1; - if (ins(d, "P_QUOTE", (long)P_QUOTE)) return -1; - if (ins(d, "P_TILDE", (long)P_TILDE)) return -1; - if (ins(d, "P_UNRELATED", (long)P_UNRELATED)) return -1; - if (ins(d, "P_DEBUGDESC", (long)P_DEBUGDESC)) return -1; -#else - if (ins(d, "P_WAIT", (long)_P_WAIT)) return -1; - if (ins(d, "P_NOWAIT", (long)_P_NOWAIT)) return -1; - if (ins(d, "P_OVERLAY", (long)_OLD_P_OVERLAY)) return -1; - if (ins(d, "P_NOWAITO", (long)_P_NOWAITO)) return -1; - if (ins(d, "P_DETACH", (long)_P_DETACH)) return -1; + if (ins(d, "P_WAIT", (long)P_WAIT)) return -1; + if (ins(d, "P_NOWAIT", (long)P_NOWAIT)) return -1; + if (ins(d, "P_OVERLAY", (long)P_OVERLAY)) return -1; + if (ins(d, "P_DEBUG", (long)P_DEBUG)) return -1; + if (ins(d, "P_SESSION", (long)P_SESSION)) return -1; + if (ins(d, "P_DETACH", (long)P_DETACH)) return -1; + if (ins(d, "P_PM", (long)P_PM)) return -1; + if (ins(d, "P_DEFAULT", (long)P_DEFAULT)) return -1; + if (ins(d, "P_MINIMIZE", (long)P_MINIMIZE)) return -1; + if (ins(d, "P_MAXIMIZE", (long)P_MAXIMIZE)) return -1; + if (ins(d, "P_FULLSCREEN", (long)P_FULLSCREEN)) return -1; + if (ins(d, "P_WINDOWED", (long)P_WINDOWED)) return -1; + if (ins(d, "P_FOREGROUND", (long)P_FOREGROUND)) return -1; + if (ins(d, "P_BACKGROUND", (long)P_BACKGROUND)) return -1; + if (ins(d, "P_NOCLOSE", (long)P_NOCLOSE)) return -1; + if (ins(d, "P_NOSESSION", (long)P_NOSESSION)) return -1; + if (ins(d, "P_QUOTE", (long)P_QUOTE)) return -1; + if (ins(d, "P_TILDE", (long)P_TILDE)) return -1; + if (ins(d, "P_UNRELATED", (long)P_UNRELATED)) return -1; + if (ins(d, "P_DEBUGDESC", (long)P_DEBUGDESC)) return -1; +#else + if (ins(d, "P_WAIT", (long)_P_WAIT)) return -1; + if (ins(d, "P_NOWAIT", (long)_P_NOWAIT)) return -1; + if (ins(d, "P_OVERLAY", (long)_OLD_P_OVERLAY)) return -1; + if (ins(d, "P_NOWAITO", (long)_P_NOWAITO)) return -1; + if (ins(d, "P_DETACH", (long)_P_DETACH)) return -1; #endif #endif #if defined(PYOS_OS2) - if (insertvalues(d)) return -1; + if (insertvalues(d)) return -1; #endif - return 0; + return 0; } @@ -7621,114 +7622,114 @@ #endif static struct PyModuleDef posixmodule = { - PyModuleDef_HEAD_INIT, - MODNAME, - posix__doc__, - -1, - posix_methods, - NULL, - NULL, - NULL, - NULL + PyModuleDef_HEAD_INIT, + MODNAME, + posix__doc__, + -1, + posix_methods, + NULL, + NULL, + NULL, + NULL }; PyMODINIT_FUNC INITFUNC(void) { - PyObject *m, *v; + PyObject *m, *v; - m = PyModule_Create(&posixmodule); - if (m == NULL) - return NULL; - - /* Initialize environ dictionary */ - v = convertenviron(); - Py_XINCREF(v); - if (v == NULL || PyModule_AddObject(m, "environ", v) != 0) - return NULL; - Py_DECREF(v); + m = PyModule_Create(&posixmodule); + if (m == NULL) + return NULL; - if (all_ins(m)) - return NULL; + /* Initialize environ dictionary */ + v = convertenviron(); + Py_XINCREF(v); + if (v == NULL || PyModule_AddObject(m, "environ", v) != 0) + return NULL; + Py_DECREF(v); - if (setup_confname_tables(m)) - return NULL; + if (all_ins(m)) + return NULL; + + if (setup_confname_tables(m)) + return NULL; - Py_INCREF(PyExc_OSError); - PyModule_AddObject(m, "error", PyExc_OSError); + Py_INCREF(PyExc_OSError); + PyModule_AddObject(m, "error", PyExc_OSError); #ifdef HAVE_PUTENV - if (posix_putenv_garbage == NULL) - posix_putenv_garbage = PyDict_New(); + if (posix_putenv_garbage == NULL) + posix_putenv_garbage = PyDict_New(); #endif - if (!initialized) { - stat_result_desc.name = MODNAME ".stat_result"; - stat_result_desc.fields[7].name = PyStructSequence_UnnamedField; - stat_result_desc.fields[8].name = PyStructSequence_UnnamedField; - stat_result_desc.fields[9].name = PyStructSequence_UnnamedField; - PyStructSequence_InitType(&StatResultType, &stat_result_desc); - structseq_new = StatResultType.tp_new; - StatResultType.tp_new = statresult_new; + if (!initialized) { + stat_result_desc.name = MODNAME ".stat_result"; + stat_result_desc.fields[7].name = PyStructSequence_UnnamedField; + stat_result_desc.fields[8].name = PyStructSequence_UnnamedField; + stat_result_desc.fields[9].name = PyStructSequence_UnnamedField; + PyStructSequence_InitType(&StatResultType, &stat_result_desc); + structseq_new = StatResultType.tp_new; + StatResultType.tp_new = statresult_new; - statvfs_result_desc.name = MODNAME ".statvfs_result"; - PyStructSequence_InitType(&StatVFSResultType, &statvfs_result_desc); + statvfs_result_desc.name = MODNAME ".statvfs_result"; + PyStructSequence_InitType(&StatVFSResultType, &statvfs_result_desc); #ifdef NEED_TICKS_PER_SECOND # if defined(HAVE_SYSCONF) && defined(_SC_CLK_TCK) - ticks_per_second = sysconf(_SC_CLK_TCK); + ticks_per_second = sysconf(_SC_CLK_TCK); # elif defined(HZ) - ticks_per_second = HZ; + ticks_per_second = HZ; # else - ticks_per_second = 60; /* magic fallback value; may be bogus */ + ticks_per_second = 60; /* magic fallback value; may be bogus */ # endif #endif - } - Py_INCREF((PyObject*) &StatResultType); - PyModule_AddObject(m, "stat_result", (PyObject*) &StatResultType); - Py_INCREF((PyObject*) &StatVFSResultType); - PyModule_AddObject(m, "statvfs_result", - (PyObject*) &StatVFSResultType); - initialized = 1; + } + Py_INCREF((PyObject*) &StatResultType); + PyModule_AddObject(m, "stat_result", (PyObject*) &StatResultType); + Py_INCREF((PyObject*) &StatVFSResultType); + PyModule_AddObject(m, "statvfs_result", + (PyObject*) &StatVFSResultType); + initialized = 1; #ifdef __APPLE__ - /* - * Step 2 of weak-linking support on Mac OS X. - * - * The code below removes functions that are not available on the - * currently active platform. - * - * This block allow one to use a python binary that was build on - * OSX 10.4 on OSX 10.3, without loosing access to new APIs on - * OSX 10.4. - */ + /* + * Step 2 of weak-linking support on Mac OS X. + * + * The code below removes functions that are not available on the + * currently active platform. + * + * This block allow one to use a python binary that was build on + * OSX 10.4 on OSX 10.3, without loosing access to new APIs on + * OSX 10.4. + */ #ifdef HAVE_FSTATVFS - if (fstatvfs == NULL) { - if (PyObject_DelAttrString(m, "fstatvfs") == -1) { - return NULL; - } - } + if (fstatvfs == NULL) { + if (PyObject_DelAttrString(m, "fstatvfs") == -1) { + return NULL; + } + } #endif /* HAVE_FSTATVFS */ #ifdef HAVE_STATVFS - if (statvfs == NULL) { - if (PyObject_DelAttrString(m, "statvfs") == -1) { - return NULL; - } - } + if (statvfs == NULL) { + if (PyObject_DelAttrString(m, "statvfs") == -1) { + return NULL; + } + } #endif /* HAVE_STATVFS */ # ifdef HAVE_LCHOWN - if (lchown == NULL) { - if (PyObject_DelAttrString(m, "lchown") == -1) { - return NULL; - } - } + if (lchown == NULL) { + if (PyObject_DelAttrString(m, "lchown") == -1) { + return NULL; + } + } #endif /* HAVE_LCHOWN */ #endif /* __APPLE__ */ - return m; + return m; } From solipsis at pitrou.net Thu May 6 02:10:42 2010 From: solipsis at pitrou.net (Antoine Pitrou) Date: Thu, 6 May 2010 00:10:42 +0000 (UTC) Subject: [Python-checkins] =?utf-8?q?r80846_-_in_python/branches/py3k=3A?= =?utf-8?q?=09Modules/posixmodule=2Ec?= References: <20100506000846.D1A38EE9B7@mail.python.org> Message-ID: writes: > > Author: victor.stinner > Date: Thu May 6 02:08:46 2010 > New Revision: 80846 > [snip] Thank you! cheers Antoine. From python-checkins at python.org Thu May 6 02:20:45 2010 From: python-checkins at python.org (victor.stinner) Date: Thu, 6 May 2010 02:20:45 +0200 (CEST) Subject: [Python-checkins] r80847 - python/branches/release26-maint/Modules/posixmodule.c Message-ID: <20100506002045.05356EE9B7@mail.python.org> Author: victor.stinner Date: Thu May 6 02:20:44 2010 New Revision: 80847 Log: Merged revisions 80844-80845 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r80844 | victor.stinner | 2010-05-06 01:33:33 +0200 (jeu., 06 mai 2010) | 5 lines Untabify Modules/posixmodule.c Run Antoine Pitrou "untabify" script + manual editions (OS/2 and some continuation lines). ........ r80845 | victor.stinner | 2010-05-06 02:03:44 +0200 (jeu., 06 mai 2010) | 4 lines Untabify Modules/posixmodule.c (2) Fix some more functions by hand ........ Modified: python/branches/release26-maint/Modules/posixmodule.c Modified: python/branches/release26-maint/Modules/posixmodule.c ============================================================================== --- python/branches/release26-maint/Modules/posixmodule.c (original) +++ python/branches/release26-maint/Modules/posixmodule.c Thu May 6 02:20:44 2010 @@ -15,7 +15,7 @@ #ifdef __APPLE__ /* - * Step 1 of support for weak-linking a number of symbols existing on + * Step 1 of support for weak-linking a number of symbols existing on * OSX 10.4 and later, see the comment in the #ifdef __APPLE__ block * at the end of this file for more information. */ @@ -73,7 +73,7 @@ #endif /* HAVE_SYS_STAT_H */ #ifdef HAVE_SYS_WAIT_H -#include /* For WNOHANG */ +#include /* For WNOHANG */ #endif #ifdef HAVE_SIGNAL_H @@ -101,43 +101,43 @@ #if defined(PYCC_VACPP) && defined(PYOS_OS2) #include #else -#if defined(__WATCOMC__) && !defined(__QNX__) /* Watcom compiler */ +#if defined(__WATCOMC__) && !defined(__QNX__) /* Watcom compiler */ #define HAVE_GETCWD 1 #define HAVE_OPENDIR 1 -#define HAVE_SYSTEM 1 +#define HAVE_SYSTEM 1 #if defined(__OS2__) #define HAVE_EXECV 1 #define HAVE_WAIT 1 #endif #include #else -#ifdef __BORLANDC__ /* Borland compiler */ +#ifdef __BORLANDC__ /* Borland compiler */ #define HAVE_EXECV 1 #define HAVE_GETCWD 1 #define HAVE_OPENDIR 1 #define HAVE_PIPE 1 #define HAVE_POPEN 1 -#define HAVE_SYSTEM 1 +#define HAVE_SYSTEM 1 #define HAVE_WAIT 1 #else -#ifdef _MSC_VER /* Microsoft compiler */ +#ifdef _MSC_VER /* Microsoft compiler */ #define HAVE_GETCWD 1 -#define HAVE_SPAWNV 1 +#define HAVE_SPAWNV 1 #define HAVE_EXECV 1 #define HAVE_PIPE 1 #define HAVE_POPEN 1 -#define HAVE_SYSTEM 1 -#define HAVE_CWAIT 1 -#define HAVE_FSYNC 1 +#define HAVE_SYSTEM 1 +#define HAVE_CWAIT 1 +#define HAVE_FSYNC 1 #define fsync _commit #else #if defined(PYOS_OS2) && defined(PYCC_GCC) || defined(__VMS) /* Everything needed is defined in PC/os2emx/pyconfig.h or vms/pyconfig.h */ -#else /* all other compilers */ +#else /* all other compilers */ /* Unix functions that the configure script doesn't check for */ #define HAVE_EXECV 1 #define HAVE_FORK 1 -#if defined(__USLC__) && defined(__SCO_VERSION__) /* SCO UDK Compiler */ +#if defined(__USLC__) && defined(__SCO_VERSION__) /* SCO UDK Compiler */ #define HAVE_FORK1 1 #endif #define HAVE_GETCWD 1 @@ -152,9 +152,9 @@ #ifndef __rtems__ #define HAVE_POPEN 1 #endif -#define HAVE_SYSTEM 1 +#define HAVE_SYSTEM 1 #define HAVE_WAIT 1 -#define HAVE_TTYNAME 1 +#define HAVE_TTYNAME 1 #endif /* PYOS_OS2 && PYCC_GCC && __VMS */ #endif /* _MSC_VER */ #endif /* __BORLANDC__ */ @@ -270,9 +270,9 @@ #endif #include "osdefs.h" #include -#include /* for ShellExecute() */ -#define popen _popen -#define pclose _pclose +#include /* for ShellExecute() */ +#define popen _popen +#define pclose _pclose #endif /* _MSC_VER */ #if defined(PYCC_VACPP) && defined(PYOS_OS2) @@ -340,13 +340,13 @@ /* choose the appropriate stat and fstat functions and return structs */ #undef STAT #if defined(MS_WIN64) || defined(MS_WINDOWS) -# define STAT win32_stat -# define FSTAT win32_fstat -# define STRUCT_STAT struct win32_stat -#else -# define STAT stat -# define FSTAT fstat -# define STRUCT_STAT struct stat +# define STAT win32_stat +# define FSTAT win32_fstat +# define STRUCT_STAT struct win32_stat +#else +# define STAT stat +# define FSTAT fstat +# define STRUCT_STAT struct stat #endif #if defined(MAJOR_IN_MKDEV) @@ -374,62 +374,61 @@ static PyObject * convertenviron(void) { - PyObject *d; - char **e; - d = PyDict_New(); - if (d == NULL) - return NULL; + PyObject *d; + char **e; +#if defined(PYOS_OS2) + APIRET rc; + char buffer[1024]; /* OS/2 Provides a Documented Max of 1024 Chars */ +#endif + d = PyDict_New(); + if (d == NULL) + return NULL; #ifdef WITH_NEXT_FRAMEWORK - if (environ == NULL) - environ = *_NSGetEnviron(); + if (environ == NULL) + environ = *_NSGetEnviron(); #endif - if (environ == NULL) - return d; - /* This part ignores errors */ - for (e = environ; *e != NULL; e++) { - PyObject *k; - PyObject *v; - char *p = strchr(*e, '='); - if (p == NULL) - continue; - k = PyString_FromStringAndSize(*e, (int)(p-*e)); - if (k == NULL) { - PyErr_Clear(); - continue; - } - v = PyString_FromString(p+1); - if (v == NULL) { - PyErr_Clear(); - Py_DECREF(k); - continue; - } - if (PyDict_GetItem(d, k) == NULL) { - if (PyDict_SetItem(d, k, v) != 0) - PyErr_Clear(); - } - Py_DECREF(k); - Py_DECREF(v); - } -#if defined(PYOS_OS2) - { - APIRET rc; - char buffer[1024]; /* OS/2 Provides a Documented Max of 1024 Chars */ - - rc = DosQueryExtLIBPATH(buffer, BEGIN_LIBPATH); - if (rc == NO_ERROR) { /* (not a type, envname is NOT 'BEGIN_LIBPATH') */ - PyObject *v = PyString_FromString(buffer); - PyDict_SetItemString(d, "BEGINLIBPATH", v); - Py_DECREF(v); + if (environ == NULL) + return d; + /* This part ignores errors */ + for (e = environ; *e != NULL; e++) { + PyObject *k; + PyObject *v; + char *p = strchr(*e, '='); + if (p == NULL) + continue; + k = PyString_FromStringAndSize(*e, (int)(p-*e)); + if (k == NULL) { + PyErr_Clear(); + continue; } - rc = DosQueryExtLIBPATH(buffer, END_LIBPATH); - if (rc == NO_ERROR) { /* (not a typo, envname is NOT 'END_LIBPATH') */ - PyObject *v = PyString_FromString(buffer); - PyDict_SetItemString(d, "ENDLIBPATH", v); - Py_DECREF(v); + v = PyString_FromString(p+1); + if (v == NULL) { + PyErr_Clear(); + Py_DECREF(k); + continue; } + if (PyDict_GetItem(d, k) == NULL) { + if (PyDict_SetItem(d, k, v) != 0) + PyErr_Clear(); + } + Py_DECREF(k); + Py_DECREF(v); + } +#if defined(PYOS_OS2) + rc = DosQueryExtLIBPATH(buffer, BEGIN_LIBPATH); + if (rc == NO_ERROR) { /* (not a type, envname is NOT 'BEGIN_LIBPATH') */ + PyObject *v = PyString_FromString(buffer); + PyDict_SetItemString(d, "BEGINLIBPATH", v); + Py_DECREF(v); + } + rc = DosQueryExtLIBPATH(buffer, END_LIBPATH); + if (rc == NO_ERROR) { /* (not a typo, envname is NOT 'END_LIBPATH') */ + PyObject *v = PyString_FromString(buffer); + PyDict_SetItemString(d, "ENDLIBPATH", v); + Py_DECREF(v); } #endif - return d; + return d; } @@ -438,19 +437,19 @@ static PyObject * posix_error(void) { - return PyErr_SetFromErrno(PyExc_OSError); + return PyErr_SetFromErrno(PyExc_OSError); } static PyObject * posix_error_with_filename(char* name) { - return PyErr_SetFromErrnoWithFilename(PyExc_OSError, name); + return PyErr_SetFromErrnoWithFilename(PyExc_OSError, name); } #ifdef Py_WIN_WIDE_FILENAMES static PyObject * posix_error_with_unicode_filename(Py_UNICODE* name) { - return PyErr_SetFromErrnoWithUnicodeFilename(PyExc_OSError, name); + return PyErr_SetFromErrnoWithUnicodeFilename(PyExc_OSError, name); } #endif /* Py_WIN_WIDE_FILENAMES */ @@ -458,37 +457,37 @@ static PyObject * posix_error_with_allocated_filename(char* name) { - PyObject *rc = PyErr_SetFromErrnoWithFilename(PyExc_OSError, name); - PyMem_Free(name); - return rc; + PyObject *rc = PyErr_SetFromErrnoWithFilename(PyExc_OSError, name); + PyMem_Free(name); + return rc; } #ifdef MS_WINDOWS static PyObject * win32_error(char* function, char* filename) { - /* XXX We should pass the function name along in the future. - (_winreg.c also wants to pass the function name.) - This would however require an additional param to the - Windows error object, which is non-trivial. - */ - errno = GetLastError(); - if (filename) - return PyErr_SetFromWindowsErrWithFilename(errno, filename); - else - return PyErr_SetFromWindowsErr(errno); + /* XXX We should pass the function name along in the future. + (_winreg.c also wants to pass the function name.) + This would however require an additional param to the + Windows error object, which is non-trivial. + */ + errno = GetLastError(); + if (filename) + return PyErr_SetFromWindowsErrWithFilename(errno, filename); + else + return PyErr_SetFromWindowsErr(errno); } #ifdef Py_WIN_WIDE_FILENAMES static PyObject * win32_error_unicode(char* function, Py_UNICODE* filename) { - /* XXX - see win32_error for comments on 'function' */ - errno = GetLastError(); - if (filename) - return PyErr_SetFromWindowsErrWithUnicodeFilename(errno, filename); - else - return PyErr_SetFromWindowsErr(errno); + /* XXX - see win32_error for comments on 'function' */ + errno = GetLastError(); + if (filename) + return PyErr_SetFromWindowsErrWithUnicodeFilename(errno, filename); + else + return PyErr_SetFromWindowsErr(errno); } static PyObject *_PyUnicode_FromFileSystemEncodedObject(register PyObject *obj) @@ -498,18 +497,18 @@ static int convert_to_unicode(PyObject **param) { - if (PyUnicode_CheckExact(*param)) - Py_INCREF(*param); - else if (PyUnicode_Check(*param)) - /* For a Unicode subtype that's not a Unicode object, - return a true Unicode object with the same data. */ - *param = PyUnicode_FromUnicode(PyUnicode_AS_UNICODE(*param), - PyUnicode_GET_SIZE(*param)); - else - *param = PyUnicode_FromEncodedObject(*param, - Py_FileSystemDefaultEncoding, - "strict"); - return (*param) != NULL; + if (PyUnicode_CheckExact(*param)) + Py_INCREF(*param); + else if (PyUnicode_Check(*param)) + /* For a Unicode subtype that's not a Unicode object, + return a true Unicode object with the same data. */ + *param = PyUnicode_FromUnicode(PyUnicode_AS_UNICODE(*param), + PyUnicode_GET_SIZE(*param)); + else + *param = PyUnicode_FromEncodedObject(*param, + Py_FileSystemDefaultEncoding, + "strict"); + return (*param) != NULL; } #endif /* Py_WIN_WIDE_FILENAMES */ @@ -520,7 +519,7 @@ /********************************************************************** * Helper Function to Trim and Format OS/2 Messages **********************************************************************/ - static void +static void os2_formatmsg(char *msgbuf, int msglen, char *reason) { msgbuf[msglen] = '\0'; /* OS/2 Doesn't Guarantee a Terminator */ @@ -550,7 +549,7 @@ * the file OSO001.MSG in the \OS2 directory hierarchy. * **********************************************************************/ - static char * +static char * os2_strerror(char *msgbuf, int msgbuflen, int errorcode, char *reason) { APIRET rc; @@ -566,7 +565,7 @@ os2_formatmsg(msgbuf, msglen, reason); else PyOS_snprintf(msgbuf, msgbuflen, - "unknown OS error #%d", errorcode); + "unknown OS error #%d", errorcode); return msgbuf; } @@ -575,7 +574,8 @@ errors are not in a global variable e.g. 'errno' nor are they congruent with posix error numbers. */ -static PyObject * os2_error(int code) +static PyObject * +os2_error(int code) { char text[1024]; PyObject *v; @@ -597,106 +597,106 @@ static PyObject * posix_fildes(PyObject *fdobj, int (*func)(int)) { - int fd; - int res; - fd = PyObject_AsFileDescriptor(fdobj); - if (fd < 0) - return NULL; - Py_BEGIN_ALLOW_THREADS - res = (*func)(fd); - Py_END_ALLOW_THREADS - if (res < 0) - return posix_error(); - Py_INCREF(Py_None); - return Py_None; + int fd; + int res; + fd = PyObject_AsFileDescriptor(fdobj); + if (fd < 0) + return NULL; + Py_BEGIN_ALLOW_THREADS + res = (*func)(fd); + Py_END_ALLOW_THREADS + if (res < 0) + return posix_error(); + Py_INCREF(Py_None); + return Py_None; } #ifdef Py_WIN_WIDE_FILENAMES static int unicode_file_names(void) { - static int canusewide = -1; - if (canusewide == -1) { - /* As per doc for ::GetVersion(), this is the correct test for - the Windows NT family. */ - canusewide = (GetVersion() < 0x80000000) ? 1 : 0; - } - return canusewide; + static int canusewide = -1; + if (canusewide == -1) { + /* As per doc for ::GetVersion(), this is the correct test for + the Windows NT family. */ + canusewide = (GetVersion() < 0x80000000) ? 1 : 0; + } + return canusewide; } #endif static PyObject * posix_1str(PyObject *args, char *format, int (*func)(const char*)) { - char *path1 = NULL; - int res; - if (!PyArg_ParseTuple(args, format, - Py_FileSystemDefaultEncoding, &path1)) - return NULL; - Py_BEGIN_ALLOW_THREADS - res = (*func)(path1); - Py_END_ALLOW_THREADS - if (res < 0) - return posix_error_with_allocated_filename(path1); - PyMem_Free(path1); - Py_INCREF(Py_None); - return Py_None; + char *path1 = NULL; + int res; + if (!PyArg_ParseTuple(args, format, + Py_FileSystemDefaultEncoding, &path1)) + return NULL; + Py_BEGIN_ALLOW_THREADS + res = (*func)(path1); + Py_END_ALLOW_THREADS + if (res < 0) + return posix_error_with_allocated_filename(path1); + PyMem_Free(path1); + Py_INCREF(Py_None); + return Py_None; } static PyObject * posix_2str(PyObject *args, - char *format, - int (*func)(const char *, const char *)) + char *format, + int (*func)(const char *, const char *)) { - char *path1 = NULL, *path2 = NULL; - int res; - if (!PyArg_ParseTuple(args, format, - Py_FileSystemDefaultEncoding, &path1, - Py_FileSystemDefaultEncoding, &path2)) - return NULL; - Py_BEGIN_ALLOW_THREADS - res = (*func)(path1, path2); - Py_END_ALLOW_THREADS - PyMem_Free(path1); - PyMem_Free(path2); - if (res != 0) - /* XXX how to report both path1 and path2??? */ - return posix_error(); - Py_INCREF(Py_None); - return Py_None; + char *path1 = NULL, *path2 = NULL; + int res; + if (!PyArg_ParseTuple(args, format, + Py_FileSystemDefaultEncoding, &path1, + Py_FileSystemDefaultEncoding, &path2)) + return NULL; + Py_BEGIN_ALLOW_THREADS + res = (*func)(path1, path2); + Py_END_ALLOW_THREADS + PyMem_Free(path1); + PyMem_Free(path2); + if (res != 0) + /* XXX how to report both path1 and path2??? */ + return posix_error(); + Py_INCREF(Py_None); + return Py_None; } #ifdef Py_WIN_WIDE_FILENAMES static PyObject* -win32_1str(PyObject* args, char* func, - char* format, BOOL (__stdcall *funcA)(LPCSTR), - char* wformat, BOOL (__stdcall *funcW)(LPWSTR)) -{ - PyObject *uni; - char *ansi; - BOOL result; - if (unicode_file_names()) { - if (!PyArg_ParseTuple(args, wformat, &uni)) - PyErr_Clear(); - else { - Py_BEGIN_ALLOW_THREADS - result = funcW(PyUnicode_AsUnicode(uni)); - Py_END_ALLOW_THREADS - if (!result) - return win32_error_unicode(func, PyUnicode_AsUnicode(uni)); - Py_INCREF(Py_None); - return Py_None; - } - } - if (!PyArg_ParseTuple(args, format, &ansi)) - return NULL; - Py_BEGIN_ALLOW_THREADS - result = funcA(ansi); - Py_END_ALLOW_THREADS - if (!result) - return win32_error(func, ansi); - Py_INCREF(Py_None); - return Py_None; +win32_1str(PyObject* args, char* func, + char* format, BOOL (__stdcall *funcA)(LPCSTR), + char* wformat, BOOL (__stdcall *funcW)(LPWSTR)) +{ + PyObject *uni; + char *ansi; + BOOL result; + if (unicode_file_names()) { + if (!PyArg_ParseTuple(args, wformat, &uni)) + PyErr_Clear(); + else { + Py_BEGIN_ALLOW_THREADS + result = funcW(PyUnicode_AsUnicode(uni)); + Py_END_ALLOW_THREADS + if (!result) + return win32_error_unicode(func, PyUnicode_AsUnicode(uni)); + Py_INCREF(Py_None); + return Py_None; + } + } + if (!PyArg_ParseTuple(args, format, &ansi)) + return NULL; + Py_BEGIN_ALLOW_THREADS + result = funcA(ansi); + Py_END_ALLOW_THREADS + if (!result) + return win32_error(func, ansi); + Py_INCREF(Py_None); + return Py_None; } @@ -708,24 +708,24 @@ BOOL __stdcall win32_chdir(LPCSTR path) { - char new_path[MAX_PATH+1]; - int result; - char env[4] = "=x:"; - - if(!SetCurrentDirectoryA(path)) - return FALSE; - result = GetCurrentDirectoryA(MAX_PATH+1, new_path); - if (!result) - return FALSE; - /* In the ANSI API, there should not be any paths longer - than MAX_PATH. */ - assert(result <= MAX_PATH+1); - if (strncmp(new_path, "\\\\", 2) == 0 || - strncmp(new_path, "//", 2) == 0) - /* UNC path, nothing to do. */ - return TRUE; - env[1] = new_path[0]; - return SetEnvironmentVariableA(env, new_path); + char new_path[MAX_PATH+1]; + int result; + char env[4] = "=x:"; + + if(!SetCurrentDirectoryA(path)) + return FALSE; + result = GetCurrentDirectoryA(MAX_PATH+1, new_path); + if (!result) + return FALSE; + /* In the ANSI API, there should not be any paths longer + than MAX_PATH. */ + assert(result <= MAX_PATH+1); + if (strncmp(new_path, "\\\\", 2) == 0 || + strncmp(new_path, "//", 2) == 0) + /* UNC path, nothing to do. */ + return TRUE; + env[1] = new_path[0]; + return SetEnvironmentVariableA(env, new_path); } /* The Unicode version differs from the ANSI version @@ -733,36 +733,36 @@ BOOL __stdcall win32_wchdir(LPCWSTR path) { - wchar_t _new_path[MAX_PATH+1], *new_path = _new_path; - int result; - wchar_t env[4] = L"=x:"; - - if(!SetCurrentDirectoryW(path)) - return FALSE; - result = GetCurrentDirectoryW(MAX_PATH+1, new_path); - if (!result) - return FALSE; - if (result > MAX_PATH+1) { - new_path = malloc(result * sizeof(wchar_t)); - if (!new_path) { - SetLastError(ERROR_OUTOFMEMORY); - return FALSE; - } - result = GetCurrentDirectoryW(result, new_path); - if (!result) { - free(new_path); - return FALSE; - } - } - if (wcsncmp(new_path, L"\\\\", 2) == 0 || - wcsncmp(new_path, L"//", 2) == 0) - /* UNC path, nothing to do. */ - return TRUE; - env[1] = new_path[0]; - result = SetEnvironmentVariableW(env, new_path); - if (new_path != _new_path) - free(new_path); - return result; + wchar_t _new_path[MAX_PATH+1], *new_path = _new_path; + int result; + wchar_t env[4] = L"=x:"; + + if(!SetCurrentDirectoryW(path)) + return FALSE; + result = GetCurrentDirectoryW(MAX_PATH+1, new_path); + if (!result) + return FALSE; + if (result > MAX_PATH+1) { + new_path = malloc(result * sizeof(wchar_t)); + if (!new_path) { + SetLastError(ERROR_OUTOFMEMORY); + return FALSE; + } + result = GetCurrentDirectoryW(result, new_path); + if (!result) { + free(new_path); + return FALSE; + } + } + if (wcsncmp(new_path, L"\\\\", 2) == 0 || + wcsncmp(new_path, L"//", 2) == 0) + /* UNC path, nothing to do. */ + return TRUE; + env[1] = new_path[0]; + result = SetEnvironmentVariableW(env, new_path); + if (new_path != _new_path) + free(new_path); + return result; } #endif @@ -773,7 +773,7 @@ UTC and local time Therefore, we implement our own stat, based on the Win32 API directly. */ -#define HAVE_STAT_NSEC 1 +#define HAVE_STAT_NSEC 1 struct win32_stat{ int st_dev; @@ -797,24 +797,24 @@ static void FILE_TIME_to_time_t_nsec(FILETIME *in_ptr, int *time_out, int* nsec_out) { - /* XXX endianness. Shouldn't matter, as all Windows implementations are little-endian */ - /* Cannot simply cast and dereference in_ptr, - since it might not be aligned properly */ - __int64 in; - memcpy(&in, in_ptr, sizeof(in)); - *nsec_out = (int)(in % 10000000) * 100; /* FILETIME is in units of 100 nsec. */ - /* XXX Win32 supports time stamps past 2038; we currently don't */ - *time_out = Py_SAFE_DOWNCAST((in / 10000000) - secs_between_epochs, __int64, int); + /* XXX endianness. Shouldn't matter, as all Windows implementations are little-endian */ + /* Cannot simply cast and dereference in_ptr, + since it might not be aligned properly */ + __int64 in; + memcpy(&in, in_ptr, sizeof(in)); + *nsec_out = (int)(in % 10000000) * 100; /* FILETIME is in units of 100 nsec. */ + /* XXX Win32 supports time stamps past 2038; we currently don't */ + *time_out = Py_SAFE_DOWNCAST((in / 10000000) - secs_between_epochs, __int64, int); } static void time_t_to_FILE_TIME(int time_in, int nsec_in, FILETIME *out_ptr) { - /* XXX endianness */ - __int64 out; - out = time_in + secs_between_epochs; - out = out * 10000000 + nsec_in / 100; - memcpy(out_ptr, &out, sizeof(out)); + /* XXX endianness */ + __int64 out; + out = time_in + secs_between_epochs; + out = out * 10000000 + nsec_in / 100; + memcpy(out_ptr, &out, sizeof(out)); } /* Below, we *know* that ugo+r is 0444 */ @@ -824,29 +824,29 @@ static int attributes_to_mode(DWORD attr) { - int m = 0; - if (attr & FILE_ATTRIBUTE_DIRECTORY) - m |= _S_IFDIR | 0111; /* IFEXEC for user,group,other */ - else - m |= _S_IFREG; - if (attr & FILE_ATTRIBUTE_READONLY) - m |= 0444; - else - m |= 0666; - return m; + int m = 0; + if (attr & FILE_ATTRIBUTE_DIRECTORY) + m |= _S_IFDIR | 0111; /* IFEXEC for user,group,other */ + else + m |= _S_IFREG; + if (attr & FILE_ATTRIBUTE_READONLY) + m |= 0444; + else + m |= 0666; + return m; } static int attribute_data_to_stat(WIN32_FILE_ATTRIBUTE_DATA *info, struct win32_stat *result) { - memset(result, 0, sizeof(*result)); - result->st_mode = attributes_to_mode(info->dwFileAttributes); - result->st_size = (((__int64)info->nFileSizeHigh)<<32) + info->nFileSizeLow; - FILE_TIME_to_time_t_nsec(&info->ftCreationTime, &result->st_ctime, &result->st_ctime_nsec); - FILE_TIME_to_time_t_nsec(&info->ftLastWriteTime, &result->st_mtime, &result->st_mtime_nsec); - FILE_TIME_to_time_t_nsec(&info->ftLastAccessTime, &result->st_atime, &result->st_atime_nsec); + memset(result, 0, sizeof(*result)); + result->st_mode = attributes_to_mode(info->dwFileAttributes); + result->st_size = (((__int64)info->nFileSizeHigh)<<32) + info->nFileSizeLow; + FILE_TIME_to_time_t_nsec(&info->ftCreationTime, &result->st_ctime, &result->st_ctime_nsec); + FILE_TIME_to_time_t_nsec(&info->ftLastWriteTime, &result->st_mtime, &result->st_mtime_nsec); + FILE_TIME_to_time_t_nsec(&info->ftLastAccessTime, &result->st_atime, &result->st_atime_nsec); - return 0; + return 0; } /* Emulate GetFileAttributesEx[AW] on Windows 95 */ @@ -856,239 +856,239 @@ static void check_gfax() { - HINSTANCE hKernel32; - if (checked) - return; - checked = 1; - hKernel32 = GetModuleHandle("KERNEL32"); - *(FARPROC*)&gfaxa = GetProcAddress(hKernel32, "GetFileAttributesExA"); - *(FARPROC*)&gfaxw = GetProcAddress(hKernel32, "GetFileAttributesExW"); + HINSTANCE hKernel32; + if (checked) + return; + checked = 1; + hKernel32 = GetModuleHandle("KERNEL32"); + *(FARPROC*)&gfaxa = GetProcAddress(hKernel32, "GetFileAttributesExA"); + *(FARPROC*)&gfaxw = GetProcAddress(hKernel32, "GetFileAttributesExW"); } static BOOL attributes_from_dir(LPCSTR pszFile, LPWIN32_FILE_ATTRIBUTE_DATA pfad) { - HANDLE hFindFile; - WIN32_FIND_DATAA FileData; - hFindFile = FindFirstFileA(pszFile, &FileData); - if (hFindFile == INVALID_HANDLE_VALUE) - return FALSE; - FindClose(hFindFile); - pfad->dwFileAttributes = FileData.dwFileAttributes; - pfad->ftCreationTime = FileData.ftCreationTime; - pfad->ftLastAccessTime = FileData.ftLastAccessTime; - pfad->ftLastWriteTime = FileData.ftLastWriteTime; - pfad->nFileSizeHigh = FileData.nFileSizeHigh; - pfad->nFileSizeLow = FileData.nFileSizeLow; - return TRUE; + HANDLE hFindFile; + WIN32_FIND_DATAA FileData; + hFindFile = FindFirstFileA(pszFile, &FileData); + if (hFindFile == INVALID_HANDLE_VALUE) + return FALSE; + FindClose(hFindFile); + pfad->dwFileAttributes = FileData.dwFileAttributes; + pfad->ftCreationTime = FileData.ftCreationTime; + pfad->ftLastAccessTime = FileData.ftLastAccessTime; + pfad->ftLastWriteTime = FileData.ftLastWriteTime; + pfad->nFileSizeHigh = FileData.nFileSizeHigh; + pfad->nFileSizeLow = FileData.nFileSizeLow; + return TRUE; } static BOOL attributes_from_dir_w(LPCWSTR pszFile, LPWIN32_FILE_ATTRIBUTE_DATA pfad) { - HANDLE hFindFile; - WIN32_FIND_DATAW FileData; - hFindFile = FindFirstFileW(pszFile, &FileData); - if (hFindFile == INVALID_HANDLE_VALUE) - return FALSE; - FindClose(hFindFile); - pfad->dwFileAttributes = FileData.dwFileAttributes; - pfad->ftCreationTime = FileData.ftCreationTime; - pfad->ftLastAccessTime = FileData.ftLastAccessTime; - pfad->ftLastWriteTime = FileData.ftLastWriteTime; - pfad->nFileSizeHigh = FileData.nFileSizeHigh; - pfad->nFileSizeLow = FileData.nFileSizeLow; - return TRUE; + HANDLE hFindFile; + WIN32_FIND_DATAW FileData; + hFindFile = FindFirstFileW(pszFile, &FileData); + if (hFindFile == INVALID_HANDLE_VALUE) + return FALSE; + FindClose(hFindFile); + pfad->dwFileAttributes = FileData.dwFileAttributes; + pfad->ftCreationTime = FileData.ftCreationTime; + pfad->ftLastAccessTime = FileData.ftLastAccessTime; + pfad->ftLastWriteTime = FileData.ftLastWriteTime; + pfad->nFileSizeHigh = FileData.nFileSizeHigh; + pfad->nFileSizeLow = FileData.nFileSizeLow; + return TRUE; } static BOOL WINAPI -Py_GetFileAttributesExA(LPCSTR pszFile, - GET_FILEEX_INFO_LEVELS level, +Py_GetFileAttributesExA(LPCSTR pszFile, + GET_FILEEX_INFO_LEVELS level, LPVOID pv) { - BOOL result; - LPWIN32_FILE_ATTRIBUTE_DATA pfad = pv; - /* First try to use the system's implementation, if that is - available and either succeeds to gives an error other than - that it isn't implemented. */ - check_gfax(); - if (gfaxa) { - result = gfaxa(pszFile, level, pv); - if (result || GetLastError() != ERROR_CALL_NOT_IMPLEMENTED) - return result; - } - /* It's either not present, or not implemented. - Emulate using FindFirstFile. */ - if (level != GetFileExInfoStandard) { - SetLastError(ERROR_INVALID_PARAMETER); - return FALSE; - } - /* Use GetFileAttributes to validate that the file name - does not contain wildcards (which FindFirstFile would - accept). */ - if (GetFileAttributesA(pszFile) == 0xFFFFFFFF) - return FALSE; - return attributes_from_dir(pszFile, pfad); + BOOL result; + LPWIN32_FILE_ATTRIBUTE_DATA pfad = pv; + /* First try to use the system's implementation, if that is + available and either succeeds to gives an error other than + that it isn't implemented. */ + check_gfax(); + if (gfaxa) { + result = gfaxa(pszFile, level, pv); + if (result || GetLastError() != ERROR_CALL_NOT_IMPLEMENTED) + return result; + } + /* It's either not present, or not implemented. + Emulate using FindFirstFile. */ + if (level != GetFileExInfoStandard) { + SetLastError(ERROR_INVALID_PARAMETER); + return FALSE; + } + /* Use GetFileAttributes to validate that the file name + does not contain wildcards (which FindFirstFile would + accept). */ + if (GetFileAttributesA(pszFile) == 0xFFFFFFFF) + return FALSE; + return attributes_from_dir(pszFile, pfad); } static BOOL WINAPI -Py_GetFileAttributesExW(LPCWSTR pszFile, - GET_FILEEX_INFO_LEVELS level, +Py_GetFileAttributesExW(LPCWSTR pszFile, + GET_FILEEX_INFO_LEVELS level, LPVOID pv) { - BOOL result; - LPWIN32_FILE_ATTRIBUTE_DATA pfad = pv; - /* First try to use the system's implementation, if that is - available and either succeeds to gives an error other than - that it isn't implemented. */ - check_gfax(); - if (gfaxa) { - result = gfaxw(pszFile, level, pv); - if (result || GetLastError() != ERROR_CALL_NOT_IMPLEMENTED) - return result; - } - /* It's either not present, or not implemented. - Emulate using FindFirstFile. */ - if (level != GetFileExInfoStandard) { - SetLastError(ERROR_INVALID_PARAMETER); - return FALSE; - } - /* Use GetFileAttributes to validate that the file name - does not contain wildcards (which FindFirstFile would - accept). */ - if (GetFileAttributesW(pszFile) == 0xFFFFFFFF) - return FALSE; - return attributes_from_dir_w(pszFile, pfad); + BOOL result; + LPWIN32_FILE_ATTRIBUTE_DATA pfad = pv; + /* First try to use the system's implementation, if that is + available and either succeeds to gives an error other than + that it isn't implemented. */ + check_gfax(); + if (gfaxa) { + result = gfaxw(pszFile, level, pv); + if (result || GetLastError() != ERROR_CALL_NOT_IMPLEMENTED) + return result; + } + /* It's either not present, or not implemented. + Emulate using FindFirstFile. */ + if (level != GetFileExInfoStandard) { + SetLastError(ERROR_INVALID_PARAMETER); + return FALSE; + } + /* Use GetFileAttributes to validate that the file name + does not contain wildcards (which FindFirstFile would + accept). */ + if (GetFileAttributesW(pszFile) == 0xFFFFFFFF) + return FALSE; + return attributes_from_dir_w(pszFile, pfad); } -static int +static int win32_stat(const char* path, struct win32_stat *result) { - WIN32_FILE_ATTRIBUTE_DATA info; - int code; - char *dot; - /* XXX not supported on Win95 and NT 3.x */ - if (!Py_GetFileAttributesExA(path, GetFileExInfoStandard, &info)) { - if (GetLastError() != ERROR_SHARING_VIOLATION) { - /* Protocol violation: we explicitly clear errno, instead of - setting it to a POSIX error. Callers should use GetLastError. */ - errno = 0; - return -1; - } else { - /* Could not get attributes on open file. Fall back to - reading the directory. */ - if (!attributes_from_dir(path, &info)) { - /* Very strange. This should not fail now */ - errno = 0; - return -1; - } - } - } - code = attribute_data_to_stat(&info, result); - if (code != 0) - return code; - /* Set S_IFEXEC if it is an .exe, .bat, ... */ - dot = strrchr(path, '.'); - if (dot) { - if (stricmp(dot, ".bat") == 0 || - stricmp(dot, ".cmd") == 0 || - stricmp(dot, ".exe") == 0 || - stricmp(dot, ".com") == 0) - result->st_mode |= 0111; - } - return code; + WIN32_FILE_ATTRIBUTE_DATA info; + int code; + char *dot; + /* XXX not supported on Win95 and NT 3.x */ + if (!Py_GetFileAttributesExA(path, GetFileExInfoStandard, &info)) { + if (GetLastError() != ERROR_SHARING_VIOLATION) { + /* Protocol violation: we explicitly clear errno, instead of + setting it to a POSIX error. Callers should use GetLastError. */ + errno = 0; + return -1; + } else { + /* Could not get attributes on open file. Fall back to + reading the directory. */ + if (!attributes_from_dir(path, &info)) { + /* Very strange. This should not fail now */ + errno = 0; + return -1; + } + } + } + code = attribute_data_to_stat(&info, result); + if (code != 0) + return code; + /* Set S_IFEXEC if it is an .exe, .bat, ... */ + dot = strrchr(path, '.'); + if (dot) { + if (stricmp(dot, ".bat") == 0 || + stricmp(dot, ".cmd") == 0 || + stricmp(dot, ".exe") == 0 || + stricmp(dot, ".com") == 0) + result->st_mode |= 0111; + } + return code; } -static int +static int win32_wstat(const wchar_t* path, struct win32_stat *result) { - int code; - const wchar_t *dot; - WIN32_FILE_ATTRIBUTE_DATA info; - /* XXX not supported on Win95 and NT 3.x */ - if (!Py_GetFileAttributesExW(path, GetFileExInfoStandard, &info)) { - if (GetLastError() != ERROR_SHARING_VIOLATION) { - /* Protocol violation: we explicitly clear errno, instead of - setting it to a POSIX error. Callers should use GetLastError. */ - errno = 0; - return -1; - } else { - /* Could not get attributes on open file. Fall back to - reading the directory. */ - if (!attributes_from_dir_w(path, &info)) { - /* Very strange. This should not fail now */ - errno = 0; - return -1; - } - } - } - code = attribute_data_to_stat(&info, result); - if (code < 0) - return code; - /* Set IFEXEC if it is an .exe, .bat, ... */ - dot = wcsrchr(path, '.'); - if (dot) { - if (_wcsicmp(dot, L".bat") == 0 || - _wcsicmp(dot, L".cmd") == 0 || - _wcsicmp(dot, L".exe") == 0 || - _wcsicmp(dot, L".com") == 0) - result->st_mode |= 0111; - } - return code; + int code; + const wchar_t *dot; + WIN32_FILE_ATTRIBUTE_DATA info; + /* XXX not supported on Win95 and NT 3.x */ + if (!Py_GetFileAttributesExW(path, GetFileExInfoStandard, &info)) { + if (GetLastError() != ERROR_SHARING_VIOLATION) { + /* Protocol violation: we explicitly clear errno, instead of + setting it to a POSIX error. Callers should use GetLastError. */ + errno = 0; + return -1; + } else { + /* Could not get attributes on open file. Fall back to + reading the directory. */ + if (!attributes_from_dir_w(path, &info)) { + /* Very strange. This should not fail now */ + errno = 0; + return -1; + } + } + } + code = attribute_data_to_stat(&info, result); + if (code < 0) + return code; + /* Set IFEXEC if it is an .exe, .bat, ... */ + dot = wcsrchr(path, '.'); + if (dot) { + if (_wcsicmp(dot, L".bat") == 0 || + _wcsicmp(dot, L".cmd") == 0 || + _wcsicmp(dot, L".exe") == 0 || + _wcsicmp(dot, L".com") == 0) + result->st_mode |= 0111; + } + return code; } static int win32_fstat(int file_number, struct win32_stat *result) { - BY_HANDLE_FILE_INFORMATION info; - HANDLE h; - int type; - - h = (HANDLE)_get_osfhandle(file_number); - - /* Protocol violation: we explicitly clear errno, instead of - setting it to a POSIX error. Callers should use GetLastError. */ - errno = 0; - - if (h == INVALID_HANDLE_VALUE) { - /* This is really a C library error (invalid file handle). - We set the Win32 error to the closes one matching. */ - SetLastError(ERROR_INVALID_HANDLE); - return -1; - } - memset(result, 0, sizeof(*result)); - - type = GetFileType(h); - if (type == FILE_TYPE_UNKNOWN) { - DWORD error = GetLastError(); - if (error != 0) { - return -1; - } - /* else: valid but unknown file */ - } - - if (type != FILE_TYPE_DISK) { - if (type == FILE_TYPE_CHAR) - result->st_mode = _S_IFCHR; - else if (type == FILE_TYPE_PIPE) - result->st_mode = _S_IFIFO; - return 0; - } - - if (!GetFileInformationByHandle(h, &info)) { - return -1; - } - - /* similar to stat() */ - result->st_mode = attributes_to_mode(info.dwFileAttributes); - result->st_size = (((__int64)info.nFileSizeHigh)<<32) + info.nFileSizeLow; - FILE_TIME_to_time_t_nsec(&info.ftCreationTime, &result->st_ctime, &result->st_ctime_nsec); - FILE_TIME_to_time_t_nsec(&info.ftLastWriteTime, &result->st_mtime, &result->st_mtime_nsec); - FILE_TIME_to_time_t_nsec(&info.ftLastAccessTime, &result->st_atime, &result->st_atime_nsec); - /* specific to fstat() */ - result->st_nlink = info.nNumberOfLinks; - result->st_ino = (((__int64)info.nFileIndexHigh)<<32) + info.nFileIndexLow; - return 0; + BY_HANDLE_FILE_INFORMATION info; + HANDLE h; + int type; + + h = (HANDLE)_get_osfhandle(file_number); + + /* Protocol violation: we explicitly clear errno, instead of + setting it to a POSIX error. Callers should use GetLastError. */ + errno = 0; + + if (h == INVALID_HANDLE_VALUE) { + /* This is really a C library error (invalid file handle). + We set the Win32 error to the closes one matching. */ + SetLastError(ERROR_INVALID_HANDLE); + return -1; + } + memset(result, 0, sizeof(*result)); + + type = GetFileType(h); + if (type == FILE_TYPE_UNKNOWN) { + DWORD error = GetLastError(); + if (error != 0) { + return -1; + } + /* else: valid but unknown file */ + } + + if (type != FILE_TYPE_DISK) { + if (type == FILE_TYPE_CHAR) + result->st_mode = _S_IFCHR; + else if (type == FILE_TYPE_PIPE) + result->st_mode = _S_IFIFO; + return 0; + } + + if (!GetFileInformationByHandle(h, &info)) { + return -1; + } + + /* similar to stat() */ + result->st_mode = attributes_to_mode(info.dwFileAttributes); + result->st_size = (((__int64)info.nFileSizeHigh)<<32) + info.nFileSizeLow; + FILE_TIME_to_time_t_nsec(&info.ftCreationTime, &result->st_ctime, &result->st_ctime_nsec); + FILE_TIME_to_time_t_nsec(&info.ftLastWriteTime, &result->st_mtime, &result->st_mtime_nsec); + FILE_TIME_to_time_t_nsec(&info.ftLastAccessTime, &result->st_atime, &result->st_atime_nsec); + /* specific to fstat() */ + result->st_nlink = info.nNumberOfLinks; + result->st_ino = (((__int64)info.nFileIndexHigh)<<32) + info.nFileIndexLow; + return 0; } #endif /* MS_WINDOWS */ @@ -1105,39 +1105,39 @@ See os.stat for more information."); static PyStructSequence_Field stat_result_fields[] = { - {"st_mode", "protection bits"}, - {"st_ino", "inode"}, - {"st_dev", "device"}, - {"st_nlink", "number of hard links"}, - {"st_uid", "user ID of owner"}, - {"st_gid", "group ID of owner"}, - {"st_size", "total size, in bytes"}, - /* The NULL is replaced with PyStructSequence_UnnamedField later. */ - {NULL, "integer time of last access"}, - {NULL, "integer time of last modification"}, - {NULL, "integer time of last change"}, - {"st_atime", "time of last access"}, - {"st_mtime", "time of last modification"}, - {"st_ctime", "time of last change"}, + {"st_mode", "protection bits"}, + {"st_ino", "inode"}, + {"st_dev", "device"}, + {"st_nlink", "number of hard links"}, + {"st_uid", "user ID of owner"}, + {"st_gid", "group ID of owner"}, + {"st_size", "total size, in bytes"}, + /* The NULL is replaced with PyStructSequence_UnnamedField later. */ + {NULL, "integer time of last access"}, + {NULL, "integer time of last modification"}, + {NULL, "integer time of last change"}, + {"st_atime", "time of last access"}, + {"st_mtime", "time of last modification"}, + {"st_ctime", "time of last change"}, #ifdef HAVE_STRUCT_STAT_ST_BLKSIZE - {"st_blksize", "blocksize for filesystem I/O"}, + {"st_blksize", "blocksize for filesystem I/O"}, #endif #ifdef HAVE_STRUCT_STAT_ST_BLOCKS - {"st_blocks", "number of blocks allocated"}, + {"st_blocks", "number of blocks allocated"}, #endif #ifdef HAVE_STRUCT_STAT_ST_RDEV - {"st_rdev", "device type (if inode device)"}, + {"st_rdev", "device type (if inode device)"}, #endif #ifdef HAVE_STRUCT_STAT_ST_FLAGS - {"st_flags", "user defined flags for file"}, + {"st_flags", "user defined flags for file"}, #endif #ifdef HAVE_STRUCT_STAT_ST_GEN - {"st_gen", "generation number"}, + {"st_gen", "generation number"}, #endif #ifdef HAVE_STRUCT_STAT_ST_BIRTHTIME - {"st_birthtime", "time of creation"}, + {"st_birthtime", "time of creation"}, #endif - {0} + {0} }; #ifdef HAVE_STRUCT_STAT_ST_BLKSIZE @@ -1177,10 +1177,10 @@ #endif static PyStructSequence_Desc stat_result_desc = { - "stat_result", /* name */ - stat_result__doc__, /* doc */ - stat_result_fields, - 10 + "stat_result", /* name */ + stat_result__doc__, /* doc */ + stat_result_fields, + 10 }; PyDoc_STRVAR(statvfs_result__doc__, @@ -1192,24 +1192,24 @@ See os.statvfs for more information."); static PyStructSequence_Field statvfs_result_fields[] = { - {"f_bsize", }, - {"f_frsize", }, - {"f_blocks", }, - {"f_bfree", }, - {"f_bavail", }, - {"f_files", }, - {"f_ffree", }, - {"f_favail", }, - {"f_flag", }, - {"f_namemax",}, - {0} + {"f_bsize", }, + {"f_frsize", }, + {"f_blocks", }, + {"f_bfree", }, + {"f_bavail", }, + {"f_files", }, + {"f_ffree", }, + {"f_favail", }, + {"f_flag", }, + {"f_namemax",}, + {0} }; static PyStructSequence_Desc statvfs_result_desc = { - "statvfs_result", /* name */ - statvfs_result__doc__, /* doc */ - statvfs_result_fields, - 10 + "statvfs_result", /* name */ + statvfs_result__doc__, /* doc */ + statvfs_result_fields, + 10 }; static int initialized; @@ -1220,23 +1220,23 @@ static PyObject * statresult_new(PyTypeObject *type, PyObject *args, PyObject *kwds) { - PyStructSequence *result; - int i; + PyStructSequence *result; + int i; - result = (PyStructSequence*)structseq_new(type, args, kwds); - if (!result) - return NULL; - /* If we have been initialized from a tuple, - st_?time might be set to None. Initialize it - from the int slots. */ - for (i = 7; i <= 9; i++) { - if (result->ob_item[i+3] == Py_None) { - Py_DECREF(Py_None); - Py_INCREF(result->ob_item[i]); - result->ob_item[i+3] = result->ob_item[i]; - } - } - return (PyObject*)result; + result = (PyStructSequence*)structseq_new(type, args, kwds); + if (!result) + return NULL; + /* If we have been initialized from a tuple, + st_?time might be set to None. Initialize it + from the int slots. */ + for (i = 7; i <= 9; i++) { + if (result->ob_item[i+3] == Py_None) { + Py_DECREF(Py_None); + Py_INCREF(result->ob_item[i]); + result->ob_item[i+3] = result->ob_item[i]; + } + } + return (PyObject*)result; } @@ -1254,36 +1254,36 @@ static PyObject* stat_float_times(PyObject* self, PyObject *args) { - int newval = -1; - if (!PyArg_ParseTuple(args, "|i:stat_float_times", &newval)) - return NULL; - if (newval == -1) - /* Return old value */ - return PyBool_FromLong(_stat_float_times); - _stat_float_times = newval; - Py_INCREF(Py_None); - return Py_None; + int newval = -1; + if (!PyArg_ParseTuple(args, "|i:stat_float_times", &newval)) + return NULL; + if (newval == -1) + /* Return old value */ + return PyBool_FromLong(_stat_float_times); + _stat_float_times = newval; + Py_INCREF(Py_None); + return Py_None; } static void fill_time(PyObject *v, int index, time_t sec, unsigned long nsec) { - PyObject *fval,*ival; + PyObject *fval,*ival; #if SIZEOF_TIME_T > SIZEOF_LONG - ival = PyLong_FromLongLong((PY_LONG_LONG)sec); + ival = PyLong_FromLongLong((PY_LONG_LONG)sec); #else - ival = PyInt_FromLong((long)sec); + ival = PyInt_FromLong((long)sec); #endif - if (!ival) - return; - if (_stat_float_times) { - fval = PyFloat_FromDouble(sec + 1e-9*nsec); - } else { - fval = ival; - Py_INCREF(fval); - } - PyStructSequence_SET_ITEM(v, index, ival); - PyStructSequence_SET_ITEM(v, index+3, fval); + if (!ival) + return; + if (_stat_float_times) { + fval = PyFloat_FromDouble(sec + 1e-9*nsec); + } else { + fval = ival; + Py_INCREF(fval); + } + PyStructSequence_SET_ITEM(v, index, ival); + PyStructSequence_SET_ITEM(v, index+3, fval); } /* pack a system stat C structure into the Python stat tuple @@ -1291,99 +1291,99 @@ static PyObject* _pystat_fromstructstat(STRUCT_STAT *st) { - unsigned long ansec, mnsec, cnsec; - PyObject *v = PyStructSequence_New(&StatResultType); - if (v == NULL) - return NULL; + unsigned long ansec, mnsec, cnsec; + PyObject *v = PyStructSequence_New(&StatResultType); + if (v == NULL) + return NULL; - PyStructSequence_SET_ITEM(v, 0, PyInt_FromLong((long)st->st_mode)); + PyStructSequence_SET_ITEM(v, 0, PyInt_FromLong((long)st->st_mode)); #ifdef HAVE_LARGEFILE_SUPPORT - PyStructSequence_SET_ITEM(v, 1, - PyLong_FromLongLong((PY_LONG_LONG)st->st_ino)); + PyStructSequence_SET_ITEM(v, 1, + PyLong_FromLongLong((PY_LONG_LONG)st->st_ino)); #else - PyStructSequence_SET_ITEM(v, 1, PyInt_FromLong((long)st->st_ino)); + PyStructSequence_SET_ITEM(v, 1, PyInt_FromLong((long)st->st_ino)); #endif #if defined(HAVE_LONG_LONG) && !defined(MS_WINDOWS) - PyStructSequence_SET_ITEM(v, 2, - PyLong_FromLongLong((PY_LONG_LONG)st->st_dev)); + PyStructSequence_SET_ITEM(v, 2, + PyLong_FromLongLong((PY_LONG_LONG)st->st_dev)); #else - PyStructSequence_SET_ITEM(v, 2, PyInt_FromLong((long)st->st_dev)); + PyStructSequence_SET_ITEM(v, 2, PyInt_FromLong((long)st->st_dev)); #endif - PyStructSequence_SET_ITEM(v, 3, PyInt_FromLong((long)st->st_nlink)); - PyStructSequence_SET_ITEM(v, 4, PyInt_FromLong((long)st->st_uid)); - PyStructSequence_SET_ITEM(v, 5, PyInt_FromLong((long)st->st_gid)); + PyStructSequence_SET_ITEM(v, 3, PyInt_FromLong((long)st->st_nlink)); + PyStructSequence_SET_ITEM(v, 4, PyInt_FromLong((long)st->st_uid)); + PyStructSequence_SET_ITEM(v, 5, PyInt_FromLong((long)st->st_gid)); #ifdef HAVE_LARGEFILE_SUPPORT - PyStructSequence_SET_ITEM(v, 6, - PyLong_FromLongLong((PY_LONG_LONG)st->st_size)); + PyStructSequence_SET_ITEM(v, 6, + PyLong_FromLongLong((PY_LONG_LONG)st->st_size)); #else - PyStructSequence_SET_ITEM(v, 6, PyInt_FromLong(st->st_size)); + PyStructSequence_SET_ITEM(v, 6, PyInt_FromLong(st->st_size)); #endif #if defined(HAVE_STAT_TV_NSEC) - ansec = st->st_atim.tv_nsec; - mnsec = st->st_mtim.tv_nsec; - cnsec = st->st_ctim.tv_nsec; + ansec = st->st_atim.tv_nsec; + mnsec = st->st_mtim.tv_nsec; + cnsec = st->st_ctim.tv_nsec; #elif defined(HAVE_STAT_TV_NSEC2) - ansec = st->st_atimespec.tv_nsec; - mnsec = st->st_mtimespec.tv_nsec; - cnsec = st->st_ctimespec.tv_nsec; + ansec = st->st_atimespec.tv_nsec; + mnsec = st->st_mtimespec.tv_nsec; + cnsec = st->st_ctimespec.tv_nsec; #elif defined(HAVE_STAT_NSEC) - ansec = st->st_atime_nsec; - mnsec = st->st_mtime_nsec; - cnsec = st->st_ctime_nsec; -#else - ansec = mnsec = cnsec = 0; -#endif - fill_time(v, 7, st->st_atime, ansec); - fill_time(v, 8, st->st_mtime, mnsec); - fill_time(v, 9, st->st_ctime, cnsec); + ansec = st->st_atime_nsec; + mnsec = st->st_mtime_nsec; + cnsec = st->st_ctime_nsec; +#else + ansec = mnsec = cnsec = 0; +#endif + fill_time(v, 7, st->st_atime, ansec); + fill_time(v, 8, st->st_mtime, mnsec); + fill_time(v, 9, st->st_ctime, cnsec); #ifdef HAVE_STRUCT_STAT_ST_BLKSIZE - PyStructSequence_SET_ITEM(v, ST_BLKSIZE_IDX, - PyInt_FromLong((long)st->st_blksize)); + PyStructSequence_SET_ITEM(v, ST_BLKSIZE_IDX, + PyInt_FromLong((long)st->st_blksize)); #endif #ifdef HAVE_STRUCT_STAT_ST_BLOCKS - PyStructSequence_SET_ITEM(v, ST_BLOCKS_IDX, - PyInt_FromLong((long)st->st_blocks)); + PyStructSequence_SET_ITEM(v, ST_BLOCKS_IDX, + PyInt_FromLong((long)st->st_blocks)); #endif #ifdef HAVE_STRUCT_STAT_ST_RDEV - PyStructSequence_SET_ITEM(v, ST_RDEV_IDX, - PyInt_FromLong((long)st->st_rdev)); + PyStructSequence_SET_ITEM(v, ST_RDEV_IDX, + PyInt_FromLong((long)st->st_rdev)); #endif #ifdef HAVE_STRUCT_STAT_ST_GEN - PyStructSequence_SET_ITEM(v, ST_GEN_IDX, - PyInt_FromLong((long)st->st_gen)); + PyStructSequence_SET_ITEM(v, ST_GEN_IDX, + PyInt_FromLong((long)st->st_gen)); #endif #ifdef HAVE_STRUCT_STAT_ST_BIRTHTIME - { - PyObject *val; - unsigned long bsec,bnsec; - bsec = (long)st->st_birthtime; + { + PyObject *val; + unsigned long bsec,bnsec; + bsec = (long)st->st_birthtime; #ifdef HAVE_STAT_TV_NSEC2 - bnsec = st->st_birthtimespec.tv_nsec; + bnsec = st->st_birthtimespec.tv_nsec; #else - bnsec = 0; + bnsec = 0; #endif - if (_stat_float_times) { - val = PyFloat_FromDouble(bsec + 1e-9*bnsec); - } else { - val = PyInt_FromLong((long)bsec); - } - PyStructSequence_SET_ITEM(v, ST_BIRTHTIME_IDX, - val); - } + if (_stat_float_times) { + val = PyFloat_FromDouble(bsec + 1e-9*bnsec); + } else { + val = PyInt_FromLong((long)bsec); + } + PyStructSequence_SET_ITEM(v, ST_BIRTHTIME_IDX, + val); + } #endif #ifdef HAVE_STRUCT_STAT_ST_FLAGS - PyStructSequence_SET_ITEM(v, ST_FLAGS_IDX, - PyInt_FromLong((long)st->st_flags)); + PyStructSequence_SET_ITEM(v, ST_FLAGS_IDX, + PyInt_FromLong((long)st->st_flags)); #endif - if (PyErr_Occurred()) { - Py_DECREF(v); - return NULL; - } + if (PyErr_Occurred()) { + Py_DECREF(v); + return NULL; + } - return v; + return v; } #ifdef MS_WINDOWS @@ -1402,114 +1402,114 @@ static BOOL IsUNCRootA(char *path, int pathlen) { - #define ISSLASH ISSLASHA + #define ISSLASH ISSLASHA - int i, share; + int i, share; - if (pathlen < 5 || !ISSLASH(path[0]) || !ISSLASH(path[1])) - /* minimum UNCRoot is \\x\y */ - return FALSE; - for (i = 2; i < pathlen ; i++) - if (ISSLASH(path[i])) break; - if (i == 2 || i == pathlen) - /* do not allow \\\SHARE or \\SERVER */ - return FALSE; - share = i+1; - for (i = share; i < pathlen; i++) - if (ISSLASH(path[i])) break; - return (i != share && (i == pathlen || i == pathlen-1)); + if (pathlen < 5 || !ISSLASH(path[0]) || !ISSLASH(path[1])) + /* minimum UNCRoot is \\x\y */ + return FALSE; + for (i = 2; i < pathlen ; i++) + if (ISSLASH(path[i])) break; + if (i == 2 || i == pathlen) + /* do not allow \\\SHARE or \\SERVER */ + return FALSE; + share = i+1; + for (i = share; i < pathlen; i++) + if (ISSLASH(path[i])) break; + return (i != share && (i == pathlen || i == pathlen-1)); - #undef ISSLASH + #undef ISSLASH } #ifdef Py_WIN_WIDE_FILENAMES static BOOL IsUNCRootW(Py_UNICODE *path, int pathlen) { - #define ISSLASH ISSLASHW + #define ISSLASH ISSLASHW - int i, share; + int i, share; - if (pathlen < 5 || !ISSLASH(path[0]) || !ISSLASH(path[1])) - /* minimum UNCRoot is \\x\y */ - return FALSE; - for (i = 2; i < pathlen ; i++) - if (ISSLASH(path[i])) break; - if (i == 2 || i == pathlen) - /* do not allow \\\SHARE or \\SERVER */ - return FALSE; - share = i+1; - for (i = share; i < pathlen; i++) - if (ISSLASH(path[i])) break; - return (i != share && (i == pathlen || i == pathlen-1)); + if (pathlen < 5 || !ISSLASH(path[0]) || !ISSLASH(path[1])) + /* minimum UNCRoot is \\x\y */ + return FALSE; + for (i = 2; i < pathlen ; i++) + if (ISSLASH(path[i])) break; + if (i == 2 || i == pathlen) + /* do not allow \\\SHARE or \\SERVER */ + return FALSE; + share = i+1; + for (i = share; i < pathlen; i++) + if (ISSLASH(path[i])) break; + return (i != share && (i == pathlen || i == pathlen-1)); - #undef ISSLASH + #undef ISSLASH } #endif /* Py_WIN_WIDE_FILENAMES */ #endif /* MS_WINDOWS */ static PyObject * posix_do_stat(PyObject *self, PyObject *args, - char *format, + char *format, #ifdef __VMS - int (*statfunc)(const char *, STRUCT_STAT *, ...), + int (*statfunc)(const char *, STRUCT_STAT *, ...), #else - int (*statfunc)(const char *, STRUCT_STAT *), + int (*statfunc)(const char *, STRUCT_STAT *), #endif - char *wformat, - int (*wstatfunc)(const Py_UNICODE *, STRUCT_STAT *)) + char *wformat, + int (*wstatfunc)(const Py_UNICODE *, STRUCT_STAT *)) { - STRUCT_STAT st; - char *path = NULL; /* pass this to stat; do not free() it */ - char *pathfree = NULL; /* this memory must be free'd */ - int res; - PyObject *result; + STRUCT_STAT st; + char *path = NULL; /* pass this to stat; do not free() it */ + char *pathfree = NULL; /* this memory must be free'd */ + int res; + PyObject *result; #ifdef Py_WIN_WIDE_FILENAMES - /* If on wide-character-capable OS see if argument - is Unicode and if so use wide API. */ - if (unicode_file_names()) { - PyUnicodeObject *po; - if (PyArg_ParseTuple(args, wformat, &po)) { - Py_UNICODE *wpath = PyUnicode_AS_UNICODE(po); - - Py_BEGIN_ALLOW_THREADS - /* PyUnicode_AS_UNICODE result OK without - thread lock as it is a simple dereference. */ - res = wstatfunc(wpath, &st); - Py_END_ALLOW_THREADS - - if (res != 0) - return win32_error_unicode("stat", wpath); - return _pystat_fromstructstat(&st); - } - /* Drop the argument parsing error as narrow strings - are also valid. */ - PyErr_Clear(); - } -#endif - - if (!PyArg_ParseTuple(args, format, - Py_FileSystemDefaultEncoding, &path)) - return NULL; - pathfree = path; - - Py_BEGIN_ALLOW_THREADS - res = (*statfunc)(path, &st); - Py_END_ALLOW_THREADS + /* If on wide-character-capable OS see if argument + is Unicode and if so use wide API. */ + if (unicode_file_names()) { + PyUnicodeObject *po; + if (PyArg_ParseTuple(args, wformat, &po)) { + Py_UNICODE *wpath = PyUnicode_AS_UNICODE(po); + + Py_BEGIN_ALLOW_THREADS + /* PyUnicode_AS_UNICODE result OK without + thread lock as it is a simple dereference. */ + res = wstatfunc(wpath, &st); + Py_END_ALLOW_THREADS + + if (res != 0) + return win32_error_unicode("stat", wpath); + return _pystat_fromstructstat(&st); + } + /* Drop the argument parsing error as narrow strings + are also valid. */ + PyErr_Clear(); + } +#endif + + if (!PyArg_ParseTuple(args, format, + Py_FileSystemDefaultEncoding, &path)) + return NULL; + pathfree = path; - if (res != 0) { + Py_BEGIN_ALLOW_THREADS + res = (*statfunc)(path, &st); + Py_END_ALLOW_THREADS + + if (res != 0) { #ifdef MS_WINDOWS - result = win32_error("stat", pathfree); + result = win32_error("stat", pathfree); #else - result = posix_error_with_filename(pathfree); + result = posix_error_with_filename(pathfree); #endif - } - else - result = _pystat_fromstructstat(&st); + } + else + result = _pystat_fromstructstat(&st); - PyMem_Free(pathfree); - return result; + PyMem_Free(pathfree); + return result; } /* POSIX methods */ @@ -1525,52 +1525,52 @@ static PyObject * posix_access(PyObject *self, PyObject *args) { - char *path; - int mode; - + char *path; + int mode; + #ifdef Py_WIN_WIDE_FILENAMES - DWORD attr; - if (unicode_file_names()) { - PyUnicodeObject *po; - if (PyArg_ParseTuple(args, "Ui:access", &po, &mode)) { - Py_BEGIN_ALLOW_THREADS - /* PyUnicode_AS_UNICODE OK without thread lock as - it is a simple dereference. */ - attr = GetFileAttributesW(PyUnicode_AS_UNICODE(po)); - Py_END_ALLOW_THREADS - goto finish; - } - /* Drop the argument parsing error as narrow strings - are also valid. */ - PyErr_Clear(); - } - if (!PyArg_ParseTuple(args, "eti:access", - Py_FileSystemDefaultEncoding, &path, &mode)) - return 0; - Py_BEGIN_ALLOW_THREADS - attr = GetFileAttributesA(path); - Py_END_ALLOW_THREADS - PyMem_Free(path); + DWORD attr; + if (unicode_file_names()) { + PyUnicodeObject *po; + if (PyArg_ParseTuple(args, "Ui:access", &po, &mode)) { + Py_BEGIN_ALLOW_THREADS + /* PyUnicode_AS_UNICODE OK without thread lock as + it is a simple dereference. */ + attr = GetFileAttributesW(PyUnicode_AS_UNICODE(po)); + Py_END_ALLOW_THREADS + goto finish; + } + /* Drop the argument parsing error as narrow strings + are also valid. */ + PyErr_Clear(); + } + if (!PyArg_ParseTuple(args, "eti:access", + Py_FileSystemDefaultEncoding, &path, &mode)) + return 0; + Py_BEGIN_ALLOW_THREADS + attr = GetFileAttributesA(path); + Py_END_ALLOW_THREADS + PyMem_Free(path); finish: - if (attr == 0xFFFFFFFF) - /* File does not exist, or cannot read attributes */ - return PyBool_FromLong(0); - /* Access is possible if either write access wasn't requested, or - the file isn't read-only, or if it's a directory, as there are - no read-only directories on Windows. */ - return PyBool_FromLong(!(mode & 2) - || !(attr & FILE_ATTRIBUTE_READONLY) - || (attr & FILE_ATTRIBUTE_DIRECTORY)); -#else - int res; - if (!PyArg_ParseTuple(args, "eti:access", - Py_FileSystemDefaultEncoding, &path, &mode)) - return NULL; - Py_BEGIN_ALLOW_THREADS - res = access(path, mode); - Py_END_ALLOW_THREADS - PyMem_Free(path); - return PyBool_FromLong(res == 0); + if (attr == 0xFFFFFFFF) + /* File does not exist, or cannot read attributes */ + return PyBool_FromLong(0); + /* Access is possible if either write access wasn't requested, or + the file isn't read-only, or if it's a directory, as there are + no read-only directories on Windows. */ + return PyBool_FromLong(!(mode & 2) + || !(attr & FILE_ATTRIBUTE_READONLY) + || (attr & FILE_ATTRIBUTE_DIRECTORY)); +#else + int res; + if (!PyArg_ParseTuple(args, "eti:access", + Py_FileSystemDefaultEncoding, &path, &mode)) + return NULL; + Py_BEGIN_ALLOW_THREADS + res = access(path, mode); + Py_END_ALLOW_THREADS + PyMem_Free(path); + return PyBool_FromLong(res == 0); #endif } @@ -1595,26 +1595,26 @@ static PyObject * posix_ttyname(PyObject *self, PyObject *args) { - int id; - char *ret; + int id; + char *ret; - if (!PyArg_ParseTuple(args, "i:ttyname", &id)) - return NULL; + if (!PyArg_ParseTuple(args, "i:ttyname", &id)) + return NULL; #if defined(__VMS) - /* file descriptor 0 only, the default input device (stdin) */ - if (id == 0) { - ret = ttyname(); - } - else { - ret = NULL; - } -#else - ret = ttyname(id); -#endif - if (ret == NULL) - return posix_error(); - return PyString_FromString(ret); + /* file descriptor 0 only, the default input device (stdin) */ + if (id == 0) { + ret = ttyname(); + } + else { + ret = NULL; + } +#else + ret = ttyname(id); +#endif + if (ret == NULL) + return posix_error(); + return PyString_FromString(ret); } #endif @@ -1626,17 +1626,17 @@ static PyObject * posix_ctermid(PyObject *self, PyObject *noargs) { - char *ret; - char buffer[L_ctermid]; + char *ret; + char buffer[L_ctermid]; #ifdef USE_CTERMID_R - ret = ctermid_r(buffer); + ret = ctermid_r(buffer); #else - ret = ctermid(buffer); + ret = ctermid(buffer); #endif - if (ret == NULL) - return posix_error(); - return PyString_FromString(buffer); + if (ret == NULL) + return posix_error(); + return PyString_FromString(buffer); } #endif @@ -1648,13 +1648,13 @@ posix_chdir(PyObject *self, PyObject *args) { #ifdef MS_WINDOWS - return win32_1str(args, "chdir", "s:chdir", win32_chdir, "U:chdir", win32_wchdir); + return win32_1str(args, "chdir", "s:chdir", win32_chdir, "U:chdir", win32_wchdir); #elif defined(PYOS_OS2) && defined(PYCC_GCC) - return posix_1str(args, "et:chdir", _chdir2); + return posix_1str(args, "et:chdir", _chdir2); #elif defined(__VMS) - return posix_1str(args, "et:chdir", (int (*)(const char *))chdir); + return posix_1str(args, "et:chdir", (int (*)(const char *))chdir); #else - return posix_1str(args, "et:chdir", chdir); + return posix_1str(args, "et:chdir", chdir); #endif } @@ -1667,7 +1667,7 @@ static PyObject * posix_fchdir(PyObject *self, PyObject *fdobj) { - return posix_fildes(fdobj, fchdir); + return posix_fildes(fdobj, fchdir); } #endif /* HAVE_FCHDIR */ @@ -1679,71 +1679,71 @@ static PyObject * posix_chmod(PyObject *self, PyObject *args) { - char *path = NULL; - int i; - int res; + char *path = NULL; + int i; + int res; #ifdef Py_WIN_WIDE_FILENAMES - DWORD attr; - if (unicode_file_names()) { - PyUnicodeObject *po; - if (PyArg_ParseTuple(args, "Ui|:chmod", &po, &i)) { - Py_BEGIN_ALLOW_THREADS - attr = GetFileAttributesW(PyUnicode_AS_UNICODE(po)); - if (attr != 0xFFFFFFFF) { - if (i & _S_IWRITE) - attr &= ~FILE_ATTRIBUTE_READONLY; - else - attr |= FILE_ATTRIBUTE_READONLY; - res = SetFileAttributesW(PyUnicode_AS_UNICODE(po), attr); - } - else - res = 0; - Py_END_ALLOW_THREADS - if (!res) - return win32_error_unicode("chmod", - PyUnicode_AS_UNICODE(po)); - Py_INCREF(Py_None); - return Py_None; - } - /* Drop the argument parsing error as narrow strings - are also valid. */ - PyErr_Clear(); - } - if (!PyArg_ParseTuple(args, "eti:chmod", Py_FileSystemDefaultEncoding, - &path, &i)) - return NULL; - Py_BEGIN_ALLOW_THREADS - attr = GetFileAttributesA(path); - if (attr != 0xFFFFFFFF) { - if (i & _S_IWRITE) - attr &= ~FILE_ATTRIBUTE_READONLY; - else - attr |= FILE_ATTRIBUTE_READONLY; - res = SetFileAttributesA(path, attr); - } - else - res = 0; - Py_END_ALLOW_THREADS - if (!res) { - win32_error("chmod", path); - PyMem_Free(path); - return NULL; - } - PyMem_Free(path); - Py_INCREF(Py_None); - return Py_None; + DWORD attr; + if (unicode_file_names()) { + PyUnicodeObject *po; + if (PyArg_ParseTuple(args, "Ui|:chmod", &po, &i)) { + Py_BEGIN_ALLOW_THREADS + attr = GetFileAttributesW(PyUnicode_AS_UNICODE(po)); + if (attr != 0xFFFFFFFF) { + if (i & _S_IWRITE) + attr &= ~FILE_ATTRIBUTE_READONLY; + else + attr |= FILE_ATTRIBUTE_READONLY; + res = SetFileAttributesW(PyUnicode_AS_UNICODE(po), attr); + } + else + res = 0; + Py_END_ALLOW_THREADS + if (!res) + return win32_error_unicode("chmod", + PyUnicode_AS_UNICODE(po)); + Py_INCREF(Py_None); + return Py_None; + } + /* Drop the argument parsing error as narrow strings + are also valid. */ + PyErr_Clear(); + } + if (!PyArg_ParseTuple(args, "eti:chmod", Py_FileSystemDefaultEncoding, + &path, &i)) + return NULL; + Py_BEGIN_ALLOW_THREADS + attr = GetFileAttributesA(path); + if (attr != 0xFFFFFFFF) { + if (i & _S_IWRITE) + attr &= ~FILE_ATTRIBUTE_READONLY; + else + attr |= FILE_ATTRIBUTE_READONLY; + res = SetFileAttributesA(path, attr); + } + else + res = 0; + Py_END_ALLOW_THREADS + if (!res) { + win32_error("chmod", path); + PyMem_Free(path); + return NULL; + } + PyMem_Free(path); + Py_INCREF(Py_None); + return Py_None; #else /* Py_WIN_WIDE_FILENAMES */ - if (!PyArg_ParseTuple(args, "eti:chmod", Py_FileSystemDefaultEncoding, - &path, &i)) - return NULL; - Py_BEGIN_ALLOW_THREADS - res = chmod(path, i); - Py_END_ALLOW_THREADS - if (res < 0) - return posix_error_with_allocated_filename(path); - PyMem_Free(path); - Py_INCREF(Py_None); - return Py_None; + if (!PyArg_ParseTuple(args, "eti:chmod", Py_FileSystemDefaultEncoding, + &path, &i)) + return NULL; + Py_BEGIN_ALLOW_THREADS + res = chmod(path, i); + Py_END_ALLOW_THREADS + if (res < 0) + return posix_error_with_allocated_filename(path); + PyMem_Free(path); + Py_INCREF(Py_None); + return Py_None; #endif } @@ -1756,15 +1756,15 @@ static PyObject * posix_fchmod(PyObject *self, PyObject *args) { - int fd, mode, res; - if (!PyArg_ParseTuple(args, "ii:fchmod", &fd, &mode)) - return NULL; - Py_BEGIN_ALLOW_THREADS - res = fchmod(fd, mode); - Py_END_ALLOW_THREADS - if (res < 0) - return posix_error(); - Py_RETURN_NONE; + int fd, mode, res; + if (!PyArg_ParseTuple(args, "ii:fchmod", &fd, &mode)) + return NULL; + Py_BEGIN_ALLOW_THREADS + res = fchmod(fd, mode); + Py_END_ALLOW_THREADS + if (res < 0) + return posix_error(); + Py_RETURN_NONE; } #endif /* HAVE_FCHMOD */ @@ -1777,19 +1777,19 @@ static PyObject * posix_lchmod(PyObject *self, PyObject *args) { - char *path = NULL; - int i; - int res; - if (!PyArg_ParseTuple(args, "eti:lchmod", Py_FileSystemDefaultEncoding, - &path, &i)) - return NULL; - Py_BEGIN_ALLOW_THREADS - res = lchmod(path, i); - Py_END_ALLOW_THREADS - if (res < 0) - return posix_error_with_allocated_filename(path); - PyMem_Free(path); - Py_RETURN_NONE; + char *path = NULL; + int i; + int res; + if (!PyArg_ParseTuple(args, "eti:lchmod", Py_FileSystemDefaultEncoding, + &path, &i)) + return NULL; + Py_BEGIN_ALLOW_THREADS + res = lchmod(path, i); + Py_END_ALLOW_THREADS + if (res < 0) + return posix_error_with_allocated_filename(path); + PyMem_Free(path); + Py_RETURN_NONE; } #endif /* HAVE_LCHMOD */ @@ -1802,20 +1802,20 @@ static PyObject * posix_chflags(PyObject *self, PyObject *args) { - char *path; - unsigned long flags; - int res; - if (!PyArg_ParseTuple(args, "etk:chflags", - Py_FileSystemDefaultEncoding, &path, &flags)) - return NULL; - Py_BEGIN_ALLOW_THREADS - res = chflags(path, flags); - Py_END_ALLOW_THREADS - if (res < 0) - return posix_error_with_allocated_filename(path); - PyMem_Free(path); - Py_INCREF(Py_None); - return Py_None; + char *path; + unsigned long flags; + int res; + if (!PyArg_ParseTuple(args, "etk:chflags", + Py_FileSystemDefaultEncoding, &path, &flags)) + return NULL; + Py_BEGIN_ALLOW_THREADS + res = chflags(path, flags); + Py_END_ALLOW_THREADS + if (res < 0) + return posix_error_with_allocated_filename(path); + PyMem_Free(path); + Py_INCREF(Py_None); + return Py_None; } #endif /* HAVE_CHFLAGS */ @@ -1828,20 +1828,20 @@ static PyObject * posix_lchflags(PyObject *self, PyObject *args) { - char *path; - unsigned long flags; - int res; - if (!PyArg_ParseTuple(args, "etk:lchflags", - Py_FileSystemDefaultEncoding, &path, &flags)) - return NULL; - Py_BEGIN_ALLOW_THREADS - res = lchflags(path, flags); - Py_END_ALLOW_THREADS - if (res < 0) - return posix_error_with_allocated_filename(path); - PyMem_Free(path); - Py_INCREF(Py_None); - return Py_None; + char *path; + unsigned long flags; + int res; + if (!PyArg_ParseTuple(args, "etk:lchflags", + Py_FileSystemDefaultEncoding, &path, &flags)) + return NULL; + Py_BEGIN_ALLOW_THREADS + res = lchflags(path, flags); + Py_END_ALLOW_THREADS + if (res < 0) + return posix_error_with_allocated_filename(path); + PyMem_Free(path); + Py_INCREF(Py_None); + return Py_None; } #endif /* HAVE_LCHFLAGS */ @@ -1853,7 +1853,7 @@ static PyObject * posix_chroot(PyObject *self, PyObject *args) { - return posix_1str(args, "et:chroot", chroot); + return posix_1str(args, "et:chroot", chroot); } #endif @@ -1896,21 +1896,21 @@ static PyObject * posix_chown(PyObject *self, PyObject *args) { - char *path = NULL; - long uid, gid; - int res; - if (!PyArg_ParseTuple(args, "etll:chown", - Py_FileSystemDefaultEncoding, &path, - &uid, &gid)) - return NULL; - Py_BEGIN_ALLOW_THREADS - res = chown(path, (uid_t) uid, (gid_t) gid); - Py_END_ALLOW_THREADS - if (res < 0) - return posix_error_with_allocated_filename(path); - PyMem_Free(path); - Py_INCREF(Py_None); - return Py_None; + char *path = NULL; + long uid, gid; + int res; + if (!PyArg_ParseTuple(args, "etll:chown", + Py_FileSystemDefaultEncoding, &path, + &uid, &gid)) + return NULL; + Py_BEGIN_ALLOW_THREADS + res = chown(path, (uid_t) uid, (gid_t) gid); + Py_END_ALLOW_THREADS + if (res < 0) + return posix_error_with_allocated_filename(path); + PyMem_Free(path); + Py_INCREF(Py_None); + return Py_None; } #endif /* HAVE_CHOWN */ @@ -1923,17 +1923,17 @@ static PyObject * posix_fchown(PyObject *self, PyObject *args) { - int fd; - long uid, gid; - int res; - if (!PyArg_ParseTuple(args, "ill:chown", &fd, &uid, &gid)) - return NULL; - Py_BEGIN_ALLOW_THREADS - res = fchown(fd, (uid_t) uid, (gid_t) gid); - Py_END_ALLOW_THREADS - if (res < 0) - return posix_error(); - Py_RETURN_NONE; + int fd; + long uid, gid; + int res; + if (!PyArg_ParseTuple(args, "ill:chown", &fd, &uid, &gid)) + return NULL; + Py_BEGIN_ALLOW_THREADS + res = fchown(fd, (uid_t) uid, (gid_t) gid); + Py_END_ALLOW_THREADS + if (res < 0) + return posix_error(); + Py_RETURN_NONE; } #endif /* HAVE_FCHOWN */ @@ -1946,21 +1946,21 @@ static PyObject * posix_lchown(PyObject *self, PyObject *args) { - char *path = NULL; - long uid, gid; - int res; - if (!PyArg_ParseTuple(args, "etll:lchown", - Py_FileSystemDefaultEncoding, &path, - &uid, &gid)) - return NULL; - Py_BEGIN_ALLOW_THREADS - res = lchown(path, (uid_t) uid, (gid_t) gid); - Py_END_ALLOW_THREADS - if (res < 0) - return posix_error_with_allocated_filename(path); - PyMem_Free(path); - Py_INCREF(Py_None); - return Py_None; + char *path = NULL; + long uid, gid; + int res; + if (!PyArg_ParseTuple(args, "etll:lchown", + Py_FileSystemDefaultEncoding, &path, + &uid, &gid)) + return NULL; + Py_BEGIN_ALLOW_THREADS + res = lchown(path, (uid_t) uid, (gid_t) gid); + Py_END_ALLOW_THREADS + if (res < 0) + return posix_error_with_allocated_filename(path); + PyMem_Free(path); + Py_INCREF(Py_None); + return Py_None; } #endif /* HAVE_LCHOWN */ @@ -1973,38 +1973,38 @@ static PyObject * posix_getcwd(PyObject *self, PyObject *noargs) { - int bufsize_incr = 1024; - int bufsize = 0; - char *tmpbuf = NULL; - char *res = NULL; - PyObject *dynamic_return; - - Py_BEGIN_ALLOW_THREADS - do { - bufsize = bufsize + bufsize_incr; - tmpbuf = malloc(bufsize); - if (tmpbuf == NULL) { - break; - } + int bufsize_incr = 1024; + int bufsize = 0; + char *tmpbuf = NULL; + char *res = NULL; + PyObject *dynamic_return; + + Py_BEGIN_ALLOW_THREADS + do { + bufsize = bufsize + bufsize_incr; + tmpbuf = malloc(bufsize); + if (tmpbuf == NULL) { + break; + } #if defined(PYOS_OS2) && defined(PYCC_GCC) - res = _getcwd2(tmpbuf, bufsize); + res = _getcwd2(tmpbuf, bufsize); #else - res = getcwd(tmpbuf, bufsize); + res = getcwd(tmpbuf, bufsize); #endif - if (res == NULL) { - free(tmpbuf); - } - } while ((res == NULL) && (errno == ERANGE)); - Py_END_ALLOW_THREADS + if (res == NULL) { + free(tmpbuf); + } + } while ((res == NULL) && (errno == ERANGE)); + Py_END_ALLOW_THREADS - if (res == NULL) - return posix_error(); + if (res == NULL) + return posix_error(); - dynamic_return = PyString_FromString(tmpbuf); - free(tmpbuf); + dynamic_return = PyString_FromString(tmpbuf); + free(tmpbuf); - return dynamic_return; + return dynamic_return; } #ifdef Py_USING_UNICODE @@ -2015,50 +2015,50 @@ static PyObject * posix_getcwdu(PyObject *self, PyObject *noargs) { - char buf[1026]; - char *res; + char buf[1026]; + char *res; #ifdef Py_WIN_WIDE_FILENAMES - DWORD len; - if (unicode_file_names()) { - wchar_t wbuf[1026]; - wchar_t *wbuf2 = wbuf; - PyObject *resobj; - Py_BEGIN_ALLOW_THREADS - len = GetCurrentDirectoryW(sizeof wbuf/ sizeof wbuf[0], wbuf); - /* If the buffer is large enough, len does not include the - terminating \0. If the buffer is too small, len includes - the space needed for the terminator. */ - if (len >= sizeof wbuf/ sizeof wbuf[0]) { - wbuf2 = malloc(len * sizeof(wchar_t)); - if (wbuf2) - len = GetCurrentDirectoryW(len, wbuf2); - } - Py_END_ALLOW_THREADS - if (!wbuf2) { - PyErr_NoMemory(); - return NULL; - } - if (!len) { - if (wbuf2 != wbuf) free(wbuf2); - return win32_error("getcwdu", NULL); - } - resobj = PyUnicode_FromWideChar(wbuf2, len); - if (wbuf2 != wbuf) free(wbuf2); - return resobj; - } + DWORD len; + if (unicode_file_names()) { + wchar_t wbuf[1026]; + wchar_t *wbuf2 = wbuf; + PyObject *resobj; + Py_BEGIN_ALLOW_THREADS + len = GetCurrentDirectoryW(sizeof wbuf/ sizeof wbuf[0], wbuf); + /* If the buffer is large enough, len does not include the + terminating \0. If the buffer is too small, len includes + the space needed for the terminator. */ + if (len >= sizeof wbuf/ sizeof wbuf[0]) { + wbuf2 = malloc(len * sizeof(wchar_t)); + if (wbuf2) + len = GetCurrentDirectoryW(len, wbuf2); + } + Py_END_ALLOW_THREADS + if (!wbuf2) { + PyErr_NoMemory(); + return NULL; + } + if (!len) { + if (wbuf2 != wbuf) free(wbuf2); + return win32_error("getcwdu", NULL); + } + resobj = PyUnicode_FromWideChar(wbuf2, len); + if (wbuf2 != wbuf) free(wbuf2); + return resobj; + } #endif - Py_BEGIN_ALLOW_THREADS + Py_BEGIN_ALLOW_THREADS #if defined(PYOS_OS2) && defined(PYCC_GCC) - res = _getcwd2(buf, sizeof buf); + res = _getcwd2(buf, sizeof buf); #else - res = getcwd(buf, sizeof buf); + res = getcwd(buf, sizeof buf); #endif - Py_END_ALLOW_THREADS - if (res == NULL) - return posix_error(); - return PyUnicode_Decode(buf, strlen(buf), Py_FileSystemDefaultEncoding,"strict"); + Py_END_ALLOW_THREADS + if (res == NULL) + return posix_error(); + return PyUnicode_Decode(buf, strlen(buf), Py_FileSystemDefaultEncoding,"strict"); } #endif #endif @@ -2072,7 +2072,7 @@ static PyObject * posix_link(PyObject *self, PyObject *args) { - return posix_2str(args, "etet:link", link); + return posix_2str(args, "etet:link", link); } #endif /* HAVE_LINK */ @@ -2081,7 +2081,7 @@ "listdir(path) -> list_of_strings\n\n\ Return a list containing the names of the entries in the directory.\n\ \n\ - path: path of directory to list\n\ + path: path of directory to list\n\ \n\ The list is in arbitrary order. It does not include the special\n\ entries '.' and '..' even if they are present in the directory."); @@ -2089,160 +2089,160 @@ static PyObject * posix_listdir(PyObject *self, PyObject *args) { - /* XXX Should redo this putting the (now four) versions of opendir - in separate files instead of having them all here... */ + /* XXX Should redo this putting the (now four) versions of opendir + in separate files instead of having them all here... */ #if defined(MS_WINDOWS) && !defined(HAVE_OPENDIR) - PyObject *d, *v; - HANDLE hFindFile; - BOOL result; - WIN32_FIND_DATA FileData; - char namebuf[MAX_PATH+5]; /* Overallocate for \\*.*\0 */ - char *bufptr = namebuf; - Py_ssize_t len = sizeof(namebuf)-5; /* only claim to have space for MAX_PATH */ + PyObject *d, *v; + HANDLE hFindFile; + BOOL result; + WIN32_FIND_DATA FileData; + char namebuf[MAX_PATH+5]; /* Overallocate for \\*.*\0 */ + char *bufptr = namebuf; + Py_ssize_t len = sizeof(namebuf)-5; /* only claim to have space for MAX_PATH */ #ifdef Py_WIN_WIDE_FILENAMES - /* If on wide-character-capable OS see if argument - is Unicode and if so use wide API. */ - if (unicode_file_names()) { - PyObject *po; - if (PyArg_ParseTuple(args, "U:listdir", &po)) { - WIN32_FIND_DATAW wFileData; - Py_UNICODE *wnamebuf; - Py_UNICODE wch; - /* Overallocate for \\*.*\0 */ - len = PyUnicode_GET_SIZE(po); - wnamebuf = malloc((len + 5) * sizeof(wchar_t)); - if (!wnamebuf) { - PyErr_NoMemory(); - return NULL; - } - wcscpy(wnamebuf, PyUnicode_AS_UNICODE(po)); - wch = len > 0 ? wnamebuf[len-1] : '\0'; - if (wch != L'/' && wch != L'\\' && wch != L':') - wnamebuf[len++] = L'\\'; - wcscpy(wnamebuf + len, L"*.*"); - if ((d = PyList_New(0)) == NULL) { - free(wnamebuf); - return NULL; - } - hFindFile = FindFirstFileW(wnamebuf, &wFileData); - if (hFindFile == INVALID_HANDLE_VALUE) { - int error = GetLastError(); - if (error == ERROR_FILE_NOT_FOUND) { - free(wnamebuf); - return d; - } - Py_DECREF(d); - win32_error_unicode("FindFirstFileW", wnamebuf); - free(wnamebuf); - return NULL; - } - do { - /* Skip over . and .. */ - if (wcscmp(wFileData.cFileName, L".") != 0 && - wcscmp(wFileData.cFileName, L"..") != 0) { - v = PyUnicode_FromUnicode(wFileData.cFileName, wcslen(wFileData.cFileName)); - if (v == NULL) { - Py_DECREF(d); - d = NULL; - break; - } - if (PyList_Append(d, v) != 0) { - Py_DECREF(v); - Py_DECREF(d); - d = NULL; - break; - } - Py_DECREF(v); - } - Py_BEGIN_ALLOW_THREADS - result = FindNextFileW(hFindFile, &wFileData); - Py_END_ALLOW_THREADS - /* FindNextFile sets error to ERROR_NO_MORE_FILES if - it got to the end of the directory. */ - if (!result && GetLastError() != ERROR_NO_MORE_FILES) { - Py_DECREF(d); - win32_error_unicode("FindNextFileW", wnamebuf); - FindClose(hFindFile); - free(wnamebuf); - return NULL; - } - } while (result == TRUE); - - if (FindClose(hFindFile) == FALSE) { - Py_DECREF(d); - win32_error_unicode("FindClose", wnamebuf); - free(wnamebuf); - return NULL; - } - free(wnamebuf); - return d; - } - /* Drop the argument parsing error as narrow strings - are also valid. */ - PyErr_Clear(); - } -#endif - - if (!PyArg_ParseTuple(args, "et#:listdir", - Py_FileSystemDefaultEncoding, &bufptr, &len)) - return NULL; - if (len > 0) { - char ch = namebuf[len-1]; - if (ch != SEP && ch != ALTSEP && ch != ':') - namebuf[len++] = '/'; - } - strcpy(namebuf + len, "*.*"); - - if ((d = PyList_New(0)) == NULL) - return NULL; - - hFindFile = FindFirstFile(namebuf, &FileData); - if (hFindFile == INVALID_HANDLE_VALUE) { - int error = GetLastError(); - if (error == ERROR_FILE_NOT_FOUND) - return d; - Py_DECREF(d); - return win32_error("FindFirstFile", namebuf); - } - do { - /* Skip over . and .. */ - if (strcmp(FileData.cFileName, ".") != 0 && - strcmp(FileData.cFileName, "..") != 0) { - v = PyString_FromString(FileData.cFileName); - if (v == NULL) { - Py_DECREF(d); - d = NULL; - break; - } - if (PyList_Append(d, v) != 0) { - Py_DECREF(v); - Py_DECREF(d); - d = NULL; - break; - } - Py_DECREF(v); - } - Py_BEGIN_ALLOW_THREADS - result = FindNextFile(hFindFile, &FileData); - Py_END_ALLOW_THREADS - /* FindNextFile sets error to ERROR_NO_MORE_FILES if - it got to the end of the directory. */ - if (!result && GetLastError() != ERROR_NO_MORE_FILES) { - Py_DECREF(d); - win32_error("FindNextFile", namebuf); - FindClose(hFindFile); - return NULL; - } - } while (result == TRUE); - - if (FindClose(hFindFile) == FALSE) { - Py_DECREF(d); - return win32_error("FindClose", namebuf); - } + /* If on wide-character-capable OS see if argument + is Unicode and if so use wide API. */ + if (unicode_file_names()) { + PyObject *po; + if (PyArg_ParseTuple(args, "U:listdir", &po)) { + WIN32_FIND_DATAW wFileData; + Py_UNICODE *wnamebuf; + Py_UNICODE wch; + /* Overallocate for \\*.*\0 */ + len = PyUnicode_GET_SIZE(po); + wnamebuf = malloc((len + 5) * sizeof(wchar_t)); + if (!wnamebuf) { + PyErr_NoMemory(); + return NULL; + } + wcscpy(wnamebuf, PyUnicode_AS_UNICODE(po)); + wch = len > 0 ? wnamebuf[len-1] : '\0'; + if (wch != L'/' && wch != L'\\' && wch != L':') + wnamebuf[len++] = L'\\'; + wcscpy(wnamebuf + len, L"*.*"); + if ((d = PyList_New(0)) == NULL) { + free(wnamebuf); + return NULL; + } + hFindFile = FindFirstFileW(wnamebuf, &wFileData); + if (hFindFile == INVALID_HANDLE_VALUE) { + int error = GetLastError(); + if (error == ERROR_FILE_NOT_FOUND) { + free(wnamebuf); + return d; + } + Py_DECREF(d); + win32_error_unicode("FindFirstFileW", wnamebuf); + free(wnamebuf); + return NULL; + } + do { + /* Skip over . and .. */ + if (wcscmp(wFileData.cFileName, L".") != 0 && + wcscmp(wFileData.cFileName, L"..") != 0) { + v = PyUnicode_FromUnicode(wFileData.cFileName, wcslen(wFileData.cFileName)); + if (v == NULL) { + Py_DECREF(d); + d = NULL; + break; + } + if (PyList_Append(d, v) != 0) { + Py_DECREF(v); + Py_DECREF(d); + d = NULL; + break; + } + Py_DECREF(v); + } + Py_BEGIN_ALLOW_THREADS + result = FindNextFileW(hFindFile, &wFileData); + Py_END_ALLOW_THREADS + /* FindNextFile sets error to ERROR_NO_MORE_FILES if + it got to the end of the directory. */ + if (!result && GetLastError() != ERROR_NO_MORE_FILES) { + Py_DECREF(d); + win32_error_unicode("FindNextFileW", wnamebuf); + FindClose(hFindFile); + free(wnamebuf); + return NULL; + } + } while (result == TRUE); + + if (FindClose(hFindFile) == FALSE) { + Py_DECREF(d); + win32_error_unicode("FindClose", wnamebuf); + free(wnamebuf); + return NULL; + } + free(wnamebuf); + return d; + } + /* Drop the argument parsing error as narrow strings + are also valid. */ + PyErr_Clear(); + } +#endif + + if (!PyArg_ParseTuple(args, "et#:listdir", + Py_FileSystemDefaultEncoding, &bufptr, &len)) + return NULL; + if (len > 0) { + char ch = namebuf[len-1]; + if (ch != SEP && ch != ALTSEP && ch != ':') + namebuf[len++] = '/'; + } + strcpy(namebuf + len, "*.*"); + + if ((d = PyList_New(0)) == NULL) + return NULL; + + hFindFile = FindFirstFile(namebuf, &FileData); + if (hFindFile == INVALID_HANDLE_VALUE) { + int error = GetLastError(); + if (error == ERROR_FILE_NOT_FOUND) + return d; + Py_DECREF(d); + return win32_error("FindFirstFile", namebuf); + } + do { + /* Skip over . and .. */ + if (strcmp(FileData.cFileName, ".") != 0 && + strcmp(FileData.cFileName, "..") != 0) { + v = PyString_FromString(FileData.cFileName); + if (v == NULL) { + Py_DECREF(d); + d = NULL; + break; + } + if (PyList_Append(d, v) != 0) { + Py_DECREF(v); + Py_DECREF(d); + d = NULL; + break; + } + Py_DECREF(v); + } + Py_BEGIN_ALLOW_THREADS + result = FindNextFile(hFindFile, &FileData); + Py_END_ALLOW_THREADS + /* FindNextFile sets error to ERROR_NO_MORE_FILES if + it got to the end of the directory. */ + if (!result && GetLastError() != ERROR_NO_MORE_FILES) { + Py_DECREF(d); + win32_error("FindNextFile", namebuf); + FindClose(hFindFile); + return NULL; + } + } while (result == TRUE); + + if (FindClose(hFindFile) == FALSE) { + Py_DECREF(d); + return win32_error("FindClose", namebuf); + } - return d; + return d; #elif defined(PYOS_OS2) @@ -2261,7 +2261,7 @@ if (!PyArg_ParseTuple(args, "t#:listdir", &name, &len)) return NULL; if (len >= MAX_PATH) { - PyErr_SetString(PyExc_ValueError, "path too long"); + PyErr_SetString(PyExc_ValueError, "path too long"); return NULL; } strcpy(namebuf, name); @@ -2272,7 +2272,7 @@ namebuf[len++] = SEP; strcpy(namebuf + len, "*.*"); - if ((d = PyList_New(0)) == NULL) + if ((d = PyList_New(0)) == NULL) return NULL; rc = DosFindFirst(namebuf, /* Wildcard Pattern to Match */ @@ -2317,81 +2317,81 @@ return d; #else - char *name = NULL; - PyObject *d, *v; - DIR *dirp; - struct dirent *ep; - int arg_is_unicode = 1; - - errno = 0; - if (!PyArg_ParseTuple(args, "U:listdir", &v)) { - arg_is_unicode = 0; - PyErr_Clear(); - } - if (!PyArg_ParseTuple(args, "et:listdir", Py_FileSystemDefaultEncoding, &name)) - return NULL; - if ((dirp = opendir(name)) == NULL) { - return posix_error_with_allocated_filename(name); - } - if ((d = PyList_New(0)) == NULL) { - closedir(dirp); - PyMem_Free(name); - return NULL; - } - for (;;) { - errno = 0; - Py_BEGIN_ALLOW_THREADS - ep = readdir(dirp); - Py_END_ALLOW_THREADS - if (ep == NULL) { - if (errno == 0) { - break; - } else { - closedir(dirp); - Py_DECREF(d); - return posix_error_with_allocated_filename(name); - } - } - if (ep->d_name[0] == '.' && - (NAMLEN(ep) == 1 || - (ep->d_name[1] == '.' && NAMLEN(ep) == 2))) - continue; - v = PyString_FromStringAndSize(ep->d_name, NAMLEN(ep)); - if (v == NULL) { - Py_DECREF(d); - d = NULL; - break; - } + char *name = NULL; + PyObject *d, *v; + DIR *dirp; + struct dirent *ep; + int arg_is_unicode = 1; + + errno = 0; + if (!PyArg_ParseTuple(args, "U:listdir", &v)) { + arg_is_unicode = 0; + PyErr_Clear(); + } + if (!PyArg_ParseTuple(args, "et:listdir", Py_FileSystemDefaultEncoding, &name)) + return NULL; + if ((dirp = opendir(name)) == NULL) { + return posix_error_with_allocated_filename(name); + } + if ((d = PyList_New(0)) == NULL) { + closedir(dirp); + PyMem_Free(name); + return NULL; + } + for (;;) { + errno = 0; + Py_BEGIN_ALLOW_THREADS + ep = readdir(dirp); + Py_END_ALLOW_THREADS + if (ep == NULL) { + if (errno == 0) { + break; + } else { + closedir(dirp); + Py_DECREF(d); + return posix_error_with_allocated_filename(name); + } + } + if (ep->d_name[0] == '.' && + (NAMLEN(ep) == 1 || + (ep->d_name[1] == '.' && NAMLEN(ep) == 2))) + continue; + v = PyString_FromStringAndSize(ep->d_name, NAMLEN(ep)); + if (v == NULL) { + Py_DECREF(d); + d = NULL; + break; + } #ifdef Py_USING_UNICODE - if (arg_is_unicode) { - PyObject *w; + if (arg_is_unicode) { + PyObject *w; - w = PyUnicode_FromEncodedObject(v, - Py_FileSystemDefaultEncoding, - "strict"); - if (w != NULL) { - Py_DECREF(v); - v = w; - } - else { - /* fall back to the original byte string, as - discussed in patch #683592 */ - PyErr_Clear(); - } - } -#endif - if (PyList_Append(d, v) != 0) { - Py_DECREF(v); - Py_DECREF(d); - d = NULL; - break; - } - Py_DECREF(v); - } - closedir(dirp); - PyMem_Free(name); + w = PyUnicode_FromEncodedObject(v, + Py_FileSystemDefaultEncoding, + "strict"); + if (w != NULL) { + Py_DECREF(v); + v = w; + } + else { + /* fall back to the original byte string, as + discussed in patch #683592 */ + PyErr_Clear(); + } + } +#endif + if (PyList_Append(d, v) != 0) { + Py_DECREF(v); + Py_DECREF(d); + d = NULL; + break; + } + Py_DECREF(v); + } + closedir(dirp); + PyMem_Free(name); - return d; + return d; #endif /* which OS */ } /* end of posix_listdir */ @@ -2401,55 +2401,55 @@ static PyObject * posix__getfullpathname(PyObject *self, PyObject *args) { - /* assume encoded strings won't more than double no of chars */ - char inbuf[MAX_PATH*2]; - char *inbufp = inbuf; - Py_ssize_t insize = sizeof(inbuf); - char outbuf[MAX_PATH*2]; - char *temp; + /* assume encoded strings won't more than double no of chars */ + char inbuf[MAX_PATH*2]; + char *inbufp = inbuf; + Py_ssize_t insize = sizeof(inbuf); + char outbuf[MAX_PATH*2]; + char *temp; #ifdef Py_WIN_WIDE_FILENAMES - if (unicode_file_names()) { - PyUnicodeObject *po; - if (PyArg_ParseTuple(args, "U|:_getfullpathname", &po)) { - Py_UNICODE *wpath = PyUnicode_AS_UNICODE(po); - Py_UNICODE woutbuf[MAX_PATH*2], *woutbufp = woutbuf; - Py_UNICODE *wtemp; - DWORD result; - PyObject *v; - result = GetFullPathNameW(wpath, - sizeof(woutbuf)/sizeof(woutbuf[0]), - woutbuf, &wtemp); - if (result > sizeof(woutbuf)/sizeof(woutbuf[0])) { - woutbufp = malloc(result * sizeof(Py_UNICODE)); - if (!woutbufp) - return PyErr_NoMemory(); - result = GetFullPathNameW(wpath, result, woutbufp, &wtemp); - } - if (result) - v = PyUnicode_FromUnicode(woutbufp, wcslen(woutbufp)); - else - v = win32_error_unicode("GetFullPathNameW", wpath); - if (woutbufp != woutbuf) - free(woutbufp); - return v; - } - /* Drop the argument parsing error as narrow strings - are also valid. */ - PyErr_Clear(); - } -#endif - if (!PyArg_ParseTuple (args, "et#:_getfullpathname", - Py_FileSystemDefaultEncoding, &inbufp, - &insize)) - return NULL; - if (!GetFullPathName(inbuf, sizeof(outbuf)/sizeof(outbuf[0]), - outbuf, &temp)) - return win32_error("GetFullPathName", inbuf); - if (PyUnicode_Check(PyTuple_GetItem(args, 0))) { - return PyUnicode_Decode(outbuf, strlen(outbuf), - Py_FileSystemDefaultEncoding, NULL); - } - return PyString_FromString(outbuf); + if (unicode_file_names()) { + PyUnicodeObject *po; + if (PyArg_ParseTuple(args, "U|:_getfullpathname", &po)) { + Py_UNICODE *wpath = PyUnicode_AS_UNICODE(po); + Py_UNICODE woutbuf[MAX_PATH*2], *woutbufp = woutbuf; + Py_UNICODE *wtemp; + DWORD result; + PyObject *v; + result = GetFullPathNameW(wpath, + sizeof(woutbuf)/sizeof(woutbuf[0]), + woutbuf, &wtemp); + if (result > sizeof(woutbuf)/sizeof(woutbuf[0])) { + woutbufp = malloc(result * sizeof(Py_UNICODE)); + if (!woutbufp) + return PyErr_NoMemory(); + result = GetFullPathNameW(wpath, result, woutbufp, &wtemp); + } + if (result) + v = PyUnicode_FromUnicode(woutbufp, wcslen(woutbufp)); + else + v = win32_error_unicode("GetFullPathNameW", wpath); + if (woutbufp != woutbuf) + free(woutbufp); + return v; + } + /* Drop the argument parsing error as narrow strings + are also valid. */ + PyErr_Clear(); + } +#endif + if (!PyArg_ParseTuple (args, "et#:_getfullpathname", + Py_FileSystemDefaultEncoding, &inbufp, + &insize)) + return NULL; + if (!GetFullPathName(inbuf, sizeof(outbuf)/sizeof(outbuf[0]), + outbuf, &temp)) + return win32_error("GetFullPathName", inbuf); + if (PyUnicode_Check(PyTuple_GetItem(args, 0))) { + return PyUnicode_Decode(outbuf, strlen(outbuf), + Py_FileSystemDefaultEncoding, NULL); + } + return PyString_FromString(outbuf); } /* end of posix__getfullpathname */ #endif /* MS_WINDOWS */ @@ -2460,64 +2460,64 @@ static PyObject * posix_mkdir(PyObject *self, PyObject *args) { - int res; - char *path = NULL; - int mode = 0777; + int res; + char *path = NULL; + int mode = 0777; #ifdef Py_WIN_WIDE_FILENAMES - if (unicode_file_names()) { - PyUnicodeObject *po; - if (PyArg_ParseTuple(args, "U|i:mkdir", &po, &mode)) { - Py_BEGIN_ALLOW_THREADS - /* PyUnicode_AS_UNICODE OK without thread lock as - it is a simple dereference. */ - res = CreateDirectoryW(PyUnicode_AS_UNICODE(po), NULL); - Py_END_ALLOW_THREADS - if (!res) - return win32_error_unicode("mkdir", PyUnicode_AS_UNICODE(po)); - Py_INCREF(Py_None); - return Py_None; - } - /* Drop the argument parsing error as narrow strings - are also valid. */ - PyErr_Clear(); - } - if (!PyArg_ParseTuple(args, "et|i:mkdir", - Py_FileSystemDefaultEncoding, &path, &mode)) - return NULL; - Py_BEGIN_ALLOW_THREADS - /* PyUnicode_AS_UNICODE OK without thread lock as - it is a simple dereference. */ - res = CreateDirectoryA(path, NULL); - Py_END_ALLOW_THREADS - if (!res) { - win32_error("mkdir", path); - PyMem_Free(path); - return NULL; - } - PyMem_Free(path); - Py_INCREF(Py_None); - return Py_None; -#else - - if (!PyArg_ParseTuple(args, "et|i:mkdir", - Py_FileSystemDefaultEncoding, &path, &mode)) - return NULL; - Py_BEGIN_ALLOW_THREADS -#if ( defined(__WATCOMC__) || defined(PYCC_VACPP) ) && !defined(__QNX__) - res = mkdir(path); -#else - res = mkdir(path, mode); -#endif - Py_END_ALLOW_THREADS - if (res < 0) - return posix_error_with_allocated_filename(path); - PyMem_Free(path); - Py_INCREF(Py_None); - return Py_None; -#endif -} - + if (unicode_file_names()) { + PyUnicodeObject *po; + if (PyArg_ParseTuple(args, "U|i:mkdir", &po, &mode)) { + Py_BEGIN_ALLOW_THREADS + /* PyUnicode_AS_UNICODE OK without thread lock as + it is a simple dereference. */ + res = CreateDirectoryW(PyUnicode_AS_UNICODE(po), NULL); + Py_END_ALLOW_THREADS + if (!res) + return win32_error_unicode("mkdir", PyUnicode_AS_UNICODE(po)); + Py_INCREF(Py_None); + return Py_None; + } + /* Drop the argument parsing error as narrow strings + are also valid. */ + PyErr_Clear(); + } + if (!PyArg_ParseTuple(args, "et|i:mkdir", + Py_FileSystemDefaultEncoding, &path, &mode)) + return NULL; + Py_BEGIN_ALLOW_THREADS + /* PyUnicode_AS_UNICODE OK without thread lock as + it is a simple dereference. */ + res = CreateDirectoryA(path, NULL); + Py_END_ALLOW_THREADS + if (!res) { + win32_error("mkdir", path); + PyMem_Free(path); + return NULL; + } + PyMem_Free(path); + Py_INCREF(Py_None); + return Py_None; +#else + + if (!PyArg_ParseTuple(args, "et|i:mkdir", + Py_FileSystemDefaultEncoding, &path, &mode)) + return NULL; + Py_BEGIN_ALLOW_THREADS +#if ( defined(__WATCOMC__) || defined(PYCC_VACPP) ) && !defined(__QNX__) + res = mkdir(path); +#else + res = mkdir(path, mode); +#endif + Py_END_ALLOW_THREADS + if (res < 0) + return posix_error_with_allocated_filename(path); + PyMem_Free(path); + Py_INCREF(Py_None); + return Py_None; +#endif +} + /* sys/resource.h is needed for at least: wait3(), wait4(), broken nice. */ #if defined(HAVE_SYS_RESOURCE_H) @@ -2533,31 +2533,31 @@ static PyObject * posix_nice(PyObject *self, PyObject *args) { - int increment, value; + int increment, value; - if (!PyArg_ParseTuple(args, "i:nice", &increment)) - return NULL; + if (!PyArg_ParseTuple(args, "i:nice", &increment)) + return NULL; - /* There are two flavours of 'nice': one that returns the new - priority (as required by almost all standards out there) and the - Linux/FreeBSD/BSDI one, which returns '0' on success and advices - the use of getpriority() to get the new priority. - - If we are of the nice family that returns the new priority, we - need to clear errno before the call, and check if errno is filled - before calling posix_error() on a returnvalue of -1, because the - -1 may be the actual new priority! */ + /* There are two flavours of 'nice': one that returns the new + priority (as required by almost all standards out there) and the + Linux/FreeBSD/BSDI one, which returns '0' on success and advices + the use of getpriority() to get the new priority. + + If we are of the nice family that returns the new priority, we + need to clear errno before the call, and check if errno is filled + before calling posix_error() on a returnvalue of -1, because the + -1 may be the actual new priority! */ - errno = 0; - value = nice(increment); + errno = 0; + value = nice(increment); #if defined(HAVE_BROKEN_NICE) && defined(HAVE_GETPRIORITY) - if (value == 0) - value = getpriority(PRIO_PROCESS, 0); + if (value == 0) + value = getpriority(PRIO_PROCESS, 0); #endif - if (value == -1 && errno != 0) - /* either nice() or getpriority() returned an error */ - return posix_error(); - return PyInt_FromLong((long) value); + if (value == -1 && errno != 0) + /* either nice() or getpriority() returned an error */ + return posix_error(); + return PyInt_FromLong((long) value); } #endif /* HAVE_NICE */ @@ -2569,42 +2569,42 @@ posix_rename(PyObject *self, PyObject *args) { #ifdef MS_WINDOWS - PyObject *o1, *o2; - char *p1, *p2; - BOOL result; - if (unicode_file_names()) { - if (!PyArg_ParseTuple(args, "OO:rename", &o1, &o2)) - goto error; - if (!convert_to_unicode(&o1)) - goto error; - if (!convert_to_unicode(&o2)) { - Py_DECREF(o1); - goto error; - } - Py_BEGIN_ALLOW_THREADS - result = MoveFileW(PyUnicode_AsUnicode(o1), - PyUnicode_AsUnicode(o2)); - Py_END_ALLOW_THREADS - Py_DECREF(o1); - Py_DECREF(o2); - if (!result) - return win32_error("rename", NULL); - Py_INCREF(Py_None); - return Py_None; + PyObject *o1, *o2; + char *p1, *p2; + BOOL result; + if (unicode_file_names()) { + if (!PyArg_ParseTuple(args, "OO:rename", &o1, &o2)) + goto error; + if (!convert_to_unicode(&o1)) + goto error; + if (!convert_to_unicode(&o2)) { + Py_DECREF(o1); + goto error; + } + Py_BEGIN_ALLOW_THREADS + result = MoveFileW(PyUnicode_AsUnicode(o1), + PyUnicode_AsUnicode(o2)); + Py_END_ALLOW_THREADS + Py_DECREF(o1); + Py_DECREF(o2); + if (!result) + return win32_error("rename", NULL); + Py_INCREF(Py_None); + return Py_None; error: - PyErr_Clear(); - } - if (!PyArg_ParseTuple(args, "ss:rename", &p1, &p2)) - return NULL; - Py_BEGIN_ALLOW_THREADS - result = MoveFileA(p1, p2); - Py_END_ALLOW_THREADS - if (!result) - return win32_error("rename", NULL); - Py_INCREF(Py_None); - return Py_None; + PyErr_Clear(); + } + if (!PyArg_ParseTuple(args, "ss:rename", &p1, &p2)) + return NULL; + Py_BEGIN_ALLOW_THREADS + result = MoveFileA(p1, p2); + Py_END_ALLOW_THREADS + if (!result) + return win32_error("rename", NULL); + Py_INCREF(Py_None); + return Py_None; #else - return posix_2str(args, "etet:rename", rename); + return posix_2str(args, "etet:rename", rename); #endif } @@ -2617,9 +2617,9 @@ posix_rmdir(PyObject *self, PyObject *args) { #ifdef MS_WINDOWS - return win32_1str(args, "rmdir", "s:rmdir", RemoveDirectoryA, "U:rmdir", RemoveDirectoryW); + return win32_1str(args, "rmdir", "s:rmdir", RemoveDirectoryA, "U:rmdir", RemoveDirectoryW); #else - return posix_1str(args, "et:rmdir", rmdir); + return posix_1str(args, "et:rmdir", rmdir); #endif } @@ -2632,9 +2632,9 @@ posix_stat(PyObject *self, PyObject *args) { #ifdef MS_WINDOWS - return posix_do_stat(self, args, "et:stat", STAT, "U:stat", win32_wstat); + return posix_do_stat(self, args, "et:stat", STAT, "U:stat", win32_wstat); #else - return posix_do_stat(self, args, "et:stat", STAT, NULL, NULL); + return posix_do_stat(self, args, "et:stat", STAT, NULL, NULL); #endif } @@ -2647,14 +2647,14 @@ static PyObject * posix_system(PyObject *self, PyObject *args) { - char *command; - long sts; - if (!PyArg_ParseTuple(args, "s:system", &command)) - return NULL; - Py_BEGIN_ALLOW_THREADS - sts = system(command); - Py_END_ALLOW_THREADS - return PyInt_FromLong(sts); + char *command; + long sts; + if (!PyArg_ParseTuple(args, "s:system", &command)) + return NULL; + Py_BEGIN_ALLOW_THREADS + sts = system(command); + Py_END_ALLOW_THREADS + return PyInt_FromLong(sts); } #endif @@ -2666,13 +2666,13 @@ static PyObject * posix_umask(PyObject *self, PyObject *args) { - int i; - if (!PyArg_ParseTuple(args, "i:umask", &i)) - return NULL; - i = (int)umask(i); - if (i < 0) - return posix_error(); - return PyInt_FromLong((long)i); + int i; + if (!PyArg_ParseTuple(args, "i:umask", &i)) + return NULL; + i = (int)umask(i); + if (i < 0) + return posix_error(); + return PyInt_FromLong((long)i); } @@ -2688,9 +2688,9 @@ posix_unlink(PyObject *self, PyObject *args) { #ifdef MS_WINDOWS - return win32_1str(args, "remove", "s:remove", DeleteFileA, "U:remove", DeleteFileW); + return win32_1str(args, "remove", "s:remove", DeleteFileA, "U:remove", DeleteFileW); #else - return posix_1str(args, "et:remove", unlink); + return posix_1str(args, "et:remove", unlink); #endif } @@ -2703,50 +2703,50 @@ static PyObject * posix_uname(PyObject *self, PyObject *noargs) { - struct utsname u; - int res; + struct utsname u; + int res; - Py_BEGIN_ALLOW_THREADS - res = uname(&u); - Py_END_ALLOW_THREADS - if (res < 0) - return posix_error(); - return Py_BuildValue("(sssss)", - u.sysname, - u.nodename, - u.release, - u.version, - u.machine); + Py_BEGIN_ALLOW_THREADS + res = uname(&u); + Py_END_ALLOW_THREADS + if (res < 0) + return posix_error(); + return Py_BuildValue("(sssss)", + u.sysname, + u.nodename, + u.release, + u.version, + u.machine); } #endif /* HAVE_UNAME */ static int extract_time(PyObject *t, long* sec, long* usec) { - long intval; - if (PyFloat_Check(t)) { - double tval = PyFloat_AsDouble(t); - PyObject *intobj = Py_TYPE(t)->tp_as_number->nb_int(t); - if (!intobj) - return -1; - intval = PyInt_AsLong(intobj); - Py_DECREF(intobj); - if (intval == -1 && PyErr_Occurred()) - return -1; - *sec = intval; - *usec = (long)((tval - intval) * 1e6); /* can't exceed 1000000 */ - if (*usec < 0) - /* If rounding gave us a negative number, - truncate. */ - *usec = 0; - return 0; - } - intval = PyInt_AsLong(t); - if (intval == -1 && PyErr_Occurred()) - return -1; - *sec = intval; - *usec = 0; + long intval; + if (PyFloat_Check(t)) { + double tval = PyFloat_AsDouble(t); + PyObject *intobj = Py_TYPE(t)->tp_as_number->nb_int(t); + if (!intobj) + return -1; + intval = PyInt_AsLong(intobj); + Py_DECREF(intobj); + if (intval == -1 && PyErr_Occurred()) + return -1; + *sec = intval; + *usec = (long)((tval - intval) * 1e6); /* can't exceed 1000000 */ + if (*usec < 0) + /* If rounding gave us a negative number, + truncate. */ + *usec = 0; return 0; + } + intval = PyInt_AsLong(t); + if (intval == -1 && PyErr_Occurred()) + return -1; + *sec = intval; + *usec = 0; + return 0; } PyDoc_STRVAR(posix_utime__doc__, @@ -2759,154 +2759,154 @@ posix_utime(PyObject *self, PyObject *args) { #ifdef Py_WIN_WIDE_FILENAMES - PyObject *arg; - PyUnicodeObject *obwpath; - wchar_t *wpath = NULL; - char *apath = NULL; - HANDLE hFile; - long atimesec, mtimesec, ausec, musec; - FILETIME atime, mtime; - PyObject *result = NULL; - - if (unicode_file_names()) { - if (PyArg_ParseTuple(args, "UO|:utime", &obwpath, &arg)) { - wpath = PyUnicode_AS_UNICODE(obwpath); - Py_BEGIN_ALLOW_THREADS - hFile = CreateFileW(wpath, FILE_WRITE_ATTRIBUTES, 0, - NULL, OPEN_EXISTING, - FILE_FLAG_BACKUP_SEMANTICS, NULL); - Py_END_ALLOW_THREADS - if (hFile == INVALID_HANDLE_VALUE) - return win32_error_unicode("utime", wpath); - } else - /* Drop the argument parsing error as narrow strings - are also valid. */ - PyErr_Clear(); - } - if (!wpath) { - if (!PyArg_ParseTuple(args, "etO:utime", - Py_FileSystemDefaultEncoding, &apath, &arg)) - return NULL; - Py_BEGIN_ALLOW_THREADS - hFile = CreateFileA(apath, FILE_WRITE_ATTRIBUTES, 0, - NULL, OPEN_EXISTING, - FILE_FLAG_BACKUP_SEMANTICS, NULL); - Py_END_ALLOW_THREADS - if (hFile == INVALID_HANDLE_VALUE) { - win32_error("utime", apath); - PyMem_Free(apath); - return NULL; - } - PyMem_Free(apath); - } - - if (arg == Py_None) { - SYSTEMTIME now; - GetSystemTime(&now); - if (!SystemTimeToFileTime(&now, &mtime) || - !SystemTimeToFileTime(&now, &atime)) { - win32_error("utime", NULL); - goto done; - } - } - else if (!PyTuple_Check(arg) || PyTuple_Size(arg) != 2) { - PyErr_SetString(PyExc_TypeError, - "utime() arg 2 must be a tuple (atime, mtime)"); - goto done; - } - else { - if (extract_time(PyTuple_GET_ITEM(arg, 0), - &atimesec, &ausec) == -1) - goto done; - time_t_to_FILE_TIME(atimesec, 1000*ausec, &atime); - if (extract_time(PyTuple_GET_ITEM(arg, 1), - &mtimesec, &musec) == -1) - goto done; - time_t_to_FILE_TIME(mtimesec, 1000*musec, &mtime); - } - if (!SetFileTime(hFile, NULL, &atime, &mtime)) { - /* Avoid putting the file name into the error here, - as that may confuse the user into believing that - something is wrong with the file, when it also - could be the time stamp that gives a problem. */ - win32_error("utime", NULL); - } - Py_INCREF(Py_None); - result = Py_None; + PyObject *arg; + PyUnicodeObject *obwpath; + wchar_t *wpath = NULL; + char *apath = NULL; + HANDLE hFile; + long atimesec, mtimesec, ausec, musec; + FILETIME atime, mtime; + PyObject *result = NULL; + + if (unicode_file_names()) { + if (PyArg_ParseTuple(args, "UO|:utime", &obwpath, &arg)) { + wpath = PyUnicode_AS_UNICODE(obwpath); + Py_BEGIN_ALLOW_THREADS + hFile = CreateFileW(wpath, FILE_WRITE_ATTRIBUTES, 0, + NULL, OPEN_EXISTING, + FILE_FLAG_BACKUP_SEMANTICS, NULL); + Py_END_ALLOW_THREADS + if (hFile == INVALID_HANDLE_VALUE) + return win32_error_unicode("utime", wpath); + } else + /* Drop the argument parsing error as narrow strings + are also valid. */ + PyErr_Clear(); + } + if (!wpath) { + if (!PyArg_ParseTuple(args, "etO:utime", + Py_FileSystemDefaultEncoding, &apath, &arg)) + return NULL; + Py_BEGIN_ALLOW_THREADS + hFile = CreateFileA(apath, FILE_WRITE_ATTRIBUTES, 0, + NULL, OPEN_EXISTING, + FILE_FLAG_BACKUP_SEMANTICS, NULL); + Py_END_ALLOW_THREADS + if (hFile == INVALID_HANDLE_VALUE) { + win32_error("utime", apath); + PyMem_Free(apath); + return NULL; + } + PyMem_Free(apath); + } + + if (arg == Py_None) { + SYSTEMTIME now; + GetSystemTime(&now); + if (!SystemTimeToFileTime(&now, &mtime) || + !SystemTimeToFileTime(&now, &atime)) { + win32_error("utime", NULL); + goto done; + } + } + else if (!PyTuple_Check(arg) || PyTuple_Size(arg) != 2) { + PyErr_SetString(PyExc_TypeError, + "utime() arg 2 must be a tuple (atime, mtime)"); + goto done; + } + else { + if (extract_time(PyTuple_GET_ITEM(arg, 0), + &atimesec, &ausec) == -1) + goto done; + time_t_to_FILE_TIME(atimesec, 1000*ausec, &atime); + if (extract_time(PyTuple_GET_ITEM(arg, 1), + &mtimesec, &musec) == -1) + goto done; + time_t_to_FILE_TIME(mtimesec, 1000*musec, &mtime); + } + if (!SetFileTime(hFile, NULL, &atime, &mtime)) { + /* Avoid putting the file name into the error here, + as that may confuse the user into believing that + something is wrong with the file, when it also + could be the time stamp that gives a problem. */ + win32_error("utime", NULL); + } + Py_INCREF(Py_None); + result = Py_None; done: - CloseHandle(hFile); - return result; + CloseHandle(hFile); + return result; #else /* Py_WIN_WIDE_FILENAMES */ - char *path = NULL; - long atime, mtime, ausec, musec; - int res; - PyObject* arg; + char *path = NULL; + long atime, mtime, ausec, musec; + int res; + PyObject* arg; #if defined(HAVE_UTIMES) - struct timeval buf[2]; + struct timeval buf[2]; #define ATIME buf[0].tv_sec #define MTIME buf[1].tv_sec #elif defined(HAVE_UTIME_H) /* XXX should define struct utimbuf instead, above */ - struct utimbuf buf; + struct utimbuf buf; #define ATIME buf.actime #define MTIME buf.modtime #define UTIME_ARG &buf #else /* HAVE_UTIMES */ - time_t buf[2]; + time_t buf[2]; #define ATIME buf[0] #define MTIME buf[1] #define UTIME_ARG buf #endif /* HAVE_UTIMES */ - if (!PyArg_ParseTuple(args, "etO:utime", - Py_FileSystemDefaultEncoding, &path, &arg)) - return NULL; - if (arg == Py_None) { - /* optional time values not given */ - Py_BEGIN_ALLOW_THREADS - res = utime(path, NULL); - Py_END_ALLOW_THREADS - } - else if (!PyTuple_Check(arg) || PyTuple_Size(arg) != 2) { - PyErr_SetString(PyExc_TypeError, - "utime() arg 2 must be a tuple (atime, mtime)"); - PyMem_Free(path); - return NULL; - } - else { - if (extract_time(PyTuple_GET_ITEM(arg, 0), - &atime, &ausec) == -1) { - PyMem_Free(path); - return NULL; - } - if (extract_time(PyTuple_GET_ITEM(arg, 1), - &mtime, &musec) == -1) { - PyMem_Free(path); - return NULL; - } - ATIME = atime; - MTIME = mtime; + if (!PyArg_ParseTuple(args, "etO:utime", + Py_FileSystemDefaultEncoding, &path, &arg)) + return NULL; + if (arg == Py_None) { + /* optional time values not given */ + Py_BEGIN_ALLOW_THREADS + res = utime(path, NULL); + Py_END_ALLOW_THREADS + } + else if (!PyTuple_Check(arg) || PyTuple_Size(arg) != 2) { + PyErr_SetString(PyExc_TypeError, + "utime() arg 2 must be a tuple (atime, mtime)"); + PyMem_Free(path); + return NULL; + } + else { + if (extract_time(PyTuple_GET_ITEM(arg, 0), + &atime, &ausec) == -1) { + PyMem_Free(path); + return NULL; + } + if (extract_time(PyTuple_GET_ITEM(arg, 1), + &mtime, &musec) == -1) { + PyMem_Free(path); + return NULL; + } + ATIME = atime; + MTIME = mtime; #ifdef HAVE_UTIMES - buf[0].tv_usec = ausec; - buf[1].tv_usec = musec; - Py_BEGIN_ALLOW_THREADS - res = utimes(path, buf); - Py_END_ALLOW_THREADS -#else - Py_BEGIN_ALLOW_THREADS - res = utime(path, UTIME_ARG); - Py_END_ALLOW_THREADS + buf[0].tv_usec = ausec; + buf[1].tv_usec = musec; + Py_BEGIN_ALLOW_THREADS + res = utimes(path, buf); + Py_END_ALLOW_THREADS +#else + Py_BEGIN_ALLOW_THREADS + res = utime(path, UTIME_ARG); + Py_END_ALLOW_THREADS #endif /* HAVE_UTIMES */ - } - if (res < 0) { - return posix_error_with_allocated_filename(path); - } - PyMem_Free(path); - Py_INCREF(Py_None); - return Py_None; + } + if (res < 0) { + return posix_error_with_allocated_filename(path); + } + PyMem_Free(path); + Py_INCREF(Py_None); + return Py_None; #undef UTIME_ARG #undef ATIME #undef MTIME @@ -2923,21 +2923,21 @@ static PyObject * posix__exit(PyObject *self, PyObject *args) { - int sts; - if (!PyArg_ParseTuple(args, "i:_exit", &sts)) - return NULL; - _exit(sts); - return NULL; /* Make gcc -Wall happy */ + int sts; + if (!PyArg_ParseTuple(args, "i:_exit", &sts)) + return NULL; + _exit(sts); + return NULL; /* Make gcc -Wall happy */ } #if defined(HAVE_EXECV) || defined(HAVE_SPAWNV) static void free_string_array(char **array, Py_ssize_t count) { - Py_ssize_t i; - for (i = 0; i < count; i++) - PyMem_Free(array[i]); - PyMem_DEL(array); + Py_ssize_t i; + for (i = 0; i < count; i++) + PyMem_Free(array[i]); + PyMem_DEL(array); } #endif @@ -2947,65 +2947,65 @@ "execv(path, args)\n\n\ Execute an executable path with arguments, replacing current process.\n\ \n\ - path: path of executable file\n\ - args: tuple or list of strings"); + path: path of executable file\n\ + args: tuple or list of strings"); static PyObject * posix_execv(PyObject *self, PyObject *args) { - char *path; - PyObject *argv; - char **argvlist; - Py_ssize_t i, argc; - PyObject *(*getitem)(PyObject *, Py_ssize_t); - - /* execv has two arguments: (path, argv), where - argv is a list or tuple of strings. */ - - if (!PyArg_ParseTuple(args, "etO:execv", - Py_FileSystemDefaultEncoding, - &path, &argv)) - return NULL; - if (PyList_Check(argv)) { - argc = PyList_Size(argv); - getitem = PyList_GetItem; - } - else if (PyTuple_Check(argv)) { - argc = PyTuple_Size(argv); - getitem = PyTuple_GetItem; - } - else { - PyErr_SetString(PyExc_TypeError, "execv() arg 2 must be a tuple or list"); - PyMem_Free(path); - return NULL; - } - - argvlist = PyMem_NEW(char *, argc+1); - if (argvlist == NULL) { - PyMem_Free(path); - return PyErr_NoMemory(); - } - for (i = 0; i < argc; i++) { - if (!PyArg_Parse((*getitem)(argv, i), "et", - Py_FileSystemDefaultEncoding, - &argvlist[i])) { - free_string_array(argvlist, i); - PyErr_SetString(PyExc_TypeError, - "execv() arg 2 must contain only strings"); - PyMem_Free(path); - return NULL; - - } - } - argvlist[argc] = NULL; - - execv(path, argvlist); - - /* If we get here it's definitely an error */ - - free_string_array(argvlist, argc); - PyMem_Free(path); - return posix_error(); + char *path; + PyObject *argv; + char **argvlist; + Py_ssize_t i, argc; + PyObject *(*getitem)(PyObject *, Py_ssize_t); + + /* execv has two arguments: (path, argv), where + argv is a list or tuple of strings. */ + + if (!PyArg_ParseTuple(args, "etO:execv", + Py_FileSystemDefaultEncoding, + &path, &argv)) + return NULL; + if (PyList_Check(argv)) { + argc = PyList_Size(argv); + getitem = PyList_GetItem; + } + else if (PyTuple_Check(argv)) { + argc = PyTuple_Size(argv); + getitem = PyTuple_GetItem; + } + else { + PyErr_SetString(PyExc_TypeError, "execv() arg 2 must be a tuple or list"); + PyMem_Free(path); + return NULL; + } + + argvlist = PyMem_NEW(char *, argc+1); + if (argvlist == NULL) { + PyMem_Free(path); + return PyErr_NoMemory(); + } + for (i = 0; i < argc; i++) { + if (!PyArg_Parse((*getitem)(argv, i), "et", + Py_FileSystemDefaultEncoding, + &argvlist[i])) { + free_string_array(argvlist, i); + PyErr_SetString(PyExc_TypeError, + "execv() arg 2 must contain only strings"); + PyMem_Free(path); + return NULL; + + } + } + argvlist[argc] = NULL; + + execv(path, argvlist); + + /* If we get here it's definitely an error */ + + free_string_array(argvlist, argc); + PyMem_Free(path); + return posix_error(); } @@ -3013,142 +3013,142 @@ "execve(path, args, env)\n\n\ Execute a path with arguments and environment, replacing current process.\n\ \n\ - path: path of executable file\n\ - args: tuple or list of arguments\n\ - env: dictionary of strings mapping to strings"); + path: path of executable file\n\ + args: tuple or list of arguments\n\ + env: dictionary of strings mapping to strings"); static PyObject * posix_execve(PyObject *self, PyObject *args) { - char *path; - PyObject *argv, *env; - char **argvlist; - char **envlist; - PyObject *key, *val, *keys=NULL, *vals=NULL; - Py_ssize_t i, pos, argc, envc; - PyObject *(*getitem)(PyObject *, Py_ssize_t); - Py_ssize_t lastarg = 0; - - /* execve has three arguments: (path, argv, env), where - argv is a list or tuple of strings and env is a dictionary - like posix.environ. */ - - if (!PyArg_ParseTuple(args, "etOO:execve", - Py_FileSystemDefaultEncoding, - &path, &argv, &env)) - return NULL; - if (PyList_Check(argv)) { - argc = PyList_Size(argv); - getitem = PyList_GetItem; - } - else if (PyTuple_Check(argv)) { - argc = PyTuple_Size(argv); - getitem = PyTuple_GetItem; - } - else { - PyErr_SetString(PyExc_TypeError, - "execve() arg 2 must be a tuple or list"); - goto fail_0; - } - if (!PyMapping_Check(env)) { - PyErr_SetString(PyExc_TypeError, - "execve() arg 3 must be a mapping object"); - goto fail_0; - } - - argvlist = PyMem_NEW(char *, argc+1); - if (argvlist == NULL) { - PyErr_NoMemory(); - goto fail_0; - } - for (i = 0; i < argc; i++) { - if (!PyArg_Parse((*getitem)(argv, i), - "et;execve() arg 2 must contain only strings", - Py_FileSystemDefaultEncoding, - &argvlist[i])) - { - lastarg = i; - goto fail_1; - } - } - lastarg = argc; - argvlist[argc] = NULL; - - i = PyMapping_Size(env); - if (i < 0) - goto fail_1; - envlist = PyMem_NEW(char *, i + 1); - if (envlist == NULL) { - PyErr_NoMemory(); - goto fail_1; - } - envc = 0; - keys = PyMapping_Keys(env); - vals = PyMapping_Values(env); - if (!keys || !vals) - goto fail_2; - if (!PyList_Check(keys) || !PyList_Check(vals)) { - PyErr_SetString(PyExc_TypeError, - "execve(): env.keys() or env.values() is not a list"); - goto fail_2; - } - - for (pos = 0; pos < i; pos++) { - char *p, *k, *v; - size_t len; - - key = PyList_GetItem(keys, pos); - val = PyList_GetItem(vals, pos); - if (!key || !val) - goto fail_2; - - if (!PyArg_Parse( - key, - "s;execve() arg 3 contains a non-string key", - &k) || - !PyArg_Parse( - val, - "s;execve() arg 3 contains a non-string value", - &v)) - { - goto fail_2; - } + char *path; + PyObject *argv, *env; + char **argvlist; + char **envlist; + PyObject *key, *val, *keys=NULL, *vals=NULL; + Py_ssize_t i, pos, argc, envc; + PyObject *(*getitem)(PyObject *, Py_ssize_t); + Py_ssize_t lastarg = 0; + + /* execve has three arguments: (path, argv, env), where + argv is a list or tuple of strings and env is a dictionary + like posix.environ. */ + + if (!PyArg_ParseTuple(args, "etOO:execve", + Py_FileSystemDefaultEncoding, + &path, &argv, &env)) + return NULL; + if (PyList_Check(argv)) { + argc = PyList_Size(argv); + getitem = PyList_GetItem; + } + else if (PyTuple_Check(argv)) { + argc = PyTuple_Size(argv); + getitem = PyTuple_GetItem; + } + else { + PyErr_SetString(PyExc_TypeError, + "execve() arg 2 must be a tuple or list"); + goto fail_0; + } + if (!PyMapping_Check(env)) { + PyErr_SetString(PyExc_TypeError, + "execve() arg 3 must be a mapping object"); + goto fail_0; + } + + argvlist = PyMem_NEW(char *, argc+1); + if (argvlist == NULL) { + PyErr_NoMemory(); + goto fail_0; + } + for (i = 0; i < argc; i++) { + if (!PyArg_Parse((*getitem)(argv, i), + "et;execve() arg 2 must contain only strings", + Py_FileSystemDefaultEncoding, + &argvlist[i])) + { + lastarg = i; + goto fail_1; + } + } + lastarg = argc; + argvlist[argc] = NULL; + + i = PyMapping_Size(env); + if (i < 0) + goto fail_1; + envlist = PyMem_NEW(char *, i + 1); + if (envlist == NULL) { + PyErr_NoMemory(); + goto fail_1; + } + envc = 0; + keys = PyMapping_Keys(env); + vals = PyMapping_Values(env); + if (!keys || !vals) + goto fail_2; + if (!PyList_Check(keys) || !PyList_Check(vals)) { + PyErr_SetString(PyExc_TypeError, + "execve(): env.keys() or env.values() is not a list"); + goto fail_2; + } + + for (pos = 0; pos < i; pos++) { + char *p, *k, *v; + size_t len; + + key = PyList_GetItem(keys, pos); + val = PyList_GetItem(vals, pos); + if (!key || !val) + goto fail_2; + + if (!PyArg_Parse( + key, + "s;execve() arg 3 contains a non-string key", + &k) || + !PyArg_Parse( + val, + "s;execve() arg 3 contains a non-string value", + &v)) + { + goto fail_2; + } #if defined(PYOS_OS2) /* Omit Pseudo-Env Vars that Would Confuse Programs if Passed On */ if (stricmp(k, "BEGINLIBPATH") != 0 && stricmp(k, "ENDLIBPATH") != 0) { #endif - len = PyString_Size(key) + PyString_Size(val) + 2; - p = PyMem_NEW(char, len); - if (p == NULL) { - PyErr_NoMemory(); - goto fail_2; - } - PyOS_snprintf(p, len, "%s=%s", k, v); - envlist[envc++] = p; + len = PyString_Size(key) + PyString_Size(val) + 2; + p = PyMem_NEW(char, len); + if (p == NULL) { + PyErr_NoMemory(); + goto fail_2; + } + PyOS_snprintf(p, len, "%s=%s", k, v); + envlist[envc++] = p; #if defined(PYOS_OS2) - } + } #endif - } - envlist[envc] = 0; + } + envlist[envc] = 0; - execve(path, argvlist, envlist); + execve(path, argvlist, envlist); - /* If we get here it's definitely an error */ + /* If we get here it's definitely an error */ - (void) posix_error(); + (void) posix_error(); fail_2: - while (--envc >= 0) - PyMem_DEL(envlist[envc]); - PyMem_DEL(envlist); + while (--envc >= 0) + PyMem_DEL(envlist[envc]); + PyMem_DEL(envlist); fail_1: - free_string_array(argvlist, lastarg); - Py_XDECREF(vals); - Py_XDECREF(keys); + free_string_array(argvlist, lastarg); + Py_XDECREF(vals); + Py_XDECREF(keys); fail_0: - PyMem_Free(path); - return NULL; + PyMem_Free(path); + return NULL; } #endif /* HAVE_EXECV */ @@ -3158,85 +3158,85 @@ "spawnv(mode, path, args)\n\n\ Execute the program 'path' in a new process.\n\ \n\ - mode: mode of process creation\n\ - path: path of executable file\n\ - args: tuple or list of strings"); + mode: mode of process creation\n\ + path: path of executable file\n\ + args: tuple or list of strings"); static PyObject * posix_spawnv(PyObject *self, PyObject *args) { - char *path; - PyObject *argv; - char **argvlist; - int mode, i; - Py_ssize_t argc; - Py_intptr_t spawnval; - PyObject *(*getitem)(PyObject *, Py_ssize_t); - - /* spawnv has three arguments: (mode, path, argv), where - argv is a list or tuple of strings. */ - - if (!PyArg_ParseTuple(args, "ietO:spawnv", &mode, - Py_FileSystemDefaultEncoding, - &path, &argv)) - return NULL; - if (PyList_Check(argv)) { - argc = PyList_Size(argv); - getitem = PyList_GetItem; - } - else if (PyTuple_Check(argv)) { - argc = PyTuple_Size(argv); - getitem = PyTuple_GetItem; - } - else { - PyErr_SetString(PyExc_TypeError, - "spawnv() arg 2 must be a tuple or list"); - PyMem_Free(path); - return NULL; - } - - argvlist = PyMem_NEW(char *, argc+1); - if (argvlist == NULL) { - PyMem_Free(path); - return PyErr_NoMemory(); - } - for (i = 0; i < argc; i++) { - if (!PyArg_Parse((*getitem)(argv, i), "et", - Py_FileSystemDefaultEncoding, - &argvlist[i])) { - free_string_array(argvlist, i); - PyErr_SetString( - PyExc_TypeError, - "spawnv() arg 2 must contain only strings"); - PyMem_Free(path); - return NULL; - } - } - argvlist[argc] = NULL; + char *path; + PyObject *argv; + char **argvlist; + int mode, i; + Py_ssize_t argc; + Py_intptr_t spawnval; + PyObject *(*getitem)(PyObject *, Py_ssize_t); + + /* spawnv has three arguments: (mode, path, argv), where + argv is a list or tuple of strings. */ + + if (!PyArg_ParseTuple(args, "ietO:spawnv", &mode, + Py_FileSystemDefaultEncoding, + &path, &argv)) + return NULL; + if (PyList_Check(argv)) { + argc = PyList_Size(argv); + getitem = PyList_GetItem; + } + else if (PyTuple_Check(argv)) { + argc = PyTuple_Size(argv); + getitem = PyTuple_GetItem; + } + else { + PyErr_SetString(PyExc_TypeError, + "spawnv() arg 2 must be a tuple or list"); + PyMem_Free(path); + return NULL; + } + + argvlist = PyMem_NEW(char *, argc+1); + if (argvlist == NULL) { + PyMem_Free(path); + return PyErr_NoMemory(); + } + for (i = 0; i < argc; i++) { + if (!PyArg_Parse((*getitem)(argv, i), "et", + Py_FileSystemDefaultEncoding, + &argvlist[i])) { + free_string_array(argvlist, i); + PyErr_SetString( + PyExc_TypeError, + "spawnv() arg 2 must contain only strings"); + PyMem_Free(path); + return NULL; + } + } + argvlist[argc] = NULL; #if defined(PYOS_OS2) && defined(PYCC_GCC) - Py_BEGIN_ALLOW_THREADS - spawnval = spawnv(mode, path, argvlist); - Py_END_ALLOW_THREADS + Py_BEGIN_ALLOW_THREADS + spawnval = spawnv(mode, path, argvlist); + Py_END_ALLOW_THREADS #else - if (mode == _OLD_P_OVERLAY) - mode = _P_OVERLAY; + if (mode == _OLD_P_OVERLAY) + mode = _P_OVERLAY; - Py_BEGIN_ALLOW_THREADS - spawnval = _spawnv(mode, path, argvlist); - Py_END_ALLOW_THREADS + Py_BEGIN_ALLOW_THREADS + spawnval = _spawnv(mode, path, argvlist); + Py_END_ALLOW_THREADS #endif - free_string_array(argvlist, argc); - PyMem_Free(path); + free_string_array(argvlist, argc); + PyMem_Free(path); - if (spawnval == -1) - return posix_error(); - else + if (spawnval == -1) + return posix_error(); + else #if SIZEOF_LONG == SIZEOF_VOID_P - return Py_BuildValue("l", (long) spawnval); + return Py_BuildValue("l", (long) spawnval); #else - return Py_BuildValue("L", (PY_LONG_LONG) spawnval); + return Py_BuildValue("L", (PY_LONG_LONG) spawnval); #endif } @@ -3245,153 +3245,153 @@ "spawnve(mode, path, args, env)\n\n\ Execute the program 'path' in a new process.\n\ \n\ - mode: mode of process creation\n\ - path: path of executable file\n\ - args: tuple or list of arguments\n\ - env: dictionary of strings mapping to strings"); + mode: mode of process creation\n\ + path: path of executable file\n\ + args: tuple or list of arguments\n\ + env: dictionary of strings mapping to strings"); static PyObject * posix_spawnve(PyObject *self, PyObject *args) { - char *path; - PyObject *argv, *env; - char **argvlist; - char **envlist; - PyObject *key, *val, *keys=NULL, *vals=NULL, *res=NULL; - int mode, pos, envc; - Py_ssize_t argc, i; - Py_intptr_t spawnval; - PyObject *(*getitem)(PyObject *, Py_ssize_t); - Py_ssize_t lastarg = 0; - - /* spawnve has four arguments: (mode, path, argv, env), where - argv is a list or tuple of strings and env is a dictionary - like posix.environ. */ - - if (!PyArg_ParseTuple(args, "ietOO:spawnve", &mode, - Py_FileSystemDefaultEncoding, - &path, &argv, &env)) - return NULL; - if (PyList_Check(argv)) { - argc = PyList_Size(argv); - getitem = PyList_GetItem; - } - else if (PyTuple_Check(argv)) { - argc = PyTuple_Size(argv); - getitem = PyTuple_GetItem; - } - else { - PyErr_SetString(PyExc_TypeError, - "spawnve() arg 2 must be a tuple or list"); - goto fail_0; - } - if (!PyMapping_Check(env)) { - PyErr_SetString(PyExc_TypeError, - "spawnve() arg 3 must be a mapping object"); - goto fail_0; - } - - argvlist = PyMem_NEW(char *, argc+1); - if (argvlist == NULL) { - PyErr_NoMemory(); - goto fail_0; - } - for (i = 0; i < argc; i++) { - if (!PyArg_Parse((*getitem)(argv, i), - "et;spawnve() arg 2 must contain only strings", - Py_FileSystemDefaultEncoding, - &argvlist[i])) - { - lastarg = i; - goto fail_1; - } - } - lastarg = argc; - argvlist[argc] = NULL; - - i = PyMapping_Size(env); - if (i < 0) - goto fail_1; - envlist = PyMem_NEW(char *, i + 1); - if (envlist == NULL) { - PyErr_NoMemory(); - goto fail_1; - } - envc = 0; - keys = PyMapping_Keys(env); - vals = PyMapping_Values(env); - if (!keys || !vals) - goto fail_2; - if (!PyList_Check(keys) || !PyList_Check(vals)) { - PyErr_SetString(PyExc_TypeError, - "spawnve(): env.keys() or env.values() is not a list"); - goto fail_2; - } - - for (pos = 0; pos < i; pos++) { - char *p, *k, *v; - size_t len; - - key = PyList_GetItem(keys, pos); - val = PyList_GetItem(vals, pos); - if (!key || !val) - goto fail_2; - - if (!PyArg_Parse( - key, - "s;spawnve() arg 3 contains a non-string key", - &k) || - !PyArg_Parse( - val, - "s;spawnve() arg 3 contains a non-string value", - &v)) - { - goto fail_2; - } - len = PyString_Size(key) + PyString_Size(val) + 2; - p = PyMem_NEW(char, len); - if (p == NULL) { - PyErr_NoMemory(); - goto fail_2; - } - PyOS_snprintf(p, len, "%s=%s", k, v); - envlist[envc++] = p; - } - envlist[envc] = 0; + char *path; + PyObject *argv, *env; + char **argvlist; + char **envlist; + PyObject *key, *val, *keys=NULL, *vals=NULL, *res=NULL; + int mode, pos, envc; + Py_ssize_t argc, i; + Py_intptr_t spawnval; + PyObject *(*getitem)(PyObject *, Py_ssize_t); + Py_ssize_t lastarg = 0; + + /* spawnve has four arguments: (mode, path, argv, env), where + argv is a list or tuple of strings and env is a dictionary + like posix.environ. */ + + if (!PyArg_ParseTuple(args, "ietOO:spawnve", &mode, + Py_FileSystemDefaultEncoding, + &path, &argv, &env)) + return NULL; + if (PyList_Check(argv)) { + argc = PyList_Size(argv); + getitem = PyList_GetItem; + } + else if (PyTuple_Check(argv)) { + argc = PyTuple_Size(argv); + getitem = PyTuple_GetItem; + } + else { + PyErr_SetString(PyExc_TypeError, + "spawnve() arg 2 must be a tuple or list"); + goto fail_0; + } + if (!PyMapping_Check(env)) { + PyErr_SetString(PyExc_TypeError, + "spawnve() arg 3 must be a mapping object"); + goto fail_0; + } + + argvlist = PyMem_NEW(char *, argc+1); + if (argvlist == NULL) { + PyErr_NoMemory(); + goto fail_0; + } + for (i = 0; i < argc; i++) { + if (!PyArg_Parse((*getitem)(argv, i), + "et;spawnve() arg 2 must contain only strings", + Py_FileSystemDefaultEncoding, + &argvlist[i])) + { + lastarg = i; + goto fail_1; + } + } + lastarg = argc; + argvlist[argc] = NULL; + + i = PyMapping_Size(env); + if (i < 0) + goto fail_1; + envlist = PyMem_NEW(char *, i + 1); + if (envlist == NULL) { + PyErr_NoMemory(); + goto fail_1; + } + envc = 0; + keys = PyMapping_Keys(env); + vals = PyMapping_Values(env); + if (!keys || !vals) + goto fail_2; + if (!PyList_Check(keys) || !PyList_Check(vals)) { + PyErr_SetString(PyExc_TypeError, + "spawnve(): env.keys() or env.values() is not a list"); + goto fail_2; + } + + for (pos = 0; pos < i; pos++) { + char *p, *k, *v; + size_t len; + + key = PyList_GetItem(keys, pos); + val = PyList_GetItem(vals, pos); + if (!key || !val) + goto fail_2; + + if (!PyArg_Parse( + key, + "s;spawnve() arg 3 contains a non-string key", + &k) || + !PyArg_Parse( + val, + "s;spawnve() arg 3 contains a non-string value", + &v)) + { + goto fail_2; + } + len = PyString_Size(key) + PyString_Size(val) + 2; + p = PyMem_NEW(char, len); + if (p == NULL) { + PyErr_NoMemory(); + goto fail_2; + } + PyOS_snprintf(p, len, "%s=%s", k, v); + envlist[envc++] = p; + } + envlist[envc] = 0; #if defined(PYOS_OS2) && defined(PYCC_GCC) - Py_BEGIN_ALLOW_THREADS - spawnval = spawnve(mode, path, argvlist, envlist); - Py_END_ALLOW_THREADS + Py_BEGIN_ALLOW_THREADS + spawnval = spawnve(mode, path, argvlist, envlist); + Py_END_ALLOW_THREADS #else - if (mode == _OLD_P_OVERLAY) - mode = _P_OVERLAY; + if (mode == _OLD_P_OVERLAY) + mode = _P_OVERLAY; - Py_BEGIN_ALLOW_THREADS - spawnval = _spawnve(mode, path, argvlist, envlist); - Py_END_ALLOW_THREADS + Py_BEGIN_ALLOW_THREADS + spawnval = _spawnve(mode, path, argvlist, envlist); + Py_END_ALLOW_THREADS #endif - if (spawnval == -1) - (void) posix_error(); - else + if (spawnval == -1) + (void) posix_error(); + else #if SIZEOF_LONG == SIZEOF_VOID_P - res = Py_BuildValue("l", (long) spawnval); + res = Py_BuildValue("l", (long) spawnval); #else - res = Py_BuildValue("L", (PY_LONG_LONG) spawnval); + res = Py_BuildValue("L", (PY_LONG_LONG) spawnval); #endif fail_2: - while (--envc >= 0) - PyMem_DEL(envlist[envc]); - PyMem_DEL(envlist); + while (--envc >= 0) + PyMem_DEL(envlist[envc]); + PyMem_DEL(envlist); fail_1: - free_string_array(argvlist, lastarg); - Py_XDECREF(vals); - Py_XDECREF(keys); + free_string_array(argvlist, lastarg); + Py_XDECREF(vals); + Py_XDECREF(keys); fail_0: - PyMem_Free(path); - return res; + PyMem_Free(path); + return res; } /* OS/2 supports spawnvp & spawnvpe natively */ @@ -3401,76 +3401,76 @@ Execute the program 'file' in a new process, using the environment\n\ search path to find the file.\n\ \n\ - mode: mode of process creation\n\ - file: executable file name\n\ - args: tuple or list of strings"); + mode: mode of process creation\n\ + file: executable file name\n\ + args: tuple or list of strings"); static PyObject * posix_spawnvp(PyObject *self, PyObject *args) { - char *path; - PyObject *argv; - char **argvlist; - int mode, i, argc; - Py_intptr_t spawnval; - PyObject *(*getitem)(PyObject *, Py_ssize_t); - - /* spawnvp has three arguments: (mode, path, argv), where - argv is a list or tuple of strings. */ - - if (!PyArg_ParseTuple(args, "ietO:spawnvp", &mode, - Py_FileSystemDefaultEncoding, - &path, &argv)) - return NULL; - if (PyList_Check(argv)) { - argc = PyList_Size(argv); - getitem = PyList_GetItem; - } - else if (PyTuple_Check(argv)) { - argc = PyTuple_Size(argv); - getitem = PyTuple_GetItem; - } - else { - PyErr_SetString(PyExc_TypeError, - "spawnvp() arg 2 must be a tuple or list"); - PyMem_Free(path); - return NULL; - } - - argvlist = PyMem_NEW(char *, argc+1); - if (argvlist == NULL) { - PyMem_Free(path); - return PyErr_NoMemory(); - } - for (i = 0; i < argc; i++) { - if (!PyArg_Parse((*getitem)(argv, i), "et", - Py_FileSystemDefaultEncoding, - &argvlist[i])) { - free_string_array(argvlist, i); - PyErr_SetString( - PyExc_TypeError, - "spawnvp() arg 2 must contain only strings"); - PyMem_Free(path); - return NULL; - } - } - argvlist[argc] = NULL; + char *path; + PyObject *argv; + char **argvlist; + int mode, i, argc; + Py_intptr_t spawnval; + PyObject *(*getitem)(PyObject *, Py_ssize_t); + + /* spawnvp has three arguments: (mode, path, argv), where + argv is a list or tuple of strings. */ + + if (!PyArg_ParseTuple(args, "ietO:spawnvp", &mode, + Py_FileSystemDefaultEncoding, + &path, &argv)) + return NULL; + if (PyList_Check(argv)) { + argc = PyList_Size(argv); + getitem = PyList_GetItem; + } + else if (PyTuple_Check(argv)) { + argc = PyTuple_Size(argv); + getitem = PyTuple_GetItem; + } + else { + PyErr_SetString(PyExc_TypeError, + "spawnvp() arg 2 must be a tuple or list"); + PyMem_Free(path); + return NULL; + } + + argvlist = PyMem_NEW(char *, argc+1); + if (argvlist == NULL) { + PyMem_Free(path); + return PyErr_NoMemory(); + } + for (i = 0; i < argc; i++) { + if (!PyArg_Parse((*getitem)(argv, i), "et", + Py_FileSystemDefaultEncoding, + &argvlist[i])) { + free_string_array(argvlist, i); + PyErr_SetString( + PyExc_TypeError, + "spawnvp() arg 2 must contain only strings"); + PyMem_Free(path); + return NULL; + } + } + argvlist[argc] = NULL; - Py_BEGIN_ALLOW_THREADS + Py_BEGIN_ALLOW_THREADS #if defined(PYCC_GCC) - spawnval = spawnvp(mode, path, argvlist); + spawnval = spawnvp(mode, path, argvlist); #else - spawnval = _spawnvp(mode, path, argvlist); + spawnval = _spawnvp(mode, path, argvlist); #endif - Py_END_ALLOW_THREADS + Py_END_ALLOW_THREADS - free_string_array(argvlist, argc); - PyMem_Free(path); + free_string_array(argvlist, argc); + PyMem_Free(path); - if (spawnval == -1) - return posix_error(); - else - return Py_BuildValue("l", (long) spawnval); + if (spawnval == -1) + return posix_error(); + else + return Py_BuildValue("l", (long) spawnval); } @@ -3479,143 +3479,143 @@ Execute the program 'file' in a new process, using the environment\n\ search path to find the file.\n\ \n\ - mode: mode of process creation\n\ - file: executable file name\n\ - args: tuple or list of arguments\n\ - env: dictionary of strings mapping to strings"); + mode: mode of process creation\n\ + file: executable file name\n\ + args: tuple or list of arguments\n\ + env: dictionary of strings mapping to strings"); static PyObject * posix_spawnvpe(PyObject *self, PyObject *args) { - char *path; - PyObject *argv, *env; - char **argvlist; - char **envlist; - PyObject *key, *val, *keys=NULL, *vals=NULL, *res=NULL; - int mode, i, pos, argc, envc; - Py_intptr_t spawnval; - PyObject *(*getitem)(PyObject *, Py_ssize_t); - int lastarg = 0; - - /* spawnvpe has four arguments: (mode, path, argv, env), where - argv is a list or tuple of strings and env is a dictionary - like posix.environ. */ - - if (!PyArg_ParseTuple(args, "ietOO:spawnvpe", &mode, - Py_FileSystemDefaultEncoding, - &path, &argv, &env)) - return NULL; - if (PyList_Check(argv)) { - argc = PyList_Size(argv); - getitem = PyList_GetItem; - } - else if (PyTuple_Check(argv)) { - argc = PyTuple_Size(argv); - getitem = PyTuple_GetItem; - } - else { - PyErr_SetString(PyExc_TypeError, - "spawnvpe() arg 2 must be a tuple or list"); - goto fail_0; - } - if (!PyMapping_Check(env)) { - PyErr_SetString(PyExc_TypeError, - "spawnvpe() arg 3 must be a mapping object"); - goto fail_0; - } - - argvlist = PyMem_NEW(char *, argc+1); - if (argvlist == NULL) { - PyErr_NoMemory(); - goto fail_0; - } - for (i = 0; i < argc; i++) { - if (!PyArg_Parse((*getitem)(argv, i), - "et;spawnvpe() arg 2 must contain only strings", - Py_FileSystemDefaultEncoding, - &argvlist[i])) - { - lastarg = i; - goto fail_1; - } - } - lastarg = argc; - argvlist[argc] = NULL; - - i = PyMapping_Size(env); - if (i < 0) - goto fail_1; - envlist = PyMem_NEW(char *, i + 1); - if (envlist == NULL) { - PyErr_NoMemory(); - goto fail_1; - } - envc = 0; - keys = PyMapping_Keys(env); - vals = PyMapping_Values(env); - if (!keys || !vals) - goto fail_2; - if (!PyList_Check(keys) || !PyList_Check(vals)) { - PyErr_SetString(PyExc_TypeError, - "spawnvpe(): env.keys() or env.values() is not a list"); - goto fail_2; - } - - for (pos = 0; pos < i; pos++) { - char *p, *k, *v; - size_t len; - - key = PyList_GetItem(keys, pos); - val = PyList_GetItem(vals, pos); - if (!key || !val) - goto fail_2; - - if (!PyArg_Parse( - key, - "s;spawnvpe() arg 3 contains a non-string key", - &k) || - !PyArg_Parse( - val, - "s;spawnvpe() arg 3 contains a non-string value", - &v)) - { - goto fail_2; - } - len = PyString_Size(key) + PyString_Size(val) + 2; - p = PyMem_NEW(char, len); - if (p == NULL) { - PyErr_NoMemory(); - goto fail_2; - } - PyOS_snprintf(p, len, "%s=%s", k, v); - envlist[envc++] = p; - } - envlist[envc] = 0; + char *path; + PyObject *argv, *env; + char **argvlist; + char **envlist; + PyObject *key, *val, *keys=NULL, *vals=NULL, *res=NULL; + int mode, i, pos, argc, envc; + Py_intptr_t spawnval; + PyObject *(*getitem)(PyObject *, Py_ssize_t); + int lastarg = 0; + + /* spawnvpe has four arguments: (mode, path, argv, env), where + argv is a list or tuple of strings and env is a dictionary + like posix.environ. */ + + if (!PyArg_ParseTuple(args, "ietOO:spawnvpe", &mode, + Py_FileSystemDefaultEncoding, + &path, &argv, &env)) + return NULL; + if (PyList_Check(argv)) { + argc = PyList_Size(argv); + getitem = PyList_GetItem; + } + else if (PyTuple_Check(argv)) { + argc = PyTuple_Size(argv); + getitem = PyTuple_GetItem; + } + else { + PyErr_SetString(PyExc_TypeError, + "spawnvpe() arg 2 must be a tuple or list"); + goto fail_0; + } + if (!PyMapping_Check(env)) { + PyErr_SetString(PyExc_TypeError, + "spawnvpe() arg 3 must be a mapping object"); + goto fail_0; + } + + argvlist = PyMem_NEW(char *, argc+1); + if (argvlist == NULL) { + PyErr_NoMemory(); + goto fail_0; + } + for (i = 0; i < argc; i++) { + if (!PyArg_Parse((*getitem)(argv, i), + "et;spawnvpe() arg 2 must contain only strings", + Py_FileSystemDefaultEncoding, + &argvlist[i])) + { + lastarg = i; + goto fail_1; + } + } + lastarg = argc; + argvlist[argc] = NULL; - Py_BEGIN_ALLOW_THREADS + i = PyMapping_Size(env); + if (i < 0) + goto fail_1; + envlist = PyMem_NEW(char *, i + 1); + if (envlist == NULL) { + PyErr_NoMemory(); + goto fail_1; + } + envc = 0; + keys = PyMapping_Keys(env); + vals = PyMapping_Values(env); + if (!keys || !vals) + goto fail_2; + if (!PyList_Check(keys) || !PyList_Check(vals)) { + PyErr_SetString(PyExc_TypeError, + "spawnvpe(): env.keys() or env.values() is not a list"); + goto fail_2; + } + + for (pos = 0; pos < i; pos++) { + char *p, *k, *v; + size_t len; + + key = PyList_GetItem(keys, pos); + val = PyList_GetItem(vals, pos); + if (!key || !val) + goto fail_2; + + if (!PyArg_Parse( + key, + "s;spawnvpe() arg 3 contains a non-string key", + &k) || + !PyArg_Parse( + val, + "s;spawnvpe() arg 3 contains a non-string value", + &v)) + { + goto fail_2; + } + len = PyString_Size(key) + PyString_Size(val) + 2; + p = PyMem_NEW(char, len); + if (p == NULL) { + PyErr_NoMemory(); + goto fail_2; + } + PyOS_snprintf(p, len, "%s=%s", k, v); + envlist[envc++] = p; + } + envlist[envc] = 0; + + Py_BEGIN_ALLOW_THREADS #if defined(PYCC_GCC) - spawnval = spawnvpe(mode, path, argvlist, envlist); + spawnval = spawnvpe(mode, path, argvlist, envlist); #else - spawnval = _spawnvpe(mode, path, argvlist, envlist); + spawnval = _spawnvpe(mode, path, argvlist, envlist); #endif - Py_END_ALLOW_THREADS + Py_END_ALLOW_THREADS - if (spawnval == -1) - (void) posix_error(); - else - res = Py_BuildValue("l", (long) spawnval); + if (spawnval == -1) + (void) posix_error(); + else + res = Py_BuildValue("l", (long) spawnval); fail_2: - while (--envc >= 0) - PyMem_DEL(envlist[envc]); - PyMem_DEL(envlist); + while (--envc >= 0) + PyMem_DEL(envlist[envc]); + PyMem_DEL(envlist); fail_1: - free_string_array(argvlist, lastarg); - Py_XDECREF(vals); - Py_XDECREF(keys); + free_string_array(argvlist, lastarg); + Py_XDECREF(vals); + Py_XDECREF(keys); fail_0: - PyMem_Free(path); - return res; + PyMem_Free(path); + return res; } #endif /* PYOS_OS2 */ #endif /* HAVE_SPAWNV */ @@ -3631,26 +3631,26 @@ static PyObject * posix_fork1(PyObject *self, PyObject *noargs) { - pid_t pid; - int result = 0; - _PyImport_AcquireLock(); - pid = fork1(); - if (pid == 0) { - /* child: this clobbers and resets the import lock. */ - PyOS_AfterFork(); - } else { - /* parent: release the import lock. */ - result = _PyImport_ReleaseLock(); - } - if (pid == -1) - return posix_error(); - if (result < 0) { - /* Don't clobber the OSError if the fork failed. */ - PyErr_SetString(PyExc_RuntimeError, - "not holding the import lock"); - return NULL; - } - return PyLong_FromPid(pid); + pid_t pid; + int result = 0; + _PyImport_AcquireLock(); + pid = fork1(); + if (pid == 0) { + /* child: this clobbers and resets the import lock. */ + PyOS_AfterFork(); + } else { + /* parent: release the import lock. */ + result = _PyImport_ReleaseLock(); + } + if (pid == -1) + return posix_error(); + if (result < 0) { + /* Don't clobber the OSError if the fork failed. */ + PyErr_SetString(PyExc_RuntimeError, + "not holding the import lock"); + return NULL; + } + return PyLong_FromPid(pid); } #endif @@ -3664,26 +3664,26 @@ static PyObject * posix_fork(PyObject *self, PyObject *noargs) { - pid_t pid; - int result = 0; - _PyImport_AcquireLock(); - pid = fork(); - if (pid == 0) { - /* child: this clobbers and resets the import lock. */ - PyOS_AfterFork(); - } else { - /* parent: release the import lock. */ - result = _PyImport_ReleaseLock(); - } - if (pid == -1) - return posix_error(); - if (result < 0) { - /* Don't clobber the OSError if the fork failed. */ - PyErr_SetString(PyExc_RuntimeError, - "not holding the import lock"); - return NULL; - } - return PyLong_FromPid(pid); + pid_t pid; + int result = 0; + _PyImport_AcquireLock(); + pid = fork(); + if (pid == 0) { + /* child: this clobbers and resets the import lock. */ + PyOS_AfterFork(); + } else { + /* parent: release the import lock. */ + result = _PyImport_ReleaseLock(); + } + if (pid == -1) + return posix_error(); + if (result < 0) { + /* Don't clobber the OSError if the fork failed. */ + PyErr_SetString(PyExc_RuntimeError, + "not holding the import lock"); + return NULL; + } + return PyLong_FromPid(pid); } #endif @@ -3717,60 +3717,60 @@ static PyObject * posix_openpty(PyObject *self, PyObject *noargs) { - int master_fd, slave_fd; + int master_fd, slave_fd; #ifndef HAVE_OPENPTY - char * slave_name; + char * slave_name; #endif #if defined(HAVE_DEV_PTMX) && !defined(HAVE_OPENPTY) && !defined(HAVE__GETPTY) - PyOS_sighandler_t sig_saved; + PyOS_sighandler_t sig_saved; #ifdef sun - extern char *ptsname(int fildes); + extern char *ptsname(int fildes); #endif #endif #ifdef HAVE_OPENPTY - if (openpty(&master_fd, &slave_fd, NULL, NULL, NULL) != 0) - return posix_error(); + if (openpty(&master_fd, &slave_fd, NULL, NULL, NULL) != 0) + return posix_error(); #elif defined(HAVE__GETPTY) - slave_name = _getpty(&master_fd, O_RDWR, 0666, 0); - if (slave_name == NULL) - return posix_error(); - - slave_fd = open(slave_name, O_RDWR); - if (slave_fd < 0) - return posix_error(); -#else - master_fd = open(DEV_PTY_FILE, O_RDWR | O_NOCTTY); /* open master */ - if (master_fd < 0) - return posix_error(); - sig_saved = PyOS_setsig(SIGCHLD, SIG_DFL); - /* change permission of slave */ - if (grantpt(master_fd) < 0) { - PyOS_setsig(SIGCHLD, sig_saved); - return posix_error(); - } - /* unlock slave */ - if (unlockpt(master_fd) < 0) { - PyOS_setsig(SIGCHLD, sig_saved); - return posix_error(); - } - PyOS_setsig(SIGCHLD, sig_saved); - slave_name = ptsname(master_fd); /* get name of slave */ - if (slave_name == NULL) - return posix_error(); - slave_fd = open(slave_name, O_RDWR | O_NOCTTY); /* open slave */ - if (slave_fd < 0) - return posix_error(); + slave_name = _getpty(&master_fd, O_RDWR, 0666, 0); + if (slave_name == NULL) + return posix_error(); + + slave_fd = open(slave_name, O_RDWR); + if (slave_fd < 0) + return posix_error(); +#else + master_fd = open(DEV_PTY_FILE, O_RDWR | O_NOCTTY); /* open master */ + if (master_fd < 0) + return posix_error(); + sig_saved = PyOS_setsig(SIGCHLD, SIG_DFL); + /* change permission of slave */ + if (grantpt(master_fd) < 0) { + PyOS_setsig(SIGCHLD, sig_saved); + return posix_error(); + } + /* unlock slave */ + if (unlockpt(master_fd) < 0) { + PyOS_setsig(SIGCHLD, sig_saved); + return posix_error(); + } + PyOS_setsig(SIGCHLD, sig_saved); + slave_name = ptsname(master_fd); /* get name of slave */ + if (slave_name == NULL) + return posix_error(); + slave_fd = open(slave_name, O_RDWR | O_NOCTTY); /* open slave */ + if (slave_fd < 0) + return posix_error(); #if !defined(__CYGWIN__) && !defined(HAVE_DEV_PTC) - ioctl(slave_fd, I_PUSH, "ptem"); /* push ptem */ - ioctl(slave_fd, I_PUSH, "ldterm"); /* push ldterm */ + ioctl(slave_fd, I_PUSH, "ptem"); /* push ptem */ + ioctl(slave_fd, I_PUSH, "ldterm"); /* push ldterm */ #ifndef __hpux - ioctl(slave_fd, I_PUSH, "ttcompat"); /* push ttcompat */ + ioctl(slave_fd, I_PUSH, "ttcompat"); /* push ttcompat */ #endif /* __hpux */ #endif /* HAVE_CYGWIN */ #endif /* HAVE_OPENPTY */ - return Py_BuildValue("(ii)", master_fd, slave_fd); + return Py_BuildValue("(ii)", master_fd, slave_fd); } #endif /* defined(HAVE_OPENPTY) || defined(HAVE__GETPTY) || defined(HAVE_DEV_PTMX) */ @@ -3785,27 +3785,27 @@ static PyObject * posix_forkpty(PyObject *self, PyObject *noargs) { - int master_fd = -1, result = 0; - pid_t pid; + int master_fd = -1, result = 0; + pid_t pid; - _PyImport_AcquireLock(); - pid = forkpty(&master_fd, NULL, NULL, NULL); - if (pid == 0) { - /* child: this clobbers and resets the import lock. */ - PyOS_AfterFork(); - } else { - /* parent: release the import lock. */ - result = _PyImport_ReleaseLock(); - } - if (pid == -1) - return posix_error(); - if (result < 0) { - /* Don't clobber the OSError if the fork failed. */ - PyErr_SetString(PyExc_RuntimeError, - "not holding the import lock"); - return NULL; - } - return Py_BuildValue("(Ni)", PyLong_FromPid(pid), master_fd); + _PyImport_AcquireLock(); + pid = forkpty(&master_fd, NULL, NULL, NULL); + if (pid == 0) { + /* child: this clobbers and resets the import lock. */ + PyOS_AfterFork(); + } else { + /* parent: release the import lock. */ + result = _PyImport_ReleaseLock(); + } + if (pid == -1) + return posix_error(); + if (result < 0) { + /* Don't clobber the OSError if the fork failed. */ + PyErr_SetString(PyExc_RuntimeError, + "not holding the import lock"); + return NULL; + } + return Py_BuildValue("(Ni)", PyLong_FromPid(pid), master_fd); } #endif @@ -3817,7 +3817,7 @@ static PyObject * posix_getegid(PyObject *self, PyObject *noargs) { - return PyInt_FromLong((long)getegid()); + return PyInt_FromLong((long)getegid()); } #endif @@ -3830,7 +3830,7 @@ static PyObject * posix_geteuid(PyObject *self, PyObject *noargs) { - return PyInt_FromLong((long)geteuid()); + return PyInt_FromLong((long)geteuid()); } #endif @@ -3843,7 +3843,7 @@ static PyObject * posix_getgid(PyObject *self, PyObject *noargs) { - return PyInt_FromLong((long)getgid()); + return PyInt_FromLong((long)getgid()); } #endif @@ -3855,7 +3855,7 @@ static PyObject * posix_getpid(PyObject *self, PyObject *noargs) { - return PyLong_FromPid(getpid()); + return PyLong_FromPid(getpid()); } @@ -3872,30 +3872,30 @@ #ifdef NGROUPS_MAX #define MAX_GROUPS NGROUPS_MAX #else - /* defined to be 16 on Solaris7, so this should be a small number */ + /* defined to be 16 on Solaris7, so this should be a small number */ #define MAX_GROUPS 64 #endif - gid_t grouplist[MAX_GROUPS]; - int n; + gid_t grouplist[MAX_GROUPS]; + int n; - n = getgroups(MAX_GROUPS, grouplist); - if (n < 0) - posix_error(); - else { - result = PyList_New(n); - if (result != NULL) { - int i; - for (i = 0; i < n; ++i) { - PyObject *o = PyInt_FromLong((long)grouplist[i]); - if (o == NULL) { - Py_DECREF(result); - result = NULL; - break; - } - PyList_SET_ITEM(result, i, o); - } + n = getgroups(MAX_GROUPS, grouplist); + if (n < 0) + posix_error(); + else { + result = PyList_New(n); + if (result != NULL) { + int i; + for (i = 0; i < n; ++i) { + PyObject *o = PyInt_FromLong((long)grouplist[i]); + if (o == NULL) { + Py_DECREF(result); + result = NULL; + break; } + PyList_SET_ITEM(result, i, o); + } } + } return result; } @@ -3909,13 +3909,13 @@ static PyObject * posix_getpgid(PyObject *self, PyObject *args) { - pid_t pid, pgid; - if (!PyArg_ParseTuple(args, PARSE_PID ":getpgid", &pid)) - return NULL; - pgid = getpgid(pid); - if (pgid < 0) - return posix_error(); - return PyLong_FromPid(pgid); + pid_t pid, pgid; + if (!PyArg_ParseTuple(args, PARSE_PID ":getpgid", &pid)) + return NULL; + pgid = getpgid(pid); + if (pgid < 0) + return posix_error(); + return PyLong_FromPid(pgid); } #endif /* HAVE_GETPGID */ @@ -3929,9 +3929,9 @@ posix_getpgrp(PyObject *self, PyObject *noargs) { #ifdef GETPGRP_HAVE_ARG - return PyLong_FromPid(getpgrp(0)); + return PyLong_FromPid(getpgrp(0)); #else /* GETPGRP_HAVE_ARG */ - return PyLong_FromPid(getpgrp()); + return PyLong_FromPid(getpgrp()); #endif /* GETPGRP_HAVE_ARG */ } #endif /* HAVE_GETPGRP */ @@ -3946,13 +3946,13 @@ posix_setpgrp(PyObject *self, PyObject *noargs) { #ifdef SETPGRP_HAVE_ARG - if (setpgrp(0, 0) < 0) + if (setpgrp(0, 0) < 0) #else /* SETPGRP_HAVE_ARG */ - if (setpgrp() < 0) + if (setpgrp() < 0) #endif /* SETPGRP_HAVE_ARG */ - return posix_error(); - Py_INCREF(Py_None); - return Py_None; + return posix_error(); + Py_INCREF(Py_None); + return Py_None; } #endif /* HAVE_SETPGRP */ @@ -3965,7 +3965,7 @@ static PyObject * posix_getppid(PyObject *self, PyObject *noargs) { - return PyLong_FromPid(getppid()); + return PyLong_FromPid(getppid()); } #endif @@ -3978,22 +3978,22 @@ static PyObject * posix_getlogin(PyObject *self, PyObject *noargs) { - PyObject *result = NULL; - char *name; - int old_errno = errno; + PyObject *result = NULL; + char *name; + int old_errno = errno; - errno = 0; - name = getlogin(); - if (name == NULL) { - if (errno) - posix_error(); - else - PyErr_SetString(PyExc_OSError, - "unable to determine login name"); - } + errno = 0; + name = getlogin(); + if (name == NULL) { + if (errno) + posix_error(); else - result = PyString_FromString(name); - errno = old_errno; + PyErr_SetString(PyExc_OSError, + "unable to determine login name"); + } + else + result = PyString_FromString(name); + errno = old_errno; return result; } @@ -4007,7 +4007,7 @@ static PyObject * posix_getuid(PyObject *self, PyObject *noargs) { - return PyInt_FromLong((long)getuid()); + return PyInt_FromLong((long)getuid()); } #endif @@ -4020,10 +4020,10 @@ static PyObject * posix_kill(PyObject *self, PyObject *args) { - pid_t pid; - int sig; - if (!PyArg_ParseTuple(args, PARSE_PID "i:kill", &pid, &sig)) - return NULL; + pid_t pid; + int sig; + if (!PyArg_ParseTuple(args, PARSE_PID "i:kill", &pid, &sig)) + return NULL; #if defined(PYOS_OS2) && !defined(PYCC_GCC) if (sig == XCPT_SIGNAL_INTR || sig == XCPT_SIGNAL_BREAK) { APIRET rc; @@ -4038,11 +4038,11 @@ } else return NULL; /* Unrecognized Signal Requested */ #else - if (kill(pid, sig) == -1) - return posix_error(); + if (kill(pid, sig) == -1) + return posix_error(); #endif - Py_INCREF(Py_None); - return Py_None; + Py_INCREF(Py_None); + return Py_None; } #endif @@ -4054,18 +4054,18 @@ static PyObject * posix_killpg(PyObject *self, PyObject *args) { - int sig; - pid_t pgid; - /* XXX some man pages make the `pgid` parameter an int, others - a pid_t. Since getpgrp() returns a pid_t, we assume killpg should - take the same type. Moreover, pid_t is always at least as wide as - int (else compilation of this module fails), which is safe. */ - if (!PyArg_ParseTuple(args, PARSE_PID "i:killpg", &pgid, &sig)) - return NULL; - if (killpg(pgid, sig) == -1) - return posix_error(); - Py_INCREF(Py_None); - return Py_None; + int sig; + pid_t pgid; + /* XXX some man pages make the `pgid` parameter an int, others + a pid_t. Since getpgrp() returns a pid_t, we assume killpg should + take the same type. Moreover, pid_t is always at least as wide as + int (else compilation of this module fails), which is safe. */ + if (!PyArg_ParseTuple(args, PARSE_PID "i:killpg", &pgid, &sig)) + return NULL; + if (killpg(pgid, sig) == -1) + return posix_error(); + Py_INCREF(Py_None); + return Py_None; } #endif @@ -4082,13 +4082,13 @@ static PyObject * posix_plock(PyObject *self, PyObject *args) { - int op; - if (!PyArg_ParseTuple(args, "i:plock", &op)) - return NULL; - if (plock(op) == -1) - return posix_error(); - Py_INCREF(Py_None); - return Py_None; + int op; + if (!PyArg_ParseTuple(args, "i:plock", &op)) + return NULL; + if (plock(op) == -1) + return posix_error(); + Py_INCREF(Py_None); + return Py_None; } #endif @@ -4103,107 +4103,107 @@ static int async_system(const char *command) { - char errormsg[256], args[1024]; - RESULTCODES rcodes; - APIRET rc; - - char *shell = getenv("COMSPEC"); - if (!shell) - shell = "cmd"; - - /* avoid overflowing the argument buffer */ - if (strlen(shell) + 3 + strlen(command) >= 1024) - return ERROR_NOT_ENOUGH_MEMORY - - args[0] = '\0'; - strcat(args, shell); - strcat(args, "/c "); - strcat(args, command); - - /* execute asynchronously, inheriting the environment */ - rc = DosExecPgm(errormsg, - sizeof(errormsg), - EXEC_ASYNC, - args, - NULL, - &rcodes, - shell); - return rc; + char errormsg[256], args[1024]; + RESULTCODES rcodes; + APIRET rc; + + char *shell = getenv("COMSPEC"); + if (!shell) + shell = "cmd"; + + /* avoid overflowing the argument buffer */ + if (strlen(shell) + 3 + strlen(command) >= 1024) + return ERROR_NOT_ENOUGH_MEMORY + + args[0] = '\0'; + strcat(args, shell); + strcat(args, "/c "); + strcat(args, command); + + /* execute asynchronously, inheriting the environment */ + rc = DosExecPgm(errormsg, + sizeof(errormsg), + EXEC_ASYNC, + args, + NULL, + &rcodes, + shell); + return rc; } static FILE * popen(const char *command, const char *mode, int pipesize, int *err) { - int oldfd, tgtfd; - HFILE pipeh[2]; - APIRET rc; - - /* mode determines which of stdin or stdout is reconnected to - * the pipe to the child - */ - if (strchr(mode, 'r') != NULL) { - tgt_fd = 1; /* stdout */ - } else if (strchr(mode, 'w')) { - tgt_fd = 0; /* stdin */ - } else { - *err = ERROR_INVALID_ACCESS; - return NULL; - } - - /* setup the pipe */ - if ((rc = DosCreatePipe(&pipeh[0], &pipeh[1], pipesize)) != NO_ERROR) { - *err = rc; - return NULL; - } - - /* prevent other threads accessing stdio */ - DosEnterCritSec(); - - /* reconnect stdio and execute child */ - oldfd = dup(tgtfd); - close(tgtfd); - if (dup2(pipeh[tgtfd], tgtfd) == 0) { - DosClose(pipeh[tgtfd]); - rc = async_system(command); - } - - /* restore stdio */ - dup2(oldfd, tgtfd); - close(oldfd); - - /* allow other threads access to stdio */ - DosExitCritSec(); - - /* if execution of child was successful return file stream */ - if (rc == NO_ERROR) - return fdopen(pipeh[1 - tgtfd], mode); - else { - DosClose(pipeh[1 - tgtfd]); - *err = rc; - return NULL; - } + int oldfd, tgtfd; + HFILE pipeh[2]; + APIRET rc; + + /* mode determines which of stdin or stdout is reconnected to + * the pipe to the child + */ + if (strchr(mode, 'r') != NULL) { + tgt_fd = 1; /* stdout */ + } else if (strchr(mode, 'w')) { + tgt_fd = 0; /* stdin */ + } else { + *err = ERROR_INVALID_ACCESS; + return NULL; + } + + /* setup the pipe */ + if ((rc = DosCreatePipe(&pipeh[0], &pipeh[1], pipesize)) != NO_ERROR) { + *err = rc; + return NULL; + } + + /* prevent other threads accessing stdio */ + DosEnterCritSec(); + + /* reconnect stdio and execute child */ + oldfd = dup(tgtfd); + close(tgtfd); + if (dup2(pipeh[tgtfd], tgtfd) == 0) { + DosClose(pipeh[tgtfd]); + rc = async_system(command); + } + + /* restore stdio */ + dup2(oldfd, tgtfd); + close(oldfd); + + /* allow other threads access to stdio */ + DosExitCritSec(); + + /* if execution of child was successful return file stream */ + if (rc == NO_ERROR) + return fdopen(pipeh[1 - tgtfd], mode); + else { + DosClose(pipeh[1 - tgtfd]); + *err = rc; + return NULL; + } } static PyObject * posix_popen(PyObject *self, PyObject *args) { - char *name; - char *mode = "r"; - int err, bufsize = -1; - FILE *fp; - PyObject *f; - if (!PyArg_ParseTuple(args, "s|si:popen", &name, &mode, &bufsize)) - return NULL; - Py_BEGIN_ALLOW_THREADS - fp = popen(name, mode, (bufsize > 0) ? bufsize : 4096, &err); - Py_END_ALLOW_THREADS - if (fp == NULL) - return os2_error(err); - - f = PyFile_FromFile(fp, name, mode, fclose); - if (f != NULL) - PyFile_SetBufSize(f, bufsize); - return f; + char *name; + char *mode = "r"; + int err, bufsize = -1; + FILE *fp; + PyObject *f; + if (!PyArg_ParseTuple(args, "s|si:popen", &name, &mode, &bufsize)) + return NULL; + Py_BEGIN_ALLOW_THREADS + fp = popen(name, mode, (bufsize > 0) ? bufsize : 4096, &err); + Py_END_ALLOW_THREADS + if (fp == NULL) + return os2_error(err); + + f = PyFile_FromFile(fp, name, mode, fclose); + if (f != NULL) + PyFile_SetBufSize(f, bufsize); + return f; } #elif defined(PYCC_GCC) @@ -4212,22 +4212,22 @@ static PyObject * posix_popen(PyObject *self, PyObject *args) { - char *name; - char *mode = "r"; - int bufsize = -1; - FILE *fp; - PyObject *f; - if (!PyArg_ParseTuple(args, "s|si:popen", &name, &mode, &bufsize)) - return NULL; - Py_BEGIN_ALLOW_THREADS - fp = popen(name, mode); - Py_END_ALLOW_THREADS - if (fp == NULL) - return posix_error(); - f = PyFile_FromFile(fp, name, mode, pclose); - if (f != NULL) - PyFile_SetBufSize(f, bufsize); - return f; + char *name; + char *mode = "r"; + int bufsize = -1; + FILE *fp; + PyObject *f; + if (!PyArg_ParseTuple(args, "s|si:popen", &name, &mode, &bufsize)) + return NULL; + Py_BEGIN_ALLOW_THREADS + fp = popen(name, mode); + Py_END_ALLOW_THREADS + if (fp == NULL) + return posix_error(); + f = PyFile_FromFile(fp, name, mode, pclose); + if (f != NULL) + PyFile_SetBufSize(f, bufsize); + return f; } /* fork() under OS/2 has lots'o'warts @@ -4261,26 +4261,26 @@ static PyObject * os2emx_popen2(PyObject *self, PyObject *args) { - PyObject *f; - int tm=0; + PyObject *f; + int tm=0; - char *cmdstring; - char *mode = "t"; - int bufsize = -1; - if (!PyArg_ParseTuple(args, "s|si:popen2", &cmdstring, &mode, &bufsize)) - return NULL; - - if (*mode == 't') - tm = O_TEXT; - else if (*mode != 'b') { - PyErr_SetString(PyExc_ValueError, "mode must be 't' or 'b'"); - return NULL; - } else - tm = O_BINARY; + char *cmdstring; + char *mode = "t"; + int bufsize = -1; + if (!PyArg_ParseTuple(args, "s|si:popen2", &cmdstring, &mode, &bufsize)) + return NULL; + + if (*mode == 't') + tm = O_TEXT; + else if (*mode != 'b') { + PyErr_SetString(PyExc_ValueError, "mode must be 't' or 'b'"); + return NULL; + } else + tm = O_BINARY; - f = _PyPopen(cmdstring, tm, POPEN_2, bufsize); + f = _PyPopen(cmdstring, tm, POPEN_2, bufsize); - return f; + return f; } /* @@ -4293,26 +4293,26 @@ static PyObject * os2emx_popen3(PyObject *self, PyObject *args) { - PyObject *f; - int tm = 0; + PyObject *f; + int tm = 0; - char *cmdstring; - char *mode = "t"; - int bufsize = -1; - if (!PyArg_ParseTuple(args, "s|si:popen3", &cmdstring, &mode, &bufsize)) - return NULL; - - if (*mode == 't') - tm = O_TEXT; - else if (*mode != 'b') { - PyErr_SetString(PyExc_ValueError, "mode must be 't' or 'b'"); - return NULL; - } else - tm = O_BINARY; + char *cmdstring; + char *mode = "t"; + int bufsize = -1; + if (!PyArg_ParseTuple(args, "s|si:popen3", &cmdstring, &mode, &bufsize)) + return NULL; + + if (*mode == 't') + tm = O_TEXT; + else if (*mode != 'b') { + PyErr_SetString(PyExc_ValueError, "mode must be 't' or 'b'"); + return NULL; + } else + tm = O_BINARY; - f = _PyPopen(cmdstring, tm, POPEN_3, bufsize); + f = _PyPopen(cmdstring, tm, POPEN_3, bufsize); - return f; + return f; } /* @@ -4325,26 +4325,26 @@ static PyObject * os2emx_popen4(PyObject *self, PyObject *args) { - PyObject *f; - int tm = 0; + PyObject *f; + int tm = 0; - char *cmdstring; - char *mode = "t"; - int bufsize = -1; - if (!PyArg_ParseTuple(args, "s|si:popen4", &cmdstring, &mode, &bufsize)) - return NULL; - - if (*mode == 't') - tm = O_TEXT; - else if (*mode != 'b') { - PyErr_SetString(PyExc_ValueError, "mode must be 't' or 'b'"); - return NULL; - } else - tm = O_BINARY; + char *cmdstring; + char *mode = "t"; + int bufsize = -1; + if (!PyArg_ParseTuple(args, "s|si:popen4", &cmdstring, &mode, &bufsize)) + return NULL; + + if (*mode == 't') + tm = O_TEXT; + else if (*mode != 'b') { + PyErr_SetString(PyExc_ValueError, "mode must be 't' or 'b'"); + return NULL; + } else + tm = O_BINARY; - f = _PyPopen(cmdstring, tm, POPEN_4, bufsize); + f = _PyPopen(cmdstring, tm, POPEN_4, bufsize); - return f; + return f; } /* a couple of structures for convenient handling of multiple @@ -4352,14 +4352,14 @@ */ struct file_ref { - int handle; - int flags; + int handle; + int flags; }; struct pipe_ref { - int rd; - int wr; + int rd; + int wr; }; /* The following code is derived from the win32 code */ @@ -4367,306 +4367,306 @@ static PyObject * _PyPopen(char *cmdstring, int mode, int n, int bufsize) { - struct file_ref stdio[3]; - struct pipe_ref p_fd[3]; - FILE *p_s[3]; - int file_count, i, pipe_err; - pid_t pipe_pid; - char *shell, *sh_name, *opt, *rd_mode, *wr_mode; - PyObject *f, *p_f[3]; - - /* file modes for subsequent fdopen's on pipe handles */ - if (mode == O_TEXT) - { - rd_mode = "rt"; - wr_mode = "wt"; - } - else - { - rd_mode = "rb"; - wr_mode = "wb"; - } - - /* prepare shell references */ - if ((shell = getenv("EMXSHELL")) == NULL) - if ((shell = getenv("COMSPEC")) == NULL) - { - errno = ENOENT; - return posix_error(); - } - - sh_name = _getname(shell); - if (stricmp(sh_name, "cmd.exe") == 0 || stricmp(sh_name, "4os2.exe") == 0) - opt = "/c"; - else - opt = "-c"; - - /* save current stdio fds + their flags, and set not inheritable */ - i = pipe_err = 0; - while (pipe_err >= 0 && i < 3) - { - pipe_err = stdio[i].handle = dup(i); - stdio[i].flags = fcntl(i, F_GETFD, 0); - fcntl(stdio[i].handle, F_SETFD, stdio[i].flags | FD_CLOEXEC); - i++; - } - if (pipe_err < 0) - { - /* didn't get them all saved - clean up and bail out */ - int saved_err = errno; - while (i-- > 0) - { - close(stdio[i].handle); - } - errno = saved_err; - return posix_error(); - } - - /* create pipe ends */ - file_count = 2; - if (n == POPEN_3) - file_count = 3; - i = pipe_err = 0; - while ((pipe_err == 0) && (i < file_count)) - pipe_err = pipe((int *)&p_fd[i++]); - if (pipe_err < 0) - { - /* didn't get them all made - clean up and bail out */ - while (i-- > 0) - { - close(p_fd[i].wr); - close(p_fd[i].rd); - } - errno = EPIPE; - return posix_error(); - } - - /* change the actual standard IO streams over temporarily, - * making the retained pipe ends non-inheritable - */ - pipe_err = 0; - - /* - stdin */ - if (dup2(p_fd[0].rd, 0) == 0) - { - close(p_fd[0].rd); - i = fcntl(p_fd[0].wr, F_GETFD, 0); - fcntl(p_fd[0].wr, F_SETFD, i | FD_CLOEXEC); - if ((p_s[0] = fdopen(p_fd[0].wr, wr_mode)) == NULL) - { - close(p_fd[0].wr); - pipe_err = -1; - } - } - else - { - pipe_err = -1; - } - - /* - stdout */ - if (pipe_err == 0) - { - if (dup2(p_fd[1].wr, 1) == 1) - { - close(p_fd[1].wr); - i = fcntl(p_fd[1].rd, F_GETFD, 0); - fcntl(p_fd[1].rd, F_SETFD, i | FD_CLOEXEC); - if ((p_s[1] = fdopen(p_fd[1].rd, rd_mode)) == NULL) - { - close(p_fd[1].rd); - pipe_err = -1; - } - } - else - { - pipe_err = -1; - } - } - - /* - stderr, as required */ - if (pipe_err == 0) - switch (n) - { - case POPEN_3: - { - if (dup2(p_fd[2].wr, 2) == 2) - { - close(p_fd[2].wr); - i = fcntl(p_fd[2].rd, F_GETFD, 0); - fcntl(p_fd[2].rd, F_SETFD, i | FD_CLOEXEC); - if ((p_s[2] = fdopen(p_fd[2].rd, rd_mode)) == NULL) - { - close(p_fd[2].rd); - pipe_err = -1; - } - } - else - { - pipe_err = -1; - } - break; - } - - case POPEN_4: - { - if (dup2(1, 2) != 2) - { - pipe_err = -1; - } - break; - } - } - - /* spawn the child process */ - if (pipe_err == 0) - { - pipe_pid = spawnlp(P_NOWAIT, shell, shell, opt, cmdstring, (char *)0); - if (pipe_pid == -1) - { - pipe_err = -1; - } - else - { - /* save the PID into the FILE structure - * NOTE: this implementation doesn't actually - * take advantage of this, but do it for - * completeness - AIM Apr01 - */ - for (i = 0; i < file_count; i++) - p_s[i]->_pid = pipe_pid; - } - } - - /* reset standard IO to normal */ - for (i = 0; i < 3; i++) - { - dup2(stdio[i].handle, i); - fcntl(i, F_SETFD, stdio[i].flags); - close(stdio[i].handle); - } - - /* if any remnant problems, clean up and bail out */ - if (pipe_err < 0) - { - for (i = 0; i < 3; i++) - { - close(p_fd[i].rd); - close(p_fd[i].wr); - } - errno = EPIPE; - return posix_error_with_filename(cmdstring); - } - - /* build tuple of file objects to return */ - if ((p_f[0] = PyFile_FromFile(p_s[0], cmdstring, wr_mode, _PyPclose)) != NULL) - PyFile_SetBufSize(p_f[0], bufsize); - if ((p_f[1] = PyFile_FromFile(p_s[1], cmdstring, rd_mode, _PyPclose)) != NULL) - PyFile_SetBufSize(p_f[1], bufsize); - if (n == POPEN_3) - { - if ((p_f[2] = PyFile_FromFile(p_s[2], cmdstring, rd_mode, _PyPclose)) != NULL) - PyFile_SetBufSize(p_f[0], bufsize); - f = PyTuple_Pack(3, p_f[0], p_f[1], p_f[2]); - } - else - f = PyTuple_Pack(2, p_f[0], p_f[1]); - - /* - * Insert the files we've created into the process dictionary - * all referencing the list with the process handle and the - * initial number of files (see description below in _PyPclose). - * Since if _PyPclose later tried to wait on a process when all - * handles weren't closed, it could create a deadlock with the - * child, we spend some energy here to try to ensure that we - * either insert all file handles into the dictionary or none - * at all. It's a little clumsy with the various popen modes - * and variable number of files involved. - */ - if (!_PyPopenProcs) - { - _PyPopenProcs = PyDict_New(); - } - - if (_PyPopenProcs) - { - PyObject *procObj, *pidObj, *intObj, *fileObj[3]; - int ins_rc[3]; - - fileObj[0] = fileObj[1] = fileObj[2] = NULL; - ins_rc[0] = ins_rc[1] = ins_rc[2] = 0; - - procObj = PyList_New(2); - pidObj = PyLong_FromPid(pipe_pid); - intObj = PyInt_FromLong((long) file_count); - - if (procObj && pidObj && intObj) - { - PyList_SetItem(procObj, 0, pidObj); - PyList_SetItem(procObj, 1, intObj); - - fileObj[0] = PyLong_FromVoidPtr(p_s[0]); - if (fileObj[0]) - { - ins_rc[0] = PyDict_SetItem(_PyPopenProcs, - fileObj[0], - procObj); - } - fileObj[1] = PyLong_FromVoidPtr(p_s[1]); - if (fileObj[1]) - { - ins_rc[1] = PyDict_SetItem(_PyPopenProcs, - fileObj[1], - procObj); - } - if (file_count >= 3) - { - fileObj[2] = PyLong_FromVoidPtr(p_s[2]); - if (fileObj[2]) - { - ins_rc[2] = PyDict_SetItem(_PyPopenProcs, - fileObj[2], - procObj); - } - } - - if (ins_rc[0] < 0 || !fileObj[0] || - ins_rc[1] < 0 || (file_count > 1 && !fileObj[1]) || - ins_rc[2] < 0 || (file_count > 2 && !fileObj[2])) - { - /* Something failed - remove any dictionary - * entries that did make it. - */ - if (!ins_rc[0] && fileObj[0]) - { - PyDict_DelItem(_PyPopenProcs, - fileObj[0]); - } - if (!ins_rc[1] && fileObj[1]) - { - PyDict_DelItem(_PyPopenProcs, - fileObj[1]); - } - if (!ins_rc[2] && fileObj[2]) - { - PyDict_DelItem(_PyPopenProcs, - fileObj[2]); - } - } - } - - /* - * Clean up our localized references for the dictionary keys - * and value since PyDict_SetItem will Py_INCREF any copies - * that got placed in the dictionary. - */ - Py_XDECREF(procObj); - Py_XDECREF(fileObj[0]); - Py_XDECREF(fileObj[1]); - Py_XDECREF(fileObj[2]); - } + struct file_ref stdio[3]; + struct pipe_ref p_fd[3]; + FILE *p_s[3]; + int file_count, i, pipe_err; + pid_t pipe_pid; + char *shell, *sh_name, *opt, *rd_mode, *wr_mode; + PyObject *f, *p_f[3]; + + /* file modes for subsequent fdopen's on pipe handles */ + if (mode == O_TEXT) + { + rd_mode = "rt"; + wr_mode = "wt"; + } + else + { + rd_mode = "rb"; + wr_mode = "wb"; + } + + /* prepare shell references */ + if ((shell = getenv("EMXSHELL")) == NULL) + if ((shell = getenv("COMSPEC")) == NULL) + { + errno = ENOENT; + return posix_error(); + } + + sh_name = _getname(shell); + if (stricmp(sh_name, "cmd.exe") == 0 || stricmp(sh_name, "4os2.exe") == 0) + opt = "/c"; + else + opt = "-c"; + + /* save current stdio fds + their flags, and set not inheritable */ + i = pipe_err = 0; + while (pipe_err >= 0 && i < 3) + { + pipe_err = stdio[i].handle = dup(i); + stdio[i].flags = fcntl(i, F_GETFD, 0); + fcntl(stdio[i].handle, F_SETFD, stdio[i].flags | FD_CLOEXEC); + i++; + } + if (pipe_err < 0) + { + /* didn't get them all saved - clean up and bail out */ + int saved_err = errno; + while (i-- > 0) + { + close(stdio[i].handle); + } + errno = saved_err; + return posix_error(); + } - /* Child is launched. */ - return f; + /* create pipe ends */ + file_count = 2; + if (n == POPEN_3) + file_count = 3; + i = pipe_err = 0; + while ((pipe_err == 0) && (i < file_count)) + pipe_err = pipe((int *)&p_fd[i++]); + if (pipe_err < 0) + { + /* didn't get them all made - clean up and bail out */ + while (i-- > 0) + { + close(p_fd[i].wr); + close(p_fd[i].rd); + } + errno = EPIPE; + return posix_error(); + } + + /* change the actual standard IO streams over temporarily, + * making the retained pipe ends non-inheritable + */ + pipe_err = 0; + + /* - stdin */ + if (dup2(p_fd[0].rd, 0) == 0) + { + close(p_fd[0].rd); + i = fcntl(p_fd[0].wr, F_GETFD, 0); + fcntl(p_fd[0].wr, F_SETFD, i | FD_CLOEXEC); + if ((p_s[0] = fdopen(p_fd[0].wr, wr_mode)) == NULL) + { + close(p_fd[0].wr); + pipe_err = -1; + } + } + else + { + pipe_err = -1; + } + + /* - stdout */ + if (pipe_err == 0) + { + if (dup2(p_fd[1].wr, 1) == 1) + { + close(p_fd[1].wr); + i = fcntl(p_fd[1].rd, F_GETFD, 0); + fcntl(p_fd[1].rd, F_SETFD, i | FD_CLOEXEC); + if ((p_s[1] = fdopen(p_fd[1].rd, rd_mode)) == NULL) + { + close(p_fd[1].rd); + pipe_err = -1; + } + } + else + { + pipe_err = -1; + } + } + + /* - stderr, as required */ + if (pipe_err == 0) + switch (n) + { + case POPEN_3: + { + if (dup2(p_fd[2].wr, 2) == 2) + { + close(p_fd[2].wr); + i = fcntl(p_fd[2].rd, F_GETFD, 0); + fcntl(p_fd[2].rd, F_SETFD, i | FD_CLOEXEC); + if ((p_s[2] = fdopen(p_fd[2].rd, rd_mode)) == NULL) + { + close(p_fd[2].rd); + pipe_err = -1; + } + } + else + { + pipe_err = -1; + } + break; + } + + case POPEN_4: + { + if (dup2(1, 2) != 2) + { + pipe_err = -1; + } + break; + } + } + + /* spawn the child process */ + if (pipe_err == 0) + { + pipe_pid = spawnlp(P_NOWAIT, shell, shell, opt, cmdstring, (char *)0); + if (pipe_pid == -1) + { + pipe_err = -1; + } + else + { + /* save the PID into the FILE structure + * NOTE: this implementation doesn't actually + * take advantage of this, but do it for + * completeness - AIM Apr01 + */ + for (i = 0; i < file_count; i++) + p_s[i]->_pid = pipe_pid; + } + } + + /* reset standard IO to normal */ + for (i = 0; i < 3; i++) + { + dup2(stdio[i].handle, i); + fcntl(i, F_SETFD, stdio[i].flags); + close(stdio[i].handle); + } + + /* if any remnant problems, clean up and bail out */ + if (pipe_err < 0) + { + for (i = 0; i < 3; i++) + { + close(p_fd[i].rd); + close(p_fd[i].wr); + } + errno = EPIPE; + return posix_error_with_filename(cmdstring); + } + + /* build tuple of file objects to return */ + if ((p_f[0] = PyFile_FromFile(p_s[0], cmdstring, wr_mode, _PyPclose)) != NULL) + PyFile_SetBufSize(p_f[0], bufsize); + if ((p_f[1] = PyFile_FromFile(p_s[1], cmdstring, rd_mode, _PyPclose)) != NULL) + PyFile_SetBufSize(p_f[1], bufsize); + if (n == POPEN_3) + { + if ((p_f[2] = PyFile_FromFile(p_s[2], cmdstring, rd_mode, _PyPclose)) != NULL) + PyFile_SetBufSize(p_f[0], bufsize); + f = PyTuple_Pack(3, p_f[0], p_f[1], p_f[2]); + } + else + f = PyTuple_Pack(2, p_f[0], p_f[1]); + + /* + * Insert the files we've created into the process dictionary + * all referencing the list with the process handle and the + * initial number of files (see description below in _PyPclose). + * Since if _PyPclose later tried to wait on a process when all + * handles weren't closed, it could create a deadlock with the + * child, we spend some energy here to try to ensure that we + * either insert all file handles into the dictionary or none + * at all. It's a little clumsy with the various popen modes + * and variable number of files involved. + */ + if (!_PyPopenProcs) + { + _PyPopenProcs = PyDict_New(); + } + + if (_PyPopenProcs) + { + PyObject *procObj, *pidObj, *intObj, *fileObj[3]; + int ins_rc[3]; + + fileObj[0] = fileObj[1] = fileObj[2] = NULL; + ins_rc[0] = ins_rc[1] = ins_rc[2] = 0; + + procObj = PyList_New(2); + pidObj = PyLong_FromPid(pipe_pid); + intObj = PyInt_FromLong((long) file_count); + + if (procObj && pidObj && intObj) + { + PyList_SetItem(procObj, 0, pidObj); + PyList_SetItem(procObj, 1, intObj); + + fileObj[0] = PyLong_FromVoidPtr(p_s[0]); + if (fileObj[0]) + { + ins_rc[0] = PyDict_SetItem(_PyPopenProcs, + fileObj[0], + procObj); + } + fileObj[1] = PyLong_FromVoidPtr(p_s[1]); + if (fileObj[1]) + { + ins_rc[1] = PyDict_SetItem(_PyPopenProcs, + fileObj[1], + procObj); + } + if (file_count >= 3) + { + fileObj[2] = PyLong_FromVoidPtr(p_s[2]); + if (fileObj[2]) + { + ins_rc[2] = PyDict_SetItem(_PyPopenProcs, + fileObj[2], + procObj); + } + } + + if (ins_rc[0] < 0 || !fileObj[0] || + ins_rc[1] < 0 || (file_count > 1 && !fileObj[1]) || + ins_rc[2] < 0 || (file_count > 2 && !fileObj[2])) + { + /* Something failed - remove any dictionary + * entries that did make it. + */ + if (!ins_rc[0] && fileObj[0]) + { + PyDict_DelItem(_PyPopenProcs, + fileObj[0]); + } + if (!ins_rc[1] && fileObj[1]) + { + PyDict_DelItem(_PyPopenProcs, + fileObj[1]); + } + if (!ins_rc[2] && fileObj[2]) + { + PyDict_DelItem(_PyPopenProcs, + fileObj[2]); + } + } + } + + /* + * Clean up our localized references for the dictionary keys + * and value since PyDict_SetItem will Py_INCREF any copies + * that got placed in the dictionary. + */ + Py_XDECREF(procObj); + Py_XDECREF(fileObj[0]); + Py_XDECREF(fileObj[1]); + Py_XDECREF(fileObj[2]); + } + + /* Child is launched. */ + return f; } /* @@ -4697,88 +4697,88 @@ static int _PyPclose(FILE *file) { - int result; - int exit_code; - pid_t pipe_pid; - PyObject *procObj, *pidObj, *intObj, *fileObj; - int file_count; + int result; + int exit_code; + pid_t pipe_pid; + PyObject *procObj, *pidObj, *intObj, *fileObj; + int file_count; #ifdef WITH_THREAD - PyGILState_STATE state; + PyGILState_STATE state; #endif - /* Close the file handle first, to ensure it can't block the - * child from exiting if it's the last handle. - */ - result = fclose(file); + /* Close the file handle first, to ensure it can't block the + * child from exiting if it's the last handle. + */ + result = fclose(file); #ifdef WITH_THREAD - state = PyGILState_Ensure(); + state = PyGILState_Ensure(); #endif - if (_PyPopenProcs) - { - if ((fileObj = PyLong_FromVoidPtr(file)) != NULL && - (procObj = PyDict_GetItem(_PyPopenProcs, - fileObj)) != NULL && - (pidObj = PyList_GetItem(procObj,0)) != NULL && - (intObj = PyList_GetItem(procObj,1)) != NULL) - { - pipe_pid = (pid_t) PyLong_AsPid(pidObj); - file_count = (int) PyInt_AsLong(intObj); - - if (file_count > 1) - { - /* Still other files referencing process */ - file_count--; - PyList_SetItem(procObj,1, - PyInt_FromLong((long) file_count)); - } - else - { - /* Last file for this process */ - if (result != EOF && - waitpid(pipe_pid, &exit_code, 0) == pipe_pid) - { - /* extract exit status */ - if (WIFEXITED(exit_code)) - { - result = WEXITSTATUS(exit_code); - } - else - { - errno = EPIPE; - result = -1; - } - } - else - { - /* Indicate failure - this will cause the file object - * to raise an I/O error and translate the last - * error code from errno. We do have a problem with - * last errors that overlap the normal errno table, - * but that's a consistent problem with the file object. - */ - result = -1; - } - } - - /* Remove this file pointer from dictionary */ - PyDict_DelItem(_PyPopenProcs, fileObj); - - if (PyDict_Size(_PyPopenProcs) == 0) - { - Py_DECREF(_PyPopenProcs); - _PyPopenProcs = NULL; - } + if (_PyPopenProcs) + { + if ((fileObj = PyLong_FromVoidPtr(file)) != NULL && + (procObj = PyDict_GetItem(_PyPopenProcs, + fileObj)) != NULL && + (pidObj = PyList_GetItem(procObj,0)) != NULL && + (intObj = PyList_GetItem(procObj,1)) != NULL) + { + pipe_pid = (pid_t) PyLong_AsPid(pidObj); + file_count = (int) PyInt_AsLong(intObj); + + if (file_count > 1) + { + /* Still other files referencing process */ + file_count--; + PyList_SetItem(procObj,1, + PyInt_FromLong((long) file_count)); + } + else + { + /* Last file for this process */ + if (result != EOF && + waitpid(pipe_pid, &exit_code, 0) == pipe_pid) + { + /* extract exit status */ + if (WIFEXITED(exit_code)) + { + result = WEXITSTATUS(exit_code); + } + else + { + errno = EPIPE; + result = -1; + } + } + else + { + /* Indicate failure - this will cause the file object + * to raise an I/O error and translate the last + * error code from errno. We do have a problem with + * last errors that overlap the normal errno table, + * but that's a consistent problem with the file object. + */ + result = -1; + } + } - } /* if object retrieval ok */ + /* Remove this file pointer from dictionary */ + PyDict_DelItem(_PyPopenProcs, fileObj); + + if (PyDict_Size(_PyPopenProcs) == 0) + { + Py_DECREF(_PyPopenProcs); + _PyPopenProcs = NULL; + } - Py_XDECREF(fileObj); - } /* if _PyPopenProcs */ + } /* if object retrieval ok */ + + Py_XDECREF(fileObj); + } /* if _PyPopenProcs */ #ifdef WITH_THREAD - PyGILState_Release(state); + PyGILState_Release(state); #endif - return result; + return result; } #endif /* PYCC_??? */ @@ -4823,36 +4823,36 @@ static PyObject * posix_popen(PyObject *self, PyObject *args) { - PyObject *f; - int tm = 0; + PyObject *f; + int tm = 0; + + char *cmdstring; + char *mode = "r"; + int bufsize = -1; + if (!PyArg_ParseTuple(args, "s|si:popen", &cmdstring, &mode, &bufsize)) + return NULL; + + if (*mode == 'r') + tm = _O_RDONLY; + else if (*mode != 'w') { + PyErr_SetString(PyExc_ValueError, "popen() arg 2 must be 'r' or 'w'"); + return NULL; + } else + tm = _O_WRONLY; + + if (bufsize != -1) { + PyErr_SetString(PyExc_ValueError, "popen() arg 3 must be -1"); + return NULL; + } - char *cmdstring; - char *mode = "r"; - int bufsize = -1; - if (!PyArg_ParseTuple(args, "s|si:popen", &cmdstring, &mode, &bufsize)) - return NULL; - - if (*mode == 'r') - tm = _O_RDONLY; - else if (*mode != 'w') { - PyErr_SetString(PyExc_ValueError, "popen() arg 2 must be 'r' or 'w'"); - return NULL; - } else - tm = _O_WRONLY; - - if (bufsize != -1) { - PyErr_SetString(PyExc_ValueError, "popen() arg 3 must be -1"); - return NULL; - } - - if (*(mode+1) == 't') - f = _PyPopen(cmdstring, tm | _O_TEXT, POPEN_1); - else if (*(mode+1) == 'b') - f = _PyPopen(cmdstring, tm | _O_BINARY, POPEN_1); - else - f = _PyPopen(cmdstring, tm | _O_TEXT, POPEN_1); + if (*(mode+1) == 't') + f = _PyPopen(cmdstring, tm | _O_TEXT, POPEN_1); + else if (*(mode+1) == 'b') + f = _PyPopen(cmdstring, tm | _O_BINARY, POPEN_1); + else + f = _PyPopen(cmdstring, tm | _O_TEXT, POPEN_1); - return f; + return f; } /* Variation on win32pipe.popen @@ -4864,31 +4864,31 @@ static PyObject * win32_popen2(PyObject *self, PyObject *args) { - PyObject *f; - int tm=0; + PyObject *f; + int tm=0; + + char *cmdstring; + char *mode = "t"; + int bufsize = -1; + if (!PyArg_ParseTuple(args, "s|si:popen2", &cmdstring, &mode, &bufsize)) + return NULL; + + if (*mode == 't') + tm = _O_TEXT; + else if (*mode != 'b') { + PyErr_SetString(PyExc_ValueError, "popen2() arg 2 must be 't' or 'b'"); + return NULL; + } else + tm = _O_BINARY; - char *cmdstring; - char *mode = "t"; - int bufsize = -1; - if (!PyArg_ParseTuple(args, "s|si:popen2", &cmdstring, &mode, &bufsize)) - return NULL; - - if (*mode == 't') - tm = _O_TEXT; - else if (*mode != 'b') { - PyErr_SetString(PyExc_ValueError, "popen2() arg 2 must be 't' or 'b'"); - return NULL; - } else - tm = _O_BINARY; - - if (bufsize != -1) { - PyErr_SetString(PyExc_ValueError, "popen2() arg 3 must be -1"); - return NULL; - } + if (bufsize != -1) { + PyErr_SetString(PyExc_ValueError, "popen2() arg 3 must be -1"); + return NULL; + } - f = _PyPopen(cmdstring, tm, POPEN_2); + f = _PyPopen(cmdstring, tm, POPEN_2); - return f; + return f; } /* @@ -4901,31 +4901,31 @@ static PyObject * win32_popen3(PyObject *self, PyObject *args) { - PyObject *f; - int tm = 0; + PyObject *f; + int tm = 0; - char *cmdstring; - char *mode = "t"; - int bufsize = -1; - if (!PyArg_ParseTuple(args, "s|si:popen3", &cmdstring, &mode, &bufsize)) - return NULL; - - if (*mode == 't') - tm = _O_TEXT; - else if (*mode != 'b') { - PyErr_SetString(PyExc_ValueError, "popen3() arg 2 must be 't' or 'b'"); - return NULL; - } else - tm = _O_BINARY; - - if (bufsize != -1) { - PyErr_SetString(PyExc_ValueError, "popen3() arg 3 must be -1"); - return NULL; - } + char *cmdstring; + char *mode = "t"; + int bufsize = -1; + if (!PyArg_ParseTuple(args, "s|si:popen3", &cmdstring, &mode, &bufsize)) + return NULL; + + if (*mode == 't') + tm = _O_TEXT; + else if (*mode != 'b') { + PyErr_SetString(PyExc_ValueError, "popen3() arg 2 must be 't' or 'b'"); + return NULL; + } else + tm = _O_BINARY; + + if (bufsize != -1) { + PyErr_SetString(PyExc_ValueError, "popen3() arg 3 must be -1"); + return NULL; + } - f = _PyPopen(cmdstring, tm, POPEN_3); + f = _PyPopen(cmdstring, tm, POPEN_3); - return f; + return f; } /* @@ -4938,186 +4938,186 @@ static PyObject * win32_popen4(PyObject *self, PyObject *args) { - PyObject *f; - int tm = 0; + PyObject *f; + int tm = 0; - char *cmdstring; - char *mode = "t"; - int bufsize = -1; - if (!PyArg_ParseTuple(args, "s|si:popen4", &cmdstring, &mode, &bufsize)) - return NULL; - - if (*mode == 't') - tm = _O_TEXT; - else if (*mode != 'b') { - PyErr_SetString(PyExc_ValueError, "popen4() arg 2 must be 't' or 'b'"); - return NULL; - } else - tm = _O_BINARY; - - if (bufsize != -1) { - PyErr_SetString(PyExc_ValueError, "popen4() arg 3 must be -1"); - return NULL; - } + char *cmdstring; + char *mode = "t"; + int bufsize = -1; + if (!PyArg_ParseTuple(args, "s|si:popen4", &cmdstring, &mode, &bufsize)) + return NULL; + + if (*mode == 't') + tm = _O_TEXT; + else if (*mode != 'b') { + PyErr_SetString(PyExc_ValueError, "popen4() arg 2 must be 't' or 'b'"); + return NULL; + } else + tm = _O_BINARY; + + if (bufsize != -1) { + PyErr_SetString(PyExc_ValueError, "popen4() arg 3 must be -1"); + return NULL; + } - f = _PyPopen(cmdstring, tm, POPEN_4); + f = _PyPopen(cmdstring, tm, POPEN_4); - return f; + return f; } static BOOL _PyPopenCreateProcess(char *cmdstring, - HANDLE hStdin, - HANDLE hStdout, - HANDLE hStderr, - HANDLE *hProcess) -{ - PROCESS_INFORMATION piProcInfo; - STARTUPINFO siStartInfo; - DWORD dwProcessFlags = 0; /* no NEW_CONSOLE by default for Ctrl+C handling */ - char *s1,*s2, *s3 = " /c "; - const char *szConsoleSpawn = "w9xpopen.exe"; - int i; - Py_ssize_t x; - - if (i = GetEnvironmentVariable("COMSPEC",NULL,0)) { - char *comshell; - - s1 = (char *)alloca(i); - if (!(x = GetEnvironmentVariable("COMSPEC", s1, i))) - /* x < i, so x fits into an integer */ - return (int)x; - - /* Explicitly check if we are using COMMAND.COM. If we are - * then use the w9xpopen hack. - */ - comshell = s1 + x; - while (comshell >= s1 && *comshell != '\\') - --comshell; - ++comshell; - - if (GetVersion() < 0x80000000 && - _stricmp(comshell, "command.com") != 0) { - /* NT/2000 and not using command.com. */ - x = i + strlen(s3) + strlen(cmdstring) + 1; - s2 = (char *)alloca(x); - ZeroMemory(s2, x); - PyOS_snprintf(s2, x, "%s%s%s", s1, s3, cmdstring); - } - else { - /* - * Oh gag, we're on Win9x or using COMMAND.COM. Use - * the workaround listed in KB: Q150956 - */ - char modulepath[_MAX_PATH]; - struct stat statinfo; - GetModuleFileName(NULL, modulepath, sizeof(modulepath)); - for (x = i = 0; modulepath[i]; i++) - if (modulepath[i] == SEP) - x = i+1; - modulepath[x] = '\0'; - /* Create the full-name to w9xpopen, so we can test it exists */ - strncat(modulepath, - szConsoleSpawn, - (sizeof(modulepath)/sizeof(modulepath[0])) - -strlen(modulepath)); - if (stat(modulepath, &statinfo) != 0) { - size_t mplen = sizeof(modulepath)/sizeof(modulepath[0]); - /* Eeek - file-not-found - possibly an embedding - situation - see if we can locate it in sys.prefix - */ - strncpy(modulepath, - Py_GetExecPrefix(), - mplen); - modulepath[mplen-1] = '\0'; - if (modulepath[strlen(modulepath)-1] != '\\') - strcat(modulepath, "\\"); - strncat(modulepath, - szConsoleSpawn, - mplen-strlen(modulepath)); - /* No where else to look - raise an easily identifiable - error, rather than leaving Windows to report - "file not found" - as the user is probably blissfully - unaware this shim EXE is used, and it will confuse them. - (well, it confused me for a while ;-) - */ - if (stat(modulepath, &statinfo) != 0) { - PyErr_Format(PyExc_RuntimeError, - "Can not locate '%s' which is needed " - "for popen to work with your shell " - "or platform.", - szConsoleSpawn); - return FALSE; - } - } - x = i + strlen(s3) + strlen(cmdstring) + 1 + - strlen(modulepath) + - strlen(szConsoleSpawn) + 1; - - s2 = (char *)alloca(x); - ZeroMemory(s2, x); - /* To maintain correct argument passing semantics, - we pass the command-line as it stands, and allow - quoting to be applied. w9xpopen.exe will then - use its argv vector, and re-quote the necessary - args for the ultimate child process. - */ - PyOS_snprintf( - s2, x, - "\"%s\" %s%s%s", - modulepath, - s1, - s3, - cmdstring); - /* Not passing CREATE_NEW_CONSOLE has been known to - cause random failures on win9x. Specifically a - dialog: - "Your program accessed mem currently in use at xxx" - and a hopeful warning about the stability of your - system. - Cost is Ctrl+C won't kill children, but anyone - who cares can have a go! - */ - dwProcessFlags |= CREATE_NEW_CONSOLE; - } - } - - /* Could be an else here to try cmd.exe / command.com in the path - Now we'll just error out.. */ - else { - PyErr_SetString(PyExc_RuntimeError, - "Cannot locate a COMSPEC environment variable to " - "use as the shell"); - return FALSE; - } - - ZeroMemory(&siStartInfo, sizeof(STARTUPINFO)); - siStartInfo.cb = sizeof(STARTUPINFO); - siStartInfo.dwFlags = STARTF_USESTDHANDLES | STARTF_USESHOWWINDOW; - siStartInfo.hStdInput = hStdin; - siStartInfo.hStdOutput = hStdout; - siStartInfo.hStdError = hStderr; - siStartInfo.wShowWindow = SW_HIDE; - - if (CreateProcess(NULL, - s2, - NULL, - NULL, - TRUE, - dwProcessFlags, - NULL, - NULL, - &siStartInfo, - &piProcInfo) ) { - /* Close the handles now so anyone waiting is woken. */ - CloseHandle(piProcInfo.hThread); - - /* Return process handle */ - *hProcess = piProcInfo.hProcess; - return TRUE; - } - win32_error("CreateProcess", s2); - return FALSE; + HANDLE hStdin, + HANDLE hStdout, + HANDLE hStderr, + HANDLE *hProcess) +{ + PROCESS_INFORMATION piProcInfo; + STARTUPINFO siStartInfo; + DWORD dwProcessFlags = 0; /* no NEW_CONSOLE by default for Ctrl+C handling */ + char *s1,*s2, *s3 = " /c "; + const char *szConsoleSpawn = "w9xpopen.exe"; + int i; + Py_ssize_t x; + + if (i = GetEnvironmentVariable("COMSPEC",NULL,0)) { + char *comshell; + + s1 = (char *)alloca(i); + if (!(x = GetEnvironmentVariable("COMSPEC", s1, i))) + /* x < i, so x fits into an integer */ + return (int)x; + + /* Explicitly check if we are using COMMAND.COM. If we are + * then use the w9xpopen hack. + */ + comshell = s1 + x; + while (comshell >= s1 && *comshell != '\\') + --comshell; + ++comshell; + + if (GetVersion() < 0x80000000 && + _stricmp(comshell, "command.com") != 0) { + /* NT/2000 and not using command.com. */ + x = i + strlen(s3) + strlen(cmdstring) + 1; + s2 = (char *)alloca(x); + ZeroMemory(s2, x); + PyOS_snprintf(s2, x, "%s%s%s", s1, s3, cmdstring); + } + else { + /* + * Oh gag, we're on Win9x or using COMMAND.COM. Use + * the workaround listed in KB: Q150956 + */ + char modulepath[_MAX_PATH]; + struct stat statinfo; + GetModuleFileName(NULL, modulepath, sizeof(modulepath)); + for (x = i = 0; modulepath[i]; i++) + if (modulepath[i] == SEP) + x = i+1; + modulepath[x] = '\0'; + /* Create the full-name to w9xpopen, so we can test it exists */ + strncat(modulepath, + szConsoleSpawn, + (sizeof(modulepath)/sizeof(modulepath[0])) + -strlen(modulepath)); + if (stat(modulepath, &statinfo) != 0) { + size_t mplen = sizeof(modulepath)/sizeof(modulepath[0]); + /* Eeek - file-not-found - possibly an embedding + situation - see if we can locate it in sys.prefix + */ + strncpy(modulepath, + Py_GetExecPrefix(), + mplen); + modulepath[mplen-1] = '\0'; + if (modulepath[strlen(modulepath)-1] != '\\') + strcat(modulepath, "\\"); + strncat(modulepath, + szConsoleSpawn, + mplen-strlen(modulepath)); + /* No where else to look - raise an easily identifiable + error, rather than leaving Windows to report + "file not found" - as the user is probably blissfully + unaware this shim EXE is used, and it will confuse them. + (well, it confused me for a while ;-) + */ + if (stat(modulepath, &statinfo) != 0) { + PyErr_Format(PyExc_RuntimeError, + "Can not locate '%s' which is needed " + "for popen to work with your shell " + "or platform.", + szConsoleSpawn); + return FALSE; + } + } + x = i + strlen(s3) + strlen(cmdstring) + 1 + + strlen(modulepath) + + strlen(szConsoleSpawn) + 1; + + s2 = (char *)alloca(x); + ZeroMemory(s2, x); + /* To maintain correct argument passing semantics, + we pass the command-line as it stands, and allow + quoting to be applied. w9xpopen.exe will then + use its argv vector, and re-quote the necessary + args for the ultimate child process. + */ + PyOS_snprintf( + s2, x, + "\"%s\" %s%s%s", + modulepath, + s1, + s3, + cmdstring); + /* Not passing CREATE_NEW_CONSOLE has been known to + cause random failures on win9x. Specifically a + dialog: + "Your program accessed mem currently in use at xxx" + and a hopeful warning about the stability of your + system. + Cost is Ctrl+C won't kill children, but anyone + who cares can have a go! + */ + dwProcessFlags |= CREATE_NEW_CONSOLE; + } + } + + /* Could be an else here to try cmd.exe / command.com in the path + Now we'll just error out.. */ + else { + PyErr_SetString(PyExc_RuntimeError, + "Cannot locate a COMSPEC environment variable to " + "use as the shell"); + return FALSE; + } + + ZeroMemory(&siStartInfo, sizeof(STARTUPINFO)); + siStartInfo.cb = sizeof(STARTUPINFO); + siStartInfo.dwFlags = STARTF_USESTDHANDLES | STARTF_USESHOWWINDOW; + siStartInfo.hStdInput = hStdin; + siStartInfo.hStdOutput = hStdout; + siStartInfo.hStdError = hStderr; + siStartInfo.wShowWindow = SW_HIDE; + + if (CreateProcess(NULL, + s2, + NULL, + NULL, + TRUE, + dwProcessFlags, + NULL, + NULL, + &siStartInfo, + &piProcInfo) ) { + /* Close the handles now so anyone waiting is woken. */ + CloseHandle(piProcInfo.hThread); + + /* Return process handle */ + *hProcess = piProcInfo.hProcess; + return TRUE; + } + win32_error("CreateProcess", s2); + return FALSE; } /* The following code is based off of KB: Q190351 */ @@ -5125,301 +5125,301 @@ static PyObject * _PyPopen(char *cmdstring, int mode, int n) { - HANDLE hChildStdinRd, hChildStdinWr, hChildStdoutRd, hChildStdoutWr, - hChildStderrRd, hChildStderrWr, hChildStdinWrDup, hChildStdoutRdDup, - hChildStderrRdDup, hProcess; /* hChildStdoutWrDup; */ - - SECURITY_ATTRIBUTES saAttr; - BOOL fSuccess; - int fd1, fd2, fd3; - FILE *f1, *f2, *f3; - long file_count; - PyObject *f; - - saAttr.nLength = sizeof(SECURITY_ATTRIBUTES); - saAttr.bInheritHandle = TRUE; - saAttr.lpSecurityDescriptor = NULL; - - if (!CreatePipe(&hChildStdinRd, &hChildStdinWr, &saAttr, 0)) - return win32_error("CreatePipe", NULL); - - /* Create new output read handle and the input write handle. Set - * the inheritance properties to FALSE. Otherwise, the child inherits - * these handles; resulting in non-closeable handles to the pipes - * being created. */ - fSuccess = DuplicateHandle(GetCurrentProcess(), hChildStdinWr, - GetCurrentProcess(), &hChildStdinWrDup, 0, - FALSE, - DUPLICATE_SAME_ACCESS); - if (!fSuccess) - return win32_error("DuplicateHandle", NULL); - - /* Close the inheritable version of ChildStdin - that we're using. */ - CloseHandle(hChildStdinWr); - - if (!CreatePipe(&hChildStdoutRd, &hChildStdoutWr, &saAttr, 0)) - return win32_error("CreatePipe", NULL); - - fSuccess = DuplicateHandle(GetCurrentProcess(), hChildStdoutRd, - GetCurrentProcess(), &hChildStdoutRdDup, 0, - FALSE, DUPLICATE_SAME_ACCESS); - if (!fSuccess) - return win32_error("DuplicateHandle", NULL); - - /* Close the inheritable version of ChildStdout - that we're using. */ - CloseHandle(hChildStdoutRd); - - if (n != POPEN_4) { - if (!CreatePipe(&hChildStderrRd, &hChildStderrWr, &saAttr, 0)) - return win32_error("CreatePipe", NULL); - fSuccess = DuplicateHandle(GetCurrentProcess(), - hChildStderrRd, - GetCurrentProcess(), - &hChildStderrRdDup, 0, - FALSE, DUPLICATE_SAME_ACCESS); - if (!fSuccess) - return win32_error("DuplicateHandle", NULL); - /* Close the inheritable version of ChildStdErr that we're using. */ - CloseHandle(hChildStderrRd); - } - - switch (n) { - case POPEN_1: - switch (mode & (_O_RDONLY | _O_TEXT | _O_BINARY | _O_WRONLY)) { - case _O_WRONLY | _O_TEXT: - /* Case for writing to child Stdin in text mode. */ - fd1 = _open_osfhandle((Py_intptr_t)hChildStdinWrDup, mode); - f1 = _fdopen(fd1, "w"); - f = PyFile_FromFile(f1, cmdstring, "w", _PyPclose); - PyFile_SetBufSize(f, 0); - /* We don't care about these pipes anymore, so close them. */ - CloseHandle(hChildStdoutRdDup); - CloseHandle(hChildStderrRdDup); - break; - - case _O_RDONLY | _O_TEXT: - /* Case for reading from child Stdout in text mode. */ - fd1 = _open_osfhandle((Py_intptr_t)hChildStdoutRdDup, mode); - f1 = _fdopen(fd1, "r"); - f = PyFile_FromFile(f1, cmdstring, "r", _PyPclose); - PyFile_SetBufSize(f, 0); - /* We don't care about these pipes anymore, so close them. */ - CloseHandle(hChildStdinWrDup); - CloseHandle(hChildStderrRdDup); - break; - - case _O_RDONLY | _O_BINARY: - /* Case for readinig from child Stdout in binary mode. */ - fd1 = _open_osfhandle((Py_intptr_t)hChildStdoutRdDup, mode); - f1 = _fdopen(fd1, "rb"); - f = PyFile_FromFile(f1, cmdstring, "rb", _PyPclose); - PyFile_SetBufSize(f, 0); - /* We don't care about these pipes anymore, so close them. */ - CloseHandle(hChildStdinWrDup); - CloseHandle(hChildStderrRdDup); - break; - - case _O_WRONLY | _O_BINARY: - /* Case for writing to child Stdin in binary mode. */ - fd1 = _open_osfhandle((Py_intptr_t)hChildStdinWrDup, mode); - f1 = _fdopen(fd1, "wb"); - f = PyFile_FromFile(f1, cmdstring, "wb", _PyPclose); - PyFile_SetBufSize(f, 0); - /* We don't care about these pipes anymore, so close them. */ - CloseHandle(hChildStdoutRdDup); - CloseHandle(hChildStderrRdDup); - break; - } - file_count = 1; - break; - - case POPEN_2: - case POPEN_4: - { - char *m1, *m2; - PyObject *p1, *p2; - - if (mode & _O_TEXT) { - m1 = "r"; - m2 = "w"; - } else { - m1 = "rb"; - m2 = "wb"; - } - - fd1 = _open_osfhandle((Py_intptr_t)hChildStdinWrDup, mode); - f1 = _fdopen(fd1, m2); - fd2 = _open_osfhandle((Py_intptr_t)hChildStdoutRdDup, mode); - f2 = _fdopen(fd2, m1); - p1 = PyFile_FromFile(f1, cmdstring, m2, _PyPclose); - PyFile_SetBufSize(p1, 0); - p2 = PyFile_FromFile(f2, cmdstring, m1, _PyPclose); - PyFile_SetBufSize(p2, 0); - - if (n != 4) - CloseHandle(hChildStderrRdDup); - - f = PyTuple_Pack(2,p1,p2); - Py_XDECREF(p1); - Py_XDECREF(p2); - file_count = 2; - break; - } - - case POPEN_3: - { - char *m1, *m2; - PyObject *p1, *p2, *p3; - - if (mode & _O_TEXT) { - m1 = "r"; - m2 = "w"; - } else { - m1 = "rb"; - m2 = "wb"; - } - - fd1 = _open_osfhandle((Py_intptr_t)hChildStdinWrDup, mode); - f1 = _fdopen(fd1, m2); - fd2 = _open_osfhandle((Py_intptr_t)hChildStdoutRdDup, mode); - f2 = _fdopen(fd2, m1); - fd3 = _open_osfhandle((Py_intptr_t)hChildStderrRdDup, mode); - f3 = _fdopen(fd3, m1); - p1 = PyFile_FromFile(f1, cmdstring, m2, _PyPclose); - p2 = PyFile_FromFile(f2, cmdstring, m1, _PyPclose); - p3 = PyFile_FromFile(f3, cmdstring, m1, _PyPclose); - PyFile_SetBufSize(p1, 0); - PyFile_SetBufSize(p2, 0); - PyFile_SetBufSize(p3, 0); - f = PyTuple_Pack(3,p1,p2,p3); - Py_XDECREF(p1); - Py_XDECREF(p2); - Py_XDECREF(p3); - file_count = 3; - break; - } - } - - if (n == POPEN_4) { - if (!_PyPopenCreateProcess(cmdstring, - hChildStdinRd, - hChildStdoutWr, - hChildStdoutWr, - &hProcess)) - return NULL; - } - else { - if (!_PyPopenCreateProcess(cmdstring, - hChildStdinRd, - hChildStdoutWr, - hChildStderrWr, - &hProcess)) - return NULL; - } - - /* - * Insert the files we've created into the process dictionary - * all referencing the list with the process handle and the - * initial number of files (see description below in _PyPclose). - * Since if _PyPclose later tried to wait on a process when all - * handles weren't closed, it could create a deadlock with the - * child, we spend some energy here to try to ensure that we - * either insert all file handles into the dictionary or none - * at all. It's a little clumsy with the various popen modes - * and variable number of files involved. - */ - if (!_PyPopenProcs) { - _PyPopenProcs = PyDict_New(); - } - - if (_PyPopenProcs) { - PyObject *procObj, *hProcessObj, *intObj, *fileObj[3]; - int ins_rc[3]; - - fileObj[0] = fileObj[1] = fileObj[2] = NULL; - ins_rc[0] = ins_rc[1] = ins_rc[2] = 0; - - procObj = PyList_New(2); - hProcessObj = PyLong_FromVoidPtr(hProcess); - intObj = PyInt_FromLong(file_count); - - if (procObj && hProcessObj && intObj) { - PyList_SetItem(procObj,0,hProcessObj); - PyList_SetItem(procObj,1,intObj); - - fileObj[0] = PyLong_FromVoidPtr(f1); - if (fileObj[0]) { - ins_rc[0] = PyDict_SetItem(_PyPopenProcs, - fileObj[0], - procObj); - } - if (file_count >= 2) { - fileObj[1] = PyLong_FromVoidPtr(f2); - if (fileObj[1]) { - ins_rc[1] = PyDict_SetItem(_PyPopenProcs, - fileObj[1], - procObj); - } - } - if (file_count >= 3) { - fileObj[2] = PyLong_FromVoidPtr(f3); - if (fileObj[2]) { - ins_rc[2] = PyDict_SetItem(_PyPopenProcs, - fileObj[2], - procObj); - } - } - - if (ins_rc[0] < 0 || !fileObj[0] || - ins_rc[1] < 0 || (file_count > 1 && !fileObj[1]) || - ins_rc[2] < 0 || (file_count > 2 && !fileObj[2])) { - /* Something failed - remove any dictionary - * entries that did make it. - */ - if (!ins_rc[0] && fileObj[0]) { - PyDict_DelItem(_PyPopenProcs, - fileObj[0]); - } - if (!ins_rc[1] && fileObj[1]) { - PyDict_DelItem(_PyPopenProcs, - fileObj[1]); - } - if (!ins_rc[2] && fileObj[2]) { - PyDict_DelItem(_PyPopenProcs, - fileObj[2]); - } - } - } - - /* - * Clean up our localized references for the dictionary keys - * and value since PyDict_SetItem will Py_INCREF any copies - * that got placed in the dictionary. - */ - Py_XDECREF(procObj); - Py_XDECREF(fileObj[0]); - Py_XDECREF(fileObj[1]); - Py_XDECREF(fileObj[2]); - } - - /* Child is launched. Close the parents copy of those pipe - * handles that only the child should have open. You need to - * make sure that no handles to the write end of the output pipe - * are maintained in this process or else the pipe will not close - * when the child process exits and the ReadFile will hang. */ - - if (!CloseHandle(hChildStdinRd)) - return win32_error("CloseHandle", NULL); + HANDLE hChildStdinRd, hChildStdinWr, hChildStdoutRd, hChildStdoutWr, + hChildStderrRd, hChildStderrWr, hChildStdinWrDup, hChildStdoutRdDup, + hChildStderrRdDup, hProcess; /* hChildStdoutWrDup; */ + + SECURITY_ATTRIBUTES saAttr; + BOOL fSuccess; + int fd1, fd2, fd3; + FILE *f1, *f2, *f3; + long file_count; + PyObject *f; + + saAttr.nLength = sizeof(SECURITY_ATTRIBUTES); + saAttr.bInheritHandle = TRUE; + saAttr.lpSecurityDescriptor = NULL; + + if (!CreatePipe(&hChildStdinRd, &hChildStdinWr, &saAttr, 0)) + return win32_error("CreatePipe", NULL); + + /* Create new output read handle and the input write handle. Set + * the inheritance properties to FALSE. Otherwise, the child inherits + * these handles; resulting in non-closeable handles to the pipes + * being created. */ + fSuccess = DuplicateHandle(GetCurrentProcess(), hChildStdinWr, + GetCurrentProcess(), &hChildStdinWrDup, 0, + FALSE, + DUPLICATE_SAME_ACCESS); + if (!fSuccess) + return win32_error("DuplicateHandle", NULL); + + /* Close the inheritable version of ChildStdin + that we're using. */ + CloseHandle(hChildStdinWr); + + if (!CreatePipe(&hChildStdoutRd, &hChildStdoutWr, &saAttr, 0)) + return win32_error("CreatePipe", NULL); + + fSuccess = DuplicateHandle(GetCurrentProcess(), hChildStdoutRd, + GetCurrentProcess(), &hChildStdoutRdDup, 0, + FALSE, DUPLICATE_SAME_ACCESS); + if (!fSuccess) + return win32_error("DuplicateHandle", NULL); + + /* Close the inheritable version of ChildStdout + that we're using. */ + CloseHandle(hChildStdoutRd); + + if (n != POPEN_4) { + if (!CreatePipe(&hChildStderrRd, &hChildStderrWr, &saAttr, 0)) + return win32_error("CreatePipe", NULL); + fSuccess = DuplicateHandle(GetCurrentProcess(), + hChildStderrRd, + GetCurrentProcess(), + &hChildStderrRdDup, 0, + FALSE, DUPLICATE_SAME_ACCESS); + if (!fSuccess) + return win32_error("DuplicateHandle", NULL); + /* Close the inheritable version of ChildStdErr that we're using. */ + CloseHandle(hChildStderrRd); + } + + switch (n) { + case POPEN_1: + switch (mode & (_O_RDONLY | _O_TEXT | _O_BINARY | _O_WRONLY)) { + case _O_WRONLY | _O_TEXT: + /* Case for writing to child Stdin in text mode. */ + fd1 = _open_osfhandle((Py_intptr_t)hChildStdinWrDup, mode); + f1 = _fdopen(fd1, "w"); + f = PyFile_FromFile(f1, cmdstring, "w", _PyPclose); + PyFile_SetBufSize(f, 0); + /* We don't care about these pipes anymore, so close them. */ + CloseHandle(hChildStdoutRdDup); + CloseHandle(hChildStderrRdDup); + break; + + case _O_RDONLY | _O_TEXT: + /* Case for reading from child Stdout in text mode. */ + fd1 = _open_osfhandle((Py_intptr_t)hChildStdoutRdDup, mode); + f1 = _fdopen(fd1, "r"); + f = PyFile_FromFile(f1, cmdstring, "r", _PyPclose); + PyFile_SetBufSize(f, 0); + /* We don't care about these pipes anymore, so close them. */ + CloseHandle(hChildStdinWrDup); + CloseHandle(hChildStderrRdDup); + break; + + case _O_RDONLY | _O_BINARY: + /* Case for readinig from child Stdout in binary mode. */ + fd1 = _open_osfhandle((Py_intptr_t)hChildStdoutRdDup, mode); + f1 = _fdopen(fd1, "rb"); + f = PyFile_FromFile(f1, cmdstring, "rb", _PyPclose); + PyFile_SetBufSize(f, 0); + /* We don't care about these pipes anymore, so close them. */ + CloseHandle(hChildStdinWrDup); + CloseHandle(hChildStderrRdDup); + break; + + case _O_WRONLY | _O_BINARY: + /* Case for writing to child Stdin in binary mode. */ + fd1 = _open_osfhandle((Py_intptr_t)hChildStdinWrDup, mode); + f1 = _fdopen(fd1, "wb"); + f = PyFile_FromFile(f1, cmdstring, "wb", _PyPclose); + PyFile_SetBufSize(f, 0); + /* We don't care about these pipes anymore, so close them. */ + CloseHandle(hChildStdoutRdDup); + CloseHandle(hChildStderrRdDup); + break; + } + file_count = 1; + break; + + case POPEN_2: + case POPEN_4: + { + char *m1, *m2; + PyObject *p1, *p2; + + if (mode & _O_TEXT) { + m1 = "r"; + m2 = "w"; + } else { + m1 = "rb"; + m2 = "wb"; + } + + fd1 = _open_osfhandle((Py_intptr_t)hChildStdinWrDup, mode); + f1 = _fdopen(fd1, m2); + fd2 = _open_osfhandle((Py_intptr_t)hChildStdoutRdDup, mode); + f2 = _fdopen(fd2, m1); + p1 = PyFile_FromFile(f1, cmdstring, m2, _PyPclose); + PyFile_SetBufSize(p1, 0); + p2 = PyFile_FromFile(f2, cmdstring, m1, _PyPclose); + PyFile_SetBufSize(p2, 0); + + if (n != 4) + CloseHandle(hChildStderrRdDup); + + f = PyTuple_Pack(2,p1,p2); + Py_XDECREF(p1); + Py_XDECREF(p2); + file_count = 2; + break; + } + + case POPEN_3: + { + char *m1, *m2; + PyObject *p1, *p2, *p3; + + if (mode & _O_TEXT) { + m1 = "r"; + m2 = "w"; + } else { + m1 = "rb"; + m2 = "wb"; + } + + fd1 = _open_osfhandle((Py_intptr_t)hChildStdinWrDup, mode); + f1 = _fdopen(fd1, m2); + fd2 = _open_osfhandle((Py_intptr_t)hChildStdoutRdDup, mode); + f2 = _fdopen(fd2, m1); + fd3 = _open_osfhandle((Py_intptr_t)hChildStderrRdDup, mode); + f3 = _fdopen(fd3, m1); + p1 = PyFile_FromFile(f1, cmdstring, m2, _PyPclose); + p2 = PyFile_FromFile(f2, cmdstring, m1, _PyPclose); + p3 = PyFile_FromFile(f3, cmdstring, m1, _PyPclose); + PyFile_SetBufSize(p1, 0); + PyFile_SetBufSize(p2, 0); + PyFile_SetBufSize(p3, 0); + f = PyTuple_Pack(3,p1,p2,p3); + Py_XDECREF(p1); + Py_XDECREF(p2); + Py_XDECREF(p3); + file_count = 3; + break; + } + } + + if (n == POPEN_4) { + if (!_PyPopenCreateProcess(cmdstring, + hChildStdinRd, + hChildStdoutWr, + hChildStdoutWr, + &hProcess)) + return NULL; + } + else { + if (!_PyPopenCreateProcess(cmdstring, + hChildStdinRd, + hChildStdoutWr, + hChildStderrWr, + &hProcess)) + return NULL; + } + + /* + * Insert the files we've created into the process dictionary + * all referencing the list with the process handle and the + * initial number of files (see description below in _PyPclose). + * Since if _PyPclose later tried to wait on a process when all + * handles weren't closed, it could create a deadlock with the + * child, we spend some energy here to try to ensure that we + * either insert all file handles into the dictionary or none + * at all. It's a little clumsy with the various popen modes + * and variable number of files involved. + */ + if (!_PyPopenProcs) { + _PyPopenProcs = PyDict_New(); + } + + if (_PyPopenProcs) { + PyObject *procObj, *hProcessObj, *intObj, *fileObj[3]; + int ins_rc[3]; + + fileObj[0] = fileObj[1] = fileObj[2] = NULL; + ins_rc[0] = ins_rc[1] = ins_rc[2] = 0; + + procObj = PyList_New(2); + hProcessObj = PyLong_FromVoidPtr(hProcess); + intObj = PyInt_FromLong(file_count); + + if (procObj && hProcessObj && intObj) { + PyList_SetItem(procObj,0,hProcessObj); + PyList_SetItem(procObj,1,intObj); + + fileObj[0] = PyLong_FromVoidPtr(f1); + if (fileObj[0]) { + ins_rc[0] = PyDict_SetItem(_PyPopenProcs, + fileObj[0], + procObj); + } + if (file_count >= 2) { + fileObj[1] = PyLong_FromVoidPtr(f2); + if (fileObj[1]) { + ins_rc[1] = PyDict_SetItem(_PyPopenProcs, + fileObj[1], + procObj); + } + } + if (file_count >= 3) { + fileObj[2] = PyLong_FromVoidPtr(f3); + if (fileObj[2]) { + ins_rc[2] = PyDict_SetItem(_PyPopenProcs, + fileObj[2], + procObj); + } + } + + if (ins_rc[0] < 0 || !fileObj[0] || + ins_rc[1] < 0 || (file_count > 1 && !fileObj[1]) || + ins_rc[2] < 0 || (file_count > 2 && !fileObj[2])) { + /* Something failed - remove any dictionary + * entries that did make it. + */ + if (!ins_rc[0] && fileObj[0]) { + PyDict_DelItem(_PyPopenProcs, + fileObj[0]); + } + if (!ins_rc[1] && fileObj[1]) { + PyDict_DelItem(_PyPopenProcs, + fileObj[1]); + } + if (!ins_rc[2] && fileObj[2]) { + PyDict_DelItem(_PyPopenProcs, + fileObj[2]); + } + } + } + + /* + * Clean up our localized references for the dictionary keys + * and value since PyDict_SetItem will Py_INCREF any copies + * that got placed in the dictionary. + */ + Py_XDECREF(procObj); + Py_XDECREF(fileObj[0]); + Py_XDECREF(fileObj[1]); + Py_XDECREF(fileObj[2]); + } + + /* Child is launched. Close the parents copy of those pipe + * handles that only the child should have open. You need to + * make sure that no handles to the write end of the output pipe + * are maintained in this process or else the pipe will not close + * when the child process exits and the ReadFile will hang. */ + + if (!CloseHandle(hChildStdinRd)) + return win32_error("CloseHandle", NULL); - if (!CloseHandle(hChildStdoutWr)) - return win32_error("CloseHandle", NULL); + if (!CloseHandle(hChildStdoutWr)) + return win32_error("CloseHandle", NULL); - if ((n != 4) && (!CloseHandle(hChildStderrWr))) - return win32_error("CloseHandle", NULL); + if ((n != 4) && (!CloseHandle(hChildStderrWr))) + return win32_error("CloseHandle", NULL); - return f; + return f; } /* @@ -5450,110 +5450,110 @@ static int _PyPclose(FILE *file) { - int result; - DWORD exit_code; - HANDLE hProcess; - PyObject *procObj, *hProcessObj, *intObj, *fileObj; - long file_count; + int result; + DWORD exit_code; + HANDLE hProcess; + PyObject *procObj, *hProcessObj, *intObj, *fileObj; + long file_count; #ifdef WITH_THREAD - PyGILState_STATE state; + PyGILState_STATE state; #endif - /* Close the file handle first, to ensure it can't block the - * child from exiting if it's the last handle. - */ - result = fclose(file); + /* Close the file handle first, to ensure it can't block the + * child from exiting if it's the last handle. + */ + result = fclose(file); #ifdef WITH_THREAD - state = PyGILState_Ensure(); + state = PyGILState_Ensure(); #endif - if (_PyPopenProcs) { - if ((fileObj = PyLong_FromVoidPtr(file)) != NULL && - (procObj = PyDict_GetItem(_PyPopenProcs, - fileObj)) != NULL && - (hProcessObj = PyList_GetItem(procObj,0)) != NULL && - (intObj = PyList_GetItem(procObj,1)) != NULL) { - - hProcess = PyLong_AsVoidPtr(hProcessObj); - file_count = PyInt_AsLong(intObj); - - if (file_count > 1) { - /* Still other files referencing process */ - file_count--; - PyList_SetItem(procObj,1, - PyInt_FromLong(file_count)); - } else { - /* Last file for this process */ - if (result != EOF && - WaitForSingleObject(hProcess, INFINITE) != WAIT_FAILED && - GetExitCodeProcess(hProcess, &exit_code)) { - /* Possible truncation here in 16-bit environments, but - * real exit codes are just the lower byte in any event. - */ - result = exit_code; - } else { - /* Indicate failure - this will cause the file object - * to raise an I/O error and translate the last Win32 - * error code from errno. We do have a problem with - * last errors that overlap the normal errno table, - * but that's a consistent problem with the file object. - */ - if (result != EOF) { - /* If the error wasn't from the fclose(), then - * set errno for the file object error handling. - */ - errno = GetLastError(); - } - result = -1; - } - - /* Free up the native handle at this point */ - CloseHandle(hProcess); - } - - /* Remove this file pointer from dictionary */ - PyDict_DelItem(_PyPopenProcs, fileObj); - - if (PyDict_Size(_PyPopenProcs) == 0) { - Py_DECREF(_PyPopenProcs); - _PyPopenProcs = NULL; - } + if (_PyPopenProcs) { + if ((fileObj = PyLong_FromVoidPtr(file)) != NULL && + (procObj = PyDict_GetItem(_PyPopenProcs, + fileObj)) != NULL && + (hProcessObj = PyList_GetItem(procObj,0)) != NULL && + (intObj = PyList_GetItem(procObj,1)) != NULL) { + + hProcess = PyLong_AsVoidPtr(hProcessObj); + file_count = PyInt_AsLong(intObj); + + if (file_count > 1) { + /* Still other files referencing process */ + file_count--; + PyList_SetItem(procObj,1, + PyInt_FromLong(file_count)); + } else { + /* Last file for this process */ + if (result != EOF && + WaitForSingleObject(hProcess, INFINITE) != WAIT_FAILED && + GetExitCodeProcess(hProcess, &exit_code)) { + /* Possible truncation here in 16-bit environments, but + * real exit codes are just the lower byte in any event. + */ + result = exit_code; + } else { + /* Indicate failure - this will cause the file object + * to raise an I/O error and translate the last Win32 + * error code from errno. We do have a problem with + * last errors that overlap the normal errno table, + * but that's a consistent problem with the file object. + */ + if (result != EOF) { + /* If the error wasn't from the fclose(), then + * set errno for the file object error handling. + */ + errno = GetLastError(); + } + result = -1; + } + + /* Free up the native handle at this point */ + CloseHandle(hProcess); + } - } /* if object retrieval ok */ + /* Remove this file pointer from dictionary */ + PyDict_DelItem(_PyPopenProcs, fileObj); - Py_XDECREF(fileObj); - } /* if _PyPopenProcs */ + if (PyDict_Size(_PyPopenProcs) == 0) { + Py_DECREF(_PyPopenProcs); + _PyPopenProcs = NULL; + } + + } /* if object retrieval ok */ + + Py_XDECREF(fileObj); + } /* if _PyPopenProcs */ #ifdef WITH_THREAD - PyGILState_Release(state); + PyGILState_Release(state); #endif - return result; + return result; } #else /* which OS? */ static PyObject * posix_popen(PyObject *self, PyObject *args) { - char *name; - char *mode = "r"; - int bufsize = -1; - FILE *fp; - PyObject *f; - if (!PyArg_ParseTuple(args, "s|si:popen", &name, &mode, &bufsize)) - return NULL; - /* Strip mode of binary or text modifiers */ - if (strcmp(mode, "rb") == 0 || strcmp(mode, "rt") == 0) - mode = "r"; - else if (strcmp(mode, "wb") == 0 || strcmp(mode, "wt") == 0) - mode = "w"; - Py_BEGIN_ALLOW_THREADS - fp = popen(name, mode); - Py_END_ALLOW_THREADS - if (fp == NULL) - return posix_error(); - f = PyFile_FromFile(fp, name, mode, pclose); - if (f != NULL) - PyFile_SetBufSize(f, bufsize); - return f; + char *name; + char *mode = "r"; + int bufsize = -1; + FILE *fp; + PyObject *f; + if (!PyArg_ParseTuple(args, "s|si:popen", &name, &mode, &bufsize)) + return NULL; + /* Strip mode of binary or text modifiers */ + if (strcmp(mode, "rb") == 0 || strcmp(mode, "rt") == 0) + mode = "r"; + else if (strcmp(mode, "wb") == 0 || strcmp(mode, "wt") == 0) + mode = "w"; + Py_BEGIN_ALLOW_THREADS + fp = popen(name, mode); + Py_END_ALLOW_THREADS + if (fp == NULL) + return posix_error(); + f = PyFile_FromFile(fp, name, mode, pclose); + if (f != NULL) + PyFile_SetBufSize(f, bufsize); + return f; } #endif /* PYOS_??? */ @@ -5568,19 +5568,19 @@ static PyObject * posix_setuid(PyObject *self, PyObject *args) { - long uid_arg; - uid_t uid; - if (!PyArg_ParseTuple(args, "l:setuid", &uid_arg)) - return NULL; - uid = uid_arg; - if (uid != uid_arg) { - PyErr_SetString(PyExc_OverflowError, "user id too big"); - return NULL; - } - if (setuid(uid) < 0) - return posix_error(); - Py_INCREF(Py_None); - return Py_None; + long uid_arg; + uid_t uid; + if (!PyArg_ParseTuple(args, "l:setuid", &uid_arg)) + return NULL; + uid = uid_arg; + if (uid != uid_arg) { + PyErr_SetString(PyExc_OverflowError, "user id too big"); + return NULL; + } + if (setuid(uid) < 0) + return posix_error(); + Py_INCREF(Py_None); + return Py_None; } #endif /* HAVE_SETUID */ @@ -5593,21 +5593,21 @@ static PyObject * posix_seteuid (PyObject *self, PyObject *args) { - long euid_arg; - uid_t euid; - if (!PyArg_ParseTuple(args, "l", &euid_arg)) - return NULL; - euid = euid_arg; - if (euid != euid_arg) { - PyErr_SetString(PyExc_OverflowError, "user id too big"); - return NULL; - } - if (seteuid(euid) < 0) { - return posix_error(); - } else { - Py_INCREF(Py_None); - return Py_None; - } + long euid_arg; + uid_t euid; + if (!PyArg_ParseTuple(args, "l", &euid_arg)) + return NULL; + euid = euid_arg; + if (euid != euid_arg) { + PyErr_SetString(PyExc_OverflowError, "user id too big"); + return NULL; + } + if (seteuid(euid) < 0) { + return posix_error(); + } else { + Py_INCREF(Py_None); + return Py_None; + } } #endif /* HAVE_SETEUID */ @@ -5619,21 +5619,21 @@ static PyObject * posix_setegid (PyObject *self, PyObject *args) { - long egid_arg; - gid_t egid; - if (!PyArg_ParseTuple(args, "l", &egid_arg)) - return NULL; - egid = egid_arg; - if (egid != egid_arg) { - PyErr_SetString(PyExc_OverflowError, "group id too big"); - return NULL; - } - if (setegid(egid) < 0) { - return posix_error(); - } else { - Py_INCREF(Py_None); - return Py_None; - } + long egid_arg; + gid_t egid; + if (!PyArg_ParseTuple(args, "l", &egid_arg)) + return NULL; + egid = egid_arg; + if (egid != egid_arg) { + PyErr_SetString(PyExc_OverflowError, "group id too big"); + return NULL; + } + if (setegid(egid) < 0) { + return posix_error(); + } else { + Py_INCREF(Py_None); + return Py_None; + } } #endif /* HAVE_SETEGID */ @@ -5645,29 +5645,29 @@ static PyObject * posix_setreuid (PyObject *self, PyObject *args) { - long ruid_arg, euid_arg; - uid_t ruid, euid; - if (!PyArg_ParseTuple(args, "ll", &ruid_arg, &euid_arg)) - return NULL; - if (ruid_arg == -1) - ruid = (uid_t)-1; /* let the compiler choose how -1 fits */ - else - ruid = ruid_arg; /* otherwise, assign from our long */ - if (euid_arg == -1) - euid = (uid_t)-1; - else - euid = euid_arg; - if ((euid_arg != -1 && euid != euid_arg) || - (ruid_arg != -1 && ruid != ruid_arg)) { - PyErr_SetString(PyExc_OverflowError, "user id too big"); - return NULL; - } - if (setreuid(ruid, euid) < 0) { - return posix_error(); - } else { - Py_INCREF(Py_None); - return Py_None; - } + long ruid_arg, euid_arg; + uid_t ruid, euid; + if (!PyArg_ParseTuple(args, "ll", &ruid_arg, &euid_arg)) + return NULL; + if (ruid_arg == -1) + ruid = (uid_t)-1; /* let the compiler choose how -1 fits */ + else + ruid = ruid_arg; /* otherwise, assign from our long */ + if (euid_arg == -1) + euid = (uid_t)-1; + else + euid = euid_arg; + if ((euid_arg != -1 && euid != euid_arg) || + (ruid_arg != -1 && ruid != ruid_arg)) { + PyErr_SetString(PyExc_OverflowError, "user id too big"); + return NULL; + } + if (setreuid(ruid, euid) < 0) { + return posix_error(); + } else { + Py_INCREF(Py_None); + return Py_None; + } } #endif /* HAVE_SETREUID */ @@ -5679,29 +5679,29 @@ static PyObject * posix_setregid (PyObject *self, PyObject *args) { - long rgid_arg, egid_arg; - gid_t rgid, egid; - if (!PyArg_ParseTuple(args, "ll", &rgid_arg, &egid_arg)) - return NULL; - if (rgid_arg == -1) - rgid = (gid_t)-1; /* let the compiler choose how -1 fits */ - else - rgid = rgid_arg; /* otherwise, assign from our long */ - if (egid_arg == -1) - egid = (gid_t)-1; - else - egid = egid_arg; - if ((egid_arg != -1 && egid != egid_arg) || - (rgid_arg != -1 && rgid != rgid_arg)) { - PyErr_SetString(PyExc_OverflowError, "group id too big"); - return NULL; - } - if (setregid(rgid, egid) < 0) { - return posix_error(); - } else { - Py_INCREF(Py_None); - return Py_None; - } + long rgid_arg, egid_arg; + gid_t rgid, egid; + if (!PyArg_ParseTuple(args, "ll", &rgid_arg, &egid_arg)) + return NULL; + if (rgid_arg == -1) + rgid = (gid_t)-1; /* let the compiler choose how -1 fits */ + else + rgid = rgid_arg; /* otherwise, assign from our long */ + if (egid_arg == -1) + egid = (gid_t)-1; + else + egid = egid_arg; + if ((egid_arg != -1 && egid != egid_arg) || + (rgid_arg != -1 && rgid != rgid_arg)) { + PyErr_SetString(PyExc_OverflowError, "group id too big"); + return NULL; + } + if (setregid(rgid, egid) < 0) { + return posix_error(); + } else { + Py_INCREF(Py_None); + return Py_None; + } } #endif /* HAVE_SETREGID */ @@ -5713,19 +5713,19 @@ static PyObject * posix_setgid(PyObject *self, PyObject *args) { - long gid_arg; - gid_t gid; - if (!PyArg_ParseTuple(args, "l:setgid", &gid_arg)) - return NULL; - gid = gid_arg; - if (gid != gid_arg) { - PyErr_SetString(PyExc_OverflowError, "group id too big"); - return NULL; - } - if (setgid(gid) < 0) - return posix_error(); - Py_INCREF(Py_None); - return Py_None; + long gid_arg; + gid_t gid; + if (!PyArg_ParseTuple(args, "l:setgid", &gid_arg)) + return NULL; + gid = gid_arg; + if (gid != gid_arg) { + PyErr_SetString(PyExc_OverflowError, "group id too big"); + return NULL; + } + if (setgid(gid) < 0) + return posix_error(); + Py_INCREF(Py_None); + return Py_None; } #endif /* HAVE_SETGID */ @@ -5737,63 +5737,63 @@ static PyObject * posix_setgroups(PyObject *self, PyObject *groups) { - int i, len; - gid_t grouplist[MAX_GROUPS]; + int i, len; + gid_t grouplist[MAX_GROUPS]; - if (!PySequence_Check(groups)) { - PyErr_SetString(PyExc_TypeError, "setgroups argument must be a sequence"); - return NULL; - } - len = PySequence_Size(groups); - if (len > MAX_GROUPS) { - PyErr_SetString(PyExc_ValueError, "too many groups"); - return NULL; - } - for(i = 0; i < len; i++) { - PyObject *elem; - elem = PySequence_GetItem(groups, i); - if (!elem) - return NULL; - if (!PyInt_Check(elem)) { - if (!PyLong_Check(elem)) { - PyErr_SetString(PyExc_TypeError, - "groups must be integers"); - Py_DECREF(elem); - return NULL; - } else { - unsigned long x = PyLong_AsUnsignedLong(elem); - if (PyErr_Occurred()) { - PyErr_SetString(PyExc_TypeError, - "group id too big"); - Py_DECREF(elem); - return NULL; - } - grouplist[i] = x; - /* read back to see if it fits in gid_t */ - if (grouplist[i] != x) { - PyErr_SetString(PyExc_TypeError, - "group id too big"); - Py_DECREF(elem); - return NULL; - } - } - } else { - long x = PyInt_AsLong(elem); - grouplist[i] = x; - if (grouplist[i] != x) { - PyErr_SetString(PyExc_TypeError, - "group id too big"); - Py_DECREF(elem); - return NULL; - } - } - Py_DECREF(elem); - } - - if (setgroups(len, grouplist) < 0) - return posix_error(); - Py_INCREF(Py_None); - return Py_None; + if (!PySequence_Check(groups)) { + PyErr_SetString(PyExc_TypeError, "setgroups argument must be a sequence"); + return NULL; + } + len = PySequence_Size(groups); + if (len > MAX_GROUPS) { + PyErr_SetString(PyExc_ValueError, "too many groups"); + return NULL; + } + for(i = 0; i < len; i++) { + PyObject *elem; + elem = PySequence_GetItem(groups, i); + if (!elem) + return NULL; + if (!PyInt_Check(elem)) { + if (!PyLong_Check(elem)) { + PyErr_SetString(PyExc_TypeError, + "groups must be integers"); + Py_DECREF(elem); + return NULL; + } else { + unsigned long x = PyLong_AsUnsignedLong(elem); + if (PyErr_Occurred()) { + PyErr_SetString(PyExc_TypeError, + "group id too big"); + Py_DECREF(elem); + return NULL; + } + grouplist[i] = x; + /* read back to see if it fits in gid_t */ + if (grouplist[i] != x) { + PyErr_SetString(PyExc_TypeError, + "group id too big"); + Py_DECREF(elem); + return NULL; + } + } + } else { + long x = PyInt_AsLong(elem); + grouplist[i] = x; + if (grouplist[i] != x) { + PyErr_SetString(PyExc_TypeError, + "group id too big"); + Py_DECREF(elem); + return NULL; + } + } + Py_DECREF(elem); + } + + if (setgroups(len, grouplist) < 0) + return posix_error(); + Py_INCREF(Py_None); + return Py_None; } #endif /* HAVE_SETGROUPS */ @@ -5801,59 +5801,59 @@ static PyObject * wait_helper(pid_t pid, int status, struct rusage *ru) { - PyObject *result; - static PyObject *struct_rusage; + PyObject *result; + static PyObject *struct_rusage; + + if (pid == -1) + return posix_error(); - if (pid == -1) - return posix_error(); + if (struct_rusage == NULL) { + PyObject *m = PyImport_ImportModuleNoBlock("resource"); + if (m == NULL) + return NULL; + struct_rusage = PyObject_GetAttrString(m, "struct_rusage"); + Py_DECREF(m); + if (struct_rusage == NULL) + return NULL; + } - if (struct_rusage == NULL) { - PyObject *m = PyImport_ImportModuleNoBlock("resource"); - if (m == NULL) - return NULL; - struct_rusage = PyObject_GetAttrString(m, "struct_rusage"); - Py_DECREF(m); - if (struct_rusage == NULL) - return NULL; - } - - /* XXX(nnorwitz): Copied (w/mods) from resource.c, there should be only one. */ - result = PyStructSequence_New((PyTypeObject*) struct_rusage); - if (!result) - return NULL; + /* XXX(nnorwitz): Copied (w/mods) from resource.c, there should be only one. */ + result = PyStructSequence_New((PyTypeObject*) struct_rusage); + if (!result) + return NULL; #ifndef doubletime #define doubletime(TV) ((double)(TV).tv_sec + (TV).tv_usec * 0.000001) #endif - PyStructSequence_SET_ITEM(result, 0, - PyFloat_FromDouble(doubletime(ru->ru_utime))); - PyStructSequence_SET_ITEM(result, 1, - PyFloat_FromDouble(doubletime(ru->ru_stime))); + PyStructSequence_SET_ITEM(result, 0, + PyFloat_FromDouble(doubletime(ru->ru_utime))); + PyStructSequence_SET_ITEM(result, 1, + PyFloat_FromDouble(doubletime(ru->ru_stime))); #define SET_INT(result, index, value)\ - PyStructSequence_SET_ITEM(result, index, PyInt_FromLong(value)) - SET_INT(result, 2, ru->ru_maxrss); - SET_INT(result, 3, ru->ru_ixrss); - SET_INT(result, 4, ru->ru_idrss); - SET_INT(result, 5, ru->ru_isrss); - SET_INT(result, 6, ru->ru_minflt); - SET_INT(result, 7, ru->ru_majflt); - SET_INT(result, 8, ru->ru_nswap); - SET_INT(result, 9, ru->ru_inblock); - SET_INT(result, 10, ru->ru_oublock); - SET_INT(result, 11, ru->ru_msgsnd); - SET_INT(result, 12, ru->ru_msgrcv); - SET_INT(result, 13, ru->ru_nsignals); - SET_INT(result, 14, ru->ru_nvcsw); - SET_INT(result, 15, ru->ru_nivcsw); + PyStructSequence_SET_ITEM(result, index, PyInt_FromLong(value)) + SET_INT(result, 2, ru->ru_maxrss); + SET_INT(result, 3, ru->ru_ixrss); + SET_INT(result, 4, ru->ru_idrss); + SET_INT(result, 5, ru->ru_isrss); + SET_INT(result, 6, ru->ru_minflt); + SET_INT(result, 7, ru->ru_majflt); + SET_INT(result, 8, ru->ru_nswap); + SET_INT(result, 9, ru->ru_inblock); + SET_INT(result, 10, ru->ru_oublock); + SET_INT(result, 11, ru->ru_msgsnd); + SET_INT(result, 12, ru->ru_msgrcv); + SET_INT(result, 13, ru->ru_nsignals); + SET_INT(result, 14, ru->ru_nvcsw); + SET_INT(result, 15, ru->ru_nivcsw); #undef SET_INT - if (PyErr_Occurred()) { - Py_DECREF(result); - return NULL; - } + if (PyErr_Occurred()) { + Py_DECREF(result); + return NULL; + } - return Py_BuildValue("NiN", PyLong_FromPid(pid), status, result); + return Py_BuildValue("NiN", PyLong_FromPid(pid), status, result); } #endif /* HAVE_WAIT3 || HAVE_WAIT4 */ @@ -5865,20 +5865,20 @@ static PyObject * posix_wait3(PyObject *self, PyObject *args) { - pid_t pid; - int options; - struct rusage ru; - WAIT_TYPE status; - WAIT_STATUS_INT(status) = 0; - - if (!PyArg_ParseTuple(args, "i:wait3", &options)) - return NULL; - - Py_BEGIN_ALLOW_THREADS - pid = wait3(&status, options, &ru); - Py_END_ALLOW_THREADS + pid_t pid; + int options; + struct rusage ru; + WAIT_TYPE status; + WAIT_STATUS_INT(status) = 0; + + if (!PyArg_ParseTuple(args, "i:wait3", &options)) + return NULL; + + Py_BEGIN_ALLOW_THREADS + pid = wait3(&status, options, &ru); + Py_END_ALLOW_THREADS - return wait_helper(pid, WAIT_STATUS_INT(status), &ru); + return wait_helper(pid, WAIT_STATUS_INT(status), &ru); } #endif /* HAVE_WAIT3 */ @@ -5890,20 +5890,20 @@ static PyObject * posix_wait4(PyObject *self, PyObject *args) { - pid_t pid; - int options; - struct rusage ru; - WAIT_TYPE status; - WAIT_STATUS_INT(status) = 0; - - if (!PyArg_ParseTuple(args, PARSE_PID "i:wait4", &pid, &options)) - return NULL; - - Py_BEGIN_ALLOW_THREADS - pid = wait4(pid, &status, options, &ru); - Py_END_ALLOW_THREADS + pid_t pid; + int options; + struct rusage ru; + WAIT_TYPE status; + WAIT_STATUS_INT(status) = 0; + + if (!PyArg_ParseTuple(args, PARSE_PID "i:wait4", &pid, &options)) + return NULL; + + Py_BEGIN_ALLOW_THREADS + pid = wait4(pid, &status, options, &ru); + Py_END_ALLOW_THREADS - return wait_helper(pid, WAIT_STATUS_INT(status), &ru); + return wait_helper(pid, WAIT_STATUS_INT(status), &ru); } #endif /* HAVE_WAIT4 */ @@ -5915,20 +5915,20 @@ static PyObject * posix_waitpid(PyObject *self, PyObject *args) { - pid_t pid; - int options; - WAIT_TYPE status; - WAIT_STATUS_INT(status) = 0; - - if (!PyArg_ParseTuple(args, PARSE_PID "i:waitpid", &pid, &options)) - return NULL; - Py_BEGIN_ALLOW_THREADS - pid = waitpid(pid, &status, options); - Py_END_ALLOW_THREADS - if (pid == -1) - return posix_error(); + pid_t pid; + int options; + WAIT_TYPE status; + WAIT_STATUS_INT(status) = 0; + + if (!PyArg_ParseTuple(args, PARSE_PID "i:waitpid", &pid, &options)) + return NULL; + Py_BEGIN_ALLOW_THREADS + pid = waitpid(pid, &status, options); + Py_END_ALLOW_THREADS + if (pid == -1) + return posix_error(); - return Py_BuildValue("Ni", PyLong_FromPid(pid), WAIT_STATUS_INT(status)); + return Py_BuildValue("Ni", PyLong_FromPid(pid), WAIT_STATUS_INT(status)); } #elif defined(HAVE_CWAIT) @@ -5941,19 +5941,19 @@ static PyObject * posix_waitpid(PyObject *self, PyObject *args) { - Py_intptr_t pid; - int status, options; + Py_intptr_t pid; + int status, options; - if (!PyArg_ParseTuple(args, PARSE_PID "i:waitpid", &pid, &options)) - return NULL; - Py_BEGIN_ALLOW_THREADS - pid = _cwait(&status, pid, options); - Py_END_ALLOW_THREADS - if (pid == -1) - return posix_error(); + if (!PyArg_ParseTuple(args, PARSE_PID "i:waitpid", &pid, &options)) + return NULL; + Py_BEGIN_ALLOW_THREADS + pid = _cwait(&status, pid, options); + Py_END_ALLOW_THREADS + if (pid == -1) + return posix_error(); - /* shift the status left a byte so this is more like the POSIX waitpid */ - return Py_BuildValue("Ni", PyLong_FromPid(pid), status << 8); + /* shift the status left a byte so this is more like the POSIX waitpid */ + return Py_BuildValue("Ni", PyLong_FromPid(pid), status << 8); } #endif /* HAVE_WAITPID || HAVE_CWAIT */ @@ -5965,17 +5965,17 @@ static PyObject * posix_wait(PyObject *self, PyObject *noargs) { - pid_t pid; - WAIT_TYPE status; - WAIT_STATUS_INT(status) = 0; - - Py_BEGIN_ALLOW_THREADS - pid = wait(&status); - Py_END_ALLOW_THREADS - if (pid == -1) - return posix_error(); + pid_t pid; + WAIT_TYPE status; + WAIT_STATUS_INT(status) = 0; + + Py_BEGIN_ALLOW_THREADS + pid = wait(&status); + Py_END_ALLOW_THREADS + if (pid == -1) + return posix_error(); - return Py_BuildValue("Ni", PyLong_FromPid(pid), WAIT_STATUS_INT(status)); + return Py_BuildValue("Ni", PyLong_FromPid(pid), WAIT_STATUS_INT(status)); } #endif @@ -5988,12 +5988,12 @@ posix_lstat(PyObject *self, PyObject *args) { #ifdef HAVE_LSTAT - return posix_do_stat(self, args, "et:lstat", lstat, NULL, NULL); + return posix_do_stat(self, args, "et:lstat", lstat, NULL, NULL); #else /* !HAVE_LSTAT */ #ifdef MS_WINDOWS - return posix_do_stat(self, args, "et:lstat", STAT, "U:lstat", win32_wstat); + return posix_do_stat(self, args, "et:lstat", STAT, "U:lstat", win32_wstat); #else - return posix_do_stat(self, args, "et:lstat", STAT, NULL, NULL); + return posix_do_stat(self, args, "et:lstat", STAT, NULL, NULL); #endif #endif /* !HAVE_LSTAT */ } @@ -6007,57 +6007,57 @@ static PyObject * posix_readlink(PyObject *self, PyObject *args) { - PyObject* v; - char buf[MAXPATHLEN]; - char *path; - int n; + PyObject* v; + char buf[MAXPATHLEN]; + char *path; + int n; #ifdef Py_USING_UNICODE - int arg_is_unicode = 0; + int arg_is_unicode = 0; #endif - if (!PyArg_ParseTuple(args, "et:readlink", - Py_FileSystemDefaultEncoding, &path)) - return NULL; + if (!PyArg_ParseTuple(args, "et:readlink", + Py_FileSystemDefaultEncoding, &path)) + return NULL; #ifdef Py_USING_UNICODE - v = PySequence_GetItem(args, 0); - if (v == NULL) { - PyMem_Free(path); - return NULL; - } - - if (PyUnicode_Check(v)) { - arg_is_unicode = 1; - } - Py_DECREF(v); -#endif - - Py_BEGIN_ALLOW_THREADS - n = readlink(path, buf, (int) sizeof buf); - Py_END_ALLOW_THREADS - if (n < 0) - return posix_error_with_allocated_filename(path); + v = PySequence_GetItem(args, 0); + if (v == NULL) { + PyMem_Free(path); + return NULL; + } + + if (PyUnicode_Check(v)) { + arg_is_unicode = 1; + } + Py_DECREF(v); +#endif + + Py_BEGIN_ALLOW_THREADS + n = readlink(path, buf, (int) sizeof buf); + Py_END_ALLOW_THREADS + if (n < 0) + return posix_error_with_allocated_filename(path); - PyMem_Free(path); - v = PyString_FromStringAndSize(buf, n); + PyMem_Free(path); + v = PyString_FromStringAndSize(buf, n); #ifdef Py_USING_UNICODE - if (arg_is_unicode) { - PyObject *w; + if (arg_is_unicode) { + PyObject *w; - w = PyUnicode_FromEncodedObject(v, - Py_FileSystemDefaultEncoding, - "strict"); - if (w != NULL) { - Py_DECREF(v); - v = w; - } - else { - /* fall back to the original byte string, as - discussed in patch #683592 */ - PyErr_Clear(); - } - } + w = PyUnicode_FromEncodedObject(v, + Py_FileSystemDefaultEncoding, + "strict"); + if (w != NULL) { + Py_DECREF(v); + v = w; + } + else { + /* fall back to the original byte string, as + discussed in patch #683592 */ + PyErr_Clear(); + } + } #endif - return v; + return v; } #endif /* HAVE_READLINK */ @@ -6070,7 +6070,7 @@ static PyObject * posix_symlink(PyObject *self, PyObject *args) { - return posix_2str(args, "etet:symlink", symlink); + return posix_2str(args, "etet:symlink", symlink); } #endif /* HAVE_SYMLINK */ @@ -6093,12 +6093,12 @@ posix_times(PyObject *self, PyObject *noargs) { /* Currently Only Uptime is Provided -- Others Later */ - return Py_BuildValue("ddddd", - (double)0 /* t.tms_utime / HZ */, - (double)0 /* t.tms_stime / HZ */, - (double)0 /* t.tms_cutime / HZ */, - (double)0 /* t.tms_cstime / HZ */, - (double)system_uptime() / 1000); + return Py_BuildValue("ddddd", + (double)0 /* t.tms_utime / HZ */, + (double)0 /* t.tms_stime / HZ */, + (double)0 /* t.tms_cutime / HZ */, + (double)0 /* t.tms_cstime / HZ */, + (double)system_uptime() / 1000); } #else /* not OS2 */ #define NEED_TICKS_PER_SECOND @@ -6106,46 +6106,46 @@ static PyObject * posix_times(PyObject *self, PyObject *noargs) { - struct tms t; - clock_t c; - errno = 0; - c = times(&t); - if (c == (clock_t) -1) - return posix_error(); - return Py_BuildValue("ddddd", - (double)t.tms_utime / ticks_per_second, - (double)t.tms_stime / ticks_per_second, - (double)t.tms_cutime / ticks_per_second, - (double)t.tms_cstime / ticks_per_second, - (double)c / ticks_per_second); + struct tms t; + clock_t c; + errno = 0; + c = times(&t); + if (c == (clock_t) -1) + return posix_error(); + return Py_BuildValue("ddddd", + (double)t.tms_utime / ticks_per_second, + (double)t.tms_stime / ticks_per_second, + (double)t.tms_cutime / ticks_per_second, + (double)t.tms_cstime / ticks_per_second, + (double)c / ticks_per_second); } #endif /* not OS2 */ #endif /* HAVE_TIMES */ #ifdef MS_WINDOWS -#define HAVE_TIMES /* so the method table will pick it up */ +#define HAVE_TIMES /* so the method table will pick it up */ static PyObject * posix_times(PyObject *self, PyObject *noargs) { - FILETIME create, exit, kernel, user; - HANDLE hProc; - hProc = GetCurrentProcess(); - GetProcessTimes(hProc, &create, &exit, &kernel, &user); - /* The fields of a FILETIME structure are the hi and lo part - of a 64-bit value expressed in 100 nanosecond units. - 1e7 is one second in such units; 1e-7 the inverse. - 429.4967296 is 2**32 / 1e7 or 2**32 * 1e-7. - */ - return Py_BuildValue( - "ddddd", - (double)(user.dwHighDateTime*429.4967296 + - user.dwLowDateTime*1e-7), - (double)(kernel.dwHighDateTime*429.4967296 + - kernel.dwLowDateTime*1e-7), - (double)0, - (double)0, - (double)0); + FILETIME create, exit, kernel, user; + HANDLE hProc; + hProc = GetCurrentProcess(); + GetProcessTimes(hProc, &create, &exit, &kernel, &user); + /* The fields of a FILETIME structure are the hi and lo part + of a 64-bit value expressed in 100 nanosecond units. + 1e7 is one second in such units; 1e-7 the inverse. + 429.4967296 is 2**32 / 1e7 or 2**32 * 1e-7. + */ + return Py_BuildValue( + "ddddd", + (double)(user.dwHighDateTime*429.4967296 + + user.dwLowDateTime*1e-7), + (double)(kernel.dwHighDateTime*429.4967296 + + kernel.dwLowDateTime*1e-7), + (double)0, + (double)0, + (double)0); } #endif /* MS_WINDOWS */ @@ -6164,14 +6164,14 @@ static PyObject * posix_getsid(PyObject *self, PyObject *args) { - pid_t pid; - int sid; - if (!PyArg_ParseTuple(args, PARSE_PID ":getsid", &pid)) - return NULL; - sid = getsid(pid); - if (sid < 0) - return posix_error(); - return PyInt_FromLong((long)sid); + pid_t pid; + int sid; + if (!PyArg_ParseTuple(args, PARSE_PID ":getsid", &pid)) + return NULL; + sid = getsid(pid); + if (sid < 0) + return posix_error(); + return PyInt_FromLong((long)sid); } #endif /* HAVE_GETSID */ @@ -6184,10 +6184,10 @@ static PyObject * posix_setsid(PyObject *self, PyObject *noargs) { - if (setsid() < 0) - return posix_error(); - Py_INCREF(Py_None); - return Py_None; + if (setsid() < 0) + return posix_error(); + Py_INCREF(Py_None); + return Py_None; } #endif /* HAVE_SETSID */ @@ -6199,14 +6199,14 @@ static PyObject * posix_setpgid(PyObject *self, PyObject *args) { - pid_t pid; - int pgrp; - if (!PyArg_ParseTuple(args, PARSE_PID "i:setpgid", &pid, &pgrp)) - return NULL; - if (setpgid(pid, pgrp) < 0) - return posix_error(); - Py_INCREF(Py_None); - return Py_None; + pid_t pid; + int pgrp; + if (!PyArg_ParseTuple(args, PARSE_PID "i:setpgid", &pid, &pgrp)) + return NULL; + if (setpgid(pid, pgrp) < 0) + return posix_error(); + Py_INCREF(Py_None); + return Py_None; } #endif /* HAVE_SETPGID */ @@ -6219,14 +6219,14 @@ static PyObject * posix_tcgetpgrp(PyObject *self, PyObject *args) { - int fd; - pid_t pgid; - if (!PyArg_ParseTuple(args, "i:tcgetpgrp", &fd)) - return NULL; - pgid = tcgetpgrp(fd); - if (pgid < 0) - return posix_error(); - return PyLong_FromPid(pgid); + int fd; + pid_t pgid; + if (!PyArg_ParseTuple(args, "i:tcgetpgrp", &fd)) + return NULL; + pgid = tcgetpgrp(fd); + if (pgid < 0) + return posix_error(); + return PyLong_FromPid(pgid); } #endif /* HAVE_TCGETPGRP */ @@ -6239,14 +6239,14 @@ static PyObject * posix_tcsetpgrp(PyObject *self, PyObject *args) { - int fd; - pid_t pgid; - if (!PyArg_ParseTuple(args, "i" PARSE_PID ":tcsetpgrp", &fd, &pgid)) - return NULL; - if (tcsetpgrp(fd, pgid) < 0) - return posix_error(); - Py_INCREF(Py_None); - return Py_None; + int fd; + pid_t pgid; + if (!PyArg_ParseTuple(args, "i" PARSE_PID ":tcsetpgrp", &fd, &pgid)) + return NULL; + if (tcsetpgrp(fd, pgid) < 0) + return posix_error(); + Py_INCREF(Py_None); + return Py_None; } #endif /* HAVE_TCSETPGRP */ @@ -6259,42 +6259,42 @@ static PyObject * posix_open(PyObject *self, PyObject *args) { - char *file = NULL; - int flag; - int mode = 0777; - int fd; + char *file = NULL; + int flag; + int mode = 0777; + int fd; #ifdef MS_WINDOWS - if (unicode_file_names()) { - PyUnicodeObject *po; - if (PyArg_ParseTuple(args, "Ui|i:mkdir", &po, &flag, &mode)) { - Py_BEGIN_ALLOW_THREADS - /* PyUnicode_AS_UNICODE OK without thread - lock as it is a simple dereference. */ - fd = _wopen(PyUnicode_AS_UNICODE(po), flag, mode); - Py_END_ALLOW_THREADS - if (fd < 0) - return posix_error(); - return PyInt_FromLong((long)fd); - } - /* Drop the argument parsing error as narrow strings - are also valid. */ - PyErr_Clear(); - } -#endif - - if (!PyArg_ParseTuple(args, "eti|i", - Py_FileSystemDefaultEncoding, &file, - &flag, &mode)) - return NULL; - - Py_BEGIN_ALLOW_THREADS - fd = open(file, flag, mode); - Py_END_ALLOW_THREADS - if (fd < 0) - return posix_error_with_allocated_filename(file); - PyMem_Free(file); - return PyInt_FromLong((long)fd); + if (unicode_file_names()) { + PyUnicodeObject *po; + if (PyArg_ParseTuple(args, "Ui|i:mkdir", &po, &flag, &mode)) { + Py_BEGIN_ALLOW_THREADS + /* PyUnicode_AS_UNICODE OK without thread + lock as it is a simple dereference. */ + fd = _wopen(PyUnicode_AS_UNICODE(po), flag, mode); + Py_END_ALLOW_THREADS + if (fd < 0) + return posix_error(); + return PyInt_FromLong((long)fd); + } + /* Drop the argument parsing error as narrow strings + are also valid. */ + PyErr_Clear(); + } +#endif + + if (!PyArg_ParseTuple(args, "eti|i", + Py_FileSystemDefaultEncoding, &file, + &flag, &mode)) + return NULL; + + Py_BEGIN_ALLOW_THREADS + fd = open(file, flag, mode); + Py_END_ALLOW_THREADS + if (fd < 0) + return posix_error_with_allocated_filename(file); + PyMem_Free(file); + return PyInt_FromLong((long)fd); } @@ -6305,34 +6305,34 @@ static PyObject * posix_close(PyObject *self, PyObject *args) { - int fd, res; - if (!PyArg_ParseTuple(args, "i:close", &fd)) - return NULL; - Py_BEGIN_ALLOW_THREADS - res = close(fd); - Py_END_ALLOW_THREADS - if (res < 0) - return posix_error(); - Py_INCREF(Py_None); - return Py_None; + int fd, res; + if (!PyArg_ParseTuple(args, "i:close", &fd)) + return NULL; + Py_BEGIN_ALLOW_THREADS + res = close(fd); + Py_END_ALLOW_THREADS + if (res < 0) + return posix_error(); + Py_INCREF(Py_None); + return Py_None; } -PyDoc_STRVAR(posix_closerange__doc__, +PyDoc_STRVAR(posix_closerange__doc__, "closerange(fd_low, fd_high)\n\n\ Closes all file descriptors in [fd_low, fd_high), ignoring errors."); static PyObject * posix_closerange(PyObject *self, PyObject *args) { - int fd_from, fd_to, i; - if (!PyArg_ParseTuple(args, "ii:closerange", &fd_from, &fd_to)) - return NULL; - Py_BEGIN_ALLOW_THREADS - for (i = fd_from; i < fd_to; i++) - close(i); - Py_END_ALLOW_THREADS - Py_RETURN_NONE; + int fd_from, fd_to, i; + if (!PyArg_ParseTuple(args, "ii:closerange", &fd_from, &fd_to)) + return NULL; + Py_BEGIN_ALLOW_THREADS + for (i = fd_from; i < fd_to; i++) + close(i); + Py_END_ALLOW_THREADS + Py_RETURN_NONE; } @@ -6343,15 +6343,15 @@ static PyObject * posix_dup(PyObject *self, PyObject *args) { - int fd; - if (!PyArg_ParseTuple(args, "i:dup", &fd)) - return NULL; - Py_BEGIN_ALLOW_THREADS - fd = dup(fd); - Py_END_ALLOW_THREADS - if (fd < 0) - return posix_error(); - return PyInt_FromLong((long)fd); + int fd; + if (!PyArg_ParseTuple(args, "i:dup", &fd)) + return NULL; + Py_BEGIN_ALLOW_THREADS + fd = dup(fd); + Py_END_ALLOW_THREADS + if (fd < 0) + return posix_error(); + return PyInt_FromLong((long)fd); } @@ -6362,16 +6362,16 @@ static PyObject * posix_dup2(PyObject *self, PyObject *args) { - int fd, fd2, res; - if (!PyArg_ParseTuple(args, "ii:dup2", &fd, &fd2)) - return NULL; - Py_BEGIN_ALLOW_THREADS - res = dup2(fd, fd2); - Py_END_ALLOW_THREADS - if (res < 0) - return posix_error(); - Py_INCREF(Py_None); - return Py_None; + int fd, fd2, res; + if (!PyArg_ParseTuple(args, "ii:dup2", &fd, &fd2)) + return NULL; + Py_BEGIN_ALLOW_THREADS + res = dup2(fd, fd2); + Py_END_ALLOW_THREADS + if (res < 0) + return posix_error(); + Py_INCREF(Py_None); + return Py_None; } @@ -6382,47 +6382,47 @@ static PyObject * posix_lseek(PyObject *self, PyObject *args) { - int fd, how; + int fd, how; #if defined(MS_WIN64) || defined(MS_WINDOWS) - PY_LONG_LONG pos, res; + PY_LONG_LONG pos, res; #else - off_t pos, res; + off_t pos, res; #endif - PyObject *posobj; - if (!PyArg_ParseTuple(args, "iOi:lseek", &fd, &posobj, &how)) - return NULL; + PyObject *posobj; + if (!PyArg_ParseTuple(args, "iOi:lseek", &fd, &posobj, &how)) + return NULL; #ifdef SEEK_SET - /* Turn 0, 1, 2 into SEEK_{SET,CUR,END} */ - switch (how) { - case 0: how = SEEK_SET; break; - case 1: how = SEEK_CUR; break; - case 2: how = SEEK_END; break; - } + /* Turn 0, 1, 2 into SEEK_{SET,CUR,END} */ + switch (how) { + case 0: how = SEEK_SET; break; + case 1: how = SEEK_CUR; break; + case 2: how = SEEK_END; break; + } #endif /* SEEK_END */ #if !defined(HAVE_LARGEFILE_SUPPORT) - pos = PyInt_AsLong(posobj); + pos = PyInt_AsLong(posobj); #else - pos = PyLong_Check(posobj) ? - PyLong_AsLongLong(posobj) : PyInt_AsLong(posobj); + pos = PyLong_Check(posobj) ? + PyLong_AsLongLong(posobj) : PyInt_AsLong(posobj); #endif - if (PyErr_Occurred()) - return NULL; + if (PyErr_Occurred()) + return NULL; - Py_BEGIN_ALLOW_THREADS + Py_BEGIN_ALLOW_THREADS #if defined(MS_WIN64) || defined(MS_WINDOWS) - res = _lseeki64(fd, pos, how); + res = _lseeki64(fd, pos, how); #else - res = lseek(fd, pos, how); + res = lseek(fd, pos, how); #endif - Py_END_ALLOW_THREADS - if (res < 0) - return posix_error(); + Py_END_ALLOW_THREADS + if (res < 0) + return posix_error(); #if !defined(HAVE_LARGEFILE_SUPPORT) - return PyInt_FromLong(res); + return PyInt_FromLong(res); #else - return PyLong_FromLongLong(res); + return PyLong_FromLongLong(res); #endif } @@ -6434,27 +6434,27 @@ static PyObject * posix_read(PyObject *self, PyObject *args) { - int fd, size, n; - PyObject *buffer; - if (!PyArg_ParseTuple(args, "ii:read", &fd, &size)) - return NULL; - if (size < 0) { - errno = EINVAL; - return posix_error(); - } - buffer = PyString_FromStringAndSize((char *)NULL, size); - if (buffer == NULL) - return NULL; - Py_BEGIN_ALLOW_THREADS - n = read(fd, PyString_AsString(buffer), size); - Py_END_ALLOW_THREADS - if (n < 0) { - Py_DECREF(buffer); - return posix_error(); - } - if (n != size) - _PyString_Resize(&buffer, n); - return buffer; + int fd, size, n; + PyObject *buffer; + if (!PyArg_ParseTuple(args, "ii:read", &fd, &size)) + return NULL; + if (size < 0) { + errno = EINVAL; + return posix_error(); + } + buffer = PyString_FromStringAndSize((char *)NULL, size); + if (buffer == NULL) + return NULL; + Py_BEGIN_ALLOW_THREADS + n = read(fd, PyString_AsString(buffer), size); + Py_END_ALLOW_THREADS + if (n < 0) { + Py_DECREF(buffer); + return posix_error(); + } + if (n != size) + _PyString_Resize(&buffer, n); + return buffer; } @@ -6465,19 +6465,19 @@ static PyObject * posix_write(PyObject *self, PyObject *args) { - Py_buffer pbuf; - int fd; - Py_ssize_t size; - - if (!PyArg_ParseTuple(args, "is*:write", &fd, &pbuf)) - return NULL; - Py_BEGIN_ALLOW_THREADS - size = write(fd, pbuf.buf, (size_t)pbuf.len); - Py_END_ALLOW_THREADS - PyBuffer_Release(&pbuf); - if (size < 0) - return posix_error(); - return PyInt_FromSsize_t(size); + Py_buffer pbuf; + int fd; + Py_ssize_t size; + + if (!PyArg_ParseTuple(args, "is*:write", &fd, &pbuf)) + return NULL; + Py_BEGIN_ALLOW_THREADS + size = write(fd, pbuf.buf, (size_t)pbuf.len); + Py_END_ALLOW_THREADS + PyBuffer_Release(&pbuf); + if (size < 0) + return posix_error(); + return PyInt_FromSsize_t(size); } @@ -6488,27 +6488,27 @@ static PyObject * posix_fstat(PyObject *self, PyObject *args) { - int fd; - STRUCT_STAT st; - int res; - if (!PyArg_ParseTuple(args, "i:fstat", &fd)) - return NULL; + int fd; + STRUCT_STAT st; + int res; + if (!PyArg_ParseTuple(args, "i:fstat", &fd)) + return NULL; #ifdef __VMS - /* on OpenVMS we must ensure that all bytes are written to the file */ - fsync(fd); + /* on OpenVMS we must ensure that all bytes are written to the file */ + fsync(fd); #endif - Py_BEGIN_ALLOW_THREADS - res = FSTAT(fd, &st); - Py_END_ALLOW_THREADS - if (res != 0) { + Py_BEGIN_ALLOW_THREADS + res = FSTAT(fd, &st); + Py_END_ALLOW_THREADS + if (res != 0) { #ifdef MS_WINDOWS - return win32_error("fstat", NULL); + return win32_error("fstat", NULL); #else - return posix_error(); + return posix_error(); #endif - } + } - return _pystat_fromstructstat(&st); + return _pystat_fromstructstat(&st); } @@ -6519,52 +6519,52 @@ static PyObject * posix_fdopen(PyObject *self, PyObject *args) { - int fd; - char *orgmode = "r"; - int bufsize = -1; - FILE *fp; - PyObject *f; - char *mode; - if (!PyArg_ParseTuple(args, "i|si", &fd, &orgmode, &bufsize)) - return NULL; - - /* Sanitize mode. See fileobject.c */ - mode = PyMem_MALLOC(strlen(orgmode)+3); - if (!mode) { - PyErr_NoMemory(); - return NULL; - } - strcpy(mode, orgmode); - if (_PyFile_SanitizeMode(mode)) { - PyMem_FREE(mode); - return NULL; - } - Py_BEGIN_ALLOW_THREADS + int fd; + char *orgmode = "r"; + int bufsize = -1; + FILE *fp; + PyObject *f; + char *mode; + if (!PyArg_ParseTuple(args, "i|si", &fd, &orgmode, &bufsize)) + return NULL; + + /* Sanitize mode. See fileobject.c */ + mode = PyMem_MALLOC(strlen(orgmode)+3); + if (!mode) { + PyErr_NoMemory(); + return NULL; + } + strcpy(mode, orgmode); + if (_PyFile_SanitizeMode(mode)) { + PyMem_FREE(mode); + return NULL; + } + Py_BEGIN_ALLOW_THREADS #if !defined(MS_WINDOWS) && defined(HAVE_FCNTL_H) - if (mode[0] == 'a') { - /* try to make sure the O_APPEND flag is set */ - int flags; - flags = fcntl(fd, F_GETFL); - if (flags != -1) - fcntl(fd, F_SETFL, flags | O_APPEND); - fp = fdopen(fd, mode); - if (fp == NULL && flags != -1) - /* restore old mode if fdopen failed */ - fcntl(fd, F_SETFL, flags); - } else { - fp = fdopen(fd, mode); - } -#else - fp = fdopen(fd, mode); -#endif - Py_END_ALLOW_THREADS - PyMem_FREE(mode); - if (fp == NULL) - return posix_error(); - f = PyFile_FromFile(fp, "", orgmode, fclose); - if (f != NULL) - PyFile_SetBufSize(f, bufsize); - return f; + if (mode[0] == 'a') { + /* try to make sure the O_APPEND flag is set */ + int flags; + flags = fcntl(fd, F_GETFL); + if (flags != -1) + fcntl(fd, F_SETFL, flags | O_APPEND); + fp = fdopen(fd, mode); + if (fp == NULL && flags != -1) + /* restore old mode if fdopen failed */ + fcntl(fd, F_SETFL, flags); + } else { + fp = fdopen(fd, mode); + } +#else + fp = fdopen(fd, mode); +#endif + Py_END_ALLOW_THREADS + PyMem_FREE(mode); + if (fp == NULL) + return posix_error(); + f = PyFile_FromFile(fp, "", orgmode, fclose); + if (f != NULL) + PyFile_SetBufSize(f, bufsize); + return f; } PyDoc_STRVAR(posix_isatty__doc__, @@ -6575,10 +6575,10 @@ static PyObject * posix_isatty(PyObject *self, PyObject *args) { - int fd; - if (!PyArg_ParseTuple(args, "i:isatty", &fd)) - return NULL; - return PyBool_FromLong(isatty(fd)); + int fd; + if (!PyArg_ParseTuple(args, "i:isatty", &fd)) + return NULL; + return PyBool_FromLong(isatty(fd)); } #ifdef HAVE_PIPE @@ -6593,35 +6593,35 @@ HFILE read, write; APIRET rc; - Py_BEGIN_ALLOW_THREADS + Py_BEGIN_ALLOW_THREADS rc = DosCreatePipe( &read, &write, 4096); - Py_END_ALLOW_THREADS + Py_END_ALLOW_THREADS if (rc != NO_ERROR) return os2_error(rc); return Py_BuildValue("(ii)", read, write); #else #if !defined(MS_WINDOWS) - int fds[2]; - int res; - Py_BEGIN_ALLOW_THREADS - res = pipe(fds); - Py_END_ALLOW_THREADS - if (res != 0) - return posix_error(); - return Py_BuildValue("(ii)", fds[0], fds[1]); + int fds[2]; + int res; + Py_BEGIN_ALLOW_THREADS + res = pipe(fds); + Py_END_ALLOW_THREADS + if (res != 0) + return posix_error(); + return Py_BuildValue("(ii)", fds[0], fds[1]); #else /* MS_WINDOWS */ - HANDLE read, write; - int read_fd, write_fd; - BOOL ok; - Py_BEGIN_ALLOW_THREADS - ok = CreatePipe(&read, &write, NULL, 0); - Py_END_ALLOW_THREADS - if (!ok) - return win32_error("CreatePipe", NULL); - read_fd = _open_osfhandle((Py_intptr_t)read, 0); - write_fd = _open_osfhandle((Py_intptr_t)write, 1); - return Py_BuildValue("(ii)", read_fd, write_fd); + HANDLE read, write; + int read_fd, write_fd; + BOOL ok; + Py_BEGIN_ALLOW_THREADS + ok = CreatePipe(&read, &write, NULL, 0); + Py_END_ALLOW_THREADS + if (!ok) + return win32_error("CreatePipe", NULL); + read_fd = _open_osfhandle((Py_intptr_t)read, 0); + write_fd = _open_osfhandle((Py_intptr_t)write, 1); + return Py_BuildValue("(ii)", read_fd, write_fd); #endif /* MS_WINDOWS */ #endif } @@ -6636,18 +6636,18 @@ static PyObject * posix_mkfifo(PyObject *self, PyObject *args) { - char *filename; - int mode = 0666; - int res; - if (!PyArg_ParseTuple(args, "s|i:mkfifo", &filename, &mode)) - return NULL; - Py_BEGIN_ALLOW_THREADS - res = mkfifo(filename, mode); - Py_END_ALLOW_THREADS - if (res < 0) - return posix_error(); - Py_INCREF(Py_None); - return Py_None; + char *filename; + int mode = 0666; + int res; + if (!PyArg_ParseTuple(args, "s|i:mkfifo", &filename, &mode)) + return NULL; + Py_BEGIN_ALLOW_THREADS + res = mkfifo(filename, mode); + Py_END_ALLOW_THREADS + if (res < 0) + return posix_error(); + Py_INCREF(Py_None); + return Py_None; } #endif @@ -6666,19 +6666,19 @@ static PyObject * posix_mknod(PyObject *self, PyObject *args) { - char *filename; - int mode = 0600; - int device = 0; - int res; - if (!PyArg_ParseTuple(args, "s|ii:mknod", &filename, &mode, &device)) - return NULL; - Py_BEGIN_ALLOW_THREADS - res = mknod(filename, mode, device); - Py_END_ALLOW_THREADS - if (res < 0) - return posix_error(); - Py_INCREF(Py_None); - return Py_None; + char *filename; + int mode = 0600; + int device = 0; + int res; + if (!PyArg_ParseTuple(args, "s|ii:mknod", &filename, &mode, &device)) + return NULL; + Py_BEGIN_ALLOW_THREADS + res = mknod(filename, mode, device); + Py_END_ALLOW_THREADS + if (res < 0) + return posix_error(); + Py_INCREF(Py_None); + return Py_None; } #endif @@ -6690,10 +6690,10 @@ static PyObject * posix_major(PyObject *self, PyObject *args) { - int device; - if (!PyArg_ParseTuple(args, "i:major", &device)) - return NULL; - return PyInt_FromLong((long)major(device)); + int device; + if (!PyArg_ParseTuple(args, "i:major", &device)) + return NULL; + return PyInt_FromLong((long)major(device)); } PyDoc_STRVAR(posix_minor__doc__, @@ -6703,10 +6703,10 @@ static PyObject * posix_minor(PyObject *self, PyObject *args) { - int device; - if (!PyArg_ParseTuple(args, "i:minor", &device)) - return NULL; - return PyInt_FromLong((long)minor(device)); + int device; + if (!PyArg_ParseTuple(args, "i:minor", &device)) + return NULL; + return PyInt_FromLong((long)minor(device)); } PyDoc_STRVAR(posix_makedev__doc__, @@ -6716,10 +6716,10 @@ static PyObject * posix_makedev(PyObject *self, PyObject *args) { - int major, minor; - if (!PyArg_ParseTuple(args, "ii:makedev", &major, &minor)) - return NULL; - return PyInt_FromLong((long)makedev(major, minor)); + int major, minor; + if (!PyArg_ParseTuple(args, "ii:makedev", &major, &minor)) + return NULL; + return PyInt_FromLong((long)makedev(major, minor)); } #endif /* device macros */ @@ -6732,32 +6732,32 @@ static PyObject * posix_ftruncate(PyObject *self, PyObject *args) { - int fd; - off_t length; - int res; - PyObject *lenobj; + int fd; + off_t length; + int res; + PyObject *lenobj; - if (!PyArg_ParseTuple(args, "iO:ftruncate", &fd, &lenobj)) - return NULL; + if (!PyArg_ParseTuple(args, "iO:ftruncate", &fd, &lenobj)) + return NULL; #if !defined(HAVE_LARGEFILE_SUPPORT) - length = PyInt_AsLong(lenobj); + length = PyInt_AsLong(lenobj); #else - length = PyLong_Check(lenobj) ? - PyLong_AsLongLong(lenobj) : PyInt_AsLong(lenobj); + length = PyLong_Check(lenobj) ? + PyLong_AsLongLong(lenobj) : PyInt_AsLong(lenobj); #endif - if (PyErr_Occurred()) - return NULL; + if (PyErr_Occurred()) + return NULL; - Py_BEGIN_ALLOW_THREADS - res = ftruncate(fd, length); - Py_END_ALLOW_THREADS - if (res < 0) { - PyErr_SetFromErrno(PyExc_IOError); - return NULL; - } - Py_INCREF(Py_None); - return Py_None; + Py_BEGIN_ALLOW_THREADS + res = ftruncate(fd, length); + Py_END_ALLOW_THREADS + if (res < 0) { + PyErr_SetFromErrno(PyExc_IOError); + return NULL; + } + Py_INCREF(Py_None); + return Py_None; } #endif @@ -6773,13 +6773,13 @@ static PyObject * posix_putenv(PyObject *self, PyObject *args) { - char *s1, *s2; - char *newenv; - PyObject *newstr; - size_t len; + char *s1, *s2; + char *newenv; + PyObject *newstr; + size_t len; - if (!PyArg_ParseTuple(args, "ss:putenv", &s1, &s2)) - return NULL; + if (!PyArg_ParseTuple(args, "ss:putenv", &s1, &s2)) + return NULL; #if defined(PYOS_OS2) if (stricmp(s1, "BEGINLIBPATH") == 0) { @@ -6798,38 +6798,38 @@ } else { #endif - /* XXX This can leak memory -- not easy to fix :-( */ - len = strlen(s1) + strlen(s2) + 2; - /* len includes space for a trailing \0; the size arg to - PyString_FromStringAndSize does not count that */ - newstr = PyString_FromStringAndSize(NULL, (int)len - 1); - if (newstr == NULL) - return PyErr_NoMemory(); - newenv = PyString_AS_STRING(newstr); - PyOS_snprintf(newenv, len, "%s=%s", s1, s2); - if (putenv(newenv)) { - Py_DECREF(newstr); - posix_error(); - return NULL; - } - /* Install the first arg and newstr in posix_putenv_garbage; - * this will cause previous value to be collected. This has to - * happen after the real putenv() call because the old value - * was still accessible until then. */ - if (PyDict_SetItem(posix_putenv_garbage, - PyTuple_GET_ITEM(args, 0), newstr)) { - /* really not much we can do; just leak */ - PyErr_Clear(); - } - else { - Py_DECREF(newstr); - } + /* XXX This can leak memory -- not easy to fix :-( */ + len = strlen(s1) + strlen(s2) + 2; + /* len includes space for a trailing \0; the size arg to + PyString_FromStringAndSize does not count that */ + newstr = PyString_FromStringAndSize(NULL, (int)len - 1); + if (newstr == NULL) + return PyErr_NoMemory(); + newenv = PyString_AS_STRING(newstr); + PyOS_snprintf(newenv, len, "%s=%s", s1, s2); + if (putenv(newenv)) { + Py_DECREF(newstr); + posix_error(); + return NULL; + } + /* Install the first arg and newstr in posix_putenv_garbage; + * this will cause previous value to be collected. This has to + * happen after the real putenv() call because the old value + * was still accessible until then. */ + if (PyDict_SetItem(posix_putenv_garbage, + PyTuple_GET_ITEM(args, 0), newstr)) { + /* really not much we can do; just leak */ + PyErr_Clear(); + } + else { + Py_DECREF(newstr); + } #if defined(PYOS_OS2) } #endif - Py_INCREF(Py_None); - return Py_None; + Py_INCREF(Py_None); + return Py_None; } #endif /* putenv */ @@ -6841,26 +6841,26 @@ static PyObject * posix_unsetenv(PyObject *self, PyObject *args) { - char *s1; + char *s1; - if (!PyArg_ParseTuple(args, "s:unsetenv", &s1)) - return NULL; + if (!PyArg_ParseTuple(args, "s:unsetenv", &s1)) + return NULL; - unsetenv(s1); + unsetenv(s1); - /* Remove the key from posix_putenv_garbage; - * this will cause it to be collected. This has to - * happen after the real unsetenv() call because the - * old value was still accessible until then. - */ - if (PyDict_DelItem(posix_putenv_garbage, - PyTuple_GET_ITEM(args, 0))) { - /* really not much we can do; just leak */ - PyErr_Clear(); - } + /* Remove the key from posix_putenv_garbage; + * this will cause it to be collected. This has to + * happen after the real unsetenv() call because the + * old value was still accessible until then. + */ + if (PyDict_DelItem(posix_putenv_garbage, + PyTuple_GET_ITEM(args, 0))) { + /* really not much we can do; just leak */ + PyErr_Clear(); + } - Py_INCREF(Py_None); - return Py_None; + Py_INCREF(Py_None); + return Py_None; } #endif /* unsetenv */ @@ -6871,17 +6871,17 @@ static PyObject * posix_strerror(PyObject *self, PyObject *args) { - int code; - char *message; - if (!PyArg_ParseTuple(args, "i:strerror", &code)) - return NULL; - message = strerror(code); - if (message == NULL) { - PyErr_SetString(PyExc_ValueError, - "strerror() argument out of range"); - return NULL; - } - return PyString_FromString(message); + int code; + char *message; + if (!PyArg_ParseTuple(args, "i:strerror", &code)) + return NULL; + message = strerror(code); + if (message == NULL) { + PyErr_SetString(PyExc_ValueError, + "strerror() argument out of range"); + return NULL; + } + return PyString_FromString(message); } @@ -6895,13 +6895,13 @@ static PyObject * posix_WCOREDUMP(PyObject *self, PyObject *args) { - WAIT_TYPE status; - WAIT_STATUS_INT(status) = 0; + WAIT_TYPE status; + WAIT_STATUS_INT(status) = 0; - if (!PyArg_ParseTuple(args, "i:WCOREDUMP", &WAIT_STATUS_INT(status))) - return NULL; + if (!PyArg_ParseTuple(args, "i:WCOREDUMP", &WAIT_STATUS_INT(status))) + return NULL; - return PyBool_FromLong(WCOREDUMP(status)); + return PyBool_FromLong(WCOREDUMP(status)); } #endif /* WCOREDUMP */ @@ -6914,13 +6914,13 @@ static PyObject * posix_WIFCONTINUED(PyObject *self, PyObject *args) { - WAIT_TYPE status; - WAIT_STATUS_INT(status) = 0; + WAIT_TYPE status; + WAIT_STATUS_INT(status) = 0; - if (!PyArg_ParseTuple(args, "i:WCONTINUED", &WAIT_STATUS_INT(status))) - return NULL; + if (!PyArg_ParseTuple(args, "i:WCONTINUED", &WAIT_STATUS_INT(status))) + return NULL; - return PyBool_FromLong(WIFCONTINUED(status)); + return PyBool_FromLong(WIFCONTINUED(status)); } #endif /* WIFCONTINUED */ @@ -6932,13 +6932,13 @@ static PyObject * posix_WIFSTOPPED(PyObject *self, PyObject *args) { - WAIT_TYPE status; - WAIT_STATUS_INT(status) = 0; + WAIT_TYPE status; + WAIT_STATUS_INT(status) = 0; - if (!PyArg_ParseTuple(args, "i:WIFSTOPPED", &WAIT_STATUS_INT(status))) - return NULL; + if (!PyArg_ParseTuple(args, "i:WIFSTOPPED", &WAIT_STATUS_INT(status))) + return NULL; - return PyBool_FromLong(WIFSTOPPED(status)); + return PyBool_FromLong(WIFSTOPPED(status)); } #endif /* WIFSTOPPED */ @@ -6950,13 +6950,13 @@ static PyObject * posix_WIFSIGNALED(PyObject *self, PyObject *args) { - WAIT_TYPE status; - WAIT_STATUS_INT(status) = 0; + WAIT_TYPE status; + WAIT_STATUS_INT(status) = 0; - if (!PyArg_ParseTuple(args, "i:WIFSIGNALED", &WAIT_STATUS_INT(status))) - return NULL; + if (!PyArg_ParseTuple(args, "i:WIFSIGNALED", &WAIT_STATUS_INT(status))) + return NULL; - return PyBool_FromLong(WIFSIGNALED(status)); + return PyBool_FromLong(WIFSIGNALED(status)); } #endif /* WIFSIGNALED */ @@ -6969,13 +6969,13 @@ static PyObject * posix_WIFEXITED(PyObject *self, PyObject *args) { - WAIT_TYPE status; - WAIT_STATUS_INT(status) = 0; + WAIT_TYPE status; + WAIT_STATUS_INT(status) = 0; - if (!PyArg_ParseTuple(args, "i:WIFEXITED", &WAIT_STATUS_INT(status))) - return NULL; + if (!PyArg_ParseTuple(args, "i:WIFEXITED", &WAIT_STATUS_INT(status))) + return NULL; - return PyBool_FromLong(WIFEXITED(status)); + return PyBool_FromLong(WIFEXITED(status)); } #endif /* WIFEXITED */ @@ -6987,13 +6987,13 @@ static PyObject * posix_WEXITSTATUS(PyObject *self, PyObject *args) { - WAIT_TYPE status; - WAIT_STATUS_INT(status) = 0; + WAIT_TYPE status; + WAIT_STATUS_INT(status) = 0; - if (!PyArg_ParseTuple(args, "i:WEXITSTATUS", &WAIT_STATUS_INT(status))) - return NULL; + if (!PyArg_ParseTuple(args, "i:WEXITSTATUS", &WAIT_STATUS_INT(status))) + return NULL; - return Py_BuildValue("i", WEXITSTATUS(status)); + return Py_BuildValue("i", WEXITSTATUS(status)); } #endif /* WEXITSTATUS */ @@ -7006,13 +7006,13 @@ static PyObject * posix_WTERMSIG(PyObject *self, PyObject *args) { - WAIT_TYPE status; - WAIT_STATUS_INT(status) = 0; + WAIT_TYPE status; + WAIT_STATUS_INT(status) = 0; - if (!PyArg_ParseTuple(args, "i:WTERMSIG", &WAIT_STATUS_INT(status))) - return NULL; + if (!PyArg_ParseTuple(args, "i:WTERMSIG", &WAIT_STATUS_INT(status))) + return NULL; - return Py_BuildValue("i", WTERMSIG(status)); + return Py_BuildValue("i", WTERMSIG(status)); } #endif /* WTERMSIG */ @@ -7025,13 +7025,13 @@ static PyObject * posix_WSTOPSIG(PyObject *self, PyObject *args) { - WAIT_TYPE status; - WAIT_STATUS_INT(status) = 0; + WAIT_TYPE status; + WAIT_STATUS_INT(status) = 0; - if (!PyArg_ParseTuple(args, "i:WSTOPSIG", &WAIT_STATUS_INT(status))) - return NULL; + if (!PyArg_ParseTuple(args, "i:WSTOPSIG", &WAIT_STATUS_INT(status))) + return NULL; - return Py_BuildValue("i", WSTOPSIG(status)); + return Py_BuildValue("i", WSTOPSIG(status)); } #endif /* WSTOPSIG */ @@ -7048,41 +7048,41 @@ static PyObject* _pystatvfs_fromstructstatvfs(struct statvfs st) { - PyObject *v = PyStructSequence_New(&StatVFSResultType); - if (v == NULL) - return NULL; + PyObject *v = PyStructSequence_New(&StatVFSResultType); + if (v == NULL) + return NULL; #if !defined(HAVE_LARGEFILE_SUPPORT) - PyStructSequence_SET_ITEM(v, 0, PyInt_FromLong((long) st.f_bsize)); - PyStructSequence_SET_ITEM(v, 1, PyInt_FromLong((long) st.f_frsize)); - PyStructSequence_SET_ITEM(v, 2, PyInt_FromLong((long) st.f_blocks)); - PyStructSequence_SET_ITEM(v, 3, PyInt_FromLong((long) st.f_bfree)); - PyStructSequence_SET_ITEM(v, 4, PyInt_FromLong((long) st.f_bavail)); - PyStructSequence_SET_ITEM(v, 5, PyInt_FromLong((long) st.f_files)); - PyStructSequence_SET_ITEM(v, 6, PyInt_FromLong((long) st.f_ffree)); - PyStructSequence_SET_ITEM(v, 7, PyInt_FromLong((long) st.f_favail)); - PyStructSequence_SET_ITEM(v, 8, PyInt_FromLong((long) st.f_flag)); - PyStructSequence_SET_ITEM(v, 9, PyInt_FromLong((long) st.f_namemax)); -#else - PyStructSequence_SET_ITEM(v, 0, PyInt_FromLong((long) st.f_bsize)); - PyStructSequence_SET_ITEM(v, 1, PyInt_FromLong((long) st.f_frsize)); - PyStructSequence_SET_ITEM(v, 2, - PyLong_FromLongLong((PY_LONG_LONG) st.f_blocks)); - PyStructSequence_SET_ITEM(v, 3, - PyLong_FromLongLong((PY_LONG_LONG) st.f_bfree)); - PyStructSequence_SET_ITEM(v, 4, - PyLong_FromLongLong((PY_LONG_LONG) st.f_bavail)); - PyStructSequence_SET_ITEM(v, 5, - PyLong_FromLongLong((PY_LONG_LONG) st.f_files)); - PyStructSequence_SET_ITEM(v, 6, - PyLong_FromLongLong((PY_LONG_LONG) st.f_ffree)); - PyStructSequence_SET_ITEM(v, 7, - PyLong_FromLongLong((PY_LONG_LONG) st.f_favail)); - PyStructSequence_SET_ITEM(v, 8, PyInt_FromLong((long) st.f_flag)); - PyStructSequence_SET_ITEM(v, 9, PyInt_FromLong((long) st.f_namemax)); + PyStructSequence_SET_ITEM(v, 0, PyInt_FromLong((long) st.f_bsize)); + PyStructSequence_SET_ITEM(v, 1, PyInt_FromLong((long) st.f_frsize)); + PyStructSequence_SET_ITEM(v, 2, PyInt_FromLong((long) st.f_blocks)); + PyStructSequence_SET_ITEM(v, 3, PyInt_FromLong((long) st.f_bfree)); + PyStructSequence_SET_ITEM(v, 4, PyInt_FromLong((long) st.f_bavail)); + PyStructSequence_SET_ITEM(v, 5, PyInt_FromLong((long) st.f_files)); + PyStructSequence_SET_ITEM(v, 6, PyInt_FromLong((long) st.f_ffree)); + PyStructSequence_SET_ITEM(v, 7, PyInt_FromLong((long) st.f_favail)); + PyStructSequence_SET_ITEM(v, 8, PyInt_FromLong((long) st.f_flag)); + PyStructSequence_SET_ITEM(v, 9, PyInt_FromLong((long) st.f_namemax)); +#else + PyStructSequence_SET_ITEM(v, 0, PyInt_FromLong((long) st.f_bsize)); + PyStructSequence_SET_ITEM(v, 1, PyInt_FromLong((long) st.f_frsize)); + PyStructSequence_SET_ITEM(v, 2, + PyLong_FromLongLong((PY_LONG_LONG) st.f_blocks)); + PyStructSequence_SET_ITEM(v, 3, + PyLong_FromLongLong((PY_LONG_LONG) st.f_bfree)); + PyStructSequence_SET_ITEM(v, 4, + PyLong_FromLongLong((PY_LONG_LONG) st.f_bavail)); + PyStructSequence_SET_ITEM(v, 5, + PyLong_FromLongLong((PY_LONG_LONG) st.f_files)); + PyStructSequence_SET_ITEM(v, 6, + PyLong_FromLongLong((PY_LONG_LONG) st.f_ffree)); + PyStructSequence_SET_ITEM(v, 7, + PyLong_FromLongLong((PY_LONG_LONG) st.f_favail)); + PyStructSequence_SET_ITEM(v, 8, PyInt_FromLong((long) st.f_flag)); + PyStructSequence_SET_ITEM(v, 9, PyInt_FromLong((long) st.f_namemax)); #endif - return v; + return v; } PyDoc_STRVAR(posix_fstatvfs__doc__, @@ -7092,18 +7092,18 @@ static PyObject * posix_fstatvfs(PyObject *self, PyObject *args) { - int fd, res; - struct statvfs st; + int fd, res; + struct statvfs st; - if (!PyArg_ParseTuple(args, "i:fstatvfs", &fd)) - return NULL; - Py_BEGIN_ALLOW_THREADS - res = fstatvfs(fd, &st); - Py_END_ALLOW_THREADS - if (res != 0) - return posix_error(); + if (!PyArg_ParseTuple(args, "i:fstatvfs", &fd)) + return NULL; + Py_BEGIN_ALLOW_THREADS + res = fstatvfs(fd, &st); + Py_END_ALLOW_THREADS + if (res != 0) + return posix_error(); - return _pystatvfs_fromstructstatvfs(st); + return _pystatvfs_fromstructstatvfs(st); } #endif /* HAVE_FSTATVFS && HAVE_SYS_STATVFS_H */ @@ -7118,18 +7118,18 @@ static PyObject * posix_statvfs(PyObject *self, PyObject *args) { - char *path; - int res; - struct statvfs st; - if (!PyArg_ParseTuple(args, "s:statvfs", &path)) - return NULL; - Py_BEGIN_ALLOW_THREADS - res = statvfs(path, &st); - Py_END_ALLOW_THREADS - if (res != 0) - return posix_error_with_filename(path); + char *path; + int res; + struct statvfs st; + if (!PyArg_ParseTuple(args, "s:statvfs", &path)) + return NULL; + Py_BEGIN_ALLOW_THREADS + res = statvfs(path, &st); + Py_END_ALLOW_THREADS + if (res != 0) + return posix_error_with_filename(path); - return _pystatvfs_fromstructstatvfs(st); + return _pystatvfs_fromstructstatvfs(st); } #endif /* HAVE_STATVFS */ @@ -7150,11 +7150,11 @@ char *name; if (!PyArg_ParseTuple(args, "|zz:tempnam", &dir, &pfx)) - return NULL; + return NULL; if (PyErr_Warn(PyExc_RuntimeWarning, - "tempnam is a potential security risk to your program") < 0) - return NULL; + "tempnam is a potential security risk to your program") < 0) + return NULL; #ifdef MS_WINDOWS name = _tempnam(dir, pfx); @@ -7162,7 +7162,7 @@ name = tempnam(dir, pfx); #endif if (name == NULL) - return PyErr_NoMemory(); + return PyErr_NoMemory(); result = PyString_FromString(name); free(name); return result; @@ -7182,7 +7182,7 @@ fp = tmpfile(); if (fp == NULL) - return posix_error(); + return posix_error(); return PyFile_FromFile(fp, "", "w+b", fclose); } #endif @@ -7200,8 +7200,8 @@ char *name; if (PyErr_Warn(PyExc_RuntimeWarning, - "tmpnam is a potential security risk to your program") < 0) - return NULL; + "tmpnam is a potential security risk to your program") < 0) + return NULL; #ifdef USE_TMPNAM_R name = tmpnam_r(buffer); @@ -7209,16 +7209,16 @@ name = tmpnam(buffer); #endif if (name == NULL) { - PyObject *err = Py_BuildValue("is", 0, + PyObject *err = Py_BuildValue("is", 0, #ifdef USE_TMPNAM_R - "unexpected NULL from tmpnam_r" + "unexpected NULL from tmpnam_r" #else - "unexpected NULL from tmpnam" + "unexpected NULL from tmpnam" #endif - ); - PyErr_SetObject(PyExc_OSError, err); - Py_XDECREF(err); - return NULL; + ); + PyErr_SetObject(PyExc_OSError, err); + Py_XDECREF(err); + return NULL; } return PyString_FromString(buffer); } @@ -7243,36 +7243,36 @@ static int conv_confname(PyObject *arg, int *valuep, struct constdef *table, - size_t tablesize) + size_t tablesize) { if (PyInt_Check(arg)) { - *valuep = PyInt_AS_LONG(arg); - return 1; + *valuep = PyInt_AS_LONG(arg); + return 1; } if (PyString_Check(arg)) { - /* look up the value in the table using a binary search */ - size_t lo = 0; - size_t mid; - size_t hi = tablesize; - int cmp; - char *confname = PyString_AS_STRING(arg); - while (lo < hi) { - mid = (lo + hi) / 2; - cmp = strcmp(confname, table[mid].name); - if (cmp < 0) - hi = mid; - else if (cmp > 0) - lo = mid + 1; - else { - *valuep = table[mid].value; - return 1; - } + /* look up the value in the table using a binary search */ + size_t lo = 0; + size_t mid; + size_t hi = tablesize; + int cmp; + char *confname = PyString_AS_STRING(arg); + while (lo < hi) { + mid = (lo + hi) / 2; + cmp = strcmp(confname, table[mid].name); + if (cmp < 0) + hi = mid; + else if (cmp > 0) + lo = mid + 1; + else { + *valuep = table[mid].value; + return 1; } - PyErr_SetString(PyExc_ValueError, "unrecognized configuration name"); + } + PyErr_SetString(PyExc_ValueError, "unrecognized configuration name"); } else - PyErr_SetString(PyExc_TypeError, - "configuration names must be strings or integers"); + PyErr_SetString(PyExc_TypeError, + "configuration names must be strings or integers"); return 0; } @@ -7280,55 +7280,55 @@ #if defined(HAVE_FPATHCONF) || defined(HAVE_PATHCONF) static struct constdef posix_constants_pathconf[] = { #ifdef _PC_ABI_AIO_XFER_MAX - {"PC_ABI_AIO_XFER_MAX", _PC_ABI_AIO_XFER_MAX}, + {"PC_ABI_AIO_XFER_MAX", _PC_ABI_AIO_XFER_MAX}, #endif #ifdef _PC_ABI_ASYNC_IO - {"PC_ABI_ASYNC_IO", _PC_ABI_ASYNC_IO}, + {"PC_ABI_ASYNC_IO", _PC_ABI_ASYNC_IO}, #endif #ifdef _PC_ASYNC_IO - {"PC_ASYNC_IO", _PC_ASYNC_IO}, + {"PC_ASYNC_IO", _PC_ASYNC_IO}, #endif #ifdef _PC_CHOWN_RESTRICTED - {"PC_CHOWN_RESTRICTED", _PC_CHOWN_RESTRICTED}, + {"PC_CHOWN_RESTRICTED", _PC_CHOWN_RESTRICTED}, #endif #ifdef _PC_FILESIZEBITS - {"PC_FILESIZEBITS", _PC_FILESIZEBITS}, + {"PC_FILESIZEBITS", _PC_FILESIZEBITS}, #endif #ifdef _PC_LAST - {"PC_LAST", _PC_LAST}, + {"PC_LAST", _PC_LAST}, #endif #ifdef _PC_LINK_MAX - {"PC_LINK_MAX", _PC_LINK_MAX}, + {"PC_LINK_MAX", _PC_LINK_MAX}, #endif #ifdef _PC_MAX_CANON - {"PC_MAX_CANON", _PC_MAX_CANON}, + {"PC_MAX_CANON", _PC_MAX_CANON}, #endif #ifdef _PC_MAX_INPUT - {"PC_MAX_INPUT", _PC_MAX_INPUT}, + {"PC_MAX_INPUT", _PC_MAX_INPUT}, #endif #ifdef _PC_NAME_MAX - {"PC_NAME_MAX", _PC_NAME_MAX}, + {"PC_NAME_MAX", _PC_NAME_MAX}, #endif #ifdef _PC_NO_TRUNC - {"PC_NO_TRUNC", _PC_NO_TRUNC}, + {"PC_NO_TRUNC", _PC_NO_TRUNC}, #endif #ifdef _PC_PATH_MAX - {"PC_PATH_MAX", _PC_PATH_MAX}, + {"PC_PATH_MAX", _PC_PATH_MAX}, #endif #ifdef _PC_PIPE_BUF - {"PC_PIPE_BUF", _PC_PIPE_BUF}, + {"PC_PIPE_BUF", _PC_PIPE_BUF}, #endif #ifdef _PC_PRIO_IO - {"PC_PRIO_IO", _PC_PRIO_IO}, + {"PC_PRIO_IO", _PC_PRIO_IO}, #endif #ifdef _PC_SOCK_MAXBUF - {"PC_SOCK_MAXBUF", _PC_SOCK_MAXBUF}, + {"PC_SOCK_MAXBUF", _PC_SOCK_MAXBUF}, #endif #ifdef _PC_SYNC_IO - {"PC_SYNC_IO", _PC_SYNC_IO}, + {"PC_SYNC_IO", _PC_SYNC_IO}, #endif #ifdef _PC_VDISABLE - {"PC_VDISABLE", _PC_VDISABLE}, + {"PC_VDISABLE", _PC_VDISABLE}, #endif }; @@ -7355,14 +7355,14 @@ if (PyArg_ParseTuple(args, "iO&:fpathconf", &fd, conv_path_confname, &name)) { - long limit; + long limit; - errno = 0; - limit = fpathconf(fd, name); - if (limit == -1 && errno != 0) - posix_error(); - else - result = PyInt_FromLong(limit); + errno = 0; + limit = fpathconf(fd, name); + if (limit == -1 && errno != 0) + posix_error(); + else + result = PyInt_FromLong(limit); } return result; } @@ -7384,19 +7384,19 @@ if (PyArg_ParseTuple(args, "sO&:pathconf", &path, conv_path_confname, &name)) { - long limit; + long limit; - errno = 0; - limit = pathconf(path, name); - if (limit == -1 && errno != 0) { - if (errno == EINVAL) - /* could be a path or name problem */ - posix_error(); - else - posix_error_with_filename(path); - } + errno = 0; + limit = pathconf(path, name); + if (limit == -1 && errno != 0) { + if (errno == EINVAL) + /* could be a path or name problem */ + posix_error(); else - result = PyInt_FromLong(limit); + posix_error_with_filename(path); + } + else + result = PyInt_FromLong(limit); } return result; } @@ -7405,148 +7405,148 @@ #ifdef HAVE_CONFSTR static struct constdef posix_constants_confstr[] = { #ifdef _CS_ARCHITECTURE - {"CS_ARCHITECTURE", _CS_ARCHITECTURE}, + {"CS_ARCHITECTURE", _CS_ARCHITECTURE}, #endif #ifdef _CS_HOSTNAME - {"CS_HOSTNAME", _CS_HOSTNAME}, + {"CS_HOSTNAME", _CS_HOSTNAME}, #endif #ifdef _CS_HW_PROVIDER - {"CS_HW_PROVIDER", _CS_HW_PROVIDER}, + {"CS_HW_PROVIDER", _CS_HW_PROVIDER}, #endif #ifdef _CS_HW_SERIAL - {"CS_HW_SERIAL", _CS_HW_SERIAL}, + {"CS_HW_SERIAL", _CS_HW_SERIAL}, #endif #ifdef _CS_INITTAB_NAME - {"CS_INITTAB_NAME", _CS_INITTAB_NAME}, + {"CS_INITTAB_NAME", _CS_INITTAB_NAME}, #endif #ifdef _CS_LFS64_CFLAGS - {"CS_LFS64_CFLAGS", _CS_LFS64_CFLAGS}, + {"CS_LFS64_CFLAGS", _CS_LFS64_CFLAGS}, #endif #ifdef _CS_LFS64_LDFLAGS - {"CS_LFS64_LDFLAGS", _CS_LFS64_LDFLAGS}, + {"CS_LFS64_LDFLAGS", _CS_LFS64_LDFLAGS}, #endif #ifdef _CS_LFS64_LIBS - {"CS_LFS64_LIBS", _CS_LFS64_LIBS}, + {"CS_LFS64_LIBS", _CS_LFS64_LIBS}, #endif #ifdef _CS_LFS64_LINTFLAGS - {"CS_LFS64_LINTFLAGS", _CS_LFS64_LINTFLAGS}, + {"CS_LFS64_LINTFLAGS", _CS_LFS64_LINTFLAGS}, #endif #ifdef _CS_LFS_CFLAGS - {"CS_LFS_CFLAGS", _CS_LFS_CFLAGS}, + {"CS_LFS_CFLAGS", _CS_LFS_CFLAGS}, #endif #ifdef _CS_LFS_LDFLAGS - {"CS_LFS_LDFLAGS", _CS_LFS_LDFLAGS}, + {"CS_LFS_LDFLAGS", _CS_LFS_LDFLAGS}, #endif #ifdef _CS_LFS_LIBS - {"CS_LFS_LIBS", _CS_LFS_LIBS}, + {"CS_LFS_LIBS", _CS_LFS_LIBS}, #endif #ifdef _CS_LFS_LINTFLAGS - {"CS_LFS_LINTFLAGS", _CS_LFS_LINTFLAGS}, + {"CS_LFS_LINTFLAGS", _CS_LFS_LINTFLAGS}, #endif #ifdef _CS_MACHINE - {"CS_MACHINE", _CS_MACHINE}, + {"CS_MACHINE", _CS_MACHINE}, #endif #ifdef _CS_PATH - {"CS_PATH", _CS_PATH}, + {"CS_PATH", _CS_PATH}, #endif #ifdef _CS_RELEASE - {"CS_RELEASE", _CS_RELEASE}, + {"CS_RELEASE", _CS_RELEASE}, #endif #ifdef _CS_SRPC_DOMAIN - {"CS_SRPC_DOMAIN", _CS_SRPC_DOMAIN}, + {"CS_SRPC_DOMAIN", _CS_SRPC_DOMAIN}, #endif #ifdef _CS_SYSNAME - {"CS_SYSNAME", _CS_SYSNAME}, + {"CS_SYSNAME", _CS_SYSNAME}, #endif #ifdef _CS_VERSION - {"CS_VERSION", _CS_VERSION}, + {"CS_VERSION", _CS_VERSION}, #endif #ifdef _CS_XBS5_ILP32_OFF32_CFLAGS - {"CS_XBS5_ILP32_OFF32_CFLAGS", _CS_XBS5_ILP32_OFF32_CFLAGS}, + {"CS_XBS5_ILP32_OFF32_CFLAGS", _CS_XBS5_ILP32_OFF32_CFLAGS}, #endif #ifdef _CS_XBS5_ILP32_OFF32_LDFLAGS - {"CS_XBS5_ILP32_OFF32_LDFLAGS", _CS_XBS5_ILP32_OFF32_LDFLAGS}, + {"CS_XBS5_ILP32_OFF32_LDFLAGS", _CS_XBS5_ILP32_OFF32_LDFLAGS}, #endif #ifdef _CS_XBS5_ILP32_OFF32_LIBS - {"CS_XBS5_ILP32_OFF32_LIBS", _CS_XBS5_ILP32_OFF32_LIBS}, + {"CS_XBS5_ILP32_OFF32_LIBS", _CS_XBS5_ILP32_OFF32_LIBS}, #endif #ifdef _CS_XBS5_ILP32_OFF32_LINTFLAGS - {"CS_XBS5_ILP32_OFF32_LINTFLAGS", _CS_XBS5_ILP32_OFF32_LINTFLAGS}, + {"CS_XBS5_ILP32_OFF32_LINTFLAGS", _CS_XBS5_ILP32_OFF32_LINTFLAGS}, #endif #ifdef _CS_XBS5_ILP32_OFFBIG_CFLAGS - {"CS_XBS5_ILP32_OFFBIG_CFLAGS", _CS_XBS5_ILP32_OFFBIG_CFLAGS}, + {"CS_XBS5_ILP32_OFFBIG_CFLAGS", _CS_XBS5_ILP32_OFFBIG_CFLAGS}, #endif #ifdef _CS_XBS5_ILP32_OFFBIG_LDFLAGS - {"CS_XBS5_ILP32_OFFBIG_LDFLAGS", _CS_XBS5_ILP32_OFFBIG_LDFLAGS}, + {"CS_XBS5_ILP32_OFFBIG_LDFLAGS", _CS_XBS5_ILP32_OFFBIG_LDFLAGS}, #endif #ifdef _CS_XBS5_ILP32_OFFBIG_LIBS - {"CS_XBS5_ILP32_OFFBIG_LIBS", _CS_XBS5_ILP32_OFFBIG_LIBS}, + {"CS_XBS5_ILP32_OFFBIG_LIBS", _CS_XBS5_ILP32_OFFBIG_LIBS}, #endif #ifdef _CS_XBS5_ILP32_OFFBIG_LINTFLAGS - {"CS_XBS5_ILP32_OFFBIG_LINTFLAGS", _CS_XBS5_ILP32_OFFBIG_LINTFLAGS}, + {"CS_XBS5_ILP32_OFFBIG_LINTFLAGS", _CS_XBS5_ILP32_OFFBIG_LINTFLAGS}, #endif #ifdef _CS_XBS5_LP64_OFF64_CFLAGS - {"CS_XBS5_LP64_OFF64_CFLAGS", _CS_XBS5_LP64_OFF64_CFLAGS}, + {"CS_XBS5_LP64_OFF64_CFLAGS", _CS_XBS5_LP64_OFF64_CFLAGS}, #endif #ifdef _CS_XBS5_LP64_OFF64_LDFLAGS - {"CS_XBS5_LP64_OFF64_LDFLAGS", _CS_XBS5_LP64_OFF64_LDFLAGS}, + {"CS_XBS5_LP64_OFF64_LDFLAGS", _CS_XBS5_LP64_OFF64_LDFLAGS}, #endif #ifdef _CS_XBS5_LP64_OFF64_LIBS - {"CS_XBS5_LP64_OFF64_LIBS", _CS_XBS5_LP64_OFF64_LIBS}, + {"CS_XBS5_LP64_OFF64_LIBS", _CS_XBS5_LP64_OFF64_LIBS}, #endif #ifdef _CS_XBS5_LP64_OFF64_LINTFLAGS - {"CS_XBS5_LP64_OFF64_LINTFLAGS", _CS_XBS5_LP64_OFF64_LINTFLAGS}, + {"CS_XBS5_LP64_OFF64_LINTFLAGS", _CS_XBS5_LP64_OFF64_LINTFLAGS}, #endif #ifdef _CS_XBS5_LPBIG_OFFBIG_CFLAGS - {"CS_XBS5_LPBIG_OFFBIG_CFLAGS", _CS_XBS5_LPBIG_OFFBIG_CFLAGS}, + {"CS_XBS5_LPBIG_OFFBIG_CFLAGS", _CS_XBS5_LPBIG_OFFBIG_CFLAGS}, #endif #ifdef _CS_XBS5_LPBIG_OFFBIG_LDFLAGS - {"CS_XBS5_LPBIG_OFFBIG_LDFLAGS", _CS_XBS5_LPBIG_OFFBIG_LDFLAGS}, + {"CS_XBS5_LPBIG_OFFBIG_LDFLAGS", _CS_XBS5_LPBIG_OFFBIG_LDFLAGS}, #endif #ifdef _CS_XBS5_LPBIG_OFFBIG_LIBS - {"CS_XBS5_LPBIG_OFFBIG_LIBS", _CS_XBS5_LPBIG_OFFBIG_LIBS}, + {"CS_XBS5_LPBIG_OFFBIG_LIBS", _CS_XBS5_LPBIG_OFFBIG_LIBS}, #endif #ifdef _CS_XBS5_LPBIG_OFFBIG_LINTFLAGS - {"CS_XBS5_LPBIG_OFFBIG_LINTFLAGS", _CS_XBS5_LPBIG_OFFBIG_LINTFLAGS}, + {"CS_XBS5_LPBIG_OFFBIG_LINTFLAGS", _CS_XBS5_LPBIG_OFFBIG_LINTFLAGS}, #endif #ifdef _MIPS_CS_AVAIL_PROCESSORS - {"MIPS_CS_AVAIL_PROCESSORS", _MIPS_CS_AVAIL_PROCESSORS}, + {"MIPS_CS_AVAIL_PROCESSORS", _MIPS_CS_AVAIL_PROCESSORS}, #endif #ifdef _MIPS_CS_BASE - {"MIPS_CS_BASE", _MIPS_CS_BASE}, + {"MIPS_CS_BASE", _MIPS_CS_BASE}, #endif #ifdef _MIPS_CS_HOSTID - {"MIPS_CS_HOSTID", _MIPS_CS_HOSTID}, + {"MIPS_CS_HOSTID", _MIPS_CS_HOSTID}, #endif #ifdef _MIPS_CS_HW_NAME - {"MIPS_CS_HW_NAME", _MIPS_CS_HW_NAME}, + {"MIPS_CS_HW_NAME", _MIPS_CS_HW_NAME}, #endif #ifdef _MIPS_CS_NUM_PROCESSORS - {"MIPS_CS_NUM_PROCESSORS", _MIPS_CS_NUM_PROCESSORS}, + {"MIPS_CS_NUM_PROCESSORS", _MIPS_CS_NUM_PROCESSORS}, #endif #ifdef _MIPS_CS_OSREL_MAJ - {"MIPS_CS_OSREL_MAJ", _MIPS_CS_OSREL_MAJ}, + {"MIPS_CS_OSREL_MAJ", _MIPS_CS_OSREL_MAJ}, #endif #ifdef _MIPS_CS_OSREL_MIN - {"MIPS_CS_OSREL_MIN", _MIPS_CS_OSREL_MIN}, + {"MIPS_CS_OSREL_MIN", _MIPS_CS_OSREL_MIN}, #endif #ifdef _MIPS_CS_OSREL_PATCH - {"MIPS_CS_OSREL_PATCH", _MIPS_CS_OSREL_PATCH}, + {"MIPS_CS_OSREL_PATCH", _MIPS_CS_OSREL_PATCH}, #endif #ifdef _MIPS_CS_OS_NAME - {"MIPS_CS_OS_NAME", _MIPS_CS_OS_NAME}, + {"MIPS_CS_OS_NAME", _MIPS_CS_OS_NAME}, #endif #ifdef _MIPS_CS_OS_PROVIDER - {"MIPS_CS_OS_PROVIDER", _MIPS_CS_OS_PROVIDER}, + {"MIPS_CS_OS_PROVIDER", _MIPS_CS_OS_PROVIDER}, #endif #ifdef _MIPS_CS_PROCESSORS - {"MIPS_CS_PROCESSORS", _MIPS_CS_PROCESSORS}, + {"MIPS_CS_PROCESSORS", _MIPS_CS_PROCESSORS}, #endif #ifdef _MIPS_CS_SERIAL - {"MIPS_CS_SERIAL", _MIPS_CS_SERIAL}, + {"MIPS_CS_SERIAL", _MIPS_CS_SERIAL}, #endif #ifdef _MIPS_CS_VENDOR - {"MIPS_CS_VENDOR", _MIPS_CS_VENDOR}, + {"MIPS_CS_VENDOR", _MIPS_CS_VENDOR}, #endif }; @@ -7570,29 +7570,29 @@ char buffer[256]; if (PyArg_ParseTuple(args, "O&:confstr", conv_confstr_confname, &name)) { - int len; + int len; - errno = 0; - len = confstr(name, buffer, sizeof(buffer)); - if (len == 0) { - if (errno) { - posix_error(); - } - else { - result = Py_None; - Py_INCREF(Py_None); - } + errno = 0; + len = confstr(name, buffer, sizeof(buffer)); + if (len == 0) { + if (errno) { + posix_error(); } else { - if ((unsigned int)len >= sizeof(buffer)) { - result = PyString_FromStringAndSize(NULL, len-1); - if (result != NULL) - confstr(name, PyString_AS_STRING(result), len); - } - else - result = PyString_FromStringAndSize(buffer, len-1); + result = Py_None; + Py_INCREF(Py_None); } } + else { + if ((unsigned int)len >= sizeof(buffer)) { + result = PyString_FromStringAndSize(NULL, len-1); + if (result != NULL) + confstr(name, PyString_AS_STRING(result), len); + } + else + result = PyString_FromStringAndSize(buffer, len-1); + } + } return result; } #endif @@ -7601,496 +7601,496 @@ #ifdef HAVE_SYSCONF static struct constdef posix_constants_sysconf[] = { #ifdef _SC_2_CHAR_TERM - {"SC_2_CHAR_TERM", _SC_2_CHAR_TERM}, + {"SC_2_CHAR_TERM", _SC_2_CHAR_TERM}, #endif #ifdef _SC_2_C_BIND - {"SC_2_C_BIND", _SC_2_C_BIND}, + {"SC_2_C_BIND", _SC_2_C_BIND}, #endif #ifdef _SC_2_C_DEV - {"SC_2_C_DEV", _SC_2_C_DEV}, + {"SC_2_C_DEV", _SC_2_C_DEV}, #endif #ifdef _SC_2_C_VERSION - {"SC_2_C_VERSION", _SC_2_C_VERSION}, + {"SC_2_C_VERSION", _SC_2_C_VERSION}, #endif #ifdef _SC_2_FORT_DEV - {"SC_2_FORT_DEV", _SC_2_FORT_DEV}, + {"SC_2_FORT_DEV", _SC_2_FORT_DEV}, #endif #ifdef _SC_2_FORT_RUN - {"SC_2_FORT_RUN", _SC_2_FORT_RUN}, + {"SC_2_FORT_RUN", _SC_2_FORT_RUN}, #endif #ifdef _SC_2_LOCALEDEF - {"SC_2_LOCALEDEF", _SC_2_LOCALEDEF}, + {"SC_2_LOCALEDEF", _SC_2_LOCALEDEF}, #endif #ifdef _SC_2_SW_DEV - {"SC_2_SW_DEV", _SC_2_SW_DEV}, + {"SC_2_SW_DEV", _SC_2_SW_DEV}, #endif #ifdef _SC_2_UPE - {"SC_2_UPE", _SC_2_UPE}, + {"SC_2_UPE", _SC_2_UPE}, #endif #ifdef _SC_2_VERSION - {"SC_2_VERSION", _SC_2_VERSION}, + {"SC_2_VERSION", _SC_2_VERSION}, #endif #ifdef _SC_ABI_ASYNCHRONOUS_IO - {"SC_ABI_ASYNCHRONOUS_IO", _SC_ABI_ASYNCHRONOUS_IO}, + {"SC_ABI_ASYNCHRONOUS_IO", _SC_ABI_ASYNCHRONOUS_IO}, #endif #ifdef _SC_ACL - {"SC_ACL", _SC_ACL}, + {"SC_ACL", _SC_ACL}, #endif #ifdef _SC_AIO_LISTIO_MAX - {"SC_AIO_LISTIO_MAX", _SC_AIO_LISTIO_MAX}, + {"SC_AIO_LISTIO_MAX", _SC_AIO_LISTIO_MAX}, #endif #ifdef _SC_AIO_MAX - {"SC_AIO_MAX", _SC_AIO_MAX}, + {"SC_AIO_MAX", _SC_AIO_MAX}, #endif #ifdef _SC_AIO_PRIO_DELTA_MAX - {"SC_AIO_PRIO_DELTA_MAX", _SC_AIO_PRIO_DELTA_MAX}, + {"SC_AIO_PRIO_DELTA_MAX", _SC_AIO_PRIO_DELTA_MAX}, #endif #ifdef _SC_ARG_MAX - {"SC_ARG_MAX", _SC_ARG_MAX}, + {"SC_ARG_MAX", _SC_ARG_MAX}, #endif #ifdef _SC_ASYNCHRONOUS_IO - {"SC_ASYNCHRONOUS_IO", _SC_ASYNCHRONOUS_IO}, + {"SC_ASYNCHRONOUS_IO", _SC_ASYNCHRONOUS_IO}, #endif #ifdef _SC_ATEXIT_MAX - {"SC_ATEXIT_MAX", _SC_ATEXIT_MAX}, + {"SC_ATEXIT_MAX", _SC_ATEXIT_MAX}, #endif #ifdef _SC_AUDIT - {"SC_AUDIT", _SC_AUDIT}, + {"SC_AUDIT", _SC_AUDIT}, #endif #ifdef _SC_AVPHYS_PAGES - {"SC_AVPHYS_PAGES", _SC_AVPHYS_PAGES}, + {"SC_AVPHYS_PAGES", _SC_AVPHYS_PAGES}, #endif #ifdef _SC_BC_BASE_MAX - {"SC_BC_BASE_MAX", _SC_BC_BASE_MAX}, + {"SC_BC_BASE_MAX", _SC_BC_BASE_MAX}, #endif #ifdef _SC_BC_DIM_MAX - {"SC_BC_DIM_MAX", _SC_BC_DIM_MAX}, + {"SC_BC_DIM_MAX", _SC_BC_DIM_MAX}, #endif #ifdef _SC_BC_SCALE_MAX - {"SC_BC_SCALE_MAX", _SC_BC_SCALE_MAX}, + {"SC_BC_SCALE_MAX", _SC_BC_SCALE_MAX}, #endif #ifdef _SC_BC_STRING_MAX - {"SC_BC_STRING_MAX", _SC_BC_STRING_MAX}, + {"SC_BC_STRING_MAX", _SC_BC_STRING_MAX}, #endif #ifdef _SC_CAP - {"SC_CAP", _SC_CAP}, + {"SC_CAP", _SC_CAP}, #endif #ifdef _SC_CHARCLASS_NAME_MAX - {"SC_CHARCLASS_NAME_MAX", _SC_CHARCLASS_NAME_MAX}, + {"SC_CHARCLASS_NAME_MAX", _SC_CHARCLASS_NAME_MAX}, #endif #ifdef _SC_CHAR_BIT - {"SC_CHAR_BIT", _SC_CHAR_BIT}, + {"SC_CHAR_BIT", _SC_CHAR_BIT}, #endif #ifdef _SC_CHAR_MAX - {"SC_CHAR_MAX", _SC_CHAR_MAX}, + {"SC_CHAR_MAX", _SC_CHAR_MAX}, #endif #ifdef _SC_CHAR_MIN - {"SC_CHAR_MIN", _SC_CHAR_MIN}, + {"SC_CHAR_MIN", _SC_CHAR_MIN}, #endif #ifdef _SC_CHILD_MAX - {"SC_CHILD_MAX", _SC_CHILD_MAX}, + {"SC_CHILD_MAX", _SC_CHILD_MAX}, #endif #ifdef _SC_CLK_TCK - {"SC_CLK_TCK", _SC_CLK_TCK}, + {"SC_CLK_TCK", _SC_CLK_TCK}, #endif #ifdef _SC_COHER_BLKSZ - {"SC_COHER_BLKSZ", _SC_COHER_BLKSZ}, + {"SC_COHER_BLKSZ", _SC_COHER_BLKSZ}, #endif #ifdef _SC_COLL_WEIGHTS_MAX - {"SC_COLL_WEIGHTS_MAX", _SC_COLL_WEIGHTS_MAX}, + {"SC_COLL_WEIGHTS_MAX", _SC_COLL_WEIGHTS_MAX}, #endif #ifdef _SC_DCACHE_ASSOC - {"SC_DCACHE_ASSOC", _SC_DCACHE_ASSOC}, + {"SC_DCACHE_ASSOC", _SC_DCACHE_ASSOC}, #endif #ifdef _SC_DCACHE_BLKSZ - {"SC_DCACHE_BLKSZ", _SC_DCACHE_BLKSZ}, + {"SC_DCACHE_BLKSZ", _SC_DCACHE_BLKSZ}, #endif #ifdef _SC_DCACHE_LINESZ - {"SC_DCACHE_LINESZ", _SC_DCACHE_LINESZ}, + {"SC_DCACHE_LINESZ", _SC_DCACHE_LINESZ}, #endif #ifdef _SC_DCACHE_SZ - {"SC_DCACHE_SZ", _SC_DCACHE_SZ}, + {"SC_DCACHE_SZ", _SC_DCACHE_SZ}, #endif #ifdef _SC_DCACHE_TBLKSZ - {"SC_DCACHE_TBLKSZ", _SC_DCACHE_TBLKSZ}, + {"SC_DCACHE_TBLKSZ", _SC_DCACHE_TBLKSZ}, #endif #ifdef _SC_DELAYTIMER_MAX - {"SC_DELAYTIMER_MAX", _SC_DELAYTIMER_MAX}, + {"SC_DELAYTIMER_MAX", _SC_DELAYTIMER_MAX}, #endif #ifdef _SC_EQUIV_CLASS_MAX - {"SC_EQUIV_CLASS_MAX", _SC_EQUIV_CLASS_MAX}, + {"SC_EQUIV_CLASS_MAX", _SC_EQUIV_CLASS_MAX}, #endif #ifdef _SC_EXPR_NEST_MAX - {"SC_EXPR_NEST_MAX", _SC_EXPR_NEST_MAX}, + {"SC_EXPR_NEST_MAX", _SC_EXPR_NEST_MAX}, #endif #ifdef _SC_FSYNC - {"SC_FSYNC", _SC_FSYNC}, + {"SC_FSYNC", _SC_FSYNC}, #endif #ifdef _SC_GETGR_R_SIZE_MAX - {"SC_GETGR_R_SIZE_MAX", _SC_GETGR_R_SIZE_MAX}, + {"SC_GETGR_R_SIZE_MAX", _SC_GETGR_R_SIZE_MAX}, #endif #ifdef _SC_GETPW_R_SIZE_MAX - {"SC_GETPW_R_SIZE_MAX", _SC_GETPW_R_SIZE_MAX}, + {"SC_GETPW_R_SIZE_MAX", _SC_GETPW_R_SIZE_MAX}, #endif #ifdef _SC_ICACHE_ASSOC - {"SC_ICACHE_ASSOC", _SC_ICACHE_ASSOC}, + {"SC_ICACHE_ASSOC", _SC_ICACHE_ASSOC}, #endif #ifdef _SC_ICACHE_BLKSZ - {"SC_ICACHE_BLKSZ", _SC_ICACHE_BLKSZ}, + {"SC_ICACHE_BLKSZ", _SC_ICACHE_BLKSZ}, #endif #ifdef _SC_ICACHE_LINESZ - {"SC_ICACHE_LINESZ", _SC_ICACHE_LINESZ}, + {"SC_ICACHE_LINESZ", _SC_ICACHE_LINESZ}, #endif #ifdef _SC_ICACHE_SZ - {"SC_ICACHE_SZ", _SC_ICACHE_SZ}, + {"SC_ICACHE_SZ", _SC_ICACHE_SZ}, #endif #ifdef _SC_INF - {"SC_INF", _SC_INF}, + {"SC_INF", _SC_INF}, #endif #ifdef _SC_INT_MAX - {"SC_INT_MAX", _SC_INT_MAX}, + {"SC_INT_MAX", _SC_INT_MAX}, #endif #ifdef _SC_INT_MIN - {"SC_INT_MIN", _SC_INT_MIN}, + {"SC_INT_MIN", _SC_INT_MIN}, #endif #ifdef _SC_IOV_MAX - {"SC_IOV_MAX", _SC_IOV_MAX}, + {"SC_IOV_MAX", _SC_IOV_MAX}, #endif #ifdef _SC_IP_SECOPTS - {"SC_IP_SECOPTS", _SC_IP_SECOPTS}, + {"SC_IP_SECOPTS", _SC_IP_SECOPTS}, #endif #ifdef _SC_JOB_CONTROL - {"SC_JOB_CONTROL", _SC_JOB_CONTROL}, + {"SC_JOB_CONTROL", _SC_JOB_CONTROL}, #endif #ifdef _SC_KERN_POINTERS - {"SC_KERN_POINTERS", _SC_KERN_POINTERS}, + {"SC_KERN_POINTERS", _SC_KERN_POINTERS}, #endif #ifdef _SC_KERN_SIM - {"SC_KERN_SIM", _SC_KERN_SIM}, + {"SC_KERN_SIM", _SC_KERN_SIM}, #endif #ifdef _SC_LINE_MAX - {"SC_LINE_MAX", _SC_LINE_MAX}, + {"SC_LINE_MAX", _SC_LINE_MAX}, #endif #ifdef _SC_LOGIN_NAME_MAX - {"SC_LOGIN_NAME_MAX", _SC_LOGIN_NAME_MAX}, + {"SC_LOGIN_NAME_MAX", _SC_LOGIN_NAME_MAX}, #endif #ifdef _SC_LOGNAME_MAX - {"SC_LOGNAME_MAX", _SC_LOGNAME_MAX}, + {"SC_LOGNAME_MAX", _SC_LOGNAME_MAX}, #endif #ifdef _SC_LONG_BIT - {"SC_LONG_BIT", _SC_LONG_BIT}, + {"SC_LONG_BIT", _SC_LONG_BIT}, #endif #ifdef _SC_MAC - {"SC_MAC", _SC_MAC}, + {"SC_MAC", _SC_MAC}, #endif #ifdef _SC_MAPPED_FILES - {"SC_MAPPED_FILES", _SC_MAPPED_FILES}, + {"SC_MAPPED_FILES", _SC_MAPPED_FILES}, #endif #ifdef _SC_MAXPID - {"SC_MAXPID", _SC_MAXPID}, + {"SC_MAXPID", _SC_MAXPID}, #endif #ifdef _SC_MB_LEN_MAX - {"SC_MB_LEN_MAX", _SC_MB_LEN_MAX}, + {"SC_MB_LEN_MAX", _SC_MB_LEN_MAX}, #endif #ifdef _SC_MEMLOCK - {"SC_MEMLOCK", _SC_MEMLOCK}, + {"SC_MEMLOCK", _SC_MEMLOCK}, #endif #ifdef _SC_MEMLOCK_RANGE - {"SC_MEMLOCK_RANGE", _SC_MEMLOCK_RANGE}, + {"SC_MEMLOCK_RANGE", _SC_MEMLOCK_RANGE}, #endif #ifdef _SC_MEMORY_PROTECTION - {"SC_MEMORY_PROTECTION", _SC_MEMORY_PROTECTION}, + {"SC_MEMORY_PROTECTION", _SC_MEMORY_PROTECTION}, #endif #ifdef _SC_MESSAGE_PASSING - {"SC_MESSAGE_PASSING", _SC_MESSAGE_PASSING}, + {"SC_MESSAGE_PASSING", _SC_MESSAGE_PASSING}, #endif #ifdef _SC_MMAP_FIXED_ALIGNMENT - {"SC_MMAP_FIXED_ALIGNMENT", _SC_MMAP_FIXED_ALIGNMENT}, + {"SC_MMAP_FIXED_ALIGNMENT", _SC_MMAP_FIXED_ALIGNMENT}, #endif #ifdef _SC_MQ_OPEN_MAX - {"SC_MQ_OPEN_MAX", _SC_MQ_OPEN_MAX}, + {"SC_MQ_OPEN_MAX", _SC_MQ_OPEN_MAX}, #endif #ifdef _SC_MQ_PRIO_MAX - {"SC_MQ_PRIO_MAX", _SC_MQ_PRIO_MAX}, + {"SC_MQ_PRIO_MAX", _SC_MQ_PRIO_MAX}, #endif #ifdef _SC_NACLS_MAX - {"SC_NACLS_MAX", _SC_NACLS_MAX}, + {"SC_NACLS_MAX", _SC_NACLS_MAX}, #endif #ifdef _SC_NGROUPS_MAX - {"SC_NGROUPS_MAX", _SC_NGROUPS_MAX}, + {"SC_NGROUPS_MAX", _SC_NGROUPS_MAX}, #endif #ifdef _SC_NL_ARGMAX - {"SC_NL_ARGMAX", _SC_NL_ARGMAX}, + {"SC_NL_ARGMAX", _SC_NL_ARGMAX}, #endif #ifdef _SC_NL_LANGMAX - {"SC_NL_LANGMAX", _SC_NL_LANGMAX}, + {"SC_NL_LANGMAX", _SC_NL_LANGMAX}, #endif #ifdef _SC_NL_MSGMAX - {"SC_NL_MSGMAX", _SC_NL_MSGMAX}, + {"SC_NL_MSGMAX", _SC_NL_MSGMAX}, #endif #ifdef _SC_NL_NMAX - {"SC_NL_NMAX", _SC_NL_NMAX}, + {"SC_NL_NMAX", _SC_NL_NMAX}, #endif #ifdef _SC_NL_SETMAX - {"SC_NL_SETMAX", _SC_NL_SETMAX}, + {"SC_NL_SETMAX", _SC_NL_SETMAX}, #endif #ifdef _SC_NL_TEXTMAX - {"SC_NL_TEXTMAX", _SC_NL_TEXTMAX}, + {"SC_NL_TEXTMAX", _SC_NL_TEXTMAX}, #endif #ifdef _SC_NPROCESSORS_CONF - {"SC_NPROCESSORS_CONF", _SC_NPROCESSORS_CONF}, + {"SC_NPROCESSORS_CONF", _SC_NPROCESSORS_CONF}, #endif #ifdef _SC_NPROCESSORS_ONLN - {"SC_NPROCESSORS_ONLN", _SC_NPROCESSORS_ONLN}, + {"SC_NPROCESSORS_ONLN", _SC_NPROCESSORS_ONLN}, #endif #ifdef _SC_NPROC_CONF - {"SC_NPROC_CONF", _SC_NPROC_CONF}, + {"SC_NPROC_CONF", _SC_NPROC_CONF}, #endif #ifdef _SC_NPROC_ONLN - {"SC_NPROC_ONLN", _SC_NPROC_ONLN}, + {"SC_NPROC_ONLN", _SC_NPROC_ONLN}, #endif #ifdef _SC_NZERO - {"SC_NZERO", _SC_NZERO}, + {"SC_NZERO", _SC_NZERO}, #endif #ifdef _SC_OPEN_MAX - {"SC_OPEN_MAX", _SC_OPEN_MAX}, + {"SC_OPEN_MAX", _SC_OPEN_MAX}, #endif #ifdef _SC_PAGESIZE - {"SC_PAGESIZE", _SC_PAGESIZE}, + {"SC_PAGESIZE", _SC_PAGESIZE}, #endif #ifdef _SC_PAGE_SIZE - {"SC_PAGE_SIZE", _SC_PAGE_SIZE}, + {"SC_PAGE_SIZE", _SC_PAGE_SIZE}, #endif #ifdef _SC_PASS_MAX - {"SC_PASS_MAX", _SC_PASS_MAX}, + {"SC_PASS_MAX", _SC_PASS_MAX}, #endif #ifdef _SC_PHYS_PAGES - {"SC_PHYS_PAGES", _SC_PHYS_PAGES}, + {"SC_PHYS_PAGES", _SC_PHYS_PAGES}, #endif #ifdef _SC_PII - {"SC_PII", _SC_PII}, + {"SC_PII", _SC_PII}, #endif #ifdef _SC_PII_INTERNET - {"SC_PII_INTERNET", _SC_PII_INTERNET}, + {"SC_PII_INTERNET", _SC_PII_INTERNET}, #endif #ifdef _SC_PII_INTERNET_DGRAM - {"SC_PII_INTERNET_DGRAM", _SC_PII_INTERNET_DGRAM}, + {"SC_PII_INTERNET_DGRAM", _SC_PII_INTERNET_DGRAM}, #endif #ifdef _SC_PII_INTERNET_STREAM - {"SC_PII_INTERNET_STREAM", _SC_PII_INTERNET_STREAM}, + {"SC_PII_INTERNET_STREAM", _SC_PII_INTERNET_STREAM}, #endif #ifdef _SC_PII_OSI - {"SC_PII_OSI", _SC_PII_OSI}, + {"SC_PII_OSI", _SC_PII_OSI}, #endif #ifdef _SC_PII_OSI_CLTS - {"SC_PII_OSI_CLTS", _SC_PII_OSI_CLTS}, + {"SC_PII_OSI_CLTS", _SC_PII_OSI_CLTS}, #endif #ifdef _SC_PII_OSI_COTS - {"SC_PII_OSI_COTS", _SC_PII_OSI_COTS}, + {"SC_PII_OSI_COTS", _SC_PII_OSI_COTS}, #endif #ifdef _SC_PII_OSI_M - {"SC_PII_OSI_M", _SC_PII_OSI_M}, + {"SC_PII_OSI_M", _SC_PII_OSI_M}, #endif #ifdef _SC_PII_SOCKET - {"SC_PII_SOCKET", _SC_PII_SOCKET}, + {"SC_PII_SOCKET", _SC_PII_SOCKET}, #endif #ifdef _SC_PII_XTI - {"SC_PII_XTI", _SC_PII_XTI}, + {"SC_PII_XTI", _SC_PII_XTI}, #endif #ifdef _SC_POLL - {"SC_POLL", _SC_POLL}, + {"SC_POLL", _SC_POLL}, #endif #ifdef _SC_PRIORITIZED_IO - {"SC_PRIORITIZED_IO", _SC_PRIORITIZED_IO}, + {"SC_PRIORITIZED_IO", _SC_PRIORITIZED_IO}, #endif #ifdef _SC_PRIORITY_SCHEDULING - {"SC_PRIORITY_SCHEDULING", _SC_PRIORITY_SCHEDULING}, + {"SC_PRIORITY_SCHEDULING", _SC_PRIORITY_SCHEDULING}, #endif #ifdef _SC_REALTIME_SIGNALS - {"SC_REALTIME_SIGNALS", _SC_REALTIME_SIGNALS}, + {"SC_REALTIME_SIGNALS", _SC_REALTIME_SIGNALS}, #endif #ifdef _SC_RE_DUP_MAX - {"SC_RE_DUP_MAX", _SC_RE_DUP_MAX}, + {"SC_RE_DUP_MAX", _SC_RE_DUP_MAX}, #endif #ifdef _SC_RTSIG_MAX - {"SC_RTSIG_MAX", _SC_RTSIG_MAX}, + {"SC_RTSIG_MAX", _SC_RTSIG_MAX}, #endif #ifdef _SC_SAVED_IDS - {"SC_SAVED_IDS", _SC_SAVED_IDS}, + {"SC_SAVED_IDS", _SC_SAVED_IDS}, #endif #ifdef _SC_SCHAR_MAX - {"SC_SCHAR_MAX", _SC_SCHAR_MAX}, + {"SC_SCHAR_MAX", _SC_SCHAR_MAX}, #endif #ifdef _SC_SCHAR_MIN - {"SC_SCHAR_MIN", _SC_SCHAR_MIN}, + {"SC_SCHAR_MIN", _SC_SCHAR_MIN}, #endif #ifdef _SC_SELECT - {"SC_SELECT", _SC_SELECT}, + {"SC_SELECT", _SC_SELECT}, #endif #ifdef _SC_SEMAPHORES - {"SC_SEMAPHORES", _SC_SEMAPHORES}, + {"SC_SEMAPHORES", _SC_SEMAPHORES}, #endif #ifdef _SC_SEM_NSEMS_MAX - {"SC_SEM_NSEMS_MAX", _SC_SEM_NSEMS_MAX}, + {"SC_SEM_NSEMS_MAX", _SC_SEM_NSEMS_MAX}, #endif #ifdef _SC_SEM_VALUE_MAX - {"SC_SEM_VALUE_MAX", _SC_SEM_VALUE_MAX}, + {"SC_SEM_VALUE_MAX", _SC_SEM_VALUE_MAX}, #endif #ifdef _SC_SHARED_MEMORY_OBJECTS - {"SC_SHARED_MEMORY_OBJECTS", _SC_SHARED_MEMORY_OBJECTS}, + {"SC_SHARED_MEMORY_OBJECTS", _SC_SHARED_MEMORY_OBJECTS}, #endif #ifdef _SC_SHRT_MAX - {"SC_SHRT_MAX", _SC_SHRT_MAX}, + {"SC_SHRT_MAX", _SC_SHRT_MAX}, #endif #ifdef _SC_SHRT_MIN - {"SC_SHRT_MIN", _SC_SHRT_MIN}, + {"SC_SHRT_MIN", _SC_SHRT_MIN}, #endif #ifdef _SC_SIGQUEUE_MAX - {"SC_SIGQUEUE_MAX", _SC_SIGQUEUE_MAX}, + {"SC_SIGQUEUE_MAX", _SC_SIGQUEUE_MAX}, #endif #ifdef _SC_SIGRT_MAX - {"SC_SIGRT_MAX", _SC_SIGRT_MAX}, + {"SC_SIGRT_MAX", _SC_SIGRT_MAX}, #endif #ifdef _SC_SIGRT_MIN - {"SC_SIGRT_MIN", _SC_SIGRT_MIN}, + {"SC_SIGRT_MIN", _SC_SIGRT_MIN}, #endif #ifdef _SC_SOFTPOWER - {"SC_SOFTPOWER", _SC_SOFTPOWER}, + {"SC_SOFTPOWER", _SC_SOFTPOWER}, #endif #ifdef _SC_SPLIT_CACHE - {"SC_SPLIT_CACHE", _SC_SPLIT_CACHE}, + {"SC_SPLIT_CACHE", _SC_SPLIT_CACHE}, #endif #ifdef _SC_SSIZE_MAX - {"SC_SSIZE_MAX", _SC_SSIZE_MAX}, + {"SC_SSIZE_MAX", _SC_SSIZE_MAX}, #endif #ifdef _SC_STACK_PROT - {"SC_STACK_PROT", _SC_STACK_PROT}, + {"SC_STACK_PROT", _SC_STACK_PROT}, #endif #ifdef _SC_STREAM_MAX - {"SC_STREAM_MAX", _SC_STREAM_MAX}, + {"SC_STREAM_MAX", _SC_STREAM_MAX}, #endif #ifdef _SC_SYNCHRONIZED_IO - {"SC_SYNCHRONIZED_IO", _SC_SYNCHRONIZED_IO}, + {"SC_SYNCHRONIZED_IO", _SC_SYNCHRONIZED_IO}, #endif #ifdef _SC_THREADS - {"SC_THREADS", _SC_THREADS}, + {"SC_THREADS", _SC_THREADS}, #endif #ifdef _SC_THREAD_ATTR_STACKADDR - {"SC_THREAD_ATTR_STACKADDR", _SC_THREAD_ATTR_STACKADDR}, + {"SC_THREAD_ATTR_STACKADDR", _SC_THREAD_ATTR_STACKADDR}, #endif #ifdef _SC_THREAD_ATTR_STACKSIZE - {"SC_THREAD_ATTR_STACKSIZE", _SC_THREAD_ATTR_STACKSIZE}, + {"SC_THREAD_ATTR_STACKSIZE", _SC_THREAD_ATTR_STACKSIZE}, #endif #ifdef _SC_THREAD_DESTRUCTOR_ITERATIONS - {"SC_THREAD_DESTRUCTOR_ITERATIONS", _SC_THREAD_DESTRUCTOR_ITERATIONS}, + {"SC_THREAD_DESTRUCTOR_ITERATIONS", _SC_THREAD_DESTRUCTOR_ITERATIONS}, #endif #ifdef _SC_THREAD_KEYS_MAX - {"SC_THREAD_KEYS_MAX", _SC_THREAD_KEYS_MAX}, + {"SC_THREAD_KEYS_MAX", _SC_THREAD_KEYS_MAX}, #endif #ifdef _SC_THREAD_PRIORITY_SCHEDULING - {"SC_THREAD_PRIORITY_SCHEDULING", _SC_THREAD_PRIORITY_SCHEDULING}, + {"SC_THREAD_PRIORITY_SCHEDULING", _SC_THREAD_PRIORITY_SCHEDULING}, #endif #ifdef _SC_THREAD_PRIO_INHERIT - {"SC_THREAD_PRIO_INHERIT", _SC_THREAD_PRIO_INHERIT}, + {"SC_THREAD_PRIO_INHERIT", _SC_THREAD_PRIO_INHERIT}, #endif #ifdef _SC_THREAD_PRIO_PROTECT - {"SC_THREAD_PRIO_PROTECT", _SC_THREAD_PRIO_PROTECT}, + {"SC_THREAD_PRIO_PROTECT", _SC_THREAD_PRIO_PROTECT}, #endif #ifdef _SC_THREAD_PROCESS_SHARED - {"SC_THREAD_PROCESS_SHARED", _SC_THREAD_PROCESS_SHARED}, + {"SC_THREAD_PROCESS_SHARED", _SC_THREAD_PROCESS_SHARED}, #endif #ifdef _SC_THREAD_SAFE_FUNCTIONS - {"SC_THREAD_SAFE_FUNCTIONS", _SC_THREAD_SAFE_FUNCTIONS}, + {"SC_THREAD_SAFE_FUNCTIONS", _SC_THREAD_SAFE_FUNCTIONS}, #endif #ifdef _SC_THREAD_STACK_MIN - {"SC_THREAD_STACK_MIN", _SC_THREAD_STACK_MIN}, + {"SC_THREAD_STACK_MIN", _SC_THREAD_STACK_MIN}, #endif #ifdef _SC_THREAD_THREADS_MAX - {"SC_THREAD_THREADS_MAX", _SC_THREAD_THREADS_MAX}, + {"SC_THREAD_THREADS_MAX", _SC_THREAD_THREADS_MAX}, #endif #ifdef _SC_TIMERS - {"SC_TIMERS", _SC_TIMERS}, + {"SC_TIMERS", _SC_TIMERS}, #endif #ifdef _SC_TIMER_MAX - {"SC_TIMER_MAX", _SC_TIMER_MAX}, + {"SC_TIMER_MAX", _SC_TIMER_MAX}, #endif #ifdef _SC_TTY_NAME_MAX - {"SC_TTY_NAME_MAX", _SC_TTY_NAME_MAX}, + {"SC_TTY_NAME_MAX", _SC_TTY_NAME_MAX}, #endif #ifdef _SC_TZNAME_MAX - {"SC_TZNAME_MAX", _SC_TZNAME_MAX}, + {"SC_TZNAME_MAX", _SC_TZNAME_MAX}, #endif #ifdef _SC_T_IOV_MAX - {"SC_T_IOV_MAX", _SC_T_IOV_MAX}, + {"SC_T_IOV_MAX", _SC_T_IOV_MAX}, #endif #ifdef _SC_UCHAR_MAX - {"SC_UCHAR_MAX", _SC_UCHAR_MAX}, + {"SC_UCHAR_MAX", _SC_UCHAR_MAX}, #endif #ifdef _SC_UINT_MAX - {"SC_UINT_MAX", _SC_UINT_MAX}, + {"SC_UINT_MAX", _SC_UINT_MAX}, #endif #ifdef _SC_UIO_MAXIOV - {"SC_UIO_MAXIOV", _SC_UIO_MAXIOV}, + {"SC_UIO_MAXIOV", _SC_UIO_MAXIOV}, #endif #ifdef _SC_ULONG_MAX - {"SC_ULONG_MAX", _SC_ULONG_MAX}, + {"SC_ULONG_MAX", _SC_ULONG_MAX}, #endif #ifdef _SC_USHRT_MAX - {"SC_USHRT_MAX", _SC_USHRT_MAX}, + {"SC_USHRT_MAX", _SC_USHRT_MAX}, #endif #ifdef _SC_VERSION - {"SC_VERSION", _SC_VERSION}, + {"SC_VERSION", _SC_VERSION}, #endif #ifdef _SC_WORD_BIT - {"SC_WORD_BIT", _SC_WORD_BIT}, + {"SC_WORD_BIT", _SC_WORD_BIT}, #endif #ifdef _SC_XBS5_ILP32_OFF32 - {"SC_XBS5_ILP32_OFF32", _SC_XBS5_ILP32_OFF32}, + {"SC_XBS5_ILP32_OFF32", _SC_XBS5_ILP32_OFF32}, #endif #ifdef _SC_XBS5_ILP32_OFFBIG - {"SC_XBS5_ILP32_OFFBIG", _SC_XBS5_ILP32_OFFBIG}, + {"SC_XBS5_ILP32_OFFBIG", _SC_XBS5_ILP32_OFFBIG}, #endif #ifdef _SC_XBS5_LP64_OFF64 - {"SC_XBS5_LP64_OFF64", _SC_XBS5_LP64_OFF64}, + {"SC_XBS5_LP64_OFF64", _SC_XBS5_LP64_OFF64}, #endif #ifdef _SC_XBS5_LPBIG_OFFBIG - {"SC_XBS5_LPBIG_OFFBIG", _SC_XBS5_LPBIG_OFFBIG}, + {"SC_XBS5_LPBIG_OFFBIG", _SC_XBS5_LPBIG_OFFBIG}, #endif #ifdef _SC_XOPEN_CRYPT - {"SC_XOPEN_CRYPT", _SC_XOPEN_CRYPT}, + {"SC_XOPEN_CRYPT", _SC_XOPEN_CRYPT}, #endif #ifdef _SC_XOPEN_ENH_I18N - {"SC_XOPEN_ENH_I18N", _SC_XOPEN_ENH_I18N}, + {"SC_XOPEN_ENH_I18N", _SC_XOPEN_ENH_I18N}, #endif #ifdef _SC_XOPEN_LEGACY - {"SC_XOPEN_LEGACY", _SC_XOPEN_LEGACY}, + {"SC_XOPEN_LEGACY", _SC_XOPEN_LEGACY}, #endif #ifdef _SC_XOPEN_REALTIME - {"SC_XOPEN_REALTIME", _SC_XOPEN_REALTIME}, + {"SC_XOPEN_REALTIME", _SC_XOPEN_REALTIME}, #endif #ifdef _SC_XOPEN_REALTIME_THREADS - {"SC_XOPEN_REALTIME_THREADS", _SC_XOPEN_REALTIME_THREADS}, + {"SC_XOPEN_REALTIME_THREADS", _SC_XOPEN_REALTIME_THREADS}, #endif #ifdef _SC_XOPEN_SHM - {"SC_XOPEN_SHM", _SC_XOPEN_SHM}, + {"SC_XOPEN_SHM", _SC_XOPEN_SHM}, #endif #ifdef _SC_XOPEN_UNIX - {"SC_XOPEN_UNIX", _SC_XOPEN_UNIX}, + {"SC_XOPEN_UNIX", _SC_XOPEN_UNIX}, #endif #ifdef _SC_XOPEN_VERSION - {"SC_XOPEN_VERSION", _SC_XOPEN_VERSION}, + {"SC_XOPEN_VERSION", _SC_XOPEN_VERSION}, #endif #ifdef _SC_XOPEN_XCU_VERSION - {"SC_XOPEN_XCU_VERSION", _SC_XOPEN_XCU_VERSION}, + {"SC_XOPEN_XCU_VERSION", _SC_XOPEN_XCU_VERSION}, #endif #ifdef _SC_XOPEN_XPG2 - {"SC_XOPEN_XPG2", _SC_XOPEN_XPG2}, + {"SC_XOPEN_XPG2", _SC_XOPEN_XPG2}, #endif #ifdef _SC_XOPEN_XPG3 - {"SC_XOPEN_XPG3", _SC_XOPEN_XPG3}, + {"SC_XOPEN_XPG3", _SC_XOPEN_XPG3}, #endif #ifdef _SC_XOPEN_XPG4 - {"SC_XOPEN_XPG4", _SC_XOPEN_XPG4}, + {"SC_XOPEN_XPG4", _SC_XOPEN_XPG4}, #endif }; @@ -8141,16 +8141,16 @@ cmp_constdefs(const void *v1, const void *v2) { const struct constdef *c1 = - (const struct constdef *) v1; + (const struct constdef *) v1; const struct constdef *c2 = - (const struct constdef *) v2; + (const struct constdef *) v2; return strcmp(c1->name, c2->name); } static int setup_confname_table(struct constdef *table, size_t tablesize, - char *tablename, PyObject *module) + char *tablename, PyObject *module) { PyObject *d = NULL; size_t i; @@ -8158,16 +8158,16 @@ qsort(table, tablesize, sizeof(struct constdef), cmp_constdefs); d = PyDict_New(); if (d == NULL) - return -1; + return -1; for (i=0; i < tablesize; ++i) { - PyObject *o = PyInt_FromLong(table[i].value); - if (o == NULL || PyDict_SetItemString(d, table[i].name, o) == -1) { - Py_XDECREF(o); - Py_DECREF(d); - return -1; - } - Py_DECREF(o); + PyObject *o = PyInt_FromLong(table[i].value); + if (o == NULL || PyDict_SetItemString(d, table[i].name, o) == -1) { + Py_XDECREF(o); + Py_DECREF(d); + return -1; + } + Py_DECREF(o); } return PyModule_AddObject(module, tablename, d); } @@ -8181,21 +8181,21 @@ sizeof(posix_constants_pathconf) / sizeof(struct constdef), "pathconf_names", module)) - return -1; + return -1; #endif #ifdef HAVE_CONFSTR if (setup_confname_table(posix_constants_confstr, sizeof(posix_constants_confstr) / sizeof(struct constdef), "confstr_names", module)) - return -1; + return -1; #endif #ifdef HAVE_SYSCONF if (setup_confname_table(posix_constants_sysconf, sizeof(posix_constants_sysconf) / sizeof(struct constdef), "sysconf_names", module)) - return -1; + return -1; #endif return 0; } @@ -8238,63 +8238,63 @@ static PyObject * win32_startfile(PyObject *self, PyObject *args) { - char *filepath; - char *operation = NULL; - HINSTANCE rc; + char *filepath; + char *operation = NULL; + HINSTANCE rc; #ifdef Py_WIN_WIDE_FILENAMES - if (unicode_file_names()) { - PyObject *unipath, *woperation = NULL; - if (!PyArg_ParseTuple(args, "U|s:startfile", - &unipath, &operation)) { - PyErr_Clear(); - goto normal; - } - - - if (operation) { - woperation = PyUnicode_DecodeASCII(operation, - strlen(operation), NULL); - if (!woperation) { - PyErr_Clear(); - operation = NULL; - goto normal; - } - } - - Py_BEGIN_ALLOW_THREADS - rc = ShellExecuteW((HWND)0, woperation ? PyUnicode_AS_UNICODE(woperation) : 0, - PyUnicode_AS_UNICODE(unipath), - NULL, NULL, SW_SHOWNORMAL); - Py_END_ALLOW_THREADS - - Py_XDECREF(woperation); - if (rc <= (HINSTANCE)32) { - PyObject *errval = win32_error_unicode("startfile", - PyUnicode_AS_UNICODE(unipath)); - return errval; - } - Py_INCREF(Py_None); - return Py_None; - } + if (unicode_file_names()) { + PyObject *unipath, *woperation = NULL; + if (!PyArg_ParseTuple(args, "U|s:startfile", + &unipath, &operation)) { + PyErr_Clear(); + goto normal; + } + + + if (operation) { + woperation = PyUnicode_DecodeASCII(operation, + strlen(operation), NULL); + if (!woperation) { + PyErr_Clear(); + operation = NULL; + goto normal; + } + } + + Py_BEGIN_ALLOW_THREADS + rc = ShellExecuteW((HWND)0, woperation ? PyUnicode_AS_UNICODE(woperation) : 0, + PyUnicode_AS_UNICODE(unipath), + NULL, NULL, SW_SHOWNORMAL); + Py_END_ALLOW_THREADS + + Py_XDECREF(woperation); + if (rc <= (HINSTANCE)32) { + PyObject *errval = win32_error_unicode("startfile", + PyUnicode_AS_UNICODE(unipath)); + return errval; + } + Py_INCREF(Py_None); + return Py_None; + } #endif normal: - if (!PyArg_ParseTuple(args, "et|s:startfile", - Py_FileSystemDefaultEncoding, &filepath, - &operation)) - return NULL; - Py_BEGIN_ALLOW_THREADS - rc = ShellExecute((HWND)0, operation, filepath, - NULL, NULL, SW_SHOWNORMAL); - Py_END_ALLOW_THREADS - if (rc <= (HINSTANCE)32) { - PyObject *errval = win32_error("startfile", filepath); - PyMem_Free(filepath); - return errval; - } - PyMem_Free(filepath); - Py_INCREF(Py_None); - return Py_None; + if (!PyArg_ParseTuple(args, "et|s:startfile", + Py_FileSystemDefaultEncoding, &filepath, + &operation)) + return NULL; + Py_BEGIN_ALLOW_THREADS + rc = ShellExecute((HWND)0, operation, filepath, + NULL, NULL, SW_SHOWNORMAL); + Py_END_ALLOW_THREADS + if (rc <= (HINSTANCE)32) { + PyObject *errval = win32_error("startfile", filepath); + PyMem_Free(filepath); + return errval; + } + PyMem_Free(filepath); + Py_INCREF(Py_None); + return Py_None; } #endif @@ -8310,10 +8310,10 @@ { double loadavg[3]; if (getloadavg(loadavg, 3)!=3) { - PyErr_SetString(PyExc_OSError, "Load averages are unobtainable"); - return NULL; + PyErr_SetString(PyExc_OSError, "Load averages are unobtainable"); + return NULL; } else - return Py_BuildValue("ddd", loadavg[0], loadavg[1], loadavg[2]); + return Py_BuildValue("ddd", loadavg[0], loadavg[1], loadavg[2]); } #endif @@ -8337,59 +8337,59 @@ static PyObject* win32_urandom(PyObject *self, PyObject *args) { - int howMany; - PyObject* result; + int howMany; + PyObject* result; + + /* Read arguments */ + if (! PyArg_ParseTuple(args, "i:urandom", &howMany)) + return NULL; + if (howMany < 0) + return PyErr_Format(PyExc_ValueError, + "negative argument not allowed"); + + if (hCryptProv == 0) { + HINSTANCE hAdvAPI32 = NULL; + CRYPTACQUIRECONTEXTA pCryptAcquireContext = NULL; + + /* Obtain handle to the DLL containing CryptoAPI + This should not fail */ + hAdvAPI32 = GetModuleHandle("advapi32.dll"); + if(hAdvAPI32 == NULL) + return win32_error("GetModuleHandle", NULL); + + /* Obtain pointers to the CryptoAPI functions + This will fail on some early versions of Win95 */ + pCryptAcquireContext = (CRYPTACQUIRECONTEXTA)GetProcAddress( + hAdvAPI32, + "CryptAcquireContextA"); + if (pCryptAcquireContext == NULL) + return PyErr_Format(PyExc_NotImplementedError, + "CryptAcquireContextA not found"); + + pCryptGenRandom = (CRYPTGENRANDOM)GetProcAddress( + hAdvAPI32, "CryptGenRandom"); + if (pCryptGenRandom == NULL) + return PyErr_Format(PyExc_NotImplementedError, + "CryptGenRandom not found"); + + /* Acquire context */ + if (! pCryptAcquireContext(&hCryptProv, NULL, NULL, + PROV_RSA_FULL, CRYPT_VERIFYCONTEXT)) + return win32_error("CryptAcquireContext", NULL); + } - /* Read arguments */ - if (! PyArg_ParseTuple(args, "i:urandom", &howMany)) - return NULL; - if (howMany < 0) - return PyErr_Format(PyExc_ValueError, - "negative argument not allowed"); - - if (hCryptProv == 0) { - HINSTANCE hAdvAPI32 = NULL; - CRYPTACQUIRECONTEXTA pCryptAcquireContext = NULL; - - /* Obtain handle to the DLL containing CryptoAPI - This should not fail */ - hAdvAPI32 = GetModuleHandle("advapi32.dll"); - if(hAdvAPI32 == NULL) - return win32_error("GetModuleHandle", NULL); - - /* Obtain pointers to the CryptoAPI functions - This will fail on some early versions of Win95 */ - pCryptAcquireContext = (CRYPTACQUIRECONTEXTA)GetProcAddress( - hAdvAPI32, - "CryptAcquireContextA"); - if (pCryptAcquireContext == NULL) - return PyErr_Format(PyExc_NotImplementedError, - "CryptAcquireContextA not found"); - - pCryptGenRandom = (CRYPTGENRANDOM)GetProcAddress( - hAdvAPI32, "CryptGenRandom"); - if (pCryptGenRandom == NULL) - return PyErr_Format(PyExc_NotImplementedError, - "CryptGenRandom not found"); - - /* Acquire context */ - if (! pCryptAcquireContext(&hCryptProv, NULL, NULL, - PROV_RSA_FULL, CRYPT_VERIFYCONTEXT)) - return win32_error("CryptAcquireContext", NULL); - } - - /* Allocate bytes */ - result = PyString_FromStringAndSize(NULL, howMany); - if (result != NULL) { - /* Get random data */ - memset(PyString_AS_STRING(result), 0, howMany); /* zero seed */ - if (! pCryptGenRandom(hCryptProv, howMany, (unsigned char*) - PyString_AS_STRING(result))) { - Py_DECREF(result); - return win32_error("CryptGenRandom", NULL); - } - } - return result; + /* Allocate bytes */ + result = PyString_FromStringAndSize(NULL, howMany); + if (result != NULL) { + /* Get random data */ + memset(PyString_AS_STRING(result), 0, howMany); /* zero seed */ + if (! pCryptGenRandom(hCryptProv, howMany, (unsigned char*) + PyString_AS_STRING(result))) { + Py_DECREF(result); + return win32_error("CryptGenRandom", NULL); + } + } + return result; } #endif @@ -8403,350 +8403,350 @@ static PyObject* vms_urandom(PyObject *self, PyObject *args) { - int howMany; - PyObject* result; + int howMany; + PyObject* result; - /* Read arguments */ - if (! PyArg_ParseTuple(args, "i:urandom", &howMany)) - return NULL; - if (howMany < 0) - return PyErr_Format(PyExc_ValueError, - "negative argument not allowed"); - - /* Allocate bytes */ - result = PyString_FromStringAndSize(NULL, howMany); - if (result != NULL) { - /* Get random data */ - if (RAND_pseudo_bytes((unsigned char*) - PyString_AS_STRING(result), - howMany) < 0) { - Py_DECREF(result); - return PyErr_Format(PyExc_ValueError, - "RAND_pseudo_bytes"); - } - } - return result; + /* Read arguments */ + if (! PyArg_ParseTuple(args, "i:urandom", &howMany)) + return NULL; + if (howMany < 0) + return PyErr_Format(PyExc_ValueError, + "negative argument not allowed"); + + /* Allocate bytes */ + result = PyString_FromStringAndSize(NULL, howMany); + if (result != NULL) { + /* Get random data */ + if (RAND_pseudo_bytes((unsigned char*) + PyString_AS_STRING(result), + howMany) < 0) { + Py_DECREF(result); + return PyErr_Format(PyExc_ValueError, + "RAND_pseudo_bytes"); + } + } + return result; } #endif static PyMethodDef posix_methods[] = { - {"access", posix_access, METH_VARARGS, posix_access__doc__}, + {"access", posix_access, METH_VARARGS, posix_access__doc__}, #ifdef HAVE_TTYNAME - {"ttyname", posix_ttyname, METH_VARARGS, posix_ttyname__doc__}, + {"ttyname", posix_ttyname, METH_VARARGS, posix_ttyname__doc__}, #endif - {"chdir", posix_chdir, METH_VARARGS, posix_chdir__doc__}, + {"chdir", posix_chdir, METH_VARARGS, posix_chdir__doc__}, #ifdef HAVE_CHFLAGS - {"chflags", posix_chflags, METH_VARARGS, posix_chflags__doc__}, + {"chflags", posix_chflags, METH_VARARGS, posix_chflags__doc__}, #endif /* HAVE_CHFLAGS */ - {"chmod", posix_chmod, METH_VARARGS, posix_chmod__doc__}, + {"chmod", posix_chmod, METH_VARARGS, posix_chmod__doc__}, #ifdef HAVE_FCHMOD - {"fchmod", posix_fchmod, METH_VARARGS, posix_fchmod__doc__}, + {"fchmod", posix_fchmod, METH_VARARGS, posix_fchmod__doc__}, #endif /* HAVE_FCHMOD */ #ifdef HAVE_CHOWN - {"chown", posix_chown, METH_VARARGS, posix_chown__doc__}, + {"chown", posix_chown, METH_VARARGS, posix_chown__doc__}, #endif /* HAVE_CHOWN */ #ifdef HAVE_LCHMOD - {"lchmod", posix_lchmod, METH_VARARGS, posix_lchmod__doc__}, + {"lchmod", posix_lchmod, METH_VARARGS, posix_lchmod__doc__}, #endif /* HAVE_LCHMOD */ #ifdef HAVE_FCHOWN - {"fchown", posix_fchown, METH_VARARGS, posix_fchown__doc__}, + {"fchown", posix_fchown, METH_VARARGS, posix_fchown__doc__}, #endif /* HAVE_FCHOWN */ #ifdef HAVE_LCHFLAGS - {"lchflags", posix_lchflags, METH_VARARGS, posix_lchflags__doc__}, + {"lchflags", posix_lchflags, METH_VARARGS, posix_lchflags__doc__}, #endif /* HAVE_LCHFLAGS */ #ifdef HAVE_LCHOWN - {"lchown", posix_lchown, METH_VARARGS, posix_lchown__doc__}, + {"lchown", posix_lchown, METH_VARARGS, posix_lchown__doc__}, #endif /* HAVE_LCHOWN */ #ifdef HAVE_CHROOT - {"chroot", posix_chroot, METH_VARARGS, posix_chroot__doc__}, + {"chroot", posix_chroot, METH_VARARGS, posix_chroot__doc__}, #endif #ifdef HAVE_CTERMID - {"ctermid", posix_ctermid, METH_NOARGS, posix_ctermid__doc__}, + {"ctermid", posix_ctermid, METH_NOARGS, posix_ctermid__doc__}, #endif #ifdef HAVE_GETCWD - {"getcwd", posix_getcwd, METH_NOARGS, posix_getcwd__doc__}, + {"getcwd", posix_getcwd, METH_NOARGS, posix_getcwd__doc__}, #ifdef Py_USING_UNICODE - {"getcwdu", posix_getcwdu, METH_NOARGS, posix_getcwdu__doc__}, + {"getcwdu", posix_getcwdu, METH_NOARGS, posix_getcwdu__doc__}, #endif #endif #ifdef HAVE_LINK - {"link", posix_link, METH_VARARGS, posix_link__doc__}, + {"link", posix_link, METH_VARARGS, posix_link__doc__}, #endif /* HAVE_LINK */ - {"listdir", posix_listdir, METH_VARARGS, posix_listdir__doc__}, - {"lstat", posix_lstat, METH_VARARGS, posix_lstat__doc__}, - {"mkdir", posix_mkdir, METH_VARARGS, posix_mkdir__doc__}, + {"listdir", posix_listdir, METH_VARARGS, posix_listdir__doc__}, + {"lstat", posix_lstat, METH_VARARGS, posix_lstat__doc__}, + {"mkdir", posix_mkdir, METH_VARARGS, posix_mkdir__doc__}, #ifdef HAVE_NICE - {"nice", posix_nice, METH_VARARGS, posix_nice__doc__}, + {"nice", posix_nice, METH_VARARGS, posix_nice__doc__}, #endif /* HAVE_NICE */ #ifdef HAVE_READLINK - {"readlink", posix_readlink, METH_VARARGS, posix_readlink__doc__}, + {"readlink", posix_readlink, METH_VARARGS, posix_readlink__doc__}, #endif /* HAVE_READLINK */ - {"rename", posix_rename, METH_VARARGS, posix_rename__doc__}, - {"rmdir", posix_rmdir, METH_VARARGS, posix_rmdir__doc__}, - {"stat", posix_stat, METH_VARARGS, posix_stat__doc__}, - {"stat_float_times", stat_float_times, METH_VARARGS, stat_float_times__doc__}, + {"rename", posix_rename, METH_VARARGS, posix_rename__doc__}, + {"rmdir", posix_rmdir, METH_VARARGS, posix_rmdir__doc__}, + {"stat", posix_stat, METH_VARARGS, posix_stat__doc__}, + {"stat_float_times", stat_float_times, METH_VARARGS, stat_float_times__doc__}, #ifdef HAVE_SYMLINK - {"symlink", posix_symlink, METH_VARARGS, posix_symlink__doc__}, + {"symlink", posix_symlink, METH_VARARGS, posix_symlink__doc__}, #endif /* HAVE_SYMLINK */ #ifdef HAVE_SYSTEM - {"system", posix_system, METH_VARARGS, posix_system__doc__}, + {"system", posix_system, METH_VARARGS, posix_system__doc__}, #endif - {"umask", posix_umask, METH_VARARGS, posix_umask__doc__}, + {"umask", posix_umask, METH_VARARGS, posix_umask__doc__}, #ifdef HAVE_UNAME - {"uname", posix_uname, METH_NOARGS, posix_uname__doc__}, + {"uname", posix_uname, METH_NOARGS, posix_uname__doc__}, #endif /* HAVE_UNAME */ - {"unlink", posix_unlink, METH_VARARGS, posix_unlink__doc__}, - {"remove", posix_unlink, METH_VARARGS, posix_remove__doc__}, - {"utime", posix_utime, METH_VARARGS, posix_utime__doc__}, + {"unlink", posix_unlink, METH_VARARGS, posix_unlink__doc__}, + {"remove", posix_unlink, METH_VARARGS, posix_remove__doc__}, + {"utime", posix_utime, METH_VARARGS, posix_utime__doc__}, #ifdef HAVE_TIMES - {"times", posix_times, METH_NOARGS, posix_times__doc__}, + {"times", posix_times, METH_NOARGS, posix_times__doc__}, #endif /* HAVE_TIMES */ - {"_exit", posix__exit, METH_VARARGS, posix__exit__doc__}, + {"_exit", posix__exit, METH_VARARGS, posix__exit__doc__}, #ifdef HAVE_EXECV - {"execv", posix_execv, METH_VARARGS, posix_execv__doc__}, - {"execve", posix_execve, METH_VARARGS, posix_execve__doc__}, + {"execv", posix_execv, METH_VARARGS, posix_execv__doc__}, + {"execve", posix_execve, METH_VARARGS, posix_execve__doc__}, #endif /* HAVE_EXECV */ #ifdef HAVE_SPAWNV - {"spawnv", posix_spawnv, METH_VARARGS, posix_spawnv__doc__}, - {"spawnve", posix_spawnve, METH_VARARGS, posix_spawnve__doc__}, + {"spawnv", posix_spawnv, METH_VARARGS, posix_spawnv__doc__}, + {"spawnve", posix_spawnve, METH_VARARGS, posix_spawnve__doc__}, #if defined(PYOS_OS2) - {"spawnvp", posix_spawnvp, METH_VARARGS, posix_spawnvp__doc__}, - {"spawnvpe", posix_spawnvpe, METH_VARARGS, posix_spawnvpe__doc__}, + {"spawnvp", posix_spawnvp, METH_VARARGS, posix_spawnvp__doc__}, + {"spawnvpe", posix_spawnvpe, METH_VARARGS, posix_spawnvpe__doc__}, #endif /* PYOS_OS2 */ #endif /* HAVE_SPAWNV */ #ifdef HAVE_FORK1 - {"fork1", posix_fork1, METH_NOARGS, posix_fork1__doc__}, + {"fork1", posix_fork1, METH_NOARGS, posix_fork1__doc__}, #endif /* HAVE_FORK1 */ #ifdef HAVE_FORK - {"fork", posix_fork, METH_NOARGS, posix_fork__doc__}, + {"fork", posix_fork, METH_NOARGS, posix_fork__doc__}, #endif /* HAVE_FORK */ #if defined(HAVE_OPENPTY) || defined(HAVE__GETPTY) || defined(HAVE_DEV_PTMX) - {"openpty", posix_openpty, METH_NOARGS, posix_openpty__doc__}, + {"openpty", posix_openpty, METH_NOARGS, posix_openpty__doc__}, #endif /* HAVE_OPENPTY || HAVE__GETPTY || HAVE_DEV_PTMX */ #ifdef HAVE_FORKPTY - {"forkpty", posix_forkpty, METH_NOARGS, posix_forkpty__doc__}, + {"forkpty", posix_forkpty, METH_NOARGS, posix_forkpty__doc__}, #endif /* HAVE_FORKPTY */ #ifdef HAVE_GETEGID - {"getegid", posix_getegid, METH_NOARGS, posix_getegid__doc__}, + {"getegid", posix_getegid, METH_NOARGS, posix_getegid__doc__}, #endif /* HAVE_GETEGID */ #ifdef HAVE_GETEUID - {"geteuid", posix_geteuid, METH_NOARGS, posix_geteuid__doc__}, + {"geteuid", posix_geteuid, METH_NOARGS, posix_geteuid__doc__}, #endif /* HAVE_GETEUID */ #ifdef HAVE_GETGID - {"getgid", posix_getgid, METH_NOARGS, posix_getgid__doc__}, + {"getgid", posix_getgid, METH_NOARGS, posix_getgid__doc__}, #endif /* HAVE_GETGID */ #ifdef HAVE_GETGROUPS - {"getgroups", posix_getgroups, METH_NOARGS, posix_getgroups__doc__}, + {"getgroups", posix_getgroups, METH_NOARGS, posix_getgroups__doc__}, #endif - {"getpid", posix_getpid, METH_NOARGS, posix_getpid__doc__}, + {"getpid", posix_getpid, METH_NOARGS, posix_getpid__doc__}, #ifdef HAVE_GETPGRP - {"getpgrp", posix_getpgrp, METH_NOARGS, posix_getpgrp__doc__}, + {"getpgrp", posix_getpgrp, METH_NOARGS, posix_getpgrp__doc__}, #endif /* HAVE_GETPGRP */ #ifdef HAVE_GETPPID - {"getppid", posix_getppid, METH_NOARGS, posix_getppid__doc__}, + {"getppid", posix_getppid, METH_NOARGS, posix_getppid__doc__}, #endif /* HAVE_GETPPID */ #ifdef HAVE_GETUID - {"getuid", posix_getuid, METH_NOARGS, posix_getuid__doc__}, + {"getuid", posix_getuid, METH_NOARGS, posix_getuid__doc__}, #endif /* HAVE_GETUID */ #ifdef HAVE_GETLOGIN - {"getlogin", posix_getlogin, METH_NOARGS, posix_getlogin__doc__}, + {"getlogin", posix_getlogin, METH_NOARGS, posix_getlogin__doc__}, #endif #ifdef HAVE_KILL - {"kill", posix_kill, METH_VARARGS, posix_kill__doc__}, + {"kill", posix_kill, METH_VARARGS, posix_kill__doc__}, #endif /* HAVE_KILL */ #ifdef HAVE_KILLPG - {"killpg", posix_killpg, METH_VARARGS, posix_killpg__doc__}, + {"killpg", posix_killpg, METH_VARARGS, posix_killpg__doc__}, #endif /* HAVE_KILLPG */ #ifdef HAVE_PLOCK - {"plock", posix_plock, METH_VARARGS, posix_plock__doc__}, + {"plock", posix_plock, METH_VARARGS, posix_plock__doc__}, #endif /* HAVE_PLOCK */ #ifdef HAVE_POPEN - {"popen", posix_popen, METH_VARARGS, posix_popen__doc__}, + {"popen", posix_popen, METH_VARARGS, posix_popen__doc__}, #ifdef MS_WINDOWS - {"popen2", win32_popen2, METH_VARARGS}, - {"popen3", win32_popen3, METH_VARARGS}, - {"popen4", win32_popen4, METH_VARARGS}, - {"startfile", win32_startfile, METH_VARARGS, win32_startfile__doc__}, + {"popen2", win32_popen2, METH_VARARGS}, + {"popen3", win32_popen3, METH_VARARGS}, + {"popen4", win32_popen4, METH_VARARGS}, + {"startfile", win32_startfile, METH_VARARGS, win32_startfile__doc__}, #else #if defined(PYOS_OS2) && defined(PYCC_GCC) - {"popen2", os2emx_popen2, METH_VARARGS}, - {"popen3", os2emx_popen3, METH_VARARGS}, - {"popen4", os2emx_popen4, METH_VARARGS}, + {"popen2", os2emx_popen2, METH_VARARGS}, + {"popen3", os2emx_popen3, METH_VARARGS}, + {"popen4", os2emx_popen4, METH_VARARGS}, #endif #endif #endif /* HAVE_POPEN */ #ifdef HAVE_SETUID - {"setuid", posix_setuid, METH_VARARGS, posix_setuid__doc__}, + {"setuid", posix_setuid, METH_VARARGS, posix_setuid__doc__}, #endif /* HAVE_SETUID */ #ifdef HAVE_SETEUID - {"seteuid", posix_seteuid, METH_VARARGS, posix_seteuid__doc__}, + {"seteuid", posix_seteuid, METH_VARARGS, posix_seteuid__doc__}, #endif /* HAVE_SETEUID */ #ifdef HAVE_SETEGID - {"setegid", posix_setegid, METH_VARARGS, posix_setegid__doc__}, + {"setegid", posix_setegid, METH_VARARGS, posix_setegid__doc__}, #endif /* HAVE_SETEGID */ #ifdef HAVE_SETREUID - {"setreuid", posix_setreuid, METH_VARARGS, posix_setreuid__doc__}, + {"setreuid", posix_setreuid, METH_VARARGS, posix_setreuid__doc__}, #endif /* HAVE_SETREUID */ #ifdef HAVE_SETREGID - {"setregid", posix_setregid, METH_VARARGS, posix_setregid__doc__}, + {"setregid", posix_setregid, METH_VARARGS, posix_setregid__doc__}, #endif /* HAVE_SETREGID */ #ifdef HAVE_SETGID - {"setgid", posix_setgid, METH_VARARGS, posix_setgid__doc__}, + {"setgid", posix_setgid, METH_VARARGS, posix_setgid__doc__}, #endif /* HAVE_SETGID */ #ifdef HAVE_SETGROUPS - {"setgroups", posix_setgroups, METH_O, posix_setgroups__doc__}, + {"setgroups", posix_setgroups, METH_O, posix_setgroups__doc__}, #endif /* HAVE_SETGROUPS */ #ifdef HAVE_GETPGID - {"getpgid", posix_getpgid, METH_VARARGS, posix_getpgid__doc__}, + {"getpgid", posix_getpgid, METH_VARARGS, posix_getpgid__doc__}, #endif /* HAVE_GETPGID */ #ifdef HAVE_SETPGRP - {"setpgrp", posix_setpgrp, METH_NOARGS, posix_setpgrp__doc__}, + {"setpgrp", posix_setpgrp, METH_NOARGS, posix_setpgrp__doc__}, #endif /* HAVE_SETPGRP */ #ifdef HAVE_WAIT - {"wait", posix_wait, METH_NOARGS, posix_wait__doc__}, + {"wait", posix_wait, METH_NOARGS, posix_wait__doc__}, #endif /* HAVE_WAIT */ #ifdef HAVE_WAIT3 - {"wait3", posix_wait3, METH_VARARGS, posix_wait3__doc__}, + {"wait3", posix_wait3, METH_VARARGS, posix_wait3__doc__}, #endif /* HAVE_WAIT3 */ #ifdef HAVE_WAIT4 - {"wait4", posix_wait4, METH_VARARGS, posix_wait4__doc__}, + {"wait4", posix_wait4, METH_VARARGS, posix_wait4__doc__}, #endif /* HAVE_WAIT4 */ #if defined(HAVE_WAITPID) || defined(HAVE_CWAIT) - {"waitpid", posix_waitpid, METH_VARARGS, posix_waitpid__doc__}, + {"waitpid", posix_waitpid, METH_VARARGS, posix_waitpid__doc__}, #endif /* HAVE_WAITPID */ #ifdef HAVE_GETSID - {"getsid", posix_getsid, METH_VARARGS, posix_getsid__doc__}, + {"getsid", posix_getsid, METH_VARARGS, posix_getsid__doc__}, #endif /* HAVE_GETSID */ #ifdef HAVE_SETSID - {"setsid", posix_setsid, METH_NOARGS, posix_setsid__doc__}, + {"setsid", posix_setsid, METH_NOARGS, posix_setsid__doc__}, #endif /* HAVE_SETSID */ #ifdef HAVE_SETPGID - {"setpgid", posix_setpgid, METH_VARARGS, posix_setpgid__doc__}, + {"setpgid", posix_setpgid, METH_VARARGS, posix_setpgid__doc__}, #endif /* HAVE_SETPGID */ #ifdef HAVE_TCGETPGRP - {"tcgetpgrp", posix_tcgetpgrp, METH_VARARGS, posix_tcgetpgrp__doc__}, + {"tcgetpgrp", posix_tcgetpgrp, METH_VARARGS, posix_tcgetpgrp__doc__}, #endif /* HAVE_TCGETPGRP */ #ifdef HAVE_TCSETPGRP - {"tcsetpgrp", posix_tcsetpgrp, METH_VARARGS, posix_tcsetpgrp__doc__}, + {"tcsetpgrp", posix_tcsetpgrp, METH_VARARGS, posix_tcsetpgrp__doc__}, #endif /* HAVE_TCSETPGRP */ - {"open", posix_open, METH_VARARGS, posix_open__doc__}, - {"close", posix_close, METH_VARARGS, posix_close__doc__}, - {"closerange", posix_closerange, METH_VARARGS, posix_closerange__doc__}, - {"dup", posix_dup, METH_VARARGS, posix_dup__doc__}, - {"dup2", posix_dup2, METH_VARARGS, posix_dup2__doc__}, - {"lseek", posix_lseek, METH_VARARGS, posix_lseek__doc__}, - {"read", posix_read, METH_VARARGS, posix_read__doc__}, - {"write", posix_write, METH_VARARGS, posix_write__doc__}, - {"fstat", posix_fstat, METH_VARARGS, posix_fstat__doc__}, - {"fdopen", posix_fdopen, METH_VARARGS, posix_fdopen__doc__}, - {"isatty", posix_isatty, METH_VARARGS, posix_isatty__doc__}, + {"open", posix_open, METH_VARARGS, posix_open__doc__}, + {"close", posix_close, METH_VARARGS, posix_close__doc__}, + {"closerange", posix_closerange, METH_VARARGS, posix_closerange__doc__}, + {"dup", posix_dup, METH_VARARGS, posix_dup__doc__}, + {"dup2", posix_dup2, METH_VARARGS, posix_dup2__doc__}, + {"lseek", posix_lseek, METH_VARARGS, posix_lseek__doc__}, + {"read", posix_read, METH_VARARGS, posix_read__doc__}, + {"write", posix_write, METH_VARARGS, posix_write__doc__}, + {"fstat", posix_fstat, METH_VARARGS, posix_fstat__doc__}, + {"fdopen", posix_fdopen, METH_VARARGS, posix_fdopen__doc__}, + {"isatty", posix_isatty, METH_VARARGS, posix_isatty__doc__}, #ifdef HAVE_PIPE - {"pipe", posix_pipe, METH_NOARGS, posix_pipe__doc__}, + {"pipe", posix_pipe, METH_NOARGS, posix_pipe__doc__}, #endif #ifdef HAVE_MKFIFO - {"mkfifo", posix_mkfifo, METH_VARARGS, posix_mkfifo__doc__}, + {"mkfifo", posix_mkfifo, METH_VARARGS, posix_mkfifo__doc__}, #endif #if defined(HAVE_MKNOD) && defined(HAVE_MAKEDEV) - {"mknod", posix_mknod, METH_VARARGS, posix_mknod__doc__}, + {"mknod", posix_mknod, METH_VARARGS, posix_mknod__doc__}, #endif #ifdef HAVE_DEVICE_MACROS - {"major", posix_major, METH_VARARGS, posix_major__doc__}, - {"minor", posix_minor, METH_VARARGS, posix_minor__doc__}, - {"makedev", posix_makedev, METH_VARARGS, posix_makedev__doc__}, + {"major", posix_major, METH_VARARGS, posix_major__doc__}, + {"minor", posix_minor, METH_VARARGS, posix_minor__doc__}, + {"makedev", posix_makedev, METH_VARARGS, posix_makedev__doc__}, #endif #ifdef HAVE_FTRUNCATE - {"ftruncate", posix_ftruncate, METH_VARARGS, posix_ftruncate__doc__}, + {"ftruncate", posix_ftruncate, METH_VARARGS, posix_ftruncate__doc__}, #endif #ifdef HAVE_PUTENV - {"putenv", posix_putenv, METH_VARARGS, posix_putenv__doc__}, + {"putenv", posix_putenv, METH_VARARGS, posix_putenv__doc__}, #endif #ifdef HAVE_UNSETENV - {"unsetenv", posix_unsetenv, METH_VARARGS, posix_unsetenv__doc__}, + {"unsetenv", posix_unsetenv, METH_VARARGS, posix_unsetenv__doc__}, #endif - {"strerror", posix_strerror, METH_VARARGS, posix_strerror__doc__}, + {"strerror", posix_strerror, METH_VARARGS, posix_strerror__doc__}, #ifdef HAVE_FCHDIR - {"fchdir", posix_fchdir, METH_O, posix_fchdir__doc__}, + {"fchdir", posix_fchdir, METH_O, posix_fchdir__doc__}, #endif #ifdef HAVE_FSYNC - {"fsync", posix_fsync, METH_O, posix_fsync__doc__}, + {"fsync", posix_fsync, METH_O, posix_fsync__doc__}, #endif #ifdef HAVE_FDATASYNC - {"fdatasync", posix_fdatasync, METH_O, posix_fdatasync__doc__}, + {"fdatasync", posix_fdatasync, METH_O, posix_fdatasync__doc__}, #endif #ifdef HAVE_SYS_WAIT_H #ifdef WCOREDUMP - {"WCOREDUMP", posix_WCOREDUMP, METH_VARARGS, posix_WCOREDUMP__doc__}, + {"WCOREDUMP", posix_WCOREDUMP, METH_VARARGS, posix_WCOREDUMP__doc__}, #endif /* WCOREDUMP */ #ifdef WIFCONTINUED - {"WIFCONTINUED",posix_WIFCONTINUED, METH_VARARGS, posix_WIFCONTINUED__doc__}, + {"WIFCONTINUED",posix_WIFCONTINUED, METH_VARARGS, posix_WIFCONTINUED__doc__}, #endif /* WIFCONTINUED */ #ifdef WIFSTOPPED - {"WIFSTOPPED", posix_WIFSTOPPED, METH_VARARGS, posix_WIFSTOPPED__doc__}, + {"WIFSTOPPED", posix_WIFSTOPPED, METH_VARARGS, posix_WIFSTOPPED__doc__}, #endif /* WIFSTOPPED */ #ifdef WIFSIGNALED - {"WIFSIGNALED", posix_WIFSIGNALED, METH_VARARGS, posix_WIFSIGNALED__doc__}, + {"WIFSIGNALED", posix_WIFSIGNALED, METH_VARARGS, posix_WIFSIGNALED__doc__}, #endif /* WIFSIGNALED */ #ifdef WIFEXITED - {"WIFEXITED", posix_WIFEXITED, METH_VARARGS, posix_WIFEXITED__doc__}, + {"WIFEXITED", posix_WIFEXITED, METH_VARARGS, posix_WIFEXITED__doc__}, #endif /* WIFEXITED */ #ifdef WEXITSTATUS - {"WEXITSTATUS", posix_WEXITSTATUS, METH_VARARGS, posix_WEXITSTATUS__doc__}, + {"WEXITSTATUS", posix_WEXITSTATUS, METH_VARARGS, posix_WEXITSTATUS__doc__}, #endif /* WEXITSTATUS */ #ifdef WTERMSIG - {"WTERMSIG", posix_WTERMSIG, METH_VARARGS, posix_WTERMSIG__doc__}, + {"WTERMSIG", posix_WTERMSIG, METH_VARARGS, posix_WTERMSIG__doc__}, #endif /* WTERMSIG */ #ifdef WSTOPSIG - {"WSTOPSIG", posix_WSTOPSIG, METH_VARARGS, posix_WSTOPSIG__doc__}, + {"WSTOPSIG", posix_WSTOPSIG, METH_VARARGS, posix_WSTOPSIG__doc__}, #endif /* WSTOPSIG */ #endif /* HAVE_SYS_WAIT_H */ #if defined(HAVE_FSTATVFS) && defined(HAVE_SYS_STATVFS_H) - {"fstatvfs", posix_fstatvfs, METH_VARARGS, posix_fstatvfs__doc__}, + {"fstatvfs", posix_fstatvfs, METH_VARARGS, posix_fstatvfs__doc__}, #endif #if defined(HAVE_STATVFS) && defined(HAVE_SYS_STATVFS_H) - {"statvfs", posix_statvfs, METH_VARARGS, posix_statvfs__doc__}, + {"statvfs", posix_statvfs, METH_VARARGS, posix_statvfs__doc__}, #endif #ifdef HAVE_TMPFILE - {"tmpfile", posix_tmpfile, METH_NOARGS, posix_tmpfile__doc__}, + {"tmpfile", posix_tmpfile, METH_NOARGS, posix_tmpfile__doc__}, #endif #ifdef HAVE_TEMPNAM - {"tempnam", posix_tempnam, METH_VARARGS, posix_tempnam__doc__}, + {"tempnam", posix_tempnam, METH_VARARGS, posix_tempnam__doc__}, #endif #ifdef HAVE_TMPNAM - {"tmpnam", posix_tmpnam, METH_NOARGS, posix_tmpnam__doc__}, + {"tmpnam", posix_tmpnam, METH_NOARGS, posix_tmpnam__doc__}, #endif #ifdef HAVE_CONFSTR - {"confstr", posix_confstr, METH_VARARGS, posix_confstr__doc__}, + {"confstr", posix_confstr, METH_VARARGS, posix_confstr__doc__}, #endif #ifdef HAVE_SYSCONF - {"sysconf", posix_sysconf, METH_VARARGS, posix_sysconf__doc__}, + {"sysconf", posix_sysconf, METH_VARARGS, posix_sysconf__doc__}, #endif #ifdef HAVE_FPATHCONF - {"fpathconf", posix_fpathconf, METH_VARARGS, posix_fpathconf__doc__}, + {"fpathconf", posix_fpathconf, METH_VARARGS, posix_fpathconf__doc__}, #endif #ifdef HAVE_PATHCONF - {"pathconf", posix_pathconf, METH_VARARGS, posix_pathconf__doc__}, + {"pathconf", posix_pathconf, METH_VARARGS, posix_pathconf__doc__}, #endif - {"abort", posix_abort, METH_NOARGS, posix_abort__doc__}, + {"abort", posix_abort, METH_NOARGS, posix_abort__doc__}, #ifdef MS_WINDOWS - {"_getfullpathname", posix__getfullpathname, METH_VARARGS, NULL}, + {"_getfullpathname", posix__getfullpathname, METH_VARARGS, NULL}, #endif #ifdef HAVE_GETLOADAVG - {"getloadavg", posix_getloadavg, METH_NOARGS, posix_getloadavg__doc__}, + {"getloadavg", posix_getloadavg, METH_NOARGS, posix_getloadavg__doc__}, #endif #ifdef MS_WINDOWS - {"urandom", win32_urandom, METH_VARARGS, win32_urandom__doc__}, + {"urandom", win32_urandom, METH_VARARGS, win32_urandom__doc__}, #endif #ifdef __VMS - {"urandom", vms_urandom, METH_VARARGS, vms_urandom__doc__}, + {"urandom", vms_urandom, METH_VARARGS, vms_urandom__doc__}, #endif - {NULL, NULL} /* Sentinel */ + {NULL, NULL} /* Sentinel */ }; static int ins(PyObject *module, char *symbol, long value) { - return PyModule_AddIntConstant(module, symbol, value); + return PyModule_AddIntConstant(module, symbol, value); } #if defined(PYOS_OS2) @@ -8784,7 +8784,7 @@ case 50: ver = "5.00"; break; default: PyOS_snprintf(tmp, sizeof(tmp), - "%d-%d", values[QSV_VERSION_MAJOR], + "%d-%d", values[QSV_VERSION_MAJOR], values[QSV_VERSION_MINOR]); ver = &tmp[0]; } @@ -8806,221 +8806,221 @@ all_ins(PyObject *d) { #ifdef F_OK - if (ins(d, "F_OK", (long)F_OK)) return -1; + if (ins(d, "F_OK", (long)F_OK)) return -1; #endif #ifdef R_OK - if (ins(d, "R_OK", (long)R_OK)) return -1; + if (ins(d, "R_OK", (long)R_OK)) return -1; #endif #ifdef W_OK - if (ins(d, "W_OK", (long)W_OK)) return -1; + if (ins(d, "W_OK", (long)W_OK)) return -1; #endif #ifdef X_OK - if (ins(d, "X_OK", (long)X_OK)) return -1; + if (ins(d, "X_OK", (long)X_OK)) return -1; #endif #ifdef NGROUPS_MAX - if (ins(d, "NGROUPS_MAX", (long)NGROUPS_MAX)) return -1; + if (ins(d, "NGROUPS_MAX", (long)NGROUPS_MAX)) return -1; #endif #ifdef TMP_MAX - if (ins(d, "TMP_MAX", (long)TMP_MAX)) return -1; + if (ins(d, "TMP_MAX", (long)TMP_MAX)) return -1; #endif #ifdef WCONTINUED - if (ins(d, "WCONTINUED", (long)WCONTINUED)) return -1; + if (ins(d, "WCONTINUED", (long)WCONTINUED)) return -1; #endif #ifdef WNOHANG - if (ins(d, "WNOHANG", (long)WNOHANG)) return -1; + if (ins(d, "WNOHANG", (long)WNOHANG)) return -1; #endif #ifdef WUNTRACED - if (ins(d, "WUNTRACED", (long)WUNTRACED)) return -1; + if (ins(d, "WUNTRACED", (long)WUNTRACED)) return -1; #endif #ifdef O_RDONLY - if (ins(d, "O_RDONLY", (long)O_RDONLY)) return -1; + if (ins(d, "O_RDONLY", (long)O_RDONLY)) return -1; #endif #ifdef O_WRONLY - if (ins(d, "O_WRONLY", (long)O_WRONLY)) return -1; + if (ins(d, "O_WRONLY", (long)O_WRONLY)) return -1; #endif #ifdef O_RDWR - if (ins(d, "O_RDWR", (long)O_RDWR)) return -1; + if (ins(d, "O_RDWR", (long)O_RDWR)) return -1; #endif #ifdef O_NDELAY - if (ins(d, "O_NDELAY", (long)O_NDELAY)) return -1; + if (ins(d, "O_NDELAY", (long)O_NDELAY)) return -1; #endif #ifdef O_NONBLOCK - if (ins(d, "O_NONBLOCK", (long)O_NONBLOCK)) return -1; + if (ins(d, "O_NONBLOCK", (long)O_NONBLOCK)) return -1; #endif #ifdef O_APPEND - if (ins(d, "O_APPEND", (long)O_APPEND)) return -1; + if (ins(d, "O_APPEND", (long)O_APPEND)) return -1; #endif #ifdef O_DSYNC - if (ins(d, "O_DSYNC", (long)O_DSYNC)) return -1; + if (ins(d, "O_DSYNC", (long)O_DSYNC)) return -1; #endif #ifdef O_RSYNC - if (ins(d, "O_RSYNC", (long)O_RSYNC)) return -1; + if (ins(d, "O_RSYNC", (long)O_RSYNC)) return -1; #endif #ifdef O_SYNC - if (ins(d, "O_SYNC", (long)O_SYNC)) return -1; + if (ins(d, "O_SYNC", (long)O_SYNC)) return -1; #endif #ifdef O_NOCTTY - if (ins(d, "O_NOCTTY", (long)O_NOCTTY)) return -1; + if (ins(d, "O_NOCTTY", (long)O_NOCTTY)) return -1; #endif #ifdef O_CREAT - if (ins(d, "O_CREAT", (long)O_CREAT)) return -1; + if (ins(d, "O_CREAT", (long)O_CREAT)) return -1; #endif #ifdef O_EXCL - if (ins(d, "O_EXCL", (long)O_EXCL)) return -1; + if (ins(d, "O_EXCL", (long)O_EXCL)) return -1; #endif #ifdef O_TRUNC - if (ins(d, "O_TRUNC", (long)O_TRUNC)) return -1; + if (ins(d, "O_TRUNC", (long)O_TRUNC)) return -1; #endif #ifdef O_BINARY - if (ins(d, "O_BINARY", (long)O_BINARY)) return -1; + if (ins(d, "O_BINARY", (long)O_BINARY)) return -1; #endif #ifdef O_TEXT - if (ins(d, "O_TEXT", (long)O_TEXT)) return -1; + if (ins(d, "O_TEXT", (long)O_TEXT)) return -1; #endif #ifdef O_LARGEFILE - if (ins(d, "O_LARGEFILE", (long)O_LARGEFILE)) return -1; + if (ins(d, "O_LARGEFILE", (long)O_LARGEFILE)) return -1; #endif #ifdef O_SHLOCK - if (ins(d, "O_SHLOCK", (long)O_SHLOCK)) return -1; + if (ins(d, "O_SHLOCK", (long)O_SHLOCK)) return -1; #endif #ifdef O_EXLOCK - if (ins(d, "O_EXLOCK", (long)O_EXLOCK)) return -1; + if (ins(d, "O_EXLOCK", (long)O_EXLOCK)) return -1; #endif /* MS Windows */ #ifdef O_NOINHERIT - /* Don't inherit in child processes. */ - if (ins(d, "O_NOINHERIT", (long)O_NOINHERIT)) return -1; + /* Don't inherit in child processes. */ + if (ins(d, "O_NOINHERIT", (long)O_NOINHERIT)) return -1; #endif #ifdef _O_SHORT_LIVED - /* Optimize for short life (keep in memory). */ - /* MS forgot to define this one with a non-underscore form too. */ - if (ins(d, "O_SHORT_LIVED", (long)_O_SHORT_LIVED)) return -1; + /* Optimize for short life (keep in memory). */ + /* MS forgot to define this one with a non-underscore form too. */ + if (ins(d, "O_SHORT_LIVED", (long)_O_SHORT_LIVED)) return -1; #endif #ifdef O_TEMPORARY - /* Automatically delete when last handle is closed. */ - if (ins(d, "O_TEMPORARY", (long)O_TEMPORARY)) return -1; + /* Automatically delete when last handle is closed. */ + if (ins(d, "O_TEMPORARY", (long)O_TEMPORARY)) return -1; #endif #ifdef O_RANDOM - /* Optimize for random access. */ - if (ins(d, "O_RANDOM", (long)O_RANDOM)) return -1; + /* Optimize for random access. */ + if (ins(d, "O_RANDOM", (long)O_RANDOM)) return -1; #endif #ifdef O_SEQUENTIAL - /* Optimize for sequential access. */ - if (ins(d, "O_SEQUENTIAL", (long)O_SEQUENTIAL)) return -1; + /* Optimize for sequential access. */ + if (ins(d, "O_SEQUENTIAL", (long)O_SEQUENTIAL)) return -1; #endif /* GNU extensions. */ #ifdef O_ASYNC - /* Send a SIGIO signal whenever input or output - becomes available on file descriptor */ - if (ins(d, "O_ASYNC", (long)O_ASYNC)) return -1; + /* Send a SIGIO signal whenever input or output + becomes available on file descriptor */ + if (ins(d, "O_ASYNC", (long)O_ASYNC)) return -1; #endif #ifdef O_DIRECT - /* Direct disk access. */ - if (ins(d, "O_DIRECT", (long)O_DIRECT)) return -1; + /* Direct disk access. */ + if (ins(d, "O_DIRECT", (long)O_DIRECT)) return -1; #endif #ifdef O_DIRECTORY - /* Must be a directory. */ - if (ins(d, "O_DIRECTORY", (long)O_DIRECTORY)) return -1; + /* Must be a directory. */ + if (ins(d, "O_DIRECTORY", (long)O_DIRECTORY)) return -1; #endif #ifdef O_NOFOLLOW - /* Do not follow links. */ - if (ins(d, "O_NOFOLLOW", (long)O_NOFOLLOW)) return -1; + /* Do not follow links. */ + if (ins(d, "O_NOFOLLOW", (long)O_NOFOLLOW)) return -1; #endif #ifdef O_NOATIME - /* Do not update the access time. */ - if (ins(d, "O_NOATIME", (long)O_NOATIME)) return -1; + /* Do not update the access time. */ + if (ins(d, "O_NOATIME", (long)O_NOATIME)) return -1; #endif - /* These come from sysexits.h */ + /* These come from sysexits.h */ #ifdef EX_OK - if (ins(d, "EX_OK", (long)EX_OK)) return -1; + if (ins(d, "EX_OK", (long)EX_OK)) return -1; #endif /* EX_OK */ #ifdef EX_USAGE - if (ins(d, "EX_USAGE", (long)EX_USAGE)) return -1; + if (ins(d, "EX_USAGE", (long)EX_USAGE)) return -1; #endif /* EX_USAGE */ #ifdef EX_DATAERR - if (ins(d, "EX_DATAERR", (long)EX_DATAERR)) return -1; + if (ins(d, "EX_DATAERR", (long)EX_DATAERR)) return -1; #endif /* EX_DATAERR */ #ifdef EX_NOINPUT - if (ins(d, "EX_NOINPUT", (long)EX_NOINPUT)) return -1; + if (ins(d, "EX_NOINPUT", (long)EX_NOINPUT)) return -1; #endif /* EX_NOINPUT */ #ifdef EX_NOUSER - if (ins(d, "EX_NOUSER", (long)EX_NOUSER)) return -1; + if (ins(d, "EX_NOUSER", (long)EX_NOUSER)) return -1; #endif /* EX_NOUSER */ #ifdef EX_NOHOST - if (ins(d, "EX_NOHOST", (long)EX_NOHOST)) return -1; + if (ins(d, "EX_NOHOST", (long)EX_NOHOST)) return -1; #endif /* EX_NOHOST */ #ifdef EX_UNAVAILABLE - if (ins(d, "EX_UNAVAILABLE", (long)EX_UNAVAILABLE)) return -1; + if (ins(d, "EX_UNAVAILABLE", (long)EX_UNAVAILABLE)) return -1; #endif /* EX_UNAVAILABLE */ #ifdef EX_SOFTWARE - if (ins(d, "EX_SOFTWARE", (long)EX_SOFTWARE)) return -1; + if (ins(d, "EX_SOFTWARE", (long)EX_SOFTWARE)) return -1; #endif /* EX_SOFTWARE */ #ifdef EX_OSERR - if (ins(d, "EX_OSERR", (long)EX_OSERR)) return -1; + if (ins(d, "EX_OSERR", (long)EX_OSERR)) return -1; #endif /* EX_OSERR */ #ifdef EX_OSFILE - if (ins(d, "EX_OSFILE", (long)EX_OSFILE)) return -1; + if (ins(d, "EX_OSFILE", (long)EX_OSFILE)) return -1; #endif /* EX_OSFILE */ #ifdef EX_CANTCREAT - if (ins(d, "EX_CANTCREAT", (long)EX_CANTCREAT)) return -1; + if (ins(d, "EX_CANTCREAT", (long)EX_CANTCREAT)) return -1; #endif /* EX_CANTCREAT */ #ifdef EX_IOERR - if (ins(d, "EX_IOERR", (long)EX_IOERR)) return -1; + if (ins(d, "EX_IOERR", (long)EX_IOERR)) return -1; #endif /* EX_IOERR */ #ifdef EX_TEMPFAIL - if (ins(d, "EX_TEMPFAIL", (long)EX_TEMPFAIL)) return -1; + if (ins(d, "EX_TEMPFAIL", (long)EX_TEMPFAIL)) return -1; #endif /* EX_TEMPFAIL */ #ifdef EX_PROTOCOL - if (ins(d, "EX_PROTOCOL", (long)EX_PROTOCOL)) return -1; + if (ins(d, "EX_PROTOCOL", (long)EX_PROTOCOL)) return -1; #endif /* EX_PROTOCOL */ #ifdef EX_NOPERM - if (ins(d, "EX_NOPERM", (long)EX_NOPERM)) return -1; + if (ins(d, "EX_NOPERM", (long)EX_NOPERM)) return -1; #endif /* EX_NOPERM */ #ifdef EX_CONFIG - if (ins(d, "EX_CONFIG", (long)EX_CONFIG)) return -1; + if (ins(d, "EX_CONFIG", (long)EX_CONFIG)) return -1; #endif /* EX_CONFIG */ #ifdef EX_NOTFOUND - if (ins(d, "EX_NOTFOUND", (long)EX_NOTFOUND)) return -1; + if (ins(d, "EX_NOTFOUND", (long)EX_NOTFOUND)) return -1; #endif /* EX_NOTFOUND */ #ifdef HAVE_SPAWNV #if defined(PYOS_OS2) && defined(PYCC_GCC) - if (ins(d, "P_WAIT", (long)P_WAIT)) return -1; - if (ins(d, "P_NOWAIT", (long)P_NOWAIT)) return -1; - if (ins(d, "P_OVERLAY", (long)P_OVERLAY)) return -1; - if (ins(d, "P_DEBUG", (long)P_DEBUG)) return -1; - if (ins(d, "P_SESSION", (long)P_SESSION)) return -1; - if (ins(d, "P_DETACH", (long)P_DETACH)) return -1; - if (ins(d, "P_PM", (long)P_PM)) return -1; - if (ins(d, "P_DEFAULT", (long)P_DEFAULT)) return -1; - if (ins(d, "P_MINIMIZE", (long)P_MINIMIZE)) return -1; - if (ins(d, "P_MAXIMIZE", (long)P_MAXIMIZE)) return -1; - if (ins(d, "P_FULLSCREEN", (long)P_FULLSCREEN)) return -1; - if (ins(d, "P_WINDOWED", (long)P_WINDOWED)) return -1; - if (ins(d, "P_FOREGROUND", (long)P_FOREGROUND)) return -1; - if (ins(d, "P_BACKGROUND", (long)P_BACKGROUND)) return -1; - if (ins(d, "P_NOCLOSE", (long)P_NOCLOSE)) return -1; - if (ins(d, "P_NOSESSION", (long)P_NOSESSION)) return -1; - if (ins(d, "P_QUOTE", (long)P_QUOTE)) return -1; - if (ins(d, "P_TILDE", (long)P_TILDE)) return -1; - if (ins(d, "P_UNRELATED", (long)P_UNRELATED)) return -1; - if (ins(d, "P_DEBUGDESC", (long)P_DEBUGDESC)) return -1; -#else - if (ins(d, "P_WAIT", (long)_P_WAIT)) return -1; - if (ins(d, "P_NOWAIT", (long)_P_NOWAIT)) return -1; - if (ins(d, "P_OVERLAY", (long)_OLD_P_OVERLAY)) return -1; - if (ins(d, "P_NOWAITO", (long)_P_NOWAITO)) return -1; - if (ins(d, "P_DETACH", (long)_P_DETACH)) return -1; + if (ins(d, "P_WAIT", (long)P_WAIT)) return -1; + if (ins(d, "P_NOWAIT", (long)P_NOWAIT)) return -1; + if (ins(d, "P_OVERLAY", (long)P_OVERLAY)) return -1; + if (ins(d, "P_DEBUG", (long)P_DEBUG)) return -1; + if (ins(d, "P_SESSION", (long)P_SESSION)) return -1; + if (ins(d, "P_DETACH", (long)P_DETACH)) return -1; + if (ins(d, "P_PM", (long)P_PM)) return -1; + if (ins(d, "P_DEFAULT", (long)P_DEFAULT)) return -1; + if (ins(d, "P_MINIMIZE", (long)P_MINIMIZE)) return -1; + if (ins(d, "P_MAXIMIZE", (long)P_MAXIMIZE)) return -1; + if (ins(d, "P_FULLSCREEN", (long)P_FULLSCREEN)) return -1; + if (ins(d, "P_WINDOWED", (long)P_WINDOWED)) return -1; + if (ins(d, "P_FOREGROUND", (long)P_FOREGROUND)) return -1; + if (ins(d, "P_BACKGROUND", (long)P_BACKGROUND)) return -1; + if (ins(d, "P_NOCLOSE", (long)P_NOCLOSE)) return -1; + if (ins(d, "P_NOSESSION", (long)P_NOSESSION)) return -1; + if (ins(d, "P_QUOTE", (long)P_QUOTE)) return -1; + if (ins(d, "P_TILDE", (long)P_TILDE)) return -1; + if (ins(d, "P_UNRELATED", (long)P_UNRELATED)) return -1; + if (ins(d, "P_DEBUGDESC", (long)P_DEBUGDESC)) return -1; +#else + if (ins(d, "P_WAIT", (long)_P_WAIT)) return -1; + if (ins(d, "P_NOWAIT", (long)_P_NOWAIT)) return -1; + if (ins(d, "P_OVERLAY", (long)_OLD_P_OVERLAY)) return -1; + if (ins(d, "P_NOWAITO", (long)_P_NOWAITO)) return -1; + if (ins(d, "P_DETACH", (long)_P_DETACH)) return -1; #endif #endif #if defined(PYOS_OS2) - if (insertvalues(d)) return -1; + if (insertvalues(d)) return -1; #endif - return 0; + return 0; } @@ -9040,96 +9040,96 @@ PyMODINIT_FUNC INITFUNC(void) { - PyObject *m, *v; + PyObject *m, *v; - m = Py_InitModule3(MODNAME, - posix_methods, - posix__doc__); - if (m == NULL) - return; - - /* Initialize environ dictionary */ - v = convertenviron(); - Py_XINCREF(v); - if (v == NULL || PyModule_AddObject(m, "environ", v) != 0) - return; - Py_DECREF(v); + m = Py_InitModule3(MODNAME, + posix_methods, + posix__doc__); + if (m == NULL) + return; + + /* Initialize environ dictionary */ + v = convertenviron(); + Py_XINCREF(v); + if (v == NULL || PyModule_AddObject(m, "environ", v) != 0) + return; + Py_DECREF(v); - if (all_ins(m)) - return; + if (all_ins(m)) + return; - if (setup_confname_tables(m)) - return; + if (setup_confname_tables(m)) + return; - Py_INCREF(PyExc_OSError); - PyModule_AddObject(m, "error", PyExc_OSError); + Py_INCREF(PyExc_OSError); + PyModule_AddObject(m, "error", PyExc_OSError); #ifdef HAVE_PUTENV - if (posix_putenv_garbage == NULL) - posix_putenv_garbage = PyDict_New(); + if (posix_putenv_garbage == NULL) + posix_putenv_garbage = PyDict_New(); #endif - if (!initialized) { - stat_result_desc.name = MODNAME ".stat_result"; - stat_result_desc.fields[7].name = PyStructSequence_UnnamedField; - stat_result_desc.fields[8].name = PyStructSequence_UnnamedField; - stat_result_desc.fields[9].name = PyStructSequence_UnnamedField; - PyStructSequence_InitType(&StatResultType, &stat_result_desc); - structseq_new = StatResultType.tp_new; - StatResultType.tp_new = statresult_new; + if (!initialized) { + stat_result_desc.name = MODNAME ".stat_result"; + stat_result_desc.fields[7].name = PyStructSequence_UnnamedField; + stat_result_desc.fields[8].name = PyStructSequence_UnnamedField; + stat_result_desc.fields[9].name = PyStructSequence_UnnamedField; + PyStructSequence_InitType(&StatResultType, &stat_result_desc); + structseq_new = StatResultType.tp_new; + StatResultType.tp_new = statresult_new; - statvfs_result_desc.name = MODNAME ".statvfs_result"; - PyStructSequence_InitType(&StatVFSResultType, &statvfs_result_desc); + statvfs_result_desc.name = MODNAME ".statvfs_result"; + PyStructSequence_InitType(&StatVFSResultType, &statvfs_result_desc); #ifdef NEED_TICKS_PER_SECOND # if defined(HAVE_SYSCONF) && defined(_SC_CLK_TCK) - ticks_per_second = sysconf(_SC_CLK_TCK); + ticks_per_second = sysconf(_SC_CLK_TCK); # elif defined(HZ) - ticks_per_second = HZ; + ticks_per_second = HZ; # else - ticks_per_second = 60; /* magic fallback value; may be bogus */ + ticks_per_second = 60; /* magic fallback value; may be bogus */ # endif #endif - } - Py_INCREF((PyObject*) &StatResultType); - PyModule_AddObject(m, "stat_result", (PyObject*) &StatResultType); - Py_INCREF((PyObject*) &StatVFSResultType); - PyModule_AddObject(m, "statvfs_result", - (PyObject*) &StatVFSResultType); - initialized = 1; + } + Py_INCREF((PyObject*) &StatResultType); + PyModule_AddObject(m, "stat_result", (PyObject*) &StatResultType); + Py_INCREF((PyObject*) &StatVFSResultType); + PyModule_AddObject(m, "statvfs_result", + (PyObject*) &StatVFSResultType); + initialized = 1; #ifdef __APPLE__ - /* - * Step 2 of weak-linking support on Mac OS X. - * - * The code below removes functions that are not available on the - * currently active platform. - * - * This block allow one to use a python binary that was build on - * OSX 10.4 on OSX 10.3, without loosing access to new APIs on - * OSX 10.4. - */ + /* + * Step 2 of weak-linking support on Mac OS X. + * + * The code below removes functions that are not available on the + * currently active platform. + * + * This block allow one to use a python binary that was build on + * OSX 10.4 on OSX 10.3, without loosing access to new APIs on + * OSX 10.4. + */ #ifdef HAVE_FSTATVFS - if (fstatvfs == NULL) { - if (PyObject_DelAttrString(m, "fstatvfs") == -1) { - return; - } - } + if (fstatvfs == NULL) { + if (PyObject_DelAttrString(m, "fstatvfs") == -1) { + return; + } + } #endif /* HAVE_FSTATVFS */ #ifdef HAVE_STATVFS - if (statvfs == NULL) { - if (PyObject_DelAttrString(m, "statvfs") == -1) { - return; - } - } + if (statvfs == NULL) { + if (PyObject_DelAttrString(m, "statvfs") == -1) { + return; + } + } #endif /* HAVE_STATVFS */ # ifdef HAVE_LCHOWN - if (lchown == NULL) { - if (PyObject_DelAttrString(m, "lchown") == -1) { - return; - } - } + if (lchown == NULL) { + if (PyObject_DelAttrString(m, "lchown") == -1) { + return; + } + } #endif /* HAVE_LCHOWN */ From python-checkins at python.org Thu May 6 02:25:40 2010 From: python-checkins at python.org (victor.stinner) Date: Thu, 6 May 2010 02:25:40 +0200 (CEST) Subject: [Python-checkins] r80848 - in python/branches/release31-maint: Modules/posixmodule.c Message-ID: <20100506002540.32C6AEE9A9@mail.python.org> Author: victor.stinner Date: Thu May 6 02:25:39 2010 New Revision: 80848 Log: Recorded merge of revisions 80846 via svnmerge from svn+ssh://pythondev at svn.python.org/python/branches/py3k ................ r80846 | victor.stinner | 2010-05-06 02:08:46 +0200 (jeu., 06 mai 2010) | 20 lines Recorded merge of revisions 80844-80845 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r80844 | victor.stinner | 2010-05-06 01:33:33 +0200 (jeu., 06 mai 2010) | 5 lines Untabify Modules/posixmodule.c Run Antoine Pitrou "untabify" script + manual editions (OS/2 and some continuation lines). ........ r80845 | victor.stinner | 2010-05-06 02:03:44 +0200 (jeu., 06 mai 2010) | 4 lines Untabify Modules/posixmodule.c (2) Fix some more functions by hand ........ I rewrote the patch for py3k from scratch using untabify + manual editions ................ Modified: python/branches/release31-maint/ (props changed) python/branches/release31-maint/Modules/posixmodule.c Modified: python/branches/release31-maint/Modules/posixmodule.c ============================================================================== --- python/branches/release31-maint/Modules/posixmodule.c (original) +++ python/branches/release31-maint/Modules/posixmodule.c Thu May 6 02:25:39 2010 @@ -15,7 +15,7 @@ #ifdef __APPLE__ /* - * Step 1 of support for weak-linking a number of symbols existing on + * Step 1 of support for weak-linking a number of symbols existing on * OSX 10.4 and later, see the comment in the #ifdef __APPLE__ block * at the end of this file for more information. */ @@ -69,7 +69,7 @@ #endif /* HAVE_SYS_STAT_H */ #ifdef HAVE_SYS_WAIT_H -#include /* For WNOHANG */ +#include /* For WNOHANG */ #endif #ifdef HAVE_SIGNAL_H @@ -101,41 +101,41 @@ #if defined(PYCC_VACPP) && defined(PYOS_OS2) #include #else -#if defined(__WATCOMC__) && !defined(__QNX__) /* Watcom compiler */ +#if defined(__WATCOMC__) && !defined(__QNX__) /* Watcom compiler */ #define HAVE_GETCWD 1 #define HAVE_OPENDIR 1 -#define HAVE_SYSTEM 1 +#define HAVE_SYSTEM 1 #if defined(__OS2__) #define HAVE_EXECV 1 #define HAVE_WAIT 1 #endif #include #else -#ifdef __BORLANDC__ /* Borland compiler */ +#ifdef __BORLANDC__ /* Borland compiler */ #define HAVE_EXECV 1 #define HAVE_GETCWD 1 #define HAVE_OPENDIR 1 #define HAVE_PIPE 1 -#define HAVE_SYSTEM 1 +#define HAVE_SYSTEM 1 #define HAVE_WAIT 1 #else -#ifdef _MSC_VER /* Microsoft compiler */ +#ifdef _MSC_VER /* Microsoft compiler */ #define HAVE_GETCWD 1 -#define HAVE_SPAWNV 1 +#define HAVE_SPAWNV 1 #define HAVE_EXECV 1 #define HAVE_PIPE 1 -#define HAVE_SYSTEM 1 -#define HAVE_CWAIT 1 -#define HAVE_FSYNC 1 +#define HAVE_SYSTEM 1 +#define HAVE_CWAIT 1 +#define HAVE_FSYNC 1 #define fsync _commit #else #if defined(PYOS_OS2) && defined(PYCC_GCC) || defined(__VMS) /* Everything needed is defined in PC/os2emx/pyconfig.h or vms/pyconfig.h */ -#else /* all other compilers */ +#else /* all other compilers */ /* Unix functions that the configure script doesn't check for */ #define HAVE_EXECV 1 #define HAVE_FORK 1 -#if defined(__USLC__) && defined(__SCO_VERSION__) /* SCO UDK Compiler */ +#if defined(__USLC__) && defined(__SCO_VERSION__) /* SCO UDK Compiler */ #define HAVE_FORK1 1 #endif #define HAVE_GETCWD 1 @@ -147,9 +147,9 @@ #define HAVE_KILL 1 #define HAVE_OPENDIR 1 #define HAVE_PIPE 1 -#define HAVE_SYSTEM 1 +#define HAVE_SYSTEM 1 #define HAVE_WAIT 1 -#define HAVE_TTYNAME 1 +#define HAVE_TTYNAME 1 #endif /* PYOS_OS2 && PYCC_GCC && __VMS */ #endif /* _MSC_VER */ #endif /* __BORLANDC__ */ @@ -265,7 +265,7 @@ #include "osdefs.h" #include #include -#include /* for ShellExecute() */ +#include /* for ShellExecute() */ #endif /* _MSC_VER */ #if defined(PYCC_VACPP) && defined(PYOS_OS2) @@ -329,13 +329,13 @@ /* choose the appropriate stat and fstat functions and return structs */ #undef STAT #if defined(MS_WIN64) || defined(MS_WINDOWS) -# define STAT win32_stat -# define FSTAT win32_fstat -# define STRUCT_STAT struct win32_stat -#else -# define STAT stat -# define FSTAT fstat -# define STRUCT_STAT struct stat +# define STAT win32_stat +# define FSTAT win32_fstat +# define STRUCT_STAT struct win32_stat +#else +# define STAT stat +# define FSTAT fstat +# define STRUCT_STAT struct stat #endif #if defined(MAJOR_IN_MKDEV) @@ -362,7 +362,7 @@ * as a fd and should merely raise a python exception on error. * The Microsoft CRT doesn't provide an official way to check for the * validity of a file descriptor, but we can emulate its internal behaviour - * by using the exported __pinfo data member and knowledge of the + * by using the exported __pinfo data member and knowledge of the * internal structures involved. * The structures below must be updated for each version of visual studio * according to the file internal.h in the CRT source, until MS comes @@ -374,8 +374,8 @@ * Only the first items must be present. */ typedef struct { - intptr_t osfhnd; - char osfile; + intptr_t osfhnd; + char osfile; } my_ioinfo; extern __declspec(dllimport) char * __pioinfo[]; @@ -390,52 +390,52 @@ int _PyVerify_fd(int fd) { - const int i1 = fd >> IOINFO_L2E; - const int i2 = fd & ((1 << IOINFO_L2E) - 1); - - static int sizeof_ioinfo = 0; - - /* Determine the actual size of the ioinfo structure, - * as used by the CRT loaded in memory - */ - if (sizeof_ioinfo == 0 && __pioinfo[0] != NULL) { - sizeof_ioinfo = _msize(__pioinfo[0]) / IOINFO_ARRAY_ELTS; - } - if (sizeof_ioinfo == 0) { - /* This should not happen... */ - goto fail; - } - - /* See that it isn't a special CLEAR fileno */ - if (fd != _NO_CONSOLE_FILENO) { - /* Microsoft CRT would check that 0<=fd<_nhandle but we can't do that. Instead - * we check pointer validity and other info - */ - if (0 <= i1 && i1 < IOINFO_ARRAYS && __pioinfo[i1] != NULL) { - /* finally, check that the file is open */ - my_ioinfo* info = (my_ioinfo*)(__pioinfo[i1] + i2 * sizeof_ioinfo); - if (info->osfile & FOPEN) { - return 1; - } - } - } + const int i1 = fd >> IOINFO_L2E; + const int i2 = fd & ((1 << IOINFO_L2E) - 1); + + static int sizeof_ioinfo = 0; + + /* Determine the actual size of the ioinfo structure, + * as used by the CRT loaded in memory + */ + if (sizeof_ioinfo == 0 && __pioinfo[0] != NULL) { + sizeof_ioinfo = _msize(__pioinfo[0]) / IOINFO_ARRAY_ELTS; + } + if (sizeof_ioinfo == 0) { + /* This should not happen... */ + goto fail; + } + + /* See that it isn't a special CLEAR fileno */ + if (fd != _NO_CONSOLE_FILENO) { + /* Microsoft CRT would check that 0<=fd<_nhandle but we can't do that. Instead + * we check pointer validity and other info + */ + if (0 <= i1 && i1 < IOINFO_ARRAYS && __pioinfo[i1] != NULL) { + /* finally, check that the file is open */ + my_ioinfo* info = (my_ioinfo*)(__pioinfo[i1] + i2 * sizeof_ioinfo); + if (info->osfile & FOPEN) { + return 1; + } + } + } fail: - errno = EBADF; - return 0; + errno = EBADF; + return 0; } /* the special case of checking dup2. The target fd must be in a sensible range */ static int _PyVerify_fd_dup2(int fd1, int fd2) { - if (!_PyVerify_fd(fd1)) - return 0; - if (fd2 == _NO_CONSOLE_FILENO) - return 0; - if ((unsigned)fd2 < _NHANDLE_) - return 1; - else - return 0; + if (!_PyVerify_fd(fd1)) + return 0; + if (fd2 == _NO_CONSOLE_FILENO) + return 0; + if ((unsigned)fd2 < _NHANDLE_) + return 1; + else + return 0; } #else /* dummy version. _PyVerify_fd() is already defined in fileobject.h */ @@ -456,101 +456,101 @@ static PyObject * convertenviron(void) { - PyObject *d; + PyObject *d; #ifdef MS_WINDOWS - wchar_t **e; + wchar_t **e; #else - char **e; + char **e; #endif - d = PyDict_New(); - if (d == NULL) - return NULL; +#if defined(PYOS_OS2) + APIRET rc; + char buffer[1024]; /* OS/2 Provides a Documented Max of 1024 Chars */ +#endif + + d = PyDict_New(); + if (d == NULL) + return NULL; #ifdef WITH_NEXT_FRAMEWORK - if (environ == NULL) - environ = *_NSGetEnviron(); + if (environ == NULL) + environ = *_NSGetEnviron(); #endif #ifdef MS_WINDOWS - /* _wenviron must be initialized in this way if the program is started - through main() instead of wmain(). */ - _wgetenv(L""); - if (_wenviron == NULL) - return d; - /* This part ignores errors */ - for (e = _wenviron; *e != NULL; e++) { - PyObject *k; - PyObject *v; - wchar_t *p = wcschr(*e, L'='); - if (p == NULL) - continue; - k = PyUnicode_FromWideChar(*e, (Py_ssize_t)(p-*e)); - if (k == NULL) { - PyErr_Clear(); - continue; - } - v = PyUnicode_FromWideChar(p+1, wcslen(p+1)); - if (v == NULL) { - PyErr_Clear(); - Py_DECREF(k); - continue; - } - if (PyDict_GetItem(d, k) == NULL) { - if (PyDict_SetItem(d, k, v) != 0) - PyErr_Clear(); - } - Py_DECREF(k); - Py_DECREF(v); - } -#else - if (environ == NULL) - return d; - /* This part ignores errors */ - for (e = environ; *e != NULL; e++) { - PyObject *k; - PyObject *v; - char *p = strchr(*e, '='); - if (p == NULL) - continue; - k = PyUnicode_Decode(*e, (int)(p-*e), - Py_FileSystemDefaultEncoding, "surrogateescape"); - if (k == NULL) { - PyErr_Clear(); - continue; - } - v = PyUnicode_Decode(p+1, strlen(p+1), - Py_FileSystemDefaultEncoding, "surrogateescape"); - if (v == NULL) { - PyErr_Clear(); - Py_DECREF(k); - continue; - } - if (PyDict_GetItem(d, k) == NULL) { - if (PyDict_SetItem(d, k, v) != 0) - PyErr_Clear(); - } - Py_DECREF(k); - Py_DECREF(v); - } -#endif -#if defined(PYOS_OS2) - { - APIRET rc; - char buffer[1024]; /* OS/2 Provides a Documented Max of 1024 Chars */ - - rc = DosQueryExtLIBPATH(buffer, BEGIN_LIBPATH); - if (rc == NO_ERROR) { /* (not a type, envname is NOT 'BEGIN_LIBPATH') */ - PyObject *v = PyBytes_FromString(buffer); - PyDict_SetItemString(d, "BEGINLIBPATH", v); - Py_DECREF(v); + /* _wenviron must be initialized in this way if the program is started + through main() instead of wmain(). */ + _wgetenv(L""); + if (_wenviron == NULL) + return d; + /* This part ignores errors */ + for (e = _wenviron; *e != NULL; e++) { + PyObject *k; + PyObject *v; + wchar_t *p = wcschr(*e, L'='); + if (p == NULL) + continue; + k = PyUnicode_FromWideChar(*e, (Py_ssize_t)(p-*e)); + if (k == NULL) { + PyErr_Clear(); + continue; } - rc = DosQueryExtLIBPATH(buffer, END_LIBPATH); - if (rc == NO_ERROR) { /* (not a typo, envname is NOT 'END_LIBPATH') */ - PyObject *v = PyBytes_FromString(buffer); - PyDict_SetItemString(d, "ENDLIBPATH", v); - Py_DECREF(v); + v = PyUnicode_FromWideChar(p+1, wcslen(p+1)); + if (v == NULL) { + PyErr_Clear(); + Py_DECREF(k); + continue; + } + if (PyDict_GetItem(d, k) == NULL) { + if (PyDict_SetItem(d, k, v) != 0) + PyErr_Clear(); + } + Py_DECREF(k); + Py_DECREF(v); + } +#else + if (environ == NULL) + return d; + /* This part ignores errors */ + for (e = environ; *e != NULL; e++) { + PyObject *k; + PyObject *v; + char *p = strchr(*e, '='); + if (p == NULL) + continue; + k = PyUnicode_Decode(*e, (int)(p-*e), + Py_FileSystemDefaultEncoding, "surrogateescape"); + if (k == NULL) { + PyErr_Clear(); + continue; + } + v = PyUnicode_Decode(p+1, strlen(p+1), + Py_FileSystemDefaultEncoding, "surrogateescape"); + if (v == NULL) { + PyErr_Clear(); + Py_DECREF(k); + continue; } + if (PyDict_GetItem(d, k) == NULL) { + if (PyDict_SetItem(d, k, v) != 0) + PyErr_Clear(); + } + Py_DECREF(k); + Py_DECREF(v); + } +#endif +#if defined(PYOS_OS2) + rc = DosQueryExtLIBPATH(buffer, BEGIN_LIBPATH); + if (rc == NO_ERROR) { /* (not a type, envname is NOT 'BEGIN_LIBPATH') */ + PyObject *v = PyBytes_FromString(buffer); + PyDict_SetItemString(d, "BEGINLIBPATH", v); + Py_DECREF(v); + } + rc = DosQueryExtLIBPATH(buffer, END_LIBPATH); + if (rc == NO_ERROR) { /* (not a typo, envname is NOT 'END_LIBPATH') */ + PyObject *v = PyBytes_FromString(buffer); + PyDict_SetItemString(d, "ENDLIBPATH", v); + Py_DECREF(v); } #endif - return d; + return d; } /* Convert a bytes object to a char*. Optionally lock the buffer if it is a @@ -559,29 +559,29 @@ static char* bytes2str(PyObject* o, int lock) { - if(PyBytes_Check(o)) - return PyBytes_AsString(o); - else if(PyByteArray_Check(o)) { - if (lock && PyObject_GetBuffer(o, NULL, 0) < 0) - /* On a bytearray, this should not fail. */ - PyErr_BadInternalCall(); - return PyByteArray_AsString(o); - } else { - /* The FS converter should have verified that this - is either bytes or bytearray. */ - Py_FatalError("bad object passed to bytes2str"); - /* not reached. */ - return ""; - } + if(PyBytes_Check(o)) + return PyBytes_AsString(o); + else if(PyByteArray_Check(o)) { + if (lock && PyObject_GetBuffer(o, NULL, 0) < 0) + /* On a bytearray, this should not fail. */ + PyErr_BadInternalCall(); + return PyByteArray_AsString(o); + } else { + /* The FS converter should have verified that this + is either bytes or bytearray. */ + Py_FatalError("bad object passed to bytes2str"); + /* not reached. */ + return ""; + } } /* Release the lock, decref the object. */ static void release_bytes(PyObject* o) { - if (PyByteArray_Check(o)) - o->ob_type->tp_as_buffer->bf_releasebuffer(o, 0); - Py_DECREF(o); + if (PyByteArray_Check(o)) + o->ob_type->tp_as_buffer->bf_releasebuffer(o, 0); + Py_DECREF(o); } @@ -590,19 +590,19 @@ static PyObject * posix_error(void) { - return PyErr_SetFromErrno(PyExc_OSError); + return PyErr_SetFromErrno(PyExc_OSError); } static PyObject * posix_error_with_filename(char* name) { - return PyErr_SetFromErrnoWithFilename(PyExc_OSError, name); + return PyErr_SetFromErrnoWithFilename(PyExc_OSError, name); } #ifdef MS_WINDOWS static PyObject * posix_error_with_unicode_filename(Py_UNICODE* name) { - return PyErr_SetFromErrnoWithUnicodeFilename(PyExc_OSError, name); + return PyErr_SetFromErrnoWithUnicodeFilename(PyExc_OSError, name); } #endif /* MS_WINDOWS */ @@ -610,54 +610,54 @@ static PyObject * posix_error_with_allocated_filename(PyObject* name) { - PyObject *rc = PyErr_SetFromErrnoWithFilename(PyExc_OSError, - bytes2str(name, 0)); - release_bytes(name); - return rc; + PyObject *rc = PyErr_SetFromErrnoWithFilename(PyExc_OSError, + bytes2str(name, 0)); + release_bytes(name); + return rc; } #ifdef MS_WINDOWS static PyObject * win32_error(char* function, char* filename) { - /* XXX We should pass the function name along in the future. - (winreg.c also wants to pass the function name.) - This would however require an additional param to the - Windows error object, which is non-trivial. - */ - errno = GetLastError(); - if (filename) - return PyErr_SetFromWindowsErrWithFilename(errno, filename); - else - return PyErr_SetFromWindowsErr(errno); + /* XXX We should pass the function name along in the future. + (winreg.c also wants to pass the function name.) + This would however require an additional param to the + Windows error object, which is non-trivial. + */ + errno = GetLastError(); + if (filename) + return PyErr_SetFromWindowsErrWithFilename(errno, filename); + else + return PyErr_SetFromWindowsErr(errno); } static PyObject * win32_error_unicode(char* function, Py_UNICODE* filename) { - /* XXX - see win32_error for comments on 'function' */ - errno = GetLastError(); - if (filename) - return PyErr_SetFromWindowsErrWithUnicodeFilename(errno, filename); - else - return PyErr_SetFromWindowsErr(errno); + /* XXX - see win32_error for comments on 'function' */ + errno = GetLastError(); + if (filename) + return PyErr_SetFromWindowsErrWithUnicodeFilename(errno, filename); + else + return PyErr_SetFromWindowsErr(errno); } static int convert_to_unicode(PyObject **param) { - if (PyUnicode_CheckExact(*param)) - Py_INCREF(*param); - else if (PyUnicode_Check(*param)) - /* For a Unicode subtype that's not a Unicode object, - return a true Unicode object with the same data. */ - *param = PyUnicode_FromUnicode(PyUnicode_AS_UNICODE(*param), - PyUnicode_GET_SIZE(*param)); - else - *param = PyUnicode_FromEncodedObject(*param, - Py_FileSystemDefaultEncoding, - "strict"); - return (*param) != NULL; + if (PyUnicode_CheckExact(*param)) + Py_INCREF(*param); + else if (PyUnicode_Check(*param)) + /* For a Unicode subtype that's not a Unicode object, + return a true Unicode object with the same data. */ + *param = PyUnicode_FromUnicode(PyUnicode_AS_UNICODE(*param), + PyUnicode_GET_SIZE(*param)); + else + *param = PyUnicode_FromEncodedObject(*param, + Py_FileSystemDefaultEncoding, + "strict"); + return (*param) != NULL; } #endif /* MS_WINDOWS */ @@ -666,7 +666,7 @@ /********************************************************************** * Helper Function to Trim and Format OS/2 Messages **********************************************************************/ - static void +static void os2_formatmsg(char *msgbuf, int msglen, char *reason) { msgbuf[msglen] = '\0'; /* OS/2 Doesn't Guarantee a Terminator */ @@ -696,7 +696,7 @@ * the file OSO001.MSG in the \OS2 directory hierarchy. * **********************************************************************/ - static char * +static char * os2_strerror(char *msgbuf, int msgbuflen, int errorcode, char *reason) { APIRET rc; @@ -712,7 +712,7 @@ os2_formatmsg(msgbuf, msglen, reason); else PyOS_snprintf(msgbuf, msgbuflen, - "unknown OS error #%d", errorcode); + "unknown OS error #%d", errorcode); return msgbuf; } @@ -721,7 +721,8 @@ errors are not in a global variable e.g. 'errno' nor are they congruent with posix error numbers. */ -static PyObject * os2_error(int code) +static PyObject * +os2_error(int code) { char text[1024]; PyObject *v; @@ -743,114 +744,114 @@ static PyObject * posix_fildes(PyObject *fdobj, int (*func)(int)) { - int fd; - int res; - fd = PyObject_AsFileDescriptor(fdobj); - if (fd < 0) - return NULL; - if (!_PyVerify_fd(fd)) - return posix_error(); - Py_BEGIN_ALLOW_THREADS - res = (*func)(fd); - Py_END_ALLOW_THREADS - if (res < 0) - return posix_error(); - Py_INCREF(Py_None); - return Py_None; + int fd; + int res; + fd = PyObject_AsFileDescriptor(fdobj); + if (fd < 0) + return NULL; + if (!_PyVerify_fd(fd)) + return posix_error(); + Py_BEGIN_ALLOW_THREADS + res = (*func)(fd); + Py_END_ALLOW_THREADS + if (res < 0) + return posix_error(); + Py_INCREF(Py_None); + return Py_None; } #ifdef MS_WINDOWS static int unicode_file_names(void) { - static int canusewide = -1; - if (canusewide == -1) { - /* As per doc for ::GetVersion(), this is the correct test for - the Windows NT family. */ - canusewide = (GetVersion() < 0x80000000) ? 1 : 0; - } - return canusewide; + static int canusewide = -1; + if (canusewide == -1) { + /* As per doc for ::GetVersion(), this is the correct test for + the Windows NT family. */ + canusewide = (GetVersion() < 0x80000000) ? 1 : 0; + } + return canusewide; } #endif static PyObject * posix_1str(PyObject *args, char *format, int (*func)(const char*)) { - PyObject *opath1 = NULL; - char *path1; - int res; - if (!PyArg_ParseTuple(args, format, - PyUnicode_FSConverter, &opath1)) - return NULL; - path1 = bytes2str(opath1, 1); - Py_BEGIN_ALLOW_THREADS - res = (*func)(path1); - Py_END_ALLOW_THREADS - if (res < 0) - return posix_error_with_allocated_filename(opath1); - release_bytes(opath1); - Py_INCREF(Py_None); - return Py_None; + PyObject *opath1 = NULL; + char *path1; + int res; + if (!PyArg_ParseTuple(args, format, + PyUnicode_FSConverter, &opath1)) + return NULL; + path1 = bytes2str(opath1, 1); + Py_BEGIN_ALLOW_THREADS + res = (*func)(path1); + Py_END_ALLOW_THREADS + if (res < 0) + return posix_error_with_allocated_filename(opath1); + release_bytes(opath1); + Py_INCREF(Py_None); + return Py_None; } static PyObject * posix_2str(PyObject *args, - char *format, - int (*func)(const char *, const char *)) + char *format, + int (*func)(const char *, const char *)) { - PyObject *opath1 = NULL, *opath2 = NULL; - char *path1, *path2; - int res; - if (!PyArg_ParseTuple(args, format, - PyUnicode_FSConverter, &opath1, - PyUnicode_FSConverter, &opath2)) { - return NULL; - } - path1 = bytes2str(opath1, 1); - path2 = bytes2str(opath2, 1); - Py_BEGIN_ALLOW_THREADS - res = (*func)(path1, path2); - Py_END_ALLOW_THREADS - release_bytes(opath1); - release_bytes(opath2); - if (res != 0) - /* XXX how to report both path1 and path2??? */ - return posix_error(); - Py_INCREF(Py_None); - return Py_None; + PyObject *opath1 = NULL, *opath2 = NULL; + char *path1, *path2; + int res; + if (!PyArg_ParseTuple(args, format, + PyUnicode_FSConverter, &opath1, + PyUnicode_FSConverter, &opath2)) { + return NULL; + } + path1 = bytes2str(opath1, 1); + path2 = bytes2str(opath2, 1); + Py_BEGIN_ALLOW_THREADS + res = (*func)(path1, path2); + Py_END_ALLOW_THREADS + release_bytes(opath1); + release_bytes(opath2); + if (res != 0) + /* XXX how to report both path1 and path2??? */ + return posix_error(); + Py_INCREF(Py_None); + return Py_None; } #ifdef MS_WINDOWS static PyObject* -win32_1str(PyObject* args, char* func, - char* format, BOOL (__stdcall *funcA)(LPCSTR), - char* wformat, BOOL (__stdcall *funcW)(LPWSTR)) -{ - PyObject *uni; - char *ansi; - BOOL result; - if (unicode_file_names()) { - if (!PyArg_ParseTuple(args, wformat, &uni)) - PyErr_Clear(); - else { - Py_BEGIN_ALLOW_THREADS - result = funcW(PyUnicode_AsUnicode(uni)); - Py_END_ALLOW_THREADS - if (!result) - return win32_error_unicode(func, PyUnicode_AsUnicode(uni)); - Py_INCREF(Py_None); - return Py_None; - } - } - if (!PyArg_ParseTuple(args, format, &ansi)) - return NULL; - Py_BEGIN_ALLOW_THREADS - result = funcA(ansi); - Py_END_ALLOW_THREADS - if (!result) - return win32_error(func, ansi); - Py_INCREF(Py_None); - return Py_None; +win32_1str(PyObject* args, char* func, + char* format, BOOL (__stdcall *funcA)(LPCSTR), + char* wformat, BOOL (__stdcall *funcW)(LPWSTR)) +{ + PyObject *uni; + char *ansi; + BOOL result; + if (unicode_file_names()) { + if (!PyArg_ParseTuple(args, wformat, &uni)) + PyErr_Clear(); + else { + Py_BEGIN_ALLOW_THREADS + result = funcW(PyUnicode_AsUnicode(uni)); + Py_END_ALLOW_THREADS + if (!result) + return win32_error_unicode(func, PyUnicode_AsUnicode(uni)); + Py_INCREF(Py_None); + return Py_None; + } + } + if (!PyArg_ParseTuple(args, format, &ansi)) + return NULL; + Py_BEGIN_ALLOW_THREADS + result = funcA(ansi); + Py_END_ALLOW_THREADS + if (!result) + return win32_error(func, ansi); + Py_INCREF(Py_None); + return Py_None; } @@ -862,24 +863,24 @@ static BOOL __stdcall win32_chdir(LPCSTR path) { - char new_path[MAX_PATH+1]; - int result; - char env[4] = "=x:"; - - if(!SetCurrentDirectoryA(path)) - return FALSE; - result = GetCurrentDirectoryA(MAX_PATH+1, new_path); - if (!result) - return FALSE; - /* In the ANSI API, there should not be any paths longer - than MAX_PATH. */ - assert(result <= MAX_PATH+1); - if (strncmp(new_path, "\\\\", 2) == 0 || - strncmp(new_path, "//", 2) == 0) - /* UNC path, nothing to do. */ - return TRUE; - env[1] = new_path[0]; - return SetEnvironmentVariableA(env, new_path); + char new_path[MAX_PATH+1]; + int result; + char env[4] = "=x:"; + + if(!SetCurrentDirectoryA(path)) + return FALSE; + result = GetCurrentDirectoryA(MAX_PATH+1, new_path); + if (!result) + return FALSE; + /* In the ANSI API, there should not be any paths longer + than MAX_PATH. */ + assert(result <= MAX_PATH+1); + if (strncmp(new_path, "\\\\", 2) == 0 || + strncmp(new_path, "//", 2) == 0) + /* UNC path, nothing to do. */ + return TRUE; + env[1] = new_path[0]; + return SetEnvironmentVariableA(env, new_path); } /* The Unicode version differs from the ANSI version @@ -887,36 +888,36 @@ static BOOL __stdcall win32_wchdir(LPCWSTR path) { - wchar_t _new_path[MAX_PATH+1], *new_path = _new_path; - int result; - wchar_t env[4] = L"=x:"; - - if(!SetCurrentDirectoryW(path)) - return FALSE; - result = GetCurrentDirectoryW(MAX_PATH+1, new_path); - if (!result) - return FALSE; - if (result > MAX_PATH+1) { - new_path = malloc(result * sizeof(wchar_t)); - if (!new_path) { - SetLastError(ERROR_OUTOFMEMORY); - return FALSE; - } - result = GetCurrentDirectoryW(result, new_path); - if (!result) { - free(new_path); - return FALSE; - } - } - if (wcsncmp(new_path, L"\\\\", 2) == 0 || - wcsncmp(new_path, L"//", 2) == 0) - /* UNC path, nothing to do. */ - return TRUE; - env[1] = new_path[0]; - result = SetEnvironmentVariableW(env, new_path); - if (new_path != _new_path) - free(new_path); - return result; + wchar_t _new_path[MAX_PATH+1], *new_path = _new_path; + int result; + wchar_t env[4] = L"=x:"; + + if(!SetCurrentDirectoryW(path)) + return FALSE; + result = GetCurrentDirectoryW(MAX_PATH+1, new_path); + if (!result) + return FALSE; + if (result > MAX_PATH+1) { + new_path = malloc(result * sizeof(wchar_t)); + if (!new_path) { + SetLastError(ERROR_OUTOFMEMORY); + return FALSE; + } + result = GetCurrentDirectoryW(result, new_path); + if (!result) { + free(new_path); + return FALSE; + } + } + if (wcsncmp(new_path, L"\\\\", 2) == 0 || + wcsncmp(new_path, L"//", 2) == 0) + /* UNC path, nothing to do. */ + return TRUE; + env[1] = new_path[0]; + result = SetEnvironmentVariableW(env, new_path); + if (new_path != _new_path) + free(new_path); + return result; } #endif @@ -927,7 +928,7 @@ UTC and local time Therefore, we implement our own stat, based on the Win32 API directly. */ -#define HAVE_STAT_NSEC 1 +#define HAVE_STAT_NSEC 1 struct win32_stat{ int st_dev; @@ -951,24 +952,24 @@ static void FILE_TIME_to_time_t_nsec(FILETIME *in_ptr, int *time_out, int* nsec_out) { - /* XXX endianness. Shouldn't matter, as all Windows implementations are little-endian */ - /* Cannot simply cast and dereference in_ptr, - since it might not be aligned properly */ - __int64 in; - memcpy(&in, in_ptr, sizeof(in)); - *nsec_out = (int)(in % 10000000) * 100; /* FILETIME is in units of 100 nsec. */ - /* XXX Win32 supports time stamps past 2038; we currently don't */ - *time_out = Py_SAFE_DOWNCAST((in / 10000000) - secs_between_epochs, __int64, int); + /* XXX endianness. Shouldn't matter, as all Windows implementations are little-endian */ + /* Cannot simply cast and dereference in_ptr, + since it might not be aligned properly */ + __int64 in; + memcpy(&in, in_ptr, sizeof(in)); + *nsec_out = (int)(in % 10000000) * 100; /* FILETIME is in units of 100 nsec. */ + /* XXX Win32 supports time stamps past 2038; we currently don't */ + *time_out = Py_SAFE_DOWNCAST((in / 10000000) - secs_between_epochs, __int64, int); } static void time_t_to_FILE_TIME(int time_in, int nsec_in, FILETIME *out_ptr) { - /* XXX endianness */ - __int64 out; - out = time_in + secs_between_epochs; - out = out * 10000000 + nsec_in / 100; - memcpy(out_ptr, &out, sizeof(out)); + /* XXX endianness */ + __int64 out; + out = time_in + secs_between_epochs; + out = out * 10000000 + nsec_in / 100; + memcpy(out_ptr, &out, sizeof(out)); } /* Below, we *know* that ugo+r is 0444 */ @@ -978,29 +979,29 @@ static int attributes_to_mode(DWORD attr) { - int m = 0; - if (attr & FILE_ATTRIBUTE_DIRECTORY) - m |= _S_IFDIR | 0111; /* IFEXEC for user,group,other */ - else - m |= _S_IFREG; - if (attr & FILE_ATTRIBUTE_READONLY) - m |= 0444; - else - m |= 0666; - return m; + int m = 0; + if (attr & FILE_ATTRIBUTE_DIRECTORY) + m |= _S_IFDIR | 0111; /* IFEXEC for user,group,other */ + else + m |= _S_IFREG; + if (attr & FILE_ATTRIBUTE_READONLY) + m |= 0444; + else + m |= 0666; + return m; } static int attribute_data_to_stat(WIN32_FILE_ATTRIBUTE_DATA *info, struct win32_stat *result) { - memset(result, 0, sizeof(*result)); - result->st_mode = attributes_to_mode(info->dwFileAttributes); - result->st_size = (((__int64)info->nFileSizeHigh)<<32) + info->nFileSizeLow; - FILE_TIME_to_time_t_nsec(&info->ftCreationTime, &result->st_ctime, &result->st_ctime_nsec); - FILE_TIME_to_time_t_nsec(&info->ftLastWriteTime, &result->st_mtime, &result->st_mtime_nsec); - FILE_TIME_to_time_t_nsec(&info->ftLastAccessTime, &result->st_atime, &result->st_atime_nsec); + memset(result, 0, sizeof(*result)); + result->st_mode = attributes_to_mode(info->dwFileAttributes); + result->st_size = (((__int64)info->nFileSizeHigh)<<32) + info->nFileSizeLow; + FILE_TIME_to_time_t_nsec(&info->ftCreationTime, &result->st_ctime, &result->st_ctime_nsec); + FILE_TIME_to_time_t_nsec(&info->ftLastWriteTime, &result->st_mtime, &result->st_mtime_nsec); + FILE_TIME_to_time_t_nsec(&info->ftLastAccessTime, &result->st_atime, &result->st_atime_nsec); - return 0; + return 0; } /* Emulate GetFileAttributesEx[AW] on Windows 95 */ @@ -1010,239 +1011,239 @@ static void check_gfax() { - HINSTANCE hKernel32; - if (checked) - return; - checked = 1; - hKernel32 = GetModuleHandle("KERNEL32"); - *(FARPROC*)&gfaxa = GetProcAddress(hKernel32, "GetFileAttributesExA"); - *(FARPROC*)&gfaxw = GetProcAddress(hKernel32, "GetFileAttributesExW"); + HINSTANCE hKernel32; + if (checked) + return; + checked = 1; + hKernel32 = GetModuleHandle("KERNEL32"); + *(FARPROC*)&gfaxa = GetProcAddress(hKernel32, "GetFileAttributesExA"); + *(FARPROC*)&gfaxw = GetProcAddress(hKernel32, "GetFileAttributesExW"); } static BOOL attributes_from_dir(LPCSTR pszFile, LPWIN32_FILE_ATTRIBUTE_DATA pfad) { - HANDLE hFindFile; - WIN32_FIND_DATAA FileData; - hFindFile = FindFirstFileA(pszFile, &FileData); - if (hFindFile == INVALID_HANDLE_VALUE) - return FALSE; - FindClose(hFindFile); - pfad->dwFileAttributes = FileData.dwFileAttributes; - pfad->ftCreationTime = FileData.ftCreationTime; - pfad->ftLastAccessTime = FileData.ftLastAccessTime; - pfad->ftLastWriteTime = FileData.ftLastWriteTime; - pfad->nFileSizeHigh = FileData.nFileSizeHigh; - pfad->nFileSizeLow = FileData.nFileSizeLow; - return TRUE; + HANDLE hFindFile; + WIN32_FIND_DATAA FileData; + hFindFile = FindFirstFileA(pszFile, &FileData); + if (hFindFile == INVALID_HANDLE_VALUE) + return FALSE; + FindClose(hFindFile); + pfad->dwFileAttributes = FileData.dwFileAttributes; + pfad->ftCreationTime = FileData.ftCreationTime; + pfad->ftLastAccessTime = FileData.ftLastAccessTime; + pfad->ftLastWriteTime = FileData.ftLastWriteTime; + pfad->nFileSizeHigh = FileData.nFileSizeHigh; + pfad->nFileSizeLow = FileData.nFileSizeLow; + return TRUE; } static BOOL attributes_from_dir_w(LPCWSTR pszFile, LPWIN32_FILE_ATTRIBUTE_DATA pfad) { - HANDLE hFindFile; - WIN32_FIND_DATAW FileData; - hFindFile = FindFirstFileW(pszFile, &FileData); - if (hFindFile == INVALID_HANDLE_VALUE) - return FALSE; - FindClose(hFindFile); - pfad->dwFileAttributes = FileData.dwFileAttributes; - pfad->ftCreationTime = FileData.ftCreationTime; - pfad->ftLastAccessTime = FileData.ftLastAccessTime; - pfad->ftLastWriteTime = FileData.ftLastWriteTime; - pfad->nFileSizeHigh = FileData.nFileSizeHigh; - pfad->nFileSizeLow = FileData.nFileSizeLow; - return TRUE; + HANDLE hFindFile; + WIN32_FIND_DATAW FileData; + hFindFile = FindFirstFileW(pszFile, &FileData); + if (hFindFile == INVALID_HANDLE_VALUE) + return FALSE; + FindClose(hFindFile); + pfad->dwFileAttributes = FileData.dwFileAttributes; + pfad->ftCreationTime = FileData.ftCreationTime; + pfad->ftLastAccessTime = FileData.ftLastAccessTime; + pfad->ftLastWriteTime = FileData.ftLastWriteTime; + pfad->nFileSizeHigh = FileData.nFileSizeHigh; + pfad->nFileSizeLow = FileData.nFileSizeLow; + return TRUE; } static BOOL WINAPI -Py_GetFileAttributesExA(LPCSTR pszFile, - GET_FILEEX_INFO_LEVELS level, +Py_GetFileAttributesExA(LPCSTR pszFile, + GET_FILEEX_INFO_LEVELS level, LPVOID pv) { - BOOL result; - LPWIN32_FILE_ATTRIBUTE_DATA pfad = pv; - /* First try to use the system's implementation, if that is - available and either succeeds to gives an error other than - that it isn't implemented. */ - check_gfax(); - if (gfaxa) { - result = gfaxa(pszFile, level, pv); - if (result || GetLastError() != ERROR_CALL_NOT_IMPLEMENTED) - return result; - } - /* It's either not present, or not implemented. - Emulate using FindFirstFile. */ - if (level != GetFileExInfoStandard) { - SetLastError(ERROR_INVALID_PARAMETER); - return FALSE; - } - /* Use GetFileAttributes to validate that the file name - does not contain wildcards (which FindFirstFile would - accept). */ - if (GetFileAttributesA(pszFile) == 0xFFFFFFFF) - return FALSE; - return attributes_from_dir(pszFile, pfad); + BOOL result; + LPWIN32_FILE_ATTRIBUTE_DATA pfad = pv; + /* First try to use the system's implementation, if that is + available and either succeeds to gives an error other than + that it isn't implemented. */ + check_gfax(); + if (gfaxa) { + result = gfaxa(pszFile, level, pv); + if (result || GetLastError() != ERROR_CALL_NOT_IMPLEMENTED) + return result; + } + /* It's either not present, or not implemented. + Emulate using FindFirstFile. */ + if (level != GetFileExInfoStandard) { + SetLastError(ERROR_INVALID_PARAMETER); + return FALSE; + } + /* Use GetFileAttributes to validate that the file name + does not contain wildcards (which FindFirstFile would + accept). */ + if (GetFileAttributesA(pszFile) == 0xFFFFFFFF) + return FALSE; + return attributes_from_dir(pszFile, pfad); } static BOOL WINAPI -Py_GetFileAttributesExW(LPCWSTR pszFile, - GET_FILEEX_INFO_LEVELS level, +Py_GetFileAttributesExW(LPCWSTR pszFile, + GET_FILEEX_INFO_LEVELS level, LPVOID pv) { - BOOL result; - LPWIN32_FILE_ATTRIBUTE_DATA pfad = pv; - /* First try to use the system's implementation, if that is - available and either succeeds to gives an error other than - that it isn't implemented. */ - check_gfax(); - if (gfaxa) { - result = gfaxw(pszFile, level, pv); - if (result || GetLastError() != ERROR_CALL_NOT_IMPLEMENTED) - return result; - } - /* It's either not present, or not implemented. - Emulate using FindFirstFile. */ - if (level != GetFileExInfoStandard) { - SetLastError(ERROR_INVALID_PARAMETER); - return FALSE; - } - /* Use GetFileAttributes to validate that the file name - does not contain wildcards (which FindFirstFile would - accept). */ - if (GetFileAttributesW(pszFile) == 0xFFFFFFFF) - return FALSE; - return attributes_from_dir_w(pszFile, pfad); + BOOL result; + LPWIN32_FILE_ATTRIBUTE_DATA pfad = pv; + /* First try to use the system's implementation, if that is + available and either succeeds to gives an error other than + that it isn't implemented. */ + check_gfax(); + if (gfaxa) { + result = gfaxw(pszFile, level, pv); + if (result || GetLastError() != ERROR_CALL_NOT_IMPLEMENTED) + return result; + } + /* It's either not present, or not implemented. + Emulate using FindFirstFile. */ + if (level != GetFileExInfoStandard) { + SetLastError(ERROR_INVALID_PARAMETER); + return FALSE; + } + /* Use GetFileAttributes to validate that the file name + does not contain wildcards (which FindFirstFile would + accept). */ + if (GetFileAttributesW(pszFile) == 0xFFFFFFFF) + return FALSE; + return attributes_from_dir_w(pszFile, pfad); } -static int +static int win32_stat(const char* path, struct win32_stat *result) { - WIN32_FILE_ATTRIBUTE_DATA info; - int code; - char *dot; - /* XXX not supported on Win95 and NT 3.x */ - if (!Py_GetFileAttributesExA(path, GetFileExInfoStandard, &info)) { - if (GetLastError() != ERROR_SHARING_VIOLATION) { - /* Protocol violation: we explicitly clear errno, instead of - setting it to a POSIX error. Callers should use GetLastError. */ - errno = 0; - return -1; - } else { - /* Could not get attributes on open file. Fall back to - reading the directory. */ - if (!attributes_from_dir(path, &info)) { - /* Very strange. This should not fail now */ - errno = 0; - return -1; - } - } - } - code = attribute_data_to_stat(&info, result); - if (code != 0) - return code; - /* Set S_IFEXEC if it is an .exe, .bat, ... */ - dot = strrchr(path, '.'); - if (dot) { - if (stricmp(dot, ".bat") == 0 || - stricmp(dot, ".cmd") == 0 || - stricmp(dot, ".exe") == 0 || - stricmp(dot, ".com") == 0) - result->st_mode |= 0111; - } - return code; + WIN32_FILE_ATTRIBUTE_DATA info; + int code; + char *dot; + /* XXX not supported on Win95 and NT 3.x */ + if (!Py_GetFileAttributesExA(path, GetFileExInfoStandard, &info)) { + if (GetLastError() != ERROR_SHARING_VIOLATION) { + /* Protocol violation: we explicitly clear errno, instead of + setting it to a POSIX error. Callers should use GetLastError. */ + errno = 0; + return -1; + } else { + /* Could not get attributes on open file. Fall back to + reading the directory. */ + if (!attributes_from_dir(path, &info)) { + /* Very strange. This should not fail now */ + errno = 0; + return -1; + } + } + } + code = attribute_data_to_stat(&info, result); + if (code != 0) + return code; + /* Set S_IFEXEC if it is an .exe, .bat, ... */ + dot = strrchr(path, '.'); + if (dot) { + if (stricmp(dot, ".bat") == 0 || + stricmp(dot, ".cmd") == 0 || + stricmp(dot, ".exe") == 0 || + stricmp(dot, ".com") == 0) + result->st_mode |= 0111; + } + return code; } -static int +static int win32_wstat(const wchar_t* path, struct win32_stat *result) { - int code; - const wchar_t *dot; - WIN32_FILE_ATTRIBUTE_DATA info; - /* XXX not supported on Win95 and NT 3.x */ - if (!Py_GetFileAttributesExW(path, GetFileExInfoStandard, &info)) { - if (GetLastError() != ERROR_SHARING_VIOLATION) { - /* Protocol violation: we explicitly clear errno, instead of - setting it to a POSIX error. Callers should use GetLastError. */ - errno = 0; - return -1; - } else { - /* Could not get attributes on open file. Fall back to - reading the directory. */ - if (!attributes_from_dir_w(path, &info)) { - /* Very strange. This should not fail now */ - errno = 0; - return -1; - } - } - } - code = attribute_data_to_stat(&info, result); - if (code < 0) - return code; - /* Set IFEXEC if it is an .exe, .bat, ... */ - dot = wcsrchr(path, '.'); - if (dot) { - if (_wcsicmp(dot, L".bat") == 0 || - _wcsicmp(dot, L".cmd") == 0 || - _wcsicmp(dot, L".exe") == 0 || - _wcsicmp(dot, L".com") == 0) - result->st_mode |= 0111; - } - return code; + int code; + const wchar_t *dot; + WIN32_FILE_ATTRIBUTE_DATA info; + /* XXX not supported on Win95 and NT 3.x */ + if (!Py_GetFileAttributesExW(path, GetFileExInfoStandard, &info)) { + if (GetLastError() != ERROR_SHARING_VIOLATION) { + /* Protocol violation: we explicitly clear errno, instead of + setting it to a POSIX error. Callers should use GetLastError. */ + errno = 0; + return -1; + } else { + /* Could not get attributes on open file. Fall back to + reading the directory. */ + if (!attributes_from_dir_w(path, &info)) { + /* Very strange. This should not fail now */ + errno = 0; + return -1; + } + } + } + code = attribute_data_to_stat(&info, result); + if (code < 0) + return code; + /* Set IFEXEC if it is an .exe, .bat, ... */ + dot = wcsrchr(path, '.'); + if (dot) { + if (_wcsicmp(dot, L".bat") == 0 || + _wcsicmp(dot, L".cmd") == 0 || + _wcsicmp(dot, L".exe") == 0 || + _wcsicmp(dot, L".com") == 0) + result->st_mode |= 0111; + } + return code; } static int win32_fstat(int file_number, struct win32_stat *result) { - BY_HANDLE_FILE_INFORMATION info; - HANDLE h; - int type; - - h = (HANDLE)_get_osfhandle(file_number); - - /* Protocol violation: we explicitly clear errno, instead of - setting it to a POSIX error. Callers should use GetLastError. */ - errno = 0; - - if (h == INVALID_HANDLE_VALUE) { - /* This is really a C library error (invalid file handle). - We set the Win32 error to the closes one matching. */ - SetLastError(ERROR_INVALID_HANDLE); - return -1; - } - memset(result, 0, sizeof(*result)); - - type = GetFileType(h); - if (type == FILE_TYPE_UNKNOWN) { - DWORD error = GetLastError(); - if (error != 0) { - return -1; - } - /* else: valid but unknown file */ - } - - if (type != FILE_TYPE_DISK) { - if (type == FILE_TYPE_CHAR) - result->st_mode = _S_IFCHR; - else if (type == FILE_TYPE_PIPE) - result->st_mode = _S_IFIFO; - return 0; - } - - if (!GetFileInformationByHandle(h, &info)) { - return -1; - } - - /* similar to stat() */ - result->st_mode = attributes_to_mode(info.dwFileAttributes); - result->st_size = (((__int64)info.nFileSizeHigh)<<32) + info.nFileSizeLow; - FILE_TIME_to_time_t_nsec(&info.ftCreationTime, &result->st_ctime, &result->st_ctime_nsec); - FILE_TIME_to_time_t_nsec(&info.ftLastWriteTime, &result->st_mtime, &result->st_mtime_nsec); - FILE_TIME_to_time_t_nsec(&info.ftLastAccessTime, &result->st_atime, &result->st_atime_nsec); - /* specific to fstat() */ - result->st_nlink = info.nNumberOfLinks; - result->st_ino = (((__int64)info.nFileIndexHigh)<<32) + info.nFileIndexLow; - return 0; + BY_HANDLE_FILE_INFORMATION info; + HANDLE h; + int type; + + h = (HANDLE)_get_osfhandle(file_number); + + /* Protocol violation: we explicitly clear errno, instead of + setting it to a POSIX error. Callers should use GetLastError. */ + errno = 0; + + if (h == INVALID_HANDLE_VALUE) { + /* This is really a C library error (invalid file handle). + We set the Win32 error to the closes one matching. */ + SetLastError(ERROR_INVALID_HANDLE); + return -1; + } + memset(result, 0, sizeof(*result)); + + type = GetFileType(h); + if (type == FILE_TYPE_UNKNOWN) { + DWORD error = GetLastError(); + if (error != 0) { + return -1; + } + /* else: valid but unknown file */ + } + + if (type != FILE_TYPE_DISK) { + if (type == FILE_TYPE_CHAR) + result->st_mode = _S_IFCHR; + else if (type == FILE_TYPE_PIPE) + result->st_mode = _S_IFIFO; + return 0; + } + + if (!GetFileInformationByHandle(h, &info)) { + return -1; + } + + /* similar to stat() */ + result->st_mode = attributes_to_mode(info.dwFileAttributes); + result->st_size = (((__int64)info.nFileSizeHigh)<<32) + info.nFileSizeLow; + FILE_TIME_to_time_t_nsec(&info.ftCreationTime, &result->st_ctime, &result->st_ctime_nsec); + FILE_TIME_to_time_t_nsec(&info.ftLastWriteTime, &result->st_mtime, &result->st_mtime_nsec); + FILE_TIME_to_time_t_nsec(&info.ftLastAccessTime, &result->st_atime, &result->st_atime_nsec); + /* specific to fstat() */ + result->st_nlink = info.nNumberOfLinks; + result->st_ino = (((__int64)info.nFileIndexHigh)<<32) + info.nFileIndexLow; + return 0; } #endif /* MS_WINDOWS */ @@ -1259,39 +1260,39 @@ See os.stat for more information."); static PyStructSequence_Field stat_result_fields[] = { - {"st_mode", "protection bits"}, - {"st_ino", "inode"}, - {"st_dev", "device"}, - {"st_nlink", "number of hard links"}, - {"st_uid", "user ID of owner"}, - {"st_gid", "group ID of owner"}, - {"st_size", "total size, in bytes"}, - /* The NULL is replaced with PyStructSequence_UnnamedField later. */ - {NULL, "integer time of last access"}, - {NULL, "integer time of last modification"}, - {NULL, "integer time of last change"}, - {"st_atime", "time of last access"}, - {"st_mtime", "time of last modification"}, - {"st_ctime", "time of last change"}, + {"st_mode", "protection bits"}, + {"st_ino", "inode"}, + {"st_dev", "device"}, + {"st_nlink", "number of hard links"}, + {"st_uid", "user ID of owner"}, + {"st_gid", "group ID of owner"}, + {"st_size", "total size, in bytes"}, + /* The NULL is replaced with PyStructSequence_UnnamedField later. */ + {NULL, "integer time of last access"}, + {NULL, "integer time of last modification"}, + {NULL, "integer time of last change"}, + {"st_atime", "time of last access"}, + {"st_mtime", "time of last modification"}, + {"st_ctime", "time of last change"}, #ifdef HAVE_STRUCT_STAT_ST_BLKSIZE - {"st_blksize", "blocksize for filesystem I/O"}, + {"st_blksize", "blocksize for filesystem I/O"}, #endif #ifdef HAVE_STRUCT_STAT_ST_BLOCKS - {"st_blocks", "number of blocks allocated"}, + {"st_blocks", "number of blocks allocated"}, #endif #ifdef HAVE_STRUCT_STAT_ST_RDEV - {"st_rdev", "device type (if inode device)"}, + {"st_rdev", "device type (if inode device)"}, #endif #ifdef HAVE_STRUCT_STAT_ST_FLAGS - {"st_flags", "user defined flags for file"}, + {"st_flags", "user defined flags for file"}, #endif #ifdef HAVE_STRUCT_STAT_ST_GEN - {"st_gen", "generation number"}, + {"st_gen", "generation number"}, #endif #ifdef HAVE_STRUCT_STAT_ST_BIRTHTIME - {"st_birthtime", "time of creation"}, + {"st_birthtime", "time of creation"}, #endif - {0} + {0} }; #ifdef HAVE_STRUCT_STAT_ST_BLKSIZE @@ -1331,10 +1332,10 @@ #endif static PyStructSequence_Desc stat_result_desc = { - "stat_result", /* name */ - stat_result__doc__, /* doc */ - stat_result_fields, - 10 + "stat_result", /* name */ + stat_result__doc__, /* doc */ + stat_result_fields, + 10 }; PyDoc_STRVAR(statvfs_result__doc__, @@ -1346,24 +1347,24 @@ See os.statvfs for more information."); static PyStructSequence_Field statvfs_result_fields[] = { - {"f_bsize", }, - {"f_frsize", }, - {"f_blocks", }, - {"f_bfree", }, - {"f_bavail", }, - {"f_files", }, - {"f_ffree", }, - {"f_favail", }, - {"f_flag", }, - {"f_namemax",}, - {0} + {"f_bsize", }, + {"f_frsize", }, + {"f_blocks", }, + {"f_bfree", }, + {"f_bavail", }, + {"f_files", }, + {"f_ffree", }, + {"f_favail", }, + {"f_flag", }, + {"f_namemax",}, + {0} }; static PyStructSequence_Desc statvfs_result_desc = { - "statvfs_result", /* name */ - statvfs_result__doc__, /* doc */ - statvfs_result_fields, - 10 + "statvfs_result", /* name */ + statvfs_result__doc__, /* doc */ + statvfs_result_fields, + 10 }; static int initialized; @@ -1374,23 +1375,23 @@ static PyObject * statresult_new(PyTypeObject *type, PyObject *args, PyObject *kwds) { - PyStructSequence *result; - int i; + PyStructSequence *result; + int i; - result = (PyStructSequence*)structseq_new(type, args, kwds); - if (!result) - return NULL; - /* If we have been initialized from a tuple, - st_?time might be set to None. Initialize it - from the int slots. */ - for (i = 7; i <= 9; i++) { - if (result->ob_item[i+3] == Py_None) { - Py_DECREF(Py_None); - Py_INCREF(result->ob_item[i]); - result->ob_item[i+3] = result->ob_item[i]; - } - } - return (PyObject*)result; + result = (PyStructSequence*)structseq_new(type, args, kwds); + if (!result) + return NULL; + /* If we have been initialized from a tuple, + st_?time might be set to None. Initialize it + from the int slots. */ + for (i = 7; i <= 9; i++) { + if (result->ob_item[i+3] == Py_None) { + Py_DECREF(Py_None); + Py_INCREF(result->ob_item[i]); + result->ob_item[i+3] = result->ob_item[i]; + } + } + return (PyObject*)result; } @@ -1408,36 +1409,36 @@ static PyObject* stat_float_times(PyObject* self, PyObject *args) { - int newval = -1; - if (!PyArg_ParseTuple(args, "|i:stat_float_times", &newval)) - return NULL; - if (newval == -1) - /* Return old value */ - return PyBool_FromLong(_stat_float_times); - _stat_float_times = newval; - Py_INCREF(Py_None); - return Py_None; + int newval = -1; + if (!PyArg_ParseTuple(args, "|i:stat_float_times", &newval)) + return NULL; + if (newval == -1) + /* Return old value */ + return PyBool_FromLong(_stat_float_times); + _stat_float_times = newval; + Py_INCREF(Py_None); + return Py_None; } static void fill_time(PyObject *v, int index, time_t sec, unsigned long nsec) { - PyObject *fval,*ival; + PyObject *fval,*ival; #if SIZEOF_TIME_T > SIZEOF_LONG - ival = PyLong_FromLongLong((PY_LONG_LONG)sec); + ival = PyLong_FromLongLong((PY_LONG_LONG)sec); #else - ival = PyLong_FromLong((long)sec); + ival = PyLong_FromLong((long)sec); #endif - if (!ival) - return; - if (_stat_float_times) { - fval = PyFloat_FromDouble(sec + 1e-9*nsec); - } else { - fval = ival; - Py_INCREF(fval); - } - PyStructSequence_SET_ITEM(v, index, ival); - PyStructSequence_SET_ITEM(v, index+3, fval); + if (!ival) + return; + if (_stat_float_times) { + fval = PyFloat_FromDouble(sec + 1e-9*nsec); + } else { + fval = ival; + Py_INCREF(fval); + } + PyStructSequence_SET_ITEM(v, index, ival); + PyStructSequence_SET_ITEM(v, index+3, fval); } /* pack a system stat C structure into the Python stat tuple @@ -1445,99 +1446,99 @@ static PyObject* _pystat_fromstructstat(STRUCT_STAT *st) { - unsigned long ansec, mnsec, cnsec; - PyObject *v = PyStructSequence_New(&StatResultType); - if (v == NULL) - return NULL; + unsigned long ansec, mnsec, cnsec; + PyObject *v = PyStructSequence_New(&StatResultType); + if (v == NULL) + return NULL; - PyStructSequence_SET_ITEM(v, 0, PyLong_FromLong((long)st->st_mode)); + PyStructSequence_SET_ITEM(v, 0, PyLong_FromLong((long)st->st_mode)); #ifdef HAVE_LARGEFILE_SUPPORT - PyStructSequence_SET_ITEM(v, 1, - PyLong_FromLongLong((PY_LONG_LONG)st->st_ino)); + PyStructSequence_SET_ITEM(v, 1, + PyLong_FromLongLong((PY_LONG_LONG)st->st_ino)); #else - PyStructSequence_SET_ITEM(v, 1, PyLong_FromLong((long)st->st_ino)); + PyStructSequence_SET_ITEM(v, 1, PyLong_FromLong((long)st->st_ino)); #endif #if defined(HAVE_LONG_LONG) && !defined(MS_WINDOWS) - PyStructSequence_SET_ITEM(v, 2, - PyLong_FromLongLong((PY_LONG_LONG)st->st_dev)); + PyStructSequence_SET_ITEM(v, 2, + PyLong_FromLongLong((PY_LONG_LONG)st->st_dev)); #else - PyStructSequence_SET_ITEM(v, 2, PyLong_FromLong((long)st->st_dev)); + PyStructSequence_SET_ITEM(v, 2, PyLong_FromLong((long)st->st_dev)); #endif - PyStructSequence_SET_ITEM(v, 3, PyLong_FromLong((long)st->st_nlink)); - PyStructSequence_SET_ITEM(v, 4, PyLong_FromLong((long)st->st_uid)); - PyStructSequence_SET_ITEM(v, 5, PyLong_FromLong((long)st->st_gid)); + PyStructSequence_SET_ITEM(v, 3, PyLong_FromLong((long)st->st_nlink)); + PyStructSequence_SET_ITEM(v, 4, PyLong_FromLong((long)st->st_uid)); + PyStructSequence_SET_ITEM(v, 5, PyLong_FromLong((long)st->st_gid)); #ifdef HAVE_LARGEFILE_SUPPORT - PyStructSequence_SET_ITEM(v, 6, - PyLong_FromLongLong((PY_LONG_LONG)st->st_size)); + PyStructSequence_SET_ITEM(v, 6, + PyLong_FromLongLong((PY_LONG_LONG)st->st_size)); #else - PyStructSequence_SET_ITEM(v, 6, PyLong_FromLong(st->st_size)); + PyStructSequence_SET_ITEM(v, 6, PyLong_FromLong(st->st_size)); #endif #if defined(HAVE_STAT_TV_NSEC) - ansec = st->st_atim.tv_nsec; - mnsec = st->st_mtim.tv_nsec; - cnsec = st->st_ctim.tv_nsec; + ansec = st->st_atim.tv_nsec; + mnsec = st->st_mtim.tv_nsec; + cnsec = st->st_ctim.tv_nsec; #elif defined(HAVE_STAT_TV_NSEC2) - ansec = st->st_atimespec.tv_nsec; - mnsec = st->st_mtimespec.tv_nsec; - cnsec = st->st_ctimespec.tv_nsec; + ansec = st->st_atimespec.tv_nsec; + mnsec = st->st_mtimespec.tv_nsec; + cnsec = st->st_ctimespec.tv_nsec; #elif defined(HAVE_STAT_NSEC) - ansec = st->st_atime_nsec; - mnsec = st->st_mtime_nsec; - cnsec = st->st_ctime_nsec; -#else - ansec = mnsec = cnsec = 0; -#endif - fill_time(v, 7, st->st_atime, ansec); - fill_time(v, 8, st->st_mtime, mnsec); - fill_time(v, 9, st->st_ctime, cnsec); + ansec = st->st_atime_nsec; + mnsec = st->st_mtime_nsec; + cnsec = st->st_ctime_nsec; +#else + ansec = mnsec = cnsec = 0; +#endif + fill_time(v, 7, st->st_atime, ansec); + fill_time(v, 8, st->st_mtime, mnsec); + fill_time(v, 9, st->st_ctime, cnsec); #ifdef HAVE_STRUCT_STAT_ST_BLKSIZE - PyStructSequence_SET_ITEM(v, ST_BLKSIZE_IDX, - PyLong_FromLong((long)st->st_blksize)); + PyStructSequence_SET_ITEM(v, ST_BLKSIZE_IDX, + PyLong_FromLong((long)st->st_blksize)); #endif #ifdef HAVE_STRUCT_STAT_ST_BLOCKS - PyStructSequence_SET_ITEM(v, ST_BLOCKS_IDX, - PyLong_FromLong((long)st->st_blocks)); + PyStructSequence_SET_ITEM(v, ST_BLOCKS_IDX, + PyLong_FromLong((long)st->st_blocks)); #endif #ifdef HAVE_STRUCT_STAT_ST_RDEV - PyStructSequence_SET_ITEM(v, ST_RDEV_IDX, - PyLong_FromLong((long)st->st_rdev)); + PyStructSequence_SET_ITEM(v, ST_RDEV_IDX, + PyLong_FromLong((long)st->st_rdev)); #endif #ifdef HAVE_STRUCT_STAT_ST_GEN - PyStructSequence_SET_ITEM(v, ST_GEN_IDX, - PyLong_FromLong((long)st->st_gen)); + PyStructSequence_SET_ITEM(v, ST_GEN_IDX, + PyLong_FromLong((long)st->st_gen)); #endif #ifdef HAVE_STRUCT_STAT_ST_BIRTHTIME - { - PyObject *val; - unsigned long bsec,bnsec; - bsec = (long)st->st_birthtime; + { + PyObject *val; + unsigned long bsec,bnsec; + bsec = (long)st->st_birthtime; #ifdef HAVE_STAT_TV_NSEC2 - bnsec = st->st_birthtimespec.tv_nsec; + bnsec = st->st_birthtimespec.tv_nsec; #else - bnsec = 0; + bnsec = 0; #endif - if (_stat_float_times) { - val = PyFloat_FromDouble(bsec + 1e-9*bnsec); - } else { - val = PyLong_FromLong((long)bsec); - } - PyStructSequence_SET_ITEM(v, ST_BIRTHTIME_IDX, - val); - } + if (_stat_float_times) { + val = PyFloat_FromDouble(bsec + 1e-9*bnsec); + } else { + val = PyLong_FromLong((long)bsec); + } + PyStructSequence_SET_ITEM(v, ST_BIRTHTIME_IDX, + val); + } #endif #ifdef HAVE_STRUCT_STAT_ST_FLAGS - PyStructSequence_SET_ITEM(v, ST_FLAGS_IDX, - PyLong_FromLong((long)st->st_flags)); + PyStructSequence_SET_ITEM(v, ST_FLAGS_IDX, + PyLong_FromLong((long)st->st_flags)); #endif - if (PyErr_Occurred()) { - Py_DECREF(v); - return NULL; - } + if (PyErr_Occurred()) { + Py_DECREF(v); + return NULL; + } - return v; + return v; } #ifdef MS_WINDOWS @@ -1556,111 +1557,111 @@ static BOOL IsUNCRootA(char *path, int pathlen) { - #define ISSLASH ISSLASHA + #define ISSLASH ISSLASHA - int i, share; + int i, share; - if (pathlen < 5 || !ISSLASH(path[0]) || !ISSLASH(path[1])) - /* minimum UNCRoot is \\x\y */ - return FALSE; - for (i = 2; i < pathlen ; i++) - if (ISSLASH(path[i])) break; - if (i == 2 || i == pathlen) - /* do not allow \\\SHARE or \\SERVER */ - return FALSE; - share = i+1; - for (i = share; i < pathlen; i++) - if (ISSLASH(path[i])) break; - return (i != share && (i == pathlen || i == pathlen-1)); + if (pathlen < 5 || !ISSLASH(path[0]) || !ISSLASH(path[1])) + /* minimum UNCRoot is \\x\y */ + return FALSE; + for (i = 2; i < pathlen ; i++) + if (ISSLASH(path[i])) break; + if (i == 2 || i == pathlen) + /* do not allow \\\SHARE or \\SERVER */ + return FALSE; + share = i+1; + for (i = share; i < pathlen; i++) + if (ISSLASH(path[i])) break; + return (i != share && (i == pathlen || i == pathlen-1)); - #undef ISSLASH + #undef ISSLASH } static BOOL IsUNCRootW(Py_UNICODE *path, int pathlen) { - #define ISSLASH ISSLASHW + #define ISSLASH ISSLASHW - int i, share; + int i, share; - if (pathlen < 5 || !ISSLASH(path[0]) || !ISSLASH(path[1])) - /* minimum UNCRoot is \\x\y */ - return FALSE; - for (i = 2; i < pathlen ; i++) - if (ISSLASH(path[i])) break; - if (i == 2 || i == pathlen) - /* do not allow \\\SHARE or \\SERVER */ - return FALSE; - share = i+1; - for (i = share; i < pathlen; i++) - if (ISSLASH(path[i])) break; - return (i != share && (i == pathlen || i == pathlen-1)); + if (pathlen < 5 || !ISSLASH(path[0]) || !ISSLASH(path[1])) + /* minimum UNCRoot is \\x\y */ + return FALSE; + for (i = 2; i < pathlen ; i++) + if (ISSLASH(path[i])) break; + if (i == 2 || i == pathlen) + /* do not allow \\\SHARE or \\SERVER */ + return FALSE; + share = i+1; + for (i = share; i < pathlen; i++) + if (ISSLASH(path[i])) break; + return (i != share && (i == pathlen || i == pathlen-1)); - #undef ISSLASH + #undef ISSLASH } #endif /* MS_WINDOWS */ static PyObject * posix_do_stat(PyObject *self, PyObject *args, - char *format, + char *format, #ifdef __VMS - int (*statfunc)(const char *, STRUCT_STAT *, ...), + int (*statfunc)(const char *, STRUCT_STAT *, ...), #else - int (*statfunc)(const char *, STRUCT_STAT *), + int (*statfunc)(const char *, STRUCT_STAT *), #endif - char *wformat, - int (*wstatfunc)(const Py_UNICODE *, STRUCT_STAT *)) + char *wformat, + int (*wstatfunc)(const Py_UNICODE *, STRUCT_STAT *)) { - STRUCT_STAT st; - PyObject *opath; - char *path; - int res; - PyObject *result; + STRUCT_STAT st; + PyObject *opath; + char *path; + int res; + PyObject *result; #ifdef MS_WINDOWS - /* If on wide-character-capable OS see if argument - is Unicode and if so use wide API. */ - if (unicode_file_names()) { - PyUnicodeObject *po; - if (PyArg_ParseTuple(args, wformat, &po)) { - Py_UNICODE *wpath = PyUnicode_AS_UNICODE(po); - - Py_BEGIN_ALLOW_THREADS - /* PyUnicode_AS_UNICODE result OK without - thread lock as it is a simple dereference. */ - res = wstatfunc(wpath, &st); - Py_END_ALLOW_THREADS - - if (res != 0) - return win32_error_unicode("stat", wpath); - return _pystat_fromstructstat(&st); - } - /* Drop the argument parsing error as narrow strings - are also valid. */ - PyErr_Clear(); - } -#endif - - if (!PyArg_ParseTuple(args, format, - PyUnicode_FSConverter, &opath)) - return NULL; - path = bytes2str(opath, 1); - Py_BEGIN_ALLOW_THREADS - res = (*statfunc)(path, &st); - Py_END_ALLOW_THREADS + /* If on wide-character-capable OS see if argument + is Unicode and if so use wide API. */ + if (unicode_file_names()) { + PyUnicodeObject *po; + if (PyArg_ParseTuple(args, wformat, &po)) { + Py_UNICODE *wpath = PyUnicode_AS_UNICODE(po); + + Py_BEGIN_ALLOW_THREADS + /* PyUnicode_AS_UNICODE result OK without + thread lock as it is a simple dereference. */ + res = wstatfunc(wpath, &st); + Py_END_ALLOW_THREADS + + if (res != 0) + return win32_error_unicode("stat", wpath); + return _pystat_fromstructstat(&st); + } + /* Drop the argument parsing error as narrow strings + are also valid. */ + PyErr_Clear(); + } +#endif - if (res != 0) { + if (!PyArg_ParseTuple(args, format, + PyUnicode_FSConverter, &opath)) + return NULL; + path = bytes2str(opath, 1); + Py_BEGIN_ALLOW_THREADS + res = (*statfunc)(path, &st); + Py_END_ALLOW_THREADS + + if (res != 0) { #ifdef MS_WINDOWS - result = win32_error("stat", path); + result = win32_error("stat", path); #else - result = posix_error_with_filename(path); + result = posix_error_with_filename(path); #endif - } - else - result = _pystat_fromstructstat(&st); + } + else + result = _pystat_fromstructstat(&st); - release_bytes(opath); - return result; + release_bytes(opath); + return result; } /* POSIX methods */ @@ -1676,55 +1677,55 @@ static PyObject * posix_access(PyObject *self, PyObject *args) { - PyObject *opath; - char *path; - int mode; - + PyObject *opath; + char *path; + int mode; + #ifdef MS_WINDOWS - DWORD attr; - if (unicode_file_names()) { - PyUnicodeObject *po; - if (PyArg_ParseTuple(args, "Ui:access", &po, &mode)) { - Py_BEGIN_ALLOW_THREADS - /* PyUnicode_AS_UNICODE OK without thread lock as - it is a simple dereference. */ - attr = GetFileAttributesW(PyUnicode_AS_UNICODE(po)); - Py_END_ALLOW_THREADS - goto finish; - } - /* Drop the argument parsing error as narrow strings - are also valid. */ - PyErr_Clear(); - } - if (!PyArg_ParseTuple(args, "O&i:access", - PyUnicode_FSConverter, &opath, &mode)) - return 0; - path = bytes2str(opath, 1); - Py_BEGIN_ALLOW_THREADS - attr = GetFileAttributesA(path); - Py_END_ALLOW_THREADS - release_bytes(opath); + DWORD attr; + if (unicode_file_names()) { + PyUnicodeObject *po; + if (PyArg_ParseTuple(args, "Ui:access", &po, &mode)) { + Py_BEGIN_ALLOW_THREADS + /* PyUnicode_AS_UNICODE OK without thread lock as + it is a simple dereference. */ + attr = GetFileAttributesW(PyUnicode_AS_UNICODE(po)); + Py_END_ALLOW_THREADS + goto finish; + } + /* Drop the argument parsing error as narrow strings + are also valid. */ + PyErr_Clear(); + } + if (!PyArg_ParseTuple(args, "O&i:access", + PyUnicode_FSConverter, &opath, &mode)) + return 0; + path = bytes2str(opath, 1); + Py_BEGIN_ALLOW_THREADS + attr = GetFileAttributesA(path); + Py_END_ALLOW_THREADS + release_bytes(opath); finish: - if (attr == 0xFFFFFFFF) - /* File does not exist, or cannot read attributes */ - return PyBool_FromLong(0); - /* Access is possible if either write access wasn't requested, or - the file isn't read-only, or if it's a directory, as there are - no read-only directories on Windows. */ - return PyBool_FromLong(!(mode & 2) - || !(attr & FILE_ATTRIBUTE_READONLY) - || (attr & FILE_ATTRIBUTE_DIRECTORY)); -#else - int res; - if (!PyArg_ParseTuple(args, "O&i:access", - PyUnicode_FSConverter, &opath, &mode)) - return NULL; - path = bytes2str(opath, 1); - Py_BEGIN_ALLOW_THREADS - res = access(path, mode); - Py_END_ALLOW_THREADS - release_bytes(opath); - return PyBool_FromLong(res == 0); + if (attr == 0xFFFFFFFF) + /* File does not exist, or cannot read attributes */ + return PyBool_FromLong(0); + /* Access is possible if either write access wasn't requested, or + the file isn't read-only, or if it's a directory, as there are + no read-only directories on Windows. */ + return PyBool_FromLong(!(mode & 2) + || !(attr & FILE_ATTRIBUTE_READONLY) + || (attr & FILE_ATTRIBUTE_DIRECTORY)); +#else + int res; + if (!PyArg_ParseTuple(args, "O&i:access", + PyUnicode_FSConverter, &opath, &mode)) + return NULL; + path = bytes2str(opath, 1); + Py_BEGIN_ALLOW_THREADS + res = access(path, mode); + Py_END_ALLOW_THREADS + release_bytes(opath); + return PyBool_FromLong(res == 0); #endif } @@ -1749,26 +1750,26 @@ static PyObject * posix_ttyname(PyObject *self, PyObject *args) { - int id; - char *ret; + int id; + char *ret; - if (!PyArg_ParseTuple(args, "i:ttyname", &id)) - return NULL; + if (!PyArg_ParseTuple(args, "i:ttyname", &id)) + return NULL; #if defined(__VMS) - /* file descriptor 0 only, the default input device (stdin) */ - if (id == 0) { - ret = ttyname(); - } - else { - ret = NULL; - } -#else - ret = ttyname(id); -#endif - if (ret == NULL) - return posix_error(); - return PyUnicode_FromString(ret); + /* file descriptor 0 only, the default input device (stdin) */ + if (id == 0) { + ret = ttyname(); + } + else { + ret = NULL; + } +#else + ret = ttyname(id); +#endif + if (ret == NULL) + return posix_error(); + return PyUnicode_FromString(ret); } #endif @@ -1780,17 +1781,17 @@ static PyObject * posix_ctermid(PyObject *self, PyObject *noargs) { - char *ret; - char buffer[L_ctermid]; + char *ret; + char buffer[L_ctermid]; #ifdef USE_CTERMID_R - ret = ctermid_r(buffer); + ret = ctermid_r(buffer); #else - ret = ctermid(buffer); + ret = ctermid(buffer); #endif - if (ret == NULL) - return posix_error(); - return PyUnicode_FromString(buffer); + if (ret == NULL) + return posix_error(); + return PyUnicode_FromString(buffer); } #endif @@ -1802,13 +1803,13 @@ posix_chdir(PyObject *self, PyObject *args) { #ifdef MS_WINDOWS - return win32_1str(args, "chdir", "y:chdir", win32_chdir, "U:chdir", win32_wchdir); + return win32_1str(args, "chdir", "y:chdir", win32_chdir, "U:chdir", win32_wchdir); #elif defined(PYOS_OS2) && defined(PYCC_GCC) - return posix_1str(args, "O&:chdir", _chdir2); + return posix_1str(args, "O&:chdir", _chdir2); #elif defined(__VMS) - return posix_1str(args, "O&:chdir", (int (*)(const char *))chdir); + return posix_1str(args, "O&:chdir", (int (*)(const char *))chdir); #else - return posix_1str(args, "O&:chdir", chdir); + return posix_1str(args, "O&:chdir", chdir); #endif } @@ -1821,7 +1822,7 @@ static PyObject * posix_fchdir(PyObject *self, PyObject *fdobj) { - return posix_fildes(fdobj, fchdir); + return posix_fildes(fdobj, fchdir); } #endif /* HAVE_FCHDIR */ @@ -1833,74 +1834,74 @@ static PyObject * posix_chmod(PyObject *self, PyObject *args) { - PyObject *opath = NULL; - char *path = NULL; - int i; - int res; + PyObject *opath = NULL; + char *path = NULL; + int i; + int res; #ifdef MS_WINDOWS - DWORD attr; - if (unicode_file_names()) { - PyUnicodeObject *po; - if (PyArg_ParseTuple(args, "Ui|:chmod", &po, &i)) { - Py_BEGIN_ALLOW_THREADS - attr = GetFileAttributesW(PyUnicode_AS_UNICODE(po)); - if (attr != 0xFFFFFFFF) { - if (i & _S_IWRITE) - attr &= ~FILE_ATTRIBUTE_READONLY; - else - attr |= FILE_ATTRIBUTE_READONLY; - res = SetFileAttributesW(PyUnicode_AS_UNICODE(po), attr); - } - else - res = 0; - Py_END_ALLOW_THREADS - if (!res) - return win32_error_unicode("chmod", - PyUnicode_AS_UNICODE(po)); - Py_INCREF(Py_None); - return Py_None; - } - /* Drop the argument parsing error as narrow strings - are also valid. */ - PyErr_Clear(); - } - if (!PyArg_ParseTuple(args, "O&i:chmod", PyUnicode_FSConverter, - &opath, &i)) - return NULL; - path = bytes2str(opath, 1); - Py_BEGIN_ALLOW_THREADS - attr = GetFileAttributesA(path); - if (attr != 0xFFFFFFFF) { - if (i & _S_IWRITE) - attr &= ~FILE_ATTRIBUTE_READONLY; - else - attr |= FILE_ATTRIBUTE_READONLY; - res = SetFileAttributesA(path, attr); - } - else - res = 0; - Py_END_ALLOW_THREADS - if (!res) { - win32_error("chmod", path); - release_bytes(opath); - return NULL; - } - release_bytes(opath); - Py_INCREF(Py_None); - return Py_None; + DWORD attr; + if (unicode_file_names()) { + PyUnicodeObject *po; + if (PyArg_ParseTuple(args, "Ui|:chmod", &po, &i)) { + Py_BEGIN_ALLOW_THREADS + attr = GetFileAttributesW(PyUnicode_AS_UNICODE(po)); + if (attr != 0xFFFFFFFF) { + if (i & _S_IWRITE) + attr &= ~FILE_ATTRIBUTE_READONLY; + else + attr |= FILE_ATTRIBUTE_READONLY; + res = SetFileAttributesW(PyUnicode_AS_UNICODE(po), attr); + } + else + res = 0; + Py_END_ALLOW_THREADS + if (!res) + return win32_error_unicode("chmod", + PyUnicode_AS_UNICODE(po)); + Py_INCREF(Py_None); + return Py_None; + } + /* Drop the argument parsing error as narrow strings + are also valid. */ + PyErr_Clear(); + } + if (!PyArg_ParseTuple(args, "O&i:chmod", PyUnicode_FSConverter, + &opath, &i)) + return NULL; + path = bytes2str(opath, 1); + Py_BEGIN_ALLOW_THREADS + attr = GetFileAttributesA(path); + if (attr != 0xFFFFFFFF) { + if (i & _S_IWRITE) + attr &= ~FILE_ATTRIBUTE_READONLY; + else + attr |= FILE_ATTRIBUTE_READONLY; + res = SetFileAttributesA(path, attr); + } + else + res = 0; + Py_END_ALLOW_THREADS + if (!res) { + win32_error("chmod", path); + release_bytes(opath); + return NULL; + } + release_bytes(opath); + Py_INCREF(Py_None); + return Py_None; #else /* MS_WINDOWS */ - if (!PyArg_ParseTuple(args, "O&i:chmod", PyUnicode_FSConverter, - &opath, &i)) - return NULL; - path = bytes2str(opath, 1); - Py_BEGIN_ALLOW_THREADS - res = chmod(path, i); - Py_END_ALLOW_THREADS - if (res < 0) - return posix_error_with_allocated_filename(opath); - release_bytes(opath); - Py_INCREF(Py_None); - return Py_None; + if (!PyArg_ParseTuple(args, "O&i:chmod", PyUnicode_FSConverter, + &opath, &i)) + return NULL; + path = bytes2str(opath, 1); + Py_BEGIN_ALLOW_THREADS + res = chmod(path, i); + Py_END_ALLOW_THREADS + if (res < 0) + return posix_error_with_allocated_filename(opath); + release_bytes(opath); + Py_INCREF(Py_None); + return Py_None; #endif } @@ -1913,15 +1914,15 @@ static PyObject * posix_fchmod(PyObject *self, PyObject *args) { - int fd, mode, res; - if (!PyArg_ParseTuple(args, "ii:fchmod", &fd, &mode)) - return NULL; - Py_BEGIN_ALLOW_THREADS - res = fchmod(fd, mode); - Py_END_ALLOW_THREADS - if (res < 0) - return posix_error(); - Py_RETURN_NONE; + int fd, mode, res; + if (!PyArg_ParseTuple(args, "ii:fchmod", &fd, &mode)) + return NULL; + Py_BEGIN_ALLOW_THREADS + res = fchmod(fd, mode); + Py_END_ALLOW_THREADS + if (res < 0) + return posix_error(); + Py_RETURN_NONE; } #endif /* HAVE_FCHMOD */ @@ -1934,21 +1935,21 @@ static PyObject * posix_lchmod(PyObject *self, PyObject *args) { - PyObject *opath; - char *path; - int i; - int res; - if (!PyArg_ParseTuple(args, "O&i:lchmod", PyUnicode_FSConverter, - &opath, &i)) - return NULL; - path = bytes2str(opath, 1); - Py_BEGIN_ALLOW_THREADS - res = lchmod(path, i); - Py_END_ALLOW_THREADS - if (res < 0) - return posix_error_with_allocated_filename(opath); - release_bytes(opath); - Py_RETURN_NONE; + PyObject *opath; + char *path; + int i; + int res; + if (!PyArg_ParseTuple(args, "O&i:lchmod", PyUnicode_FSConverter, + &opath, &i)) + return NULL; + path = bytes2str(opath, 1); + Py_BEGIN_ALLOW_THREADS + res = lchmod(path, i); + Py_END_ALLOW_THREADS + if (res < 0) + return posix_error_with_allocated_filename(opath); + release_bytes(opath); + Py_RETURN_NONE; } #endif /* HAVE_LCHMOD */ @@ -1961,22 +1962,22 @@ static PyObject * posix_chflags(PyObject *self, PyObject *args) { - PyObject *opath; - char *path; - unsigned long flags; - int res; - if (!PyArg_ParseTuple(args, "O&k:chflags", - PyUnicode_FSConverter, &opath, &flags)) - return NULL; - path = bytes2str(opath, 1); - Py_BEGIN_ALLOW_THREADS - res = chflags(path, flags); - Py_END_ALLOW_THREADS - if (res < 0) - return posix_error_with_allocated_filename(opath); - release_bytes(opath); - Py_INCREF(Py_None); - return Py_None; + PyObject *opath; + char *path; + unsigned long flags; + int res; + if (!PyArg_ParseTuple(args, "O&k:chflags", + PyUnicode_FSConverter, &opath, &flags)) + return NULL; + path = bytes2str(opath, 1); + Py_BEGIN_ALLOW_THREADS + res = chflags(path, flags); + Py_END_ALLOW_THREADS + if (res < 0) + return posix_error_with_allocated_filename(opath); + release_bytes(opath); + Py_INCREF(Py_None); + return Py_None; } #endif /* HAVE_CHFLAGS */ @@ -1989,22 +1990,22 @@ static PyObject * posix_lchflags(PyObject *self, PyObject *args) { - PyObject *opath; - char *path; - unsigned long flags; - int res; - if (!PyArg_ParseTuple(args, "O&k:lchflags", - PyUnicode_FSConverter, &opath, &flags)) - return NULL; - path = bytes2str(opath, 1); - Py_BEGIN_ALLOW_THREADS - res = lchflags(path, flags); - Py_END_ALLOW_THREADS - if (res < 0) - return posix_error_with_allocated_filename(opath); - release_bytes(opath); - Py_INCREF(Py_None); - return Py_None; + PyObject *opath; + char *path; + unsigned long flags; + int res; + if (!PyArg_ParseTuple(args, "O&k:lchflags", + PyUnicode_FSConverter, &opath, &flags)) + return NULL; + path = bytes2str(opath, 1); + Py_BEGIN_ALLOW_THREADS + res = lchflags(path, flags); + Py_END_ALLOW_THREADS + if (res < 0) + return posix_error_with_allocated_filename(opath); + release_bytes(opath); + Py_INCREF(Py_None); + return Py_None; } #endif /* HAVE_LCHFLAGS */ @@ -2016,7 +2017,7 @@ static PyObject * posix_chroot(PyObject *self, PyObject *args) { - return posix_1str(args, "O&:chroot", chroot); + return posix_1str(args, "O&:chroot", chroot); } #endif @@ -2059,23 +2060,23 @@ static PyObject * posix_chown(PyObject *self, PyObject *args) { - PyObject *opath; - char *path; - long uid, gid; - int res; - if (!PyArg_ParseTuple(args, "O&ll:chown", - PyUnicode_FSConverter, &opath, - &uid, &gid)) - return NULL; - path = bytes2str(opath, 1); - Py_BEGIN_ALLOW_THREADS - res = chown(path, (uid_t) uid, (gid_t) gid); - Py_END_ALLOW_THREADS - if (res < 0) - return posix_error_with_allocated_filename(opath); - release_bytes(opath); - Py_INCREF(Py_None); - return Py_None; + PyObject *opath; + char *path; + long uid, gid; + int res; + if (!PyArg_ParseTuple(args, "O&ll:chown", + PyUnicode_FSConverter, &opath, + &uid, &gid)) + return NULL; + path = bytes2str(opath, 1); + Py_BEGIN_ALLOW_THREADS + res = chown(path, (uid_t) uid, (gid_t) gid); + Py_END_ALLOW_THREADS + if (res < 0) + return posix_error_with_allocated_filename(opath); + release_bytes(opath); + Py_INCREF(Py_None); + return Py_None; } #endif /* HAVE_CHOWN */ @@ -2088,17 +2089,17 @@ static PyObject * posix_fchown(PyObject *self, PyObject *args) { - int fd; - long uid, gid; - int res; - if (!PyArg_ParseTuple(args, "ill:chown", &fd, &uid, &gid)) - return NULL; - Py_BEGIN_ALLOW_THREADS - res = fchown(fd, (uid_t) uid, (gid_t) gid); - Py_END_ALLOW_THREADS - if (res < 0) - return posix_error(); - Py_RETURN_NONE; + int fd; + long uid, gid; + int res; + if (!PyArg_ParseTuple(args, "ill:chown", &fd, &uid, &gid)) + return NULL; + Py_BEGIN_ALLOW_THREADS + res = fchown(fd, (uid_t) uid, (gid_t) gid); + Py_END_ALLOW_THREADS + if (res < 0) + return posix_error(); + Py_RETURN_NONE; } #endif /* HAVE_FCHOWN */ @@ -2111,23 +2112,23 @@ static PyObject * posix_lchown(PyObject *self, PyObject *args) { - PyObject *opath; - char *path; - long uid, gid; - int res; - if (!PyArg_ParseTuple(args, "O&ll:lchown", - PyUnicode_FSConverter, &opath, - &uid, &gid)) - return NULL; - path = bytes2str(opath, 1); - Py_BEGIN_ALLOW_THREADS - res = lchown(path, (uid_t) uid, (gid_t) gid); - Py_END_ALLOW_THREADS - if (res < 0) - return posix_error_with_allocated_filename(opath); - release_bytes(opath); - Py_INCREF(Py_None); - return Py_None; + PyObject *opath; + char *path; + long uid, gid; + int res; + if (!PyArg_ParseTuple(args, "O&ll:lchown", + PyUnicode_FSConverter, &opath, + &uid, &gid)) + return NULL; + path = bytes2str(opath, 1); + Py_BEGIN_ALLOW_THREADS + res = lchown(path, (uid_t) uid, (gid_t) gid); + Py_END_ALLOW_THREADS + if (res < 0) + return posix_error_with_allocated_filename(opath); + release_bytes(opath); + Py_INCREF(Py_None); + return Py_None; } #endif /* HAVE_LCHOWN */ @@ -2136,52 +2137,52 @@ static PyObject * posix_getcwd(int use_bytes) { - char buf[1026]; - char *res; + char buf[1026]; + char *res; #ifdef MS_WINDOWS - if (!use_bytes && unicode_file_names()) { - wchar_t wbuf[1026]; - wchar_t *wbuf2 = wbuf; - PyObject *resobj; - DWORD len; - Py_BEGIN_ALLOW_THREADS - len = GetCurrentDirectoryW(sizeof wbuf/ sizeof wbuf[0], wbuf); - /* If the buffer is large enough, len does not include the - terminating \0. If the buffer is too small, len includes - the space needed for the terminator. */ - if (len >= sizeof wbuf/ sizeof wbuf[0]) { - wbuf2 = malloc(len * sizeof(wchar_t)); - if (wbuf2) - len = GetCurrentDirectoryW(len, wbuf2); - } - Py_END_ALLOW_THREADS - if (!wbuf2) { - PyErr_NoMemory(); - return NULL; - } - if (!len) { - if (wbuf2 != wbuf) free(wbuf2); - return win32_error("getcwdu", NULL); - } - resobj = PyUnicode_FromWideChar(wbuf2, len); - if (wbuf2 != wbuf) free(wbuf2); - return resobj; - } + if (!use_bytes && unicode_file_names()) { + wchar_t wbuf[1026]; + wchar_t *wbuf2 = wbuf; + PyObject *resobj; + DWORD len; + Py_BEGIN_ALLOW_THREADS + len = GetCurrentDirectoryW(sizeof wbuf/ sizeof wbuf[0], wbuf); + /* If the buffer is large enough, len does not include the + terminating \0. If the buffer is too small, len includes + the space needed for the terminator. */ + if (len >= sizeof wbuf/ sizeof wbuf[0]) { + wbuf2 = malloc(len * sizeof(wchar_t)); + if (wbuf2) + len = GetCurrentDirectoryW(len, wbuf2); + } + Py_END_ALLOW_THREADS + if (!wbuf2) { + PyErr_NoMemory(); + return NULL; + } + if (!len) { + if (wbuf2 != wbuf) free(wbuf2); + return win32_error("getcwdu", NULL); + } + resobj = PyUnicode_FromWideChar(wbuf2, len); + if (wbuf2 != wbuf) free(wbuf2); + return resobj; + } #endif - Py_BEGIN_ALLOW_THREADS + Py_BEGIN_ALLOW_THREADS #if defined(PYOS_OS2) && defined(PYCC_GCC) - res = _getcwd2(buf, sizeof buf); + res = _getcwd2(buf, sizeof buf); #else - res = getcwd(buf, sizeof buf); + res = getcwd(buf, sizeof buf); #endif - Py_END_ALLOW_THREADS - if (res == NULL) - return posix_error(); - if (use_bytes) - return PyBytes_FromStringAndSize(buf, strlen(buf)); - return PyUnicode_Decode(buf, strlen(buf), Py_FileSystemDefaultEncoding,"surrogateescape"); + Py_END_ALLOW_THREADS + if (res == NULL) + return posix_error(); + if (use_bytes) + return PyBytes_FromStringAndSize(buf, strlen(buf)); + return PyUnicode_Decode(buf, strlen(buf), Py_FileSystemDefaultEncoding,"surrogateescape"); } PyDoc_STRVAR(posix_getcwd__doc__, @@ -2214,7 +2215,7 @@ static PyObject * posix_link(PyObject *self, PyObject *args) { - return posix_2str(args, "O&O&:link", link); + return posix_2str(args, "O&O&:link", link); } #endif /* HAVE_LINK */ @@ -2223,7 +2224,7 @@ "listdir(path) -> list_of_strings\n\n\ Return a list containing the names of the entries in the directory.\n\ \n\ - path: path of directory to list\n\ + path: path of directory to list\n\ \n\ The list is in arbitrary order. It does not include the special\n\ entries '.' and '..' even if they are present in the directory."); @@ -2231,167 +2232,167 @@ static PyObject * posix_listdir(PyObject *self, PyObject *args) { - /* XXX Should redo this putting the (now four) versions of opendir - in separate files instead of having them all here... */ + /* XXX Should redo this putting the (now four) versions of opendir + in separate files instead of having them all here... */ #if defined(MS_WINDOWS) && !defined(HAVE_OPENDIR) - PyObject *d, *v; - HANDLE hFindFile; - BOOL result; - WIN32_FIND_DATA FileData; - PyObject *opath; - char namebuf[MAX_PATH+5]; /* Overallocate for \\*.*\0 */ - char *bufptr = namebuf; - Py_ssize_t len = sizeof(namebuf)-5; /* only claim to have space for MAX_PATH */ - - /* If on wide-character-capable OS see if argument - is Unicode and if so use wide API. */ - if (unicode_file_names()) { - PyObject *po; - if (PyArg_ParseTuple(args, "U:listdir", &po)) { - WIN32_FIND_DATAW wFileData; - Py_UNICODE *wnamebuf; - /* Overallocate for \\*.*\0 */ - len = PyUnicode_GET_SIZE(po); - wnamebuf = malloc((len + 5) * sizeof(wchar_t)); - if (!wnamebuf) { - PyErr_NoMemory(); - return NULL; - } - wcscpy(wnamebuf, PyUnicode_AS_UNICODE(po)); - if (len > 0) { - Py_UNICODE wch = wnamebuf[len-1]; - if (wch != L'/' && wch != L'\\' && wch != L':') - wnamebuf[len++] = L'\\'; - wcscpy(wnamebuf + len, L"*.*"); - } - if ((d = PyList_New(0)) == NULL) { - free(wnamebuf); - return NULL; - } - hFindFile = FindFirstFileW(wnamebuf, &wFileData); - if (hFindFile == INVALID_HANDLE_VALUE) { - int error = GetLastError(); - if (error == ERROR_FILE_NOT_FOUND) { - free(wnamebuf); - return d; - } - Py_DECREF(d); - win32_error_unicode("FindFirstFileW", wnamebuf); - free(wnamebuf); - return NULL; - } - do { - /* Skip over . and .. */ - if (wcscmp(wFileData.cFileName, L".") != 0 && - wcscmp(wFileData.cFileName, L"..") != 0) { - v = PyUnicode_FromUnicode(wFileData.cFileName, wcslen(wFileData.cFileName)); - if (v == NULL) { - Py_DECREF(d); - d = NULL; - break; - } - if (PyList_Append(d, v) != 0) { - Py_DECREF(v); - Py_DECREF(d); - d = NULL; - break; - } - Py_DECREF(v); - } - Py_BEGIN_ALLOW_THREADS - result = FindNextFileW(hFindFile, &wFileData); - Py_END_ALLOW_THREADS - /* FindNextFile sets error to ERROR_NO_MORE_FILES if - it got to the end of the directory. */ - if (!result && GetLastError() != ERROR_NO_MORE_FILES) { - Py_DECREF(d); - win32_error_unicode("FindNextFileW", wnamebuf); - FindClose(hFindFile); - free(wnamebuf); - return NULL; - } - } while (result == TRUE); - - if (FindClose(hFindFile) == FALSE) { - Py_DECREF(d); - win32_error_unicode("FindClose", wnamebuf); - free(wnamebuf); - return NULL; - } - free(wnamebuf); - return d; - } - /* Drop the argument parsing error as narrow strings - are also valid. */ - PyErr_Clear(); - } - - if (!PyArg_ParseTuple(args, "O&:listdir", - PyUnicode_FSConverter, &opath)) - return NULL; - if (PyObject_Size(opath)+1 > MAX_PATH) { - PyErr_SetString(PyExc_ValueError, "path too long"); - Py_DECREF(opath); - return NULL; - } - strcpy(namebuf, bytes2str(opath, 0)); - len = PyObject_Size(opath); - if (len > 0) { - char ch = namebuf[len-1]; - if (ch != SEP && ch != ALTSEP && ch != ':') - namebuf[len++] = '/'; - strcpy(namebuf + len, "*.*"); - } - - if ((d = PyList_New(0)) == NULL) - return NULL; - - hFindFile = FindFirstFile(namebuf, &FileData); - if (hFindFile == INVALID_HANDLE_VALUE) { - int error = GetLastError(); - if (error == ERROR_FILE_NOT_FOUND) - return d; - Py_DECREF(d); - return win32_error("FindFirstFile", namebuf); - } - do { - /* Skip over . and .. */ - if (strcmp(FileData.cFileName, ".") != 0 && - strcmp(FileData.cFileName, "..") != 0) { - v = PyBytes_FromString(FileData.cFileName); - if (v == NULL) { - Py_DECREF(d); - d = NULL; - break; - } - if (PyList_Append(d, v) != 0) { - Py_DECREF(v); - Py_DECREF(d); - d = NULL; - break; - } - Py_DECREF(v); - } - Py_BEGIN_ALLOW_THREADS - result = FindNextFile(hFindFile, &FileData); - Py_END_ALLOW_THREADS - /* FindNextFile sets error to ERROR_NO_MORE_FILES if - it got to the end of the directory. */ - if (!result && GetLastError() != ERROR_NO_MORE_FILES) { - Py_DECREF(d); - win32_error("FindNextFile", namebuf); - FindClose(hFindFile); - return NULL; - } - } while (result == TRUE); - - if (FindClose(hFindFile) == FALSE) { - Py_DECREF(d); - return win32_error("FindClose", namebuf); - } + PyObject *d, *v; + HANDLE hFindFile; + BOOL result; + WIN32_FIND_DATA FileData; + PyObject *opath; + char namebuf[MAX_PATH+5]; /* Overallocate for \\*.*\0 */ + char *bufptr = namebuf; + Py_ssize_t len = sizeof(namebuf)-5; /* only claim to have space for MAX_PATH */ + + /* If on wide-character-capable OS see if argument + is Unicode and if so use wide API. */ + if (unicode_file_names()) { + PyObject *po; + if (PyArg_ParseTuple(args, "U:listdir", &po)) { + WIN32_FIND_DATAW wFileData; + Py_UNICODE *wnamebuf; + /* Overallocate for \\*.*\0 */ + len = PyUnicode_GET_SIZE(po); + wnamebuf = malloc((len + 5) * sizeof(wchar_t)); + if (!wnamebuf) { + PyErr_NoMemory(); + return NULL; + } + wcscpy(wnamebuf, PyUnicode_AS_UNICODE(po)); + if (len > 0) { + Py_UNICODE wch = wnamebuf[len-1]; + if (wch != L'/' && wch != L'\\' && wch != L':') + wnamebuf[len++] = L'\\'; + wcscpy(wnamebuf + len, L"*.*"); + } + if ((d = PyList_New(0)) == NULL) { + free(wnamebuf); + return NULL; + } + hFindFile = FindFirstFileW(wnamebuf, &wFileData); + if (hFindFile == INVALID_HANDLE_VALUE) { + int error = GetLastError(); + if (error == ERROR_FILE_NOT_FOUND) { + free(wnamebuf); + return d; + } + Py_DECREF(d); + win32_error_unicode("FindFirstFileW", wnamebuf); + free(wnamebuf); + return NULL; + } + do { + /* Skip over . and .. */ + if (wcscmp(wFileData.cFileName, L".") != 0 && + wcscmp(wFileData.cFileName, L"..") != 0) { + v = PyUnicode_FromUnicode(wFileData.cFileName, wcslen(wFileData.cFileName)); + if (v == NULL) { + Py_DECREF(d); + d = NULL; + break; + } + if (PyList_Append(d, v) != 0) { + Py_DECREF(v); + Py_DECREF(d); + d = NULL; + break; + } + Py_DECREF(v); + } + Py_BEGIN_ALLOW_THREADS + result = FindNextFileW(hFindFile, &wFileData); + Py_END_ALLOW_THREADS + /* FindNextFile sets error to ERROR_NO_MORE_FILES if + it got to the end of the directory. */ + if (!result && GetLastError() != ERROR_NO_MORE_FILES) { + Py_DECREF(d); + win32_error_unicode("FindNextFileW", wnamebuf); + FindClose(hFindFile); + free(wnamebuf); + return NULL; + } + } while (result == TRUE); - return d; + if (FindClose(hFindFile) == FALSE) { + Py_DECREF(d); + win32_error_unicode("FindClose", wnamebuf); + free(wnamebuf); + return NULL; + } + free(wnamebuf); + return d; + } + /* Drop the argument parsing error as narrow strings + are also valid. */ + PyErr_Clear(); + } + + if (!PyArg_ParseTuple(args, "O&:listdir", + PyUnicode_FSConverter, &opath)) + return NULL; + if (PyObject_Size(opath)+1 > MAX_PATH) { + PyErr_SetString(PyExc_ValueError, "path too long"); + Py_DECREF(opath); + return NULL; + } + strcpy(namebuf, bytes2str(opath, 0)); + len = PyObject_Size(opath); + if (len > 0) { + char ch = namebuf[len-1]; + if (ch != SEP && ch != ALTSEP && ch != ':') + namebuf[len++] = '/'; + strcpy(namebuf + len, "*.*"); + } + + if ((d = PyList_New(0)) == NULL) + return NULL; + + hFindFile = FindFirstFile(namebuf, &FileData); + if (hFindFile == INVALID_HANDLE_VALUE) { + int error = GetLastError(); + if (error == ERROR_FILE_NOT_FOUND) + return d; + Py_DECREF(d); + return win32_error("FindFirstFile", namebuf); + } + do { + /* Skip over . and .. */ + if (strcmp(FileData.cFileName, ".") != 0 && + strcmp(FileData.cFileName, "..") != 0) { + v = PyBytes_FromString(FileData.cFileName); + if (v == NULL) { + Py_DECREF(d); + d = NULL; + break; + } + if (PyList_Append(d, v) != 0) { + Py_DECREF(v); + Py_DECREF(d); + d = NULL; + break; + } + Py_DECREF(v); + } + Py_BEGIN_ALLOW_THREADS + result = FindNextFile(hFindFile, &FileData); + Py_END_ALLOW_THREADS + /* FindNextFile sets error to ERROR_NO_MORE_FILES if + it got to the end of the directory. */ + if (!result && GetLastError() != ERROR_NO_MORE_FILES) { + Py_DECREF(d); + win32_error("FindNextFile", namebuf); + FindClose(hFindFile); + return NULL; + } + } while (result == TRUE); + + if (FindClose(hFindFile) == FALSE) { + Py_DECREF(d); + return win32_error("FindClose", namebuf); + } + + return d; #elif defined(PYOS_OS2) @@ -2408,7 +2409,7 @@ FILEFINDBUF3 ep; APIRET rc; - if (!PyArg_ParseTuple(args, "O&:listdir", + if (!PyArg_ParseTuple(args, "O&:listdir", PyUnicode_FSConverter, &oname)) return NULL; name = bytes2str(oname); @@ -2473,82 +2474,82 @@ release_bytes(oname); return d; #else - PyObject *oname; - char *name; - PyObject *d, *v; - DIR *dirp; - struct dirent *ep; - int arg_is_unicode = 1; - - errno = 0; - if (!PyArg_ParseTuple(args, "U:listdir", &v)) { - arg_is_unicode = 0; - PyErr_Clear(); - } - if (!PyArg_ParseTuple(args, "O&:listdir", PyUnicode_FSConverter, &oname)) - return NULL; - name = bytes2str(oname, 1); - if ((dirp = opendir(name)) == NULL) { - return posix_error_with_allocated_filename(oname); - } - if ((d = PyList_New(0)) == NULL) { - closedir(dirp); - release_bytes(oname); - return NULL; - } - for (;;) { - errno = 0; - Py_BEGIN_ALLOW_THREADS - ep = readdir(dirp); - Py_END_ALLOW_THREADS - if (ep == NULL) { - if (errno == 0) { - break; - } else { - closedir(dirp); - Py_DECREF(d); - return posix_error_with_allocated_filename(oname); - } - } - if (ep->d_name[0] == '.' && - (NAMLEN(ep) == 1 || - (ep->d_name[1] == '.' && NAMLEN(ep) == 2))) - continue; - v = PyBytes_FromStringAndSize(ep->d_name, NAMLEN(ep)); - if (v == NULL) { - Py_DECREF(d); - d = NULL; - break; - } - if (arg_is_unicode) { - PyObject *w; - - w = PyUnicode_FromEncodedObject(v, - Py_FileSystemDefaultEncoding, - "surrogateescape"); - Py_DECREF(v); - if (w != NULL) - v = w; - else { - /* Encoding failed to decode ASCII bytes. - Raise exception. */ - Py_DECREF(d); - d = NULL; - break; - } - } - if (PyList_Append(d, v) != 0) { - Py_DECREF(v); - Py_DECREF(d); - d = NULL; - break; - } - Py_DECREF(v); - } - closedir(dirp); - release_bytes(oname); + PyObject *oname; + char *name; + PyObject *d, *v; + DIR *dirp; + struct dirent *ep; + int arg_is_unicode = 1; + + errno = 0; + if (!PyArg_ParseTuple(args, "U:listdir", &v)) { + arg_is_unicode = 0; + PyErr_Clear(); + } + if (!PyArg_ParseTuple(args, "O&:listdir", PyUnicode_FSConverter, &oname)) + return NULL; + name = bytes2str(oname, 1); + if ((dirp = opendir(name)) == NULL) { + return posix_error_with_allocated_filename(oname); + } + if ((d = PyList_New(0)) == NULL) { + closedir(dirp); + release_bytes(oname); + return NULL; + } + for (;;) { + errno = 0; + Py_BEGIN_ALLOW_THREADS + ep = readdir(dirp); + Py_END_ALLOW_THREADS + if (ep == NULL) { + if (errno == 0) { + break; + } else { + closedir(dirp); + Py_DECREF(d); + return posix_error_with_allocated_filename(oname); + } + } + if (ep->d_name[0] == '.' && + (NAMLEN(ep) == 1 || + (ep->d_name[1] == '.' && NAMLEN(ep) == 2))) + continue; + v = PyBytes_FromStringAndSize(ep->d_name, NAMLEN(ep)); + if (v == NULL) { + Py_DECREF(d); + d = NULL; + break; + } + if (arg_is_unicode) { + PyObject *w; - return d; + w = PyUnicode_FromEncodedObject(v, + Py_FileSystemDefaultEncoding, + "surrogateescape"); + Py_DECREF(v); + if (w != NULL) + v = w; + else { + /* Encoding failed to decode ASCII bytes. + Raise exception. */ + Py_DECREF(d); + d = NULL; + break; + } + } + if (PyList_Append(d, v) != 0) { + Py_DECREF(v); + Py_DECREF(d); + d = NULL; + break; + } + Py_DECREF(v); + } + closedir(dirp); + release_bytes(oname); + + return d; #endif /* which OS */ } /* end of posix_listdir */ @@ -2558,57 +2559,57 @@ static PyObject * posix__getfullpathname(PyObject *self, PyObject *args) { - PyObject *opath; - char *path; - char outbuf[MAX_PATH*2]; - char *temp; + PyObject *opath; + char *path; + char outbuf[MAX_PATH*2]; + char *temp; #ifdef MS_WINDOWS - if (unicode_file_names()) { - PyUnicodeObject *po; - if (PyArg_ParseTuple(args, "U|:_getfullpathname", &po)) { - Py_UNICODE *wpath = PyUnicode_AS_UNICODE(po); - Py_UNICODE woutbuf[MAX_PATH*2], *woutbufp = woutbuf; - Py_UNICODE *wtemp; - DWORD result; - PyObject *v; - result = GetFullPathNameW(wpath, - sizeof(woutbuf)/sizeof(woutbuf[0]), - woutbuf, &wtemp); - if (result > sizeof(woutbuf)/sizeof(woutbuf[0])) { - woutbufp = malloc(result * sizeof(Py_UNICODE)); - if (!woutbufp) - return PyErr_NoMemory(); - result = GetFullPathNameW(wpath, result, woutbufp, &wtemp); - } - if (result) - v = PyUnicode_FromUnicode(woutbufp, wcslen(woutbufp)); - else - v = win32_error_unicode("GetFullPathNameW", wpath); - if (woutbufp != woutbuf) - free(woutbufp); - return v; - } - /* Drop the argument parsing error as narrow strings - are also valid. */ - PyErr_Clear(); - } -#endif - if (!PyArg_ParseTuple (args, "O&:_getfullpathname", - PyUnicode_FSConverter, &opath)) - return NULL; - path = bytes2str(opath, 1); - if (!GetFullPathName(path, sizeof(outbuf)/sizeof(outbuf[0]), - outbuf, &temp)) { - win32_error("GetFullPathName", path); - release_bytes(opath); - return NULL; - } - release_bytes(opath); - if (PyUnicode_Check(PyTuple_GetItem(args, 0))) { - return PyUnicode_Decode(outbuf, strlen(outbuf), - Py_FileSystemDefaultEncoding, NULL); - } - return PyBytes_FromString(outbuf); + if (unicode_file_names()) { + PyUnicodeObject *po; + if (PyArg_ParseTuple(args, "U|:_getfullpathname", &po)) { + Py_UNICODE *wpath = PyUnicode_AS_UNICODE(po); + Py_UNICODE woutbuf[MAX_PATH*2], *woutbufp = woutbuf; + Py_UNICODE *wtemp; + DWORD result; + PyObject *v; + result = GetFullPathNameW(wpath, + sizeof(woutbuf)/sizeof(woutbuf[0]), + woutbuf, &wtemp); + if (result > sizeof(woutbuf)/sizeof(woutbuf[0])) { + woutbufp = malloc(result * sizeof(Py_UNICODE)); + if (!woutbufp) + return PyErr_NoMemory(); + result = GetFullPathNameW(wpath, result, woutbufp, &wtemp); + } + if (result) + v = PyUnicode_FromUnicode(woutbufp, wcslen(woutbufp)); + else + v = win32_error_unicode("GetFullPathNameW", wpath); + if (woutbufp != woutbuf) + free(woutbufp); + return v; + } + /* Drop the argument parsing error as narrow strings + are also valid. */ + PyErr_Clear(); + } +#endif + if (!PyArg_ParseTuple (args, "O&:_getfullpathname", + PyUnicode_FSConverter, &opath)) + return NULL; + path = bytes2str(opath, 1); + if (!GetFullPathName(path, sizeof(outbuf)/sizeof(outbuf[0]), + outbuf, &temp)) { + win32_error("GetFullPathName", path); + release_bytes(opath); + return NULL; + } + release_bytes(opath); + if (PyUnicode_Check(PyTuple_GetItem(args, 0))) { + return PyUnicode_Decode(outbuf, strlen(outbuf), + Py_FileSystemDefaultEncoding, NULL); + } + return PyBytes_FromString(outbuf); } /* end of posix__getfullpathname */ #endif /* MS_WINDOWS */ @@ -2619,64 +2620,64 @@ static PyObject * posix_mkdir(PyObject *self, PyObject *args) { - int res; - PyObject *opath; - char *path; - int mode = 0777; + int res; + PyObject *opath; + char *path; + int mode = 0777; #ifdef MS_WINDOWS - if (unicode_file_names()) { - PyUnicodeObject *po; - if (PyArg_ParseTuple(args, "U|i:mkdir", &po, &mode)) { - Py_BEGIN_ALLOW_THREADS - /* PyUnicode_AS_UNICODE OK without thread lock as - it is a simple dereference. */ - res = CreateDirectoryW(PyUnicode_AS_UNICODE(po), NULL); - Py_END_ALLOW_THREADS - if (!res) - return win32_error_unicode("mkdir", PyUnicode_AS_UNICODE(po)); - Py_INCREF(Py_None); - return Py_None; - } - /* Drop the argument parsing error as narrow strings - are also valid. */ - PyErr_Clear(); - } - if (!PyArg_ParseTuple(args, "O&|i:mkdir", - PyUnicode_FSConverter, &opath, &mode)) - return NULL; - path = bytes2str(opath, 1); - Py_BEGIN_ALLOW_THREADS - /* PyUnicode_AS_UNICODE OK without thread lock as - it is a simple dereference. */ - res = CreateDirectoryA(path, NULL); - Py_END_ALLOW_THREADS - if (!res) { - win32_error("mkdir", path); - release_bytes(opath); - return NULL; - } - release_bytes(opath); - Py_INCREF(Py_None); - return Py_None; -#else - - if (!PyArg_ParseTuple(args, "O&|i:mkdir", - PyUnicode_FSConverter, &opath, &mode)) - return NULL; - path = bytes2str(opath, 1); - Py_BEGIN_ALLOW_THREADS + if (unicode_file_names()) { + PyUnicodeObject *po; + if (PyArg_ParseTuple(args, "U|i:mkdir", &po, &mode)) { + Py_BEGIN_ALLOW_THREADS + /* PyUnicode_AS_UNICODE OK without thread lock as + it is a simple dereference. */ + res = CreateDirectoryW(PyUnicode_AS_UNICODE(po), NULL); + Py_END_ALLOW_THREADS + if (!res) + return win32_error_unicode("mkdir", PyUnicode_AS_UNICODE(po)); + Py_INCREF(Py_None); + return Py_None; + } + /* Drop the argument parsing error as narrow strings + are also valid. */ + PyErr_Clear(); + } + if (!PyArg_ParseTuple(args, "O&|i:mkdir", + PyUnicode_FSConverter, &opath, &mode)) + return NULL; + path = bytes2str(opath, 1); + Py_BEGIN_ALLOW_THREADS + /* PyUnicode_AS_UNICODE OK without thread lock as + it is a simple dereference. */ + res = CreateDirectoryA(path, NULL); + Py_END_ALLOW_THREADS + if (!res) { + win32_error("mkdir", path); + release_bytes(opath); + return NULL; + } + release_bytes(opath); + Py_INCREF(Py_None); + return Py_None; +#else + + if (!PyArg_ParseTuple(args, "O&|i:mkdir", + PyUnicode_FSConverter, &opath, &mode)) + return NULL; + path = bytes2str(opath, 1); + Py_BEGIN_ALLOW_THREADS #if ( defined(__WATCOMC__) || defined(PYCC_VACPP) ) && !defined(__QNX__) - res = mkdir(path); + res = mkdir(path); #else - res = mkdir(path, mode); + res = mkdir(path, mode); #endif - Py_END_ALLOW_THREADS - if (res < 0) - return posix_error_with_allocated_filename(opath); - release_bytes(opath); - Py_INCREF(Py_None); - return Py_None; + Py_END_ALLOW_THREADS + if (res < 0) + return posix_error_with_allocated_filename(opath); + release_bytes(opath); + Py_INCREF(Py_None); + return Py_None; #endif } @@ -2695,31 +2696,31 @@ static PyObject * posix_nice(PyObject *self, PyObject *args) { - int increment, value; + int increment, value; - if (!PyArg_ParseTuple(args, "i:nice", &increment)) - return NULL; + if (!PyArg_ParseTuple(args, "i:nice", &increment)) + return NULL; - /* There are two flavours of 'nice': one that returns the new - priority (as required by almost all standards out there) and the - Linux/FreeBSD/BSDI one, which returns '0' on success and advices - the use of getpriority() to get the new priority. - - If we are of the nice family that returns the new priority, we - need to clear errno before the call, and check if errno is filled - before calling posix_error() on a returnvalue of -1, because the - -1 may be the actual new priority! */ + /* There are two flavours of 'nice': one that returns the new + priority (as required by almost all standards out there) and the + Linux/FreeBSD/BSDI one, which returns '0' on success and advices + the use of getpriority() to get the new priority. + + If we are of the nice family that returns the new priority, we + need to clear errno before the call, and check if errno is filled + before calling posix_error() on a returnvalue of -1, because the + -1 may be the actual new priority! */ - errno = 0; - value = nice(increment); + errno = 0; + value = nice(increment); #if defined(HAVE_BROKEN_NICE) && defined(HAVE_GETPRIORITY) - if (value == 0) - value = getpriority(PRIO_PROCESS, 0); + if (value == 0) + value = getpriority(PRIO_PROCESS, 0); #endif - if (value == -1 && errno != 0) - /* either nice() or getpriority() returned an error */ - return posix_error(); - return PyLong_FromLong((long) value); + if (value == -1 && errno != 0) + /* either nice() or getpriority() returned an error */ + return posix_error(); + return PyLong_FromLong((long) value); } #endif /* HAVE_NICE */ @@ -2731,42 +2732,42 @@ posix_rename(PyObject *self, PyObject *args) { #ifdef MS_WINDOWS - PyObject *o1, *o2; - char *p1, *p2; - BOOL result; - if (unicode_file_names()) { - if (!PyArg_ParseTuple(args, "OO:rename", &o1, &o2)) - goto error; - if (!convert_to_unicode(&o1)) - goto error; - if (!convert_to_unicode(&o2)) { - Py_DECREF(o1); - goto error; - } - Py_BEGIN_ALLOW_THREADS - result = MoveFileW(PyUnicode_AsUnicode(o1), - PyUnicode_AsUnicode(o2)); - Py_END_ALLOW_THREADS - Py_DECREF(o1); - Py_DECREF(o2); - if (!result) - return win32_error("rename", NULL); - Py_INCREF(Py_None); - return Py_None; + PyObject *o1, *o2; + char *p1, *p2; + BOOL result; + if (unicode_file_names()) { + if (!PyArg_ParseTuple(args, "OO:rename", &o1, &o2)) + goto error; + if (!convert_to_unicode(&o1)) + goto error; + if (!convert_to_unicode(&o2)) { + Py_DECREF(o1); + goto error; + } + Py_BEGIN_ALLOW_THREADS + result = MoveFileW(PyUnicode_AsUnicode(o1), + PyUnicode_AsUnicode(o2)); + Py_END_ALLOW_THREADS + Py_DECREF(o1); + Py_DECREF(o2); + if (!result) + return win32_error("rename", NULL); + Py_INCREF(Py_None); + return Py_None; error: - PyErr_Clear(); - } - if (!PyArg_ParseTuple(args, "ss:rename", &p1, &p2)) - return NULL; - Py_BEGIN_ALLOW_THREADS - result = MoveFileA(p1, p2); - Py_END_ALLOW_THREADS - if (!result) - return win32_error("rename", NULL); - Py_INCREF(Py_None); - return Py_None; + PyErr_Clear(); + } + if (!PyArg_ParseTuple(args, "ss:rename", &p1, &p2)) + return NULL; + Py_BEGIN_ALLOW_THREADS + result = MoveFileA(p1, p2); + Py_END_ALLOW_THREADS + if (!result) + return win32_error("rename", NULL); + Py_INCREF(Py_None); + return Py_None; #else - return posix_2str(args, "O&O&:rename", rename); + return posix_2str(args, "O&O&:rename", rename); #endif } @@ -2779,9 +2780,9 @@ posix_rmdir(PyObject *self, PyObject *args) { #ifdef MS_WINDOWS - return win32_1str(args, "rmdir", "y:rmdir", RemoveDirectoryA, "U:rmdir", RemoveDirectoryW); + return win32_1str(args, "rmdir", "y:rmdir", RemoveDirectoryA, "U:rmdir", RemoveDirectoryW); #else - return posix_1str(args, "O&:rmdir", rmdir); + return posix_1str(args, "O&:rmdir", rmdir); #endif } @@ -2794,9 +2795,9 @@ posix_stat(PyObject *self, PyObject *args) { #ifdef MS_WINDOWS - return posix_do_stat(self, args, "O&:stat", STAT, "U:stat", win32_wstat); + return posix_do_stat(self, args, "O&:stat", STAT, "U:stat", win32_wstat); #else - return posix_do_stat(self, args, "O&:stat", STAT, NULL, NULL); + return posix_do_stat(self, args, "O&:stat", STAT, NULL, NULL); #endif } @@ -2809,29 +2810,29 @@ static PyObject * posix_system(PyObject *self, PyObject *args) { - long sts; + long sts; #ifdef MS_WINDOWS - wchar_t *command; - if (!PyArg_ParseTuple(args, "u:system", &command)) - return NULL; - - Py_BEGIN_ALLOW_THREADS - sts = _wsystem(command); - Py_END_ALLOW_THREADS -#else - PyObject *command_obj; - char *command; - if (!PyArg_ParseTuple(args, "O&:system", - PyUnicode_FSConverter, &command_obj)) - return NULL; - - command = bytes2str(command_obj, 1); - Py_BEGIN_ALLOW_THREADS - sts = system(command); - Py_END_ALLOW_THREADS - release_bytes(command_obj); + wchar_t *command; + if (!PyArg_ParseTuple(args, "u:system", &command)) + return NULL; + + Py_BEGIN_ALLOW_THREADS + sts = _wsystem(command); + Py_END_ALLOW_THREADS +#else + PyObject *command_obj; + char *command; + if (!PyArg_ParseTuple(args, "O&:system", + PyUnicode_FSConverter, &command_obj)) + return NULL; + + command = bytes2str(command_obj, 1); + Py_BEGIN_ALLOW_THREADS + sts = system(command); + Py_END_ALLOW_THREADS + release_bytes(command_obj); #endif - return PyLong_FromLong(sts); + return PyLong_FromLong(sts); } #endif @@ -2843,13 +2844,13 @@ static PyObject * posix_umask(PyObject *self, PyObject *args) { - int i; - if (!PyArg_ParseTuple(args, "i:umask", &i)) - return NULL; - i = (int)umask(i); - if (i < 0) - return posix_error(); - return PyLong_FromLong((long)i); + int i; + if (!PyArg_ParseTuple(args, "i:umask", &i)) + return NULL; + i = (int)umask(i); + if (i < 0) + return posix_error(); + return PyLong_FromLong((long)i); } @@ -2865,9 +2866,9 @@ posix_unlink(PyObject *self, PyObject *args) { #ifdef MS_WINDOWS - return win32_1str(args, "remove", "y:remove", DeleteFileA, "U:remove", DeleteFileW); + return win32_1str(args, "remove", "y:remove", DeleteFileA, "U:remove", DeleteFileW); #else - return posix_1str(args, "O&:remove", unlink); + return posix_1str(args, "O&:remove", unlink); #endif } @@ -2880,50 +2881,50 @@ static PyObject * posix_uname(PyObject *self, PyObject *noargs) { - struct utsname u; - int res; + struct utsname u; + int res; - Py_BEGIN_ALLOW_THREADS - res = uname(&u); - Py_END_ALLOW_THREADS - if (res < 0) - return posix_error(); - return Py_BuildValue("(sssss)", - u.sysname, - u.nodename, - u.release, - u.version, - u.machine); + Py_BEGIN_ALLOW_THREADS + res = uname(&u); + Py_END_ALLOW_THREADS + if (res < 0) + return posix_error(); + return Py_BuildValue("(sssss)", + u.sysname, + u.nodename, + u.release, + u.version, + u.machine); } #endif /* HAVE_UNAME */ static int extract_time(PyObject *t, long* sec, long* usec) { - long intval; - if (PyFloat_Check(t)) { - double tval = PyFloat_AsDouble(t); - PyObject *intobj = Py_TYPE(t)->tp_as_number->nb_int(t); - if (!intobj) - return -1; - intval = PyLong_AsLong(intobj); - Py_DECREF(intobj); - if (intval == -1 && PyErr_Occurred()) - return -1; - *sec = intval; - *usec = (long)((tval - intval) * 1e6); /* can't exceed 1000000 */ - if (*usec < 0) - /* If rounding gave us a negative number, - truncate. */ - *usec = 0; - return 0; - } - intval = PyLong_AsLong(t); - if (intval == -1 && PyErr_Occurred()) - return -1; - *sec = intval; - *usec = 0; + long intval; + if (PyFloat_Check(t)) { + double tval = PyFloat_AsDouble(t); + PyObject *intobj = Py_TYPE(t)->tp_as_number->nb_int(t); + if (!intobj) + return -1; + intval = PyLong_AsLong(intobj); + Py_DECREF(intobj); + if (intval == -1 && PyErr_Occurred()) + return -1; + *sec = intval; + *usec = (long)((tval - intval) * 1e6); /* can't exceed 1000000 */ + if (*usec < 0) + /* If rounding gave us a negative number, + truncate. */ + *usec = 0; return 0; + } + intval = PyLong_AsLong(t); + if (intval == -1 && PyErr_Occurred()) + return -1; + *sec = intval; + *usec = 0; + return 0; } PyDoc_STRVAR(posix_utime__doc__, @@ -2936,158 +2937,158 @@ posix_utime(PyObject *self, PyObject *args) { #ifdef MS_WINDOWS - PyObject *arg; - PyUnicodeObject *obwpath; - wchar_t *wpath = NULL; - PyObject *oapath; - char *apath; - HANDLE hFile; - long atimesec, mtimesec, ausec, musec; - FILETIME atime, mtime; - PyObject *result = NULL; - - if (unicode_file_names()) { - if (PyArg_ParseTuple(args, "UO|:utime", &obwpath, &arg)) { - wpath = PyUnicode_AS_UNICODE(obwpath); - Py_BEGIN_ALLOW_THREADS - hFile = CreateFileW(wpath, FILE_WRITE_ATTRIBUTES, 0, - NULL, OPEN_EXISTING, - FILE_FLAG_BACKUP_SEMANTICS, NULL); - Py_END_ALLOW_THREADS - if (hFile == INVALID_HANDLE_VALUE) - return win32_error_unicode("utime", wpath); - } else - /* Drop the argument parsing error as narrow strings - are also valid. */ - PyErr_Clear(); - } - if (!wpath) { - if (!PyArg_ParseTuple(args, "O&O:utime", - PyUnicode_FSConverter, &oapath, &arg)) - return NULL; - apath = bytes2str(oapath, 1); - Py_BEGIN_ALLOW_THREADS - hFile = CreateFileA(apath, FILE_WRITE_ATTRIBUTES, 0, - NULL, OPEN_EXISTING, - FILE_FLAG_BACKUP_SEMANTICS, NULL); - Py_END_ALLOW_THREADS - if (hFile == INVALID_HANDLE_VALUE) { - win32_error("utime", apath); - release_bytes(oapath); - return NULL; - } - release_bytes(oapath); - } - - if (arg == Py_None) { - SYSTEMTIME now; - GetSystemTime(&now); - if (!SystemTimeToFileTime(&now, &mtime) || - !SystemTimeToFileTime(&now, &atime)) { - win32_error("utime", NULL); - goto done; - } - } - else if (!PyTuple_Check(arg) || PyTuple_Size(arg) != 2) { - PyErr_SetString(PyExc_TypeError, - "utime() arg 2 must be a tuple (atime, mtime)"); - goto done; - } - else { - if (extract_time(PyTuple_GET_ITEM(arg, 0), - &atimesec, &ausec) == -1) - goto done; - time_t_to_FILE_TIME(atimesec, 1000*ausec, &atime); - if (extract_time(PyTuple_GET_ITEM(arg, 1), - &mtimesec, &musec) == -1) - goto done; - time_t_to_FILE_TIME(mtimesec, 1000*musec, &mtime); - } - if (!SetFileTime(hFile, NULL, &atime, &mtime)) { - /* Avoid putting the file name into the error here, - as that may confuse the user into believing that - something is wrong with the file, when it also - could be the time stamp that gives a problem. */ - win32_error("utime", NULL); - } - Py_INCREF(Py_None); - result = Py_None; + PyObject *arg; + PyUnicodeObject *obwpath; + wchar_t *wpath = NULL; + PyObject *oapath; + char *apath; + HANDLE hFile; + long atimesec, mtimesec, ausec, musec; + FILETIME atime, mtime; + PyObject *result = NULL; + + if (unicode_file_names()) { + if (PyArg_ParseTuple(args, "UO|:utime", &obwpath, &arg)) { + wpath = PyUnicode_AS_UNICODE(obwpath); + Py_BEGIN_ALLOW_THREADS + hFile = CreateFileW(wpath, FILE_WRITE_ATTRIBUTES, 0, + NULL, OPEN_EXISTING, + FILE_FLAG_BACKUP_SEMANTICS, NULL); + Py_END_ALLOW_THREADS + if (hFile == INVALID_HANDLE_VALUE) + return win32_error_unicode("utime", wpath); + } else + /* Drop the argument parsing error as narrow strings + are also valid. */ + PyErr_Clear(); + } + if (!wpath) { + if (!PyArg_ParseTuple(args, "O&O:utime", + PyUnicode_FSConverter, &oapath, &arg)) + return NULL; + apath = bytes2str(oapath, 1); + Py_BEGIN_ALLOW_THREADS + hFile = CreateFileA(apath, FILE_WRITE_ATTRIBUTES, 0, + NULL, OPEN_EXISTING, + FILE_FLAG_BACKUP_SEMANTICS, NULL); + Py_END_ALLOW_THREADS + if (hFile == INVALID_HANDLE_VALUE) { + win32_error("utime", apath); + release_bytes(oapath); + return NULL; + } + release_bytes(oapath); + } + + if (arg == Py_None) { + SYSTEMTIME now; + GetSystemTime(&now); + if (!SystemTimeToFileTime(&now, &mtime) || + !SystemTimeToFileTime(&now, &atime)) { + win32_error("utime", NULL); + goto done; + } + } + else if (!PyTuple_Check(arg) || PyTuple_Size(arg) != 2) { + PyErr_SetString(PyExc_TypeError, + "utime() arg 2 must be a tuple (atime, mtime)"); + goto done; + } + else { + if (extract_time(PyTuple_GET_ITEM(arg, 0), + &atimesec, &ausec) == -1) + goto done; + time_t_to_FILE_TIME(atimesec, 1000*ausec, &atime); + if (extract_time(PyTuple_GET_ITEM(arg, 1), + &mtimesec, &musec) == -1) + goto done; + time_t_to_FILE_TIME(mtimesec, 1000*musec, &mtime); + } + if (!SetFileTime(hFile, NULL, &atime, &mtime)) { + /* Avoid putting the file name into the error here, + as that may confuse the user into believing that + something is wrong with the file, when it also + could be the time stamp that gives a problem. */ + win32_error("utime", NULL); + } + Py_INCREF(Py_None); + result = Py_None; done: - CloseHandle(hFile); - return result; + CloseHandle(hFile); + return result; #else /* MS_WINDOWS */ - PyObject *opath; - char *path; - long atime, mtime, ausec, musec; - int res; - PyObject* arg; + PyObject *opath; + char *path; + long atime, mtime, ausec, musec; + int res; + PyObject* arg; #if defined(HAVE_UTIMES) - struct timeval buf[2]; + struct timeval buf[2]; #define ATIME buf[0].tv_sec #define MTIME buf[1].tv_sec #elif defined(HAVE_UTIME_H) /* XXX should define struct utimbuf instead, above */ - struct utimbuf buf; + struct utimbuf buf; #define ATIME buf.actime #define MTIME buf.modtime #define UTIME_ARG &buf #else /* HAVE_UTIMES */ - time_t buf[2]; + time_t buf[2]; #define ATIME buf[0] #define MTIME buf[1] #define UTIME_ARG buf #endif /* HAVE_UTIMES */ - if (!PyArg_ParseTuple(args, "O&O:utime", - PyUnicode_FSConverter, &opath, &arg)) - return NULL; - path = bytes2str(opath, 1); - if (arg == Py_None) { - /* optional time values not given */ - Py_BEGIN_ALLOW_THREADS - res = utime(path, NULL); - Py_END_ALLOW_THREADS - } - else if (!PyTuple_Check(arg) || PyTuple_Size(arg) != 2) { - PyErr_SetString(PyExc_TypeError, - "utime() arg 2 must be a tuple (atime, mtime)"); - release_bytes(opath); - return NULL; - } - else { - if (extract_time(PyTuple_GET_ITEM(arg, 0), - &atime, &ausec) == -1) { - release_bytes(opath); - return NULL; - } - if (extract_time(PyTuple_GET_ITEM(arg, 1), - &mtime, &musec) == -1) { - release_bytes(opath); - return NULL; - } - ATIME = atime; - MTIME = mtime; + if (!PyArg_ParseTuple(args, "O&O:utime", + PyUnicode_FSConverter, &opath, &arg)) + return NULL; + path = bytes2str(opath, 1); + if (arg == Py_None) { + /* optional time values not given */ + Py_BEGIN_ALLOW_THREADS + res = utime(path, NULL); + Py_END_ALLOW_THREADS + } + else if (!PyTuple_Check(arg) || PyTuple_Size(arg) != 2) { + PyErr_SetString(PyExc_TypeError, + "utime() arg 2 must be a tuple (atime, mtime)"); + release_bytes(opath); + return NULL; + } + else { + if (extract_time(PyTuple_GET_ITEM(arg, 0), + &atime, &ausec) == -1) { + release_bytes(opath); + return NULL; + } + if (extract_time(PyTuple_GET_ITEM(arg, 1), + &mtime, &musec) == -1) { + release_bytes(opath); + return NULL; + } + ATIME = atime; + MTIME = mtime; #ifdef HAVE_UTIMES - buf[0].tv_usec = ausec; - buf[1].tv_usec = musec; - Py_BEGIN_ALLOW_THREADS - res = utimes(path, buf); - Py_END_ALLOW_THREADS -#else - Py_BEGIN_ALLOW_THREADS - res = utime(path, UTIME_ARG); - Py_END_ALLOW_THREADS + buf[0].tv_usec = ausec; + buf[1].tv_usec = musec; + Py_BEGIN_ALLOW_THREADS + res = utimes(path, buf); + Py_END_ALLOW_THREADS +#else + Py_BEGIN_ALLOW_THREADS + res = utime(path, UTIME_ARG); + Py_END_ALLOW_THREADS #endif /* HAVE_UTIMES */ - } - if (res < 0) { - return posix_error_with_allocated_filename(opath); - } - release_bytes(opath); - Py_INCREF(Py_None); - return Py_None; + } + if (res < 0) { + return posix_error_with_allocated_filename(opath); + } + release_bytes(opath); + Py_INCREF(Py_None); + return Py_None; #undef UTIME_ARG #undef ATIME #undef MTIME @@ -3104,38 +3105,38 @@ static PyObject * posix__exit(PyObject *self, PyObject *args) { - int sts; - if (!PyArg_ParseTuple(args, "i:_exit", &sts)) - return NULL; - _exit(sts); - return NULL; /* Make gcc -Wall happy */ + int sts; + if (!PyArg_ParseTuple(args, "i:_exit", &sts)) + return NULL; + _exit(sts); + return NULL; /* Make gcc -Wall happy */ } #if defined(HAVE_EXECV) || defined(HAVE_SPAWNV) static void free_string_array(char **array, Py_ssize_t count) { - Py_ssize_t i; - for (i = 0; i < count; i++) - PyMem_Free(array[i]); - PyMem_DEL(array); + Py_ssize_t i; + for (i = 0; i < count; i++) + PyMem_Free(array[i]); + PyMem_DEL(array); } static int fsconvert_strdup(PyObject *o, char**out) { - PyObject *bytes; - Py_ssize_t size; - if (!PyUnicode_FSConverter(o, &bytes)) - return 0; - size = PyObject_Size(bytes); - *out = PyMem_Malloc(size+1); - if (!*out) - return 0; - /* Don't lock bytes, as we hold the GIL */ - memcpy(*out, bytes2str(bytes, 0), size+1); - Py_DECREF(bytes); - return 1; + PyObject *bytes; + Py_ssize_t size; + if (!PyUnicode_FSConverter(o, &bytes)) + return 0; + size = PyObject_Size(bytes); + *out = PyMem_Malloc(size+1); + if (!*out) + return 0; + /* Don't lock bytes, as we hold the GIL */ + memcpy(*out, bytes2str(bytes, 0), size+1); + Py_DECREF(bytes); + return 1; } #endif @@ -3145,236 +3146,236 @@ "execv(path, args)\n\n\ Execute an executable path with arguments, replacing current process.\n\ \n\ - path: path of executable file\n\ - args: tuple or list of strings"); + path: path of executable file\n\ + args: tuple or list of strings"); static PyObject * posix_execv(PyObject *self, PyObject *args) { - PyObject *opath; - char *path; - PyObject *argv; - char **argvlist; - Py_ssize_t i, argc; - PyObject *(*getitem)(PyObject *, Py_ssize_t); - - /* execv has two arguments: (path, argv), where - argv is a list or tuple of strings. */ - - if (!PyArg_ParseTuple(args, "O&O:execv", - PyUnicode_FSConverter, - &opath, &argv)) - return NULL; - path = bytes2str(opath, 1); - if (PyList_Check(argv)) { - argc = PyList_Size(argv); - getitem = PyList_GetItem; - } - else if (PyTuple_Check(argv)) { - argc = PyTuple_Size(argv); - getitem = PyTuple_GetItem; - } - else { - PyErr_SetString(PyExc_TypeError, "execv() arg 2 must be a tuple or list"); - release_bytes(opath); - return NULL; - } - if (argc < 1) { - PyErr_SetString(PyExc_ValueError, "execv() arg 2 must not be empty"); - release_bytes(opath); - return NULL; - } - - argvlist = PyMem_NEW(char *, argc+1); - if (argvlist == NULL) { - release_bytes(opath); - return PyErr_NoMemory(); - } - for (i = 0; i < argc; i++) { - if (!fsconvert_strdup((*getitem)(argv, i), - &argvlist[i])) { - free_string_array(argvlist, i); - PyErr_SetString(PyExc_TypeError, - "execv() arg 2 must contain only strings"); - release_bytes(opath); - return NULL; - - } - } - argvlist[argc] = NULL; - - execv(path, argvlist); - - /* If we get here it's definitely an error */ - - free_string_array(argvlist, argc); - release_bytes(opath); - return posix_error(); + PyObject *opath; + char *path; + PyObject *argv; + char **argvlist; + Py_ssize_t i, argc; + PyObject *(*getitem)(PyObject *, Py_ssize_t); + + /* execv has two arguments: (path, argv), where + argv is a list or tuple of strings. */ + + if (!PyArg_ParseTuple(args, "O&O:execv", + PyUnicode_FSConverter, + &opath, &argv)) + return NULL; + path = bytes2str(opath, 1); + if (PyList_Check(argv)) { + argc = PyList_Size(argv); + getitem = PyList_GetItem; + } + else if (PyTuple_Check(argv)) { + argc = PyTuple_Size(argv); + getitem = PyTuple_GetItem; + } + else { + PyErr_SetString(PyExc_TypeError, "execv() arg 2 must be a tuple or list"); + release_bytes(opath); + return NULL; + } + if (argc < 1) { + PyErr_SetString(PyExc_ValueError, "execv() arg 2 must not be empty"); + release_bytes(opath); + return NULL; + } + + argvlist = PyMem_NEW(char *, argc+1); + if (argvlist == NULL) { + release_bytes(opath); + return PyErr_NoMemory(); + } + for (i = 0; i < argc; i++) { + if (!fsconvert_strdup((*getitem)(argv, i), + &argvlist[i])) { + free_string_array(argvlist, i); + PyErr_SetString(PyExc_TypeError, + "execv() arg 2 must contain only strings"); + release_bytes(opath); + return NULL; + + } + } + argvlist[argc] = NULL; + + execv(path, argvlist); + + /* If we get here it's definitely an error */ + + free_string_array(argvlist, argc); + release_bytes(opath); + return posix_error(); } static char** parse_envlist(PyObject* env, Py_ssize_t *envc_ptr) { - char **envlist; - Py_ssize_t i, pos, envc; - PyObject *keys=NULL, *vals=NULL; - PyObject *key, *val, *key2, *val2; - char *p, *k, *v; - size_t len; - - i = PyMapping_Size(env); - if (i < 0) - return NULL; - envlist = PyMem_NEW(char *, i + 1); - if (envlist == NULL) { - PyErr_NoMemory(); - return NULL; - } - envc = 0; - keys = PyMapping_Keys(env); - vals = PyMapping_Values(env); - if (!keys || !vals) - goto error; - if (!PyList_Check(keys) || !PyList_Check(vals)) { - PyErr_Format(PyExc_TypeError, - "env.keys() or env.values() is not a list"); - goto error; - } - - for (pos = 0; pos < i; pos++) { - key = PyList_GetItem(keys, pos); - val = PyList_GetItem(vals, pos); - if (!key || !val) - goto error; - - if (PyUnicode_FSConverter(key, &key2) == 0) - goto error; - if (PyUnicode_FSConverter(val, &val2) == 0) { - Py_DECREF(key2); - goto error; - } + char **envlist; + Py_ssize_t i, pos, envc; + PyObject *keys=NULL, *vals=NULL; + PyObject *key, *val, *key2, *val2; + char *p, *k, *v; + size_t len; + + i = PyMapping_Size(env); + if (i < 0) + return NULL; + envlist = PyMem_NEW(char *, i + 1); + if (envlist == NULL) { + PyErr_NoMemory(); + return NULL; + } + envc = 0; + keys = PyMapping_Keys(env); + vals = PyMapping_Values(env); + if (!keys || !vals) + goto error; + if (!PyList_Check(keys) || !PyList_Check(vals)) { + PyErr_Format(PyExc_TypeError, + "env.keys() or env.values() is not a list"); + goto error; + } + + for (pos = 0; pos < i; pos++) { + key = PyList_GetItem(keys, pos); + val = PyList_GetItem(vals, pos); + if (!key || !val) + goto error; + + if (PyUnicode_FSConverter(key, &key2) == 0) + goto error; + if (PyUnicode_FSConverter(val, &val2) == 0) { + Py_DECREF(key2); + goto error; + } #if defined(PYOS_OS2) - /* Omit Pseudo-Env Vars that Would Confuse Programs if Passed On */ - if (stricmp(k, "BEGINLIBPATH") != 0 && stricmp(k, "ENDLIBPATH") != 0) { + /* Omit Pseudo-Env Vars that Would Confuse Programs if Passed On */ + if (stricmp(k, "BEGINLIBPATH") != 0 && stricmp(k, "ENDLIBPATH") != 0) { #endif - k = PyBytes_AsString(key2); - v = PyBytes_AsString(val2); - len = PyBytes_GET_SIZE(key2) + PyBytes_GET_SIZE(val2) + 2; - - p = PyMem_NEW(char, len); - if (p == NULL) { - PyErr_NoMemory(); - Py_DECREF(key2); - Py_DECREF(val2); - goto error; - } - PyOS_snprintf(p, len, "%s=%s", k, v); - envlist[envc++] = p; - Py_DECREF(key2); - Py_DECREF(val2); + k = PyBytes_AsString(key2); + v = PyBytes_AsString(val2); + len = PyBytes_GET_SIZE(key2) + PyBytes_GET_SIZE(val2) + 2; + + p = PyMem_NEW(char, len); + if (p == NULL) { + PyErr_NoMemory(); + Py_DECREF(key2); + Py_DECREF(val2); + goto error; + } + PyOS_snprintf(p, len, "%s=%s", k, v); + envlist[envc++] = p; + Py_DECREF(key2); + Py_DECREF(val2); #if defined(PYOS_OS2) - } + } #endif - } - Py_DECREF(vals); - Py_DECREF(keys); - - envlist[envc] = 0; - *envc_ptr = envc; - return envlist; + } + Py_DECREF(vals); + Py_DECREF(keys); + + envlist[envc] = 0; + *envc_ptr = envc; + return envlist; error: - Py_XDECREF(keys); - Py_XDECREF(vals); - while (--envc >= 0) - PyMem_DEL(envlist[envc]); - PyMem_DEL(envlist); - return NULL; + Py_XDECREF(keys); + Py_XDECREF(vals); + while (--envc >= 0) + PyMem_DEL(envlist[envc]); + PyMem_DEL(envlist); + return NULL; } PyDoc_STRVAR(posix_execve__doc__, "execve(path, args, env)\n\n\ Execute a path with arguments and environment, replacing current process.\n\ \n\ - path: path of executable file\n\ - args: tuple or list of arguments\n\ - env: dictionary of strings mapping to strings"); + path: path of executable file\n\ + args: tuple or list of arguments\n\ + env: dictionary of strings mapping to strings"); static PyObject * posix_execve(PyObject *self, PyObject *args) { - PyObject *opath; - char *path; - PyObject *argv, *env; - char **argvlist; - char **envlist; - Py_ssize_t i, argc, envc; - PyObject *(*getitem)(PyObject *, Py_ssize_t); - Py_ssize_t lastarg = 0; - - /* execve has three arguments: (path, argv, env), where - argv is a list or tuple of strings and env is a dictionary - like posix.environ. */ - - if (!PyArg_ParseTuple(args, "O&OO:execve", - PyUnicode_FSConverter, - &opath, &argv, &env)) - return NULL; - path = bytes2str(opath, 1); - if (PyList_Check(argv)) { - argc = PyList_Size(argv); - getitem = PyList_GetItem; - } - else if (PyTuple_Check(argv)) { - argc = PyTuple_Size(argv); - getitem = PyTuple_GetItem; - } - else { - PyErr_SetString(PyExc_TypeError, - "execve() arg 2 must be a tuple or list"); - goto fail_0; - } - if (!PyMapping_Check(env)) { - PyErr_SetString(PyExc_TypeError, - "execve() arg 3 must be a mapping object"); - goto fail_0; - } - - argvlist = PyMem_NEW(char *, argc+1); - if (argvlist == NULL) { - PyErr_NoMemory(); - goto fail_0; - } - for (i = 0; i < argc; i++) { - if (!fsconvert_strdup((*getitem)(argv, i), - &argvlist[i])) - { - lastarg = i; - goto fail_1; - } - } - lastarg = argc; - argvlist[argc] = NULL; - - envlist = parse_envlist(env, &envc); - if (envlist == NULL) - goto fail_1; - - execve(path, argvlist, envlist); - - /* If we get here it's definitely an error */ - - (void) posix_error(); - - while (--envc >= 0) - PyMem_DEL(envlist[envc]); - PyMem_DEL(envlist); + PyObject *opath; + char *path; + PyObject *argv, *env; + char **argvlist; + char **envlist; + Py_ssize_t i, argc, envc; + PyObject *(*getitem)(PyObject *, Py_ssize_t); + Py_ssize_t lastarg = 0; + + /* execve has three arguments: (path, argv, env), where + argv is a list or tuple of strings and env is a dictionary + like posix.environ. */ + + if (!PyArg_ParseTuple(args, "O&OO:execve", + PyUnicode_FSConverter, + &opath, &argv, &env)) + return NULL; + path = bytes2str(opath, 1); + if (PyList_Check(argv)) { + argc = PyList_Size(argv); + getitem = PyList_GetItem; + } + else if (PyTuple_Check(argv)) { + argc = PyTuple_Size(argv); + getitem = PyTuple_GetItem; + } + else { + PyErr_SetString(PyExc_TypeError, + "execve() arg 2 must be a tuple or list"); + goto fail_0; + } + if (!PyMapping_Check(env)) { + PyErr_SetString(PyExc_TypeError, + "execve() arg 3 must be a mapping object"); + goto fail_0; + } + + argvlist = PyMem_NEW(char *, argc+1); + if (argvlist == NULL) { + PyErr_NoMemory(); + goto fail_0; + } + for (i = 0; i < argc; i++) { + if (!fsconvert_strdup((*getitem)(argv, i), + &argvlist[i])) + { + lastarg = i; + goto fail_1; + } + } + lastarg = argc; + argvlist[argc] = NULL; + + envlist = parse_envlist(env, &envc); + if (envlist == NULL) + goto fail_1; + + execve(path, argvlist, envlist); + + /* If we get here it's definitely an error */ + + (void) posix_error(); + + while (--envc >= 0) + PyMem_DEL(envlist[envc]); + PyMem_DEL(envlist); fail_1: - free_string_array(argvlist, lastarg); + free_string_array(argvlist, lastarg); fail_0: - release_bytes(opath); - return NULL; + release_bytes(opath); + return NULL; } #endif /* HAVE_EXECV */ @@ -3384,86 +3385,86 @@ "spawnv(mode, path, args)\n\n\ Execute the program 'path' in a new process.\n\ \n\ - mode: mode of process creation\n\ - path: path of executable file\n\ - args: tuple or list of strings"); + mode: mode of process creation\n\ + path: path of executable file\n\ + args: tuple or list of strings"); static PyObject * posix_spawnv(PyObject *self, PyObject *args) { - PyObject *opath; - char *path; - PyObject *argv; - char **argvlist; - int mode, i; - Py_ssize_t argc; - Py_intptr_t spawnval; - PyObject *(*getitem)(PyObject *, Py_ssize_t); - - /* spawnv has three arguments: (mode, path, argv), where - argv is a list or tuple of strings. */ - - if (!PyArg_ParseTuple(args, "iO&O:spawnv", &mode, - PyUnicode_FSConverter, - &opath, &argv)) - return NULL; - path = bytes2str(opath, 1); - if (PyList_Check(argv)) { - argc = PyList_Size(argv); - getitem = PyList_GetItem; - } - else if (PyTuple_Check(argv)) { - argc = PyTuple_Size(argv); - getitem = PyTuple_GetItem; - } - else { - PyErr_SetString(PyExc_TypeError, - "spawnv() arg 2 must be a tuple or list"); - release_bytes(opath); - return NULL; - } - - argvlist = PyMem_NEW(char *, argc+1); - if (argvlist == NULL) { - release_bytes(opath); - return PyErr_NoMemory(); - } - for (i = 0; i < argc; i++) { - if (!fsconvert_strdup((*getitem)(argv, i), - &argvlist[i])) { - free_string_array(argvlist, i); - PyErr_SetString( - PyExc_TypeError, - "spawnv() arg 2 must contain only strings"); - release_bytes(opath); - return NULL; - } - } - argvlist[argc] = NULL; + PyObject *opath; + char *path; + PyObject *argv; + char **argvlist; + int mode, i; + Py_ssize_t argc; + Py_intptr_t spawnval; + PyObject *(*getitem)(PyObject *, Py_ssize_t); + + /* spawnv has three arguments: (mode, path, argv), where + argv is a list or tuple of strings. */ + + if (!PyArg_ParseTuple(args, "iO&O:spawnv", &mode, + PyUnicode_FSConverter, + &opath, &argv)) + return NULL; + path = bytes2str(opath, 1); + if (PyList_Check(argv)) { + argc = PyList_Size(argv); + getitem = PyList_GetItem; + } + else if (PyTuple_Check(argv)) { + argc = PyTuple_Size(argv); + getitem = PyTuple_GetItem; + } + else { + PyErr_SetString(PyExc_TypeError, + "spawnv() arg 2 must be a tuple or list"); + release_bytes(opath); + return NULL; + } + + argvlist = PyMem_NEW(char *, argc+1); + if (argvlist == NULL) { + release_bytes(opath); + return PyErr_NoMemory(); + } + for (i = 0; i < argc; i++) { + if (!fsconvert_strdup((*getitem)(argv, i), + &argvlist[i])) { + free_string_array(argvlist, i); + PyErr_SetString( + PyExc_TypeError, + "spawnv() arg 2 must contain only strings"); + release_bytes(opath); + return NULL; + } + } + argvlist[argc] = NULL; #if defined(PYOS_OS2) && defined(PYCC_GCC) - Py_BEGIN_ALLOW_THREADS - spawnval = spawnv(mode, path, argvlist); - Py_END_ALLOW_THREADS + Py_BEGIN_ALLOW_THREADS + spawnval = spawnv(mode, path, argvlist); + Py_END_ALLOW_THREADS #else - if (mode == _OLD_P_OVERLAY) - mode = _P_OVERLAY; + if (mode == _OLD_P_OVERLAY) + mode = _P_OVERLAY; - Py_BEGIN_ALLOW_THREADS - spawnval = _spawnv(mode, path, argvlist); - Py_END_ALLOW_THREADS + Py_BEGIN_ALLOW_THREADS + spawnval = _spawnv(mode, path, argvlist); + Py_END_ALLOW_THREADS #endif - free_string_array(argvlist, argc); - release_bytes(opath); + free_string_array(argvlist, argc); + release_bytes(opath); - if (spawnval == -1) - return posix_error(); - else + if (spawnval == -1) + return posix_error(); + else #if SIZEOF_LONG == SIZEOF_VOID_P - return Py_BuildValue("l", (long) spawnval); + return Py_BuildValue("l", (long) spawnval); #else - return Py_BuildValue("L", (PY_LONG_LONG) spawnval); + return Py_BuildValue("L", (PY_LONG_LONG) spawnval); #endif } @@ -3472,104 +3473,104 @@ "spawnve(mode, path, args, env)\n\n\ Execute the program 'path' in a new process.\n\ \n\ - mode: mode of process creation\n\ - path: path of executable file\n\ - args: tuple or list of arguments\n\ - env: dictionary of strings mapping to strings"); + mode: mode of process creation\n\ + path: path of executable file\n\ + args: tuple or list of arguments\n\ + env: dictionary of strings mapping to strings"); static PyObject * posix_spawnve(PyObject *self, PyObject *args) { - PyObject *opath; - char *path; - PyObject *argv, *env; - char **argvlist; - char **envlist; - PyObject *res = NULL; - int mode, envc; - Py_ssize_t argc, i; - Py_intptr_t spawnval; - PyObject *(*getitem)(PyObject *, Py_ssize_t); - Py_ssize_t lastarg = 0; - - /* spawnve has four arguments: (mode, path, argv, env), where - argv is a list or tuple of strings and env is a dictionary - like posix.environ. */ - - if (!PyArg_ParseTuple(args, "iO&OO:spawnve", &mode, - PyUnicode_FSConverter, - &opath, &argv, &env)) - return NULL; - path = bytes2str(opath, 1); - if (PyList_Check(argv)) { - argc = PyList_Size(argv); - getitem = PyList_GetItem; - } - else if (PyTuple_Check(argv)) { - argc = PyTuple_Size(argv); - getitem = PyTuple_GetItem; - } - else { - PyErr_SetString(PyExc_TypeError, - "spawnve() arg 2 must be a tuple or list"); - goto fail_0; - } - if (!PyMapping_Check(env)) { - PyErr_SetString(PyExc_TypeError, - "spawnve() arg 3 must be a mapping object"); - goto fail_0; - } - - argvlist = PyMem_NEW(char *, argc+1); - if (argvlist == NULL) { - PyErr_NoMemory(); - goto fail_0; - } - for (i = 0; i < argc; i++) { - if (!fsconvert_strdup((*getitem)(argv, i), - &argvlist[i])) - { - lastarg = i; - goto fail_1; - } - } - lastarg = argc; - argvlist[argc] = NULL; - - envlist = parse_envlist(env, &envc); - if (envlist == NULL) - goto fail_1; + PyObject *opath; + char *path; + PyObject *argv, *env; + char **argvlist; + char **envlist; + PyObject *res = NULL; + int mode, envc; + Py_ssize_t argc, i; + Py_intptr_t spawnval; + PyObject *(*getitem)(PyObject *, Py_ssize_t); + Py_ssize_t lastarg = 0; + + /* spawnve has four arguments: (mode, path, argv, env), where + argv is a list or tuple of strings and env is a dictionary + like posix.environ. */ + + if (!PyArg_ParseTuple(args, "iO&OO:spawnve", &mode, + PyUnicode_FSConverter, + &opath, &argv, &env)) + return NULL; + path = bytes2str(opath, 1); + if (PyList_Check(argv)) { + argc = PyList_Size(argv); + getitem = PyList_GetItem; + } + else if (PyTuple_Check(argv)) { + argc = PyTuple_Size(argv); + getitem = PyTuple_GetItem; + } + else { + PyErr_SetString(PyExc_TypeError, + "spawnve() arg 2 must be a tuple or list"); + goto fail_0; + } + if (!PyMapping_Check(env)) { + PyErr_SetString(PyExc_TypeError, + "spawnve() arg 3 must be a mapping object"); + goto fail_0; + } + + argvlist = PyMem_NEW(char *, argc+1); + if (argvlist == NULL) { + PyErr_NoMemory(); + goto fail_0; + } + for (i = 0; i < argc; i++) { + if (!fsconvert_strdup((*getitem)(argv, i), + &argvlist[i])) + { + lastarg = i; + goto fail_1; + } + } + lastarg = argc; + argvlist[argc] = NULL; + + envlist = parse_envlist(env, &envc); + if (envlist == NULL) + goto fail_1; #if defined(PYOS_OS2) && defined(PYCC_GCC) - Py_BEGIN_ALLOW_THREADS - spawnval = spawnve(mode, path, argvlist, envlist); - Py_END_ALLOW_THREADS + Py_BEGIN_ALLOW_THREADS + spawnval = spawnve(mode, path, argvlist, envlist); + Py_END_ALLOW_THREADS #else - if (mode == _OLD_P_OVERLAY) - mode = _P_OVERLAY; + if (mode == _OLD_P_OVERLAY) + mode = _P_OVERLAY; - Py_BEGIN_ALLOW_THREADS - spawnval = _spawnve(mode, path, argvlist, envlist); - Py_END_ALLOW_THREADS + Py_BEGIN_ALLOW_THREADS + spawnval = _spawnve(mode, path, argvlist, envlist); + Py_END_ALLOW_THREADS #endif - if (spawnval == -1) - (void) posix_error(); - else + if (spawnval == -1) + (void) posix_error(); + else #if SIZEOF_LONG == SIZEOF_VOID_P - res = Py_BuildValue("l", (long) spawnval); + res = Py_BuildValue("l", (long) spawnval); #else - res = Py_BuildValue("L", (PY_LONG_LONG) spawnval); + res = Py_BuildValue("L", (PY_LONG_LONG) spawnval); #endif - while (--envc >= 0) - PyMem_DEL(envlist[envc]); - PyMem_DEL(envlist); + while (--envc >= 0) + PyMem_DEL(envlist[envc]); + PyMem_DEL(envlist); fail_1: - free_string_array(argvlist, lastarg); + free_string_array(argvlist, lastarg); fail_0: - release_bytes(opath); - return res; + release_bytes(opath); + return res; } /* OS/2 supports spawnvp & spawnvpe natively */ @@ -3579,77 +3580,77 @@ Execute the program 'file' in a new process, using the environment\n\ search path to find the file.\n\ \n\ - mode: mode of process creation\n\ - file: executable file name\n\ - args: tuple or list of strings"); + mode: mode of process creation\n\ + file: executable file name\n\ + args: tuple or list of strings"); static PyObject * posix_spawnvp(PyObject *self, PyObject *args) { - PyObject *opath; - char *path; - PyObject *argv; - char **argvlist; - int mode, i, argc; - Py_intptr_t spawnval; - PyObject *(*getitem)(PyObject *, Py_ssize_t); - - /* spawnvp has three arguments: (mode, path, argv), where - argv is a list or tuple of strings. */ - - if (!PyArg_ParseTuple(args, "iO&O:spawnvp", &mode, - PyUnicode_FSConverter, - &opath, &argv)) - return NULL; - path = bytes2str(opath); - if (PyList_Check(argv)) { - argc = PyList_Size(argv); - getitem = PyList_GetItem; - } - else if (PyTuple_Check(argv)) { - argc = PyTuple_Size(argv); - getitem = PyTuple_GetItem; - } - else { - PyErr_SetString(PyExc_TypeError, - "spawnvp() arg 2 must be a tuple or list"); - release_bytes(opath); - return NULL; - } - - argvlist = PyMem_NEW(char *, argc+1); - if (argvlist == NULL) { - release_bytes(opath); - return PyErr_NoMemory(); - } - for (i = 0; i < argc; i++) { - if (!fsconvert_strdup((*getitem)(argv, i), - &argvlist[i])) { - free_string_array(argvlist, i); - PyErr_SetString( - PyExc_TypeError, - "spawnvp() arg 2 must contain only strings"); - release_bytes(opath); - return NULL; - } - } - argvlist[argc] = NULL; + PyObject *opath; + char *path; + PyObject *argv; + char **argvlist; + int mode, i, argc; + Py_intptr_t spawnval; + PyObject *(*getitem)(PyObject *, Py_ssize_t); + + /* spawnvp has three arguments: (mode, path, argv), where + argv is a list or tuple of strings. */ + + if (!PyArg_ParseTuple(args, "iO&O:spawnvp", &mode, + PyUnicode_FSConverter, + &opath, &argv)) + return NULL; + path = bytes2str(opath); + if (PyList_Check(argv)) { + argc = PyList_Size(argv); + getitem = PyList_GetItem; + } + else if (PyTuple_Check(argv)) { + argc = PyTuple_Size(argv); + getitem = PyTuple_GetItem; + } + else { + PyErr_SetString(PyExc_TypeError, + "spawnvp() arg 2 must be a tuple or list"); + release_bytes(opath); + return NULL; + } + + argvlist = PyMem_NEW(char *, argc+1); + if (argvlist == NULL) { + release_bytes(opath); + return PyErr_NoMemory(); + } + for (i = 0; i < argc; i++) { + if (!fsconvert_strdup((*getitem)(argv, i), + &argvlist[i])) { + free_string_array(argvlist, i); + PyErr_SetString( + PyExc_TypeError, + "spawnvp() arg 2 must contain only strings"); + release_bytes(opath); + return NULL; + } + } + argvlist[argc] = NULL; - Py_BEGIN_ALLOW_THREADS + Py_BEGIN_ALLOW_THREADS #if defined(PYCC_GCC) - spawnval = spawnvp(mode, path, argvlist); + spawnval = spawnvp(mode, path, argvlist); #else - spawnval = _spawnvp(mode, path, argvlist); + spawnval = _spawnvp(mode, path, argvlist); #endif - Py_END_ALLOW_THREADS + Py_END_ALLOW_THREADS - free_string_array(argvlist, argc); - release_bytes(opath); + free_string_array(argvlist, argc); + release_bytes(opath); - if (spawnval == -1) - return posix_error(); - else - return Py_BuildValue("l", (long) spawnval); + if (spawnval == -1) + return posix_error(); + else + return Py_BuildValue("l", (long) spawnval); } @@ -3658,94 +3659,94 @@ Execute the program 'file' in a new process, using the environment\n\ search path to find the file.\n\ \n\ - mode: mode of process creation\n\ - file: executable file name\n\ - args: tuple or list of arguments\n\ - env: dictionary of strings mapping to strings"); + mode: mode of process creation\n\ + file: executable file name\n\ + args: tuple or list of arguments\n\ + env: dictionary of strings mapping to strings"); static PyObject * posix_spawnvpe(PyObject *self, PyObject *args) { - PyObject *opath - char *path; - PyObject *argv, *env; - char **argvlist; - char **envlist; - PyObject *res=NULL; - int mode, i, argc, envc; - Py_intptr_t spawnval; - PyObject *(*getitem)(PyObject *, Py_ssize_t); - int lastarg = 0; - - /* spawnvpe has four arguments: (mode, path, argv, env), where - argv is a list or tuple of strings and env is a dictionary - like posix.environ. */ - - if (!PyArg_ParseTuple(args, "ietOO:spawnvpe", &mode, - PyUnicode_FSConverter, - &opath, &argv, &env)) - return NULL; - path = bytes2str(opath); - if (PyList_Check(argv)) { - argc = PyList_Size(argv); - getitem = PyList_GetItem; - } - else if (PyTuple_Check(argv)) { - argc = PyTuple_Size(argv); - getitem = PyTuple_GetItem; - } - else { - PyErr_SetString(PyExc_TypeError, - "spawnvpe() arg 2 must be a tuple or list"); - goto fail_0; - } - if (!PyMapping_Check(env)) { - PyErr_SetString(PyExc_TypeError, - "spawnvpe() arg 3 must be a mapping object"); - goto fail_0; - } - - argvlist = PyMem_NEW(char *, argc+1); - if (argvlist == NULL) { - PyErr_NoMemory(); - goto fail_0; - } - for (i = 0; i < argc; i++) { - if (!fsconvert_strdup((*getitem)(argv, i), - &argvlist[i])) - { - lastarg = i; - goto fail_1; - } - } - lastarg = argc; - argvlist[argc] = NULL; - - envlist = parse_envlist(env, &envc); - if (envlist == NULL) - goto fail_1; + PyObject *opath + char *path; + PyObject *argv, *env; + char **argvlist; + char **envlist; + PyObject *res=NULL; + int mode, i, argc, envc; + Py_intptr_t spawnval; + PyObject *(*getitem)(PyObject *, Py_ssize_t); + int lastarg = 0; + + /* spawnvpe has four arguments: (mode, path, argv, env), where + argv is a list or tuple of strings and env is a dictionary + like posix.environ. */ + + if (!PyArg_ParseTuple(args, "ietOO:spawnvpe", &mode, + PyUnicode_FSConverter, + &opath, &argv, &env)) + return NULL; + path = bytes2str(opath); + if (PyList_Check(argv)) { + argc = PyList_Size(argv); + getitem = PyList_GetItem; + } + else if (PyTuple_Check(argv)) { + argc = PyTuple_Size(argv); + getitem = PyTuple_GetItem; + } + else { + PyErr_SetString(PyExc_TypeError, + "spawnvpe() arg 2 must be a tuple or list"); + goto fail_0; + } + if (!PyMapping_Check(env)) { + PyErr_SetString(PyExc_TypeError, + "spawnvpe() arg 3 must be a mapping object"); + goto fail_0; + } - Py_BEGIN_ALLOW_THREADS + argvlist = PyMem_NEW(char *, argc+1); + if (argvlist == NULL) { + PyErr_NoMemory(); + goto fail_0; + } + for (i = 0; i < argc; i++) { + if (!fsconvert_strdup((*getitem)(argv, i), + &argvlist[i])) + { + lastarg = i; + goto fail_1; + } + } + lastarg = argc; + argvlist[argc] = NULL; + + envlist = parse_envlist(env, &envc); + if (envlist == NULL) + goto fail_1; + + Py_BEGIN_ALLOW_THREADS #if defined(PYCC_GCC) - spawnval = spawnvpe(mode, path, argvlist, envlist); + spawnval = spawnvpe(mode, path, argvlist, envlist); #else - spawnval = _spawnvpe(mode, path, argvlist, envlist); + spawnval = _spawnvpe(mode, path, argvlist, envlist); #endif - Py_END_ALLOW_THREADS + Py_END_ALLOW_THREADS - if (spawnval == -1) - (void) posix_error(); - else - res = Py_BuildValue("l", (long) spawnval); + if (spawnval == -1) + (void) posix_error(); + else + res = Py_BuildValue("l", (long) spawnval); - while (--envc >= 0) - PyMem_DEL(envlist[envc]); - PyMem_DEL(envlist); + while (--envc >= 0) + PyMem_DEL(envlist[envc]); + PyMem_DEL(envlist); fail_1: - free_string_array(argvlist, lastarg); + free_string_array(argvlist, lastarg); fail_0: - release_bytes(opath); - return res; + release_bytes(opath); + return res; } #endif /* PYOS_OS2 */ #endif /* HAVE_SPAWNV */ @@ -3761,22 +3762,22 @@ static PyObject * posix_fork1(PyObject *self, PyObject *noargs) { - pid_t pid; - int result; - _PyImport_AcquireLock(); - pid = fork1(); - result = _PyImport_ReleaseLock(); - if (pid == -1) - return posix_error(); - if (pid == 0) - PyOS_AfterFork(); - if (result < 0) { - /* Don't clobber the OSError if the fork failed. */ - PyErr_SetString(PyExc_RuntimeError, - "not holding the import lock"); - return NULL; - } - return PyLong_FromPid(pid); + pid_t pid; + int result; + _PyImport_AcquireLock(); + pid = fork1(); + result = _PyImport_ReleaseLock(); + if (pid == -1) + return posix_error(); + if (pid == 0) + PyOS_AfterFork(); + if (result < 0) { + /* Don't clobber the OSError if the fork failed. */ + PyErr_SetString(PyExc_RuntimeError, + "not holding the import lock"); + return NULL; + } + return PyLong_FromPid(pid); } #endif @@ -3790,22 +3791,22 @@ static PyObject * posix_fork(PyObject *self, PyObject *noargs) { - pid_t pid; - int result; - _PyImport_AcquireLock(); - pid = fork(); - result = _PyImport_ReleaseLock(); - if (pid == -1) - return posix_error(); - if (pid == 0) - PyOS_AfterFork(); - if (result < 0) { - /* Don't clobber the OSError if the fork failed. */ - PyErr_SetString(PyExc_RuntimeError, - "not holding the import lock"); - return NULL; - } - return PyLong_FromPid(pid); + pid_t pid; + int result; + _PyImport_AcquireLock(); + pid = fork(); + result = _PyImport_ReleaseLock(); + if (pid == -1) + return posix_error(); + if (pid == 0) + PyOS_AfterFork(); + if (result < 0) { + /* Don't clobber the OSError if the fork failed. */ + PyErr_SetString(PyExc_RuntimeError, + "not holding the import lock"); + return NULL; + } + return PyLong_FromPid(pid); } #endif @@ -3839,60 +3840,60 @@ static PyObject * posix_openpty(PyObject *self, PyObject *noargs) { - int master_fd, slave_fd; + int master_fd, slave_fd; #ifndef HAVE_OPENPTY - char * slave_name; + char * slave_name; #endif #if defined(HAVE_DEV_PTMX) && !defined(HAVE_OPENPTY) && !defined(HAVE__GETPTY) - PyOS_sighandler_t sig_saved; + PyOS_sighandler_t sig_saved; #ifdef sun - extern char *ptsname(int fildes); + extern char *ptsname(int fildes); #endif #endif #ifdef HAVE_OPENPTY - if (openpty(&master_fd, &slave_fd, NULL, NULL, NULL) != 0) - return posix_error(); + if (openpty(&master_fd, &slave_fd, NULL, NULL, NULL) != 0) + return posix_error(); #elif defined(HAVE__GETPTY) - slave_name = _getpty(&master_fd, O_RDWR, 0666, 0); - if (slave_name == NULL) - return posix_error(); - - slave_fd = open(slave_name, O_RDWR); - if (slave_fd < 0) - return posix_error(); -#else - master_fd = open(DEV_PTY_FILE, O_RDWR | O_NOCTTY); /* open master */ - if (master_fd < 0) - return posix_error(); - sig_saved = PyOS_setsig(SIGCHLD, SIG_DFL); - /* change permission of slave */ - if (grantpt(master_fd) < 0) { - PyOS_setsig(SIGCHLD, sig_saved); - return posix_error(); - } - /* unlock slave */ - if (unlockpt(master_fd) < 0) { - PyOS_setsig(SIGCHLD, sig_saved); - return posix_error(); - } - PyOS_setsig(SIGCHLD, sig_saved); - slave_name = ptsname(master_fd); /* get name of slave */ - if (slave_name == NULL) - return posix_error(); - slave_fd = open(slave_name, O_RDWR | O_NOCTTY); /* open slave */ - if (slave_fd < 0) - return posix_error(); + slave_name = _getpty(&master_fd, O_RDWR, 0666, 0); + if (slave_name == NULL) + return posix_error(); + + slave_fd = open(slave_name, O_RDWR); + if (slave_fd < 0) + return posix_error(); +#else + master_fd = open(DEV_PTY_FILE, O_RDWR | O_NOCTTY); /* open master */ + if (master_fd < 0) + return posix_error(); + sig_saved = PyOS_setsig(SIGCHLD, SIG_DFL); + /* change permission of slave */ + if (grantpt(master_fd) < 0) { + PyOS_setsig(SIGCHLD, sig_saved); + return posix_error(); + } + /* unlock slave */ + if (unlockpt(master_fd) < 0) { + PyOS_setsig(SIGCHLD, sig_saved); + return posix_error(); + } + PyOS_setsig(SIGCHLD, sig_saved); + slave_name = ptsname(master_fd); /* get name of slave */ + if (slave_name == NULL) + return posix_error(); + slave_fd = open(slave_name, O_RDWR | O_NOCTTY); /* open slave */ + if (slave_fd < 0) + return posix_error(); #if !defined(__CYGWIN__) && !defined(HAVE_DEV_PTC) - ioctl(slave_fd, I_PUSH, "ptem"); /* push ptem */ - ioctl(slave_fd, I_PUSH, "ldterm"); /* push ldterm */ + ioctl(slave_fd, I_PUSH, "ptem"); /* push ptem */ + ioctl(slave_fd, I_PUSH, "ldterm"); /* push ldterm */ #ifndef __hpux - ioctl(slave_fd, I_PUSH, "ttcompat"); /* push ttcompat */ + ioctl(slave_fd, I_PUSH, "ttcompat"); /* push ttcompat */ #endif /* __hpux */ #endif /* HAVE_CYGWIN */ #endif /* HAVE_OPENPTY */ - return Py_BuildValue("(ii)", master_fd, slave_fd); + return Py_BuildValue("(ii)", master_fd, slave_fd); } #endif /* defined(HAVE_OPENPTY) || defined(HAVE__GETPTY) || defined(HAVE_DEV_PTMX) */ @@ -3907,23 +3908,23 @@ static PyObject * posix_forkpty(PyObject *self, PyObject *noargs) { - int master_fd = -1, result; - pid_t pid; + int master_fd = -1, result; + pid_t pid; - _PyImport_AcquireLock(); - pid = forkpty(&master_fd, NULL, NULL, NULL); - result = _PyImport_ReleaseLock(); - if (pid == -1) - return posix_error(); - if (pid == 0) - PyOS_AfterFork(); - if (result < 0) { - /* Don't clobber the OSError if the fork failed. */ - PyErr_SetString(PyExc_RuntimeError, - "not holding the import lock"); - return NULL; - } - return Py_BuildValue("(Ni)", PyLong_FromPid(pid), master_fd); + _PyImport_AcquireLock(); + pid = forkpty(&master_fd, NULL, NULL, NULL); + result = _PyImport_ReleaseLock(); + if (pid == -1) + return posix_error(); + if (pid == 0) + PyOS_AfterFork(); + if (result < 0) { + /* Don't clobber the OSError if the fork failed. */ + PyErr_SetString(PyExc_RuntimeError, + "not holding the import lock"); + return NULL; + } + return Py_BuildValue("(Ni)", PyLong_FromPid(pid), master_fd); } #endif @@ -3935,7 +3936,7 @@ static PyObject * posix_getegid(PyObject *self, PyObject *noargs) { - return PyLong_FromLong((long)getegid()); + return PyLong_FromLong((long)getegid()); } #endif @@ -3948,7 +3949,7 @@ static PyObject * posix_geteuid(PyObject *self, PyObject *noargs) { - return PyLong_FromLong((long)geteuid()); + return PyLong_FromLong((long)geteuid()); } #endif @@ -3961,7 +3962,7 @@ static PyObject * posix_getgid(PyObject *self, PyObject *noargs) { - return PyLong_FromLong((long)getgid()); + return PyLong_FromLong((long)getgid()); } #endif @@ -3973,7 +3974,7 @@ static PyObject * posix_getpid(PyObject *self, PyObject *noargs) { - return PyLong_FromPid(getpid()); + return PyLong_FromPid(getpid()); } @@ -3990,30 +3991,30 @@ #ifdef NGROUPS_MAX #define MAX_GROUPS NGROUPS_MAX #else - /* defined to be 16 on Solaris7, so this should be a small number */ + /* defined to be 16 on Solaris7, so this should be a small number */ #define MAX_GROUPS 64 #endif - gid_t grouplist[MAX_GROUPS]; - int n; + gid_t grouplist[MAX_GROUPS]; + int n; - n = getgroups(MAX_GROUPS, grouplist); - if (n < 0) - posix_error(); - else { - result = PyList_New(n); - if (result != NULL) { - int i; - for (i = 0; i < n; ++i) { - PyObject *o = PyLong_FromLong((long)grouplist[i]); - if (o == NULL) { - Py_DECREF(result); - result = NULL; - break; - } - PyList_SET_ITEM(result, i, o); - } + n = getgroups(MAX_GROUPS, grouplist); + if (n < 0) + posix_error(); + else { + result = PyList_New(n); + if (result != NULL) { + int i; + for (i = 0; i < n; ++i) { + PyObject *o = PyLong_FromLong((long)grouplist[i]); + if (o == NULL) { + Py_DECREF(result); + result = NULL; + break; } + PyList_SET_ITEM(result, i, o); } + } + } return result; } @@ -4027,13 +4028,13 @@ static PyObject * posix_getpgid(PyObject *self, PyObject *args) { - pid_t pid, pgid; - if (!PyArg_ParseTuple(args, PARSE_PID ":getpgid", &pid)) - return NULL; - pgid = getpgid(pid); - if (pgid < 0) - return posix_error(); - return PyLong_FromPid(pgid); + pid_t pid, pgid; + if (!PyArg_ParseTuple(args, PARSE_PID ":getpgid", &pid)) + return NULL; + pgid = getpgid(pid); + if (pgid < 0) + return posix_error(); + return PyLong_FromPid(pgid); } #endif /* HAVE_GETPGID */ @@ -4047,9 +4048,9 @@ posix_getpgrp(PyObject *self, PyObject *noargs) { #ifdef GETPGRP_HAVE_ARG - return PyLong_FromPid(getpgrp(0)); + return PyLong_FromPid(getpgrp(0)); #else /* GETPGRP_HAVE_ARG */ - return PyLong_FromPid(getpgrp()); + return PyLong_FromPid(getpgrp()); #endif /* GETPGRP_HAVE_ARG */ } #endif /* HAVE_GETPGRP */ @@ -4064,13 +4065,13 @@ posix_setpgrp(PyObject *self, PyObject *noargs) { #ifdef SETPGRP_HAVE_ARG - if (setpgrp(0, 0) < 0) + if (setpgrp(0, 0) < 0) #else /* SETPGRP_HAVE_ARG */ - if (setpgrp() < 0) + if (setpgrp() < 0) #endif /* SETPGRP_HAVE_ARG */ - return posix_error(); - Py_INCREF(Py_None); - return Py_None; + return posix_error(); + Py_INCREF(Py_None); + return Py_None; } #endif /* HAVE_SETPGRP */ @@ -4083,7 +4084,7 @@ static PyObject * posix_getppid(PyObject *self, PyObject *noargs) { - return PyLong_FromPid(getppid()); + return PyLong_FromPid(getppid()); } #endif @@ -4096,22 +4097,22 @@ static PyObject * posix_getlogin(PyObject *self, PyObject *noargs) { - PyObject *result = NULL; - char *name; - int old_errno = errno; + PyObject *result = NULL; + char *name; + int old_errno = errno; - errno = 0; - name = getlogin(); - if (name == NULL) { - if (errno) - posix_error(); - else - PyErr_SetString(PyExc_OSError, - "unable to determine login name"); - } + errno = 0; + name = getlogin(); + if (name == NULL) { + if (errno) + posix_error(); else - result = PyUnicode_FromString(name); - errno = old_errno; + PyErr_SetString(PyExc_OSError, + "unable to determine login name"); + } + else + result = PyUnicode_FromString(name); + errno = old_errno; return result; } @@ -4125,7 +4126,7 @@ static PyObject * posix_getuid(PyObject *self, PyObject *noargs) { - return PyLong_FromLong((long)getuid()); + return PyLong_FromLong((long)getuid()); } #endif @@ -4138,10 +4139,10 @@ static PyObject * posix_kill(PyObject *self, PyObject *args) { - pid_t pid; - int sig; - if (!PyArg_ParseTuple(args, PARSE_PID "i:kill", &pid, &sig)) - return NULL; + pid_t pid; + int sig; + if (!PyArg_ParseTuple(args, PARSE_PID "i:kill", &pid, &sig)) + return NULL; #if defined(PYOS_OS2) && !defined(PYCC_GCC) if (sig == XCPT_SIGNAL_INTR || sig == XCPT_SIGNAL_BREAK) { APIRET rc; @@ -4156,11 +4157,11 @@ } else return NULL; /* Unrecognized Signal Requested */ #else - if (kill(pid, sig) == -1) - return posix_error(); + if (kill(pid, sig) == -1) + return posix_error(); #endif - Py_INCREF(Py_None); - return Py_None; + Py_INCREF(Py_None); + return Py_None; } #endif @@ -4172,18 +4173,18 @@ static PyObject * posix_killpg(PyObject *self, PyObject *args) { - int sig; - pid_t pgid; - /* XXX some man pages make the `pgid` parameter an int, others - a pid_t. Since getpgrp() returns a pid_t, we assume killpg should - take the same type. Moreover, pid_t is always at least as wide as - int (else compilation of this module fails), which is safe. */ - if (!PyArg_ParseTuple(args, PARSE_PID "i:killpg", &pgid, &sig)) - return NULL; - if (killpg(pgid, sig) == -1) - return posix_error(); - Py_INCREF(Py_None); - return Py_None; + int sig; + pid_t pgid; + /* XXX some man pages make the `pgid` parameter an int, others + a pid_t. Since getpgrp() returns a pid_t, we assume killpg should + take the same type. Moreover, pid_t is always at least as wide as + int (else compilation of this module fails), which is safe. */ + if (!PyArg_ParseTuple(args, PARSE_PID "i:killpg", &pgid, &sig)) + return NULL; + if (killpg(pgid, sig) == -1) + return posix_error(); + Py_INCREF(Py_None); + return Py_None; } #endif @@ -4200,13 +4201,13 @@ static PyObject * posix_plock(PyObject *self, PyObject *args) { - int op; - if (!PyArg_ParseTuple(args, "i:plock", &op)) - return NULL; - if (plock(op) == -1) - return posix_error(); - Py_INCREF(Py_None); - return Py_None; + int op; + if (!PyArg_ParseTuple(args, "i:plock", &op)) + return NULL; + if (plock(op) == -1) + return posix_error(); + Py_INCREF(Py_None); + return Py_None; } #endif @@ -4218,19 +4219,19 @@ static PyObject * posix_setuid(PyObject *self, PyObject *args) { - long uid_arg; - uid_t uid; - if (!PyArg_ParseTuple(args, "l:setuid", &uid_arg)) - return NULL; - uid = uid_arg; - if (uid != uid_arg) { - PyErr_SetString(PyExc_OverflowError, "user id too big"); - return NULL; - } - if (setuid(uid) < 0) - return posix_error(); - Py_INCREF(Py_None); - return Py_None; + long uid_arg; + uid_t uid; + if (!PyArg_ParseTuple(args, "l:setuid", &uid_arg)) + return NULL; + uid = uid_arg; + if (uid != uid_arg) { + PyErr_SetString(PyExc_OverflowError, "user id too big"); + return NULL; + } + if (setuid(uid) < 0) + return posix_error(); + Py_INCREF(Py_None); + return Py_None; } #endif /* HAVE_SETUID */ @@ -4243,21 +4244,21 @@ static PyObject * posix_seteuid (PyObject *self, PyObject *args) { - long euid_arg; - uid_t euid; - if (!PyArg_ParseTuple(args, "l", &euid_arg)) - return NULL; - euid = euid_arg; - if (euid != euid_arg) { - PyErr_SetString(PyExc_OverflowError, "user id too big"); - return NULL; - } - if (seteuid(euid) < 0) { - return posix_error(); - } else { - Py_INCREF(Py_None); - return Py_None; - } + long euid_arg; + uid_t euid; + if (!PyArg_ParseTuple(args, "l", &euid_arg)) + return NULL; + euid = euid_arg; + if (euid != euid_arg) { + PyErr_SetString(PyExc_OverflowError, "user id too big"); + return NULL; + } + if (seteuid(euid) < 0) { + return posix_error(); + } else { + Py_INCREF(Py_None); + return Py_None; + } } #endif /* HAVE_SETEUID */ @@ -4269,21 +4270,21 @@ static PyObject * posix_setegid (PyObject *self, PyObject *args) { - long egid_arg; - gid_t egid; - if (!PyArg_ParseTuple(args, "l", &egid_arg)) - return NULL; - egid = egid_arg; - if (egid != egid_arg) { - PyErr_SetString(PyExc_OverflowError, "group id too big"); - return NULL; - } - if (setegid(egid) < 0) { - return posix_error(); - } else { - Py_INCREF(Py_None); - return Py_None; - } + long egid_arg; + gid_t egid; + if (!PyArg_ParseTuple(args, "l", &egid_arg)) + return NULL; + egid = egid_arg; + if (egid != egid_arg) { + PyErr_SetString(PyExc_OverflowError, "group id too big"); + return NULL; + } + if (setegid(egid) < 0) { + return posix_error(); + } else { + Py_INCREF(Py_None); + return Py_None; + } } #endif /* HAVE_SETEGID */ @@ -4295,29 +4296,29 @@ static PyObject * posix_setreuid (PyObject *self, PyObject *args) { - long ruid_arg, euid_arg; - uid_t ruid, euid; - if (!PyArg_ParseTuple(args, "ll", &ruid_arg, &euid_arg)) - return NULL; - if (ruid_arg == -1) - ruid = (uid_t)-1; /* let the compiler choose how -1 fits */ - else - ruid = ruid_arg; /* otherwise, assign from our long */ - if (euid_arg == -1) - euid = (uid_t)-1; - else - euid = euid_arg; - if ((euid_arg != -1 && euid != euid_arg) || - (ruid_arg != -1 && ruid != ruid_arg)) { - PyErr_SetString(PyExc_OverflowError, "user id too big"); - return NULL; - } - if (setreuid(ruid, euid) < 0) { - return posix_error(); - } else { - Py_INCREF(Py_None); - return Py_None; - } + long ruid_arg, euid_arg; + uid_t ruid, euid; + if (!PyArg_ParseTuple(args, "ll", &ruid_arg, &euid_arg)) + return NULL; + if (ruid_arg == -1) + ruid = (uid_t)-1; /* let the compiler choose how -1 fits */ + else + ruid = ruid_arg; /* otherwise, assign from our long */ + if (euid_arg == -1) + euid = (uid_t)-1; + else + euid = euid_arg; + if ((euid_arg != -1 && euid != euid_arg) || + (ruid_arg != -1 && ruid != ruid_arg)) { + PyErr_SetString(PyExc_OverflowError, "user id too big"); + return NULL; + } + if (setreuid(ruid, euid) < 0) { + return posix_error(); + } else { + Py_INCREF(Py_None); + return Py_None; + } } #endif /* HAVE_SETREUID */ @@ -4329,29 +4330,29 @@ static PyObject * posix_setregid (PyObject *self, PyObject *args) { - long rgid_arg, egid_arg; - gid_t rgid, egid; - if (!PyArg_ParseTuple(args, "ll", &rgid_arg, &egid_arg)) - return NULL; - if (rgid_arg == -1) - rgid = (gid_t)-1; /* let the compiler choose how -1 fits */ - else - rgid = rgid_arg; /* otherwise, assign from our long */ - if (egid_arg == -1) - egid = (gid_t)-1; - else - egid = egid_arg; - if ((egid_arg != -1 && egid != egid_arg) || - (rgid_arg != -1 && rgid != rgid_arg)) { - PyErr_SetString(PyExc_OverflowError, "group id too big"); - return NULL; - } - if (setregid(rgid, egid) < 0) { - return posix_error(); - } else { - Py_INCREF(Py_None); - return Py_None; - } + long rgid_arg, egid_arg; + gid_t rgid, egid; + if (!PyArg_ParseTuple(args, "ll", &rgid_arg, &egid_arg)) + return NULL; + if (rgid_arg == -1) + rgid = (gid_t)-1; /* let the compiler choose how -1 fits */ + else + rgid = rgid_arg; /* otherwise, assign from our long */ + if (egid_arg == -1) + egid = (gid_t)-1; + else + egid = egid_arg; + if ((egid_arg != -1 && egid != egid_arg) || + (rgid_arg != -1 && rgid != rgid_arg)) { + PyErr_SetString(PyExc_OverflowError, "group id too big"); + return NULL; + } + if (setregid(rgid, egid) < 0) { + return posix_error(); + } else { + Py_INCREF(Py_None); + return Py_None; + } } #endif /* HAVE_SETREGID */ @@ -4363,19 +4364,19 @@ static PyObject * posix_setgid(PyObject *self, PyObject *args) { - long gid_arg; - gid_t gid; - if (!PyArg_ParseTuple(args, "l:setgid", &gid_arg)) - return NULL; - gid = gid_arg; - if (gid != gid_arg) { - PyErr_SetString(PyExc_OverflowError, "group id too big"); - return NULL; - } - if (setgid(gid) < 0) - return posix_error(); - Py_INCREF(Py_None); - return Py_None; + long gid_arg; + gid_t gid; + if (!PyArg_ParseTuple(args, "l:setgid", &gid_arg)) + return NULL; + gid = gid_arg; + if (gid != gid_arg) { + PyErr_SetString(PyExc_OverflowError, "group id too big"); + return NULL; + } + if (setgid(gid) < 0) + return posix_error(); + Py_INCREF(Py_None); + return Py_None; } #endif /* HAVE_SETGID */ @@ -4387,52 +4388,52 @@ static PyObject * posix_setgroups(PyObject *self, PyObject *groups) { - int i, len; - gid_t grouplist[MAX_GROUPS]; + int i, len; + gid_t grouplist[MAX_GROUPS]; + + if (!PySequence_Check(groups)) { + PyErr_SetString(PyExc_TypeError, "setgroups argument must be a sequence"); + return NULL; + } + len = PySequence_Size(groups); + if (len > MAX_GROUPS) { + PyErr_SetString(PyExc_ValueError, "too many groups"); + return NULL; + } + for(i = 0; i < len; i++) { + PyObject *elem; + elem = PySequence_GetItem(groups, i); + if (!elem) + return NULL; + if (!PyLong_Check(elem)) { + PyErr_SetString(PyExc_TypeError, + "groups must be integers"); + Py_DECREF(elem); + return NULL; + } else { + unsigned long x = PyLong_AsUnsignedLong(elem); + if (PyErr_Occurred()) { + PyErr_SetString(PyExc_TypeError, + "group id too big"); + Py_DECREF(elem); + return NULL; + } + grouplist[i] = x; + /* read back the value to see if it fitted in gid_t */ + if (grouplist[i] != x) { + PyErr_SetString(PyExc_TypeError, + "group id too big"); + Py_DECREF(elem); + return NULL; + } + } + Py_DECREF(elem); + } - if (!PySequence_Check(groups)) { - PyErr_SetString(PyExc_TypeError, "setgroups argument must be a sequence"); - return NULL; - } - len = PySequence_Size(groups); - if (len > MAX_GROUPS) { - PyErr_SetString(PyExc_ValueError, "too many groups"); - return NULL; - } - for(i = 0; i < len; i++) { - PyObject *elem; - elem = PySequence_GetItem(groups, i); - if (!elem) - return NULL; - if (!PyLong_Check(elem)) { - PyErr_SetString(PyExc_TypeError, - "groups must be integers"); - Py_DECREF(elem); - return NULL; - } else { - unsigned long x = PyLong_AsUnsignedLong(elem); - if (PyErr_Occurred()) { - PyErr_SetString(PyExc_TypeError, - "group id too big"); - Py_DECREF(elem); - return NULL; - } - grouplist[i] = x; - /* read back the value to see if it fitted in gid_t */ - if (grouplist[i] != x) { - PyErr_SetString(PyExc_TypeError, - "group id too big"); - Py_DECREF(elem); - return NULL; - } - } - Py_DECREF(elem); - } - - if (setgroups(len, grouplist) < 0) - return posix_error(); - Py_INCREF(Py_None); - return Py_None; + if (setgroups(len, grouplist) < 0) + return posix_error(); + Py_INCREF(Py_None); + return Py_None; } #endif /* HAVE_SETGROUPS */ @@ -4440,59 +4441,59 @@ static PyObject * wait_helper(pid_t pid, int status, struct rusage *ru) { - PyObject *result; - static PyObject *struct_rusage; + PyObject *result; + static PyObject *struct_rusage; - if (pid == -1) - return posix_error(); + if (pid == -1) + return posix_error(); + + if (struct_rusage == NULL) { + PyObject *m = PyImport_ImportModuleNoBlock("resource"); + if (m == NULL) + return NULL; + struct_rusage = PyObject_GetAttrString(m, "struct_rusage"); + Py_DECREF(m); + if (struct_rusage == NULL) + return NULL; + } - if (struct_rusage == NULL) { - PyObject *m = PyImport_ImportModuleNoBlock("resource"); - if (m == NULL) - return NULL; - struct_rusage = PyObject_GetAttrString(m, "struct_rusage"); - Py_DECREF(m); - if (struct_rusage == NULL) - return NULL; - } - - /* XXX(nnorwitz): Copied (w/mods) from resource.c, there should be only one. */ - result = PyStructSequence_New((PyTypeObject*) struct_rusage); - if (!result) - return NULL; + /* XXX(nnorwitz): Copied (w/mods) from resource.c, there should be only one. */ + result = PyStructSequence_New((PyTypeObject*) struct_rusage); + if (!result) + return NULL; #ifndef doubletime #define doubletime(TV) ((double)(TV).tv_sec + (TV).tv_usec * 0.000001) #endif - PyStructSequence_SET_ITEM(result, 0, - PyFloat_FromDouble(doubletime(ru->ru_utime))); - PyStructSequence_SET_ITEM(result, 1, - PyFloat_FromDouble(doubletime(ru->ru_stime))); + PyStructSequence_SET_ITEM(result, 0, + PyFloat_FromDouble(doubletime(ru->ru_utime))); + PyStructSequence_SET_ITEM(result, 1, + PyFloat_FromDouble(doubletime(ru->ru_stime))); #define SET_INT(result, index, value)\ - PyStructSequence_SET_ITEM(result, index, PyLong_FromLong(value)) - SET_INT(result, 2, ru->ru_maxrss); - SET_INT(result, 3, ru->ru_ixrss); - SET_INT(result, 4, ru->ru_idrss); - SET_INT(result, 5, ru->ru_isrss); - SET_INT(result, 6, ru->ru_minflt); - SET_INT(result, 7, ru->ru_majflt); - SET_INT(result, 8, ru->ru_nswap); - SET_INT(result, 9, ru->ru_inblock); - SET_INT(result, 10, ru->ru_oublock); - SET_INT(result, 11, ru->ru_msgsnd); - SET_INT(result, 12, ru->ru_msgrcv); - SET_INT(result, 13, ru->ru_nsignals); - SET_INT(result, 14, ru->ru_nvcsw); - SET_INT(result, 15, ru->ru_nivcsw); + PyStructSequence_SET_ITEM(result, index, PyLong_FromLong(value)) + SET_INT(result, 2, ru->ru_maxrss); + SET_INT(result, 3, ru->ru_ixrss); + SET_INT(result, 4, ru->ru_idrss); + SET_INT(result, 5, ru->ru_isrss); + SET_INT(result, 6, ru->ru_minflt); + SET_INT(result, 7, ru->ru_majflt); + SET_INT(result, 8, ru->ru_nswap); + SET_INT(result, 9, ru->ru_inblock); + SET_INT(result, 10, ru->ru_oublock); + SET_INT(result, 11, ru->ru_msgsnd); + SET_INT(result, 12, ru->ru_msgrcv); + SET_INT(result, 13, ru->ru_nsignals); + SET_INT(result, 14, ru->ru_nvcsw); + SET_INT(result, 15, ru->ru_nivcsw); #undef SET_INT - if (PyErr_Occurred()) { - Py_DECREF(result); - return NULL; - } + if (PyErr_Occurred()) { + Py_DECREF(result); + return NULL; + } - return Py_BuildValue("NiN", PyLong_FromPid(pid), status, result); + return Py_BuildValue("NiN", PyLong_FromPid(pid), status, result); } #endif /* HAVE_WAIT3 || HAVE_WAIT4 */ @@ -4504,20 +4505,20 @@ static PyObject * posix_wait3(PyObject *self, PyObject *args) { - pid_t pid; - int options; - struct rusage ru; - WAIT_TYPE status; - WAIT_STATUS_INT(status) = 0; - - if (!PyArg_ParseTuple(args, "i:wait3", &options)) - return NULL; - - Py_BEGIN_ALLOW_THREADS - pid = wait3(&status, options, &ru); - Py_END_ALLOW_THREADS + pid_t pid; + int options; + struct rusage ru; + WAIT_TYPE status; + WAIT_STATUS_INT(status) = 0; + + if (!PyArg_ParseTuple(args, "i:wait3", &options)) + return NULL; + + Py_BEGIN_ALLOW_THREADS + pid = wait3(&status, options, &ru); + Py_END_ALLOW_THREADS - return wait_helper(pid, WAIT_STATUS_INT(status), &ru); + return wait_helper(pid, WAIT_STATUS_INT(status), &ru); } #endif /* HAVE_WAIT3 */ @@ -4529,20 +4530,20 @@ static PyObject * posix_wait4(PyObject *self, PyObject *args) { - pid_t pid; - int options; - struct rusage ru; - WAIT_TYPE status; - WAIT_STATUS_INT(status) = 0; - - if (!PyArg_ParseTuple(args, PARSE_PID "i:wait4", &pid, &options)) - return NULL; - - Py_BEGIN_ALLOW_THREADS - pid = wait4(pid, &status, options, &ru); - Py_END_ALLOW_THREADS + pid_t pid; + int options; + struct rusage ru; + WAIT_TYPE status; + WAIT_STATUS_INT(status) = 0; + + if (!PyArg_ParseTuple(args, PARSE_PID "i:wait4", &pid, &options)) + return NULL; + + Py_BEGIN_ALLOW_THREADS + pid = wait4(pid, &status, options, &ru); + Py_END_ALLOW_THREADS - return wait_helper(pid, WAIT_STATUS_INT(status), &ru); + return wait_helper(pid, WAIT_STATUS_INT(status), &ru); } #endif /* HAVE_WAIT4 */ @@ -4554,20 +4555,20 @@ static PyObject * posix_waitpid(PyObject *self, PyObject *args) { - pid_t pid; - int options; - WAIT_TYPE status; - WAIT_STATUS_INT(status) = 0; - - if (!PyArg_ParseTuple(args, PARSE_PID "i:waitpid", &pid, &options)) - return NULL; - Py_BEGIN_ALLOW_THREADS - pid = waitpid(pid, &status, options); - Py_END_ALLOW_THREADS - if (pid == -1) - return posix_error(); + pid_t pid; + int options; + WAIT_TYPE status; + WAIT_STATUS_INT(status) = 0; + + if (!PyArg_ParseTuple(args, PARSE_PID "i:waitpid", &pid, &options)) + return NULL; + Py_BEGIN_ALLOW_THREADS + pid = waitpid(pid, &status, options); + Py_END_ALLOW_THREADS + if (pid == -1) + return posix_error(); - return Py_BuildValue("Ni", PyLong_FromPid(pid), WAIT_STATUS_INT(status)); + return Py_BuildValue("Ni", PyLong_FromPid(pid), WAIT_STATUS_INT(status)); } #elif defined(HAVE_CWAIT) @@ -4580,19 +4581,19 @@ static PyObject * posix_waitpid(PyObject *self, PyObject *args) { - Py_intptr_t pid; - int status, options; + Py_intptr_t pid; + int status, options; - if (!PyArg_ParseTuple(args, PARSE_PID "i:waitpid", &pid, &options)) - return NULL; - Py_BEGIN_ALLOW_THREADS - pid = _cwait(&status, pid, options); - Py_END_ALLOW_THREADS - if (pid == -1) - return posix_error(); + if (!PyArg_ParseTuple(args, PARSE_PID "i:waitpid", &pid, &options)) + return NULL; + Py_BEGIN_ALLOW_THREADS + pid = _cwait(&status, pid, options); + Py_END_ALLOW_THREADS + if (pid == -1) + return posix_error(); - /* shift the status left a byte so this is more like the POSIX waitpid */ - return Py_BuildValue("Ni", PyLong_FromPid(pid), status << 8); + /* shift the status left a byte so this is more like the POSIX waitpid */ + return Py_BuildValue("Ni", PyLong_FromPid(pid), status << 8); } #endif /* HAVE_WAITPID || HAVE_CWAIT */ @@ -4604,17 +4605,17 @@ static PyObject * posix_wait(PyObject *self, PyObject *noargs) { - pid_t pid; - WAIT_TYPE status; - WAIT_STATUS_INT(status) = 0; - - Py_BEGIN_ALLOW_THREADS - pid = wait(&status); - Py_END_ALLOW_THREADS - if (pid == -1) - return posix_error(); + pid_t pid; + WAIT_TYPE status; + WAIT_STATUS_INT(status) = 0; - return Py_BuildValue("Ni", PyLong_FromPid(pid), WAIT_STATUS_INT(status)); + Py_BEGIN_ALLOW_THREADS + pid = wait(&status); + Py_END_ALLOW_THREADS + if (pid == -1) + return posix_error(); + + return Py_BuildValue("Ni", PyLong_FromPid(pid), WAIT_STATUS_INT(status)); } #endif @@ -4627,12 +4628,12 @@ posix_lstat(PyObject *self, PyObject *args) { #ifdef HAVE_LSTAT - return posix_do_stat(self, args, "O&:lstat", lstat, NULL, NULL); + return posix_do_stat(self, args, "O&:lstat", lstat, NULL, NULL); #else /* !HAVE_LSTAT */ #ifdef MS_WINDOWS - return posix_do_stat(self, args, "O&:lstat", STAT, "U:lstat", win32_wstat); + return posix_do_stat(self, args, "O&:lstat", STAT, "U:lstat", win32_wstat); #else - return posix_do_stat(self, args, "O&:lstat", STAT, NULL, NULL); + return posix_do_stat(self, args, "O&:lstat", STAT, NULL, NULL); #endif #endif /* !HAVE_LSTAT */ } @@ -4646,51 +4647,51 @@ static PyObject * posix_readlink(PyObject *self, PyObject *args) { - PyObject* v; - char buf[MAXPATHLEN]; - PyObject *opath; - char *path; - int n; - int arg_is_unicode = 0; - - if (!PyArg_ParseTuple(args, "O&:readlink", - PyUnicode_FSConverter, &opath)) - return NULL; - path = bytes2str(opath, 1); - v = PySequence_GetItem(args, 0); - if (v == NULL) { - release_bytes(opath); - return NULL; - } - - if (PyUnicode_Check(v)) { - arg_is_unicode = 1; - } - Py_DECREF(v); - - Py_BEGIN_ALLOW_THREADS - n = readlink(path, buf, (int) sizeof buf); - Py_END_ALLOW_THREADS - if (n < 0) - return posix_error_with_allocated_filename(opath); - - release_bytes(opath); - v = PyBytes_FromStringAndSize(buf, n); - if (arg_is_unicode) { - PyObject *w; - - w = PyUnicode_FromEncodedObject(v, - Py_FileSystemDefaultEncoding, - "surrogateescape"); - if (w != NULL) { - Py_DECREF(v); - v = w; - } - else { - v = NULL; - } - } - return v; + PyObject* v; + char buf[MAXPATHLEN]; + PyObject *opath; + char *path; + int n; + int arg_is_unicode = 0; + + if (!PyArg_ParseTuple(args, "O&:readlink", + PyUnicode_FSConverter, &opath)) + return NULL; + path = bytes2str(opath, 1); + v = PySequence_GetItem(args, 0); + if (v == NULL) { + release_bytes(opath); + return NULL; + } + + if (PyUnicode_Check(v)) { + arg_is_unicode = 1; + } + Py_DECREF(v); + + Py_BEGIN_ALLOW_THREADS + n = readlink(path, buf, (int) sizeof buf); + Py_END_ALLOW_THREADS + if (n < 0) + return posix_error_with_allocated_filename(opath); + + release_bytes(opath); + v = PyBytes_FromStringAndSize(buf, n); + if (arg_is_unicode) { + PyObject *w; + + w = PyUnicode_FromEncodedObject(v, + Py_FileSystemDefaultEncoding, + "surrogateescape"); + if (w != NULL) { + Py_DECREF(v); + v = w; + } + else { + v = NULL; + } + } + return v; } #endif /* HAVE_READLINK */ @@ -4703,7 +4704,7 @@ static PyObject * posix_symlink(PyObject *self, PyObject *args) { - return posix_2str(args, "O&O&:symlink", symlink); + return posix_2str(args, "O&O&:symlink", symlink); } #endif /* HAVE_SYMLINK */ @@ -4726,12 +4727,12 @@ posix_times(PyObject *self, PyObject *noargs) { /* Currently Only Uptime is Provided -- Others Later */ - return Py_BuildValue("ddddd", - (double)0 /* t.tms_utime / HZ */, - (double)0 /* t.tms_stime / HZ */, - (double)0 /* t.tms_cutime / HZ */, - (double)0 /* t.tms_cstime / HZ */, - (double)system_uptime() / 1000); + return Py_BuildValue("ddddd", + (double)0 /* t.tms_utime / HZ */, + (double)0 /* t.tms_stime / HZ */, + (double)0 /* t.tms_cutime / HZ */, + (double)0 /* t.tms_cstime / HZ */, + (double)system_uptime() / 1000); } #else /* not OS2 */ #define NEED_TICKS_PER_SECOND @@ -4739,46 +4740,46 @@ static PyObject * posix_times(PyObject *self, PyObject *noargs) { - struct tms t; - clock_t c; - errno = 0; - c = times(&t); - if (c == (clock_t) -1) - return posix_error(); - return Py_BuildValue("ddddd", - (double)t.tms_utime / ticks_per_second, - (double)t.tms_stime / ticks_per_second, - (double)t.tms_cutime / ticks_per_second, - (double)t.tms_cstime / ticks_per_second, - (double)c / ticks_per_second); + struct tms t; + clock_t c; + errno = 0; + c = times(&t); + if (c == (clock_t) -1) + return posix_error(); + return Py_BuildValue("ddddd", + (double)t.tms_utime / ticks_per_second, + (double)t.tms_stime / ticks_per_second, + (double)t.tms_cutime / ticks_per_second, + (double)t.tms_cstime / ticks_per_second, + (double)c / ticks_per_second); } #endif /* not OS2 */ #endif /* HAVE_TIMES */ #ifdef MS_WINDOWS -#define HAVE_TIMES /* so the method table will pick it up */ +#define HAVE_TIMES /* so the method table will pick it up */ static PyObject * posix_times(PyObject *self, PyObject *noargs) { - FILETIME create, exit, kernel, user; - HANDLE hProc; - hProc = GetCurrentProcess(); - GetProcessTimes(hProc, &create, &exit, &kernel, &user); - /* The fields of a FILETIME structure are the hi and lo part - of a 64-bit value expressed in 100 nanosecond units. - 1e7 is one second in such units; 1e-7 the inverse. - 429.4967296 is 2**32 / 1e7 or 2**32 * 1e-7. - */ - return Py_BuildValue( - "ddddd", - (double)(user.dwHighDateTime*429.4967296 + - user.dwLowDateTime*1e-7), - (double)(kernel.dwHighDateTime*429.4967296 + - kernel.dwLowDateTime*1e-7), - (double)0, - (double)0, - (double)0); + FILETIME create, exit, kernel, user; + HANDLE hProc; + hProc = GetCurrentProcess(); + GetProcessTimes(hProc, &create, &exit, &kernel, &user); + /* The fields of a FILETIME structure are the hi and lo part + of a 64-bit value expressed in 100 nanosecond units. + 1e7 is one second in such units; 1e-7 the inverse. + 429.4967296 is 2**32 / 1e7 or 2**32 * 1e-7. + */ + return Py_BuildValue( + "ddddd", + (double)(user.dwHighDateTime*429.4967296 + + user.dwLowDateTime*1e-7), + (double)(kernel.dwHighDateTime*429.4967296 + + kernel.dwLowDateTime*1e-7), + (double)0, + (double)0, + (double)0); } #endif /* MS_WINDOWS */ @@ -4797,14 +4798,14 @@ static PyObject * posix_getsid(PyObject *self, PyObject *args) { - pid_t pid; - int sid; - if (!PyArg_ParseTuple(args, PARSE_PID ":getsid", &pid)) - return NULL; - sid = getsid(pid); - if (sid < 0) - return posix_error(); - return PyLong_FromLong((long)sid); + pid_t pid; + int sid; + if (!PyArg_ParseTuple(args, PARSE_PID ":getsid", &pid)) + return NULL; + sid = getsid(pid); + if (sid < 0) + return posix_error(); + return PyLong_FromLong((long)sid); } #endif /* HAVE_GETSID */ @@ -4817,10 +4818,10 @@ static PyObject * posix_setsid(PyObject *self, PyObject *noargs) { - if (setsid() < 0) - return posix_error(); - Py_INCREF(Py_None); - return Py_None; + if (setsid() < 0) + return posix_error(); + Py_INCREF(Py_None); + return Py_None; } #endif /* HAVE_SETSID */ @@ -4832,14 +4833,14 @@ static PyObject * posix_setpgid(PyObject *self, PyObject *args) { - pid_t pid; - int pgrp; - if (!PyArg_ParseTuple(args, PARSE_PID "i:setpgid", &pid, &pgrp)) - return NULL; - if (setpgid(pid, pgrp) < 0) - return posix_error(); - Py_INCREF(Py_None); - return Py_None; + pid_t pid; + int pgrp; + if (!PyArg_ParseTuple(args, PARSE_PID "i:setpgid", &pid, &pgrp)) + return NULL; + if (setpgid(pid, pgrp) < 0) + return posix_error(); + Py_INCREF(Py_None); + return Py_None; } #endif /* HAVE_SETPGID */ @@ -4852,14 +4853,14 @@ static PyObject * posix_tcgetpgrp(PyObject *self, PyObject *args) { - int fd; - pid_t pgid; - if (!PyArg_ParseTuple(args, "i:tcgetpgrp", &fd)) - return NULL; - pgid = tcgetpgrp(fd); - if (pgid < 0) - return posix_error(); - return PyLong_FromPid(pgid); + int fd; + pid_t pgid; + if (!PyArg_ParseTuple(args, "i:tcgetpgrp", &fd)) + return NULL; + pgid = tcgetpgrp(fd); + if (pgid < 0) + return posix_error(); + return PyLong_FromPid(pgid); } #endif /* HAVE_TCGETPGRP */ @@ -4872,14 +4873,14 @@ static PyObject * posix_tcsetpgrp(PyObject *self, PyObject *args) { - int fd; - pid_t pgid; - if (!PyArg_ParseTuple(args, "i" PARSE_PID ":tcsetpgrp", &fd, &pgid)) - return NULL; - if (tcsetpgrp(fd, pgid) < 0) - return posix_error(); - Py_INCREF(Py_None); - return Py_None; + int fd; + pid_t pgid; + if (!PyArg_ParseTuple(args, "i" PARSE_PID ":tcsetpgrp", &fd, &pgid)) + return NULL; + if (tcsetpgrp(fd, pgid) < 0) + return posix_error(); + Py_INCREF(Py_None); + return Py_None; } #endif /* HAVE_TCSETPGRP */ @@ -4892,43 +4893,43 @@ static PyObject * posix_open(PyObject *self, PyObject *args) { - PyObject *ofile; - char *file; - int flag; - int mode = 0777; - int fd; + PyObject *ofile; + char *file; + int flag; + int mode = 0777; + int fd; #ifdef MS_WINDOWS - if (unicode_file_names()) { - PyUnicodeObject *po; - if (PyArg_ParseTuple(args, "Ui|i:mkdir", &po, &flag, &mode)) { - Py_BEGIN_ALLOW_THREADS - /* PyUnicode_AS_UNICODE OK without thread - lock as it is a simple dereference. */ - fd = _wopen(PyUnicode_AS_UNICODE(po), flag, mode); - Py_END_ALLOW_THREADS - if (fd < 0) - return posix_error(); - return PyLong_FromLong((long)fd); - } - /* Drop the argument parsing error as narrow strings - are also valid. */ - PyErr_Clear(); - } -#endif - - if (!PyArg_ParseTuple(args, "O&i|i", - PyUnicode_FSConverter, &ofile, - &flag, &mode)) - return NULL; - file = bytes2str(ofile, 1); - Py_BEGIN_ALLOW_THREADS - fd = open(file, flag, mode); - Py_END_ALLOW_THREADS - if (fd < 0) - return posix_error_with_allocated_filename(ofile); - release_bytes(ofile); - return PyLong_FromLong((long)fd); + if (unicode_file_names()) { + PyUnicodeObject *po; + if (PyArg_ParseTuple(args, "Ui|i:mkdir", &po, &flag, &mode)) { + Py_BEGIN_ALLOW_THREADS + /* PyUnicode_AS_UNICODE OK without thread + lock as it is a simple dereference. */ + fd = _wopen(PyUnicode_AS_UNICODE(po), flag, mode); + Py_END_ALLOW_THREADS + if (fd < 0) + return posix_error(); + return PyLong_FromLong((long)fd); + } + /* Drop the argument parsing error as narrow strings + are also valid. */ + PyErr_Clear(); + } +#endif + + if (!PyArg_ParseTuple(args, "O&i|i", + PyUnicode_FSConverter, &ofile, + &flag, &mode)) + return NULL; + file = bytes2str(ofile, 1); + Py_BEGIN_ALLOW_THREADS + fd = open(file, flag, mode); + Py_END_ALLOW_THREADS + if (fd < 0) + return posix_error_with_allocated_filename(ofile); + release_bytes(ofile); + return PyLong_FromLong((long)fd); } @@ -4939,37 +4940,37 @@ static PyObject * posix_close(PyObject *self, PyObject *args) { - int fd, res; - if (!PyArg_ParseTuple(args, "i:close", &fd)) - return NULL; - if (!_PyVerify_fd(fd)) - return posix_error(); - Py_BEGIN_ALLOW_THREADS - res = close(fd); - Py_END_ALLOW_THREADS - if (res < 0) - return posix_error(); - Py_INCREF(Py_None); - return Py_None; + int fd, res; + if (!PyArg_ParseTuple(args, "i:close", &fd)) + return NULL; + if (!_PyVerify_fd(fd)) + return posix_error(); + Py_BEGIN_ALLOW_THREADS + res = close(fd); + Py_END_ALLOW_THREADS + if (res < 0) + return posix_error(); + Py_INCREF(Py_None); + return Py_None; } -PyDoc_STRVAR(posix_closerange__doc__, +PyDoc_STRVAR(posix_closerange__doc__, "closerange(fd_low, fd_high)\n\n\ Closes all file descriptors in [fd_low, fd_high), ignoring errors."); static PyObject * posix_closerange(PyObject *self, PyObject *args) { - int fd_from, fd_to, i; - if (!PyArg_ParseTuple(args, "ii:closerange", &fd_from, &fd_to)) - return NULL; - Py_BEGIN_ALLOW_THREADS - for (i = fd_from; i < fd_to; i++) - if (_PyVerify_fd(i)) - close(i); - Py_END_ALLOW_THREADS - Py_RETURN_NONE; + int fd_from, fd_to, i; + if (!PyArg_ParseTuple(args, "ii:closerange", &fd_from, &fd_to)) + return NULL; + Py_BEGIN_ALLOW_THREADS + for (i = fd_from; i < fd_to; i++) + if (_PyVerify_fd(i)) + close(i); + Py_END_ALLOW_THREADS + Py_RETURN_NONE; } @@ -4980,17 +4981,17 @@ static PyObject * posix_dup(PyObject *self, PyObject *args) { - int fd; - if (!PyArg_ParseTuple(args, "i:dup", &fd)) - return NULL; - if (!_PyVerify_fd(fd)) - return posix_error(); - Py_BEGIN_ALLOW_THREADS - fd = dup(fd); - Py_END_ALLOW_THREADS - if (fd < 0) - return posix_error(); - return PyLong_FromLong((long)fd); + int fd; + if (!PyArg_ParseTuple(args, "i:dup", &fd)) + return NULL; + if (!_PyVerify_fd(fd)) + return posix_error(); + Py_BEGIN_ALLOW_THREADS + fd = dup(fd); + Py_END_ALLOW_THREADS + if (fd < 0) + return posix_error(); + return PyLong_FromLong((long)fd); } @@ -5001,18 +5002,18 @@ static PyObject * posix_dup2(PyObject *self, PyObject *args) { - int fd, fd2, res; - if (!PyArg_ParseTuple(args, "ii:dup2", &fd, &fd2)) - return NULL; - if (!_PyVerify_fd_dup2(fd, fd2)) - return posix_error(); - Py_BEGIN_ALLOW_THREADS - res = dup2(fd, fd2); - Py_END_ALLOW_THREADS - if (res < 0) - return posix_error(); - Py_INCREF(Py_None); - return Py_None; + int fd, fd2, res; + if (!PyArg_ParseTuple(args, "ii:dup2", &fd, &fd2)) + return NULL; + if (!_PyVerify_fd_dup2(fd, fd2)) + return posix_error(); + Py_BEGIN_ALLOW_THREADS + res = dup2(fd, fd2); + Py_END_ALLOW_THREADS + if (res < 0) + return posix_error(); + Py_INCREF(Py_None); + return Py_None; } @@ -5023,49 +5024,49 @@ static PyObject * posix_lseek(PyObject *self, PyObject *args) { - int fd, how; + int fd, how; #if defined(MS_WIN64) || defined(MS_WINDOWS) - PY_LONG_LONG pos, res; + PY_LONG_LONG pos, res; #else - off_t pos, res; + off_t pos, res; #endif - PyObject *posobj; - if (!PyArg_ParseTuple(args, "iOi:lseek", &fd, &posobj, &how)) - return NULL; + PyObject *posobj; + if (!PyArg_ParseTuple(args, "iOi:lseek", &fd, &posobj, &how)) + return NULL; #ifdef SEEK_SET - /* Turn 0, 1, 2 into SEEK_{SET,CUR,END} */ - switch (how) { - case 0: how = SEEK_SET; break; - case 1: how = SEEK_CUR; break; - case 2: how = SEEK_END; break; - } + /* Turn 0, 1, 2 into SEEK_{SET,CUR,END} */ + switch (how) { + case 0: how = SEEK_SET; break; + case 1: how = SEEK_CUR; break; + case 2: how = SEEK_END; break; + } #endif /* SEEK_END */ #if !defined(HAVE_LARGEFILE_SUPPORT) - pos = PyLong_AsLong(posobj); + pos = PyLong_AsLong(posobj); #else - pos = PyLong_Check(posobj) ? - PyLong_AsLongLong(posobj) : PyLong_AsLong(posobj); + pos = PyLong_Check(posobj) ? + PyLong_AsLongLong(posobj) : PyLong_AsLong(posobj); #endif - if (PyErr_Occurred()) - return NULL; + if (PyErr_Occurred()) + return NULL; - if (!_PyVerify_fd(fd)) - return posix_error(); - Py_BEGIN_ALLOW_THREADS + if (!_PyVerify_fd(fd)) + return posix_error(); + Py_BEGIN_ALLOW_THREADS #if defined(MS_WIN64) || defined(MS_WINDOWS) - res = _lseeki64(fd, pos, how); + res = _lseeki64(fd, pos, how); #else - res = lseek(fd, pos, how); + res = lseek(fd, pos, how); #endif - Py_END_ALLOW_THREADS - if (res < 0) - return posix_error(); + Py_END_ALLOW_THREADS + if (res < 0) + return posix_error(); #if !defined(HAVE_LARGEFILE_SUPPORT) - return PyLong_FromLong(res); + return PyLong_FromLong(res); #else - return PyLong_FromLongLong(res); + return PyLong_FromLongLong(res); #endif } @@ -5077,30 +5078,30 @@ static PyObject * posix_read(PyObject *self, PyObject *args) { - int fd, size; - Py_ssize_t n; - PyObject *buffer; - if (!PyArg_ParseTuple(args, "ii:read", &fd, &size)) - return NULL; - if (size < 0) { - errno = EINVAL; - return posix_error(); - } - buffer = PyBytes_FromStringAndSize((char *)NULL, size); - if (buffer == NULL) - return NULL; - if (!_PyVerify_fd(fd)) - return posix_error(); - Py_BEGIN_ALLOW_THREADS - n = read(fd, PyBytes_AS_STRING(buffer), size); - Py_END_ALLOW_THREADS - if (n < 0) { - Py_DECREF(buffer); - return posix_error(); - } - if (n != size) - _PyBytes_Resize(&buffer, n); - return buffer; + int fd, size; + Py_ssize_t n; + PyObject *buffer; + if (!PyArg_ParseTuple(args, "ii:read", &fd, &size)) + return NULL; + if (size < 0) { + errno = EINVAL; + return posix_error(); + } + buffer = PyBytes_FromStringAndSize((char *)NULL, size); + if (buffer == NULL) + return NULL; + if (!_PyVerify_fd(fd)) + return posix_error(); + Py_BEGIN_ALLOW_THREADS + n = read(fd, PyBytes_AS_STRING(buffer), size); + Py_END_ALLOW_THREADS + if (n < 0) { + Py_DECREF(buffer); + return posix_error(); + } + if (n != size) + _PyBytes_Resize(&buffer, n); + return buffer; } @@ -5111,21 +5112,21 @@ static PyObject * posix_write(PyObject *self, PyObject *args) { - Py_buffer pbuf; - int fd; - Py_ssize_t size; - - if (!PyArg_ParseTuple(args, "iy*:write", &fd, &pbuf)) - return NULL; - if (!_PyVerify_fd(fd)) - return posix_error(); - Py_BEGIN_ALLOW_THREADS - size = write(fd, pbuf.buf, (size_t)pbuf.len); - Py_END_ALLOW_THREADS - PyBuffer_Release(&pbuf); - if (size < 0) - return posix_error(); - return PyLong_FromSsize_t(size); + Py_buffer pbuf; + int fd; + Py_ssize_t size; + + if (!PyArg_ParseTuple(args, "iy*:write", &fd, &pbuf)) + return NULL; + if (!_PyVerify_fd(fd)) + return posix_error(); + Py_BEGIN_ALLOW_THREADS + size = write(fd, pbuf.buf, (size_t)pbuf.len); + Py_END_ALLOW_THREADS + PyBuffer_Release(&pbuf); + if (size < 0) + return posix_error(); + return PyLong_FromSsize_t(size); } @@ -5136,29 +5137,29 @@ static PyObject * posix_fstat(PyObject *self, PyObject *args) { - int fd; - STRUCT_STAT st; - int res; - if (!PyArg_ParseTuple(args, "i:fstat", &fd)) - return NULL; + int fd; + STRUCT_STAT st; + int res; + if (!PyArg_ParseTuple(args, "i:fstat", &fd)) + return NULL; #ifdef __VMS - /* on OpenVMS we must ensure that all bytes are written to the file */ - fsync(fd); + /* on OpenVMS we must ensure that all bytes are written to the file */ + fsync(fd); #endif - if (!_PyVerify_fd(fd)) - return posix_error(); - Py_BEGIN_ALLOW_THREADS - res = FSTAT(fd, &st); - Py_END_ALLOW_THREADS - if (res != 0) { + if (!_PyVerify_fd(fd)) + return posix_error(); + Py_BEGIN_ALLOW_THREADS + res = FSTAT(fd, &st); + Py_END_ALLOW_THREADS + if (res != 0) { #ifdef MS_WINDOWS - return win32_error("fstat", NULL); + return win32_error("fstat", NULL); #else - return posix_error(); + return posix_error(); #endif - } + } - return _pystat_fromstructstat(&st); + return _pystat_fromstructstat(&st); } PyDoc_STRVAR(posix_isatty__doc__, @@ -5169,12 +5170,12 @@ static PyObject * posix_isatty(PyObject *self, PyObject *args) { - int fd; - if (!PyArg_ParseTuple(args, "i:isatty", &fd)) - return NULL; - if (!_PyVerify_fd(fd)) - return PyBool_FromLong(0); - return PyBool_FromLong(isatty(fd)); + int fd; + if (!PyArg_ParseTuple(args, "i:isatty", &fd)) + return NULL; + if (!_PyVerify_fd(fd)) + return PyBool_FromLong(0); + return PyBool_FromLong(isatty(fd)); } #ifdef HAVE_PIPE @@ -5189,35 +5190,35 @@ HFILE read, write; APIRET rc; - Py_BEGIN_ALLOW_THREADS + Py_BEGIN_ALLOW_THREADS rc = DosCreatePipe( &read, &write, 4096); - Py_END_ALLOW_THREADS + Py_END_ALLOW_THREADS if (rc != NO_ERROR) return os2_error(rc); return Py_BuildValue("(ii)", read, write); #else #if !defined(MS_WINDOWS) - int fds[2]; - int res; - Py_BEGIN_ALLOW_THREADS - res = pipe(fds); - Py_END_ALLOW_THREADS - if (res != 0) - return posix_error(); - return Py_BuildValue("(ii)", fds[0], fds[1]); + int fds[2]; + int res; + Py_BEGIN_ALLOW_THREADS + res = pipe(fds); + Py_END_ALLOW_THREADS + if (res != 0) + return posix_error(); + return Py_BuildValue("(ii)", fds[0], fds[1]); #else /* MS_WINDOWS */ - HANDLE read, write; - int read_fd, write_fd; - BOOL ok; - Py_BEGIN_ALLOW_THREADS - ok = CreatePipe(&read, &write, NULL, 0); - Py_END_ALLOW_THREADS - if (!ok) - return win32_error("CreatePipe", NULL); - read_fd = _open_osfhandle((Py_intptr_t)read, 0); - write_fd = _open_osfhandle((Py_intptr_t)write, 1); - return Py_BuildValue("(ii)", read_fd, write_fd); + HANDLE read, write; + int read_fd, write_fd; + BOOL ok; + Py_BEGIN_ALLOW_THREADS + ok = CreatePipe(&read, &write, NULL, 0); + Py_END_ALLOW_THREADS + if (!ok) + return win32_error("CreatePipe", NULL); + read_fd = _open_osfhandle((Py_intptr_t)read, 0); + write_fd = _open_osfhandle((Py_intptr_t)write, 1); + return Py_BuildValue("(ii)", read_fd, write_fd); #endif /* MS_WINDOWS */ #endif } @@ -5232,18 +5233,18 @@ static PyObject * posix_mkfifo(PyObject *self, PyObject *args) { - char *filename; - int mode = 0666; - int res; - if (!PyArg_ParseTuple(args, "s|i:mkfifo", &filename, &mode)) - return NULL; - Py_BEGIN_ALLOW_THREADS - res = mkfifo(filename, mode); - Py_END_ALLOW_THREADS - if (res < 0) - return posix_error(); - Py_INCREF(Py_None); - return Py_None; + char *filename; + int mode = 0666; + int res; + if (!PyArg_ParseTuple(args, "s|i:mkfifo", &filename, &mode)) + return NULL; + Py_BEGIN_ALLOW_THREADS + res = mkfifo(filename, mode); + Py_END_ALLOW_THREADS + if (res < 0) + return posix_error(); + Py_INCREF(Py_None); + return Py_None; } #endif @@ -5262,19 +5263,19 @@ static PyObject * posix_mknod(PyObject *self, PyObject *args) { - char *filename; - int mode = 0600; - int device = 0; - int res; - if (!PyArg_ParseTuple(args, "s|ii:mknod", &filename, &mode, &device)) - return NULL; - Py_BEGIN_ALLOW_THREADS - res = mknod(filename, mode, device); - Py_END_ALLOW_THREADS - if (res < 0) - return posix_error(); - Py_INCREF(Py_None); - return Py_None; + char *filename; + int mode = 0600; + int device = 0; + int res; + if (!PyArg_ParseTuple(args, "s|ii:mknod", &filename, &mode, &device)) + return NULL; + Py_BEGIN_ALLOW_THREADS + res = mknod(filename, mode, device); + Py_END_ALLOW_THREADS + if (res < 0) + return posix_error(); + Py_INCREF(Py_None); + return Py_None; } #endif @@ -5286,10 +5287,10 @@ static PyObject * posix_major(PyObject *self, PyObject *args) { - int device; - if (!PyArg_ParseTuple(args, "i:major", &device)) - return NULL; - return PyLong_FromLong((long)major(device)); + int device; + if (!PyArg_ParseTuple(args, "i:major", &device)) + return NULL; + return PyLong_FromLong((long)major(device)); } PyDoc_STRVAR(posix_minor__doc__, @@ -5299,10 +5300,10 @@ static PyObject * posix_minor(PyObject *self, PyObject *args) { - int device; - if (!PyArg_ParseTuple(args, "i:minor", &device)) - return NULL; - return PyLong_FromLong((long)minor(device)); + int device; + if (!PyArg_ParseTuple(args, "i:minor", &device)) + return NULL; + return PyLong_FromLong((long)minor(device)); } PyDoc_STRVAR(posix_makedev__doc__, @@ -5312,10 +5313,10 @@ static PyObject * posix_makedev(PyObject *self, PyObject *args) { - int major, minor; - if (!PyArg_ParseTuple(args, "ii:makedev", &major, &minor)) - return NULL; - return PyLong_FromLong((long)makedev(major, minor)); + int major, minor; + if (!PyArg_ParseTuple(args, "ii:makedev", &major, &minor)) + return NULL; + return PyLong_FromLong((long)makedev(major, minor)); } #endif /* device macros */ @@ -5328,30 +5329,30 @@ static PyObject * posix_ftruncate(PyObject *self, PyObject *args) { - int fd; - off_t length; - int res; - PyObject *lenobj; + int fd; + off_t length; + int res; + PyObject *lenobj; - if (!PyArg_ParseTuple(args, "iO:ftruncate", &fd, &lenobj)) - return NULL; + if (!PyArg_ParseTuple(args, "iO:ftruncate", &fd, &lenobj)) + return NULL; #if !defined(HAVE_LARGEFILE_SUPPORT) - length = PyLong_AsLong(lenobj); + length = PyLong_AsLong(lenobj); #else - length = PyLong_Check(lenobj) ? - PyLong_AsLongLong(lenobj) : PyLong_AsLong(lenobj); + length = PyLong_Check(lenobj) ? + PyLong_AsLongLong(lenobj) : PyLong_AsLong(lenobj); #endif - if (PyErr_Occurred()) - return NULL; + if (PyErr_Occurred()) + return NULL; - Py_BEGIN_ALLOW_THREADS - res = ftruncate(fd, length); - Py_END_ALLOW_THREADS - if (res < 0) - return posix_error(); - Py_INCREF(Py_None); - return Py_None; + Py_BEGIN_ALLOW_THREADS + res = ftruncate(fd, length); + Py_END_ALLOW_THREADS + if (res < 0) + return posix_error(); + Py_INCREF(Py_None); + return Py_None; } #endif @@ -5368,29 +5369,29 @@ posix_putenv(PyObject *self, PyObject *args) { #ifdef MS_WINDOWS - wchar_t *s1, *s2; - wchar_t *newenv; + wchar_t *s1, *s2; + wchar_t *newenv; #else - PyObject *os1, *os2; - char *s1, *s2; - char *newenv; + PyObject *os1, *os2; + char *s1, *s2; + char *newenv; #endif - PyObject *newstr; - size_t len; + PyObject *newstr; + size_t len; #ifdef MS_WINDOWS - if (!PyArg_ParseTuple(args, - "uu:putenv", - &s1, &s2)) - return NULL; -#else - if (!PyArg_ParseTuple(args, - "O&O&:putenv", - PyUnicode_FSConverter, &os1, - PyUnicode_FSConverter, &os2)) - return NULL; - s1 = bytes2str(os1, 1); - s2 = bytes2str(os2, 1); + if (!PyArg_ParseTuple(args, + "uu:putenv", + &s1, &s2)) + return NULL; +#else + if (!PyArg_ParseTuple(args, + "O&O&:putenv", + PyUnicode_FSConverter, &os1, + PyUnicode_FSConverter, &os2)) + return NULL; + s1 = bytes2str(os1, 1); + s2 = bytes2str(os2, 1); #endif #if defined(PYOS_OS2) @@ -5409,59 +5410,59 @@ return os2_error(rc); } else { #endif - /* XXX This can leak memory -- not easy to fix :-( */ - /* len includes space for a trailing \0; the size arg to - PyBytes_FromStringAndSize does not count that */ + /* XXX This can leak memory -- not easy to fix :-( */ + /* len includes space for a trailing \0; the size arg to + PyBytes_FromStringAndSize does not count that */ #ifdef MS_WINDOWS - len = wcslen(s1) + wcslen(s2) + 2; - newstr = PyUnicode_FromUnicode(NULL, (int)len - 1); + len = wcslen(s1) + wcslen(s2) + 2; + newstr = PyUnicode_FromUnicode(NULL, (int)len - 1); #else - len = strlen(s1) + strlen(s2) + 2; - newstr = PyBytes_FromStringAndSize(NULL, (int)len - 1); + len = strlen(s1) + strlen(s2) + 2; + newstr = PyBytes_FromStringAndSize(NULL, (int)len - 1); #endif - if (newstr == NULL) - return PyErr_NoMemory(); + if (newstr == NULL) + return PyErr_NoMemory(); #ifdef MS_WINDOWS - newenv = PyUnicode_AsUnicode(newstr); - _snwprintf(newenv, len, L"%s=%s", s1, s2); - if (_wputenv(newenv)) { - Py_DECREF(newstr); - posix_error(); - return NULL; - } + newenv = PyUnicode_AsUnicode(newstr); + _snwprintf(newenv, len, L"%s=%s", s1, s2); + if (_wputenv(newenv)) { + Py_DECREF(newstr); + posix_error(); + return NULL; + } #else - newenv = PyBytes_AS_STRING(newstr); - PyOS_snprintf(newenv, len, "%s=%s", s1, s2); - if (putenv(newenv)) { - Py_DECREF(newstr); - release_bytes(os1); - release_bytes(os2); - posix_error(); - return NULL; - } + newenv = PyBytes_AS_STRING(newstr); + PyOS_snprintf(newenv, len, "%s=%s", s1, s2); + if (putenv(newenv)) { + Py_DECREF(newstr); + release_bytes(os1); + release_bytes(os2); + posix_error(); + return NULL; + } #endif - /* Install the first arg and newstr in posix_putenv_garbage; - * this will cause previous value to be collected. This has to - * happen after the real putenv() call because the old value - * was still accessible until then. */ - if (PyDict_SetItem(posix_putenv_garbage, - PyTuple_GET_ITEM(args, 0), newstr)) { - /* really not much we can do; just leak */ - PyErr_Clear(); - } - else { - Py_DECREF(newstr); - } + /* Install the first arg and newstr in posix_putenv_garbage; + * this will cause previous value to be collected. This has to + * happen after the real putenv() call because the old value + * was still accessible until then. */ + if (PyDict_SetItem(posix_putenv_garbage, + PyTuple_GET_ITEM(args, 0), newstr)) { + /* really not much we can do; just leak */ + PyErr_Clear(); + } + else { + Py_DECREF(newstr); + } #if defined(PYOS_OS2) } #endif #ifndef MS_WINDOWS - release_bytes(os1); - release_bytes(os2); + release_bytes(os1); + release_bytes(os2); #endif - Py_INCREF(Py_None); - return Py_None; + Py_INCREF(Py_None); + return Py_None; } #endif /* putenv */ @@ -5473,26 +5474,26 @@ static PyObject * posix_unsetenv(PyObject *self, PyObject *args) { - char *s1; + char *s1; - if (!PyArg_ParseTuple(args, "s:unsetenv", &s1)) - return NULL; + if (!PyArg_ParseTuple(args, "s:unsetenv", &s1)) + return NULL; - unsetenv(s1); + unsetenv(s1); - /* Remove the key from posix_putenv_garbage; - * this will cause it to be collected. This has to - * happen after the real unsetenv() call because the - * old value was still accessible until then. - */ - if (PyDict_DelItem(posix_putenv_garbage, - PyTuple_GET_ITEM(args, 0))) { - /* really not much we can do; just leak */ - PyErr_Clear(); - } + /* Remove the key from posix_putenv_garbage; + * this will cause it to be collected. This has to + * happen after the real unsetenv() call because the + * old value was still accessible until then. + */ + if (PyDict_DelItem(posix_putenv_garbage, + PyTuple_GET_ITEM(args, 0))) { + /* really not much we can do; just leak */ + PyErr_Clear(); + } - Py_INCREF(Py_None); - return Py_None; + Py_INCREF(Py_None); + return Py_None; } #endif /* unsetenv */ @@ -5503,17 +5504,17 @@ static PyObject * posix_strerror(PyObject *self, PyObject *args) { - int code; - char *message; - if (!PyArg_ParseTuple(args, "i:strerror", &code)) - return NULL; - message = strerror(code); - if (message == NULL) { - PyErr_SetString(PyExc_ValueError, - "strerror() argument out of range"); - return NULL; - } - return PyUnicode_FromString(message); + int code; + char *message; + if (!PyArg_ParseTuple(args, "i:strerror", &code)) + return NULL; + message = strerror(code); + if (message == NULL) { + PyErr_SetString(PyExc_ValueError, + "strerror() argument out of range"); + return NULL; + } + return PyUnicode_FromString(message); } @@ -5527,13 +5528,13 @@ static PyObject * posix_WCOREDUMP(PyObject *self, PyObject *args) { - WAIT_TYPE status; - WAIT_STATUS_INT(status) = 0; + WAIT_TYPE status; + WAIT_STATUS_INT(status) = 0; - if (!PyArg_ParseTuple(args, "i:WCOREDUMP", &WAIT_STATUS_INT(status))) - return NULL; + if (!PyArg_ParseTuple(args, "i:WCOREDUMP", &WAIT_STATUS_INT(status))) + return NULL; - return PyBool_FromLong(WCOREDUMP(status)); + return PyBool_FromLong(WCOREDUMP(status)); } #endif /* WCOREDUMP */ @@ -5546,13 +5547,13 @@ static PyObject * posix_WIFCONTINUED(PyObject *self, PyObject *args) { - WAIT_TYPE status; - WAIT_STATUS_INT(status) = 0; + WAIT_TYPE status; + WAIT_STATUS_INT(status) = 0; - if (!PyArg_ParseTuple(args, "i:WCONTINUED", &WAIT_STATUS_INT(status))) - return NULL; + if (!PyArg_ParseTuple(args, "i:WCONTINUED", &WAIT_STATUS_INT(status))) + return NULL; - return PyBool_FromLong(WIFCONTINUED(status)); + return PyBool_FromLong(WIFCONTINUED(status)); } #endif /* WIFCONTINUED */ @@ -5564,13 +5565,13 @@ static PyObject * posix_WIFSTOPPED(PyObject *self, PyObject *args) { - WAIT_TYPE status; - WAIT_STATUS_INT(status) = 0; + WAIT_TYPE status; + WAIT_STATUS_INT(status) = 0; - if (!PyArg_ParseTuple(args, "i:WIFSTOPPED", &WAIT_STATUS_INT(status))) - return NULL; + if (!PyArg_ParseTuple(args, "i:WIFSTOPPED", &WAIT_STATUS_INT(status))) + return NULL; - return PyBool_FromLong(WIFSTOPPED(status)); + return PyBool_FromLong(WIFSTOPPED(status)); } #endif /* WIFSTOPPED */ @@ -5582,13 +5583,13 @@ static PyObject * posix_WIFSIGNALED(PyObject *self, PyObject *args) { - WAIT_TYPE status; - WAIT_STATUS_INT(status) = 0; + WAIT_TYPE status; + WAIT_STATUS_INT(status) = 0; - if (!PyArg_ParseTuple(args, "i:WIFSIGNALED", &WAIT_STATUS_INT(status))) - return NULL; + if (!PyArg_ParseTuple(args, "i:WIFSIGNALED", &WAIT_STATUS_INT(status))) + return NULL; - return PyBool_FromLong(WIFSIGNALED(status)); + return PyBool_FromLong(WIFSIGNALED(status)); } #endif /* WIFSIGNALED */ @@ -5601,13 +5602,13 @@ static PyObject * posix_WIFEXITED(PyObject *self, PyObject *args) { - WAIT_TYPE status; - WAIT_STATUS_INT(status) = 0; + WAIT_TYPE status; + WAIT_STATUS_INT(status) = 0; - if (!PyArg_ParseTuple(args, "i:WIFEXITED", &WAIT_STATUS_INT(status))) - return NULL; + if (!PyArg_ParseTuple(args, "i:WIFEXITED", &WAIT_STATUS_INT(status))) + return NULL; - return PyBool_FromLong(WIFEXITED(status)); + return PyBool_FromLong(WIFEXITED(status)); } #endif /* WIFEXITED */ @@ -5619,13 +5620,13 @@ static PyObject * posix_WEXITSTATUS(PyObject *self, PyObject *args) { - WAIT_TYPE status; - WAIT_STATUS_INT(status) = 0; + WAIT_TYPE status; + WAIT_STATUS_INT(status) = 0; - if (!PyArg_ParseTuple(args, "i:WEXITSTATUS", &WAIT_STATUS_INT(status))) - return NULL; + if (!PyArg_ParseTuple(args, "i:WEXITSTATUS", &WAIT_STATUS_INT(status))) + return NULL; - return Py_BuildValue("i", WEXITSTATUS(status)); + return Py_BuildValue("i", WEXITSTATUS(status)); } #endif /* WEXITSTATUS */ @@ -5638,13 +5639,13 @@ static PyObject * posix_WTERMSIG(PyObject *self, PyObject *args) { - WAIT_TYPE status; - WAIT_STATUS_INT(status) = 0; + WAIT_TYPE status; + WAIT_STATUS_INT(status) = 0; - if (!PyArg_ParseTuple(args, "i:WTERMSIG", &WAIT_STATUS_INT(status))) - return NULL; + if (!PyArg_ParseTuple(args, "i:WTERMSIG", &WAIT_STATUS_INT(status))) + return NULL; - return Py_BuildValue("i", WTERMSIG(status)); + return Py_BuildValue("i", WTERMSIG(status)); } #endif /* WTERMSIG */ @@ -5657,13 +5658,13 @@ static PyObject * posix_WSTOPSIG(PyObject *self, PyObject *args) { - WAIT_TYPE status; - WAIT_STATUS_INT(status) = 0; + WAIT_TYPE status; + WAIT_STATUS_INT(status) = 0; - if (!PyArg_ParseTuple(args, "i:WSTOPSIG", &WAIT_STATUS_INT(status))) - return NULL; + if (!PyArg_ParseTuple(args, "i:WSTOPSIG", &WAIT_STATUS_INT(status))) + return NULL; - return Py_BuildValue("i", WSTOPSIG(status)); + return Py_BuildValue("i", WSTOPSIG(status)); } #endif /* WSTOPSIG */ @@ -5680,41 +5681,41 @@ static PyObject* _pystatvfs_fromstructstatvfs(struct statvfs st) { - PyObject *v = PyStructSequence_New(&StatVFSResultType); - if (v == NULL) - return NULL; + PyObject *v = PyStructSequence_New(&StatVFSResultType); + if (v == NULL) + return NULL; #if !defined(HAVE_LARGEFILE_SUPPORT) - PyStructSequence_SET_ITEM(v, 0, PyLong_FromLong((long) st.f_bsize)); - PyStructSequence_SET_ITEM(v, 1, PyLong_FromLong((long) st.f_frsize)); - PyStructSequence_SET_ITEM(v, 2, PyLong_FromLong((long) st.f_blocks)); - PyStructSequence_SET_ITEM(v, 3, PyLong_FromLong((long) st.f_bfree)); - PyStructSequence_SET_ITEM(v, 4, PyLong_FromLong((long) st.f_bavail)); - PyStructSequence_SET_ITEM(v, 5, PyLong_FromLong((long) st.f_files)); - PyStructSequence_SET_ITEM(v, 6, PyLong_FromLong((long) st.f_ffree)); - PyStructSequence_SET_ITEM(v, 7, PyLong_FromLong((long) st.f_favail)); - PyStructSequence_SET_ITEM(v, 8, PyLong_FromLong((long) st.f_flag)); - PyStructSequence_SET_ITEM(v, 9, PyLong_FromLong((long) st.f_namemax)); -#else - PyStructSequence_SET_ITEM(v, 0, PyLong_FromLong((long) st.f_bsize)); - PyStructSequence_SET_ITEM(v, 1, PyLong_FromLong((long) st.f_frsize)); - PyStructSequence_SET_ITEM(v, 2, - PyLong_FromLongLong((PY_LONG_LONG) st.f_blocks)); - PyStructSequence_SET_ITEM(v, 3, - PyLong_FromLongLong((PY_LONG_LONG) st.f_bfree)); - PyStructSequence_SET_ITEM(v, 4, - PyLong_FromLongLong((PY_LONG_LONG) st.f_bavail)); - PyStructSequence_SET_ITEM(v, 5, - PyLong_FromLongLong((PY_LONG_LONG) st.f_files)); - PyStructSequence_SET_ITEM(v, 6, - PyLong_FromLongLong((PY_LONG_LONG) st.f_ffree)); - PyStructSequence_SET_ITEM(v, 7, - PyLong_FromLongLong((PY_LONG_LONG) st.f_favail)); - PyStructSequence_SET_ITEM(v, 8, PyLong_FromLong((long) st.f_flag)); - PyStructSequence_SET_ITEM(v, 9, PyLong_FromLong((long) st.f_namemax)); + PyStructSequence_SET_ITEM(v, 0, PyLong_FromLong((long) st.f_bsize)); + PyStructSequence_SET_ITEM(v, 1, PyLong_FromLong((long) st.f_frsize)); + PyStructSequence_SET_ITEM(v, 2, PyLong_FromLong((long) st.f_blocks)); + PyStructSequence_SET_ITEM(v, 3, PyLong_FromLong((long) st.f_bfree)); + PyStructSequence_SET_ITEM(v, 4, PyLong_FromLong((long) st.f_bavail)); + PyStructSequence_SET_ITEM(v, 5, PyLong_FromLong((long) st.f_files)); + PyStructSequence_SET_ITEM(v, 6, PyLong_FromLong((long) st.f_ffree)); + PyStructSequence_SET_ITEM(v, 7, PyLong_FromLong((long) st.f_favail)); + PyStructSequence_SET_ITEM(v, 8, PyLong_FromLong((long) st.f_flag)); + PyStructSequence_SET_ITEM(v, 9, PyLong_FromLong((long) st.f_namemax)); +#else + PyStructSequence_SET_ITEM(v, 0, PyLong_FromLong((long) st.f_bsize)); + PyStructSequence_SET_ITEM(v, 1, PyLong_FromLong((long) st.f_frsize)); + PyStructSequence_SET_ITEM(v, 2, + PyLong_FromLongLong((PY_LONG_LONG) st.f_blocks)); + PyStructSequence_SET_ITEM(v, 3, + PyLong_FromLongLong((PY_LONG_LONG) st.f_bfree)); + PyStructSequence_SET_ITEM(v, 4, + PyLong_FromLongLong((PY_LONG_LONG) st.f_bavail)); + PyStructSequence_SET_ITEM(v, 5, + PyLong_FromLongLong((PY_LONG_LONG) st.f_files)); + PyStructSequence_SET_ITEM(v, 6, + PyLong_FromLongLong((PY_LONG_LONG) st.f_ffree)); + PyStructSequence_SET_ITEM(v, 7, + PyLong_FromLongLong((PY_LONG_LONG) st.f_favail)); + PyStructSequence_SET_ITEM(v, 8, PyLong_FromLong((long) st.f_flag)); + PyStructSequence_SET_ITEM(v, 9, PyLong_FromLong((long) st.f_namemax)); #endif - return v; + return v; } PyDoc_STRVAR(posix_fstatvfs__doc__, @@ -5724,18 +5725,18 @@ static PyObject * posix_fstatvfs(PyObject *self, PyObject *args) { - int fd, res; - struct statvfs st; + int fd, res; + struct statvfs st; - if (!PyArg_ParseTuple(args, "i:fstatvfs", &fd)) - return NULL; - Py_BEGIN_ALLOW_THREADS - res = fstatvfs(fd, &st); - Py_END_ALLOW_THREADS - if (res != 0) - return posix_error(); + if (!PyArg_ParseTuple(args, "i:fstatvfs", &fd)) + return NULL; + Py_BEGIN_ALLOW_THREADS + res = fstatvfs(fd, &st); + Py_END_ALLOW_THREADS + if (res != 0) + return posix_error(); - return _pystatvfs_fromstructstatvfs(st); + return _pystatvfs_fromstructstatvfs(st); } #endif /* HAVE_FSTATVFS && HAVE_SYS_STATVFS_H */ @@ -5750,18 +5751,18 @@ static PyObject * posix_statvfs(PyObject *self, PyObject *args) { - char *path; - int res; - struct statvfs st; - if (!PyArg_ParseTuple(args, "s:statvfs", &path)) - return NULL; - Py_BEGIN_ALLOW_THREADS - res = statvfs(path, &st); - Py_END_ALLOW_THREADS - if (res != 0) - return posix_error_with_filename(path); + char *path; + int res; + struct statvfs st; + if (!PyArg_ParseTuple(args, "s:statvfs", &path)) + return NULL; + Py_BEGIN_ALLOW_THREADS + res = statvfs(path, &st); + Py_END_ALLOW_THREADS + if (res != 0) + return posix_error_with_filename(path); - return _pystatvfs_fromstructstatvfs(st); + return _pystatvfs_fromstructstatvfs(st); } #endif /* HAVE_STATVFS */ @@ -5786,38 +5787,38 @@ size_t tablesize) { if (PyLong_Check(arg)) { - *valuep = PyLong_AS_LONG(arg); - return 1; + *valuep = PyLong_AS_LONG(arg); + return 1; } else { - /* look up the value in the table using a binary search */ - size_t lo = 0; - size_t mid; - size_t hi = tablesize; - int cmp; - const char *confname; - if (!PyUnicode_Check(arg)) { - PyErr_SetString(PyExc_TypeError, - "configuration names must be strings or integers"); - return 0; - } - confname = _PyUnicode_AsString(arg); - if (confname == NULL) - return 0; - while (lo < hi) { - mid = (lo + hi) / 2; - cmp = strcmp(confname, table[mid].name); - if (cmp < 0) - hi = mid; - else if (cmp > 0) - lo = mid + 1; - else { - *valuep = table[mid].value; - return 1; - } - } - PyErr_SetString(PyExc_ValueError, "unrecognized configuration name"); + /* look up the value in the table using a binary search */ + size_t lo = 0; + size_t mid; + size_t hi = tablesize; + int cmp; + const char *confname; + if (!PyUnicode_Check(arg)) { + PyErr_SetString(PyExc_TypeError, + "configuration names must be strings or integers"); + return 0; + } + confname = _PyUnicode_AsString(arg); + if (confname == NULL) return 0; + while (lo < hi) { + mid = (lo + hi) / 2; + cmp = strcmp(confname, table[mid].name); + if (cmp < 0) + hi = mid; + else if (cmp > 0) + lo = mid + 1; + else { + *valuep = table[mid].value; + return 1; + } + } + PyErr_SetString(PyExc_ValueError, "unrecognized configuration name"); + return 0; } } @@ -5825,55 +5826,55 @@ #if defined(HAVE_FPATHCONF) || defined(HAVE_PATHCONF) static struct constdef posix_constants_pathconf[] = { #ifdef _PC_ABI_AIO_XFER_MAX - {"PC_ABI_AIO_XFER_MAX", _PC_ABI_AIO_XFER_MAX}, + {"PC_ABI_AIO_XFER_MAX", _PC_ABI_AIO_XFER_MAX}, #endif #ifdef _PC_ABI_ASYNC_IO - {"PC_ABI_ASYNC_IO", _PC_ABI_ASYNC_IO}, + {"PC_ABI_ASYNC_IO", _PC_ABI_ASYNC_IO}, #endif #ifdef _PC_ASYNC_IO - {"PC_ASYNC_IO", _PC_ASYNC_IO}, + {"PC_ASYNC_IO", _PC_ASYNC_IO}, #endif #ifdef _PC_CHOWN_RESTRICTED - {"PC_CHOWN_RESTRICTED", _PC_CHOWN_RESTRICTED}, + {"PC_CHOWN_RESTRICTED", _PC_CHOWN_RESTRICTED}, #endif #ifdef _PC_FILESIZEBITS - {"PC_FILESIZEBITS", _PC_FILESIZEBITS}, + {"PC_FILESIZEBITS", _PC_FILESIZEBITS}, #endif #ifdef _PC_LAST - {"PC_LAST", _PC_LAST}, + {"PC_LAST", _PC_LAST}, #endif #ifdef _PC_LINK_MAX - {"PC_LINK_MAX", _PC_LINK_MAX}, + {"PC_LINK_MAX", _PC_LINK_MAX}, #endif #ifdef _PC_MAX_CANON - {"PC_MAX_CANON", _PC_MAX_CANON}, + {"PC_MAX_CANON", _PC_MAX_CANON}, #endif #ifdef _PC_MAX_INPUT - {"PC_MAX_INPUT", _PC_MAX_INPUT}, + {"PC_MAX_INPUT", _PC_MAX_INPUT}, #endif #ifdef _PC_NAME_MAX - {"PC_NAME_MAX", _PC_NAME_MAX}, + {"PC_NAME_MAX", _PC_NAME_MAX}, #endif #ifdef _PC_NO_TRUNC - {"PC_NO_TRUNC", _PC_NO_TRUNC}, + {"PC_NO_TRUNC", _PC_NO_TRUNC}, #endif #ifdef _PC_PATH_MAX - {"PC_PATH_MAX", _PC_PATH_MAX}, + {"PC_PATH_MAX", _PC_PATH_MAX}, #endif #ifdef _PC_PIPE_BUF - {"PC_PIPE_BUF", _PC_PIPE_BUF}, + {"PC_PIPE_BUF", _PC_PIPE_BUF}, #endif #ifdef _PC_PRIO_IO - {"PC_PRIO_IO", _PC_PRIO_IO}, + {"PC_PRIO_IO", _PC_PRIO_IO}, #endif #ifdef _PC_SOCK_MAXBUF - {"PC_SOCK_MAXBUF", _PC_SOCK_MAXBUF}, + {"PC_SOCK_MAXBUF", _PC_SOCK_MAXBUF}, #endif #ifdef _PC_SYNC_IO - {"PC_SYNC_IO", _PC_SYNC_IO}, + {"PC_SYNC_IO", _PC_SYNC_IO}, #endif #ifdef _PC_VDISABLE - {"PC_VDISABLE", _PC_VDISABLE}, + {"PC_VDISABLE", _PC_VDISABLE}, #endif }; @@ -5900,14 +5901,14 @@ if (PyArg_ParseTuple(args, "iO&:fpathconf", &fd, conv_path_confname, &name)) { - long limit; + long limit; - errno = 0; - limit = fpathconf(fd, name); - if (limit == -1 && errno != 0) - posix_error(); - else - result = PyLong_FromLong(limit); + errno = 0; + limit = fpathconf(fd, name); + if (limit == -1 && errno != 0) + posix_error(); + else + result = PyLong_FromLong(limit); } return result; } @@ -5929,19 +5930,19 @@ if (PyArg_ParseTuple(args, "sO&:pathconf", &path, conv_path_confname, &name)) { - long limit; + long limit; - errno = 0; - limit = pathconf(path, name); - if (limit == -1 && errno != 0) { - if (errno == EINVAL) - /* could be a path or name problem */ - posix_error(); - else - posix_error_with_filename(path); - } + errno = 0; + limit = pathconf(path, name); + if (limit == -1 && errno != 0) { + if (errno == EINVAL) + /* could be a path or name problem */ + posix_error(); else - result = PyLong_FromLong(limit); + posix_error_with_filename(path); + } + else + result = PyLong_FromLong(limit); } return result; } @@ -5950,154 +5951,154 @@ #ifdef HAVE_CONFSTR static struct constdef posix_constants_confstr[] = { #ifdef _CS_ARCHITECTURE - {"CS_ARCHITECTURE", _CS_ARCHITECTURE}, + {"CS_ARCHITECTURE", _CS_ARCHITECTURE}, #endif #ifdef _CS_GNU_LIBC_VERSION - {"CS_GNU_LIBC_VERSION", _CS_GNU_LIBC_VERSION}, + {"CS_GNU_LIBC_VERSION", _CS_GNU_LIBC_VERSION}, #endif #ifdef _CS_GNU_LIBPTHREAD_VERSION - {"CS_GNU_LIBPTHREAD_VERSION", _CS_GNU_LIBPTHREAD_VERSION}, + {"CS_GNU_LIBPTHREAD_VERSION", _CS_GNU_LIBPTHREAD_VERSION}, #endif #ifdef _CS_HOSTNAME - {"CS_HOSTNAME", _CS_HOSTNAME}, + {"CS_HOSTNAME", _CS_HOSTNAME}, #endif #ifdef _CS_HW_PROVIDER - {"CS_HW_PROVIDER", _CS_HW_PROVIDER}, + {"CS_HW_PROVIDER", _CS_HW_PROVIDER}, #endif #ifdef _CS_HW_SERIAL - {"CS_HW_SERIAL", _CS_HW_SERIAL}, + {"CS_HW_SERIAL", _CS_HW_SERIAL}, #endif #ifdef _CS_INITTAB_NAME - {"CS_INITTAB_NAME", _CS_INITTAB_NAME}, + {"CS_INITTAB_NAME", _CS_INITTAB_NAME}, #endif #ifdef _CS_LFS64_CFLAGS - {"CS_LFS64_CFLAGS", _CS_LFS64_CFLAGS}, + {"CS_LFS64_CFLAGS", _CS_LFS64_CFLAGS}, #endif #ifdef _CS_LFS64_LDFLAGS - {"CS_LFS64_LDFLAGS", _CS_LFS64_LDFLAGS}, + {"CS_LFS64_LDFLAGS", _CS_LFS64_LDFLAGS}, #endif #ifdef _CS_LFS64_LIBS - {"CS_LFS64_LIBS", _CS_LFS64_LIBS}, + {"CS_LFS64_LIBS", _CS_LFS64_LIBS}, #endif #ifdef _CS_LFS64_LINTFLAGS - {"CS_LFS64_LINTFLAGS", _CS_LFS64_LINTFLAGS}, + {"CS_LFS64_LINTFLAGS", _CS_LFS64_LINTFLAGS}, #endif #ifdef _CS_LFS_CFLAGS - {"CS_LFS_CFLAGS", _CS_LFS_CFLAGS}, + {"CS_LFS_CFLAGS", _CS_LFS_CFLAGS}, #endif #ifdef _CS_LFS_LDFLAGS - {"CS_LFS_LDFLAGS", _CS_LFS_LDFLAGS}, + {"CS_LFS_LDFLAGS", _CS_LFS_LDFLAGS}, #endif #ifdef _CS_LFS_LIBS - {"CS_LFS_LIBS", _CS_LFS_LIBS}, + {"CS_LFS_LIBS", _CS_LFS_LIBS}, #endif #ifdef _CS_LFS_LINTFLAGS - {"CS_LFS_LINTFLAGS", _CS_LFS_LINTFLAGS}, + {"CS_LFS_LINTFLAGS", _CS_LFS_LINTFLAGS}, #endif #ifdef _CS_MACHINE - {"CS_MACHINE", _CS_MACHINE}, + {"CS_MACHINE", _CS_MACHINE}, #endif #ifdef _CS_PATH - {"CS_PATH", _CS_PATH}, + {"CS_PATH", _CS_PATH}, #endif #ifdef _CS_RELEASE - {"CS_RELEASE", _CS_RELEASE}, + {"CS_RELEASE", _CS_RELEASE}, #endif #ifdef _CS_SRPC_DOMAIN - {"CS_SRPC_DOMAIN", _CS_SRPC_DOMAIN}, + {"CS_SRPC_DOMAIN", _CS_SRPC_DOMAIN}, #endif #ifdef _CS_SYSNAME - {"CS_SYSNAME", _CS_SYSNAME}, + {"CS_SYSNAME", _CS_SYSNAME}, #endif #ifdef _CS_VERSION - {"CS_VERSION", _CS_VERSION}, + {"CS_VERSION", _CS_VERSION}, #endif #ifdef _CS_XBS5_ILP32_OFF32_CFLAGS - {"CS_XBS5_ILP32_OFF32_CFLAGS", _CS_XBS5_ILP32_OFF32_CFLAGS}, + {"CS_XBS5_ILP32_OFF32_CFLAGS", _CS_XBS5_ILP32_OFF32_CFLAGS}, #endif #ifdef _CS_XBS5_ILP32_OFF32_LDFLAGS - {"CS_XBS5_ILP32_OFF32_LDFLAGS", _CS_XBS5_ILP32_OFF32_LDFLAGS}, + {"CS_XBS5_ILP32_OFF32_LDFLAGS", _CS_XBS5_ILP32_OFF32_LDFLAGS}, #endif #ifdef _CS_XBS5_ILP32_OFF32_LIBS - {"CS_XBS5_ILP32_OFF32_LIBS", _CS_XBS5_ILP32_OFF32_LIBS}, + {"CS_XBS5_ILP32_OFF32_LIBS", _CS_XBS5_ILP32_OFF32_LIBS}, #endif #ifdef _CS_XBS5_ILP32_OFF32_LINTFLAGS - {"CS_XBS5_ILP32_OFF32_LINTFLAGS", _CS_XBS5_ILP32_OFF32_LINTFLAGS}, + {"CS_XBS5_ILP32_OFF32_LINTFLAGS", _CS_XBS5_ILP32_OFF32_LINTFLAGS}, #endif #ifdef _CS_XBS5_ILP32_OFFBIG_CFLAGS - {"CS_XBS5_ILP32_OFFBIG_CFLAGS", _CS_XBS5_ILP32_OFFBIG_CFLAGS}, + {"CS_XBS5_ILP32_OFFBIG_CFLAGS", _CS_XBS5_ILP32_OFFBIG_CFLAGS}, #endif #ifdef _CS_XBS5_ILP32_OFFBIG_LDFLAGS - {"CS_XBS5_ILP32_OFFBIG_LDFLAGS", _CS_XBS5_ILP32_OFFBIG_LDFLAGS}, + {"CS_XBS5_ILP32_OFFBIG_LDFLAGS", _CS_XBS5_ILP32_OFFBIG_LDFLAGS}, #endif #ifdef _CS_XBS5_ILP32_OFFBIG_LIBS - {"CS_XBS5_ILP32_OFFBIG_LIBS", _CS_XBS5_ILP32_OFFBIG_LIBS}, + {"CS_XBS5_ILP32_OFFBIG_LIBS", _CS_XBS5_ILP32_OFFBIG_LIBS}, #endif #ifdef _CS_XBS5_ILP32_OFFBIG_LINTFLAGS - {"CS_XBS5_ILP32_OFFBIG_LINTFLAGS", _CS_XBS5_ILP32_OFFBIG_LINTFLAGS}, + {"CS_XBS5_ILP32_OFFBIG_LINTFLAGS", _CS_XBS5_ILP32_OFFBIG_LINTFLAGS}, #endif #ifdef _CS_XBS5_LP64_OFF64_CFLAGS - {"CS_XBS5_LP64_OFF64_CFLAGS", _CS_XBS5_LP64_OFF64_CFLAGS}, + {"CS_XBS5_LP64_OFF64_CFLAGS", _CS_XBS5_LP64_OFF64_CFLAGS}, #endif #ifdef _CS_XBS5_LP64_OFF64_LDFLAGS - {"CS_XBS5_LP64_OFF64_LDFLAGS", _CS_XBS5_LP64_OFF64_LDFLAGS}, + {"CS_XBS5_LP64_OFF64_LDFLAGS", _CS_XBS5_LP64_OFF64_LDFLAGS}, #endif #ifdef _CS_XBS5_LP64_OFF64_LIBS - {"CS_XBS5_LP64_OFF64_LIBS", _CS_XBS5_LP64_OFF64_LIBS}, + {"CS_XBS5_LP64_OFF64_LIBS", _CS_XBS5_LP64_OFF64_LIBS}, #endif #ifdef _CS_XBS5_LP64_OFF64_LINTFLAGS - {"CS_XBS5_LP64_OFF64_LINTFLAGS", _CS_XBS5_LP64_OFF64_LINTFLAGS}, + {"CS_XBS5_LP64_OFF64_LINTFLAGS", _CS_XBS5_LP64_OFF64_LINTFLAGS}, #endif #ifdef _CS_XBS5_LPBIG_OFFBIG_CFLAGS - {"CS_XBS5_LPBIG_OFFBIG_CFLAGS", _CS_XBS5_LPBIG_OFFBIG_CFLAGS}, + {"CS_XBS5_LPBIG_OFFBIG_CFLAGS", _CS_XBS5_LPBIG_OFFBIG_CFLAGS}, #endif #ifdef _CS_XBS5_LPBIG_OFFBIG_LDFLAGS - {"CS_XBS5_LPBIG_OFFBIG_LDFLAGS", _CS_XBS5_LPBIG_OFFBIG_LDFLAGS}, + {"CS_XBS5_LPBIG_OFFBIG_LDFLAGS", _CS_XBS5_LPBIG_OFFBIG_LDFLAGS}, #endif #ifdef _CS_XBS5_LPBIG_OFFBIG_LIBS - {"CS_XBS5_LPBIG_OFFBIG_LIBS", _CS_XBS5_LPBIG_OFFBIG_LIBS}, + {"CS_XBS5_LPBIG_OFFBIG_LIBS", _CS_XBS5_LPBIG_OFFBIG_LIBS}, #endif #ifdef _CS_XBS5_LPBIG_OFFBIG_LINTFLAGS - {"CS_XBS5_LPBIG_OFFBIG_LINTFLAGS", _CS_XBS5_LPBIG_OFFBIG_LINTFLAGS}, + {"CS_XBS5_LPBIG_OFFBIG_LINTFLAGS", _CS_XBS5_LPBIG_OFFBIG_LINTFLAGS}, #endif #ifdef _MIPS_CS_AVAIL_PROCESSORS - {"MIPS_CS_AVAIL_PROCESSORS", _MIPS_CS_AVAIL_PROCESSORS}, + {"MIPS_CS_AVAIL_PROCESSORS", _MIPS_CS_AVAIL_PROCESSORS}, #endif #ifdef _MIPS_CS_BASE - {"MIPS_CS_BASE", _MIPS_CS_BASE}, + {"MIPS_CS_BASE", _MIPS_CS_BASE}, #endif #ifdef _MIPS_CS_HOSTID - {"MIPS_CS_HOSTID", _MIPS_CS_HOSTID}, + {"MIPS_CS_HOSTID", _MIPS_CS_HOSTID}, #endif #ifdef _MIPS_CS_HW_NAME - {"MIPS_CS_HW_NAME", _MIPS_CS_HW_NAME}, + {"MIPS_CS_HW_NAME", _MIPS_CS_HW_NAME}, #endif #ifdef _MIPS_CS_NUM_PROCESSORS - {"MIPS_CS_NUM_PROCESSORS", _MIPS_CS_NUM_PROCESSORS}, + {"MIPS_CS_NUM_PROCESSORS", _MIPS_CS_NUM_PROCESSORS}, #endif #ifdef _MIPS_CS_OSREL_MAJ - {"MIPS_CS_OSREL_MAJ", _MIPS_CS_OSREL_MAJ}, + {"MIPS_CS_OSREL_MAJ", _MIPS_CS_OSREL_MAJ}, #endif #ifdef _MIPS_CS_OSREL_MIN - {"MIPS_CS_OSREL_MIN", _MIPS_CS_OSREL_MIN}, + {"MIPS_CS_OSREL_MIN", _MIPS_CS_OSREL_MIN}, #endif #ifdef _MIPS_CS_OSREL_PATCH - {"MIPS_CS_OSREL_PATCH", _MIPS_CS_OSREL_PATCH}, + {"MIPS_CS_OSREL_PATCH", _MIPS_CS_OSREL_PATCH}, #endif #ifdef _MIPS_CS_OS_NAME - {"MIPS_CS_OS_NAME", _MIPS_CS_OS_NAME}, + {"MIPS_CS_OS_NAME", _MIPS_CS_OS_NAME}, #endif #ifdef _MIPS_CS_OS_PROVIDER - {"MIPS_CS_OS_PROVIDER", _MIPS_CS_OS_PROVIDER}, + {"MIPS_CS_OS_PROVIDER", _MIPS_CS_OS_PROVIDER}, #endif #ifdef _MIPS_CS_PROCESSORS - {"MIPS_CS_PROCESSORS", _MIPS_CS_PROCESSORS}, + {"MIPS_CS_PROCESSORS", _MIPS_CS_PROCESSORS}, #endif #ifdef _MIPS_CS_SERIAL - {"MIPS_CS_SERIAL", _MIPS_CS_SERIAL}, + {"MIPS_CS_SERIAL", _MIPS_CS_SERIAL}, #endif #ifdef _MIPS_CS_VENDOR - {"MIPS_CS_VENDOR", _MIPS_CS_VENDOR}, + {"MIPS_CS_VENDOR", _MIPS_CS_VENDOR}, #endif }; @@ -6121,21 +6122,21 @@ char buffer[256]; if (PyArg_ParseTuple(args, "O&:confstr", conv_confstr_confname, &name)) { - int len; + int len; errno = 0; - len = confstr(name, buffer, sizeof(buffer)); - if (len == 0) { - if (errno) { - posix_error(); - } - else { - result = Py_None; - Py_INCREF(Py_None); - } + len = confstr(name, buffer, sizeof(buffer)); + if (len == 0) { + if (errno) { + posix_error(); + } + else { + result = Py_None; + Py_INCREF(Py_None); + } } else { - if ((unsigned int)len >= sizeof(buffer)) { + if ((unsigned int)len >= sizeof(buffer)) { result = PyUnicode_FromStringAndSize(NULL, len-1); if (result != NULL) confstr(name, _PyUnicode_AsString(result), len); @@ -6152,496 +6153,496 @@ #ifdef HAVE_SYSCONF static struct constdef posix_constants_sysconf[] = { #ifdef _SC_2_CHAR_TERM - {"SC_2_CHAR_TERM", _SC_2_CHAR_TERM}, + {"SC_2_CHAR_TERM", _SC_2_CHAR_TERM}, #endif #ifdef _SC_2_C_BIND - {"SC_2_C_BIND", _SC_2_C_BIND}, + {"SC_2_C_BIND", _SC_2_C_BIND}, #endif #ifdef _SC_2_C_DEV - {"SC_2_C_DEV", _SC_2_C_DEV}, + {"SC_2_C_DEV", _SC_2_C_DEV}, #endif #ifdef _SC_2_C_VERSION - {"SC_2_C_VERSION", _SC_2_C_VERSION}, + {"SC_2_C_VERSION", _SC_2_C_VERSION}, #endif #ifdef _SC_2_FORT_DEV - {"SC_2_FORT_DEV", _SC_2_FORT_DEV}, + {"SC_2_FORT_DEV", _SC_2_FORT_DEV}, #endif #ifdef _SC_2_FORT_RUN - {"SC_2_FORT_RUN", _SC_2_FORT_RUN}, + {"SC_2_FORT_RUN", _SC_2_FORT_RUN}, #endif #ifdef _SC_2_LOCALEDEF - {"SC_2_LOCALEDEF", _SC_2_LOCALEDEF}, + {"SC_2_LOCALEDEF", _SC_2_LOCALEDEF}, #endif #ifdef _SC_2_SW_DEV - {"SC_2_SW_DEV", _SC_2_SW_DEV}, + {"SC_2_SW_DEV", _SC_2_SW_DEV}, #endif #ifdef _SC_2_UPE - {"SC_2_UPE", _SC_2_UPE}, + {"SC_2_UPE", _SC_2_UPE}, #endif #ifdef _SC_2_VERSION - {"SC_2_VERSION", _SC_2_VERSION}, + {"SC_2_VERSION", _SC_2_VERSION}, #endif #ifdef _SC_ABI_ASYNCHRONOUS_IO - {"SC_ABI_ASYNCHRONOUS_IO", _SC_ABI_ASYNCHRONOUS_IO}, + {"SC_ABI_ASYNCHRONOUS_IO", _SC_ABI_ASYNCHRONOUS_IO}, #endif #ifdef _SC_ACL - {"SC_ACL", _SC_ACL}, + {"SC_ACL", _SC_ACL}, #endif #ifdef _SC_AIO_LISTIO_MAX - {"SC_AIO_LISTIO_MAX", _SC_AIO_LISTIO_MAX}, + {"SC_AIO_LISTIO_MAX", _SC_AIO_LISTIO_MAX}, #endif #ifdef _SC_AIO_MAX - {"SC_AIO_MAX", _SC_AIO_MAX}, + {"SC_AIO_MAX", _SC_AIO_MAX}, #endif #ifdef _SC_AIO_PRIO_DELTA_MAX - {"SC_AIO_PRIO_DELTA_MAX", _SC_AIO_PRIO_DELTA_MAX}, + {"SC_AIO_PRIO_DELTA_MAX", _SC_AIO_PRIO_DELTA_MAX}, #endif #ifdef _SC_ARG_MAX - {"SC_ARG_MAX", _SC_ARG_MAX}, + {"SC_ARG_MAX", _SC_ARG_MAX}, #endif #ifdef _SC_ASYNCHRONOUS_IO - {"SC_ASYNCHRONOUS_IO", _SC_ASYNCHRONOUS_IO}, + {"SC_ASYNCHRONOUS_IO", _SC_ASYNCHRONOUS_IO}, #endif #ifdef _SC_ATEXIT_MAX - {"SC_ATEXIT_MAX", _SC_ATEXIT_MAX}, + {"SC_ATEXIT_MAX", _SC_ATEXIT_MAX}, #endif #ifdef _SC_AUDIT - {"SC_AUDIT", _SC_AUDIT}, + {"SC_AUDIT", _SC_AUDIT}, #endif #ifdef _SC_AVPHYS_PAGES - {"SC_AVPHYS_PAGES", _SC_AVPHYS_PAGES}, + {"SC_AVPHYS_PAGES", _SC_AVPHYS_PAGES}, #endif #ifdef _SC_BC_BASE_MAX - {"SC_BC_BASE_MAX", _SC_BC_BASE_MAX}, + {"SC_BC_BASE_MAX", _SC_BC_BASE_MAX}, #endif #ifdef _SC_BC_DIM_MAX - {"SC_BC_DIM_MAX", _SC_BC_DIM_MAX}, + {"SC_BC_DIM_MAX", _SC_BC_DIM_MAX}, #endif #ifdef _SC_BC_SCALE_MAX - {"SC_BC_SCALE_MAX", _SC_BC_SCALE_MAX}, + {"SC_BC_SCALE_MAX", _SC_BC_SCALE_MAX}, #endif #ifdef _SC_BC_STRING_MAX - {"SC_BC_STRING_MAX", _SC_BC_STRING_MAX}, + {"SC_BC_STRING_MAX", _SC_BC_STRING_MAX}, #endif #ifdef _SC_CAP - {"SC_CAP", _SC_CAP}, + {"SC_CAP", _SC_CAP}, #endif #ifdef _SC_CHARCLASS_NAME_MAX - {"SC_CHARCLASS_NAME_MAX", _SC_CHARCLASS_NAME_MAX}, + {"SC_CHARCLASS_NAME_MAX", _SC_CHARCLASS_NAME_MAX}, #endif #ifdef _SC_CHAR_BIT - {"SC_CHAR_BIT", _SC_CHAR_BIT}, + {"SC_CHAR_BIT", _SC_CHAR_BIT}, #endif #ifdef _SC_CHAR_MAX - {"SC_CHAR_MAX", _SC_CHAR_MAX}, + {"SC_CHAR_MAX", _SC_CHAR_MAX}, #endif #ifdef _SC_CHAR_MIN - {"SC_CHAR_MIN", _SC_CHAR_MIN}, + {"SC_CHAR_MIN", _SC_CHAR_MIN}, #endif #ifdef _SC_CHILD_MAX - {"SC_CHILD_MAX", _SC_CHILD_MAX}, + {"SC_CHILD_MAX", _SC_CHILD_MAX}, #endif #ifdef _SC_CLK_TCK - {"SC_CLK_TCK", _SC_CLK_TCK}, + {"SC_CLK_TCK", _SC_CLK_TCK}, #endif #ifdef _SC_COHER_BLKSZ - {"SC_COHER_BLKSZ", _SC_COHER_BLKSZ}, + {"SC_COHER_BLKSZ", _SC_COHER_BLKSZ}, #endif #ifdef _SC_COLL_WEIGHTS_MAX - {"SC_COLL_WEIGHTS_MAX", _SC_COLL_WEIGHTS_MAX}, + {"SC_COLL_WEIGHTS_MAX", _SC_COLL_WEIGHTS_MAX}, #endif #ifdef _SC_DCACHE_ASSOC - {"SC_DCACHE_ASSOC", _SC_DCACHE_ASSOC}, + {"SC_DCACHE_ASSOC", _SC_DCACHE_ASSOC}, #endif #ifdef _SC_DCACHE_BLKSZ - {"SC_DCACHE_BLKSZ", _SC_DCACHE_BLKSZ}, + {"SC_DCACHE_BLKSZ", _SC_DCACHE_BLKSZ}, #endif #ifdef _SC_DCACHE_LINESZ - {"SC_DCACHE_LINESZ", _SC_DCACHE_LINESZ}, + {"SC_DCACHE_LINESZ", _SC_DCACHE_LINESZ}, #endif #ifdef _SC_DCACHE_SZ - {"SC_DCACHE_SZ", _SC_DCACHE_SZ}, + {"SC_DCACHE_SZ", _SC_DCACHE_SZ}, #endif #ifdef _SC_DCACHE_TBLKSZ - {"SC_DCACHE_TBLKSZ", _SC_DCACHE_TBLKSZ}, + {"SC_DCACHE_TBLKSZ", _SC_DCACHE_TBLKSZ}, #endif #ifdef _SC_DELAYTIMER_MAX - {"SC_DELAYTIMER_MAX", _SC_DELAYTIMER_MAX}, + {"SC_DELAYTIMER_MAX", _SC_DELAYTIMER_MAX}, #endif #ifdef _SC_EQUIV_CLASS_MAX - {"SC_EQUIV_CLASS_MAX", _SC_EQUIV_CLASS_MAX}, + {"SC_EQUIV_CLASS_MAX", _SC_EQUIV_CLASS_MAX}, #endif #ifdef _SC_EXPR_NEST_MAX - {"SC_EXPR_NEST_MAX", _SC_EXPR_NEST_MAX}, + {"SC_EXPR_NEST_MAX", _SC_EXPR_NEST_MAX}, #endif #ifdef _SC_FSYNC - {"SC_FSYNC", _SC_FSYNC}, + {"SC_FSYNC", _SC_FSYNC}, #endif #ifdef _SC_GETGR_R_SIZE_MAX - {"SC_GETGR_R_SIZE_MAX", _SC_GETGR_R_SIZE_MAX}, + {"SC_GETGR_R_SIZE_MAX", _SC_GETGR_R_SIZE_MAX}, #endif #ifdef _SC_GETPW_R_SIZE_MAX - {"SC_GETPW_R_SIZE_MAX", _SC_GETPW_R_SIZE_MAX}, + {"SC_GETPW_R_SIZE_MAX", _SC_GETPW_R_SIZE_MAX}, #endif #ifdef _SC_ICACHE_ASSOC - {"SC_ICACHE_ASSOC", _SC_ICACHE_ASSOC}, + {"SC_ICACHE_ASSOC", _SC_ICACHE_ASSOC}, #endif #ifdef _SC_ICACHE_BLKSZ - {"SC_ICACHE_BLKSZ", _SC_ICACHE_BLKSZ}, + {"SC_ICACHE_BLKSZ", _SC_ICACHE_BLKSZ}, #endif #ifdef _SC_ICACHE_LINESZ - {"SC_ICACHE_LINESZ", _SC_ICACHE_LINESZ}, + {"SC_ICACHE_LINESZ", _SC_ICACHE_LINESZ}, #endif #ifdef _SC_ICACHE_SZ - {"SC_ICACHE_SZ", _SC_ICACHE_SZ}, + {"SC_ICACHE_SZ", _SC_ICACHE_SZ}, #endif #ifdef _SC_INF - {"SC_INF", _SC_INF}, + {"SC_INF", _SC_INF}, #endif #ifdef _SC_INT_MAX - {"SC_INT_MAX", _SC_INT_MAX}, + {"SC_INT_MAX", _SC_INT_MAX}, #endif #ifdef _SC_INT_MIN - {"SC_INT_MIN", _SC_INT_MIN}, + {"SC_INT_MIN", _SC_INT_MIN}, #endif #ifdef _SC_IOV_MAX - {"SC_IOV_MAX", _SC_IOV_MAX}, + {"SC_IOV_MAX", _SC_IOV_MAX}, #endif #ifdef _SC_IP_SECOPTS - {"SC_IP_SECOPTS", _SC_IP_SECOPTS}, + {"SC_IP_SECOPTS", _SC_IP_SECOPTS}, #endif #ifdef _SC_JOB_CONTROL - {"SC_JOB_CONTROL", _SC_JOB_CONTROL}, + {"SC_JOB_CONTROL", _SC_JOB_CONTROL}, #endif #ifdef _SC_KERN_POINTERS - {"SC_KERN_POINTERS", _SC_KERN_POINTERS}, + {"SC_KERN_POINTERS", _SC_KERN_POINTERS}, #endif #ifdef _SC_KERN_SIM - {"SC_KERN_SIM", _SC_KERN_SIM}, + {"SC_KERN_SIM", _SC_KERN_SIM}, #endif #ifdef _SC_LINE_MAX - {"SC_LINE_MAX", _SC_LINE_MAX}, + {"SC_LINE_MAX", _SC_LINE_MAX}, #endif #ifdef _SC_LOGIN_NAME_MAX - {"SC_LOGIN_NAME_MAX", _SC_LOGIN_NAME_MAX}, + {"SC_LOGIN_NAME_MAX", _SC_LOGIN_NAME_MAX}, #endif #ifdef _SC_LOGNAME_MAX - {"SC_LOGNAME_MAX", _SC_LOGNAME_MAX}, + {"SC_LOGNAME_MAX", _SC_LOGNAME_MAX}, #endif #ifdef _SC_LONG_BIT - {"SC_LONG_BIT", _SC_LONG_BIT}, + {"SC_LONG_BIT", _SC_LONG_BIT}, #endif #ifdef _SC_MAC - {"SC_MAC", _SC_MAC}, + {"SC_MAC", _SC_MAC}, #endif #ifdef _SC_MAPPED_FILES - {"SC_MAPPED_FILES", _SC_MAPPED_FILES}, + {"SC_MAPPED_FILES", _SC_MAPPED_FILES}, #endif #ifdef _SC_MAXPID - {"SC_MAXPID", _SC_MAXPID}, + {"SC_MAXPID", _SC_MAXPID}, #endif #ifdef _SC_MB_LEN_MAX - {"SC_MB_LEN_MAX", _SC_MB_LEN_MAX}, + {"SC_MB_LEN_MAX", _SC_MB_LEN_MAX}, #endif #ifdef _SC_MEMLOCK - {"SC_MEMLOCK", _SC_MEMLOCK}, + {"SC_MEMLOCK", _SC_MEMLOCK}, #endif #ifdef _SC_MEMLOCK_RANGE - {"SC_MEMLOCK_RANGE", _SC_MEMLOCK_RANGE}, + {"SC_MEMLOCK_RANGE", _SC_MEMLOCK_RANGE}, #endif #ifdef _SC_MEMORY_PROTECTION - {"SC_MEMORY_PROTECTION", _SC_MEMORY_PROTECTION}, + {"SC_MEMORY_PROTECTION", _SC_MEMORY_PROTECTION}, #endif #ifdef _SC_MESSAGE_PASSING - {"SC_MESSAGE_PASSING", _SC_MESSAGE_PASSING}, + {"SC_MESSAGE_PASSING", _SC_MESSAGE_PASSING}, #endif #ifdef _SC_MMAP_FIXED_ALIGNMENT - {"SC_MMAP_FIXED_ALIGNMENT", _SC_MMAP_FIXED_ALIGNMENT}, + {"SC_MMAP_FIXED_ALIGNMENT", _SC_MMAP_FIXED_ALIGNMENT}, #endif #ifdef _SC_MQ_OPEN_MAX - {"SC_MQ_OPEN_MAX", _SC_MQ_OPEN_MAX}, + {"SC_MQ_OPEN_MAX", _SC_MQ_OPEN_MAX}, #endif #ifdef _SC_MQ_PRIO_MAX - {"SC_MQ_PRIO_MAX", _SC_MQ_PRIO_MAX}, + {"SC_MQ_PRIO_MAX", _SC_MQ_PRIO_MAX}, #endif #ifdef _SC_NACLS_MAX - {"SC_NACLS_MAX", _SC_NACLS_MAX}, + {"SC_NACLS_MAX", _SC_NACLS_MAX}, #endif #ifdef _SC_NGROUPS_MAX - {"SC_NGROUPS_MAX", _SC_NGROUPS_MAX}, + {"SC_NGROUPS_MAX", _SC_NGROUPS_MAX}, #endif #ifdef _SC_NL_ARGMAX - {"SC_NL_ARGMAX", _SC_NL_ARGMAX}, + {"SC_NL_ARGMAX", _SC_NL_ARGMAX}, #endif #ifdef _SC_NL_LANGMAX - {"SC_NL_LANGMAX", _SC_NL_LANGMAX}, + {"SC_NL_LANGMAX", _SC_NL_LANGMAX}, #endif #ifdef _SC_NL_MSGMAX - {"SC_NL_MSGMAX", _SC_NL_MSGMAX}, + {"SC_NL_MSGMAX", _SC_NL_MSGMAX}, #endif #ifdef _SC_NL_NMAX - {"SC_NL_NMAX", _SC_NL_NMAX}, + {"SC_NL_NMAX", _SC_NL_NMAX}, #endif #ifdef _SC_NL_SETMAX - {"SC_NL_SETMAX", _SC_NL_SETMAX}, + {"SC_NL_SETMAX", _SC_NL_SETMAX}, #endif #ifdef _SC_NL_TEXTMAX - {"SC_NL_TEXTMAX", _SC_NL_TEXTMAX}, + {"SC_NL_TEXTMAX", _SC_NL_TEXTMAX}, #endif #ifdef _SC_NPROCESSORS_CONF - {"SC_NPROCESSORS_CONF", _SC_NPROCESSORS_CONF}, + {"SC_NPROCESSORS_CONF", _SC_NPROCESSORS_CONF}, #endif #ifdef _SC_NPROCESSORS_ONLN - {"SC_NPROCESSORS_ONLN", _SC_NPROCESSORS_ONLN}, + {"SC_NPROCESSORS_ONLN", _SC_NPROCESSORS_ONLN}, #endif #ifdef _SC_NPROC_CONF - {"SC_NPROC_CONF", _SC_NPROC_CONF}, + {"SC_NPROC_CONF", _SC_NPROC_CONF}, #endif #ifdef _SC_NPROC_ONLN - {"SC_NPROC_ONLN", _SC_NPROC_ONLN}, + {"SC_NPROC_ONLN", _SC_NPROC_ONLN}, #endif #ifdef _SC_NZERO - {"SC_NZERO", _SC_NZERO}, + {"SC_NZERO", _SC_NZERO}, #endif #ifdef _SC_OPEN_MAX - {"SC_OPEN_MAX", _SC_OPEN_MAX}, + {"SC_OPEN_MAX", _SC_OPEN_MAX}, #endif #ifdef _SC_PAGESIZE - {"SC_PAGESIZE", _SC_PAGESIZE}, + {"SC_PAGESIZE", _SC_PAGESIZE}, #endif #ifdef _SC_PAGE_SIZE - {"SC_PAGE_SIZE", _SC_PAGE_SIZE}, + {"SC_PAGE_SIZE", _SC_PAGE_SIZE}, #endif #ifdef _SC_PASS_MAX - {"SC_PASS_MAX", _SC_PASS_MAX}, + {"SC_PASS_MAX", _SC_PASS_MAX}, #endif #ifdef _SC_PHYS_PAGES - {"SC_PHYS_PAGES", _SC_PHYS_PAGES}, + {"SC_PHYS_PAGES", _SC_PHYS_PAGES}, #endif #ifdef _SC_PII - {"SC_PII", _SC_PII}, + {"SC_PII", _SC_PII}, #endif #ifdef _SC_PII_INTERNET - {"SC_PII_INTERNET", _SC_PII_INTERNET}, + {"SC_PII_INTERNET", _SC_PII_INTERNET}, #endif #ifdef _SC_PII_INTERNET_DGRAM - {"SC_PII_INTERNET_DGRAM", _SC_PII_INTERNET_DGRAM}, + {"SC_PII_INTERNET_DGRAM", _SC_PII_INTERNET_DGRAM}, #endif #ifdef _SC_PII_INTERNET_STREAM - {"SC_PII_INTERNET_STREAM", _SC_PII_INTERNET_STREAM}, + {"SC_PII_INTERNET_STREAM", _SC_PII_INTERNET_STREAM}, #endif #ifdef _SC_PII_OSI - {"SC_PII_OSI", _SC_PII_OSI}, + {"SC_PII_OSI", _SC_PII_OSI}, #endif #ifdef _SC_PII_OSI_CLTS - {"SC_PII_OSI_CLTS", _SC_PII_OSI_CLTS}, + {"SC_PII_OSI_CLTS", _SC_PII_OSI_CLTS}, #endif #ifdef _SC_PII_OSI_COTS - {"SC_PII_OSI_COTS", _SC_PII_OSI_COTS}, + {"SC_PII_OSI_COTS", _SC_PII_OSI_COTS}, #endif #ifdef _SC_PII_OSI_M - {"SC_PII_OSI_M", _SC_PII_OSI_M}, + {"SC_PII_OSI_M", _SC_PII_OSI_M}, #endif #ifdef _SC_PII_SOCKET - {"SC_PII_SOCKET", _SC_PII_SOCKET}, + {"SC_PII_SOCKET", _SC_PII_SOCKET}, #endif #ifdef _SC_PII_XTI - {"SC_PII_XTI", _SC_PII_XTI}, + {"SC_PII_XTI", _SC_PII_XTI}, #endif #ifdef _SC_POLL - {"SC_POLL", _SC_POLL}, + {"SC_POLL", _SC_POLL}, #endif #ifdef _SC_PRIORITIZED_IO - {"SC_PRIORITIZED_IO", _SC_PRIORITIZED_IO}, + {"SC_PRIORITIZED_IO", _SC_PRIORITIZED_IO}, #endif #ifdef _SC_PRIORITY_SCHEDULING - {"SC_PRIORITY_SCHEDULING", _SC_PRIORITY_SCHEDULING}, + {"SC_PRIORITY_SCHEDULING", _SC_PRIORITY_SCHEDULING}, #endif #ifdef _SC_REALTIME_SIGNALS - {"SC_REALTIME_SIGNALS", _SC_REALTIME_SIGNALS}, + {"SC_REALTIME_SIGNALS", _SC_REALTIME_SIGNALS}, #endif #ifdef _SC_RE_DUP_MAX - {"SC_RE_DUP_MAX", _SC_RE_DUP_MAX}, + {"SC_RE_DUP_MAX", _SC_RE_DUP_MAX}, #endif #ifdef _SC_RTSIG_MAX - {"SC_RTSIG_MAX", _SC_RTSIG_MAX}, + {"SC_RTSIG_MAX", _SC_RTSIG_MAX}, #endif #ifdef _SC_SAVED_IDS - {"SC_SAVED_IDS", _SC_SAVED_IDS}, + {"SC_SAVED_IDS", _SC_SAVED_IDS}, #endif #ifdef _SC_SCHAR_MAX - {"SC_SCHAR_MAX", _SC_SCHAR_MAX}, + {"SC_SCHAR_MAX", _SC_SCHAR_MAX}, #endif #ifdef _SC_SCHAR_MIN - {"SC_SCHAR_MIN", _SC_SCHAR_MIN}, + {"SC_SCHAR_MIN", _SC_SCHAR_MIN}, #endif #ifdef _SC_SELECT - {"SC_SELECT", _SC_SELECT}, + {"SC_SELECT", _SC_SELECT}, #endif #ifdef _SC_SEMAPHORES - {"SC_SEMAPHORES", _SC_SEMAPHORES}, + {"SC_SEMAPHORES", _SC_SEMAPHORES}, #endif #ifdef _SC_SEM_NSEMS_MAX - {"SC_SEM_NSEMS_MAX", _SC_SEM_NSEMS_MAX}, + {"SC_SEM_NSEMS_MAX", _SC_SEM_NSEMS_MAX}, #endif #ifdef _SC_SEM_VALUE_MAX - {"SC_SEM_VALUE_MAX", _SC_SEM_VALUE_MAX}, + {"SC_SEM_VALUE_MAX", _SC_SEM_VALUE_MAX}, #endif #ifdef _SC_SHARED_MEMORY_OBJECTS - {"SC_SHARED_MEMORY_OBJECTS", _SC_SHARED_MEMORY_OBJECTS}, + {"SC_SHARED_MEMORY_OBJECTS", _SC_SHARED_MEMORY_OBJECTS}, #endif #ifdef _SC_SHRT_MAX - {"SC_SHRT_MAX", _SC_SHRT_MAX}, + {"SC_SHRT_MAX", _SC_SHRT_MAX}, #endif #ifdef _SC_SHRT_MIN - {"SC_SHRT_MIN", _SC_SHRT_MIN}, + {"SC_SHRT_MIN", _SC_SHRT_MIN}, #endif #ifdef _SC_SIGQUEUE_MAX - {"SC_SIGQUEUE_MAX", _SC_SIGQUEUE_MAX}, + {"SC_SIGQUEUE_MAX", _SC_SIGQUEUE_MAX}, #endif #ifdef _SC_SIGRT_MAX - {"SC_SIGRT_MAX", _SC_SIGRT_MAX}, + {"SC_SIGRT_MAX", _SC_SIGRT_MAX}, #endif #ifdef _SC_SIGRT_MIN - {"SC_SIGRT_MIN", _SC_SIGRT_MIN}, + {"SC_SIGRT_MIN", _SC_SIGRT_MIN}, #endif #ifdef _SC_SOFTPOWER - {"SC_SOFTPOWER", _SC_SOFTPOWER}, + {"SC_SOFTPOWER", _SC_SOFTPOWER}, #endif #ifdef _SC_SPLIT_CACHE - {"SC_SPLIT_CACHE", _SC_SPLIT_CACHE}, + {"SC_SPLIT_CACHE", _SC_SPLIT_CACHE}, #endif #ifdef _SC_SSIZE_MAX - {"SC_SSIZE_MAX", _SC_SSIZE_MAX}, + {"SC_SSIZE_MAX", _SC_SSIZE_MAX}, #endif #ifdef _SC_STACK_PROT - {"SC_STACK_PROT", _SC_STACK_PROT}, + {"SC_STACK_PROT", _SC_STACK_PROT}, #endif #ifdef _SC_STREAM_MAX - {"SC_STREAM_MAX", _SC_STREAM_MAX}, + {"SC_STREAM_MAX", _SC_STREAM_MAX}, #endif #ifdef _SC_SYNCHRONIZED_IO - {"SC_SYNCHRONIZED_IO", _SC_SYNCHRONIZED_IO}, + {"SC_SYNCHRONIZED_IO", _SC_SYNCHRONIZED_IO}, #endif #ifdef _SC_THREADS - {"SC_THREADS", _SC_THREADS}, + {"SC_THREADS", _SC_THREADS}, #endif #ifdef _SC_THREAD_ATTR_STACKADDR - {"SC_THREAD_ATTR_STACKADDR", _SC_THREAD_ATTR_STACKADDR}, + {"SC_THREAD_ATTR_STACKADDR", _SC_THREAD_ATTR_STACKADDR}, #endif #ifdef _SC_THREAD_ATTR_STACKSIZE - {"SC_THREAD_ATTR_STACKSIZE", _SC_THREAD_ATTR_STACKSIZE}, + {"SC_THREAD_ATTR_STACKSIZE", _SC_THREAD_ATTR_STACKSIZE}, #endif #ifdef _SC_THREAD_DESTRUCTOR_ITERATIONS - {"SC_THREAD_DESTRUCTOR_ITERATIONS", _SC_THREAD_DESTRUCTOR_ITERATIONS}, + {"SC_THREAD_DESTRUCTOR_ITERATIONS", _SC_THREAD_DESTRUCTOR_ITERATIONS}, #endif #ifdef _SC_THREAD_KEYS_MAX - {"SC_THREAD_KEYS_MAX", _SC_THREAD_KEYS_MAX}, + {"SC_THREAD_KEYS_MAX", _SC_THREAD_KEYS_MAX}, #endif #ifdef _SC_THREAD_PRIORITY_SCHEDULING - {"SC_THREAD_PRIORITY_SCHEDULING", _SC_THREAD_PRIORITY_SCHEDULING}, + {"SC_THREAD_PRIORITY_SCHEDULING", _SC_THREAD_PRIORITY_SCHEDULING}, #endif #ifdef _SC_THREAD_PRIO_INHERIT - {"SC_THREAD_PRIO_INHERIT", _SC_THREAD_PRIO_INHERIT}, + {"SC_THREAD_PRIO_INHERIT", _SC_THREAD_PRIO_INHERIT}, #endif #ifdef _SC_THREAD_PRIO_PROTECT - {"SC_THREAD_PRIO_PROTECT", _SC_THREAD_PRIO_PROTECT}, + {"SC_THREAD_PRIO_PROTECT", _SC_THREAD_PRIO_PROTECT}, #endif #ifdef _SC_THREAD_PROCESS_SHARED - {"SC_THREAD_PROCESS_SHARED", _SC_THREAD_PROCESS_SHARED}, + {"SC_THREAD_PROCESS_SHARED", _SC_THREAD_PROCESS_SHARED}, #endif #ifdef _SC_THREAD_SAFE_FUNCTIONS - {"SC_THREAD_SAFE_FUNCTIONS", _SC_THREAD_SAFE_FUNCTIONS}, + {"SC_THREAD_SAFE_FUNCTIONS", _SC_THREAD_SAFE_FUNCTIONS}, #endif #ifdef _SC_THREAD_STACK_MIN - {"SC_THREAD_STACK_MIN", _SC_THREAD_STACK_MIN}, + {"SC_THREAD_STACK_MIN", _SC_THREAD_STACK_MIN}, #endif #ifdef _SC_THREAD_THREADS_MAX - {"SC_THREAD_THREADS_MAX", _SC_THREAD_THREADS_MAX}, + {"SC_THREAD_THREADS_MAX", _SC_THREAD_THREADS_MAX}, #endif #ifdef _SC_TIMERS - {"SC_TIMERS", _SC_TIMERS}, + {"SC_TIMERS", _SC_TIMERS}, #endif #ifdef _SC_TIMER_MAX - {"SC_TIMER_MAX", _SC_TIMER_MAX}, + {"SC_TIMER_MAX", _SC_TIMER_MAX}, #endif #ifdef _SC_TTY_NAME_MAX - {"SC_TTY_NAME_MAX", _SC_TTY_NAME_MAX}, + {"SC_TTY_NAME_MAX", _SC_TTY_NAME_MAX}, #endif #ifdef _SC_TZNAME_MAX - {"SC_TZNAME_MAX", _SC_TZNAME_MAX}, + {"SC_TZNAME_MAX", _SC_TZNAME_MAX}, #endif #ifdef _SC_T_IOV_MAX - {"SC_T_IOV_MAX", _SC_T_IOV_MAX}, + {"SC_T_IOV_MAX", _SC_T_IOV_MAX}, #endif #ifdef _SC_UCHAR_MAX - {"SC_UCHAR_MAX", _SC_UCHAR_MAX}, + {"SC_UCHAR_MAX", _SC_UCHAR_MAX}, #endif #ifdef _SC_UINT_MAX - {"SC_UINT_MAX", _SC_UINT_MAX}, + {"SC_UINT_MAX", _SC_UINT_MAX}, #endif #ifdef _SC_UIO_MAXIOV - {"SC_UIO_MAXIOV", _SC_UIO_MAXIOV}, + {"SC_UIO_MAXIOV", _SC_UIO_MAXIOV}, #endif #ifdef _SC_ULONG_MAX - {"SC_ULONG_MAX", _SC_ULONG_MAX}, + {"SC_ULONG_MAX", _SC_ULONG_MAX}, #endif #ifdef _SC_USHRT_MAX - {"SC_USHRT_MAX", _SC_USHRT_MAX}, + {"SC_USHRT_MAX", _SC_USHRT_MAX}, #endif #ifdef _SC_VERSION - {"SC_VERSION", _SC_VERSION}, + {"SC_VERSION", _SC_VERSION}, #endif #ifdef _SC_WORD_BIT - {"SC_WORD_BIT", _SC_WORD_BIT}, + {"SC_WORD_BIT", _SC_WORD_BIT}, #endif #ifdef _SC_XBS5_ILP32_OFF32 - {"SC_XBS5_ILP32_OFF32", _SC_XBS5_ILP32_OFF32}, + {"SC_XBS5_ILP32_OFF32", _SC_XBS5_ILP32_OFF32}, #endif #ifdef _SC_XBS5_ILP32_OFFBIG - {"SC_XBS5_ILP32_OFFBIG", _SC_XBS5_ILP32_OFFBIG}, + {"SC_XBS5_ILP32_OFFBIG", _SC_XBS5_ILP32_OFFBIG}, #endif #ifdef _SC_XBS5_LP64_OFF64 - {"SC_XBS5_LP64_OFF64", _SC_XBS5_LP64_OFF64}, + {"SC_XBS5_LP64_OFF64", _SC_XBS5_LP64_OFF64}, #endif #ifdef _SC_XBS5_LPBIG_OFFBIG - {"SC_XBS5_LPBIG_OFFBIG", _SC_XBS5_LPBIG_OFFBIG}, + {"SC_XBS5_LPBIG_OFFBIG", _SC_XBS5_LPBIG_OFFBIG}, #endif #ifdef _SC_XOPEN_CRYPT - {"SC_XOPEN_CRYPT", _SC_XOPEN_CRYPT}, + {"SC_XOPEN_CRYPT", _SC_XOPEN_CRYPT}, #endif #ifdef _SC_XOPEN_ENH_I18N - {"SC_XOPEN_ENH_I18N", _SC_XOPEN_ENH_I18N}, + {"SC_XOPEN_ENH_I18N", _SC_XOPEN_ENH_I18N}, #endif #ifdef _SC_XOPEN_LEGACY - {"SC_XOPEN_LEGACY", _SC_XOPEN_LEGACY}, + {"SC_XOPEN_LEGACY", _SC_XOPEN_LEGACY}, #endif #ifdef _SC_XOPEN_REALTIME - {"SC_XOPEN_REALTIME", _SC_XOPEN_REALTIME}, + {"SC_XOPEN_REALTIME", _SC_XOPEN_REALTIME}, #endif #ifdef _SC_XOPEN_REALTIME_THREADS - {"SC_XOPEN_REALTIME_THREADS", _SC_XOPEN_REALTIME_THREADS}, + {"SC_XOPEN_REALTIME_THREADS", _SC_XOPEN_REALTIME_THREADS}, #endif #ifdef _SC_XOPEN_SHM - {"SC_XOPEN_SHM", _SC_XOPEN_SHM}, + {"SC_XOPEN_SHM", _SC_XOPEN_SHM}, #endif #ifdef _SC_XOPEN_UNIX - {"SC_XOPEN_UNIX", _SC_XOPEN_UNIX}, + {"SC_XOPEN_UNIX", _SC_XOPEN_UNIX}, #endif #ifdef _SC_XOPEN_VERSION - {"SC_XOPEN_VERSION", _SC_XOPEN_VERSION}, + {"SC_XOPEN_VERSION", _SC_XOPEN_VERSION}, #endif #ifdef _SC_XOPEN_XCU_VERSION - {"SC_XOPEN_XCU_VERSION", _SC_XOPEN_XCU_VERSION}, + {"SC_XOPEN_XCU_VERSION", _SC_XOPEN_XCU_VERSION}, #endif #ifdef _SC_XOPEN_XPG2 - {"SC_XOPEN_XPG2", _SC_XOPEN_XPG2}, + {"SC_XOPEN_XPG2", _SC_XOPEN_XPG2}, #endif #ifdef _SC_XOPEN_XPG3 - {"SC_XOPEN_XPG3", _SC_XOPEN_XPG3}, + {"SC_XOPEN_XPG3", _SC_XOPEN_XPG3}, #endif #ifdef _SC_XOPEN_XPG4 - {"SC_XOPEN_XPG4", _SC_XOPEN_XPG4}, + {"SC_XOPEN_XPG4", _SC_XOPEN_XPG4}, #endif }; @@ -6692,16 +6693,16 @@ cmp_constdefs(const void *v1, const void *v2) { const struct constdef *c1 = - (const struct constdef *) v1; + (const struct constdef *) v1; const struct constdef *c2 = - (const struct constdef *) v2; + (const struct constdef *) v2; return strcmp(c1->name, c2->name); } static int setup_confname_table(struct constdef *table, size_t tablesize, - char *tablename, PyObject *module) + char *tablename, PyObject *module) { PyObject *d = NULL; size_t i; @@ -6709,16 +6710,16 @@ qsort(table, tablesize, sizeof(struct constdef), cmp_constdefs); d = PyDict_New(); if (d == NULL) - return -1; + return -1; for (i=0; i < tablesize; ++i) { - PyObject *o = PyLong_FromLong(table[i].value); - if (o == NULL || PyDict_SetItemString(d, table[i].name, o) == -1) { - Py_XDECREF(o); - Py_DECREF(d); - return -1; - } - Py_DECREF(o); + PyObject *o = PyLong_FromLong(table[i].value); + if (o == NULL || PyDict_SetItemString(d, table[i].name, o) == -1) { + Py_XDECREF(o); + Py_DECREF(d); + return -1; + } + Py_DECREF(o); } return PyModule_AddObject(module, tablename, d); } @@ -6732,21 +6733,21 @@ sizeof(posix_constants_pathconf) / sizeof(struct constdef), "pathconf_names", module)) - return -1; + return -1; #endif #ifdef HAVE_CONFSTR if (setup_confname_table(posix_constants_confstr, sizeof(posix_constants_confstr) / sizeof(struct constdef), "confstr_names", module)) - return -1; + return -1; #endif #ifdef HAVE_SYSCONF if (setup_confname_table(posix_constants_sysconf, sizeof(posix_constants_sysconf) / sizeof(struct constdef), "sysconf_names", module)) - return -1; + return -1; #endif return 0; } @@ -6789,64 +6790,64 @@ static PyObject * win32_startfile(PyObject *self, PyObject *args) { - PyObject *ofilepath; - char *filepath; - char *operation = NULL; - HINSTANCE rc; - - if (unicode_file_names()) { - PyObject *unipath, *woperation = NULL; - if (!PyArg_ParseTuple(args, "U|s:startfile", - &unipath, &operation)) { - PyErr_Clear(); - goto normal; - } - - - if (operation) { - woperation = PyUnicode_DecodeASCII(operation, - strlen(operation), NULL); - if (!woperation) { - PyErr_Clear(); - operation = NULL; - goto normal; - } - } - - Py_BEGIN_ALLOW_THREADS - rc = ShellExecuteW((HWND)0, woperation ? PyUnicode_AS_UNICODE(woperation) : 0, - PyUnicode_AS_UNICODE(unipath), - NULL, NULL, SW_SHOWNORMAL); - Py_END_ALLOW_THREADS - - Py_XDECREF(woperation); - if (rc <= (HINSTANCE)32) { - PyObject *errval = win32_error_unicode("startfile", - PyUnicode_AS_UNICODE(unipath)); - return errval; - } - Py_INCREF(Py_None); - return Py_None; - } + PyObject *ofilepath; + char *filepath; + char *operation = NULL; + HINSTANCE rc; + + if (unicode_file_names()) { + PyObject *unipath, *woperation = NULL; + if (!PyArg_ParseTuple(args, "U|s:startfile", + &unipath, &operation)) { + PyErr_Clear(); + goto normal; + } + + + if (operation) { + woperation = PyUnicode_DecodeASCII(operation, + strlen(operation), NULL); + if (!woperation) { + PyErr_Clear(); + operation = NULL; + goto normal; + } + } + + Py_BEGIN_ALLOW_THREADS + rc = ShellExecuteW((HWND)0, woperation ? PyUnicode_AS_UNICODE(woperation) : 0, + PyUnicode_AS_UNICODE(unipath), + NULL, NULL, SW_SHOWNORMAL); + Py_END_ALLOW_THREADS + + Py_XDECREF(woperation); + if (rc <= (HINSTANCE)32) { + PyObject *errval = win32_error_unicode("startfile", + PyUnicode_AS_UNICODE(unipath)); + return errval; + } + Py_INCREF(Py_None); + return Py_None; + } normal: - if (!PyArg_ParseTuple(args, "O&|s:startfile", - PyUnicode_FSConverter, &ofilepath, - &operation)) - return NULL; - filepath = bytes2str(ofilepath, 1); - Py_BEGIN_ALLOW_THREADS - rc = ShellExecute((HWND)0, operation, filepath, - NULL, NULL, SW_SHOWNORMAL); - Py_END_ALLOW_THREADS - if (rc <= (HINSTANCE)32) { - PyObject *errval = win32_error("startfile", filepath); - release_bytes(ofilepath); - return errval; - } - release_bytes(ofilepath); - Py_INCREF(Py_None); - return Py_None; + if (!PyArg_ParseTuple(args, "O&|s:startfile", + PyUnicode_FSConverter, &ofilepath, + &operation)) + return NULL; + filepath = bytes2str(ofilepath, 1); + Py_BEGIN_ALLOW_THREADS + rc = ShellExecute((HWND)0, operation, filepath, + NULL, NULL, SW_SHOWNORMAL); + Py_END_ALLOW_THREADS + if (rc <= (HINSTANCE)32) { + PyObject *errval = win32_error("startfile", filepath); + release_bytes(ofilepath); + return errval; + } + release_bytes(ofilepath); + Py_INCREF(Py_None); + return Py_None; } #endif @@ -6862,10 +6863,10 @@ { double loadavg[3]; if (getloadavg(loadavg, 3)!=3) { - PyErr_SetString(PyExc_OSError, "Load averages are unobtainable"); - return NULL; + PyErr_SetString(PyExc_OSError, "Load averages are unobtainable"); + return NULL; } else - return Py_BuildValue("ddd", loadavg[0], loadavg[1], loadavg[2]); + return Py_BuildValue("ddd", loadavg[0], loadavg[1], loadavg[2]); } #endif @@ -6889,59 +6890,59 @@ static PyObject* win32_urandom(PyObject *self, PyObject *args) { - int howMany; - PyObject* result; + int howMany; + PyObject* result; + + /* Read arguments */ + if (! PyArg_ParseTuple(args, "i:urandom", &howMany)) + return NULL; + if (howMany < 0) + return PyErr_Format(PyExc_ValueError, + "negative argument not allowed"); + + if (hCryptProv == 0) { + HINSTANCE hAdvAPI32 = NULL; + CRYPTACQUIRECONTEXTA pCryptAcquireContext = NULL; + + /* Obtain handle to the DLL containing CryptoAPI + This should not fail */ + hAdvAPI32 = GetModuleHandle("advapi32.dll"); + if(hAdvAPI32 == NULL) + return win32_error("GetModuleHandle", NULL); + + /* Obtain pointers to the CryptoAPI functions + This will fail on some early versions of Win95 */ + pCryptAcquireContext = (CRYPTACQUIRECONTEXTA)GetProcAddress( + hAdvAPI32, + "CryptAcquireContextA"); + if (pCryptAcquireContext == NULL) + return PyErr_Format(PyExc_NotImplementedError, + "CryptAcquireContextA not found"); + + pCryptGenRandom = (CRYPTGENRANDOM)GetProcAddress( + hAdvAPI32, "CryptGenRandom"); + if (pCryptGenRandom == NULL) + return PyErr_Format(PyExc_NotImplementedError, + "CryptGenRandom not found"); + + /* Acquire context */ + if (! pCryptAcquireContext(&hCryptProv, NULL, NULL, + PROV_RSA_FULL, CRYPT_VERIFYCONTEXT)) + return win32_error("CryptAcquireContext", NULL); + } - /* Read arguments */ - if (! PyArg_ParseTuple(args, "i:urandom", &howMany)) - return NULL; - if (howMany < 0) - return PyErr_Format(PyExc_ValueError, - "negative argument not allowed"); - - if (hCryptProv == 0) { - HINSTANCE hAdvAPI32 = NULL; - CRYPTACQUIRECONTEXTA pCryptAcquireContext = NULL; - - /* Obtain handle to the DLL containing CryptoAPI - This should not fail */ - hAdvAPI32 = GetModuleHandle("advapi32.dll"); - if(hAdvAPI32 == NULL) - return win32_error("GetModuleHandle", NULL); - - /* Obtain pointers to the CryptoAPI functions - This will fail on some early versions of Win95 */ - pCryptAcquireContext = (CRYPTACQUIRECONTEXTA)GetProcAddress( - hAdvAPI32, - "CryptAcquireContextA"); - if (pCryptAcquireContext == NULL) - return PyErr_Format(PyExc_NotImplementedError, - "CryptAcquireContextA not found"); - - pCryptGenRandom = (CRYPTGENRANDOM)GetProcAddress( - hAdvAPI32, "CryptGenRandom"); - if (pCryptGenRandom == NULL) - return PyErr_Format(PyExc_NotImplementedError, - "CryptGenRandom not found"); - - /* Acquire context */ - if (! pCryptAcquireContext(&hCryptProv, NULL, NULL, - PROV_RSA_FULL, CRYPT_VERIFYCONTEXT)) - return win32_error("CryptAcquireContext", NULL); - } - - /* Allocate bytes */ - result = PyBytes_FromStringAndSize(NULL, howMany); - if (result != NULL) { - /* Get random data */ - memset(PyBytes_AS_STRING(result), 0, howMany); /* zero seed */ - if (! pCryptGenRandom(hCryptProv, howMany, (unsigned char*) - PyBytes_AS_STRING(result))) { - Py_DECREF(result); - return win32_error("CryptGenRandom", NULL); - } - } - return result; + /* Allocate bytes */ + result = PyBytes_FromStringAndSize(NULL, howMany); + if (result != NULL) { + /* Get random data */ + memset(PyBytes_AS_STRING(result), 0, howMany); /* zero seed */ + if (! pCryptGenRandom(hCryptProv, howMany, (unsigned char*) + PyBytes_AS_STRING(result))) { + Py_DECREF(result); + return win32_error("CryptGenRandom", NULL); + } + } + return result; } #endif @@ -6953,33 +6954,33 @@ static PyObject * device_encoding(PyObject *self, PyObject *args) { - int fd; - if (!PyArg_ParseTuple(args, "i:device_encoding", &fd)) - return NULL; - if (!_PyVerify_fd(fd) || !isatty(fd)) { - Py_INCREF(Py_None); - return Py_None; - } + int fd; + if (!PyArg_ParseTuple(args, "i:device_encoding", &fd)) + return NULL; + if (!_PyVerify_fd(fd) || !isatty(fd)) { + Py_INCREF(Py_None); + return Py_None; + } #if defined(MS_WINDOWS) || defined(MS_WIN64) - if (fd == 0) { - char buf[100]; - sprintf(buf, "cp%d", GetConsoleCP()); - return PyUnicode_FromString(buf); - } - if (fd == 1 || fd == 2) { - char buf[100]; - sprintf(buf, "cp%d", GetConsoleOutputCP()); - return PyUnicode_FromString(buf); - } + if (fd == 0) { + char buf[100]; + sprintf(buf, "cp%d", GetConsoleCP()); + return PyUnicode_FromString(buf); + } + if (fd == 1 || fd == 2) { + char buf[100]; + sprintf(buf, "cp%d", GetConsoleOutputCP()); + return PyUnicode_FromString(buf); + } #elif defined(CODESET) - { - char *codeset = nl_langinfo(CODESET); - if (codeset != NULL && codeset[0] != 0) - return PyUnicode_FromString(codeset); - } + { + char *codeset = nl_langinfo(CODESET); + if (codeset != NULL && codeset[0] != 0) + return PyUnicode_FromString(codeset); + } #endif - Py_INCREF(Py_None); - return Py_None; + Py_INCREF(Py_None); + return Py_None; } #ifdef __VMS @@ -6992,329 +6993,329 @@ static PyObject* vms_urandom(PyObject *self, PyObject *args) { - int howMany; - PyObject* result; + int howMany; + PyObject* result; - /* Read arguments */ - if (! PyArg_ParseTuple(args, "i:urandom", &howMany)) - return NULL; - if (howMany < 0) - return PyErr_Format(PyExc_ValueError, - "negative argument not allowed"); - - /* Allocate bytes */ - result = PyBytes_FromStringAndSize(NULL, howMany); - if (result != NULL) { - /* Get random data */ - if (RAND_pseudo_bytes((unsigned char*) - PyBytes_AS_STRING(result), - howMany) < 0) { - Py_DECREF(result); - return PyErr_Format(PyExc_ValueError, - "RAND_pseudo_bytes"); - } - } - return result; + /* Read arguments */ + if (! PyArg_ParseTuple(args, "i:urandom", &howMany)) + return NULL; + if (howMany < 0) + return PyErr_Format(PyExc_ValueError, + "negative argument not allowed"); + + /* Allocate bytes */ + result = PyBytes_FromStringAndSize(NULL, howMany); + if (result != NULL) { + /* Get random data */ + if (RAND_pseudo_bytes((unsigned char*) + PyBytes_AS_STRING(result), + howMany) < 0) { + Py_DECREF(result); + return PyErr_Format(PyExc_ValueError, + "RAND_pseudo_bytes"); + } + } + return result; } #endif static PyMethodDef posix_methods[] = { - {"access", posix_access, METH_VARARGS, posix_access__doc__}, + {"access", posix_access, METH_VARARGS, posix_access__doc__}, #ifdef HAVE_TTYNAME - {"ttyname", posix_ttyname, METH_VARARGS, posix_ttyname__doc__}, + {"ttyname", posix_ttyname, METH_VARARGS, posix_ttyname__doc__}, #endif - {"chdir", posix_chdir, METH_VARARGS, posix_chdir__doc__}, + {"chdir", posix_chdir, METH_VARARGS, posix_chdir__doc__}, #ifdef HAVE_CHFLAGS - {"chflags", posix_chflags, METH_VARARGS, posix_chflags__doc__}, + {"chflags", posix_chflags, METH_VARARGS, posix_chflags__doc__}, #endif /* HAVE_CHFLAGS */ - {"chmod", posix_chmod, METH_VARARGS, posix_chmod__doc__}, + {"chmod", posix_chmod, METH_VARARGS, posix_chmod__doc__}, #ifdef HAVE_FCHMOD - {"fchmod", posix_fchmod, METH_VARARGS, posix_fchmod__doc__}, + {"fchmod", posix_fchmod, METH_VARARGS, posix_fchmod__doc__}, #endif /* HAVE_FCHMOD */ #ifdef HAVE_CHOWN - {"chown", posix_chown, METH_VARARGS, posix_chown__doc__}, + {"chown", posix_chown, METH_VARARGS, posix_chown__doc__}, #endif /* HAVE_CHOWN */ #ifdef HAVE_LCHMOD - {"lchmod", posix_lchmod, METH_VARARGS, posix_lchmod__doc__}, + {"lchmod", posix_lchmod, METH_VARARGS, posix_lchmod__doc__}, #endif /* HAVE_LCHMOD */ #ifdef HAVE_FCHOWN - {"fchown", posix_fchown, METH_VARARGS, posix_fchown__doc__}, + {"fchown", posix_fchown, METH_VARARGS, posix_fchown__doc__}, #endif /* HAVE_FCHOWN */ #ifdef HAVE_LCHFLAGS - {"lchflags", posix_lchflags, METH_VARARGS, posix_lchflags__doc__}, + {"lchflags", posix_lchflags, METH_VARARGS, posix_lchflags__doc__}, #endif /* HAVE_LCHFLAGS */ #ifdef HAVE_LCHOWN - {"lchown", posix_lchown, METH_VARARGS, posix_lchown__doc__}, + {"lchown", posix_lchown, METH_VARARGS, posix_lchown__doc__}, #endif /* HAVE_LCHOWN */ #ifdef HAVE_CHROOT - {"chroot", posix_chroot, METH_VARARGS, posix_chroot__doc__}, + {"chroot", posix_chroot, METH_VARARGS, posix_chroot__doc__}, #endif #ifdef HAVE_CTERMID - {"ctermid", posix_ctermid, METH_NOARGS, posix_ctermid__doc__}, + {"ctermid", posix_ctermid, METH_NOARGS, posix_ctermid__doc__}, #endif #ifdef HAVE_GETCWD - {"getcwd", (PyCFunction)posix_getcwd_unicode, - METH_NOARGS, posix_getcwd__doc__}, - {"getcwdb", (PyCFunction)posix_getcwd_bytes, - METH_NOARGS, posix_getcwdb__doc__}, + {"getcwd", (PyCFunction)posix_getcwd_unicode, + METH_NOARGS, posix_getcwd__doc__}, + {"getcwdb", (PyCFunction)posix_getcwd_bytes, + METH_NOARGS, posix_getcwdb__doc__}, #endif #ifdef HAVE_LINK - {"link", posix_link, METH_VARARGS, posix_link__doc__}, + {"link", posix_link, METH_VARARGS, posix_link__doc__}, #endif /* HAVE_LINK */ - {"listdir", posix_listdir, METH_VARARGS, posix_listdir__doc__}, - {"lstat", posix_lstat, METH_VARARGS, posix_lstat__doc__}, - {"mkdir", posix_mkdir, METH_VARARGS, posix_mkdir__doc__}, + {"listdir", posix_listdir, METH_VARARGS, posix_listdir__doc__}, + {"lstat", posix_lstat, METH_VARARGS, posix_lstat__doc__}, + {"mkdir", posix_mkdir, METH_VARARGS, posix_mkdir__doc__}, #ifdef HAVE_NICE - {"nice", posix_nice, METH_VARARGS, posix_nice__doc__}, + {"nice", posix_nice, METH_VARARGS, posix_nice__doc__}, #endif /* HAVE_NICE */ #ifdef HAVE_READLINK - {"readlink", posix_readlink, METH_VARARGS, posix_readlink__doc__}, + {"readlink", posix_readlink, METH_VARARGS, posix_readlink__doc__}, #endif /* HAVE_READLINK */ - {"rename", posix_rename, METH_VARARGS, posix_rename__doc__}, - {"rmdir", posix_rmdir, METH_VARARGS, posix_rmdir__doc__}, - {"stat", posix_stat, METH_VARARGS, posix_stat__doc__}, - {"stat_float_times", stat_float_times, METH_VARARGS, stat_float_times__doc__}, + {"rename", posix_rename, METH_VARARGS, posix_rename__doc__}, + {"rmdir", posix_rmdir, METH_VARARGS, posix_rmdir__doc__}, + {"stat", posix_stat, METH_VARARGS, posix_stat__doc__}, + {"stat_float_times", stat_float_times, METH_VARARGS, stat_float_times__doc__}, #ifdef HAVE_SYMLINK - {"symlink", posix_symlink, METH_VARARGS, posix_symlink__doc__}, + {"symlink", posix_symlink, METH_VARARGS, posix_symlink__doc__}, #endif /* HAVE_SYMLINK */ #ifdef HAVE_SYSTEM - {"system", posix_system, METH_VARARGS, posix_system__doc__}, + {"system", posix_system, METH_VARARGS, posix_system__doc__}, #endif - {"umask", posix_umask, METH_VARARGS, posix_umask__doc__}, + {"umask", posix_umask, METH_VARARGS, posix_umask__doc__}, #ifdef HAVE_UNAME - {"uname", posix_uname, METH_NOARGS, posix_uname__doc__}, + {"uname", posix_uname, METH_NOARGS, posix_uname__doc__}, #endif /* HAVE_UNAME */ - {"unlink", posix_unlink, METH_VARARGS, posix_unlink__doc__}, - {"remove", posix_unlink, METH_VARARGS, posix_remove__doc__}, - {"utime", posix_utime, METH_VARARGS, posix_utime__doc__}, + {"unlink", posix_unlink, METH_VARARGS, posix_unlink__doc__}, + {"remove", posix_unlink, METH_VARARGS, posix_remove__doc__}, + {"utime", posix_utime, METH_VARARGS, posix_utime__doc__}, #ifdef HAVE_TIMES - {"times", posix_times, METH_NOARGS, posix_times__doc__}, + {"times", posix_times, METH_NOARGS, posix_times__doc__}, #endif /* HAVE_TIMES */ - {"_exit", posix__exit, METH_VARARGS, posix__exit__doc__}, + {"_exit", posix__exit, METH_VARARGS, posix__exit__doc__}, #ifdef HAVE_EXECV - {"execv", posix_execv, METH_VARARGS, posix_execv__doc__}, - {"execve", posix_execve, METH_VARARGS, posix_execve__doc__}, + {"execv", posix_execv, METH_VARARGS, posix_execv__doc__}, + {"execve", posix_execve, METH_VARARGS, posix_execve__doc__}, #endif /* HAVE_EXECV */ #ifdef HAVE_SPAWNV - {"spawnv", posix_spawnv, METH_VARARGS, posix_spawnv__doc__}, - {"spawnve", posix_spawnve, METH_VARARGS, posix_spawnve__doc__}, + {"spawnv", posix_spawnv, METH_VARARGS, posix_spawnv__doc__}, + {"spawnve", posix_spawnve, METH_VARARGS, posix_spawnve__doc__}, #if defined(PYOS_OS2) - {"spawnvp", posix_spawnvp, METH_VARARGS, posix_spawnvp__doc__}, - {"spawnvpe", posix_spawnvpe, METH_VARARGS, posix_spawnvpe__doc__}, + {"spawnvp", posix_spawnvp, METH_VARARGS, posix_spawnvp__doc__}, + {"spawnvpe", posix_spawnvpe, METH_VARARGS, posix_spawnvpe__doc__}, #endif /* PYOS_OS2 */ #endif /* HAVE_SPAWNV */ #ifdef HAVE_FORK1 - {"fork1", posix_fork1, METH_NOARGS, posix_fork1__doc__}, + {"fork1", posix_fork1, METH_NOARGS, posix_fork1__doc__}, #endif /* HAVE_FORK1 */ #ifdef HAVE_FORK - {"fork", posix_fork, METH_NOARGS, posix_fork__doc__}, + {"fork", posix_fork, METH_NOARGS, posix_fork__doc__}, #endif /* HAVE_FORK */ #if defined(HAVE_OPENPTY) || defined(HAVE__GETPTY) || defined(HAVE_DEV_PTMX) - {"openpty", posix_openpty, METH_NOARGS, posix_openpty__doc__}, + {"openpty", posix_openpty, METH_NOARGS, posix_openpty__doc__}, #endif /* HAVE_OPENPTY || HAVE__GETPTY || HAVE_DEV_PTMX */ #ifdef HAVE_FORKPTY - {"forkpty", posix_forkpty, METH_NOARGS, posix_forkpty__doc__}, + {"forkpty", posix_forkpty, METH_NOARGS, posix_forkpty__doc__}, #endif /* HAVE_FORKPTY */ #ifdef HAVE_GETEGID - {"getegid", posix_getegid, METH_NOARGS, posix_getegid__doc__}, + {"getegid", posix_getegid, METH_NOARGS, posix_getegid__doc__}, #endif /* HAVE_GETEGID */ #ifdef HAVE_GETEUID - {"geteuid", posix_geteuid, METH_NOARGS, posix_geteuid__doc__}, + {"geteuid", posix_geteuid, METH_NOARGS, posix_geteuid__doc__}, #endif /* HAVE_GETEUID */ #ifdef HAVE_GETGID - {"getgid", posix_getgid, METH_NOARGS, posix_getgid__doc__}, + {"getgid", posix_getgid, METH_NOARGS, posix_getgid__doc__}, #endif /* HAVE_GETGID */ #ifdef HAVE_GETGROUPS - {"getgroups", posix_getgroups, METH_NOARGS, posix_getgroups__doc__}, + {"getgroups", posix_getgroups, METH_NOARGS, posix_getgroups__doc__}, #endif - {"getpid", posix_getpid, METH_NOARGS, posix_getpid__doc__}, + {"getpid", posix_getpid, METH_NOARGS, posix_getpid__doc__}, #ifdef HAVE_GETPGRP - {"getpgrp", posix_getpgrp, METH_NOARGS, posix_getpgrp__doc__}, + {"getpgrp", posix_getpgrp, METH_NOARGS, posix_getpgrp__doc__}, #endif /* HAVE_GETPGRP */ #ifdef HAVE_GETPPID - {"getppid", posix_getppid, METH_NOARGS, posix_getppid__doc__}, + {"getppid", posix_getppid, METH_NOARGS, posix_getppid__doc__}, #endif /* HAVE_GETPPID */ #ifdef HAVE_GETUID - {"getuid", posix_getuid, METH_NOARGS, posix_getuid__doc__}, + {"getuid", posix_getuid, METH_NOARGS, posix_getuid__doc__}, #endif /* HAVE_GETUID */ #ifdef HAVE_GETLOGIN - {"getlogin", posix_getlogin, METH_NOARGS, posix_getlogin__doc__}, + {"getlogin", posix_getlogin, METH_NOARGS, posix_getlogin__doc__}, #endif #ifdef HAVE_KILL - {"kill", posix_kill, METH_VARARGS, posix_kill__doc__}, + {"kill", posix_kill, METH_VARARGS, posix_kill__doc__}, #endif /* HAVE_KILL */ #ifdef HAVE_KILLPG - {"killpg", posix_killpg, METH_VARARGS, posix_killpg__doc__}, + {"killpg", posix_killpg, METH_VARARGS, posix_killpg__doc__}, #endif /* HAVE_KILLPG */ #ifdef HAVE_PLOCK - {"plock", posix_plock, METH_VARARGS, posix_plock__doc__}, + {"plock", posix_plock, METH_VARARGS, posix_plock__doc__}, #endif /* HAVE_PLOCK */ #ifdef MS_WINDOWS - {"startfile", win32_startfile, METH_VARARGS, win32_startfile__doc__}, + {"startfile", win32_startfile, METH_VARARGS, win32_startfile__doc__}, #endif #ifdef HAVE_SETUID - {"setuid", posix_setuid, METH_VARARGS, posix_setuid__doc__}, + {"setuid", posix_setuid, METH_VARARGS, posix_setuid__doc__}, #endif /* HAVE_SETUID */ #ifdef HAVE_SETEUID - {"seteuid", posix_seteuid, METH_VARARGS, posix_seteuid__doc__}, + {"seteuid", posix_seteuid, METH_VARARGS, posix_seteuid__doc__}, #endif /* HAVE_SETEUID */ #ifdef HAVE_SETEGID - {"setegid", posix_setegid, METH_VARARGS, posix_setegid__doc__}, + {"setegid", posix_setegid, METH_VARARGS, posix_setegid__doc__}, #endif /* HAVE_SETEGID */ #ifdef HAVE_SETREUID - {"setreuid", posix_setreuid, METH_VARARGS, posix_setreuid__doc__}, + {"setreuid", posix_setreuid, METH_VARARGS, posix_setreuid__doc__}, #endif /* HAVE_SETREUID */ #ifdef HAVE_SETREGID - {"setregid", posix_setregid, METH_VARARGS, posix_setregid__doc__}, + {"setregid", posix_setregid, METH_VARARGS, posix_setregid__doc__}, #endif /* HAVE_SETREGID */ #ifdef HAVE_SETGID - {"setgid", posix_setgid, METH_VARARGS, posix_setgid__doc__}, + {"setgid", posix_setgid, METH_VARARGS, posix_setgid__doc__}, #endif /* HAVE_SETGID */ #ifdef HAVE_SETGROUPS - {"setgroups", posix_setgroups, METH_O, posix_setgroups__doc__}, + {"setgroups", posix_setgroups, METH_O, posix_setgroups__doc__}, #endif /* HAVE_SETGROUPS */ #ifdef HAVE_GETPGID - {"getpgid", posix_getpgid, METH_VARARGS, posix_getpgid__doc__}, + {"getpgid", posix_getpgid, METH_VARARGS, posix_getpgid__doc__}, #endif /* HAVE_GETPGID */ #ifdef HAVE_SETPGRP - {"setpgrp", posix_setpgrp, METH_NOARGS, posix_setpgrp__doc__}, + {"setpgrp", posix_setpgrp, METH_NOARGS, posix_setpgrp__doc__}, #endif /* HAVE_SETPGRP */ #ifdef HAVE_WAIT - {"wait", posix_wait, METH_NOARGS, posix_wait__doc__}, + {"wait", posix_wait, METH_NOARGS, posix_wait__doc__}, #endif /* HAVE_WAIT */ #ifdef HAVE_WAIT3 - {"wait3", posix_wait3, METH_VARARGS, posix_wait3__doc__}, + {"wait3", posix_wait3, METH_VARARGS, posix_wait3__doc__}, #endif /* HAVE_WAIT3 */ #ifdef HAVE_WAIT4 - {"wait4", posix_wait4, METH_VARARGS, posix_wait4__doc__}, + {"wait4", posix_wait4, METH_VARARGS, posix_wait4__doc__}, #endif /* HAVE_WAIT4 */ #if defined(HAVE_WAITPID) || defined(HAVE_CWAIT) - {"waitpid", posix_waitpid, METH_VARARGS, posix_waitpid__doc__}, + {"waitpid", posix_waitpid, METH_VARARGS, posix_waitpid__doc__}, #endif /* HAVE_WAITPID */ #ifdef HAVE_GETSID - {"getsid", posix_getsid, METH_VARARGS, posix_getsid__doc__}, + {"getsid", posix_getsid, METH_VARARGS, posix_getsid__doc__}, #endif /* HAVE_GETSID */ #ifdef HAVE_SETSID - {"setsid", posix_setsid, METH_NOARGS, posix_setsid__doc__}, + {"setsid", posix_setsid, METH_NOARGS, posix_setsid__doc__}, #endif /* HAVE_SETSID */ #ifdef HAVE_SETPGID - {"setpgid", posix_setpgid, METH_VARARGS, posix_setpgid__doc__}, + {"setpgid", posix_setpgid, METH_VARARGS, posix_setpgid__doc__}, #endif /* HAVE_SETPGID */ #ifdef HAVE_TCGETPGRP - {"tcgetpgrp", posix_tcgetpgrp, METH_VARARGS, posix_tcgetpgrp__doc__}, + {"tcgetpgrp", posix_tcgetpgrp, METH_VARARGS, posix_tcgetpgrp__doc__}, #endif /* HAVE_TCGETPGRP */ #ifdef HAVE_TCSETPGRP - {"tcsetpgrp", posix_tcsetpgrp, METH_VARARGS, posix_tcsetpgrp__doc__}, + {"tcsetpgrp", posix_tcsetpgrp, METH_VARARGS, posix_tcsetpgrp__doc__}, #endif /* HAVE_TCSETPGRP */ - {"open", posix_open, METH_VARARGS, posix_open__doc__}, - {"close", posix_close, METH_VARARGS, posix_close__doc__}, - {"closerange", posix_closerange, METH_VARARGS, posix_closerange__doc__}, - {"device_encoding", device_encoding, METH_VARARGS, device_encoding__doc__}, - {"dup", posix_dup, METH_VARARGS, posix_dup__doc__}, - {"dup2", posix_dup2, METH_VARARGS, posix_dup2__doc__}, - {"lseek", posix_lseek, METH_VARARGS, posix_lseek__doc__}, - {"read", posix_read, METH_VARARGS, posix_read__doc__}, - {"write", posix_write, METH_VARARGS, posix_write__doc__}, - {"fstat", posix_fstat, METH_VARARGS, posix_fstat__doc__}, - {"isatty", posix_isatty, METH_VARARGS, posix_isatty__doc__}, + {"open", posix_open, METH_VARARGS, posix_open__doc__}, + {"close", posix_close, METH_VARARGS, posix_close__doc__}, + {"closerange", posix_closerange, METH_VARARGS, posix_closerange__doc__}, + {"device_encoding", device_encoding, METH_VARARGS, device_encoding__doc__}, + {"dup", posix_dup, METH_VARARGS, posix_dup__doc__}, + {"dup2", posix_dup2, METH_VARARGS, posix_dup2__doc__}, + {"lseek", posix_lseek, METH_VARARGS, posix_lseek__doc__}, + {"read", posix_read, METH_VARARGS, posix_read__doc__}, + {"write", posix_write, METH_VARARGS, posix_write__doc__}, + {"fstat", posix_fstat, METH_VARARGS, posix_fstat__doc__}, + {"isatty", posix_isatty, METH_VARARGS, posix_isatty__doc__}, #ifdef HAVE_PIPE - {"pipe", posix_pipe, METH_NOARGS, posix_pipe__doc__}, + {"pipe", posix_pipe, METH_NOARGS, posix_pipe__doc__}, #endif #ifdef HAVE_MKFIFO - {"mkfifo", posix_mkfifo, METH_VARARGS, posix_mkfifo__doc__}, + {"mkfifo", posix_mkfifo, METH_VARARGS, posix_mkfifo__doc__}, #endif #if defined(HAVE_MKNOD) && defined(HAVE_MAKEDEV) - {"mknod", posix_mknod, METH_VARARGS, posix_mknod__doc__}, + {"mknod", posix_mknod, METH_VARARGS, posix_mknod__doc__}, #endif #ifdef HAVE_DEVICE_MACROS - {"major", posix_major, METH_VARARGS, posix_major__doc__}, - {"minor", posix_minor, METH_VARARGS, posix_minor__doc__}, - {"makedev", posix_makedev, METH_VARARGS, posix_makedev__doc__}, + {"major", posix_major, METH_VARARGS, posix_major__doc__}, + {"minor", posix_minor, METH_VARARGS, posix_minor__doc__}, + {"makedev", posix_makedev, METH_VARARGS, posix_makedev__doc__}, #endif #ifdef HAVE_FTRUNCATE - {"ftruncate", posix_ftruncate, METH_VARARGS, posix_ftruncate__doc__}, + {"ftruncate", posix_ftruncate, METH_VARARGS, posix_ftruncate__doc__}, #endif #ifdef HAVE_PUTENV - {"putenv", posix_putenv, METH_VARARGS, posix_putenv__doc__}, + {"putenv", posix_putenv, METH_VARARGS, posix_putenv__doc__}, #endif #ifdef HAVE_UNSETENV - {"unsetenv", posix_unsetenv, METH_VARARGS, posix_unsetenv__doc__}, + {"unsetenv", posix_unsetenv, METH_VARARGS, posix_unsetenv__doc__}, #endif - {"strerror", posix_strerror, METH_VARARGS, posix_strerror__doc__}, + {"strerror", posix_strerror, METH_VARARGS, posix_strerror__doc__}, #ifdef HAVE_FCHDIR - {"fchdir", posix_fchdir, METH_O, posix_fchdir__doc__}, + {"fchdir", posix_fchdir, METH_O, posix_fchdir__doc__}, #endif #ifdef HAVE_FSYNC - {"fsync", posix_fsync, METH_O, posix_fsync__doc__}, + {"fsync", posix_fsync, METH_O, posix_fsync__doc__}, #endif #ifdef HAVE_FDATASYNC - {"fdatasync", posix_fdatasync, METH_O, posix_fdatasync__doc__}, + {"fdatasync", posix_fdatasync, METH_O, posix_fdatasync__doc__}, #endif #ifdef HAVE_SYS_WAIT_H #ifdef WCOREDUMP - {"WCOREDUMP", posix_WCOREDUMP, METH_VARARGS, posix_WCOREDUMP__doc__}, + {"WCOREDUMP", posix_WCOREDUMP, METH_VARARGS, posix_WCOREDUMP__doc__}, #endif /* WCOREDUMP */ #ifdef WIFCONTINUED - {"WIFCONTINUED",posix_WIFCONTINUED, METH_VARARGS, posix_WIFCONTINUED__doc__}, + {"WIFCONTINUED",posix_WIFCONTINUED, METH_VARARGS, posix_WIFCONTINUED__doc__}, #endif /* WIFCONTINUED */ #ifdef WIFSTOPPED - {"WIFSTOPPED", posix_WIFSTOPPED, METH_VARARGS, posix_WIFSTOPPED__doc__}, + {"WIFSTOPPED", posix_WIFSTOPPED, METH_VARARGS, posix_WIFSTOPPED__doc__}, #endif /* WIFSTOPPED */ #ifdef WIFSIGNALED - {"WIFSIGNALED", posix_WIFSIGNALED, METH_VARARGS, posix_WIFSIGNALED__doc__}, + {"WIFSIGNALED", posix_WIFSIGNALED, METH_VARARGS, posix_WIFSIGNALED__doc__}, #endif /* WIFSIGNALED */ #ifdef WIFEXITED - {"WIFEXITED", posix_WIFEXITED, METH_VARARGS, posix_WIFEXITED__doc__}, + {"WIFEXITED", posix_WIFEXITED, METH_VARARGS, posix_WIFEXITED__doc__}, #endif /* WIFEXITED */ #ifdef WEXITSTATUS - {"WEXITSTATUS", posix_WEXITSTATUS, METH_VARARGS, posix_WEXITSTATUS__doc__}, + {"WEXITSTATUS", posix_WEXITSTATUS, METH_VARARGS, posix_WEXITSTATUS__doc__}, #endif /* WEXITSTATUS */ #ifdef WTERMSIG - {"WTERMSIG", posix_WTERMSIG, METH_VARARGS, posix_WTERMSIG__doc__}, + {"WTERMSIG", posix_WTERMSIG, METH_VARARGS, posix_WTERMSIG__doc__}, #endif /* WTERMSIG */ #ifdef WSTOPSIG - {"WSTOPSIG", posix_WSTOPSIG, METH_VARARGS, posix_WSTOPSIG__doc__}, + {"WSTOPSIG", posix_WSTOPSIG, METH_VARARGS, posix_WSTOPSIG__doc__}, #endif /* WSTOPSIG */ #endif /* HAVE_SYS_WAIT_H */ #if defined(HAVE_FSTATVFS) && defined(HAVE_SYS_STATVFS_H) - {"fstatvfs", posix_fstatvfs, METH_VARARGS, posix_fstatvfs__doc__}, + {"fstatvfs", posix_fstatvfs, METH_VARARGS, posix_fstatvfs__doc__}, #endif #if defined(HAVE_STATVFS) && defined(HAVE_SYS_STATVFS_H) - {"statvfs", posix_statvfs, METH_VARARGS, posix_statvfs__doc__}, + {"statvfs", posix_statvfs, METH_VARARGS, posix_statvfs__doc__}, #endif #ifdef HAVE_CONFSTR - {"confstr", posix_confstr, METH_VARARGS, posix_confstr__doc__}, + {"confstr", posix_confstr, METH_VARARGS, posix_confstr__doc__}, #endif #ifdef HAVE_SYSCONF - {"sysconf", posix_sysconf, METH_VARARGS, posix_sysconf__doc__}, + {"sysconf", posix_sysconf, METH_VARARGS, posix_sysconf__doc__}, #endif #ifdef HAVE_FPATHCONF - {"fpathconf", posix_fpathconf, METH_VARARGS, posix_fpathconf__doc__}, + {"fpathconf", posix_fpathconf, METH_VARARGS, posix_fpathconf__doc__}, #endif #ifdef HAVE_PATHCONF - {"pathconf", posix_pathconf, METH_VARARGS, posix_pathconf__doc__}, + {"pathconf", posix_pathconf, METH_VARARGS, posix_pathconf__doc__}, #endif - {"abort", posix_abort, METH_NOARGS, posix_abort__doc__}, + {"abort", posix_abort, METH_NOARGS, posix_abort__doc__}, #ifdef MS_WINDOWS - {"_getfullpathname", posix__getfullpathname, METH_VARARGS, NULL}, + {"_getfullpathname", posix__getfullpathname, METH_VARARGS, NULL}, #endif #ifdef HAVE_GETLOADAVG - {"getloadavg", posix_getloadavg, METH_NOARGS, posix_getloadavg__doc__}, + {"getloadavg", posix_getloadavg, METH_NOARGS, posix_getloadavg__doc__}, #endif #ifdef MS_WINDOWS - {"urandom", win32_urandom, METH_VARARGS, win32_urandom__doc__}, + {"urandom", win32_urandom, METH_VARARGS, win32_urandom__doc__}, #endif #ifdef __VMS - {"urandom", vms_urandom, METH_VARARGS, vms_urandom__doc__}, + {"urandom", vms_urandom, METH_VARARGS, vms_urandom__doc__}, #endif - {NULL, NULL} /* Sentinel */ + {NULL, NULL} /* Sentinel */ }; static int ins(PyObject *module, char *symbol, long value) { - return PyModule_AddIntConstant(module, symbol, value); + return PyModule_AddIntConstant(module, symbol, value); } #if defined(PYOS_OS2) @@ -7352,7 +7353,7 @@ case 50: ver = "5.00"; break; default: PyOS_snprintf(tmp, sizeof(tmp), - "%d-%d", values[QSV_VERSION_MAJOR], + "%d-%d", values[QSV_VERSION_MAJOR], values[QSV_VERSION_MINOR]); ver = &tmp[0]; } @@ -7374,221 +7375,221 @@ all_ins(PyObject *d) { #ifdef F_OK - if (ins(d, "F_OK", (long)F_OK)) return -1; + if (ins(d, "F_OK", (long)F_OK)) return -1; #endif #ifdef R_OK - if (ins(d, "R_OK", (long)R_OK)) return -1; + if (ins(d, "R_OK", (long)R_OK)) return -1; #endif #ifdef W_OK - if (ins(d, "W_OK", (long)W_OK)) return -1; + if (ins(d, "W_OK", (long)W_OK)) return -1; #endif #ifdef X_OK - if (ins(d, "X_OK", (long)X_OK)) return -1; + if (ins(d, "X_OK", (long)X_OK)) return -1; #endif #ifdef NGROUPS_MAX - if (ins(d, "NGROUPS_MAX", (long)NGROUPS_MAX)) return -1; + if (ins(d, "NGROUPS_MAX", (long)NGROUPS_MAX)) return -1; #endif #ifdef TMP_MAX - if (ins(d, "TMP_MAX", (long)TMP_MAX)) return -1; + if (ins(d, "TMP_MAX", (long)TMP_MAX)) return -1; #endif #ifdef WCONTINUED - if (ins(d, "WCONTINUED", (long)WCONTINUED)) return -1; + if (ins(d, "WCONTINUED", (long)WCONTINUED)) return -1; #endif #ifdef WNOHANG - if (ins(d, "WNOHANG", (long)WNOHANG)) return -1; + if (ins(d, "WNOHANG", (long)WNOHANG)) return -1; #endif #ifdef WUNTRACED - if (ins(d, "WUNTRACED", (long)WUNTRACED)) return -1; + if (ins(d, "WUNTRACED", (long)WUNTRACED)) return -1; #endif #ifdef O_RDONLY - if (ins(d, "O_RDONLY", (long)O_RDONLY)) return -1; + if (ins(d, "O_RDONLY", (long)O_RDONLY)) return -1; #endif #ifdef O_WRONLY - if (ins(d, "O_WRONLY", (long)O_WRONLY)) return -1; + if (ins(d, "O_WRONLY", (long)O_WRONLY)) return -1; #endif #ifdef O_RDWR - if (ins(d, "O_RDWR", (long)O_RDWR)) return -1; + if (ins(d, "O_RDWR", (long)O_RDWR)) return -1; #endif #ifdef O_NDELAY - if (ins(d, "O_NDELAY", (long)O_NDELAY)) return -1; + if (ins(d, "O_NDELAY", (long)O_NDELAY)) return -1; #endif #ifdef O_NONBLOCK - if (ins(d, "O_NONBLOCK", (long)O_NONBLOCK)) return -1; + if (ins(d, "O_NONBLOCK", (long)O_NONBLOCK)) return -1; #endif #ifdef O_APPEND - if (ins(d, "O_APPEND", (long)O_APPEND)) return -1; + if (ins(d, "O_APPEND", (long)O_APPEND)) return -1; #endif #ifdef O_DSYNC - if (ins(d, "O_DSYNC", (long)O_DSYNC)) return -1; + if (ins(d, "O_DSYNC", (long)O_DSYNC)) return -1; #endif #ifdef O_RSYNC - if (ins(d, "O_RSYNC", (long)O_RSYNC)) return -1; + if (ins(d, "O_RSYNC", (long)O_RSYNC)) return -1; #endif #ifdef O_SYNC - if (ins(d, "O_SYNC", (long)O_SYNC)) return -1; + if (ins(d, "O_SYNC", (long)O_SYNC)) return -1; #endif #ifdef O_NOCTTY - if (ins(d, "O_NOCTTY", (long)O_NOCTTY)) return -1; + if (ins(d, "O_NOCTTY", (long)O_NOCTTY)) return -1; #endif #ifdef O_CREAT - if (ins(d, "O_CREAT", (long)O_CREAT)) return -1; + if (ins(d, "O_CREAT", (long)O_CREAT)) return -1; #endif #ifdef O_EXCL - if (ins(d, "O_EXCL", (long)O_EXCL)) return -1; + if (ins(d, "O_EXCL", (long)O_EXCL)) return -1; #endif #ifdef O_TRUNC - if (ins(d, "O_TRUNC", (long)O_TRUNC)) return -1; + if (ins(d, "O_TRUNC", (long)O_TRUNC)) return -1; #endif #ifdef O_BINARY - if (ins(d, "O_BINARY", (long)O_BINARY)) return -1; + if (ins(d, "O_BINARY", (long)O_BINARY)) return -1; #endif #ifdef O_TEXT - if (ins(d, "O_TEXT", (long)O_TEXT)) return -1; + if (ins(d, "O_TEXT", (long)O_TEXT)) return -1; #endif #ifdef O_LARGEFILE - if (ins(d, "O_LARGEFILE", (long)O_LARGEFILE)) return -1; + if (ins(d, "O_LARGEFILE", (long)O_LARGEFILE)) return -1; #endif #ifdef O_SHLOCK - if (ins(d, "O_SHLOCK", (long)O_SHLOCK)) return -1; + if (ins(d, "O_SHLOCK", (long)O_SHLOCK)) return -1; #endif #ifdef O_EXLOCK - if (ins(d, "O_EXLOCK", (long)O_EXLOCK)) return -1; + if (ins(d, "O_EXLOCK", (long)O_EXLOCK)) return -1; #endif /* MS Windows */ #ifdef O_NOINHERIT - /* Don't inherit in child processes. */ - if (ins(d, "O_NOINHERIT", (long)O_NOINHERIT)) return -1; + /* Don't inherit in child processes. */ + if (ins(d, "O_NOINHERIT", (long)O_NOINHERIT)) return -1; #endif #ifdef _O_SHORT_LIVED - /* Optimize for short life (keep in memory). */ - /* MS forgot to define this one with a non-underscore form too. */ - if (ins(d, "O_SHORT_LIVED", (long)_O_SHORT_LIVED)) return -1; + /* Optimize for short life (keep in memory). */ + /* MS forgot to define this one with a non-underscore form too. */ + if (ins(d, "O_SHORT_LIVED", (long)_O_SHORT_LIVED)) return -1; #endif #ifdef O_TEMPORARY - /* Automatically delete when last handle is closed. */ - if (ins(d, "O_TEMPORARY", (long)O_TEMPORARY)) return -1; + /* Automatically delete when last handle is closed. */ + if (ins(d, "O_TEMPORARY", (long)O_TEMPORARY)) return -1; #endif #ifdef O_RANDOM - /* Optimize for random access. */ - if (ins(d, "O_RANDOM", (long)O_RANDOM)) return -1; + /* Optimize for random access. */ + if (ins(d, "O_RANDOM", (long)O_RANDOM)) return -1; #endif #ifdef O_SEQUENTIAL - /* Optimize for sequential access. */ - if (ins(d, "O_SEQUENTIAL", (long)O_SEQUENTIAL)) return -1; + /* Optimize for sequential access. */ + if (ins(d, "O_SEQUENTIAL", (long)O_SEQUENTIAL)) return -1; #endif /* GNU extensions. */ #ifdef O_ASYNC - /* Send a SIGIO signal whenever input or output - becomes available on file descriptor */ - if (ins(d, "O_ASYNC", (long)O_ASYNC)) return -1; + /* Send a SIGIO signal whenever input or output + becomes available on file descriptor */ + if (ins(d, "O_ASYNC", (long)O_ASYNC)) return -1; #endif #ifdef O_DIRECT - /* Direct disk access. */ - if (ins(d, "O_DIRECT", (long)O_DIRECT)) return -1; + /* Direct disk access. */ + if (ins(d, "O_DIRECT", (long)O_DIRECT)) return -1; #endif #ifdef O_DIRECTORY - /* Must be a directory. */ - if (ins(d, "O_DIRECTORY", (long)O_DIRECTORY)) return -1; + /* Must be a directory. */ + if (ins(d, "O_DIRECTORY", (long)O_DIRECTORY)) return -1; #endif #ifdef O_NOFOLLOW - /* Do not follow links. */ - if (ins(d, "O_NOFOLLOW", (long)O_NOFOLLOW)) return -1; + /* Do not follow links. */ + if (ins(d, "O_NOFOLLOW", (long)O_NOFOLLOW)) return -1; #endif #ifdef O_NOATIME - /* Do not update the access time. */ - if (ins(d, "O_NOATIME", (long)O_NOATIME)) return -1; + /* Do not update the access time. */ + if (ins(d, "O_NOATIME", (long)O_NOATIME)) return -1; #endif - /* These come from sysexits.h */ + /* These come from sysexits.h */ #ifdef EX_OK - if (ins(d, "EX_OK", (long)EX_OK)) return -1; + if (ins(d, "EX_OK", (long)EX_OK)) return -1; #endif /* EX_OK */ #ifdef EX_USAGE - if (ins(d, "EX_USAGE", (long)EX_USAGE)) return -1; + if (ins(d, "EX_USAGE", (long)EX_USAGE)) return -1; #endif /* EX_USAGE */ #ifdef EX_DATAERR - if (ins(d, "EX_DATAERR", (long)EX_DATAERR)) return -1; + if (ins(d, "EX_DATAERR", (long)EX_DATAERR)) return -1; #endif /* EX_DATAERR */ #ifdef EX_NOINPUT - if (ins(d, "EX_NOINPUT", (long)EX_NOINPUT)) return -1; + if (ins(d, "EX_NOINPUT", (long)EX_NOINPUT)) return -1; #endif /* EX_NOINPUT */ #ifdef EX_NOUSER - if (ins(d, "EX_NOUSER", (long)EX_NOUSER)) return -1; + if (ins(d, "EX_NOUSER", (long)EX_NOUSER)) return -1; #endif /* EX_NOUSER */ #ifdef EX_NOHOST - if (ins(d, "EX_NOHOST", (long)EX_NOHOST)) return -1; + if (ins(d, "EX_NOHOST", (long)EX_NOHOST)) return -1; #endif /* EX_NOHOST */ #ifdef EX_UNAVAILABLE - if (ins(d, "EX_UNAVAILABLE", (long)EX_UNAVAILABLE)) return -1; + if (ins(d, "EX_UNAVAILABLE", (long)EX_UNAVAILABLE)) return -1; #endif /* EX_UNAVAILABLE */ #ifdef EX_SOFTWARE - if (ins(d, "EX_SOFTWARE", (long)EX_SOFTWARE)) return -1; + if (ins(d, "EX_SOFTWARE", (long)EX_SOFTWARE)) return -1; #endif /* EX_SOFTWARE */ #ifdef EX_OSERR - if (ins(d, "EX_OSERR", (long)EX_OSERR)) return -1; + if (ins(d, "EX_OSERR", (long)EX_OSERR)) return -1; #endif /* EX_OSERR */ #ifdef EX_OSFILE - if (ins(d, "EX_OSFILE", (long)EX_OSFILE)) return -1; + if (ins(d, "EX_OSFILE", (long)EX_OSFILE)) return -1; #endif /* EX_OSFILE */ #ifdef EX_CANTCREAT - if (ins(d, "EX_CANTCREAT", (long)EX_CANTCREAT)) return -1; + if (ins(d, "EX_CANTCREAT", (long)EX_CANTCREAT)) return -1; #endif /* EX_CANTCREAT */ #ifdef EX_IOERR - if (ins(d, "EX_IOERR", (long)EX_IOERR)) return -1; + if (ins(d, "EX_IOERR", (long)EX_IOERR)) return -1; #endif /* EX_IOERR */ #ifdef EX_TEMPFAIL - if (ins(d, "EX_TEMPFAIL", (long)EX_TEMPFAIL)) return -1; + if (ins(d, "EX_TEMPFAIL", (long)EX_TEMPFAIL)) return -1; #endif /* EX_TEMPFAIL */ #ifdef EX_PROTOCOL - if (ins(d, "EX_PROTOCOL", (long)EX_PROTOCOL)) return -1; + if (ins(d, "EX_PROTOCOL", (long)EX_PROTOCOL)) return -1; #endif /* EX_PROTOCOL */ #ifdef EX_NOPERM - if (ins(d, "EX_NOPERM", (long)EX_NOPERM)) return -1; + if (ins(d, "EX_NOPERM", (long)EX_NOPERM)) return -1; #endif /* EX_NOPERM */ #ifdef EX_CONFIG - if (ins(d, "EX_CONFIG", (long)EX_CONFIG)) return -1; + if (ins(d, "EX_CONFIG", (long)EX_CONFIG)) return -1; #endif /* EX_CONFIG */ #ifdef EX_NOTFOUND - if (ins(d, "EX_NOTFOUND", (long)EX_NOTFOUND)) return -1; + if (ins(d, "EX_NOTFOUND", (long)EX_NOTFOUND)) return -1; #endif /* EX_NOTFOUND */ #ifdef HAVE_SPAWNV #if defined(PYOS_OS2) && defined(PYCC_GCC) - if (ins(d, "P_WAIT", (long)P_WAIT)) return -1; - if (ins(d, "P_NOWAIT", (long)P_NOWAIT)) return -1; - if (ins(d, "P_OVERLAY", (long)P_OVERLAY)) return -1; - if (ins(d, "P_DEBUG", (long)P_DEBUG)) return -1; - if (ins(d, "P_SESSION", (long)P_SESSION)) return -1; - if (ins(d, "P_DETACH", (long)P_DETACH)) return -1; - if (ins(d, "P_PM", (long)P_PM)) return -1; - if (ins(d, "P_DEFAULT", (long)P_DEFAULT)) return -1; - if (ins(d, "P_MINIMIZE", (long)P_MINIMIZE)) return -1; - if (ins(d, "P_MAXIMIZE", (long)P_MAXIMIZE)) return -1; - if (ins(d, "P_FULLSCREEN", (long)P_FULLSCREEN)) return -1; - if (ins(d, "P_WINDOWED", (long)P_WINDOWED)) return -1; - if (ins(d, "P_FOREGROUND", (long)P_FOREGROUND)) return -1; - if (ins(d, "P_BACKGROUND", (long)P_BACKGROUND)) return -1; - if (ins(d, "P_NOCLOSE", (long)P_NOCLOSE)) return -1; - if (ins(d, "P_NOSESSION", (long)P_NOSESSION)) return -1; - if (ins(d, "P_QUOTE", (long)P_QUOTE)) return -1; - if (ins(d, "P_TILDE", (long)P_TILDE)) return -1; - if (ins(d, "P_UNRELATED", (long)P_UNRELATED)) return -1; - if (ins(d, "P_DEBUGDESC", (long)P_DEBUGDESC)) return -1; -#else - if (ins(d, "P_WAIT", (long)_P_WAIT)) return -1; - if (ins(d, "P_NOWAIT", (long)_P_NOWAIT)) return -1; - if (ins(d, "P_OVERLAY", (long)_OLD_P_OVERLAY)) return -1; - if (ins(d, "P_NOWAITO", (long)_P_NOWAITO)) return -1; - if (ins(d, "P_DETACH", (long)_P_DETACH)) return -1; + if (ins(d, "P_WAIT", (long)P_WAIT)) return -1; + if (ins(d, "P_NOWAIT", (long)P_NOWAIT)) return -1; + if (ins(d, "P_OVERLAY", (long)P_OVERLAY)) return -1; + if (ins(d, "P_DEBUG", (long)P_DEBUG)) return -1; + if (ins(d, "P_SESSION", (long)P_SESSION)) return -1; + if (ins(d, "P_DETACH", (long)P_DETACH)) return -1; + if (ins(d, "P_PM", (long)P_PM)) return -1; + if (ins(d, "P_DEFAULT", (long)P_DEFAULT)) return -1; + if (ins(d, "P_MINIMIZE", (long)P_MINIMIZE)) return -1; + if (ins(d, "P_MAXIMIZE", (long)P_MAXIMIZE)) return -1; + if (ins(d, "P_FULLSCREEN", (long)P_FULLSCREEN)) return -1; + if (ins(d, "P_WINDOWED", (long)P_WINDOWED)) return -1; + if (ins(d, "P_FOREGROUND", (long)P_FOREGROUND)) return -1; + if (ins(d, "P_BACKGROUND", (long)P_BACKGROUND)) return -1; + if (ins(d, "P_NOCLOSE", (long)P_NOCLOSE)) return -1; + if (ins(d, "P_NOSESSION", (long)P_NOSESSION)) return -1; + if (ins(d, "P_QUOTE", (long)P_QUOTE)) return -1; + if (ins(d, "P_TILDE", (long)P_TILDE)) return -1; + if (ins(d, "P_UNRELATED", (long)P_UNRELATED)) return -1; + if (ins(d, "P_DEBUGDESC", (long)P_DEBUGDESC)) return -1; +#else + if (ins(d, "P_WAIT", (long)_P_WAIT)) return -1; + if (ins(d, "P_NOWAIT", (long)_P_NOWAIT)) return -1; + if (ins(d, "P_OVERLAY", (long)_OLD_P_OVERLAY)) return -1; + if (ins(d, "P_NOWAITO", (long)_P_NOWAITO)) return -1; + if (ins(d, "P_DETACH", (long)_P_DETACH)) return -1; #endif #endif #if defined(PYOS_OS2) - if (insertvalues(d)) return -1; + if (insertvalues(d)) return -1; #endif - return 0; + return 0; } @@ -7606,114 +7607,114 @@ #endif static struct PyModuleDef posixmodule = { - PyModuleDef_HEAD_INIT, - MODNAME, - posix__doc__, - -1, - posix_methods, - NULL, - NULL, - NULL, - NULL + PyModuleDef_HEAD_INIT, + MODNAME, + posix__doc__, + -1, + posix_methods, + NULL, + NULL, + NULL, + NULL }; PyMODINIT_FUNC INITFUNC(void) { - PyObject *m, *v; + PyObject *m, *v; - m = PyModule_Create(&posixmodule); - if (m == NULL) - return NULL; - - /* Initialize environ dictionary */ - v = convertenviron(); - Py_XINCREF(v); - if (v == NULL || PyModule_AddObject(m, "environ", v) != 0) - return NULL; - Py_DECREF(v); + m = PyModule_Create(&posixmodule); + if (m == NULL) + return NULL; - if (all_ins(m)) - return NULL; + /* Initialize environ dictionary */ + v = convertenviron(); + Py_XINCREF(v); + if (v == NULL || PyModule_AddObject(m, "environ", v) != 0) + return NULL; + Py_DECREF(v); - if (setup_confname_tables(m)) - return NULL; + if (all_ins(m)) + return NULL; + + if (setup_confname_tables(m)) + return NULL; - Py_INCREF(PyExc_OSError); - PyModule_AddObject(m, "error", PyExc_OSError); + Py_INCREF(PyExc_OSError); + PyModule_AddObject(m, "error", PyExc_OSError); #ifdef HAVE_PUTENV - if (posix_putenv_garbage == NULL) - posix_putenv_garbage = PyDict_New(); + if (posix_putenv_garbage == NULL) + posix_putenv_garbage = PyDict_New(); #endif - if (!initialized) { - stat_result_desc.name = MODNAME ".stat_result"; - stat_result_desc.fields[7].name = PyStructSequence_UnnamedField; - stat_result_desc.fields[8].name = PyStructSequence_UnnamedField; - stat_result_desc.fields[9].name = PyStructSequence_UnnamedField; - PyStructSequence_InitType(&StatResultType, &stat_result_desc); - structseq_new = StatResultType.tp_new; - StatResultType.tp_new = statresult_new; + if (!initialized) { + stat_result_desc.name = MODNAME ".stat_result"; + stat_result_desc.fields[7].name = PyStructSequence_UnnamedField; + stat_result_desc.fields[8].name = PyStructSequence_UnnamedField; + stat_result_desc.fields[9].name = PyStructSequence_UnnamedField; + PyStructSequence_InitType(&StatResultType, &stat_result_desc); + structseq_new = StatResultType.tp_new; + StatResultType.tp_new = statresult_new; - statvfs_result_desc.name = MODNAME ".statvfs_result"; - PyStructSequence_InitType(&StatVFSResultType, &statvfs_result_desc); + statvfs_result_desc.name = MODNAME ".statvfs_result"; + PyStructSequence_InitType(&StatVFSResultType, &statvfs_result_desc); #ifdef NEED_TICKS_PER_SECOND # if defined(HAVE_SYSCONF) && defined(_SC_CLK_TCK) - ticks_per_second = sysconf(_SC_CLK_TCK); + ticks_per_second = sysconf(_SC_CLK_TCK); # elif defined(HZ) - ticks_per_second = HZ; + ticks_per_second = HZ; # else - ticks_per_second = 60; /* magic fallback value; may be bogus */ + ticks_per_second = 60; /* magic fallback value; may be bogus */ # endif #endif - } - Py_INCREF((PyObject*) &StatResultType); - PyModule_AddObject(m, "stat_result", (PyObject*) &StatResultType); - Py_INCREF((PyObject*) &StatVFSResultType); - PyModule_AddObject(m, "statvfs_result", - (PyObject*) &StatVFSResultType); - initialized = 1; + } + Py_INCREF((PyObject*) &StatResultType); + PyModule_AddObject(m, "stat_result", (PyObject*) &StatResultType); + Py_INCREF((PyObject*) &StatVFSResultType); + PyModule_AddObject(m, "statvfs_result", + (PyObject*) &StatVFSResultType); + initialized = 1; #ifdef __APPLE__ - /* - * Step 2 of weak-linking support on Mac OS X. - * - * The code below removes functions that are not available on the - * currently active platform. - * - * This block allow one to use a python binary that was build on - * OSX 10.4 on OSX 10.3, without loosing access to new APIs on - * OSX 10.4. - */ + /* + * Step 2 of weak-linking support on Mac OS X. + * + * The code below removes functions that are not available on the + * currently active platform. + * + * This block allow one to use a python binary that was build on + * OSX 10.4 on OSX 10.3, without loosing access to new APIs on + * OSX 10.4. + */ #ifdef HAVE_FSTATVFS - if (fstatvfs == NULL) { - if (PyObject_DelAttrString(m, "fstatvfs") == -1) { - return NULL; - } - } + if (fstatvfs == NULL) { + if (PyObject_DelAttrString(m, "fstatvfs") == -1) { + return NULL; + } + } #endif /* HAVE_FSTATVFS */ #ifdef HAVE_STATVFS - if (statvfs == NULL) { - if (PyObject_DelAttrString(m, "statvfs") == -1) { - return NULL; - } - } + if (statvfs == NULL) { + if (PyObject_DelAttrString(m, "statvfs") == -1) { + return NULL; + } + } #endif /* HAVE_STATVFS */ # ifdef HAVE_LCHOWN - if (lchown == NULL) { - if (PyObject_DelAttrString(m, "lchown") == -1) { - return NULL; - } - } + if (lchown == NULL) { + if (PyObject_DelAttrString(m, "lchown") == -1) { + return NULL; + } + } #endif /* HAVE_LCHOWN */ #endif /* __APPLE__ */ - return m; + return m; } From python-checkins at python.org Thu May 6 02:59:04 2010 From: python-checkins at python.org (r.david.murray) Date: Thu, 6 May 2010 02:59:04 +0200 (CEST) Subject: [Python-checkins] r80849 - python/trunk/Tools/scripts/serve.py Message-ID: <20100506005904.3120CEE9B7@mail.python.org> Author: r.david.murray Date: Thu May 6 02:59:04 2010 New Revision: 80849 Log: Have the serve.py script announce the directory it is serving and which port it is serving it on (I can never remember the default port number it uses...) Modified: python/trunk/Tools/scripts/serve.py Modified: python/trunk/Tools/scripts/serve.py ============================================================================== --- python/trunk/Tools/scripts/serve.py (original) +++ python/trunk/Tools/scripts/serve.py Thu May 6 02:59:04 2010 @@ -28,4 +28,5 @@ path = sys.argv[1] port = int(sys.argv[2]) if len(sys.argv) > 2 else 8000 httpd = simple_server.make_server('', port, app) + print "Serving %s on port %s" % (path, port) httpd.serve_forever() From python-checkins at python.org Thu May 6 03:06:27 2010 From: python-checkins at python.org (r.david.murray) Date: Thu, 6 May 2010 03:06:27 +0200 (CEST) Subject: [Python-checkins] r80850 - python/branches/release26-maint Message-ID: <20100506010627.31274EE9AA@mail.python.org> Author: r.david.murray Date: Thu May 6 03:06:27 2010 New Revision: 80850 Log: Blocked revisions 80849 via svnmerge ........ r80849 | r.david.murray | 2010-05-05 20:59:04 -0400 (Wed, 05 May 2010) | 4 lines Have the serve.py script announce the directory it is serving and which port it is serving it on (I can never remember the default port number it uses...) ........ Modified: python/branches/release26-maint/ (props changed) From python-checkins at python.org Thu May 6 03:09:27 2010 From: python-checkins at python.org (r.david.murray) Date: Thu, 6 May 2010 03:09:27 +0200 (CEST) Subject: [Python-checkins] r80851 - in python/branches/py3k: Tools/scripts/serve.py Message-ID: <20100506010927.5D623EE9AA@mail.python.org> Author: r.david.murray Date: Thu May 6 03:09:27 2010 New Revision: 80851 Log: Merged revisions 80849 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r80849 | r.david.murray | 2010-05-05 20:59:04 -0400 (Wed, 05 May 2010) | 4 lines Have the serve.py script announce the directory it is serving and which port it is serving it on (I can never remember the default port number it uses...) ........ Modified: python/branches/py3k/ (props changed) python/branches/py3k/Tools/scripts/serve.py Modified: python/branches/py3k/Tools/scripts/serve.py ============================================================================== --- python/branches/py3k/Tools/scripts/serve.py (original) +++ python/branches/py3k/Tools/scripts/serve.py Thu May 6 03:09:27 2010 @@ -28,4 +28,5 @@ path = sys.argv[1] port = int(sys.argv[2]) if len(sys.argv) > 2 else 8000 httpd = simple_server.make_server('', port, app) + print("Serving {} on port {}".format(path, port)) httpd.serve_forever() From python-checkins at python.org Thu May 6 03:09:48 2010 From: python-checkins at python.org (andrew.kuchling) Date: Thu, 6 May 2010 03:09:48 +0200 (CEST) Subject: [Python-checkins] r80852 - python/trunk/Doc/library/sysconfig.rst Message-ID: <20100506010948.1B914EE9AA@mail.python.org> Author: andrew.kuchling Date: Thu May 6 03:09:47 2010 New Revision: 80852 Log: Reword paragraph; fix filename, which should be pyconfig.h Modified: python/trunk/Doc/library/sysconfig.rst Modified: python/trunk/Doc/library/sysconfig.rst ============================================================================== --- python/trunk/Doc/library/sysconfig.rst (original) +++ python/trunk/Doc/library/sysconfig.rst Thu May 6 03:09:47 2010 @@ -16,9 +16,9 @@ Configuration variables ----------------------- -A Python distribution contains a :file:`Makefile` file and a :file:`python.h` -that are necessary to build the Python binary itself, but also any C extension -created in a third party project and compiled using :mod:`distutils`. +A Python distribution contains a :file:`Makefile` and a :file:`pyconfig.h` +header file that are necessary to build both the Python binary itself and +third-party C extensions compiled using :mod:`distutils`. :mod:`sysconfig` puts all variables found in these files in a dictionary that can be accessed using :func:`get_config_vars` or :func:`get_config_var`. From python-checkins at python.org Thu May 6 03:10:50 2010 From: python-checkins at python.org (r.david.murray) Date: Thu, 6 May 2010 03:10:50 +0200 (CEST) Subject: [Python-checkins] r80853 - python/branches/release31-maint Message-ID: <20100506011050.B692EEE9B7@mail.python.org> Author: r.david.murray Date: Thu May 6 03:10:50 2010 New Revision: 80853 Log: Blocked revisions 80851 via svnmerge ................ r80851 | r.david.murray | 2010-05-05 21:09:27 -0400 (Wed, 05 May 2010) | 11 lines Merged revisions 80849 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r80849 | r.david.murray | 2010-05-05 20:59:04 -0400 (Wed, 05 May 2010) | 4 lines Have the serve.py script announce the directory it is serving and which port it is serving it on (I can never remember the default port number it uses...) ........ ................ Modified: python/branches/release31-maint/ (props changed) From python-checkins at python.org Thu May 6 03:10:56 2010 From: python-checkins at python.org (andrew.kuchling) Date: Thu, 6 May 2010 03:10:56 +0200 (CEST) Subject: [Python-checkins] r80854 - python/trunk/Doc/whatsnew/2.7.rst Message-ID: <20100506011056.51811EEA2A@mail.python.org> Author: andrew.kuchling Date: Thu May 6 03:10:56 2010 New Revision: 80854 Log: Add various items Modified: python/trunk/Doc/whatsnew/2.7.rst Modified: python/trunk/Doc/whatsnew/2.7.rst ============================================================================== --- python/trunk/Doc/whatsnew/2.7.rst (original) +++ python/trunk/Doc/whatsnew/2.7.rst Thu May 6 03:10:56 2010 @@ -8,8 +8,7 @@ .. Fix accents on Kristjan Valur Jonsson, Fuerstenau -.. Big jobs: ElementTree 1.3, pep 391, sysconfig -.. unittest test discovery +.. Big jobs: ElementTree 1.3, pep 391 .. hyperlink all the methods & functions. .. T_STRING_INPLACE not described in main docs @@ -1217,6 +1216,20 @@ now accept an optional *flags* argument, for consistency with the other functions in the module. (Added by Gregory P. Smith.) +* New function: :func:`~runpy.run_path` in the :mod:`runpy` module + will execute the code at a provided *path* argument. *path* can be + the path of a Python source file (:file:`example.py`), a compiled + bytecode file (:file:`example.pyc`), a directory + (:file:`./package/'), or a zip archive (:file:`example.zip`). If a + directory or zip path is provided, it will be added to the front of + ``sys.path`` and the module :mod:`__main__` will be imported. It's + expected that the directory or zip contains a :file:`__main__.py`; + if it doesn't, some other :file:`__main__.py` might be imported from + a location later in ``sys.path``. This makes some of the machinery + of :mod:`runpy` available to scripts that want to mimic the behaviour + of Python's :option:`-m` switch. (Added by Nick Coghlan; + :issue:`6816`.) + * New function: in the :mod:`shutil` module, :func:`~shutil.make_archive` takes a filename, archive type (zip or tar-format), and a directory path, and creates an archive containing the directory's contents. @@ -1443,12 +1456,31 @@ New module: sysconfig --------------------------------- -XXX A new :mod:`sysconfig` module has been extracted from -:mod:`distutils` and put in the standard library. +The :mod:`sysconfig` module has been pulled out of the Distutils +package, becoming a new top-level module in its own right. +:mod:`sysconfig` provides functions for getting information about +Python's build process: compiler switches, installation paths, the +platform name, and whether Python is running from its source +directory. + +Some of the functions in the module are: + +* :func:`~sysconfig.get_config_var` returns variables from Python's + Makefile and the :file:`pyconfig.h` file. +* :func:`~sysconfig.get_config_vars` returns a dictionary containing + all of the configuration variables. +* :func:`~sysconfig.getpath` returns the configured path for + a particular type of module: the standard library, + site-specific modules, platform-specific modules, etc. +* :func:`~sysconfig.is_python_build` returns true if you're running a + binary from a Python source tree, and false otherwise. + +Consult the :mod:`sysconfig` documentation for more details and for +a complete list of functions. + +The Distutils package and :mod:`sysconfig` are now maintained and +renamed by Tarek Ziad?. -The :mod:`sysconfig` module provides access to Python's configuration -information like the list of installation paths and the configuration -variables relevant for the current platform. (contributed by Tarek) Updated module: ElementTree 1.3 --------------------------------- From python-checkins at python.org Thu May 6 03:41:14 2010 From: python-checkins at python.org (r.david.murray) Date: Thu, 6 May 2010 03:41:14 +0200 (CEST) Subject: [Python-checkins] r80855 - in python/branches/py3k: Lib/email/test/test_email.py Message-ID: <20100506014114.5EF43EE9B7@mail.python.org> Author: r.david.murray Date: Thu May 6 03:41:14 2010 New Revision: 80855 Log: Merged revisions 80800 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk It turns out that email5 (py3k), because it is using unicode for the payload, doesn't do the encoding to the output character set until later in the process. Specifically, charset.body_encode no longer does the input-to-output charset conversion. So the if test in the exception clause in encoders.encode_7or8bit really is needed in email5. So, this merge only merges the test, not the removal of the 'if'. ........ r80800 | r.david.murray | 2010-05-05 13:31:03 -0400 (Wed, 05 May 2010) | 9 lines Issue #7472: remove unused code from email.encoders.encode_7or8bit. Yukihiro Nakadaira noticed a typo in encode_7or8bit that was trying to special case iso-2022 codecs. It turns out that the code in question is never used, because whereas it was designed to trigger if the payload encoding was eight bit but its output encoding was 7 bit, in practice the payload is always converted to the 7bit encoding before encode_7or8bit is called. Patch by Shawat Anand. ........ Modified: python/branches/py3k/ (props changed) python/branches/py3k/Lib/email/test/test_email.py Modified: python/branches/py3k/Lib/email/test/test_email.py ============================================================================== --- python/branches/py3k/Lib/email/test/test_email.py (original) +++ python/branches/py3k/Lib/email/test/test_email.py Thu May 6 03:41:14 2010 @@ -530,6 +530,13 @@ msg = MIMEText('hello \xf8 world', _charset='iso-8859-1') eq(msg['content-transfer-encoding'], 'quoted-printable') + def test_encode7or8bit(self): + # Make sure a charset whose input character set is 8bit but + # whose output character set is 7bit gets a transfer-encoding + # of 7bit. + eq = self.assertEqual + msg = MIMEText('\xca\xb8', _charset='euc-jp') + eq(msg['content-transfer-encoding'], '7bit') # Test long header wrapping From python-checkins at python.org Thu May 6 03:53:04 2010 From: python-checkins at python.org (r.david.murray) Date: Thu, 6 May 2010 03:53:04 +0200 (CEST) Subject: [Python-checkins] r80856 - in python/branches/release31-maint: Lib/email/encoders.py Lib/email/test/test_email.py Misc/NEWS Message-ID: <20100506015304.0BA97EEA5D@mail.python.org> Author: r.david.murray Date: Thu May 6 03:53:03 2010 New Revision: 80856 Log: Merged revisions 79996,80855 via svnmerge from svn+ssh://pythondev at svn.python.org/python/branches/py3k ................ r79996 | r.david.murray | 2010-04-12 10:48:58 -0400 (Mon, 12 Apr 2010) | 15 lines Merged revisions 79994 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r79994 | r.david.murray | 2010-04-12 10:26:06 -0400 (Mon, 12 Apr 2010) | 9 lines Issue #7472: ISO-2022 charsets now consistently use 7bit CTE. Fixed a typo in the email.encoders module so that messages output using an ISO-2022 character set will use a content-transfer-encoding of 7bit consistently. Previously if the input data had any eight bit characters the output data would get marked as 8bit even though it was actually 7bit. ........ ................ r80855 | r.david.murray | 2010-05-05 21:41:14 -0400 (Wed, 05 May 2010) | 24 lines Merged revisions 80800 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk It turns out that email5 (py3k), because it is using unicode for the payload, doesn't do the encoding to the output character set until later in the process. Specifically, charset.body_encode no longer does the input-to-output charset conversion. So the if test in the exception clause in encoders.encode_7or8bit really is needed in email5. So, this merge only merges the test, not the removal of the 'if'. ........ r80800 | r.david.murray | 2010-05-05 13:31:03 -0400 (Wed, 05 May 2010) | 9 lines Issue #7472: remove unused code from email.encoders.encode_7or8bit. Yukihiro Nakadaira noticed a typo in encode_7or8bit that was trying to special case iso-2022 codecs. It turns out that the code in question is never used, because whereas it was designed to trigger if the payload encoding was eight bit but its output encoding was 7 bit, in practice the payload is always converted to the 7bit encoding before encode_7or8bit is called. Patch by Shawat Anand. ........ ................ Modified: python/branches/release31-maint/ (props changed) python/branches/release31-maint/Lib/email/encoders.py python/branches/release31-maint/Lib/email/test/test_email.py python/branches/release31-maint/Misc/NEWS Modified: python/branches/release31-maint/Lib/email/encoders.py ============================================================================== --- python/branches/release31-maint/Lib/email/encoders.py (original) +++ python/branches/release31-maint/Lib/email/encoders.py Thu May 6 03:53:03 2010 @@ -62,7 +62,7 @@ # iso-2022-* is non-ASCII but still 7-bit charset = msg.get_charset() output_cset = charset and charset.output_charset - if output_cset and output_cset.lower().startswith('iso-2202-'): + if output_cset and output_cset.lower().startswith('iso-2022-'): msg['Content-Transfer-Encoding'] = '7bit' else: msg['Content-Transfer-Encoding'] = '8bit' Modified: python/branches/release31-maint/Lib/email/test/test_email.py ============================================================================== --- python/branches/release31-maint/Lib/email/test/test_email.py (original) +++ python/branches/release31-maint/Lib/email/test/test_email.py Thu May 6 03:53:03 2010 @@ -526,6 +526,13 @@ msg = MIMEText('hello \xf8 world', _charset='iso-8859-1') eq(msg['content-transfer-encoding'], 'quoted-printable') + def test_encode7or8bit(self): + # Make sure a charset whose input character set is 8bit but + # whose output character set is 7bit gets a transfer-encoding + # of 7bit. + eq = self.assertEqual + msg = MIMEText('\xca\xb8', _charset='euc-jp') + eq(msg['content-transfer-encoding'], '7bit') # Test long header wrapping Modified: python/branches/release31-maint/Misc/NEWS ============================================================================== --- python/branches/release31-maint/Misc/NEWS (original) +++ python/branches/release31-maint/Misc/NEWS Thu May 6 03:53:03 2010 @@ -40,6 +40,10 @@ Library ------- +- Issue #7472: Fixed typo in email.encoders module; messages using ISO-2022 + character sets will now consistently use a Content-Transfer-Encoding of + 7bit rather than sometimes being marked as 8bit. + - Issue #4265: shutil.copyfile() was leaking file descriptors when disk fills. Patch by Tres Seaver. From python-checkins at python.org Thu May 6 04:54:44 2010 From: python-checkins at python.org (brian.curtin) Date: Thu, 6 May 2010 04:54:44 +0200 (CEST) Subject: [Python-checkins] r80857 - python/trunk/Lib/platform.py Message-ID: <20100506025444.56E55F10A@mail.python.org> Author: brian.curtin Date: Thu May 6 04:54:44 2010 New Revision: 80857 Log: Fix #7863. Properly identify Windows 7 and Server 2008 R2. Removed various unused code and added a way to correctly determine server vs. workstation via the registry. Modified: python/trunk/Lib/platform.py Modified: python/trunk/Lib/platform.py ============================================================================== --- python/trunk/Lib/platform.py (original) +++ python/trunk/Lib/platform.py Thu May 6 04:54:44 2010 @@ -603,12 +603,19 @@ VER_PLATFORM_WIN32_WINDOWS = 1 VER_PLATFORM_WIN32_NT = 2 VER_NT_WORKSTATION = 1 + VER_NT_SERVER = 3 + REG_SZ = 1 # Find out the registry key and some general version infos - maj,min,buildno,plat,csd = GetVersionEx() + winver = GetVersionEx() + maj,min,buildno,plat,csd = winver version = '%i.%i.%i' % (maj,min,buildno & 0xFFFF) - if csd[:13] == 'Service Pack ': - csd = 'SP' + csd[13:] + if hasattr(winver, "service_pack"): + if winver.service_pack != "": + csd = 'SP%s' % winver.service_pack_major + else: + if csd[:13] == 'Service Pack ': + csd = 'SP' + csd[13:] if plat == VER_PLATFORM_WIN32_WINDOWS: regkey = 'SOFTWARE\\Microsoft\\Windows\\CurrentVersion' @@ -639,23 +646,33 @@ else: release = 'post2003' elif maj == 6: - if min == 0: - # Per http://msdn2.microsoft.com/en-us/library/ms724429.aspx + if hasattr(winver, "product_type"): + product_type = winver.product_type + else: + product_type = VER_NT_WORKSTATION + # Without an OSVERSIONINFOEX capable sys.getwindowsversion(), + # or help from the registry, we cannot properly identify + # non-workstation versions. try: - productType = GetVersionEx(1)[8] - except TypeError: - # sys.getwindowsversion() doesn't take any arguments, so - # we cannot detect 2008 Server that way. - # XXX Add some other means of detecting 2008 Server ?! + key = RegOpenKeyEx(HKEY_LOCAL_MACHINE, regkey) + name, type = RegQueryValueEx(key, "ProductName") + # Discard any type that isn't REG_SZ + if type == REG_SZ and name.find("Server") != -1: + product_type = VER_NT_SERVER + except WindowsError: + # Use default of VER_NT_WORKSTATION + pass + + if min == 0: + if product_type == VER_NT_WORKSTATION: release = 'Vista' else: - if productType == VER_NT_WORKSTATION: - release = 'Vista' - else: - release = '2008Server' - #elif min == 1: - # # Windows 7 release candidate uses version 6.1.7100 - # release = '7RC' + release = '2008Server' + elif min == 1: + if product_type == VER_NT_WORKSTATION: + release = '7' + else: + release = '2008ServerR2' else: release = 'post2008Server' From python-checkins at python.org Thu May 6 05:01:55 2010 From: python-checkins at python.org (brian.curtin) Date: Thu, 6 May 2010 05:01:55 +0200 (CEST) Subject: [Python-checkins] r80858 - in python/branches/release26-maint: Lib/platform.py Message-ID: <20100506030155.9442CEEA59@mail.python.org> Author: brian.curtin Date: Thu May 6 05:01:55 2010 New Revision: 80858 Log: Merged revisions 80857 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r80857 | brian.curtin | 2010-05-05 21:54:44 -0500 (Wed, 05 May 2010) | 5 lines Fix #7863. Properly identify Windows 7 and Server 2008 R2. Removed various unused code and added a way to correctly determine server vs. workstation via the registry. ........ Modified: python/branches/release26-maint/ (props changed) python/branches/release26-maint/Lib/platform.py Modified: python/branches/release26-maint/Lib/platform.py ============================================================================== --- python/branches/release26-maint/Lib/platform.py (original) +++ python/branches/release26-maint/Lib/platform.py Thu May 6 05:01:55 2010 @@ -596,12 +596,19 @@ VER_PLATFORM_WIN32_WINDOWS = 1 VER_PLATFORM_WIN32_NT = 2 VER_NT_WORKSTATION = 1 + VER_NT_SERVER = 3 + REG_SZ = 1 # Find out the registry key and some general version infos - maj,min,buildno,plat,csd = GetVersionEx() + winver = GetVersionEx() + maj,min,buildno,plat,csd = winver version = '%i.%i.%i' % (maj,min,buildno & 0xFFFF) - if csd[:13] == 'Service Pack ': - csd = 'SP' + csd[13:] + if hasattr(winver, "service_pack"): + if winver.service_pack != "": + csd = 'SP%s' % winver.service_pack_major + else: + if csd[:13] == 'Service Pack ': + csd = 'SP' + csd[13:] if plat == VER_PLATFORM_WIN32_WINDOWS: regkey = 'SOFTWARE\\Microsoft\\Windows\\CurrentVersion' # Try to guess the release name @@ -630,20 +637,33 @@ else: release = 'post2003' elif maj == 6: - if min == 0: - # Per http://msdn2.microsoft.com/en-us/library/ms724429.aspx + if hasattr(winver, "product_type"): + product_type = winver.product_type + else: + product_type = VER_NT_WORKSTATION + # Without an OSVERSIONINFOEX capable sys.getwindowsversion(), + # or help from the registry, we cannot properly identify + # non-workstation versions. try: - productType = GetVersionEx(1)[8] - except TypeError: - # sys.getwindowsversion() doesn't take any arguments, so - # we cannot detect 2008 Server that way. - # XXX Add some other means of detecting 2008 Server ?! + key = RegOpenKeyEx(HKEY_LOCAL_MACHINE, regkey) + name, type = RegQueryValueEx(key, "ProductName") + # Discard any type that isn't REG_SZ + if type == REG_SZ and name.find("Server") != -1: + product_type = VER_NT_SERVER + except WindowsError: + # Use default of VER_NT_WORKSTATION + pass + + if min == 0: + if product_type == VER_NT_WORKSTATION: release = 'Vista' else: - if productType == VER_NT_WORKSTATION: - release = 'Vista' - else: - release = '2008Server' + release = '2008Server' + elif min == 1: + if product_type == VER_NT_WORKSTATION: + release = '7' + else: + release = '2008ServerR2' else: release = 'post2008Server' else: From python-checkins at python.org Thu May 6 05:05:50 2010 From: python-checkins at python.org (brian.curtin) Date: Thu, 6 May 2010 05:05:50 +0200 (CEST) Subject: [Python-checkins] r80859 - in python/branches/py3k: Lib/platform.py Message-ID: <20100506030550.6208CEEA59@mail.python.org> Author: brian.curtin Date: Thu May 6 05:05:50 2010 New Revision: 80859 Log: Merged revisions 80857 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r80857 | brian.curtin | 2010-05-05 21:54:44 -0500 (Wed, 05 May 2010) | 5 lines Fix #7863. Properly identify Windows 7 and Server 2008 R2. Removed various unused code and added a way to correctly determine server vs. workstation via the registry. ........ Modified: python/branches/py3k/ (props changed) python/branches/py3k/Lib/platform.py Modified: python/branches/py3k/Lib/platform.py ============================================================================== --- python/branches/py3k/Lib/platform.py (original) +++ python/branches/py3k/Lib/platform.py Thu May 6 05:05:50 2010 @@ -601,12 +601,19 @@ VER_PLATFORM_WIN32_WINDOWS = 1 VER_PLATFORM_WIN32_NT = 2 VER_NT_WORKSTATION = 1 + VER_NT_SERVER = 3 + REG_SZ = 1 # Find out the registry key and some general version infos - maj,min,buildno,plat,csd = GetVersionEx() + winver = GetVersionEx() + maj,min,buildno,plat,csd = winver version = '%i.%i.%i' % (maj,min,buildno & 0xFFFF) - if csd[:13] == 'Service Pack ': - csd = 'SP' + csd[13:] + if hasattr(winver, "service_pack"): + if winver.service_pack != "": + csd = 'SP%s' % winver.service_pack_major + else: + if csd[:13] == 'Service Pack ': + csd = 'SP' + csd[13:] if plat == VER_PLATFORM_WIN32_WINDOWS: regkey = 'SOFTWARE\\Microsoft\\Windows\\CurrentVersion' @@ -637,23 +644,33 @@ else: release = 'post2003' elif maj == 6: - if min == 0: - # Per http://msdn2.microsoft.com/en-us/library/ms724429.aspx + if hasattr(winver, "product_type"): + product_type = winver.product_type + else: + product_type = VER_NT_WORKSTATION + # Without an OSVERSIONINFOEX capable sys.getwindowsversion(), + # or help from the registry, we cannot properly identify + # non-workstation versions. try: - productType = GetVersionEx(1)[8] - except TypeError: - # sys.getwindowsversion() doesn't take any arguments, so - # we cannot detect 2008 Server that way. - # XXX Add some other means of detecting 2008 Server ?! + key = RegOpenKeyEx(HKEY_LOCAL_MACHINE, regkey) + name, type = RegQueryValueEx(key, "ProductName") + # Discard any type that isn't REG_SZ + if type == REG_SZ and name.find("Server") != -1: + product_type = VER_NT_SERVER + except WindowsError: + # Use default of VER_NT_WORKSTATION + pass + + if min == 0: + if product_type == VER_NT_WORKSTATION: release = 'Vista' else: - if productType == VER_NT_WORKSTATION: - release = 'Vista' - else: - release = '2008Server' - #elif min == 1: - # # Windows 7 release candidate uses version 6.1.7100 - # release = '7RC' + release = '2008Server' + elif min == 1: + if product_type == VER_NT_WORKSTATION: + release = '7' + else: + release = '2008ServerR2' else: release = 'post2008Server' From python-checkins at python.org Thu May 6 05:09:10 2010 From: python-checkins at python.org (brian.curtin) Date: Thu, 6 May 2010 05:09:10 +0200 (CEST) Subject: [Python-checkins] r80860 - in python/branches/release31-maint: Lib/platform.py Message-ID: <20100506030910.375ADEEA75@mail.python.org> Author: brian.curtin Date: Thu May 6 05:09:10 2010 New Revision: 80860 Log: Merged revisions 80859 via svnmerge from svn+ssh://pythondev at svn.python.org/python/branches/py3k ................ r80859 | brian.curtin | 2010-05-05 22:05:50 -0500 (Wed, 05 May 2010) | 12 lines Merged revisions 80857 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r80857 | brian.curtin | 2010-05-05 21:54:44 -0500 (Wed, 05 May 2010) | 5 lines Fix #7863. Properly identify Windows 7 and Server 2008 R2. Removed various unused code and added a way to correctly determine server vs. workstation via the registry. ........ ................ Modified: python/branches/release31-maint/ (props changed) python/branches/release31-maint/Lib/platform.py Modified: python/branches/release31-maint/Lib/platform.py ============================================================================== --- python/branches/release31-maint/Lib/platform.py (original) +++ python/branches/release31-maint/Lib/platform.py Thu May 6 05:09:10 2010 @@ -576,12 +576,19 @@ VER_PLATFORM_WIN32_WINDOWS = 1 VER_PLATFORM_WIN32_NT = 2 VER_NT_WORKSTATION = 1 + VER_NT_SERVER = 3 + REG_SZ = 1 # Find out the registry key and some general version infos - maj,min,buildno,plat,csd = GetVersionEx() + winver = GetVersionEx() + maj,min,buildno,plat,csd = winver version = '%i.%i.%i' % (maj,min,buildno & 0xFFFF) - if csd[:13] == 'Service Pack ': - csd = 'SP' + csd[13:] + if hasattr(winver, "service_pack"): + if winver.service_pack != "": + csd = 'SP%s' % winver.service_pack_major + else: + if csd[:13] == 'Service Pack ': + csd = 'SP' + csd[13:] if plat == VER_PLATFORM_WIN32_WINDOWS: regkey = 'SOFTWARE\\Microsoft\\Windows\\CurrentVersion' # Try to guess the release name @@ -610,20 +617,33 @@ else: release = 'post2003' elif maj == 6: - if min == 0: - # Per http://msdn2.microsoft.com/en-us/library/ms724429.aspx + if hasattr(winver, "product_type"): + product_type = winver.product_type + else: + product_type = VER_NT_WORKSTATION + # Without an OSVERSIONINFOEX capable sys.getwindowsversion(), + # or help from the registry, we cannot properly identify + # non-workstation versions. try: - productType = GetVersionEx(1)[8] - except TypeError: - # sys.getwindowsversion() doesn't take any arguments, so - # we cannot detect 2008 Server that way. - # XXX Add some other means of detecting 2008 Server ?! + key = RegOpenKeyEx(HKEY_LOCAL_MACHINE, regkey) + name, type = RegQueryValueEx(key, "ProductName") + # Discard any type that isn't REG_SZ + if type == REG_SZ and name.find("Server") != -1: + product_type = VER_NT_SERVER + except WindowsError: + # Use default of VER_NT_WORKSTATION + pass + + if min == 0: + if product_type == VER_NT_WORKSTATION: release = 'Vista' else: - if productType == VER_NT_WORKSTATION: - release = 'Vista' - else: - release = '2008Server' + release = '2008Server' + elif min == 1: + if product_type == VER_NT_WORKSTATION: + release = '7' + else: + release = '2008ServerR2' else: release = 'post2008Server' else: From python-checkins at python.org Thu May 6 05:19:08 2010 From: python-checkins at python.org (jean-paul.calderone) Date: Thu, 6 May 2010 05:19:08 +0200 (CEST) Subject: [Python-checkins] r80861 - python/branches/signalfd-issue8407/Modules/signalmodule.c Message-ID: <20100506031908.87F7FEE9A9@mail.python.org> Author: jean-paul.calderone Date: Thu May 6 05:19:08 2010 New Revision: 80861 Log: Use pthread_sigmask if it is available and not broken Modified: python/branches/signalfd-issue8407/Modules/signalmodule.c Modified: python/branches/signalfd-issue8407/Modules/signalmodule.c ============================================================================== --- python/branches/signalfd-issue8407/Modules/signalmodule.c (original) +++ python/branches/signalfd-issue8407/Modules/signalmodule.c Thu May 6 05:19:08 2010 @@ -492,8 +492,13 @@ return 0; } +#if defined(HAVE_PTHREAD_SIGMASK) && !defined(HAVE_BROKEN_PTHREAD_SIGMASK) +# define PY_SIGMASK pthread_sigmask +#elif defined(HAVE_SIGPROCMASK) +# define PY_SIGMASK sigprocmask +#endif -#ifdef HAVE_SIGPROCMASK +#ifdef PY_SIGMASK static PyObject * signal_sigprocmask(PyObject *self, PyObject *args) { @@ -512,7 +517,7 @@ return NULL; } - if (sigprocmask(how, &mask, &previous) == -1) { + if (PY_SIGMASK(how, &mask, &previous) == -1) { PyOS_snprintf(how_buffer, sizeof(how_buffer), how_format, how); PyErr_SetString(PyExc_ValueError, how_buffer); return NULL; @@ -601,8 +606,10 @@ {"signal", signal_signal, METH_VARARGS, signal_doc}, {"getsignal", signal_getsignal, METH_VARARGS, getsignal_doc}, {"set_wakeup_fd", signal_set_wakeup_fd, METH_VARARGS, set_wakeup_fd_doc}, -#ifdef HAVE_SIGPROCMASK +#ifdef PY_SIGMASK {"sigprocmask", signal_sigprocmask, METH_VARARGS, sigprocmask_doc}, +/* It's no longer needed, so clean up the namespace. */ +#undef PY_SIGMASK #endif #ifdef HAVE_SIGNALFD {"signalfd", signal_signalfd, METH_VARARGS, signalfd_doc}, From python-checkins at python.org Thu May 6 05:25:50 2010 From: python-checkins at python.org (jean-paul.calderone) Date: Thu, 6 May 2010 05:25:50 +0200 (CEST) Subject: [Python-checkins] r80862 - python/branches/signalfd-issue8407/Doc/library/signal.rst Message-ID: <20100506032550.CE959EE9A2@mail.python.org> Author: jean-paul.calderone Date: Thu May 6 05:25:50 2010 New Revision: 80862 Log: Add a bunch of versionadded markers. Also drop the section about unspecified multithreading behavior. This should work in multithreaded apps now. Modified: python/branches/signalfd-issue8407/Doc/library/signal.rst Modified: python/branches/signalfd-issue8407/Doc/library/signal.rst ============================================================================== --- python/branches/signalfd-issue8407/Doc/library/signal.rst (original) +++ python/branches/signalfd-issue8407/Doc/library/signal.rst Thu May 6 05:25:50 2010 @@ -115,29 +115,40 @@ A possible value for the *how* parameter to :func:`sigprocmask` indicating that signals are to be blocked. + .. versionadded:: 2.7 + .. data:: SIG_UNBLOCK A possible value for the *how* parameter to :func:`sigprocmask` indicating that signals are to be unblocked. + .. versionadded:: 2.7 + .. data:: SIG_SETMASK A possible value for the *how* parameter to :func:`sigprocmask` indicating that the signal mask is to be replaced. + .. versionadded:: 2.7 + .. data:: SFD_CLOEXEC A possible flag in the *flags* parameter to :func:`signalfd` which causes the new file descriptor to be marked as close-on-exec. + .. versionadded:: 2.7 + + .. data:: SFD_NONBLOCK A possible flag in the *flags* parameter to :func:`signalfd` which causes the new file description to be set non-blocking. + .. versionadded:: 2.7 + The :mod:`signal` module defines one exception: @@ -272,7 +283,7 @@ *flags* is a bitvector which may include any :const:`signal.SFD_*` flag. - .. versionadded:: X.Y + .. versionadded:: 2.7 .. function:: sigprocmask(how, mask) @@ -291,10 +302,7 @@ *mask* is a list of signal numbers (eg :const:`signal.SIGUSR1`). - The behavior of this function in a multi-threaded program is unspecified. - See :func:`thread.sigmask` for multi-threaded uses. XXX - - .. versionadded:: X.Y + .. versionadded:: 2.7 .. _signal-example: From python-checkins at python.org Thu May 6 05:27:16 2010 From: python-checkins at python.org (jean-paul.calderone) Date: Thu, 6 May 2010 05:27:16 +0200 (CEST) Subject: [Python-checkins] r80863 - python/branches/signalfd-issue8407/Doc/library/signal.rst Message-ID: <20100506032716.0E4C6EE9A2@mail.python.org> Author: jean-paul.calderone Date: Thu May 6 05:27:15 2010 New Revision: 80863 Log: Point to the pthread_sigmask man page as well Modified: python/branches/signalfd-issue8407/Doc/library/signal.rst Modified: python/branches/signalfd-issue8407/Doc/library/signal.rst ============================================================================== --- python/branches/signalfd-issue8407/Doc/library/signal.rst (original) +++ python/branches/signalfd-issue8407/Doc/library/signal.rst Thu May 6 05:27:15 2010 @@ -289,7 +289,8 @@ .. function:: sigprocmask(how, mask) Set the signal mask for the process. The old signal mask is returned. - Availability: Unix (See the Unix man page :manpage:`sigprocmask(2)`.) + Availability: Unix (See the Unix man page :manpage:`sigprocmask(2)` and + :manpage:`pthread_sigmask(2)`.) If *how* is :const:`signal.SIG_BLOCK`, the signals in the mask are added to the set of blocked signals. From python-checkins at python.org Thu May 6 05:33:18 2010 From: python-checkins at python.org (jean-paul.calderone) Date: Thu, 6 May 2010 05:33:18 +0200 (CEST) Subject: [Python-checkins] r80864 - python/branches/signalfd-issue8407/Modules/signalmodule.c Message-ID: <20100506033318.6C027EE9AA@mail.python.org> Author: jean-paul.calderone Date: Thu May 6 05:33:18 2010 New Revision: 80864 Log: Check `how` ourselves; pthread_sigmask appears not to Modified: python/branches/signalfd-issue8407/Modules/signalmodule.c Modified: python/branches/signalfd-issue8407/Modules/signalmodule.c ============================================================================== --- python/branches/signalfd-issue8407/Modules/signalmodule.c (original) +++ python/branches/signalfd-issue8407/Modules/signalmodule.c Thu May 6 05:33:18 2010 @@ -506,6 +506,7 @@ char how_buffer[1024]; int how, sig; + int valid; PyObject *signals, *result, *signum; sigset_t mask, previous; @@ -517,7 +518,12 @@ return NULL; } - if (PY_SIGMASK(how, &mask, &previous) == -1) { + /* + * It seems that invalid values of how are not always discovered. + */ + valid = (how == SIG_BLOCK || how == SIG_UNBLOCK || how == SIG_SETMASK); + + if (!valid || PY_SIGMASK(how, &mask, &previous) == -1) { PyOS_snprintf(how_buffer, sizeof(how_buffer), how_format, how); PyErr_SetString(PyExc_ValueError, how_buffer); return NULL; From nnorwitz at gmail.com Thu May 6 12:20:03 2010 From: nnorwitz at gmail.com (Neal Norwitz) Date: Thu, 6 May 2010 06:20:03 -0400 Subject: [Python-checkins] Python Regression Test Failures refleak (1) Message-ID: <20100506102003.GA22514@kbk-i386-bb.psfb.org> More important issues: ---------------------- test_bz2 leaked [0, 0, 70] references, sum=70 Less important issues: ---------------------- test_threadsignals leaked [0, 0, -8] references, sum=-8 From python-checkins at python.org Thu May 6 12:48:46 2010 From: python-checkins at python.org (tarek.ziade) Date: Thu, 06 May 2010 12:48:46 +0200 Subject: [Python-checkins] distutils2: make sure we don't catch packages that are not in packages themselves. Message-ID: tarek.ziade pushed d56a79cf458c to distutils2: http://hg.python.org/distutils2/rev/d56a79cf458c changeset: 124:d56a79cf458c tag: tip user: Tarek Ziade date: Thu May 06 12:48:37 2010 +0200 summary: make sure we don't catch packages that are not in packages themselves. Otherwise we would catch accidentally stuff like packages created in build/ files: src/distutils2/tests/test_util.py, src/distutils2/util.py diff --git a/src/distutils2/tests/test_util.py b/src/distutils2/tests/test_util.py --- a/src/distutils2/tests/test_util.py +++ b/src/distutils2/tests/test_util.py @@ -270,7 +270,9 @@ # __init__ # pkg6 # __init__ - # pkg4 + # pkg4 <--- not a pkg + # pkg8 + # __init__ # pkg5 # __init__ # @@ -285,6 +287,8 @@ os.mkdir(os.path.join(pkg1, 'pkg3', 'pkg6')) self.write_file(os.path.join(pkg1, 'pkg3', 'pkg6', '__init__.py')) os.mkdir(os.path.join(pkg1, 'pkg4')) + os.mkdir(os.path.join(pkg1, 'pkg4', 'pkg8')) + self.write_file(os.path.join(pkg1, 'pkg4', 'pkg8', '__init__.py')) pkg5 = os.path.join(root, 'pkg5') os.mkdir(pkg5) self.write_file(os.path.join(pkg5, '__init__.py')) diff --git a/src/distutils2/util.py b/src/distutils2/util.py --- a/src/distutils2/util.py +++ b/src/distutils2/util.py @@ -550,9 +550,19 @@ return False return os.path.isfile(os.path.join(path, '__init__.py')) +def _under(path, root): + path = path.split(os.sep) + root = root.split(os.sep) + if len(root) > len(path): + return False + for pos, part in enumerate(root): + if path[pos] != part: + return False + return True + def _package_name(root_path, path): """Returns a dotted package name, given a subpath.""" - if not path.startswith(root_path): + if not _under(path, root_path): raise ValueError('"%s" is not a subpath of "%s"' % (path, root_path)) return path[len(root_path) + 1:].replace(os.sep, '.') @@ -569,15 +579,24 @@ of 'foo' (but not 'foo' itself). """ packages = [] + discarded = [] + def _discarded(path): + for discard in discarded: + if _under(path, discard): + return True + return False + for path in paths: path = convert_path(path) for root, dirs, files in os.walk(path): for dir_ in dirs: fullpath = os.path.join(root, dir_) + if _discarded(fullpath): + continue # we work only with Python packages if not _is_package(fullpath): + discarded.append(fullpath) continue - # see if it's excluded excluded = False package_name = _package_name(path, fullpath) -- Repository URL: http://hg.python.org/distutils2 From python-checkins at python.org Thu May 6 12:48:46 2010 From: python-checkins at python.org (tarek.ziade) Date: Thu, 06 May 2010 12:48:46 +0200 Subject: [Python-checkins] distutils2: added distutils2.util.find_packages Message-ID: tarek.ziade pushed 7c97f99f508b to distutils2: http://hg.python.org/distutils2/rev/7c97f99f508b changeset: 123:7c97f99f508b user: Tarek Ziade date: Thu May 06 12:05:44 2010 +0200 summary: added distutils2.util.find_packages files: src/CHANGES.txt, src/distutils2/tests/test_util.py, src/distutils2/util.py diff --git a/src/CHANGES.txt b/src/CHANGES.txt --- a/src/CHANGES.txt +++ b/src/CHANGES.txt @@ -5,6 +5,8 @@ 1.0a1 ----- -- Initial import from the stdlib +- Initial import from the stdlib [tarek] +- Added support for PEP 376 in distutils2.version [tarek] +- Added support for PEP 345 in distutils2.metadata [tarek] +- Added distutils2.util.find_package [tarek] - diff --git a/src/distutils2/tests/test_util.py b/src/distutils2/tests/test_util.py --- a/src/distutils2/tests/test_util.py +++ b/src/distutils2/tests/test_util.py @@ -14,7 +14,7 @@ check_environ, split_quoted, strtobool, rfc822_escape, get_compiler_versions, _find_exe_version, _MAC_OS_X_LD_VERSION, - byte_compile) + byte_compile, find_packages) from distutils2 import util from distutils2.tests import support @@ -32,7 +32,9 @@ self.stdout = StringIO(exes[self.cmd]) self.stderr = StringIO() -class UtilTestCase(support.EnvironGuard, unittest2.TestCase): +class UtilTestCase(support.EnvironGuard, + support.TempdirManager, + unittest2.TestCase): def setUp(self): super(UtilTestCase, self).setUp() @@ -257,6 +259,40 @@ self.assertRaises(DistutilsFileError, util.newer, 'xxx', 'xxx') + def test_find_packages(self): + # let's create a structure we want to scan: + # + # pkg1 + # __init__ + # pkg2 + # __init__ + # pkg3 + # __init__ + # pkg6 + # __init__ + # pkg4 + # pkg5 + # __init__ + # + root = self.mkdtemp() + pkg1 = os.path.join(root, 'pkg1') + os.mkdir(pkg1) + self.write_file(os.path.join(pkg1, '__init__.py')) + os.mkdir(os.path.join(pkg1, 'pkg2')) + self.write_file(os.path.join(pkg1, 'pkg2', '__init__.py')) + os.mkdir(os.path.join(pkg1, 'pkg3')) + self.write_file(os.path.join(pkg1, 'pkg3', '__init__.py')) + os.mkdir(os.path.join(pkg1, 'pkg3', 'pkg6')) + self.write_file(os.path.join(pkg1, 'pkg3', 'pkg6', '__init__.py')) + os.mkdir(os.path.join(pkg1, 'pkg4')) + pkg5 = os.path.join(root, 'pkg5') + os.mkdir(pkg5) + self.write_file(os.path.join(pkg5, '__init__.py')) + + res = find_packages([root], ['pkg1.pkg2']) + self.assertEquals(res, ['pkg1', 'pkg5', 'pkg1.pkg3', 'pkg1.pkg3.pkg6']) + + def test_suite(): return unittest2.makeSuite(UtilTestCase) diff --git a/src/distutils2/util.py b/src/distutils2/util.py --- a/src/distutils2/util.py +++ b/src/distutils2/util.py @@ -7,6 +7,7 @@ __revision__ = "$Id: util.py 77761 2010-01-26 22:46:15Z tarek.ziade $" import sys, os, string, re +from fnmatch import fnmatchcase from distutils2.errors import (DistutilsPlatformError, DistutilsFileError, DistutilsByteCompileError) @@ -543,3 +544,51 @@ f.write(line + "\n") f.close() +def _is_package(path): + """Returns True if path is a package (a dir with an __init__ file.""" + if not os.path.isdir(path): + return False + return os.path.isfile(os.path.join(path, '__init__.py')) + +def _package_name(root_path, path): + """Returns a dotted package name, given a subpath.""" + if not path.startswith(root_path): + raise ValueError('"%s" is not a subpath of "%s"' % (path, root_path)) + return path[len(root_path) + 1:].replace(os.sep, '.') + +def find_packages(paths=('.',), exclude=()): + """Return a list all Python packages found recursively within + directories 'paths' + + 'paths' should be supplied as a sequence of "cross-platform" + (i.e. URL-style) path; it will be converted to the appropriate local + path syntax. + + 'exclude' is a sequence of package names to exclude; '*' can be used as + a wildcard in the names, such that 'foo.*' will exclude all subpackages + of 'foo' (but not 'foo' itself). + """ + packages = [] + for path in paths: + path = convert_path(path) + for root, dirs, files in os.walk(path): + for dir_ in dirs: + fullpath = os.path.join(root, dir_) + # we work only with Python packages + if not _is_package(fullpath): + continue + + # see if it's excluded + excluded = False + package_name = _package_name(path, fullpath) + for pattern in exclude: + if fnmatchcase(package_name, pattern): + excluded = True + break + if excluded: + continue + + # adding it to the list + packages.append(package_name) + return packages + -- Repository URL: http://hg.python.org/distutils2 From python-checkins at python.org Thu May 6 13:28:46 2010 From: python-checkins at python.org (tarek.ziade) Date: Thu, 06 May 2010 13:28:46 +0200 Subject: [Python-checkins] distutils2: now setup.py uses PEP 345-style fields Message-ID: tarek.ziade pushed 460814489712 to distutils2: http://hg.python.org/distutils2/rev/460814489712 changeset: 126:460814489712 tag: tip user: Tarek Ziade date: Thu May 06 13:28:35 2010 +0200 summary: now setup.py uses PEP 345-style fields files: src/README.txt, src/setup.py diff --git a/src/README.txt b/src/README.txt --- a/src/README.txt +++ b/src/README.txt @@ -1,5 +1,8 @@ -====== -README -====== +========== +Distutils2 +========== +Welcome to Distutils2 ! + + diff --git a/src/setup.py b/src/setup.py --- a/src/setup.py +++ b/src/setup.py @@ -8,6 +8,7 @@ from distutils2.command.sdist import sdist from distutils2.command.install import install from distutils2 import __version__ as VERSION +from distutils2.util import find_packages f = open('README.txt') try: @@ -67,18 +68,28 @@ if sys.version < '2.6': setup_kwargs['scripts'] = ['distutils2/mkpkg.py'] +_CLASSIFIERS = """\ +Development Status :: 3 - Alpha +Intended Audience :: Developers +License :: OSI Approved :: Python Software Foundation License +Operating System :: OS Independent +Programming Language :: Python +Topic :: Software Development :: Libraries :: Python Modules +Topic :: System :: Archiving :: Packaging +Topic :: System :: Systems Administration +Topic :: Utilities""" + setup (name="Distutils2", version=VERSION, - description="Python Distribution Utilities", + summary="Python Distribution Utilities", + keywords=['packaging', 'distutils'], author="Tarek Ziade", author_email="tarek at ziade.org", - url="http://www.python.org/sigs/distutils-sig", + home_page="http://www.python.org/sigs/distutils-sig", license="PSF", - long_description=README, - packages=['distutils2', - 'distutils2.command', - 'distutils2.tests', - 'distutils2._backport'], + description=README, + classifier=_CLASSIFIERS.split('\n'), + packages=find_packages(), cmdclass={'sdist': sdist_hg, 'install': install_hg}, package_data={'distutils2._backport': ['sysconfig.cfg']}, **setup_kwargs -- Repository URL: http://hg.python.org/distutils2 From python-checkins at python.org Thu May 6 13:28:46 2010 From: python-checkins at python.org (tarek.ziade) Date: Thu, 06 May 2010 13:28:46 +0200 Subject: [Python-checkins] distutils2: make sure 1.2 is picked when a 1.1 or 1.2 field is encoutered Message-ID: tarek.ziade pushed 09e726d8a111 to distutils2: http://hg.python.org/distutils2/rev/09e726d8a111 changeset: 125:09e726d8a111 user: Tarek Ziade date: Thu May 06 13:28:08 2010 +0200 summary: make sure 1.2 is picked when a 1.1 or 1.2 field is encoutered files: src/distutils2/metadata.py, src/distutils2/tests/test_metadata.py diff --git a/src/distutils2/metadata.py b/src/distutils2/metadata.py --- a/src/distutils2/metadata.py +++ b/src/distutils2/metadata.py @@ -103,20 +103,44 @@ if marker in keys: return True return False + keys = fields.keys() - is_1_1 = _has_marker(keys, _314_MARKERS) - is_1_2 = _has_marker(keys, _345_MARKERS) + possible_versions = ['1.0', '1.1', '1.2'] + + + # first let's try to see if a field is not part of one of the version + for key in keys: + if key not in _241_FIELDS and '1.0' in possible_versions: + possible_versions.remove('1.0') + if key not in _314_FIELDS and '1.1' in possible_versions: + possible_versions.remove('1.1') + if key not in _345_FIELDS and '1.2' in possible_versions: + possible_versions.remove('1.2') + + # possible_version contains qualified versions + if len(possible_versions) == 1: + return possible_versions[0] # found ! + elif len(possible_versions) == 0: + raise MetadataConflictError('Unknown metadata set') + + # let's see if one unique marker is found + is_1_1 = '1.1' in possible_versions and _has_marker(keys, _314_MARKERS) + is_1_2 = '1.2' in possible_versions and _has_marker(keys, _345_MARKERS) if is_1_1 and is_1_2: - raise MetadataConflictError('You used both 1.1 and 1.2 fields') + raise MetadataConflictError('You used incompatible 1.1 and 1.2 fields') # we have the choice, either 1.0, or 1.2 # - 1.0 has a broken Summary field but work with all tools # - 1.1 is to avoid # - 1.2 fixes Summary but is not spreaded yet if not is_1_1 and not is_1_2: - return PKG_INFO_PREFERRED_VERSION + # we couldn't find any specific marker + if PKG_INFO_PREFERRED_VERSION in possible_versions: + return PKG_INFO_PREFERRED_VERSION if is_1_1: return '1.1' + + # default marker when 1.0 is disqualified return '1.2' _ATTR2FIELD = {'metadata_version': 'Metadata-Version', diff --git a/src/distutils2/tests/test_metadata.py b/src/distutils2/tests/test_metadata.py --- a/src/distutils2/tests/test_metadata.py +++ b/src/distutils2/tests/test_metadata.py @@ -4,7 +4,8 @@ import sys from StringIO import StringIO -from distutils2.metadata import DistributionMetadata, _interpret +from distutils2.metadata import (DistributionMetadata, _interpret, + PKG_INFO_PREFERRED_VERSION) class DistributionMetadataTestCase(unittest2.TestCase): @@ -200,6 +201,12 @@ self.assertEquals(missing, ['Name', 'Home-page']) self.assertEquals(len(warnings), 2) + def test_best_choice(self): + metadata = DistributionMetadata() + metadata['Version'] = '1.0' + self.assertEquals(metadata.version, PKG_INFO_PREFERRED_VERSION) + metadata['Classifier'] = ['ok'] + self.assertEquals(metadata.version, '1.2') def test_suite(): return unittest2.makeSuite(DistributionMetadataTestCase) -- Repository URL: http://hg.python.org/distutils2 From python-checkins at python.org Thu May 6 14:06:33 2010 From: python-checkins at python.org (antoine.pitrou) Date: Thu, 6 May 2010 14:06:33 +0200 (CEST) Subject: [Python-checkins] r80865 - sandbox/trunk/untabify/untabify.py Message-ID: <20100506120633.1860EEE994@mail.python.org> Author: antoine.pitrou Date: Thu May 6 14:06:32 2010 New Revision: 80865 Log: Add a note that the script also removes trailing whitespace Modified: sandbox/trunk/untabify/untabify.py Modified: sandbox/trunk/untabify/untabify.py ============================================================================== --- sandbox/trunk/untabify/untabify.py (original) +++ sandbox/trunk/untabify/untabify.py Thu May 6 14:06:32 2010 @@ -10,6 +10,7 @@ Notes: +- this script also removes trailing whitespace on processed files - only whitespace is added/removed, therefore compilation can't be broken. - only run on files really using tab indent; this shouldn't be run on files From dickinsm at gmail.com Thu May 6 14:11:55 2010 From: dickinsm at gmail.com (Mark Dickinson) Date: Thu, 6 May 2010 13:11:55 +0100 Subject: [Python-checkins] r80809 - python/trunk/Objects/floatobject.c In-Reply-To: <20100505201609.5D92EF68D2@mail.python.org> References: <20100505201609.5D92EF68D2@mail.python.org> Message-ID: On Wed, May 5, 2010 at 9:16 PM, brett.cannon wrote: > Author: brett.cannon > Date: Wed May ?5 22:16:09 2010 > New Revision: 80809 > > Log: > Remove an unneeded variable increment. > > Found using Clang's static analyzer. > > > Modified: > ? python/trunk/Objects/floatobject.c > > Modified: python/trunk/Objects/floatobject.c > ============================================================================== > --- python/trunk/Objects/floatobject.c ?(original) > +++ python/trunk/Objects/floatobject.c ?Wed May ?5 22:16:09 2010 > @@ -2478,7 +2478,6 @@ > > ? ? ? ? ? ? ? ?/* Eighth byte */ > ? ? ? ? ? ? ? ?*p = flo & 0xFF; > - ? ? ? ? ? ? ? p += incr; > > ? ? ? ? ? ? ? ?/* Done */ > ? ? ? ? ? ? ? ?return 0; At the risk of bikeshedding, it's not clear to me that making changes like this is necessarily a Good Thing. In this case, it means (a) treating the last byte of the packed float differently from the first 7, and (b) breaking an invariant that held previously---namely that at the end of that section of code, p points just past the last byte written. Clearly these are very minor issues, and don't affect correctness in this case. But I'd argue that similar changes elsewhere could adversely affect future maintenance and/or code readability, albeit to a tiny degree. IOW, redundancy isn't always a bad thing, especially if it aids comprehension for the human code reader. From eric at trueblade.com Thu May 6 14:32:31 2010 From: eric at trueblade.com (Eric Smith) Date: Thu, 06 May 2010 08:32:31 -0400 Subject: [Python-checkins] r80809 - python/trunk/Objects/floatobject.c In-Reply-To: References: <20100505201609.5D92EF68D2@mail.python.org> Message-ID: <4BE2B6DF.6030901@trueblade.com> Mark Dickinson wrote: > On Wed, May 5, 2010 at 9:16 PM, brett.cannon wrote: >> Author: brett.cannon >> Date: Wed May 5 22:16:09 2010 >> New Revision: 80809 >> >> Log: >> Remove an unneeded variable increment. >> >> Found using Clang's static analyzer. >> >> >> Modified: >> python/trunk/Objects/floatobject.c >> >> Modified: python/trunk/Objects/floatobject.c >> ============================================================================== >> --- python/trunk/Objects/floatobject.c (original) >> +++ python/trunk/Objects/floatobject.c Wed May 5 22:16:09 2010 >> @@ -2478,7 +2478,6 @@ >> >> /* Eighth byte */ >> *p = flo & 0xFF; >> - p += incr; >> >> /* Done */ >> return 0; > > At the risk of bikeshedding, it's not clear to me that making changes > like this is necessarily a Good Thing. In this case, it means (a) > treating the last byte of the packed float differently from the first > 7, and (b) breaking an invariant that held previously---namely that at > the end of that section of code, p points just past the last byte > written. Clearly these are very minor issues, and don't affect > correctness in this case. But I'd argue that similar changes > elsewhere could adversely affect future maintenance and/or code > readability, albeit to a tiny degree. > > IOW, redundancy isn't always a bad thing, especially if it aids > comprehension for the human code reader. I agree. I often leave pointers positioned at the next insertion point in a buffer, in case I later add code that again inserts into the buffer. Surely compilers will optimize this away. -- Eric. From python-checkins at python.org Thu May 6 15:03:39 2010 From: python-checkins at python.org (andrew.kuchling) Date: Thu, 6 May 2010 15:03:39 +0200 (CEST) Subject: [Python-checkins] r80866 - python/trunk/Doc/library/_winreg.rst Message-ID: <20100506130339.AA530EEA12@mail.python.org> Author: andrew.kuchling Date: Thu May 6 15:03:39 2010 New Revision: 80866 Log: Use anonymous hyperlinks Modified: python/trunk/Doc/library/_winreg.rst Modified: python/trunk/Doc/library/_winreg.rst ============================================================================== --- python/trunk/Doc/library/_winreg.rst (original) +++ python/trunk/Doc/library/_winreg.rst Thu May 6 15:03:39 2010 @@ -84,7 +84,7 @@ *sam* is an integer that specifies an access mask that describes the desired security access for the key. Default is :const:`KEY_ALL_ACCESS`. See the `Win32 documentation - `_ for + `__ for other allowed values. @@ -136,7 +136,7 @@ *sam* is an integer that specifies an access mask that describes the desired security access for the key. Default is :const:`KEY_WOW64_64KEY`. See the `Win32 documentation - `_ for + `__ for other allowed values. @@ -252,7 +252,7 @@ A call to :func:`LoadKey` fails if the calling process does not have the :const:`SE_RESTORE_PRIVILEGE` privilege. Note that privileges are different from permissions -- see the `Win32 documentation - `_ for + `__ for more details. If *key* is a handle returned by :func:`ConnectRegistry`, then the path @@ -273,7 +273,7 @@ *sam* is an integer that specifies an access mask that describes the desired security access for the key. Default is :const:`KEY_READ`. See the `Win32 documentation - `_ for + `__ for other allowed values. The result is a new handle to the specified key. From python-checkins at python.org Thu May 6 15:07:34 2010 From: python-checkins at python.org (tarek.ziade) Date: Thu, 06 May 2010 15:07:34 +0200 Subject: [Python-checkins] distutils2: make sure project_url is correctly serialized Message-ID: tarek.ziade pushed 550491a6e271 to distutils2: http://hg.python.org/distutils2/rev/550491a6e271 changeset: 127:550491a6e271 tag: tip user: Tarek Ziade date: Thu May 06 15:07:29 2010 +0200 summary: make sure project_url is correctly serialized files: src/distutils2/metadata.py, src/distutils2/tests/test_metadata.py diff --git a/src/distutils2/metadata.py b/src/distutils2/metadata.py --- a/src/distutils2/metadata.py +++ b/src/distutils2/metadata.py @@ -293,6 +293,8 @@ if field in _LISTFIELDS: # we can have multiple lines values = msg.get_all(field) + if field in _LISTTUPLEFIELDS and values is not None: + values = [tuple(value.split(',')) for value in values] self.set(field, values) else: # single line @@ -323,6 +325,9 @@ values = values.replace('\n', '\n |') values = [values] + if field in _LISTTUPLEFIELDS: + values = [','.join(value) for value in values] + for value in values: self._write_field(fileobject, field, value) diff --git a/src/distutils2/tests/test_metadata.py b/src/distutils2/tests/test_metadata.py --- a/src/distutils2/tests/test_metadata.py +++ b/src/distutils2/tests/test_metadata.py @@ -208,6 +208,25 @@ metadata['Classifier'] = ['ok'] self.assertEquals(metadata.version, '1.2') + def test_project_urls(self): + # project-url is a bit specific, make sure we write it + # properly in PKG-INFO + metadata = DistributionMetadata() + metadata['Version'] = '1.0' + metadata['Project-Url'] = [('one', 'http://ok')] + self.assertEquals(metadata['Project-Url'], [('one', 'http://ok')]) + file_ = StringIO() + metadata.write_file(file_) + file_.seek(0) + res = file_.read().split('\n') + self.assertIn('Project-URL: one,http://ok', res) + + file_.seek(0) + metadata = DistributionMetadata() + metadata.read_file(file_) + self.assertEquals(metadata['Project-Url'], [('one', 'http://ok')]) + + def test_suite(): return unittest2.makeSuite(DistributionMetadataTestCase) -- Repository URL: http://hg.python.org/distutils2 From python-checkins at python.org Thu May 6 15:08:21 2010 From: python-checkins at python.org (tarek.ziade) Date: Thu, 06 May 2010 15:08:21 +0200 Subject: [Python-checkins] distutils2: added some project urls Message-ID: tarek.ziade pushed 948e6fb09655 to distutils2: http://hg.python.org/distutils2/rev/948e6fb09655 changeset: 128:948e6fb09655 tag: tip user: Tarek Ziade date: Thu May 06 15:08:13 2010 +0200 summary: added some project urls files: src/setup.py diff --git a/src/setup.py b/src/setup.py --- a/src/setup.py +++ b/src/setup.py @@ -85,13 +85,19 @@ keywords=['packaging', 'distutils'], author="Tarek Ziade", author_email="tarek at ziade.org", - home_page="http://www.python.org/sigs/distutils-sig", + home_page="http://bitbucket.org/tarek/distutils2/wiki/Home", license="PSF", description=README, classifier=_CLASSIFIERS.split('\n'), packages=find_packages(), cmdclass={'sdist': sdist_hg, 'install': install_hg}, package_data={'distutils2._backport': ['sysconfig.cfg']}, + project_url=[('Mailing-list', + 'http://mail.python.org/mailman/listinfo/distutils-sig/'), + ('Documentation', + 'http://bitbucket.org/tarek/distutils2/wiki/Home'), + ('Repository', 'http://hg.python.org/distutils2'), + ('Bug tracker', 'http://bugs.python.org')], **setup_kwargs ) -- Repository URL: http://hg.python.org/distutils2 From python-checkins at python.org Thu May 6 15:15:26 2010 From: python-checkins at python.org (tarek.ziade) Date: Thu, 06 May 2010 15:15:26 +0200 Subject: [Python-checkins] distutils2: doc page points to packages.python.org now Message-ID: tarek.ziade pushed 5847fb2b7549 to distutils2: http://hg.python.org/distutils2/rev/5847fb2b7549 changeset: 129:5847fb2b7549 tag: tip user: Tarek Ziade date: Thu May 06 15:13:16 2010 +0200 summary: doc page points to packages.python.org now files: src/README.txt, src/setup.py diff --git a/src/README.txt b/src/README.txt --- a/src/README.txt +++ b/src/README.txt @@ -4,5 +4,12 @@ Welcome to Distutils2 ! +Distutils2 is the new version of Distutils. It's not backward compatible with +Distutils but provides more features, and implement most new packaging +standards. +See the documentation at http://packages.python.org/distutils2 for more info. +**Beware that Distutils2 is its in early stage and should not be used in +production. Its API is subject to changes** + diff --git a/src/setup.py b/src/setup.py --- a/src/setup.py +++ b/src/setup.py @@ -95,7 +95,7 @@ project_url=[('Mailing-list', 'http://mail.python.org/mailman/listinfo/distutils-sig/'), ('Documentation', - 'http://bitbucket.org/tarek/distutils2/wiki/Home'), + 'http://packages.python.org/distutils2'), ('Repository', 'http://hg.python.org/distutils2'), ('Bug tracker', 'http://bugs.python.org')], **setup_kwargs -- Repository URL: http://hg.python.org/distutils2 From python-checkins at python.org Thu May 6 15:15:58 2010 From: python-checkins at python.org (tarek.ziade) Date: Thu, 06 May 2010 15:15:58 +0200 Subject: [Python-checkins] distutils2: Added tag 1.0a1 for changeset 5847fb2b7549 Message-ID: tarek.ziade pushed f89fe926df9f to distutils2: http://hg.python.org/distutils2/rev/f89fe926df9f changeset: 130:f89fe926df9f tag: tip user: Tarek Ziade date: Thu May 06 15:15:43 2010 +0200 summary: Added tag 1.0a1 for changeset 5847fb2b7549 files: .hgtags diff --git a/.hgtags b/.hgtags new file mode 100644 --- /dev/null +++ b/.hgtags @@ -0,0 +1,1 @@ +5847fb2b7549fb301882c1054eb8b3d0893e3570 1.0a1 -- Repository URL: http://hg.python.org/distutils2 From python-checkins at python.org Thu May 6 15:19:01 2010 From: python-checkins at python.org (tarek.ziade) Date: Thu, 06 May 2010 15:19:01 +0200 Subject: [Python-checkins] distutils2: starting 1.0a2 Message-ID: tarek.ziade pushed 8a826f49ee98 to distutils2: http://hg.python.org/distutils2/rev/8a826f49ee98 changeset: 131:8a826f49ee98 tag: tip user: Tarek Ziade date: Thu May 06 15:18:55 2010 +0200 summary: starting 1.0a2 files: src/CHANGES.txt, src/distutils2/__init__.py diff --git a/src/CHANGES.txt b/src/CHANGES.txt --- a/src/CHANGES.txt +++ b/src/CHANGES.txt @@ -2,8 +2,13 @@ CHANGES ======= -1.0a1 ------ +1.0a2 - ? +-------- + +- + +1.0a1 - 2010-05-06 +------------------ - Initial import from the stdlib [tarek] - Added support for PEP 376 in distutils2.version [tarek] diff --git a/src/distutils2/__init__.py b/src/distutils2/__init__.py --- a/src/distutils2/__init__.py +++ b/src/distutils2/__init__.py @@ -10,7 +10,7 @@ __all__ = ['__version__', 'setup'] __revision__ = "$Id: __init__.py 78020 2010-02-06 16:37:32Z benjamin.peterson $" -__version__ = "1.0a1" +__version__ = "1.0a2" from distutils2.core import setup -- Repository URL: http://hg.python.org/distutils2 From python-checkins at python.org Thu May 6 15:25:55 2010 From: python-checkins at python.org (tarek.ziade) Date: Thu, 06 May 2010 15:25:55 +0200 Subject: [Python-checkins] distutils2: fixed the documentation URL Message-ID: tarek.ziade pushed ea54c5f7ddc5 to distutils2: http://hg.python.org/distutils2/rev/ea54c5f7ddc5 changeset: 132:ea54c5f7ddc5 tag: tip user: Tarek Ziade date: Thu May 06 15:25:43 2010 +0200 summary: fixed the documentation URL files: src/setup.py diff --git a/src/setup.py b/src/setup.py --- a/src/setup.py +++ b/src/setup.py @@ -95,7 +95,7 @@ project_url=[('Mailing-list', 'http://mail.python.org/mailman/listinfo/distutils-sig/'), ('Documentation', - 'http://packages.python.org/distutils2'), + 'http://packages.python.org/Distutils2'), ('Repository', 'http://hg.python.org/distutils2'), ('Bug tracker', 'http://bugs.python.org')], **setup_kwargs -- Repository URL: http://hg.python.org/distutils2 From ncoghlan at gmail.com Thu May 6 15:27:01 2010 From: ncoghlan at gmail.com (Nick Coghlan) Date: Thu, 06 May 2010 23:27:01 +1000 Subject: [Python-checkins] r80854 - python/trunk/Doc/whatsnew/2.7.rst In-Reply-To: <20100506011056.51811EEA2A@mail.python.org> References: <20100506011056.51811EEA2A@mail.python.org> Message-ID: <4BE2C3A5.6080005@gmail.com> andrew.kuchling wrote: > +* New function: :func:`~runpy.run_path` in the :mod:`runpy` module > + will execute the code at a provided *path* argument. *path* can be > + the path of a Python source file (:file:`example.py`), a compiled > + bytecode file (:file:`example.pyc`), a directory > + (:file:`./package/'), or a zip archive (:file:`example.zip`). If a > + directory or zip path is provided, it will be added to the front of > + ``sys.path`` and the module :mod:`__main__` will be imported. It's > + expected that the directory or zip contains a :file:`__main__.py`; > + if it doesn't, some other :file:`__main__.py` might be imported from > + a location later in ``sys.path``. This makes some of the machinery > + of :mod:`runpy` available to scripts that want to mimic the behaviour > + of Python's :option:`-m` switch. (Added by Nick Coghlan; > + :issue:`6816`.) -m (or, more accurately, it's very close cousin) is already available through runpy.run_module(). The new function is to make it easier to mimic the way the command line processes an explicit path name (most notably, the zipfile/directory execution stuff that was added in 2.6). Cheers, Nick. -- Nick Coghlan | ncoghlan at gmail.com | Brisbane, Australia --------------------------------------------------------------- From python-checkins at python.org Thu May 6 15:32:36 2010 From: python-checkins at python.org (tarek.ziade) Date: Thu, 06 May 2010 15:32:36 +0200 Subject: [Python-checkins] distutils2: fixed link Message-ID: tarek.ziade pushed d519643faee6 to distutils2: http://hg.python.org/distutils2/rev/d519643faee6 changeset: 133:d519643faee6 tag: tip user: Tarek Ziade date: Thu May 06 15:32:31 2010 +0200 summary: fixed link files: src/README.txt diff --git a/src/README.txt b/src/README.txt --- a/src/README.txt +++ b/src/README.txt @@ -8,7 +8,7 @@ Distutils but provides more features, and implement most new packaging standards. -See the documentation at http://packages.python.org/distutils2 for more info. +See the documentation at http://packages.python.org/Distutils2 for more info. **Beware that Distutils2 is its in early stage and should not be used in production. Its API is subject to changes** -- Repository URL: http://hg.python.org/distutils2 From python-checkins at python.org Thu May 6 15:49:10 2010 From: python-checkins at python.org (antoine.pitrou) Date: Thu, 6 May 2010 15:49:10 +0200 (CEST) Subject: [Python-checkins] r80867 - in python/branches/release26-maint: Lib/test/test_ssl.py Misc/NEWS Message-ID: <20100506134910.B6B92EE98D@mail.python.org> Author: antoine.pitrou Date: Thu May 6 15:49:10 2010 New Revision: 80867 Log: Issue #8629: Disable some test_ssl tests, since they give different results with OpenSSL 1.0.0 and higher. Modified: python/branches/release26-maint/Lib/test/test_ssl.py python/branches/release26-maint/Misc/NEWS Modified: python/branches/release26-maint/Lib/test/test_ssl.py ============================================================================== --- python/branches/release26-maint/Lib/test/test_ssl.py (original) +++ python/branches/release26-maint/Lib/test/test_ssl.py Thu May 6 15:49:10 2010 @@ -716,7 +716,7 @@ raise else: if not expect_success: - self.fail( + raise AssertionError( "Client protocol %s succeeded with server protocol %s!" % (ssl.get_protocol_name(client_protocol), ssl.get_protocol_name(server_protocol))) @@ -832,7 +832,9 @@ def test_protocol_sslv2(self): """Connecting to an SSLv2 server with various client options""" if test_support.verbose: - sys.stdout.write("\n") + sys.stdout.write("\ntest_protocol_sslv2 disabled, " + "as it fails on OpenSSL 1.0.0+") + return try_protocol_combo(ssl.PROTOCOL_SSLv2, ssl.PROTOCOL_SSLv2, True) try_protocol_combo(ssl.PROTOCOL_SSLv2, ssl.PROTOCOL_SSLv2, True, ssl.CERT_OPTIONAL) try_protocol_combo(ssl.PROTOCOL_SSLv2, ssl.PROTOCOL_SSLv2, True, ssl.CERT_REQUIRED) @@ -843,7 +845,9 @@ def test_protocol_sslv23(self): """Connecting to an SSLv23 server with various client options""" if test_support.verbose: - sys.stdout.write("\n") + sys.stdout.write("\ntest_protocol_sslv23 disabled, " + "as it fails on OpenSSL 1.0.0+") + return try: try_protocol_combo(ssl.PROTOCOL_SSLv23, ssl.PROTOCOL_SSLv2, True) except (ssl.SSLError, socket.error), x: @@ -867,7 +871,9 @@ def test_protocol_sslv3(self): """Connecting to an SSLv3 server with various client options""" if test_support.verbose: - sys.stdout.write("\n") + sys.stdout.write("\ntest_protocol_sslv3 disabled, " + "as it fails on OpenSSL 1.0.0+") + return try_protocol_combo(ssl.PROTOCOL_SSLv3, ssl.PROTOCOL_SSLv3, True) try_protocol_combo(ssl.PROTOCOL_SSLv3, ssl.PROTOCOL_SSLv3, True, ssl.CERT_OPTIONAL) try_protocol_combo(ssl.PROTOCOL_SSLv3, ssl.PROTOCOL_SSLv3, True, ssl.CERT_REQUIRED) @@ -878,7 +884,9 @@ def test_protocol_tlsv1(self): """Connecting to a TLSv1 server with various client options""" if test_support.verbose: - sys.stdout.write("\n") + sys.stdout.write("\ntest_protocol_tlsv1 disabled, " + "as it fails on OpenSSL 1.0.0+") + return try_protocol_combo(ssl.PROTOCOL_TLSv1, ssl.PROTOCOL_TLSv1, True) try_protocol_combo(ssl.PROTOCOL_TLSv1, ssl.PROTOCOL_TLSv1, True, ssl.CERT_OPTIONAL) try_protocol_combo(ssl.PROTOCOL_TLSv1, ssl.PROTOCOL_TLSv1, True, ssl.CERT_REQUIRED) Modified: python/branches/release26-maint/Misc/NEWS ============================================================================== --- python/branches/release26-maint/Misc/NEWS (original) +++ python/branches/release26-maint/Misc/NEWS Thu May 6 15:49:10 2010 @@ -164,6 +164,9 @@ Tests ----- +- Issue #8629: Disable some test_ssl tests, since they give different + results with OpenSSL 1.0.0 and higher. + - Issue #8576: Remove use of find_unused_port() in test_smtplib and test_multiprocessing. Patch by Paul Moore. From python-checkins at python.org Thu May 6 15:54:43 2010 From: python-checkins at python.org (antoine.pitrou) Date: Thu, 6 May 2010 15:54:43 +0200 (CEST) Subject: [Python-checkins] r80868 - in python/branches/release31-maint: Lib/test/test_ssl.py Misc/NEWS Message-ID: <20100506135443.DCD8BEEA79@mail.python.org> Author: antoine.pitrou Date: Thu May 6 15:54:43 2010 New Revision: 80868 Log: Issue #8629: Disable some test_ssl tests, since they give different results with OpenSSL 1.0.0 and higher. Modified: python/branches/release31-maint/Lib/test/test_ssl.py python/branches/release31-maint/Misc/NEWS Modified: python/branches/release31-maint/Lib/test/test_ssl.py ============================================================================== --- python/branches/release31-maint/Lib/test/test_ssl.py (original) +++ python/branches/release31-maint/Lib/test/test_ssl.py Thu May 6 15:54:43 2010 @@ -711,7 +711,7 @@ raise else: if not expect_success: - self.fail( + raise AssertionError( "Client protocol %s succeeded with server protocol %s!" % (ssl.get_protocol_name(client_protocol), ssl.get_protocol_name(server_protocol))) @@ -827,7 +827,9 @@ def test_protocol_sslv2(self): """Connecting to an SSLv2 server with various client options""" if support.verbose: - sys.stdout.write("\n") + sys.stdout.write("\ntest_protocol_sslv2 disabled, " + "as it fails on OpenSSL 1.0.0+") + return try_protocol_combo(ssl.PROTOCOL_SSLv2, ssl.PROTOCOL_SSLv2, True) try_protocol_combo(ssl.PROTOCOL_SSLv2, ssl.PROTOCOL_SSLv2, True, ssl.CERT_OPTIONAL) try_protocol_combo(ssl.PROTOCOL_SSLv2, ssl.PROTOCOL_SSLv2, True, ssl.CERT_REQUIRED) @@ -838,7 +840,9 @@ def test_protocol_sslv23(self): """Connecting to an SSLv23 server with various client options""" if support.verbose: - sys.stdout.write("\n") + sys.stdout.write("\ntest_protocol_sslv23 disabled, " + "as it fails on OpenSSL 1.0.0+") + return try: try_protocol_combo(ssl.PROTOCOL_SSLv23, ssl.PROTOCOL_SSLv2, True) except (ssl.SSLError, socket.error) as x: @@ -862,7 +866,9 @@ def test_protocol_sslv3(self): """Connecting to an SSLv3 server with various client options""" if support.verbose: - sys.stdout.write("\n") + sys.stdout.write("\ntest_protocol_sslv3 disabled, " + "as it fails on OpenSSL 1.0.0+") + return try_protocol_combo(ssl.PROTOCOL_SSLv3, ssl.PROTOCOL_SSLv3, True) try_protocol_combo(ssl.PROTOCOL_SSLv3, ssl.PROTOCOL_SSLv3, True, ssl.CERT_OPTIONAL) try_protocol_combo(ssl.PROTOCOL_SSLv3, ssl.PROTOCOL_SSLv3, True, ssl.CERT_REQUIRED) @@ -873,7 +879,9 @@ def test_protocol_tlsv1(self): """Connecting to a TLSv1 server with various client options""" if support.verbose: - sys.stdout.write("\n") + sys.stdout.write("\ntest_protocol_tlsv1 disabled, " + "as it fails on OpenSSL 1.0.0+") + return try_protocol_combo(ssl.PROTOCOL_TLSv1, ssl.PROTOCOL_TLSv1, True) try_protocol_combo(ssl.PROTOCOL_TLSv1, ssl.PROTOCOL_TLSv1, True, ssl.CERT_OPTIONAL) try_protocol_combo(ssl.PROTOCOL_TLSv1, ssl.PROTOCOL_TLSv1, True, ssl.CERT_REQUIRED) Modified: python/branches/release31-maint/Misc/NEWS ============================================================================== --- python/branches/release31-maint/Misc/NEWS (original) +++ python/branches/release31-maint/Misc/NEWS Thu May 6 15:54:43 2010 @@ -160,6 +160,9 @@ Tests ----- +- Issue #8629: Disable some test_ssl tests, since they give different + results with OpenSSL 1.0.0 and higher. + - Issue #8533: regrtest uses backslashreplace error handler for stdout to avoid UnicodeEncodeError (write non-ASCII character to stdout using ASCII encoding) From python-checkins at python.org Thu May 6 16:11:23 2010 From: python-checkins at python.org (antoine.pitrou) Date: Thu, 6 May 2010 16:11:23 +0200 (CEST) Subject: [Python-checkins] r80869 - python/trunk/Lib/test/test_ssl.py Message-ID: <20100506141123.7CBD6EE98D@mail.python.org> Author: antoine.pitrou Date: Thu May 6 16:11:23 2010 New Revision: 80869 Log: `self` doesn't exist here Modified: python/trunk/Lib/test/test_ssl.py Modified: python/trunk/Lib/test/test_ssl.py ============================================================================== --- python/trunk/Lib/test/test_ssl.py (original) +++ python/trunk/Lib/test/test_ssl.py Thu May 6 16:11:23 2010 @@ -665,7 +665,7 @@ if test_support.verbose: sys.stdout.write("\nsocket.error is %s\n" % x[1]) else: - self.fail("Use of invalid cert should have failed!") + raise AssertionError("Use of invalid cert should have failed!") finally: server.stop() server.join() @@ -712,7 +712,7 @@ if test_support.verbose: sys.stdout.write(" client: read %s\n" % repr(outdata)) if outdata != indata.lower(): - self.fail( + raise AssertionError( "bad data <<%s>> (%d) received; expected <<%s>> (%d)\n" % (outdata[:min(len(outdata),20)], len(outdata), indata[:min(len(indata),20)].lower(), len(indata))) @@ -759,7 +759,7 @@ raise else: if not expect_success: - self.fail( + raise AssertionError( "Client protocol %s succeeded with server protocol %s!" % (ssl.get_protocol_name(client_protocol), ssl.get_protocol_name(server_protocol))) From python-checkins at python.org Thu May 6 16:14:09 2010 From: python-checkins at python.org (andrew.kuchling) Date: Thu, 6 May 2010 16:14:09 +0200 (CEST) Subject: [Python-checkins] r80870 - python/trunk/Doc/whatsnew/2.7.rst Message-ID: <20100506141409.A05F3EE992@mail.python.org> Author: andrew.kuchling Date: Thu May 6 16:14:09 2010 New Revision: 80870 Log: Describe ElementTree 1.3; rearrange new-module sections; describe dict views as sets; small edits and items Modified: python/trunk/Doc/whatsnew/2.7.rst Modified: python/trunk/Doc/whatsnew/2.7.rst ============================================================================== --- python/trunk/Doc/whatsnew/2.7.rst (original) +++ python/trunk/Doc/whatsnew/2.7.rst Thu May 6 16:14:09 2010 @@ -8,10 +8,11 @@ .. Fix accents on Kristjan Valur Jonsson, Fuerstenau -.. Big jobs: ElementTree 1.3, pep 391 +.. Big jobs: pep 391 .. hyperlink all the methods & functions. .. T_STRING_INPLACE not described in main docs +.. XXX "Format String Syntax" in string.rst could use many more examples. .. $Id$ Rules for maintenance: @@ -238,8 +239,6 @@ comma-formatting mechanism isn't as general as the :mod:`locale` module, but it's easier to use. -.. XXX "Format String Syntax" in string.rst could use many more examples. - .. seealso:: :pep:`378` - Format Specifier for Thousands Separator @@ -366,7 +365,7 @@ .. rev79293 -* :class:`Logger` instances gained a :meth:`getChild` that retrieves a +* :class:`Logger` instances gained a :meth:`getChild` method that retrieves a descendant logger using a relative path. For example, once you retrieve a logger by doing ``log = getLogger('app')``, calling ``log.getChild('network.listen')`` is equivalent to @@ -388,8 +387,6 @@ are different in Python 3.x. They return an object called a :dfn:`view` instead of a fully materialized list. -.. Views can be iterated over, but they also behave like sets. XXX not working. - It's not possible to change the return values of :meth:`keys`, :meth:`values`, and :meth:`items` in Python 2.7 because too much code would break. Instead the 3.x versions were added under the new names @@ -403,6 +400,16 @@ >>> d.viewkeys() dict_keys([0, 130, 10, 140, 20, 150, 30, ..., 250]) +Views can be iterated over, but they also behave like sets. The ``&`` +operator performs intersection, and ``|`` performs a union:: + + >>> d1 = dict((i*10, chr(65+i)) for i in range(26)) + >>> d2 = dict((i**.5, i) for i in range(1000)) + >>> d1.viewkeys() & d2.viewkeys() + set([0.0, 10.0, 20.0, 30.0]) + >>> d1.viewkeys() | range(0, 30) + set([0, 1, 130, 3, 4, 5, 6, ..., 120, 250]) + The view keeps track of the dictionary and its contents change as the dictionary is modified:: @@ -940,6 +947,11 @@ length as the read-only :attr:`~collections.deque.maxlen` attribute. (Both features added by Raymond Hettinger.) +* Deprecated function: :func:`contextlib.nested`, which allows + handling more than one context manager with a single :keyword:`with` + statement, has been deprecated, because :keyword:`with` supports + multiple context managers syntactically now. + * The :mod:`copy` module's :func:`~copy.deepcopy` function will now correctly copy bound instance methods. (Implemented by Robert Collins; :issue:`1515`.) @@ -1437,9 +1449,9 @@ management protocol, so you can write ``with zipfile.ZipFile(...) as f: ...``. (Contributed by Brian Curtin; :issue:`5511`.) - :mod:`zipfile` now supports archiving empty directories and + :mod:`zipfile` now also supports archiving empty directories and extracts them correctly. (Fixed by Kuba Wieczorek; :issue:`4710`.) - Reading files out of an archive is now faster, and interleaving + Reading files out of an archive is faster, and interleaving :meth:`~zipfile.ZipFile.read` and :meth:`~zipfile.ZipFile.readline` now works correctly. (Contributed by Nir Aides; :issue:`7610`.) @@ -1453,6 +1465,47 @@ :issue:`6003`.) +.. ====================================================================== +.. whole new modules get described in subsections here + + +.. _importlib-section: + +New module: importlib +------------------------------ + +Python 3.1 includes the :mod:`importlib` package, a re-implementation +of the logic underlying Python's :keyword:`import` statement. +:mod:`importlib` is useful for implementors of Python interpreters and +to users who wish to write new importers that can participate in the +import process. Python 2.7 doesn't contain the complete +:mod:`importlib` package, but instead has a tiny subset that contains +a single function, :func:`~importlib.import_module`. + +``import_module(name, package=None)`` imports a module. *name* is +a string containing the module or package's name. It's possible to do +relative imports by providing a string that begins with a ``.`` +character, such as ``..utils.errors``. For relative imports, the +*package* argument must be provided and is the name of the package that +will be used as the anchor for +the relative import. :func:`~importlib.import_module` both inserts the imported +module into ``sys.modules`` and returns the module object. + +Here are some examples:: + + >>> from importlib import import_module + >>> anydbm = import_module('anydbm') # Standard absolute import + >>> anydbm + + >>> # Relative import + >>> sysconfig = import_module('..sysconfig', 'distutils.command') + >>> sysconfig + + +:mod:`importlib` was implemented by Brett Cannon and introduced in +Python 3.1. + + New module: sysconfig --------------------------------- @@ -1482,15 +1535,26 @@ renamed by Tarek Ziad?. -Updated module: ElementTree 1.3 ---------------------------------- +ttk: Themed Widgets for Tk +-------------------------- -XXX write this. +Tcl/Tk 8.5 includes a set of themed widgets that re-implement basic Tk +widgets but have a more customizable appearance and can therefore more +closely resemble the native platform's widgets. This widget +set was originally called Tile, but was renamed to Ttk (for "themed Tk") +on being added to Tcl/Tck release 8.5. -.. ====================================================================== -.. whole new modules get described in subsections here +XXX write a brief discussion and an example here. + +The :mod:`ttk` module was written by Guilherme Polo and added in +:issue:`2983`. An alternate version called ``Tile.py``, written by +Martin Franklin and maintained by Kevin Walzer, was proposed for +inclusion in :issue:`2618`, but the authors argued that Guilherme +Polo's work was more comprehensive. +.. _unittest-section: + Unit Testing Enhancements --------------------------------- @@ -1668,67 +1732,91 @@ module is imported or used. -.. _importlib-section: - -importlib: Importing Modules ------------------------------- - -Python 3.1 includes the :mod:`importlib` package, a re-implementation -of the logic underlying Python's :keyword:`import` statement. -:mod:`importlib` is useful for implementors of Python interpreters and -to users who wish to write new importers that can participate in the -import process. Python 2.7 doesn't contain the complete -:mod:`importlib` package, but instead has a tiny subset that contains -a single function, :func:`~importlib.import_module`. - -``import_module(name, package=None)`` imports a module. *name* is -a string containing the module or package's name. It's possible to do -relative imports by providing a string that begins with a ``.`` -character, such as ``..utils.errors``. For relative imports, the -*package* argument must be provided and is the name of the package that -will be used as the anchor for -the relative import. :func:`~importlib.import_module` both inserts the imported -module into ``sys.modules`` and returns the module object. - -Here are some examples:: - - >>> from importlib import import_module - >>> anydbm = import_module('anydbm') # Standard absolute import - >>> anydbm - - >>> # Relative import - >>> sysconfig = import_module('..sysconfig', 'distutils.command') - >>> sysconfig - - -:mod:`importlib` was implemented by Brett Cannon and introduced in -Python 3.1. - - -ttk: Themed Widgets for Tk --------------------------- - -Tcl/Tk 8.5 includes a set of themed widgets that re-implement basic Tk -widgets but have a more customizable appearance and can therefore more -closely resemble the native platform's widgets. This widget -set was originally called Tile, but was renamed to Ttk (for "themed Tk") -on being added to Tcl/Tck release 8.5. - -XXX write a brief discussion and an example here. - -The :mod:`ttk` module was written by Guilherme Polo and added in -:issue:`2983`. An alternate version called ``Tile.py``, written by -Martin Franklin and maintained by Kevin Walzer, was proposed for -inclusion in :issue:`2618`, but the authors argued that Guilherme -Polo's work was more comprehensive. +.. _elementtree-section: +Updated module: ElementTree 1.3 +--------------------------------- -Deprecations and Removals -========================= +The version of the ElementTree library included with Python was updated to +version 1.3. Some of the new features in ElementTree 1.3 are: -* :func:`contextlib.nested`, which allows handling more than one context manager - with one :keyword:`with` statement, has been deprecated; :keyword:`with` - supports multiple context managers syntactically now. +* The various parsing functions now take a *parser* keyword argument + that can be used to provide an :class:`XMLParser` instance that will + be used. This makes it possible to override the file's internal encoding: + + p = ET.XMLParser(encoding='utf-8') + t = ET.XML("""""", parser=p) + + Errors in parsing XML now raise a :exc:`ParseError` exception. + Instances of :exc:`ParseError` have a :attr:`position` attribute + containing a (*line*, *column*) tuple giving the location of the problem. + +* ElementTree's code for converting trees to a string has been + significantly reworked, making it roughly twice as fast in many + cases. The :class:`ElementTree` :meth:`write` and :class:`Element` + :meth:`write` methods now have a *method* parameter that can be + "xml" (the default), "html", or "text". HTML mode will output empty + elements as ```` instead of ````, and text + mode will skip over elements and only output the text chunks. If + you set the :attr:`tag` attribute of an element to ``None`` but + leaves its children in place, the element will be omitted when the + tree is written out, so you don't need to do more extensive rearrangement + to remove a single element. + + Namespace aspects have also been improved. All the ``xmlns:`` + declarations are now put on the root element and not scattered throughout + the resulting output. You can set the default namespace for a tree + by setting the :attr:`default_namespace` attribute and can + register new prefixes with :meth:`regsiter_namespace`. In XML mode, + you can use the true/false *xml_declaration* parameter to suppress the + XML declaration. + +* New :class:`Element` method: :meth:`extend` appends the items from a + sequence to the element's children. Elements themselves behave like + sequences, so it's easy to move children from one element to + another:: + + from xml.etree import ElementTree as ET + + t = ET.XML(""" + 1 2 3 + """) + new = ET.XML('') + new.extend(t) + + # Outputs 1... + print ET.tostring(new) + +* New :class:`Element` method: :meth:`iter` yields the children of the + element as a generator. It's also possible to write ``for child in + elem: ...`` to loop over an element's children. The existing method + :meth:`getiterator` is now deprecated. :meth:`getchildren` is + another similar method that constructs and returns a list of + children; it's also deprecated. + +* New :class:`Element` method: :meth:`itertext` yields all chunks of + text that are descendants of the element. For example:: + + t = ET.XML(""" + 1 2 3 + """) + + # Outputs ['\n ', '1', ' ', '2', ' ', '3', '\n'] + print list(t.itertext()) + +* Deprecated: using an element as a Boolean (i.e., ``if elem: ...``) + would return true if the element had any children, or false if + there were no children. This behaviour will eventually change or be removed + because it's confusing (``None`` is false, but so is a childless element?), + so it will now trigger a :exc:`FutureWarning`. In your code, + you should be explicit: write ``len(elem) != 0`` if you're interested in + the number of children, or ``elem is not None`` Instead, + +Fredrik Lundh develops ElementTree and produced the 1.3 version; +you can read his article describing 1.3 at +http://effbot.org/zone/elementtree-13-intro.htm. +Florent Xicluna updated the version included with +Python, after discussions on python-dev and in :issue:`6472`.) .. ====================================================================== @@ -1988,6 +2076,11 @@ This section lists previously described changes and other bugfixes that may require changes to your code: +* The :func:`range` function processes its arguments more + consistently; it will now call :meth:`__int__` on non-float, + non-integer arguments that are supplied to it. (Fixed by Alexander + Belopolsky; :issue:`1533`.) + * The string :meth:`format` method changed the default precision used for floating-point and complex numbers from 6 decimal places to 12, which matches the precision used by :func:`str`. From python-checkins at python.org Thu May 6 16:15:10 2010 From: python-checkins at python.org (antoine.pitrou) Date: Thu, 6 May 2010 16:15:10 +0200 (CEST) Subject: [Python-checkins] r80871 - in python/branches/py3k: Lib/test/test_ssl.py Message-ID: <20100506141510.4788BEE9A2@mail.python.org> Author: antoine.pitrou Date: Thu May 6 16:15:10 2010 New Revision: 80871 Log: Merged revisions 80869 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r80869 | antoine.pitrou | 2010-05-06 16:11:23 +0200 (jeu., 06 mai 2010) | 3 lines `self` doesn't exist here ........ Modified: python/branches/py3k/ (props changed) python/branches/py3k/Lib/test/test_ssl.py Modified: python/branches/py3k/Lib/test/test_ssl.py ============================================================================== --- python/branches/py3k/Lib/test/test_ssl.py (original) +++ python/branches/py3k/Lib/test/test_ssl.py Thu May 6 16:15:10 2010 @@ -659,7 +659,7 @@ if support.verbose: sys.stdout.write("\nsocket.error is %s\n" % x[1]) else: - self.fail("Use of invalid cert should have failed!") + raise AssertionError("Use of invalid cert should have failed!") finally: server.stop() server.join() @@ -704,7 +704,7 @@ if support.verbose: sys.stdout.write(" client: read %r\n" % outdata) if outdata != indata.lower(): - self.fail( + raise AssertionError( "bad data <<%r>> (%d) received; expected <<%r>> (%d)\n" % (outdata[:20], len(outdata), indata[:20].lower(), len(indata))) @@ -752,7 +752,7 @@ raise else: if not expect_success: - self.fail( + raise AssertionError( "Client protocol %s succeeded with server protocol %s!" % (ssl.get_protocol_name(client_protocol), ssl.get_protocol_name(server_protocol))) From amk at amk.ca Thu May 6 18:51:18 2010 From: amk at amk.ca (A.M. Kuchling) Date: Thu, 6 May 2010 12:51:18 -0400 Subject: [Python-checkins] r80724 - in python/branches/py3k: Include/Python.h Include/dynamic_annotations.h Include/pyatomic.h Include/pystate.h Makefile.pre.in Objects/dictobject.c PC/VS7.1/pythoncore.vcproj PC/VS8.0/pythoncore.vcproj PC/os2emx/Makefile PCbuild/pythoncore.vcproj Python/ceval.c Python/ceval_gil.h Python/dynamic_annotations.c Python/pystate.c Python/thread_pthread.h configure configure.in In-Reply-To: <20100503192935.3B92DE934@mail.python.org> References: <20100503192935.3B92DE934@mail.python.org> Message-ID: <20100506165118.GA14237@amk-desktop.matrixgroup.net> On Mon, May 03, 2010 at 09:29:35PM +0200, jeffrey.yasskin wrote: > I've implemented part of the C1x atomic types so that we can explicitly mark > variables that are used across threads, and get defined behavior as compilers > advance. > > I've added tsan's client header and implementation to the codebase in > dynamic_annotations.{h,c} (docs at > http://code.google.com/p/data-race-test/wiki/DynamicAnnotations). Do we need to describe any of this in the c-api documentation (even if only by reference to the ISO draft spec and to that wiki page)? --amk From python-checkins at python.org Thu May 6 19:21:59 2010 From: python-checkins at python.org (andrew.kuchling) Date: Thu, 6 May 2010 19:21:59 +0200 (CEST) Subject: [Python-checkins] r80872 - python/trunk/Doc/whatsnew/2.7.rst Message-ID: <20100506172159.449E0EE9A2@mail.python.org> Author: andrew.kuchling Date: Thu May 6 19:21:59 2010 New Revision: 80872 Log: Add 2 items; record ideas for two initial sections; clarify wording Modified: python/trunk/Doc/whatsnew/2.7.rst Modified: python/trunk/Doc/whatsnew/2.7.rst ============================================================================== --- python/trunk/Doc/whatsnew/2.7.rst (original) +++ python/trunk/Doc/whatsnew/2.7.rst Thu May 6 19:21:59 2010 @@ -9,6 +9,9 @@ .. Fix accents on Kristjan Valur Jonsson, Fuerstenau .. Big jobs: pep 391 +.. Initial section: development plans for 2.x in future +.. Initial section: changes in deprecation warning behaviour + .. hyperlink all the methods & functions. .. T_STRING_INPLACE not described in main docs @@ -56,7 +59,7 @@ when researching a change. This article explains the new features in Python 2.7. The final -release of 2.7 is currently scheduled for June 2010; the detailed +release of 2.7 is currently scheduled for July 2010; the detailed schedule is described in :pep:`373`. Python 2.7 is planned to be the last major release in the 2.x series. @@ -80,7 +83,7 @@ A partial list of 3.1 features that were backported to 2.7: -* A version of the :mod:`io` library, rewritten in C for performance. +* A new version of the :mod:`io` library, rewritten in C for performance. * The ordered-dictionary type described in :ref:`pep-0372`. * The new format specifier described in :ref:`pep-0378`. * The :class:`memoryview` object. @@ -1176,6 +1179,12 @@ with any object literal that decodes to a list of pairs. (Contributed by Raymond Hettinger; :issue:`5381`.) +* The :mod:`mailbox` module's :class:`Maildir` class now records the + timestamp on the directories it reads, and only re-reads them if the + modification time has subsequently changed. This improves + performance by avoiding unneeded directory scans. (Fixed by + A.M. Kuchling and Antoine Pitrou; :issue:`1607951`, :issue:`6896`.) + * New functions: the :mod:`math` module gained :func:`~math.erf` and :func:`~math.erfc` for the error function and the complementary error function, :func:`~math.expm1` which computes ``e**x - 1`` with more precision than @@ -1238,9 +1247,9 @@ expected that the directory or zip contains a :file:`__main__.py`; if it doesn't, some other :file:`__main__.py` might be imported from a location later in ``sys.path``. This makes some of the machinery - of :mod:`runpy` available to scripts that want to mimic the behaviour - of Python's :option:`-m` switch. (Added by Nick Coghlan; - :issue:`6816`.) + of :mod:`runpy` available to scripts that want to mimic the way + Python's :option:`-m` processes an explicit path name. + (Added by Nick Coghlan; :issue:`6816`.) * New function: in the :mod:`shutil` module, :func:`~shutil.make_archive` takes a filename, archive type (zip or tar-format), and a directory @@ -2092,6 +2101,12 @@ affects new-style classes (derived from :class:`object`) and C extension types. (:issue:`6101`.) +* Due to a bug in Python 2.6, the *exc_value* parameter to + :meth:`__exit__` methods was often the string representation of the + exception, not an instance. This was fixed in 2.7, so *exc_value* + will be an instance as expected. (Fixed by Florent Xicluna; + :issue:`7853`.) + * When a restricted set of attributes were set using ``__slots__``, deleting an unset attribute would not raise :exc:`AttributeError` as you would expect. Fixed by Benjamin Peterson; :issue:`7604`.) From python-checkins at python.org Thu May 6 19:27:57 2010 From: python-checkins at python.org (andrew.kuchling) Date: Thu, 6 May 2010 19:27:57 +0200 (CEST) Subject: [Python-checkins] r80873 - python/trunk/Doc/whatsnew/2.7.rst Message-ID: <20100506172757.DBB5FEE9A2@mail.python.org> Author: andrew.kuchling Date: Thu May 6 19:27:57 2010 New Revision: 80873 Log: Change section title; point to unittest2 Modified: python/trunk/Doc/whatsnew/2.7.rst Modified: python/trunk/Doc/whatsnew/2.7.rst ============================================================================== --- python/trunk/Doc/whatsnew/2.7.rst (original) +++ python/trunk/Doc/whatsnew/2.7.rst Thu May 6 19:27:57 2010 @@ -1564,12 +1564,15 @@ .. _unittest-section: -Unit Testing Enhancements +Updated module: unittest --------------------------------- The :mod:`unittest` module was greatly enhanced; many new features were added. Most of these features were implemented -by Michael Foord, unless otherwise noted. +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 +http://pypi.python.org/pypi/unittest2. When used from the command line, the module can automatically discover tests. It's not as fancy as `py.test `__ or From jyasskin at gmail.com Thu May 6 19:43:47 2010 From: jyasskin at gmail.com (Jeffrey Yasskin) Date: Thu, 6 May 2010 10:43:47 -0700 Subject: [Python-checkins] r80724 - in python/branches/py3k: Include/Python.h Include/dynamic_annotations.h Include/pyatomic.h Include/pystate.h Makefile.pre.in Objects/dictobject.c PC/VS7.1/pythoncore.vcproj PC/VS8.0/pythoncore.vcproj PC/os2emx/Makefile Message-ID: On Thu, May 6, 2010 at 9:51 AM, A.M. Kuchling wrote: > On Mon, May 03, 2010 at 09:29:35PM +0200, jeffrey.yasskin wrote: >> I've implemented part of the C1x atomic types so that we can explicitly mark >> variables that are used across threads, and get defined behavior as compilers >> advance. >> >> I've added tsan's client header and implementation to the codebase in >> dynamic_annotations.{h,c} (docs at >> http://code.google.com/p/data-race-test/wiki/DynamicAnnotations). > > Do we need to describe any of this in the c-api documentation (even if > only by reference to the ISO draft spec and to that wiki page)? I'm not sure. I mostly intended it for people working on the interpreter itself, which is why I made everything start with _Py_, and internal interfaces don't usually go in the c-api docs. The new functions could be useful for people trying to make their extensions thread-safe though. If people think they will be, I can rename them to Py_ and try to explain how to use them for extension development in the c-api docs. I'm somewhat inclined to wait until an extension author asks for them though, so they can beta-test my instructions. Jeffrey From python-checkins at python.org Thu May 6 19:56:36 2010 From: python-checkins at python.org (brett.cannon) Date: Thu, 6 May 2010 19:56:36 +0200 (CEST) Subject: [Python-checkins] r80874 - python/trunk/Objects/floatobject.c Message-ID: <20100506175636.EB5A5EEAA6@mail.python.org> Author: brett.cannon Date: Thu May 6 19:56:36 2010 New Revision: 80874 Log: Add back in a line that was unneeded which advanced a pointer, but commented out as it is currently unneeded. This effectively adds back in the line removed in r80809 as a comment. Modified: python/trunk/Objects/floatobject.c Modified: python/trunk/Objects/floatobject.c ============================================================================== --- python/trunk/Objects/floatobject.c (original) +++ python/trunk/Objects/floatobject.c Thu May 6 19:56:36 2010 @@ -2478,6 +2478,7 @@ /* Eighth byte */ *p = flo & 0xFF; + /* p += incr; Unneeded (for now) */ /* Done */ return 0; From python-checkins at python.org Thu May 6 19:57:06 2010 From: python-checkins at python.org (giampaolo.rodola) Date: Thu, 6 May 2010 19:57:06 +0200 (CEST) Subject: [Python-checkins] r80875 - in python/trunk: Lib/asyncore.py Lib/test/test_asyncore.py Misc/NEWS Message-ID: <20100506175706.4DC53EEAC1@mail.python.org> Author: giampaolo.rodola Date: Thu May 6 19:57:06 2010 New Revision: 80875 Log: Fix asyncore issues 8573 and 8483: _strerror might throw ValueError; asyncore.__getattr__ cheap inheritance caused confusing error messages when accessing undefined class attributes; added an alias for __str__ which now is used as a fallback for __repr__ Modified: python/trunk/Lib/asyncore.py python/trunk/Lib/test/test_asyncore.py python/trunk/Misc/NEWS Modified: python/trunk/Lib/asyncore.py ============================================================================== --- python/trunk/Lib/asyncore.py (original) +++ python/trunk/Lib/asyncore.py Thu May 6 19:57:06 2010 @@ -50,6 +50,7 @@ import socket import sys import time +import warnings import os from errno import EALREADY, EINPROGRESS, EWOULDBLOCK, ECONNRESET, \ @@ -61,10 +62,12 @@ socket_map = {} def _strerror(err): - res = os.strerror(err) - if res == 'Unknown error': - res = errorcode[err] - return res + try: + return strerror(err) + except (ValueError, OverflowError): + if err in errorcode: + return errorcode[err] + return "Unknown error %s" %err class ExitNow(Exception): pass @@ -265,6 +268,8 @@ status.append(repr(self.addr)) return '<%s at %#x>' % (' '.join(status), id(self)) + __str__ = __repr__ + def add_channel(self, map=None): #self.log_info('adding channel %s' % self) if map is None: @@ -396,7 +401,15 @@ # cheap inheritance, used to pass all other attribute # references to the underlying socket object. def __getattr__(self, attr): - return getattr(self.socket, attr) + try: + retattr = getattr(self.socket, attr) + except AttributeError: + raise AttributeError("%s instance has no attribute '%s'" + %(self.__class__.__name__, attr)) + else: + warnings.warn("cheap inheritance is deprecated", DeprecationWarning, + stacklevel=2) + return retattr # log and log_info may be overridden to provide more sophisticated # logging and warning methods. In general, log is for 'hit' logging Modified: python/trunk/Lib/test/test_asyncore.py ============================================================================== --- python/trunk/Lib/test/test_asyncore.py (original) +++ python/trunk/Lib/test/test_asyncore.py Thu May 6 19:57:06 2010 @@ -5,6 +5,7 @@ import socket import sys import time +import warnings from test import test_support from test.test_support import TESTFN, run_unittest, unlink @@ -305,6 +306,22 @@ 'warning: unhandled accept event'] self.assertEquals(lines, expected) + def test_issue_8594(self): + # XXX - this test is supposed to be removed in next major Python + # version + d = asyncore.dispatcher(socket.socket()) + # make sure the error message no longer refers to the socket + # object but the dispatcher instance instead + self.assertRaisesRegexp(AttributeError, 'dispatcher instance', + getattr, d, 'foo') + # cheap inheritance with the underlying socket is supposed + # to still work but a DeprecationWarning is expected + with warnings.catch_warnings(record=True) as w: + warnings.simplefilter("always") + family = d.family + self.assertEqual(family, socket.AF_INET) + self.assertTrue(len(w) == 1) + self.assertTrue(issubclass(w[0].category, DeprecationWarning)) class dispatcherwithsend_noread(asyncore.dispatcher_with_send): Modified: python/trunk/Misc/NEWS ============================================================================== --- python/trunk/Misc/NEWS (original) +++ python/trunk/Misc/NEWS Thu May 6 19:57:06 2010 @@ -41,6 +41,13 @@ Library ------- +- Issue #8573: asyncore _strerror() function might throw ValueError. + +- Issue #8483: asyncore.dispatcher's __getattr__ method produced confusing + error messages when accessing undefined class attributes because of the cheap + inheritance with the underlying socket object. + The cheap inheritance has been deprecated. + - Issue #4265: shutil.copyfile() was leaking file descriptors when disk fills. Patch by Tres Seaver. From brett at python.org Thu May 6 19:59:39 2010 From: brett at python.org (Brett Cannon) Date: Thu, 6 May 2010 10:59:39 -0700 Subject: [Python-checkins] r80809 - python/trunk/Objects/floatobject.c In-Reply-To: <4BE2B6DF.6030901@trueblade.com> References: <20100505201609.5D92EF68D2@mail.python.org> <4BE2B6DF.6030901@trueblade.com> Message-ID: I added the line back in as a comment and if I do this again for py3k I will do that for all pointer advancement code. That way you guys get your code for possible future use and I get my compiler silenced and everyone is happy. And in case people are being timid in fear of upsetting me, feel free to undo any changes I made. Obviously I prefer having the lines added back in as comments so Clang does not complain about them in the future, but if you simply revert a change I am not going to complain. On Thu, May 6, 2010 at 05:32, Eric Smith wrote: > Mark Dickinson wrote: > >> On Wed, May 5, 2010 at 9:16 PM, brett.cannon >> wrote: >> >>> Author: brett.cannon >>> Date: Wed May 5 22:16:09 2010 >>> New Revision: 80809 >>> >>> Log: >>> Remove an unneeded variable increment. >>> >>> Found using Clang's static analyzer. >>> >>> >>> Modified: >>> python/trunk/Objects/floatobject.c >>> >>> Modified: python/trunk/Objects/floatobject.c >>> >>> ============================================================================== >>> --- python/trunk/Objects/floatobject.c (original) >>> +++ python/trunk/Objects/floatobject.c Wed May 5 22:16:09 2010 >>> @@ -2478,7 +2478,6 @@ >>> >>> /* Eighth byte */ >>> *p = flo & 0xFF; >>> - p += incr; >>> >>> /* Done */ >>> return 0; >>> >> >> At the risk of bikeshedding, it's not clear to me that making changes >> like this is necessarily a Good Thing. In this case, it means (a) >> treating the last byte of the packed float differently from the first >> 7, and (b) breaking an invariant that held previously---namely that at >> the end of that section of code, p points just past the last byte >> written. Clearly these are very minor issues, and don't affect >> correctness in this case. But I'd argue that similar changes >> elsewhere could adversely affect future maintenance and/or code >> readability, albeit to a tiny degree. >> >> IOW, redundancy isn't always a bad thing, especially if it aids >> comprehension for the human code reader. >> > > I agree. I often leave pointers positioned at the next insertion point in a > buffer, in case I later add code that again inserts into the buffer. Surely > compilers will optimize this away. > > -- > Eric. > > _______________________________________________ > Python-checkins mailing list > Python-checkins at python.org > http://mail.python.org/mailman/listinfo/python-checkins > -------------- next part -------------- An HTML attachment was scrubbed... URL: From python-checkins at python.org Thu May 6 20:06:30 2010 From: python-checkins at python.org (giampaolo.rodola) Date: Thu, 6 May 2010 20:06:30 +0200 (CEST) Subject: [Python-checkins] r80876 - in python/branches/py3k: Lib/asyncore.py Lib/test/test_asyncore.py Misc/NEWS Message-ID: <20100506180630.9C1A8EEA99@mail.python.org> Author: giampaolo.rodola Date: Thu May 6 20:06:30 2010 New Revision: 80876 Log: Merged revisions 80875 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r80875 | giampaolo.rodola | 2010-05-06 19:57:06 +0200 (gio, 06 mag 2010) | 1 line Fix asyncore issues 8573 and 8483: _strerror might throw ValueError; asyncore.__getattr__ cheap inheritance caused confusing error messages when accessing undefined class attributes; added an alias for __str__ which now is used as a fallback for __repr__ ........ Modified: python/branches/py3k/ (props changed) python/branches/py3k/Lib/asyncore.py python/branches/py3k/Lib/test/test_asyncore.py python/branches/py3k/Misc/NEWS Modified: python/branches/py3k/Lib/asyncore.py ============================================================================== --- python/branches/py3k/Lib/asyncore.py (original) +++ python/branches/py3k/Lib/asyncore.py Thu May 6 20:06:30 2010 @@ -50,6 +50,8 @@ import socket import sys import time +import warnings + import os from errno import EALREADY, EINPROGRESS, EWOULDBLOCK, ECONNRESET, \ ENOTCONN, ESHUTDOWN, EINTR, EISCONN, EBADF, ECONNABORTED, errorcode @@ -60,10 +62,12 @@ socket_map = {} def _strerror(err): - res = os.strerror(err) - if res == 'Unknown error': - res = errorcode[err] - return res + try: + return strerror(err) + except (ValueError, OverflowError): + if err in errorcode: + return errorcode[err] + return "Unknown error %s" %err class ExitNow(Exception): pass @@ -264,6 +268,8 @@ status.append(repr(self.addr)) return '<%s at %#x>' % (' '.join(status), id(self)) + __str__ = __repr__ + def add_channel(self, map=None): #self.log_info('adding channel %s' % self) if map is None: @@ -395,7 +401,15 @@ # cheap inheritance, used to pass all other attribute # references to the underlying socket object. def __getattr__(self, attr): - return getattr(self.socket, attr) + try: + retattr = getattr(self.socket, attr) + except AttributeError: + raise AttributeError("%s instance has no attribute '%s'" + %(self.__class__.__name__, attr)) + else: + warnings.warn("cheap inheritance is deprecated", DeprecationWarning, + stacklevel=2) + return retattr # log and log_info may be overridden to provide more sophisticated # logging and warning methods. In general, log is for 'hit' logging Modified: python/branches/py3k/Lib/test/test_asyncore.py ============================================================================== --- python/branches/py3k/Lib/test/test_asyncore.py (original) +++ python/branches/py3k/Lib/test/test_asyncore.py Thu May 6 20:06:30 2010 @@ -5,6 +5,7 @@ import socket import sys import time +import warnings from test import support from test.support import TESTFN, run_unittest, unlink @@ -306,6 +307,22 @@ 'warning: unhandled accept event'] self.assertEquals(lines, expected) + def test_issue_8594(self): + # XXX - this test is supposed to be removed in next major Python + # version + d = asyncore.dispatcher(socket.socket()) + # make sure the error message no longer refers to the socket + # object but the dispatcher instance instead + self.assertRaisesRegexp(AttributeError, 'dispatcher instance', + getattr, d, 'foo') + # cheap inheritance with the underlying socket is supposed + # to still work but a DeprecationWarning is expected + with warnings.catch_warnings(record=True) as w: + warnings.simplefilter("always") + family = d.family + self.assertEqual(family, socket.AF_INET) + self.assertTrue(len(w) == 1) + self.assertTrue(issubclass(w[0].category, DeprecationWarning)) class dispatcherwithsend_noread(asyncore.dispatcher_with_send): Modified: python/branches/py3k/Misc/NEWS ============================================================================== --- python/branches/py3k/Misc/NEWS (original) +++ python/branches/py3k/Misc/NEWS Thu May 6 20:06:30 2010 @@ -348,6 +348,13 @@ Library ------- +- Issue #8573: asyncore _strerror() function might throw ValueError. + +- Issue #8483: asyncore.dispatcher's __getattr__ method produced confusing + error messages when accessing undefined class attributes because of the cheap + inheritance with the underlying socket object. + The cheap inheritance has been deprecated. + - Issue #4265: shutil.copyfile() was leaking file descriptors when disk fills. Patch by Tres Seaver. From python-checkins at python.org Thu May 6 20:20:39 2010 From: python-checkins at python.org (jean-paul.calderone) Date: Thu, 6 May 2010 20:20:39 +0200 (CEST) Subject: [Python-checkins] r80877 - in python/branches/signalfd-issue8407: Doc/library/signal.rst Lib/test/test_signal.py Modules/signalmodule.c Message-ID: <20100506182039.2D922F750@mail.python.org> Author: jean-paul.calderone Date: Thu May 6 20:20:38 2010 New Revision: 80877 Log: Address almost all review feedback from Antoine Pitrou and Brian Curtin See http://codereview.appspot.com/1132041/show Modified: python/branches/signalfd-issue8407/Doc/library/signal.rst python/branches/signalfd-issue8407/Lib/test/test_signal.py python/branches/signalfd-issue8407/Modules/signalmodule.c Modified: python/branches/signalfd-issue8407/Doc/library/signal.rst ============================================================================== --- python/branches/signalfd-issue8407/Doc/library/signal.rst (original) +++ python/branches/signalfd-issue8407/Doc/library/signal.rst Thu May 6 20:20:38 2010 @@ -281,7 +281,7 @@ *mask* is a list of signal numbers which will trigger data on this file descriptor. - *flags* is a bitvector which may include any :const:`signal.SFD_*` flag. + *flags* is a bit mask which may include any :const:`signal.SFD_*` flag. .. versionadded:: 2.7 Modified: python/branches/signalfd-issue8407/Lib/test/test_signal.py ============================================================================== --- python/branches/signalfd-issue8407/Lib/test/test_signal.py (original) +++ python/branches/signalfd-issue8407/Lib/test/test_signal.py Thu May 6 20:20:38 2010 @@ -406,20 +406,16 @@ def raiser(*args): - """A signal handler which raises SomeException. - """ + """A signal handler which raises SomeException.""" raise SomeException() class SigprocmaskTests(unittest.TestCase): - """ - Tests for sigprocmask. - """ + """Tests for sigprocmask.""" def _handle_sigusr1(self): old_handler = signal.signal(signal.SIGUSR1, raiser) self.addCleanup(signal.signal, signal.SIGUSR1, old_handler) - return SomeException def test_signature(self): @@ -432,14 +428,30 @@ def test_invalid_how(self): - """If a valid other than SIG_BLOCK, SIG_UNBLOCK, or SIG_SETMASK is + """If a value other than SIG_BLOCK, SIG_UNBLOCK, or SIG_SETMASK is passed for the how argument to sigprocmask, ValueError is raised. """ - with self.assertRaises(ValueError) as cm: + message = "value specified for how \(1700\) invalid" + with self.assertRaisesRegexp(ValueError, message): signal.sigprocmask(1700, []) - exc = cm.exception - self.assertTrue(isinstance(exc, ValueError)) - self.assertEquals(str(exc), "value specified for how (1700) invalid") + + + def test_invalid_signal_iterable(self): + """If iterating over the value passed for the signals parameter to + sigprocmask raises an exception, sigprocmask raises that exception. + """ + class BrokenIter(object): + def __iter__(self): + raise RuntimeError("my __iter__ is broken") + with self.assertRaisesRegexp(RuntimeError, "my __iter__ is broken"): + signal.sigprocmask(signal.SIG_BLOCK, BrokenIter()) + + + def test_invalid_signal(self): + """If an object in the iterable passed for the signals parameter to + sigprocmask isn't an integer, TypeError is raised.""" + with self.assertRaisesRegexp(TypeError, "an integer is required"): + signal.sigprocmask(signal.SIG_BLOCK, [object()]) def test_return_previous_mask(self): @@ -457,12 +469,9 @@ self._handle_sigusr1() previous = signal.sigprocmask(signal.SIG_BLOCK, [signal.SIGUSR1]) os.kill(os.getpid(), signal.SIGUSR1) - try: + with self.assertRaises(SomeException): + # Expect to receive SIGUSR1 after unblocking it. signal.sigprocmask(signal.SIG_SETMASK, previous) - except SomeException: - pass - else: - self.fail("Expected to receive SIGUSR1 after unblocking it.") def test_unblock(self): @@ -473,13 +482,18 @@ previous = signal.sigprocmask(signal.SIG_BLOCK, [signal.SIGUSR1]) self.addCleanup(signal.sigprocmask, signal.SIG_SETMASK, previous) signal.sigprocmask(signal.SIG_UNBLOCK, [signal.SIGUSR1]) - try: + + with self.assertRaises(SomeException): os.kill(os.getpid(), signal.SIGUSR1) - time.sleep(1) - except SomeException: - pass - else: - self.fail("SomeException was expected but not raised") + + + def test_long_signals(self): + """sigprocmask accepts signal numbers as instances of long.""" + previous = signal.sigprocmask( + signal.SIG_SETMASK, [long(signal.SIGUSR1), long(signal.SIGUSR2)]) + masked = signal.sigprocmask(signal.SIG_SETMASK, previous) + self.assertEquals(masked, [signal.SIGUSR1, signal.SIGUSR2]) + class SignalfdTests(unittest.TestCase): @@ -524,11 +538,9 @@ """If a signal number that is out of the valid range is included in the sigmask list argument to signalfd, ValueError is raised. """ - with self.assertRaises(ValueError) as cm: + message = "signal number -2 out of range" + with self.assertRaisesRegexp(ValueError, message): signal.signalfd(-1, [-2]) - exc = cm.exception - self.assertTrue(isinstance(exc, ValueError)) - self.assertEquals(str(exc), "signal number -2 out of range") def test_handle_signals(self): Modified: python/branches/signalfd-issue8407/Modules/signalmodule.c ============================================================================== --- python/branches/signalfd-issue8407/Modules/signalmodule.c (original) +++ python/branches/signalfd-issue8407/Modules/signalmodule.c Thu May 6 20:20:38 2010 @@ -468,28 +468,36 @@ { static const char* range_format = "signal number %d out of range"; char range_buffer[1024]; + int result = 0; - PyObject *item, *iterator; + PyObject *item, *iterator = NULL; sigemptyset(mask); iterator = PyObject_GetIter(iterable); if (iterator == NULL) { - return -1; + result = -1; + goto error; } - for (item = PyIter_Next(iterator); item; item = PyIter_Next(iterator)) { + while ((item = PyIter_Next(iterator))) { int signum = PyInt_AsLong(item); + Py_DECREF(item); if (signum == -1 && PyErr_Occurred()) { - return -1; + result = -1; + goto error; } if (sigaddset(mask, signum) == -1) { PyOS_snprintf(range_buffer, sizeof(range_buffer), range_format, signum); PyErr_SetString(PyExc_ValueError, range_buffer); - return -1; + result = -1; + goto error; } } - return 0; + +error: + Py_XDECREF(iterator); + return result; } #if defined(HAVE_PTHREAD_SIGMASK) && !defined(HAVE_BROKEN_PTHREAD_SIGMASK) @@ -506,7 +514,6 @@ char how_buffer[1024]; int how, sig; - int valid; PyObject *signals, *result, *signum; sigset_t mask, previous; @@ -518,12 +525,7 @@ return NULL; } - /* - * It seems that invalid values of how are not always discovered. - */ - valid = (how == SIG_BLOCK || how == SIG_UNBLOCK || how == SIG_SETMASK); - - if (!valid || PY_SIGMASK(how, &mask, &previous) == -1) { + if (PY_SIGMASK(how, &mask, &previous) != 0) { PyOS_snprintf(how_buffer, sizeof(how_buffer), how_format, how); PyErr_SetString(PyExc_ValueError, how_buffer); return NULL; @@ -551,6 +553,7 @@ Py_DECREF(result); return NULL; } + Py_DECREF(signum); } } return result; From python-checkins at python.org Thu May 6 20:24:02 2010 From: python-checkins at python.org (giampaolo.rodola) Date: Thu, 6 May 2010 20:24:02 +0200 (CEST) Subject: [Python-checkins] r80878 - in python/branches/release26-maint: Lib/asyncore.py Lib/test/test_asyncore.py Misc/NEWS Message-ID: <20100506182402.DD428EE98D@mail.python.org> Author: giampaolo.rodola Date: Thu May 6 20:24:02 2010 New Revision: 80878 Log: Merged revisions 80875 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r80875 | giampaolo.rodola | 2010-05-06 19:57:06 +0200 (gio, 06 mag 2010) | 1 line Fix asyncore issues 8573 and 8483: _strerror might throw ValueError; asyncore.__getattr__ cheap inheritance caused confusing error messages when accessing undefined class attributes; added an alias for __str__ which now is used as a fallback for __repr__ ........ Modified: python/branches/release26-maint/ (props changed) python/branches/release26-maint/Lib/asyncore.py python/branches/release26-maint/Lib/test/test_asyncore.py python/branches/release26-maint/Misc/NEWS Modified: python/branches/release26-maint/Lib/asyncore.py ============================================================================== --- python/branches/release26-maint/Lib/asyncore.py (original) +++ python/branches/release26-maint/Lib/asyncore.py Thu May 6 20:24:02 2010 @@ -61,10 +61,12 @@ socket_map = {} def _strerror(err): - res = os.strerror(err) - if res == 'Unknown error': - res = errorcode[err] - return res + try: + return strerror(err) + except (ValueError, OverflowError): + if err in errorcode: + return errorcode[err] + return "Unknown error %s" %err class ExitNow(Exception): pass @@ -391,7 +393,11 @@ # cheap inheritance, used to pass all other attribute # references to the underlying socket object. def __getattr__(self, attr): - return getattr(self.socket, attr) + try: + return getattr(self.socket, attr) + except AttributeError: + raise AttributeError("%s instance has no attribute '%s'" + %(self.__class__.__name__, attr)) # log and log_info may be overridden to provide more sophisticated # logging and warning methods. In general, log is for 'hit' logging Modified: python/branches/release26-maint/Lib/test/test_asyncore.py ============================================================================== --- python/branches/release26-maint/Lib/test/test_asyncore.py (original) +++ python/branches/release26-maint/Lib/test/test_asyncore.py Thu May 6 20:24:02 2010 @@ -301,6 +301,18 @@ 'warning: unhandled accept event'] self.assertEquals(lines, expected) + def test_issue_8594(self): + d = asyncore.dispatcher(socket.socket()) + # make sure the error message no longer refers to the socket + # object but the dispatcher instance instead + try: + d.foo + except AttributeError, err: + self.assertTrue('dispatcher instance' in str(err)) + else: + self.fail("exception not raised") + # test cheap inheritance with the underlying socket + self.assertEqual(d.family, socket.AF_INET) class dispatcherwithsend_noread(asyncore.dispatcher_with_send): Modified: python/branches/release26-maint/Misc/NEWS ============================================================================== --- python/branches/release26-maint/Misc/NEWS (original) +++ python/branches/release26-maint/Misc/NEWS Thu May 6 20:24:02 2010 @@ -33,6 +33,12 @@ Library ------- +- Issue #8573: asyncore _strerror() function might throw ValueError. + +- Issue #8483: asyncore.dispatcher's __getattr__ method produced confusing + error messages when accessing undefined class attributes because of the cheap + inheritance with the underlying socket object. + - Issue #4265: shutil.copyfile() was leaking file descriptors when disk fills. Patch by Tres Seaver. From python-checkins at python.org Thu May 6 20:37:34 2010 From: python-checkins at python.org (giampaolo.rodola) Date: Thu, 6 May 2010 20:37:34 +0200 (CEST) Subject: [Python-checkins] r80879 - in python/branches/release31-maint: Lib/asyncore.py Lib/test/test_asyncore.py Misc/NEWS Message-ID: <20100506183734.B8410C8D8@mail.python.org> Author: giampaolo.rodola Date: Thu May 6 20:37:34 2010 New Revision: 80879 Log: Merged revisions 80876 via svnmerge from svn+ssh://pythondev at svn.python.org/python/branches/py3k ................ r80876 | giampaolo.rodola | 2010-05-06 20:06:30 +0200 (gio, 06 mag 2010) | 9 lines Merged revisions 80875 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r80875 | giampaolo.rodola | 2010-05-06 19:57:06 +0200 (gio, 06 mag 2010) | 1 line Fix asyncore issues 8573 and 8483: _strerror might throw ValueError; asyncore.__getattr__ cheap inheritance caused confusing error messages when accessing undefined class attributes; added an alias for __str__ which now is used as a fallback for __repr__ ........ ................ Modified: python/branches/release31-maint/ (props changed) python/branches/release31-maint/Lib/asyncore.py python/branches/release31-maint/Lib/test/test_asyncore.py python/branches/release31-maint/Misc/NEWS Modified: python/branches/release31-maint/Lib/asyncore.py ============================================================================== --- python/branches/release31-maint/Lib/asyncore.py (original) +++ python/branches/release31-maint/Lib/asyncore.py Thu May 6 20:37:34 2010 @@ -60,10 +60,12 @@ socket_map = {} def _strerror(err): - res = os.strerror(err) - if res == 'Unknown error': - res = errorcode[err] - return res + try: + return strerror(err) + except (ValueError, OverflowError): + if err in errorcode: + return errorcode[err] + return "Unknown error %s" %err class ExitNow(Exception): pass @@ -395,7 +397,11 @@ # cheap inheritance, used to pass all other attribute # references to the underlying socket object. def __getattr__(self, attr): - return getattr(self.socket, attr) + try: + return getattr(self.socket, attr) + except AttributeError: + raise AttributeError("%s instance has no attribute '%s'" + %(self.__class__.__name__, attr)) # log and log_info may be overridden to provide more sophisticated # logging and warning methods. In general, log is for 'hit' logging Modified: python/branches/release31-maint/Lib/test/test_asyncore.py ============================================================================== --- python/branches/release31-maint/Lib/test/test_asyncore.py (original) +++ python/branches/release31-maint/Lib/test/test_asyncore.py Thu May 6 20:37:34 2010 @@ -302,6 +302,18 @@ 'warning: unhandled accept event'] self.assertEquals(lines, expected) + def test_issue_8594(self): + d = asyncore.dispatcher(socket.socket()) + # make sure the error message no longer refers to the socket + # object but the dispatcher instance instead + try: + d.foo + except AttributeError as err: + self.assertTrue('dispatcher instance' in str(err)) + else: + self.fail("exception not raised") + # test cheap inheritance with the underlying socket + self.assertEqual(d.family, socket.AF_INET) class dispatcherwithsend_noread(asyncore.dispatcher_with_send): Modified: python/branches/release31-maint/Misc/NEWS ============================================================================== --- python/branches/release31-maint/Misc/NEWS (original) +++ python/branches/release31-maint/Misc/NEWS Thu May 6 20:37:34 2010 @@ -40,6 +40,12 @@ Library ------- +- Issue #8573: asyncore _strerror() function might throw ValueError. + +- Issue #8483: asyncore.dispatcher's __getattr__ method produced confusing + error messages when accessing undefined class attributes because of the cheap + inheritance with the underlying socket object. + - Issue #7472: Fixed typo in email.encoders module; messages using ISO-2022 character sets will now consistently use a Content-Transfer-Encoding of 7bit rather than sometimes being marked as 8bit. From python-checkins at python.org Thu May 6 21:56:34 2010 From: python-checkins at python.org (giampaolo.rodola) Date: Thu, 6 May 2010 21:56:34 +0200 (CEST) Subject: [Python-checkins] r80880 - python/trunk/Lib/asyncore.py Message-ID: <20100506195634.57D78E7DB@mail.python.org> Author: giampaolo.rodola Date: Thu May 6 21:56:34 2010 New Revision: 80880 Log: provides a clearer warning message when cheap inheritance with the underlying socket object is used Modified: python/trunk/Lib/asyncore.py Modified: python/trunk/Lib/asyncore.py ============================================================================== --- python/trunk/Lib/asyncore.py (original) +++ python/trunk/Lib/asyncore.py Thu May 6 21:56:34 2010 @@ -407,8 +407,9 @@ raise AttributeError("%s instance has no attribute '%s'" %(self.__class__.__name__, attr)) else: - warnings.warn("cheap inheritance is deprecated", DeprecationWarning, - stacklevel=2) + msg = "%(me)s.%(attr)s is deprecated. Use %(me)s.socket.%(attr)s " \ + "instead." % {'me': self.__class__.__name__, 'attr':attr} + warnings.warn(msg, DeprecationWarning, stacklevel=2) return retattr # log and log_info may be overridden to provide more sophisticated From python-checkins at python.org Thu May 6 22:02:37 2010 From: python-checkins at python.org (giampaolo.rodola) Date: Thu, 6 May 2010 22:02:37 +0200 (CEST) Subject: [Python-checkins] r80881 - in python/branches/py3k: Lib/asyncore.py Message-ID: <20100506200237.A25C6EE98D@mail.python.org> Author: giampaolo.rodola Date: Thu May 6 22:02:37 2010 New Revision: 80881 Log: Merged revisions 80880 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r80880 | giampaolo.rodola | 2010-05-06 21:56:34 +0200 (gio, 06 mag 2010) | 1 line provides a clearer warning message when cheap inheritance with the underlying socket object is used ........ Modified: python/branches/py3k/ (props changed) python/branches/py3k/Lib/asyncore.py Modified: python/branches/py3k/Lib/asyncore.py ============================================================================== --- python/branches/py3k/Lib/asyncore.py (original) +++ python/branches/py3k/Lib/asyncore.py Thu May 6 22:02:37 2010 @@ -407,8 +407,9 @@ raise AttributeError("%s instance has no attribute '%s'" %(self.__class__.__name__, attr)) else: - warnings.warn("cheap inheritance is deprecated", DeprecationWarning, - stacklevel=2) + msg = "%(me)s.%(attr)s is deprecated; use %(me)s.socket.%(attr)s " \ + "instead" % {'me' : self.__class__.__name__, 'attr' : attr} + warnings.warn(msg, DeprecationWarning, stacklevel=2) return retattr # log and log_info may be overridden to provide more sophisticated From python-checkins at python.org Thu May 6 22:19:32 2010 From: python-checkins at python.org (giampaolo.rodola) Date: Thu, 6 May 2010 22:19:32 +0200 (CEST) Subject: [Python-checkins] r80882 - in python/trunk/Lib/test: test_ftplib.py test_smtplib.py Message-ID: <20100506201932.A16A7EE98D@mail.python.org> Author: giampaolo.rodola Date: Thu May 6 22:19:32 2010 New Revision: 80882 Log: adds handle_error(self):raise to test modules using asyncore to provide a clearer error message in case something goes wrong Modified: python/trunk/Lib/test/test_ftplib.py python/trunk/Lib/test/test_smtplib.py Modified: python/trunk/Lib/test/test_ftplib.py ============================================================================== --- python/trunk/Lib/test/test_ftplib.py (original) +++ python/trunk/Lib/test/test_ftplib.py Thu May 6 22:19:32 2010 @@ -48,6 +48,9 @@ self.close() self.dtp_conn_closed = True + def handle_error(self): + raise + class DummyFTPHandler(asynchat.async_chat): Modified: python/trunk/Lib/test/test_smtplib.py ============================================================================== --- python/trunk/Lib/test/test_smtplib.py (original) +++ python/trunk/Lib/test/test_smtplib.py Thu May 6 22:19:32 2010 @@ -366,6 +366,9 @@ else: self.push('550 No access for you!') + def handle_error(self): + raise + class SimSMTPServer(smtpd.SMTPServer): @@ -384,6 +387,9 @@ def add_feature(self, feature): self._extra_features.append(feature) + def handle_error(self): + raise + # Test various SMTP & ESMTP commands/behaviors that require a simulated server # (i.e., something with more features than DebuggingServer) From python-checkins at python.org Thu May 6 22:21:57 2010 From: python-checkins at python.org (giampaolo.rodola) Date: Thu, 6 May 2010 22:21:57 +0200 (CEST) Subject: [Python-checkins] r80883 - in python/branches/py3k: Lib/test/test_ftplib.py Lib/test/test_smtplib.py Message-ID: <20100506202157.E3047EE992@mail.python.org> Author: giampaolo.rodola Date: Thu May 6 22:21:57 2010 New Revision: 80883 Log: Merged revisions 80882 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r80882 | giampaolo.rodola | 2010-05-06 22:19:32 +0200 (gio, 06 mag 2010) | 1 line adds handle_error(self):raise to test modules using asyncore to provide a clearer error message in case something goes wrong ........ Modified: python/branches/py3k/ (props changed) python/branches/py3k/Lib/test/test_ftplib.py python/branches/py3k/Lib/test/test_smtplib.py Modified: python/branches/py3k/Lib/test/test_ftplib.py ============================================================================== --- python/branches/py3k/Lib/test/test_ftplib.py (original) +++ python/branches/py3k/Lib/test/test_ftplib.py Thu May 6 22:21:57 2010 @@ -50,6 +50,9 @@ def push(self, what): super(DummyDTPHandler, self).push(what.encode('ascii')) + def handle_error(self): + raise + class DummyFTPHandler(asynchat.async_chat): Modified: python/branches/py3k/Lib/test/test_smtplib.py ============================================================================== --- python/branches/py3k/Lib/test/test_smtplib.py (original) +++ python/branches/py3k/Lib/test/test_smtplib.py Thu May 6 22:21:57 2010 @@ -374,6 +374,9 @@ else: self.push('550 No access for you!') + def handle_error(self): + raise + class SimSMTPServer(smtpd.SMTPServer): @@ -392,6 +395,9 @@ def add_feature(self, feature): self._extra_features.append(feature) + def handle_error(self): + raise + # Test various SMTP & ESMTP commands/behaviors that require a simulated server # (i.e., something with more features than DebuggingServer) From nnorwitz at gmail.com Thu May 6 22:53:57 2010 From: nnorwitz at gmail.com (Neal Norwitz) Date: Thu, 6 May 2010 16:53:57 -0400 Subject: [Python-checkins] Python Regression Test Failures opt (1) Message-ID: <20100506205357.GA30530@kbk-i386-bb.psfb.org> 347 tests OK. 1 test failed: test_subprocess 36 tests skipped: test_aepack test_al test_applesingle test_bsddb185 test_bsddb3 test_cd test_cl test_curses test_epoll test_gdb test_gl test_imgfile test_ioctl test_kqueue test_linuxaudiodev test_macos test_macostools test_multiprocessing test_ossaudiodev test_py3kwarn test_scriptpackages test_smtpnet test_socketserver test_startfile test_sunaudiodev test_tcl test_timeout test_tk test_ttk_guionly test_ttk_textonly test_unicode_file test_urllib2net test_urllibnet test_winreg test_winsound test_zipfile64 7 skips unexpected on linux2: test_epoll test_gdb test_ioctl test_multiprocessing test_tk test_ttk_guionly test_ttk_textonly == CPython 2.7b1+ (trunk:80880M, May 6 2010, 16:01:42) [GCC 3.3.4 20040623 (Gentoo Linux 3.3.4-r1, ssp-3.3.2-2, pie-8.7.6)] == Linux-2.6.9-gentoo-r1-i686-AMD_Athlon-tm-_XP_3000+-with-gentoo-1.4.16 == /tmp/test_python_10967 test_grammar test_opcodes test_dict test_builtin test_exceptions test_types test_unittest test_doctest test_doctest2 test_MimeWriter test_SimpleHTTPServer test_StringIO test___all__ test___future__ test__locale test_abc test_abstract_numbers test_aepack test_aepack skipped -- No module named aetypes test_aifc test_al test_al skipped -- No module named al test_anydbm test_applesingle test_applesingle skipped -- No module named MacOS test_argparse test_array test_ascii_formatd test_ast test_asynchat test_asyncore test_atexit test_audioop test_augassign test_base64 test_bastion test_bigaddrspace test_bigmem test_binascii test_binhex test_binop test_bisect test_bool test_bsddb test_bsddb185 test_bsddb185 skipped -- No module named bsddb185 test_bsddb3 test_bsddb3 skipped -- Use of the `bsddb' resource not enabled test_buffer test_bufio test_bytes test_bz2 test_calendar test_call test_capi test_cd test_cd skipped -- No module named cd test_cfgparser test_cgi test_charmapcodec test_cl test_cl skipped -- No module named cl test_class test_cmath test_cmd test_cmd_line test_cmd_line_script test_code test_codeccallbacks test_codecencodings_cn test_codecencodings_hk test_codecencodings_jp test_codecencodings_kr test_codecencodings_tw test_codecmaps_cn test_codecmaps_hk test_codecmaps_jp test_codecmaps_kr test_codecmaps_tw test_codecs test_codeop test_coding test_coercion test_collections test_colorsys test_commands test_compare test_compile test_compileall test_compiler test_complex test_complex_args test_contains test_contextlib test_cookie test_cookielib test_copy test_copy_reg test_cpickle test_cprofile test_crypt test_csv test_ctypes test_curses test_curses skipped -- Use of the `curses' resource not enabled test_datetime test_dbm test_decimal test_decorators test_defaultdict test_deque test_descr test_descrtut test_dictcomps test_dictviews test_difflib test_dircache test_dis test_distutils [20649 refs] [20649 refs] [20649 refs] [20649 refs] [20646 refs] test_dl test_docxmlrpc test_dumbdbm test_dummy_thread test_dummy_threading test_email test_email_codecs test_email_renamed test_enumerate test_eof test_epoll test_epoll skipped -- kernel doesn't support epoll() test_errno test_exception_variations test_extcall test_fcntl test_file test_file2k test_filecmp test_fileinput test_fileio test_float test_fnmatch test_fork1 test_format test_fpformat test_fractions test_frozen test_ftplib test_funcattrs test_functools test_future test_future3 test_future4 test_future5 test_future_builtins test_gc test_gdb test_gdb skipped -- gdb versions before 7.0 didn't support python embedding Saw: GNU gdb 6.2.1 Copyright 2004 Free Software Foundation, Inc. GDB is free software, covered by the GNU General Public License, and you are welcome to change it and/or distribute copies of it under certain conditions. Type "show copying" to see the conditions. There is absolutely no warranty for GDB. Type "show warranty" for details. This GDB was configured as "i386-pc-linux-gnu". test_gdbm test_generators test_genericpath test_genexps test_getargs test_getargs2 test_getopt test_gettext test_gl test_gl skipped -- No module named gl test_glob test_global test_grp test_gzip test_hash test_hashlib test_heapq test_hmac test_hotshot test_htmllib test_htmlparser test_httplib test_httpservers [16651 refs] [16651 refs] [16651 refs] [26931 refs] test_imageop test_imaplib test_imgfile test_imgfile skipped -- No module named imgfile test_imp test_import test_importhooks test_importlib test_index test_inspect test_int test_int_literal test_io test_ioctl test_ioctl skipped -- Unable to open /dev/tty test_isinstance test_iter test_iterlen test_itertools test_json test_kqueue test_kqueue skipped -- test works only on BSD test_largefile test_lib2to3 test_linecache test_linuxaudiodev test_linuxaudiodev skipped -- Use of the `audio' resource not enabled test_list test_locale test_logging test_long test_long_future test_longexp test_macos test_macos skipped -- No module named MacOS test_macostools test_macostools skipped -- No module named MacOS test_macpath test_mailbox test_marshal test_math test_md5 test_memoryio test_memoryview test_mhlib test_mimetools test_mimetypes test_minidom test_mmap test_module test_modulefinder test_multibytecodec test_multibytecodec_support test_multifile test_multiprocessing test_multiprocessing skipped -- This platform lacks a functioning sem_open implementation, therefore, the required synchronization primitives needed will not function, see issue 3770. test_mutants test_mutex test_netrc test_new test_nis test_normalization test_ntpath test_old_mailbox test_openpty test_operator test_optparse test_os [16651 refs] [16651 refs] test_ossaudiodev test_ossaudiodev skipped -- Use of the `audio' resource not enabled test_parser Expecting 's_push: parser stack overflow' in next line s_push: parser stack overflow test_pdb test_peepholer test_pep247 test_pep263 test_pep277 test_pep292 test_pep352 test_pickle test_pickletools test_pipes test_pkg test_pkgimport test_pkgutil test_platform [18047 refs] [18047 refs] test_plistlib test_poll test_popen [16656 refs] [16656 refs] [16656 refs] test_popen2 test_poplib test_posix test_posixpath test_pow test_pprint test_print test_profile test_profilehooks test_property test_pstats test_pty test_pwd test_py3kwarn test_py3kwarn skipped -- test.test_py3kwarn must be run with the -3 flag test_pyclbr test_pydoc [21863 refs] [21863 refs] [21863 refs] [21863 refs] [21863 refs] [21862 refs] [21862 refs] test_pyexpat test_queue test_quopri [19480 refs] [19480 refs] test_random test_re test_readline test_repr test_resource test_rfc822 test_richcmp test_robotparser test_runpy test_sax test_scope test_scriptpackages test_scriptpackages skipped -- No module named aetools test_select test_set test_setcomps test_sets test_sgmllib test_sha test_shelve test_shlex test_shutil test_signal test_site [16651 refs] [16651 refs] [16651 refs] [16651 refs] test_slice test_smtplib test_smtpnet test_smtpnet skipped -- Use of the `network' resource not enabled test_socket test_socketserver test_socketserver skipped -- Use of the `network' resource not enabled test_softspace test_sort test_sqlite test_ssl test_startfile test_startfile skipped -- module os has no attribute startfile test_str test_strftime test_string test_stringprep test_strop test_strptime test_strtod test_struct test_structmembers test_structseq test_subprocess [16651 refs] [16651 refs] [16651 refs] [16651 refs] [16651 refs] [16651 refs] [16651 refs] [16651 refs] [16651 refs] [16651 refs] [16651 refs] [16651 refs] [16651 refs] [16651 refs] [16866 refs] [16651 refs] [16651 refs] [16651 refs] [16651 refs] [16651 refs] . [16651 refs] [16651 refs] this bit of output is from a test of stdout in a different process ... [16651 refs] [16651 refs] [16866 refs] [16651 refs] [16651 refs] [16651 refs] [16651 refs] [16651 refs] [16651 refs] [16651 refs] [16651 refs] [16651 refs] [16651 refs] [16651 refs] [16651 refs] [16651 refs] [16651 refs] [16651 refs] [16651 refs] [16651 refs] [16866 refs] [16651 refs] [16651 refs] [16651 refs] [16651 refs] [16651 refs] . [16651 refs] [16651 refs] this bit of output is from a test of stdout in a different process ... [16651 refs] [16651 refs] [16866 refs] test test_subprocess failed -- multiple errors occurred; run in verbose mode for details Re-running test 'test_subprocess' in verbose mode test_call_kwargs (test.test_subprocess.ProcessTestCase) ... [16651 refs] ERROR test_call_seq (test.test_subprocess.ProcessTestCase) ... [16651 refs] ERROR test_check_call_nonzero (test.test_subprocess.ProcessTestCase) ... [16651 refs] ERROR test_check_call_zero (test.test_subprocess.ProcessTestCase) ... [16651 refs] ERROR test_check_output (test.test_subprocess.ProcessTestCase) ... [16651 refs] ERROR test_check_output_nonzero (test.test_subprocess.ProcessTestCase) ... [16651 refs] ERROR test_check_output_stderr (test.test_subprocess.ProcessTestCase) ... ERROR test_check_output_stdout_arg (test.test_subprocess.ProcessTestCase) ... ERROR test_communicate (test.test_subprocess.ProcessTestCase) ... ERROR test_communicate_pipe_buf (test.test_subprocess.ProcessTestCase) ... ERROR test_communicate_pipe_fd_leak (test.test_subprocess.ProcessTestCase) ... [16651 refs] ERROR test_communicate_returns (test.test_subprocess.ProcessTestCase) ... [16651 refs] ERROR test_communicate_stderr (test.test_subprocess.ProcessTestCase) ... ERROR test_communicate_stdin (test.test_subprocess.ProcessTestCase) ... [16651 refs] ERROR test_communicate_stdout (test.test_subprocess.ProcessTestCase) ... [16651 refs] ERROR test_cwd (test.test_subprocess.ProcessTestCase) ... [16651 refs] ERROR test_env (test.test_subprocess.ProcessTestCase) ... [16651 refs] ERROR test_executable_with_cwd (test.test_subprocess.ProcessTestCase) ... [16651 refs] ERROR test_executable_without_cwd (test.test_subprocess.ProcessTestCase) ... [16651 refs] ERROR test_invalid_bufsize (test.test_subprocess.ProcessTestCase) ... ERROR test_leaking_fds_on_error (test.test_subprocess.ProcessTestCase) ... ERROR test_list2cmdline (test.test_subprocess.ProcessTestCase) ... ERROR test_no_leaking (test.test_subprocess.ProcessTestCase) ... ERROR test_poll (test.test_subprocess.ProcessTestCase) ... [16866 refs] ERROR test_stderr_filedes (test.test_subprocess.ProcessTestCase) ... ERROR test_stderr_fileobj (test.test_subprocess.ProcessTestCase) ... ERROR test_stderr_none (test.test_subprocess.ProcessTestCase) ... [16651 refs] ERROR test_stderr_pipe (test.test_subprocess.ProcessTestCase) ... ERROR test_stdin_filedes (test.test_subprocess.ProcessTestCase) ... [16651 refs] ERROR test_stdin_fileobj (test.test_subprocess.ProcessTestCase) ... [16651 refs] ERROR test_stdin_none (test.test_subprocess.ProcessTestCase) ... ERROR test_stdin_pipe (test.test_subprocess.ProcessTestCase) ... [16651 refs] ERROR test_stdout_filedes (test.test_subprocess.ProcessTestCase) ... [16651 refs] ERROR test_stdout_filedes_of_stdout (test.test_subprocess.ProcessTestCase) ... . [16651 refs] ERROR test_stdout_fileobj (test.test_subprocess.ProcessTestCase) ... [16651 refs] ERROR test_stdout_none (test.test_subprocess.ProcessTestCase) ... this bit of output is from a test of stdout in a different process ... ERROR test_stdout_pipe (test.test_subprocess.ProcessTestCase) ... [16651 refs] ERROR test_stdout_stderr_file (test.test_subprocess.ProcessTestCase) ... ERROR test_stdout_stderr_pipe (test.test_subprocess.ProcessTestCase) ... ERROR test_universal_newlines (test.test_subprocess.ProcessTestCase) ... [16651 refs] ERROR test_universal_newlines_communicate (test.test_subprocess.ProcessTestCase) ... ERROR test_wait (test.test_subprocess.ProcessTestCase) ... [16866 refs] ERROR test_writes_before_communicate (test.test_subprocess.ProcessTestCase) ... ERROR test_args_string (test.test_subprocess.POSIXProcessTestCase) ... [16651 refs] ERROR test_call_string (test.test_subprocess.POSIXProcessTestCase) ... [16651 refs] ERROR test_exceptions (test.test_subprocess.POSIXProcessTestCase) ... ERROR test_invalid_args (test.test_subprocess.POSIXProcessTestCase) ... ERROR test_kill (test.test_subprocess.POSIXProcessTestCase) ... ERROR test_preexec (test.test_subprocess.POSIXProcessTestCase) ... [16651 refs] ERROR test_run_abort (test.test_subprocess.POSIXProcessTestCase) ... ERROR test_send_signal (test.test_subprocess.POSIXProcessTestCase) ... ERROR test_shell_sequence (test.test_subprocess.POSIXProcessTestCase) ... ERROR test_shell_string (test.test_subprocess.POSIXProcessTestCase) ... ERROR test_terminate (test.test_subprocess.POSIXProcessTestCase) ... ERROR test_call_string (test.test_subprocess.Win32ProcessTestCase) ... skipped 'Windows specific tests' test_close_fds (test.test_subprocess.Win32ProcessTestCase) ... skipped 'Windows specific tests' test_creationflags (test.test_subprocess.Win32ProcessTestCase) ... skipped 'Windows specific tests' test_invalid_args (test.test_subprocess.Win32ProcessTestCase) ... skipped 'Windows specific tests' test_kill (test.test_subprocess.Win32ProcessTestCase) ... skipped 'Windows specific tests' test_send_signal (test.test_subprocess.Win32ProcessTestCase) ... skipped 'Windows specific tests' test_shell_sequence (test.test_subprocess.Win32ProcessTestCase) ... skipped 'Windows specific tests' test_shell_string (test.test_subprocess.Win32ProcessTestCase) ... skipped 'Windows specific tests' test_startupinfo (test.test_subprocess.Win32ProcessTestCase) ... skipped 'Windows specific tests' test_terminate (test.test_subprocess.Win32ProcessTestCase) ... skipped 'Windows specific tests' test_call_kwargs (test.test_subprocess.ProcessTestCaseNoPoll) ... [16651 refs] ERROR test_call_seq (test.test_subprocess.ProcessTestCaseNoPoll) ... [16651 refs] ERROR test_check_call_nonzero (test.test_subprocess.ProcessTestCaseNoPoll) ... [16651 refs] ERROR test_check_call_zero (test.test_subprocess.ProcessTestCaseNoPoll) ... [16651 refs] ERROR test_check_output (test.test_subprocess.ProcessTestCaseNoPoll) ... [16651 refs] ERROR test_check_output_nonzero (test.test_subprocess.ProcessTestCaseNoPoll) ... [16651 refs] ERROR test_check_output_stderr (test.test_subprocess.ProcessTestCaseNoPoll) ... ERROR test_check_output_stdout_arg (test.test_subprocess.ProcessTestCaseNoPoll) ... ERROR test_communicate (test.test_subprocess.ProcessTestCaseNoPoll) ... ERROR test_communicate_pipe_buf (test.test_subprocess.ProcessTestCaseNoPoll) ... ERROR test_communicate_pipe_fd_leak (test.test_subprocess.ProcessTestCaseNoPoll) ... [16651 refs] ERROR test_communicate_returns (test.test_subprocess.ProcessTestCaseNoPoll) ... [16651 refs] ERROR test_communicate_stderr (test.test_subprocess.ProcessTestCaseNoPoll) ... ERROR test_communicate_stdin (test.test_subprocess.ProcessTestCaseNoPoll) ... [16651 refs] ERROR test_communicate_stdout (test.test_subprocess.ProcessTestCaseNoPoll) ... [16651 refs] ERROR test_cwd (test.test_subprocess.ProcessTestCaseNoPoll) ... [16651 refs] ERROR test_env (test.test_subprocess.ProcessTestCaseNoPoll) ... [16651 refs] ERROR test_executable_with_cwd (test.test_subprocess.ProcessTestCaseNoPoll) ... [16651 refs] ERROR test_executable_without_cwd (test.test_subprocess.ProcessTestCaseNoPoll) ... [16651 refs] ERROR test_invalid_bufsize (test.test_subprocess.ProcessTestCaseNoPoll) ... ERROR test_leaking_fds_on_error (test.test_subprocess.ProcessTestCaseNoPoll) ... ERROR test_list2cmdline (test.test_subprocess.ProcessTestCaseNoPoll) ... ERROR test_no_leaking (test.test_subprocess.ProcessTestCaseNoPoll) ... ERROR test_poll (test.test_subprocess.ProcessTestCaseNoPoll) ... [16866 refs] ERROR test_stderr_filedes (test.test_subprocess.ProcessTestCaseNoPoll) ... ERROR test_stderr_fileobj (test.test_subprocess.ProcessTestCaseNoPoll) ... ERROR test_stderr_none (test.test_subprocess.ProcessTestCaseNoPoll) ... [16651 refs] ERROR test_stderr_pipe (test.test_subprocess.ProcessTestCaseNoPoll) ... ERROR test_stdin_filedes (test.test_subprocess.ProcessTestCaseNoPoll) ... [16651 refs] ERROR test_stdin_fileobj (test.test_subprocess.ProcessTestCaseNoPoll) ... [16651 refs] ERROR test_stdin_none (test.test_subprocess.ProcessTestCaseNoPoll) ... ERROR test_stdin_pipe (test.test_subprocess.ProcessTestCaseNoPoll) ... [16651 refs] ERROR test_stdout_filedes (test.test_subprocess.ProcessTestCaseNoPoll) ... [16651 refs] ERROR test_stdout_filedes_of_stdout (test.test_subprocess.ProcessTestCaseNoPoll) ... . [16651 refs] ERROR test_stdout_fileobj (test.test_subprocess.ProcessTestCaseNoPoll) ... [16651 refs] ERROR test_stdout_none (test.test_subprocess.ProcessTestCaseNoPoll) ... this bit of output is from a test of stdout in a different process ... ERROR test_stdout_pipe (test.test_subprocess.ProcessTestCaseNoPoll) ... [16651 refs] ERROR test_stdout_stderr_file (test.test_subprocess.ProcessTestCaseNoPoll) ... ERROR test_stdout_stderr_pipe (test.test_subprocess.ProcessTestCaseNoPoll) ... ERROR test_universal_newlines (test.test_subprocess.ProcessTestCaseNoPoll) ... [16651 refs] ERROR test_universal_newlines_communicate (test.test_subprocess.ProcessTestCaseNoPoll) ... ERROR test_wait (test.test_subprocess.ProcessTestCaseNoPoll) ... [16866 refs] ERROR test_writes_before_communicate (test.test_subprocess.ProcessTestCaseNoPoll) ... ERROR test_eintr_retry_call (test.test_subprocess.HelperFunctionTests) ... ok ====================================================================== ERROR: test_call_kwargs (test.test_subprocess.ProcessTestCase) ---------------------------------------------------------------------- Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/test_subprocess.py", line 46, in tearDown self.assertFalse(subprocess._active, "subprocess._active not empty") AssertionError: subprocess._active not empty ====================================================================== ERROR: test_call_seq (test.test_subprocess.ProcessTestCase) ---------------------------------------------------------------------- Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/test_subprocess.py", line 46, in tearDown self.assertFalse(subprocess._active, "subprocess._active not empty") AssertionError: subprocess._active not empty ====================================================================== ERROR: test_check_call_nonzero (test.test_subprocess.ProcessTestCase) ---------------------------------------------------------------------- Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/test_subprocess.py", line 46, in tearDown self.assertFalse(subprocess._active, "subprocess._active not empty") AssertionError: subprocess._active not empty ====================================================================== ERROR: test_check_call_zero (test.test_subprocess.ProcessTestCase) ---------------------------------------------------------------------- Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/test_subprocess.py", line 46, in tearDown self.assertFalse(subprocess._active, "subprocess._active not empty") AssertionError: subprocess._active not empty ====================================================================== ERROR: test_check_output (test.test_subprocess.ProcessTestCase) ---------------------------------------------------------------------- Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/test_subprocess.py", line 46, in tearDown self.assertFalse(subprocess._active, "subprocess._active not empty") AssertionError: subprocess._active not empty ====================================================================== ERROR: test_check_output_nonzero (test.test_subprocess.ProcessTestCase) ---------------------------------------------------------------------- Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/test_subprocess.py", line 46, in tearDown self.assertFalse(subprocess._active, "subprocess._active not empty") AssertionError: subprocess._active not empty ====================================================================== ERROR: test_check_output_stderr (test.test_subprocess.ProcessTestCase) ---------------------------------------------------------------------- Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/test_subprocess.py", line 46, in tearDown self.assertFalse(subprocess._active, "subprocess._active not empty") AssertionError: subprocess._active not empty ====================================================================== ERROR: test_check_output_stdout_arg (test.test_subprocess.ProcessTestCase) ---------------------------------------------------------------------- Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/test_subprocess.py", line 46, in tearDown self.assertFalse(subprocess._active, "subprocess._active not empty") AssertionError: subprocess._active not empty ====================================================================== ERROR: test_communicate (test.test_subprocess.ProcessTestCase) ---------------------------------------------------------------------- Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/test_subprocess.py", line 46, in tearDown self.assertFalse(subprocess._active, "subprocess._active not empty") AssertionError: subprocess._active not empty ====================================================================== ERROR: test_communicate_pipe_buf (test.test_subprocess.ProcessTestCase) ---------------------------------------------------------------------- Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/test_subprocess.py", line 46, in tearDown self.assertFalse(subprocess._active, "subprocess._active not empty") AssertionError: subprocess._active not empty ====================================================================== ERROR: test_communicate_pipe_fd_leak (test.test_subprocess.ProcessTestCase) ---------------------------------------------------------------------- Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/test_subprocess.py", line 46, in tearDown self.assertFalse(subprocess._active, "subprocess._active not empty") AssertionError: subprocess._active not empty ====================================================================== ERROR: test_communicate_returns (test.test_subprocess.ProcessTestCase) ---------------------------------------------------------------------- Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/test_subprocess.py", line 46, in tearDown self.assertFalse(subprocess._active, "subprocess._active not empty") AssertionError: subprocess._active not empty ====================================================================== ERROR: test_communicate_stderr (test.test_subprocess.ProcessTestCase) ---------------------------------------------------------------------- Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/test_subprocess.py", line 46, in tearDown self.assertFalse(subprocess._active, "subprocess._active not empty") AssertionError: subprocess._active not empty ====================================================================== ERROR: test_communicate_stdin (test.test_subprocess.ProcessTestCase) ---------------------------------------------------------------------- Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/test_subprocess.py", line 46, in tearDown self.assertFalse(subprocess._active, "subprocess._active not empty") AssertionError: subprocess._active not empty ====================================================================== ERROR: test_communicate_stdout (test.test_subprocess.ProcessTestCase) ---------------------------------------------------------------------- Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/test_subprocess.py", line 46, in tearDown self.assertFalse(subprocess._active, "subprocess._active not empty") AssertionError: subprocess._active not empty ====================================================================== ERROR: test_cwd (test.test_subprocess.ProcessTestCase) ---------------------------------------------------------------------- Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/test_subprocess.py", line 46, in tearDown self.assertFalse(subprocess._active, "subprocess._active not empty") AssertionError: subprocess._active not empty ====================================================================== ERROR: test_env (test.test_subprocess.ProcessTestCase) ---------------------------------------------------------------------- Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/test_subprocess.py", line 46, in tearDown self.assertFalse(subprocess._active, "subprocess._active not empty") AssertionError: subprocess._active not empty ====================================================================== ERROR: test_executable_with_cwd (test.test_subprocess.ProcessTestCase) ---------------------------------------------------------------------- Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/test_subprocess.py", line 46, in tearDown self.assertFalse(subprocess._active, "subprocess._active not empty") AssertionError: subprocess._active not empty ====================================================================== ERROR: test_executable_without_cwd (test.test_subprocess.ProcessTestCase) ---------------------------------------------------------------------- Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/test_subprocess.py", line 46, in tearDown self.assertFalse(subprocess._active, "subprocess._active not empty") AssertionError: subprocess._active not empty ====================================================================== ERROR: test_invalid_bufsize (test.test_subprocess.ProcessTestCase) ---------------------------------------------------------------------- Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/test_subprocess.py", line 46, in tearDown self.assertFalse(subprocess._active, "subprocess._active not empty") AssertionError: subprocess._active not empty ====================================================================== ERROR: test_leaking_fds_on_error (test.test_subprocess.ProcessTestCase) ---------------------------------------------------------------------- Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/test_subprocess.py", line 46, in tearDown self.assertFalse(subprocess._active, "subprocess._active not empty") AssertionError: subprocess._active not empty ====================================================================== ERROR: test_list2cmdline (test.test_subprocess.ProcessTestCase) ---------------------------------------------------------------------- Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/test_subprocess.py", line 46, in tearDown self.assertFalse(subprocess._active, "subprocess._active not empty") AssertionError: subprocess._active not empty ====================================================================== ERROR: test_no_leaking (test.test_subprocess.ProcessTestCase) ---------------------------------------------------------------------- Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/test_subprocess.py", line 46, in tearDown self.assertFalse(subprocess._active, "subprocess._active not empty") AssertionError: subprocess._active not empty ====================================================================== ERROR: test_poll (test.test_subprocess.ProcessTestCase) ---------------------------------------------------------------------- Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/test_subprocess.py", line 46, in tearDown self.assertFalse(subprocess._active, "subprocess._active not empty") AssertionError: subprocess._active not empty ====================================================================== ERROR: test_stderr_filedes (test.test_subprocess.ProcessTestCase) ---------------------------------------------------------------------- Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/test_subprocess.py", line 46, in tearDown self.assertFalse(subprocess._active, "subprocess._active not empty") AssertionError: subprocess._active not empty ====================================================================== ERROR: test_stderr_fileobj (test.test_subprocess.ProcessTestCase) ---------------------------------------------------------------------- Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/test_subprocess.py", line 46, in tearDown self.assertFalse(subprocess._active, "subprocess._active not empty") AssertionError: subprocess._active not empty ====================================================================== ERROR: test_stderr_none (test.test_subprocess.ProcessTestCase) ---------------------------------------------------------------------- Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/test_subprocess.py", line 46, in tearDown self.assertFalse(subprocess._active, "subprocess._active not empty") AssertionError: subprocess._active not empty ====================================================================== ERROR: test_stderr_pipe (test.test_subprocess.ProcessTestCase) ---------------------------------------------------------------------- Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/test_subprocess.py", line 46, in tearDown self.assertFalse(subprocess._active, "subprocess._active not empty") AssertionError: subprocess._active not empty ====================================================================== ERROR: test_stdin_filedes (test.test_subprocess.ProcessTestCase) ---------------------------------------------------------------------- Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/test_subprocess.py", line 46, in tearDown self.assertFalse(subprocess._active, "subprocess._active not empty") AssertionError: subprocess._active not empty ====================================================================== ERROR: test_stdin_fileobj (test.test_subprocess.ProcessTestCase) ---------------------------------------------------------------------- Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/test_subprocess.py", line 46, in tearDown self.assertFalse(subprocess._active, "subprocess._active not empty") AssertionError: subprocess._active not empty ====================================================================== ERROR: test_stdin_none (test.test_subprocess.ProcessTestCase) ---------------------------------------------------------------------- Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/test_subprocess.py", line 46, in tearDown self.assertFalse(subprocess._active, "subprocess._active not empty") AssertionError: subprocess._active not empty ====================================================================== ERROR: test_stdin_pipe (test.test_subprocess.ProcessTestCase) ---------------------------------------------------------------------- Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/test_subprocess.py", line 46, in tearDown self.assertFalse(subprocess._active, "subprocess._active not empty") AssertionError: subprocess._active not empty ====================================================================== ERROR: test_stdout_filedes (test.test_subprocess.ProcessTestCase) ---------------------------------------------------------------------- Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/test_subprocess.py", line 46, in tearDown self.assertFalse(subprocess._active, "subprocess._active not empty") AssertionError: subprocess._active not empty ====================================================================== ERROR: test_stdout_filedes_of_stdout (test.test_subprocess.ProcessTestCase) ---------------------------------------------------------------------- Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/test_subprocess.py", line 46, in tearDown self.assertFalse(subprocess._active, "subprocess._active not empty") AssertionError: subprocess._active not empty ====================================================================== ERROR: test_stdout_fileobj (test.test_subprocess.ProcessTestCase) ---------------------------------------------------------------------- Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/test_subprocess.py", line 46, in tearDown self.assertFalse(subprocess._active, "subprocess._active not empty") AssertionError: subprocess._active not empty ====================================================================== ERROR: test_stdout_none (test.test_subprocess.ProcessTestCase) ---------------------------------------------------------------------- Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/test_subprocess.py", line 46, in tearDown self.assertFalse(subprocess._active, "subprocess._active not empty") AssertionError: subprocess._active not empty ====================================================================== ERROR: test_stdout_pipe (test.test_subprocess.ProcessTestCase) ---------------------------------------------------------------------- Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/test_subprocess.py", line 46, in tearDown self.assertFalse(subprocess._active, "subprocess._active not empty") AssertionError: subprocess._active not empty ====================================================================== ERROR: test_stdout_stderr_file (test.test_subprocess.ProcessTestCase) ---------------------------------------------------------------------- Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/test_subprocess.py", line 46, in tearDown self.assertFalse(subprocess._active, "subprocess._active not empty") AssertionError: subprocess._active not empty ====================================================================== ERROR: test_stdout_stderr_pipe (test.test_subprocess.ProcessTestCase) ---------------------------------------------------------------------- Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/test_subprocess.py", line 46, in tearDown self.assertFalse(subprocess._active, "subprocess._active not empty") AssertionError: subprocess._active not empty ====================================================================== ERROR: test_universal_newlines (test.test_subprocess.ProcessTestCase) ---------------------------------------------------------------------- Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/test_subprocess.py", line 46, in tearDown self.assertFalse(subprocess._active, "subprocess._active not empty") AssertionError: subprocess._active not empty ====================================================================== ERROR: test_universal_newlines_communicate (test.test_subprocess.ProcessTestCase) ---------------------------------------------------------------------- Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/test_subprocess.py", line 46, in tearDown self.assertFalse(subprocess._active, "subprocess._active not empty") AssertionError: subprocess._active not empty ====================================================================== ERROR: test_wait (test.test_subprocess.ProcessTestCase) ---------------------------------------------------------------------- Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/test_subprocess.py", line 46, in tearDown self.assertFalse(subprocess._active, "subprocess._active not empty") AssertionError: subprocess._active not empty ====================================================================== ERROR: test_writes_before_communicate (test.test_subprocess.ProcessTestCase) ---------------------------------------------------------------------- Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/test_subprocess.py", line 46, in tearDown self.assertFalse(subprocess._active, "subprocess._active not empty") AssertionError: subprocess._active not empty ====================================================================== ERROR: test_args_string (test.test_subprocess.POSIXProcessTestCase) ---------------------------------------------------------------------- Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/test_subprocess.py", line 46, in tearDown self.assertFalse(subprocess._active, "subprocess._active not empty") AssertionError: subprocess._active not empty ====================================================================== ERROR: test_call_string (test.test_subprocess.POSIXProcessTestCase) ---------------------------------------------------------------------- Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/test_subprocess.py", line 46, in tearDown self.assertFalse(subprocess._active, "subprocess._active not empty") AssertionError: subprocess._active not empty ====================================================================== ERROR: test_exceptions (test.test_subprocess.POSIXProcessTestCase) ---------------------------------------------------------------------- Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/test_subprocess.py", line 46, in tearDown self.assertFalse(subprocess._active, "subprocess._active not empty") AssertionError: subprocess._active not empty ====================================================================== ERROR: test_invalid_args (test.test_subprocess.POSIXProcessTestCase) ---------------------------------------------------------------------- Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/test_subprocess.py", line 46, in tearDown self.assertFalse(subprocess._active, "subprocess._active not empty") AssertionError: subprocess._active not empty ====================================================================== ERROR: test_kill (test.test_subprocess.POSIXProcessTestCase) ---------------------------------------------------------------------- Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/test_subprocess.py", line 46, in tearDown self.assertFalse(subprocess._active, "subprocess._active not empty") AssertionError: subprocess._active not empty ====================================================================== ERROR: test_preexec (test.test_subprocess.POSIXProcessTestCase) ---------------------------------------------------------------------- Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/test_subprocess.py", line 46, in tearDown self.assertFalse(subprocess._active, "subprocess._active not empty") AssertionError: subprocess._active not empty ====================================================================== ERROR: test_run_abort (test.test_subprocess.POSIXProcessTestCase) ---------------------------------------------------------------------- Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/test_subprocess.py", line 46, in tearDown self.assertFalse(subprocess._active, "subprocess._active not empty") AssertionError: subprocess._active not empty ====================================================================== ERROR: test_send_signal (test.test_subprocess.POSIXProcessTestCase) ---------------------------------------------------------------------- Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/test_subprocess.py", line 46, in tearDown self.assertFalse(subprocess._active, "subprocess._active not empty") AssertionError: subprocess._active not empty ====================================================================== ERROR: test_shell_sequence (test.test_subprocess.POSIXProcessTestCase) ---------------------------------------------------------------------- Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/test_subprocess.py", line 46, in tearDown self.assertFalse(subprocess._active, "subprocess._active not empty") AssertionError: subprocess._active not empty ====================================================================== ERROR: test_shell_string (test.test_subprocess.POSIXProcessTestCase) ---------------------------------------------------------------------- Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/test_subprocess.py", line 46, in tearDown self.assertFalse(subprocess._active, "subprocess._active not empty") AssertionError: subprocess._active not empty ====================================================================== ERROR: test_terminate (test.test_subprocess.POSIXProcessTestCase) ---------------------------------------------------------------------- Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/test_subprocess.py", line 46, in tearDown self.assertFalse(subprocess._active, "subprocess._active not empty") AssertionError: subprocess._active not empty ====================================================================== ERROR: test_call_kwargs (test.test_subprocess.ProcessTestCaseNoPoll) ---------------------------------------------------------------------- Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/test_subprocess.py", line 802, in tearDown ProcessTestCase.tearDown(self) File "/tmp/python-test/local/lib/python2.7/test/test_subprocess.py", line 46, in tearDown self.assertFalse(subprocess._active, "subprocess._active not empty") AssertionError: subprocess._active not empty ====================================================================== ERROR: test_call_seq (test.test_subprocess.ProcessTestCaseNoPoll) ---------------------------------------------------------------------- Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/test_subprocess.py", line 802, in tearDown ProcessTestCase.tearDown(self) File "/tmp/python-test/local/lib/python2.7/test/test_subprocess.py", line 46, in tearDown self.assertFalse(subprocess._active, "subprocess._active not empty") AssertionError: subprocess._active not empty ====================================================================== ERROR: test_check_call_nonzero (test.test_subprocess.ProcessTestCaseNoPoll) ---------------------------------------------------------------------- Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/test_subprocess.py", line 802, in tearDown ProcessTestCase.tearDown(self) File "/tmp/python-test/local/lib/python2.7/test/test_subprocess.py", line 46, in tearDown self.assertFalse(subprocess._active, "subprocess._active not empty") AssertionError: subprocess._active not empty ====================================================================== ERROR: test_check_call_zero (test.test_subprocess.ProcessTestCaseNoPoll) ---------------------------------------------------------------------- Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/test_subprocess.py", line 802, in tearDown ProcessTestCase.tearDown(self) File "/tmp/python-test/local/lib/python2.7/test/test_subprocess.py", line 46, in tearDown self.assertFalse(subprocess._active, "subprocess._active not empty") AssertionError: subprocess._active not empty ====================================================================== ERROR: test_check_output (test.test_subprocess.ProcessTestCaseNoPoll) ---------------------------------------------------------------------- Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/test_subprocess.py", line 802, in tearDown ProcessTestCase.tearDown(self) File "/tmp/python-test/local/lib/python2.7/test/test_subprocess.py", line 46, in tearDown self.assertFalse(subprocess._active, "subprocess._active not empty") AssertionError: subprocess._active not empty ====================================================================== ERROR: test_check_output_nonzero (test.test_subprocess.ProcessTestCaseNoPoll) ---------------------------------------------------------------------- Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/test_subprocess.py", line 802, in tearDown ProcessTestCase.tearDown(self) File "/tmp/python-test/local/lib/python2.7/test/test_subprocess.py", line 46, in tearDown self.assertFalse(subprocess._active, "subprocess._active not empty") AssertionError: subprocess._active not empty ====================================================================== ERROR: test_check_output_stderr (test.test_subprocess.ProcessTestCaseNoPoll) ---------------------------------------------------------------------- Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/test_subprocess.py", line 802, in tearDown ProcessTestCase.tearDown(self) File "/tmp/python-test/local/lib/python2.7/test/test_subprocess.py", line 46, in tearDown self.assertFalse(subprocess._active, "subprocess._active not empty") AssertionError: subprocess._active not empty ====================================================================== ERROR: test_check_output_stdout_arg (test.test_subprocess.ProcessTestCaseNoPoll) ---------------------------------------------------------------------- Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/test_subprocess.py", line 802, in tearDown ProcessTestCase.tearDown(self) File "/tmp/python-test/local/lib/python2.7/test/test_subprocess.py", line 46, in tearDown self.assertFalse(subprocess._active, "subprocess._active not empty") AssertionError: subprocess._active not empty ====================================================================== ERROR: test_communicate (test.test_subprocess.ProcessTestCaseNoPoll) ---------------------------------------------------------------------- Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/test_subprocess.py", line 802, in tearDown ProcessTestCase.tearDown(self) File "/tmp/python-test/local/lib/python2.7/test/test_subprocess.py", line 46, in tearDown self.assertFalse(subprocess._active, "subprocess._active not empty") AssertionError: subprocess._active not empty ====================================================================== ERROR: test_communicate_pipe_buf (test.test_subprocess.ProcessTestCaseNoPoll) ---------------------------------------------------------------------- Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/test_subprocess.py", line 802, in tearDown ProcessTestCase.tearDown(self) File "/tmp/python-test/local/lib/python2.7/test/test_subprocess.py", line 46, in tearDown self.assertFalse(subprocess._active, "subprocess._active not empty") AssertionError: subprocess._active not empty ====================================================================== ERROR: test_communicate_pipe_fd_leak (test.test_subprocess.ProcessTestCaseNoPoll) ---------------------------------------------------------------------- Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/test_subprocess.py", line 802, in tearDown ProcessTestCase.tearDown(self) File "/tmp/python-test/local/lib/python2.7/test/test_subprocess.py", line 46, in tearDown self.assertFalse(subprocess._active, "subprocess._active not empty") AssertionError: subprocess._active not empty ====================================================================== ERROR: test_communicate_returns (test.test_subprocess.ProcessTestCaseNoPoll) ---------------------------------------------------------------------- Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/test_subprocess.py", line 802, in tearDown ProcessTestCase.tearDown(self) File "/tmp/python-test/local/lib/python2.7/test/test_subprocess.py", line 46, in tearDown self.assertFalse(subprocess._active, "subprocess._active not empty") AssertionError: subprocess._active not empty ====================================================================== ERROR: test_communicate_stderr (test.test_subprocess.ProcessTestCaseNoPoll) ---------------------------------------------------------------------- Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/test_subprocess.py", line 802, in tearDown ProcessTestCase.tearDown(self) File "/tmp/python-test/local/lib/python2.7/test/test_subprocess.py", line 46, in tearDown self.assertFalse(subprocess._active, "subprocess._active not empty") AssertionError: subprocess._active not empty ====================================================================== ERROR: test_communicate_stdin (test.test_subprocess.ProcessTestCaseNoPoll) ---------------------------------------------------------------------- Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/test_subprocess.py", line 802, in tearDown ProcessTestCase.tearDown(self) File "/tmp/python-test/local/lib/python2.7/test/test_subprocess.py", line 46, in tearDown self.assertFalse(subprocess._active, "subprocess._active not empty") AssertionError: subprocess._active not empty ====================================================================== ERROR: test_communicate_stdout (test.test_subprocess.ProcessTestCaseNoPoll) ---------------------------------------------------------------------- Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/test_subprocess.py", line 802, in tearDown ProcessTestCase.tearDown(self) File "/tmp/python-test/local/lib/python2.7/test/test_subprocess.py", line 46, in tearDown self.assertFalse(subprocess._active, "subprocess._active not empty") AssertionError: subprocess._active not empty ====================================================================== ERROR: test_cwd (test.test_subprocess.ProcessTestCaseNoPoll) ---------------------------------------------------------------------- Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/test_subprocess.py", line 802, in tearDown ProcessTestCase.tearDown(self) File "/tmp/python-test/local/lib/python2.7/test/test_subprocess.py", line 46, in tearDown self.assertFalse(subprocess._active, "subprocess._active not empty") AssertionError: subprocess._active not empty ====================================================================== ERROR: test_env (test.test_subprocess.ProcessTestCaseNoPoll) ---------------------------------------------------------------------- Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/test_subprocess.py", line 802, in tearDown ProcessTestCase.tearDown(self) File "/tmp/python-test/local/lib/python2.7/test/test_subprocess.py", line 46, in tearDown self.assertFalse(subprocess._active, "subprocess._active not empty") AssertionError: subprocess._active not empty ====================================================================== ERROR: test_executable_with_cwd (test.test_subprocess.ProcessTestCaseNoPoll) ---------------------------------------------------------------------- Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/test_subprocess.py", line 802, in tearDown ProcessTestCase.tearDown(self) File "/tmp/python-test/local/lib/python2.7/test/test_subprocess.py", line 46, in tearDown self.assertFalse(subprocess._active, "subprocess._active not empty") AssertionError: subprocess._active not empty ====================================================================== ERROR: test_executable_without_cwd (test.test_subprocess.ProcessTestCaseNoPoll) ---------------------------------------------------------------------- Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/test_subprocess.py", line 802, in tearDown ProcessTestCase.tearDown(self) File "/tmp/python-test/local/lib/python2.7/test/test_subprocess.py", line 46, in tearDown self.assertFalse(subprocess._active, "subprocess._active not empty") AssertionError: subprocess._active not empty ====================================================================== ERROR: test_invalid_bufsize (test.test_subprocess.ProcessTestCaseNoPoll) ---------------------------------------------------------------------- Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/test_subprocess.py", line 802, in tearDown ProcessTestCase.tearDown(self) File "/tmp/python-test/local/lib/python2.7/test/test_subprocess.py", line 46, in tearDown self.assertFalse(subprocess._active, "subprocess._active not empty") AssertionError: subprocess._active not empty ====================================================================== ERROR: test_leaking_fds_on_error (test.test_subprocess.ProcessTestCaseNoPoll) ---------------------------------------------------------------------- Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/test_subprocess.py", line 802, in tearDown ProcessTestCase.tearDown(self) File "/tmp/python-test/local/lib/python2.7/test/test_subprocess.py", line 46, in tearDown self.assertFalse(subprocess._active, "subprocess._active not empty") AssertionError: subprocess._active not empty ====================================================================== ERROR: test_list2cmdline (test.test_subprocess.ProcessTestCaseNoPoll) ---------------------------------------------------------------------- Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/test_subprocess.py", line 802, in tearDown ProcessTestCase.tearDown(self) File "/tmp/python-test/local/lib/python2.7/test/test_subprocess.py", line 46, in tearDown self.assertFalse(subprocess._active, "subprocess._active not empty") AssertionError: subprocess._active not empty ====================================================================== ERROR: test_no_leaking (test.test_subprocess.ProcessTestCaseNoPoll) ---------------------------------------------------------------------- Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/test_subprocess.py", line 802, in tearDown ProcessTestCase.tearDown(self) File "/tmp/python-test/local/lib/python2.7/test/test_subprocess.py", line 46, in tearDown self.assertFalse(subprocess._active, "subprocess._active not empty") AssertionError: subprocess._active not empty ====================================================================== ERROR: test_poll (test.test_subprocess.ProcessTestCaseNoPoll) ---------------------------------------------------------------------- Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/test_subprocess.py", line 802, in tearDown ProcessTestCase.tearDown(self) File "/tmp/python-test/local/lib/python2.7/test/test_subprocess.py", line 46, in tearDown self.assertFalse(subprocess._active, "subprocess._active not empty") AssertionError: subprocess._active not empty ====================================================================== ERROR: test_stderr_filedes (test.test_subprocess.ProcessTestCaseNoPoll) ---------------------------------------------------------------------- Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/test_subprocess.py", line 802, in tearDown ProcessTestCase.tearDown(self) File "/tmp/python-test/local/lib/python2.7/test/test_subprocess.py", line 46, in tearDown self.assertFalse(subprocess._active, "subprocess._active not empty") AssertionError: subprocess._active not empty ====================================================================== ERROR: test_stderr_fileobj (test.test_subprocess.ProcessTestCaseNoPoll) ---------------------------------------------------------------------- Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/test_subprocess.py", line 802, in tearDown ProcessTestCase.tearDown(self) File "/tmp/python-test/local/lib/python2.7/test/test_subprocess.py", line 46, in tearDown self.assertFalse(subprocess._active, "subprocess._active not empty") AssertionError: subprocess._active not empty ====================================================================== ERROR: test_stderr_none (test.test_subprocess.ProcessTestCaseNoPoll) ---------------------------------------------------------------------- Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/test_subprocess.py", line 802, in tearDown ProcessTestCase.tearDown(self) File "/tmp/python-test/local/lib/python2.7/test/test_subprocess.py", line 46, in tearDown self.assertFalse(subprocess._active, "subprocess._active not empty") AssertionError: subprocess._active not empty ====================================================================== ERROR: test_stderr_pipe (test.test_subprocess.ProcessTestCaseNoPoll) ---------------------------------------------------------------------- Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/test_subprocess.py", line 802, in tearDown ProcessTestCase.tearDown(self) File "/tmp/python-test/local/lib/python2.7/test/test_subprocess.py", line 46, in tearDown self.assertFalse(subprocess._active, "subprocess._active not empty") AssertionError: subprocess._active not empty ====================================================================== ERROR: test_stdin_filedes (test.test_subprocess.ProcessTestCaseNoPoll) ---------------------------------------------------------------------- Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/test_subprocess.py", line 802, in tearDown ProcessTestCase.tearDown(self) File "/tmp/python-test/local/lib/python2.7/test/test_subprocess.py", line 46, in tearDown self.assertFalse(subprocess._active, "subprocess._active not empty") AssertionError: subprocess._active not empty ====================================================================== ERROR: test_stdin_fileobj (test.test_subprocess.ProcessTestCaseNoPoll) ---------------------------------------------------------------------- Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/test_subprocess.py", line 802, in tearDown ProcessTestCase.tearDown(self) File "/tmp/python-test/local/lib/python2.7/test/test_subprocess.py", line 46, in tearDown self.assertFalse(subprocess._active, "subprocess._active not empty") AssertionError: subprocess._active not empty ====================================================================== ERROR: test_stdin_none (test.test_subprocess.ProcessTestCaseNoPoll) ---------------------------------------------------------------------- Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/test_subprocess.py", line 802, in tearDown ProcessTestCase.tearDown(self) File "/tmp/python-test/local/lib/python2.7/test/test_subprocess.py", line 46, in tearDown self.assertFalse(subprocess._active, "subprocess._active not empty") AssertionError: subprocess._active not empty ====================================================================== ERROR: test_stdin_pipe (test.test_subprocess.ProcessTestCaseNoPoll) ---------------------------------------------------------------------- Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/test_subprocess.py", line 802, in tearDown ProcessTestCase.tearDown(self) File "/tmp/python-test/local/lib/python2.7/test/test_subprocess.py", line 46, in tearDown self.assertFalse(subprocess._active, "subprocess._active not empty") AssertionError: subprocess._active not empty ====================================================================== ERROR: test_stdout_filedes (test.test_subprocess.ProcessTestCaseNoPoll) ---------------------------------------------------------------------- Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/test_subprocess.py", line 802, in tearDown ProcessTestCase.tearDown(self) File "/tmp/python-test/local/lib/python2.7/test/test_subprocess.py", line 46, in tearDown self.assertFalse(subprocess._active, "subprocess._active not empty") AssertionError: subprocess._active not empty ====================================================================== ERROR: test_stdout_filedes_of_stdout (test.test_subprocess.ProcessTestCaseNoPoll) ---------------------------------------------------------------------- Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/test_subprocess.py", line 802, in tearDown ProcessTestCase.tearDown(self) File "/tmp/python-test/local/lib/python2.7/test/test_subprocess.py", line 46, in tearDown self.assertFalse(subprocess._active, "subprocess._active not empty") AssertionError: subprocess._active not empty ====================================================================== ERROR: test_stdout_fileobj (test.test_subprocess.ProcessTestCaseNoPoll) ---------------------------------------------------------------------- Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/test_subprocess.py", line 802, in tearDown ProcessTestCase.tearDown(self) File "/tmp/python-test/local/lib/python2.7/test/test_subprocess.py", line 46, in tearDown self.assertFalse(subprocess._active, "subprocess._active not empty") AssertionError: subprocess._active not empty ====================================================================== ERROR: test_stdout_none (test.test_subprocess.ProcessTestCaseNoPoll) ---------------------------------------------------------------------- Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/test_subprocess.py", line 802, in tearDown ProcessTestCase.tearDown(self) File "/tmp/python-test/local/lib/python2.7/test/test_subprocess.py", line 46, in tearDown self.assertFalse(subprocess._active, "subprocess._active not empty") AssertionError: subprocess._active not empty ====================================================================== ERROR: test_stdout_pipe (test.test_subprocess.ProcessTestCaseNoPoll) ---------------------------------------------------------------------- Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/test_subprocess.py", line 802, in tearDown ProcessTestCase.tearDown(self) File "/tmp/python-test/local/lib/python2.7/test/test_subprocess.py", line 46, in tearDown self.assertFalse(subprocess._active, "subprocess._active not empty") AssertionError: subprocess._active not empty ====================================================================== ERROR: test_stdout_stderr_file (test.test_subprocess.ProcessTestCaseNoPoll) ---------------------------------------------------------------------- Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/test_subprocess.py", line 802, in tearDown ProcessTestCase.tearDown(self) File "/tmp/python-test/local/lib/python2.7/test/test_subprocess.py", line 46, in tearDown self.assertFalse(subprocess._active, "subprocess._active not empty") AssertionError: subprocess._active not empty ====================================================================== ERROR: test_stdout_stderr_pipe (test.test_subprocess.ProcessTestCaseNoPoll) ---------------------------------------------------------------------- Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/test_subprocess.py", line 802, in tearDown ProcessTestCase.tearDown(self) File "/tmp/python-test/local/lib/python2.7/test/test_subprocess.py", line 46, in tearDown self.assertFalse(subprocess._active, "subprocess._active not empty") AssertionError: subprocess._active not empty ====================================================================== ERROR: test_universal_newlines (test.test_subprocess.ProcessTestCaseNoPoll) ---------------------------------------------------------------------- Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/test_subprocess.py", line 802, in tearDown ProcessTestCase.tearDown(self) File "/tmp/python-test/local/lib/python2.7/test/test_subprocess.py", line 46, in tearDown self.assertFalse(subprocess._active, "subprocess._active not empty") AssertionError: subprocess._active not empty ====================================================================== ERROR: test_universal_newlines_communicate (test.test_subprocess.ProcessTestCaseNoPoll) ---------------------------------------------------------------------- Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/test_subprocess.py", line 802, in tearDown ProcessTestCase.tearDown(self) File "/tmp/python-test/local/lib/python2.7/test/test_subprocess.py", line 46, in tearDown self.assertFalse(subprocess._active, "subprocess._active not empty") AssertionError: subprocess._active not empty ====================================================================== ERROR: test_wait (test.test_subprocess.ProcessTestCaseNoPoll) ---------------------------------------------------------------------- Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/test_subprocess.py", line 802, in tearDown ProcessTestCase.tearDown(self) File "/tmp/python-test/local/lib/python2.7/test/test_subprocess.py", line 46, in tearDown self.assertFalse(subprocess._active, "subprocess._active not empty") AssertionError: subprocess._active not empty ====================================================================== ERROR: test_writes_before_communicate (test.test_subprocess.ProcessTestCaseNoPoll) ---------------------------------------------------------------------- Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/test_subprocess.py", line 802, in tearDown ProcessTestCase.tearDown(self) File "/tmp/python-test/local/lib/python2.7/test/test_subprocess.py", line 46, in tearDown self.assertFalse(subprocess._active, "subprocess._active not empty") AssertionError: subprocess._active not empty ---------------------------------------------------------------------- Ran 108 tests in 110.728s FAILED (errors=97, skipped=10) test test_subprocess failed -- multiple errors occurred test_sunaudiodev test_sunaudiodev skipped -- No module named sunaudiodev test_sundry test_symtable test_syntax test_sys [16651 refs] [16651 refs] [16651 refs] [16880 refs] [16674 refs] test_sysconfig [16651 refs] [16651 refs] test_tarfile test_tcl test_tcl skipped -- No module named _tkinter test_telnetlib test_tempfile [16651 refs] test_textwrap test_thread test_threaded_import test_threadedtempfile test_threading [19951 refs] [21220 refs] [21034 refs] [21034 refs] [21034 refs] [21034 refs] test_threading_local test_threadsignals test_time test_timeout test_timeout skipped -- Use of the `network' resource not enabled test_tk test_tk skipped -- No module named _tkinter test_tokenize test_trace test_traceback test_transformer test_ttk_guionly test_ttk_guionly skipped -- No module named _tkinter test_ttk_textonly test_ttk_textonly skipped -- No module named _tkinter test_tuple test_typechecks test_ucn test_unary test_undocumented_details test_unicode test_unicode_file test_unicode_file skipped -- No Unicode filesystem semantics on this platform. test_unicodedata test_univnewlines test_univnewlines2k test_unpack test_urllib test_urllib2 test_urllib2_localnet test_urllib2net test_urllib2net skipped -- Use of the `network' resource not enabled test_urllibnet test_urllibnet skipped -- Use of the `network' resource not enabled test_urlparse test_userdict test_userlist test_userstring test_uu test_uuid test_wait3 test_wait4 test_warnings [16682 refs] [16682 refs] [16675 refs] [16682 refs] [16682 refs] [16675 refs] test_wave test_weakref test_weakset test_whichdb test_winreg test_winreg skipped -- No module named _winreg test_winsound test_winsound skipped -- No module named winsound test_with test_wsgiref test_xdrlib test_xml_etree test_xml_etree_c test_xmllib test_xmlrpc test_xpickle test_xpickle -- skipping backwards compat tests. Use 'regrtest.py -u xpickle' to run them. test_xrange test_zipfile test_zipfile64 test_zipfile64 skipped -- test requires loads of disk-space bytes and a long time to run test_zipimport test_zipimport_support test_zlib 347 tests OK. 1 test failed: test_subprocess 36 tests skipped: test_aepack test_al test_applesingle test_bsddb185 test_bsddb3 test_cd test_cl test_curses test_epoll test_gdb test_gl test_imgfile test_ioctl test_kqueue test_linuxaudiodev test_macos test_macostools test_multiprocessing test_ossaudiodev test_py3kwarn test_scriptpackages test_smtpnet test_socketserver test_startfile test_sunaudiodev test_tcl test_timeout test_tk test_ttk_guionly test_ttk_textonly test_unicode_file test_urllib2net test_urllibnet test_winreg test_winsound test_zipfile64 7 skips unexpected on linux2: test_epoll test_gdb test_ioctl test_multiprocessing test_tk test_ttk_guionly test_ttk_textonly [960473 refs] From python-checkins at python.org Thu May 6 23:49:29 2010 From: python-checkins at python.org (collin.winter) Date: Thu, 6 May 2010 23:49:29 +0200 (CEST) Subject: [Python-checkins] r80884 - in python/branches/py3k-jit: Demo/pdist/FSProxy.py Doc/library/numbers.rst Doc/library/tarfile.rst Doc/library/urllib.request.rst Doc/whatsnew/3.2.rst Lib/asyncore.py Lib/ctypes/test/test_win32.py Lib/decimal.py Lib/distutils/command/install.py Lib/distutils/file_util.py Lib/distutils/util.py Lib/email/test/data/audiotest.au Lib/email/test/test_email.py Lib/gzip.py Lib/platform.py Lib/profile.py Lib/pydoc.py Lib/shutil.py Lib/tarfile.py Lib/test/audiotest.au Lib/test/regrtest.py Lib/test/support.py Lib/test/test_asyncore.py Lib/test/test_builtin.py Lib/test/test_decimal.py Lib/test/test_dictviews.py Lib/test/test_frozen.py Lib/test/test_ftplib.py Lib/test/test_gdb.py Lib/test/test_ossaudiodev.py Lib/test/test_reprlib.py Lib/test/test_select.py Lib/test/test_shutil.py Lib/test/test_smtplib.py Lib/test/test_socket.py Lib/test/test_ssl.py Lib/test/test_strptime.py Lib/test/test_tarfile.py Lib/test/test_tempfile.py Lib/test/test_urllib2.py Lib/test/test_uuid.py Lib/urllib/request.py Lib/uuid.py Mac/Makefile.in Misc/NEWS Modules/_ctypes/callproc.c Modules/_ctypes/libffi_msvc/LICENSE Modules/_ctypes/libffi_msvc/README Modules/_ctypes/libffi_msvc/README.ctypes Modules/_ctypes/libffi_msvc/ffi.c Modules/_ctypes/libffi_msvc/ffi.h Modules/_ctypes/libffi_msvc/ffi_common.h Modules/_ctypes/libffi_msvc/fficonfig.h Modules/_ctypes/libffi_msvc/ffitarget.h Modules/_ctypes/libffi_msvc/prep_cif.c Modules/_ctypes/libffi_msvc/types.c Modules/_ctypes/libffi_msvc/win32.c Modules/_ctypes/libffi_msvc/win64.asm Modules/_io/fileio.c Modules/_ssl.c Modules/posixmodule.c PCbuild/_ctypes.vcproj Tools/scripts/serve.py Tools/webchecker/wcgui.py Tools/webchecker/websucker.py configure configure.in setup.py Message-ID: <20100506214929.12BC7EC36@mail.python.org> Author: collin.winter Date: Thu May 6 23:49:27 2010 New Revision: 80884 Log: Merged revisions 80740,80750-80751,80755,80757,80760,80764,80767,80771-80773,80775,80778,80781,80783,80786,80790,80795,80798,80803,80805-80806,80824,80828,80833-80834,80836,80840,80842,80846,80851,80855,80859,80871,80876,80881,80883 via svnmerge from svn+ssh://pythondev at svn.python.org/python/branches/py3k ................ r80740 | benjamin.peterson | 2010-05-03 17:36:36 -0700 (Mon, 03 May 2010) | 10 lines Blocked revisions 80738 via svnmerge ........ r80738 | brett.cannon | 2010-05-03 19:30:17 -0500 (Mon, 03 May 2010) | 4 lines Remove a redundant string length check and variable assignment. Found with Clang's static analyzer. ........ ................ r80750 | alexandre.vassalotti | 2010-05-03 20:26:10 -0700 (Mon, 03 May 2010) | 8 lines Blocked revisions 80749 via svnmerge ........ r80749 | alexandre.vassalotti | 2010-05-03 20:21:51 -0700 (Mon, 03 May 2010) | 2 lines Issue #8404: Fix set operations on dictionary views. ........ ................ r80751 | alexandre.vassalotti | 2010-05-03 20:41:49 -0700 (Mon, 03 May 2010) | 4 lines Forward port unit tests for set operation and repr. Patch by Alexander Belopolsky. ................ r80755 | mark.dickinson | 2010-05-04 07:35:33 -0700 (Tue, 04 May 2010) | 17 lines Merged revisions 80753 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r80753 | mark.dickinson | 2010-05-04 15:25:50 +0100 (Tue, 04 May 2010) | 10 lines Issue #8567: Fix incorrect precedence of signals in Decimal module. When a Decimal operation raises multiple signals and more than one of those signals is trapped, the specification determines the order in which the signals should be handled. In many cases this order wasn't being followed, leading to the wrong Python exception being raised. This commit fixes those cases, and adds extra tests. The tests are only enabled when EXTENDEDERRORTESTS is True, since they involve rerunning each Decimal testcase several times. ........ ................ r80757 | r.david.murray | 2010-05-04 09:17:50 -0700 (Tue, 04 May 2010) | 12 lines Recorded merge of revisions 80458 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk Sean merged this in r84059. ........ r80458 | sean.reifschneider | 2010-04-25 02:31:23 -0400 (Sun, 25 Apr 2010) | 3 lines Fixing obscure syslog corner-case when sys.argv = None, syslog() would call openlog() for every logged message. ........ ................ r80760 | mark.dickinson | 2010-05-04 09:50:06 -0700 (Tue, 04 May 2010) | 18 lines Blocked revisions 80758-80759 via svnmerge ........ r80758 | mark.dickinson | 2010-05-04 17:18:25 +0100 (Tue, 04 May 2010) | 9 lines Issue #1533: fix inconsistency in range function argument processing: any non-float non-integer argument is now converted to an integer (if possible) using its __int__ method. Previously, only small arguments were treated this way; larger arguments (those whose __int__ was outside the range of a C long) would produce a TypeError. Patch by Alexander Belopolsky (with minor modifications). ........ r80759 | mark.dickinson | 2010-05-04 17:19:06 +0100 (Tue, 04 May 2010) | 1 line Fix trailing whitespace. ........ ................ r80764 | mark.dickinson | 2010-05-04 11:47:04 -0700 (Tue, 04 May 2010) | 10 lines Merged revisions 80762 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r80762 | mark.dickinson | 2010-05-04 19:45:27 +0100 (Tue, 04 May 2010) | 3 lines Fix test_gzip failure on OS X. The failure was a result of trying to fflush a file that wasn't open for writing. Patch by Antoine Pitrou. ........ ................ r80767 | thomas.heller | 2010-05-04 12:17:41 -0700 (Tue, 04 May 2010) | 19 lines Merged revisions 80761,80766 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r80761 | thomas.heller | 2010-05-04 20:44:42 +0200 (Di, 04 Mai 2010) | 8 lines On Windows, ctypes does no longer check the stack before and after calling a foreign function. This allows to use the unmodified libffi library. Remove most files from _ctypes/libffi_msvc, only two include files stay (updated from _ctypes/libffi/...). Other files are used in the cross-platform _ctypes/libffi directory. ........ r80766 | thomas.heller | 2010-05-04 21:08:18 +0200 (Di, 04 Mai 2010) | 2 lines Remove reference to unused source file. ........ ................ r80771 | michael.foord | 2010-05-04 15:29:10 -0700 (Tue, 04 May 2010) | 1 line Fix error handling removing files in test.support.unlink ................ r80772 | antoine.pitrou | 2010-05-04 16:31:41 -0700 (Tue, 04 May 2010) | 3 lines Add what's new entry for r80157 and r80071. ................ r80773 | senthil.kumaran | 2010-05-04 22:32:16 -0700 (Tue, 04 May 2010) | 3 lines Fix Issue8619 docfix related to urllib. ................ r80775 | senthil.kumaran | 2010-05-05 00:22:18 -0700 (Wed, 05 May 2010) | 3 lines Fix issue8619 - Doc fix - code example. ................ r80778 | victor.stinner | 2010-05-05 05:42:20 -0700 (Wed, 05 May 2010) | 9 lines Blocked revisions 80777 via svnmerge ........ r80777 | victor.stinner | 2010-05-05 14:40:49 +0200 (mer., 05 mai 2010) | 3 lines Issue #8313: traceback.format_exception_only() encodes unicode message to ASCII with backslashreplace error handler if str(value) failed ........ ................ r80781 | ronald.oussoren | 2010-05-05 06:20:31 -0700 (Wed, 05 May 2010) | 4 lines Small update to Mac/Makefile to ensure that we install python binaries that support all architectures in a universal build. ................ r80783 | marc-andre.lemburg | 2010-05-05 06:32:59 -0700 (Wed, 05 May 2010) | 9 lines Merged revisions 80782 via svnmerge from svn+pythonssh://pythondev at svn.python.org/python/trunk ........ r80782 | marc-andre.lemburg | 2010-05-05 15:30:01 +0200 (Wed, 05 May 2010) | 3 lines Update the NEWS entry for issue #8211. ........ ................ r80786 | ronald.oussoren | 2010-05-05 08:32:33 -0700 (Wed, 05 May 2010) | 16 lines Merged revisions 80784 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r80784 | ronald.oussoren | 2010-05-05 16:48:37 +0200 (Wed, 05 May 2010) | 9 lines The C function used by uuid.uuid4 is broken on OSX 10.6 in that after os.fork() the parent and child generate the same sequence of UUIDs. This patch falls back to the the Python implementation on OSX 10.6 or later. Fixes issue #8621. ........ ................ r80790 | antoine.pitrou | 2010-05-05 08:57:33 -0700 (Wed, 05 May 2010) | 9 lines Merged revisions 80789 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r80789 | antoine.pitrou | 2010-05-05 17:53:45 +0200 (mer., 05 mai 2010) | 3 lines Untabify Modules/_ssl.c ........ ................ r80795 | barry.warsaw | 2010-05-05 09:18:31 -0700 (Wed, 05 May 2010) | 5 lines Bug 7755: audiotest.au is arguably copyrighted material, but definitely makes Debian unhappy. The actual contents of the audio clip are unimportant, so replace it with something that we know is okay. Guido likes woodpeckers. ................ r80798 | antoine.pitrou | 2010-05-05 09:31:07 -0700 (Wed, 05 May 2010) | 9 lines Merged revisions 80796 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r80796 | antoine.pitrou | 2010-05-05 18:27:30 +0200 (mer., 05 mai 2010) | 3 lines Untabify Modules/_io/fileio.c ........ ................ r80803 | antoine.pitrou | 2010-05-05 11:30:22 -0700 (Wed, 05 May 2010) | 9 lines Merged revisions 80802 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r80802 | antoine.pitrou | 2010-05-05 20:29:02 +0200 (mer., 05 mai 2010) | 3 lines Issue #8600: fix test_gdb failures when gdb issues some spurious warnings. ........ ................ r80805 | ronald.oussoren | 2010-05-05 12:11:21 -0700 (Wed, 05 May 2010) | 4 lines Remove traces of MacOS9 support. Fix for issue #7908 ................ r80806 | ronald.oussoren | 2010-05-05 12:12:30 -0700 (Wed, 05 May 2010) | 14 lines Blocked revisions 80804 via svnmerge ........ r80804 | ronald.oussoren | 2010-05-05 21:09:31 +0200 (Wed, 05 May 2010) | 8 lines In a number of places code still revers to "sys.platform == 'mac'" and that is dead code because it refers to a platform that is no longer supported (and hasn't been supported for several releases). Fixes issue #7908 for the trunk. ........ ................ r80824 | victor.stinner | 2010-05-05 14:43:57 -0700 (Wed, 05 May 2010) | 3 lines Issue #8390: tarfile uses surrogateespace as the default error handler (instead of replace in read mode or strict in write mode) ................ r80828 | mark.dickinson | 2010-05-05 14:54:18 -0700 (Wed, 05 May 2010) | 9 lines Merged revisions 80826 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r80826 | mark.dickinson | 2010-05-05 22:52:39 +0100 (Wed, 05 May 2010) | 1 line Issue 8628: fix incorrect documentation for numbers.Complex.imag. ........ ................ r80833 | tarek.ziade | 2010-05-05 15:27:31 -0700 (Wed, 05 May 2010) | 9 lines Merged revisions 80830 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r80830 | tarek.ziade | 2010-05-06 00:15:31 +0200 (Thu, 06 May 2010) | 1 line Fixed #4265: shutil.copyfile() was leaking file descriptors when disk fills ........ ................ r80834 | mark.dickinson | 2010-05-05 15:31:36 -0700 (Wed, 05 May 2010) | 9 lines Merged revisions 80832 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r80832 | mark.dickinson | 2010-05-05 23:23:58 +0100 (Wed, 05 May 2010) | 2 lines Issue #8625: Turn off gcc optimization in debug builds. ........ ................ r80836 | mark.dickinson | 2010-05-05 15:39:58 -0700 (Wed, 05 May 2010) | 3 lines Issue #1533: Merge added trunk range tests to py3k. (The fix itself doesn't need to be merged.) Patch by Alexander Belopolsky. ................ r80840 | tarek.ziade | 2010-05-05 15:43:04 -0700 (Wed, 05 May 2010) | 9 lines Merged revisions 80837 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r80837 | tarek.ziade | 2010-05-06 00:41:25 +0200 (Thu, 06 May 2010) | 1 line removed non needed lines ........ ................ r80842 | mark.dickinson | 2010-05-05 15:44:34 -0700 (Wed, 05 May 2010) | 9 lines Blocked revisions 80839 via svnmerge ........ r80839 | mark.dickinson | 2010-05-05 23:42:51 +0100 (Wed, 05 May 2010) | 3 lines Issue #1533: test_range in test_builtin: fix test comment and add test for rejection of small floats. Thanks Alexander Belopolsky. ........ ................ r80846 | victor.stinner | 2010-05-05 17:08:46 -0700 (Wed, 05 May 2010) | 20 lines Recorded merge of revisions 80844-80845 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r80844 | victor.stinner | 2010-05-06 01:33:33 +0200 (jeu., 06 mai 2010) | 5 lines Untabify Modules/posixmodule.c Run Antoine Pitrou "untabify" script + manual editions (OS/2 and some continuation lines). ........ r80845 | victor.stinner | 2010-05-06 02:03:44 +0200 (jeu., 06 mai 2010) | 4 lines Untabify Modules/posixmodule.c (2) Fix some more functions by hand ........ I rewrote the patch for py3k from scratch using untabify + manual editions ................ r80851 | r.david.murray | 2010-05-05 18:09:27 -0700 (Wed, 05 May 2010) | 11 lines Merged revisions 80849 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r80849 | r.david.murray | 2010-05-05 20:59:04 -0400 (Wed, 05 May 2010) | 4 lines Have the serve.py script announce the directory it is serving and which port it is serving it on (I can never remember the default port number it uses...) ........ ................ r80855 | r.david.murray | 2010-05-05 18:41:14 -0700 (Wed, 05 May 2010) | 24 lines Merged revisions 80800 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk It turns out that email5 (py3k), because it is using unicode for the payload, doesn't do the encoding to the output character set until later in the process. Specifically, charset.body_encode no longer does the input-to-output charset conversion. So the if test in the exception clause in encoders.encode_7or8bit really is needed in email5. So, this merge only merges the test, not the removal of the 'if'. ........ r80800 | r.david.murray | 2010-05-05 13:31:03 -0400 (Wed, 05 May 2010) | 9 lines Issue #7472: remove unused code from email.encoders.encode_7or8bit. Yukihiro Nakadaira noticed a typo in encode_7or8bit that was trying to special case iso-2022 codecs. It turns out that the code in question is never used, because whereas it was designed to trigger if the payload encoding was eight bit but its output encoding was 7 bit, in practice the payload is always converted to the 7bit encoding before encode_7or8bit is called. Patch by Shawat Anand. ........ ................ r80859 | brian.curtin | 2010-05-05 20:05:50 -0700 (Wed, 05 May 2010) | 12 lines Merged revisions 80857 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r80857 | brian.curtin | 2010-05-05 21:54:44 -0500 (Wed, 05 May 2010) | 5 lines Fix #7863. Properly identify Windows 7 and Server 2008 R2. Removed various unused code and added a way to correctly determine server vs. workstation via the registry. ........ ................ r80871 | antoine.pitrou | 2010-05-06 07:15:10 -0700 (Thu, 06 May 2010) | 9 lines Merged revisions 80869 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r80869 | antoine.pitrou | 2010-05-06 16:11:23 +0200 (jeu., 06 mai 2010) | 3 lines `self` doesn't exist here ........ ................ r80876 | giampaolo.rodola | 2010-05-06 11:06:30 -0700 (Thu, 06 May 2010) | 9 lines Merged revisions 80875 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r80875 | giampaolo.rodola | 2010-05-06 19:57:06 +0200 (gio, 06 mag 2010) | 1 line Fix asyncore issues 8573 and 8483: _strerror might throw ValueError; asyncore.__getattr__ cheap inheritance caused confusing error messages when accessing undefined class attributes; added an alias for __str__ which now is used as a fallback for __repr__ ........ ................ r80881 | giampaolo.rodola | 2010-05-06 13:02:37 -0700 (Thu, 06 May 2010) | 9 lines Merged revisions 80880 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r80880 | giampaolo.rodola | 2010-05-06 21:56:34 +0200 (gio, 06 mag 2010) | 1 line provides a clearer warning message when cheap inheritance with the underlying socket object is used ........ ................ r80883 | giampaolo.rodola | 2010-05-06 13:21:57 -0700 (Thu, 06 May 2010) | 9 lines Merged revisions 80882 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r80882 | giampaolo.rodola | 2010-05-06 22:19:32 +0200 (gio, 06 mag 2010) | 1 line adds handle_error(self):raise to test modules using asyncore to provide a clearer error message in case something goes wrong ........ ................ Removed: python/branches/py3k-jit/Modules/_ctypes/libffi_msvc/LICENSE python/branches/py3k-jit/Modules/_ctypes/libffi_msvc/README python/branches/py3k-jit/Modules/_ctypes/libffi_msvc/README.ctypes python/branches/py3k-jit/Modules/_ctypes/libffi_msvc/ffi.c python/branches/py3k-jit/Modules/_ctypes/libffi_msvc/ffi_common.h python/branches/py3k-jit/Modules/_ctypes/libffi_msvc/ffitarget.h python/branches/py3k-jit/Modules/_ctypes/libffi_msvc/prep_cif.c python/branches/py3k-jit/Modules/_ctypes/libffi_msvc/types.c python/branches/py3k-jit/Modules/_ctypes/libffi_msvc/win32.c python/branches/py3k-jit/Modules/_ctypes/libffi_msvc/win64.asm Modified: python/branches/py3k-jit/ (props changed) python/branches/py3k-jit/Demo/pdist/FSProxy.py python/branches/py3k-jit/Doc/library/numbers.rst python/branches/py3k-jit/Doc/library/tarfile.rst python/branches/py3k-jit/Doc/library/urllib.request.rst python/branches/py3k-jit/Doc/whatsnew/3.2.rst python/branches/py3k-jit/Lib/asyncore.py python/branches/py3k-jit/Lib/ctypes/test/test_win32.py python/branches/py3k-jit/Lib/decimal.py python/branches/py3k-jit/Lib/distutils/command/install.py python/branches/py3k-jit/Lib/distutils/file_util.py python/branches/py3k-jit/Lib/distutils/util.py python/branches/py3k-jit/Lib/email/test/data/audiotest.au python/branches/py3k-jit/Lib/email/test/test_email.py python/branches/py3k-jit/Lib/gzip.py python/branches/py3k-jit/Lib/platform.py python/branches/py3k-jit/Lib/profile.py python/branches/py3k-jit/Lib/pydoc.py python/branches/py3k-jit/Lib/shutil.py python/branches/py3k-jit/Lib/tarfile.py python/branches/py3k-jit/Lib/test/audiotest.au python/branches/py3k-jit/Lib/test/regrtest.py python/branches/py3k-jit/Lib/test/support.py python/branches/py3k-jit/Lib/test/test_asyncore.py python/branches/py3k-jit/Lib/test/test_builtin.py python/branches/py3k-jit/Lib/test/test_decimal.py python/branches/py3k-jit/Lib/test/test_dictviews.py python/branches/py3k-jit/Lib/test/test_frozen.py python/branches/py3k-jit/Lib/test/test_ftplib.py python/branches/py3k-jit/Lib/test/test_gdb.py python/branches/py3k-jit/Lib/test/test_ossaudiodev.py python/branches/py3k-jit/Lib/test/test_reprlib.py python/branches/py3k-jit/Lib/test/test_select.py python/branches/py3k-jit/Lib/test/test_shutil.py python/branches/py3k-jit/Lib/test/test_smtplib.py python/branches/py3k-jit/Lib/test/test_socket.py python/branches/py3k-jit/Lib/test/test_ssl.py python/branches/py3k-jit/Lib/test/test_strptime.py python/branches/py3k-jit/Lib/test/test_tarfile.py python/branches/py3k-jit/Lib/test/test_tempfile.py python/branches/py3k-jit/Lib/test/test_urllib2.py python/branches/py3k-jit/Lib/test/test_uuid.py python/branches/py3k-jit/Lib/urllib/request.py python/branches/py3k-jit/Lib/uuid.py python/branches/py3k-jit/Mac/Makefile.in python/branches/py3k-jit/Misc/NEWS python/branches/py3k-jit/Modules/_ctypes/callproc.c python/branches/py3k-jit/Modules/_ctypes/libffi_msvc/ffi.h python/branches/py3k-jit/Modules/_ctypes/libffi_msvc/fficonfig.h python/branches/py3k-jit/Modules/_io/fileio.c python/branches/py3k-jit/Modules/_ssl.c python/branches/py3k-jit/Modules/posixmodule.c python/branches/py3k-jit/PCbuild/_ctypes.vcproj python/branches/py3k-jit/Tools/scripts/serve.py python/branches/py3k-jit/Tools/webchecker/wcgui.py python/branches/py3k-jit/Tools/webchecker/websucker.py python/branches/py3k-jit/configure python/branches/py3k-jit/configure.in python/branches/py3k-jit/setup.py Modified: python/branches/py3k-jit/Demo/pdist/FSProxy.py ============================================================================== --- python/branches/py3k-jit/Demo/pdist/FSProxy.py (original) +++ python/branches/py3k-jit/Demo/pdist/FSProxy.py Thu May 6 23:49:27 2010 @@ -23,12 +23,7 @@ import time import fnmatch -if os.name == 'mac': - import macfs - maxnamelen = 31 -else: - macfs = None - maxnamelen = 255 +maxnamelen = 255 skipnames = (os.curdir, os.pardir) @@ -63,16 +58,10 @@ return ignore def _hidden(self, name): - if os.name == 'mac': - return name[0] == '(' and name[-1] == ')' - else: - return name[0] == '.' + return name[0] == '.' def _hide(self, name): - if os.name == 'mac': - return '(%s)' % name - else: - return '.%s' % name + return '.%s' % name def visible(self, name): if len(name) > maxnamelen: return 0 @@ -81,18 +70,8 @@ if self._hidden(name): return 0 head, tail = os.path.split(name) if head or not tail: return 0 - if macfs: - if os.path.exists(name) and not os.path.isdir(name): - try: - fs = macfs.FSSpec(name) - c, t = fs.GetCreatorType() - if t != 'TEXT': return 0 - except macfs.error as msg: - print("***", name, msg) - return 0 - else: - if os.path.islink(name): return 0 - if '\0' in open(name, 'rb').read(512): return 0 + if os.path.islink(name): return 0 + if '\0' in open(name, 'rb').read(512): return 0 for ign in self._ignore: if fnmatch.fnmatch(name, ign): return 0 return 1 Modified: python/branches/py3k-jit/Doc/library/numbers.rst ============================================================================== --- python/branches/py3k-jit/Doc/library/numbers.rst (original) +++ python/branches/py3k-jit/Doc/library/numbers.rst Thu May 6 23:49:27 2010 @@ -29,11 +29,11 @@ .. attribute:: real - Abstract. Retrieves the :class:`Real` component of this number. + Abstract. Retrieves the real component of this number. .. attribute:: imag - Abstract. Retrieves the :class:`Real` component of this number. + Abstract. Retrieves the imaginary component of this number. .. method:: conjugate() Modified: python/branches/py3k-jit/Doc/library/tarfile.rst ============================================================================== --- python/branches/py3k-jit/Doc/library/tarfile.rst (original) +++ python/branches/py3k-jit/Doc/library/tarfile.rst Thu May 6 23:49:27 2010 @@ -218,7 +218,7 @@ .. versionadded:: 3.2 Added support for the context manager protocol. -.. class:: TarFile(name=None, mode='r', fileobj=None, format=DEFAULT_FORMAT, tarinfo=TarInfo, dereference=False, ignore_zeros=False, encoding=ENCODING, errors=None, pax_headers=None, debug=0, errorlevel=0) +.. class:: TarFile(name=None, mode='r', fileobj=None, format=DEFAULT_FORMAT, tarinfo=TarInfo, dereference=False, ignore_zeros=False, encoding=ENCODING, errors='surrogateescape', pax_headers=None, debug=0, errorlevel=0) All following arguments are optional and can be accessed as instance attributes as well. @@ -267,6 +267,9 @@ to be handled. The default settings will work for most users. See section :ref:`tar-unicode` for in-depth information. + .. versionchanged:: 3.2 + Use ``'surrogateescape'`` as the default for the *errors* argument. + The *pax_headers* argument is an optional dictionary of strings which will be added as a pax global header if *format* is :const:`PAX_FORMAT`. @@ -449,11 +452,14 @@ a :class:`TarInfo` object. -.. method:: TarInfo.tobuf(format=DEFAULT_FORMAT, encoding=ENCODING, errors='strict') +.. method:: TarInfo.tobuf(format=DEFAULT_FORMAT, encoding=ENCODING, errors='surrogateescape') Create a string buffer from a :class:`TarInfo` object. For information on the arguments see the constructor of the :class:`TarFile` class. + .. versionchanged:: 3.2 + Use ``'surrogateescape'`` as the default for the *errors* argument. + A ``TarInfo`` object has the following public data attributes: @@ -701,11 +707,10 @@ appropriately, this conversion may fail. The *errors* argument defines how characters are treated that cannot be -converted. Possible values are listed in section :ref:`codec-base-classes`. In -read mode the default scheme is ``'replace'``. This avoids unexpected -:exc:`UnicodeError` exceptions and guarantees that an archive can always be -read. In write mode the default value for *errors* is ``'strict'``. This -ensures that name information is not altered unnoticed. +converted. Possible values are listed in section :ref:`codec-base-classes`. +The default scheme is ``'surrogateescape'`` which Python also uses for its +file system calls, see :ref:`os-filenames`. In case of writing :const:`PAX_FORMAT` archives, *encoding* is ignored because -non-ASCII metadata is stored using *UTF-8*. +non-ASCII metadata is stored using *UTF-8*. Storing surrogate characters is not +possible and will raise a :exc:`UnicodeEncodeError`. Modified: python/branches/py3k-jit/Doc/library/urllib.request.rst ============================================================================== --- python/branches/py3k-jit/Doc/library/urllib.request.rst (original) +++ python/branches/py3k-jit/Doc/library/urllib.request.rst Thu May 6 23:49:27 2010 @@ -133,17 +133,17 @@ of the :class:`FancyURLopener` class and use it to perform their requested actions. To override this functionality, programmers can create a subclass of :class:`URLopener` or :class:`FancyURLopener`, then assign an instance of that - class to the ``urllib._urlopener`` variable before calling the desired function. - For example, applications may want to specify a different - :mailheader:`User-Agent` header than :class:`URLopener` defines. This can be - accomplished with the following code:: + class to the ``urllib.request._urlopener`` variable before calling the + desired function. For example, applications may want to specify a different + :mailheader:`User-Agent` header than :class:`URLopener` defines. + This can be accomplished with the following code:: import urllib.request class AppURLopener(urllib.request.FancyURLopener): version = "App/1.7" - urllib._urlopener = AppURLopener() + urllib.request._urlopener = AppURLopener() .. function:: urlcleanup() Modified: python/branches/py3k-jit/Doc/whatsnew/3.2.rst ============================================================================== --- python/branches/py3k-jit/Doc/whatsnew/3.2.rst (original) +++ python/branches/py3k-jit/Doc/whatsnew/3.2.rst Thu May 6 23:49:27 2010 @@ -123,6 +123,11 @@ (Contributed by Antoine Pitrou; :issue:`3001`.) +* Regular and recursive locks now accept an optional *timeout* argument + to their ``acquire`` method. (Contributed by Antoine Pitrou; :issue:`7316`) + Similarly, :meth:`threading.Semaphore.acquire` also gains a *timeout* + argument. (Contributed by Torsten Landschoff; :issue:`850728`.) + Optimizations ============= Modified: python/branches/py3k-jit/Lib/asyncore.py ============================================================================== --- python/branches/py3k-jit/Lib/asyncore.py (original) +++ python/branches/py3k-jit/Lib/asyncore.py Thu May 6 23:49:27 2010 @@ -50,6 +50,8 @@ import socket import sys import time +import warnings + import os from errno import EALREADY, EINPROGRESS, EWOULDBLOCK, ECONNRESET, \ ENOTCONN, ESHUTDOWN, EINTR, EISCONN, EBADF, ECONNABORTED, errorcode @@ -60,10 +62,12 @@ socket_map = {} def _strerror(err): - res = os.strerror(err) - if res == 'Unknown error': - res = errorcode[err] - return res + try: + return strerror(err) + except (ValueError, OverflowError): + if err in errorcode: + return errorcode[err] + return "Unknown error %s" %err class ExitNow(Exception): pass @@ -264,6 +268,8 @@ status.append(repr(self.addr)) return '<%s at %#x>' % (' '.join(status), id(self)) + __str__ = __repr__ + def add_channel(self, map=None): #self.log_info('adding channel %s' % self) if map is None: @@ -395,7 +401,16 @@ # cheap inheritance, used to pass all other attribute # references to the underlying socket object. def __getattr__(self, attr): - return getattr(self.socket, attr) + try: + retattr = getattr(self.socket, attr) + except AttributeError: + raise AttributeError("%s instance has no attribute '%s'" + %(self.__class__.__name__, attr)) + else: + msg = "%(me)s.%(attr)s is deprecated; use %(me)s.socket.%(attr)s " \ + "instead" % {'me' : self.__class__.__name__, 'attr' : attr} + warnings.warn(msg, DeprecationWarning, stacklevel=2) + return retattr # log and log_info may be overridden to provide more sophisticated # logging and warning methods. In general, log is for 'hit' logging Modified: python/branches/py3k-jit/Lib/ctypes/test/test_win32.py ============================================================================== --- python/branches/py3k-jit/Lib/ctypes/test/test_win32.py (original) +++ python/branches/py3k-jit/Lib/ctypes/test/test_win32.py Thu May 6 23:49:27 2010 @@ -6,32 +6,6 @@ import _ctypes_test -if sys.platform == "win32" and sizeof(c_void_p) == sizeof(c_int): - # Only windows 32-bit has different calling conventions. - - class WindowsTestCase(unittest.TestCase): - def test_callconv_1(self): - # Testing stdcall function - - IsWindow = windll.user32.IsWindow - # ValueError: Procedure probably called with not enough arguments (4 bytes missing) - self.assertRaises(ValueError, IsWindow) - - # This one should succeeed... - self.assertEqual(0, IsWindow(0)) - - # ValueError: Procedure probably called with too many arguments (8 bytes in excess) - self.assertRaises(ValueError, IsWindow, 0, 0, 0) - - def test_callconv_2(self): - # Calling stdcall function as cdecl - - IsWindow = cdll.user32.IsWindow - - # ValueError: Procedure called with not enough arguments (4 bytes missing) - # or wrong calling convention - self.assertRaises(ValueError, IsWindow, None) - if sys.platform == "win32": class FunctionCallTestCase(unittest.TestCase): Modified: python/branches/py3k-jit/Lib/decimal.py ============================================================================== --- python/branches/py3k-jit/Lib/decimal.py (original) +++ python/branches/py3k-jit/Lib/decimal.py Thu May 6 23:49:27 2010 @@ -1655,47 +1655,53 @@ exp_min = len(self._int) + self._exp - context.prec if exp_min > Etop: # overflow: exp_min > Etop iff self.adjusted() > Emax + ans = context._raise_error(Overflow, 'above Emax', self._sign) context._raise_error(Inexact) context._raise_error(Rounded) - return context._raise_error(Overflow, 'above Emax', self._sign) + return ans + self_is_subnormal = exp_min < Etiny if self_is_subnormal: - context._raise_error(Subnormal) exp_min = Etiny # round if self has too many digits if self._exp < exp_min: - context._raise_error(Rounded) digits = len(self._int) + self._exp - exp_min if digits < 0: self = _dec_from_triple(self._sign, '1', exp_min-1) digits = 0 - this_function = getattr(self, self._pick_rounding_function[context.rounding]) - changed = this_function(digits) + rounding_method = self._pick_rounding_function[context.rounding] + changed = getattr(self, rounding_method)(digits) coeff = self._int[:digits] or '0' - if changed == 1: + if changed > 0: coeff = str(int(coeff)+1) - ans = _dec_from_triple(self._sign, coeff, exp_min) + if len(coeff) > context.prec: + coeff = coeff[:-1] + exp_min += 1 + + # check whether the rounding pushed the exponent out of range + if exp_min > Etop: + ans = context._raise_error(Overflow, 'above Emax', self._sign) + else: + ans = _dec_from_triple(self._sign, coeff, exp_min) + # raise the appropriate signals, taking care to respect + # the precedence described in the specification + if changed and self_is_subnormal: + context._raise_error(Underflow) + if self_is_subnormal: + context._raise_error(Subnormal) if changed: context._raise_error(Inexact) - if self_is_subnormal: - context._raise_error(Underflow) - if not ans: - # raise Clamped on underflow to 0 - context._raise_error(Clamped) - elif len(ans._int) == context.prec+1: - # we get here only if rescaling rounds the - # cofficient up to exactly 10**context.prec - if ans._exp < Etop: - ans = _dec_from_triple(ans._sign, - ans._int[:-1], ans._exp+1) - else: - # Inexact and Rounded have already been raised - ans = context._raise_error(Overflow, 'above Emax', - self._sign) + context._raise_error(Rounded) + if not ans: + # raise Clamped on underflow to 0 + context._raise_error(Clamped) return ans + if self_is_subnormal: + context._raise_error(Subnormal) + # fold down if _clamp == 1 and self has too few digits if context._clamp == 1 and self._exp > Etop: context._raise_error(Clamped) @@ -2322,6 +2328,7 @@ # from here on, the result always goes through the call # to _fix at the end of this function. ans = None + exact = False # crude test to catch cases of extreme overflow/underflow. If # log10(self)*other >= 10**bound and bound >= len(str(Emax)) @@ -2346,6 +2353,7 @@ ans = self._power_exact(other, context.prec + 1) if ans is not None and result_sign == 1: ans = _dec_from_triple(1, ans._int, ans._exp) + exact = True # usual case: inexact result, x**y computed directly as exp(y*log(x)) if ans is None: @@ -2368,24 +2376,55 @@ ans = _dec_from_triple(result_sign, str(coeff), exp) - # the specification says that for non-integer other we need to - # raise Inexact, even when the result is actually exact. In - # the same way, we need to raise Underflow here if the result - # is subnormal. (The call to _fix will take care of raising - # Rounded and Subnormal, as usual.) - if not other._isinteger(): - context._raise_error(Inexact) - # pad with zeros up to length context.prec+1 if necessary + # unlike exp, ln and log10, the power function respects the + # rounding mode; no need to switch to ROUND_HALF_EVEN here + + # There's a difficulty here when 'other' is not an integer and + # the result is exact. In this case, the specification + # requires that the Inexact flag be raised (in spite of + # exactness), but since the result is exact _fix won't do this + # for us. (Correspondingly, the Underflow signal should also + # be raised for subnormal results.) We can't directly raise + # these signals either before or after calling _fix, since + # that would violate the precedence for signals. So we wrap + # the ._fix call in a temporary context, and reraise + # afterwards. + if exact and not other._isinteger(): + # pad with zeros up to length context.prec+1 if necessary; this + # ensures that the Rounded signal will be raised. if len(ans._int) <= context.prec: - expdiff = context.prec+1 - len(ans._int) + expdiff = context.prec + 1 - len(ans._int) ans = _dec_from_triple(ans._sign, ans._int+'0'*expdiff, ans._exp-expdiff) - if ans.adjusted() < context.Emin: - context._raise_error(Underflow) - # unlike exp, ln and log10, the power function respects the - # rounding mode; no need to use ROUND_HALF_EVEN here - ans = ans._fix(context) + # create a copy of the current context, with cleared flags/traps + newcontext = context.copy() + newcontext.clear_flags() + for exception in _signals: + newcontext.traps[exception] = 0 + + # round in the new context + ans = ans._fix(newcontext) + + # raise Inexact, and if necessary, Underflow + newcontext._raise_error(Inexact) + if newcontext.flags[Subnormal]: + newcontext._raise_error(Underflow) + + # propagate signals to the original context; _fix could + # have raised any of Overflow, Underflow, Subnormal, + # Inexact, Rounded, Clamped. Overflow needs the correct + # arguments. Note that the order of the exceptions is + # important here. + if newcontext.flags[Overflow]: + context._raise_error(Overflow, 'above Emax', ans._sign) + for exception in Underflow, Subnormal, Inexact, Rounded, Clamped: + if newcontext.flags[exception]: + context._raise_error(exception) + + else: + ans = ans._fix(context) + return ans def __rpow__(self, other, context=None): @@ -2479,14 +2518,15 @@ 'quantize result has too many digits for current context') # raise appropriate flags + if ans and ans.adjusted() < context.Emin: + context._raise_error(Subnormal) if ans._exp > self._exp: - context._raise_error(Rounded) if ans != self: context._raise_error(Inexact) - if ans and ans.adjusted() < context.Emin: - context._raise_error(Subnormal) + context._raise_error(Rounded) - # call to fix takes care of any necessary folddown + # call to fix takes care of any necessary folddown, and + # signals Clamped if necessary ans = ans._fix(context) return ans @@ -2585,10 +2625,10 @@ context = getcontext() if rounding is None: rounding = context.rounding - context._raise_error(Rounded) ans = self._rescale(0, rounding) if ans != self: context._raise_error(Inexact) + context._raise_error(Rounded) return ans def to_integral_value(self, rounding=None, context=None): @@ -3469,13 +3509,13 @@ context._raise_error(Overflow, 'Infinite result from next_toward', ans._sign) - context._raise_error(Rounded) context._raise_error(Inexact) + context._raise_error(Rounded) elif ans.adjusted() < context.Emin: context._raise_error(Underflow) context._raise_error(Subnormal) - context._raise_error(Rounded) context._raise_error(Inexact) + context._raise_error(Rounded) # if precision == 1 then we don't raise Clamped for a # result 0E-Etiny. if not ans: Modified: python/branches/py3k-jit/Lib/distutils/command/install.py ============================================================================== --- python/branches/py3k-jit/Lib/distutils/command/install.py (original) +++ python/branches/py3k-jit/Lib/distutils/command/install.py Thu May 6 23:49:27 2010 @@ -65,20 +65,6 @@ 'scripts': '$userbase/Scripts', 'data' : '$userbase', }, - 'mac': { - 'purelib': '$base/Lib/site-packages', - 'platlib': '$base/Lib/site-packages', - 'headers': '$base/Include/$dist_name', - 'scripts': '$base/Scripts', - 'data' : '$base', - }, - 'mac_user': { - 'purelib': '$usersite', - 'platlib': '$usersite', - 'headers': '$userbase/$py_version_short/include/$dist_name', - 'scripts': '$userbase/bin', - 'data' : '$userbase', - }, 'os2': { 'purelib': '$base/Lib/site-packages', 'platlib': '$base/Lib/site-packages', Modified: python/branches/py3k-jit/Lib/distutils/file_util.py ============================================================================== --- python/branches/py3k-jit/Lib/distutils/file_util.py (original) +++ python/branches/py3k-jit/Lib/distutils/file_util.py Thu May 6 23:49:27 2010 @@ -132,15 +132,6 @@ if dry_run: return (dst, 1) - # On Mac OS, use the native file copy routine - if os.name == 'mac': - import macostools - try: - macostools.copy(src, dst, 0, preserve_times) - except os.error as exc: - raise DistutilsFileError( - "could not copy '%s' to '%s': %s" % (src, dst, exc.args[-1])) - # If linking (hard or symbolic), use the appropriate system call # (Unix only, of course, but that's the caller's responsibility) elif link == 'hard': Modified: python/branches/py3k-jit/Lib/distutils/util.py ============================================================================== --- python/branches/py3k-jit/Lib/distutils/util.py (original) +++ python/branches/py3k-jit/Lib/distutils/util.py Thu May 6 23:49:27 2010 @@ -91,15 +91,6 @@ path = path[1:] return os.path.join(new_root, path) - elif os.name == 'mac': - if not os.path.isabs(pathname): - return os.path.join(new_root, pathname) - else: - # Chop off volume name from start of path - elements = pathname.split(":", 1) - pathname = ":" + elements[1] - return os.path.join(new_root, pathname) - else: raise DistutilsPlatformError("nothing known about " "platform '%s'" % os.name) Modified: python/branches/py3k-jit/Lib/email/test/data/audiotest.au ============================================================================== Binary files. No diff available. Modified: python/branches/py3k-jit/Lib/email/test/test_email.py ============================================================================== --- python/branches/py3k-jit/Lib/email/test/test_email.py (original) +++ python/branches/py3k-jit/Lib/email/test/test_email.py Thu May 6 23:49:27 2010 @@ -530,6 +530,13 @@ msg = MIMEText('hello \xf8 world', _charset='iso-8859-1') eq(msg['content-transfer-encoding'], 'quoted-printable') + def test_encode7or8bit(self): + # Make sure a charset whose input character set is 8bit but + # whose output character set is 7bit gets a transfer-encoding + # of 7bit. + eq = self.assertEqual + msg = MIMEText('\xca\xb8', _charset='euc-jp') + eq(msg['content-transfer-encoding'], '7bit') # Test long header wrapping Modified: python/branches/py3k-jit/Lib/gzip.py ============================================================================== --- python/branches/py3k-jit/Lib/gzip.py (original) +++ python/branches/py3k-jit/Lib/gzip.py Thu May 6 23:49:27 2010 @@ -380,7 +380,7 @@ if self.mode == WRITE: # Ensure the compressor's buffer is flushed self.fileobj.write(self.compress.flush(zlib_mode)) - self.fileobj.flush() + self.fileobj.flush() def fileno(self): """Invoke the underlying file object's fileno() method. Modified: python/branches/py3k-jit/Lib/platform.py ============================================================================== --- python/branches/py3k-jit/Lib/platform.py (original) +++ python/branches/py3k-jit/Lib/platform.py Thu May 6 23:49:27 2010 @@ -601,12 +601,19 @@ VER_PLATFORM_WIN32_WINDOWS = 1 VER_PLATFORM_WIN32_NT = 2 VER_NT_WORKSTATION = 1 + VER_NT_SERVER = 3 + REG_SZ = 1 # Find out the registry key and some general version infos - maj,min,buildno,plat,csd = GetVersionEx() + winver = GetVersionEx() + maj,min,buildno,plat,csd = winver version = '%i.%i.%i' % (maj,min,buildno & 0xFFFF) - if csd[:13] == 'Service Pack ': - csd = 'SP' + csd[13:] + if hasattr(winver, "service_pack"): + if winver.service_pack != "": + csd = 'SP%s' % winver.service_pack_major + else: + if csd[:13] == 'Service Pack ': + csd = 'SP' + csd[13:] if plat == VER_PLATFORM_WIN32_WINDOWS: regkey = 'SOFTWARE\\Microsoft\\Windows\\CurrentVersion' @@ -637,23 +644,33 @@ else: release = 'post2003' elif maj == 6: - if min == 0: - # Per http://msdn2.microsoft.com/en-us/library/ms724429.aspx + if hasattr(winver, "product_type"): + product_type = winver.product_type + else: + product_type = VER_NT_WORKSTATION + # Without an OSVERSIONINFOEX capable sys.getwindowsversion(), + # or help from the registry, we cannot properly identify + # non-workstation versions. try: - productType = GetVersionEx(1)[8] - except TypeError: - # sys.getwindowsversion() doesn't take any arguments, so - # we cannot detect 2008 Server that way. - # XXX Add some other means of detecting 2008 Server ?! + key = RegOpenKeyEx(HKEY_LOCAL_MACHINE, regkey) + name, type = RegQueryValueEx(key, "ProductName") + # Discard any type that isn't REG_SZ + if type == REG_SZ and name.find("Server") != -1: + product_type = VER_NT_SERVER + except WindowsError: + # Use default of VER_NT_WORKSTATION + pass + + if min == 0: + if product_type == VER_NT_WORKSTATION: release = 'Vista' else: - if productType == VER_NT_WORKSTATION: - release = 'Vista' - else: - release = '2008Server' - #elif min == 1: - # # Windows 7 release candidate uses version 6.1.7100 - # release = '7RC' + release = '2008Server' + elif min == 1: + if product_type == VER_NT_WORKSTATION: + release = '7' + else: + release = '2008ServerR2' else: release = 'post2008Server' @@ -1147,10 +1164,6 @@ if not version: version = vendor - elif os.name == 'mac': - release,(version,stage,nonrel),machine = mac_ver() - system = 'MacOS' - # System specific extensions if system == 'OpenVMS': # OpenVMS seems to have release and version mixed up Modified: python/branches/py3k-jit/Lib/profile.py ============================================================================== --- python/branches/py3k-jit/Lib/profile.py (original) +++ python/branches/py3k-jit/Lib/profile.py Thu May 6 23:49:27 2010 @@ -92,11 +92,6 @@ else: return prof.print_stats() -if os.name == "mac": - import MacOS - def _get_time_mac(timer=MacOS.GetTicks): - return timer() / 60.0 - if hasattr(os, "times"): def _get_time_times(timer=os.times): t = timer() @@ -173,10 +168,6 @@ self.timer = resgetrusage self.dispatcher = self.trace_dispatch self.get_time = _get_time_resource - elif os.name == 'mac': - self.timer = MacOS.GetTicks - self.dispatcher = self.trace_dispatch_mac - self.get_time = _get_time_mac elif hasattr(time, 'clock'): self.timer = self.get_time = time.clock self.dispatcher = self.trace_dispatch_i Modified: python/branches/py3k-jit/Lib/pydoc.py ============================================================================== --- python/branches/py3k-jit/Lib/pydoc.py (original) +++ python/branches/py3k-jit/Lib/pydoc.py Thu May 6 23:49:27 2010 @@ -2024,7 +2024,7 @@ class DocServer(http.server.HTTPServer): def __init__(self, port, callback): - host = (sys.platform == 'mac') and '127.0.0.1' or 'localhost' + host = 'localhost' self.address = ('', port) self.url = 'http://%s:%d/' % (host, port) self.callback = callback @@ -2141,10 +2141,6 @@ except ImportError: # pre-webbrowser.py compatibility if sys.platform == 'win32': os.system('start "%s"' % url) - elif sys.platform == 'mac': - try: import ic - except ImportError: pass - else: ic.launchurl(url) else: rc = os.system('netscape -remote "openURL(%s)" &' % url) if rc: os.system('netscape "%s" &' % url) Modified: python/branches/py3k-jit/Lib/shutil.py ============================================================================== --- python/branches/py3k-jit/Lib/shutil.py (original) +++ python/branches/py3k-jit/Lib/shutil.py Thu May 6 23:49:27 2010 @@ -84,8 +84,6 @@ if _samefile(src, dst): raise Error("`%s` and `%s` are the same file" % (src, dst)) - fsrc = None - fdst = None for fn in [src, dst]: try: st = os.stat(fn) @@ -96,15 +94,10 @@ # XXX What about other special files? (sockets, devices...) if stat.S_ISFIFO(st.st_mode): raise SpecialFileError("`%s` is a named pipe" % fn) - try: - fsrc = open(src, 'rb') - fdst = open(dst, 'wb') - copyfileobj(fsrc, fdst) - finally: - if fdst: - fdst.close() - if fsrc: - fsrc.close() + + with open(src, 'rb') as fsrc: + with open(dst, 'wb') as fdst: + copyfileobj(fsrc, fdst) def copymode(src, dst): """Copy mode bits from src to dst""" Modified: python/branches/py3k-jit/Lib/tarfile.py ============================================================================== --- python/branches/py3k-jit/Lib/tarfile.py (original) +++ python/branches/py3k-jit/Lib/tarfile.py Thu May 6 23:49:27 2010 @@ -50,13 +50,6 @@ import copy import re -if sys.platform == 'mac': - # This module needs work for MacOS9, especially in the area of pathname - # handling. In many places it is assumed a simple substitution of / by the - # local os.path.sep is good enough to convert pathnames, but this does not - # work with the mac rooted:path:name versus :nonrooted:path:name syntax - raise ImportError("tarfile does not work for platform==mac") - try: import grp, pwd except ImportError: @@ -985,7 +978,7 @@ return info - def tobuf(self, format=DEFAULT_FORMAT, encoding=ENCODING, errors="strict"): + def tobuf(self, format=DEFAULT_FORMAT, encoding=ENCODING, errors="surrogateescape"): """Return a tar header as a string of 512 byte blocks. """ info = self.get_info() @@ -1497,7 +1490,7 @@ def __init__(self, name=None, mode="r", fileobj=None, format=None, tarinfo=None, dereference=None, ignore_zeros=None, encoding=None, - errors=None, pax_headers=None, debug=None, errorlevel=None): + errors="surrogateescape", pax_headers=None, debug=None, errorlevel=None): """Open an (uncompressed) tar archive `name'. `mode' is either 'r' to read from an existing archive, 'a' to append data to an existing file or 'w' to create a new file overwriting an existing one. `mode' @@ -1538,13 +1531,7 @@ self.ignore_zeros = ignore_zeros if encoding is not None: self.encoding = encoding - - if errors is not None: - self.errors = errors - elif mode == "r": - self.errors = "replace" - else: - self.errors = "strict" + self.errors = errors if pax_headers is not None and self.format == PAX_FORMAT: self.pax_headers = pax_headers Modified: python/branches/py3k-jit/Lib/test/audiotest.au ============================================================================== Binary files. No diff available. Modified: python/branches/py3k-jit/Lib/test/regrtest.py ============================================================================== --- python/branches/py3k-jit/Lib/test/regrtest.py (original) +++ python/branches/py3k-jit/Lib/test/regrtest.py Thu May 6 23:49:27 2010 @@ -1209,34 +1209,6 @@ test_kqueue test_ossaudiodev """, - 'mac': - """ - test_atexit - test_bz2 - test_crypt - test_curses - test_dbm - test_fcntl - test_fork1 - test_epoll - test_grp - test_ioctl - test_largefile - test_locale - test_kqueue - test_mmap - test_openpty - test_ossaudiodev - test_poll - test_popen - test_posix - test_pty - test_pwd - test_resource - test_signal - test_sundry - test_tarfile - """, 'unixware7': """ test_epoll Modified: python/branches/py3k-jit/Lib/test/support.py ============================================================================== --- python/branches/py3k-jit/Lib/test/support.py (original) +++ python/branches/py3k-jit/Lib/test/support.py Thu May 6 23:49:27 2010 @@ -186,7 +186,7 @@ os.unlink(filename) except OSError as error: # The filename need not exist. - if error.errno != errno.ENOENT: + if error.errno not in (errno.ENOENT, errno.ENOTDIR): raise def rmtree(path): @@ -376,6 +376,7 @@ # module name. TESTFN = "{}_{}_tmp".format(TESTFN, os.getpid()) + # Assuming sys.getfilesystemencoding()!=sys.getdefaultencoding() # TESTFN_UNICODE is a filename that can be encoded using the # file system encoding, but *not* with the default (ascii) encoding Modified: python/branches/py3k-jit/Lib/test/test_asyncore.py ============================================================================== --- python/branches/py3k-jit/Lib/test/test_asyncore.py (original) +++ python/branches/py3k-jit/Lib/test/test_asyncore.py Thu May 6 23:49:27 2010 @@ -5,6 +5,7 @@ import socket import sys import time +import warnings from test import support from test.support import TESTFN, run_unittest, unlink @@ -306,6 +307,22 @@ 'warning: unhandled accept event'] self.assertEquals(lines, expected) + def test_issue_8594(self): + # XXX - this test is supposed to be removed in next major Python + # version + d = asyncore.dispatcher(socket.socket()) + # make sure the error message no longer refers to the socket + # object but the dispatcher instance instead + self.assertRaisesRegexp(AttributeError, 'dispatcher instance', + getattr, d, 'foo') + # cheap inheritance with the underlying socket is supposed + # to still work but a DeprecationWarning is expected + with warnings.catch_warnings(record=True) as w: + warnings.simplefilter("always") + family = d.family + self.assertEqual(family, socket.AF_INET) + self.assertTrue(len(w) == 1) + self.assertTrue(issubclass(w[0].category, DeprecationWarning)) class dispatcherwithsend_noread(asyncore.dispatcher_with_send): Modified: python/branches/py3k-jit/Lib/test/test_builtin.py ============================================================================== --- python/branches/py3k-jit/Lib/test/test_builtin.py (original) +++ python/branches/py3k-jit/Lib/test/test_builtin.py Thu May 6 23:49:27 2010 @@ -942,8 +942,8 @@ self.assertRaises(RuntimeError, range, a, a + 1, badzero(1)) """ - # Reject floats when it would require PyLongs to represent. - # (smaller floats still accepted, but deprecated) + # Reject floats. + self.assertRaises(TypeError, range, 1., 1., 1.) self.assertRaises(TypeError, range, 1e100, 1e101, 1e101) self.assertRaises(TypeError, range, 0, "spam") @@ -954,6 +954,46 @@ self.assertRaises(OverflowError, len, range(0, sys.maxsize**10)) + bignum = 2*sys.maxsize + smallnum = 42 + + # User-defined class with an __index__ method + class I: + def __init__(self, n): + self.n = int(n) + def __index__(self): + return self.n + self.assertEqual(list(range(I(bignum), I(bignum + 1))), [bignum]) + self.assertEqual(list(range(I(smallnum), I(smallnum + 1))), [smallnum]) + + # User-defined class with a failing __index__ method + class IX: + def __index__(self): + raise RuntimeError + self.assertRaises(RuntimeError, range, IX()) + + # User-defined class with an invalid __index__ method + class IN: + def __index__(self): + return "not a number" + + self.assertRaises(TypeError, range, IN()) + # Exercise various combinations of bad arguments, to check + # refcounting logic + self.assertRaises(TypeError, range, 0.0) + + self.assertRaises(TypeError, range, 0, 0.0) + self.assertRaises(TypeError, range, 0.0, 0) + self.assertRaises(TypeError, range, 0.0, 0.0) + + self.assertRaises(TypeError, range, 0, 0, 1.0) + self.assertRaises(TypeError, range, 0, 0.0, 1) + self.assertRaises(TypeError, range, 0, 0.0, 1.0) + self.assertRaises(TypeError, range, 0.0, 0, 1) + self.assertRaises(TypeError, range, 0.0, 0, 1.0) + self.assertRaises(TypeError, range, 0.0, 0.0, 1) + self.assertRaises(TypeError, range, 0.0, 0.0, 1.0) + def test_input(self): self.write_testfile() fp = open(TESTFN, 'r') Modified: python/branches/py3k-jit/Lib/test/test_decimal.py ============================================================================== --- python/branches/py3k-jit/Lib/test/test_decimal.py (original) +++ python/branches/py3k-jit/Lib/test/test_decimal.py Thu May 6 23:49:27 2010 @@ -41,6 +41,12 @@ # Useful Test Constant Signals = tuple(getcontext().flags.keys()) +# Signals ordered with respect to precedence: when an operation +# produces multiple signals, signals occurring later in the list +# should be handled before those occurring earlier in the list. +OrderedSignals = (Clamped, Rounded, Inexact, Subnormal, + Underflow, Overflow, DivisionByZero, InvalidOperation) + # Tests are built around these assumed context defaults. # test_main() restores the original context. def init(): @@ -351,6 +357,25 @@ else: self.fail("Did not raise %s in %s" % (error, s)) self.context.traps[error] = 0 + + # as above, but add traps cumulatively, to check precedence + ordered_errors = [e for e in OrderedSignals if e in theirexceptions] + for error in ordered_errors: + self.context.traps[error] = 1 + try: + funct(*vals) + except error: + pass + except Signals as e: + self.fail("Raised %s in %s; expected %s" % + (type(e), s, error)) + else: + self.fail("Did not raise %s in %s" % (error, s)) + # reset traps + for error in ordered_errors: + self.context.traps[error] = 0 + + if DEBUG: print("--", self.context) try: Modified: python/branches/py3k-jit/Lib/test/test_dictviews.py ============================================================================== --- python/branches/py3k-jit/Lib/test/test_dictviews.py (original) +++ python/branches/py3k-jit/Lib/test/test_dictviews.py Thu May 6 23:49:27 2010 @@ -69,6 +69,82 @@ self.assertEqual(set(values), {10, "ABC"}) self.assertEqual(len(values), 2) + def test_dict_repr(self): + d = {1: 10, "a": "ABC"} + self.assertIsInstance(repr(d), str) + r = repr(d.items()) + self.assertIsInstance(r, str) + self.assertTrue(r == "dict_items([('a', 'ABC'), (1, 10)])" or + r == "dict_items([(1, 10), ('a', 'ABC')])") + r = repr(d.keys()) + self.assertIsInstance(r, str) + self.assertTrue(r == "dict_keys(['a', 1])" or + r == "dict_keys([1, 'a'])") + r = repr(d.values()) + self.assertIsInstance(r, str) + self.assertTrue(r == "dict_values(['ABC', 10])" or + r == "dict_values([10, 'ABC'])") + + def test_keys_set_operations(self): + d1 = {'a': 1, 'b': 2} + d2 = {'b': 3, 'c': 2} + d3 = {'d': 4, 'e': 5} + self.assertEqual(d1.keys() & d1.keys(), {'a', 'b'}) + self.assertEqual(d1.keys() & d2.keys(), {'b'}) + self.assertEqual(d1.keys() & d3.keys(), set()) + self.assertEqual(d1.keys() & set(d1.keys()), {'a', 'b'}) + self.assertEqual(d1.keys() & set(d2.keys()), {'b'}) + self.assertEqual(d1.keys() & set(d3.keys()), set()) + + self.assertEqual(d1.keys() | d1.keys(), {'a', 'b'}) + self.assertEqual(d1.keys() | d2.keys(), {'a', 'b', 'c'}) + self.assertEqual(d1.keys() | d3.keys(), {'a', 'b', 'd', 'e'}) + self.assertEqual(d1.keys() | set(d1.keys()), {'a', 'b'}) + self.assertEqual(d1.keys() | set(d2.keys()), {'a', 'b', 'c'}) + self.assertEqual(d1.keys() | set(d3.keys()), + {'a', 'b', 'd', 'e'}) + + self.assertEqual(d1.keys() ^ d1.keys(), set()) + self.assertEqual(d1.keys() ^ d2.keys(), {'a', 'c'}) + self.assertEqual(d1.keys() ^ d3.keys(), {'a', 'b', 'd', 'e'}) + self.assertEqual(d1.keys() ^ set(d1.keys()), set()) + self.assertEqual(d1.keys() ^ set(d2.keys()), {'a', 'c'}) + self.assertEqual(d1.keys() ^ set(d3.keys()), + {'a', 'b', 'd', 'e'}) + + def test_items_set_operations(self): + d1 = {'a': 1, 'b': 2} + d2 = {'a': 2, 'b': 2} + d3 = {'d': 4, 'e': 5} + self.assertEqual( + d1.items() & d1.items(), {('a', 1), ('b', 2)}) + self.assertEqual(d1.items() & d2.items(), {('b', 2)}) + self.assertEqual(d1.items() & d3.items(), set()) + self.assertEqual(d1.items() & set(d1.items()), + {('a', 1), ('b', 2)}) + self.assertEqual(d1.items() & set(d2.items()), {('b', 2)}) + self.assertEqual(d1.items() & set(d3.items()), set()) + + self.assertEqual(d1.items() | d1.items(), + {('a', 1), ('b', 2)}) + self.assertEqual(d1.items() | d2.items(), + {('a', 1), ('a', 2), ('b', 2)}) + self.assertEqual(d1.items() | d3.items(), + {('a', 1), ('b', 2), ('d', 4), ('e', 5)}) + self.assertEqual(d1.items() | set(d1.items()), + {('a', 1), ('b', 2)}) + self.assertEqual(d1.items() | set(d2.items()), + {('a', 1), ('a', 2), ('b', 2)}) + self.assertEqual(d1.items() | set(d3.items()), + {('a', 1), ('b', 2), ('d', 4), ('e', 5)}) + + self.assertEqual(d1.items() ^ d1.items(), set()) + self.assertEqual(d1.items() ^ d2.items(), + {('a', 1), ('a', 2)}) + self.assertEqual(d1.items() ^ d3.items(), + {('a', 1), ('b', 2), ('d', 4), ('e', 5)}) + + def test_main(): support.run_unittest(DictSetTest) Modified: python/branches/py3k-jit/Lib/test/test_frozen.py ============================================================================== --- python/branches/py3k-jit/Lib/test/test_frozen.py (original) +++ python/branches/py3k-jit/Lib/test/test_frozen.py Thu May 6 23:49:27 2010 @@ -39,13 +39,12 @@ else: self.fail("import __phello__.foo should have failed") - if sys.platform != "mac": # On the Mac this import does succeed. - try: - import __phello__.foo - except ImportError: - pass - else: - self.fail("import __phello__.foo should have failed") + try: + import __phello__.foo + except ImportError: + pass + else: + self.fail("import __phello__.foo should have failed") del sys.modules['__hello__'] del sys.modules['__phello__'] Modified: python/branches/py3k-jit/Lib/test/test_ftplib.py ============================================================================== --- python/branches/py3k-jit/Lib/test/test_ftplib.py (original) +++ python/branches/py3k-jit/Lib/test/test_ftplib.py Thu May 6 23:49:27 2010 @@ -50,6 +50,9 @@ def push(self, what): super(DummyDTPHandler, self).push(what.encode('ascii')) + def handle_error(self): + raise + class DummyFTPHandler(asynchat.async_chat): Modified: python/branches/py3k-jit/Lib/test/test_gdb.py ============================================================================== --- python/branches/py3k-jit/Lib/test/test_gdb.py (original) +++ python/branches/py3k-jit/Lib/test/test_gdb.py Thu May 6 23:49:27 2010 @@ -121,6 +121,11 @@ # Ignore some noise on stderr due to the pending breakpoint: err = err.replace('Function "%s" not defined.\n' % breakpoint, '') + # Ignore some other noise on stderr (http://bugs.python.org/issue8600) + err = err.replace("warning: Unable to find libthread_db matching" + " inferior's thread library, thread debugging will" + " not be available.\n", + '') # Ensure no unexpected error messages: self.assertEquals(err, '') Modified: python/branches/py3k-jit/Lib/test/test_ossaudiodev.py ============================================================================== --- python/branches/py3k-jit/Lib/test/test_ossaudiodev.py (original) +++ python/branches/py3k-jit/Lib/test/test_ossaudiodev.py Thu May 6 23:49:27 2010 @@ -76,7 +76,7 @@ # set parameters based on .au file headers dsp.setparameters(AFMT_S16_NE, nchannels, rate) - self.assertTrue(abs(expected_time - 2.94) < 1e-2, expected_time) + self.assertTrue(abs(expected_time - 3.51) < 1e-2, expected_time) t1 = time.time() dsp.write(data) dsp.close() Modified: python/branches/py3k-jit/Lib/test/test_reprlib.py ============================================================================== --- python/branches/py3k-jit/Lib/test/test_reprlib.py (original) +++ python/branches/py3k-jit/Lib/test/test_reprlib.py Thu May 6 23:49:27 2010 @@ -304,8 +304,7 @@ def test_main(): run_unittest(ReprTests) - if os.name != 'mac': - run_unittest(LongReprTest) + run_unittest(LongReprTest) if __name__ == "__main__": Modified: python/branches/py3k-jit/Lib/test/test_select.py ============================================================================== --- python/branches/py3k-jit/Lib/test/test_select.py (original) +++ python/branches/py3k-jit/Lib/test/test_select.py Thu May 6 23:49:27 2010 @@ -4,7 +4,7 @@ import os import sys - at unittest.skipIf(sys.platform[:3] in ('win', 'mac', 'os2', 'riscos'), + at unittest.skipIf(sys.platform[:3] in ('win', 'os2', 'riscos'), "can't easily test on this system") class SelectTestCase(unittest.TestCase): Modified: python/branches/py3k-jit/Lib/test/test_shutil.py ============================================================================== --- python/branches/py3k-jit/Lib/test/test_shutil.py (original) +++ python/branches/py3k-jit/Lib/test/test_shutil.py Thu May 6 23:49:27 2010 @@ -798,8 +798,112 @@ shutil.rmtree(TESTFN, ignore_errors=True) +class TestCopyFile(unittest.TestCase): + + _delete = False + + class Faux(object): + _entered = False + _exited_with = None + _raised = False + def __init__(self, raise_in_exit=False, suppress_at_exit=True): + self._raise_in_exit = raise_in_exit + self._suppress_at_exit = suppress_at_exit + def read(self, *args): + return '' + def __enter__(self): + self._entered = True + def __exit__(self, exc_type, exc_val, exc_tb): + self._exited_with = exc_type, exc_val, exc_tb + if self._raise_in_exit: + self._raised = True + raise IOError("Cannot close") + return self._suppress_at_exit + + def tearDown(self): + if self._delete: + del shutil.open + + def _set_shutil_open(self, func): + shutil.open = func + self._delete = True + + def test_w_source_open_fails(self): + def _open(filename, mode='r'): + if filename == 'srcfile': + raise IOError('Cannot open "srcfile"') + assert 0 # shouldn't reach here. + + self._set_shutil_open(_open) + + self.assertRaises(IOError, shutil.copyfile, 'srcfile', 'destfile') + + def test_w_dest_open_fails(self): + + srcfile = self.Faux() + + def _open(filename, mode='r'): + if filename == 'srcfile': + return srcfile + if filename == 'destfile': + raise IOError('Cannot open "destfile"') + assert 0 # shouldn't reach here. + + self._set_shutil_open(_open) + + shutil.copyfile('srcfile', 'destfile') + self.assertTrue(srcfile._entered) + self.assertTrue(srcfile._exited_with[0] is IOError) + self.assertEqual(srcfile._exited_with[1].args, + ('Cannot open "destfile"',)) + + def test_w_dest_close_fails(self): + + srcfile = self.Faux() + destfile = self.Faux(True) + + def _open(filename, mode='r'): + if filename == 'srcfile': + return srcfile + if filename == 'destfile': + return destfile + assert 0 # shouldn't reach here. + + self._set_shutil_open(_open) + + shutil.copyfile('srcfile', 'destfile') + self.assertTrue(srcfile._entered) + self.assertTrue(destfile._entered) + self.assertTrue(destfile._raised) + self.assertTrue(srcfile._exited_with[0] is IOError) + self.assertEqual(srcfile._exited_with[1].args, + ('Cannot close',)) + + def test_w_source_close_fails(self): + + srcfile = self.Faux(True) + destfile = self.Faux() + + def _open(filename, mode='r'): + if filename == 'srcfile': + return srcfile + if filename == 'destfile': + return destfile + assert 0 # shouldn't reach here. + + self._set_shutil_open(_open) + + self.assertRaises(IOError, + shutil.copyfile, 'srcfile', 'destfile') + self.assertTrue(srcfile._entered) + self.assertTrue(destfile._entered) + self.assertFalse(destfile._raised) + self.assertTrue(srcfile._exited_with[0] is None) + self.assertTrue(srcfile._raised) + + def test_main(): - support.run_unittest(TestShutil, TestMove) + support.run_unittest(TestShutil, TestMove, TestCopyFile) if __name__ == '__main__': test_main() Modified: python/branches/py3k-jit/Lib/test/test_smtplib.py ============================================================================== --- python/branches/py3k-jit/Lib/test/test_smtplib.py (original) +++ python/branches/py3k-jit/Lib/test/test_smtplib.py Thu May 6 23:49:27 2010 @@ -374,6 +374,9 @@ else: self.push('550 No access for you!') + def handle_error(self): + raise + class SimSMTPServer(smtpd.SMTPServer): @@ -392,6 +395,9 @@ def add_feature(self, feature): self._extra_features.append(feature) + def handle_error(self): + raise + # Test various SMTP & ESMTP commands/behaviors that require a simulated server # (i.e., something with more features than DebuggingServer) Modified: python/branches/py3k-jit/Lib/test/test_socket.py ============================================================================== --- python/branches/py3k-jit/Lib/test/test_socket.py (original) +++ python/branches/py3k-jit/Lib/test/test_socket.py Thu May 6 23:49:27 2010 @@ -1465,9 +1465,7 @@ def test_main(): tests = [GeneralModuleTests, BasicTCPTest, TCPCloserTest, TCPTimeoutTest, - TestExceptions, BufferIOTest, BasicTCPTest2] - if sys.platform != 'mac': - tests.extend([ BasicUDPTest, UDPTimeoutTest ]) + TestExceptions, BufferIOTest, BasicTCPTest2, BasicUDPTest, UDPTimeoutTest ] tests.extend([ NonBlockingTCPTests, Modified: python/branches/py3k-jit/Lib/test/test_ssl.py ============================================================================== --- python/branches/py3k-jit/Lib/test/test_ssl.py (original) +++ python/branches/py3k-jit/Lib/test/test_ssl.py Thu May 6 23:49:27 2010 @@ -659,7 +659,7 @@ if support.verbose: sys.stdout.write("\nsocket.error is %s\n" % x[1]) else: - self.fail("Use of invalid cert should have failed!") + raise AssertionError("Use of invalid cert should have failed!") finally: server.stop() server.join() @@ -704,7 +704,7 @@ if support.verbose: sys.stdout.write(" client: read %r\n" % outdata) if outdata != indata.lower(): - self.fail( + raise AssertionError( "bad data <<%r>> (%d) received; expected <<%r>> (%d)\n" % (outdata[:20], len(outdata), indata[:20].lower(), len(indata))) @@ -752,7 +752,7 @@ raise else: if not expect_success: - self.fail( + raise AssertionError( "Client protocol %s succeeded with server protocol %s!" % (ssl.get_protocol_name(client_protocol), ssl.get_protocol_name(server_protocol))) Modified: python/branches/py3k-jit/Lib/test/test_strptime.py ============================================================================== --- python/branches/py3k-jit/Lib/test/test_strptime.py (original) +++ python/branches/py3k-jit/Lib/test/test_strptime.py Thu May 6 23:49:27 2010 @@ -298,9 +298,6 @@ self.assertEqual(strp_output.tm_isdst, 0) strp_output = _strptime._strptime_time("GMT", "%Z") self.assertEqual(strp_output.tm_isdst, 0) - if sys.platform == "mac": - # Timezones don't really work on MacOS9 - return time_tuple = time.localtime() strf_output = time.strftime("%Z") #UTC does not have a timezone strp_output = _strptime._strptime_time(strf_output, "%Z") @@ -317,8 +314,6 @@ def test_bad_timezone(self): # Explicitly test possibility of bad timezone; # when time.tzname[0] == time.tzname[1] and time.daylight - if sys.platform == "mac": - return #MacOS9 has severely broken timezone support. tz_name = time.tzname[0] if tz_name.upper() in ("UTC", "GMT"): return Modified: python/branches/py3k-jit/Lib/test/test_tarfile.py ============================================================================== --- python/branches/py3k-jit/Lib/test/test_tarfile.py (original) +++ python/branches/py3k-jit/Lib/test/test_tarfile.py Thu May 6 23:49:27 2010 @@ -1118,8 +1118,8 @@ if self.format != tarfile.PAX_FORMAT: tar = tarfile.open(tmpname, encoding="ascii") t = tar.getmember("foo") - self.assertEqual(t.uname, "\ufffd\ufffd\ufffd") - self.assertEqual(t.gname, "\ufffd\ufffd\ufffd") + self.assertEqual(t.uname, "\udce4\udcf6\udcfc") + self.assertEqual(t.gname, "\udce4\udcf6\udcfc") class GNUUnicodeTest(UstarUnicodeTest): Modified: python/branches/py3k-jit/Lib/test/test_tempfile.py ============================================================================== --- python/branches/py3k-jit/Lib/test/test_tempfile.py (original) +++ python/branches/py3k-jit/Lib/test/test_tempfile.py Thu May 6 23:49:27 2010 @@ -20,9 +20,7 @@ # TEST_FILES may need to be tweaked for systems depending on the maximum # number of files that can be opened at one time (see ulimit -n) -if sys.platform == 'mac': - TEST_FILES = 32 -elif sys.platform in ('openbsd3', 'openbsd4'): +if sys.platform in ('openbsd3', 'openbsd4'): TEST_FILES = 48 else: TEST_FILES = 100 @@ -265,7 +263,7 @@ file = self.do_create() mode = stat.S_IMODE(os.stat(file.name).st_mode) expected = 0o600 - if sys.platform in ('win32', 'os2emx', 'mac'): + if sys.platform in ('win32', 'os2emx'): # There's no distinction among 'user', 'group' and 'world'; # replicate the 'user' bits. user = expected >> 6 @@ -488,7 +486,7 @@ mode = stat.S_IMODE(os.stat(dir).st_mode) mode &= 0o777 # Mask off sticky bits inherited from /tmp expected = 0o700 - if sys.platform in ('win32', 'os2emx', 'mac'): + if sys.platform in ('win32', 'os2emx'): # There's no distinction among 'user', 'group' and 'world'; # replicate the 'user' bits. user = expected >> 6 Modified: python/branches/py3k-jit/Lib/test/test_urllib2.py ============================================================================== --- python/branches/py3k-jit/Lib/test/test_urllib2.py (original) +++ python/branches/py3k-jit/Lib/test/test_urllib2.py Thu May 6 23:49:27 2010 @@ -22,11 +22,6 @@ # XXX Name hacking to get this to work on Windows. fname = os.path.abspath(urllib.request.__file__).replace('\\', '/') - # And more hacking to get it to work on MacOS. This assumes - # urllib.pathname2url works, unfortunately... - if os.name == 'mac': - fname = '/' + fname.replace(':', '/') - if os.name == 'nt': file_url = "file:///%s" % fname else: Modified: python/branches/py3k-jit/Lib/test/test_uuid.py ============================================================================== --- python/branches/py3k-jit/Lib/test/test_uuid.py (original) +++ python/branches/py3k-jit/Lib/test/test_uuid.py Thu May 6 23:49:27 2010 @@ -457,6 +457,34 @@ equal(u, uuid.UUID(v)) equal(str(u), v) + def testIssue8621(self): + import os + import sys + if os.name != 'posix': + return + + # On at least some versions of OSX uuid.uuid4 generates + # the same sequence of UUIDs in the parent and any + # children started using fork. + fds = os.pipe() + pid = os.fork() + if pid == 0: + os.close(fds[0]) + value = uuid.uuid4() + os.write(fds[1], value.hex.encode('latin1')) + os._exit(0) + + else: + os.close(fds[1]) + parent_value = uuid.uuid4().hex + os.waitpid(pid, 0) + child_value = os.read(fds[0], 100).decode('latin1') + + self.assertNotEqual(parent_value, child_value) + + + + def test_main(): support.run_unittest(TestUUID) Modified: python/branches/py3k-jit/Lib/urllib/request.py ============================================================================== --- python/branches/py3k-jit/Lib/urllib/request.py (original) +++ python/branches/py3k-jit/Lib/urllib/request.py Thu May 6 23:49:27 2010 @@ -1338,9 +1338,7 @@ MAXFTPCACHE = 10 # Trim the ftp cache beyond this size # Helper for non-unix systems -if os.name == 'mac': - from macurl2path import url2pathname, pathname2url -elif os.name == 'nt': +if os.name == 'nt': from nturl2path import url2pathname, pathname2url else: def url2pathname(pathname): Modified: python/branches/py3k-jit/Lib/uuid.py ============================================================================== --- python/branches/py3k-jit/Lib/uuid.py (original) +++ python/branches/py3k-jit/Lib/uuid.py Thu May 6 23:49:27 2010 @@ -427,6 +427,19 @@ if hasattr(lib, 'uuid_generate_time'): _uuid_generate_time = lib.uuid_generate_time + # The uuid_generate_* functions are broken on MacOS X 10.6, as noted + # in issue #8621 the function generates the same sequence of values + # in the parent process and all children created using fork (unless + # those children use exec as well). + # + # Assume that the uuid_generate functions are broken from 10.6 onward, + # the test can be adjusted when a later version is fixed. + import sys + if sys.platform == 'darwin': + import os + if int(os.uname()[2].split('.')[0]) >= 10: + _uuid_generate_random = _uuid_generate_time = None + # On Windows prior to 2000, UuidCreate gives a UUID containing the # hardware address. On Windows 2000 and later, UuidCreate makes a # random UUID and UuidCreateSequential gives a UUID containing the Modified: python/branches/py3k-jit/Mac/Makefile.in ============================================================================== --- python/branches/py3k-jit/Mac/Makefile.in (original) +++ python/branches/py3k-jit/Mac/Makefile.in Thu May 6 23:49:27 2010 @@ -58,8 +58,8 @@ ifneq ($(LIPO_32BIT_FLAGS),) lipo $(LIPO_32BIT_FLAGS) -output $(DESTDIR)$(prefix)/bin/python$(VERSION)-32 pythonw lipo $(LIPO_32BIT_FLAGS) -output $(DESTDIR)$(prefix)/bin/pythonw$(VERSION)-32 pythonw - ln -sf pythonw$(VERSION)-32 "$(DESTDIR)$(prefix)/bin/pythonw$(VERSION)" - ln -sf python$(VERSION)-32 "$(DESTDIR)$(prefix)/bin/python$(VERSION)" + ln -sf pythonw$(VERSION)-32 "$(DESTDIR)$(prefix)/bin/pythonw3-32" + ln -sf python$(VERSION)-32 "$(DESTDIR)$(prefix)/bin/python3-32" endif # Modified: python/branches/py3k-jit/Misc/NEWS ============================================================================== --- python/branches/py3k-jit/Misc/NEWS (original) +++ python/branches/py3k-jit/Misc/NEWS Thu May 6 23:49:27 2010 @@ -54,8 +54,8 @@ - Raise a TypeError when trying to delete a T_STRING_INPLACE struct member. -- Issue #8211: Save/restore CFLAGS around AC_PROG_CC in configure.in, compiler - optimizations are disabled when --with-pydebug is used. +- Issue #8211: Save/restore CFLAGS around AC_PROG_CC in configure.in, in + case it is set. - Issue #8226: sys.setfilesystemencoding() raises a LookupError if the encoding is unknown @@ -348,6 +348,30 @@ Library ------- +- Issue #8573: asyncore _strerror() function might throw ValueError. + +- Issue #8483: asyncore.dispatcher's __getattr__ method produced confusing + error messages when accessing undefined class attributes because of the cheap + inheritance with the underlying socket object. + The cheap inheritance has been deprecated. + +- Issue #4265: shutil.copyfile() was leaking file descriptors when disk fills. + Patch by Tres Seaver. + +- Issue #8390: tarfile uses surrogateespace as the default error handler + (instead of replace in read mode or strict in write mode) + +- Issue #7755: Use an unencumbered audio file for tests. + +- Issue #8621: uuid.uuid4() returned the same sequence of values in the + parent and any children created using ``os.fork`` on MacOS X 10.6. + +- Issue #8567: Fix precedence of signals in Decimal module: when a + Decimal operation raises multiple signals and more than one of those + signals is trapped, the specification determines the order in which + the signals should be handled. In many cases this order wasn't + being followed, leading to the wrong Python exception being raised. + - Issue #7865: The close() method of :mod:`io` objects should not swallow exceptions raised by the implicit flush(). Also ensure that calling close() several times is supported. Patch by Pascal Chambon. @@ -1128,6 +1152,12 @@ Build ----- +- Issue #8625: Turn off optimization in --with-pydebug builds with + gcc. (Optimization was unintentionally turned on in gcc + --with-pydebug builds as a result of the issue #1628484 fix, + combined with autoconf's strange choice of default CFLAGS produced + by AC_PROG_CC for gcc.) + - Issue #3646: It is now easily possible to install a Python framework into your home directory on MacOSX, see Mac/README for more information. Modified: python/branches/py3k-jit/Modules/_ctypes/callproc.c ============================================================================== --- python/branches/py3k-jit/Modules/_ctypes/callproc.c (original) +++ python/branches/py3k-jit/Modules/_ctypes/callproc.c Thu May 6 23:49:27 2010 @@ -761,7 +761,6 @@ ffi_cif cif; int cc; #ifdef MS_WIN32 - int delta; #ifndef DONT_USE_SEH DWORD dwExceptionCode = 0; EXCEPTION_RECORD record; @@ -812,9 +811,8 @@ #ifndef DONT_USE_SEH __try { #endif - delta = #endif - ffi_call(&cif, (void *)pProc, resmem, avalues); + ffi_call(&cif, (void *)pProc, resmem, avalues); #ifdef MS_WIN32 #ifndef DONT_USE_SEH } @@ -846,35 +844,6 @@ return -1; } #endif -#ifdef MS_WIN64 - if (delta != 0) { - PyErr_Format(PyExc_RuntimeError, - "ffi_call failed with code %d", - delta); - return -1; - } -#else - if (delta < 0) { - if (flags & FUNCFLAG_CDECL) - PyErr_Format(PyExc_ValueError, - "Procedure called with not enough " - "arguments (%d bytes missing) " - "or wrong calling convention", - -delta); - else - PyErr_Format(PyExc_ValueError, - "Procedure probably called with not enough " - "arguments (%d bytes missing)", - -delta); - return -1; - } else if (delta > 0) { - PyErr_Format(PyExc_ValueError, - "Procedure probably called with too many " - "arguments (%d bytes in excess)", - delta); - return -1; - } -#endif #endif if ((flags & FUNCFLAG_PYTHONAPI) && PyErr_Occurred()) return -1; @@ -1147,11 +1116,7 @@ } for (i = 0; i < argcount; ++i) { atypes[i] = args[i].ffi_type; - if (atypes[i]->type == FFI_TYPE_STRUCT -#ifdef _WIN64 - && atypes[i]->size <= sizeof(void *) -#endif - ) + if (atypes[i]->type == FFI_TYPE_STRUCT) avalues[i] = (void *)args[i].value.p; else avalues[i] = (void *)&args[i].value; Deleted: python/branches/py3k-jit/Modules/_ctypes/libffi_msvc/LICENSE ============================================================================== --- python/branches/py3k-jit/Modules/_ctypes/libffi_msvc/LICENSE Thu May 6 23:49:27 2010 +++ (empty file) @@ -1,20 +0,0 @@ -libffi - Copyright (c) 1996-2003 Red Hat, Inc. - -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 CYGNUS SOLUTIONS 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. Deleted: python/branches/py3k-jit/Modules/_ctypes/libffi_msvc/README ============================================================================== --- python/branches/py3k-jit/Modules/_ctypes/libffi_msvc/README Thu May 6 23:49:27 2010 +++ (empty file) @@ -1,500 +0,0 @@ -This directory contains the libffi package, which is not part of GCC but -shipped with GCC as convenience. - -Status -====== - -libffi-2.00 has not been released yet! This is a development snapshot! - -libffi-1.20 was released on October 5, 1998. Check the libffi web -page for updates: . - - -What is libffi? -=============== - -Compilers for high level languages generate code that follow certain -conventions. These conventions are necessary, in part, for separate -compilation to work. One such convention is the "calling -convention". The "calling convention" is essentially a set of -assumptions made by the compiler about where function arguments will -be found on entry to a function. A "calling convention" also specifies -where the return value for a function is found. - -Some programs may not know at the time of compilation what arguments -are to be passed to a function. For instance, an interpreter may be -told at run-time about the number and types of arguments used to call -a given function. Libffi can be used in such programs to provide a -bridge from the interpreter program to compiled code. - -The libffi library provides a portable, high level programming -interface to various calling conventions. This allows a programmer to -call any function specified by a call interface description at run -time. - -Ffi stands for Foreign Function Interface. A foreign function -interface is the popular name for the interface that allows code -written in one language to call code written in another language. The -libffi library really only provides the lowest, machine dependent -layer of a fully featured foreign function interface. A layer must -exist above libffi that handles type conversions for values passed -between the two languages. - - -Supported Platforms and Prerequisites -===================================== - -Libffi has been ported to: - - SunOS 4.1.3 & Solaris 2.x (SPARC-V8, SPARC-V9) - - Irix 5.3 & 6.2 (System V/o32 & n32) - - Intel x86 - Linux (System V ABI) - - Alpha - Linux and OSF/1 - - m68k - Linux (System V ABI) - - PowerPC - Linux (System V ABI, Darwin, AIX) - - ARM - Linux (System V ABI) - -Libffi has been tested with the egcs 1.0.2 gcc compiler. Chances are -that other versions will work. Libffi has also been built and tested -with the SGI compiler tools. - -On PowerPC, the tests failed (see the note below). - -You must use GNU make to build libffi. SGI's make will not work. -Sun's probably won't either. - -If you port libffi to another platform, please let me know! I assume -that some will be easy (x86 NetBSD), and others will be more difficult -(HP). - - -Installing libffi -================= - -[Note: before actually performing any of these installation steps, - you may wish to read the "Platform Specific Notes" below.] - -First you must configure the distribution for your particular -system. Go to the directory you wish to build libffi in and run the -"configure" program found in the root directory of the libffi source -distribution. - -You may want to tell configure where to install the libffi library and -header files. To do that, use the --prefix configure switch. Libffi -will install under /usr/local by default. - -If you want to enable extra run-time debugging checks use the the ---enable-debug configure switch. This is useful when your program dies -mysteriously while using libffi. - -Another useful configure switch is --enable-purify-safety. Using this -will add some extra code which will suppress certain warnings when you -are using Purify with libffi. Only use this switch when using -Purify, as it will slow down the library. - -Configure has many other options. Use "configure --help" to see them all. - -Once configure has finished, type "make". Note that you must be using -GNU make. SGI's make will not work. Sun's probably won't either. -You can ftp GNU make from prep.ai.mit.edu:/pub/gnu. - -To ensure that libffi is working as advertised, type "make test". - -To install the library and header files, type "make install". - - -Using libffi -============ - - The Basics - ---------- - -Libffi assumes that you have a pointer to the function you wish to -call and that you know the number and types of arguments to pass it, -as well as the return type of the function. - -The first thing you must do is create an ffi_cif object that matches -the signature of the function you wish to call. The cif in ffi_cif -stands for Call InterFace. To prepare a call interface object, use the -following function: - -ffi_status ffi_prep_cif(ffi_cif *cif, ffi_abi abi, - unsigned int nargs, - ffi_type *rtype, ffi_type **atypes); - - CIF is a pointer to the call interface object you wish - to initialize. - - ABI is an enum that specifies the calling convention - to use for the call. FFI_DEFAULT_ABI defaults - to the system's native calling convention. Other - ABI's may be used with care. They are system - specific. - - NARGS is the number of arguments this function accepts. - libffi does not yet support vararg functions. - - RTYPE is a pointer to an ffi_type structure that represents - the return type of the function. Ffi_type objects - describe the types of values. libffi provides - ffi_type objects for many of the native C types: - signed int, unsigned int, signed char, unsigned char, - etc. There is also a pointer ffi_type object and - a void ffi_type. Use &ffi_type_void for functions that - don't return values. - - ATYPES is a vector of ffi_type pointers. ARGS must be NARGS long. - If NARGS is 0, this is ignored. - - -ffi_prep_cif will return a status code that you are responsible -for checking. It will be one of the following: - - FFI_OK - All is good. - - FFI_BAD_TYPEDEF - One of the ffi_type objects that ffi_prep_cif - came across is bad. - - -Before making the call, the VALUES vector should be initialized -with pointers to the appropriate argument values. - -To call the the function using the initialized ffi_cif, use the -ffi_call function: - -void ffi_call(ffi_cif *cif, void *fn, void *rvalue, void **avalues); - - CIF is a pointer to the ffi_cif initialized specifically - for this function. - - FN is a pointer to the function you want to call. - - RVALUE is a pointer to a chunk of memory that is to hold the - result of the function call. Currently, it must be - at least one word in size (except for the n32 version - under Irix 6.x, which must be a pointer to an 8 byte - aligned value (a long long). It must also be at least - word aligned (depending on the return type, and the - system's alignment requirements). If RTYPE is - &ffi_type_void, this is ignored. If RVALUE is NULL, - the return value is discarded. - - AVALUES is a vector of void* that point to the memory locations - holding the argument values for a call. - If NARGS is 0, this is ignored. - - -If you are expecting a return value from FN it will have been stored -at RVALUE. - - - - An Example - ---------- - -Here is a trivial example that calls puts() a few times. - - #include - #include - - int main() - { - ffi_cif cif; - ffi_type *args[1]; - void *values[1]; - char *s; - int rc; - - /* Initialize the argument info vectors */ - args[0] = &ffi_type_uint; - values[0] = &s; - - /* Initialize the cif */ - if (ffi_prep_cif(&cif, FFI_DEFAULT_ABI, 1, - &ffi_type_uint, args) == FFI_OK) - { - s = "Hello World!"; - ffi_call(&cif, puts, &rc, values); - /* rc now holds the result of the call to puts */ - - /* values holds a pointer to the function's arg, so to - call puts() again all we need to do is change the - value of s */ - s = "This is cool!"; - ffi_call(&cif, puts, &rc, values); - } - - return 0; - } - - - - Aggregate Types - --------------- - -Although libffi has no special support for unions or bit-fields, it is -perfectly happy passing structures back and forth. You must first -describe the structure to libffi by creating a new ffi_type object -for it. Here is the definition of ffi_type: - - typedef struct _ffi_type - { - unsigned size; - short alignment; - short type; - struct _ffi_type **elements; - } ffi_type; - -All structures must have type set to FFI_TYPE_STRUCT. You may set -size and alignment to 0. These will be calculated and reset to the -appropriate values by ffi_prep_cif(). - -elements is a NULL terminated array of pointers to ffi_type objects -that describe the type of the structure elements. These may, in turn, -be structure elements. - -The following example initializes a ffi_type object representing the -tm struct from Linux's time.h: - - struct tm { - int tm_sec; - int tm_min; - int tm_hour; - int tm_mday; - int tm_mon; - int tm_year; - int tm_wday; - int tm_yday; - int tm_isdst; - /* Those are for future use. */ - long int __tm_gmtoff__; - __const char *__tm_zone__; - }; - - { - ffi_type tm_type; - ffi_type *tm_type_elements[12]; - int i; - - tm_type.size = tm_type.alignment = 0; - tm_type.elements = &tm_type_elements; - - for (i = 0; i < 9; i++) - tm_type_elements[i] = &ffi_type_sint; - - tm_type_elements[9] = &ffi_type_slong; - tm_type_elements[10] = &ffi_type_pointer; - tm_type_elements[11] = NULL; - - /* tm_type can now be used to represent tm argument types and - return types for ffi_prep_cif() */ - } - - - -Platform Specific Notes -======================= - - Intel x86 - --------- - -There are no known problems with the x86 port. - - Sun SPARC - SunOS 4.1.3 & Solaris 2.x - ------------------------------------- - -You must use GNU Make to build libffi on Sun platforms. - - MIPS - Irix 5.3 & 6.x - --------------------- - -Irix 6.2 and better supports three different calling conventions: o32, -n32 and n64. Currently, libffi only supports both o32 and n32 under -Irix 6.x, but only o32 under Irix 5.3. Libffi will automatically be -configured for whichever calling convention it was built for. - -By default, the configure script will try to build libffi with the GNU -development tools. To build libffi with the SGI development tools, set -the environment variable CC to either "cc -32" or "cc -n32" before -running configure under Irix 6.x (depending on whether you want an o32 -or n32 library), or just "cc" for Irix 5.3. - -With the n32 calling convention, when returning structures smaller -than 16 bytes, be sure to provide an RVALUE that is 8 byte aligned. -Here's one way of forcing this: - - double struct_storage[2]; - my_small_struct *s = (my_small_struct *) struct_storage; - /* Use s for RVALUE */ - -If you don't do this you are liable to get spurious bus errors. - -"long long" values are not supported yet. - -You must use GNU Make to build libffi on SGI platforms. - - ARM - System V ABI - ------------------ - -The ARM port was performed on a NetWinder running ARM Linux ELF -(2.0.31) and gcc 2.8.1. - - - - PowerPC System V ABI - -------------------- - -There are two `System V ABI's which libffi implements for PowerPC. -They differ only in how small structures are returned from functions. - -In the FFI_SYSV version, structures that are 8 bytes or smaller are -returned in registers. This is what GCC does when it is configured -for solaris, and is what the System V ABI I have (dated September -1995) says. - -In the FFI_GCC_SYSV version, all structures are returned the same way: -by passing a pointer as the first argument to the function. This is -what GCC does when it is configured for linux or a generic sysv -target. - -EGCS 1.0.1 (and probably other versions of EGCS/GCC) also has a -inconsistency with the SysV ABI: When a procedure is called with many -floating-point arguments, some of them get put on the stack. They are -all supposed to be stored in double-precision format, even if they are -only single-precision, but EGCS stores single-precision arguments as -single-precision anyway. This causes one test to fail (the `many -arguments' test). - - -What's With The Crazy Comments? -=============================== - -You might notice a number of cryptic comments in the code, delimited -by /*@ and @*/. These are annotations read by the program LCLint, a -tool for statically checking C programs. You can read all about it at -. - - -History -======= - -1.20 Oct-5-98 - Raffaele Sena produces ARM port. - -1.19 Oct-5-98 - Fixed x86 long double and long long return support. - m68k bug fixes from Andreas Schwab. - Patch for DU assembler compatibility for the Alpha from Richard - Henderson. - -1.18 Apr-17-98 - Bug fixes and MIPS configuration changes. - -1.17 Feb-24-98 - Bug fixes and m68k port from Andreas Schwab. PowerPC port from - Geoffrey Keating. Various bug x86, Sparc and MIPS bug fixes. - -1.16 Feb-11-98 - Richard Henderson produces Alpha port. - -1.15 Dec-4-97 - Fixed an n32 ABI bug. New libtool, auto* support. - -1.14 May-13-97 - libtool is now used to generate shared and static libraries. - Fixed a minor portability problem reported by Russ McManus - . - -1.13 Dec-2-96 - Added --enable-purify-safety to keep Purify from complaining - about certain low level code. - Sparc fix for calling functions with < 6 args. - Linux x86 a.out fix. - -1.12 Nov-22-96 - Added missing ffi_type_void, needed for supporting void return - types. Fixed test case for non MIPS machines. Cygnus Support - is now Cygnus Solutions. - -1.11 Oct-30-96 - Added notes about GNU make. - -1.10 Oct-29-96 - Added configuration fix for non GNU compilers. - -1.09 Oct-29-96 - Added --enable-debug configure switch. Clean-ups based on LCLint - feedback. ffi_mips.h is always installed. Many configuration - fixes. Fixed ffitest.c for sparc builds. - -1.08 Oct-15-96 - Fixed n32 problem. Many clean-ups. - -1.07 Oct-14-96 - Gordon Irlam rewrites v8.S again. Bug fixes. - -1.06 Oct-14-96 - Gordon Irlam improved the sparc port. - -1.05 Oct-14-96 - Interface changes based on feedback. - -1.04 Oct-11-96 - Sparc port complete (modulo struct passing bug). - -1.03 Oct-10-96 - Passing struct args, and returning struct values works for - all architectures/calling conventions. Expanded tests. - -1.02 Oct-9-96 - Added SGI n32 support. Fixed bugs in both o32 and Linux support. - Added "make test". - -1.01 Oct-8-96 - Fixed float passing bug in mips version. Restructured some - of the code. Builds cleanly with SGI tools. - -1.00 Oct-7-96 - First release. No public announcement. - - -Authors & Credits -================= - -libffi was written by Anthony Green . - -Portions of libffi were derived from Gianni Mariani's free gencall -library for Silicon Graphics machines. - -The closure mechanism was designed and implemented by Kresten Krab -Thorup. - -The Sparc port was derived from code contributed by the fine folks at -Visible Decisions Inc . Further enhancements were -made by Gordon Irlam at Cygnus Solutions . - -The Alpha port was written by Richard Henderson at Cygnus Solutions. - -Andreas Schwab ported libffi to m68k Linux and provided a number of -bug fixes. - -Geoffrey Keating ported libffi to the PowerPC. - -Raffaele Sena ported libffi to the ARM. - -Jesper Skov and Andrew Haley both did more than their fair share of -stepping through the code and tracking down bugs. - -Thanks also to Tom Tromey for bug fixes and configuration help. - -Thanks to Jim Blandy, who provided some useful feedback on the libffi -interface. - -If you have a problem, or have found a bug, please send a note to -green at cygnus.com. Deleted: python/branches/py3k-jit/Modules/_ctypes/libffi_msvc/README.ctypes ============================================================================== --- python/branches/py3k-jit/Modules/_ctypes/libffi_msvc/README.ctypes Thu May 6 23:49:27 2010 +++ (empty file) @@ -1,7 +0,0 @@ -The purpose is to hack the libffi sources so that they can be compiled -with MSVC, and to extend them so that they have the features I need -for ctypes. - -I retrieved the libffi sources from the gcc cvs repository on -2004-01-27. Then I did 'configure' in a 'build' subdirectory on a x86 -linux system, and copied the files I found useful. Deleted: python/branches/py3k-jit/Modules/_ctypes/libffi_msvc/ffi.c ============================================================================== --- python/branches/py3k-jit/Modules/_ctypes/libffi_msvc/ffi.c Thu May 6 23:49:27 2010 +++ (empty file) @@ -1,457 +0,0 @@ -/* ----------------------------------------------------------------------- - ffi.c - Copyright (c) 1996, 1998, 1999, 2001 Red Hat, Inc. - Copyright (c) 2002 Ranjit Mathew - Copyright (c) 2002 Bo Thorsen - Copyright (c) 2002 Roger Sayle - - x86 Foreign Function Interface - - 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 CYGNUS SOLUTIONS 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. - ----------------------------------------------------------------------- */ - -#include -#include - -#include - -/* ffi_prep_args is called by the assembly routine once stack space - has been allocated for the function's arguments */ - -extern void Py_FatalError(const char *msg); - -/*@-exportheader@*/ -void ffi_prep_args(char *stack, extended_cif *ecif) -/*@=exportheader@*/ -{ - register unsigned int i; - register void **p_argv; - register char *argp; - register ffi_type **p_arg; - - argp = stack; - if (ecif->cif->rtype->type == FFI_TYPE_STRUCT) - { - *(void **) argp = ecif->rvalue; - argp += sizeof(void *); - } - - p_argv = ecif->avalue; - - for (i = ecif->cif->nargs, p_arg = ecif->cif->arg_types; - i != 0; - i--, p_arg++) - { - size_t z; - - /* Align if necessary */ - if ((sizeof(void *) - 1) & (size_t) argp) - argp = (char *) ALIGN(argp, sizeof(void *)); - - z = (*p_arg)->size; - if (z < sizeof(int)) - { - z = sizeof(int); - switch ((*p_arg)->type) - { - case FFI_TYPE_SINT8: - *(signed int *) argp = (signed int)*(SINT8 *)(* p_argv); - break; - - case FFI_TYPE_UINT8: - *(unsigned int *) argp = (unsigned int)*(UINT8 *)(* p_argv); - break; - - case FFI_TYPE_SINT16: - *(signed int *) argp = (signed int)*(SINT16 *)(* p_argv); - break; - - case FFI_TYPE_UINT16: - *(unsigned int *) argp = (unsigned int)*(UINT16 *)(* p_argv); - break; - - case FFI_TYPE_SINT32: - *(signed int *) argp = (signed int)*(SINT32 *)(* p_argv); - break; - - case FFI_TYPE_UINT32: - *(unsigned int *) argp = (unsigned int)*(UINT32 *)(* p_argv); - break; - - case FFI_TYPE_STRUCT: - *(unsigned int *) argp = (unsigned int)*(UINT32 *)(* p_argv); - break; - - default: - FFI_ASSERT(0); - } - } - else - { - memcpy(argp, *p_argv, z); - } - p_argv++; - argp += z; - } - - if (argp - stack > ecif->cif->bytes) - { - Py_FatalError("FFI BUG: not enough stack space for arguments"); - } - return; -} - -/* Perform machine dependent cif processing */ -ffi_status ffi_prep_cif_machdep(ffi_cif *cif) -{ - /* Set the return type flag */ - switch (cif->rtype->type) - { - case FFI_TYPE_VOID: - case FFI_TYPE_STRUCT: - case FFI_TYPE_SINT64: - case FFI_TYPE_FLOAT: - case FFI_TYPE_DOUBLE: - case FFI_TYPE_LONGDOUBLE: - cif->flags = (unsigned) cif->rtype->type; - break; - - case FFI_TYPE_UINT64: -#ifdef _WIN64 - case FFI_TYPE_POINTER: -#endif - cif->flags = FFI_TYPE_SINT64; - break; - - default: - cif->flags = FFI_TYPE_INT; - break; - } - - return FFI_OK; -} - -#ifdef _WIN32 -extern int -ffi_call_x86(void (*)(char *, extended_cif *), - /*@out@*/ extended_cif *, - unsigned, unsigned, - /*@out@*/ unsigned *, - void (*fn)()); -#endif - -#ifdef _WIN64 -extern int -ffi_call_AMD64(void (*)(char *, extended_cif *), - /*@out@*/ extended_cif *, - unsigned, unsigned, - /*@out@*/ unsigned *, - void (*fn)()); -#endif - -int -ffi_call(/*@dependent@*/ ffi_cif *cif, - void (*fn)(), - /*@out@*/ void *rvalue, - /*@dependent@*/ void **avalue) -{ - extended_cif ecif; - - ecif.cif = cif; - ecif.avalue = avalue; - - /* If the return value is a struct and we don't have a return */ - /* value address then we need to make one */ - - if ((rvalue == NULL) && - (cif->rtype->type == FFI_TYPE_STRUCT)) - { - /*@-sysunrecog@*/ - ecif.rvalue = alloca(cif->rtype->size); - /*@=sysunrecog@*/ - } - else - ecif.rvalue = rvalue; - - - switch (cif->abi) - { -#if !defined(_WIN64) - case FFI_SYSV: - case FFI_STDCALL: - return ffi_call_x86(ffi_prep_args, &ecif, cif->bytes, - cif->flags, ecif.rvalue, fn); - break; -#else - case FFI_SYSV: - /*@-usedef@*/ - /* Function call needs at least 40 bytes stack size, on win64 AMD64 */ - return ffi_call_AMD64(ffi_prep_args, &ecif, cif->bytes ? cif->bytes : 40, - cif->flags, ecif.rvalue, fn); - /*@=usedef@*/ - break; -#endif - - default: - FFI_ASSERT(0); - break; - } - return -1; /* theller: Hrm. */ -} - - -/** private members **/ - -static void ffi_prep_incoming_args_SYSV (char *stack, void **ret, - void** args, ffi_cif* cif); -/* This function is jumped to by the trampoline */ - -#ifdef _WIN64 -void * -#else -static void __fastcall -#endif -ffi_closure_SYSV (ffi_closure *closure, int *argp) -{ - // this is our return value storage - long double res; - - // our various things... - ffi_cif *cif; - void **arg_area; - unsigned short rtype; - void *resp = (void*)&res; - void *args = &argp[1]; - - cif = closure->cif; - arg_area = (void**) alloca (cif->nargs * sizeof (void*)); - - /* this call will initialize ARG_AREA, such that each - * element in that array points to the corresponding - * value on the stack; and if the function returns - * a structure, it will re-set RESP to point to the - * structure return address. */ - - ffi_prep_incoming_args_SYSV(args, (void**)&resp, arg_area, cif); - - (closure->fun) (cif, resp, arg_area, closure->user_data); - - rtype = cif->flags; - -#if defined(_WIN32) && !defined(_WIN64) -#ifdef _MSC_VER - /* now, do a generic return based on the value of rtype */ - if (rtype == FFI_TYPE_INT) - { - _asm mov eax, resp ; - _asm mov eax, [eax] ; - } - else if (rtype == FFI_TYPE_FLOAT) - { - _asm mov eax, resp ; - _asm fld DWORD PTR [eax] ; -// asm ("flds (%0)" : : "r" (resp) : "st" ); - } - else if (rtype == FFI_TYPE_DOUBLE) - { - _asm mov eax, resp ; - _asm fld QWORD PTR [eax] ; -// asm ("fldl (%0)" : : "r" (resp) : "st", "st(1)" ); - } - else if (rtype == FFI_TYPE_LONGDOUBLE) - { -// asm ("fldt (%0)" : : "r" (resp) : "st", "st(1)" ); - } - else if (rtype == FFI_TYPE_SINT64) - { - _asm mov edx, resp ; - _asm mov eax, [edx] ; - _asm mov edx, [edx + 4] ; -// asm ("movl 0(%0),%%eax;" -// "movl 4(%0),%%edx" -// : : "r"(resp) -// : "eax", "edx"); - } -#else - /* now, do a generic return based on the value of rtype */ - if (rtype == FFI_TYPE_INT) - { - asm ("movl (%0),%%eax" : : "r" (resp) : "eax"); - } - else if (rtype == FFI_TYPE_FLOAT) - { - asm ("flds (%0)" : : "r" (resp) : "st" ); - } - else if (rtype == FFI_TYPE_DOUBLE) - { - asm ("fldl (%0)" : : "r" (resp) : "st", "st(1)" ); - } - else if (rtype == FFI_TYPE_LONGDOUBLE) - { - asm ("fldt (%0)" : : "r" (resp) : "st", "st(1)" ); - } - else if (rtype == FFI_TYPE_SINT64) - { - asm ("movl 0(%0),%%eax;" - "movl 4(%0),%%edx" - : : "r"(resp) - : "eax", "edx"); - } -#endif -#endif - -#ifdef _WIN64 - /* The result is returned in rax. This does the right thing for - result types except for floats; we have to 'mov xmm0, rax' in the - caller to correct this. - */ - return *(void **)resp; -#endif -} - -/*@-exportheader@*/ -static void -ffi_prep_incoming_args_SYSV(char *stack, void **rvalue, - void **avalue, ffi_cif *cif) -/*@=exportheader@*/ -{ - register unsigned int i; - register void **p_argv; - register char *argp; - register ffi_type **p_arg; - - argp = stack; - - if ( cif->rtype->type == FFI_TYPE_STRUCT ) { - *rvalue = *(void **) argp; - argp += 4; - } - - p_argv = avalue; - - for (i = cif->nargs, p_arg = cif->arg_types; (i != 0); i--, p_arg++) - { - size_t z; - - /* Align if necessary */ - if ((sizeof(char *) - 1) & (size_t) argp) { - argp = (char *) ALIGN(argp, sizeof(char*)); - } - - z = (*p_arg)->size; - - /* because we're little endian, this is what it turns into. */ - - *p_argv = (void*) argp; - - p_argv++; - argp += z; - } - - return; -} - -/* the cif must already be prep'ed */ -extern void ffi_closure_OUTER(); - -ffi_status -ffi_prep_closure (ffi_closure* closure, - ffi_cif* cif, - void (*fun)(ffi_cif*,void*,void**,void*), - void *user_data) -{ - short bytes; - char *tramp; -#ifdef _WIN64 - int mask; -#endif - FFI_ASSERT (cif->abi == FFI_SYSV); - - if (cif->abi == FFI_SYSV) - bytes = 0; -#if !defined(_WIN64) - else if (cif->abi == FFI_STDCALL) - bytes = cif->bytes; -#endif - else - return FFI_BAD_ABI; - - tramp = &closure->tramp[0]; - -#define BYTES(text) memcpy(tramp, text, sizeof(text)), tramp += sizeof(text)-1 -#define POINTER(x) *(void**)tramp = (void*)(x), tramp += sizeof(void*) -#define SHORT(x) *(short*)tramp = x, tramp += sizeof(short) -#define INT(x) *(int*)tramp = x, tramp += sizeof(int) - -#ifdef _WIN64 - if (cif->nargs >= 1 && - (cif->arg_types[0]->type == FFI_TYPE_FLOAT - || cif->arg_types[0]->type == FFI_TYPE_DOUBLE)) - mask |= 1; - if (cif->nargs >= 2 && - (cif->arg_types[1]->type == FFI_TYPE_FLOAT - || cif->arg_types[1]->type == FFI_TYPE_DOUBLE)) - mask |= 2; - if (cif->nargs >= 3 && - (cif->arg_types[2]->type == FFI_TYPE_FLOAT - || cif->arg_types[2]->type == FFI_TYPE_DOUBLE)) - mask |= 4; - if (cif->nargs >= 4 && - (cif->arg_types[3]->type == FFI_TYPE_FLOAT - || cif->arg_types[3]->type == FFI_TYPE_DOUBLE)) - mask |= 8; - - /* 41 BB ---- mov r11d,mask */ - BYTES("\x41\xBB"); INT(mask); - - /* 48 B8 -------- mov rax, closure */ - BYTES("\x48\xB8"); POINTER(closure); - - /* 49 BA -------- mov r10, ffi_closure_OUTER */ - BYTES("\x49\xBA"); POINTER(ffi_closure_OUTER); - - /* 41 FF E2 jmp r10 */ - BYTES("\x41\xFF\xE2"); - -#else - - /* mov ecx, closure */ - BYTES("\xb9"); POINTER(closure); - - /* mov edx, esp */ - BYTES("\x8b\xd4"); - - /* call ffi_closure_SYSV */ - BYTES("\xe8"); POINTER((char*)&ffi_closure_SYSV - (tramp + 4)); - - /* ret bytes */ - BYTES("\xc2"); - SHORT(bytes); - -#endif - - if (tramp - &closure->tramp[0] > FFI_TRAMPOLINE_SIZE) - Py_FatalError("FFI_TRAMPOLINE_SIZE too small in " __FILE__); - - closure->cif = cif; - closure->user_data = user_data; - closure->fun = fun; - - return FFI_OK; -} Modified: python/branches/py3k-jit/Modules/_ctypes/libffi_msvc/ffi.h ============================================================================== --- python/branches/py3k-jit/Modules/_ctypes/libffi_msvc/ffi.h (original) +++ python/branches/py3k-jit/Modules/_ctypes/libffi_msvc/ffi.h Thu May 6 23:49:27 2010 @@ -1,5 +1,5 @@ /* -----------------------------------------------------------------*-C-*- - libffi 2.00-beta - Copyright (c) 1996-2003 Red Hat, Inc. + libffi @VERSION@ - Copyright (c) 1996-2003, 2007, 2008 Red Hat, Inc. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the @@ -12,13 +12,14 @@ 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 CYGNUS SOLUTIONS 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. + 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. ----------------------------------------------------------------------- */ @@ -56,7 +57,7 @@ #endif /* Specify which architecture libffi is configured for. */ -//XXX #define X86 +/* #define @TARGET@ */ /* ---- System configuration information --------------------------------- */ @@ -64,6 +65,10 @@ #ifndef LIBFFI_ASM +#ifdef _MSC_VER +#define __attribute__(X) +#endif + #include #include @@ -79,12 +84,21 @@ # ifdef __GNUC__ # define FFI_LONG_LONG_MAX __LONG_LONG_MAX__ # endif -# ifdef _MSC_VER -# define FFI_LONG_LONG_MAX _I64_MAX -# endif # endif #endif +/* The closure code assumes that this works on pointers, i.e. a size_t */ +/* can hold a pointer. */ + +typedef struct _ffi_type +{ + size_t size; + unsigned short alignment; + unsigned short type; + struct _ffi_type **elements; +} ffi_type; + +#ifndef LIBFFI_HIDE_BASIC_TYPES #if SCHAR_MAX == 127 # define ffi_type_uchar ffi_type_uint8 # define ffi_type_schar ffi_type_sint8 @@ -115,26 +129,23 @@ #error "int size not supported" #endif -#define ffi_type_ulong ffi_type_uint64 -#define ffi_type_slong ffi_type_sint64 #if LONG_MAX == 2147483647 # if FFI_LONG_LONG_MAX != 9223372036854775807 - #error "no 64-bit data type supported" + #error "no 64-bit data type supported" # endif #elif LONG_MAX != 9223372036854775807 #error "long size not supported" #endif -/* The closure code assumes that this works on pointers, i.e. a size_t */ -/* can hold a pointer. */ - -typedef struct _ffi_type -{ - size_t size; - unsigned short alignment; - unsigned short type; - /*@null@*/ struct _ffi_type **elements; -} ffi_type; +#if LONG_MAX == 2147483647 +# define ffi_type_ulong ffi_type_uint32 +# define ffi_type_slong ffi_type_sint32 +#elif LONG_MAX == 9223372036854775807 +# define ffi_type_ulong ffi_type_uint64 +# define ffi_type_slong ffi_type_sint64 +#else + #error "long size not supported" +#endif /* These are defined in types.c */ extern ffi_type ffi_type_void; @@ -148,14 +159,19 @@ extern ffi_type ffi_type_sint64; extern ffi_type ffi_type_float; extern ffi_type ffi_type_double; -extern ffi_type ffi_type_longdouble; extern ffi_type ffi_type_pointer; +#if HAVE_LONG_DOUBLE +extern ffi_type ffi_type_longdouble; +#else +#define ffi_type_longdouble ffi_type_double +#endif +#endif /* LIBFFI_HIDE_BASIC_TYPES */ typedef enum { FFI_OK = 0, FFI_BAD_TYPEDEF, - FFI_BAD_ABI + FFI_BAD_ABI } ffi_status; typedef unsigned FFI_TYPE; @@ -163,8 +179,8 @@ typedef struct { ffi_abi abi; unsigned nargs; - /*@dependent@*/ ffi_type **arg_types; - /*@dependent@*/ ffi_type *rtype; + ffi_type **arg_types; + ffi_type *rtype; unsigned bytes; unsigned flags; #ifdef FFI_EXTRA_CIF_FIELDS @@ -174,10 +190,16 @@ /* ---- Definitions for the raw API -------------------------------------- */ -#ifdef _WIN64 -#define FFI_SIZEOF_ARG 8 -#else -#define FFI_SIZEOF_ARG 4 +#ifndef FFI_SIZEOF_ARG +# if LONG_MAX == 2147483647 +# define FFI_SIZEOF_ARG 4 +# elif LONG_MAX == 9223372036854775807 +# define FFI_SIZEOF_ARG 8 +# endif +#endif + +#ifndef FFI_SIZEOF_JAVA_RAW +# define FFI_SIZEOF_JAVA_RAW FFI_SIZEOF_ARG #endif typedef union { @@ -188,10 +210,25 @@ void* ptr; } ffi_raw; -void ffi_raw_call (/*@dependent@*/ ffi_cif *cif, - void (*fn)(), - /*@out@*/ void *rvalue, - /*@dependent@*/ ffi_raw *avalue); +#if FFI_SIZEOF_JAVA_RAW == 4 && FFI_SIZEOF_ARG == 8 +/* This is a special case for mips64/n32 ABI (and perhaps others) where + sizeof(void *) is 4 and FFI_SIZEOF_ARG is 8. */ +typedef union { + signed int sint; + unsigned int uint; + float flt; + char data[FFI_SIZEOF_JAVA_RAW]; + void* ptr; +} ffi_java_raw; +#else +typedef ffi_raw ffi_java_raw; +#endif + + +void ffi_raw_call (ffi_cif *cif, + void (*fn)(void), + void *rvalue, + ffi_raw *avalue); void ffi_ptrarray_to_raw (ffi_cif *cif, void **args, ffi_raw *raw); void ffi_raw_to_ptrarray (ffi_cif *cif, ffi_raw *raw, void **args); @@ -201,25 +238,35 @@ /* packing, even on 64-bit machines. I.e. on 64-bit machines */ /* longs and doubles are followed by an empty 64-bit word. */ -void ffi_java_raw_call (/*@dependent@*/ ffi_cif *cif, - void (*fn)(), - /*@out@*/ void *rvalue, - /*@dependent@*/ ffi_raw *avalue); +void ffi_java_raw_call (ffi_cif *cif, + void (*fn)(void), + void *rvalue, + ffi_java_raw *avalue); -void ffi_java_ptrarray_to_raw (ffi_cif *cif, void **args, ffi_raw *raw); -void ffi_java_raw_to_ptrarray (ffi_cif *cif, ffi_raw *raw, void **args); +void ffi_java_ptrarray_to_raw (ffi_cif *cif, void **args, ffi_java_raw *raw); +void ffi_java_raw_to_ptrarray (ffi_cif *cif, ffi_java_raw *raw, void **args); size_t ffi_java_raw_size (ffi_cif *cif); /* ---- Definitions for closures ----------------------------------------- */ #if FFI_CLOSURES +#ifdef _MSC_VER +__declspec(align(8)) +#endif typedef struct { char tramp[FFI_TRAMPOLINE_SIZE]; ffi_cif *cif; void (*fun)(ffi_cif*,void*,void**,void*); void *user_data; +#ifdef __GNUC__ +} ffi_closure __attribute__((aligned (8))); +#else } ffi_closure; +#endif + +void *ffi_closure_alloc (size_t size, void **code); +void ffi_closure_free (void *); ffi_status ffi_prep_closure (ffi_closure*, @@ -227,6 +274,13 @@ void (*fun)(ffi_cif*,void*,void**,void*), void *user_data); +ffi_status +ffi_prep_closure_loc (ffi_closure*, + ffi_cif *, + void (*fun)(ffi_cif*,void*,void**,void*), + void *user_data, + void*codeloc); + typedef struct { char tramp[FFI_TRAMPOLINE_SIZE]; @@ -248,6 +302,27 @@ } ffi_raw_closure; +typedef struct { + char tramp[FFI_TRAMPOLINE_SIZE]; + + ffi_cif *cif; + +#if !FFI_NATIVE_RAW_API + + /* if this is enabled, then a raw closure has the same layout + as a regular closure. We use this to install an intermediate + handler to do the transaltion, void** -> ffi_raw*. */ + + void (*translate_args)(ffi_cif*,void*,void**,void*); + void *this_closure; + +#endif + + void (*fun)(ffi_cif*,void*,ffi_java_raw*,void*); + void *user_data; + +} ffi_java_raw_closure; + ffi_status ffi_prep_raw_closure (ffi_raw_closure*, ffi_cif *cif, @@ -255,29 +330,42 @@ void *user_data); ffi_status -ffi_prep_java_raw_closure (ffi_raw_closure*, +ffi_prep_raw_closure_loc (ffi_raw_closure*, + ffi_cif *cif, + void (*fun)(ffi_cif*,void*,ffi_raw*,void*), + void *user_data, + void *codeloc); + +ffi_status +ffi_prep_java_raw_closure (ffi_java_raw_closure*, ffi_cif *cif, - void (*fun)(ffi_cif*,void*,ffi_raw*,void*), + void (*fun)(ffi_cif*,void*,ffi_java_raw*,void*), void *user_data); +ffi_status +ffi_prep_java_raw_closure_loc (ffi_java_raw_closure*, + ffi_cif *cif, + void (*fun)(ffi_cif*,void*,ffi_java_raw*,void*), + void *user_data, + void *codeloc); + #endif /* FFI_CLOSURES */ /* ---- Public interface definition -------------------------------------- */ -ffi_status ffi_prep_cif(/*@out@*/ /*@partial@*/ ffi_cif *cif, +ffi_status ffi_prep_cif(ffi_cif *cif, ffi_abi abi, - unsigned int nargs, - /*@dependent@*/ /*@out@*/ /*@partial@*/ ffi_type *rtype, - /*@dependent@*/ ffi_type **atypes); - -int -ffi_call(/*@dependent@*/ ffi_cif *cif, - void (*fn)(), - /*@out@*/ void *rvalue, - /*@dependent@*/ void **avalue); + unsigned int nargs, + ffi_type *rtype, + ffi_type **atypes); + +void ffi_call(ffi_cif *cif, + void (*fn)(void), + void *rvalue, + void **avalue); /* Useful for eliminating compiler warnings */ -#define FFI_FN(f) ((void (*)())f) +#define FFI_FN(f) ((void (*)(void))f) /* ---- Definitions shared with assembly code ---------------------------- */ @@ -288,7 +376,7 @@ #define FFI_TYPE_INT 1 #define FFI_TYPE_FLOAT 2 #define FFI_TYPE_DOUBLE 3 -#if 1 +#if HAVE_LONG_DOUBLE #define FFI_TYPE_LONGDOUBLE 4 #else #define FFI_TYPE_LONGDOUBLE FFI_TYPE_DOUBLE @@ -312,4 +400,3 @@ #endif #endif - Deleted: python/branches/py3k-jit/Modules/_ctypes/libffi_msvc/ffi_common.h ============================================================================== --- python/branches/py3k-jit/Modules/_ctypes/libffi_msvc/ffi_common.h Thu May 6 23:49:27 2010 +++ (empty file) @@ -1,77 +0,0 @@ -/* ----------------------------------------------------------------------- - ffi_common.h - Copyright (c) 1996 Red Hat, Inc. - - Common internal definitions and macros. Only necessary for building - libffi. - ----------------------------------------------------------------------- */ - -#ifndef FFI_COMMON_H -#define FFI_COMMON_H - -#ifdef __cplusplus -extern "C" { -#endif - -#include -#include - -/* Check for the existence of memcpy. */ -#if STDC_HEADERS -# include -#else -# ifndef HAVE_MEMCPY -# define memcpy(d, s, n) bcopy ((s), (d), (n)) -# endif -#endif - -#if defined(FFI_DEBUG) -#include -#endif - -#ifdef FFI_DEBUG -/*@exits@*/ void ffi_assert(/*@temp@*/ char *expr, /*@temp@*/ char *file, int line); -void ffi_stop_here(void); -void ffi_type_test(/*@temp@*/ /*@out@*/ ffi_type *a, /*@temp@*/ char *file, int line); - -#define FFI_ASSERT(x) ((x) ? (void)0 : ffi_assert(#x, __FILE__,__LINE__)) -#define FFI_ASSERT_AT(x, f, l) ((x) ? 0 : ffi_assert(#x, (f), (l))) -#define FFI_ASSERT_VALID_TYPE(x) ffi_type_test (x, __FILE__, __LINE__) -#else -#define FFI_ASSERT(x) -#define FFI_ASSERT_AT(x, f, l) -#define FFI_ASSERT_VALID_TYPE(x) -#endif - -#define ALIGN(v, a) (((((size_t) (v))-1) | ((a)-1))+1) - -/* Perform machine dependent cif processing */ -ffi_status ffi_prep_cif_machdep(ffi_cif *cif); - -/* Extended cif, used in callback from assembly routine */ -typedef struct -{ - /*@dependent@*/ ffi_cif *cif; - /*@dependent@*/ void *rvalue; - /*@dependent@*/ void **avalue; -} extended_cif; - -/* Terse sized type definitions. */ -typedef unsigned int UINT8 __attribute__((__mode__(__QI__))); -typedef signed int SINT8 __attribute__((__mode__(__QI__))); -typedef unsigned int UINT16 __attribute__((__mode__(__HI__))); -typedef signed int SINT16 __attribute__((__mode__(__HI__))); -typedef unsigned int UINT32 __attribute__((__mode__(__SI__))); -typedef signed int SINT32 __attribute__((__mode__(__SI__))); -typedef unsigned int UINT64 __attribute__((__mode__(__DI__))); -typedef signed int SINT64 __attribute__((__mode__(__DI__))); - -typedef float FLOAT32; - - -#ifdef __cplusplus -} -#endif - -#endif - - Modified: python/branches/py3k-jit/Modules/_ctypes/libffi_msvc/fficonfig.h ============================================================================== --- python/branches/py3k-jit/Modules/_ctypes/libffi_msvc/fficonfig.h (original) +++ python/branches/py3k-jit/Modules/_ctypes/libffi_msvc/fficonfig.h Thu May 6 23:49:27 2010 @@ -1,96 +1,186 @@ /* fficonfig.h. Originally created by configure, now hand_maintained for MSVC. */ -/* fficonfig.h. Generated automatically by configure. */ -/* fficonfig.h.in. Generated automatically from configure.in by autoheader. */ +/* fficonfig.h.in. Generated from configure.ac by autoheader. */ -/* Define this for MSVC, but not for mingw32! */ -#ifdef _MSC_VER -#define __attribute__(x) /* */ -#endif -#define alloca _alloca +/* Define if building universal (internal helper macro) */ +/* #undef AC_APPLE_UNIVERSAL_BUILD */ -/*----------------------------------------------------------------*/ +/* Define to one of `_getb67', `GETB67', `getb67' for Cray-2 and Cray-YMP + systems. This function is required for `alloca.c' support on those systems. + */ +/* #undef CRAY_STACKSEG_END */ -/* Define if using alloca.c. */ +/* Define to 1 if using `alloca.c'. */ /* #undef C_ALLOCA */ -/* Define to one of _getb67, GETB67, getb67 for Cray-2 and Cray-YMP systems. - This function is required for alloca.c support on those systems. */ -/* #undef CRAY_STACKSEG_END */ +/* Define to the flags needed for the .section .eh_frame directive. */ +/* #undef EH_FRAME_FLAGS */ -/* Define if you have alloca, as a function or macro. */ -#define HAVE_ALLOCA 1 +/* Define this if you want extra debugging. */ +/* #undef FFI_DEBUG */ -/* Define if you have and it should be used (not on Ultrix). */ -/* #define HAVE_ALLOCA_H 1 */ +/* Cannot use malloc on this target, so, we revert to alternative means */ +/* #undef FFI_MMAP_EXEC_WRIT */ -/* If using the C implementation of alloca, define if you know the - direction of stack growth for your system; otherwise it will be - automatically deduced at run-time. - STACK_DIRECTION > 0 => grows toward higher addresses - STACK_DIRECTION < 0 => grows toward lower addresses - STACK_DIRECTION = 0 => direction of growth unknown - */ -/* #undef STACK_DIRECTION */ +/* Define this is you do not want support for the raw API. */ +#define FFI_NO_RAW_API 1 -/* Define if you have the ANSI C header files. */ -#define STDC_HEADERS 1 +/* Define this is you do not want support for aggregate types. */ +/* #undef FFI_NO_STRUCTS */ -/* Define if you have the memcpy function. */ -#define HAVE_MEMCPY 1 +/* Define to 1 if you have `alloca', as a function or macro. */ +#define HAVE_ALLOCA 1 -/* Define if read-only mmap of a plain file works. */ -//#define HAVE_MMAP_FILE 1 +/* Define to 1 if you have and it should be used (not on Ultrix). + */ +/* #undef HAVE_ALLOCA_H */ -/* Define if mmap of /dev/zero works. */ -//#define HAVE_MMAP_DEV_ZERO 1 +/* Define if your assembler supports .cfi_* directives. */ +/* #undef HAVE_AS_CFI_PSEUDO_OP */ -/* Define if mmap with MAP_ANON(YMOUS) works. */ -//#define HAVE_MMAP_ANON 1 +/* Define if your assembler supports .register. */ +/* #undef HAVE_AS_REGISTER_PSEUDO_OP */ -/* The number of bytes in type double */ -#define SIZEOF_DOUBLE 8 +/* Define if your assembler and linker support unaligned PC relative relocs. + */ +/* #undef HAVE_AS_SPARC_UA_PCREL */ -/* The number of bytes in type long double */ -#define SIZEOF_LONG_DOUBLE 12 +/* Define if your assembler supports PC relative relocs. */ +/* #undef HAVE_AS_X86_PCREL */ + +/* Define to 1 if you have the header file. */ +/* #undef HAVE_DLFCN_H */ + +/* Define if __attribute__((visibility("hidden"))) is supported. */ +/* #undef HAVE_HIDDEN_VISIBILITY_ATTRIBUTE */ + +/* Define to 1 if you have the header file. */ +/* #undef HAVE_INTTYPES_H */ /* Define if you have the long double type and it is bigger than a double */ -#define HAVE_LONG_DOUBLE 1 +/* #undef HAVE_LONG_DOUBLE */ -/* whether byteorder is bigendian */ -/* #undef WORDS_BIGENDIAN */ +/* Define to 1 if you have the `memcpy' function. */ +#define HAVE_MEMCPY 1 -/* Define if the host machine stores words of multi-word integers in - big-endian order. */ -/* #undef HOST_WORDS_BIG_ENDIAN */ +/* Define to 1 if you have the header file. */ +/* #undef HAVE_MEMORY_H */ -/* 1234 = LIL_ENDIAN, 4321 = BIGENDIAN */ -#define BYTEORDER 1234 +/* Define to 1 if you have the `mmap' function. */ +/* #undef HAVE_MMAP */ -/* Define if your assembler and linker support unaligned PC relative relocs. */ -/* #undef HAVE_AS_SPARC_UA_PCREL */ +/* Define if mmap with MAP_ANON(YMOUS) works. */ +/* #undef HAVE_MMAP_ANON */ -/* Define if your assembler supports .register. */ -/* #undef HAVE_AS_REGISTER_PSEUDO_OP */ +/* Define if mmap of /dev/zero works. */ +/* #undef HAVE_MMAP_DEV_ZERO */ + +/* Define if read-only mmap of a plain file works. */ +/* #undef HAVE_MMAP_FILE */ /* Define if .eh_frame sections should be read-only. */ /* #undef HAVE_RO_EH_FRAME */ -/* Define to the flags needed for the .section .eh_frame directive. */ -/* #define EH_FRAME_FLAGS "aw" */ +/* Define to 1 if you have the header file. */ +#undef HAVE_STDINT_H -/* Define to the flags needed for the .section .eh_frame directive. */ -/* #define EH_FRAME_FLAGS "aw" */ +/* Define to 1 if you have the header file. */ +#undef HAVE_STDLIB_H -/* Define this if you want extra debugging. */ -/* #undef FFI_DEBUG */ +/* Define to 1 if you have the header file. */ +#undef HAVE_STRINGS_H -/* Define this is you do not want support for aggregate types. */ -/* #undef FFI_NO_STRUCTS */ +/* Define to 1 if you have the header file. */ +#undef HAVE_STRING_H -/* Define this is you do not want support for the raw API. */ -/* #undef FFI_NO_RAW_API */ +/* Define to 1 if you have the header file. */ +/* #undef HAVE_SYS_MMAN_H */ + +/* Define to 1 if you have the header file. */ +/* #undef HAVE_SYS_STAT_H */ + +/* Define to 1 if you have the header file. */ +/* #undef HAVE_SYS_TYPES_H */ + +/* Define to 1 if you have the header file. */ +/* #undef HAVE_UNISTD_H */ + +/* Define to the sub-directory in which libtool stores uninstalled libraries. + */ +/* #undef LT_OBJDIR */ + +/* Define to 1 if your C compiler doesn't accept -c and -o together. */ +/* #undef NO_MINUS_C_MINUS_O */ + +/* Name of package */ +/* #undef PACKAGE */ + +/* Define to the address where bug reports for this package should be sent. */ +/* #undef PACKAGE_BUGREPORT */ + +/* Define to the full name of this package. */ +/* #undef PACKAGE_NAME */ + +/* Define to the full name and version of this package. */ +/* #undef PACKAGE_STRING */ + +/* Define to the one symbol short name of this package. */ +/* #undef PACKAGE_TARNAME */ + +/* Define to the home page for this package. */ +/* #undef PACKAGE_URL */ + +/* Define to the version of this package. */ +/* #undef PACKAGE_VERSION */ -/* Define this if you are using Purify and want to suppress spurious messages. */ +/* The size of `double', as computed by sizeof. */ +#define SIZEOF_DOUBLE 8 + +/* The size of `long double', as computed by sizeof. */ +#undef SIZEOF_LONG_DOUBLE + +/* If using the C implementation of alloca, define if you know the + direction of stack growth for your system; otherwise it will be + automatically deduced at runtime. + STACK_DIRECTION > 0 => grows toward higher addresses + STACK_DIRECTION < 0 => grows toward lower addresses + STACK_DIRECTION = 0 => direction of growth unknown */ +/* #undef STACK_DIRECTION */ + +/* Define to 1 if you have the ANSI C header files. */ +#define STDC_HEADERS 1 + +/* Define this if you are using Purify and want to suppress spurious messages. + */ /* #undef USING_PURIFY */ +/* Version number of package */ +/* #undef VERSION */ + +/* Define WORDS_BIGENDIAN to 1 if your processor stores words with the most + significant byte first (like Motorola and SPARC, unlike Intel). */ +#if defined AC_APPLE_UNIVERSAL_BUILD +# if defined __BIG_ENDIAN__ +# define WORDS_BIGENDIAN 1 +# endif +#else +# ifndef WORDS_BIGENDIAN +# undef WORDS_BIGENDIAN +# endif +#endif + + +#ifdef HAVE_HIDDEN_VISIBILITY_ATTRIBUTE +#ifdef LIBFFI_ASM +#define FFI_HIDDEN(name) .hidden name +#else +#define FFI_HIDDEN __attribute__ ((visibility ("hidden"))) +#endif +#else +#ifdef LIBFFI_ASM +#define FFI_HIDDEN(name) +#else +#define FFI_HIDDEN +#endif +#endif + Deleted: python/branches/py3k-jit/Modules/_ctypes/libffi_msvc/ffitarget.h ============================================================================== --- python/branches/py3k-jit/Modules/_ctypes/libffi_msvc/ffitarget.h Thu May 6 23:49:27 2010 +++ (empty file) @@ -1,85 +0,0 @@ -/* -----------------------------------------------------------------*-C-*- - ffitarget.h - Copyright (c) 1996-2003 Red Hat, Inc. - Target configuration macros for x86 and x86-64. - - 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 CYGNUS SOLUTIONS 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. - - ----------------------------------------------------------------------- */ - -#ifndef LIBFFI_TARGET_H -#define LIBFFI_TARGET_H - -/* ---- System specific configurations ----------------------------------- */ - -#if defined (X86_64) && defined (__i386__) -#undef X86_64 -#define X86 -#endif - -/* ---- Generic type definitions ----------------------------------------- */ - -#ifndef LIBFFI_ASM -#ifndef _WIN64 -typedef unsigned long ffi_arg; -#else -typedef unsigned __int64 ffi_arg; -#endif -typedef signed long ffi_sarg; - -typedef enum ffi_abi { - FFI_FIRST_ABI = 0, - - /* ---- Intel x86 Win32 ---------- */ - FFI_SYSV, -#ifndef _WIN64 - FFI_STDCALL, -#endif - /* TODO: Add fastcall support for the sake of completeness */ - FFI_DEFAULT_ABI = FFI_SYSV, - - /* ---- Intel x86 and AMD x86-64 - */ -/* #if !defined(X86_WIN32) && (defined(__i386__) || defined(__x86_64__)) */ -/* FFI_SYSV, */ -/* FFI_UNIX64,*/ /* Unix variants all use the same ABI for x86-64 */ -/* #ifdef __i386__ */ -/* FFI_DEFAULT_ABI = FFI_SYSV, */ -/* #else */ -/* FFI_DEFAULT_ABI = FFI_UNIX64, */ -/* #endif */ -/* #endif */ - - FFI_LAST_ABI = FFI_DEFAULT_ABI + 1 -} ffi_abi; -#endif - -/* ---- Definitions for closures ----------------------------------------- */ - -#define FFI_CLOSURES 1 - -#ifdef _WIN64 -#define FFI_TRAMPOLINE_SIZE 29 -#define FFI_NATIVE_RAW_API 0 -#else -#define FFI_TRAMPOLINE_SIZE 15 -#define FFI_NATIVE_RAW_API 1 /* x86 has native raw api support */ -#endif - -#endif - Deleted: python/branches/py3k-jit/Modules/_ctypes/libffi_msvc/prep_cif.c ============================================================================== --- python/branches/py3k-jit/Modules/_ctypes/libffi_msvc/prep_cif.c Thu May 6 23:49:27 2010 +++ (empty file) @@ -1,175 +0,0 @@ -/* ----------------------------------------------------------------------- - prep_cif.c - Copyright (c) 1996, 1998 Red Hat, Inc. - - 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 CYGNUS SOLUTIONS 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. - ----------------------------------------------------------------------- */ - -#include -#include -#include - - -/* Round up to FFI_SIZEOF_ARG. */ - -#define STACK_ARG_SIZE(x) ALIGN(x, FFI_SIZEOF_ARG) - -/* Perform machine independent initialization of aggregate type - specifications. */ - -static ffi_status initialize_aggregate(/*@out@*/ ffi_type *arg) -{ - ffi_type **ptr; - - FFI_ASSERT(arg != NULL); - - /*@-usedef@*/ - - FFI_ASSERT(arg->elements != NULL); - FFI_ASSERT(arg->size == 0); - FFI_ASSERT(arg->alignment == 0); - - ptr = &(arg->elements[0]); - - while ((*ptr) != NULL) - { - if (((*ptr)->size == 0) && (initialize_aggregate((*ptr)) != FFI_OK)) - return FFI_BAD_TYPEDEF; - - /* Perform a sanity check on the argument type */ - FFI_ASSERT_VALID_TYPE(*ptr); - - arg->size = ALIGN(arg->size, (*ptr)->alignment); - arg->size += (*ptr)->size; - - arg->alignment = (arg->alignment > (*ptr)->alignment) ? - arg->alignment : (*ptr)->alignment; - - ptr++; - } - - /* Structure size includes tail padding. This is important for - structures that fit in one register on ABIs like the PowerPC64 - Linux ABI that right justify small structs in a register. - It's also needed for nested structure layout, for example - struct A { long a; char b; }; struct B { struct A x; char y; }; - should find y at an offset of 2*sizeof(long) and result in a - total size of 3*sizeof(long). */ - arg->size = ALIGN (arg->size, arg->alignment); - - if (arg->size == 0) - return FFI_BAD_TYPEDEF; - else - return FFI_OK; - - /*@=usedef@*/ -} - -/* Perform machine independent ffi_cif preparation, then call - machine dependent routine. */ - -ffi_status ffi_prep_cif(/*@out@*/ /*@partial@*/ ffi_cif *cif, - ffi_abi abi, unsigned int nargs, - /*@dependent@*/ /*@out@*/ /*@partial@*/ ffi_type *rtype, - /*@dependent@*/ ffi_type **atypes) -{ - unsigned bytes = 0; - unsigned int i; - ffi_type **ptr; - - FFI_ASSERT(cif != NULL); - FFI_ASSERT((abi > FFI_FIRST_ABI) && (abi <= FFI_DEFAULT_ABI)); - - cif->abi = abi; - cif->arg_types = atypes; - cif->nargs = nargs; - cif->rtype = rtype; - - cif->flags = 0; - - /* Initialize the return type if necessary */ - /*@-usedef@*/ - if ((cif->rtype->size == 0) && (initialize_aggregate(cif->rtype) != FFI_OK)) - return FFI_BAD_TYPEDEF; - /*@=usedef@*/ - - /* Perform a sanity check on the return type */ - FFI_ASSERT_VALID_TYPE(cif->rtype); - - /* x86-64 and s390 stack space allocation is handled in prep_machdep. */ -#if !defined M68K && !defined __x86_64__ && !defined S390 - /* Make space for the return structure pointer */ - if (cif->rtype->type == FFI_TYPE_STRUCT - /* MSVC returns small structures in registers. But we have a different - workaround: pretend int32 or int64 return type, and converting to - structure afterwards. */ -#ifdef SPARC - && (cif->abi != FFI_V9 || cif->rtype->size > 32) -#endif - ) - bytes = STACK_ARG_SIZE(sizeof(void*)); -#endif - - for (ptr = cif->arg_types, i = cif->nargs; i > 0; i--, ptr++) - { - - /* Initialize any uninitialized aggregate type definitions */ - if (((*ptr)->size == 0) && (initialize_aggregate((*ptr)) != FFI_OK)) - return FFI_BAD_TYPEDEF; - - /* Perform a sanity check on the argument type, do this - check after the initialization. */ - FFI_ASSERT_VALID_TYPE(*ptr); - -#if !defined __x86_64__ && !defined S390 -#ifdef SPARC - if (((*ptr)->type == FFI_TYPE_STRUCT - && ((*ptr)->size > 16 || cif->abi != FFI_V9)) - || ((*ptr)->type == FFI_TYPE_LONGDOUBLE - && cif->abi != FFI_V9)) - bytes += sizeof(void*); - else -#endif - { -#if !defined(_MSC_VER) && !defined(__MINGW32__) - /* Don't know if this is a libffi bug or not. At least on - Windows with MSVC, function call parameters are *not* - aligned in the same way as structure fields are, they are - only aligned in integer boundaries. - - This doesn't do any harm for cdecl functions and closures, - since the caller cleans up the stack, but it is wrong for - stdcall functions where the callee cleans. - */ - - /* Add any padding if necessary */ - if (((*ptr)->alignment - 1) & bytes) - bytes = ALIGN(bytes, (*ptr)->alignment); - -#endif - bytes += (unsigned)STACK_ARG_SIZE((*ptr)->size); - } -#endif - } - - cif->bytes = bytes; - - /* Perform machine dependent cif processing */ - return ffi_prep_cif_machdep(cif); -} Deleted: python/branches/py3k-jit/Modules/_ctypes/libffi_msvc/types.c ============================================================================== --- python/branches/py3k-jit/Modules/_ctypes/libffi_msvc/types.c Thu May 6 23:49:27 2010 +++ (empty file) @@ -1,104 +0,0 @@ -/* ----------------------------------------------------------------------- - types.c - Copyright (c) 1996, 1998 Red Hat, Inc. - - Predefined ffi_types needed by libffi. - - 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 CYGNUS SOLUTIONS 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. - ----------------------------------------------------------------------- */ - -#include -#include - -/* Type definitions */ - -#define FFI_INTEGRAL_TYPEDEF(n, s, a, t) ffi_type ffi_type_##n = { s, a, t, NULL } -#define FFI_AGGREGATE_TYPEDEF(n, e) ffi_type ffi_type_##n = { 0, 0, FFI_TYPE_STRUCT, e } - -/* Size and alignment are fake here. They must not be 0. */ -FFI_INTEGRAL_TYPEDEF(void, 1, 1, FFI_TYPE_VOID); - -FFI_INTEGRAL_TYPEDEF(uint8, 1, 1, FFI_TYPE_UINT8); -FFI_INTEGRAL_TYPEDEF(sint8, 1, 1, FFI_TYPE_SINT8); -FFI_INTEGRAL_TYPEDEF(uint16, 2, 2, FFI_TYPE_UINT16); -FFI_INTEGRAL_TYPEDEF(sint16, 2, 2, FFI_TYPE_SINT16); -FFI_INTEGRAL_TYPEDEF(uint32, 4, 4, FFI_TYPE_UINT32); -FFI_INTEGRAL_TYPEDEF(sint32, 4, 4, FFI_TYPE_SINT32); -FFI_INTEGRAL_TYPEDEF(float, 4, 4, FFI_TYPE_FLOAT); - -#if defined ALPHA || defined SPARC64 || defined X86_64 || defined S390X \ - || defined IA64 - -FFI_INTEGRAL_TYPEDEF(pointer, 8, 8, FFI_TYPE_POINTER); - -#else - -FFI_INTEGRAL_TYPEDEF(pointer, 4, 4, FFI_TYPE_POINTER); - -#endif - -#if defined X86 || defined X86_WIN32 || defined ARM || defined M68K - -FFI_INTEGRAL_TYPEDEF(uint64, 8, 4, FFI_TYPE_UINT64); -FFI_INTEGRAL_TYPEDEF(sint64, 8, 4, FFI_TYPE_SINT64); - -#elif defined SH - -FFI_INTEGRAL_TYPEDEF(uint64, 8, 4, FFI_TYPE_UINT64); -FFI_INTEGRAL_TYPEDEF(sint64, 8, 4, FFI_TYPE_SINT64); - -#else - -FFI_INTEGRAL_TYPEDEF(uint64, 8, 8, FFI_TYPE_UINT64); -FFI_INTEGRAL_TYPEDEF(sint64, 8, 8, FFI_TYPE_SINT64); - -#endif - - -#if defined X86 || defined X86_WIN32 || defined M68K - -FFI_INTEGRAL_TYPEDEF(double, 8, 4, FFI_TYPE_DOUBLE); -FFI_INTEGRAL_TYPEDEF(longdouble, 12, 4, FFI_TYPE_LONGDOUBLE); - -#elif defined ARM || defined SH || defined POWERPC_AIX || defined POWERPC_DARWIN - -FFI_INTEGRAL_TYPEDEF(double, 8, 4, FFI_TYPE_DOUBLE); -FFI_INTEGRAL_TYPEDEF(longdouble, 8, 4, FFI_TYPE_LONGDOUBLE); - -#elif defined SPARC - -FFI_INTEGRAL_TYPEDEF(double, 8, 8, FFI_TYPE_DOUBLE); -#ifdef SPARC64 -FFI_INTEGRAL_TYPEDEF(longdouble, 16, 16, FFI_TYPE_LONGDOUBLE); -#else -FFI_INTEGRAL_TYPEDEF(longdouble, 16, 8, FFI_TYPE_LONGDOUBLE); -#endif - -#elif defined X86_64 - -FFI_INTEGRAL_TYPEDEF(double, 8, 8, FFI_TYPE_DOUBLE); -FFI_INTEGRAL_TYPEDEF(longdouble, 16, 16, FFI_TYPE_LONGDOUBLE); - -#else - -FFI_INTEGRAL_TYPEDEF(double, 8, 8, FFI_TYPE_DOUBLE); -FFI_INTEGRAL_TYPEDEF(longdouble, 8, 8, FFI_TYPE_LONGDOUBLE); - -#endif - Deleted: python/branches/py3k-jit/Modules/_ctypes/libffi_msvc/win32.c ============================================================================== --- python/branches/py3k-jit/Modules/_ctypes/libffi_msvc/win32.c Thu May 6 23:49:27 2010 +++ (empty file) @@ -1,162 +0,0 @@ -/* ----------------------------------------------------------------------- - win32.S - Copyright (c) 1996, 1998, 2001, 2002 Red Hat, Inc. - Copyright (c) 2001 John Beniton - Copyright (c) 2002 Ranjit Mathew - - - X86 Foreign Function Interface - - 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 CYGNUS SOLUTIONS 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. - ----------------------------------------------------------------------- */ - -/* theller: almost verbatim translation from gas syntax to MSVC inline - assembler code. */ - -/* theller: ffi_call_x86 now returns an integer - the difference of the stack - pointer before and after the function call. If everything is ok, zero is - returned. If stdcall functions are passed the wrong number of arguments, - the difference will be nonzero. */ - -#include -#include - -__declspec(naked) int -ffi_call_x86(void (* prepfunc)(char *, extended_cif *), /* 8 */ - extended_cif *ecif, /* 12 */ - unsigned bytes, /* 16 */ - unsigned flags, /* 20 */ - unsigned *rvalue, /* 24 */ - void (*fn)()) /* 28 */ -{ - _asm { - push ebp - mov ebp, esp - - push esi // NEW: this register must be preserved across function calls -// XXX SAVE ESP NOW! - mov esi, esp // save stack pointer before the call - -// Make room for all of the new args. - mov ecx, [ebp+16] - sub esp, ecx // sub esp, bytes - - mov eax, esp - -// Place all of the ffi_prep_args in position - push [ebp + 12] // ecif - push eax - call [ebp + 8] // prepfunc - -// Return stack to previous state and call the function - add esp, 8 -// FIXME: Align the stack to a 128-bit boundary to avoid -// potential performance hits. - call [ebp + 28] - -// Load ecif->cif->abi - mov ecx, [ebp + 12] - mov ecx, [ecx]ecif.cif - mov ecx, [ecx]ecif.cif.abi - - cmp ecx, FFI_STDCALL - je noclean -// STDCALL: Remove the space we pushed for the args - mov ecx, [ebp + 16] - add esp, ecx -// CDECL: Caller has already cleaned the stack -noclean: -// Check that esp has the same value as before! - sub esi, esp - -// Load %ecx with the return type code - mov ecx, [ebp + 20] - -// If the return value pointer is NULL, assume no return value. -/* - Intel asm is weird. We have to explicitely specify 'DWORD PTR' in the nexr instruction, - otherwise only one BYTE will be compared (instead of a DWORD)! - */ - cmp DWORD PTR [ebp + 24], 0 - jne sc_retint - -// Even if there is no space for the return value, we are -// obliged to handle floating-point values. - cmp ecx, FFI_TYPE_FLOAT - jne sc_noretval -// fstp %st(0) - fstp st(0) - - jmp sc_epilogue - -sc_retint: - cmp ecx, FFI_TYPE_INT - jne sc_retfloat -// # Load %ecx with the pointer to storage for the return value - mov ecx, [ebp + 24] - mov [ecx + 0], eax - jmp sc_epilogue - -sc_retfloat: - cmp ecx, FFI_TYPE_FLOAT - jne sc_retdouble -// Load %ecx with the pointer to storage for the return value - mov ecx, [ebp+24] -// fstps (%ecx) - fstp DWORD PTR [ecx] - jmp sc_epilogue - -sc_retdouble: - cmp ecx, FFI_TYPE_DOUBLE - jne sc_retlongdouble -// movl 24(%ebp),%ecx - mov ecx, [ebp+24] - fstp QWORD PTR [ecx] - jmp sc_epilogue - - jmp sc_retlongdouble // avoid warning about unused label -sc_retlongdouble: - cmp ecx, FFI_TYPE_LONGDOUBLE - jne sc_retint64 -// Load %ecx with the pointer to storage for the return value - mov ecx, [ebp+24] -// fstpt (%ecx) - fstp QWORD PTR [ecx] /* XXX ??? */ - jmp sc_epilogue - -sc_retint64: - cmp ecx, FFI_TYPE_SINT64 - jne sc_retstruct -// Load %ecx with the pointer to storage for the return value - mov ecx, [ebp+24] - mov [ecx+0], eax - mov [ecx+4], edx - -sc_retstruct: -// Nothing to do! - -sc_noretval: -sc_epilogue: - mov eax, esi - pop esi // NEW restore: must be preserved across function calls - mov esp, ebp - pop ebp - ret - } -} Deleted: python/branches/py3k-jit/Modules/_ctypes/libffi_msvc/win64.asm ============================================================================== --- python/branches/py3k-jit/Modules/_ctypes/libffi_msvc/win64.asm Thu May 6 23:49:27 2010 +++ (empty file) @@ -1,156 +0,0 @@ -PUBLIC ffi_call_AMD64 - -EXTRN __chkstk:NEAR -EXTRN ffi_closure_SYSV:NEAR - -_TEXT SEGMENT - -;;; ffi_closure_OUTER will be called with these registers set: -;;; rax points to 'closure' -;;; r11 contains a bit mask that specifies which of the -;;; first four parameters are float or double -;;; -;;; It must move the parameters passed in registers to their stack location, -;;; call ffi_closure_SYSV for the actual work, then return the result. -;;; -ffi_closure_OUTER PROC FRAME - ;; save actual arguments to their stack space. - test r11, 1 - jne first_is_float - mov QWORD PTR [rsp+8], rcx - jmp second -first_is_float: - movlpd QWORD PTR [rsp+8], xmm0 - -second: - test r11, 2 - jne second_is_float - mov QWORD PTR [rsp+16], rdx - jmp third -second_is_float: - movlpd QWORD PTR [rsp+16], xmm1 - -third: - test r11, 4 - jne third_is_float - mov QWORD PTR [rsp+24], r8 - jmp forth -third_is_float: - movlpd QWORD PTR [rsp+24], xmm2 - -forth: - test r11, 8 - jne forth_is_float - mov QWORD PTR [rsp+32], r9 - jmp done -forth_is_float: - movlpd QWORD PTR [rsp+32], xmm3 - -done: -.ALLOCSTACK 40 - sub rsp, 40 -.ENDPROLOG - mov rcx, rax ; context is first parameter - mov rdx, rsp ; stack is second parameter - add rdx, 40 ; correct our own area - mov rax, ffi_closure_SYSV - call rax ; call the real closure function - ;; Here, code is missing that handles float return values - add rsp, 40 - movd xmm0, rax ; In case the closure returned a float. - ret 0 -ffi_closure_OUTER ENDP - - -;;; ffi_call_AMD64 - -stack$ = 0 -prepfunc$ = 32 -ecif$ = 40 -bytes$ = 48 -flags$ = 56 -rvalue$ = 64 -fn$ = 72 - -ffi_call_AMD64 PROC FRAME - - mov QWORD PTR [rsp+32], r9 - mov QWORD PTR [rsp+24], r8 - mov QWORD PTR [rsp+16], rdx - mov QWORD PTR [rsp+8], rcx -.PUSHREG rbp - push rbp -.ALLOCSTACK 48 - sub rsp, 48 ; 00000030H -.SETFRAME rbp, 32 - lea rbp, QWORD PTR [rsp+32] -.ENDPROLOG - - mov eax, DWORD PTR bytes$[rbp] - add rax, 15 - and rax, -16 - call __chkstk - sub rsp, rax - lea rax, QWORD PTR [rsp+32] - mov QWORD PTR stack$[rbp], rax - - mov rdx, QWORD PTR ecif$[rbp] - mov rcx, QWORD PTR stack$[rbp] - call QWORD PTR prepfunc$[rbp] - - mov rsp, QWORD PTR stack$[rbp] - - movlpd xmm3, QWORD PTR [rsp+24] - movd r9, xmm3 - - movlpd xmm2, QWORD PTR [rsp+16] - movd r8, xmm2 - - movlpd xmm1, QWORD PTR [rsp+8] - movd rdx, xmm1 - - movlpd xmm0, QWORD PTR [rsp] - movd rcx, xmm0 - - call QWORD PTR fn$[rbp] -ret_int$: - cmp DWORD PTR flags$[rbp], 1 ; FFI_TYPE_INT - jne ret_float$ - - mov rcx, QWORD PTR rvalue$[rbp] - mov DWORD PTR [rcx], eax - jmp SHORT ret_nothing$ - -ret_float$: - cmp DWORD PTR flags$[rbp], 2 ; FFI_TYPE_FLOAT - jne SHORT ret_double$ - - mov rax, QWORD PTR rvalue$[rbp] - movlpd QWORD PTR [rax], xmm0 - jmp SHORT ret_nothing$ - -ret_double$: - cmp DWORD PTR flags$[rbp], 3 ; FFI_TYPE_DOUBLE - jne SHORT ret_int64$ - - mov rax, QWORD PTR rvalue$[rbp] - movlpd QWORD PTR [rax], xmm0 - jmp SHORT ret_nothing$ - -ret_int64$: - cmp DWORD PTR flags$[rbp], 12 ; FFI_TYPE_SINT64 - jne ret_nothing$ - - mov rcx, QWORD PTR rvalue$[rbp] - mov QWORD PTR [rcx], rax - jmp SHORT ret_nothing$ - -ret_nothing$: - xor eax, eax - - lea rsp, QWORD PTR [rbp+16] - pop rbp - ret 0 -ffi_call_AMD64 ENDP -_TEXT ENDS -END Modified: python/branches/py3k-jit/Modules/_io/fileio.c ============================================================================== --- python/branches/py3k-jit/Modules/_io/fileio.c (original) +++ python/branches/py3k-jit/Modules/_io/fileio.c Thu May 6 23:49:27 2010 @@ -49,14 +49,14 @@ #endif typedef struct { - PyObject_HEAD - int fd; - unsigned int readable : 1; - unsigned int writable : 1; - signed int seekable : 2; /* -1 means unknown */ - unsigned int closefd : 1; - PyObject *weakreflist; - PyObject *dict; + PyObject_HEAD + int fd; + unsigned int readable : 1; + unsigned int writable : 1; + signed int seekable : 2; /* -1 means unknown */ + unsigned int closefd : 1; + PyObject *weakreflist; + PyObject *dict; } fileio; PyTypeObject PyFileIO_Type; @@ -66,7 +66,7 @@ int _PyFileIO_closed(PyObject *self) { - return ((fileio *)self)->fd < 0; + return ((fileio *)self)->fd < 0; } static PyObject * @@ -78,64 +78,64 @@ static int internal_close(fileio *self) { - int err = 0; - int save_errno = 0; - if (self->fd >= 0) { - int fd = self->fd; - self->fd = -1; - /* fd is accessible and someone else may have closed it */ - if (_PyVerify_fd(fd)) { - Py_BEGIN_ALLOW_THREADS - err = close(fd); - if (err < 0) - save_errno = errno; - Py_END_ALLOW_THREADS - } else { - save_errno = errno; - err = -1; - } - } - if (err < 0) { - errno = save_errno; - PyErr_SetFromErrno(PyExc_IOError); - return -1; - } - return 0; + int err = 0; + int save_errno = 0; + if (self->fd >= 0) { + int fd = self->fd; + self->fd = -1; + /* fd is accessible and someone else may have closed it */ + if (_PyVerify_fd(fd)) { + Py_BEGIN_ALLOW_THREADS + err = close(fd); + if (err < 0) + save_errno = errno; + Py_END_ALLOW_THREADS + } else { + save_errno = errno; + err = -1; + } + } + if (err < 0) { + errno = save_errno; + PyErr_SetFromErrno(PyExc_IOError); + return -1; + } + return 0; } static PyObject * fileio_close(fileio *self) { - if (!self->closefd) { - self->fd = -1; - Py_RETURN_NONE; - } - errno = internal_close(self); - if (errno < 0) - return NULL; + if (!self->closefd) { + self->fd = -1; + Py_RETURN_NONE; + } + errno = internal_close(self); + if (errno < 0) + return NULL; - return PyObject_CallMethod((PyObject*)&PyRawIOBase_Type, - "close", "O", self); + return PyObject_CallMethod((PyObject*)&PyRawIOBase_Type, + "close", "O", self); } static PyObject * fileio_new(PyTypeObject *type, PyObject *args, PyObject *kwds) { - fileio *self; + fileio *self; - assert(type != NULL && type->tp_alloc != NULL); + assert(type != NULL && type->tp_alloc != NULL); - self = (fileio *) type->tp_alloc(type, 0); - if (self != NULL) { - self->fd = -1; - self->readable = 0; - self->writable = 0; - self->seekable = -1; - self->closefd = 1; - self->weakreflist = NULL; - } + self = (fileio *) type->tp_alloc(type, 0); + if (self != NULL) { + self->fd = -1; + self->readable = 0; + self->writable = 0; + self->seekable = -1; + self->closefd = 1; + self->weakreflist = NULL; + } - return (PyObject *) self; + return (PyObject *) self; } /* On Unix, open will succeed for directories. @@ -146,535 +146,535 @@ dircheck(fileio* self, const char *name) { #if defined(HAVE_FSTAT) && defined(S_IFDIR) && defined(EISDIR) - struct stat buf; - if (self->fd < 0) - return 0; - if (fstat(self->fd, &buf) == 0 && S_ISDIR(buf.st_mode)) { - char *msg = strerror(EISDIR); - PyObject *exc; - if (internal_close(self)) - return -1; - - exc = PyObject_CallFunction(PyExc_IOError, "(iss)", - EISDIR, msg, name); - PyErr_SetObject(PyExc_IOError, exc); - Py_XDECREF(exc); - return -1; - } + struct stat buf; + if (self->fd < 0) + return 0; + if (fstat(self->fd, &buf) == 0 && S_ISDIR(buf.st_mode)) { + char *msg = strerror(EISDIR); + PyObject *exc; + if (internal_close(self)) + return -1; + + exc = PyObject_CallFunction(PyExc_IOError, "(iss)", + EISDIR, msg, name); + PyErr_SetObject(PyExc_IOError, exc); + Py_XDECREF(exc); + return -1; + } #endif - return 0; + return 0; } static int check_fd(int fd) { #if defined(HAVE_FSTAT) - struct stat buf; - if (!_PyVerify_fd(fd) || (fstat(fd, &buf) < 0 && errno == EBADF)) { - PyObject *exc; - char *msg = strerror(EBADF); - exc = PyObject_CallFunction(PyExc_OSError, "(is)", - EBADF, msg); - PyErr_SetObject(PyExc_OSError, exc); - Py_XDECREF(exc); - return -1; - } + struct stat buf; + if (!_PyVerify_fd(fd) || (fstat(fd, &buf) < 0 && errno == EBADF)) { + PyObject *exc; + char *msg = strerror(EBADF); + exc = PyObject_CallFunction(PyExc_OSError, "(is)", + EBADF, msg); + PyErr_SetObject(PyExc_OSError, exc); + Py_XDECREF(exc); + return -1; + } #endif - return 0; + return 0; } static int fileio_init(PyObject *oself, PyObject *args, PyObject *kwds) { - fileio *self = (fileio *) oself; - static char *kwlist[] = {"file", "mode", "closefd", NULL}; - const char *name = NULL; - PyObject *nameobj, *stringobj = NULL; - char *mode = "r"; - char *s; + fileio *self = (fileio *) oself; + static char *kwlist[] = {"file", "mode", "closefd", NULL}; + const char *name = NULL; + PyObject *nameobj, *stringobj = NULL; + char *mode = "r"; + char *s; #ifdef MS_WINDOWS - Py_UNICODE *widename = NULL; + Py_UNICODE *widename = NULL; #endif - int ret = 0; - int rwa = 0, plus = 0, append = 0; - int flags = 0; - int fd = -1; - int closefd = 1; - - assert(PyFileIO_Check(oself)); - if (self->fd >= 0) { - /* Have to close the existing file first. */ - if (internal_close(self) < 0) - return -1; - } - - if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|si:fileio", - kwlist, &nameobj, &mode, &closefd)) - return -1; - - if (PyFloat_Check(nameobj)) { - PyErr_SetString(PyExc_TypeError, - "integer argument expected, got float"); - return -1; - } - - fd = PyLong_AsLong(nameobj); - if (fd < 0) { - if (!PyErr_Occurred()) { - PyErr_SetString(PyExc_ValueError, - "Negative filedescriptor"); - return -1; - } - PyErr_Clear(); - } + int ret = 0; + int rwa = 0, plus = 0, append = 0; + int flags = 0; + int fd = -1; + int closefd = 1; + + assert(PyFileIO_Check(oself)); + if (self->fd >= 0) { + /* Have to close the existing file first. */ + if (internal_close(self) < 0) + return -1; + } + + if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|si:fileio", + kwlist, &nameobj, &mode, &closefd)) + return -1; + + if (PyFloat_Check(nameobj)) { + PyErr_SetString(PyExc_TypeError, + "integer argument expected, got float"); + return -1; + } + + fd = PyLong_AsLong(nameobj); + if (fd < 0) { + if (!PyErr_Occurred()) { + PyErr_SetString(PyExc_ValueError, + "Negative filedescriptor"); + return -1; + } + PyErr_Clear(); + } #ifdef MS_WINDOWS - if (PyUnicode_Check(nameobj)) - widename = PyUnicode_AS_UNICODE(nameobj); - if (widename == NULL) + if (PyUnicode_Check(nameobj)) + widename = PyUnicode_AS_UNICODE(nameobj); + if (widename == NULL) #endif - if (fd < 0) - { - if (PyBytes_Check(nameobj) || PyByteArray_Check(nameobj)) { - Py_ssize_t namelen; - if (PyObject_AsCharBuffer(nameobj, &name, &namelen) < 0) - return -1; - } - else { - PyObject *u = PyUnicode_FromObject(nameobj); - - if (u == NULL) - return -1; - - stringobj = PyUnicode_AsEncodedString( - u, Py_FileSystemDefaultEncoding, "surrogateescape"); - Py_DECREF(u); - if (stringobj == NULL) - return -1; - if (!PyBytes_Check(stringobj)) { - PyErr_SetString(PyExc_TypeError, - "encoder failed to return bytes"); - goto error; - } - name = PyBytes_AS_STRING(stringobj); - } - } - - s = mode; - while (*s) { - switch (*s++) { - case 'r': - if (rwa) { - bad_mode: - PyErr_SetString(PyExc_ValueError, - "Must have exactly one of read/write/append mode"); - goto error; - } - rwa = 1; - self->readable = 1; - break; - case 'w': - if (rwa) - goto bad_mode; - rwa = 1; - self->writable = 1; - flags |= O_CREAT | O_TRUNC; - break; - case 'a': - if (rwa) - goto bad_mode; - rwa = 1; - self->writable = 1; - flags |= O_CREAT; - append = 1; - break; - case 'b': - break; - case '+': - if (plus) - goto bad_mode; - self->readable = self->writable = 1; - plus = 1; - break; - default: - PyErr_Format(PyExc_ValueError, - "invalid mode: %.200s", mode); - goto error; - } - } - - if (!rwa) - goto bad_mode; - - if (self->readable && self->writable) - flags |= O_RDWR; - else if (self->readable) - flags |= O_RDONLY; - else - flags |= O_WRONLY; + if (fd < 0) + { + if (PyBytes_Check(nameobj) || PyByteArray_Check(nameobj)) { + Py_ssize_t namelen; + if (PyObject_AsCharBuffer(nameobj, &name, &namelen) < 0) + return -1; + } + else { + PyObject *u = PyUnicode_FromObject(nameobj); + + if (u == NULL) + return -1; + + stringobj = PyUnicode_AsEncodedString( + u, Py_FileSystemDefaultEncoding, "surrogateescape"); + Py_DECREF(u); + if (stringobj == NULL) + return -1; + if (!PyBytes_Check(stringobj)) { + PyErr_SetString(PyExc_TypeError, + "encoder failed to return bytes"); + goto error; + } + name = PyBytes_AS_STRING(stringobj); + } + } + + s = mode; + while (*s) { + switch (*s++) { + case 'r': + if (rwa) { + bad_mode: + PyErr_SetString(PyExc_ValueError, + "Must have exactly one of read/write/append mode"); + goto error; + } + rwa = 1; + self->readable = 1; + break; + case 'w': + if (rwa) + goto bad_mode; + rwa = 1; + self->writable = 1; + flags |= O_CREAT | O_TRUNC; + break; + case 'a': + if (rwa) + goto bad_mode; + rwa = 1; + self->writable = 1; + flags |= O_CREAT; + append = 1; + break; + case 'b': + break; + case '+': + if (plus) + goto bad_mode; + self->readable = self->writable = 1; + plus = 1; + break; + default: + PyErr_Format(PyExc_ValueError, + "invalid mode: %.200s", mode); + goto error; + } + } + + if (!rwa) + goto bad_mode; + + if (self->readable && self->writable) + flags |= O_RDWR; + else if (self->readable) + flags |= O_RDONLY; + else + flags |= O_WRONLY; #ifdef O_BINARY - flags |= O_BINARY; + flags |= O_BINARY; #endif #ifdef O_APPEND - if (append) - flags |= O_APPEND; + if (append) + flags |= O_APPEND; #endif - if (fd >= 0) { - if (check_fd(fd)) - goto error; - self->fd = fd; - self->closefd = closefd; - } - else { - self->closefd = 1; - if (!closefd) { - PyErr_SetString(PyExc_ValueError, - "Cannot use closefd=False with file name"); - goto error; - } + if (fd >= 0) { + if (check_fd(fd)) + goto error; + self->fd = fd; + self->closefd = closefd; + } + else { + self->closefd = 1; + if (!closefd) { + PyErr_SetString(PyExc_ValueError, + "Cannot use closefd=False with file name"); + goto error; + } - Py_BEGIN_ALLOW_THREADS - errno = 0; + Py_BEGIN_ALLOW_THREADS + errno = 0; #ifdef MS_WINDOWS - if (widename != NULL) - self->fd = _wopen(widename, flags, 0666); - else + if (widename != NULL) + self->fd = _wopen(widename, flags, 0666); + else #endif - self->fd = open(name, flags, 0666); - Py_END_ALLOW_THREADS - if (self->fd < 0) { + self->fd = open(name, flags, 0666); + Py_END_ALLOW_THREADS + if (self->fd < 0) { #ifdef MS_WINDOWS - if (widename != NULL) - PyErr_SetFromErrnoWithUnicodeFilename(PyExc_IOError, widename); - else + if (widename != NULL) + PyErr_SetFromErrnoWithUnicodeFilename(PyExc_IOError, widename); + else #endif - PyErr_SetFromErrnoWithFilename(PyExc_IOError, name); - goto error; - } - if(dircheck(self, name) < 0) - goto error; - } - - if (PyObject_SetAttrString((PyObject *)self, "name", nameobj) < 0) - goto error; - - if (append) { - /* For consistent behaviour, we explicitly seek to the - end of file (otherwise, it might be done only on the - first write()). */ - PyObject *pos = portable_lseek(self->fd, NULL, 2); - if (pos == NULL) - goto error; - Py_DECREF(pos); - } + PyErr_SetFromErrnoWithFilename(PyExc_IOError, name); + goto error; + } + if(dircheck(self, name) < 0) + goto error; + } + + if (PyObject_SetAttrString((PyObject *)self, "name", nameobj) < 0) + goto error; + + if (append) { + /* For consistent behaviour, we explicitly seek to the + end of file (otherwise, it might be done only on the + first write()). */ + PyObject *pos = portable_lseek(self->fd, NULL, 2); + if (pos == NULL) + goto error; + Py_DECREF(pos); + } - goto done; + goto done; error: - ret = -1; + ret = -1; done: - Py_CLEAR(stringobj); - return ret; + Py_CLEAR(stringobj); + return ret; } static int fileio_traverse(fileio *self, visitproc visit, void *arg) { - Py_VISIT(self->dict); - return 0; + Py_VISIT(self->dict); + return 0; } static int fileio_clear(fileio *self) { - Py_CLEAR(self->dict); - return 0; + Py_CLEAR(self->dict); + return 0; } static void fileio_dealloc(fileio *self) { - if (_PyIOBase_finalize((PyObject *) self) < 0) - return; - _PyObject_GC_UNTRACK(self); - if (self->weakreflist != NULL) - PyObject_ClearWeakRefs((PyObject *) self); - Py_CLEAR(self->dict); - Py_TYPE(self)->tp_free((PyObject *)self); + if (_PyIOBase_finalize((PyObject *) self) < 0) + return; + _PyObject_GC_UNTRACK(self); + if (self->weakreflist != NULL) + PyObject_ClearWeakRefs((PyObject *) self); + Py_CLEAR(self->dict); + Py_TYPE(self)->tp_free((PyObject *)self); } static PyObject * err_closed(void) { - PyErr_SetString(PyExc_ValueError, "I/O operation on closed file"); - return NULL; + PyErr_SetString(PyExc_ValueError, "I/O operation on closed file"); + return NULL; } static PyObject * err_mode(char *action) { - PyErr_Format(PyExc_ValueError, "File not open for %s", action); - return NULL; + PyErr_Format(PyExc_ValueError, "File not open for %s", action); + return NULL; } static PyObject * fileio_fileno(fileio *self) { - if (self->fd < 0) - return err_closed(); - return PyLong_FromLong((long) self->fd); + if (self->fd < 0) + return err_closed(); + return PyLong_FromLong((long) self->fd); } static PyObject * fileio_readable(fileio *self) { - if (self->fd < 0) - return err_closed(); - return PyBool_FromLong((long) self->readable); + if (self->fd < 0) + return err_closed(); + return PyBool_FromLong((long) self->readable); } static PyObject * fileio_writable(fileio *self) { - if (self->fd < 0) - return err_closed(); - return PyBool_FromLong((long) self->writable); + if (self->fd < 0) + return err_closed(); + return PyBool_FromLong((long) self->writable); } static PyObject * fileio_seekable(fileio *self) { - if (self->fd < 0) - return err_closed(); - if (self->seekable < 0) { - PyObject *pos = portable_lseek(self->fd, NULL, SEEK_CUR); - if (pos == NULL) { - PyErr_Clear(); - self->seekable = 0; - } else { - Py_DECREF(pos); - self->seekable = 1; - } - } - return PyBool_FromLong((long) self->seekable); + if (self->fd < 0) + return err_closed(); + if (self->seekable < 0) { + PyObject *pos = portable_lseek(self->fd, NULL, SEEK_CUR); + if (pos == NULL) { + PyErr_Clear(); + self->seekable = 0; + } else { + Py_DECREF(pos); + self->seekable = 1; + } + } + return PyBool_FromLong((long) self->seekable); } static PyObject * fileio_readinto(fileio *self, PyObject *args) { - Py_buffer pbuf; - Py_ssize_t n; + Py_buffer pbuf; + Py_ssize_t n; - if (self->fd < 0) - return err_closed(); - if (!self->readable) - return err_mode("reading"); - - if (!PyArg_ParseTuple(args, "w*", &pbuf)) - return NULL; - - if (_PyVerify_fd(self->fd)) { - Py_BEGIN_ALLOW_THREADS - errno = 0; - n = read(self->fd, pbuf.buf, pbuf.len); - Py_END_ALLOW_THREADS - } else - n = -1; - PyBuffer_Release(&pbuf); - if (n < 0) { - if (errno == EAGAIN) - Py_RETURN_NONE; - PyErr_SetFromErrno(PyExc_IOError); - return NULL; - } + if (self->fd < 0) + return err_closed(); + if (!self->readable) + return err_mode("reading"); + + if (!PyArg_ParseTuple(args, "w*", &pbuf)) + return NULL; + + if (_PyVerify_fd(self->fd)) { + Py_BEGIN_ALLOW_THREADS + errno = 0; + n = read(self->fd, pbuf.buf, pbuf.len); + Py_END_ALLOW_THREADS + } else + n = -1; + PyBuffer_Release(&pbuf); + if (n < 0) { + if (errno == EAGAIN) + Py_RETURN_NONE; + PyErr_SetFromErrno(PyExc_IOError); + return NULL; + } - return PyLong_FromSsize_t(n); + return PyLong_FromSsize_t(n); } static size_t new_buffersize(fileio *self, size_t currentsize) { #ifdef HAVE_FSTAT - off_t pos, end; - struct stat st; - if (fstat(self->fd, &st) == 0) { - end = st.st_size; - pos = lseek(self->fd, 0L, SEEK_CUR); - /* Files claiming a size smaller than SMALLCHUNK may - actually be streaming pseudo-files. In this case, we - apply the more aggressive algorithm below. - */ - if (end >= SMALLCHUNK && end >= pos && pos >= 0) { - /* Add 1 so if the file were to grow we'd notice. */ - return currentsize + end - pos + 1; - } - } + off_t pos, end; + struct stat st; + if (fstat(self->fd, &st) == 0) { + end = st.st_size; + pos = lseek(self->fd, 0L, SEEK_CUR); + /* Files claiming a size smaller than SMALLCHUNK may + actually be streaming pseudo-files. In this case, we + apply the more aggressive algorithm below. + */ + if (end >= SMALLCHUNK && end >= pos && pos >= 0) { + /* Add 1 so if the file were to grow we'd notice. */ + return currentsize + end - pos + 1; + } + } #endif - if (currentsize > SMALLCHUNK) { - /* Keep doubling until we reach BIGCHUNK; - then keep adding BIGCHUNK. */ - if (currentsize <= BIGCHUNK) - return currentsize + currentsize; - else - return currentsize + BIGCHUNK; - } - return currentsize + SMALLCHUNK; + if (currentsize > SMALLCHUNK) { + /* Keep doubling until we reach BIGCHUNK; + then keep adding BIGCHUNK. */ + if (currentsize <= BIGCHUNK) + return currentsize + currentsize; + else + return currentsize + BIGCHUNK; + } + return currentsize + SMALLCHUNK; } static PyObject * fileio_readall(fileio *self) { - PyObject *result; - Py_ssize_t total = 0; - int n; - - if (!_PyVerify_fd(self->fd)) - return PyErr_SetFromErrno(PyExc_IOError); - - result = PyBytes_FromStringAndSize(NULL, SMALLCHUNK); - if (result == NULL) - return NULL; - - while (1) { - size_t newsize = new_buffersize(self, total); - if (newsize > PY_SSIZE_T_MAX || newsize <= 0) { - PyErr_SetString(PyExc_OverflowError, - "unbounded read returned more bytes " - "than a Python string can hold "); - Py_DECREF(result); - return NULL; - } - - if (PyBytes_GET_SIZE(result) < (Py_ssize_t)newsize) { - if (_PyBytes_Resize(&result, newsize) < 0) { - if (total == 0) { - Py_DECREF(result); - return NULL; - } - PyErr_Clear(); - break; - } - } - Py_BEGIN_ALLOW_THREADS - errno = 0; - n = read(self->fd, - PyBytes_AS_STRING(result) + total, - newsize - total); - Py_END_ALLOW_THREADS - if (n == 0) - break; - if (n < 0) { - if (total > 0) - break; - if (errno == EAGAIN) { - Py_DECREF(result); - Py_RETURN_NONE; - } - Py_DECREF(result); - PyErr_SetFromErrno(PyExc_IOError); - return NULL; - } - total += n; - } - - if (PyBytes_GET_SIZE(result) > total) { - if (_PyBytes_Resize(&result, total) < 0) { - /* This should never happen, but just in case */ - Py_DECREF(result); - return NULL; - } - } - return result; + PyObject *result; + Py_ssize_t total = 0; + int n; + + if (!_PyVerify_fd(self->fd)) + return PyErr_SetFromErrno(PyExc_IOError); + + result = PyBytes_FromStringAndSize(NULL, SMALLCHUNK); + if (result == NULL) + return NULL; + + while (1) { + size_t newsize = new_buffersize(self, total); + if (newsize > PY_SSIZE_T_MAX || newsize <= 0) { + PyErr_SetString(PyExc_OverflowError, + "unbounded read returned more bytes " + "than a Python string can hold "); + Py_DECREF(result); + return NULL; + } + + if (PyBytes_GET_SIZE(result) < (Py_ssize_t)newsize) { + if (_PyBytes_Resize(&result, newsize) < 0) { + if (total == 0) { + Py_DECREF(result); + return NULL; + } + PyErr_Clear(); + break; + } + } + Py_BEGIN_ALLOW_THREADS + errno = 0; + n = read(self->fd, + PyBytes_AS_STRING(result) + total, + newsize - total); + Py_END_ALLOW_THREADS + if (n == 0) + break; + if (n < 0) { + if (total > 0) + break; + if (errno == EAGAIN) { + Py_DECREF(result); + Py_RETURN_NONE; + } + Py_DECREF(result); + PyErr_SetFromErrno(PyExc_IOError); + return NULL; + } + total += n; + } + + if (PyBytes_GET_SIZE(result) > total) { + if (_PyBytes_Resize(&result, total) < 0) { + /* This should never happen, but just in case */ + Py_DECREF(result); + return NULL; + } + } + return result; } static PyObject * fileio_read(fileio *self, PyObject *args) { - char *ptr; - Py_ssize_t n; - Py_ssize_t size = -1; - PyObject *bytes; - - if (self->fd < 0) - return err_closed(); - if (!self->readable) - return err_mode("reading"); - - if (!PyArg_ParseTuple(args, "|O&", &_PyIO_ConvertSsize_t, &size)) - return NULL; - - if (size < 0) { - return fileio_readall(self); - } - - bytes = PyBytes_FromStringAndSize(NULL, size); - if (bytes == NULL) - return NULL; - ptr = PyBytes_AS_STRING(bytes); - - if (_PyVerify_fd(self->fd)) { - Py_BEGIN_ALLOW_THREADS - errno = 0; - n = read(self->fd, ptr, size); - Py_END_ALLOW_THREADS - } else - n = -1; - - if (n < 0) { - Py_DECREF(bytes); - if (errno == EAGAIN) - Py_RETURN_NONE; - PyErr_SetFromErrno(PyExc_IOError); - return NULL; - } - - if (n != size) { - if (_PyBytes_Resize(&bytes, n) < 0) { - Py_DECREF(bytes); - return NULL; - } - } + char *ptr; + Py_ssize_t n; + Py_ssize_t size = -1; + PyObject *bytes; + + if (self->fd < 0) + return err_closed(); + if (!self->readable) + return err_mode("reading"); + + if (!PyArg_ParseTuple(args, "|O&", &_PyIO_ConvertSsize_t, &size)) + return NULL; + + if (size < 0) { + return fileio_readall(self); + } + + bytes = PyBytes_FromStringAndSize(NULL, size); + if (bytes == NULL) + return NULL; + ptr = PyBytes_AS_STRING(bytes); + + if (_PyVerify_fd(self->fd)) { + Py_BEGIN_ALLOW_THREADS + errno = 0; + n = read(self->fd, ptr, size); + Py_END_ALLOW_THREADS + } else + n = -1; + + if (n < 0) { + Py_DECREF(bytes); + if (errno == EAGAIN) + Py_RETURN_NONE; + PyErr_SetFromErrno(PyExc_IOError); + return NULL; + } + + if (n != size) { + if (_PyBytes_Resize(&bytes, n) < 0) { + Py_DECREF(bytes); + return NULL; + } + } - return (PyObject *) bytes; + return (PyObject *) bytes; } static PyObject * fileio_write(fileio *self, PyObject *args) { - Py_buffer pbuf; - Py_ssize_t n; + Py_buffer pbuf; + Py_ssize_t n; - if (self->fd < 0) - return err_closed(); - if (!self->writable) - return err_mode("writing"); - - if (!PyArg_ParseTuple(args, "y*", &pbuf)) - return NULL; - - if (_PyVerify_fd(self->fd)) { - Py_BEGIN_ALLOW_THREADS - errno = 0; - n = write(self->fd, pbuf.buf, pbuf.len); - Py_END_ALLOW_THREADS - } else - n = -1; - - PyBuffer_Release(&pbuf); - - if (n < 0) { - if (errno == EAGAIN) - Py_RETURN_NONE; - PyErr_SetFromErrno(PyExc_IOError); - return NULL; - } + if (self->fd < 0) + return err_closed(); + if (!self->writable) + return err_mode("writing"); + + if (!PyArg_ParseTuple(args, "y*", &pbuf)) + return NULL; + + if (_PyVerify_fd(self->fd)) { + Py_BEGIN_ALLOW_THREADS + errno = 0; + n = write(self->fd, pbuf.buf, pbuf.len); + Py_END_ALLOW_THREADS + } else + n = -1; + + PyBuffer_Release(&pbuf); + + if (n < 0) { + if (errno == EAGAIN) + Py_RETURN_NONE; + PyErr_SetFromErrno(PyExc_IOError); + return NULL; + } - return PyLong_FromSsize_t(n); + return PyLong_FromSsize_t(n); } /* XXX Windows support below is likely incomplete */ @@ -683,235 +683,235 @@ static PyObject * portable_lseek(int fd, PyObject *posobj, int whence) { - Py_off_t pos, res; + Py_off_t pos, res; #ifdef SEEK_SET - /* Turn 0, 1, 2 into SEEK_{SET,CUR,END} */ - switch (whence) { + /* Turn 0, 1, 2 into SEEK_{SET,CUR,END} */ + switch (whence) { #if SEEK_SET != 0 - case 0: whence = SEEK_SET; break; + case 0: whence = SEEK_SET; break; #endif #if SEEK_CUR != 1 - case 1: whence = SEEK_CUR; break; + case 1: whence = SEEK_CUR; break; #endif #if SEEK_END != 2 - case 2: whence = SEEK_END; break; + case 2: whence = SEEK_END; break; #endif - } + } #endif /* SEEK_SET */ - if (posobj == NULL) - pos = 0; - else { - if(PyFloat_Check(posobj)) { - PyErr_SetString(PyExc_TypeError, "an integer is required"); - return NULL; - } + if (posobj == NULL) + pos = 0; + else { + if(PyFloat_Check(posobj)) { + PyErr_SetString(PyExc_TypeError, "an integer is required"); + return NULL; + } #if defined(HAVE_LARGEFILE_SUPPORT) - pos = PyLong_AsLongLong(posobj); + pos = PyLong_AsLongLong(posobj); #else - pos = PyLong_AsLong(posobj); + pos = PyLong_AsLong(posobj); #endif - if (PyErr_Occurred()) - return NULL; - } + if (PyErr_Occurred()) + return NULL; + } - if (_PyVerify_fd(fd)) { - Py_BEGIN_ALLOW_THREADS + if (_PyVerify_fd(fd)) { + Py_BEGIN_ALLOW_THREADS #if defined(MS_WIN64) || defined(MS_WINDOWS) - res = _lseeki64(fd, pos, whence); + res = _lseeki64(fd, pos, whence); #else - res = lseek(fd, pos, whence); + res = lseek(fd, pos, whence); #endif - Py_END_ALLOW_THREADS - } else - res = -1; - if (res < 0) - return PyErr_SetFromErrno(PyExc_IOError); + Py_END_ALLOW_THREADS + } else + res = -1; + if (res < 0) + return PyErr_SetFromErrno(PyExc_IOError); #if defined(HAVE_LARGEFILE_SUPPORT) - return PyLong_FromLongLong(res); + return PyLong_FromLongLong(res); #else - return PyLong_FromLong(res); + return PyLong_FromLong(res); #endif } static PyObject * fileio_seek(fileio *self, PyObject *args) { - PyObject *posobj; - int whence = 0; + PyObject *posobj; + int whence = 0; - if (self->fd < 0) - return err_closed(); + if (self->fd < 0) + return err_closed(); - if (!PyArg_ParseTuple(args, "O|i", &posobj, &whence)) - return NULL; + if (!PyArg_ParseTuple(args, "O|i", &posobj, &whence)) + return NULL; - return portable_lseek(self->fd, posobj, whence); + return portable_lseek(self->fd, posobj, whence); } static PyObject * fileio_tell(fileio *self, PyObject *args) { - if (self->fd < 0) - return err_closed(); + if (self->fd < 0) + return err_closed(); - return portable_lseek(self->fd, NULL, 1); + return portable_lseek(self->fd, NULL, 1); } #ifdef HAVE_FTRUNCATE static PyObject * fileio_truncate(fileio *self, PyObject *args) { - PyObject *posobj = NULL; /* the new size wanted by the user */ + PyObject *posobj = NULL; /* the new size wanted by the user */ #ifndef MS_WINDOWS - Py_off_t pos; + Py_off_t pos; #endif - int ret; - int fd; + int ret; + int fd; - fd = self->fd; - if (fd < 0) - return err_closed(); - if (!self->writable) - return err_mode("writing"); - - if (!PyArg_ParseTuple(args, "|O", &posobj)) - return NULL; - - if (posobj == Py_None || posobj == NULL) { - /* Get the current position. */ - posobj = portable_lseek(fd, NULL, 1); - if (posobj == NULL) - return NULL; - } - else { - Py_INCREF(posobj); - } + fd = self->fd; + if (fd < 0) + return err_closed(); + if (!self->writable) + return err_mode("writing"); + + if (!PyArg_ParseTuple(args, "|O", &posobj)) + return NULL; + + if (posobj == Py_None || posobj == NULL) { + /* Get the current position. */ + posobj = portable_lseek(fd, NULL, 1); + if (posobj == NULL) + return NULL; + } + else { + Py_INCREF(posobj); + } #ifdef MS_WINDOWS - /* MS _chsize doesn't work if newsize doesn't fit in 32 bits, - so don't even try using it. */ - { - PyObject *oldposobj, *tempposobj; - HANDLE hFile; - - /* we save the file pointer position */ - oldposobj = portable_lseek(fd, NULL, 1); - if (oldposobj == NULL) { - Py_DECREF(posobj); - return NULL; - } - - /* we then move to the truncation position */ - tempposobj = portable_lseek(fd, posobj, 0); - if (tempposobj == NULL) { - Py_DECREF(oldposobj); - Py_DECREF(posobj); - return NULL; - } - Py_DECREF(tempposobj); - - /* Truncate. Note that this may grow the file! */ - Py_BEGIN_ALLOW_THREADS - errno = 0; - hFile = (HANDLE)_get_osfhandle(fd); - ret = hFile == (HANDLE)-1; /* testing for INVALID_HANDLE value */ - if (ret == 0) { - ret = SetEndOfFile(hFile) == 0; - if (ret) - errno = EACCES; - } - Py_END_ALLOW_THREADS - - /* we restore the file pointer position in any case */ - tempposobj = portable_lseek(fd, oldposobj, 0); - Py_DECREF(oldposobj); - if (tempposobj == NULL) { - Py_DECREF(posobj); - return NULL; - } - Py_DECREF(tempposobj); - } + /* MS _chsize doesn't work if newsize doesn't fit in 32 bits, + so don't even try using it. */ + { + PyObject *oldposobj, *tempposobj; + HANDLE hFile; + + /* we save the file pointer position */ + oldposobj = portable_lseek(fd, NULL, 1); + if (oldposobj == NULL) { + Py_DECREF(posobj); + return NULL; + } + + /* we then move to the truncation position */ + tempposobj = portable_lseek(fd, posobj, 0); + if (tempposobj == NULL) { + Py_DECREF(oldposobj); + Py_DECREF(posobj); + return NULL; + } + Py_DECREF(tempposobj); + + /* Truncate. Note that this may grow the file! */ + Py_BEGIN_ALLOW_THREADS + errno = 0; + hFile = (HANDLE)_get_osfhandle(fd); + ret = hFile == (HANDLE)-1; /* testing for INVALID_HANDLE value */ + if (ret == 0) { + ret = SetEndOfFile(hFile) == 0; + if (ret) + errno = EACCES; + } + Py_END_ALLOW_THREADS + + /* we restore the file pointer position in any case */ + tempposobj = portable_lseek(fd, oldposobj, 0); + Py_DECREF(oldposobj); + if (tempposobj == NULL) { + Py_DECREF(posobj); + return NULL; + } + Py_DECREF(tempposobj); + } #else #if defined(HAVE_LARGEFILE_SUPPORT) - pos = PyLong_AsLongLong(posobj); + pos = PyLong_AsLongLong(posobj); #else - pos = PyLong_AsLong(posobj); + pos = PyLong_AsLong(posobj); #endif - if (PyErr_Occurred()){ - Py_DECREF(posobj); - return NULL; - } - - Py_BEGIN_ALLOW_THREADS - errno = 0; - ret = ftruncate(fd, pos); - Py_END_ALLOW_THREADS + if (PyErr_Occurred()){ + Py_DECREF(posobj); + return NULL; + } + + Py_BEGIN_ALLOW_THREADS + errno = 0; + ret = ftruncate(fd, pos); + Py_END_ALLOW_THREADS #endif /* !MS_WINDOWS */ - if (ret != 0) { - Py_DECREF(posobj); - PyErr_SetFromErrno(PyExc_IOError); - return NULL; - } + if (ret != 0) { + Py_DECREF(posobj); + PyErr_SetFromErrno(PyExc_IOError); + return NULL; + } - return posobj; + return posobj; } #endif /* HAVE_FTRUNCATE */ static char * mode_string(fileio *self) { - if (self->readable) { - if (self->writable) - return "rb+"; - else - return "rb"; - } - else - return "wb"; + if (self->readable) { + if (self->writable) + return "rb+"; + else + return "rb"; + } + else + return "wb"; } static PyObject * fileio_repr(fileio *self) { - PyObject *nameobj, *res; + PyObject *nameobj, *res; - if (self->fd < 0) - return PyUnicode_FromFormat("<_io.FileIO [closed]>"); + if (self->fd < 0) + return PyUnicode_FromFormat("<_io.FileIO [closed]>"); - nameobj = PyObject_GetAttrString((PyObject *) self, "name"); - if (nameobj == NULL) { - if (PyErr_ExceptionMatches(PyExc_AttributeError)) - PyErr_Clear(); - else - return NULL; - res = PyUnicode_FromFormat("<_io.FileIO fd=%d mode='%s'>", - self->fd, mode_string(self)); - } - else { - res = PyUnicode_FromFormat("<_io.FileIO name=%R mode='%s'>", - nameobj, mode_string(self)); - Py_DECREF(nameobj); - } - return res; + nameobj = PyObject_GetAttrString((PyObject *) self, "name"); + if (nameobj == NULL) { + if (PyErr_ExceptionMatches(PyExc_AttributeError)) + PyErr_Clear(); + else + return NULL; + res = PyUnicode_FromFormat("<_io.FileIO fd=%d mode='%s'>", + self->fd, mode_string(self)); + } + else { + res = PyUnicode_FromFormat("<_io.FileIO name=%R mode='%s'>", + nameobj, mode_string(self)); + Py_DECREF(nameobj); + } + return res; } static PyObject * fileio_isatty(fileio *self) { - long res; + long res; - if (self->fd < 0) - return err_closed(); - Py_BEGIN_ALLOW_THREADS - res = isatty(self->fd); - Py_END_ALLOW_THREADS - return PyBool_FromLong(res); + if (self->fd < 0) + return err_closed(); + Py_BEGIN_ALLOW_THREADS + res = isatty(self->fd); + Py_END_ALLOW_THREADS + return PyBool_FromLong(res); } @@ -919,7 +919,7 @@ "file(name: str[, mode: str]) -> file IO object\n" "\n" "Open a file. The mode can be 'r', 'w' or 'a' for reading (default),\n" -"writing or appending. The file will be created if it doesn't exist\n" +"writing or appending. The file will be created if it doesn't exist\n" "when opened for writing or appending; it will be truncated when\n" "opened for writing. Add a '+' to the mode to allow simultaneous\n" "reading and writing."); @@ -961,14 +961,14 @@ #ifdef HAVE_FTRUNCATE PyDoc_STRVAR(truncate_doc, -"truncate([size: int]) -> None. Truncate the file to at most size bytes.\n" +"truncate([size: int]) -> None. Truncate the file to at most size bytes.\n" "\n" "Size defaults to the current file position, as returned by tell()." "The current file position is changed to the value of size."); #endif PyDoc_STRVAR(tell_doc, -"tell() -> int. Current file position"); +"tell() -> int. Current file position"); PyDoc_STRVAR(readinto_doc, "readinto() -> Same as RawIOBase.readinto()."); @@ -992,22 +992,22 @@ "writable() -> bool. True if file was opened in a write mode."); static PyMethodDef fileio_methods[] = { - {"read", (PyCFunction)fileio_read, METH_VARARGS, read_doc}, - {"readall", (PyCFunction)fileio_readall, METH_NOARGS, readall_doc}, - {"readinto", (PyCFunction)fileio_readinto, METH_VARARGS, readinto_doc}, - {"write", (PyCFunction)fileio_write, METH_VARARGS, write_doc}, - {"seek", (PyCFunction)fileio_seek, METH_VARARGS, seek_doc}, - {"tell", (PyCFunction)fileio_tell, METH_VARARGS, tell_doc}, + {"read", (PyCFunction)fileio_read, METH_VARARGS, read_doc}, + {"readall", (PyCFunction)fileio_readall, METH_NOARGS, readall_doc}, + {"readinto", (PyCFunction)fileio_readinto, METH_VARARGS, readinto_doc}, + {"write", (PyCFunction)fileio_write, METH_VARARGS, write_doc}, + {"seek", (PyCFunction)fileio_seek, METH_VARARGS, seek_doc}, + {"tell", (PyCFunction)fileio_tell, METH_VARARGS, tell_doc}, #ifdef HAVE_FTRUNCATE - {"truncate", (PyCFunction)fileio_truncate, METH_VARARGS, truncate_doc}, + {"truncate", (PyCFunction)fileio_truncate, METH_VARARGS, truncate_doc}, #endif - {"close", (PyCFunction)fileio_close, METH_NOARGS, close_doc}, - {"seekable", (PyCFunction)fileio_seekable, METH_NOARGS, seekable_doc}, - {"readable", (PyCFunction)fileio_readable, METH_NOARGS, readable_doc}, - {"writable", (PyCFunction)fileio_writable, METH_NOARGS, writable_doc}, - {"fileno", (PyCFunction)fileio_fileno, METH_NOARGS, fileno_doc}, - {"isatty", (PyCFunction)fileio_isatty, METH_NOARGS, isatty_doc}, - {NULL, NULL} /* sentinel */ + {"close", (PyCFunction)fileio_close, METH_NOARGS, close_doc}, + {"seekable", (PyCFunction)fileio_seekable, METH_NOARGS, seekable_doc}, + {"readable", (PyCFunction)fileio_readable, METH_NOARGS, readable_doc}, + {"writable", (PyCFunction)fileio_writable, METH_NOARGS, writable_doc}, + {"fileno", (PyCFunction)fileio_fileno, METH_NOARGS, fileno_doc}, + {"isatty", (PyCFunction)fileio_isatty, METH_NOARGS, isatty_doc}, + {NULL, NULL} /* sentinel */ }; /* 'closed' and 'mode' are attributes for backwards compatibility reasons. */ @@ -1015,68 +1015,68 @@ static PyObject * get_closed(fileio *self, void *closure) { - return PyBool_FromLong((long)(self->fd < 0)); + return PyBool_FromLong((long)(self->fd < 0)); } static PyObject * get_closefd(fileio *self, void *closure) { - return PyBool_FromLong((long)(self->closefd)); + return PyBool_FromLong((long)(self->closefd)); } static PyObject * get_mode(fileio *self, void *closure) { - return PyUnicode_FromString(mode_string(self)); + return PyUnicode_FromString(mode_string(self)); } static PyGetSetDef fileio_getsetlist[] = { - {"closed", (getter)get_closed, NULL, "True if the file is closed"}, - {"closefd", (getter)get_closefd, NULL, - "True if the file descriptor will be closed"}, - {"mode", (getter)get_mode, NULL, "String giving the file mode"}, - {NULL}, + {"closed", (getter)get_closed, NULL, "True if the file is closed"}, + {"closefd", (getter)get_closefd, NULL, + "True if the file descriptor will be closed"}, + {"mode", (getter)get_mode, NULL, "String giving the file mode"}, + {NULL}, }; PyTypeObject PyFileIO_Type = { - PyVarObject_HEAD_INIT(NULL, 0) - "_io.FileIO", - sizeof(fileio), - 0, - (destructor)fileio_dealloc, /* tp_dealloc */ - 0, /* tp_print */ - 0, /* tp_getattr */ - 0, /* tp_setattr */ - 0, /* tp_reserved */ - (reprfunc)fileio_repr, /* 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_BASETYPE - | Py_TPFLAGS_HAVE_GC, /* tp_flags */ - fileio_doc, /* tp_doc */ - (traverseproc)fileio_traverse, /* tp_traverse */ - (inquiry)fileio_clear, /* tp_clear */ - 0, /* tp_richcompare */ - offsetof(fileio, weakreflist), /* tp_weaklistoffset */ - 0, /* tp_iter */ - 0, /* tp_iternext */ - fileio_methods, /* tp_methods */ - 0, /* tp_members */ - fileio_getsetlist, /* tp_getset */ - 0, /* tp_base */ - 0, /* tp_dict */ - 0, /* tp_descr_get */ - 0, /* tp_descr_set */ - offsetof(fileio, dict), /* tp_dictoffset */ - fileio_init, /* tp_init */ - PyType_GenericAlloc, /* tp_alloc */ - fileio_new, /* tp_new */ - PyObject_GC_Del, /* tp_free */ + PyVarObject_HEAD_INIT(NULL, 0) + "_io.FileIO", + sizeof(fileio), + 0, + (destructor)fileio_dealloc, /* tp_dealloc */ + 0, /* tp_print */ + 0, /* tp_getattr */ + 0, /* tp_setattr */ + 0, /* tp_reserved */ + (reprfunc)fileio_repr, /* 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_BASETYPE + | Py_TPFLAGS_HAVE_GC, /* tp_flags */ + fileio_doc, /* tp_doc */ + (traverseproc)fileio_traverse, /* tp_traverse */ + (inquiry)fileio_clear, /* tp_clear */ + 0, /* tp_richcompare */ + offsetof(fileio, weakreflist), /* tp_weaklistoffset */ + 0, /* tp_iter */ + 0, /* tp_iternext */ + fileio_methods, /* tp_methods */ + 0, /* tp_members */ + fileio_getsetlist, /* tp_getset */ + 0, /* tp_base */ + 0, /* tp_dict */ + 0, /* tp_descr_get */ + 0, /* tp_descr_set */ + offsetof(fileio, dict), /* tp_dictoffset */ + fileio_init, /* tp_init */ + PyType_GenericAlloc, /* tp_alloc */ + fileio_new, /* tp_new */ + PyObject_GC_Del, /* tp_free */ }; Modified: python/branches/py3k-jit/Modules/_ssl.c ============================================================================== --- python/branches/py3k-jit/Modules/_ssl.c (original) +++ python/branches/py3k-jit/Modules/_ssl.c Thu May 6 23:49:27 2010 @@ -19,14 +19,14 @@ #ifdef WITH_THREAD #include "pythread.h" #define PySSL_BEGIN_ALLOW_THREADS { \ - PyThreadState *_save = NULL; \ - if (_ssl_locks_count>0) {_save = PyEval_SaveThread();} -#define PySSL_BLOCK_THREADS if (_ssl_locks_count>0){PyEval_RestoreThread(_save)}; -#define PySSL_UNBLOCK_THREADS if (_ssl_locks_count>0){_save = PyEval_SaveThread()}; -#define PySSL_END_ALLOW_THREADS if (_ssl_locks_count>0){PyEval_RestoreThread(_save);} \ - } + PyThreadState *_save = NULL; \ + if (_ssl_locks_count>0) {_save = PyEval_SaveThread();} +#define PySSL_BLOCK_THREADS if (_ssl_locks_count>0){PyEval_RestoreThread(_save)}; +#define PySSL_UNBLOCK_THREADS if (_ssl_locks_count>0){_save = PyEval_SaveThread()}; +#define PySSL_END_ALLOW_THREADS if (_ssl_locks_count>0){PyEval_RestoreThread(_save);} \ + } -#else /* no WITH_THREAD */ +#else /* no WITH_THREAD */ #define PySSL_BEGIN_ALLOW_THREADS #define PySSL_BLOCK_THREADS @@ -36,37 +36,37 @@ #endif enum py_ssl_error { - /* these mirror ssl.h */ - PY_SSL_ERROR_NONE, - PY_SSL_ERROR_SSL, - PY_SSL_ERROR_WANT_READ, - PY_SSL_ERROR_WANT_WRITE, - PY_SSL_ERROR_WANT_X509_LOOKUP, - PY_SSL_ERROR_SYSCALL, /* look at error stack/return value/errno */ - PY_SSL_ERROR_ZERO_RETURN, - PY_SSL_ERROR_WANT_CONNECT, - /* start of non ssl.h errorcodes */ - PY_SSL_ERROR_EOF, /* special case of SSL_ERROR_SYSCALL */ - PY_SSL_ERROR_NO_SOCKET, /* socket has been GC'd */ - PY_SSL_ERROR_INVALID_ERROR_CODE + /* these mirror ssl.h */ + PY_SSL_ERROR_NONE, + PY_SSL_ERROR_SSL, + PY_SSL_ERROR_WANT_READ, + PY_SSL_ERROR_WANT_WRITE, + PY_SSL_ERROR_WANT_X509_LOOKUP, + PY_SSL_ERROR_SYSCALL, /* look at error stack/return value/errno */ + PY_SSL_ERROR_ZERO_RETURN, + PY_SSL_ERROR_WANT_CONNECT, + /* start of non ssl.h errorcodes */ + PY_SSL_ERROR_EOF, /* special case of SSL_ERROR_SYSCALL */ + PY_SSL_ERROR_NO_SOCKET, /* socket has been GC'd */ + PY_SSL_ERROR_INVALID_ERROR_CODE }; enum py_ssl_server_or_client { - PY_SSL_CLIENT, - PY_SSL_SERVER + PY_SSL_CLIENT, + PY_SSL_SERVER }; enum py_ssl_cert_requirements { - PY_SSL_CERT_NONE, - PY_SSL_CERT_OPTIONAL, - PY_SSL_CERT_REQUIRED + PY_SSL_CERT_NONE, + PY_SSL_CERT_OPTIONAL, + PY_SSL_CERT_REQUIRED }; enum py_ssl_version { - PY_SSL_VERSION_SSL2, - PY_SSL_VERSION_SSL3, - PY_SSL_VERSION_SSL23, - PY_SSL_VERSION_TLS1 + PY_SSL_VERSION_SSL2, + PY_SSL_VERSION_SSL3, + PY_SSL_VERSION_SSL23, + PY_SSL_VERSION_TLS1 }; /* Include symbols from _socket module */ @@ -114,12 +114,12 @@ #endif typedef struct { - PyObject_HEAD - PyObject *Socket; /* weakref to socket on which we're layered */ - SSL_CTX* ctx; - SSL* ssl; - X509* peer_cert; - int shutdown_seen_zero; + PyObject_HEAD + PyObject *Socket; /* weakref to socket on which we're layered */ + SSL_CTX* ctx; + SSL* ssl; + X509* peer_cert; + int shutdown_seen_zero; } PySSLObject; @@ -127,19 +127,19 @@ static PyObject *PySSL_SSLwrite(PySSLObject *self, PyObject *args); static PyObject *PySSL_SSLread(PySSLObject *self, PyObject *args); static int check_socket_and_wait_for_timeout(PySocketSockObject *s, - int writing); + int writing); static PyObject *PySSL_peercert(PySSLObject *self, PyObject *args); static PyObject *PySSL_cipher(PySSLObject *self); -#define PySSLObject_Check(v) (Py_TYPE(v) == &PySSL_Type) +#define PySSLObject_Check(v) (Py_TYPE(v) == &PySSL_Type) typedef enum { - SOCKET_IS_NONBLOCKING, - SOCKET_IS_BLOCKING, - SOCKET_HAS_TIMED_OUT, - SOCKET_HAS_BEEN_CLOSED, - SOCKET_TOO_LARGE_FOR_SELECT, - SOCKET_OPERATION_OK + SOCKET_IS_NONBLOCKING, + SOCKET_IS_BLOCKING, + SOCKET_HAS_TIMED_OUT, + SOCKET_HAS_BEEN_CLOSED, + SOCKET_TOO_LARGE_FOR_SELECT, + SOCKET_OPERATION_OK } timeout_state; /* Wrap error strings with filename and line # */ @@ -156,293 +156,293 @@ static PyObject * PySSL_SetError(PySSLObject *obj, int ret, char *filename, int lineno) { - PyObject *v; - char buf[2048]; - char *errstr; - int err; - enum py_ssl_error p = PY_SSL_ERROR_NONE; - - assert(ret <= 0); - - if (obj->ssl != NULL) { - err = SSL_get_error(obj->ssl, ret); - - switch (err) { - case SSL_ERROR_ZERO_RETURN: - errstr = "TLS/SSL connection has been closed"; - p = PY_SSL_ERROR_ZERO_RETURN; - break; - case SSL_ERROR_WANT_READ: - errstr = "The operation did not complete (read)"; - p = PY_SSL_ERROR_WANT_READ; - break; - case SSL_ERROR_WANT_WRITE: - p = PY_SSL_ERROR_WANT_WRITE; - errstr = "The operation did not complete (write)"; - break; - case SSL_ERROR_WANT_X509_LOOKUP: - p = PY_SSL_ERROR_WANT_X509_LOOKUP; - errstr = - "The operation did not complete (X509 lookup)"; - break; - case SSL_ERROR_WANT_CONNECT: - p = PY_SSL_ERROR_WANT_CONNECT; - errstr = "The operation did not complete (connect)"; - break; - case SSL_ERROR_SYSCALL: - { - unsigned long e = ERR_get_error(); - if (e == 0) { - PySocketSockObject *s - = (PySocketSockObject *) PyWeakref_GetObject(obj->Socket); - if (ret == 0 || (((PyObject *)s) == Py_None)) { - p = PY_SSL_ERROR_EOF; - errstr = - "EOF occurred in violation of protocol"; - } else if (ret == -1) { - /* underlying BIO reported an I/O error */ - return s->errorhandler(); - } else { /* possible? */ - p = PY_SSL_ERROR_SYSCALL; - errstr = "Some I/O error occurred"; - } - } else { - p = PY_SSL_ERROR_SYSCALL; - /* XXX Protected by global interpreter lock */ - errstr = ERR_error_string(e, NULL); - } - break; - } - case SSL_ERROR_SSL: - { - unsigned long e = ERR_get_error(); - p = PY_SSL_ERROR_SSL; - if (e != 0) - /* XXX Protected by global interpreter lock */ - errstr = ERR_error_string(e, NULL); - else { /* possible? */ - errstr = - "A failure in the SSL library occurred"; - } - break; - } - default: - p = PY_SSL_ERROR_INVALID_ERROR_CODE; - errstr = "Invalid error code"; - } - } else { - errstr = ERR_error_string(ERR_peek_last_error(), NULL); - } - PyOS_snprintf(buf, sizeof(buf), "_ssl.c:%d: %s", lineno, errstr); - v = Py_BuildValue("(is)", p, buf); - if (v != NULL) { - PyErr_SetObject(PySSLErrorObject, v); - Py_DECREF(v); - } - return NULL; + PyObject *v; + char buf[2048]; + char *errstr; + int err; + enum py_ssl_error p = PY_SSL_ERROR_NONE; + + assert(ret <= 0); + + if (obj->ssl != NULL) { + err = SSL_get_error(obj->ssl, ret); + + switch (err) { + case SSL_ERROR_ZERO_RETURN: + errstr = "TLS/SSL connection has been closed"; + p = PY_SSL_ERROR_ZERO_RETURN; + break; + case SSL_ERROR_WANT_READ: + errstr = "The operation did not complete (read)"; + p = PY_SSL_ERROR_WANT_READ; + break; + case SSL_ERROR_WANT_WRITE: + p = PY_SSL_ERROR_WANT_WRITE; + errstr = "The operation did not complete (write)"; + break; + case SSL_ERROR_WANT_X509_LOOKUP: + p = PY_SSL_ERROR_WANT_X509_LOOKUP; + errstr = + "The operation did not complete (X509 lookup)"; + break; + case SSL_ERROR_WANT_CONNECT: + p = PY_SSL_ERROR_WANT_CONNECT; + errstr = "The operation did not complete (connect)"; + break; + case SSL_ERROR_SYSCALL: + { + unsigned long e = ERR_get_error(); + if (e == 0) { + PySocketSockObject *s + = (PySocketSockObject *) PyWeakref_GetObject(obj->Socket); + if (ret == 0 || (((PyObject *)s) == Py_None)) { + p = PY_SSL_ERROR_EOF; + errstr = + "EOF occurred in violation of protocol"; + } else if (ret == -1) { + /* underlying BIO reported an I/O error */ + return s->errorhandler(); + } else { /* possible? */ + p = PY_SSL_ERROR_SYSCALL; + errstr = "Some I/O error occurred"; + } + } else { + p = PY_SSL_ERROR_SYSCALL; + /* XXX Protected by global interpreter lock */ + errstr = ERR_error_string(e, NULL); + } + break; + } + case SSL_ERROR_SSL: + { + unsigned long e = ERR_get_error(); + p = PY_SSL_ERROR_SSL; + if (e != 0) + /* XXX Protected by global interpreter lock */ + errstr = ERR_error_string(e, NULL); + else { /* possible? */ + errstr = + "A failure in the SSL library occurred"; + } + break; + } + default: + p = PY_SSL_ERROR_INVALID_ERROR_CODE; + errstr = "Invalid error code"; + } + } else { + errstr = ERR_error_string(ERR_peek_last_error(), NULL); + } + PyOS_snprintf(buf, sizeof(buf), "_ssl.c:%d: %s", lineno, errstr); + v = Py_BuildValue("(is)", p, buf); + if (v != NULL) { + PyErr_SetObject(PySSLErrorObject, v); + Py_DECREF(v); + } + return NULL; } static PyObject * _setSSLError (char *errstr, int errcode, char *filename, int lineno) { - char buf[2048]; - PyObject *v; + char buf[2048]; + PyObject *v; - if (errstr == NULL) { - errcode = ERR_peek_last_error(); - errstr = ERR_error_string(errcode, NULL); - } - PyOS_snprintf(buf, sizeof(buf), "_ssl.c:%d: %s", lineno, errstr); - v = Py_BuildValue("(is)", errcode, buf); - if (v != NULL) { - PyErr_SetObject(PySSLErrorObject, v); - Py_DECREF(v); - } - return NULL; + if (errstr == NULL) { + errcode = ERR_peek_last_error(); + errstr = ERR_error_string(errcode, NULL); + } + PyOS_snprintf(buf, sizeof(buf), "_ssl.c:%d: %s", lineno, errstr); + v = Py_BuildValue("(is)", errcode, buf); + if (v != NULL) { + PyErr_SetObject(PySSLErrorObject, v); + Py_DECREF(v); + } + return NULL; } static PySSLObject * newPySSLObject(PySocketSockObject *Sock, char *key_file, char *cert_file, - enum py_ssl_server_or_client socket_type, - enum py_ssl_cert_requirements certreq, - enum py_ssl_version proto_version, - char *cacerts_file, char *ciphers) + enum py_ssl_server_or_client socket_type, + enum py_ssl_cert_requirements certreq, + enum py_ssl_version proto_version, + char *cacerts_file, char *ciphers) { - PySSLObject *self; - char *errstr = NULL; - int ret; - int verification_mode; - - self = PyObject_New(PySSLObject, &PySSL_Type); /* Create new object */ - if (self == NULL) - return NULL; - self->peer_cert = NULL; - self->ssl = NULL; - self->ctx = NULL; - self->Socket = NULL; - - /* Make sure the SSL error state is initialized */ - (void) ERR_get_state(); - ERR_clear_error(); - - if ((key_file && !cert_file) || (!key_file && cert_file)) { - errstr = ERRSTR("Both the key & certificate files " - "must be specified"); - goto fail; - } - - if ((socket_type == PY_SSL_SERVER) && - ((key_file == NULL) || (cert_file == NULL))) { - errstr = ERRSTR("Both the key & certificate files " - "must be specified for server-side operation"); - goto fail; - } - - PySSL_BEGIN_ALLOW_THREADS - if (proto_version == PY_SSL_VERSION_TLS1) - self->ctx = SSL_CTX_new(TLSv1_method()); /* Set up context */ - else if (proto_version == PY_SSL_VERSION_SSL3) - self->ctx = SSL_CTX_new(SSLv3_method()); /* Set up context */ - else if (proto_version == PY_SSL_VERSION_SSL2) - self->ctx = SSL_CTX_new(SSLv2_method()); /* Set up context */ - else if (proto_version == PY_SSL_VERSION_SSL23) - self->ctx = SSL_CTX_new(SSLv23_method()); /* Set up context */ - PySSL_END_ALLOW_THREADS - - if (self->ctx == NULL) { - errstr = ERRSTR("Invalid SSL protocol variant specified."); - goto fail; - } - - if (ciphers != NULL) { - ret = SSL_CTX_set_cipher_list(self->ctx, ciphers); - if (ret == 0) { - errstr = ERRSTR("No cipher can be selected."); - goto fail; - } - } - - if (certreq != PY_SSL_CERT_NONE) { - if (cacerts_file == NULL) { - errstr = ERRSTR("No root certificates specified for " - "verification of other-side certificates."); - goto fail; - } else { - PySSL_BEGIN_ALLOW_THREADS - ret = SSL_CTX_load_verify_locations(self->ctx, - cacerts_file, - NULL); - PySSL_END_ALLOW_THREADS - if (ret != 1) { - _setSSLError(NULL, 0, __FILE__, __LINE__); - goto fail; - } - } - } - if (key_file) { - PySSL_BEGIN_ALLOW_THREADS - ret = SSL_CTX_use_PrivateKey_file(self->ctx, key_file, - SSL_FILETYPE_PEM); - PySSL_END_ALLOW_THREADS - if (ret != 1) { - _setSSLError(NULL, ret, __FILE__, __LINE__); - goto fail; - } - - PySSL_BEGIN_ALLOW_THREADS - ret = SSL_CTX_use_certificate_chain_file(self->ctx, - cert_file); - PySSL_END_ALLOW_THREADS - if (ret != 1) { - /* - fprintf(stderr, "ret is %d, errcode is %lu, %lu, with file \"%s\"\n", - ret, ERR_peek_error(), ERR_peek_last_error(), cert_file); - */ - if (ERR_peek_last_error() != 0) { - _setSSLError(NULL, ret, __FILE__, __LINE__); - goto fail; - } - } - } - - /* ssl compatibility */ - SSL_CTX_set_options(self->ctx, SSL_OP_ALL); - - verification_mode = SSL_VERIFY_NONE; - if (certreq == PY_SSL_CERT_OPTIONAL) - verification_mode = SSL_VERIFY_PEER; - else if (certreq == PY_SSL_CERT_REQUIRED) - verification_mode = (SSL_VERIFY_PEER | - SSL_VERIFY_FAIL_IF_NO_PEER_CERT); - SSL_CTX_set_verify(self->ctx, verification_mode, - NULL); /* set verify lvl */ - - PySSL_BEGIN_ALLOW_THREADS - self->ssl = SSL_new(self->ctx); /* New ssl struct */ - PySSL_END_ALLOW_THREADS - SSL_set_fd(self->ssl, Sock->sock_fd); /* Set the socket for SSL */ + PySSLObject *self; + char *errstr = NULL; + int ret; + int verification_mode; + + self = PyObject_New(PySSLObject, &PySSL_Type); /* Create new object */ + if (self == NULL) + return NULL; + self->peer_cert = NULL; + self->ssl = NULL; + self->ctx = NULL; + self->Socket = NULL; + + /* Make sure the SSL error state is initialized */ + (void) ERR_get_state(); + ERR_clear_error(); + + if ((key_file && !cert_file) || (!key_file && cert_file)) { + errstr = ERRSTR("Both the key & certificate files " + "must be specified"); + goto fail; + } + + if ((socket_type == PY_SSL_SERVER) && + ((key_file == NULL) || (cert_file == NULL))) { + errstr = ERRSTR("Both the key & certificate files " + "must be specified for server-side operation"); + goto fail; + } + + PySSL_BEGIN_ALLOW_THREADS + if (proto_version == PY_SSL_VERSION_TLS1) + self->ctx = SSL_CTX_new(TLSv1_method()); /* Set up context */ + else if (proto_version == PY_SSL_VERSION_SSL3) + self->ctx = SSL_CTX_new(SSLv3_method()); /* Set up context */ + else if (proto_version == PY_SSL_VERSION_SSL2) + self->ctx = SSL_CTX_new(SSLv2_method()); /* Set up context */ + else if (proto_version == PY_SSL_VERSION_SSL23) + self->ctx = SSL_CTX_new(SSLv23_method()); /* Set up context */ + PySSL_END_ALLOW_THREADS + + if (self->ctx == NULL) { + errstr = ERRSTR("Invalid SSL protocol variant specified."); + goto fail; + } + + if (ciphers != NULL) { + ret = SSL_CTX_set_cipher_list(self->ctx, ciphers); + if (ret == 0) { + errstr = ERRSTR("No cipher can be selected."); + goto fail; + } + } + + if (certreq != PY_SSL_CERT_NONE) { + if (cacerts_file == NULL) { + errstr = ERRSTR("No root certificates specified for " + "verification of other-side certificates."); + goto fail; + } else { + PySSL_BEGIN_ALLOW_THREADS + ret = SSL_CTX_load_verify_locations(self->ctx, + cacerts_file, + NULL); + PySSL_END_ALLOW_THREADS + if (ret != 1) { + _setSSLError(NULL, 0, __FILE__, __LINE__); + goto fail; + } + } + } + if (key_file) { + PySSL_BEGIN_ALLOW_THREADS + ret = SSL_CTX_use_PrivateKey_file(self->ctx, key_file, + SSL_FILETYPE_PEM); + PySSL_END_ALLOW_THREADS + if (ret != 1) { + _setSSLError(NULL, ret, __FILE__, __LINE__); + goto fail; + } + + PySSL_BEGIN_ALLOW_THREADS + ret = SSL_CTX_use_certificate_chain_file(self->ctx, + cert_file); + PySSL_END_ALLOW_THREADS + if (ret != 1) { + /* + fprintf(stderr, "ret is %d, errcode is %lu, %lu, with file \"%s\"\n", + ret, ERR_peek_error(), ERR_peek_last_error(), cert_file); + */ + if (ERR_peek_last_error() != 0) { + _setSSLError(NULL, ret, __FILE__, __LINE__); + goto fail; + } + } + } + + /* ssl compatibility */ + SSL_CTX_set_options(self->ctx, SSL_OP_ALL); + + verification_mode = SSL_VERIFY_NONE; + if (certreq == PY_SSL_CERT_OPTIONAL) + verification_mode = SSL_VERIFY_PEER; + else if (certreq == PY_SSL_CERT_REQUIRED) + verification_mode = (SSL_VERIFY_PEER | + SSL_VERIFY_FAIL_IF_NO_PEER_CERT); + SSL_CTX_set_verify(self->ctx, verification_mode, + NULL); /* set verify lvl */ + + PySSL_BEGIN_ALLOW_THREADS + self->ssl = SSL_new(self->ctx); /* New ssl struct */ + PySSL_END_ALLOW_THREADS + SSL_set_fd(self->ssl, Sock->sock_fd); /* Set the socket for SSL */ #ifdef SSL_MODE_AUTO_RETRY - SSL_set_mode(self->ssl, SSL_MODE_AUTO_RETRY); + SSL_set_mode(self->ssl, SSL_MODE_AUTO_RETRY); #endif - /* If the socket is in non-blocking mode or timeout mode, set the BIO - * to non-blocking mode (blocking is the default) - */ - if (Sock->sock_timeout >= 0.0) { - /* Set both the read and write BIO's to non-blocking mode */ - BIO_set_nbio(SSL_get_rbio(self->ssl), 1); - BIO_set_nbio(SSL_get_wbio(self->ssl), 1); - } - - PySSL_BEGIN_ALLOW_THREADS - if (socket_type == PY_SSL_CLIENT) - SSL_set_connect_state(self->ssl); - else - SSL_set_accept_state(self->ssl); - PySSL_END_ALLOW_THREADS + /* If the socket is in non-blocking mode or timeout mode, set the BIO + * to non-blocking mode (blocking is the default) + */ + if (Sock->sock_timeout >= 0.0) { + /* Set both the read and write BIO's to non-blocking mode */ + BIO_set_nbio(SSL_get_rbio(self->ssl), 1); + BIO_set_nbio(SSL_get_wbio(self->ssl), 1); + } + + PySSL_BEGIN_ALLOW_THREADS + if (socket_type == PY_SSL_CLIENT) + SSL_set_connect_state(self->ssl); + else + SSL_set_accept_state(self->ssl); + PySSL_END_ALLOW_THREADS - self->Socket = PyWeakref_NewRef((PyObject *) Sock, Py_None); - return self; + self->Socket = PyWeakref_NewRef((PyObject *) Sock, Py_None); + return self; fail: - if (errstr) - PyErr_SetString(PySSLErrorObject, errstr); - Py_DECREF(self); - return NULL; + if (errstr) + PyErr_SetString(PySSLErrorObject, errstr); + Py_DECREF(self); + return NULL; } static PyObject * PySSL_sslwrap(PyObject *self, PyObject *args) { - PySocketSockObject *Sock; - int server_side = 0; - int verification_mode = PY_SSL_CERT_NONE; - int protocol = PY_SSL_VERSION_SSL23; - char *key_file = NULL; - char *cert_file = NULL; - char *cacerts_file = NULL; - char *ciphers = NULL; - - if (!PyArg_ParseTuple(args, "O!i|zziizz:sslwrap", - PySocketModule.Sock_Type, - &Sock, - &server_side, - &key_file, &cert_file, - &verification_mode, &protocol, - &cacerts_file, &ciphers)) - return NULL; - - /* - fprintf(stderr, - "server_side is %d, keyfile %p, certfile %p, verify_mode %d, " - "protocol %d, certs %p\n", - server_side, key_file, cert_file, verification_mode, - protocol, cacerts_file); - */ - - return (PyObject *) newPySSLObject(Sock, key_file, cert_file, - server_side, verification_mode, - protocol, cacerts_file, - ciphers); + PySocketSockObject *Sock; + int server_side = 0; + int verification_mode = PY_SSL_CERT_NONE; + int protocol = PY_SSL_VERSION_SSL23; + char *key_file = NULL; + char *cert_file = NULL; + char *cacerts_file = NULL; + char *ciphers = NULL; + + if (!PyArg_ParseTuple(args, "O!i|zziizz:sslwrap", + PySocketModule.Sock_Type, + &Sock, + &server_side, + &key_file, &cert_file, + &verification_mode, &protocol, + &cacerts_file, &ciphers)) + return NULL; + + /* + fprintf(stderr, + "server_side is %d, keyfile %p, certfile %p, verify_mode %d, " + "protocol %d, certs %p\n", + server_side, key_file, cert_file, verification_mode, + protocol, cacerts_file); + */ + + return (PyObject *) newPySSLObject(Sock, key_file, cert_file, + server_side, verification_mode, + protocol, cacerts_file, + ciphers); } PyDoc_STRVAR(ssl_doc, @@ -453,580 +453,580 @@ static PyObject *PySSL_SSLdo_handshake(PySSLObject *self) { - int ret; - int err; - int sockstate, nonblocking; - PySocketSockObject *sock - = (PySocketSockObject *) PyWeakref_GetObject(self->Socket); - - if (((PyObject*)sock) == Py_None) { - _setSSLError("Underlying socket connection gone", - PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__); - return NULL; - } - - /* just in case the blocking state of the socket has been changed */ - nonblocking = (sock->sock_timeout >= 0.0); - BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking); - BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking); - - /* Actually negotiate SSL connection */ - /* XXX If SSL_do_handshake() returns 0, it's also a failure. */ - sockstate = 0; - do { - PySSL_BEGIN_ALLOW_THREADS - ret = SSL_do_handshake(self->ssl); - err = SSL_get_error(self->ssl, ret); - PySSL_END_ALLOW_THREADS - if(PyErr_CheckSignals()) { - return NULL; - } - if (err == SSL_ERROR_WANT_READ) { - sockstate = check_socket_and_wait_for_timeout(sock, 0); - } else if (err == SSL_ERROR_WANT_WRITE) { - sockstate = check_socket_and_wait_for_timeout(sock, 1); - } else { - sockstate = SOCKET_OPERATION_OK; - } - if (sockstate == SOCKET_HAS_TIMED_OUT) { - PyErr_SetString(PySSLErrorObject, - ERRSTR("The handshake operation timed out")); - return NULL; - } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) { - PyErr_SetString(PySSLErrorObject, - ERRSTR("Underlying socket has been closed.")); - return NULL; - } else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) { - PyErr_SetString(PySSLErrorObject, - ERRSTR("Underlying socket too large for select().")); - return NULL; - } else if (sockstate == SOCKET_IS_NONBLOCKING) { - break; - } - } while (err == SSL_ERROR_WANT_READ || err == SSL_ERROR_WANT_WRITE); - if (ret < 1) - return PySSL_SetError(self, ret, __FILE__, __LINE__); - self->ssl->debug = 1; + int ret; + int err; + int sockstate, nonblocking; + PySocketSockObject *sock + = (PySocketSockObject *) PyWeakref_GetObject(self->Socket); + + if (((PyObject*)sock) == Py_None) { + _setSSLError("Underlying socket connection gone", + PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__); + return NULL; + } - if (self->peer_cert) - X509_free (self->peer_cert); + /* just in case the blocking state of the socket has been changed */ + nonblocking = (sock->sock_timeout >= 0.0); + BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking); + BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking); + + /* Actually negotiate SSL connection */ + /* XXX If SSL_do_handshake() returns 0, it's also a failure. */ + sockstate = 0; + do { PySSL_BEGIN_ALLOW_THREADS - self->peer_cert = SSL_get_peer_certificate(self->ssl); - PySSL_END_ALLOW_THREADS + ret = SSL_do_handshake(self->ssl); + err = SSL_get_error(self->ssl, ret); + PySSL_END_ALLOW_THREADS + if(PyErr_CheckSignals()) { + return NULL; + } + if (err == SSL_ERROR_WANT_READ) { + sockstate = check_socket_and_wait_for_timeout(sock, 0); + } else if (err == SSL_ERROR_WANT_WRITE) { + sockstate = check_socket_and_wait_for_timeout(sock, 1); + } else { + sockstate = SOCKET_OPERATION_OK; + } + if (sockstate == SOCKET_HAS_TIMED_OUT) { + PyErr_SetString(PySSLErrorObject, + ERRSTR("The handshake operation timed out")); + return NULL; + } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) { + PyErr_SetString(PySSLErrorObject, + ERRSTR("Underlying socket has been closed.")); + return NULL; + } else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) { + PyErr_SetString(PySSLErrorObject, + ERRSTR("Underlying socket too large for select().")); + return NULL; + } else if (sockstate == SOCKET_IS_NONBLOCKING) { + break; + } + } while (err == SSL_ERROR_WANT_READ || err == SSL_ERROR_WANT_WRITE); + if (ret < 1) + return PySSL_SetError(self, ret, __FILE__, __LINE__); + self->ssl->debug = 1; + + if (self->peer_cert) + X509_free (self->peer_cert); + PySSL_BEGIN_ALLOW_THREADS + self->peer_cert = SSL_get_peer_certificate(self->ssl); + PySSL_END_ALLOW_THREADS - Py_INCREF(Py_None); - return Py_None; + Py_INCREF(Py_None); + return Py_None; } static PyObject * _create_tuple_for_attribute (ASN1_OBJECT *name, ASN1_STRING *value) { - char namebuf[X509_NAME_MAXLEN]; - int buflen; - PyObject *name_obj; - PyObject *value_obj; - PyObject *attr; - unsigned char *valuebuf = NULL; - - buflen = OBJ_obj2txt(namebuf, sizeof(namebuf), name, 0); - if (buflen < 0) { - _setSSLError(NULL, 0, __FILE__, __LINE__); - goto fail; - } - name_obj = PyUnicode_FromStringAndSize(namebuf, buflen); - if (name_obj == NULL) - goto fail; - - buflen = ASN1_STRING_to_UTF8(&valuebuf, value); - if (buflen < 0) { - _setSSLError(NULL, 0, __FILE__, __LINE__); - Py_DECREF(name_obj); - goto fail; - } - value_obj = PyUnicode_DecodeUTF8((char *) valuebuf, - buflen, "strict"); - OPENSSL_free(valuebuf); - if (value_obj == NULL) { - Py_DECREF(name_obj); - goto fail; - } - attr = PyTuple_New(2); - if (attr == NULL) { - Py_DECREF(name_obj); - Py_DECREF(value_obj); - goto fail; - } - PyTuple_SET_ITEM(attr, 0, name_obj); - PyTuple_SET_ITEM(attr, 1, value_obj); - return attr; + char namebuf[X509_NAME_MAXLEN]; + int buflen; + PyObject *name_obj; + PyObject *value_obj; + PyObject *attr; + unsigned char *valuebuf = NULL; + + buflen = OBJ_obj2txt(namebuf, sizeof(namebuf), name, 0); + if (buflen < 0) { + _setSSLError(NULL, 0, __FILE__, __LINE__); + goto fail; + } + name_obj = PyUnicode_FromStringAndSize(namebuf, buflen); + if (name_obj == NULL) + goto fail; + + buflen = ASN1_STRING_to_UTF8(&valuebuf, value); + if (buflen < 0) { + _setSSLError(NULL, 0, __FILE__, __LINE__); + Py_DECREF(name_obj); + goto fail; + } + value_obj = PyUnicode_DecodeUTF8((char *) valuebuf, + buflen, "strict"); + OPENSSL_free(valuebuf); + if (value_obj == NULL) { + Py_DECREF(name_obj); + goto fail; + } + attr = PyTuple_New(2); + if (attr == NULL) { + Py_DECREF(name_obj); + Py_DECREF(value_obj); + goto fail; + } + PyTuple_SET_ITEM(attr, 0, name_obj); + PyTuple_SET_ITEM(attr, 1, value_obj); + return attr; fail: - return NULL; + return NULL; } static PyObject * _create_tuple_for_X509_NAME (X509_NAME *xname) { - PyObject *dn = NULL; /* tuple which represents the "distinguished name" */ - PyObject *rdn = NULL; /* tuple to hold a "relative distinguished name" */ - PyObject *rdnt; - PyObject *attr = NULL; /* tuple to hold an attribute */ - int entry_count = X509_NAME_entry_count(xname); - X509_NAME_ENTRY *entry; - ASN1_OBJECT *name; - ASN1_STRING *value; - int index_counter; - int rdn_level = -1; - int retcode; - - dn = PyList_New(0); - if (dn == NULL) - return NULL; - /* now create another tuple to hold the top-level RDN */ - rdn = PyList_New(0); - if (rdn == NULL) - goto fail0; - - for (index_counter = 0; - index_counter < entry_count; - index_counter++) - { - entry = X509_NAME_get_entry(xname, index_counter); - - /* check to see if we've gotten to a new RDN */ - if (rdn_level >= 0) { - if (rdn_level != entry->set) { - /* yes, new RDN */ - /* add old RDN to DN */ - rdnt = PyList_AsTuple(rdn); - Py_DECREF(rdn); - if (rdnt == NULL) - goto fail0; - retcode = PyList_Append(dn, rdnt); - Py_DECREF(rdnt); - if (retcode < 0) - goto fail0; - /* create new RDN */ - rdn = PyList_New(0); - if (rdn == NULL) - goto fail0; - } - } - rdn_level = entry->set; - - /* now add this attribute to the current RDN */ - name = X509_NAME_ENTRY_get_object(entry); - value = X509_NAME_ENTRY_get_data(entry); - attr = _create_tuple_for_attribute(name, value); - /* - fprintf(stderr, "RDN level %d, attribute %s: %s\n", - entry->set, - PyBytes_AS_STRING(PyTuple_GET_ITEM(attr, 0)), - PyBytes_AS_STRING(PyTuple_GET_ITEM(attr, 1))); - */ - if (attr == NULL) - goto fail1; - retcode = PyList_Append(rdn, attr); - Py_DECREF(attr); - if (retcode < 0) - goto fail1; - } - /* now, there's typically a dangling RDN */ - if ((rdn != NULL) && (PyList_Size(rdn) > 0)) { - rdnt = PyList_AsTuple(rdn); - Py_DECREF(rdn); - if (rdnt == NULL) - goto fail0; - retcode = PyList_Append(dn, rdnt); - Py_DECREF(rdnt); - if (retcode < 0) - goto fail0; - } - - /* convert list to tuple */ - rdnt = PyList_AsTuple(dn); - Py_DECREF(dn); - if (rdnt == NULL) - return NULL; - return rdnt; + PyObject *dn = NULL; /* tuple which represents the "distinguished name" */ + PyObject *rdn = NULL; /* tuple to hold a "relative distinguished name" */ + PyObject *rdnt; + PyObject *attr = NULL; /* tuple to hold an attribute */ + int entry_count = X509_NAME_entry_count(xname); + X509_NAME_ENTRY *entry; + ASN1_OBJECT *name; + ASN1_STRING *value; + int index_counter; + int rdn_level = -1; + int retcode; + + dn = PyList_New(0); + if (dn == NULL) + return NULL; + /* now create another tuple to hold the top-level RDN */ + rdn = PyList_New(0); + if (rdn == NULL) + goto fail0; + + for (index_counter = 0; + index_counter < entry_count; + index_counter++) + { + entry = X509_NAME_get_entry(xname, index_counter); + + /* check to see if we've gotten to a new RDN */ + if (rdn_level >= 0) { + if (rdn_level != entry->set) { + /* yes, new RDN */ + /* add old RDN to DN */ + rdnt = PyList_AsTuple(rdn); + Py_DECREF(rdn); + if (rdnt == NULL) + goto fail0; + retcode = PyList_Append(dn, rdnt); + Py_DECREF(rdnt); + if (retcode < 0) + goto fail0; + /* create new RDN */ + rdn = PyList_New(0); + if (rdn == NULL) + goto fail0; + } + } + rdn_level = entry->set; + + /* now add this attribute to the current RDN */ + name = X509_NAME_ENTRY_get_object(entry); + value = X509_NAME_ENTRY_get_data(entry); + attr = _create_tuple_for_attribute(name, value); + /* + fprintf(stderr, "RDN level %d, attribute %s: %s\n", + entry->set, + PyBytes_AS_STRING(PyTuple_GET_ITEM(attr, 0)), + PyBytes_AS_STRING(PyTuple_GET_ITEM(attr, 1))); + */ + if (attr == NULL) + goto fail1; + retcode = PyList_Append(rdn, attr); + Py_DECREF(attr); + if (retcode < 0) + goto fail1; + } + /* now, there's typically a dangling RDN */ + if ((rdn != NULL) && (PyList_Size(rdn) > 0)) { + rdnt = PyList_AsTuple(rdn); + Py_DECREF(rdn); + if (rdnt == NULL) + goto fail0; + retcode = PyList_Append(dn, rdnt); + Py_DECREF(rdnt); + if (retcode < 0) + goto fail0; + } + + /* convert list to tuple */ + rdnt = PyList_AsTuple(dn); + Py_DECREF(dn); + if (rdnt == NULL) + return NULL; + return rdnt; fail1: - Py_XDECREF(rdn); + Py_XDECREF(rdn); fail0: - Py_XDECREF(dn); - return NULL; + Py_XDECREF(dn); + return NULL; } static PyObject * _get_peer_alt_names (X509 *certificate) { - /* this code follows the procedure outlined in - OpenSSL's crypto/x509v3/v3_prn.c:X509v3_EXT_print() - function to extract the STACK_OF(GENERAL_NAME), - then iterates through the stack to add the - names. */ - - int i, j; - PyObject *peer_alt_names = Py_None; - PyObject *v, *t; - X509_EXTENSION *ext = NULL; - GENERAL_NAMES *names = NULL; - GENERAL_NAME *name; - X509V3_EXT_METHOD *method; - BIO *biobuf = NULL; - char buf[2048]; - char *vptr; - int len; - /* Issue #2973: ASN1_item_d2i() API changed in OpenSSL 0.9.6m */ + /* this code follows the procedure outlined in + OpenSSL's crypto/x509v3/v3_prn.c:X509v3_EXT_print() + function to extract the STACK_OF(GENERAL_NAME), + then iterates through the stack to add the + names. */ + + int i, j; + PyObject *peer_alt_names = Py_None; + PyObject *v, *t; + X509_EXTENSION *ext = NULL; + GENERAL_NAMES *names = NULL; + GENERAL_NAME *name; + X509V3_EXT_METHOD *method; + BIO *biobuf = NULL; + char buf[2048]; + char *vptr; + int len; + /* Issue #2973: ASN1_item_d2i() API changed in OpenSSL 0.9.6m */ #if OPENSSL_VERSION_NUMBER >= 0x009060dfL - const unsigned char *p; + const unsigned char *p; #else - unsigned char *p; + unsigned char *p; #endif - if (certificate == NULL) - return peer_alt_names; + if (certificate == NULL) + return peer_alt_names; + + /* get a memory buffer */ + biobuf = BIO_new(BIO_s_mem()); - /* get a memory buffer */ - biobuf = BIO_new(BIO_s_mem()); + i = 0; + while ((i = X509_get_ext_by_NID( + certificate, NID_subject_alt_name, i)) >= 0) { + + if (peer_alt_names == Py_None) { + peer_alt_names = PyList_New(0); + if (peer_alt_names == NULL) + goto fail; + } + + /* now decode the altName */ + ext = X509_get_ext(certificate, i); + if(!(method = X509V3_EXT_get(ext))) { + PyErr_SetString + (PySSLErrorObject, + ERRSTR("No method for internalizing subjectAltName!")); + goto fail; + } - i = 0; - while ((i = X509_get_ext_by_NID( - certificate, NID_subject_alt_name, i)) >= 0) { - - if (peer_alt_names == Py_None) { - peer_alt_names = PyList_New(0); - if (peer_alt_names == NULL) - goto fail; - } - - /* now decode the altName */ - ext = X509_get_ext(certificate, i); - if(!(method = X509V3_EXT_get(ext))) { - PyErr_SetString - (PySSLErrorObject, - ERRSTR("No method for internalizing subjectAltName!")); - goto fail; - } - - p = ext->value->data; - if (method->it) - names = (GENERAL_NAMES*) - (ASN1_item_d2i(NULL, - &p, - ext->value->length, - ASN1_ITEM_ptr(method->it))); - else - names = (GENERAL_NAMES*) - (method->d2i(NULL, - &p, - ext->value->length)); - - for(j = 0; j < sk_GENERAL_NAME_num(names); j++) { - - /* get a rendering of each name in the set of names */ - - name = sk_GENERAL_NAME_value(names, j); - if (name->type == GEN_DIRNAME) { - - /* we special-case DirName as a tuple of - tuples of attributes */ - - t = PyTuple_New(2); - if (t == NULL) { - goto fail; - } - - v = PyUnicode_FromString("DirName"); - if (v == NULL) { - Py_DECREF(t); - goto fail; - } - PyTuple_SET_ITEM(t, 0, v); - - v = _create_tuple_for_X509_NAME (name->d.dirn); - if (v == NULL) { - Py_DECREF(t); - goto fail; - } - PyTuple_SET_ITEM(t, 1, v); - - } else { - - /* for everything else, we use the OpenSSL print form */ - - (void) BIO_reset(biobuf); - GENERAL_NAME_print(biobuf, name); - len = BIO_gets(biobuf, buf, sizeof(buf)-1); - if (len < 0) { - _setSSLError(NULL, 0, __FILE__, __LINE__); - goto fail; - } - vptr = strchr(buf, ':'); - if (vptr == NULL) - goto fail; - t = PyTuple_New(2); - if (t == NULL) - goto fail; - v = PyUnicode_FromStringAndSize(buf, (vptr - buf)); - if (v == NULL) { - Py_DECREF(t); - goto fail; - } - PyTuple_SET_ITEM(t, 0, v); - v = PyUnicode_FromStringAndSize((vptr + 1), - (len - (vptr - buf + 1))); - if (v == NULL) { - Py_DECREF(t); - goto fail; - } - PyTuple_SET_ITEM(t, 1, v); - } - - /* and add that rendering to the list */ - - if (PyList_Append(peer_alt_names, t) < 0) { - Py_DECREF(t); - goto fail; - } - Py_DECREF(t); - } - } - BIO_free(biobuf); - if (peer_alt_names != Py_None) { - v = PyList_AsTuple(peer_alt_names); - Py_DECREF(peer_alt_names); - return v; - } else { - return peer_alt_names; - } + p = ext->value->data; + if (method->it) + names = (GENERAL_NAMES*) + (ASN1_item_d2i(NULL, + &p, + ext->value->length, + ASN1_ITEM_ptr(method->it))); + else + names = (GENERAL_NAMES*) + (method->d2i(NULL, + &p, + ext->value->length)); + + for(j = 0; j < sk_GENERAL_NAME_num(names); j++) { + + /* get a rendering of each name in the set of names */ + + name = sk_GENERAL_NAME_value(names, j); + if (name->type == GEN_DIRNAME) { + + /* we special-case DirName as a tuple of + tuples of attributes */ + + t = PyTuple_New(2); + if (t == NULL) { + goto fail; + } + + v = PyUnicode_FromString("DirName"); + if (v == NULL) { + Py_DECREF(t); + goto fail; + } + PyTuple_SET_ITEM(t, 0, v); + + v = _create_tuple_for_X509_NAME (name->d.dirn); + if (v == NULL) { + Py_DECREF(t); + goto fail; + } + PyTuple_SET_ITEM(t, 1, v); + + } else { + + /* for everything else, we use the OpenSSL print form */ + + (void) BIO_reset(biobuf); + GENERAL_NAME_print(biobuf, name); + len = BIO_gets(biobuf, buf, sizeof(buf)-1); + if (len < 0) { + _setSSLError(NULL, 0, __FILE__, __LINE__); + goto fail; + } + vptr = strchr(buf, ':'); + if (vptr == NULL) + goto fail; + t = PyTuple_New(2); + if (t == NULL) + goto fail; + v = PyUnicode_FromStringAndSize(buf, (vptr - buf)); + if (v == NULL) { + Py_DECREF(t); + goto fail; + } + PyTuple_SET_ITEM(t, 0, v); + v = PyUnicode_FromStringAndSize((vptr + 1), + (len - (vptr - buf + 1))); + if (v == NULL) { + Py_DECREF(t); + goto fail; + } + PyTuple_SET_ITEM(t, 1, v); + } + + /* and add that rendering to the list */ + + if (PyList_Append(peer_alt_names, t) < 0) { + Py_DECREF(t); + goto fail; + } + Py_DECREF(t); + } + } + BIO_free(biobuf); + if (peer_alt_names != Py_None) { + v = PyList_AsTuple(peer_alt_names); + Py_DECREF(peer_alt_names); + return v; + } else { + return peer_alt_names; + } fail: - if (biobuf != NULL) - BIO_free(biobuf); + if (biobuf != NULL) + BIO_free(biobuf); - if (peer_alt_names != Py_None) { - Py_XDECREF(peer_alt_names); - } + if (peer_alt_names != Py_None) { + Py_XDECREF(peer_alt_names); + } - return NULL; + return NULL; } static PyObject * _decode_certificate (X509 *certificate, int verbose) { - PyObject *retval = NULL; - BIO *biobuf = NULL; - PyObject *peer; - PyObject *peer_alt_names = NULL; - PyObject *issuer; - PyObject *version; - PyObject *sn_obj; - ASN1_INTEGER *serialNumber; - char buf[2048]; - int len; - ASN1_TIME *notBefore, *notAfter; - PyObject *pnotBefore, *pnotAfter; - - retval = PyDict_New(); - if (retval == NULL) - return NULL; - - peer = _create_tuple_for_X509_NAME( - X509_get_subject_name(certificate)); - if (peer == NULL) - goto fail0; - if (PyDict_SetItemString(retval, (const char *) "subject", peer) < 0) { - Py_DECREF(peer); - goto fail0; - } - Py_DECREF(peer); - - if (verbose) { - issuer = _create_tuple_for_X509_NAME( - X509_get_issuer_name(certificate)); - if (issuer == NULL) - goto fail0; - if (PyDict_SetItemString(retval, (const char *)"issuer", issuer) < 0) { - Py_DECREF(issuer); - goto fail0; - } - Py_DECREF(issuer); - - version = PyLong_FromLong(X509_get_version(certificate) + 1); - if (PyDict_SetItemString(retval, "version", version) < 0) { - Py_DECREF(version); - goto fail0; - } - Py_DECREF(version); - } - - /* get a memory buffer */ - biobuf = BIO_new(BIO_s_mem()); - - if (verbose) { - - (void) BIO_reset(biobuf); - serialNumber = X509_get_serialNumber(certificate); - /* should not exceed 20 octets, 160 bits, so buf is big enough */ - i2a_ASN1_INTEGER(biobuf, serialNumber); - len = BIO_gets(biobuf, buf, sizeof(buf)-1); - if (len < 0) { - _setSSLError(NULL, 0, __FILE__, __LINE__); - goto fail1; - } - sn_obj = PyUnicode_FromStringAndSize(buf, len); - if (sn_obj == NULL) - goto fail1; - if (PyDict_SetItemString(retval, "serialNumber", sn_obj) < 0) { - Py_DECREF(sn_obj); - goto fail1; - } - Py_DECREF(sn_obj); - - (void) BIO_reset(biobuf); - notBefore = X509_get_notBefore(certificate); - ASN1_TIME_print(biobuf, notBefore); - len = BIO_gets(biobuf, buf, sizeof(buf)-1); - if (len < 0) { - _setSSLError(NULL, 0, __FILE__, __LINE__); - goto fail1; - } - pnotBefore = PyUnicode_FromStringAndSize(buf, len); - if (pnotBefore == NULL) - goto fail1; - if (PyDict_SetItemString(retval, "notBefore", pnotBefore) < 0) { - Py_DECREF(pnotBefore); - goto fail1; - } - Py_DECREF(pnotBefore); - } - - (void) BIO_reset(biobuf); - notAfter = X509_get_notAfter(certificate); - ASN1_TIME_print(biobuf, notAfter); - len = BIO_gets(biobuf, buf, sizeof(buf)-1); - if (len < 0) { - _setSSLError(NULL, 0, __FILE__, __LINE__); - goto fail1; - } - pnotAfter = PyUnicode_FromStringAndSize(buf, len); - if (pnotAfter == NULL) - goto fail1; - if (PyDict_SetItemString(retval, "notAfter", pnotAfter) < 0) { - Py_DECREF(pnotAfter); - goto fail1; - } - Py_DECREF(pnotAfter); - - /* Now look for subjectAltName */ - - peer_alt_names = _get_peer_alt_names(certificate); - if (peer_alt_names == NULL) - goto fail1; - else if (peer_alt_names != Py_None) { - if (PyDict_SetItemString(retval, "subjectAltName", - peer_alt_names) < 0) { - Py_DECREF(peer_alt_names); - goto fail1; - } - Py_DECREF(peer_alt_names); - } + PyObject *retval = NULL; + BIO *biobuf = NULL; + PyObject *peer; + PyObject *peer_alt_names = NULL; + PyObject *issuer; + PyObject *version; + PyObject *sn_obj; + ASN1_INTEGER *serialNumber; + char buf[2048]; + int len; + ASN1_TIME *notBefore, *notAfter; + PyObject *pnotBefore, *pnotAfter; + + retval = PyDict_New(); + if (retval == NULL) + return NULL; + + peer = _create_tuple_for_X509_NAME( + X509_get_subject_name(certificate)); + if (peer == NULL) + goto fail0; + if (PyDict_SetItemString(retval, (const char *) "subject", peer) < 0) { + Py_DECREF(peer); + goto fail0; + } + Py_DECREF(peer); + + if (verbose) { + issuer = _create_tuple_for_X509_NAME( + X509_get_issuer_name(certificate)); + if (issuer == NULL) + goto fail0; + if (PyDict_SetItemString(retval, (const char *)"issuer", issuer) < 0) { + Py_DECREF(issuer); + goto fail0; + } + Py_DECREF(issuer); + + version = PyLong_FromLong(X509_get_version(certificate) + 1); + if (PyDict_SetItemString(retval, "version", version) < 0) { + Py_DECREF(version); + goto fail0; + } + Py_DECREF(version); + } + + /* get a memory buffer */ + biobuf = BIO_new(BIO_s_mem()); + + if (verbose) { + + (void) BIO_reset(biobuf); + serialNumber = X509_get_serialNumber(certificate); + /* should not exceed 20 octets, 160 bits, so buf is big enough */ + i2a_ASN1_INTEGER(biobuf, serialNumber); + len = BIO_gets(biobuf, buf, sizeof(buf)-1); + if (len < 0) { + _setSSLError(NULL, 0, __FILE__, __LINE__); + goto fail1; + } + sn_obj = PyUnicode_FromStringAndSize(buf, len); + if (sn_obj == NULL) + goto fail1; + if (PyDict_SetItemString(retval, "serialNumber", sn_obj) < 0) { + Py_DECREF(sn_obj); + goto fail1; + } + Py_DECREF(sn_obj); + + (void) BIO_reset(biobuf); + notBefore = X509_get_notBefore(certificate); + ASN1_TIME_print(biobuf, notBefore); + len = BIO_gets(biobuf, buf, sizeof(buf)-1); + if (len < 0) { + _setSSLError(NULL, 0, __FILE__, __LINE__); + goto fail1; + } + pnotBefore = PyUnicode_FromStringAndSize(buf, len); + if (pnotBefore == NULL) + goto fail1; + if (PyDict_SetItemString(retval, "notBefore", pnotBefore) < 0) { + Py_DECREF(pnotBefore); + goto fail1; + } + Py_DECREF(pnotBefore); + } - BIO_free(biobuf); - return retval; + (void) BIO_reset(biobuf); + notAfter = X509_get_notAfter(certificate); + ASN1_TIME_print(biobuf, notAfter); + len = BIO_gets(biobuf, buf, sizeof(buf)-1); + if (len < 0) { + _setSSLError(NULL, 0, __FILE__, __LINE__); + goto fail1; + } + pnotAfter = PyUnicode_FromStringAndSize(buf, len); + if (pnotAfter == NULL) + goto fail1; + if (PyDict_SetItemString(retval, "notAfter", pnotAfter) < 0) { + Py_DECREF(pnotAfter); + goto fail1; + } + Py_DECREF(pnotAfter); + + /* Now look for subjectAltName */ + + peer_alt_names = _get_peer_alt_names(certificate); + if (peer_alt_names == NULL) + goto fail1; + else if (peer_alt_names != Py_None) { + if (PyDict_SetItemString(retval, "subjectAltName", + peer_alt_names) < 0) { + Py_DECREF(peer_alt_names); + goto fail1; + } + Py_DECREF(peer_alt_names); + } + + BIO_free(biobuf); + return retval; fail1: - if (biobuf != NULL) - BIO_free(biobuf); + if (biobuf != NULL) + BIO_free(biobuf); fail0: - Py_XDECREF(retval); - return NULL; + Py_XDECREF(retval); + return NULL; } static PyObject * PySSL_test_decode_certificate (PyObject *mod, PyObject *args) { - PyObject *retval = NULL; - char *filename = NULL; - X509 *x=NULL; - BIO *cert; - int verbose = 1; - - if (!PyArg_ParseTuple(args, "s|i:test_decode_certificate", - &filename, &verbose)) - return NULL; - - if ((cert=BIO_new(BIO_s_file())) == NULL) { - PyErr_SetString(PySSLErrorObject, - "Can't malloc memory to read file"); - goto fail0; - } - - if (BIO_read_filename(cert,filename) <= 0) { - PyErr_SetString(PySSLErrorObject, - "Can't open file"); - goto fail0; - } - - x = PEM_read_bio_X509_AUX(cert,NULL, NULL, NULL); - if (x == NULL) { - PyErr_SetString(PySSLErrorObject, - "Error decoding PEM-encoded file"); - goto fail0; - } + PyObject *retval = NULL; + char *filename = NULL; + X509 *x=NULL; + BIO *cert; + int verbose = 1; + + if (!PyArg_ParseTuple(args, "s|i:test_decode_certificate", + &filename, &verbose)) + return NULL; + + if ((cert=BIO_new(BIO_s_file())) == NULL) { + PyErr_SetString(PySSLErrorObject, + "Can't malloc memory to read file"); + goto fail0; + } + + if (BIO_read_filename(cert,filename) <= 0) { + PyErr_SetString(PySSLErrorObject, + "Can't open file"); + goto fail0; + } + + x = PEM_read_bio_X509_AUX(cert,NULL, NULL, NULL); + if (x == NULL) { + PyErr_SetString(PySSLErrorObject, + "Error decoding PEM-encoded file"); + goto fail0; + } - retval = _decode_certificate(x, verbose); + retval = _decode_certificate(x, verbose); fail0: - if (cert != NULL) BIO_free(cert); - return retval; + if (cert != NULL) BIO_free(cert); + return retval; } static PyObject * PySSL_peercert(PySSLObject *self, PyObject *args) { - PyObject *retval = NULL; - int len; - int verification; - PyObject *binary_mode = Py_None; - - if (!PyArg_ParseTuple(args, "|O:peer_certificate", &binary_mode)) - return NULL; - - if (!self->peer_cert) - Py_RETURN_NONE; - - if (PyObject_IsTrue(binary_mode)) { - /* return cert in DER-encoded format */ - - unsigned char *bytes_buf = NULL; - - bytes_buf = NULL; - len = i2d_X509(self->peer_cert, &bytes_buf); - if (len < 0) { - PySSL_SetError(self, len, __FILE__, __LINE__); - return NULL; - } - /* this is actually an immutable bytes sequence */ - retval = PyBytes_FromStringAndSize - ((const char *) bytes_buf, len); - OPENSSL_free(bytes_buf); - return retval; - - } else { - - verification = SSL_CTX_get_verify_mode(self->ctx); - if ((verification & SSL_VERIFY_PEER) == 0) - return PyDict_New(); - else - return _decode_certificate (self->peer_cert, 0); - } + PyObject *retval = NULL; + int len; + int verification; + PyObject *binary_mode = Py_None; + + if (!PyArg_ParseTuple(args, "|O:peer_certificate", &binary_mode)) + return NULL; + + if (!self->peer_cert) + Py_RETURN_NONE; + + if (PyObject_IsTrue(binary_mode)) { + /* return cert in DER-encoded format */ + + unsigned char *bytes_buf = NULL; + + bytes_buf = NULL; + len = i2d_X509(self->peer_cert, &bytes_buf); + if (len < 0) { + PySSL_SetError(self, len, __FILE__, __LINE__); + return NULL; + } + /* this is actually an immutable bytes sequence */ + retval = PyBytes_FromStringAndSize + ((const char *) bytes_buf, len); + OPENSSL_free(bytes_buf); + return retval; + + } else { + + verification = SSL_CTX_get_verify_mode(self->ctx); + if ((verification & SSL_VERIFY_PEER) == 0) + return PyDict_New(); + else + return _decode_certificate (self->peer_cert, 0); + } } PyDoc_STRVAR(PySSL_peercert_doc, @@ -1043,60 +1043,60 @@ static PyObject *PySSL_cipher (PySSLObject *self) { - PyObject *retval, *v; - SSL_CIPHER *current; - char *cipher_name; - char *cipher_protocol; - - if (self->ssl == NULL) - return Py_None; - current = SSL_get_current_cipher(self->ssl); - if (current == NULL) - return Py_None; - - retval = PyTuple_New(3); - if (retval == NULL) - return NULL; - - cipher_name = (char *) SSL_CIPHER_get_name(current); - if (cipher_name == NULL) { - PyTuple_SET_ITEM(retval, 0, Py_None); - } else { - v = PyUnicode_FromString(cipher_name); - if (v == NULL) - goto fail0; - PyTuple_SET_ITEM(retval, 0, v); - } - cipher_protocol = SSL_CIPHER_get_version(current); - if (cipher_protocol == NULL) { - PyTuple_SET_ITEM(retval, 1, Py_None); - } else { - v = PyUnicode_FromString(cipher_protocol); - if (v == NULL) - goto fail0; - PyTuple_SET_ITEM(retval, 1, v); - } - v = PyLong_FromLong(SSL_CIPHER_get_bits(current, NULL)); - if (v == NULL) - goto fail0; - PyTuple_SET_ITEM(retval, 2, v); - return retval; + PyObject *retval, *v; + SSL_CIPHER *current; + char *cipher_name; + char *cipher_protocol; + + if (self->ssl == NULL) + return Py_None; + current = SSL_get_current_cipher(self->ssl); + if (current == NULL) + return Py_None; + + retval = PyTuple_New(3); + if (retval == NULL) + return NULL; + + cipher_name = (char *) SSL_CIPHER_get_name(current); + if (cipher_name == NULL) { + PyTuple_SET_ITEM(retval, 0, Py_None); + } else { + v = PyUnicode_FromString(cipher_name); + if (v == NULL) + goto fail0; + PyTuple_SET_ITEM(retval, 0, v); + } + cipher_protocol = SSL_CIPHER_get_version(current); + if (cipher_protocol == NULL) { + PyTuple_SET_ITEM(retval, 1, Py_None); + } else { + v = PyUnicode_FromString(cipher_protocol); + if (v == NULL) + goto fail0; + PyTuple_SET_ITEM(retval, 1, v); + } + v = PyLong_FromLong(SSL_CIPHER_get_bits(current, NULL)); + if (v == NULL) + goto fail0; + PyTuple_SET_ITEM(retval, 2, v); + return retval; fail0: - Py_DECREF(retval); - return NULL; + Py_DECREF(retval); + return NULL; } static void PySSL_dealloc(PySSLObject *self) { - if (self->peer_cert) /* Possible not to have one? */ - X509_free (self->peer_cert); - if (self->ssl) - SSL_free(self->ssl); - if (self->ctx) - SSL_CTX_free(self->ctx); - Py_XDECREF(self->Socket); - PyObject_Del(self); + if (self->peer_cert) /* Possible not to have one? */ + X509_free (self->peer_cert); + if (self->ssl) + SSL_free(self->ssl); + if (self->ctx) + SSL_CTX_free(self->ctx); + Py_XDECREF(self->Socket); + PyObject_Del(self); } /* If the socket has a timeout, do a select()/poll() on the socket. @@ -1107,146 +1107,146 @@ static int check_socket_and_wait_for_timeout(PySocketSockObject *s, int writing) { - fd_set fds; - struct timeval tv; - int rc; - - /* Nothing to do unless we're in timeout mode (not non-blocking) */ - if (s->sock_timeout < 0.0) - return SOCKET_IS_BLOCKING; - else if (s->sock_timeout == 0.0) - return SOCKET_IS_NONBLOCKING; - - /* Guard against closed socket */ - if (s->sock_fd < 0) - return SOCKET_HAS_BEEN_CLOSED; + fd_set fds; + struct timeval tv; + int rc; + + /* Nothing to do unless we're in timeout mode (not non-blocking) */ + if (s->sock_timeout < 0.0) + return SOCKET_IS_BLOCKING; + else if (s->sock_timeout == 0.0) + return SOCKET_IS_NONBLOCKING; + + /* Guard against closed socket */ + if (s->sock_fd < 0) + return SOCKET_HAS_BEEN_CLOSED; - /* Prefer poll, if available, since you can poll() any fd - * which can't be done with select(). */ + /* Prefer poll, if available, since you can poll() any fd + * which can't be done with select(). */ #ifdef HAVE_POLL - { - struct pollfd pollfd; - int timeout; - - pollfd.fd = s->sock_fd; - pollfd.events = writing ? POLLOUT : POLLIN; - - /* s->sock_timeout is in seconds, timeout in ms */ - timeout = (int)(s->sock_timeout * 1000 + 0.5); - PySSL_BEGIN_ALLOW_THREADS - rc = poll(&pollfd, 1, timeout); - PySSL_END_ALLOW_THREADS + { + struct pollfd pollfd; + int timeout; + + pollfd.fd = s->sock_fd; + pollfd.events = writing ? POLLOUT : POLLIN; - goto normal_return; - } + /* s->sock_timeout is in seconds, timeout in ms */ + timeout = (int)(s->sock_timeout * 1000 + 0.5); + PySSL_BEGIN_ALLOW_THREADS + rc = poll(&pollfd, 1, timeout); + PySSL_END_ALLOW_THREADS + + goto normal_return; + } #endif - /* Guard against socket too large for select*/ + /* Guard against socket too large for select*/ #ifndef Py_SOCKET_FD_CAN_BE_GE_FD_SETSIZE - if (s->sock_fd >= FD_SETSIZE) - return SOCKET_TOO_LARGE_FOR_SELECT; + if (s->sock_fd >= FD_SETSIZE) + return SOCKET_TOO_LARGE_FOR_SELECT; #endif - /* Construct the arguments to select */ - tv.tv_sec = (int)s->sock_timeout; - tv.tv_usec = (int)((s->sock_timeout - tv.tv_sec) * 1e6); - FD_ZERO(&fds); - FD_SET(s->sock_fd, &fds); - - /* See if the socket is ready */ - PySSL_BEGIN_ALLOW_THREADS - if (writing) - rc = select(s->sock_fd+1, NULL, &fds, NULL, &tv); - else - rc = select(s->sock_fd+1, &fds, NULL, NULL, &tv); - PySSL_END_ALLOW_THREADS + /* Construct the arguments to select */ + tv.tv_sec = (int)s->sock_timeout; + tv.tv_usec = (int)((s->sock_timeout - tv.tv_sec) * 1e6); + FD_ZERO(&fds); + FD_SET(s->sock_fd, &fds); + + /* See if the socket is ready */ + PySSL_BEGIN_ALLOW_THREADS + if (writing) + rc = select(s->sock_fd+1, NULL, &fds, NULL, &tv); + else + rc = select(s->sock_fd+1, &fds, NULL, NULL, &tv); + PySSL_END_ALLOW_THREADS #ifdef HAVE_POLL normal_return: #endif - /* Return SOCKET_TIMED_OUT on timeout, SOCKET_OPERATION_OK otherwise - (when we are able to write or when there's something to read) */ - return rc == 0 ? SOCKET_HAS_TIMED_OUT : SOCKET_OPERATION_OK; + /* Return SOCKET_TIMED_OUT on timeout, SOCKET_OPERATION_OK otherwise + (when we are able to write or when there's something to read) */ + return rc == 0 ? SOCKET_HAS_TIMED_OUT : SOCKET_OPERATION_OK; } static PyObject *PySSL_SSLwrite(PySSLObject *self, PyObject *args) { - Py_buffer buf; - int len; - int sockstate; - int err; - int nonblocking; - PySocketSockObject *sock - = (PySocketSockObject *) PyWeakref_GetObject(self->Socket); - - if (((PyObject*)sock) == Py_None) { - _setSSLError("Underlying socket connection gone", - PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__); - return NULL; - } - - if (!PyArg_ParseTuple(args, "y*:write", &buf)) - return NULL; - - /* just in case the blocking state of the socket has been changed */ - nonblocking = (sock->sock_timeout >= 0.0); - BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking); - BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking); - - sockstate = check_socket_and_wait_for_timeout(sock, 1); - if (sockstate == SOCKET_HAS_TIMED_OUT) { - PyErr_SetString(PySSLErrorObject, - "The write operation timed out"); - goto error; - } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) { - PyErr_SetString(PySSLErrorObject, - "Underlying socket has been closed."); - goto error; - } else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) { - PyErr_SetString(PySSLErrorObject, - "Underlying socket too large for select()."); - goto error; - } - do { - err = 0; - PySSL_BEGIN_ALLOW_THREADS - len = SSL_write(self->ssl, buf.buf, buf.len); - err = SSL_get_error(self->ssl, len); - PySSL_END_ALLOW_THREADS - if (PyErr_CheckSignals()) { - goto error; - } - if (err == SSL_ERROR_WANT_READ) { - sockstate = - check_socket_and_wait_for_timeout(sock, 0); - } else if (err == SSL_ERROR_WANT_WRITE) { - sockstate = - check_socket_and_wait_for_timeout(sock, 1); - } else { - sockstate = SOCKET_OPERATION_OK; - } - if (sockstate == SOCKET_HAS_TIMED_OUT) { - PyErr_SetString(PySSLErrorObject, - "The write operation timed out"); - goto error; - } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) { - PyErr_SetString(PySSLErrorObject, - "Underlying socket has been closed."); - goto error; - } else if (sockstate == SOCKET_IS_NONBLOCKING) { - break; - } - } while (err == SSL_ERROR_WANT_READ || err == SSL_ERROR_WANT_WRITE); - - PyBuffer_Release(&buf); - if (len > 0) - return PyLong_FromLong(len); - else - return PySSL_SetError(self, len, __FILE__, __LINE__); + Py_buffer buf; + int len; + int sockstate; + int err; + int nonblocking; + PySocketSockObject *sock + = (PySocketSockObject *) PyWeakref_GetObject(self->Socket); + + if (((PyObject*)sock) == Py_None) { + _setSSLError("Underlying socket connection gone", + PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__); + return NULL; + } + + if (!PyArg_ParseTuple(args, "y*:write", &buf)) + return NULL; + + /* just in case the blocking state of the socket has been changed */ + nonblocking = (sock->sock_timeout >= 0.0); + BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking); + BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking); + + sockstate = check_socket_and_wait_for_timeout(sock, 1); + if (sockstate == SOCKET_HAS_TIMED_OUT) { + PyErr_SetString(PySSLErrorObject, + "The write operation timed out"); + goto error; + } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) { + PyErr_SetString(PySSLErrorObject, + "Underlying socket has been closed."); + goto error; + } else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) { + PyErr_SetString(PySSLErrorObject, + "Underlying socket too large for select()."); + goto error; + } + do { + err = 0; + PySSL_BEGIN_ALLOW_THREADS + len = SSL_write(self->ssl, buf.buf, buf.len); + err = SSL_get_error(self->ssl, len); + PySSL_END_ALLOW_THREADS + if (PyErr_CheckSignals()) { + goto error; + } + if (err == SSL_ERROR_WANT_READ) { + sockstate = + check_socket_and_wait_for_timeout(sock, 0); + } else if (err == SSL_ERROR_WANT_WRITE) { + sockstate = + check_socket_and_wait_for_timeout(sock, 1); + } else { + sockstate = SOCKET_OPERATION_OK; + } + if (sockstate == SOCKET_HAS_TIMED_OUT) { + PyErr_SetString(PySSLErrorObject, + "The write operation timed out"); + goto error; + } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) { + PyErr_SetString(PySSLErrorObject, + "Underlying socket has been closed."); + goto error; + } else if (sockstate == SOCKET_IS_NONBLOCKING) { + break; + } + } while (err == SSL_ERROR_WANT_READ || err == SSL_ERROR_WANT_WRITE); + + PyBuffer_Release(&buf); + if (len > 0) + return PyLong_FromLong(len); + else + return PySSL_SetError(self, len, __FILE__, __LINE__); error: - PyBuffer_Release(&buf); - return NULL; + PyBuffer_Release(&buf); + return NULL; } PyDoc_STRVAR(PySSL_SSLwrite_doc, @@ -1257,15 +1257,15 @@ static PyObject *PySSL_SSLpending(PySSLObject *self) { - int count = 0; + int count = 0; - PySSL_BEGIN_ALLOW_THREADS - count = SSL_pending(self->ssl); - PySSL_END_ALLOW_THREADS - if (count < 0) - return PySSL_SetError(self, count, __FILE__, __LINE__); - else - return PyLong_FromLong(count); + PySSL_BEGIN_ALLOW_THREADS + count = SSL_pending(self->ssl); + PySSL_END_ALLOW_THREADS + if (count < 0) + return PySSL_SetError(self, count, __FILE__, __LINE__); + else + return PyLong_FromLong(count); } PyDoc_STRVAR(PySSL_SSLpending_doc, @@ -1276,122 +1276,122 @@ static PyObject *PySSL_SSLread(PySSLObject *self, PyObject *args) { - PyObject *dest = NULL; - Py_buffer buf; - int buf_passed = 0; - int count = -1; - char *mem; - /* XXX this should use Py_ssize_t */ - int len = 1024; - int sockstate; - int err; - int nonblocking; - PySocketSockObject *sock - = (PySocketSockObject *) PyWeakref_GetObject(self->Socket); - - if (((PyObject*)sock) == Py_None) { - _setSSLError("Underlying socket connection gone", - PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__); - return NULL; - } - - if (!PyArg_ParseTuple(args, "|Oi:read", &dest, &count)) - return NULL; - if ((dest == NULL) || (dest == Py_None)) { - if (!(dest = PyByteArray_FromStringAndSize((char *) 0, len))) - return NULL; - mem = PyByteArray_AS_STRING(dest); - } else if (PyLong_Check(dest)) { - len = PyLong_AS_LONG(dest); - if (!(dest = PyByteArray_FromStringAndSize((char *) 0, len))) - return NULL; - mem = PyByteArray_AS_STRING(dest); - } else { - if (PyObject_GetBuffer(dest, &buf, PyBUF_CONTIG) < 0) - return NULL; - mem = buf.buf; - len = buf.len; - if ((count > 0) && (count <= len)) - len = count; - buf_passed = 1; - } - - /* just in case the blocking state of the socket has been changed */ - nonblocking = (sock->sock_timeout >= 0.0); - BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking); - BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking); - - /* first check if there are bytes ready to be read */ - PySSL_BEGIN_ALLOW_THREADS - count = SSL_pending(self->ssl); - PySSL_END_ALLOW_THREADS - - if (!count) { - sockstate = check_socket_and_wait_for_timeout(sock, 0); - if (sockstate == SOCKET_HAS_TIMED_OUT) { - PyErr_SetString(PySSLErrorObject, - "The read operation timed out"); - goto error; - } else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) { - PyErr_SetString(PySSLErrorObject, - "Underlying socket too large for select()."); - goto error; - } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) { - count = 0; - goto done; - } - } - do { - err = 0; - PySSL_BEGIN_ALLOW_THREADS - count = SSL_read(self->ssl, mem, len); - err = SSL_get_error(self->ssl, count); - PySSL_END_ALLOW_THREADS - if (PyErr_CheckSignals()) - goto error; - if (err == SSL_ERROR_WANT_READ) { - sockstate = - check_socket_and_wait_for_timeout(sock, 0); - } else if (err == SSL_ERROR_WANT_WRITE) { - sockstate = - check_socket_and_wait_for_timeout(sock, 1); - } else if ((err == SSL_ERROR_ZERO_RETURN) && - (SSL_get_shutdown(self->ssl) == - SSL_RECEIVED_SHUTDOWN)) - { - count = 0; - goto done; - } else { - sockstate = SOCKET_OPERATION_OK; - } - if (sockstate == SOCKET_HAS_TIMED_OUT) { - PyErr_SetString(PySSLErrorObject, - "The read operation timed out"); - goto error; - } else if (sockstate == SOCKET_IS_NONBLOCKING) { - break; - } - } while (err == SSL_ERROR_WANT_READ || err == SSL_ERROR_WANT_WRITE); - if (count <= 0) { - PySSL_SetError(self, count, __FILE__, __LINE__); - goto error; - } + PyObject *dest = NULL; + Py_buffer buf; + int buf_passed = 0; + int count = -1; + char *mem; + /* XXX this should use Py_ssize_t */ + int len = 1024; + int sockstate; + int err; + int nonblocking; + PySocketSockObject *sock + = (PySocketSockObject *) PyWeakref_GetObject(self->Socket); + + if (((PyObject*)sock) == Py_None) { + _setSSLError("Underlying socket connection gone", + PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__); + return NULL; + } + + if (!PyArg_ParseTuple(args, "|Oi:read", &dest, &count)) + return NULL; + if ((dest == NULL) || (dest == Py_None)) { + if (!(dest = PyByteArray_FromStringAndSize((char *) 0, len))) + return NULL; + mem = PyByteArray_AS_STRING(dest); + } else if (PyLong_Check(dest)) { + len = PyLong_AS_LONG(dest); + if (!(dest = PyByteArray_FromStringAndSize((char *) 0, len))) + return NULL; + mem = PyByteArray_AS_STRING(dest); + } else { + if (PyObject_GetBuffer(dest, &buf, PyBUF_CONTIG) < 0) + return NULL; + mem = buf.buf; + len = buf.len; + if ((count > 0) && (count <= len)) + len = count; + buf_passed = 1; + } + + /* just in case the blocking state of the socket has been changed */ + nonblocking = (sock->sock_timeout >= 0.0); + BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking); + BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking); + + /* first check if there are bytes ready to be read */ + PySSL_BEGIN_ALLOW_THREADS + count = SSL_pending(self->ssl); + PySSL_END_ALLOW_THREADS + + if (!count) { + sockstate = check_socket_and_wait_for_timeout(sock, 0); + if (sockstate == SOCKET_HAS_TIMED_OUT) { + PyErr_SetString(PySSLErrorObject, + "The read operation timed out"); + goto error; + } else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) { + PyErr_SetString(PySSLErrorObject, + "Underlying socket too large for select()."); + goto error; + } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) { + count = 0; + goto done; + } + } + do { + err = 0; + PySSL_BEGIN_ALLOW_THREADS + count = SSL_read(self->ssl, mem, len); + err = SSL_get_error(self->ssl, count); + PySSL_END_ALLOW_THREADS + if (PyErr_CheckSignals()) + goto error; + if (err == SSL_ERROR_WANT_READ) { + sockstate = + check_socket_and_wait_for_timeout(sock, 0); + } else if (err == SSL_ERROR_WANT_WRITE) { + sockstate = + check_socket_and_wait_for_timeout(sock, 1); + } else if ((err == SSL_ERROR_ZERO_RETURN) && + (SSL_get_shutdown(self->ssl) == + SSL_RECEIVED_SHUTDOWN)) + { + count = 0; + goto done; + } else { + sockstate = SOCKET_OPERATION_OK; + } + if (sockstate == SOCKET_HAS_TIMED_OUT) { + PyErr_SetString(PySSLErrorObject, + "The read operation timed out"); + goto error; + } else if (sockstate == SOCKET_IS_NONBLOCKING) { + break; + } + } while (err == SSL_ERROR_WANT_READ || err == SSL_ERROR_WANT_WRITE); + if (count <= 0) { + PySSL_SetError(self, count, __FILE__, __LINE__); + goto error; + } done: - if (!buf_passed) { - PyObject *res = PyBytes_FromStringAndSize(mem, count); - Py_DECREF(dest); - return res; - } else { - PyBuffer_Release(&buf); - return PyLong_FromLong(count); - } + if (!buf_passed) { + PyObject *res = PyBytes_FromStringAndSize(mem, count); + Py_DECREF(dest); + return res; + } else { + PyBuffer_Release(&buf); + return PyLong_FromLong(count); + } error: - if (!buf_passed) { - Py_DECREF(dest); - } else { - PyBuffer_Release(&buf); - } - return NULL; + if (!buf_passed) { + Py_DECREF(dest); + } else { + PyBuffer_Release(&buf); + } + return NULL; } PyDoc_STRVAR(PySSL_SSLread_doc, @@ -1401,84 +1401,84 @@ static PyObject *PySSL_SSLshutdown(PySSLObject *self) { - int err, ssl_err, sockstate, nonblocking; - int zeros = 0; - PySocketSockObject *sock - = (PySocketSockObject *) PyWeakref_GetObject(self->Socket); - - /* Guard against closed socket */ - if ((((PyObject*)sock) == Py_None) || (sock->sock_fd < 0)) { - _setSSLError("Underlying socket connection gone", - PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__); - return NULL; - } - - /* Just in case the blocking state of the socket has been changed */ - nonblocking = (sock->sock_timeout >= 0.0); - BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking); - BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking); - - while (1) { - PySSL_BEGIN_ALLOW_THREADS - /* Disable read-ahead so that unwrap can work correctly. - * Otherwise OpenSSL might read in too much data, - * eating clear text data that happens to be - * transmitted after the SSL shutdown. - * Should be safe to call repeatedly everytime this - * function is used and the shutdown_seen_zero != 0 - * condition is met. - */ - if (self->shutdown_seen_zero) - SSL_set_read_ahead(self->ssl, 0); - err = SSL_shutdown(self->ssl); - PySSL_END_ALLOW_THREADS - /* If err == 1, a secure shutdown with SSL_shutdown() is complete */ - if (err > 0) - break; - if (err == 0) { - /* Don't loop endlessly; instead preserve legacy - behaviour of trying SSL_shutdown() only twice. - This looks necessary for OpenSSL < 0.9.8m */ - if (++zeros > 1) - break; - /* Shutdown was sent, now try receiving */ - self->shutdown_seen_zero = 1; - continue; - } - - /* Possibly retry shutdown until timeout or failure */ - ssl_err = SSL_get_error(self->ssl, err); - if (ssl_err == SSL_ERROR_WANT_READ) - sockstate = check_socket_and_wait_for_timeout(sock, 0); - else if (ssl_err == SSL_ERROR_WANT_WRITE) - sockstate = check_socket_and_wait_for_timeout(sock, 1); - else - break; - if (sockstate == SOCKET_HAS_TIMED_OUT) { - if (ssl_err == SSL_ERROR_WANT_READ) - PyErr_SetString(PySSLErrorObject, - "The read operation timed out"); - else - PyErr_SetString(PySSLErrorObject, - "The write operation timed out"); - return NULL; - } - else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) { - PyErr_SetString(PySSLErrorObject, - "Underlying socket too large for select()."); - return NULL; - } - else if (sockstate != SOCKET_OPERATION_OK) - /* Retain the SSL error code */ - break; - } - - if (err < 0) - return PySSL_SetError(self, err, __FILE__, __LINE__); - else { - Py_INCREF(sock); - return (PyObject *) sock; - } + int err, ssl_err, sockstate, nonblocking; + int zeros = 0; + PySocketSockObject *sock + = (PySocketSockObject *) PyWeakref_GetObject(self->Socket); + + /* Guard against closed socket */ + if ((((PyObject*)sock) == Py_None) || (sock->sock_fd < 0)) { + _setSSLError("Underlying socket connection gone", + PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__); + return NULL; + } + + /* Just in case the blocking state of the socket has been changed */ + nonblocking = (sock->sock_timeout >= 0.0); + BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking); + BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking); + + while (1) { + PySSL_BEGIN_ALLOW_THREADS + /* Disable read-ahead so that unwrap can work correctly. + * Otherwise OpenSSL might read in too much data, + * eating clear text data that happens to be + * transmitted after the SSL shutdown. + * Should be safe to call repeatedly everytime this + * function is used and the shutdown_seen_zero != 0 + * condition is met. + */ + if (self->shutdown_seen_zero) + SSL_set_read_ahead(self->ssl, 0); + err = SSL_shutdown(self->ssl); + PySSL_END_ALLOW_THREADS + /* If err == 1, a secure shutdown with SSL_shutdown() is complete */ + if (err > 0) + break; + if (err == 0) { + /* Don't loop endlessly; instead preserve legacy + behaviour of trying SSL_shutdown() only twice. + This looks necessary for OpenSSL < 0.9.8m */ + if (++zeros > 1) + break; + /* Shutdown was sent, now try receiving */ + self->shutdown_seen_zero = 1; + continue; + } + + /* Possibly retry shutdown until timeout or failure */ + ssl_err = SSL_get_error(self->ssl, err); + if (ssl_err == SSL_ERROR_WANT_READ) + sockstate = check_socket_and_wait_for_timeout(sock, 0); + else if (ssl_err == SSL_ERROR_WANT_WRITE) + sockstate = check_socket_and_wait_for_timeout(sock, 1); + else + break; + if (sockstate == SOCKET_HAS_TIMED_OUT) { + if (ssl_err == SSL_ERROR_WANT_READ) + PyErr_SetString(PySSLErrorObject, + "The read operation timed out"); + else + PyErr_SetString(PySSLErrorObject, + "The write operation timed out"); + return NULL; + } + else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) { + PyErr_SetString(PySSLErrorObject, + "Underlying socket too large for select()."); + return NULL; + } + else if (sockstate != SOCKET_OPERATION_OK) + /* Retain the SSL error code */ + break; + } + + if (err < 0) + return PySSL_SetError(self, err, __FILE__, __LINE__); + else { + Py_INCREF(sock); + return (PyObject *) sock; + } } PyDoc_STRVAR(PySSL_SSLshutdown_doc, @@ -1489,51 +1489,51 @@ static PyMethodDef PySSLMethods[] = { - {"do_handshake", (PyCFunction)PySSL_SSLdo_handshake, METH_NOARGS}, - {"write", (PyCFunction)PySSL_SSLwrite, METH_VARARGS, - PySSL_SSLwrite_doc}, - {"read", (PyCFunction)PySSL_SSLread, METH_VARARGS, - PySSL_SSLread_doc}, - {"pending", (PyCFunction)PySSL_SSLpending, METH_NOARGS, - PySSL_SSLpending_doc}, - {"peer_certificate", (PyCFunction)PySSL_peercert, METH_VARARGS, - PySSL_peercert_doc}, - {"cipher", (PyCFunction)PySSL_cipher, METH_NOARGS}, - {"shutdown", (PyCFunction)PySSL_SSLshutdown, METH_NOARGS, - PySSL_SSLshutdown_doc}, - {NULL, NULL} + {"do_handshake", (PyCFunction)PySSL_SSLdo_handshake, METH_NOARGS}, + {"write", (PyCFunction)PySSL_SSLwrite, METH_VARARGS, + PySSL_SSLwrite_doc}, + {"read", (PyCFunction)PySSL_SSLread, METH_VARARGS, + PySSL_SSLread_doc}, + {"pending", (PyCFunction)PySSL_SSLpending, METH_NOARGS, + PySSL_SSLpending_doc}, + {"peer_certificate", (PyCFunction)PySSL_peercert, METH_VARARGS, + PySSL_peercert_doc}, + {"cipher", (PyCFunction)PySSL_cipher, METH_NOARGS}, + {"shutdown", (PyCFunction)PySSL_SSLshutdown, METH_NOARGS, + PySSL_SSLshutdown_doc}, + {NULL, NULL} }; static PyTypeObject PySSL_Type = { - PyVarObject_HEAD_INIT(NULL, 0) - "ssl.SSLContext", /*tp_name*/ - sizeof(PySSLObject), /*tp_basicsize*/ - 0, /*tp_itemsize*/ - /* methods */ - (destructor)PySSL_dealloc, /*tp_dealloc*/ - 0, /*tp_print*/ - 0, /*tp_getattr*/ - 0, /*tp_setattr*/ - 0, /*tp_reserved*/ - 0, /*tp_repr*/ - 0, /*tp_as_number*/ - 0, /*tp_as_sequence*/ - 0, /*tp_as_mapping*/ - 0, /*tp_hash*/ - 0, /*tp_call*/ - 0, /*tp_str*/ - 0, /*tp_getattro*/ - 0, /*tp_setattro*/ - 0, /*tp_as_buffer*/ - Py_TPFLAGS_DEFAULT, /*tp_flags*/ - 0, /*tp_doc*/ - 0, /*tp_traverse*/ - 0, /*tp_clear*/ - 0, /*tp_richcompare*/ - 0, /*tp_weaklistoffset*/ - 0, /*tp_iter*/ - 0, /*tp_iternext*/ - PySSLMethods, /*tp_methods*/ + PyVarObject_HEAD_INIT(NULL, 0) + "ssl.SSLContext", /*tp_name*/ + sizeof(PySSLObject), /*tp_basicsize*/ + 0, /*tp_itemsize*/ + /* methods */ + (destructor)PySSL_dealloc, /*tp_dealloc*/ + 0, /*tp_print*/ + 0, /*tp_getattr*/ + 0, /*tp_setattr*/ + 0, /*tp_reserved*/ + 0, /*tp_repr*/ + 0, /*tp_as_number*/ + 0, /*tp_as_sequence*/ + 0, /*tp_as_mapping*/ + 0, /*tp_hash*/ + 0, /*tp_call*/ + 0, /*tp_str*/ + 0, /*tp_getattro*/ + 0, /*tp_setattro*/ + 0, /*tp_as_buffer*/ + Py_TPFLAGS_DEFAULT, /*tp_flags*/ + 0, /*tp_doc*/ + 0, /*tp_traverse*/ + 0, /*tp_clear*/ + 0, /*tp_richcompare*/ + 0, /*tp_weaklistoffset*/ + 0, /*tp_iter*/ + 0, /*tp_iternext*/ + PySSLMethods, /*tp_methods*/ }; #ifdef HAVE_OPENSSL_RAND @@ -1547,7 +1547,7 @@ double entropy; if (!PyArg_ParseTuple(args, "s#d:RAND_add", &buf, &len, &entropy)) - return NULL; + return NULL; RAND_add(buf, len, entropy); Py_INCREF(Py_None); return Py_None; @@ -1578,15 +1578,15 @@ int bytes; if (!PyUnicode_Check(arg)) - return PyErr_Format(PyExc_TypeError, - "RAND_egd() expected string, found %s", - Py_TYPE(arg)->tp_name); + return PyErr_Format(PyExc_TypeError, + "RAND_egd() expected string, found %s", + Py_TYPE(arg)->tp_name); bytes = RAND_egd(_PyUnicode_AsString(arg)); if (bytes == -1) { - PyErr_SetString(PySSLErrorObject, - "EGD connection failed or EGD did not return " - "enough data to seed the PRNG"); - return NULL; + PyErr_SetString(PySSLErrorObject, + "EGD connection failed or EGD did not return " + "enough data to seed the PRNG"); + return NULL; } return PyLong_FromLong(bytes); } @@ -1605,19 +1605,19 @@ /* List of functions exported by this module. */ static PyMethodDef PySSL_methods[] = { - {"sslwrap", PySSL_sslwrap, - METH_VARARGS, ssl_doc}, - {"_test_decode_cert", PySSL_test_decode_certificate, - METH_VARARGS}, + {"sslwrap", PySSL_sslwrap, + METH_VARARGS, ssl_doc}, + {"_test_decode_cert", PySSL_test_decode_certificate, + METH_VARARGS}, #ifdef HAVE_OPENSSL_RAND - {"RAND_add", PySSL_RAND_add, METH_VARARGS, - PySSL_RAND_add_doc}, - {"RAND_egd", PySSL_RAND_egd, METH_O, - PySSL_RAND_egd_doc}, - {"RAND_status", (PyCFunction)PySSL_RAND_status, METH_NOARGS, - PySSL_RAND_status_doc}, + {"RAND_add", PySSL_RAND_add, METH_VARARGS, + PySSL_RAND_add_doc}, + {"RAND_egd", PySSL_RAND_egd, METH_O, + PySSL_RAND_egd_doc}, + {"RAND_status", (PyCFunction)PySSL_RAND_status, METH_NOARGS, + PySSL_RAND_status_doc}, #endif - {NULL, NULL} /* Sentinel */ + {NULL, NULL} /* Sentinel */ }; @@ -1629,66 +1629,66 @@ static PyThread_type_lock *_ssl_locks = NULL; static unsigned long _ssl_thread_id_function (void) { - return PyThread_get_thread_ident(); + return PyThread_get_thread_ident(); } static void _ssl_thread_locking_function - (int mode, int n, const char *file, int line) { - /* this function is needed to perform locking on shared data - structures. (Note that OpenSSL uses a number of global data - structures that will be implicitly shared whenever multiple - threads use OpenSSL.) Multi-threaded applications will - crash at random if it is not set. - - locking_function() must be able to handle up to - CRYPTO_num_locks() different mutex locks. It sets the n-th - lock if mode & CRYPTO_LOCK, and releases it otherwise. - - file and line are the file number of the function setting the - lock. They can be useful for debugging. - */ - - if ((_ssl_locks == NULL) || - (n < 0) || ((unsigned)n >= _ssl_locks_count)) - return; - - if (mode & CRYPTO_LOCK) { - PyThread_acquire_lock(_ssl_locks[n], 1); - } else { - PyThread_release_lock(_ssl_locks[n]); - } + (int mode, int n, const char *file, int line) { + /* this function is needed to perform locking on shared data + structures. (Note that OpenSSL uses a number of global data + structures that will be implicitly shared whenever multiple + threads use OpenSSL.) Multi-threaded applications will + crash at random if it is not set. + + locking_function() must be able to handle up to + CRYPTO_num_locks() different mutex locks. It sets the n-th + lock if mode & CRYPTO_LOCK, and releases it otherwise. + + file and line are the file number of the function setting the + lock. They can be useful for debugging. + */ + + if ((_ssl_locks == NULL) || + (n < 0) || ((unsigned)n >= _ssl_locks_count)) + return; + + if (mode & CRYPTO_LOCK) { + PyThread_acquire_lock(_ssl_locks[n], 1); + } else { + PyThread_release_lock(_ssl_locks[n]); + } } static int _setup_ssl_threads(void) { - unsigned int i; + unsigned int i; - if (_ssl_locks == NULL) { - _ssl_locks_count = CRYPTO_num_locks(); - _ssl_locks = (PyThread_type_lock *) - malloc(sizeof(PyThread_type_lock) * _ssl_locks_count); - if (_ssl_locks == NULL) - return 0; - memset(_ssl_locks, 0, - sizeof(PyThread_type_lock) * _ssl_locks_count); - for (i = 0; i < _ssl_locks_count; i++) { - _ssl_locks[i] = PyThread_allocate_lock(); - if (_ssl_locks[i] == NULL) { - unsigned int j; - for (j = 0; j < i; j++) { - PyThread_free_lock(_ssl_locks[j]); - } - free(_ssl_locks); - return 0; - } - } - CRYPTO_set_locking_callback(_ssl_thread_locking_function); - CRYPTO_set_id_callback(_ssl_thread_id_function); - } - return 1; + if (_ssl_locks == NULL) { + _ssl_locks_count = CRYPTO_num_locks(); + _ssl_locks = (PyThread_type_lock *) + malloc(sizeof(PyThread_type_lock) * _ssl_locks_count); + if (_ssl_locks == NULL) + return 0; + memset(_ssl_locks, 0, + sizeof(PyThread_type_lock) * _ssl_locks_count); + for (i = 0; i < _ssl_locks_count; i++) { + _ssl_locks[i] = PyThread_allocate_lock(); + if (_ssl_locks[i] == NULL) { + unsigned int j; + for (j = 0; j < i; j++) { + PyThread_free_lock(_ssl_locks[j]); + } + free(_ssl_locks); + return 0; + } + } + CRYPTO_set_locking_callback(_ssl_thread_locking_function); + CRYPTO_set_id_callback(_ssl_thread_id_function); + } + return 1; } -#endif /* def HAVE_THREAD */ +#endif /* def HAVE_THREAD */ PyDoc_STRVAR(module_doc, "Implementation module for SSL socket operations. See the socket module\n\ @@ -1696,123 +1696,123 @@ static struct PyModuleDef _sslmodule = { - PyModuleDef_HEAD_INIT, - "_ssl", - module_doc, - -1, - PySSL_methods, - NULL, - NULL, - NULL, - NULL + PyModuleDef_HEAD_INIT, + "_ssl", + module_doc, + -1, + PySSL_methods, + NULL, + NULL, + NULL, + NULL }; PyMODINIT_FUNC PyInit__ssl(void) { - PyObject *m, *d, *r; - unsigned long libver; - unsigned int major, minor, fix, patch, status; - PySocketModule_APIObject *socket_api; - - if (PyType_Ready(&PySSL_Type) < 0) - return NULL; - - m = PyModule_Create(&_sslmodule); - if (m == NULL) - return NULL; - d = PyModule_GetDict(m); - - /* Load _socket module and its C API */ - socket_api = PySocketModule_ImportModuleAndAPI(); - if (!socket_api) - return NULL; - PySocketModule = *socket_api; - - /* Init OpenSSL */ - SSL_load_error_strings(); - SSL_library_init(); + PyObject *m, *d, *r; + unsigned long libver; + unsigned int major, minor, fix, patch, status; + PySocketModule_APIObject *socket_api; + + if (PyType_Ready(&PySSL_Type) < 0) + return NULL; + + m = PyModule_Create(&_sslmodule); + if (m == NULL) + return NULL; + d = PyModule_GetDict(m); + + /* Load _socket module and its C API */ + socket_api = PySocketModule_ImportModuleAndAPI(); + if (!socket_api) + return NULL; + PySocketModule = *socket_api; + + /* Init OpenSSL */ + SSL_load_error_strings(); + SSL_library_init(); #ifdef WITH_THREAD - /* note that this will start threading if not already started */ - if (!_setup_ssl_threads()) { - return NULL; - } + /* note that this will start threading if not already started */ + if (!_setup_ssl_threads()) { + return NULL; + } #endif - OpenSSL_add_all_algorithms(); + OpenSSL_add_all_algorithms(); - /* Add symbols to module dict */ - PySSLErrorObject = PyErr_NewException("ssl.SSLError", - PySocketModule.error, - NULL); - if (PySSLErrorObject == NULL) - return NULL; - if (PyDict_SetItemString(d, "SSLError", PySSLErrorObject) != 0) - return NULL; - if (PyDict_SetItemString(d, "SSLType", - (PyObject *)&PySSL_Type) != 0) - return NULL; - PyModule_AddIntConstant(m, "SSL_ERROR_ZERO_RETURN", - PY_SSL_ERROR_ZERO_RETURN); - PyModule_AddIntConstant(m, "SSL_ERROR_WANT_READ", - PY_SSL_ERROR_WANT_READ); - PyModule_AddIntConstant(m, "SSL_ERROR_WANT_WRITE", - PY_SSL_ERROR_WANT_WRITE); - PyModule_AddIntConstant(m, "SSL_ERROR_WANT_X509_LOOKUP", - PY_SSL_ERROR_WANT_X509_LOOKUP); - PyModule_AddIntConstant(m, "SSL_ERROR_SYSCALL", - PY_SSL_ERROR_SYSCALL); - PyModule_AddIntConstant(m, "SSL_ERROR_SSL", - PY_SSL_ERROR_SSL); - PyModule_AddIntConstant(m, "SSL_ERROR_WANT_CONNECT", - PY_SSL_ERROR_WANT_CONNECT); - /* non ssl.h errorcodes */ - PyModule_AddIntConstant(m, "SSL_ERROR_EOF", - PY_SSL_ERROR_EOF); - PyModule_AddIntConstant(m, "SSL_ERROR_INVALID_ERROR_CODE", - PY_SSL_ERROR_INVALID_ERROR_CODE); - /* cert requirements */ - PyModule_AddIntConstant(m, "CERT_NONE", - PY_SSL_CERT_NONE); - PyModule_AddIntConstant(m, "CERT_OPTIONAL", - PY_SSL_CERT_OPTIONAL); - PyModule_AddIntConstant(m, "CERT_REQUIRED", - PY_SSL_CERT_REQUIRED); - - /* protocol versions */ - PyModule_AddIntConstant(m, "PROTOCOL_SSLv2", - PY_SSL_VERSION_SSL2); - PyModule_AddIntConstant(m, "PROTOCOL_SSLv3", - PY_SSL_VERSION_SSL3); - PyModule_AddIntConstant(m, "PROTOCOL_SSLv23", - PY_SSL_VERSION_SSL23); - PyModule_AddIntConstant(m, "PROTOCOL_TLSv1", - PY_SSL_VERSION_TLS1); - - /* OpenSSL version */ - /* SSLeay() gives us the version of the library linked against, - which could be different from the headers version. - */ - libver = SSLeay(); - r = PyLong_FromUnsignedLong(libver); - if (r == NULL) - return NULL; - if (PyModule_AddObject(m, "OPENSSL_VERSION_NUMBER", r)) - return NULL; - status = libver & 0xF; - libver >>= 4; - patch = libver & 0xFF; - libver >>= 8; - fix = libver & 0xFF; - libver >>= 8; - minor = libver & 0xFF; - libver >>= 8; - major = libver & 0xFF; - r = Py_BuildValue("IIIII", major, minor, fix, patch, status); - if (r == NULL || PyModule_AddObject(m, "OPENSSL_VERSION_INFO", r)) - return NULL; - r = PyUnicode_FromString(SSLeay_version(SSLEAY_VERSION)); - if (r == NULL || PyModule_AddObject(m, "OPENSSL_VERSION", r)) - return NULL; + /* Add symbols to module dict */ + PySSLErrorObject = PyErr_NewException("ssl.SSLError", + PySocketModule.error, + NULL); + if (PySSLErrorObject == NULL) + return NULL; + if (PyDict_SetItemString(d, "SSLError", PySSLErrorObject) != 0) + return NULL; + if (PyDict_SetItemString(d, "SSLType", + (PyObject *)&PySSL_Type) != 0) + return NULL; + PyModule_AddIntConstant(m, "SSL_ERROR_ZERO_RETURN", + PY_SSL_ERROR_ZERO_RETURN); + PyModule_AddIntConstant(m, "SSL_ERROR_WANT_READ", + PY_SSL_ERROR_WANT_READ); + PyModule_AddIntConstant(m, "SSL_ERROR_WANT_WRITE", + PY_SSL_ERROR_WANT_WRITE); + PyModule_AddIntConstant(m, "SSL_ERROR_WANT_X509_LOOKUP", + PY_SSL_ERROR_WANT_X509_LOOKUP); + PyModule_AddIntConstant(m, "SSL_ERROR_SYSCALL", + PY_SSL_ERROR_SYSCALL); + PyModule_AddIntConstant(m, "SSL_ERROR_SSL", + PY_SSL_ERROR_SSL); + PyModule_AddIntConstant(m, "SSL_ERROR_WANT_CONNECT", + PY_SSL_ERROR_WANT_CONNECT); + /* non ssl.h errorcodes */ + PyModule_AddIntConstant(m, "SSL_ERROR_EOF", + PY_SSL_ERROR_EOF); + PyModule_AddIntConstant(m, "SSL_ERROR_INVALID_ERROR_CODE", + PY_SSL_ERROR_INVALID_ERROR_CODE); + /* cert requirements */ + PyModule_AddIntConstant(m, "CERT_NONE", + PY_SSL_CERT_NONE); + PyModule_AddIntConstant(m, "CERT_OPTIONAL", + PY_SSL_CERT_OPTIONAL); + PyModule_AddIntConstant(m, "CERT_REQUIRED", + PY_SSL_CERT_REQUIRED); + + /* protocol versions */ + PyModule_AddIntConstant(m, "PROTOCOL_SSLv2", + PY_SSL_VERSION_SSL2); + PyModule_AddIntConstant(m, "PROTOCOL_SSLv3", + PY_SSL_VERSION_SSL3); + PyModule_AddIntConstant(m, "PROTOCOL_SSLv23", + PY_SSL_VERSION_SSL23); + PyModule_AddIntConstant(m, "PROTOCOL_TLSv1", + PY_SSL_VERSION_TLS1); + + /* OpenSSL version */ + /* SSLeay() gives us the version of the library linked against, + which could be different from the headers version. + */ + libver = SSLeay(); + r = PyLong_FromUnsignedLong(libver); + if (r == NULL) + return NULL; + if (PyModule_AddObject(m, "OPENSSL_VERSION_NUMBER", r)) + return NULL; + status = libver & 0xF; + libver >>= 4; + patch = libver & 0xFF; + libver >>= 8; + fix = libver & 0xFF; + libver >>= 8; + minor = libver & 0xFF; + libver >>= 8; + major = libver & 0xFF; + r = Py_BuildValue("IIIII", major, minor, fix, patch, status); + if (r == NULL || PyModule_AddObject(m, "OPENSSL_VERSION_INFO", r)) + return NULL; + r = PyUnicode_FromString(SSLeay_version(SSLEAY_VERSION)); + if (r == NULL || PyModule_AddObject(m, "OPENSSL_VERSION", r)) + return NULL; - return m; + return m; } Modified: python/branches/py3k-jit/Modules/posixmodule.c ============================================================================== --- python/branches/py3k-jit/Modules/posixmodule.c (original) +++ python/branches/py3k-jit/Modules/posixmodule.c Thu May 6 23:49:27 2010 @@ -15,7 +15,7 @@ #ifdef __APPLE__ /* - * Step 1 of support for weak-linking a number of symbols existing on + * Step 1 of support for weak-linking a number of symbols existing on * OSX 10.4 and later, see the comment in the #ifdef __APPLE__ block * at the end of this file for more information. */ @@ -69,7 +69,7 @@ #endif /* HAVE_SYS_STAT_H */ #ifdef HAVE_SYS_WAIT_H -#include /* For WNOHANG */ +#include /* For WNOHANG */ #endif #ifdef HAVE_SIGNAL_H @@ -101,41 +101,41 @@ #if defined(PYCC_VACPP) && defined(PYOS_OS2) #include #else -#if defined(__WATCOMC__) && !defined(__QNX__) /* Watcom compiler */ +#if defined(__WATCOMC__) && !defined(__QNX__) /* Watcom compiler */ #define HAVE_GETCWD 1 #define HAVE_OPENDIR 1 -#define HAVE_SYSTEM 1 +#define HAVE_SYSTEM 1 #if defined(__OS2__) #define HAVE_EXECV 1 #define HAVE_WAIT 1 #endif #include #else -#ifdef __BORLANDC__ /* Borland compiler */ +#ifdef __BORLANDC__ /* Borland compiler */ #define HAVE_EXECV 1 #define HAVE_GETCWD 1 #define HAVE_OPENDIR 1 #define HAVE_PIPE 1 -#define HAVE_SYSTEM 1 +#define HAVE_SYSTEM 1 #define HAVE_WAIT 1 #else -#ifdef _MSC_VER /* Microsoft compiler */ +#ifdef _MSC_VER /* Microsoft compiler */ #define HAVE_GETCWD 1 -#define HAVE_SPAWNV 1 +#define HAVE_SPAWNV 1 #define HAVE_EXECV 1 #define HAVE_PIPE 1 -#define HAVE_SYSTEM 1 -#define HAVE_CWAIT 1 -#define HAVE_FSYNC 1 +#define HAVE_SYSTEM 1 +#define HAVE_CWAIT 1 +#define HAVE_FSYNC 1 #define fsync _commit #else #if defined(PYOS_OS2) && defined(PYCC_GCC) || defined(__VMS) /* Everything needed is defined in PC/os2emx/pyconfig.h or vms/pyconfig.h */ -#else /* all other compilers */ +#else /* all other compilers */ /* Unix functions that the configure script doesn't check for */ #define HAVE_EXECV 1 #define HAVE_FORK 1 -#if defined(__USLC__) && defined(__SCO_VERSION__) /* SCO UDK Compiler */ +#if defined(__USLC__) && defined(__SCO_VERSION__) /* SCO UDK Compiler */ #define HAVE_FORK1 1 #endif #define HAVE_GETCWD 1 @@ -147,9 +147,9 @@ #define HAVE_KILL 1 #define HAVE_OPENDIR 1 #define HAVE_PIPE 1 -#define HAVE_SYSTEM 1 +#define HAVE_SYSTEM 1 #define HAVE_WAIT 1 -#define HAVE_TTYNAME 1 +#define HAVE_TTYNAME 1 #endif /* PYOS_OS2 && PYCC_GCC && __VMS */ #endif /* _MSC_VER */ #endif /* __BORLANDC__ */ @@ -265,7 +265,7 @@ #include "osdefs.h" #include #include -#include /* for ShellExecute() */ +#include /* for ShellExecute() */ #endif /* _MSC_VER */ #if defined(PYCC_VACPP) && defined(PYOS_OS2) @@ -312,13 +312,13 @@ /* choose the appropriate stat and fstat functions and return structs */ #undef STAT #if defined(MS_WIN64) || defined(MS_WINDOWS) -# define STAT win32_stat -# define FSTAT win32_fstat -# define STRUCT_STAT struct win32_stat -#else -# define STAT stat -# define FSTAT fstat -# define STRUCT_STAT struct stat +# define STAT win32_stat +# define FSTAT win32_fstat +# define STRUCT_STAT struct win32_stat +#else +# define STAT stat +# define FSTAT fstat +# define STRUCT_STAT struct stat #endif #if defined(MAJOR_IN_MKDEV) @@ -345,7 +345,7 @@ * as a fd and should merely raise a python exception on error. * The Microsoft CRT doesn't provide an official way to check for the * validity of a file descriptor, but we can emulate its internal behaviour - * by using the exported __pinfo data member and knowledge of the + * by using the exported __pinfo data member and knowledge of the * internal structures involved. * The structures below must be updated for each version of visual studio * according to the file internal.h in the CRT source, until MS comes @@ -357,8 +357,8 @@ * Only the first items must be present. */ typedef struct { - intptr_t osfhnd; - char osfile; + intptr_t osfhnd; + char osfile; } my_ioinfo; extern __declspec(dllimport) char * __pioinfo[]; @@ -373,52 +373,52 @@ int _PyVerify_fd(int fd) { - const int i1 = fd >> IOINFO_L2E; - const int i2 = fd & ((1 << IOINFO_L2E) - 1); - - static int sizeof_ioinfo = 0; - - /* Determine the actual size of the ioinfo structure, - * as used by the CRT loaded in memory - */ - if (sizeof_ioinfo == 0 && __pioinfo[0] != NULL) { - sizeof_ioinfo = _msize(__pioinfo[0]) / IOINFO_ARRAY_ELTS; - } - if (sizeof_ioinfo == 0) { - /* This should not happen... */ - goto fail; - } - - /* See that it isn't a special CLEAR fileno */ - if (fd != _NO_CONSOLE_FILENO) { - /* Microsoft CRT would check that 0<=fd<_nhandle but we can't do that. Instead - * we check pointer validity and other info - */ - if (0 <= i1 && i1 < IOINFO_ARRAYS && __pioinfo[i1] != NULL) { - /* finally, check that the file is open */ - my_ioinfo* info = (my_ioinfo*)(__pioinfo[i1] + i2 * sizeof_ioinfo); - if (info->osfile & FOPEN) { - return 1; - } - } - } + const int i1 = fd >> IOINFO_L2E; + const int i2 = fd & ((1 << IOINFO_L2E) - 1); + + static int sizeof_ioinfo = 0; + + /* Determine the actual size of the ioinfo structure, + * as used by the CRT loaded in memory + */ + if (sizeof_ioinfo == 0 && __pioinfo[0] != NULL) { + sizeof_ioinfo = _msize(__pioinfo[0]) / IOINFO_ARRAY_ELTS; + } + if (sizeof_ioinfo == 0) { + /* This should not happen... */ + goto fail; + } + + /* See that it isn't a special CLEAR fileno */ + if (fd != _NO_CONSOLE_FILENO) { + /* Microsoft CRT would check that 0<=fd<_nhandle but we can't do that. Instead + * we check pointer validity and other info + */ + if (0 <= i1 && i1 < IOINFO_ARRAYS && __pioinfo[i1] != NULL) { + /* finally, check that the file is open */ + my_ioinfo* info = (my_ioinfo*)(__pioinfo[i1] + i2 * sizeof_ioinfo); + if (info->osfile & FOPEN) { + return 1; + } + } + } fail: - errno = EBADF; - return 0; + errno = EBADF; + return 0; } /* the special case of checking dup2. The target fd must be in a sensible range */ static int _PyVerify_fd_dup2(int fd1, int fd2) { - if (!_PyVerify_fd(fd1)) - return 0; - if (fd2 == _NO_CONSOLE_FILENO) - return 0; - if ((unsigned)fd2 < _NHANDLE_) - return 1; - else - return 0; + if (!_PyVerify_fd(fd1)) + return 0; + if (fd2 == _NO_CONSOLE_FILENO) + return 0; + if ((unsigned)fd2 < _NHANDLE_) + return 1; + else + return 0; } #else /* dummy version. _PyVerify_fd() is already defined in fileobject.h */ @@ -439,101 +439,101 @@ static PyObject * convertenviron(void) { - PyObject *d; + PyObject *d; #ifdef MS_WINDOWS - wchar_t **e; + wchar_t **e; #else - char **e; + char **e; +#endif +#if defined(PYOS_OS2) + APIRET rc; + char buffer[1024]; /* OS/2 Provides a Documented Max of 1024 Chars */ #endif - d = PyDict_New(); - if (d == NULL) - return NULL; + + d = PyDict_New(); + if (d == NULL) + return NULL; #ifdef WITH_NEXT_FRAMEWORK - if (environ == NULL) - environ = *_NSGetEnviron(); + if (environ == NULL) + environ = *_NSGetEnviron(); #endif #ifdef MS_WINDOWS - /* _wenviron must be initialized in this way if the program is started - through main() instead of wmain(). */ - _wgetenv(L""); - if (_wenviron == NULL) - return d; - /* This part ignores errors */ - for (e = _wenviron; *e != NULL; e++) { - PyObject *k; - PyObject *v; - wchar_t *p = wcschr(*e, L'='); - if (p == NULL) - continue; - k = PyUnicode_FromWideChar(*e, (Py_ssize_t)(p-*e)); - if (k == NULL) { - PyErr_Clear(); - continue; - } - v = PyUnicode_FromWideChar(p+1, wcslen(p+1)); - if (v == NULL) { - PyErr_Clear(); - Py_DECREF(k); - continue; - } - if (PyDict_GetItem(d, k) == NULL) { - if (PyDict_SetItem(d, k, v) != 0) - PyErr_Clear(); - } - Py_DECREF(k); - Py_DECREF(v); - } -#else - if (environ == NULL) - return d; - /* This part ignores errors */ - for (e = environ; *e != NULL; e++) { - PyObject *k; - PyObject *v; - char *p = strchr(*e, '='); - if (p == NULL) - continue; - k = PyUnicode_Decode(*e, (int)(p-*e), - Py_FileSystemDefaultEncoding, "surrogateescape"); - if (k == NULL) { - PyErr_Clear(); - continue; - } - v = PyUnicode_Decode(p+1, strlen(p+1), - Py_FileSystemDefaultEncoding, "surrogateescape"); - if (v == NULL) { - PyErr_Clear(); - Py_DECREF(k); - continue; - } - if (PyDict_GetItem(d, k) == NULL) { - if (PyDict_SetItem(d, k, v) != 0) - PyErr_Clear(); - } - Py_DECREF(k); - Py_DECREF(v); - } -#endif -#if defined(PYOS_OS2) - { - APIRET rc; - char buffer[1024]; /* OS/2 Provides a Documented Max of 1024 Chars */ - - rc = DosQueryExtLIBPATH(buffer, BEGIN_LIBPATH); - if (rc == NO_ERROR) { /* (not a type, envname is NOT 'BEGIN_LIBPATH') */ - PyObject *v = PyBytes_FromString(buffer); - PyDict_SetItemString(d, "BEGINLIBPATH", v); - Py_DECREF(v); + /* _wenviron must be initialized in this way if the program is started + through main() instead of wmain(). */ + _wgetenv(L""); + if (_wenviron == NULL) + return d; + /* This part ignores errors */ + for (e = _wenviron; *e != NULL; e++) { + PyObject *k; + PyObject *v; + wchar_t *p = wcschr(*e, L'='); + if (p == NULL) + continue; + k = PyUnicode_FromWideChar(*e, (Py_ssize_t)(p-*e)); + if (k == NULL) { + PyErr_Clear(); + continue; } - rc = DosQueryExtLIBPATH(buffer, END_LIBPATH); - if (rc == NO_ERROR) { /* (not a typo, envname is NOT 'END_LIBPATH') */ - PyObject *v = PyBytes_FromString(buffer); - PyDict_SetItemString(d, "ENDLIBPATH", v); - Py_DECREF(v); + v = PyUnicode_FromWideChar(p+1, wcslen(p+1)); + if (v == NULL) { + PyErr_Clear(); + Py_DECREF(k); + continue; + } + if (PyDict_GetItem(d, k) == NULL) { + if (PyDict_SetItem(d, k, v) != 0) + PyErr_Clear(); } + Py_DECREF(k); + Py_DECREF(v); + } +#else + if (environ == NULL) + return d; + /* This part ignores errors */ + for (e = environ; *e != NULL; e++) { + PyObject *k; + PyObject *v; + char *p = strchr(*e, '='); + if (p == NULL) + continue; + k = PyUnicode_Decode(*e, (int)(p-*e), + Py_FileSystemDefaultEncoding, "surrogateescape"); + if (k == NULL) { + PyErr_Clear(); + continue; + } + v = PyUnicode_Decode(p+1, strlen(p+1), + Py_FileSystemDefaultEncoding, "surrogateescape"); + if (v == NULL) { + PyErr_Clear(); + Py_DECREF(k); + continue; + } + if (PyDict_GetItem(d, k) == NULL) { + if (PyDict_SetItem(d, k, v) != 0) + PyErr_Clear(); + } + Py_DECREF(k); + Py_DECREF(v); + } +#endif +#if defined(PYOS_OS2) + rc = DosQueryExtLIBPATH(buffer, BEGIN_LIBPATH); + if (rc == NO_ERROR) { /* (not a type, envname is NOT 'BEGIN_LIBPATH') */ + PyObject *v = PyBytes_FromString(buffer); + PyDict_SetItemString(d, "BEGINLIBPATH", v); + Py_DECREF(v); + } + rc = DosQueryExtLIBPATH(buffer, END_LIBPATH); + if (rc == NO_ERROR) { /* (not a typo, envname is NOT 'END_LIBPATH') */ + PyObject *v = PyBytes_FromString(buffer); + PyDict_SetItemString(d, "ENDLIBPATH", v); + Py_DECREF(v); } #endif - return d; + return d; } /* Set a POSIX-specific error from errno, and return NULL */ @@ -541,19 +541,19 @@ static PyObject * posix_error(void) { - return PyErr_SetFromErrno(PyExc_OSError); + return PyErr_SetFromErrno(PyExc_OSError); } static PyObject * posix_error_with_filename(char* name) { - return PyErr_SetFromErrnoWithFilename(PyExc_OSError, name); + return PyErr_SetFromErrnoWithFilename(PyExc_OSError, name); } #ifdef MS_WINDOWS static PyObject * posix_error_with_unicode_filename(Py_UNICODE* name) { - return PyErr_SetFromErrnoWithUnicodeFilename(PyExc_OSError, name); + return PyErr_SetFromErrnoWithUnicodeFilename(PyExc_OSError, name); } #endif /* MS_WINDOWS */ @@ -561,54 +561,54 @@ static PyObject * posix_error_with_allocated_filename(PyObject* name) { - PyObject *rc = PyErr_SetFromErrnoWithFilename(PyExc_OSError, - PyBytes_AsString(name)); - Py_DECREF(name); - return rc; + PyObject *rc = PyErr_SetFromErrnoWithFilename(PyExc_OSError, + PyBytes_AsString(name)); + Py_DECREF(name); + return rc; } #ifdef MS_WINDOWS static PyObject * win32_error(char* function, char* filename) { - /* XXX We should pass the function name along in the future. - (winreg.c also wants to pass the function name.) - This would however require an additional param to the - Windows error object, which is non-trivial. - */ - errno = GetLastError(); - if (filename) - return PyErr_SetFromWindowsErrWithFilename(errno, filename); - else - return PyErr_SetFromWindowsErr(errno); + /* XXX We should pass the function name along in the future. + (winreg.c also wants to pass the function name.) + This would however require an additional param to the + Windows error object, which is non-trivial. + */ + errno = GetLastError(); + if (filename) + return PyErr_SetFromWindowsErrWithFilename(errno, filename); + else + return PyErr_SetFromWindowsErr(errno); } static PyObject * win32_error_unicode(char* function, Py_UNICODE* filename) { - /* XXX - see win32_error for comments on 'function' */ - errno = GetLastError(); - if (filename) - return PyErr_SetFromWindowsErrWithUnicodeFilename(errno, filename); - else - return PyErr_SetFromWindowsErr(errno); + /* XXX - see win32_error for comments on 'function' */ + errno = GetLastError(); + if (filename) + return PyErr_SetFromWindowsErrWithUnicodeFilename(errno, filename); + else + return PyErr_SetFromWindowsErr(errno); } static int convert_to_unicode(PyObject **param) { - if (PyUnicode_CheckExact(*param)) - Py_INCREF(*param); - else if (PyUnicode_Check(*param)) - /* For a Unicode subtype that's not a Unicode object, - return a true Unicode object with the same data. */ - *param = PyUnicode_FromUnicode(PyUnicode_AS_UNICODE(*param), - PyUnicode_GET_SIZE(*param)); - else - *param = PyUnicode_FromEncodedObject(*param, - Py_FileSystemDefaultEncoding, - "strict"); - return (*param) != NULL; + if (PyUnicode_CheckExact(*param)) + Py_INCREF(*param); + else if (PyUnicode_Check(*param)) + /* For a Unicode subtype that's not a Unicode object, + return a true Unicode object with the same data. */ + *param = PyUnicode_FromUnicode(PyUnicode_AS_UNICODE(*param), + PyUnicode_GET_SIZE(*param)); + else + *param = PyUnicode_FromEncodedObject(*param, + Py_FileSystemDefaultEncoding, + "strict"); + return (*param) != NULL; } #endif /* MS_WINDOWS */ @@ -617,7 +617,7 @@ /********************************************************************** * Helper Function to Trim and Format OS/2 Messages **********************************************************************/ - static void +static void os2_formatmsg(char *msgbuf, int msglen, char *reason) { msgbuf[msglen] = '\0'; /* OS/2 Doesn't Guarantee a Terminator */ @@ -647,7 +647,7 @@ * the file OSO001.MSG in the \OS2 directory hierarchy. * **********************************************************************/ - static char * +static char * os2_strerror(char *msgbuf, int msgbuflen, int errorcode, char *reason) { APIRET rc; @@ -663,7 +663,7 @@ os2_formatmsg(msgbuf, msglen, reason); else PyOS_snprintf(msgbuf, msgbuflen, - "unknown OS error #%d", errorcode); + "unknown OS error #%d", errorcode); return msgbuf; } @@ -672,7 +672,8 @@ errors are not in a global variable e.g. 'errno' nor are they congruent with posix error numbers. */ -static PyObject * os2_error(int code) +static PyObject * +os2_error(int code) { char text[1024]; PyObject *v; @@ -694,99 +695,99 @@ static PyObject * posix_fildes(PyObject *fdobj, int (*func)(int)) { - int fd; - int res; - fd = PyObject_AsFileDescriptor(fdobj); - if (fd < 0) - return NULL; - if (!_PyVerify_fd(fd)) - return posix_error(); - Py_BEGIN_ALLOW_THREADS - res = (*func)(fd); - Py_END_ALLOW_THREADS - if (res < 0) - return posix_error(); - Py_INCREF(Py_None); - return Py_None; + int fd; + int res; + fd = PyObject_AsFileDescriptor(fdobj); + if (fd < 0) + return NULL; + if (!_PyVerify_fd(fd)) + return posix_error(); + Py_BEGIN_ALLOW_THREADS + res = (*func)(fd); + Py_END_ALLOW_THREADS + if (res < 0) + return posix_error(); + Py_INCREF(Py_None); + return Py_None; } static PyObject * posix_1str(PyObject *args, char *format, int (*func)(const char*)) { - PyObject *opath1 = NULL; - char *path1; - int res; - if (!PyArg_ParseTuple(args, format, - PyUnicode_FSConverter, &opath1)) - return NULL; - path1 = PyBytes_AsString(opath1); - Py_BEGIN_ALLOW_THREADS - res = (*func)(path1); - Py_END_ALLOW_THREADS - if (res < 0) - return posix_error_with_allocated_filename(opath1); - Py_DECREF(opath1); - Py_INCREF(Py_None); - return Py_None; + PyObject *opath1 = NULL; + char *path1; + int res; + if (!PyArg_ParseTuple(args, format, + PyUnicode_FSConverter, &opath1)) + return NULL; + path1 = PyBytes_AsString(opath1); + Py_BEGIN_ALLOW_THREADS + res = (*func)(path1); + Py_END_ALLOW_THREADS + if (res < 0) + return posix_error_with_allocated_filename(opath1); + Py_DECREF(opath1); + Py_INCREF(Py_None); + return Py_None; } static PyObject * posix_2str(PyObject *args, - char *format, - int (*func)(const char *, const char *)) + char *format, + int (*func)(const char *, const char *)) { - PyObject *opath1 = NULL, *opath2 = NULL; - char *path1, *path2; - int res; - if (!PyArg_ParseTuple(args, format, - PyUnicode_FSConverter, &opath1, - PyUnicode_FSConverter, &opath2)) { - return NULL; - } - path1 = PyBytes_AsString(opath1); - path2 = PyBytes_AsString(opath2); - Py_BEGIN_ALLOW_THREADS - res = (*func)(path1, path2); - Py_END_ALLOW_THREADS - Py_DECREF(opath1); - Py_DECREF(opath2); - if (res != 0) - /* XXX how to report both path1 and path2??? */ - return posix_error(); - Py_INCREF(Py_None); - return Py_None; + PyObject *opath1 = NULL, *opath2 = NULL; + char *path1, *path2; + int res; + if (!PyArg_ParseTuple(args, format, + PyUnicode_FSConverter, &opath1, + PyUnicode_FSConverter, &opath2)) { + return NULL; + } + path1 = PyBytes_AsString(opath1); + path2 = PyBytes_AsString(opath2); + Py_BEGIN_ALLOW_THREADS + res = (*func)(path1, path2); + Py_END_ALLOW_THREADS + Py_DECREF(opath1); + Py_DECREF(opath2); + if (res != 0) + /* XXX how to report both path1 and path2??? */ + return posix_error(); + Py_INCREF(Py_None); + return Py_None; } #ifdef MS_WINDOWS static PyObject* -win32_1str(PyObject* args, char* func, - char* format, BOOL (__stdcall *funcA)(LPCSTR), - char* wformat, BOOL (__stdcall *funcW)(LPWSTR)) -{ - PyObject *uni; - char *ansi; - BOOL result; - - if (!PyArg_ParseTuple(args, wformat, &uni)) - PyErr_Clear(); - else { - Py_BEGIN_ALLOW_THREADS - result = funcW(PyUnicode_AsUnicode(uni)); - Py_END_ALLOW_THREADS - if (!result) - return win32_error_unicode(func, PyUnicode_AsUnicode(uni)); - Py_INCREF(Py_None); - return Py_None; - } - if (!PyArg_ParseTuple(args, format, &ansi)) - return NULL; - Py_BEGIN_ALLOW_THREADS - result = funcA(ansi); - Py_END_ALLOW_THREADS - if (!result) - return win32_error(func, ansi); - Py_INCREF(Py_None); - return Py_None; +win32_1str(PyObject* args, char* func, + char* format, BOOL (__stdcall *funcA)(LPCSTR), + char* wformat, BOOL (__stdcall *funcW)(LPWSTR)) +{ + PyObject *uni; + char *ansi; + BOOL result; + + if (!PyArg_ParseTuple(args, wformat, &uni)) + PyErr_Clear(); + else { + Py_BEGIN_ALLOW_THREADS + result = funcW(PyUnicode_AsUnicode(uni)); + Py_END_ALLOW_THREADS + if (!result) + return win32_error_unicode(func, PyUnicode_AsUnicode(uni)); + Py_INCREF(Py_None); + return Py_None; + } + if (!PyArg_ParseTuple(args, format, &ansi)) + return NULL; + Py_BEGIN_ALLOW_THREADS + result = funcA(ansi); + Py_END_ALLOW_THREADS + if (!result) + return win32_error(func, ansi); + Py_INCREF(Py_None); + return Py_None; } @@ -798,24 +799,24 @@ static BOOL __stdcall win32_chdir(LPCSTR path) { - char new_path[MAX_PATH+1]; - int result; - char env[4] = "=x:"; - - if(!SetCurrentDirectoryA(path)) - return FALSE; - result = GetCurrentDirectoryA(MAX_PATH+1, new_path); - if (!result) - return FALSE; - /* In the ANSI API, there should not be any paths longer - than MAX_PATH. */ - assert(result <= MAX_PATH+1); - if (strncmp(new_path, "\\\\", 2) == 0 || - strncmp(new_path, "//", 2) == 0) - /* UNC path, nothing to do. */ - return TRUE; - env[1] = new_path[0]; - return SetEnvironmentVariableA(env, new_path); + char new_path[MAX_PATH+1]; + int result; + char env[4] = "=x:"; + + if(!SetCurrentDirectoryA(path)) + return FALSE; + result = GetCurrentDirectoryA(MAX_PATH+1, new_path); + if (!result) + return FALSE; + /* In the ANSI API, there should not be any paths longer + than MAX_PATH. */ + assert(result <= MAX_PATH+1); + if (strncmp(new_path, "\\\\", 2) == 0 || + strncmp(new_path, "//", 2) == 0) + /* UNC path, nothing to do. */ + return TRUE; + env[1] = new_path[0]; + return SetEnvironmentVariableA(env, new_path); } /* The Unicode version differs from the ANSI version @@ -823,36 +824,36 @@ static BOOL __stdcall win32_wchdir(LPCWSTR path) { - wchar_t _new_path[MAX_PATH+1], *new_path = _new_path; - int result; - wchar_t env[4] = L"=x:"; - - if(!SetCurrentDirectoryW(path)) - return FALSE; - result = GetCurrentDirectoryW(MAX_PATH+1, new_path); - if (!result) - return FALSE; - if (result > MAX_PATH+1) { - new_path = malloc(result * sizeof(wchar_t)); - if (!new_path) { - SetLastError(ERROR_OUTOFMEMORY); - return FALSE; - } - result = GetCurrentDirectoryW(result, new_path); - if (!result) { - free(new_path); - return FALSE; - } - } - if (wcsncmp(new_path, L"\\\\", 2) == 0 || - wcsncmp(new_path, L"//", 2) == 0) - /* UNC path, nothing to do. */ - return TRUE; - env[1] = new_path[0]; - result = SetEnvironmentVariableW(env, new_path); - if (new_path != _new_path) - free(new_path); - return result; + wchar_t _new_path[MAX_PATH+1], *new_path = _new_path; + int result; + wchar_t env[4] = L"=x:"; + + if(!SetCurrentDirectoryW(path)) + return FALSE; + result = GetCurrentDirectoryW(MAX_PATH+1, new_path); + if (!result) + return FALSE; + if (result > MAX_PATH+1) { + new_path = malloc(result * sizeof(wchar_t)); + if (!new_path) { + SetLastError(ERROR_OUTOFMEMORY); + return FALSE; + } + result = GetCurrentDirectoryW(result, new_path); + if (!result) { + free(new_path); + return FALSE; + } + } + if (wcsncmp(new_path, L"\\\\", 2) == 0 || + wcsncmp(new_path, L"//", 2) == 0) + /* UNC path, nothing to do. */ + return TRUE; + env[1] = new_path[0]; + result = SetEnvironmentVariableW(env, new_path); + if (new_path != _new_path) + free(new_path); + return result; } #endif @@ -863,7 +864,7 @@ UTC and local time Therefore, we implement our own stat, based on the Win32 API directly. */ -#define HAVE_STAT_NSEC 1 +#define HAVE_STAT_NSEC 1 struct win32_stat{ int st_dev; @@ -887,24 +888,24 @@ static void FILE_TIME_to_time_t_nsec(FILETIME *in_ptr, int *time_out, int* nsec_out) { - /* XXX endianness. Shouldn't matter, as all Windows implementations are little-endian */ - /* Cannot simply cast and dereference in_ptr, - since it might not be aligned properly */ - __int64 in; - memcpy(&in, in_ptr, sizeof(in)); - *nsec_out = (int)(in % 10000000) * 100; /* FILETIME is in units of 100 nsec. */ - /* XXX Win32 supports time stamps past 2038; we currently don't */ - *time_out = Py_SAFE_DOWNCAST((in / 10000000) - secs_between_epochs, __int64, int); + /* XXX endianness. Shouldn't matter, as all Windows implementations are little-endian */ + /* Cannot simply cast and dereference in_ptr, + since it might not be aligned properly */ + __int64 in; + memcpy(&in, in_ptr, sizeof(in)); + *nsec_out = (int)(in % 10000000) * 100; /* FILETIME is in units of 100 nsec. */ + /* XXX Win32 supports time stamps past 2038; we currently don't */ + *time_out = Py_SAFE_DOWNCAST((in / 10000000) - secs_between_epochs, __int64, int); } static void time_t_to_FILE_TIME(int time_in, int nsec_in, FILETIME *out_ptr) { - /* XXX endianness */ - __int64 out; - out = time_in + secs_between_epochs; - out = out * 10000000 + nsec_in / 100; - memcpy(out_ptr, &out, sizeof(out)); + /* XXX endianness */ + __int64 out; + out = time_in + secs_between_epochs; + out = out * 10000000 + nsec_in / 100; + memcpy(out_ptr, &out, sizeof(out)); } /* Below, we *know* that ugo+r is 0444 */ @@ -914,193 +915,193 @@ static int attributes_to_mode(DWORD attr) { - int m = 0; - if (attr & FILE_ATTRIBUTE_DIRECTORY) - m |= _S_IFDIR | 0111; /* IFEXEC for user,group,other */ - else - m |= _S_IFREG; - if (attr & FILE_ATTRIBUTE_READONLY) - m |= 0444; - else - m |= 0666; - return m; + int m = 0; + if (attr & FILE_ATTRIBUTE_DIRECTORY) + m |= _S_IFDIR | 0111; /* IFEXEC for user,group,other */ + else + m |= _S_IFREG; + if (attr & FILE_ATTRIBUTE_READONLY) + m |= 0444; + else + m |= 0666; + return m; } static int attribute_data_to_stat(WIN32_FILE_ATTRIBUTE_DATA *info, struct win32_stat *result) { - memset(result, 0, sizeof(*result)); - result->st_mode = attributes_to_mode(info->dwFileAttributes); - result->st_size = (((__int64)info->nFileSizeHigh)<<32) + info->nFileSizeLow; - FILE_TIME_to_time_t_nsec(&info->ftCreationTime, &result->st_ctime, &result->st_ctime_nsec); - FILE_TIME_to_time_t_nsec(&info->ftLastWriteTime, &result->st_mtime, &result->st_mtime_nsec); - FILE_TIME_to_time_t_nsec(&info->ftLastAccessTime, &result->st_atime, &result->st_atime_nsec); + memset(result, 0, sizeof(*result)); + result->st_mode = attributes_to_mode(info->dwFileAttributes); + result->st_size = (((__int64)info->nFileSizeHigh)<<32) + info->nFileSizeLow; + FILE_TIME_to_time_t_nsec(&info->ftCreationTime, &result->st_ctime, &result->st_ctime_nsec); + FILE_TIME_to_time_t_nsec(&info->ftLastWriteTime, &result->st_mtime, &result->st_mtime_nsec); + FILE_TIME_to_time_t_nsec(&info->ftLastAccessTime, &result->st_atime, &result->st_atime_nsec); - return 0; + return 0; } static BOOL attributes_from_dir(LPCSTR pszFile, LPWIN32_FILE_ATTRIBUTE_DATA pfad) { - HANDLE hFindFile; - WIN32_FIND_DATAA FileData; - hFindFile = FindFirstFileA(pszFile, &FileData); - if (hFindFile == INVALID_HANDLE_VALUE) - return FALSE; - FindClose(hFindFile); - pfad->dwFileAttributes = FileData.dwFileAttributes; - pfad->ftCreationTime = FileData.ftCreationTime; - pfad->ftLastAccessTime = FileData.ftLastAccessTime; - pfad->ftLastWriteTime = FileData.ftLastWriteTime; - pfad->nFileSizeHigh = FileData.nFileSizeHigh; - pfad->nFileSizeLow = FileData.nFileSizeLow; - return TRUE; + HANDLE hFindFile; + WIN32_FIND_DATAA FileData; + hFindFile = FindFirstFileA(pszFile, &FileData); + if (hFindFile == INVALID_HANDLE_VALUE) + return FALSE; + FindClose(hFindFile); + pfad->dwFileAttributes = FileData.dwFileAttributes; + pfad->ftCreationTime = FileData.ftCreationTime; + pfad->ftLastAccessTime = FileData.ftLastAccessTime; + pfad->ftLastWriteTime = FileData.ftLastWriteTime; + pfad->nFileSizeHigh = FileData.nFileSizeHigh; + pfad->nFileSizeLow = FileData.nFileSizeLow; + return TRUE; } static BOOL attributes_from_dir_w(LPCWSTR pszFile, LPWIN32_FILE_ATTRIBUTE_DATA pfad) { - HANDLE hFindFile; - WIN32_FIND_DATAW FileData; - hFindFile = FindFirstFileW(pszFile, &FileData); - if (hFindFile == INVALID_HANDLE_VALUE) - return FALSE; - FindClose(hFindFile); - pfad->dwFileAttributes = FileData.dwFileAttributes; - pfad->ftCreationTime = FileData.ftCreationTime; - pfad->ftLastAccessTime = FileData.ftLastAccessTime; - pfad->ftLastWriteTime = FileData.ftLastWriteTime; - pfad->nFileSizeHigh = FileData.nFileSizeHigh; - pfad->nFileSizeLow = FileData.nFileSizeLow; - return TRUE; + HANDLE hFindFile; + WIN32_FIND_DATAW FileData; + hFindFile = FindFirstFileW(pszFile, &FileData); + if (hFindFile == INVALID_HANDLE_VALUE) + return FALSE; + FindClose(hFindFile); + pfad->dwFileAttributes = FileData.dwFileAttributes; + pfad->ftCreationTime = FileData.ftCreationTime; + pfad->ftLastAccessTime = FileData.ftLastAccessTime; + pfad->ftLastWriteTime = FileData.ftLastWriteTime; + pfad->nFileSizeHigh = FileData.nFileSizeHigh; + pfad->nFileSizeLow = FileData.nFileSizeLow; + return TRUE; } -static int +static int win32_stat(const char* path, struct win32_stat *result) { - WIN32_FILE_ATTRIBUTE_DATA info; - int code; - char *dot; - if (!GetFileAttributesExA(path, GetFileExInfoStandard, &info)) { - if (GetLastError() != ERROR_SHARING_VIOLATION) { - /* Protocol violation: we explicitly clear errno, instead of - setting it to a POSIX error. Callers should use GetLastError. */ - errno = 0; - return -1; - } else { - /* Could not get attributes on open file. Fall back to - reading the directory. */ - if (!attributes_from_dir(path, &info)) { - /* Very strange. This should not fail now */ - errno = 0; - return -1; - } - } - } - code = attribute_data_to_stat(&info, result); - if (code != 0) - return code; - /* Set S_IFEXEC if it is an .exe, .bat, ... */ - dot = strrchr(path, '.'); - if (dot) { - if (stricmp(dot, ".bat") == 0 || - stricmp(dot, ".cmd") == 0 || - stricmp(dot, ".exe") == 0 || - stricmp(dot, ".com") == 0) - result->st_mode |= 0111; - } - return code; + WIN32_FILE_ATTRIBUTE_DATA info; + int code; + char *dot; + if (!GetFileAttributesExA(path, GetFileExInfoStandard, &info)) { + if (GetLastError() != ERROR_SHARING_VIOLATION) { + /* Protocol violation: we explicitly clear errno, instead of + setting it to a POSIX error. Callers should use GetLastError. */ + errno = 0; + return -1; + } else { + /* Could not get attributes on open file. Fall back to + reading the directory. */ + if (!attributes_from_dir(path, &info)) { + /* Very strange. This should not fail now */ + errno = 0; + return -1; + } + } + } + code = attribute_data_to_stat(&info, result); + if (code != 0) + return code; + /* Set S_IFEXEC if it is an .exe, .bat, ... */ + dot = strrchr(path, '.'); + if (dot) { + if (stricmp(dot, ".bat") == 0 || + stricmp(dot, ".cmd") == 0 || + stricmp(dot, ".exe") == 0 || + stricmp(dot, ".com") == 0) + result->st_mode |= 0111; + } + return code; } -static int +static int win32_wstat(const wchar_t* path, struct win32_stat *result) { - int code; - const wchar_t *dot; - WIN32_FILE_ATTRIBUTE_DATA info; - if (!GetFileAttributesExW(path, GetFileExInfoStandard, &info)) { - if (GetLastError() != ERROR_SHARING_VIOLATION) { - /* Protocol violation: we explicitly clear errno, instead of - setting it to a POSIX error. Callers should use GetLastError. */ - errno = 0; - return -1; - } else { - /* Could not get attributes on open file. Fall back to - reading the directory. */ - if (!attributes_from_dir_w(path, &info)) { - /* Very strange. This should not fail now */ - errno = 0; - return -1; - } - } - } - code = attribute_data_to_stat(&info, result); - if (code < 0) - return code; - /* Set IFEXEC if it is an .exe, .bat, ... */ - dot = wcsrchr(path, '.'); - if (dot) { - if (_wcsicmp(dot, L".bat") == 0 || - _wcsicmp(dot, L".cmd") == 0 || - _wcsicmp(dot, L".exe") == 0 || - _wcsicmp(dot, L".com") == 0) - result->st_mode |= 0111; - } - return code; + int code; + const wchar_t *dot; + WIN32_FILE_ATTRIBUTE_DATA info; + if (!GetFileAttributesExW(path, GetFileExInfoStandard, &info)) { + if (GetLastError() != ERROR_SHARING_VIOLATION) { + /* Protocol violation: we explicitly clear errno, instead of + setting it to a POSIX error. Callers should use GetLastError. */ + errno = 0; + return -1; + } else { + /* Could not get attributes on open file. Fall back to + reading the directory. */ + if (!attributes_from_dir_w(path, &info)) { + /* Very strange. This should not fail now */ + errno = 0; + return -1; + } + } + } + code = attribute_data_to_stat(&info, result); + if (code < 0) + return code; + /* Set IFEXEC if it is an .exe, .bat, ... */ + dot = wcsrchr(path, '.'); + if (dot) { + if (_wcsicmp(dot, L".bat") == 0 || + _wcsicmp(dot, L".cmd") == 0 || + _wcsicmp(dot, L".exe") == 0 || + _wcsicmp(dot, L".com") == 0) + result->st_mode |= 0111; + } + return code; } static int win32_fstat(int file_number, struct win32_stat *result) { - BY_HANDLE_FILE_INFORMATION info; - HANDLE h; - int type; - - h = (HANDLE)_get_osfhandle(file_number); - - /* Protocol violation: we explicitly clear errno, instead of - setting it to a POSIX error. Callers should use GetLastError. */ - errno = 0; - - if (h == INVALID_HANDLE_VALUE) { - /* This is really a C library error (invalid file handle). - We set the Win32 error to the closes one matching. */ - SetLastError(ERROR_INVALID_HANDLE); - return -1; - } - memset(result, 0, sizeof(*result)); - - type = GetFileType(h); - if (type == FILE_TYPE_UNKNOWN) { - DWORD error = GetLastError(); - if (error != 0) { - return -1; - } - /* else: valid but unknown file */ - } - - if (type != FILE_TYPE_DISK) { - if (type == FILE_TYPE_CHAR) - result->st_mode = _S_IFCHR; - else if (type == FILE_TYPE_PIPE) - result->st_mode = _S_IFIFO; - return 0; - } - - if (!GetFileInformationByHandle(h, &info)) { - return -1; - } - - /* similar to stat() */ - result->st_mode = attributes_to_mode(info.dwFileAttributes); - result->st_size = (((__int64)info.nFileSizeHigh)<<32) + info.nFileSizeLow; - FILE_TIME_to_time_t_nsec(&info.ftCreationTime, &result->st_ctime, &result->st_ctime_nsec); - FILE_TIME_to_time_t_nsec(&info.ftLastWriteTime, &result->st_mtime, &result->st_mtime_nsec); - FILE_TIME_to_time_t_nsec(&info.ftLastAccessTime, &result->st_atime, &result->st_atime_nsec); - /* specific to fstat() */ - result->st_nlink = info.nNumberOfLinks; - result->st_ino = (((__int64)info.nFileIndexHigh)<<32) + info.nFileIndexLow; - return 0; + BY_HANDLE_FILE_INFORMATION info; + HANDLE h; + int type; + + h = (HANDLE)_get_osfhandle(file_number); + + /* Protocol violation: we explicitly clear errno, instead of + setting it to a POSIX error. Callers should use GetLastError. */ + errno = 0; + + if (h == INVALID_HANDLE_VALUE) { + /* This is really a C library error (invalid file handle). + We set the Win32 error to the closes one matching. */ + SetLastError(ERROR_INVALID_HANDLE); + return -1; + } + memset(result, 0, sizeof(*result)); + + type = GetFileType(h); + if (type == FILE_TYPE_UNKNOWN) { + DWORD error = GetLastError(); + if (error != 0) { + return -1; + } + /* else: valid but unknown file */ + } + + if (type != FILE_TYPE_DISK) { + if (type == FILE_TYPE_CHAR) + result->st_mode = _S_IFCHR; + else if (type == FILE_TYPE_PIPE) + result->st_mode = _S_IFIFO; + return 0; + } + + if (!GetFileInformationByHandle(h, &info)) { + return -1; + } + + /* similar to stat() */ + result->st_mode = attributes_to_mode(info.dwFileAttributes); + result->st_size = (((__int64)info.nFileSizeHigh)<<32) + info.nFileSizeLow; + FILE_TIME_to_time_t_nsec(&info.ftCreationTime, &result->st_ctime, &result->st_ctime_nsec); + FILE_TIME_to_time_t_nsec(&info.ftLastWriteTime, &result->st_mtime, &result->st_mtime_nsec); + FILE_TIME_to_time_t_nsec(&info.ftLastAccessTime, &result->st_atime, &result->st_atime_nsec); + /* specific to fstat() */ + result->st_nlink = info.nNumberOfLinks; + result->st_ino = (((__int64)info.nFileIndexHigh)<<32) + info.nFileIndexLow; + return 0; } #endif /* MS_WINDOWS */ @@ -1117,39 +1118,39 @@ See os.stat for more information."); static PyStructSequence_Field stat_result_fields[] = { - {"st_mode", "protection bits"}, - {"st_ino", "inode"}, - {"st_dev", "device"}, - {"st_nlink", "number of hard links"}, - {"st_uid", "user ID of owner"}, - {"st_gid", "group ID of owner"}, - {"st_size", "total size, in bytes"}, - /* The NULL is replaced with PyStructSequence_UnnamedField later. */ - {NULL, "integer time of last access"}, - {NULL, "integer time of last modification"}, - {NULL, "integer time of last change"}, - {"st_atime", "time of last access"}, - {"st_mtime", "time of last modification"}, - {"st_ctime", "time of last change"}, + {"st_mode", "protection bits"}, + {"st_ino", "inode"}, + {"st_dev", "device"}, + {"st_nlink", "number of hard links"}, + {"st_uid", "user ID of owner"}, + {"st_gid", "group ID of owner"}, + {"st_size", "total size, in bytes"}, + /* The NULL is replaced with PyStructSequence_UnnamedField later. */ + {NULL, "integer time of last access"}, + {NULL, "integer time of last modification"}, + {NULL, "integer time of last change"}, + {"st_atime", "time of last access"}, + {"st_mtime", "time of last modification"}, + {"st_ctime", "time of last change"}, #ifdef HAVE_STRUCT_STAT_ST_BLKSIZE - {"st_blksize", "blocksize for filesystem I/O"}, + {"st_blksize", "blocksize for filesystem I/O"}, #endif #ifdef HAVE_STRUCT_STAT_ST_BLOCKS - {"st_blocks", "number of blocks allocated"}, + {"st_blocks", "number of blocks allocated"}, #endif #ifdef HAVE_STRUCT_STAT_ST_RDEV - {"st_rdev", "device type (if inode device)"}, + {"st_rdev", "device type (if inode device)"}, #endif #ifdef HAVE_STRUCT_STAT_ST_FLAGS - {"st_flags", "user defined flags for file"}, + {"st_flags", "user defined flags for file"}, #endif #ifdef HAVE_STRUCT_STAT_ST_GEN - {"st_gen", "generation number"}, + {"st_gen", "generation number"}, #endif #ifdef HAVE_STRUCT_STAT_ST_BIRTHTIME - {"st_birthtime", "time of creation"}, + {"st_birthtime", "time of creation"}, #endif - {0} + {0} }; #ifdef HAVE_STRUCT_STAT_ST_BLKSIZE @@ -1189,10 +1190,10 @@ #endif static PyStructSequence_Desc stat_result_desc = { - "stat_result", /* name */ - stat_result__doc__, /* doc */ - stat_result_fields, - 10 + "stat_result", /* name */ + stat_result__doc__, /* doc */ + stat_result_fields, + 10 }; PyDoc_STRVAR(statvfs_result__doc__, @@ -1204,24 +1205,24 @@ See os.statvfs for more information."); static PyStructSequence_Field statvfs_result_fields[] = { - {"f_bsize", }, - {"f_frsize", }, - {"f_blocks", }, - {"f_bfree", }, - {"f_bavail", }, - {"f_files", }, - {"f_ffree", }, - {"f_favail", }, - {"f_flag", }, - {"f_namemax",}, - {0} + {"f_bsize", }, + {"f_frsize", }, + {"f_blocks", }, + {"f_bfree", }, + {"f_bavail", }, + {"f_files", }, + {"f_ffree", }, + {"f_favail", }, + {"f_flag", }, + {"f_namemax",}, + {0} }; static PyStructSequence_Desc statvfs_result_desc = { - "statvfs_result", /* name */ - statvfs_result__doc__, /* doc */ - statvfs_result_fields, - 10 + "statvfs_result", /* name */ + statvfs_result__doc__, /* doc */ + statvfs_result_fields, + 10 }; static int initialized; @@ -1232,23 +1233,23 @@ static PyObject * statresult_new(PyTypeObject *type, PyObject *args, PyObject *kwds) { - PyStructSequence *result; - int i; + PyStructSequence *result; + int i; - result = (PyStructSequence*)structseq_new(type, args, kwds); - if (!result) - return NULL; - /* If we have been initialized from a tuple, - st_?time might be set to None. Initialize it - from the int slots. */ - for (i = 7; i <= 9; i++) { - if (result->ob_item[i+3] == Py_None) { - Py_DECREF(Py_None); - Py_INCREF(result->ob_item[i]); - result->ob_item[i+3] = result->ob_item[i]; - } - } - return (PyObject*)result; + result = (PyStructSequence*)structseq_new(type, args, kwds); + if (!result) + return NULL; + /* If we have been initialized from a tuple, + st_?time might be set to None. Initialize it + from the int slots. */ + for (i = 7; i <= 9; i++) { + if (result->ob_item[i+3] == Py_None) { + Py_DECREF(Py_None); + Py_INCREF(result->ob_item[i]); + result->ob_item[i+3] = result->ob_item[i]; + } + } + return (PyObject*)result; } @@ -1266,36 +1267,36 @@ static PyObject* stat_float_times(PyObject* self, PyObject *args) { - int newval = -1; - if (!PyArg_ParseTuple(args, "|i:stat_float_times", &newval)) - return NULL; - if (newval == -1) - /* Return old value */ - return PyBool_FromLong(_stat_float_times); - _stat_float_times = newval; - Py_INCREF(Py_None); - return Py_None; + int newval = -1; + if (!PyArg_ParseTuple(args, "|i:stat_float_times", &newval)) + return NULL; + if (newval == -1) + /* Return old value */ + return PyBool_FromLong(_stat_float_times); + _stat_float_times = newval; + Py_INCREF(Py_None); + return Py_None; } static void fill_time(PyObject *v, int index, time_t sec, unsigned long nsec) { - PyObject *fval,*ival; + PyObject *fval,*ival; #if SIZEOF_TIME_T > SIZEOF_LONG - ival = PyLong_FromLongLong((PY_LONG_LONG)sec); + ival = PyLong_FromLongLong((PY_LONG_LONG)sec); #else - ival = PyLong_FromLong((long)sec); + ival = PyLong_FromLong((long)sec); #endif - if (!ival) - return; - if (_stat_float_times) { - fval = PyFloat_FromDouble(sec + 1e-9*nsec); - } else { - fval = ival; - Py_INCREF(fval); - } - PyStructSequence_SET_ITEM(v, index, ival); - PyStructSequence_SET_ITEM(v, index+3, fval); + if (!ival) + return; + if (_stat_float_times) { + fval = PyFloat_FromDouble(sec + 1e-9*nsec); + } else { + fval = ival; + Py_INCREF(fval); + } + PyStructSequence_SET_ITEM(v, index, ival); + PyStructSequence_SET_ITEM(v, index+3, fval); } /* pack a system stat C structure into the Python stat tuple @@ -1303,99 +1304,99 @@ static PyObject* _pystat_fromstructstat(STRUCT_STAT *st) { - unsigned long ansec, mnsec, cnsec; - PyObject *v = PyStructSequence_New(&StatResultType); - if (v == NULL) - return NULL; + unsigned long ansec, mnsec, cnsec; + PyObject *v = PyStructSequence_New(&StatResultType); + if (v == NULL) + return NULL; - PyStructSequence_SET_ITEM(v, 0, PyLong_FromLong((long)st->st_mode)); + PyStructSequence_SET_ITEM(v, 0, PyLong_FromLong((long)st->st_mode)); #ifdef HAVE_LARGEFILE_SUPPORT - PyStructSequence_SET_ITEM(v, 1, - PyLong_FromLongLong((PY_LONG_LONG)st->st_ino)); + PyStructSequence_SET_ITEM(v, 1, + PyLong_FromLongLong((PY_LONG_LONG)st->st_ino)); #else - PyStructSequence_SET_ITEM(v, 1, PyLong_FromLong((long)st->st_ino)); + PyStructSequence_SET_ITEM(v, 1, PyLong_FromLong((long)st->st_ino)); #endif #if defined(HAVE_LONG_LONG) && !defined(MS_WINDOWS) - PyStructSequence_SET_ITEM(v, 2, - PyLong_FromLongLong((PY_LONG_LONG)st->st_dev)); + PyStructSequence_SET_ITEM(v, 2, + PyLong_FromLongLong((PY_LONG_LONG)st->st_dev)); #else - PyStructSequence_SET_ITEM(v, 2, PyLong_FromLong((long)st->st_dev)); + PyStructSequence_SET_ITEM(v, 2, PyLong_FromLong((long)st->st_dev)); #endif - PyStructSequence_SET_ITEM(v, 3, PyLong_FromLong((long)st->st_nlink)); - PyStructSequence_SET_ITEM(v, 4, PyLong_FromLong((long)st->st_uid)); - PyStructSequence_SET_ITEM(v, 5, PyLong_FromLong((long)st->st_gid)); + PyStructSequence_SET_ITEM(v, 3, PyLong_FromLong((long)st->st_nlink)); + PyStructSequence_SET_ITEM(v, 4, PyLong_FromLong((long)st->st_uid)); + PyStructSequence_SET_ITEM(v, 5, PyLong_FromLong((long)st->st_gid)); #ifdef HAVE_LARGEFILE_SUPPORT - PyStructSequence_SET_ITEM(v, 6, - PyLong_FromLongLong((PY_LONG_LONG)st->st_size)); + PyStructSequence_SET_ITEM(v, 6, + PyLong_FromLongLong((PY_LONG_LONG)st->st_size)); #else - PyStructSequence_SET_ITEM(v, 6, PyLong_FromLong(st->st_size)); + PyStructSequence_SET_ITEM(v, 6, PyLong_FromLong(st->st_size)); #endif #if defined(HAVE_STAT_TV_NSEC) - ansec = st->st_atim.tv_nsec; - mnsec = st->st_mtim.tv_nsec; - cnsec = st->st_ctim.tv_nsec; + ansec = st->st_atim.tv_nsec; + mnsec = st->st_mtim.tv_nsec; + cnsec = st->st_ctim.tv_nsec; #elif defined(HAVE_STAT_TV_NSEC2) - ansec = st->st_atimespec.tv_nsec; - mnsec = st->st_mtimespec.tv_nsec; - cnsec = st->st_ctimespec.tv_nsec; + ansec = st->st_atimespec.tv_nsec; + mnsec = st->st_mtimespec.tv_nsec; + cnsec = st->st_ctimespec.tv_nsec; #elif defined(HAVE_STAT_NSEC) - ansec = st->st_atime_nsec; - mnsec = st->st_mtime_nsec; - cnsec = st->st_ctime_nsec; -#else - ansec = mnsec = cnsec = 0; -#endif - fill_time(v, 7, st->st_atime, ansec); - fill_time(v, 8, st->st_mtime, mnsec); - fill_time(v, 9, st->st_ctime, cnsec); + ansec = st->st_atime_nsec; + mnsec = st->st_mtime_nsec; + cnsec = st->st_ctime_nsec; +#else + ansec = mnsec = cnsec = 0; +#endif + fill_time(v, 7, st->st_atime, ansec); + fill_time(v, 8, st->st_mtime, mnsec); + fill_time(v, 9, st->st_ctime, cnsec); #ifdef HAVE_STRUCT_STAT_ST_BLKSIZE - PyStructSequence_SET_ITEM(v, ST_BLKSIZE_IDX, - PyLong_FromLong((long)st->st_blksize)); + PyStructSequence_SET_ITEM(v, ST_BLKSIZE_IDX, + PyLong_FromLong((long)st->st_blksize)); #endif #ifdef HAVE_STRUCT_STAT_ST_BLOCKS - PyStructSequence_SET_ITEM(v, ST_BLOCKS_IDX, - PyLong_FromLong((long)st->st_blocks)); + PyStructSequence_SET_ITEM(v, ST_BLOCKS_IDX, + PyLong_FromLong((long)st->st_blocks)); #endif #ifdef HAVE_STRUCT_STAT_ST_RDEV - PyStructSequence_SET_ITEM(v, ST_RDEV_IDX, - PyLong_FromLong((long)st->st_rdev)); + PyStructSequence_SET_ITEM(v, ST_RDEV_IDX, + PyLong_FromLong((long)st->st_rdev)); #endif #ifdef HAVE_STRUCT_STAT_ST_GEN - PyStructSequence_SET_ITEM(v, ST_GEN_IDX, - PyLong_FromLong((long)st->st_gen)); + PyStructSequence_SET_ITEM(v, ST_GEN_IDX, + PyLong_FromLong((long)st->st_gen)); #endif #ifdef HAVE_STRUCT_STAT_ST_BIRTHTIME - { - PyObject *val; - unsigned long bsec,bnsec; - bsec = (long)st->st_birthtime; + { + PyObject *val; + unsigned long bsec,bnsec; + bsec = (long)st->st_birthtime; #ifdef HAVE_STAT_TV_NSEC2 - bnsec = st->st_birthtimespec.tv_nsec; + bnsec = st->st_birthtimespec.tv_nsec; #else - bnsec = 0; + bnsec = 0; #endif - if (_stat_float_times) { - val = PyFloat_FromDouble(bsec + 1e-9*bnsec); - } else { - val = PyLong_FromLong((long)bsec); - } - PyStructSequence_SET_ITEM(v, ST_BIRTHTIME_IDX, - val); - } + if (_stat_float_times) { + val = PyFloat_FromDouble(bsec + 1e-9*bnsec); + } else { + val = PyLong_FromLong((long)bsec); + } + PyStructSequence_SET_ITEM(v, ST_BIRTHTIME_IDX, + val); + } #endif #ifdef HAVE_STRUCT_STAT_ST_FLAGS - PyStructSequence_SET_ITEM(v, ST_FLAGS_IDX, - PyLong_FromLong((long)st->st_flags)); + PyStructSequence_SET_ITEM(v, ST_FLAGS_IDX, + PyLong_FromLong((long)st->st_flags)); #endif - if (PyErr_Occurred()) { - Py_DECREF(v); - return NULL; - } + if (PyErr_Occurred()) { + Py_DECREF(v); + return NULL; + } - return v; + return v; } #ifdef MS_WINDOWS @@ -1414,107 +1415,107 @@ static BOOL IsUNCRootA(char *path, int pathlen) { - #define ISSLASH ISSLASHA + #define ISSLASH ISSLASHA - int i, share; + int i, share; - if (pathlen < 5 || !ISSLASH(path[0]) || !ISSLASH(path[1])) - /* minimum UNCRoot is \\x\y */ - return FALSE; - for (i = 2; i < pathlen ; i++) - if (ISSLASH(path[i])) break; - if (i == 2 || i == pathlen) - /* do not allow \\\SHARE or \\SERVER */ - return FALSE; - share = i+1; - for (i = share; i < pathlen; i++) - if (ISSLASH(path[i])) break; - return (i != share && (i == pathlen || i == pathlen-1)); + if (pathlen < 5 || !ISSLASH(path[0]) || !ISSLASH(path[1])) + /* minimum UNCRoot is \\x\y */ + return FALSE; + for (i = 2; i < pathlen ; i++) + if (ISSLASH(path[i])) break; + if (i == 2 || i == pathlen) + /* do not allow \\\SHARE or \\SERVER */ + return FALSE; + share = i+1; + for (i = share; i < pathlen; i++) + if (ISSLASH(path[i])) break; + return (i != share && (i == pathlen || i == pathlen-1)); - #undef ISSLASH + #undef ISSLASH } static BOOL IsUNCRootW(Py_UNICODE *path, int pathlen) { - #define ISSLASH ISSLASHW + #define ISSLASH ISSLASHW - int i, share; + int i, share; - if (pathlen < 5 || !ISSLASH(path[0]) || !ISSLASH(path[1])) - /* minimum UNCRoot is \\x\y */ - return FALSE; - for (i = 2; i < pathlen ; i++) - if (ISSLASH(path[i])) break; - if (i == 2 || i == pathlen) - /* do not allow \\\SHARE or \\SERVER */ - return FALSE; - share = i+1; - for (i = share; i < pathlen; i++) - if (ISSLASH(path[i])) break; - return (i != share && (i == pathlen || i == pathlen-1)); + if (pathlen < 5 || !ISSLASH(path[0]) || !ISSLASH(path[1])) + /* minimum UNCRoot is \\x\y */ + return FALSE; + for (i = 2; i < pathlen ; i++) + if (ISSLASH(path[i])) break; + if (i == 2 || i == pathlen) + /* do not allow \\\SHARE or \\SERVER */ + return FALSE; + share = i+1; + for (i = share; i < pathlen; i++) + if (ISSLASH(path[i])) break; + return (i != share && (i == pathlen || i == pathlen-1)); - #undef ISSLASH + #undef ISSLASH } #endif /* MS_WINDOWS */ static PyObject * posix_do_stat(PyObject *self, PyObject *args, - char *format, + char *format, #ifdef __VMS - int (*statfunc)(const char *, STRUCT_STAT *, ...), + int (*statfunc)(const char *, STRUCT_STAT *, ...), #else - int (*statfunc)(const char *, STRUCT_STAT *), + int (*statfunc)(const char *, STRUCT_STAT *), #endif - char *wformat, - int (*wstatfunc)(const Py_UNICODE *, STRUCT_STAT *)) + char *wformat, + int (*wstatfunc)(const Py_UNICODE *, STRUCT_STAT *)) { - STRUCT_STAT st; - PyObject *opath; - char *path; - int res; - PyObject *result; + STRUCT_STAT st; + PyObject *opath; + char *path; + int res; + PyObject *result; #ifdef MS_WINDOWS - PyUnicodeObject *po; - if (PyArg_ParseTuple(args, wformat, &po)) { - Py_UNICODE *wpath = PyUnicode_AS_UNICODE(po); - - Py_BEGIN_ALLOW_THREADS - /* PyUnicode_AS_UNICODE result OK without - thread lock as it is a simple dereference. */ - res = wstatfunc(wpath, &st); - Py_END_ALLOW_THREADS - - if (res != 0) - return win32_error_unicode("stat", wpath); - return _pystat_fromstructstat(&st); - } - /* Drop the argument parsing error as narrow strings - are also valid. */ - PyErr_Clear(); -#endif - - if (!PyArg_ParseTuple(args, format, - PyUnicode_FSConverter, &opath)) - return NULL; - path = PyBytes_AsString(opath); - Py_BEGIN_ALLOW_THREADS - res = (*statfunc)(path, &st); - Py_END_ALLOW_THREADS + PyUnicodeObject *po; + if (PyArg_ParseTuple(args, wformat, &po)) { + Py_UNICODE *wpath = PyUnicode_AS_UNICODE(po); + + Py_BEGIN_ALLOW_THREADS + /* PyUnicode_AS_UNICODE result OK without + thread lock as it is a simple dereference. */ + res = wstatfunc(wpath, &st); + Py_END_ALLOW_THREADS + + if (res != 0) + return win32_error_unicode("stat", wpath); + return _pystat_fromstructstat(&st); + } + /* Drop the argument parsing error as narrow strings + are also valid. */ + PyErr_Clear(); +#endif + + if (!PyArg_ParseTuple(args, format, + PyUnicode_FSConverter, &opath)) + return NULL; + path = PyBytes_AsString(opath); + Py_BEGIN_ALLOW_THREADS + res = (*statfunc)(path, &st); + Py_END_ALLOW_THREADS - if (res != 0) { + if (res != 0) { #ifdef MS_WINDOWS - result = win32_error("stat", path); + result = win32_error("stat", path); #else - result = posix_error_with_filename(path); + result = posix_error_with_filename(path); #endif - } - else - result = _pystat_fromstructstat(&st); + } + else + result = _pystat_fromstructstat(&st); - Py_DECREF(opath); - return result; + Py_DECREF(opath); + return result; } /* POSIX methods */ @@ -1530,53 +1531,53 @@ static PyObject * posix_access(PyObject *self, PyObject *args) { - PyObject *opath; - char *path; - int mode; - + PyObject *opath; + char *path; + int mode; + #ifdef MS_WINDOWS - DWORD attr; - PyUnicodeObject *po; - if (PyArg_ParseTuple(args, "Ui:access", &po, &mode)) { - Py_BEGIN_ALLOW_THREADS - /* PyUnicode_AS_UNICODE OK without thread lock as - it is a simple dereference. */ - attr = GetFileAttributesW(PyUnicode_AS_UNICODE(po)); - Py_END_ALLOW_THREADS - goto finish; - } - /* Drop the argument parsing error as narrow strings - are also valid. */ - PyErr_Clear(); - if (!PyArg_ParseTuple(args, "O&i:access", - PyUnicode_FSConverter, &opath, &mode)) - return NULL; - path = PyBytes_AsString(opath); - Py_BEGIN_ALLOW_THREADS - attr = GetFileAttributesA(path); - Py_END_ALLOW_THREADS - Py_DECREF(opath); + DWORD attr; + PyUnicodeObject *po; + if (PyArg_ParseTuple(args, "Ui:access", &po, &mode)) { + Py_BEGIN_ALLOW_THREADS + /* PyUnicode_AS_UNICODE OK without thread lock as + it is a simple dereference. */ + attr = GetFileAttributesW(PyUnicode_AS_UNICODE(po)); + Py_END_ALLOW_THREADS + goto finish; + } + /* Drop the argument parsing error as narrow strings + are also valid. */ + PyErr_Clear(); + if (!PyArg_ParseTuple(args, "O&i:access", + PyUnicode_FSConverter, &opath, &mode)) + return NULL; + path = PyBytes_AsString(opath); + Py_BEGIN_ALLOW_THREADS + attr = GetFileAttributesA(path); + Py_END_ALLOW_THREADS + Py_DECREF(opath); finish: - if (attr == 0xFFFFFFFF) - /* File does not exist, or cannot read attributes */ - return PyBool_FromLong(0); - /* Access is possible if either write access wasn't requested, or - the file isn't read-only, or if it's a directory, as there are - no read-only directories on Windows. */ - return PyBool_FromLong(!(mode & 2) - || !(attr & FILE_ATTRIBUTE_READONLY) - || (attr & FILE_ATTRIBUTE_DIRECTORY)); -#else - int res; - if (!PyArg_ParseTuple(args, "O&i:access", - PyUnicode_FSConverter, &opath, &mode)) - return NULL; - path = PyBytes_AsString(opath); - Py_BEGIN_ALLOW_THREADS - res = access(path, mode); - Py_END_ALLOW_THREADS - Py_DECREF(opath); - return PyBool_FromLong(res == 0); + if (attr == 0xFFFFFFFF) + /* File does not exist, or cannot read attributes */ + return PyBool_FromLong(0); + /* Access is possible if either write access wasn't requested, or + the file isn't read-only, or if it's a directory, as there are + no read-only directories on Windows. */ + return PyBool_FromLong(!(mode & 2) + || !(attr & FILE_ATTRIBUTE_READONLY) + || (attr & FILE_ATTRIBUTE_DIRECTORY)); +#else + int res; + if (!PyArg_ParseTuple(args, "O&i:access", + PyUnicode_FSConverter, &opath, &mode)) + return NULL; + path = PyBytes_AsString(opath); + Py_BEGIN_ALLOW_THREADS + res = access(path, mode); + Py_END_ALLOW_THREADS + Py_DECREF(opath); + return PyBool_FromLong(res == 0); #endif } @@ -1601,26 +1602,26 @@ static PyObject * posix_ttyname(PyObject *self, PyObject *args) { - int id; - char *ret; + int id; + char *ret; - if (!PyArg_ParseTuple(args, "i:ttyname", &id)) - return NULL; + if (!PyArg_ParseTuple(args, "i:ttyname", &id)) + return NULL; #if defined(__VMS) - /* file descriptor 0 only, the default input device (stdin) */ - if (id == 0) { - ret = ttyname(); - } - else { - ret = NULL; - } -#else - ret = ttyname(id); -#endif - if (ret == NULL) - return posix_error(); - return PyUnicode_FromString(ret); + /* file descriptor 0 only, the default input device (stdin) */ + if (id == 0) { + ret = ttyname(); + } + else { + ret = NULL; + } +#else + ret = ttyname(id); +#endif + if (ret == NULL) + return posix_error(); + return PyUnicode_FromString(ret); } #endif @@ -1632,17 +1633,17 @@ static PyObject * posix_ctermid(PyObject *self, PyObject *noargs) { - char *ret; - char buffer[L_ctermid]; + char *ret; + char buffer[L_ctermid]; #ifdef USE_CTERMID_R - ret = ctermid_r(buffer); + ret = ctermid_r(buffer); #else - ret = ctermid(buffer); + ret = ctermid(buffer); #endif - if (ret == NULL) - return posix_error(); - return PyUnicode_FromString(buffer); + if (ret == NULL) + return posix_error(); + return PyUnicode_FromString(buffer); } #endif @@ -1654,13 +1655,13 @@ posix_chdir(PyObject *self, PyObject *args) { #ifdef MS_WINDOWS - return win32_1str(args, "chdir", "y:chdir", win32_chdir, "U:chdir", win32_wchdir); + return win32_1str(args, "chdir", "y:chdir", win32_chdir, "U:chdir", win32_wchdir); #elif defined(PYOS_OS2) && defined(PYCC_GCC) - return posix_1str(args, "O&:chdir", _chdir2); + return posix_1str(args, "O&:chdir", _chdir2); #elif defined(__VMS) - return posix_1str(args, "O&:chdir", (int (*)(const char *))chdir); + return posix_1str(args, "O&:chdir", (int (*)(const char *))chdir); #else - return posix_1str(args, "O&:chdir", chdir); + return posix_1str(args, "O&:chdir", chdir); #endif } @@ -1673,7 +1674,7 @@ static PyObject * posix_fchdir(PyObject *self, PyObject *fdobj) { - return posix_fildes(fdobj, fchdir); + return posix_fildes(fdobj, fchdir); } #endif /* HAVE_FCHDIR */ @@ -1685,73 +1686,73 @@ static PyObject * posix_chmod(PyObject *self, PyObject *args) { - PyObject *opath = NULL; - char *path = NULL; - int i; - int res; + PyObject *opath = NULL; + char *path = NULL; + int i; + int res; #ifdef MS_WINDOWS - DWORD attr; - PyUnicodeObject *po; - if (PyArg_ParseTuple(args, "Ui|:chmod", &po, &i)) { - Py_BEGIN_ALLOW_THREADS - attr = GetFileAttributesW(PyUnicode_AS_UNICODE(po)); - if (attr != 0xFFFFFFFF) { - if (i & _S_IWRITE) - attr &= ~FILE_ATTRIBUTE_READONLY; - else - attr |= FILE_ATTRIBUTE_READONLY; - res = SetFileAttributesW(PyUnicode_AS_UNICODE(po), attr); - } - else - res = 0; - Py_END_ALLOW_THREADS - if (!res) - return win32_error_unicode("chmod", - PyUnicode_AS_UNICODE(po)); - Py_INCREF(Py_None); - return Py_None; - } - /* Drop the argument parsing error as narrow strings - are also valid. */ - PyErr_Clear(); - - if (!PyArg_ParseTuple(args, "O&i:chmod", PyUnicode_FSConverter, - &opath, &i)) - return NULL; - path = PyBytes_AsString(opath); - Py_BEGIN_ALLOW_THREADS - attr = GetFileAttributesA(path); - if (attr != 0xFFFFFFFF) { - if (i & _S_IWRITE) - attr &= ~FILE_ATTRIBUTE_READONLY; - else - attr |= FILE_ATTRIBUTE_READONLY; - res = SetFileAttributesA(path, attr); - } - else - res = 0; - Py_END_ALLOW_THREADS - if (!res) { - win32_error("chmod", path); - Py_DECREF(opath); - return NULL; - } - Py_DECREF(opath); - Py_INCREF(Py_None); - return Py_None; + DWORD attr; + PyUnicodeObject *po; + if (PyArg_ParseTuple(args, "Ui|:chmod", &po, &i)) { + Py_BEGIN_ALLOW_THREADS + attr = GetFileAttributesW(PyUnicode_AS_UNICODE(po)); + if (attr != 0xFFFFFFFF) { + if (i & _S_IWRITE) + attr &= ~FILE_ATTRIBUTE_READONLY; + else + attr |= FILE_ATTRIBUTE_READONLY; + res = SetFileAttributesW(PyUnicode_AS_UNICODE(po), attr); + } + else + res = 0; + Py_END_ALLOW_THREADS + if (!res) + return win32_error_unicode("chmod", + PyUnicode_AS_UNICODE(po)); + Py_INCREF(Py_None); + return Py_None; + } + /* Drop the argument parsing error as narrow strings + are also valid. */ + PyErr_Clear(); + + if (!PyArg_ParseTuple(args, "O&i:chmod", PyUnicode_FSConverter, + &opath, &i)) + return NULL; + path = PyBytes_AsString(opath); + Py_BEGIN_ALLOW_THREADS + attr = GetFileAttributesA(path); + if (attr != 0xFFFFFFFF) { + if (i & _S_IWRITE) + attr &= ~FILE_ATTRIBUTE_READONLY; + else + attr |= FILE_ATTRIBUTE_READONLY; + res = SetFileAttributesA(path, attr); + } + else + res = 0; + Py_END_ALLOW_THREADS + if (!res) { + win32_error("chmod", path); + Py_DECREF(opath); + return NULL; + } + Py_DECREF(opath); + Py_INCREF(Py_None); + return Py_None; #else /* MS_WINDOWS */ - if (!PyArg_ParseTuple(args, "O&i:chmod", PyUnicode_FSConverter, - &opath, &i)) - return NULL; - path = PyBytes_AsString(opath); - Py_BEGIN_ALLOW_THREADS - res = chmod(path, i); - Py_END_ALLOW_THREADS - if (res < 0) - return posix_error_with_allocated_filename(opath); - Py_DECREF(opath); - Py_INCREF(Py_None); - return Py_None; + if (!PyArg_ParseTuple(args, "O&i:chmod", PyUnicode_FSConverter, + &opath, &i)) + return NULL; + path = PyBytes_AsString(opath); + Py_BEGIN_ALLOW_THREADS + res = chmod(path, i); + Py_END_ALLOW_THREADS + if (res < 0) + return posix_error_with_allocated_filename(opath); + Py_DECREF(opath); + Py_INCREF(Py_None); + return Py_None; #endif } @@ -1764,15 +1765,15 @@ static PyObject * posix_fchmod(PyObject *self, PyObject *args) { - int fd, mode, res; - if (!PyArg_ParseTuple(args, "ii:fchmod", &fd, &mode)) - return NULL; - Py_BEGIN_ALLOW_THREADS - res = fchmod(fd, mode); - Py_END_ALLOW_THREADS - if (res < 0) - return posix_error(); - Py_RETURN_NONE; + int fd, mode, res; + if (!PyArg_ParseTuple(args, "ii:fchmod", &fd, &mode)) + return NULL; + Py_BEGIN_ALLOW_THREADS + res = fchmod(fd, mode); + Py_END_ALLOW_THREADS + if (res < 0) + return posix_error(); + Py_RETURN_NONE; } #endif /* HAVE_FCHMOD */ @@ -1785,21 +1786,21 @@ static PyObject * posix_lchmod(PyObject *self, PyObject *args) { - PyObject *opath; - char *path; - int i; - int res; - if (!PyArg_ParseTuple(args, "O&i:lchmod", PyUnicode_FSConverter, - &opath, &i)) - return NULL; - path = PyBytes_AsString(opath); - Py_BEGIN_ALLOW_THREADS - res = lchmod(path, i); - Py_END_ALLOW_THREADS - if (res < 0) - return posix_error_with_allocated_filename(opath); - Py_DECREF(opath); - Py_RETURN_NONE; + PyObject *opath; + char *path; + int i; + int res; + if (!PyArg_ParseTuple(args, "O&i:lchmod", PyUnicode_FSConverter, + &opath, &i)) + return NULL; + path = PyBytes_AsString(opath); + Py_BEGIN_ALLOW_THREADS + res = lchmod(path, i); + Py_END_ALLOW_THREADS + if (res < 0) + return posix_error_with_allocated_filename(opath); + Py_DECREF(opath); + Py_RETURN_NONE; } #endif /* HAVE_LCHMOD */ @@ -1812,22 +1813,22 @@ static PyObject * posix_chflags(PyObject *self, PyObject *args) { - PyObject *opath; - char *path; - unsigned long flags; - int res; - if (!PyArg_ParseTuple(args, "O&k:chflags", - PyUnicode_FSConverter, &opath, &flags)) - return NULL; - path = PyBytes_AsString(opath); - Py_BEGIN_ALLOW_THREADS - res = chflags(path, flags); - Py_END_ALLOW_THREADS - if (res < 0) - return posix_error_with_allocated_filename(opath); - Py_DECREF(opath); - Py_INCREF(Py_None); - return Py_None; + PyObject *opath; + char *path; + unsigned long flags; + int res; + if (!PyArg_ParseTuple(args, "O&k:chflags", + PyUnicode_FSConverter, &opath, &flags)) + return NULL; + path = PyBytes_AsString(opath); + Py_BEGIN_ALLOW_THREADS + res = chflags(path, flags); + Py_END_ALLOW_THREADS + if (res < 0) + return posix_error_with_allocated_filename(opath); + Py_DECREF(opath); + Py_INCREF(Py_None); + return Py_None; } #endif /* HAVE_CHFLAGS */ @@ -1840,22 +1841,22 @@ static PyObject * posix_lchflags(PyObject *self, PyObject *args) { - PyObject *opath; - char *path; - unsigned long flags; - int res; - if (!PyArg_ParseTuple(args, "O&k:lchflags", - PyUnicode_FSConverter, &opath, &flags)) - return NULL; - path = PyBytes_AsString(opath); - Py_BEGIN_ALLOW_THREADS - res = lchflags(path, flags); - Py_END_ALLOW_THREADS - if (res < 0) - return posix_error_with_allocated_filename(opath); - Py_DECREF(opath); - Py_INCREF(Py_None); - return Py_None; + PyObject *opath; + char *path; + unsigned long flags; + int res; + if (!PyArg_ParseTuple(args, "O&k:lchflags", + PyUnicode_FSConverter, &opath, &flags)) + return NULL; + path = PyBytes_AsString(opath); + Py_BEGIN_ALLOW_THREADS + res = lchflags(path, flags); + Py_END_ALLOW_THREADS + if (res < 0) + return posix_error_with_allocated_filename(opath); + Py_DECREF(opath); + Py_INCREF(Py_None); + return Py_None; } #endif /* HAVE_LCHFLAGS */ @@ -1867,7 +1868,7 @@ static PyObject * posix_chroot(PyObject *self, PyObject *args) { - return posix_1str(args, "O&:chroot", chroot); + return posix_1str(args, "O&:chroot", chroot); } #endif @@ -1910,23 +1911,23 @@ static PyObject * posix_chown(PyObject *self, PyObject *args) { - PyObject *opath; - char *path; - long uid, gid; - int res; - if (!PyArg_ParseTuple(args, "O&ll:chown", - PyUnicode_FSConverter, &opath, - &uid, &gid)) - return NULL; - path = PyBytes_AsString(opath); - Py_BEGIN_ALLOW_THREADS - res = chown(path, (uid_t) uid, (gid_t) gid); - Py_END_ALLOW_THREADS - if (res < 0) - return posix_error_with_allocated_filename(opath); - Py_DECREF(opath); - Py_INCREF(Py_None); - return Py_None; + PyObject *opath; + char *path; + long uid, gid; + int res; + if (!PyArg_ParseTuple(args, "O&ll:chown", + PyUnicode_FSConverter, &opath, + &uid, &gid)) + return NULL; + path = PyBytes_AsString(opath); + Py_BEGIN_ALLOW_THREADS + res = chown(path, (uid_t) uid, (gid_t) gid); + Py_END_ALLOW_THREADS + if (res < 0) + return posix_error_with_allocated_filename(opath); + Py_DECREF(opath); + Py_INCREF(Py_None); + return Py_None; } #endif /* HAVE_CHOWN */ @@ -1939,17 +1940,17 @@ static PyObject * posix_fchown(PyObject *self, PyObject *args) { - int fd; - long uid, gid; - int res; - if (!PyArg_ParseTuple(args, "ill:chown", &fd, &uid, &gid)) - return NULL; - Py_BEGIN_ALLOW_THREADS - res = fchown(fd, (uid_t) uid, (gid_t) gid); - Py_END_ALLOW_THREADS - if (res < 0) - return posix_error(); - Py_RETURN_NONE; + int fd; + long uid, gid; + int res; + if (!PyArg_ParseTuple(args, "ill:chown", &fd, &uid, &gid)) + return NULL; + Py_BEGIN_ALLOW_THREADS + res = fchown(fd, (uid_t) uid, (gid_t) gid); + Py_END_ALLOW_THREADS + if (res < 0) + return posix_error(); + Py_RETURN_NONE; } #endif /* HAVE_FCHOWN */ @@ -1962,23 +1963,23 @@ static PyObject * posix_lchown(PyObject *self, PyObject *args) { - PyObject *opath; - char *path; - long uid, gid; - int res; - if (!PyArg_ParseTuple(args, "O&ll:lchown", - PyUnicode_FSConverter, &opath, - &uid, &gid)) - return NULL; - path = PyBytes_AsString(opath); - Py_BEGIN_ALLOW_THREADS - res = lchown(path, (uid_t) uid, (gid_t) gid); - Py_END_ALLOW_THREADS - if (res < 0) - return posix_error_with_allocated_filename(opath); - Py_DECREF(opath); - Py_INCREF(Py_None); - return Py_None; + PyObject *opath; + char *path; + long uid, gid; + int res; + if (!PyArg_ParseTuple(args, "O&ll:lchown", + PyUnicode_FSConverter, &opath, + &uid, &gid)) + return NULL; + path = PyBytes_AsString(opath); + Py_BEGIN_ALLOW_THREADS + res = lchown(path, (uid_t) uid, (gid_t) gid); + Py_END_ALLOW_THREADS + if (res < 0) + return posix_error_with_allocated_filename(opath); + Py_DECREF(opath); + Py_INCREF(Py_None); + return Py_None; } #endif /* HAVE_LCHOWN */ @@ -1987,52 +1988,52 @@ static PyObject * posix_getcwd(int use_bytes) { - char buf[1026]; - char *res; + char buf[1026]; + char *res; #ifdef MS_WINDOWS - if (!use_bytes) { - wchar_t wbuf[1026]; - wchar_t *wbuf2 = wbuf; - PyObject *resobj; - DWORD len; - Py_BEGIN_ALLOW_THREADS - len = GetCurrentDirectoryW(sizeof wbuf/ sizeof wbuf[0], wbuf); - /* If the buffer is large enough, len does not include the - terminating \0. If the buffer is too small, len includes - the space needed for the terminator. */ - if (len >= sizeof wbuf/ sizeof wbuf[0]) { - wbuf2 = malloc(len * sizeof(wchar_t)); - if (wbuf2) - len = GetCurrentDirectoryW(len, wbuf2); - } - Py_END_ALLOW_THREADS - if (!wbuf2) { - PyErr_NoMemory(); - return NULL; - } - if (!len) { - if (wbuf2 != wbuf) free(wbuf2); - return win32_error("getcwdu", NULL); - } - resobj = PyUnicode_FromWideChar(wbuf2, len); - if (wbuf2 != wbuf) free(wbuf2); - return resobj; - } + if (!use_bytes) { + wchar_t wbuf[1026]; + wchar_t *wbuf2 = wbuf; + PyObject *resobj; + DWORD len; + Py_BEGIN_ALLOW_THREADS + len = GetCurrentDirectoryW(sizeof wbuf/ sizeof wbuf[0], wbuf); + /* If the buffer is large enough, len does not include the + terminating \0. If the buffer is too small, len includes + the space needed for the terminator. */ + if (len >= sizeof wbuf/ sizeof wbuf[0]) { + wbuf2 = malloc(len * sizeof(wchar_t)); + if (wbuf2) + len = GetCurrentDirectoryW(len, wbuf2); + } + Py_END_ALLOW_THREADS + if (!wbuf2) { + PyErr_NoMemory(); + return NULL; + } + if (!len) { + if (wbuf2 != wbuf) free(wbuf2); + return win32_error("getcwdu", NULL); + } + resobj = PyUnicode_FromWideChar(wbuf2, len); + if (wbuf2 != wbuf) free(wbuf2); + return resobj; + } #endif - Py_BEGIN_ALLOW_THREADS + Py_BEGIN_ALLOW_THREADS #if defined(PYOS_OS2) && defined(PYCC_GCC) - res = _getcwd2(buf, sizeof buf); + res = _getcwd2(buf, sizeof buf); #else - res = getcwd(buf, sizeof buf); + res = getcwd(buf, sizeof buf); #endif - Py_END_ALLOW_THREADS - if (res == NULL) - return posix_error(); - if (use_bytes) - return PyBytes_FromStringAndSize(buf, strlen(buf)); - return PyUnicode_Decode(buf, strlen(buf), Py_FileSystemDefaultEncoding,"surrogateescape"); + Py_END_ALLOW_THREADS + if (res == NULL) + return posix_error(); + if (use_bytes) + return PyBytes_FromStringAndSize(buf, strlen(buf)); + return PyUnicode_Decode(buf, strlen(buf), Py_FileSystemDefaultEncoding,"surrogateescape"); } PyDoc_STRVAR(posix_getcwd__doc__, @@ -2065,7 +2066,7 @@ static PyObject * posix_link(PyObject *self, PyObject *args) { - return posix_2str(args, "O&O&:link", link); + return posix_2str(args, "O&O&:link", link); } #endif /* HAVE_LINK */ @@ -2074,7 +2075,7 @@ "listdir(path) -> list_of_strings\n\n\ Return a list containing the names of the entries in the directory.\n\ \n\ - path: path of directory to list\n\ + path: path of directory to list\n\ \n\ The list is in arbitrary order. It does not include the special\n\ entries '.' and '..' even if they are present in the directory."); @@ -2082,163 +2083,163 @@ static PyObject * posix_listdir(PyObject *self, PyObject *args) { - /* XXX Should redo this putting the (now four) versions of opendir - in separate files instead of having them all here... */ + /* XXX Should redo this putting the (now four) versions of opendir + in separate files instead of having them all here... */ #if defined(MS_WINDOWS) && !defined(HAVE_OPENDIR) - PyObject *d, *v; - HANDLE hFindFile; - BOOL result; - WIN32_FIND_DATA FileData; - PyObject *opath; - char namebuf[MAX_PATH+5]; /* Overallocate for \\*.*\0 */ - char *bufptr = namebuf; - Py_ssize_t len = sizeof(namebuf)-5; /* only claim to have space for MAX_PATH */ - - PyObject *po; - if (PyArg_ParseTuple(args, "U:listdir", &po)) { - WIN32_FIND_DATAW wFileData; - Py_UNICODE *wnamebuf; - /* Overallocate for \\*.*\0 */ - len = PyUnicode_GET_SIZE(po); - wnamebuf = malloc((len + 5) * sizeof(wchar_t)); - if (!wnamebuf) { - PyErr_NoMemory(); - return NULL; - } - wcscpy(wnamebuf, PyUnicode_AS_UNICODE(po)); - if (len > 0) { - Py_UNICODE wch = wnamebuf[len-1]; - if (wch != L'/' && wch != L'\\' && wch != L':') - wnamebuf[len++] = L'\\'; - wcscpy(wnamebuf + len, L"*.*"); - } - if ((d = PyList_New(0)) == NULL) { - free(wnamebuf); - return NULL; - } - hFindFile = FindFirstFileW(wnamebuf, &wFileData); - if (hFindFile == INVALID_HANDLE_VALUE) { - int error = GetLastError(); - if (error == ERROR_FILE_NOT_FOUND) { - free(wnamebuf); - return d; - } - Py_DECREF(d); - win32_error_unicode("FindFirstFileW", wnamebuf); - free(wnamebuf); - return NULL; - } - do { - /* Skip over . and .. */ - if (wcscmp(wFileData.cFileName, L".") != 0 && - wcscmp(wFileData.cFileName, L"..") != 0) { - v = PyUnicode_FromUnicode(wFileData.cFileName, wcslen(wFileData.cFileName)); - if (v == NULL) { - Py_DECREF(d); - d = NULL; - break; - } - if (PyList_Append(d, v) != 0) { - Py_DECREF(v); - Py_DECREF(d); - d = NULL; - break; - } - Py_DECREF(v); - } - Py_BEGIN_ALLOW_THREADS - result = FindNextFileW(hFindFile, &wFileData); - Py_END_ALLOW_THREADS - /* FindNextFile sets error to ERROR_NO_MORE_FILES if - it got to the end of the directory. */ - if (!result && GetLastError() != ERROR_NO_MORE_FILES) { - Py_DECREF(d); - win32_error_unicode("FindNextFileW", wnamebuf); - FindClose(hFindFile); - free(wnamebuf); - return NULL; - } - } while (result == TRUE); - - if (FindClose(hFindFile) == FALSE) { - Py_DECREF(d); - win32_error_unicode("FindClose", wnamebuf); - free(wnamebuf); - return NULL; - } - free(wnamebuf); - return d; - } - /* Drop the argument parsing error as narrow strings - are also valid. */ - PyErr_Clear(); - - if (!PyArg_ParseTuple(args, "O&:listdir", - PyUnicode_FSConverter, &opath)) - return NULL; - if (PyBytes_GET_SIZE(opath)+1 > MAX_PATH) { - PyErr_SetString(PyExc_ValueError, "path too long"); - Py_DECREF(opath); - return NULL; - } - strcpy(namebuf, PyBytes_AsString(opath)); - len = PyObject_Size(opath); - if (len > 0) { - char ch = namebuf[len-1]; - if (ch != SEP && ch != ALTSEP && ch != ':') - namebuf[len++] = '/'; - strcpy(namebuf + len, "*.*"); - } - - if ((d = PyList_New(0)) == NULL) - return NULL; - - hFindFile = FindFirstFile(namebuf, &FileData); - if (hFindFile == INVALID_HANDLE_VALUE) { - int error = GetLastError(); - if (error == ERROR_FILE_NOT_FOUND) - return d; - Py_DECREF(d); - return win32_error("FindFirstFile", namebuf); - } - do { - /* Skip over . and .. */ - if (strcmp(FileData.cFileName, ".") != 0 && - strcmp(FileData.cFileName, "..") != 0) { - v = PyBytes_FromString(FileData.cFileName); - if (v == NULL) { - Py_DECREF(d); - d = NULL; - break; - } - if (PyList_Append(d, v) != 0) { - Py_DECREF(v); - Py_DECREF(d); - d = NULL; - break; - } - Py_DECREF(v); - } - Py_BEGIN_ALLOW_THREADS - result = FindNextFile(hFindFile, &FileData); - Py_END_ALLOW_THREADS - /* FindNextFile sets error to ERROR_NO_MORE_FILES if - it got to the end of the directory. */ - if (!result && GetLastError() != ERROR_NO_MORE_FILES) { - Py_DECREF(d); - win32_error("FindNextFile", namebuf); - FindClose(hFindFile); - return NULL; - } - } while (result == TRUE); - - if (FindClose(hFindFile) == FALSE) { - Py_DECREF(d); - return win32_error("FindClose", namebuf); - } + PyObject *d, *v; + HANDLE hFindFile; + BOOL result; + WIN32_FIND_DATA FileData; + PyObject *opath; + char namebuf[MAX_PATH+5]; /* Overallocate for \\*.*\0 */ + char *bufptr = namebuf; + Py_ssize_t len = sizeof(namebuf)-5; /* only claim to have space for MAX_PATH */ + + PyObject *po; + if (PyArg_ParseTuple(args, "U:listdir", &po)) { + WIN32_FIND_DATAW wFileData; + Py_UNICODE *wnamebuf; + /* Overallocate for \\*.*\0 */ + len = PyUnicode_GET_SIZE(po); + wnamebuf = malloc((len + 5) * sizeof(wchar_t)); + if (!wnamebuf) { + PyErr_NoMemory(); + return NULL; + } + wcscpy(wnamebuf, PyUnicode_AS_UNICODE(po)); + if (len > 0) { + Py_UNICODE wch = wnamebuf[len-1]; + if (wch != L'/' && wch != L'\\' && wch != L':') + wnamebuf[len++] = L'\\'; + wcscpy(wnamebuf + len, L"*.*"); + } + if ((d = PyList_New(0)) == NULL) { + free(wnamebuf); + return NULL; + } + hFindFile = FindFirstFileW(wnamebuf, &wFileData); + if (hFindFile == INVALID_HANDLE_VALUE) { + int error = GetLastError(); + if (error == ERROR_FILE_NOT_FOUND) { + free(wnamebuf); + return d; + } + Py_DECREF(d); + win32_error_unicode("FindFirstFileW", wnamebuf); + free(wnamebuf); + return NULL; + } + do { + /* Skip over . and .. */ + if (wcscmp(wFileData.cFileName, L".") != 0 && + wcscmp(wFileData.cFileName, L"..") != 0) { + v = PyUnicode_FromUnicode(wFileData.cFileName, wcslen(wFileData.cFileName)); + if (v == NULL) { + Py_DECREF(d); + d = NULL; + break; + } + if (PyList_Append(d, v) != 0) { + Py_DECREF(v); + Py_DECREF(d); + d = NULL; + break; + } + Py_DECREF(v); + } + Py_BEGIN_ALLOW_THREADS + result = FindNextFileW(hFindFile, &wFileData); + Py_END_ALLOW_THREADS + /* FindNextFile sets error to ERROR_NO_MORE_FILES if + it got to the end of the directory. */ + if (!result && GetLastError() != ERROR_NO_MORE_FILES) { + Py_DECREF(d); + win32_error_unicode("FindNextFileW", wnamebuf); + FindClose(hFindFile); + free(wnamebuf); + return NULL; + } + } while (result == TRUE); + + if (FindClose(hFindFile) == FALSE) { + Py_DECREF(d); + win32_error_unicode("FindClose", wnamebuf); + free(wnamebuf); + return NULL; + } + free(wnamebuf); + return d; + } + /* Drop the argument parsing error as narrow strings + are also valid. */ + PyErr_Clear(); + + if (!PyArg_ParseTuple(args, "O&:listdir", + PyUnicode_FSConverter, &opath)) + return NULL; + if (PyBytes_GET_SIZE(opath)+1 > MAX_PATH) { + PyErr_SetString(PyExc_ValueError, "path too long"); + Py_DECREF(opath); + return NULL; + } + strcpy(namebuf, PyBytes_AsString(opath)); + len = PyObject_Size(opath); + if (len > 0) { + char ch = namebuf[len-1]; + if (ch != SEP && ch != ALTSEP && ch != ':') + namebuf[len++] = '/'; + strcpy(namebuf + len, "*.*"); + } + + if ((d = PyList_New(0)) == NULL) + return NULL; + + hFindFile = FindFirstFile(namebuf, &FileData); + if (hFindFile == INVALID_HANDLE_VALUE) { + int error = GetLastError(); + if (error == ERROR_FILE_NOT_FOUND) + return d; + Py_DECREF(d); + return win32_error("FindFirstFile", namebuf); + } + do { + /* Skip over . and .. */ + if (strcmp(FileData.cFileName, ".") != 0 && + strcmp(FileData.cFileName, "..") != 0) { + v = PyBytes_FromString(FileData.cFileName); + if (v == NULL) { + Py_DECREF(d); + d = NULL; + break; + } + if (PyList_Append(d, v) != 0) { + Py_DECREF(v); + Py_DECREF(d); + d = NULL; + break; + } + Py_DECREF(v); + } + Py_BEGIN_ALLOW_THREADS + result = FindNextFile(hFindFile, &FileData); + Py_END_ALLOW_THREADS + /* FindNextFile sets error to ERROR_NO_MORE_FILES if + it got to the end of the directory. */ + if (!result && GetLastError() != ERROR_NO_MORE_FILES) { + Py_DECREF(d); + win32_error("FindNextFile", namebuf); + FindClose(hFindFile); + return NULL; + } + } while (result == TRUE); + + if (FindClose(hFindFile) == FALSE) { + Py_DECREF(d); + return win32_error("FindClose", namebuf); + } - return d; + return d; #elif defined(PYOS_OS2) @@ -2255,7 +2256,7 @@ FILEFINDBUF3 ep; APIRET rc; - if (!PyArg_ParseTuple(args, "O&:listdir", + if (!PyArg_ParseTuple(args, "O&:listdir", PyUnicode_FSConverter, &oname)) return NULL; name = PyBytes_AsString(oname); @@ -2320,82 +2321,82 @@ Py_DECREF(oname); return d; #else - PyObject *oname; - char *name; - PyObject *d, *v; - DIR *dirp; - struct dirent *ep; - int arg_is_unicode = 1; - - errno = 0; - if (!PyArg_ParseTuple(args, "U:listdir", &v)) { - arg_is_unicode = 0; - PyErr_Clear(); - } - if (!PyArg_ParseTuple(args, "O&:listdir", PyUnicode_FSConverter, &oname)) - return NULL; - name = PyBytes_AsString(oname); - if ((dirp = opendir(name)) == NULL) { - return posix_error_with_allocated_filename(oname); - } - if ((d = PyList_New(0)) == NULL) { - closedir(dirp); - Py_DECREF(oname); - return NULL; - } - for (;;) { - errno = 0; - Py_BEGIN_ALLOW_THREADS - ep = readdir(dirp); - Py_END_ALLOW_THREADS - if (ep == NULL) { - if (errno == 0) { - break; - } else { - closedir(dirp); - Py_DECREF(d); - return posix_error_with_allocated_filename(oname); - } - } - if (ep->d_name[0] == '.' && - (NAMLEN(ep) == 1 || - (ep->d_name[1] == '.' && NAMLEN(ep) == 2))) - continue; - v = PyBytes_FromStringAndSize(ep->d_name, NAMLEN(ep)); - if (v == NULL) { - Py_DECREF(d); - d = NULL; - break; - } - if (arg_is_unicode) { - PyObject *w; - - w = PyUnicode_FromEncodedObject(v, - Py_FileSystemDefaultEncoding, - "surrogateescape"); - Py_DECREF(v); - if (w != NULL) - v = w; - else { - /* Encoding failed to decode ASCII bytes. - Raise exception. */ - Py_DECREF(d); - d = NULL; - break; - } - } - if (PyList_Append(d, v) != 0) { - Py_DECREF(v); - Py_DECREF(d); - d = NULL; - break; - } - Py_DECREF(v); - } - closedir(dirp); - Py_DECREF(oname); + PyObject *oname; + char *name; + PyObject *d, *v; + DIR *dirp; + struct dirent *ep; + int arg_is_unicode = 1; + + errno = 0; + if (!PyArg_ParseTuple(args, "U:listdir", &v)) { + arg_is_unicode = 0; + PyErr_Clear(); + } + if (!PyArg_ParseTuple(args, "O&:listdir", PyUnicode_FSConverter, &oname)) + return NULL; + name = PyBytes_AsString(oname); + if ((dirp = opendir(name)) == NULL) { + return posix_error_with_allocated_filename(oname); + } + if ((d = PyList_New(0)) == NULL) { + closedir(dirp); + Py_DECREF(oname); + return NULL; + } + for (;;) { + errno = 0; + Py_BEGIN_ALLOW_THREADS + ep = readdir(dirp); + Py_END_ALLOW_THREADS + if (ep == NULL) { + if (errno == 0) { + break; + } else { + closedir(dirp); + Py_DECREF(d); + return posix_error_with_allocated_filename(oname); + } + } + if (ep->d_name[0] == '.' && + (NAMLEN(ep) == 1 || + (ep->d_name[1] == '.' && NAMLEN(ep) == 2))) + continue; + v = PyBytes_FromStringAndSize(ep->d_name, NAMLEN(ep)); + if (v == NULL) { + Py_DECREF(d); + d = NULL; + break; + } + if (arg_is_unicode) { + PyObject *w; + + w = PyUnicode_FromEncodedObject(v, + Py_FileSystemDefaultEncoding, + "surrogateescape"); + Py_DECREF(v); + if (w != NULL) + v = w; + else { + /* Encoding failed to decode ASCII bytes. + Raise exception. */ + Py_DECREF(d); + d = NULL; + break; + } + } + if (PyList_Append(d, v) != 0) { + Py_DECREF(v); + Py_DECREF(d); + d = NULL; + break; + } + Py_DECREF(v); + } + closedir(dirp); + Py_DECREF(oname); - return d; + return d; #endif /* which OS */ } /* end of posix_listdir */ @@ -2405,56 +2406,56 @@ static PyObject * posix__getfullpathname(PyObject *self, PyObject *args) { - PyObject *opath; - char *path; - char outbuf[MAX_PATH*2]; - char *temp; + PyObject *opath; + char *path; + char outbuf[MAX_PATH*2]; + char *temp; #ifdef MS_WINDOWS - PyUnicodeObject *po; - if (PyArg_ParseTuple(args, "U|:_getfullpathname", &po)) { - Py_UNICODE *wpath = PyUnicode_AS_UNICODE(po); - Py_UNICODE woutbuf[MAX_PATH*2], *woutbufp = woutbuf; - Py_UNICODE *wtemp; - DWORD result; - PyObject *v; - result = GetFullPathNameW(wpath, - sizeof(woutbuf)/sizeof(woutbuf[0]), - woutbuf, &wtemp); - if (result > sizeof(woutbuf)/sizeof(woutbuf[0])) { - woutbufp = malloc(result * sizeof(Py_UNICODE)); - if (!woutbufp) - return PyErr_NoMemory(); - result = GetFullPathNameW(wpath, result, woutbufp, &wtemp); - } - if (result) - v = PyUnicode_FromUnicode(woutbufp, wcslen(woutbufp)); - else - v = win32_error_unicode("GetFullPathNameW", wpath); - if (woutbufp != woutbuf) - free(woutbufp); - return v; - } - /* Drop the argument parsing error as narrow strings - are also valid. */ - PyErr_Clear(); - -#endif - if (!PyArg_ParseTuple (args, "O&:_getfullpathname", - PyUnicode_FSConverter, &opath)) - return NULL; - path = PyBytes_AsString(opath); - if (!GetFullPathName(path, sizeof(outbuf)/sizeof(outbuf[0]), - outbuf, &temp)) { - win32_error("GetFullPathName", path); - Py_DECREF(opath); - return NULL; - } - Py_DECREF(opath); - if (PyUnicode_Check(PyTuple_GetItem(args, 0))) { - return PyUnicode_Decode(outbuf, strlen(outbuf), - Py_FileSystemDefaultEncoding, NULL); - } - return PyBytes_FromString(outbuf); + PyUnicodeObject *po; + if (PyArg_ParseTuple(args, "U|:_getfullpathname", &po)) { + Py_UNICODE *wpath = PyUnicode_AS_UNICODE(po); + Py_UNICODE woutbuf[MAX_PATH*2], *woutbufp = woutbuf; + Py_UNICODE *wtemp; + DWORD result; + PyObject *v; + result = GetFullPathNameW(wpath, + sizeof(woutbuf)/sizeof(woutbuf[0]), + woutbuf, &wtemp); + if (result > sizeof(woutbuf)/sizeof(woutbuf[0])) { + woutbufp = malloc(result * sizeof(Py_UNICODE)); + if (!woutbufp) + return PyErr_NoMemory(); + result = GetFullPathNameW(wpath, result, woutbufp, &wtemp); + } + if (result) + v = PyUnicode_FromUnicode(woutbufp, wcslen(woutbufp)); + else + v = win32_error_unicode("GetFullPathNameW", wpath); + if (woutbufp != woutbuf) + free(woutbufp); + return v; + } + /* Drop the argument parsing error as narrow strings + are also valid. */ + PyErr_Clear(); + +#endif + if (!PyArg_ParseTuple (args, "O&:_getfullpathname", + PyUnicode_FSConverter, &opath)) + return NULL; + path = PyBytes_AsString(opath); + if (!GetFullPathName(path, sizeof(outbuf)/sizeof(outbuf[0]), + outbuf, &temp)) { + win32_error("GetFullPathName", path); + Py_DECREF(opath); + return NULL; + } + Py_DECREF(opath); + if (PyUnicode_Check(PyTuple_GetItem(args, 0))) { + return PyUnicode_Decode(outbuf, strlen(outbuf), + Py_FileSystemDefaultEncoding, NULL); + } + return PyBytes_FromString(outbuf); } /* end of posix__getfullpathname */ #endif /* MS_WINDOWS */ @@ -2465,62 +2466,62 @@ static PyObject * posix_mkdir(PyObject *self, PyObject *args) { - int res; - PyObject *opath; - char *path; - int mode = 0777; + int res; + PyObject *opath; + char *path; + int mode = 0777; #ifdef MS_WINDOWS - PyUnicodeObject *po; - if (PyArg_ParseTuple(args, "U|i:mkdir", &po, &mode)) { - Py_BEGIN_ALLOW_THREADS - /* PyUnicode_AS_UNICODE OK without thread lock as - it is a simple dereference. */ - res = CreateDirectoryW(PyUnicode_AS_UNICODE(po), NULL); - Py_END_ALLOW_THREADS - if (!res) - return win32_error_unicode("mkdir", PyUnicode_AS_UNICODE(po)); - Py_INCREF(Py_None); - return Py_None; - } - /* Drop the argument parsing error as narrow strings - are also valid. */ - PyErr_Clear(); - if (!PyArg_ParseTuple(args, "O&|i:mkdir", - PyUnicode_FSConverter, &opath, &mode)) - return NULL; - path = PyBytes_AsString(opath); - Py_BEGIN_ALLOW_THREADS - /* PyUnicode_AS_UNICODE OK without thread lock as - it is a simple dereference. */ - res = CreateDirectoryA(path, NULL); - Py_END_ALLOW_THREADS - if (!res) { - win32_error("mkdir", path); - Py_DECREF(opath); - return NULL; - } - Py_DECREF(opath); - Py_INCREF(Py_None); - return Py_None; -#else - - if (!PyArg_ParseTuple(args, "O&|i:mkdir", - PyUnicode_FSConverter, &opath, &mode)) - return NULL; - path = PyBytes_AsString(opath); - Py_BEGIN_ALLOW_THREADS + PyUnicodeObject *po; + if (PyArg_ParseTuple(args, "U|i:mkdir", &po, &mode)) { + Py_BEGIN_ALLOW_THREADS + /* PyUnicode_AS_UNICODE OK without thread lock as + it is a simple dereference. */ + res = CreateDirectoryW(PyUnicode_AS_UNICODE(po), NULL); + Py_END_ALLOW_THREADS + if (!res) + return win32_error_unicode("mkdir", PyUnicode_AS_UNICODE(po)); + Py_INCREF(Py_None); + return Py_None; + } + /* Drop the argument parsing error as narrow strings + are also valid. */ + PyErr_Clear(); + if (!PyArg_ParseTuple(args, "O&|i:mkdir", + PyUnicode_FSConverter, &opath, &mode)) + return NULL; + path = PyBytes_AsString(opath); + Py_BEGIN_ALLOW_THREADS + /* PyUnicode_AS_UNICODE OK without thread lock as + it is a simple dereference. */ + res = CreateDirectoryA(path, NULL); + Py_END_ALLOW_THREADS + if (!res) { + win32_error("mkdir", path); + Py_DECREF(opath); + return NULL; + } + Py_DECREF(opath); + Py_INCREF(Py_None); + return Py_None; +#else + + if (!PyArg_ParseTuple(args, "O&|i:mkdir", + PyUnicode_FSConverter, &opath, &mode)) + return NULL; + path = PyBytes_AsString(opath); + Py_BEGIN_ALLOW_THREADS #if ( defined(__WATCOMC__) || defined(PYCC_VACPP) ) && !defined(__QNX__) - res = mkdir(path); + res = mkdir(path); #else - res = mkdir(path, mode); + res = mkdir(path, mode); #endif - Py_END_ALLOW_THREADS - if (res < 0) - return posix_error_with_allocated_filename(opath); - Py_DECREF(opath); - Py_INCREF(Py_None); - return Py_None; + Py_END_ALLOW_THREADS + if (res < 0) + return posix_error_with_allocated_filename(opath); + Py_DECREF(opath); + Py_INCREF(Py_None); + return Py_None; #endif } @@ -2539,31 +2540,31 @@ static PyObject * posix_nice(PyObject *self, PyObject *args) { - int increment, value; + int increment, value; - if (!PyArg_ParseTuple(args, "i:nice", &increment)) - return NULL; + if (!PyArg_ParseTuple(args, "i:nice", &increment)) + return NULL; - /* There are two flavours of 'nice': one that returns the new - priority (as required by almost all standards out there) and the - Linux/FreeBSD/BSDI one, which returns '0' on success and advices - the use of getpriority() to get the new priority. - - If we are of the nice family that returns the new priority, we - need to clear errno before the call, and check if errno is filled - before calling posix_error() on a returnvalue of -1, because the - -1 may be the actual new priority! */ + /* There are two flavours of 'nice': one that returns the new + priority (as required by almost all standards out there) and the + Linux/FreeBSD/BSDI one, which returns '0' on success and advices + the use of getpriority() to get the new priority. + + If we are of the nice family that returns the new priority, we + need to clear errno before the call, and check if errno is filled + before calling posix_error() on a returnvalue of -1, because the + -1 may be the actual new priority! */ - errno = 0; - value = nice(increment); + errno = 0; + value = nice(increment); #if defined(HAVE_BROKEN_NICE) && defined(HAVE_GETPRIORITY) - if (value == 0) - value = getpriority(PRIO_PROCESS, 0); + if (value == 0) + value = getpriority(PRIO_PROCESS, 0); #endif - if (value == -1 && errno != 0) - /* either nice() or getpriority() returned an error */ - return posix_error(); - return PyLong_FromLong((long) value); + if (value == -1 && errno != 0) + /* either nice() or getpriority() returned an error */ + return posix_error(); + return PyLong_FromLong((long) value); } #endif /* HAVE_NICE */ @@ -2575,40 +2576,40 @@ posix_rename(PyObject *self, PyObject *args) { #ifdef MS_WINDOWS - PyObject *o1, *o2; - char *p1, *p2; - BOOL result; - if (!PyArg_ParseTuple(args, "OO:rename", &o1, &o2)) - goto error; - if (!convert_to_unicode(&o1)) - goto error; - if (!convert_to_unicode(&o2)) { - Py_DECREF(o1); - goto error; - } - Py_BEGIN_ALLOW_THREADS - result = MoveFileW(PyUnicode_AsUnicode(o1), - PyUnicode_AsUnicode(o2)); - Py_END_ALLOW_THREADS - Py_DECREF(o1); - Py_DECREF(o2); - if (!result) - return win32_error("rename", NULL); - Py_INCREF(Py_None); - return Py_None; + PyObject *o1, *o2; + char *p1, *p2; + BOOL result; + if (!PyArg_ParseTuple(args, "OO:rename", &o1, &o2)) + goto error; + if (!convert_to_unicode(&o1)) + goto error; + if (!convert_to_unicode(&o2)) { + Py_DECREF(o1); + goto error; + } + Py_BEGIN_ALLOW_THREADS + result = MoveFileW(PyUnicode_AsUnicode(o1), + PyUnicode_AsUnicode(o2)); + Py_END_ALLOW_THREADS + Py_DECREF(o1); + Py_DECREF(o2); + if (!result) + return win32_error("rename", NULL); + Py_INCREF(Py_None); + return Py_None; error: - PyErr_Clear(); - if (!PyArg_ParseTuple(args, "ss:rename", &p1, &p2)) - return NULL; - Py_BEGIN_ALLOW_THREADS - result = MoveFileA(p1, p2); - Py_END_ALLOW_THREADS - if (!result) - return win32_error("rename", NULL); - Py_INCREF(Py_None); - return Py_None; + PyErr_Clear(); + if (!PyArg_ParseTuple(args, "ss:rename", &p1, &p2)) + return NULL; + Py_BEGIN_ALLOW_THREADS + result = MoveFileA(p1, p2); + Py_END_ALLOW_THREADS + if (!result) + return win32_error("rename", NULL); + Py_INCREF(Py_None); + return Py_None; #else - return posix_2str(args, "O&O&:rename", rename); + return posix_2str(args, "O&O&:rename", rename); #endif } @@ -2621,9 +2622,9 @@ posix_rmdir(PyObject *self, PyObject *args) { #ifdef MS_WINDOWS - return win32_1str(args, "rmdir", "y:rmdir", RemoveDirectoryA, "U:rmdir", RemoveDirectoryW); + return win32_1str(args, "rmdir", "y:rmdir", RemoveDirectoryA, "U:rmdir", RemoveDirectoryW); #else - return posix_1str(args, "O&:rmdir", rmdir); + return posix_1str(args, "O&:rmdir", rmdir); #endif } @@ -2636,9 +2637,9 @@ posix_stat(PyObject *self, PyObject *args) { #ifdef MS_WINDOWS - return posix_do_stat(self, args, "O&:stat", STAT, "U:stat", win32_wstat); + return posix_do_stat(self, args, "O&:stat", STAT, "U:stat", win32_wstat); #else - return posix_do_stat(self, args, "O&:stat", STAT, NULL, NULL); + return posix_do_stat(self, args, "O&:stat", STAT, NULL, NULL); #endif } @@ -2651,29 +2652,29 @@ static PyObject * posix_system(PyObject *self, PyObject *args) { - long sts; + long sts; #ifdef MS_WINDOWS - wchar_t *command; - if (!PyArg_ParseTuple(args, "u:system", &command)) - return NULL; - - Py_BEGIN_ALLOW_THREADS - sts = _wsystem(command); - Py_END_ALLOW_THREADS -#else - PyObject *command_obj; - char *command; - if (!PyArg_ParseTuple(args, "O&:system", - PyUnicode_FSConverter, &command_obj)) - return NULL; - - command = PyBytes_AsString(command_obj); - Py_BEGIN_ALLOW_THREADS - sts = system(command); - Py_END_ALLOW_THREADS - Py_DECREF(command_obj); + wchar_t *command; + if (!PyArg_ParseTuple(args, "u:system", &command)) + return NULL; + + Py_BEGIN_ALLOW_THREADS + sts = _wsystem(command); + Py_END_ALLOW_THREADS +#else + PyObject *command_obj; + char *command; + if (!PyArg_ParseTuple(args, "O&:system", + PyUnicode_FSConverter, &command_obj)) + return NULL; + + command = PyBytes_AsString(command_obj); + Py_BEGIN_ALLOW_THREADS + sts = system(command); + Py_END_ALLOW_THREADS + Py_DECREF(command_obj); #endif - return PyLong_FromLong(sts); + return PyLong_FromLong(sts); } #endif @@ -2685,13 +2686,13 @@ static PyObject * posix_umask(PyObject *self, PyObject *args) { - int i; - if (!PyArg_ParseTuple(args, "i:umask", &i)) - return NULL; - i = (int)umask(i); - if (i < 0) - return posix_error(); - return PyLong_FromLong((long)i); + int i; + if (!PyArg_ParseTuple(args, "i:umask", &i)) + return NULL; + i = (int)umask(i); + if (i < 0) + return posix_error(); + return PyLong_FromLong((long)i); } @@ -2707,9 +2708,9 @@ posix_unlink(PyObject *self, PyObject *args) { #ifdef MS_WINDOWS - return win32_1str(args, "remove", "y:remove", DeleteFileA, "U:remove", DeleteFileW); + return win32_1str(args, "remove", "y:remove", DeleteFileA, "U:remove", DeleteFileW); #else - return posix_1str(args, "O&:remove", unlink); + return posix_1str(args, "O&:remove", unlink); #endif } @@ -2722,50 +2723,50 @@ static PyObject * posix_uname(PyObject *self, PyObject *noargs) { - struct utsname u; - int res; + struct utsname u; + int res; - Py_BEGIN_ALLOW_THREADS - res = uname(&u); - Py_END_ALLOW_THREADS - if (res < 0) - return posix_error(); - return Py_BuildValue("(sssss)", - u.sysname, - u.nodename, - u.release, - u.version, - u.machine); + Py_BEGIN_ALLOW_THREADS + res = uname(&u); + Py_END_ALLOW_THREADS + if (res < 0) + return posix_error(); + return Py_BuildValue("(sssss)", + u.sysname, + u.nodename, + u.release, + u.version, + u.machine); } #endif /* HAVE_UNAME */ static int extract_time(PyObject *t, long* sec, long* usec) { - long intval; - if (PyFloat_Check(t)) { - double tval = PyFloat_AsDouble(t); - PyObject *intobj = Py_TYPE(t)->tp_as_number->nb_int(t); - if (!intobj) - return -1; - intval = PyLong_AsLong(intobj); - Py_DECREF(intobj); - if (intval == -1 && PyErr_Occurred()) - return -1; - *sec = intval; - *usec = (long)((tval - intval) * 1e6); /* can't exceed 1000000 */ - if (*usec < 0) - /* If rounding gave us a negative number, - truncate. */ - *usec = 0; - return 0; - } - intval = PyLong_AsLong(t); - if (intval == -1 && PyErr_Occurred()) - return -1; - *sec = intval; - *usec = 0; + long intval; + if (PyFloat_Check(t)) { + double tval = PyFloat_AsDouble(t); + PyObject *intobj = Py_TYPE(t)->tp_as_number->nb_int(t); + if (!intobj) + return -1; + intval = PyLong_AsLong(intobj); + Py_DECREF(intobj); + if (intval == -1 && PyErr_Occurred()) + return -1; + *sec = intval; + *usec = (long)((tval - intval) * 1e6); /* can't exceed 1000000 */ + if (*usec < 0) + /* If rounding gave us a negative number, + truncate. */ + *usec = 0; return 0; + } + intval = PyLong_AsLong(t); + if (intval == -1 && PyErr_Occurred()) + return -1; + *sec = intval; + *usec = 0; + return 0; } PyDoc_STRVAR(posix_utime__doc__, @@ -2778,157 +2779,157 @@ posix_utime(PyObject *self, PyObject *args) { #ifdef MS_WINDOWS - PyObject *arg; - PyUnicodeObject *obwpath; - wchar_t *wpath = NULL; - PyObject *oapath; - char *apath; - HANDLE hFile; - long atimesec, mtimesec, ausec, musec; - FILETIME atime, mtime; - PyObject *result = NULL; - - if (PyArg_ParseTuple(args, "UO|:utime", &obwpath, &arg)) { - wpath = PyUnicode_AS_UNICODE(obwpath); - Py_BEGIN_ALLOW_THREADS - hFile = CreateFileW(wpath, FILE_WRITE_ATTRIBUTES, 0, - NULL, OPEN_EXISTING, - FILE_FLAG_BACKUP_SEMANTICS, NULL); - Py_END_ALLOW_THREADS - if (hFile == INVALID_HANDLE_VALUE) - return win32_error_unicode("utime", wpath); - } else - /* Drop the argument parsing error as narrow strings - are also valid. */ - PyErr_Clear(); - - if (!wpath) { - if (!PyArg_ParseTuple(args, "O&O:utime", - PyUnicode_FSConverter, &oapath, &arg)) - return NULL; - apath = PyBytes_AsString(oapath); - Py_BEGIN_ALLOW_THREADS - hFile = CreateFileA(apath, FILE_WRITE_ATTRIBUTES, 0, - NULL, OPEN_EXISTING, - FILE_FLAG_BACKUP_SEMANTICS, NULL); - Py_END_ALLOW_THREADS - if (hFile == INVALID_HANDLE_VALUE) { - win32_error("utime", apath); - Py_DECREF(oapath); - return NULL; - } - Py_DECREF(oapath); - } - - if (arg == Py_None) { - SYSTEMTIME now; - GetSystemTime(&now); - if (!SystemTimeToFileTime(&now, &mtime) || - !SystemTimeToFileTime(&now, &atime)) { - win32_error("utime", NULL); - goto done; - } - } - else if (!PyTuple_Check(arg) || PyTuple_Size(arg) != 2) { - PyErr_SetString(PyExc_TypeError, - "utime() arg 2 must be a tuple (atime, mtime)"); - goto done; - } - else { - if (extract_time(PyTuple_GET_ITEM(arg, 0), - &atimesec, &ausec) == -1) - goto done; - time_t_to_FILE_TIME(atimesec, 1000*ausec, &atime); - if (extract_time(PyTuple_GET_ITEM(arg, 1), - &mtimesec, &musec) == -1) - goto done; - time_t_to_FILE_TIME(mtimesec, 1000*musec, &mtime); - } - if (!SetFileTime(hFile, NULL, &atime, &mtime)) { - /* Avoid putting the file name into the error here, - as that may confuse the user into believing that - something is wrong with the file, when it also - could be the time stamp that gives a problem. */ - win32_error("utime", NULL); - } - Py_INCREF(Py_None); - result = Py_None; + PyObject *arg; + PyUnicodeObject *obwpath; + wchar_t *wpath = NULL; + PyObject *oapath; + char *apath; + HANDLE hFile; + long atimesec, mtimesec, ausec, musec; + FILETIME atime, mtime; + PyObject *result = NULL; + + if (PyArg_ParseTuple(args, "UO|:utime", &obwpath, &arg)) { + wpath = PyUnicode_AS_UNICODE(obwpath); + Py_BEGIN_ALLOW_THREADS + hFile = CreateFileW(wpath, FILE_WRITE_ATTRIBUTES, 0, + NULL, OPEN_EXISTING, + FILE_FLAG_BACKUP_SEMANTICS, NULL); + Py_END_ALLOW_THREADS + if (hFile == INVALID_HANDLE_VALUE) + return win32_error_unicode("utime", wpath); + } else + /* Drop the argument parsing error as narrow strings + are also valid. */ + PyErr_Clear(); + + if (!wpath) { + if (!PyArg_ParseTuple(args, "O&O:utime", + PyUnicode_FSConverter, &oapath, &arg)) + return NULL; + apath = PyBytes_AsString(oapath); + Py_BEGIN_ALLOW_THREADS + hFile = CreateFileA(apath, FILE_WRITE_ATTRIBUTES, 0, + NULL, OPEN_EXISTING, + FILE_FLAG_BACKUP_SEMANTICS, NULL); + Py_END_ALLOW_THREADS + if (hFile == INVALID_HANDLE_VALUE) { + win32_error("utime", apath); + Py_DECREF(oapath); + return NULL; + } + Py_DECREF(oapath); + } + + if (arg == Py_None) { + SYSTEMTIME now; + GetSystemTime(&now); + if (!SystemTimeToFileTime(&now, &mtime) || + !SystemTimeToFileTime(&now, &atime)) { + win32_error("utime", NULL); + goto done; + } + } + else if (!PyTuple_Check(arg) || PyTuple_Size(arg) != 2) { + PyErr_SetString(PyExc_TypeError, + "utime() arg 2 must be a tuple (atime, mtime)"); + goto done; + } + else { + if (extract_time(PyTuple_GET_ITEM(arg, 0), + &atimesec, &ausec) == -1) + goto done; + time_t_to_FILE_TIME(atimesec, 1000*ausec, &atime); + if (extract_time(PyTuple_GET_ITEM(arg, 1), + &mtimesec, &musec) == -1) + goto done; + time_t_to_FILE_TIME(mtimesec, 1000*musec, &mtime); + } + if (!SetFileTime(hFile, NULL, &atime, &mtime)) { + /* Avoid putting the file name into the error here, + as that may confuse the user into believing that + something is wrong with the file, when it also + could be the time stamp that gives a problem. */ + win32_error("utime", NULL); + } + Py_INCREF(Py_None); + result = Py_None; done: - CloseHandle(hFile); - return result; + CloseHandle(hFile); + return result; #else /* MS_WINDOWS */ - PyObject *opath; - char *path; - long atime, mtime, ausec, musec; - int res; - PyObject* arg; + PyObject *opath; + char *path; + long atime, mtime, ausec, musec; + int res; + PyObject* arg; #if defined(HAVE_UTIMES) - struct timeval buf[2]; + struct timeval buf[2]; #define ATIME buf[0].tv_sec #define MTIME buf[1].tv_sec #elif defined(HAVE_UTIME_H) /* XXX should define struct utimbuf instead, above */ - struct utimbuf buf; + struct utimbuf buf; #define ATIME buf.actime #define MTIME buf.modtime #define UTIME_ARG &buf #else /* HAVE_UTIMES */ - time_t buf[2]; + time_t buf[2]; #define ATIME buf[0] #define MTIME buf[1] #define UTIME_ARG buf #endif /* HAVE_UTIMES */ - if (!PyArg_ParseTuple(args, "O&O:utime", - PyUnicode_FSConverter, &opath, &arg)) - return NULL; - path = PyBytes_AsString(opath); - if (arg == Py_None) { - /* optional time values not given */ - Py_BEGIN_ALLOW_THREADS - res = utime(path, NULL); - Py_END_ALLOW_THREADS - } - else if (!PyTuple_Check(arg) || PyTuple_Size(arg) != 2) { - PyErr_SetString(PyExc_TypeError, - "utime() arg 2 must be a tuple (atime, mtime)"); - Py_DECREF(opath); - return NULL; - } - else { - if (extract_time(PyTuple_GET_ITEM(arg, 0), - &atime, &ausec) == -1) { - Py_DECREF(opath); - return NULL; - } - if (extract_time(PyTuple_GET_ITEM(arg, 1), - &mtime, &musec) == -1) { - Py_DECREF(opath); - return NULL; - } - ATIME = atime; - MTIME = mtime; + if (!PyArg_ParseTuple(args, "O&O:utime", + PyUnicode_FSConverter, &opath, &arg)) + return NULL; + path = PyBytes_AsString(opath); + if (arg == Py_None) { + /* optional time values not given */ + Py_BEGIN_ALLOW_THREADS + res = utime(path, NULL); + Py_END_ALLOW_THREADS + } + else if (!PyTuple_Check(arg) || PyTuple_Size(arg) != 2) { + PyErr_SetString(PyExc_TypeError, + "utime() arg 2 must be a tuple (atime, mtime)"); + Py_DECREF(opath); + return NULL; + } + else { + if (extract_time(PyTuple_GET_ITEM(arg, 0), + &atime, &ausec) == -1) { + Py_DECREF(opath); + return NULL; + } + if (extract_time(PyTuple_GET_ITEM(arg, 1), + &mtime, &musec) == -1) { + Py_DECREF(opath); + return NULL; + } + ATIME = atime; + MTIME = mtime; #ifdef HAVE_UTIMES - buf[0].tv_usec = ausec; - buf[1].tv_usec = musec; - Py_BEGIN_ALLOW_THREADS - res = utimes(path, buf); - Py_END_ALLOW_THREADS -#else - Py_BEGIN_ALLOW_THREADS - res = utime(path, UTIME_ARG); - Py_END_ALLOW_THREADS + buf[0].tv_usec = ausec; + buf[1].tv_usec = musec; + Py_BEGIN_ALLOW_THREADS + res = utimes(path, buf); + Py_END_ALLOW_THREADS +#else + Py_BEGIN_ALLOW_THREADS + res = utime(path, UTIME_ARG); + Py_END_ALLOW_THREADS #endif /* HAVE_UTIMES */ - } - if (res < 0) { - return posix_error_with_allocated_filename(opath); - } - Py_DECREF(opath); - Py_INCREF(Py_None); - return Py_None; + } + if (res < 0) { + return posix_error_with_allocated_filename(opath); + } + Py_DECREF(opath); + Py_INCREF(Py_None); + return Py_None; #undef UTIME_ARG #undef ATIME #undef MTIME @@ -2945,37 +2946,37 @@ static PyObject * posix__exit(PyObject *self, PyObject *args) { - int sts; - if (!PyArg_ParseTuple(args, "i:_exit", &sts)) - return NULL; - _exit(sts); - return NULL; /* Make gcc -Wall happy */ + int sts; + if (!PyArg_ParseTuple(args, "i:_exit", &sts)) + return NULL; + _exit(sts); + return NULL; /* Make gcc -Wall happy */ } #if defined(HAVE_EXECV) || defined(HAVE_SPAWNV) static void free_string_array(char **array, Py_ssize_t count) { - Py_ssize_t i; - for (i = 0; i < count; i++) - PyMem_Free(array[i]); - PyMem_DEL(array); + Py_ssize_t i; + for (i = 0; i < count; i++) + PyMem_Free(array[i]); + PyMem_DEL(array); } static int fsconvert_strdup(PyObject *o, char**out) { - PyObject *bytes; - Py_ssize_t size; - if (!PyUnicode_FSConverter(o, &bytes)) - return 0; - size = PyBytes_GET_SIZE(bytes); - *out = PyMem_Malloc(size+1); - if (!*out) - return 0; - memcpy(*out, PyBytes_AsString(bytes), size+1); - Py_DECREF(bytes); - return 1; + PyObject *bytes; + Py_ssize_t size; + if (!PyUnicode_FSConverter(o, &bytes)) + return 0; + size = PyBytes_GET_SIZE(bytes); + *out = PyMem_Malloc(size+1); + if (!*out) + return 0; + memcpy(*out, PyBytes_AsString(bytes), size+1); + Py_DECREF(bytes); + return 1; } #endif @@ -2985,236 +2986,236 @@ "execv(path, args)\n\n\ Execute an executable path with arguments, replacing current process.\n\ \n\ - path: path of executable file\n\ - args: tuple or list of strings"); + path: path of executable file\n\ + args: tuple or list of strings"); static PyObject * posix_execv(PyObject *self, PyObject *args) { - PyObject *opath; - char *path; - PyObject *argv; - char **argvlist; - Py_ssize_t i, argc; - PyObject *(*getitem)(PyObject *, Py_ssize_t); - - /* execv has two arguments: (path, argv), where - argv is a list or tuple of strings. */ - - if (!PyArg_ParseTuple(args, "O&O:execv", - PyUnicode_FSConverter, - &opath, &argv)) - return NULL; - path = PyBytes_AsString(opath); - if (PyList_Check(argv)) { - argc = PyList_Size(argv); - getitem = PyList_GetItem; - } - else if (PyTuple_Check(argv)) { - argc = PyTuple_Size(argv); - getitem = PyTuple_GetItem; - } - else { - PyErr_SetString(PyExc_TypeError, "execv() arg 2 must be a tuple or list"); - Py_DECREF(opath); - return NULL; - } - if (argc < 1) { - PyErr_SetString(PyExc_ValueError, "execv() arg 2 must not be empty"); - Py_DECREF(opath); - return NULL; - } - - argvlist = PyMem_NEW(char *, argc+1); - if (argvlist == NULL) { - Py_DECREF(opath); - return PyErr_NoMemory(); - } - for (i = 0; i < argc; i++) { - if (!fsconvert_strdup((*getitem)(argv, i), - &argvlist[i])) { - free_string_array(argvlist, i); - PyErr_SetString(PyExc_TypeError, - "execv() arg 2 must contain only strings"); - Py_DECREF(opath); - return NULL; - - } - } - argvlist[argc] = NULL; - - execv(path, argvlist); - - /* If we get here it's definitely an error */ - - free_string_array(argvlist, argc); - Py_DECREF(opath); - return posix_error(); + PyObject *opath; + char *path; + PyObject *argv; + char **argvlist; + Py_ssize_t i, argc; + PyObject *(*getitem)(PyObject *, Py_ssize_t); + + /* execv has two arguments: (path, argv), where + argv is a list or tuple of strings. */ + + if (!PyArg_ParseTuple(args, "O&O:execv", + PyUnicode_FSConverter, + &opath, &argv)) + return NULL; + path = PyBytes_AsString(opath); + if (PyList_Check(argv)) { + argc = PyList_Size(argv); + getitem = PyList_GetItem; + } + else if (PyTuple_Check(argv)) { + argc = PyTuple_Size(argv); + getitem = PyTuple_GetItem; + } + else { + PyErr_SetString(PyExc_TypeError, "execv() arg 2 must be a tuple or list"); + Py_DECREF(opath); + return NULL; + } + if (argc < 1) { + PyErr_SetString(PyExc_ValueError, "execv() arg 2 must not be empty"); + Py_DECREF(opath); + return NULL; + } + + argvlist = PyMem_NEW(char *, argc+1); + if (argvlist == NULL) { + Py_DECREF(opath); + return PyErr_NoMemory(); + } + for (i = 0; i < argc; i++) { + if (!fsconvert_strdup((*getitem)(argv, i), + &argvlist[i])) { + free_string_array(argvlist, i); + PyErr_SetString(PyExc_TypeError, + "execv() arg 2 must contain only strings"); + Py_DECREF(opath); + return NULL; + + } + } + argvlist[argc] = NULL; + + execv(path, argvlist); + + /* If we get here it's definitely an error */ + + free_string_array(argvlist, argc); + Py_DECREF(opath); + return posix_error(); } static char** parse_envlist(PyObject* env, Py_ssize_t *envc_ptr) { - char **envlist; - Py_ssize_t i, pos, envc; - PyObject *keys=NULL, *vals=NULL; - PyObject *key, *val, *key2, *val2; - char *p, *k, *v; - size_t len; - - i = PyMapping_Size(env); - if (i < 0) - return NULL; - envlist = PyMem_NEW(char *, i + 1); - if (envlist == NULL) { - PyErr_NoMemory(); - return NULL; - } - envc = 0; - keys = PyMapping_Keys(env); - vals = PyMapping_Values(env); - if (!keys || !vals) - goto error; - if (!PyList_Check(keys) || !PyList_Check(vals)) { - PyErr_Format(PyExc_TypeError, - "env.keys() or env.values() is not a list"); - goto error; - } - - for (pos = 0; pos < i; pos++) { - key = PyList_GetItem(keys, pos); - val = PyList_GetItem(vals, pos); - if (!key || !val) - goto error; - - if (PyUnicode_FSConverter(key, &key2) == 0) - goto error; - if (PyUnicode_FSConverter(val, &val2) == 0) { - Py_DECREF(key2); - goto error; - } + char **envlist; + Py_ssize_t i, pos, envc; + PyObject *keys=NULL, *vals=NULL; + PyObject *key, *val, *key2, *val2; + char *p, *k, *v; + size_t len; + + i = PyMapping_Size(env); + if (i < 0) + return NULL; + envlist = PyMem_NEW(char *, i + 1); + if (envlist == NULL) { + PyErr_NoMemory(); + return NULL; + } + envc = 0; + keys = PyMapping_Keys(env); + vals = PyMapping_Values(env); + if (!keys || !vals) + goto error; + if (!PyList_Check(keys) || !PyList_Check(vals)) { + PyErr_Format(PyExc_TypeError, + "env.keys() or env.values() is not a list"); + goto error; + } + + for (pos = 0; pos < i; pos++) { + key = PyList_GetItem(keys, pos); + val = PyList_GetItem(vals, pos); + if (!key || !val) + goto error; + + if (PyUnicode_FSConverter(key, &key2) == 0) + goto error; + if (PyUnicode_FSConverter(val, &val2) == 0) { + Py_DECREF(key2); + goto error; + } #if defined(PYOS_OS2) - /* Omit Pseudo-Env Vars that Would Confuse Programs if Passed On */ - if (stricmp(k, "BEGINLIBPATH") != 0 && stricmp(k, "ENDLIBPATH") != 0) { + /* Omit Pseudo-Env Vars that Would Confuse Programs if Passed On */ + if (stricmp(k, "BEGINLIBPATH") != 0 && stricmp(k, "ENDLIBPATH") != 0) { #endif - k = PyBytes_AsString(key2); - v = PyBytes_AsString(val2); - len = PyBytes_GET_SIZE(key2) + PyBytes_GET_SIZE(val2) + 2; - - p = PyMem_NEW(char, len); - if (p == NULL) { - PyErr_NoMemory(); - Py_DECREF(key2); - Py_DECREF(val2); - goto error; - } - PyOS_snprintf(p, len, "%s=%s", k, v); - envlist[envc++] = p; - Py_DECREF(key2); - Py_DECREF(val2); + k = PyBytes_AsString(key2); + v = PyBytes_AsString(val2); + len = PyBytes_GET_SIZE(key2) + PyBytes_GET_SIZE(val2) + 2; + + p = PyMem_NEW(char, len); + if (p == NULL) { + PyErr_NoMemory(); + Py_DECREF(key2); + Py_DECREF(val2); + goto error; + } + PyOS_snprintf(p, len, "%s=%s", k, v); + envlist[envc++] = p; + Py_DECREF(key2); + Py_DECREF(val2); #if defined(PYOS_OS2) - } + } #endif - } - Py_DECREF(vals); - Py_DECREF(keys); - - envlist[envc] = 0; - *envc_ptr = envc; - return envlist; + } + Py_DECREF(vals); + Py_DECREF(keys); + + envlist[envc] = 0; + *envc_ptr = envc; + return envlist; error: - Py_XDECREF(keys); - Py_XDECREF(vals); - while (--envc >= 0) - PyMem_DEL(envlist[envc]); - PyMem_DEL(envlist); - return NULL; + Py_XDECREF(keys); + Py_XDECREF(vals); + while (--envc >= 0) + PyMem_DEL(envlist[envc]); + PyMem_DEL(envlist); + return NULL; } PyDoc_STRVAR(posix_execve__doc__, "execve(path, args, env)\n\n\ Execute a path with arguments and environment, replacing current process.\n\ \n\ - path: path of executable file\n\ - args: tuple or list of arguments\n\ - env: dictionary of strings mapping to strings"); + path: path of executable file\n\ + args: tuple or list of arguments\n\ + env: dictionary of strings mapping to strings"); static PyObject * posix_execve(PyObject *self, PyObject *args) { - PyObject *opath; - char *path; - PyObject *argv, *env; - char **argvlist; - char **envlist; - Py_ssize_t i, argc, envc; - PyObject *(*getitem)(PyObject *, Py_ssize_t); - Py_ssize_t lastarg = 0; - - /* execve has three arguments: (path, argv, env), where - argv is a list or tuple of strings and env is a dictionary - like posix.environ. */ - - if (!PyArg_ParseTuple(args, "O&OO:execve", - PyUnicode_FSConverter, - &opath, &argv, &env)) - return NULL; - path = PyBytes_AsString(opath); - if (PyList_Check(argv)) { - argc = PyList_Size(argv); - getitem = PyList_GetItem; - } - else if (PyTuple_Check(argv)) { - argc = PyTuple_Size(argv); - getitem = PyTuple_GetItem; - } - else { - PyErr_SetString(PyExc_TypeError, - "execve() arg 2 must be a tuple or list"); - goto fail_0; - } - if (!PyMapping_Check(env)) { - PyErr_SetString(PyExc_TypeError, - "execve() arg 3 must be a mapping object"); - goto fail_0; - } - - argvlist = PyMem_NEW(char *, argc+1); - if (argvlist == NULL) { - PyErr_NoMemory(); - goto fail_0; - } - for (i = 0; i < argc; i++) { - if (!fsconvert_strdup((*getitem)(argv, i), - &argvlist[i])) - { - lastarg = i; - goto fail_1; - } - } - lastarg = argc; - argvlist[argc] = NULL; - - envlist = parse_envlist(env, &envc); - if (envlist == NULL) - goto fail_1; - - execve(path, argvlist, envlist); - - /* If we get here it's definitely an error */ - - (void) posix_error(); - - while (--envc >= 0) - PyMem_DEL(envlist[envc]); - PyMem_DEL(envlist); + PyObject *opath; + char *path; + PyObject *argv, *env; + char **argvlist; + char **envlist; + Py_ssize_t i, argc, envc; + PyObject *(*getitem)(PyObject *, Py_ssize_t); + Py_ssize_t lastarg = 0; + + /* execve has three arguments: (path, argv, env), where + argv is a list or tuple of strings and env is a dictionary + like posix.environ. */ + + if (!PyArg_ParseTuple(args, "O&OO:execve", + PyUnicode_FSConverter, + &opath, &argv, &env)) + return NULL; + path = PyBytes_AsString(opath); + if (PyList_Check(argv)) { + argc = PyList_Size(argv); + getitem = PyList_GetItem; + } + else if (PyTuple_Check(argv)) { + argc = PyTuple_Size(argv); + getitem = PyTuple_GetItem; + } + else { + PyErr_SetString(PyExc_TypeError, + "execve() arg 2 must be a tuple or list"); + goto fail_0; + } + if (!PyMapping_Check(env)) { + PyErr_SetString(PyExc_TypeError, + "execve() arg 3 must be a mapping object"); + goto fail_0; + } + + argvlist = PyMem_NEW(char *, argc+1); + if (argvlist == NULL) { + PyErr_NoMemory(); + goto fail_0; + } + for (i = 0; i < argc; i++) { + if (!fsconvert_strdup((*getitem)(argv, i), + &argvlist[i])) + { + lastarg = i; + goto fail_1; + } + } + lastarg = argc; + argvlist[argc] = NULL; + + envlist = parse_envlist(env, &envc); + if (envlist == NULL) + goto fail_1; + + execve(path, argvlist, envlist); + + /* If we get here it's definitely an error */ + + (void) posix_error(); + + while (--envc >= 0) + PyMem_DEL(envlist[envc]); + PyMem_DEL(envlist); fail_1: - free_string_array(argvlist, lastarg); + free_string_array(argvlist, lastarg); fail_0: - Py_DECREF(opath); - return NULL; + Py_DECREF(opath); + return NULL; } #endif /* HAVE_EXECV */ @@ -3224,86 +3225,86 @@ "spawnv(mode, path, args)\n\n\ Execute the program 'path' in a new process.\n\ \n\ - mode: mode of process creation\n\ - path: path of executable file\n\ - args: tuple or list of strings"); + mode: mode of process creation\n\ + path: path of executable file\n\ + args: tuple or list of strings"); static PyObject * posix_spawnv(PyObject *self, PyObject *args) { - PyObject *opath; - char *path; - PyObject *argv; - char **argvlist; - int mode, i; - Py_ssize_t argc; - Py_intptr_t spawnval; - PyObject *(*getitem)(PyObject *, Py_ssize_t); - - /* spawnv has three arguments: (mode, path, argv), where - argv is a list or tuple of strings. */ - - if (!PyArg_ParseTuple(args, "iO&O:spawnv", &mode, - PyUnicode_FSConverter, - &opath, &argv)) - return NULL; - path = PyBytes_AsString(opath); - if (PyList_Check(argv)) { - argc = PyList_Size(argv); - getitem = PyList_GetItem; - } - else if (PyTuple_Check(argv)) { - argc = PyTuple_Size(argv); - getitem = PyTuple_GetItem; - } - else { - PyErr_SetString(PyExc_TypeError, - "spawnv() arg 2 must be a tuple or list"); - Py_DECREF(opath); - return NULL; - } - - argvlist = PyMem_NEW(char *, argc+1); - if (argvlist == NULL) { - Py_DECREF(opath); - return PyErr_NoMemory(); - } - for (i = 0; i < argc; i++) { - if (!fsconvert_strdup((*getitem)(argv, i), - &argvlist[i])) { - free_string_array(argvlist, i); - PyErr_SetString( - PyExc_TypeError, - "spawnv() arg 2 must contain only strings"); - Py_DECREF(opath); - return NULL; - } - } - argvlist[argc] = NULL; + PyObject *opath; + char *path; + PyObject *argv; + char **argvlist; + int mode, i; + Py_ssize_t argc; + Py_intptr_t spawnval; + PyObject *(*getitem)(PyObject *, Py_ssize_t); + + /* spawnv has three arguments: (mode, path, argv), where + argv is a list or tuple of strings. */ + + if (!PyArg_ParseTuple(args, "iO&O:spawnv", &mode, + PyUnicode_FSConverter, + &opath, &argv)) + return NULL; + path = PyBytes_AsString(opath); + if (PyList_Check(argv)) { + argc = PyList_Size(argv); + getitem = PyList_GetItem; + } + else if (PyTuple_Check(argv)) { + argc = PyTuple_Size(argv); + getitem = PyTuple_GetItem; + } + else { + PyErr_SetString(PyExc_TypeError, + "spawnv() arg 2 must be a tuple or list"); + Py_DECREF(opath); + return NULL; + } + + argvlist = PyMem_NEW(char *, argc+1); + if (argvlist == NULL) { + Py_DECREF(opath); + return PyErr_NoMemory(); + } + for (i = 0; i < argc; i++) { + if (!fsconvert_strdup((*getitem)(argv, i), + &argvlist[i])) { + free_string_array(argvlist, i); + PyErr_SetString( + PyExc_TypeError, + "spawnv() arg 2 must contain only strings"); + Py_DECREF(opath); + return NULL; + } + } + argvlist[argc] = NULL; #if defined(PYOS_OS2) && defined(PYCC_GCC) - Py_BEGIN_ALLOW_THREADS - spawnval = spawnv(mode, path, argvlist); - Py_END_ALLOW_THREADS + Py_BEGIN_ALLOW_THREADS + spawnval = spawnv(mode, path, argvlist); + Py_END_ALLOW_THREADS #else - if (mode == _OLD_P_OVERLAY) - mode = _P_OVERLAY; + if (mode == _OLD_P_OVERLAY) + mode = _P_OVERLAY; - Py_BEGIN_ALLOW_THREADS - spawnval = _spawnv(mode, path, argvlist); - Py_END_ALLOW_THREADS + Py_BEGIN_ALLOW_THREADS + spawnval = _spawnv(mode, path, argvlist); + Py_END_ALLOW_THREADS #endif - free_string_array(argvlist, argc); - Py_DECREF(opath); + free_string_array(argvlist, argc); + Py_DECREF(opath); - if (spawnval == -1) - return posix_error(); - else + if (spawnval == -1) + return posix_error(); + else #if SIZEOF_LONG == SIZEOF_VOID_P - return Py_BuildValue("l", (long) spawnval); + return Py_BuildValue("l", (long) spawnval); #else - return Py_BuildValue("L", (PY_LONG_LONG) spawnval); + return Py_BuildValue("L", (PY_LONG_LONG) spawnval); #endif } @@ -3312,104 +3313,104 @@ "spawnve(mode, path, args, env)\n\n\ Execute the program 'path' in a new process.\n\ \n\ - mode: mode of process creation\n\ - path: path of executable file\n\ - args: tuple or list of arguments\n\ - env: dictionary of strings mapping to strings"); + mode: mode of process creation\n\ + path: path of executable file\n\ + args: tuple or list of arguments\n\ + env: dictionary of strings mapping to strings"); static PyObject * posix_spawnve(PyObject *self, PyObject *args) { - PyObject *opath; - char *path; - PyObject *argv, *env; - char **argvlist; - char **envlist; - PyObject *res = NULL; - int mode, envc; - Py_ssize_t argc, i; - Py_intptr_t spawnval; - PyObject *(*getitem)(PyObject *, Py_ssize_t); - Py_ssize_t lastarg = 0; - - /* spawnve has four arguments: (mode, path, argv, env), where - argv is a list or tuple of strings and env is a dictionary - like posix.environ. */ - - if (!PyArg_ParseTuple(args, "iO&OO:spawnve", &mode, - PyUnicode_FSConverter, - &opath, &argv, &env)) - return NULL; - path = PyBytes_AsString(opath); - if (PyList_Check(argv)) { - argc = PyList_Size(argv); - getitem = PyList_GetItem; - } - else if (PyTuple_Check(argv)) { - argc = PyTuple_Size(argv); - getitem = PyTuple_GetItem; - } - else { - PyErr_SetString(PyExc_TypeError, - "spawnve() arg 2 must be a tuple or list"); - goto fail_0; - } - if (!PyMapping_Check(env)) { - PyErr_SetString(PyExc_TypeError, - "spawnve() arg 3 must be a mapping object"); - goto fail_0; - } - - argvlist = PyMem_NEW(char *, argc+1); - if (argvlist == NULL) { - PyErr_NoMemory(); - goto fail_0; - } - for (i = 0; i < argc; i++) { - if (!fsconvert_strdup((*getitem)(argv, i), - &argvlist[i])) - { - lastarg = i; - goto fail_1; - } - } - lastarg = argc; - argvlist[argc] = NULL; - - envlist = parse_envlist(env, &envc); - if (envlist == NULL) - goto fail_1; + PyObject *opath; + char *path; + PyObject *argv, *env; + char **argvlist; + char **envlist; + PyObject *res = NULL; + int mode, envc; + Py_ssize_t argc, i; + Py_intptr_t spawnval; + PyObject *(*getitem)(PyObject *, Py_ssize_t); + Py_ssize_t lastarg = 0; + + /* spawnve has four arguments: (mode, path, argv, env), where + argv is a list or tuple of strings and env is a dictionary + like posix.environ. */ + + if (!PyArg_ParseTuple(args, "iO&OO:spawnve", &mode, + PyUnicode_FSConverter, + &opath, &argv, &env)) + return NULL; + path = PyBytes_AsString(opath); + if (PyList_Check(argv)) { + argc = PyList_Size(argv); + getitem = PyList_GetItem; + } + else if (PyTuple_Check(argv)) { + argc = PyTuple_Size(argv); + getitem = PyTuple_GetItem; + } + else { + PyErr_SetString(PyExc_TypeError, + "spawnve() arg 2 must be a tuple or list"); + goto fail_0; + } + if (!PyMapping_Check(env)) { + PyErr_SetString(PyExc_TypeError, + "spawnve() arg 3 must be a mapping object"); + goto fail_0; + } + + argvlist = PyMem_NEW(char *, argc+1); + if (argvlist == NULL) { + PyErr_NoMemory(); + goto fail_0; + } + for (i = 0; i < argc; i++) { + if (!fsconvert_strdup((*getitem)(argv, i), + &argvlist[i])) + { + lastarg = i; + goto fail_1; + } + } + lastarg = argc; + argvlist[argc] = NULL; + + envlist = parse_envlist(env, &envc); + if (envlist == NULL) + goto fail_1; #if defined(PYOS_OS2) && defined(PYCC_GCC) - Py_BEGIN_ALLOW_THREADS - spawnval = spawnve(mode, path, argvlist, envlist); - Py_END_ALLOW_THREADS + Py_BEGIN_ALLOW_THREADS + spawnval = spawnve(mode, path, argvlist, envlist); + Py_END_ALLOW_THREADS #else - if (mode == _OLD_P_OVERLAY) - mode = _P_OVERLAY; + if (mode == _OLD_P_OVERLAY) + mode = _P_OVERLAY; - Py_BEGIN_ALLOW_THREADS - spawnval = _spawnve(mode, path, argvlist, envlist); - Py_END_ALLOW_THREADS + Py_BEGIN_ALLOW_THREADS + spawnval = _spawnve(mode, path, argvlist, envlist); + Py_END_ALLOW_THREADS #endif - if (spawnval == -1) - (void) posix_error(); - else + if (spawnval == -1) + (void) posix_error(); + else #if SIZEOF_LONG == SIZEOF_VOID_P - res = Py_BuildValue("l", (long) spawnval); + res = Py_BuildValue("l", (long) spawnval); #else - res = Py_BuildValue("L", (PY_LONG_LONG) spawnval); + res = Py_BuildValue("L", (PY_LONG_LONG) spawnval); #endif - while (--envc >= 0) - PyMem_DEL(envlist[envc]); - PyMem_DEL(envlist); + while (--envc >= 0) + PyMem_DEL(envlist[envc]); + PyMem_DEL(envlist); fail_1: - free_string_array(argvlist, lastarg); + free_string_array(argvlist, lastarg); fail_0: - Py_DECREF(opath); - return res; + Py_DECREF(opath); + return res; } /* OS/2 supports spawnvp & spawnvpe natively */ @@ -3419,77 +3420,77 @@ Execute the program 'file' in a new process, using the environment\n\ search path to find the file.\n\ \n\ - mode: mode of process creation\n\ - file: executable file name\n\ - args: tuple or list of strings"); + mode: mode of process creation\n\ + file: executable file name\n\ + args: tuple or list of strings"); static PyObject * posix_spawnvp(PyObject *self, PyObject *args) { - PyObject *opath; - char *path; - PyObject *argv; - char **argvlist; - int mode, i, argc; - Py_intptr_t spawnval; - PyObject *(*getitem)(PyObject *, Py_ssize_t); - - /* spawnvp has three arguments: (mode, path, argv), where - argv is a list or tuple of strings. */ - - if (!PyArg_ParseTuple(args, "iO&O:spawnvp", &mode, - PyUnicode_FSConverter, - &opath, &argv)) - return NULL; - path = PyBytes_AsString(opath); - if (PyList_Check(argv)) { - argc = PyList_Size(argv); - getitem = PyList_GetItem; - } - else if (PyTuple_Check(argv)) { - argc = PyTuple_Size(argv); - getitem = PyTuple_GetItem; - } - else { - PyErr_SetString(PyExc_TypeError, - "spawnvp() arg 2 must be a tuple or list"); - Py_DECREF(opath); - return NULL; - } - - argvlist = PyMem_NEW(char *, argc+1); - if (argvlist == NULL) { - Py_DECREF(opath); - return PyErr_NoMemory(); - } - for (i = 0; i < argc; i++) { - if (!fsconvert_strdup((*getitem)(argv, i), - &argvlist[i])) { - free_string_array(argvlist, i); - PyErr_SetString( - PyExc_TypeError, - "spawnvp() arg 2 must contain only strings"); - Py_DECREF(opath); - return NULL; - } - } - argvlist[argc] = NULL; + PyObject *opath; + char *path; + PyObject *argv; + char **argvlist; + int mode, i, argc; + Py_intptr_t spawnval; + PyObject *(*getitem)(PyObject *, Py_ssize_t); + + /* spawnvp has three arguments: (mode, path, argv), where + argv is a list or tuple of strings. */ + + if (!PyArg_ParseTuple(args, "iO&O:spawnvp", &mode, + PyUnicode_FSConverter, + &opath, &argv)) + return NULL; + path = PyBytes_AsString(opath); + if (PyList_Check(argv)) { + argc = PyList_Size(argv); + getitem = PyList_GetItem; + } + else if (PyTuple_Check(argv)) { + argc = PyTuple_Size(argv); + getitem = PyTuple_GetItem; + } + else { + PyErr_SetString(PyExc_TypeError, + "spawnvp() arg 2 must be a tuple or list"); + Py_DECREF(opath); + return NULL; + } + + argvlist = PyMem_NEW(char *, argc+1); + if (argvlist == NULL) { + Py_DECREF(opath); + return PyErr_NoMemory(); + } + for (i = 0; i < argc; i++) { + if (!fsconvert_strdup((*getitem)(argv, i), + &argvlist[i])) { + free_string_array(argvlist, i); + PyErr_SetString( + PyExc_TypeError, + "spawnvp() arg 2 must contain only strings"); + Py_DECREF(opath); + return NULL; + } + } + argvlist[argc] = NULL; - Py_BEGIN_ALLOW_THREADS + Py_BEGIN_ALLOW_THREADS #if defined(PYCC_GCC) - spawnval = spawnvp(mode, path, argvlist); + spawnval = spawnvp(mode, path, argvlist); #else - spawnval = _spawnvp(mode, path, argvlist); + spawnval = _spawnvp(mode, path, argvlist); #endif - Py_END_ALLOW_THREADS + Py_END_ALLOW_THREADS - free_string_array(argvlist, argc); - Py_DECREF(opath); + free_string_array(argvlist, argc); + Py_DECREF(opath); - if (spawnval == -1) - return posix_error(); - else - return Py_BuildValue("l", (long) spawnval); + if (spawnval == -1) + return posix_error(); + else + return Py_BuildValue("l", (long) spawnval); } @@ -3498,94 +3499,94 @@ Execute the program 'file' in a new process, using the environment\n\ search path to find the file.\n\ \n\ - mode: mode of process creation\n\ - file: executable file name\n\ - args: tuple or list of arguments\n\ - env: dictionary of strings mapping to strings"); + mode: mode of process creation\n\ + file: executable file name\n\ + args: tuple or list of arguments\n\ + env: dictionary of strings mapping to strings"); static PyObject * posix_spawnvpe(PyObject *self, PyObject *args) { - PyObject *opath - char *path; - PyObject *argv, *env; - char **argvlist; - char **envlist; - PyObject *res=NULL; - int mode, i, argc, envc; - Py_intptr_t spawnval; - PyObject *(*getitem)(PyObject *, Py_ssize_t); - int lastarg = 0; - - /* spawnvpe has four arguments: (mode, path, argv, env), where - argv is a list or tuple of strings and env is a dictionary - like posix.environ. */ - - if (!PyArg_ParseTuple(args, "ietOO:spawnvpe", &mode, - PyUnicode_FSConverter, - &opath, &argv, &env)) - return NULL; - path = PyBytes_AsString(opath); - if (PyList_Check(argv)) { - argc = PyList_Size(argv); - getitem = PyList_GetItem; - } - else if (PyTuple_Check(argv)) { - argc = PyTuple_Size(argv); - getitem = PyTuple_GetItem; - } - else { - PyErr_SetString(PyExc_TypeError, - "spawnvpe() arg 2 must be a tuple or list"); - goto fail_0; - } - if (!PyMapping_Check(env)) { - PyErr_SetString(PyExc_TypeError, - "spawnvpe() arg 3 must be a mapping object"); - goto fail_0; - } - - argvlist = PyMem_NEW(char *, argc+1); - if (argvlist == NULL) { - PyErr_NoMemory(); - goto fail_0; - } - for (i = 0; i < argc; i++) { - if (!fsconvert_strdup((*getitem)(argv, i), - &argvlist[i])) - { - lastarg = i; - goto fail_1; - } - } - lastarg = argc; - argvlist[argc] = NULL; - - envlist = parse_envlist(env, &envc); - if (envlist == NULL) - goto fail_1; + PyObject *opath + char *path; + PyObject *argv, *env; + char **argvlist; + char **envlist; + PyObject *res=NULL; + int mode, i, argc, envc; + Py_intptr_t spawnval; + PyObject *(*getitem)(PyObject *, Py_ssize_t); + int lastarg = 0; + + /* spawnvpe has four arguments: (mode, path, argv, env), where + argv is a list or tuple of strings and env is a dictionary + like posix.environ. */ + + if (!PyArg_ParseTuple(args, "ietOO:spawnvpe", &mode, + PyUnicode_FSConverter, + &opath, &argv, &env)) + return NULL; + path = PyBytes_AsString(opath); + if (PyList_Check(argv)) { + argc = PyList_Size(argv); + getitem = PyList_GetItem; + } + else if (PyTuple_Check(argv)) { + argc = PyTuple_Size(argv); + getitem = PyTuple_GetItem; + } + else { + PyErr_SetString(PyExc_TypeError, + "spawnvpe() arg 2 must be a tuple or list"); + goto fail_0; + } + if (!PyMapping_Check(env)) { + PyErr_SetString(PyExc_TypeError, + "spawnvpe() arg 3 must be a mapping object"); + goto fail_0; + } + + argvlist = PyMem_NEW(char *, argc+1); + if (argvlist == NULL) { + PyErr_NoMemory(); + goto fail_0; + } + for (i = 0; i < argc; i++) { + if (!fsconvert_strdup((*getitem)(argv, i), + &argvlist[i])) + { + lastarg = i; + goto fail_1; + } + } + lastarg = argc; + argvlist[argc] = NULL; + + envlist = parse_envlist(env, &envc); + if (envlist == NULL) + goto fail_1; - Py_BEGIN_ALLOW_THREADS + Py_BEGIN_ALLOW_THREADS #if defined(PYCC_GCC) - spawnval = spawnvpe(mode, path, argvlist, envlist); + spawnval = spawnvpe(mode, path, argvlist, envlist); #else - spawnval = _spawnvpe(mode, path, argvlist, envlist); + spawnval = _spawnvpe(mode, path, argvlist, envlist); #endif - Py_END_ALLOW_THREADS + Py_END_ALLOW_THREADS - if (spawnval == -1) - (void) posix_error(); - else - res = Py_BuildValue("l", (long) spawnval); + if (spawnval == -1) + (void) posix_error(); + else + res = Py_BuildValue("l", (long) spawnval); - while (--envc >= 0) - PyMem_DEL(envlist[envc]); - PyMem_DEL(envlist); + while (--envc >= 0) + PyMem_DEL(envlist[envc]); + PyMem_DEL(envlist); fail_1: - free_string_array(argvlist, lastarg); + free_string_array(argvlist, lastarg); fail_0: - Py_DECREF(opath); - return res; + Py_DECREF(opath); + return res; } #endif /* PYOS_OS2 */ #endif /* HAVE_SPAWNV */ @@ -3601,26 +3602,26 @@ static PyObject * posix_fork1(PyObject *self, PyObject *noargs) { - pid_t pid; - int result = 0; - _PyImport_AcquireLock(); - pid = fork1(); - if (pid == 0) { - /* child: this clobbers and resets the import lock. */ - PyOS_AfterFork(); - } else { - /* parent: release the import lock. */ - result = _PyImport_ReleaseLock(); - } - if (pid == -1) - return posix_error(); - if (result < 0) { - /* Don't clobber the OSError if the fork failed. */ - PyErr_SetString(PyExc_RuntimeError, - "not holding the import lock"); - return NULL; - } - return PyLong_FromPid(pid); + pid_t pid; + int result = 0; + _PyImport_AcquireLock(); + pid = fork1(); + if (pid == 0) { + /* child: this clobbers and resets the import lock. */ + PyOS_AfterFork(); + } else { + /* parent: release the import lock. */ + result = _PyImport_ReleaseLock(); + } + if (pid == -1) + return posix_error(); + if (result < 0) { + /* Don't clobber the OSError if the fork failed. */ + PyErr_SetString(PyExc_RuntimeError, + "not holding the import lock"); + return NULL; + } + return PyLong_FromPid(pid); } #endif @@ -3634,26 +3635,26 @@ static PyObject * posix_fork(PyObject *self, PyObject *noargs) { - pid_t pid; - int result = 0; - _PyImport_AcquireLock(); - pid = fork(); - if (pid == 0) { - /* child: this clobbers and resets the import lock. */ - PyOS_AfterFork(); - } else { - /* parent: release the import lock. */ - result = _PyImport_ReleaseLock(); - } - if (pid == -1) - return posix_error(); - if (result < 0) { - /* Don't clobber the OSError if the fork failed. */ - PyErr_SetString(PyExc_RuntimeError, - "not holding the import lock"); - return NULL; - } - return PyLong_FromPid(pid); + pid_t pid; + int result = 0; + _PyImport_AcquireLock(); + pid = fork(); + if (pid == 0) { + /* child: this clobbers and resets the import lock. */ + PyOS_AfterFork(); + } else { + /* parent: release the import lock. */ + result = _PyImport_ReleaseLock(); + } + if (pid == -1) + return posix_error(); + if (result < 0) { + /* Don't clobber the OSError if the fork failed. */ + PyErr_SetString(PyExc_RuntimeError, + "not holding the import lock"); + return NULL; + } + return PyLong_FromPid(pid); } #endif @@ -3691,60 +3692,60 @@ static PyObject * posix_openpty(PyObject *self, PyObject *noargs) { - int master_fd, slave_fd; + int master_fd, slave_fd; #ifndef HAVE_OPENPTY - char * slave_name; + char * slave_name; #endif #if defined(HAVE_DEV_PTMX) && !defined(HAVE_OPENPTY) && !defined(HAVE__GETPTY) - PyOS_sighandler_t sig_saved; + PyOS_sighandler_t sig_saved; #ifdef sun - extern char *ptsname(int fildes); + extern char *ptsname(int fildes); #endif #endif #ifdef HAVE_OPENPTY - if (openpty(&master_fd, &slave_fd, NULL, NULL, NULL) != 0) - return posix_error(); + if (openpty(&master_fd, &slave_fd, NULL, NULL, NULL) != 0) + return posix_error(); #elif defined(HAVE__GETPTY) - slave_name = _getpty(&master_fd, O_RDWR, 0666, 0); - if (slave_name == NULL) - return posix_error(); - - slave_fd = open(slave_name, O_RDWR); - if (slave_fd < 0) - return posix_error(); -#else - master_fd = open(DEV_PTY_FILE, O_RDWR | O_NOCTTY); /* open master */ - if (master_fd < 0) - return posix_error(); - sig_saved = PyOS_setsig(SIGCHLD, SIG_DFL); - /* change permission of slave */ - if (grantpt(master_fd) < 0) { - PyOS_setsig(SIGCHLD, sig_saved); - return posix_error(); - } - /* unlock slave */ - if (unlockpt(master_fd) < 0) { - PyOS_setsig(SIGCHLD, sig_saved); - return posix_error(); - } - PyOS_setsig(SIGCHLD, sig_saved); - slave_name = ptsname(master_fd); /* get name of slave */ - if (slave_name == NULL) - return posix_error(); - slave_fd = open(slave_name, O_RDWR | O_NOCTTY); /* open slave */ - if (slave_fd < 0) - return posix_error(); + slave_name = _getpty(&master_fd, O_RDWR, 0666, 0); + if (slave_name == NULL) + return posix_error(); + + slave_fd = open(slave_name, O_RDWR); + if (slave_fd < 0) + return posix_error(); +#else + master_fd = open(DEV_PTY_FILE, O_RDWR | O_NOCTTY); /* open master */ + if (master_fd < 0) + return posix_error(); + sig_saved = PyOS_setsig(SIGCHLD, SIG_DFL); + /* change permission of slave */ + if (grantpt(master_fd) < 0) { + PyOS_setsig(SIGCHLD, sig_saved); + return posix_error(); + } + /* unlock slave */ + if (unlockpt(master_fd) < 0) { + PyOS_setsig(SIGCHLD, sig_saved); + return posix_error(); + } + PyOS_setsig(SIGCHLD, sig_saved); + slave_name = ptsname(master_fd); /* get name of slave */ + if (slave_name == NULL) + return posix_error(); + slave_fd = open(slave_name, O_RDWR | O_NOCTTY); /* open slave */ + if (slave_fd < 0) + return posix_error(); #if !defined(__CYGWIN__) && !defined(HAVE_DEV_PTC) - ioctl(slave_fd, I_PUSH, "ptem"); /* push ptem */ - ioctl(slave_fd, I_PUSH, "ldterm"); /* push ldterm */ + ioctl(slave_fd, I_PUSH, "ptem"); /* push ptem */ + ioctl(slave_fd, I_PUSH, "ldterm"); /* push ldterm */ #ifndef __hpux - ioctl(slave_fd, I_PUSH, "ttcompat"); /* push ttcompat */ + ioctl(slave_fd, I_PUSH, "ttcompat"); /* push ttcompat */ #endif /* __hpux */ #endif /* HAVE_CYGWIN */ #endif /* HAVE_OPENPTY */ - return Py_BuildValue("(ii)", master_fd, slave_fd); + return Py_BuildValue("(ii)", master_fd, slave_fd); } #endif /* defined(HAVE_OPENPTY) || defined(HAVE__GETPTY) || defined(HAVE_DEV_PTMX) */ @@ -3759,27 +3760,27 @@ static PyObject * posix_forkpty(PyObject *self, PyObject *noargs) { - int master_fd = -1, result = 0; - pid_t pid; + int master_fd = -1, result = 0; + pid_t pid; - _PyImport_AcquireLock(); - pid = forkpty(&master_fd, NULL, NULL, NULL); - if (pid == 0) { - /* child: this clobbers and resets the import lock. */ - PyOS_AfterFork(); - } else { - /* parent: release the import lock. */ - result = _PyImport_ReleaseLock(); - } - if (pid == -1) - return posix_error(); - if (result < 0) { - /* Don't clobber the OSError if the fork failed. */ - PyErr_SetString(PyExc_RuntimeError, - "not holding the import lock"); - return NULL; - } - return Py_BuildValue("(Ni)", PyLong_FromPid(pid), master_fd); + _PyImport_AcquireLock(); + pid = forkpty(&master_fd, NULL, NULL, NULL); + if (pid == 0) { + /* child: this clobbers and resets the import lock. */ + PyOS_AfterFork(); + } else { + /* parent: release the import lock. */ + result = _PyImport_ReleaseLock(); + } + if (pid == -1) + return posix_error(); + if (result < 0) { + /* Don't clobber the OSError if the fork failed. */ + PyErr_SetString(PyExc_RuntimeError, + "not holding the import lock"); + return NULL; + } + return Py_BuildValue("(Ni)", PyLong_FromPid(pid), master_fd); } #endif @@ -3791,7 +3792,7 @@ static PyObject * posix_getegid(PyObject *self, PyObject *noargs) { - return PyLong_FromLong((long)getegid()); + return PyLong_FromLong((long)getegid()); } #endif @@ -3804,7 +3805,7 @@ static PyObject * posix_geteuid(PyObject *self, PyObject *noargs) { - return PyLong_FromLong((long)geteuid()); + return PyLong_FromLong((long)geteuid()); } #endif @@ -3817,7 +3818,7 @@ static PyObject * posix_getgid(PyObject *self, PyObject *noargs) { - return PyLong_FromLong((long)getgid()); + return PyLong_FromLong((long)getgid()); } #endif @@ -3829,7 +3830,7 @@ static PyObject * posix_getpid(PyObject *self, PyObject *noargs) { - return PyLong_FromPid(getpid()); + return PyLong_FromPid(getpid()); } @@ -3846,30 +3847,30 @@ #ifdef NGROUPS_MAX #define MAX_GROUPS NGROUPS_MAX #else - /* defined to be 16 on Solaris7, so this should be a small number */ + /* defined to be 16 on Solaris7, so this should be a small number */ #define MAX_GROUPS 64 #endif - gid_t grouplist[MAX_GROUPS]; - int n; + gid_t grouplist[MAX_GROUPS]; + int n; - n = getgroups(MAX_GROUPS, grouplist); - if (n < 0) - posix_error(); - else { - result = PyList_New(n); - if (result != NULL) { - int i; - for (i = 0; i < n; ++i) { - PyObject *o = PyLong_FromLong((long)grouplist[i]); - if (o == NULL) { - Py_DECREF(result); - result = NULL; - break; - } - PyList_SET_ITEM(result, i, o); - } + n = getgroups(MAX_GROUPS, grouplist); + if (n < 0) + posix_error(); + else { + result = PyList_New(n); + if (result != NULL) { + int i; + for (i = 0; i < n; ++i) { + PyObject *o = PyLong_FromLong((long)grouplist[i]); + if (o == NULL) { + Py_DECREF(result); + result = NULL; + break; } + PyList_SET_ITEM(result, i, o); + } } + } return result; } @@ -3885,17 +3886,17 @@ static PyObject * posix_initgroups(PyObject *self, PyObject *args) { - char *username; - long gid; + char *username; + long gid; - if (!PyArg_ParseTuple(args, "sl:initgroups", &username, &gid)) - return NULL; + if (!PyArg_ParseTuple(args, "sl:initgroups", &username, &gid)) + return NULL; - if (initgroups(username, (gid_t) gid) == -1) - return PyErr_SetFromErrno(PyExc_OSError); + if (initgroups(username, (gid_t) gid) == -1) + return PyErr_SetFromErrno(PyExc_OSError); - Py_INCREF(Py_None); - return Py_None; + Py_INCREF(Py_None); + return Py_None; } #endif @@ -3907,13 +3908,13 @@ static PyObject * posix_getpgid(PyObject *self, PyObject *args) { - pid_t pid, pgid; - if (!PyArg_ParseTuple(args, _Py_PARSE_PID ":getpgid", &pid)) - return NULL; - pgid = getpgid(pid); - if (pgid < 0) - return posix_error(); - return PyLong_FromPid(pgid); + pid_t pid, pgid; + if (!PyArg_ParseTuple(args, _Py_PARSE_PID ":getpgid", &pid)) + return NULL; + pgid = getpgid(pid); + if (pgid < 0) + return posix_error(); + return PyLong_FromPid(pgid); } #endif /* HAVE_GETPGID */ @@ -3927,9 +3928,9 @@ posix_getpgrp(PyObject *self, PyObject *noargs) { #ifdef GETPGRP_HAVE_ARG - return PyLong_FromPid(getpgrp(0)); + return PyLong_FromPid(getpgrp(0)); #else /* GETPGRP_HAVE_ARG */ - return PyLong_FromPid(getpgrp()); + return PyLong_FromPid(getpgrp()); #endif /* GETPGRP_HAVE_ARG */ } #endif /* HAVE_GETPGRP */ @@ -3944,13 +3945,13 @@ posix_setpgrp(PyObject *self, PyObject *noargs) { #ifdef SETPGRP_HAVE_ARG - if (setpgrp(0, 0) < 0) + if (setpgrp(0, 0) < 0) #else /* SETPGRP_HAVE_ARG */ - if (setpgrp() < 0) + if (setpgrp() < 0) #endif /* SETPGRP_HAVE_ARG */ - return posix_error(); - Py_INCREF(Py_None); - return Py_None; + return posix_error(); + Py_INCREF(Py_None); + return Py_None; } #endif /* HAVE_SETPGRP */ @@ -3963,7 +3964,7 @@ static PyObject * posix_getppid(PyObject *self, PyObject *noargs) { - return PyLong_FromPid(getppid()); + return PyLong_FromPid(getppid()); } #endif @@ -3976,22 +3977,22 @@ static PyObject * posix_getlogin(PyObject *self, PyObject *noargs) { - PyObject *result = NULL; - char *name; - int old_errno = errno; + PyObject *result = NULL; + char *name; + int old_errno = errno; - errno = 0; - name = getlogin(); - if (name == NULL) { - if (errno) - posix_error(); - else - PyErr_SetString(PyExc_OSError, - "unable to determine login name"); - } + errno = 0; + name = getlogin(); + if (name == NULL) { + if (errno) + posix_error(); else - result = PyUnicode_FromString(name); - errno = old_errno; + PyErr_SetString(PyExc_OSError, + "unable to determine login name"); + } + else + result = PyUnicode_FromString(name); + errno = old_errno; return result; } @@ -4005,7 +4006,7 @@ static PyObject * posix_getuid(PyObject *self, PyObject *noargs) { - return PyLong_FromLong((long)getuid()); + return PyLong_FromLong((long)getuid()); } #endif @@ -4018,10 +4019,10 @@ static PyObject * posix_kill(PyObject *self, PyObject *args) { - pid_t pid; - int sig; - if (!PyArg_ParseTuple(args, _Py_PARSE_PID "i:kill", &pid, &sig)) - return NULL; + pid_t pid; + int sig; + if (!PyArg_ParseTuple(args, _Py_PARSE_PID "i:kill", &pid, &sig)) + return NULL; #if defined(PYOS_OS2) && !defined(PYCC_GCC) if (sig == XCPT_SIGNAL_INTR || sig == XCPT_SIGNAL_BREAK) { APIRET rc; @@ -4036,11 +4037,11 @@ } else return NULL; /* Unrecognized Signal Requested */ #else - if (kill(pid, sig) == -1) - return posix_error(); + if (kill(pid, sig) == -1) + return posix_error(); #endif - Py_INCREF(Py_None); - return Py_None; + Py_INCREF(Py_None); + return Py_None; } #endif @@ -4052,18 +4053,18 @@ static PyObject * posix_killpg(PyObject *self, PyObject *args) { - int sig; - pid_t pgid; - /* XXX some man pages make the `pgid` parameter an int, others - a pid_t. Since getpgrp() returns a pid_t, we assume killpg should - take the same type. Moreover, pid_t is always at least as wide as - int (else compilation of this module fails), which is safe. */ - if (!PyArg_ParseTuple(args, _Py_PARSE_PID "i:killpg", &pgid, &sig)) - return NULL; - if (killpg(pgid, sig) == -1) - return posix_error(); - Py_INCREF(Py_None); - return Py_None; + int sig; + pid_t pgid; + /* XXX some man pages make the `pgid` parameter an int, others + a pid_t. Since getpgrp() returns a pid_t, we assume killpg should + take the same type. Moreover, pid_t is always at least as wide as + int (else compilation of this module fails), which is safe. */ + if (!PyArg_ParseTuple(args, _Py_PARSE_PID "i:killpg", &pgid, &sig)) + return NULL; + if (killpg(pgid, sig) == -1) + return posix_error(); + Py_INCREF(Py_None); + return Py_None; } #endif @@ -4075,42 +4076,42 @@ static PyObject * win32_kill(PyObject *self, PyObject *args) { - PyObject *result, handle_obj; - DWORD pid, sig, err; - HANDLE handle; - - if (!PyArg_ParseTuple(args, "kk:kill", &pid, &sig)) - return NULL; - - /* Console processes which share a common console can be sent CTRL+C or - CTRL+BREAK events, provided they handle said events. */ - if (sig == CTRL_C_EVENT || sig == CTRL_BREAK_EVENT) { - if (GenerateConsoleCtrlEvent(sig, pid) == 0) { - err = GetLastError(); - PyErr_SetFromWindowsErr(err); - } - else - Py_RETURN_NONE; - } - - /* If the signal is outside of what GenerateConsoleCtrlEvent can use, - attempt to open and terminate the process. */ - handle = OpenProcess(PROCESS_ALL_ACCESS, FALSE, pid); - if (handle == NULL) { - err = GetLastError(); - return PyErr_SetFromWindowsErr(err); - } - - if (TerminateProcess(handle, sig) == 0) { - err = GetLastError(); - result = PyErr_SetFromWindowsErr(err); - } else { - Py_INCREF(Py_None); - result = Py_None; - } + PyObject *result, handle_obj; + DWORD pid, sig, err; + HANDLE handle; + + if (!PyArg_ParseTuple(args, "kk:kill", &pid, &sig)) + return NULL; + + /* Console processes which share a common console can be sent CTRL+C or + CTRL+BREAK events, provided they handle said events. */ + if (sig == CTRL_C_EVENT || sig == CTRL_BREAK_EVENT) { + if (GenerateConsoleCtrlEvent(sig, pid) == 0) { + err = GetLastError(); + PyErr_SetFromWindowsErr(err); + } + else + Py_RETURN_NONE; + } + + /* If the signal is outside of what GenerateConsoleCtrlEvent can use, + attempt to open and terminate the process. */ + handle = OpenProcess(PROCESS_ALL_ACCESS, FALSE, pid); + if (handle == NULL) { + err = GetLastError(); + return PyErr_SetFromWindowsErr(err); + } - CloseHandle(handle); - return result; + if (TerminateProcess(handle, sig) == 0) { + err = GetLastError(); + result = PyErr_SetFromWindowsErr(err); + } else { + Py_INCREF(Py_None); + result = Py_None; + } + + CloseHandle(handle); + return result; } #endif /* MS_WINDOWS */ @@ -4127,13 +4128,13 @@ static PyObject * posix_plock(PyObject *self, PyObject *args) { - int op; - if (!PyArg_ParseTuple(args, "i:plock", &op)) - return NULL; - if (plock(op) == -1) - return posix_error(); - Py_INCREF(Py_None); - return Py_None; + int op; + if (!PyArg_ParseTuple(args, "i:plock", &op)) + return NULL; + if (plock(op) == -1) + return posix_error(); + Py_INCREF(Py_None); + return Py_None; } #endif @@ -4145,19 +4146,19 @@ static PyObject * posix_setuid(PyObject *self, PyObject *args) { - long uid_arg; - uid_t uid; - if (!PyArg_ParseTuple(args, "l:setuid", &uid_arg)) - return NULL; - uid = uid_arg; - if (uid != uid_arg) { - PyErr_SetString(PyExc_OverflowError, "user id too big"); - return NULL; - } - if (setuid(uid) < 0) - return posix_error(); - Py_INCREF(Py_None); - return Py_None; + long uid_arg; + uid_t uid; + if (!PyArg_ParseTuple(args, "l:setuid", &uid_arg)) + return NULL; + uid = uid_arg; + if (uid != uid_arg) { + PyErr_SetString(PyExc_OverflowError, "user id too big"); + return NULL; + } + if (setuid(uid) < 0) + return posix_error(); + Py_INCREF(Py_None); + return Py_None; } #endif /* HAVE_SETUID */ @@ -4170,21 +4171,21 @@ static PyObject * posix_seteuid (PyObject *self, PyObject *args) { - long euid_arg; - uid_t euid; - if (!PyArg_ParseTuple(args, "l", &euid_arg)) - return NULL; - euid = euid_arg; - if (euid != euid_arg) { - PyErr_SetString(PyExc_OverflowError, "user id too big"); - return NULL; - } - if (seteuid(euid) < 0) { - return posix_error(); - } else { - Py_INCREF(Py_None); - return Py_None; - } + long euid_arg; + uid_t euid; + if (!PyArg_ParseTuple(args, "l", &euid_arg)) + return NULL; + euid = euid_arg; + if (euid != euid_arg) { + PyErr_SetString(PyExc_OverflowError, "user id too big"); + return NULL; + } + if (seteuid(euid) < 0) { + return posix_error(); + } else { + Py_INCREF(Py_None); + return Py_None; + } } #endif /* HAVE_SETEUID */ @@ -4196,21 +4197,21 @@ static PyObject * posix_setegid (PyObject *self, PyObject *args) { - long egid_arg; - gid_t egid; - if (!PyArg_ParseTuple(args, "l", &egid_arg)) - return NULL; - egid = egid_arg; - if (egid != egid_arg) { - PyErr_SetString(PyExc_OverflowError, "group id too big"); - return NULL; - } - if (setegid(egid) < 0) { - return posix_error(); - } else { - Py_INCREF(Py_None); - return Py_None; - } + long egid_arg; + gid_t egid; + if (!PyArg_ParseTuple(args, "l", &egid_arg)) + return NULL; + egid = egid_arg; + if (egid != egid_arg) { + PyErr_SetString(PyExc_OverflowError, "group id too big"); + return NULL; + } + if (setegid(egid) < 0) { + return posix_error(); + } else { + Py_INCREF(Py_None); + return Py_None; + } } #endif /* HAVE_SETEGID */ @@ -4222,29 +4223,29 @@ static PyObject * posix_setreuid (PyObject *self, PyObject *args) { - long ruid_arg, euid_arg; - uid_t ruid, euid; - if (!PyArg_ParseTuple(args, "ll", &ruid_arg, &euid_arg)) - return NULL; - if (ruid_arg == -1) - ruid = (uid_t)-1; /* let the compiler choose how -1 fits */ - else - ruid = ruid_arg; /* otherwise, assign from our long */ - if (euid_arg == -1) - euid = (uid_t)-1; - else - euid = euid_arg; - if ((euid_arg != -1 && euid != euid_arg) || - (ruid_arg != -1 && ruid != ruid_arg)) { - PyErr_SetString(PyExc_OverflowError, "user id too big"); - return NULL; - } - if (setreuid(ruid, euid) < 0) { - return posix_error(); - } else { - Py_INCREF(Py_None); - return Py_None; - } + long ruid_arg, euid_arg; + uid_t ruid, euid; + if (!PyArg_ParseTuple(args, "ll", &ruid_arg, &euid_arg)) + return NULL; + if (ruid_arg == -1) + ruid = (uid_t)-1; /* let the compiler choose how -1 fits */ + else + ruid = ruid_arg; /* otherwise, assign from our long */ + if (euid_arg == -1) + euid = (uid_t)-1; + else + euid = euid_arg; + if ((euid_arg != -1 && euid != euid_arg) || + (ruid_arg != -1 && ruid != ruid_arg)) { + PyErr_SetString(PyExc_OverflowError, "user id too big"); + return NULL; + } + if (setreuid(ruid, euid) < 0) { + return posix_error(); + } else { + Py_INCREF(Py_None); + return Py_None; + } } #endif /* HAVE_SETREUID */ @@ -4256,29 +4257,29 @@ static PyObject * posix_setregid (PyObject *self, PyObject *args) { - long rgid_arg, egid_arg; - gid_t rgid, egid; - if (!PyArg_ParseTuple(args, "ll", &rgid_arg, &egid_arg)) - return NULL; - if (rgid_arg == -1) - rgid = (gid_t)-1; /* let the compiler choose how -1 fits */ - else - rgid = rgid_arg; /* otherwise, assign from our long */ - if (egid_arg == -1) - egid = (gid_t)-1; - else - egid = egid_arg; - if ((egid_arg != -1 && egid != egid_arg) || - (rgid_arg != -1 && rgid != rgid_arg)) { - PyErr_SetString(PyExc_OverflowError, "group id too big"); - return NULL; - } - if (setregid(rgid, egid) < 0) { - return posix_error(); - } else { - Py_INCREF(Py_None); - return Py_None; - } + long rgid_arg, egid_arg; + gid_t rgid, egid; + if (!PyArg_ParseTuple(args, "ll", &rgid_arg, &egid_arg)) + return NULL; + if (rgid_arg == -1) + rgid = (gid_t)-1; /* let the compiler choose how -1 fits */ + else + rgid = rgid_arg; /* otherwise, assign from our long */ + if (egid_arg == -1) + egid = (gid_t)-1; + else + egid = egid_arg; + if ((egid_arg != -1 && egid != egid_arg) || + (rgid_arg != -1 && rgid != rgid_arg)) { + PyErr_SetString(PyExc_OverflowError, "group id too big"); + return NULL; + } + if (setregid(rgid, egid) < 0) { + return posix_error(); + } else { + Py_INCREF(Py_None); + return Py_None; + } } #endif /* HAVE_SETREGID */ @@ -4290,19 +4291,19 @@ static PyObject * posix_setgid(PyObject *self, PyObject *args) { - long gid_arg; - gid_t gid; - if (!PyArg_ParseTuple(args, "l:setgid", &gid_arg)) - return NULL; - gid = gid_arg; - if (gid != gid_arg) { - PyErr_SetString(PyExc_OverflowError, "group id too big"); - return NULL; - } - if (setgid(gid) < 0) - return posix_error(); - Py_INCREF(Py_None); - return Py_None; + long gid_arg; + gid_t gid; + if (!PyArg_ParseTuple(args, "l:setgid", &gid_arg)) + return NULL; + gid = gid_arg; + if (gid != gid_arg) { + PyErr_SetString(PyExc_OverflowError, "group id too big"); + return NULL; + } + if (setgid(gid) < 0) + return posix_error(); + Py_INCREF(Py_None); + return Py_None; } #endif /* HAVE_SETGID */ @@ -4314,52 +4315,52 @@ static PyObject * posix_setgroups(PyObject *self, PyObject *groups) { - int i, len; - gid_t grouplist[MAX_GROUPS]; + int i, len; + gid_t grouplist[MAX_GROUPS]; + + if (!PySequence_Check(groups)) { + PyErr_SetString(PyExc_TypeError, "setgroups argument must be a sequence"); + return NULL; + } + len = PySequence_Size(groups); + if (len > MAX_GROUPS) { + PyErr_SetString(PyExc_ValueError, "too many groups"); + return NULL; + } + for(i = 0; i < len; i++) { + PyObject *elem; + elem = PySequence_GetItem(groups, i); + if (!elem) + return NULL; + if (!PyLong_Check(elem)) { + PyErr_SetString(PyExc_TypeError, + "groups must be integers"); + Py_DECREF(elem); + return NULL; + } else { + unsigned long x = PyLong_AsUnsignedLong(elem); + if (PyErr_Occurred()) { + PyErr_SetString(PyExc_TypeError, + "group id too big"); + Py_DECREF(elem); + return NULL; + } + grouplist[i] = x; + /* read back the value to see if it fitted in gid_t */ + if (grouplist[i] != x) { + PyErr_SetString(PyExc_TypeError, + "group id too big"); + Py_DECREF(elem); + return NULL; + } + } + Py_DECREF(elem); + } - if (!PySequence_Check(groups)) { - PyErr_SetString(PyExc_TypeError, "setgroups argument must be a sequence"); - return NULL; - } - len = PySequence_Size(groups); - if (len > MAX_GROUPS) { - PyErr_SetString(PyExc_ValueError, "too many groups"); - return NULL; - } - for(i = 0; i < len; i++) { - PyObject *elem; - elem = PySequence_GetItem(groups, i); - if (!elem) - return NULL; - if (!PyLong_Check(elem)) { - PyErr_SetString(PyExc_TypeError, - "groups must be integers"); - Py_DECREF(elem); - return NULL; - } else { - unsigned long x = PyLong_AsUnsignedLong(elem); - if (PyErr_Occurred()) { - PyErr_SetString(PyExc_TypeError, - "group id too big"); - Py_DECREF(elem); - return NULL; - } - grouplist[i] = x; - /* read back the value to see if it fitted in gid_t */ - if (grouplist[i] != x) { - PyErr_SetString(PyExc_TypeError, - "group id too big"); - Py_DECREF(elem); - return NULL; - } - } - Py_DECREF(elem); - } - - if (setgroups(len, grouplist) < 0) - return posix_error(); - Py_INCREF(Py_None); - return Py_None; + if (setgroups(len, grouplist) < 0) + return posix_error(); + Py_INCREF(Py_None); + return Py_None; } #endif /* HAVE_SETGROUPS */ @@ -4367,59 +4368,59 @@ static PyObject * wait_helper(pid_t pid, int status, struct rusage *ru) { - PyObject *result; - static PyObject *struct_rusage; + PyObject *result; + static PyObject *struct_rusage; - if (pid == -1) - return posix_error(); + if (pid == -1) + return posix_error(); - if (struct_rusage == NULL) { - PyObject *m = PyImport_ImportModuleNoBlock("resource"); - if (m == NULL) - return NULL; - struct_rusage = PyObject_GetAttrString(m, "struct_rusage"); - Py_DECREF(m); - if (struct_rusage == NULL) - return NULL; - } - - /* XXX(nnorwitz): Copied (w/mods) from resource.c, there should be only one. */ - result = PyStructSequence_New((PyTypeObject*) struct_rusage); - if (!result) - return NULL; + if (struct_rusage == NULL) { + PyObject *m = PyImport_ImportModuleNoBlock("resource"); + if (m == NULL) + return NULL; + struct_rusage = PyObject_GetAttrString(m, "struct_rusage"); + Py_DECREF(m); + if (struct_rusage == NULL) + return NULL; + } + + /* XXX(nnorwitz): Copied (w/mods) from resource.c, there should be only one. */ + result = PyStructSequence_New((PyTypeObject*) struct_rusage); + if (!result) + return NULL; #ifndef doubletime #define doubletime(TV) ((double)(TV).tv_sec + (TV).tv_usec * 0.000001) #endif - PyStructSequence_SET_ITEM(result, 0, - PyFloat_FromDouble(doubletime(ru->ru_utime))); - PyStructSequence_SET_ITEM(result, 1, - PyFloat_FromDouble(doubletime(ru->ru_stime))); + PyStructSequence_SET_ITEM(result, 0, + PyFloat_FromDouble(doubletime(ru->ru_utime))); + PyStructSequence_SET_ITEM(result, 1, + PyFloat_FromDouble(doubletime(ru->ru_stime))); #define SET_INT(result, index, value)\ - PyStructSequence_SET_ITEM(result, index, PyLong_FromLong(value)) - SET_INT(result, 2, ru->ru_maxrss); - SET_INT(result, 3, ru->ru_ixrss); - SET_INT(result, 4, ru->ru_idrss); - SET_INT(result, 5, ru->ru_isrss); - SET_INT(result, 6, ru->ru_minflt); - SET_INT(result, 7, ru->ru_majflt); - SET_INT(result, 8, ru->ru_nswap); - SET_INT(result, 9, ru->ru_inblock); - SET_INT(result, 10, ru->ru_oublock); - SET_INT(result, 11, ru->ru_msgsnd); - SET_INT(result, 12, ru->ru_msgrcv); - SET_INT(result, 13, ru->ru_nsignals); - SET_INT(result, 14, ru->ru_nvcsw); - SET_INT(result, 15, ru->ru_nivcsw); + PyStructSequence_SET_ITEM(result, index, PyLong_FromLong(value)) + SET_INT(result, 2, ru->ru_maxrss); + SET_INT(result, 3, ru->ru_ixrss); + SET_INT(result, 4, ru->ru_idrss); + SET_INT(result, 5, ru->ru_isrss); + SET_INT(result, 6, ru->ru_minflt); + SET_INT(result, 7, ru->ru_majflt); + SET_INT(result, 8, ru->ru_nswap); + SET_INT(result, 9, ru->ru_inblock); + SET_INT(result, 10, ru->ru_oublock); + SET_INT(result, 11, ru->ru_msgsnd); + SET_INT(result, 12, ru->ru_msgrcv); + SET_INT(result, 13, ru->ru_nsignals); + SET_INT(result, 14, ru->ru_nvcsw); + SET_INT(result, 15, ru->ru_nivcsw); #undef SET_INT - if (PyErr_Occurred()) { - Py_DECREF(result); - return NULL; - } + if (PyErr_Occurred()) { + Py_DECREF(result); + return NULL; + } - return Py_BuildValue("NiN", PyLong_FromPid(pid), status, result); + return Py_BuildValue("NiN", PyLong_FromPid(pid), status, result); } #endif /* HAVE_WAIT3 || HAVE_WAIT4 */ @@ -4431,20 +4432,20 @@ static PyObject * posix_wait3(PyObject *self, PyObject *args) { - pid_t pid; - int options; - struct rusage ru; - WAIT_TYPE status; - WAIT_STATUS_INT(status) = 0; - - if (!PyArg_ParseTuple(args, "i:wait3", &options)) - return NULL; - - Py_BEGIN_ALLOW_THREADS - pid = wait3(&status, options, &ru); - Py_END_ALLOW_THREADS + pid_t pid; + int options; + struct rusage ru; + WAIT_TYPE status; + WAIT_STATUS_INT(status) = 0; + + if (!PyArg_ParseTuple(args, "i:wait3", &options)) + return NULL; + + Py_BEGIN_ALLOW_THREADS + pid = wait3(&status, options, &ru); + Py_END_ALLOW_THREADS - return wait_helper(pid, WAIT_STATUS_INT(status), &ru); + return wait_helper(pid, WAIT_STATUS_INT(status), &ru); } #endif /* HAVE_WAIT3 */ @@ -4456,20 +4457,20 @@ static PyObject * posix_wait4(PyObject *self, PyObject *args) { - pid_t pid; - int options; - struct rusage ru; - WAIT_TYPE status; - WAIT_STATUS_INT(status) = 0; - - if (!PyArg_ParseTuple(args, _Py_PARSE_PID "i:wait4", &pid, &options)) - return NULL; - - Py_BEGIN_ALLOW_THREADS - pid = wait4(pid, &status, options, &ru); - Py_END_ALLOW_THREADS + pid_t pid; + int options; + struct rusage ru; + WAIT_TYPE status; + WAIT_STATUS_INT(status) = 0; + + if (!PyArg_ParseTuple(args, _Py_PARSE_PID "i:wait4", &pid, &options)) + return NULL; - return wait_helper(pid, WAIT_STATUS_INT(status), &ru); + Py_BEGIN_ALLOW_THREADS + pid = wait4(pid, &status, options, &ru); + Py_END_ALLOW_THREADS + + return wait_helper(pid, WAIT_STATUS_INT(status), &ru); } #endif /* HAVE_WAIT4 */ @@ -4481,20 +4482,20 @@ static PyObject * posix_waitpid(PyObject *self, PyObject *args) { - pid_t pid; - int options; - WAIT_TYPE status; - WAIT_STATUS_INT(status) = 0; - - if (!PyArg_ParseTuple(args, _Py_PARSE_PID "i:waitpid", &pid, &options)) - return NULL; - Py_BEGIN_ALLOW_THREADS - pid = waitpid(pid, &status, options); - Py_END_ALLOW_THREADS - if (pid == -1) - return posix_error(); + pid_t pid; + int options; + WAIT_TYPE status; + WAIT_STATUS_INT(status) = 0; + + if (!PyArg_ParseTuple(args, _Py_PARSE_PID "i:waitpid", &pid, &options)) + return NULL; + Py_BEGIN_ALLOW_THREADS + pid = waitpid(pid, &status, options); + Py_END_ALLOW_THREADS + if (pid == -1) + return posix_error(); - return Py_BuildValue("Ni", PyLong_FromPid(pid), WAIT_STATUS_INT(status)); + return Py_BuildValue("Ni", PyLong_FromPid(pid), WAIT_STATUS_INT(status)); } #elif defined(HAVE_CWAIT) @@ -4507,19 +4508,19 @@ static PyObject * posix_waitpid(PyObject *self, PyObject *args) { - Py_intptr_t pid; - int status, options; + Py_intptr_t pid; + int status, options; - if (!PyArg_ParseTuple(args, _Py_PARSE_PID "i:waitpid", &pid, &options)) - return NULL; - Py_BEGIN_ALLOW_THREADS - pid = _cwait(&status, pid, options); - Py_END_ALLOW_THREADS - if (pid == -1) - return posix_error(); + if (!PyArg_ParseTuple(args, _Py_PARSE_PID "i:waitpid", &pid, &options)) + return NULL; + Py_BEGIN_ALLOW_THREADS + pid = _cwait(&status, pid, options); + Py_END_ALLOW_THREADS + if (pid == -1) + return posix_error(); - /* shift the status left a byte so this is more like the POSIX waitpid */ - return Py_BuildValue("Ni", PyLong_FromPid(pid), status << 8); + /* shift the status left a byte so this is more like the POSIX waitpid */ + return Py_BuildValue("Ni", PyLong_FromPid(pid), status << 8); } #endif /* HAVE_WAITPID || HAVE_CWAIT */ @@ -4531,17 +4532,17 @@ static PyObject * posix_wait(PyObject *self, PyObject *noargs) { - pid_t pid; - WAIT_TYPE status; - WAIT_STATUS_INT(status) = 0; - - Py_BEGIN_ALLOW_THREADS - pid = wait(&status); - Py_END_ALLOW_THREADS - if (pid == -1) - return posix_error(); + pid_t pid; + WAIT_TYPE status; + WAIT_STATUS_INT(status) = 0; + + Py_BEGIN_ALLOW_THREADS + pid = wait(&status); + Py_END_ALLOW_THREADS + if (pid == -1) + return posix_error(); - return Py_BuildValue("Ni", PyLong_FromPid(pid), WAIT_STATUS_INT(status)); + return Py_BuildValue("Ni", PyLong_FromPid(pid), WAIT_STATUS_INT(status)); } #endif @@ -4554,12 +4555,12 @@ posix_lstat(PyObject *self, PyObject *args) { #ifdef HAVE_LSTAT - return posix_do_stat(self, args, "O&:lstat", lstat, NULL, NULL); + return posix_do_stat(self, args, "O&:lstat", lstat, NULL, NULL); #else /* !HAVE_LSTAT */ #ifdef MS_WINDOWS - return posix_do_stat(self, args, "O&:lstat", STAT, "U:lstat", win32_wstat); + return posix_do_stat(self, args, "O&:lstat", STAT, "U:lstat", win32_wstat); #else - return posix_do_stat(self, args, "O&:lstat", STAT, NULL, NULL); + return posix_do_stat(self, args, "O&:lstat", STAT, NULL, NULL); #endif #endif /* !HAVE_LSTAT */ } @@ -4573,51 +4574,51 @@ static PyObject * posix_readlink(PyObject *self, PyObject *args) { - PyObject* v; - char buf[MAXPATHLEN]; - PyObject *opath; - char *path; - int n; - int arg_is_unicode = 0; - - if (!PyArg_ParseTuple(args, "O&:readlink", - PyUnicode_FSConverter, &opath)) - return NULL; - path = PyBytes_AsString(opath); - v = PySequence_GetItem(args, 0); - if (v == NULL) { - Py_DECREF(opath); - return NULL; - } - - if (PyUnicode_Check(v)) { - arg_is_unicode = 1; - } - Py_DECREF(v); - - Py_BEGIN_ALLOW_THREADS - n = readlink(path, buf, (int) sizeof buf); - Py_END_ALLOW_THREADS - if (n < 0) - return posix_error_with_allocated_filename(opath); - - Py_DECREF(opath); - v = PyBytes_FromStringAndSize(buf, n); - if (arg_is_unicode) { - PyObject *w; - - w = PyUnicode_FromEncodedObject(v, - Py_FileSystemDefaultEncoding, - "surrogateescape"); - if (w != NULL) { - Py_DECREF(v); - v = w; - } - else { - v = NULL; - } - } - return v; + PyObject* v; + char buf[MAXPATHLEN]; + PyObject *opath; + char *path; + int n; + int arg_is_unicode = 0; + + if (!PyArg_ParseTuple(args, "O&:readlink", + PyUnicode_FSConverter, &opath)) + return NULL; + path = PyBytes_AsString(opath); + v = PySequence_GetItem(args, 0); + if (v == NULL) { + Py_DECREF(opath); + return NULL; + } + + if (PyUnicode_Check(v)) { + arg_is_unicode = 1; + } + Py_DECREF(v); + + Py_BEGIN_ALLOW_THREADS + n = readlink(path, buf, (int) sizeof buf); + Py_END_ALLOW_THREADS + if (n < 0) + return posix_error_with_allocated_filename(opath); + + Py_DECREF(opath); + v = PyBytes_FromStringAndSize(buf, n); + if (arg_is_unicode) { + PyObject *w; + + w = PyUnicode_FromEncodedObject(v, + Py_FileSystemDefaultEncoding, + "surrogateescape"); + if (w != NULL) { + Py_DECREF(v); + v = w; + } + else { + v = NULL; + } + } + return v; } #endif /* HAVE_READLINK */ @@ -4630,7 +4631,7 @@ static PyObject * posix_symlink(PyObject *self, PyObject *args) { - return posix_2str(args, "O&O&:symlink", symlink); + return posix_2str(args, "O&O&:symlink", symlink); } #endif /* HAVE_SYMLINK */ @@ -4653,12 +4654,12 @@ posix_times(PyObject *self, PyObject *noargs) { /* Currently Only Uptime is Provided -- Others Later */ - return Py_BuildValue("ddddd", - (double)0 /* t.tms_utime / HZ */, - (double)0 /* t.tms_stime / HZ */, - (double)0 /* t.tms_cutime / HZ */, - (double)0 /* t.tms_cstime / HZ */, - (double)system_uptime() / 1000); + return Py_BuildValue("ddddd", + (double)0 /* t.tms_utime / HZ */, + (double)0 /* t.tms_stime / HZ */, + (double)0 /* t.tms_cutime / HZ */, + (double)0 /* t.tms_cstime / HZ */, + (double)system_uptime() / 1000); } #else /* not OS2 */ #define NEED_TICKS_PER_SECOND @@ -4666,46 +4667,46 @@ static PyObject * posix_times(PyObject *self, PyObject *noargs) { - struct tms t; - clock_t c; - errno = 0; - c = times(&t); - if (c == (clock_t) -1) - return posix_error(); - return Py_BuildValue("ddddd", - (double)t.tms_utime / ticks_per_second, - (double)t.tms_stime / ticks_per_second, - (double)t.tms_cutime / ticks_per_second, - (double)t.tms_cstime / ticks_per_second, - (double)c / ticks_per_second); + struct tms t; + clock_t c; + errno = 0; + c = times(&t); + if (c == (clock_t) -1) + return posix_error(); + return Py_BuildValue("ddddd", + (double)t.tms_utime / ticks_per_second, + (double)t.tms_stime / ticks_per_second, + (double)t.tms_cutime / ticks_per_second, + (double)t.tms_cstime / ticks_per_second, + (double)c / ticks_per_second); } #endif /* not OS2 */ #endif /* HAVE_TIMES */ #ifdef MS_WINDOWS -#define HAVE_TIMES /* so the method table will pick it up */ +#define HAVE_TIMES /* so the method table will pick it up */ static PyObject * posix_times(PyObject *self, PyObject *noargs) { - FILETIME create, exit, kernel, user; - HANDLE hProc; - hProc = GetCurrentProcess(); - GetProcessTimes(hProc, &create, &exit, &kernel, &user); - /* The fields of a FILETIME structure are the hi and lo part - of a 64-bit value expressed in 100 nanosecond units. - 1e7 is one second in such units; 1e-7 the inverse. - 429.4967296 is 2**32 / 1e7 or 2**32 * 1e-7. - */ - return Py_BuildValue( - "ddddd", - (double)(user.dwHighDateTime*429.4967296 + - user.dwLowDateTime*1e-7), - (double)(kernel.dwHighDateTime*429.4967296 + - kernel.dwLowDateTime*1e-7), - (double)0, - (double)0, - (double)0); + FILETIME create, exit, kernel, user; + HANDLE hProc; + hProc = GetCurrentProcess(); + GetProcessTimes(hProc, &create, &exit, &kernel, &user); + /* The fields of a FILETIME structure are the hi and lo part + of a 64-bit value expressed in 100 nanosecond units. + 1e7 is one second in such units; 1e-7 the inverse. + 429.4967296 is 2**32 / 1e7 or 2**32 * 1e-7. + */ + return Py_BuildValue( + "ddddd", + (double)(user.dwHighDateTime*429.4967296 + + user.dwLowDateTime*1e-7), + (double)(kernel.dwHighDateTime*429.4967296 + + kernel.dwLowDateTime*1e-7), + (double)0, + (double)0, + (double)0); } #endif /* MS_WINDOWS */ @@ -4724,14 +4725,14 @@ static PyObject * posix_getsid(PyObject *self, PyObject *args) { - pid_t pid; - int sid; - if (!PyArg_ParseTuple(args, _Py_PARSE_PID ":getsid", &pid)) - return NULL; - sid = getsid(pid); - if (sid < 0) - return posix_error(); - return PyLong_FromLong((long)sid); + pid_t pid; + int sid; + if (!PyArg_ParseTuple(args, _Py_PARSE_PID ":getsid", &pid)) + return NULL; + sid = getsid(pid); + if (sid < 0) + return posix_error(); + return PyLong_FromLong((long)sid); } #endif /* HAVE_GETSID */ @@ -4744,10 +4745,10 @@ static PyObject * posix_setsid(PyObject *self, PyObject *noargs) { - if (setsid() < 0) - return posix_error(); - Py_INCREF(Py_None); - return Py_None; + if (setsid() < 0) + return posix_error(); + Py_INCREF(Py_None); + return Py_None; } #endif /* HAVE_SETSID */ @@ -4759,14 +4760,14 @@ static PyObject * posix_setpgid(PyObject *self, PyObject *args) { - pid_t pid; - int pgrp; - if (!PyArg_ParseTuple(args, _Py_PARSE_PID "i:setpgid", &pid, &pgrp)) - return NULL; - if (setpgid(pid, pgrp) < 0) - return posix_error(); - Py_INCREF(Py_None); - return Py_None; + pid_t pid; + int pgrp; + if (!PyArg_ParseTuple(args, _Py_PARSE_PID "i:setpgid", &pid, &pgrp)) + return NULL; + if (setpgid(pid, pgrp) < 0) + return posix_error(); + Py_INCREF(Py_None); + return Py_None; } #endif /* HAVE_SETPGID */ @@ -4779,14 +4780,14 @@ static PyObject * posix_tcgetpgrp(PyObject *self, PyObject *args) { - int fd; - pid_t pgid; - if (!PyArg_ParseTuple(args, "i:tcgetpgrp", &fd)) - return NULL; - pgid = tcgetpgrp(fd); - if (pgid < 0) - return posix_error(); - return PyLong_FromPid(pgid); + int fd; + pid_t pgid; + if (!PyArg_ParseTuple(args, "i:tcgetpgrp", &fd)) + return NULL; + pgid = tcgetpgrp(fd); + if (pgid < 0) + return posix_error(); + return PyLong_FromPid(pgid); } #endif /* HAVE_TCGETPGRP */ @@ -4799,14 +4800,14 @@ static PyObject * posix_tcsetpgrp(PyObject *self, PyObject *args) { - int fd; - pid_t pgid; - if (!PyArg_ParseTuple(args, "i" _Py_PARSE_PID ":tcsetpgrp", &fd, &pgid)) - return NULL; - if (tcsetpgrp(fd, pgid) < 0) - return posix_error(); - Py_INCREF(Py_None); - return Py_None; + int fd; + pid_t pgid; + if (!PyArg_ParseTuple(args, "i" _Py_PARSE_PID ":tcsetpgrp", &fd, &pgid)) + return NULL; + if (tcsetpgrp(fd, pgid) < 0) + return posix_error(); + Py_INCREF(Py_None); + return Py_None; } #endif /* HAVE_TCSETPGRP */ @@ -4819,41 +4820,41 @@ static PyObject * posix_open(PyObject *self, PyObject *args) { - PyObject *ofile; - char *file; - int flag; - int mode = 0777; - int fd; + PyObject *ofile; + char *file; + int flag; + int mode = 0777; + int fd; #ifdef MS_WINDOWS - PyUnicodeObject *po; - if (PyArg_ParseTuple(args, "Ui|i:mkdir", &po, &flag, &mode)) { - Py_BEGIN_ALLOW_THREADS - /* PyUnicode_AS_UNICODE OK without thread - lock as it is a simple dereference. */ - fd = _wopen(PyUnicode_AS_UNICODE(po), flag, mode); - Py_END_ALLOW_THREADS - if (fd < 0) - return posix_error(); - return PyLong_FromLong((long)fd); - } - /* Drop the argument parsing error as narrow strings - are also valid. */ - PyErr_Clear(); -#endif - - if (!PyArg_ParseTuple(args, "O&i|i", - PyUnicode_FSConverter, &ofile, - &flag, &mode)) - return NULL; - file = PyBytes_AsString(ofile); - Py_BEGIN_ALLOW_THREADS - fd = open(file, flag, mode); - Py_END_ALLOW_THREADS - if (fd < 0) - return posix_error_with_allocated_filename(ofile); - Py_DECREF(ofile); - return PyLong_FromLong((long)fd); + PyUnicodeObject *po; + if (PyArg_ParseTuple(args, "Ui|i:mkdir", &po, &flag, &mode)) { + Py_BEGIN_ALLOW_THREADS + /* PyUnicode_AS_UNICODE OK without thread + lock as it is a simple dereference. */ + fd = _wopen(PyUnicode_AS_UNICODE(po), flag, mode); + Py_END_ALLOW_THREADS + if (fd < 0) + return posix_error(); + return PyLong_FromLong((long)fd); + } + /* Drop the argument parsing error as narrow strings + are also valid. */ + PyErr_Clear(); +#endif + + if (!PyArg_ParseTuple(args, "O&i|i", + PyUnicode_FSConverter, &ofile, + &flag, &mode)) + return NULL; + file = PyBytes_AsString(ofile); + Py_BEGIN_ALLOW_THREADS + fd = open(file, flag, mode); + Py_END_ALLOW_THREADS + if (fd < 0) + return posix_error_with_allocated_filename(ofile); + Py_DECREF(ofile); + return PyLong_FromLong((long)fd); } @@ -4864,37 +4865,37 @@ static PyObject * posix_close(PyObject *self, PyObject *args) { - int fd, res; - if (!PyArg_ParseTuple(args, "i:close", &fd)) - return NULL; - if (!_PyVerify_fd(fd)) - return posix_error(); - Py_BEGIN_ALLOW_THREADS - res = close(fd); - Py_END_ALLOW_THREADS - if (res < 0) - return posix_error(); - Py_INCREF(Py_None); - return Py_None; + int fd, res; + if (!PyArg_ParseTuple(args, "i:close", &fd)) + return NULL; + if (!_PyVerify_fd(fd)) + return posix_error(); + Py_BEGIN_ALLOW_THREADS + res = close(fd); + Py_END_ALLOW_THREADS + if (res < 0) + return posix_error(); + Py_INCREF(Py_None); + return Py_None; } -PyDoc_STRVAR(posix_closerange__doc__, +PyDoc_STRVAR(posix_closerange__doc__, "closerange(fd_low, fd_high)\n\n\ Closes all file descriptors in [fd_low, fd_high), ignoring errors."); static PyObject * posix_closerange(PyObject *self, PyObject *args) { - int fd_from, fd_to, i; - if (!PyArg_ParseTuple(args, "ii:closerange", &fd_from, &fd_to)) - return NULL; - Py_BEGIN_ALLOW_THREADS - for (i = fd_from; i < fd_to; i++) - if (_PyVerify_fd(i)) - close(i); - Py_END_ALLOW_THREADS - Py_RETURN_NONE; + int fd_from, fd_to, i; + if (!PyArg_ParseTuple(args, "ii:closerange", &fd_from, &fd_to)) + return NULL; + Py_BEGIN_ALLOW_THREADS + for (i = fd_from; i < fd_to; i++) + if (_PyVerify_fd(i)) + close(i); + Py_END_ALLOW_THREADS + Py_RETURN_NONE; } @@ -4905,17 +4906,17 @@ static PyObject * posix_dup(PyObject *self, PyObject *args) { - int fd; - if (!PyArg_ParseTuple(args, "i:dup", &fd)) - return NULL; - if (!_PyVerify_fd(fd)) - return posix_error(); - Py_BEGIN_ALLOW_THREADS - fd = dup(fd); - Py_END_ALLOW_THREADS - if (fd < 0) - return posix_error(); - return PyLong_FromLong((long)fd); + int fd; + if (!PyArg_ParseTuple(args, "i:dup", &fd)) + return NULL; + if (!_PyVerify_fd(fd)) + return posix_error(); + Py_BEGIN_ALLOW_THREADS + fd = dup(fd); + Py_END_ALLOW_THREADS + if (fd < 0) + return posix_error(); + return PyLong_FromLong((long)fd); } @@ -4926,18 +4927,18 @@ static PyObject * posix_dup2(PyObject *self, PyObject *args) { - int fd, fd2, res; - if (!PyArg_ParseTuple(args, "ii:dup2", &fd, &fd2)) - return NULL; - if (!_PyVerify_fd_dup2(fd, fd2)) - return posix_error(); - Py_BEGIN_ALLOW_THREADS - res = dup2(fd, fd2); - Py_END_ALLOW_THREADS - if (res < 0) - return posix_error(); - Py_INCREF(Py_None); - return Py_None; + int fd, fd2, res; + if (!PyArg_ParseTuple(args, "ii:dup2", &fd, &fd2)) + return NULL; + if (!_PyVerify_fd_dup2(fd, fd2)) + return posix_error(); + Py_BEGIN_ALLOW_THREADS + res = dup2(fd, fd2); + Py_END_ALLOW_THREADS + if (res < 0) + return posix_error(); + Py_INCREF(Py_None); + return Py_None; } @@ -4948,49 +4949,49 @@ static PyObject * posix_lseek(PyObject *self, PyObject *args) { - int fd, how; + int fd, how; #if defined(MS_WIN64) || defined(MS_WINDOWS) - PY_LONG_LONG pos, res; + PY_LONG_LONG pos, res; #else - off_t pos, res; + off_t pos, res; #endif - PyObject *posobj; - if (!PyArg_ParseTuple(args, "iOi:lseek", &fd, &posobj, &how)) - return NULL; + PyObject *posobj; + if (!PyArg_ParseTuple(args, "iOi:lseek", &fd, &posobj, &how)) + return NULL; #ifdef SEEK_SET - /* Turn 0, 1, 2 into SEEK_{SET,CUR,END} */ - switch (how) { - case 0: how = SEEK_SET; break; - case 1: how = SEEK_CUR; break; - case 2: how = SEEK_END; break; - } + /* Turn 0, 1, 2 into SEEK_{SET,CUR,END} */ + switch (how) { + case 0: how = SEEK_SET; break; + case 1: how = SEEK_CUR; break; + case 2: how = SEEK_END; break; + } #endif /* SEEK_END */ #if !defined(HAVE_LARGEFILE_SUPPORT) - pos = PyLong_AsLong(posobj); + pos = PyLong_AsLong(posobj); #else - pos = PyLong_Check(posobj) ? - PyLong_AsLongLong(posobj) : PyLong_AsLong(posobj); + pos = PyLong_Check(posobj) ? + PyLong_AsLongLong(posobj) : PyLong_AsLong(posobj); #endif - if (PyErr_Occurred()) - return NULL; + if (PyErr_Occurred()) + return NULL; - if (!_PyVerify_fd(fd)) - return posix_error(); - Py_BEGIN_ALLOW_THREADS + if (!_PyVerify_fd(fd)) + return posix_error(); + Py_BEGIN_ALLOW_THREADS #if defined(MS_WIN64) || defined(MS_WINDOWS) - res = _lseeki64(fd, pos, how); + res = _lseeki64(fd, pos, how); #else - res = lseek(fd, pos, how); + res = lseek(fd, pos, how); #endif - Py_END_ALLOW_THREADS - if (res < 0) - return posix_error(); + Py_END_ALLOW_THREADS + if (res < 0) + return posix_error(); #if !defined(HAVE_LARGEFILE_SUPPORT) - return PyLong_FromLong(res); + return PyLong_FromLong(res); #else - return PyLong_FromLongLong(res); + return PyLong_FromLongLong(res); #endif } @@ -5002,30 +5003,30 @@ static PyObject * posix_read(PyObject *self, PyObject *args) { - int fd, size; - Py_ssize_t n; - PyObject *buffer; - if (!PyArg_ParseTuple(args, "ii:read", &fd, &size)) - return NULL; - if (size < 0) { - errno = EINVAL; - return posix_error(); - } - buffer = PyBytes_FromStringAndSize((char *)NULL, size); - if (buffer == NULL) - return NULL; - if (!_PyVerify_fd(fd)) - return posix_error(); - Py_BEGIN_ALLOW_THREADS - n = read(fd, PyBytes_AS_STRING(buffer), size); - Py_END_ALLOW_THREADS - if (n < 0) { - Py_DECREF(buffer); - return posix_error(); - } - if (n != size) - _PyBytes_Resize(&buffer, n); - return buffer; + int fd, size; + Py_ssize_t n; + PyObject *buffer; + if (!PyArg_ParseTuple(args, "ii:read", &fd, &size)) + return NULL; + if (size < 0) { + errno = EINVAL; + return posix_error(); + } + buffer = PyBytes_FromStringAndSize((char *)NULL, size); + if (buffer == NULL) + return NULL; + if (!_PyVerify_fd(fd)) + return posix_error(); + Py_BEGIN_ALLOW_THREADS + n = read(fd, PyBytes_AS_STRING(buffer), size); + Py_END_ALLOW_THREADS + if (n < 0) { + Py_DECREF(buffer); + return posix_error(); + } + if (n != size) + _PyBytes_Resize(&buffer, n); + return buffer; } @@ -5036,21 +5037,21 @@ static PyObject * posix_write(PyObject *self, PyObject *args) { - Py_buffer pbuf; - int fd; - Py_ssize_t size; - - if (!PyArg_ParseTuple(args, "iy*:write", &fd, &pbuf)) - return NULL; - if (!_PyVerify_fd(fd)) - return posix_error(); - Py_BEGIN_ALLOW_THREADS - size = write(fd, pbuf.buf, (size_t)pbuf.len); - Py_END_ALLOW_THREADS - PyBuffer_Release(&pbuf); - if (size < 0) - return posix_error(); - return PyLong_FromSsize_t(size); + Py_buffer pbuf; + int fd; + Py_ssize_t size; + + if (!PyArg_ParseTuple(args, "iy*:write", &fd, &pbuf)) + return NULL; + if (!_PyVerify_fd(fd)) + return posix_error(); + Py_BEGIN_ALLOW_THREADS + size = write(fd, pbuf.buf, (size_t)pbuf.len); + Py_END_ALLOW_THREADS + PyBuffer_Release(&pbuf); + if (size < 0) + return posix_error(); + return PyLong_FromSsize_t(size); } @@ -5061,29 +5062,29 @@ static PyObject * posix_fstat(PyObject *self, PyObject *args) { - int fd; - STRUCT_STAT st; - int res; - if (!PyArg_ParseTuple(args, "i:fstat", &fd)) - return NULL; + int fd; + STRUCT_STAT st; + int res; + if (!PyArg_ParseTuple(args, "i:fstat", &fd)) + return NULL; #ifdef __VMS - /* on OpenVMS we must ensure that all bytes are written to the file */ - fsync(fd); + /* on OpenVMS we must ensure that all bytes are written to the file */ + fsync(fd); #endif - if (!_PyVerify_fd(fd)) - return posix_error(); - Py_BEGIN_ALLOW_THREADS - res = FSTAT(fd, &st); - Py_END_ALLOW_THREADS - if (res != 0) { + if (!_PyVerify_fd(fd)) + return posix_error(); + Py_BEGIN_ALLOW_THREADS + res = FSTAT(fd, &st); + Py_END_ALLOW_THREADS + if (res != 0) { #ifdef MS_WINDOWS - return win32_error("fstat", NULL); + return win32_error("fstat", NULL); #else - return posix_error(); + return posix_error(); #endif - } + } - return _pystat_fromstructstat(&st); + return _pystat_fromstructstat(&st); } PyDoc_STRVAR(posix_isatty__doc__, @@ -5094,12 +5095,12 @@ static PyObject * posix_isatty(PyObject *self, PyObject *args) { - int fd; - if (!PyArg_ParseTuple(args, "i:isatty", &fd)) - return NULL; - if (!_PyVerify_fd(fd)) - return PyBool_FromLong(0); - return PyBool_FromLong(isatty(fd)); + int fd; + if (!PyArg_ParseTuple(args, "i:isatty", &fd)) + return NULL; + if (!_PyVerify_fd(fd)) + return PyBool_FromLong(0); + return PyBool_FromLong(isatty(fd)); } #ifdef HAVE_PIPE @@ -5114,35 +5115,35 @@ HFILE read, write; APIRET rc; - Py_BEGIN_ALLOW_THREADS + Py_BEGIN_ALLOW_THREADS rc = DosCreatePipe( &read, &write, 4096); - Py_END_ALLOW_THREADS + Py_END_ALLOW_THREADS if (rc != NO_ERROR) return os2_error(rc); return Py_BuildValue("(ii)", read, write); #else #if !defined(MS_WINDOWS) - int fds[2]; - int res; - Py_BEGIN_ALLOW_THREADS - res = pipe(fds); - Py_END_ALLOW_THREADS - if (res != 0) - return posix_error(); - return Py_BuildValue("(ii)", fds[0], fds[1]); + int fds[2]; + int res; + Py_BEGIN_ALLOW_THREADS + res = pipe(fds); + Py_END_ALLOW_THREADS + if (res != 0) + return posix_error(); + return Py_BuildValue("(ii)", fds[0], fds[1]); #else /* MS_WINDOWS */ - HANDLE read, write; - int read_fd, write_fd; - BOOL ok; - Py_BEGIN_ALLOW_THREADS - ok = CreatePipe(&read, &write, NULL, 0); - Py_END_ALLOW_THREADS - if (!ok) - return win32_error("CreatePipe", NULL); - read_fd = _open_osfhandle((Py_intptr_t)read, 0); - write_fd = _open_osfhandle((Py_intptr_t)write, 1); - return Py_BuildValue("(ii)", read_fd, write_fd); + HANDLE read, write; + int read_fd, write_fd; + BOOL ok; + Py_BEGIN_ALLOW_THREADS + ok = CreatePipe(&read, &write, NULL, 0); + Py_END_ALLOW_THREADS + if (!ok) + return win32_error("CreatePipe", NULL); + read_fd = _open_osfhandle((Py_intptr_t)read, 0); + write_fd = _open_osfhandle((Py_intptr_t)write, 1); + return Py_BuildValue("(ii)", read_fd, write_fd); #endif /* MS_WINDOWS */ #endif } @@ -5157,18 +5158,18 @@ static PyObject * posix_mkfifo(PyObject *self, PyObject *args) { - char *filename; - int mode = 0666; - int res; - if (!PyArg_ParseTuple(args, "s|i:mkfifo", &filename, &mode)) - return NULL; - Py_BEGIN_ALLOW_THREADS - res = mkfifo(filename, mode); - Py_END_ALLOW_THREADS - if (res < 0) - return posix_error(); - Py_INCREF(Py_None); - return Py_None; + char *filename; + int mode = 0666; + int res; + if (!PyArg_ParseTuple(args, "s|i:mkfifo", &filename, &mode)) + return NULL; + Py_BEGIN_ALLOW_THREADS + res = mkfifo(filename, mode); + Py_END_ALLOW_THREADS + if (res < 0) + return posix_error(); + Py_INCREF(Py_None); + return Py_None; } #endif @@ -5187,19 +5188,19 @@ static PyObject * posix_mknod(PyObject *self, PyObject *args) { - char *filename; - int mode = 0600; - int device = 0; - int res; - if (!PyArg_ParseTuple(args, "s|ii:mknod", &filename, &mode, &device)) - return NULL; - Py_BEGIN_ALLOW_THREADS - res = mknod(filename, mode, device); - Py_END_ALLOW_THREADS - if (res < 0) - return posix_error(); - Py_INCREF(Py_None); - return Py_None; + char *filename; + int mode = 0600; + int device = 0; + int res; + if (!PyArg_ParseTuple(args, "s|ii:mknod", &filename, &mode, &device)) + return NULL; + Py_BEGIN_ALLOW_THREADS + res = mknod(filename, mode, device); + Py_END_ALLOW_THREADS + if (res < 0) + return posix_error(); + Py_INCREF(Py_None); + return Py_None; } #endif @@ -5211,10 +5212,10 @@ static PyObject * posix_major(PyObject *self, PyObject *args) { - int device; - if (!PyArg_ParseTuple(args, "i:major", &device)) - return NULL; - return PyLong_FromLong((long)major(device)); + int device; + if (!PyArg_ParseTuple(args, "i:major", &device)) + return NULL; + return PyLong_FromLong((long)major(device)); } PyDoc_STRVAR(posix_minor__doc__, @@ -5224,10 +5225,10 @@ static PyObject * posix_minor(PyObject *self, PyObject *args) { - int device; - if (!PyArg_ParseTuple(args, "i:minor", &device)) - return NULL; - return PyLong_FromLong((long)minor(device)); + int device; + if (!PyArg_ParseTuple(args, "i:minor", &device)) + return NULL; + return PyLong_FromLong((long)minor(device)); } PyDoc_STRVAR(posix_makedev__doc__, @@ -5237,10 +5238,10 @@ static PyObject * posix_makedev(PyObject *self, PyObject *args) { - int major, minor; - if (!PyArg_ParseTuple(args, "ii:makedev", &major, &minor)) - return NULL; - return PyLong_FromLong((long)makedev(major, minor)); + int major, minor; + if (!PyArg_ParseTuple(args, "ii:makedev", &major, &minor)) + return NULL; + return PyLong_FromLong((long)makedev(major, minor)); } #endif /* device macros */ @@ -5253,30 +5254,30 @@ static PyObject * posix_ftruncate(PyObject *self, PyObject *args) { - int fd; - off_t length; - int res; - PyObject *lenobj; + int fd; + off_t length; + int res; + PyObject *lenobj; - if (!PyArg_ParseTuple(args, "iO:ftruncate", &fd, &lenobj)) - return NULL; + if (!PyArg_ParseTuple(args, "iO:ftruncate", &fd, &lenobj)) + return NULL; #if !defined(HAVE_LARGEFILE_SUPPORT) - length = PyLong_AsLong(lenobj); + length = PyLong_AsLong(lenobj); #else - length = PyLong_Check(lenobj) ? - PyLong_AsLongLong(lenobj) : PyLong_AsLong(lenobj); + length = PyLong_Check(lenobj) ? + PyLong_AsLongLong(lenobj) : PyLong_AsLong(lenobj); #endif - if (PyErr_Occurred()) - return NULL; + if (PyErr_Occurred()) + return NULL; - Py_BEGIN_ALLOW_THREADS - res = ftruncate(fd, length); - Py_END_ALLOW_THREADS - if (res < 0) - return posix_error(); - Py_INCREF(Py_None); - return Py_None; + Py_BEGIN_ALLOW_THREADS + res = ftruncate(fd, length); + Py_END_ALLOW_THREADS + if (res < 0) + return posix_error(); + Py_INCREF(Py_None); + return Py_None; } #endif @@ -5293,29 +5294,29 @@ posix_putenv(PyObject *self, PyObject *args) { #ifdef MS_WINDOWS - wchar_t *s1, *s2; - wchar_t *newenv; + wchar_t *s1, *s2; + wchar_t *newenv; #else - PyObject *os1, *os2; - char *s1, *s2; - char *newenv; + PyObject *os1, *os2; + char *s1, *s2; + char *newenv; #endif - PyObject *newstr; - size_t len; + PyObject *newstr; + size_t len; #ifdef MS_WINDOWS - if (!PyArg_ParseTuple(args, - "uu:putenv", - &s1, &s2)) - return NULL; -#else - if (!PyArg_ParseTuple(args, - "O&O&:putenv", - PyUnicode_FSConverter, &os1, - PyUnicode_FSConverter, &os2)) - return NULL; - s1 = PyBytes_AsString(os1); - s2 = PyBytes_AsString(os2); + if (!PyArg_ParseTuple(args, + "uu:putenv", + &s1, &s2)) + return NULL; +#else + if (!PyArg_ParseTuple(args, + "O&O&:putenv", + PyUnicode_FSConverter, &os1, + PyUnicode_FSConverter, &os2)) + return NULL; + s1 = PyBytes_AsString(os1); + s2 = PyBytes_AsString(os2); #endif #if defined(PYOS_OS2) @@ -5334,59 +5335,59 @@ return os2_error(rc); } else { #endif - /* XXX This can leak memory -- not easy to fix :-( */ - /* len includes space for a trailing \0; the size arg to - PyBytes_FromStringAndSize does not count that */ + /* XXX This can leak memory -- not easy to fix :-( */ + /* len includes space for a trailing \0; the size arg to + PyBytes_FromStringAndSize does not count that */ #ifdef MS_WINDOWS - len = wcslen(s1) + wcslen(s2) + 2; - newstr = PyUnicode_FromUnicode(NULL, (int)len - 1); + len = wcslen(s1) + wcslen(s2) + 2; + newstr = PyUnicode_FromUnicode(NULL, (int)len - 1); #else - len = strlen(s1) + strlen(s2) + 2; - newstr = PyBytes_FromStringAndSize(NULL, (int)len - 1); + len = strlen(s1) + strlen(s2) + 2; + newstr = PyBytes_FromStringAndSize(NULL, (int)len - 1); #endif - if (newstr == NULL) - return PyErr_NoMemory(); + if (newstr == NULL) + return PyErr_NoMemory(); #ifdef MS_WINDOWS - newenv = PyUnicode_AsUnicode(newstr); - _snwprintf(newenv, len, L"%s=%s", s1, s2); - if (_wputenv(newenv)) { - Py_DECREF(newstr); - posix_error(); - return NULL; - } + newenv = PyUnicode_AsUnicode(newstr); + _snwprintf(newenv, len, L"%s=%s", s1, s2); + if (_wputenv(newenv)) { + Py_DECREF(newstr); + posix_error(); + return NULL; + } #else - newenv = PyBytes_AS_STRING(newstr); - PyOS_snprintf(newenv, len, "%s=%s", s1, s2); - if (putenv(newenv)) { - Py_DECREF(newstr); - Py_DECREF(os1); - Py_DECREF(os2); - posix_error(); - return NULL; - } + newenv = PyBytes_AS_STRING(newstr); + PyOS_snprintf(newenv, len, "%s=%s", s1, s2); + if (putenv(newenv)) { + Py_DECREF(newstr); + Py_DECREF(os1); + Py_DECREF(os2); + posix_error(); + return NULL; + } #endif - /* Install the first arg and newstr in posix_putenv_garbage; - * this will cause previous value to be collected. This has to - * happen after the real putenv() call because the old value - * was still accessible until then. */ - if (PyDict_SetItem(posix_putenv_garbage, - PyTuple_GET_ITEM(args, 0), newstr)) { - /* really not much we can do; just leak */ - PyErr_Clear(); - } - else { - Py_DECREF(newstr); - } + /* Install the first arg and newstr in posix_putenv_garbage; + * this will cause previous value to be collected. This has to + * happen after the real putenv() call because the old value + * was still accessible until then. */ + if (PyDict_SetItem(posix_putenv_garbage, + PyTuple_GET_ITEM(args, 0), newstr)) { + /* really not much we can do; just leak */ + PyErr_Clear(); + } + else { + Py_DECREF(newstr); + } #if defined(PYOS_OS2) } #endif #ifndef MS_WINDOWS - Py_DECREF(os1); - Py_DECREF(os2); + Py_DECREF(os1); + Py_DECREF(os2); #endif - Py_INCREF(Py_None); - return Py_None; + Py_INCREF(Py_None); + return Py_None; } #endif /* putenv */ @@ -5398,26 +5399,26 @@ static PyObject * posix_unsetenv(PyObject *self, PyObject *args) { - char *s1; + char *s1; - if (!PyArg_ParseTuple(args, "s:unsetenv", &s1)) - return NULL; + if (!PyArg_ParseTuple(args, "s:unsetenv", &s1)) + return NULL; - unsetenv(s1); + unsetenv(s1); - /* Remove the key from posix_putenv_garbage; - * this will cause it to be collected. This has to - * happen after the real unsetenv() call because the - * old value was still accessible until then. - */ - if (PyDict_DelItem(posix_putenv_garbage, - PyTuple_GET_ITEM(args, 0))) { - /* really not much we can do; just leak */ - PyErr_Clear(); - } + /* Remove the key from posix_putenv_garbage; + * this will cause it to be collected. This has to + * happen after the real unsetenv() call because the + * old value was still accessible until then. + */ + if (PyDict_DelItem(posix_putenv_garbage, + PyTuple_GET_ITEM(args, 0))) { + /* really not much we can do; just leak */ + PyErr_Clear(); + } - Py_INCREF(Py_None); - return Py_None; + Py_INCREF(Py_None); + return Py_None; } #endif /* unsetenv */ @@ -5428,17 +5429,17 @@ static PyObject * posix_strerror(PyObject *self, PyObject *args) { - int code; - char *message; - if (!PyArg_ParseTuple(args, "i:strerror", &code)) - return NULL; - message = strerror(code); - if (message == NULL) { - PyErr_SetString(PyExc_ValueError, - "strerror() argument out of range"); - return NULL; - } - return PyUnicode_FromString(message); + int code; + char *message; + if (!PyArg_ParseTuple(args, "i:strerror", &code)) + return NULL; + message = strerror(code); + if (message == NULL) { + PyErr_SetString(PyExc_ValueError, + "strerror() argument out of range"); + return NULL; + } + return PyUnicode_FromString(message); } @@ -5452,13 +5453,13 @@ static PyObject * posix_WCOREDUMP(PyObject *self, PyObject *args) { - WAIT_TYPE status; - WAIT_STATUS_INT(status) = 0; + WAIT_TYPE status; + WAIT_STATUS_INT(status) = 0; - if (!PyArg_ParseTuple(args, "i:WCOREDUMP", &WAIT_STATUS_INT(status))) - return NULL; + if (!PyArg_ParseTuple(args, "i:WCOREDUMP", &WAIT_STATUS_INT(status))) + return NULL; - return PyBool_FromLong(WCOREDUMP(status)); + return PyBool_FromLong(WCOREDUMP(status)); } #endif /* WCOREDUMP */ @@ -5471,13 +5472,13 @@ static PyObject * posix_WIFCONTINUED(PyObject *self, PyObject *args) { - WAIT_TYPE status; - WAIT_STATUS_INT(status) = 0; + WAIT_TYPE status; + WAIT_STATUS_INT(status) = 0; - if (!PyArg_ParseTuple(args, "i:WCONTINUED", &WAIT_STATUS_INT(status))) - return NULL; + if (!PyArg_ParseTuple(args, "i:WCONTINUED", &WAIT_STATUS_INT(status))) + return NULL; - return PyBool_FromLong(WIFCONTINUED(status)); + return PyBool_FromLong(WIFCONTINUED(status)); } #endif /* WIFCONTINUED */ @@ -5489,13 +5490,13 @@ static PyObject * posix_WIFSTOPPED(PyObject *self, PyObject *args) { - WAIT_TYPE status; - WAIT_STATUS_INT(status) = 0; + WAIT_TYPE status; + WAIT_STATUS_INT(status) = 0; - if (!PyArg_ParseTuple(args, "i:WIFSTOPPED", &WAIT_STATUS_INT(status))) - return NULL; + if (!PyArg_ParseTuple(args, "i:WIFSTOPPED", &WAIT_STATUS_INT(status))) + return NULL; - return PyBool_FromLong(WIFSTOPPED(status)); + return PyBool_FromLong(WIFSTOPPED(status)); } #endif /* WIFSTOPPED */ @@ -5507,13 +5508,13 @@ static PyObject * posix_WIFSIGNALED(PyObject *self, PyObject *args) { - WAIT_TYPE status; - WAIT_STATUS_INT(status) = 0; + WAIT_TYPE status; + WAIT_STATUS_INT(status) = 0; - if (!PyArg_ParseTuple(args, "i:WIFSIGNALED", &WAIT_STATUS_INT(status))) - return NULL; + if (!PyArg_ParseTuple(args, "i:WIFSIGNALED", &WAIT_STATUS_INT(status))) + return NULL; - return PyBool_FromLong(WIFSIGNALED(status)); + return PyBool_FromLong(WIFSIGNALED(status)); } #endif /* WIFSIGNALED */ @@ -5526,13 +5527,13 @@ static PyObject * posix_WIFEXITED(PyObject *self, PyObject *args) { - WAIT_TYPE status; - WAIT_STATUS_INT(status) = 0; + WAIT_TYPE status; + WAIT_STATUS_INT(status) = 0; - if (!PyArg_ParseTuple(args, "i:WIFEXITED", &WAIT_STATUS_INT(status))) - return NULL; + if (!PyArg_ParseTuple(args, "i:WIFEXITED", &WAIT_STATUS_INT(status))) + return NULL; - return PyBool_FromLong(WIFEXITED(status)); + return PyBool_FromLong(WIFEXITED(status)); } #endif /* WIFEXITED */ @@ -5544,13 +5545,13 @@ static PyObject * posix_WEXITSTATUS(PyObject *self, PyObject *args) { - WAIT_TYPE status; - WAIT_STATUS_INT(status) = 0; + WAIT_TYPE status; + WAIT_STATUS_INT(status) = 0; - if (!PyArg_ParseTuple(args, "i:WEXITSTATUS", &WAIT_STATUS_INT(status))) - return NULL; + if (!PyArg_ParseTuple(args, "i:WEXITSTATUS", &WAIT_STATUS_INT(status))) + return NULL; - return Py_BuildValue("i", WEXITSTATUS(status)); + return Py_BuildValue("i", WEXITSTATUS(status)); } #endif /* WEXITSTATUS */ @@ -5563,13 +5564,13 @@ static PyObject * posix_WTERMSIG(PyObject *self, PyObject *args) { - WAIT_TYPE status; - WAIT_STATUS_INT(status) = 0; + WAIT_TYPE status; + WAIT_STATUS_INT(status) = 0; - if (!PyArg_ParseTuple(args, "i:WTERMSIG", &WAIT_STATUS_INT(status))) - return NULL; + if (!PyArg_ParseTuple(args, "i:WTERMSIG", &WAIT_STATUS_INT(status))) + return NULL; - return Py_BuildValue("i", WTERMSIG(status)); + return Py_BuildValue("i", WTERMSIG(status)); } #endif /* WTERMSIG */ @@ -5582,13 +5583,13 @@ static PyObject * posix_WSTOPSIG(PyObject *self, PyObject *args) { - WAIT_TYPE status; - WAIT_STATUS_INT(status) = 0; + WAIT_TYPE status; + WAIT_STATUS_INT(status) = 0; - if (!PyArg_ParseTuple(args, "i:WSTOPSIG", &WAIT_STATUS_INT(status))) - return NULL; + if (!PyArg_ParseTuple(args, "i:WSTOPSIG", &WAIT_STATUS_INT(status))) + return NULL; - return Py_BuildValue("i", WSTOPSIG(status)); + return Py_BuildValue("i", WSTOPSIG(status)); } #endif /* WSTOPSIG */ @@ -5605,41 +5606,41 @@ static PyObject* _pystatvfs_fromstructstatvfs(struct statvfs st) { - PyObject *v = PyStructSequence_New(&StatVFSResultType); - if (v == NULL) - return NULL; + PyObject *v = PyStructSequence_New(&StatVFSResultType); + if (v == NULL) + return NULL; #if !defined(HAVE_LARGEFILE_SUPPORT) - PyStructSequence_SET_ITEM(v, 0, PyLong_FromLong((long) st.f_bsize)); - PyStructSequence_SET_ITEM(v, 1, PyLong_FromLong((long) st.f_frsize)); - PyStructSequence_SET_ITEM(v, 2, PyLong_FromLong((long) st.f_blocks)); - PyStructSequence_SET_ITEM(v, 3, PyLong_FromLong((long) st.f_bfree)); - PyStructSequence_SET_ITEM(v, 4, PyLong_FromLong((long) st.f_bavail)); - PyStructSequence_SET_ITEM(v, 5, PyLong_FromLong((long) st.f_files)); - PyStructSequence_SET_ITEM(v, 6, PyLong_FromLong((long) st.f_ffree)); - PyStructSequence_SET_ITEM(v, 7, PyLong_FromLong((long) st.f_favail)); - PyStructSequence_SET_ITEM(v, 8, PyLong_FromLong((long) st.f_flag)); - PyStructSequence_SET_ITEM(v, 9, PyLong_FromLong((long) st.f_namemax)); -#else - PyStructSequence_SET_ITEM(v, 0, PyLong_FromLong((long) st.f_bsize)); - PyStructSequence_SET_ITEM(v, 1, PyLong_FromLong((long) st.f_frsize)); - PyStructSequence_SET_ITEM(v, 2, - PyLong_FromLongLong((PY_LONG_LONG) st.f_blocks)); - PyStructSequence_SET_ITEM(v, 3, - PyLong_FromLongLong((PY_LONG_LONG) st.f_bfree)); - PyStructSequence_SET_ITEM(v, 4, - PyLong_FromLongLong((PY_LONG_LONG) st.f_bavail)); - PyStructSequence_SET_ITEM(v, 5, - PyLong_FromLongLong((PY_LONG_LONG) st.f_files)); - PyStructSequence_SET_ITEM(v, 6, - PyLong_FromLongLong((PY_LONG_LONG) st.f_ffree)); - PyStructSequence_SET_ITEM(v, 7, - PyLong_FromLongLong((PY_LONG_LONG) st.f_favail)); - PyStructSequence_SET_ITEM(v, 8, PyLong_FromLong((long) st.f_flag)); - PyStructSequence_SET_ITEM(v, 9, PyLong_FromLong((long) st.f_namemax)); + PyStructSequence_SET_ITEM(v, 0, PyLong_FromLong((long) st.f_bsize)); + PyStructSequence_SET_ITEM(v, 1, PyLong_FromLong((long) st.f_frsize)); + PyStructSequence_SET_ITEM(v, 2, PyLong_FromLong((long) st.f_blocks)); + PyStructSequence_SET_ITEM(v, 3, PyLong_FromLong((long) st.f_bfree)); + PyStructSequence_SET_ITEM(v, 4, PyLong_FromLong((long) st.f_bavail)); + PyStructSequence_SET_ITEM(v, 5, PyLong_FromLong((long) st.f_files)); + PyStructSequence_SET_ITEM(v, 6, PyLong_FromLong((long) st.f_ffree)); + PyStructSequence_SET_ITEM(v, 7, PyLong_FromLong((long) st.f_favail)); + PyStructSequence_SET_ITEM(v, 8, PyLong_FromLong((long) st.f_flag)); + PyStructSequence_SET_ITEM(v, 9, PyLong_FromLong((long) st.f_namemax)); +#else + PyStructSequence_SET_ITEM(v, 0, PyLong_FromLong((long) st.f_bsize)); + PyStructSequence_SET_ITEM(v, 1, PyLong_FromLong((long) st.f_frsize)); + PyStructSequence_SET_ITEM(v, 2, + PyLong_FromLongLong((PY_LONG_LONG) st.f_blocks)); + PyStructSequence_SET_ITEM(v, 3, + PyLong_FromLongLong((PY_LONG_LONG) st.f_bfree)); + PyStructSequence_SET_ITEM(v, 4, + PyLong_FromLongLong((PY_LONG_LONG) st.f_bavail)); + PyStructSequence_SET_ITEM(v, 5, + PyLong_FromLongLong((PY_LONG_LONG) st.f_files)); + PyStructSequence_SET_ITEM(v, 6, + PyLong_FromLongLong((PY_LONG_LONG) st.f_ffree)); + PyStructSequence_SET_ITEM(v, 7, + PyLong_FromLongLong((PY_LONG_LONG) st.f_favail)); + PyStructSequence_SET_ITEM(v, 8, PyLong_FromLong((long) st.f_flag)); + PyStructSequence_SET_ITEM(v, 9, PyLong_FromLong((long) st.f_namemax)); #endif - return v; + return v; } PyDoc_STRVAR(posix_fstatvfs__doc__, @@ -5649,18 +5650,18 @@ static PyObject * posix_fstatvfs(PyObject *self, PyObject *args) { - int fd, res; - struct statvfs st; + int fd, res; + struct statvfs st; - if (!PyArg_ParseTuple(args, "i:fstatvfs", &fd)) - return NULL; - Py_BEGIN_ALLOW_THREADS - res = fstatvfs(fd, &st); - Py_END_ALLOW_THREADS - if (res != 0) - return posix_error(); + if (!PyArg_ParseTuple(args, "i:fstatvfs", &fd)) + return NULL; + Py_BEGIN_ALLOW_THREADS + res = fstatvfs(fd, &st); + Py_END_ALLOW_THREADS + if (res != 0) + return posix_error(); - return _pystatvfs_fromstructstatvfs(st); + return _pystatvfs_fromstructstatvfs(st); } #endif /* HAVE_FSTATVFS && HAVE_SYS_STATVFS_H */ @@ -5675,18 +5676,18 @@ static PyObject * posix_statvfs(PyObject *self, PyObject *args) { - char *path; - int res; - struct statvfs st; - if (!PyArg_ParseTuple(args, "s:statvfs", &path)) - return NULL; - Py_BEGIN_ALLOW_THREADS - res = statvfs(path, &st); - Py_END_ALLOW_THREADS - if (res != 0) - return posix_error_with_filename(path); + char *path; + int res; + struct statvfs st; + if (!PyArg_ParseTuple(args, "s:statvfs", &path)) + return NULL; + Py_BEGIN_ALLOW_THREADS + res = statvfs(path, &st); + Py_END_ALLOW_THREADS + if (res != 0) + return posix_error_with_filename(path); - return _pystatvfs_fromstructstatvfs(st); + return _pystatvfs_fromstructstatvfs(st); } #endif /* HAVE_STATVFS */ @@ -5711,38 +5712,38 @@ size_t tablesize) { if (PyLong_Check(arg)) { - *valuep = PyLong_AS_LONG(arg); - return 1; + *valuep = PyLong_AS_LONG(arg); + return 1; } else { - /* look up the value in the table using a binary search */ - size_t lo = 0; - size_t mid; - size_t hi = tablesize; - int cmp; - const char *confname; - if (!PyUnicode_Check(arg)) { - PyErr_SetString(PyExc_TypeError, - "configuration names must be strings or integers"); - return 0; - } - confname = _PyUnicode_AsString(arg); - if (confname == NULL) - return 0; - while (lo < hi) { - mid = (lo + hi) / 2; - cmp = strcmp(confname, table[mid].name); - if (cmp < 0) - hi = mid; - else if (cmp > 0) - lo = mid + 1; - else { - *valuep = table[mid].value; - return 1; - } - } - PyErr_SetString(PyExc_ValueError, "unrecognized configuration name"); + /* look up the value in the table using a binary search */ + size_t lo = 0; + size_t mid; + size_t hi = tablesize; + int cmp; + const char *confname; + if (!PyUnicode_Check(arg)) { + PyErr_SetString(PyExc_TypeError, + "configuration names must be strings or integers"); + return 0; + } + confname = _PyUnicode_AsString(arg); + if (confname == NULL) return 0; + while (lo < hi) { + mid = (lo + hi) / 2; + cmp = strcmp(confname, table[mid].name); + if (cmp < 0) + hi = mid; + else if (cmp > 0) + lo = mid + 1; + else { + *valuep = table[mid].value; + return 1; + } + } + PyErr_SetString(PyExc_ValueError, "unrecognized configuration name"); + return 0; } } @@ -5750,55 +5751,55 @@ #if defined(HAVE_FPATHCONF) || defined(HAVE_PATHCONF) static struct constdef posix_constants_pathconf[] = { #ifdef _PC_ABI_AIO_XFER_MAX - {"PC_ABI_AIO_XFER_MAX", _PC_ABI_AIO_XFER_MAX}, + {"PC_ABI_AIO_XFER_MAX", _PC_ABI_AIO_XFER_MAX}, #endif #ifdef _PC_ABI_ASYNC_IO - {"PC_ABI_ASYNC_IO", _PC_ABI_ASYNC_IO}, + {"PC_ABI_ASYNC_IO", _PC_ABI_ASYNC_IO}, #endif #ifdef _PC_ASYNC_IO - {"PC_ASYNC_IO", _PC_ASYNC_IO}, + {"PC_ASYNC_IO", _PC_ASYNC_IO}, #endif #ifdef _PC_CHOWN_RESTRICTED - {"PC_CHOWN_RESTRICTED", _PC_CHOWN_RESTRICTED}, + {"PC_CHOWN_RESTRICTED", _PC_CHOWN_RESTRICTED}, #endif #ifdef _PC_FILESIZEBITS - {"PC_FILESIZEBITS", _PC_FILESIZEBITS}, + {"PC_FILESIZEBITS", _PC_FILESIZEBITS}, #endif #ifdef _PC_LAST - {"PC_LAST", _PC_LAST}, + {"PC_LAST", _PC_LAST}, #endif #ifdef _PC_LINK_MAX - {"PC_LINK_MAX", _PC_LINK_MAX}, + {"PC_LINK_MAX", _PC_LINK_MAX}, #endif #ifdef _PC_MAX_CANON - {"PC_MAX_CANON", _PC_MAX_CANON}, + {"PC_MAX_CANON", _PC_MAX_CANON}, #endif #ifdef _PC_MAX_INPUT - {"PC_MAX_INPUT", _PC_MAX_INPUT}, + {"PC_MAX_INPUT", _PC_MAX_INPUT}, #endif #ifdef _PC_NAME_MAX - {"PC_NAME_MAX", _PC_NAME_MAX}, + {"PC_NAME_MAX", _PC_NAME_MAX}, #endif #ifdef _PC_NO_TRUNC - {"PC_NO_TRUNC", _PC_NO_TRUNC}, + {"PC_NO_TRUNC", _PC_NO_TRUNC}, #endif #ifdef _PC_PATH_MAX - {"PC_PATH_MAX", _PC_PATH_MAX}, + {"PC_PATH_MAX", _PC_PATH_MAX}, #endif #ifdef _PC_PIPE_BUF - {"PC_PIPE_BUF", _PC_PIPE_BUF}, + {"PC_PIPE_BUF", _PC_PIPE_BUF}, #endif #ifdef _PC_PRIO_IO - {"PC_PRIO_IO", _PC_PRIO_IO}, + {"PC_PRIO_IO", _PC_PRIO_IO}, #endif #ifdef _PC_SOCK_MAXBUF - {"PC_SOCK_MAXBUF", _PC_SOCK_MAXBUF}, + {"PC_SOCK_MAXBUF", _PC_SOCK_MAXBUF}, #endif #ifdef _PC_SYNC_IO - {"PC_SYNC_IO", _PC_SYNC_IO}, + {"PC_SYNC_IO", _PC_SYNC_IO}, #endif #ifdef _PC_VDISABLE - {"PC_VDISABLE", _PC_VDISABLE}, + {"PC_VDISABLE", _PC_VDISABLE}, #endif }; @@ -5825,14 +5826,14 @@ if (PyArg_ParseTuple(args, "iO&:fpathconf", &fd, conv_path_confname, &name)) { - long limit; + long limit; - errno = 0; - limit = fpathconf(fd, name); - if (limit == -1 && errno != 0) - posix_error(); - else - result = PyLong_FromLong(limit); + errno = 0; + limit = fpathconf(fd, name); + if (limit == -1 && errno != 0) + posix_error(); + else + result = PyLong_FromLong(limit); } return result; } @@ -5854,19 +5855,19 @@ if (PyArg_ParseTuple(args, "sO&:pathconf", &path, conv_path_confname, &name)) { - long limit; + long limit; - errno = 0; - limit = pathconf(path, name); - if (limit == -1 && errno != 0) { - if (errno == EINVAL) - /* could be a path or name problem */ - posix_error(); - else - posix_error_with_filename(path); - } + errno = 0; + limit = pathconf(path, name); + if (limit == -1 && errno != 0) { + if (errno == EINVAL) + /* could be a path or name problem */ + posix_error(); else - result = PyLong_FromLong(limit); + posix_error_with_filename(path); + } + else + result = PyLong_FromLong(limit); } return result; } @@ -5875,154 +5876,154 @@ #ifdef HAVE_CONFSTR static struct constdef posix_constants_confstr[] = { #ifdef _CS_ARCHITECTURE - {"CS_ARCHITECTURE", _CS_ARCHITECTURE}, + {"CS_ARCHITECTURE", _CS_ARCHITECTURE}, #endif #ifdef _CS_GNU_LIBC_VERSION - {"CS_GNU_LIBC_VERSION", _CS_GNU_LIBC_VERSION}, + {"CS_GNU_LIBC_VERSION", _CS_GNU_LIBC_VERSION}, #endif #ifdef _CS_GNU_LIBPTHREAD_VERSION - {"CS_GNU_LIBPTHREAD_VERSION", _CS_GNU_LIBPTHREAD_VERSION}, + {"CS_GNU_LIBPTHREAD_VERSION", _CS_GNU_LIBPTHREAD_VERSION}, #endif #ifdef _CS_HOSTNAME - {"CS_HOSTNAME", _CS_HOSTNAME}, + {"CS_HOSTNAME", _CS_HOSTNAME}, #endif #ifdef _CS_HW_PROVIDER - {"CS_HW_PROVIDER", _CS_HW_PROVIDER}, + {"CS_HW_PROVIDER", _CS_HW_PROVIDER}, #endif #ifdef _CS_HW_SERIAL - {"CS_HW_SERIAL", _CS_HW_SERIAL}, + {"CS_HW_SERIAL", _CS_HW_SERIAL}, #endif #ifdef _CS_INITTAB_NAME - {"CS_INITTAB_NAME", _CS_INITTAB_NAME}, + {"CS_INITTAB_NAME", _CS_INITTAB_NAME}, #endif #ifdef _CS_LFS64_CFLAGS - {"CS_LFS64_CFLAGS", _CS_LFS64_CFLAGS}, + {"CS_LFS64_CFLAGS", _CS_LFS64_CFLAGS}, #endif #ifdef _CS_LFS64_LDFLAGS - {"CS_LFS64_LDFLAGS", _CS_LFS64_LDFLAGS}, + {"CS_LFS64_LDFLAGS", _CS_LFS64_LDFLAGS}, #endif #ifdef _CS_LFS64_LIBS - {"CS_LFS64_LIBS", _CS_LFS64_LIBS}, + {"CS_LFS64_LIBS", _CS_LFS64_LIBS}, #endif #ifdef _CS_LFS64_LINTFLAGS - {"CS_LFS64_LINTFLAGS", _CS_LFS64_LINTFLAGS}, + {"CS_LFS64_LINTFLAGS", _CS_LFS64_LINTFLAGS}, #endif #ifdef _CS_LFS_CFLAGS - {"CS_LFS_CFLAGS", _CS_LFS_CFLAGS}, + {"CS_LFS_CFLAGS", _CS_LFS_CFLAGS}, #endif #ifdef _CS_LFS_LDFLAGS - {"CS_LFS_LDFLAGS", _CS_LFS_LDFLAGS}, + {"CS_LFS_LDFLAGS", _CS_LFS_LDFLAGS}, #endif #ifdef _CS_LFS_LIBS - {"CS_LFS_LIBS", _CS_LFS_LIBS}, + {"CS_LFS_LIBS", _CS_LFS_LIBS}, #endif #ifdef _CS_LFS_LINTFLAGS - {"CS_LFS_LINTFLAGS", _CS_LFS_LINTFLAGS}, + {"CS_LFS_LINTFLAGS", _CS_LFS_LINTFLAGS}, #endif #ifdef _CS_MACHINE - {"CS_MACHINE", _CS_MACHINE}, + {"CS_MACHINE", _CS_MACHINE}, #endif #ifdef _CS_PATH - {"CS_PATH", _CS_PATH}, + {"CS_PATH", _CS_PATH}, #endif #ifdef _CS_RELEASE - {"CS_RELEASE", _CS_RELEASE}, + {"CS_RELEASE", _CS_RELEASE}, #endif #ifdef _CS_SRPC_DOMAIN - {"CS_SRPC_DOMAIN", _CS_SRPC_DOMAIN}, + {"CS_SRPC_DOMAIN", _CS_SRPC_DOMAIN}, #endif #ifdef _CS_SYSNAME - {"CS_SYSNAME", _CS_SYSNAME}, + {"CS_SYSNAME", _CS_SYSNAME}, #endif #ifdef _CS_VERSION - {"CS_VERSION", _CS_VERSION}, + {"CS_VERSION", _CS_VERSION}, #endif #ifdef _CS_XBS5_ILP32_OFF32_CFLAGS - {"CS_XBS5_ILP32_OFF32_CFLAGS", _CS_XBS5_ILP32_OFF32_CFLAGS}, + {"CS_XBS5_ILP32_OFF32_CFLAGS", _CS_XBS5_ILP32_OFF32_CFLAGS}, #endif #ifdef _CS_XBS5_ILP32_OFF32_LDFLAGS - {"CS_XBS5_ILP32_OFF32_LDFLAGS", _CS_XBS5_ILP32_OFF32_LDFLAGS}, + {"CS_XBS5_ILP32_OFF32_LDFLAGS", _CS_XBS5_ILP32_OFF32_LDFLAGS}, #endif #ifdef _CS_XBS5_ILP32_OFF32_LIBS - {"CS_XBS5_ILP32_OFF32_LIBS", _CS_XBS5_ILP32_OFF32_LIBS}, + {"CS_XBS5_ILP32_OFF32_LIBS", _CS_XBS5_ILP32_OFF32_LIBS}, #endif #ifdef _CS_XBS5_ILP32_OFF32_LINTFLAGS - {"CS_XBS5_ILP32_OFF32_LINTFLAGS", _CS_XBS5_ILP32_OFF32_LINTFLAGS}, + {"CS_XBS5_ILP32_OFF32_LINTFLAGS", _CS_XBS5_ILP32_OFF32_LINTFLAGS}, #endif #ifdef _CS_XBS5_ILP32_OFFBIG_CFLAGS - {"CS_XBS5_ILP32_OFFBIG_CFLAGS", _CS_XBS5_ILP32_OFFBIG_CFLAGS}, + {"CS_XBS5_ILP32_OFFBIG_CFLAGS", _CS_XBS5_ILP32_OFFBIG_CFLAGS}, #endif #ifdef _CS_XBS5_ILP32_OFFBIG_LDFLAGS - {"CS_XBS5_ILP32_OFFBIG_LDFLAGS", _CS_XBS5_ILP32_OFFBIG_LDFLAGS}, + {"CS_XBS5_ILP32_OFFBIG_LDFLAGS", _CS_XBS5_ILP32_OFFBIG_LDFLAGS}, #endif #ifdef _CS_XBS5_ILP32_OFFBIG_LIBS - {"CS_XBS5_ILP32_OFFBIG_LIBS", _CS_XBS5_ILP32_OFFBIG_LIBS}, + {"CS_XBS5_ILP32_OFFBIG_LIBS", _CS_XBS5_ILP32_OFFBIG_LIBS}, #endif #ifdef _CS_XBS5_ILP32_OFFBIG_LINTFLAGS - {"CS_XBS5_ILP32_OFFBIG_LINTFLAGS", _CS_XBS5_ILP32_OFFBIG_LINTFLAGS}, + {"CS_XBS5_ILP32_OFFBIG_LINTFLAGS", _CS_XBS5_ILP32_OFFBIG_LINTFLAGS}, #endif #ifdef _CS_XBS5_LP64_OFF64_CFLAGS - {"CS_XBS5_LP64_OFF64_CFLAGS", _CS_XBS5_LP64_OFF64_CFLAGS}, + {"CS_XBS5_LP64_OFF64_CFLAGS", _CS_XBS5_LP64_OFF64_CFLAGS}, #endif #ifdef _CS_XBS5_LP64_OFF64_LDFLAGS - {"CS_XBS5_LP64_OFF64_LDFLAGS", _CS_XBS5_LP64_OFF64_LDFLAGS}, + {"CS_XBS5_LP64_OFF64_LDFLAGS", _CS_XBS5_LP64_OFF64_LDFLAGS}, #endif #ifdef _CS_XBS5_LP64_OFF64_LIBS - {"CS_XBS5_LP64_OFF64_LIBS", _CS_XBS5_LP64_OFF64_LIBS}, + {"CS_XBS5_LP64_OFF64_LIBS", _CS_XBS5_LP64_OFF64_LIBS}, #endif #ifdef _CS_XBS5_LP64_OFF64_LINTFLAGS - {"CS_XBS5_LP64_OFF64_LINTFLAGS", _CS_XBS5_LP64_OFF64_LINTFLAGS}, + {"CS_XBS5_LP64_OFF64_LINTFLAGS", _CS_XBS5_LP64_OFF64_LINTFLAGS}, #endif #ifdef _CS_XBS5_LPBIG_OFFBIG_CFLAGS - {"CS_XBS5_LPBIG_OFFBIG_CFLAGS", _CS_XBS5_LPBIG_OFFBIG_CFLAGS}, + {"CS_XBS5_LPBIG_OFFBIG_CFLAGS", _CS_XBS5_LPBIG_OFFBIG_CFLAGS}, #endif #ifdef _CS_XBS5_LPBIG_OFFBIG_LDFLAGS - {"CS_XBS5_LPBIG_OFFBIG_LDFLAGS", _CS_XBS5_LPBIG_OFFBIG_LDFLAGS}, + {"CS_XBS5_LPBIG_OFFBIG_LDFLAGS", _CS_XBS5_LPBIG_OFFBIG_LDFLAGS}, #endif #ifdef _CS_XBS5_LPBIG_OFFBIG_LIBS - {"CS_XBS5_LPBIG_OFFBIG_LIBS", _CS_XBS5_LPBIG_OFFBIG_LIBS}, + {"CS_XBS5_LPBIG_OFFBIG_LIBS", _CS_XBS5_LPBIG_OFFBIG_LIBS}, #endif #ifdef _CS_XBS5_LPBIG_OFFBIG_LINTFLAGS - {"CS_XBS5_LPBIG_OFFBIG_LINTFLAGS", _CS_XBS5_LPBIG_OFFBIG_LINTFLAGS}, + {"CS_XBS5_LPBIG_OFFBIG_LINTFLAGS", _CS_XBS5_LPBIG_OFFBIG_LINTFLAGS}, #endif #ifdef _MIPS_CS_AVAIL_PROCESSORS - {"MIPS_CS_AVAIL_PROCESSORS", _MIPS_CS_AVAIL_PROCESSORS}, + {"MIPS_CS_AVAIL_PROCESSORS", _MIPS_CS_AVAIL_PROCESSORS}, #endif #ifdef _MIPS_CS_BASE - {"MIPS_CS_BASE", _MIPS_CS_BASE}, + {"MIPS_CS_BASE", _MIPS_CS_BASE}, #endif #ifdef _MIPS_CS_HOSTID - {"MIPS_CS_HOSTID", _MIPS_CS_HOSTID}, + {"MIPS_CS_HOSTID", _MIPS_CS_HOSTID}, #endif #ifdef _MIPS_CS_HW_NAME - {"MIPS_CS_HW_NAME", _MIPS_CS_HW_NAME}, + {"MIPS_CS_HW_NAME", _MIPS_CS_HW_NAME}, #endif #ifdef _MIPS_CS_NUM_PROCESSORS - {"MIPS_CS_NUM_PROCESSORS", _MIPS_CS_NUM_PROCESSORS}, + {"MIPS_CS_NUM_PROCESSORS", _MIPS_CS_NUM_PROCESSORS}, #endif #ifdef _MIPS_CS_OSREL_MAJ - {"MIPS_CS_OSREL_MAJ", _MIPS_CS_OSREL_MAJ}, + {"MIPS_CS_OSREL_MAJ", _MIPS_CS_OSREL_MAJ}, #endif #ifdef _MIPS_CS_OSREL_MIN - {"MIPS_CS_OSREL_MIN", _MIPS_CS_OSREL_MIN}, + {"MIPS_CS_OSREL_MIN", _MIPS_CS_OSREL_MIN}, #endif #ifdef _MIPS_CS_OSREL_PATCH - {"MIPS_CS_OSREL_PATCH", _MIPS_CS_OSREL_PATCH}, + {"MIPS_CS_OSREL_PATCH", _MIPS_CS_OSREL_PATCH}, #endif #ifdef _MIPS_CS_OS_NAME - {"MIPS_CS_OS_NAME", _MIPS_CS_OS_NAME}, + {"MIPS_CS_OS_NAME", _MIPS_CS_OS_NAME}, #endif #ifdef _MIPS_CS_OS_PROVIDER - {"MIPS_CS_OS_PROVIDER", _MIPS_CS_OS_PROVIDER}, + {"MIPS_CS_OS_PROVIDER", _MIPS_CS_OS_PROVIDER}, #endif #ifdef _MIPS_CS_PROCESSORS - {"MIPS_CS_PROCESSORS", _MIPS_CS_PROCESSORS}, + {"MIPS_CS_PROCESSORS", _MIPS_CS_PROCESSORS}, #endif #ifdef _MIPS_CS_SERIAL - {"MIPS_CS_SERIAL", _MIPS_CS_SERIAL}, + {"MIPS_CS_SERIAL", _MIPS_CS_SERIAL}, #endif #ifdef _MIPS_CS_VENDOR - {"MIPS_CS_VENDOR", _MIPS_CS_VENDOR}, + {"MIPS_CS_VENDOR", _MIPS_CS_VENDOR}, #endif }; @@ -6046,21 +6047,21 @@ char buffer[256]; if (PyArg_ParseTuple(args, "O&:confstr", conv_confstr_confname, &name)) { - int len; + int len; errno = 0; - len = confstr(name, buffer, sizeof(buffer)); - if (len == 0) { - if (errno) { - posix_error(); - } - else { - result = Py_None; - Py_INCREF(Py_None); - } + len = confstr(name, buffer, sizeof(buffer)); + if (len == 0) { + if (errno) { + posix_error(); + } + else { + result = Py_None; + Py_INCREF(Py_None); + } } else { - if ((unsigned int)len >= sizeof(buffer)) { + if ((unsigned int)len >= sizeof(buffer)) { result = PyUnicode_FromStringAndSize(NULL, len-1); if (result != NULL) confstr(name, _PyUnicode_AsString(result), len); @@ -6077,496 +6078,496 @@ #ifdef HAVE_SYSCONF static struct constdef posix_constants_sysconf[] = { #ifdef _SC_2_CHAR_TERM - {"SC_2_CHAR_TERM", _SC_2_CHAR_TERM}, + {"SC_2_CHAR_TERM", _SC_2_CHAR_TERM}, #endif #ifdef _SC_2_C_BIND - {"SC_2_C_BIND", _SC_2_C_BIND}, + {"SC_2_C_BIND", _SC_2_C_BIND}, #endif #ifdef _SC_2_C_DEV - {"SC_2_C_DEV", _SC_2_C_DEV}, + {"SC_2_C_DEV", _SC_2_C_DEV}, #endif #ifdef _SC_2_C_VERSION - {"SC_2_C_VERSION", _SC_2_C_VERSION}, + {"SC_2_C_VERSION", _SC_2_C_VERSION}, #endif #ifdef _SC_2_FORT_DEV - {"SC_2_FORT_DEV", _SC_2_FORT_DEV}, + {"SC_2_FORT_DEV", _SC_2_FORT_DEV}, #endif #ifdef _SC_2_FORT_RUN - {"SC_2_FORT_RUN", _SC_2_FORT_RUN}, + {"SC_2_FORT_RUN", _SC_2_FORT_RUN}, #endif #ifdef _SC_2_LOCALEDEF - {"SC_2_LOCALEDEF", _SC_2_LOCALEDEF}, + {"SC_2_LOCALEDEF", _SC_2_LOCALEDEF}, #endif #ifdef _SC_2_SW_DEV - {"SC_2_SW_DEV", _SC_2_SW_DEV}, + {"SC_2_SW_DEV", _SC_2_SW_DEV}, #endif #ifdef _SC_2_UPE - {"SC_2_UPE", _SC_2_UPE}, + {"SC_2_UPE", _SC_2_UPE}, #endif #ifdef _SC_2_VERSION - {"SC_2_VERSION", _SC_2_VERSION}, + {"SC_2_VERSION", _SC_2_VERSION}, #endif #ifdef _SC_ABI_ASYNCHRONOUS_IO - {"SC_ABI_ASYNCHRONOUS_IO", _SC_ABI_ASYNCHRONOUS_IO}, + {"SC_ABI_ASYNCHRONOUS_IO", _SC_ABI_ASYNCHRONOUS_IO}, #endif #ifdef _SC_ACL - {"SC_ACL", _SC_ACL}, + {"SC_ACL", _SC_ACL}, #endif #ifdef _SC_AIO_LISTIO_MAX - {"SC_AIO_LISTIO_MAX", _SC_AIO_LISTIO_MAX}, + {"SC_AIO_LISTIO_MAX", _SC_AIO_LISTIO_MAX}, #endif #ifdef _SC_AIO_MAX - {"SC_AIO_MAX", _SC_AIO_MAX}, + {"SC_AIO_MAX", _SC_AIO_MAX}, #endif #ifdef _SC_AIO_PRIO_DELTA_MAX - {"SC_AIO_PRIO_DELTA_MAX", _SC_AIO_PRIO_DELTA_MAX}, + {"SC_AIO_PRIO_DELTA_MAX", _SC_AIO_PRIO_DELTA_MAX}, #endif #ifdef _SC_ARG_MAX - {"SC_ARG_MAX", _SC_ARG_MAX}, + {"SC_ARG_MAX", _SC_ARG_MAX}, #endif #ifdef _SC_ASYNCHRONOUS_IO - {"SC_ASYNCHRONOUS_IO", _SC_ASYNCHRONOUS_IO}, + {"SC_ASYNCHRONOUS_IO", _SC_ASYNCHRONOUS_IO}, #endif #ifdef _SC_ATEXIT_MAX - {"SC_ATEXIT_MAX", _SC_ATEXIT_MAX}, + {"SC_ATEXIT_MAX", _SC_ATEXIT_MAX}, #endif #ifdef _SC_AUDIT - {"SC_AUDIT", _SC_AUDIT}, + {"SC_AUDIT", _SC_AUDIT}, #endif #ifdef _SC_AVPHYS_PAGES - {"SC_AVPHYS_PAGES", _SC_AVPHYS_PAGES}, + {"SC_AVPHYS_PAGES", _SC_AVPHYS_PAGES}, #endif #ifdef _SC_BC_BASE_MAX - {"SC_BC_BASE_MAX", _SC_BC_BASE_MAX}, + {"SC_BC_BASE_MAX", _SC_BC_BASE_MAX}, #endif #ifdef _SC_BC_DIM_MAX - {"SC_BC_DIM_MAX", _SC_BC_DIM_MAX}, + {"SC_BC_DIM_MAX", _SC_BC_DIM_MAX}, #endif #ifdef _SC_BC_SCALE_MAX - {"SC_BC_SCALE_MAX", _SC_BC_SCALE_MAX}, + {"SC_BC_SCALE_MAX", _SC_BC_SCALE_MAX}, #endif #ifdef _SC_BC_STRING_MAX - {"SC_BC_STRING_MAX", _SC_BC_STRING_MAX}, + {"SC_BC_STRING_MAX", _SC_BC_STRING_MAX}, #endif #ifdef _SC_CAP - {"SC_CAP", _SC_CAP}, + {"SC_CAP", _SC_CAP}, #endif #ifdef _SC_CHARCLASS_NAME_MAX - {"SC_CHARCLASS_NAME_MAX", _SC_CHARCLASS_NAME_MAX}, + {"SC_CHARCLASS_NAME_MAX", _SC_CHARCLASS_NAME_MAX}, #endif #ifdef _SC_CHAR_BIT - {"SC_CHAR_BIT", _SC_CHAR_BIT}, + {"SC_CHAR_BIT", _SC_CHAR_BIT}, #endif #ifdef _SC_CHAR_MAX - {"SC_CHAR_MAX", _SC_CHAR_MAX}, + {"SC_CHAR_MAX", _SC_CHAR_MAX}, #endif #ifdef _SC_CHAR_MIN - {"SC_CHAR_MIN", _SC_CHAR_MIN}, + {"SC_CHAR_MIN", _SC_CHAR_MIN}, #endif #ifdef _SC_CHILD_MAX - {"SC_CHILD_MAX", _SC_CHILD_MAX}, + {"SC_CHILD_MAX", _SC_CHILD_MAX}, #endif #ifdef _SC_CLK_TCK - {"SC_CLK_TCK", _SC_CLK_TCK}, + {"SC_CLK_TCK", _SC_CLK_TCK}, #endif #ifdef _SC_COHER_BLKSZ - {"SC_COHER_BLKSZ", _SC_COHER_BLKSZ}, + {"SC_COHER_BLKSZ", _SC_COHER_BLKSZ}, #endif #ifdef _SC_COLL_WEIGHTS_MAX - {"SC_COLL_WEIGHTS_MAX", _SC_COLL_WEIGHTS_MAX}, + {"SC_COLL_WEIGHTS_MAX", _SC_COLL_WEIGHTS_MAX}, #endif #ifdef _SC_DCACHE_ASSOC - {"SC_DCACHE_ASSOC", _SC_DCACHE_ASSOC}, + {"SC_DCACHE_ASSOC", _SC_DCACHE_ASSOC}, #endif #ifdef _SC_DCACHE_BLKSZ - {"SC_DCACHE_BLKSZ", _SC_DCACHE_BLKSZ}, + {"SC_DCACHE_BLKSZ", _SC_DCACHE_BLKSZ}, #endif #ifdef _SC_DCACHE_LINESZ - {"SC_DCACHE_LINESZ", _SC_DCACHE_LINESZ}, + {"SC_DCACHE_LINESZ", _SC_DCACHE_LINESZ}, #endif #ifdef _SC_DCACHE_SZ - {"SC_DCACHE_SZ", _SC_DCACHE_SZ}, + {"SC_DCACHE_SZ", _SC_DCACHE_SZ}, #endif #ifdef _SC_DCACHE_TBLKSZ - {"SC_DCACHE_TBLKSZ", _SC_DCACHE_TBLKSZ}, + {"SC_DCACHE_TBLKSZ", _SC_DCACHE_TBLKSZ}, #endif #ifdef _SC_DELAYTIMER_MAX - {"SC_DELAYTIMER_MAX", _SC_DELAYTIMER_MAX}, + {"SC_DELAYTIMER_MAX", _SC_DELAYTIMER_MAX}, #endif #ifdef _SC_EQUIV_CLASS_MAX - {"SC_EQUIV_CLASS_MAX", _SC_EQUIV_CLASS_MAX}, + {"SC_EQUIV_CLASS_MAX", _SC_EQUIV_CLASS_MAX}, #endif #ifdef _SC_EXPR_NEST_MAX - {"SC_EXPR_NEST_MAX", _SC_EXPR_NEST_MAX}, + {"SC_EXPR_NEST_MAX", _SC_EXPR_NEST_MAX}, #endif #ifdef _SC_FSYNC - {"SC_FSYNC", _SC_FSYNC}, + {"SC_FSYNC", _SC_FSYNC}, #endif #ifdef _SC_GETGR_R_SIZE_MAX - {"SC_GETGR_R_SIZE_MAX", _SC_GETGR_R_SIZE_MAX}, + {"SC_GETGR_R_SIZE_MAX", _SC_GETGR_R_SIZE_MAX}, #endif #ifdef _SC_GETPW_R_SIZE_MAX - {"SC_GETPW_R_SIZE_MAX", _SC_GETPW_R_SIZE_MAX}, + {"SC_GETPW_R_SIZE_MAX", _SC_GETPW_R_SIZE_MAX}, #endif #ifdef _SC_ICACHE_ASSOC - {"SC_ICACHE_ASSOC", _SC_ICACHE_ASSOC}, + {"SC_ICACHE_ASSOC", _SC_ICACHE_ASSOC}, #endif #ifdef _SC_ICACHE_BLKSZ - {"SC_ICACHE_BLKSZ", _SC_ICACHE_BLKSZ}, + {"SC_ICACHE_BLKSZ", _SC_ICACHE_BLKSZ}, #endif #ifdef _SC_ICACHE_LINESZ - {"SC_ICACHE_LINESZ", _SC_ICACHE_LINESZ}, + {"SC_ICACHE_LINESZ", _SC_ICACHE_LINESZ}, #endif #ifdef _SC_ICACHE_SZ - {"SC_ICACHE_SZ", _SC_ICACHE_SZ}, + {"SC_ICACHE_SZ", _SC_ICACHE_SZ}, #endif #ifdef _SC_INF - {"SC_INF", _SC_INF}, + {"SC_INF", _SC_INF}, #endif #ifdef _SC_INT_MAX - {"SC_INT_MAX", _SC_INT_MAX}, + {"SC_INT_MAX", _SC_INT_MAX}, #endif #ifdef _SC_INT_MIN - {"SC_INT_MIN", _SC_INT_MIN}, + {"SC_INT_MIN", _SC_INT_MIN}, #endif #ifdef _SC_IOV_MAX - {"SC_IOV_MAX", _SC_IOV_MAX}, + {"SC_IOV_MAX", _SC_IOV_MAX}, #endif #ifdef _SC_IP_SECOPTS - {"SC_IP_SECOPTS", _SC_IP_SECOPTS}, + {"SC_IP_SECOPTS", _SC_IP_SECOPTS}, #endif #ifdef _SC_JOB_CONTROL - {"SC_JOB_CONTROL", _SC_JOB_CONTROL}, + {"SC_JOB_CONTROL", _SC_JOB_CONTROL}, #endif #ifdef _SC_KERN_POINTERS - {"SC_KERN_POINTERS", _SC_KERN_POINTERS}, + {"SC_KERN_POINTERS", _SC_KERN_POINTERS}, #endif #ifdef _SC_KERN_SIM - {"SC_KERN_SIM", _SC_KERN_SIM}, + {"SC_KERN_SIM", _SC_KERN_SIM}, #endif #ifdef _SC_LINE_MAX - {"SC_LINE_MAX", _SC_LINE_MAX}, + {"SC_LINE_MAX", _SC_LINE_MAX}, #endif #ifdef _SC_LOGIN_NAME_MAX - {"SC_LOGIN_NAME_MAX", _SC_LOGIN_NAME_MAX}, + {"SC_LOGIN_NAME_MAX", _SC_LOGIN_NAME_MAX}, #endif #ifdef _SC_LOGNAME_MAX - {"SC_LOGNAME_MAX", _SC_LOGNAME_MAX}, + {"SC_LOGNAME_MAX", _SC_LOGNAME_MAX}, #endif #ifdef _SC_LONG_BIT - {"SC_LONG_BIT", _SC_LONG_BIT}, + {"SC_LONG_BIT", _SC_LONG_BIT}, #endif #ifdef _SC_MAC - {"SC_MAC", _SC_MAC}, + {"SC_MAC", _SC_MAC}, #endif #ifdef _SC_MAPPED_FILES - {"SC_MAPPED_FILES", _SC_MAPPED_FILES}, + {"SC_MAPPED_FILES", _SC_MAPPED_FILES}, #endif #ifdef _SC_MAXPID - {"SC_MAXPID", _SC_MAXPID}, + {"SC_MAXPID", _SC_MAXPID}, #endif #ifdef _SC_MB_LEN_MAX - {"SC_MB_LEN_MAX", _SC_MB_LEN_MAX}, + {"SC_MB_LEN_MAX", _SC_MB_LEN_MAX}, #endif #ifdef _SC_MEMLOCK - {"SC_MEMLOCK", _SC_MEMLOCK}, + {"SC_MEMLOCK", _SC_MEMLOCK}, #endif #ifdef _SC_MEMLOCK_RANGE - {"SC_MEMLOCK_RANGE", _SC_MEMLOCK_RANGE}, + {"SC_MEMLOCK_RANGE", _SC_MEMLOCK_RANGE}, #endif #ifdef _SC_MEMORY_PROTECTION - {"SC_MEMORY_PROTECTION", _SC_MEMORY_PROTECTION}, + {"SC_MEMORY_PROTECTION", _SC_MEMORY_PROTECTION}, #endif #ifdef _SC_MESSAGE_PASSING - {"SC_MESSAGE_PASSING", _SC_MESSAGE_PASSING}, + {"SC_MESSAGE_PASSING", _SC_MESSAGE_PASSING}, #endif #ifdef _SC_MMAP_FIXED_ALIGNMENT - {"SC_MMAP_FIXED_ALIGNMENT", _SC_MMAP_FIXED_ALIGNMENT}, + {"SC_MMAP_FIXED_ALIGNMENT", _SC_MMAP_FIXED_ALIGNMENT}, #endif #ifdef _SC_MQ_OPEN_MAX - {"SC_MQ_OPEN_MAX", _SC_MQ_OPEN_MAX}, + {"SC_MQ_OPEN_MAX", _SC_MQ_OPEN_MAX}, #endif #ifdef _SC_MQ_PRIO_MAX - {"SC_MQ_PRIO_MAX", _SC_MQ_PRIO_MAX}, + {"SC_MQ_PRIO_MAX", _SC_MQ_PRIO_MAX}, #endif #ifdef _SC_NACLS_MAX - {"SC_NACLS_MAX", _SC_NACLS_MAX}, + {"SC_NACLS_MAX", _SC_NACLS_MAX}, #endif #ifdef _SC_NGROUPS_MAX - {"SC_NGROUPS_MAX", _SC_NGROUPS_MAX}, + {"SC_NGROUPS_MAX", _SC_NGROUPS_MAX}, #endif #ifdef _SC_NL_ARGMAX - {"SC_NL_ARGMAX", _SC_NL_ARGMAX}, + {"SC_NL_ARGMAX", _SC_NL_ARGMAX}, #endif #ifdef _SC_NL_LANGMAX - {"SC_NL_LANGMAX", _SC_NL_LANGMAX}, + {"SC_NL_LANGMAX", _SC_NL_LANGMAX}, #endif #ifdef _SC_NL_MSGMAX - {"SC_NL_MSGMAX", _SC_NL_MSGMAX}, + {"SC_NL_MSGMAX", _SC_NL_MSGMAX}, #endif #ifdef _SC_NL_NMAX - {"SC_NL_NMAX", _SC_NL_NMAX}, + {"SC_NL_NMAX", _SC_NL_NMAX}, #endif #ifdef _SC_NL_SETMAX - {"SC_NL_SETMAX", _SC_NL_SETMAX}, + {"SC_NL_SETMAX", _SC_NL_SETMAX}, #endif #ifdef _SC_NL_TEXTMAX - {"SC_NL_TEXTMAX", _SC_NL_TEXTMAX}, + {"SC_NL_TEXTMAX", _SC_NL_TEXTMAX}, #endif #ifdef _SC_NPROCESSORS_CONF - {"SC_NPROCESSORS_CONF", _SC_NPROCESSORS_CONF}, + {"SC_NPROCESSORS_CONF", _SC_NPROCESSORS_CONF}, #endif #ifdef _SC_NPROCESSORS_ONLN - {"SC_NPROCESSORS_ONLN", _SC_NPROCESSORS_ONLN}, + {"SC_NPROCESSORS_ONLN", _SC_NPROCESSORS_ONLN}, #endif #ifdef _SC_NPROC_CONF - {"SC_NPROC_CONF", _SC_NPROC_CONF}, + {"SC_NPROC_CONF", _SC_NPROC_CONF}, #endif #ifdef _SC_NPROC_ONLN - {"SC_NPROC_ONLN", _SC_NPROC_ONLN}, + {"SC_NPROC_ONLN", _SC_NPROC_ONLN}, #endif #ifdef _SC_NZERO - {"SC_NZERO", _SC_NZERO}, + {"SC_NZERO", _SC_NZERO}, #endif #ifdef _SC_OPEN_MAX - {"SC_OPEN_MAX", _SC_OPEN_MAX}, + {"SC_OPEN_MAX", _SC_OPEN_MAX}, #endif #ifdef _SC_PAGESIZE - {"SC_PAGESIZE", _SC_PAGESIZE}, + {"SC_PAGESIZE", _SC_PAGESIZE}, #endif #ifdef _SC_PAGE_SIZE - {"SC_PAGE_SIZE", _SC_PAGE_SIZE}, + {"SC_PAGE_SIZE", _SC_PAGE_SIZE}, #endif #ifdef _SC_PASS_MAX - {"SC_PASS_MAX", _SC_PASS_MAX}, + {"SC_PASS_MAX", _SC_PASS_MAX}, #endif #ifdef _SC_PHYS_PAGES - {"SC_PHYS_PAGES", _SC_PHYS_PAGES}, + {"SC_PHYS_PAGES", _SC_PHYS_PAGES}, #endif #ifdef _SC_PII - {"SC_PII", _SC_PII}, + {"SC_PII", _SC_PII}, #endif #ifdef _SC_PII_INTERNET - {"SC_PII_INTERNET", _SC_PII_INTERNET}, + {"SC_PII_INTERNET", _SC_PII_INTERNET}, #endif #ifdef _SC_PII_INTERNET_DGRAM - {"SC_PII_INTERNET_DGRAM", _SC_PII_INTERNET_DGRAM}, + {"SC_PII_INTERNET_DGRAM", _SC_PII_INTERNET_DGRAM}, #endif #ifdef _SC_PII_INTERNET_STREAM - {"SC_PII_INTERNET_STREAM", _SC_PII_INTERNET_STREAM}, + {"SC_PII_INTERNET_STREAM", _SC_PII_INTERNET_STREAM}, #endif #ifdef _SC_PII_OSI - {"SC_PII_OSI", _SC_PII_OSI}, + {"SC_PII_OSI", _SC_PII_OSI}, #endif #ifdef _SC_PII_OSI_CLTS - {"SC_PII_OSI_CLTS", _SC_PII_OSI_CLTS}, + {"SC_PII_OSI_CLTS", _SC_PII_OSI_CLTS}, #endif #ifdef _SC_PII_OSI_COTS - {"SC_PII_OSI_COTS", _SC_PII_OSI_COTS}, + {"SC_PII_OSI_COTS", _SC_PII_OSI_COTS}, #endif #ifdef _SC_PII_OSI_M - {"SC_PII_OSI_M", _SC_PII_OSI_M}, + {"SC_PII_OSI_M", _SC_PII_OSI_M}, #endif #ifdef _SC_PII_SOCKET - {"SC_PII_SOCKET", _SC_PII_SOCKET}, + {"SC_PII_SOCKET", _SC_PII_SOCKET}, #endif #ifdef _SC_PII_XTI - {"SC_PII_XTI", _SC_PII_XTI}, + {"SC_PII_XTI", _SC_PII_XTI}, #endif #ifdef _SC_POLL - {"SC_POLL", _SC_POLL}, + {"SC_POLL", _SC_POLL}, #endif #ifdef _SC_PRIORITIZED_IO - {"SC_PRIORITIZED_IO", _SC_PRIORITIZED_IO}, + {"SC_PRIORITIZED_IO", _SC_PRIORITIZED_IO}, #endif #ifdef _SC_PRIORITY_SCHEDULING - {"SC_PRIORITY_SCHEDULING", _SC_PRIORITY_SCHEDULING}, + {"SC_PRIORITY_SCHEDULING", _SC_PRIORITY_SCHEDULING}, #endif #ifdef _SC_REALTIME_SIGNALS - {"SC_REALTIME_SIGNALS", _SC_REALTIME_SIGNALS}, + {"SC_REALTIME_SIGNALS", _SC_REALTIME_SIGNALS}, #endif #ifdef _SC_RE_DUP_MAX - {"SC_RE_DUP_MAX", _SC_RE_DUP_MAX}, + {"SC_RE_DUP_MAX", _SC_RE_DUP_MAX}, #endif #ifdef _SC_RTSIG_MAX - {"SC_RTSIG_MAX", _SC_RTSIG_MAX}, + {"SC_RTSIG_MAX", _SC_RTSIG_MAX}, #endif #ifdef _SC_SAVED_IDS - {"SC_SAVED_IDS", _SC_SAVED_IDS}, + {"SC_SAVED_IDS", _SC_SAVED_IDS}, #endif #ifdef _SC_SCHAR_MAX - {"SC_SCHAR_MAX", _SC_SCHAR_MAX}, + {"SC_SCHAR_MAX", _SC_SCHAR_MAX}, #endif #ifdef _SC_SCHAR_MIN - {"SC_SCHAR_MIN", _SC_SCHAR_MIN}, + {"SC_SCHAR_MIN", _SC_SCHAR_MIN}, #endif #ifdef _SC_SELECT - {"SC_SELECT", _SC_SELECT}, + {"SC_SELECT", _SC_SELECT}, #endif #ifdef _SC_SEMAPHORES - {"SC_SEMAPHORES", _SC_SEMAPHORES}, + {"SC_SEMAPHORES", _SC_SEMAPHORES}, #endif #ifdef _SC_SEM_NSEMS_MAX - {"SC_SEM_NSEMS_MAX", _SC_SEM_NSEMS_MAX}, + {"SC_SEM_NSEMS_MAX", _SC_SEM_NSEMS_MAX}, #endif #ifdef _SC_SEM_VALUE_MAX - {"SC_SEM_VALUE_MAX", _SC_SEM_VALUE_MAX}, + {"SC_SEM_VALUE_MAX", _SC_SEM_VALUE_MAX}, #endif #ifdef _SC_SHARED_MEMORY_OBJECTS - {"SC_SHARED_MEMORY_OBJECTS", _SC_SHARED_MEMORY_OBJECTS}, + {"SC_SHARED_MEMORY_OBJECTS", _SC_SHARED_MEMORY_OBJECTS}, #endif #ifdef _SC_SHRT_MAX - {"SC_SHRT_MAX", _SC_SHRT_MAX}, + {"SC_SHRT_MAX", _SC_SHRT_MAX}, #endif #ifdef _SC_SHRT_MIN - {"SC_SHRT_MIN", _SC_SHRT_MIN}, + {"SC_SHRT_MIN", _SC_SHRT_MIN}, #endif #ifdef _SC_SIGQUEUE_MAX - {"SC_SIGQUEUE_MAX", _SC_SIGQUEUE_MAX}, + {"SC_SIGQUEUE_MAX", _SC_SIGQUEUE_MAX}, #endif #ifdef _SC_SIGRT_MAX - {"SC_SIGRT_MAX", _SC_SIGRT_MAX}, + {"SC_SIGRT_MAX", _SC_SIGRT_MAX}, #endif #ifdef _SC_SIGRT_MIN - {"SC_SIGRT_MIN", _SC_SIGRT_MIN}, + {"SC_SIGRT_MIN", _SC_SIGRT_MIN}, #endif #ifdef _SC_SOFTPOWER - {"SC_SOFTPOWER", _SC_SOFTPOWER}, + {"SC_SOFTPOWER", _SC_SOFTPOWER}, #endif #ifdef _SC_SPLIT_CACHE - {"SC_SPLIT_CACHE", _SC_SPLIT_CACHE}, + {"SC_SPLIT_CACHE", _SC_SPLIT_CACHE}, #endif #ifdef _SC_SSIZE_MAX - {"SC_SSIZE_MAX", _SC_SSIZE_MAX}, + {"SC_SSIZE_MAX", _SC_SSIZE_MAX}, #endif #ifdef _SC_STACK_PROT - {"SC_STACK_PROT", _SC_STACK_PROT}, + {"SC_STACK_PROT", _SC_STACK_PROT}, #endif #ifdef _SC_STREAM_MAX - {"SC_STREAM_MAX", _SC_STREAM_MAX}, + {"SC_STREAM_MAX", _SC_STREAM_MAX}, #endif #ifdef _SC_SYNCHRONIZED_IO - {"SC_SYNCHRONIZED_IO", _SC_SYNCHRONIZED_IO}, + {"SC_SYNCHRONIZED_IO", _SC_SYNCHRONIZED_IO}, #endif #ifdef _SC_THREADS - {"SC_THREADS", _SC_THREADS}, + {"SC_THREADS", _SC_THREADS}, #endif #ifdef _SC_THREAD_ATTR_STACKADDR - {"SC_THREAD_ATTR_STACKADDR", _SC_THREAD_ATTR_STACKADDR}, + {"SC_THREAD_ATTR_STACKADDR", _SC_THREAD_ATTR_STACKADDR}, #endif #ifdef _SC_THREAD_ATTR_STACKSIZE - {"SC_THREAD_ATTR_STACKSIZE", _SC_THREAD_ATTR_STACKSIZE}, + {"SC_THREAD_ATTR_STACKSIZE", _SC_THREAD_ATTR_STACKSIZE}, #endif #ifdef _SC_THREAD_DESTRUCTOR_ITERATIONS - {"SC_THREAD_DESTRUCTOR_ITERATIONS", _SC_THREAD_DESTRUCTOR_ITERATIONS}, + {"SC_THREAD_DESTRUCTOR_ITERATIONS", _SC_THREAD_DESTRUCTOR_ITERATIONS}, #endif #ifdef _SC_THREAD_KEYS_MAX - {"SC_THREAD_KEYS_MAX", _SC_THREAD_KEYS_MAX}, + {"SC_THREAD_KEYS_MAX", _SC_THREAD_KEYS_MAX}, #endif #ifdef _SC_THREAD_PRIORITY_SCHEDULING - {"SC_THREAD_PRIORITY_SCHEDULING", _SC_THREAD_PRIORITY_SCHEDULING}, + {"SC_THREAD_PRIORITY_SCHEDULING", _SC_THREAD_PRIORITY_SCHEDULING}, #endif #ifdef _SC_THREAD_PRIO_INHERIT - {"SC_THREAD_PRIO_INHERIT", _SC_THREAD_PRIO_INHERIT}, + {"SC_THREAD_PRIO_INHERIT", _SC_THREAD_PRIO_INHERIT}, #endif #ifdef _SC_THREAD_PRIO_PROTECT - {"SC_THREAD_PRIO_PROTECT", _SC_THREAD_PRIO_PROTECT}, + {"SC_THREAD_PRIO_PROTECT", _SC_THREAD_PRIO_PROTECT}, #endif #ifdef _SC_THREAD_PROCESS_SHARED - {"SC_THREAD_PROCESS_SHARED", _SC_THREAD_PROCESS_SHARED}, + {"SC_THREAD_PROCESS_SHARED", _SC_THREAD_PROCESS_SHARED}, #endif #ifdef _SC_THREAD_SAFE_FUNCTIONS - {"SC_THREAD_SAFE_FUNCTIONS", _SC_THREAD_SAFE_FUNCTIONS}, + {"SC_THREAD_SAFE_FUNCTIONS", _SC_THREAD_SAFE_FUNCTIONS}, #endif #ifdef _SC_THREAD_STACK_MIN - {"SC_THREAD_STACK_MIN", _SC_THREAD_STACK_MIN}, + {"SC_THREAD_STACK_MIN", _SC_THREAD_STACK_MIN}, #endif #ifdef _SC_THREAD_THREADS_MAX - {"SC_THREAD_THREADS_MAX", _SC_THREAD_THREADS_MAX}, + {"SC_THREAD_THREADS_MAX", _SC_THREAD_THREADS_MAX}, #endif #ifdef _SC_TIMERS - {"SC_TIMERS", _SC_TIMERS}, + {"SC_TIMERS", _SC_TIMERS}, #endif #ifdef _SC_TIMER_MAX - {"SC_TIMER_MAX", _SC_TIMER_MAX}, + {"SC_TIMER_MAX", _SC_TIMER_MAX}, #endif #ifdef _SC_TTY_NAME_MAX - {"SC_TTY_NAME_MAX", _SC_TTY_NAME_MAX}, + {"SC_TTY_NAME_MAX", _SC_TTY_NAME_MAX}, #endif #ifdef _SC_TZNAME_MAX - {"SC_TZNAME_MAX", _SC_TZNAME_MAX}, + {"SC_TZNAME_MAX", _SC_TZNAME_MAX}, #endif #ifdef _SC_T_IOV_MAX - {"SC_T_IOV_MAX", _SC_T_IOV_MAX}, + {"SC_T_IOV_MAX", _SC_T_IOV_MAX}, #endif #ifdef _SC_UCHAR_MAX - {"SC_UCHAR_MAX", _SC_UCHAR_MAX}, + {"SC_UCHAR_MAX", _SC_UCHAR_MAX}, #endif #ifdef _SC_UINT_MAX - {"SC_UINT_MAX", _SC_UINT_MAX}, + {"SC_UINT_MAX", _SC_UINT_MAX}, #endif #ifdef _SC_UIO_MAXIOV - {"SC_UIO_MAXIOV", _SC_UIO_MAXIOV}, + {"SC_UIO_MAXIOV", _SC_UIO_MAXIOV}, #endif #ifdef _SC_ULONG_MAX - {"SC_ULONG_MAX", _SC_ULONG_MAX}, + {"SC_ULONG_MAX", _SC_ULONG_MAX}, #endif #ifdef _SC_USHRT_MAX - {"SC_USHRT_MAX", _SC_USHRT_MAX}, + {"SC_USHRT_MAX", _SC_USHRT_MAX}, #endif #ifdef _SC_VERSION - {"SC_VERSION", _SC_VERSION}, + {"SC_VERSION", _SC_VERSION}, #endif #ifdef _SC_WORD_BIT - {"SC_WORD_BIT", _SC_WORD_BIT}, + {"SC_WORD_BIT", _SC_WORD_BIT}, #endif #ifdef _SC_XBS5_ILP32_OFF32 - {"SC_XBS5_ILP32_OFF32", _SC_XBS5_ILP32_OFF32}, + {"SC_XBS5_ILP32_OFF32", _SC_XBS5_ILP32_OFF32}, #endif #ifdef _SC_XBS5_ILP32_OFFBIG - {"SC_XBS5_ILP32_OFFBIG", _SC_XBS5_ILP32_OFFBIG}, + {"SC_XBS5_ILP32_OFFBIG", _SC_XBS5_ILP32_OFFBIG}, #endif #ifdef _SC_XBS5_LP64_OFF64 - {"SC_XBS5_LP64_OFF64", _SC_XBS5_LP64_OFF64}, + {"SC_XBS5_LP64_OFF64", _SC_XBS5_LP64_OFF64}, #endif #ifdef _SC_XBS5_LPBIG_OFFBIG - {"SC_XBS5_LPBIG_OFFBIG", _SC_XBS5_LPBIG_OFFBIG}, + {"SC_XBS5_LPBIG_OFFBIG", _SC_XBS5_LPBIG_OFFBIG}, #endif #ifdef _SC_XOPEN_CRYPT - {"SC_XOPEN_CRYPT", _SC_XOPEN_CRYPT}, + {"SC_XOPEN_CRYPT", _SC_XOPEN_CRYPT}, #endif #ifdef _SC_XOPEN_ENH_I18N - {"SC_XOPEN_ENH_I18N", _SC_XOPEN_ENH_I18N}, + {"SC_XOPEN_ENH_I18N", _SC_XOPEN_ENH_I18N}, #endif #ifdef _SC_XOPEN_LEGACY - {"SC_XOPEN_LEGACY", _SC_XOPEN_LEGACY}, + {"SC_XOPEN_LEGACY", _SC_XOPEN_LEGACY}, #endif #ifdef _SC_XOPEN_REALTIME - {"SC_XOPEN_REALTIME", _SC_XOPEN_REALTIME}, + {"SC_XOPEN_REALTIME", _SC_XOPEN_REALTIME}, #endif #ifdef _SC_XOPEN_REALTIME_THREADS - {"SC_XOPEN_REALTIME_THREADS", _SC_XOPEN_REALTIME_THREADS}, + {"SC_XOPEN_REALTIME_THREADS", _SC_XOPEN_REALTIME_THREADS}, #endif #ifdef _SC_XOPEN_SHM - {"SC_XOPEN_SHM", _SC_XOPEN_SHM}, + {"SC_XOPEN_SHM", _SC_XOPEN_SHM}, #endif #ifdef _SC_XOPEN_UNIX - {"SC_XOPEN_UNIX", _SC_XOPEN_UNIX}, + {"SC_XOPEN_UNIX", _SC_XOPEN_UNIX}, #endif #ifdef _SC_XOPEN_VERSION - {"SC_XOPEN_VERSION", _SC_XOPEN_VERSION}, + {"SC_XOPEN_VERSION", _SC_XOPEN_VERSION}, #endif #ifdef _SC_XOPEN_XCU_VERSION - {"SC_XOPEN_XCU_VERSION", _SC_XOPEN_XCU_VERSION}, + {"SC_XOPEN_XCU_VERSION", _SC_XOPEN_XCU_VERSION}, #endif #ifdef _SC_XOPEN_XPG2 - {"SC_XOPEN_XPG2", _SC_XOPEN_XPG2}, + {"SC_XOPEN_XPG2", _SC_XOPEN_XPG2}, #endif #ifdef _SC_XOPEN_XPG3 - {"SC_XOPEN_XPG3", _SC_XOPEN_XPG3}, + {"SC_XOPEN_XPG3", _SC_XOPEN_XPG3}, #endif #ifdef _SC_XOPEN_XPG4 - {"SC_XOPEN_XPG4", _SC_XOPEN_XPG4}, + {"SC_XOPEN_XPG4", _SC_XOPEN_XPG4}, #endif }; @@ -6617,16 +6618,16 @@ cmp_constdefs(const void *v1, const void *v2) { const struct constdef *c1 = - (const struct constdef *) v1; + (const struct constdef *) v1; const struct constdef *c2 = - (const struct constdef *) v2; + (const struct constdef *) v2; return strcmp(c1->name, c2->name); } static int setup_confname_table(struct constdef *table, size_t tablesize, - char *tablename, PyObject *module) + char *tablename, PyObject *module) { PyObject *d = NULL; size_t i; @@ -6634,16 +6635,16 @@ qsort(table, tablesize, sizeof(struct constdef), cmp_constdefs); d = PyDict_New(); if (d == NULL) - return -1; + return -1; for (i=0; i < tablesize; ++i) { - PyObject *o = PyLong_FromLong(table[i].value); - if (o == NULL || PyDict_SetItemString(d, table[i].name, o) == -1) { - Py_XDECREF(o); - Py_DECREF(d); - return -1; - } - Py_DECREF(o); + PyObject *o = PyLong_FromLong(table[i].value); + if (o == NULL || PyDict_SetItemString(d, table[i].name, o) == -1) { + Py_XDECREF(o); + Py_DECREF(d); + return -1; + } + Py_DECREF(o); } return PyModule_AddObject(module, tablename, d); } @@ -6657,21 +6658,21 @@ sizeof(posix_constants_pathconf) / sizeof(struct constdef), "pathconf_names", module)) - return -1; + return -1; #endif #ifdef HAVE_CONFSTR if (setup_confname_table(posix_constants_confstr, sizeof(posix_constants_confstr) / sizeof(struct constdef), "confstr_names", module)) - return -1; + return -1; #endif #ifdef HAVE_SYSCONF if (setup_confname_table(posix_constants_sysconf, sizeof(posix_constants_sysconf) / sizeof(struct constdef), "sysconf_names", module)) - return -1; + return -1; #endif return 0; } @@ -6714,61 +6715,61 @@ static PyObject * win32_startfile(PyObject *self, PyObject *args) { - PyObject *ofilepath; - char *filepath; - char *operation = NULL; - HINSTANCE rc; - - PyObject *unipath, *woperation = NULL; - if (!PyArg_ParseTuple(args, "U|s:startfile", - &unipath, &operation)) { - PyErr_Clear(); - goto normal; - } - - if (operation) { - woperation = PyUnicode_DecodeASCII(operation, - strlen(operation), NULL); - if (!woperation) { - PyErr_Clear(); - operation = NULL; - goto normal; - } - } - - Py_BEGIN_ALLOW_THREADS - rc = ShellExecuteW((HWND)0, woperation ? PyUnicode_AS_UNICODE(woperation) : 0, - PyUnicode_AS_UNICODE(unipath), - NULL, NULL, SW_SHOWNORMAL); - Py_END_ALLOW_THREADS - - Py_XDECREF(woperation); - if (rc <= (HINSTANCE)32) { - PyObject *errval = win32_error_unicode("startfile", - PyUnicode_AS_UNICODE(unipath)); - return errval; - } - Py_INCREF(Py_None); - return Py_None; + PyObject *ofilepath; + char *filepath; + char *operation = NULL; + HINSTANCE rc; + + PyObject *unipath, *woperation = NULL; + if (!PyArg_ParseTuple(args, "U|s:startfile", + &unipath, &operation)) { + PyErr_Clear(); + goto normal; + } + + if (operation) { + woperation = PyUnicode_DecodeASCII(operation, + strlen(operation), NULL); + if (!woperation) { + PyErr_Clear(); + operation = NULL; + goto normal; + } + } + + Py_BEGIN_ALLOW_THREADS + rc = ShellExecuteW((HWND)0, woperation ? PyUnicode_AS_UNICODE(woperation) : 0, + PyUnicode_AS_UNICODE(unipath), + NULL, NULL, SW_SHOWNORMAL); + Py_END_ALLOW_THREADS + + Py_XDECREF(woperation); + if (rc <= (HINSTANCE)32) { + PyObject *errval = win32_error_unicode("startfile", + PyUnicode_AS_UNICODE(unipath)); + return errval; + } + Py_INCREF(Py_None); + return Py_None; normal: - if (!PyArg_ParseTuple(args, "O&|s:startfile", - PyUnicode_FSConverter, &ofilepath, - &operation)) - return NULL; - filepath = PyBytes_AsString(ofilepath); - Py_BEGIN_ALLOW_THREADS - rc = ShellExecute((HWND)0, operation, filepath, - NULL, NULL, SW_SHOWNORMAL); - Py_END_ALLOW_THREADS - if (rc <= (HINSTANCE)32) { - PyObject *errval = win32_error("startfile", filepath); - Py_DECREF(ofilepath); - return errval; - } - Py_DECREF(ofilepath); - Py_INCREF(Py_None); - return Py_None; + if (!PyArg_ParseTuple(args, "O&|s:startfile", + PyUnicode_FSConverter, &ofilepath, + &operation)) + return NULL; + filepath = PyBytes_AsString(ofilepath); + Py_BEGIN_ALLOW_THREADS + rc = ShellExecute((HWND)0, operation, filepath, + NULL, NULL, SW_SHOWNORMAL); + Py_END_ALLOW_THREADS + if (rc <= (HINSTANCE)32) { + PyObject *errval = win32_error("startfile", filepath); + Py_DECREF(ofilepath); + return errval; + } + Py_DECREF(ofilepath); + Py_INCREF(Py_None); + return Py_None; } #endif @@ -6784,10 +6785,10 @@ { double loadavg[3]; if (getloadavg(loadavg, 3)!=3) { - PyErr_SetString(PyExc_OSError, "Load averages are unobtainable"); - return NULL; + PyErr_SetString(PyExc_OSError, "Load averages are unobtainable"); + return NULL; } else - return Py_BuildValue("ddd", loadavg[0], loadavg[1], loadavg[2]); + return Py_BuildValue("ddd", loadavg[0], loadavg[1], loadavg[2]); } #endif @@ -6811,59 +6812,59 @@ static PyObject* win32_urandom(PyObject *self, PyObject *args) { - int howMany; - PyObject* result; + int howMany; + PyObject* result; + + /* Read arguments */ + if (! PyArg_ParseTuple(args, "i:urandom", &howMany)) + return NULL; + if (howMany < 0) + return PyErr_Format(PyExc_ValueError, + "negative argument not allowed"); + + if (hCryptProv == 0) { + HINSTANCE hAdvAPI32 = NULL; + CRYPTACQUIRECONTEXTA pCryptAcquireContext = NULL; + + /* Obtain handle to the DLL containing CryptoAPI + This should not fail */ + hAdvAPI32 = GetModuleHandle("advapi32.dll"); + if(hAdvAPI32 == NULL) + return win32_error("GetModuleHandle", NULL); + + /* Obtain pointers to the CryptoAPI functions + This will fail on some early versions of Win95 */ + pCryptAcquireContext = (CRYPTACQUIRECONTEXTA)GetProcAddress( + hAdvAPI32, + "CryptAcquireContextA"); + if (pCryptAcquireContext == NULL) + return PyErr_Format(PyExc_NotImplementedError, + "CryptAcquireContextA not found"); + + pCryptGenRandom = (CRYPTGENRANDOM)GetProcAddress( + hAdvAPI32, "CryptGenRandom"); + if (pCryptGenRandom == NULL) + return PyErr_Format(PyExc_NotImplementedError, + "CryptGenRandom not found"); + + /* Acquire context */ + if (! pCryptAcquireContext(&hCryptProv, NULL, NULL, + PROV_RSA_FULL, CRYPT_VERIFYCONTEXT)) + return win32_error("CryptAcquireContext", NULL); + } - /* Read arguments */ - if (! PyArg_ParseTuple(args, "i:urandom", &howMany)) - return NULL; - if (howMany < 0) - return PyErr_Format(PyExc_ValueError, - "negative argument not allowed"); - - if (hCryptProv == 0) { - HINSTANCE hAdvAPI32 = NULL; - CRYPTACQUIRECONTEXTA pCryptAcquireContext = NULL; - - /* Obtain handle to the DLL containing CryptoAPI - This should not fail */ - hAdvAPI32 = GetModuleHandle("advapi32.dll"); - if(hAdvAPI32 == NULL) - return win32_error("GetModuleHandle", NULL); - - /* Obtain pointers to the CryptoAPI functions - This will fail on some early versions of Win95 */ - pCryptAcquireContext = (CRYPTACQUIRECONTEXTA)GetProcAddress( - hAdvAPI32, - "CryptAcquireContextA"); - if (pCryptAcquireContext == NULL) - return PyErr_Format(PyExc_NotImplementedError, - "CryptAcquireContextA not found"); - - pCryptGenRandom = (CRYPTGENRANDOM)GetProcAddress( - hAdvAPI32, "CryptGenRandom"); - if (pCryptGenRandom == NULL) - return PyErr_Format(PyExc_NotImplementedError, - "CryptGenRandom not found"); - - /* Acquire context */ - if (! pCryptAcquireContext(&hCryptProv, NULL, NULL, - PROV_RSA_FULL, CRYPT_VERIFYCONTEXT)) - return win32_error("CryptAcquireContext", NULL); - } - - /* Allocate bytes */ - result = PyBytes_FromStringAndSize(NULL, howMany); - if (result != NULL) { - /* Get random data */ - memset(PyBytes_AS_STRING(result), 0, howMany); /* zero seed */ - if (! pCryptGenRandom(hCryptProv, howMany, (unsigned char*) - PyBytes_AS_STRING(result))) { - Py_DECREF(result); - return win32_error("CryptGenRandom", NULL); - } - } - return result; + /* Allocate bytes */ + result = PyBytes_FromStringAndSize(NULL, howMany); + if (result != NULL) { + /* Get random data */ + memset(PyBytes_AS_STRING(result), 0, howMany); /* zero seed */ + if (! pCryptGenRandom(hCryptProv, howMany, (unsigned char*) + PyBytes_AS_STRING(result))) { + Py_DECREF(result); + return win32_error("CryptGenRandom", NULL); + } + } + return result; } #endif @@ -6875,33 +6876,33 @@ static PyObject * device_encoding(PyObject *self, PyObject *args) { - int fd; - if (!PyArg_ParseTuple(args, "i:device_encoding", &fd)) - return NULL; - if (!_PyVerify_fd(fd) || !isatty(fd)) { - Py_INCREF(Py_None); - return Py_None; - } + int fd; + if (!PyArg_ParseTuple(args, "i:device_encoding", &fd)) + return NULL; + if (!_PyVerify_fd(fd) || !isatty(fd)) { + Py_INCREF(Py_None); + return Py_None; + } #if defined(MS_WINDOWS) || defined(MS_WIN64) - if (fd == 0) { - char buf[100]; - sprintf(buf, "cp%d", GetConsoleCP()); - return PyUnicode_FromString(buf); - } - if (fd == 1 || fd == 2) { - char buf[100]; - sprintf(buf, "cp%d", GetConsoleOutputCP()); - return PyUnicode_FromString(buf); - } + if (fd == 0) { + char buf[100]; + sprintf(buf, "cp%d", GetConsoleCP()); + return PyUnicode_FromString(buf); + } + if (fd == 1 || fd == 2) { + char buf[100]; + sprintf(buf, "cp%d", GetConsoleOutputCP()); + return PyUnicode_FromString(buf); + } #elif defined(CODESET) - { - char *codeset = nl_langinfo(CODESET); - if (codeset != NULL && codeset[0] != 0) - return PyUnicode_FromString(codeset); - } + { + char *codeset = nl_langinfo(CODESET); + if (codeset != NULL && codeset[0] != 0) + return PyUnicode_FromString(codeset); + } #endif - Py_INCREF(Py_None); - return Py_None; + Py_INCREF(Py_None); + return Py_None; } #ifdef __VMS @@ -6914,29 +6915,29 @@ static PyObject* vms_urandom(PyObject *self, PyObject *args) { - int howMany; - PyObject* result; + int howMany; + PyObject* result; - /* Read arguments */ - if (! PyArg_ParseTuple(args, "i:urandom", &howMany)) - return NULL; - if (howMany < 0) - return PyErr_Format(PyExc_ValueError, - "negative argument not allowed"); - - /* Allocate bytes */ - result = PyBytes_FromStringAndSize(NULL, howMany); - if (result != NULL) { - /* Get random data */ - if (RAND_pseudo_bytes((unsigned char*) - PyBytes_AS_STRING(result), - howMany) < 0) { - Py_DECREF(result); - return PyErr_Format(PyExc_ValueError, - "RAND_pseudo_bytes"); - } - } - return result; + /* Read arguments */ + if (! PyArg_ParseTuple(args, "i:urandom", &howMany)) + return NULL; + if (howMany < 0) + return PyErr_Format(PyExc_ValueError, + "negative argument not allowed"); + + /* Allocate bytes */ + result = PyBytes_FromStringAndSize(NULL, howMany); + if (result != NULL) { + /* Get random data */ + if (RAND_pseudo_bytes((unsigned char*) + PyBytes_AS_STRING(result), + howMany) < 0) { + Py_DECREF(result); + return PyErr_Format(PyExc_ValueError, + "RAND_pseudo_bytes"); + } + } + return result; } #endif @@ -6948,13 +6949,13 @@ static PyObject* posix_setresuid (PyObject *self, PyObject *args) { - /* We assume uid_t is no larger than a long. */ - long ruid, euid, suid; - if (!PyArg_ParseTuple(args, "lll", &ruid, &euid, &suid)) - return NULL; - if (setresuid(ruid, euid, suid) < 0) - return posix_error(); - Py_RETURN_NONE; + /* We assume uid_t is no larger than a long. */ + long ruid, euid, suid; + if (!PyArg_ParseTuple(args, "lll", &ruid, &euid, &suid)) + return NULL; + if (setresuid(ruid, euid, suid) < 0) + return posix_error(); + Py_RETURN_NONE; } #endif @@ -6966,13 +6967,13 @@ static PyObject* posix_setresgid (PyObject *self, PyObject *args) { - /* We assume uid_t is no larger than a long. */ - long rgid, egid, sgid; - if (!PyArg_ParseTuple(args, "lll", &rgid, &egid, &sgid)) - return NULL; - if (setresgid(rgid, egid, sgid) < 0) - return posix_error(); - Py_RETURN_NONE; + /* We assume uid_t is no larger than a long. */ + long rgid, egid, sgid; + if (!PyArg_ParseTuple(args, "lll", &rgid, &egid, &sgid)) + return NULL; + if (setresgid(rgid, egid, sgid) < 0) + return posix_error(); + Py_RETURN_NONE; } #endif @@ -6984,15 +6985,15 @@ static PyObject* posix_getresuid (PyObject *self, PyObject *noargs) { - uid_t ruid, euid, suid; - long l_ruid, l_euid, l_suid; - if (getresuid(&ruid, &euid, &suid) < 0) - return posix_error(); - /* Force the values into long's as we don't know the size of uid_t. */ - l_ruid = ruid; - l_euid = euid; - l_suid = suid; - return Py_BuildValue("(lll)", l_ruid, l_euid, l_suid); + uid_t ruid, euid, suid; + long l_ruid, l_euid, l_suid; + if (getresuid(&ruid, &euid, &suid) < 0) + return posix_error(); + /* Force the values into long's as we don't know the size of uid_t. */ + l_ruid = ruid; + l_euid = euid; + l_suid = suid; + return Py_BuildValue("(lll)", l_ruid, l_euid, l_suid); } #endif @@ -7004,332 +7005,332 @@ static PyObject* posix_getresgid (PyObject *self, PyObject *noargs) { - uid_t rgid, egid, sgid; - long l_rgid, l_egid, l_sgid; - if (getresgid(&rgid, &egid, &sgid) < 0) - return posix_error(); - /* Force the values into long's as we don't know the size of uid_t. */ - l_rgid = rgid; - l_egid = egid; - l_sgid = sgid; - return Py_BuildValue("(lll)", l_rgid, l_egid, l_sgid); + uid_t rgid, egid, sgid; + long l_rgid, l_egid, l_sgid; + if (getresgid(&rgid, &egid, &sgid) < 0) + return posix_error(); + /* Force the values into long's as we don't know the size of uid_t. */ + l_rgid = rgid; + l_egid = egid; + l_sgid = sgid; + return Py_BuildValue("(lll)", l_rgid, l_egid, l_sgid); } #endif static PyMethodDef posix_methods[] = { - {"access", posix_access, METH_VARARGS, posix_access__doc__}, + {"access", posix_access, METH_VARARGS, posix_access__doc__}, #ifdef HAVE_TTYNAME - {"ttyname", posix_ttyname, METH_VARARGS, posix_ttyname__doc__}, + {"ttyname", posix_ttyname, METH_VARARGS, posix_ttyname__doc__}, #endif - {"chdir", posix_chdir, METH_VARARGS, posix_chdir__doc__}, + {"chdir", posix_chdir, METH_VARARGS, posix_chdir__doc__}, #ifdef HAVE_CHFLAGS - {"chflags", posix_chflags, METH_VARARGS, posix_chflags__doc__}, + {"chflags", posix_chflags, METH_VARARGS, posix_chflags__doc__}, #endif /* HAVE_CHFLAGS */ - {"chmod", posix_chmod, METH_VARARGS, posix_chmod__doc__}, + {"chmod", posix_chmod, METH_VARARGS, posix_chmod__doc__}, #ifdef HAVE_FCHMOD - {"fchmod", posix_fchmod, METH_VARARGS, posix_fchmod__doc__}, + {"fchmod", posix_fchmod, METH_VARARGS, posix_fchmod__doc__}, #endif /* HAVE_FCHMOD */ #ifdef HAVE_CHOWN - {"chown", posix_chown, METH_VARARGS, posix_chown__doc__}, + {"chown", posix_chown, METH_VARARGS, posix_chown__doc__}, #endif /* HAVE_CHOWN */ #ifdef HAVE_LCHMOD - {"lchmod", posix_lchmod, METH_VARARGS, posix_lchmod__doc__}, + {"lchmod", posix_lchmod, METH_VARARGS, posix_lchmod__doc__}, #endif /* HAVE_LCHMOD */ #ifdef HAVE_FCHOWN - {"fchown", posix_fchown, METH_VARARGS, posix_fchown__doc__}, + {"fchown", posix_fchown, METH_VARARGS, posix_fchown__doc__}, #endif /* HAVE_FCHOWN */ #ifdef HAVE_LCHFLAGS - {"lchflags", posix_lchflags, METH_VARARGS, posix_lchflags__doc__}, + {"lchflags", posix_lchflags, METH_VARARGS, posix_lchflags__doc__}, #endif /* HAVE_LCHFLAGS */ #ifdef HAVE_LCHOWN - {"lchown", posix_lchown, METH_VARARGS, posix_lchown__doc__}, + {"lchown", posix_lchown, METH_VARARGS, posix_lchown__doc__}, #endif /* HAVE_LCHOWN */ #ifdef HAVE_CHROOT - {"chroot", posix_chroot, METH_VARARGS, posix_chroot__doc__}, + {"chroot", posix_chroot, METH_VARARGS, posix_chroot__doc__}, #endif #ifdef HAVE_CTERMID - {"ctermid", posix_ctermid, METH_NOARGS, posix_ctermid__doc__}, + {"ctermid", posix_ctermid, METH_NOARGS, posix_ctermid__doc__}, #endif #ifdef HAVE_GETCWD - {"getcwd", (PyCFunction)posix_getcwd_unicode, - METH_NOARGS, posix_getcwd__doc__}, - {"getcwdb", (PyCFunction)posix_getcwd_bytes, - METH_NOARGS, posix_getcwdb__doc__}, + {"getcwd", (PyCFunction)posix_getcwd_unicode, + METH_NOARGS, posix_getcwd__doc__}, + {"getcwdb", (PyCFunction)posix_getcwd_bytes, + METH_NOARGS, posix_getcwdb__doc__}, #endif #ifdef HAVE_LINK - {"link", posix_link, METH_VARARGS, posix_link__doc__}, + {"link", posix_link, METH_VARARGS, posix_link__doc__}, #endif /* HAVE_LINK */ - {"listdir", posix_listdir, METH_VARARGS, posix_listdir__doc__}, - {"lstat", posix_lstat, METH_VARARGS, posix_lstat__doc__}, - {"mkdir", posix_mkdir, METH_VARARGS, posix_mkdir__doc__}, + {"listdir", posix_listdir, METH_VARARGS, posix_listdir__doc__}, + {"lstat", posix_lstat, METH_VARARGS, posix_lstat__doc__}, + {"mkdir", posix_mkdir, METH_VARARGS, posix_mkdir__doc__}, #ifdef HAVE_NICE - {"nice", posix_nice, METH_VARARGS, posix_nice__doc__}, + {"nice", posix_nice, METH_VARARGS, posix_nice__doc__}, #endif /* HAVE_NICE */ #ifdef HAVE_READLINK - {"readlink", posix_readlink, METH_VARARGS, posix_readlink__doc__}, + {"readlink", posix_readlink, METH_VARARGS, posix_readlink__doc__}, #endif /* HAVE_READLINK */ - {"rename", posix_rename, METH_VARARGS, posix_rename__doc__}, - {"rmdir", posix_rmdir, METH_VARARGS, posix_rmdir__doc__}, - {"stat", posix_stat, METH_VARARGS, posix_stat__doc__}, - {"stat_float_times", stat_float_times, METH_VARARGS, stat_float_times__doc__}, + {"rename", posix_rename, METH_VARARGS, posix_rename__doc__}, + {"rmdir", posix_rmdir, METH_VARARGS, posix_rmdir__doc__}, + {"stat", posix_stat, METH_VARARGS, posix_stat__doc__}, + {"stat_float_times", stat_float_times, METH_VARARGS, stat_float_times__doc__}, #ifdef HAVE_SYMLINK - {"symlink", posix_symlink, METH_VARARGS, posix_symlink__doc__}, + {"symlink", posix_symlink, METH_VARARGS, posix_symlink__doc__}, #endif /* HAVE_SYMLINK */ #ifdef HAVE_SYSTEM - {"system", posix_system, METH_VARARGS, posix_system__doc__}, + {"system", posix_system, METH_VARARGS, posix_system__doc__}, #endif - {"umask", posix_umask, METH_VARARGS, posix_umask__doc__}, + {"umask", posix_umask, METH_VARARGS, posix_umask__doc__}, #ifdef HAVE_UNAME - {"uname", posix_uname, METH_NOARGS, posix_uname__doc__}, + {"uname", posix_uname, METH_NOARGS, posix_uname__doc__}, #endif /* HAVE_UNAME */ - {"unlink", posix_unlink, METH_VARARGS, posix_unlink__doc__}, - {"remove", posix_unlink, METH_VARARGS, posix_remove__doc__}, - {"utime", posix_utime, METH_VARARGS, posix_utime__doc__}, + {"unlink", posix_unlink, METH_VARARGS, posix_unlink__doc__}, + {"remove", posix_unlink, METH_VARARGS, posix_remove__doc__}, + {"utime", posix_utime, METH_VARARGS, posix_utime__doc__}, #ifdef HAVE_TIMES - {"times", posix_times, METH_NOARGS, posix_times__doc__}, + {"times", posix_times, METH_NOARGS, posix_times__doc__}, #endif /* HAVE_TIMES */ - {"_exit", posix__exit, METH_VARARGS, posix__exit__doc__}, + {"_exit", posix__exit, METH_VARARGS, posix__exit__doc__}, #ifdef HAVE_EXECV - {"execv", posix_execv, METH_VARARGS, posix_execv__doc__}, - {"execve", posix_execve, METH_VARARGS, posix_execve__doc__}, + {"execv", posix_execv, METH_VARARGS, posix_execv__doc__}, + {"execve", posix_execve, METH_VARARGS, posix_execve__doc__}, #endif /* HAVE_EXECV */ #ifdef HAVE_SPAWNV - {"spawnv", posix_spawnv, METH_VARARGS, posix_spawnv__doc__}, - {"spawnve", posix_spawnve, METH_VARARGS, posix_spawnve__doc__}, + {"spawnv", posix_spawnv, METH_VARARGS, posix_spawnv__doc__}, + {"spawnve", posix_spawnve, METH_VARARGS, posix_spawnve__doc__}, #if defined(PYOS_OS2) - {"spawnvp", posix_spawnvp, METH_VARARGS, posix_spawnvp__doc__}, - {"spawnvpe", posix_spawnvpe, METH_VARARGS, posix_spawnvpe__doc__}, + {"spawnvp", posix_spawnvp, METH_VARARGS, posix_spawnvp__doc__}, + {"spawnvpe", posix_spawnvpe, METH_VARARGS, posix_spawnvpe__doc__}, #endif /* PYOS_OS2 */ #endif /* HAVE_SPAWNV */ #ifdef HAVE_FORK1 - {"fork1", posix_fork1, METH_NOARGS, posix_fork1__doc__}, + {"fork1", posix_fork1, METH_NOARGS, posix_fork1__doc__}, #endif /* HAVE_FORK1 */ #ifdef HAVE_FORK - {"fork", posix_fork, METH_NOARGS, posix_fork__doc__}, + {"fork", posix_fork, METH_NOARGS, posix_fork__doc__}, #endif /* HAVE_FORK */ #if defined(HAVE_OPENPTY) || defined(HAVE__GETPTY) || defined(HAVE_DEV_PTMX) - {"openpty", posix_openpty, METH_NOARGS, posix_openpty__doc__}, + {"openpty", posix_openpty, METH_NOARGS, posix_openpty__doc__}, #endif /* HAVE_OPENPTY || HAVE__GETPTY || HAVE_DEV_PTMX */ #ifdef HAVE_FORKPTY - {"forkpty", posix_forkpty, METH_NOARGS, posix_forkpty__doc__}, + {"forkpty", posix_forkpty, METH_NOARGS, posix_forkpty__doc__}, #endif /* HAVE_FORKPTY */ #ifdef HAVE_GETEGID - {"getegid", posix_getegid, METH_NOARGS, posix_getegid__doc__}, + {"getegid", posix_getegid, METH_NOARGS, posix_getegid__doc__}, #endif /* HAVE_GETEGID */ #ifdef HAVE_GETEUID - {"geteuid", posix_geteuid, METH_NOARGS, posix_geteuid__doc__}, + {"geteuid", posix_geteuid, METH_NOARGS, posix_geteuid__doc__}, #endif /* HAVE_GETEUID */ #ifdef HAVE_GETGID - {"getgid", posix_getgid, METH_NOARGS, posix_getgid__doc__}, + {"getgid", posix_getgid, METH_NOARGS, posix_getgid__doc__}, #endif /* HAVE_GETGID */ #ifdef HAVE_GETGROUPS - {"getgroups", posix_getgroups, METH_NOARGS, posix_getgroups__doc__}, + {"getgroups", posix_getgroups, METH_NOARGS, posix_getgroups__doc__}, #endif - {"getpid", posix_getpid, METH_NOARGS, posix_getpid__doc__}, + {"getpid", posix_getpid, METH_NOARGS, posix_getpid__doc__}, #ifdef HAVE_GETPGRP - {"getpgrp", posix_getpgrp, METH_NOARGS, posix_getpgrp__doc__}, + {"getpgrp", posix_getpgrp, METH_NOARGS, posix_getpgrp__doc__}, #endif /* HAVE_GETPGRP */ #ifdef HAVE_GETPPID - {"getppid", posix_getppid, METH_NOARGS, posix_getppid__doc__}, + {"getppid", posix_getppid, METH_NOARGS, posix_getppid__doc__}, #endif /* HAVE_GETPPID */ #ifdef HAVE_GETUID - {"getuid", posix_getuid, METH_NOARGS, posix_getuid__doc__}, + {"getuid", posix_getuid, METH_NOARGS, posix_getuid__doc__}, #endif /* HAVE_GETUID */ #ifdef HAVE_GETLOGIN - {"getlogin", posix_getlogin, METH_NOARGS, posix_getlogin__doc__}, + {"getlogin", posix_getlogin, METH_NOARGS, posix_getlogin__doc__}, #endif #ifdef HAVE_KILL - {"kill", posix_kill, METH_VARARGS, posix_kill__doc__}, + {"kill", posix_kill, METH_VARARGS, posix_kill__doc__}, #endif /* HAVE_KILL */ #ifdef HAVE_KILLPG - {"killpg", posix_killpg, METH_VARARGS, posix_killpg__doc__}, + {"killpg", posix_killpg, METH_VARARGS, posix_killpg__doc__}, #endif /* HAVE_KILLPG */ #ifdef HAVE_PLOCK - {"plock", posix_plock, METH_VARARGS, posix_plock__doc__}, + {"plock", posix_plock, METH_VARARGS, posix_plock__doc__}, #endif /* HAVE_PLOCK */ #ifdef MS_WINDOWS - {"startfile", win32_startfile, METH_VARARGS, win32_startfile__doc__}, - {"kill", win32_kill, METH_VARARGS, win32_kill__doc__}, + {"startfile", win32_startfile, METH_VARARGS, win32_startfile__doc__}, + {"kill", win32_kill, METH_VARARGS, win32_kill__doc__}, #endif #ifdef HAVE_SETUID - {"setuid", posix_setuid, METH_VARARGS, posix_setuid__doc__}, + {"setuid", posix_setuid, METH_VARARGS, posix_setuid__doc__}, #endif /* HAVE_SETUID */ #ifdef HAVE_SETEUID - {"seteuid", posix_seteuid, METH_VARARGS, posix_seteuid__doc__}, + {"seteuid", posix_seteuid, METH_VARARGS, posix_seteuid__doc__}, #endif /* HAVE_SETEUID */ #ifdef HAVE_SETEGID - {"setegid", posix_setegid, METH_VARARGS, posix_setegid__doc__}, + {"setegid", posix_setegid, METH_VARARGS, posix_setegid__doc__}, #endif /* HAVE_SETEGID */ #ifdef HAVE_SETREUID - {"setreuid", posix_setreuid, METH_VARARGS, posix_setreuid__doc__}, + {"setreuid", posix_setreuid, METH_VARARGS, posix_setreuid__doc__}, #endif /* HAVE_SETREUID */ #ifdef HAVE_SETREGID - {"setregid", posix_setregid, METH_VARARGS, posix_setregid__doc__}, + {"setregid", posix_setregid, METH_VARARGS, posix_setregid__doc__}, #endif /* HAVE_SETREGID */ #ifdef HAVE_SETGID - {"setgid", posix_setgid, METH_VARARGS, posix_setgid__doc__}, + {"setgid", posix_setgid, METH_VARARGS, posix_setgid__doc__}, #endif /* HAVE_SETGID */ #ifdef HAVE_SETGROUPS - {"setgroups", posix_setgroups, METH_O, posix_setgroups__doc__}, + {"setgroups", posix_setgroups, METH_O, posix_setgroups__doc__}, #endif /* HAVE_SETGROUPS */ #ifdef HAVE_INITGROUPS - {"initgroups", posix_initgroups, METH_VARARGS, posix_initgroups__doc__}, + {"initgroups", posix_initgroups, METH_VARARGS, posix_initgroups__doc__}, #endif /* HAVE_INITGROUPS */ #ifdef HAVE_GETPGID - {"getpgid", posix_getpgid, METH_VARARGS, posix_getpgid__doc__}, + {"getpgid", posix_getpgid, METH_VARARGS, posix_getpgid__doc__}, #endif /* HAVE_GETPGID */ #ifdef HAVE_SETPGRP - {"setpgrp", posix_setpgrp, METH_NOARGS, posix_setpgrp__doc__}, + {"setpgrp", posix_setpgrp, METH_NOARGS, posix_setpgrp__doc__}, #endif /* HAVE_SETPGRP */ #ifdef HAVE_WAIT - {"wait", posix_wait, METH_NOARGS, posix_wait__doc__}, + {"wait", posix_wait, METH_NOARGS, posix_wait__doc__}, #endif /* HAVE_WAIT */ #ifdef HAVE_WAIT3 - {"wait3", posix_wait3, METH_VARARGS, posix_wait3__doc__}, + {"wait3", posix_wait3, METH_VARARGS, posix_wait3__doc__}, #endif /* HAVE_WAIT3 */ #ifdef HAVE_WAIT4 - {"wait4", posix_wait4, METH_VARARGS, posix_wait4__doc__}, + {"wait4", posix_wait4, METH_VARARGS, posix_wait4__doc__}, #endif /* HAVE_WAIT4 */ #if defined(HAVE_WAITPID) || defined(HAVE_CWAIT) - {"waitpid", posix_waitpid, METH_VARARGS, posix_waitpid__doc__}, + {"waitpid", posix_waitpid, METH_VARARGS, posix_waitpid__doc__}, #endif /* HAVE_WAITPID */ #ifdef HAVE_GETSID - {"getsid", posix_getsid, METH_VARARGS, posix_getsid__doc__}, + {"getsid", posix_getsid, METH_VARARGS, posix_getsid__doc__}, #endif /* HAVE_GETSID */ #ifdef HAVE_SETSID - {"setsid", posix_setsid, METH_NOARGS, posix_setsid__doc__}, + {"setsid", posix_setsid, METH_NOARGS, posix_setsid__doc__}, #endif /* HAVE_SETSID */ #ifdef HAVE_SETPGID - {"setpgid", posix_setpgid, METH_VARARGS, posix_setpgid__doc__}, + {"setpgid", posix_setpgid, METH_VARARGS, posix_setpgid__doc__}, #endif /* HAVE_SETPGID */ #ifdef HAVE_TCGETPGRP - {"tcgetpgrp", posix_tcgetpgrp, METH_VARARGS, posix_tcgetpgrp__doc__}, + {"tcgetpgrp", posix_tcgetpgrp, METH_VARARGS, posix_tcgetpgrp__doc__}, #endif /* HAVE_TCGETPGRP */ #ifdef HAVE_TCSETPGRP - {"tcsetpgrp", posix_tcsetpgrp, METH_VARARGS, posix_tcsetpgrp__doc__}, + {"tcsetpgrp", posix_tcsetpgrp, METH_VARARGS, posix_tcsetpgrp__doc__}, #endif /* HAVE_TCSETPGRP */ - {"open", posix_open, METH_VARARGS, posix_open__doc__}, - {"close", posix_close, METH_VARARGS, posix_close__doc__}, - {"closerange", posix_closerange, METH_VARARGS, posix_closerange__doc__}, - {"device_encoding", device_encoding, METH_VARARGS, device_encoding__doc__}, - {"dup", posix_dup, METH_VARARGS, posix_dup__doc__}, - {"dup2", posix_dup2, METH_VARARGS, posix_dup2__doc__}, - {"lseek", posix_lseek, METH_VARARGS, posix_lseek__doc__}, - {"read", posix_read, METH_VARARGS, posix_read__doc__}, - {"write", posix_write, METH_VARARGS, posix_write__doc__}, - {"fstat", posix_fstat, METH_VARARGS, posix_fstat__doc__}, - {"isatty", posix_isatty, METH_VARARGS, posix_isatty__doc__}, + {"open", posix_open, METH_VARARGS, posix_open__doc__}, + {"close", posix_close, METH_VARARGS, posix_close__doc__}, + {"closerange", posix_closerange, METH_VARARGS, posix_closerange__doc__}, + {"device_encoding", device_encoding, METH_VARARGS, device_encoding__doc__}, + {"dup", posix_dup, METH_VARARGS, posix_dup__doc__}, + {"dup2", posix_dup2, METH_VARARGS, posix_dup2__doc__}, + {"lseek", posix_lseek, METH_VARARGS, posix_lseek__doc__}, + {"read", posix_read, METH_VARARGS, posix_read__doc__}, + {"write", posix_write, METH_VARARGS, posix_write__doc__}, + {"fstat", posix_fstat, METH_VARARGS, posix_fstat__doc__}, + {"isatty", posix_isatty, METH_VARARGS, posix_isatty__doc__}, #ifdef HAVE_PIPE - {"pipe", posix_pipe, METH_NOARGS, posix_pipe__doc__}, + {"pipe", posix_pipe, METH_NOARGS, posix_pipe__doc__}, #endif #ifdef HAVE_MKFIFO - {"mkfifo", posix_mkfifo, METH_VARARGS, posix_mkfifo__doc__}, + {"mkfifo", posix_mkfifo, METH_VARARGS, posix_mkfifo__doc__}, #endif #if defined(HAVE_MKNOD) && defined(HAVE_MAKEDEV) - {"mknod", posix_mknod, METH_VARARGS, posix_mknod__doc__}, + {"mknod", posix_mknod, METH_VARARGS, posix_mknod__doc__}, #endif #ifdef HAVE_DEVICE_MACROS - {"major", posix_major, METH_VARARGS, posix_major__doc__}, - {"minor", posix_minor, METH_VARARGS, posix_minor__doc__}, - {"makedev", posix_makedev, METH_VARARGS, posix_makedev__doc__}, + {"major", posix_major, METH_VARARGS, posix_major__doc__}, + {"minor", posix_minor, METH_VARARGS, posix_minor__doc__}, + {"makedev", posix_makedev, METH_VARARGS, posix_makedev__doc__}, #endif #ifdef HAVE_FTRUNCATE - {"ftruncate", posix_ftruncate, METH_VARARGS, posix_ftruncate__doc__}, + {"ftruncate", posix_ftruncate, METH_VARARGS, posix_ftruncate__doc__}, #endif #ifdef HAVE_PUTENV - {"putenv", posix_putenv, METH_VARARGS, posix_putenv__doc__}, + {"putenv", posix_putenv, METH_VARARGS, posix_putenv__doc__}, #endif #ifdef HAVE_UNSETENV - {"unsetenv", posix_unsetenv, METH_VARARGS, posix_unsetenv__doc__}, + {"unsetenv", posix_unsetenv, METH_VARARGS, posix_unsetenv__doc__}, #endif - {"strerror", posix_strerror, METH_VARARGS, posix_strerror__doc__}, + {"strerror", posix_strerror, METH_VARARGS, posix_strerror__doc__}, #ifdef HAVE_FCHDIR - {"fchdir", posix_fchdir, METH_O, posix_fchdir__doc__}, + {"fchdir", posix_fchdir, METH_O, posix_fchdir__doc__}, #endif #ifdef HAVE_FSYNC - {"fsync", posix_fsync, METH_O, posix_fsync__doc__}, + {"fsync", posix_fsync, METH_O, posix_fsync__doc__}, #endif #ifdef HAVE_FDATASYNC - {"fdatasync", posix_fdatasync, METH_O, posix_fdatasync__doc__}, + {"fdatasync", posix_fdatasync, METH_O, posix_fdatasync__doc__}, #endif #ifdef HAVE_SYS_WAIT_H #ifdef WCOREDUMP - {"WCOREDUMP", posix_WCOREDUMP, METH_VARARGS, posix_WCOREDUMP__doc__}, + {"WCOREDUMP", posix_WCOREDUMP, METH_VARARGS, posix_WCOREDUMP__doc__}, #endif /* WCOREDUMP */ #ifdef WIFCONTINUED - {"WIFCONTINUED",posix_WIFCONTINUED, METH_VARARGS, posix_WIFCONTINUED__doc__}, + {"WIFCONTINUED",posix_WIFCONTINUED, METH_VARARGS, posix_WIFCONTINUED__doc__}, #endif /* WIFCONTINUED */ #ifdef WIFSTOPPED - {"WIFSTOPPED", posix_WIFSTOPPED, METH_VARARGS, posix_WIFSTOPPED__doc__}, + {"WIFSTOPPED", posix_WIFSTOPPED, METH_VARARGS, posix_WIFSTOPPED__doc__}, #endif /* WIFSTOPPED */ #ifdef WIFSIGNALED - {"WIFSIGNALED", posix_WIFSIGNALED, METH_VARARGS, posix_WIFSIGNALED__doc__}, + {"WIFSIGNALED", posix_WIFSIGNALED, METH_VARARGS, posix_WIFSIGNALED__doc__}, #endif /* WIFSIGNALED */ #ifdef WIFEXITED - {"WIFEXITED", posix_WIFEXITED, METH_VARARGS, posix_WIFEXITED__doc__}, + {"WIFEXITED", posix_WIFEXITED, METH_VARARGS, posix_WIFEXITED__doc__}, #endif /* WIFEXITED */ #ifdef WEXITSTATUS - {"WEXITSTATUS", posix_WEXITSTATUS, METH_VARARGS, posix_WEXITSTATUS__doc__}, + {"WEXITSTATUS", posix_WEXITSTATUS, METH_VARARGS, posix_WEXITSTATUS__doc__}, #endif /* WEXITSTATUS */ #ifdef WTERMSIG - {"WTERMSIG", posix_WTERMSIG, METH_VARARGS, posix_WTERMSIG__doc__}, + {"WTERMSIG", posix_WTERMSIG, METH_VARARGS, posix_WTERMSIG__doc__}, #endif /* WTERMSIG */ #ifdef WSTOPSIG - {"WSTOPSIG", posix_WSTOPSIG, METH_VARARGS, posix_WSTOPSIG__doc__}, + {"WSTOPSIG", posix_WSTOPSIG, METH_VARARGS, posix_WSTOPSIG__doc__}, #endif /* WSTOPSIG */ #endif /* HAVE_SYS_WAIT_H */ #if defined(HAVE_FSTATVFS) && defined(HAVE_SYS_STATVFS_H) - {"fstatvfs", posix_fstatvfs, METH_VARARGS, posix_fstatvfs__doc__}, + {"fstatvfs", posix_fstatvfs, METH_VARARGS, posix_fstatvfs__doc__}, #endif #if defined(HAVE_STATVFS) && defined(HAVE_SYS_STATVFS_H) - {"statvfs", posix_statvfs, METH_VARARGS, posix_statvfs__doc__}, + {"statvfs", posix_statvfs, METH_VARARGS, posix_statvfs__doc__}, #endif #ifdef HAVE_CONFSTR - {"confstr", posix_confstr, METH_VARARGS, posix_confstr__doc__}, + {"confstr", posix_confstr, METH_VARARGS, posix_confstr__doc__}, #endif #ifdef HAVE_SYSCONF - {"sysconf", posix_sysconf, METH_VARARGS, posix_sysconf__doc__}, + {"sysconf", posix_sysconf, METH_VARARGS, posix_sysconf__doc__}, #endif #ifdef HAVE_FPATHCONF - {"fpathconf", posix_fpathconf, METH_VARARGS, posix_fpathconf__doc__}, + {"fpathconf", posix_fpathconf, METH_VARARGS, posix_fpathconf__doc__}, #endif #ifdef HAVE_PATHCONF - {"pathconf", posix_pathconf, METH_VARARGS, posix_pathconf__doc__}, + {"pathconf", posix_pathconf, METH_VARARGS, posix_pathconf__doc__}, #endif - {"abort", posix_abort, METH_NOARGS, posix_abort__doc__}, + {"abort", posix_abort, METH_NOARGS, posix_abort__doc__}, #ifdef MS_WINDOWS - {"_getfullpathname", posix__getfullpathname, METH_VARARGS, NULL}, + {"_getfullpathname", posix__getfullpathname, METH_VARARGS, NULL}, #endif #ifdef HAVE_GETLOADAVG - {"getloadavg", posix_getloadavg, METH_NOARGS, posix_getloadavg__doc__}, + {"getloadavg", posix_getloadavg, METH_NOARGS, posix_getloadavg__doc__}, #endif #ifdef MS_WINDOWS - {"urandom", win32_urandom, METH_VARARGS, win32_urandom__doc__}, + {"urandom", win32_urandom, METH_VARARGS, win32_urandom__doc__}, #endif #ifdef __VMS - {"urandom", vms_urandom, METH_VARARGS, vms_urandom__doc__}, + {"urandom", vms_urandom, METH_VARARGS, vms_urandom__doc__}, #endif #ifdef HAVE_SETRESUID - {"setresuid", posix_setresuid, METH_VARARGS, posix_setresuid__doc__}, + {"setresuid", posix_setresuid, METH_VARARGS, posix_setresuid__doc__}, #endif #ifdef HAVE_SETRESGID - {"setresgid", posix_setresgid, METH_VARARGS, posix_setresgid__doc__}, + {"setresgid", posix_setresgid, METH_VARARGS, posix_setresgid__doc__}, #endif #ifdef HAVE_GETRESUID - {"getresuid", posix_getresuid, METH_NOARGS, posix_getresuid__doc__}, + {"getresuid", posix_getresuid, METH_NOARGS, posix_getresuid__doc__}, #endif #ifdef HAVE_GETRESGID - {"getresgid", posix_getresgid, METH_NOARGS, posix_getresgid__doc__}, + {"getresgid", posix_getresgid, METH_NOARGS, posix_getresgid__doc__}, #endif - {NULL, NULL} /* Sentinel */ + {NULL, NULL} /* Sentinel */ }; static int ins(PyObject *module, char *symbol, long value) { - return PyModule_AddIntConstant(module, symbol, value); + return PyModule_AddIntConstant(module, symbol, value); } #if defined(PYOS_OS2) @@ -7367,7 +7368,7 @@ case 50: ver = "5.00"; break; default: PyOS_snprintf(tmp, sizeof(tmp), - "%d-%d", values[QSV_VERSION_MAJOR], + "%d-%d", values[QSV_VERSION_MAJOR], values[QSV_VERSION_MINOR]); ver = &tmp[0]; } @@ -7389,221 +7390,221 @@ all_ins(PyObject *d) { #ifdef F_OK - if (ins(d, "F_OK", (long)F_OK)) return -1; + if (ins(d, "F_OK", (long)F_OK)) return -1; #endif #ifdef R_OK - if (ins(d, "R_OK", (long)R_OK)) return -1; + if (ins(d, "R_OK", (long)R_OK)) return -1; #endif #ifdef W_OK - if (ins(d, "W_OK", (long)W_OK)) return -1; + if (ins(d, "W_OK", (long)W_OK)) return -1; #endif #ifdef X_OK - if (ins(d, "X_OK", (long)X_OK)) return -1; + if (ins(d, "X_OK", (long)X_OK)) return -1; #endif #ifdef NGROUPS_MAX - if (ins(d, "NGROUPS_MAX", (long)NGROUPS_MAX)) return -1; + if (ins(d, "NGROUPS_MAX", (long)NGROUPS_MAX)) return -1; #endif #ifdef TMP_MAX - if (ins(d, "TMP_MAX", (long)TMP_MAX)) return -1; + if (ins(d, "TMP_MAX", (long)TMP_MAX)) return -1; #endif #ifdef WCONTINUED - if (ins(d, "WCONTINUED", (long)WCONTINUED)) return -1; + if (ins(d, "WCONTINUED", (long)WCONTINUED)) return -1; #endif #ifdef WNOHANG - if (ins(d, "WNOHANG", (long)WNOHANG)) return -1; + if (ins(d, "WNOHANG", (long)WNOHANG)) return -1; #endif #ifdef WUNTRACED - if (ins(d, "WUNTRACED", (long)WUNTRACED)) return -1; + if (ins(d, "WUNTRACED", (long)WUNTRACED)) return -1; #endif #ifdef O_RDONLY - if (ins(d, "O_RDONLY", (long)O_RDONLY)) return -1; + if (ins(d, "O_RDONLY", (long)O_RDONLY)) return -1; #endif #ifdef O_WRONLY - if (ins(d, "O_WRONLY", (long)O_WRONLY)) return -1; + if (ins(d, "O_WRONLY", (long)O_WRONLY)) return -1; #endif #ifdef O_RDWR - if (ins(d, "O_RDWR", (long)O_RDWR)) return -1; + if (ins(d, "O_RDWR", (long)O_RDWR)) return -1; #endif #ifdef O_NDELAY - if (ins(d, "O_NDELAY", (long)O_NDELAY)) return -1; + if (ins(d, "O_NDELAY", (long)O_NDELAY)) return -1; #endif #ifdef O_NONBLOCK - if (ins(d, "O_NONBLOCK", (long)O_NONBLOCK)) return -1; + if (ins(d, "O_NONBLOCK", (long)O_NONBLOCK)) return -1; #endif #ifdef O_APPEND - if (ins(d, "O_APPEND", (long)O_APPEND)) return -1; + if (ins(d, "O_APPEND", (long)O_APPEND)) return -1; #endif #ifdef O_DSYNC - if (ins(d, "O_DSYNC", (long)O_DSYNC)) return -1; + if (ins(d, "O_DSYNC", (long)O_DSYNC)) return -1; #endif #ifdef O_RSYNC - if (ins(d, "O_RSYNC", (long)O_RSYNC)) return -1; + if (ins(d, "O_RSYNC", (long)O_RSYNC)) return -1; #endif #ifdef O_SYNC - if (ins(d, "O_SYNC", (long)O_SYNC)) return -1; + if (ins(d, "O_SYNC", (long)O_SYNC)) return -1; #endif #ifdef O_NOCTTY - if (ins(d, "O_NOCTTY", (long)O_NOCTTY)) return -1; + if (ins(d, "O_NOCTTY", (long)O_NOCTTY)) return -1; #endif #ifdef O_CREAT - if (ins(d, "O_CREAT", (long)O_CREAT)) return -1; + if (ins(d, "O_CREAT", (long)O_CREAT)) return -1; #endif #ifdef O_EXCL - if (ins(d, "O_EXCL", (long)O_EXCL)) return -1; + if (ins(d, "O_EXCL", (long)O_EXCL)) return -1; #endif #ifdef O_TRUNC - if (ins(d, "O_TRUNC", (long)O_TRUNC)) return -1; + if (ins(d, "O_TRUNC", (long)O_TRUNC)) return -1; #endif #ifdef O_BINARY - if (ins(d, "O_BINARY", (long)O_BINARY)) return -1; + if (ins(d, "O_BINARY", (long)O_BINARY)) return -1; #endif #ifdef O_TEXT - if (ins(d, "O_TEXT", (long)O_TEXT)) return -1; + if (ins(d, "O_TEXT", (long)O_TEXT)) return -1; #endif #ifdef O_LARGEFILE - if (ins(d, "O_LARGEFILE", (long)O_LARGEFILE)) return -1; + if (ins(d, "O_LARGEFILE", (long)O_LARGEFILE)) return -1; #endif #ifdef O_SHLOCK - if (ins(d, "O_SHLOCK", (long)O_SHLOCK)) return -1; + if (ins(d, "O_SHLOCK", (long)O_SHLOCK)) return -1; #endif #ifdef O_EXLOCK - if (ins(d, "O_EXLOCK", (long)O_EXLOCK)) return -1; + if (ins(d, "O_EXLOCK", (long)O_EXLOCK)) return -1; #endif /* MS Windows */ #ifdef O_NOINHERIT - /* Don't inherit in child processes. */ - if (ins(d, "O_NOINHERIT", (long)O_NOINHERIT)) return -1; + /* Don't inherit in child processes. */ + if (ins(d, "O_NOINHERIT", (long)O_NOINHERIT)) return -1; #endif #ifdef _O_SHORT_LIVED - /* Optimize for short life (keep in memory). */ - /* MS forgot to define this one with a non-underscore form too. */ - if (ins(d, "O_SHORT_LIVED", (long)_O_SHORT_LIVED)) return -1; + /* Optimize for short life (keep in memory). */ + /* MS forgot to define this one with a non-underscore form too. */ + if (ins(d, "O_SHORT_LIVED", (long)_O_SHORT_LIVED)) return -1; #endif #ifdef O_TEMPORARY - /* Automatically delete when last handle is closed. */ - if (ins(d, "O_TEMPORARY", (long)O_TEMPORARY)) return -1; + /* Automatically delete when last handle is closed. */ + if (ins(d, "O_TEMPORARY", (long)O_TEMPORARY)) return -1; #endif #ifdef O_RANDOM - /* Optimize for random access. */ - if (ins(d, "O_RANDOM", (long)O_RANDOM)) return -1; + /* Optimize for random access. */ + if (ins(d, "O_RANDOM", (long)O_RANDOM)) return -1; #endif #ifdef O_SEQUENTIAL - /* Optimize for sequential access. */ - if (ins(d, "O_SEQUENTIAL", (long)O_SEQUENTIAL)) return -1; + /* Optimize for sequential access. */ + if (ins(d, "O_SEQUENTIAL", (long)O_SEQUENTIAL)) return -1; #endif /* GNU extensions. */ #ifdef O_ASYNC - /* Send a SIGIO signal whenever input or output - becomes available on file descriptor */ - if (ins(d, "O_ASYNC", (long)O_ASYNC)) return -1; + /* Send a SIGIO signal whenever input or output + becomes available on file descriptor */ + if (ins(d, "O_ASYNC", (long)O_ASYNC)) return -1; #endif #ifdef O_DIRECT - /* Direct disk access. */ - if (ins(d, "O_DIRECT", (long)O_DIRECT)) return -1; + /* Direct disk access. */ + if (ins(d, "O_DIRECT", (long)O_DIRECT)) return -1; #endif #ifdef O_DIRECTORY - /* Must be a directory. */ - if (ins(d, "O_DIRECTORY", (long)O_DIRECTORY)) return -1; + /* Must be a directory. */ + if (ins(d, "O_DIRECTORY", (long)O_DIRECTORY)) return -1; #endif #ifdef O_NOFOLLOW - /* Do not follow links. */ - if (ins(d, "O_NOFOLLOW", (long)O_NOFOLLOW)) return -1; + /* Do not follow links. */ + if (ins(d, "O_NOFOLLOW", (long)O_NOFOLLOW)) return -1; #endif #ifdef O_NOATIME - /* Do not update the access time. */ - if (ins(d, "O_NOATIME", (long)O_NOATIME)) return -1; + /* Do not update the access time. */ + if (ins(d, "O_NOATIME", (long)O_NOATIME)) return -1; #endif - /* These come from sysexits.h */ + /* These come from sysexits.h */ #ifdef EX_OK - if (ins(d, "EX_OK", (long)EX_OK)) return -1; + if (ins(d, "EX_OK", (long)EX_OK)) return -1; #endif /* EX_OK */ #ifdef EX_USAGE - if (ins(d, "EX_USAGE", (long)EX_USAGE)) return -1; + if (ins(d, "EX_USAGE", (long)EX_USAGE)) return -1; #endif /* EX_USAGE */ #ifdef EX_DATAERR - if (ins(d, "EX_DATAERR", (long)EX_DATAERR)) return -1; + if (ins(d, "EX_DATAERR", (long)EX_DATAERR)) return -1; #endif /* EX_DATAERR */ #ifdef EX_NOINPUT - if (ins(d, "EX_NOINPUT", (long)EX_NOINPUT)) return -1; + if (ins(d, "EX_NOINPUT", (long)EX_NOINPUT)) return -1; #endif /* EX_NOINPUT */ #ifdef EX_NOUSER - if (ins(d, "EX_NOUSER", (long)EX_NOUSER)) return -1; + if (ins(d, "EX_NOUSER", (long)EX_NOUSER)) return -1; #endif /* EX_NOUSER */ #ifdef EX_NOHOST - if (ins(d, "EX_NOHOST", (long)EX_NOHOST)) return -1; + if (ins(d, "EX_NOHOST", (long)EX_NOHOST)) return -1; #endif /* EX_NOHOST */ #ifdef EX_UNAVAILABLE - if (ins(d, "EX_UNAVAILABLE", (long)EX_UNAVAILABLE)) return -1; + if (ins(d, "EX_UNAVAILABLE", (long)EX_UNAVAILABLE)) return -1; #endif /* EX_UNAVAILABLE */ #ifdef EX_SOFTWARE - if (ins(d, "EX_SOFTWARE", (long)EX_SOFTWARE)) return -1; + if (ins(d, "EX_SOFTWARE", (long)EX_SOFTWARE)) return -1; #endif /* EX_SOFTWARE */ #ifdef EX_OSERR - if (ins(d, "EX_OSERR", (long)EX_OSERR)) return -1; + if (ins(d, "EX_OSERR", (long)EX_OSERR)) return -1; #endif /* EX_OSERR */ #ifdef EX_OSFILE - if (ins(d, "EX_OSFILE", (long)EX_OSFILE)) return -1; + if (ins(d, "EX_OSFILE", (long)EX_OSFILE)) return -1; #endif /* EX_OSFILE */ #ifdef EX_CANTCREAT - if (ins(d, "EX_CANTCREAT", (long)EX_CANTCREAT)) return -1; + if (ins(d, "EX_CANTCREAT", (long)EX_CANTCREAT)) return -1; #endif /* EX_CANTCREAT */ #ifdef EX_IOERR - if (ins(d, "EX_IOERR", (long)EX_IOERR)) return -1; + if (ins(d, "EX_IOERR", (long)EX_IOERR)) return -1; #endif /* EX_IOERR */ #ifdef EX_TEMPFAIL - if (ins(d, "EX_TEMPFAIL", (long)EX_TEMPFAIL)) return -1; + if (ins(d, "EX_TEMPFAIL", (long)EX_TEMPFAIL)) return -1; #endif /* EX_TEMPFAIL */ #ifdef EX_PROTOCOL - if (ins(d, "EX_PROTOCOL", (long)EX_PROTOCOL)) return -1; + if (ins(d, "EX_PROTOCOL", (long)EX_PROTOCOL)) return -1; #endif /* EX_PROTOCOL */ #ifdef EX_NOPERM - if (ins(d, "EX_NOPERM", (long)EX_NOPERM)) return -1; + if (ins(d, "EX_NOPERM", (long)EX_NOPERM)) return -1; #endif /* EX_NOPERM */ #ifdef EX_CONFIG - if (ins(d, "EX_CONFIG", (long)EX_CONFIG)) return -1; + if (ins(d, "EX_CONFIG", (long)EX_CONFIG)) return -1; #endif /* EX_CONFIG */ #ifdef EX_NOTFOUND - if (ins(d, "EX_NOTFOUND", (long)EX_NOTFOUND)) return -1; + if (ins(d, "EX_NOTFOUND", (long)EX_NOTFOUND)) return -1; #endif /* EX_NOTFOUND */ #ifdef HAVE_SPAWNV #if defined(PYOS_OS2) && defined(PYCC_GCC) - if (ins(d, "P_WAIT", (long)P_WAIT)) return -1; - if (ins(d, "P_NOWAIT", (long)P_NOWAIT)) return -1; - if (ins(d, "P_OVERLAY", (long)P_OVERLAY)) return -1; - if (ins(d, "P_DEBUG", (long)P_DEBUG)) return -1; - if (ins(d, "P_SESSION", (long)P_SESSION)) return -1; - if (ins(d, "P_DETACH", (long)P_DETACH)) return -1; - if (ins(d, "P_PM", (long)P_PM)) return -1; - if (ins(d, "P_DEFAULT", (long)P_DEFAULT)) return -1; - if (ins(d, "P_MINIMIZE", (long)P_MINIMIZE)) return -1; - if (ins(d, "P_MAXIMIZE", (long)P_MAXIMIZE)) return -1; - if (ins(d, "P_FULLSCREEN", (long)P_FULLSCREEN)) return -1; - if (ins(d, "P_WINDOWED", (long)P_WINDOWED)) return -1; - if (ins(d, "P_FOREGROUND", (long)P_FOREGROUND)) return -1; - if (ins(d, "P_BACKGROUND", (long)P_BACKGROUND)) return -1; - if (ins(d, "P_NOCLOSE", (long)P_NOCLOSE)) return -1; - if (ins(d, "P_NOSESSION", (long)P_NOSESSION)) return -1; - if (ins(d, "P_QUOTE", (long)P_QUOTE)) return -1; - if (ins(d, "P_TILDE", (long)P_TILDE)) return -1; - if (ins(d, "P_UNRELATED", (long)P_UNRELATED)) return -1; - if (ins(d, "P_DEBUGDESC", (long)P_DEBUGDESC)) return -1; -#else - if (ins(d, "P_WAIT", (long)_P_WAIT)) return -1; - if (ins(d, "P_NOWAIT", (long)_P_NOWAIT)) return -1; - if (ins(d, "P_OVERLAY", (long)_OLD_P_OVERLAY)) return -1; - if (ins(d, "P_NOWAITO", (long)_P_NOWAITO)) return -1; - if (ins(d, "P_DETACH", (long)_P_DETACH)) return -1; + if (ins(d, "P_WAIT", (long)P_WAIT)) return -1; + if (ins(d, "P_NOWAIT", (long)P_NOWAIT)) return -1; + if (ins(d, "P_OVERLAY", (long)P_OVERLAY)) return -1; + if (ins(d, "P_DEBUG", (long)P_DEBUG)) return -1; + if (ins(d, "P_SESSION", (long)P_SESSION)) return -1; + if (ins(d, "P_DETACH", (long)P_DETACH)) return -1; + if (ins(d, "P_PM", (long)P_PM)) return -1; + if (ins(d, "P_DEFAULT", (long)P_DEFAULT)) return -1; + if (ins(d, "P_MINIMIZE", (long)P_MINIMIZE)) return -1; + if (ins(d, "P_MAXIMIZE", (long)P_MAXIMIZE)) return -1; + if (ins(d, "P_FULLSCREEN", (long)P_FULLSCREEN)) return -1; + if (ins(d, "P_WINDOWED", (long)P_WINDOWED)) return -1; + if (ins(d, "P_FOREGROUND", (long)P_FOREGROUND)) return -1; + if (ins(d, "P_BACKGROUND", (long)P_BACKGROUND)) return -1; + if (ins(d, "P_NOCLOSE", (long)P_NOCLOSE)) return -1; + if (ins(d, "P_NOSESSION", (long)P_NOSESSION)) return -1; + if (ins(d, "P_QUOTE", (long)P_QUOTE)) return -1; + if (ins(d, "P_TILDE", (long)P_TILDE)) return -1; + if (ins(d, "P_UNRELATED", (long)P_UNRELATED)) return -1; + if (ins(d, "P_DEBUGDESC", (long)P_DEBUGDESC)) return -1; +#else + if (ins(d, "P_WAIT", (long)_P_WAIT)) return -1; + if (ins(d, "P_NOWAIT", (long)_P_NOWAIT)) return -1; + if (ins(d, "P_OVERLAY", (long)_OLD_P_OVERLAY)) return -1; + if (ins(d, "P_NOWAITO", (long)_P_NOWAITO)) return -1; + if (ins(d, "P_DETACH", (long)_P_DETACH)) return -1; #endif #endif #if defined(PYOS_OS2) - if (insertvalues(d)) return -1; + if (insertvalues(d)) return -1; #endif - return 0; + return 0; } @@ -7621,114 +7622,114 @@ #endif static struct PyModuleDef posixmodule = { - PyModuleDef_HEAD_INIT, - MODNAME, - posix__doc__, - -1, - posix_methods, - NULL, - NULL, - NULL, - NULL + PyModuleDef_HEAD_INIT, + MODNAME, + posix__doc__, + -1, + posix_methods, + NULL, + NULL, + NULL, + NULL }; PyMODINIT_FUNC INITFUNC(void) { - PyObject *m, *v; + PyObject *m, *v; - m = PyModule_Create(&posixmodule); - if (m == NULL) - return NULL; - - /* Initialize environ dictionary */ - v = convertenviron(); - Py_XINCREF(v); - if (v == NULL || PyModule_AddObject(m, "environ", v) != 0) - return NULL; - Py_DECREF(v); + m = PyModule_Create(&posixmodule); + if (m == NULL) + return NULL; - if (all_ins(m)) - return NULL; + /* Initialize environ dictionary */ + v = convertenviron(); + Py_XINCREF(v); + if (v == NULL || PyModule_AddObject(m, "environ", v) != 0) + return NULL; + Py_DECREF(v); - if (setup_confname_tables(m)) - return NULL; + if (all_ins(m)) + return NULL; + + if (setup_confname_tables(m)) + return NULL; - Py_INCREF(PyExc_OSError); - PyModule_AddObject(m, "error", PyExc_OSError); + Py_INCREF(PyExc_OSError); + PyModule_AddObject(m, "error", PyExc_OSError); #ifdef HAVE_PUTENV - if (posix_putenv_garbage == NULL) - posix_putenv_garbage = PyDict_New(); + if (posix_putenv_garbage == NULL) + posix_putenv_garbage = PyDict_New(); #endif - if (!initialized) { - stat_result_desc.name = MODNAME ".stat_result"; - stat_result_desc.fields[7].name = PyStructSequence_UnnamedField; - stat_result_desc.fields[8].name = PyStructSequence_UnnamedField; - stat_result_desc.fields[9].name = PyStructSequence_UnnamedField; - PyStructSequence_InitType(&StatResultType, &stat_result_desc); - structseq_new = StatResultType.tp_new; - StatResultType.tp_new = statresult_new; + if (!initialized) { + stat_result_desc.name = MODNAME ".stat_result"; + stat_result_desc.fields[7].name = PyStructSequence_UnnamedField; + stat_result_desc.fields[8].name = PyStructSequence_UnnamedField; + stat_result_desc.fields[9].name = PyStructSequence_UnnamedField; + PyStructSequence_InitType(&StatResultType, &stat_result_desc); + structseq_new = StatResultType.tp_new; + StatResultType.tp_new = statresult_new; - statvfs_result_desc.name = MODNAME ".statvfs_result"; - PyStructSequence_InitType(&StatVFSResultType, &statvfs_result_desc); + statvfs_result_desc.name = MODNAME ".statvfs_result"; + PyStructSequence_InitType(&StatVFSResultType, &statvfs_result_desc); #ifdef NEED_TICKS_PER_SECOND # if defined(HAVE_SYSCONF) && defined(_SC_CLK_TCK) - ticks_per_second = sysconf(_SC_CLK_TCK); + ticks_per_second = sysconf(_SC_CLK_TCK); # elif defined(HZ) - ticks_per_second = HZ; + ticks_per_second = HZ; # else - ticks_per_second = 60; /* magic fallback value; may be bogus */ + ticks_per_second = 60; /* magic fallback value; may be bogus */ # endif #endif - } - Py_INCREF((PyObject*) &StatResultType); - PyModule_AddObject(m, "stat_result", (PyObject*) &StatResultType); - Py_INCREF((PyObject*) &StatVFSResultType); - PyModule_AddObject(m, "statvfs_result", - (PyObject*) &StatVFSResultType); - initialized = 1; + } + Py_INCREF((PyObject*) &StatResultType); + PyModule_AddObject(m, "stat_result", (PyObject*) &StatResultType); + Py_INCREF((PyObject*) &StatVFSResultType); + PyModule_AddObject(m, "statvfs_result", + (PyObject*) &StatVFSResultType); + initialized = 1; #ifdef __APPLE__ - /* - * Step 2 of weak-linking support on Mac OS X. - * - * The code below removes functions that are not available on the - * currently active platform. - * - * This block allow one to use a python binary that was build on - * OSX 10.4 on OSX 10.3, without loosing access to new APIs on - * OSX 10.4. - */ + /* + * Step 2 of weak-linking support on Mac OS X. + * + * The code below removes functions that are not available on the + * currently active platform. + * + * This block allow one to use a python binary that was build on + * OSX 10.4 on OSX 10.3, without loosing access to new APIs on + * OSX 10.4. + */ #ifdef HAVE_FSTATVFS - if (fstatvfs == NULL) { - if (PyObject_DelAttrString(m, "fstatvfs") == -1) { - return NULL; - } - } + if (fstatvfs == NULL) { + if (PyObject_DelAttrString(m, "fstatvfs") == -1) { + return NULL; + } + } #endif /* HAVE_FSTATVFS */ #ifdef HAVE_STATVFS - if (statvfs == NULL) { - if (PyObject_DelAttrString(m, "statvfs") == -1) { - return NULL; - } - } + if (statvfs == NULL) { + if (PyObject_DelAttrString(m, "statvfs") == -1) { + return NULL; + } + } #endif /* HAVE_STATVFS */ # ifdef HAVE_LCHOWN - if (lchown == NULL) { - if (PyObject_DelAttrString(m, "lchown") == -1) { - return NULL; - } - } + if (lchown == NULL) { + if (PyObject_DelAttrString(m, "lchown") == -1) { + return NULL; + } + } #endif /* HAVE_LCHOWN */ #endif /* __APPLE__ */ - return m; + return m; } Modified: python/branches/py3k-jit/PCbuild/_ctypes.vcproj ============================================================================== --- python/branches/py3k-jit/PCbuild/_ctypes.vcproj (original) +++ python/branches/py3k-jit/PCbuild/_ctypes.vcproj Thu May 6 23:49:27 2010 @@ -1,7 +1,7 @@ @@ -575,15 +583,23 @@ > + + + + + + + + + + + + + + + Modified: python/branches/py3k-jit/Tools/scripts/serve.py ============================================================================== --- python/branches/py3k-jit/Tools/scripts/serve.py (original) +++ python/branches/py3k-jit/Tools/scripts/serve.py Thu May 6 23:49:27 2010 @@ -28,4 +28,5 @@ path = sys.argv[1] port = int(sys.argv[2]) if len(sys.argv) > 2 else 8000 httpd = simple_server.make_server('', port, app) + print("Serving {} on port {}".format(path, port)) httpd.serve_forever() Modified: python/branches/py3k-jit/Tools/webchecker/wcgui.py ============================================================================== --- python/branches/py3k-jit/Tools/webchecker/wcgui.py (original) +++ python/branches/py3k-jit/Tools/webchecker/wcgui.py Thu May 6 23:49:27 2010 @@ -64,12 +64,6 @@ import tktools import webchecker -# Override some for a weaker platform -if sys.platform == 'mac': - webchecker.DEFROOT = "http://grail.cnri.reston.va.us/" - webchecker.MAXPAGE = 50000 - webchecker.verbose = 4 - def main(): try: opts, args = getopt.getopt(sys.argv[1:], 't:m:qva') Modified: python/branches/py3k-jit/Tools/webchecker/websucker.py ============================================================================== --- python/branches/py3k-jit/Tools/webchecker/websucker.py (original) +++ python/branches/py3k-jit/Tools/webchecker/websucker.py Thu May 6 23:49:27 2010 @@ -97,8 +97,6 @@ path = path + "index.html" if os.sep != "/": path = os.sep.join(path.split("/")) - if os.name == "mac": - path = os.sep + path path = os.path.join(host, path) return path Modified: python/branches/py3k-jit/configure ============================================================================== --- python/branches/py3k-jit/configure (original) +++ python/branches/py3k-jit/configure Thu May 6 23:49:27 2010 @@ -1,5 +1,5 @@ #! /bin/sh -# From configure.in Revision: 80666 . +# From configure.in Revision: 80728 . # Guess values for system-dependent variables and create Makefiles. # Generated by GNU Autoconf 2.65 for python 3.2. # @@ -5288,7 +5288,7 @@ if test "$Py_DEBUG" = 'true' ; then # Optimization messes up debuggers, so turn it off for # debug builds. - OPT="-g -Wall $STRICT_PROTO" + OPT="-g -O0 -Wall $STRICT_PROTO" else OPT="-g $WRAP -O3 -Wall $STRICT_PROTO" fi @@ -13553,13 +13553,14 @@ - case $ac_sys_system in OSF*) as_fn_error "OSF* systems are deprecated unless somebody volunteers. Check http://bugs.python.org/issue8606" "$LINENO" 5 ;; esac + + for h in `(cd $srcdir;echo Python/thread_*.h)` do THREADHEADERS="$THREADHEADERS \$(srcdir)/$h" Modified: python/branches/py3k-jit/configure.in ============================================================================== --- python/branches/py3k-jit/configure.in (original) +++ python/branches/py3k-jit/configure.in Thu May 6 23:49:27 2010 @@ -875,7 +875,7 @@ if test "$Py_DEBUG" = 'true' ; then # Optimization messes up debuggers, so turn it off for # debug builds. - OPT="-g -Wall $STRICT_PROTO" + OPT="-g -O0 -Wall $STRICT_PROTO" else OPT="-g $WRAP -O3 -Wall $STRICT_PROTO" fi Modified: python/branches/py3k-jit/setup.py ============================================================================== --- python/branches/py3k-jit/setup.py (original) +++ python/branches/py3k-jit/setup.py Thu May 6 23:49:27 2010 @@ -150,22 +150,21 @@ if ext.name in sys.builtin_module_names: self.extensions.remove(ext) - if platform != 'mac': - # Parse Modules/Setup and Modules/Setup.local to figure out which - # modules are turned on in the file. - remove_modules = [] - for filename in ('Modules/Setup', 'Modules/Setup.local'): - input = text_file.TextFile(filename, join_lines=1) - while 1: - line = input.readline() - if not line: break - line = line.split() - remove_modules.append(line[0]) - input.close() - - for ext in self.extensions[:]: - if ext.name in remove_modules: - self.extensions.remove(ext) + # Parse Modules/Setup and Modules/Setup.local to figure out which + # modules are turned on in the file. + remove_modules = [] + for filename in ('Modules/Setup', 'Modules/Setup.local'): + input = text_file.TextFile(filename, join_lines=1) + while 1: + line = input.readline() + if not line: break + line = line.split() + remove_modules.append(line[0]) + input.close() + + for ext in self.extensions[:]: + if ext.name in remove_modules: + self.extensions.remove(ext) # When you run "make CC=altcc" or something similar, you really want # those environment variables passed into the setup.py phase. Here's @@ -381,7 +380,7 @@ # Check for MacOS X, which doesn't need libm.a at all math_libs = ['m'] - if platform in ['darwin', 'mac']: + if platform == 'darwin': math_libs = [] # XXX Omitted modules: gl, pure, dl, SGI-specific modules @@ -441,19 +440,16 @@ # fcntl(2) and ioctl(2) exts.append( Extension('fcntl', ['fcntlmodule.c']) ) - if platform not in ['mac']: - # pwd(3) - exts.append( Extension('pwd', ['pwdmodule.c']) ) - # grp(3) - exts.append( Extension('grp', ['grpmodule.c']) ) - # spwd, shadow passwords - if (config_h_vars.get('HAVE_GETSPNAM', False) or - config_h_vars.get('HAVE_GETSPENT', False)): - exts.append( Extension('spwd', ['spwdmodule.c']) ) - else: - missing.append('spwd') + # pwd(3) + exts.append( Extension('pwd', ['pwdmodule.c']) ) + # grp(3) + exts.append( Extension('grp', ['grpmodule.c']) ) + # spwd, shadow passwords + if (config_h_vars.get('HAVE_GETSPNAM', False) or + config_h_vars.get('HAVE_GETSPENT', False)): + exts.append( Extension('spwd', ['spwdmodule.c']) ) else: - missing.extend(['pwd', 'grp', 'spwd']) + missing.append('spwd') # select(2); not on ancient System V exts.append( Extension('select', ['selectmodule.c']) ) @@ -462,17 +458,11 @@ exts.append( Extension('parser', ['parsermodule.c']) ) # Memory-mapped files (also works on Win32). - if platform not in ['mac']: - exts.append( Extension('mmap', ['mmapmodule.c']) ) - else: - missing.append('mmap') + exts.append( Extension('mmap', ['mmapmodule.c']) ) # Lance Ellinghaus's syslog module - if platform not in ['mac']: - # syslog daemon interface - exts.append( Extension('syslog', ['syslogmodule.c']) ) - else: - missing.append('syslog') + # syslog daemon interface + exts.append( Extension('syslog', ['syslogmodule.c']) ) # # Here ends the simple stuff. From here on, modules need certain @@ -532,16 +522,13 @@ else: missing.append('readline') - if platform not in ['mac']: - # crypt module. + # crypt module. - if self.compiler_obj.find_library_file(lib_dirs, 'crypt'): - libs = ['crypt'] - else: - libs = [] - exts.append( Extension('crypt', ['cryptmodule.c'], libraries=libs) ) + if self.compiler_obj.find_library_file(lib_dirs, 'crypt'): + libs = ['crypt'] else: - missing.append('crypt') + libs = [] + exts.append( Extension('crypt', ['cryptmodule.c'], libraries=libs) ) # CSV files exts.append( Extension('_csv', ['_csv.c']) ) @@ -986,7 +973,7 @@ missing.append('_gdbm') # Unix-only modules - if platform not in ['mac', 'win32']: + if platform != 'win32': # Steen Lumholt's termios module exts.append( Extension('termios', ['termios.c']) ) # Jeremy Hylton's rlimit interface From ncoghlan at gmail.com Thu May 6 23:57:47 2010 From: ncoghlan at gmail.com (Nick Coghlan) Date: Fri, 07 May 2010 07:57:47 +1000 Subject: [Python-checkins] r80809 - python/trunk/Objects/floatobject.c In-Reply-To: References: <20100505201609.5D92EF68D2@mail.python.org> <4BE2B6DF.6030901@trueblade.com> Message-ID: <4BE33B5B.7020506@gmail.com> Brett Cannon wrote: > And in case people are being timid in fear of upsetting me, feel free to > undo any changes I made. Obviously I prefer having the lines added back > in as comments so Clang does not complain about them in the future, but > if you simply revert a change I am not going to complain. Does Clang offer a "please be quiet" comment directive? (I'm pretty sure Klocwerk used to have that). Cheers, Nick. -- Nick Coghlan | ncoghlan at gmail.com | Brisbane, Australia --------------------------------------------------------------- From python-checkins at python.org Fri May 7 00:05:07 2010 From: python-checkins at python.org (victor.stinner) Date: Fri, 7 May 2010 00:05:07 +0200 (CEST) Subject: [Python-checkins] r80885 - in python/branches/py3k: Doc/library/os.rst Doc/library/posix.rst Lib/os.py Lib/test/test_os.py Lib/test/test_subprocess.py Misc/NEWS Modules/posixmodule.c Message-ID: <20100506220507.DD404EE992@mail.python.org> Author: victor.stinner Date: Fri May 7 00:05:07 2010 New Revision: 80885 Log: Issue #8603: Create a bytes version of os.environ for Unix Create os.environb mapping and os.getenvb() function, os.unsetenv() encodes str argument to the file system encoding with the surrogateescape error handler (instead of utf8/strict) and accepts bytes, and posix.environ keys and values are bytes. Modified: python/branches/py3k/Doc/library/os.rst python/branches/py3k/Doc/library/posix.rst python/branches/py3k/Lib/os.py python/branches/py3k/Lib/test/test_os.py python/branches/py3k/Lib/test/test_subprocess.py python/branches/py3k/Misc/NEWS python/branches/py3k/Modules/posixmodule.c Modified: python/branches/py3k/Doc/library/os.rst ============================================================================== --- python/branches/py3k/Doc/library/os.rst (original) +++ python/branches/py3k/Doc/library/os.rst Fri May 7 00:05:07 2010 @@ -107,6 +107,10 @@ to modify the environment as well as query the environment. :func:`putenv` will be called automatically when the mapping is modified. + On Unix, keys and values use :func:`sys.getfilesystemencoding` and + ``'surrogateescape'`` error handler. Use :data:`environb` if you would like + to use a different encoding. + .. note:: Calling :func:`putenv` directly does not change ``os.environ``, so it's better @@ -128,6 +132,16 @@ one of the :meth:`pop` or :meth:`clear` methods is called. +.. data:: environb + + Bytes version of :data:`environ`: a mapping object representing the + environment as byte strings. :data:`environ` and :data:`environb` are + synchronized (modify :data:`environb` updates :data:`environ`, and vice + versa). + + Availability: Unix. + + .. function:: chdir(path) fchdir(fd) getcwd() @@ -251,7 +265,19 @@ .. function:: getenv(key, default=None) Return the value of the environment variable *key* if it exists, or - *default* if it doesn't. Availability: most flavors of Unix, Windows. + *default* if it doesn't. *key*, *default* and the result are str. + Availability: most flavors of Unix, Windows. + + On Unix, keys and values are decoded with :func:`sys.getfilesystemencoding` + and ``'surrogateescape'`` error handler. Use :func:`os.getenvb` if you + would like to use a different encoding. + + +.. function:: getenvb(key, default=None) + + Return the value of the environment variable *key* if it exists, or + *default* if it doesn't. *key*, *default* and the result are bytes. + Availability: most flavors of Unix. .. function:: putenv(key, value) Modified: python/branches/py3k/Doc/library/posix.rst ============================================================================== --- python/branches/py3k/Doc/library/posix.rst (original) +++ python/branches/py3k/Doc/library/posix.rst Fri May 7 00:05:07 2010 @@ -69,17 +69,22 @@ .. data:: environ A dictionary representing the string environment at the time the interpreter - was started. For example, ``environ['HOME']`` is the pathname of your home - directory, equivalent to ``getenv("HOME")`` in C. + was started. Keys and values are bytes on Unix and str on Windows. For + example, ``environ[b'HOME']`` (``environ['HOME']`` on Windows) is the + pathname of your home directory, equivalent to ``getenv("HOME")`` in C. Modifying this dictionary does not affect the string environment passed on by :func:`execv`, :func:`popen` or :func:`system`; if you need to change the environment, pass ``environ`` to :func:`execve` or add variable assignments and export statements to the command string for :func:`system` or :func:`popen`. + .. versionchanged:: 3.2 + On Unix, keys and values are bytes. + .. note:: - The :mod:`os` module provides an alternate implementation of ``environ`` which - updates the environment on modification. Note also that updating ``os.environ`` - will render this dictionary obsolete. Use of the :mod:`os` module version of - this is recommended over direct access to the :mod:`posix` module. + The :mod:`os` module provides an alternate implementation of ``environ`` + which updates the environment on modification. Note also that updating + :data:`os.environ` will render this dictionary obsolete. Use of the + :mod:`os` module version of this is recommended over direct access to the + :mod:`posix` module. Modified: python/branches/py3k/Lib/os.py ============================================================================== --- python/branches/py3k/Lib/os.py (original) +++ python/branches/py3k/Lib/os.py Fri May 7 00:05:07 2010 @@ -387,29 +387,33 @@ from _abcoll import MutableMapping # Can't use collections (bootstrap) class _Environ(MutableMapping): - def __init__(self, environ, keymap, putenv, unsetenv): - self.keymap = keymap + def __init__(self, data, encodekey, decodekey, encodevalue, decodevalue, putenv, unsetenv): + self.encodekey = encodekey + self.decodekey = decodekey + self.encodevalue = encodevalue + self.decodevalue = decodevalue self.putenv = putenv self.unsetenv = unsetenv - self.data = data = {} - for key, value in environ.items(): - data[keymap(key)] = str(value) + self.data = data def __getitem__(self, key): - return self.data[self.keymap(key)] + value = self.data[self.encodekey(key)] + return self.decodevalue(value) def __setitem__(self, key, value): - value = str(value) + key = self.encodekey(key) + value = self.encodevalue(value) self.putenv(key, value) - self.data[self.keymap(key)] = value + self.data[key] = value def __delitem__(self, key): + key = self.encodekey(key) self.unsetenv(key) - del self.data[self.keymap(key)] + del self.data[key] def __iter__(self): for key in self.data: - yield key + yield self.decodekey(key) def __len__(self): return len(self.data) @@ -439,22 +443,67 @@ else: __all__.append("unsetenv") -if name in ('os2', 'nt'): # Where Env Var Names Must Be UPPERCASE - _keymap = lambda key: str(key.upper()) -else: # Where Env Var Names Can Be Mixed Case - _keymap = lambda key: str(key) - -environ = _Environ(environ, _keymap, _putenv, _unsetenv) +def _createenviron(): + if name in ('os2', 'nt'): + # Where Env Var Names Must Be UPPERCASE + def check_str(value): + if not isinstance(value, str): + raise TypeError("str expected, not %s" % type(value).__name__) + return value + encode = check_str + decode = str + def encodekey(key): + return encode(key).upper() + data = {} + for key, value in environ.items(): + data[encodekey(key)] = value + else: + # Where Env Var Names Can Be Mixed Case + def encode(value): + if not isinstance(value, str): + raise TypeError("str expected, not %s" % type(value).__name__) + return value.encode(sys.getfilesystemencoding(), 'surrogateescape') + def decode(value): + return value.decode(sys.getfilesystemencoding(), 'surrogateescape') + encodekey = encode + data = environ + return _Environ(data, + encodekey, decode, + encode, decode, + _putenv, _unsetenv) + +# unicode environ +environ = _createenviron() +del _createenviron def getenv(key, default=None): """Get an environment variable, return None if it doesn't exist. - The optional second argument can specify an alternate default.""" - if isinstance(key, bytes): - key = key.decode(sys.getfilesystemencoding(), "surrogateescape") + The optional second argument can specify an alternate default. + key, default and the result are str.""" return environ.get(key, default) __all__.append("getenv") +if name not in ('os2', 'nt'): + def _check_bytes(value): + if not isinstance(value, bytes): + raise TypeError("bytes expected, not %s" % type(value).__name__) + return value + + # bytes environ + environb = _Environ(environ.data, + _check_bytes, bytes, + _check_bytes, bytes, + _putenv, _unsetenv) + del _check_bytes + + def getenvb(key, default=None): + """Get an environment variable, return None if it doesn't exist. + The optional second argument can specify an alternate default. + key, default and the result are bytes.""" + return environb.get(key, default) + __all__.append("getenvb") + def _exists(name): return name in globals() Modified: python/branches/py3k/Lib/test/test_os.py ============================================================================== --- python/branches/py3k/Lib/test/test_os.py (original) +++ python/branches/py3k/Lib/test/test_os.py Fri May 7 00:05:07 2010 @@ -369,12 +369,15 @@ def setUp(self): self.__save = dict(os.environ) + self.__saveb = dict(os.environb) for key, value in self._reference().items(): os.environ[key] = value def tearDown(self): os.environ.clear() os.environ.update(self.__save) + os.environb.clear() + os.environb.update(self.__saveb) def _reference(self): return {"KEY1":"VALUE1", "KEY2":"VALUE2", "KEY3":"VALUE3"} @@ -439,6 +442,24 @@ # Supplied PATH environment variable self.assertSequenceEqual(test_path, os.get_exec_path(test_env)) + @unittest.skipIf(sys.platform == "win32", "POSIX specific test") + def test_environb(self): + # os.environ -> os.environb + value = 'euro\u20ac' + try: + value_bytes = value.encode(sys.getfilesystemencoding(), 'surrogateescape') + except UnicodeEncodeError: + raise unittest.SkipTest("U+20AC character is not encodable to %s" % sys.getfilesystemencoding()) + os.environ['unicode'] = value + self.assertEquals(os.environ['unicode'], value) + self.assertEquals(os.environb[b'unicode'], value_bytes) + + # os.environb -> os.environ + value = b'\xff' + os.environb[b'bytes'] = value + self.assertEquals(os.environb[b'bytes'], value) + value_str = value.decode(sys.getfilesystemencoding(), 'surrogateescape') + self.assertEquals(os.environ['bytes'], value_str) class WalkTests(unittest.TestCase): """Tests for os.walk().""" Modified: python/branches/py3k/Lib/test/test_subprocess.py ============================================================================== --- python/branches/py3k/Lib/test/test_subprocess.py (original) +++ python/branches/py3k/Lib/test/test_subprocess.py Fri May 7 00:05:07 2010 @@ -803,8 +803,6 @@ def test_undecodable_env(self): for key, value in (('test', 'abc\uDCFF'), ('test\uDCFF', '42')): - value_repr = repr(value).encode("ascii") - # test str with surrogates script = "import os; print(repr(os.getenv(%s)))" % repr(key) env = os.environ.copy() @@ -813,19 +811,19 @@ [sys.executable, "-c", script], env=env) stdout = stdout.rstrip(b'\n\r') - self.assertEquals(stdout, value_repr) + self.assertEquals(stdout.decode('ascii'), repr(value)) # test bytes key = key.encode("ascii", "surrogateescape") value = value.encode("ascii", "surrogateescape") - script = "import os; print(repr(os.getenv(%s)))" % repr(key) + script = "import os; print(repr(os.getenvb(%s)))" % repr(key) env = os.environ.copy() env[key] = value stdout = subprocess.check_output( [sys.executable, "-c", script], env=env) stdout = stdout.rstrip(b'\n\r') - self.assertEquals(stdout, value_repr) + self.assertEquals(stdout.decode('ascii'), repr(value)) @unittest.skipUnless(mswindows, "Windows specific tests") Modified: python/branches/py3k/Misc/NEWS ============================================================================== --- python/branches/py3k/Misc/NEWS (original) +++ python/branches/py3k/Misc/NEWS Fri May 7 00:05:07 2010 @@ -348,6 +348,12 @@ Library ------- +- Issue #8603: Create a bytes version of os.environ for Unix: create + os.environb mapping and os.getenvb() function, os.unsetenv() encodes str + argument to the file system encoding with the surrogateescape error handler + (instead of utf8/strict) and accepts bytes, and posix.environ keys and values + are bytes. + - Issue #8573: asyncore _strerror() function might throw ValueError. - Issue #8483: asyncore.dispatcher's __getattr__ method produced confusing Modified: python/branches/py3k/Modules/posixmodule.c ============================================================================== --- python/branches/py3k/Modules/posixmodule.c (original) +++ python/branches/py3k/Modules/posixmodule.c Fri May 7 00:05:07 2010 @@ -498,14 +498,12 @@ char *p = strchr(*e, '='); if (p == NULL) continue; - k = PyUnicode_Decode(*e, (int)(p-*e), - Py_FileSystemDefaultEncoding, "surrogateescape"); + k = PyBytes_FromStringAndSize(*e, (int)(p-*e)); if (k == NULL) { PyErr_Clear(); continue; } - v = PyUnicode_Decode(p+1, strlen(p+1), - Py_FileSystemDefaultEncoding, "surrogateescape"); + v = PyBytes_FromStringAndSize(p+1, strlen(p+1)); if (v == NULL) { PyErr_Clear(); Py_DECREF(k); @@ -5301,7 +5299,7 @@ char *s1, *s2; char *newenv; #endif - PyObject *newstr; + PyObject *newstr = NULL; size_t len; #ifdef MS_WINDOWS @@ -5324,15 +5322,19 @@ APIRET rc; rc = DosSetExtLIBPATH(s2, BEGIN_LIBPATH); - if (rc != NO_ERROR) - return os2_error(rc); + if (rc != NO_ERROR) { + os2_error(rc); + goto error; + } } else if (stricmp(s1, "ENDLIBPATH") == 0) { APIRET rc; rc = DosSetExtLIBPATH(s2, END_LIBPATH); - if (rc != NO_ERROR) - return os2_error(rc); + if (rc != NO_ERROR) { + os2_error(rc); + goto error; + } } else { #endif /* XXX This can leak memory -- not easy to fix :-( */ @@ -5342,36 +5344,40 @@ len = wcslen(s1) + wcslen(s2) + 2; newstr = PyUnicode_FromUnicode(NULL, (int)len - 1); #else - len = strlen(s1) + strlen(s2) + 2; + len = PyBytes_GET_SIZE(os1) + PyBytes_GET_SIZE(os2) + 2; newstr = PyBytes_FromStringAndSize(NULL, (int)len - 1); #endif - if (newstr == NULL) - return PyErr_NoMemory(); + if (newstr == NULL) { + PyErr_NoMemory(); + goto error; + } #ifdef MS_WINDOWS newenv = PyUnicode_AsUnicode(newstr); _snwprintf(newenv, len, L"%s=%s", s1, s2); if (_wputenv(newenv)) { - Py_DECREF(newstr); posix_error(); - return NULL; + goto error; } #else newenv = PyBytes_AS_STRING(newstr); PyOS_snprintf(newenv, len, "%s=%s", s1, s2); if (putenv(newenv)) { - Py_DECREF(newstr); - Py_DECREF(os1); - Py_DECREF(os2); posix_error(); - return NULL; + goto error; } #endif + /* Install the first arg and newstr in posix_putenv_garbage; * this will cause previous value to be collected. This has to * happen after the real putenv() call because the old value * was still accessible until then. */ if (PyDict_SetItem(posix_putenv_garbage, - PyTuple_GET_ITEM(args, 0), newstr)) { +#ifdef MS_WINDOWS + PyTuple_GET_ITEM(args, 0), +#else + os1, +#endif + newstr)) { /* really not much we can do; just leak */ PyErr_Clear(); } @@ -5382,12 +5388,20 @@ #if defined(PYOS_OS2) } #endif + #ifndef MS_WINDOWS Py_DECREF(os1); Py_DECREF(os2); #endif - Py_INCREF(Py_None); - return Py_None; + Py_RETURN_NONE; + +error: +#ifndef MS_WINDOWS + Py_DECREF(os1); + Py_DECREF(os2); +#endif + Py_XDECREF(newstr); + return NULL; } #endif /* putenv */ @@ -5399,10 +5413,20 @@ static PyObject * posix_unsetenv(PyObject *self, PyObject *args) { +#ifdef MS_WINDOWS char *s1; if (!PyArg_ParseTuple(args, "s:unsetenv", &s1)) return NULL; +#else + PyObject *os1; + char *s1; + + if (!PyArg_ParseTuple(args, "O&:unsetenv", + PyUnicode_FSConverter, &os1)) + return NULL; + s1 = PyBytes_AsString(os1); +#endif unsetenv(s1); @@ -5412,13 +5436,20 @@ * old value was still accessible until then. */ if (PyDict_DelItem(posix_putenv_garbage, - PyTuple_GET_ITEM(args, 0))) { +#ifdef MS_WINDOWS + PyTuple_GET_ITEM(args, 0) +#else + os1 +#endif + )) { /* really not much we can do; just leak */ PyErr_Clear(); } - Py_INCREF(Py_None); - return Py_None; +#ifndef MS_WINDOWS + Py_DECREF(os1); +#endif + Py_RETURN_NONE; } #endif /* unsetenv */ From python-checkins at python.org Fri May 7 00:06:25 2010 From: python-checkins at python.org (victor.stinner) Date: Fri, 7 May 2010 00:06:25 +0200 (CEST) Subject: [Python-checkins] r80886 - python/branches/release31-maint Message-ID: <20100506220625.E38A6EE992@mail.python.org> Author: victor.stinner Date: Fri May 7 00:06:25 2010 New Revision: 80886 Log: Blocked revisions 80885 via svnmerge ........ r80885 | victor.stinner | 2010-05-07 00:05:07 +0200 (ven., 07 mai 2010) | 7 lines Issue #8603: Create a bytes version of os.environ for Unix Create os.environb mapping and os.getenvb() function, os.unsetenv() encodes str argument to the file system encoding with the surrogateescape error handler (instead of utf8/strict) and accepts bytes, and posix.environ keys and values are bytes. ........ Modified: python/branches/release31-maint/ (props changed) From python-checkins at python.org Fri May 7 00:09:03 2010 From: python-checkins at python.org (benjamin.peterson) Date: Fri, 7 May 2010 00:09:03 +0200 (CEST) Subject: [Python-checkins] r80887 - python/branches/py3k/Doc/library/os.rst Message-ID: <20100506220903.4EEB8EE9C9@mail.python.org> Author: benjamin.peterson Date: Fri May 7 00:09:03 2010 New Revision: 80887 Log: versionadded for environb Modified: python/branches/py3k/Doc/library/os.rst Modified: python/branches/py3k/Doc/library/os.rst ============================================================================== --- python/branches/py3k/Doc/library/os.rst (original) +++ python/branches/py3k/Doc/library/os.rst Fri May 7 00:09:03 2010 @@ -141,6 +141,8 @@ Availability: Unix. + .. versionadded:: 3.2 + .. function:: chdir(path) fchdir(fd) From ncoghlan at gmail.com Fri May 7 00:08:56 2010 From: ncoghlan at gmail.com (Nick Coghlan) Date: Fri, 07 May 2010 08:08:56 +1000 Subject: [Python-checkins] r80872 - python/trunk/Doc/whatsnew/2.7.rst In-Reply-To: <20100506172159.449E0EE9A2@mail.python.org> References: <20100506172159.449E0EE9A2@mail.python.org> Message-ID: <4BE33DF8.8090306@gmail.com> andrew.kuchling wrote: > @@ -1238,9 +1247,9 @@ > expected that the directory or zip contains a :file:`__main__.py`; > if it doesn't, some other :file:`__main__.py` might be imported from > a location later in ``sys.path``. This makes some of the machinery > - of :mod:`runpy` available to scripts that want to mimic the behaviour > - of Python's :option:`-m` switch. (Added by Nick Coghlan; > - :issue:`6816`.) > + of :mod:`runpy` available to scripts that want to mimic the way > + Python's :option:`-m` processes an explicit path name. > + (Added by Nick Coghlan; :issue:`6816`.) Getting closer... despite being in runpy, there's no command line option involved here, it's just a Python implementation of the path name processing used by the interpreter command line. i.e. "python foo" or "python foo.zip" or "python foo.pyc" or python "foo.py" As with run_module, it *isn't* the exact same code as the interpreter itself uses, since it can be used for module's other than __main__ (and doesn't reuse the existing __main__ module). Cheers, Nick. -- Nick Coghlan | ncoghlan at gmail.com | Brisbane, Australia --------------------------------------------------------------- From python-checkins at python.org Fri May 7 00:13:11 2010 From: python-checkins at python.org (benjamin.peterson) Date: Fri, 7 May 2010 00:13:11 +0200 (CEST) Subject: [Python-checkins] r80888 - python/branches/py3k/Doc/library/os.rst Message-ID: <20100506221311.6FBCCEE9C9@mail.python.org> Author: benjamin.peterson Date: Fri May 7 00:13:11 2010 New Revision: 80888 Log: spacing and another versionadded Modified: python/branches/py3k/Doc/library/os.rst Modified: python/branches/py3k/Doc/library/os.rst ============================================================================== --- python/branches/py3k/Doc/library/os.rst (original) +++ python/branches/py3k/Doc/library/os.rst Fri May 7 00:13:11 2010 @@ -279,8 +279,11 @@ Return the value of the environment variable *key* if it exists, or *default* if it doesn't. *key*, *default* and the result are bytes. + Availability: most flavors of Unix. + .. versionadded:: 3.2 + .. function:: putenv(key, value) From python-checkins at python.org Fri May 7 00:19:31 2010 From: python-checkins at python.org (victor.stinner) Date: Fri, 7 May 2010 00:19:31 +0200 (CEST) Subject: [Python-checkins] r80889 - python/branches/py3k/Lib/test/test_posix.py Message-ID: <20100506221931.06210EE98D@mail.python.org> Author: victor.stinner Date: Fri May 7 00:19:30 2010 New Revision: 80889 Log: Fix test_posix (regression introduced by r80885) Modified: python/branches/py3k/Lib/test/test_posix.py Modified: python/branches/py3k/Lib/test/test_posix.py ============================================================================== --- python/branches/py3k/Lib/test/test_posix.py (original) +++ python/branches/py3k/Lib/test/test_posix.py Fri May 7 00:19:30 2010 @@ -299,9 +299,13 @@ posix.lchflags(support.TESTFN, st.st_flags) def test_environ(self): + if os.name == "nt": + item_type = str + else: + item_type = bytes for k, v in posix.environ.items(): - self.assertEqual(type(k), str) - self.assertEqual(type(v), str) + self.assertEqual(type(k), item_type) + self.assertEqual(type(v), item_type) def test_getcwd_long_pathnames(self): if hasattr(posix, 'getcwd'): From python-checkins at python.org Fri May 7 00:23:58 2010 From: python-checkins at python.org (benjamin.peterson) Date: Fri, 7 May 2010 00:23:58 +0200 (CEST) Subject: [Python-checkins] r80890 - python/branches/py3k/Lib/test/test_os.py Message-ID: <20100506222358.316AEEE98D@mail.python.org> Author: benjamin.peterson Date: Fri May 7 00:23:58 2010 New Revision: 80890 Log: use concise skipping Modified: python/branches/py3k/Lib/test/test_os.py Modified: python/branches/py3k/Lib/test/test_os.py ============================================================================== --- python/branches/py3k/Lib/test/test_os.py (original) +++ python/branches/py3k/Lib/test/test_os.py Fri May 7 00:23:58 2010 @@ -449,7 +449,7 @@ try: value_bytes = value.encode(sys.getfilesystemencoding(), 'surrogateescape') except UnicodeEncodeError: - raise unittest.SkipTest("U+20AC character is not encodable to %s" % sys.getfilesystemencoding()) + raise self.skip("U+20AC character is not encodable to %s" % sys.getfilesystemencoding()) os.environ['unicode'] = value self.assertEquals(os.environ['unicode'], value) self.assertEquals(os.environb[b'unicode'], value_bytes) From python-checkins at python.org Fri May 7 00:25:42 2010 From: python-checkins at python.org (benjamin.peterson) Date: Fri, 7 May 2010 00:25:42 +0200 (CEST) Subject: [Python-checkins] r80891 - python/branches/py3k/Lib/test/test_os.py Message-ID: <20100506222542.998E5EE98D@mail.python.org> Author: benjamin.peterson Date: Fri May 7 00:25:42 2010 New Revision: 80891 Log: wrap long lines Modified: python/branches/py3k/Lib/test/test_os.py Modified: python/branches/py3k/Lib/test/test_os.py ============================================================================== --- python/branches/py3k/Lib/test/test_os.py (original) +++ python/branches/py3k/Lib/test/test_os.py Fri May 7 00:25:42 2010 @@ -447,9 +447,12 @@ # os.environ -> os.environb value = 'euro\u20ac' try: - value_bytes = value.encode(sys.getfilesystemencoding(), 'surrogateescape') + value_bytes = value.encode(sys.getfilesystemencoding(), + 'surrogateescape') except UnicodeEncodeError: - raise self.skip("U+20AC character is not encodable to %s" % sys.getfilesystemencoding()) + msg = "U+20AC character is not encodable to %s" % ( + sys.getfilesystemencoding(),) + self.skip(msg) os.environ['unicode'] = value self.assertEquals(os.environ['unicode'], value) self.assertEquals(os.environb[b'unicode'], value_bytes) From python-checkins at python.org Fri May 7 00:26:31 2010 From: python-checkins at python.org (benjamin.peterson) Date: Fri, 7 May 2010 00:26:31 +0200 (CEST) Subject: [Python-checkins] r80892 - python/branches/py3k/Lib/test/test_os.py Message-ID: <20100506222631.34A8EEE98D@mail.python.org> Author: benjamin.peterson Date: Fri May 7 00:26:31 2010 New Revision: 80892 Log: self.skip -> self.skipTest Modified: python/branches/py3k/Lib/test/test_os.py Modified: python/branches/py3k/Lib/test/test_os.py ============================================================================== --- python/branches/py3k/Lib/test/test_os.py (original) +++ python/branches/py3k/Lib/test/test_os.py Fri May 7 00:26:31 2010 @@ -452,7 +452,7 @@ except UnicodeEncodeError: msg = "U+20AC character is not encodable to %s" % ( sys.getfilesystemencoding(),) - self.skip(msg) + self.skipTest(msg) os.environ['unicode'] = value self.assertEquals(os.environ['unicode'], value) self.assertEquals(os.environb[b'unicode'], value_bytes) From python-checkins at python.org Fri May 7 00:29:54 2010 From: python-checkins at python.org (benjamin.peterson) Date: Fri, 7 May 2010 00:29:54 +0200 (CEST) Subject: [Python-checkins] r80893 - python/branches/py3k/Misc/NEWS Message-ID: <20100506222954.0CE62EE9C9@mail.python.org> Author: benjamin.peterson Date: Fri May 7 00:29:53 2010 New Revision: 80893 Log: rephrase Modified: python/branches/py3k/Misc/NEWS Modified: python/branches/py3k/Misc/NEWS ============================================================================== --- python/branches/py3k/Misc/NEWS (original) +++ python/branches/py3k/Misc/NEWS Fri May 7 00:29:53 2010 @@ -348,11 +348,10 @@ Library ------- -- Issue #8603: Create a bytes version of os.environ for Unix: create - os.environb mapping and os.getenvb() function, os.unsetenv() encodes str - argument to the file system encoding with the surrogateescape error handler - (instead of utf8/strict) and accepts bytes, and posix.environ keys and values - are bytes. +- Issue #8603: Support bytes environmental variables on Unix: Add os.environb + mapping and os.getenvb() function. os.unsetenv() encodes str argument to the + file system encoding with the surrogateescape error handler (instead of + utf8/strict) and accepts bytes. posix.environ keys and values are now bytes. - Issue #8573: asyncore _strerror() function might throw ValueError. From python-checkins at python.org Fri May 7 00:33:46 2010 From: python-checkins at python.org (benjamin.peterson) Date: Fri, 7 May 2010 00:33:46 +0200 (CEST) Subject: [Python-checkins] r80894 - python/trunk/Doc/library/os.path.rst Message-ID: <20100506223346.79579EEA9C@mail.python.org> Author: benjamin.peterson Date: Fri May 7 00:33:46 2010 New Revision: 80894 Log: Availability gets its own line Modified: python/trunk/Doc/library/os.path.rst Modified: python/trunk/Doc/library/os.path.rst ============================================================================== --- python/trunk/Doc/library/os.path.rst (original) +++ python/trunk/Doc/library/os.path.rst Fri May 7 00:33:46 2010 @@ -231,7 +231,9 @@ Return a relative filepath to *path* either from the current directory or from an optional *start* point. - *start* defaults to :attr:`os.curdir`. Availability: Windows, Unix. + *start* defaults to :attr:`os.curdir`. + + Availability: Windows, Unix. .. versionadded:: 2.6 @@ -240,12 +242,15 @@ Return ``True`` if both pathname arguments refer to the same file or directory (as indicated by device number and i-node number). Raise an exception if a - :func:`os.stat` call on either pathname fails. Availability: Unix. + :func:`os.stat` call on either pathname fails. + + Availability: Unix. .. function:: sameopenfile(fp1, fp2) Return ``True`` if the file descriptors *fp1* and *fp2* refer to the same file. + Availability: Unix. @@ -254,7 +259,9 @@ Return ``True`` if the stat tuples *stat1* and *stat2* refer to the same file. These structures may have been returned by :func:`fstat`, :func:`lstat`, or :func:`stat`. This function implements the underlying comparison used by - :func:`samefile` and :func:`sameopenfile`. Availability: Unix. + :func:`samefile` and :func:`sameopenfile`. + + Availability: Unix. .. function:: split(path) @@ -296,7 +303,9 @@ Split the pathname *path* into a pair ``(unc, rest)`` so that *unc* is the UNC mount point (such as ``r'\\host\mount'``), if present, and *rest* the rest of the path (such as ``r'\path\file.ext'``). For paths containing drive letters, - *unc* will always be the empty string. Availability: Windows. + *unc* will always be the empty string. + + Availability: Windows. .. function:: walk(path, visit, arg) From python-checkins at python.org Fri May 7 00:46:50 2010 From: python-checkins at python.org (giampaolo.rodola) Date: Fri, 7 May 2010 00:46:50 +0200 (CEST) Subject: [Python-checkins] r80895 - python/branches/asyncore-tests-issue8490/Lib/test/test_asyncore.py Message-ID: <20100506224650.4D7E2EE983@mail.python.org> Author: giampaolo.rodola Date: Fri May 7 00:46:50 2010 New Revision: 80895 Log: workarounds to make tests pass on solaris: disabled handle_expt test and connect attribute test Modified: python/branches/asyncore-tests-issue8490/Lib/test/test_asyncore.py Modified: python/branches/asyncore-tests-issue8490/Lib/test/test_asyncore.py ============================================================================== --- python/branches/asyncore-tests-issue8490/Lib/test/test_asyncore.py (original) +++ python/branches/asyncore-tests-issue8490/Lib/test/test_asyncore.py Fri May 7 00:46:50 2010 @@ -552,6 +552,7 @@ client = TestClient(server.address) self.loop_waiting_for_flag(client) + @unittest.skipIf(sys.platform.startswith("solaris"), "OOB support is broken") def test_handle_expt(self): # Make sure handle_expt is called on OOB data received. # Note: this might fail on some platforms as OOB data is @@ -573,7 +574,7 @@ def test_handle_error(self): class TestClient(BaseClient): - def handle_connect(self): + def handle_write(self): 1.0 / 0 def handle_error(self): self.flag = True @@ -595,7 +596,10 @@ # we start disconnected self.assertFalse(server.connected) self.assertTrue(server.accepting) - self.assertFalse(client.connected) + # solaris seems to connect() immediately even without starting + # the poller + if not sys.platform.startswith("solaris"): + self.assertFalse(client.connected) self.assertFalse(client.accepting) # execute some loops so that client connects to server From python-checkins at python.org Fri May 7 00:49:29 2010 From: python-checkins at python.org (benjamin.peterson) Date: Fri, 7 May 2010 00:49:29 +0200 (CEST) Subject: [Python-checkins] r80896 - python/trunk/Doc/library/os.rst Message-ID: <20100506224929.13237EE992@mail.python.org> Author: benjamin.peterson Date: Fri May 7 00:49:28 2010 New Revision: 80896 Log: ensure that availability information is on its own line at the end of the function docs Modified: python/trunk/Doc/library/os.rst Modified: python/trunk/Doc/library/os.rst ============================================================================== --- python/trunk/Doc/library/os.rst (original) +++ python/trunk/Doc/library/os.rst Fri May 7 00:49:28 2010 @@ -32,6 +32,9 @@ * If not separately noted, all functions that claim "Availability: Unix" are supported on Mac OS X, which builds on a Unix core. +.. Availability notes get their own line and occur at the end of the function +.. documentation. + .. note:: All functions in this module raise :exc:`OSError` in the case of invalid or @@ -111,33 +114,40 @@ .. function:: ctermid() Return the filename corresponding to the controlling terminal of the process. + Availability: Unix. .. function:: getegid() Return the effective group id of the current process. This corresponds to the - "set id" bit on the file being executed in the current process. Availability: - Unix. + "set id" bit on the file being executed in the current process. + + Availability: Unix. .. function:: geteuid() .. index:: single: user; effective id - Return the current process's effective user id. Availability: Unix. + Return the current process's effective user id. + + Availability: Unix. .. function:: getgid() .. index:: single: process; group - Return the real group id of the current process. Availability: Unix. + Return the real group id of the current process. + + Availability: Unix. .. function:: getgroups() Return list of supplemental group ids associated with the current process. + Availability: Unix. @@ -145,7 +155,9 @@ Call the system initgroups() to initialize the group access list with all of the groups of which the specified username is a member, plus the specified - group id. Availability: Unix. + group id. + + Availability: Unix. .. versionadded:: 2.7 @@ -156,13 +168,17 @@ process. For most purposes, it is more useful to use the environment variable :envvar:`LOGNAME` to find out who the user is, or ``pwd.getpwuid(os.getuid())[0]`` to get the login name of the currently - effective user id. Availability: Unix. + effective user id. + + Availability: Unix. .. function:: getpgid(pid) Return the process group id of the process with process id *pid*. If *pid* is 0, - the process group id of the current process is returned. Availability: Unix. + the process group id of the current process is returned. + + Availability: Unix. .. versionadded:: 2.3 @@ -171,27 +187,35 @@ .. index:: single: process; group - Return the id of the current process group. Availability: Unix. + Return the id of the current process group. + + Availability: Unix. .. function:: getpid() .. index:: single: process; id - Return the current process id. Availability: Unix, Windows. + Return the current process id. + + Availability: Unix, Windows. .. function:: getppid() .. index:: single: process; id of parent - Return the parent's process id. Availability: Unix. + Return the parent's process id. + + Availability: Unix. .. function:: getresuid() Return a tuple (ruid, euid, suid) denoting the current process's - real, effective, and saved user ids. Availability: Unix. + real, effective, and saved user ids. + + Availability: Unix. .. versionadded:: 2.7 @@ -199,7 +223,9 @@ .. function:: getresgid() Return a tuple (rgid, egid, sgid) denoting the current process's - real, effective, and saved user ids. Availability: Unix. + real, effective, and saved user ids. + + Availability: Unix. .. versionadded:: 2.7 @@ -208,14 +234,17 @@ .. index:: single: user; id - Return the current process's user id. Availability: Unix. + Return the current process's user id. + + Availability: Unix. .. function:: getenv(varname[, value]) Return the value of the environment variable *varname* if it exists, or *value* - if it doesn't. *value* defaults to ``None``. Availability: most flavors of - Unix, Windows. + if it doesn't. *value* defaults to ``None``. + + Availability: most flavors of Unix, Windows. .. function:: putenv(varname, value) @@ -224,8 +253,9 @@ Set the environment variable named *varname* to the string *value*. Such changes to the environment affect subprocesses started with :func:`os.system`, - :func:`popen` or :func:`fork` and :func:`execv`. Availability: most flavors of - Unix, Windows. + :func:`popen` or :func:`fork` and :func:`execv`. + + Availability: most flavors of Unix, Windows. .. note:: @@ -240,17 +270,23 @@ .. function:: setegid(egid) - Set the current process's effective group id. Availability: Unix. + Set the current process's effective group id. + + Availability: Unix. .. function:: seteuid(euid) - Set the current process's effective user id. Availability: Unix. + Set the current process's effective user id. + + Availability: Unix. .. function:: setgid(gid) - Set the current process' group id. Availability: Unix. + Set the current process' group id. + + Availability: Unix. .. function:: setgroups(groups) @@ -258,6 +294,7 @@ Set the list of supplemental group ids associated with the current process to *groups*. *groups* must be a sequence, and each element must be an integer identifying a group. This operation is typically available only to the superuser. + Availability: Unix. .. versionadded:: 2.2 @@ -267,6 +304,7 @@ Call the system call :cfunc:`setpgrp` or :cfunc:`setpgrp(0, 0)` depending on which version is implemented (if any). See the Unix manual for the semantics. + Availability: Unix. @@ -274,17 +312,22 @@ Call the system call :cfunc:`setpgid` to set the process group id of the process with id *pid* to the process group with id *pgrp*. See the Unix manual - for the semantics. Availability: Unix. + for the semantics. + + Availability: Unix. .. function:: setregid(rgid, egid) - Set the current process's real and effective group ids. Availability: Unix. + Set the current process's real and effective group ids. + + Availability: Unix. .. function:: setresgid(rgid, egid, sgid) Set the current process's real, effective, and saved group ids. + Availability: Unix. .. versionadded:: 2.7 @@ -293,6 +336,7 @@ .. function:: setresuid(ruid, euid, suid) Set the current process's real, effective, and saved user ids. + Availibility: Unix. .. versionadded:: 2.7 @@ -300,12 +344,15 @@ .. function:: setreuid(ruid, euid) - Set the current process's real and effective user ids. Availability: Unix. + Set the current process's real and effective user ids. + + Availability: Unix. .. function:: getsid(pid) Call the system call :cfunc:`getsid`. See the Unix manual for the semantics. + Availability: Unix. .. versionadded:: 2.4 @@ -314,6 +361,7 @@ .. function:: setsid() Call the system call :cfunc:`setsid`. See the Unix manual for the semantics. + Availability: Unix. @@ -321,7 +369,9 @@ .. index:: single: user; id, setting - Set the current process's user id. Availability: Unix. + Set the current process's user id. + + Availability: Unix. .. placed in this section since it relates to errno.... a little weak @@ -329,13 +379,16 @@ Return the error message corresponding to the error code in *code*. On platforms where :cfunc:`strerror` returns ``NULL`` when given an unknown - error number, :exc:`ValueError` is raised. Availability: Unix, Windows. + error number, :exc:`ValueError` is raised. + + Availability: Unix, Windows. .. function:: umask(mask) - Set the current numeric umask and return the previous umask. Availability: - Unix, Windows. + Set the current numeric umask and return the previous umask. + + Availability: Unix, Windows. .. function:: uname() @@ -349,8 +402,9 @@ machine)``. Some systems truncate the nodename to 8 characters or to the leading component; a better way to get the hostname is :func:`socket.gethostname` or even - ``socket.gethostbyaddr(socket.gethostname())``. Availability: recent flavors of - Unix. + ``socket.gethostbyaddr(socket.gethostname())``. + + Availability: recent flavors of Unix. .. function:: unsetenv(varname) @@ -359,13 +413,15 @@ Unset (delete) the environment variable named *varname*. Such changes to the environment affect subprocesses started with :func:`os.system`, :func:`popen` or - :func:`fork` and :func:`execv`. Availability: most flavors of Unix, Windows. + :func:`fork` and :func:`execv`. When :func:`unsetenv` is supported, deletion of items in ``os.environ`` is automatically translated into a corresponding call to :func:`unsetenv`; however, calls to :func:`unsetenv` don't update ``os.environ``, so it is actually preferable to delete items of ``os.environ``. + Availability: most flavors of Unix, Windows. + .. _os-newstreams: @@ -381,7 +437,9 @@ Return an open file object connected to the file descriptor *fd*. The *mode* and *bufsize* arguments have the same meaning as the corresponding arguments to - the built-in :func:`open` function. Availability: Unix, Windows. + the built-in :func:`open` function. + + Availability: Unix, Windows. .. versionchanged:: 2.3 When specified, the *mode* argument must now start with one of the letters @@ -402,7 +460,9 @@ status of the command (encoded in the format specified for :func:`wait`) is available as the return value of the :meth:`~file.close` method of the file object, except that when the exit status is zero (termination without errors), ``None`` - is returned. Availability: Unix, Windows. + is returned. + + Availability: Unix, Windows. .. deprecated:: 2.6 This function is obsolete. Use the :mod:`subprocess` module. Check @@ -419,8 +479,9 @@ Return a new file object opened in update mode (``w+b``). The file has no directory entries associated with it and will be automatically deleted once - there are no file descriptors for the file. Availability: Unix, - Windows. + there are no file descriptors for the file. + + Availability: Unix, Windows. There are a number of different :func:`popen\*` functions that provide slightly different ways to create subprocesses. @@ -520,7 +581,9 @@ .. function:: close(fd) - Close file descriptor *fd*. Availability: Unix, Windows. + Close file descriptor *fd*. + + Availability: Unix, Windows. .. note:: @@ -533,7 +596,7 @@ .. function:: closerange(fd_low, fd_high) Close all file descriptors from *fd_low* (inclusive) to *fd_high* (exclusive), - ignoring errors. Availability: Unix, Windows. Equivalent to:: + ignoring errors. Equivalent to:: for fd in xrange(fd_low, fd_high): try: @@ -541,25 +604,31 @@ except OSError: pass + Availability: Unix, Windows. + .. versionadded:: 2.6 .. function:: dup(fd) - Return a duplicate of file descriptor *fd*. Availability: Unix, - Windows. + Return a duplicate of file descriptor *fd*. + + Availability: Unix, Windows. .. function:: dup2(fd, fd2) Duplicate file descriptor *fd* to *fd2*, closing the latter first if necessary. + Availability: Unix, Windows. .. function:: fchmod(fd, mode) Change the mode of the file given by *fd* to the numeric *mode*. See the docs - for :func:`chmod` for possible values of *mode*. Availability: Unix. + for :func:`chmod` for possible values of *mode*. + + Availability: Unix. .. versionadded:: 2.6 @@ -568,6 +637,7 @@ Change the owner and group id of the file given by *fd* to the numeric *uid* and *gid*. To leave one of the ids unchanged, set it to -1. + Availability: Unix. .. versionadded:: 2.6 @@ -576,7 +646,9 @@ .. function:: fdatasync(fd) Force write of file with filedescriptor *fd* to disk. Does not force update of - metadata. Availability: Unix. + metadata. + + Availability: Unix. .. note:: This function is not available on MacOS. @@ -591,24 +663,28 @@ additional names as well. The names known to the host operating system are given in the ``pathconf_names`` dictionary. For configuration variables not included in that mapping, passing an integer for *name* is also accepted. - Availability: Unix. If *name* is a string and is not known, :exc:`ValueError` is raised. If a specific value for *name* is not supported by the host system, even if it is included in ``pathconf_names``, an :exc:`OSError` is raised with :const:`errno.EINVAL` for the error number. + Availability: Unix. + .. function:: fstat(fd) - Return status for file descriptor *fd*, like :func:`stat`. Availability: - Unix, Windows. + Return status for file descriptor *fd*, like :func:`stat`. + + Availability: Unix, Windows. .. function:: fstatvfs(fd) Return information about the filesystem containing the file associated with file - descriptor *fd*, like :func:`statvfs`. Availability: Unix. + descriptor *fd*, like :func:`statvfs`. + + Availability: Unix. .. function:: fsync(fd) @@ -618,20 +694,25 @@ If you're starting with a Python file object *f*, first do ``f.flush()``, and then do ``os.fsync(f.fileno())``, to ensure that all internal buffers associated - with *f* are written to disk. Availability: Unix, and Windows - starting in 2.2.3. + with *f* are written to disk. + + Availability: Unix, and Windows starting in 2.2.3. .. function:: ftruncate(fd, length) Truncate the file corresponding to file descriptor *fd*, so that it is at most - *length* bytes in size. Availability: Unix. + *length* bytes in size. + + Availability: Unix. .. function:: isatty(fd) Return ``True`` if the file descriptor *fd* is open and connected to a - tty(-like) device, else ``False``. Availability: Unix. + tty(-like) device, else ``False``. + + Availability: Unix. .. function:: lseek(fd, pos, how) @@ -640,7 +721,9 @@ by *how*: :const:`SEEK_SET` or ``0`` to set the position relative to the beginning of the file; :const:`SEEK_CUR` or ``1`` to set it relative to the current position; :const:`os.SEEK_END` or ``2`` to set it relative to the end of - the file. Availability: Unix, Windows. + the file. + + Availability: Unix, Windows. .. data:: SEEK_SET @@ -648,7 +731,9 @@ SEEK_END Parameters to the :func:`lseek` function. Their values are 0, 1, and 2, - respectively. Availability: Windows, Unix. + respectively. + + Availability: Windows, Unix. .. versionadded:: 2.5 @@ -658,18 +743,20 @@ Open the file *file* and set various flags according to *flags* and possibly its mode according to *mode*. The default *mode* is ``0777`` (octal), and the current umask value is first masked out. Return the file descriptor for the - newly opened file. Availability: Unix, Windows. + newly opened file. For a description of the flag and mode values, see the C run-time documentation; flag constants (like :const:`O_RDONLY` and :const:`O_WRONLY`) are defined in this module too (see :ref:`open-constants`). In particular, on Windows adding :const:`O_BINARY` is needed to open files in binary mode. + Availability: Unix, Windows. + .. note:: This function is intended for low-level I/O. For normal usage, use the built-in function :func:`open`, which returns a "file object" with - :meth:`~file.read` and :meth:`~file.write` methods (and many more). To + :meth:`~file.read` and :meth:`~file.wprite` methods (and many more). To wrap a file descriptor in a "file object", use :func:`fdopen`. @@ -679,21 +766,26 @@ Open a new pseudo-terminal pair. Return a pair of file descriptors ``(master, slave)`` for the pty and the tty, respectively. For a (slightly) more portable - approach, use the :mod:`pty` module. Availability: some flavors of - Unix. + approach, use the :mod:`pty` module. + + Availability: some flavors of Unix. .. function:: pipe() Create a pipe. Return a pair of file descriptors ``(r, w)`` usable for reading - and writing, respectively. Availability: Unix, Windows. + and writing, respectively. + + Availability: Unix, Windows. .. function:: read(fd, n) Read at most *n* bytes from file descriptor *fd*. Return a string containing the bytes read. If the end of the file referred to by *fd* has been reached, an - empty string is returned. Availability: Unix, Windows. + empty string is returned. + + Availability: Unix, Windows. .. note:: @@ -707,26 +799,34 @@ .. function:: tcgetpgrp(fd) Return the process group associated with the terminal given by *fd* (an open - file descriptor as returned by :func:`os.open`). Availability: Unix. + file descriptor as returned by :func:`os.open`). + + Availability: Unix. .. function:: tcsetpgrp(fd, pg) Set the process group associated with the terminal given by *fd* (an open file - descriptor as returned by :func:`os.open`) to *pg*. Availability: Unix. + descriptor as returned by :func:`os.open`) to *pg*. + + Availability: Unix. .. function:: ttyname(fd) Return a string which specifies the terminal device associated with file descriptor *fd*. If *fd* is not associated with a terminal device, an - exception is raised. Availability: Unix. + exception is raised. + + Availability: Unix. .. function:: write(fd, str) Write the string *str* to file descriptor *fd*. Return the number of bytes - actually written. Availability: Unix, Windows. + actually written. + + Availability: Unix, Windows. .. note:: @@ -807,7 +907,9 @@ can be the inclusive OR of one or more of :const:`R_OK`, :const:`W_OK`, and :const:`X_OK` to test permissions. Return :const:`True` if access is allowed, :const:`False` if not. See the Unix man page :manpage:`access(2)` for more - information. Availability: Unix, Windows. + information. + + Availability: Unix, Windows. .. note:: @@ -851,28 +953,33 @@ .. index:: single: directory; changing - Change the current working directory to *path*. Availability: Unix, - Windows. + Change the current working directory to *path*. + + Availability: Unix, Windows. .. function:: fchdir(fd) Change the current working directory to the directory represented by the file descriptor *fd*. The descriptor must refer to an opened directory, not an open - file. Availability: Unix. + file. + + Availability: Unix. .. versionadded:: 2.3 .. function:: getcwd() - Return a string representing the current working directory. Availability: - Unix, Windows. + Return a string representing the current working directory. + + Availability: Unix, Windows. .. function:: getcwdu() Return a Unicode object representing the current working directory. + Availability: Unix, Windows. .. versionadded:: 2.3 @@ -947,13 +1054,17 @@ .. function:: chown(path, uid, gid) Change the owner and group id of *path* to the numeric *uid* and *gid*. To leave - one of the ids unchanged, set it to -1. Availability: Unix. + one of the ids unchanged, set it to -1. + + Availability: Unix. .. function:: lchflags(path, flags) Set the flags of *path* to the numeric *flags*, like :func:`chflags`, but do not - follow symbolic links. Availability: Unix. + follow symbolic links. + + Availability: Unix. .. versionadded:: 2.6 @@ -962,7 +1073,9 @@ Change the mode of *path* to the numeric *mode*. If path is a symlink, this affects the symlink rather than the target. See the docs for :func:`chmod` - for possible values of *mode*. Availability: Unix. + for possible values of *mode*. + + Availability: Unix. .. versionadded:: 2.6 @@ -970,15 +1083,18 @@ .. function:: lchown(path, uid, gid) Change the owner and group id of *path* to the numeric *uid* and *gid*. This - function will not follow symbolic links. Availability: Unix. + function will not follow symbolic links. + + Availability: Unix. .. versionadded:: 2.3 .. function:: link(source, link_name) - Create a hard link pointing to *source* named *link_name*. Availability: - Unix. + Create a hard link pointing to *source* named *link_name*. + + Availability: Unix. .. function:: listdir(path) @@ -986,7 +1102,9 @@ Return a list containing the names of the entries in the directory given by *path*. The list is in arbitrary order. It does not include the special entries ``'.'`` and ``'..'`` even if they are present in the - directory. Availability: Unix, Windows. + directory. + + Availability: Unix, Windows. .. versionchanged:: 2.3 On Windows NT/2k/XP and Unix, if *path* is a Unicode object, the result will be @@ -1005,7 +1123,9 @@ Create a FIFO (a named pipe) named *path* with numeric mode *mode*. The default *mode* is ``0666`` (octal). The current umask value is first masked out from - the mode. Availability: Unix. + the mode. + + Availability: Unix. FIFOs are pipes that can be accessed like regular files. FIFOs exist until they are deleted (for example with :func:`os.unlink`). Generally, FIFOs are used as @@ -1055,11 +1175,13 @@ Create a directory named *path* with numeric mode *mode*. The default *mode* is ``0777`` (octal). On some systems, *mode* is ignored. Where it is used, the - current umask value is first masked out. Availability: Unix, Windows. + current umask value is first masked out. It is also possible to create temporary directories; see the :mod:`tempfile` module's :func:`tempfile.mkdtemp` function. + Availability: Unix, Windows. + .. function:: makedirs(path[, mode]) @@ -1093,13 +1215,14 @@ additional names as well. The names known to the host operating system are given in the ``pathconf_names`` dictionary. For configuration variables not included in that mapping, passing an integer for *name* is also accepted. - Availability: Unix. If *name* is a string and is not known, :exc:`ValueError` is raised. If a specific value for *name* is not supported by the host system, even if it is included in ``pathconf_names``, an :exc:`OSError` is raised with :const:`errno.EINVAL` for the error number. + Availability: Unix. + .. data:: pathconf_names @@ -1129,8 +1252,9 @@ the :func:`unlink` function documented below. On Windows, attempting to remove a file that is in use causes an exception to be raised; on Unix, the directory entry is removed but the storage allocated to the file is not made - available until the original file is no longer in use. Availability: Unix, - Windows. + available until the original file is no longer in use. + + Availability: Unix, Windows. .. function:: removedirs(path) @@ -1158,7 +1282,9 @@ the renaming will be an atomic operation (this is a POSIX requirement). On Windows, if *dst* already exists, :exc:`OSError` will be raised even if it is a file; there may be no way to implement an atomic rename when *dst* names an - existing file. Availability: Unix, Windows. + existing file. + + Availability: Unix, Windows. .. function:: renames(old, new) @@ -1180,8 +1306,9 @@ Remove (delete) the directory *path*. Only works when the directory is empty, otherwise, :exc:`OSError` is raised. In order to remove whole - directory trees, :func:`shutil.rmtree` can be used. Availability: Unix, - Windows. + directory trees, :func:`shutil.rmtree` can be used. + + Availability: Unix, Windows. .. function:: stat(path) @@ -1287,7 +1414,7 @@ correspond to the members of the :ctype:`statvfs` structure, namely: :attr:`f_bsize`, :attr:`f_frsize`, :attr:`f_blocks`, :attr:`f_bfree`, :attr:`f_bavail`, :attr:`f_files`, :attr:`f_ffree`, :attr:`f_favail`, - :attr:`f_flag`, :attr:`f_namemax`. Availability: Unix. + :attr:`f_flag`, :attr:`f_namemax`. .. index:: module: statvfs @@ -1298,14 +1425,17 @@ this remains useful when writing code that needs to work with versions of Python that don't support accessing the fields as attributes. + Availability: Unix. + .. versionchanged:: 2.2 Added access to values as attributes of the returned object. .. function:: symlink(source, link_name) - Create a symbolic link pointing to *source* named *link_name*. Availability: - Unix. + Create a symbolic link pointing to *source* named *link_name*. + + Availability: Unix. .. function:: tempnam([dir[, prefix]]) @@ -1359,7 +1489,9 @@ Remove (delete) the file *path*. This is the same function as :func:`remove`; the :func:`unlink` name is its traditional Unix - name. Availability: Unix, Windows. + name. + + Availability: Unix, Windows. .. function:: utime(path, times) @@ -1491,6 +1623,7 @@ behavior is to produce a core dump; on Windows, the process immediately returns an exit code of ``3``. Be aware that programs which use :func:`signal.signal` to register a handler for :const:`SIGABRT` will behave differently. + Availability: Unix, Windows. @@ -1546,7 +1679,9 @@ .. function:: _exit(n) Exit to the system with status *n*, without calling cleanup handlers, flushing - stdio buffers, etc. Availability: Unix, Windows. + stdio buffers, etc. + + Availability: Unix, Windows. .. note:: @@ -1566,7 +1701,9 @@ .. data:: EX_OK - Exit code that means no error occurred. Availability: Unix. + Exit code that means no error occurred. + + Availability: Unix. .. versionadded:: 2.3 @@ -1574,14 +1711,18 @@ .. data:: EX_USAGE Exit code that means the command was used incorrectly, such as when the wrong - number of arguments are given. Availability: Unix. + number of arguments are given. + + Availability: Unix. .. versionadded:: 2.3 .. data:: EX_DATAERR - Exit code that means the input data was incorrect. Availability: Unix. + Exit code that means the input data was incorrect. + + Availability: Unix. .. versionadded:: 2.3 @@ -1589,6 +1730,7 @@ .. data:: EX_NOINPUT Exit code that means an input file did not exist or was not readable. + Availability: Unix. .. versionadded:: 2.3 @@ -1596,30 +1738,36 @@ .. data:: EX_NOUSER - Exit code that means a specified user did not exist. Availability: Unix. + Exit code that means a specified user did not exist. + + Availability: Unix. .. versionadded:: 2.3 .. data:: EX_NOHOST - Exit code that means a specified host did not exist. Availability: Unix. + Exit code that means a specified host did not exist. + + Availability: Unix. .. versionadded:: 2.3 .. data:: EX_UNAVAILABLE - Exit code that means that a required service is unavailable. Availability: - Unix. + Exit code that means that a required service is unavailable. + + Availability: Unix. .. versionadded:: 2.3 .. data:: EX_SOFTWARE - Exit code that means an internal software error was detected. Availability: - Unix. + Exit code that means an internal software error was detected. + + Availability: Unix. .. versionadded:: 2.3 @@ -1627,7 +1775,9 @@ .. data:: EX_OSERR Exit code that means an operating system error was detected, such as the - inability to fork or create a pipe. Availability: Unix. + inability to fork or create a pipe. + + Availability: Unix. .. versionadded:: 2.3 @@ -1635,7 +1785,9 @@ .. data:: EX_OSFILE Exit code that means some system file did not exist, could not be opened, or had - some other kind of error. Availability: Unix. + some other kind of error. + + Availability: Unix. .. versionadded:: 2.3 @@ -1643,6 +1795,7 @@ .. data:: EX_CANTCREAT Exit code that means a user specified output file could not be created. + Availability: Unix. .. versionadded:: 2.3 @@ -1651,6 +1804,7 @@ .. data:: EX_IOERR Exit code that means that an error occurred while doing I/O on some file. + Availability: Unix. .. versionadded:: 2.3 @@ -1660,7 +1814,9 @@ Exit code that means a temporary failure occurred. This indicates something that may not really be an error, such as a network connection that couldn't be - made during a retryable operation. Availability: Unix. + made during a retryable operation. + + Availability: Unix. .. versionadded:: 2.3 @@ -1668,7 +1824,9 @@ .. data:: EX_PROTOCOL Exit code that means that a protocol exchange was illegal, invalid, or not - understood. Availability: Unix. + understood. + + Availability: Unix. .. versionadded:: 2.3 @@ -1676,7 +1834,9 @@ .. data:: EX_NOPERM Exit code that means that there were insufficient permissions to perform the - operation (but not intended for file system problems). Availability: Unix. + operation (but not intended for file system problems). + + Availability: Unix. .. versionadded:: 2.3 @@ -1684,6 +1844,7 @@ .. data:: EX_CONFIG Exit code that means that some kind of configuration error occurred. + Availability: Unix. .. versionadded:: 2.3 @@ -1691,8 +1852,9 @@ .. data:: EX_NOTFOUND - Exit code that means something like "an entry was not found". Availability: - Unix. + Exit code that means something like "an entry was not found". + + Availability: Unix. .. versionadded:: 2.3 @@ -1715,6 +1877,7 @@ new child's process id in the parent, and *fd* is the file descriptor of the master end of the pseudo-terminal. For a more portable approach, use the :mod:`pty` module. If an error occurs :exc:`OSError` is raised. + Availability: some flavors of Unix. @@ -1744,7 +1907,9 @@ single: process; killing single: process; signalling - Send the signal *sig* to the process group *pgid*. Availability: Unix. + Send the signal *sig* to the process group *pgid*. + + Availability: Unix. .. versionadded:: 2.3 @@ -1752,13 +1917,16 @@ .. function:: nice(increment) Add *increment* to the process's "niceness". Return the new niceness. + Availability: Unix. .. function:: plock(op) Lock program segments into memory. The value of *op* (defined in - ````) determines which segments are locked. Availability: Unix. + ````) determines which segments are locked. + + Availability: Unix. .. function:: popen(...) @@ -1842,7 +2010,9 @@ Possible values for the *mode* parameter to the :func:`spawn\*` family of functions. If either of these values is given, the :func:`spawn\*` functions will return as soon as the new process has been created, with the process id as - the return value. Availability: Unix, Windows. + the return value. + + Availability: Unix, Windows. .. versionadded:: 1.6 @@ -1853,7 +2023,9 @@ functions. If this is given as *mode*, the :func:`spawn\*` functions will not return until the new process has run to completion and will return the exit code of the process the run is successful, or ``-signal`` if a signal kills the - process. Availability: Unix, Windows. + process. + + Availability: Unix, Windows. .. versionadded:: 1.6 @@ -1866,6 +2038,7 @@ is similar to :const:`P_NOWAIT`, but the new process is detached from the console of the calling process. If :const:`P_OVERLAY` is used, the current process will be replaced; the :func:`spawn\*` function will not return. + Availability: Windows. .. versionadded:: 1.6 @@ -1891,7 +2064,9 @@ directory. If you want to use an absolute path, make sure the first character is not a slash (``'/'``); the underlying Win32 :cfunc:`ShellExecute` function doesn't work if it is. Use the :func:`os.path.normpath` function to ensure that - the path is properly encoded for Win32. Availability: Windows. + the path is properly encoded for Win32. + + Availability: Windows. .. versionadded:: 2.0 @@ -1918,22 +2093,24 @@ the command run; on systems using a non-native shell, consult your shell documentation. - Availability: Unix, Windows. - The :mod:`subprocess` module provides more powerful facilities for spawning new processes and retrieving their results; using that module is preferable to using this function. Use the :mod:`subprocess` module. Check especially the :ref:`subprocess-replacements` section. + Availability: Unix, Windows. + .. function:: times() - Return a 5-tuple of floating point numbers indicating accumulated (processor or - other) times, in seconds. The items are: user time, system time, children's - user time, children's system time, and elapsed real time since a fixed point in - the past, in that order. See the Unix manual page :manpage:`times(2)` or the - corresponding Windows Platform API documentation. Availability: Unix, - Windows. On Windows, only the first two items are filled, the others are zero. + Return a 5-tuple of floating point numbers indicating accumulated (processor + or other) times, in seconds. The items are: user time, system time, + children's user time, children's system time, and elapsed real time since a + fixed point in the past, in that order. See the Unix manual page + :manpage:`times(2)` or the corresponding Windows Platform API documentation. + On Windows, only the first two items are filled, the others are zero. + + Availability: Unix, Windows .. function:: wait() @@ -1942,7 +2119,9 @@ and exit status indication: a 16-bit number, whose low byte is the signal number that killed the process, and whose high byte is the exit status (if the signal number is zero); the high bit of the low byte is set if a core file was - produced. Availability: Unix. + produced. + + Availability: Unix. .. function:: waitpid(pid, options) @@ -1980,6 +2159,7 @@ resource usage information is returned. Refer to :mod:`resource`.\ :func:`getrusage` for details on resource usage information. The option argument is the same as that provided to :func:`waitpid` and :func:`wait4`. + Availability: Unix. .. versionadded:: 2.5 @@ -1991,7 +2171,9 @@ process id, exit status indication, and resource usage information is returned. Refer to :mod:`resource`.\ :func:`getrusage` for details on resource usage information. The arguments to :func:`wait4` are the same as those provided to - :func:`waitpid`. Availability: Unix. + :func:`waitpid`. + + Availability: Unix. .. versionadded:: 2.5 @@ -2000,14 +2182,16 @@ The option for :func:`waitpid` to return immediately if no child process status is available immediately. The function returns ``(0, 0)`` in this case. + Availability: Unix. .. data:: WCONTINUED This option causes child processes to be reported if they have been continued - from a job control stop since their status was last reported. Availability: Some - Unix systems. + from a job control stop since their status was last reported. + + Availability: Some Unix systems. .. versionadded:: 2.3 @@ -2015,8 +2199,9 @@ .. data:: WUNTRACED This option causes child processes to be reported if they have been stopped but - their current state has not been reported since they were stopped. Availability: - Unix. + their current state has not been reported since they were stopped. + + Availability: Unix. .. versionadded:: 2.3 @@ -2028,7 +2213,9 @@ .. function:: WCOREDUMP(status) Return ``True`` if a core dump was generated for the process, otherwise - return ``False``. Availability: Unix. + return ``False``. + + Availability: Unix. .. versionadded:: 2.3 @@ -2036,7 +2223,9 @@ .. function:: WIFCONTINUED(status) Return ``True`` if the process has been continued from a job control stop, - otherwise return ``False``. Availability: Unix. + otherwise return ``False``. + + Availability: Unix. .. versionadded:: 2.3 @@ -2044,36 +2233,47 @@ .. function:: WIFSTOPPED(status) Return ``True`` if the process has been stopped, otherwise return - ``False``. Availability: Unix. + ``False``. + + Availability: Unix. .. function:: WIFSIGNALED(status) Return ``True`` if the process exited due to a signal, otherwise return - ``False``. Availability: Unix. + ``False``. + + Availability: Unix. .. function:: WIFEXITED(status) Return ``True`` if the process exited using the :manpage:`exit(2)` system call, - otherwise return ``False``. Availability: Unix. + otherwise return ``False``. + + Availability: Unix. .. function:: WEXITSTATUS(status) If ``WIFEXITED(status)`` is true, return the integer parameter to the :manpage:`exit(2)` system call. Otherwise, the return value is meaningless. + Availability: Unix. .. function:: WSTOPSIG(status) - Return the signal which caused the process to stop. Availability: Unix. + Return the signal which caused the process to stop. + + Availability: Unix. .. function:: WTERMSIG(status) - Return the signal which caused the process to exit. Availability: Unix. + Return the signal which caused the process to exit. + + Availability: Unix. .. _os-path: @@ -2090,8 +2290,7 @@ Unix 95, Unix 98, and others). Some platforms define additional names as well. The names known to the host operating system are given as the keys of the ``confstr_names`` dictionary. For configuration variables not included in that - mapping, passing an integer for *name* is also accepted. Availability: - Unix. + mapping, passing an integer for *name* is also accepted. If the configuration value specified by *name* isn't defined, ``None`` is returned. @@ -2101,19 +2300,25 @@ included in ``confstr_names``, an :exc:`OSError` is raised with :const:`errno.EINVAL` for the error number. + Availability: Unix + .. data:: confstr_names Dictionary mapping names accepted by :func:`confstr` to the integer values defined for those names by the host operating system. This can be used to - determine the set of names known to the system. Availability: Unix. + determine the set of names known to the system. + + Availability: Unix. .. function:: getloadavg() Return the number of processes in the system run queue averaged over the last 1, 5, and 15 minutes or raises :exc:`OSError` if the load average was - unobtainable. Availability: Unix. + unobtainable. + + Availability: Unix. .. versionadded:: 2.3 @@ -2124,6 +2329,7 @@ specified by *name* isn't defined, ``-1`` is returned. The comments regarding the *name* parameter for :func:`confstr` apply here as well; the dictionary that provides information on the known names is given by ``sysconf_names``. + Availability: Unix. @@ -2131,7 +2337,9 @@ Dictionary mapping names accepted by :func:`sysconf` to the integer values defined for those names by the host operating system. This can be used to - determine the set of names known to the system. Availability: Unix. + determine the set of names known to the system. + + Availability: Unix. The following data values are used to support path manipulation operations. These are defined for all platforms. From brett at python.org Fri May 7 00:58:41 2010 From: brett at python.org (Brett Cannon) Date: Thu, 6 May 2010 15:58:41 -0700 Subject: [Python-checkins] r80809 - python/trunk/Objects/floatobject.c In-Reply-To: <4BE33B5B.7020506@gmail.com> References: <20100505201609.5D92EF68D2@mail.python.org> <4BE2B6DF.6030901@trueblade.com> <4BE33B5B.7020506@gmail.com> Message-ID: On Thu, May 6, 2010 at 14:57, Nick Coghlan wrote: > Brett Cannon wrote: > > And in case people are being timid in fear of upsetting me, feel free to > > undo any changes I made. Obviously I prefer having the lines added back > > in as comments so Clang does not complain about them in the future, but > > if you simply revert a change I am not going to complain. > > Does Clang offer a "please be quiet" comment directive? (I'm pretty sure > Klocwerk used to have that). > You can do annotations, but I would rather not litter the code with that unless it added some feature that we wouldn't have otherwise (e.g. reference counting checks). Plus I don't know if it is limited to functions or any expression. -Brett > > Cheers, > Nick. > > -- > Nick Coghlan | ncoghlan at gmail.com | Brisbane, Australia > --------------------------------------------------------------- > -------------- next part -------------- An HTML attachment was scrubbed... URL: From python-checkins at python.org Fri May 7 01:03:06 2010 From: python-checkins at python.org (benjamin.peterson) Date: Fri, 7 May 2010 01:03:06 +0200 (CEST) Subject: [Python-checkins] r80897 - in python/branches/py3k: Doc/library/os.path.rst Doc/library/os.rst Message-ID: <20100506230306.120B8EE9E8@mail.python.org> Author: benjamin.peterson Date: Fri May 7 01:03:05 2010 New Revision: 80897 Log: Merged revisions 80894,80896 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r80894 | benjamin.peterson | 2010-05-06 17:33:46 -0500 (Thu, 06 May 2010) | 1 line Availability gets its own line ........ r80896 | benjamin.peterson | 2010-05-06 17:49:28 -0500 (Thu, 06 May 2010) | 1 line ensure that availability information is on its own line at the end of the function docs ........ Modified: python/branches/py3k/ (props changed) python/branches/py3k/Doc/library/os.path.rst python/branches/py3k/Doc/library/os.rst Modified: python/branches/py3k/Doc/library/os.path.rst ============================================================================== --- python/branches/py3k/Doc/library/os.path.rst (original) +++ python/branches/py3k/Doc/library/os.path.rst Fri May 7 01:03:05 2010 @@ -223,19 +223,24 @@ Return a relative filepath to *path* either from the current directory or from an optional *start* point. - *start* defaults to :attr:`os.curdir`. Availability: Windows, Unix. + *start* defaults to :attr:`os.curdir`. + + Availability: Windows, Unix. .. function:: samefile(path1, path2) Return ``True`` if both pathname arguments refer to the same file or directory (as indicated by device number and i-node number). Raise an exception if a - :func:`os.stat` call on either pathname fails. Availability: Unix. + :func:`os.stat` call on either pathname fails. + + Availability: Unix. .. function:: sameopenfile(fp1, fp2) Return ``True`` if the file descriptors *fp1* and *fp2* refer to the same file. + Availability: Unix. @@ -244,7 +249,9 @@ Return ``True`` if the stat tuples *stat1* and *stat2* refer to the same file. These structures may have been returned by :func:`fstat`, :func:`lstat`, or :func:`stat`. This function implements the underlying comparison used by - :func:`samefile` and :func:`sameopenfile`. Availability: Unix. + :func:`samefile` and :func:`sameopenfile`. + + Availability: Unix. .. function:: split(path) @@ -293,7 +300,9 @@ Split the pathname *path* into a pair ``(unc, rest)`` so that *unc* is the UNC mount point (such as ``r'\\host\mount'``), if present, and *rest* the rest of the path (such as ``r'\path\file.ext'``). For paths containing drive letters, - *unc* will always be the empty string. Availability: Windows. + *unc* will always be the empty string. + + Availability: Windows. .. data:: supports_unicode_filenames Modified: python/branches/py3k/Doc/library/os.rst ============================================================================== --- python/branches/py3k/Doc/library/os.rst (original) +++ python/branches/py3k/Doc/library/os.rst Fri May 7 01:03:05 2010 @@ -41,6 +41,9 @@ * If not separately noted, all functions that claim "Availability: Unix" are supported on Mac OS X, which builds on a Unix core. +.. Availability notes get their own line and occur at the end of the function +.. documentation. + .. note:: All functions in this module raise :exc:`OSError` in the case of invalid or @@ -166,33 +169,40 @@ .. function:: ctermid() Return the filename corresponding to the controlling terminal of the process. + Availability: Unix. .. function:: getegid() Return the effective group id of the current process. This corresponds to the - "set id" bit on the file being executed in the current process. Availability: - Unix. + "set id" bit on the file being executed in the current process. + + Availability: Unix. .. function:: geteuid() .. index:: single: user; effective id - Return the current process's effective user id. Availability: Unix. + Return the current process's effective user id. + + Availability: Unix. .. function:: getgid() .. index:: single: process; group - Return the real group id of the current process. Availability: Unix. + Return the real group id of the current process. + + Availability: Unix. .. function:: getgroups() Return list of supplemental group ids associated with the current process. + Availability: Unix. @@ -200,7 +210,9 @@ Call the system initgroups() to initialize the group access list with all of the groups of which the specified username is a member, plus the specified - group id. Availability: Unix. + group id. + + Availability: Unix. .. versionadded:: 3.2 @@ -211,40 +223,51 @@ process. For most purposes, it is more useful to use the environment variable :envvar:`LOGNAME` to find out who the user is, or ``pwd.getpwuid(os.getuid())[0]`` to get the login name of the currently - effective user id. Availability: Unix. + effective user id. + + Availability: Unix. .. function:: getpgid(pid) Return the process group id of the process with process id *pid*. If *pid* is 0, - the process group id of the current process is returned. Availability: Unix. + the process group id of the current process is returned. + Availability: Unix. .. function:: getpgrp() .. index:: single: process; group - Return the id of the current process group. Availability: Unix. + Return the id of the current process group. + + Availability: Unix. .. function:: getpid() .. index:: single: process; id - Return the current process id. Availability: Unix, Windows. + Return the current process id. + + Availability: Unix, Windows. .. function:: getppid() .. index:: single: process; id of parent - Return the parent's process id. Availability: Unix. + Return the parent's process id. + + Availability: Unix. .. function:: getresuid() Return a tuple (ruid, euid, suid) denoting the current process's - real, effective, and saved user ids. Availability: Unix. + real, effective, and saved user ids. + + Availability: Unix. .. versionadded:: 3.2 @@ -252,7 +275,9 @@ .. function:: getresgid() Return a tuple (rgid, egid, sgid) denoting the current process's - real, effective, and saved user ids. Availability: Unix. + real, effective, and saved user ids. + + Availability: Unix. .. versionadded:: 3.2 @@ -261,19 +286,22 @@ .. index:: single: user; id - Return the current process's user id. Availability: Unix. + Return the current process's user id. + + Availability: Unix. .. function:: getenv(key, default=None) Return the value of the environment variable *key* if it exists, or *default* if it doesn't. *key*, *default* and the result are str. - Availability: most flavors of Unix, Windows. On Unix, keys and values are decoded with :func:`sys.getfilesystemencoding` and ``'surrogateescape'`` error handler. Use :func:`os.getenvb` if you would like to use a different encoding. + Availability: most flavors of Unix, Windows. + .. function:: getenvb(key, default=None) @@ -291,8 +319,9 @@ Set the environment variable named *key* to the string *value*. Such changes to the environment affect subprocesses started with :func:`os.system`, - :func:`popen` or :func:`fork` and :func:`execv`. Availability: most flavors of - Unix, Windows. + :func:`popen` or :func:`fork` and :func:`execv`. + + Availability: most flavors of Unix, Windows. .. note:: @@ -307,17 +336,23 @@ .. function:: setegid(egid) - Set the current process's effective group id. Availability: Unix. + Set the current process's effective group id. + + Availability: Unix. .. function:: seteuid(euid) - Set the current process's effective user id. Availability: Unix. + Set the current process's effective user id. + + Availability: Unix. .. function:: setgid(gid) - Set the current process' group id. Availability: Unix. + Set the current process' group id. + + Availability: Unix. .. function:: setgroups(groups) @@ -325,6 +360,7 @@ Set the list of supplemental group ids associated with the current process to *groups*. *groups* must be a sequence, and each element must be an integer identifying a group. This operation is typically available only to the superuser. + Availability: Unix. @@ -332,6 +368,7 @@ Call the system call :cfunc:`setpgrp` or :cfunc:`setpgrp(0, 0)` depending on which version is implemented (if any). See the Unix manual for the semantics. + Availability: Unix. @@ -339,17 +376,22 @@ Call the system call :cfunc:`setpgid` to set the process group id of the process with id *pid* to the process group with id *pgrp*. See the Unix manual - for the semantics. Availability: Unix. + for the semantics. + + Availability: Unix. .. function:: setregid(rgid, egid) - Set the current process's real and effective group ids. Availability: Unix. + Set the current process's real and effective group ids. + + Availability: Unix. .. function:: setresgid(rgid, egid, sgid) Set the current process's real, effective, and saved group ids. + Availability: Unix. .. versionadded:: 3.2 @@ -358,6 +400,7 @@ .. function:: setresuid(ruid, euid, suid) Set the current process's real, effective, and saved user ids. + Availibility: Unix. .. versionadded:: 3.2 @@ -365,18 +408,22 @@ .. function:: setreuid(ruid, euid) - Set the current process's real and effective user ids. Availability: Unix. + Set the current process's real and effective user ids. + + Availability: Unix. .. function:: getsid(pid) Call the system call :cfunc:`getsid`. See the Unix manual for the semantics. + Availability: Unix. .. function:: setsid() Call the system call :cfunc:`setsid`. See the Unix manual for the semantics. + Availability: Unix. @@ -384,7 +431,9 @@ .. index:: single: user; id, setting - Set the current process's user id. Availability: Unix. + Set the current process's user id. + + Availability: Unix. .. placed in this section since it relates to errno.... a little weak @@ -392,13 +441,16 @@ Return the error message corresponding to the error code in *code*. On platforms where :cfunc:`strerror` returns ``NULL`` when given an unknown - error number, :exc:`ValueError` is raised. Availability: Unix, Windows. + error number, :exc:`ValueError` is raised. + + Availability: Unix, Windows. .. function:: umask(mask) - Set the current numeric umask and return the previous umask. Availability: - Unix, Windows. + Set the current numeric umask and return the previous umask. + + Availability: Unix, Windows. .. function:: uname() @@ -412,8 +464,9 @@ machine)``. Some systems truncate the nodename to 8 characters or to the leading component; a better way to get the hostname is :func:`socket.gethostname` or even - ``socket.gethostbyaddr(socket.gethostname())``. Availability: recent flavors of - Unix. + ``socket.gethostbyaddr(socket.gethostname())``. + + Availability: recent flavors of Unix. .. function:: unsetenv(key) @@ -422,13 +475,15 @@ Unset (delete) the environment variable named *key*. Such changes to the environment affect subprocesses started with :func:`os.system`, :func:`popen` or - :func:`fork` and :func:`execv`. Availability: most flavors of Unix, Windows. + :func:`fork` and :func:`execv`. When :func:`unsetenv` is supported, deletion of items in ``os.environ`` is automatically translated into a corresponding call to :func:`unsetenv`; however, calls to :func:`unsetenv` don't update ``os.environ``, so it is actually preferable to delete items of ``os.environ``. + Availability: most flavors of Unix, Windows. + .. _os-newstreams: @@ -444,7 +499,7 @@ Return an open file object connected to the file descriptor *fd*. The *mode* and *bufsize* arguments have the same meaning as the corresponding arguments to - the built-in :func:`open` function. Availability: Unix, Windows. + the built-in :func:`open` function. When specified, the *mode* argument must start with one of the letters ``'r'``, ``'w'``, or ``'a'``, otherwise a :exc:`ValueError` is raised. @@ -453,6 +508,8 @@ set on the file descriptor (which the :cfunc:`fdopen` implementation already does on most platforms). + Availability: Unix, Windows. + .. _os-fd-ops: @@ -475,7 +532,9 @@ .. function:: close(fd) - Close file descriptor *fd*. Availability: Unix, Windows. + Close file descriptor *fd*. + + Availability: Unix, Windows. .. note:: @@ -488,7 +547,7 @@ .. function:: closerange(fd_low, fd_high) Close all file descriptors from *fd_low* (inclusive) to *fd_high* (exclusive), - ignoring errors. Availability: Unix, Windows. Equivalent to:: + ignoring errors. Equivalent to:: for fd in range(fd_low, fd_high): try: @@ -496,6 +555,8 @@ except OSError: pass + Availability: Unix, Windows. + .. function:: device_encoding(fd) @@ -505,33 +566,40 @@ .. function:: dup(fd) - Return a duplicate of file descriptor *fd*. Availability: Unix, - Windows. + Return a duplicate of file descriptor *fd*. + + Availability: Unix, Windows. .. function:: dup2(fd, fd2) Duplicate file descriptor *fd* to *fd2*, closing the latter first if necessary. + Availability: Unix, Windows. .. function:: fchmod(fd, mode) Change the mode of the file given by *fd* to the numeric *mode*. See the docs - for :func:`chmod` for possible values of *mode*. Availability: Unix. + for :func:`chmod` for possible values of *mode*. + + Availability: Unix. .. function:: fchown(fd, uid, gid) Change the owner and group id of the file given by *fd* to the numeric *uid* and *gid*. To leave one of the ids unchanged, set it to -1. + Availability: Unix. .. function:: fdatasync(fd) Force write of file with filedescriptor *fd* to disk. Does not force update of - metadata. Availability: Unix. + metadata. + + Availability: Unix. .. note:: This function is not available on MacOS. @@ -546,24 +614,28 @@ additional names as well. The names known to the host operating system are given in the ``pathconf_names`` dictionary. For configuration variables not included in that mapping, passing an integer for *name* is also accepted. - Availability: Unix. If *name* is a string and is not known, :exc:`ValueError` is raised. If a specific value for *name* is not supported by the host system, even if it is included in ``pathconf_names``, an :exc:`OSError` is raised with :const:`errno.EINVAL` for the error number. + Availability: Unix. + .. function:: fstat(fd) - Return status for file descriptor *fd*, like :func:`stat`. Availability: - Unix, Windows. + Return status for file descriptor *fd*, like :func:`stat`. + + Availability: Unix, Windows. .. function:: fstatvfs(fd) Return information about the filesystem containing the file associated with file - descriptor *fd*, like :func:`statvfs`. Availability: Unix. + descriptor *fd*, like :func:`statvfs`. + + Availability: Unix. .. function:: fsync(fd) @@ -573,19 +645,25 @@ If you're starting with a Python file object *f*, first do ``f.flush()``, and then do ``os.fsync(f.fileno())``, to ensure that all internal buffers associated - with *f* are written to disk. Availability: Unix, Windows. + with *f* are written to disk. + + Availability: Unix, and Windows. .. function:: ftruncate(fd, length) Truncate the file corresponding to file descriptor *fd*, so that it is at most - *length* bytes in size. Availability: Unix. + *length* bytes in size. + + Availability: Unix. .. function:: isatty(fd) Return ``True`` if the file descriptor *fd* is open and connected to a - tty(-like) device, else ``False``. Availability: Unix. + tty(-like) device, else ``False``. + + Availability: Unix. .. function:: lseek(fd, pos, how) @@ -594,7 +672,9 @@ by *how*: :const:`SEEK_SET` or ``0`` to set the position relative to the beginning of the file; :const:`SEEK_CUR` or ``1`` to set it relative to the current position; :const:`os.SEEK_END` or ``2`` to set it relative to the end of - the file. Availability: Unix, Windows. + the file. + + Availability: Unix, Windows. .. function:: open(file, flags[, mode]) @@ -602,17 +682,19 @@ Open the file *file* and set various flags according to *flags* and possibly its mode according to *mode*. The default *mode* is ``0o777`` (octal), and the current umask value is first masked out. Return the file descriptor for - the newly opened file. Availability: Unix, Windows. + the newly opened file. For a description of the flag and mode values, see the C run-time documentation; flag constants (like :const:`O_RDONLY` and :const:`O_WRONLY`) are defined in this module too (see below). + Availability: Unix, Windows. + .. note:: This function is intended for low-level I/O. For normal usage, use the built-in function :func:`open`, which returns a "file object" with - :meth:`~file.read` and :meth:`~file.write` methods (and many more). To + :meth:`~file.read` and :meth:`~file.wprite` methods (and many more). To wrap a file descriptor in a "file object", use :func:`fdopen`. @@ -622,21 +704,26 @@ Open a new pseudo-terminal pair. Return a pair of file descriptors ``(master, slave)`` for the pty and the tty, respectively. For a (slightly) more portable - approach, use the :mod:`pty` module. Availability: some flavors of - Unix. + approach, use the :mod:`pty` module. + + Availability: some flavors of Unix. .. function:: pipe() Create a pipe. Return a pair of file descriptors ``(r, w)`` usable for reading - and writing, respectively. Availability: Unix, Windows. + and writing, respectively. + + Availability: Unix, Windows. .. function:: read(fd, n) Read at most *n* bytes from file descriptor *fd*. Return a bytestring containing the bytes read. If the end of the file referred to by *fd* has been reached, an - empty bytes object is returned. Availability: Unix, Windows. + empty bytes object is returned. + + Availability: Unix, Windows. .. note:: @@ -650,26 +737,34 @@ .. function:: tcgetpgrp(fd) Return the process group associated with the terminal given by *fd* (an open - file descriptor as returned by :func:`os.open`). Availability: Unix. + file descriptor as returned by :func:`os.open`). + + Availability: Unix. .. function:: tcsetpgrp(fd, pg) Set the process group associated with the terminal given by *fd* (an open file - descriptor as returned by :func:`os.open`) to *pg*. Availability: Unix. + descriptor as returned by :func:`os.open`) to *pg*. + + Availability: Unix. .. function:: ttyname(fd) Return a string which specifies the terminal device associated with file descriptor *fd*. If *fd* is not associated with a terminal device, an - exception is raised. Availability: Unix. + exception is raised. + + Availability: Unix. .. function:: write(fd, str) Write the bytestring in *str* to file descriptor *fd*. Return the number of - bytes actually written. Availability: Unix, Windows. + bytes actually written. + + Availability: Unix, Windows. .. note:: @@ -752,7 +847,9 @@ can be the inclusive OR of one or more of :const:`R_OK`, :const:`W_OK`, and :const:`X_OK` to test permissions. Return :const:`True` if access is allowed, :const:`False` if not. See the Unix man page :manpage:`access(2)` for more - information. Availability: Unix, Windows. + information. + + Availability: Unix, Windows. .. note:: @@ -796,25 +893,31 @@ .. index:: single: directory; changing - Change the current working directory to *path*. Availability: Unix, - Windows. + Change the current working directory to *path*. + + Availability: Unix, Windows. .. function:: fchdir(fd) Change the current working directory to the directory represented by the file descriptor *fd*. The descriptor must refer to an opened directory, not an open - file. Availability: Unix. + file. + + Availability: Unix. .. function:: getcwd() Return a string representing the current working directory. + Availability: Unix, Windows. + .. function:: getcwdb() Return a bytestring representing the current working directory. + Availability: Unix, Windows. @@ -882,32 +985,41 @@ .. function:: chown(path, uid, gid) Change the owner and group id of *path* to the numeric *uid* and *gid*. To leave - one of the ids unchanged, set it to -1. Availability: Unix. + one of the ids unchanged, set it to -1. + + Availability: Unix. .. function:: lchflags(path, flags) Set the flags of *path* to the numeric *flags*, like :func:`chflags`, but do not - follow symbolic links. Availability: Unix. + follow symbolic links. + + Availability: Unix. .. function:: lchmod(path, mode) Change the mode of *path* to the numeric *mode*. If path is a symlink, this affects the symlink rather than the target. See the docs for :func:`chmod` - for possible values of *mode*. Availability: Unix. + for possible values of *mode*. + + Availability: Unix. .. function:: lchown(path, uid, gid) Change the owner and group id of *path* to the numeric *uid* and *gid*. This - function will not follow symbolic links. Availability: Unix. + function will not follow symbolic links. + + Availability: Unix. .. function:: link(source, link_name) - Create a hard link pointing to *source* named *link_name*. Availability: - Unix. + Create a hard link pointing to *source* named *link_name*. + + Availability: Unix. .. function:: listdir(path) @@ -915,11 +1027,12 @@ Return a list containing the names of the entries in the directory given by *path*. The list is in arbitrary order. It does not include the special entries ``'.'`` and ``'..'`` even if they are present in the directory. - Availability: Unix, Windows. This function can be called with a bytes or string argument, and returns filenames of the same datatype. + Availability: Unix, Windows. + .. function:: lstat(path) @@ -932,7 +1045,7 @@ Create a FIFO (a named pipe) named *path* with numeric mode *mode*. The default *mode* is ``0o666`` (octal). The current umask value is first masked - out from the mode. Availability: Unix. + out from the mode. FIFOs are pipes that can be accessed like regular files. FIFOs exist until they are deleted (for example with :func:`os.unlink`). Generally, FIFOs are used as @@ -940,6 +1053,8 @@ FIFO for reading, and the client opens it for writing. Note that :func:`mkfifo` doesn't open the FIFO --- it just creates the rendezvous point. + Availability: Unix. + .. function:: mknod(filename[, mode=0o600[, device]]) @@ -973,11 +1088,13 @@ Create a directory named *path* with numeric mode *mode*. The default *mode* is ``0o777`` (octal). On some systems, *mode* is ignored. Where it is used, - the current umask value is first masked out. Availability: Unix, Windows. + the current umask value is first masked out. It is also possible to create temporary directories; see the :mod:`tempfile` module's :func:`tempfile.mkdtemp` function. + Availability: Unix, Windows. + .. function:: makedirs(path[, mode]) @@ -1008,13 +1125,14 @@ additional names as well. The names known to the host operating system are given in the ``pathconf_names`` dictionary. For configuration variables not included in that mapping, passing an integer for *name* is also accepted. - Availability: Unix. If *name* is a string and is not known, :exc:`ValueError` is raised. If a specific value for *name* is not supported by the host system, even if it is included in ``pathconf_names``, an :exc:`OSError` is raised with :const:`errno.EINVAL` for the error number. + Availability: Unix. + .. data:: pathconf_names @@ -1045,8 +1163,9 @@ the :func:`unlink` function documented below. On Windows, attempting to remove a file that is in use causes an exception to be raised; on Unix, the directory entry is removed but the storage allocated to the file is not made - available until the original file is no longer in use. Availability: Unix, - Windows. + available until the original file is no longer in use. + + Availability: Unix, Windows. .. function:: removedirs(path) @@ -1072,7 +1191,9 @@ the renaming will be an atomic operation (this is a POSIX requirement). On Windows, if *dst* already exists, :exc:`OSError` will be raised even if it is a file; there may be no way to implement an atomic rename when *dst* names an - existing file. Availability: Unix, Windows. + existing file. + + Availability: Unix, Windows. .. function:: renames(old, new) @@ -1092,8 +1213,9 @@ Remove (delete) the directory *path*. Only works when the directory is empty, otherwise, :exc:`OSError` is raised. In order to remove whole - directory trees, :func:`shutil.rmtree` can be used. Availability: Unix, - Windows. + directory trees, :func:`shutil.rmtree` can be used. + + Availability: Unix, Windows. .. function:: stat(path) @@ -1184,20 +1306,25 @@ correspond to the members of the :ctype:`statvfs` structure, namely: :attr:`f_bsize`, :attr:`f_frsize`, :attr:`f_blocks`, :attr:`f_bfree`, :attr:`f_bavail`, :attr:`f_files`, :attr:`f_ffree`, :attr:`f_favail`, - :attr:`f_flag`, :attr:`f_namemax`. Availability: Unix. + :attr:`f_flag`, :attr:`f_namemax`. + + Availability: Unix. .. function:: symlink(source, link_name) - Create a symbolic link pointing to *source* named *link_name*. Availability: - Unix. + Create a symbolic link pointing to *source* named *link_name*. + + Availability: Unix. .. function:: unlink(path) Remove (delete) the file *path*. This is the same function as :func:`remove`; the :func:`unlink` name is its traditional Unix - name. Availability: Unix, Windows. + name. + + Availability: Unix, Windows. .. function:: utime(path, times) @@ -1321,6 +1448,7 @@ behavior is to produce a core dump; on Windows, the process immediately returns an exit code of ``3``. Be aware that programs which use :func:`signal.signal` to register a handler for :const:`SIGABRT` will behave differently. + Availability: Unix, Windows. @@ -1376,7 +1504,9 @@ .. function:: _exit(n) Exit to the system with status *n*, without calling cleanup handlers, flushing - stdio buffers, etc. Availability: Unix, Windows. + stdio buffers, etc. + + Availability: Unix, Windows. .. note:: @@ -1396,69 +1526,88 @@ .. data:: EX_OK - Exit code that means no error occurred. Availability: Unix. + Exit code that means no error occurred. + + Availability: Unix. .. data:: EX_USAGE Exit code that means the command was used incorrectly, such as when the wrong - number of arguments are given. Availability: Unix. + number of arguments are given. + + Availability: Unix. .. data:: EX_DATAERR - Exit code that means the input data was incorrect. Availability: Unix. + Exit code that means the input data was incorrect. + + Availability: Unix. .. data:: EX_NOINPUT Exit code that means an input file did not exist or was not readable. + Availability: Unix. .. data:: EX_NOUSER - Exit code that means a specified user did not exist. Availability: Unix. + Exit code that means a specified user did not exist. + + Availability: Unix. .. data:: EX_NOHOST - Exit code that means a specified host did not exist. Availability: Unix. + Exit code that means a specified host did not exist. + + Availability: Unix. .. data:: EX_UNAVAILABLE - Exit code that means that a required service is unavailable. Availability: - Unix. + Exit code that means that a required service is unavailable. + + Availability: Unix. .. data:: EX_SOFTWARE - Exit code that means an internal software error was detected. Availability: - Unix. + Exit code that means an internal software error was detected. + + Availability: Unix. .. data:: EX_OSERR Exit code that means an operating system error was detected, such as the - inability to fork or create a pipe. Availability: Unix. + inability to fork or create a pipe. + + Availability: Unix. .. data:: EX_OSFILE Exit code that means some system file did not exist, could not be opened, or had - some other kind of error. Availability: Unix. + some other kind of error. + + Availability: Unix. .. data:: EX_CANTCREAT Exit code that means a user specified output file could not be created. + Availability: Unix. .. data:: EX_IOERR Exit code that means that an error occurred while doing I/O on some file. + Availability: Unix. @@ -1466,31 +1615,39 @@ Exit code that means a temporary failure occurred. This indicates something that may not really be an error, such as a network connection that couldn't be - made during a retryable operation. Availability: Unix. + made during a retryable operation. + + Availability: Unix. .. data:: EX_PROTOCOL Exit code that means that a protocol exchange was illegal, invalid, or not - understood. Availability: Unix. + understood. + + Availability: Unix. .. data:: EX_NOPERM Exit code that means that there were insufficient permissions to perform the - operation (but not intended for file system problems). Availability: Unix. + operation (but not intended for file system problems). + + Availability: Unix. .. data:: EX_CONFIG Exit code that means that some kind of configuration error occurred. + Availability: Unix. .. data:: EX_NOTFOUND - Exit code that means something like "an entry was not found". Availability: - Unix. + Exit code that means something like "an entry was not found". + + Availability: Unix. .. function:: fork() @@ -1511,6 +1668,7 @@ new child's process id in the parent, and *fd* is the file descriptor of the master end of the pseudo-terminal. For a more portable approach, use the :mod:`pty` module. If an error occurs :exc:`OSError` is raised. + Availability: some flavors of Unix. @@ -1540,19 +1698,24 @@ single: process; killing single: process; signalling - Send the signal *sig* to the process group *pgid*. Availability: Unix. + Send the signal *sig* to the process group *pgid*. + + Availability: Unix. .. function:: nice(increment) Add *increment* to the process's "niceness". Return the new niceness. + Availability: Unix. .. function:: plock(op) Lock program segments into memory. The value of *op* (defined in - ````) determines which segments are locked. Availability: Unix. + ````) determines which segments are locked. + + Availability: Unix. .. function:: popen(...) @@ -1631,7 +1794,9 @@ Possible values for the *mode* parameter to the :func:`spawn\*` family of functions. If either of these values is given, the :func:`spawn\*` functions will return as soon as the new process has been created, with the process id as - the return value. Availability: Unix, Windows. + the return value. + + Availability: Unix, Windows. .. data:: P_WAIT @@ -1640,7 +1805,9 @@ functions. If this is given as *mode*, the :func:`spawn\*` functions will not return until the new process has run to completion and will return the exit code of the process the run is successful, or ``-signal`` if a signal kills the - process. Availability: Unix, Windows. + process. + + Availability: Unix, Windows. .. data:: P_DETACH @@ -1651,6 +1818,7 @@ is similar to :const:`P_NOWAIT`, but the new process is detached from the console of the calling process. If :const:`P_OVERLAY` is used, the current process will be replaced; the :func:`spawn\*` function will not return. + Availability: Windows. @@ -1674,7 +1842,9 @@ directory. If you want to use an absolute path, make sure the first character is not a slash (``'/'``); the underlying Win32 :cfunc:`ShellExecute` function doesn't work if it is. Use the :func:`os.path.normpath` function to ensure that - the path is properly encoded for Win32. Availability: Windows. + the path is properly encoded for Win32. + + Availability: Windows. .. function:: system(command) @@ -1696,22 +1866,24 @@ the command run; on systems using a non-native shell, consult your shell documentation. - Availability: Unix, Windows. - The :mod:`subprocess` module provides more powerful facilities for spawning new processes and retrieving their results; using that module is preferable to using this function. Use the :mod:`subprocess` module. Check especially the :ref:`subprocess-replacements` section. + Availability: Unix, Windows. + .. function:: times() - Return a 5-tuple of floating point numbers indicating accumulated (processor or - other) times, in seconds. The items are: user time, system time, children's - user time, children's system time, and elapsed real time since a fixed point in - the past, in that order. See the Unix manual page :manpage:`times(2)` or the - corresponding Windows Platform API documentation. Availability: Unix, - Windows. On Windows, only the first two items are filled, the others are zero. + Return a 5-tuple of floating point numbers indicating accumulated (processor + or other) times, in seconds. The items are: user time, system time, + children's user time, children's system time, and elapsed real time since a + fixed point in the past, in that order. See the Unix manual page + :manpage:`times(2)` or the corresponding Windows Platform API documentation. + On Windows, only the first two items are filled, the others are zero. + + Availability: Unix, Windows .. function:: wait() @@ -1720,7 +1892,9 @@ and exit status indication: a 16-bit number, whose low byte is the signal number that killed the process, and whose high byte is the exit status (if the signal number is zero); the high bit of the low byte is set if a core file was - produced. Availability: Unix. + produced. + + Availability: Unix. .. function:: waitpid(pid, options) @@ -1758,6 +1932,7 @@ resource usage information is returned. Refer to :mod:`resource`.\ :func:`getrusage` for details on resource usage information. The option argument is the same as that provided to :func:`waitpid` and :func:`wait4`. + Availability: Unix. @@ -1767,28 +1942,33 @@ process id, exit status indication, and resource usage information is returned. Refer to :mod:`resource`.\ :func:`getrusage` for details on resource usage information. The arguments to :func:`wait4` are the same as those provided to - :func:`waitpid`. Availability: Unix. + :func:`waitpid`. + + Availability: Unix. .. data:: WNOHANG The option for :func:`waitpid` to return immediately if no child process status is available immediately. The function returns ``(0, 0)`` in this case. + Availability: Unix. .. data:: WCONTINUED This option causes child processes to be reported if they have been continued - from a job control stop since their status was last reported. Availability: Some - Unix systems. + from a job control stop since their status was last reported. + + Availability: Some Unix systems. .. data:: WUNTRACED This option causes child processes to be reported if they have been stopped but - their current state has not been reported since they were stopped. Availability: - Unix. + their current state has not been reported since they were stopped. + + Availability: Unix. The following functions take a process status code as returned by @@ -1798,48 +1978,63 @@ .. function:: WCOREDUMP(status) Return ``True`` if a core dump was generated for the process, otherwise - return ``False``. Availability: Unix. + return ``False``. + + Availability: Unix. .. function:: WIFCONTINUED(status) Return ``True`` if the process has been continued from a job control stop, - otherwise return ``False``. Availability: Unix. + otherwise return ``False``. + + Availability: Unix. .. function:: WIFSTOPPED(status) Return ``True`` if the process has been stopped, otherwise return - ``False``. Availability: Unix. + ``False``. + + Availability: Unix. .. function:: WIFSIGNALED(status) Return ``True`` if the process exited due to a signal, otherwise return - ``False``. Availability: Unix. + ``False``. + + Availability: Unix. .. function:: WIFEXITED(status) Return ``True`` if the process exited using the :manpage:`exit(2)` system call, - otherwise return ``False``. Availability: Unix. + otherwise return ``False``. + + Availability: Unix. .. function:: WEXITSTATUS(status) If ``WIFEXITED(status)`` is true, return the integer parameter to the :manpage:`exit(2)` system call. Otherwise, the return value is meaningless. + Availability: Unix. .. function:: WSTOPSIG(status) - Return the signal which caused the process to stop. Availability: Unix. + Return the signal which caused the process to stop. + + Availability: Unix. .. function:: WTERMSIG(status) - Return the signal which caused the process to exit. Availability: Unix. + Return the signal which caused the process to exit. + + Availability: Unix. .. _os-path: @@ -1856,8 +2051,7 @@ Unix 95, Unix 98, and others). Some platforms define additional names as well. The names known to the host operating system are given as the keys of the ``confstr_names`` dictionary. For configuration variables not included in that - mapping, passing an integer for *name* is also accepted. Availability: - Unix. + mapping, passing an integer for *name* is also accepted. If the configuration value specified by *name* isn't defined, ``None`` is returned. @@ -1867,19 +2061,25 @@ included in ``confstr_names``, an :exc:`OSError` is raised with :const:`errno.EINVAL` for the error number. + Availability: Unix + .. data:: confstr_names Dictionary mapping names accepted by :func:`confstr` to the integer values defined for those names by the host operating system. This can be used to - determine the set of names known to the system. Availability: Unix. + determine the set of names known to the system. + + Availability: Unix. .. function:: getloadavg() Return the number of processes in the system run queue averaged over the last 1, 5, and 15 minutes or raises :exc:`OSError` if the load average was - unobtainable. Availability: Unix. + unobtainable. + + Availability: Unix. .. function:: sysconf(name) @@ -1888,6 +2088,7 @@ specified by *name* isn't defined, ``-1`` is returned. The comments regarding the *name* parameter for :func:`confstr` apply here as well; the dictionary that provides information on the known names is given by ``sysconf_names``. + Availability: Unix. @@ -1895,7 +2096,9 @@ Dictionary mapping names accepted by :func:`sysconf` to the integer values defined for those names by the host operating system. This can be used to - determine the set of names known to the system. Availability: Unix. + determine the set of names known to the system. + + Availability: Unix. The following data values are used to support path manipulation operations. These are defined for all platforms. From python-checkins at python.org Fri May 7 01:04:44 2010 From: python-checkins at python.org (benjamin.peterson) Date: Fri, 7 May 2010 01:04:44 +0200 (CEST) Subject: [Python-checkins] r80898 - in python/branches/release26-maint: Doc/library/os.path.rst Doc/library/os.rst Message-ID: <20100506230444.EA17AEE9E8@mail.python.org> Author: benjamin.peterson Date: Fri May 7 01:04:44 2010 New Revision: 80898 Log: Merged revisions 80894,80896 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r80894 | benjamin.peterson | 2010-05-06 17:33:46 -0500 (Thu, 06 May 2010) | 1 line Availability gets its own line ........ r80896 | benjamin.peterson | 2010-05-06 17:49:28 -0500 (Thu, 06 May 2010) | 1 line ensure that availability information is on its own line at the end of the function docs ........ Modified: python/branches/release26-maint/ (props changed) python/branches/release26-maint/Doc/library/os.path.rst python/branches/release26-maint/Doc/library/os.rst Modified: python/branches/release26-maint/Doc/library/os.path.rst ============================================================================== --- python/branches/release26-maint/Doc/library/os.path.rst (original) +++ python/branches/release26-maint/Doc/library/os.path.rst Fri May 7 01:04:44 2010 @@ -231,7 +231,9 @@ Return a relative filepath to *path* either from the current directory or from an optional *start* point. - *start* defaults to :attr:`os.curdir`. Availability: Windows, Unix. + *start* defaults to :attr:`os.curdir`. + + Availability: Windows, Unix. .. versionadded:: 2.6 @@ -240,12 +242,15 @@ Return ``True`` if both pathname arguments refer to the same file or directory (as indicated by device number and i-node number). Raise an exception if a - :func:`os.stat` call on either pathname fails. Availability: Unix. + :func:`os.stat` call on either pathname fails. + + Availability: Unix. .. function:: sameopenfile(fp1, fp2) Return ``True`` if the file descriptors *fp1* and *fp2* refer to the same file. + Availability: Unix. @@ -254,7 +259,9 @@ Return ``True`` if the stat tuples *stat1* and *stat2* refer to the same file. These structures may have been returned by :func:`fstat`, :func:`lstat`, or :func:`stat`. This function implements the underlying comparison used by - :func:`samefile` and :func:`sameopenfile`. Availability: Unix. + :func:`samefile` and :func:`sameopenfile`. + + Availability: Unix. .. function:: split(path) @@ -296,7 +303,9 @@ Split the pathname *path* into a pair ``(unc, rest)`` so that *unc* is the UNC mount point (such as ``r'\\host\mount'``), if present, and *rest* the rest of the path (such as ``r'\path\file.ext'``). For paths containing drive letters, - *unc* will always be the empty string. Availability: Windows. + *unc* will always be the empty string. + + Availability: Windows. .. function:: walk(path, visit, arg) Modified: python/branches/release26-maint/Doc/library/os.rst ============================================================================== --- python/branches/release26-maint/Doc/library/os.rst (original) +++ python/branches/release26-maint/Doc/library/os.rst Fri May 7 01:04:44 2010 @@ -32,6 +32,9 @@ * If not separately noted, all functions that claim "Availability: Unix" are supported on Mac OS X, which builds on a Unix core. +.. Availability notes get their own line and occur at the end of the function +.. documentation. + .. note:: All functions in this module raise :exc:`OSError` in the case of invalid or @@ -111,33 +114,40 @@ .. function:: ctermid() Return the filename corresponding to the controlling terminal of the process. + Availability: Unix. .. function:: getegid() Return the effective group id of the current process. This corresponds to the - "set id" bit on the file being executed in the current process. Availability: - Unix. + "set id" bit on the file being executed in the current process. + + Availability: Unix. .. function:: geteuid() .. index:: single: user; effective id - Return the current process's effective user id. Availability: Unix. + Return the current process's effective user id. + + Availability: Unix. .. function:: getgid() .. index:: single: process; group - Return the real group id of the current process. Availability: Unix. + Return the real group id of the current process. + + Availability: Unix. .. function:: getgroups() Return list of supplemental group ids associated with the current process. + Availability: Unix. @@ -147,13 +157,17 @@ process. For most purposes, it is more useful to use the environment variable :envvar:`LOGNAME` to find out who the user is, or ``pwd.getpwuid(os.getuid())[0]`` to get the login name of the currently - effective user id. Availability: Unix. + effective user id. + + Availability: Unix. .. function:: getpgid(pid) Return the process group id of the process with process id *pid*. If *pid* is 0, - the process group id of the current process is returned. Availability: Unix. + the process group id of the current process is returned. + + Availability: Unix. .. versionadded:: 2.3 @@ -162,35 +176,44 @@ .. index:: single: process; group - Return the id of the current process group. Availability: Unix. + Return the id of the current process group. + + Availability: Unix. .. function:: getpid() .. index:: single: process; id - Return the current process id. Availability: Unix, Windows. + Return the current process id. + + Availability: Unix, Windows. .. function:: getppid() .. index:: single: process; id of parent - Return the parent's process id. Availability: Unix. + Return the parent's process id. + + Availability: Unix. .. function:: getuid() .. index:: single: user; id - Return the current process's user id. Availability: Unix. + Return the current process's user id. + + Availability: Unix. .. function:: getenv(varname[, value]) Return the value of the environment variable *varname* if it exists, or *value* - if it doesn't. *value* defaults to ``None``. Availability: most flavors of - Unix, Windows. + if it doesn't. *value* defaults to ``None``. + + Availability: most flavors of Unix, Windows. .. function:: putenv(varname, value) @@ -199,8 +222,9 @@ Set the environment variable named *varname* to the string *value*. Such changes to the environment affect subprocesses started with :func:`os.system`, - :func:`popen` or :func:`fork` and :func:`execv`. Availability: most flavors of - Unix, Windows. + :func:`popen` or :func:`fork` and :func:`execv`. + + Availability: most flavors of Unix, Windows. .. note:: @@ -215,17 +239,23 @@ .. function:: setegid(egid) - Set the current process's effective group id. Availability: Unix. + Set the current process's effective group id. + + Availability: Unix. .. function:: seteuid(euid) - Set the current process's effective user id. Availability: Unix. + Set the current process's effective user id. + + Availability: Unix. .. function:: setgid(gid) - Set the current process' group id. Availability: Unix. + Set the current process' group id. + + Availability: Unix. .. function:: setgroups(groups) @@ -233,6 +263,7 @@ Set the list of supplemental group ids associated with the current process to *groups*. *groups* must be a sequence, and each element must be an integer identifying a group. This operation is typically available only to the superuser. + Availability: Unix. .. versionadded:: 2.2 @@ -242,6 +273,7 @@ Call the system call :cfunc:`setpgrp` or :cfunc:`setpgrp(0, 0)` depending on which version is implemented (if any). See the Unix manual for the semantics. + Availability: Unix. @@ -249,22 +281,29 @@ Call the system call :cfunc:`setpgid` to set the process group id of the process with id *pid* to the process group with id *pgrp*. See the Unix manual - for the semantics. Availability: Unix. + for the semantics. + + Availability: Unix. .. function:: setreuid(ruid, euid) - Set the current process's real and effective user ids. Availability: Unix. + Set the current process's real and effective user ids. + + Availability: Unix. .. function:: setregid(rgid, egid) - Set the current process's real and effective group ids. Availability: Unix. + Set the current process's real and effective group ids. + + Availability: Unix. .. function:: getsid(pid) Call the system call :cfunc:`getsid`. See the Unix manual for the semantics. + Availability: Unix. .. versionadded:: 2.4 @@ -273,6 +312,7 @@ .. function:: setsid() Call the system call :cfunc:`setsid`. See the Unix manual for the semantics. + Availability: Unix. @@ -280,7 +320,9 @@ .. index:: single: user; id, setting - Set the current process's user id. Availability: Unix. + Set the current process's user id. + + Availability: Unix. .. placed in this section since it relates to errno.... a little weak @@ -288,13 +330,16 @@ Return the error message corresponding to the error code in *code*. On platforms where :cfunc:`strerror` returns ``NULL`` when given an unknown - error number, :exc:`ValueError` is raised. Availability: Unix, Windows. + error number, :exc:`ValueError` is raised. + + Availability: Unix, Windows. .. function:: umask(mask) - Set the current numeric umask and return the previous umask. Availability: - Unix, Windows. + Set the current numeric umask and return the previous umask. + + Availability: Unix, Windows. .. function:: uname() @@ -308,8 +353,9 @@ machine)``. Some systems truncate the nodename to 8 characters or to the leading component; a better way to get the hostname is :func:`socket.gethostname` or even - ``socket.gethostbyaddr(socket.gethostname())``. Availability: recent flavors of - Unix. + ``socket.gethostbyaddr(socket.gethostname())``. + + Availability: recent flavors of Unix. .. function:: unsetenv(varname) @@ -318,13 +364,15 @@ Unset (delete) the environment variable named *varname*. Such changes to the environment affect subprocesses started with :func:`os.system`, :func:`popen` or - :func:`fork` and :func:`execv`. Availability: most flavors of Unix, Windows. + :func:`fork` and :func:`execv`. When :func:`unsetenv` is supported, deletion of items in ``os.environ`` is automatically translated into a corresponding call to :func:`unsetenv`; however, calls to :func:`unsetenv` don't update ``os.environ``, so it is actually preferable to delete items of ``os.environ``. + Availability: most flavors of Unix, Windows. + .. _os-newstreams: @@ -340,7 +388,9 @@ Return an open file object connected to the file descriptor *fd*. The *mode* and *bufsize* arguments have the same meaning as the corresponding arguments to - the built-in :func:`open` function. Availability: Unix, Windows. + the built-in :func:`open` function. + + Availability: Unix, Windows. .. versionchanged:: 2.3 When specified, the *mode* argument must now start with one of the letters @@ -361,7 +411,9 @@ status of the command (encoded in the format specified for :func:`wait`) is available as the return value of the :meth:`~file.close` method of the file object, except that when the exit status is zero (termination without errors), ``None`` - is returned. Availability: Unix, Windows. + is returned. + + Availability: Unix, Windows. .. deprecated:: 2.6 This function is obsolete. Use the :mod:`subprocess` module. Check @@ -378,8 +430,9 @@ Return a new file object opened in update mode (``w+b``). The file has no directory entries associated with it and will be automatically deleted once - there are no file descriptors for the file. Availability: Unix, - Windows. + there are no file descriptors for the file. + + Availability: Unix, Windows. There are a number of different :func:`popen\*` functions that provide slightly different ways to create subprocesses. @@ -475,7 +528,9 @@ .. function:: close(fd) - Close file descriptor *fd*. Availability: Unix, Windows. + Close file descriptor *fd*. + + Availability: Unix, Windows. .. note:: @@ -488,7 +543,7 @@ .. function:: closerange(fd_low, fd_high) Close all file descriptors from *fd_low* (inclusive) to *fd_high* (exclusive), - ignoring errors. Availability: Unix, Windows. Equivalent to:: + ignoring errors. Equivalent to:: for fd in xrange(fd_low, fd_high): try: @@ -496,25 +551,31 @@ except OSError: pass + Availability: Unix, Windows. + .. versionadded:: 2.6 .. function:: dup(fd) - Return a duplicate of file descriptor *fd*. Availability: Unix, - Windows. + Return a duplicate of file descriptor *fd*. + + Availability: Unix, Windows. .. function:: dup2(fd, fd2) Duplicate file descriptor *fd* to *fd2*, closing the latter first if necessary. + Availability: Unix, Windows. .. function:: fchmod(fd, mode) Change the mode of the file given by *fd* to the numeric *mode*. See the docs - for :func:`chmod` for possible values of *mode*. Availability: Unix. + for :func:`chmod` for possible values of *mode*. + + Availability: Unix. .. versionadded:: 2.6 @@ -523,6 +584,7 @@ Change the owner and group id of the file given by *fd* to the numeric *uid* and *gid*. To leave one of the ids unchanged, set it to -1. + Availability: Unix. .. versionadded:: 2.6 @@ -531,7 +593,9 @@ .. function:: fdatasync(fd) Force write of file with filedescriptor *fd* to disk. Does not force update of - metadata. Availability: Unix. + metadata. + + Availability: Unix. .. note:: This function is not available on MacOS. @@ -546,24 +610,28 @@ additional names as well. The names known to the host operating system are given in the ``pathconf_names`` dictionary. For configuration variables not included in that mapping, passing an integer for *name* is also accepted. - Availability: Unix. If *name* is a string and is not known, :exc:`ValueError` is raised. If a specific value for *name* is not supported by the host system, even if it is included in ``pathconf_names``, an :exc:`OSError` is raised with :const:`errno.EINVAL` for the error number. + Availability: Unix. + .. function:: fstat(fd) - Return status for file descriptor *fd*, like :func:`stat`. Availability: - Unix, Windows. + Return status for file descriptor *fd*, like :func:`stat`. + + Availability: Unix, Windows. .. function:: fstatvfs(fd) Return information about the filesystem containing the file associated with file - descriptor *fd*, like :func:`statvfs`. Availability: Unix. + descriptor *fd*, like :func:`statvfs`. + + Availability: Unix. .. function:: fsync(fd) @@ -573,20 +641,25 @@ If you're starting with a Python file object *f*, first do ``f.flush()``, and then do ``os.fsync(f.fileno())``, to ensure that all internal buffers associated - with *f* are written to disk. Availability: Unix, and Windows - starting in 2.2.3. + with *f* are written to disk. + + Availability: Unix, and Windows starting in 2.2.3. .. function:: ftruncate(fd, length) Truncate the file corresponding to file descriptor *fd*, so that it is at most - *length* bytes in size. Availability: Unix. + *length* bytes in size. + + Availability: Unix. .. function:: isatty(fd) Return ``True`` if the file descriptor *fd* is open and connected to a - tty(-like) device, else ``False``. Availability: Unix. + tty(-like) device, else ``False``. + + Availability: Unix. .. function:: lseek(fd, pos, how) @@ -595,7 +668,9 @@ by *how*: :const:`SEEK_SET` or ``0`` to set the position relative to the beginning of the file; :const:`SEEK_CUR` or ``1`` to set it relative to the current position; :const:`os.SEEK_END` or ``2`` to set it relative to the end of - the file. Availability: Unix, Windows. + the file. + + Availability: Unix, Windows. .. function:: open(file, flags[, mode]) @@ -603,17 +678,19 @@ Open the file *file* and set various flags according to *flags* and possibly its mode according to *mode*. The default *mode* is ``0777`` (octal), and the current umask value is first masked out. Return the file descriptor for the - newly opened file. Availability: Unix, Windows. + newly opened file. For a description of the flag and mode values, see the C run-time documentation; flag constants (like :const:`O_RDONLY` and :const:`O_WRONLY`) are defined in this module too (see below). + Availability: Unix, Windows. + .. note:: This function is intended for low-level I/O. For normal usage, use the built-in function :func:`open`, which returns a "file object" with - :meth:`~file.read` and :meth:`~file.write` methods (and many more). To + :meth:`~file.read` and :meth:`~file.wprite` methods (and many more). To wrap a file descriptor in a "file object", use :func:`fdopen`. @@ -623,21 +700,26 @@ Open a new pseudo-terminal pair. Return a pair of file descriptors ``(master, slave)`` for the pty and the tty, respectively. For a (slightly) more portable - approach, use the :mod:`pty` module. Availability: some flavors of - Unix. + approach, use the :mod:`pty` module. + + Availability: some flavors of Unix. .. function:: pipe() Create a pipe. Return a pair of file descriptors ``(r, w)`` usable for reading - and writing, respectively. Availability: Unix, Windows. + and writing, respectively. + + Availability: Unix, Windows. .. function:: read(fd, n) Read at most *n* bytes from file descriptor *fd*. Return a string containing the bytes read. If the end of the file referred to by *fd* has been reached, an - empty string is returned. Availability: Unix, Windows. + empty string is returned. + + Availability: Unix, Windows. .. note:: @@ -651,26 +733,34 @@ .. function:: tcgetpgrp(fd) Return the process group associated with the terminal given by *fd* (an open - file descriptor as returned by :func:`os.open`). Availability: Unix. + file descriptor as returned by :func:`os.open`). + + Availability: Unix. .. function:: tcsetpgrp(fd, pg) Set the process group associated with the terminal given by *fd* (an open file - descriptor as returned by :func:`os.open`) to *pg*. Availability: Unix. + descriptor as returned by :func:`os.open`) to *pg*. + + Availability: Unix. .. function:: ttyname(fd) Return a string which specifies the terminal device associated with file descriptor *fd*. If *fd* is not associated with a terminal device, an - exception is raised. Availability: Unix. + exception is raised. + + Availability: Unix. .. function:: write(fd, str) Write the string *str* to file descriptor *fd*. Return the number of bytes - actually written. Availability: Unix, Windows. + actually written. + + Availability: Unix, Windows. .. note:: @@ -755,7 +845,9 @@ can be the inclusive OR of one or more of :const:`R_OK`, :const:`W_OK`, and :const:`X_OK` to test permissions. Return :const:`True` if access is allowed, :const:`False` if not. See the Unix man page :manpage:`access(2)` for more - information. Availability: Unix, Windows. + information. + + Availability: Unix, Windows. .. note:: @@ -799,28 +891,33 @@ .. index:: single: directory; changing - Change the current working directory to *path*. Availability: Unix, - Windows. + Change the current working directory to *path*. + + Availability: Unix, Windows. .. function:: fchdir(fd) Change the current working directory to the directory represented by the file descriptor *fd*. The descriptor must refer to an opened directory, not an open - file. Availability: Unix. + file. + + Availability: Unix. .. versionadded:: 2.3 .. function:: getcwd() - Return a string representing the current working directory. Availability: - Unix, Windows. + Return a string representing the current working directory. + + Availability: Unix, Windows. .. function:: getcwdu() Return a Unicode object representing the current working directory. + Availability: Unix, Windows. .. versionadded:: 2.3 @@ -895,13 +992,17 @@ .. function:: chown(path, uid, gid) Change the owner and group id of *path* to the numeric *uid* and *gid*. To leave - one of the ids unchanged, set it to -1. Availability: Unix. + one of the ids unchanged, set it to -1. + + Availability: Unix. .. function:: lchflags(path, flags) Set the flags of *path* to the numeric *flags*, like :func:`chflags`, but do not - follow symbolic links. Availability: Unix. + follow symbolic links. + + Availability: Unix. .. versionadded:: 2.6 @@ -910,7 +1011,9 @@ Change the mode of *path* to the numeric *mode*. If path is a symlink, this affects the symlink rather than the target. See the docs for :func:`chmod` - for possible values of *mode*. Availability: Unix. + for possible values of *mode*. + + Availability: Unix. .. versionadded:: 2.6 @@ -918,15 +1021,18 @@ .. function:: lchown(path, uid, gid) Change the owner and group id of *path* to the numeric *uid* and *gid*. This - function will not follow symbolic links. Availability: Unix. + function will not follow symbolic links. + + Availability: Unix. .. versionadded:: 2.3 .. function:: link(source, link_name) - Create a hard link pointing to *source* named *link_name*. Availability: - Unix. + Create a hard link pointing to *source* named *link_name*. + + Availability: Unix. .. function:: listdir(path) @@ -934,7 +1040,9 @@ Return a list containing the names of the entries in the directory given by *path*. The list is in arbitrary order. It does not include the special entries ``'.'`` and ``'..'`` even if they are present in the - directory. Availability: Unix, Windows. + directory. + + Availability: Unix, Windows. .. versionchanged:: 2.3 On Windows NT/2k/XP and Unix, if *path* is a Unicode object, the result will be @@ -953,7 +1061,9 @@ Create a FIFO (a named pipe) named *path* with numeric mode *mode*. The default *mode* is ``0666`` (octal). The current umask value is first masked out from - the mode. Availability: Unix. + the mode. + + Availability: Unix. FIFOs are pipes that can be accessed like regular files. FIFOs exist until they are deleted (for example with :func:`os.unlink`). Generally, FIFOs are used as @@ -1003,11 +1113,13 @@ Create a directory named *path* with numeric mode *mode*. The default *mode* is ``0777`` (octal). On some systems, *mode* is ignored. Where it is used, the - current umask value is first masked out. Availability: Unix, Windows. + current umask value is first masked out. It is also possible to create temporary directories; see the :mod:`tempfile` module's :func:`tempfile.mkdtemp` function. + Availability: Unix, Windows. + .. function:: makedirs(path[, mode]) @@ -1041,13 +1153,14 @@ additional names as well. The names known to the host operating system are given in the ``pathconf_names`` dictionary. For configuration variables not included in that mapping, passing an integer for *name* is also accepted. - Availability: Unix. If *name* is a string and is not known, :exc:`ValueError` is raised. If a specific value for *name* is not supported by the host system, even if it is included in ``pathconf_names``, an :exc:`OSError` is raised with :const:`errno.EINVAL` for the error number. + Availability: Unix. + .. data:: pathconf_names @@ -1077,8 +1190,9 @@ the :func:`unlink` function documented below. On Windows, attempting to remove a file that is in use causes an exception to be raised; on Unix, the directory entry is removed but the storage allocated to the file is not made - available until the original file is no longer in use. Availability: Unix, - Windows. + available until the original file is no longer in use. + + Availability: Unix, Windows. .. function:: removedirs(path) @@ -1106,7 +1220,9 @@ the renaming will be an atomic operation (this is a POSIX requirement). On Windows, if *dst* already exists, :exc:`OSError` will be raised even if it is a file; there may be no way to implement an atomic rename when *dst* names an - existing file. Availability: Unix, Windows. + existing file. + + Availability: Unix, Windows. .. function:: renames(old, new) @@ -1128,8 +1244,9 @@ Remove (delete) the directory *path*. Only works when the directory is empty, otherwise, :exc:`OSError` is raised. In order to remove whole - directory trees, :func:`shutil.rmtree` can be used. Availability: Unix, - Windows. + directory trees, :func:`shutil.rmtree` can be used. + + Availability: Unix, Windows. .. function:: stat(path) @@ -1235,7 +1352,7 @@ correspond to the members of the :ctype:`statvfs` structure, namely: :attr:`f_bsize`, :attr:`f_frsize`, :attr:`f_blocks`, :attr:`f_bfree`, :attr:`f_bavail`, :attr:`f_files`, :attr:`f_ffree`, :attr:`f_favail`, - :attr:`f_flag`, :attr:`f_namemax`. Availability: Unix. + :attr:`f_flag`, :attr:`f_namemax`. .. index:: module: statvfs @@ -1246,14 +1363,17 @@ this remains useful when writing code that needs to work with versions of Python that don't support accessing the fields as attributes. + Availability: Unix. + .. versionchanged:: 2.2 Added access to values as attributes of the returned object. .. function:: symlink(source, link_name) - Create a symbolic link pointing to *source* named *link_name*. Availability: - Unix. + Create a symbolic link pointing to *source* named *link_name*. + + Availability: Unix. .. function:: tempnam([dir[, prefix]]) @@ -1307,7 +1427,9 @@ Remove (delete) the file *path*. This is the same function as :func:`remove`; the :func:`unlink` name is its traditional Unix - name. Availability: Unix, Windows. + name. + + Availability: Unix, Windows. .. function:: utime(path, times) @@ -1439,6 +1561,7 @@ behavior is to produce a core dump; on Windows, the process immediately returns an exit code of ``3``. Be aware that programs which use :func:`signal.signal` to register a handler for :const:`SIGABRT` will behave differently. + Availability: Unix, Windows. @@ -1494,7 +1617,9 @@ .. function:: _exit(n) Exit to the system with status *n*, without calling cleanup handlers, flushing - stdio buffers, etc. Availability: Unix, Windows. + stdio buffers, etc. + + Availability: Unix, Windows. .. note:: @@ -1514,7 +1639,9 @@ .. data:: EX_OK - Exit code that means no error occurred. Availability: Unix. + Exit code that means no error occurred. + + Availability: Unix. .. versionadded:: 2.3 @@ -1522,14 +1649,18 @@ .. data:: EX_USAGE Exit code that means the command was used incorrectly, such as when the wrong - number of arguments are given. Availability: Unix. + number of arguments are given. + + Availability: Unix. .. versionadded:: 2.3 .. data:: EX_DATAERR - Exit code that means the input data was incorrect. Availability: Unix. + Exit code that means the input data was incorrect. + + Availability: Unix. .. versionadded:: 2.3 @@ -1537,6 +1668,7 @@ .. data:: EX_NOINPUT Exit code that means an input file did not exist or was not readable. + Availability: Unix. .. versionadded:: 2.3 @@ -1544,30 +1676,36 @@ .. data:: EX_NOUSER - Exit code that means a specified user did not exist. Availability: Unix. + Exit code that means a specified user did not exist. + + Availability: Unix. .. versionadded:: 2.3 .. data:: EX_NOHOST - Exit code that means a specified host did not exist. Availability: Unix. + Exit code that means a specified host did not exist. + + Availability: Unix. .. versionadded:: 2.3 .. data:: EX_UNAVAILABLE - Exit code that means that a required service is unavailable. Availability: - Unix. + Exit code that means that a required service is unavailable. + + Availability: Unix. .. versionadded:: 2.3 .. data:: EX_SOFTWARE - Exit code that means an internal software error was detected. Availability: - Unix. + Exit code that means an internal software error was detected. + + Availability: Unix. .. versionadded:: 2.3 @@ -1575,7 +1713,9 @@ .. data:: EX_OSERR Exit code that means an operating system error was detected, such as the - inability to fork or create a pipe. Availability: Unix. + inability to fork or create a pipe. + + Availability: Unix. .. versionadded:: 2.3 @@ -1583,7 +1723,9 @@ .. data:: EX_OSFILE Exit code that means some system file did not exist, could not be opened, or had - some other kind of error. Availability: Unix. + some other kind of error. + + Availability: Unix. .. versionadded:: 2.3 @@ -1591,6 +1733,7 @@ .. data:: EX_CANTCREAT Exit code that means a user specified output file could not be created. + Availability: Unix. .. versionadded:: 2.3 @@ -1599,6 +1742,7 @@ .. data:: EX_IOERR Exit code that means that an error occurred while doing I/O on some file. + Availability: Unix. .. versionadded:: 2.3 @@ -1608,7 +1752,9 @@ Exit code that means a temporary failure occurred. This indicates something that may not really be an error, such as a network connection that couldn't be - made during a retryable operation. Availability: Unix. + made during a retryable operation. + + Availability: Unix. .. versionadded:: 2.3 @@ -1616,7 +1762,9 @@ .. data:: EX_PROTOCOL Exit code that means that a protocol exchange was illegal, invalid, or not - understood. Availability: Unix. + understood. + + Availability: Unix. .. versionadded:: 2.3 @@ -1624,7 +1772,9 @@ .. data:: EX_NOPERM Exit code that means that there were insufficient permissions to perform the - operation (but not intended for file system problems). Availability: Unix. + operation (but not intended for file system problems). + + Availability: Unix. .. versionadded:: 2.3 @@ -1632,6 +1782,7 @@ .. data:: EX_CONFIG Exit code that means that some kind of configuration error occurred. + Availability: Unix. .. versionadded:: 2.3 @@ -1639,8 +1790,9 @@ .. data:: EX_NOTFOUND - Exit code that means something like "an entry was not found". Availability: - Unix. + Exit code that means something like "an entry was not found". + + Availability: Unix. .. versionadded:: 2.3 @@ -1663,6 +1815,7 @@ new child's process id in the parent, and *fd* is the file descriptor of the master end of the pseudo-terminal. For a more portable approach, use the :mod:`pty` module. If an error occurs :exc:`OSError` is raised. + Availability: some flavors of Unix. @@ -1683,7 +1836,9 @@ single: process; killing single: process; signalling - Send the signal *sig* to the process group *pgid*. Availability: Unix. + Send the signal *sig* to the process group *pgid*. + + Availability: Unix. .. versionadded:: 2.3 @@ -1691,13 +1846,16 @@ .. function:: nice(increment) Add *increment* to the process's "niceness". Return the new niceness. + Availability: Unix. .. function:: plock(op) Lock program segments into memory. The value of *op* (defined in - ````) determines which segments are locked. Availability: Unix. + ````) determines which segments are locked. + + Availability: Unix. .. function:: popen(...) @@ -1781,7 +1939,9 @@ Possible values for the *mode* parameter to the :func:`spawn\*` family of functions. If either of these values is given, the :func:`spawn\*` functions will return as soon as the new process has been created, with the process id as - the return value. Availability: Unix, Windows. + the return value. + + Availability: Unix, Windows. .. versionadded:: 1.6 @@ -1792,7 +1952,9 @@ functions. If this is given as *mode*, the :func:`spawn\*` functions will not return until the new process has run to completion and will return the exit code of the process the run is successful, or ``-signal`` if a signal kills the - process. Availability: Unix, Windows. + process. + + Availability: Unix, Windows. .. versionadded:: 1.6 @@ -1805,6 +1967,7 @@ is similar to :const:`P_NOWAIT`, but the new process is detached from the console of the calling process. If :const:`P_OVERLAY` is used, the current process will be replaced; the :func:`spawn\*` function will not return. + Availability: Windows. .. versionadded:: 1.6 @@ -1830,7 +1993,9 @@ directory. If you want to use an absolute path, make sure the first character is not a slash (``'/'``); the underlying Win32 :cfunc:`ShellExecute` function doesn't work if it is. Use the :func:`os.path.normpath` function to ensure that - the path is properly encoded for Win32. Availability: Windows. + the path is properly encoded for Win32. + + Availability: Windows. .. versionadded:: 2.0 @@ -1857,22 +2022,24 @@ the command run; on systems using a non-native shell, consult your shell documentation. - Availability: Unix, Windows. - The :mod:`subprocess` module provides more powerful facilities for spawning new processes and retrieving their results; using that module is preferable to using this function. Use the :mod:`subprocess` module. Check especially the :ref:`subprocess-replacements` section. + Availability: Unix, Windows. + .. function:: times() - Return a 5-tuple of floating point numbers indicating accumulated (processor or - other) times, in seconds. The items are: user time, system time, children's - user time, children's system time, and elapsed real time since a fixed point in - the past, in that order. See the Unix manual page :manpage:`times(2)` or the - corresponding Windows Platform API documentation. Availability: Unix, - Windows. On Windows, only the first two items are filled, the others are zero. + Return a 5-tuple of floating point numbers indicating accumulated (processor + or other) times, in seconds. The items are: user time, system time, + children's user time, children's system time, and elapsed real time since a + fixed point in the past, in that order. See the Unix manual page + :manpage:`times(2)` or the corresponding Windows Platform API documentation. + On Windows, only the first two items are filled, the others are zero. + + Availability: Unix, Windows .. function:: wait() @@ -1881,7 +2048,9 @@ and exit status indication: a 16-bit number, whose low byte is the signal number that killed the process, and whose high byte is the exit status (if the signal number is zero); the high bit of the low byte is set if a core file was - produced. Availability: Unix. + produced. + + Availability: Unix. .. function:: waitpid(pid, options) @@ -1919,6 +2088,7 @@ resource usage information is returned. Refer to :mod:`resource`.\ :func:`getrusage` for details on resource usage information. The option argument is the same as that provided to :func:`waitpid` and :func:`wait4`. + Availability: Unix. .. versionadded:: 2.5 @@ -1930,7 +2100,9 @@ process id, exit status indication, and resource usage information is returned. Refer to :mod:`resource`.\ :func:`getrusage` for details on resource usage information. The arguments to :func:`wait4` are the same as those provided to - :func:`waitpid`. Availability: Unix. + :func:`waitpid`. + + Availability: Unix. .. versionadded:: 2.5 @@ -1939,14 +2111,16 @@ The option for :func:`waitpid` to return immediately if no child process status is available immediately. The function returns ``(0, 0)`` in this case. + Availability: Unix. .. data:: WCONTINUED This option causes child processes to be reported if they have been continued - from a job control stop since their status was last reported. Availability: Some - Unix systems. + from a job control stop since their status was last reported. + + Availability: Some Unix systems. .. versionadded:: 2.3 @@ -1954,8 +2128,9 @@ .. data:: WUNTRACED This option causes child processes to be reported if they have been stopped but - their current state has not been reported since they were stopped. Availability: - Unix. + their current state has not been reported since they were stopped. + + Availability: Unix. .. versionadded:: 2.3 @@ -1967,7 +2142,9 @@ .. function:: WCOREDUMP(status) Return ``True`` if a core dump was generated for the process, otherwise - return ``False``. Availability: Unix. + return ``False``. + + Availability: Unix. .. versionadded:: 2.3 @@ -1975,7 +2152,9 @@ .. function:: WIFCONTINUED(status) Return ``True`` if the process has been continued from a job control stop, - otherwise return ``False``. Availability: Unix. + otherwise return ``False``. + + Availability: Unix. .. versionadded:: 2.3 @@ -1983,36 +2162,47 @@ .. function:: WIFSTOPPED(status) Return ``True`` if the process has been stopped, otherwise return - ``False``. Availability: Unix. + ``False``. + + Availability: Unix. .. function:: WIFSIGNALED(status) Return ``True`` if the process exited due to a signal, otherwise return - ``False``. Availability: Unix. + ``False``. + + Availability: Unix. .. function:: WIFEXITED(status) Return ``True`` if the process exited using the :manpage:`exit(2)` system call, - otherwise return ``False``. Availability: Unix. + otherwise return ``False``. + + Availability: Unix. .. function:: WEXITSTATUS(status) If ``WIFEXITED(status)`` is true, return the integer parameter to the :manpage:`exit(2)` system call. Otherwise, the return value is meaningless. + Availability: Unix. .. function:: WSTOPSIG(status) - Return the signal which caused the process to stop. Availability: Unix. + Return the signal which caused the process to stop. + + Availability: Unix. .. function:: WTERMSIG(status) - Return the signal which caused the process to exit. Availability: Unix. + Return the signal which caused the process to exit. + + Availability: Unix. .. _os-path: @@ -2029,8 +2219,7 @@ Unix 95, Unix 98, and others). Some platforms define additional names as well. The names known to the host operating system are given as the keys of the ``confstr_names`` dictionary. For configuration variables not included in that - mapping, passing an integer for *name* is also accepted. Availability: - Unix. + mapping, passing an integer for *name* is also accepted. If the configuration value specified by *name* isn't defined, ``None`` is returned. @@ -2040,19 +2229,25 @@ included in ``confstr_names``, an :exc:`OSError` is raised with :const:`errno.EINVAL` for the error number. + Availability: Unix + .. data:: confstr_names Dictionary mapping names accepted by :func:`confstr` to the integer values defined for those names by the host operating system. This can be used to - determine the set of names known to the system. Availability: Unix. + determine the set of names known to the system. + + Availability: Unix. .. function:: getloadavg() Return the number of processes in the system run queue averaged over the last 1, 5, and 15 minutes or raises :exc:`OSError` if the load average was - unobtainable. Availability: Unix. + unobtainable. + + Availability: Unix. .. versionadded:: 2.3 @@ -2063,6 +2258,7 @@ specified by *name* isn't defined, ``-1`` is returned. The comments regarding the *name* parameter for :func:`confstr` apply here as well; the dictionary that provides information on the known names is given by ``sysconf_names``. + Availability: Unix. @@ -2070,7 +2266,9 @@ Dictionary mapping names accepted by :func:`sysconf` to the integer values defined for those names by the host operating system. This can be used to - determine the set of names known to the system. Availability: Unix. + determine the set of names known to the system. + + Availability: Unix. The following data values are used to support path manipulation operations. These are defined for all platforms. From python-checkins at python.org Fri May 7 01:20:40 2010 From: python-checkins at python.org (benjamin.peterson) Date: Fri, 7 May 2010 01:20:40 +0200 (CEST) Subject: [Python-checkins] r80899 - in python/branches/release31-maint: Doc/library/os.path.rst Doc/library/os.rst Message-ID: <20100506232040.4F280EE983@mail.python.org> Author: benjamin.peterson Date: Fri May 7 01:20:40 2010 New Revision: 80899 Log: Merged revisions 80897 via svnmerge from svn+ssh://pythondev at svn.python.org/python/branches/py3k ................ r80897 | benjamin.peterson | 2010-05-06 18:03:05 -0500 (Thu, 06 May 2010) | 13 lines Merged revisions 80894,80896 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r80894 | benjamin.peterson | 2010-05-06 17:33:46 -0500 (Thu, 06 May 2010) | 1 line Availability gets its own line ........ r80896 | benjamin.peterson | 2010-05-06 17:49:28 -0500 (Thu, 06 May 2010) | 1 line ensure that availability information is on its own line at the end of the function docs ........ ................ Modified: python/branches/release31-maint/ (props changed) python/branches/release31-maint/Doc/library/os.path.rst python/branches/release31-maint/Doc/library/os.rst Modified: python/branches/release31-maint/Doc/library/os.path.rst ============================================================================== --- python/branches/release31-maint/Doc/library/os.path.rst (original) +++ python/branches/release31-maint/Doc/library/os.path.rst Fri May 7 01:20:40 2010 @@ -223,19 +223,24 @@ Return a relative filepath to *path* either from the current directory or from an optional *start* point. - *start* defaults to :attr:`os.curdir`. Availability: Windows, Unix. + *start* defaults to :attr:`os.curdir`. + + Availability: Windows, Unix. .. function:: samefile(path1, path2) Return ``True`` if both pathname arguments refer to the same file or directory (as indicated by device number and i-node number). Raise an exception if a - :func:`os.stat` call on either pathname fails. Availability: Unix. + :func:`os.stat` call on either pathname fails. + + Availability: Unix. .. function:: sameopenfile(fp1, fp2) Return ``True`` if the file descriptors *fp1* and *fp2* refer to the same file. + Availability: Unix. @@ -244,7 +249,9 @@ Return ``True`` if the stat tuples *stat1* and *stat2* refer to the same file. These structures may have been returned by :func:`fstat`, :func:`lstat`, or :func:`stat`. This function implements the underlying comparison used by - :func:`samefile` and :func:`sameopenfile`. Availability: Unix. + :func:`samefile` and :func:`sameopenfile`. + + Availability: Unix. .. function:: split(path) @@ -293,7 +300,9 @@ Split the pathname *path* into a pair ``(unc, rest)`` so that *unc* is the UNC mount point (such as ``r'\\host\mount'``), if present, and *rest* the rest of the path (such as ``r'\path\file.ext'``). For paths containing drive letters, - *unc* will always be the empty string. Availability: Windows. + *unc* will always be the empty string. + + Availability: Windows. .. data:: supports_unicode_filenames Modified: python/branches/release31-maint/Doc/library/os.rst ============================================================================== --- python/branches/release31-maint/Doc/library/os.rst (original) +++ python/branches/release31-maint/Doc/library/os.rst Fri May 7 01:20:40 2010 @@ -41,6 +41,9 @@ * If not separately noted, all functions that claim "Availability: Unix" are supported on Mac OS X, which builds on a Unix core. +.. Availability notes get their own line and occur at the end of the function +.. documentation. + .. note:: All functions in this module raise :exc:`OSError` in the case of invalid or @@ -139,33 +142,40 @@ .. function:: ctermid() Return the filename corresponding to the controlling terminal of the process. + Availability: Unix. .. function:: getegid() Return the effective group id of the current process. This corresponds to the - "set id" bit on the file being executed in the current process. Availability: - Unix. + "set id" bit on the file being executed in the current process. + + Availability: Unix. .. function:: geteuid() .. index:: single: user; effective id - Return the current process's effective user id. Availability: Unix. + Return the current process's effective user id. + + Availability: Unix. .. function:: getgid() .. index:: single: process; group - Return the real group id of the current process. Availability: Unix. + Return the real group id of the current process. + + Availability: Unix. .. function:: getgroups() Return list of supplemental group ids associated with the current process. + Availability: Unix. @@ -175,48 +185,60 @@ process. For most purposes, it is more useful to use the environment variable :envvar:`LOGNAME` to find out who the user is, or ``pwd.getpwuid(os.getuid())[0]`` to get the login name of the currently - effective user id. Availability: Unix. + effective user id. + + Availability: Unix. .. function:: getpgid(pid) Return the process group id of the process with process id *pid*. If *pid* is 0, - the process group id of the current process is returned. Availability: Unix. + the process group id of the current process is returned. + Availability: Unix. .. function:: getpgrp() .. index:: single: process; group - Return the id of the current process group. Availability: Unix. + Return the id of the current process group. + + Availability: Unix. .. function:: getpid() .. index:: single: process; id - Return the current process id. Availability: Unix, Windows. + Return the current process id. + + Availability: Unix, Windows. .. function:: getppid() .. index:: single: process; id of parent - Return the parent's process id. Availability: Unix. + Return the parent's process id. + + Availability: Unix. .. function:: getuid() .. index:: single: user; id - Return the current process's user id. Availability: Unix. + Return the current process's user id. + + Availability: Unix. .. function:: getenv(varname[, value]) Return the value of the environment variable *varname* if it exists, or *value* - if it doesn't. *value* defaults to ``None``. Availability: most flavors of - Unix, Windows. + if it doesn't. *value* defaults to ``None``. + + Availability: most flavors of Unix, Windows. .. function:: putenv(varname, value) @@ -225,8 +247,9 @@ Set the environment variable named *varname* to the string *value*. Such changes to the environment affect subprocesses started with :func:`os.system`, - :func:`popen` or :func:`fork` and :func:`execv`. Availability: most flavors of - Unix, Windows. + :func:`popen` or :func:`fork` and :func:`execv`. + + Availability: most flavors of Unix, Windows. .. note:: @@ -241,17 +264,23 @@ .. function:: setegid(egid) - Set the current process's effective group id. Availability: Unix. + Set the current process's effective group id. + + Availability: Unix. .. function:: seteuid(euid) - Set the current process's effective user id. Availability: Unix. + Set the current process's effective user id. + + Availability: Unix. .. function:: setgid(gid) - Set the current process' group id. Availability: Unix. + Set the current process' group id. + + Availability: Unix. .. function:: setgroups(groups) @@ -259,6 +288,7 @@ Set the list of supplemental group ids associated with the current process to *groups*. *groups* must be a sequence, and each element must be an integer identifying a group. This operation is typically available only to the superuser. + Availability: Unix. @@ -266,6 +296,7 @@ Call the system call :cfunc:`setpgrp` or :cfunc:`setpgrp(0, 0)` depending on which version is implemented (if any). See the Unix manual for the semantics. + Availability: Unix. @@ -273,28 +304,37 @@ Call the system call :cfunc:`setpgid` to set the process group id of the process with id *pid* to the process group with id *pgrp*. See the Unix manual - for the semantics. Availability: Unix. + for the semantics. + + Availability: Unix. .. function:: setreuid(ruid, euid) - Set the current process's real and effective user ids. Availability: Unix. + + Set the current process's real and effective user ids. + + Availability: Unix. .. function:: setregid(rgid, egid) - Set the current process's real and effective group ids. Availability: Unix. + Set the current process's real and effective group ids. + + Availability: Unix. .. function:: getsid(pid) Call the system call :cfunc:`getsid`. See the Unix manual for the semantics. + Availability: Unix. .. function:: setsid() Call the system call :cfunc:`setsid`. See the Unix manual for the semantics. + Availability: Unix. @@ -302,7 +342,9 @@ .. index:: single: user; id, setting - Set the current process's user id. Availability: Unix. + Set the current process's user id. + + Availability: Unix. .. placed in this section since it relates to errno.... a little weak @@ -310,13 +352,16 @@ Return the error message corresponding to the error code in *code*. On platforms where :cfunc:`strerror` returns ``NULL`` when given an unknown - error number, :exc:`ValueError` is raised. Availability: Unix, Windows. + error number, :exc:`ValueError` is raised. + + Availability: Unix, Windows. .. function:: umask(mask) - Set the current numeric umask and return the previous umask. Availability: - Unix, Windows. + Set the current numeric umask and return the previous umask. + + Availability: Unix, Windows. .. function:: uname() @@ -330,8 +375,9 @@ machine)``. Some systems truncate the nodename to 8 characters or to the leading component; a better way to get the hostname is :func:`socket.gethostname` or even - ``socket.gethostbyaddr(socket.gethostname())``. Availability: recent flavors of - Unix. + ``socket.gethostbyaddr(socket.gethostname())``. + + Availability: recent flavors of Unix. .. function:: unsetenv(varname) @@ -340,13 +386,15 @@ Unset (delete) the environment variable named *varname*. Such changes to the environment affect subprocesses started with :func:`os.system`, :func:`popen` or - :func:`fork` and :func:`execv`. Availability: most flavors of Unix, Windows. + :func:`fork` and :func:`execv`. When :func:`unsetenv` is supported, deletion of items in ``os.environ`` is automatically translated into a corresponding call to :func:`unsetenv`; however, calls to :func:`unsetenv` don't update ``os.environ``, so it is actually preferable to delete items of ``os.environ``. + Availability: most flavors of Unix, Windows. + .. _os-newstreams: @@ -362,7 +410,7 @@ Return an open file object connected to the file descriptor *fd*. The *mode* and *bufsize* arguments have the same meaning as the corresponding arguments to - the built-in :func:`open` function. Availability: Unix, Windows. + the built-in :func:`open` function. When specified, the *mode* argument must start with one of the letters ``'r'``, ``'w'``, or ``'a'``, otherwise a :exc:`ValueError` is raised. @@ -371,6 +419,8 @@ set on the file descriptor (which the :cfunc:`fdopen` implementation already does on most platforms). + Availability: Unix, Windows. + .. _os-fd-ops: @@ -389,7 +439,9 @@ .. function:: close(fd) - Close file descriptor *fd*. Availability: Unix, Windows. + Close file descriptor *fd*. + + Availability: Unix, Windows. .. note:: @@ -402,7 +454,7 @@ .. function:: closerange(fd_low, fd_high) Close all file descriptors from *fd_low* (inclusive) to *fd_high* (exclusive), - ignoring errors. Availability: Unix, Windows. Equivalent to:: + ignoring errors. Equivalent to:: for fd in range(fd_low, fd_high): try: @@ -410,6 +462,8 @@ except OSError: pass + Availability: Unix, Windows. + .. function:: device_encoding(fd) @@ -419,33 +473,40 @@ .. function:: dup(fd) - Return a duplicate of file descriptor *fd*. Availability: Unix, - Windows. + Return a duplicate of file descriptor *fd*. + + Availability: Unix, Windows. .. function:: dup2(fd, fd2) Duplicate file descriptor *fd* to *fd2*, closing the latter first if necessary. + Availability: Unix, Windows. .. function:: fchmod(fd, mode) Change the mode of the file given by *fd* to the numeric *mode*. See the docs - for :func:`chmod` for possible values of *mode*. Availability: Unix. + for :func:`chmod` for possible values of *mode*. + + Availability: Unix. .. function:: fchown(fd, uid, gid) Change the owner and group id of the file given by *fd* to the numeric *uid* and *gid*. To leave one of the ids unchanged, set it to -1. + Availability: Unix. .. function:: fdatasync(fd) Force write of file with filedescriptor *fd* to disk. Does not force update of - metadata. Availability: Unix. + metadata. + + Availability: Unix. .. note:: This function is not available on MacOS. @@ -460,24 +521,28 @@ additional names as well. The names known to the host operating system are given in the ``pathconf_names`` dictionary. For configuration variables not included in that mapping, passing an integer for *name* is also accepted. - Availability: Unix. If *name* is a string and is not known, :exc:`ValueError` is raised. If a specific value for *name* is not supported by the host system, even if it is included in ``pathconf_names``, an :exc:`OSError` is raised with :const:`errno.EINVAL` for the error number. + Availability: Unix. + .. function:: fstat(fd) - Return status for file descriptor *fd*, like :func:`stat`. Availability: - Unix, Windows. + Return status for file descriptor *fd*, like :func:`stat`. + + Availability: Unix, Windows. .. function:: fstatvfs(fd) Return information about the filesystem containing the file associated with file - descriptor *fd*, like :func:`statvfs`. Availability: Unix. + descriptor *fd*, like :func:`statvfs`. + + Availability: Unix. .. function:: fsync(fd) @@ -487,19 +552,25 @@ If you're starting with a Python file object *f*, first do ``f.flush()``, and then do ``os.fsync(f.fileno())``, to ensure that all internal buffers associated - with *f* are written to disk. Availability: Unix, Windows. + with *f* are written to disk. + + Availability: Unix, and Windows. .. function:: ftruncate(fd, length) Truncate the file corresponding to file descriptor *fd*, so that it is at most - *length* bytes in size. Availability: Unix. + *length* bytes in size. + + Availability: Unix. .. function:: isatty(fd) Return ``True`` if the file descriptor *fd* is open and connected to a - tty(-like) device, else ``False``. Availability: Unix. + tty(-like) device, else ``False``. + + Availability: Unix. .. function:: lseek(fd, pos, how) @@ -508,7 +579,9 @@ by *how*: :const:`SEEK_SET` or ``0`` to set the position relative to the beginning of the file; :const:`SEEK_CUR` or ``1`` to set it relative to the current position; :const:`os.SEEK_END` or ``2`` to set it relative to the end of - the file. Availability: Unix, Windows. + the file. + + Availability: Unix, Windows. .. function:: open(file, flags[, mode]) @@ -516,17 +589,19 @@ Open the file *file* and set various flags according to *flags* and possibly its mode according to *mode*. The default *mode* is ``0o777`` (octal), and the current umask value is first masked out. Return the file descriptor for - the newly opened file. Availability: Unix, Windows. + the newly opened file. For a description of the flag and mode values, see the C run-time documentation; flag constants (like :const:`O_RDONLY` and :const:`O_WRONLY`) are defined in this module too (see below). + Availability: Unix, Windows. + .. note:: This function is intended for low-level I/O. For normal usage, use the built-in function :func:`open`, which returns a "file object" with - :meth:`~file.read` and :meth:`~file.write` methods (and many more). To + :meth:`~file.read` and :meth:`~file.wprite` methods (and many more). To wrap a file descriptor in a "file object", use :func:`fdopen`. @@ -536,21 +611,26 @@ Open a new pseudo-terminal pair. Return a pair of file descriptors ``(master, slave)`` for the pty and the tty, respectively. For a (slightly) more portable - approach, use the :mod:`pty` module. Availability: some flavors of - Unix. + approach, use the :mod:`pty` module. + + Availability: some flavors of Unix. .. function:: pipe() Create a pipe. Return a pair of file descriptors ``(r, w)`` usable for reading - and writing, respectively. Availability: Unix, Windows. + and writing, respectively. + + Availability: Unix, Windows. .. function:: read(fd, n) Read at most *n* bytes from file descriptor *fd*. Return a bytestring containing the bytes read. If the end of the file referred to by *fd* has been reached, an - empty bytes object is returned. Availability: Unix, Windows. + empty bytes object is returned. + + Availability: Unix, Windows. .. note:: @@ -564,26 +644,34 @@ .. function:: tcgetpgrp(fd) Return the process group associated with the terminal given by *fd* (an open - file descriptor as returned by :func:`os.open`). Availability: Unix. + file descriptor as returned by :func:`os.open`). + + Availability: Unix. .. function:: tcsetpgrp(fd, pg) Set the process group associated with the terminal given by *fd* (an open file - descriptor as returned by :func:`os.open`) to *pg*. Availability: Unix. + descriptor as returned by :func:`os.open`) to *pg*. + + Availability: Unix. .. function:: ttyname(fd) Return a string which specifies the terminal device associated with file descriptor *fd*. If *fd* is not associated with a terminal device, an - exception is raised. Availability: Unix. + exception is raised. + + Availability: Unix. .. function:: write(fd, str) Write the bytestring in *str* to file descriptor *fd*. Return the number of - bytes actually written. Availability: Unix, Windows. + bytes actually written. + + Availability: Unix, Windows. .. note:: @@ -666,7 +754,9 @@ can be the inclusive OR of one or more of :const:`R_OK`, :const:`W_OK`, and :const:`X_OK` to test permissions. Return :const:`True` if access is allowed, :const:`False` if not. See the Unix man page :manpage:`access(2)` for more - information. Availability: Unix, Windows. + information. + + Availability: Unix, Windows. .. note:: @@ -710,25 +800,31 @@ .. index:: single: directory; changing - Change the current working directory to *path*. Availability: Unix, - Windows. + Change the current working directory to *path*. + + Availability: Unix, Windows. .. function:: fchdir(fd) Change the current working directory to the directory represented by the file descriptor *fd*. The descriptor must refer to an opened directory, not an open - file. Availability: Unix. + file. + + Availability: Unix. .. function:: getcwd() Return a string representing the current working directory. + Availability: Unix, Windows. + .. function:: getcwdb() Return a bytestring representing the current working directory. + Availability: Unix, Windows. @@ -796,32 +892,41 @@ .. function:: chown(path, uid, gid) Change the owner and group id of *path* to the numeric *uid* and *gid*. To leave - one of the ids unchanged, set it to -1. Availability: Unix. + one of the ids unchanged, set it to -1. + + Availability: Unix. .. function:: lchflags(path, flags) Set the flags of *path* to the numeric *flags*, like :func:`chflags`, but do not - follow symbolic links. Availability: Unix. + follow symbolic links. + + Availability: Unix. .. function:: lchmod(path, mode) Change the mode of *path* to the numeric *mode*. If path is a symlink, this affects the symlink rather than the target. See the docs for :func:`chmod` - for possible values of *mode*. Availability: Unix. + for possible values of *mode*. + + Availability: Unix. .. function:: lchown(path, uid, gid) Change the owner and group id of *path* to the numeric *uid* and *gid*. This - function will not follow symbolic links. Availability: Unix. + function will not follow symbolic links. + + Availability: Unix. .. function:: link(source, link_name) - Create a hard link pointing to *source* named *link_name*. Availability: - Unix. + Create a hard link pointing to *source* named *link_name*. + + Availability: Unix. .. function:: listdir(path) @@ -829,11 +934,12 @@ Return a list containing the names of the entries in the directory given by *path*. The list is in arbitrary order. It does not include the special entries ``'.'`` and ``'..'`` even if they are present in the directory. - Availability: Unix, Windows. This function can be called with a bytes or string argument, and returns filenames of the same datatype. + Availability: Unix, Windows. + .. function:: lstat(path) @@ -846,7 +952,7 @@ Create a FIFO (a named pipe) named *path* with numeric mode *mode*. The default *mode* is ``0o666`` (octal). The current umask value is first masked - out from the mode. Availability: Unix. + out from the mode. FIFOs are pipes that can be accessed like regular files. FIFOs exist until they are deleted (for example with :func:`os.unlink`). Generally, FIFOs are used as @@ -854,6 +960,8 @@ FIFO for reading, and the client opens it for writing. Note that :func:`mkfifo` doesn't open the FIFO --- it just creates the rendezvous point. + Availability: Unix. + .. function:: mknod(filename[, mode=0o600, device]) @@ -888,11 +996,13 @@ Create a directory named *path* with numeric mode *mode*. The default *mode* is ``0o777`` (octal). On some systems, *mode* is ignored. Where it is used, - the current umask value is first masked out. Availability: Unix, Windows. + the current umask value is first masked out. It is also possible to create temporary directories; see the :mod:`tempfile` module's :func:`tempfile.mkdtemp` function. + Availability: Unix, Windows. + .. function:: makedirs(path[, mode]) @@ -923,13 +1033,14 @@ additional names as well. The names known to the host operating system are given in the ``pathconf_names`` dictionary. For configuration variables not included in that mapping, passing an integer for *name* is also accepted. - Availability: Unix. If *name* is a string and is not known, :exc:`ValueError` is raised. If a specific value for *name* is not supported by the host system, even if it is included in ``pathconf_names``, an :exc:`OSError` is raised with :const:`errno.EINVAL` for the error number. + Availability: Unix. + .. data:: pathconf_names @@ -960,8 +1071,9 @@ the :func:`unlink` function documented below. On Windows, attempting to remove a file that is in use causes an exception to be raised; on Unix, the directory entry is removed but the storage allocated to the file is not made - available until the original file is no longer in use. Availability: Unix, - Windows. + available until the original file is no longer in use. + + Availability: Unix, Windows. .. function:: removedirs(path) @@ -987,7 +1099,9 @@ the renaming will be an atomic operation (this is a POSIX requirement). On Windows, if *dst* already exists, :exc:`OSError` will be raised even if it is a file; there may be no way to implement an atomic rename when *dst* names an - existing file. Availability: Unix, Windows. + existing file. + + Availability: Unix, Windows. .. function:: renames(old, new) @@ -1007,8 +1121,9 @@ Remove (delete) the directory *path*. Only works when the directory is empty, otherwise, :exc:`OSError` is raised. In order to remove whole - directory trees, :func:`shutil.rmtree` can be used. Availability: Unix, - Windows. + directory trees, :func:`shutil.rmtree` can be used. + + Availability: Unix, Windows. .. function:: stat(path) @@ -1099,20 +1214,25 @@ correspond to the members of the :ctype:`statvfs` structure, namely: :attr:`f_bsize`, :attr:`f_frsize`, :attr:`f_blocks`, :attr:`f_bfree`, :attr:`f_bavail`, :attr:`f_files`, :attr:`f_ffree`, :attr:`f_favail`, - :attr:`f_flag`, :attr:`f_namemax`. Availability: Unix. + :attr:`f_flag`, :attr:`f_namemax`. + + Availability: Unix. .. function:: symlink(source, link_name) - Create a symbolic link pointing to *source* named *link_name*. Availability: - Unix. + Create a symbolic link pointing to *source* named *link_name*. + + Availability: Unix. .. function:: unlink(path) Remove (delete) the file *path*. This is the same function as :func:`remove`; the :func:`unlink` name is its traditional Unix - name. Availability: Unix, Windows. + name. + + Availability: Unix, Windows. .. function:: utime(path, times) @@ -1236,6 +1356,7 @@ behavior is to produce a core dump; on Windows, the process immediately returns an exit code of ``3``. Be aware that programs which use :func:`signal.signal` to register a handler for :const:`SIGABRT` will behave differently. + Availability: Unix, Windows. @@ -1291,7 +1412,9 @@ .. function:: _exit(n) Exit to the system with status *n*, without calling cleanup handlers, flushing - stdio buffers, etc. Availability: Unix, Windows. + stdio buffers, etc. + + Availability: Unix, Windows. .. note:: @@ -1311,69 +1434,88 @@ .. data:: EX_OK - Exit code that means no error occurred. Availability: Unix. + Exit code that means no error occurred. + + Availability: Unix. .. data:: EX_USAGE Exit code that means the command was used incorrectly, such as when the wrong - number of arguments are given. Availability: Unix. + number of arguments are given. + + Availability: Unix. .. data:: EX_DATAERR - Exit code that means the input data was incorrect. Availability: Unix. + Exit code that means the input data was incorrect. + + Availability: Unix. .. data:: EX_NOINPUT Exit code that means an input file did not exist or was not readable. + Availability: Unix. .. data:: EX_NOUSER - Exit code that means a specified user did not exist. Availability: Unix. + Exit code that means a specified user did not exist. + + Availability: Unix. .. data:: EX_NOHOST - Exit code that means a specified host did not exist. Availability: Unix. + Exit code that means a specified host did not exist. + + Availability: Unix. .. data:: EX_UNAVAILABLE - Exit code that means that a required service is unavailable. Availability: - Unix. + Exit code that means that a required service is unavailable. + + Availability: Unix. .. data:: EX_SOFTWARE - Exit code that means an internal software error was detected. Availability: - Unix. + Exit code that means an internal software error was detected. + + Availability: Unix. .. data:: EX_OSERR Exit code that means an operating system error was detected, such as the - inability to fork or create a pipe. Availability: Unix. + inability to fork or create a pipe. + + Availability: Unix. .. data:: EX_OSFILE Exit code that means some system file did not exist, could not be opened, or had - some other kind of error. Availability: Unix. + some other kind of error. + + Availability: Unix. .. data:: EX_CANTCREAT Exit code that means a user specified output file could not be created. + Availability: Unix. .. data:: EX_IOERR Exit code that means that an error occurred while doing I/O on some file. + Availability: Unix. @@ -1381,31 +1523,39 @@ Exit code that means a temporary failure occurred. This indicates something that may not really be an error, such as a network connection that couldn't be - made during a retryable operation. Availability: Unix. + made during a retryable operation. + + Availability: Unix. .. data:: EX_PROTOCOL Exit code that means that a protocol exchange was illegal, invalid, or not - understood. Availability: Unix. + understood. + + Availability: Unix. .. data:: EX_NOPERM Exit code that means that there were insufficient permissions to perform the - operation (but not intended for file system problems). Availability: Unix. + operation (but not intended for file system problems). + + Availability: Unix. .. data:: EX_CONFIG Exit code that means that some kind of configuration error occurred. + Availability: Unix. .. data:: EX_NOTFOUND - Exit code that means something like "an entry was not found". Availability: - Unix. + Exit code that means something like "an entry was not found". + + Availability: Unix. .. function:: fork() @@ -1426,6 +1576,7 @@ new child's process id in the parent, and *fd* is the file descriptor of the master end of the pseudo-terminal. For a more portable approach, use the :mod:`pty` module. If an error occurs :exc:`OSError` is raised. + Availability: some flavors of Unix. @@ -1446,19 +1597,24 @@ single: process; killing single: process; signalling - Send the signal *sig* to the process group *pgid*. Availability: Unix. + Send the signal *sig* to the process group *pgid*. + + Availability: Unix. .. function:: nice(increment) Add *increment* to the process's "niceness". Return the new niceness. + Availability: Unix. .. function:: plock(op) Lock program segments into memory. The value of *op* (defined in - ````) determines which segments are locked. Availability: Unix. + ````) determines which segments are locked. + + Availability: Unix. .. function:: popen(...) @@ -1537,7 +1693,9 @@ Possible values for the *mode* parameter to the :func:`spawn\*` family of functions. If either of these values is given, the :func:`spawn\*` functions will return as soon as the new process has been created, with the process id as - the return value. Availability: Unix, Windows. + the return value. + + Availability: Unix, Windows. .. data:: P_WAIT @@ -1546,7 +1704,9 @@ functions. If this is given as *mode*, the :func:`spawn\*` functions will not return until the new process has run to completion and will return the exit code of the process the run is successful, or ``-signal`` if a signal kills the - process. Availability: Unix, Windows. + process. + + Availability: Unix, Windows. .. data:: P_DETACH @@ -1557,6 +1717,7 @@ is similar to :const:`P_NOWAIT`, but the new process is detached from the console of the calling process. If :const:`P_OVERLAY` is used, the current process will be replaced; the :func:`spawn\*` function will not return. + Availability: Windows. @@ -1580,7 +1741,9 @@ directory. If you want to use an absolute path, make sure the first character is not a slash (``'/'``); the underlying Win32 :cfunc:`ShellExecute` function doesn't work if it is. Use the :func:`os.path.normpath` function to ensure that - the path is properly encoded for Win32. Availability: Windows. + the path is properly encoded for Win32. + + Availability: Windows. .. function:: system(command) @@ -1602,22 +1765,24 @@ the command run; on systems using a non-native shell, consult your shell documentation. - Availability: Unix, Windows. - The :mod:`subprocess` module provides more powerful facilities for spawning new processes and retrieving their results; using that module is preferable to using this function. Use the :mod:`subprocess` module. Check especially the :ref:`subprocess-replacements` section. + Availability: Unix, Windows. + .. function:: times() - Return a 5-tuple of floating point numbers indicating accumulated (processor or - other) times, in seconds. The items are: user time, system time, children's - user time, children's system time, and elapsed real time since a fixed point in - the past, in that order. See the Unix manual page :manpage:`times(2)` or the - corresponding Windows Platform API documentation. Availability: Unix, - Windows. On Windows, only the first two items are filled, the others are zero. + Return a 5-tuple of floating point numbers indicating accumulated (processor + or other) times, in seconds. The items are: user time, system time, + children's user time, children's system time, and elapsed real time since a + fixed point in the past, in that order. See the Unix manual page + :manpage:`times(2)` or the corresponding Windows Platform API documentation. + On Windows, only the first two items are filled, the others are zero. + + Availability: Unix, Windows .. function:: wait() @@ -1626,7 +1791,9 @@ and exit status indication: a 16-bit number, whose low byte is the signal number that killed the process, and whose high byte is the exit status (if the signal number is zero); the high bit of the low byte is set if a core file was - produced. Availability: Unix. + produced. + + Availability: Unix. .. function:: waitpid(pid, options) @@ -1664,6 +1831,7 @@ resource usage information is returned. Refer to :mod:`resource`.\ :func:`getrusage` for details on resource usage information. The option argument is the same as that provided to :func:`waitpid` and :func:`wait4`. + Availability: Unix. @@ -1673,28 +1841,33 @@ process id, exit status indication, and resource usage information is returned. Refer to :mod:`resource`.\ :func:`getrusage` for details on resource usage information. The arguments to :func:`wait4` are the same as those provided to - :func:`waitpid`. Availability: Unix. + :func:`waitpid`. + + Availability: Unix. .. data:: WNOHANG The option for :func:`waitpid` to return immediately if no child process status is available immediately. The function returns ``(0, 0)`` in this case. + Availability: Unix. .. data:: WCONTINUED This option causes child processes to be reported if they have been continued - from a job control stop since their status was last reported. Availability: Some - Unix systems. + from a job control stop since their status was last reported. + + Availability: Some Unix systems. .. data:: WUNTRACED This option causes child processes to be reported if they have been stopped but - their current state has not been reported since they were stopped. Availability: - Unix. + their current state has not been reported since they were stopped. + + Availability: Unix. The following functions take a process status code as returned by @@ -1704,48 +1877,63 @@ .. function:: WCOREDUMP(status) Return ``True`` if a core dump was generated for the process, otherwise - return ``False``. Availability: Unix. + return ``False``. + + Availability: Unix. .. function:: WIFCONTINUED(status) Return ``True`` if the process has been continued from a job control stop, - otherwise return ``False``. Availability: Unix. + otherwise return ``False``. + + Availability: Unix. .. function:: WIFSTOPPED(status) Return ``True`` if the process has been stopped, otherwise return - ``False``. Availability: Unix. + ``False``. + + Availability: Unix. .. function:: WIFSIGNALED(status) Return ``True`` if the process exited due to a signal, otherwise return - ``False``. Availability: Unix. + ``False``. + + Availability: Unix. .. function:: WIFEXITED(status) Return ``True`` if the process exited using the :manpage:`exit(2)` system call, - otherwise return ``False``. Availability: Unix. + otherwise return ``False``. + + Availability: Unix. .. function:: WEXITSTATUS(status) If ``WIFEXITED(status)`` is true, return the integer parameter to the :manpage:`exit(2)` system call. Otherwise, the return value is meaningless. + Availability: Unix. .. function:: WSTOPSIG(status) - Return the signal which caused the process to stop. Availability: Unix. + Return the signal which caused the process to stop. + + Availability: Unix. .. function:: WTERMSIG(status) - Return the signal which caused the process to exit. Availability: Unix. + Return the signal which caused the process to exit. + + Availability: Unix. .. _os-path: @@ -1762,8 +1950,7 @@ Unix 95, Unix 98, and others). Some platforms define additional names as well. The names known to the host operating system are given as the keys of the ``confstr_names`` dictionary. For configuration variables not included in that - mapping, passing an integer for *name* is also accepted. Availability: - Unix. + mapping, passing an integer for *name* is also accepted. If the configuration value specified by *name* isn't defined, ``None`` is returned. @@ -1773,19 +1960,25 @@ included in ``confstr_names``, an :exc:`OSError` is raised with :const:`errno.EINVAL` for the error number. + Availability: Unix + .. data:: confstr_names Dictionary mapping names accepted by :func:`confstr` to the integer values defined for those names by the host operating system. This can be used to - determine the set of names known to the system. Availability: Unix. + determine the set of names known to the system. + + Availability: Unix. .. function:: getloadavg() Return the number of processes in the system run queue averaged over the last 1, 5, and 15 minutes or raises :exc:`OSError` if the load average was - unobtainable. Availability: Unix. + unobtainable. + + Availability: Unix. .. function:: sysconf(name) @@ -1794,6 +1987,7 @@ specified by *name* isn't defined, ``-1`` is returned. The comments regarding the *name* parameter for :func:`confstr` apply here as well; the dictionary that provides information on the known names is given by ``sysconf_names``. + Availability: Unix. @@ -1801,7 +1995,9 @@ Dictionary mapping names accepted by :func:`sysconf` to the integer values defined for those names by the host operating system. This can be used to - determine the set of names known to the system. Availability: Unix. + determine the set of names known to the system. + + Availability: Unix. The following data values are used to support path manipulation operations. These are defined for all platforms. From solipsis at pitrou.net Fri May 7 01:22:53 2010 From: solipsis at pitrou.net (solipsis at pitrou.net) Date: Fri, 7 May 2010 01:22:53 +0200 (CEST) Subject: [Python-checkins] Daily py3k reference leaks (r80883): sum=0 Message-ID: <20100506232253.274C11770A@ns6635.ovh.net> py3k results for svn r80883 (hg cset 89ad31e25a91) -------------------------------------------------- Command line was: ['./python', '-m', 'test.regrtest', '-uall', '-R', '3:3:/home/antoine/py3k/refleaks/reflogClj8GY', '-x'] From python-checkins at python.org Fri May 7 02:41:18 2010 From: python-checkins at python.org (victor.stinner) Date: Fri, 7 May 2010 02:41:18 +0200 (CEST) Subject: [Python-checkins] r80900 - python/branches/py3k/Objects/codeobject.c Message-ID: <20100507004118.415EAEEAD7@mail.python.org> Author: victor.stinner Date: Fri May 7 02:41:18 2010 New Revision: 80900 Log: code_repr(): use %U to format the filename Avoid useless unicode decoding/recoding of the filename. Modified: python/branches/py3k/Objects/codeobject.c Modified: python/branches/py3k/Objects/codeobject.c ============================================================================== --- python/branches/py3k/Objects/codeobject.c (original) +++ python/branches/py3k/Objects/codeobject.c Fri May 7 02:41:18 2010 @@ -340,16 +340,20 @@ static PyObject * code_repr(PyCodeObject *co) { - int lineno = -1; - char *filename = "???"; - + int lineno; if (co->co_firstlineno != 0) lineno = co->co_firstlineno; - if (co->co_filename && PyUnicode_Check(co->co_filename)) - filename = _PyUnicode_AsString(co->co_filename); - return PyUnicode_FromFormat( - "", - co->co_name, co, filename, lineno); + else + lineno = -1; + if (co->co_filename && PyUnicode_Check(co->co_filename)) { + return PyUnicode_FromFormat( + "", + co->co_name, co, co->co_filename, lineno); + } else { + return PyUnicode_FromFormat( + "", + co->co_name, co, lineno); + } } static PyObject * From python-checkins at python.org Fri May 7 02:41:55 2010 From: python-checkins at python.org (victor.stinner) Date: Fri, 7 May 2010 02:41:55 +0200 (CEST) Subject: [Python-checkins] r80901 - python/branches/release31-maint Message-ID: <20100507004155.67620C84C@mail.python.org> Author: victor.stinner Date: Fri May 7 02:41:55 2010 New Revision: 80901 Log: Blocked revisions 80900 via svnmerge ........ r80900 | victor.stinner | 2010-05-07 02:41:18 +0200 (ven., 07 mai 2010) | 4 lines code_repr(): use %U to format the filename Avoid useless unicode decoding/recoding of the filename. ........ Modified: python/branches/release31-maint/ (props changed) From python-checkins at python.org Fri May 7 02:50:12 2010 From: python-checkins at python.org (victor.stinner) Date: Fri, 7 May 2010 02:50:12 +0200 (CEST) Subject: [Python-checkins] r80902 - python/branches/py3k/Objects/moduleobject.c Message-ID: <20100507005012.42C11EE984@mail.python.org> Author: victor.stinner Date: Fri May 7 02:50:12 2010 New Revision: 80902 Log: module_repr(): use %U to format the file name Avoid useless encode/decode of the filename Modified: python/branches/py3k/Objects/moduleobject.c Modified: python/branches/py3k/Objects/moduleobject.c ============================================================================== --- python/branches/py3k/Objects/moduleobject.c (original) +++ python/branches/py3k/Objects/moduleobject.c Fri May 7 02:50:12 2010 @@ -191,8 +191,8 @@ return _PyUnicode_AsString(nameobj); } -const char * -PyModule_GetFilename(PyObject *m) +static PyObject* +module_getfilename(PyObject *m) { PyObject *d; PyObject *fileobj; @@ -208,6 +208,16 @@ PyErr_SetString(PyExc_SystemError, "module filename missing"); return NULL; } + return fileobj; +} + +const char * +PyModule_GetFilename(PyObject *m) +{ + PyObject *fileobj; + fileobj = module_getfilename(m); + if (fileobj == NULL) + return NULL; return _PyUnicode_AsString(fileobj); } @@ -327,19 +337,19 @@ module_repr(PyModuleObject *m) { const char *name; - const char *filename; + PyObject *filename; name = PyModule_GetName((PyObject *)m); if (name == NULL) { PyErr_Clear(); name = "?"; } - filename = PyModule_GetFilename((PyObject *)m); + filename = module_getfilename((PyObject *)m); if (filename == NULL) { PyErr_Clear(); return PyUnicode_FromFormat("", name); } - return PyUnicode_FromFormat("", name, filename); + return PyUnicode_FromFormat("", name, filename); } static int From python-checkins at python.org Fri May 7 02:51:05 2010 From: python-checkins at python.org (victor.stinner) Date: Fri, 7 May 2010 02:51:05 +0200 (CEST) Subject: [Python-checkins] r80903 - python/branches/release31-maint Message-ID: <20100507005105.45F76EEAD7@mail.python.org> Author: victor.stinner Date: Fri May 7 02:51:05 2010 New Revision: 80903 Log: Blocked revisions 80902 via svnmerge ........ r80902 | victor.stinner | 2010-05-07 02:50:12 +0200 (ven., 07 mai 2010) | 4 lines module_repr(): use %U to format the file name Avoid useless encode/decode of the filename ........ Modified: python/branches/release31-maint/ (props changed) From python-checkins at python.org Fri May 7 02:54:14 2010 From: python-checkins at python.org (victor.stinner) Date: Fri, 7 May 2010 02:54:14 +0200 (CEST) Subject: [Python-checkins] r80904 - python/branches/py3k/Lib/test/test_os.py Message-ID: <20100507005414.2CAD9EEADC@mail.python.org> Author: victor.stinner Date: Fri May 7 02:54:14 2010 New Revision: 80904 Log: Fix test_os: os.environb doesn't exist on Windows Modified: python/branches/py3k/Lib/test/test_os.py Modified: python/branches/py3k/Lib/test/test_os.py ============================================================================== --- python/branches/py3k/Lib/test/test_os.py (original) +++ python/branches/py3k/Lib/test/test_os.py Fri May 7 02:54:14 2010 @@ -369,15 +369,17 @@ def setUp(self): self.__save = dict(os.environ) - self.__saveb = dict(os.environb) + if os.name not in ('os2', 'nt'): + self.__saveb = dict(os.environb) for key, value in self._reference().items(): os.environ[key] = value def tearDown(self): os.environ.clear() os.environ.update(self.__save) - os.environb.clear() - os.environb.update(self.__saveb) + if os.name not in ('os2', 'nt'): + os.environb.clear() + os.environb.update(self.__saveb) def _reference(self): return {"KEY1":"VALUE1", "KEY2":"VALUE2", "KEY3":"VALUE3"} From python-checkins at python.org Fri May 7 02:57:12 2010 From: python-checkins at python.org (victor.stinner) Date: Fri, 7 May 2010 02:57:12 +0200 (CEST) Subject: [Python-checkins] r80905 - python/branches/py3k/Lib/test/regrtest.py Message-ID: <20100507005712.6530BE942@mail.python.org> Author: victor.stinner Date: Fri May 7 02:57:12 2010 New Revision: 80905 Log: regrtest.py: disable replace_stdout() on Windows until it is fixed See issue #8533 (problem with newlines on Windows). Modified: python/branches/py3k/Lib/test/regrtest.py Modified: python/branches/py3k/Lib/test/regrtest.py ============================================================================== --- python/branches/py3k/Lib/test/regrtest.py (original) +++ python/branches/py3k/Lib/test/regrtest.py Fri May 7 02:57:12 2010 @@ -733,6 +733,9 @@ def replace_stdout(): """Set stdout encoder error handler to backslashreplace (as stderr error handler) to avoid UnicodeEncodeError when printing a traceback""" + if os.name == "nt": + # Replace sys.stdout breaks the stdout newlines on Windows: issue #8533 + return stdout = sys.stdout sys.stdout = open(stdout.fileno(), 'w', encoding=stdout.encoding, From python-checkins at python.org Fri May 7 02:58:26 2010 From: python-checkins at python.org (victor.stinner) Date: Fri, 7 May 2010 02:58:26 +0200 (CEST) Subject: [Python-checkins] r80906 - in python/branches/release31-maint: Lib/test/regrtest.py Message-ID: <20100507005826.5912FC7CC@mail.python.org> Author: victor.stinner Date: Fri May 7 02:58:26 2010 New Revision: 80906 Log: Merged revisions 80905 via svnmerge from svn+ssh://pythondev at svn.python.org/python/branches/py3k ........ r80905 | victor.stinner | 2010-05-07 02:57:12 +0200 (ven., 07 mai 2010) | 4 lines regrtest.py: disable replace_stdout() on Windows until it is fixed See issue #8533 (problem with newlines on Windows). ........ Modified: python/branches/release31-maint/ (props changed) python/branches/release31-maint/Lib/test/regrtest.py Modified: python/branches/release31-maint/Lib/test/regrtest.py ============================================================================== --- python/branches/release31-maint/Lib/test/regrtest.py (original) +++ python/branches/release31-maint/Lib/test/regrtest.py Fri May 7 02:58:26 2010 @@ -560,6 +560,9 @@ def replace_stdout(): """Set stdout encoder error handler to backslashreplace (as stderr error handler) to avoid UnicodeEncodeError when printing a traceback""" + if os.name == "nt": + # Replace sys.stdout breaks the stdout newlines on Windows: issue #8533 + return stdout = sys.stdout sys.stdout = open(stdout.fileno(), 'w', encoding=stdout.encoding, From python-checkins at python.org Fri May 7 03:45:14 2010 From: python-checkins at python.org (andrew.kuchling) Date: Fri, 7 May 2010 03:45:14 +0200 (CEST) Subject: [Python-checkins] r80907 - python/trunk/Doc/whatsnew/2.7.rst Message-ID: <20100507014514.9044EEE983@mail.python.org> Author: andrew.kuchling Date: Fri May 7 03:45:14 2010 New Revision: 80907 Log: Add a new section on the development plan; add an item Modified: python/trunk/Doc/whatsnew/2.7.rst Modified: python/trunk/Doc/whatsnew/2.7.rst ============================================================================== --- python/trunk/Doc/whatsnew/2.7.rst (original) +++ python/trunk/Doc/whatsnew/2.7.rst Fri May 7 03:45:14 2010 @@ -8,9 +8,7 @@ .. Fix accents on Kristjan Valur Jonsson, Fuerstenau -.. Big jobs: pep 391 -.. Initial section: development plans for 2.x in future -.. Initial section: changes in deprecation warning behaviour +.. Big jobs: pep 391, PyCapsule .. hyperlink all the methods & functions. @@ -62,17 +60,42 @@ release of 2.7 is currently scheduled for July 2010; the detailed schedule is described in :pep:`373`. -Python 2.7 is planned to be the last major release in the 2.x series. -Though more major releases have not been absolutely ruled out, the -Python maintainers are planning to focus more on Python 3.x. Despite -that, it's likely that the 2.7 release will have a longer period of -maintenance compared to earlier 2.x versions. - .. Compare with previous release in 2 - 3 sentences here. add hyperlink when the documentation becomes available online. .. _whatsnew27-python31: +The Future for Python 2.x +========================= + +Python 2.7 is intended to be the last major release in the 2.x series. +Though more major releases have not been absolutely ruled out, the +Python maintainers are planning to focus their efforts on Python 3.x. + +This means that 2.7 will remain in place for a long time, running +production systems that have not been ported to Python 3.x. +Two consequences of the long-term significance of 2.7 are: + +* It's very likely the 2.7 release will have a longer period of + maintenance compared to earlier 2.x versions. Python 2.7 will + continue to be maintained while the transition to 3.x is in + progress, and that transition will itself be lengthy. Most 2.x + versions are maintained for about 4 years, from the first to the + last bugfix release; patchlevel releases for Python 2.7 will + probably be made for at least 6 years. + +* Because 2.7 will be running production applications, a policy + decision was made to silence warnings only of interest to developers + by default. Silencing :exc:`DeprecationWarning` and its descendants + prevents users from seeing warnings triggered by an application. + (Carried out in :issue:`7319`.) + + You can re-enable display of :exc:`DeprecationWarning` messages by + running Python with the :option:`-Wdefault` (short form: + :option:`-Wd`) switch, or you can add + ``warnings.simplefilter('default')`` to your code. + + Python 3.1 Features ======================= @@ -181,11 +204,6 @@ deletion doesn't have to traverse the entire linked list and therefore remains O(1). -.. XXX check O(1)-ness with Raymond -.. Also check if the 'somenamedtuple' in the collection module should -.. be replaced/removed in order to use -.. :meth:`~collections.namedtuple._asdict()` (see below) - The standard library now supports use of ordered dictionaries in several modules. @@ -364,10 +382,17 @@ XXX describe an example. -Two smaller enhancements to the logging module are: +Three smaller enhancements to the :mod:`logging` module, all +implemented by Vinay Sajip, are: .. rev79293 +* The :class:`~logging.handlers.SysLogHandler` class now supports + syslogging over TCP. The constructor has a *socktype* parameter + giving the type of socket to use, either :const:`socket.SOCK_DGRAM` + for UDP or :const:`socket.SOCK_STREAM` for TCP. The default + protocol remains UDP. + * :class:`Logger` instances gained a :meth:`getChild` method that retrieves a descendant logger using a relative path. For example, once you retrieve a logger by doing ``log = getLogger('app')``, @@ -950,6 +975,30 @@ length as the read-only :attr:`~collections.deque.maxlen` attribute. (Both features added by Raymond Hettinger.) +* Constructors for the parsing classes in the :mod:`ConfigParser` module now + take a *allow_no_value* parameter, defaulting to false; if true, + options without values will be allowed. For example:: + + >>> import ConfigParser, StringIO + >>> sample_config = """ + ... [mysqld] + ... user = mysql + ... pid-file = /var/run/mysqld/mysqld.pid + ... skip-bdb + ... """ + >>> config = ConfigParser.RawConfigParser(allow_no_value=True) + >>> config.readfp(StringIO.StringIO(sample_config)) + >>> config.get('mysqld', 'user') + 'mysql' + >>> print config.get('mysqld', 'skip-bdb') + None + >>> print config.get('mysqld', 'unknown') + Traceback (most recent call last): + ... + ConfigParser.NoOptionError: No option 'unknown' in section: 'mysqld' + + (Contributed by Mats Kindahl; :issue:`7005`.) + * Deprecated function: :func:`contextlib.nested`, which allows handling more than one context manager with a single :keyword:`with` statement, has been deprecated, because :keyword:`with` supports From python-checkins at python.org Fri May 7 06:07:30 2010 From: python-checkins at python.org (senthil.kumaran) Date: Fri, 7 May 2010 06:07:30 +0200 (CEST) Subject: [Python-checkins] r80908 - python/trunk/Lib/test/test_urlparse.py Message-ID: <20100507040730.34BE0EEA25@mail.python.org> Author: senthil.kumaran Date: Fri May 7 06:07:29 2010 New Revision: 80908 Log: Testsuite for RFC3986 based parsing scenario. Related Issue1462525. Modified: python/trunk/Lib/test/test_urlparse.py Modified: python/trunk/Lib/test/test_urlparse.py ============================================================================== --- python/trunk/Lib/test/test_urlparse.py (original) +++ python/trunk/Lib/test/test_urlparse.py Fri May 7 06:07:29 2010 @@ -6,7 +6,7 @@ RFC1808_BASE = "http://a/b/c/d;p?q#f" RFC2396_BASE = "http://a/b/c/d;p?q" -RFC3986_BASE = "http://a/b/c/d;p?q" +RFC3986_BASE = 'http://a/b/c/d;p?q' # A list of test cases. Each test case is a a two-tuple that contains # a string with the query and a dictionary with the expected result. @@ -234,14 +234,60 @@ self.checkJoin(RFC2396_BASE, 'g#s/./x', 'http://a/b/c/g#s/./x') self.checkJoin(RFC2396_BASE, 'g#s/../x', 'http://a/b/c/g#s/../x') - #The following scenarios have been updated in RFC3986 - #self.checkJoin(RFC2396_BASE, '?y', 'http://a/b/c/?y') - #self.checkJoin(RFC2396_BASE, ';x', 'http://a/b/c/;x') - - def test_RFC3986(self): + # Test cases from RFC3986 self.checkJoin(RFC3986_BASE, '?y','http://a/b/c/d;p?y') self.checkJoin(RFC2396_BASE, ';x', 'http://a/b/c/;x') + self.checkJoin(RFC3986_BASE, 'g:h','g:h') + self.checkJoin(RFC3986_BASE, 'g','http://a/b/c/g') + self.checkJoin(RFC3986_BASE, './g','http://a/b/c/g') + self.checkJoin(RFC3986_BASE, 'g/','http://a/b/c/g/') + self.checkJoin(RFC3986_BASE, '/g','http://a/g') + self.checkJoin(RFC3986_BASE, '//g','http://g') + self.checkJoin(RFC3986_BASE, '?y','http://a/b/c/d;p?y') + self.checkJoin(RFC3986_BASE, 'g?y','http://a/b/c/g?y') + self.checkJoin(RFC3986_BASE, '#s','http://a/b/c/d;p?q#s') + self.checkJoin(RFC3986_BASE, 'g#s','http://a/b/c/g#s') + self.checkJoin(RFC3986_BASE, 'g?y#s','http://a/b/c/g?y#s') + self.checkJoin(RFC3986_BASE, ';x','http://a/b/c/;x') + self.checkJoin(RFC3986_BASE, 'g;x','http://a/b/c/g;x') + self.checkJoin(RFC3986_BASE, 'g;x?y#s','http://a/b/c/g;x?y#s') + self.checkJoin(RFC3986_BASE, '','http://a/b/c/d;p?q') + self.checkJoin(RFC3986_BASE, '.','http://a/b/c/') + self.checkJoin(RFC3986_BASE, './','http://a/b/c/') + self.checkJoin(RFC3986_BASE, '..','http://a/b/') + self.checkJoin(RFC3986_BASE, '../','http://a/b/') + self.checkJoin(RFC3986_BASE, '../g','http://a/b/g') + self.checkJoin(RFC3986_BASE, '../..','http://a/') + self.checkJoin(RFC3986_BASE, '../../','http://a/') + self.checkJoin(RFC3986_BASE, '../../g','http://a/g') + + #Abnormal Examples + + # The 'abnormal scenarios' are incompatible with RFC2986 parsing + # Tests are here for reference. + + #self.checkJoin(RFC3986_BASE, '../../../g','http://a/g') + #self.checkJoin(RFC3986_BASE, '../../../../g','http://a/g') + #self.checkJoin(RFC3986_BASE, '/./g','http://a/g') + #self.checkJoin(RFC3986_BASE, '/../g','http://a/g') + + self.checkJoin(RFC3986_BASE, 'g.','http://a/b/c/g.') + self.checkJoin(RFC3986_BASE, '.g','http://a/b/c/.g') + self.checkJoin(RFC3986_BASE, 'g..','http://a/b/c/g..') + self.checkJoin(RFC3986_BASE, '..g','http://a/b/c/..g') + self.checkJoin(RFC3986_BASE, './../g','http://a/b/g') + self.checkJoin(RFC3986_BASE, './g/.','http://a/b/c/g/') + self.checkJoin(RFC3986_BASE, 'g/./h','http://a/b/c/g/h') + self.checkJoin(RFC3986_BASE, 'g/../h','http://a/b/c/h') + self.checkJoin(RFC3986_BASE, 'g;x=1/./y','http://a/b/c/g;x=1/y') + self.checkJoin(RFC3986_BASE, 'g;x=1/../y','http://a/b/c/y') + self.checkJoin(RFC3986_BASE, 'g?y/./x','http://a/b/c/g?y/./x') + self.checkJoin(RFC3986_BASE, 'g?y/../x','http://a/b/c/g?y/../x') + self.checkJoin(RFC3986_BASE, 'g#s/./x','http://a/b/c/g#s/./x') + self.checkJoin(RFC3986_BASE, 'g#s/../x','http://a/b/c/g#s/../x') + #self.checkJoin(RFC3986_BASE, 'http:g','http:g') # strict parser + self.checkJoin(RFC3986_BASE, 'http:g','http://a/b/c/g') # relaxed parser def test_RFC2732(self): for url, hostname, port in [ From python-checkins at python.org Fri May 7 06:15:56 2010 From: python-checkins at python.org (senthil.kumaran) Date: Fri, 7 May 2010 06:15:56 +0200 (CEST) Subject: [Python-checkins] r80909 - in python/branches/release26-maint: Lib/test/test_urlparse.py Message-ID: <20100507041556.E1B7CEEA25@mail.python.org> Author: senthil.kumaran Date: Fri May 7 06:15:56 2010 New Revision: 80909 Log: Merged revisions 80908 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r80908 | senthil.kumaran | 2010-05-07 09:37:29 +0530 (Fri, 07 May 2010) | 3 lines Testsuite for RFC3986 based parsing scenario. Related Issue1462525. ........ Modified: python/branches/release26-maint/ (props changed) python/branches/release26-maint/Lib/test/test_urlparse.py Modified: python/branches/release26-maint/Lib/test/test_urlparse.py ============================================================================== --- python/branches/release26-maint/Lib/test/test_urlparse.py (original) +++ python/branches/release26-maint/Lib/test/test_urlparse.py Fri May 7 06:15:56 2010 @@ -6,7 +6,7 @@ RFC1808_BASE = "http://a/b/c/d;p?q#f" RFC2396_BASE = "http://a/b/c/d;p?q" -RFC3986_BASE = "http://a/b/c/d;p?q" +RFC3986_BASE = 'http://a/b/c/d;p?q' # A list of test cases. Each test case is a a two-tuple that contains # a string with the query and a dictionary with the expected result. @@ -231,13 +231,60 @@ self.checkJoin(RFC2396_BASE, 'g#s/./x', 'http://a/b/c/g#s/./x') self.checkJoin(RFC2396_BASE, 'g#s/../x', 'http://a/b/c/g#s/../x') - #The following scenarios have been updated in RFC3986 - #self.checkJoin(RFC2396_BASE, '?y', 'http://a/b/c/?y') - #self.checkJoin(RFC2396_BASE, ';x', 'http://a/b/c/;x') - def test_RFC3986(self): + # Test cases from RFC3986 self.checkJoin(RFC3986_BASE, '?y','http://a/b/c/d;p?y') self.checkJoin(RFC2396_BASE, ';x', 'http://a/b/c/;x') + self.checkJoin(RFC3986_BASE, 'g:h','g:h') + self.checkJoin(RFC3986_BASE, 'g','http://a/b/c/g') + self.checkJoin(RFC3986_BASE, './g','http://a/b/c/g') + self.checkJoin(RFC3986_BASE, 'g/','http://a/b/c/g/') + self.checkJoin(RFC3986_BASE, '/g','http://a/g') + self.checkJoin(RFC3986_BASE, '//g','http://g') + self.checkJoin(RFC3986_BASE, '?y','http://a/b/c/d;p?y') + self.checkJoin(RFC3986_BASE, 'g?y','http://a/b/c/g?y') + self.checkJoin(RFC3986_BASE, '#s','http://a/b/c/d;p?q#s') + self.checkJoin(RFC3986_BASE, 'g#s','http://a/b/c/g#s') + self.checkJoin(RFC3986_BASE, 'g?y#s','http://a/b/c/g?y#s') + self.checkJoin(RFC3986_BASE, ';x','http://a/b/c/;x') + self.checkJoin(RFC3986_BASE, 'g;x','http://a/b/c/g;x') + self.checkJoin(RFC3986_BASE, 'g;x?y#s','http://a/b/c/g;x?y#s') + self.checkJoin(RFC3986_BASE, '','http://a/b/c/d;p?q') + self.checkJoin(RFC3986_BASE, '.','http://a/b/c/') + self.checkJoin(RFC3986_BASE, './','http://a/b/c/') + self.checkJoin(RFC3986_BASE, '..','http://a/b/') + self.checkJoin(RFC3986_BASE, '../','http://a/b/') + self.checkJoin(RFC3986_BASE, '../g','http://a/b/g') + self.checkJoin(RFC3986_BASE, '../..','http://a/') + self.checkJoin(RFC3986_BASE, '../../','http://a/') + self.checkJoin(RFC3986_BASE, '../../g','http://a/g') + + #Abnormal Examples + + # The 'abnormal scenarios' are incompatible with RFC2986 parsing + # Tests are here for reference. + + #self.checkJoin(RFC3986_BASE, '../../../g','http://a/g') + #self.checkJoin(RFC3986_BASE, '../../../../g','http://a/g') + #self.checkJoin(RFC3986_BASE, '/./g','http://a/g') + #self.checkJoin(RFC3986_BASE, '/../g','http://a/g') + + self.checkJoin(RFC3986_BASE, 'g.','http://a/b/c/g.') + self.checkJoin(RFC3986_BASE, '.g','http://a/b/c/.g') + self.checkJoin(RFC3986_BASE, 'g..','http://a/b/c/g..') + self.checkJoin(RFC3986_BASE, '..g','http://a/b/c/..g') + self.checkJoin(RFC3986_BASE, './../g','http://a/b/g') + self.checkJoin(RFC3986_BASE, './g/.','http://a/b/c/g/') + self.checkJoin(RFC3986_BASE, 'g/./h','http://a/b/c/g/h') + self.checkJoin(RFC3986_BASE, 'g/../h','http://a/b/c/h') + self.checkJoin(RFC3986_BASE, 'g;x=1/./y','http://a/b/c/g;x=1/y') + self.checkJoin(RFC3986_BASE, 'g;x=1/../y','http://a/b/c/y') + self.checkJoin(RFC3986_BASE, 'g?y/./x','http://a/b/c/g?y/./x') + self.checkJoin(RFC3986_BASE, 'g?y/../x','http://a/b/c/g?y/../x') + self.checkJoin(RFC3986_BASE, 'g#s/./x','http://a/b/c/g#s/./x') + self.checkJoin(RFC3986_BASE, 'g#s/../x','http://a/b/c/g#s/../x') + #self.checkJoin(RFC3986_BASE, 'http:g','http:g') # strict parser + self.checkJoin(RFC3986_BASE, 'http:g','http://a/b/c/g') #relaxed parser def test_urldefrag(self): for url, defrag, frag in [ From python-checkins at python.org Fri May 7 06:19:23 2010 From: python-checkins at python.org (senthil.kumaran) Date: Fri, 7 May 2010 06:19:23 +0200 (CEST) Subject: [Python-checkins] r80910 - in python/branches/py3k: Lib/test/test_urlparse.py Message-ID: <20100507041923.64B75EEA25@mail.python.org> Author: senthil.kumaran Date: Fri May 7 06:19:23 2010 New Revision: 80910 Log: Merged revisions 80908 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r80908 | senthil.kumaran | 2010-05-07 09:37:29 +0530 (Fri, 07 May 2010) | 3 lines Testsuite for RFC3986 based parsing scenario. Related Issue1462525. ........ Modified: python/branches/py3k/ (props changed) python/branches/py3k/Lib/test/test_urlparse.py Modified: python/branches/py3k/Lib/test/test_urlparse.py ============================================================================== --- python/branches/py3k/Lib/test/test_urlparse.py (original) +++ python/branches/py3k/Lib/test/test_urlparse.py Fri May 7 06:19:23 2010 @@ -6,7 +6,7 @@ RFC1808_BASE = "http://a/b/c/d;p?q#f" RFC2396_BASE = "http://a/b/c/d;p?q" -RFC3986_BASE = "http://a/b/c/d;p?q" +RFC3986_BASE = 'http://a/b/c/d;p?q' # A list of test cases. Each test case is a a two-tuple that contains # a string with the query and a dictionary with the expected result. @@ -235,14 +235,60 @@ self.checkJoin(RFC2396_BASE, 'g#s/./x', 'http://a/b/c/g#s/./x') self.checkJoin(RFC2396_BASE, 'g#s/../x', 'http://a/b/c/g#s/../x') - #The following scenarios have been updated in RFC3986 - #self.checkJoin(RFC2396_BASE, '?y', 'http://a/b/c/?y') - #self.checkJoin(RFC2396_BASE, ';x', 'http://a/b/c/;x') - - def test_RFC3986(self): + # Test cases from RFC3986 self.checkJoin(RFC3986_BASE, '?y','http://a/b/c/d;p?y') self.checkJoin(RFC2396_BASE, ';x', 'http://a/b/c/;x') + self.checkJoin(RFC3986_BASE, 'g:h','g:h') + self.checkJoin(RFC3986_BASE, 'g','http://a/b/c/g') + self.checkJoin(RFC3986_BASE, './g','http://a/b/c/g') + self.checkJoin(RFC3986_BASE, 'g/','http://a/b/c/g/') + self.checkJoin(RFC3986_BASE, '/g','http://a/g') + self.checkJoin(RFC3986_BASE, '//g','http://g') + self.checkJoin(RFC3986_BASE, '?y','http://a/b/c/d;p?y') + self.checkJoin(RFC3986_BASE, 'g?y','http://a/b/c/g?y') + self.checkJoin(RFC3986_BASE, '#s','http://a/b/c/d;p?q#s') + self.checkJoin(RFC3986_BASE, 'g#s','http://a/b/c/g#s') + self.checkJoin(RFC3986_BASE, 'g?y#s','http://a/b/c/g?y#s') + self.checkJoin(RFC3986_BASE, ';x','http://a/b/c/;x') + self.checkJoin(RFC3986_BASE, 'g;x','http://a/b/c/g;x') + self.checkJoin(RFC3986_BASE, 'g;x?y#s','http://a/b/c/g;x?y#s') + self.checkJoin(RFC3986_BASE, '','http://a/b/c/d;p?q') + self.checkJoin(RFC3986_BASE, '.','http://a/b/c/') + self.checkJoin(RFC3986_BASE, './','http://a/b/c/') + self.checkJoin(RFC3986_BASE, '..','http://a/b/') + self.checkJoin(RFC3986_BASE, '../','http://a/b/') + self.checkJoin(RFC3986_BASE, '../g','http://a/b/g') + self.checkJoin(RFC3986_BASE, '../..','http://a/') + self.checkJoin(RFC3986_BASE, '../../','http://a/') + self.checkJoin(RFC3986_BASE, '../../g','http://a/g') + + #Abnormal Examples + + # The 'abnormal scenarios' are incompatible with RFC2986 parsing + # Tests are here for reference. + + #self.checkJoin(RFC3986_BASE, '../../../g','http://a/g') + #self.checkJoin(RFC3986_BASE, '../../../../g','http://a/g') + #self.checkJoin(RFC3986_BASE, '/./g','http://a/g') + #self.checkJoin(RFC3986_BASE, '/../g','http://a/g') + + self.checkJoin(RFC3986_BASE, 'g.','http://a/b/c/g.') + self.checkJoin(RFC3986_BASE, '.g','http://a/b/c/.g') + self.checkJoin(RFC3986_BASE, 'g..','http://a/b/c/g..') + self.checkJoin(RFC3986_BASE, '..g','http://a/b/c/..g') + self.checkJoin(RFC3986_BASE, './../g','http://a/b/g') + self.checkJoin(RFC3986_BASE, './g/.','http://a/b/c/g/') + self.checkJoin(RFC3986_BASE, 'g/./h','http://a/b/c/g/h') + self.checkJoin(RFC3986_BASE, 'g/../h','http://a/b/c/h') + self.checkJoin(RFC3986_BASE, 'g;x=1/./y','http://a/b/c/g;x=1/y') + self.checkJoin(RFC3986_BASE, 'g;x=1/../y','http://a/b/c/y') + self.checkJoin(RFC3986_BASE, 'g?y/./x','http://a/b/c/g?y/./x') + self.checkJoin(RFC3986_BASE, 'g?y/../x','http://a/b/c/g?y/../x') + self.checkJoin(RFC3986_BASE, 'g#s/./x','http://a/b/c/g#s/./x') + self.checkJoin(RFC3986_BASE, 'g#s/../x','http://a/b/c/g#s/../x') + #self.checkJoin(RFC3986_BASE, 'http:g','http:g') # strict parser + self.checkJoin(RFC3986_BASE, 'http:g','http://a/b/c/g') #relaxed parser def test_RFC2732(self): for url, hostname, port in [ From python-checkins at python.org Fri May 7 06:24:31 2010 From: python-checkins at python.org (senthil.kumaran) Date: Fri, 7 May 2010 06:24:31 +0200 (CEST) Subject: [Python-checkins] r80911 - in python/branches/release31-maint: Lib/test/test_urlparse.py Message-ID: <20100507042431.10587EE9D3@mail.python.org> Author: senthil.kumaran Date: Fri May 7 06:24:30 2010 New Revision: 80911 Log: Merged revisions 80910 via svnmerge from svn+ssh://pythondev at svn.python.org/python/branches/py3k ................ r80910 | senthil.kumaran | 2010-05-07 09:49:23 +0530 (Fri, 07 May 2010) | 9 lines Merged revisions 80908 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r80908 | senthil.kumaran | 2010-05-07 09:37:29 +0530 (Fri, 07 May 2010) | 3 lines Testsuite for RFC3986 based parsing scenario. Related Issue1462525. ........ ................ Modified: python/branches/release31-maint/ (props changed) python/branches/release31-maint/Lib/test/test_urlparse.py Modified: python/branches/release31-maint/Lib/test/test_urlparse.py ============================================================================== --- python/branches/release31-maint/Lib/test/test_urlparse.py (original) +++ python/branches/release31-maint/Lib/test/test_urlparse.py Fri May 7 06:24:30 2010 @@ -6,7 +6,7 @@ RFC1808_BASE = "http://a/b/c/d;p?q#f" RFC2396_BASE = "http://a/b/c/d;p?q" -RFC3986_BASE = "http://a/b/c/d;p?q" +RFC3986_BASE = 'http://a/b/c/d;p?q' # A list of test cases. Each test case is a a two-tuple that contains # a string with the query and a dictionary with the expected result. @@ -193,8 +193,6 @@ def test_RFC2396(self): # cases from RFC 2396 - - self.checkJoin(RFC2396_BASE, 'g:h', 'g:h') self.checkJoin(RFC2396_BASE, 'g', 'http://a/b/c/g') self.checkJoin(RFC2396_BASE, './g', 'http://a/b/c/g') @@ -235,13 +233,59 @@ self.checkJoin(RFC2396_BASE, 'g#s/./x', 'http://a/b/c/g#s/./x') self.checkJoin(RFC2396_BASE, 'g#s/../x', 'http://a/b/c/g#s/../x') - #The following scenarios have been updated in RFC3986 - #self.checkJoin(RFC2396_BASE, '?y', 'http://a/b/c/?y') - #self.checkJoin(RFC2396_BASE, ';x', 'http://a/b/c/;x') - def test_RFC3986(self): + # Test cases from RFC3986 self.checkJoin(RFC3986_BASE, '?y','http://a/b/c/d;p?y') self.checkJoin(RFC2396_BASE, ';x', 'http://a/b/c/;x') + self.checkJoin(RFC3986_BASE, 'g:h','g:h') + self.checkJoin(RFC3986_BASE, 'g','http://a/b/c/g') + self.checkJoin(RFC3986_BASE, './g','http://a/b/c/g') + self.checkJoin(RFC3986_BASE, 'g/','http://a/b/c/g/') + self.checkJoin(RFC3986_BASE, '/g','http://a/g') + self.checkJoin(RFC3986_BASE, '//g','http://g') + self.checkJoin(RFC3986_BASE, '?y','http://a/b/c/d;p?y') + self.checkJoin(RFC3986_BASE, 'g?y','http://a/b/c/g?y') + self.checkJoin(RFC3986_BASE, '#s','http://a/b/c/d;p?q#s') + self.checkJoin(RFC3986_BASE, 'g#s','http://a/b/c/g#s') + self.checkJoin(RFC3986_BASE, 'g?y#s','http://a/b/c/g?y#s') + self.checkJoin(RFC3986_BASE, ';x','http://a/b/c/;x') + self.checkJoin(RFC3986_BASE, 'g;x','http://a/b/c/g;x') + self.checkJoin(RFC3986_BASE, 'g;x?y#s','http://a/b/c/g;x?y#s') + self.checkJoin(RFC3986_BASE, '','http://a/b/c/d;p?q') + self.checkJoin(RFC3986_BASE, '.','http://a/b/c/') + self.checkJoin(RFC3986_BASE, './','http://a/b/c/') + self.checkJoin(RFC3986_BASE, '..','http://a/b/') + self.checkJoin(RFC3986_BASE, '../','http://a/b/') + self.checkJoin(RFC3986_BASE, '../g','http://a/b/g') + self.checkJoin(RFC3986_BASE, '../..','http://a/') + self.checkJoin(RFC3986_BASE, '../../','http://a/') + self.checkJoin(RFC3986_BASE, '../../g','http://a/g') + + #Abnormal Examples + # The 'abnormal scenarios' are incompatible with RFC2986 parsing + # Tests are here for reference. + + #self.checkJoin(RFC3986_BASE, '../../../g','http://a/g') + #self.checkJoin(RFC3986_BASE, '../../../../g','http://a/g') + #self.checkJoin(RFC3986_BASE, '/./g','http://a/g') + #self.checkJoin(RFC3986_BASE, '/../g','http://a/g') + + self.checkJoin(RFC3986_BASE, 'g.','http://a/b/c/g.') + self.checkJoin(RFC3986_BASE, '.g','http://a/b/c/.g') + self.checkJoin(RFC3986_BASE, 'g..','http://a/b/c/g..') + self.checkJoin(RFC3986_BASE, '..g','http://a/b/c/..g') + self.checkJoin(RFC3986_BASE, './../g','http://a/b/g') + self.checkJoin(RFC3986_BASE, './g/.','http://a/b/c/g/') + self.checkJoin(RFC3986_BASE, 'g/./h','http://a/b/c/g/h') + self.checkJoin(RFC3986_BASE, 'g/../h','http://a/b/c/h') + self.checkJoin(RFC3986_BASE, 'g;x=1/./y','http://a/b/c/g;x=1/y') + self.checkJoin(RFC3986_BASE, 'g;x=1/../y','http://a/b/c/y') + self.checkJoin(RFC3986_BASE, 'g?y/./x','http://a/b/c/g?y/./x') + self.checkJoin(RFC3986_BASE, 'g?y/../x','http://a/b/c/g?y/../x') + self.checkJoin(RFC3986_BASE, 'g#s/./x','http://a/b/c/g#s/./x') + self.checkJoin(RFC3986_BASE, 'g#s/../x','http://a/b/c/g#s/../x') + #self.checkJoin(RFC3986_BASE, 'http:g','http:g') # strict parser + self.checkJoin(RFC3986_BASE, 'http:g','http://a/b/c/g') #relaxed parser def test_urldefrag(self): for url, defrag, frag in [ From python-checkins at python.org Fri May 7 09:25:30 2010 From: python-checkins at python.org (jean-paul.calderone) Date: Fri, 7 May 2010 09:25:30 +0200 (CEST) Subject: [Python-checkins] r80912 - python/branches/siginterrupt-reset-issue8354 Message-ID: <20100507072530.19FB9EEACE@mail.python.org> Author: jean-paul.calderone Date: Fri May 7 09:25:29 2010 New Revision: 80912 Log: Branching to 'siginterrupt-reset-issue8354' Added: python/branches/siginterrupt-reset-issue8354/ - copied from r80911, /python/trunk/ From python-checkins at python.org Fri May 7 09:28:41 2010 From: python-checkins at python.org (jean-paul.calderone) Date: Fri, 7 May 2010 09:28:41 +0200 (CEST) Subject: [Python-checkins] r80913 - in python/branches/siginterrupt-reset-issue8354: Lib/test/test_signal.py Modules/signalmodule.c Python/pythonrun.c Message-ID: <20100507072841.26B01EEAFC@mail.python.org> Author: jean-paul.calderone Date: Fri May 7 09:28:40 2010 New Revision: 80913 Log: Clean up the siginterrupt tests a lot. Add a test for multiple signal delivery. Apply the fixed pointed out by neologix, to not call PyOS_setsig if we're using sigaction. Modified: python/branches/siginterrupt-reset-issue8354/Lib/test/test_signal.py python/branches/siginterrupt-reset-issue8354/Modules/signalmodule.c python/branches/siginterrupt-reset-issue8354/Python/pythonrun.c Modified: python/branches/siginterrupt-reset-issue8354/Lib/test/test_signal.py ============================================================================== --- python/branches/siginterrupt-reset-issue8354/Lib/test/test_signal.py (original) +++ python/branches/siginterrupt-reset-issue8354/Lib/test/test_signal.py Fri May 7 09:28:40 2010 @@ -255,49 +255,112 @@ class SiginterruptTest(unittest.TestCase): signum = signal.SIGUSR1 + + def setUp(self): + """Install a no-op signal handler that can be set to allow + interrupts or not, and arrange for the original signal handler to be + re-installed when the test is finished. + """ + oldhandler = signal.signal(self.signum, lambda x,y: None) + self.addCleanup(signal.signal, self.signum, oldhandler) + + def readpipe_interrupted(self, cb): + """Perform a read during which a signal will arrive. Return True if + the read is interrupted by the signal and raises an exception, False + if it returns normally. + """ + # Create a pipe that can be used for the read. Also clean it up + # when the test is over, since nothing else will (but see below for + # the write end). r, w = os.pipe() + self.addCleanup(os.close, r) + + # Give the test-method supplied function a chance to perhaps change + # the disposition of the handler. + cb() + + # Create another process which can send a signal to this one to try + # to interrupt the read. ppid = os.getpid() pid = os.fork() - oldhandler = signal.signal(self.signum, lambda x,y: None) - cb() - if pid==0: - # child code: sleep, kill, sleep. and then exit, - # which closes the pipe from which the parent process reads + if pid == 0: + # Child code: sleep to give the parent enough time to enter the + # read() call (there's a race here, but it's really tricky to + # eliminate it); then signal the parent process. Also, sleep + # again to make it likely that the signal is delivered to the + # parent process before the child exits. If the child exits + # first, the write end of the pipe will be closed and the test + # is invalid. try: time.sleep(0.2) os.kill(ppid, self.signum) time.sleep(0.2) finally: + # No matter what, just exit as fast as possible now. exit_subprocess() - - try: + else: + # Parent code. + # Make sure the child is eventually reaped, else it'll be a + # zombie for the rest of the test suite run. + self.addCleanup(os.waitpid, pid, 0) + + # Close the write end of the pipe. The child has a copy, so + # it's not really closed until the child exits. We need it to + # close when the child exits so that in the non-interrupt case + # the read eventually completes, otherwise we could just close + # it *after* the test. os.close(w) + # Try the read and report whether it is interrupted or not to + # the caller. try: - d=os.read(r, 1) + d = os.read(r, 1) return False except OSError, err: if err.errno != errno.EINTR: raise return True - finally: - signal.signal(self.signum, oldhandler) - os.waitpid(pid, 0) + def test_without_siginterrupt(self): - i=self.readpipe_interrupted(lambda: None) + """If a signal handler is installed and siginterrupt is not called + at all, when that signal arrives, it interrupts a syscall that's in + progress. + """ + i = self.readpipe_interrupted(lambda: None) + self.assertEquals(i, True) + # Arrival of the signal shouldn't have changed anything. + i = self.readpipe_interrupted(lambda: None) self.assertEquals(i, True) + def test_siginterrupt_on(self): - i=self.readpipe_interrupted(lambda: signal.siginterrupt(self.signum, 1)) + """If a signal handler is installed and siginterrupt is called with + a true value for the second argument, when that signal arrives, it + interrupts a syscall that's in progress. + """ + i = self.readpipe_interrupted(lambda: signal.siginterrupt(self.signum, 1)) + self.assertEquals(i, True) + # Arrival of the signal shouldn't have changed anything. + i = self.readpipe_interrupted(lambda: None) self.assertEquals(i, True) + def test_siginterrupt_off(self): - i=self.readpipe_interrupted(lambda: signal.siginterrupt(self.signum, 0)) + """If a signal handler is installed and siginterrupt is called with + a false value for the second argument, when that signal arrives, it + does not interrupt a syscall that's in progress. + """ + i = self.readpipe_interrupted(lambda: signal.siginterrupt(self.signum, 0)) + self.assertEquals(i, False) + # Arrival of the signal shouldn't have changed anything. + i = self.readpipe_interrupted(lambda: None) self.assertEquals(i, False) + + class ItimerTest(unittest.TestCase): def setUp(self): self.hndl_called = False Modified: python/branches/siginterrupt-reset-issue8354/Modules/signalmodule.c ============================================================================== --- python/branches/siginterrupt-reset-issue8354/Modules/signalmodule.c (original) +++ python/branches/siginterrupt-reset-issue8354/Modules/signalmodule.c Fri May 7 09:28:40 2010 @@ -198,7 +198,12 @@ return; } #endif +#ifndef HAVE_SIGACTION + /* If the handler was not set up with sigaction, reinstall it. See + * Python/pythonrun.c for the implementation of PyOS_setsig which + * makes this true. */ PyOS_setsig(sig_num, signal_handler); +#endif } Modified: python/branches/siginterrupt-reset-issue8354/Python/pythonrun.c ============================================================================== --- python/branches/siginterrupt-reset-issue8354/Python/pythonrun.c (original) +++ python/branches/siginterrupt-reset-issue8354/Python/pythonrun.c Fri May 7 09:28:40 2010 @@ -1862,6 +1862,10 @@ PyOS_setsig(int sig, PyOS_sighandler_t handler) { #ifdef HAVE_SIGACTION + /* Some code in Modules/signalmodule.c depends on sigaction() being + * used here if HAVE_SIGACTION is defined. Fix that if this code + * changes to invalidate that assumption. + */ struct sigaction context, ocontext; context.sa_handler = handler; sigemptyset(&context.sa_mask); From python-checkins at python.org Fri May 7 09:30:50 2010 From: python-checkins at python.org (jean-paul.calderone) Date: Fri, 7 May 2010 09:30:50 +0200 (CEST) Subject: [Python-checkins] r80914 - in python/branches/signalfd-issue8407: Lib/test/test_signal.py Modules/signalmodule.c Message-ID: <20100507073050.CB6C5EEA55@mail.python.org> Author: jean-paul.calderone Date: Fri May 7 09:30:50 2010 New Revision: 80914 Log: Implement flags parameter to signalfd Modified: python/branches/signalfd-issue8407/Lib/test/test_signal.py python/branches/signalfd-issue8407/Modules/signalmodule.c Modified: python/branches/signalfd-issue8407/Lib/test/test_signal.py ============================================================================== --- python/branches/signalfd-issue8407/Lib/test/test_signal.py (original) +++ python/branches/signalfd-issue8407/Lib/test/test_signal.py Fri May 7 09:30:50 2010 @@ -557,6 +557,43 @@ self.assertTrue(bytes) + def test_close_on_exec(self): + """If the bit mask passed as the 3rd argument to signalfd includes + SFD_CLOEXEC, the returned file descriptor has FD_CLOEXEC set on it. + """ + import fcntl + fd = signal.signalfd(-1, [], signal.SFD_CLOEXEC) + self.addCleanup(os.close, fd) + flags = fcntl.fcntl(fd, fcntl.F_GETFD) + self.assertTrue(flags & fcntl.FD_CLOEXEC) + + + def test_nonblocking(self): + """If the bit mask passed as the 3rd argument to signalfd includes + SFD_NOBLOCK, the file description referenced by the returned file + descriptor has O_NONBLOCK set on it. + """ + import fcntl + fd = signal.signalfd(-1, [], signal.SFD_NONBLOCK) + self.addCleanup(os.close, fd) + flags = fcntl.fcntl(fd, fcntl.F_GETFL) + self.assertTrue(flags & os.O_NONBLOCK) + + + def test_default_flags(self): + """If an empty bit mask is passed as the 3rd argument to signalfd, + neither FD_CLOEXEC nor O_NONBLOCK is set on the resulting file + descriptor/description. + """ + import fcntl + fd = signal.signalfd(-1, []) + self.addCleanup(os.close, fd) + flags = fcntl.fcntl(fd, fcntl.F_GETFD) + self.assertFalse(flags & fcntl.FD_CLOEXEC) + flags = fcntl.fcntl(fd, fcntl.F_GETFL) + self.assertFalse(flags & os.O_NONBLOCK) + + def test_main(): test_support.run_unittest( BasicSignalTests, InterProcessSignalTests, Modified: python/branches/signalfd-issue8407/Modules/signalmodule.c ============================================================================== --- python/branches/signalfd-issue8407/Modules/signalmodule.c (original) +++ python/branches/signalfd-issue8407/Modules/signalmodule.c Fri May 7 09:30:50 2010 @@ -569,13 +569,13 @@ static PyObject * signal_signalfd(PyObject *self, PyObject *args) { - int result; + int result, flags = 0; sigset_t mask; int fd; PyObject *signals; - if (!PyArg_ParseTuple(args, "iO:signalfd", &fd, &signals)) { + if (!PyArg_ParseTuple(args, "iO|i:signalfd", &fd, &signals, &flags)) { return NULL; } @@ -583,7 +583,7 @@ return NULL; } - result = signalfd(-1, &mask, 0); + result = signalfd(-1, &mask, flags); if (result == -1) { PyErr_SetFromErrno(PyExc_OSError); From python-checkins at python.org Fri May 7 12:15:51 2010 From: python-checkins at python.org (antoine.pitrou) Date: Fri, 7 May 2010 12:15:51 +0200 (CEST) Subject: [Python-checkins] r80915 - python/trunk/Doc/whatsnew/2.7.rst Message-ID: <20100507101551.E1691E9A7@mail.python.org> Author: antoine.pitrou Date: Fri May 7 12:15:51 2010 New Revision: 80915 Log: Fix some markup and a class name. Also, wrap a long line. Modified: python/trunk/Doc/whatsnew/2.7.rst Modified: python/trunk/Doc/whatsnew/2.7.rst ============================================================================== --- python/trunk/Doc/whatsnew/2.7.rst (original) +++ python/trunk/Doc/whatsnew/2.7.rst Fri May 7 12:15:51 2010 @@ -1351,17 +1351,19 @@ and then call :meth:`~sqlite3.Connection.load_extension` to load a particular shared library. (Updated by Gerhard H?ring.) -* The :mod:`ssl` module's :class:`~ssl.SSL` objects now support the +* The :mod:`ssl` module's :class:`ssl.SSLSocket` objects now support the buffer API, which fixed a test suite failure (fix by Antoine Pitrou; :issue:`7133`) and automatically set OpenSSL's :cmacro:`SSL_MODE_AUTO_RETRY`, which will prevent an error code being returned from :meth:`recv` operations that trigger an SSL renegotiation (fix by Antoine Pitrou; :issue:`8222`). - The :func:`wrap_socket` constructor function now takes a + The :func:`ssl.wrap_socket` constructor function now takes a *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`.) + `in the OpenSSL documentation + `__. + (Added by Antoine Pitrou; :issue:`8322`.) Another change makes the extension load all of OpenSSL's ciphers and digest algorithms so that they're all available. Some SSL @@ -1370,9 +1372,9 @@ :issue:`8484`.) The version of OpenSSL being used is now available as the module - attributes :attr:`OPENSSL_VERSION` (a string), - :attr:`OPENSSL_VERSION_INFO` (a 5-tuple), and - :attr:`OPENSSL_VERSION_NUMBER` (an integer). (Added by Antoine + attributes :data:`ssl.OPENSSL_VERSION` (a string), + :data:`ssl.OPENSSL_VERSION_INFO` (a 5-tuple), and + :data:`ssl.OPENSSL_VERSION_NUMBER` (an integer). (Added by Antoine Pitrou; :issue:`8321`.) * The :mod:`struct` module will no longer silently ignore overflow From nnorwitz at gmail.com Fri May 7 12:57:22 2010 From: nnorwitz at gmail.com (Neal Norwitz) Date: Fri, 7 May 2010 06:57:22 -0400 Subject: [Python-checkins] Python Regression Test Failures refleak (1) Message-ID: <20100507105722.GA30662@kbk-i386-bb.psfb.org> More important issues: ---------------------- test_bz2 leaked [-80, 0, 0] references, sum=-80 Less important issues: ---------------------- test_threadsignals leaked [0, 0, -8] references, sum=-8 From python-checkins at python.org Fri May 7 13:30:47 2010 From: python-checkins at python.org (andrew.kuchling) Date: Fri, 7 May 2010 13:30:47 +0200 (CEST) Subject: [Python-checkins] r80916 - python/trunk/Doc/whatsnew/2.7.rst Message-ID: <20100507113047.34E5FC73B@mail.python.org> Author: andrew.kuchling Date: Fri May 7 13:30:47 2010 New Revision: 80916 Log: Re-word text Modified: python/trunk/Doc/whatsnew/2.7.rst Modified: python/trunk/Doc/whatsnew/2.7.rst ============================================================================== --- python/trunk/Doc/whatsnew/2.7.rst (original) +++ python/trunk/Doc/whatsnew/2.7.rst Fri May 7 13:30:47 2010 @@ -69,8 +69,8 @@ ========================= Python 2.7 is intended to be the last major release in the 2.x series. -Though more major releases have not been absolutely ruled out, the -Python maintainers are planning to focus their efforts on Python 3.x. +The Python maintainers are planning to focus their future efforts on +the Python 3.x series. This means that 2.7 will remain in place for a long time, running production systems that have not been ported to Python 3.x. @@ -78,17 +78,27 @@ * It's very likely the 2.7 release will have a longer period of maintenance compared to earlier 2.x versions. Python 2.7 will - continue to be maintained while the transition to 3.x is in - progress, and that transition will itself be lengthy. Most 2.x - versions are maintained for about 4 years, from the first to the - last bugfix release; patchlevel releases for Python 2.7 will - probably be made for at least 6 years. - -* Because 2.7 will be running production applications, a policy - decision was made to silence warnings only of interest to developers - by default. Silencing :exc:`DeprecationWarning` and its descendants - prevents users from seeing warnings triggered by an application. - (Carried out in :issue:`7319`.) + continue to be maintained while the transition to 3.x continues. + Maintenance releases for Python 2.7 will probably be made for 5 + years. + +* A policy decision was made to silence warnings only of interest to + developers by default. :exc:`DeprecationWarning` and its + descendants are now ignored unless otherwise requested, preventing + users from seeing warnings triggered by an application. (Carried + out in :issue:`7319`.) + + In previous releases, :exc:`DeprecationWarning` messages were + enabled by default, providing Python developers with a clear + indication of where their code may break in a future major version + of Python. + + However, there are increasingly many users of Python-based + applications who are not directly involved in the development of + those applications. :exc:`DeprecationWarning` messages are + irrelevant to such users, making them worry about an application + that's actually working correctly and burdening the developers of + these applications with responding to these concerns. You can re-enable display of :exc:`DeprecationWarning` messages by running Python with the :option:`-Wdefault` (short form: From python-checkins at python.org Fri May 7 15:23:18 2010 From: python-checkins at python.org (mark.dickinson) Date: Fri, 7 May 2010 15:23:18 +0200 (CEST) Subject: [Python-checkins] r80917 - in python/branches/release26-maint: Lib/test/test_builtin.py Misc/NEWS Python/bltinmodule.c Message-ID: <20100507132318.842C5E9FD@mail.python.org> Author: mark.dickinson Date: Fri May 7 15:23:18 2010 New Revision: 80917 Log: Merged revisions 80758 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r80758 | mark.dickinson | 2010-05-04 17:18:25 +0100 (Tue, 04 May 2010) | 9 lines Issue #1533: fix inconsistency in range function argument processing: any non-float non-integer argument is now converted to an integer (if possible) using its __int__ method. Previously, only small arguments were treated this way; larger arguments (those whose __int__ was outside the range of a C long) would produce a TypeError. Patch by Alexander Belopolsky (with minor modifications). ........ Modified: python/branches/release26-maint/Lib/test/test_builtin.py python/branches/release26-maint/Misc/NEWS python/branches/release26-maint/Python/bltinmodule.c Modified: python/branches/release26-maint/Lib/test/test_builtin.py ============================================================================== --- python/branches/release26-maint/Lib/test/test_builtin.py (original) +++ python/branches/release26-maint/Lib/test/test_builtin.py Fri May 7 15:23:18 2010 @@ -3,7 +3,7 @@ import platform import test.test_support, unittest from test.test_support import fcmp, have_unicode, TESTFN, unlink, \ - run_unittest, run_with_locale + run_unittest, run_with_locale, check_warnings from operator import neg import sys, warnings, cStringIO, random, fractions, UserDict @@ -1074,6 +1074,10 @@ # Reject floats when it would require PyLongs to represent. # (smaller floats still accepted, but deprecated) self.assertRaises(TypeError, range, 1e100, 1e101, 1e101) + with check_warnings() as w: + warnings.simplefilter("always") + self.assertEqual(range(1.0), [0]) + self.assertEqual(w.category, DeprecationWarning) self.assertRaises(TypeError, range, 0, "spam") self.assertRaises(TypeError, range, 0, 42, "spam") @@ -1081,6 +1085,54 @@ self.assertRaises(OverflowError, range, -sys.maxint, sys.maxint) self.assertRaises(OverflowError, range, 0, 2*sys.maxint) + bignum = 2*sys.maxint + smallnum = 42 + # Old-style user-defined class with __int__ method + class I0: + def __init__(self, n): + self.n = int(n) + def __int__(self): + return self.n + self.assertEqual(range(I0(bignum), I0(bignum + 1)), [bignum]) + self.assertEqual(range(I0(smallnum), I0(smallnum + 1)), [smallnum]) + + # New-style user-defined class with __int__ method + class I1(object): + def __init__(self, n): + self.n = int(n) + def __int__(self): + return self.n + self.assertEqual(range(I1(bignum), I1(bignum + 1)), [bignum]) + self.assertEqual(range(I1(smallnum), I1(smallnum + 1)), [smallnum]) + + # New-style user-defined class with failing __int__ method + class IX(object): + def __int__(self): + raise RuntimeError + self.assertRaises(RuntimeError, range, IX()) + + # New-style user-defined class with invalid __int__ method + class IN(object): + def __int__(self): + return "not a number" + self.assertRaises(TypeError, range, IN()) + + # Exercise various combinations of bad arguments, to check + # refcounting logic + self.assertRaises(TypeError, range, 1e100) + + self.assertRaises(TypeError, range, 0, 1e100) + self.assertRaises(TypeError, range, 1e100, 0) + self.assertRaises(TypeError, range, 1e100, 1e100) + + self.assertRaises(TypeError, range, 0, 0, 1e100) + self.assertRaises(TypeError, range, 0, 1e100, 1) + self.assertRaises(TypeError, range, 0, 1e100, 1e100) + self.assertRaises(TypeError, range, 1e100, 0, 1) + self.assertRaises(TypeError, range, 1e100, 0, 1e100) + self.assertRaises(TypeError, range, 1e100, 1e100, 1) + self.assertRaises(TypeError, range, 1e100, 1e100, 1e100) + def test_input_and_raw_input(self): self.write_testfile() fp = open(TESTFN, 'r') Modified: python/branches/release26-maint/Misc/NEWS ============================================================================== --- python/branches/release26-maint/Misc/NEWS (original) +++ python/branches/release26-maint/Misc/NEWS Fri May 7 15:23:18 2010 @@ -12,6 +12,12 @@ Core and Builtins ----------------- +- Issue #1533: fix inconsistency in range function argument + processing: any non-float non-integer argument is now converted to + an integer (if possible) using its __int__ method. Previously, only + small arguments were treated this way; larger arguments (those whose + __int__ was outside the range of a C long) would produce a TypeError. + - Issue #8417: Raise an OverflowError when an integer larger than sys.maxsize is passed to bytearray. Modified: python/branches/release26-maint/Python/bltinmodule.c ============================================================================== --- python/branches/release26-maint/Python/bltinmodule.c (original) +++ python/branches/release26-maint/Python/bltinmodule.c Fri May 7 15:23:18 2010 @@ -1745,15 +1745,54 @@ return -1; } +/* Helper function for handle_range_longs. If arg is int or long + object, returns it with incremented reference count. If arg is + float, raises type error. As a last resort, creates a new int by + calling arg type's nb_int method if it is defined. Returns NULL + and sets exception on error. + + Returns a new reference to an int object. */ +static PyObject * +get_range_long_argument(PyObject *arg, const char *name) +{ + PyObject *v; + PyNumberMethods *nb; + if (PyInt_Check(arg) || PyLong_Check(arg)) { + Py_INCREF(arg); + return arg; + } + if (PyFloat_Check(arg) || + (nb = Py_TYPE(arg)->tp_as_number) == NULL || + nb->nb_int == NULL) { + PyErr_Format(PyExc_TypeError, + "range() integer %s argument expected, got %s.", + name, arg->ob_type->tp_name); + return NULL; + } + v = nb->nb_int(arg); + if (v == NULL) + return NULL; + if (PyInt_Check(v) || PyLong_Check(v)) + return v; + Py_DECREF(v); + PyErr_SetString(PyExc_TypeError, + "__int__ should return int object"); + return NULL; +} + /* An extension of builtin_range() that handles the case when PyLong * arguments are given. */ static PyObject * handle_range_longs(PyObject *self, PyObject *args) { - PyObject *ilow; + PyObject *ilow = NULL; PyObject *ihigh = NULL; PyObject *istep = NULL; + PyObject *low = NULL; + PyObject *high = NULL; + PyObject *step = NULL; + PyObject *curnum = NULL; PyObject *v = NULL; long bign; @@ -1772,7 +1811,7 @@ /* Figure out which way we were called, supply defaults, and be * sure to incref everything so that the decrefs at the end - * are correct. + * are correct. NB: ilow, ihigh and istep are borrowed references. */ assert(ilow != NULL); if (ihigh == NULL) { @@ -1780,47 +1819,35 @@ ihigh = ilow; ilow = NULL; } + + /* convert ihigh if necessary */ assert(ihigh != NULL); - Py_INCREF(ihigh); + high = get_range_long_argument(ihigh, "end"); + if (high == NULL) + goto Fail; /* ihigh correct now; do ilow */ - if (ilow == NULL) - ilow = zero; - Py_INCREF(ilow); - - /* ilow and ihigh correct now; do istep */ - if (istep == NULL) { - istep = PyLong_FromLong(1L); - if (istep == NULL) - goto Fail; + if (ilow == NULL) { + Py_INCREF(zero); + low = zero; } else { - Py_INCREF(istep); - } - - if (!PyInt_Check(ilow) && !PyLong_Check(ilow)) { - PyErr_Format(PyExc_TypeError, - "range() integer start argument expected, got %s.", - ilow->ob_type->tp_name); - goto Fail; + low = get_range_long_argument(ilow, "start"); + if (low == NULL) + goto Fail; } - if (!PyInt_Check(ihigh) && !PyLong_Check(ihigh)) { - PyErr_Format(PyExc_TypeError, - "range() integer end argument expected, got %s.", - ihigh->ob_type->tp_name); + /* ilow and ihigh correct now; do istep */ + if (istep == NULL) + step = PyLong_FromLong(1); + else + step = get_range_long_argument(istep, "step"); + if (step == NULL) goto Fail; - } - if (!PyInt_Check(istep) && !PyLong_Check(istep)) { - PyErr_Format(PyExc_TypeError, - "range() integer step argument expected, got %s.", - istep->ob_type->tp_name); + if (PyObject_Cmp(step, zero, &cmp_result) == -1) goto Fail; - } - if (PyObject_Cmp(istep, zero, &cmp_result) == -1) - goto Fail; if (cmp_result == 0) { PyErr_SetString(PyExc_ValueError, "range() step argument must not be zero"); @@ -1828,13 +1855,13 @@ } if (cmp_result > 0) - bign = get_len_of_range_longs(ilow, ihigh, istep); + bign = get_len_of_range_longs(low, high, step); else { - PyObject *neg_istep = PyNumber_Negative(istep); - if (neg_istep == NULL) + PyObject *neg_step = PyNumber_Negative(step); + if (neg_step == NULL) goto Fail; - bign = get_len_of_range_longs(ihigh, ilow, neg_istep); - Py_DECREF(neg_istep); + bign = get_len_of_range_longs(high, low, neg_step); + Py_DECREF(neg_step); } n = (int)bign; @@ -1848,7 +1875,7 @@ if (v == NULL) goto Fail; - curnum = ilow; + curnum = low; Py_INCREF(curnum); for (i = 0; i < n; i++) { @@ -1859,24 +1886,24 @@ PyList_SET_ITEM(v, i, w); - tmp_num = PyNumber_Add(curnum, istep); + tmp_num = PyNumber_Add(curnum, step); if (tmp_num == NULL) goto Fail; Py_DECREF(curnum); curnum = tmp_num; } - Py_DECREF(ilow); - Py_DECREF(ihigh); - Py_DECREF(istep); + Py_DECREF(low); + Py_DECREF(high); + Py_DECREF(step); Py_DECREF(zero); Py_DECREF(curnum); return v; Fail: - Py_DECREF(ilow); - Py_DECREF(ihigh); - Py_XDECREF(istep); + Py_XDECREF(low); + Py_XDECREF(high); + Py_XDECREF(step); Py_DECREF(zero); Py_XDECREF(curnum); Py_XDECREF(v); From python-checkins at python.org Fri May 7 17:34:08 2010 From: python-checkins at python.org (michael.foord) Date: Fri, 7 May 2010 17:34:08 +0200 (CEST) Subject: [Python-checkins] r80918 - in python/trunk/Lib/unittest: main.py test/test_program.py Message-ID: <20100507153408.362DEEE8E@mail.python.org> Author: michael.foord Date: Fri May 7 17:34:08 2010 New Revision: 80918 Log: Adding a test for unittest test discovery with dotted path name. Modified: python/trunk/Lib/unittest/main.py python/trunk/Lib/unittest/test/test_program.py Modified: python/trunk/Lib/unittest/main.py ============================================================================== --- python/trunk/Lib/unittest/main.py (original) +++ python/trunk/Lib/unittest/main.py Fri May 7 17:34:08 2010 @@ -70,10 +70,10 @@ # defaults for testing failfast = catchbreak = buffer = None - def __init__(self, module='__main__', defaultTest=None, - argv=None, testRunner=None, - testLoader=loader.defaultTestLoader, exit=True, - verbosity=1, failfast=None, catchbreak=None, buffer=None): + def __init__(self, module='__main__', defaultTest=None, argv=None, + testRunner=None, testLoader=loader.defaultTestLoader, + exit=True, verbosity=1, failfast=None, catchbreak=None, + buffer=None): if isinstance(module, basestring): self.module = __import__(module) for part in module.split('.')[1:]: Modified: python/trunk/Lib/unittest/test/test_program.py ============================================================================== --- python/trunk/Lib/unittest/test/test_program.py (original) +++ python/trunk/Lib/unittest/test/test_program.py Fri May 7 17:34:08 2010 @@ -1,10 +1,27 @@ from cStringIO import StringIO +import os import unittest class Test_TestProgram(unittest.TestCase): + def test_discovery_from_dotted_path(self): + loader = unittest.TestLoader() + + tests = [self] + expectedPath = os.path.abspath(os.path.dirname(unittest.test.__file__)) + + self.wasRun = False + def _find_tests(start_dir, pattern): + self.wasRun = True + self.assertEqual(start_dir, expectedPath) + return tests + loader._find_tests = _find_tests + suite = loader.discover('unittest.test') + self.assertTrue(self.wasRun) + self.assertEqual(suite._tests, tests) + # Horrible white box test def testNoExit(self): result = object() From python-checkins at python.org Fri May 7 17:35:24 2010 From: python-checkins at python.org (michael.foord) Date: Fri, 7 May 2010 17:35:24 +0200 (CEST) Subject: [Python-checkins] r80919 - in python/branches/py3k: Lib/unittest/main.py Lib/unittest/test/test_program.py Message-ID: <20100507153524.26AF1EE8E@mail.python.org> Author: michael.foord Date: Fri May 7 17:35:24 2010 New Revision: 80919 Log: Merged revisions 80918 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r80918 | michael.foord | 2010-05-07 17:34:08 +0200 (Fri, 07 May 2010) | 1 line Adding a test for unittest test discovery with dotted path name. ........ Modified: python/branches/py3k/ (props changed) python/branches/py3k/Lib/unittest/main.py python/branches/py3k/Lib/unittest/test/test_program.py Modified: python/branches/py3k/Lib/unittest/main.py ============================================================================== --- python/branches/py3k/Lib/unittest/main.py (original) +++ python/branches/py3k/Lib/unittest/main.py Fri May 7 17:35:24 2010 @@ -70,10 +70,10 @@ # defaults for testing failfast = catchbreak = buffer = None - def __init__(self, module='__main__', defaultTest=None, - argv=None, testRunner=None, - testLoader=loader.defaultTestLoader, exit=True, - verbosity=1, failfast=None, catchbreak=None, buffer=None): + def __init__(self, module='__main__', defaultTest=None, argv=None, + testRunner=None, testLoader=loader.defaultTestLoader, + exit=True, verbosity=1, failfast=None, catchbreak=None, + buffer=None): if isinstance(module, str): self.module = __import__(module) for part in module.split('.')[1:]: Modified: python/branches/py3k/Lib/unittest/test/test_program.py ============================================================================== --- python/branches/py3k/Lib/unittest/test/test_program.py (original) +++ python/branches/py3k/Lib/unittest/test/test_program.py Fri May 7 17:35:24 2010 @@ -1,10 +1,27 @@ import io +import os import unittest class Test_TestProgram(unittest.TestCase): + def test_discovery_from_dotted_path(self): + loader = unittest.TestLoader() + + tests = [self] + expectedPath = os.path.abspath(os.path.dirname(unittest.test.__file__)) + + self.wasRun = False + def _find_tests(start_dir, pattern): + self.wasRun = True + self.assertEqual(start_dir, expectedPath) + return tests + loader._find_tests = _find_tests + suite = loader.discover('unittest.test') + self.assertTrue(self.wasRun) + self.assertEqual(suite._tests, tests) + # Horrible white box test def testNoExit(self): result = object() From python-checkins at python.org Fri May 7 17:52:05 2010 From: python-checkins at python.org (michael.foord) Date: Fri, 7 May 2010 17:52:05 +0200 (CEST) Subject: [Python-checkins] r80920 - in python/trunk/Lib/unittest/test: test_program.py test_runner.py Message-ID: <20100507155205.4F904F95A@mail.python.org> Author: michael.foord Date: Fri May 7 17:52:05 2010 New Revision: 80920 Log: Adding tests for unittest command line handling of buffer, catchbreak and failfast. Modified: python/trunk/Lib/unittest/test/test_program.py python/trunk/Lib/unittest/test/test_runner.py Modified: python/trunk/Lib/unittest/test/test_program.py ============================================================================== --- python/trunk/Lib/unittest/test/test_program.py (original) +++ python/trunk/Lib/unittest/test/test_program.py Fri May 7 17:52:05 2010 @@ -1,6 +1,7 @@ from cStringIO import StringIO import os +import sys import unittest @@ -91,5 +92,164 @@ testLoader=self.FooBarLoader()) +class InitialisableProgram(unittest.TestProgram): + exit = False + result = None + verbosity = 1 + defaultTest = None + testRunner = None + testLoader = unittest.defaultTestLoader + progName = 'test' + test = 'test' + def __init__(self, *args): + pass + +RESULT = object() + +class FakeRunner(object): + initArgs = None + test = None + raiseError = False + + def __init__(self, **kwargs): + FakeRunner.initArgs = kwargs + if FakeRunner.raiseError: + FakeRunner.raiseError = False + raise TypeError + + def run(self, test): + FakeRunner.test = test + return RESULT + +class TestCommandLineArgs(unittest.TestCase): + + def setUp(self): + self.program = InitialisableProgram() + self.program.createTests = lambda: None + FakeRunner.initArgs = None + FakeRunner.test = None + FakeRunner.raiseError = False + + def testHelpAndUnknown(self): + program = self.program + def usageExit(msg=None): + program.msg = msg + program.exit = True + program.usageExit = usageExit + + for opt in '-h', '-H', '--help': + program.exit = False + program.parseArgs([None, opt]) + self.assertTrue(program.exit) + self.assertIsNone(program.msg) + + program.parseArgs([None, '-$']) + self.assertTrue(program.exit) + self.assertIsNotNone(program.msg) + + def testVerbosity(self): + program = self.program + + for opt in '-q', '--quiet': + program.verbosity = 1 + program.parseArgs([None, opt]) + self.assertEqual(program.verbosity, 0) + + for opt in '-v', '--verbose': + program.verbosity = 1 + program.parseArgs([None, opt]) + self.assertEqual(program.verbosity, 2) + + def testBufferCatchFailfast(self): + program = self.program + for arg, attr in (('buffer', 'buffer'), ('failfast', 'failfast'), + ('catch', 'catchbreak')): + if attr == 'catch' and not hasInstallHandler: + continue + + short_opt = '-%s' % arg[0] + long_opt = '--%s' % arg + for opt in short_opt, long_opt: + setattr(program, attr, None) + + program.parseArgs([None, opt]) + self.assertTrue(getattr(program, attr)) + + for opt in short_opt, long_opt: + not_none = object() + setattr(program, attr, not_none) + + program.parseArgs([None, opt]) + self.assertEqual(getattr(program, attr), not_none) + + def testRunTestsRunnerClass(self): + program = self.program + + program.testRunner = FakeRunner + program.verbosity = 'verbosity' + program.failfast = 'failfast' + program.buffer = 'buffer' + + program.runTests() + + self.assertEqual(FakeRunner.initArgs, {'verbosity': 'verbosity', + 'failfast': 'failfast', + 'buffer': 'buffer'}) + self.assertEqual(FakeRunner.test, 'test') + self.assertIs(program.result, RESULT) + + def testRunTestsRunnerInstance(self): + program = self.program + + program.testRunner = FakeRunner() + FakeRunner.initArgs = None + + program.runTests() + + # A new FakeRunner should not have been instantiated + self.assertIsNone(FakeRunner.initArgs) + + self.assertEqual(FakeRunner.test, 'test') + self.assertIs(program.result, RESULT) + + def testRunTestsOldRunnerClass(self): + program = self.program + + FakeRunner.raiseError = True + program.testRunner = FakeRunner + program.verbosity = 'verbosity' + program.failfast = 'failfast' + program.buffer = 'buffer' + program.test = 'test' + + program.runTests() + + # If initialising raises a type error it should be retried + # without the new keyword arguments + self.assertEqual(FakeRunner.initArgs, {}) + self.assertEqual(FakeRunner.test, 'test') + self.assertIs(program.result, RESULT) + + def testCatchBreakInstallsHandler(self): + module = sys.modules['unittest.main'] + original = module.installHandler + def restore(): + module.installHandler = original + self.addCleanup(restore) + + self.installed = False + def fakeInstallHandler(): + self.installed = True + module.installHandler = fakeInstallHandler + + program = self.program + program.catchbreak = True + + program.testRunner = FakeRunner + + program.runTests() + self.assertTrue(self.installed) + + if __name__ == '__main__': unittest.main() Modified: python/trunk/Lib/unittest/test/test_runner.py ============================================================================== --- python/trunk/Lib/unittest/test/test_runner.py (original) +++ python/trunk/Lib/unittest/test/test_runner.py Fri May 7 17:52:05 2010 @@ -115,6 +115,52 @@ class Test_TextTestRunner(unittest.TestCase): """Tests for TextTestRunner.""" + def test_init(self): + runner = unittest.TextTestRunner() + self.assertFalse(runner.failfast) + self.assertFalse(runner.buffer) + self.assertEqual(runner.verbosity, 1) + self.assertTrue(runner.descriptions) + self.assertEqual(runner.resultclass, unittest.TextTestResult) + + + def testBufferAndFailfast(self): + class Test(unittest.TestCase): + def testFoo(self): + pass + result = unittest.TestResult() + runner = unittest.TextTestRunner(stream=StringIO(), failfast=True, + buffer=True) + # Use our result object + runner._makeResult = lambda: result + runner.run(Test('testFoo')) + + self.assertTrue(result.failfast) + self.assertTrue(result.buffer) + + def testRunnerRegistersResult(self): + class Test(unittest.TestCase): + def testFoo(self): + pass + originalRegisterResult = unittest.runner.registerResult + def cleanup(): + unittest.runner.registerResult = originalRegisterResult + self.addCleanup(cleanup) + + result = unittest.TestResult() + runner = unittest.TextTestRunner(stream=StringIO()) + # Use our result object + runner._makeResult = lambda: result + + self.wasRegistered = 0 + def fakeRegisterResult(thisResult): + self.wasRegistered += 1 + self.assertEqual(thisResult, result) + unittest.runner.registerResult = fakeRegisterResult + + runner.run(unittest.TestSuite()) + self.assertEqual(self.wasRegistered, 1) + def test_works_with_result_without_startTestRun_stopTestRun(self): class OldTextResult(ResultWithNoStartTestRunStopTestRun): separator2 = '' From python-checkins at python.org Fri May 7 18:00:31 2010 From: python-checkins at python.org (michael.foord) Date: Fri, 7 May 2010 18:00:31 +0200 (CEST) Subject: [Python-checkins] r80921 - in python/branches/py3k: Lib/unittest/test/test_program.py Lib/unittest/test/test_runner.py Message-ID: <20100507160031.19A77ED07@mail.python.org> Author: michael.foord Date: Fri May 7 18:00:30 2010 New Revision: 80921 Log: Merged revisions 80920 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r80920 | michael.foord | 2010-05-07 17:52:05 +0200 (Fri, 07 May 2010) | 1 line Adding tests for unittest command line handling of buffer, catchbreak and failfast. ........ Modified: python/branches/py3k/ (props changed) python/branches/py3k/Lib/unittest/test/test_program.py python/branches/py3k/Lib/unittest/test/test_runner.py Modified: python/branches/py3k/Lib/unittest/test/test_program.py ============================================================================== --- python/branches/py3k/Lib/unittest/test/test_program.py (original) +++ python/branches/py3k/Lib/unittest/test/test_program.py Fri May 7 18:00:30 2010 @@ -1,6 +1,7 @@ import io import os +import sys import unittest @@ -89,3 +90,166 @@ argv=["foobar"], testRunner=unittest.TextTestRunner(stream=io.StringIO()), testLoader=self.FooBarLoader()) + + +class InitialisableProgram(unittest.TestProgram): + exit = False + result = None + verbosity = 1 + defaultTest = None + testRunner = None + testLoader = unittest.defaultTestLoader + progName = 'test' + test = 'test' + def __init__(self, *args): + pass + +RESULT = object() + +class FakeRunner(object): + initArgs = None + test = None + raiseError = False + + def __init__(self, **kwargs): + FakeRunner.initArgs = kwargs + if FakeRunner.raiseError: + FakeRunner.raiseError = False + raise TypeError + + def run(self, test): + FakeRunner.test = test + return RESULT + +class TestCommandLineArgs(unittest.TestCase): + + def setUp(self): + self.program = InitialisableProgram() + self.program.createTests = lambda: None + FakeRunner.initArgs = None + FakeRunner.test = None + FakeRunner.raiseError = False + + def testHelpAndUnknown(self): + program = self.program + def usageExit(msg=None): + program.msg = msg + program.exit = True + program.usageExit = usageExit + + for opt in '-h', '-H', '--help': + program.exit = False + program.parseArgs([None, opt]) + self.assertTrue(program.exit) + self.assertIsNone(program.msg) + + program.parseArgs([None, '-$']) + self.assertTrue(program.exit) + self.assertIsNotNone(program.msg) + + def testVerbosity(self): + program = self.program + + for opt in '-q', '--quiet': + program.verbosity = 1 + program.parseArgs([None, opt]) + self.assertEqual(program.verbosity, 0) + + for opt in '-v', '--verbose': + program.verbosity = 1 + program.parseArgs([None, opt]) + self.assertEqual(program.verbosity, 2) + + def testBufferCatchFailfast(self): + program = self.program + for arg, attr in (('buffer', 'buffer'), ('failfast', 'failfast'), + ('catch', 'catchbreak')): + if attr == 'catch' and not hasInstallHandler: + continue + + short_opt = '-%s' % arg[0] + long_opt = '--%s' % arg + for opt in short_opt, long_opt: + setattr(program, attr, None) + + program.parseArgs([None, opt]) + self.assertTrue(getattr(program, attr)) + + for opt in short_opt, long_opt: + not_none = object() + setattr(program, attr, not_none) + + program.parseArgs([None, opt]) + self.assertEqual(getattr(program, attr), not_none) + + def testRunTestsRunnerClass(self): + program = self.program + + program.testRunner = FakeRunner + program.verbosity = 'verbosity' + program.failfast = 'failfast' + program.buffer = 'buffer' + + program.runTests() + + self.assertEqual(FakeRunner.initArgs, {'verbosity': 'verbosity', + 'failfast': 'failfast', + 'buffer': 'buffer'}) + self.assertEqual(FakeRunner.test, 'test') + self.assertIs(program.result, RESULT) + + def testRunTestsRunnerInstance(self): + program = self.program + + program.testRunner = FakeRunner() + FakeRunner.initArgs = None + + program.runTests() + + # A new FakeRunner should not have been instantiated + self.assertIsNone(FakeRunner.initArgs) + + self.assertEqual(FakeRunner.test, 'test') + self.assertIs(program.result, RESULT) + + def testRunTestsOldRunnerClass(self): + program = self.program + + FakeRunner.raiseError = True + program.testRunner = FakeRunner + program.verbosity = 'verbosity' + program.failfast = 'failfast' + program.buffer = 'buffer' + program.test = 'test' + + program.runTests() + + # If initialising raises a type error it should be retried + # without the new keyword arguments + self.assertEqual(FakeRunner.initArgs, {}) + self.assertEqual(FakeRunner.test, 'test') + self.assertIs(program.result, RESULT) + + def testCatchBreakInstallsHandler(self): + module = sys.modules['unittest.main'] + original = module.installHandler + def restore(): + module.installHandler = original + self.addCleanup(restore) + + self.installed = False + def fakeInstallHandler(): + self.installed = True + module.installHandler = fakeInstallHandler + + program = self.program + program.catchbreak = True + + program.testRunner = FakeRunner + + program.runTests() + self.assertTrue(self.installed) + + +if __name__ == '__main__': + unittest.main() Modified: python/branches/py3k/Lib/unittest/test/test_runner.py ============================================================================== --- python/branches/py3k/Lib/unittest/test/test_runner.py (original) +++ python/branches/py3k/Lib/unittest/test/test_runner.py Fri May 7 18:00:30 2010 @@ -114,6 +114,52 @@ class Test_TextTestRunner(unittest.TestCase): """Tests for TextTestRunner.""" + def test_init(self): + runner = unittest.TextTestRunner() + self.assertFalse(runner.failfast) + self.assertFalse(runner.buffer) + self.assertEqual(runner.verbosity, 1) + self.assertTrue(runner.descriptions) + self.assertEqual(runner.resultclass, unittest.TextTestResult) + + + def testBufferAndFailfast(self): + class Test(unittest.TestCase): + def testFoo(self): + pass + result = unittest.TestResult() + runner = unittest.TextTestRunner(stream=io.StringIO(), failfast=True, + buffer=True) + # Use our result object + runner._makeResult = lambda: result + runner.run(Test('testFoo')) + + self.assertTrue(result.failfast) + self.assertTrue(result.buffer) + + def testRunnerRegistersResult(self): + class Test(unittest.TestCase): + def testFoo(self): + pass + originalRegisterResult = unittest.runner.registerResult + def cleanup(): + unittest.runner.registerResult = originalRegisterResult + self.addCleanup(cleanup) + + result = unittest.TestResult() + runner = unittest.TextTestRunner(stream=io.StringIO()) + # Use our result object + runner._makeResult = lambda: result + + self.wasRegistered = 0 + def fakeRegisterResult(thisResult): + self.wasRegistered += 1 + self.assertEqual(thisResult, result) + unittest.runner.registerResult = fakeRegisterResult + + runner.run(unittest.TestSuite()) + self.assertEqual(self.wasRegistered, 1) + def test_works_with_result_without_startTestRun_stopTestRun(self): class OldTextResult(ResultWithNoStartTestRunStopTestRun): separator2 = '' From python-checkins at python.org Fri May 7 18:06:25 2010 From: python-checkins at python.org (benjamin.peterson) Date: Fri, 7 May 2010 18:06:25 +0200 (CEST) Subject: [Python-checkins] r80922 - in sandbox/trunk/2to3/lib2to3: fixes/fix_xrange.py tests/test_fixers.py Message-ID: <20100507160625.CAA69F657@mail.python.org> Author: benjamin.peterson Date: Fri May 7 18:06:25 2010 New Revision: 80922 Log: prevent xrange transformation from wrapping range calls it produces in list Modified: sandbox/trunk/2to3/lib2to3/fixes/fix_xrange.py sandbox/trunk/2to3/lib2to3/tests/test_fixers.py Modified: sandbox/trunk/2to3/lib2to3/fixes/fix_xrange.py ============================================================================== --- sandbox/trunk/2to3/lib2to3/fixes/fix_xrange.py (original) +++ sandbox/trunk/2to3/lib2to3/fixes/fix_xrange.py Fri May 7 18:06:25 2010 @@ -17,6 +17,13 @@ rest=any* > """ + def start_tree(self, tree, filename): + super(FixXrange, self).start_tree(tree, filename) + self.transformed_xranges = set() + + def finish_tree(self, tree, filename): + self.transformed_xranges = None + def transform(self, node, results): name = results["name"] if name.value == u"xrange": @@ -29,9 +36,12 @@ def transform_xrange(self, node, results): name = results["name"] name.replace(Name(u"range", prefix=name.prefix)) + # This prevents the new range call from being wrapped in a list later. + self.transformed_xranges.add(id(node)) def transform_range(self, node, results): - if not self.in_special_context(node): + if (id(node) not in self.transformed_xranges and + not self.in_special_context(node)): range_call = Call(Name(u"range"), [results["args"].clone()]) # Encase the range call in list(). list_call = Call(Name(u"list"), [range_call], Modified: sandbox/trunk/2to3/lib2to3/tests/test_fixers.py ============================================================================== --- sandbox/trunk/2to3/lib2to3/tests/test_fixers.py (original) +++ sandbox/trunk/2to3/lib2to3/tests/test_fixers.py Fri May 7 18:06:25 2010 @@ -1497,6 +1497,17 @@ for call in fixer_util.consuming_calls: self.unchanged("a = %s(range(10))" % call) +class Test_xrange_with_reduce(FixerTestCase): + + def setUp(self): + super(Test_xrange_with_reduce, self).setUp(["xrange", "reduce"]) + + def test_double_transform(self): + b = """reduce(x, xrange(5))""" + a = """from functools import reduce +reduce(x, range(5))""" + self.check(b, a) + class Test_raw_input(FixerTestCase): fixer = "raw_input" From python-checkins at python.org Fri May 7 18:34:53 2010 From: python-checkins at python.org (victor.stinner) Date: Fri, 7 May 2010 18:34:53 +0200 (CEST) Subject: [Python-checkins] r80923 - in python/branches/py3k/Modules: grpmodule.c posixmodule.c pwdmodule.c spwdmodule.c Message-ID: <20100507163453.BCE99EE985@mail.python.org> Author: victor.stinner Date: Fri May 7 18:34:53 2010 New Revision: 80923 Log: Replace PyUnicode_Decode(buf, strlen(buf), Py_FileSystemDefaultEncoding, "surrogateescape") by PyUnicode_DecodeFSDefault(val). Modified: python/branches/py3k/Modules/grpmodule.c python/branches/py3k/Modules/posixmodule.c python/branches/py3k/Modules/pwdmodule.c python/branches/py3k/Modules/spwdmodule.c Modified: python/branches/py3k/Modules/grpmodule.c ============================================================================== --- python/branches/py3k/Modules/grpmodule.c (original) +++ python/branches/py3k/Modules/grpmodule.c Fri May 7 18:34:53 2010 @@ -46,11 +46,8 @@ Py_DECREF(v); return NULL; } -#define FSDECODE(val) PyUnicode_Decode(val, strlen(val),\ - Py_FileSystemDefaultEncoding,\ - "surrogateescape") for (member = p->gr_mem; *member != NULL; member++) { - PyObject *x = FSDECODE(*member); + PyObject *x = PyUnicode_DecodeFSDefault(*member); if (x == NULL || PyList_Append(w, x) != 0) { Py_XDECREF(x); Py_DECREF(w); @@ -61,13 +58,13 @@ } #define SET(i,val) PyStructSequence_SET_ITEM(v, i, val) - SET(setIndex++, FSDECODE(p->gr_name)); + SET(setIndex++, PyUnicode_DecodeFSDefault(p->gr_name)); #ifdef __VMS SET(setIndex++, Py_None); Py_INCREF(Py_None); #else if (p->gr_passwd) - SET(setIndex++, FSDECODE(p->gr_passwd)); + SET(setIndex++, PyUnicode_DecodeFSDefault(p->gr_passwd)); else { SET(setIndex++, Py_None); Py_INCREF(Py_None); Modified: python/branches/py3k/Modules/posixmodule.c ============================================================================== --- python/branches/py3k/Modules/posixmodule.c (original) +++ python/branches/py3k/Modules/posixmodule.c Fri May 7 18:34:53 2010 @@ -2031,7 +2031,7 @@ return posix_error(); if (use_bytes) return PyBytes_FromStringAndSize(buf, strlen(buf)); - return PyUnicode_Decode(buf, strlen(buf), Py_FileSystemDefaultEncoding,"surrogateescape"); + return PyUnicode_DecodeFSDefault(buf); } PyDoc_STRVAR(posix_getcwd__doc__, Modified: python/branches/py3k/Modules/pwdmodule.c ============================================================================== --- python/branches/py3k/Modules/pwdmodule.c (original) +++ python/branches/py3k/Modules/pwdmodule.c Fri May 7 18:34:53 2010 @@ -49,7 +49,7 @@ sets(PyObject *v, int i, const char* val) { if (val) { - PyObject *o = PyUnicode_Decode(val, strlen(val), + PyObject *o = PyUnicode_DecodeFSDefault(val, strlen(val), Py_FileSystemDefaultEncoding, "surrogateescape"); PyStructSequence_SET_ITEM(v, i, o); Modified: python/branches/py3k/Modules/spwdmodule.c ============================================================================== --- python/branches/py3k/Modules/spwdmodule.c (original) +++ python/branches/py3k/Modules/spwdmodule.c Fri May 7 18:34:53 2010 @@ -60,9 +60,7 @@ sets(PyObject *v, int i, const char* val) { if (val) { - PyObject *o = PyUnicode_Decode(val, strlen(val), - Py_FileSystemDefaultEncoding, - "surrogateescape"); + PyObject *o = PyUnicode_DecodeFSDefault(val); PyStructSequence_SET_ITEM(v, i, o); } else { PyStructSequence_SET_ITEM(v, i, Py_None); From python-checkins at python.org Fri May 7 18:35:44 2010 From: python-checkins at python.org (victor.stinner) Date: Fri, 7 May 2010 18:35:44 +0200 (CEST) Subject: [Python-checkins] r80924 - python/branches/release31-maint Message-ID: <20100507163544.5DA48EE9BE@mail.python.org> Author: victor.stinner Date: Fri May 7 18:35:44 2010 New Revision: 80924 Log: Blocked revisions 80923 via svnmerge ........ r80923 | victor.stinner | 2010-05-07 18:34:53 +0200 (ven., 07 mai 2010) | 3 lines Replace PyUnicode_Decode(buf, strlen(buf), Py_FileSystemDefaultEncoding, "surrogateescape") by PyUnicode_DecodeFSDefault(val). ........ Modified: python/branches/release31-maint/ (props changed) From python-checkins at python.org Fri May 7 18:42:51 2010 From: python-checkins at python.org (benjamin.peterson) Date: Fri, 7 May 2010 18:42:51 +0200 (CEST) Subject: [Python-checkins] r80925 - python/branches/py3k/Modules/pwdmodule.c Message-ID: <20100507164251.7E871EE99F@mail.python.org> Author: benjamin.peterson Date: Fri May 7 18:42:51 2010 New Revision: 80925 Log: correct call Modified: python/branches/py3k/Modules/pwdmodule.c Modified: python/branches/py3k/Modules/pwdmodule.c ============================================================================== --- python/branches/py3k/Modules/pwdmodule.c (original) +++ python/branches/py3k/Modules/pwdmodule.c Fri May 7 18:42:51 2010 @@ -49,9 +49,7 @@ sets(PyObject *v, int i, const char* val) { if (val) { - PyObject *o = PyUnicode_DecodeFSDefault(val, strlen(val), - Py_FileSystemDefaultEncoding, - "surrogateescape"); + PyObject *o = PyUnicode_DecodeFSDefault(val); PyStructSequence_SET_ITEM(v, i, o); } else { From python-checkins at python.org Fri May 7 18:50:35 2010 From: python-checkins at python.org (antoine.pitrou) Date: Fri, 7 May 2010 18:50:35 +0200 (CEST) Subject: [Python-checkins] r80926 - in python/trunk: Lib/test/test_zlib.py Misc/NEWS Modules/zlibmodule.c Message-ID: <20100507165035.045A5EE9BE@mail.python.org> Author: antoine.pitrou Date: Fri May 7 18:50:34 2010 New Revision: 80926 Log: Issue #8571: Fix an internal error when compressing or decompressing a chunk larger than 1GB with the zlib module's compressor and decompressor objects. Modified: python/trunk/Lib/test/test_zlib.py python/trunk/Misc/NEWS python/trunk/Modules/zlibmodule.c Modified: python/trunk/Lib/test/test_zlib.py ============================================================================== --- python/trunk/Lib/test/test_zlib.py (original) +++ python/trunk/Lib/test/test_zlib.py Fri May 7 18:50:34 2010 @@ -2,6 +2,7 @@ from test import test_support import binascii import random +from test.test_support import precisionbigmemtest, _1G zlib = test_support.import_module('zlib') @@ -90,8 +91,39 @@ self.assertRaises(ValueError, zlib.decompressobj().flush, -1) +class BaseCompressTestCase(object): + def check_big_compress_buffer(self, size, compress_func): + _1M = 1024 * 1024 + fmt = "%%0%dx" % (2 * _1M) + # Generate 10MB worth of random, and expand it by repeating it. + # The assumption is that zlib's memory is not big enough to exploit + # such spread out redundancy. + data = ''.join([binascii.a2b_hex(fmt % random.getrandbits(8 * _1M)) + for i in range(10)]) + data = data * (size // len(data) + 1) + try: + compress_func(data) + finally: + # Release memory + data = None + + def check_big_decompress_buffer(self, size, decompress_func): + data = 'x' * size + try: + compressed = zlib.compress(data, 1) + finally: + # Release memory + data = None + data = decompress_func(compressed) + # Sanity check + try: + self.assertEqual(len(data), size) + self.assertEqual(len(data.strip('x')), 0) + finally: + data = None -class CompressTestCase(unittest.TestCase): + +class CompressTestCase(BaseCompressTestCase, unittest.TestCase): # Test compression in one go (whole message compression) def test_speech(self): x = zlib.compress(HAMLET_SCENE) @@ -103,10 +135,19 @@ x = zlib.compress(data) self.assertEqual(zlib.decompress(x), data) + # Memory use of the following functions takes into account overallocation + + @precisionbigmemtest(size=_1G + 1024 * 1024, memuse=3) + def test_big_compress_buffer(self, size): + compress = lambda s: zlib.compress(s, 1) + self.check_big_compress_buffer(size, compress) + @precisionbigmemtest(size=_1G + 1024 * 1024, memuse=2) + def test_big_decompress_buffer(self, size): + self.check_big_decompress_buffer(size, zlib.decompress) -class CompressObjectTestCase(unittest.TestCase): +class CompressObjectTestCase(BaseCompressTestCase, unittest.TestCase): # Test compression object def test_pair(self): # straightforward compress/decompress objects @@ -380,6 +421,21 @@ d.flush() self.assertRaises(ValueError, d.copy) + # Memory use of the following functions takes into account overallocation + + @precisionbigmemtest(size=_1G + 1024 * 1024, memuse=3) + def test_big_compress_buffer(self, size): + c = zlib.compressobj(1) + compress = lambda s: c.compress(s) + c.flush() + self.check_big_compress_buffer(size, compress) + + @precisionbigmemtest(size=_1G + 1024 * 1024, memuse=2) + def test_big_decompress_buffer(self, size): + d = zlib.decompressobj() + decompress = lambda s: d.decompress(s) + d.flush() + self.check_big_decompress_buffer(size, decompress) + + def genblock(seed, length, step=1024, generator=random): """length-byte stream of random data from a seed (in step-byte blocks).""" if seed is not None: Modified: python/trunk/Misc/NEWS ============================================================================== --- python/trunk/Misc/NEWS (original) +++ python/trunk/Misc/NEWS Fri May 7 18:50:34 2010 @@ -41,6 +41,10 @@ Library ------- +- Issue #8571: Fix an internal error when compressing or decompressing a + chunk larger than 1GB with the zlib module's compressor and decompressor + objects. + - Issue #8573: asyncore _strerror() function might throw ValueError. - Issue #8483: asyncore.dispatcher's __getattr__ method produced confusing Modified: python/trunk/Modules/zlibmodule.c ============================================================================== --- python/trunk/Modules/zlibmodule.c (original) +++ python/trunk/Modules/zlibmodule.c Fri May 7 18:50:34 2010 @@ -392,7 +392,8 @@ static PyObject * PyZlib_objcompress(compobject *self, PyObject *args) { - int err, inplen, length = DEFAULTALLOC; + int err, inplen; + Py_ssize_t length = DEFAULTALLOC; PyObject *RetVal; Byte *input; unsigned long start_total_out; @@ -461,8 +462,8 @@ static PyObject * PyZlib_objdecompress(compobject *self, PyObject *args) { - int err, inplen, old_length, length = DEFAULTALLOC; - int max_length = 0; + int err, inplen, max_length = 0; + Py_ssize_t old_length, length = DEFAULTALLOC; PyObject *RetVal; Byte *input; unsigned long start_total_out; From python-checkins at python.org Fri May 7 18:59:00 2010 From: python-checkins at python.org (antoine.pitrou) Date: Fri, 7 May 2010 18:59:00 +0200 (CEST) Subject: [Python-checkins] r80927 - in python/branches/release26-maint: Lib/test/test_zlib.py Misc/NEWS Modules/zlibmodule.c Message-ID: <20100507165900.C6E63EE98D@mail.python.org> Author: antoine.pitrou Date: Fri May 7 18:59:00 2010 New Revision: 80927 Log: Merged revisions 80926 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r80926 | antoine.pitrou | 2010-05-07 18:50:34 +0200 (ven., 07 mai 2010) | 5 lines Issue #8571: Fix an internal error when compressing or decompressing a chunk larger than 1GB with the zlib module's compressor and decompressor objects. ........ Modified: python/branches/release26-maint/ (props changed) python/branches/release26-maint/Lib/test/test_zlib.py python/branches/release26-maint/Misc/NEWS python/branches/release26-maint/Modules/zlibmodule.c Modified: python/branches/release26-maint/Lib/test/test_zlib.py ============================================================================== --- python/branches/release26-maint/Lib/test/test_zlib.py (original) +++ python/branches/release26-maint/Lib/test/test_zlib.py Fri May 7 18:59:00 2010 @@ -3,6 +3,7 @@ import zlib import binascii import random +from test.test_support import precisionbigmemtest, _1G class ChecksumTestCase(unittest.TestCase): @@ -89,8 +90,39 @@ self.assertRaises(ValueError, zlib.decompressobj().flush, -1) +class BaseCompressTestCase(object): + def check_big_compress_buffer(self, size, compress_func): + _1M = 1024 * 1024 + fmt = "%%0%dx" % (2 * _1M) + # Generate 10MB worth of random, and expand it by repeating it. + # The assumption is that zlib's memory is not big enough to exploit + # such spread out redundancy. + data = ''.join([binascii.a2b_hex(fmt % random.getrandbits(8 * _1M)) + for i in range(10)]) + data = data * (size // len(data) + 1) + try: + compress_func(data) + finally: + # Release memory + data = None + + def check_big_decompress_buffer(self, size, decompress_func): + data = 'x' * size + try: + compressed = zlib.compress(data, 1) + finally: + # Release memory + data = None + data = decompress_func(compressed) + # Sanity check + try: + self.assertEqual(len(data), size) + self.assertEqual(len(data.strip('x')), 0) + finally: + data = None -class CompressTestCase(unittest.TestCase): + +class CompressTestCase(BaseCompressTestCase, unittest.TestCase): # Test compression in one go (whole message compression) def test_speech(self): x = zlib.compress(HAMLET_SCENE) @@ -102,10 +134,19 @@ x = zlib.compress(data) self.assertEqual(zlib.decompress(x), data) + # Memory use of the following functions takes into account overallocation + + @precisionbigmemtest(size=_1G + 1024 * 1024, memuse=3) + def test_big_compress_buffer(self, size): + compress = lambda s: zlib.compress(s, 1) + self.check_big_compress_buffer(size, compress) + @precisionbigmemtest(size=_1G + 1024 * 1024, memuse=2) + def test_big_decompress_buffer(self, size): + self.check_big_decompress_buffer(size, zlib.decompress) -class CompressObjectTestCase(unittest.TestCase): +class CompressObjectTestCase(BaseCompressTestCase, unittest.TestCase): # Test compression object def test_pair(self): # straightforward compress/decompress objects @@ -379,6 +420,21 @@ d.flush() self.assertRaises(ValueError, d.copy) + # Memory use of the following functions takes into account overallocation + + @precisionbigmemtest(size=_1G + 1024 * 1024, memuse=3) + def test_big_compress_buffer(self, size): + c = zlib.compressobj(1) + compress = lambda s: c.compress(s) + c.flush() + self.check_big_compress_buffer(size, compress) + + @precisionbigmemtest(size=_1G + 1024 * 1024, memuse=2) + def test_big_decompress_buffer(self, size): + d = zlib.decompressobj() + decompress = lambda s: d.decompress(s) + d.flush() + self.check_big_decompress_buffer(size, decompress) + + def genblock(seed, length, step=1024, generator=random): """length-byte stream of random data from a seed (in step-byte blocks).""" if seed is not None: Modified: python/branches/release26-maint/Misc/NEWS ============================================================================== --- python/branches/release26-maint/Misc/NEWS (original) +++ python/branches/release26-maint/Misc/NEWS Fri May 7 18:59:00 2010 @@ -39,6 +39,10 @@ Library ------- +- Issue #8571: Fix an internal error when compressing or decompressing a + chunk larger than 1GB with the zlib module's compressor and decompressor + objects. + - Issue #8573: asyncore _strerror() function might throw ValueError. - Issue #8483: asyncore.dispatcher's __getattr__ method produced confusing Modified: python/branches/release26-maint/Modules/zlibmodule.c ============================================================================== --- python/branches/release26-maint/Modules/zlibmodule.c (original) +++ python/branches/release26-maint/Modules/zlibmodule.c Fri May 7 18:59:00 2010 @@ -392,7 +392,8 @@ static PyObject * PyZlib_objcompress(compobject *self, PyObject *args) { - int err, inplen, length = DEFAULTALLOC; + int err, inplen; + Py_ssize_t length = DEFAULTALLOC; PyObject *RetVal; Byte *input; unsigned long start_total_out; @@ -461,8 +462,8 @@ static PyObject * PyZlib_objdecompress(compobject *self, PyObject *args) { - int err, inplen, old_length, length = DEFAULTALLOC; - int max_length = 0; + int err, inplen, max_length = 0; + Py_ssize_t old_length, length = DEFAULTALLOC; PyObject *RetVal; Byte *input; unsigned long start_total_out; From python-checkins at python.org Fri May 7 19:04:02 2010 From: python-checkins at python.org (antoine.pitrou) Date: Fri, 7 May 2010 19:04:02 +0200 (CEST) Subject: [Python-checkins] r80928 - in python/branches/py3k: Lib/test/test_zlib.py Misc/NEWS Modules/zlibmodule.c Message-ID: <20100507170402.F34D4EE98D@mail.python.org> Author: antoine.pitrou Date: Fri May 7 19:04:02 2010 New Revision: 80928 Log: Merged revisions 80926 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r80926 | antoine.pitrou | 2010-05-07 18:50:34 +0200 (ven., 07 mai 2010) | 5 lines Issue #8571: Fix an internal error when compressing or decompressing a chunk larger than 1GB with the zlib module's compressor and decompressor objects. ........ Modified: python/branches/py3k/ (props changed) python/branches/py3k/Lib/test/test_zlib.py python/branches/py3k/Misc/NEWS python/branches/py3k/Modules/zlibmodule.c Modified: python/branches/py3k/Lib/test/test_zlib.py ============================================================================== --- python/branches/py3k/Lib/test/test_zlib.py (original) +++ python/branches/py3k/Lib/test/test_zlib.py Fri May 7 19:04:02 2010 @@ -2,6 +2,7 @@ from test import support import binascii import random +from test.support import precisionbigmemtest, _1G zlib = support.import_module('zlib') @@ -93,8 +94,39 @@ self.assertRaises(ValueError, zlib.decompressobj().flush, -1) +class BaseCompressTestCase(object): + def check_big_compress_buffer(self, size, compress_func): + _1M = 1024 * 1024 + fmt = "%%0%dx" % (2 * _1M) + # Generate 10MB worth of random, and expand it by repeating it. + # The assumption is that zlib's memory is not big enough to exploit + # such spread out redundancy. + data = b''.join([random.getrandbits(8 * _1M).to_bytes(_1M, 'little') + for i in range(10)]) + data = data * (size // len(data) + 1) + try: + compress_func(data) + finally: + # Release memory + data = None + + def check_big_decompress_buffer(self, size, decompress_func): + data = b'x' * size + try: + compressed = zlib.compress(data, 1) + finally: + # Release memory + data = None + data = decompress_func(compressed) + # Sanity check + try: + self.assertEqual(len(data), size) + self.assertEqual(len(data.strip(b'x')), 0) + finally: + data = None -class CompressTestCase(unittest.TestCase): + +class CompressTestCase(BaseCompressTestCase, unittest.TestCase): # Test compression in one go (whole message compression) def test_speech(self): x = zlib.compress(HAMLET_SCENE) @@ -108,9 +140,19 @@ for ob in x, bytearray(x): self.assertEqual(zlib.decompress(ob), data) + # Memory use of the following functions takes into account overallocation + + @precisionbigmemtest(size=_1G + 1024 * 1024, memuse=3) + def test_big_compress_buffer(self, size): + compress = lambda s: zlib.compress(s, 1) + self.check_big_compress_buffer(size, compress) + + @precisionbigmemtest(size=_1G + 1024 * 1024, memuse=2) + def test_big_decompress_buffer(self, size): + self.check_big_decompress_buffer(size, zlib.decompress) -class CompressObjectTestCase(unittest.TestCase): +class CompressObjectTestCase(BaseCompressTestCase, unittest.TestCase): # Test compression object def test_pair(self): # straightforward compress/decompress objects @@ -399,6 +441,21 @@ d.flush() self.assertRaises(ValueError, d.copy) + # Memory use of the following functions takes into account overallocation + + @precisionbigmemtest(size=_1G + 1024 * 1024, memuse=3) + def test_big_compress_buffer(self, size): + c = zlib.compressobj(1) + compress = lambda s: c.compress(s) + c.flush() + self.check_big_compress_buffer(size, compress) + + @precisionbigmemtest(size=_1G + 1024 * 1024, memuse=2) + def test_big_decompress_buffer(self, size): + d = zlib.decompressobj() + decompress = lambda s: d.decompress(s) + d.flush() + self.check_big_decompress_buffer(size, decompress) + + def genblock(seed, length, step=1024, generator=random): """length-byte stream of random data from a seed (in step-byte blocks).""" if seed is not None: Modified: python/branches/py3k/Misc/NEWS ============================================================================== --- python/branches/py3k/Misc/NEWS (original) +++ python/branches/py3k/Misc/NEWS Fri May 7 19:04:02 2010 @@ -348,6 +348,10 @@ Library ------- +- Issue #8571: Fix an internal error when compressing or decompressing a + chunk larger than 1GB with the zlib module's compressor and decompressor + objects. + - Issue #8603: Support bytes environmental variables on Unix: Add os.environb mapping and os.getenvb() function. os.unsetenv() encodes str argument to the file system encoding with the surrogateescape error handler (instead of Modified: python/branches/py3k/Modules/zlibmodule.c ============================================================================== --- python/branches/py3k/Modules/zlibmodule.c (original) +++ python/branches/py3k/Modules/zlibmodule.c Fri May 7 19:04:02 2010 @@ -396,7 +396,8 @@ static PyObject * PyZlib_objcompress(compobject *self, PyObject *args) { - int err, inplen, length = DEFAULTALLOC; + int err, inplen; + Py_ssize_t length = DEFAULTALLOC; PyObject *RetVal; Py_buffer pinput; Byte *input; @@ -477,8 +478,8 @@ static PyObject * PyZlib_objdecompress(compobject *self, PyObject *args) { - int err, inplen, old_length, length = DEFAULTALLOC; - int max_length = 0; + int err, inplen, max_length = 0; + Py_ssize_t old_length, length = DEFAULTALLOC; PyObject *RetVal; Py_buffer pinput; Byte *input; From python-checkins at python.org Fri May 7 19:08:54 2010 From: python-checkins at python.org (antoine.pitrou) Date: Fri, 7 May 2010 19:08:54 +0200 (CEST) Subject: [Python-checkins] r80929 - in python/branches/release31-maint: Lib/test/test_zlib.py Misc/NEWS Modules/zlibmodule.c Message-ID: <20100507170854.51135EE98D@mail.python.org> Author: antoine.pitrou Date: Fri May 7 19:08:54 2010 New Revision: 80929 Log: Merged revisions 80928 via svnmerge from svn+ssh://pythondev at svn.python.org/python/branches/py3k ................ r80928 | antoine.pitrou | 2010-05-07 19:04:02 +0200 (ven., 07 mai 2010) | 11 lines Merged revisions 80926 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r80926 | antoine.pitrou | 2010-05-07 18:50:34 +0200 (ven., 07 mai 2010) | 5 lines Issue #8571: Fix an internal error when compressing or decompressing a chunk larger than 1GB with the zlib module's compressor and decompressor objects. ........ ................ Modified: python/branches/release31-maint/ (props changed) python/branches/release31-maint/Lib/test/test_zlib.py python/branches/release31-maint/Misc/NEWS python/branches/release31-maint/Modules/zlibmodule.c Modified: python/branches/release31-maint/Lib/test/test_zlib.py ============================================================================== --- python/branches/release31-maint/Lib/test/test_zlib.py (original) +++ python/branches/release31-maint/Lib/test/test_zlib.py Fri May 7 19:08:54 2010 @@ -2,6 +2,7 @@ from test import support import binascii import random +from test.support import precisionbigmemtest, _1G zlib = support.import_module('zlib') @@ -93,8 +94,39 @@ self.assertRaises(ValueError, zlib.decompressobj().flush, -1) +class BaseCompressTestCase(object): + def check_big_compress_buffer(self, size, compress_func): + _1M = 1024 * 1024 + fmt = "%%0%dx" % (2 * _1M) + # Generate 10MB worth of random, and expand it by repeating it. + # The assumption is that zlib's memory is not big enough to exploit + # such spread out redundancy. + data = b''.join([random.getrandbits(8 * _1M).to_bytes(_1M, 'little') + for i in range(10)]) + data = data * (size // len(data) + 1) + try: + compress_func(data) + finally: + # Release memory + data = None + + def check_big_decompress_buffer(self, size, decompress_func): + data = b'x' * size + try: + compressed = zlib.compress(data, 1) + finally: + # Release memory + data = None + data = decompress_func(compressed) + # Sanity check + try: + self.assertEqual(len(data), size) + self.assertEqual(len(data.strip(b'x')), 0) + finally: + data = None -class CompressTestCase(unittest.TestCase): + +class CompressTestCase(BaseCompressTestCase, unittest.TestCase): # Test compression in one go (whole message compression) def test_speech(self): x = zlib.compress(HAMLET_SCENE) @@ -108,9 +140,19 @@ for ob in x, bytearray(x): self.assertEqual(zlib.decompress(ob), data) + # Memory use of the following functions takes into account overallocation + + @precisionbigmemtest(size=_1G + 1024 * 1024, memuse=3) + def test_big_compress_buffer(self, size): + compress = lambda s: zlib.compress(s, 1) + self.check_big_compress_buffer(size, compress) + + @precisionbigmemtest(size=_1G + 1024 * 1024, memuse=2) + def test_big_decompress_buffer(self, size): + self.check_big_decompress_buffer(size, zlib.decompress) -class CompressObjectTestCase(unittest.TestCase): +class CompressObjectTestCase(BaseCompressTestCase, unittest.TestCase): # Test compression object def test_pair(self): # straightforward compress/decompress objects @@ -399,6 +441,21 @@ d.flush() self.assertRaises(ValueError, d.copy) + # Memory use of the following functions takes into account overallocation + + @precisionbigmemtest(size=_1G + 1024 * 1024, memuse=3) + def test_big_compress_buffer(self, size): + c = zlib.compressobj(1) + compress = lambda s: c.compress(s) + c.flush() + self.check_big_compress_buffer(size, compress) + + @precisionbigmemtest(size=_1G + 1024 * 1024, memuse=2) + def test_big_decompress_buffer(self, size): + d = zlib.decompressobj() + decompress = lambda s: d.decompress(s) + d.flush() + self.check_big_decompress_buffer(size, decompress) + + def genblock(seed, length, step=1024, generator=random): """length-byte stream of random data from a seed (in step-byte blocks).""" if seed is not None: Modified: python/branches/release31-maint/Misc/NEWS ============================================================================== --- python/branches/release31-maint/Misc/NEWS (original) +++ python/branches/release31-maint/Misc/NEWS Fri May 7 19:08:54 2010 @@ -40,6 +40,10 @@ Library ------- +- Issue #8571: Fix an internal error when compressing or decompressing a + chunk larger than 1GB with the zlib module's compressor and decompressor + objects. + - Issue #8573: asyncore _strerror() function might throw ValueError. - Issue #8483: asyncore.dispatcher's __getattr__ method produced confusing Modified: python/branches/release31-maint/Modules/zlibmodule.c ============================================================================== --- python/branches/release31-maint/Modules/zlibmodule.c (original) +++ python/branches/release31-maint/Modules/zlibmodule.c Fri May 7 19:08:54 2010 @@ -396,7 +396,8 @@ static PyObject * PyZlib_objcompress(compobject *self, PyObject *args) { - int err, inplen, length = DEFAULTALLOC; + int err, inplen; + Py_ssize_t length = DEFAULTALLOC; PyObject *RetVal; Py_buffer pinput; Byte *input; @@ -477,8 +478,8 @@ static PyObject * PyZlib_objdecompress(compobject *self, PyObject *args) { - int err, inplen, old_length, length = DEFAULTALLOC; - int max_length = 0; + int err, inplen, max_length = 0; + Py_ssize_t old_length, length = DEFAULTALLOC; PyObject *RetVal; Py_buffer pinput; Byte *input; From python-checkins at python.org Fri May 7 19:59:50 2010 From: python-checkins at python.org (giampaolo.rodola) Date: Fri, 7 May 2010 19:59:50 +0200 (CEST) Subject: [Python-checkins] r80930 - python/branches/asyncore-tests-issue8490/Lib/test/test_asyncore.py Message-ID: <20100507175950.AFA12EEA00@mail.python.org> Author: giampaolo.rodola Date: Fri May 7 19:59:50 2010 New Revision: 80930 Log: determine whether we're on solaris by using sys.platform == 'sunos' instead of 'solaris' Modified: python/branches/asyncore-tests-issue8490/Lib/test/test_asyncore.py Modified: python/branches/asyncore-tests-issue8490/Lib/test/test_asyncore.py ============================================================================== --- python/branches/asyncore-tests-issue8490/Lib/test/test_asyncore.py (original) +++ python/branches/asyncore-tests-issue8490/Lib/test/test_asyncore.py Fri May 7 19:59:50 2010 @@ -552,7 +552,7 @@ client = TestClient(server.address) self.loop_waiting_for_flag(client) - @unittest.skipIf(sys.platform.startswith("solaris"), "OOB support is broken") + @unittest.skipIf(sys.platform.startswith("sunos"), "OOB support is broken") def test_handle_expt(self): # Make sure handle_expt is called on OOB data received. # Note: this might fail on some platforms as OOB data is @@ -598,7 +598,7 @@ self.assertTrue(server.accepting) # solaris seems to connect() immediately even without starting # the poller - if not sys.platform.startswith("solaris"): + if not sys.platform.startswith("sunos"): self.assertFalse(client.connected) self.assertFalse(client.accepting) From python-checkins at python.org Fri May 7 20:09:36 2010 From: python-checkins at python.org (antoine.pitrou) Date: Fri, 7 May 2010 20:09:36 +0200 (CEST) Subject: [Python-checkins] r80931 - python/branches/release31-maint/Lib/test/test_zlib.py Message-ID: <20100507180936.7A0A6EE9EA@mail.python.org> Author: antoine.pitrou Date: Fri May 7 20:09:36 2010 New Revision: 80931 Log: Fix failure introduced in r80929. Modified: python/branches/release31-maint/Lib/test/test_zlib.py Modified: python/branches/release31-maint/Lib/test/test_zlib.py ============================================================================== --- python/branches/release31-maint/Lib/test/test_zlib.py (original) +++ python/branches/release31-maint/Lib/test/test_zlib.py Fri May 7 20:09:36 2010 @@ -101,7 +101,7 @@ # Generate 10MB worth of random, and expand it by repeating it. # The assumption is that zlib's memory is not big enough to exploit # such spread out redundancy. - data = b''.join([random.getrandbits(8 * _1M).to_bytes(_1M, 'little') + data = b''.join([binascii.a2b_hex(fmt % random.getrandbits(8 * _1M)) for i in range(10)]) data = data * (size // len(data) + 1) try: From python-checkins at python.org Fri May 7 20:16:19 2010 From: python-checkins at python.org (michael.foord) Date: Fri, 7 May 2010 20:16:19 +0200 (CEST) Subject: [Python-checkins] r80932 - in python/trunk/Lib/unittest: loader.py test/test_discovery.py Message-ID: <20100507181619.EC0DFC8AF@mail.python.org> Author: michael.foord Date: Fri May 7 20:16:19 2010 New Revision: 80932 Log: Issue 8547 - detecting and reporting that modules have been imported from the wrong location under test discovery. Modified: python/trunk/Lib/unittest/loader.py python/trunk/Lib/unittest/test/test_discovery.py Modified: python/trunk/Lib/unittest/loader.py ============================================================================== --- python/trunk/Lib/unittest/loader.py (original) +++ python/trunk/Lib/unittest/loader.py Fri May 7 20:16:19 2010 @@ -173,7 +173,10 @@ if not top_level_dir in sys.path: # all test modules must be importable from the top level directory - sys.path.append(top_level_dir) + # should we *unconditionally* put the start directory in first + # in sys.path to minimise likelihood of conflicts between installed + # modules and development versions? + sys.path.insert(0, top_level_dir) self._top_level_dir = top_level_dir is_not_importable = False @@ -246,6 +249,16 @@ except: yield _make_failed_import_test(name, self.suiteClass) else: + mod_file = os.path.abspath(getattr(module, '__file__', full_path)) + 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] + expected_dir = os.path.dirname(full_path) + msg = ("%r module incorrectly imported from %r. Expected %r. " + "Is this module globally installed?") + raise ImportError(msg % (mod_name, module_dir, expected_dir)) yield self.loadTestsFromModule(module) elif os.path.isdir(full_path): if not os.path.isfile(os.path.join(full_path, '__init__.py')): Modified: python/trunk/Lib/unittest/test/test_discovery.py ============================================================================== --- python/trunk/Lib/unittest/test/test_discovery.py (original) +++ python/trunk/Lib/unittest/test/test_discovery.py Fri May 7 20:16:19 2010 @@ -298,6 +298,45 @@ self.assertTrue(program.failfast) self.assertTrue(program.catchbreak) + def test_detect_module_clash(self): + class Module(object): + __file__ = 'bar/foo.py' + sys.modules['foo'] = Module + full_path = os.path.abspath('foo') + original_listdir = os.listdir + original_isfile = os.path.isfile + original_isdir = os.path.isdir + + def cleanup(): + os.listdir = original_listdir + os.path.isfile = original_isfile + os.path.isdir = original_isdir + del sys.modules['foo'] + if full_path in sys.path: + sys.path.remove(full_path) + self.addCleanup(cleanup) + + def listdir(_): + return ['foo.py'] + def isfile(_): + return True + def isdir(_): + return True + os.listdir = listdir + os.path.isfile = isfile + os.path.isdir = isdir + + loader = unittest.TestLoader() + + mod_dir = os.path.abspath('bar') + expected_dir = os.path.abspath('foo') + msg = (r"^'foo' module incorrectly imported from %r\. Expected %r\. " + "Is this module globally installed\?$") % (mod_dir, expected_dir) + self.assertRaisesRegexp( + ImportError, msg, loader.discover, + start_dir='foo', pattern='foo.py' + ) + self.assertEqual(sys.path[0], full_path) if __name__ == '__main__': unittest.main() From python-checkins at python.org Fri May 7 20:18:14 2010 From: python-checkins at python.org (michael.foord) Date: Fri, 7 May 2010 20:18:14 +0200 (CEST) Subject: [Python-checkins] r80933 - in python/branches/py3k: Lib/unittest/loader.py Lib/unittest/test/test_discovery.py Message-ID: <20100507181814.E7EE0D9C8@mail.python.org> Author: michael.foord Date: Fri May 7 20:18:14 2010 New Revision: 80933 Log: Merged revisions 80932 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r80932 | michael.foord | 2010-05-07 20:16:19 +0200 (Fri, 07 May 2010) | 1 line Issue 8547 - detecting and reporting that modules have been imported from the wrong location under test discovery. ........ Modified: python/branches/py3k/ (props changed) python/branches/py3k/Lib/unittest/loader.py python/branches/py3k/Lib/unittest/test/test_discovery.py Modified: python/branches/py3k/Lib/unittest/loader.py ============================================================================== --- python/branches/py3k/Lib/unittest/loader.py (original) +++ python/branches/py3k/Lib/unittest/loader.py Fri May 7 20:18:14 2010 @@ -178,7 +178,10 @@ if not top_level_dir in sys.path: # all test modules must be importable from the top level directory - sys.path.append(top_level_dir) + # should we *unconditionally* put the start directory in first + # in sys.path to minimise likelihood of conflicts between installed + # modules and development versions? + sys.path.insert(0, top_level_dir) self._top_level_dir = top_level_dir is_not_importable = False @@ -251,6 +254,16 @@ except: yield _make_failed_import_test(name, self.suiteClass) else: + mod_file = os.path.abspath(getattr(module, '__file__', full_path)) + 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] + expected_dir = os.path.dirname(full_path) + msg = ("%r module incorrectly imported from %r. Expected %r. " + "Is this module globally installed?") + raise ImportError(msg % (mod_name, module_dir, expected_dir)) yield self.loadTestsFromModule(module) elif os.path.isdir(full_path): if not os.path.isfile(os.path.join(full_path, '__init__.py')): Modified: python/branches/py3k/Lib/unittest/test/test_discovery.py ============================================================================== --- python/branches/py3k/Lib/unittest/test/test_discovery.py (original) +++ python/branches/py3k/Lib/unittest/test/test_discovery.py Fri May 7 20:18:14 2010 @@ -294,6 +294,45 @@ self.assertTrue(program.failfast) self.assertTrue(program.catchbreak) + def test_detect_module_clash(self): + class Module(object): + __file__ = 'bar/foo.py' + sys.modules['foo'] = Module + full_path = os.path.abspath('foo') + original_listdir = os.listdir + original_isfile = os.path.isfile + original_isdir = os.path.isdir + + def cleanup(): + os.listdir = original_listdir + os.path.isfile = original_isfile + os.path.isdir = original_isdir + del sys.modules['foo'] + if full_path in sys.path: + sys.path.remove(full_path) + self.addCleanup(cleanup) + + def listdir(_): + return ['foo.py'] + def isfile(_): + return True + def isdir(_): + return True + os.listdir = listdir + os.path.isfile = isfile + os.path.isdir = isdir + + loader = unittest.TestLoader() + + mod_dir = os.path.abspath('bar') + expected_dir = os.path.abspath('foo') + msg = (r"^'foo' module incorrectly imported from %r\. Expected %r\. " + "Is this module globally installed\?$") % (mod_dir, expected_dir) + self.assertRaisesRegexp( + ImportError, msg, loader.discover, + start_dir='foo', pattern='foo.py' + ) + self.assertEqual(sys.path[0], full_path) if __name__ == '__main__': unittest.main() From python-checkins at python.org Fri May 7 20:58:24 2010 From: python-checkins at python.org (benjamin.peterson) Date: Fri, 7 May 2010 20:58:24 +0200 (CEST) Subject: [Python-checkins] r80934 - in python/trunk/Lib/lib2to3: fixes/fix_import.py fixes/fix_operator.py fixes/fix_reduce.py fixes/fix_sys_exc.py fixes/fix_tuple_params.py fixes/fix_xrange.py main.py patcomp.py pgen2/tokenize.py pytree.py refactor.py tests/test_fixers.py tests/test_parser.py tests/test_pytree.py tests/test_refactor.py Message-ID: <20100507185824.0C5C2F87B@mail.python.org> Author: benjamin.peterson Date: Fri May 7 20:58:23 2010 New Revision: 80934 Log: Merged revisions 79911,79916-79917,80018,80418,80572-80573,80635-80639,80668,80922 via svnmerge from svn+ssh://pythondev at svn.python.org/sandbox/trunk/2to3/lib2to3 ........ r79911 | benjamin.peterson | 2010-04-09 15:38:53 -0500 (Fri, 09 Apr 2010) | 1 line use absolute import ........ r79916 | benjamin.peterson | 2010-04-09 16:05:21 -0500 (Fri, 09 Apr 2010) | 1 line generalize detection of __future__ imports and attach them to the tree ........ r79917 | benjamin.peterson | 2010-04-09 16:11:44 -0500 (Fri, 09 Apr 2010) | 1 line don't try to 'fix' relative imports when absolute_import is enabled #8858 ........ r80018 | benjamin.peterson | 2010-04-12 16:12:12 -0500 (Mon, 12 Apr 2010) | 4 lines prevent diffs from being mangled is multiprocess mode #6409 Patch by George Boutsioukis. ........ r80418 | benjamin.peterson | 2010-04-23 16:00:03 -0500 (Fri, 23 Apr 2010) | 1 line remove unhelpful description ........ r80572 | benjamin.peterson | 2010-04-27 20:33:54 -0500 (Tue, 27 Apr 2010) | 1 line use unicode literals ........ r80573 | jeffrey.yasskin | 2010-04-27 23:08:27 -0500 (Tue, 27 Apr 2010) | 6 lines Don't transform imports that are already relative. 2to3 turned from . import refactor into from .. import refactor which broke the transformation of 2to3 itself. ........ r80635 | benjamin.peterson | 2010-04-29 16:02:23 -0500 (Thu, 29 Apr 2010) | 1 line remove imports ........ r80636 | benjamin.peterson | 2010-04-29 16:02:41 -0500 (Thu, 29 Apr 2010) | 1 line unicode literal ........ r80637 | benjamin.peterson | 2010-04-29 16:03:42 -0500 (Thu, 29 Apr 2010) | 1 line must pass a string to Number ........ r80638 | benjamin.peterson | 2010-04-29 16:05:34 -0500 (Thu, 29 Apr 2010) | 1 line unicode literals ........ r80639 | benjamin.peterson | 2010-04-29 16:06:09 -0500 (Thu, 29 Apr 2010) | 1 line pass string to Number ........ r80668 | jeffrey.yasskin | 2010-04-30 18:02:47 -0500 (Fri, 30 Apr 2010) | 4 lines Make 2to3 run under Python 2.5 so that the benchmark suite at http://hg.python.org/benchmarks/ can use it and still run on implementations that haven't gotten to 2.6 yet. Fixes issue 8566. ........ r80922 | benjamin.peterson | 2010-05-07 11:06:25 -0500 (Fri, 07 May 2010) | 1 line prevent xrange transformation from wrapping range calls it produces in list ........ Modified: python/trunk/Lib/lib2to3/ (props changed) python/trunk/Lib/lib2to3/fixes/fix_import.py python/trunk/Lib/lib2to3/fixes/fix_operator.py python/trunk/Lib/lib2to3/fixes/fix_reduce.py python/trunk/Lib/lib2to3/fixes/fix_sys_exc.py python/trunk/Lib/lib2to3/fixes/fix_tuple_params.py python/trunk/Lib/lib2to3/fixes/fix_xrange.py python/trunk/Lib/lib2to3/main.py python/trunk/Lib/lib2to3/patcomp.py python/trunk/Lib/lib2to3/pgen2/tokenize.py python/trunk/Lib/lib2to3/pytree.py python/trunk/Lib/lib2to3/refactor.py python/trunk/Lib/lib2to3/tests/test_fixers.py python/trunk/Lib/lib2to3/tests/test_parser.py python/trunk/Lib/lib2to3/tests/test_pytree.py python/trunk/Lib/lib2to3/tests/test_refactor.py Modified: python/trunk/Lib/lib2to3/fixes/fix_import.py ============================================================================== --- python/trunk/Lib/lib2to3/fixes/fix_import.py (original) +++ python/trunk/Lib/lib2to3/fixes/fix_import.py Fri May 7 20:58:23 2010 @@ -43,7 +43,13 @@ import_name< 'import' imp=any > """ + def start_tree(self, tree, name): + super(FixImport, self).start_tree(tree, name) + self.skip = "absolute_import" in tree.future_features + def transform(self, node, results): + if self.skip: + return imp = results['imp'] if node.type == syms.import_from: @@ -71,19 +77,22 @@ self.warning(node, "absolute and local imports together") return - new = FromImport('.', [imp]) + new = FromImport(u".", [imp]) new.prefix = node.prefix return new def probably_a_local_import(self, imp_name): - imp_name = imp_name.split('.', 1)[0] + if imp_name.startswith(u"."): + # Relative imports are certainly not local imports. + return False + imp_name = imp_name.split(u".", 1)[0] base_path = dirname(self.filename) base_path = join(base_path, imp_name) # If there is no __init__.py next to the file its not in a package # so can't be a relative import. - if not exists(join(dirname(base_path), '__init__.py')): + if not exists(join(dirname(base_path), "__init__.py")): return False - for ext in ['.py', sep, '.pyc', '.so', '.sl', '.pyd']: + for ext in [".py", sep, ".pyc", ".so", ".sl", ".pyd"]: if exists(base_path + ext): return True return False Modified: python/trunk/Lib/lib2to3/fixes/fix_operator.py ============================================================================== --- python/trunk/Lib/lib2to3/fixes/fix_operator.py (original) +++ python/trunk/Lib/lib2to3/fixes/fix_operator.py Fri May 7 20:58:23 2010 @@ -14,10 +14,10 @@ func = "'(' func=any ')'" PATTERN = """ power< module='operator' - trailer< '.' {methods} > trailer< {func} > > + trailer< '.' %(methods)s > trailer< %(func)s > > | - power< {methods} trailer< {func} > > - """.format(methods=methods, func=func) + power< %(methods)s trailer< %(func)s > > + """ % dict(methods=methods, func=func) def transform(self, node, results): method = results["method"][0] Modified: python/trunk/Lib/lib2to3/fixes/fix_reduce.py ============================================================================== --- python/trunk/Lib/lib2to3/fixes/fix_reduce.py (original) +++ python/trunk/Lib/lib2to3/fixes/fix_reduce.py Fri May 7 20:58:23 2010 @@ -7,9 +7,8 @@ used in that module. """ -from .. import pytree -from .. import fixer_base -from ..fixer_util import Name, Attr, touch_import +from lib2to3 import fixer_base +from lib2to3.fixer_util import touch_import Modified: python/trunk/Lib/lib2to3/fixes/fix_sys_exc.py ============================================================================== --- python/trunk/Lib/lib2to3/fixes/fix_sys_exc.py (original) +++ python/trunk/Lib/lib2to3/fixes/fix_sys_exc.py Fri May 7 20:58:23 2010 @@ -13,14 +13,14 @@ class FixSysExc(fixer_base.BaseFix): # This order matches the ordering of sys.exc_info(). - exc_info = ["exc_type", "exc_value", "exc_traceback"] + exc_info = [u"exc_type", u"exc_value", u"exc_traceback"] PATTERN = """ power< 'sys' trailer< dot='.' attribute=(%s) > > """ % '|'.join("'%s'" % e for e in exc_info) def transform(self, node, results): sys_attr = results["attribute"][0] - index = Number(self.exc_info.index(sys_attr.value)) + index = Number(unicode(self.exc_info.index(sys_attr.value))) call = Call(Name(u"exc_info"), prefix=sys_attr.prefix) attr = Attr(Name(u"sys"), call) Modified: python/trunk/Lib/lib2to3/fixes/fix_tuple_params.py ============================================================================== --- python/trunk/Lib/lib2to3/fixes/fix_tuple_params.py (original) +++ python/trunk/Lib/lib2to3/fixes/fix_tuple_params.py Fri May 7 20:58:23 2010 @@ -54,7 +54,7 @@ end = Newline() else: start = 0 - indent = "; " + indent = u"; " end = pytree.Leaf(token.INDENT, u"") # We need access to self for new_name(), and making this a method @@ -154,7 +154,7 @@ if d is None: d = {} for i, obj in enumerate(param_list): - trailer = [Subscript(Number(i))] + trailer = [Subscript(Number(unicode(i)))] if isinstance(obj, list): map_to_index(obj, trailer, d=d) else: Modified: python/trunk/Lib/lib2to3/fixes/fix_xrange.py ============================================================================== --- python/trunk/Lib/lib2to3/fixes/fix_xrange.py (original) +++ python/trunk/Lib/lib2to3/fixes/fix_xrange.py Fri May 7 20:58:23 2010 @@ -17,6 +17,13 @@ rest=any* > """ + def start_tree(self, tree, filename): + super(FixXrange, self).start_tree(tree, filename) + self.transformed_xranges = set() + + def finish_tree(self, tree, filename): + self.transformed_xranges = None + def transform(self, node, results): name = results["name"] if name.value == u"xrange": @@ -29,9 +36,12 @@ def transform_xrange(self, node, results): name = results["name"] name.replace(Name(u"range", prefix=name.prefix)) + # This prevents the new range call from being wrapped in a list later. + self.transformed_xranges.add(id(node)) def transform_range(self, node, results): - if not self.in_special_context(node): + if (id(node) not in self.transformed_xranges and + not self.in_special_context(node)): range_call = Call(Name(u"range"), [results["args"].clone()]) # Encase the range call in list(). list_call = Call(Name(u"list"), [range_call], Modified: python/trunk/Lib/lib2to3/main.py ============================================================================== --- python/trunk/Lib/lib2to3/main.py (original) +++ python/trunk/Lib/lib2to3/main.py Fri May 7 20:58:23 2010 @@ -2,6 +2,8 @@ Main program for 2to3. """ +from __future__ import with_statement + import sys import os import difflib @@ -62,8 +64,14 @@ if self.show_diffs: diff_lines = diff_texts(old, new, filename) try: - for line in diff_lines: - print line + if self.output_lock is not None: + with self.output_lock: + for line in diff_lines: + print line + sys.stdout.flush() + else: + for line in diff_lines: + print line except UnicodeEncodeError: warn("couldn't encode %s's diff for your terminal" % (filename,)) @@ -95,7 +103,7 @@ parser.add_option("-x", "--nofix", action="append", default=[], help="Prevent a fixer from being run.") parser.add_option("-l", "--list-fixes", action="store_true", - help="List available transformations (fixes/fix_*.py)") + help="List available transformations") parser.add_option("-p", "--print-function", action="store_true", help="Modify the grammar so that print() is a function") parser.add_option("-v", "--verbose", action="store_true", Modified: python/trunk/Lib/lib2to3/patcomp.py ============================================================================== --- python/trunk/Lib/lib2to3/patcomp.py (original) +++ python/trunk/Lib/lib2to3/patcomp.py Fri May 7 20:58:23 2010 @@ -57,7 +57,7 @@ tokens = tokenize_wrapper(input) try: root = self.driver.parse_tokens(tokens, debug=debug) - except parse.ParseError as e: + except parse.ParseError, e: raise PatternSyntaxError(str(e)) return self.compile_node(root) Modified: python/trunk/Lib/lib2to3/pgen2/tokenize.py ============================================================================== --- python/trunk/Lib/lib2to3/pgen2/tokenize.py (original) +++ python/trunk/Lib/lib2to3/pgen2/tokenize.py Fri May 7 20:58:23 2010 @@ -38,6 +38,13 @@ "generate_tokens", "untokenize"] del token +try: + bytes +except NameError: + # Support bytes type in Python <= 2.5, so 2to3 turns itself into + # valid Python 3 code. + bytes = str + def group(*choices): return '(' + '|'.join(choices) + ')' def any(*choices): return group(*choices) + '*' def maybe(*choices): return group(*choices) + '?' @@ -267,7 +274,7 @@ try: return readline() except StopIteration: - return b'' + return bytes() def find_cookie(line): try: Modified: python/trunk/Lib/lib2to3/pytree.py ============================================================================== --- python/trunk/Lib/lib2to3/pytree.py (original) +++ python/trunk/Lib/lib2to3/pytree.py Fri May 7 20:58:23 2010 @@ -289,8 +289,7 @@ for node in child.post_order(): yield node - @property - def prefix(self): + def _prefix_getter(self): """ The whitespace and comments preceding this node in the input. """ @@ -298,11 +297,12 @@ return "" return self.children[0].prefix - @prefix.setter - def prefix(self, prefix): + def _prefix_setter(self, prefix): if self.children: self.children[0].prefix = prefix + prefix = property(_prefix_getter, _prefix_setter) + def set_child(self, i, child): """ Equivalent to 'node.children[i] = child'. This method also sets the @@ -390,18 +390,17 @@ """Return a pre-order iterator for the tree.""" yield self - @property - def prefix(self): + def _prefix_getter(self): """ The whitespace and comments preceding this token in the input. """ return self._prefix - @prefix.setter - def prefix(self, prefix): + def _prefix_setter(self, prefix): self.changed() self._prefix = prefix + prefix = property(_prefix_getter, _prefix_setter) def convert(gr, raw_node): """ Modified: python/trunk/Lib/lib2to3/refactor.py ============================================================================== --- python/trunk/Lib/lib2to3/refactor.py (original) +++ python/trunk/Lib/lib2to3/refactor.py Fri May 7 20:58:23 2010 @@ -8,6 +8,8 @@ provides infrastructure to write your own refactoring tool. """ +from __future__ import with_statement + __author__ = "Guido van Rossum " @@ -122,13 +124,14 @@ _to_system_newlines = _identity -def _detect_future_print(source): +def _detect_future_features(source): have_docstring = False gen = tokenize.generate_tokens(StringIO.StringIO(source).readline) def advance(): - tok = next(gen) + tok = gen.next() return tok[0], tok[1] ignore = frozenset((token.NEWLINE, tokenize.NL, token.COMMENT)) + features = set() try: while True: tp, value = advance() @@ -140,26 +143,25 @@ have_docstring = True elif tp == token.NAME and value == u"from": tp, value = advance() - if tp != token.NAME and value != u"__future__": + if tp != token.NAME or value != u"__future__": break tp, value = advance() - if tp != token.NAME and value != u"import": + if tp != token.NAME or value != u"import": break tp, value = advance() if tp == token.OP and value == u"(": tp, value = advance() while tp == token.NAME: - if value == u"print_function": - return True + features.add(value) tp, value = advance() - if tp != token.OP and value != u",": + if tp != token.OP or value != u",": break tp, value = advance() else: break except StopIteration: pass - return False + return frozenset(features) class FixerError(Exception): @@ -341,7 +343,8 @@ An AST corresponding to the refactored input stream; None if there were errors during the parse. """ - if _detect_future_print(data): + features = _detect_future_features(data) + if "print_function" in features: self.driver.grammar = pygram.python_grammar_no_print_statement try: tree = self.driver.parse_string(data) @@ -351,6 +354,7 @@ return finally: self.driver.grammar = self.grammar + tree.future_features = features self.log_debug("Refactoring %s", name) self.refactor_tree(tree, name) return tree @@ -605,6 +609,7 @@ def __init__(self, *args, **kwargs): super(MultiprocessRefactoringTool, self).__init__(*args, **kwargs) self.queue = None + self.output_lock = None def refactor(self, items, write=False, doctests_only=False, num_processes=1): @@ -618,6 +623,7 @@ if self.queue is not None: raise RuntimeError("already doing multiple processes") self.queue = multiprocessing.JoinableQueue() + self.output_lock = multiprocessing.Lock() processes = [multiprocessing.Process(target=self._child) for i in xrange(num_processes)] try: Modified: python/trunk/Lib/lib2to3/tests/test_fixers.py ============================================================================== --- python/trunk/Lib/lib2to3/tests/test_fixers.py (original) +++ python/trunk/Lib/lib2to3/tests/test_fixers.py Fri May 7 20:58:23 2010 @@ -1497,6 +1497,17 @@ for call in fixer_util.consuming_calls: self.unchanged("a = %s(range(10))" % call) +class Test_xrange_with_reduce(FixerTestCase): + + def setUp(self): + super(Test_xrange_with_reduce, self).setUp(["xrange", "reduce"]) + + def test_double_transform(self): + b = """reduce(x, xrange(5))""" + a = """from functools import reduce +reduce(x, range(5))""" + self.check(b, a) + class Test_raw_input(FixerTestCase): fixer = "raw_input" @@ -3679,7 +3690,7 @@ self.files_checked.append(name) return self.always_exists or (name in self.present_files) - from ..fixes import fix_import + from lib2to3.fixes import fix_import fix_import.exists = fake_exists def tearDown(self): @@ -3722,6 +3733,12 @@ self.present_files = set(["bar.py"]) self.unchanged(s) + def test_with_absolute_import_enabled(self): + s = "from __future__ import absolute_import\nimport bar" + self.always_exists = False + self.present_files = set(["__init__.py", "bar.py"]) + self.unchanged(s) + def test_in_package(self): b = "import bar" a = "from . import bar" @@ -3736,6 +3753,10 @@ self.present_files = set(["__init__.py", "bar" + os.path.sep]) self.check(b, a) + def test_already_relative_import(self): + s = "from . import bar" + self.unchanged(s) + def test_comments_and_indent(self): b = "import bar # Foo" a = "from . import bar # Foo" Modified: python/trunk/Lib/lib2to3/tests/test_parser.py ============================================================================== --- python/trunk/Lib/lib2to3/tests/test_parser.py (original) +++ python/trunk/Lib/lib2to3/tests/test_parser.py Fri May 7 20:58:23 2010 @@ -6,13 +6,14 @@ test_grammar.py files from both Python 2 and Python 3. """ +from __future__ import with_statement + # Testing imports from . import support from .support import driver, test_dir # Python imports import os -import io import sys # Local imports @@ -156,8 +157,9 @@ encoding = tokenize.detect_encoding(fp.readline)[0] self.assertTrue(encoding is not None, "can't detect encoding for %s" % filepath) - with io.open(filepath, "r", encoding=encoding) as fp: + with open(filepath, "r") as fp: source = fp.read() + source = source.decode(encoding) tree = driver.parse_string(source) new = unicode(tree) if diff(filepath, new, encoding): @@ -203,9 +205,9 @@ def diff(fn, result, encoding): - f = io.open("@", "w", encoding=encoding) + f = open("@", "w") try: - f.write(result) + f.write(result.encode(encoding)) finally: f.close() try: Modified: python/trunk/Lib/lib2to3/tests/test_pytree.py ============================================================================== --- python/trunk/Lib/lib2to3/tests/test_pytree.py (original) +++ python/trunk/Lib/lib2to3/tests/test_pytree.py Fri May 7 20:58:23 2010 @@ -9,6 +9,9 @@ especially when debugging a test. """ +from __future__ import with_statement + +import sys import warnings # Testing imports @@ -28,20 +31,22 @@ """Unit tests for nodes (Base, Leaf, Node).""" - def test_deprecated_prefix_methods(self): - l = pytree.Leaf(100, "foo") - with warnings.catch_warnings(record=True) as w: - warnings.simplefilter("always", DeprecationWarning) - self.assertEqual(l.get_prefix(), "") - l.set_prefix("hi") - self.assertEqual(l.prefix, "hi") - self.assertEqual(len(w), 2) - for warning in w: - self.assertTrue(warning.category is DeprecationWarning) - self.assertEqual(str(w[0].message), "get_prefix() is deprecated; " \ - "use the prefix property") - self.assertEqual(str(w[1].message), "set_prefix() is deprecated; " \ - "use the prefix property") + if sys.version_info >= (2,6): + # warnings.catch_warnings is new in 2.6. + def test_deprecated_prefix_methods(self): + l = pytree.Leaf(100, "foo") + with warnings.catch_warnings(record=True) as w: + warnings.simplefilter("always", DeprecationWarning) + self.assertEqual(l.get_prefix(), "") + l.set_prefix("hi") + self.assertEqual(l.prefix, "hi") + self.assertEqual(len(w), 2) + for warning in w: + self.assertTrue(warning.category is DeprecationWarning) + self.assertEqual(str(w[0].message), "get_prefix() is deprecated; " \ + "use the prefix property") + self.assertEqual(str(w[1].message), "set_prefix() is deprecated; " \ + "use the prefix property") def test_instantiate_base(self): if __debug__: Modified: python/trunk/Lib/lib2to3/tests/test_refactor.py ============================================================================== --- python/trunk/Lib/lib2to3/tests/test_refactor.py (original) +++ python/trunk/Lib/lib2to3/tests/test_refactor.py Fri May 7 20:58:23 2010 @@ -2,6 +2,8 @@ Unit tests for refactor.py. """ +from __future__ import with_statement + import sys import os import codecs @@ -61,42 +63,50 @@ self.assertEqual(full_names, ["myfixes.fix_" + name for name in contents]) - def test_detect_future_print(self): - run = refactor._detect_future_print - self.assertFalse(run("")) - self.assertTrue(run("from __future__ import print_function")) - self.assertFalse(run("from __future__ import generators")) - self.assertFalse(run("from __future__ import generators, feature")) - input = "from __future__ import generators, print_function" - self.assertTrue(run(input)) - input ="from __future__ import print_function, generators" - self.assertTrue(run(input)) - input = "from __future__ import (print_function,)" - self.assertTrue(run(input)) - input = "from __future__ import (generators, print_function)" - self.assertTrue(run(input)) - input = "from __future__ import (generators, nested_scopes)" - self.assertFalse(run(input)) - input = """from __future__ import generators + def test_detect_future_features(self): + run = refactor._detect_future_features + fs = frozenset + empty = fs() + self.assertEqual(run(""), empty) + self.assertEqual(run("from __future__ import print_function"), + fs(("print_function",))) + self.assertEqual(run("from __future__ import generators"), + fs(("generators",))) + self.assertEqual(run("from __future__ import generators, feature"), + fs(("generators", "feature"))) + inp = "from __future__ import generators, print_function" + self.assertEqual(run(inp), fs(("generators", "print_function"))) + inp ="from __future__ import print_function, generators" + self.assertEqual(run(inp), fs(("print_function", "generators"))) + inp = "from __future__ import (print_function,)" + self.assertEqual(run(inp), fs(("print_function",))) + inp = "from __future__ import (generators, print_function)" + self.assertEqual(run(inp), fs(("generators", "print_function"))) + inp = "from __future__ import (generators, nested_scopes)" + self.assertEqual(run(inp), fs(("generators", "nested_scopes"))) + inp = """from __future__ import generators from __future__ import print_function""" - self.assertTrue(run(input)) - self.assertFalse(run("from")) - self.assertFalse(run("from 4")) - self.assertFalse(run("from x")) - self.assertFalse(run("from x 5")) - self.assertFalse(run("from x im")) - self.assertFalse(run("from x import")) - self.assertFalse(run("from x import 4")) - input = "'docstring'\nfrom __future__ import print_function" - self.assertTrue(run(input)) - input = "'docstring'\n'somng'\nfrom __future__ import print_function" - self.assertFalse(run(input)) - input = "# comment\nfrom __future__ import print_function" - self.assertTrue(run(input)) - input = "# comment\n'doc'\nfrom __future__ import print_function" - self.assertTrue(run(input)) - input = "class x: pass\nfrom __future__ import print_function" - self.assertFalse(run(input)) + self.assertEqual(run(inp), fs(("generators", "print_function"))) + invalid = ("from", + "from 4", + "from x", + "from x 5", + "from x im", + "from x import", + "from x import 4", + ) + for inp in invalid: + self.assertEqual(run(inp), empty) + inp = "'docstring'\nfrom __future__ import print_function" + self.assertEqual(run(inp), fs(("print_function",))) + inp = "'docstring'\n'somng'\nfrom __future__ import print_function" + self.assertEqual(run(inp), empty) + inp = "# comment\nfrom __future__ import print_function" + self.assertEqual(run(inp), fs(("print_function",))) + inp = "# comment\n'doc'\nfrom __future__ import print_function" + self.assertEqual(run(inp), fs(("print_function",))) + inp = "class x: pass\nfrom __future__ import print_function" + self.assertEqual(run(inp), empty) def test_get_headnode_dict(self): class NoneFix(fixer_base.BaseFix): From python-checkins at python.org Fri May 7 21:06:32 2010 From: python-checkins at python.org (benjamin.peterson) Date: Fri, 7 May 2010 21:06:32 +0200 (CEST) Subject: [Python-checkins] r80935 - in python/branches/release26-maint: Lib/lib2to3 Lib/lib2to3/fixes/fix_import.py Lib/lib2to3/fixes/fix_operator.py Lib/lib2to3/fixes/fix_reduce.py Lib/lib2to3/fixes/fix_sys_exc.py Lib/lib2to3/fixes/fix_tuple_params.py Lib/lib2to3/fixes/fix_xrange.py Lib/lib2to3/main.py Lib/lib2to3/patcomp.py Lib/lib2to3/pgen2/tokenize.py Lib/lib2to3/pytree.py Lib/lib2to3/refactor.py Lib/lib2to3/tests/test_fixers.py Lib/lib2to3/tests/test_parser.py Lib/lib2to3/tests/test_pytree.py Lib/lib2to3/tests/test_refactor.py Message-ID: <20100507190632.E1A25F9B6@mail.python.org> Author: benjamin.peterson Date: Fri May 7 21:06:32 2010 New Revision: 80935 Log: Merged revisions 80934 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ................ r80934 | benjamin.peterson | 2010-05-07 13:58:23 -0500 (Fri, 07 May 2010) | 69 lines Merged revisions 79911,79916-79917,80018,80418,80572-80573,80635-80639,80668,80922 via svnmerge from svn+ssh://pythondev at svn.python.org/sandbox/trunk/2to3/lib2to3 ........ r79911 | benjamin.peterson | 2010-04-09 15:38:53 -0500 (Fri, 09 Apr 2010) | 1 line use absolute import ........ r79916 | benjamin.peterson | 2010-04-09 16:05:21 -0500 (Fri, 09 Apr 2010) | 1 line generalize detection of __future__ imports and attach them to the tree ........ r79917 | benjamin.peterson | 2010-04-09 16:11:44 -0500 (Fri, 09 Apr 2010) | 1 line don't try to 'fix' relative imports when absolute_import is enabled #8858 ........ r80018 | benjamin.peterson | 2010-04-12 16:12:12 -0500 (Mon, 12 Apr 2010) | 4 lines prevent diffs from being mangled is multiprocess mode #6409 Patch by George Boutsioukis. ........ r80418 | benjamin.peterson | 2010-04-23 16:00:03 -0500 (Fri, 23 Apr 2010) | 1 line remove unhelpful description ........ r80572 | benjamin.peterson | 2010-04-27 20:33:54 -0500 (Tue, 27 Apr 2010) | 1 line use unicode literals ........ r80573 | jeffrey.yasskin | 2010-04-27 23:08:27 -0500 (Tue, 27 Apr 2010) | 6 lines Don't transform imports that are already relative. 2to3 turned from . import refactor into from .. import refactor which broke the transformation of 2to3 itself. ........ r80635 | benjamin.peterson | 2010-04-29 16:02:23 -0500 (Thu, 29 Apr 2010) | 1 line remove imports ........ r80636 | benjamin.peterson | 2010-04-29 16:02:41 -0500 (Thu, 29 Apr 2010) | 1 line unicode literal ........ r80637 | benjamin.peterson | 2010-04-29 16:03:42 -0500 (Thu, 29 Apr 2010) | 1 line must pass a string to Number ........ r80638 | benjamin.peterson | 2010-04-29 16:05:34 -0500 (Thu, 29 Apr 2010) | 1 line unicode literals ........ r80639 | benjamin.peterson | 2010-04-29 16:06:09 -0500 (Thu, 29 Apr 2010) | 1 line pass string to Number ........ r80668 | jeffrey.yasskin | 2010-04-30 18:02:47 -0500 (Fri, 30 Apr 2010) | 4 lines Make 2to3 run under Python 2.5 so that the benchmark suite at http://hg.python.org/benchmarks/ can use it and still run on implementations that haven't gotten to 2.6 yet. Fixes issue 8566. ........ r80922 | benjamin.peterson | 2010-05-07 11:06:25 -0500 (Fri, 07 May 2010) | 1 line prevent xrange transformation from wrapping range calls it produces in list ........ ................ Modified: python/branches/release26-maint/ (props changed) python/branches/release26-maint/Lib/lib2to3/ (props changed) python/branches/release26-maint/Lib/lib2to3/fixes/fix_import.py python/branches/release26-maint/Lib/lib2to3/fixes/fix_operator.py python/branches/release26-maint/Lib/lib2to3/fixes/fix_reduce.py python/branches/release26-maint/Lib/lib2to3/fixes/fix_sys_exc.py python/branches/release26-maint/Lib/lib2to3/fixes/fix_tuple_params.py python/branches/release26-maint/Lib/lib2to3/fixes/fix_xrange.py python/branches/release26-maint/Lib/lib2to3/main.py python/branches/release26-maint/Lib/lib2to3/patcomp.py python/branches/release26-maint/Lib/lib2to3/pgen2/tokenize.py python/branches/release26-maint/Lib/lib2to3/pytree.py python/branches/release26-maint/Lib/lib2to3/refactor.py python/branches/release26-maint/Lib/lib2to3/tests/test_fixers.py python/branches/release26-maint/Lib/lib2to3/tests/test_parser.py python/branches/release26-maint/Lib/lib2to3/tests/test_pytree.py python/branches/release26-maint/Lib/lib2to3/tests/test_refactor.py Modified: python/branches/release26-maint/Lib/lib2to3/fixes/fix_import.py ============================================================================== --- python/branches/release26-maint/Lib/lib2to3/fixes/fix_import.py (original) +++ python/branches/release26-maint/Lib/lib2to3/fixes/fix_import.py Fri May 7 21:06:32 2010 @@ -43,7 +43,13 @@ import_name< 'import' imp=any > """ + def start_tree(self, tree, name): + super(FixImport, self).start_tree(tree, name) + self.skip = "absolute_import" in tree.future_features + def transform(self, node, results): + if self.skip: + return imp = results['imp'] if node.type == syms.import_from: @@ -71,19 +77,22 @@ self.warning(node, "absolute and local imports together") return - new = FromImport('.', [imp]) + new = FromImport(u".", [imp]) new.prefix = node.prefix return new def probably_a_local_import(self, imp_name): - imp_name = imp_name.split('.', 1)[0] + if imp_name.startswith(u"."): + # Relative imports are certainly not local imports. + return False + imp_name = imp_name.split(u".", 1)[0] base_path = dirname(self.filename) base_path = join(base_path, imp_name) # If there is no __init__.py next to the file its not in a package # so can't be a relative import. - if not exists(join(dirname(base_path), '__init__.py')): + if not exists(join(dirname(base_path), "__init__.py")): return False - for ext in ['.py', sep, '.pyc', '.so', '.sl', '.pyd']: + for ext in [".py", sep, ".pyc", ".so", ".sl", ".pyd"]: if exists(base_path + ext): return True return False Modified: python/branches/release26-maint/Lib/lib2to3/fixes/fix_operator.py ============================================================================== --- python/branches/release26-maint/Lib/lib2to3/fixes/fix_operator.py (original) +++ python/branches/release26-maint/Lib/lib2to3/fixes/fix_operator.py Fri May 7 21:06:32 2010 @@ -14,10 +14,10 @@ func = "'(' func=any ')'" PATTERN = """ power< module='operator' - trailer< '.' {methods} > trailer< {func} > > + trailer< '.' %(methods)s > trailer< %(func)s > > | - power< {methods} trailer< {func} > > - """.format(methods=methods, func=func) + power< %(methods)s trailer< %(func)s > > + """ % dict(methods=methods, func=func) def transform(self, node, results): method = results["method"][0] Modified: python/branches/release26-maint/Lib/lib2to3/fixes/fix_reduce.py ============================================================================== --- python/branches/release26-maint/Lib/lib2to3/fixes/fix_reduce.py (original) +++ python/branches/release26-maint/Lib/lib2to3/fixes/fix_reduce.py Fri May 7 21:06:32 2010 @@ -7,9 +7,8 @@ used in that module. """ -from .. import pytree -from .. import fixer_base -from ..fixer_util import Name, Attr, touch_import +from lib2to3 import fixer_base +from lib2to3.fixer_util import touch_import Modified: python/branches/release26-maint/Lib/lib2to3/fixes/fix_sys_exc.py ============================================================================== --- python/branches/release26-maint/Lib/lib2to3/fixes/fix_sys_exc.py (original) +++ python/branches/release26-maint/Lib/lib2to3/fixes/fix_sys_exc.py Fri May 7 21:06:32 2010 @@ -13,14 +13,14 @@ class FixSysExc(fixer_base.BaseFix): # This order matches the ordering of sys.exc_info(). - exc_info = ["exc_type", "exc_value", "exc_traceback"] + exc_info = [u"exc_type", u"exc_value", u"exc_traceback"] PATTERN = """ power< 'sys' trailer< dot='.' attribute=(%s) > > """ % '|'.join("'%s'" % e for e in exc_info) def transform(self, node, results): sys_attr = results["attribute"][0] - index = Number(self.exc_info.index(sys_attr.value)) + index = Number(unicode(self.exc_info.index(sys_attr.value))) call = Call(Name(u"exc_info"), prefix=sys_attr.prefix) attr = Attr(Name(u"sys"), call) Modified: python/branches/release26-maint/Lib/lib2to3/fixes/fix_tuple_params.py ============================================================================== --- python/branches/release26-maint/Lib/lib2to3/fixes/fix_tuple_params.py (original) +++ python/branches/release26-maint/Lib/lib2to3/fixes/fix_tuple_params.py Fri May 7 21:06:32 2010 @@ -54,7 +54,7 @@ end = Newline() else: start = 0 - indent = "; " + indent = u"; " end = pytree.Leaf(token.INDENT, u"") # We need access to self for new_name(), and making this a method @@ -154,7 +154,7 @@ if d is None: d = {} for i, obj in enumerate(param_list): - trailer = [Subscript(Number(i))] + trailer = [Subscript(Number(unicode(i)))] if isinstance(obj, list): map_to_index(obj, trailer, d=d) else: Modified: python/branches/release26-maint/Lib/lib2to3/fixes/fix_xrange.py ============================================================================== --- python/branches/release26-maint/Lib/lib2to3/fixes/fix_xrange.py (original) +++ python/branches/release26-maint/Lib/lib2to3/fixes/fix_xrange.py Fri May 7 21:06:32 2010 @@ -17,6 +17,13 @@ rest=any* > """ + def start_tree(self, tree, filename): + super(FixXrange, self).start_tree(tree, filename) + self.transformed_xranges = set() + + def finish_tree(self, tree, filename): + self.transformed_xranges = None + def transform(self, node, results): name = results["name"] if name.value == u"xrange": @@ -29,9 +36,12 @@ def transform_xrange(self, node, results): name = results["name"] name.replace(Name(u"range", prefix=name.prefix)) + # This prevents the new range call from being wrapped in a list later. + self.transformed_xranges.add(id(node)) def transform_range(self, node, results): - if not self.in_special_context(node): + if (id(node) not in self.transformed_xranges and + not self.in_special_context(node)): range_call = Call(Name(u"range"), [results["args"].clone()]) # Encase the range call in list(). list_call = Call(Name(u"list"), [range_call], Modified: python/branches/release26-maint/Lib/lib2to3/main.py ============================================================================== --- python/branches/release26-maint/Lib/lib2to3/main.py (original) +++ python/branches/release26-maint/Lib/lib2to3/main.py Fri May 7 21:06:32 2010 @@ -2,6 +2,8 @@ Main program for 2to3. """ +from __future__ import with_statement + import sys import os import difflib @@ -62,8 +64,14 @@ if self.show_diffs: diff_lines = diff_texts(old, new, filename) try: - for line in diff_lines: - print line + if self.output_lock is not None: + with self.output_lock: + for line in diff_lines: + print line + sys.stdout.flush() + else: + for line in diff_lines: + print line except UnicodeEncodeError: warn("couldn't encode %s's diff for your terminal" % (filename,)) @@ -95,7 +103,7 @@ parser.add_option("-x", "--nofix", action="append", default=[], help="Prevent a fixer from being run.") parser.add_option("-l", "--list-fixes", action="store_true", - help="List available transformations (fixes/fix_*.py)") + help="List available transformations") parser.add_option("-p", "--print-function", action="store_true", help="Modify the grammar so that print() is a function") parser.add_option("-v", "--verbose", action="store_true", Modified: python/branches/release26-maint/Lib/lib2to3/patcomp.py ============================================================================== --- python/branches/release26-maint/Lib/lib2to3/patcomp.py (original) +++ python/branches/release26-maint/Lib/lib2to3/patcomp.py Fri May 7 21:06:32 2010 @@ -57,7 +57,7 @@ tokens = tokenize_wrapper(input) try: root = self.driver.parse_tokens(tokens, debug=debug) - except parse.ParseError as e: + except parse.ParseError, e: raise PatternSyntaxError(str(e)) return self.compile_node(root) Modified: python/branches/release26-maint/Lib/lib2to3/pgen2/tokenize.py ============================================================================== --- python/branches/release26-maint/Lib/lib2to3/pgen2/tokenize.py (original) +++ python/branches/release26-maint/Lib/lib2to3/pgen2/tokenize.py Fri May 7 21:06:32 2010 @@ -38,6 +38,13 @@ "generate_tokens", "untokenize"] del token +try: + bytes +except NameError: + # Support bytes type in Python <= 2.5, so 2to3 turns itself into + # valid Python 3 code. + bytes = str + def group(*choices): return '(' + '|'.join(choices) + ')' def any(*choices): return group(*choices) + '*' def maybe(*choices): return group(*choices) + '?' @@ -267,7 +274,7 @@ try: return readline() except StopIteration: - return b'' + return bytes() def find_cookie(line): try: Modified: python/branches/release26-maint/Lib/lib2to3/pytree.py ============================================================================== --- python/branches/release26-maint/Lib/lib2to3/pytree.py (original) +++ python/branches/release26-maint/Lib/lib2to3/pytree.py Fri May 7 21:06:32 2010 @@ -289,8 +289,7 @@ for node in child.post_order(): yield node - @property - def prefix(self): + def _prefix_getter(self): """ The whitespace and comments preceding this node in the input. """ @@ -298,11 +297,12 @@ return "" return self.children[0].prefix - @prefix.setter - def prefix(self, prefix): + def _prefix_setter(self, prefix): if self.children: self.children[0].prefix = prefix + prefix = property(_prefix_getter, _prefix_setter) + def set_child(self, i, child): """ Equivalent to 'node.children[i] = child'. This method also sets the @@ -390,18 +390,17 @@ """Return a pre-order iterator for the tree.""" yield self - @property - def prefix(self): + def _prefix_getter(self): """ The whitespace and comments preceding this token in the input. """ return self._prefix - @prefix.setter - def prefix(self, prefix): + def _prefix_setter(self, prefix): self.changed() self._prefix = prefix + prefix = property(_prefix_getter, _prefix_setter) def convert(gr, raw_node): """ Modified: python/branches/release26-maint/Lib/lib2to3/refactor.py ============================================================================== --- python/branches/release26-maint/Lib/lib2to3/refactor.py (original) +++ python/branches/release26-maint/Lib/lib2to3/refactor.py Fri May 7 21:06:32 2010 @@ -8,6 +8,8 @@ provides infrastructure to write your own refactoring tool. """ +from __future__ import with_statement + __author__ = "Guido van Rossum " @@ -122,13 +124,14 @@ _to_system_newlines = _identity -def _detect_future_print(source): +def _detect_future_features(source): have_docstring = False gen = tokenize.generate_tokens(StringIO.StringIO(source).readline) def advance(): - tok = next(gen) + tok = gen.next() return tok[0], tok[1] ignore = frozenset((token.NEWLINE, tokenize.NL, token.COMMENT)) + features = set() try: while True: tp, value = advance() @@ -140,26 +143,25 @@ have_docstring = True elif tp == token.NAME and value == u"from": tp, value = advance() - if tp != token.NAME and value != u"__future__": + if tp != token.NAME or value != u"__future__": break tp, value = advance() - if tp != token.NAME and value != u"import": + if tp != token.NAME or value != u"import": break tp, value = advance() if tp == token.OP and value == u"(": tp, value = advance() while tp == token.NAME: - if value == u"print_function": - return True + features.add(value) tp, value = advance() - if tp != token.OP and value != u",": + if tp != token.OP or value != u",": break tp, value = advance() else: break except StopIteration: pass - return False + return frozenset(features) class FixerError(Exception): @@ -341,7 +343,8 @@ An AST corresponding to the refactored input stream; None if there were errors during the parse. """ - if _detect_future_print(data): + features = _detect_future_features(data) + if "print_function" in features: self.driver.grammar = pygram.python_grammar_no_print_statement try: tree = self.driver.parse_string(data) @@ -351,6 +354,7 @@ return finally: self.driver.grammar = self.grammar + tree.future_features = features self.log_debug("Refactoring %s", name) self.refactor_tree(tree, name) return tree @@ -605,6 +609,7 @@ def __init__(self, *args, **kwargs): super(MultiprocessRefactoringTool, self).__init__(*args, **kwargs) self.queue = None + self.output_lock = None def refactor(self, items, write=False, doctests_only=False, num_processes=1): @@ -618,6 +623,7 @@ if self.queue is not None: raise RuntimeError("already doing multiple processes") self.queue = multiprocessing.JoinableQueue() + self.output_lock = multiprocessing.Lock() processes = [multiprocessing.Process(target=self._child) for i in xrange(num_processes)] try: Modified: python/branches/release26-maint/Lib/lib2to3/tests/test_fixers.py ============================================================================== --- python/branches/release26-maint/Lib/lib2to3/tests/test_fixers.py (original) +++ python/branches/release26-maint/Lib/lib2to3/tests/test_fixers.py Fri May 7 21:06:32 2010 @@ -1497,6 +1497,17 @@ for call in fixer_util.consuming_calls: self.unchanged("a = %s(range(10))" % call) +class Test_xrange_with_reduce(FixerTestCase): + + def setUp(self): + super(Test_xrange_with_reduce, self).setUp(["xrange", "reduce"]) + + def test_double_transform(self): + b = """reduce(x, xrange(5))""" + a = """from functools import reduce +reduce(x, range(5))""" + self.check(b, a) + class Test_raw_input(FixerTestCase): fixer = "raw_input" @@ -3679,7 +3690,7 @@ self.files_checked.append(name) return self.always_exists or (name in self.present_files) - from ..fixes import fix_import + from lib2to3.fixes import fix_import fix_import.exists = fake_exists def tearDown(self): @@ -3722,6 +3733,12 @@ self.present_files = set(["bar.py"]) self.unchanged(s) + def test_with_absolute_import_enabled(self): + s = "from __future__ import absolute_import\nimport bar" + self.always_exists = False + self.present_files = set(["__init__.py", "bar.py"]) + self.unchanged(s) + def test_in_package(self): b = "import bar" a = "from . import bar" @@ -3736,6 +3753,10 @@ self.present_files = set(["__init__.py", "bar" + os.path.sep]) self.check(b, a) + def test_already_relative_import(self): + s = "from . import bar" + self.unchanged(s) + def test_comments_and_indent(self): b = "import bar # Foo" a = "from . import bar # Foo" Modified: python/branches/release26-maint/Lib/lib2to3/tests/test_parser.py ============================================================================== --- python/branches/release26-maint/Lib/lib2to3/tests/test_parser.py (original) +++ python/branches/release26-maint/Lib/lib2to3/tests/test_parser.py Fri May 7 21:06:32 2010 @@ -6,13 +6,14 @@ test_grammar.py files from both Python 2 and Python 3. """ +from __future__ import with_statement + # Testing imports from . import support from .support import driver, test_dir # Python imports import os -import io import sys # Local imports @@ -156,8 +157,9 @@ encoding = tokenize.detect_encoding(fp.readline)[0] self.assertTrue(encoding is not None, "can't detect encoding for %s" % filepath) - with io.open(filepath, "r", encoding=encoding) as fp: + with open(filepath, "r") as fp: source = fp.read() + source = source.decode(encoding) tree = driver.parse_string(source) new = unicode(tree) if diff(filepath, new, encoding): @@ -203,9 +205,9 @@ def diff(fn, result, encoding): - f = io.open("@", "w", encoding=encoding) + f = open("@", "w") try: - f.write(result) + f.write(result.encode(encoding)) finally: f.close() try: Modified: python/branches/release26-maint/Lib/lib2to3/tests/test_pytree.py ============================================================================== --- python/branches/release26-maint/Lib/lib2to3/tests/test_pytree.py (original) +++ python/branches/release26-maint/Lib/lib2to3/tests/test_pytree.py Fri May 7 21:06:32 2010 @@ -9,6 +9,9 @@ especially when debugging a test. """ +from __future__ import with_statement + +import sys import warnings # Testing imports @@ -28,20 +31,22 @@ """Unit tests for nodes (Base, Leaf, Node).""" - def test_deprecated_prefix_methods(self): - l = pytree.Leaf(100, "foo") - with warnings.catch_warnings(record=True) as w: - warnings.simplefilter("always", DeprecationWarning) - self.assertEqual(l.get_prefix(), "") - l.set_prefix("hi") - self.assertEqual(l.prefix, "hi") - self.assertEqual(len(w), 2) - for warning in w: - self.assertTrue(warning.category is DeprecationWarning) - self.assertEqual(str(w[0].message), "get_prefix() is deprecated; " \ - "use the prefix property") - self.assertEqual(str(w[1].message), "set_prefix() is deprecated; " \ - "use the prefix property") + if sys.version_info >= (2,6): + # warnings.catch_warnings is new in 2.6. + def test_deprecated_prefix_methods(self): + l = pytree.Leaf(100, "foo") + with warnings.catch_warnings(record=True) as w: + warnings.simplefilter("always", DeprecationWarning) + self.assertEqual(l.get_prefix(), "") + l.set_prefix("hi") + self.assertEqual(l.prefix, "hi") + self.assertEqual(len(w), 2) + for warning in w: + self.assertTrue(warning.category is DeprecationWarning) + self.assertEqual(str(w[0].message), "get_prefix() is deprecated; " \ + "use the prefix property") + self.assertEqual(str(w[1].message), "set_prefix() is deprecated; " \ + "use the prefix property") def test_instantiate_base(self): if __debug__: Modified: python/branches/release26-maint/Lib/lib2to3/tests/test_refactor.py ============================================================================== --- python/branches/release26-maint/Lib/lib2to3/tests/test_refactor.py (original) +++ python/branches/release26-maint/Lib/lib2to3/tests/test_refactor.py Fri May 7 21:06:32 2010 @@ -2,6 +2,8 @@ Unit tests for refactor.py. """ +from __future__ import with_statement + import sys import os import codecs @@ -61,42 +63,50 @@ self.assertEqual(full_names, ["myfixes.fix_" + name for name in contents]) - def test_detect_future_print(self): - run = refactor._detect_future_print - self.assertFalse(run("")) - self.assertTrue(run("from __future__ import print_function")) - self.assertFalse(run("from __future__ import generators")) - self.assertFalse(run("from __future__ import generators, feature")) - input = "from __future__ import generators, print_function" - self.assertTrue(run(input)) - input ="from __future__ import print_function, generators" - self.assertTrue(run(input)) - input = "from __future__ import (print_function,)" - self.assertTrue(run(input)) - input = "from __future__ import (generators, print_function)" - self.assertTrue(run(input)) - input = "from __future__ import (generators, nested_scopes)" - self.assertFalse(run(input)) - input = """from __future__ import generators + def test_detect_future_features(self): + run = refactor._detect_future_features + fs = frozenset + empty = fs() + self.assertEqual(run(""), empty) + self.assertEqual(run("from __future__ import print_function"), + fs(("print_function",))) + self.assertEqual(run("from __future__ import generators"), + fs(("generators",))) + self.assertEqual(run("from __future__ import generators, feature"), + fs(("generators", "feature"))) + inp = "from __future__ import generators, print_function" + self.assertEqual(run(inp), fs(("generators", "print_function"))) + inp ="from __future__ import print_function, generators" + self.assertEqual(run(inp), fs(("print_function", "generators"))) + inp = "from __future__ import (print_function,)" + self.assertEqual(run(inp), fs(("print_function",))) + inp = "from __future__ import (generators, print_function)" + self.assertEqual(run(inp), fs(("generators", "print_function"))) + inp = "from __future__ import (generators, nested_scopes)" + self.assertEqual(run(inp), fs(("generators", "nested_scopes"))) + inp = """from __future__ import generators from __future__ import print_function""" - self.assertTrue(run(input)) - self.assertFalse(run("from")) - self.assertFalse(run("from 4")) - self.assertFalse(run("from x")) - self.assertFalse(run("from x 5")) - self.assertFalse(run("from x im")) - self.assertFalse(run("from x import")) - self.assertFalse(run("from x import 4")) - input = "'docstring'\nfrom __future__ import print_function" - self.assertTrue(run(input)) - input = "'docstring'\n'somng'\nfrom __future__ import print_function" - self.assertFalse(run(input)) - input = "# comment\nfrom __future__ import print_function" - self.assertTrue(run(input)) - input = "# comment\n'doc'\nfrom __future__ import print_function" - self.assertTrue(run(input)) - input = "class x: pass\nfrom __future__ import print_function" - self.assertFalse(run(input)) + self.assertEqual(run(inp), fs(("generators", "print_function"))) + invalid = ("from", + "from 4", + "from x", + "from x 5", + "from x im", + "from x import", + "from x import 4", + ) + for inp in invalid: + self.assertEqual(run(inp), empty) + inp = "'docstring'\nfrom __future__ import print_function" + self.assertEqual(run(inp), fs(("print_function",))) + inp = "'docstring'\n'somng'\nfrom __future__ import print_function" + self.assertEqual(run(inp), empty) + inp = "# comment\nfrom __future__ import print_function" + self.assertEqual(run(inp), fs(("print_function",))) + inp = "# comment\n'doc'\nfrom __future__ import print_function" + self.assertEqual(run(inp), fs(("print_function",))) + inp = "class x: pass\nfrom __future__ import print_function" + self.assertEqual(run(inp), empty) def test_get_headnode_dict(self): class NoneFix(fixer_base.BaseFix): From python-checkins at python.org Fri May 7 21:10:11 2010 From: python-checkins at python.org (benjamin.peterson) Date: Fri, 7 May 2010 21:10:11 +0200 (CEST) Subject: [Python-checkins] r80936 - in python/branches/py3k: Lib/lib2to3/fixes/fix_import.py Lib/lib2to3/fixes/fix_operator.py Lib/lib2to3/fixes/fix_reduce.py Lib/lib2to3/fixes/fix_tuple_params.py Lib/lib2to3/fixes/fix_xrange.py Lib/lib2to3/main.py Lib/lib2to3/pgen2/tokenize.py Lib/lib2to3/pytree.py Lib/lib2to3/refactor.py Lib/lib2to3/tests/test_fixers.py Lib/lib2to3/tests/test_parser.py Lib/lib2to3/tests/test_pytree.py Lib/lib2to3/tests/test_refactor.py Message-ID: <20100507191011.D7BB0EE982@mail.python.org> Author: benjamin.peterson Date: Fri May 7 21:10:11 2010 New Revision: 80936 Log: Merged revisions 80934 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ................ r80934 | benjamin.peterson | 2010-05-07 13:58:23 -0500 (Fri, 07 May 2010) | 69 lines Merged revisions 79911,79916-79917,80018,80418,80572-80573,80635-80639,80668,80922 via svnmerge from svn+ssh://pythondev at svn.python.org/sandbox/trunk/2to3/lib2to3 ........ r79911 | benjamin.peterson | 2010-04-09 15:38:53 -0500 (Fri, 09 Apr 2010) | 1 line use absolute import ........ r79916 | benjamin.peterson | 2010-04-09 16:05:21 -0500 (Fri, 09 Apr 2010) | 1 line generalize detection of __future__ imports and attach them to the tree ........ r79917 | benjamin.peterson | 2010-04-09 16:11:44 -0500 (Fri, 09 Apr 2010) | 1 line don't try to 'fix' relative imports when absolute_import is enabled #8858 ........ r80018 | benjamin.peterson | 2010-04-12 16:12:12 -0500 (Mon, 12 Apr 2010) | 4 lines prevent diffs from being mangled is multiprocess mode #6409 Patch by George Boutsioukis. ........ r80418 | benjamin.peterson | 2010-04-23 16:00:03 -0500 (Fri, 23 Apr 2010) | 1 line remove unhelpful description ........ r80572 | benjamin.peterson | 2010-04-27 20:33:54 -0500 (Tue, 27 Apr 2010) | 1 line use unicode literals ........ r80573 | jeffrey.yasskin | 2010-04-27 23:08:27 -0500 (Tue, 27 Apr 2010) | 6 lines Don't transform imports that are already relative. 2to3 turned from . import refactor into from .. import refactor which broke the transformation of 2to3 itself. ........ r80635 | benjamin.peterson | 2010-04-29 16:02:23 -0500 (Thu, 29 Apr 2010) | 1 line remove imports ........ r80636 | benjamin.peterson | 2010-04-29 16:02:41 -0500 (Thu, 29 Apr 2010) | 1 line unicode literal ........ r80637 | benjamin.peterson | 2010-04-29 16:03:42 -0500 (Thu, 29 Apr 2010) | 1 line must pass a string to Number ........ r80638 | benjamin.peterson | 2010-04-29 16:05:34 -0500 (Thu, 29 Apr 2010) | 1 line unicode literals ........ r80639 | benjamin.peterson | 2010-04-29 16:06:09 -0500 (Thu, 29 Apr 2010) | 1 line pass string to Number ........ r80668 | jeffrey.yasskin | 2010-04-30 18:02:47 -0500 (Fri, 30 Apr 2010) | 4 lines Make 2to3 run under Python 2.5 so that the benchmark suite at http://hg.python.org/benchmarks/ can use it and still run on implementations that haven't gotten to 2.6 yet. Fixes issue 8566. ........ r80922 | benjamin.peterson | 2010-05-07 11:06:25 -0500 (Fri, 07 May 2010) | 1 line prevent xrange transformation from wrapping range calls it produces in list ........ ................ Modified: python/branches/py3k/ (props changed) python/branches/py3k/Lib/lib2to3/fixes/fix_import.py python/branches/py3k/Lib/lib2to3/fixes/fix_operator.py python/branches/py3k/Lib/lib2to3/fixes/fix_reduce.py python/branches/py3k/Lib/lib2to3/fixes/fix_tuple_params.py python/branches/py3k/Lib/lib2to3/fixes/fix_xrange.py python/branches/py3k/Lib/lib2to3/main.py python/branches/py3k/Lib/lib2to3/pgen2/tokenize.py python/branches/py3k/Lib/lib2to3/pytree.py python/branches/py3k/Lib/lib2to3/refactor.py python/branches/py3k/Lib/lib2to3/tests/test_fixers.py python/branches/py3k/Lib/lib2to3/tests/test_parser.py python/branches/py3k/Lib/lib2to3/tests/test_pytree.py python/branches/py3k/Lib/lib2to3/tests/test_refactor.py Modified: python/branches/py3k/Lib/lib2to3/fixes/fix_import.py ============================================================================== --- python/branches/py3k/Lib/lib2to3/fixes/fix_import.py (original) +++ python/branches/py3k/Lib/lib2to3/fixes/fix_import.py Fri May 7 21:10:11 2010 @@ -43,7 +43,13 @@ import_name< 'import' imp=any > """ + def start_tree(self, tree, name): + super(FixImport, self).start_tree(tree, name) + self.skip = "absolute_import" in tree.future_features + def transform(self, node, results): + if self.skip: + return imp = results['imp'] if node.type == syms.import_from: @@ -71,19 +77,22 @@ self.warning(node, "absolute and local imports together") return - new = FromImport('.', [imp]) + new = FromImport(".", [imp]) new.prefix = node.prefix return new def probably_a_local_import(self, imp_name): - imp_name = imp_name.split('.', 1)[0] + if imp_name.startswith("."): + # Relative imports are certainly not local imports. + return False + imp_name = imp_name.split(".", 1)[0] base_path = dirname(self.filename) base_path = join(base_path, imp_name) # If there is no __init__.py next to the file its not in a package # so can't be a relative import. - if not exists(join(dirname(base_path), '__init__.py')): + if not exists(join(dirname(base_path), "__init__.py")): return False - for ext in ['.py', sep, '.pyc', '.so', '.sl', '.pyd']: + for ext in [".py", sep, ".pyc", ".so", ".sl", ".pyd"]: if exists(base_path + ext): return True return False Modified: python/branches/py3k/Lib/lib2to3/fixes/fix_operator.py ============================================================================== --- python/branches/py3k/Lib/lib2to3/fixes/fix_operator.py (original) +++ python/branches/py3k/Lib/lib2to3/fixes/fix_operator.py Fri May 7 21:10:11 2010 @@ -14,10 +14,10 @@ func = "'(' func=any ')'" PATTERN = """ power< module='operator' - trailer< '.' {methods} > trailer< {func} > > + trailer< '.' %(methods)s > trailer< %(func)s > > | - power< {methods} trailer< {func} > > - """.format(methods=methods, func=func) + power< %(methods)s trailer< %(func)s > > + """ % dict(methods=methods, func=func) def transform(self, node, results): method = results["method"][0] Modified: python/branches/py3k/Lib/lib2to3/fixes/fix_reduce.py ============================================================================== --- python/branches/py3k/Lib/lib2to3/fixes/fix_reduce.py (original) +++ python/branches/py3k/Lib/lib2to3/fixes/fix_reduce.py Fri May 7 21:10:11 2010 @@ -7,9 +7,8 @@ used in that module. """ -from .. import pytree -from .. import fixer_base -from ..fixer_util import Name, Attr, touch_import +from lib2to3 import fixer_base +from lib2to3.fixer_util import touch_import Modified: python/branches/py3k/Lib/lib2to3/fixes/fix_tuple_params.py ============================================================================== --- python/branches/py3k/Lib/lib2to3/fixes/fix_tuple_params.py (original) +++ python/branches/py3k/Lib/lib2to3/fixes/fix_tuple_params.py Fri May 7 21:10:11 2010 @@ -154,7 +154,7 @@ if d is None: d = {} for i, obj in enumerate(param_list): - trailer = [Subscript(Number(i))] + trailer = [Subscript(Number(str(i)))] if isinstance(obj, list): map_to_index(obj, trailer, d=d) else: Modified: python/branches/py3k/Lib/lib2to3/fixes/fix_xrange.py ============================================================================== --- python/branches/py3k/Lib/lib2to3/fixes/fix_xrange.py (original) +++ python/branches/py3k/Lib/lib2to3/fixes/fix_xrange.py Fri May 7 21:10:11 2010 @@ -17,6 +17,13 @@ rest=any* > """ + def start_tree(self, tree, filename): + super(FixXrange, self).start_tree(tree, filename) + self.transformed_xranges = set() + + def finish_tree(self, tree, filename): + self.transformed_xranges = None + def transform(self, node, results): name = results["name"] if name.value == "xrange": @@ -29,9 +36,12 @@ def transform_xrange(self, node, results): name = results["name"] name.replace(Name("range", prefix=name.prefix)) + # This prevents the new range call from being wrapped in a list later. + self.transformed_xranges.add(id(node)) def transform_range(self, node, results): - if not self.in_special_context(node): + if (id(node) not in self.transformed_xranges and + not self.in_special_context(node)): range_call = Call(Name("range"), [results["args"].clone()]) # Encase the range call in list(). list_call = Call(Name("list"), [range_call], Modified: python/branches/py3k/Lib/lib2to3/main.py ============================================================================== --- python/branches/py3k/Lib/lib2to3/main.py (original) +++ python/branches/py3k/Lib/lib2to3/main.py Fri May 7 21:10:11 2010 @@ -2,6 +2,8 @@ Main program for 2to3. """ +from __future__ import with_statement + import sys import os import difflib @@ -62,8 +64,14 @@ if self.show_diffs: diff_lines = diff_texts(old, new, filename) try: - for line in diff_lines: - print(line) + if self.output_lock is not None: + with self.output_lock: + for line in diff_lines: + print(line) + sys.stdout.flush() + else: + for line in diff_lines: + print(line) except UnicodeEncodeError: warn("couldn't encode %s's diff for your terminal" % (filename,)) @@ -94,7 +102,7 @@ parser.add_option("-x", "--nofix", action="append", default=[], help="Prevent a fixer from being run.") parser.add_option("-l", "--list-fixes", action="store_true", - help="List available transformations (fixes/fix_*.py)") + help="List available transformations") parser.add_option("-p", "--print-function", action="store_true", help="Modify the grammar so that print() is a function") parser.add_option("-v", "--verbose", action="store_true", Modified: python/branches/py3k/Lib/lib2to3/pgen2/tokenize.py ============================================================================== --- python/branches/py3k/Lib/lib2to3/pgen2/tokenize.py (original) +++ python/branches/py3k/Lib/lib2to3/pgen2/tokenize.py Fri May 7 21:10:11 2010 @@ -38,6 +38,13 @@ "generate_tokens", "untokenize"] del token +try: + bytes +except NameError: + # Support bytes type in Python <= 2.5, so 2to3 turns itself into + # valid Python 3 code. + bytes = str + def group(*choices): return '(' + '|'.join(choices) + ')' def any(*choices): return group(*choices) + '*' def maybe(*choices): return group(*choices) + '?' @@ -267,7 +274,7 @@ try: return readline() except StopIteration: - return b'' + return bytes() def find_cookie(line): try: Modified: python/branches/py3k/Lib/lib2to3/pytree.py ============================================================================== --- python/branches/py3k/Lib/lib2to3/pytree.py (original) +++ python/branches/py3k/Lib/lib2to3/pytree.py Fri May 7 21:10:11 2010 @@ -289,8 +289,7 @@ for node in child.post_order(): yield node - @property - def prefix(self): + def _prefix_getter(self): """ The whitespace and comments preceding this node in the input. """ @@ -298,11 +297,12 @@ return "" return self.children[0].prefix - @prefix.setter - def prefix(self, prefix): + def _prefix_setter(self, prefix): if self.children: self.children[0].prefix = prefix + prefix = property(_prefix_getter, _prefix_setter) + def set_child(self, i, child): """ Equivalent to 'node.children[i] = child'. This method also sets the @@ -390,18 +390,17 @@ """Return a pre-order iterator for the tree.""" yield self - @property - def prefix(self): + def _prefix_getter(self): """ The whitespace and comments preceding this token in the input. """ return self._prefix - @prefix.setter - def prefix(self, prefix): + def _prefix_setter(self, prefix): self.changed() self._prefix = prefix + prefix = property(_prefix_getter, _prefix_setter) def convert(gr, raw_node): """ Modified: python/branches/py3k/Lib/lib2to3/refactor.py ============================================================================== --- python/branches/py3k/Lib/lib2to3/refactor.py (original) +++ python/branches/py3k/Lib/lib2to3/refactor.py Fri May 7 21:10:11 2010 @@ -8,6 +8,8 @@ provides infrastructure to write your own refactoring tool. """ +from __future__ import with_statement + __author__ = "Guido van Rossum " @@ -122,13 +124,14 @@ _to_system_newlines = _identity -def _detect_future_print(source): +def _detect_future_features(source): have_docstring = False gen = tokenize.generate_tokens(io.StringIO(source).readline) def advance(): tok = next(gen) return tok[0], tok[1] ignore = frozenset((token.NEWLINE, tokenize.NL, token.COMMENT)) + features = set() try: while True: tp, value = advance() @@ -140,26 +143,25 @@ have_docstring = True elif tp == token.NAME and value == "from": tp, value = advance() - if tp != token.NAME and value != "__future__": + if tp != token.NAME or value != "__future__": break tp, value = advance() - if tp != token.NAME and value != "import": + if tp != token.NAME or value != "import": break tp, value = advance() if tp == token.OP and value == "(": tp, value = advance() while tp == token.NAME: - if value == "print_function": - return True + features.add(value) tp, value = advance() - if tp != token.OP and value != ",": + if tp != token.OP or value != ",": break tp, value = advance() else: break except StopIteration: pass - return False + return frozenset(features) class FixerError(Exception): @@ -341,7 +343,8 @@ An AST corresponding to the refactored input stream; None if there were errors during the parse. """ - if _detect_future_print(data): + features = _detect_future_features(data) + if "print_function" in features: self.driver.grammar = pygram.python_grammar_no_print_statement try: tree = self.driver.parse_string(data) @@ -351,6 +354,7 @@ return finally: self.driver.grammar = self.grammar + tree.future_features = features self.log_debug("Refactoring %s", name) self.refactor_tree(tree, name) return tree @@ -605,6 +609,7 @@ def __init__(self, *args, **kwargs): super(MultiprocessRefactoringTool, self).__init__(*args, **kwargs) self.queue = None + self.output_lock = None def refactor(self, items, write=False, doctests_only=False, num_processes=1): @@ -618,6 +623,7 @@ if self.queue is not None: raise RuntimeError("already doing multiple processes") self.queue = multiprocessing.JoinableQueue() + self.output_lock = multiprocessing.Lock() processes = [multiprocessing.Process(target=self._child) for i in range(num_processes)] try: Modified: python/branches/py3k/Lib/lib2to3/tests/test_fixers.py ============================================================================== --- python/branches/py3k/Lib/lib2to3/tests/test_fixers.py (original) +++ python/branches/py3k/Lib/lib2to3/tests/test_fixers.py Fri May 7 21:10:11 2010 @@ -1497,6 +1497,17 @@ for call in fixer_util.consuming_calls: self.unchanged("a = %s(range(10))" % call) +class Test_xrange_with_reduce(FixerTestCase): + + def setUp(self): + super(Test_xrange_with_reduce, self).setUp(["xrange", "reduce"]) + + def test_double_transform(self): + b = """reduce(x, xrange(5))""" + a = """from functools import reduce +reduce(x, range(5))""" + self.check(b, a) + class Test_raw_input(FixerTestCase): fixer = "raw_input" @@ -3679,7 +3690,7 @@ self.files_checked.append(name) return self.always_exists or (name in self.present_files) - from ..fixes import fix_import + from lib2to3.fixes import fix_import fix_import.exists = fake_exists def tearDown(self): @@ -3722,6 +3733,12 @@ self.present_files = set(["bar.py"]) self.unchanged(s) + def test_with_absolute_import_enabled(self): + s = "from __future__ import absolute_import\nimport bar" + self.always_exists = False + self.present_files = set(["__init__.py", "bar.py"]) + self.unchanged(s) + def test_in_package(self): b = "import bar" a = "from . import bar" @@ -3736,6 +3753,10 @@ self.present_files = set(["__init__.py", "bar" + os.path.sep]) self.check(b, a) + def test_already_relative_import(self): + s = "from . import bar" + self.unchanged(s) + def test_comments_and_indent(self): b = "import bar # Foo" a = "from . import bar # Foo" Modified: python/branches/py3k/Lib/lib2to3/tests/test_parser.py ============================================================================== --- python/branches/py3k/Lib/lib2to3/tests/test_parser.py (original) +++ python/branches/py3k/Lib/lib2to3/tests/test_parser.py Fri May 7 21:10:11 2010 @@ -6,6 +6,8 @@ test_grammar.py files from both Python 2 and Python 3. """ +from __future__ import with_statement + # Testing imports from . import support from .support import driver, test_dir @@ -149,10 +151,11 @@ for filepath in support.all_project_files(): with open(filepath, "rb") as fp: encoding = tokenize.detect_encoding(fp.readline)[0] - fp.seek(0) + self.assertTrue(encoding is not None, + "can't detect encoding for %s" % filepath) + with open(filepath, "r") as fp: source = fp.read() - if encoding: - source = source.decode(encoding) + source = source.decode(encoding) tree = driver.parse_string(source) new = str(tree) if encoding: @@ -199,10 +202,10 @@ self.validate(s) -def diff(fn, result): - f = open("@", "wb") +def diff(fn, result, encoding): + f = open("@", "w") try: - f.write(result) + f.write(result.encode(encoding)) finally: f.close() try: Modified: python/branches/py3k/Lib/lib2to3/tests/test_pytree.py ============================================================================== --- python/branches/py3k/Lib/lib2to3/tests/test_pytree.py (original) +++ python/branches/py3k/Lib/lib2to3/tests/test_pytree.py Fri May 7 21:10:11 2010 @@ -9,6 +9,9 @@ especially when debugging a test. """ +from __future__ import with_statement + +import sys import warnings # Testing imports @@ -28,20 +31,22 @@ """Unit tests for nodes (Base, Leaf, Node).""" - def test_deprecated_prefix_methods(self): - l = pytree.Leaf(100, "foo") - with warnings.catch_warnings(record=True) as w: - warnings.simplefilter("always", DeprecationWarning) - self.assertEqual(l.get_prefix(), "") - l.set_prefix("hi") - self.assertEqual(l.prefix, "hi") - self.assertEqual(len(w), 2) - for warning in w: - self.assertTrue(warning.category is DeprecationWarning) - self.assertEqual(str(w[0].message), "get_prefix() is deprecated; " \ - "use the prefix property") - self.assertEqual(str(w[1].message), "set_prefix() is deprecated; " \ - "use the prefix property") + if sys.version_info >= (2,6): + # warnings.catch_warnings is new in 2.6. + def test_deprecated_prefix_methods(self): + l = pytree.Leaf(100, "foo") + with warnings.catch_warnings(record=True) as w: + warnings.simplefilter("always", DeprecationWarning) + self.assertEqual(l.get_prefix(), "") + l.set_prefix("hi") + self.assertEqual(l.prefix, "hi") + self.assertEqual(len(w), 2) + for warning in w: + self.assertTrue(warning.category is DeprecationWarning) + self.assertEqual(str(w[0].message), "get_prefix() is deprecated; " \ + "use the prefix property") + self.assertEqual(str(w[1].message), "set_prefix() is deprecated; " \ + "use the prefix property") def test_instantiate_base(self): if __debug__: Modified: python/branches/py3k/Lib/lib2to3/tests/test_refactor.py ============================================================================== --- python/branches/py3k/Lib/lib2to3/tests/test_refactor.py (original) +++ python/branches/py3k/Lib/lib2to3/tests/test_refactor.py Fri May 7 21:10:11 2010 @@ -2,6 +2,8 @@ Unit tests for refactor.py. """ +from __future__ import with_statement + import sys import os import codecs @@ -61,42 +63,50 @@ self.assertEqual(full_names, ["myfixes.fix_" + name for name in contents]) - def test_detect_future_print(self): - run = refactor._detect_future_print - self.assertFalse(run("")) - self.assertTrue(run("from __future__ import print_function")) - self.assertFalse(run("from __future__ import generators")) - self.assertFalse(run("from __future__ import generators, feature")) - input = "from __future__ import generators, print_function" - self.assertTrue(run(input)) - input ="from __future__ import print_function, generators" - self.assertTrue(run(input)) - input = "from __future__ import (print_function,)" - self.assertTrue(run(input)) - input = "from __future__ import (generators, print_function)" - self.assertTrue(run(input)) - input = "from __future__ import (generators, nested_scopes)" - self.assertFalse(run(input)) - input = """from __future__ import generators + def test_detect_future_features(self): + run = refactor._detect_future_features + fs = frozenset + empty = fs() + self.assertEqual(run(""), empty) + self.assertEqual(run("from __future__ import print_function"), + fs(("print_function",))) + self.assertEqual(run("from __future__ import generators"), + fs(("generators",))) + self.assertEqual(run("from __future__ import generators, feature"), + fs(("generators", "feature"))) + inp = "from __future__ import generators, print_function" + self.assertEqual(run(inp), fs(("generators", "print_function"))) + inp ="from __future__ import print_function, generators" + self.assertEqual(run(inp), fs(("print_function", "generators"))) + inp = "from __future__ import (print_function,)" + self.assertEqual(run(inp), fs(("print_function",))) + inp = "from __future__ import (generators, print_function)" + self.assertEqual(run(inp), fs(("generators", "print_function"))) + inp = "from __future__ import (generators, nested_scopes)" + self.assertEqual(run(inp), fs(("generators", "nested_scopes"))) + inp = """from __future__ import generators from __future__ import print_function""" - self.assertTrue(run(input)) - self.assertFalse(run("from")) - self.assertFalse(run("from 4")) - self.assertFalse(run("from x")) - self.assertFalse(run("from x 5")) - self.assertFalse(run("from x im")) - self.assertFalse(run("from x import")) - self.assertFalse(run("from x import 4")) - input = "'docstring'\nfrom __future__ import print_function" - self.assertTrue(run(input)) - input = "'docstring'\n'somng'\nfrom __future__ import print_function" - self.assertFalse(run(input)) - input = "# comment\nfrom __future__ import print_function" - self.assertTrue(run(input)) - input = "# comment\n'doc'\nfrom __future__ import print_function" - self.assertTrue(run(input)) - input = "class x: pass\nfrom __future__ import print_function" - self.assertFalse(run(input)) + self.assertEqual(run(inp), fs(("generators", "print_function"))) + invalid = ("from", + "from 4", + "from x", + "from x 5", + "from x im", + "from x import", + "from x import 4", + ) + for inp in invalid: + self.assertEqual(run(inp), empty) + inp = "'docstring'\nfrom __future__ import print_function" + self.assertEqual(run(inp), fs(("print_function",))) + inp = "'docstring'\n'somng'\nfrom __future__ import print_function" + self.assertEqual(run(inp), empty) + inp = "# comment\nfrom __future__ import print_function" + self.assertEqual(run(inp), fs(("print_function",))) + inp = "# comment\n'doc'\nfrom __future__ import print_function" + self.assertEqual(run(inp), fs(("print_function",))) + inp = "class x: pass\nfrom __future__ import print_function" + self.assertEqual(run(inp), empty) def test_get_headnode_dict(self): class NoneFix(fixer_base.BaseFix): From python-checkins at python.org Fri May 7 21:10:58 2010 From: python-checkins at python.org (benjamin.peterson) Date: Fri, 7 May 2010 21:10:58 +0200 (CEST) Subject: [Python-checkins] r80937 - sandbox/trunk/2to3/lib2to3/fixes/fix_sys_exc.py Message-ID: <20100507191058.628B6EE982@mail.python.org> Author: benjamin.peterson Date: Fri May 7 21:10:58 2010 New Revision: 80937 Log: remove redundant unicode call Modified: sandbox/trunk/2to3/lib2to3/fixes/fix_sys_exc.py Modified: sandbox/trunk/2to3/lib2to3/fixes/fix_sys_exc.py ============================================================================== --- sandbox/trunk/2to3/lib2to3/fixes/fix_sys_exc.py (original) +++ sandbox/trunk/2to3/lib2to3/fixes/fix_sys_exc.py Fri May 7 21:10:58 2010 @@ -20,7 +20,7 @@ def transform(self, node, results): sys_attr = results["attribute"][0] - index = Number(unicode(self.exc_info.index(sys_attr.value))) + index = Number(self.exc_info.index(sys_attr.value)) call = Call(Name(u"exc_info"), prefix=sys_attr.prefix) attr = Attr(Name(u"sys"), call) From python-checkins at python.org Fri May 7 22:21:27 2010 From: python-checkins at python.org (benjamin.peterson) Date: Fri, 7 May 2010 22:21:27 +0200 (CEST) Subject: [Python-checkins] r80938 - python/branches/py3k/Include/unicodeobject.h Message-ID: <20100507202127.2034DC8AF@mail.python.org> Author: benjamin.peterson Date: Fri May 7 22:21:26 2010 New Revision: 80938 Log: alias PyUnicode_CompareWithASCII Modified: python/branches/py3k/Include/unicodeobject.h Modified: python/branches/py3k/Include/unicodeobject.h ============================================================================== --- python/branches/py3k/Include/unicodeobject.h (original) +++ python/branches/py3k/Include/unicodeobject.h Fri May 7 22:21:26 2010 @@ -158,6 +158,7 @@ # define PyUnicode_AsWideChar PyUnicodeUCS2_AsWideChar # define PyUnicode_ClearFreeList PyUnicodeUCS2_ClearFreelist # define PyUnicode_Compare PyUnicodeUCS2_Compare +# define PyUnicode_CompareWithASCII PyUnicodeUCS2_CompareASCII # define PyUnicode_Concat PyUnicodeUCS2_Concat # define PyUnicode_Append PyUnicodeUCS2_Append # define PyUnicode_AppendAndDel PyUnicodeUCS2_AppendAndDel @@ -257,6 +258,7 @@ # define PyUnicode_AsWideChar PyUnicodeUCS4_AsWideChar # define PyUnicode_ClearFreeList PyUnicodeUCS4_ClearFreelist # define PyUnicode_Compare PyUnicodeUCS4_Compare +# define PyUnicode_CompareWithASCII PyUnicodeUCS4_CompareWithASCII # define PyUnicode_Concat PyUnicodeUCS4_Concat # define PyUnicode_Append PyUnicodeUCS4_Append # define PyUnicode_AppendAndDel PyUnicodeUCS4_AppendAndDel From python-checkins at python.org Fri May 7 22:45:08 2010 From: python-checkins at python.org (benjamin.peterson) Date: Fri, 7 May 2010 22:45:08 +0200 (CEST) Subject: [Python-checkins] r80939 - in python/trunk/Lib/unittest: loader.py test/test_discovery.py Message-ID: <20100507204508.0BD20F68D0@mail.python.org> Author: benjamin.peterson Date: Fri May 7 22:45:07 2010 New Revision: 80939 Log: revert r80932; it breaks windows Modified: python/trunk/Lib/unittest/loader.py python/trunk/Lib/unittest/test/test_discovery.py Modified: python/trunk/Lib/unittest/loader.py ============================================================================== --- python/trunk/Lib/unittest/loader.py (original) +++ python/trunk/Lib/unittest/loader.py Fri May 7 22:45:07 2010 @@ -173,10 +173,7 @@ if not top_level_dir in sys.path: # all test modules must be importable from the top level directory - # should we *unconditionally* put the start directory in first - # in sys.path to minimise likelihood of conflicts between installed - # modules and development versions? - sys.path.insert(0, top_level_dir) + sys.path.append(top_level_dir) self._top_level_dir = top_level_dir is_not_importable = False @@ -249,16 +246,6 @@ except: yield _make_failed_import_test(name, self.suiteClass) else: - mod_file = os.path.abspath(getattr(module, '__file__', full_path)) - 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] - expected_dir = os.path.dirname(full_path) - msg = ("%r module incorrectly imported from %r. Expected %r. " - "Is this module globally installed?") - raise ImportError(msg % (mod_name, module_dir, expected_dir)) yield self.loadTestsFromModule(module) elif os.path.isdir(full_path): if not os.path.isfile(os.path.join(full_path, '__init__.py')): Modified: python/trunk/Lib/unittest/test/test_discovery.py ============================================================================== --- python/trunk/Lib/unittest/test/test_discovery.py (original) +++ python/trunk/Lib/unittest/test/test_discovery.py Fri May 7 22:45:07 2010 @@ -298,45 +298,6 @@ self.assertTrue(program.failfast) self.assertTrue(program.catchbreak) - def test_detect_module_clash(self): - class Module(object): - __file__ = 'bar/foo.py' - sys.modules['foo'] = Module - full_path = os.path.abspath('foo') - original_listdir = os.listdir - original_isfile = os.path.isfile - original_isdir = os.path.isdir - - def cleanup(): - os.listdir = original_listdir - os.path.isfile = original_isfile - os.path.isdir = original_isdir - del sys.modules['foo'] - if full_path in sys.path: - sys.path.remove(full_path) - self.addCleanup(cleanup) - - def listdir(_): - return ['foo.py'] - def isfile(_): - return True - def isdir(_): - return True - os.listdir = listdir - os.path.isfile = isfile - os.path.isdir = isdir - - loader = unittest.TestLoader() - - mod_dir = os.path.abspath('bar') - expected_dir = os.path.abspath('foo') - msg = (r"^'foo' module incorrectly imported from %r\. Expected %r\. " - "Is this module globally installed\?$") % (mod_dir, expected_dir) - self.assertRaisesRegexp( - ImportError, msg, loader.discover, - start_dir='foo', pattern='foo.py' - ) - self.assertEqual(sys.path[0], full_path) if __name__ == '__main__': unittest.main() From python-checkins at python.org Fri May 7 22:47:43 2010 From: python-checkins at python.org (benjamin.peterson) Date: Fri, 7 May 2010 22:47:43 +0200 (CEST) Subject: [Python-checkins] r80940 - in python/branches/py3k: Lib/unittest/loader.py Lib/unittest/test/test_discovery.py Message-ID: <20100507204743.78780F68DE@mail.python.org> Author: benjamin.peterson Date: Fri May 7 22:47:43 2010 New Revision: 80940 Log: Merged revisions 80939 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r80939 | benjamin.peterson | 2010-05-07 15:45:07 -0500 (Fri, 07 May 2010) | 1 line revert r80932; it breaks windows ........ Modified: python/branches/py3k/ (props changed) python/branches/py3k/Lib/unittest/loader.py python/branches/py3k/Lib/unittest/test/test_discovery.py Modified: python/branches/py3k/Lib/unittest/loader.py ============================================================================== --- python/branches/py3k/Lib/unittest/loader.py (original) +++ python/branches/py3k/Lib/unittest/loader.py Fri May 7 22:47:43 2010 @@ -178,10 +178,7 @@ if not top_level_dir in sys.path: # all test modules must be importable from the top level directory - # should we *unconditionally* put the start directory in first - # in sys.path to minimise likelihood of conflicts between installed - # modules and development versions? - sys.path.insert(0, top_level_dir) + sys.path.append(top_level_dir) self._top_level_dir = top_level_dir is_not_importable = False @@ -254,16 +251,6 @@ except: yield _make_failed_import_test(name, self.suiteClass) else: - mod_file = os.path.abspath(getattr(module, '__file__', full_path)) - 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] - expected_dir = os.path.dirname(full_path) - msg = ("%r module incorrectly imported from %r. Expected %r. " - "Is this module globally installed?") - raise ImportError(msg % (mod_name, module_dir, expected_dir)) yield self.loadTestsFromModule(module) elif os.path.isdir(full_path): if not os.path.isfile(os.path.join(full_path, '__init__.py')): Modified: python/branches/py3k/Lib/unittest/test/test_discovery.py ============================================================================== --- python/branches/py3k/Lib/unittest/test/test_discovery.py (original) +++ python/branches/py3k/Lib/unittest/test/test_discovery.py Fri May 7 22:47:43 2010 @@ -294,45 +294,6 @@ self.assertTrue(program.failfast) self.assertTrue(program.catchbreak) - def test_detect_module_clash(self): - class Module(object): - __file__ = 'bar/foo.py' - sys.modules['foo'] = Module - full_path = os.path.abspath('foo') - original_listdir = os.listdir - original_isfile = os.path.isfile - original_isdir = os.path.isdir - - def cleanup(): - os.listdir = original_listdir - os.path.isfile = original_isfile - os.path.isdir = original_isdir - del sys.modules['foo'] - if full_path in sys.path: - sys.path.remove(full_path) - self.addCleanup(cleanup) - - def listdir(_): - return ['foo.py'] - def isfile(_): - return True - def isdir(_): - return True - os.listdir = listdir - os.path.isfile = isfile - os.path.isdir = isdir - - loader = unittest.TestLoader() - - mod_dir = os.path.abspath('bar') - expected_dir = os.path.abspath('foo') - msg = (r"^'foo' module incorrectly imported from %r\. Expected %r\. " - "Is this module globally installed\?$") % (mod_dir, expected_dir) - self.assertRaisesRegexp( - ImportError, msg, loader.discover, - start_dir='foo', pattern='foo.py' - ) - self.assertEqual(sys.path[0], full_path) if __name__ == '__main__': unittest.main() From python-checkins at python.org Sat May 8 00:41:56 2010 From: python-checkins at python.org (jean-paul.calderone) Date: Sat, 8 May 2010 00:41:56 +0200 (CEST) Subject: [Python-checkins] r80941 - python/branches/siginterrupt-reset-issue8354/Lib/test/test_signal.py Message-ID: <20100507224156.C1AC1F9B6@mail.python.org> Author: jean-paul.calderone Date: Sat May 8 00:41:56 2010 New Revision: 80941 Log: Use single blank line between methods Modified: python/branches/siginterrupt-reset-issue8354/Lib/test/test_signal.py Modified: python/branches/siginterrupt-reset-issue8354/Lib/test/test_signal.py ============================================================================== --- python/branches/siginterrupt-reset-issue8354/Lib/test/test_signal.py (original) +++ python/branches/siginterrupt-reset-issue8354/Lib/test/test_signal.py Sat May 8 00:41:56 2010 @@ -264,7 +264,6 @@ oldhandler = signal.signal(self.signum, lambda x,y: None) self.addCleanup(signal.signal, self.signum, oldhandler) - def readpipe_interrupted(self, cb): """Perform a read during which a signal will arrive. Return True if the read is interrupted by the signal and raises an exception, False @@ -323,7 +322,6 @@ raise return True - def test_without_siginterrupt(self): """If a signal handler is installed and siginterrupt is not called at all, when that signal arrives, it interrupts a syscall that's in @@ -335,7 +333,6 @@ i = self.readpipe_interrupted(lambda: None) self.assertEquals(i, True) - def test_siginterrupt_on(self): """If a signal handler is installed and siginterrupt is called with a true value for the second argument, when that signal arrives, it @@ -347,7 +344,6 @@ i = self.readpipe_interrupted(lambda: None) self.assertEquals(i, True) - def test_siginterrupt_off(self): """If a signal handler is installed and siginterrupt is called with a false value for the second argument, when that signal arrives, it From python-checkins at python.org Sat May 8 00:42:17 2010 From: python-checkins at python.org (jean-paul.calderone) Date: Sat, 8 May 2010 00:42:17 +0200 (CEST) Subject: [Python-checkins] r80942 - python/branches/siginterrupt-reset-issue8354/Lib/test/test_signal.py Message-ID: <20100507224217.0FB83F9B6@mail.python.org> Author: jean-paul.calderone Date: Sat May 8 00:42:16 2010 New Revision: 80942 Log: Fix run-on sentence Modified: python/branches/siginterrupt-reset-issue8354/Lib/test/test_signal.py Modified: python/branches/siginterrupt-reset-issue8354/Lib/test/test_signal.py ============================================================================== --- python/branches/siginterrupt-reset-issue8354/Lib/test/test_signal.py (original) +++ python/branches/siginterrupt-reset-issue8354/Lib/test/test_signal.py Sat May 8 00:42:16 2010 @@ -265,8 +265,8 @@ self.addCleanup(signal.signal, self.signum, oldhandler) def readpipe_interrupted(self, cb): - """Perform a read during which a signal will arrive. Return True if - the read is interrupted by the signal and raises an exception, False + """Perform a read during which a signal will arrive. Return True if the + read is interrupted by the signal and raises an exception. Return False if it returns normally. """ # Create a pipe that can be used for the read. Also clean it up From python-checkins at python.org Sat May 8 00:43:43 2010 From: python-checkins at python.org (jean-paul.calderone) Date: Sat, 8 May 2010 00:43:43 +0200 (CEST) Subject: [Python-checkins] r80943 - python/branches/siginterrupt-reset-issue8354/Lib/test/test_signal.py Message-ID: <20100507224343.7F9BBF9B6@mail.python.org> Author: jean-paul.calderone Date: Sat May 8 00:43:43 2010 New Revision: 80943 Log: Get rid of the cb callback in readpipe_interrupted; just call siginterrupt in the test methods (if appropriate). Modified: python/branches/siginterrupt-reset-issue8354/Lib/test/test_signal.py Modified: python/branches/siginterrupt-reset-issue8354/Lib/test/test_signal.py ============================================================================== --- python/branches/siginterrupt-reset-issue8354/Lib/test/test_signal.py (original) +++ python/branches/siginterrupt-reset-issue8354/Lib/test/test_signal.py Sat May 8 00:43:43 2010 @@ -264,7 +264,7 @@ oldhandler = signal.signal(self.signum, lambda x,y: None) self.addCleanup(signal.signal, self.signum, oldhandler) - def readpipe_interrupted(self, cb): + def readpipe_interrupted(self): """Perform a read during which a signal will arrive. Return True if the read is interrupted by the signal and raises an exception. Return False if it returns normally. @@ -275,10 +275,6 @@ r, w = os.pipe() self.addCleanup(os.close, r) - # Give the test-method supplied function a chance to perhaps change - # the disposition of the handler. - cb() - # Create another process which can send a signal to this one to try # to interrupt the read. ppid = os.getpid() @@ -327,10 +323,10 @@ at all, when that signal arrives, it interrupts a syscall that's in progress. """ - i = self.readpipe_interrupted(lambda: None) + i = self.readpipe_interrupted() self.assertEquals(i, True) # Arrival of the signal shouldn't have changed anything. - i = self.readpipe_interrupted(lambda: None) + i = self.readpipe_interrupted() self.assertEquals(i, True) def test_siginterrupt_on(self): @@ -338,10 +334,11 @@ a true value for the second argument, when that signal arrives, it interrupts a syscall that's in progress. """ - i = self.readpipe_interrupted(lambda: signal.siginterrupt(self.signum, 1)) + signal.siginterrupt(self.signum, 1) + i = self.readpipe_interrupted() self.assertEquals(i, True) # Arrival of the signal shouldn't have changed anything. - i = self.readpipe_interrupted(lambda: None) + i = self.readpipe_interrupted() self.assertEquals(i, True) def test_siginterrupt_off(self): @@ -349,10 +346,11 @@ a false value for the second argument, when that signal arrives, it does not interrupt a syscall that's in progress. """ - i = self.readpipe_interrupted(lambda: signal.siginterrupt(self.signum, 0)) + signal.siginterrupt(self.signum, 0) + i = self.readpipe_interrupted() self.assertEquals(i, False) # Arrival of the signal shouldn't have changed anything. - i = self.readpipe_interrupted(lambda: None) + i = self.readpipe_interrupted() self.assertEquals(i, False) From python-checkins at python.org Sat May 8 00:46:33 2010 From: python-checkins at python.org (jean-paul.calderone) Date: Sat, 8 May 2010 00:46:33 +0200 (CEST) Subject: [Python-checkins] r80944 - python/branches/siginterrupt-reset-issue8354/Lib/test/test_signal.py Message-ID: <20100507224633.61549EE991@mail.python.org> Author: jean-paul.calderone Date: Sat May 8 00:46:33 2010 New Revision: 80944 Log: use assertTrue and assertFalse Modified: python/branches/siginterrupt-reset-issue8354/Lib/test/test_signal.py Modified: python/branches/siginterrupt-reset-issue8354/Lib/test/test_signal.py ============================================================================== --- python/branches/siginterrupt-reset-issue8354/Lib/test/test_signal.py (original) +++ python/branches/siginterrupt-reset-issue8354/Lib/test/test_signal.py Sat May 8 00:46:33 2010 @@ -324,10 +324,10 @@ progress. """ i = self.readpipe_interrupted() - self.assertEquals(i, True) + self.assertTrue(i) # Arrival of the signal shouldn't have changed anything. i = self.readpipe_interrupted() - self.assertEquals(i, True) + self.assertTrue(i) def test_siginterrupt_on(self): """If a signal handler is installed and siginterrupt is called with @@ -336,10 +336,10 @@ """ signal.siginterrupt(self.signum, 1) i = self.readpipe_interrupted() - self.assertEquals(i, True) + self.assertTrue(i) # Arrival of the signal shouldn't have changed anything. i = self.readpipe_interrupted() - self.assertEquals(i, True) + self.assertTrue(i) def test_siginterrupt_off(self): """If a signal handler is installed and siginterrupt is called with @@ -348,10 +348,10 @@ """ signal.siginterrupt(self.signum, 0) i = self.readpipe_interrupted() - self.assertEquals(i, False) + self.assertFalse(i) # Arrival of the signal shouldn't have changed anything. i = self.readpipe_interrupted() - self.assertEquals(i, False) + self.assertFalse(i) From python-checkins at python.org Sat May 8 00:46:41 2010 From: python-checkins at python.org (jean-paul.calderone) Date: Sat, 8 May 2010 00:46:41 +0200 (CEST) Subject: [Python-checkins] r80945 - python/branches/siginterrupt-reset-issue8354/Modules/signalmodule.c Message-ID: <20100507224641.908E0EE9EE@mail.python.org> Author: jean-paul.calderone Date: Sat May 8 00:46:41 2010 New Revision: 80945 Log: Reference the issue number for this change. Modified: python/branches/siginterrupt-reset-issue8354/Modules/signalmodule.c Modified: python/branches/siginterrupt-reset-issue8354/Modules/signalmodule.c ============================================================================== --- python/branches/siginterrupt-reset-issue8354/Modules/signalmodule.c (original) +++ python/branches/siginterrupt-reset-issue8354/Modules/signalmodule.c Sat May 8 00:46:41 2010 @@ -201,7 +201,7 @@ #ifndef HAVE_SIGACTION /* If the handler was not set up with sigaction, reinstall it. See * Python/pythonrun.c for the implementation of PyOS_setsig which - * makes this true. */ + * makes this true. See also issue8354. */ PyOS_setsig(sig_num, signal_handler); #endif } From solipsis at pitrou.net Sat May 8 01:22:20 2010 From: solipsis at pitrou.net (solipsis at pitrou.net) Date: Sat, 8 May 2010 01:22:20 +0200 (CEST) Subject: [Python-checkins] Daily py3k reference leaks (r80940): sum=0 Message-ID: <20100507232220.96B8C1770A@ns6635.ovh.net> py3k results for svn r80940 (hg cset 219d87136f0f) -------------------------------------------------- Command line was: ['./python', '-m', 'test.regrtest', '-uall', '-R', '3:3:/home/antoine/py3k/refleaks/reflogxwM8YX', '-x'] From python-checkins at python.org Sat May 8 01:39:38 2010 From: python-checkins at python.org (michael.foord) Date: Sat, 8 May 2010 01:39:38 +0200 (CEST) Subject: [Python-checkins] r80946 - in python/trunk/Lib/unittest: loader.py test/test_discovery.py Message-ID: <20100507233938.A530FEE982@mail.python.org> Author: michael.foord Date: Sat May 8 01:39:38 2010 New Revision: 80946 Log: Issue 8547 - detecting and reporting that modules have been imported from the wrong location under test discovery. Modified: python/trunk/Lib/unittest/loader.py python/trunk/Lib/unittest/test/test_discovery.py Modified: python/trunk/Lib/unittest/loader.py ============================================================================== --- python/trunk/Lib/unittest/loader.py (original) +++ python/trunk/Lib/unittest/loader.py Sat May 8 01:39:38 2010 @@ -173,7 +173,10 @@ if not top_level_dir in sys.path: # all test modules must be importable from the top level directory - sys.path.append(top_level_dir) + # should we *unconditionally* put the start directory in first + # in sys.path to minimise likelihood of conflicts between installed + # modules and development versions? + sys.path.insert(0, top_level_dir) self._top_level_dir = top_level_dir is_not_importable = False @@ -246,6 +249,16 @@ except: yield _make_failed_import_test(name, self.suiteClass) else: + mod_file = os.path.abspath(getattr(module, '__file__', full_path)) + 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] + expected_dir = os.path.dirname(full_path) + msg = ("%r module incorrectly imported from %r. Expected %r. " + "Is this module globally installed?") + raise ImportError(msg % (mod_name, module_dir, expected_dir)) yield self.loadTestsFromModule(module) elif os.path.isdir(full_path): if not os.path.isfile(os.path.join(full_path, '__init__.py')): Modified: python/trunk/Lib/unittest/test/test_discovery.py ============================================================================== --- python/trunk/Lib/unittest/test/test_discovery.py (original) +++ python/trunk/Lib/unittest/test/test_discovery.py Sat May 8 01:39:38 2010 @@ -1,4 +1,5 @@ import os +import re import sys import unittest @@ -54,8 +55,9 @@ loader._get_module_from_name = lambda path: path + ' module' loader.loadTestsFromModule = lambda module: module + ' tests' - loader._top_level_dir = '/foo' - suite = list(loader._find_tests('/foo', 'test*.py')) + top_level = os.path.abspath('/foo') + loader._top_level_dir = top_level + suite = list(loader._find_tests(top_level, 'test*.py')) expected = [name + ' module tests' for name in ('test1', 'test2')] @@ -298,6 +300,46 @@ self.assertTrue(program.failfast) self.assertTrue(program.catchbreak) + def test_detect_module_clash(self): + class Module(object): + __file__ = 'bar/foo.py' + sys.modules['foo'] = Module + full_path = os.path.abspath('foo') + original_listdir = os.listdir + original_isfile = os.path.isfile + original_isdir = os.path.isdir + + def cleanup(): + os.listdir = original_listdir + os.path.isfile = original_isfile + os.path.isdir = original_isdir + del sys.modules['foo'] + if full_path in sys.path: + sys.path.remove(full_path) + self.addCleanup(cleanup) + + def listdir(_): + return ['foo.py'] + def isfile(_): + return True + def isdir(_): + return True + os.listdir = listdir + os.path.isfile = isfile + os.path.isdir = isdir + + loader = unittest.TestLoader() + + mod_dir = os.path.abspath('bar') + expected_dir = os.path.abspath('foo') + msg = re.escape(r"'foo' module incorrectly imported from %r. Expected %r. " + "Is this module globally installed?" % (mod_dir, expected_dir)) + self.assertRaisesRegexp( + ImportError, '^%s$' % msg, loader.discover, + start_dir='foo', pattern='foo.py' + ) + self.assertEqual(sys.path[0], full_path) + if __name__ == '__main__': unittest.main() From python-checkins at python.org Sat May 8 01:42:40 2010 From: python-checkins at python.org (michael.foord) Date: Sat, 8 May 2010 01:42:40 +0200 (CEST) Subject: [Python-checkins] r80947 - in python/branches/py3k: Lib/unittest/loader.py Lib/unittest/test/test_discovery.py Message-ID: <20100507234240.CE9F5EE987@mail.python.org> Author: michael.foord Date: Sat May 8 01:42:40 2010 New Revision: 80947 Log: Merged revisions 80946 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r80946 | michael.foord | 2010-05-08 01:39:38 +0200 (Sat, 08 May 2010) | 1 line Issue 8547 - detecting and reporting that modules have been imported from the wrong location under test discovery. ........ Modified: python/branches/py3k/ (props changed) python/branches/py3k/Lib/unittest/loader.py python/branches/py3k/Lib/unittest/test/test_discovery.py Modified: python/branches/py3k/Lib/unittest/loader.py ============================================================================== --- python/branches/py3k/Lib/unittest/loader.py (original) +++ python/branches/py3k/Lib/unittest/loader.py Sat May 8 01:42:40 2010 @@ -178,7 +178,10 @@ if not top_level_dir in sys.path: # all test modules must be importable from the top level directory - sys.path.append(top_level_dir) + # should we *unconditionally* put the start directory in first + # in sys.path to minimise likelihood of conflicts between installed + # modules and development versions? + sys.path.insert(0, top_level_dir) self._top_level_dir = top_level_dir is_not_importable = False @@ -251,6 +254,16 @@ except: yield _make_failed_import_test(name, self.suiteClass) else: + mod_file = os.path.abspath(getattr(module, '__file__', full_path)) + 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] + expected_dir = os.path.dirname(full_path) + msg = ("%r module incorrectly imported from %r. Expected %r. " + "Is this module globally installed?") + raise ImportError(msg % (mod_name, module_dir, expected_dir)) yield self.loadTestsFromModule(module) elif os.path.isdir(full_path): if not os.path.isfile(os.path.join(full_path, '__init__.py')): Modified: python/branches/py3k/Lib/unittest/test/test_discovery.py ============================================================================== --- python/branches/py3k/Lib/unittest/test/test_discovery.py (original) +++ python/branches/py3k/Lib/unittest/test/test_discovery.py Sat May 8 01:42:40 2010 @@ -1,4 +1,5 @@ import os +import re import sys import unittest @@ -53,8 +54,9 @@ loader._get_module_from_name = lambda path: path + ' module' loader.loadTestsFromModule = lambda module: module + ' tests' - loader._top_level_dir = '/foo' - suite = list(loader._find_tests('/foo', 'test*.py')) + top_level = os.path.abspath('/foo') + loader._top_level_dir = top_level + suite = list(loader._find_tests(top_level, 'test*.py')) expected = [name + ' module tests' for name in ('test1', 'test2')] @@ -294,6 +296,46 @@ self.assertTrue(program.failfast) self.assertTrue(program.catchbreak) + def test_detect_module_clash(self): + class Module(object): + __file__ = 'bar/foo.py' + sys.modules['foo'] = Module + full_path = os.path.abspath('foo') + original_listdir = os.listdir + original_isfile = os.path.isfile + original_isdir = os.path.isdir + + def cleanup(): + os.listdir = original_listdir + os.path.isfile = original_isfile + os.path.isdir = original_isdir + del sys.modules['foo'] + if full_path in sys.path: + sys.path.remove(full_path) + self.addCleanup(cleanup) + + def listdir(_): + return ['foo.py'] + def isfile(_): + return True + def isdir(_): + return True + os.listdir = listdir + os.path.isfile = isfile + os.path.isdir = isdir + + loader = unittest.TestLoader() + + mod_dir = os.path.abspath('bar') + expected_dir = os.path.abspath('foo') + msg = re.escape(r"'foo' module incorrectly imported from %r. Expected %r. " + "Is this module globally installed?" % (mod_dir, expected_dir)) + self.assertRaisesRegexp( + ImportError, '^%s$' % msg, loader.discover, + start_dir='foo', pattern='foo.py' + ) + self.assertEqual(sys.path[0], full_path) + if __name__ == '__main__': unittest.main() From python-checkins at python.org Sat May 8 02:07:07 2010 From: python-checkins at python.org (victor.stinner) Date: Sat, 8 May 2010 02:07:07 +0200 (CEST) Subject: [Python-checkins] r80948 - python/branches/py3k/Python/pythonrun.c Message-ID: <20100508000707.BBAF9EC52@mail.python.org> Author: victor.stinner Date: Sat May 8 02:07:07 2010 New Revision: 80948 Log: err_input(): don't encode/decode the unicode message Modified: python/branches/py3k/Python/pythonrun.c Modified: python/branches/py3k/Python/pythonrun.c ============================================================================== --- python/branches/py3k/Python/pythonrun.c (original) +++ python/branches/py3k/Python/pythonrun.c Sat May 8 02:07:07 2010 @@ -1896,7 +1896,7 @@ err_input(perrdetail *err) { PyObject *v, *w, *errtype, *errtext; - PyObject* u = NULL; + PyObject *msg_obj = NULL; char *msg = NULL; errtype = PyExc_SyntaxError; switch (err->error) { @@ -1952,14 +1952,9 @@ case E_DECODE: { PyObject *type, *value, *tb; PyErr_Fetch(&type, &value, &tb); - if (value != NULL) { - u = PyObject_Str(value); - if (u != NULL) { - msg = _PyUnicode_AsString(u); - } - } - if (msg == NULL) - msg = "unknown decode error"; + msg = "unknown decode error"; + if (value != NULL) + msg_obj = PyObject_Str(value); Py_XDECREF(type); Py_XDECREF(value); Py_XDECREF(tb); @@ -1988,14 +1983,18 @@ } v = Py_BuildValue("(ziiN)", err->filename, err->lineno, err->offset, errtext); - w = NULL; - if (v != NULL) - w = Py_BuildValue("(sO)", msg, v); - Py_XDECREF(u); + if (v != NULL) { + if (msg_obj) + w = Py_BuildValue("(OO)", msg_obj, v); + else + w = Py_BuildValue("(sO)", msg, v); + } else + w = NULL; Py_XDECREF(v); PyErr_SetObject(errtype, w); Py_XDECREF(w); cleanup: + Py_XDECREF(msg_obj); if (err->text != NULL) { PyObject_FREE(err->text); err->text = NULL; From python-checkins at python.org Sat May 8 02:35:33 2010 From: python-checkins at python.org (victor.stinner) Date: Sat, 8 May 2010 02:35:33 +0200 (CEST) Subject: [Python-checkins] r80949 - python/branches/py3k/Python/errors.c Message-ID: <20100508003533.86885EE999@mail.python.org> Author: victor.stinner Date: Sat May 8 02:35:33 2010 New Revision: 80949 Log: PyErr_SetFromErrnoWithFilename() decodes the filename using PyUnicode_DecodeFSDefault() instead of PyUnicode_FromString() Modified: python/branches/py3k/Python/errors.c Modified: python/branches/py3k/Python/errors.c ============================================================================== --- python/branches/py3k/Python/errors.c (original) +++ python/branches/py3k/Python/errors.c Sat May 8 02:35:33 2010 @@ -446,7 +446,7 @@ PyObject * PyErr_SetFromErrnoWithFilename(PyObject *exc, const char *filename) { - PyObject *name = filename ? PyUnicode_FromString(filename) : NULL; + PyObject *name = filename ? PyUnicode_DecodeFSDefault(filename) : NULL; PyObject *result = PyErr_SetFromErrnoWithFilenameObject(exc, name); Py_XDECREF(name); return result; From python-checkins at python.org Sat May 8 02:36:42 2010 From: python-checkins at python.org (victor.stinner) Date: Sat, 8 May 2010 02:36:42 +0200 (CEST) Subject: [Python-checkins] r80950 - python/branches/py3k/Modules/posixmodule.c Message-ID: <20100508003642.67771EE999@mail.python.org> Author: victor.stinner Date: Sat May 8 02:36:42 2010 New Revision: 80950 Log: posix_error_with_allocated_filename() decodes the filename with PyUnicode_DecodeFSDefaultAndSize() and call PyErr_SetFromErrnoWithFilenameObject() instead of PyErr_SetFromErrnoWithFilename() Modified: python/branches/py3k/Modules/posixmodule.c Modified: python/branches/py3k/Modules/posixmodule.c ============================================================================== --- python/branches/py3k/Modules/posixmodule.c (original) +++ python/branches/py3k/Modules/posixmodule.c Sat May 8 02:36:42 2010 @@ -559,9 +559,13 @@ static PyObject * posix_error_with_allocated_filename(PyObject* name) { - PyObject *rc = PyErr_SetFromErrnoWithFilename(PyExc_OSError, - PyBytes_AsString(name)); + PyObject *name_str, *rc; + name_str = PyUnicode_DecodeFSDefaultAndSize(PyBytes_AsString(name), + PyBytes_GET_SIZE(name)); Py_DECREF(name); + rc = PyErr_SetFromErrnoWithFilenameObject(PyExc_OSError, + name_str); + Py_XDECREF(name_str); return rc; } From python-checkins at python.org Sat May 8 03:15:27 2010 From: python-checkins at python.org (andrew.kuchling) Date: Sat, 8 May 2010 03:15:27 +0200 (CEST) Subject: [Python-checkins] r80951 - python/trunk/Doc/whatsnew/2.7.rst Message-ID: <20100508011527.04AC0EEA26@mail.python.org> Author: andrew.kuchling Date: Sat May 8 03:15:26 2010 New Revision: 80951 Log: Add two items Modified: python/trunk/Doc/whatsnew/2.7.rst Modified: python/trunk/Doc/whatsnew/2.7.rst ============================================================================== --- python/trunk/Doc/whatsnew/2.7.rst (original) +++ python/trunk/Doc/whatsnew/2.7.rst Sat May 8 03:15:26 2010 @@ -8,7 +8,7 @@ .. Fix accents on Kristjan Valur Jonsson, Fuerstenau -.. Big jobs: pep 391, PyCapsule +.. Big jobs: pep 391 example .. hyperlink all the methods & functions. @@ -125,6 +125,7 @@ results more correctly. And :func:`repr` of a floating-point number *x* returns a result that's guaranteed to round back to the same number when converted back to a string. +* The :ctype:`PyCapsule` type, used to provide a C API for an extension module. * The :cfunc:`PyLong_AsLongAndOverflow` C API function. One porting change: the :option:`-3` switch now automatically @@ -1348,11 +1349,26 @@ Antoine Pitrou; :issue:`8104`.) * The :mod:`SocketServer` module's :class:`~SocketServer.TCPServer` class now - has a :attr:`~SocketServer.TCPServer.disable_nagle_algorithm` class attribute. - The default value is False; if overridden to be True, + supports socket timeouts and disabling the Nagle algorithm. + The :attr:`~SocketServer.TCPServer.disable_nagle_algorithm` class attribute + defaults to False; if overridden to be True, new request connections will have the TCP_NODELAY option set to prevent buffering many small sends into a single TCP packet. - (Contributed by Kristjan Valur Jonsson; :issue:`6192`.) + The :attr:`~SocketServer.TCPServer.timeout` class attribute can hold + a timeout in seconds that will be applied to the request socket; if + no request is received within that time, :meth:`handle_timeout` + will be called and :meth:`handle_request` will return. + (Contributed by Kristjan Valur Jonsson; :issue:`6192` and :issue:`6267`.) + +* The XML-RPC client and server, provided by the :mod:`xmlrpclib` and + :mod:`SimpleXMLRPCServer` modules, have improved performance by + supporting HTTP/1.1 keep-alive and by optionally using gzip encoding + to compress the XML being exchanged. The gzip compression is + controlled by the :attr:`encode_threshold` attribute of + :class:`SimpleXMLRPCRequestHandler`, which contains a size in bytes; + responses larger than this will be compressed. + (Contributed by Kristjan Valur Jonsson; :issue:`6267`.) + * Updated module: the :mod:`sqlite3` module has been updated to version 2.6.0 of the `pysqlite package `__. Version 2.6.0 includes a number of bugfixes, and adds @@ -1515,6 +1531,15 @@ or comment (which looks like ````). (Patch by Neil Muller; :issue:`2746`.) +* The XML-RPC client and server, provided by the :mod:`xmlrpclib` and + :mod:`SimpleXMLRPCServer` modules, have improved performance by + supporting HTTP/1.1 keep-alive and by optionally using gzip encoding + to compress the XML being exchanged. The gzip compression is + controlled by the :attr:`encode_threshold` attribute of + :class:`SimpleXMLRPCRequestHandler`, which contains a size in bytes; + responses larger than this will be compressed. + (Contributed by Kristjan Valur Jonsson; :issue:`6267`.) + * The :mod:`zipfile` module's :class:`~zipfile.ZipFile` now supports the context management protocol, so you can write ``with zipfile.ZipFile(...) as f: ...``. (Contributed by Brian Curtin; :issue:`5511`.) @@ -2047,6 +2072,52 @@ Arfrever Frehtes Taifersar Arahesis; :issue:`6094`.) +.. _whatsnew27-capsules: + +Capsules +------------------- + +Python 3.1 adds a new C datatype, :ctype:`PyCapsule`, for providing a +C API to an extension module. A capsule is essentially the holder for +a C ``void *`` pointer, and is bound to a module attribute; for +example, the :mod:`socket` module's API is exposed as ``socket.CAPI`, +and :mod:`unicodedata` calls it ``ucnhash_CAPI``. Other extensions +can import the module, access its dictionary to get the capsule +object, and then get the ``void *`` pointer, which will usually point +to an array of pointers to the various API functions. + +There is an existing data type that already does this, +:ctype:`PyCObject`, but it doesn't provide type safety. Evil code +written in pure Python could cause a segmentation fault by taking a +:ctype:`PyCObject` from module A and somehow substituting it for the +:ctype:`PyCObject` in module B. Capsules know their own name, +and getting the pointer requires providing the name:: + + void *vtable; + + if (!PyCapsule_IsValid(capsule, "mymodule.CAPI") { + PyErr_SetString(PyExc_ValueError, "argument type invalid"); + return NULL; + } + + vtable = PyCapsule_GetPointer(capsule, "mymodule.CAPI"); + +You are assured that ``vtable`` points to whatever you're expecting. +If a different capsule was passed in, :cfunc:`PyCapsule_IsValid` would +detect the mismatched name and return false. Refer to +:ref:`using-capsules` for more information on using these objects. + +Python 2.7 now uses capsules internally to provide various +extension-module APIs, but the :cfunc:`PyCObject_AsVoidPtr` was +modified to handle capsules, preserving compile-time compatibility +with the :ctype:`CObject` interface. Use of +:cfunc:`PyCObject_AsVoidPtr` will signal a +:exc:`PendingDeprecationWarning`, which is silent by default. + +Implemented in Python 3.1 and backported to 2.7 by Larry Hastings; +discussed in :issue:`5630`. + + .. ====================================================================== Port-Specific Changes: Windows From python-checkins at python.org Sat May 8 03:35:55 2010 From: python-checkins at python.org (andrew.kuchling) Date: Sat, 8 May 2010 03:35:55 +0200 (CEST) Subject: [Python-checkins] r80952 - python/trunk/Doc/whatsnew/2.7.rst Message-ID: <20100508013555.7BBB7E234@mail.python.org> Author: andrew.kuchling Date: Sat May 8 03:35:55 2010 New Revision: 80952 Log: Get accents correct Modified: python/trunk/Doc/whatsnew/2.7.rst Modified: python/trunk/Doc/whatsnew/2.7.rst ============================================================================== --- python/trunk/Doc/whatsnew/2.7.rst (original) +++ python/trunk/Doc/whatsnew/2.7.rst Sat May 8 03:35:55 2010 @@ -6,8 +6,6 @@ :Release: |release| :Date: |today| -.. Fix accents on Kristjan Valur Jonsson, Fuerstenau - .. Big jobs: pep 391 example .. hyperlink all the methods & functions. @@ -911,7 +909,7 @@ * The :mod:`bz2` module's :class:`~bz2.BZ2File` now supports the context management protocol, so you can write ``with bz2.BZ2File(...) as f: ...``. - (Contributed by Hagen Fuerstenau; :issue:`3860`.) + (Contributed by Hagen F?rstenau; :issue:`3860`.) * New class: the :class:`~collections.Counter` class in the :mod:`collections` module is useful for tallying data. :class:`~collections.Counter` instances @@ -1125,7 +1123,7 @@ * The :mod:`gzip` module's :class:`~gzip.GzipFile` now supports the context management protocol, so you can write ``with gzip.GzipFile(...) as f: ...`` - (contributed by Hagen Fuerstenau; :issue:`3860`), and it now implements + (contributed by Hagen F?rstenau; :issue:`3860`), and it now implements the :class:`io.BufferedIOBase` ABC, so you can wrap it with :class:`io.BufferedReader` for faster processing (contributed by Nir Aides; :issue:`7471`). @@ -1145,7 +1143,7 @@ * The default :class:`~httplib.HTTPResponse` class used by the :mod:`httplib` module now supports buffering, resulting in much faster reading of HTTP responses. - (Contributed by Kristjan Valur Jonsson; :issue:`4879`.) + (Contributed by Kristj?n Valur J?nsson; :issue:`4879`.) The :class:`~httplib.HTTPConnection` and :class:`~httplib.HTTPSConnection` classes now support a *source_address* parameter, a ``(host, port)`` 2-tuple @@ -1358,7 +1356,7 @@ a timeout in seconds that will be applied to the request socket; if no request is received within that time, :meth:`handle_timeout` will be called and :meth:`handle_request` will return. - (Contributed by Kristjan Valur Jonsson; :issue:`6192` and :issue:`6267`.) + (Contributed by Kristj?n Valur J?nsson; :issue:`6192` and :issue:`6267`.) * The XML-RPC client and server, provided by the :mod:`xmlrpclib` and :mod:`SimpleXMLRPCServer` modules, have improved performance by @@ -1367,7 +1365,7 @@ controlled by the :attr:`encode_threshold` attribute of :class:`SimpleXMLRPCRequestHandler`, which contains a size in bytes; responses larger than this will be compressed. - (Contributed by Kristjan Valur Jonsson; :issue:`6267`.) + (Contributed by Kristj?n Valur J?nsson; :issue:`6267`.) * Updated module: the :mod:`sqlite3` module has been updated to @@ -1538,7 +1536,7 @@ controlled by the :attr:`encode_threshold` attribute of :class:`SimpleXMLRPCRequestHandler`, which contains a size in bytes; responses larger than this will be compressed. - (Contributed by Kristjan Valur Jonsson; :issue:`6267`.) + (Contributed by Kristj?n Valur J?nsson; :issue:`6267`.) * The :mod:`zipfile` module's :class:`~zipfile.ZipFile` now supports the context management protocol, so you can write ``with zipfile.ZipFile(...) as f: ...``. @@ -1944,7 +1942,7 @@ * :cfunc:`Py_AddPendingCall` is now thread-safe, letting any worker thread submit notifications to the main Python thread. This is particularly useful for asynchronous IO operations. - (Contributed by Kristjan Valur Jonsson; :issue:`4293`.) + (Contributed by Kristj?n Valur J?nsson; :issue:`4293`.) * New function: :cfunc:`PyCode_NewEmpty` creates an empty code object; only the filename, function name, and first line number are required. @@ -2140,7 +2138,7 @@ * The new :cfunc:`_beginthreadex` API is used to start threads, and the native thread-local storage functions are now used. - (Contributed by Kristjan Valur Jonsson; :issue:`3582`.) + (Contributed by Kristj?n Valur J?nsson; :issue:`3582`.) * The :func:`os.kill` function now works on Windows. The signal value can be the constants :const:`CTRL_C_EVENT`, From python-checkins at python.org Sat May 8 05:11:50 2010 From: python-checkins at python.org (senthil.kumaran) Date: Sat, 8 May 2010 05:11:50 +0200 (CEST) Subject: [Python-checkins] r80953 - in python/trunk/Lib: test/test_urllib2.py urllib2.py Message-ID: <20100508031150.B28E4EE987@mail.python.org> Author: senthil.kumaran Date: Sat May 8 05:11:50 2010 New Revision: 80953 Log: Fix Issue8656 - urllib2 mangles file://-scheme URLs Modified: python/trunk/Lib/test/test_urllib2.py python/trunk/Lib/urllib2.py Modified: python/trunk/Lib/test/test_urllib2.py ============================================================================== --- python/trunk/Lib/test/test_urllib2.py (original) +++ python/trunk/Lib/test/test_urllib2.py Sat May 8 05:11:50 2010 @@ -679,7 +679,7 @@ try: data = r.read() headers = r.info() - newurl = r.geturl() + respurl = r.geturl() finally: r.close() stats = os.stat(TESTFN) @@ -690,6 +690,7 @@ self.assertEqual(headers["Content-type"], "text/plain") self.assertEqual(headers["Content-length"], "13") self.assertEqual(headers["Last-modified"], modified) + self.assertEqual(respurl, url) for url in [ "file://localhost:80%s" % urlpath, Modified: python/trunk/Lib/urllib2.py ============================================================================== --- python/trunk/Lib/urllib2.py (original) +++ python/trunk/Lib/urllib2.py Sat May 8 05:11:50 2010 @@ -1291,7 +1291,7 @@ if not host or \ (not port and socket.gethostbyname(host) in self.get_names()): return addinfourl(open(localfile, 'rb'), - headers, 'file:'+file) + headers, 'file://'+ host + file) except OSError, msg: # urllib2 users shouldn't expect OSErrors coming from urlopen() raise URLError(msg) From python-checkins at python.org Sat May 8 05:14:33 2010 From: python-checkins at python.org (senthil.kumaran) Date: Sat, 8 May 2010 05:14:33 +0200 (CEST) Subject: [Python-checkins] r80954 - in python/branches/release26-maint: Lib/test/test_urllib2.py Lib/urllib2.py Message-ID: <20100508031433.DA2A3EE987@mail.python.org> Author: senthil.kumaran Date: Sat May 8 05:14:33 2010 New Revision: 80954 Log: Merged revisions 80953 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r80953 | senthil.kumaran | 2010-05-08 08:41:50 +0530 (Sat, 08 May 2010) | 3 lines Fix Issue8656 - urllib2 mangles file://-scheme URLs ........ Modified: python/branches/release26-maint/ (props changed) python/branches/release26-maint/Lib/test/test_urllib2.py python/branches/release26-maint/Lib/urllib2.py Modified: python/branches/release26-maint/Lib/test/test_urllib2.py ============================================================================== --- python/branches/release26-maint/Lib/test/test_urllib2.py (original) +++ python/branches/release26-maint/Lib/test/test_urllib2.py Sat May 8 05:14:33 2010 @@ -681,7 +681,7 @@ try: data = r.read() headers = r.info() - newurl = r.geturl() + respurl = r.geturl() finally: r.close() stats = os.stat(TESTFN) @@ -692,6 +692,7 @@ self.assertEqual(headers["Content-type"], "text/plain") self.assertEqual(headers["Content-length"], "13") self.assertEqual(headers["Last-modified"], modified) + self.assertEqual(respurl, url) for url in [ "file://localhost:80%s" % urlpath, Modified: python/branches/release26-maint/Lib/urllib2.py ============================================================================== --- python/branches/release26-maint/Lib/urllib2.py (original) +++ python/branches/release26-maint/Lib/urllib2.py Sat May 8 05:14:33 2010 @@ -1288,7 +1288,7 @@ if not host or \ (not port and socket.gethostbyname(host) in self.get_names()): return addinfourl(open(localfile, 'rb'), - headers, 'file:'+file) + headers, 'file://'+ host + file) except OSError, msg: # urllib2 users shouldn't expect OSErrors coming from urlopen() raise URLError(msg) From python-checkins at python.org Sat May 8 05:29:09 2010 From: python-checkins at python.org (senthil.kumaran) Date: Sat, 8 May 2010 05:29:09 +0200 (CEST) Subject: [Python-checkins] r80955 - in python/branches/py3k: Lib/test/test_urllib2.py Lib/urllib/request.py Message-ID: <20100508032909.7E66BEE987@mail.python.org> Author: senthil.kumaran Date: Sat May 8 05:29:09 2010 New Revision: 80955 Log: Merged revisions 80953 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r80953 | senthil.kumaran | 2010-05-08 08:41:50 +0530 (Sat, 08 May 2010) | 3 lines Fix Issue8656 - urllib2 mangles file://-scheme URLs ........ Modified: python/branches/py3k/ (props changed) python/branches/py3k/Lib/test/test_urllib2.py python/branches/py3k/Lib/urllib/request.py Modified: python/branches/py3k/Lib/test/test_urllib2.py ============================================================================== --- python/branches/py3k/Lib/test/test_urllib2.py (original) +++ python/branches/py3k/Lib/test/test_urllib2.py Sat May 8 05:29:09 2010 @@ -684,7 +684,7 @@ try: data = r.read() headers = r.info() - newurl = r.geturl() + respurl = r.geturl() finally: r.close() stats = os.stat(TESTFN) @@ -695,6 +695,7 @@ self.assertEqual(headers["Content-type"], "text/plain") self.assertEqual(headers["Content-length"], "13") self.assertEqual(headers["Last-modified"], modified) + self.assertEqual(respurl, url) for url in [ "file://localhost:80%s" % urlpath, Modified: python/branches/py3k/Lib/urllib/request.py ============================================================================== --- python/branches/py3k/Lib/urllib/request.py (original) +++ python/branches/py3k/Lib/urllib/request.py Sat May 8 05:29:09 2010 @@ -1216,7 +1216,8 @@ host, port = splitport(host) if not host or \ (not port and _safe_gethostbyname(host) in self.get_names()): - return addinfourl(open(localfile, 'rb'), headers, 'file:'+file) + return addinfourl(open(localfile, 'rb'), headers, 'file://'+ + host + file) except OSError as msg: # users shouldn't expect OSErrors coming from urlopen() raise URLError(msg) From python-checkins at python.org Sat May 8 05:31:57 2010 From: python-checkins at python.org (senthil.kumaran) Date: Sat, 8 May 2010 05:31:57 +0200 (CEST) Subject: [Python-checkins] r80956 - in python/branches/release31-maint: Lib/test/test_urllib2.py Lib/urllib/request.py Message-ID: <20100508033157.18516FD8E@mail.python.org> Author: senthil.kumaran Date: Sat May 8 05:31:56 2010 New Revision: 80956 Log: Merged revisions 80955 via svnmerge from svn+ssh://pythondev at svn.python.org/python/branches/py3k ................ r80955 | senthil.kumaran | 2010-05-08 08:59:09 +0530 (Sat, 08 May 2010) | 9 lines Merged revisions 80953 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r80953 | senthil.kumaran | 2010-05-08 08:41:50 +0530 (Sat, 08 May 2010) | 3 lines Fix Issue8656 - urllib2 mangles file://-scheme URLs ........ ................ Modified: python/branches/release31-maint/ (props changed) python/branches/release31-maint/Lib/test/test_urllib2.py python/branches/release31-maint/Lib/urllib/request.py Modified: python/branches/release31-maint/Lib/test/test_urllib2.py ============================================================================== --- python/branches/release31-maint/Lib/test/test_urllib2.py (original) +++ python/branches/release31-maint/Lib/test/test_urllib2.py Sat May 8 05:31:56 2010 @@ -689,7 +689,7 @@ try: data = r.read() headers = r.info() - newurl = r.geturl() + respurl = r.geturl() finally: r.close() stats = os.stat(TESTFN) @@ -700,6 +700,7 @@ self.assertEqual(headers["Content-type"], "text/plain") self.assertEqual(headers["Content-length"], "13") self.assertEqual(headers["Last-modified"], modified) + self.assertEqual(respurl, url) for url in [ "file://localhost:80%s" % urlpath, Modified: python/branches/release31-maint/Lib/urllib/request.py ============================================================================== --- python/branches/release31-maint/Lib/urllib/request.py (original) +++ python/branches/release31-maint/Lib/urllib/request.py Sat May 8 05:31:56 2010 @@ -1216,7 +1216,8 @@ host, port = splitport(host) if not host or \ (not port and _safe_gethostbyname(host) in self.get_names()): - return addinfourl(open(localfile, 'rb'), headers, 'file:'+file) + return addinfourl(open(localfile, 'rb'), headers, 'file://'+ + host + file) except OSError as msg: # users shouldn't expect OSErrors coming from urlopen() raise URLError(msg) From python-checkins at python.org Sat May 8 07:00:11 2010 From: python-checkins at python.org (senthil.kumaran) Date: Sat, 8 May 2010 07:00:11 +0200 (CEST) Subject: [Python-checkins] r80957 - python/trunk/Lib/urllib2.py Message-ID: <20100508050011.9D0D4EE987@mail.python.org> Author: senthil.kumaran Date: Sat May 8 07:00:11 2010 New Revision: 80957 Log: Fixing the errors trigerred in test_urllib2net. Related to issue8656. Modified: python/trunk/Lib/urllib2.py Modified: python/trunk/Lib/urllib2.py ============================================================================== --- python/trunk/Lib/urllib2.py (original) +++ python/trunk/Lib/urllib2.py Sat May 8 07:00:11 2010 @@ -1276,13 +1276,13 @@ import email.utils import mimetypes host = req.get_host() - file = req.get_selector() - localfile = url2pathname(file) + filename = req.get_selector() + localfile = url2pathname(filename) try: stats = os.stat(localfile) size = stats.st_size modified = email.utils.formatdate(stats.st_mtime, usegmt=True) - mtype = mimetypes.guess_type(file)[0] + mtype = mimetypes.guess_type(filename)[0] headers = mimetools.Message(StringIO( 'Content-type: %s\nContent-length: %d\nLast-modified: %s\n' % (mtype or 'text/plain', size, modified))) @@ -1290,8 +1290,11 @@ host, port = splitport(host) if not host or \ (not port and socket.gethostbyname(host) in self.get_names()): - return addinfourl(open(localfile, 'rb'), - headers, 'file://'+ host + file) + if host: + origurl = 'file://' + host + filename + else: + origurl = 'file://' + filename + return addinfourl(open(localfile, 'rb'), headers, origurl) except OSError, msg: # urllib2 users shouldn't expect OSErrors coming from urlopen() raise URLError(msg) From python-checkins at python.org Sat May 8 07:03:46 2010 From: python-checkins at python.org (senthil.kumaran) Date: Sat, 8 May 2010 07:03:46 +0200 (CEST) Subject: [Python-checkins] r80958 - in python/branches/release26-maint: Lib/urllib2.py Message-ID: <20100508050346.0EA12EE987@mail.python.org> Author: senthil.kumaran Date: Sat May 8 07:03:45 2010 New Revision: 80958 Log: Merged revisions 80957 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r80957 | senthil.kumaran | 2010-05-08 10:30:11 +0530 (Sat, 08 May 2010) | 2 lines Fixing the errors trigerred in test_urllib2net. Related to issue8656. ........ Modified: python/branches/release26-maint/ (props changed) python/branches/release26-maint/Lib/urllib2.py Modified: python/branches/release26-maint/Lib/urllib2.py ============================================================================== --- python/branches/release26-maint/Lib/urllib2.py (original) +++ python/branches/release26-maint/Lib/urllib2.py Sat May 8 07:03:45 2010 @@ -1273,13 +1273,13 @@ import email.utils import mimetypes host = req.get_host() - file = req.get_selector() - localfile = url2pathname(file) + filename = req.get_selector() + localfile = url2pathname(filename) try: stats = os.stat(localfile) size = stats.st_size modified = email.utils.formatdate(stats.st_mtime, usegmt=True) - mtype = mimetypes.guess_type(file)[0] + mtype = mimetypes.guess_type(filename)[0] headers = mimetools.Message(StringIO( 'Content-type: %s\nContent-length: %d\nLast-modified: %s\n' % (mtype or 'text/plain', size, modified))) @@ -1287,8 +1287,11 @@ host, port = splitport(host) if not host or \ (not port and socket.gethostbyname(host) in self.get_names()): - return addinfourl(open(localfile, 'rb'), - headers, 'file://'+ host + file) + if host: + origurl = 'file://' + host + filename + else: + origurl = 'file://' + filename + return addinfourl(open(localfile, 'rb'), headers, origurl) except OSError, msg: # urllib2 users shouldn't expect OSErrors coming from urlopen() raise URLError(msg) From python-checkins at python.org Sat May 8 07:12:05 2010 From: python-checkins at python.org (senthil.kumaran) Date: Sat, 8 May 2010 07:12:05 +0200 (CEST) Subject: [Python-checkins] r80959 - in python/branches/py3k: Lib/urllib/request.py Message-ID: <20100508051205.33BAEEE987@mail.python.org> Author: senthil.kumaran Date: Sat May 8 07:12:05 2010 New Revision: 80959 Log: Merged revisions 80957 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r80957 | senthil.kumaran | 2010-05-08 10:30:11 +0530 (Sat, 08 May 2010) | 2 lines Fixing the errors trigerred in test_urllib2net. Related to issue8656. ........ Modified: python/branches/py3k/ (props changed) python/branches/py3k/Lib/urllib/request.py Modified: python/branches/py3k/Lib/urllib/request.py ============================================================================== --- python/branches/py3k/Lib/urllib/request.py (original) +++ python/branches/py3k/Lib/urllib/request.py Sat May 8 07:12:05 2010 @@ -1202,13 +1202,13 @@ import email.utils import mimetypes host = req.host - file = req.selector - localfile = url2pathname(file) + filename = req.selector + localfile = url2pathname(filename) try: stats = os.stat(localfile) size = stats.st_size modified = email.utils.formatdate(stats.st_mtime, usegmt=True) - mtype = mimetypes.guess_type(file)[0] + mtype = mimetypes.guess_type(filename)[0] headers = email.message_from_string( 'Content-type: %s\nContent-length: %d\nLast-modified: %s\n' % (mtype or 'text/plain', size, modified)) @@ -1216,8 +1216,11 @@ host, port = splitport(host) if not host or \ (not port and _safe_gethostbyname(host) in self.get_names()): - return addinfourl(open(localfile, 'rb'), headers, 'file://'+ - host + file) + if host: + origurl = 'file://' + host + filename + else: + origurl = 'file://' + filename + return addinfourl(open(localfile, 'rb'), headers, origurl) except OSError as msg: # users shouldn't expect OSErrors coming from urlopen() raise URLError(msg) From python-checkins at python.org Sat May 8 07:14:29 2010 From: python-checkins at python.org (senthil.kumaran) Date: Sat, 8 May 2010 07:14:29 +0200 (CEST) Subject: [Python-checkins] r80960 - in python/branches/release31-maint: Lib/urllib/request.py Message-ID: <20100508051429.D9C92EE987@mail.python.org> Author: senthil.kumaran Date: Sat May 8 07:14:29 2010 New Revision: 80960 Log: Merged revisions 80959 via svnmerge from svn+ssh://pythondev at svn.python.org/python/branches/py3k ................ r80959 | senthil.kumaran | 2010-05-08 10:42:05 +0530 (Sat, 08 May 2010) | 9 lines Merged revisions 80957 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r80957 | senthil.kumaran | 2010-05-08 10:30:11 +0530 (Sat, 08 May 2010) | 2 lines Fixing the errors trigerred in test_urllib2net. Related to issue8656. ........ ................ Modified: python/branches/release31-maint/ (props changed) python/branches/release31-maint/Lib/urllib/request.py Modified: python/branches/release31-maint/Lib/urllib/request.py ============================================================================== --- python/branches/release31-maint/Lib/urllib/request.py (original) +++ python/branches/release31-maint/Lib/urllib/request.py Sat May 8 07:14:29 2010 @@ -1202,13 +1202,13 @@ import email.utils import mimetypes host = req.host - file = req.selector - localfile = url2pathname(file) + filename = req.selector + localfile = url2pathname(filename) try: stats = os.stat(localfile) size = stats.st_size modified = email.utils.formatdate(stats.st_mtime, usegmt=True) - mtype = mimetypes.guess_type(file)[0] + mtype = mimetypes.guess_type(filename)[0] headers = email.message_from_string( 'Content-type: %s\nContent-length: %d\nLast-modified: %s\n' % (mtype or 'text/plain', size, modified)) @@ -1216,8 +1216,11 @@ host, port = splitport(host) if not host or \ (not port and _safe_gethostbyname(host) in self.get_names()): - return addinfourl(open(localfile, 'rb'), headers, 'file://'+ - host + file) + if host: + origurl = 'file://' + host + filename + else: + origurl = 'file://' + filename + return addinfourl(open(localfile, 'rb'), headers, origurl) except OSError as msg: # users shouldn't expect OSErrors coming from urlopen() raise URLError(msg) From python-checkins at python.org Sat May 8 10:01:19 2010 From: python-checkins at python.org (mark.dickinson) Date: Sat, 8 May 2010 10:01:19 +0200 (CEST) Subject: [Python-checkins] r80961 - python/trunk/Objects/longobject.c Message-ID: <20100508080119.863DDDD1C@mail.python.org> Author: mark.dickinson Date: Sat May 8 10:01:19 2010 New Revision: 80961 Log: Issue #8659: Remove redundant ABS calls. Thanks Daniel Stutzbach. Modified: python/trunk/Objects/longobject.c Modified: python/trunk/Objects/longobject.c ============================================================================== --- python/trunk/Objects/longobject.c (original) +++ python/trunk/Objects/longobject.c Sat May 8 10:01:19 2010 @@ -2354,10 +2354,7 @@ Py_ssize_t sign; if (Py_SIZE(a) != Py_SIZE(b)) { - if (ABS(Py_SIZE(a)) == 0 && ABS(Py_SIZE(b)) == 0) - sign = 0; - else - sign = Py_SIZE(a) - Py_SIZE(b); + sign = Py_SIZE(a) - Py_SIZE(b); } else { Py_ssize_t i = ABS(Py_SIZE(a)); @@ -3606,7 +3603,7 @@ static int long_nonzero(PyLongObject *v) { - return ABS(Py_SIZE(v)) != 0; + return Py_SIZE(v) != 0; } static PyObject * From python-checkins at python.org Sat May 8 10:03:10 2010 From: python-checkins at python.org (mark.dickinson) Date: Sat, 8 May 2010 10:03:10 +0200 (CEST) Subject: [Python-checkins] r80962 - in python/branches/py3k: Objects/longobject.c Message-ID: <20100508080310.174BEEE9A6@mail.python.org> Author: mark.dickinson Date: Sat May 8 10:03:09 2010 New Revision: 80962 Log: Merged revisions 80961 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r80961 | mark.dickinson | 2010-05-08 09:01:19 +0100 (Sat, 08 May 2010) | 2 lines Issue #8659: Remove redundant ABS calls. Thanks Daniel Stutzbach. ........ Modified: python/branches/py3k/ (props changed) python/branches/py3k/Objects/longobject.c Modified: python/branches/py3k/Objects/longobject.c ============================================================================== --- python/branches/py3k/Objects/longobject.c (original) +++ python/branches/py3k/Objects/longobject.c Sat May 8 10:03:09 2010 @@ -2492,10 +2492,7 @@ Py_ssize_t sign; if (Py_SIZE(a) != Py_SIZE(b)) { - if (ABS(Py_SIZE(a)) == 0 && ABS(Py_SIZE(b)) == 0) - sign = 0; - else - sign = Py_SIZE(a) - Py_SIZE(b); + sign = Py_SIZE(a) - Py_SIZE(b); } else { Py_ssize_t i = ABS(Py_SIZE(a)); @@ -3772,7 +3769,7 @@ static int long_bool(PyLongObject *v) { - return ABS(Py_SIZE(v)) != 0; + return Py_SIZE(v) != 0; } static PyObject * From python-checkins at python.org Sat May 8 10:44:37 2010 From: python-checkins at python.org (ronald.oussoren) Date: Sat, 8 May 2010 10:44:37 +0200 (CEST) Subject: [Python-checkins] r80963 - in python/trunk: Lib/distutils/unixccompiler.py Misc/NEWS setup.py Message-ID: <20100508084437.CCD72E96E@mail.python.org> Author: ronald.oussoren Date: Sat May 8 10:44:37 2010 New Revision: 80963 Log: Fix for issue #7724: make it possible to build using the OSX 10.4u SDK on MacOSX 10.6 by honoring the specified SDK when looking for files. Modified: python/trunk/Lib/distutils/unixccompiler.py python/trunk/Misc/NEWS python/trunk/setup.py Modified: python/trunk/Lib/distutils/unixccompiler.py ============================================================================== --- python/trunk/Lib/distutils/unixccompiler.py (original) +++ python/trunk/Lib/distutils/unixccompiler.py Sat May 8 10:44:37 2010 @@ -15,7 +15,7 @@ __revision__ = "$Id$" -import os, sys +import os, sys, re from types import StringType, NoneType from distutils import sysconfig @@ -305,10 +305,29 @@ dylib_f = self.library_filename(lib, lib_type='dylib') static_f = self.library_filename(lib, lib_type='static') + if sys.platform == 'darwin': + # On OSX users can specify an alternate SDK using + # '-isysroot', calculate the SDK root if it is specified + # (and use it further on) + cflags = sysconfig.get_config_var('CFLAGS') + m = re.search(r'-isysroot\s+(\S+)', cflags) + if m is None: + sysroot = '/' + else: + sysroot = m.group(1) + + + for dir in dirs: shared = os.path.join(dir, shared_f) dylib = os.path.join(dir, dylib_f) static = os.path.join(dir, static_f) + + if sys.platform == 'darwin' and (dir.startswith('/System/') or dir.startswith('/usr/')): + shared = os.path.join(sysroot, dir[1:], shared_f) + dylib = os.path.join(sysroot, dir[1:], dylib_f) + static = os.path.join(sysroot, dir[1:], static_f) + # We're second-guessing the linker here, with not much hard # data to go on: GCC seems to prefer the shared library, so I'm # assuming that *all* Unix C compilers do. And of course I'm Modified: python/trunk/Misc/NEWS ============================================================================== --- python/trunk/Misc/NEWS (original) +++ python/trunk/Misc/NEWS Sat May 8 10:44:37 2010 @@ -212,6 +212,9 @@ - Issue #3646: It is now easily possible to install a Python framework into your home directory on MacOSX, see Mac/README for more information. +- Issue #7724: Building now full honors an MacOSX SDK when specified, which + makes it possible do a working build with the OSX 10.4 SDK on MacOSX 10.6. + Misc ---- Modified: python/trunk/setup.py ============================================================================== --- python/trunk/setup.py (original) +++ python/trunk/setup.py Sat May 8 10:44:37 2010 @@ -29,6 +29,27 @@ if dir is not None and os.path.isdir(dir) and dir not in dirlist: dirlist.insert(0, dir) +def macosx_sdk_root(): + """ + Return the directory of the current OSX SDK, + or '/' if no SDK was specified. + """ + cflags = sysconfig.get_config_var('CFLAGS') + m = re.search(r'-isysroot\s+(\S+)', cflags) + if m is None: + sysroot = '/' + else: + sysroot = m.group(1) + return sysroot + +def is_macosx_sdk_path(path): + """ + Returns True if 'path' can be located in an OSX SDK + """ + return path.startswith('/usr/') or path.startswith('/System/') + + + def find_file(filename, std_dirs, paths): """Searches for the directory where a given file is located, and returns a possibly-empty list of additional directories, or None @@ -40,15 +61,28 @@ 'paths' is a list of additional locations to check; if the file is found in one of them, the resulting list will contain the directory. """ + if sys.platform == 'darwin': + # Honor the MacOSX SDK setting when one was specified. + # An SDK is a directory with the same structure as a real + # system, but with only header files and libraries. + sysroot = macosx_sdk_root() # Check the standard locations for dir in std_dirs: f = os.path.join(dir, filename) + + if sys.platform == 'darwin' and is_macosx_sdk_path(dir): + f = os.path.join(sysroot, dir[1:], filename) + if os.path.exists(f): return [] # Check the additional directories for dir in paths: f = os.path.join(dir, filename) + + if sys.platform == 'darwin' and dir.startswith('/System') or dir.startswith('/usr'): + f = os.path.join(sysroot, dir[1:], filename) + if os.path.exists(f): return [dir] @@ -60,11 +94,19 @@ if result is None: return None + if sys.platform == 'darwin': + sysroot = macosx_sdk_root() + # Check whether the found file is in one of the standard directories dirname = os.path.dirname(result) for p in std_dirs: # Ensure path doesn't end with path separator p = p.rstrip(os.sep) + + if sys.platform == 'darwin' and is_macosx_sdk_path(p): + if os.path.join(sysroot, p[1:]) == dirname: + return [ ] + if p == dirname: return [ ] @@ -73,6 +115,11 @@ for p in paths: # Ensure path doesn't end with path separator p = p.rstrip(os.sep) + + if sys.platform == 'darwin' and is_macosx_sdk_path(p): + if os.path.join(sysroot, p[1:]) == dirname: + return [ p ] + if p == dirname: return [p] else: @@ -560,7 +607,7 @@ # library and then a static library, instead of first looking # for dynamic libraries on the entiry path. # This way a staticly linked custom readline gets picked up - # before the (broken) dynamic library in /usr/lib. + # before the (possibly broken) dynamic library in /usr/lib. readline_extra_link_args = ('-Wl,-search_paths_first',) else: readline_extra_link_args = () @@ -631,24 +678,20 @@ openssl_ver = 0 openssl_ver_re = re.compile( '^\s*#\s*define\s+OPENSSL_VERSION_NUMBER\s+(0x[0-9a-fA-F]+)' ) - for ssl_inc_dir in inc_dirs + search_for_ssl_incs_in: - name = os.path.join(ssl_inc_dir, 'openssl', 'opensslv.h') - if os.path.isfile(name): - try: - incfile = open(name, 'r') - for line in incfile: - m = openssl_ver_re.match(line) - if m: - openssl_ver = eval(m.group(1)) - break - except IOError: - pass - # first version found is what we'll use (as the compiler should) - if openssl_ver: - break + # look for the openssl version header on the compiler search path. + opensslv_h = find_file('openssl/opensslv.h', inc_dirs, search_for_ssl_incs_in) + if opensslv_h: + name = opensslv_h[0] + try: + incfile = open(name, 'r') + for line in incfile: + m = openssl_ver_re.match(line) + if m: + openssl_ver = eval(m.group(1)) + except IOError: + pass - #print 'openssl_ver = 0x%08x' % openssl_ver min_openssl_ver = 0x00907000 have_any_openssl = ssl_incs is not None and ssl_libs is not None have_usable_openssl = (have_any_openssl and @@ -781,12 +824,19 @@ db_ver_inc_map = {} + if sys.platform == 'darwin': + sysroot = macosx_sdk_root() + class db_found(Exception): pass try: # See whether there is a Sleepycat header in the standard # search path. for d in inc_dirs + db_inc_paths: f = os.path.join(d, "db.h") + + if sys.platform == 'darwin' and is_macosx_sdk_path(d): + f = os.path.join(sysroot, d[1:], "db.h") + if db_setup_debug: print "db: looking for db.h in", f if os.path.exists(f): f = open(f).read() @@ -833,7 +883,20 @@ db_incdir.replace("include", 'lib64'), db_incdir.replace("include", 'lib'), ] - db_dirs_to_check = filter(os.path.isdir, db_dirs_to_check) + + if sys.platform != 'darwin': + db_dirs_to_check = filter(os.path.isdir, db_dirs_to_check) + + else: + # Same as other branch, but takes OSX SDK into account + tmp = [] + for dn in db_dirs_to_check: + if is_macosx_sdk_path(dn): + if os.path.isdir(os.path.join(sysroot, dn[1:])): + tmp.append(dn) + else: + if os.path.isdir(dn): + tmp.append(dn) # Look for a version specific db-X.Y before an ambiguoius dbX # XXX should we -ever- look for a dbX name? Do any @@ -895,8 +958,15 @@ # Scan the default include directories before the SQLite specific # ones. This allows one to override the copy of sqlite on OSX, # where /usr/include contains an old version of sqlite. + if sys.platform == 'darwin': + sysroot = macosx_sdk_root() + for d in inc_dirs + sqlite_inc_paths: f = os.path.join(d, "sqlite3.h") + + if sys.platform == 'darwin' and is_macosx_sdk_path(d): + f = os.path.join(sysroot, d[1:], "sqlite3.h") + if os.path.exists(f): if sqlite_setup_debug: print "sqlite: found %s"%f incf = open(f).read() @@ -984,6 +1054,12 @@ # the more recent berkeleydb's db.h file first in the include path # when attempting to compile and it will fail. f = "/usr/include/db.h" + + if sys.platform == 'darwin': + if is_macosx_sdk_path(f): + sysroot = macosx_sdk_root() + f = os.path.join(sysroot, f[1:]) + if os.path.exists(f) and not db_incs: data = open(f).read() m = re.search(r"#s*define\s+HASHVERSION\s+2\s*", data) @@ -1490,14 +1566,22 @@ join(os.getenv('HOME'), '/Library/Frameworks') ] + sysroot = macosx_sdk_root() + # Find the directory that contains the Tcl.framework and Tk.framework # bundles. # XXX distutils should support -F! for F in framework_dirs: # both Tcl.framework and Tk.framework should be present + + for fw in 'Tcl', 'Tk': - if not exists(join(F, fw + '.framework')): - break + if is_macosx_sdk_path(F): + if not exists(join(sysroot, F[1:], fw + '.framework')): + break + else: + if not exists(join(F, fw + '.framework')): + break else: # ok, F is now directory with both frameworks. Continure # building @@ -1527,7 +1611,12 @@ # architectures. cflags = sysconfig.get_config_vars('CFLAGS')[0] archs = re.findall('-arch\s+(\w+)', cflags) - fp = os.popen("file %s/Tk.framework/Tk | grep 'for architecture'"%(F,)) + + if is_macosx_sdk_path(F): + fp = os.popen("file %s/Tk.framework/Tk | grep 'for architecture'"%(os.path.join(sysroot, F[1:]),)) + else: + fp = os.popen("file %s/Tk.framework/Tk | grep 'for architecture'"%(F,)) + detected_archs = [] for ln in fp: a = ln.split()[-1] From python-checkins at python.org Sat May 8 12:00:29 2010 From: python-checkins at python.org (matthias.klose) Date: Sat, 8 May 2010 12:00:29 +0200 (CEST) Subject: [Python-checkins] r80964 - in python/trunk: Misc/NEWS configure configure.in Message-ID: <20100508100029.B45F1EE9AE@mail.python.org> Author: matthias.klose Date: Sat May 8 12:00:28 2010 New Revision: 80964 Log: - Issue #8510: Update to autoconf2.65. Modified: python/trunk/Misc/NEWS python/trunk/configure python/trunk/configure.in Modified: python/trunk/Misc/NEWS ============================================================================== --- python/trunk/Misc/NEWS (original) +++ python/trunk/Misc/NEWS Sat May 8 12:00:28 2010 @@ -215,6 +215,8 @@ - Issue #7724: Building now full honors an MacOSX SDK when specified, which makes it possible do a working build with the OSX 10.4 SDK on MacOSX 10.6. +- Issue #8510: Update to autoconf2.65. + Misc ---- Modified: python/trunk/configure ============================================================================== --- python/trunk/configure (original) +++ python/trunk/configure Sat May 8 12:00:28 2010 @@ -1,63 +1,86 @@ #! /bin/sh -# From configure.in Revision: 80665 . +# From configure.in Revision: 80832 . # Guess values for system-dependent variables and create Makefiles. -# Generated by GNU Autoconf 2.61 for python 2.7. +# Generated by GNU Autoconf 2.65 for python 2.7. # # Report bugs to . # +# # Copyright (C) 1992, 1993, 1994, 1995, 1996, 1998, 1999, 2000, 2001, -# 2002, 2003, 2004, 2005, 2006 Free Software Foundation, Inc. +# 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009 Free Software Foundation, +# Inc. +# +# # This configure script is free software; the Free Software Foundation # gives unlimited permission to copy, distribute and modify it. -## --------------------- ## -## M4sh Initialization. ## -## --------------------- ## +## -------------------- ## +## M4sh Initialization. ## +## -------------------- ## # Be more Bourne compatible DUALCASE=1; export DUALCASE # for MKS sh -if test -n "${ZSH_VERSION+set}" && (emulate sh) >/dev/null 2>&1; then +if test -n "${ZSH_VERSION+set}" && (emulate sh) >/dev/null 2>&1; then : emulate sh NULLCMD=: - # Zsh 3.x and 4.x performs word splitting on ${1+"$@"}, which + # Pre-4.2 versions of Zsh do word splitting on ${1+"$@"}, which # is contrary to our usage. Disable this feature. alias -g '${1+"$@"}'='"$@"' setopt NO_GLOB_SUBST else - case `(set -o) 2>/dev/null` in - *posix*) set -o posix ;; + case `(set -o) 2>/dev/null` in #( + *posix*) : + set -o posix ;; #( + *) : + ;; esac - fi - - -# PATH needs CR -# Avoid depending upon Character Ranges. -as_cr_letters='abcdefghijklmnopqrstuvwxyz' -as_cr_LETTERS='ABCDEFGHIJKLMNOPQRSTUVWXYZ' -as_cr_Letters=$as_cr_letters$as_cr_LETTERS -as_cr_digits='0123456789' -as_cr_alnum=$as_cr_Letters$as_cr_digits - -# The user is always right. -if test "${PATH_SEPARATOR+set}" != set; then - echo "#! /bin/sh" >conf$$.sh - echo "exit 0" >>conf$$.sh - chmod +x conf$$.sh - if (PATH="/nonexistent;."; conf$$.sh) >/dev/null 2>&1; then - PATH_SEPARATOR=';' - else - PATH_SEPARATOR=: +as_nl=' +' +export as_nl +# Printing a long string crashes Solaris 7 /usr/bin/printf. +as_echo='\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\' +as_echo=$as_echo$as_echo$as_echo$as_echo$as_echo +as_echo=$as_echo$as_echo$as_echo$as_echo$as_echo$as_echo +# Prefer a ksh shell builtin over an external printf program on Solaris, +# but without wasting forks for bash or zsh. +if test -z "$BASH_VERSION$ZSH_VERSION" \ + && (test "X`print -r -- $as_echo`" = "X$as_echo") 2>/dev/null; then + as_echo='print -r --' + as_echo_n='print -rn --' +elif (test "X`printf %s $as_echo`" = "X$as_echo") 2>/dev/null; then + as_echo='printf %s\n' + as_echo_n='printf %s' +else + if test "X`(/usr/ucb/echo -n -n $as_echo) 2>/dev/null`" = "X-n $as_echo"; then + as_echo_body='eval /usr/ucb/echo -n "$1$as_nl"' + as_echo_n='/usr/ucb/echo -n' + else + as_echo_body='eval expr "X$1" : "X\\(.*\\)"' + as_echo_n_body='eval + arg=$1; + case $arg in #( + *"$as_nl"*) + expr "X$arg" : "X\\(.*\\)$as_nl"; + arg=`expr "X$arg" : ".*$as_nl\\(.*\\)"`;; + esac; + expr "X$arg" : "X\\(.*\\)" | tr -d "$as_nl" + ' + export as_echo_n_body + as_echo_n='sh -c $as_echo_n_body as_echo' fi - rm -f conf$$.sh + export as_echo_body + as_echo='sh -c $as_echo_body as_echo' fi -# Support unset when possible. -if ( (MAIL=60; unset MAIL) || exit) >/dev/null 2>&1; then - as_unset=unset -else - as_unset=false +# The user is always right. +if test "${PATH_SEPARATOR+set}" != set; then + PATH_SEPARATOR=: + (PATH='/bin;/bin'; FPATH=$PATH; sh -c :) >/dev/null 2>&1 && { + (PATH='/bin:/bin'; FPATH=$PATH; sh -c :) >/dev/null 2>&1 || + PATH_SEPARATOR=';' + } fi @@ -66,20 +89,18 @@ # there to prevent editors from complaining about space-tab. # (If _AS_PATH_WALK were called with IFS unset, it would disable word # splitting by setting IFS to empty value.) -as_nl=' -' IFS=" "" $as_nl" # Find who we are. Look in the path if we contain no directory separator. -case $0 in +case $0 in #(( *[\\/]* ) as_myself=$0 ;; *) as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $PATH do IFS=$as_save_IFS test -z "$as_dir" && as_dir=. - test -r "$as_dir/$0" && as_myself=$as_dir/$0 && break -done + test -r "$as_dir/$0" && as_myself=$as_dir/$0 && break + done IFS=$as_save_IFS ;; @@ -90,354 +111,322 @@ as_myself=$0 fi if test ! -f "$as_myself"; then - echo "$as_myself: error: cannot find myself; rerun with an absolute file name" >&2 - { (exit 1); exit 1; } + $as_echo "$as_myself: error: cannot find myself; rerun with an absolute file name" >&2 + exit 1 fi -# Work around bugs in pre-3.0 UWIN ksh. -for as_var in ENV MAIL MAILPATH -do ($as_unset $as_var) >/dev/null 2>&1 && $as_unset $as_var +# Unset variables that we do not need and which cause bugs (e.g. in +# pre-3.0 UWIN ksh). But do not cause bugs in bash 2.01; the "|| exit 1" +# suppresses any "Segmentation fault" message there. '((' could +# trigger a bug in pdksh 5.2.14. +for as_var in BASH_ENV ENV MAIL MAILPATH +do eval test x\${$as_var+set} = xset \ + && ( (unset $as_var) || exit 1) >/dev/null 2>&1 && unset $as_var || : done PS1='$ ' PS2='> ' PS4='+ ' # NLS nuisances. -for as_var in \ - LANG LANGUAGE LC_ADDRESS LC_ALL LC_COLLATE LC_CTYPE LC_IDENTIFICATION \ - LC_MEASUREMENT LC_MESSAGES LC_MONETARY LC_NAME LC_NUMERIC LC_PAPER \ - LC_TELEPHONE LC_TIME -do - if (set +x; test -z "`(eval $as_var=C; export $as_var) 2>&1`"); then - eval $as_var=C; export $as_var - else - ($as_unset $as_var) >/dev/null 2>&1 && $as_unset $as_var - fi -done - -# Required to use basename. -if expr a : '\(a\)' >/dev/null 2>&1 && - test "X`expr 00001 : '.*\(...\)'`" = X001; then - as_expr=expr -else - as_expr=false -fi - -if (basename -- /) >/dev/null 2>&1 && test "X`basename -- / 2>&1`" = "X/"; then - as_basename=basename -else - as_basename=false -fi - - -# Name of the executable. -as_me=`$as_basename -- "$0" || -$as_expr X/"$0" : '.*/\([^/][^/]*\)/*$' \| \ - X"$0" : 'X\(//\)$' \| \ - X"$0" : 'X\(/\)' \| . 2>/dev/null || -echo X/"$0" | - sed '/^.*\/\([^/][^/]*\)\/*$/{ - s//\1/ - q - } - /^X\/\(\/\/\)$/{ - s//\1/ - q - } - /^X\/\(\/\).*/{ - s//\1/ - q - } - s/.*/./; q'` +LC_ALL=C +export LC_ALL +LANGUAGE=C +export LANGUAGE # CDPATH. -$as_unset CDPATH - +(unset CDPATH) >/dev/null 2>&1 && unset CDPATH if test "x$CONFIG_SHELL" = x; then - if (eval ":") 2>/dev/null; then - as_have_required=yes + as_bourne_compatible="if test -n \"\${ZSH_VERSION+set}\" && (emulate sh) >/dev/null 2>&1; then : + emulate sh + NULLCMD=: + # Pre-4.2 versions of Zsh do word splitting on \${1+\"\$@\"}, which + # is contrary to our usage. Disable this feature. + alias -g '\${1+\"\$@\"}'='\"\$@\"' + setopt NO_GLOB_SUBST else - as_have_required=no + case \`(set -o) 2>/dev/null\` in #( + *posix*) : + set -o posix ;; #( + *) : + ;; +esac fi - - if test $as_have_required = yes && (eval ": -(as_func_return () { - (exit \$1) -} -as_func_success () { - as_func_return 0 -} -as_func_failure () { - as_func_return 1 -} -as_func_ret_success () { - return 0 -} -as_func_ret_failure () { - return 1 -} +" + as_required="as_fn_return () { (exit \$1); } +as_fn_success () { as_fn_return 0; } +as_fn_failure () { as_fn_return 1; } +as_fn_ret_success () { return 0; } +as_fn_ret_failure () { return 1; } exitcode=0 -if as_func_success; then - : -else - exitcode=1 - echo as_func_success failed. -fi - -if as_func_failure; then - exitcode=1 - echo as_func_failure succeeded. -fi - -if as_func_ret_success; then - : -else - exitcode=1 - echo as_func_ret_success failed. -fi - -if as_func_ret_failure; then - exitcode=1 - echo as_func_ret_failure succeeded. -fi - -if ( set x; as_func_ret_success y && test x = \"\$1\" ); then - : +as_fn_success || { exitcode=1; echo as_fn_success failed.; } +as_fn_failure && { exitcode=1; echo as_fn_failure succeeded.; } +as_fn_ret_success || { exitcode=1; echo as_fn_ret_success failed.; } +as_fn_ret_failure && { exitcode=1; echo as_fn_ret_failure succeeded.; } +if ( set x; as_fn_ret_success y && test x = \"\$1\" ); then : + +else + exitcode=1; echo positional parameters were not saved. +fi +test x\$exitcode = x0 || exit 1" + as_suggested=" as_lineno_1=";as_suggested=$as_suggested$LINENO;as_suggested=$as_suggested" as_lineno_1a=\$LINENO + as_lineno_2=";as_suggested=$as_suggested$LINENO;as_suggested=$as_suggested" as_lineno_2a=\$LINENO + eval 'test \"x\$as_lineno_1'\$as_run'\" != \"x\$as_lineno_2'\$as_run'\" && + test \"x\`expr \$as_lineno_1'\$as_run' + 1\`\" = \"x\$as_lineno_2'\$as_run'\"' || exit 1 +test \$(( 1 + 1 )) = 2 || exit 1" + if (eval "$as_required") 2>/dev/null; then : + as_have_required=yes else - exitcode=1 - echo positional parameters were not saved. + as_have_required=no fi + if test x$as_have_required = xyes && (eval "$as_suggested") 2>/dev/null; then : -test \$exitcode = 0) || { (exit 1); exit 1; } - -( - as_lineno_1=\$LINENO - as_lineno_2=\$LINENO - test \"x\$as_lineno_1\" != \"x\$as_lineno_2\" && - test \"x\`expr \$as_lineno_1 + 1\`\" = \"x\$as_lineno_2\") || { (exit 1); exit 1; } -") 2> /dev/null; then - : else - as_candidate_shells= - as_save_IFS=$IFS; IFS=$PATH_SEPARATOR + as_save_IFS=$IFS; IFS=$PATH_SEPARATOR +as_found=false for as_dir in /bin$PATH_SEPARATOR/usr/bin$PATH_SEPARATOR$PATH do IFS=$as_save_IFS test -z "$as_dir" && as_dir=. - case $as_dir in + as_found=: + case $as_dir in #( /*) for as_base in sh bash ksh sh5; do - as_candidate_shells="$as_candidate_shells $as_dir/$as_base" + # Try only shells that exist, to save several forks. + as_shell=$as_dir/$as_base + if { test -f "$as_shell" || test -f "$as_shell.exe"; } && + { $as_echo "$as_bourne_compatible""$as_required" | as_run=a "$as_shell"; } 2>/dev/null; then : + CONFIG_SHELL=$as_shell as_have_required=yes + if { $as_echo "$as_bourne_compatible""$as_suggested" | as_run=a "$as_shell"; } 2>/dev/null; then : + break 2 +fi +fi done;; esac + as_found=false done +$as_found || { if { test -f "$SHELL" || test -f "$SHELL.exe"; } && + { $as_echo "$as_bourne_compatible""$as_required" | as_run=a "$SHELL"; } 2>/dev/null; then : + CONFIG_SHELL=$SHELL as_have_required=yes +fi; } IFS=$as_save_IFS - for as_shell in $as_candidate_shells $SHELL; do - # Try only shells that exist, to save several forks. - if { test -f "$as_shell" || test -f "$as_shell.exe"; } && - { ("$as_shell") 2> /dev/null <<\_ASEOF -if test -n "${ZSH_VERSION+set}" && (emulate sh) >/dev/null 2>&1; then - emulate sh - NULLCMD=: - # Zsh 3.x and 4.x performs word splitting on ${1+"$@"}, which - # is contrary to our usage. Disable this feature. - alias -g '${1+"$@"}'='"$@"' - setopt NO_GLOB_SUBST -else - case `(set -o) 2>/dev/null` in - *posix*) set -o posix ;; -esac - + if test "x$CONFIG_SHELL" != x; then : + # We cannot yet assume a decent shell, so we have to provide a + # neutralization value for shells without unset; and this also + # works around shells that cannot unset nonexistent variables. + BASH_ENV=/dev/null + ENV=/dev/null + (unset BASH_ENV) >/dev/null 2>&1 && unset BASH_ENV ENV + export CONFIG_SHELL + exec "$CONFIG_SHELL" "$as_myself" ${1+"$@"} +fi + + if test x$as_have_required = xno; then : + $as_echo "$0: This script requires a shell more modern than all" + $as_echo "$0: the shells that I found on your system." + if test x${ZSH_VERSION+set} = xset ; then + $as_echo "$0: In particular, zsh $ZSH_VERSION has bugs and should" + $as_echo "$0: be upgraded to zsh 4.3.4 or later." + else + $as_echo "$0: Please tell bug-autoconf at gnu.org and +$0: http://bugs.python.org/ about your system, including +$0: any error possibly output before this message. Then +$0: install a modern shell, or manually run the script +$0: under such a shell if you do have one." + fi + exit 1 fi - - -: -_ASEOF -}; then - CONFIG_SHELL=$as_shell - as_have_required=yes - if { "$as_shell" 2> /dev/null <<\_ASEOF -if test -n "${ZSH_VERSION+set}" && (emulate sh) >/dev/null 2>&1; then - emulate sh - NULLCMD=: - # Zsh 3.x and 4.x performs word splitting on ${1+"$@"}, which - # is contrary to our usage. Disable this feature. - alias -g '${1+"$@"}'='"$@"' - setopt NO_GLOB_SUBST -else - case `(set -o) 2>/dev/null` in - *posix*) set -o posix ;; -esac - fi - - -: -(as_func_return () { - (exit $1) -} -as_func_success () { - as_func_return 0 -} -as_func_failure () { - as_func_return 1 -} -as_func_ret_success () { - return 0 -} -as_func_ret_failure () { - return 1 -} - -exitcode=0 -if as_func_success; then - : -else - exitcode=1 - echo as_func_success failed. fi +SHELL=${CONFIG_SHELL-/bin/sh} +export SHELL +# Unset more variables known to interfere with behavior of common tools. +CLICOLOR_FORCE= GREP_OPTIONS= +unset CLICOLOR_FORCE GREP_OPTIONS -if as_func_failure; then - exitcode=1 - echo as_func_failure succeeded. -fi +## --------------------- ## +## M4sh Shell Functions. ## +## --------------------- ## +# as_fn_unset VAR +# --------------- +# Portably unset VAR. +as_fn_unset () +{ + { eval $1=; unset $1;} +} +as_unset=as_fn_unset + +# as_fn_set_status STATUS +# ----------------------- +# Set $? to STATUS, without forking. +as_fn_set_status () +{ + return $1 +} # as_fn_set_status + +# as_fn_exit STATUS +# ----------------- +# Exit the shell with STATUS, even in a "trap 0" or "set -e" context. +as_fn_exit () +{ + set +e + as_fn_set_status $1 + exit $1 +} # as_fn_exit + +# as_fn_mkdir_p +# ------------- +# Create "$as_dir" as a directory, including parents if necessary. +as_fn_mkdir_p () +{ -if as_func_ret_success; then - : -else - exitcode=1 - echo as_func_ret_success failed. -fi + case $as_dir in #( + -*) as_dir=./$as_dir;; + esac + test -d "$as_dir" || eval $as_mkdir_p || { + as_dirs= + while :; do + case $as_dir in #( + *\'*) as_qdir=`$as_echo "$as_dir" | sed "s/'/'\\\\\\\\''/g"`;; #'( + *) as_qdir=$as_dir;; + esac + as_dirs="'$as_qdir' $as_dirs" + as_dir=`$as_dirname -- "$as_dir" || +$as_expr X"$as_dir" : 'X\(.*[^/]\)//*[^/][^/]*/*$' \| \ + X"$as_dir" : 'X\(//\)[^/]' \| \ + X"$as_dir" : 'X\(//\)$' \| \ + X"$as_dir" : 'X\(/\)' \| . 2>/dev/null || +$as_echo X"$as_dir" | + sed '/^X\(.*[^/]\)\/\/*[^/][^/]*\/*$/{ + s//\1/ + q + } + /^X\(\/\/\)[^/].*/{ + s//\1/ + q + } + /^X\(\/\/\)$/{ + s//\1/ + q + } + /^X\(\/\).*/{ + s//\1/ + q + } + s/.*/./; q'` + test -d "$as_dir" && break + done + test -z "$as_dirs" || eval "mkdir $as_dirs" + } || test -d "$as_dir" || as_fn_error "cannot create directory $as_dir" -if as_func_ret_failure; then - exitcode=1 - echo as_func_ret_failure succeeded. -fi -if ( set x; as_func_ret_success y && test x = "$1" ); then - : +} # as_fn_mkdir_p +# as_fn_append VAR VALUE +# ---------------------- +# Append the text in VALUE to the end of the definition contained in VAR. Take +# advantage of any shell optimizations that allow amortized linear growth over +# repeated appends, instead of the typical quadratic growth present in naive +# implementations. +if (eval "as_var=1; as_var+=2; test x\$as_var = x12") 2>/dev/null; then : + eval 'as_fn_append () + { + eval $1+=\$2 + }' else - exitcode=1 - echo positional parameters were not saved. -fi - -test $exitcode = 0) || { (exit 1); exit 1; } - -( - as_lineno_1=$LINENO - as_lineno_2=$LINENO - test "x$as_lineno_1" != "x$as_lineno_2" && - test "x`expr $as_lineno_1 + 1`" = "x$as_lineno_2") || { (exit 1); exit 1; } - -_ASEOF -}; then - break -fi - -fi - - done - - if test "x$CONFIG_SHELL" != x; then - for as_var in BASH_ENV ENV - do ($as_unset $as_var) >/dev/null 2>&1 && $as_unset $as_var - done - export CONFIG_SHELL - exec "$CONFIG_SHELL" "$as_myself" ${1+"$@"} -fi - - - if test $as_have_required = no; then - echo This script requires a shell more modern than all the - echo shells that I found on your system. Please install a - echo modern shell, or manually run the script under such a - echo shell if you do have one. - { (exit 1); exit 1; } -fi - - -fi - -fi + as_fn_append () + { + eval $1=\$$1\$2 + } +fi # as_fn_append +# as_fn_arith ARG... +# ------------------ +# Perform arithmetic evaluation on the ARGs, and store the result in the +# global $as_val. Take advantage of shells that can avoid forks. The arguments +# must be portable across $(()) and expr. +if (eval "test \$(( 1 + 1 )) = 2") 2>/dev/null; then : + eval 'as_fn_arith () + { + as_val=$(( $* )) + }' +else + as_fn_arith () + { + as_val=`expr "$@" || test $? -eq 1` + } +fi # as_fn_arith -(eval "as_func_return () { - (exit \$1) -} -as_func_success () { - as_func_return 0 -} -as_func_failure () { - as_func_return 1 -} -as_func_ret_success () { - return 0 -} -as_func_ret_failure () { - return 1 -} +# as_fn_error ERROR [LINENO LOG_FD] +# --------------------------------- +# Output "`basename $0`: error: ERROR" to stderr. If LINENO and LOG_FD are +# provided, also output the error to LOG_FD, referencing LINENO. Then exit the +# script with status $?, using 1 if that was 0. +as_fn_error () +{ + as_status=$?; test $as_status -eq 0 && as_status=1 + if test "$3"; then + as_lineno=${as_lineno-"$2"} as_lineno_stack=as_lineno_stack=$as_lineno_stack + $as_echo "$as_me:${as_lineno-$LINENO}: error: $1" >&$3 + fi + $as_echo "$as_me: error: $1" >&2 + as_fn_exit $as_status +} # as_fn_error -exitcode=0 -if as_func_success; then - : +if expr a : '\(a\)' >/dev/null 2>&1 && + test "X`expr 00001 : '.*\(...\)'`" = X001; then + as_expr=expr else - exitcode=1 - echo as_func_success failed. -fi - -if as_func_failure; then - exitcode=1 - echo as_func_failure succeeded. + as_expr=false fi -if as_func_ret_success; then - : +if (basename -- /) >/dev/null 2>&1 && test "X`basename -- / 2>&1`" = "X/"; then + as_basename=basename else - exitcode=1 - echo as_func_ret_success failed. -fi - -if as_func_ret_failure; then - exitcode=1 - echo as_func_ret_failure succeeded. + as_basename=false fi -if ( set x; as_func_ret_success y && test x = \"\$1\" ); then - : +if (as_dir=`dirname -- /` && test "X$as_dir" = X/) >/dev/null 2>&1; then + as_dirname=dirname else - exitcode=1 - echo positional parameters were not saved. + as_dirname=false fi -test \$exitcode = 0") || { - echo No shell found that supports shell functions. - echo Please tell autoconf at gnu.org about your system, - echo including any error possibly output before this - echo message -} +as_me=`$as_basename -- "$0" || +$as_expr X/"$0" : '.*/\([^/][^/]*\)/*$' \| \ + X"$0" : 'X\(//\)$' \| \ + X"$0" : 'X\(/\)' \| . 2>/dev/null || +$as_echo X/"$0" | + sed '/^.*\/\([^/][^/]*\)\/*$/{ + s//\1/ + q + } + /^X\/\(\/\/\)$/{ + s//\1/ + q + } + /^X\/\(\/\).*/{ + s//\1/ + q + } + s/.*/./; q'` +# Avoid depending upon Character Ranges. +as_cr_letters='abcdefghijklmnopqrstuvwxyz' +as_cr_LETTERS='ABCDEFGHIJKLMNOPQRSTUVWXYZ' +as_cr_Letters=$as_cr_letters$as_cr_LETTERS +as_cr_digits='0123456789' +as_cr_alnum=$as_cr_Letters$as_cr_digits - as_lineno_1=$LINENO - as_lineno_2=$LINENO - test "x$as_lineno_1" != "x$as_lineno_2" && - test "x`expr $as_lineno_1 + 1`" = "x$as_lineno_2" || { - - # Create $as_me.lineno as a copy of $as_myself, but with $LINENO - # uniformly replaced by the line number. The first 'sed' inserts a - # line-number line after each line using $LINENO; the second 'sed' - # does the real work. The second script uses 'N' to pair each - # line-number line with the line containing $LINENO, and appends - # trailing '-' during substitution so that $LINENO is not a special - # case at line end. - # (Raja R Harinath suggested sed '=', and Paul Eggert wrote the - # scripts with optimization help from Paolo Bonzini. Blame Lee - # E. McMahon (1931-1989) for sed's syntax. :-) + as_lineno_1=$LINENO as_lineno_1a=$LINENO + as_lineno_2=$LINENO as_lineno_2a=$LINENO + eval 'test "x$as_lineno_1'$as_run'" != "x$as_lineno_2'$as_run'" && + test "x`expr $as_lineno_1'$as_run' + 1`" = "x$as_lineno_2'$as_run'"' || { + # Blame Lee E. McMahon (1931-1989) for sed's syntax. :-) sed -n ' p /[$]LINENO/= @@ -454,8 +443,7 @@ s/-\n.*// ' >$as_me.lineno && chmod +x "$as_me.lineno" || - { echo "$as_me: error: cannot create $as_me.lineno; rerun with a POSIX shell" >&2 - { (exit 1); exit 1; }; } + { $as_echo "$as_me: error: cannot create $as_me.lineno; rerun with a POSIX shell" >&2; as_fn_exit 1; } # Don't try to exec as it changes $[0], causing all sort of problems # (the dirname of $[0] is not the place where we might find the @@ -465,49 +453,40 @@ exit } - -if (as_dir=`dirname -- /` && test "X$as_dir" = X/) >/dev/null 2>&1; then - as_dirname=dirname -else - as_dirname=false -fi - ECHO_C= ECHO_N= ECHO_T= -case `echo -n x` in +case `echo -n x` in #((((( -n*) - case `echo 'x\c'` in + case `echo 'xy\c'` in *c*) ECHO_T=' ';; # ECHO_T is single tab character. - *) ECHO_C='\c';; + xy) ECHO_C='\c';; + *) echo `echo ksh88 bug on AIX 6.1` > /dev/null + ECHO_T=' ';; esac;; *) ECHO_N='-n';; esac -if expr a : '\(a\)' >/dev/null 2>&1 && - test "X`expr 00001 : '.*\(...\)'`" = X001; then - as_expr=expr -else - as_expr=false -fi - rm -f conf$$ conf$$.exe conf$$.file if test -d conf$$.dir; then rm -f conf$$.dir/conf$$.file else rm -f conf$$.dir - mkdir conf$$.dir + mkdir conf$$.dir 2>/dev/null fi -echo >conf$$.file -if ln -s conf$$.file conf$$ 2>/dev/null; then - as_ln_s='ln -s' - # ... but there are two gotchas: - # 1) On MSYS, both `ln -s file dir' and `ln file dir' fail. - # 2) DJGPP < 2.04 has no symlinks; `ln -s' creates a wrapper executable. - # In both cases, we have to default to `cp -p'. - ln -s conf$$.file conf$$.dir 2>/dev/null && test ! -f conf$$.exe || +if (echo >conf$$.file) 2>/dev/null; then + if ln -s conf$$.file conf$$ 2>/dev/null; then + as_ln_s='ln -s' + # ... but there are two gotchas: + # 1) On MSYS, both `ln -s file dir' and `ln file dir' fail. + # 2) DJGPP < 2.04 has no symlinks; `ln -s' creates a wrapper executable. + # In both cases, we have to default to `cp -p'. + ln -s conf$$.file conf$$.dir 2>/dev/null && test ! -f conf$$.exe || + as_ln_s='cp -p' + elif ln conf$$.file conf$$ 2>/dev/null; then + as_ln_s=ln + else as_ln_s='cp -p' -elif ln conf$$.file conf$$ 2>/dev/null; then - as_ln_s=ln + fi else as_ln_s='cp -p' fi @@ -515,7 +494,7 @@ rmdir conf$$.dir 2>/dev/null if mkdir -p . 2>/dev/null; then - as_mkdir_p=: + as_mkdir_p='mkdir -p "$as_dir"' else test -d ./-p && rmdir ./-p as_mkdir_p=false @@ -532,12 +511,12 @@ as_test_x=' eval sh -c '\'' if test -d "$1"; then - test -d "$1/."; + test -d "$1/."; else - case $1 in - -*)set "./$1";; + case $1 in #( + -*)set "./$1";; esac; - case `ls -ld'$as_ls_L_option' "$1" 2>/dev/null` in + case `ls -ld'$as_ls_L_option' "$1" 2>/dev/null` in #(( ???[sx]*):;;*)false;;esac;fi '\'' sh ' @@ -551,8 +530,8 @@ as_tr_sh="eval sed 'y%*+%pp%;s%[^_$as_cr_alnum]%_%g'" - -exec 7<&0 &1 +test -n "$DJDIR" || exec 7<&0 &1 # Name of the host. # hostname on some systems (SVR3.2, Linux) returns a bogus exit status, @@ -570,7 +549,6 @@ subdirs= MFLAGS= MAKEFLAGS= -SHELL=${CONFIG_SHELL-/bin/sh} # Identity of this package. PACKAGE_NAME='python' @@ -578,6 +556,7 @@ PACKAGE_VERSION='2.7' PACKAGE_STRING='python 2.7' PACKAGE_BUGREPORT='http://bugs.python.org/' +PACKAGE_URL='' ac_unique_file="Include/object.h" # Factoring default headers for most tests. @@ -616,140 +595,175 @@ # include #endif" -ac_subst_vars='SHELL -PATH_SEPARATOR -PACKAGE_NAME -PACKAGE_TARNAME -PACKAGE_VERSION -PACKAGE_STRING -PACKAGE_BUGREPORT -exec_prefix -prefix -program_transform_name -bindir -sbindir -libexecdir -datarootdir -datadir -sysconfdir -sharedstatedir -localstatedir -includedir -oldincludedir -docdir -infodir -htmldir -dvidir -pdfdir -psdir -libdir -localedir -mandir -DEFS -ECHO_C -ECHO_N -ECHO_T -LIBS +ac_subst_vars='LTLIBOBJS +SRCDIRS +THREADHEADERS +UNICODE_OBJS +LIBC +LIBM +HAVE_GETHOSTBYNAME +HAVE_GETHOSTBYNAME_R +HAVE_GETHOSTBYNAME_R_3_ARG +HAVE_GETHOSTBYNAME_R_5_ARG +HAVE_GETHOSTBYNAME_R_6_ARG +LIBOBJS +TRUE +MACHDEP_OBJS +DYNLOADFILE +DLINCLDIR +THREADOBJ +LDLAST +USE_THREAD_MODULE +SIGNAL_OBJS +USE_SIGNAL_MODULE +LIBFFI_INCLUDEDIR +PKG_CONFIG +SHLIBS +CFLAGSFORSHARED +LINKFORSHARED +CCSHARED +BLDSHARED +LDCXXSHARED +LDSHARED +SO +LIBTOOL_CRUFT +OTHER_LIBTOOL_OPT +UNIVERSAL_ARCH_FLAGS +BASECFLAGS +OPT +LN +INSTALL_DATA +INSTALL_SCRIPT +INSTALL_PROGRAM +SVNVERSION +ARFLAGS +AR +RANLIB +GNULD +LINKCC +RUNSHARED +INSTSONAME +LDLIBRARYDIR +BLDLIBRARY +DLLLIBRARY +LDLIBRARY +LIBRARY +BUILDEXEEXT +EGREP +GREP +CPP +MAINCC +CXX +OBJEXT +EXEEXT +ac_ct_CC +CPPFLAGS +LDFLAGS +CFLAGS +CC +EXPORT_MACOSX_DEPLOYMENT_TARGET +CONFIGURE_MACOSX_DEPLOYMENT_TARGET +EXTRAMACHDEPPATH +EXTRAPLATDIR +SGI_ABI +MACHDEP +FRAMEWORKINSTALLAPPSPREFIX +FRAMEWORKUNIXTOOLSPREFIX +FRAMEWORKALTINSTALLLAST +FRAMEWORKALTINSTALLFIRST +FRAMEWORKINSTALLLAST +FRAMEWORKINSTALLFIRST +PYTHONFRAMEWORKINSTALLDIR +PYTHONFRAMEWORKPREFIX +PYTHONFRAMEWORKDIR +PYTHONFRAMEWORKIDENTIFIER +PYTHONFRAMEWORK +LIPO_32BIT_FLAGS +ARCH_RUN_32BIT +UNIVERSALSDK +CONFIG_ARGS +SOVERSION +VERSION +target_alias +host_alias build_alias +LIBS +ECHO_T +ECHO_N +ECHO_C +DEFS +mandir +localedir +libdir +psdir +pdfdir +dvidir +htmldir +infodir +docdir +oldincludedir +includedir +localstatedir +sharedstatedir +sysconfdir +datadir +datarootdir +libexecdir +sbindir +bindir +program_transform_name +prefix +exec_prefix +PACKAGE_URL +PACKAGE_BUGREPORT +PACKAGE_STRING +PACKAGE_VERSION +PACKAGE_TARNAME +PACKAGE_NAME +PATH_SEPARATOR +SHELL' +ac_subst_files='' +ac_user_opts=' +enable_option_checking +enable_universalsdk +with_universal_archs +with_framework_name +enable_framework +with_gcc +with_cxx_main +with_suffix +enable_shared +enable_profiling +with_pydebug +enable_toolbox_glue +with_libs +with_system_expat +with_system_ffi +with_dbmliborder +with_signal_module +with_dec_threads +with_threads +with_thread +with_pth +enable_ipv6 +with_doc_strings +with_tsc +with_pymalloc +with_valgrind +with_wctype_functions +with_fpectl +with_libm +with_libc +enable_big_digits +enable_unicode +' + ac_precious_vars='build_alias host_alias target_alias -VERSION -SOVERSION -CONFIG_ARGS -UNIVERSALSDK -ARCH_RUN_32BIT -LIPO_32BIT_FLAGS -PYTHONFRAMEWORK -PYTHONFRAMEWORKIDENTIFIER -PYTHONFRAMEWORKDIR -PYTHONFRAMEWORKPREFIX -PYTHONFRAMEWORKINSTALLDIR -FRAMEWORKINSTALLFIRST -FRAMEWORKINSTALLLAST -FRAMEWORKALTINSTALLFIRST -FRAMEWORKALTINSTALLLAST -FRAMEWORKUNIXTOOLSPREFIX -FRAMEWORKINSTALLAPPSPREFIX -MACHDEP -SGI_ABI -EXTRAPLATDIR -EXTRAMACHDEPPATH -CONFIGURE_MACOSX_DEPLOYMENT_TARGET -EXPORT_MACOSX_DEPLOYMENT_TARGET CC CFLAGS LDFLAGS -CPPFLAGS -ac_ct_CC -EXEEXT -OBJEXT -CXX -MAINCC -CPP -GREP -EGREP -BUILDEXEEXT -LIBRARY -LDLIBRARY -DLLLIBRARY -BLDLIBRARY -LDLIBRARYDIR -INSTSONAME -RUNSHARED -LINKCC -GNULD -RANLIB -AR -ARFLAGS -SVNVERSION -INSTALL_PROGRAM -INSTALL_SCRIPT -INSTALL_DATA -LN -OPT -BASECFLAGS -UNIVERSAL_ARCH_FLAGS -OTHER_LIBTOOL_OPT -LIBTOOL_CRUFT -SO -LDSHARED -LDCXXSHARED -BLDSHARED -CCSHARED -LINKFORSHARED -CFLAGSFORSHARED -SHLIBS -PKG_CONFIG -LIBFFI_INCLUDEDIR -USE_SIGNAL_MODULE -SIGNAL_OBJS -USE_THREAD_MODULE -LDLAST -THREADOBJ -DLINCLDIR -DYNLOADFILE -MACHDEP_OBJS -TRUE -LIBOBJS -HAVE_GETHOSTBYNAME_R_6_ARG -HAVE_GETHOSTBYNAME_R_5_ARG -HAVE_GETHOSTBYNAME_R_3_ARG -HAVE_GETHOSTBYNAME_R -HAVE_GETHOSTBYNAME -LIBM -LIBC -UNICODE_OBJS -THREADHEADERS -SRCDIRS -LTLIBOBJS' -ac_subst_files='' - ac_precious_vars='build_alias -host_alias -target_alias -CC -CFLAGS -LDFLAGS -LIBS +LIBS CPPFLAGS CPP' @@ -757,6 +771,8 @@ # Initialize some variables set by options. ac_init_help= ac_init_version=false +ac_unrecognized_opts= +ac_unrecognized_sep= # The variables have the same names as the options, with # dashes changed to underlines. cache_file=/dev/null @@ -855,13 +871,20 @@ datarootdir=$ac_optarg ;; -disable-* | --disable-*) - ac_feature=`expr "x$ac_option" : 'x-*disable-\(.*\)'` + ac_useropt=`expr "x$ac_option" : 'x-*disable-\(.*\)'` # Reject names that are not valid shell variable names. - expr "x$ac_feature" : ".*[^-._$as_cr_alnum]" >/dev/null && - { echo "$as_me: error: invalid feature name: $ac_feature" >&2 - { (exit 1); exit 1; }; } - ac_feature=`echo $ac_feature | sed 's/[-.]/_/g'` - eval enable_$ac_feature=no ;; + expr "x$ac_useropt" : ".*[^-+._$as_cr_alnum]" >/dev/null && + as_fn_error "invalid feature name: $ac_useropt" + ac_useropt_orig=$ac_useropt + ac_useropt=`$as_echo "$ac_useropt" | sed 's/[-+.]/_/g'` + case $ac_user_opts in + *" +"enable_$ac_useropt" +"*) ;; + *) ac_unrecognized_opts="$ac_unrecognized_opts$ac_unrecognized_sep--disable-$ac_useropt_orig" + ac_unrecognized_sep=', ';; + esac + eval enable_$ac_useropt=no ;; -docdir | --docdir | --docdi | --doc | --do) ac_prev=docdir ;; @@ -874,13 +897,20 @@ dvidir=$ac_optarg ;; -enable-* | --enable-*) - ac_feature=`expr "x$ac_option" : 'x-*enable-\([^=]*\)'` + ac_useropt=`expr "x$ac_option" : 'x-*enable-\([^=]*\)'` # Reject names that are not valid shell variable names. - expr "x$ac_feature" : ".*[^-._$as_cr_alnum]" >/dev/null && - { echo "$as_me: error: invalid feature name: $ac_feature" >&2 - { (exit 1); exit 1; }; } - ac_feature=`echo $ac_feature | sed 's/[-.]/_/g'` - eval enable_$ac_feature=\$ac_optarg ;; + expr "x$ac_useropt" : ".*[^-+._$as_cr_alnum]" >/dev/null && + as_fn_error "invalid feature name: $ac_useropt" + ac_useropt_orig=$ac_useropt + ac_useropt=`$as_echo "$ac_useropt" | sed 's/[-+.]/_/g'` + case $ac_user_opts in + *" +"enable_$ac_useropt" +"*) ;; + *) ac_unrecognized_opts="$ac_unrecognized_opts$ac_unrecognized_sep--enable-$ac_useropt_orig" + ac_unrecognized_sep=', ';; + esac + eval enable_$ac_useropt=\$ac_optarg ;; -exec-prefix | --exec_prefix | --exec-prefix | --exec-prefi \ | --exec-pref | --exec-pre | --exec-pr | --exec-p | --exec- \ @@ -1071,22 +1101,36 @@ ac_init_version=: ;; -with-* | --with-*) - ac_package=`expr "x$ac_option" : 'x-*with-\([^=]*\)'` + ac_useropt=`expr "x$ac_option" : 'x-*with-\([^=]*\)'` # Reject names that are not valid shell variable names. - expr "x$ac_package" : ".*[^-._$as_cr_alnum]" >/dev/null && - { echo "$as_me: error: invalid package name: $ac_package" >&2 - { (exit 1); exit 1; }; } - ac_package=`echo $ac_package | sed 's/[-.]/_/g'` - eval with_$ac_package=\$ac_optarg ;; + expr "x$ac_useropt" : ".*[^-+._$as_cr_alnum]" >/dev/null && + as_fn_error "invalid package name: $ac_useropt" + ac_useropt_orig=$ac_useropt + ac_useropt=`$as_echo "$ac_useropt" | sed 's/[-+.]/_/g'` + case $ac_user_opts in + *" +"with_$ac_useropt" +"*) ;; + *) ac_unrecognized_opts="$ac_unrecognized_opts$ac_unrecognized_sep--with-$ac_useropt_orig" + ac_unrecognized_sep=', ';; + esac + eval with_$ac_useropt=\$ac_optarg ;; -without-* | --without-*) - ac_package=`expr "x$ac_option" : 'x-*without-\(.*\)'` + ac_useropt=`expr "x$ac_option" : 'x-*without-\(.*\)'` # Reject names that are not valid shell variable names. - expr "x$ac_package" : ".*[^-._$as_cr_alnum]" >/dev/null && - { echo "$as_me: error: invalid package name: $ac_package" >&2 - { (exit 1); exit 1; }; } - ac_package=`echo $ac_package | sed 's/[-.]/_/g'` - eval with_$ac_package=no ;; + expr "x$ac_useropt" : ".*[^-+._$as_cr_alnum]" >/dev/null && + as_fn_error "invalid package name: $ac_useropt" + ac_useropt_orig=$ac_useropt + ac_useropt=`$as_echo "$ac_useropt" | sed 's/[-+.]/_/g'` + case $ac_user_opts in + *" +"with_$ac_useropt" +"*) ;; + *) ac_unrecognized_opts="$ac_unrecognized_opts$ac_unrecognized_sep--without-$ac_useropt_orig" + ac_unrecognized_sep=', ';; + esac + eval with_$ac_useropt=no ;; --x) # Obsolete; use --with-x. @@ -1106,25 +1150,25 @@ | --x-librar=* | --x-libra=* | --x-libr=* | --x-lib=* | --x-li=* | --x-l=*) x_libraries=$ac_optarg ;; - -*) { echo "$as_me: error: unrecognized option: $ac_option -Try \`$0 --help' for more information." >&2 - { (exit 1); exit 1; }; } + -*) as_fn_error "unrecognized option: \`$ac_option' +Try \`$0 --help' for more information." ;; *=*) ac_envvar=`expr "x$ac_option" : 'x\([^=]*\)='` # Reject names that are not valid shell variable names. - expr "x$ac_envvar" : ".*[^_$as_cr_alnum]" >/dev/null && - { echo "$as_me: error: invalid variable name: $ac_envvar" >&2 - { (exit 1); exit 1; }; } + case $ac_envvar in #( + '' | [0-9]* | *[!_$as_cr_alnum]* ) + as_fn_error "invalid variable name: \`$ac_envvar'" ;; + esac eval $ac_envvar=\$ac_optarg export $ac_envvar ;; *) # FIXME: should be removed in autoconf 3.0. - echo "$as_me: WARNING: you should use --build, --host, --target" >&2 + $as_echo "$as_me: WARNING: you should use --build, --host, --target" >&2 expr "x$ac_option" : ".*[^-._$as_cr_alnum]" >/dev/null && - echo "$as_me: WARNING: invalid host type: $ac_option" >&2 + $as_echo "$as_me: WARNING: invalid host type: $ac_option" >&2 : ${build_alias=$ac_option} ${host_alias=$ac_option} ${target_alias=$ac_option} ;; @@ -1133,23 +1177,36 @@ if test -n "$ac_prev"; then ac_option=--`echo $ac_prev | sed 's/_/-/g'` - { echo "$as_me: error: missing argument to $ac_option" >&2 - { (exit 1); exit 1; }; } + as_fn_error "missing argument to $ac_option" +fi + +if test -n "$ac_unrecognized_opts"; then + case $enable_option_checking in + no) ;; + fatal) as_fn_error "unrecognized options: $ac_unrecognized_opts" ;; + *) $as_echo "$as_me: WARNING: unrecognized options: $ac_unrecognized_opts" >&2 ;; + esac fi -# Be sure to have absolute directory names. +# Check all directory arguments for consistency. for ac_var in exec_prefix prefix bindir sbindir libexecdir datarootdir \ datadir sysconfdir sharedstatedir localstatedir includedir \ oldincludedir docdir infodir htmldir dvidir pdfdir psdir \ libdir localedir mandir do eval ac_val=\$$ac_var + # Remove trailing slashes. + case $ac_val in + */ ) + ac_val=`expr "X$ac_val" : 'X\(.*[^/]\)' \| "X$ac_val" : 'X\(.*\)'` + eval $ac_var=\$ac_val;; + esac + # Be sure to have absolute directory names. case $ac_val in [\\/$]* | ?:[\\/]* ) continue;; NONE | '' ) case $ac_var in *prefix ) continue;; esac;; esac - { echo "$as_me: error: expected an absolute directory name for --$ac_var: $ac_val" >&2 - { (exit 1); exit 1; }; } + as_fn_error "expected an absolute directory name for --$ac_var: $ac_val" done # There might be people who depend on the old broken behavior: `$host' @@ -1163,7 +1220,7 @@ if test "x$host_alias" != x; then if test "x$build_alias" = x; then cross_compiling=maybe - echo "$as_me: WARNING: If you wanted to set the --build type, don't use --host. + $as_echo "$as_me: WARNING: If you wanted to set the --build type, don't use --host. If a cross compiler is detected then cross compile mode will be used." >&2 elif test "x$build_alias" != "x$host_alias"; then cross_compiling=yes @@ -1179,23 +1236,21 @@ ac_pwd=`pwd` && test -n "$ac_pwd" && ac_ls_di=`ls -di .` && ac_pwd_ls_di=`cd "$ac_pwd" && ls -di .` || - { echo "$as_me: error: Working directory cannot be determined" >&2 - { (exit 1); exit 1; }; } + as_fn_error "working directory cannot be determined" test "X$ac_ls_di" = "X$ac_pwd_ls_di" || - { echo "$as_me: error: pwd does not report name of working directory" >&2 - { (exit 1); exit 1; }; } + as_fn_error "pwd does not report name of working directory" # Find the source files, if location was not specified. if test -z "$srcdir"; then ac_srcdir_defaulted=yes # Try the directory containing this script, then the parent directory. - ac_confdir=`$as_dirname -- "$0" || -$as_expr X"$0" : 'X\(.*[^/]\)//*[^/][^/]*/*$' \| \ - X"$0" : 'X\(//\)[^/]' \| \ - X"$0" : 'X\(//\)$' \| \ - X"$0" : 'X\(/\)' \| . 2>/dev/null || -echo X"$0" | + ac_confdir=`$as_dirname -- "$as_myself" || +$as_expr X"$as_myself" : 'X\(.*[^/]\)//*[^/][^/]*/*$' \| \ + X"$as_myself" : 'X\(//\)[^/]' \| \ + X"$as_myself" : 'X\(//\)$' \| \ + X"$as_myself" : 'X\(/\)' \| . 2>/dev/null || +$as_echo X"$as_myself" | sed '/^X\(.*[^/]\)\/\/*[^/][^/]*\/*$/{ s//\1/ q @@ -1222,13 +1277,11 @@ fi if test ! -r "$srcdir/$ac_unique_file"; then test "$ac_srcdir_defaulted" = yes && srcdir="$ac_confdir or .." - { echo "$as_me: error: cannot find sources ($ac_unique_file) in $srcdir" >&2 - { (exit 1); exit 1; }; } + as_fn_error "cannot find sources ($ac_unique_file) in $srcdir" fi ac_msg="sources are in $srcdir, but \`cd $srcdir' does not work" ac_abs_confdir=`( - cd "$srcdir" && test -r "./$ac_unique_file" || { echo "$as_me: error: $ac_msg" >&2 - { (exit 1); exit 1; }; } + cd "$srcdir" && test -r "./$ac_unique_file" || as_fn_error "$ac_msg" pwd)` # When building in place, set srcdir=. if test "$ac_abs_confdir" = "$ac_pwd"; then @@ -1276,9 +1329,9 @@ Installation directories: --prefix=PREFIX install architecture-independent files in PREFIX - [$ac_default_prefix] + [$ac_default_prefix] --exec-prefix=EPREFIX install architecture-dependent files in EPREFIX - [PREFIX] + [PREFIX] By default, \`make install' will install all the files in \`$ac_default_prefix/bin', \`$ac_default_prefix/lib' etc. You can specify @@ -1288,25 +1341,25 @@ For better control, use the options below. Fine tuning of the installation directories: - --bindir=DIR user executables [EPREFIX/bin] - --sbindir=DIR system admin executables [EPREFIX/sbin] - --libexecdir=DIR program executables [EPREFIX/libexec] - --sysconfdir=DIR read-only single-machine data [PREFIX/etc] - --sharedstatedir=DIR modifiable architecture-independent data [PREFIX/com] - --localstatedir=DIR modifiable single-machine data [PREFIX/var] - --libdir=DIR object code libraries [EPREFIX/lib] - --includedir=DIR C header files [PREFIX/include] - --oldincludedir=DIR C header files for non-gcc [/usr/include] - --datarootdir=DIR read-only arch.-independent data root [PREFIX/share] - --datadir=DIR read-only architecture-independent data [DATAROOTDIR] - --infodir=DIR info documentation [DATAROOTDIR/info] - --localedir=DIR locale-dependent data [DATAROOTDIR/locale] - --mandir=DIR man documentation [DATAROOTDIR/man] - --docdir=DIR documentation root [DATAROOTDIR/doc/python] - --htmldir=DIR html documentation [DOCDIR] - --dvidir=DIR dvi documentation [DOCDIR] - --pdfdir=DIR pdf documentation [DOCDIR] - --psdir=DIR ps documentation [DOCDIR] + --bindir=DIR user executables [EPREFIX/bin] + --sbindir=DIR system admin executables [EPREFIX/sbin] + --libexecdir=DIR program executables [EPREFIX/libexec] + --sysconfdir=DIR read-only single-machine data [PREFIX/etc] + --sharedstatedir=DIR modifiable architecture-independent data [PREFIX/com] + --localstatedir=DIR modifiable single-machine data [PREFIX/var] + --libdir=DIR object code libraries [EPREFIX/lib] + --includedir=DIR C header files [PREFIX/include] + --oldincludedir=DIR C header files for non-gcc [/usr/include] + --datarootdir=DIR read-only arch.-independent data root [PREFIX/share] + --datadir=DIR read-only architecture-independent data [DATAROOTDIR] + --infodir=DIR info documentation [DATAROOTDIR/info] + --localedir=DIR locale-dependent data [DATAROOTDIR/locale] + --mandir=DIR man documentation [DATAROOTDIR/man] + --docdir=DIR documentation root [DATAROOTDIR/doc/python] + --htmldir=DIR html documentation [DOCDIR] + --dvidir=DIR dvi documentation [DOCDIR] + --pdfdir=DIR pdf documentation [DOCDIR] + --psdir=DIR ps documentation [DOCDIR] _ACEOF cat <<\_ACEOF @@ -1320,6 +1373,7 @@ cat <<\_ACEOF Optional Features: + --disable-option-checking ignore unrecognized --enable/--with options --disable-FEATURE do not include FEATURE (same as --enable-FEATURE=no) --enable-FEATURE[=ARG] include FEATURE [ARG=yes] --enable-universalsdk[=SDKDIR] @@ -1332,7 +1386,7 @@ --enable-ipv6 Enable ipv6 (with ipv4) support --disable-ipv6 Disable ipv6 support --enable-big-digits[=BITS] - use big digits for Python longs [BITS=30] + use big digits for Python longs [[BITS=30]] --enable-unicode[=ucs[24]] Enable Unicode strings (default is yes) @@ -1381,7 +1435,7 @@ LDFLAGS linker flags, e.g. -L if you have libraries in a nonstandard directory LIBS libraries to pass to the linker, e.g. -l - CPPFLAGS C/C++/Objective C preprocessor flags, e.g. -I if + CPPFLAGS (Objective) C/C++ preprocessor flags, e.g. -I if you have headers in a nonstandard directory CPP C preprocessor @@ -1396,15 +1450,17 @@ if test "$ac_init_help" = "recursive"; then # If there are subdirs, report their specific --help. for ac_dir in : $ac_subdirs_all; do test "x$ac_dir" = x: && continue - test -d "$ac_dir" || continue + test -d "$ac_dir" || + { cd "$srcdir" && ac_pwd=`pwd` && srcdir=. && test -d "$ac_dir"; } || + continue ac_builddir=. case "$ac_dir" in .) ac_dir_suffix= ac_top_builddir_sub=. ac_top_build_prefix= ;; *) - ac_dir_suffix=/`echo "$ac_dir" | sed 's,^\.[\\/],,'` + ac_dir_suffix=/`$as_echo "$ac_dir" | sed 's|^\.[\\/]||'` # A ".." for each directory in $ac_dir_suffix. - ac_top_builddir_sub=`echo "$ac_dir_suffix" | sed 's,/[^\\/]*,/..,g;s,/,,'` + ac_top_builddir_sub=`$as_echo "$ac_dir_suffix" | sed 's|/[^\\/]*|/..|g;s|/||'` case $ac_top_builddir_sub in "") ac_top_builddir_sub=. ac_top_build_prefix= ;; *) ac_top_build_prefix=$ac_top_builddir_sub/ ;; @@ -1440,7 +1496,7 @@ echo && $SHELL "$ac_srcdir/configure" --help=recursive else - echo "$as_me: WARNING: no configuration information is in $ac_dir" >&2 + $as_echo "$as_me: WARNING: no configuration information is in $ac_dir" >&2 fi || ac_status=$? cd "$ac_pwd" || { ac_status=$?; break; } done @@ -1450,5891 +1506,5101 @@ if $ac_init_version; then cat <<\_ACEOF python configure 2.7 -generated by GNU Autoconf 2.61 +generated by GNU Autoconf 2.65 -Copyright (C) 1992, 1993, 1994, 1995, 1996, 1998, 1999, 2000, 2001, -2002, 2003, 2004, 2005, 2006 Free Software Foundation, Inc. +Copyright (C) 2009 Free Software Foundation, Inc. This configure script is free software; the Free Software Foundation gives unlimited permission to copy, distribute and modify it. _ACEOF exit fi -cat >config.log <<_ACEOF -This file contains any messages produced by compilers while -running configure, to aid debugging if configure makes a mistake. -It was created by python $as_me 2.7, which was -generated by GNU Autoconf 2.61. Invocation command line was +## ------------------------ ## +## Autoconf initialization. ## +## ------------------------ ## + +# ac_fn_c_try_compile LINENO +# -------------------------- +# Try to compile conftest.$ac_ext, and return whether this succeeded. +ac_fn_c_try_compile () +{ + as_lineno=${as_lineno-"$1"} as_lineno_stack=as_lineno_stack=$as_lineno_stack + rm -f conftest.$ac_objext + if { { ac_try="$ac_compile" +case "(($ac_try" in + *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; + *) ac_try_echo=$ac_try;; +esac +eval ac_try_echo="\"\$as_me:${as_lineno-$LINENO}: $ac_try_echo\"" +$as_echo "$ac_try_echo"; } >&5 + (eval "$ac_compile") 2>conftest.err + ac_status=$? + if test -s conftest.err; then + grep -v '^ *+' conftest.err >conftest.er1 + cat conftest.er1 >&5 + mv -f conftest.er1 conftest.err + fi + $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 + test $ac_status = 0; } && { + test -z "$ac_c_werror_flag" || + test ! -s conftest.err + } && test -s conftest.$ac_objext; then : + ac_retval=0 +else + $as_echo "$as_me: failed program was:" >&5 +sed 's/^/| /' conftest.$ac_ext >&5 - $ $0 $@ + ac_retval=1 +fi + eval $as_lineno_stack; test "x$as_lineno_stack" = x && { as_lineno=; unset as_lineno;} + as_fn_set_status $ac_retval -_ACEOF -exec 5>>config.log +} # ac_fn_c_try_compile + +# ac_fn_c_try_cpp LINENO +# ---------------------- +# Try to preprocess conftest.$ac_ext, and return whether this succeeded. +ac_fn_c_try_cpp () { -cat <<_ASUNAME -## --------- ## -## Platform. ## -## --------- ## + as_lineno=${as_lineno-"$1"} as_lineno_stack=as_lineno_stack=$as_lineno_stack + if { { ac_try="$ac_cpp conftest.$ac_ext" +case "(($ac_try" in + *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; + *) ac_try_echo=$ac_try;; +esac +eval ac_try_echo="\"\$as_me:${as_lineno-$LINENO}: $ac_try_echo\"" +$as_echo "$ac_try_echo"; } >&5 + (eval "$ac_cpp conftest.$ac_ext") 2>conftest.err + ac_status=$? + if test -s conftest.err; then + grep -v '^ *+' conftest.err >conftest.er1 + cat conftest.er1 >&5 + mv -f conftest.er1 conftest.err + fi + $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 + test $ac_status = 0; } >/dev/null && { + test -z "$ac_c_preproc_warn_flag$ac_c_werror_flag" || + test ! -s conftest.err + }; then : + ac_retval=0 +else + $as_echo "$as_me: failed program was:" >&5 +sed 's/^/| /' conftest.$ac_ext >&5 -hostname = `(hostname || uname -n) 2>/dev/null | sed 1q` -uname -m = `(uname -m) 2>/dev/null || echo unknown` -uname -r = `(uname -r) 2>/dev/null || echo unknown` -uname -s = `(uname -s) 2>/dev/null || echo unknown` -uname -v = `(uname -v) 2>/dev/null || echo unknown` + ac_retval=1 +fi + eval $as_lineno_stack; test "x$as_lineno_stack" = x && { as_lineno=; unset as_lineno;} + as_fn_set_status $ac_retval -/usr/bin/uname -p = `(/usr/bin/uname -p) 2>/dev/null || echo unknown` -/bin/uname -X = `(/bin/uname -X) 2>/dev/null || echo unknown` +} # ac_fn_c_try_cpp -/bin/arch = `(/bin/arch) 2>/dev/null || echo unknown` -/usr/bin/arch -k = `(/usr/bin/arch -k) 2>/dev/null || echo unknown` -/usr/convex/getsysinfo = `(/usr/convex/getsysinfo) 2>/dev/null || echo unknown` -/usr/bin/hostinfo = `(/usr/bin/hostinfo) 2>/dev/null || echo unknown` -/bin/machine = `(/bin/machine) 2>/dev/null || echo unknown` -/usr/bin/oslevel = `(/usr/bin/oslevel) 2>/dev/null || echo unknown` -/bin/universe = `(/bin/universe) 2>/dev/null || echo unknown` +# ac_fn_c_check_header_mongrel LINENO HEADER VAR INCLUDES +# ------------------------------------------------------- +# Tests whether HEADER exists, giving a warning if it cannot be compiled using +# the include files in INCLUDES and setting the cache variable VAR +# accordingly. +ac_fn_c_check_header_mongrel () +{ + as_lineno=${as_lineno-"$1"} as_lineno_stack=as_lineno_stack=$as_lineno_stack + if { as_var=$3; eval "test \"\${$as_var+set}\" = set"; }; then : + { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $2" >&5 +$as_echo_n "checking for $2... " >&6; } +if { as_var=$3; eval "test \"\${$as_var+set}\" = set"; }; then : + $as_echo_n "(cached) " >&6 +fi +eval ac_res=\$$3 + { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_res" >&5 +$as_echo "$ac_res" >&6; } +else + # Is the header compilable? +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking $2 usability" >&5 +$as_echo_n "checking $2 usability... " >&6; } +cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ +$4 +#include <$2> +_ACEOF +if ac_fn_c_try_compile "$LINENO"; then : + ac_header_compiler=yes +else + ac_header_compiler=no +fi +rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_header_compiler" >&5 +$as_echo "$ac_header_compiler" >&6; } -_ASUNAME +# Is the header present? +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking $2 presence" >&5 +$as_echo_n "checking $2 presence... " >&6; } +cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ +#include <$2> +_ACEOF +if ac_fn_c_try_cpp "$LINENO"; then : + ac_header_preproc=yes +else + ac_header_preproc=no +fi +rm -f conftest.err conftest.$ac_ext +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_header_preproc" >&5 +$as_echo "$ac_header_preproc" >&6; } -as_save_IFS=$IFS; IFS=$PATH_SEPARATOR -for as_dir in $PATH -do - IFS=$as_save_IFS - test -z "$as_dir" && as_dir=. - echo "PATH: $as_dir" -done -IFS=$as_save_IFS +# So? What about this header? +case $ac_header_compiler:$ac_header_preproc:$ac_c_preproc_warn_flag in #(( + yes:no: ) + { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: $2: accepted by the compiler, rejected by the preprocessor!" >&5 +$as_echo "$as_me: WARNING: $2: accepted by the compiler, rejected by the preprocessor!" >&2;} + { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: $2: proceeding with the compiler's result" >&5 +$as_echo "$as_me: WARNING: $2: proceeding with the compiler's result" >&2;} + ;; + no:yes:* ) + { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: $2: present but cannot be compiled" >&5 +$as_echo "$as_me: WARNING: $2: present but cannot be compiled" >&2;} + { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: $2: check for missing prerequisite headers?" >&5 +$as_echo "$as_me: WARNING: $2: check for missing prerequisite headers?" >&2;} + { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: $2: see the Autoconf documentation" >&5 +$as_echo "$as_me: WARNING: $2: see the Autoconf documentation" >&2;} + { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: $2: section \"Present But Cannot Be Compiled\"" >&5 +$as_echo "$as_me: WARNING: $2: section \"Present But Cannot Be Compiled\"" >&2;} + { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: $2: proceeding with the compiler's result" >&5 +$as_echo "$as_me: WARNING: $2: proceeding with the compiler's result" >&2;} +( cat <<\_ASBOX +## -------------------------------------- ## +## Report this to http://bugs.python.org/ ## +## -------------------------------------- ## +_ASBOX + ) | sed "s/^/$as_me: WARNING: /" >&2 + ;; +esac + { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $2" >&5 +$as_echo_n "checking for $2... " >&6; } +if { as_var=$3; eval "test \"\${$as_var+set}\" = set"; }; then : + $as_echo_n "(cached) " >&6 +else + eval "$3=\$ac_header_compiler" +fi +eval ac_res=\$$3 + { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_res" >&5 +$as_echo "$ac_res" >&6; } +fi + eval $as_lineno_stack; test "x$as_lineno_stack" = x && { as_lineno=; unset as_lineno;} -} >&5 +} # ac_fn_c_check_header_mongrel -cat >&5 <<_ACEOF +# ac_fn_c_try_run LINENO +# ---------------------- +# Try to link conftest.$ac_ext, and return whether this succeeded. Assumes +# that executables *can* be run. +ac_fn_c_try_run () +{ + as_lineno=${as_lineno-"$1"} as_lineno_stack=as_lineno_stack=$as_lineno_stack + if { { ac_try="$ac_link" +case "(($ac_try" in + *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; + *) ac_try_echo=$ac_try;; +esac +eval ac_try_echo="\"\$as_me:${as_lineno-$LINENO}: $ac_try_echo\"" +$as_echo "$ac_try_echo"; } >&5 + (eval "$ac_link") 2>&5 + ac_status=$? + $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 + test $ac_status = 0; } && { ac_try='./conftest$ac_exeext' + { { case "(($ac_try" in + *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; + *) ac_try_echo=$ac_try;; +esac +eval ac_try_echo="\"\$as_me:${as_lineno-$LINENO}: $ac_try_echo\"" +$as_echo "$ac_try_echo"; } >&5 + (eval "$ac_try") 2>&5 + ac_status=$? + $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 + test $ac_status = 0; }; }; then : + ac_retval=0 +else + $as_echo "$as_me: program exited with status $ac_status" >&5 + $as_echo "$as_me: failed program was:" >&5 +sed 's/^/| /' conftest.$ac_ext >&5 + ac_retval=$ac_status +fi + rm -rf conftest.dSYM conftest_ipa8_conftest.oo + eval $as_lineno_stack; test "x$as_lineno_stack" = x && { as_lineno=; unset as_lineno;} + as_fn_set_status $ac_retval -## ----------- ## -## Core tests. ## -## ----------- ## +} # ac_fn_c_try_run +# ac_fn_c_check_header_compile LINENO HEADER VAR INCLUDES +# ------------------------------------------------------- +# Tests whether HEADER exists and can be compiled using the include files in +# INCLUDES, setting the cache variable VAR accordingly. +ac_fn_c_check_header_compile () +{ + as_lineno=${as_lineno-"$1"} as_lineno_stack=as_lineno_stack=$as_lineno_stack + { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $2" >&5 +$as_echo_n "checking for $2... " >&6; } +if { as_var=$3; eval "test \"\${$as_var+set}\" = set"; }; then : + $as_echo_n "(cached) " >&6 +else + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ +$4 +#include <$2> _ACEOF +if ac_fn_c_try_compile "$LINENO"; then : + eval "$3=yes" +else + eval "$3=no" +fi +rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext +fi +eval ac_res=\$$3 + { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_res" >&5 +$as_echo "$ac_res" >&6; } + eval $as_lineno_stack; test "x$as_lineno_stack" = x && { as_lineno=; unset as_lineno;} +} # ac_fn_c_check_header_compile -# Keep a trace of the command line. -# Strip out --no-create and --no-recursion so they do not pile up. -# Strip out --silent because we don't want to record it for future runs. -# Also quote any args containing shell meta-characters. -# Make two passes to allow for proper duplicate-argument suppression. -ac_configure_args= -ac_configure_args0= -ac_configure_args1= -ac_must_keep_next=false -for ac_pass in 1 2 -do - for ac_arg - do - case $ac_arg in - -no-create | --no-c* | -n | -no-recursion | --no-r*) continue ;; - -q | -quiet | --quiet | --quie | --qui | --qu | --q \ - | -silent | --silent | --silen | --sile | --sil) - continue ;; - *\'*) - ac_arg=`echo "$ac_arg" | sed "s/'/'\\\\\\\\''/g"` ;; - esac - case $ac_pass in - 1) ac_configure_args0="$ac_configure_args0 '$ac_arg'" ;; - 2) - ac_configure_args1="$ac_configure_args1 '$ac_arg'" - if test $ac_must_keep_next = true; then - ac_must_keep_next=false # Got value, back to normal. - else - case $ac_arg in - *=* | --config-cache | -C | -disable-* | --disable-* \ - | -enable-* | --enable-* | -gas | --g* | -nfp | --nf* \ - | -q | -quiet | --q* | -silent | --sil* | -v | -verb* \ - | -with-* | --with-* | -without-* | --without-* | --x) - case "$ac_configure_args0 " in - "$ac_configure_args1"*" '$ac_arg' "* ) continue ;; - esac - ;; - -* ) ac_must_keep_next=true ;; - esac - fi - ac_configure_args="$ac_configure_args '$ac_arg'" - ;; - esac - done -done -$as_unset ac_configure_args0 || test "${ac_configure_args0+set}" != set || { ac_configure_args0=; export ac_configure_args0; } -$as_unset ac_configure_args1 || test "${ac_configure_args1+set}" != set || { ac_configure_args1=; export ac_configure_args1; } - -# When interrupted or exit'd, cleanup temporary files, and complete -# config.log. We remove comments because anyway the quotes in there -# would cause problems or look ugly. -# WARNING: Use '\'' to represent an apostrophe within the trap. -# WARNING: Do not start the trap code with a newline, due to a FreeBSD 4.0 bug. -trap 'exit_status=$? - # Save into config.log some information that might help in debugging. - { - echo +# ac_fn_c_try_link LINENO +# ----------------------- +# Try to link conftest.$ac_ext, and return whether this succeeded. +ac_fn_c_try_link () +{ + as_lineno=${as_lineno-"$1"} as_lineno_stack=as_lineno_stack=$as_lineno_stack + rm -f conftest.$ac_objext conftest$ac_exeext + if { { ac_try="$ac_link" +case "(($ac_try" in + *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; + *) ac_try_echo=$ac_try;; +esac +eval ac_try_echo="\"\$as_me:${as_lineno-$LINENO}: $ac_try_echo\"" +$as_echo "$ac_try_echo"; } >&5 + (eval "$ac_link") 2>conftest.err + ac_status=$? + if test -s conftest.err; then + grep -v '^ *+' conftest.err >conftest.er1 + cat conftest.er1 >&5 + mv -f conftest.er1 conftest.err + fi + $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 + test $ac_status = 0; } && { + test -z "$ac_c_werror_flag" || + test ! -s conftest.err + } && test -s conftest$ac_exeext && { + test "$cross_compiling" = yes || + $as_test_x conftest$ac_exeext + }; then : + ac_retval=0 +else + $as_echo "$as_me: failed program was:" >&5 +sed 's/^/| /' conftest.$ac_ext >&5 - cat <<\_ASBOX -## ---------------- ## -## Cache variables. ## -## ---------------- ## -_ASBOX - echo - # The following way of writing the cache mishandles newlines in values, -( - for ac_var in `(set) 2>&1 | sed -n '\''s/^\([a-zA-Z_][a-zA-Z0-9_]*\)=.*/\1/p'\''`; do - eval ac_val=\$$ac_var - case $ac_val in #( - *${as_nl}*) - case $ac_var in #( - *_cv_*) { echo "$as_me:$LINENO: WARNING: Cache variable $ac_var contains a newline." >&5 -echo "$as_me: WARNING: Cache variable $ac_var contains a newline." >&2;} ;; - esac - case $ac_var in #( - _ | IFS | as_nl) ;; #( - *) $as_unset $ac_var ;; - esac ;; - esac - done - (set) 2>&1 | - case $as_nl`(ac_space='\'' '\''; set) 2>&1` in #( - *${as_nl}ac_space=\ *) - sed -n \ - "s/'\''/'\''\\\\'\'''\''/g; - s/^\\([_$as_cr_alnum]*_cv_[_$as_cr_alnum]*\\)=\\(.*\\)/\\1='\''\\2'\''/p" - ;; #( - *) - sed -n "/^[_$as_cr_alnum]*_cv_[_$as_cr_alnum]*=/p" - ;; - esac | - sort -) - echo + ac_retval=1 +fi + # Delete the IPA/IPO (Inter Procedural Analysis/Optimization) information + # created by the PGI compiler (conftest_ipa8_conftest.oo), as it would + # interfere with the next link command; also delete a directory that is + # left behind by Apple's compiler. We do this before executing the actions. + rm -rf conftest.dSYM conftest_ipa8_conftest.oo + eval $as_lineno_stack; test "x$as_lineno_stack" = x && { as_lineno=; unset as_lineno;} + as_fn_set_status $ac_retval - cat <<\_ASBOX -## ----------------- ## -## Output variables. ## -## ----------------- ## -_ASBOX - echo - for ac_var in $ac_subst_vars - do - eval ac_val=\$$ac_var - case $ac_val in - *\'\''*) ac_val=`echo "$ac_val" | sed "s/'\''/'\''\\\\\\\\'\'''\''/g"`;; - esac - echo "$ac_var='\''$ac_val'\''" - done | sort - echo +} # ac_fn_c_try_link - if test -n "$ac_subst_files"; then - cat <<\_ASBOX -## ------------------- ## -## File substitutions. ## -## ------------------- ## -_ASBOX - echo - for ac_var in $ac_subst_files - do - eval ac_val=\$$ac_var - case $ac_val in - *\'\''*) ac_val=`echo "$ac_val" | sed "s/'\''/'\''\\\\\\\\'\'''\''/g"`;; - esac - echo "$ac_var='\''$ac_val'\''" - done | sort - echo - fi +# ac_fn_c_check_type LINENO TYPE VAR INCLUDES +# ------------------------------------------- +# Tests whether TYPE exists after having included INCLUDES, setting cache +# variable VAR accordingly. +ac_fn_c_check_type () +{ + as_lineno=${as_lineno-"$1"} as_lineno_stack=as_lineno_stack=$as_lineno_stack + { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $2" >&5 +$as_echo_n "checking for $2... " >&6; } +if { as_var=$3; eval "test \"\${$as_var+set}\" = set"; }; then : + $as_echo_n "(cached) " >&6 +else + eval "$3=no" + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ +$4 +int +main () +{ +if (sizeof ($2)) + return 0; + ; + return 0; +} +_ACEOF +if ac_fn_c_try_compile "$LINENO"; then : + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ +$4 +int +main () +{ +if (sizeof (($2))) + return 0; + ; + return 0; +} +_ACEOF +if ac_fn_c_try_compile "$LINENO"; then : - if test -s confdefs.h; then - cat <<\_ASBOX -## ----------- ## -## confdefs.h. ## -## ----------- ## -_ASBOX - echo - cat confdefs.h - echo - fi - test "$ac_signal" != 0 && - echo "$as_me: caught signal $ac_signal" - echo "$as_me: exit $exit_status" - } >&5 - rm -f core *.core core.conftest.* && - rm -f -r conftest* confdefs* conf$$* $ac_clean_files && - exit $exit_status -' 0 -for ac_signal in 1 2 13 15; do - trap 'ac_signal='$ac_signal'; { (exit 1); exit 1; }' $ac_signal -done -ac_signal=0 +else + eval "$3=yes" +fi +rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext +fi +rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext +fi +eval ac_res=\$$3 + { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_res" >&5 +$as_echo "$ac_res" >&6; } + eval $as_lineno_stack; test "x$as_lineno_stack" = x && { as_lineno=; unset as_lineno;} -# confdefs.h avoids OS command line length limits that DEFS can exceed. -rm -f -r conftest* confdefs.h +} # ac_fn_c_check_type -# Predefined preprocessor variables. +# ac_fn_c_find_uintX_t LINENO BITS VAR +# ------------------------------------ +# Finds an unsigned integer type with width BITS, setting cache variable VAR +# accordingly. +ac_fn_c_find_uintX_t () +{ + as_lineno=${as_lineno-"$1"} as_lineno_stack=as_lineno_stack=$as_lineno_stack + { $as_echo "$as_me:${as_lineno-$LINENO}: checking for uint$2_t" >&5 +$as_echo_n "checking for uint$2_t... " >&6; } +if { as_var=$3; eval "test \"\${$as_var+set}\" = set"; }; then : + $as_echo_n "(cached) " >&6 +else + eval "$3=no" + # Order is important - never check a type that is potentially smaller + # than half of the expected target width. + for ac_type in uint$2_t 'unsigned int' 'unsigned long int' \ + 'unsigned long long int' 'unsigned short int' 'unsigned char'; do + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ +$ac_includes_default +int +main () +{ +static int test_array [1 - 2 * !((($ac_type) -1 >> ($2 / 2 - 1)) >> ($2 / 2 - 1) == 3)]; +test_array [0] = 0 -cat >>confdefs.h <<_ACEOF -#define PACKAGE_NAME "$PACKAGE_NAME" + ; + return 0; +} _ACEOF +if ac_fn_c_try_compile "$LINENO"; then : + case $ac_type in #( + uint$2_t) : + eval "$3=yes" ;; #( + *) : + eval "$3=\$ac_type" ;; +esac +fi +rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext + eval as_val=\$$3 + if test "x$as_val" = x""no; then : +else + break +fi + done +fi +eval ac_res=\$$3 + { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_res" >&5 +$as_echo "$ac_res" >&6; } + eval $as_lineno_stack; test "x$as_lineno_stack" = x && { as_lineno=; unset as_lineno;} + +} # ac_fn_c_find_uintX_t + +# ac_fn_c_find_intX_t LINENO BITS VAR +# ----------------------------------- +# Finds a signed integer type with width BITS, setting cache variable VAR +# accordingly. +ac_fn_c_find_intX_t () +{ + as_lineno=${as_lineno-"$1"} as_lineno_stack=as_lineno_stack=$as_lineno_stack + { $as_echo "$as_me:${as_lineno-$LINENO}: checking for int$2_t" >&5 +$as_echo_n "checking for int$2_t... " >&6; } +if { as_var=$3; eval "test \"\${$as_var+set}\" = set"; }; then : + $as_echo_n "(cached) " >&6 +else + eval "$3=no" + # Order is important - never check a type that is potentially smaller + # than half of the expected target width. + for ac_type in int$2_t 'int' 'long int' \ + 'long long int' 'short int' 'signed char'; do + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ +$ac_includes_default + enum { N = $2 / 2 - 1 }; +int +main () +{ +static int test_array [1 - 2 * !(0 < ($ac_type) ((((($ac_type) 1 << N) << N) - 1) * 2 + 1))]; +test_array [0] = 0 -cat >>confdefs.h <<_ACEOF -#define PACKAGE_TARNAME "$PACKAGE_TARNAME" + ; + return 0; +} _ACEOF +if ac_fn_c_try_compile "$LINENO"; then : + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ +$ac_includes_default + enum { N = $2 / 2 - 1 }; +int +main () +{ +static int test_array [1 - 2 * !(($ac_type) ((((($ac_type) 1 << N) << N) - 1) * 2 + 1) + < ($ac_type) ((((($ac_type) 1 << N) << N) - 1) * 2 + 2))]; +test_array [0] = 0 - -cat >>confdefs.h <<_ACEOF -#define PACKAGE_VERSION "$PACKAGE_VERSION" + ; + return 0; +} _ACEOF +if ac_fn_c_try_compile "$LINENO"; then : +else + case $ac_type in #( + int$2_t) : + eval "$3=yes" ;; #( + *) : + eval "$3=\$ac_type" ;; +esac +fi +rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext +fi +rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext + eval as_val=\$$3 + if test "x$as_val" = x""no; then : -cat >>confdefs.h <<_ACEOF -#define PACKAGE_STRING "$PACKAGE_STRING" +else + break +fi + done +fi +eval ac_res=\$$3 + { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_res" >&5 +$as_echo "$ac_res" >&6; } + eval $as_lineno_stack; test "x$as_lineno_stack" = x && { as_lineno=; unset as_lineno;} + +} # ac_fn_c_find_intX_t + +# ac_fn_c_compute_int LINENO EXPR VAR INCLUDES +# -------------------------------------------- +# Tries to find the compile-time value of EXPR in a program that includes +# INCLUDES, setting VAR accordingly. Returns whether the value could be +# computed +ac_fn_c_compute_int () +{ + as_lineno=${as_lineno-"$1"} as_lineno_stack=as_lineno_stack=$as_lineno_stack + if test "$cross_compiling" = yes; then + # Depending upon the size, compute the lo and hi bounds. +cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ +$4 +int +main () +{ +static int test_array [1 - 2 * !(($2) >= 0)]; +test_array [0] = 0 + + ; + return 0; +} _ACEOF +if ac_fn_c_try_compile "$LINENO"; then : + ac_lo=0 ac_mid=0 + while :; do + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ +$4 +int +main () +{ +static int test_array [1 - 2 * !(($2) <= $ac_mid)]; +test_array [0] = 0 + ; + return 0; +} +_ACEOF +if ac_fn_c_try_compile "$LINENO"; then : + ac_hi=$ac_mid; break +else + as_fn_arith $ac_mid + 1 && ac_lo=$as_val + if test $ac_lo -le $ac_mid; then + ac_lo= ac_hi= + break + fi + as_fn_arith 2 '*' $ac_mid + 1 && ac_mid=$as_val +fi +rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext + done +else + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ +$4 +int +main () +{ +static int test_array [1 - 2 * !(($2) < 0)]; +test_array [0] = 0 -cat >>confdefs.h <<_ACEOF -#define PACKAGE_BUGREPORT "$PACKAGE_BUGREPORT" + ; + return 0; +} _ACEOF +if ac_fn_c_try_compile "$LINENO"; then : + ac_hi=-1 ac_mid=-1 + while :; do + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ +$4 +int +main () +{ +static int test_array [1 - 2 * !(($2) >= $ac_mid)]; +test_array [0] = 0 + ; + return 0; +} +_ACEOF +if ac_fn_c_try_compile "$LINENO"; then : + ac_lo=$ac_mid; break +else + as_fn_arith '(' $ac_mid ')' - 1 && ac_hi=$as_val + if test $ac_mid -le $ac_hi; then + ac_lo= ac_hi= + break + fi + as_fn_arith 2 '*' $ac_mid && ac_mid=$as_val +fi +rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext + done +else + ac_lo= ac_hi= +fi +rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext +fi +rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext +# Binary search between lo and hi bounds. +while test "x$ac_lo" != "x$ac_hi"; do + as_fn_arith '(' $ac_hi - $ac_lo ')' / 2 + $ac_lo && ac_mid=$as_val + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ +$4 +int +main () +{ +static int test_array [1 - 2 * !(($2) <= $ac_mid)]; +test_array [0] = 0 -# Let the site file select an alternate cache file if it wants to. -# Prefer explicitly selected file to automatically selected ones. -if test -n "$CONFIG_SITE"; then - set x "$CONFIG_SITE" -elif test "x$prefix" != xNONE; then - set x "$prefix/share/config.site" "$prefix/etc/config.site" + ; + return 0; +} +_ACEOF +if ac_fn_c_try_compile "$LINENO"; then : + ac_hi=$ac_mid else - set x "$ac_default_prefix/share/config.site" \ - "$ac_default_prefix/etc/config.site" + as_fn_arith '(' $ac_mid ')' + 1 && ac_lo=$as_val fi -shift -for ac_site_file -do - if test -r "$ac_site_file"; then - { echo "$as_me:$LINENO: loading site script $ac_site_file" >&5 -echo "$as_me: loading site script $ac_site_file" >&6;} - sed 's/^/| /' "$ac_site_file" >&5 - . "$ac_site_file" - fi +rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext done +case $ac_lo in #(( +?*) eval "$3=\$ac_lo"; ac_retval=0 ;; +'') ac_retval=1 ;; +esac + else + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ +$4 +static long int longval () { return $2; } +static unsigned long int ulongval () { return $2; } +#include +#include +int +main () +{ -if test -r "$cache_file"; then - # Some versions of bash will fail to source /dev/null (special - # files actually), so we avoid doing that. - if test -f "$cache_file"; then - { echo "$as_me:$LINENO: loading cache $cache_file" >&5 -echo "$as_me: loading cache $cache_file" >&6;} - case $cache_file in - [\\/]* | ?:[\\/]* ) . "$cache_file";; - *) . "./$cache_file";; - esac - fi + FILE *f = fopen ("conftest.val", "w"); + if (! f) + return 1; + if (($2) < 0) + { + long int i = longval (); + if (i != ($2)) + return 1; + fprintf (f, "%ld", i); + } + else + { + unsigned long int i = ulongval (); + if (i != ($2)) + return 1; + fprintf (f, "%lu", i); + } + /* Do not output a trailing newline, as this causes \r\n confusion + on some platforms. */ + return ferror (f) || fclose (f) != 0; + + ; + return 0; +} +_ACEOF +if ac_fn_c_try_run "$LINENO"; then : + echo >>conftest.val; read $3 &5 -echo "$as_me: creating cache $cache_file" >&6;} - >$cache_file + ac_retval=1 fi +rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext \ + conftest.$ac_objext conftest.beam conftest.$ac_ext +rm -f conftest.val -# Check that the precious variables saved in the cache have kept the same -# value. -ac_cache_corrupted=false -for ac_var in $ac_precious_vars; do - eval ac_old_set=\$ac_cv_env_${ac_var}_set - eval ac_new_set=\$ac_env_${ac_var}_set - eval ac_old_val=\$ac_cv_env_${ac_var}_value - eval ac_new_val=\$ac_env_${ac_var}_value - case $ac_old_set,$ac_new_set in - set,) - { echo "$as_me:$LINENO: error: \`$ac_var' was set to \`$ac_old_val' in the previous run" >&5 -echo "$as_me: error: \`$ac_var' was set to \`$ac_old_val' in the previous run" >&2;} - ac_cache_corrupted=: ;; - ,set) - { echo "$as_me:$LINENO: error: \`$ac_var' was not set in the previous run" >&5 -echo "$as_me: error: \`$ac_var' was not set in the previous run" >&2;} - ac_cache_corrupted=: ;; - ,);; - *) - if test "x$ac_old_val" != "x$ac_new_val"; then - { echo "$as_me:$LINENO: error: \`$ac_var' has changed since the previous run:" >&5 -echo "$as_me: error: \`$ac_var' has changed since the previous run:" >&2;} - { echo "$as_me:$LINENO: former value: $ac_old_val" >&5 -echo "$as_me: former value: $ac_old_val" >&2;} - { echo "$as_me:$LINENO: current value: $ac_new_val" >&5 -echo "$as_me: current value: $ac_new_val" >&2;} - ac_cache_corrupted=: - fi;; - esac - # Pass precious variables to config.status. - if test "$ac_new_set" = set; then - case $ac_new_val in - *\'*) ac_arg=$ac_var=`echo "$ac_new_val" | sed "s/'/'\\\\\\\\''/g"` ;; - *) ac_arg=$ac_var=$ac_new_val ;; - esac - case " $ac_configure_args " in - *" '$ac_arg' "*) ;; # Avoid dups. Use of quotes ensures accuracy. - *) ac_configure_args="$ac_configure_args '$ac_arg'" ;; - esac fi -done -if $ac_cache_corrupted; then - { echo "$as_me:$LINENO: error: changes in the environment can compromise the build" >&5 -echo "$as_me: error: changes in the environment can compromise the build" >&2;} - { { echo "$as_me:$LINENO: error: run \`make distclean' and/or \`rm $cache_file' and start over" >&5 -echo "$as_me: error: run \`make distclean' and/or \`rm $cache_file' and start over" >&2;} - { (exit 1); exit 1; }; } -fi - - - - - - - - - - - - - - - - - - - - - - - - - -ac_ext=c -ac_cpp='$CPP $CPPFLAGS' -ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5' -ac_link='$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5' -ac_compiler_gnu=$ac_cv_c_compiler_gnu - - - -ac_config_headers="$ac_config_headers pyconfig.h" - - - -if test "$prefix" != "/"; then - prefix=`echo "$prefix" | sed -e 's/\/$//g'` -fi - - - - - - -# We don't use PACKAGE_ variables, and they cause conflicts -# with other autoconf-based packages that include Python.h -grep -v 'define PACKAGE_' confdefs.h.new -rm confdefs.h -mv confdefs.h.new confdefs.h - - -VERSION=2.7 + eval $as_lineno_stack; test "x$as_lineno_stack" = x && { as_lineno=; unset as_lineno;} + as_fn_set_status $ac_retval +} # ac_fn_c_compute_int -SOVERSION=1.0 +# ac_fn_c_check_func LINENO FUNC VAR +# ---------------------------------- +# Tests whether FUNC exists, setting the cache variable VAR accordingly +ac_fn_c_check_func () +{ + as_lineno=${as_lineno-"$1"} as_lineno_stack=as_lineno_stack=$as_lineno_stack + { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $2" >&5 +$as_echo_n "checking for $2... " >&6; } +if { as_var=$3; eval "test \"\${$as_var+set}\" = set"; }; then : + $as_echo_n "(cached) " >&6 +else + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ +/* Define $2 to an innocuous variant, in case declares $2. + For example, HP-UX 11i declares gettimeofday. */ +#define $2 innocuous_$2 -# The later defininition of _XOPEN_SOURCE disables certain features -# on Linux, so we need _GNU_SOURCE to re-enable them (makedev, tm_zone). +/* System header to define __stub macros and hopefully few prototypes, + which can conflict with char $2 (); below. + Prefer to if __STDC__ is defined, since + exists even on freestanding compilers. */ -cat >>confdefs.h <<\_ACEOF -#define _GNU_SOURCE 1 -_ACEOF +#ifdef __STDC__ +# include +#else +# include +#endif +#undef $2 -# The later defininition of _XOPEN_SOURCE and _POSIX_C_SOURCE disables -# certain features on NetBSD, so we need _NETBSD_SOURCE to re-enable -# them. +/* Override any GCC internal prototype to avoid an error. + Use char because int might match the return type of a GCC + builtin and then its argument prototype would still apply. */ +#ifdef __cplusplus +extern "C" +#endif +char $2 (); +/* The GNU C library defines this for functions which it implements + to always fail with ENOSYS. Some functions are actually named + something starting with __ and the normal name is an alias. */ +#if defined __stub_$2 || defined __stub___$2 +choke me +#endif -cat >>confdefs.h <<\_ACEOF -#define _NETBSD_SOURCE 1 +int +main () +{ +return $2 (); + ; + return 0; +} _ACEOF +if ac_fn_c_try_link "$LINENO"; then : + eval "$3=yes" +else + eval "$3=no" +fi +rm -f core conftest.err conftest.$ac_objext \ + conftest$ac_exeext conftest.$ac_ext +fi +eval ac_res=\$$3 + { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_res" >&5 +$as_echo "$ac_res" >&6; } + eval $as_lineno_stack; test "x$as_lineno_stack" = x && { as_lineno=; unset as_lineno;} +} # ac_fn_c_check_func -# The later defininition of _XOPEN_SOURCE and _POSIX_C_SOURCE disables -# certain features on FreeBSD, so we need __BSD_VISIBLE to re-enable -# them. - -cat >>confdefs.h <<\_ACEOF -#define __BSD_VISIBLE 1 +# ac_fn_c_check_member LINENO AGGR MEMBER VAR INCLUDES +# ---------------------------------------------------- +# Tries to find if the field MEMBER exists in type AGGR, after including +# INCLUDES, setting cache variable VAR accordingly. +ac_fn_c_check_member () +{ + as_lineno=${as_lineno-"$1"} as_lineno_stack=as_lineno_stack=$as_lineno_stack + { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $2.$3" >&5 +$as_echo_n "checking for $2.$3... " >&6; } +if { as_var=$4; eval "test \"\${$as_var+set}\" = set"; }; then : + $as_echo_n "(cached) " >&6 +else + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ +$5 +int +main () +{ +static $2 ac_aggr; +if (ac_aggr.$3) +return 0; + ; + return 0; +} _ACEOF - - -# The later defininition of _XOPEN_SOURCE and _POSIX_C_SOURCE disables -# u_int on Irix 5.3. Defining _BSD_TYPES brings it back. - -cat >>confdefs.h <<\_ACEOF -#define _BSD_TYPES 1 +if ac_fn_c_try_compile "$LINENO"; then : + eval "$4=yes" +else + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ +$5 +int +main () +{ +static $2 ac_aggr; +if (sizeof ac_aggr.$3) +return 0; + ; + return 0; +} _ACEOF +if ac_fn_c_try_compile "$LINENO"; then : + eval "$4=yes" +else + eval "$4=no" +fi +rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext +fi +rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext +fi +eval ac_res=\$$4 + { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_res" >&5 +$as_echo "$ac_res" >&6; } + eval $as_lineno_stack; test "x$as_lineno_stack" = x && { as_lineno=; unset as_lineno;} +} # ac_fn_c_check_member -# The later defininition of _XOPEN_SOURCE and _POSIX_C_SOURCE disables -# certain features on Mac OS X, so we need _DARWIN_C_SOURCE to re-enable -# them. +# ac_fn_c_check_decl LINENO SYMBOL VAR +# ------------------------------------ +# Tests whether SYMBOL is declared, setting cache variable VAR accordingly. +ac_fn_c_check_decl () +{ + as_lineno=${as_lineno-"$1"} as_lineno_stack=as_lineno_stack=$as_lineno_stack + { $as_echo "$as_me:${as_lineno-$LINENO}: checking whether $2 is declared" >&5 +$as_echo_n "checking whether $2 is declared... " >&6; } +if { as_var=$3; eval "test \"\${$as_var+set}\" = set"; }; then : + $as_echo_n "(cached) " >&6 +else + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ +$4 +int +main () +{ +#ifndef $2 + (void) $2; +#endif -cat >>confdefs.h <<\_ACEOF -#define _DARWIN_C_SOURCE 1 + ; + return 0; +} _ACEOF - - - -define_xopen_source=yes - -# Arguments passed to configure. - -CONFIG_ARGS="$ac_configure_args" - -{ echo "$as_me:$LINENO: checking for --enable-universalsdk" >&5 -echo $ECHO_N "checking for --enable-universalsdk... $ECHO_C" >&6; } -# Check whether --enable-universalsdk was given. -if test "${enable_universalsdk+set}" = set; then - enableval=$enable_universalsdk; - case $enableval in - yes) - enableval=/Developer/SDKs/MacOSX10.4u.sdk - if test ! -d "${enableval}" - then - enableval=/ - fi - ;; - esac - case $enableval in - no) - UNIVERSALSDK= - enable_universalsdk= - ;; - *) - UNIVERSALSDK=$enableval - if test ! -d "${UNIVERSALSDK}" - then - { { echo "$as_me:$LINENO: error: --enable-universalsdk specifies non-existing SDK: ${UNIVERSALSDK}" >&5 -echo "$as_me: error: --enable-universalsdk specifies non-existing SDK: ${UNIVERSALSDK}" >&2;} - { (exit 1); exit 1; }; } - fi - ;; - esac - - +if ac_fn_c_try_compile "$LINENO"; then : + eval "$3=yes" else - - UNIVERSALSDK= - enable_universalsdk= - + eval "$3=no" fi - -if test -n "${UNIVERSALSDK}" -then - { echo "$as_me:$LINENO: result: ${UNIVERSALSDK}" >&5 -echo "${ECHO_T}${UNIVERSALSDK}" >&6; } -else - { echo "$as_me:$LINENO: result: no" >&5 -echo "${ECHO_T}no" >&6; } +rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext fi +eval ac_res=\$$3 + { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_res" >&5 +$as_echo "$ac_res" >&6; } + eval $as_lineno_stack; test "x$as_lineno_stack" = x && { as_lineno=; unset as_lineno;} +} # ac_fn_c_check_decl +cat >config.log <<_ACEOF +This file contains any messages produced by compilers while +running configure, to aid debugging if configure makes a mistake. +It was created by python $as_me 2.7, which was +generated by GNU Autoconf 2.65. Invocation command line was + $ $0 $@ -UNIVERSAL_ARCHS="32-bit" +_ACEOF +exec 5>>config.log +{ +cat <<_ASUNAME +## --------- ## +## Platform. ## +## --------- ## -{ echo "$as_me:$LINENO: checking for --with-universal-archs" >&5 -echo $ECHO_N "checking for --with-universal-archs... $ECHO_C" >&6; } +hostname = `(hostname || uname -n) 2>/dev/null | sed 1q` +uname -m = `(uname -m) 2>/dev/null || echo unknown` +uname -r = `(uname -r) 2>/dev/null || echo unknown` +uname -s = `(uname -s) 2>/dev/null || echo unknown` +uname -v = `(uname -v) 2>/dev/null || echo unknown` -# Check whether --with-universal-archs was given. -if test "${with_universal_archs+set}" = set; then - withval=$with_universal_archs; - { echo "$as_me:$LINENO: result: $withval" >&5 -echo "${ECHO_T}$withval" >&6; } - UNIVERSAL_ARCHS="$withval" - if test "${enable_universalsdk}" ; then - : - else - { { echo "$as_me:$LINENO: error: --with-universal-archs without --enable-universalsdk. See Mac/README" >&5 -echo "$as_me: error: --with-universal-archs without --enable-universalsdk. See Mac/README" >&2;} - { (exit 1); exit 1; }; } - fi +/usr/bin/uname -p = `(/usr/bin/uname -p) 2>/dev/null || echo unknown` +/bin/uname -X = `(/bin/uname -X) 2>/dev/null || echo unknown` -else +/bin/arch = `(/bin/arch) 2>/dev/null || echo unknown` +/usr/bin/arch -k = `(/usr/bin/arch -k) 2>/dev/null || echo unknown` +/usr/convex/getsysinfo = `(/usr/convex/getsysinfo) 2>/dev/null || echo unknown` +/usr/bin/hostinfo = `(/usr/bin/hostinfo) 2>/dev/null || echo unknown` +/bin/machine = `(/bin/machine) 2>/dev/null || echo unknown` +/usr/bin/oslevel = `(/usr/bin/oslevel) 2>/dev/null || echo unknown` +/bin/universe = `(/bin/universe) 2>/dev/null || echo unknown` - { echo "$as_me:$LINENO: result: 32-bit" >&5 -echo "${ECHO_T}32-bit" >&6; } +_ASUNAME -fi +as_save_IFS=$IFS; IFS=$PATH_SEPARATOR +for as_dir in $PATH +do + IFS=$as_save_IFS + test -z "$as_dir" && as_dir=. + $as_echo "PATH: $as_dir" + done +IFS=$as_save_IFS +} >&5 +cat >&5 <<_ACEOF +## ----------- ## +## Core tests. ## +## ----------- ## -# Check whether --with-framework-name was given. -if test "${with_framework_name+set}" = set; then - withval=$with_framework_name; - if test "${enable_framework}"; then - : - else - { { echo "$as_me:$LINENO: error: --with-framework-name without --enable-framework. See Mac/README" >&5 -echo "$as_me: error: --with-framework-name without --enable-framework. See Mac/README" >&2;} - { (exit 1); exit 1; }; } - fi - PYTHONFRAMEWORK=${withval} - PYTHONFRAMEWORKDIR=${withval}.framework - PYTHONFRAMEWORKIDENTIFIER=org.python.`echo $withval | tr 'A-Z' 'a-z'` +_ACEOF -else - PYTHONFRAMEWORK=Python - PYTHONFRAMEWORKDIR=Python.framework - PYTHONFRAMEWORKIDENTIFIER=org.python.python - -fi - -# Check whether --enable-framework was given. -if test "${enable_framework+set}" = set; then - enableval=$enable_framework; - case $enableval in - yes) - enableval=/Library/Frameworks +# Keep a trace of the command line. +# Strip out --no-create and --no-recursion so they do not pile up. +# Strip out --silent because we don't want to record it for future runs. +# Also quote any args containing shell meta-characters. +# Make two passes to allow for proper duplicate-argument suppression. +ac_configure_args= +ac_configure_args0= +ac_configure_args1= +ac_must_keep_next=false +for ac_pass in 1 2 +do + for ac_arg + do + case $ac_arg in + -no-create | --no-c* | -n | -no-recursion | --no-r*) continue ;; + -q | -quiet | --quiet | --quie | --qui | --qu | --q \ + | -silent | --silent | --silen | --sile | --sil) + continue ;; + *\'*) + ac_arg=`$as_echo "$ac_arg" | sed "s/'/'\\\\\\\\''/g"` ;; + esac + case $ac_pass in + 1) as_fn_append ac_configure_args0 " '$ac_arg'" ;; + 2) + as_fn_append ac_configure_args1 " '$ac_arg'" + if test $ac_must_keep_next = true; then + ac_must_keep_next=false # Got value, back to normal. + else + case $ac_arg in + *=* | --config-cache | -C | -disable-* | --disable-* \ + | -enable-* | --enable-* | -gas | --g* | -nfp | --nf* \ + | -q | -quiet | --q* | -silent | --sil* | -v | -verb* \ + | -with-* | --with-* | -without-* | --without-* | --x) + case "$ac_configure_args0 " in + "$ac_configure_args1"*" '$ac_arg' "* ) continue ;; + esac + ;; + -* ) ac_must_keep_next=true ;; esac - case $enableval in - no) - PYTHONFRAMEWORK= - PYTHONFRAMEWORKDIR=no-framework - PYTHONFRAMEWORKPREFIX= - PYTHONFRAMEWORKINSTALLDIR= - FRAMEWORKINSTALLFIRST= - FRAMEWORKINSTALLLAST= - FRAMEWORKALTINSTALLFIRST= - FRAMEWORKALTINSTALLLAST= - if test "x${prefix}" = "xNONE"; then - FRAMEWORKUNIXTOOLSPREFIX="${ac_default_prefix}" - else - FRAMEWORKUNIXTOOLSPREFIX="${prefix}" - fi - enable_framework= - ;; - *) - PYTHONFRAMEWORKPREFIX="${enableval}" - PYTHONFRAMEWORKINSTALLDIR=$PYTHONFRAMEWORKPREFIX/$PYTHONFRAMEWORKDIR - FRAMEWORKINSTALLFIRST="frameworkinstallstructure" - FRAMEWORKALTINSTALLFIRST="frameworkinstallstructure bininstall maninstall" - FRAMEWORKINSTALLLAST="frameworkinstallmaclib frameworkinstallapps frameworkinstallunixtools" - FRAMEWORKALTINSTALLLAST="frameworkinstallmaclib frameworkinstallapps frameworkaltinstallunixtools" - FRAMEWORKINSTALLAPPSPREFIX="/Applications" - - if test "x${prefix}" = "xNONE" ; then - FRAMEWORKUNIXTOOLSPREFIX="${ac_default_prefix}" - - else - FRAMEWORKUNIXTOOLSPREFIX="${prefix}" - fi + fi + as_fn_append ac_configure_args " '$ac_arg'" + ;; + esac + done +done +{ ac_configure_args0=; unset ac_configure_args0;} +{ ac_configure_args1=; unset ac_configure_args1;} - case "${enableval}" in - /System*) - FRAMEWORKINSTALLAPPSPREFIX="/Applications" - if test "${prefix}" = "NONE" ; then - # See below - FRAMEWORKUNIXTOOLSPREFIX="/usr" - fi - ;; +# When interrupted or exit'd, cleanup temporary files, and complete +# config.log. We remove comments because anyway the quotes in there +# would cause problems or look ugly. +# WARNING: Use '\'' to represent an apostrophe within the trap. +# WARNING: Do not start the trap code with a newline, due to a FreeBSD 4.0 bug. +trap 'exit_status=$? + # Save into config.log some information that might help in debugging. + { + echo - /Library*) - FRAMEWORKINSTALLAPPSPREFIX="/Applications" - ;; + cat <<\_ASBOX +## ---------------- ## +## Cache variables. ## +## ---------------- ## +_ASBOX + echo + # The following way of writing the cache mishandles newlines in values, +( + for ac_var in `(set) 2>&1 | sed -n '\''s/^\([a-zA-Z_][a-zA-Z0-9_]*\)=.*/\1/p'\''`; do + eval ac_val=\$$ac_var + case $ac_val in #( + *${as_nl}*) + case $ac_var in #( + *_cv_*) { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: cache variable $ac_var contains a newline" >&5 +$as_echo "$as_me: WARNING: cache variable $ac_var contains a newline" >&2;} ;; + esac + case $ac_var in #( + _ | IFS | as_nl) ;; #( + BASH_ARGV | BASH_SOURCE) eval $ac_var= ;; #( + *) { eval $ac_var=; unset $ac_var;} ;; + esac ;; + esac + done + (set) 2>&1 | + case $as_nl`(ac_space='\'' '\''; set) 2>&1` in #( + *${as_nl}ac_space=\ *) + sed -n \ + "s/'\''/'\''\\\\'\'''\''/g; + s/^\\([_$as_cr_alnum]*_cv_[_$as_cr_alnum]*\\)=\\(.*\\)/\\1='\''\\2'\''/p" + ;; #( + *) + sed -n "/^[_$as_cr_alnum]*_cv_[_$as_cr_alnum]*=/p" + ;; + esac | + sort +) + echo - */Library/Frameworks) - MDIR="`dirname "${enableval}"`" - MDIR="`dirname "${MDIR}"`" - FRAMEWORKINSTALLAPPSPREFIX="${MDIR}/Applications" + cat <<\_ASBOX +## ----------------- ## +## Output variables. ## +## ----------------- ## +_ASBOX + echo + for ac_var in $ac_subst_vars + do + eval ac_val=\$$ac_var + case $ac_val in + *\'\''*) ac_val=`$as_echo "$ac_val" | sed "s/'\''/'\''\\\\\\\\'\'''\''/g"`;; + esac + $as_echo "$ac_var='\''$ac_val'\''" + done | sort + echo - if test "${prefix}" = "NONE"; then - # User hasn't specified the - # --prefix option, but wants to install - # the framework in a non-default location, - # ensure that the compatibility links get - # installed relative to that prefix as well - # instead of in /usr/local. - FRAMEWORKUNIXTOOLSPREFIX="${MDIR}" - fi - ;; + if test -n "$ac_subst_files"; then + cat <<\_ASBOX +## ------------------- ## +## File substitutions. ## +## ------------------- ## +_ASBOX + echo + for ac_var in $ac_subst_files + do + eval ac_val=\$$ac_var + case $ac_val in + *\'\''*) ac_val=`$as_echo "$ac_val" | sed "s/'\''/'\''\\\\\\\\'\'''\''/g"`;; + esac + $as_echo "$ac_var='\''$ac_val'\''" + done | sort + echo + fi - *) - FRAMEWORKINSTALLAPPSPREFIX="/Applications" - ;; - esac + if test -s confdefs.h; then + cat <<\_ASBOX +## ----------- ## +## confdefs.h. ## +## ----------- ## +_ASBOX + echo + cat confdefs.h + echo + fi + test "$ac_signal" != 0 && + $as_echo "$as_me: caught signal $ac_signal" + $as_echo "$as_me: exit $exit_status" + } >&5 + rm -f core *.core core.conftest.* && + rm -f -r conftest* confdefs* conf$$* $ac_clean_files && + exit $exit_status +' 0 +for ac_signal in 1 2 13 15; do + trap 'ac_signal='$ac_signal'; as_fn_exit 1' $ac_signal +done +ac_signal=0 - prefix=$PYTHONFRAMEWORKINSTALLDIR/Versions/$VERSION +# confdefs.h avoids OS command line length limits that DEFS can exceed. +rm -f -r conftest* confdefs.h - # Add files for Mac specific code to the list of output - # files: - ac_config_files="$ac_config_files Mac/Makefile" +$as_echo "/* confdefs.h */" > confdefs.h - ac_config_files="$ac_config_files Mac/PythonLauncher/Makefile" +# Predefined preprocessor variables. - ac_config_files="$ac_config_files Mac/IDLE/Makefile" +cat >>confdefs.h <<_ACEOF +#define PACKAGE_NAME "$PACKAGE_NAME" +_ACEOF - ac_config_files="$ac_config_files Mac/Resources/framework/Info.plist" +cat >>confdefs.h <<_ACEOF +#define PACKAGE_TARNAME "$PACKAGE_TARNAME" +_ACEOF - ac_config_files="$ac_config_files Mac/Resources/app/Info.plist" +cat >>confdefs.h <<_ACEOF +#define PACKAGE_VERSION "$PACKAGE_VERSION" +_ACEOF - esac +cat >>confdefs.h <<_ACEOF +#define PACKAGE_STRING "$PACKAGE_STRING" +_ACEOF -else +cat >>confdefs.h <<_ACEOF +#define PACKAGE_BUGREPORT "$PACKAGE_BUGREPORT" +_ACEOF - PYTHONFRAMEWORK= - PYTHONFRAMEWORKDIR=no-framework - PYTHONFRAMEWORKPREFIX= - PYTHONFRAMEWORKINSTALLDIR= - FRAMEWORKINSTALLFIRST= - FRAMEWORKINSTALLLAST= - FRAMEWORKALTINSTALLFIRST= - FRAMEWORKALTINSTALLLAST= - if test "x${prefix}" = "xNONE" ; then - FRAMEWORKUNIXTOOLSPREFIX="${ac_default_prefix}" - else - FRAMEWORKUNIXTOOLSPREFIX="${prefix}" - fi - enable_framework= +cat >>confdefs.h <<_ACEOF +#define PACKAGE_URL "$PACKAGE_URL" +_ACEOF +# Let the site file select an alternate cache file if it wants to. +# Prefer an explicitly selected file to automatically selected ones. +ac_site_file1=NONE +ac_site_file2=NONE +if test -n "$CONFIG_SITE"; then + ac_site_file1=$CONFIG_SITE +elif test "x$prefix" != xNONE; then + ac_site_file1=$prefix/share/config.site + ac_site_file2=$prefix/etc/config.site +else + ac_site_file1=$ac_default_prefix/share/config.site + ac_site_file2=$ac_default_prefix/etc/config.site fi +for ac_site_file in "$ac_site_file1" "$ac_site_file2" +do + test "x$ac_site_file" = xNONE && continue + if test /dev/null != "$ac_site_file" && test -r "$ac_site_file"; then + { $as_echo "$as_me:${as_lineno-$LINENO}: loading site script $ac_site_file" >&5 +$as_echo "$as_me: loading site script $ac_site_file" >&6;} + sed 's/^/| /' "$ac_site_file" >&5 + . "$ac_site_file" + fi +done +if test -r "$cache_file"; then + # Some versions of bash will fail to source /dev/null (special files + # actually), so we avoid doing that. DJGPP emulates it as a regular file. + if test /dev/null != "$cache_file" && test -f "$cache_file"; then + { $as_echo "$as_me:${as_lineno-$LINENO}: loading cache $cache_file" >&5 +$as_echo "$as_me: loading cache $cache_file" >&6;} + case $cache_file in + [\\/]* | ?:[\\/]* ) . "$cache_file";; + *) . "./$cache_file";; + esac + fi +else + { $as_echo "$as_me:${as_lineno-$LINENO}: creating cache $cache_file" >&5 +$as_echo "$as_me: creating cache $cache_file" >&6;} + >$cache_file +fi +# Check that the precious variables saved in the cache have kept the same +# value. +ac_cache_corrupted=false +for ac_var in $ac_precious_vars; do + eval ac_old_set=\$ac_cv_env_${ac_var}_set + eval ac_new_set=\$ac_env_${ac_var}_set + eval ac_old_val=\$ac_cv_env_${ac_var}_value + eval ac_new_val=\$ac_env_${ac_var}_value + case $ac_old_set,$ac_new_set in + set,) + { $as_echo "$as_me:${as_lineno-$LINENO}: error: \`$ac_var' was set to \`$ac_old_val' in the previous run" >&5 +$as_echo "$as_me: error: \`$ac_var' was set to \`$ac_old_val' in the previous run" >&2;} + ac_cache_corrupted=: ;; + ,set) + { $as_echo "$as_me:${as_lineno-$LINENO}: error: \`$ac_var' was not set in the previous run" >&5 +$as_echo "$as_me: error: \`$ac_var' was not set in the previous run" >&2;} + ac_cache_corrupted=: ;; + ,);; + *) + if test "x$ac_old_val" != "x$ac_new_val"; then + # differences in whitespace do not lead to failure. + ac_old_val_w=`echo x $ac_old_val` + ac_new_val_w=`echo x $ac_new_val` + if test "$ac_old_val_w" != "$ac_new_val_w"; then + { $as_echo "$as_me:${as_lineno-$LINENO}: error: \`$ac_var' has changed since the previous run:" >&5 +$as_echo "$as_me: error: \`$ac_var' has changed since the previous run:" >&2;} + ac_cache_corrupted=: + else + { $as_echo "$as_me:${as_lineno-$LINENO}: warning: ignoring whitespace changes in \`$ac_var' since the previous run:" >&5 +$as_echo "$as_me: warning: ignoring whitespace changes in \`$ac_var' since the previous run:" >&2;} + eval $ac_var=\$ac_old_val + fi + { $as_echo "$as_me:${as_lineno-$LINENO}: former value: \`$ac_old_val'" >&5 +$as_echo "$as_me: former value: \`$ac_old_val'" >&2;} + { $as_echo "$as_me:${as_lineno-$LINENO}: current value: \`$ac_new_val'" >&5 +$as_echo "$as_me: current value: \`$ac_new_val'" >&2;} + fi;; + esac + # Pass precious variables to config.status. + if test "$ac_new_set" = set; then + case $ac_new_val in + *\'*) ac_arg=$ac_var=`$as_echo "$ac_new_val" | sed "s/'/'\\\\\\\\''/g"` ;; + *) ac_arg=$ac_var=$ac_new_val ;; + esac + case " $ac_configure_args " in + *" '$ac_arg' "*) ;; # Avoid dups. Use of quotes ensures accuracy. + *) as_fn_append ac_configure_args " '$ac_arg'" ;; + esac + fi +done +if $ac_cache_corrupted; then + { $as_echo "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5 +$as_echo "$as_me: error: in \`$ac_pwd':" >&2;} + { $as_echo "$as_me:${as_lineno-$LINENO}: error: changes in the environment can compromise the build" >&5 +$as_echo "$as_me: error: changes in the environment can compromise the build" >&2;} + as_fn_error "run \`make distclean' and/or \`rm $cache_file' and start over" "$LINENO" 5 +fi +## -------------------- ## +## Main body of script. ## +## -------------------- ## +ac_ext=c +ac_cpp='$CPP $CPPFLAGS' +ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5' +ac_link='$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5' +ac_compiler_gnu=$ac_cv_c_compiler_gnu +ac_config_headers="$ac_config_headers pyconfig.h" +if test "$prefix" != "/"; then + prefix=`echo "$prefix" | sed -e 's/\/$//g'` +fi -##AC_ARG_WITH(dyld, -## AC_HELP_STRING(--with-dyld, -## Use (OpenStep|Rhapsody) dynamic linker)) -## -# Set name for machine-dependent library files - -{ echo "$as_me:$LINENO: checking MACHDEP" >&5 -echo $ECHO_N "checking MACHDEP... $ECHO_C" >&6; } -if test -z "$MACHDEP" -then - ac_sys_system=`uname -s` - if test "$ac_sys_system" = "AIX" \ - -o "$ac_sys_system" = "UnixWare" -o "$ac_sys_system" = "OpenUNIX"; then - ac_sys_release=`uname -v` - else - ac_sys_release=`uname -r` - fi - ac_md_system=`echo $ac_sys_system | - tr -d '/ ' | tr '[A-Z]' '[a-z]'` - ac_md_release=`echo $ac_sys_release | - tr -d '/ ' | sed 's/^[A-Z]\.//' | sed 's/\..*//'` - MACHDEP="$ac_md_system$ac_md_release" - - case $MACHDEP in - cygwin*) MACHDEP="cygwin";; - darwin*) MACHDEP="darwin";; - atheos*) MACHDEP="atheos";; - irix646) MACHDEP="irix6";; - '') MACHDEP="unknown";; - esac -fi - -# Some systems cannot stand _XOPEN_SOURCE being defined at all; they -# disable features if it is defined, without any means to access these -# features as extensions. For these systems, we skip the definition of -# _XOPEN_SOURCE. Before adding a system to the list to gain access to -# some feature, make sure there is no alternative way to access this -# feature. Also, when using wildcards, make sure you have verified the -# need for not defining _XOPEN_SOURCE on all systems matching the -# wildcard, and that the wildcard does not include future systems -# (which may remove their limitations). -case $ac_sys_system/$ac_sys_release in - # On OpenBSD, select(2) is not available if _XOPEN_SOURCE is defined, - # even though select is a POSIX function. Reported by J. Ribbens. - # Reconfirmed for OpenBSD 3.3 by Zachary Hamm, for 3.4 by Jason Ish. - # In addition, Stefan Krah confirms that issue #1244610 exists through - # OpenBSD 4.6, but is fixed in 4.7. - OpenBSD/2.* | OpenBSD/3.[0123456789] | OpenBSD/4.[0123456]) - define_xopen_source=no - # OpenBSD undoes our definition of __BSD_VISIBLE if _XOPEN_SOURCE is - # also defined. This can be overridden by defining _BSD_SOURCE - # As this has a different meaning on Linux, only define it on OpenBSD +# We don't use PACKAGE_ variables, and they cause conflicts +# with other autoconf-based packages that include Python.h +grep -v 'define PACKAGE_' confdefs.h.new +rm confdefs.h +mv confdefs.h.new confdefs.h -cat >>confdefs.h <<\_ACEOF -#define _BSD_SOURCE 1 -_ACEOF - ;; - OpenBSD/4.[789]) - # OpenBSD undoes our definition of __BSD_VISIBLE if _XOPEN_SOURCE is - # also defined. This can be overridden by defining _BSD_SOURCE - # As this has a different meaning on Linux, only define it on OpenBSD +VERSION=2.7 -cat >>confdefs.h <<\_ACEOF -#define _BSD_SOURCE 1 -_ACEOF - ;; - # Defining _XOPEN_SOURCE on NetBSD version prior to the introduction of - # _NETBSD_SOURCE disables certain features (eg. setgroups). Reported by - # Marc Recht - NetBSD/1.5 | NetBSD/1.5.* | NetBSD/1.6 | NetBSD/1.6.* | NetBSD/1.6[A-S]) - define_xopen_source=no;; - # On Solaris 2.6, sys/wait.h is inconsistent in the usage - # of union __?sigval. Reported by Stuart Bishop. - SunOS/5.6) - define_xopen_source=no;; - # On UnixWare 7, u_long is never defined with _XOPEN_SOURCE, - # but used in /usr/include/netinet/tcp.h. Reported by Tim Rice. - # Reconfirmed for 7.1.4 by Martin v. Loewis. - OpenUNIX/8.0.0| UnixWare/7.1.[0-4]) - define_xopen_source=no;; - # On OpenServer 5, u_short is never defined with _XOPEN_SOURCE, - # but used in struct sockaddr.sa_family. Reported by Tim Rice. - SCO_SV/3.2) - define_xopen_source=no;; - # On FreeBSD 4, the math functions C89 does not cover are never defined - # with _XOPEN_SOURCE and __BSD_VISIBLE does not re-enable them. - FreeBSD/4.*) - define_xopen_source=no;; - # On MacOS X 10.2, a bug in ncurses.h means that it craps out if - # _XOPEN_EXTENDED_SOURCE is defined. Apparently, this is fixed in 10.3, which - # identifies itself as Darwin/7.* - # On Mac OS X 10.4, defining _POSIX_C_SOURCE or _XOPEN_SOURCE - # disables platform specific features beyond repair. - # On Mac OS X 10.3, defining _POSIX_C_SOURCE or _XOPEN_SOURCE - # has no effect, don't bother defining them - Darwin/[6789].*) - define_xopen_source=no;; - Darwin/1[0-9].*) - define_xopen_source=no;; - # On AIX 4 and 5.1, mbstate_t is defined only when _XOPEN_SOURCE == 500 but - # used in wcsnrtombs() and mbsnrtowcs() even if _XOPEN_SOURCE is not defined - # or has another value. By not (re)defining it, the defaults come in place. - AIX/4) - define_xopen_source=no;; - AIX/5) - if test `uname -r` -eq 1; then - define_xopen_source=no - fi - ;; - # On QNX 6.3.2, defining _XOPEN_SOURCE prevents netdb.h from - # defining NI_NUMERICHOST. - QNX/6.3.2) - define_xopen_source=no - ;; +SOVERSION=1.0 -esac +# The later defininition of _XOPEN_SOURCE disables certain features +# on Linux, so we need _GNU_SOURCE to re-enable them (makedev, tm_zone). -if test $define_xopen_source = yes -then - # On Solaris w/ g++ it appears that _XOPEN_SOURCE has to be - # defined precisely as g++ defines it - # Furthermore, on Solaris 10, XPG6 requires the use of a C99 - # compiler - case $ac_sys_system/$ac_sys_release in - SunOS/5.8|SunOS/5.9|SunOS/5.10) +$as_echo "#define _GNU_SOURCE 1" >>confdefs.h -cat >>confdefs.h <<\_ACEOF -#define _XOPEN_SOURCE 500 -_ACEOF - ;; - *) +# The later defininition of _XOPEN_SOURCE and _POSIX_C_SOURCE disables +# certain features on NetBSD, so we need _NETBSD_SOURCE to re-enable +# them. -cat >>confdefs.h <<\_ACEOF -#define _XOPEN_SOURCE 600 -_ACEOF +$as_echo "#define _NETBSD_SOURCE 1" >>confdefs.h - ;; - esac - # On Tru64 Unix 4.0F, defining _XOPEN_SOURCE also requires - # definition of _XOPEN_SOURCE_EXTENDED and _POSIX_C_SOURCE, or else - # several APIs are not declared. Since this is also needed in some - # cases for HP-UX, we define it globally. - # except for Solaris 10, where it must not be defined, - # as it implies XPG4.2 - case $ac_sys_system/$ac_sys_release in - SunOS/5.10) - ;; - *) +# The later defininition of _XOPEN_SOURCE and _POSIX_C_SOURCE disables +# certain features on FreeBSD, so we need __BSD_VISIBLE to re-enable +# them. -cat >>confdefs.h <<\_ACEOF -#define _XOPEN_SOURCE_EXTENDED 1 -_ACEOF +$as_echo "#define __BSD_VISIBLE 1" >>confdefs.h - ;; - esac +# The later defininition of _XOPEN_SOURCE and _POSIX_C_SOURCE disables +# u_int on Irix 5.3. Defining _BSD_TYPES brings it back. -cat >>confdefs.h <<\_ACEOF -#define _POSIX_C_SOURCE 200112L -_ACEOF +$as_echo "#define _BSD_TYPES 1" >>confdefs.h -fi +# The later defininition of _XOPEN_SOURCE and _POSIX_C_SOURCE disables +# certain features on Mac OS X, so we need _DARWIN_C_SOURCE to re-enable +# them. -# -# SGI compilers allow the specification of the both the ABI and the -# ISA on the command line. Depending on the values of these switches, -# different and often incompatable code will be generated. -# -# The SGI_ABI variable can be used to modify the CC and LDFLAGS and -# thus supply support for various ABI/ISA combinations. The MACHDEP -# variable is also adjusted. -# +$as_echo "#define _DARWIN_C_SOURCE 1" >>confdefs.h -if test ! -z "$SGI_ABI" -then - CC="cc $SGI_ABI" - LDFLAGS="$SGI_ABI $LDFLAGS" - MACHDEP=`echo "${MACHDEP}${SGI_ABI}" | sed 's/ *//g'` -fi -{ echo "$as_me:$LINENO: result: $MACHDEP" >&5 -echo "${ECHO_T}$MACHDEP" >&6; } -# And add extra plat-mac for darwin +define_xopen_source=yes -{ echo "$as_me:$LINENO: checking EXTRAPLATDIR" >&5 -echo $ECHO_N "checking EXTRAPLATDIR... $ECHO_C" >&6; } -if test -z "$EXTRAPLATDIR" -then - case $MACHDEP in - darwin) - EXTRAPLATDIR="\$(PLATMACDIRS)" - EXTRAMACHDEPPATH="\$(PLATMACPATH)" +# Arguments passed to configure. + +CONFIG_ARGS="$ac_configure_args" + +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for --enable-universalsdk" >&5 +$as_echo_n "checking for --enable-universalsdk... " >&6; } +# Check whether --enable-universalsdk was given. +if test "${enable_universalsdk+set}" = set; then : + enableval=$enable_universalsdk; + case $enableval in + yes) + enableval=/Developer/SDKs/MacOSX10.4u.sdk + if test ! -d "${enableval}" + then + enableval=/ + fi + ;; + esac + case $enableval in + no) + UNIVERSALSDK= + enable_universalsdk= ;; *) - EXTRAPLATDIR="" - EXTRAMACHDEPPATH="" + UNIVERSALSDK=$enableval + if test ! -d "${UNIVERSALSDK}" + then + as_fn_error "--enable-universalsdk specifies non-existing SDK: ${UNIVERSALSDK}" "$LINENO" 5 + fi ;; esac -fi -{ echo "$as_me:$LINENO: result: $EXTRAPLATDIR" >&5 -echo "${ECHO_T}$EXTRAPLATDIR" >&6; } -# Record the configure-time value of MACOSX_DEPLOYMENT_TARGET, -# it may influence the way we can build extensions, so distutils -# needs to check it +else -CONFIGURE_MACOSX_DEPLOYMENT_TARGET= -EXPORT_MACOSX_DEPLOYMENT_TARGET='#' - -{ echo "$as_me:$LINENO: checking machine type as reported by uname -m" >&5 -echo $ECHO_N "checking machine type as reported by uname -m... $ECHO_C" >&6; } -ac_sys_machine=`uname -m` -{ echo "$as_me:$LINENO: result: $ac_sys_machine" >&5 -echo "${ECHO_T}$ac_sys_machine" >&6; } - -# checks for alternative programs - -# compiler flags are generated in two sets, BASECFLAGS and OPT. OPT is just -# for debug/optimization stuff. BASECFLAGS is for flags that are required -# just to get things to compile and link. Users are free to override OPT -# when running configure or make. The build should not break if they do. -# BASECFLAGS should generally not be messed with, however. - -# XXX shouldn't some/most/all of this code be merged with the stuff later -# on that fiddles with OPT and BASECFLAGS? -{ echo "$as_me:$LINENO: checking for --without-gcc" >&5 -echo $ECHO_N "checking for --without-gcc... $ECHO_C" >&6; } - -# Check whether --with-gcc was given. -if test "${with_gcc+set}" = set; then - withval=$with_gcc; - case $withval in - no) CC=${CC:-cc} - without_gcc=yes;; - yes) CC=gcc - without_gcc=no;; - *) CC=$withval - without_gcc=$withval;; - esac -else + UNIVERSALSDK= + enable_universalsdk= - case $ac_sys_system in - AIX*) CC=cc_r - without_gcc=;; - BeOS*) - case $BE_HOST_CPU in - ppc) - CC=mwcc - without_gcc=yes - BASECFLAGS="$BASECFLAGS -export pragma" - OPT="$OPT -O" - LDFLAGS="$LDFLAGS -nodup" - ;; - x86) - CC=gcc - without_gcc=no - OPT="$OPT -O" - ;; - *) - { { echo "$as_me:$LINENO: error: Unknown BeOS platform \"$BE_HOST_CPU\"" >&5 -echo "$as_me: error: Unknown BeOS platform \"$BE_HOST_CPU\"" >&2;} - { (exit 1); exit 1; }; } - ;; - esac - AR="\$(srcdir)/Modules/ar_beos" - RANLIB=: - ;; - *) without_gcc=no;; - esac fi -{ echo "$as_me:$LINENO: result: $without_gcc" >&5 -echo "${ECHO_T}$without_gcc" >&6; } - -# If the user switches compilers, we can't believe the cache -if test ! -z "$ac_cv_prog_CC" -a ! -z "$CC" -a "$CC" != "$ac_cv_prog_CC" +if test -n "${UNIVERSALSDK}" then - { { echo "$as_me:$LINENO: error: cached CC is different -- throw away $cache_file -(it is also a good idea to do 'make clean' before compiling)" >&5 -echo "$as_me: error: cached CC is different -- throw away $cache_file -(it is also a good idea to do 'make clean' before compiling)" >&2;} - { (exit 1); exit 1; }; } + { $as_echo "$as_me:${as_lineno-$LINENO}: result: ${UNIVERSALSDK}" >&5 +$as_echo "${UNIVERSALSDK}" >&6; } +else + { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 +$as_echo "no" >&6; } fi -# If the user set CFLAGS, use this instead of the automatically -# determined setting -preset_cflags="$CFLAGS" -ac_ext=c -ac_cpp='$CPP $CPPFLAGS' -ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5' -ac_link='$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5' -ac_compiler_gnu=$ac_cv_c_compiler_gnu -if test -n "$ac_tool_prefix"; then - # Extract the first word of "${ac_tool_prefix}gcc", so it can be a program name with args. -set dummy ${ac_tool_prefix}gcc; ac_word=$2 -{ echo "$as_me:$LINENO: checking for $ac_word" >&5 -echo $ECHO_N "checking for $ac_word... $ECHO_C" >&6; } -if test "${ac_cv_prog_CC+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 -else - if test -n "$CC"; then - ac_cv_prog_CC="$CC" # Let the user override the test. -else -as_save_IFS=$IFS; IFS=$PATH_SEPARATOR -for as_dir in $PATH -do - IFS=$as_save_IFS - test -z "$as_dir" && as_dir=. - for ac_exec_ext in '' $ac_executable_extensions; do - if { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_test_x "$as_dir/$ac_word$ac_exec_ext"; }; then - ac_cv_prog_CC="${ac_tool_prefix}gcc" - echo "$as_me:$LINENO: found $as_dir/$ac_word$ac_exec_ext" >&5 - break 2 - fi -done -done -IFS=$as_save_IFS -fi -fi -CC=$ac_cv_prog_CC -if test -n "$CC"; then - { echo "$as_me:$LINENO: result: $CC" >&5 -echo "${ECHO_T}$CC" >&6; } -else - { echo "$as_me:$LINENO: result: no" >&5 -echo "${ECHO_T}no" >&6; } -fi -fi -if test -z "$ac_cv_prog_CC"; then - ac_ct_CC=$CC - # Extract the first word of "gcc", so it can be a program name with args. -set dummy gcc; ac_word=$2 -{ echo "$as_me:$LINENO: checking for $ac_word" >&5 -echo $ECHO_N "checking for $ac_word... $ECHO_C" >&6; } -if test "${ac_cv_prog_ac_ct_CC+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 -else - if test -n "$ac_ct_CC"; then - ac_cv_prog_ac_ct_CC="$ac_ct_CC" # Let the user override the test. -else -as_save_IFS=$IFS; IFS=$PATH_SEPARATOR -for as_dir in $PATH -do - IFS=$as_save_IFS - test -z "$as_dir" && as_dir=. - for ac_exec_ext in '' $ac_executable_extensions; do - if { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_test_x "$as_dir/$ac_word$ac_exec_ext"; }; then - ac_cv_prog_ac_ct_CC="gcc" - echo "$as_me:$LINENO: found $as_dir/$ac_word$ac_exec_ext" >&5 - break 2 - fi -done -done -IFS=$as_save_IFS +UNIVERSAL_ARCHS="32-bit" -fi -fi -ac_ct_CC=$ac_cv_prog_ac_ct_CC -if test -n "$ac_ct_CC"; then - { echo "$as_me:$LINENO: result: $ac_ct_CC" >&5 -echo "${ECHO_T}$ac_ct_CC" >&6; } -else - { echo "$as_me:$LINENO: result: no" >&5 -echo "${ECHO_T}no" >&6; } -fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for --with-universal-archs" >&5 +$as_echo_n "checking for --with-universal-archs... " >&6; } - if test "x$ac_ct_CC" = x; then - CC="" - else - case $cross_compiling:$ac_tool_warned in -yes:) -{ echo "$as_me:$LINENO: WARNING: In the future, Autoconf will not detect cross-tools -whose name does not start with the host triplet. If you think this -configuration is useful to you, please write to autoconf at gnu.org." >&5 -echo "$as_me: WARNING: In the future, Autoconf will not detect cross-tools -whose name does not start with the host triplet. If you think this -configuration is useful to you, please write to autoconf at gnu.org." >&2;} -ac_tool_warned=yes ;; -esac - CC=$ac_ct_CC - fi -else - CC="$ac_cv_prog_CC" -fi +# Check whether --with-universal-archs was given. +if test "${with_universal_archs+set}" = set; then : + withval=$with_universal_archs; + { $as_echo "$as_me:${as_lineno-$LINENO}: result: $withval" >&5 +$as_echo "$withval" >&6; } + UNIVERSAL_ARCHS="$withval" + if test "${enable_universalsdk}" ; then + : + else + as_fn_error "--with-universal-archs without --enable-universalsdk. See Mac/README" "$LINENO" 5 + fi -if test -z "$CC"; then - if test -n "$ac_tool_prefix"; then - # Extract the first word of "${ac_tool_prefix}cc", so it can be a program name with args. -set dummy ${ac_tool_prefix}cc; ac_word=$2 -{ echo "$as_me:$LINENO: checking for $ac_word" >&5 -echo $ECHO_N "checking for $ac_word... $ECHO_C" >&6; } -if test "${ac_cv_prog_CC+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 -else - if test -n "$CC"; then - ac_cv_prog_CC="$CC" # Let the user override the test. else -as_save_IFS=$IFS; IFS=$PATH_SEPARATOR -for as_dir in $PATH -do - IFS=$as_save_IFS - test -z "$as_dir" && as_dir=. - for ac_exec_ext in '' $ac_executable_extensions; do - if { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_test_x "$as_dir/$ac_word$ac_exec_ext"; }; then - ac_cv_prog_CC="${ac_tool_prefix}cc" - echo "$as_me:$LINENO: found $as_dir/$ac_word$ac_exec_ext" >&5 - break 2 - fi -done -done -IFS=$as_save_IFS -fi -fi -CC=$ac_cv_prog_CC -if test -n "$CC"; then - { echo "$as_me:$LINENO: result: $CC" >&5 -echo "${ECHO_T}$CC" >&6; } -else - { echo "$as_me:$LINENO: result: no" >&5 -echo "${ECHO_T}no" >&6; } + { $as_echo "$as_me:${as_lineno-$LINENO}: result: 32-bit" >&5 +$as_echo "32-bit" >&6; } + fi - fi -fi -if test -z "$CC"; then - # Extract the first word of "cc", so it can be a program name with args. -set dummy cc; ac_word=$2 -{ echo "$as_me:$LINENO: checking for $ac_word" >&5 -echo $ECHO_N "checking for $ac_word... $ECHO_C" >&6; } -if test "${ac_cv_prog_CC+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 -else - if test -n "$CC"; then - ac_cv_prog_CC="$CC" # Let the user override the test. -else - ac_prog_rejected=no -as_save_IFS=$IFS; IFS=$PATH_SEPARATOR -for as_dir in $PATH -do - IFS=$as_save_IFS - test -z "$as_dir" && as_dir=. - for ac_exec_ext in '' $ac_executable_extensions; do - if { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_test_x "$as_dir/$ac_word$ac_exec_ext"; }; then - if test "$as_dir/$ac_word$ac_exec_ext" = "/usr/ucb/cc"; then - ac_prog_rejected=yes - continue - fi - ac_cv_prog_CC="cc" - echo "$as_me:$LINENO: found $as_dir/$ac_word$ac_exec_ext" >&5 - break 2 - fi -done -done -IFS=$as_save_IFS -if test $ac_prog_rejected = yes; then - # We found a bogon in the path, so make sure we never use it. - set dummy $ac_cv_prog_CC - shift - if test $# != 0; then - # We chose a different compiler from the bogus one. - # However, it has the same basename, so the bogon will be chosen - # first if we set CC to just the basename; use the full file name. - shift - ac_cv_prog_CC="$as_dir/$ac_word${1+' '}$@" - fi -fi -fi -fi -CC=$ac_cv_prog_CC -if test -n "$CC"; then - { echo "$as_me:$LINENO: result: $CC" >&5 -echo "${ECHO_T}$CC" >&6; } -else - { echo "$as_me:$LINENO: result: no" >&5 -echo "${ECHO_T}no" >&6; } -fi -fi -if test -z "$CC"; then - if test -n "$ac_tool_prefix"; then - for ac_prog in cl.exe - do - # Extract the first word of "$ac_tool_prefix$ac_prog", so it can be a program name with args. -set dummy $ac_tool_prefix$ac_prog; ac_word=$2 -{ echo "$as_me:$LINENO: checking for $ac_word" >&5 -echo $ECHO_N "checking for $ac_word... $ECHO_C" >&6; } -if test "${ac_cv_prog_CC+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 -else - if test -n "$CC"; then - ac_cv_prog_CC="$CC" # Let the user override the test. -else -as_save_IFS=$IFS; IFS=$PATH_SEPARATOR -for as_dir in $PATH -do - IFS=$as_save_IFS - test -z "$as_dir" && as_dir=. - for ac_exec_ext in '' $ac_executable_extensions; do - if { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_test_x "$as_dir/$ac_word$ac_exec_ext"; }; then - ac_cv_prog_CC="$ac_tool_prefix$ac_prog" - echo "$as_me:$LINENO: found $as_dir/$ac_word$ac_exec_ext" >&5 - break 2 - fi -done -done -IFS=$as_save_IFS +# Check whether --with-framework-name was given. +if test "${with_framework_name+set}" = set; then : + withval=$with_framework_name; + if test "${enable_framework}"; then + : + else + as_fn_error "--with-framework-name without --enable-framework. See Mac/README" "$LINENO" 5 + fi + PYTHONFRAMEWORK=${withval} + PYTHONFRAMEWORKDIR=${withval}.framework + PYTHONFRAMEWORKIDENTIFIER=org.python.`echo $withval | tr 'A-Z' 'a-z'` -fi -fi -CC=$ac_cv_prog_CC -if test -n "$CC"; then - { echo "$as_me:$LINENO: result: $CC" >&5 -echo "${ECHO_T}$CC" >&6; } else - { echo "$as_me:$LINENO: result: no" >&5 -echo "${ECHO_T}no" >&6; } -fi + PYTHONFRAMEWORK=Python + PYTHONFRAMEWORKDIR=Python.framework + PYTHONFRAMEWORKIDENTIFIER=org.python.python - test -n "$CC" && break - done fi -if test -z "$CC"; then - ac_ct_CC=$CC - for ac_prog in cl.exe -do - # Extract the first word of "$ac_prog", so it can be a program name with args. -set dummy $ac_prog; ac_word=$2 -{ echo "$as_me:$LINENO: checking for $ac_word" >&5 -echo $ECHO_N "checking for $ac_word... $ECHO_C" >&6; } -if test "${ac_cv_prog_ac_ct_CC+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 -else - if test -n "$ac_ct_CC"; then - ac_cv_prog_ac_ct_CC="$ac_ct_CC" # Let the user override the test. -else -as_save_IFS=$IFS; IFS=$PATH_SEPARATOR -for as_dir in $PATH -do - IFS=$as_save_IFS - test -z "$as_dir" && as_dir=. - for ac_exec_ext in '' $ac_executable_extensions; do - if { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_test_x "$as_dir/$ac_word$ac_exec_ext"; }; then - ac_cv_prog_ac_ct_CC="$ac_prog" - echo "$as_me:$LINENO: found $as_dir/$ac_word$ac_exec_ext" >&5 - break 2 - fi -done -done -IFS=$as_save_IFS -fi -fi -ac_ct_CC=$ac_cv_prog_ac_ct_CC -if test -n "$ac_ct_CC"; then - { echo "$as_me:$LINENO: result: $ac_ct_CC" >&5 -echo "${ECHO_T}$ac_ct_CC" >&6; } -else - { echo "$as_me:$LINENO: result: no" >&5 -echo "${ECHO_T}no" >&6; } -fi +# Check whether --enable-framework was given. +if test "${enable_framework+set}" = set; then : + enableval=$enable_framework; + case $enableval in + yes) + enableval=/Library/Frameworks + esac + case $enableval in + no) + PYTHONFRAMEWORK= + PYTHONFRAMEWORKDIR=no-framework + PYTHONFRAMEWORKPREFIX= + PYTHONFRAMEWORKINSTALLDIR= + FRAMEWORKINSTALLFIRST= + FRAMEWORKINSTALLLAST= + FRAMEWORKALTINSTALLFIRST= + FRAMEWORKALTINSTALLLAST= + if test "x${prefix}" = "xNONE"; then + FRAMEWORKUNIXTOOLSPREFIX="${ac_default_prefix}" + else + FRAMEWORKUNIXTOOLSPREFIX="${prefix}" + fi + enable_framework= + ;; + *) + PYTHONFRAMEWORKPREFIX="${enableval}" + PYTHONFRAMEWORKINSTALLDIR=$PYTHONFRAMEWORKPREFIX/$PYTHONFRAMEWORKDIR + FRAMEWORKINSTALLFIRST="frameworkinstallstructure" + FRAMEWORKALTINSTALLFIRST="frameworkinstallstructure bininstall maninstall" + FRAMEWORKINSTALLLAST="frameworkinstallmaclib frameworkinstallapps frameworkinstallunixtools" + FRAMEWORKALTINSTALLLAST="frameworkinstallmaclib frameworkinstallapps frameworkaltinstallunixtools" + FRAMEWORKINSTALLAPPSPREFIX="/Applications" + if test "x${prefix}" = "xNONE" ; then + FRAMEWORKUNIXTOOLSPREFIX="${ac_default_prefix}" - test -n "$ac_ct_CC" && break -done + else + FRAMEWORKUNIXTOOLSPREFIX="${prefix}" + fi - if test "x$ac_ct_CC" = x; then - CC="" - else - case $cross_compiling:$ac_tool_warned in -yes:) -{ echo "$as_me:$LINENO: WARNING: In the future, Autoconf will not detect cross-tools -whose name does not start with the host triplet. If you think this -configuration is useful to you, please write to autoconf at gnu.org." >&5 -echo "$as_me: WARNING: In the future, Autoconf will not detect cross-tools -whose name does not start with the host triplet. If you think this -configuration is useful to you, please write to autoconf at gnu.org." >&2;} -ac_tool_warned=yes ;; -esac - CC=$ac_ct_CC - fi -fi + case "${enableval}" in + /System*) + FRAMEWORKINSTALLAPPSPREFIX="/Applications" + if test "${prefix}" = "NONE" ; then + # See below + FRAMEWORKUNIXTOOLSPREFIX="/usr" + fi + ;; -fi + /Library*) + FRAMEWORKINSTALLAPPSPREFIX="/Applications" + ;; + */Library/Frameworks) + MDIR="`dirname "${enableval}"`" + MDIR="`dirname "${MDIR}"`" + FRAMEWORKINSTALLAPPSPREFIX="${MDIR}/Applications" -test -z "$CC" && { { echo "$as_me:$LINENO: error: no acceptable C compiler found in \$PATH -See \`config.log' for more details." >&5 -echo "$as_me: error: no acceptable C compiler found in \$PATH -See \`config.log' for more details." >&2;} - { (exit 1); exit 1; }; } + if test "${prefix}" = "NONE"; then + # User hasn't specified the + # --prefix option, but wants to install + # the framework in a non-default location, + # ensure that the compatibility links get + # installed relative to that prefix as well + # instead of in /usr/local. + FRAMEWORKUNIXTOOLSPREFIX="${MDIR}" + fi + ;; -# Provide some information about the compiler. -echo "$as_me:$LINENO: checking for C compiler version" >&5 -ac_compiler=`set X $ac_compile; echo $2` -{ (ac_try="$ac_compiler --version >&5" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_compiler --version >&5") 2>&5 - ac_status=$? - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } -{ (ac_try="$ac_compiler -v >&5" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_compiler -v >&5") 2>&5 - ac_status=$? - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } -{ (ac_try="$ac_compiler -V >&5" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_compiler -V >&5") 2>&5 - ac_status=$? - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } + *) + FRAMEWORKINSTALLAPPSPREFIX="/Applications" + ;; + esac -cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ + prefix=$PYTHONFRAMEWORKINSTALLDIR/Versions/$VERSION -int -main () -{ + # Add files for Mac specific code to the list of output + # files: + ac_config_files="$ac_config_files Mac/Makefile" - ; - return 0; -} -_ACEOF -ac_clean_files_save=$ac_clean_files -ac_clean_files="$ac_clean_files a.out a.exe b.out" -# Try to create an executable without -o first, disregard a.out. -# It will help us diagnose broken compilers, and finding out an intuition -# of exeext. -{ echo "$as_me:$LINENO: checking for C compiler default output file name" >&5 -echo $ECHO_N "checking for C compiler default output file name... $ECHO_C" >&6; } -ac_link_default=`echo "$ac_link" | sed 's/ -o *conftest[^ ]*//'` -# -# List of possible output files, starting from the most likely. -# The algorithm is not robust to junk in `.', hence go to wildcards (a.*) -# only as a last resort. b.out is created by i960 compilers. -ac_files='a_out.exe a.exe conftest.exe a.out conftest a.* conftest.* b.out' -# -# The IRIX 6 linker writes into existing files which may not be -# executable, retaining their permissions. Remove them first so a -# subsequent execution test works. -ac_rmfiles= -for ac_file in $ac_files -do - case $ac_file in - *.$ac_ext | *.xcoff | *.tds | *.d | *.pdb | *.xSYM | *.bb | *.bbg | *.map | *.inf | *.o | *.obj ) ;; - * ) ac_rmfiles="$ac_rmfiles $ac_file";; - esac -done -rm -f $ac_rmfiles + ac_config_files="$ac_config_files Mac/PythonLauncher/Makefile" -if { (ac_try="$ac_link_default" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_link_default") 2>&5 - ac_status=$? - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); }; then - # Autoconf-2.13 could set the ac_cv_exeext variable to `no'. -# So ignore a value of `no', otherwise this would lead to `EXEEXT = no' -# in a Makefile. We should not override ac_cv_exeext if it was cached, -# so that the user can short-circuit this test for compilers unknown to -# Autoconf. -for ac_file in $ac_files '' -do - test -f "$ac_file" || continue - case $ac_file in - *.$ac_ext | *.xcoff | *.tds | *.d | *.pdb | *.xSYM | *.bb | *.bbg | *.map | *.inf | *.o | *.obj ) - ;; - [ab].out ) - # We found the default executable, but exeext='' is most - # certainly right. - break;; - *.* ) - if test "${ac_cv_exeext+set}" = set && test "$ac_cv_exeext" != no; - then :; else - ac_cv_exeext=`expr "$ac_file" : '[^.]*\(\..*\)'` - fi - # We set ac_cv_exeext here because the later test for it is not - # safe: cross compilers may not add the suffix if given an `-o' - # argument, so we may need to know it at that point already. - # Even if this section looks crufty: it has the advantage of - # actually working. - break;; - * ) - break;; - esac -done -test "$ac_cv_exeext" = no && ac_cv_exeext= + ac_config_files="$ac_config_files Mac/IDLE/Makefile" + + ac_config_files="$ac_config_files Mac/Resources/framework/Info.plist" + + ac_config_files="$ac_config_files Mac/Resources/app/Info.plist" + + esac else - ac_file='' -fi -{ echo "$as_me:$LINENO: result: $ac_file" >&5 -echo "${ECHO_T}$ac_file" >&6; } -if test -z "$ac_file"; then - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 + PYTHONFRAMEWORK= + PYTHONFRAMEWORKDIR=no-framework + PYTHONFRAMEWORKPREFIX= + PYTHONFRAMEWORKINSTALLDIR= + FRAMEWORKINSTALLFIRST= + FRAMEWORKINSTALLLAST= + FRAMEWORKALTINSTALLFIRST= + FRAMEWORKALTINSTALLLAST= + if test "x${prefix}" = "xNONE" ; then + FRAMEWORKUNIXTOOLSPREFIX="${ac_default_prefix}" + else + FRAMEWORKUNIXTOOLSPREFIX="${prefix}" + fi + enable_framework= + -{ { echo "$as_me:$LINENO: error: C compiler cannot create executables -See \`config.log' for more details." >&5 -echo "$as_me: error: C compiler cannot create executables -See \`config.log' for more details." >&2;} - { (exit 77); exit 77; }; } fi -ac_exeext=$ac_cv_exeext -# Check that the compiler produces executables we can run. If not, either -# the compiler is broken, or we cross compile. -{ echo "$as_me:$LINENO: checking whether the C compiler works" >&5 -echo $ECHO_N "checking whether the C compiler works... $ECHO_C" >&6; } -# FIXME: These cross compiler hacks should be removed for Autoconf 3.0 -# If not cross compiling, check that we can run a simple program. -if test "$cross_compiling" != yes; then - if { ac_try='./$ac_file' - { (case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_try") 2>&5 - ac_status=$? - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); }; }; then - cross_compiling=no - else - if test "$cross_compiling" = maybe; then - cross_compiling=yes - else - { { echo "$as_me:$LINENO: error: cannot run C compiled programs. -If you meant to cross compile, use \`--host'. -See \`config.log' for more details." >&5 -echo "$as_me: error: cannot run C compiled programs. -If you meant to cross compile, use \`--host'. -See \`config.log' for more details." >&2;} - { (exit 1); exit 1; }; } - fi - fi -fi -{ echo "$as_me:$LINENO: result: yes" >&5 -echo "${ECHO_T}yes" >&6; } -rm -f a.out a.exe conftest$ac_cv_exeext b.out -ac_clean_files=$ac_clean_files_save -# Check that the compiler produces executables we can run. If not, either -# the compiler is broken, or we cross compile. -{ echo "$as_me:$LINENO: checking whether we are cross compiling" >&5 -echo $ECHO_N "checking whether we are cross compiling... $ECHO_C" >&6; } -{ echo "$as_me:$LINENO: result: $cross_compiling" >&5 -echo "${ECHO_T}$cross_compiling" >&6; } - -{ echo "$as_me:$LINENO: checking for suffix of executables" >&5 -echo $ECHO_N "checking for suffix of executables... $ECHO_C" >&6; } -if { (ac_try="$ac_link" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_link") 2>&5 - ac_status=$? - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); }; then - # If both `conftest.exe' and `conftest' are `present' (well, observable) -# catch `conftest.exe'. For instance with Cygwin, `ls conftest' will -# work properly (i.e., refer to `conftest.exe'), while it won't with -# `rm'. -for ac_file in conftest.exe conftest conftest.*; do - test -f "$ac_file" || continue - case $ac_file in - *.$ac_ext | *.xcoff | *.tds | *.d | *.pdb | *.xSYM | *.bb | *.bbg | *.map | *.inf | *.o | *.obj ) ;; - *.* ) ac_cv_exeext=`expr "$ac_file" : '[^.]*\(\..*\)'` - break;; - * ) break;; - esac -done -else - { { echo "$as_me:$LINENO: error: cannot compute suffix of executables: cannot compile and link -See \`config.log' for more details." >&5 -echo "$as_me: error: cannot compute suffix of executables: cannot compile and link -See \`config.log' for more details." >&2;} - { (exit 1); exit 1; }; } -fi -rm -f conftest$ac_cv_exeext -{ echo "$as_me:$LINENO: result: $ac_cv_exeext" >&5 -echo "${ECHO_T}$ac_cv_exeext" >&6; } -rm -f conftest.$ac_ext -EXEEXT=$ac_cv_exeext -ac_exeext=$EXEEXT -{ echo "$as_me:$LINENO: checking for suffix of object files" >&5 -echo $ECHO_N "checking for suffix of object files... $ECHO_C" >&6; } -if test "${ac_cv_objext+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 -else - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -int -main () -{ - ; - return 0; -} -_ACEOF -rm -f conftest.o conftest.obj -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_compile") 2>&5 - ac_status=$? - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); }; then - for ac_file in conftest.o conftest.obj conftest.*; do - test -f "$ac_file" || continue; - case $ac_file in - *.$ac_ext | *.xcoff | *.tds | *.d | *.pdb | *.xSYM | *.bb | *.bbg | *.map | *.inf ) ;; - *) ac_cv_objext=`expr "$ac_file" : '.*\.\(.*\)'` - break;; - esac -done -else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 -{ { echo "$as_me:$LINENO: error: cannot compute suffix of object files: cannot compile -See \`config.log' for more details." >&5 -echo "$as_me: error: cannot compute suffix of object files: cannot compile -See \`config.log' for more details." >&2;} - { (exit 1); exit 1; }; } -fi -rm -f conftest.$ac_cv_objext conftest.$ac_ext -fi -{ echo "$as_me:$LINENO: result: $ac_cv_objext" >&5 -echo "${ECHO_T}$ac_cv_objext" >&6; } -OBJEXT=$ac_cv_objext -ac_objext=$OBJEXT -{ echo "$as_me:$LINENO: checking whether we are using the GNU C compiler" >&5 -echo $ECHO_N "checking whether we are using the GNU C compiler... $ECHO_C" >&6; } -if test "${ac_cv_c_compiler_gnu+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 -else - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -int -main () -{ -#ifndef __GNUC__ - choke me -#endif - ; - return 0; -} -_ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - ac_compiler_gnu=yes -else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - ac_compiler_gnu=no -fi -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext -ac_cv_c_compiler_gnu=$ac_compiler_gnu +##AC_ARG_WITH(dyld, +## AC_HELP_STRING(--with-dyld, +## Use (OpenStep|Rhapsody) dynamic linker)) +## +# Set name for machine-dependent library files + +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking MACHDEP" >&5 +$as_echo_n "checking MACHDEP... " >&6; } +if test -z "$MACHDEP" +then + ac_sys_system=`uname -s` + if test "$ac_sys_system" = "AIX" \ + -o "$ac_sys_system" = "UnixWare" -o "$ac_sys_system" = "OpenUNIX"; then + ac_sys_release=`uname -v` + else + ac_sys_release=`uname -r` + fi + ac_md_system=`echo $ac_sys_system | + tr -d '/ ' | tr '[A-Z]' '[a-z]'` + ac_md_release=`echo $ac_sys_release | + tr -d '/ ' | sed 's/^[A-Z]\.//' | sed 's/\..*//'` + MACHDEP="$ac_md_system$ac_md_release" + case $MACHDEP in + cygwin*) MACHDEP="cygwin";; + darwin*) MACHDEP="darwin";; + atheos*) MACHDEP="atheos";; + irix646) MACHDEP="irix6";; + '') MACHDEP="unknown";; + esac fi -{ echo "$as_me:$LINENO: result: $ac_cv_c_compiler_gnu" >&5 -echo "${ECHO_T}$ac_cv_c_compiler_gnu" >&6; } -GCC=`test $ac_compiler_gnu = yes && echo yes` -ac_test_CFLAGS=${CFLAGS+set} -ac_save_CFLAGS=$CFLAGS -{ echo "$as_me:$LINENO: checking whether $CC accepts -g" >&5 -echo $ECHO_N "checking whether $CC accepts -g... $ECHO_C" >&6; } -if test "${ac_cv_prog_cc_g+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 -else - ac_save_c_werror_flag=$ac_c_werror_flag - ac_c_werror_flag=yes - ac_cv_prog_cc_g=no - CFLAGS="-g" - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -int -main () -{ +# Some systems cannot stand _XOPEN_SOURCE being defined at all; they +# disable features if it is defined, without any means to access these +# features as extensions. For these systems, we skip the definition of +# _XOPEN_SOURCE. Before adding a system to the list to gain access to +# some feature, make sure there is no alternative way to access this +# feature. Also, when using wildcards, make sure you have verified the +# need for not defining _XOPEN_SOURCE on all systems matching the +# wildcard, and that the wildcard does not include future systems +# (which may remove their limitations). +case $ac_sys_system/$ac_sys_release in + # On OpenBSD, select(2) is not available if _XOPEN_SOURCE is defined, + # even though select is a POSIX function. Reported by J. Ribbens. + # Reconfirmed for OpenBSD 3.3 by Zachary Hamm, for 3.4 by Jason Ish. + # In addition, Stefan Krah confirms that issue #1244610 exists through + # OpenBSD 4.6, but is fixed in 4.7. + OpenBSD/2.* | OpenBSD/3.[0123456789] | OpenBSD/4.[0123456]) + define_xopen_source=no + # OpenBSD undoes our definition of __BSD_VISIBLE if _XOPEN_SOURCE is + # also defined. This can be overridden by defining _BSD_SOURCE + # As this has a different meaning on Linux, only define it on OpenBSD - ; - return 0; -} -_ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - ac_cv_prog_cc_g=yes -else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 +$as_echo "#define _BSD_SOURCE 1" >>confdefs.h - CFLAGS="" - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ + ;; + OpenBSD/4.[789]) + # OpenBSD undoes our definition of __BSD_VISIBLE if _XOPEN_SOURCE is + # also defined. This can be overridden by defining _BSD_SOURCE + # As this has a different meaning on Linux, only define it on OpenBSD -int -main () -{ +$as_echo "#define _BSD_SOURCE 1" >>confdefs.h + + ;; + # Defining _XOPEN_SOURCE on NetBSD version prior to the introduction of + # _NETBSD_SOURCE disables certain features (eg. setgroups). Reported by + # Marc Recht + NetBSD/1.5 | NetBSD/1.5.* | NetBSD/1.6 | NetBSD/1.6.* | NetBSD/1.6[A-S]) + define_xopen_source=no;; + # On Solaris 2.6, sys/wait.h is inconsistent in the usage + # of union __?sigval. Reported by Stuart Bishop. + SunOS/5.6) + define_xopen_source=no;; + # On UnixWare 7, u_long is never defined with _XOPEN_SOURCE, + # but used in /usr/include/netinet/tcp.h. Reported by Tim Rice. + # Reconfirmed for 7.1.4 by Martin v. Loewis. + OpenUNIX/8.0.0| UnixWare/7.1.[0-4]) + define_xopen_source=no;; + # On OpenServer 5, u_short is never defined with _XOPEN_SOURCE, + # but used in struct sockaddr.sa_family. Reported by Tim Rice. + SCO_SV/3.2) + define_xopen_source=no;; + # On FreeBSD 4, the math functions C89 does not cover are never defined + # with _XOPEN_SOURCE and __BSD_VISIBLE does not re-enable them. + FreeBSD/4.*) + define_xopen_source=no;; + # On MacOS X 10.2, a bug in ncurses.h means that it craps out if + # _XOPEN_EXTENDED_SOURCE is defined. Apparently, this is fixed in 10.3, which + # identifies itself as Darwin/7.* + # On Mac OS X 10.4, defining _POSIX_C_SOURCE or _XOPEN_SOURCE + # disables platform specific features beyond repair. + # On Mac OS X 10.3, defining _POSIX_C_SOURCE or _XOPEN_SOURCE + # has no effect, don't bother defining them + Darwin/[6789].*) + define_xopen_source=no;; + Darwin/1[0-9].*) + define_xopen_source=no;; + # On AIX 4 and 5.1, mbstate_t is defined only when _XOPEN_SOURCE == 500 but + # used in wcsnrtombs() and mbsnrtowcs() even if _XOPEN_SOURCE is not defined + # or has another value. By not (re)defining it, the defaults come in place. + AIX/4) + define_xopen_source=no;; + AIX/5) + if test `uname -r` -eq 1; then + define_xopen_source=no + fi + ;; + # On QNX 6.3.2, defining _XOPEN_SOURCE prevents netdb.h from + # defining NI_NUMERICHOST. + QNX/6.3.2) + define_xopen_source=no + ;; - ; - return 0; -} -_ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - : -else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - ac_c_werror_flag=$ac_save_c_werror_flag - CFLAGS="-g" - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ +if test $define_xopen_source = yes +then + # On Solaris w/ g++ it appears that _XOPEN_SOURCE has to be + # defined precisely as g++ defines it + # Furthermore, on Solaris 10, XPG6 requires the use of a C99 + # compiler + case $ac_sys_system/$ac_sys_release in + SunOS/5.8|SunOS/5.9|SunOS/5.10) -int -main () -{ +$as_echo "#define _XOPEN_SOURCE 500" >>confdefs.h - ; - return 0; -} -_ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - ac_cv_prog_cc_g=yes -else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 + ;; + *) +$as_echo "#define _XOPEN_SOURCE 600" >>confdefs.h -fi + ;; + esac -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext -fi + # On Tru64 Unix 4.0F, defining _XOPEN_SOURCE also requires + # definition of _XOPEN_SOURCE_EXTENDED and _POSIX_C_SOURCE, or else + # several APIs are not declared. Since this is also needed in some + # cases for HP-UX, we define it globally. + # except for Solaris 10, where it must not be defined, + # as it implies XPG4.2 + case $ac_sys_system/$ac_sys_release in + SunOS/5.10) + ;; + *) + +$as_echo "#define _XOPEN_SOURCE_EXTENDED 1" >>confdefs.h + + ;; + esac + + +$as_echo "#define _POSIX_C_SOURCE 200112L" >>confdefs.h -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext -fi -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext - ac_c_werror_flag=$ac_save_c_werror_flag fi -{ echo "$as_me:$LINENO: result: $ac_cv_prog_cc_g" >&5 -echo "${ECHO_T}$ac_cv_prog_cc_g" >&6; } -if test "$ac_test_CFLAGS" = set; then - CFLAGS=$ac_save_CFLAGS -elif test $ac_cv_prog_cc_g = yes; then - if test "$GCC" = yes; then - CFLAGS="-g -O2" - else - CFLAGS="-g" - fi -else - if test "$GCC" = yes; then - CFLAGS="-O2" - else - CFLAGS= - fi -fi -{ echo "$as_me:$LINENO: checking for $CC option to accept ISO C89" >&5 -echo $ECHO_N "checking for $CC option to accept ISO C89... $ECHO_C" >&6; } -if test "${ac_cv_prog_cc_c89+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 -else - ac_cv_prog_cc_c89=no -ac_save_CC=$CC -cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -#include -#include -#include -#include -/* Most of the following tests are stolen from RCS 5.7's src/conf.sh. */ -struct buf { int x; }; -FILE * (*rcsopen) (struct buf *, struct stat *, int); -static char *e (p, i) - char **p; - int i; -{ - return p[i]; -} -static char *f (char * (*g) (char **, int), char **p, ...) -{ - char *s; - va_list v; - va_start (v,p); - s = g (p, va_arg (v,int)); - va_end (v); - return s; -} - -/* OSF 4.0 Compaq cc is some sort of almost-ANSI by default. It has - function prototypes and stuff, but not '\xHH' hex character constants. - These don't provoke an error unfortunately, instead are silently treated - as 'x'. The following induces an error, until -std is added to get - proper ANSI mode. Curiously '\x00'!='x' always comes out true, for an - array size at least. It's necessary to write '\x00'==0 to get something - that's true only with -std. */ -int osf4_cc_array ['\x00' == 0 ? 1 : -1]; - -/* IBM C 6 for AIX is almost-ANSI by default, but it replaces macro parameters - inside strings and character constants. */ -#define FOO(x) 'x' -int xlc6_cc_array[FOO(a) == 'x' ? 1 : -1]; - -int test (int i, double x); -struct s1 {int (*f) (int a);}; -struct s2 {int (*f) (double a);}; -int pairnames (int, char **, FILE *(*)(struct buf *, struct stat *, int), int, int); -int argc; -char **argv; -int -main () -{ -return f (e, argv, 0) != argv[0] || f (e, argv, 1) != argv[1]; - ; - return 0; -} -_ACEOF -for ac_arg in '' -qlanglvl=extc89 -qlanglvl=ansi -std \ - -Ae "-Aa -D_HPUX_SOURCE" "-Xc -D__EXTENSIONS__" -do - CC="$ac_save_CC $ac_arg" - rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - ac_cv_prog_cc_c89=$ac_arg -else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 +# +# SGI compilers allow the specification of the both the ABI and the +# ISA on the command line. Depending on the values of these switches, +# different and often incompatable code will be generated. +# +# The SGI_ABI variable can be used to modify the CC and LDFLAGS and +# thus supply support for various ABI/ISA combinations. The MACHDEP +# variable is also adjusted. +# +if test ! -z "$SGI_ABI" +then + CC="cc $SGI_ABI" + LDFLAGS="$SGI_ABI $LDFLAGS" + MACHDEP=`echo "${MACHDEP}${SGI_ABI}" | sed 's/ *//g'` fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $MACHDEP" >&5 +$as_echo "$MACHDEP" >&6; } -rm -f core conftest.err conftest.$ac_objext - test "x$ac_cv_prog_cc_c89" != "xno" && break -done -rm -f conftest.$ac_ext -CC=$ac_save_CC +# And add extra plat-mac for darwin + +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking EXTRAPLATDIR" >&5 +$as_echo_n "checking EXTRAPLATDIR... " >&6; } +if test -z "$EXTRAPLATDIR" +then + case $MACHDEP in + darwin) + EXTRAPLATDIR="\$(PLATMACDIRS)" + EXTRAMACHDEPPATH="\$(PLATMACPATH)" + ;; + *) + EXTRAPLATDIR="" + EXTRAMACHDEPPATH="" + ;; + esac fi -# AC_CACHE_VAL -case "x$ac_cv_prog_cc_c89" in - x) - { echo "$as_me:$LINENO: result: none needed" >&5 -echo "${ECHO_T}none needed" >&6; } ;; - xno) - { echo "$as_me:$LINENO: result: unsupported" >&5 -echo "${ECHO_T}unsupported" >&6; } ;; - *) - CC="$CC $ac_cv_prog_cc_c89" - { echo "$as_me:$LINENO: result: $ac_cv_prog_cc_c89" >&5 -echo "${ECHO_T}$ac_cv_prog_cc_c89" >&6; } ;; -esac +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $EXTRAPLATDIR" >&5 +$as_echo "$EXTRAPLATDIR" >&6; } +# Record the configure-time value of MACOSX_DEPLOYMENT_TARGET, +# it may influence the way we can build extensions, so distutils +# needs to check it -ac_ext=c -ac_cpp='$CPP $CPPFLAGS' -ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5' -ac_link='$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5' -ac_compiler_gnu=$ac_cv_c_compiler_gnu -if test ! -z "$preset_cflags" -then - CFLAGS=$preset_cflags -fi +CONFIGURE_MACOSX_DEPLOYMENT_TARGET= +EXPORT_MACOSX_DEPLOYMENT_TARGET='#' +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking machine type as reported by uname -m" >&5 +$as_echo_n "checking machine type as reported by uname -m... " >&6; } +ac_sys_machine=`uname -m` +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_sys_machine" >&5 +$as_echo "$ac_sys_machine" >&6; } +# checks for alternative programs -{ echo "$as_me:$LINENO: checking for --with-cxx-main=" >&5 -echo $ECHO_N "checking for --with-cxx-main=... $ECHO_C" >&6; } +# compiler flags are generated in two sets, BASECFLAGS and OPT. OPT is just +# for debug/optimization stuff. BASECFLAGS is for flags that are required +# just to get things to compile and link. Users are free to override OPT +# when running configure or make. The build should not break if they do. +# BASECFLAGS should generally not be messed with, however. -# Check whether --with-cxx_main was given. -if test "${with_cxx_main+set}" = set; then - withval=$with_cxx_main; +# XXX shouldn't some/most/all of this code be merged with the stuff later +# on that fiddles with OPT and BASECFLAGS? +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for --without-gcc" >&5 +$as_echo_n "checking for --without-gcc... " >&6; } +# Check whether --with-gcc was given. +if test "${with_gcc+set}" = set; then : + withval=$with_gcc; case $withval in - no) with_cxx_main=no - MAINCC='$(CC)';; - yes) with_cxx_main=yes - MAINCC='$(CXX)';; - *) with_cxx_main=yes - MAINCC=$withval - if test -z "$CXX" - then - CXX=$withval - fi;; + no) CC=${CC:-cc} + without_gcc=yes;; + yes) CC=gcc + without_gcc=no;; + *) CC=$withval + without_gcc=$withval;; esac else - with_cxx_main=no - MAINCC='$(CC)' - + case $ac_sys_system in + AIX*) CC=cc_r + without_gcc=;; + BeOS*) + case $BE_HOST_CPU in + ppc) + CC=mwcc + without_gcc=yes + BASECFLAGS="$BASECFLAGS -export pragma" + OPT="$OPT -O" + LDFLAGS="$LDFLAGS -nodup" + ;; + x86) + CC=gcc + without_gcc=no + OPT="$OPT -O" + ;; + *) + as_fn_error "Unknown BeOS platform \"$BE_HOST_CPU\"" "$LINENO" 5 + ;; + esac + AR="\$(srcdir)/Modules/ar_beos" + RANLIB=: + ;; + *) without_gcc=no;; + esac fi -{ echo "$as_me:$LINENO: result: $with_cxx_main" >&5 -echo "${ECHO_T}$with_cxx_main" >&6; } +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $without_gcc" >&5 +$as_echo "$without_gcc" >&6; } -preset_cxx="$CXX" -if test -z "$CXX" +# If the user switches compilers, we can't believe the cache +if test ! -z "$ac_cv_prog_CC" -a ! -z "$CC" -a "$CC" != "$ac_cv_prog_CC" then - case "$CC" in - gcc) # Extract the first word of "g++", so it can be a program name with args. -set dummy g++; ac_word=$2 -{ echo "$as_me:$LINENO: checking for $ac_word" >&5 -echo $ECHO_N "checking for $ac_word... $ECHO_C" >&6; } -if test "${ac_cv_path_CXX+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 + as_fn_error "cached CC is different -- throw away $cache_file +(it is also a good idea to do 'make clean' before compiling)" "$LINENO" 5 +fi + +# If the user set CFLAGS, use this instead of the automatically +# determined setting +preset_cflags="$CFLAGS" +ac_ext=c +ac_cpp='$CPP $CPPFLAGS' +ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5' +ac_link='$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5' +ac_compiler_gnu=$ac_cv_c_compiler_gnu +if test -n "$ac_tool_prefix"; then + # Extract the first word of "${ac_tool_prefix}gcc", so it can be a program name with args. +set dummy ${ac_tool_prefix}gcc; ac_word=$2 +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 +$as_echo_n "checking for $ac_word... " >&6; } +if test "${ac_cv_prog_CC+set}" = set; then : + $as_echo_n "(cached) " >&6 else - case $CXX in - [\\/]* | ?:[\\/]*) - ac_cv_path_CXX="$CXX" # Let the user override the test with a path. - ;; - *) - as_save_IFS=$IFS; IFS=$PATH_SEPARATOR -for as_dir in notfound + if test -n "$CC"; then + ac_cv_prog_CC="$CC" # Let the user override the test. +else +as_save_IFS=$IFS; IFS=$PATH_SEPARATOR +for as_dir in $PATH do IFS=$as_save_IFS test -z "$as_dir" && as_dir=. - for ac_exec_ext in '' $ac_executable_extensions; do + for ac_exec_ext in '' $ac_executable_extensions; do if { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_test_x "$as_dir/$ac_word$ac_exec_ext"; }; then - ac_cv_path_CXX="$as_dir/$ac_word$ac_exec_ext" - echo "$as_me:$LINENO: found $as_dir/$ac_word$ac_exec_ext" >&5 + ac_cv_prog_CC="${ac_tool_prefix}gcc" + $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 break 2 fi done -done + done IFS=$as_save_IFS - test -z "$ac_cv_path_CXX" && ac_cv_path_CXX="g++" - ;; -esac fi -CXX=$ac_cv_path_CXX -if test -n "$CXX"; then - { echo "$as_me:$LINENO: result: $CXX" >&5 -echo "${ECHO_T}$CXX" >&6; } +fi +CC=$ac_cv_prog_CC +if test -n "$CC"; then + { $as_echo "$as_me:${as_lineno-$LINENO}: result: $CC" >&5 +$as_echo "$CC" >&6; } else - { echo "$as_me:$LINENO: result: no" >&5 -echo "${ECHO_T}no" >&6; } + { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 +$as_echo "no" >&6; } fi - ;; - cc) # Extract the first word of "c++", so it can be a program name with args. -set dummy c++; ac_word=$2 -{ echo "$as_me:$LINENO: checking for $ac_word" >&5 -echo $ECHO_N "checking for $ac_word... $ECHO_C" >&6; } -if test "${ac_cv_path_CXX+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 + +fi +if test -z "$ac_cv_prog_CC"; then + ac_ct_CC=$CC + # Extract the first word of "gcc", so it can be a program name with args. +set dummy gcc; ac_word=$2 +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 +$as_echo_n "checking for $ac_word... " >&6; } +if test "${ac_cv_prog_ac_ct_CC+set}" = set; then : + $as_echo_n "(cached) " >&6 else - case $CXX in - [\\/]* | ?:[\\/]*) - ac_cv_path_CXX="$CXX" # Let the user override the test with a path. - ;; - *) - as_save_IFS=$IFS; IFS=$PATH_SEPARATOR -for as_dir in notfound + if test -n "$ac_ct_CC"; then + ac_cv_prog_ac_ct_CC="$ac_ct_CC" # Let the user override the test. +else +as_save_IFS=$IFS; IFS=$PATH_SEPARATOR +for as_dir in $PATH do IFS=$as_save_IFS test -z "$as_dir" && as_dir=. - for ac_exec_ext in '' $ac_executable_extensions; do + for ac_exec_ext in '' $ac_executable_extensions; do if { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_test_x "$as_dir/$ac_word$ac_exec_ext"; }; then - ac_cv_path_CXX="$as_dir/$ac_word$ac_exec_ext" - echo "$as_me:$LINENO: found $as_dir/$ac_word$ac_exec_ext" >&5 + ac_cv_prog_ac_ct_CC="gcc" + $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 break 2 fi done -done + done IFS=$as_save_IFS - test -z "$ac_cv_path_CXX" && ac_cv_path_CXX="c++" - ;; -esac fi -CXX=$ac_cv_path_CXX -if test -n "$CXX"; then - { echo "$as_me:$LINENO: result: $CXX" >&5 -echo "${ECHO_T}$CXX" >&6; } +fi +ac_ct_CC=$ac_cv_prog_ac_ct_CC +if test -n "$ac_ct_CC"; then + { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_ct_CC" >&5 +$as_echo "$ac_ct_CC" >&6; } else - { echo "$as_me:$LINENO: result: no" >&5 -echo "${ECHO_T}no" >&6; } + { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 +$as_echo "no" >&6; } fi - ;; - esac - if test "$CXX" = "notfound" - then - CXX="" - fi + if test "x$ac_ct_CC" = x; then + CC="" + else + case $cross_compiling:$ac_tool_warned in +yes:) +{ $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: using cross tools not prefixed with host triplet" >&5 +$as_echo "$as_me: WARNING: using cross tools not prefixed with host triplet" >&2;} +ac_tool_warned=yes ;; +esac + CC=$ac_ct_CC + fi +else + CC="$ac_cv_prog_CC" fi -if test -z "$CXX" -then - for ac_prog in $CCC c++ g++ gcc CC cxx cc++ cl -do - # Extract the first word of "$ac_prog", so it can be a program name with args. -set dummy $ac_prog; ac_word=$2 -{ echo "$as_me:$LINENO: checking for $ac_word" >&5 -echo $ECHO_N "checking for $ac_word... $ECHO_C" >&6; } -if test "${ac_cv_prog_CXX+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 + +if test -z "$CC"; then + if test -n "$ac_tool_prefix"; then + # Extract the first word of "${ac_tool_prefix}cc", so it can be a program name with args. +set dummy ${ac_tool_prefix}cc; ac_word=$2 +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 +$as_echo_n "checking for $ac_word... " >&6; } +if test "${ac_cv_prog_CC+set}" = set; then : + $as_echo_n "(cached) " >&6 else - if test -n "$CXX"; then - ac_cv_prog_CXX="$CXX" # Let the user override the test. + if test -n "$CC"; then + ac_cv_prog_CC="$CC" # Let the user override the test. else as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $PATH do IFS=$as_save_IFS test -z "$as_dir" && as_dir=. - for ac_exec_ext in '' $ac_executable_extensions; do + for ac_exec_ext in '' $ac_executable_extensions; do if { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_test_x "$as_dir/$ac_word$ac_exec_ext"; }; then - ac_cv_prog_CXX="$ac_prog" - echo "$as_me:$LINENO: found $as_dir/$ac_word$ac_exec_ext" >&5 + ac_cv_prog_CC="${ac_tool_prefix}cc" + $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 break 2 fi done -done + done IFS=$as_save_IFS fi fi -CXX=$ac_cv_prog_CXX -if test -n "$CXX"; then - { echo "$as_me:$LINENO: result: $CXX" >&5 -echo "${ECHO_T}$CXX" >&6; } +CC=$ac_cv_prog_CC +if test -n "$CC"; then + { $as_echo "$as_me:${as_lineno-$LINENO}: result: $CC" >&5 +$as_echo "$CC" >&6; } else - { echo "$as_me:$LINENO: result: no" >&5 -echo "${ECHO_T}no" >&6; } + { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 +$as_echo "no" >&6; } fi - test -n "$CXX" && break + fi +fi +if test -z "$CC"; then + # Extract the first word of "cc", so it can be a program name with args. +set dummy cc; ac_word=$2 +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 +$as_echo_n "checking for $ac_word... " >&6; } +if test "${ac_cv_prog_CC+set}" = set; then : + $as_echo_n "(cached) " >&6 +else + if test -n "$CC"; then + ac_cv_prog_CC="$CC" # Let the user override the test. +else + ac_prog_rejected=no +as_save_IFS=$IFS; IFS=$PATH_SEPARATOR +for as_dir in $PATH +do + IFS=$as_save_IFS + test -z "$as_dir" && as_dir=. + for ac_exec_ext in '' $ac_executable_extensions; do + if { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_test_x "$as_dir/$ac_word$ac_exec_ext"; }; then + if test "$as_dir/$ac_word$ac_exec_ext" = "/usr/ucb/cc"; then + ac_prog_rejected=yes + continue + fi + ac_cv_prog_CC="cc" + $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 + break 2 + fi done -test -n "$CXX" || CXX="notfound" + done +IFS=$as_save_IFS - if test "$CXX" = "notfound" - then - CXX="" - fi +if test $ac_prog_rejected = yes; then + # We found a bogon in the path, so make sure we never use it. + set dummy $ac_cv_prog_CC + shift + if test $# != 0; then + # We chose a different compiler from the bogus one. + # However, it has the same basename, so the bogon will be chosen + # first if we set CC to just the basename; use the full file name. + shift + ac_cv_prog_CC="$as_dir/$ac_word${1+' '}$@" + fi +fi +fi +fi +CC=$ac_cv_prog_CC +if test -n "$CC"; then + { $as_echo "$as_me:${as_lineno-$LINENO}: result: $CC" >&5 +$as_echo "$CC" >&6; } +else + { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 +$as_echo "no" >&6; } fi -if test "$preset_cxx" != "$CXX" -then - { echo "$as_me:$LINENO: WARNING: - By default, distutils will build C++ extension modules with \"$CXX\". - If this is not intended, then set CXX on the configure command line. - " >&5 -echo "$as_me: WARNING: - By default, distutils will build C++ extension modules with \"$CXX\". - If this is not intended, then set CXX on the configure command line. - " >&2;} fi +if test -z "$CC"; then + if test -n "$ac_tool_prefix"; then + for ac_prog in cl.exe + do + # Extract the first word of "$ac_tool_prefix$ac_prog", so it can be a program name with args. +set dummy $ac_tool_prefix$ac_prog; ac_word=$2 +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 +$as_echo_n "checking for $ac_word... " >&6; } +if test "${ac_cv_prog_CC+set}" = set; then : + $as_echo_n "(cached) " >&6 +else + if test -n "$CC"; then + ac_cv_prog_CC="$CC" # Let the user override the test. +else +as_save_IFS=$IFS; IFS=$PATH_SEPARATOR +for as_dir in $PATH +do + IFS=$as_save_IFS + test -z "$as_dir" && as_dir=. + for ac_exec_ext in '' $ac_executable_extensions; do + if { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_test_x "$as_dir/$ac_word$ac_exec_ext"; }; then + ac_cv_prog_CC="$ac_tool_prefix$ac_prog" + $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 + break 2 + fi +done + done +IFS=$as_save_IFS +fi +fi +CC=$ac_cv_prog_CC +if test -n "$CC"; then + { $as_echo "$as_me:${as_lineno-$LINENO}: result: $CC" >&5 +$as_echo "$CC" >&6; } +else + { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 +$as_echo "no" >&6; } +fi -# checks for UNIX variants that set C preprocessor variables -ac_ext=c -ac_cpp='$CPP $CPPFLAGS' -ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5' -ac_link='$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5' -ac_compiler_gnu=$ac_cv_c_compiler_gnu -{ echo "$as_me:$LINENO: checking how to run the C preprocessor" >&5 -echo $ECHO_N "checking how to run the C preprocessor... $ECHO_C" >&6; } -# On Suns, sometimes $CPP names a directory. -if test -n "$CPP" && test -d "$CPP"; then - CPP= + test -n "$CC" && break + done fi -if test -z "$CPP"; then - if test "${ac_cv_prog_CPP+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 +if test -z "$CC"; then + ac_ct_CC=$CC + for ac_prog in cl.exe +do + # Extract the first word of "$ac_prog", so it can be a program name with args. +set dummy $ac_prog; ac_word=$2 +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 +$as_echo_n "checking for $ac_word... " >&6; } +if test "${ac_cv_prog_ac_ct_CC+set}" = set; then : + $as_echo_n "(cached) " >&6 else - # Double quotes because CPP needs to be expanded - for CPP in "$CC -E" "$CC -E -traditional-cpp" "/lib/cpp" - do - ac_preproc_ok=false -for ac_c_preproc_warn_flag in '' yes + if test -n "$ac_ct_CC"; then + ac_cv_prog_ac_ct_CC="$ac_ct_CC" # Let the user override the test. +else +as_save_IFS=$IFS; IFS=$PATH_SEPARATOR +for as_dir in $PATH do - # Use a header file that comes with gcc, so configuring glibc - # with a fresh cross-compiler works. - # Prefer to if __STDC__ is defined, since - # exists even on freestanding compilers. - # On the NeXT, cc -E runs the code through the compiler's parser, - # not just through cpp. "Syntax error" is here to catch this case. - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -#ifdef __STDC__ -# include -#else -# include -#endif - Syntax error -_ACEOF -if { (ac_try="$ac_cpp conftest.$ac_ext" + IFS=$as_save_IFS + test -z "$as_dir" && as_dir=. + for ac_exec_ext in '' $ac_executable_extensions; do + if { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_test_x "$as_dir/$ac_word$ac_exec_ext"; }; then + ac_cv_prog_ac_ct_CC="$ac_prog" + $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 + break 2 + fi +done + done +IFS=$as_save_IFS + +fi +fi +ac_ct_CC=$ac_cv_prog_ac_ct_CC +if test -n "$ac_ct_CC"; then + { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_ct_CC" >&5 +$as_echo "$ac_ct_CC" >&6; } +else + { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 +$as_echo "no" >&6; } +fi + + + test -n "$ac_ct_CC" && break +done + + if test "x$ac_ct_CC" = x; then + CC="" + else + case $cross_compiling:$ac_tool_warned in +yes:) +{ $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: using cross tools not prefixed with host triplet" >&5 +$as_echo "$as_me: WARNING: using cross tools not prefixed with host triplet" >&2;} +ac_tool_warned=yes ;; +esac + CC=$ac_ct_CC + fi +fi + +fi + + +test -z "$CC" && { { $as_echo "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5 +$as_echo "$as_me: error: in \`$ac_pwd':" >&2;} +as_fn_error "no acceptable C compiler found in \$PATH +See \`config.log' for more details." "$LINENO" 5; } + +# Provide some information about the compiler. +$as_echo "$as_me:${as_lineno-$LINENO}: checking for C compiler version" >&5 +set X $ac_compile +ac_compiler=$2 +for ac_option in --version -v -V -qversion; do + { { ac_try="$ac_compiler $ac_option >&5" case "(($ac_try" in *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_cpp conftest.$ac_ext") 2>conftest.er1 +eval ac_try_echo="\"\$as_me:${as_lineno-$LINENO}: $ac_try_echo\"" +$as_echo "$ac_try_echo"; } >&5 + (eval "$ac_compiler $ac_option >&5") 2>conftest.err ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } >/dev/null && { - test -z "$ac_c_preproc_warn_flag$ac_c_werror_flag" || - test ! -s conftest.err - }; then - : -else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 + if test -s conftest.err; then + sed '10a\ +... rest of stderr output deleted ... + 10q' conftest.err >conftest.er1 + cat conftest.er1 >&5 + fi + rm -f conftest.er1 conftest.err + $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 + test $ac_status = 0; } +done - # Broken: fails on valid input. -continue -fi +cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ -rm -f conftest.err conftest.$ac_ext +int +main () +{ - # OK, works on sane cases. Now check whether nonexistent headers - # can be detected and how. - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -#include + ; + return 0; +} _ACEOF -if { (ac_try="$ac_cpp conftest.$ac_ext" +ac_clean_files_save=$ac_clean_files +ac_clean_files="$ac_clean_files a.out a.out.dSYM a.exe b.out" +# Try to create an executable without -o first, disregard a.out. +# It will help us diagnose broken compilers, and finding out an intuition +# of exeext. +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking whether the C compiler works" >&5 +$as_echo_n "checking whether the C compiler works... " >&6; } +ac_link_default=`$as_echo "$ac_link" | sed 's/ -o *conftest[^ ]*//'` + +# The possible output files: +ac_files="a.out conftest.exe conftest a.exe a_out.exe b.out conftest.*" + +ac_rmfiles= +for ac_file in $ac_files +do + case $ac_file in + *.$ac_ext | *.xcoff | *.tds | *.d | *.pdb | *.xSYM | *.bb | *.bbg | *.map | *.inf | *.dSYM | *.o | *.obj ) ;; + * ) ac_rmfiles="$ac_rmfiles $ac_file";; + esac +done +rm -f $ac_rmfiles + +if { { ac_try="$ac_link_default" case "(($ac_try" in *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_cpp conftest.$ac_ext") 2>conftest.er1 +eval ac_try_echo="\"\$as_me:${as_lineno-$LINENO}: $ac_try_echo\"" +$as_echo "$ac_try_echo"; } >&5 + (eval "$ac_link_default") 2>&5 ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } >/dev/null && { - test -z "$ac_c_preproc_warn_flag$ac_c_werror_flag" || - test ! -s conftest.err - }; then - # Broken: success on invalid input. -continue -else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 + $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 + test $ac_status = 0; }; then : + # Autoconf-2.13 could set the ac_cv_exeext variable to `no'. +# So ignore a value of `no', otherwise this would lead to `EXEEXT = no' +# in a Makefile. We should not override ac_cv_exeext if it was cached, +# so that the user can short-circuit this test for compilers unknown to +# Autoconf. +for ac_file in $ac_files '' +do + test -f "$ac_file" || continue + case $ac_file in + *.$ac_ext | *.xcoff | *.tds | *.d | *.pdb | *.xSYM | *.bb | *.bbg | *.map | *.inf | *.dSYM | *.o | *.obj ) + ;; + [ab].out ) + # We found the default executable, but exeext='' is most + # certainly right. + break;; + *.* ) + if test "${ac_cv_exeext+set}" = set && test "$ac_cv_exeext" != no; + then :; else + ac_cv_exeext=`expr "$ac_file" : '[^.]*\(\..*\)'` + fi + # We set ac_cv_exeext here because the later test for it is not + # safe: cross compilers may not add the suffix if given an `-o' + # argument, so we may need to know it at that point already. + # Even if this section looks crufty: it has the advantage of + # actually working. + break;; + * ) + break;; + esac +done +test "$ac_cv_exeext" = no && ac_cv_exeext= - # Passes both tests. -ac_preproc_ok=: -break +else + ac_file='' fi +if test -z "$ac_file"; then : + { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 +$as_echo "no" >&6; } +$as_echo "$as_me: failed program was:" >&5 +sed 's/^/| /' conftest.$ac_ext >&5 + +{ { $as_echo "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5 +$as_echo "$as_me: error: in \`$ac_pwd':" >&2;} +{ as_fn_set_status 77 +as_fn_error "C compiler cannot create executables +See \`config.log' for more details." "$LINENO" 5; }; } +else + { $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +$as_echo "yes" >&6; } +fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for C compiler default output file name" >&5 +$as_echo_n "checking for C compiler default output file name... " >&6; } +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_file" >&5 +$as_echo "$ac_file" >&6; } +ac_exeext=$ac_cv_exeext -rm -f conftest.err conftest.$ac_ext - +rm -f -r a.out a.out.dSYM a.exe conftest$ac_cv_exeext b.out +ac_clean_files=$ac_clean_files_save +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for suffix of executables" >&5 +$as_echo_n "checking for suffix of executables... " >&6; } +if { { ac_try="$ac_link" +case "(($ac_try" in + *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; + *) ac_try_echo=$ac_try;; +esac +eval ac_try_echo="\"\$as_me:${as_lineno-$LINENO}: $ac_try_echo\"" +$as_echo "$ac_try_echo"; } >&5 + (eval "$ac_link") 2>&5 + ac_status=$? + $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 + test $ac_status = 0; }; then : + # If both `conftest.exe' and `conftest' are `present' (well, observable) +# catch `conftest.exe'. For instance with Cygwin, `ls conftest' will +# work properly (i.e., refer to `conftest.exe'), while it won't with +# `rm'. +for ac_file in conftest.exe conftest conftest.*; do + test -f "$ac_file" || continue + case $ac_file in + *.$ac_ext | *.xcoff | *.tds | *.d | *.pdb | *.xSYM | *.bb | *.bbg | *.map | *.inf | *.dSYM | *.o | *.obj ) ;; + *.* ) ac_cv_exeext=`expr "$ac_file" : '[^.]*\(\..*\)'` + break;; + * ) break;; + esac done -# Because of `break', _AC_PREPROC_IFELSE's cleaning code was skipped. -rm -f conftest.err conftest.$ac_ext -if $ac_preproc_ok; then - break -fi - - done - ac_cv_prog_CPP=$CPP - -fi - CPP=$ac_cv_prog_CPP else - ac_cv_prog_CPP=$CPP -fi -{ echo "$as_me:$LINENO: result: $CPP" >&5 -echo "${ECHO_T}$CPP" >&6; } -ac_preproc_ok=false -for ac_c_preproc_warn_flag in '' yes -do - # Use a header file that comes with gcc, so configuring glibc - # with a fresh cross-compiler works. - # Prefer to if __STDC__ is defined, since - # exists even on freestanding compilers. - # On the NeXT, cc -E runs the code through the compiler's parser, - # not just through cpp. "Syntax error" is here to catch this case. - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF + { { $as_echo "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5 +$as_echo "$as_me: error: in \`$ac_pwd':" >&2;} +as_fn_error "cannot compute suffix of executables: cannot compile and link +See \`config.log' for more details." "$LINENO" 5; } +fi +rm -f conftest conftest$ac_cv_exeext +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_exeext" >&5 +$as_echo "$ac_cv_exeext" >&6; } + +rm -f conftest.$ac_ext +EXEEXT=$ac_cv_exeext +ac_exeext=$EXEEXT +cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ -#ifdef __STDC__ -# include -#else -# include -#endif - Syntax error +#include +int +main () +{ +FILE *f = fopen ("conftest.out", "w"); + return ferror (f) || fclose (f) != 0; + + ; + return 0; +} _ACEOF -if { (ac_try="$ac_cpp conftest.$ac_ext" +ac_clean_files="$ac_clean_files conftest.out" +# Check that the compiler produces executables we can run. If not, either +# the compiler is broken, or we cross compile. +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking whether we are cross compiling" >&5 +$as_echo_n "checking whether we are cross compiling... " >&6; } +if test "$cross_compiling" != yes; then + { { ac_try="$ac_link" case "(($ac_try" in *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_cpp conftest.$ac_ext") 2>conftest.er1 +eval ac_try_echo="\"\$as_me:${as_lineno-$LINENO}: $ac_try_echo\"" +$as_echo "$ac_try_echo"; } >&5 + (eval "$ac_link") 2>&5 ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } >/dev/null && { - test -z "$ac_c_preproc_warn_flag$ac_c_werror_flag" || - test ! -s conftest.err - }; then - : -else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - # Broken: fails on valid input. -continue + $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 + test $ac_status = 0; } + if { ac_try='./conftest$ac_cv_exeext' + { { case "(($ac_try" in + *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; + *) ac_try_echo=$ac_try;; +esac +eval ac_try_echo="\"\$as_me:${as_lineno-$LINENO}: $ac_try_echo\"" +$as_echo "$ac_try_echo"; } >&5 + (eval "$ac_try") 2>&5 + ac_status=$? + $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 + test $ac_status = 0; }; }; then + cross_compiling=no + else + if test "$cross_compiling" = maybe; then + cross_compiling=yes + else + { { $as_echo "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5 +$as_echo "$as_me: error: in \`$ac_pwd':" >&2;} +as_fn_error "cannot run C compiled programs. +If you meant to cross compile, use \`--host'. +See \`config.log' for more details." "$LINENO" 5; } + fi + fi fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $cross_compiling" >&5 +$as_echo "$cross_compiling" >&6; } -rm -f conftest.err conftest.$ac_ext - - # OK, works on sane cases. Now check whether nonexistent headers - # can be detected and how. - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF +rm -f conftest.$ac_ext conftest$ac_cv_exeext conftest.out +ac_clean_files=$ac_clean_files_save +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for suffix of object files" >&5 +$as_echo_n "checking for suffix of object files... " >&6; } +if test "${ac_cv_objext+set}" = set; then : + $as_echo_n "(cached) " >&6 +else + cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ -#include + +int +main () +{ + + ; + return 0; +} _ACEOF -if { (ac_try="$ac_cpp conftest.$ac_ext" +rm -f conftest.o conftest.obj +if { { ac_try="$ac_compile" case "(($ac_try" in *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_cpp conftest.$ac_ext") 2>conftest.er1 +eval ac_try_echo="\"\$as_me:${as_lineno-$LINENO}: $ac_try_echo\"" +$as_echo "$ac_try_echo"; } >&5 + (eval "$ac_compile") 2>&5 ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } >/dev/null && { - test -z "$ac_c_preproc_warn_flag$ac_c_werror_flag" || - test ! -s conftest.err - }; then - # Broken: success on invalid input. -continue + $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 + test $ac_status = 0; }; then : + for ac_file in conftest.o conftest.obj conftest.*; do + test -f "$ac_file" || continue; + case $ac_file in + *.$ac_ext | *.xcoff | *.tds | *.d | *.pdb | *.xSYM | *.bb | *.bbg | *.map | *.inf | *.dSYM ) ;; + *) ac_cv_objext=`expr "$ac_file" : '.*\.\(.*\)'` + break;; + esac +done else - echo "$as_me: failed program was:" >&5 + $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 - # Passes both tests. -ac_preproc_ok=: -break +{ { $as_echo "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5 +$as_echo "$as_me: error: in \`$ac_pwd':" >&2;} +as_fn_error "cannot compute suffix of object files: cannot compile +See \`config.log' for more details." "$LINENO" 5; } fi - -rm -f conftest.err conftest.$ac_ext - -done -# Because of `break', _AC_PREPROC_IFELSE's cleaning code was skipped. -rm -f conftest.err conftest.$ac_ext -if $ac_preproc_ok; then - : -else - { { echo "$as_me:$LINENO: error: C preprocessor \"$CPP\" fails sanity check -See \`config.log' for more details." >&5 -echo "$as_me: error: C preprocessor \"$CPP\" fails sanity check -See \`config.log' for more details." >&2;} - { (exit 1); exit 1; }; } +rm -f conftest.$ac_cv_objext conftest.$ac_ext fi - -ac_ext=c -ac_cpp='$CPP $CPPFLAGS' -ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5' -ac_link='$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5' -ac_compiler_gnu=$ac_cv_c_compiler_gnu - - -{ echo "$as_me:$LINENO: checking for grep that handles long lines and -e" >&5 -echo $ECHO_N "checking for grep that handles long lines and -e... $ECHO_C" >&6; } -if test "${ac_cv_path_GREP+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 -else - # Extract the first word of "grep ggrep" to use in msg output -if test -z "$GREP"; then -set dummy grep ggrep; ac_prog_name=$2 -if test "${ac_cv_path_GREP+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_objext" >&5 +$as_echo "$ac_cv_objext" >&6; } +OBJEXT=$ac_cv_objext +ac_objext=$OBJEXT +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking whether we are using the GNU C compiler" >&5 +$as_echo_n "checking whether we are using the GNU C compiler... " >&6; } +if test "${ac_cv_c_compiler_gnu+set}" = set; then : + $as_echo_n "(cached) " >&6 else - ac_path_GREP_found=false -# Loop through the user's path and test for each of PROGNAME-LIST -as_save_IFS=$IFS; IFS=$PATH_SEPARATOR -for as_dir in $PATH$PATH_SEPARATOR/usr/xpg4/bin -do - IFS=$as_save_IFS - test -z "$as_dir" && as_dir=. - for ac_prog in grep ggrep; do - for ac_exec_ext in '' $ac_executable_extensions; do - ac_path_GREP="$as_dir/$ac_prog$ac_exec_ext" - { test -f "$ac_path_GREP" && $as_test_x "$ac_path_GREP"; } || continue - # Check for GNU ac_path_GREP and select it if it is found. - # Check for GNU $ac_path_GREP -case `"$ac_path_GREP" --version 2>&1` in -*GNU*) - ac_cv_path_GREP="$ac_path_GREP" ac_path_GREP_found=:;; -*) - ac_count=0 - echo $ECHO_N "0123456789$ECHO_C" >"conftest.in" - while : - do - cat "conftest.in" "conftest.in" >"conftest.tmp" - mv "conftest.tmp" "conftest.in" - cp "conftest.in" "conftest.nl" - echo 'GREP' >> "conftest.nl" - "$ac_path_GREP" -e 'GREP$' -e '-(cannot match)-' < "conftest.nl" >"conftest.out" 2>/dev/null || break - diff "conftest.out" "conftest.nl" >/dev/null 2>&1 || break - ac_count=`expr $ac_count + 1` - if test $ac_count -gt ${ac_path_GREP_max-0}; then - # Best one so far, save it but keep looking for a better one - ac_cv_path_GREP="$ac_path_GREP" - ac_path_GREP_max=$ac_count - fi - # 10*(2^10) chars as input seems more than enough - test $ac_count -gt 10 && break - done - rm -f conftest.in conftest.tmp conftest.nl conftest.out;; -esac - - - $ac_path_GREP_found && break 3 - done -done - -done -IFS=$as_save_IFS + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ +int +main () +{ +#ifndef __GNUC__ + choke me +#endif + ; + return 0; +} +_ACEOF +if ac_fn_c_try_compile "$LINENO"; then : + ac_compiler_gnu=yes +else + ac_compiler_gnu=no fi +rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext +ac_cv_c_compiler_gnu=$ac_compiler_gnu -GREP="$ac_cv_path_GREP" -if test -z "$GREP"; then - { { echo "$as_me:$LINENO: error: no acceptable $ac_prog_name could be found in $PATH$PATH_SEPARATOR/usr/xpg4/bin" >&5 -echo "$as_me: error: no acceptable $ac_prog_name could be found in $PATH$PATH_SEPARATOR/usr/xpg4/bin" >&2;} - { (exit 1); exit 1; }; } fi - +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_c_compiler_gnu" >&5 +$as_echo "$ac_cv_c_compiler_gnu" >&6; } +if test $ac_compiler_gnu = yes; then + GCC=yes else - ac_cv_path_GREP=$GREP + GCC= fi +ac_test_CFLAGS=${CFLAGS+set} +ac_save_CFLAGS=$CFLAGS +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking whether $CC accepts -g" >&5 +$as_echo_n "checking whether $CC accepts -g... " >&6; } +if test "${ac_cv_prog_cc_g+set}" = set; then : + $as_echo_n "(cached) " >&6 +else + ac_save_c_werror_flag=$ac_c_werror_flag + ac_c_werror_flag=yes + ac_cv_prog_cc_g=no + CFLAGS="-g" + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ +int +main () +{ -fi -{ echo "$as_me:$LINENO: result: $ac_cv_path_GREP" >&5 -echo "${ECHO_T}$ac_cv_path_GREP" >&6; } - GREP="$ac_cv_path_GREP" + ; + return 0; +} +_ACEOF +if ac_fn_c_try_compile "$LINENO"; then : + ac_cv_prog_cc_g=yes +else + CFLAGS="" + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ +int +main () +{ -{ echo "$as_me:$LINENO: checking for egrep" >&5 -echo $ECHO_N "checking for egrep... $ECHO_C" >&6; } -if test "${ac_cv_path_EGREP+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 -else - if echo a | $GREP -E '(a|b)' >/dev/null 2>&1 - then ac_cv_path_EGREP="$GREP -E" - else - # Extract the first word of "egrep" to use in msg output -if test -z "$EGREP"; then -set dummy egrep; ac_prog_name=$2 -if test "${ac_cv_path_EGREP+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 -else - ac_path_EGREP_found=false -# Loop through the user's path and test for each of PROGNAME-LIST -as_save_IFS=$IFS; IFS=$PATH_SEPARATOR -for as_dir in $PATH$PATH_SEPARATOR/usr/xpg4/bin -do - IFS=$as_save_IFS - test -z "$as_dir" && as_dir=. - for ac_prog in egrep; do - for ac_exec_ext in '' $ac_executable_extensions; do - ac_path_EGREP="$as_dir/$ac_prog$ac_exec_ext" - { test -f "$ac_path_EGREP" && $as_test_x "$ac_path_EGREP"; } || continue - # Check for GNU ac_path_EGREP and select it if it is found. - # Check for GNU $ac_path_EGREP -case `"$ac_path_EGREP" --version 2>&1` in -*GNU*) - ac_cv_path_EGREP="$ac_path_EGREP" ac_path_EGREP_found=:;; -*) - ac_count=0 - echo $ECHO_N "0123456789$ECHO_C" >"conftest.in" - while : - do - cat "conftest.in" "conftest.in" >"conftest.tmp" - mv "conftest.tmp" "conftest.in" - cp "conftest.in" "conftest.nl" - echo 'EGREP' >> "conftest.nl" - "$ac_path_EGREP" 'EGREP$' < "conftest.nl" >"conftest.out" 2>/dev/null || break - diff "conftest.out" "conftest.nl" >/dev/null 2>&1 || break - ac_count=`expr $ac_count + 1` - if test $ac_count -gt ${ac_path_EGREP_max-0}; then - # Best one so far, save it but keep looking for a better one - ac_cv_path_EGREP="$ac_path_EGREP" - ac_path_EGREP_max=$ac_count - fi - # 10*(2^10) chars as input seems more than enough - test $ac_count -gt 10 && break - done - rm -f conftest.in conftest.tmp conftest.nl conftest.out;; -esac - - - $ac_path_EGREP_found && break 3 - done -done + ; + return 0; +} +_ACEOF +if ac_fn_c_try_compile "$LINENO"; then : -done -IFS=$as_save_IFS +else + ac_c_werror_flag=$ac_save_c_werror_flag + CFLAGS="-g" + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ +int +main () +{ + ; + return 0; +} +_ACEOF +if ac_fn_c_try_compile "$LINENO"; then : + ac_cv_prog_cc_g=yes fi - -EGREP="$ac_cv_path_EGREP" -if test -z "$EGREP"; then - { { echo "$as_me:$LINENO: error: no acceptable $ac_prog_name could be found in $PATH$PATH_SEPARATOR/usr/xpg4/bin" >&5 -echo "$as_me: error: no acceptable $ac_prog_name could be found in $PATH$PATH_SEPARATOR/usr/xpg4/bin" >&2;} - { (exit 1); exit 1; }; } +rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext fi - -else - ac_cv_path_EGREP=$EGREP +rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext fi - - - fi +rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext + ac_c_werror_flag=$ac_save_c_werror_flag fi -{ echo "$as_me:$LINENO: result: $ac_cv_path_EGREP" >&5 -echo "${ECHO_T}$ac_cv_path_EGREP" >&6; } - EGREP="$ac_cv_path_EGREP" +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_prog_cc_g" >&5 +$as_echo "$ac_cv_prog_cc_g" >&6; } +if test "$ac_test_CFLAGS" = set; then + CFLAGS=$ac_save_CFLAGS +elif test $ac_cv_prog_cc_g = yes; then + if test "$GCC" = yes; then + CFLAGS="-g -O2" + else + CFLAGS="-g" + fi +else + if test "$GCC" = yes; then + CFLAGS="-O2" + else + CFLAGS= + fi +fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $CC option to accept ISO C89" >&5 +$as_echo_n "checking for $CC option to accept ISO C89... " >&6; } +if test "${ac_cv_prog_cc_c89+set}" = set; then : + $as_echo_n "(cached) " >&6 +else + ac_cv_prog_cc_c89=no +ac_save_CC=$CC +cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ +#include +#include +#include +#include +/* Most of the following tests are stolen from RCS 5.7's src/conf.sh. */ +struct buf { int x; }; +FILE * (*rcsopen) (struct buf *, struct stat *, int); +static char *e (p, i) + char **p; + int i; +{ + return p[i]; +} +static char *f (char * (*g) (char **, int), char **p, ...) +{ + char *s; + va_list v; + va_start (v,p); + s = g (p, va_arg (v,int)); + va_end (v); + return s; +} +/* OSF 4.0 Compaq cc is some sort of almost-ANSI by default. It has + function prototypes and stuff, but not '\xHH' hex character constants. + These don't provoke an error unfortunately, instead are silently treated + as 'x'. The following induces an error, until -std is added to get + proper ANSI mode. Curiously '\x00'!='x' always comes out true, for an + array size at least. It's necessary to write '\x00'==0 to get something + that's true only with -std. */ +int osf4_cc_array ['\x00' == 0 ? 1 : -1]; +/* IBM C 6 for AIX is almost-ANSI by default, but it replaces macro parameters + inside strings and character constants. */ +#define FOO(x) 'x' +int xlc6_cc_array[FOO(a) == 'x' ? 1 : -1]; -{ echo "$as_me:$LINENO: checking for AIX" >&5 -echo $ECHO_N "checking for AIX... $ECHO_C" >&6; } -cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ +int test (int i, double x); +struct s1 {int (*f) (int a);}; +struct s2 {int (*f) (double a);}; +int pairnames (int, char **, FILE *(*)(struct buf *, struct stat *, int), int, int); +int argc; +char **argv; +int +main () +{ +return f (e, argv, 0) != argv[0] || f (e, argv, 1) != argv[1]; + ; + return 0; +} _ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -#ifdef _AIX - yes -#endif +for ac_arg in '' -qlanglvl=extc89 -qlanglvl=ansi -std \ + -Ae "-Aa -D_HPUX_SOURCE" "-Xc -D__EXTENSIONS__" +do + CC="$ac_save_CC $ac_arg" + if ac_fn_c_try_compile "$LINENO"; then : + ac_cv_prog_cc_c89=$ac_arg +fi +rm -f core conftest.err conftest.$ac_objext + test "x$ac_cv_prog_cc_c89" != "xno" && break +done +rm -f conftest.$ac_ext +CC=$ac_save_CC -_ACEOF -if (eval "$ac_cpp conftest.$ac_ext") 2>&5 | - $EGREP "yes" >/dev/null 2>&1; then - { echo "$as_me:$LINENO: result: yes" >&5 -echo "${ECHO_T}yes" >&6; } -cat >>confdefs.h <<\_ACEOF -#define _ALL_SOURCE 1 -_ACEOF +fi +# AC_CACHE_VAL +case "x$ac_cv_prog_cc_c89" in + x) + { $as_echo "$as_me:${as_lineno-$LINENO}: result: none needed" >&5 +$as_echo "none needed" >&6; } ;; + xno) + { $as_echo "$as_me:${as_lineno-$LINENO}: result: unsupported" >&5 +$as_echo "unsupported" >&6; } ;; + *) + CC="$CC $ac_cv_prog_cc_c89" + { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_prog_cc_c89" >&5 +$as_echo "$ac_cv_prog_cc_c89" >&6; } ;; +esac +if test "x$ac_cv_prog_cc_c89" != xno; then : -else - { echo "$as_me:$LINENO: result: no" >&5 -echo "${ECHO_T}no" >&6; } fi -rm -f conftest* +ac_ext=c +ac_cpp='$CPP $CPPFLAGS' +ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5' +ac_link='$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5' +ac_compiler_gnu=$ac_cv_c_compiler_gnu + +if test ! -z "$preset_cflags" +then + CFLAGS=$preset_cflags +fi -# Check for unsupported systems -case $ac_sys_system/$ac_sys_release in -atheos*|Linux*/1*) - echo This system \($ac_sys_system/$ac_sys_release\) is no longer supported. - echo See README for details. - exit 1;; -esac +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for --with-cxx-main=" >&5 +$as_echo_n "checking for --with-cxx-main=... " >&6; } -{ echo "$as_me:$LINENO: checking for --with-suffix" >&5 -echo $ECHO_N "checking for --with-suffix... $ECHO_C" >&6; } +# Check whether --with-cxx_main was given. +if test "${with_cxx_main+set}" = set; then : + withval=$with_cxx_main; -# Check whether --with-suffix was given. -if test "${with_suffix+set}" = set; then - withval=$with_suffix; case $withval in - no) EXEEXT=;; - yes) EXEEXT=.exe;; - *) EXEEXT=$withval;; + no) with_cxx_main=no + MAINCC='$(CC)';; + yes) with_cxx_main=yes + MAINCC='$(CXX)';; + *) with_cxx_main=yes + MAINCC=$withval + if test -z "$CXX" + then + CXX=$withval + fi;; esac -fi - -{ echo "$as_me:$LINENO: result: $EXEEXT" >&5 -echo "${ECHO_T}$EXEEXT" >&6; } +else -# Test whether we're running on a non-case-sensitive system, in which -# case we give a warning if no ext is given + with_cxx_main=no + MAINCC='$(CC)' -{ echo "$as_me:$LINENO: checking for case-insensitive build directory" >&5 -echo $ECHO_N "checking for case-insensitive build directory... $ECHO_C" >&6; } -if test ! -d CaseSensitiveTestDir; then -mkdir CaseSensitiveTestDir fi -if test -d casesensitivetestdir +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $with_cxx_main" >&5 +$as_echo "$with_cxx_main" >&6; } + +preset_cxx="$CXX" +if test -z "$CXX" then - { echo "$as_me:$LINENO: result: yes" >&5 -echo "${ECHO_T}yes" >&6; } - BUILDEXEEXT=.exe + case "$CC" in + gcc) # Extract the first word of "g++", so it can be a program name with args. +set dummy g++; ac_word=$2 +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 +$as_echo_n "checking for $ac_word... " >&6; } +if test "${ac_cv_path_CXX+set}" = set; then : + $as_echo_n "(cached) " >&6 else - { echo "$as_me:$LINENO: result: no" >&5 -echo "${ECHO_T}no" >&6; } - BUILDEXEEXT=$EXEEXT -fi -rmdir CaseSensitiveTestDir - -case $MACHDEP in -bsdos*) - case $CC in - gcc) CC="$CC -D_HAVE_BSDI";; - esac;; -esac - -case $ac_sys_system in -hp*|HP*) - case $CC in - cc|*/cc) CC="$CC -Ae";; - esac;; -SunOS*) - # Some functions have a prototype only with that define, e.g. confstr - -cat >>confdefs.h <<\_ACEOF -#define __EXTENSIONS__ 1 -_ACEOF + case $CXX in + [\\/]* | ?:[\\/]*) + ac_cv_path_CXX="$CXX" # Let the user override the test with a path. + ;; + *) + as_save_IFS=$IFS; IFS=$PATH_SEPARATOR +for as_dir in notfound +do + IFS=$as_save_IFS + test -z "$as_dir" && as_dir=. + for ac_exec_ext in '' $ac_executable_extensions; do + if { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_test_x "$as_dir/$ac_word$ac_exec_ext"; }; then + ac_cv_path_CXX="$as_dir/$ac_word$ac_exec_ext" + $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 + break 2 + fi +done + done +IFS=$as_save_IFS - ;; + test -z "$ac_cv_path_CXX" && ac_cv_path_CXX="g++" + ;; esac - - - -{ echo "$as_me:$LINENO: checking LIBRARY" >&5 -echo $ECHO_N "checking LIBRARY... $ECHO_C" >&6; } -if test -z "$LIBRARY" -then - LIBRARY='libpython$(VERSION).a' fi -{ echo "$as_me:$LINENO: result: $LIBRARY" >&5 -echo "${ECHO_T}$LIBRARY" >&6; } +CXX=$ac_cv_path_CXX +if test -n "$CXX"; then + { $as_echo "$as_me:${as_lineno-$LINENO}: result: $CXX" >&5 +$as_echo "$CXX" >&6; } +else + { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 +$as_echo "no" >&6; } +fi -# LDLIBRARY is the name of the library to link against (as opposed to the -# name of the library into which to insert object files). BLDLIBRARY is also -# the library to link against, usually. On Mac OS X frameworks, BLDLIBRARY -# is blank as the main program is not linked directly against LDLIBRARY. -# LDLIBRARYDIR is the path to LDLIBRARY, which is made in a subdirectory. On -# systems without shared libraries, LDLIBRARY is the same as LIBRARY -# (defined in the Makefiles). On Cygwin LDLIBRARY is the import library, -# DLLLIBRARY is the shared (i.e., DLL) library. -# -# RUNSHARED is used to run shared python without installed libraries -# -# INSTSONAME is the name of the shared library that will be use to install -# on the system - some systems like version suffix, others don't - - - - - - -LDLIBRARY="$LIBRARY" -BLDLIBRARY='$(LDLIBRARY)' -INSTSONAME='$(LDLIBRARY)' -DLLLIBRARY='' -LDLIBRARYDIR='' -RUNSHARED='' - -# LINKCC is the command that links the python executable -- default is $(CC). -# If CXX is set, and if it is needed to link a main function that was -# compiled with CXX, LINKCC is CXX instead. Always using CXX is undesirable: -# python might then depend on the C++ runtime -# This is altered for AIX in order to build the export list before -# linking. - -{ echo "$as_me:$LINENO: checking LINKCC" >&5 -echo $ECHO_N "checking LINKCC... $ECHO_C" >&6; } -if test -z "$LINKCC" -then - LINKCC='$(PURIFY) $(MAINCC)' - case $ac_sys_system in - AIX*) - exp_extra="\"\"" - if test $ac_sys_release -ge 5 -o \ - $ac_sys_release -eq 4 -a `uname -r` -ge 2 ; then - exp_extra="." - fi - LINKCC="\$(srcdir)/Modules/makexp_aix Modules/python.exp $exp_extra \$(LIBRARY); $LINKCC";; - QNX*) - # qcc must be used because the other compilers do not - # support -N. - LINKCC=qcc;; - esac -fi -{ echo "$as_me:$LINENO: result: $LINKCC" >&5 -echo "${ECHO_T}$LINKCC" >&6; } - -# GNULD is set to "yes" if the GNU linker is used. If this goes wrong -# make sure we default having it set to "no": this is used by -# distutils.unixccompiler to know if it should add --enable-new-dtags -# to linker command lines, and failing to detect GNU ld simply results -# in the same bahaviour as before. - -{ echo "$as_me:$LINENO: checking for GNU ld" >&5 -echo $ECHO_N "checking for GNU ld... $ECHO_C" >&6; } -ac_prog=ld -if test "$GCC" = yes; then - ac_prog=`$CC -print-prog-name=ld` -fi -case `"$ac_prog" -V 2>&1 < /dev/null` in - *GNU*) - GNULD=yes;; - *) - GNULD=no;; -esac -{ echo "$as_me:$LINENO: result: $GNULD" >&5 -echo "${ECHO_T}$GNULD" >&6; } - -{ echo "$as_me:$LINENO: checking for --enable-shared" >&5 -echo $ECHO_N "checking for --enable-shared... $ECHO_C" >&6; } -# Check whether --enable-shared was given. -if test "${enable_shared+set}" = set; then - enableval=$enable_shared; -fi - - -if test -z "$enable_shared" -then - case $ac_sys_system in - CYGWIN* | atheos*) - enable_shared="yes";; + ;; + cc) # Extract the first word of "c++", so it can be a program name with args. +set dummy c++; ac_word=$2 +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 +$as_echo_n "checking for $ac_word... " >&6; } +if test "${ac_cv_path_CXX+set}" = set; then : + $as_echo_n "(cached) " >&6 +else + case $CXX in + [\\/]* | ?:[\\/]*) + ac_cv_path_CXX="$CXX" # Let the user override the test with a path. + ;; *) - enable_shared="no";; - esac -fi -{ echo "$as_me:$LINENO: result: $enable_shared" >&5 -echo "${ECHO_T}$enable_shared" >&6; } + as_save_IFS=$IFS; IFS=$PATH_SEPARATOR +for as_dir in notfound +do + IFS=$as_save_IFS + test -z "$as_dir" && as_dir=. + for ac_exec_ext in '' $ac_executable_extensions; do + if { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_test_x "$as_dir/$ac_word$ac_exec_ext"; }; then + ac_cv_path_CXX="$as_dir/$ac_word$ac_exec_ext" + $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 + break 2 + fi +done + done +IFS=$as_save_IFS -{ echo "$as_me:$LINENO: checking for --enable-profiling" >&5 -echo $ECHO_N "checking for --enable-profiling... $ECHO_C" >&6; } -# Check whether --enable-profiling was given. -if test "${enable_profiling+set}" = set; then - enableval=$enable_profiling; ac_save_cc="$CC" - CC="$CC -pg" - if test "$cross_compiling" = yes; then - ac_enable_profiling="no" -else - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -int main() { return 0; } -_ACEOF -rm -f conftest$ac_exeext -if { (ac_try="$ac_link" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_link") 2>&5 - ac_status=$? - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { ac_try='./conftest$ac_exeext' - { (case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; + test -z "$ac_cv_path_CXX" && ac_cv_path_CXX="c++" + ;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_try") 2>&5 - ac_status=$? - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); }; }; then - ac_enable_profiling="yes" -else - echo "$as_me: program exited with status $ac_status" >&5 -echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - -( exit $ac_status ) -ac_enable_profiling="no" -fi -rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext conftest.$ac_objext conftest.$ac_ext -fi - - - CC="$ac_save_cc" fi - -{ echo "$as_me:$LINENO: result: $ac_enable_profiling" >&5 -echo "${ECHO_T}$ac_enable_profiling" >&6; } - -case "$ac_enable_profiling" in - "yes") - BASECFLAGS="-pg $BASECFLAGS" - LDFLAGS="-pg $LDFLAGS" - ;; -esac - -{ echo "$as_me:$LINENO: checking LDLIBRARY" >&5 -echo $ECHO_N "checking LDLIBRARY... $ECHO_C" >&6; } - -# MacOSX framework builds need more magic. LDLIBRARY is the dynamic -# library that we build, but we do not want to link against it (we -# will find it with a -framework option). For this reason there is an -# extra variable BLDLIBRARY against which Python and the extension -# modules are linked, BLDLIBRARY. This is normally the same as -# LDLIBRARY, but empty for MacOSX framework builds. -if test "$enable_framework" -then - LDLIBRARY='$(PYTHONFRAMEWORKDIR)/Versions/$(VERSION)/$(PYTHONFRAMEWORK)' - RUNSHARED=DYLD_FRAMEWORK_PATH="`pwd`:$DYLD_FRAMEWORK_PATH" - BLDLIBRARY='' +CXX=$ac_cv_path_CXX +if test -n "$CXX"; then + { $as_echo "$as_me:${as_lineno-$LINENO}: result: $CXX" >&5 +$as_echo "$CXX" >&6; } else - BLDLIBRARY='$(LDLIBRARY)' + { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 +$as_echo "no" >&6; } fi -# Other platforms follow -if test $enable_shared = "yes"; then - -cat >>confdefs.h <<\_ACEOF -#define Py_ENABLE_SHARED 1 -_ACEOF - - case $ac_sys_system in - BeOS*) - LDLIBRARY='libpython$(VERSION).so' - ;; - CYGWIN*) - LDLIBRARY='libpython$(VERSION).dll.a' - DLLLIBRARY='libpython$(VERSION).dll' - ;; - SunOS*) - LDLIBRARY='libpython$(VERSION).so' - BLDLIBRARY='-Wl,-R,$(LIBDIR) -L. -lpython$(VERSION)' - RUNSHARED=LD_LIBRARY_PATH=`pwd`:${LD_LIBRARY_PATH} - INSTSONAME="$LDLIBRARY".$SOVERSION - ;; - Linux*|GNU*|NetBSD*|FreeBSD*|DragonFly*) - LDLIBRARY='libpython$(VERSION).so' - BLDLIBRARY='-L. -lpython$(VERSION)' - RUNSHARED=LD_LIBRARY_PATH=`pwd`:${LD_LIBRARY_PATH} - case $ac_sys_system in - FreeBSD*) - SOVERSION=`echo $SOVERSION|cut -d "." -f 1` - ;; - esac - INSTSONAME="$LDLIBRARY".$SOVERSION - ;; - hp*|HP*) - case `uname -m` in - ia64) - LDLIBRARY='libpython$(VERSION).so' - ;; - *) - LDLIBRARY='libpython$(VERSION).sl' - ;; - esac - BLDLIBRARY='-Wl,+b,$(LIBDIR) -L. -lpython$(VERSION)' - RUNSHARED=SHLIB_PATH=`pwd`:${SHLIB_PATH} - ;; - OSF*) - LDLIBRARY='libpython$(VERSION).so' - BLDLIBRARY='-rpath $(LIBDIR) -L. -lpython$(VERSION)' - RUNSHARED=LD_LIBRARY_PATH=`pwd`:${LD_LIBRARY_PATH} - ;; - atheos*) - LDLIBRARY='libpython$(VERSION).so' - BLDLIBRARY='-L. -lpython$(VERSION)' - RUNSHARED=DLL_PATH=`pwd`:${DLL_PATH:-/atheos/sys/libs:/atheos/autolnk/lib} - ;; - Darwin*) - LDLIBRARY='libpython$(VERSION).dylib' - BLDLIBRARY='-L. -lpython$(VERSION)' - RUNSHARED='DYLD_LIBRARY_PATH=`pwd`:${DYLD_LIBRARY_PATH}' - ;; - - esac -else # shared is disabled - case $ac_sys_system in - CYGWIN*) - BLDLIBRARY='$(LIBRARY)' - LDLIBRARY='libpython$(VERSION).dll.a' - ;; - esac + ;; + esac + if test "$CXX" = "notfound" + then + CXX="" + fi fi - -{ echo "$as_me:$LINENO: result: $LDLIBRARY" >&5 -echo "${ECHO_T}$LDLIBRARY" >&6; } - -if test -n "$ac_tool_prefix"; then - # Extract the first word of "${ac_tool_prefix}ranlib", so it can be a program name with args. -set dummy ${ac_tool_prefix}ranlib; ac_word=$2 -{ echo "$as_me:$LINENO: checking for $ac_word" >&5 -echo $ECHO_N "checking for $ac_word... $ECHO_C" >&6; } -if test "${ac_cv_prog_RANLIB+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 +if test -z "$CXX" +then + for ac_prog in $CCC c++ g++ gcc CC cxx cc++ cl +do + # Extract the first word of "$ac_prog", so it can be a program name with args. +set dummy $ac_prog; ac_word=$2 +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 +$as_echo_n "checking for $ac_word... " >&6; } +if test "${ac_cv_prog_CXX+set}" = set; then : + $as_echo_n "(cached) " >&6 else - if test -n "$RANLIB"; then - ac_cv_prog_RANLIB="$RANLIB" # Let the user override the test. + if test -n "$CXX"; then + ac_cv_prog_CXX="$CXX" # Let the user override the test. else as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $PATH do IFS=$as_save_IFS test -z "$as_dir" && as_dir=. - for ac_exec_ext in '' $ac_executable_extensions; do + for ac_exec_ext in '' $ac_executable_extensions; do if { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_test_x "$as_dir/$ac_word$ac_exec_ext"; }; then - ac_cv_prog_RANLIB="${ac_tool_prefix}ranlib" - echo "$as_me:$LINENO: found $as_dir/$ac_word$ac_exec_ext" >&5 + ac_cv_prog_CXX="$ac_prog" + $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 break 2 fi done -done + done IFS=$as_save_IFS fi fi -RANLIB=$ac_cv_prog_RANLIB -if test -n "$RANLIB"; then - { echo "$as_me:$LINENO: result: $RANLIB" >&5 -echo "${ECHO_T}$RANLIB" >&6; } +CXX=$ac_cv_prog_CXX +if test -n "$CXX"; then + { $as_echo "$as_me:${as_lineno-$LINENO}: result: $CXX" >&5 +$as_echo "$CXX" >&6; } else - { echo "$as_me:$LINENO: result: no" >&5 -echo "${ECHO_T}no" >&6; } + { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 +$as_echo "no" >&6; } fi -fi -if test -z "$ac_cv_prog_RANLIB"; then - ac_ct_RANLIB=$RANLIB - # Extract the first word of "ranlib", so it can be a program name with args. -set dummy ranlib; ac_word=$2 -{ echo "$as_me:$LINENO: checking for $ac_word" >&5 -echo $ECHO_N "checking for $ac_word... $ECHO_C" >&6; } -if test "${ac_cv_prog_ac_ct_RANLIB+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 -else - if test -n "$ac_ct_RANLIB"; then - ac_cv_prog_ac_ct_RANLIB="$ac_ct_RANLIB" # Let the user override the test. -else -as_save_IFS=$IFS; IFS=$PATH_SEPARATOR -for as_dir in $PATH -do - IFS=$as_save_IFS - test -z "$as_dir" && as_dir=. - for ac_exec_ext in '' $ac_executable_extensions; do - if { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_test_x "$as_dir/$ac_word$ac_exec_ext"; }; then - ac_cv_prog_ac_ct_RANLIB="ranlib" - echo "$as_me:$LINENO: found $as_dir/$ac_word$ac_exec_ext" >&5 - break 2 - fi -done + test -n "$CXX" && break done -IFS=$as_save_IFS +test -n "$CXX" || CXX="notfound" + if test "$CXX" = "notfound" + then + CXX="" + fi fi -fi -ac_ct_RANLIB=$ac_cv_prog_ac_ct_RANLIB -if test -n "$ac_ct_RANLIB"; then - { echo "$as_me:$LINENO: result: $ac_ct_RANLIB" >&5 -echo "${ECHO_T}$ac_ct_RANLIB" >&6; } -else - { echo "$as_me:$LINENO: result: no" >&5 -echo "${ECHO_T}no" >&6; } -fi +if test "$preset_cxx" != "$CXX" +then + { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: - if test "x$ac_ct_RANLIB" = x; then - RANLIB=":" - else - case $cross_compiling:$ac_tool_warned in -yes:) -{ echo "$as_me:$LINENO: WARNING: In the future, Autoconf will not detect cross-tools -whose name does not start with the host triplet. If you think this -configuration is useful to you, please write to autoconf at gnu.org." >&5 -echo "$as_me: WARNING: In the future, Autoconf will not detect cross-tools -whose name does not start with the host triplet. If you think this -configuration is useful to you, please write to autoconf at gnu.org." >&2;} -ac_tool_warned=yes ;; -esac - RANLIB=$ac_ct_RANLIB - fi -else - RANLIB="$ac_cv_prog_RANLIB" + By default, distutils will build C++ extension modules with \"$CXX\". + If this is not intended, then set CXX on the configure command line. + " >&5 +$as_echo "$as_me: WARNING: + + By default, distutils will build C++ extension modules with \"$CXX\". + If this is not intended, then set CXX on the configure command line. + " >&2;} fi -for ac_prog in ar aal -do - # Extract the first word of "$ac_prog", so it can be a program name with args. -set dummy $ac_prog; ac_word=$2 -{ echo "$as_me:$LINENO: checking for $ac_word" >&5 -echo $ECHO_N "checking for $ac_word... $ECHO_C" >&6; } -if test "${ac_cv_prog_AR+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 -else - if test -n "$AR"; then - ac_cv_prog_AR="$AR" # Let the user override the test. +# checks for UNIX variants that set C preprocessor variables + +ac_ext=c +ac_cpp='$CPP $CPPFLAGS' +ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5' +ac_link='$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5' +ac_compiler_gnu=$ac_cv_c_compiler_gnu +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking how to run the C preprocessor" >&5 +$as_echo_n "checking how to run the C preprocessor... " >&6; } +# On Suns, sometimes $CPP names a directory. +if test -n "$CPP" && test -d "$CPP"; then + CPP= +fi +if test -z "$CPP"; then + if test "${ac_cv_prog_CPP+set}" = set; then : + $as_echo_n "(cached) " >&6 else -as_save_IFS=$IFS; IFS=$PATH_SEPARATOR -for as_dir in $PATH + # Double quotes because CPP needs to be expanded + for CPP in "$CC -E" "$CC -E -traditional-cpp" "/lib/cpp" + do + ac_preproc_ok=false +for ac_c_preproc_warn_flag in '' yes do - IFS=$as_save_IFS - test -z "$as_dir" && as_dir=. - for ac_exec_ext in '' $ac_executable_extensions; do - if { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_test_x "$as_dir/$ac_word$ac_exec_ext"; }; then - ac_cv_prog_AR="$ac_prog" - echo "$as_me:$LINENO: found $as_dir/$ac_word$ac_exec_ext" >&5 - break 2 - fi -done -done -IFS=$as_save_IFS + # Use a header file that comes with gcc, so configuring glibc + # with a fresh cross-compiler works. + # Prefer to if __STDC__ is defined, since + # exists even on freestanding compilers. + # On the NeXT, cc -E runs the code through the compiler's parser, + # not just through cpp. "Syntax error" is here to catch this case. + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ +#ifdef __STDC__ +# include +#else +# include +#endif + Syntax error +_ACEOF +if ac_fn_c_try_cpp "$LINENO"; then : -fi -fi -AR=$ac_cv_prog_AR -if test -n "$AR"; then - { echo "$as_me:$LINENO: result: $AR" >&5 -echo "${ECHO_T}$AR" >&6; } else - { echo "$as_me:$LINENO: result: no" >&5 -echo "${ECHO_T}no" >&6; } + # Broken: fails on valid input. +continue fi +rm -f conftest.err conftest.$ac_ext + # OK, works on sane cases. Now check whether nonexistent headers + # can be detected and how. + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ +#include +_ACEOF +if ac_fn_c_try_cpp "$LINENO"; then : + # Broken: success on invalid input. +continue +else + # Passes both tests. +ac_preproc_ok=: +break +fi +rm -f conftest.err conftest.$ac_ext - test -n "$AR" && break done -test -n "$AR" || AR="ar" - - -# tweak ARFLAGS only if the user didn't set it on the command line - -if test -z "$ARFLAGS" -then - ARFLAGS="rc" +# Because of `break', _AC_PREPROC_IFELSE's cleaning code was skipped. +rm -f conftest.err conftest.$ac_ext +if $ac_preproc_ok; then : + break fi + done + ac_cv_prog_CPP=$CPP -# Extract the first word of "svnversion", so it can be a program name with args. -set dummy svnversion; ac_word=$2 -{ echo "$as_me:$LINENO: checking for $ac_word" >&5 -echo $ECHO_N "checking for $ac_word... $ECHO_C" >&6; } -if test "${ac_cv_prog_SVNVERSION+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 -else - if test -n "$SVNVERSION"; then - ac_cv_prog_SVNVERSION="$SVNVERSION" # Let the user override the test. +fi + CPP=$ac_cv_prog_CPP else -as_save_IFS=$IFS; IFS=$PATH_SEPARATOR -for as_dir in $PATH + ac_cv_prog_CPP=$CPP +fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $CPP" >&5 +$as_echo "$CPP" >&6; } +ac_preproc_ok=false +for ac_c_preproc_warn_flag in '' yes do - IFS=$as_save_IFS - test -z "$as_dir" && as_dir=. - for ac_exec_ext in '' $ac_executable_extensions; do - if { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_test_x "$as_dir/$ac_word$ac_exec_ext"; }; then - ac_cv_prog_SVNVERSION="found" - echo "$as_me:$LINENO: found $as_dir/$ac_word$ac_exec_ext" >&5 - break 2 - fi -done -done -IFS=$as_save_IFS + # Use a header file that comes with gcc, so configuring glibc + # with a fresh cross-compiler works. + # Prefer to if __STDC__ is defined, since + # exists even on freestanding compilers. + # On the NeXT, cc -E runs the code through the compiler's parser, + # not just through cpp. "Syntax error" is here to catch this case. + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ +#ifdef __STDC__ +# include +#else +# include +#endif + Syntax error +_ACEOF +if ac_fn_c_try_cpp "$LINENO"; then : - test -z "$ac_cv_prog_SVNVERSION" && ac_cv_prog_SVNVERSION="not-found" -fi -fi -SVNVERSION=$ac_cv_prog_SVNVERSION -if test -n "$SVNVERSION"; then - { echo "$as_me:$LINENO: result: $SVNVERSION" >&5 -echo "${ECHO_T}$SVNVERSION" >&6; } else - { echo "$as_me:$LINENO: result: no" >&5 -echo "${ECHO_T}no" >&6; } + # Broken: fails on valid input. +continue fi +rm -f conftest.err conftest.$ac_ext - -if test $SVNVERSION = found -then - SVNVERSION="svnversion \$(srcdir)" + # OK, works on sane cases. Now check whether nonexistent headers + # can be detected and how. + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ +#include +_ACEOF +if ac_fn_c_try_cpp "$LINENO"; then : + # Broken: success on invalid input. +continue else - SVNVERSION="echo Unversioned directory" + # Passes both tests. +ac_preproc_ok=: +break fi +rm -f conftest.err conftest.$ac_ext -case $MACHDEP in -bsdos*|hp*|HP*) - # install -d does not work on BSDI or HP-UX - if test -z "$INSTALL" - then - INSTALL="${srcdir}/install-sh -c" - fi -esac -ac_aux_dir= -for ac_dir in "$srcdir" "$srcdir/.." "$srcdir/../.."; do - if test -f "$ac_dir/install-sh"; then - ac_aux_dir=$ac_dir - ac_install_sh="$ac_aux_dir/install-sh -c" - break - elif test -f "$ac_dir/install.sh"; then - ac_aux_dir=$ac_dir - ac_install_sh="$ac_aux_dir/install.sh -c" - break - elif test -f "$ac_dir/shtool"; then - ac_aux_dir=$ac_dir - ac_install_sh="$ac_aux_dir/shtool install -c" - break - fi done -if test -z "$ac_aux_dir"; then - { { echo "$as_me:$LINENO: error: cannot find install-sh or install.sh in \"$srcdir\" \"$srcdir/..\" \"$srcdir/../..\"" >&5 -echo "$as_me: error: cannot find install-sh or install.sh in \"$srcdir\" \"$srcdir/..\" \"$srcdir/../..\"" >&2;} - { (exit 1); exit 1; }; } +# Because of `break', _AC_PREPROC_IFELSE's cleaning code was skipped. +rm -f conftest.err conftest.$ac_ext +if $ac_preproc_ok; then : + +else + { { $as_echo "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5 +$as_echo "$as_me: error: in \`$ac_pwd':" >&2;} +as_fn_error "C preprocessor \"$CPP\" fails sanity check +See \`config.log' for more details." "$LINENO" 5; } fi -# These three variables are undocumented and unsupported, -# and are intended to be withdrawn in a future Autoconf release. -# They can cause serious problems if a builder's source tree is in a directory -# whose full name contains unusual characters. -ac_config_guess="$SHELL $ac_aux_dir/config.guess" # Please don't use this var. -ac_config_sub="$SHELL $ac_aux_dir/config.sub" # Please don't use this var. -ac_configure="$SHELL $ac_aux_dir/configure" # Please don't use this var. +ac_ext=c +ac_cpp='$CPP $CPPFLAGS' +ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5' +ac_link='$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5' +ac_compiler_gnu=$ac_cv_c_compiler_gnu -# Find a good install program. We prefer a C program (faster), -# so one script is as good as another. But avoid the broken or -# incompatible versions: -# SysV /etc/install, /usr/sbin/install -# SunOS /usr/etc/install -# IRIX /sbin/install -# AIX /bin/install -# AmigaOS /C/install, which installs bootblocks on floppy discs -# AIX 4 /usr/bin/installbsd, which doesn't work without a -g flag -# AFS /usr/afsws/bin/install, which mishandles nonexistent args -# SVR4 /usr/ucb/install, which tries to use the nonexistent group "staff" -# OS/2's system install, which has a completely different semantic -# ./install, which can be erroneously created by make from ./install.sh. -{ echo "$as_me:$LINENO: checking for a BSD-compatible install" >&5 -echo $ECHO_N "checking for a BSD-compatible install... $ECHO_C" >&6; } -if test -z "$INSTALL"; then -if test "${ac_cv_path_install+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for grep that handles long lines and -e" >&5 +$as_echo_n "checking for grep that handles long lines and -e... " >&6; } +if test "${ac_cv_path_GREP+set}" = set; then : + $as_echo_n "(cached) " >&6 else + if test -z "$GREP"; then + ac_path_GREP_found=false + # Loop through the user's path and test for each of PROGNAME-LIST as_save_IFS=$IFS; IFS=$PATH_SEPARATOR -for as_dir in $PATH +for as_dir in $PATH$PATH_SEPARATOR/usr/xpg4/bin do IFS=$as_save_IFS test -z "$as_dir" && as_dir=. - # Account for people who put trailing slashes in PATH elements. -case $as_dir/ in - ./ | .// | /cC/* | \ - /etc/* | /usr/sbin/* | /usr/etc/* | /sbin/* | /usr/afsws/bin/* | \ - ?:\\/os2\\/install\\/* | ?:\\/OS2\\/INSTALL\\/* | \ - /usr/ucb/* ) ;; - *) - # OSF1 and SCO ODT 3.0 have their own names for install. - # Don't use installbsd from OSF since it installs stuff as root - # by default. - for ac_prog in ginstall scoinst install; do - for ac_exec_ext in '' $ac_executable_extensions; do - if { test -f "$as_dir/$ac_prog$ac_exec_ext" && $as_test_x "$as_dir/$ac_prog$ac_exec_ext"; }; then - if test $ac_prog = install && - grep dspmsg "$as_dir/$ac_prog$ac_exec_ext" >/dev/null 2>&1; then - # AIX install. It has an incompatible calling convention. - : - elif test $ac_prog = install && - grep pwplus "$as_dir/$ac_prog$ac_exec_ext" >/dev/null 2>&1; then - # program-specific install script used by HP pwplus--don't use. - : - else - ac_cv_path_install="$as_dir/$ac_prog$ac_exec_ext -c" - break 3 - fi - fi - done - done - ;; + for ac_prog in grep ggrep; do + for ac_exec_ext in '' $ac_executable_extensions; do + ac_path_GREP="$as_dir/$ac_prog$ac_exec_ext" + { test -f "$ac_path_GREP" && $as_test_x "$ac_path_GREP"; } || continue +# Check for GNU ac_path_GREP and select it if it is found. + # Check for GNU $ac_path_GREP +case `"$ac_path_GREP" --version 2>&1` in +*GNU*) + ac_cv_path_GREP="$ac_path_GREP" ac_path_GREP_found=:;; +*) + ac_count=0 + $as_echo_n 0123456789 >"conftest.in" + while : + do + cat "conftest.in" "conftest.in" >"conftest.tmp" + mv "conftest.tmp" "conftest.in" + cp "conftest.in" "conftest.nl" + $as_echo 'GREP' >> "conftest.nl" + "$ac_path_GREP" -e 'GREP$' -e '-(cannot match)-' < "conftest.nl" >"conftest.out" 2>/dev/null || break + diff "conftest.out" "conftest.nl" >/dev/null 2>&1 || break + as_fn_arith $ac_count + 1 && ac_count=$as_val + if test $ac_count -gt ${ac_path_GREP_max-0}; then + # Best one so far, save it but keep looking for a better one + ac_cv_path_GREP="$ac_path_GREP" + ac_path_GREP_max=$ac_count + fi + # 10*(2^10) chars as input seems more than enough + test $ac_count -gt 10 && break + done + rm -f conftest.in conftest.tmp conftest.nl conftest.out;; esac -done -IFS=$as_save_IFS - -fi - if test "${ac_cv_path_install+set}" = set; then - INSTALL=$ac_cv_path_install - else - # As a last resort, use the slow shell script. Don't cache a - # value for INSTALL within a source directory, because that will - # break other packages using the cache if that directory is - # removed, or if the value is a relative name. - INSTALL=$ac_install_sh + $ac_path_GREP_found && break 3 + done + done + done +IFS=$as_save_IFS + if test -z "$ac_cv_path_GREP"; then + as_fn_error "no acceptable grep could be found in $PATH$PATH_SEPARATOR/usr/xpg4/bin" "$LINENO" 5 fi +else + ac_cv_path_GREP=$GREP fi -{ echo "$as_me:$LINENO: result: $INSTALL" >&5 -echo "${ECHO_T}$INSTALL" >&6; } - -# Use test -z because SunOS4 sh mishandles braces in ${var-val}. -# It thinks the first close brace ends the variable substitution. -test -z "$INSTALL_PROGRAM" && INSTALL_PROGRAM='${INSTALL}' -test -z "$INSTALL_SCRIPT" && INSTALL_SCRIPT='${INSTALL}' +fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_path_GREP" >&5 +$as_echo "$ac_cv_path_GREP" >&6; } + GREP="$ac_cv_path_GREP" -test -z "$INSTALL_DATA" && INSTALL_DATA='${INSTALL} -m 644' +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for egrep" >&5 +$as_echo_n "checking for egrep... " >&6; } +if test "${ac_cv_path_EGREP+set}" = set; then : + $as_echo_n "(cached) " >&6 +else + if echo a | $GREP -E '(a|b)' >/dev/null 2>&1 + then ac_cv_path_EGREP="$GREP -E" + else + if test -z "$EGREP"; then + ac_path_EGREP_found=false + # Loop through the user's path and test for each of PROGNAME-LIST + as_save_IFS=$IFS; IFS=$PATH_SEPARATOR +for as_dir in $PATH$PATH_SEPARATOR/usr/xpg4/bin +do + IFS=$as_save_IFS + test -z "$as_dir" && as_dir=. + for ac_prog in egrep; do + for ac_exec_ext in '' $ac_executable_extensions; do + ac_path_EGREP="$as_dir/$ac_prog$ac_exec_ext" + { test -f "$ac_path_EGREP" && $as_test_x "$ac_path_EGREP"; } || continue +# Check for GNU ac_path_EGREP and select it if it is found. + # Check for GNU $ac_path_EGREP +case `"$ac_path_EGREP" --version 2>&1` in +*GNU*) + ac_cv_path_EGREP="$ac_path_EGREP" ac_path_EGREP_found=:;; +*) + ac_count=0 + $as_echo_n 0123456789 >"conftest.in" + while : + do + cat "conftest.in" "conftest.in" >"conftest.tmp" + mv "conftest.tmp" "conftest.in" + cp "conftest.in" "conftest.nl" + $as_echo 'EGREP' >> "conftest.nl" + "$ac_path_EGREP" 'EGREP$' < "conftest.nl" >"conftest.out" 2>/dev/null || break + diff "conftest.out" "conftest.nl" >/dev/null 2>&1 || break + as_fn_arith $ac_count + 1 && ac_count=$as_val + if test $ac_count -gt ${ac_path_EGREP_max-0}; then + # Best one so far, save it but keep looking for a better one + ac_cv_path_EGREP="$ac_path_EGREP" + ac_path_EGREP_max=$ac_count + fi + # 10*(2^10) chars as input seems more than enough + test $ac_count -gt 10 && break + done + rm -f conftest.in conftest.tmp conftest.nl conftest.out;; +esac -# Not every filesystem supports hard links + $ac_path_EGREP_found && break 3 + done + done + done +IFS=$as_save_IFS + if test -z "$ac_cv_path_EGREP"; then + as_fn_error "no acceptable egrep could be found in $PATH$PATH_SEPARATOR/usr/xpg4/bin" "$LINENO" 5 + fi +else + ac_cv_path_EGREP=$EGREP +fi -if test -z "$LN" ; then - case $ac_sys_system in - BeOS*) LN="ln -s";; - CYGWIN*) LN="ln -s";; - atheos*) LN="ln -s";; - *) LN=ln;; - esac + fi fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_path_EGREP" >&5 +$as_echo "$ac_cv_path_EGREP" >&6; } + EGREP="$ac_cv_path_EGREP" -# Check for --with-pydebug -{ echo "$as_me:$LINENO: checking for --with-pydebug" >&5 -echo $ECHO_N "checking for --with-pydebug... $ECHO_C" >&6; } -# Check whether --with-pydebug was given. -if test "${with_pydebug+set}" = set; then - withval=$with_pydebug; -if test "$withval" != no -then +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for ANSI C header files" >&5 +$as_echo_n "checking for ANSI C header files... " >&6; } +if test "${ac_cv_header_stdc+set}" = set; then : + $as_echo_n "(cached) " >&6 +else + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ +#include +#include +#include +#include -cat >>confdefs.h <<\_ACEOF -#define Py_DEBUG 1 -_ACEOF +int +main () +{ - { echo "$as_me:$LINENO: result: yes" >&5 -echo "${ECHO_T}yes" >&6; }; - Py_DEBUG='true' -else { echo "$as_me:$LINENO: result: no" >&5 -echo "${ECHO_T}no" >&6; }; Py_DEBUG='false' -fi + ; + return 0; +} +_ACEOF +if ac_fn_c_try_compile "$LINENO"; then : + ac_cv_header_stdc=yes else - { echo "$as_me:$LINENO: result: no" >&5 -echo "${ECHO_T}no" >&6; } + ac_cv_header_stdc=no fi +rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext +if test $ac_cv_header_stdc = yes; then + # SunOS 4.x string.h does not declare mem*, contrary to ANSI. + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ +#include -# XXX Shouldn't the code above that fiddles with BASECFLAGS and OPT be -# merged with this chunk of code? - -# Optimizer/debugger flags -# ------------------------ -# (The following bit of code is complicated enough - please keep things -# indented properly. Just pretend you're editing Python code. ;-) - -# There are two parallel sets of case statements below, one that checks to -# see if OPT was set and one that does BASECFLAGS setting based upon -# compiler and platform. BASECFLAGS tweaks need to be made even if the -# user set OPT. - -# tweak OPT based on compiler and platform, only if the user didn't set -# it on the command line +_ACEOF +if (eval "$ac_cpp conftest.$ac_ext") 2>&5 | + $EGREP "memchr" >/dev/null 2>&1; then : -if test "${OPT-unset}" = "unset" -then - case $GCC in - yes) - if test "$CC" != 'g++' ; then - STRICT_PROTO="-Wstrict-prototypes" - fi - # For gcc 4.x we need to use -fwrapv so lets check if its supported - if "$CC" -v --help 2>/dev/null |grep -- -fwrapv > /dev/null; then - WRAP="-fwrapv" - fi - case $ac_cv_prog_cc_g in - yes) - if test "$Py_DEBUG" = 'true' ; then - # Optimization messes up debuggers, so turn it off for - # debug builds. - OPT="-g -O0 -Wall $STRICT_PROTO" - else - OPT="-g $WRAP -O3 -Wall $STRICT_PROTO" - fi - ;; - *) - OPT="-O3 -Wall $STRICT_PROTO" - ;; - esac - case $ac_sys_system in - SCO_SV*) OPT="$OPT -m486 -DSCO5" - ;; - esac - ;; +else + ac_cv_header_stdc=no +fi +rm -f conftest* - *) - OPT="-O" - ;; - esac fi +if test $ac_cv_header_stdc = yes; then + # ISC 2.0.2 stdlib.h does not declare free, contrary to ANSI. + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ +#include +_ACEOF +if (eval "$ac_cpp conftest.$ac_ext") 2>&5 | + $EGREP "free" >/dev/null 2>&1; then : -# The -arch flags for universal builds on OSX -UNIVERSAL_ARCH_FLAGS= +else + ac_cv_header_stdc=no +fi +rm -f conftest* +fi -# tweak BASECFLAGS based on compiler and platform -case $GCC in -yes) - # Python violates C99 rules, by casting between incompatible - # pointer types. GCC may generate bad code as a result of that, - # so use -fno-strict-aliasing if supported. - { echo "$as_me:$LINENO: checking whether $CC accepts -fno-strict-aliasing" >&5 -echo $ECHO_N "checking whether $CC accepts -fno-strict-aliasing... $ECHO_C" >&6; } - ac_save_cc="$CC" - CC="$CC -fno-strict-aliasing" - if test "${ac_cv_no_strict_aliasing_ok+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 +if test $ac_cv_header_stdc = yes; then + # /bin/cc in Irix-4.0.5 gets non-ANSI ctype macros unless using -ansi. + if test "$cross_compiling" = yes; then : + : else - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF + cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ +#include +#include +#if ((' ' & 0x0FF) == 0x020) +# define ISLOWER(c) ('a' <= (c) && (c) <= 'z') +# define TOUPPER(c) (ISLOWER(c) ? 'A' + ((c) - 'a') : (c)) +#else +# define ISLOWER(c) \ + (('a' <= (c) && (c) <= 'i') \ + || ('j' <= (c) && (c) <= 'r') \ + || ('s' <= (c) && (c) <= 'z')) +# define TOUPPER(c) (ISLOWER(c) ? ((c) | 0x40) : (c)) +#endif +#define XOR(e, f) (((e) && !(f)) || (!(e) && (f))) int main () { -int main() { return 0; } - ; + int i; + for (i = 0; i < 256; i++) + if (XOR (islower (i), ISLOWER (i)) + || toupper (i) != TOUPPER (i)) + return 2; return 0; } _ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - ac_cv_no_strict_aliasing_ok=yes -else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 +if ac_fn_c_try_run "$LINENO"; then : - ac_cv_no_strict_aliasing_ok=no +else + ac_cv_header_stdc=no +fi +rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext \ + conftest.$ac_objext conftest.beam conftest.$ac_ext fi -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext fi +fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_header_stdc" >&5 +$as_echo "$ac_cv_header_stdc" >&6; } +if test $ac_cv_header_stdc = yes; then - CC="$ac_save_cc" - { echo "$as_me:$LINENO: result: $ac_cv_no_strict_aliasing_ok" >&5 -echo "${ECHO_T}$ac_cv_no_strict_aliasing_ok" >&6; } - if test $ac_cv_no_strict_aliasing_ok = yes - then - BASECFLAGS="$BASECFLAGS -fno-strict-aliasing" - fi +$as_echo "#define STDC_HEADERS 1" >>confdefs.h - # if using gcc on alpha, use -mieee to get (near) full IEEE 754 - # support. Without this, treatment of subnormals doesn't follow - # the standard. - case $ac_sys_machine in - alpha*) - BASECFLAGS="$BASECFLAGS -mieee" - ;; - esac - - case $ac_sys_system in - SCO_SV*) - BASECFLAGS="$BASECFLAGS -m486 -DSCO5" - ;; - # is there any other compiler on Darwin besides gcc? - Darwin*) - # -Wno-long-double, -no-cpp-precomp, and -mno-fused-madd - # used to be here, but non-Apple gcc doesn't accept them. - if test "${CC}" = gcc - then - { echo "$as_me:$LINENO: checking which compiler should be used" >&5 -echo $ECHO_N "checking which compiler should be used... $ECHO_C" >&6; } - case "${UNIVERSALSDK}" in - */MacOSX10.4u.sdk) - # Build using 10.4 SDK, force usage of gcc when the - # compiler is gcc, otherwise the user will get very - # confusing error messages when building on OSX 10.6 - CC=gcc-4.0 - CPP=cpp-4.0 - ;; - esac - { echo "$as_me:$LINENO: result: $CC" >&5 -echo "${ECHO_T}$CC" >&6; } - fi - - # Calculate the right deployment target for this build. - # - cur_target=`sw_vers -productVersion | sed 's/\(10\.[0-9]*\).*/\1/'` - if test ${cur_target} '>' 10.2; then - cur_target=10.3 - if test ${enable_universalsdk}; then - if test "${UNIVERSAL_ARCHS}" = "all"; then - # Ensure that the default platform for a - # 4-way universal build is OSX 10.5, - # that's the first OS release where - # 4-way builds make sense. - cur_target='10.5' - - elif test "${UNIVERSAL_ARCHS}" = "3-way"; then - cur_target='10.5' - - elif test "${UNIVERSAL_ARCHS}" = "intel"; then - cur_target='10.5' - - elif test "${UNIVERSAL_ARCHS}" = "64-bit"; then - cur_target='10.5' - fi - else - if test `/usr/bin/arch` = "i386"; then - # On Intel macs default to a deployment - # target of 10.4, that's the first OSX - # release with Intel support. - cur_target="10.4" - fi - fi - fi - CONFIGURE_MACOSX_DEPLOYMENT_TARGET=${MACOSX_DEPLOYMENT_TARGET-${cur_target}} - - # Make sure that MACOSX_DEPLOYMENT_TARGET is set in the - # environment with a value that is the same as what we'll use - # in the Makefile to ensure that we'll get the same compiler - # environment during configure and build time. - MACOSX_DEPLOYMENT_TARGET="$CONFIGURE_MACOSX_DEPLOYMENT_TARGET" - export MACOSX_DEPLOYMENT_TARGET - EXPORT_MACOSX_DEPLOYMENT_TARGET='' - - if test "${enable_universalsdk}"; then - UNIVERSAL_ARCH_FLAGS="" - if test "$UNIVERSAL_ARCHS" = "32-bit" ; then - UNIVERSAL_ARCH_FLAGS="-arch ppc -arch i386" - ARCH_RUN_32BIT="" - LIPO_32BIT_FLAGS="" +fi - elif test "$UNIVERSAL_ARCHS" = "64-bit" ; then - UNIVERSAL_ARCH_FLAGS="-arch ppc64 -arch x86_64" - LIPO_32BIT_FLAGS="" - ARCH_RUN_32BIT="true" +# On IRIX 5.3, sys/types and inttypes.h are conflicting. +for ac_header in sys/types.h sys/stat.h stdlib.h string.h memory.h strings.h \ + inttypes.h stdint.h unistd.h +do : + as_ac_Header=`$as_echo "ac_cv_header_$ac_header" | $as_tr_sh` +ac_fn_c_check_header_compile "$LINENO" "$ac_header" "$as_ac_Header" "$ac_includes_default +" +eval as_val=\$$as_ac_Header + if test "x$as_val" = x""yes; then : + cat >>confdefs.h <<_ACEOF +#define `$as_echo "HAVE_$ac_header" | $as_tr_cpp` 1 +_ACEOF - elif test "$UNIVERSAL_ARCHS" = "all" ; then - UNIVERSAL_ARCH_FLAGS="-arch i386 -arch ppc -arch ppc64 -arch x86_64" - LIPO_32BIT_FLAGS="-extract ppc7400 -extract i386" - ARCH_RUN_32BIT="/usr/bin/arch -i386 -ppc" +fi - elif test "$UNIVERSAL_ARCHS" = "intel" ; then - UNIVERSAL_ARCH_FLAGS="-arch i386 -arch x86_64" - LIPO_32BIT_FLAGS="-extract i386" - ARCH_RUN_32BIT="/usr/bin/arch -i386" +done - elif test "$UNIVERSAL_ARCHS" = "3-way" ; then - UNIVERSAL_ARCH_FLAGS="-arch i386 -arch ppc -arch x86_64" - LIPO_32BIT_FLAGS="-extract ppc7400 -extract i386" - ARCH_RUN_32BIT="/usr/bin/arch -i386 -ppc" - else - { { echo "$as_me:$LINENO: error: proper usage is --with-universal-arch=32-bit|64-bit|all|intel|3-way" >&5 -echo "$as_me: error: proper usage is --with-universal-arch=32-bit|64-bit|all|intel|3-way" >&2;} - { (exit 1); exit 1; }; } - fi + ac_fn_c_check_header_mongrel "$LINENO" "minix/config.h" "ac_cv_header_minix_config_h" "$ac_includes_default" +if test "x$ac_cv_header_minix_config_h" = x""yes; then : + MINIX=yes +else + MINIX= +fi - CFLAGS="${UNIVERSAL_ARCH_FLAGS} ${CFLAGS}" - if test "${UNIVERSALSDK}" != "/" - then - CPPFLAGS="-isysroot ${UNIVERSALSDK} ${CPPFLAGS}" - LDFLAGS="-isysroot ${UNIVERSALSDK} ${LDFLAGS}" - CFLAGS="-isysroot ${UNIVERSALSDK} ${CFLAGS}" - fi + if test "$MINIX" = yes; then - fi +$as_echo "#define _POSIX_SOURCE 1" >>confdefs.h - ;; - OSF*) - BASECFLAGS="$BASECFLAGS -mieee" - ;; - esac - ;; +$as_echo "#define _POSIX_1_SOURCE 2" >>confdefs.h -*) - case $ac_sys_system in - OpenUNIX*|UnixWare*) - BASECFLAGS="$BASECFLAGS -K pentium,host,inline,loop_unroll,alloca " - ;; - OSF*) - BASECFLAGS="$BASECFLAGS -ieee -std" - ;; - SCO_SV*) - BASECFLAGS="$BASECFLAGS -belf -Ki486 -DSCO5" - ;; - esac - ;; -esac -if test "$Py_DEBUG" = 'true'; then - : -else - OPT="-DNDEBUG $OPT" -fi +$as_echo "#define _MINIX 1" >>confdefs.h -if test "$ac_arch_flags" -then - BASECFLAGS="$BASECFLAGS $ac_arch_flags" -fi + fi -# disable check for icc since it seems to pass, but generates a warning -if test "$CC" = icc -then - ac_cv_opt_olimit_ok=no -fi -{ echo "$as_me:$LINENO: checking whether $CC accepts -OPT:Olimit=0" >&5 -echo $ECHO_N "checking whether $CC accepts -OPT:Olimit=0... $ECHO_C" >&6; } -if test "${ac_cv_opt_olimit_ok+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 + { $as_echo "$as_me:${as_lineno-$LINENO}: checking whether it is safe to define __EXTENSIONS__" >&5 +$as_echo_n "checking whether it is safe to define __EXTENSIONS__... " >&6; } +if test "${ac_cv_safe_to_define___extensions__+set}" = set; then : + $as_echo_n "(cached) " >&6 else - ac_save_cc="$CC" -CC="$CC -OPT:Olimit=0" -cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF + cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ +# define __EXTENSIONS__ 1 + $ac_includes_default int main () { -int main() { return 0; } + ; return 0; } _ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - ac_cv_opt_olimit_ok=yes +if ac_fn_c_try_compile "$LINENO"; then : + ac_cv_safe_to_define___extensions__=yes else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - ac_cv_opt_olimit_ok=no + ac_cv_safe_to_define___extensions__=no fi - rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext -CC="$ac_save_cc" fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_safe_to_define___extensions__" >&5 +$as_echo "$ac_cv_safe_to_define___extensions__" >&6; } + test $ac_cv_safe_to_define___extensions__ = yes && + $as_echo "#define __EXTENSIONS__ 1" >>confdefs.h -{ echo "$as_me:$LINENO: result: $ac_cv_opt_olimit_ok" >&5 -echo "${ECHO_T}$ac_cv_opt_olimit_ok" >&6; } -if test $ac_cv_opt_olimit_ok = yes; then - case $ac_sys_system in - # XXX is this branch needed? On MacOSX 10.2.2 the result of the - # olimit_ok test is "no". Is it "yes" in some other Darwin-esque - # environment? - Darwin*) - ;; - *) - BASECFLAGS="$BASECFLAGS -OPT:Olimit=0" - ;; - esac -else - { echo "$as_me:$LINENO: checking whether $CC accepts -Olimit 1500" >&5 -echo $ECHO_N "checking whether $CC accepts -Olimit 1500... $ECHO_C" >&6; } - if test "${ac_cv_olimit_ok+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 -else - ac_save_cc="$CC" - CC="$CC -Olimit 1500" - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ - -int -main () -{ -int main() { return 0; } - ; - return 0; -} -_ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - ac_cv_olimit_ok=yes -else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 + $as_echo "#define _ALL_SOURCE 1" >>confdefs.h - ac_cv_olimit_ok=no -fi + $as_echo "#define _GNU_SOURCE 1" >>confdefs.h -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext - CC="$ac_save_cc" -fi + $as_echo "#define _POSIX_PTHREAD_SEMANTICS 1" >>confdefs.h - { echo "$as_me:$LINENO: result: $ac_cv_olimit_ok" >&5 -echo "${ECHO_T}$ac_cv_olimit_ok" >&6; } - if test $ac_cv_olimit_ok = yes; then - BASECFLAGS="$BASECFLAGS -Olimit 1500" - fi -fi + $as_echo "#define _TANDEM_SOURCE 1" >>confdefs.h -# Check whether GCC supports PyArg_ParseTuple format -if test "$GCC" = "yes" -then - { echo "$as_me:$LINENO: checking whether gcc supports ParseTuple __format__" >&5 -echo $ECHO_N "checking whether gcc supports ParseTuple __format__... $ECHO_C" >&6; } - save_CFLAGS=$CFLAGS - CFLAGS="$CFLAGS -Werror" - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ - void f(char*,...)__attribute((format(PyArg_ParseTuple, 1, 2))); -int -main () -{ - ; - return 0; -} -_ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; +# Check for unsupported systems +case $ac_sys_system/$ac_sys_release in +atheos*|Linux*/1*) + echo This system \($ac_sys_system/$ac_sys_release\) is no longer supported. + echo See README for details. + exit 1;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then -cat >>confdefs.h <<\_ACEOF -#define HAVE_ATTRIBUTE_FORMAT_PARSETUPLE 1 -_ACEOF - - { echo "$as_me:$LINENO: result: yes" >&5 -echo "${ECHO_T}yes" >&6; } -else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - { echo "$as_me:$LINENO: result: no" >&5 -echo "${ECHO_T}no" >&6; } +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for --with-suffix" >&5 +$as_echo_n "checking for --with-suffix... " >&6; } +# Check whether --with-suffix was given. +if test "${with_suffix+set}" = set; then : + withval=$with_suffix; + case $withval in + no) EXEEXT=;; + yes) EXEEXT=.exe;; + *) EXEEXT=$withval;; + esac fi -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext - CFLAGS=$save_CFLAGS +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $EXEEXT" >&5 +$as_echo "$EXEEXT" >&6; } + +# Test whether we're running on a non-case-sensitive system, in which +# case we give a warning if no ext is given + +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for case-insensitive build directory" >&5 +$as_echo_n "checking for case-insensitive build directory... " >&6; } +if test ! -d CaseSensitiveTestDir; then +mkdir CaseSensitiveTestDir fi -# On some compilers, pthreads are available without further options -# (e.g. MacOS X). On some of these systems, the compiler will not -# complain if unaccepted options are passed (e.g. gcc on Mac OS X). -# So we have to see first whether pthreads are available without -# options before we can check whether -Kpthread improves anything. -{ echo "$as_me:$LINENO: checking whether pthreads are available without options" >&5 -echo $ECHO_N "checking whether pthreads are available without options... $ECHO_C" >&6; } -if test "${ac_cv_pthread_is_default+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 -else - if test "$cross_compiling" = yes; then - ac_cv_pthread_is_default=no +if test -d casesensitivetestdir +then + { $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +$as_echo "yes" >&6; } + BUILDEXEEXT=.exe else - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ + { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 +$as_echo "no" >&6; } + BUILDEXEEXT=$EXEEXT +fi +rmdir CaseSensitiveTestDir -#include +case $MACHDEP in +bsdos*) + case $CC in + gcc) CC="$CC -D_HAVE_BSDI";; + esac;; +esac -void* routine(void* p){return NULL;} +case $ac_sys_system in +hp*|HP*) + case $CC in + cc|*/cc) CC="$CC -Ae";; + esac;; +SunOS*) + # Some functions have a prototype only with that define, e.g. confstr -int main(){ - pthread_t p; - if(pthread_create(&p,NULL,routine,NULL)!=0) - return 1; - (void)pthread_detach(p); - return 0; -} +$as_echo "#define __EXTENSIONS__ 1" >>confdefs.h -_ACEOF -rm -f conftest$ac_exeext -if { (ac_try="$ac_link" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_link") 2>&5 - ac_status=$? - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { ac_try='./conftest$ac_exeext' - { (case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; + ;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_try") 2>&5 - ac_status=$? - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); }; }; then - ac_cv_pthread_is_default=yes - ac_cv_kthread=no - ac_cv_pthread=no -else - echo "$as_me: program exited with status $ac_status" >&5 -echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 -( exit $ac_status ) -ac_cv_pthread_is_default=no -fi -rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext conftest.$ac_objext conftest.$ac_ext +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking LIBRARY" >&5 +$as_echo_n "checking LIBRARY... " >&6; } +if test -z "$LIBRARY" +then + LIBRARY='libpython$(VERSION).a' fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $LIBRARY" >&5 +$as_echo "$LIBRARY" >&6; } +# LDLIBRARY is the name of the library to link against (as opposed to the +# name of the library into which to insert object files). BLDLIBRARY is also +# the library to link against, usually. On Mac OS X frameworks, BLDLIBRARY +# is blank as the main program is not linked directly against LDLIBRARY. +# LDLIBRARYDIR is the path to LDLIBRARY, which is made in a subdirectory. On +# systems without shared libraries, LDLIBRARY is the same as LIBRARY +# (defined in the Makefiles). On Cygwin LDLIBRARY is the import library, +# DLLLIBRARY is the shared (i.e., DLL) library. +# +# RUNSHARED is used to run shared python without installed libraries +# +# INSTSONAME is the name of the shared library that will be use to install +# on the system - some systems like version suffix, others don't -fi - -{ echo "$as_me:$LINENO: result: $ac_cv_pthread_is_default" >&5 -echo "${ECHO_T}$ac_cv_pthread_is_default" >&6; } - -if test $ac_cv_pthread_is_default = yes -then - ac_cv_kpthread=no -else -# -Kpthread, if available, provides the right #defines -# and linker options to make pthread_create available -# Some compilers won't report that they do not support -Kpthread, -# so we need to run a program to see whether it really made the -# function available. -{ echo "$as_me:$LINENO: checking whether $CC accepts -Kpthread" >&5 -echo $ECHO_N "checking whether $CC accepts -Kpthread... $ECHO_C" >&6; } -if test "${ac_cv_kpthread+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 -else - ac_save_cc="$CC" -CC="$CC -Kpthread" -if test "$cross_compiling" = yes; then - ac_cv_kpthread=no -else - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -#include -void* routine(void* p){return NULL;} -int main(){ - pthread_t p; - if(pthread_create(&p,NULL,routine,NULL)!=0) - return 1; - (void)pthread_detach(p); - return 0; -} +LDLIBRARY="$LIBRARY" +BLDLIBRARY='$(LDLIBRARY)' +INSTSONAME='$(LDLIBRARY)' +DLLLIBRARY='' +LDLIBRARYDIR='' +RUNSHARED='' -_ACEOF -rm -f conftest$ac_exeext -if { (ac_try="$ac_link" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_link") 2>&5 - ac_status=$? - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { ac_try='./conftest$ac_exeext' - { (case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_try") 2>&5 - ac_status=$? - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); }; }; then - ac_cv_kpthread=yes -else - echo "$as_me: program exited with status $ac_status" >&5 -echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 +# LINKCC is the command that links the python executable -- default is $(CC). +# If CXX is set, and if it is needed to link a main function that was +# compiled with CXX, LINKCC is CXX instead. Always using CXX is undesirable: +# python might then depend on the C++ runtime +# This is altered for AIX in order to build the export list before +# linking. -( exit $ac_status ) -ac_cv_kpthread=no -fi -rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext conftest.$ac_objext conftest.$ac_ext +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking LINKCC" >&5 +$as_echo_n "checking LINKCC... " >&6; } +if test -z "$LINKCC" +then + LINKCC='$(PURIFY) $(MAINCC)' + case $ac_sys_system in + AIX*) + exp_extra="\"\"" + if test $ac_sys_release -ge 5 -o \ + $ac_sys_release -eq 4 -a `uname -r` -ge 2 ; then + exp_extra="." + fi + LINKCC="\$(srcdir)/Modules/makexp_aix Modules/python.exp $exp_extra \$(LIBRARY); $LINKCC";; + QNX*) + # qcc must be used because the other compilers do not + # support -N. + LINKCC=qcc;; + esac fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $LINKCC" >&5 +$as_echo "$LINKCC" >&6; } +# GNULD is set to "yes" if the GNU linker is used. If this goes wrong +# make sure we default having it set to "no": this is used by +# distutils.unixccompiler to know if it should add --enable-new-dtags +# to linker command lines, and failing to detect GNU ld simply results +# in the same bahaviour as before. -CC="$ac_save_cc" +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for GNU ld" >&5 +$as_echo_n "checking for GNU ld... " >&6; } +ac_prog=ld +if test "$GCC" = yes; then + ac_prog=`$CC -print-prog-name=ld` fi +case `"$ac_prog" -V 2>&1 < /dev/null` in + *GNU*) + GNULD=yes;; + *) + GNULD=no;; +esac +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $GNULD" >&5 +$as_echo "$GNULD" >&6; } -{ echo "$as_me:$LINENO: result: $ac_cv_kpthread" >&5 -echo "${ECHO_T}$ac_cv_kpthread" >&6; } +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for --enable-shared" >&5 +$as_echo_n "checking for --enable-shared... " >&6; } +# Check whether --enable-shared was given. +if test "${enable_shared+set}" = set; then : + enableval=$enable_shared; fi -if test $ac_cv_kpthread = no -a $ac_cv_pthread_is_default = no + +if test -z "$enable_shared" then -# -Kthread, if available, provides the right #defines -# and linker options to make pthread_create available -# Some compilers won't report that they do not support -Kthread, -# so we need to run a program to see whether it really made the -# function available. -{ echo "$as_me:$LINENO: checking whether $CC accepts -Kthread" >&5 -echo $ECHO_N "checking whether $CC accepts -Kthread... $ECHO_C" >&6; } -if test "${ac_cv_kthread+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 -else - ac_save_cc="$CC" -CC="$CC -Kthread" -if test "$cross_compiling" = yes; then - ac_cv_kthread=no + case $ac_sys_system in + CYGWIN* | atheos*) + enable_shared="yes";; + *) + enable_shared="no";; + esac +fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $enable_shared" >&5 +$as_echo "$enable_shared" >&6; } + +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for --enable-profiling" >&5 +$as_echo_n "checking for --enable-profiling... " >&6; } +# Check whether --enable-profiling was given. +if test "${enable_profiling+set}" = set; then : + enableval=$enable_profiling; ac_save_cc="$CC" + CC="$CC -pg" + if test "$cross_compiling" = yes; then : + ac_enable_profiling="no" else - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF + cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ - -#include - -void* routine(void* p){return NULL;} - -int main(){ - pthread_t p; - if(pthread_create(&p,NULL,routine,NULL)!=0) - return 1; - (void)pthread_detach(p); - return 0; -} - +int main() { return 0; } _ACEOF -rm -f conftest$ac_exeext -if { (ac_try="$ac_link" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_link") 2>&5 - ac_status=$? - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { ac_try='./conftest$ac_exeext' - { (case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_try") 2>&5 - ac_status=$? - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); }; }; then - ac_cv_kthread=yes +if ac_fn_c_try_run "$LINENO"; then : + ac_enable_profiling="yes" else - echo "$as_me: program exited with status $ac_status" >&5 -echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - -( exit $ac_status ) -ac_cv_kthread=no + ac_enable_profiling="no" fi -rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext conftest.$ac_objext conftest.$ac_ext +rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext \ + conftest.$ac_objext conftest.beam conftest.$ac_ext fi - -CC="$ac_save_cc" + CC="$ac_save_cc" fi -{ echo "$as_me:$LINENO: result: $ac_cv_kthread" >&5 -echo "${ECHO_T}$ac_cv_kthread" >&6; } -fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_enable_profiling" >&5 +$as_echo "$ac_enable_profiling" >&6; } -if test $ac_cv_kthread = no -a $ac_cv_pthread_is_default = no +case "$ac_enable_profiling" in + "yes") + BASECFLAGS="-pg $BASECFLAGS" + LDFLAGS="-pg $LDFLAGS" + ;; +esac + +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking LDLIBRARY" >&5 +$as_echo_n "checking LDLIBRARY... " >&6; } + +# MacOSX framework builds need more magic. LDLIBRARY is the dynamic +# library that we build, but we do not want to link against it (we +# will find it with a -framework option). For this reason there is an +# extra variable BLDLIBRARY against which Python and the extension +# modules are linked, BLDLIBRARY. This is normally the same as +# LDLIBRARY, but empty for MacOSX framework builds. +if test "$enable_framework" then -# -pthread, if available, provides the right #defines -# and linker options to make pthread_create available -# Some compilers won't report that they do not support -pthread, -# so we need to run a program to see whether it really made the -# function available. -{ echo "$as_me:$LINENO: checking whether $CC accepts -pthread" >&5 -echo $ECHO_N "checking whether $CC accepts -pthread... $ECHO_C" >&6; } -if test "${ac_cv_thread+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 -else - ac_save_cc="$CC" -CC="$CC -pthread" -if test "$cross_compiling" = yes; then - ac_cv_pthread=no + LDLIBRARY='$(PYTHONFRAMEWORKDIR)/Versions/$(VERSION)/$(PYTHONFRAMEWORK)' + RUNSHARED=DYLD_FRAMEWORK_PATH="`pwd`:$DYLD_FRAMEWORK_PATH" + BLDLIBRARY='' else - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ + BLDLIBRARY='$(LDLIBRARY)' +fi -#include +# Other platforms follow +if test $enable_shared = "yes"; then -void* routine(void* p){return NULL;} +$as_echo "#define Py_ENABLE_SHARED 1" >>confdefs.h -int main(){ - pthread_t p; - if(pthread_create(&p,NULL,routine,NULL)!=0) - return 1; - (void)pthread_detach(p); - return 0; -} + case $ac_sys_system in + BeOS*) + LDLIBRARY='libpython$(VERSION).so' + ;; + CYGWIN*) + LDLIBRARY='libpython$(VERSION).dll.a' + DLLLIBRARY='libpython$(VERSION).dll' + ;; + SunOS*) + LDLIBRARY='libpython$(VERSION).so' + BLDLIBRARY='-Wl,-R,$(LIBDIR) -L. -lpython$(VERSION)' + RUNSHARED=LD_LIBRARY_PATH=`pwd`:${LD_LIBRARY_PATH} + INSTSONAME="$LDLIBRARY".$SOVERSION + ;; + Linux*|GNU*|NetBSD*|FreeBSD*|DragonFly*) + LDLIBRARY='libpython$(VERSION).so' + BLDLIBRARY='-L. -lpython$(VERSION)' + RUNSHARED=LD_LIBRARY_PATH=`pwd`:${LD_LIBRARY_PATH} + case $ac_sys_system in + FreeBSD*) + SOVERSION=`echo $SOVERSION|cut -d "." -f 1` + ;; + esac + INSTSONAME="$LDLIBRARY".$SOVERSION + ;; + hp*|HP*) + case `uname -m` in + ia64) + LDLIBRARY='libpython$(VERSION).so' + ;; + *) + LDLIBRARY='libpython$(VERSION).sl' + ;; + esac + BLDLIBRARY='-Wl,+b,$(LIBDIR) -L. -lpython$(VERSION)' + RUNSHARED=SHLIB_PATH=`pwd`:${SHLIB_PATH} + ;; + OSF*) + LDLIBRARY='libpython$(VERSION).so' + BLDLIBRARY='-rpath $(LIBDIR) -L. -lpython$(VERSION)' + RUNSHARED=LD_LIBRARY_PATH=`pwd`:${LD_LIBRARY_PATH} + ;; + atheos*) + LDLIBRARY='libpython$(VERSION).so' + BLDLIBRARY='-L. -lpython$(VERSION)' + RUNSHARED=DLL_PATH=`pwd`:${DLL_PATH:-/atheos/sys/libs:/atheos/autolnk/lib} + ;; + Darwin*) + LDLIBRARY='libpython$(VERSION).dylib' + BLDLIBRARY='-L. -lpython$(VERSION)' + RUNSHARED='DYLD_LIBRARY_PATH=`pwd`:${DYLD_LIBRARY_PATH}' + ;; -_ACEOF -rm -f conftest$ac_exeext -if { (ac_try="$ac_link" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_link") 2>&5 - ac_status=$? - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { ac_try='./conftest$ac_exeext' - { (case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_try") 2>&5 - ac_status=$? - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); }; }; then - ac_cv_pthread=yes + esac +else # shared is disabled + case $ac_sys_system in + CYGWIN*) + BLDLIBRARY='$(LIBRARY)' + LDLIBRARY='libpython$(VERSION).dll.a' + ;; + esac +fi + +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $LDLIBRARY" >&5 +$as_echo "$LDLIBRARY" >&6; } + +if test -n "$ac_tool_prefix"; then + # Extract the first word of "${ac_tool_prefix}ranlib", so it can be a program name with args. +set dummy ${ac_tool_prefix}ranlib; ac_word=$2 +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 +$as_echo_n "checking for $ac_word... " >&6; } +if test "${ac_cv_prog_RANLIB+set}" = set; then : + $as_echo_n "(cached) " >&6 else - echo "$as_me: program exited with status $ac_status" >&5 -echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 + if test -n "$RANLIB"; then + ac_cv_prog_RANLIB="$RANLIB" # Let the user override the test. +else +as_save_IFS=$IFS; IFS=$PATH_SEPARATOR +for as_dir in $PATH +do + IFS=$as_save_IFS + test -z "$as_dir" && as_dir=. + for ac_exec_ext in '' $ac_executable_extensions; do + if { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_test_x "$as_dir/$ac_word$ac_exec_ext"; }; then + ac_cv_prog_RANLIB="${ac_tool_prefix}ranlib" + $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 + break 2 + fi +done + done +IFS=$as_save_IFS -( exit $ac_status ) -ac_cv_pthread=no fi -rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext conftest.$ac_objext conftest.$ac_ext +fi +RANLIB=$ac_cv_prog_RANLIB +if test -n "$RANLIB"; then + { $as_echo "$as_me:${as_lineno-$LINENO}: result: $RANLIB" >&5 +$as_echo "$RANLIB" >&6; } +else + { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 +$as_echo "no" >&6; } fi -CC="$ac_save_cc" fi +if test -z "$ac_cv_prog_RANLIB"; then + ac_ct_RANLIB=$RANLIB + # Extract the first word of "ranlib", so it can be a program name with args. +set dummy ranlib; ac_word=$2 +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 +$as_echo_n "checking for $ac_word... " >&6; } +if test "${ac_cv_prog_ac_ct_RANLIB+set}" = set; then : + $as_echo_n "(cached) " >&6 +else + if test -n "$ac_ct_RANLIB"; then + ac_cv_prog_ac_ct_RANLIB="$ac_ct_RANLIB" # Let the user override the test. +else +as_save_IFS=$IFS; IFS=$PATH_SEPARATOR +for as_dir in $PATH +do + IFS=$as_save_IFS + test -z "$as_dir" && as_dir=. + for ac_exec_ext in '' $ac_executable_extensions; do + if { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_test_x "$as_dir/$ac_word$ac_exec_ext"; }; then + ac_cv_prog_ac_ct_RANLIB="ranlib" + $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 + break 2 + fi +done + done +IFS=$as_save_IFS -{ echo "$as_me:$LINENO: result: $ac_cv_pthread" >&5 -echo "${ECHO_T}$ac_cv_pthread" >&6; } fi - -# If we have set a CC compiler flag for thread support then -# check if it works for CXX, too. -ac_cv_cxx_thread=no -if test ! -z "$CXX" -then -{ echo "$as_me:$LINENO: checking whether $CXX also accepts flags for thread support" >&5 -echo $ECHO_N "checking whether $CXX also accepts flags for thread support... $ECHO_C" >&6; } -ac_save_cxx="$CXX" - -if test "$ac_cv_kpthread" = "yes" -then - CXX="$CXX -Kpthread" - ac_cv_cxx_thread=yes -elif test "$ac_cv_kthread" = "yes" -then - CXX="$CXX -Kthread" - ac_cv_cxx_thread=yes -elif test "$ac_cv_pthread" = "yes" -then - CXX="$CXX -pthread" - ac_cv_cxx_thread=yes +fi +ac_ct_RANLIB=$ac_cv_prog_ac_ct_RANLIB +if test -n "$ac_ct_RANLIB"; then + { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_ct_RANLIB" >&5 +$as_echo "$ac_ct_RANLIB" >&6; } +else + { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 +$as_echo "no" >&6; } fi -if test $ac_cv_cxx_thread = yes -then - echo 'void foo();int main(){foo();}void foo(){}' > conftest.$ac_ext - $CXX -c conftest.$ac_ext 2>&5 - if $CXX -o conftest$ac_exeext conftest.$ac_objext 2>&5 \ - && test -s conftest$ac_exeext && ./conftest$ac_exeext - then - ac_cv_cxx_thread=yes + if test "x$ac_ct_RANLIB" = x; then + RANLIB=":" else - ac_cv_cxx_thread=no + case $cross_compiling:$ac_tool_warned in +yes:) +{ $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: using cross tools not prefixed with host triplet" >&5 +$as_echo "$as_me: WARNING: using cross tools not prefixed with host triplet" >&2;} +ac_tool_warned=yes ;; +esac + RANLIB=$ac_ct_RANLIB fi - rm -fr conftest* -fi -{ echo "$as_me:$LINENO: result: $ac_cv_cxx_thread" >&5 -echo "${ECHO_T}$ac_cv_cxx_thread" >&6; } +else + RANLIB="$ac_cv_prog_RANLIB" fi -CXX="$ac_save_cxx" -# checks for header files -{ echo "$as_me:$LINENO: checking for ANSI C header files" >&5 -echo $ECHO_N "checking for ANSI C header files... $ECHO_C" >&6; } -if test "${ac_cv_header_stdc+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 +for ac_prog in ar aal +do + # Extract the first word of "$ac_prog", so it can be a program name with args. +set dummy $ac_prog; ac_word=$2 +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 +$as_echo_n "checking for $ac_word... " >&6; } +if test "${ac_cv_prog_AR+set}" = set; then : + $as_echo_n "(cached) " >&6 else - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -#include -#include -#include -#include - -int -main () -{ - - ; - return 0; -} -_ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - ac_cv_header_stdc=yes + if test -n "$AR"; then + ac_cv_prog_AR="$AR" # Let the user override the test. else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 +as_save_IFS=$IFS; IFS=$PATH_SEPARATOR +for as_dir in $PATH +do + IFS=$as_save_IFS + test -z "$as_dir" && as_dir=. + for ac_exec_ext in '' $ac_executable_extensions; do + if { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_test_x "$as_dir/$ac_word$ac_exec_ext"; }; then + ac_cv_prog_AR="$ac_prog" + $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 + break 2 + fi +done + done +IFS=$as_save_IFS - ac_cv_header_stdc=no fi - -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext - -if test $ac_cv_header_stdc = yes; then - # SunOS 4.x string.h does not declare mem*, contrary to ANSI. - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -#include - -_ACEOF -if (eval "$ac_cpp conftest.$ac_ext") 2>&5 | - $EGREP "memchr" >/dev/null 2>&1; then - : +fi +AR=$ac_cv_prog_AR +if test -n "$AR"; then + { $as_echo "$as_me:${as_lineno-$LINENO}: result: $AR" >&5 +$as_echo "$AR" >&6; } else - ac_cv_header_stdc=no + { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 +$as_echo "no" >&6; } fi -rm -f conftest* -fi -if test $ac_cv_header_stdc = yes; then - # ISC 2.0.2 stdlib.h does not declare free, contrary to ANSI. - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -#include + test -n "$AR" && break +done +test -n "$AR" || AR="ar" -_ACEOF -if (eval "$ac_cpp conftest.$ac_ext") 2>&5 | - $EGREP "free" >/dev/null 2>&1; then - : -else - ac_cv_header_stdc=no -fi -rm -f conftest* +# tweak ARFLAGS only if the user didn't set it on the command line + +if test -z "$ARFLAGS" +then + ARFLAGS="rc" fi -if test $ac_cv_header_stdc = yes; then - # /bin/cc in Irix-4.0.5 gets non-ANSI ctype macros unless using -ansi. - if test "$cross_compiling" = yes; then - : + +# Extract the first word of "svnversion", so it can be a program name with args. +set dummy svnversion; ac_word=$2 +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 +$as_echo_n "checking for $ac_word... " >&6; } +if test "${ac_cv_prog_SVNVERSION+set}" = set; then : + $as_echo_n "(cached) " >&6 else - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -#include -#include -#if ((' ' & 0x0FF) == 0x020) -# define ISLOWER(c) ('a' <= (c) && (c) <= 'z') -# define TOUPPER(c) (ISLOWER(c) ? 'A' + ((c) - 'a') : (c)) -#else -# define ISLOWER(c) \ - (('a' <= (c) && (c) <= 'i') \ - || ('j' <= (c) && (c) <= 'r') \ - || ('s' <= (c) && (c) <= 'z')) -# define TOUPPER(c) (ISLOWER(c) ? ((c) | 0x40) : (c)) -#endif - -#define XOR(e, f) (((e) && !(f)) || (!(e) && (f))) -int -main () -{ - int i; - for (i = 0; i < 256; i++) - if (XOR (islower (i), ISLOWER (i)) - || toupper (i) != TOUPPER (i)) - return 2; - return 0; -} -_ACEOF -rm -f conftest$ac_exeext -if { (ac_try="$ac_link" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_link") 2>&5 - ac_status=$? - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { ac_try='./conftest$ac_exeext' - { (case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_try") 2>&5 - ac_status=$? - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); }; }; then - : + if test -n "$SVNVERSION"; then + ac_cv_prog_SVNVERSION="$SVNVERSION" # Let the user override the test. else - echo "$as_me: program exited with status $ac_status" >&5 -echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 +as_save_IFS=$IFS; IFS=$PATH_SEPARATOR +for as_dir in $PATH +do + IFS=$as_save_IFS + test -z "$as_dir" && as_dir=. + for ac_exec_ext in '' $ac_executable_extensions; do + if { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_test_x "$as_dir/$ac_word$ac_exec_ext"; }; then + ac_cv_prog_SVNVERSION="found" + $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 + break 2 + fi +done + done +IFS=$as_save_IFS -( exit $ac_status ) -ac_cv_header_stdc=no -fi -rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext conftest.$ac_objext conftest.$ac_ext + test -z "$ac_cv_prog_SVNVERSION" && ac_cv_prog_SVNVERSION="not-found" fi - - fi +SVNVERSION=$ac_cv_prog_SVNVERSION +if test -n "$SVNVERSION"; then + { $as_echo "$as_me:${as_lineno-$LINENO}: result: $SVNVERSION" >&5 +$as_echo "$SVNVERSION" >&6; } +else + { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 +$as_echo "no" >&6; } fi -{ echo "$as_me:$LINENO: result: $ac_cv_header_stdc" >&5 -echo "${ECHO_T}$ac_cv_header_stdc" >&6; } -if test $ac_cv_header_stdc = yes; then -cat >>confdefs.h <<\_ACEOF -#define STDC_HEADERS 1 -_ACEOF +if test $SVNVERSION = found +then + SVNVERSION="svnversion \$(srcdir)" +else + SVNVERSION="echo Unversioned directory" fi -# On IRIX 5.3, sys/types and inttypes.h are conflicting. - - - - - - +case $MACHDEP in +bsdos*|hp*|HP*) + # install -d does not work on BSDI or HP-UX + if test -z "$INSTALL" + then + INSTALL="${srcdir}/install-sh -c" + fi +esac +ac_aux_dir= +for ac_dir in "$srcdir" "$srcdir/.." "$srcdir/../.."; do + for ac_t in install-sh install.sh shtool; do + if test -f "$ac_dir/$ac_t"; then + ac_aux_dir=$ac_dir + ac_install_sh="$ac_aux_dir/$ac_t -c" + break 2 + fi + done +done +if test -z "$ac_aux_dir"; then + as_fn_error "cannot find install-sh, install.sh, or shtool in \"$srcdir\" \"$srcdir/..\" \"$srcdir/../..\"" "$LINENO" 5 +fi +# These three variables are undocumented and unsupported, +# and are intended to be withdrawn in a future Autoconf release. +# They can cause serious problems if a builder's source tree is in a directory +# whose full name contains unusual characters. +ac_config_guess="$SHELL $ac_aux_dir/config.guess" # Please don't use this var. +ac_config_sub="$SHELL $ac_aux_dir/config.sub" # Please don't use this var. +ac_configure="$SHELL $ac_aux_dir/configure" # Please don't use this var. -for ac_header in sys/types.h sys/stat.h stdlib.h string.h memory.h strings.h \ - inttypes.h stdint.h unistd.h -do -as_ac_Header=`echo "ac_cv_header_$ac_header" | $as_tr_sh` -{ echo "$as_me:$LINENO: checking for $ac_header" >&5 -echo $ECHO_N "checking for $ac_header... $ECHO_C" >&6; } -if { as_var=$as_ac_Header; eval "test \"\${$as_var+set}\" = set"; }; then - echo $ECHO_N "(cached) $ECHO_C" >&6 +# Find a good install program. We prefer a C program (faster), +# so one script is as good as another. But avoid the broken or +# incompatible versions: +# SysV /etc/install, /usr/sbin/install +# SunOS /usr/etc/install +# IRIX /sbin/install +# AIX /bin/install +# AmigaOS /C/install, which installs bootblocks on floppy discs +# AIX 4 /usr/bin/installbsd, which doesn't work without a -g flag +# AFS /usr/afsws/bin/install, which mishandles nonexistent args +# SVR4 /usr/ucb/install, which tries to use the nonexistent group "staff" +# OS/2's system install, which has a completely different semantic +# ./install, which can be erroneously created by make from ./install.sh. +# Reject install programs that cannot install multiple files. +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for a BSD-compatible install" >&5 +$as_echo_n "checking for a BSD-compatible install... " >&6; } +if test -z "$INSTALL"; then +if test "${ac_cv_path_install+set}" = set; then : + $as_echo_n "(cached) " >&6 else - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -$ac_includes_default - -#include <$ac_header> -_ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; + as_save_IFS=$IFS; IFS=$PATH_SEPARATOR +for as_dir in $PATH +do + IFS=$as_save_IFS + test -z "$as_dir" && as_dir=. + # Account for people who put trailing slashes in PATH elements. +case $as_dir/ in #(( + ./ | .// | /[cC]/* | \ + /etc/* | /usr/sbin/* | /usr/etc/* | /sbin/* | /usr/afsws/bin/* | \ + ?:[\\/]os2[\\/]install[\\/]* | ?:[\\/]OS2[\\/]INSTALL[\\/]* | \ + /usr/ucb/* ) ;; + *) + # OSF1 and SCO ODT 3.0 have their own names for install. + # Don't use installbsd from OSF since it installs stuff as root + # by default. + for ac_prog in ginstall scoinst install; do + for ac_exec_ext in '' $ac_executable_extensions; do + if { test -f "$as_dir/$ac_prog$ac_exec_ext" && $as_test_x "$as_dir/$ac_prog$ac_exec_ext"; }; then + if test $ac_prog = install && + grep dspmsg "$as_dir/$ac_prog$ac_exec_ext" >/dev/null 2>&1; then + # AIX install. It has an incompatible calling convention. + : + elif test $ac_prog = install && + grep pwplus "$as_dir/$ac_prog$ac_exec_ext" >/dev/null 2>&1; then + # program-specific install script used by HP pwplus--don't use. + : + else + rm -rf conftest.one conftest.two conftest.dir + echo one > conftest.one + echo two > conftest.two + mkdir conftest.dir + if "$as_dir/$ac_prog$ac_exec_ext" -c conftest.one conftest.two "`pwd`/conftest.dir" && + test -s conftest.one && test -s conftest.two && + test -s conftest.dir/conftest.one && + test -s conftest.dir/conftest.two + then + ac_cv_path_install="$as_dir/$ac_prog$ac_exec_ext -c" + break 3 + fi + fi + fi + done + done + ;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - eval "$as_ac_Header=yes" -else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - eval "$as_ac_Header=no" -fi + done +IFS=$as_save_IFS -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext -fi -ac_res=`eval echo '${'$as_ac_Header'}'` - { echo "$as_me:$LINENO: result: $ac_res" >&5 -echo "${ECHO_T}$ac_res" >&6; } -if test `eval echo '${'$as_ac_Header'}'` = yes; then - cat >>confdefs.h <<_ACEOF -#define `echo "HAVE_$ac_header" | $as_tr_cpp` 1 -_ACEOF +rm -rf conftest.one conftest.two conftest.dir fi + if test "${ac_cv_path_install+set}" = set; then + INSTALL=$ac_cv_path_install + else + # As a last resort, use the slow shell script. Don't cache a + # value for INSTALL within a source directory, because that will + # break other packages using the cache if that directory is + # removed, or if the value is a relative name. + INSTALL=$ac_install_sh + fi +fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $INSTALL" >&5 +$as_echo "$INSTALL" >&6; } -done - - - - - - - - - - - - - - - - - - - - - - +# Use test -z because SunOS4 sh mishandles braces in ${var-val}. +# It thinks the first close brace ends the variable substitution. +test -z "$INSTALL_PROGRAM" && INSTALL_PROGRAM='${INSTALL}' +test -z "$INSTALL_SCRIPT" && INSTALL_SCRIPT='${INSTALL}' +test -z "$INSTALL_DATA" && INSTALL_DATA='${INSTALL} -m 644' +# Not every filesystem supports hard links +if test -z "$LN" ; then + case $ac_sys_system in + BeOS*) LN="ln -s";; + CYGWIN*) LN="ln -s";; + atheos*) LN="ln -s";; + *) LN=ln;; + esac +fi +# Check for --with-pydebug +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for --with-pydebug" >&5 +$as_echo_n "checking for --with-pydebug... " >&6; } +# Check whether --with-pydebug was given. +if test "${with_pydebug+set}" = set; then : + withval=$with_pydebug; +if test "$withval" != no +then +$as_echo "#define Py_DEBUG 1" >>confdefs.h + { $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +$as_echo "yes" >&6; }; + Py_DEBUG='true' +else { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 +$as_echo "no" >&6; }; Py_DEBUG='false' +fi +else + { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 +$as_echo "no" >&6; } +fi +# XXX Shouldn't the code above that fiddles with BASECFLAGS and OPT be +# merged with this chunk of code? +# Optimizer/debugger flags +# ------------------------ +# (The following bit of code is complicated enough - please keep things +# indented properly. Just pretend you're editing Python code. ;-) +# There are two parallel sets of case statements below, one that checks to +# see if OPT was set and one that does BASECFLAGS setting based upon +# compiler and platform. BASECFLAGS tweaks need to be made even if the +# user set OPT. +# tweak OPT based on compiler and platform, only if the user didn't set +# it on the command line +if test "${OPT-unset}" = "unset" +then + case $GCC in + yes) + if test "$CC" != 'g++' ; then + STRICT_PROTO="-Wstrict-prototypes" + fi + # For gcc 4.x we need to use -fwrapv so lets check if its supported + if "$CC" -v --help 2>/dev/null |grep -- -fwrapv > /dev/null; then + WRAP="-fwrapv" + fi + case $ac_cv_prog_cc_g in + yes) + if test "$Py_DEBUG" = 'true' ; then + # Optimization messes up debuggers, so turn it off for + # debug builds. + OPT="-g -O0 -Wall $STRICT_PROTO" + else + OPT="-g $WRAP -O3 -Wall $STRICT_PROTO" + fi + ;; + *) + OPT="-O3 -Wall $STRICT_PROTO" + ;; + esac + case $ac_sys_system in + SCO_SV*) OPT="$OPT -m486 -DSCO5" + ;; + esac + ;; + *) + OPT="-O" + ;; + esac +fi +# The -arch flags for universal builds on OSX +UNIVERSAL_ARCH_FLAGS= +# tweak BASECFLAGS based on compiler and platform +case $GCC in +yes) + # Python violates C99 rules, by casting between incompatible + # pointer types. GCC may generate bad code as a result of that, + # so use -fno-strict-aliasing if supported. + { $as_echo "$as_me:${as_lineno-$LINENO}: checking whether $CC accepts -fno-strict-aliasing" >&5 +$as_echo_n "checking whether $CC accepts -fno-strict-aliasing... " >&6; } + ac_save_cc="$CC" + CC="$CC -fno-strict-aliasing" + if test "${ac_cv_no_strict_aliasing_ok+set}" = set; then : + $as_echo_n "(cached) " >&6 +else + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ +int +main () +{ +int main() { return 0; } + ; + return 0; +} +_ACEOF +if ac_fn_c_try_compile "$LINENO"; then : + ac_cv_no_strict_aliasing_ok=yes +else + ac_cv_no_strict_aliasing_ok=no +fi +rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext +fi + CC="$ac_save_cc" + { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_no_strict_aliasing_ok" >&5 +$as_echo "$ac_cv_no_strict_aliasing_ok" >&6; } + if test $ac_cv_no_strict_aliasing_ok = yes + then + BASECFLAGS="$BASECFLAGS -fno-strict-aliasing" + fi + # if using gcc on alpha, use -mieee to get (near) full IEEE 754 + # support. Without this, treatment of subnormals doesn't follow + # the standard. + case $ac_sys_machine in + alpha*) + BASECFLAGS="$BASECFLAGS -mieee" + ;; + esac + case $ac_sys_system in + SCO_SV*) + BASECFLAGS="$BASECFLAGS -m486 -DSCO5" + ;; + # is there any other compiler on Darwin besides gcc? + Darwin*) + # -Wno-long-double, -no-cpp-precomp, and -mno-fused-madd + # used to be here, but non-Apple gcc doesn't accept them. + if test "${CC}" = gcc + then + { $as_echo "$as_me:${as_lineno-$LINENO}: checking which compiler should be used" >&5 +$as_echo_n "checking which compiler should be used... " >&6; } + case "${UNIVERSALSDK}" in + */MacOSX10.4u.sdk) + # Build using 10.4 SDK, force usage of gcc when the + # compiler is gcc, otherwise the user will get very + # confusing error messages when building on OSX 10.6 + CC=gcc-4.0 + CPP=cpp-4.0 + ;; + esac + { $as_echo "$as_me:${as_lineno-$LINENO}: result: $CC" >&5 +$as_echo "$CC" >&6; } + fi + # Calculate the right deployment target for this build. + # + cur_target=`sw_vers -productVersion | sed 's/\(10\.[0-9]*\).*/\1/'` + if test ${cur_target} '>' 10.2; then + cur_target=10.3 + if test ${enable_universalsdk}; then + if test "${UNIVERSAL_ARCHS}" = "all"; then + # Ensure that the default platform for a + # 4-way universal build is OSX 10.5, + # that's the first OS release where + # 4-way builds make sense. + cur_target='10.5' + elif test "${UNIVERSAL_ARCHS}" = "3-way"; then + cur_target='10.5' + elif test "${UNIVERSAL_ARCHS}" = "intel"; then + cur_target='10.5' + elif test "${UNIVERSAL_ARCHS}" = "64-bit"; then + cur_target='10.5' + fi + else + if test `/usr/bin/arch` = "i386"; then + # On Intel macs default to a deployment + # target of 10.4, that's the first OSX + # release with Intel support. + cur_target="10.4" + fi + fi + fi + CONFIGURE_MACOSX_DEPLOYMENT_TARGET=${MACOSX_DEPLOYMENT_TARGET-${cur_target}} + # Make sure that MACOSX_DEPLOYMENT_TARGET is set in the + # environment with a value that is the same as what we'll use + # in the Makefile to ensure that we'll get the same compiler + # environment during configure and build time. + MACOSX_DEPLOYMENT_TARGET="$CONFIGURE_MACOSX_DEPLOYMENT_TARGET" + export MACOSX_DEPLOYMENT_TARGET + EXPORT_MACOSX_DEPLOYMENT_TARGET='' + if test "${enable_universalsdk}"; then + UNIVERSAL_ARCH_FLAGS="" + if test "$UNIVERSAL_ARCHS" = "32-bit" ; then + UNIVERSAL_ARCH_FLAGS="-arch ppc -arch i386" + ARCH_RUN_32BIT="" + LIPO_32BIT_FLAGS="" + elif test "$UNIVERSAL_ARCHS" = "64-bit" ; then + UNIVERSAL_ARCH_FLAGS="-arch ppc64 -arch x86_64" + LIPO_32BIT_FLAGS="" + ARCH_RUN_32BIT="true" + elif test "$UNIVERSAL_ARCHS" = "all" ; then + UNIVERSAL_ARCH_FLAGS="-arch i386 -arch ppc -arch ppc64 -arch x86_64" + LIPO_32BIT_FLAGS="-extract ppc7400 -extract i386" + ARCH_RUN_32BIT="/usr/bin/arch -i386 -ppc" + elif test "$UNIVERSAL_ARCHS" = "intel" ; then + UNIVERSAL_ARCH_FLAGS="-arch i386 -arch x86_64" + LIPO_32BIT_FLAGS="-extract i386" + ARCH_RUN_32BIT="/usr/bin/arch -i386" + elif test "$UNIVERSAL_ARCHS" = "3-way" ; then + UNIVERSAL_ARCH_FLAGS="-arch i386 -arch ppc -arch x86_64" + LIPO_32BIT_FLAGS="-extract ppc7400 -extract i386" + ARCH_RUN_32BIT="/usr/bin/arch -i386 -ppc" -for ac_header in asm/types.h conio.h curses.h direct.h dlfcn.h errno.h \ -fcntl.h grp.h \ -ieeefp.h io.h langinfo.h libintl.h ncurses.h poll.h process.h pthread.h \ -shadow.h signal.h stdint.h stropts.h termios.h thread.h \ -unistd.h utime.h \ -sys/audioio.h sys/bsdtty.h sys/epoll.h sys/event.h sys/file.h sys/loadavg.h \ -sys/lock.h sys/mkdev.h sys/modem.h \ -sys/param.h sys/poll.h sys/select.h sys/socket.h sys/statvfs.h sys/stat.h \ -sys/termio.h sys/time.h \ -sys/times.h sys/types.h sys/un.h sys/utsname.h sys/wait.h pty.h libutil.h \ -sys/resource.h netpacket/packet.h sysexits.h bluetooth.h \ -bluetooth/bluetooth.h linux/tipc.h spawn.h util.h -do -as_ac_Header=`echo "ac_cv_header_$ac_header" | $as_tr_sh` -if { as_var=$as_ac_Header; eval "test \"\${$as_var+set}\" = set"; }; then - { echo "$as_me:$LINENO: checking for $ac_header" >&5 -echo $ECHO_N "checking for $ac_header... $ECHO_C" >&6; } -if { as_var=$as_ac_Header; eval "test \"\${$as_var+set}\" = set"; }; then - echo $ECHO_N "(cached) $ECHO_C" >&6 -fi -ac_res=`eval echo '${'$as_ac_Header'}'` - { echo "$as_me:$LINENO: result: $ac_res" >&5 -echo "${ECHO_T}$ac_res" >&6; } -else - # Is the header compilable? -{ echo "$as_me:$LINENO: checking $ac_header usability" >&5 -echo $ECHO_N "checking $ac_header usability... $ECHO_C" >&6; } -cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -$ac_includes_default -#include <$ac_header> -_ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - ac_header_compiler=yes -else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 + else + as_fn_error "proper usage is --with-universal-arch=32-bit|64-bit|all|intel|3-way" "$LINENO" 5 - ac_header_compiler=no -fi + fi -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext -{ echo "$as_me:$LINENO: result: $ac_header_compiler" >&5 -echo "${ECHO_T}$ac_header_compiler" >&6; } -# Is the header present? -{ echo "$as_me:$LINENO: checking $ac_header presence" >&5 -echo $ECHO_N "checking $ac_header presence... $ECHO_C" >&6; } -cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -#include <$ac_header> -_ACEOF -if { (ac_try="$ac_cpp conftest.$ac_ext" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_cpp conftest.$ac_ext") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } >/dev/null && { - test -z "$ac_c_preproc_warn_flag$ac_c_werror_flag" || - test ! -s conftest.err - }; then - ac_header_preproc=yes -else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 + CFLAGS="${UNIVERSAL_ARCH_FLAGS} ${CFLAGS}" + if test "${UNIVERSALSDK}" != "/" + then + CPPFLAGS="-isysroot ${UNIVERSALSDK} ${CPPFLAGS}" + LDFLAGS="-isysroot ${UNIVERSALSDK} ${LDFLAGS}" + CFLAGS="-isysroot ${UNIVERSALSDK} ${CFLAGS}" + fi - ac_header_preproc=no -fi + fi -rm -f conftest.err conftest.$ac_ext -{ echo "$as_me:$LINENO: result: $ac_header_preproc" >&5 -echo "${ECHO_T}$ac_header_preproc" >&6; } -# So? What about this header? -case $ac_header_compiler:$ac_header_preproc:$ac_c_preproc_warn_flag in - yes:no: ) - { echo "$as_me:$LINENO: WARNING: $ac_header: accepted by the compiler, rejected by the preprocessor!" >&5 -echo "$as_me: WARNING: $ac_header: accepted by the compiler, rejected by the preprocessor!" >&2;} - { echo "$as_me:$LINENO: WARNING: $ac_header: proceeding with the compiler's result" >&5 -echo "$as_me: WARNING: $ac_header: proceeding with the compiler's result" >&2;} - ac_header_preproc=yes + ;; + OSF*) + BASECFLAGS="$BASECFLAGS -mieee" + ;; + esac ;; - no:yes:* ) - { echo "$as_me:$LINENO: WARNING: $ac_header: present but cannot be compiled" >&5 -echo "$as_me: WARNING: $ac_header: present but cannot be compiled" >&2;} - { echo "$as_me:$LINENO: WARNING: $ac_header: check for missing prerequisite headers?" >&5 -echo "$as_me: WARNING: $ac_header: check for missing prerequisite headers?" >&2;} - { echo "$as_me:$LINENO: WARNING: $ac_header: see the Autoconf documentation" >&5 -echo "$as_me: WARNING: $ac_header: see the Autoconf documentation" >&2;} - { echo "$as_me:$LINENO: WARNING: $ac_header: section \"Present But Cannot Be Compiled\"" >&5 -echo "$as_me: WARNING: $ac_header: section \"Present But Cannot Be Compiled\"" >&2;} - { echo "$as_me:$LINENO: WARNING: $ac_header: proceeding with the preprocessor's result" >&5 -echo "$as_me: WARNING: $ac_header: proceeding with the preprocessor's result" >&2;} - { echo "$as_me:$LINENO: WARNING: $ac_header: in the future, the compiler will take precedence" >&5 -echo "$as_me: WARNING: $ac_header: in the future, the compiler will take precedence" >&2;} - ( cat <<\_ASBOX -## -------------------------------------- ## -## Report this to http://bugs.python.org/ ## -## -------------------------------------- ## -_ASBOX - ) | sed "s/^/$as_me: WARNING: /" >&2 + +*) + case $ac_sys_system in + OpenUNIX*|UnixWare*) + BASECFLAGS="$BASECFLAGS -K pentium,host,inline,loop_unroll,alloca " + ;; + OSF*) + BASECFLAGS="$BASECFLAGS -ieee -std" + ;; + SCO_SV*) + BASECFLAGS="$BASECFLAGS -belf -Ki486 -DSCO5" + ;; + esac ;; esac -{ echo "$as_me:$LINENO: checking for $ac_header" >&5 -echo $ECHO_N "checking for $ac_header... $ECHO_C" >&6; } -if { as_var=$as_ac_Header; eval "test \"\${$as_var+set}\" = set"; }; then - echo $ECHO_N "(cached) $ECHO_C" >&6 + +if test "$Py_DEBUG" = 'true'; then + : else - eval "$as_ac_Header=\$ac_header_preproc" + OPT="-DNDEBUG $OPT" fi -ac_res=`eval echo '${'$as_ac_Header'}'` - { echo "$as_me:$LINENO: result: $ac_res" >&5 -echo "${ECHO_T}$ac_res" >&6; } +if test "$ac_arch_flags" +then + BASECFLAGS="$BASECFLAGS $ac_arch_flags" fi -if test `eval echo '${'$as_ac_Header'}'` = yes; then - cat >>confdefs.h <<_ACEOF -#define `echo "HAVE_$ac_header" | $as_tr_cpp` 1 -_ACEOF +# disable check for icc since it seems to pass, but generates a warning +if test "$CC" = icc +then + ac_cv_opt_olimit_ok=no fi -done - - - - - - -ac_header_dirent=no -for ac_hdr in dirent.h sys/ndir.h sys/dir.h ndir.h; do - as_ac_Header=`echo "ac_cv_header_dirent_$ac_hdr" | $as_tr_sh` -{ echo "$as_me:$LINENO: checking for $ac_hdr that defines DIR" >&5 -echo $ECHO_N "checking for $ac_hdr that defines DIR... $ECHO_C" >&6; } -if { as_var=$as_ac_Header; eval "test \"\${$as_var+set}\" = set"; }; then - echo $ECHO_N "(cached) $ECHO_C" >&6 +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking whether $CC accepts -OPT:Olimit=0" >&5 +$as_echo_n "checking whether $CC accepts -OPT:Olimit=0... " >&6; } +if test "${ac_cv_opt_olimit_ok+set}" = set; then : + $as_echo_n "(cached) " >&6 else - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF + ac_save_cc="$CC" +CC="$CC -OPT:Olimit=0" +cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ -#include -#include <$ac_hdr> int main () { -if ((DIR *) 0) -return 0; +int main() { return 0; } ; return 0; } _ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - eval "$as_ac_Header=yes" +if ac_fn_c_try_compile "$LINENO"; then : + ac_cv_opt_olimit_ok=yes else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - eval "$as_ac_Header=no" + ac_cv_opt_olimit_ok=no fi - rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext -fi -ac_res=`eval echo '${'$as_ac_Header'}'` - { echo "$as_me:$LINENO: result: $ac_res" >&5 -echo "${ECHO_T}$ac_res" >&6; } -if test `eval echo '${'$as_ac_Header'}'` = yes; then - cat >>confdefs.h <<_ACEOF -#define `echo "HAVE_$ac_hdr" | $as_tr_cpp` 1 -_ACEOF - -ac_header_dirent=$ac_hdr; break +CC="$ac_save_cc" fi -done -# Two versions of opendir et al. are in -ldir and -lx on SCO Xenix. -if test $ac_header_dirent = dirent.h; then - { echo "$as_me:$LINENO: checking for library containing opendir" >&5 -echo $ECHO_N "checking for library containing opendir... $ECHO_C" >&6; } -if test "${ac_cv_search_opendir+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_opt_olimit_ok" >&5 +$as_echo "$ac_cv_opt_olimit_ok" >&6; } +if test $ac_cv_opt_olimit_ok = yes; then + case $ac_sys_system in + # XXX is this branch needed? On MacOSX 10.2.2 the result of the + # olimit_ok test is "no". Is it "yes" in some other Darwin-esque + # environment? + Darwin*) + ;; + *) + BASECFLAGS="$BASECFLAGS -OPT:Olimit=0" + ;; + esac else - ac_func_search_save_LIBS=$LIBS -cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF + { $as_echo "$as_me:${as_lineno-$LINENO}: checking whether $CC accepts -Olimit 1500" >&5 +$as_echo_n "checking whether $CC accepts -Olimit 1500... " >&6; } + if test "${ac_cv_olimit_ok+set}" = set; then : + $as_echo_n "(cached) " >&6 +else + ac_save_cc="$CC" + CC="$CC -Olimit 1500" + cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ -/* Override any GCC internal prototype to avoid an error. - Use char because int might match the return type of a GCC - builtin and then its argument prototype would still apply. */ -#ifdef __cplusplus -extern "C" -#endif -char opendir (); int main () { -return opendir (); +int main() { return 0; } ; return 0; } _ACEOF -for ac_lib in '' dir; do - if test -z "$ac_lib"; then - ac_res="none required" - else - ac_res=-l$ac_lib - LIBS="-l$ac_lib $ac_func_search_save_LIBS" - fi - rm -f conftest.$ac_objext conftest$ac_exeext -if { (ac_try="$ac_link" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_link") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest$ac_exeext && - $as_test_x conftest$ac_exeext; then - ac_cv_search_opendir=$ac_res -else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - -fi - -rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \ - conftest$ac_exeext - if test "${ac_cv_search_opendir+set}" = set; then - break -fi -done -if test "${ac_cv_search_opendir+set}" = set; then - : +if ac_fn_c_try_compile "$LINENO"; then : + ac_cv_olimit_ok=yes else - ac_cv_search_opendir=no + ac_cv_olimit_ok=no fi -rm conftest.$ac_ext -LIBS=$ac_func_search_save_LIBS +rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext + CC="$ac_save_cc" fi -{ echo "$as_me:$LINENO: result: $ac_cv_search_opendir" >&5 -echo "${ECHO_T}$ac_cv_search_opendir" >&6; } -ac_res=$ac_cv_search_opendir -if test "$ac_res" != no; then - test "$ac_res" = "none required" || LIBS="$ac_res $LIBS" + { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_olimit_ok" >&5 +$as_echo "$ac_cv_olimit_ok" >&6; } + if test $ac_cv_olimit_ok = yes; then + BASECFLAGS="$BASECFLAGS -Olimit 1500" + fi fi -else - { echo "$as_me:$LINENO: checking for library containing opendir" >&5 -echo $ECHO_N "checking for library containing opendir... $ECHO_C" >&6; } -if test "${ac_cv_search_opendir+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 -else - ac_func_search_save_LIBS=$LIBS -cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF +# Check whether GCC supports PyArg_ParseTuple format +if test "$GCC" = "yes" +then + { $as_echo "$as_me:${as_lineno-$LINENO}: checking whether gcc supports ParseTuple __format__" >&5 +$as_echo_n "checking whether gcc supports ParseTuple __format__... " >&6; } + save_CFLAGS=$CFLAGS + CFLAGS="$CFLAGS -Werror" + cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ -/* Override any GCC internal prototype to avoid an error. - Use char because int might match the return type of a GCC - builtin and then its argument prototype would still apply. */ -#ifdef __cplusplus -extern "C" -#endif -char opendir (); + void f(char*,...)__attribute((format(PyArg_ParseTuple, 1, 2))); + int main () { -return opendir (); + ; return 0; } _ACEOF -for ac_lib in '' x; do - if test -z "$ac_lib"; then - ac_res="none required" - else - ac_res=-l$ac_lib - LIBS="-l$ac_lib $ac_func_search_save_LIBS" - fi - rm -f conftest.$ac_objext conftest$ac_exeext -if { (ac_try="$ac_link" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_link") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest$ac_exeext && - $as_test_x conftest$ac_exeext; then - ac_cv_search_opendir=$ac_res -else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - +if ac_fn_c_try_compile "$LINENO"; then : -fi +$as_echo "#define HAVE_ATTRIBUTE_FORMAT_PARSETUPLE 1" >>confdefs.h -rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \ - conftest$ac_exeext - if test "${ac_cv_search_opendir+set}" = set; then - break -fi -done -if test "${ac_cv_search_opendir+set}" = set; then - : + { $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +$as_echo "yes" >&6; } else - ac_cv_search_opendir=no -fi -rm conftest.$ac_ext -LIBS=$ac_func_search_save_LIBS -fi -{ echo "$as_me:$LINENO: result: $ac_cv_search_opendir" >&5 -echo "${ECHO_T}$ac_cv_search_opendir" >&6; } -ac_res=$ac_cv_search_opendir -if test "$ac_res" != no; then - test "$ac_res" = "none required" || LIBS="$ac_res $LIBS" + { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 +$as_echo "no" >&6; } fi - +rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext + CFLAGS=$save_CFLAGS fi -{ echo "$as_me:$LINENO: checking whether sys/types.h defines makedev" >&5 -echo $ECHO_N "checking whether sys/types.h defines makedev... $ECHO_C" >&6; } -if test "${ac_cv_header_sys_types_h_makedev+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 +# On some compilers, pthreads are available without further options +# (e.g. MacOS X). On some of these systems, the compiler will not +# complain if unaccepted options are passed (e.g. gcc on Mac OS X). +# So we have to see first whether pthreads are available without +# options before we can check whether -Kpthread improves anything. +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking whether pthreads are available without options" >&5 +$as_echo_n "checking whether pthreads are available without options... " >&6; } +if test "${ac_cv_pthread_is_default+set}" = set; then : + $as_echo_n "(cached) " >&6 else - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF + if test "$cross_compiling" = yes; then : + ac_cv_pthread_is_default=no +else + cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ -#include -int -main () -{ -return makedev(0, 0); - ; + +#include + +void* routine(void* p){return NULL;} + +int main(){ + pthread_t p; + if(pthread_create(&p,NULL,routine,NULL)!=0) + return 1; + (void)pthread_detach(p); return 0; } + _ACEOF -rm -f conftest.$ac_objext conftest$ac_exeext -if { (ac_try="$ac_link" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_link") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest$ac_exeext && - $as_test_x conftest$ac_exeext; then - ac_cv_header_sys_types_h_makedev=yes -else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 +if ac_fn_c_try_run "$LINENO"; then : + + ac_cv_pthread_is_default=yes + ac_cv_kthread=no + ac_cv_pthread=no - ac_cv_header_sys_types_h_makedev=no +else + ac_cv_pthread_is_default=no +fi +rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext \ + conftest.$ac_objext conftest.beam conftest.$ac_ext fi -rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \ - conftest$ac_exeext conftest.$ac_ext fi -{ echo "$as_me:$LINENO: result: $ac_cv_header_sys_types_h_makedev" >&5 -echo "${ECHO_T}$ac_cv_header_sys_types_h_makedev" >&6; } -if test $ac_cv_header_sys_types_h_makedev = no; then -if test "${ac_cv_header_sys_mkdev_h+set}" = set; then - { echo "$as_me:$LINENO: checking for sys/mkdev.h" >&5 -echo $ECHO_N "checking for sys/mkdev.h... $ECHO_C" >&6; } -if test "${ac_cv_header_sys_mkdev_h+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 -fi -{ echo "$as_me:$LINENO: result: $ac_cv_header_sys_mkdev_h" >&5 -echo "${ECHO_T}$ac_cv_header_sys_mkdev_h" >&6; } +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_pthread_is_default" >&5 +$as_echo "$ac_cv_pthread_is_default" >&6; } + + +if test $ac_cv_pthread_is_default = yes +then + ac_cv_kpthread=no else - # Is the header compilable? -{ echo "$as_me:$LINENO: checking sys/mkdev.h usability" >&5 -echo $ECHO_N "checking sys/mkdev.h usability... $ECHO_C" >&6; } -cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -$ac_includes_default -#include -_ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - ac_header_compiler=yes +# -Kpthread, if available, provides the right #defines +# and linker options to make pthread_create available +# Some compilers won't report that they do not support -Kpthread, +# so we need to run a program to see whether it really made the +# function available. +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking whether $CC accepts -Kpthread" >&5 +$as_echo_n "checking whether $CC accepts -Kpthread... " >&6; } +if test "${ac_cv_kpthread+set}" = set; then : + $as_echo_n "(cached) " >&6 else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 + ac_save_cc="$CC" +CC="$CC -Kpthread" +if test "$cross_compiling" = yes; then : + ac_cv_kpthread=no +else + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ - ac_header_compiler=no -fi +#include -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext -{ echo "$as_me:$LINENO: result: $ac_header_compiler" >&5 -echo "${ECHO_T}$ac_header_compiler" >&6; } +void* routine(void* p){return NULL;} + +int main(){ + pthread_t p; + if(pthread_create(&p,NULL,routine,NULL)!=0) + return 1; + (void)pthread_detach(p); + return 0; +} -# Is the header present? -{ echo "$as_me:$LINENO: checking sys/mkdev.h presence" >&5 -echo $ECHO_N "checking sys/mkdev.h presence... $ECHO_C" >&6; } -cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -#include _ACEOF -if { (ac_try="$ac_cpp conftest.$ac_ext" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_cpp conftest.$ac_ext") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } >/dev/null && { - test -z "$ac_c_preproc_warn_flag$ac_c_werror_flag" || - test ! -s conftest.err - }; then - ac_header_preproc=yes +if ac_fn_c_try_run "$LINENO"; then : + ac_cv_kpthread=yes else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - ac_header_preproc=no + ac_cv_kpthread=no fi - -rm -f conftest.err conftest.$ac_ext -{ echo "$as_me:$LINENO: result: $ac_header_preproc" >&5 -echo "${ECHO_T}$ac_header_preproc" >&6; } - -# So? What about this header? -case $ac_header_compiler:$ac_header_preproc:$ac_c_preproc_warn_flag in - yes:no: ) - { echo "$as_me:$LINENO: WARNING: sys/mkdev.h: accepted by the compiler, rejected by the preprocessor!" >&5 -echo "$as_me: WARNING: sys/mkdev.h: accepted by the compiler, rejected by the preprocessor!" >&2;} - { echo "$as_me:$LINENO: WARNING: sys/mkdev.h: proceeding with the compiler's result" >&5 -echo "$as_me: WARNING: sys/mkdev.h: proceeding with the compiler's result" >&2;} - ac_header_preproc=yes - ;; - no:yes:* ) - { echo "$as_me:$LINENO: WARNING: sys/mkdev.h: present but cannot be compiled" >&5 -echo "$as_me: WARNING: sys/mkdev.h: present but cannot be compiled" >&2;} - { echo "$as_me:$LINENO: WARNING: sys/mkdev.h: check for missing prerequisite headers?" >&5 -echo "$as_me: WARNING: sys/mkdev.h: check for missing prerequisite headers?" >&2;} - { echo "$as_me:$LINENO: WARNING: sys/mkdev.h: see the Autoconf documentation" >&5 -echo "$as_me: WARNING: sys/mkdev.h: see the Autoconf documentation" >&2;} - { echo "$as_me:$LINENO: WARNING: sys/mkdev.h: section \"Present But Cannot Be Compiled\"" >&5 -echo "$as_me: WARNING: sys/mkdev.h: section \"Present But Cannot Be Compiled\"" >&2;} - { echo "$as_me:$LINENO: WARNING: sys/mkdev.h: proceeding with the preprocessor's result" >&5 -echo "$as_me: WARNING: sys/mkdev.h: proceeding with the preprocessor's result" >&2;} - { echo "$as_me:$LINENO: WARNING: sys/mkdev.h: in the future, the compiler will take precedence" >&5 -echo "$as_me: WARNING: sys/mkdev.h: in the future, the compiler will take precedence" >&2;} - ( cat <<\_ASBOX -## -------------------------------------- ## -## Report this to http://bugs.python.org/ ## -## -------------------------------------- ## -_ASBOX - ) | sed "s/^/$as_me: WARNING: /" >&2 - ;; -esac -{ echo "$as_me:$LINENO: checking for sys/mkdev.h" >&5 -echo $ECHO_N "checking for sys/mkdev.h... $ECHO_C" >&6; } -if test "${ac_cv_header_sys_mkdev_h+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 -else - ac_cv_header_sys_mkdev_h=$ac_header_preproc +rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext \ + conftest.$ac_objext conftest.beam conftest.$ac_ext fi -{ echo "$as_me:$LINENO: result: $ac_cv_header_sys_mkdev_h" >&5 -echo "${ECHO_T}$ac_cv_header_sys_mkdev_h" >&6; } +CC="$ac_save_cc" fi -if test $ac_cv_header_sys_mkdev_h = yes; then - -cat >>confdefs.h <<\_ACEOF -#define MAJOR_IN_MKDEV 1 -_ACEOF +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_kpthread" >&5 +$as_echo "$ac_cv_kpthread" >&6; } fi - - - if test $ac_cv_header_sys_mkdev_h = no; then - if test "${ac_cv_header_sys_sysmacros_h+set}" = set; then - { echo "$as_me:$LINENO: checking for sys/sysmacros.h" >&5 -echo $ECHO_N "checking for sys/sysmacros.h... $ECHO_C" >&6; } -if test "${ac_cv_header_sys_sysmacros_h+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 -fi -{ echo "$as_me:$LINENO: result: $ac_cv_header_sys_sysmacros_h" >&5 -echo "${ECHO_T}$ac_cv_header_sys_sysmacros_h" >&6; } +if test $ac_cv_kpthread = no -a $ac_cv_pthread_is_default = no +then +# -Kthread, if available, provides the right #defines +# and linker options to make pthread_create available +# Some compilers won't report that they do not support -Kthread, +# so we need to run a program to see whether it really made the +# function available. +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking whether $CC accepts -Kthread" >&5 +$as_echo_n "checking whether $CC accepts -Kthread... " >&6; } +if test "${ac_cv_kthread+set}" = set; then : + $as_echo_n "(cached) " >&6 else - # Is the header compilable? -{ echo "$as_me:$LINENO: checking sys/sysmacros.h usability" >&5 -echo $ECHO_N "checking sys/sysmacros.h usability... $ECHO_C" >&6; } -cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -$ac_includes_default -#include -_ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - ac_header_compiler=yes + ac_save_cc="$CC" +CC="$CC -Kthread" +if test "$cross_compiling" = yes; then : + ac_cv_kthread=no else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - ac_header_compiler=no -fi - -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext -{ echo "$as_me:$LINENO: result: $ac_header_compiler" >&5 -echo "${ECHO_T}$ac_header_compiler" >&6; } - -# Is the header present? -{ echo "$as_me:$LINENO: checking sys/sysmacros.h presence" >&5 -echo $ECHO_N "checking sys/sysmacros.h presence... $ECHO_C" >&6; } -cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF + cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ -#include -_ACEOF -if { (ac_try="$ac_cpp conftest.$ac_ext" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_cpp conftest.$ac_ext") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } >/dev/null && { - test -z "$ac_c_preproc_warn_flag$ac_c_werror_flag" || - test ! -s conftest.err - }; then - ac_header_preproc=yes -else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - ac_header_preproc=no -fi +#include -rm -f conftest.err conftest.$ac_ext -{ echo "$as_me:$LINENO: result: $ac_header_preproc" >&5 -echo "${ECHO_T}$ac_header_preproc" >&6; } +void* routine(void* p){return NULL;} -# So? What about this header? -case $ac_header_compiler:$ac_header_preproc:$ac_c_preproc_warn_flag in - yes:no: ) - { echo "$as_me:$LINENO: WARNING: sys/sysmacros.h: accepted by the compiler, rejected by the preprocessor!" >&5 -echo "$as_me: WARNING: sys/sysmacros.h: accepted by the compiler, rejected by the preprocessor!" >&2;} - { echo "$as_me:$LINENO: WARNING: sys/sysmacros.h: proceeding with the compiler's result" >&5 -echo "$as_me: WARNING: sys/sysmacros.h: proceeding with the compiler's result" >&2;} - ac_header_preproc=yes - ;; - no:yes:* ) - { echo "$as_me:$LINENO: WARNING: sys/sysmacros.h: present but cannot be compiled" >&5 -echo "$as_me: WARNING: sys/sysmacros.h: present but cannot be compiled" >&2;} - { echo "$as_me:$LINENO: WARNING: sys/sysmacros.h: check for missing prerequisite headers?" >&5 -echo "$as_me: WARNING: sys/sysmacros.h: check for missing prerequisite headers?" >&2;} - { echo "$as_me:$LINENO: WARNING: sys/sysmacros.h: see the Autoconf documentation" >&5 -echo "$as_me: WARNING: sys/sysmacros.h: see the Autoconf documentation" >&2;} - { echo "$as_me:$LINENO: WARNING: sys/sysmacros.h: section \"Present But Cannot Be Compiled\"" >&5 -echo "$as_me: WARNING: sys/sysmacros.h: section \"Present But Cannot Be Compiled\"" >&2;} - { echo "$as_me:$LINENO: WARNING: sys/sysmacros.h: proceeding with the preprocessor's result" >&5 -echo "$as_me: WARNING: sys/sysmacros.h: proceeding with the preprocessor's result" >&2;} - { echo "$as_me:$LINENO: WARNING: sys/sysmacros.h: in the future, the compiler will take precedence" >&5 -echo "$as_me: WARNING: sys/sysmacros.h: in the future, the compiler will take precedence" >&2;} - ( cat <<\_ASBOX -## -------------------------------------- ## -## Report this to http://bugs.python.org/ ## -## -------------------------------------- ## -_ASBOX - ) | sed "s/^/$as_me: WARNING: /" >&2 - ;; -esac -{ echo "$as_me:$LINENO: checking for sys/sysmacros.h" >&5 -echo $ECHO_N "checking for sys/sysmacros.h... $ECHO_C" >&6; } -if test "${ac_cv_header_sys_sysmacros_h+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 +int main(){ + pthread_t p; + if(pthread_create(&p,NULL,routine,NULL)!=0) + return 1; + (void)pthread_detach(p); + return 0; +} + +_ACEOF +if ac_fn_c_try_run "$LINENO"; then : + ac_cv_kthread=yes else - ac_cv_header_sys_sysmacros_h=$ac_header_preproc + ac_cv_kthread=no fi -{ echo "$as_me:$LINENO: result: $ac_cv_header_sys_sysmacros_h" >&5 -echo "${ECHO_T}$ac_cv_header_sys_sysmacros_h" >&6; } - +rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext \ + conftest.$ac_objext conftest.beam conftest.$ac_ext fi -if test $ac_cv_header_sys_sysmacros_h = yes; then - -cat >>confdefs.h <<\_ACEOF -#define MAJOR_IN_SYSMACROS 1 -_ACEOF +CC="$ac_save_cc" fi - - fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_kthread" >&5 +$as_echo "$ac_cv_kthread" >&6; } fi - -# On Solaris, term.h requires curses.h - -for ac_header in term.h -do -as_ac_Header=`echo "ac_cv_header_$ac_header" | $as_tr_sh` -{ echo "$as_me:$LINENO: checking for $ac_header" >&5 -echo $ECHO_N "checking for $ac_header... $ECHO_C" >&6; } -if { as_var=$as_ac_Header; eval "test \"\${$as_var+set}\" = set"; }; then - echo $ECHO_N "(cached) $ECHO_C" >&6 +if test $ac_cv_kthread = no -a $ac_cv_pthread_is_default = no +then +# -pthread, if available, provides the right #defines +# and linker options to make pthread_create available +# Some compilers won't report that they do not support -pthread, +# so we need to run a program to see whether it really made the +# function available. +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking whether $CC accepts -pthread" >&5 +$as_echo_n "checking whether $CC accepts -pthread... " >&6; } +if test "${ac_cv_thread+set}" = set; then : + $as_echo_n "(cached) " >&6 else - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF + ac_save_cc="$CC" +CC="$CC -pthread" +if test "$cross_compiling" = yes; then : + ac_cv_pthread=no +else + cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ -#ifdef HAVE_CURSES_H -#include -#endif +#include + +void* routine(void* p){return NULL;} +int main(){ + pthread_t p; + if(pthread_create(&p,NULL,routine,NULL)!=0) + return 1; + (void)pthread_detach(p); + return 0; +} -#include <$ac_header> _ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - eval "$as_ac_Header=yes" +if ac_fn_c_try_run "$LINENO"; then : + ac_cv_pthread=yes else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - eval "$as_ac_Header=no" + ac_cv_pthread=no +fi +rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext \ + conftest.$ac_objext conftest.beam conftest.$ac_ext fi -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext +CC="$ac_save_cc" fi -ac_res=`eval echo '${'$as_ac_Header'}'` - { echo "$as_me:$LINENO: result: $ac_res" >&5 -echo "${ECHO_T}$ac_res" >&6; } -if test `eval echo '${'$as_ac_Header'}'` = yes; then - cat >>confdefs.h <<_ACEOF -#define `echo "HAVE_$ac_header" | $as_tr_cpp` 1 -_ACEOF +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_pthread" >&5 +$as_echo "$ac_cv_pthread" >&6; } fi -done +# If we have set a CC compiler flag for thread support then +# check if it works for CXX, too. +ac_cv_cxx_thread=no +if test ! -z "$CXX" +then +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking whether $CXX also accepts flags for thread support" >&5 +$as_echo_n "checking whether $CXX also accepts flags for thread support... " >&6; } +ac_save_cxx="$CXX" + +if test "$ac_cv_kpthread" = "yes" +then + CXX="$CXX -Kpthread" + ac_cv_cxx_thread=yes +elif test "$ac_cv_kthread" = "yes" +then + CXX="$CXX -Kthread" + ac_cv_cxx_thread=yes +elif test "$ac_cv_pthread" = "yes" +then + CXX="$CXX -pthread" + ac_cv_cxx_thread=yes +fi +if test $ac_cv_cxx_thread = yes +then + echo 'void foo();int main(){foo();}void foo(){}' > conftest.$ac_ext + $CXX -c conftest.$ac_ext 2>&5 + if $CXX -o conftest$ac_exeext conftest.$ac_objext 2>&5 \ + && test -s conftest$ac_exeext && ./conftest$ac_exeext + then + ac_cv_cxx_thread=yes + else + ac_cv_cxx_thread=no + fi + rm -fr conftest* +fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_cxx_thread" >&5 +$as_echo "$ac_cv_cxx_thread" >&6; } +fi +CXX="$ac_save_cxx" -# On Linux, netlink.h requires asm/types.h -for ac_header in linux/netlink.h -do -as_ac_Header=`echo "ac_cv_header_$ac_header" | $as_tr_sh` -{ echo "$as_me:$LINENO: checking for $ac_header" >&5 -echo $ECHO_N "checking for $ac_header... $ECHO_C" >&6; } -if { as_var=$as_ac_Header; eval "test \"\${$as_var+set}\" = set"; }; then - echo $ECHO_N "(cached) $ECHO_C" >&6 +# checks for header files +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for ANSI C header files" >&5 +$as_echo_n "checking for ANSI C header files... " >&6; } +if test "${ac_cv_header_stdc+set}" = set; then : + $as_echo_n "(cached) " >&6 else - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF + cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ +#include +#include +#include +#include -#ifdef HAVE_ASM_TYPES_H -#include -#endif -#ifdef HAVE_SYS_SOCKET_H -#include -#endif - +int +main () +{ -#include <$ac_header> + ; + return 0; +} _ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - eval "$as_ac_Header=yes" +if ac_fn_c_try_compile "$LINENO"; then : + ac_cv_header_stdc=yes else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - eval "$as_ac_Header=no" + ac_cv_header_stdc=no fi - rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext -fi -ac_res=`eval echo '${'$as_ac_Header'}'` - { echo "$as_me:$LINENO: result: $ac_res" >&5 -echo "${ECHO_T}$ac_res" >&6; } -if test `eval echo '${'$as_ac_Header'}'` = yes; then - cat >>confdefs.h <<_ACEOF -#define `echo "HAVE_$ac_header" | $as_tr_cpp` 1 -_ACEOF - -fi -done - - -# checks for typedefs -was_it_defined=no -{ echo "$as_me:$LINENO: checking for clock_t in time.h" >&5 -echo $ECHO_N "checking for clock_t in time.h... $ECHO_C" >&6; } -cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF +if test $ac_cv_header_stdc = yes; then + # SunOS 4.x string.h does not declare mem*, contrary to ANSI. + cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ -#include +#include _ACEOF if (eval "$ac_cpp conftest.$ac_ext") 2>&5 | - $EGREP "clock_t" >/dev/null 2>&1; then - was_it_defined=yes + $EGREP "memchr" >/dev/null 2>&1; then : + else + ac_cv_header_stdc=no +fi +rm -f conftest* + +fi +if test $ac_cv_header_stdc = yes; then + # ISC 2.0.2 stdlib.h does not declare free, contrary to ANSI. + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ +#include -cat >>confdefs.h <<\_ACEOF -#define clock_t long _ACEOF +if (eval "$ac_cpp conftest.$ac_ext") 2>&5 | + $EGREP "free" >/dev/null 2>&1; then : - +else + ac_cv_header_stdc=no fi rm -f conftest* -{ echo "$as_me:$LINENO: result: $was_it_defined" >&5 -echo "${ECHO_T}$was_it_defined" >&6; } +fi -# Check whether using makedev requires defining _OSF_SOURCE -{ echo "$as_me:$LINENO: checking for makedev" >&5 -echo $ECHO_N "checking for makedev... $ECHO_C" >&6; } -cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF +if test $ac_cv_header_stdc = yes; then + # /bin/cc in Irix-4.0.5 gets non-ANSI ctype macros unless using -ansi. + if test "$cross_compiling" = yes; then : + : +else + cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ - -#if defined(MAJOR_IN_MKDEV) -#include -#elif defined(MAJOR_IN_SYSMACROS) -#include +#include +#include +#if ((' ' & 0x0FF) == 0x020) +# define ISLOWER(c) ('a' <= (c) && (c) <= 'z') +# define TOUPPER(c) (ISLOWER(c) ? 'A' + ((c) - 'a') : (c)) #else -#include +# define ISLOWER(c) \ + (('a' <= (c) && (c) <= 'i') \ + || ('j' <= (c) && (c) <= 'r') \ + || ('s' <= (c) && (c) <= 'z')) +# define TOUPPER(c) (ISLOWER(c) ? ((c) | 0x40) : (c)) #endif + +#define XOR(e, f) (((e) && !(f)) || (!(e) && (f))) int main () { - makedev(0, 0) - ; + int i; + for (i = 0; i < 256; i++) + if (XOR (islower (i), ISLOWER (i)) + || toupper (i) != TOUPPER (i)) + return 2; return 0; } _ACEOF -rm -f conftest.$ac_objext conftest$ac_exeext -if { (ac_try="$ac_link" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_link") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest$ac_exeext && - $as_test_x conftest$ac_exeext; then - ac_cv_has_makedev=yes -else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - ac_cv_has_makedev=no -fi - -rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \ - conftest$ac_exeext conftest.$ac_ext -if test "$ac_cv_has_makedev" = "no"; then - # we didn't link, try if _OSF_SOURCE will allow us to link - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ - -#define _OSF_SOURCE 1 -#include +if ac_fn_c_try_run "$LINENO"; then : -int -main () -{ - makedev(0, 0) - ; - return 0; -} -_ACEOF -rm -f conftest.$ac_objext conftest$ac_exeext -if { (ac_try="$ac_link" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_link") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest$ac_exeext && - $as_test_x conftest$ac_exeext; then - ac_cv_has_makedev=yes else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - ac_cv_has_makedev=no + ac_cv_header_stdc=no +fi +rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext \ + conftest.$ac_objext conftest.beam conftest.$ac_ext fi -rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \ - conftest$ac_exeext conftest.$ac_ext - if test "$ac_cv_has_makedev" = "yes"; then +fi +fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_header_stdc" >&5 +$as_echo "$ac_cv_header_stdc" >&6; } +if test $ac_cv_header_stdc = yes; then -cat >>confdefs.h <<\_ACEOF -#define _OSF_SOURCE 1 -_ACEOF +$as_echo "#define STDC_HEADERS 1" >>confdefs.h - fi fi -{ echo "$as_me:$LINENO: result: $ac_cv_has_makedev" >&5 -echo "${ECHO_T}$ac_cv_has_makedev" >&6; } -if test "$ac_cv_has_makedev" = "yes"; then -cat >>confdefs.h <<\_ACEOF -#define HAVE_MAKEDEV 1 +for ac_header in asm/types.h conio.h curses.h direct.h dlfcn.h errno.h \ +fcntl.h grp.h \ +ieeefp.h io.h langinfo.h libintl.h ncurses.h poll.h process.h pthread.h \ +shadow.h signal.h stdint.h stropts.h termios.h thread.h \ +unistd.h utime.h \ +sys/audioio.h sys/bsdtty.h sys/epoll.h sys/event.h sys/file.h sys/loadavg.h \ +sys/lock.h sys/mkdev.h sys/modem.h \ +sys/param.h sys/poll.h sys/select.h sys/socket.h sys/statvfs.h sys/stat.h \ +sys/termio.h sys/time.h \ +sys/times.h sys/types.h sys/un.h sys/utsname.h sys/wait.h pty.h libutil.h \ +sys/resource.h netpacket/packet.h sysexits.h bluetooth.h \ +bluetooth/bluetooth.h linux/tipc.h spawn.h util.h +do : + as_ac_Header=`$as_echo "ac_cv_header_$ac_header" | $as_tr_sh` +ac_fn_c_check_header_mongrel "$LINENO" "$ac_header" "$as_ac_Header" "$ac_includes_default" +eval as_val=\$$as_ac_Header + if test "x$as_val" = x""yes; then : + cat >>confdefs.h <<_ACEOF +#define `$as_echo "HAVE_$ac_header" | $as_tr_cpp` 1 _ACEOF fi -# Enabling LFS on Solaris (2.6 to 9) with gcc 2.95 triggers a bug in -# the system headers: If _XOPEN_SOURCE and _LARGEFILE_SOURCE are -# defined, but the compiler does not support pragma redefine_extname, -# and _LARGEFILE64_SOURCE is not defined, the headers refer to 64-bit -# structures (such as rlimit64) without declaring them. As a -# work-around, disable LFS on such configurations +done -use_lfs=yes -{ echo "$as_me:$LINENO: checking Solaris LFS bug" >&5 -echo $ECHO_N "checking Solaris LFS bug... $ECHO_C" >&6; } -cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF +ac_header_dirent=no +for ac_hdr in dirent.h sys/ndir.h sys/dir.h ndir.h; do + as_ac_Header=`$as_echo "ac_cv_header_dirent_$ac_hdr" | $as_tr_sh` +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_hdr that defines DIR" >&5 +$as_echo_n "checking for $ac_hdr that defines DIR... " >&6; } +if { as_var=$as_ac_Header; eval "test \"\${$as_var+set}\" = set"; }; then : + $as_echo_n "(cached) " >&6 +else + cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ - -#define _LARGEFILE_SOURCE 1 -#define _FILE_OFFSET_BITS 64 -#include +#include +#include <$ac_hdr> int main () { -struct rlimit foo; +if ((DIR *) 0) +return 0; ; return 0; } _ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - sol_lfs_bug=no +if ac_fn_c_try_compile "$LINENO"; then : + eval "$as_ac_Header=yes" else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - sol_lfs_bug=yes + eval "$as_ac_Header=no" fi - rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext -{ echo "$as_me:$LINENO: result: $sol_lfs_bug" >&5 -echo "${ECHO_T}$sol_lfs_bug" >&6; } -if test "$sol_lfs_bug" = "yes"; then - use_lfs=no fi - -if test "$use_lfs" = "yes"; then -# Two defines needed to enable largefile support on various platforms -# These may affect some typedefs - -cat >>confdefs.h <<\_ACEOF -#define _LARGEFILE_SOURCE 1 -_ACEOF - - -cat >>confdefs.h <<\_ACEOF -#define _FILE_OFFSET_BITS 64 +eval ac_res=\$$as_ac_Header + { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_res" >&5 +$as_echo "$ac_res" >&6; } +eval as_val=\$$as_ac_Header + if test "x$as_val" = x""yes; then : + cat >>confdefs.h <<_ACEOF +#define `$as_echo "HAVE_$ac_hdr" | $as_tr_cpp` 1 _ACEOF +ac_header_dirent=$ac_hdr; break fi -# Add some code to confdefs.h so that the test for off_t works on SCO -cat >> confdefs.h <<\EOF -#if defined(SCO_DS) -#undef _OFF_T -#endif -EOF - -# Type availability checks -{ echo "$as_me:$LINENO: checking for mode_t" >&5 -echo $ECHO_N "checking for mode_t... $ECHO_C" >&6; } -if test "${ac_cv_type_mode_t+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 +done +# Two versions of opendir et al. are in -ldir and -lx on SCO Xenix. +if test $ac_header_dirent = dirent.h; then + { $as_echo "$as_me:${as_lineno-$LINENO}: checking for library containing opendir" >&5 +$as_echo_n "checking for library containing opendir... " >&6; } +if test "${ac_cv_search_opendir+set}" = set; then : + $as_echo_n "(cached) " >&6 else - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF + ac_func_search_save_LIBS=$LIBS +cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ -$ac_includes_default -typedef mode_t ac__type_new_; + +/* Override any GCC internal prototype to avoid an error. + Use char because int might match the return type of a GCC + builtin and then its argument prototype would still apply. */ +#ifdef __cplusplus +extern "C" +#endif +char opendir (); int main () { -if ((ac__type_new_ *) 0) - return 0; -if (sizeof (ac__type_new_)) - return 0; +return opendir (); ; return 0; } _ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - ac_cv_type_mode_t=yes -else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - ac_cv_type_mode_t=no +for ac_lib in '' dir; do + if test -z "$ac_lib"; then + ac_res="none required" + else + ac_res=-l$ac_lib + LIBS="-l$ac_lib $ac_func_search_save_LIBS" + fi + if ac_fn_c_try_link "$LINENO"; then : + ac_cv_search_opendir=$ac_res fi - -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext +rm -f core conftest.err conftest.$ac_objext \ + conftest$ac_exeext + if test "${ac_cv_search_opendir+set}" = set; then : + break fi -{ echo "$as_me:$LINENO: result: $ac_cv_type_mode_t" >&5 -echo "${ECHO_T}$ac_cv_type_mode_t" >&6; } -if test $ac_cv_type_mode_t = yes; then - : -else +done +if test "${ac_cv_search_opendir+set}" = set; then : -cat >>confdefs.h <<_ACEOF -#define mode_t int -_ACEOF +else + ac_cv_search_opendir=no +fi +rm conftest.$ac_ext +LIBS=$ac_func_search_save_LIBS +fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_search_opendir" >&5 +$as_echo "$ac_cv_search_opendir" >&6; } +ac_res=$ac_cv_search_opendir +if test "$ac_res" != no; then : + test "$ac_res" = "none required" || LIBS="$ac_res $LIBS" fi -{ echo "$as_me:$LINENO: checking for off_t" >&5 -echo $ECHO_N "checking for off_t... $ECHO_C" >&6; } -if test "${ac_cv_type_off_t+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 else - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF + { $as_echo "$as_me:${as_lineno-$LINENO}: checking for library containing opendir" >&5 +$as_echo_n "checking for library containing opendir... " >&6; } +if test "${ac_cv_search_opendir+set}" = set; then : + $as_echo_n "(cached) " >&6 +else + ac_func_search_save_LIBS=$LIBS +cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ -$ac_includes_default -typedef off_t ac__type_new_; + +/* Override any GCC internal prototype to avoid an error. + Use char because int might match the return type of a GCC + builtin and then its argument prototype would still apply. */ +#ifdef __cplusplus +extern "C" +#endif +char opendir (); int main () { -if ((ac__type_new_ *) 0) - return 0; -if (sizeof (ac__type_new_)) - return 0; +return opendir (); ; return 0; } _ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - ac_cv_type_off_t=yes -else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - ac_cv_type_off_t=no +for ac_lib in '' x; do + if test -z "$ac_lib"; then + ac_res="none required" + else + ac_res=-l$ac_lib + LIBS="-l$ac_lib $ac_func_search_save_LIBS" + fi + if ac_fn_c_try_link "$LINENO"; then : + ac_cv_search_opendir=$ac_res fi - -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext +rm -f core conftest.err conftest.$ac_objext \ + conftest$ac_exeext + if test "${ac_cv_search_opendir+set}" = set; then : + break fi -{ echo "$as_me:$LINENO: result: $ac_cv_type_off_t" >&5 -echo "${ECHO_T}$ac_cv_type_off_t" >&6; } -if test $ac_cv_type_off_t = yes; then - : +done +if test "${ac_cv_search_opendir+set}" = set; then : + else + ac_cv_search_opendir=no +fi +rm conftest.$ac_ext +LIBS=$ac_func_search_save_LIBS +fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_search_opendir" >&5 +$as_echo "$ac_cv_search_opendir" >&6; } +ac_res=$ac_cv_search_opendir +if test "$ac_res" != no; then : + test "$ac_res" = "none required" || LIBS="$ac_res $LIBS" -cat >>confdefs.h <<_ACEOF -#define off_t long int -_ACEOF +fi fi -{ echo "$as_me:$LINENO: checking for pid_t" >&5 -echo $ECHO_N "checking for pid_t... $ECHO_C" >&6; } -if test "${ac_cv_type_pid_t+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking whether sys/types.h defines makedev" >&5 +$as_echo_n "checking whether sys/types.h defines makedev... " >&6; } +if test "${ac_cv_header_sys_types_h_makedev+set}" = set; then : + $as_echo_n "(cached) " >&6 else - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF + cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ -$ac_includes_default -typedef pid_t ac__type_new_; +#include int main () { -if ((ac__type_new_ *) 0) - return 0; -if (sizeof (ac__type_new_)) - return 0; +return makedev(0, 0); ; return 0; } _ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - ac_cv_type_pid_t=yes +if ac_fn_c_try_link "$LINENO"; then : + ac_cv_header_sys_types_h_makedev=yes else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 + ac_cv_header_sys_types_h_makedev=no +fi +rm -f core conftest.err conftest.$ac_objext \ + conftest$ac_exeext conftest.$ac_ext - ac_cv_type_pid_t=no fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_header_sys_types_h_makedev" >&5 +$as_echo "$ac_cv_header_sys_types_h_makedev" >&6; } + +if test $ac_cv_header_sys_types_h_makedev = no; then +ac_fn_c_check_header_mongrel "$LINENO" "sys/mkdev.h" "ac_cv_header_sys_mkdev_h" "$ac_includes_default" +if test "x$ac_cv_header_sys_mkdev_h" = x""yes; then : + +$as_echo "#define MAJOR_IN_MKDEV 1" >>confdefs.h -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext fi -{ echo "$as_me:$LINENO: result: $ac_cv_type_pid_t" >&5 -echo "${ECHO_T}$ac_cv_type_pid_t" >&6; } -if test $ac_cv_type_pid_t = yes; then - : -else -cat >>confdefs.h <<_ACEOF -#define pid_t int -_ACEOF + + + if test $ac_cv_header_sys_mkdev_h = no; then + ac_fn_c_check_header_mongrel "$LINENO" "sys/sysmacros.h" "ac_cv_header_sys_sysmacros_h" "$ac_includes_default" +if test "x$ac_cv_header_sys_sysmacros_h" = x""yes; then : + +$as_echo "#define MAJOR_IN_SYSMACROS 1" >>confdefs.h fi -{ echo "$as_me:$LINENO: checking return type of signal handlers" >&5 -echo $ECHO_N "checking return type of signal handlers... $ECHO_C" >&6; } -if test "${ac_cv_type_signal+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 -else - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -#include -#include -int -main () -{ -return *(signal (0, 0)) (0) == 1; - ; - return 0; -} -_ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - ac_cv_type_signal=int -else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - ac_cv_type_signal=void + fi fi -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext + +# On Solaris, term.h requires curses.h +for ac_header in term.h +do : + ac_fn_c_check_header_compile "$LINENO" "term.h" "ac_cv_header_term_h" " +#ifdef HAVE_CURSES_H +#include +#endif + +" +if test "x$ac_cv_header_term_h" = x""yes; then : + cat >>confdefs.h <<_ACEOF +#define HAVE_TERM_H 1 +_ACEOF + fi -{ echo "$as_me:$LINENO: result: $ac_cv_type_signal" >&5 -echo "${ECHO_T}$ac_cv_type_signal" >&6; } -cat >>confdefs.h <<_ACEOF -#define RETSIGTYPE $ac_cv_type_signal +done + + +# On Linux, netlink.h requires asm/types.h +for ac_header in linux/netlink.h +do : + ac_fn_c_check_header_compile "$LINENO" "linux/netlink.h" "ac_cv_header_linux_netlink_h" " +#ifdef HAVE_ASM_TYPES_H +#include +#endif +#ifdef HAVE_SYS_SOCKET_H +#include +#endif + +" +if test "x$ac_cv_header_linux_netlink_h" = x""yes; then : + cat >>confdefs.h <<_ACEOF +#define HAVE_LINUX_NETLINK_H 1 _ACEOF +fi + +done + + +# checks for typedefs +was_it_defined=no +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for clock_t in time.h" >&5 +$as_echo_n "checking for clock_t in time.h... " >&6; } +cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ +#include -{ echo "$as_me:$LINENO: checking for size_t" >&5 -echo $ECHO_N "checking for size_t... $ECHO_C" >&6; } -if test "${ac_cv_type_size_t+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 -else - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ _ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF +if (eval "$ac_cpp conftest.$ac_ext") 2>&5 | + $EGREP "clock_t" >/dev/null 2>&1; then : + was_it_defined=yes +else + + +$as_echo "#define clock_t long" >>confdefs.h + + +fi +rm -f conftest* + +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $was_it_defined" >&5 +$as_echo "$was_it_defined" >&6; } + +# Check whether using makedev requires defining _OSF_SOURCE +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for makedev" >&5 +$as_echo_n "checking for makedev... " >&6; } +cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ -$ac_includes_default -typedef size_t ac__type_new_; + +#if defined(MAJOR_IN_MKDEV) +#include +#elif defined(MAJOR_IN_SYSMACROS) +#include +#else +#include +#endif int main () { -if ((ac__type_new_ *) 0) - return 0; -if (sizeof (ac__type_new_)) - return 0; + makedev(0, 0) ; return 0; } _ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - ac_cv_type_size_t=yes +if ac_fn_c_try_link "$LINENO"; then : + ac_cv_has_makedev=yes else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 + ac_cv_has_makedev=no +fi +rm -f core conftest.err conftest.$ac_objext \ + conftest$ac_exeext conftest.$ac_ext +if test "$ac_cv_has_makedev" = "no"; then + # we didn't link, try if _OSF_SOURCE will allow us to link + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ - ac_cv_type_size_t=no +#define _OSF_SOURCE 1 +#include + +int +main () +{ + makedev(0, 0) + ; + return 0; +} +_ACEOF +if ac_fn_c_try_link "$LINENO"; then : + ac_cv_has_makedev=yes +else + ac_cv_has_makedev=no fi +rm -f core conftest.err conftest.$ac_objext \ + conftest$ac_exeext conftest.$ac_ext + if test "$ac_cv_has_makedev" = "yes"; then -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext +$as_echo "#define _OSF_SOURCE 1" >>confdefs.h + + fi fi -{ echo "$as_me:$LINENO: result: $ac_cv_type_size_t" >&5 -echo "${ECHO_T}$ac_cv_type_size_t" >&6; } -if test $ac_cv_type_size_t = yes; then - : -else +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_has_makedev" >&5 +$as_echo "$ac_cv_has_makedev" >&6; } +if test "$ac_cv_has_makedev" = "yes"; then -cat >>confdefs.h <<_ACEOF -#define size_t unsigned int -_ACEOF +$as_echo "#define HAVE_MAKEDEV 1" >>confdefs.h fi -{ echo "$as_me:$LINENO: checking for uid_t in sys/types.h" >&5 -echo $ECHO_N "checking for uid_t in sys/types.h... $ECHO_C" >&6; } -if test "${ac_cv_type_uid_t+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 -else - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF +# Enabling LFS on Solaris (2.6 to 9) with gcc 2.95 triggers a bug in +# the system headers: If _XOPEN_SOURCE and _LARGEFILE_SOURCE are +# defined, but the compiler does not support pragma redefine_extname, +# and _LARGEFILE64_SOURCE is not defined, the headers refer to 64-bit +# structures (such as rlimit64) without declaring them. As a +# work-around, disable LFS on such configurations + +use_lfs=yes +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking Solaris LFS bug" >&5 +$as_echo_n "checking Solaris LFS bug... " >&6; } +cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ -#include +#define _LARGEFILE_SOURCE 1 +#define _FILE_OFFSET_BITS 64 +#include + +int +main () +{ +struct rlimit foo; + ; + return 0; +} _ACEOF -if (eval "$ac_cpp conftest.$ac_ext") 2>&5 | - $EGREP "uid_t" >/dev/null 2>&1; then - ac_cv_type_uid_t=yes +if ac_fn_c_try_compile "$LINENO"; then : + sol_lfs_bug=no else - ac_cv_type_uid_t=no + sol_lfs_bug=yes fi -rm -f conftest* +rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $sol_lfs_bug" >&5 +$as_echo "$sol_lfs_bug" >&6; } +if test "$sol_lfs_bug" = "yes"; then + use_lfs=no +fi + +if test "$use_lfs" = "yes"; then +# Two defines needed to enable largefile support on various platforms +# These may affect some typedefs + +$as_echo "#define _LARGEFILE_SOURCE 1" >>confdefs.h + + +$as_echo "#define _FILE_OFFSET_BITS 64" >>confdefs.h fi -{ echo "$as_me:$LINENO: result: $ac_cv_type_uid_t" >&5 -echo "${ECHO_T}$ac_cv_type_uid_t" >&6; } -if test $ac_cv_type_uid_t = no; then -cat >>confdefs.h <<\_ACEOF -#define uid_t int +# Add some code to confdefs.h so that the test for off_t works on SCO +cat >> confdefs.h <<\EOF +#if defined(SCO_DS) +#undef _OFF_T +#endif +EOF + +# Type availability checks +ac_fn_c_check_type "$LINENO" "mode_t" "ac_cv_type_mode_t" "$ac_includes_default" +if test "x$ac_cv_type_mode_t" = x""yes; then : + +else + +cat >>confdefs.h <<_ACEOF +#define mode_t int _ACEOF +fi + +ac_fn_c_check_type "$LINENO" "off_t" "ac_cv_type_off_t" "$ac_includes_default" +if test "x$ac_cv_type_off_t" = x""yes; then : + +else -cat >>confdefs.h <<\_ACEOF -#define gid_t int +cat >>confdefs.h <<_ACEOF +#define off_t long int _ACEOF fi +ac_fn_c_check_type "$LINENO" "pid_t" "ac_cv_type_pid_t" "$ac_includes_default" +if test "x$ac_cv_type_pid_t" = x""yes; then : - { echo "$as_me:$LINENO: checking for uint32_t" >&5 -echo $ECHO_N "checking for uint32_t... $ECHO_C" >&6; } -if test "${ac_cv_c_uint32_t+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 else - ac_cv_c_uint32_t=no - for ac_type in 'uint32_t' 'unsigned int' 'unsigned long int' \ - 'unsigned long long int' 'unsigned short int' 'unsigned char'; do - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ + +cat >>confdefs.h <<_ACEOF +#define pid_t int _ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF + +fi + +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking return type of signal handlers" >&5 +$as_echo_n "checking return type of signal handlers... " >&6; } +if test "${ac_cv_type_signal+set}" = set; then : + $as_echo_n "(cached) " >&6 +else + cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ -$ac_includes_default +#include +#include + int main () { -static int test_array [1 - 2 * !(($ac_type) -1 >> (32 - 1) == 1)]; -test_array [0] = 0 - +return *(signal (0, 0)) (0) == 1; ; return 0; } _ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - case $ac_type in - uint32_t) ac_cv_c_uint32_t=yes ;; - *) ac_cv_c_uint32_t=$ac_type ;; -esac - +if ac_fn_c_try_compile "$LINENO"; then : + ac_cv_type_signal=int else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - + ac_cv_type_signal=void fi - rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext - test "$ac_cv_c_uint32_t" != no && break - done fi -{ echo "$as_me:$LINENO: result: $ac_cv_c_uint32_t" >&5 -echo "${ECHO_T}$ac_cv_c_uint32_t" >&6; } - case $ac_cv_c_uint32_t in #( - no|yes) ;; #( - *) +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_type_signal" >&5 +$as_echo "$ac_cv_type_signal" >&6; } -cat >>confdefs.h <<\_ACEOF -#define _UINT32_T 1 +cat >>confdefs.h <<_ACEOF +#define RETSIGTYPE $ac_cv_type_signal _ACEOF +ac_fn_c_check_type "$LINENO" "size_t" "ac_cv_type_size_t" "$ac_includes_default" +if test "x$ac_cv_type_size_t" = x""yes; then : + +else + cat >>confdefs.h <<_ACEOF -#define uint32_t $ac_cv_c_uint32_t +#define size_t unsigned int _ACEOF -;; - esac +fi - { echo "$as_me:$LINENO: checking for uint64_t" >&5 -echo $ECHO_N "checking for uint64_t... $ECHO_C" >&6; } -if test "${ac_cv_c_uint64_t+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for uid_t in sys/types.h" >&5 +$as_echo_n "checking for uid_t in sys/types.h... " >&6; } +if test "${ac_cv_type_uid_t+set}" = set; then : + $as_echo_n "(cached) " >&6 else - ac_cv_c_uint64_t=no - for ac_type in 'uint64_t' 'unsigned int' 'unsigned long int' \ - 'unsigned long long int' 'unsigned short int' 'unsigned char'; do - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF + cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ -$ac_includes_default -int -main () -{ -static int test_array [1 - 2 * !(($ac_type) -1 >> (64 - 1) == 1)]; -test_array [0] = 0 +#include - ; - return 0; -} _ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - case $ac_type in - uint64_t) ac_cv_c_uint64_t=yes ;; - *) ac_cv_c_uint64_t=$ac_type ;; -esac - +if (eval "$ac_cpp conftest.$ac_ext") 2>&5 | + $EGREP "uid_t" >/dev/null 2>&1; then : + ac_cv_type_uid_t=yes else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - + ac_cv_type_uid_t=no +fi +rm -f conftest* fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_type_uid_t" >&5 +$as_echo "$ac_cv_type_uid_t" >&6; } +if test $ac_cv_type_uid_t = no; then + +$as_echo "#define uid_t int" >>confdefs.h + + +$as_echo "#define gid_t int" >>confdefs.h -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext - test "$ac_cv_c_uint64_t" != no && break - done fi -{ echo "$as_me:$LINENO: result: $ac_cv_c_uint64_t" >&5 -echo "${ECHO_T}$ac_cv_c_uint64_t" >&6; } - case $ac_cv_c_uint64_t in #( + +ac_fn_c_find_uintX_t "$LINENO" "32" "ac_cv_c_uint32_t" +case $ac_cv_c_uint32_t in #( no|yes) ;; #( *) -cat >>confdefs.h <<\_ACEOF -#define _UINT64_T 1 +$as_echo "#define _UINT32_T 1" >>confdefs.h + + +cat >>confdefs.h <<_ACEOF +#define uint32_t $ac_cv_c_uint32_t _ACEOF +;; + esac + +ac_fn_c_find_uintX_t "$LINENO" "64" "ac_cv_c_uint64_t" +case $ac_cv_c_uint64_t in #( + no|yes) ;; #( + *) + +$as_echo "#define _UINT64_T 1" >>confdefs.h cat >>confdefs.h <<_ACEOF @@ -7343,11960 +6609,1252 @@ ;; esac +ac_fn_c_find_intX_t "$LINENO" "32" "ac_cv_c_int32_t" +case $ac_cv_c_int32_t in #( + no|yes) ;; #( + *) - { echo "$as_me:$LINENO: checking for int32_t" >&5 -echo $ECHO_N "checking for int32_t... $ECHO_C" >&6; } -if test "${ac_cv_c_int32_t+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 -else - ac_cv_c_int32_t=no - for ac_type in 'int32_t' 'int' 'long int' \ - 'long long int' 'short int' 'signed char'; do - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -$ac_includes_default -int -main () -{ -static int test_array [1 - 2 * !(0 < ($ac_type) (((($ac_type) 1 << (32 - 2)) - 1) * 2 + 1))]; -test_array [0] = 0 - - ; - return 0; -} +cat >>confdefs.h <<_ACEOF +#define int32_t $ac_cv_c_int32_t _ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; +;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -$ac_includes_default -int -main () -{ -static int test_array [1 - 2 * !(($ac_type) (((($ac_type) 1 << (32 - 2)) - 1) * 2 + 1) - < ($ac_type) (((($ac_type) 1 << (32 - 2)) - 1) * 2 + 2))]; -test_array [0] = 0 - ; - return 0; -} +ac_fn_c_find_intX_t "$LINENO" "64" "ac_cv_c_int64_t" +case $ac_cv_c_int64_t in #( + no|yes) ;; #( + *) + +cat >>confdefs.h <<_ACEOF +#define int64_t $ac_cv_c_int64_t _ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; +;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - : -else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - case $ac_type in - int32_t) ac_cv_c_int32_t=yes ;; - *) ac_cv_c_int32_t=$ac_type ;; -esac +ac_fn_c_check_type "$LINENO" "ssize_t" "ac_cv_type_ssize_t" "$ac_includes_default" +if test "x$ac_cv_type_ssize_t" = x""yes; then : + +$as_echo "#define HAVE_SSIZE_T 1" >>confdefs.h fi -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext -else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 +# Sizes of various common basic types +# ANSI C requires sizeof(char) == 1, so no need to check it +# The cast to long int works around a bug in the HP C Compiler +# version HP92453-01 B.11.11.23709.GP, which incorrectly rejects +# declarations like `int a3[[(sizeof (unsigned char)) >= 0]];'. +# This bug is HP SR number 8606223364. +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking size of int" >&5 +$as_echo_n "checking size of int... " >&6; } +if test "${ac_cv_sizeof_int+set}" = set; then : + $as_echo_n "(cached) " >&6 +else + if ac_fn_c_compute_int "$LINENO" "(long int) (sizeof (int))" "ac_cv_sizeof_int" "$ac_includes_default"; then : +else + if test "$ac_cv_type_int" = yes; then + { { $as_echo "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5 +$as_echo "$as_me: error: in \`$ac_pwd':" >&2;} +{ as_fn_set_status 77 +as_fn_error "cannot compute sizeof (int) +See \`config.log' for more details." "$LINENO" 5; }; } + else + ac_cv_sizeof_int=0 + fi fi -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext - test "$ac_cv_c_int32_t" != no && break - done fi -{ echo "$as_me:$LINENO: result: $ac_cv_c_int32_t" >&5 -echo "${ECHO_T}$ac_cv_c_int32_t" >&6; } - case $ac_cv_c_int32_t in #( - no|yes) ;; #( - *) +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_sizeof_int" >&5 +$as_echo "$ac_cv_sizeof_int" >&6; } + + cat >>confdefs.h <<_ACEOF -#define int32_t $ac_cv_c_int32_t +#define SIZEOF_INT $ac_cv_sizeof_int _ACEOF -;; - esac - { echo "$as_me:$LINENO: checking for int64_t" >&5 -echo $ECHO_N "checking for int64_t... $ECHO_C" >&6; } -if test "${ac_cv_c_int64_t+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 +# The cast to long int works around a bug in the HP C Compiler +# version HP92453-01 B.11.11.23709.GP, which incorrectly rejects +# declarations like `int a3[[(sizeof (unsigned char)) >= 0]];'. +# This bug is HP SR number 8606223364. +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking size of long" >&5 +$as_echo_n "checking size of long... " >&6; } +if test "${ac_cv_sizeof_long+set}" = set; then : + $as_echo_n "(cached) " >&6 +else + if ac_fn_c_compute_int "$LINENO" "(long int) (sizeof (long))" "ac_cv_sizeof_long" "$ac_includes_default"; then : + else - ac_cv_c_int64_t=no - for ac_type in 'int64_t' 'int' 'long int' \ - 'long long int' 'short int' 'signed char'; do - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -$ac_includes_default -int -main () -{ -static int test_array [1 - 2 * !(0 < ($ac_type) (((($ac_type) 1 << (64 - 2)) - 1) * 2 + 1))]; -test_array [0] = 0 + if test "$ac_cv_type_long" = yes; then + { { $as_echo "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5 +$as_echo "$as_me: error: in \`$ac_pwd':" >&2;} +{ as_fn_set_status 77 +as_fn_error "cannot compute sizeof (long) +See \`config.log' for more details." "$LINENO" 5; }; } + else + ac_cv_sizeof_long=0 + fi +fi - ; - return 0; -} -_ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -$ac_includes_default -int -main () -{ -static int test_array [1 - 2 * !(($ac_type) (((($ac_type) 1 << (64 - 2)) - 1) * 2 + 1) - < ($ac_type) (((($ac_type) 1 << (64 - 2)) - 1) * 2 + 2))]; -test_array [0] = 0 +fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_sizeof_long" >&5 +$as_echo "$ac_cv_sizeof_long" >&6; } - ; - return 0; -} -_ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - : -else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - case $ac_type in - int64_t) ac_cv_c_int64_t=yes ;; - *) ac_cv_c_int64_t=$ac_type ;; -esac -fi +cat >>confdefs.h <<_ACEOF +#define SIZEOF_LONG $ac_cv_sizeof_long +_ACEOF -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext -else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 +# The cast to long int works around a bug in the HP C Compiler +# version HP92453-01 B.11.11.23709.GP, which incorrectly rejects +# declarations like `int a3[[(sizeof (unsigned char)) >= 0]];'. +# This bug is HP SR number 8606223364. +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking size of void *" >&5 +$as_echo_n "checking size of void *... " >&6; } +if test "${ac_cv_sizeof_void_p+set}" = set; then : + $as_echo_n "(cached) " >&6 +else + if ac_fn_c_compute_int "$LINENO" "(long int) (sizeof (void *))" "ac_cv_sizeof_void_p" "$ac_includes_default"; then : +else + if test "$ac_cv_type_void_p" = yes; then + { { $as_echo "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5 +$as_echo "$as_me: error: in \`$ac_pwd':" >&2;} +{ as_fn_set_status 77 +as_fn_error "cannot compute sizeof (void *) +See \`config.log' for more details." "$LINENO" 5; }; } + else + ac_cv_sizeof_void_p=0 + fi fi -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext - test "$ac_cv_c_int64_t" != no && break - done fi -{ echo "$as_me:$LINENO: result: $ac_cv_c_int64_t" >&5 -echo "${ECHO_T}$ac_cv_c_int64_t" >&6; } - case $ac_cv_c_int64_t in #( - no|yes) ;; #( - *) +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_sizeof_void_p" >&5 +$as_echo "$ac_cv_sizeof_void_p" >&6; } + + cat >>confdefs.h <<_ACEOF -#define int64_t $ac_cv_c_int64_t +#define SIZEOF_VOID_P $ac_cv_sizeof_void_p _ACEOF -;; - esac -{ echo "$as_me:$LINENO: checking for ssize_t" >&5 -echo $ECHO_N "checking for ssize_t... $ECHO_C" >&6; } -if test "${ac_cv_type_ssize_t+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 -else - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -$ac_includes_default -typedef ssize_t ac__type_new_; -int -main () -{ -if ((ac__type_new_ *) 0) - return 0; -if (sizeof (ac__type_new_)) - return 0; - ; - return 0; -} -_ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - ac_cv_type_ssize_t=yes -else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - ac_cv_type_ssize_t=no +# The cast to long int works around a bug in the HP C Compiler +# version HP92453-01 B.11.11.23709.GP, which incorrectly rejects +# declarations like `int a3[[(sizeof (unsigned char)) >= 0]];'. +# This bug is HP SR number 8606223364. +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking size of short" >&5 +$as_echo_n "checking size of short... " >&6; } +if test "${ac_cv_sizeof_short+set}" = set; then : + $as_echo_n "(cached) " >&6 +else + if ac_fn_c_compute_int "$LINENO" "(long int) (sizeof (short))" "ac_cv_sizeof_short" "$ac_includes_default"; then : + +else + if test "$ac_cv_type_short" = yes; then + { { $as_echo "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5 +$as_echo "$as_me: error: in \`$ac_pwd':" >&2;} +{ as_fn_set_status 77 +as_fn_error "cannot compute sizeof (short) +See \`config.log' for more details." "$LINENO" 5; }; } + else + ac_cv_sizeof_short=0 + fi fi -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext fi -{ echo "$as_me:$LINENO: result: $ac_cv_type_ssize_t" >&5 -echo "${ECHO_T}$ac_cv_type_ssize_t" >&6; } -if test $ac_cv_type_ssize_t = yes; then +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_sizeof_short" >&5 +$as_echo "$ac_cv_sizeof_short" >&6; } + -cat >>confdefs.h <<\_ACEOF -#define HAVE_SSIZE_T 1 + +cat >>confdefs.h <<_ACEOF +#define SIZEOF_SHORT $ac_cv_sizeof_short _ACEOF -fi +# The cast to long int works around a bug in the HP C Compiler +# version HP92453-01 B.11.11.23709.GP, which incorrectly rejects +# declarations like `int a3[[(sizeof (unsigned char)) >= 0]];'. +# This bug is HP SR number 8606223364. +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking size of float" >&5 +$as_echo_n "checking size of float... " >&6; } +if test "${ac_cv_sizeof_float+set}" = set; then : + $as_echo_n "(cached) " >&6 +else + if ac_fn_c_compute_int "$LINENO" "(long int) (sizeof (float))" "ac_cv_sizeof_float" "$ac_includes_default"; then : -# Sizes of various common basic types -# ANSI C requires sizeof(char) == 1, so no need to check it -{ echo "$as_me:$LINENO: checking for int" >&5 -echo $ECHO_N "checking for int... $ECHO_C" >&6; } -if test "${ac_cv_type_int+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 else - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -$ac_includes_default -typedef int ac__type_new_; -int -main () -{ -if ((ac__type_new_ *) 0) - return 0; -if (sizeof (ac__type_new_)) - return 0; - ; - return 0; -} + if test "$ac_cv_type_float" = yes; then + { { $as_echo "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5 +$as_echo "$as_me: error: in \`$ac_pwd':" >&2;} +{ as_fn_set_status 77 +as_fn_error "cannot compute sizeof (float) +See \`config.log' for more details." "$LINENO" 5; }; } + else + ac_cv_sizeof_float=0 + fi +fi + +fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_sizeof_float" >&5 +$as_echo "$ac_cv_sizeof_float" >&6; } + + + +cat >>confdefs.h <<_ACEOF +#define SIZEOF_FLOAT $ac_cv_sizeof_float _ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - ac_cv_type_int=yes -else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - ac_cv_type_int=no + +# The cast to long int works around a bug in the HP C Compiler +# version HP92453-01 B.11.11.23709.GP, which incorrectly rejects +# declarations like `int a3[[(sizeof (unsigned char)) >= 0]];'. +# This bug is HP SR number 8606223364. +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking size of double" >&5 +$as_echo_n "checking size of double... " >&6; } +if test "${ac_cv_sizeof_double+set}" = set; then : + $as_echo_n "(cached) " >&6 +else + if ac_fn_c_compute_int "$LINENO" "(long int) (sizeof (double))" "ac_cv_sizeof_double" "$ac_includes_default"; then : + +else + if test "$ac_cv_type_double" = yes; then + { { $as_echo "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5 +$as_echo "$as_me: error: in \`$ac_pwd':" >&2;} +{ as_fn_set_status 77 +as_fn_error "cannot compute sizeof (double) +See \`config.log' for more details." "$LINENO" 5; }; } + else + ac_cv_sizeof_double=0 + fi fi -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext fi -{ echo "$as_me:$LINENO: result: $ac_cv_type_int" >&5 -echo "${ECHO_T}$ac_cv_type_int" >&6; } +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_sizeof_double" >&5 +$as_echo "$ac_cv_sizeof_double" >&6; } + + + +cat >>confdefs.h <<_ACEOF +#define SIZEOF_DOUBLE $ac_cv_sizeof_double +_ACEOF + # The cast to long int works around a bug in the HP C Compiler # version HP92453-01 B.11.11.23709.GP, which incorrectly rejects # declarations like `int a3[[(sizeof (unsigned char)) >= 0]];'. # This bug is HP SR number 8606223364. -{ echo "$as_me:$LINENO: checking size of int" >&5 -echo $ECHO_N "checking size of int... $ECHO_C" >&6; } -if test "${ac_cv_sizeof_int+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking size of fpos_t" >&5 +$as_echo_n "checking size of fpos_t... " >&6; } +if test "${ac_cv_sizeof_fpos_t+set}" = set; then : + $as_echo_n "(cached) " >&6 +else + if ac_fn_c_compute_int "$LINENO" "(long int) (sizeof (fpos_t))" "ac_cv_sizeof_fpos_t" "$ac_includes_default"; then : + else - if test "$cross_compiling" = yes; then - # Depending upon the size, compute the lo and hi bounds. -cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ + if test "$ac_cv_type_fpos_t" = yes; then + { { $as_echo "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5 +$as_echo "$as_me: error: in \`$ac_pwd':" >&2;} +{ as_fn_set_status 77 +as_fn_error "cannot compute sizeof (fpos_t) +See \`config.log' for more details." "$LINENO" 5; }; } + else + ac_cv_sizeof_fpos_t=0 + fi +fi + +fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_sizeof_fpos_t" >&5 +$as_echo "$ac_cv_sizeof_fpos_t" >&6; } + + + +cat >>confdefs.h <<_ACEOF +#define SIZEOF_FPOS_T $ac_cv_sizeof_fpos_t _ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -$ac_includes_default - typedef int ac__type_sizeof_; -int -main () -{ -static int test_array [1 - 2 * !(((long int) (sizeof (ac__type_sizeof_))) >= 0)]; -test_array [0] = 0 - ; - return 0; -} -_ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - ac_lo=0 ac_mid=0 - while :; do - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -$ac_includes_default - typedef int ac__type_sizeof_; -int -main () -{ -static int test_array [1 - 2 * !(((long int) (sizeof (ac__type_sizeof_))) <= $ac_mid)]; -test_array [0] = 0 - ; - return 0; -} -_ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - ac_hi=$ac_mid; break +# The cast to long int works around a bug in the HP C Compiler +# version HP92453-01 B.11.11.23709.GP, which incorrectly rejects +# declarations like `int a3[[(sizeof (unsigned char)) >= 0]];'. +# This bug is HP SR number 8606223364. +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking size of size_t" >&5 +$as_echo_n "checking size of size_t... " >&6; } +if test "${ac_cv_sizeof_size_t+set}" = set; then : + $as_echo_n "(cached) " >&6 +else + if ac_fn_c_compute_int "$LINENO" "(long int) (sizeof (size_t))" "ac_cv_sizeof_size_t" "$ac_includes_default"; then : + else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 + if test "$ac_cv_type_size_t" = yes; then + { { $as_echo "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5 +$as_echo "$as_me: error: in \`$ac_pwd':" >&2;} +{ as_fn_set_status 77 +as_fn_error "cannot compute sizeof (size_t) +See \`config.log' for more details." "$LINENO" 5; }; } + else + ac_cv_sizeof_size_t=0 + fi +fi - ac_lo=`expr $ac_mid + 1` - if test $ac_lo -le $ac_mid; then - ac_lo= ac_hi= - break - fi - ac_mid=`expr 2 '*' $ac_mid + 1` fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_sizeof_size_t" >&5 +$as_echo "$ac_cv_sizeof_size_t" >&6; } -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext - done -else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -$ac_includes_default - typedef int ac__type_sizeof_; -int -main () -{ -static int test_array [1 - 2 * !(((long int) (sizeof (ac__type_sizeof_))) < 0)]; -test_array [0] = 0 - ; - return 0; -} -_ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - ac_hi=-1 ac_mid=-1 - while :; do - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ +cat >>confdefs.h <<_ACEOF +#define SIZEOF_SIZE_T $ac_cv_sizeof_size_t _ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -$ac_includes_default - typedef int ac__type_sizeof_; -int -main () -{ -static int test_array [1 - 2 * !(((long int) (sizeof (ac__type_sizeof_))) >= $ac_mid)]; -test_array [0] = 0 - ; - return 0; -} -_ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - ac_lo=$ac_mid; break -else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - ac_hi=`expr '(' $ac_mid ')' - 1` - if test $ac_mid -le $ac_hi; then - ac_lo= ac_hi= - break - fi - ac_mid=`expr 2 '*' $ac_mid` -fi +# The cast to long int works around a bug in the HP C Compiler +# version HP92453-01 B.11.11.23709.GP, which incorrectly rejects +# declarations like `int a3[[(sizeof (unsigned char)) >= 0]];'. +# This bug is HP SR number 8606223364. +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking size of pid_t" >&5 +$as_echo_n "checking size of pid_t... " >&6; } +if test "${ac_cv_sizeof_pid_t+set}" = set; then : + $as_echo_n "(cached) " >&6 +else + if ac_fn_c_compute_int "$LINENO" "(long int) (sizeof (pid_t))" "ac_cv_sizeof_pid_t" "$ac_includes_default"; then : -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext - done else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - ac_lo= ac_hi= + if test "$ac_cv_type_pid_t" = yes; then + { { $as_echo "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5 +$as_echo "$as_me: error: in \`$ac_pwd':" >&2;} +{ as_fn_set_status 77 +as_fn_error "cannot compute sizeof (pid_t) +See \`config.log' for more details." "$LINENO" 5; }; } + else + ac_cv_sizeof_pid_t=0 + fi fi -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_sizeof_pid_t" >&5 +$as_echo "$ac_cv_sizeof_pid_t" >&6; } -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext -# Binary search between lo and hi bounds. -while test "x$ac_lo" != "x$ac_hi"; do - ac_mid=`expr '(' $ac_hi - $ac_lo ')' / 2 + $ac_lo` - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ + + +cat >>confdefs.h <<_ACEOF +#define SIZEOF_PID_T $ac_cv_sizeof_pid_t _ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF + + + +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for long long support" >&5 +$as_echo_n "checking for long long support... " >&6; } +have_long_long=no +cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ -$ac_includes_default - typedef int ac__type_sizeof_; + int main () { -static int test_array [1 - 2 * !(((long int) (sizeof (ac__type_sizeof_))) <= $ac_mid)]; -test_array [0] = 0 - +long long x; x = (long long)0; ; return 0; } _ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - ac_hi=$ac_mid -else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 +if ac_fn_c_try_compile "$LINENO"; then : - ac_lo=`expr '(' $ac_mid ')' + 1` -fi -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext -done -case $ac_lo in -?*) ac_cv_sizeof_int=$ac_lo;; -'') if test "$ac_cv_type_int" = yes; then - { { echo "$as_me:$LINENO: error: cannot compute sizeof (int) -See \`config.log' for more details." >&5 -echo "$as_me: error: cannot compute sizeof (int) -See \`config.log' for more details." >&2;} - { (exit 77); exit 77; }; } - else - ac_cv_sizeof_int=0 - fi ;; -esac -else - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -$ac_includes_default - typedef int ac__type_sizeof_; -static long int longval () { return (long int) (sizeof (ac__type_sizeof_)); } -static unsigned long int ulongval () { return (long int) (sizeof (ac__type_sizeof_)); } -#include -#include -int -main () -{ +$as_echo "#define HAVE_LONG_LONG 1" >>confdefs.h - FILE *f = fopen ("conftest.val", "w"); - if (! f) - return 1; - if (((long int) (sizeof (ac__type_sizeof_))) < 0) - { - long int i = longval (); - if (i != ((long int) (sizeof (ac__type_sizeof_)))) - return 1; - fprintf (f, "%ld\n", i); - } - else - { - unsigned long int i = ulongval (); - if (i != ((long int) (sizeof (ac__type_sizeof_)))) - return 1; - fprintf (f, "%lu\n", i); - } - return ferror (f) || fclose (f) != 0; + have_long_long=yes - ; - return 0; -} -_ACEOF -rm -f conftest$ac_exeext -if { (ac_try="$ac_link" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_link") 2>&5 - ac_status=$? - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { ac_try='./conftest$ac_exeext' - { (case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_try") 2>&5 - ac_status=$? - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); }; }; then - ac_cv_sizeof_int=`cat conftest.val` -else - echo "$as_me: program exited with status $ac_status" >&5 -echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 +fi +rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $have_long_long" >&5 +$as_echo "$have_long_long" >&6; } +if test "$have_long_long" = yes ; then +# The cast to long int works around a bug in the HP C Compiler +# version HP92453-01 B.11.11.23709.GP, which incorrectly rejects +# declarations like `int a3[[(sizeof (unsigned char)) >= 0]];'. +# This bug is HP SR number 8606223364. +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking size of long long" >&5 +$as_echo_n "checking size of long long... " >&6; } +if test "${ac_cv_sizeof_long_long+set}" = set; then : + $as_echo_n "(cached) " >&6 +else + if ac_fn_c_compute_int "$LINENO" "(long int) (sizeof (long long))" "ac_cv_sizeof_long_long" "$ac_includes_default"; then : -( exit $ac_status ) -if test "$ac_cv_type_int" = yes; then - { { echo "$as_me:$LINENO: error: cannot compute sizeof (int) -See \`config.log' for more details." >&5 -echo "$as_me: error: cannot compute sizeof (int) -See \`config.log' for more details." >&2;} - { (exit 77); exit 77; }; } +else + if test "$ac_cv_type_long_long" = yes; then + { { $as_echo "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5 +$as_echo "$as_me: error: in \`$ac_pwd':" >&2;} +{ as_fn_set_status 77 +as_fn_error "cannot compute sizeof (long long) +See \`config.log' for more details." "$LINENO" 5; }; } else - ac_cv_sizeof_int=0 + ac_cv_sizeof_long_long=0 fi fi -rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext conftest.$ac_objext conftest.$ac_ext -fi -rm -f conftest.val + fi -{ echo "$as_me:$LINENO: result: $ac_cv_sizeof_int" >&5 -echo "${ECHO_T}$ac_cv_sizeof_int" >&6; } +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_sizeof_long_long" >&5 +$as_echo "$ac_cv_sizeof_long_long" >&6; } cat >>confdefs.h <<_ACEOF -#define SIZEOF_INT $ac_cv_sizeof_int +#define SIZEOF_LONG_LONG $ac_cv_sizeof_long_long _ACEOF -{ echo "$as_me:$LINENO: checking for long" >&5 -echo $ECHO_N "checking for long... $ECHO_C" >&6; } -if test "${ac_cv_type_long+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 -else - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF +fi + +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for long double support" >&5 +$as_echo_n "checking for long double support... " >&6; } +have_long_double=no +cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ -$ac_includes_default -typedef long ac__type_new_; + int main () { -if ((ac__type_new_ *) 0) - return 0; -if (sizeof (ac__type_new_)) - return 0; +long double x; x = (long double)0.; ; return 0; } _ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - ac_cv_type_long=yes -else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 +if ac_fn_c_try_compile "$LINENO"; then : - ac_cv_type_long=no -fi -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext -fi -{ echo "$as_me:$LINENO: result: $ac_cv_type_long" >&5 -echo "${ECHO_T}$ac_cv_type_long" >&6; } +$as_echo "#define HAVE_LONG_DOUBLE 1" >>confdefs.h + + have_long_double=yes +fi +rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $have_long_double" >&5 +$as_echo "$have_long_double" >&6; } +if test "$have_long_double" = yes ; then # The cast to long int works around a bug in the HP C Compiler # version HP92453-01 B.11.11.23709.GP, which incorrectly rejects # declarations like `int a3[[(sizeof (unsigned char)) >= 0]];'. # This bug is HP SR number 8606223364. -{ echo "$as_me:$LINENO: checking size of long" >&5 -echo $ECHO_N "checking size of long... $ECHO_C" >&6; } -if test "${ac_cv_sizeof_long+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking size of long double" >&5 +$as_echo_n "checking size of long double... " >&6; } +if test "${ac_cv_sizeof_long_double+set}" = set; then : + $as_echo_n "(cached) " >&6 +else + if ac_fn_c_compute_int "$LINENO" "(long int) (sizeof (long double))" "ac_cv_sizeof_long_double" "$ac_includes_default"; then : + else - if test "$cross_compiling" = yes; then - # Depending upon the size, compute the lo and hi bounds. -cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ + if test "$ac_cv_type_long_double" = yes; then + { { $as_echo "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5 +$as_echo "$as_me: error: in \`$ac_pwd':" >&2;} +{ as_fn_set_status 77 +as_fn_error "cannot compute sizeof (long double) +See \`config.log' for more details." "$LINENO" 5; }; } + else + ac_cv_sizeof_long_double=0 + fi +fi + +fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_sizeof_long_double" >&5 +$as_echo "$ac_cv_sizeof_long_double" >&6; } + + + +cat >>confdefs.h <<_ACEOF +#define SIZEOF_LONG_DOUBLE $ac_cv_sizeof_long_double _ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF + + +fi + +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for _Bool support" >&5 +$as_echo_n "checking for _Bool support... " >&6; } +have_c99_bool=no +cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ -$ac_includes_default - typedef long ac__type_sizeof_; + int main () { -static int test_array [1 - 2 * !(((long int) (sizeof (ac__type_sizeof_))) >= 0)]; -test_array [0] = 0 - +_Bool x; x = (_Bool)0; ; return 0; } _ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - ac_lo=0 ac_mid=0 - while :; do - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -$ac_includes_default - typedef long ac__type_sizeof_; -int -main () -{ -static int test_array [1 - 2 * !(((long int) (sizeof (ac__type_sizeof_))) <= $ac_mid)]; -test_array [0] = 0 +if ac_fn_c_try_compile "$LINENO"; then : - ; - return 0; -} -_ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - ac_hi=$ac_mid; break -else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - ac_lo=`expr $ac_mid + 1` - if test $ac_lo -le $ac_mid; then - ac_lo= ac_hi= - break - fi - ac_mid=`expr 2 '*' $ac_mid + 1` -fi +$as_echo "#define HAVE_C99_BOOL 1" >>confdefs.h + + have_c99_bool=yes +fi rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext - done +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $have_c99_bool" >&5 +$as_echo "$have_c99_bool" >&6; } +if test "$have_c99_bool" = yes ; then +# The cast to long int works around a bug in the HP C Compiler +# version HP92453-01 B.11.11.23709.GP, which incorrectly rejects +# declarations like `int a3[[(sizeof (unsigned char)) >= 0]];'. +# This bug is HP SR number 8606223364. +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking size of _Bool" >&5 +$as_echo_n "checking size of _Bool... " >&6; } +if test "${ac_cv_sizeof__Bool+set}" = set; then : + $as_echo_n "(cached) " >&6 +else + if ac_fn_c_compute_int "$LINENO" "(long int) (sizeof (_Bool))" "ac_cv_sizeof__Bool" "$ac_includes_default"; then : + else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 + if test "$ac_cv_type__Bool" = yes; then + { { $as_echo "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5 +$as_echo "$as_me: error: in \`$ac_pwd':" >&2;} +{ as_fn_set_status 77 +as_fn_error "cannot compute sizeof (_Bool) +See \`config.log' for more details." "$LINENO" 5; }; } + else + ac_cv_sizeof__Bool=0 + fi +fi - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -$ac_includes_default - typedef long ac__type_sizeof_; -int -main () -{ -static int test_array [1 - 2 * !(((long int) (sizeof (ac__type_sizeof_))) < 0)]; -test_array [0] = 0 +fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_sizeof__Bool" >&5 +$as_echo "$ac_cv_sizeof__Bool" >&6; } - ; - return 0; -} -_ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - ac_hi=-1 ac_mid=-1 - while :; do - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -$ac_includes_default - typedef long ac__type_sizeof_; -int -main () -{ -static int test_array [1 - 2 * !(((long int) (sizeof (ac__type_sizeof_))) >= $ac_mid)]; -test_array [0] = 0 - ; - return 0; -} + +cat >>confdefs.h <<_ACEOF +#define SIZEOF__BOOL $ac_cv_sizeof__Bool _ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - ac_lo=$ac_mid; break -else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - ac_hi=`expr '(' $ac_mid ')' - 1` - if test $ac_mid -le $ac_hi; then - ac_lo= ac_hi= - break - fi - ac_mid=`expr 2 '*' $ac_mid` + fi -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext - done -else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 +ac_fn_c_check_type "$LINENO" "uintptr_t" "ac_cv_type_uintptr_t" "#ifdef HAVE_STDINT_H + #include + #endif +" +if test "x$ac_cv_type_uintptr_t" = x""yes; then : - ac_lo= ac_hi= +cat >>confdefs.h <<_ACEOF +#define HAVE_UINTPTR_T 1 +_ACEOF + +# The cast to long int works around a bug in the HP C Compiler +# version HP92453-01 B.11.11.23709.GP, which incorrectly rejects +# declarations like `int a3[[(sizeof (unsigned char)) >= 0]];'. +# This bug is HP SR number 8606223364. +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking size of uintptr_t" >&5 +$as_echo_n "checking size of uintptr_t... " >&6; } +if test "${ac_cv_sizeof_uintptr_t+set}" = set; then : + $as_echo_n "(cached) " >&6 +else + if ac_fn_c_compute_int "$LINENO" "(long int) (sizeof (uintptr_t))" "ac_cv_sizeof_uintptr_t" "$ac_includes_default"; then : + +else + if test "$ac_cv_type_uintptr_t" = yes; then + { { $as_echo "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5 +$as_echo "$as_me: error: in \`$ac_pwd':" >&2;} +{ as_fn_set_status 77 +as_fn_error "cannot compute sizeof (uintptr_t) +See \`config.log' for more details." "$LINENO" 5; }; } + else + ac_cv_sizeof_uintptr_t=0 + fi fi -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_sizeof_uintptr_t" >&5 +$as_echo "$ac_cv_sizeof_uintptr_t" >&6; } -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext -# Binary search between lo and hi bounds. -while test "x$ac_lo" != "x$ac_hi"; do - ac_mid=`expr '(' $ac_hi - $ac_lo ')' / 2 + $ac_lo` - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -$ac_includes_default - typedef long ac__type_sizeof_; -int -main () -{ -static int test_array [1 - 2 * !(((long int) (sizeof (ac__type_sizeof_))) <= $ac_mid)]; -test_array [0] = 0 - ; - return 0; -} + +cat >>confdefs.h <<_ACEOF +#define SIZEOF_UINTPTR_T $ac_cv_sizeof_uintptr_t _ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - ac_hi=$ac_mid -else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - ac_lo=`expr '(' $ac_mid ')' + 1` + fi -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext -done -case $ac_lo in -?*) ac_cv_sizeof_long=$ac_lo;; -'') if test "$ac_cv_type_long" = yes; then - { { echo "$as_me:$LINENO: error: cannot compute sizeof (long) -See \`config.log' for more details." >&5 -echo "$as_me: error: cannot compute sizeof (long) -See \`config.log' for more details." >&2;} - { (exit 77); exit 77; }; } - else - ac_cv_sizeof_long=0 - fi ;; -esac + +# The cast to long int works around a bug in the HP C Compiler +# version HP92453-01 B.11.11.23709.GP, which incorrectly rejects +# declarations like `int a3[[(sizeof (unsigned char)) >= 0]];'. +# This bug is HP SR number 8606223364. +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking size of off_t" >&5 +$as_echo_n "checking size of off_t... " >&6; } +if test "${ac_cv_sizeof_off_t+set}" = set; then : + $as_echo_n "(cached) " >&6 else - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -$ac_includes_default - typedef long ac__type_sizeof_; -static long int longval () { return (long int) (sizeof (ac__type_sizeof_)); } -static unsigned long int ulongval () { return (long int) (sizeof (ac__type_sizeof_)); } -#include -#include -int -main () -{ + if ac_fn_c_compute_int "$LINENO" "(long int) (sizeof (off_t))" "ac_cv_sizeof_off_t" " +#ifdef HAVE_SYS_TYPES_H +#include +#endif - FILE *f = fopen ("conftest.val", "w"); - if (! f) - return 1; - if (((long int) (sizeof (ac__type_sizeof_))) < 0) - { - long int i = longval (); - if (i != ((long int) (sizeof (ac__type_sizeof_)))) - return 1; - fprintf (f, "%ld\n", i); - } - else - { - unsigned long int i = ulongval (); - if (i != ((long int) (sizeof (ac__type_sizeof_)))) - return 1; - fprintf (f, "%lu\n", i); - } - return ferror (f) || fclose (f) != 0; +"; then : - ; - return 0; -} -_ACEOF -rm -f conftest$ac_exeext -if { (ac_try="$ac_link" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_link") 2>&5 - ac_status=$? - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { ac_try='./conftest$ac_exeext' - { (case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_try") 2>&5 - ac_status=$? - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); }; }; then - ac_cv_sizeof_long=`cat conftest.val` else - echo "$as_me: program exited with status $ac_status" >&5 -echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - -( exit $ac_status ) -if test "$ac_cv_type_long" = yes; then - { { echo "$as_me:$LINENO: error: cannot compute sizeof (long) -See \`config.log' for more details." >&5 -echo "$as_me: error: cannot compute sizeof (long) -See \`config.log' for more details." >&2;} - { (exit 77); exit 77; }; } + if test "$ac_cv_type_off_t" = yes; then + { { $as_echo "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5 +$as_echo "$as_me: error: in \`$ac_pwd':" >&2;} +{ as_fn_set_status 77 +as_fn_error "cannot compute sizeof (off_t) +See \`config.log' for more details." "$LINENO" 5; }; } else - ac_cv_sizeof_long=0 + ac_cv_sizeof_off_t=0 fi fi -rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext conftest.$ac_objext conftest.$ac_ext -fi -rm -f conftest.val + fi -{ echo "$as_me:$LINENO: result: $ac_cv_sizeof_long" >&5 -echo "${ECHO_T}$ac_cv_sizeof_long" >&6; } +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_sizeof_off_t" >&5 +$as_echo "$ac_cv_sizeof_off_t" >&6; } cat >>confdefs.h <<_ACEOF -#define SIZEOF_LONG $ac_cv_sizeof_long +#define SIZEOF_OFF_T $ac_cv_sizeof_off_t _ACEOF -{ echo "$as_me:$LINENO: checking for void *" >&5 -echo $ECHO_N "checking for void *... $ECHO_C" >&6; } -if test "${ac_cv_type_void_p+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 -else - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -$ac_includes_default -typedef void * ac__type_new_; -int -main () -{ -if ((ac__type_new_ *) 0) - return 0; -if (sizeof (ac__type_new_)) - return 0; - ; - return 0; -} -_ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - ac_cv_type_void_p=yes -else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - ac_cv_type_void_p=no -fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking whether to enable large file support" >&5 +$as_echo_n "checking whether to enable large file support... " >&6; } +if test "$have_long_long" = yes +then +if test "$ac_cv_sizeof_off_t" -gt "$ac_cv_sizeof_long" -a \ + "$ac_cv_sizeof_long_long" -ge "$ac_cv_sizeof_off_t"; then -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext +$as_echo "#define HAVE_LARGEFILE_SUPPORT 1" >>confdefs.h + + { $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +$as_echo "yes" >&6; } +else + { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 +$as_echo "no" >&6; } +fi +else + { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 +$as_echo "no" >&6; } fi -{ echo "$as_me:$LINENO: result: $ac_cv_type_void_p" >&5 -echo "${ECHO_T}$ac_cv_type_void_p" >&6; } # The cast to long int works around a bug in the HP C Compiler # version HP92453-01 B.11.11.23709.GP, which incorrectly rejects # declarations like `int a3[[(sizeof (unsigned char)) >= 0]];'. # This bug is HP SR number 8606223364. -{ echo "$as_me:$LINENO: checking size of void *" >&5 -echo $ECHO_N "checking size of void *... $ECHO_C" >&6; } -if test "${ac_cv_sizeof_void_p+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking size of time_t" >&5 +$as_echo_n "checking size of time_t... " >&6; } +if test "${ac_cv_sizeof_time_t+set}" = set; then : + $as_echo_n "(cached) " >&6 else - if test "$cross_compiling" = yes; then - # Depending upon the size, compute the lo and hi bounds. -cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ + if ac_fn_c_compute_int "$LINENO" "(long int) (sizeof (time_t))" "ac_cv_sizeof_time_t" " +#ifdef HAVE_SYS_TYPES_H +#include +#endif +#ifdef HAVE_TIME_H +#include +#endif + +"; then : + +else + if test "$ac_cv_type_time_t" = yes; then + { { $as_echo "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5 +$as_echo "$as_me: error: in \`$ac_pwd':" >&2;} +{ as_fn_set_status 77 +as_fn_error "cannot compute sizeof (time_t) +See \`config.log' for more details." "$LINENO" 5; }; } + else + ac_cv_sizeof_time_t=0 + fi +fi + +fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_sizeof_time_t" >&5 +$as_echo "$ac_cv_sizeof_time_t" >&6; } + + + +cat >>confdefs.h <<_ACEOF +#define SIZEOF_TIME_T $ac_cv_sizeof_time_t _ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -$ac_includes_default - typedef void * ac__type_sizeof_; -int -main () -{ -static int test_array [1 - 2 * !(((long int) (sizeof (ac__type_sizeof_))) >= 0)]; -test_array [0] = 0 - ; - return 0; -} -_ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - ac_lo=0 ac_mid=0 - while :; do - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF + + +# if have pthread_t then define SIZEOF_PTHREAD_T +ac_save_cc="$CC" +if test "$ac_cv_kpthread" = "yes" +then CC="$CC -Kpthread" +elif test "$ac_cv_kthread" = "yes" +then CC="$CC -Kthread" +elif test "$ac_cv_pthread" = "yes" +then CC="$CC -pthread" +fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for pthread_t" >&5 +$as_echo_n "checking for pthread_t... " >&6; } +have_pthread_t=no +cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ -$ac_includes_default - typedef void * ac__type_sizeof_; +#include int main () { -static int test_array [1 - 2 * !(((long int) (sizeof (ac__type_sizeof_))) <= $ac_mid)]; -test_array [0] = 0 - +pthread_t x; x = *(pthread_t*)0; ; return 0; } _ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - ac_hi=$ac_mid; break +if ac_fn_c_try_compile "$LINENO"; then : + have_pthread_t=yes +fi +rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $have_pthread_t" >&5 +$as_echo "$have_pthread_t" >&6; } +if test "$have_pthread_t" = yes ; then + # The cast to long int works around a bug in the HP C Compiler +# version HP92453-01 B.11.11.23709.GP, which incorrectly rejects +# declarations like `int a3[[(sizeof (unsigned char)) >= 0]];'. +# This bug is HP SR number 8606223364. +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking size of pthread_t" >&5 +$as_echo_n "checking size of pthread_t... " >&6; } +if test "${ac_cv_sizeof_pthread_t+set}" = set; then : + $as_echo_n "(cached) " >&6 else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 + if ac_fn_c_compute_int "$LINENO" "(long int) (sizeof (pthread_t))" "ac_cv_sizeof_pthread_t" " +#ifdef HAVE_PTHREAD_H +#include +#endif - ac_lo=`expr $ac_mid + 1` - if test $ac_lo -le $ac_mid; then - ac_lo= ac_hi= - break - fi - ac_mid=`expr 2 '*' $ac_mid + 1` -fi +"; then : -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext - done else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 + if test "$ac_cv_type_pthread_t" = yes; then + { { $as_echo "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5 +$as_echo "$as_me: error: in \`$ac_pwd':" >&2;} +{ as_fn_set_status 77 +as_fn_error "cannot compute sizeof (pthread_t) +See \`config.log' for more details." "$LINENO" 5; }; } + else + ac_cv_sizeof_pthread_t=0 + fi +fi - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -$ac_includes_default - typedef void * ac__type_sizeof_; -int -main () -{ -static int test_array [1 - 2 * !(((long int) (sizeof (ac__type_sizeof_))) < 0)]; -test_array [0] = 0 +fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_sizeof_pthread_t" >&5 +$as_echo "$ac_cv_sizeof_pthread_t" >&6; } - ; - return 0; -} -_ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - ac_hi=-1 ac_mid=-1 - while :; do - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -$ac_includes_default - typedef void * ac__type_sizeof_; -int -main () -{ -static int test_array [1 - 2 * !(((long int) (sizeof (ac__type_sizeof_))) >= $ac_mid)]; -test_array [0] = 0 - ; - return 0; -} + +cat >>confdefs.h <<_ACEOF +#define SIZEOF_PTHREAD_T $ac_cv_sizeof_pthread_t _ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - ac_lo=$ac_mid; break -else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - ac_hi=`expr '(' $ac_mid ')' - 1` - if test $ac_mid -le $ac_hi; then - ac_lo= ac_hi= - break - fi - ac_mid=`expr 2 '*' $ac_mid` -fi -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext - done -else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 +fi +CC="$ac_save_cc" - ac_lo= ac_hi= +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for --enable-toolbox-glue" >&5 +$as_echo_n "checking for --enable-toolbox-glue... " >&6; } +# Check whether --enable-toolbox-glue was given. +if test "${enable_toolbox_glue+set}" = set; then : + enableval=$enable_toolbox_glue; fi -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext + +if test -z "$enable_toolbox_glue" +then + case $ac_sys_system/$ac_sys_release in + Darwin/*) + enable_toolbox_glue="yes";; + *) + enable_toolbox_glue="no";; + esac fi +case "$enable_toolbox_glue" in +yes) + extra_machdep_objs="Python/mactoolboxglue.o" + extra_undefs="-u _PyMac_Error" -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext -# Binary search between lo and hi bounds. -while test "x$ac_lo" != "x$ac_hi"; do - ac_mid=`expr '(' $ac_hi - $ac_lo ')' / 2 + $ac_lo` - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -$ac_includes_default - typedef void * ac__type_sizeof_; -int -main () -{ -static int test_array [1 - 2 * !(((long int) (sizeof (ac__type_sizeof_))) <= $ac_mid)]; -test_array [0] = 0 +$as_echo "#define USE_TOOLBOX_OBJECT_GLUE 1" >>confdefs.h - ; - return 0; -} -_ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; + ;; +*) + extra_machdep_objs="" + extra_undefs="" + ;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - ac_hi=$ac_mid -else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $enable_toolbox_glue" >&5 +$as_echo "$enable_toolbox_glue" >&6; } - ac_lo=`expr '(' $ac_mid ')' + 1` -fi -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext -done -case $ac_lo in -?*) ac_cv_sizeof_void_p=$ac_lo;; -'') if test "$ac_cv_type_void_p" = yes; then - { { echo "$as_me:$LINENO: error: cannot compute sizeof (void *) -See \`config.log' for more details." >&5 -echo "$as_me: error: cannot compute sizeof (void *) -See \`config.log' for more details." >&2;} - { (exit 77); exit 77; }; } - else - ac_cv_sizeof_void_p=0 - fi ;; + +case $ac_sys_system/$ac_sys_release in + Darwin/[01567]\..*) + OTHER_LIBTOOL_OPT="-prebind -seg1addr 0x10000000" + ;; + Darwin/*) + OTHER_LIBTOOL_OPT="" + ;; esac + + +ARCH_RUN_32BIT="" + +case $ac_sys_system/$ac_sys_release in + Darwin/[01567]\..*) + LIBTOOL_CRUFT="-framework System -lcc_dynamic" + if test "${enable_universalsdk}"; then + : + else + LIBTOOL_CRUFT="${LIBTOOL_CRUFT} -arch_only `/usr/bin/arch`" + fi + LIBTOOL_CRUFT=$LIBTOOL_CRUFT' -install_name $(PYTHONFRAMEWORKINSTALLDIR)/Versions/$(VERSION)/$(PYTHONFRAMEWORK)' + LIBTOOL_CRUFT=$LIBTOOL_CRUFT' -compatibility_version $(VERSION) -current_version $(VERSION)';; + Darwin/*) + gcc_version=`gcc -dumpversion` + if test ${gcc_version} '<' 4.0 + then + LIBTOOL_CRUFT="-lcc_dynamic" + else + LIBTOOL_CRUFT="" + fi + if test "$cross_compiling" = yes; then : + ac_osx_32bit=yes else - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF + cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ -$ac_includes_default - typedef void * ac__type_sizeof_; -static long int longval () { return (long int) (sizeof (ac__type_sizeof_)); } -static unsigned long int ulongval () { return (long int) (sizeof (ac__type_sizeof_)); } -#include -#include -int -main () -{ - FILE *f = fopen ("conftest.val", "w"); - if (! f) - return 1; - if (((long int) (sizeof (ac__type_sizeof_))) < 0) - { - long int i = longval (); - if (i != ((long int) (sizeof (ac__type_sizeof_)))) - return 1; - fprintf (f, "%ld\n", i); - } - else + #include + int main(int argc, char*argv[]) { - unsigned long int i = ulongval (); - if (i != ((long int) (sizeof (ac__type_sizeof_)))) - return 1; - fprintf (f, "%lu\n", i); + if (sizeof(long) == 4) { + return 0; + } else { + return 1; + } } - return ferror (f) || fclose (f) != 0; - ; - return 0; -} _ACEOF -rm -f conftest$ac_exeext -if { (ac_try="$ac_link" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_link") 2>&5 - ac_status=$? - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { ac_try='./conftest$ac_exeext' - { (case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_try") 2>&5 - ac_status=$? - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); }; }; then - ac_cv_sizeof_void_p=`cat conftest.val` +if ac_fn_c_try_run "$LINENO"; then : + ac_osx_32bit=yes else - echo "$as_me: program exited with status $ac_status" >&5 -echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - -( exit $ac_status ) -if test "$ac_cv_type_void_p" = yes; then - { { echo "$as_me:$LINENO: error: cannot compute sizeof (void *) -See \`config.log' for more details." >&5 -echo "$as_me: error: cannot compute sizeof (void *) -See \`config.log' for more details." >&2;} - { (exit 77); exit 77; }; } - else - ac_cv_sizeof_void_p=0 - fi + ac_osx_32bit=no fi -rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext conftest.$ac_objext conftest.$ac_ext +rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext \ + conftest.$ac_objext conftest.beam conftest.$ac_ext fi -rm -f conftest.val -fi -{ echo "$as_me:$LINENO: result: $ac_cv_sizeof_void_p" >&5 -echo "${ECHO_T}$ac_cv_sizeof_void_p" >&6; } - - - -cat >>confdefs.h <<_ACEOF -#define SIZEOF_VOID_P $ac_cv_sizeof_void_p -_ACEOF -{ echo "$as_me:$LINENO: checking for short" >&5 -echo $ECHO_N "checking for short... $ECHO_C" >&6; } -if test "${ac_cv_type_short+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 -else - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -$ac_includes_default -typedef short ac__type_new_; -int -main () -{ -if ((ac__type_new_ *) 0) - return 0; -if (sizeof (ac__type_new_)) - return 0; - ; - return 0; -} -_ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - ac_cv_type_short=yes -else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 + if test "${ac_osx_32bit}" = "yes"; then + case `/usr/bin/arch` in + i386) + MACOSX_DEFAULT_ARCH="i386" + ;; + ppc) + MACOSX_DEFAULT_ARCH="ppc" + ;; + *) + as_fn_error "Unexpected output of 'arch' on OSX" "$LINENO" 5 + ;; + esac + else + case `/usr/bin/arch` in + i386) + MACOSX_DEFAULT_ARCH="x86_64" + ;; + ppc) + MACOSX_DEFAULT_ARCH="ppc64" + ;; + *) + as_fn_error "Unexpected output of 'arch' on OSX" "$LINENO" 5 + ;; + esac - ac_cv_type_short=no -fi + #ARCH_RUN_32BIT="true" + fi -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext -fi -{ echo "$as_me:$LINENO: result: $ac_cv_type_short" >&5 -echo "${ECHO_T}$ac_cv_type_short" >&6; } + LIBTOOL_CRUFT=$LIBTOOL_CRUFT" -lSystem -lSystemStubs -arch_only ${MACOSX_DEFAULT_ARCH}" + LIBTOOL_CRUFT=$LIBTOOL_CRUFT' -install_name $(PYTHONFRAMEWORKINSTALLDIR)/Versions/$(VERSION)/$(PYTHONFRAMEWORK)' + LIBTOOL_CRUFT=$LIBTOOL_CRUFT' -compatibility_version $(VERSION) -current_version $(VERSION)';; +esac -# The cast to long int works around a bug in the HP C Compiler -# version HP92453-01 B.11.11.23709.GP, which incorrectly rejects -# declarations like `int a3[[(sizeof (unsigned char)) >= 0]];'. -# This bug is HP SR number 8606223364. -{ echo "$as_me:$LINENO: checking size of short" >&5 -echo $ECHO_N "checking size of short... $ECHO_C" >&6; } -if test "${ac_cv_sizeof_short+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 -else - if test "$cross_compiling" = yes; then - # Depending upon the size, compute the lo and hi bounds. -cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -$ac_includes_default - typedef short ac__type_sizeof_; -int -main () -{ -static int test_array [1 - 2 * !(((long int) (sizeof (ac__type_sizeof_))) >= 0)]; -test_array [0] = 0 +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for --enable-framework" >&5 +$as_echo_n "checking for --enable-framework... " >&6; } +if test "$enable_framework" +then + BASECFLAGS="$BASECFLAGS -fno-common -dynamic" + # -F. is needed to allow linking to the framework while + # in the build location. - ; - return 0; -} -_ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - ac_lo=0 ac_mid=0 - while :; do - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -$ac_includes_default - typedef short ac__type_sizeof_; -int -main () -{ -static int test_array [1 - 2 * !(((long int) (sizeof (ac__type_sizeof_))) <= $ac_mid)]; -test_array [0] = 0 +$as_echo "#define WITH_NEXT_FRAMEWORK 1" >>confdefs.h - ; - return 0; -} -_ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - ac_hi=$ac_mid; break + { $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +$as_echo "yes" >&6; } + if test $enable_shared = "yes" + then + as_fn_error "Specifying both --enable-shared and --enable-framework is not supported, use only --enable-framework instead. See Mac/README." "$LINENO" 5 + fi else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - ac_lo=`expr $ac_mid + 1` - if test $ac_lo -le $ac_mid; then - ac_lo= ac_hi= - break - fi - ac_mid=`expr 2 '*' $ac_mid + 1` + { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 +$as_echo "no" >&6; } fi -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext - done -else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for dyld" >&5 +$as_echo_n "checking for dyld... " >&6; } +case $ac_sys_system/$ac_sys_release in + Darwin/*) - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -$ac_includes_default - typedef short ac__type_sizeof_; -int -main () -{ -static int test_array [1 - 2 * !(((long int) (sizeof (ac__type_sizeof_))) < 0)]; -test_array [0] = 0 +$as_echo "#define WITH_DYLD 1" >>confdefs.h - ; - return 0; -} -_ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; + { $as_echo "$as_me:${as_lineno-$LINENO}: result: always on for Darwin" >&5 +$as_echo "always on for Darwin" >&6; } + ;; + *) + { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 +$as_echo "no" >&6; } + ;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - ac_hi=-1 ac_mid=-1 - while :; do - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -$ac_includes_default - typedef short ac__type_sizeof_; -int -main () -{ -static int test_array [1 - 2 * !(((long int) (sizeof (ac__type_sizeof_))) >= $ac_mid)]; -test_array [0] = 0 - ; - return 0; -} -_ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - ac_lo=$ac_mid; break -else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 +# Set info about shared libraries. - ac_hi=`expr '(' $ac_mid ')' - 1` - if test $ac_mid -le $ac_hi; then - ac_lo= ac_hi= - break - fi - ac_mid=`expr 2 '*' $ac_mid` -fi -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext - done -else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - ac_lo= ac_hi= -fi -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext -fi -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext -# Binary search between lo and hi bounds. -while test "x$ac_lo" != "x$ac_hi"; do - ac_mid=`expr '(' $ac_hi - $ac_lo ')' / 2 + $ac_lo` - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -$ac_includes_default - typedef short ac__type_sizeof_; -int -main () -{ -static int test_array [1 - 2 * !(((long int) (sizeof (ac__type_sizeof_))) <= $ac_mid)]; -test_array [0] = 0 - ; - return 0; -} -_ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - ac_hi=$ac_mid +# SO is the extension of shared libraries `(including the dot!) +# -- usually .so, .sl on HP-UX, .dll on Cygwin +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking SO" >&5 +$as_echo_n "checking SO... " >&6; } +if test -z "$SO" +then + case $ac_sys_system in + hp*|HP*) + case `uname -m` in + ia64) SO=.so;; + *) SO=.sl;; + esac + ;; + CYGWIN*) SO=.dll;; + *) SO=.so;; + esac else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - ac_lo=`expr '(' $ac_mid ')' + 1` + # this might also be a termcap variable, see #610332 + echo + echo '=====================================================================' + echo '+ +' + echo '+ WARNING: You have set SO in your environment. +' + echo '+ Do you really mean to change the extension for shared libraries? +' + echo '+ Continuing in 10 seconds to let you to ponder. +' + echo '+ +' + echo '=====================================================================' + sleep 10 fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $SO" >&5 +$as_echo "$SO" >&6; } -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext -done -case $ac_lo in -?*) ac_cv_sizeof_short=$ac_lo;; -'') if test "$ac_cv_type_short" = yes; then - { { echo "$as_me:$LINENO: error: cannot compute sizeof (short) -See \`config.log' for more details." >&5 -echo "$as_me: error: cannot compute sizeof (short) -See \`config.log' for more details." >&2;} - { (exit 77); exit 77; }; } - else - ac_cv_sizeof_short=0 - fi ;; -esac -else - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -$ac_includes_default - typedef short ac__type_sizeof_; -static long int longval () { return (long int) (sizeof (ac__type_sizeof_)); } -static unsigned long int ulongval () { return (long int) (sizeof (ac__type_sizeof_)); } -#include -#include -int -main () -{ - - FILE *f = fopen ("conftest.val", "w"); - if (! f) - return 1; - if (((long int) (sizeof (ac__type_sizeof_))) < 0) - { - long int i = longval (); - if (i != ((long int) (sizeof (ac__type_sizeof_)))) - return 1; - fprintf (f, "%ld\n", i); - } - else - { - unsigned long int i = ulongval (); - if (i != ((long int) (sizeof (ac__type_sizeof_)))) - return 1; - fprintf (f, "%lu\n", i); - } - return ferror (f) || fclose (f) != 0; - ; - return 0; -} +cat >>confdefs.h <<_ACEOF +#define SHLIB_EXT "$SO" _ACEOF -rm -f conftest$ac_exeext -if { (ac_try="$ac_link" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_link") 2>&5 - ac_status=$? - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { ac_try='./conftest$ac_exeext' - { (case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_try") 2>&5 - ac_status=$? - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); }; }; then - ac_cv_sizeof_short=`cat conftest.val` -else - echo "$as_me: program exited with status $ac_status" >&5 -echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - -( exit $ac_status ) -if test "$ac_cv_type_short" = yes; then - { { echo "$as_me:$LINENO: error: cannot compute sizeof (short) -See \`config.log' for more details." >&5 -echo "$as_me: error: cannot compute sizeof (short) -See \`config.log' for more details." >&2;} - { (exit 77); exit 77; }; } - else - ac_cv_sizeof_short=0 - fi -fi -rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext conftest.$ac_objext conftest.$ac_ext -fi -rm -f conftest.val -fi -{ echo "$as_me:$LINENO: result: $ac_cv_sizeof_short" >&5 -echo "${ECHO_T}$ac_cv_sizeof_short" >&6; } - - - -cat >>confdefs.h <<_ACEOF -#define SIZEOF_SHORT $ac_cv_sizeof_short -_ACEOF - - -{ echo "$as_me:$LINENO: checking for float" >&5 -echo $ECHO_N "checking for float... $ECHO_C" >&6; } -if test "${ac_cv_type_float+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 -else - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -$ac_includes_default -typedef float ac__type_new_; -int -main () -{ -if ((ac__type_new_ *) 0) - return 0; -if (sizeof (ac__type_new_)) - return 0; - ; - return 0; -} -_ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - ac_cv_type_float=yes -else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - ac_cv_type_float=no -fi - -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext -fi -{ echo "$as_me:$LINENO: result: $ac_cv_type_float" >&5 -echo "${ECHO_T}$ac_cv_type_float" >&6; } - -# The cast to long int works around a bug in the HP C Compiler -# version HP92453-01 B.11.11.23709.GP, which incorrectly rejects -# declarations like `int a3[[(sizeof (unsigned char)) >= 0]];'. -# This bug is HP SR number 8606223364. -{ echo "$as_me:$LINENO: checking size of float" >&5 -echo $ECHO_N "checking size of float... $ECHO_C" >&6; } -if test "${ac_cv_sizeof_float+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 -else - if test "$cross_compiling" = yes; then - # Depending upon the size, compute the lo and hi bounds. -cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -$ac_includes_default - typedef float ac__type_sizeof_; -int -main () -{ -static int test_array [1 - 2 * !(((long int) (sizeof (ac__type_sizeof_))) >= 0)]; -test_array [0] = 0 - - ; - return 0; -} -_ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - ac_lo=0 ac_mid=0 - while :; do - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -$ac_includes_default - typedef float ac__type_sizeof_; -int -main () -{ -static int test_array [1 - 2 * !(((long int) (sizeof (ac__type_sizeof_))) <= $ac_mid)]; -test_array [0] = 0 - - ; - return 0; -} -_ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - ac_hi=$ac_mid; break -else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - ac_lo=`expr $ac_mid + 1` - if test $ac_lo -le $ac_mid; then - ac_lo= ac_hi= - break - fi - ac_mid=`expr 2 '*' $ac_mid + 1` -fi - -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext - done -else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -$ac_includes_default - typedef float ac__type_sizeof_; -int -main () -{ -static int test_array [1 - 2 * !(((long int) (sizeof (ac__type_sizeof_))) < 0)]; -test_array [0] = 0 - - ; - return 0; -} -_ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - ac_hi=-1 ac_mid=-1 - while :; do - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -$ac_includes_default - typedef float ac__type_sizeof_; -int -main () -{ -static int test_array [1 - 2 * !(((long int) (sizeof (ac__type_sizeof_))) >= $ac_mid)]; -test_array [0] = 0 - - ; - return 0; -} -_ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - ac_lo=$ac_mid; break -else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - ac_hi=`expr '(' $ac_mid ')' - 1` - if test $ac_mid -le $ac_hi; then - ac_lo= ac_hi= - break - fi - ac_mid=`expr 2 '*' $ac_mid` -fi - -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext - done -else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - ac_lo= ac_hi= -fi - -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext -fi - -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext -# Binary search between lo and hi bounds. -while test "x$ac_lo" != "x$ac_hi"; do - ac_mid=`expr '(' $ac_hi - $ac_lo ')' / 2 + $ac_lo` - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -$ac_includes_default - typedef float ac__type_sizeof_; -int -main () -{ -static int test_array [1 - 2 * !(((long int) (sizeof (ac__type_sizeof_))) <= $ac_mid)]; -test_array [0] = 0 - - ; - return 0; -} -_ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - ac_hi=$ac_mid -else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - ac_lo=`expr '(' $ac_mid ')' + 1` -fi - -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext -done -case $ac_lo in -?*) ac_cv_sizeof_float=$ac_lo;; -'') if test "$ac_cv_type_float" = yes; then - { { echo "$as_me:$LINENO: error: cannot compute sizeof (float) -See \`config.log' for more details." >&5 -echo "$as_me: error: cannot compute sizeof (float) -See \`config.log' for more details." >&2;} - { (exit 77); exit 77; }; } - else - ac_cv_sizeof_float=0 - fi ;; -esac -else - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -$ac_includes_default - typedef float ac__type_sizeof_; -static long int longval () { return (long int) (sizeof (ac__type_sizeof_)); } -static unsigned long int ulongval () { return (long int) (sizeof (ac__type_sizeof_)); } -#include -#include -int -main () -{ - - FILE *f = fopen ("conftest.val", "w"); - if (! f) - return 1; - if (((long int) (sizeof (ac__type_sizeof_))) < 0) - { - long int i = longval (); - if (i != ((long int) (sizeof (ac__type_sizeof_)))) - return 1; - fprintf (f, "%ld\n", i); - } - else - { - unsigned long int i = ulongval (); - if (i != ((long int) (sizeof (ac__type_sizeof_)))) - return 1; - fprintf (f, "%lu\n", i); - } - return ferror (f) || fclose (f) != 0; - - ; - return 0; -} -_ACEOF -rm -f conftest$ac_exeext -if { (ac_try="$ac_link" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_link") 2>&5 - ac_status=$? - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { ac_try='./conftest$ac_exeext' - { (case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_try") 2>&5 - ac_status=$? - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); }; }; then - ac_cv_sizeof_float=`cat conftest.val` -else - echo "$as_me: program exited with status $ac_status" >&5 -echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - -( exit $ac_status ) -if test "$ac_cv_type_float" = yes; then - { { echo "$as_me:$LINENO: error: cannot compute sizeof (float) -See \`config.log' for more details." >&5 -echo "$as_me: error: cannot compute sizeof (float) -See \`config.log' for more details." >&2;} - { (exit 77); exit 77; }; } - else - ac_cv_sizeof_float=0 - fi -fi -rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext conftest.$ac_objext conftest.$ac_ext -fi -rm -f conftest.val -fi -{ echo "$as_me:$LINENO: result: $ac_cv_sizeof_float" >&5 -echo "${ECHO_T}$ac_cv_sizeof_float" >&6; } - - - -cat >>confdefs.h <<_ACEOF -#define SIZEOF_FLOAT $ac_cv_sizeof_float -_ACEOF - - -{ echo "$as_me:$LINENO: checking for double" >&5 -echo $ECHO_N "checking for double... $ECHO_C" >&6; } -if test "${ac_cv_type_double+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 -else - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -$ac_includes_default -typedef double ac__type_new_; -int -main () -{ -if ((ac__type_new_ *) 0) - return 0; -if (sizeof (ac__type_new_)) - return 0; - ; - return 0; -} -_ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - ac_cv_type_double=yes -else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - ac_cv_type_double=no -fi - -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext -fi -{ echo "$as_me:$LINENO: result: $ac_cv_type_double" >&5 -echo "${ECHO_T}$ac_cv_type_double" >&6; } - -# The cast to long int works around a bug in the HP C Compiler -# version HP92453-01 B.11.11.23709.GP, which incorrectly rejects -# declarations like `int a3[[(sizeof (unsigned char)) >= 0]];'. -# This bug is HP SR number 8606223364. -{ echo "$as_me:$LINENO: checking size of double" >&5 -echo $ECHO_N "checking size of double... $ECHO_C" >&6; } -if test "${ac_cv_sizeof_double+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 -else - if test "$cross_compiling" = yes; then - # Depending upon the size, compute the lo and hi bounds. -cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -$ac_includes_default - typedef double ac__type_sizeof_; -int -main () -{ -static int test_array [1 - 2 * !(((long int) (sizeof (ac__type_sizeof_))) >= 0)]; -test_array [0] = 0 - - ; - return 0; -} -_ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - ac_lo=0 ac_mid=0 - while :; do - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -$ac_includes_default - typedef double ac__type_sizeof_; -int -main () -{ -static int test_array [1 - 2 * !(((long int) (sizeof (ac__type_sizeof_))) <= $ac_mid)]; -test_array [0] = 0 - - ; - return 0; -} -_ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - ac_hi=$ac_mid; break -else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - ac_lo=`expr $ac_mid + 1` - if test $ac_lo -le $ac_mid; then - ac_lo= ac_hi= - break - fi - ac_mid=`expr 2 '*' $ac_mid + 1` -fi - -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext - done -else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -$ac_includes_default - typedef double ac__type_sizeof_; -int -main () -{ -static int test_array [1 - 2 * !(((long int) (sizeof (ac__type_sizeof_))) < 0)]; -test_array [0] = 0 - - ; - return 0; -} -_ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - ac_hi=-1 ac_mid=-1 - while :; do - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -$ac_includes_default - typedef double ac__type_sizeof_; -int -main () -{ -static int test_array [1 - 2 * !(((long int) (sizeof (ac__type_sizeof_))) >= $ac_mid)]; -test_array [0] = 0 - - ; - return 0; -} -_ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - ac_lo=$ac_mid; break -else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - ac_hi=`expr '(' $ac_mid ')' - 1` - if test $ac_mid -le $ac_hi; then - ac_lo= ac_hi= - break - fi - ac_mid=`expr 2 '*' $ac_mid` -fi - -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext - done -else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - ac_lo= ac_hi= -fi - -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext -fi - -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext -# Binary search between lo and hi bounds. -while test "x$ac_lo" != "x$ac_hi"; do - ac_mid=`expr '(' $ac_hi - $ac_lo ')' / 2 + $ac_lo` - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -$ac_includes_default - typedef double ac__type_sizeof_; -int -main () -{ -static int test_array [1 - 2 * !(((long int) (sizeof (ac__type_sizeof_))) <= $ac_mid)]; -test_array [0] = 0 - - ; - return 0; -} -_ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - ac_hi=$ac_mid -else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - ac_lo=`expr '(' $ac_mid ')' + 1` -fi - -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext -done -case $ac_lo in -?*) ac_cv_sizeof_double=$ac_lo;; -'') if test "$ac_cv_type_double" = yes; then - { { echo "$as_me:$LINENO: error: cannot compute sizeof (double) -See \`config.log' for more details." >&5 -echo "$as_me: error: cannot compute sizeof (double) -See \`config.log' for more details." >&2;} - { (exit 77); exit 77; }; } - else - ac_cv_sizeof_double=0 - fi ;; -esac -else - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -$ac_includes_default - typedef double ac__type_sizeof_; -static long int longval () { return (long int) (sizeof (ac__type_sizeof_)); } -static unsigned long int ulongval () { return (long int) (sizeof (ac__type_sizeof_)); } -#include -#include -int -main () -{ - - FILE *f = fopen ("conftest.val", "w"); - if (! f) - return 1; - if (((long int) (sizeof (ac__type_sizeof_))) < 0) - { - long int i = longval (); - if (i != ((long int) (sizeof (ac__type_sizeof_)))) - return 1; - fprintf (f, "%ld\n", i); - } - else - { - unsigned long int i = ulongval (); - if (i != ((long int) (sizeof (ac__type_sizeof_)))) - return 1; - fprintf (f, "%lu\n", i); - } - return ferror (f) || fclose (f) != 0; - - ; - return 0; -} -_ACEOF -rm -f conftest$ac_exeext -if { (ac_try="$ac_link" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_link") 2>&5 - ac_status=$? - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { ac_try='./conftest$ac_exeext' - { (case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_try") 2>&5 - ac_status=$? - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); }; }; then - ac_cv_sizeof_double=`cat conftest.val` -else - echo "$as_me: program exited with status $ac_status" >&5 -echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - -( exit $ac_status ) -if test "$ac_cv_type_double" = yes; then - { { echo "$as_me:$LINENO: error: cannot compute sizeof (double) -See \`config.log' for more details." >&5 -echo "$as_me: error: cannot compute sizeof (double) -See \`config.log' for more details." >&2;} - { (exit 77); exit 77; }; } - else - ac_cv_sizeof_double=0 - fi -fi -rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext conftest.$ac_objext conftest.$ac_ext -fi -rm -f conftest.val -fi -{ echo "$as_me:$LINENO: result: $ac_cv_sizeof_double" >&5 -echo "${ECHO_T}$ac_cv_sizeof_double" >&6; } - - - -cat >>confdefs.h <<_ACEOF -#define SIZEOF_DOUBLE $ac_cv_sizeof_double -_ACEOF - - -{ echo "$as_me:$LINENO: checking for fpos_t" >&5 -echo $ECHO_N "checking for fpos_t... $ECHO_C" >&6; } -if test "${ac_cv_type_fpos_t+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 -else - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -$ac_includes_default -typedef fpos_t ac__type_new_; -int -main () -{ -if ((ac__type_new_ *) 0) - return 0; -if (sizeof (ac__type_new_)) - return 0; - ; - return 0; -} -_ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - ac_cv_type_fpos_t=yes -else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - ac_cv_type_fpos_t=no -fi - -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext -fi -{ echo "$as_me:$LINENO: result: $ac_cv_type_fpos_t" >&5 -echo "${ECHO_T}$ac_cv_type_fpos_t" >&6; } - -# The cast to long int works around a bug in the HP C Compiler -# version HP92453-01 B.11.11.23709.GP, which incorrectly rejects -# declarations like `int a3[[(sizeof (unsigned char)) >= 0]];'. -# This bug is HP SR number 8606223364. -{ echo "$as_me:$LINENO: checking size of fpos_t" >&5 -echo $ECHO_N "checking size of fpos_t... $ECHO_C" >&6; } -if test "${ac_cv_sizeof_fpos_t+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 -else - if test "$cross_compiling" = yes; then - # Depending upon the size, compute the lo and hi bounds. -cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -$ac_includes_default - typedef fpos_t ac__type_sizeof_; -int -main () -{ -static int test_array [1 - 2 * !(((long int) (sizeof (ac__type_sizeof_))) >= 0)]; -test_array [0] = 0 - - ; - return 0; -} -_ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - ac_lo=0 ac_mid=0 - while :; do - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -$ac_includes_default - typedef fpos_t ac__type_sizeof_; -int -main () -{ -static int test_array [1 - 2 * !(((long int) (sizeof (ac__type_sizeof_))) <= $ac_mid)]; -test_array [0] = 0 - - ; - return 0; -} -_ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - ac_hi=$ac_mid; break -else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - ac_lo=`expr $ac_mid + 1` - if test $ac_lo -le $ac_mid; then - ac_lo= ac_hi= - break - fi - ac_mid=`expr 2 '*' $ac_mid + 1` -fi - -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext - done -else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -$ac_includes_default - typedef fpos_t ac__type_sizeof_; -int -main () -{ -static int test_array [1 - 2 * !(((long int) (sizeof (ac__type_sizeof_))) < 0)]; -test_array [0] = 0 - - ; - return 0; -} -_ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - ac_hi=-1 ac_mid=-1 - while :; do - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -$ac_includes_default - typedef fpos_t ac__type_sizeof_; -int -main () -{ -static int test_array [1 - 2 * !(((long int) (sizeof (ac__type_sizeof_))) >= $ac_mid)]; -test_array [0] = 0 - - ; - return 0; -} -_ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - ac_lo=$ac_mid; break -else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - ac_hi=`expr '(' $ac_mid ')' - 1` - if test $ac_mid -le $ac_hi; then - ac_lo= ac_hi= - break - fi - ac_mid=`expr 2 '*' $ac_mid` -fi - -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext - done -else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - ac_lo= ac_hi= -fi - -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext -fi - -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext -# Binary search between lo and hi bounds. -while test "x$ac_lo" != "x$ac_hi"; do - ac_mid=`expr '(' $ac_hi - $ac_lo ')' / 2 + $ac_lo` - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -$ac_includes_default - typedef fpos_t ac__type_sizeof_; -int -main () -{ -static int test_array [1 - 2 * !(((long int) (sizeof (ac__type_sizeof_))) <= $ac_mid)]; -test_array [0] = 0 - - ; - return 0; -} -_ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - ac_hi=$ac_mid -else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - ac_lo=`expr '(' $ac_mid ')' + 1` -fi - -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext -done -case $ac_lo in -?*) ac_cv_sizeof_fpos_t=$ac_lo;; -'') if test "$ac_cv_type_fpos_t" = yes; then - { { echo "$as_me:$LINENO: error: cannot compute sizeof (fpos_t) -See \`config.log' for more details." >&5 -echo "$as_me: error: cannot compute sizeof (fpos_t) -See \`config.log' for more details." >&2;} - { (exit 77); exit 77; }; } - else - ac_cv_sizeof_fpos_t=0 - fi ;; -esac -else - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -$ac_includes_default - typedef fpos_t ac__type_sizeof_; -static long int longval () { return (long int) (sizeof (ac__type_sizeof_)); } -static unsigned long int ulongval () { return (long int) (sizeof (ac__type_sizeof_)); } -#include -#include -int -main () -{ - - FILE *f = fopen ("conftest.val", "w"); - if (! f) - return 1; - if (((long int) (sizeof (ac__type_sizeof_))) < 0) - { - long int i = longval (); - if (i != ((long int) (sizeof (ac__type_sizeof_)))) - return 1; - fprintf (f, "%ld\n", i); - } - else - { - unsigned long int i = ulongval (); - if (i != ((long int) (sizeof (ac__type_sizeof_)))) - return 1; - fprintf (f, "%lu\n", i); - } - return ferror (f) || fclose (f) != 0; - - ; - return 0; -} -_ACEOF -rm -f conftest$ac_exeext -if { (ac_try="$ac_link" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_link") 2>&5 - ac_status=$? - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { ac_try='./conftest$ac_exeext' - { (case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_try") 2>&5 - ac_status=$? - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); }; }; then - ac_cv_sizeof_fpos_t=`cat conftest.val` -else - echo "$as_me: program exited with status $ac_status" >&5 -echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - -( exit $ac_status ) -if test "$ac_cv_type_fpos_t" = yes; then - { { echo "$as_me:$LINENO: error: cannot compute sizeof (fpos_t) -See \`config.log' for more details." >&5 -echo "$as_me: error: cannot compute sizeof (fpos_t) -See \`config.log' for more details." >&2;} - { (exit 77); exit 77; }; } - else - ac_cv_sizeof_fpos_t=0 - fi -fi -rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext conftest.$ac_objext conftest.$ac_ext -fi -rm -f conftest.val -fi -{ echo "$as_me:$LINENO: result: $ac_cv_sizeof_fpos_t" >&5 -echo "${ECHO_T}$ac_cv_sizeof_fpos_t" >&6; } - - - -cat >>confdefs.h <<_ACEOF -#define SIZEOF_FPOS_T $ac_cv_sizeof_fpos_t -_ACEOF - - -{ echo "$as_me:$LINENO: checking for size_t" >&5 -echo $ECHO_N "checking for size_t... $ECHO_C" >&6; } -if test "${ac_cv_type_size_t+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 -else - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -$ac_includes_default -typedef size_t ac__type_new_; -int -main () -{ -if ((ac__type_new_ *) 0) - return 0; -if (sizeof (ac__type_new_)) - return 0; - ; - return 0; -} -_ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - ac_cv_type_size_t=yes -else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - ac_cv_type_size_t=no -fi - -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext -fi -{ echo "$as_me:$LINENO: result: $ac_cv_type_size_t" >&5 -echo "${ECHO_T}$ac_cv_type_size_t" >&6; } - -# The cast to long int works around a bug in the HP C Compiler -# version HP92453-01 B.11.11.23709.GP, which incorrectly rejects -# declarations like `int a3[[(sizeof (unsigned char)) >= 0]];'. -# This bug is HP SR number 8606223364. -{ echo "$as_me:$LINENO: checking size of size_t" >&5 -echo $ECHO_N "checking size of size_t... $ECHO_C" >&6; } -if test "${ac_cv_sizeof_size_t+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 -else - if test "$cross_compiling" = yes; then - # Depending upon the size, compute the lo and hi bounds. -cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -$ac_includes_default - typedef size_t ac__type_sizeof_; -int -main () -{ -static int test_array [1 - 2 * !(((long int) (sizeof (ac__type_sizeof_))) >= 0)]; -test_array [0] = 0 - - ; - return 0; -} -_ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - ac_lo=0 ac_mid=0 - while :; do - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -$ac_includes_default - typedef size_t ac__type_sizeof_; -int -main () -{ -static int test_array [1 - 2 * !(((long int) (sizeof (ac__type_sizeof_))) <= $ac_mid)]; -test_array [0] = 0 - - ; - return 0; -} -_ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - ac_hi=$ac_mid; break -else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - ac_lo=`expr $ac_mid + 1` - if test $ac_lo -le $ac_mid; then - ac_lo= ac_hi= - break - fi - ac_mid=`expr 2 '*' $ac_mid + 1` -fi - -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext - done -else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -$ac_includes_default - typedef size_t ac__type_sizeof_; -int -main () -{ -static int test_array [1 - 2 * !(((long int) (sizeof (ac__type_sizeof_))) < 0)]; -test_array [0] = 0 - - ; - return 0; -} -_ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - ac_hi=-1 ac_mid=-1 - while :; do - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -$ac_includes_default - typedef size_t ac__type_sizeof_; -int -main () -{ -static int test_array [1 - 2 * !(((long int) (sizeof (ac__type_sizeof_))) >= $ac_mid)]; -test_array [0] = 0 - - ; - return 0; -} -_ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - ac_lo=$ac_mid; break -else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - ac_hi=`expr '(' $ac_mid ')' - 1` - if test $ac_mid -le $ac_hi; then - ac_lo= ac_hi= - break - fi - ac_mid=`expr 2 '*' $ac_mid` -fi - -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext - done -else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - ac_lo= ac_hi= -fi - -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext -fi - -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext -# Binary search between lo and hi bounds. -while test "x$ac_lo" != "x$ac_hi"; do - ac_mid=`expr '(' $ac_hi - $ac_lo ')' / 2 + $ac_lo` - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -$ac_includes_default - typedef size_t ac__type_sizeof_; -int -main () -{ -static int test_array [1 - 2 * !(((long int) (sizeof (ac__type_sizeof_))) <= $ac_mid)]; -test_array [0] = 0 - - ; - return 0; -} -_ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - ac_hi=$ac_mid -else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - ac_lo=`expr '(' $ac_mid ')' + 1` -fi - -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext -done -case $ac_lo in -?*) ac_cv_sizeof_size_t=$ac_lo;; -'') if test "$ac_cv_type_size_t" = yes; then - { { echo "$as_me:$LINENO: error: cannot compute sizeof (size_t) -See \`config.log' for more details." >&5 -echo "$as_me: error: cannot compute sizeof (size_t) -See \`config.log' for more details." >&2;} - { (exit 77); exit 77; }; } - else - ac_cv_sizeof_size_t=0 - fi ;; -esac -else - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -$ac_includes_default - typedef size_t ac__type_sizeof_; -static long int longval () { return (long int) (sizeof (ac__type_sizeof_)); } -static unsigned long int ulongval () { return (long int) (sizeof (ac__type_sizeof_)); } -#include -#include -int -main () -{ - - FILE *f = fopen ("conftest.val", "w"); - if (! f) - return 1; - if (((long int) (sizeof (ac__type_sizeof_))) < 0) - { - long int i = longval (); - if (i != ((long int) (sizeof (ac__type_sizeof_)))) - return 1; - fprintf (f, "%ld\n", i); - } - else - { - unsigned long int i = ulongval (); - if (i != ((long int) (sizeof (ac__type_sizeof_)))) - return 1; - fprintf (f, "%lu\n", i); - } - return ferror (f) || fclose (f) != 0; - - ; - return 0; -} -_ACEOF -rm -f conftest$ac_exeext -if { (ac_try="$ac_link" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_link") 2>&5 - ac_status=$? - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { ac_try='./conftest$ac_exeext' - { (case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_try") 2>&5 - ac_status=$? - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); }; }; then - ac_cv_sizeof_size_t=`cat conftest.val` -else - echo "$as_me: program exited with status $ac_status" >&5 -echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - -( exit $ac_status ) -if test "$ac_cv_type_size_t" = yes; then - { { echo "$as_me:$LINENO: error: cannot compute sizeof (size_t) -See \`config.log' for more details." >&5 -echo "$as_me: error: cannot compute sizeof (size_t) -See \`config.log' for more details." >&2;} - { (exit 77); exit 77; }; } - else - ac_cv_sizeof_size_t=0 - fi -fi -rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext conftest.$ac_objext conftest.$ac_ext -fi -rm -f conftest.val -fi -{ echo "$as_me:$LINENO: result: $ac_cv_sizeof_size_t" >&5 -echo "${ECHO_T}$ac_cv_sizeof_size_t" >&6; } - - - -cat >>confdefs.h <<_ACEOF -#define SIZEOF_SIZE_T $ac_cv_sizeof_size_t -_ACEOF - - -{ echo "$as_me:$LINENO: checking for pid_t" >&5 -echo $ECHO_N "checking for pid_t... $ECHO_C" >&6; } -if test "${ac_cv_type_pid_t+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 -else - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -$ac_includes_default -typedef pid_t ac__type_new_; -int -main () -{ -if ((ac__type_new_ *) 0) - return 0; -if (sizeof (ac__type_new_)) - return 0; - ; - return 0; -} -_ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - ac_cv_type_pid_t=yes -else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - ac_cv_type_pid_t=no -fi - -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext -fi -{ echo "$as_me:$LINENO: result: $ac_cv_type_pid_t" >&5 -echo "${ECHO_T}$ac_cv_type_pid_t" >&6; } - -# The cast to long int works around a bug in the HP C Compiler -# version HP92453-01 B.11.11.23709.GP, which incorrectly rejects -# declarations like `int a3[[(sizeof (unsigned char)) >= 0]];'. -# This bug is HP SR number 8606223364. -{ echo "$as_me:$LINENO: checking size of pid_t" >&5 -echo $ECHO_N "checking size of pid_t... $ECHO_C" >&6; } -if test "${ac_cv_sizeof_pid_t+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 -else - if test "$cross_compiling" = yes; then - # Depending upon the size, compute the lo and hi bounds. -cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -$ac_includes_default - typedef pid_t ac__type_sizeof_; -int -main () -{ -static int test_array [1 - 2 * !(((long int) (sizeof (ac__type_sizeof_))) >= 0)]; -test_array [0] = 0 - - ; - return 0; -} -_ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - ac_lo=0 ac_mid=0 - while :; do - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -$ac_includes_default - typedef pid_t ac__type_sizeof_; -int -main () -{ -static int test_array [1 - 2 * !(((long int) (sizeof (ac__type_sizeof_))) <= $ac_mid)]; -test_array [0] = 0 - - ; - return 0; -} -_ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - ac_hi=$ac_mid; break -else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - ac_lo=`expr $ac_mid + 1` - if test $ac_lo -le $ac_mid; then - ac_lo= ac_hi= - break - fi - ac_mid=`expr 2 '*' $ac_mid + 1` -fi - -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext - done -else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -$ac_includes_default - typedef pid_t ac__type_sizeof_; -int -main () -{ -static int test_array [1 - 2 * !(((long int) (sizeof (ac__type_sizeof_))) < 0)]; -test_array [0] = 0 - - ; - return 0; -} -_ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - ac_hi=-1 ac_mid=-1 - while :; do - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -$ac_includes_default - typedef pid_t ac__type_sizeof_; -int -main () -{ -static int test_array [1 - 2 * !(((long int) (sizeof (ac__type_sizeof_))) >= $ac_mid)]; -test_array [0] = 0 - - ; - return 0; -} -_ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - ac_lo=$ac_mid; break -else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - ac_hi=`expr '(' $ac_mid ')' - 1` - if test $ac_mid -le $ac_hi; then - ac_lo= ac_hi= - break - fi - ac_mid=`expr 2 '*' $ac_mid` -fi - -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext - done -else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - ac_lo= ac_hi= -fi - -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext -fi - -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext -# Binary search between lo and hi bounds. -while test "x$ac_lo" != "x$ac_hi"; do - ac_mid=`expr '(' $ac_hi - $ac_lo ')' / 2 + $ac_lo` - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -$ac_includes_default - typedef pid_t ac__type_sizeof_; -int -main () -{ -static int test_array [1 - 2 * !(((long int) (sizeof (ac__type_sizeof_))) <= $ac_mid)]; -test_array [0] = 0 - - ; - return 0; -} -_ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - ac_hi=$ac_mid -else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - ac_lo=`expr '(' $ac_mid ')' + 1` -fi - -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext -done -case $ac_lo in -?*) ac_cv_sizeof_pid_t=$ac_lo;; -'') if test "$ac_cv_type_pid_t" = yes; then - { { echo "$as_me:$LINENO: error: cannot compute sizeof (pid_t) -See \`config.log' for more details." >&5 -echo "$as_me: error: cannot compute sizeof (pid_t) -See \`config.log' for more details." >&2;} - { (exit 77); exit 77; }; } - else - ac_cv_sizeof_pid_t=0 - fi ;; -esac -else - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -$ac_includes_default - typedef pid_t ac__type_sizeof_; -static long int longval () { return (long int) (sizeof (ac__type_sizeof_)); } -static unsigned long int ulongval () { return (long int) (sizeof (ac__type_sizeof_)); } -#include -#include -int -main () -{ - - FILE *f = fopen ("conftest.val", "w"); - if (! f) - return 1; - if (((long int) (sizeof (ac__type_sizeof_))) < 0) - { - long int i = longval (); - if (i != ((long int) (sizeof (ac__type_sizeof_)))) - return 1; - fprintf (f, "%ld\n", i); - } - else - { - unsigned long int i = ulongval (); - if (i != ((long int) (sizeof (ac__type_sizeof_)))) - return 1; - fprintf (f, "%lu\n", i); - } - return ferror (f) || fclose (f) != 0; - - ; - return 0; -} -_ACEOF -rm -f conftest$ac_exeext -if { (ac_try="$ac_link" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_link") 2>&5 - ac_status=$? - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { ac_try='./conftest$ac_exeext' - { (case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_try") 2>&5 - ac_status=$? - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); }; }; then - ac_cv_sizeof_pid_t=`cat conftest.val` -else - echo "$as_me: program exited with status $ac_status" >&5 -echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - -( exit $ac_status ) -if test "$ac_cv_type_pid_t" = yes; then - { { echo "$as_me:$LINENO: error: cannot compute sizeof (pid_t) -See \`config.log' for more details." >&5 -echo "$as_me: error: cannot compute sizeof (pid_t) -See \`config.log' for more details." >&2;} - { (exit 77); exit 77; }; } - else - ac_cv_sizeof_pid_t=0 - fi -fi -rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext conftest.$ac_objext conftest.$ac_ext -fi -rm -f conftest.val -fi -{ echo "$as_me:$LINENO: result: $ac_cv_sizeof_pid_t" >&5 -echo "${ECHO_T}$ac_cv_sizeof_pid_t" >&6; } - - - -cat >>confdefs.h <<_ACEOF -#define SIZEOF_PID_T $ac_cv_sizeof_pid_t -_ACEOF - - - -{ echo "$as_me:$LINENO: checking for long long support" >&5 -echo $ECHO_N "checking for long long support... $ECHO_C" >&6; } -have_long_long=no -cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ - -int -main () -{ -long long x; x = (long long)0; - ; - return 0; -} -_ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - - -cat >>confdefs.h <<\_ACEOF -#define HAVE_LONG_LONG 1 -_ACEOF - - have_long_long=yes - -else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - -fi - -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext -{ echo "$as_me:$LINENO: result: $have_long_long" >&5 -echo "${ECHO_T}$have_long_long" >&6; } -if test "$have_long_long" = yes ; then -{ echo "$as_me:$LINENO: checking for long long" >&5 -echo $ECHO_N "checking for long long... $ECHO_C" >&6; } -if test "${ac_cv_type_long_long+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 -else - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -$ac_includes_default -typedef long long ac__type_new_; -int -main () -{ -if ((ac__type_new_ *) 0) - return 0; -if (sizeof (ac__type_new_)) - return 0; - ; - return 0; -} -_ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - ac_cv_type_long_long=yes -else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - ac_cv_type_long_long=no -fi - -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext -fi -{ echo "$as_me:$LINENO: result: $ac_cv_type_long_long" >&5 -echo "${ECHO_T}$ac_cv_type_long_long" >&6; } - -# The cast to long int works around a bug in the HP C Compiler -# version HP92453-01 B.11.11.23709.GP, which incorrectly rejects -# declarations like `int a3[[(sizeof (unsigned char)) >= 0]];'. -# This bug is HP SR number 8606223364. -{ echo "$as_me:$LINENO: checking size of long long" >&5 -echo $ECHO_N "checking size of long long... $ECHO_C" >&6; } -if test "${ac_cv_sizeof_long_long+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 -else - if test "$cross_compiling" = yes; then - # Depending upon the size, compute the lo and hi bounds. -cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -$ac_includes_default - typedef long long ac__type_sizeof_; -int -main () -{ -static int test_array [1 - 2 * !(((long int) (sizeof (ac__type_sizeof_))) >= 0)]; -test_array [0] = 0 - - ; - return 0; -} -_ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - ac_lo=0 ac_mid=0 - while :; do - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -$ac_includes_default - typedef long long ac__type_sizeof_; -int -main () -{ -static int test_array [1 - 2 * !(((long int) (sizeof (ac__type_sizeof_))) <= $ac_mid)]; -test_array [0] = 0 - - ; - return 0; -} -_ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - ac_hi=$ac_mid; break -else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - ac_lo=`expr $ac_mid + 1` - if test $ac_lo -le $ac_mid; then - ac_lo= ac_hi= - break - fi - ac_mid=`expr 2 '*' $ac_mid + 1` -fi - -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext - done -else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -$ac_includes_default - typedef long long ac__type_sizeof_; -int -main () -{ -static int test_array [1 - 2 * !(((long int) (sizeof (ac__type_sizeof_))) < 0)]; -test_array [0] = 0 - - ; - return 0; -} -_ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - ac_hi=-1 ac_mid=-1 - while :; do - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -$ac_includes_default - typedef long long ac__type_sizeof_; -int -main () -{ -static int test_array [1 - 2 * !(((long int) (sizeof (ac__type_sizeof_))) >= $ac_mid)]; -test_array [0] = 0 - - ; - return 0; -} -_ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - ac_lo=$ac_mid; break -else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - ac_hi=`expr '(' $ac_mid ')' - 1` - if test $ac_mid -le $ac_hi; then - ac_lo= ac_hi= - break - fi - ac_mid=`expr 2 '*' $ac_mid` -fi - -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext - done -else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - ac_lo= ac_hi= -fi - -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext -fi - -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext -# Binary search between lo and hi bounds. -while test "x$ac_lo" != "x$ac_hi"; do - ac_mid=`expr '(' $ac_hi - $ac_lo ')' / 2 + $ac_lo` - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -$ac_includes_default - typedef long long ac__type_sizeof_; -int -main () -{ -static int test_array [1 - 2 * !(((long int) (sizeof (ac__type_sizeof_))) <= $ac_mid)]; -test_array [0] = 0 - - ; - return 0; -} -_ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - ac_hi=$ac_mid -else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - ac_lo=`expr '(' $ac_mid ')' + 1` -fi - -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext -done -case $ac_lo in -?*) ac_cv_sizeof_long_long=$ac_lo;; -'') if test "$ac_cv_type_long_long" = yes; then - { { echo "$as_me:$LINENO: error: cannot compute sizeof (long long) -See \`config.log' for more details." >&5 -echo "$as_me: error: cannot compute sizeof (long long) -See \`config.log' for more details." >&2;} - { (exit 77); exit 77; }; } - else - ac_cv_sizeof_long_long=0 - fi ;; -esac -else - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -$ac_includes_default - typedef long long ac__type_sizeof_; -static long int longval () { return (long int) (sizeof (ac__type_sizeof_)); } -static unsigned long int ulongval () { return (long int) (sizeof (ac__type_sizeof_)); } -#include -#include -int -main () -{ - - FILE *f = fopen ("conftest.val", "w"); - if (! f) - return 1; - if (((long int) (sizeof (ac__type_sizeof_))) < 0) - { - long int i = longval (); - if (i != ((long int) (sizeof (ac__type_sizeof_)))) - return 1; - fprintf (f, "%ld\n", i); - } - else - { - unsigned long int i = ulongval (); - if (i != ((long int) (sizeof (ac__type_sizeof_)))) - return 1; - fprintf (f, "%lu\n", i); - } - return ferror (f) || fclose (f) != 0; - - ; - return 0; -} -_ACEOF -rm -f conftest$ac_exeext -if { (ac_try="$ac_link" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_link") 2>&5 - ac_status=$? - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { ac_try='./conftest$ac_exeext' - { (case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_try") 2>&5 - ac_status=$? - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); }; }; then - ac_cv_sizeof_long_long=`cat conftest.val` -else - echo "$as_me: program exited with status $ac_status" >&5 -echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - -( exit $ac_status ) -if test "$ac_cv_type_long_long" = yes; then - { { echo "$as_me:$LINENO: error: cannot compute sizeof (long long) -See \`config.log' for more details." >&5 -echo "$as_me: error: cannot compute sizeof (long long) -See \`config.log' for more details." >&2;} - { (exit 77); exit 77; }; } - else - ac_cv_sizeof_long_long=0 - fi -fi -rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext conftest.$ac_objext conftest.$ac_ext -fi -rm -f conftest.val -fi -{ echo "$as_me:$LINENO: result: $ac_cv_sizeof_long_long" >&5 -echo "${ECHO_T}$ac_cv_sizeof_long_long" >&6; } - - - -cat >>confdefs.h <<_ACEOF -#define SIZEOF_LONG_LONG $ac_cv_sizeof_long_long -_ACEOF - - -fi - -{ echo "$as_me:$LINENO: checking for long double support" >&5 -echo $ECHO_N "checking for long double support... $ECHO_C" >&6; } -have_long_double=no -cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ - -int -main () -{ -long double x; x = (long double)0.; - ; - return 0; -} -_ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - - -cat >>confdefs.h <<\_ACEOF -#define HAVE_LONG_DOUBLE 1 -_ACEOF - - have_long_double=yes - -else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - -fi - -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext -{ echo "$as_me:$LINENO: result: $have_long_double" >&5 -echo "${ECHO_T}$have_long_double" >&6; } -if test "$have_long_double" = yes ; then -{ echo "$as_me:$LINENO: checking for long double" >&5 -echo $ECHO_N "checking for long double... $ECHO_C" >&6; } -if test "${ac_cv_type_long_double+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 -else - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -$ac_includes_default -typedef long double ac__type_new_; -int -main () -{ -if ((ac__type_new_ *) 0) - return 0; -if (sizeof (ac__type_new_)) - return 0; - ; - return 0; -} -_ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - ac_cv_type_long_double=yes -else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - ac_cv_type_long_double=no -fi - -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext -fi -{ echo "$as_me:$LINENO: result: $ac_cv_type_long_double" >&5 -echo "${ECHO_T}$ac_cv_type_long_double" >&6; } - -# The cast to long int works around a bug in the HP C Compiler -# version HP92453-01 B.11.11.23709.GP, which incorrectly rejects -# declarations like `int a3[[(sizeof (unsigned char)) >= 0]];'. -# This bug is HP SR number 8606223364. -{ echo "$as_me:$LINENO: checking size of long double" >&5 -echo $ECHO_N "checking size of long double... $ECHO_C" >&6; } -if test "${ac_cv_sizeof_long_double+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 -else - if test "$cross_compiling" = yes; then - # Depending upon the size, compute the lo and hi bounds. -cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -$ac_includes_default - typedef long double ac__type_sizeof_; -int -main () -{ -static int test_array [1 - 2 * !(((long int) (sizeof (ac__type_sizeof_))) >= 0)]; -test_array [0] = 0 - - ; - return 0; -} -_ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - ac_lo=0 ac_mid=0 - while :; do - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -$ac_includes_default - typedef long double ac__type_sizeof_; -int -main () -{ -static int test_array [1 - 2 * !(((long int) (sizeof (ac__type_sizeof_))) <= $ac_mid)]; -test_array [0] = 0 - - ; - return 0; -} -_ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - ac_hi=$ac_mid; break -else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - ac_lo=`expr $ac_mid + 1` - if test $ac_lo -le $ac_mid; then - ac_lo= ac_hi= - break - fi - ac_mid=`expr 2 '*' $ac_mid + 1` -fi - -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext - done -else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -$ac_includes_default - typedef long double ac__type_sizeof_; -int -main () -{ -static int test_array [1 - 2 * !(((long int) (sizeof (ac__type_sizeof_))) < 0)]; -test_array [0] = 0 - - ; - return 0; -} -_ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - ac_hi=-1 ac_mid=-1 - while :; do - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -$ac_includes_default - typedef long double ac__type_sizeof_; -int -main () -{ -static int test_array [1 - 2 * !(((long int) (sizeof (ac__type_sizeof_))) >= $ac_mid)]; -test_array [0] = 0 - - ; - return 0; -} -_ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - ac_lo=$ac_mid; break -else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - ac_hi=`expr '(' $ac_mid ')' - 1` - if test $ac_mid -le $ac_hi; then - ac_lo= ac_hi= - break - fi - ac_mid=`expr 2 '*' $ac_mid` -fi - -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext - done -else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - ac_lo= ac_hi= -fi - -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext -fi - -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext -# Binary search between lo and hi bounds. -while test "x$ac_lo" != "x$ac_hi"; do - ac_mid=`expr '(' $ac_hi - $ac_lo ')' / 2 + $ac_lo` - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -$ac_includes_default - typedef long double ac__type_sizeof_; -int -main () -{ -static int test_array [1 - 2 * !(((long int) (sizeof (ac__type_sizeof_))) <= $ac_mid)]; -test_array [0] = 0 - - ; - return 0; -} -_ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - ac_hi=$ac_mid -else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - ac_lo=`expr '(' $ac_mid ')' + 1` -fi - -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext -done -case $ac_lo in -?*) ac_cv_sizeof_long_double=$ac_lo;; -'') if test "$ac_cv_type_long_double" = yes; then - { { echo "$as_me:$LINENO: error: cannot compute sizeof (long double) -See \`config.log' for more details." >&5 -echo "$as_me: error: cannot compute sizeof (long double) -See \`config.log' for more details." >&2;} - { (exit 77); exit 77; }; } - else - ac_cv_sizeof_long_double=0 - fi ;; -esac -else - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -$ac_includes_default - typedef long double ac__type_sizeof_; -static long int longval () { return (long int) (sizeof (ac__type_sizeof_)); } -static unsigned long int ulongval () { return (long int) (sizeof (ac__type_sizeof_)); } -#include -#include -int -main () -{ - - FILE *f = fopen ("conftest.val", "w"); - if (! f) - return 1; - if (((long int) (sizeof (ac__type_sizeof_))) < 0) - { - long int i = longval (); - if (i != ((long int) (sizeof (ac__type_sizeof_)))) - return 1; - fprintf (f, "%ld\n", i); - } - else - { - unsigned long int i = ulongval (); - if (i != ((long int) (sizeof (ac__type_sizeof_)))) - return 1; - fprintf (f, "%lu\n", i); - } - return ferror (f) || fclose (f) != 0; - - ; - return 0; -} -_ACEOF -rm -f conftest$ac_exeext -if { (ac_try="$ac_link" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_link") 2>&5 - ac_status=$? - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { ac_try='./conftest$ac_exeext' - { (case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_try") 2>&5 - ac_status=$? - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); }; }; then - ac_cv_sizeof_long_double=`cat conftest.val` -else - echo "$as_me: program exited with status $ac_status" >&5 -echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - -( exit $ac_status ) -if test "$ac_cv_type_long_double" = yes; then - { { echo "$as_me:$LINENO: error: cannot compute sizeof (long double) -See \`config.log' for more details." >&5 -echo "$as_me: error: cannot compute sizeof (long double) -See \`config.log' for more details." >&2;} - { (exit 77); exit 77; }; } - else - ac_cv_sizeof_long_double=0 - fi -fi -rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext conftest.$ac_objext conftest.$ac_ext -fi -rm -f conftest.val -fi -{ echo "$as_me:$LINENO: result: $ac_cv_sizeof_long_double" >&5 -echo "${ECHO_T}$ac_cv_sizeof_long_double" >&6; } - - - -cat >>confdefs.h <<_ACEOF -#define SIZEOF_LONG_DOUBLE $ac_cv_sizeof_long_double -_ACEOF - - -fi - -{ echo "$as_me:$LINENO: checking for _Bool support" >&5 -echo $ECHO_N "checking for _Bool support... $ECHO_C" >&6; } -have_c99_bool=no -cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ - -int -main () -{ -_Bool x; x = (_Bool)0; - ; - return 0; -} -_ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - - -cat >>confdefs.h <<\_ACEOF -#define HAVE_C99_BOOL 1 -_ACEOF - - have_c99_bool=yes - -else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - -fi - -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext -{ echo "$as_me:$LINENO: result: $have_c99_bool" >&5 -echo "${ECHO_T}$have_c99_bool" >&6; } -if test "$have_c99_bool" = yes ; then -{ echo "$as_me:$LINENO: checking for _Bool" >&5 -echo $ECHO_N "checking for _Bool... $ECHO_C" >&6; } -if test "${ac_cv_type__Bool+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 -else - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -$ac_includes_default -typedef _Bool ac__type_new_; -int -main () -{ -if ((ac__type_new_ *) 0) - return 0; -if (sizeof (ac__type_new_)) - return 0; - ; - return 0; -} -_ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - ac_cv_type__Bool=yes -else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - ac_cv_type__Bool=no -fi - -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext -fi -{ echo "$as_me:$LINENO: result: $ac_cv_type__Bool" >&5 -echo "${ECHO_T}$ac_cv_type__Bool" >&6; } - -# The cast to long int works around a bug in the HP C Compiler -# version HP92453-01 B.11.11.23709.GP, which incorrectly rejects -# declarations like `int a3[[(sizeof (unsigned char)) >= 0]];'. -# This bug is HP SR number 8606223364. -{ echo "$as_me:$LINENO: checking size of _Bool" >&5 -echo $ECHO_N "checking size of _Bool... $ECHO_C" >&6; } -if test "${ac_cv_sizeof__Bool+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 -else - if test "$cross_compiling" = yes; then - # Depending upon the size, compute the lo and hi bounds. -cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -$ac_includes_default - typedef _Bool ac__type_sizeof_; -int -main () -{ -static int test_array [1 - 2 * !(((long int) (sizeof (ac__type_sizeof_))) >= 0)]; -test_array [0] = 0 - - ; - return 0; -} -_ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - ac_lo=0 ac_mid=0 - while :; do - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -$ac_includes_default - typedef _Bool ac__type_sizeof_; -int -main () -{ -static int test_array [1 - 2 * !(((long int) (sizeof (ac__type_sizeof_))) <= $ac_mid)]; -test_array [0] = 0 - - ; - return 0; -} -_ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - ac_hi=$ac_mid; break -else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - ac_lo=`expr $ac_mid + 1` - if test $ac_lo -le $ac_mid; then - ac_lo= ac_hi= - break - fi - ac_mid=`expr 2 '*' $ac_mid + 1` -fi - -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext - done -else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -$ac_includes_default - typedef _Bool ac__type_sizeof_; -int -main () -{ -static int test_array [1 - 2 * !(((long int) (sizeof (ac__type_sizeof_))) < 0)]; -test_array [0] = 0 - - ; - return 0; -} -_ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - ac_hi=-1 ac_mid=-1 - while :; do - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -$ac_includes_default - typedef _Bool ac__type_sizeof_; -int -main () -{ -static int test_array [1 - 2 * !(((long int) (sizeof (ac__type_sizeof_))) >= $ac_mid)]; -test_array [0] = 0 - - ; - return 0; -} -_ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - ac_lo=$ac_mid; break -else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - ac_hi=`expr '(' $ac_mid ')' - 1` - if test $ac_mid -le $ac_hi; then - ac_lo= ac_hi= - break - fi - ac_mid=`expr 2 '*' $ac_mid` -fi - -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext - done -else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - ac_lo= ac_hi= -fi - -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext -fi - -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext -# Binary search between lo and hi bounds. -while test "x$ac_lo" != "x$ac_hi"; do - ac_mid=`expr '(' $ac_hi - $ac_lo ')' / 2 + $ac_lo` - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -$ac_includes_default - typedef _Bool ac__type_sizeof_; -int -main () -{ -static int test_array [1 - 2 * !(((long int) (sizeof (ac__type_sizeof_))) <= $ac_mid)]; -test_array [0] = 0 - - ; - return 0; -} -_ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - ac_hi=$ac_mid -else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - ac_lo=`expr '(' $ac_mid ')' + 1` -fi - -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext -done -case $ac_lo in -?*) ac_cv_sizeof__Bool=$ac_lo;; -'') if test "$ac_cv_type__Bool" = yes; then - { { echo "$as_me:$LINENO: error: cannot compute sizeof (_Bool) -See \`config.log' for more details." >&5 -echo "$as_me: error: cannot compute sizeof (_Bool) -See \`config.log' for more details." >&2;} - { (exit 77); exit 77; }; } - else - ac_cv_sizeof__Bool=0 - fi ;; -esac -else - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -$ac_includes_default - typedef _Bool ac__type_sizeof_; -static long int longval () { return (long int) (sizeof (ac__type_sizeof_)); } -static unsigned long int ulongval () { return (long int) (sizeof (ac__type_sizeof_)); } -#include -#include -int -main () -{ - - FILE *f = fopen ("conftest.val", "w"); - if (! f) - return 1; - if (((long int) (sizeof (ac__type_sizeof_))) < 0) - { - long int i = longval (); - if (i != ((long int) (sizeof (ac__type_sizeof_)))) - return 1; - fprintf (f, "%ld\n", i); - } - else - { - unsigned long int i = ulongval (); - if (i != ((long int) (sizeof (ac__type_sizeof_)))) - return 1; - fprintf (f, "%lu\n", i); - } - return ferror (f) || fclose (f) != 0; - - ; - return 0; -} -_ACEOF -rm -f conftest$ac_exeext -if { (ac_try="$ac_link" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_link") 2>&5 - ac_status=$? - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { ac_try='./conftest$ac_exeext' - { (case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_try") 2>&5 - ac_status=$? - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); }; }; then - ac_cv_sizeof__Bool=`cat conftest.val` -else - echo "$as_me: program exited with status $ac_status" >&5 -echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - -( exit $ac_status ) -if test "$ac_cv_type__Bool" = yes; then - { { echo "$as_me:$LINENO: error: cannot compute sizeof (_Bool) -See \`config.log' for more details." >&5 -echo "$as_me: error: cannot compute sizeof (_Bool) -See \`config.log' for more details." >&2;} - { (exit 77); exit 77; }; } - else - ac_cv_sizeof__Bool=0 - fi -fi -rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext conftest.$ac_objext conftest.$ac_ext -fi -rm -f conftest.val -fi -{ echo "$as_me:$LINENO: result: $ac_cv_sizeof__Bool" >&5 -echo "${ECHO_T}$ac_cv_sizeof__Bool" >&6; } - - - -cat >>confdefs.h <<_ACEOF -#define SIZEOF__BOOL $ac_cv_sizeof__Bool -_ACEOF - - -fi - -{ echo "$as_me:$LINENO: checking for uintptr_t" >&5 -echo $ECHO_N "checking for uintptr_t... $ECHO_C" >&6; } -if test "${ac_cv_type_uintptr_t+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 -else - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -#ifdef HAVE_STDINT_H - #include - #endif - -typedef uintptr_t ac__type_new_; -int -main () -{ -if ((ac__type_new_ *) 0) - return 0; -if (sizeof (ac__type_new_)) - return 0; - ; - return 0; -} -_ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - ac_cv_type_uintptr_t=yes -else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - ac_cv_type_uintptr_t=no -fi - -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext -fi -{ echo "$as_me:$LINENO: result: $ac_cv_type_uintptr_t" >&5 -echo "${ECHO_T}$ac_cv_type_uintptr_t" >&6; } -if test $ac_cv_type_uintptr_t = yes; then - -cat >>confdefs.h <<_ACEOF -#define HAVE_UINTPTR_T 1 -_ACEOF - -{ echo "$as_me:$LINENO: checking for uintptr_t" >&5 -echo $ECHO_N "checking for uintptr_t... $ECHO_C" >&6; } -if test "${ac_cv_type_uintptr_t+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 -else - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -$ac_includes_default -typedef uintptr_t ac__type_new_; -int -main () -{ -if ((ac__type_new_ *) 0) - return 0; -if (sizeof (ac__type_new_)) - return 0; - ; - return 0; -} -_ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - ac_cv_type_uintptr_t=yes -else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - ac_cv_type_uintptr_t=no -fi - -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext -fi -{ echo "$as_me:$LINENO: result: $ac_cv_type_uintptr_t" >&5 -echo "${ECHO_T}$ac_cv_type_uintptr_t" >&6; } - -# The cast to long int works around a bug in the HP C Compiler -# version HP92453-01 B.11.11.23709.GP, which incorrectly rejects -# declarations like `int a3[[(sizeof (unsigned char)) >= 0]];'. -# This bug is HP SR number 8606223364. -{ echo "$as_me:$LINENO: checking size of uintptr_t" >&5 -echo $ECHO_N "checking size of uintptr_t... $ECHO_C" >&6; } -if test "${ac_cv_sizeof_uintptr_t+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 -else - if test "$cross_compiling" = yes; then - # Depending upon the size, compute the lo and hi bounds. -cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -$ac_includes_default - typedef uintptr_t ac__type_sizeof_; -int -main () -{ -static int test_array [1 - 2 * !(((long int) (sizeof (ac__type_sizeof_))) >= 0)]; -test_array [0] = 0 - - ; - return 0; -} -_ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - ac_lo=0 ac_mid=0 - while :; do - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -$ac_includes_default - typedef uintptr_t ac__type_sizeof_; -int -main () -{ -static int test_array [1 - 2 * !(((long int) (sizeof (ac__type_sizeof_))) <= $ac_mid)]; -test_array [0] = 0 - - ; - return 0; -} -_ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - ac_hi=$ac_mid; break -else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - ac_lo=`expr $ac_mid + 1` - if test $ac_lo -le $ac_mid; then - ac_lo= ac_hi= - break - fi - ac_mid=`expr 2 '*' $ac_mid + 1` -fi - -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext - done -else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -$ac_includes_default - typedef uintptr_t ac__type_sizeof_; -int -main () -{ -static int test_array [1 - 2 * !(((long int) (sizeof (ac__type_sizeof_))) < 0)]; -test_array [0] = 0 - - ; - return 0; -} -_ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - ac_hi=-1 ac_mid=-1 - while :; do - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -$ac_includes_default - typedef uintptr_t ac__type_sizeof_; -int -main () -{ -static int test_array [1 - 2 * !(((long int) (sizeof (ac__type_sizeof_))) >= $ac_mid)]; -test_array [0] = 0 - - ; - return 0; -} -_ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - ac_lo=$ac_mid; break -else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - ac_hi=`expr '(' $ac_mid ')' - 1` - if test $ac_mid -le $ac_hi; then - ac_lo= ac_hi= - break - fi - ac_mid=`expr 2 '*' $ac_mid` -fi - -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext - done -else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - ac_lo= ac_hi= -fi - -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext -fi - -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext -# Binary search between lo and hi bounds. -while test "x$ac_lo" != "x$ac_hi"; do - ac_mid=`expr '(' $ac_hi - $ac_lo ')' / 2 + $ac_lo` - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -$ac_includes_default - typedef uintptr_t ac__type_sizeof_; -int -main () -{ -static int test_array [1 - 2 * !(((long int) (sizeof (ac__type_sizeof_))) <= $ac_mid)]; -test_array [0] = 0 - - ; - return 0; -} -_ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - ac_hi=$ac_mid -else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - ac_lo=`expr '(' $ac_mid ')' + 1` -fi - -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext -done -case $ac_lo in -?*) ac_cv_sizeof_uintptr_t=$ac_lo;; -'') if test "$ac_cv_type_uintptr_t" = yes; then - { { echo "$as_me:$LINENO: error: cannot compute sizeof (uintptr_t) -See \`config.log' for more details." >&5 -echo "$as_me: error: cannot compute sizeof (uintptr_t) -See \`config.log' for more details." >&2;} - { (exit 77); exit 77; }; } - else - ac_cv_sizeof_uintptr_t=0 - fi ;; -esac -else - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -$ac_includes_default - typedef uintptr_t ac__type_sizeof_; -static long int longval () { return (long int) (sizeof (ac__type_sizeof_)); } -static unsigned long int ulongval () { return (long int) (sizeof (ac__type_sizeof_)); } -#include -#include -int -main () -{ - - FILE *f = fopen ("conftest.val", "w"); - if (! f) - return 1; - if (((long int) (sizeof (ac__type_sizeof_))) < 0) - { - long int i = longval (); - if (i != ((long int) (sizeof (ac__type_sizeof_)))) - return 1; - fprintf (f, "%ld\n", i); - } - else - { - unsigned long int i = ulongval (); - if (i != ((long int) (sizeof (ac__type_sizeof_)))) - return 1; - fprintf (f, "%lu\n", i); - } - return ferror (f) || fclose (f) != 0; - - ; - return 0; -} -_ACEOF -rm -f conftest$ac_exeext -if { (ac_try="$ac_link" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_link") 2>&5 - ac_status=$? - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { ac_try='./conftest$ac_exeext' - { (case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_try") 2>&5 - ac_status=$? - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); }; }; then - ac_cv_sizeof_uintptr_t=`cat conftest.val` -else - echo "$as_me: program exited with status $ac_status" >&5 -echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - -( exit $ac_status ) -if test "$ac_cv_type_uintptr_t" = yes; then - { { echo "$as_me:$LINENO: error: cannot compute sizeof (uintptr_t) -See \`config.log' for more details." >&5 -echo "$as_me: error: cannot compute sizeof (uintptr_t) -See \`config.log' for more details." >&2;} - { (exit 77); exit 77; }; } - else - ac_cv_sizeof_uintptr_t=0 - fi -fi -rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext conftest.$ac_objext conftest.$ac_ext -fi -rm -f conftest.val -fi -{ echo "$as_me:$LINENO: result: $ac_cv_sizeof_uintptr_t" >&5 -echo "${ECHO_T}$ac_cv_sizeof_uintptr_t" >&6; } - - - -cat >>confdefs.h <<_ACEOF -#define SIZEOF_UINTPTR_T $ac_cv_sizeof_uintptr_t -_ACEOF - - -fi - - -{ echo "$as_me:$LINENO: checking for off_t" >&5 -echo $ECHO_N "checking for off_t... $ECHO_C" >&6; } -if test "${ac_cv_type_off_t+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 -else - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ - -#ifdef HAVE_SYS_TYPES_H -#include -#endif - - -typedef off_t ac__type_new_; -int -main () -{ -if ((ac__type_new_ *) 0) - return 0; -if (sizeof (ac__type_new_)) - return 0; - ; - return 0; -} -_ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - ac_cv_type_off_t=yes -else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - ac_cv_type_off_t=no -fi - -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext -fi -{ echo "$as_me:$LINENO: result: $ac_cv_type_off_t" >&5 -echo "${ECHO_T}$ac_cv_type_off_t" >&6; } - -# The cast to long int works around a bug in the HP C Compiler -# version HP92453-01 B.11.11.23709.GP, which incorrectly rejects -# declarations like `int a3[[(sizeof (unsigned char)) >= 0]];'. -# This bug is HP SR number 8606223364. -{ echo "$as_me:$LINENO: checking size of off_t" >&5 -echo $ECHO_N "checking size of off_t... $ECHO_C" >&6; } -if test "${ac_cv_sizeof_off_t+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 -else - if test "$cross_compiling" = yes; then - # Depending upon the size, compute the lo and hi bounds. -cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ - -#ifdef HAVE_SYS_TYPES_H -#include -#endif - - - typedef off_t ac__type_sizeof_; -int -main () -{ -static int test_array [1 - 2 * !(((long int) (sizeof (ac__type_sizeof_))) >= 0)]; -test_array [0] = 0 - - ; - return 0; -} -_ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - ac_lo=0 ac_mid=0 - while :; do - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ - -#ifdef HAVE_SYS_TYPES_H -#include -#endif - - - typedef off_t ac__type_sizeof_; -int -main () -{ -static int test_array [1 - 2 * !(((long int) (sizeof (ac__type_sizeof_))) <= $ac_mid)]; -test_array [0] = 0 - - ; - return 0; -} -_ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - ac_hi=$ac_mid; break -else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - ac_lo=`expr $ac_mid + 1` - if test $ac_lo -le $ac_mid; then - ac_lo= ac_hi= - break - fi - ac_mid=`expr 2 '*' $ac_mid + 1` -fi - -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext - done -else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ - -#ifdef HAVE_SYS_TYPES_H -#include -#endif - - - typedef off_t ac__type_sizeof_; -int -main () -{ -static int test_array [1 - 2 * !(((long int) (sizeof (ac__type_sizeof_))) < 0)]; -test_array [0] = 0 - - ; - return 0; -} -_ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - ac_hi=-1 ac_mid=-1 - while :; do - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ - -#ifdef HAVE_SYS_TYPES_H -#include -#endif - - - typedef off_t ac__type_sizeof_; -int -main () -{ -static int test_array [1 - 2 * !(((long int) (sizeof (ac__type_sizeof_))) >= $ac_mid)]; -test_array [0] = 0 - - ; - return 0; -} -_ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - ac_lo=$ac_mid; break -else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - ac_hi=`expr '(' $ac_mid ')' - 1` - if test $ac_mid -le $ac_hi; then - ac_lo= ac_hi= - break - fi - ac_mid=`expr 2 '*' $ac_mid` -fi - -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext - done -else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - ac_lo= ac_hi= -fi - -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext -fi - -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext -# Binary search between lo and hi bounds. -while test "x$ac_lo" != "x$ac_hi"; do - ac_mid=`expr '(' $ac_hi - $ac_lo ')' / 2 + $ac_lo` - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ - -#ifdef HAVE_SYS_TYPES_H -#include -#endif - - - typedef off_t ac__type_sizeof_; -int -main () -{ -static int test_array [1 - 2 * !(((long int) (sizeof (ac__type_sizeof_))) <= $ac_mid)]; -test_array [0] = 0 - - ; - return 0; -} -_ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - ac_hi=$ac_mid -else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - ac_lo=`expr '(' $ac_mid ')' + 1` -fi - -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext -done -case $ac_lo in -?*) ac_cv_sizeof_off_t=$ac_lo;; -'') if test "$ac_cv_type_off_t" = yes; then - { { echo "$as_me:$LINENO: error: cannot compute sizeof (off_t) -See \`config.log' for more details." >&5 -echo "$as_me: error: cannot compute sizeof (off_t) -See \`config.log' for more details." >&2;} - { (exit 77); exit 77; }; } - else - ac_cv_sizeof_off_t=0 - fi ;; -esac -else - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ - -#ifdef HAVE_SYS_TYPES_H -#include -#endif - - - typedef off_t ac__type_sizeof_; -static long int longval () { return (long int) (sizeof (ac__type_sizeof_)); } -static unsigned long int ulongval () { return (long int) (sizeof (ac__type_sizeof_)); } -#include -#include -int -main () -{ - - FILE *f = fopen ("conftest.val", "w"); - if (! f) - return 1; - if (((long int) (sizeof (ac__type_sizeof_))) < 0) - { - long int i = longval (); - if (i != ((long int) (sizeof (ac__type_sizeof_)))) - return 1; - fprintf (f, "%ld\n", i); - } - else - { - unsigned long int i = ulongval (); - if (i != ((long int) (sizeof (ac__type_sizeof_)))) - return 1; - fprintf (f, "%lu\n", i); - } - return ferror (f) || fclose (f) != 0; - - ; - return 0; -} -_ACEOF -rm -f conftest$ac_exeext -if { (ac_try="$ac_link" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_link") 2>&5 - ac_status=$? - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { ac_try='./conftest$ac_exeext' - { (case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_try") 2>&5 - ac_status=$? - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); }; }; then - ac_cv_sizeof_off_t=`cat conftest.val` -else - echo "$as_me: program exited with status $ac_status" >&5 -echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - -( exit $ac_status ) -if test "$ac_cv_type_off_t" = yes; then - { { echo "$as_me:$LINENO: error: cannot compute sizeof (off_t) -See \`config.log' for more details." >&5 -echo "$as_me: error: cannot compute sizeof (off_t) -See \`config.log' for more details." >&2;} - { (exit 77); exit 77; }; } - else - ac_cv_sizeof_off_t=0 - fi -fi -rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext conftest.$ac_objext conftest.$ac_ext -fi -rm -f conftest.val -fi -{ echo "$as_me:$LINENO: result: $ac_cv_sizeof_off_t" >&5 -echo "${ECHO_T}$ac_cv_sizeof_off_t" >&6; } - - - -cat >>confdefs.h <<_ACEOF -#define SIZEOF_OFF_T $ac_cv_sizeof_off_t -_ACEOF - - - -{ echo "$as_me:$LINENO: checking whether to enable large file support" >&5 -echo $ECHO_N "checking whether to enable large file support... $ECHO_C" >&6; } -if test "$have_long_long" = yes -then -if test "$ac_cv_sizeof_off_t" -gt "$ac_cv_sizeof_long" -a \ - "$ac_cv_sizeof_long_long" -ge "$ac_cv_sizeof_off_t"; then - -cat >>confdefs.h <<\_ACEOF -#define HAVE_LARGEFILE_SUPPORT 1 -_ACEOF - - { echo "$as_me:$LINENO: result: yes" >&5 -echo "${ECHO_T}yes" >&6; } -else - { echo "$as_me:$LINENO: result: no" >&5 -echo "${ECHO_T}no" >&6; } -fi -else - { echo "$as_me:$LINENO: result: no" >&5 -echo "${ECHO_T}no" >&6; } -fi - -{ echo "$as_me:$LINENO: checking for time_t" >&5 -echo $ECHO_N "checking for time_t... $ECHO_C" >&6; } -if test "${ac_cv_type_time_t+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 -else - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ - -#ifdef HAVE_SYS_TYPES_H -#include -#endif -#ifdef HAVE_TIME_H -#include -#endif - - -typedef time_t ac__type_new_; -int -main () -{ -if ((ac__type_new_ *) 0) - return 0; -if (sizeof (ac__type_new_)) - return 0; - ; - return 0; -} -_ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - ac_cv_type_time_t=yes -else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - ac_cv_type_time_t=no -fi - -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext -fi -{ echo "$as_me:$LINENO: result: $ac_cv_type_time_t" >&5 -echo "${ECHO_T}$ac_cv_type_time_t" >&6; } - -# The cast to long int works around a bug in the HP C Compiler -# version HP92453-01 B.11.11.23709.GP, which incorrectly rejects -# declarations like `int a3[[(sizeof (unsigned char)) >= 0]];'. -# This bug is HP SR number 8606223364. -{ echo "$as_me:$LINENO: checking size of time_t" >&5 -echo $ECHO_N "checking size of time_t... $ECHO_C" >&6; } -if test "${ac_cv_sizeof_time_t+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 -else - if test "$cross_compiling" = yes; then - # Depending upon the size, compute the lo and hi bounds. -cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ - -#ifdef HAVE_SYS_TYPES_H -#include -#endif -#ifdef HAVE_TIME_H -#include -#endif - - - typedef time_t ac__type_sizeof_; -int -main () -{ -static int test_array [1 - 2 * !(((long int) (sizeof (ac__type_sizeof_))) >= 0)]; -test_array [0] = 0 - - ; - return 0; -} -_ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - ac_lo=0 ac_mid=0 - while :; do - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ - -#ifdef HAVE_SYS_TYPES_H -#include -#endif -#ifdef HAVE_TIME_H -#include -#endif - - - typedef time_t ac__type_sizeof_; -int -main () -{ -static int test_array [1 - 2 * !(((long int) (sizeof (ac__type_sizeof_))) <= $ac_mid)]; -test_array [0] = 0 - - ; - return 0; -} -_ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - ac_hi=$ac_mid; break -else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - ac_lo=`expr $ac_mid + 1` - if test $ac_lo -le $ac_mid; then - ac_lo= ac_hi= - break - fi - ac_mid=`expr 2 '*' $ac_mid + 1` -fi - -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext - done -else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ - -#ifdef HAVE_SYS_TYPES_H -#include -#endif -#ifdef HAVE_TIME_H -#include -#endif - - - typedef time_t ac__type_sizeof_; -int -main () -{ -static int test_array [1 - 2 * !(((long int) (sizeof (ac__type_sizeof_))) < 0)]; -test_array [0] = 0 - - ; - return 0; -} -_ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - ac_hi=-1 ac_mid=-1 - while :; do - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ - -#ifdef HAVE_SYS_TYPES_H -#include -#endif -#ifdef HAVE_TIME_H -#include -#endif - - - typedef time_t ac__type_sizeof_; -int -main () -{ -static int test_array [1 - 2 * !(((long int) (sizeof (ac__type_sizeof_))) >= $ac_mid)]; -test_array [0] = 0 - - ; - return 0; -} -_ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - ac_lo=$ac_mid; break -else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - ac_hi=`expr '(' $ac_mid ')' - 1` - if test $ac_mid -le $ac_hi; then - ac_lo= ac_hi= - break - fi - ac_mid=`expr 2 '*' $ac_mid` -fi - -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext - done -else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - ac_lo= ac_hi= -fi - -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext -fi - -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext -# Binary search between lo and hi bounds. -while test "x$ac_lo" != "x$ac_hi"; do - ac_mid=`expr '(' $ac_hi - $ac_lo ')' / 2 + $ac_lo` - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ - -#ifdef HAVE_SYS_TYPES_H -#include -#endif -#ifdef HAVE_TIME_H -#include -#endif - - - typedef time_t ac__type_sizeof_; -int -main () -{ -static int test_array [1 - 2 * !(((long int) (sizeof (ac__type_sizeof_))) <= $ac_mid)]; -test_array [0] = 0 - - ; - return 0; -} -_ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - ac_hi=$ac_mid -else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - ac_lo=`expr '(' $ac_mid ')' + 1` -fi - -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext -done -case $ac_lo in -?*) ac_cv_sizeof_time_t=$ac_lo;; -'') if test "$ac_cv_type_time_t" = yes; then - { { echo "$as_me:$LINENO: error: cannot compute sizeof (time_t) -See \`config.log' for more details." >&5 -echo "$as_me: error: cannot compute sizeof (time_t) -See \`config.log' for more details." >&2;} - { (exit 77); exit 77; }; } - else - ac_cv_sizeof_time_t=0 - fi ;; -esac -else - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ - -#ifdef HAVE_SYS_TYPES_H -#include -#endif -#ifdef HAVE_TIME_H -#include -#endif - - - typedef time_t ac__type_sizeof_; -static long int longval () { return (long int) (sizeof (ac__type_sizeof_)); } -static unsigned long int ulongval () { return (long int) (sizeof (ac__type_sizeof_)); } -#include -#include -int -main () -{ - - FILE *f = fopen ("conftest.val", "w"); - if (! f) - return 1; - if (((long int) (sizeof (ac__type_sizeof_))) < 0) - { - long int i = longval (); - if (i != ((long int) (sizeof (ac__type_sizeof_)))) - return 1; - fprintf (f, "%ld\n", i); - } - else - { - unsigned long int i = ulongval (); - if (i != ((long int) (sizeof (ac__type_sizeof_)))) - return 1; - fprintf (f, "%lu\n", i); - } - return ferror (f) || fclose (f) != 0; - - ; - return 0; -} -_ACEOF -rm -f conftest$ac_exeext -if { (ac_try="$ac_link" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_link") 2>&5 - ac_status=$? - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { ac_try='./conftest$ac_exeext' - { (case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_try") 2>&5 - ac_status=$? - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); }; }; then - ac_cv_sizeof_time_t=`cat conftest.val` -else - echo "$as_me: program exited with status $ac_status" >&5 -echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - -( exit $ac_status ) -if test "$ac_cv_type_time_t" = yes; then - { { echo "$as_me:$LINENO: error: cannot compute sizeof (time_t) -See \`config.log' for more details." >&5 -echo "$as_me: error: cannot compute sizeof (time_t) -See \`config.log' for more details." >&2;} - { (exit 77); exit 77; }; } - else - ac_cv_sizeof_time_t=0 - fi -fi -rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext conftest.$ac_objext conftest.$ac_ext -fi -rm -f conftest.val -fi -{ echo "$as_me:$LINENO: result: $ac_cv_sizeof_time_t" >&5 -echo "${ECHO_T}$ac_cv_sizeof_time_t" >&6; } - - - -cat >>confdefs.h <<_ACEOF -#define SIZEOF_TIME_T $ac_cv_sizeof_time_t -_ACEOF - - - -# if have pthread_t then define SIZEOF_PTHREAD_T -ac_save_cc="$CC" -if test "$ac_cv_kpthread" = "yes" -then CC="$CC -Kpthread" -elif test "$ac_cv_kthread" = "yes" -then CC="$CC -Kthread" -elif test "$ac_cv_pthread" = "yes" -then CC="$CC -pthread" -fi -{ echo "$as_me:$LINENO: checking for pthread_t" >&5 -echo $ECHO_N "checking for pthread_t... $ECHO_C" >&6; } -have_pthread_t=no -cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -#include -int -main () -{ -pthread_t x; x = *(pthread_t*)0; - ; - return 0; -} -_ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - have_pthread_t=yes -else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - -fi - -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext -{ echo "$as_me:$LINENO: result: $have_pthread_t" >&5 -echo "${ECHO_T}$have_pthread_t" >&6; } -if test "$have_pthread_t" = yes ; then - { echo "$as_me:$LINENO: checking for pthread_t" >&5 -echo $ECHO_N "checking for pthread_t... $ECHO_C" >&6; } -if test "${ac_cv_type_pthread_t+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 -else - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ - -#ifdef HAVE_PTHREAD_H -#include -#endif - - -typedef pthread_t ac__type_new_; -int -main () -{ -if ((ac__type_new_ *) 0) - return 0; -if (sizeof (ac__type_new_)) - return 0; - ; - return 0; -} -_ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - ac_cv_type_pthread_t=yes -else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - ac_cv_type_pthread_t=no -fi - -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext -fi -{ echo "$as_me:$LINENO: result: $ac_cv_type_pthread_t" >&5 -echo "${ECHO_T}$ac_cv_type_pthread_t" >&6; } - -# The cast to long int works around a bug in the HP C Compiler -# version HP92453-01 B.11.11.23709.GP, which incorrectly rejects -# declarations like `int a3[[(sizeof (unsigned char)) >= 0]];'. -# This bug is HP SR number 8606223364. -{ echo "$as_me:$LINENO: checking size of pthread_t" >&5 -echo $ECHO_N "checking size of pthread_t... $ECHO_C" >&6; } -if test "${ac_cv_sizeof_pthread_t+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 -else - if test "$cross_compiling" = yes; then - # Depending upon the size, compute the lo and hi bounds. -cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ - -#ifdef HAVE_PTHREAD_H -#include -#endif - - - typedef pthread_t ac__type_sizeof_; -int -main () -{ -static int test_array [1 - 2 * !(((long int) (sizeof (ac__type_sizeof_))) >= 0)]; -test_array [0] = 0 - - ; - return 0; -} -_ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - ac_lo=0 ac_mid=0 - while :; do - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ - -#ifdef HAVE_PTHREAD_H -#include -#endif - - - typedef pthread_t ac__type_sizeof_; -int -main () -{ -static int test_array [1 - 2 * !(((long int) (sizeof (ac__type_sizeof_))) <= $ac_mid)]; -test_array [0] = 0 - - ; - return 0; -} -_ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - ac_hi=$ac_mid; break -else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - ac_lo=`expr $ac_mid + 1` - if test $ac_lo -le $ac_mid; then - ac_lo= ac_hi= - break - fi - ac_mid=`expr 2 '*' $ac_mid + 1` -fi - -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext - done -else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ - -#ifdef HAVE_PTHREAD_H -#include -#endif - - - typedef pthread_t ac__type_sizeof_; -int -main () -{ -static int test_array [1 - 2 * !(((long int) (sizeof (ac__type_sizeof_))) < 0)]; -test_array [0] = 0 - - ; - return 0; -} -_ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - ac_hi=-1 ac_mid=-1 - while :; do - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ - -#ifdef HAVE_PTHREAD_H -#include -#endif - - - typedef pthread_t ac__type_sizeof_; -int -main () -{ -static int test_array [1 - 2 * !(((long int) (sizeof (ac__type_sizeof_))) >= $ac_mid)]; -test_array [0] = 0 - - ; - return 0; -} -_ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - ac_lo=$ac_mid; break -else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - ac_hi=`expr '(' $ac_mid ')' - 1` - if test $ac_mid -le $ac_hi; then - ac_lo= ac_hi= - break - fi - ac_mid=`expr 2 '*' $ac_mid` -fi - -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext - done -else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - ac_lo= ac_hi= -fi - -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext -fi - -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext -# Binary search between lo and hi bounds. -while test "x$ac_lo" != "x$ac_hi"; do - ac_mid=`expr '(' $ac_hi - $ac_lo ')' / 2 + $ac_lo` - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ - -#ifdef HAVE_PTHREAD_H -#include -#endif - - - typedef pthread_t ac__type_sizeof_; -int -main () -{ -static int test_array [1 - 2 * !(((long int) (sizeof (ac__type_sizeof_))) <= $ac_mid)]; -test_array [0] = 0 - - ; - return 0; -} -_ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - ac_hi=$ac_mid -else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - ac_lo=`expr '(' $ac_mid ')' + 1` -fi - -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext -done -case $ac_lo in -?*) ac_cv_sizeof_pthread_t=$ac_lo;; -'') if test "$ac_cv_type_pthread_t" = yes; then - { { echo "$as_me:$LINENO: error: cannot compute sizeof (pthread_t) -See \`config.log' for more details." >&5 -echo "$as_me: error: cannot compute sizeof (pthread_t) -See \`config.log' for more details." >&2;} - { (exit 77); exit 77; }; } - else - ac_cv_sizeof_pthread_t=0 - fi ;; -esac -else - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ - -#ifdef HAVE_PTHREAD_H -#include -#endif - - - typedef pthread_t ac__type_sizeof_; -static long int longval () { return (long int) (sizeof (ac__type_sizeof_)); } -static unsigned long int ulongval () { return (long int) (sizeof (ac__type_sizeof_)); } -#include -#include -int -main () -{ - - FILE *f = fopen ("conftest.val", "w"); - if (! f) - return 1; - if (((long int) (sizeof (ac__type_sizeof_))) < 0) - { - long int i = longval (); - if (i != ((long int) (sizeof (ac__type_sizeof_)))) - return 1; - fprintf (f, "%ld\n", i); - } - else - { - unsigned long int i = ulongval (); - if (i != ((long int) (sizeof (ac__type_sizeof_)))) - return 1; - fprintf (f, "%lu\n", i); - } - return ferror (f) || fclose (f) != 0; - - ; - return 0; -} -_ACEOF -rm -f conftest$ac_exeext -if { (ac_try="$ac_link" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_link") 2>&5 - ac_status=$? - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { ac_try='./conftest$ac_exeext' - { (case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_try") 2>&5 - ac_status=$? - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); }; }; then - ac_cv_sizeof_pthread_t=`cat conftest.val` -else - echo "$as_me: program exited with status $ac_status" >&5 -echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - -( exit $ac_status ) -if test "$ac_cv_type_pthread_t" = yes; then - { { echo "$as_me:$LINENO: error: cannot compute sizeof (pthread_t) -See \`config.log' for more details." >&5 -echo "$as_me: error: cannot compute sizeof (pthread_t) -See \`config.log' for more details." >&2;} - { (exit 77); exit 77; }; } - else - ac_cv_sizeof_pthread_t=0 - fi -fi -rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext conftest.$ac_objext conftest.$ac_ext -fi -rm -f conftest.val -fi -{ echo "$as_me:$LINENO: result: $ac_cv_sizeof_pthread_t" >&5 -echo "${ECHO_T}$ac_cv_sizeof_pthread_t" >&6; } - - - -cat >>confdefs.h <<_ACEOF -#define SIZEOF_PTHREAD_T $ac_cv_sizeof_pthread_t -_ACEOF - - -fi -CC="$ac_save_cc" - -{ echo "$as_me:$LINENO: checking for --enable-toolbox-glue" >&5 -echo $ECHO_N "checking for --enable-toolbox-glue... $ECHO_C" >&6; } -# Check whether --enable-toolbox-glue was given. -if test "${enable_toolbox_glue+set}" = set; then - enableval=$enable_toolbox_glue; -fi - - -if test -z "$enable_toolbox_glue" -then - case $ac_sys_system/$ac_sys_release in - Darwin/*) - enable_toolbox_glue="yes";; - *) - enable_toolbox_glue="no";; - esac -fi -case "$enable_toolbox_glue" in -yes) - extra_machdep_objs="Python/mactoolboxglue.o" - extra_undefs="-u _PyMac_Error" - -cat >>confdefs.h <<\_ACEOF -#define USE_TOOLBOX_OBJECT_GLUE 1 -_ACEOF - - ;; -*) - extra_machdep_objs="" - extra_undefs="" - ;; -esac -{ echo "$as_me:$LINENO: result: $enable_toolbox_glue" >&5 -echo "${ECHO_T}$enable_toolbox_glue" >&6; } - - - -case $ac_sys_system/$ac_sys_release in - Darwin/[01567]\..*) - OTHER_LIBTOOL_OPT="-prebind -seg1addr 0x10000000" - ;; - Darwin/*) - OTHER_LIBTOOL_OPT="" - ;; -esac - - -ARCH_RUN_32BIT="" - -case $ac_sys_system/$ac_sys_release in - Darwin/[01567]\..*) - LIBTOOL_CRUFT="-framework System -lcc_dynamic" - if test "${enable_universalsdk}"; then - : - else - LIBTOOL_CRUFT="${LIBTOOL_CRUFT} -arch_only `/usr/bin/arch`" - fi - LIBTOOL_CRUFT=$LIBTOOL_CRUFT' -install_name $(PYTHONFRAMEWORKINSTALLDIR)/Versions/$(VERSION)/$(PYTHONFRAMEWORK)' - LIBTOOL_CRUFT=$LIBTOOL_CRUFT' -compatibility_version $(VERSION) -current_version $(VERSION)';; - Darwin/*) - gcc_version=`gcc -dumpversion` - if test ${gcc_version} '<' 4.0 - then - LIBTOOL_CRUFT="-lcc_dynamic" - else - LIBTOOL_CRUFT="" - fi - if test "$cross_compiling" = yes; then - ac_osx_32bit=yes -else - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ - - #include - int main(int argc, char*argv[]) - { - if (sizeof(long) == 4) { - return 0; - } else { - return 1; - } - } - -_ACEOF -rm -f conftest$ac_exeext -if { (ac_try="$ac_link" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_link") 2>&5 - ac_status=$? - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { ac_try='./conftest$ac_exeext' - { (case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_try") 2>&5 - ac_status=$? - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); }; }; then - ac_osx_32bit=yes -else - echo "$as_me: program exited with status $ac_status" >&5 -echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - -( exit $ac_status ) -ac_osx_32bit=no -fi -rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext conftest.$ac_objext conftest.$ac_ext -fi - - - - if test "${ac_osx_32bit}" = "yes"; then - case `/usr/bin/arch` in - i386) - MACOSX_DEFAULT_ARCH="i386" - ;; - ppc) - MACOSX_DEFAULT_ARCH="ppc" - ;; - *) - { { echo "$as_me:$LINENO: error: Unexpected output of 'arch' on OSX" >&5 -echo "$as_me: error: Unexpected output of 'arch' on OSX" >&2;} - { (exit 1); exit 1; }; } - ;; - esac - else - case `/usr/bin/arch` in - i386) - MACOSX_DEFAULT_ARCH="x86_64" - ;; - ppc) - MACOSX_DEFAULT_ARCH="ppc64" - ;; - *) - { { echo "$as_me:$LINENO: error: Unexpected output of 'arch' on OSX" >&5 -echo "$as_me: error: Unexpected output of 'arch' on OSX" >&2;} - { (exit 1); exit 1; }; } - ;; - esac - - #ARCH_RUN_32BIT="true" - fi - - LIBTOOL_CRUFT=$LIBTOOL_CRUFT" -lSystem -lSystemStubs -arch_only ${MACOSX_DEFAULT_ARCH}" - LIBTOOL_CRUFT=$LIBTOOL_CRUFT' -install_name $(PYTHONFRAMEWORKINSTALLDIR)/Versions/$(VERSION)/$(PYTHONFRAMEWORK)' - LIBTOOL_CRUFT=$LIBTOOL_CRUFT' -compatibility_version $(VERSION) -current_version $(VERSION)';; -esac - -{ echo "$as_me:$LINENO: checking for --enable-framework" >&5 -echo $ECHO_N "checking for --enable-framework... $ECHO_C" >&6; } -if test "$enable_framework" -then - BASECFLAGS="$BASECFLAGS -fno-common -dynamic" - # -F. is needed to allow linking to the framework while - # in the build location. - -cat >>confdefs.h <<\_ACEOF -#define WITH_NEXT_FRAMEWORK 1 -_ACEOF - - { echo "$as_me:$LINENO: result: yes" >&5 -echo "${ECHO_T}yes" >&6; } - if test $enable_shared = "yes" - then - { { echo "$as_me:$LINENO: error: Specifying both --enable-shared and --enable-framework is not supported, use only --enable-framework instead. See Mac/README." >&5 -echo "$as_me: error: Specifying both --enable-shared and --enable-framework is not supported, use only --enable-framework instead. See Mac/README." >&2;} - { (exit 1); exit 1; }; } - fi -else - { echo "$as_me:$LINENO: result: no" >&5 -echo "${ECHO_T}no" >&6; } -fi - -{ echo "$as_me:$LINENO: checking for dyld" >&5 -echo $ECHO_N "checking for dyld... $ECHO_C" >&6; } -case $ac_sys_system/$ac_sys_release in - Darwin/*) - -cat >>confdefs.h <<\_ACEOF -#define WITH_DYLD 1 -_ACEOF - - { echo "$as_me:$LINENO: result: always on for Darwin" >&5 -echo "${ECHO_T}always on for Darwin" >&6; } - ;; - *) - { echo "$as_me:$LINENO: result: no" >&5 -echo "${ECHO_T}no" >&6; } - ;; -esac - -# Set info about shared libraries. - - - - - - -# SO is the extension of shared libraries `(including the dot!) -# -- usually .so, .sl on HP-UX, .dll on Cygwin -{ echo "$as_me:$LINENO: checking SO" >&5 -echo $ECHO_N "checking SO... $ECHO_C" >&6; } -if test -z "$SO" -then - case $ac_sys_system in - hp*|HP*) - case `uname -m` in - ia64) SO=.so;; - *) SO=.sl;; - esac - ;; - CYGWIN*) SO=.dll;; - *) SO=.so;; - esac -else - # this might also be a termcap variable, see #610332 - echo - echo '=====================================================================' - echo '+ +' - echo '+ WARNING: You have set SO in your environment. +' - echo '+ Do you really mean to change the extension for shared libraries? +' - echo '+ Continuing in 10 seconds to let you to ponder. +' - echo '+ +' - echo '=====================================================================' - sleep 10 -fi -{ echo "$as_me:$LINENO: result: $SO" >&5 -echo "${ECHO_T}$SO" >&6; } - - -cat >>confdefs.h <<_ACEOF -#define SHLIB_EXT "$SO" -_ACEOF - -# LDSHARED is the ld *command* used to create shared library -# -- "cc -G" on SunOS 5.x, "ld -shared" on IRIX 5 -# (Shared libraries in this instance are shared modules to be loaded into -# Python, as opposed to building Python itself as a shared library.) -{ echo "$as_me:$LINENO: checking LDSHARED" >&5 -echo $ECHO_N "checking LDSHARED... $ECHO_C" >&6; } -if test -z "$LDSHARED" -then - case $ac_sys_system/$ac_sys_release in - AIX*) - BLDSHARED="\$(srcdir)/Modules/ld_so_aix \$(CC) -bI:Modules/python.exp" - LDSHARED="\$(BINLIBDEST)/config/ld_so_aix \$(CC) -bI:\$(BINLIBDEST)/config/python.exp" - ;; - BeOS*) - BLDSHARED="\$(srcdir)/Modules/ld_so_beos $LDLIBRARY" - LDSHARED="\$(BINLIBDEST)/config/ld_so_beos \$(LIBDIR)/$LDLIBRARY" - ;; - IRIX/5*) LDSHARED="ld -shared";; - IRIX*/6*) LDSHARED="ld ${SGI_ABI} -shared -all";; - SunOS/5*) - if test "$GCC" = "yes" ; then - LDSHARED='$(CC) -shared' - LDCXXSHARED='$(CXX) -shared' - else - LDSHARED='$(CC) -G' - LDCXXSHARED='$(CXX) -G' - fi ;; - hp*|HP*) - if test "$GCC" = "yes" ; then - LDSHARED='$(CC) -shared' - LDCXXSHARED='$(CXX) -shared' - else - LDSHARED='ld -b' - fi ;; - OSF*) LDSHARED="ld -shared -expect_unresolved \"*\"";; - Darwin/1.3*) - LDSHARED='$(CC) $(LDFLAGS) -bundle' - LDCXXSHARED='$(CXX) $(LDFLAGS) -bundle' - if test "$enable_framework" ; then - # Link against the framework. All externals should be defined. - BLDSHARED="$LDSHARED "'$(PYTHONFRAMEWORKDIR)/Versions/$(VERSION)/$(PYTHONFRAMEWORK)' - LDSHARED="$LDSHARED "'$(PYTHONFRAMEWORKPREFIX)/$(PYTHONFRAMEWORKDIR)/Versions/$(VERSION)/$(PYTHONFRAMEWORK)' - LDCXXSHARED="$LDCXXSHARED "'$(PYTHONFRAMEWORKPREFIX)/$(PYTHONFRAMEWORKDIR)/Versions/$(VERSION)/$(PYTHONFRAMEWORK)' - else - # No framework. Ignore undefined symbols, assuming they come from Python - LDSHARED="$LDSHARED -undefined suppress" - LDCXXSHARED="$LDCXXSHARED -undefined suppress" - fi ;; - Darwin/1.4*|Darwin/5.*|Darwin/6.*) - LDSHARED='$(CC) $(LDFLAGS) -bundle' - LDCXXSHARED='$(CXX) $(LDFLAGS) -bundle' - if test "$enable_framework" ; then - # Link against the framework. All externals should be defined. - BLDSHARED="$LDSHARED "'$(PYTHONFRAMEWORKDIR)/Versions/$(VERSION)/$(PYTHONFRAMEWORK)' - LDSHARED="$LDSHARED "'$(PYTHONFRAMEWORKPREFIX)/$(PYTHONFRAMEWORKDIR)/Versions/$(VERSION)/$(PYTHONFRAMEWORK)' - LDCXXSHARED="$LDCXXSHARED "'$(PYTHONFRAMEWORKPREFIX)/$(PYTHONFRAMEWORKDIR)/Versions/$(VERSION)/$(PYTHONFRAMEWORK)' - else - # No framework, use the Python app as bundle-loader - BLDSHARED="$LDSHARED "'-bundle_loader $(BUILDPYTHON)' - LDSHARED="$LDSHARED "'-bundle_loader $(BINDIR)/python$(VERSION)$(EXE)' - LDCXXSHARED="$LDCXXSHARED "'-bundle_loader $(BINDIR)/python$(VERSION)$(EXE)' - fi ;; - Darwin/*) - # Use -undefined dynamic_lookup whenever possible (10.3 and later). - # This allows an extension to be used in any Python - - if test ${MACOSX_DEPLOYMENT_TARGET} '>' 10.2 - then - if test "${enable_universalsdk}"; then - LDFLAGS="${UNIVERSAL_ARCH_FLAGS} -isysroot ${UNIVERSALSDK} ${LDFLAGS}" - fi - LDSHARED='$(CC) $(LDFLAGS) -bundle -undefined dynamic_lookup' - LDCXXSHARED='$(CXX) $(LDFLAGS) -bundle -undefined dynamic_lookup' - BLDSHARED="$LDSHARED" - else - LDSHARED='$(CC) $(LDFLAGS) -bundle' - LDCXXSHARED='$(CXX) $(LDFLAGS) -bundle' - if test "$enable_framework" ; then - # Link against the framework. All externals should be defined. - BLDSHARED="$LDSHARED "'$(PYTHONFRAMEWORKDIR)/Versions/$(VERSION)/$(PYTHONFRAMEWORK)' - LDSHARED="$LDSHARED "'$(PYTHONFRAMEWORKPREFIX)/$(PYTHONFRAMEWORKDIR)/Versions/$(VERSION)/$(PYTHONFRAMEWORK)' - LDCXXSHARED="$LDCXXSHARED "'$(PYTHONFRAMEWORKPREFIX)/$(PYTHONFRAMEWORKDIR)/Versions/$(VERSION)/$(PYTHONFRAMEWORK)' - else - # No framework, use the Python app as bundle-loader - BLDSHARED="$LDSHARED "'-bundle_loader $(BUILDPYTHON)' - LDSHARED="$LDSHARED "'-bundle_loader $(BINDIR)/python$(VERSION)$(EXE)' - LDCXXSHARED="$LDCXXSHARED "'-bundle_loader $(BINDIR)/python$(VERSION)$(EXE)' - fi - fi - ;; - Linux*|GNU*|QNX*) - LDSHARED='$(CC) -shared' - LDCXXSHARED='$(CXX) -shared';; - BSD/OS*/4*) - LDSHARED="gcc -shared" - LDCXXSHARED="g++ -shared";; - FreeBSD*) - if [ "`$CC -dM -E - &5 -echo "${ECHO_T}$LDSHARED" >&6; } -LDCXXSHARED=${LDCXXSHARED-$LDSHARED} -BLDSHARED=${BLDSHARED-$LDSHARED} -# CCSHARED are the C *flags* used to create objects to go into a shared -# library (module) -- this is only needed for a few systems -{ echo "$as_me:$LINENO: checking CCSHARED" >&5 -echo $ECHO_N "checking CCSHARED... $ECHO_C" >&6; } -if test -z "$CCSHARED" -then - case $ac_sys_system/$ac_sys_release in - SunOS*) if test "$GCC" = yes; - then CCSHARED="-fPIC"; - elif test `uname -p` = sparc; - then CCSHARED="-xcode=pic32"; - else CCSHARED="-Kpic"; - fi;; - hp*|HP*) if test "$GCC" = yes; - then CCSHARED="-fPIC"; - else CCSHARED="+z"; - fi;; - Linux*|GNU*) CCSHARED="-fPIC";; - BSD/OS*/4*) CCSHARED="-fpic";; - FreeBSD*|NetBSD*|OpenBSD*|DragonFly*) CCSHARED="-fPIC";; - OpenUNIX*|UnixWare*) - if test "$GCC" = "yes" - then CCSHARED="-fPIC" - else CCSHARED="-KPIC" - fi;; - SCO_SV*) - if test "$GCC" = "yes" - then CCSHARED="-fPIC" - else CCSHARED="-Kpic -belf" - fi;; - IRIX*/6*) case $CC in - *gcc*) CCSHARED="-shared";; - *) CCSHARED="";; - esac;; - atheos*) CCSHARED="-fPIC";; - esac -fi -{ echo "$as_me:$LINENO: result: $CCSHARED" >&5 -echo "${ECHO_T}$CCSHARED" >&6; } -# LINKFORSHARED are the flags passed to the $(CC) command that links -# the python executable -- this is only needed for a few systems -{ echo "$as_me:$LINENO: checking LINKFORSHARED" >&5 -echo $ECHO_N "checking LINKFORSHARED... $ECHO_C" >&6; } -if test -z "$LINKFORSHARED" -then - case $ac_sys_system/$ac_sys_release in - AIX*) LINKFORSHARED='-Wl,-bE:Modules/python.exp -lld';; - hp*|HP*) - 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";; - # -u libsys_s pulls in all symbols in libsys - Darwin/*) - # -u _PyMac_Error is needed to pull in the mac toolbox glue, - # which is - # not used by the core itself but which needs to be in the core so - # that dynamically loaded extension modules have access to it. - # -prebind is no longer used, because it actually seems to give a - # slowdown in stead of a speedup, maybe due to the large number of - # dynamic loads Python does. - - LINKFORSHARED="$extra_undefs" - if test "$enable_framework" - then - LINKFORSHARED="$LINKFORSHARED "'$(PYTHONFRAMEWORKDIR)/Versions/$(VERSION)/$(PYTHONFRAMEWORK)' - fi - LINKFORSHARED="$LINKFORSHARED";; - OpenUNIX*|UnixWare*) LINKFORSHARED="-Wl,-Bexport";; - SCO_SV*) LINKFORSHARED="-Wl,-Bexport";; - ReliantUNIX*) LINKFORSHARED="-W1 -Blargedynsym";; - FreeBSD*|NetBSD*|OpenBSD*|DragonFly*) - if [ "`$CC -dM -E - &1 | grep export-dynamic >/dev/null - then - LINKFORSHARED="-Xlinker --export-dynamic" - fi;; - esac;; - CYGWIN*) - if test $enable_shared = "no" - then - LINKFORSHARED='-Wl,--out-implib=$(LDLIBRARY)' - fi;; - QNX*) - # -Wl,-E causes the symbols to be added to the dynamic - # symbol table so that they can be found when a module - # is loaded. -N 2048K causes the stack size to be set - # to 2048 kilobytes so that the stack doesn't overflow - # when running test_compile.py. - LINKFORSHARED='-Wl,-E -N 2048K';; - esac -fi -{ echo "$as_me:$LINENO: result: $LINKFORSHARED" >&5 -echo "${ECHO_T}$LINKFORSHARED" >&6; } - - - -{ echo "$as_me:$LINENO: checking CFLAGSFORSHARED" >&5 -echo $ECHO_N "checking CFLAGSFORSHARED... $ECHO_C" >&6; } -if test ! "$LIBRARY" = "$LDLIBRARY" -then - case $ac_sys_system in - CYGWIN*) - # Cygwin needs CCSHARED when building extension DLLs - # but not when building the interpreter DLL. - CFLAGSFORSHARED='';; - *) - CFLAGSFORSHARED='$(CCSHARED)' - esac -fi -{ echo "$as_me:$LINENO: result: $CFLAGSFORSHARED" >&5 -echo "${ECHO_T}$CFLAGSFORSHARED" >&6; } - -# SHLIBS are libraries (except -lc and -lm) to link to the python shared -# library (with --enable-shared). -# For platforms on which shared libraries are not allowed to have unresolved -# symbols, this must be set to $(LIBS) (expanded by make). We do this even -# if it is not required, since it creates a dependency of the shared library -# to LIBS. This, in turn, means that applications linking the shared libpython -# don't need to link LIBS explicitly. The default should be only changed -# on systems where this approach causes problems. - -{ echo "$as_me:$LINENO: checking SHLIBS" >&5 -echo $ECHO_N "checking SHLIBS... $ECHO_C" >&6; } -case "$ac_sys_system" in - *) - SHLIBS='$(LIBS)';; -esac -{ echo "$as_me:$LINENO: result: $SHLIBS" >&5 -echo "${ECHO_T}$SHLIBS" >&6; } - - -# checks for libraries - -{ echo "$as_me:$LINENO: checking for dlopen in -ldl" >&5 -echo $ECHO_N "checking for dlopen in -ldl... $ECHO_C" >&6; } -if test "${ac_cv_lib_dl_dlopen+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 -else - ac_check_lib_save_LIBS=$LIBS -LIBS="-ldl $LIBS" -cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ - -/* Override any GCC internal prototype to avoid an error. - Use char because int might match the return type of a GCC - builtin and then its argument prototype would still apply. */ -#ifdef __cplusplus -extern "C" -#endif -char dlopen (); -int -main () -{ -return dlopen (); - ; - return 0; -} -_ACEOF -rm -f conftest.$ac_objext conftest$ac_exeext -if { (ac_try="$ac_link" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_link") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest$ac_exeext && - $as_test_x conftest$ac_exeext; then - ac_cv_lib_dl_dlopen=yes -else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - ac_cv_lib_dl_dlopen=no -fi - -rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \ - conftest$ac_exeext conftest.$ac_ext -LIBS=$ac_check_lib_save_LIBS -fi -{ echo "$as_me:$LINENO: result: $ac_cv_lib_dl_dlopen" >&5 -echo "${ECHO_T}$ac_cv_lib_dl_dlopen" >&6; } -if test $ac_cv_lib_dl_dlopen = yes; then - cat >>confdefs.h <<_ACEOF -#define HAVE_LIBDL 1 -_ACEOF - - LIBS="-ldl $LIBS" - -fi - # Dynamic linking for SunOS/Solaris and SYSV - -{ echo "$as_me:$LINENO: checking for shl_load in -ldld" >&5 -echo $ECHO_N "checking for shl_load in -ldld... $ECHO_C" >&6; } -if test "${ac_cv_lib_dld_shl_load+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 -else - ac_check_lib_save_LIBS=$LIBS -LIBS="-ldld $LIBS" -cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ - -/* Override any GCC internal prototype to avoid an error. - Use char because int might match the return type of a GCC - builtin and then its argument prototype would still apply. */ -#ifdef __cplusplus -extern "C" -#endif -char shl_load (); -int -main () -{ -return shl_load (); - ; - return 0; -} -_ACEOF -rm -f conftest.$ac_objext conftest$ac_exeext -if { (ac_try="$ac_link" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_link") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest$ac_exeext && - $as_test_x conftest$ac_exeext; then - ac_cv_lib_dld_shl_load=yes -else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - ac_cv_lib_dld_shl_load=no -fi - -rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \ - conftest$ac_exeext conftest.$ac_ext -LIBS=$ac_check_lib_save_LIBS -fi -{ echo "$as_me:$LINENO: result: $ac_cv_lib_dld_shl_load" >&5 -echo "${ECHO_T}$ac_cv_lib_dld_shl_load" >&6; } -if test $ac_cv_lib_dld_shl_load = yes; then - cat >>confdefs.h <<_ACEOF -#define HAVE_LIBDLD 1 -_ACEOF - - LIBS="-ldld $LIBS" - -fi - # Dynamic linking for HP-UX - -# only check for sem_init if thread support is requested -if test "$with_threads" = "yes" -o -z "$with_threads"; then - { echo "$as_me:$LINENO: checking for library containing sem_init" >&5 -echo $ECHO_N "checking for library containing sem_init... $ECHO_C" >&6; } -if test "${ac_cv_search_sem_init+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 -else - ac_func_search_save_LIBS=$LIBS -cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ - -/* Override any GCC internal prototype to avoid an error. - Use char because int might match the return type of a GCC - builtin and then its argument prototype would still apply. */ -#ifdef __cplusplus -extern "C" -#endif -char sem_init (); -int -main () -{ -return sem_init (); - ; - return 0; -} -_ACEOF -for ac_lib in '' pthread rt posix4; do - if test -z "$ac_lib"; then - ac_res="none required" - else - ac_res=-l$ac_lib - LIBS="-l$ac_lib $ac_func_search_save_LIBS" - fi - rm -f conftest.$ac_objext conftest$ac_exeext -if { (ac_try="$ac_link" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_link") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest$ac_exeext && - $as_test_x conftest$ac_exeext; then - ac_cv_search_sem_init=$ac_res -else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - -fi - -rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \ - conftest$ac_exeext - if test "${ac_cv_search_sem_init+set}" = set; then - break -fi -done -if test "${ac_cv_search_sem_init+set}" = set; then - : -else - ac_cv_search_sem_init=no -fi -rm conftest.$ac_ext -LIBS=$ac_func_search_save_LIBS -fi -{ echo "$as_me:$LINENO: result: $ac_cv_search_sem_init" >&5 -echo "${ECHO_T}$ac_cv_search_sem_init" >&6; } -ac_res=$ac_cv_search_sem_init -if test "$ac_res" != no; then - test "$ac_res" = "none required" || LIBS="$ac_res $LIBS" - -fi - # 'Real Time' functions on Solaris - # posix4 on Solaris 2.6 - # pthread (first!) on Linux -fi - -# check if we need libintl for locale functions -{ echo "$as_me:$LINENO: checking for textdomain in -lintl" >&5 -echo $ECHO_N "checking for textdomain in -lintl... $ECHO_C" >&6; } -if test "${ac_cv_lib_intl_textdomain+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 -else - ac_check_lib_save_LIBS=$LIBS -LIBS="-lintl $LIBS" -cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ - -/* Override any GCC internal prototype to avoid an error. - Use char because int might match the return type of a GCC - builtin and then its argument prototype would still apply. */ -#ifdef __cplusplus -extern "C" -#endif -char textdomain (); -int -main () -{ -return textdomain (); - ; - return 0; -} -_ACEOF -rm -f conftest.$ac_objext conftest$ac_exeext -if { (ac_try="$ac_link" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_link") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest$ac_exeext && - $as_test_x conftest$ac_exeext; then - ac_cv_lib_intl_textdomain=yes -else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - ac_cv_lib_intl_textdomain=no -fi - -rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \ - conftest$ac_exeext conftest.$ac_ext -LIBS=$ac_check_lib_save_LIBS -fi -{ echo "$as_me:$LINENO: result: $ac_cv_lib_intl_textdomain" >&5 -echo "${ECHO_T}$ac_cv_lib_intl_textdomain" >&6; } -if test $ac_cv_lib_intl_textdomain = yes; then - -cat >>confdefs.h <<\_ACEOF -#define WITH_LIBINTL 1 -_ACEOF - -fi - - -# checks for system dependent C++ extensions support -case "$ac_sys_system" in - AIX*) { echo "$as_me:$LINENO: checking for genuine AIX C++ extensions support" >&5 -echo $ECHO_N "checking for genuine AIX C++ extensions support... $ECHO_C" >&6; } - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -#include "/usr/lpp/xlC/include/load.h" -int -main () -{ -loadAndInit("", 0, "") - ; - return 0; -} -_ACEOF -rm -f conftest.$ac_objext conftest$ac_exeext -if { (ac_try="$ac_link" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_link") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest$ac_exeext && - $as_test_x conftest$ac_exeext; then - -cat >>confdefs.h <<\_ACEOF -#define AIX_GENUINE_CPLUSPLUS 1 -_ACEOF - - { echo "$as_me:$LINENO: result: yes" >&5 -echo "${ECHO_T}yes" >&6; } -else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - { echo "$as_me:$LINENO: result: no" >&5 -echo "${ECHO_T}no" >&6; } -fi - -rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \ - conftest$ac_exeext conftest.$ac_ext;; - *) ;; -esac - -# Most SVR4 platforms (e.g. Solaris) need -lsocket and -lnsl. -# BeOS' sockets are stashed in libnet. -{ echo "$as_me:$LINENO: checking for t_open in -lnsl" >&5 -echo $ECHO_N "checking for t_open in -lnsl... $ECHO_C" >&6; } -if test "${ac_cv_lib_nsl_t_open+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 -else - ac_check_lib_save_LIBS=$LIBS -LIBS="-lnsl $LIBS" -cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ - -/* Override any GCC internal prototype to avoid an error. - Use char because int might match the return type of a GCC - builtin and then its argument prototype would still apply. */ -#ifdef __cplusplus -extern "C" -#endif -char t_open (); -int -main () -{ -return t_open (); - ; - return 0; -} -_ACEOF -rm -f conftest.$ac_objext conftest$ac_exeext -if { (ac_try="$ac_link" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_link") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest$ac_exeext && - $as_test_x conftest$ac_exeext; then - ac_cv_lib_nsl_t_open=yes -else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - ac_cv_lib_nsl_t_open=no -fi - -rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \ - conftest$ac_exeext conftest.$ac_ext -LIBS=$ac_check_lib_save_LIBS -fi -{ echo "$as_me:$LINENO: result: $ac_cv_lib_nsl_t_open" >&5 -echo "${ECHO_T}$ac_cv_lib_nsl_t_open" >&6; } -if test $ac_cv_lib_nsl_t_open = yes; then - LIBS="-lnsl $LIBS" -fi - # SVR4 -{ echo "$as_me:$LINENO: checking for socket in -lsocket" >&5 -echo $ECHO_N "checking for socket in -lsocket... $ECHO_C" >&6; } -if test "${ac_cv_lib_socket_socket+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 -else - ac_check_lib_save_LIBS=$LIBS -LIBS="-lsocket $LIBS $LIBS" -cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ - -/* Override any GCC internal prototype to avoid an error. - Use char because int might match the return type of a GCC - builtin and then its argument prototype would still apply. */ -#ifdef __cplusplus -extern "C" -#endif -char socket (); -int -main () -{ -return socket (); - ; - return 0; -} -_ACEOF -rm -f conftest.$ac_objext conftest$ac_exeext -if { (ac_try="$ac_link" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_link") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest$ac_exeext && - $as_test_x conftest$ac_exeext; then - ac_cv_lib_socket_socket=yes -else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - ac_cv_lib_socket_socket=no -fi - -rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \ - conftest$ac_exeext conftest.$ac_ext -LIBS=$ac_check_lib_save_LIBS -fi -{ echo "$as_me:$LINENO: result: $ac_cv_lib_socket_socket" >&5 -echo "${ECHO_T}$ac_cv_lib_socket_socket" >&6; } -if test $ac_cv_lib_socket_socket = yes; then - LIBS="-lsocket $LIBS" -fi - # SVR4 sockets - -case "$ac_sys_system" in -BeOS*) -{ echo "$as_me:$LINENO: checking for socket in -lnet" >&5 -echo $ECHO_N "checking for socket in -lnet... $ECHO_C" >&6; } -if test "${ac_cv_lib_net_socket+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 -else - ac_check_lib_save_LIBS=$LIBS -LIBS="-lnet $LIBS $LIBS" -cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ - -/* Override any GCC internal prototype to avoid an error. - Use char because int might match the return type of a GCC - builtin and then its argument prototype would still apply. */ -#ifdef __cplusplus -extern "C" -#endif -char socket (); -int -main () -{ -return socket (); - ; - return 0; -} -_ACEOF -rm -f conftest.$ac_objext conftest$ac_exeext -if { (ac_try="$ac_link" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_link") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest$ac_exeext && - $as_test_x conftest$ac_exeext; then - ac_cv_lib_net_socket=yes -else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - ac_cv_lib_net_socket=no -fi - -rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \ - conftest$ac_exeext conftest.$ac_ext -LIBS=$ac_check_lib_save_LIBS -fi -{ echo "$as_me:$LINENO: result: $ac_cv_lib_net_socket" >&5 -echo "${ECHO_T}$ac_cv_lib_net_socket" >&6; } -if test $ac_cv_lib_net_socket = yes; then - LIBS="-lnet $LIBS" -fi - # BeOS -;; -esac - -{ echo "$as_me:$LINENO: checking for --with-libs" >&5 -echo $ECHO_N "checking for --with-libs... $ECHO_C" >&6; } - -# Check whether --with-libs was given. -if test "${with_libs+set}" = set; then - withval=$with_libs; -{ echo "$as_me:$LINENO: result: $withval" >&5 -echo "${ECHO_T}$withval" >&6; } -LIBS="$withval $LIBS" - -else - { echo "$as_me:$LINENO: result: no" >&5 -echo "${ECHO_T}no" >&6; } -fi - - -if test -n "$ac_tool_prefix"; then - # Extract the first word of "${ac_tool_prefix}pkg-config", so it can be a program name with args. -set dummy ${ac_tool_prefix}pkg-config; ac_word=$2 -{ echo "$as_me:$LINENO: checking for $ac_word" >&5 -echo $ECHO_N "checking for $ac_word... $ECHO_C" >&6; } -if test "${ac_cv_path_PKG_CONFIG+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 -else - case $PKG_CONFIG in - [\\/]* | ?:[\\/]*) - ac_cv_path_PKG_CONFIG="$PKG_CONFIG" # Let the user override the test with a path. - ;; - *) - as_save_IFS=$IFS; IFS=$PATH_SEPARATOR -for as_dir in $PATH -do - IFS=$as_save_IFS - test -z "$as_dir" && as_dir=. - for ac_exec_ext in '' $ac_executable_extensions; do - if { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_test_x "$as_dir/$ac_word$ac_exec_ext"; }; then - ac_cv_path_PKG_CONFIG="$as_dir/$ac_word$ac_exec_ext" - echo "$as_me:$LINENO: found $as_dir/$ac_word$ac_exec_ext" >&5 - break 2 - fi -done -done -IFS=$as_save_IFS - - ;; -esac -fi -PKG_CONFIG=$ac_cv_path_PKG_CONFIG -if test -n "$PKG_CONFIG"; then - { echo "$as_me:$LINENO: result: $PKG_CONFIG" >&5 -echo "${ECHO_T}$PKG_CONFIG" >&6; } -else - { echo "$as_me:$LINENO: result: no" >&5 -echo "${ECHO_T}no" >&6; } -fi - - -fi -if test -z "$ac_cv_path_PKG_CONFIG"; then - ac_pt_PKG_CONFIG=$PKG_CONFIG - # Extract the first word of "pkg-config", so it can be a program name with args. -set dummy pkg-config; ac_word=$2 -{ echo "$as_me:$LINENO: checking for $ac_word" >&5 -echo $ECHO_N "checking for $ac_word... $ECHO_C" >&6; } -if test "${ac_cv_path_ac_pt_PKG_CONFIG+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 -else - case $ac_pt_PKG_CONFIG in - [\\/]* | ?:[\\/]*) - ac_cv_path_ac_pt_PKG_CONFIG="$ac_pt_PKG_CONFIG" # Let the user override the test with a path. - ;; - *) - as_save_IFS=$IFS; IFS=$PATH_SEPARATOR -for as_dir in $PATH -do - IFS=$as_save_IFS - test -z "$as_dir" && as_dir=. - for ac_exec_ext in '' $ac_executable_extensions; do - if { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_test_x "$as_dir/$ac_word$ac_exec_ext"; }; then - ac_cv_path_ac_pt_PKG_CONFIG="$as_dir/$ac_word$ac_exec_ext" - echo "$as_me:$LINENO: found $as_dir/$ac_word$ac_exec_ext" >&5 - break 2 - fi -done -done -IFS=$as_save_IFS - - ;; -esac -fi -ac_pt_PKG_CONFIG=$ac_cv_path_ac_pt_PKG_CONFIG -if test -n "$ac_pt_PKG_CONFIG"; then - { echo "$as_me:$LINENO: result: $ac_pt_PKG_CONFIG" >&5 -echo "${ECHO_T}$ac_pt_PKG_CONFIG" >&6; } -else - { echo "$as_me:$LINENO: result: no" >&5 -echo "${ECHO_T}no" >&6; } -fi - - if test "x$ac_pt_PKG_CONFIG" = x; then - PKG_CONFIG="" - else - case $cross_compiling:$ac_tool_warned in -yes:) -{ echo "$as_me:$LINENO: WARNING: In the future, Autoconf will not detect cross-tools -whose name does not start with the host triplet. If you think this -configuration is useful to you, please write to autoconf at gnu.org." >&5 -echo "$as_me: WARNING: In the future, Autoconf will not detect cross-tools -whose name does not start with the host triplet. If you think this -configuration is useful to you, please write to autoconf at gnu.org." >&2;} -ac_tool_warned=yes ;; -esac - PKG_CONFIG=$ac_pt_PKG_CONFIG - fi -else - PKG_CONFIG="$ac_cv_path_PKG_CONFIG" -fi - - -# Check for use of the system expat library -{ echo "$as_me:$LINENO: checking for --with-system-expat" >&5 -echo $ECHO_N "checking for --with-system-expat... $ECHO_C" >&6; } - -# Check whether --with-system_expat was given. -if test "${with_system_expat+set}" = set; then - withval=$with_system_expat; -fi - - -{ echo "$as_me:$LINENO: result: $with_system_expat" >&5 -echo "${ECHO_T}$with_system_expat" >&6; } - -# Check for use of the system libffi library -{ echo "$as_me:$LINENO: checking for --with-system-ffi" >&5 -echo $ECHO_N "checking for --with-system-ffi... $ECHO_C" >&6; } - -# Check whether --with-system_ffi was given. -if test "${with_system_ffi+set}" = set; then - withval=$with_system_ffi; -fi - - -if test "$with_system_ffi" = "yes" && test -n "$PKG_CONFIG"; then - LIBFFI_INCLUDEDIR="`"$PKG_CONFIG" libffi --cflags-only-I 2>/dev/null | sed -e 's/^-I//;s/ *$//'`" -else - LIBFFI_INCLUDEDIR="" -fi - - -{ echo "$as_me:$LINENO: result: $with_system_ffi" >&5 -echo "${ECHO_T}$with_system_ffi" >&6; } - -# Check for --with-dbmliborder -{ echo "$as_me:$LINENO: checking for --with-dbmliborder" >&5 -echo $ECHO_N "checking for --with-dbmliborder... $ECHO_C" >&6; } - -# Check whether --with-dbmliborder was given. -if test "${with_dbmliborder+set}" = set; then - withval=$with_dbmliborder; -if test x$with_dbmliborder = xyes -then -{ { echo "$as_me:$LINENO: error: proper usage is --with-dbmliborder=db1:db2:..." >&5 -echo "$as_me: error: proper usage is --with-dbmliborder=db1:db2:..." >&2;} - { (exit 1); exit 1; }; } -else - for db in `echo $with_dbmliborder | sed 's/:/ /g'`; do - if test x$db != xndbm && test x$db != xgdbm && test x$db != xbdb - then - { { echo "$as_me:$LINENO: error: proper usage is --with-dbmliborder=db1:db2:..." >&5 -echo "$as_me: error: proper usage is --with-dbmliborder=db1:db2:..." >&2;} - { (exit 1); exit 1; }; } - fi - done -fi -fi - -{ echo "$as_me:$LINENO: result: $with_dbmliborder" >&5 -echo "${ECHO_T}$with_dbmliborder" >&6; } - -# Determine if signalmodule should be used. - - -{ echo "$as_me:$LINENO: checking for --with-signal-module" >&5 -echo $ECHO_N "checking for --with-signal-module... $ECHO_C" >&6; } - -# Check whether --with-signal-module was given. -if test "${with_signal_module+set}" = set; then - withval=$with_signal_module; -fi - - -if test -z "$with_signal_module" -then with_signal_module="yes" -fi -{ echo "$as_me:$LINENO: result: $with_signal_module" >&5 -echo "${ECHO_T}$with_signal_module" >&6; } - -if test "${with_signal_module}" = "yes"; then - USE_SIGNAL_MODULE="" - SIGNAL_OBJS="" -else - USE_SIGNAL_MODULE="#" - SIGNAL_OBJS="Parser/intrcheck.o Python/sigcheck.o" -fi - -# This is used to generate Setup.config - -USE_THREAD_MODULE="" - -{ echo "$as_me:$LINENO: checking for --with-dec-threads" >&5 -echo $ECHO_N "checking for --with-dec-threads... $ECHO_C" >&6; } - - -# Check whether --with-dec-threads was given. -if test "${with_dec_threads+set}" = set; then - withval=$with_dec_threads; -{ echo "$as_me:$LINENO: result: $withval" >&5 -echo "${ECHO_T}$withval" >&6; } -LDLAST=-threads -if test "${with_thread+set}" != set; then - with_thread="$withval"; -fi -else - { echo "$as_me:$LINENO: result: no" >&5 -echo "${ECHO_T}no" >&6; } -fi - - -# Templates for things AC_DEFINEd more than once. -# For a single AC_DEFINE, no template is needed. - - - - - - - -{ echo "$as_me:$LINENO: checking for --with-threads" >&5 -echo $ECHO_N "checking for --with-threads... $ECHO_C" >&6; } - -# Check whether --with-threads was given. -if test "${with_threads+set}" = set; then - withval=$with_threads; -fi - - -# --with-thread is deprecated, but check for it anyway - -# Check whether --with-thread was given. -if test "${with_thread+set}" = set; then - withval=$with_thread; with_threads=$with_thread -fi - - -if test -z "$with_threads" -then with_threads="yes" -fi -{ echo "$as_me:$LINENO: result: $with_threads" >&5 -echo "${ECHO_T}$with_threads" >&6; } - - -if test "$with_threads" = "no" -then - USE_THREAD_MODULE="#" -elif test "$ac_cv_pthread_is_default" = yes -then - cat >>confdefs.h <<\_ACEOF -#define WITH_THREAD 1 -_ACEOF - - # Defining _REENTRANT on system with POSIX threads should not hurt. - cat >>confdefs.h <<\_ACEOF -#define _REENTRANT 1 -_ACEOF - - posix_threads=yes - THREADOBJ="Python/thread.o" -elif test "$ac_cv_kpthread" = "yes" -then - CC="$CC -Kpthread" - if test "$ac_cv_cxx_thread" = "yes"; then - CXX="$CXX -Kpthread" - fi - cat >>confdefs.h <<\_ACEOF -#define WITH_THREAD 1 -_ACEOF - - posix_threads=yes - THREADOBJ="Python/thread.o" -elif test "$ac_cv_kthread" = "yes" -then - CC="$CC -Kthread" - if test "$ac_cv_cxx_thread" = "yes"; then - CXX="$CXX -Kthread" - fi - cat >>confdefs.h <<\_ACEOF -#define WITH_THREAD 1 -_ACEOF - - posix_threads=yes - THREADOBJ="Python/thread.o" -elif test "$ac_cv_pthread" = "yes" -then - CC="$CC -pthread" - if test "$ac_cv_cxx_thread" = "yes"; then - CXX="$CXX -pthread" - fi - cat >>confdefs.h <<\_ACEOF -#define WITH_THREAD 1 -_ACEOF - - posix_threads=yes - THREADOBJ="Python/thread.o" -else - if test ! -z "$with_threads" -a -d "$with_threads" - then LDFLAGS="$LDFLAGS -L$with_threads" - fi - if test ! -z "$withval" -a -d "$withval" - then LDFLAGS="$LDFLAGS -L$withval" - fi - - # According to the POSIX spec, a pthreads implementation must - # define _POSIX_THREADS in unistd.h. Some apparently don't - # (e.g. gnu pth with pthread emulation) - { echo "$as_me:$LINENO: checking for _POSIX_THREADS in unistd.h" >&5 -echo $ECHO_N "checking for _POSIX_THREADS in unistd.h... $ECHO_C" >&6; } - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ - -#include -#ifdef _POSIX_THREADS -yes -#endif - -_ACEOF -if (eval "$ac_cpp conftest.$ac_ext") 2>&5 | - $EGREP "yes" >/dev/null 2>&1; then - unistd_defines_pthreads=yes -else - unistd_defines_pthreads=no -fi -rm -f conftest* - - { echo "$as_me:$LINENO: result: $unistd_defines_pthreads" >&5 -echo "${ECHO_T}$unistd_defines_pthreads" >&6; } - - cat >>confdefs.h <<\_ACEOF -#define _REENTRANT 1 -_ACEOF - - if test "${ac_cv_header_cthreads_h+set}" = set; then - { echo "$as_me:$LINENO: checking for cthreads.h" >&5 -echo $ECHO_N "checking for cthreads.h... $ECHO_C" >&6; } -if test "${ac_cv_header_cthreads_h+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 -fi -{ echo "$as_me:$LINENO: result: $ac_cv_header_cthreads_h" >&5 -echo "${ECHO_T}$ac_cv_header_cthreads_h" >&6; } -else - # Is the header compilable? -{ echo "$as_me:$LINENO: checking cthreads.h usability" >&5 -echo $ECHO_N "checking cthreads.h usability... $ECHO_C" >&6; } -cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -$ac_includes_default -#include -_ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - ac_header_compiler=yes -else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - ac_header_compiler=no -fi - -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext -{ echo "$as_me:$LINENO: result: $ac_header_compiler" >&5 -echo "${ECHO_T}$ac_header_compiler" >&6; } - -# Is the header present? -{ echo "$as_me:$LINENO: checking cthreads.h presence" >&5 -echo $ECHO_N "checking cthreads.h presence... $ECHO_C" >&6; } -cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -#include -_ACEOF -if { (ac_try="$ac_cpp conftest.$ac_ext" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_cpp conftest.$ac_ext") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } >/dev/null && { - test -z "$ac_c_preproc_warn_flag$ac_c_werror_flag" || - test ! -s conftest.err - }; then - ac_header_preproc=yes -else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - ac_header_preproc=no -fi - -rm -f conftest.err conftest.$ac_ext -{ echo "$as_me:$LINENO: result: $ac_header_preproc" >&5 -echo "${ECHO_T}$ac_header_preproc" >&6; } - -# So? What about this header? -case $ac_header_compiler:$ac_header_preproc:$ac_c_preproc_warn_flag in - yes:no: ) - { echo "$as_me:$LINENO: WARNING: cthreads.h: accepted by the compiler, rejected by the preprocessor!" >&5 -echo "$as_me: WARNING: cthreads.h: accepted by the compiler, rejected by the preprocessor!" >&2;} - { echo "$as_me:$LINENO: WARNING: cthreads.h: proceeding with the compiler's result" >&5 -echo "$as_me: WARNING: cthreads.h: proceeding with the compiler's result" >&2;} - ac_header_preproc=yes - ;; - no:yes:* ) - { echo "$as_me:$LINENO: WARNING: cthreads.h: present but cannot be compiled" >&5 -echo "$as_me: WARNING: cthreads.h: present but cannot be compiled" >&2;} - { echo "$as_me:$LINENO: WARNING: cthreads.h: check for missing prerequisite headers?" >&5 -echo "$as_me: WARNING: cthreads.h: check for missing prerequisite headers?" >&2;} - { echo "$as_me:$LINENO: WARNING: cthreads.h: see the Autoconf documentation" >&5 -echo "$as_me: WARNING: cthreads.h: see the Autoconf documentation" >&2;} - { echo "$as_me:$LINENO: WARNING: cthreads.h: section \"Present But Cannot Be Compiled\"" >&5 -echo "$as_me: WARNING: cthreads.h: section \"Present But Cannot Be Compiled\"" >&2;} - { echo "$as_me:$LINENO: WARNING: cthreads.h: proceeding with the preprocessor's result" >&5 -echo "$as_me: WARNING: cthreads.h: proceeding with the preprocessor's result" >&2;} - { echo "$as_me:$LINENO: WARNING: cthreads.h: in the future, the compiler will take precedence" >&5 -echo "$as_me: WARNING: cthreads.h: in the future, the compiler will take precedence" >&2;} - ( cat <<\_ASBOX -## -------------------------------------- ## -## Report this to http://bugs.python.org/ ## -## -------------------------------------- ## -_ASBOX - ) | sed "s/^/$as_me: WARNING: /" >&2 - ;; -esac -{ echo "$as_me:$LINENO: checking for cthreads.h" >&5 -echo $ECHO_N "checking for cthreads.h... $ECHO_C" >&6; } -if test "${ac_cv_header_cthreads_h+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 -else - ac_cv_header_cthreads_h=$ac_header_preproc -fi -{ echo "$as_me:$LINENO: result: $ac_cv_header_cthreads_h" >&5 -echo "${ECHO_T}$ac_cv_header_cthreads_h" >&6; } - -fi -if test $ac_cv_header_cthreads_h = yes; then - cat >>confdefs.h <<\_ACEOF -#define WITH_THREAD 1 -_ACEOF - - cat >>confdefs.h <<\_ACEOF -#define C_THREADS 1 -_ACEOF - - -cat >>confdefs.h <<\_ACEOF -#define HURD_C_THREADS 1 -_ACEOF - - LIBS="$LIBS -lthreads" - THREADOBJ="Python/thread.o" -else - - if test "${ac_cv_header_mach_cthreads_h+set}" = set; then - { echo "$as_me:$LINENO: checking for mach/cthreads.h" >&5 -echo $ECHO_N "checking for mach/cthreads.h... $ECHO_C" >&6; } -if test "${ac_cv_header_mach_cthreads_h+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 -fi -{ echo "$as_me:$LINENO: result: $ac_cv_header_mach_cthreads_h" >&5 -echo "${ECHO_T}$ac_cv_header_mach_cthreads_h" >&6; } -else - # Is the header compilable? -{ echo "$as_me:$LINENO: checking mach/cthreads.h usability" >&5 -echo $ECHO_N "checking mach/cthreads.h usability... $ECHO_C" >&6; } -cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -$ac_includes_default -#include -_ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - ac_header_compiler=yes -else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - ac_header_compiler=no -fi - -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext -{ echo "$as_me:$LINENO: result: $ac_header_compiler" >&5 -echo "${ECHO_T}$ac_header_compiler" >&6; } - -# Is the header present? -{ echo "$as_me:$LINENO: checking mach/cthreads.h presence" >&5 -echo $ECHO_N "checking mach/cthreads.h presence... $ECHO_C" >&6; } -cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -#include -_ACEOF -if { (ac_try="$ac_cpp conftest.$ac_ext" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_cpp conftest.$ac_ext") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } >/dev/null && { - test -z "$ac_c_preproc_warn_flag$ac_c_werror_flag" || - test ! -s conftest.err - }; then - ac_header_preproc=yes -else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - ac_header_preproc=no -fi - -rm -f conftest.err conftest.$ac_ext -{ echo "$as_me:$LINENO: result: $ac_header_preproc" >&5 -echo "${ECHO_T}$ac_header_preproc" >&6; } - -# So? What about this header? -case $ac_header_compiler:$ac_header_preproc:$ac_c_preproc_warn_flag in - yes:no: ) - { echo "$as_me:$LINENO: WARNING: mach/cthreads.h: accepted by the compiler, rejected by the preprocessor!" >&5 -echo "$as_me: WARNING: mach/cthreads.h: accepted by the compiler, rejected by the preprocessor!" >&2;} - { echo "$as_me:$LINENO: WARNING: mach/cthreads.h: proceeding with the compiler's result" >&5 -echo "$as_me: WARNING: mach/cthreads.h: proceeding with the compiler's result" >&2;} - ac_header_preproc=yes - ;; - no:yes:* ) - { echo "$as_me:$LINENO: WARNING: mach/cthreads.h: present but cannot be compiled" >&5 -echo "$as_me: WARNING: mach/cthreads.h: present but cannot be compiled" >&2;} - { echo "$as_me:$LINENO: WARNING: mach/cthreads.h: check for missing prerequisite headers?" >&5 -echo "$as_me: WARNING: mach/cthreads.h: check for missing prerequisite headers?" >&2;} - { echo "$as_me:$LINENO: WARNING: mach/cthreads.h: see the Autoconf documentation" >&5 -echo "$as_me: WARNING: mach/cthreads.h: see the Autoconf documentation" >&2;} - { echo "$as_me:$LINENO: WARNING: mach/cthreads.h: section \"Present But Cannot Be Compiled\"" >&5 -echo "$as_me: WARNING: mach/cthreads.h: section \"Present But Cannot Be Compiled\"" >&2;} - { echo "$as_me:$LINENO: WARNING: mach/cthreads.h: proceeding with the preprocessor's result" >&5 -echo "$as_me: WARNING: mach/cthreads.h: proceeding with the preprocessor's result" >&2;} - { echo "$as_me:$LINENO: WARNING: mach/cthreads.h: in the future, the compiler will take precedence" >&5 -echo "$as_me: WARNING: mach/cthreads.h: in the future, the compiler will take precedence" >&2;} - ( cat <<\_ASBOX -## -------------------------------------- ## -## Report this to http://bugs.python.org/ ## -## -------------------------------------- ## -_ASBOX - ) | sed "s/^/$as_me: WARNING: /" >&2 - ;; -esac -{ echo "$as_me:$LINENO: checking for mach/cthreads.h" >&5 -echo $ECHO_N "checking for mach/cthreads.h... $ECHO_C" >&6; } -if test "${ac_cv_header_mach_cthreads_h+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 -else - ac_cv_header_mach_cthreads_h=$ac_header_preproc -fi -{ echo "$as_me:$LINENO: result: $ac_cv_header_mach_cthreads_h" >&5 -echo "${ECHO_T}$ac_cv_header_mach_cthreads_h" >&6; } - -fi -if test $ac_cv_header_mach_cthreads_h = yes; then - cat >>confdefs.h <<\_ACEOF -#define WITH_THREAD 1 -_ACEOF - - cat >>confdefs.h <<\_ACEOF -#define C_THREADS 1 -_ACEOF - - -cat >>confdefs.h <<\_ACEOF -#define MACH_C_THREADS 1 -_ACEOF - - THREADOBJ="Python/thread.o" -else - - { echo "$as_me:$LINENO: checking for --with-pth" >&5 -echo $ECHO_N "checking for --with-pth... $ECHO_C" >&6; } - -# Check whether --with-pth was given. -if test "${with_pth+set}" = set; then - withval=$with_pth; { echo "$as_me:$LINENO: result: $withval" >&5 -echo "${ECHO_T}$withval" >&6; } - cat >>confdefs.h <<\_ACEOF -#define WITH_THREAD 1 -_ACEOF - - -cat >>confdefs.h <<\_ACEOF -#define HAVE_PTH 1 -_ACEOF - - LIBS="-lpth $LIBS" - THREADOBJ="Python/thread.o" -else - { echo "$as_me:$LINENO: result: no" >&5 -echo "${ECHO_T}no" >&6; } - - # Just looking for pthread_create in libpthread is not enough: - # on HP/UX, pthread.h renames pthread_create to a different symbol name. - # So we really have to include pthread.h, and then link. - _libs=$LIBS - LIBS="$LIBS -lpthread" - { echo "$as_me:$LINENO: checking for pthread_create in -lpthread" >&5 -echo $ECHO_N "checking for pthread_create in -lpthread... $ECHO_C" >&6; } - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -#include - -void * start_routine (void *arg) { exit (0); } -int -main () -{ - -pthread_create (NULL, NULL, start_routine, NULL) - ; - return 0; -} -_ACEOF -rm -f conftest.$ac_objext conftest$ac_exeext -if { (ac_try="$ac_link" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_link") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest$ac_exeext && - $as_test_x conftest$ac_exeext; then - - { echo "$as_me:$LINENO: result: yes" >&5 -echo "${ECHO_T}yes" >&6; } - cat >>confdefs.h <<\_ACEOF -#define WITH_THREAD 1 -_ACEOF - - posix_threads=yes - THREADOBJ="Python/thread.o" -else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - - LIBS=$_libs - { echo "$as_me:$LINENO: checking for pthread_detach" >&5 -echo $ECHO_N "checking for pthread_detach... $ECHO_C" >&6; } -if test "${ac_cv_func_pthread_detach+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 -else - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -/* Define pthread_detach to an innocuous variant, in case declares pthread_detach. - For example, HP-UX 11i declares gettimeofday. */ -#define pthread_detach innocuous_pthread_detach - -/* System header to define __stub macros and hopefully few prototypes, - which can conflict with char pthread_detach (); below. - Prefer to if __STDC__ is defined, since - exists even on freestanding compilers. */ - -#ifdef __STDC__ -# include -#else -# include -#endif - -#undef pthread_detach - -/* Override any GCC internal prototype to avoid an error. - Use char because int might match the return type of a GCC - builtin and then its argument prototype would still apply. */ -#ifdef __cplusplus -extern "C" -#endif -char pthread_detach (); -/* The GNU C library defines this for functions which it implements - to always fail with ENOSYS. Some functions are actually named - something starting with __ and the normal name is an alias. */ -#if defined __stub_pthread_detach || defined __stub___pthread_detach -choke me -#endif - -int -main () -{ -return pthread_detach (); - ; - return 0; -} -_ACEOF -rm -f conftest.$ac_objext conftest$ac_exeext -if { (ac_try="$ac_link" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_link") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest$ac_exeext && - $as_test_x conftest$ac_exeext; then - ac_cv_func_pthread_detach=yes -else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - ac_cv_func_pthread_detach=no -fi - -rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \ - conftest$ac_exeext conftest.$ac_ext -fi -{ echo "$as_me:$LINENO: result: $ac_cv_func_pthread_detach" >&5 -echo "${ECHO_T}$ac_cv_func_pthread_detach" >&6; } -if test $ac_cv_func_pthread_detach = yes; then - cat >>confdefs.h <<\_ACEOF -#define WITH_THREAD 1 -_ACEOF - - posix_threads=yes - THREADOBJ="Python/thread.o" -else - - if test "${ac_cv_header_atheos_threads_h+set}" = set; then - { echo "$as_me:$LINENO: checking for atheos/threads.h" >&5 -echo $ECHO_N "checking for atheos/threads.h... $ECHO_C" >&6; } -if test "${ac_cv_header_atheos_threads_h+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 -fi -{ echo "$as_me:$LINENO: result: $ac_cv_header_atheos_threads_h" >&5 -echo "${ECHO_T}$ac_cv_header_atheos_threads_h" >&6; } -else - # Is the header compilable? -{ echo "$as_me:$LINENO: checking atheos/threads.h usability" >&5 -echo $ECHO_N "checking atheos/threads.h usability... $ECHO_C" >&6; } -cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -$ac_includes_default -#include -_ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - ac_header_compiler=yes -else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - ac_header_compiler=no -fi - -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext -{ echo "$as_me:$LINENO: result: $ac_header_compiler" >&5 -echo "${ECHO_T}$ac_header_compiler" >&6; } - -# Is the header present? -{ echo "$as_me:$LINENO: checking atheos/threads.h presence" >&5 -echo $ECHO_N "checking atheos/threads.h presence... $ECHO_C" >&6; } -cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -#include -_ACEOF -if { (ac_try="$ac_cpp conftest.$ac_ext" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_cpp conftest.$ac_ext") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } >/dev/null && { - test -z "$ac_c_preproc_warn_flag$ac_c_werror_flag" || - test ! -s conftest.err - }; then - ac_header_preproc=yes -else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - ac_header_preproc=no -fi - -rm -f conftest.err conftest.$ac_ext -{ echo "$as_me:$LINENO: result: $ac_header_preproc" >&5 -echo "${ECHO_T}$ac_header_preproc" >&6; } - -# So? What about this header? -case $ac_header_compiler:$ac_header_preproc:$ac_c_preproc_warn_flag in - yes:no: ) - { echo "$as_me:$LINENO: WARNING: atheos/threads.h: accepted by the compiler, rejected by the preprocessor!" >&5 -echo "$as_me: WARNING: atheos/threads.h: accepted by the compiler, rejected by the preprocessor!" >&2;} - { echo "$as_me:$LINENO: WARNING: atheos/threads.h: proceeding with the compiler's result" >&5 -echo "$as_me: WARNING: atheos/threads.h: proceeding with the compiler's result" >&2;} - ac_header_preproc=yes - ;; - no:yes:* ) - { echo "$as_me:$LINENO: WARNING: atheos/threads.h: present but cannot be compiled" >&5 -echo "$as_me: WARNING: atheos/threads.h: present but cannot be compiled" >&2;} - { echo "$as_me:$LINENO: WARNING: atheos/threads.h: check for missing prerequisite headers?" >&5 -echo "$as_me: WARNING: atheos/threads.h: check for missing prerequisite headers?" >&2;} - { echo "$as_me:$LINENO: WARNING: atheos/threads.h: see the Autoconf documentation" >&5 -echo "$as_me: WARNING: atheos/threads.h: see the Autoconf documentation" >&2;} - { echo "$as_me:$LINENO: WARNING: atheos/threads.h: section \"Present But Cannot Be Compiled\"" >&5 -echo "$as_me: WARNING: atheos/threads.h: section \"Present But Cannot Be Compiled\"" >&2;} - { echo "$as_me:$LINENO: WARNING: atheos/threads.h: proceeding with the preprocessor's result" >&5 -echo "$as_me: WARNING: atheos/threads.h: proceeding with the preprocessor's result" >&2;} - { echo "$as_me:$LINENO: WARNING: atheos/threads.h: in the future, the compiler will take precedence" >&5 -echo "$as_me: WARNING: atheos/threads.h: in the future, the compiler will take precedence" >&2;} - ( cat <<\_ASBOX -## -------------------------------------- ## -## Report this to http://bugs.python.org/ ## -## -------------------------------------- ## -_ASBOX - ) | sed "s/^/$as_me: WARNING: /" >&2 - ;; -esac -{ echo "$as_me:$LINENO: checking for atheos/threads.h" >&5 -echo $ECHO_N "checking for atheos/threads.h... $ECHO_C" >&6; } -if test "${ac_cv_header_atheos_threads_h+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 -else - ac_cv_header_atheos_threads_h=$ac_header_preproc -fi -{ echo "$as_me:$LINENO: result: $ac_cv_header_atheos_threads_h" >&5 -echo "${ECHO_T}$ac_cv_header_atheos_threads_h" >&6; } - -fi -if test $ac_cv_header_atheos_threads_h = yes; then - cat >>confdefs.h <<\_ACEOF -#define WITH_THREAD 1 -_ACEOF - - -cat >>confdefs.h <<\_ACEOF -#define ATHEOS_THREADS 1 -_ACEOF - - THREADOBJ="Python/thread.o" -else - - if test "${ac_cv_header_kernel_OS_h+set}" = set; then - { echo "$as_me:$LINENO: checking for kernel/OS.h" >&5 -echo $ECHO_N "checking for kernel/OS.h... $ECHO_C" >&6; } -if test "${ac_cv_header_kernel_OS_h+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 -fi -{ echo "$as_me:$LINENO: result: $ac_cv_header_kernel_OS_h" >&5 -echo "${ECHO_T}$ac_cv_header_kernel_OS_h" >&6; } -else - # Is the header compilable? -{ echo "$as_me:$LINENO: checking kernel/OS.h usability" >&5 -echo $ECHO_N "checking kernel/OS.h usability... $ECHO_C" >&6; } -cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -$ac_includes_default -#include -_ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - ac_header_compiler=yes -else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - ac_header_compiler=no -fi - -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext -{ echo "$as_me:$LINENO: result: $ac_header_compiler" >&5 -echo "${ECHO_T}$ac_header_compiler" >&6; } - -# Is the header present? -{ echo "$as_me:$LINENO: checking kernel/OS.h presence" >&5 -echo $ECHO_N "checking kernel/OS.h presence... $ECHO_C" >&6; } -cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -#include -_ACEOF -if { (ac_try="$ac_cpp conftest.$ac_ext" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_cpp conftest.$ac_ext") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } >/dev/null && { - test -z "$ac_c_preproc_warn_flag$ac_c_werror_flag" || - test ! -s conftest.err - }; then - ac_header_preproc=yes -else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - ac_header_preproc=no -fi - -rm -f conftest.err conftest.$ac_ext -{ echo "$as_me:$LINENO: result: $ac_header_preproc" >&5 -echo "${ECHO_T}$ac_header_preproc" >&6; } - -# So? What about this header? -case $ac_header_compiler:$ac_header_preproc:$ac_c_preproc_warn_flag in - yes:no: ) - { echo "$as_me:$LINENO: WARNING: kernel/OS.h: accepted by the compiler, rejected by the preprocessor!" >&5 -echo "$as_me: WARNING: kernel/OS.h: accepted by the compiler, rejected by the preprocessor!" >&2;} - { echo "$as_me:$LINENO: WARNING: kernel/OS.h: proceeding with the compiler's result" >&5 -echo "$as_me: WARNING: kernel/OS.h: proceeding with the compiler's result" >&2;} - ac_header_preproc=yes - ;; - no:yes:* ) - { echo "$as_me:$LINENO: WARNING: kernel/OS.h: present but cannot be compiled" >&5 -echo "$as_me: WARNING: kernel/OS.h: present but cannot be compiled" >&2;} - { echo "$as_me:$LINENO: WARNING: kernel/OS.h: check for missing prerequisite headers?" >&5 -echo "$as_me: WARNING: kernel/OS.h: check for missing prerequisite headers?" >&2;} - { echo "$as_me:$LINENO: WARNING: kernel/OS.h: see the Autoconf documentation" >&5 -echo "$as_me: WARNING: kernel/OS.h: see the Autoconf documentation" >&2;} - { echo "$as_me:$LINENO: WARNING: kernel/OS.h: section \"Present But Cannot Be Compiled\"" >&5 -echo "$as_me: WARNING: kernel/OS.h: section \"Present But Cannot Be Compiled\"" >&2;} - { echo "$as_me:$LINENO: WARNING: kernel/OS.h: proceeding with the preprocessor's result" >&5 -echo "$as_me: WARNING: kernel/OS.h: proceeding with the preprocessor's result" >&2;} - { echo "$as_me:$LINENO: WARNING: kernel/OS.h: in the future, the compiler will take precedence" >&5 -echo "$as_me: WARNING: kernel/OS.h: in the future, the compiler will take precedence" >&2;} - ( cat <<\_ASBOX -## -------------------------------------- ## -## Report this to http://bugs.python.org/ ## -## -------------------------------------- ## -_ASBOX - ) | sed "s/^/$as_me: WARNING: /" >&2 - ;; -esac -{ echo "$as_me:$LINENO: checking for kernel/OS.h" >&5 -echo $ECHO_N "checking for kernel/OS.h... $ECHO_C" >&6; } -if test "${ac_cv_header_kernel_OS_h+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 -else - ac_cv_header_kernel_OS_h=$ac_header_preproc -fi -{ echo "$as_me:$LINENO: result: $ac_cv_header_kernel_OS_h" >&5 -echo "${ECHO_T}$ac_cv_header_kernel_OS_h" >&6; } - -fi -if test $ac_cv_header_kernel_OS_h = yes; then - cat >>confdefs.h <<\_ACEOF -#define WITH_THREAD 1 -_ACEOF - - -cat >>confdefs.h <<\_ACEOF -#define BEOS_THREADS 1 -_ACEOF - - THREADOBJ="Python/thread.o" -else - - { echo "$as_me:$LINENO: checking for pthread_create in -lpthreads" >&5 -echo $ECHO_N "checking for pthread_create in -lpthreads... $ECHO_C" >&6; } -if test "${ac_cv_lib_pthreads_pthread_create+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 -else - ac_check_lib_save_LIBS=$LIBS -LIBS="-lpthreads $LIBS" -cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ - -/* Override any GCC internal prototype to avoid an error. - Use char because int might match the return type of a GCC - builtin and then its argument prototype would still apply. */ -#ifdef __cplusplus -extern "C" -#endif -char pthread_create (); -int -main () -{ -return pthread_create (); - ; - return 0; -} -_ACEOF -rm -f conftest.$ac_objext conftest$ac_exeext -if { (ac_try="$ac_link" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_link") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest$ac_exeext && - $as_test_x conftest$ac_exeext; then - ac_cv_lib_pthreads_pthread_create=yes -else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - ac_cv_lib_pthreads_pthread_create=no -fi - -rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \ - conftest$ac_exeext conftest.$ac_ext -LIBS=$ac_check_lib_save_LIBS -fi -{ echo "$as_me:$LINENO: result: $ac_cv_lib_pthreads_pthread_create" >&5 -echo "${ECHO_T}$ac_cv_lib_pthreads_pthread_create" >&6; } -if test $ac_cv_lib_pthreads_pthread_create = yes; then - cat >>confdefs.h <<\_ACEOF -#define WITH_THREAD 1 -_ACEOF - - posix_threads=yes - LIBS="$LIBS -lpthreads" - THREADOBJ="Python/thread.o" -else - - { echo "$as_me:$LINENO: checking for pthread_create in -lc_r" >&5 -echo $ECHO_N "checking for pthread_create in -lc_r... $ECHO_C" >&6; } -if test "${ac_cv_lib_c_r_pthread_create+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 -else - ac_check_lib_save_LIBS=$LIBS -LIBS="-lc_r $LIBS" -cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ - -/* Override any GCC internal prototype to avoid an error. - Use char because int might match the return type of a GCC - builtin and then its argument prototype would still apply. */ -#ifdef __cplusplus -extern "C" -#endif -char pthread_create (); -int -main () -{ -return pthread_create (); - ; - return 0; -} -_ACEOF -rm -f conftest.$ac_objext conftest$ac_exeext -if { (ac_try="$ac_link" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_link") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest$ac_exeext && - $as_test_x conftest$ac_exeext; then - ac_cv_lib_c_r_pthread_create=yes -else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - ac_cv_lib_c_r_pthread_create=no -fi - -rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \ - conftest$ac_exeext conftest.$ac_ext -LIBS=$ac_check_lib_save_LIBS -fi -{ echo "$as_me:$LINENO: result: $ac_cv_lib_c_r_pthread_create" >&5 -echo "${ECHO_T}$ac_cv_lib_c_r_pthread_create" >&6; } -if test $ac_cv_lib_c_r_pthread_create = yes; then - cat >>confdefs.h <<\_ACEOF -#define WITH_THREAD 1 -_ACEOF - - posix_threads=yes - LIBS="$LIBS -lc_r" - THREADOBJ="Python/thread.o" -else - - { echo "$as_me:$LINENO: checking for __pthread_create_system in -lpthread" >&5 -echo $ECHO_N "checking for __pthread_create_system in -lpthread... $ECHO_C" >&6; } -if test "${ac_cv_lib_pthread___pthread_create_system+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 -else - ac_check_lib_save_LIBS=$LIBS -LIBS="-lpthread $LIBS" -cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ - -/* Override any GCC internal prototype to avoid an error. - Use char because int might match the return type of a GCC - builtin and then its argument prototype would still apply. */ -#ifdef __cplusplus -extern "C" -#endif -char __pthread_create_system (); -int -main () -{ -return __pthread_create_system (); - ; - return 0; -} -_ACEOF -rm -f conftest.$ac_objext conftest$ac_exeext -if { (ac_try="$ac_link" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_link") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest$ac_exeext && - $as_test_x conftest$ac_exeext; then - ac_cv_lib_pthread___pthread_create_system=yes -else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - ac_cv_lib_pthread___pthread_create_system=no -fi - -rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \ - conftest$ac_exeext conftest.$ac_ext -LIBS=$ac_check_lib_save_LIBS -fi -{ echo "$as_me:$LINENO: result: $ac_cv_lib_pthread___pthread_create_system" >&5 -echo "${ECHO_T}$ac_cv_lib_pthread___pthread_create_system" >&6; } -if test $ac_cv_lib_pthread___pthread_create_system = yes; then - cat >>confdefs.h <<\_ACEOF -#define WITH_THREAD 1 -_ACEOF - - posix_threads=yes - LIBS="$LIBS -lpthread" - THREADOBJ="Python/thread.o" -else - - { echo "$as_me:$LINENO: checking for pthread_create in -lcma" >&5 -echo $ECHO_N "checking for pthread_create in -lcma... $ECHO_C" >&6; } -if test "${ac_cv_lib_cma_pthread_create+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 -else - ac_check_lib_save_LIBS=$LIBS -LIBS="-lcma $LIBS" -cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ - -/* Override any GCC internal prototype to avoid an error. - Use char because int might match the return type of a GCC - builtin and then its argument prototype would still apply. */ -#ifdef __cplusplus -extern "C" -#endif -char pthread_create (); -int -main () -{ -return pthread_create (); - ; - return 0; -} -_ACEOF -rm -f conftest.$ac_objext conftest$ac_exeext -if { (ac_try="$ac_link" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_link") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest$ac_exeext && - $as_test_x conftest$ac_exeext; then - ac_cv_lib_cma_pthread_create=yes -else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - ac_cv_lib_cma_pthread_create=no -fi - -rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \ - conftest$ac_exeext conftest.$ac_ext -LIBS=$ac_check_lib_save_LIBS -fi -{ echo "$as_me:$LINENO: result: $ac_cv_lib_cma_pthread_create" >&5 -echo "${ECHO_T}$ac_cv_lib_cma_pthread_create" >&6; } -if test $ac_cv_lib_cma_pthread_create = yes; then - cat >>confdefs.h <<\_ACEOF -#define WITH_THREAD 1 -_ACEOF - - posix_threads=yes - LIBS="$LIBS -lcma" - THREADOBJ="Python/thread.o" -else - - USE_THREAD_MODULE="#" -fi - - -fi - -fi - -fi - -fi - - -fi - - -fi - -fi - -rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \ - conftest$ac_exeext conftest.$ac_ext -fi - -fi - - -fi - - - - { echo "$as_me:$LINENO: checking for usconfig in -lmpc" >&5 -echo $ECHO_N "checking for usconfig in -lmpc... $ECHO_C" >&6; } -if test "${ac_cv_lib_mpc_usconfig+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 -else - ac_check_lib_save_LIBS=$LIBS -LIBS="-lmpc $LIBS" -cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ - -/* Override any GCC internal prototype to avoid an error. - Use char because int might match the return type of a GCC - builtin and then its argument prototype would still apply. */ -#ifdef __cplusplus -extern "C" -#endif -char usconfig (); -int -main () -{ -return usconfig (); - ; - return 0; -} -_ACEOF -rm -f conftest.$ac_objext conftest$ac_exeext -if { (ac_try="$ac_link" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_link") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest$ac_exeext && - $as_test_x conftest$ac_exeext; then - ac_cv_lib_mpc_usconfig=yes -else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - ac_cv_lib_mpc_usconfig=no -fi - -rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \ - conftest$ac_exeext conftest.$ac_ext -LIBS=$ac_check_lib_save_LIBS -fi -{ echo "$as_me:$LINENO: result: $ac_cv_lib_mpc_usconfig" >&5 -echo "${ECHO_T}$ac_cv_lib_mpc_usconfig" >&6; } -if test $ac_cv_lib_mpc_usconfig = yes; then - cat >>confdefs.h <<\_ACEOF -#define WITH_THREAD 1 -_ACEOF - - LIBS="$LIBS -lmpc" - THREADOBJ="Python/thread.o" - USE_THREAD_MODULE="" -fi - - - if test "$posix_threads" != "yes"; then - { echo "$as_me:$LINENO: checking for thr_create in -lthread" >&5 -echo $ECHO_N "checking for thr_create in -lthread... $ECHO_C" >&6; } -if test "${ac_cv_lib_thread_thr_create+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 -else - ac_check_lib_save_LIBS=$LIBS -LIBS="-lthread $LIBS" -cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ - -/* Override any GCC internal prototype to avoid an error. - Use char because int might match the return type of a GCC - builtin and then its argument prototype would still apply. */ -#ifdef __cplusplus -extern "C" -#endif -char thr_create (); -int -main () -{ -return thr_create (); - ; - return 0; -} -_ACEOF -rm -f conftest.$ac_objext conftest$ac_exeext -if { (ac_try="$ac_link" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_link") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest$ac_exeext && - $as_test_x conftest$ac_exeext; then - ac_cv_lib_thread_thr_create=yes -else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - ac_cv_lib_thread_thr_create=no -fi - -rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \ - conftest$ac_exeext conftest.$ac_ext -LIBS=$ac_check_lib_save_LIBS -fi -{ echo "$as_me:$LINENO: result: $ac_cv_lib_thread_thr_create" >&5 -echo "${ECHO_T}$ac_cv_lib_thread_thr_create" >&6; } -if test $ac_cv_lib_thread_thr_create = yes; then - cat >>confdefs.h <<\_ACEOF -#define WITH_THREAD 1 -_ACEOF - - LIBS="$LIBS -lthread" - THREADOBJ="Python/thread.o" - USE_THREAD_MODULE="" -fi - - fi - - if test "$USE_THREAD_MODULE" != "#" - then - # If the above checks didn't disable threads, (at least) OSF1 - # needs this '-threads' argument during linking. - case $ac_sys_system in - OSF1) LDLAST=-threads;; - esac - fi -fi - -if test "$posix_threads" = "yes"; then - if test "$unistd_defines_pthreads" = "no"; then - -cat >>confdefs.h <<\_ACEOF -#define _POSIX_THREADS 1 -_ACEOF - - fi - - # Bug 662787: Using semaphores causes unexplicable hangs on Solaris 8. - case $ac_sys_system/$ac_sys_release in - SunOS/5.6) -cat >>confdefs.h <<\_ACEOF -#define HAVE_PTHREAD_DESTRUCTOR 1 -_ACEOF - - ;; - SunOS/5.8) -cat >>confdefs.h <<\_ACEOF -#define HAVE_BROKEN_POSIX_SEMAPHORES 1 -_ACEOF - - ;; - AIX/5) -cat >>confdefs.h <<\_ACEOF -#define HAVE_BROKEN_POSIX_SEMAPHORES 1 -_ACEOF - - ;; - esac - - { echo "$as_me:$LINENO: checking if PTHREAD_SCOPE_SYSTEM is supported" >&5 -echo $ECHO_N "checking if PTHREAD_SCOPE_SYSTEM is supported... $ECHO_C" >&6; } - if test "${ac_cv_pthread_system_supported+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 -else - if test "$cross_compiling" = yes; then - ac_cv_pthread_system_supported=no -else - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -#include - void *foo(void *parm) { - return NULL; - } - main() { - pthread_attr_t attr; - pthread_t id; - if (pthread_attr_init(&attr)) exit(-1); - if (pthread_attr_setscope(&attr, PTHREAD_SCOPE_SYSTEM)) exit(-1); - if (pthread_create(&id, &attr, foo, NULL)) exit(-1); - exit(0); - } -_ACEOF -rm -f conftest$ac_exeext -if { (ac_try="$ac_link" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_link") 2>&5 - ac_status=$? - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { ac_try='./conftest$ac_exeext' - { (case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_try") 2>&5 - ac_status=$? - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); }; }; then - ac_cv_pthread_system_supported=yes -else - echo "$as_me: program exited with status $ac_status" >&5 -echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - -( exit $ac_status ) -ac_cv_pthread_system_supported=no -fi -rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext conftest.$ac_objext conftest.$ac_ext -fi - - - -fi - - { echo "$as_me:$LINENO: result: $ac_cv_pthread_system_supported" >&5 -echo "${ECHO_T}$ac_cv_pthread_system_supported" >&6; } - if test "$ac_cv_pthread_system_supported" = "yes"; then - -cat >>confdefs.h <<\_ACEOF -#define PTHREAD_SYSTEM_SCHED_SUPPORTED 1 -_ACEOF - - fi - -for ac_func in pthread_sigmask -do -as_ac_var=`echo "ac_cv_func_$ac_func" | $as_tr_sh` -{ echo "$as_me:$LINENO: checking for $ac_func" >&5 -echo $ECHO_N "checking for $ac_func... $ECHO_C" >&6; } -if { as_var=$as_ac_var; eval "test \"\${$as_var+set}\" = set"; }; then - echo $ECHO_N "(cached) $ECHO_C" >&6 -else - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -/* Define $ac_func to an innocuous variant, in case declares $ac_func. - For example, HP-UX 11i declares gettimeofday. */ -#define $ac_func innocuous_$ac_func - -/* System header to define __stub macros and hopefully few prototypes, - which can conflict with char $ac_func (); below. - Prefer to if __STDC__ is defined, since - exists even on freestanding compilers. */ - -#ifdef __STDC__ -# include -#else -# include -#endif - -#undef $ac_func - -/* Override any GCC internal prototype to avoid an error. - Use char because int might match the return type of a GCC - builtin and then its argument prototype would still apply. */ -#ifdef __cplusplus -extern "C" -#endif -char $ac_func (); -/* The GNU C library defines this for functions which it implements - to always fail with ENOSYS. Some functions are actually named - something starting with __ and the normal name is an alias. */ -#if defined __stub_$ac_func || defined __stub___$ac_func -choke me -#endif - -int -main () -{ -return $ac_func (); - ; - return 0; -} -_ACEOF -rm -f conftest.$ac_objext conftest$ac_exeext -if { (ac_try="$ac_link" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_link") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest$ac_exeext && - $as_test_x conftest$ac_exeext; then - eval "$as_ac_var=yes" -else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - eval "$as_ac_var=no" -fi - -rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \ - conftest$ac_exeext conftest.$ac_ext -fi -ac_res=`eval echo '${'$as_ac_var'}'` - { echo "$as_me:$LINENO: result: $ac_res" >&5 -echo "${ECHO_T}$ac_res" >&6; } -if test `eval echo '${'$as_ac_var'}'` = yes; then - cat >>confdefs.h <<_ACEOF -#define `echo "HAVE_$ac_func" | $as_tr_cpp` 1 -_ACEOF - case $ac_sys_system in - CYGWIN*) - -cat >>confdefs.h <<\_ACEOF -#define HAVE_BROKEN_PTHREAD_SIGMASK 1 -_ACEOF - - ;; - esac -fi -done - -fi - - -# Check for enable-ipv6 - - -{ echo "$as_me:$LINENO: checking if --enable-ipv6 is specified" >&5 -echo $ECHO_N "checking if --enable-ipv6 is specified... $ECHO_C" >&6; } -# Check whether --enable-ipv6 was given. -if test "${enable_ipv6+set}" = set; then - enableval=$enable_ipv6; case "$enableval" in - no) - { echo "$as_me:$LINENO: result: no" >&5 -echo "${ECHO_T}no" >&6; } - ipv6=no - ;; - *) { echo "$as_me:$LINENO: result: yes" >&5 -echo "${ECHO_T}yes" >&6; } - cat >>confdefs.h <<\_ACEOF -#define ENABLE_IPV6 1 -_ACEOF - - ipv6=yes - ;; - esac -else - - if test "$cross_compiling" = yes; then - { echo "$as_me:$LINENO: result: no" >&5 -echo "${ECHO_T}no" >&6; } - ipv6=no - -else - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ - /* AF_INET6 available check */ -#include -#include -main() -{ - if (socket(AF_INET6, SOCK_STREAM, 0) < 0) - exit(1); - else - exit(0); -} - -_ACEOF -rm -f conftest$ac_exeext -if { (ac_try="$ac_link" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_link") 2>&5 - ac_status=$? - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { ac_try='./conftest$ac_exeext' - { (case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_try") 2>&5 - ac_status=$? - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); }; }; then - { echo "$as_me:$LINENO: result: yes" >&5 -echo "${ECHO_T}yes" >&6; } - ipv6=yes -else - echo "$as_me: program exited with status $ac_status" >&5 -echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - -( exit $ac_status ) -{ echo "$as_me:$LINENO: result: no" >&5 -echo "${ECHO_T}no" >&6; } - ipv6=no -fi -rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext conftest.$ac_objext conftest.$ac_ext -fi - - - -if test "$ipv6" = "yes"; then - { echo "$as_me:$LINENO: checking if RFC2553 API is available" >&5 -echo $ECHO_N "checking if RFC2553 API is available... $ECHO_C" >&6; } - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -#include -#include -int -main () -{ -struct sockaddr_in6 x; -x.sin6_scope_id; - ; - return 0; -} -_ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - { echo "$as_me:$LINENO: result: yes" >&5 -echo "${ECHO_T}yes" >&6; } - ipv6=yes -else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - { echo "$as_me:$LINENO: result: no" >&5 -echo "${ECHO_T}no" >&6; } - ipv6=no -fi - -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext -fi - -if test "$ipv6" = "yes"; then - cat >>confdefs.h <<\_ACEOF -#define ENABLE_IPV6 1 -_ACEOF - -fi - -fi - - -ipv6type=unknown -ipv6lib=none -ipv6trylibc=no - -if test "$ipv6" = "yes"; then - { echo "$as_me:$LINENO: checking ipv6 stack type" >&5 -echo $ECHO_N "checking ipv6 stack type... $ECHO_C" >&6; } - for i in inria kame linux-glibc linux-inet6 solaris toshiba v6d zeta; - do - case $i in - inria) - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ - -#include -#ifdef IPV6_INRIA_VERSION -yes -#endif -_ACEOF -if (eval "$ac_cpp conftest.$ac_ext") 2>&5 | - $EGREP "yes" >/dev/null 2>&1; then - ipv6type=$i -fi -rm -f conftest* - - ;; - kame) - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ - -#include -#ifdef __KAME__ -yes -#endif -_ACEOF -if (eval "$ac_cpp conftest.$ac_ext") 2>&5 | - $EGREP "yes" >/dev/null 2>&1; then - ipv6type=$i; - ipv6lib=inet6 - ipv6libdir=/usr/local/v6/lib - ipv6trylibc=yes -fi -rm -f conftest* - - ;; - linux-glibc) - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ - -#include -#if defined(__GLIBC__) && ((__GLIBC__ == 2 && __GLIBC_MINOR__ >= 1) || (__GLIBC__ > 2)) -yes -#endif -_ACEOF -if (eval "$ac_cpp conftest.$ac_ext") 2>&5 | - $EGREP "yes" >/dev/null 2>&1; then - ipv6type=$i; - ipv6trylibc=yes -fi -rm -f conftest* - - ;; - linux-inet6) - if test -d /usr/inet6; then - ipv6type=$i - ipv6lib=inet6 - ipv6libdir=/usr/inet6/lib - BASECFLAGS="-I/usr/inet6/include $BASECFLAGS" - fi - ;; - solaris) - if test -f /etc/netconfig; then - if /usr/xpg4/bin/grep -q tcp6 /etc/netconfig; then - ipv6type=$i - ipv6trylibc=yes - fi - fi - ;; - toshiba) - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ - -#include -#ifdef _TOSHIBA_INET6 -yes -#endif -_ACEOF -if (eval "$ac_cpp conftest.$ac_ext") 2>&5 | - $EGREP "yes" >/dev/null 2>&1; then - ipv6type=$i; - ipv6lib=inet6; - ipv6libdir=/usr/local/v6/lib -fi -rm -f conftest* - - ;; - v6d) - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ - -#include -#ifdef __V6D__ -yes -#endif -_ACEOF -if (eval "$ac_cpp conftest.$ac_ext") 2>&5 | - $EGREP "yes" >/dev/null 2>&1; then - ipv6type=$i; - ipv6lib=v6; - ipv6libdir=/usr/local/v6/lib; - BASECFLAGS="-I/usr/local/v6/include $BASECFLAGS" -fi -rm -f conftest* - - ;; - zeta) - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ - -#include -#ifdef _ZETA_MINAMI_INET6 -yes -#endif -_ACEOF -if (eval "$ac_cpp conftest.$ac_ext") 2>&5 | - $EGREP "yes" >/dev/null 2>&1; then - ipv6type=$i; - ipv6lib=inet6; - ipv6libdir=/usr/local/v6/lib -fi -rm -f conftest* - - ;; - esac - if test "$ipv6type" != "unknown"; then - break - fi - done - { echo "$as_me:$LINENO: result: $ipv6type" >&5 -echo "${ECHO_T}$ipv6type" >&6; } -fi - -if test "$ipv6" = "yes" -a "$ipv6lib" != "none"; then - if test -d $ipv6libdir -a -f $ipv6libdir/lib$ipv6lib.a; then - LIBS="-L$ipv6libdir -l$ipv6lib $LIBS" - echo "using lib$ipv6lib" - else - if test $ipv6trylibc = "yes"; then - echo "using libc" - else - echo 'Fatal: no $ipv6lib library found. cannot continue.' - echo "You need to fetch lib$ipv6lib.a from appropriate" - echo 'ipv6 kit and compile beforehand.' - exit 1 - fi - fi -fi - -{ echo "$as_me:$LINENO: checking for OSX 10.5 SDK or later" >&5 -echo $ECHO_N "checking for OSX 10.5 SDK or later... $ECHO_C" >&6; } -cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -#include -int -main () -{ -FSIORefNum fRef = 0 - ; - return 0; -} -_ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - -cat >>confdefs.h <<\_ACEOF -#define HAVE_OSX105_SDK 1 -_ACEOF - - { echo "$as_me:$LINENO: result: yes" >&5 -echo "${ECHO_T}yes" >&6; } -else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - { echo "$as_me:$LINENO: result: no" >&5 -echo "${ECHO_T}no" >&6; } - -fi - -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext - -# Check for --with-doc-strings -{ echo "$as_me:$LINENO: checking for --with-doc-strings" >&5 -echo $ECHO_N "checking for --with-doc-strings... $ECHO_C" >&6; } - -# Check whether --with-doc-strings was given. -if test "${with_doc_strings+set}" = set; then - withval=$with_doc_strings; -fi - - -if test -z "$with_doc_strings" -then with_doc_strings="yes" -fi -if test "$with_doc_strings" != "no" -then - -cat >>confdefs.h <<\_ACEOF -#define WITH_DOC_STRINGS 1 -_ACEOF - -fi -{ echo "$as_me:$LINENO: result: $with_doc_strings" >&5 -echo "${ECHO_T}$with_doc_strings" >&6; } - -# Check for Python-specific malloc support -{ echo "$as_me:$LINENO: checking for --with-tsc" >&5 -echo $ECHO_N "checking for --with-tsc... $ECHO_C" >&6; } - -# Check whether --with-tsc was given. -if test "${with_tsc+set}" = set; then - withval=$with_tsc; -if test "$withval" != no -then - -cat >>confdefs.h <<\_ACEOF -#define WITH_TSC 1 -_ACEOF - - { echo "$as_me:$LINENO: result: yes" >&5 -echo "${ECHO_T}yes" >&6; } -else { echo "$as_me:$LINENO: result: no" >&5 -echo "${ECHO_T}no" >&6; } -fi -else - { echo "$as_me:$LINENO: result: no" >&5 -echo "${ECHO_T}no" >&6; } -fi - - -# Check for Python-specific malloc support -{ echo "$as_me:$LINENO: checking for --with-pymalloc" >&5 -echo $ECHO_N "checking for --with-pymalloc... $ECHO_C" >&6; } - -# Check whether --with-pymalloc was given. -if test "${with_pymalloc+set}" = set; then - withval=$with_pymalloc; -fi - - -if test -z "$with_pymalloc" -then with_pymalloc="yes" -fi -if test "$with_pymalloc" != "no" -then - -cat >>confdefs.h <<\_ACEOF -#define WITH_PYMALLOC 1 -_ACEOF - -fi -{ echo "$as_me:$LINENO: result: $with_pymalloc" >&5 -echo "${ECHO_T}$with_pymalloc" >&6; } - -# Check for Valgrind support -{ echo "$as_me:$LINENO: checking for --with-valgrind" >&5 -echo $ECHO_N "checking for --with-valgrind... $ECHO_C" >&6; } - -# Check whether --with-valgrind was given. -if test "${with_valgrind+set}" = set; then - withval=$with_valgrind; -else - with_valgrind=no -fi - -{ echo "$as_me:$LINENO: result: $with_valgrind" >&5 -echo "${ECHO_T}$with_valgrind" >&6; } -if test "$with_valgrind" != no; then - if test "${ac_cv_header_valgrind_valgrind_h+set}" = set; then - { echo "$as_me:$LINENO: checking for valgrind/valgrind.h" >&5 -echo $ECHO_N "checking for valgrind/valgrind.h... $ECHO_C" >&6; } -if test "${ac_cv_header_valgrind_valgrind_h+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 -fi -{ echo "$as_me:$LINENO: result: $ac_cv_header_valgrind_valgrind_h" >&5 -echo "${ECHO_T}$ac_cv_header_valgrind_valgrind_h" >&6; } -else - # Is the header compilable? -{ echo "$as_me:$LINENO: checking valgrind/valgrind.h usability" >&5 -echo $ECHO_N "checking valgrind/valgrind.h usability... $ECHO_C" >&6; } -cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -$ac_includes_default -#include -_ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - ac_header_compiler=yes -else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - ac_header_compiler=no -fi - -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext -{ echo "$as_me:$LINENO: result: $ac_header_compiler" >&5 -echo "${ECHO_T}$ac_header_compiler" >&6; } - -# Is the header present? -{ echo "$as_me:$LINENO: checking valgrind/valgrind.h presence" >&5 -echo $ECHO_N "checking valgrind/valgrind.h presence... $ECHO_C" >&6; } -cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -#include -_ACEOF -if { (ac_try="$ac_cpp conftest.$ac_ext" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_cpp conftest.$ac_ext") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } >/dev/null && { - test -z "$ac_c_preproc_warn_flag$ac_c_werror_flag" || - test ! -s conftest.err - }; then - ac_header_preproc=yes -else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - ac_header_preproc=no -fi - -rm -f conftest.err conftest.$ac_ext -{ echo "$as_me:$LINENO: result: $ac_header_preproc" >&5 -echo "${ECHO_T}$ac_header_preproc" >&6; } - -# So? What about this header? -case $ac_header_compiler:$ac_header_preproc:$ac_c_preproc_warn_flag in - yes:no: ) - { echo "$as_me:$LINENO: WARNING: valgrind/valgrind.h: accepted by the compiler, rejected by the preprocessor!" >&5 -echo "$as_me: WARNING: valgrind/valgrind.h: accepted by the compiler, rejected by the preprocessor!" >&2;} - { echo "$as_me:$LINENO: WARNING: valgrind/valgrind.h: proceeding with the compiler's result" >&5 -echo "$as_me: WARNING: valgrind/valgrind.h: proceeding with the compiler's result" >&2;} - ac_header_preproc=yes - ;; - no:yes:* ) - { echo "$as_me:$LINENO: WARNING: valgrind/valgrind.h: present but cannot be compiled" >&5 -echo "$as_me: WARNING: valgrind/valgrind.h: present but cannot be compiled" >&2;} - { echo "$as_me:$LINENO: WARNING: valgrind/valgrind.h: check for missing prerequisite headers?" >&5 -echo "$as_me: WARNING: valgrind/valgrind.h: check for missing prerequisite headers?" >&2;} - { echo "$as_me:$LINENO: WARNING: valgrind/valgrind.h: see the Autoconf documentation" >&5 -echo "$as_me: WARNING: valgrind/valgrind.h: see the Autoconf documentation" >&2;} - { echo "$as_me:$LINENO: WARNING: valgrind/valgrind.h: section \"Present But Cannot Be Compiled\"" >&5 -echo "$as_me: WARNING: valgrind/valgrind.h: section \"Present But Cannot Be Compiled\"" >&2;} - { echo "$as_me:$LINENO: WARNING: valgrind/valgrind.h: proceeding with the preprocessor's result" >&5 -echo "$as_me: WARNING: valgrind/valgrind.h: proceeding with the preprocessor's result" >&2;} - { echo "$as_me:$LINENO: WARNING: valgrind/valgrind.h: in the future, the compiler will take precedence" >&5 -echo "$as_me: WARNING: valgrind/valgrind.h: in the future, the compiler will take precedence" >&2;} - ( cat <<\_ASBOX -## -------------------------------------- ## -## Report this to http://bugs.python.org/ ## -## -------------------------------------- ## -_ASBOX - ) | sed "s/^/$as_me: WARNING: /" >&2 - ;; -esac -{ echo "$as_me:$LINENO: checking for valgrind/valgrind.h" >&5 -echo $ECHO_N "checking for valgrind/valgrind.h... $ECHO_C" >&6; } -if test "${ac_cv_header_valgrind_valgrind_h+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 -else - ac_cv_header_valgrind_valgrind_h=$ac_header_preproc -fi -{ echo "$as_me:$LINENO: result: $ac_cv_header_valgrind_valgrind_h" >&5 -echo "${ECHO_T}$ac_cv_header_valgrind_valgrind_h" >&6; } - -fi -if test $ac_cv_header_valgrind_valgrind_h = yes; then - -cat >>confdefs.h <<\_ACEOF -#define WITH_VALGRIND 1 -_ACEOF - -else - { { echo "$as_me:$LINENO: error: Valgrind support requested but headers not available" >&5 -echo "$as_me: error: Valgrind support requested but headers not available" >&2;} - { (exit 1); exit 1; }; } - -fi - - -fi - -# Check for --with-wctype-functions -{ echo "$as_me:$LINENO: checking for --with-wctype-functions" >&5 -echo $ECHO_N "checking for --with-wctype-functions... $ECHO_C" >&6; } - -# Check whether --with-wctype-functions was given. -if test "${with_wctype_functions+set}" = set; then - withval=$with_wctype_functions; -if test "$withval" != no -then - -cat >>confdefs.h <<\_ACEOF -#define WANT_WCTYPE_FUNCTIONS 1 -_ACEOF - - { echo "$as_me:$LINENO: result: yes" >&5 -echo "${ECHO_T}yes" >&6; } -else { echo "$as_me:$LINENO: result: no" >&5 -echo "${ECHO_T}no" >&6; } -fi -else - { echo "$as_me:$LINENO: result: no" >&5 -echo "${ECHO_T}no" >&6; } -fi - - -# -I${DLINCLDIR} is added to the compile rule for importdl.o - -DLINCLDIR=. - -# the dlopen() function means we might want to use dynload_shlib.o. some -# platforms, such as AIX, have dlopen(), but don't want to use it. - -for ac_func in dlopen -do -as_ac_var=`echo "ac_cv_func_$ac_func" | $as_tr_sh` -{ echo "$as_me:$LINENO: checking for $ac_func" >&5 -echo $ECHO_N "checking for $ac_func... $ECHO_C" >&6; } -if { as_var=$as_ac_var; eval "test \"\${$as_var+set}\" = set"; }; then - echo $ECHO_N "(cached) $ECHO_C" >&6 -else - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -/* Define $ac_func to an innocuous variant, in case declares $ac_func. - For example, HP-UX 11i declares gettimeofday. */ -#define $ac_func innocuous_$ac_func - -/* System header to define __stub macros and hopefully few prototypes, - which can conflict with char $ac_func (); below. - Prefer to if __STDC__ is defined, since - exists even on freestanding compilers. */ - -#ifdef __STDC__ -# include -#else -# include -#endif - -#undef $ac_func - -/* Override any GCC internal prototype to avoid an error. - Use char because int might match the return type of a GCC - builtin and then its argument prototype would still apply. */ -#ifdef __cplusplus -extern "C" -#endif -char $ac_func (); -/* The GNU C library defines this for functions which it implements - to always fail with ENOSYS. Some functions are actually named - something starting with __ and the normal name is an alias. */ -#if defined __stub_$ac_func || defined __stub___$ac_func -choke me -#endif - -int -main () -{ -return $ac_func (); - ; - return 0; -} -_ACEOF -rm -f conftest.$ac_objext conftest$ac_exeext -if { (ac_try="$ac_link" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_link") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest$ac_exeext && - $as_test_x conftest$ac_exeext; then - eval "$as_ac_var=yes" -else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - eval "$as_ac_var=no" -fi - -rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \ - conftest$ac_exeext conftest.$ac_ext -fi -ac_res=`eval echo '${'$as_ac_var'}'` - { echo "$as_me:$LINENO: result: $ac_res" >&5 -echo "${ECHO_T}$ac_res" >&6; } -if test `eval echo '${'$as_ac_var'}'` = yes; then - cat >>confdefs.h <<_ACEOF -#define `echo "HAVE_$ac_func" | $as_tr_cpp` 1 -_ACEOF - -fi -done - - -# DYNLOADFILE specifies which dynload_*.o file we will use for dynamic -# loading of modules. - -{ echo "$as_me:$LINENO: checking DYNLOADFILE" >&5 -echo $ECHO_N "checking DYNLOADFILE... $ECHO_C" >&6; } -if test -z "$DYNLOADFILE" -then - case $ac_sys_system/$ac_sys_release in - AIX*) # Use dynload_shlib.c and dlopen() if we have it; otherwise dynload_aix.c - if test "$ac_cv_func_dlopen" = yes - then DYNLOADFILE="dynload_shlib.o" - else DYNLOADFILE="dynload_aix.o" - fi - ;; - BeOS*) DYNLOADFILE="dynload_beos.o";; - hp*|HP*) DYNLOADFILE="dynload_hpux.o";; - # Use dynload_next.c only on 10.2 and below, which don't have native dlopen() - Darwin/[0156]\..*) DYNLOADFILE="dynload_next.o";; - atheos*) DYNLOADFILE="dynload_atheos.o";; - *) - # use dynload_shlib.c and dlopen() if we have it; otherwise stub - # out any dynamic loading - if test "$ac_cv_func_dlopen" = yes - then DYNLOADFILE="dynload_shlib.o" - else DYNLOADFILE="dynload_stub.o" - fi - ;; - esac -fi -{ echo "$as_me:$LINENO: result: $DYNLOADFILE" >&5 -echo "${ECHO_T}$DYNLOADFILE" >&6; } -if test "$DYNLOADFILE" != "dynload_stub.o" -then - -cat >>confdefs.h <<\_ACEOF -#define HAVE_DYNAMIC_LOADING 1 -_ACEOF - -fi - -# MACHDEP_OBJS can be set to platform-specific object files needed by Python - - -{ echo "$as_me:$LINENO: checking MACHDEP_OBJS" >&5 -echo $ECHO_N "checking MACHDEP_OBJS... $ECHO_C" >&6; } -if test -z "$MACHDEP_OBJS" -then - MACHDEP_OBJS=$extra_machdep_objs -else - MACHDEP_OBJS="$MACHDEP_OBJS $extra_machdep_objs" -fi -{ echo "$as_me:$LINENO: result: MACHDEP_OBJS" >&5 -echo "${ECHO_T}MACHDEP_OBJS" >&6; } - -# checks for library functions - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -for ac_func in alarm setitimer getitimer bind_textdomain_codeset chown \ - clock confstr ctermid execv fchmod fchown fork fpathconf ftime ftruncate \ - gai_strerror getgroups getlogin getloadavg getpeername getpgid getpid \ - getpriority getresuid getresgid getpwent getspnam getspent getsid getwd \ - initgroups kill killpg lchmod lchown lstat mkfifo mknod mktime \ - mremap nice pathconf pause plock poll pthread_init \ - putenv readlink realpath \ - select sem_open sem_timedwait sem_getvalue sem_unlink setegid seteuid \ - setgid \ - setlocale setregid setreuid setsid setpgid setpgrp setuid setvbuf snprintf \ - setlocale setregid setreuid setresuid setresgid \ - 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 -do -as_ac_var=`echo "ac_cv_func_$ac_func" | $as_tr_sh` -{ echo "$as_me:$LINENO: checking for $ac_func" >&5 -echo $ECHO_N "checking for $ac_func... $ECHO_C" >&6; } -if { as_var=$as_ac_var; eval "test \"\${$as_var+set}\" = set"; }; then - echo $ECHO_N "(cached) $ECHO_C" >&6 -else - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -/* Define $ac_func to an innocuous variant, in case declares $ac_func. - For example, HP-UX 11i declares gettimeofday. */ -#define $ac_func innocuous_$ac_func - -/* System header to define __stub macros and hopefully few prototypes, - which can conflict with char $ac_func (); below. - Prefer to if __STDC__ is defined, since - exists even on freestanding compilers. */ - -#ifdef __STDC__ -# include -#else -# include -#endif - -#undef $ac_func - -/* Override any GCC internal prototype to avoid an error. - Use char because int might match the return type of a GCC - builtin and then its argument prototype would still apply. */ -#ifdef __cplusplus -extern "C" -#endif -char $ac_func (); -/* The GNU C library defines this for functions which it implements - to always fail with ENOSYS. Some functions are actually named - something starting with __ and the normal name is an alias. */ -#if defined __stub_$ac_func || defined __stub___$ac_func -choke me -#endif - -int -main () -{ -return $ac_func (); - ; - return 0; -} -_ACEOF -rm -f conftest.$ac_objext conftest$ac_exeext -if { (ac_try="$ac_link" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_link") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest$ac_exeext && - $as_test_x conftest$ac_exeext; then - eval "$as_ac_var=yes" -else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - eval "$as_ac_var=no" -fi - -rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \ - conftest$ac_exeext conftest.$ac_ext -fi -ac_res=`eval echo '${'$as_ac_var'}'` - { echo "$as_me:$LINENO: result: $ac_res" >&5 -echo "${ECHO_T}$ac_res" >&6; } -if test `eval echo '${'$as_ac_var'}'` = yes; then - cat >>confdefs.h <<_ACEOF -#define `echo "HAVE_$ac_func" | $as_tr_cpp` 1 -_ACEOF - -fi -done - - -# For some functions, having a definition is not sufficient, since -# we want to take their address. -{ echo "$as_me:$LINENO: checking for chroot" >&5 -echo $ECHO_N "checking for chroot... $ECHO_C" >&6; } -cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -#include -int -main () -{ -void *x=chroot - ; - return 0; -} -_ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - -cat >>confdefs.h <<\_ACEOF -#define HAVE_CHROOT 1 -_ACEOF - - { echo "$as_me:$LINENO: result: yes" >&5 -echo "${ECHO_T}yes" >&6; } -else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - { echo "$as_me:$LINENO: result: no" >&5 -echo "${ECHO_T}no" >&6; } - -fi - -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext -{ echo "$as_me:$LINENO: checking for link" >&5 -echo $ECHO_N "checking for link... $ECHO_C" >&6; } -cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -#include -int -main () -{ -void *x=link - ; - return 0; -} -_ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - -cat >>confdefs.h <<\_ACEOF -#define HAVE_LINK 1 -_ACEOF - - { echo "$as_me:$LINENO: result: yes" >&5 -echo "${ECHO_T}yes" >&6; } -else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - { echo "$as_me:$LINENO: result: no" >&5 -echo "${ECHO_T}no" >&6; } - -fi - -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext -{ echo "$as_me:$LINENO: checking for symlink" >&5 -echo $ECHO_N "checking for symlink... $ECHO_C" >&6; } -cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -#include -int -main () -{ -void *x=symlink - ; - return 0; -} -_ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - -cat >>confdefs.h <<\_ACEOF -#define HAVE_SYMLINK 1 -_ACEOF - - { echo "$as_me:$LINENO: result: yes" >&5 -echo "${ECHO_T}yes" >&6; } -else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - { echo "$as_me:$LINENO: result: no" >&5 -echo "${ECHO_T}no" >&6; } - -fi - -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext -{ echo "$as_me:$LINENO: checking for fchdir" >&5 -echo $ECHO_N "checking for fchdir... $ECHO_C" >&6; } -cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -#include -int -main () -{ -void *x=fchdir - ; - return 0; -} -_ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - -cat >>confdefs.h <<\_ACEOF -#define HAVE_FCHDIR 1 -_ACEOF - - { echo "$as_me:$LINENO: result: yes" >&5 -echo "${ECHO_T}yes" >&6; } -else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - { echo "$as_me:$LINENO: result: no" >&5 -echo "${ECHO_T}no" >&6; } - -fi - -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext -{ echo "$as_me:$LINENO: checking for fsync" >&5 -echo $ECHO_N "checking for fsync... $ECHO_C" >&6; } -cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -#include -int -main () -{ -void *x=fsync - ; - return 0; -} -_ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - -cat >>confdefs.h <<\_ACEOF -#define HAVE_FSYNC 1 -_ACEOF - - { echo "$as_me:$LINENO: result: yes" >&5 -echo "${ECHO_T}yes" >&6; } -else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - { echo "$as_me:$LINENO: result: no" >&5 -echo "${ECHO_T}no" >&6; } - -fi - -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext -{ echo "$as_me:$LINENO: checking for fdatasync" >&5 -echo $ECHO_N "checking for fdatasync... $ECHO_C" >&6; } -cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -#include -int -main () -{ -void *x=fdatasync - ; - return 0; -} -_ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - -cat >>confdefs.h <<\_ACEOF -#define HAVE_FDATASYNC 1 -_ACEOF - - { echo "$as_me:$LINENO: result: yes" >&5 -echo "${ECHO_T}yes" >&6; } -else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - { echo "$as_me:$LINENO: result: no" >&5 -echo "${ECHO_T}no" >&6; } - -fi - -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext -{ echo "$as_me:$LINENO: checking for epoll" >&5 -echo $ECHO_N "checking for epoll... $ECHO_C" >&6; } -cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -#include -int -main () -{ -void *x=epoll_create - ; - return 0; -} -_ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - -cat >>confdefs.h <<\_ACEOF -#define HAVE_EPOLL 1 -_ACEOF - - { echo "$as_me:$LINENO: result: yes" >&5 -echo "${ECHO_T}yes" >&6; } -else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - { echo "$as_me:$LINENO: result: no" >&5 -echo "${ECHO_T}no" >&6; } - -fi - -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext -{ echo "$as_me:$LINENO: checking for kqueue" >&5 -echo $ECHO_N "checking for kqueue... $ECHO_C" >&6; } -cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ - -#include -#include - -int -main () -{ -int x=kqueue() - ; - return 0; -} -_ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - -cat >>confdefs.h <<\_ACEOF -#define HAVE_KQUEUE 1 -_ACEOF - - { echo "$as_me:$LINENO: result: yes" >&5 -echo "${ECHO_T}yes" >&6; } -else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - { echo "$as_me:$LINENO: result: no" >&5 -echo "${ECHO_T}no" >&6; } - -fi - -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext -# On some systems (eg. FreeBSD 5), we would find a definition of the -# functions ctermid_r, setgroups in the library, but no prototype -# (e.g. because we use _XOPEN_SOURCE). See whether we can take their -# address to avoid compiler warnings and potential miscompilations -# because of the missing prototypes. - -{ echo "$as_me:$LINENO: checking for ctermid_r" >&5 -echo $ECHO_N "checking for ctermid_r... $ECHO_C" >&6; } -cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ - -#include "confdefs.h" -#include - -int -main () -{ -void* p = ctermid_r - ; - return 0; -} -_ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - -cat >>confdefs.h <<\_ACEOF -#define HAVE_CTERMID_R 1 -_ACEOF - - { echo "$as_me:$LINENO: result: yes" >&5 -echo "${ECHO_T}yes" >&6; } -else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - { echo "$as_me:$LINENO: result: no" >&5 -echo "${ECHO_T}no" >&6; } - -fi - -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext - -{ echo "$as_me:$LINENO: checking for flock" >&5 -echo $ECHO_N "checking for flock... $ECHO_C" >&6; } -cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ - -#include "confdefs.h" -#include - -int -main () -{ -void* p = flock - ; - return 0; -} -_ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - -cat >>confdefs.h <<\_ACEOF -#define HAVE_FLOCK 1 -_ACEOF - - { echo "$as_me:$LINENO: result: yes" >&5 -echo "${ECHO_T}yes" >&6; } -else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - { echo "$as_me:$LINENO: result: no" >&5 -echo "${ECHO_T}no" >&6; } - -fi - -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext - -{ echo "$as_me:$LINENO: checking for getpagesize" >&5 -echo $ECHO_N "checking for getpagesize... $ECHO_C" >&6; } -cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ - -#include "confdefs.h" -#include - -int -main () -{ -void* p = getpagesize - ; - return 0; -} -_ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - -cat >>confdefs.h <<\_ACEOF -#define HAVE_GETPAGESIZE 1 -_ACEOF - - { echo "$as_me:$LINENO: result: yes" >&5 -echo "${ECHO_T}yes" >&6; } -else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - { echo "$as_me:$LINENO: result: no" >&5 -echo "${ECHO_T}no" >&6; } - -fi - -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext - -for ac_prog in true -do - # Extract the first word of "$ac_prog", so it can be a program name with args. -set dummy $ac_prog; ac_word=$2 -{ echo "$as_me:$LINENO: checking for $ac_word" >&5 -echo $ECHO_N "checking for $ac_word... $ECHO_C" >&6; } -if test "${ac_cv_prog_TRUE+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 -else - if test -n "$TRUE"; then - ac_cv_prog_TRUE="$TRUE" # Let the user override the test. -else -as_save_IFS=$IFS; IFS=$PATH_SEPARATOR -for as_dir in $PATH -do - IFS=$as_save_IFS - test -z "$as_dir" && as_dir=. - for ac_exec_ext in '' $ac_executable_extensions; do - if { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_test_x "$as_dir/$ac_word$ac_exec_ext"; }; then - ac_cv_prog_TRUE="$ac_prog" - echo "$as_me:$LINENO: found $as_dir/$ac_word$ac_exec_ext" >&5 - break 2 - fi -done -done -IFS=$as_save_IFS - -fi -fi -TRUE=$ac_cv_prog_TRUE -if test -n "$TRUE"; then - { echo "$as_me:$LINENO: result: $TRUE" >&5 -echo "${ECHO_T}$TRUE" >&6; } -else - { echo "$as_me:$LINENO: result: no" >&5 -echo "${ECHO_T}no" >&6; } -fi - - - test -n "$TRUE" && break -done -test -n "$TRUE" || TRUE="/bin/true" - - -{ echo "$as_me:$LINENO: checking for inet_aton in -lc" >&5 -echo $ECHO_N "checking for inet_aton in -lc... $ECHO_C" >&6; } -if test "${ac_cv_lib_c_inet_aton+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 -else - ac_check_lib_save_LIBS=$LIBS -LIBS="-lc $LIBS" -cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ - -/* Override any GCC internal prototype to avoid an error. - Use char because int might match the return type of a GCC - builtin and then its argument prototype would still apply. */ -#ifdef __cplusplus -extern "C" -#endif -char inet_aton (); -int -main () -{ -return inet_aton (); - ; - return 0; -} -_ACEOF -rm -f conftest.$ac_objext conftest$ac_exeext -if { (ac_try="$ac_link" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_link") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest$ac_exeext && - $as_test_x conftest$ac_exeext; then - ac_cv_lib_c_inet_aton=yes -else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - ac_cv_lib_c_inet_aton=no -fi - -rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \ - conftest$ac_exeext conftest.$ac_ext -LIBS=$ac_check_lib_save_LIBS -fi -{ echo "$as_me:$LINENO: result: $ac_cv_lib_c_inet_aton" >&5 -echo "${ECHO_T}$ac_cv_lib_c_inet_aton" >&6; } -if test $ac_cv_lib_c_inet_aton = yes; then - $ac_cv_prog_TRUE -else - -{ echo "$as_me:$LINENO: checking for inet_aton in -lresolv" >&5 -echo $ECHO_N "checking for inet_aton in -lresolv... $ECHO_C" >&6; } -if test "${ac_cv_lib_resolv_inet_aton+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 -else - ac_check_lib_save_LIBS=$LIBS -LIBS="-lresolv $LIBS" -cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ - -/* Override any GCC internal prototype to avoid an error. - Use char because int might match the return type of a GCC - builtin and then its argument prototype would still apply. */ -#ifdef __cplusplus -extern "C" -#endif -char inet_aton (); -int -main () -{ -return inet_aton (); - ; - return 0; -} -_ACEOF -rm -f conftest.$ac_objext conftest$ac_exeext -if { (ac_try="$ac_link" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_link") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest$ac_exeext && - $as_test_x conftest$ac_exeext; then - ac_cv_lib_resolv_inet_aton=yes -else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - ac_cv_lib_resolv_inet_aton=no -fi +# LDSHARED is the ld *command* used to create shared library +# -- "cc -G" on SunOS 5.x, "ld -shared" on IRIX 5 +# (Shared libraries in this instance are shared modules to be loaded into +# Python, as opposed to building Python itself as a shared library.) +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking LDSHARED" >&5 +$as_echo_n "checking LDSHARED... " >&6; } +if test -z "$LDSHARED" +then + case $ac_sys_system/$ac_sys_release in + AIX*) + BLDSHARED="\$(srcdir)/Modules/ld_so_aix \$(CC) -bI:Modules/python.exp" + LDSHARED="\$(BINLIBDEST)/config/ld_so_aix \$(CC) -bI:\$(BINLIBDEST)/config/python.exp" + ;; + BeOS*) + BLDSHARED="\$(srcdir)/Modules/ld_so_beos $LDLIBRARY" + LDSHARED="\$(BINLIBDEST)/config/ld_so_beos \$(LIBDIR)/$LDLIBRARY" + ;; + IRIX/5*) LDSHARED="ld -shared";; + IRIX*/6*) LDSHARED="ld ${SGI_ABI} -shared -all";; + SunOS/5*) + if test "$GCC" = "yes" ; then + LDSHARED='$(CC) -shared' + LDCXXSHARED='$(CXX) -shared' + else + LDSHARED='$(CC) -G' + LDCXXSHARED='$(CXX) -G' + fi ;; + hp*|HP*) + if test "$GCC" = "yes" ; then + LDSHARED='$(CC) -shared' + LDCXXSHARED='$(CXX) -shared' + else + LDSHARED='ld -b' + fi ;; + OSF*) LDSHARED="ld -shared -expect_unresolved \"*\"";; + Darwin/1.3*) + LDSHARED='$(CC) $(LDFLAGS) -bundle' + LDCXXSHARED='$(CXX) $(LDFLAGS) -bundle' + if test "$enable_framework" ; then + # Link against the framework. All externals should be defined. + BLDSHARED="$LDSHARED "'$(PYTHONFRAMEWORKDIR)/Versions/$(VERSION)/$(PYTHONFRAMEWORK)' + LDSHARED="$LDSHARED "'$(PYTHONFRAMEWORKPREFIX)/$(PYTHONFRAMEWORKDIR)/Versions/$(VERSION)/$(PYTHONFRAMEWORK)' + LDCXXSHARED="$LDCXXSHARED "'$(PYTHONFRAMEWORKPREFIX)/$(PYTHONFRAMEWORKDIR)/Versions/$(VERSION)/$(PYTHONFRAMEWORK)' + else + # No framework. Ignore undefined symbols, assuming they come from Python + LDSHARED="$LDSHARED -undefined suppress" + LDCXXSHARED="$LDCXXSHARED -undefined suppress" + fi ;; + Darwin/1.4*|Darwin/5.*|Darwin/6.*) + LDSHARED='$(CC) $(LDFLAGS) -bundle' + LDCXXSHARED='$(CXX) $(LDFLAGS) -bundle' + if test "$enable_framework" ; then + # Link against the framework. All externals should be defined. + BLDSHARED="$LDSHARED "'$(PYTHONFRAMEWORKDIR)/Versions/$(VERSION)/$(PYTHONFRAMEWORK)' + LDSHARED="$LDSHARED "'$(PYTHONFRAMEWORKPREFIX)/$(PYTHONFRAMEWORKDIR)/Versions/$(VERSION)/$(PYTHONFRAMEWORK)' + LDCXXSHARED="$LDCXXSHARED "'$(PYTHONFRAMEWORKPREFIX)/$(PYTHONFRAMEWORKDIR)/Versions/$(VERSION)/$(PYTHONFRAMEWORK)' + else + # No framework, use the Python app as bundle-loader + BLDSHARED="$LDSHARED "'-bundle_loader $(BUILDPYTHON)' + LDSHARED="$LDSHARED "'-bundle_loader $(BINDIR)/python$(VERSION)$(EXE)' + LDCXXSHARED="$LDCXXSHARED "'-bundle_loader $(BINDIR)/python$(VERSION)$(EXE)' + fi ;; + Darwin/*) + # Use -undefined dynamic_lookup whenever possible (10.3 and later). + # This allows an extension to be used in any Python -rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \ - conftest$ac_exeext conftest.$ac_ext -LIBS=$ac_check_lib_save_LIBS + if test ${MACOSX_DEPLOYMENT_TARGET} '>' 10.2 + then + if test "${enable_universalsdk}"; then + LDFLAGS="${UNIVERSAL_ARCH_FLAGS} -isysroot ${UNIVERSALSDK} ${LDFLAGS}" + fi + LDSHARED='$(CC) $(LDFLAGS) -bundle -undefined dynamic_lookup' + LDCXXSHARED='$(CXX) $(LDFLAGS) -bundle -undefined dynamic_lookup' + BLDSHARED="$LDSHARED" + else + LDSHARED='$(CC) $(LDFLAGS) -bundle' + LDCXXSHARED='$(CXX) $(LDFLAGS) -bundle' + if test "$enable_framework" ; then + # Link against the framework. All externals should be defined. + BLDSHARED="$LDSHARED "'$(PYTHONFRAMEWORKDIR)/Versions/$(VERSION)/$(PYTHONFRAMEWORK)' + LDSHARED="$LDSHARED "'$(PYTHONFRAMEWORKPREFIX)/$(PYTHONFRAMEWORKDIR)/Versions/$(VERSION)/$(PYTHONFRAMEWORK)' + LDCXXSHARED="$LDCXXSHARED "'$(PYTHONFRAMEWORKPREFIX)/$(PYTHONFRAMEWORKDIR)/Versions/$(VERSION)/$(PYTHONFRAMEWORK)' + else + # No framework, use the Python app as bundle-loader + BLDSHARED="$LDSHARED "'-bundle_loader $(BUILDPYTHON)' + LDSHARED="$LDSHARED "'-bundle_loader $(BINDIR)/python$(VERSION)$(EXE)' + LDCXXSHARED="$LDCXXSHARED "'-bundle_loader $(BINDIR)/python$(VERSION)$(EXE)' + fi + fi + ;; + Linux*|GNU*|QNX*) + LDSHARED='$(CC) -shared' + LDCXXSHARED='$(CXX) -shared';; + BSD/OS*/4*) + LDSHARED="gcc -shared" + LDCXXSHARED="g++ -shared";; + FreeBSD*) + if [ "`$CC -dM -E - &5 -echo "${ECHO_T}$ac_cv_lib_resolv_inet_aton" >&6; } -if test $ac_cv_lib_resolv_inet_aton = yes; then - cat >>confdefs.h <<_ACEOF -#define HAVE_LIBRESOLV 1 -_ACEOF - - LIBS="-lresolv $LIBS" - +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $LDSHARED" >&5 +$as_echo "$LDSHARED" >&6; } +LDCXXSHARED=${LDCXXSHARED-$LDSHARED} +BLDSHARED=${BLDSHARED-$LDSHARED} +# CCSHARED are the C *flags* used to create objects to go into a shared +# library (module) -- this is only needed for a few systems +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking CCSHARED" >&5 +$as_echo_n "checking CCSHARED... " >&6; } +if test -z "$CCSHARED" +then + case $ac_sys_system/$ac_sys_release in + SunOS*) if test "$GCC" = yes; + then CCSHARED="-fPIC"; + elif test `uname -p` = sparc; + then CCSHARED="-xcode=pic32"; + else CCSHARED="-Kpic"; + fi;; + hp*|HP*) if test "$GCC" = yes; + then CCSHARED="-fPIC"; + else CCSHARED="+z"; + fi;; + Linux*|GNU*) CCSHARED="-fPIC";; + BSD/OS*/4*) CCSHARED="-fpic";; + FreeBSD*|NetBSD*|OpenBSD*|DragonFly*) CCSHARED="-fPIC";; + OpenUNIX*|UnixWare*) + if test "$GCC" = "yes" + then CCSHARED="-fPIC" + else CCSHARED="-KPIC" + fi;; + SCO_SV*) + if test "$GCC" = "yes" + then CCSHARED="-fPIC" + else CCSHARED="-Kpic -belf" + fi;; + IRIX*/6*) case $CC in + *gcc*) CCSHARED="-shared";; + *) CCSHARED="";; + esac;; + atheos*) CCSHARED="-fPIC";; + esac fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $CCSHARED" >&5 +$as_echo "$CCSHARED" >&6; } +# LINKFORSHARED are the flags passed to the $(CC) command that links +# the python executable -- this is only needed for a few systems +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking LINKFORSHARED" >&5 +$as_echo_n "checking LINKFORSHARED... " >&6; } +if test -z "$LINKFORSHARED" +then + case $ac_sys_system/$ac_sys_release in + AIX*) LINKFORSHARED='-Wl,-bE:Modules/python.exp -lld';; + hp*|HP*) + 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";; + # -u libsys_s pulls in all symbols in libsys + Darwin/*) + # -u _PyMac_Error is needed to pull in the mac toolbox glue, + # which is + # not used by the core itself but which needs to be in the core so + # that dynamically loaded extension modules have access to it. + # -prebind is no longer used, because it actually seems to give a + # slowdown in stead of a speedup, maybe due to the large number of + # dynamic loads Python does. - + LINKFORSHARED="$extra_undefs" + if test "$enable_framework" + then + LINKFORSHARED="$LINKFORSHARED "'$(PYTHONFRAMEWORKDIR)/Versions/$(VERSION)/$(PYTHONFRAMEWORK)' + fi + LINKFORSHARED="$LINKFORSHARED";; + OpenUNIX*|UnixWare*) LINKFORSHARED="-Wl,-Bexport";; + SCO_SV*) LINKFORSHARED="-Wl,-Bexport";; + ReliantUNIX*) LINKFORSHARED="-W1 -Blargedynsym";; + FreeBSD*|NetBSD*|OpenBSD*|DragonFly*) + if [ "`$CC -dM -E - &1 | grep export-dynamic >/dev/null + then + LINKFORSHARED="-Xlinker --export-dynamic" + fi;; + esac;; + CYGWIN*) + if test $enable_shared = "no" + then + LINKFORSHARED='-Wl,--out-implib=$(LDLIBRARY)' + fi;; + QNX*) + # -Wl,-E causes the symbols to be added to the dynamic + # symbol table so that they can be found when a module + # is loaded. -N 2048K causes the stack size to be set + # to 2048 kilobytes so that the stack doesn't overflow + # when running test_compile.py. + LINKFORSHARED='-Wl,-E -N 2048K';; + esac fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $LINKFORSHARED" >&5 +$as_echo "$LINKFORSHARED" >&6; } -# On Tru64, chflags seems to be present, but calling it will -# exit Python -{ echo "$as_me:$LINENO: checking for chflags" >&5 -echo $ECHO_N "checking for chflags... $ECHO_C" >&6; } -if test "${ac_cv_have_chflags+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 -else - if test "$cross_compiling" = yes; then - ac_cv_have_chflags=cross -else - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -[ -#include -#include -int main(int argc, char*argv[]) -{ - if(chflags(argv[0], 0) != 0) - return 1; - return 0; -} -] -_ACEOF -rm -f conftest$ac_exeext -if { (ac_try="$ac_link" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_link") 2>&5 - ac_status=$? - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { ac_try='./conftest$ac_exeext' - { (case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_try") 2>&5 - ac_status=$? - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); }; }; then - ac_cv_have_chflags=yes -else - echo "$as_me: program exited with status $ac_status" >&5 -echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 -( exit $ac_status ) -ac_cv_have_chflags=no -fi -rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext conftest.$ac_objext conftest.$ac_ext +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking CFLAGSFORSHARED" >&5 +$as_echo_n "checking CFLAGSFORSHARED... " >&6; } +if test ! "$LIBRARY" = "$LDLIBRARY" +then + case $ac_sys_system in + CYGWIN*) + # Cygwin needs CCSHARED when building extension DLLs + # but not when building the interpreter DLL. + CFLAGSFORSHARED='';; + *) + CFLAGSFORSHARED='$(CCSHARED)' + esac fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $CFLAGSFORSHARED" >&5 +$as_echo "$CFLAGSFORSHARED" >&6; } + +# SHLIBS are libraries (except -lc and -lm) to link to the python shared +# library (with --enable-shared). +# For platforms on which shared libraries are not allowed to have unresolved +# symbols, this must be set to $(LIBS) (expanded by make). We do this even +# if it is not required, since it creates a dependency of the shared library +# to LIBS. This, in turn, means that applications linking the shared libpython +# don't need to link LIBS explicitly. The default should be only changed +# on systems where this approach causes problems. +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking SHLIBS" >&5 +$as_echo_n "checking SHLIBS... " >&6; } +case "$ac_sys_system" in + *) + SHLIBS='$(LIBS)';; +esac +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $SHLIBS" >&5 +$as_echo "$SHLIBS" >&6; } -fi -{ echo "$as_me:$LINENO: result: $ac_cv_have_chflags" >&5 -echo "${ECHO_T}$ac_cv_have_chflags" >&6; } -if test "$ac_cv_have_chflags" = cross ; then - { echo "$as_me:$LINENO: checking for chflags" >&5 -echo $ECHO_N "checking for chflags... $ECHO_C" >&6; } -if test "${ac_cv_func_chflags+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 +# checks for libraries +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for dlopen in -ldl" >&5 +$as_echo_n "checking for dlopen in -ldl... " >&6; } +if test "${ac_cv_lib_dl_dlopen+set}" = set; then : + $as_echo_n "(cached) " >&6 else - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF + ac_check_lib_save_LIBS=$LIBS +LIBS="-ldl $LIBS" +cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ -/* Define chflags to an innocuous variant, in case declares chflags. - For example, HP-UX 11i declares gettimeofday. */ -#define chflags innocuous_chflags - -/* System header to define __stub macros and hopefully few prototypes, - which can conflict with char chflags (); below. - Prefer to if __STDC__ is defined, since - exists even on freestanding compilers. */ - -#ifdef __STDC__ -# include -#else -# include -#endif - -#undef chflags /* Override any GCC internal prototype to avoid an error. Use char because int might match the return type of a GCC @@ -19304,158 +7862,44 @@ #ifdef __cplusplus extern "C" #endif -char chflags (); -/* The GNU C library defines this for functions which it implements - to always fail with ENOSYS. Some functions are actually named - something starting with __ and the normal name is an alias. */ -#if defined __stub_chflags || defined __stub___chflags -choke me -#endif - +char dlopen (); int main () { -return chflags (); +return dlopen (); ; return 0; } _ACEOF -rm -f conftest.$ac_objext conftest$ac_exeext -if { (ac_try="$ac_link" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_link") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest$ac_exeext && - $as_test_x conftest$ac_exeext; then - ac_cv_func_chflags=yes -else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - ac_cv_func_chflags=no -fi - -rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \ - conftest$ac_exeext conftest.$ac_ext -fi -{ echo "$as_me:$LINENO: result: $ac_cv_func_chflags" >&5 -echo "${ECHO_T}$ac_cv_func_chflags" >&6; } -if test $ac_cv_func_chflags = yes; then - ac_cv_have_chflags="yes" +if ac_fn_c_try_link "$LINENO"; then : + ac_cv_lib_dl_dlopen=yes else - ac_cv_have_chflags="no" -fi - + ac_cv_lib_dl_dlopen=no fi -if test "$ac_cv_have_chflags" = yes ; then - -cat >>confdefs.h <<\_ACEOF -#define HAVE_CHFLAGS 1 -_ACEOF - +rm -f core conftest.err conftest.$ac_objext \ + conftest$ac_exeext conftest.$ac_ext +LIBS=$ac_check_lib_save_LIBS fi - -{ echo "$as_me:$LINENO: checking for lchflags" >&5 -echo $ECHO_N "checking for lchflags... $ECHO_C" >&6; } -if test "${ac_cv_have_lchflags+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 -else - if test "$cross_compiling" = yes; then - ac_cv_have_lchflags=cross -else - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -[ -#include -#include -int main(int argc, char*argv[]) -{ - if(lchflags(argv[0], 0) != 0) - return 1; - return 0; -} -] +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_lib_dl_dlopen" >&5 +$as_echo "$ac_cv_lib_dl_dlopen" >&6; } +if test "x$ac_cv_lib_dl_dlopen" = x""yes; then : + cat >>confdefs.h <<_ACEOF +#define HAVE_LIBDL 1 _ACEOF -rm -f conftest$ac_exeext -if { (ac_try="$ac_link" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_link") 2>&5 - ac_status=$? - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { ac_try='./conftest$ac_exeext' - { (case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_try") 2>&5 - ac_status=$? - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); }; }; then - ac_cv_have_lchflags=yes -else - echo "$as_me: program exited with status $ac_status" >&5 -echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - -( exit $ac_status ) -ac_cv_have_lchflags=no -fi -rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext conftest.$ac_objext conftest.$ac_ext -fi - + LIBS="-ldl $LIBS" fi -{ echo "$as_me:$LINENO: result: $ac_cv_have_lchflags" >&5 -echo "${ECHO_T}$ac_cv_have_lchflags" >&6; } -if test "$ac_cv_have_lchflags" = cross ; then - { echo "$as_me:$LINENO: checking for lchflags" >&5 -echo $ECHO_N "checking for lchflags... $ECHO_C" >&6; } -if test "${ac_cv_func_lchflags+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 + # Dynamic linking for SunOS/Solaris and SYSV +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for shl_load in -ldld" >&5 +$as_echo_n "checking for shl_load in -ldld... " >&6; } +if test "${ac_cv_lib_dld_shl_load+set}" = set; then : + $as_echo_n "(cached) " >&6 else - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF + ac_check_lib_save_LIBS=$LIBS +LIBS="-ldld $LIBS" +cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ -/* Define lchflags to an innocuous variant, in case declares lchflags. - For example, HP-UX 11i declares gettimeofday. */ -#define lchflags innocuous_lchflags - -/* System header to define __stub macros and hopefully few prototypes, - which can conflict with char lchflags (); below. - Prefer to if __STDC__ is defined, since - exists even on freestanding compilers. */ - -#ifdef __STDC__ -# include -#else -# include -#endif - -#undef lchflags /* Override any GCC internal prototype to avoid an error. Use char because int might match the return type of a GCC @@ -19463,89 +7907,45 @@ #ifdef __cplusplus extern "C" #endif -char lchflags (); -/* The GNU C library defines this for functions which it implements - to always fail with ENOSYS. Some functions are actually named - something starting with __ and the normal name is an alias. */ -#if defined __stub_lchflags || defined __stub___lchflags -choke me -#endif - +char shl_load (); int main () { -return lchflags (); +return shl_load (); ; return 0; } _ACEOF -rm -f conftest.$ac_objext conftest$ac_exeext -if { (ac_try="$ac_link" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_link") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest$ac_exeext && - $as_test_x conftest$ac_exeext; then - ac_cv_func_lchflags=yes -else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - ac_cv_func_lchflags=no -fi - -rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \ - conftest$ac_exeext conftest.$ac_ext -fi -{ echo "$as_me:$LINENO: result: $ac_cv_func_lchflags" >&5 -echo "${ECHO_T}$ac_cv_func_lchflags" >&6; } -if test $ac_cv_func_lchflags = yes; then - ac_cv_have_lchflags="yes" +if ac_fn_c_try_link "$LINENO"; then : + ac_cv_lib_dld_shl_load=yes else - ac_cv_have_lchflags="no" + ac_cv_lib_dld_shl_load=no fi - +rm -f core conftest.err conftest.$ac_objext \ + conftest$ac_exeext conftest.$ac_ext +LIBS=$ac_check_lib_save_LIBS fi -if test "$ac_cv_have_lchflags" = yes ; then - -cat >>confdefs.h <<\_ACEOF -#define HAVE_LCHFLAGS 1 +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_lib_dld_shl_load" >&5 +$as_echo "$ac_cv_lib_dld_shl_load" >&6; } +if test "x$ac_cv_lib_dld_shl_load" = x""yes; then : + cat >>confdefs.h <<_ACEOF +#define HAVE_LIBDLD 1 _ACEOF -fi + LIBS="-ldld $LIBS" -case $ac_sys_system/$ac_sys_release in -Darwin/*) - _CUR_CFLAGS="${CFLAGS}" - _CUR_LDFLAGS="${LDFLAGS}" - CFLAGS="${CFLAGS} -Wl,-search_paths_first" - LDFLAGS="${LDFLAGS} -Wl,-search_paths_first -L/usr/local/lib" - ;; -esac +fi + # Dynamic linking for HP-UX -{ echo "$as_me:$LINENO: checking for inflateCopy in -lz" >&5 -echo $ECHO_N "checking for inflateCopy in -lz... $ECHO_C" >&6; } -if test "${ac_cv_lib_z_inflateCopy+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 +# only check for sem_init if thread support is requested +if test "$with_threads" = "yes" -o -z "$with_threads"; then + { $as_echo "$as_me:${as_lineno-$LINENO}: checking for library containing sem_init" >&5 +$as_echo_n "checking for library containing sem_init... " >&6; } +if test "${ac_cv_search_sem_init+set}" = set; then : + $as_echo_n "(cached) " >&6 else - ac_check_lib_save_LIBS=$LIBS -LIBS="-lz $LIBS" -cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF + ac_func_search_save_LIBS=$LIBS +cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ /* Override any GCC internal prototype to avoid an error. @@ -19554,330 +7954,136 @@ #ifdef __cplusplus extern "C" #endif -char inflateCopy (); +char sem_init (); int main () { -return inflateCopy (); +return sem_init (); ; return 0; } _ACEOF -rm -f conftest.$ac_objext conftest$ac_exeext -if { (ac_try="$ac_link" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_link") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest$ac_exeext && - $as_test_x conftest$ac_exeext; then - ac_cv_lib_z_inflateCopy=yes -else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - ac_cv_lib_z_inflateCopy=no -fi - -rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \ - conftest$ac_exeext conftest.$ac_ext -LIBS=$ac_check_lib_save_LIBS -fi -{ echo "$as_me:$LINENO: result: $ac_cv_lib_z_inflateCopy" >&5 -echo "${ECHO_T}$ac_cv_lib_z_inflateCopy" >&6; } -if test $ac_cv_lib_z_inflateCopy = yes; then - -cat >>confdefs.h <<\_ACEOF -#define HAVE_ZLIB_COPY 1 -_ACEOF - +for ac_lib in '' pthread rt posix4; do + if test -z "$ac_lib"; then + ac_res="none required" + else + ac_res=-l$ac_lib + LIBS="-l$ac_lib $ac_func_search_save_LIBS" + fi + if ac_fn_c_try_link "$LINENO"; then : + ac_cv_search_sem_init=$ac_res fi - - -case $ac_sys_system/$ac_sys_release in -Darwin/*) - CFLAGS="${_CUR_CFLAGS}" - LDFLAGS="${_CUR_LDFLAGS}" - ;; -esac - -{ echo "$as_me:$LINENO: checking for hstrerror" >&5 -echo $ECHO_N "checking for hstrerror... $ECHO_C" >&6; } -cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ - -#include "confdefs.h" -#include - -int -main () -{ -void* p = hstrerror; hstrerror(0) - ; - return 0; -} -_ACEOF -rm -f conftest.$ac_objext conftest$ac_exeext -if { (ac_try="$ac_link" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_link") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest$ac_exeext && - $as_test_x conftest$ac_exeext; then - -cat >>confdefs.h <<\_ACEOF -#define HAVE_HSTRERROR 1 -_ACEOF - - { echo "$as_me:$LINENO: result: yes" >&5 -echo "${ECHO_T}yes" >&6; } -else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - { echo "$as_me:$LINENO: result: no" >&5 -echo "${ECHO_T}no" >&6; } - +rm -f core conftest.err conftest.$ac_objext \ + conftest$ac_exeext + if test "${ac_cv_search_sem_init+set}" = set; then : + break fi +done +if test "${ac_cv_search_sem_init+set}" = set; then : -rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \ - conftest$ac_exeext conftest.$ac_ext - -{ echo "$as_me:$LINENO: checking for inet_aton" >&5 -echo $ECHO_N "checking for inet_aton... $ECHO_C" >&6; } -cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ - -#include "confdefs.h" -#include -#include -#include -#include - -int -main () -{ -void* p = inet_aton;inet_aton(0,0) - ; - return 0; -} -_ACEOF -rm -f conftest.$ac_objext conftest$ac_exeext -if { (ac_try="$ac_link" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_link") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest$ac_exeext && - $as_test_x conftest$ac_exeext; then - -cat >>confdefs.h <<\_ACEOF -#define HAVE_INET_ATON 1 -_ACEOF - - { echo "$as_me:$LINENO: result: yes" >&5 -echo "${ECHO_T}yes" >&6; } else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - { echo "$as_me:$LINENO: result: no" >&5 -echo "${ECHO_T}no" >&6; } - + ac_cv_search_sem_init=no +fi +rm conftest.$ac_ext +LIBS=$ac_func_search_save_LIBS fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_search_sem_init" >&5 +$as_echo "$ac_cv_search_sem_init" >&6; } +ac_res=$ac_cv_search_sem_init +if test "$ac_res" != no; then : + test "$ac_res" = "none required" || LIBS="$ac_res $LIBS" -rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \ - conftest$ac_exeext conftest.$ac_ext +fi + # 'Real Time' functions on Solaris + # posix4 on Solaris 2.6 + # pthread (first!) on Linux +fi -{ echo "$as_me:$LINENO: checking for inet_pton" >&5 -echo $ECHO_N "checking for inet_pton... $ECHO_C" >&6; } -cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF +# check if we need libintl for locale functions +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for textdomain in -lintl" >&5 +$as_echo_n "checking for textdomain in -lintl... " >&6; } +if test "${ac_cv_lib_intl_textdomain+set}" = set; then : + $as_echo_n "(cached) " >&6 +else + ac_check_lib_save_LIBS=$LIBS +LIBS="-lintl $LIBS" +cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ -#include "confdefs.h" -#include -#include -#include -#include - +/* Override any GCC internal prototype to avoid an error. + Use char because int might match the return type of a GCC + builtin and then its argument prototype would still apply. */ +#ifdef __cplusplus +extern "C" +#endif +char textdomain (); int main () { -void* p = inet_pton +return textdomain (); ; return 0; } _ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - -cat >>confdefs.h <<\_ACEOF -#define HAVE_INET_PTON 1 -_ACEOF - - { echo "$as_me:$LINENO: result: yes" >&5 -echo "${ECHO_T}yes" >&6; } +if ac_fn_c_try_link "$LINENO"; then : + ac_cv_lib_intl_textdomain=yes else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 + ac_cv_lib_intl_textdomain=no +fi +rm -f core conftest.err conftest.$ac_objext \ + conftest$ac_exeext conftest.$ac_ext +LIBS=$ac_check_lib_save_LIBS +fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_lib_intl_textdomain" >&5 +$as_echo "$ac_cv_lib_intl_textdomain" >&6; } +if test "x$ac_cv_lib_intl_textdomain" = x""yes; then : - { echo "$as_me:$LINENO: result: no" >&5 -echo "${ECHO_T}no" >&6; } +$as_echo "#define WITH_LIBINTL 1" >>confdefs.h fi -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext -# On some systems, setgroups is in unistd.h, on others, in grp.h -{ echo "$as_me:$LINENO: checking for setgroups" >&5 -echo $ECHO_N "checking for setgroups... $ECHO_C" >&6; } -cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF +# checks for system dependent C++ extensions support +case "$ac_sys_system" in + AIX*) { $as_echo "$as_me:${as_lineno-$LINENO}: checking for genuine AIX C++ extensions support" >&5 +$as_echo_n "checking for genuine AIX C++ extensions support... " >&6; } + cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ - -#include "confdefs.h" -#include -#ifdef HAVE_GRP_H -#include -#endif - +#include "/usr/lpp/xlC/include/load.h" int main () { -void* p = setgroups +loadAndInit("", 0, "") ; return 0; } _ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then +if ac_fn_c_try_link "$LINENO"; then : -cat >>confdefs.h <<\_ACEOF -#define HAVE_SETGROUPS 1 -_ACEOF +$as_echo "#define AIX_GENUINE_CPLUSPLUS 1" >>confdefs.h - { echo "$as_me:$LINENO: result: yes" >&5 -echo "${ECHO_T}yes" >&6; } + { $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +$as_echo "yes" >&6; } else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - { echo "$as_me:$LINENO: result: no" >&5 -echo "${ECHO_T}no" >&6; } - + { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 +$as_echo "no" >&6; } fi +rm -f core conftest.err conftest.$ac_objext \ + conftest$ac_exeext conftest.$ac_ext;; + *) ;; +esac -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext - -# check for openpty and forkpty - - -for ac_func in openpty -do -as_ac_var=`echo "ac_cv_func_$ac_func" | $as_tr_sh` -{ echo "$as_me:$LINENO: checking for $ac_func" >&5 -echo $ECHO_N "checking for $ac_func... $ECHO_C" >&6; } -if { as_var=$as_ac_var; eval "test \"\${$as_var+set}\" = set"; }; then - echo $ECHO_N "(cached) $ECHO_C" >&6 +# Most SVR4 platforms (e.g. Solaris) need -lsocket and -lnsl. +# BeOS' sockets are stashed in libnet. +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for t_open in -lnsl" >&5 +$as_echo_n "checking for t_open in -lnsl... " >&6; } +if test "${ac_cv_lib_nsl_t_open+set}" = set; then : + $as_echo_n "(cached) " >&6 else - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF + ac_check_lib_save_LIBS=$LIBS +LIBS="-lnsl $LIBS" +cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ -/* Define $ac_func to an innocuous variant, in case declares $ac_func. - For example, HP-UX 11i declares gettimeofday. */ -#define $ac_func innocuous_$ac_func - -/* System header to define __stub macros and hopefully few prototypes, - which can conflict with char $ac_func (); below. - Prefer to if __STDC__ is defined, since - exists even on freestanding compilers. */ - -#ifdef __STDC__ -# include -#else -# include -#endif - -#undef $ac_func /* Override any GCC internal prototype to avoid an error. Use char because int might match the return type of a GCC @@ -19885,72 +8091,38 @@ #ifdef __cplusplus extern "C" #endif -char $ac_func (); -/* The GNU C library defines this for functions which it implements - to always fail with ENOSYS. Some functions are actually named - something starting with __ and the normal name is an alias. */ -#if defined __stub_$ac_func || defined __stub___$ac_func -choke me -#endif - +char t_open (); int main () { -return $ac_func (); +return t_open (); ; return 0; } _ACEOF -rm -f conftest.$ac_objext conftest$ac_exeext -if { (ac_try="$ac_link" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_link") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest$ac_exeext && - $as_test_x conftest$ac_exeext; then - eval "$as_ac_var=yes" +if ac_fn_c_try_link "$LINENO"; then : + ac_cv_lib_nsl_t_open=yes else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - eval "$as_ac_var=no" + ac_cv_lib_nsl_t_open=no fi - -rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \ - conftest$ac_exeext conftest.$ac_ext +rm -f core conftest.err conftest.$ac_objext \ + conftest$ac_exeext conftest.$ac_ext +LIBS=$ac_check_lib_save_LIBS fi -ac_res=`eval echo '${'$as_ac_var'}'` - { echo "$as_me:$LINENO: result: $ac_res" >&5 -echo "${ECHO_T}$ac_res" >&6; } -if test `eval echo '${'$as_ac_var'}'` = yes; then - cat >>confdefs.h <<_ACEOF -#define `echo "HAVE_$ac_func" | $as_tr_cpp` 1 -_ACEOF - -else - { echo "$as_me:$LINENO: checking for openpty in -lutil" >&5 -echo $ECHO_N "checking for openpty in -lutil... $ECHO_C" >&6; } -if test "${ac_cv_lib_util_openpty+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_lib_nsl_t_open" >&5 +$as_echo "$ac_cv_lib_nsl_t_open" >&6; } +if test "x$ac_cv_lib_nsl_t_open" = x""yes; then : + LIBS="-lnsl $LIBS" +fi + # SVR4 +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for socket in -lsocket" >&5 +$as_echo_n "checking for socket in -lsocket... " >&6; } +if test "${ac_cv_lib_socket_socket+set}" = set; then : + $as_echo_n "(cached) " >&6 else ac_check_lib_save_LIBS=$LIBS -LIBS="-lutil $LIBS" -cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF +LIBS="-lsocket $LIBS $LIBS" +cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ /* Override any GCC internal prototype to avoid an error. @@ -19959,65 +8131,41 @@ #ifdef __cplusplus extern "C" #endif -char openpty (); +char socket (); int main () { -return openpty (); +return socket (); ; return 0; } _ACEOF -rm -f conftest.$ac_objext conftest$ac_exeext -if { (ac_try="$ac_link" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_link") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest$ac_exeext && - $as_test_x conftest$ac_exeext; then - ac_cv_lib_util_openpty=yes +if ac_fn_c_try_link "$LINENO"; then : + ac_cv_lib_socket_socket=yes else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - ac_cv_lib_util_openpty=no + ac_cv_lib_socket_socket=no fi - -rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \ - conftest$ac_exeext conftest.$ac_ext +rm -f core conftest.err conftest.$ac_objext \ + conftest$ac_exeext conftest.$ac_ext LIBS=$ac_check_lib_save_LIBS fi -{ echo "$as_me:$LINENO: result: $ac_cv_lib_util_openpty" >&5 -echo "${ECHO_T}$ac_cv_lib_util_openpty" >&6; } -if test $ac_cv_lib_util_openpty = yes; then - cat >>confdefs.h <<\_ACEOF -#define HAVE_OPENPTY 1 -_ACEOF - LIBS="$LIBS -lutil" -else - { echo "$as_me:$LINENO: checking for openpty in -lbsd" >&5 -echo $ECHO_N "checking for openpty in -lbsd... $ECHO_C" >&6; } -if test "${ac_cv_lib_bsd_openpty+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_lib_socket_socket" >&5 +$as_echo "$ac_cv_lib_socket_socket" >&6; } +if test "x$ac_cv_lib_socket_socket" = x""yes; then : + LIBS="-lsocket $LIBS" +fi + # SVR4 sockets + +case "$ac_sys_system" in +BeOS*) +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for socket in -lnet" >&5 +$as_echo_n "checking for socket in -lnet... " >&6; } +if test "${ac_cv_lib_net_socket+set}" = set; then : + $as_echo_n "(cached) " >&6 else ac_check_lib_save_LIBS=$LIBS -LIBS="-lbsd $LIBS" -cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF +LIBS="-lnet $LIBS $LIBS" +cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ /* Override any GCC internal prototype to avoid an error. @@ -20026,526 +8174,472 @@ #ifdef __cplusplus extern "C" #endif -char openpty (); +char socket (); int main () { -return openpty (); +return socket (); ; return 0; } _ACEOF -rm -f conftest.$ac_objext conftest$ac_exeext -if { (ac_try="$ac_link" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; +if ac_fn_c_try_link "$LINENO"; then : + ac_cv_lib_net_socket=yes +else + ac_cv_lib_net_socket=no +fi +rm -f core conftest.err conftest.$ac_objext \ + conftest$ac_exeext conftest.$ac_ext +LIBS=$ac_check_lib_save_LIBS +fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_lib_net_socket" >&5 +$as_echo "$ac_cv_lib_net_socket" >&6; } +if test "x$ac_cv_lib_net_socket" = x""yes; then : + LIBS="-lnet $LIBS" +fi + # BeOS +;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_link") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest$ac_exeext && - $as_test_x conftest$ac_exeext; then - ac_cv_lib_bsd_openpty=yes + +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for --with-libs" >&5 +$as_echo_n "checking for --with-libs... " >&6; } + +# Check whether --with-libs was given. +if test "${with_libs+set}" = set; then : + withval=$with_libs; +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $withval" >&5 +$as_echo "$withval" >&6; } +LIBS="$withval $LIBS" + +else + { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 +$as_echo "no" >&6; } +fi + + +if test -n "$ac_tool_prefix"; then + # Extract the first word of "${ac_tool_prefix}pkg-config", so it can be a program name with args. +set dummy ${ac_tool_prefix}pkg-config; ac_word=$2 +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 +$as_echo_n "checking for $ac_word... " >&6; } +if test "${ac_cv_path_PKG_CONFIG+set}" = set; then : + $as_echo_n "(cached) " >&6 +else + case $PKG_CONFIG in + [\\/]* | ?:[\\/]*) + ac_cv_path_PKG_CONFIG="$PKG_CONFIG" # Let the user override the test with a path. + ;; + *) + as_save_IFS=$IFS; IFS=$PATH_SEPARATOR +for as_dir in $PATH +do + IFS=$as_save_IFS + test -z "$as_dir" && as_dir=. + for ac_exec_ext in '' $ac_executable_extensions; do + if { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_test_x "$as_dir/$ac_word$ac_exec_ext"; }; then + ac_cv_path_PKG_CONFIG="$as_dir/$ac_word$ac_exec_ext" + $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 + break 2 + fi +done + done +IFS=$as_save_IFS + + ;; +esac +fi +PKG_CONFIG=$ac_cv_path_PKG_CONFIG +if test -n "$PKG_CONFIG"; then + { $as_echo "$as_me:${as_lineno-$LINENO}: result: $PKG_CONFIG" >&5 +$as_echo "$PKG_CONFIG" >&6; } +else + { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 +$as_echo "no" >&6; } +fi + + +fi +if test -z "$ac_cv_path_PKG_CONFIG"; then + ac_pt_PKG_CONFIG=$PKG_CONFIG + # Extract the first word of "pkg-config", so it can be a program name with args. +set dummy pkg-config; ac_word=$2 +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 +$as_echo_n "checking for $ac_word... " >&6; } +if test "${ac_cv_path_ac_pt_PKG_CONFIG+set}" = set; then : + $as_echo_n "(cached) " >&6 +else + case $ac_pt_PKG_CONFIG in + [\\/]* | ?:[\\/]*) + ac_cv_path_ac_pt_PKG_CONFIG="$ac_pt_PKG_CONFIG" # Let the user override the test with a path. + ;; + *) + as_save_IFS=$IFS; IFS=$PATH_SEPARATOR +for as_dir in $PATH +do + IFS=$as_save_IFS + test -z "$as_dir" && as_dir=. + for ac_exec_ext in '' $ac_executable_extensions; do + if { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_test_x "$as_dir/$ac_word$ac_exec_ext"; }; then + ac_cv_path_ac_pt_PKG_CONFIG="$as_dir/$ac_word$ac_exec_ext" + $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 + break 2 + fi +done + done +IFS=$as_save_IFS + + ;; +esac +fi +ac_pt_PKG_CONFIG=$ac_cv_path_ac_pt_PKG_CONFIG +if test -n "$ac_pt_PKG_CONFIG"; then + { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_pt_PKG_CONFIG" >&5 +$as_echo "$ac_pt_PKG_CONFIG" >&6; } +else + { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 +$as_echo "no" >&6; } +fi + + if test "x$ac_pt_PKG_CONFIG" = x; then + PKG_CONFIG="" + else + case $cross_compiling:$ac_tool_warned in +yes:) +{ $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: using cross tools not prefixed with host triplet" >&5 +$as_echo "$as_me: WARNING: using cross tools not prefixed with host triplet" >&2;} +ac_tool_warned=yes ;; +esac + PKG_CONFIG=$ac_pt_PKG_CONFIG + fi else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - ac_cv_lib_bsd_openpty=no + PKG_CONFIG="$ac_cv_path_PKG_CONFIG" fi -rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \ - conftest$ac_exeext conftest.$ac_ext -LIBS=$ac_check_lib_save_LIBS -fi -{ echo "$as_me:$LINENO: result: $ac_cv_lib_bsd_openpty" >&5 -echo "${ECHO_T}$ac_cv_lib_bsd_openpty" >&6; } -if test $ac_cv_lib_bsd_openpty = yes; then - cat >>confdefs.h <<\_ACEOF -#define HAVE_OPENPTY 1 -_ACEOF - LIBS="$LIBS -lbsd" -fi +# Check for use of the system expat library +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for --with-system-expat" >&5 +$as_echo_n "checking for --with-system-expat... " >&6; } +# Check whether --with-system_expat was given. +if test "${with_system_expat+set}" = set; then : + withval=$with_system_expat; fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $with_system_expat" >&5 +$as_echo "$with_system_expat" >&6; } + +# Check for use of the system libffi library +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for --with-system-ffi" >&5 +$as_echo_n "checking for --with-system-ffi... " >&6; } + +# Check whether --with-system_ffi was given. +if test "${with_system_ffi+set}" = set; then : + withval=$with_system_ffi; fi -done -for ac_func in forkpty -do -as_ac_var=`echo "ac_cv_func_$ac_func" | $as_tr_sh` -{ echo "$as_me:$LINENO: checking for $ac_func" >&5 -echo $ECHO_N "checking for $ac_func... $ECHO_C" >&6; } -if { as_var=$as_ac_var; eval "test \"\${$as_var+set}\" = set"; }; then - echo $ECHO_N "(cached) $ECHO_C" >&6 +if test "$with_system_ffi" = "yes" && test -n "$PKG_CONFIG"; then + LIBFFI_INCLUDEDIR="`"$PKG_CONFIG" libffi --cflags-only-I 2>/dev/null | sed -e 's/^-I//;s/ *$//'`" else - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -/* Define $ac_func to an innocuous variant, in case declares $ac_func. - For example, HP-UX 11i declares gettimeofday. */ -#define $ac_func innocuous_$ac_func - -/* System header to define __stub macros and hopefully few prototypes, - which can conflict with char $ac_func (); below. - Prefer to if __STDC__ is defined, since - exists even on freestanding compilers. */ + LIBFFI_INCLUDEDIR="" +fi -#ifdef __STDC__ -# include -#else -# include -#endif -#undef $ac_func +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $with_system_ffi" >&5 +$as_echo "$with_system_ffi" >&6; } -/* Override any GCC internal prototype to avoid an error. - Use char because int might match the return type of a GCC - builtin and then its argument prototype would still apply. */ -#ifdef __cplusplus -extern "C" -#endif -char $ac_func (); -/* The GNU C library defines this for functions which it implements - to always fail with ENOSYS. Some functions are actually named - something starting with __ and the normal name is an alias. */ -#if defined __stub_$ac_func || defined __stub___$ac_func -choke me -#endif +# Check for --with-dbmliborder +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for --with-dbmliborder" >&5 +$as_echo_n "checking for --with-dbmliborder... " >&6; } -int -main () -{ -return $ac_func (); - ; - return 0; -} -_ACEOF -rm -f conftest.$ac_objext conftest$ac_exeext -if { (ac_try="$ac_link" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_link") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest$ac_exeext && - $as_test_x conftest$ac_exeext; then - eval "$as_ac_var=yes" +# Check whether --with-dbmliborder was given. +if test "${with_dbmliborder+set}" = set; then : + withval=$with_dbmliborder; +if test x$with_dbmliborder = xyes +then +as_fn_error "proper usage is --with-dbmliborder=db1:db2:..." "$LINENO" 5 else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 + for db in `echo $with_dbmliborder | sed 's/:/ /g'`; do + if test x$db != xndbm && test x$db != xgdbm && test x$db != xbdb + then + as_fn_error "proper usage is --with-dbmliborder=db1:db2:..." "$LINENO" 5 + fi + done +fi +fi + +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $with_dbmliborder" >&5 +$as_echo "$with_dbmliborder" >&6; } + +# Determine if signalmodule should be used. - eval "$as_ac_var=no" + +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for --with-signal-module" >&5 +$as_echo_n "checking for --with-signal-module... " >&6; } + +# Check whether --with-signal-module was given. +if test "${with_signal_module+set}" = set; then : + withval=$with_signal_module; fi -rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \ - conftest$ac_exeext conftest.$ac_ext + +if test -z "$with_signal_module" +then with_signal_module="yes" fi -ac_res=`eval echo '${'$as_ac_var'}'` - { echo "$as_me:$LINENO: result: $ac_res" >&5 -echo "${ECHO_T}$ac_res" >&6; } -if test `eval echo '${'$as_ac_var'}'` = yes; then - cat >>confdefs.h <<_ACEOF -#define `echo "HAVE_$ac_func" | $as_tr_cpp` 1 -_ACEOF +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $with_signal_module" >&5 +$as_echo "$with_signal_module" >&6; } +if test "${with_signal_module}" = "yes"; then + USE_SIGNAL_MODULE="" + SIGNAL_OBJS="" else - { echo "$as_me:$LINENO: checking for forkpty in -lutil" >&5 -echo $ECHO_N "checking for forkpty in -lutil... $ECHO_C" >&6; } -if test "${ac_cv_lib_util_forkpty+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 -else - ac_check_lib_save_LIBS=$LIBS -LIBS="-lutil $LIBS" -cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ + USE_SIGNAL_MODULE="#" + SIGNAL_OBJS="Parser/intrcheck.o Python/sigcheck.o" +fi -/* Override any GCC internal prototype to avoid an error. - Use char because int might match the return type of a GCC - builtin and then its argument prototype would still apply. */ -#ifdef __cplusplus -extern "C" -#endif -char forkpty (); -int -main () -{ -return forkpty (); - ; - return 0; -} -_ACEOF -rm -f conftest.$ac_objext conftest$ac_exeext -if { (ac_try="$ac_link" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_link") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest$ac_exeext && - $as_test_x conftest$ac_exeext; then - ac_cv_lib_util_forkpty=yes -else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 +# This is used to generate Setup.config - ac_cv_lib_util_forkpty=no -fi +USE_THREAD_MODULE="" -rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \ - conftest$ac_exeext conftest.$ac_ext -LIBS=$ac_check_lib_save_LIBS +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for --with-dec-threads" >&5 +$as_echo_n "checking for --with-dec-threads... " >&6; } + + +# Check whether --with-dec-threads was given. +if test "${with_dec_threads+set}" = set; then : + withval=$with_dec_threads; +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $withval" >&5 +$as_echo "$withval" >&6; } +LDLAST=-threads +if test "${with_thread+set}" != set; then + with_thread="$withval"; fi -{ echo "$as_me:$LINENO: result: $ac_cv_lib_util_forkpty" >&5 -echo "${ECHO_T}$ac_cv_lib_util_forkpty" >&6; } -if test $ac_cv_lib_util_forkpty = yes; then - cat >>confdefs.h <<\_ACEOF -#define HAVE_FORKPTY 1 -_ACEOF - LIBS="$LIBS -lutil" -else - { echo "$as_me:$LINENO: checking for forkpty in -lbsd" >&5 -echo $ECHO_N "checking for forkpty in -lbsd... $ECHO_C" >&6; } -if test "${ac_cv_lib_bsd_forkpty+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 else - ac_check_lib_save_LIBS=$LIBS -LIBS="-lbsd $LIBS" -cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ + { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 +$as_echo "no" >&6; } +fi -/* Override any GCC internal prototype to avoid an error. - Use char because int might match the return type of a GCC - builtin and then its argument prototype would still apply. */ -#ifdef __cplusplus -extern "C" -#endif -char forkpty (); -int -main () -{ -return forkpty (); - ; - return 0; -} -_ACEOF -rm -f conftest.$ac_objext conftest$ac_exeext -if { (ac_try="$ac_link" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_link") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest$ac_exeext && - $as_test_x conftest$ac_exeext; then - ac_cv_lib_bsd_forkpty=yes -else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - ac_cv_lib_bsd_forkpty=no -fi +# Templates for things AC_DEFINEd more than once. +# For a single AC_DEFINE, no template is needed. -rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \ - conftest$ac_exeext conftest.$ac_ext -LIBS=$ac_check_lib_save_LIBS -fi -{ echo "$as_me:$LINENO: result: $ac_cv_lib_bsd_forkpty" >&5 -echo "${ECHO_T}$ac_cv_lib_bsd_forkpty" >&6; } -if test $ac_cv_lib_bsd_forkpty = yes; then - cat >>confdefs.h <<\_ACEOF -#define HAVE_FORKPTY 1 -_ACEOF - LIBS="$LIBS -lbsd" + + + +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for --with-threads" >&5 +$as_echo_n "checking for --with-threads... " >&6; } + +# Check whether --with-threads was given. +if test "${with_threads+set}" = set; then : + withval=$with_threads; fi +# --with-thread is deprecated, but check for it anyway + +# Check whether --with-thread was given. +if test "${with_thread+set}" = set; then : + withval=$with_thread; with_threads=$with_thread fi +if test -z "$with_threads" +then with_threads="yes" fi -done +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $with_threads" >&5 +$as_echo "$with_threads" >&6; } -# Stuff for expat. +if test "$with_threads" = "no" +then + USE_THREAD_MODULE="#" +elif test "$ac_cv_pthread_is_default" = yes +then + $as_echo "#define WITH_THREAD 1" >>confdefs.h -for ac_func in memmove -do -as_ac_var=`echo "ac_cv_func_$ac_func" | $as_tr_sh` -{ echo "$as_me:$LINENO: checking for $ac_func" >&5 -echo $ECHO_N "checking for $ac_func... $ECHO_C" >&6; } -if { as_var=$as_ac_var; eval "test \"\${$as_var+set}\" = set"; }; then - echo $ECHO_N "(cached) $ECHO_C" >&6 -else - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -/* Define $ac_func to an innocuous variant, in case declares $ac_func. - For example, HP-UX 11i declares gettimeofday. */ -#define $ac_func innocuous_$ac_func + # Defining _REENTRANT on system with POSIX threads should not hurt. + $as_echo "#define _REENTRANT 1" >>confdefs.h -/* System header to define __stub macros and hopefully few prototypes, - which can conflict with char $ac_func (); below. - Prefer to if __STDC__ is defined, since - exists even on freestanding compilers. */ + posix_threads=yes + THREADOBJ="Python/thread.o" +elif test "$ac_cv_kpthread" = "yes" +then + CC="$CC -Kpthread" + if test "$ac_cv_cxx_thread" = "yes"; then + CXX="$CXX -Kpthread" + fi + $as_echo "#define WITH_THREAD 1" >>confdefs.h -#ifdef __STDC__ -# include -#else -# include -#endif + posix_threads=yes + THREADOBJ="Python/thread.o" +elif test "$ac_cv_kthread" = "yes" +then + CC="$CC -Kthread" + if test "$ac_cv_cxx_thread" = "yes"; then + CXX="$CXX -Kthread" + fi + $as_echo "#define WITH_THREAD 1" >>confdefs.h -#undef $ac_func + posix_threads=yes + THREADOBJ="Python/thread.o" +elif test "$ac_cv_pthread" = "yes" +then + CC="$CC -pthread" + if test "$ac_cv_cxx_thread" = "yes"; then + CXX="$CXX -pthread" + fi + $as_echo "#define WITH_THREAD 1" >>confdefs.h -/* Override any GCC internal prototype to avoid an error. - Use char because int might match the return type of a GCC - builtin and then its argument prototype would still apply. */ -#ifdef __cplusplus -extern "C" -#endif -char $ac_func (); -/* The GNU C library defines this for functions which it implements - to always fail with ENOSYS. Some functions are actually named - something starting with __ and the normal name is an alias. */ -#if defined __stub_$ac_func || defined __stub___$ac_func -choke me + posix_threads=yes + THREADOBJ="Python/thread.o" +else + if test ! -z "$with_threads" -a -d "$with_threads" + then LDFLAGS="$LDFLAGS -L$with_threads" + fi + if test ! -z "$withval" -a -d "$withval" + then LDFLAGS="$LDFLAGS -L$withval" + fi + + # According to the POSIX spec, a pthreads implementation must + # define _POSIX_THREADS in unistd.h. Some apparently don't + # (e.g. gnu pth with pthread emulation) + { $as_echo "$as_me:${as_lineno-$LINENO}: checking for _POSIX_THREADS in unistd.h" >&5 +$as_echo_n "checking for _POSIX_THREADS in unistd.h... " >&6; } + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + +#include +#ifdef _POSIX_THREADS +yes #endif -int -main () -{ -return $ac_func (); - ; - return 0; -} _ACEOF -rm -f conftest.$ac_objext conftest$ac_exeext -if { (ac_try="$ac_link" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_link") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest$ac_exeext && - $as_test_x conftest$ac_exeext; then - eval "$as_ac_var=yes" +if (eval "$ac_cpp conftest.$ac_ext") 2>&5 | + $EGREP "yes" >/dev/null 2>&1; then : + unistd_defines_pthreads=yes else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - eval "$as_ac_var=no" + unistd_defines_pthreads=no fi +rm -f conftest* -rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \ - conftest$ac_exeext conftest.$ac_ext -fi -ac_res=`eval echo '${'$as_ac_var'}'` - { echo "$as_me:$LINENO: result: $ac_res" >&5 -echo "${ECHO_T}$ac_res" >&6; } -if test `eval echo '${'$as_ac_var'}'` = yes; then - cat >>confdefs.h <<_ACEOF -#define `echo "HAVE_$ac_func" | $as_tr_cpp` 1 -_ACEOF + { $as_echo "$as_me:${as_lineno-$LINENO}: result: $unistd_defines_pthreads" >&5 +$as_echo "$unistd_defines_pthreads" >&6; } -fi -done + $as_echo "#define _REENTRANT 1" >>confdefs.h + ac_fn_c_check_header_mongrel "$LINENO" "cthreads.h" "ac_cv_header_cthreads_h" "$ac_includes_default" +if test "x$ac_cv_header_cthreads_h" = x""yes; then : + $as_echo "#define WITH_THREAD 1" >>confdefs.h + + $as_echo "#define C_THREADS 1" >>confdefs.h -# check for long file support functions +$as_echo "#define HURD_C_THREADS 1" >>confdefs.h + + LIBS="$LIBS -lthreads" + THREADOBJ="Python/thread.o" +else + ac_fn_c_check_header_mongrel "$LINENO" "mach/cthreads.h" "ac_cv_header_mach_cthreads_h" "$ac_includes_default" +if test "x$ac_cv_header_mach_cthreads_h" = x""yes; then : + $as_echo "#define WITH_THREAD 1" >>confdefs.h + $as_echo "#define C_THREADS 1" >>confdefs.h +$as_echo "#define MACH_C_THREADS 1" >>confdefs.h -for ac_func in fseek64 fseeko fstatvfs ftell64 ftello statvfs -do -as_ac_var=`echo "ac_cv_func_$ac_func" | $as_tr_sh` -{ echo "$as_me:$LINENO: checking for $ac_func" >&5 -echo $ECHO_N "checking for $ac_func... $ECHO_C" >&6; } -if { as_var=$as_ac_var; eval "test \"\${$as_var+set}\" = set"; }; then - echo $ECHO_N "(cached) $ECHO_C" >&6 + THREADOBJ="Python/thread.o" else - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -/* Define $ac_func to an innocuous variant, in case declares $ac_func. - For example, HP-UX 11i declares gettimeofday. */ -#define $ac_func innocuous_$ac_func -/* System header to define __stub macros and hopefully few prototypes, - which can conflict with char $ac_func (); below. - Prefer to if __STDC__ is defined, since - exists even on freestanding compilers. */ + { $as_echo "$as_me:${as_lineno-$LINENO}: checking for --with-pth" >&5 +$as_echo_n "checking for --with-pth... " >&6; } -#ifdef __STDC__ -# include -#else -# include -#endif +# Check whether --with-pth was given. +if test "${with_pth+set}" = set; then : + withval=$with_pth; { $as_echo "$as_me:${as_lineno-$LINENO}: result: $withval" >&5 +$as_echo "$withval" >&6; } + $as_echo "#define WITH_THREAD 1" >>confdefs.h -#undef $ac_func -/* Override any GCC internal prototype to avoid an error. - Use char because int might match the return type of a GCC - builtin and then its argument prototype would still apply. */ -#ifdef __cplusplus -extern "C" -#endif -char $ac_func (); -/* The GNU C library defines this for functions which it implements - to always fail with ENOSYS. Some functions are actually named - something starting with __ and the normal name is an alias. */ -#if defined __stub_$ac_func || defined __stub___$ac_func -choke me -#endif +$as_echo "#define HAVE_PTH 1" >>confdefs.h + LIBS="-lpth $LIBS" + THREADOBJ="Python/thread.o" +else + { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 +$as_echo "no" >&6; } + + # Just looking for pthread_create in libpthread is not enough: + # on HP/UX, pthread.h renames pthread_create to a different symbol name. + # So we really have to include pthread.h, and then link. + _libs=$LIBS + LIBS="$LIBS -lpthread" + { $as_echo "$as_me:${as_lineno-$LINENO}: checking for pthread_create in -lpthread" >&5 +$as_echo_n "checking for pthread_create in -lpthread... " >&6; } + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ +#include + +void * start_routine (void *arg) { exit (0); } int main () { -return $ac_func (); + +pthread_create (NULL, NULL, start_routine, NULL) ; return 0; } _ACEOF -rm -f conftest.$ac_objext conftest$ac_exeext -if { (ac_try="$ac_link" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_link") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest$ac_exeext && - $as_test_x conftest$ac_exeext; then - eval "$as_ac_var=yes" -else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 +if ac_fn_c_try_link "$LINENO"; then : - eval "$as_ac_var=no" -fi + { $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +$as_echo "yes" >&6; } + $as_echo "#define WITH_THREAD 1" >>confdefs.h -rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \ - conftest$ac_exeext conftest.$ac_ext -fi -ac_res=`eval echo '${'$as_ac_var'}'` - { echo "$as_me:$LINENO: result: $ac_res" >&5 -echo "${ECHO_T}$ac_res" >&6; } -if test `eval echo '${'$as_ac_var'}'` = yes; then - cat >>confdefs.h <<_ACEOF -#define `echo "HAVE_$ac_func" | $as_tr_cpp` 1 -_ACEOF + posix_threads=yes + THREADOBJ="Python/thread.o" +else -fi -done + LIBS=$_libs + ac_fn_c_check_func "$LINENO" "pthread_detach" "ac_cv_func_pthread_detach" +if test "x$ac_cv_func_pthread_detach" = x""yes; then : + $as_echo "#define WITH_THREAD 1" >>confdefs.h + posix_threads=yes + THREADOBJ="Python/thread.o" +else + ac_fn_c_check_header_mongrel "$LINENO" "atheos/threads.h" "ac_cv_header_atheos_threads_h" "$ac_includes_default" +if test "x$ac_cv_header_atheos_threads_h" = x""yes; then : + $as_echo "#define WITH_THREAD 1" >>confdefs.h +$as_echo "#define ATHEOS_THREADS 1" >>confdefs.h -for ac_func in dup2 getcwd strdup -do -as_ac_var=`echo "ac_cv_func_$ac_func" | $as_tr_sh` -{ echo "$as_me:$LINENO: checking for $ac_func" >&5 -echo $ECHO_N "checking for $ac_func... $ECHO_C" >&6; } -if { as_var=$as_ac_var; eval "test \"\${$as_var+set}\" = set"; }; then - echo $ECHO_N "(cached) $ECHO_C" >&6 + THREADOBJ="Python/thread.o" else - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -/* Define $ac_func to an innocuous variant, in case declares $ac_func. - For example, HP-UX 11i declares gettimeofday. */ -#define $ac_func innocuous_$ac_func -/* System header to define __stub macros and hopefully few prototypes, - which can conflict with char $ac_func (); below. - Prefer to if __STDC__ is defined, since - exists even on freestanding compilers. */ + ac_fn_c_check_header_mongrel "$LINENO" "kernel/OS.h" "ac_cv_header_kernel_OS_h" "$ac_includes_default" +if test "x$ac_cv_header_kernel_OS_h" = x""yes; then : + $as_echo "#define WITH_THREAD 1" >>confdefs.h -#ifdef __STDC__ -# include -#else -# include -#endif -#undef $ac_func +$as_echo "#define BEOS_THREADS 1" >>confdefs.h + + THREADOBJ="Python/thread.o" +else + + { $as_echo "$as_me:${as_lineno-$LINENO}: checking for pthread_create in -lpthreads" >&5 +$as_echo_n "checking for pthread_create in -lpthreads... " >&6; } +if test "${ac_cv_lib_pthreads_pthread_create+set}" = set; then : + $as_echo_n "(cached) " >&6 +else + ac_check_lib_save_LIBS=$LIBS +LIBS="-lpthreads $LIBS" +cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ /* Override any GCC internal prototype to avoid an error. Use char because int might match the return type of a GCC @@ -20553,101 +8647,43 @@ #ifdef __cplusplus extern "C" #endif -char $ac_func (); -/* The GNU C library defines this for functions which it implements - to always fail with ENOSYS. Some functions are actually named - something starting with __ and the normal name is an alias. */ -#if defined __stub_$ac_func || defined __stub___$ac_func -choke me -#endif - +char pthread_create (); int main () { -return $ac_func (); +return pthread_create (); ; return 0; } _ACEOF -rm -f conftest.$ac_objext conftest$ac_exeext -if { (ac_try="$ac_link" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_link") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest$ac_exeext && - $as_test_x conftest$ac_exeext; then - eval "$as_ac_var=yes" +if ac_fn_c_try_link "$LINENO"; then : + ac_cv_lib_pthreads_pthread_create=yes else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - eval "$as_ac_var=no" + ac_cv_lib_pthreads_pthread_create=no fi - -rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \ - conftest$ac_exeext conftest.$ac_ext +rm -f core conftest.err conftest.$ac_objext \ + conftest$ac_exeext conftest.$ac_ext +LIBS=$ac_check_lib_save_LIBS fi -ac_res=`eval echo '${'$as_ac_var'}'` - { echo "$as_me:$LINENO: result: $ac_res" >&5 -echo "${ECHO_T}$ac_res" >&6; } -if test `eval echo '${'$as_ac_var'}'` = yes; then - cat >>confdefs.h <<_ACEOF -#define `echo "HAVE_$ac_func" | $as_tr_cpp` 1 -_ACEOF +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_lib_pthreads_pthread_create" >&5 +$as_echo "$ac_cv_lib_pthreads_pthread_create" >&6; } +if test "x$ac_cv_lib_pthreads_pthread_create" = x""yes; then : + $as_echo "#define WITH_THREAD 1" >>confdefs.h + posix_threads=yes + LIBS="$LIBS -lpthreads" + THREADOBJ="Python/thread.o" else - case " $LIBOBJS " in - *" $ac_func.$ac_objext "* ) ;; - *) LIBOBJS="$LIBOBJS $ac_func.$ac_objext" - ;; -esac - -fi -done - - -for ac_func in getpgrp -do -as_ac_var=`echo "ac_cv_func_$ac_func" | $as_tr_sh` -{ echo "$as_me:$LINENO: checking for $ac_func" >&5 -echo $ECHO_N "checking for $ac_func... $ECHO_C" >&6; } -if { as_var=$as_ac_var; eval "test \"\${$as_var+set}\" = set"; }; then - echo $ECHO_N "(cached) $ECHO_C" >&6 + { $as_echo "$as_me:${as_lineno-$LINENO}: checking for pthread_create in -lc_r" >&5 +$as_echo_n "checking for pthread_create in -lc_r... " >&6; } +if test "${ac_cv_lib_c_r_pthread_create+set}" = set; then : + $as_echo_n "(cached) " >&6 else - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF + ac_check_lib_save_LIBS=$LIBS +LIBS="-lc_r $LIBS" +cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ -/* Define $ac_func to an innocuous variant, in case declares $ac_func. - For example, HP-UX 11i declares gettimeofday. */ -#define $ac_func innocuous_$ac_func - -/* System header to define __stub macros and hopefully few prototypes, - which can conflict with char $ac_func (); below. - Prefer to if __STDC__ is defined, since - exists even on freestanding compilers. */ - -#ifdef __STDC__ -# include -#else -# include -#endif - -#undef $ac_func /* Override any GCC internal prototype to avoid an error. Use char because int might match the return type of a GCC @@ -20655,139 +8691,87 @@ #ifdef __cplusplus extern "C" #endif -char $ac_func (); -/* The GNU C library defines this for functions which it implements - to always fail with ENOSYS. Some functions are actually named - something starting with __ and the normal name is an alias. */ -#if defined __stub_$ac_func || defined __stub___$ac_func -choke me -#endif - +char pthread_create (); int main () { -return $ac_func (); +return pthread_create (); ; return 0; } _ACEOF -rm -f conftest.$ac_objext conftest$ac_exeext -if { (ac_try="$ac_link" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_link") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest$ac_exeext && - $as_test_x conftest$ac_exeext; then - eval "$as_ac_var=yes" +if ac_fn_c_try_link "$LINENO"; then : + ac_cv_lib_c_r_pthread_create=yes else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - eval "$as_ac_var=no" + ac_cv_lib_c_r_pthread_create=no fi - -rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \ - conftest$ac_exeext conftest.$ac_ext +rm -f core conftest.err conftest.$ac_objext \ + conftest$ac_exeext conftest.$ac_ext +LIBS=$ac_check_lib_save_LIBS fi -ac_res=`eval echo '${'$as_ac_var'}'` - { echo "$as_me:$LINENO: result: $ac_res" >&5 -echo "${ECHO_T}$ac_res" >&6; } -if test `eval echo '${'$as_ac_var'}'` = yes; then - cat >>confdefs.h <<_ACEOF -#define `echo "HAVE_$ac_func" | $as_tr_cpp` 1 -_ACEOF - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_lib_c_r_pthread_create" >&5 +$as_echo "$ac_cv_lib_c_r_pthread_create" >&6; } +if test "x$ac_cv_lib_c_r_pthread_create" = x""yes; then : + $as_echo "#define WITH_THREAD 1" >>confdefs.h + + posix_threads=yes + LIBS="$LIBS -lc_r" + THREADOBJ="Python/thread.o" +else + + { $as_echo "$as_me:${as_lineno-$LINENO}: checking for __pthread_create_system in -lpthread" >&5 +$as_echo_n "checking for __pthread_create_system in -lpthread... " >&6; } +if test "${ac_cv_lib_pthread___pthread_create_system+set}" = set; then : + $as_echo_n "(cached) " >&6 +else + ac_check_lib_save_LIBS=$LIBS +LIBS="-lpthread $LIBS" +cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ -#include + +/* Override any GCC internal prototype to avoid an error. + Use char because int might match the return type of a GCC + builtin and then its argument prototype would still apply. */ +#ifdef __cplusplus +extern "C" +#endif +char __pthread_create_system (); int main () { -getpgrp(0); +return __pthread_create_system (); ; return 0; } _ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - -cat >>confdefs.h <<\_ACEOF -#define GETPGRP_HAVE_ARG 1 -_ACEOF - - +if ac_fn_c_try_link "$LINENO"; then : + ac_cv_lib_pthread___pthread_create_system=yes else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - + ac_cv_lib_pthread___pthread_create_system=no fi - -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext - +rm -f core conftest.err conftest.$ac_objext \ + conftest$ac_exeext conftest.$ac_ext +LIBS=$ac_check_lib_save_LIBS fi -done - - -for ac_func in setpgrp -do -as_ac_var=`echo "ac_cv_func_$ac_func" | $as_tr_sh` -{ echo "$as_me:$LINENO: checking for $ac_func" >&5 -echo $ECHO_N "checking for $ac_func... $ECHO_C" >&6; } -if { as_var=$as_ac_var; eval "test \"\${$as_var+set}\" = set"; }; then - echo $ECHO_N "(cached) $ECHO_C" >&6 -else - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -/* Define $ac_func to an innocuous variant, in case declares $ac_func. - For example, HP-UX 11i declares gettimeofday. */ -#define $ac_func innocuous_$ac_func - -/* System header to define __stub macros and hopefully few prototypes, - which can conflict with char $ac_func (); below. - Prefer to if __STDC__ is defined, since - exists even on freestanding compilers. */ +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_lib_pthread___pthread_create_system" >&5 +$as_echo "$ac_cv_lib_pthread___pthread_create_system" >&6; } +if test "x$ac_cv_lib_pthread___pthread_create_system" = x""yes; then : + $as_echo "#define WITH_THREAD 1" >>confdefs.h -#ifdef __STDC__ -# include -#else -# include -#endif + posix_threads=yes + LIBS="$LIBS -lpthread" + THREADOBJ="Python/thread.o" +else -#undef $ac_func + { $as_echo "$as_me:${as_lineno-$LINENO}: checking for pthread_create in -lcma" >&5 +$as_echo_n "checking for pthread_create in -lcma... " >&6; } +if test "${ac_cv_lib_cma_pthread_create+set}" = set; then : + $as_echo_n "(cached) " >&6 +else + ac_check_lib_save_LIBS=$LIBS +LIBS="-lcma $LIBS" +cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ /* Override any GCC internal prototype to avoid an error. Use char because int might match the return type of a GCC @@ -20795,139 +8779,73 @@ #ifdef __cplusplus extern "C" #endif -char $ac_func (); -/* The GNU C library defines this for functions which it implements - to always fail with ENOSYS. Some functions are actually named - something starting with __ and the normal name is an alias. */ -#if defined __stub_$ac_func || defined __stub___$ac_func -choke me -#endif - +char pthread_create (); int main () { -return $ac_func (); +return pthread_create (); ; return 0; } _ACEOF -rm -f conftest.$ac_objext conftest$ac_exeext -if { (ac_try="$ac_link" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_link") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest$ac_exeext && - $as_test_x conftest$ac_exeext; then - eval "$as_ac_var=yes" +if ac_fn_c_try_link "$LINENO"; then : + ac_cv_lib_cma_pthread_create=yes +else + ac_cv_lib_cma_pthread_create=no +fi +rm -f core conftest.err conftest.$ac_objext \ + conftest$ac_exeext conftest.$ac_ext +LIBS=$ac_check_lib_save_LIBS +fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_lib_cma_pthread_create" >&5 +$as_echo "$ac_cv_lib_cma_pthread_create" >&6; } +if test "x$ac_cv_lib_cma_pthread_create" = x""yes; then : + $as_echo "#define WITH_THREAD 1" >>confdefs.h + + posix_threads=yes + LIBS="$LIBS -lcma" + THREADOBJ="Python/thread.o" else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - eval "$as_ac_var=no" + USE_THREAD_MODULE="#" fi -rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \ - conftest$ac_exeext conftest.$ac_ext + fi -ac_res=`eval echo '${'$as_ac_var'}'` - { echo "$as_me:$LINENO: result: $ac_res" >&5 -echo "${ECHO_T}$ac_res" >&6; } -if test `eval echo '${'$as_ac_var'}'` = yes; then - cat >>confdefs.h <<_ACEOF -#define `echo "HAVE_$ac_func" | $as_tr_cpp` 1 -_ACEOF - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -#include -int -main () -{ -setpgrp(0,0); - ; - return 0; -} -_ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then -cat >>confdefs.h <<\_ACEOF -#define SETPGRP_HAVE_ARG 1 -_ACEOF +fi +fi -else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 +fi fi -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext fi -done +fi +rm -f core conftest.err conftest.$ac_objext \ + conftest$ac_exeext conftest.$ac_ext +fi + +fi -for ac_func in gettimeofday -do -as_ac_var=`echo "ac_cv_func_$ac_func" | $as_tr_sh` -{ echo "$as_me:$LINENO: checking for $ac_func" >&5 -echo $ECHO_N "checking for $ac_func... $ECHO_C" >&6; } -if { as_var=$as_ac_var; eval "test \"\${$as_var+set}\" = set"; }; then - echo $ECHO_N "(cached) $ECHO_C" >&6 -else - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -/* Define $ac_func to an innocuous variant, in case declares $ac_func. - For example, HP-UX 11i declares gettimeofday. */ -#define $ac_func innocuous_$ac_func -/* System header to define __stub macros and hopefully few prototypes, - which can conflict with char $ac_func (); below. - Prefer to if __STDC__ is defined, since - exists even on freestanding compilers. */ +fi + -#ifdef __STDC__ -# include -#else -# include -#endif -#undef $ac_func + { $as_echo "$as_me:${as_lineno-$LINENO}: checking for usconfig in -lmpc" >&5 +$as_echo_n "checking for usconfig in -lmpc... " >&6; } +if test "${ac_cv_lib_mpc_usconfig+set}" = set; then : + $as_echo_n "(cached) " >&6 +else + ac_check_lib_save_LIBS=$LIBS +LIBS="-lmpc $LIBS" +cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ /* Override any GCC internal prototype to avoid an error. Use char because int might match the return type of a GCC @@ -20935,3781 +8853,3215 @@ #ifdef __cplusplus extern "C" #endif -char $ac_func (); -/* The GNU C library defines this for functions which it implements - to always fail with ENOSYS. Some functions are actually named - something starting with __ and the normal name is an alias. */ -#if defined __stub_$ac_func || defined __stub___$ac_func -choke me -#endif - +char usconfig (); int main () { -return $ac_func (); +return usconfig (); ; return 0; } _ACEOF -rm -f conftest.$ac_objext conftest$ac_exeext -if { (ac_try="$ac_link" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_link") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest$ac_exeext && - $as_test_x conftest$ac_exeext; then - eval "$as_ac_var=yes" +if ac_fn_c_try_link "$LINENO"; then : + ac_cv_lib_mpc_usconfig=yes else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - eval "$as_ac_var=no" + ac_cv_lib_mpc_usconfig=no fi +rm -f core conftest.err conftest.$ac_objext \ + conftest$ac_exeext conftest.$ac_ext +LIBS=$ac_check_lib_save_LIBS +fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_lib_mpc_usconfig" >&5 +$as_echo "$ac_cv_lib_mpc_usconfig" >&6; } +if test "x$ac_cv_lib_mpc_usconfig" = x""yes; then : + $as_echo "#define WITH_THREAD 1" >>confdefs.h -rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \ - conftest$ac_exeext conftest.$ac_ext + LIBS="$LIBS -lmpc" + THREADOBJ="Python/thread.o" + USE_THREAD_MODULE="" fi -ac_res=`eval echo '${'$as_ac_var'}'` - { echo "$as_me:$LINENO: result: $ac_res" >&5 -echo "${ECHO_T}$ac_res" >&6; } -if test `eval echo '${'$as_ac_var'}'` = yes; then - cat >>confdefs.h <<_ACEOF -#define `echo "HAVE_$ac_func" | $as_tr_cpp` 1 -_ACEOF - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF + + + if test "$posix_threads" != "yes"; then + { $as_echo "$as_me:${as_lineno-$LINENO}: checking for thr_create in -lthread" >&5 +$as_echo_n "checking for thr_create in -lthread... " >&6; } +if test "${ac_cv_lib_thread_thr_create+set}" = set; then : + $as_echo_n "(cached) " >&6 +else + ac_check_lib_save_LIBS=$LIBS +LIBS="-lthread $LIBS" +cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ -#include + +/* Override any GCC internal prototype to avoid an error. + Use char because int might match the return type of a GCC + builtin and then its argument prototype would still apply. */ +#ifdef __cplusplus +extern "C" +#endif +char thr_create (); int main () { -gettimeofday((struct timeval*)0,(struct timezone*)0); +return thr_create (); ; return 0; } _ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - : +if ac_fn_c_try_link "$LINENO"; then : + ac_cv_lib_thread_thr_create=yes else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 + ac_cv_lib_thread_thr_create=no +fi +rm -f core conftest.err conftest.$ac_objext \ + conftest$ac_exeext conftest.$ac_ext +LIBS=$ac_check_lib_save_LIBS +fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_lib_thread_thr_create" >&5 +$as_echo "$ac_cv_lib_thread_thr_create" >&6; } +if test "x$ac_cv_lib_thread_thr_create" = x""yes; then : + $as_echo "#define WITH_THREAD 1" >>confdefs.h + + LIBS="$LIBS -lthread" + THREADOBJ="Python/thread.o" + USE_THREAD_MODULE="" +fi + + fi + + if test "$USE_THREAD_MODULE" != "#" + then + # If the above checks didn't disable threads, (at least) OSF1 + # needs this '-threads' argument during linking. + case $ac_sys_system in + OSF1) LDLAST=-threads;; + esac + fi +fi + +if test "$posix_threads" = "yes"; then + if test "$unistd_defines_pthreads" = "no"; then + +$as_echo "#define _POSIX_THREADS 1" >>confdefs.h + + fi + + # Bug 662787: Using semaphores causes unexplicable hangs on Solaris 8. + case $ac_sys_system/$ac_sys_release in + SunOS/5.6) +$as_echo "#define HAVE_PTHREAD_DESTRUCTOR 1" >>confdefs.h + + ;; + SunOS/5.8) +$as_echo "#define HAVE_BROKEN_POSIX_SEMAPHORES 1" >>confdefs.h + ;; + AIX/5) +$as_echo "#define HAVE_BROKEN_POSIX_SEMAPHORES 1" >>confdefs.h + + ;; + esac -cat >>confdefs.h <<\_ACEOF -#define GETTIMEOFDAY_NO_TZ 1 + { $as_echo "$as_me:${as_lineno-$LINENO}: checking if PTHREAD_SCOPE_SYSTEM is supported" >&5 +$as_echo_n "checking if PTHREAD_SCOPE_SYSTEM is supported... " >&6; } + if test "${ac_cv_pthread_system_supported+set}" = set; then : + $as_echo_n "(cached) " >&6 +else + if test "$cross_compiling" = yes; then : + ac_cv_pthread_system_supported=no +else + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ +#include + void *foo(void *parm) { + return NULL; + } + main() { + pthread_attr_t attr; + pthread_t id; + if (pthread_attr_init(&attr)) exit(-1); + if (pthread_attr_setscope(&attr, PTHREAD_SCOPE_SYSTEM)) exit(-1); + if (pthread_create(&id, &attr, foo, NULL)) exit(-1); + exit(0); + } _ACEOF +if ac_fn_c_try_run "$LINENO"; then : + ac_cv_pthread_system_supported=yes +else + ac_cv_pthread_system_supported=no +fi +rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext \ + conftest.$ac_objext conftest.beam conftest.$ac_ext +fi fi -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext + { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_pthread_system_supported" >&5 +$as_echo "$ac_cv_pthread_system_supported" >&6; } + if test "$ac_cv_pthread_system_supported" = "yes"; then + +$as_echo "#define PTHREAD_SYSTEM_SCHED_SUPPORTED 1" >>confdefs.h + + fi + for ac_func in pthread_sigmask +do : + ac_fn_c_check_func "$LINENO" "pthread_sigmask" "ac_cv_func_pthread_sigmask" +if test "x$ac_cv_func_pthread_sigmask" = x""yes; then : + cat >>confdefs.h <<_ACEOF +#define HAVE_PTHREAD_SIGMASK 1 +_ACEOF + case $ac_sys_system in + CYGWIN*) + +$as_echo "#define HAVE_BROKEN_PTHREAD_SIGMASK 1" >>confdefs.h + ;; + esac fi done +fi -{ echo "$as_me:$LINENO: checking for major" >&5 -echo $ECHO_N "checking for major... $ECHO_C" >&6; } -cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -#if defined(MAJOR_IN_MKDEV) -#include -#elif defined(MAJOR_IN_SYSMACROS) -#include -#else +# Check for enable-ipv6 + +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking if --enable-ipv6 is specified" >&5 +$as_echo_n "checking if --enable-ipv6 is specified... " >&6; } +# Check whether --enable-ipv6 was given. +if test "${enable_ipv6+set}" = set; then : + enableval=$enable_ipv6; case "$enableval" in + no) + { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 +$as_echo "no" >&6; } + ipv6=no + ;; + *) { $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +$as_echo "yes" >&6; } + $as_echo "#define ENABLE_IPV6 1" >>confdefs.h + + ipv6=yes + ;; + esac +else + + if test "$cross_compiling" = yes; then : + { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 +$as_echo "no" >&6; } + ipv6=no + +else + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + /* AF_INET6 available check */ #include -#endif +#include +main() +{ + if (socket(AF_INET6, SOCK_STREAM, 0) < 0) + exit(1); + else + exit(0); +} + +_ACEOF +if ac_fn_c_try_run "$LINENO"; then : + { $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +$as_echo "yes" >&6; } + ipv6=yes +else + { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 +$as_echo "no" >&6; } + ipv6=no +fi +rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext \ + conftest.$ac_objext conftest.beam conftest.$ac_ext +fi + +if test "$ipv6" = "yes"; then + { $as_echo "$as_me:${as_lineno-$LINENO}: checking if RFC2553 API is available" >&5 +$as_echo_n "checking if RFC2553 API is available... " >&6; } + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ +#include +#include int main () { - - makedev(major(0),minor(0)); - +struct sockaddr_in6 x; +x.sin6_scope_id; ; return 0; } _ACEOF -rm -f conftest.$ac_objext conftest$ac_exeext -if { (ac_try="$ac_link" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_link") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest$ac_exeext && - $as_test_x conftest$ac_exeext; then +if ac_fn_c_try_compile "$LINENO"; then : + { $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +$as_echo "yes" >&6; } + ipv6=yes +else + { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 +$as_echo "no" >&6; } + ipv6=no +fi +rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext +fi +if test "$ipv6" = "yes"; then + $as_echo "#define ENABLE_IPV6 1" >>confdefs.h -cat >>confdefs.h <<\_ACEOF -#define HAVE_DEVICE_MACROS 1 -_ACEOF +fi - { echo "$as_me:$LINENO: result: yes" >&5 -echo "${ECHO_T}yes" >&6; } +fi -else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 +ipv6type=unknown +ipv6lib=none +ipv6trylibc=no - { echo "$as_me:$LINENO: result: no" >&5 -echo "${ECHO_T}no" >&6; } +if test "$ipv6" = "yes"; then + { $as_echo "$as_me:${as_lineno-$LINENO}: checking ipv6 stack type" >&5 +$as_echo_n "checking ipv6 stack type... " >&6; } + for i in inria kame linux-glibc linux-inet6 solaris toshiba v6d zeta; + do + case $i in + inria) + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ +#include +#ifdef IPV6_INRIA_VERSION +yes +#endif +_ACEOF +if (eval "$ac_cpp conftest.$ac_ext") 2>&5 | + $EGREP "yes" >/dev/null 2>&1; then : + ipv6type=$i fi +rm -f conftest* -rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \ - conftest$ac_exeext conftest.$ac_ext + ;; + kame) + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ -# On OSF/1 V5.1, getaddrinfo is available, but a define -# for [no]getaddrinfo in netdb.h. -{ echo "$as_me:$LINENO: checking for getaddrinfo" >&5 -echo $ECHO_N "checking for getaddrinfo... $ECHO_C" >&6; } -cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ +#include +#ifdef __KAME__ +yes +#endif _ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ +if (eval "$ac_cpp conftest.$ac_ext") 2>&5 | + $EGREP "yes" >/dev/null 2>&1; then : + ipv6type=$i; + ipv6lib=inet6 + ipv6libdir=/usr/local/v6/lib + ipv6trylibc=yes +fi +rm -f conftest* -#include -#include -#include -#include + ;; + linux-glibc) + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ -int -main () -{ -getaddrinfo(NULL, NULL, NULL, NULL); - ; - return 0; -} +#include +#if defined(__GLIBC__) && ((__GLIBC__ == 2 && __GLIBC_MINOR__ >= 1) || (__GLIBC__ > 2)) +yes +#endif _ACEOF -rm -f conftest.$ac_objext conftest$ac_exeext -if { (ac_try="$ac_link" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_link") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest$ac_exeext && - $as_test_x conftest$ac_exeext; then - have_getaddrinfo=yes -else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - have_getaddrinfo=no +if (eval "$ac_cpp conftest.$ac_ext") 2>&5 | + $EGREP "yes" >/dev/null 2>&1; then : + ipv6type=$i; + ipv6trylibc=yes fi +rm -f conftest* -rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \ - conftest$ac_exeext conftest.$ac_ext -{ echo "$as_me:$LINENO: result: $have_getaddrinfo" >&5 -echo "${ECHO_T}$have_getaddrinfo" >&6; } -if test $have_getaddrinfo = yes -then - { echo "$as_me:$LINENO: checking getaddrinfo bug" >&5 -echo $ECHO_N "checking getaddrinfo bug... $ECHO_C" >&6; } - if test "${ac_cv_buggy_getaddrinfo+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 -else - if test "$cross_compiling" = yes; then - ac_cv_buggy_getaddrinfo=yes -else - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ + ;; + linux-inet6) + if test -d /usr/inet6; then + ipv6type=$i + ipv6lib=inet6 + ipv6libdir=/usr/inet6/lib + BASECFLAGS="-I/usr/inet6/include $BASECFLAGS" + fi + ;; + solaris) + if test -f /etc/netconfig; then + if /usr/xpg4/bin/grep -q tcp6 /etc/netconfig; then + ipv6type=$i + ipv6trylibc=yes + fi + fi + ;; + toshiba) + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + +#include +#ifdef _TOSHIBA_INET6 +yes +#endif _ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF +if (eval "$ac_cpp conftest.$ac_ext") 2>&5 | + $EGREP "yes" >/dev/null 2>&1; then : + ipv6type=$i; + ipv6lib=inet6; + ipv6libdir=/usr/local/v6/lib +fi +rm -f conftest* + + ;; + v6d) + cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ -#include -#include -#include -#include -#include +#include +#ifdef __V6D__ +yes +#endif +_ACEOF +if (eval "$ac_cpp conftest.$ac_ext") 2>&5 | + $EGREP "yes" >/dev/null 2>&1; then : + ipv6type=$i; + ipv6lib=v6; + ipv6libdir=/usr/local/v6/lib; + BASECFLAGS="-I/usr/local/v6/include $BASECFLAGS" +fi +rm -f conftest* -int main() -{ - int passive, gaierr, inet4 = 0, inet6 = 0; - struct addrinfo hints, *ai, *aitop; - char straddr[INET6_ADDRSTRLEN], strport[16]; + ;; + zeta) + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ - for (passive = 0; passive <= 1; passive++) { - memset(&hints, 0, sizeof(hints)); - hints.ai_family = AF_UNSPEC; - hints.ai_flags = passive ? AI_PASSIVE : 0; - hints.ai_socktype = SOCK_STREAM; - hints.ai_protocol = IPPROTO_TCP; - if ((gaierr = getaddrinfo(NULL, "54321", &hints, &aitop)) != 0) { - (void)gai_strerror(gaierr); - goto bad; - } - for (ai = aitop; ai; ai = ai->ai_next) { - if (ai->ai_addr == NULL || - ai->ai_addrlen == 0 || - getnameinfo(ai->ai_addr, ai->ai_addrlen, - straddr, sizeof(straddr), strport, sizeof(strport), - NI_NUMERICHOST|NI_NUMERICSERV) != 0) { - goto bad; - } - switch (ai->ai_family) { - case AF_INET: - if (strcmp(strport, "54321") != 0) { - goto bad; - } - if (passive) { - if (strcmp(straddr, "0.0.0.0") != 0) { - goto bad; - } - } else { - if (strcmp(straddr, "127.0.0.1") != 0) { - goto bad; - } - } - inet4++; - break; - case AF_INET6: - if (strcmp(strport, "54321") != 0) { - goto bad; - } - if (passive) { - if (strcmp(straddr, "::") != 0) { - goto bad; - } - } else { - if (strcmp(straddr, "::1") != 0) { - goto bad; - } - } - inet6++; - break; - case AF_UNSPEC: - goto bad; - break; - default: - /* another family support? */ - break; - } - } - } +#include +#ifdef _ZETA_MINAMI_INET6 +yes +#endif +_ACEOF +if (eval "$ac_cpp conftest.$ac_ext") 2>&5 | + $EGREP "yes" >/dev/null 2>&1; then : + ipv6type=$i; + ipv6lib=inet6; + ipv6libdir=/usr/local/v6/lib +fi +rm -f conftest* - if (!(inet4 == 0 || inet4 == 2)) - goto bad; - if (!(inet6 == 0 || inet6 == 2)) - goto bad; + ;; + esac + if test "$ipv6type" != "unknown"; then + break + fi + done + { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ipv6type" >&5 +$as_echo "$ipv6type" >&6; } +fi - if (aitop) - freeaddrinfo(aitop); +if test "$ipv6" = "yes" -a "$ipv6lib" != "none"; then + if test -d $ipv6libdir -a -f $ipv6libdir/lib$ipv6lib.a; then + LIBS="-L$ipv6libdir -l$ipv6lib $LIBS" + echo "using lib$ipv6lib" + else + if test $ipv6trylibc = "yes"; then + echo "using libc" + else + echo 'Fatal: no $ipv6lib library found. cannot continue.' + echo "You need to fetch lib$ipv6lib.a from appropriate" + echo 'ipv6 kit and compile beforehand.' + exit 1 + fi + fi +fi + +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for OSX 10.5 SDK or later" >&5 +$as_echo_n "checking for OSX 10.5 SDK or later... " >&6; } +cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ +#include +int +main () +{ +FSIORefNum fRef = 0 + ; return 0; - - bad: - if (aitop) - freeaddrinfo(aitop); - return 1; } - _ACEOF -rm -f conftest$ac_exeext -if { (ac_try="$ac_link" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_link") 2>&5 - ac_status=$? - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { ac_try='./conftest$ac_exeext' - { (case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_try") 2>&5 - ac_status=$? - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); }; }; then - ac_cv_buggy_getaddrinfo=no +if ac_fn_c_try_compile "$LINENO"; then : + +$as_echo "#define HAVE_OSX105_SDK 1" >>confdefs.h + + { $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +$as_echo "yes" >&6; } else - echo "$as_me: program exited with status $ac_status" >&5 -echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 + { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 +$as_echo "no" >&6; } -( exit $ac_status ) -ac_cv_buggy_getaddrinfo=yes fi -rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext conftest.$ac_objext conftest.$ac_ext +rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext + +# Check for --with-doc-strings +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for --with-doc-strings" >&5 +$as_echo_n "checking for --with-doc-strings... " >&6; } + +# Check whether --with-doc-strings was given. +if test "${with_doc_strings+set}" = set; then : + withval=$with_doc_strings; fi +if test -z "$with_doc_strings" +then with_doc_strings="yes" fi +if test "$with_doc_strings" != "no" +then + +$as_echo "#define WITH_DOC_STRINGS 1" >>confdefs.h fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $with_doc_strings" >&5 +$as_echo "$with_doc_strings" >&6; } -if test $have_getaddrinfo = no -o "$ac_cv_buggy_getaddrinfo" = yes +# Check for Python-specific malloc support +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for --with-tsc" >&5 +$as_echo_n "checking for --with-tsc... " >&6; } + +# Check whether --with-tsc was given. +if test "${with_tsc+set}" = set; then : + withval=$with_tsc; +if test "$withval" != no then - if test $ipv6 = yes - then - echo 'Fatal: You must get working getaddrinfo() function.' - echo ' or you can specify "--disable-ipv6"'. - exit 1 - fi + +$as_echo "#define WITH_TSC 1" >>confdefs.h + + { $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +$as_echo "yes" >&6; } +else { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 +$as_echo "no" >&6; } +fi else + { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 +$as_echo "no" >&6; } +fi -cat >>confdefs.h <<\_ACEOF -#define HAVE_GETADDRINFO 1 -_ACEOF +# Check for Python-specific malloc support +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for --with-pymalloc" >&5 +$as_echo_n "checking for --with-pymalloc... " >&6; } + +# Check whether --with-pymalloc was given. +if test "${with_pymalloc+set}" = set; then : + withval=$with_pymalloc; fi -for ac_func in getnameinfo -do -as_ac_var=`echo "ac_cv_func_$ac_func" | $as_tr_sh` -{ echo "$as_me:$LINENO: checking for $ac_func" >&5 -echo $ECHO_N "checking for $ac_func... $ECHO_C" >&6; } -if { as_var=$as_ac_var; eval "test \"\${$as_var+set}\" = set"; }; then - echo $ECHO_N "(cached) $ECHO_C" >&6 -else - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -/* Define $ac_func to an innocuous variant, in case declares $ac_func. - For example, HP-UX 11i declares gettimeofday. */ -#define $ac_func innocuous_$ac_func -/* System header to define __stub macros and hopefully few prototypes, - which can conflict with char $ac_func (); below. - Prefer to if __STDC__ is defined, since - exists even on freestanding compilers. */ +if test -z "$with_pymalloc" +then with_pymalloc="yes" +fi +if test "$with_pymalloc" != "no" +then -#ifdef __STDC__ -# include -#else -# include -#endif +$as_echo "#define WITH_PYMALLOC 1" >>confdefs.h -#undef $ac_func +fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $with_pymalloc" >&5 +$as_echo "$with_pymalloc" >&6; } -/* Override any GCC internal prototype to avoid an error. - Use char because int might match the return type of a GCC - builtin and then its argument prototype would still apply. */ -#ifdef __cplusplus -extern "C" -#endif -char $ac_func (); -/* The GNU C library defines this for functions which it implements - to always fail with ENOSYS. Some functions are actually named - something starting with __ and the normal name is an alias. */ -#if defined __stub_$ac_func || defined __stub___$ac_func -choke me -#endif +# Check for Valgrind support +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for --with-valgrind" >&5 +$as_echo_n "checking for --with-valgrind... " >&6; } -int -main () -{ -return $ac_func (); - ; - return 0; -} -_ACEOF -rm -f conftest.$ac_objext conftest$ac_exeext -if { (ac_try="$ac_link" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_link") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest$ac_exeext && - $as_test_x conftest$ac_exeext; then - eval "$as_ac_var=yes" +# Check whether --with-valgrind was given. +if test "${with_valgrind+set}" = set; then : + withval=$with_valgrind; else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 + with_valgrind=no +fi + +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $with_valgrind" >&5 +$as_echo "$with_valgrind" >&6; } +if test "$with_valgrind" != no; then + ac_fn_c_check_header_mongrel "$LINENO" "valgrind/valgrind.h" "ac_cv_header_valgrind_valgrind_h" "$ac_includes_default" +if test "x$ac_cv_header_valgrind_valgrind_h" = x""yes; then : + +$as_echo "#define WITH_VALGRIND 1" >>confdefs.h + +else + as_fn_error "Valgrind support requested but headers not available" "$LINENO" 5 + +fi + - eval "$as_ac_var=no" fi -rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \ - conftest$ac_exeext conftest.$ac_ext +# Check for --with-wctype-functions +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for --with-wctype-functions" >&5 +$as_echo_n "checking for --with-wctype-functions... " >&6; } + +# Check whether --with-wctype-functions was given. +if test "${with_wctype_functions+set}" = set; then : + withval=$with_wctype_functions; +if test "$withval" != no +then + +$as_echo "#define WANT_WCTYPE_FUNCTIONS 1" >>confdefs.h + + { $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +$as_echo "yes" >&6; } +else { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 +$as_echo "no" >&6; } +fi +else + { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 +$as_echo "no" >&6; } fi -ac_res=`eval echo '${'$as_ac_var'}'` - { echo "$as_me:$LINENO: result: $ac_res" >&5 -echo "${ECHO_T}$ac_res" >&6; } -if test `eval echo '${'$as_ac_var'}'` = yes; then + + +# -I${DLINCLDIR} is added to the compile rule for importdl.o + +DLINCLDIR=. + +# the dlopen() function means we might want to use dynload_shlib.o. some +# platforms, such as AIX, have dlopen(), but don't want to use it. +for ac_func in dlopen +do : + ac_fn_c_check_func "$LINENO" "dlopen" "ac_cv_func_dlopen" +if test "x$ac_cv_func_dlopen" = x""yes; then : cat >>confdefs.h <<_ACEOF -#define `echo "HAVE_$ac_func" | $as_tr_cpp` 1 +#define HAVE_DLOPEN 1 _ACEOF fi done -# checks for structures -{ echo "$as_me:$LINENO: checking whether time.h and sys/time.h may both be included" >&5 -echo $ECHO_N "checking whether time.h and sys/time.h may both be included... $ECHO_C" >&6; } -if test "${ac_cv_header_time+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 -else - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -#include -#include -#include +# DYNLOADFILE specifies which dynload_*.o file we will use for dynamic +# loading of modules. -int -main () -{ -if ((struct tm *) 0) -return 0; - ; - return 0; -} -_ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - ac_cv_header_time=yes -else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking DYNLOADFILE" >&5 +$as_echo_n "checking DYNLOADFILE... " >&6; } +if test -z "$DYNLOADFILE" +then + case $ac_sys_system/$ac_sys_release in + AIX*) # Use dynload_shlib.c and dlopen() if we have it; otherwise dynload_aix.c + if test "$ac_cv_func_dlopen" = yes + then DYNLOADFILE="dynload_shlib.o" + else DYNLOADFILE="dynload_aix.o" + fi + ;; + BeOS*) DYNLOADFILE="dynload_beos.o";; + hp*|HP*) DYNLOADFILE="dynload_hpux.o";; + # Use dynload_next.c only on 10.2 and below, which don't have native dlopen() + Darwin/[0156]\..*) DYNLOADFILE="dynload_next.o";; + atheos*) DYNLOADFILE="dynload_atheos.o";; + *) + # use dynload_shlib.c and dlopen() if we have it; otherwise stub + # out any dynamic loading + if test "$ac_cv_func_dlopen" = yes + then DYNLOADFILE="dynload_shlib.o" + else DYNLOADFILE="dynload_stub.o" + fi + ;; + esac +fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $DYNLOADFILE" >&5 +$as_echo "$DYNLOADFILE" >&6; } +if test "$DYNLOADFILE" != "dynload_stub.o" +then + +$as_echo "#define HAVE_DYNAMIC_LOADING 1" >>confdefs.h - ac_cv_header_time=no fi -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext +# MACHDEP_OBJS can be set to platform-specific object files needed by Python + + +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking MACHDEP_OBJS" >&5 +$as_echo_n "checking MACHDEP_OBJS... " >&6; } +if test -z "$MACHDEP_OBJS" +then + MACHDEP_OBJS=$extra_machdep_objs +else + MACHDEP_OBJS="$MACHDEP_OBJS $extra_machdep_objs" fi -{ echo "$as_me:$LINENO: result: $ac_cv_header_time" >&5 -echo "${ECHO_T}$ac_cv_header_time" >&6; } -if test $ac_cv_header_time = yes; then +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: MACHDEP_OBJS" >&5 +$as_echo "MACHDEP_OBJS" >&6; } -cat >>confdefs.h <<\_ACEOF -#define TIME_WITH_SYS_TIME 1 +# checks for library functions +for ac_func in alarm setitimer getitimer bind_textdomain_codeset chown \ + clock confstr ctermid execv fchmod fchown fork fpathconf ftime ftruncate \ + gai_strerror getgroups getlogin getloadavg getpeername getpgid getpid \ + getpriority getresuid getresgid getpwent getspnam getspent getsid getwd \ + initgroups kill killpg lchmod lchown lstat mkfifo mknod mktime \ + mremap nice pathconf pause plock poll pthread_init \ + putenv readlink realpath \ + select sem_open sem_timedwait sem_getvalue sem_unlink setegid seteuid \ + setgid \ + setlocale setregid setreuid setsid setpgid setpgrp setuid setvbuf snprintf \ + setlocale setregid setreuid setresuid setresgid \ + 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 +do : + as_ac_var=`$as_echo "ac_cv_func_$ac_func" | $as_tr_sh` +ac_fn_c_check_func "$LINENO" "$ac_func" "$as_ac_var" +eval as_val=\$$as_ac_var + if test "x$as_val" = x""yes; then : + cat >>confdefs.h <<_ACEOF +#define `$as_echo "HAVE_$ac_func" | $as_tr_cpp` 1 _ACEOF fi +done -{ echo "$as_me:$LINENO: checking whether struct tm is in sys/time.h or time.h" >&5 -echo $ECHO_N "checking whether struct tm is in sys/time.h or time.h... $ECHO_C" >&6; } -if test "${ac_cv_struct_tm+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 -else - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -#include -#include +# For some functions, having a definition is not sufficient, since +# we want to take their address. +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for chroot" >&5 +$as_echo_n "checking for chroot... " >&6; } +cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ +#include int main () { -struct tm tm; - int *p = &tm.tm_sec; - return !p; +void *x=chroot ; return 0; } _ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - ac_cv_struct_tm=time.h -else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - ac_cv_struct_tm=sys/time.h -fi +if ac_fn_c_try_compile "$LINENO"; then : -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext -fi -{ echo "$as_me:$LINENO: result: $ac_cv_struct_tm" >&5 -echo "${ECHO_T}$ac_cv_struct_tm" >&6; } -if test $ac_cv_struct_tm = sys/time.h; then +$as_echo "#define HAVE_CHROOT 1" >>confdefs.h -cat >>confdefs.h <<\_ACEOF -#define TM_IN_SYS_TIME 1 -_ACEOF + { $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +$as_echo "yes" >&6; } +else + { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 +$as_echo "no" >&6; } fi - -{ echo "$as_me:$LINENO: checking for struct tm.tm_zone" >&5 -echo $ECHO_N "checking for struct tm.tm_zone... $ECHO_C" >&6; } -if test "${ac_cv_member_struct_tm_tm_zone+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 -else - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF +rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for link" >&5 +$as_echo_n "checking for link... " >&6; } +cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ -#include -#include <$ac_cv_struct_tm> - - +#include int main () { -static struct tm ac_aggr; -if (ac_aggr.tm_zone) -return 0; +void *x=link ; return 0; } _ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - ac_cv_member_struct_tm_tm_zone=yes -else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 +if ac_fn_c_try_compile "$LINENO"; then : - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -#include -#include <$ac_cv_struct_tm> +$as_echo "#define HAVE_LINK 1" >>confdefs.h + { $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +$as_echo "yes" >&6; } +else + { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 +$as_echo "no" >&6; } +fi +rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for symlink" >&5 +$as_echo_n "checking for symlink... " >&6; } +cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ +#include int main () { -static struct tm ac_aggr; -if (sizeof ac_aggr.tm_zone) -return 0; +void *x=symlink ; return 0; } _ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - ac_cv_member_struct_tm_tm_zone=yes -else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 +if ac_fn_c_try_compile "$LINENO"; then : - ac_cv_member_struct_tm_tm_zone=no -fi - -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext -fi - -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext -fi -{ echo "$as_me:$LINENO: result: $ac_cv_member_struct_tm_tm_zone" >&5 -echo "${ECHO_T}$ac_cv_member_struct_tm_tm_zone" >&6; } -if test $ac_cv_member_struct_tm_tm_zone = yes; then - -cat >>confdefs.h <<_ACEOF -#define HAVE_STRUCT_TM_TM_ZONE 1 -_ACEOF +$as_echo "#define HAVE_SYMLINK 1" >>confdefs.h + { $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +$as_echo "yes" >&6; } +else + { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 +$as_echo "no" >&6; } fi - -if test "$ac_cv_member_struct_tm_tm_zone" = yes; then - -cat >>confdefs.h <<\_ACEOF -#define HAVE_TM_ZONE 1 -_ACEOF - -else - { echo "$as_me:$LINENO: checking whether tzname is declared" >&5 -echo $ECHO_N "checking whether tzname is declared... $ECHO_C" >&6; } -if test "${ac_cv_have_decl_tzname+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 -else - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF +rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for fchdir" >&5 +$as_echo_n "checking for fchdir... " >&6; } +cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ -#include - +#include int main () { -#ifndef tzname - (void) tzname; -#endif - +void *x=fchdir ; return 0; } _ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - ac_cv_have_decl_tzname=yes +if ac_fn_c_try_compile "$LINENO"; then : + +$as_echo "#define HAVE_FCHDIR 1" >>confdefs.h + + { $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +$as_echo "yes" >&6; } else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 + { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 +$as_echo "no" >&6; } - ac_cv_have_decl_tzname=no fi - rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext -fi -{ echo "$as_me:$LINENO: result: $ac_cv_have_decl_tzname" >&5 -echo "${ECHO_T}$ac_cv_have_decl_tzname" >&6; } -if test $ac_cv_have_decl_tzname = yes; then - -cat >>confdefs.h <<_ACEOF -#define HAVE_DECL_TZNAME 1 +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for fsync" >&5 +$as_echo_n "checking for fsync... " >&6; } +cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ +#include +int +main () +{ +void *x=fsync + ; + return 0; +} _ACEOF +if ac_fn_c_try_compile "$LINENO"; then : +$as_echo "#define HAVE_FSYNC 1" >>confdefs.h + { $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +$as_echo "yes" >&6; } else - cat >>confdefs.h <<_ACEOF -#define HAVE_DECL_TZNAME 0 -_ACEOF - + { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 +$as_echo "no" >&6; } fi - - - { echo "$as_me:$LINENO: checking for tzname" >&5 -echo $ECHO_N "checking for tzname... $ECHO_C" >&6; } -if test "${ac_cv_var_tzname+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 -else - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF +rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for fdatasync" >&5 +$as_echo_n "checking for fdatasync... " >&6; } +cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ -#include -#if !HAVE_DECL_TZNAME -extern char *tzname[]; -#endif - +#include int main () { -return tzname[0][0]; +void *x=fdatasync ; return 0; } _ACEOF -rm -f conftest.$ac_objext conftest$ac_exeext -if { (ac_try="$ac_link" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_link") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest$ac_exeext && - $as_test_x conftest$ac_exeext; then - ac_cv_var_tzname=yes -else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 +if ac_fn_c_try_compile "$LINENO"; then : - ac_cv_var_tzname=no -fi - -rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \ - conftest$ac_exeext conftest.$ac_ext -fi -{ echo "$as_me:$LINENO: result: $ac_cv_var_tzname" >&5 -echo "${ECHO_T}$ac_cv_var_tzname" >&6; } - if test $ac_cv_var_tzname = yes; then +$as_echo "#define HAVE_FDATASYNC 1" >>confdefs.h -cat >>confdefs.h <<\_ACEOF -#define HAVE_TZNAME 1 -_ACEOF + { $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +$as_echo "yes" >&6; } +else + { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 +$as_echo "no" >&6; } - fi fi - -{ echo "$as_me:$LINENO: checking for struct stat.st_rdev" >&5 -echo $ECHO_N "checking for struct stat.st_rdev... $ECHO_C" >&6; } -if test "${ac_cv_member_struct_stat_st_rdev+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 -else - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF +rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for epoll" >&5 +$as_echo_n "checking for epoll... " >&6; } +cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ -$ac_includes_default +#include int main () { -static struct stat ac_aggr; -if (ac_aggr.st_rdev) -return 0; +void *x=epoll_create ; return 0; } _ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - ac_cv_member_struct_stat_st_rdev=yes +if ac_fn_c_try_compile "$LINENO"; then : + +$as_echo "#define HAVE_EPOLL 1" >>confdefs.h + + { $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +$as_echo "yes" >&6; } else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 + { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 +$as_echo "no" >&6; } - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF +fi +rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for kqueue" >&5 +$as_echo_n "checking for kqueue... " >&6; } +cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ -$ac_includes_default + +#include +#include + int main () { -static struct stat ac_aggr; -if (sizeof ac_aggr.st_rdev) -return 0; +int x=kqueue() ; return 0; } _ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - ac_cv_member_struct_stat_st_rdev=yes +if ac_fn_c_try_compile "$LINENO"; then : + +$as_echo "#define HAVE_KQUEUE 1" >>confdefs.h + + { $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +$as_echo "yes" >&6; } else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 + { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 +$as_echo "no" >&6; } - ac_cv_member_struct_stat_st_rdev=no fi - rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext -fi +# On some systems (eg. FreeBSD 5), we would find a definition of the +# functions ctermid_r, setgroups in the library, but no prototype +# (e.g. because we use _XOPEN_SOURCE). See whether we can take their +# address to avoid compiler warnings and potential miscompilations +# because of the missing prototypes. -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext -fi -{ echo "$as_me:$LINENO: result: $ac_cv_member_struct_stat_st_rdev" >&5 -echo "${ECHO_T}$ac_cv_member_struct_stat_st_rdev" >&6; } -if test $ac_cv_member_struct_stat_st_rdev = yes; then +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for ctermid_r" >&5 +$as_echo_n "checking for ctermid_r... " >&6; } +cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ -cat >>confdefs.h <<_ACEOF -#define HAVE_STRUCT_STAT_ST_RDEV 1 +#include "confdefs.h" +#include + +int +main () +{ +void* p = ctermid_r + ; + return 0; +} _ACEOF +if ac_fn_c_try_compile "$LINENO"; then : + +$as_echo "#define HAVE_CTERMID_R 1" >>confdefs.h + { $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +$as_echo "yes" >&6; } +else + { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 +$as_echo "no" >&6; } fi +rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext -{ echo "$as_me:$LINENO: checking for struct stat.st_blksize" >&5 -echo $ECHO_N "checking for struct stat.st_blksize... $ECHO_C" >&6; } -if test "${ac_cv_member_struct_stat_st_blksize+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 -else - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for flock" >&5 +$as_echo_n "checking for flock... " >&6; } +cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ -$ac_includes_default + +#include "confdefs.h" +#include + int main () { -static struct stat ac_aggr; -if (ac_aggr.st_blksize) -return 0; +void* p = flock ; return 0; } _ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - ac_cv_member_struct_stat_st_blksize=yes +if ac_fn_c_try_compile "$LINENO"; then : + +$as_echo "#define HAVE_FLOCK 1" >>confdefs.h + + { $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +$as_echo "yes" >&6; } else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 + { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 +$as_echo "no" >&6; } - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF +fi +rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext + +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for getpagesize" >&5 +$as_echo_n "checking for getpagesize... " >&6; } +cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ -$ac_includes_default + +#include "confdefs.h" +#include + int main () { -static struct stat ac_aggr; -if (sizeof ac_aggr.st_blksize) -return 0; +void* p = getpagesize ; return 0; } _ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - ac_cv_member_struct_stat_st_blksize=yes +if ac_fn_c_try_compile "$LINENO"; then : + +$as_echo "#define HAVE_GETPAGESIZE 1" >>confdefs.h + + { $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +$as_echo "yes" >&6; } else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 + { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 +$as_echo "no" >&6; } - ac_cv_member_struct_stat_st_blksize=no fi - rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext -fi -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext +for ac_prog in true +do + # Extract the first word of "$ac_prog", so it can be a program name with args. +set dummy $ac_prog; ac_word=$2 +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 +$as_echo_n "checking for $ac_word... " >&6; } +if test "${ac_cv_prog_TRUE+set}" = set; then : + $as_echo_n "(cached) " >&6 +else + if test -n "$TRUE"; then + ac_cv_prog_TRUE="$TRUE" # Let the user override the test. +else +as_save_IFS=$IFS; IFS=$PATH_SEPARATOR +for as_dir in $PATH +do + IFS=$as_save_IFS + test -z "$as_dir" && as_dir=. + for ac_exec_ext in '' $ac_executable_extensions; do + if { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_test_x "$as_dir/$ac_word$ac_exec_ext"; }; then + ac_cv_prog_TRUE="$ac_prog" + $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 + break 2 + fi +done + done +IFS=$as_save_IFS + +fi +fi +TRUE=$ac_cv_prog_TRUE +if test -n "$TRUE"; then + { $as_echo "$as_me:${as_lineno-$LINENO}: result: $TRUE" >&5 +$as_echo "$TRUE" >&6; } +else + { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 +$as_echo "no" >&6; } fi -{ echo "$as_me:$LINENO: result: $ac_cv_member_struct_stat_st_blksize" >&5 -echo "${ECHO_T}$ac_cv_member_struct_stat_st_blksize" >&6; } -if test $ac_cv_member_struct_stat_st_blksize = yes; then -cat >>confdefs.h <<_ACEOF -#define HAVE_STRUCT_STAT_ST_BLKSIZE 1 -_ACEOF + test -n "$TRUE" && break +done +test -n "$TRUE" || TRUE="/bin/true" -fi -{ echo "$as_me:$LINENO: checking for struct stat.st_flags" >&5 -echo $ECHO_N "checking for struct stat.st_flags... $ECHO_C" >&6; } -if test "${ac_cv_member_struct_stat_st_flags+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for inet_aton in -lc" >&5 +$as_echo_n "checking for inet_aton in -lc... " >&6; } +if test "${ac_cv_lib_c_inet_aton+set}" = set; then : + $as_echo_n "(cached) " >&6 else - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF + ac_check_lib_save_LIBS=$LIBS +LIBS="-lc $LIBS" +cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ -$ac_includes_default + +/* Override any GCC internal prototype to avoid an error. + Use char because int might match the return type of a GCC + builtin and then its argument prototype would still apply. */ +#ifdef __cplusplus +extern "C" +#endif +char inet_aton (); int main () { -static struct stat ac_aggr; -if (ac_aggr.st_flags) -return 0; +return inet_aton (); ; return 0; } _ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - ac_cv_member_struct_stat_st_flags=yes +if ac_fn_c_try_link "$LINENO"; then : + ac_cv_lib_c_inet_aton=yes else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF + ac_cv_lib_c_inet_aton=no +fi +rm -f core conftest.err conftest.$ac_objext \ + conftest$ac_exeext conftest.$ac_ext +LIBS=$ac_check_lib_save_LIBS +fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_lib_c_inet_aton" >&5 +$as_echo "$ac_cv_lib_c_inet_aton" >&6; } +if test "x$ac_cv_lib_c_inet_aton" = x""yes; then : + $ac_cv_prog_TRUE +else + { $as_echo "$as_me:${as_lineno-$LINENO}: checking for inet_aton in -lresolv" >&5 +$as_echo_n "checking for inet_aton in -lresolv... " >&6; } +if test "${ac_cv_lib_resolv_inet_aton+set}" = set; then : + $as_echo_n "(cached) " >&6 +else + ac_check_lib_save_LIBS=$LIBS +LIBS="-lresolv $LIBS" +cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ -$ac_includes_default + +/* Override any GCC internal prototype to avoid an error. + Use char because int might match the return type of a GCC + builtin and then its argument prototype would still apply. */ +#ifdef __cplusplus +extern "C" +#endif +char inet_aton (); int main () { -static struct stat ac_aggr; -if (sizeof ac_aggr.st_flags) -return 0; +return inet_aton (); ; return 0; } _ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - ac_cv_member_struct_stat_st_flags=yes +if ac_fn_c_try_link "$LINENO"; then : + ac_cv_lib_resolv_inet_aton=yes else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - ac_cv_member_struct_stat_st_flags=no + ac_cv_lib_resolv_inet_aton=no fi - -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext +rm -f core conftest.err conftest.$ac_objext \ + conftest$ac_exeext conftest.$ac_ext +LIBS=$ac_check_lib_save_LIBS fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_lib_resolv_inet_aton" >&5 +$as_echo "$ac_cv_lib_resolv_inet_aton" >&6; } +if test "x$ac_cv_lib_resolv_inet_aton" = x""yes; then : + cat >>confdefs.h <<_ACEOF +#define HAVE_LIBRESOLV 1 +_ACEOF -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext -fi -{ echo "$as_me:$LINENO: result: $ac_cv_member_struct_stat_st_flags" >&5 -echo "${ECHO_T}$ac_cv_member_struct_stat_st_flags" >&6; } -if test $ac_cv_member_struct_stat_st_flags = yes; then + LIBS="-lresolv $LIBS" -cat >>confdefs.h <<_ACEOF -#define HAVE_STRUCT_STAT_ST_FLAGS 1 -_ACEOF +fi fi -{ echo "$as_me:$LINENO: checking for struct stat.st_gen" >&5 -echo $ECHO_N "checking for struct stat.st_gen... $ECHO_C" >&6; } -if test "${ac_cv_member_struct_stat_st_gen+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 + +# On Tru64, chflags seems to be present, but calling it will +# exit Python +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for chflags" >&5 +$as_echo_n "checking for chflags... " >&6; } +if test "${ac_cv_have_chflags+set}" = set; then : + $as_echo_n "(cached) " >&6 else - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -$ac_includes_default -int -main () -{ -static struct stat ac_aggr; -if (ac_aggr.st_gen) -return 0; - ; - return 0; -} -_ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - ac_cv_member_struct_stat_st_gen=yes + if test "$cross_compiling" = yes; then : + ac_cv_have_chflags=cross else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF + cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ -$ac_includes_default -int -main () +[ +#include +#include +int main(int argc, char*argv[]) { -static struct stat ac_aggr; -if (sizeof ac_aggr.st_gen) -return 0; - ; + if(chflags(argv[0], 0) != 0) + return 1; return 0; } +] _ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - ac_cv_member_struct_stat_st_gen=yes +if ac_fn_c_try_run "$LINENO"; then : + ac_cv_have_chflags=yes else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - ac_cv_member_struct_stat_st_gen=no + ac_cv_have_chflags=no fi - -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext +rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext \ + conftest.$ac_objext conftest.beam conftest.$ac_ext fi -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext + +fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_have_chflags" >&5 +$as_echo "$ac_cv_have_chflags" >&6; } +if test "$ac_cv_have_chflags" = cross ; then + ac_fn_c_check_func "$LINENO" "chflags" "ac_cv_func_chflags" +if test "x$ac_cv_func_chflags" = x""yes; then : + ac_cv_have_chflags="yes" +else + ac_cv_have_chflags="no" fi -{ echo "$as_me:$LINENO: result: $ac_cv_member_struct_stat_st_gen" >&5 -echo "${ECHO_T}$ac_cv_member_struct_stat_st_gen" >&6; } -if test $ac_cv_member_struct_stat_st_gen = yes; then -cat >>confdefs.h <<_ACEOF -#define HAVE_STRUCT_STAT_ST_GEN 1 -_ACEOF +fi +if test "$ac_cv_have_chflags" = yes ; then +$as_echo "#define HAVE_CHFLAGS 1" >>confdefs.h fi -{ echo "$as_me:$LINENO: checking for struct stat.st_birthtime" >&5 -echo $ECHO_N "checking for struct stat.st_birthtime... $ECHO_C" >&6; } -if test "${ac_cv_member_struct_stat_st_birthtime+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for lchflags" >&5 +$as_echo_n "checking for lchflags... " >&6; } +if test "${ac_cv_have_lchflags+set}" = set; then : + $as_echo_n "(cached) " >&6 else - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -$ac_includes_default -int -main () -{ -static struct stat ac_aggr; -if (ac_aggr.st_birthtime) -return 0; - ; - return 0; -} -_ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - ac_cv_member_struct_stat_st_birthtime=yes + if test "$cross_compiling" = yes; then : + ac_cv_have_lchflags=cross else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF + cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ -$ac_includes_default -int -main () +[ +#include +#include +int main(int argc, char*argv[]) { -static struct stat ac_aggr; -if (sizeof ac_aggr.st_birthtime) -return 0; - ; + if(lchflags(argv[0], 0) != 0) + return 1; return 0; } +] _ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - ac_cv_member_struct_stat_st_birthtime=yes +if ac_fn_c_try_run "$LINENO"; then : + ac_cv_have_lchflags=yes else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - ac_cv_member_struct_stat_st_birthtime=no + ac_cv_have_lchflags=no fi - -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext +rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext \ + conftest.$ac_objext conftest.beam conftest.$ac_ext fi -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext + +fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_have_lchflags" >&5 +$as_echo "$ac_cv_have_lchflags" >&6; } +if test "$ac_cv_have_lchflags" = cross ; then + ac_fn_c_check_func "$LINENO" "lchflags" "ac_cv_func_lchflags" +if test "x$ac_cv_func_lchflags" = x""yes; then : + ac_cv_have_lchflags="yes" +else + ac_cv_have_lchflags="no" fi -{ echo "$as_me:$LINENO: result: $ac_cv_member_struct_stat_st_birthtime" >&5 -echo "${ECHO_T}$ac_cv_member_struct_stat_st_birthtime" >&6; } -if test $ac_cv_member_struct_stat_st_birthtime = yes; then -cat >>confdefs.h <<_ACEOF -#define HAVE_STRUCT_STAT_ST_BIRTHTIME 1 -_ACEOF +fi +if test "$ac_cv_have_lchflags" = yes ; then +$as_echo "#define HAVE_LCHFLAGS 1" >>confdefs.h fi -{ echo "$as_me:$LINENO: checking for struct stat.st_blocks" >&5 -echo $ECHO_N "checking for struct stat.st_blocks... $ECHO_C" >&6; } -if test "${ac_cv_member_struct_stat_st_blocks+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 -else - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -$ac_includes_default -int -main () -{ -static struct stat ac_aggr; -if (ac_aggr.st_blocks) -return 0; - ; - return 0; -} -_ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; +case $ac_sys_system/$ac_sys_release in +Darwin/*) + _CUR_CFLAGS="${CFLAGS}" + _CUR_LDFLAGS="${LDFLAGS}" + CFLAGS="${CFLAGS} -Wl,-search_paths_first" + LDFLAGS="${LDFLAGS} -Wl,-search_paths_first -L/usr/local/lib" + ;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - ac_cv_member_struct_stat_st_blocks=yes -else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for inflateCopy in -lz" >&5 +$as_echo_n "checking for inflateCopy in -lz... " >&6; } +if test "${ac_cv_lib_z_inflateCopy+set}" = set; then : + $as_echo_n "(cached) " >&6 +else + ac_check_lib_save_LIBS=$LIBS +LIBS="-lz $LIBS" +cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ -$ac_includes_default + +/* Override any GCC internal prototype to avoid an error. + Use char because int might match the return type of a GCC + builtin and then its argument prototype would still apply. */ +#ifdef __cplusplus +extern "C" +#endif +char inflateCopy (); int main () { -static struct stat ac_aggr; -if (sizeof ac_aggr.st_blocks) -return 0; +return inflateCopy (); ; return 0; } _ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - ac_cv_member_struct_stat_st_blocks=yes +if ac_fn_c_try_link "$LINENO"; then : + ac_cv_lib_z_inflateCopy=yes else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - ac_cv_member_struct_stat_st_blocks=no + ac_cv_lib_z_inflateCopy=no fi - -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext -fi - -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext +rm -f core conftest.err conftest.$ac_objext \ + conftest$ac_exeext conftest.$ac_ext +LIBS=$ac_check_lib_save_LIBS fi -{ echo "$as_me:$LINENO: result: $ac_cv_member_struct_stat_st_blocks" >&5 -echo "${ECHO_T}$ac_cv_member_struct_stat_st_blocks" >&6; } -if test $ac_cv_member_struct_stat_st_blocks = yes; then +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_lib_z_inflateCopy" >&5 +$as_echo "$ac_cv_lib_z_inflateCopy" >&6; } +if test "x$ac_cv_lib_z_inflateCopy" = x""yes; then : -cat >>confdefs.h <<_ACEOF -#define HAVE_STRUCT_STAT_ST_BLOCKS 1 -_ACEOF +$as_echo "#define HAVE_ZLIB_COPY 1" >>confdefs.h +fi -cat >>confdefs.h <<\_ACEOF -#define HAVE_ST_BLOCKS 1 -_ACEOF -else - case " $LIBOBJS " in - *" fileblocks.$ac_objext "* ) ;; - *) LIBOBJS="$LIBOBJS fileblocks.$ac_objext" - ;; +case $ac_sys_system/$ac_sys_release in +Darwin/*) + CFLAGS="${_CUR_CFLAGS}" + LDFLAGS="${_CUR_LDFLAGS}" + ;; esac -fi - +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for hstrerror" >&5 +$as_echo_n "checking for hstrerror... " >&6; } +cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ +#include "confdefs.h" +#include -{ echo "$as_me:$LINENO: checking for time.h that defines altzone" >&5 -echo $ECHO_N "checking for time.h that defines altzone... $ECHO_C" >&6; } -if test "${ac_cv_header_time_altzone+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 -else - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -#include int main () { -return altzone; +void* p = hstrerror; hstrerror(0) ; return 0; } _ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - ac_cv_header_time_altzone=yes +if ac_fn_c_try_link "$LINENO"; then : + +$as_echo "#define HAVE_HSTRERROR 1" >>confdefs.h + + { $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +$as_echo "yes" >&6; } else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 + { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 +$as_echo "no" >&6; } - ac_cv_header_time_altzone=no fi +rm -f core conftest.err conftest.$ac_objext \ + conftest$ac_exeext conftest.$ac_ext -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext -fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for inet_aton" >&5 +$as_echo_n "checking for inet_aton... " >&6; } +cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ -{ echo "$as_me:$LINENO: result: $ac_cv_header_time_altzone" >&5 -echo "${ECHO_T}$ac_cv_header_time_altzone" >&6; } -if test $ac_cv_header_time_altzone = yes; then +#include "confdefs.h" +#include +#include +#include +#include -cat >>confdefs.h <<\_ACEOF -#define HAVE_ALTZONE 1 +int +main () +{ +void* p = inet_aton;inet_aton(0,0) + ; + return 0; +} _ACEOF +if ac_fn_c_try_link "$LINENO"; then : + +$as_echo "#define HAVE_INET_ATON 1" >>confdefs.h + + { $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +$as_echo "yes" >&6; } +else + { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 +$as_echo "no" >&6; } fi +rm -f core conftest.err conftest.$ac_objext \ + conftest$ac_exeext conftest.$ac_ext -was_it_defined=no -{ echo "$as_me:$LINENO: checking whether sys/select.h and sys/time.h may both be included" >&5 -echo $ECHO_N "checking whether sys/select.h and sys/time.h may both be included... $ECHO_C" >&6; } -cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for inet_pton" >&5 +$as_echo_n "checking for inet_pton... " >&6; } +cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ +#include "confdefs.h" #include -#include -#include +#include +#include +#include int main () { -; +void* p = inet_pton ; return 0; } _ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - - -cat >>confdefs.h <<\_ACEOF -#define SYS_SELECT_WITH_SYS_TIME 1 -_ACEOF +if ac_fn_c_try_compile "$LINENO"; then : - was_it_defined=yes +$as_echo "#define HAVE_INET_PTON 1" >>confdefs.h + { $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +$as_echo "yes" >&6; } else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - + { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 +$as_echo "no" >&6; } fi - rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext -{ echo "$as_me:$LINENO: result: $was_it_defined" >&5 -echo "${ECHO_T}$was_it_defined" >&6; } -{ echo "$as_me:$LINENO: checking for addrinfo" >&5 -echo $ECHO_N "checking for addrinfo... $ECHO_C" >&6; } -if test "${ac_cv_struct_addrinfo+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 -else - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF +# On some systems, setgroups is in unistd.h, on others, in grp.h +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for setgroups" >&5 +$as_echo_n "checking for setgroups... " >&6; } +cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ -# include +#include "confdefs.h" +#include +#ifdef HAVE_GRP_H +#include +#endif + int main () { -struct addrinfo a +void* p = setgroups ; return 0; } _ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - ac_cv_struct_addrinfo=yes +if ac_fn_c_try_compile "$LINENO"; then : + +$as_echo "#define HAVE_SETGROUPS 1" >>confdefs.h + + { $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +$as_echo "yes" >&6; } else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 + { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 +$as_echo "no" >&6; } - ac_cv_struct_addrinfo=no fi - rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext -fi -{ echo "$as_me:$LINENO: result: $ac_cv_struct_addrinfo" >&5 -echo "${ECHO_T}$ac_cv_struct_addrinfo" >&6; } -if test $ac_cv_struct_addrinfo = yes; then +# check for openpty and forkpty -cat >>confdefs.h <<\_ACEOF -#define HAVE_ADDRINFO 1 +for ac_func in openpty +do : + ac_fn_c_check_func "$LINENO" "openpty" "ac_cv_func_openpty" +if test "x$ac_cv_func_openpty" = x""yes; then : + cat >>confdefs.h <<_ACEOF +#define HAVE_OPENPTY 1 _ACEOF -fi - -{ echo "$as_me:$LINENO: checking for sockaddr_storage" >&5 -echo $ECHO_N "checking for sockaddr_storage... $ECHO_C" >&6; } -if test "${ac_cv_struct_sockaddr_storage+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 else - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF + { $as_echo "$as_me:${as_lineno-$LINENO}: checking for openpty in -lutil" >&5 +$as_echo_n "checking for openpty in -lutil... " >&6; } +if test "${ac_cv_lib_util_openpty+set}" = set; then : + $as_echo_n "(cached) " >&6 +else + ac_check_lib_save_LIBS=$LIBS +LIBS="-lutil $LIBS" +cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ -# include -# include +/* Override any GCC internal prototype to avoid an error. + Use char because int might match the return type of a GCC + builtin and then its argument prototype would still apply. */ +#ifdef __cplusplus +extern "C" +#endif +char openpty (); int main () { -struct sockaddr_storage s +return openpty (); ; return 0; } _ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - ac_cv_struct_sockaddr_storage=yes +if ac_fn_c_try_link "$LINENO"; then : + ac_cv_lib_util_openpty=yes else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - ac_cv_struct_sockaddr_storage=no + ac_cv_lib_util_openpty=no fi - -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext -fi - -{ echo "$as_me:$LINENO: result: $ac_cv_struct_sockaddr_storage" >&5 -echo "${ECHO_T}$ac_cv_struct_sockaddr_storage" >&6; } -if test $ac_cv_struct_sockaddr_storage = yes; then - -cat >>confdefs.h <<\_ACEOF -#define HAVE_SOCKADDR_STORAGE 1 -_ACEOF - +rm -f core conftest.err conftest.$ac_objext \ + conftest$ac_exeext conftest.$ac_ext +LIBS=$ac_check_lib_save_LIBS fi - -# checks for compiler characteristics - - -{ echo "$as_me:$LINENO: checking whether char is unsigned" >&5 -echo $ECHO_N "checking whether char is unsigned... $ECHO_C" >&6; } -if test "${ac_cv_c_char_unsigned+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_lib_util_openpty" >&5 +$as_echo "$ac_cv_lib_util_openpty" >&6; } +if test "x$ac_cv_lib_util_openpty" = x""yes; then : + $as_echo "#define HAVE_OPENPTY 1" >>confdefs.h + LIBS="$LIBS -lutil" else - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF + { $as_echo "$as_me:${as_lineno-$LINENO}: checking for openpty in -lbsd" >&5 +$as_echo_n "checking for openpty in -lbsd... " >&6; } +if test "${ac_cv_lib_bsd_openpty+set}" = set; then : + $as_echo_n "(cached) " >&6 +else + ac_check_lib_save_LIBS=$LIBS +LIBS="-lbsd $LIBS" +cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ -$ac_includes_default + +/* Override any GCC internal prototype to avoid an error. + Use char because int might match the return type of a GCC + builtin and then its argument prototype would still apply. */ +#ifdef __cplusplus +extern "C" +#endif +char openpty (); int main () { -static int test_array [1 - 2 * !(((char) -1) < 0)]; -test_array [0] = 0 - +return openpty (); ; return 0; } _ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - ac_cv_c_char_unsigned=no +if ac_fn_c_try_link "$LINENO"; then : + ac_cv_lib_bsd_openpty=yes else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - ac_cv_c_char_unsigned=yes + ac_cv_lib_bsd_openpty=no +fi +rm -f core conftest.err conftest.$ac_objext \ + conftest$ac_exeext conftest.$ac_ext +LIBS=$ac_check_lib_save_LIBS +fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_lib_bsd_openpty" >&5 +$as_echo "$ac_cv_lib_bsd_openpty" >&6; } +if test "x$ac_cv_lib_bsd_openpty" = x""yes; then : + $as_echo "#define HAVE_OPENPTY 1" >>confdefs.h + LIBS="$LIBS -lbsd" fi -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext + fi -{ echo "$as_me:$LINENO: result: $ac_cv_c_char_unsigned" >&5 -echo "${ECHO_T}$ac_cv_c_char_unsigned" >&6; } -if test $ac_cv_c_char_unsigned = yes && test "$GCC" != yes; then - cat >>confdefs.h <<\_ACEOF -#define __CHAR_UNSIGNED__ 1 -_ACEOF + fi +done -{ echo "$as_me:$LINENO: checking for an ANSI C-conforming const" >&5 -echo $ECHO_N "checking for an ANSI C-conforming const... $ECHO_C" >&6; } -if test "${ac_cv_c_const+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 -else - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ +for ac_func in forkpty +do : + ac_fn_c_check_func "$LINENO" "forkpty" "ac_cv_func_forkpty" +if test "x$ac_cv_func_forkpty" = x""yes; then : + cat >>confdefs.h <<_ACEOF +#define HAVE_FORKPTY 1 _ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF + +else + { $as_echo "$as_me:${as_lineno-$LINENO}: checking for forkpty in -lutil" >&5 +$as_echo_n "checking for forkpty in -lutil... " >&6; } +if test "${ac_cv_lib_util_forkpty+set}" = set; then : + $as_echo_n "(cached) " >&6 +else + ac_check_lib_save_LIBS=$LIBS +LIBS="-lutil $LIBS" +cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ +/* Override any GCC internal prototype to avoid an error. + Use char because int might match the return type of a GCC + builtin and then its argument prototype would still apply. */ +#ifdef __cplusplus +extern "C" +#endif +char forkpty (); int main () { -/* FIXME: Include the comments suggested by Paul. */ -#ifndef __cplusplus - /* Ultrix mips cc rejects this. */ - typedef int charset[2]; - const charset cs; - /* SunOS 4.1.1 cc rejects this. */ - char const *const *pcpcc; - char **ppc; - /* NEC SVR4.0.2 mips cc rejects this. */ - struct point {int x, y;}; - static struct point const zero = {0,0}; - /* AIX XL C 1.02.0.0 rejects this. - It does not let you subtract one const X* pointer from another in - an arm of an if-expression whose if-part is not a constant - expression */ - const char *g = "string"; - pcpcc = &g + (g ? g-g : 0); - /* HPUX 7.0 cc rejects these. */ - ++pcpcc; - ppc = (char**) pcpcc; - pcpcc = (char const *const *) ppc; - { /* SCO 3.2v4 cc rejects this. */ - char *t; - char const *s = 0 ? (char *) 0 : (char const *) 0; +return forkpty (); + ; + return 0; +} +_ACEOF +if ac_fn_c_try_link "$LINENO"; then : + ac_cv_lib_util_forkpty=yes +else + ac_cv_lib_util_forkpty=no +fi +rm -f core conftest.err conftest.$ac_objext \ + conftest$ac_exeext conftest.$ac_ext +LIBS=$ac_check_lib_save_LIBS +fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_lib_util_forkpty" >&5 +$as_echo "$ac_cv_lib_util_forkpty" >&6; } +if test "x$ac_cv_lib_util_forkpty" = x""yes; then : + $as_echo "#define HAVE_FORKPTY 1" >>confdefs.h + LIBS="$LIBS -lutil" +else + { $as_echo "$as_me:${as_lineno-$LINENO}: checking for forkpty in -lbsd" >&5 +$as_echo_n "checking for forkpty in -lbsd... " >&6; } +if test "${ac_cv_lib_bsd_forkpty+set}" = set; then : + $as_echo_n "(cached) " >&6 +else + ac_check_lib_save_LIBS=$LIBS +LIBS="-lbsd $LIBS" +cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ - *t++ = 0; - if (s) return 0; - } - { /* Someone thinks the Sun supposedly-ANSI compiler will reject this. */ - int x[] = {25, 17}; - const int *foo = &x[0]; - ++foo; - } - { /* Sun SC1.0 ANSI compiler rejects this -- but not the above. */ - typedef const int *iptr; - iptr p = 0; - ++p; - } - { /* AIX XL C 1.02.0.0 rejects this saying - "k.c", line 2.27: 1506-025 (S) Operand must be a modifiable lvalue. */ - struct s { int j; const int *ap[3]; }; - struct s *b; b->j = 5; - } - { /* ULTRIX-32 V3.1 (Rev 9) vcc rejects this */ - const int foo = 10; - if (!foo) return 0; - } - return !cs[0] && !zero.x; +/* Override any GCC internal prototype to avoid an error. + Use char because int might match the return type of a GCC + builtin and then its argument prototype would still apply. */ +#ifdef __cplusplus +extern "C" #endif - +char forkpty (); +int +main () +{ +return forkpty (); ; return 0; } _ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - ac_cv_c_const=yes +if ac_fn_c_try_link "$LINENO"; then : + ac_cv_lib_bsd_forkpty=yes else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 + ac_cv_lib_bsd_forkpty=no +fi +rm -f core conftest.err conftest.$ac_objext \ + conftest$ac_exeext conftest.$ac_ext +LIBS=$ac_check_lib_save_LIBS +fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_lib_bsd_forkpty" >&5 +$as_echo "$ac_cv_lib_bsd_forkpty" >&6; } +if test "x$ac_cv_lib_bsd_forkpty" = x""yes; then : + $as_echo "#define HAVE_FORKPTY 1" >>confdefs.h + LIBS="$LIBS -lbsd" +fi + - ac_cv_c_const=no fi -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext + fi -{ echo "$as_me:$LINENO: result: $ac_cv_c_const" >&5 -echo "${ECHO_T}$ac_cv_c_const" >&6; } -if test $ac_cv_c_const = no; then +done + + +# Stuff for expat. +for ac_func in memmove +do : + ac_fn_c_check_func "$LINENO" "memmove" "ac_cv_func_memmove" +if test "x$ac_cv_func_memmove" = x""yes; then : + cat >>confdefs.h <<_ACEOF +#define HAVE_MEMMOVE 1 +_ACEOF + +fi +done + -cat >>confdefs.h <<\_ACEOF -#define const +# check for long file support functions +for ac_func in fseek64 fseeko fstatvfs ftell64 ftello statvfs +do : + as_ac_var=`$as_echo "ac_cv_func_$ac_func" | $as_tr_sh` +ac_fn_c_check_func "$LINENO" "$ac_func" "$as_ac_var" +eval as_val=\$$as_ac_var + if test "x$as_val" = x""yes; then : + cat >>confdefs.h <<_ACEOF +#define `$as_echo "HAVE_$ac_func" | $as_tr_cpp` 1 _ACEOF fi +done -works=no -{ echo "$as_me:$LINENO: checking for working volatile" >&5 -echo $ECHO_N "checking for working volatile... $ECHO_C" >&6; } -cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ +for ac_func in dup2 getcwd strdup +do : + as_ac_var=`$as_echo "ac_cv_func_$ac_func" | $as_tr_sh` +ac_fn_c_check_func "$LINENO" "$ac_func" "$as_ac_var" +eval as_val=\$$as_ac_var + if test "x$as_val" = x""yes; then : + cat >>confdefs.h <<_ACEOF +#define `$as_echo "HAVE_$ac_func" | $as_tr_cpp` 1 _ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ +else + case " $LIBOBJS " in + *" $ac_func.$ac_objext "* ) ;; + *) LIBOBJS="$LIBOBJS $ac_func.$ac_objext" + ;; +esac + +fi +done + + +for ac_func in getpgrp +do : + ac_fn_c_check_func "$LINENO" "getpgrp" "ac_cv_func_getpgrp" +if test "x$ac_cv_func_getpgrp" = x""yes; then : + cat >>confdefs.h <<_ACEOF +#define HAVE_GETPGRP 1 +_ACEOF + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ +#include int main () { -volatile int x; x = 0; +getpgrp(0); ; return 0; } _ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - works=yes -else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 +if ac_fn_c_try_compile "$LINENO"; then : +$as_echo "#define GETPGRP_HAVE_ARG 1" >>confdefs.h -cat >>confdefs.h <<\_ACEOF -#define volatile -_ACEOF +fi +rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext fi +done + +for ac_func in setpgrp +do : + ac_fn_c_check_func "$LINENO" "setpgrp" "ac_cv_func_setpgrp" +if test "x$ac_cv_func_setpgrp" = x""yes; then : + cat >>confdefs.h <<_ACEOF +#define HAVE_SETPGRP 1 +_ACEOF + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ +#include +int +main () +{ +setpgrp(0,0); + ; + return 0; +} +_ACEOF +if ac_fn_c_try_compile "$LINENO"; then : + +$as_echo "#define SETPGRP_HAVE_ARG 1" >>confdefs.h + +fi rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext -{ echo "$as_me:$LINENO: result: $works" >&5 -echo "${ECHO_T}$works" >&6; } -works=no -{ echo "$as_me:$LINENO: checking for working signed char" >&5 -echo $ECHO_N "checking for working signed char... $ECHO_C" >&6; } -cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ +fi +done + +for ac_func in gettimeofday +do : + ac_fn_c_check_func "$LINENO" "gettimeofday" "ac_cv_func_gettimeofday" +if test "x$ac_cv_func_gettimeofday" = x""yes; then : + cat >>confdefs.h <<_ACEOF +#define HAVE_GETTIMEOFDAY 1 _ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF + cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ - +#include int main () { -signed char c; +gettimeofday((struct timeval*)0,(struct timezone*)0); ; return 0; } _ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - works=yes +if ac_fn_c_try_compile "$LINENO"; then : + else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 +$as_echo "#define GETTIMEOFDAY_NO_TZ 1" >>confdefs.h -cat >>confdefs.h <<\_ACEOF -#define signed -_ACEOF +fi +rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext fi +done -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext -{ echo "$as_me:$LINENO: result: $works" >&5 -echo "${ECHO_T}$works" >&6; } -have_prototypes=no -{ echo "$as_me:$LINENO: checking for prototypes" >&5 -echo $ECHO_N "checking for prototypes... $ECHO_C" >&6; } -cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for major" >&5 +$as_echo_n "checking for major... " >&6; } +cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ -int foo(int x) { return 0; } + +#if defined(MAJOR_IN_MKDEV) +#include +#elif defined(MAJOR_IN_SYSMACROS) +#include +#else +#include +#endif + int main () { -return foo(10); + + makedev(major(0),minor(0)); + ; return 0; } _ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then +if ac_fn_c_try_link "$LINENO"; then : -cat >>confdefs.h <<\_ACEOF -#define HAVE_PROTOTYPES 1 -_ACEOF +$as_echo "#define HAVE_DEVICE_MACROS 1" >>confdefs.h - have_prototypes=yes + { $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +$as_echo "yes" >&6; } else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 + { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 +$as_echo "no" >&6; } fi +rm -f core conftest.err conftest.$ac_objext \ + conftest$ac_exeext conftest.$ac_ext -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext -{ echo "$as_me:$LINENO: result: $have_prototypes" >&5 -echo "${ECHO_T}$have_prototypes" >&6; } +# On OSF/1 V5.1, getaddrinfo is available, but a define +# for [no]getaddrinfo in netdb.h. +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for getaddrinfo" >&5 +$as_echo_n "checking for getaddrinfo... " >&6; } +cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ -works=no -{ echo "$as_me:$LINENO: checking for variable length prototypes and stdarg.h" >&5 -echo $ECHO_N "checking for variable length prototypes and stdarg.h... $ECHO_C" >&6; } -cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ +#include +#include +#include +#include + +int +main () +{ +getaddrinfo(NULL, NULL, NULL, NULL); + ; + return 0; +} _ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF +if ac_fn_c_try_link "$LINENO"; then : + have_getaddrinfo=yes +else + have_getaddrinfo=no +fi +rm -f core conftest.err conftest.$ac_objext \ + conftest$ac_exeext conftest.$ac_ext +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $have_getaddrinfo" >&5 +$as_echo "$have_getaddrinfo" >&6; } +if test $have_getaddrinfo = yes +then + { $as_echo "$as_me:${as_lineno-$LINENO}: checking getaddrinfo bug" >&5 +$as_echo_n "checking getaddrinfo bug... " >&6; } + if test "${ac_cv_buggy_getaddrinfo+set}" = set; then : + $as_echo_n "(cached) " >&6 +else + if test "$cross_compiling" = yes; then : + ac_cv_buggy_getaddrinfo=yes +else + cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ -#include -int foo(int x, ...) { - va_list va; - va_start(va, x); - va_arg(va, int); - va_arg(va, char *); - va_arg(va, double); - return 0; -} +#include +#include +#include +#include +#include + +int main() +{ + int passive, gaierr, inet4 = 0, inet6 = 0; + struct addrinfo hints, *ai, *aitop; + char straddr[INET6_ADDRSTRLEN], strport[16]; + + for (passive = 0; passive <= 1; passive++) { + memset(&hints, 0, sizeof(hints)); + hints.ai_family = AF_UNSPEC; + hints.ai_flags = passive ? AI_PASSIVE : 0; + hints.ai_socktype = SOCK_STREAM; + hints.ai_protocol = IPPROTO_TCP; + if ((gaierr = getaddrinfo(NULL, "54321", &hints, &aitop)) != 0) { + (void)gai_strerror(gaierr); + goto bad; + } + for (ai = aitop; ai; ai = ai->ai_next) { + if (ai->ai_addr == NULL || + ai->ai_addrlen == 0 || + getnameinfo(ai->ai_addr, ai->ai_addrlen, + straddr, sizeof(straddr), strport, sizeof(strport), + NI_NUMERICHOST|NI_NUMERICSERV) != 0) { + goto bad; + } + switch (ai->ai_family) { + case AF_INET: + if (strcmp(strport, "54321") != 0) { + goto bad; + } + if (passive) { + if (strcmp(straddr, "0.0.0.0") != 0) { + goto bad; + } + } else { + if (strcmp(straddr, "127.0.0.1") != 0) { + goto bad; + } + } + inet4++; + break; + case AF_INET6: + if (strcmp(strport, "54321") != 0) { + goto bad; + } + if (passive) { + if (strcmp(straddr, "::") != 0) { + goto bad; + } + } else { + if (strcmp(straddr, "::1") != 0) { + goto bad; + } + } + inet6++; + break; + case AF_UNSPEC: + goto bad; + break; + default: + /* another family support? */ + break; + } + } + } + + if (!(inet4 == 0 || inet4 == 2)) + goto bad; + if (!(inet6 == 0 || inet6 == 2)) + goto bad; -int -main () -{ -return foo(10, "", 3.14); - ; + if (aitop) + freeaddrinfo(aitop); return 0; -} -_ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then + bad: + if (aitop) + freeaddrinfo(aitop); + return 1; +} -cat >>confdefs.h <<\_ACEOF -#define HAVE_STDARG_PROTOTYPES 1 _ACEOF +if ac_fn_c_try_run "$LINENO"; then : + ac_cv_buggy_getaddrinfo=no +else + ac_cv_buggy_getaddrinfo=yes +fi +rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext \ + conftest.$ac_objext conftest.beam conftest.$ac_ext +fi - works=yes +fi + +fi +if test $have_getaddrinfo = no -o "$ac_cv_buggy_getaddrinfo" = yes +then + if test $ipv6 = yes + then + echo 'Fatal: You must get working getaddrinfo() function.' + echo ' or you can specify "--disable-ipv6"'. + exit 1 + fi else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 +$as_echo "#define HAVE_GETADDRINFO 1" >>confdefs.h fi +for ac_func in getnameinfo +do : + ac_fn_c_check_func "$LINENO" "getnameinfo" "ac_cv_func_getnameinfo" +if test "x$ac_cv_func_getnameinfo" = x""yes; then : + cat >>confdefs.h <<_ACEOF +#define HAVE_GETNAMEINFO 1 +_ACEOF -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext -{ echo "$as_me:$LINENO: result: $works" >&5 -echo "${ECHO_T}$works" >&6; } +fi +done -# check for socketpair -{ echo "$as_me:$LINENO: checking for socketpair" >&5 -echo $ECHO_N "checking for socketpair... $ECHO_C" >&6; } -cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ +# checks for structures +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking whether time.h and sys/time.h may both be included" >&5 +$as_echo_n "checking whether time.h and sys/time.h may both be included... " >&6; } +if test "${ac_cv_header_time+set}" = set; then : + $as_echo_n "(cached) " >&6 +else + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ #include -#include +#include +#include int main () { -void *x=socketpair +if ((struct tm *) 0) +return 0; ; return 0; } _ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - -cat >>confdefs.h <<\_ACEOF -#define HAVE_SOCKETPAIR 1 -_ACEOF - - { echo "$as_me:$LINENO: result: yes" >&5 -echo "${ECHO_T}yes" >&6; } +if ac_fn_c_try_compile "$LINENO"; then : + ac_cv_header_time=yes else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 + ac_cv_header_time=no +fi +rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext +fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_header_time" >&5 +$as_echo "$ac_cv_header_time" >&6; } +if test $ac_cv_header_time = yes; then - { echo "$as_me:$LINENO: result: no" >&5 -echo "${ECHO_T}no" >&6; } +$as_echo "#define TIME_WITH_SYS_TIME 1" >>confdefs.h fi -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext - -# check if sockaddr has sa_len member -{ echo "$as_me:$LINENO: checking if sockaddr has sa_len member" >&5 -echo $ECHO_N "checking if sockaddr has sa_len member... $ECHO_C" >&6; } -cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking whether struct tm is in sys/time.h or time.h" >&5 +$as_echo_n "checking whether struct tm is in sys/time.h or time.h... " >&6; } +if test "${ac_cv_struct_tm+set}" = set; then : + $as_echo_n "(cached) " >&6 +else + cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ #include -#include +#include + int main () { -struct sockaddr x; -x.sa_len = 0; +struct tm tm; + int *p = &tm.tm_sec; + return !p; ; return 0; } _ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - { echo "$as_me:$LINENO: result: yes" >&5 -echo "${ECHO_T}yes" >&6; } +if ac_fn_c_try_compile "$LINENO"; then : + ac_cv_struct_tm=time.h +else + ac_cv_struct_tm=sys/time.h +fi +rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext +fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_struct_tm" >&5 +$as_echo "$ac_cv_struct_tm" >&6; } +if test $ac_cv_struct_tm = sys/time.h; then + +$as_echo "#define TM_IN_SYS_TIME 1" >>confdefs.h + +fi + +ac_fn_c_check_member "$LINENO" "struct tm" "tm_zone" "ac_cv_member_struct_tm_tm_zone" "#include +#include <$ac_cv_struct_tm> -cat >>confdefs.h <<\_ACEOF -#define HAVE_SOCKADDR_SA_LEN 1 +" +if test "x$ac_cv_member_struct_tm_tm_zone" = x""yes; then : + +cat >>confdefs.h <<_ACEOF +#define HAVE_STRUCT_TM_TM_ZONE 1 _ACEOF -else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - { echo "$as_me:$LINENO: result: no" >&5 -echo "${ECHO_T}no" >&6; } fi -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext +if test "$ac_cv_member_struct_tm_tm_zone" = yes; then -va_list_is_array=no -{ echo "$as_me:$LINENO: checking whether va_list is an array" >&5 -echo $ECHO_N "checking whether va_list is an array... $ECHO_C" >&6; } -cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ +$as_echo "#define HAVE_TM_ZONE 1" >>confdefs.h + +else + ac_fn_c_check_decl "$LINENO" "tzname" "ac_cv_have_decl_tzname" "#include +" +if test "x$ac_cv_have_decl_tzname" = x""yes; then : + ac_have_decl=1 +else + ac_have_decl=0 +fi + +cat >>confdefs.h <<_ACEOF +#define HAVE_DECL_TZNAME $ac_have_decl _ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -#ifdef HAVE_STDARG_PROTOTYPES -#include -#else -#include + { $as_echo "$as_me:${as_lineno-$LINENO}: checking for tzname" >&5 +$as_echo_n "checking for tzname... " >&6; } +if test "${ac_cv_var_tzname+set}" = set; then : + $as_echo_n "(cached) " >&6 +else + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ +#include +#if !HAVE_DECL_TZNAME +extern char *tzname[]; #endif int main () { -va_list list1, list2; list1 = list2; +return tzname[0][0]; ; return 0; } _ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - : +if ac_fn_c_try_link "$LINENO"; then : + ac_cv_var_tzname=yes else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 + ac_cv_var_tzname=no +fi +rm -f core conftest.err conftest.$ac_objext \ + conftest$ac_exeext conftest.$ac_ext +fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_var_tzname" >&5 +$as_echo "$ac_cv_var_tzname" >&6; } + if test $ac_cv_var_tzname = yes; then + +$as_echo "#define HAVE_TZNAME 1" >>confdefs.h + fi +fi +ac_fn_c_check_member "$LINENO" "struct stat" "st_rdev" "ac_cv_member_struct_stat_st_rdev" "$ac_includes_default" +if test "x$ac_cv_member_struct_stat_st_rdev" = x""yes; then : -cat >>confdefs.h <<\_ACEOF -#define VA_LIST_IS_ARRAY 1 +cat >>confdefs.h <<_ACEOF +#define HAVE_STRUCT_STAT_ST_RDEV 1 _ACEOF - va_list_is_array=yes fi -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext -{ echo "$as_me:$LINENO: result: $va_list_is_array" >&5 -echo "${ECHO_T}$va_list_is_array" >&6; } +ac_fn_c_check_member "$LINENO" "struct stat" "st_blksize" "ac_cv_member_struct_stat_st_blksize" "$ac_includes_default" +if test "x$ac_cv_member_struct_stat_st_blksize" = x""yes; then : -# sigh -- gethostbyname_r is a mess; it can have 3, 5 or 6 arguments :-( +cat >>confdefs.h <<_ACEOF +#define HAVE_STRUCT_STAT_ST_BLKSIZE 1 +_ACEOF +fi -{ echo "$as_me:$LINENO: checking for gethostbyname_r" >&5 -echo $ECHO_N "checking for gethostbyname_r... $ECHO_C" >&6; } -if test "${ac_cv_func_gethostbyname_r+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 -else - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -/* Define gethostbyname_r to an innocuous variant, in case declares gethostbyname_r. - For example, HP-UX 11i declares gettimeofday. */ -#define gethostbyname_r innocuous_gethostbyname_r +ac_fn_c_check_member "$LINENO" "struct stat" "st_flags" "ac_cv_member_struct_stat_st_flags" "$ac_includes_default" +if test "x$ac_cv_member_struct_stat_st_flags" = x""yes; then : -/* System header to define __stub macros and hopefully few prototypes, - which can conflict with char gethostbyname_r (); below. - Prefer to if __STDC__ is defined, since - exists even on freestanding compilers. */ +cat >>confdefs.h <<_ACEOF +#define HAVE_STRUCT_STAT_ST_FLAGS 1 +_ACEOF -#ifdef __STDC__ -# include -#else -# include -#endif -#undef gethostbyname_r +fi -/* Override any GCC internal prototype to avoid an error. - Use char because int might match the return type of a GCC - builtin and then its argument prototype would still apply. */ -#ifdef __cplusplus -extern "C" -#endif -char gethostbyname_r (); -/* The GNU C library defines this for functions which it implements - to always fail with ENOSYS. Some functions are actually named - something starting with __ and the normal name is an alias. */ -#if defined __stub_gethostbyname_r || defined __stub___gethostbyname_r -choke me -#endif +ac_fn_c_check_member "$LINENO" "struct stat" "st_gen" "ac_cv_member_struct_stat_st_gen" "$ac_includes_default" +if test "x$ac_cv_member_struct_stat_st_gen" = x""yes; then : -int -main () -{ -return gethostbyname_r (); - ; - return 0; -} +cat >>confdefs.h <<_ACEOF +#define HAVE_STRUCT_STAT_ST_GEN 1 _ACEOF -rm -f conftest.$ac_objext conftest$ac_exeext -if { (ac_try="$ac_link" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_link") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest$ac_exeext && - $as_test_x conftest$ac_exeext; then - ac_cv_func_gethostbyname_r=yes -else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - ac_cv_func_gethostbyname_r=no -fi -rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \ - conftest$ac_exeext conftest.$ac_ext fi -{ echo "$as_me:$LINENO: result: $ac_cv_func_gethostbyname_r" >&5 -echo "${ECHO_T}$ac_cv_func_gethostbyname_r" >&6; } -if test $ac_cv_func_gethostbyname_r = yes; then - cat >>confdefs.h <<\_ACEOF -#define HAVE_GETHOSTBYNAME_R 1 -_ACEOF +ac_fn_c_check_member "$LINENO" "struct stat" "st_birthtime" "ac_cv_member_struct_stat_st_birthtime" "$ac_includes_default" +if test "x$ac_cv_member_struct_stat_st_birthtime" = x""yes; then : - { echo "$as_me:$LINENO: checking gethostbyname_r with 6 args" >&5 -echo $ECHO_N "checking gethostbyname_r with 6 args... $ECHO_C" >&6; } - OLD_CFLAGS=$CFLAGS - CFLAGS="$CFLAGS $MY_CPPFLAGS $MY_THREAD_CPPFLAGS $MY_CFLAGS" - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ +cat >>confdefs.h <<_ACEOF +#define HAVE_STRUCT_STAT_ST_BIRTHTIME 1 _ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -# include - -int -main () -{ - char *name; - struct hostent *he, *res; - char buffer[2048]; - int buflen = 2048; - int h_errnop; +fi - (void) gethostbyname_r(name, he, buffer, buflen, &res, &h_errnop) +ac_fn_c_check_member "$LINENO" "struct stat" "st_blocks" "ac_cv_member_struct_stat_st_blocks" "$ac_includes_default" +if test "x$ac_cv_member_struct_stat_st_blocks" = x""yes; then : - ; - return 0; -} +cat >>confdefs.h <<_ACEOF +#define HAVE_STRUCT_STAT_ST_BLOCKS 1 _ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; + + +$as_echo "#define HAVE_ST_BLOCKS 1" >>confdefs.h + +else + case " $LIBOBJS " in + *" fileblocks.$ac_objext "* ) ;; + *) LIBOBJS="$LIBOBJS fileblocks.$ac_objext" + ;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - cat >>confdefs.h <<\_ACEOF -#define HAVE_GETHOSTBYNAME_R 1 -_ACEOF +fi + -cat >>confdefs.h <<\_ACEOF -#define HAVE_GETHOSTBYNAME_R_6_ARG 1 +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for time.h that defines altzone" >&5 +$as_echo_n "checking for time.h that defines altzone... " >&6; } +if test "${ac_cv_header_time_altzone+set}" = set; then : + $as_echo_n "(cached) " >&6 +else + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ +#include +int +main () +{ +return altzone; + ; + return 0; +} _ACEOF +if ac_fn_c_try_compile "$LINENO"; then : + ac_cv_header_time_altzone=yes +else + ac_cv_header_time_altzone=no +fi +rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext +fi - { echo "$as_me:$LINENO: result: yes" >&5 -echo "${ECHO_T}yes" >&6; } +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_header_time_altzone" >&5 +$as_echo "$ac_cv_header_time_altzone" >&6; } +if test $ac_cv_header_time_altzone = yes; then -else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 +$as_echo "#define HAVE_ALTZONE 1" >>confdefs.h +fi - { echo "$as_me:$LINENO: result: no" >&5 -echo "${ECHO_T}no" >&6; } - { echo "$as_me:$LINENO: checking gethostbyname_r with 5 args" >&5 -echo $ECHO_N "checking gethostbyname_r with 5 args... $ECHO_C" >&6; } - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF +was_it_defined=no +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking whether sys/select.h and sys/time.h may both be included" >&5 +$as_echo_n "checking whether sys/select.h and sys/time.h may both be included... " >&6; } +cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ -# include +#include +#include +#include int main () { - - char *name; - struct hostent *he; - char buffer[2048]; - int buflen = 2048; - int h_errnop; - - (void) gethostbyname_r(name, he, buffer, buflen, &h_errnop) - +; ; return 0; } _ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then +if ac_fn_c_try_compile "$LINENO"; then : - cat >>confdefs.h <<\_ACEOF -#define HAVE_GETHOSTBYNAME_R 1 -_ACEOF +$as_echo "#define SYS_SELECT_WITH_SYS_TIME 1" >>confdefs.h -cat >>confdefs.h <<\_ACEOF -#define HAVE_GETHOSTBYNAME_R_5_ARG 1 -_ACEOF + was_it_defined=yes - { echo "$as_me:$LINENO: result: yes" >&5 -echo "${ECHO_T}yes" >&6; } +fi +rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $was_it_defined" >&5 +$as_echo "$was_it_defined" >&6; } +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for addrinfo" >&5 +$as_echo_n "checking for addrinfo... " >&6; } +if test "${ac_cv_struct_addrinfo+set}" = set; then : + $as_echo_n "(cached) " >&6 else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - - { echo "$as_me:$LINENO: result: no" >&5 -echo "${ECHO_T}no" >&6; } - { echo "$as_me:$LINENO: checking gethostbyname_r with 3 args" >&5 -echo $ECHO_N "checking gethostbyname_r with 3 args... $ECHO_C" >&6; } - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF + cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ -# include - +# include int main () { - - char *name; - struct hostent *he; - struct hostent_data data; - - (void) gethostbyname_r(name, he, &data); - +struct addrinfo a ; return 0; } _ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - - cat >>confdefs.h <<\_ACEOF -#define HAVE_GETHOSTBYNAME_R 1 -_ACEOF - - -cat >>confdefs.h <<\_ACEOF -#define HAVE_GETHOSTBYNAME_R_3_ARG 1 -_ACEOF - - { echo "$as_me:$LINENO: result: yes" >&5 -echo "${ECHO_T}yes" >&6; } - +if ac_fn_c_try_compile "$LINENO"; then : + ac_cv_struct_addrinfo=yes else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - - { echo "$as_me:$LINENO: result: no" >&5 -echo "${ECHO_T}no" >&6; } - -fi - -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext - + ac_cv_struct_addrinfo=no fi - rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext - fi -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext - CFLAGS=$OLD_CFLAGS +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_struct_addrinfo" >&5 +$as_echo "$ac_cv_struct_addrinfo" >&6; } +if test $ac_cv_struct_addrinfo = yes; then -else +$as_echo "#define HAVE_ADDRINFO 1" >>confdefs.h +fi -for ac_func in gethostbyname -do -as_ac_var=`echo "ac_cv_func_$ac_func" | $as_tr_sh` -{ echo "$as_me:$LINENO: checking for $ac_func" >&5 -echo $ECHO_N "checking for $ac_func... $ECHO_C" >&6; } -if { as_var=$as_ac_var; eval "test \"\${$as_var+set}\" = set"; }; then - echo $ECHO_N "(cached) $ECHO_C" >&6 +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for sockaddr_storage" >&5 +$as_echo_n "checking for sockaddr_storage... " >&6; } +if test "${ac_cv_struct_sockaddr_storage+set}" = set; then : + $as_echo_n "(cached) " >&6 else - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF + cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ -/* Define $ac_func to an innocuous variant, in case declares $ac_func. - For example, HP-UX 11i declares gettimeofday. */ -#define $ac_func innocuous_$ac_func - -/* System header to define __stub macros and hopefully few prototypes, - which can conflict with char $ac_func (); below. - Prefer to if __STDC__ is defined, since - exists even on freestanding compilers. */ - -#ifdef __STDC__ -# include -#else -# include -#endif - -#undef $ac_func - -/* Override any GCC internal prototype to avoid an error. - Use char because int might match the return type of a GCC - builtin and then its argument prototype would still apply. */ -#ifdef __cplusplus -extern "C" -#endif -char $ac_func (); -/* The GNU C library defines this for functions which it implements - to always fail with ENOSYS. Some functions are actually named - something starting with __ and the normal name is an alias. */ -#if defined __stub_$ac_func || defined __stub___$ac_func -choke me -#endif +# include +# include int main () { -return $ac_func (); +struct sockaddr_storage s ; return 0; } _ACEOF -rm -f conftest.$ac_objext conftest$ac_exeext -if { (ac_try="$ac_link" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_link") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest$ac_exeext && - $as_test_x conftest$ac_exeext; then - eval "$as_ac_var=yes" +if ac_fn_c_try_compile "$LINENO"; then : + ac_cv_struct_sockaddr_storage=yes else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - eval "$as_ac_var=no" + ac_cv_struct_sockaddr_storage=no fi - -rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \ - conftest$ac_exeext conftest.$ac_ext +rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext fi -ac_res=`eval echo '${'$as_ac_var'}'` - { echo "$as_me:$LINENO: result: $ac_res" >&5 -echo "${ECHO_T}$ac_res" >&6; } -if test `eval echo '${'$as_ac_var'}'` = yes; then - cat >>confdefs.h <<_ACEOF -#define `echo "HAVE_$ac_func" | $as_tr_cpp` 1 -_ACEOF -fi -done +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_struct_sockaddr_storage" >&5 +$as_echo "$ac_cv_struct_sockaddr_storage" >&6; } +if test $ac_cv_struct_sockaddr_storage = yes; then +$as_echo "#define HAVE_SOCKADDR_STORAGE 1" >>confdefs.h fi +# checks for compiler characteristics +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking whether char is unsigned" >&5 +$as_echo_n "checking whether char is unsigned... " >&6; } +if test "${ac_cv_c_char_unsigned+set}" = set; then : + $as_echo_n "(cached) " >&6 +else + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ +$ac_includes_default +int +main () +{ +static int test_array [1 - 2 * !(((char) -1) < 0)]; +test_array [0] = 0 + ; + return 0; +} +_ACEOF +if ac_fn_c_try_compile "$LINENO"; then : + ac_cv_c_char_unsigned=no +else + ac_cv_c_char_unsigned=yes +fi +rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext +fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_c_char_unsigned" >&5 +$as_echo "$ac_cv_c_char_unsigned" >&6; } +if test $ac_cv_c_char_unsigned = yes && test "$GCC" != yes; then + $as_echo "#define __CHAR_UNSIGNED__ 1" >>confdefs.h +fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for an ANSI C-conforming const" >&5 +$as_echo_n "checking for an ANSI C-conforming const... " >&6; } +if test "${ac_cv_c_const+set}" = set; then : + $as_echo_n "(cached) " >&6 +else + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ +int +main () +{ +/* FIXME: Include the comments suggested by Paul. */ +#ifndef __cplusplus + /* Ultrix mips cc rejects this. */ + typedef int charset[2]; + const charset cs; + /* SunOS 4.1.1 cc rejects this. */ + char const *const *pcpcc; + char **ppc; + /* NEC SVR4.0.2 mips cc rejects this. */ + struct point {int x, y;}; + static struct point const zero = {0,0}; + /* AIX XL C 1.02.0.0 rejects this. + It does not let you subtract one const X* pointer from another in + an arm of an if-expression whose if-part is not a constant + expression */ + const char *g = "string"; + pcpcc = &g + (g ? g-g : 0); + /* HPUX 7.0 cc rejects these. */ + ++pcpcc; + ppc = (char**) pcpcc; + pcpcc = (char const *const *) ppc; + { /* SCO 3.2v4 cc rejects this. */ + char *t; + char const *s = 0 ? (char *) 0 : (char const *) 0; -# checks for system services -# (none yet) + *t++ = 0; + if (s) return 0; + } + { /* Someone thinks the Sun supposedly-ANSI compiler will reject this. */ + int x[] = {25, 17}; + const int *foo = &x[0]; + ++foo; + } + { /* Sun SC1.0 ANSI compiler rejects this -- but not the above. */ + typedef const int *iptr; + iptr p = 0; + ++p; + } + { /* AIX XL C 1.02.0.0 rejects this saying + "k.c", line 2.27: 1506-025 (S) Operand must be a modifiable lvalue. */ + struct s { int j; const int *ap[3]; }; + struct s *b; b->j = 5; + } + { /* ULTRIX-32 V3.1 (Rev 9) vcc rejects this */ + const int foo = 10; + if (!foo) return 0; + } + return !cs[0] && !zero.x; +#endif -# Linux requires this for correct f.p. operations -{ echo "$as_me:$LINENO: checking for __fpu_control" >&5 -echo $ECHO_N "checking for __fpu_control... $ECHO_C" >&6; } -if test "${ac_cv_func___fpu_control+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 -else - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ + ; + return 0; +} _ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -/* Define __fpu_control to an innocuous variant, in case declares __fpu_control. - For example, HP-UX 11i declares gettimeofday. */ -#define __fpu_control innocuous___fpu_control +if ac_fn_c_try_compile "$LINENO"; then : + ac_cv_c_const=yes +else + ac_cv_c_const=no +fi +rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext +fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_c_const" >&5 +$as_echo "$ac_cv_c_const" >&6; } +if test $ac_cv_c_const = no; then -/* System header to define __stub macros and hopefully few prototypes, - which can conflict with char __fpu_control (); below. - Prefer to if __STDC__ is defined, since - exists even on freestanding compilers. */ +$as_echo "#define const /**/" >>confdefs.h -#ifdef __STDC__ -# include -#else -# include -#endif +fi -#undef __fpu_control -/* Override any GCC internal prototype to avoid an error. - Use char because int might match the return type of a GCC - builtin and then its argument prototype would still apply. */ -#ifdef __cplusplus -extern "C" -#endif -char __fpu_control (); -/* The GNU C library defines this for functions which it implements - to always fail with ENOSYS. Some functions are actually named - something starting with __ and the normal name is an alias. */ -#if defined __stub___fpu_control || defined __stub_____fpu_control -choke me -#endif +works=no +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for working volatile" >&5 +$as_echo_n "checking for working volatile... " >&6; } +cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ int main () { -return __fpu_control (); +volatile int x; x = 0; ; return 0; } _ACEOF -rm -f conftest.$ac_objext conftest$ac_exeext -if { (ac_try="$ac_link" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_link") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest$ac_exeext && - $as_test_x conftest$ac_exeext; then - ac_cv_func___fpu_control=yes +if ac_fn_c_try_compile "$LINENO"; then : + works=yes else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - ac_cv_func___fpu_control=no -fi +$as_echo "#define volatile /**/" >>confdefs.h + -rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \ - conftest$ac_exeext conftest.$ac_ext fi -{ echo "$as_me:$LINENO: result: $ac_cv_func___fpu_control" >&5 -echo "${ECHO_T}$ac_cv_func___fpu_control" >&6; } -if test $ac_cv_func___fpu_control = yes; then - : -else +rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $works" >&5 +$as_echo "$works" >&6; } -{ echo "$as_me:$LINENO: checking for __fpu_control in -lieee" >&5 -echo $ECHO_N "checking for __fpu_control in -lieee... $ECHO_C" >&6; } -if test "${ac_cv_lib_ieee___fpu_control+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 -else - ac_check_lib_save_LIBS=$LIBS -LIBS="-lieee $LIBS" -cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF +works=no +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for working signed char" >&5 +$as_echo_n "checking for working signed char... " >&6; } +cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ -/* Override any GCC internal prototype to avoid an error. - Use char because int might match the return type of a GCC - builtin and then its argument prototype would still apply. */ -#ifdef __cplusplus -extern "C" -#endif -char __fpu_control (); int main () { -return __fpu_control (); +signed char c; ; return 0; } _ACEOF -rm -f conftest.$ac_objext conftest$ac_exeext -if { (ac_try="$ac_link" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_link") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest$ac_exeext && - $as_test_x conftest$ac_exeext; then - ac_cv_lib_ieee___fpu_control=yes +if ac_fn_c_try_compile "$LINENO"; then : + works=yes else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - ac_cv_lib_ieee___fpu_control=no -fi +$as_echo "#define signed /**/" >>confdefs.h + -rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \ - conftest$ac_exeext conftest.$ac_ext -LIBS=$ac_check_lib_save_LIBS fi -{ echo "$as_me:$LINENO: result: $ac_cv_lib_ieee___fpu_control" >&5 -echo "${ECHO_T}$ac_cv_lib_ieee___fpu_control" >&6; } -if test $ac_cv_lib_ieee___fpu_control = yes; then - cat >>confdefs.h <<_ACEOF -#define HAVE_LIBIEEE 1 +rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $works" >&5 +$as_echo "$works" >&6; } + +have_prototypes=no +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for prototypes" >&5 +$as_echo_n "checking for prototypes... " >&6; } +cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ +int foo(int x) { return 0; } +int +main () +{ +return foo(10); + ; + return 0; +} _ACEOF +if ac_fn_c_try_compile "$LINENO"; then : - LIBS="-lieee $LIBS" -fi +$as_echo "#define HAVE_PROTOTYPES 1" >>confdefs.h + have_prototypes=yes fi +rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $have_prototypes" >&5 +$as_echo "$have_prototypes" >&6; } +works=no +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for variable length prototypes and stdarg.h" >&5 +$as_echo_n "checking for variable length prototypes and stdarg.h... " >&6; } +cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ -# Check for --with-fpectl -{ echo "$as_me:$LINENO: checking for --with-fpectl" >&5 -echo $ECHO_N "checking for --with-fpectl... $ECHO_C" >&6; } - -# Check whether --with-fpectl was given. -if test "${with_fpectl+set}" = set; then - withval=$with_fpectl; -if test "$withval" != no -then +#include +int foo(int x, ...) { + va_list va; + va_start(va, x); + va_arg(va, int); + va_arg(va, char *); + va_arg(va, double); + return 0; +} -cat >>confdefs.h <<\_ACEOF -#define WANT_SIGFPE_HANDLER 1 +int +main () +{ +return foo(10, "", 3.14); + ; + return 0; +} _ACEOF - - { echo "$as_me:$LINENO: result: yes" >&5 -echo "${ECHO_T}yes" >&6; } -else { echo "$as_me:$LINENO: result: no" >&5 -echo "${ECHO_T}no" >&6; } -fi -else - { echo "$as_me:$LINENO: result: no" >&5 -echo "${ECHO_T}no" >&6; } -fi +if ac_fn_c_try_compile "$LINENO"; then : -# check for --with-libm=... +$as_echo "#define HAVE_STDARG_PROTOTYPES 1" >>confdefs.h -case $ac_sys_system in -Darwin) ;; -BeOS) ;; -*) LIBM=-lm -esac -{ echo "$as_me:$LINENO: checking for --with-libm=STRING" >&5 -echo $ECHO_N "checking for --with-libm=STRING... $ECHO_C" >&6; } + works=yes -# Check whether --with-libm was given. -if test "${with_libm+set}" = set; then - withval=$with_libm; -if test "$withval" = no -then LIBM= - { echo "$as_me:$LINENO: result: force LIBM empty" >&5 -echo "${ECHO_T}force LIBM empty" >&6; } -elif test "$withval" != yes -then LIBM=$withval - { echo "$as_me:$LINENO: result: set LIBM=\"$withval\"" >&5 -echo "${ECHO_T}set LIBM=\"$withval\"" >&6; } -else { { echo "$as_me:$LINENO: error: proper usage is --with-libm=STRING" >&5 -echo "$as_me: error: proper usage is --with-libm=STRING" >&2;} - { (exit 1); exit 1; }; } -fi -else - { echo "$as_me:$LINENO: result: default LIBM=\"$LIBM\"" >&5 -echo "${ECHO_T}default LIBM=\"$LIBM\"" >&6; } fi +rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $works" >&5 +$as_echo "$works" >&6; } +# check for socketpair +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for socketpair" >&5 +$as_echo_n "checking for socketpair... " >&6; } +cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ -# check for --with-libc=... +#include +#include + +int +main () +{ +void *x=socketpair + ; + return 0; +} +_ACEOF +if ac_fn_c_try_compile "$LINENO"; then : -{ echo "$as_me:$LINENO: checking for --with-libc=STRING" >&5 -echo $ECHO_N "checking for --with-libc=STRING... $ECHO_C" >&6; } +$as_echo "#define HAVE_SOCKETPAIR 1" >>confdefs.h -# Check whether --with-libc was given. -if test "${with_libc+set}" = set; then - withval=$with_libc; -if test "$withval" = no -then LIBC= - { echo "$as_me:$LINENO: result: force LIBC empty" >&5 -echo "${ECHO_T}force LIBC empty" >&6; } -elif test "$withval" != yes -then LIBC=$withval - { echo "$as_me:$LINENO: result: set LIBC=\"$withval\"" >&5 -echo "${ECHO_T}set LIBC=\"$withval\"" >&6; } -else { { echo "$as_me:$LINENO: error: proper usage is --with-libc=STRING" >&5 -echo "$as_me: error: proper usage is --with-libc=STRING" >&2;} - { (exit 1); exit 1; }; } -fi + { $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +$as_echo "yes" >&6; } else - { echo "$as_me:$LINENO: result: default LIBC=\"$LIBC\"" >&5 -echo "${ECHO_T}default LIBC=\"$LIBC\"" >&6; } + { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 +$as_echo "no" >&6; } + fi +rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext +# check if sockaddr has sa_len member +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking if sockaddr has sa_len member" >&5 +$as_echo_n "checking if sockaddr has sa_len member... " >&6; } +cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ +#include +#include +int +main () +{ +struct sockaddr x; +x.sa_len = 0; + ; + return 0; +} +_ACEOF +if ac_fn_c_try_compile "$LINENO"; then : + { $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +$as_echo "yes" >&6; } -# ************************************************** -# * Check for various properties of floating point * -# ************************************************** +$as_echo "#define HAVE_SOCKADDR_SA_LEN 1" >>confdefs.h -{ echo "$as_me:$LINENO: checking whether C doubles are little-endian IEEE 754 binary64" >&5 -echo $ECHO_N "checking whether C doubles are little-endian IEEE 754 binary64... $ECHO_C" >&6; } -if test "${ac_cv_little_endian_double+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 else + { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 +$as_echo "no" >&6; } +fi +rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext -if test "$cross_compiling" = yes; then - ac_cv_little_endian_double=no -else - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF +va_list_is_array=no +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking whether va_list is an array" >&5 +$as_echo_n "checking whether va_list is an array... " >&6; } +cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ -#include -int main() { - double x = 9006104071832581.0; - if (memcmp(&x, "\x05\x04\x03\x02\x01\xff\x3f\x43", 8) == 0) - return 0; - else - return 1; -} +#ifdef HAVE_STDARG_PROTOTYPES +#include +#else +#include +#endif +int +main () +{ +va_list list1, list2; list1 = list2; + ; + return 0; +} _ACEOF -rm -f conftest$ac_exeext -if { (ac_try="$ac_link" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_link") 2>&5 - ac_status=$? - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { ac_try='./conftest$ac_exeext' - { (case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_try") 2>&5 - ac_status=$? - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); }; }; then - ac_cv_little_endian_double=yes +if ac_fn_c_try_compile "$LINENO"; then : + else - echo "$as_me: program exited with status $ac_status" >&5 -echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 -( exit $ac_status ) -ac_cv_little_endian_double=no -fi -rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext conftest.$ac_objext conftest.$ac_ext -fi +$as_echo "#define VA_LIST_IS_ARRAY 1" >>confdefs.h + + va_list_is_array=yes fi +rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $va_list_is_array" >&5 +$as_echo "$va_list_is_array" >&6; } -{ echo "$as_me:$LINENO: result: $ac_cv_little_endian_double" >&5 -echo "${ECHO_T}$ac_cv_little_endian_double" >&6; } -if test "$ac_cv_little_endian_double" = yes -then +# sigh -- gethostbyname_r is a mess; it can have 3, 5 or 6 arguments :-( -cat >>confdefs.h <<\_ACEOF -#define DOUBLE_IS_LITTLE_ENDIAN_IEEE754 1 -_ACEOF -fi +ac_fn_c_check_func "$LINENO" "gethostbyname_r" "ac_cv_func_gethostbyname_r" +if test "x$ac_cv_func_gethostbyname_r" = x""yes; then : -{ echo "$as_me:$LINENO: checking whether C doubles are big-endian IEEE 754 binary64" >&5 -echo $ECHO_N "checking whether C doubles are big-endian IEEE 754 binary64... $ECHO_C" >&6; } -if test "${ac_cv_big_endian_double+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 -else + $as_echo "#define HAVE_GETHOSTBYNAME_R 1" >>confdefs.h -if test "$cross_compiling" = yes; then - ac_cv_big_endian_double=no -else - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF + { $as_echo "$as_me:${as_lineno-$LINENO}: checking gethostbyname_r with 6 args" >&5 +$as_echo_n "checking gethostbyname_r with 6 args... " >&6; } + OLD_CFLAGS=$CFLAGS + CFLAGS="$CFLAGS $MY_CPPFLAGS $MY_THREAD_CPPFLAGS $MY_CFLAGS" + cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ -#include -int main() { - double x = 9006104071832581.0; - if (memcmp(&x, "\x43\x3f\xff\x01\x02\x03\x04\x05", 8) == 0) - return 0; - else - return 1; -} - -_ACEOF -rm -f conftest$ac_exeext -if { (ac_try="$ac_link" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_link") 2>&5 - ac_status=$? - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { ac_try='./conftest$ac_exeext' - { (case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_try") 2>&5 - ac_status=$? - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); }; }; then - ac_cv_big_endian_double=yes -else - echo "$as_me: program exited with status $ac_status" >&5 -echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - -( exit $ac_status ) -ac_cv_big_endian_double=no -fi -rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext conftest.$ac_objext conftest.$ac_ext -fi +# include +int +main () +{ -fi + char *name; + struct hostent *he, *res; + char buffer[2048]; + int buflen = 2048; + int h_errnop; -{ echo "$as_me:$LINENO: result: $ac_cv_big_endian_double" >&5 -echo "${ECHO_T}$ac_cv_big_endian_double" >&6; } -if test "$ac_cv_big_endian_double" = yes -then + (void) gethostbyname_r(name, he, buffer, buflen, &res, &h_errnop) -cat >>confdefs.h <<\_ACEOF -#define DOUBLE_IS_BIG_ENDIAN_IEEE754 1 + ; + return 0; +} _ACEOF +if ac_fn_c_try_compile "$LINENO"; then : -fi + $as_echo "#define HAVE_GETHOSTBYNAME_R 1" >>confdefs.h -# Some ARM platforms use a mixed-endian representation for doubles. -# While Python doesn't currently have full support for these platforms -# (see e.g., issue 1762561), we can at least make sure that float <-> string -# conversions work. -{ echo "$as_me:$LINENO: checking whether C doubles are ARM mixed-endian IEEE 754 binary64" >&5 -echo $ECHO_N "checking whether C doubles are ARM mixed-endian IEEE 754 binary64... $ECHO_C" >&6; } -if test "${ac_cv_mixed_endian_double+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 -else -if test "$cross_compiling" = yes; then - ac_cv_mixed_endian_double=no -else - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ +$as_echo "#define HAVE_GETHOSTBYNAME_R_6_ARG 1" >>confdefs.h -#include -int main() { - double x = 9006104071832581.0; - if (memcmp(&x, "\x01\xff\x3f\x43\x05\x04\x03\x02", 8) == 0) - return 0; - else - return 1; -} + { $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +$as_echo "yes" >&6; } -_ACEOF -rm -f conftest$ac_exeext -if { (ac_try="$ac_link" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_link") 2>&5 - ac_status=$? - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { ac_try='./conftest$ac_exeext' - { (case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_try") 2>&5 - ac_status=$? - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); }; }; then - ac_cv_mixed_endian_double=yes else - echo "$as_me: program exited with status $ac_status" >&5 -echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 -( exit $ac_status ) -ac_cv_mixed_endian_double=no -fi -rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext conftest.$ac_objext conftest.$ac_ext -fi + { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 +$as_echo "no" >&6; } + { $as_echo "$as_me:${as_lineno-$LINENO}: checking gethostbyname_r with 5 args" >&5 +$as_echo_n "checking gethostbyname_r with 5 args... " >&6; } + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + +# include +int +main () +{ -fi + char *name; + struct hostent *he; + char buffer[2048]; + int buflen = 2048; + int h_errnop; -{ echo "$as_me:$LINENO: result: $ac_cv_mixed_endian_double" >&5 -echo "${ECHO_T}$ac_cv_mixed_endian_double" >&6; } -if test "$ac_cv_mixed_endian_double" = yes -then + (void) gethostbyname_r(name, he, buffer, buflen, &h_errnop) -cat >>confdefs.h <<\_ACEOF -#define DOUBLE_IS_ARM_MIXED_ENDIAN_IEEE754 1 + ; + return 0; +} _ACEOF +if ac_fn_c_try_compile "$LINENO"; then : -fi + $as_echo "#define HAVE_GETHOSTBYNAME_R 1" >>confdefs.h -# The short float repr introduced in Python 3.1 requires the -# correctly-rounded string <-> double conversion functions from -# Python/dtoa.c, which in turn require that the FPU uses 53-bit -# rounding; this is a problem on x86, where the x87 FPU has a default -# rounding precision of 64 bits. For gcc/x86, we can fix this by -# using inline assembler to get and set the x87 FPU control word. -# This inline assembler syntax may also work for suncc and icc, -# so we try it on all platforms. +$as_echo "#define HAVE_GETHOSTBYNAME_R_5_ARG 1" >>confdefs.h -{ echo "$as_me:$LINENO: checking whether we can use gcc inline assembler to get and set x87 control word" >&5 -echo $ECHO_N "checking whether we can use gcc inline assembler to get and set x87 control word... $ECHO_C" >&6; } -cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF + { $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +$as_echo "yes" >&6; } + +else + + { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 +$as_echo "no" >&6; } + { $as_echo "$as_me:${as_lineno-$LINENO}: checking gethostbyname_r with 3 args" >&5 +$as_echo_n "checking gethostbyname_r with 3 args... " >&6; } + cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ +# include + int main () { - unsigned short cw; - __asm__ __volatile__ ("fnstcw %0" : "=m" (cw)); - __asm__ __volatile__ ("fldcw %0" : : "m" (cw)); + char *name; + struct hostent *he; + struct hostent_data data; + + (void) gethostbyname_r(name, he, &data); ; return 0; } _ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - have_gcc_asm_for_x87=yes +if ac_fn_c_try_compile "$LINENO"; then : + + $as_echo "#define HAVE_GETHOSTBYNAME_R 1" >>confdefs.h + + +$as_echo "#define HAVE_GETHOSTBYNAME_R_3_ARG 1" >>confdefs.h + + { $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +$as_echo "yes" >&6; } + else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - have_gcc_asm_for_x87=no -fi + { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 +$as_echo "no" >&6; } +fi rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext -{ echo "$as_me:$LINENO: result: $have_gcc_asm_for_x87" >&5 -echo "${ECHO_T}$have_gcc_asm_for_x87" >&6; } -if test "$have_gcc_asm_for_x87" = yes -then -cat >>confdefs.h <<\_ACEOF -#define HAVE_GCC_ASM_FOR_X87 1 -_ACEOF +fi +rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext fi +rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext + CFLAGS=$OLD_CFLAGS -# Detect whether system arithmetic is subject to x87-style double -# rounding issues. The result of this test has little meaning on non -# IEEE 754 platforms. On IEEE 754, test should return 1 if rounding -# mode is round-to-nearest and double rounding issues are present, and -# 0 otherwise. See http://bugs.python.org/issue2937 for more info. -{ echo "$as_me:$LINENO: checking for x87-style double rounding" >&5 -echo $ECHO_N "checking for x87-style double rounding... $ECHO_C" >&6; } -# $BASECFLAGS may affect the result -ac_save_cc="$CC" -CC="$CC $BASECFLAGS" -if test "$cross_compiling" = yes; then - ac_cv_x87_double_rounding=no else - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ - -#include -#include -int main() { - volatile double x, y, z; - /* 1./(1-2**-53) -> 1+2**-52 (correct), 1.0 (double rounding) */ - x = 0.99999999999999989; /* 1-2**-53 */ - y = 1./x; - if (y != 1.) - exit(0); - /* 1e16+2.99999 -> 1e16+2. (correct), 1e16+4. (double rounding) */ - x = 1e16; - y = 2.99999; - z = x + y; - if (z != 1e16+4.) - exit(0); - /* both tests show evidence of double rounding */ - exit(1); -} + for ac_func in gethostbyname +do : + ac_fn_c_check_func "$LINENO" "gethostbyname" "ac_cv_func_gethostbyname" +if test "x$ac_cv_func_gethostbyname" = x""yes; then : + cat >>confdefs.h <<_ACEOF +#define HAVE_GETHOSTBYNAME 1 _ACEOF -rm -f conftest$ac_exeext -if { (ac_try="$ac_link" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_link") 2>&5 - ac_status=$? - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { ac_try='./conftest$ac_exeext' - { (case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_try") 2>&5 - ac_status=$? - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); }; }; then - ac_cv_x87_double_rounding=no -else - echo "$as_me: program exited with status $ac_status" >&5 -echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 -( exit $ac_status ) -ac_cv_x87_double_rounding=yes fi -rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext conftest.$ac_objext conftest.$ac_ext +done + + fi -CC="$ac_save_cc" -{ echo "$as_me:$LINENO: result: $ac_cv_x87_double_rounding" >&5 -echo "${ECHO_T}$ac_cv_x87_double_rounding" >&6; } -if test "$ac_cv_x87_double_rounding" = yes -then -cat >>confdefs.h <<\_ACEOF -#define X87_DOUBLE_ROUNDING 1 -_ACEOF -fi -# ************************************ -# * Check for mathematical functions * -# ************************************ -LIBS_SAVE=$LIBS -LIBS="$LIBS $LIBM" -# On FreeBSD 6.2, it appears that tanh(-0.) returns 0. instead of -# -0. on some architectures. -{ echo "$as_me:$LINENO: checking whether tanh preserves the sign of zero" >&5 -echo $ECHO_N "checking whether tanh preserves the sign of zero... $ECHO_C" >&6; } -if test "${ac_cv_tanh_preserves_zero_sign+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 -else +# checks for system services +# (none yet) + +# Linux requires this for correct f.p. operations +ac_fn_c_check_func "$LINENO" "__fpu_control" "ac_cv_func___fpu_control" +if test "x$ac_cv_func___fpu_control" = x""yes; then : -if test "$cross_compiling" = yes; then - ac_cv_tanh_preserves_zero_sign=no else - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF + { $as_echo "$as_me:${as_lineno-$LINENO}: checking for __fpu_control in -lieee" >&5 +$as_echo_n "checking for __fpu_control in -lieee... " >&6; } +if test "${ac_cv_lib_ieee___fpu_control+set}" = set; then : + $as_echo_n "(cached) " >&6 +else + ac_check_lib_save_LIBS=$LIBS +LIBS="-lieee $LIBS" +cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ -#include -#include -int main() { - /* return 0 if either negative zeros don't exist - on this platform or if negative zeros exist - and tanh(-0.) == -0. */ - if (atan2(0., -1.) == atan2(-0., -1.) || - atan2(tanh(-0.), -1.) == atan2(-0., -1.)) exit(0); - else exit(1); +/* Override any GCC internal prototype to avoid an error. + Use char because int might match the return type of a GCC + builtin and then its argument prototype would still apply. */ +#ifdef __cplusplus +extern "C" +#endif +char __fpu_control (); +int +main () +{ +return __fpu_control (); + ; + return 0; } - _ACEOF -rm -f conftest$ac_exeext -if { (ac_try="$ac_link" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_link") 2>&5 - ac_status=$? - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { ac_try='./conftest$ac_exeext' - { (case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_try") 2>&5 - ac_status=$? - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); }; }; then - ac_cv_tanh_preserves_zero_sign=yes +if ac_fn_c_try_link "$LINENO"; then : + ac_cv_lib_ieee___fpu_control=yes else - echo "$as_me: program exited with status $ac_status" >&5 -echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - -( exit $ac_status ) -ac_cv_tanh_preserves_zero_sign=no + ac_cv_lib_ieee___fpu_control=no fi -rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext conftest.$ac_objext conftest.$ac_ext +rm -f core conftest.err conftest.$ac_objext \ + conftest$ac_exeext conftest.$ac_ext +LIBS=$ac_check_lib_save_LIBS +fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_lib_ieee___fpu_control" >&5 +$as_echo "$ac_cv_lib_ieee___fpu_control" >&6; } +if test "x$ac_cv_lib_ieee___fpu_control" = x""yes; then : + cat >>confdefs.h <<_ACEOF +#define HAVE_LIBIEEE 1 +_ACEOF + + LIBS="-lieee $LIBS" + fi fi -{ echo "$as_me:$LINENO: result: $ac_cv_tanh_preserves_zero_sign" >&5 -echo "${ECHO_T}$ac_cv_tanh_preserves_zero_sign" >&6; } -if test "$ac_cv_tanh_preserves_zero_sign" = yes -then -cat >>confdefs.h <<\_ACEOF -#define TANH_PRESERVES_ZERO_SIGN 1 -_ACEOF +# Check for --with-fpectl +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for --with-fpectl" >&5 +$as_echo_n "checking for --with-fpectl... " >&6; } -fi +# Check whether --with-fpectl was given. +if test "${with_fpectl+set}" = set; then : + withval=$with_fpectl; +if test "$withval" != no +then +$as_echo "#define WANT_SIGFPE_HANDLER 1" >>confdefs.h + { $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +$as_echo "yes" >&6; } +else { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 +$as_echo "no" >&6; } +fi +else + { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 +$as_echo "no" >&6; } +fi +# check for --with-libm=... +case $ac_sys_system in +Darwin) ;; +BeOS) ;; +*) LIBM=-lm +esac +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for --with-libm=STRING" >&5 +$as_echo_n "checking for --with-libm=STRING... " >&6; } +# Check whether --with-libm was given. +if test "${with_libm+set}" = set; then : + withval=$with_libm; +if test "$withval" = no +then LIBM= + { $as_echo "$as_me:${as_lineno-$LINENO}: result: force LIBM empty" >&5 +$as_echo "force LIBM empty" >&6; } +elif test "$withval" != yes +then LIBM=$withval + { $as_echo "$as_me:${as_lineno-$LINENO}: result: set LIBM=\"$withval\"" >&5 +$as_echo "set LIBM=\"$withval\"" >&6; } +else as_fn_error "proper usage is --with-libm=STRING" "$LINENO" 5 +fi +else + { $as_echo "$as_me:${as_lineno-$LINENO}: result: default LIBM=\"$LIBM\"" >&5 +$as_echo "default LIBM=\"$LIBM\"" >&6; } +fi +# check for --with-libc=... +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for --with-libc=STRING" >&5 +$as_echo_n "checking for --with-libc=STRING... " >&6; } -for ac_func in acosh asinh atanh copysign erf erfc expm1 finite gamma -do -as_ac_var=`echo "ac_cv_func_$ac_func" | $as_tr_sh` -{ echo "$as_me:$LINENO: checking for $ac_func" >&5 -echo $ECHO_N "checking for $ac_func... $ECHO_C" >&6; } -if { as_var=$as_ac_var; eval "test \"\${$as_var+set}\" = set"; }; then - echo $ECHO_N "(cached) $ECHO_C" >&6 +# Check whether --with-libc was given. +if test "${with_libc+set}" = set; then : + withval=$with_libc; +if test "$withval" = no +then LIBC= + { $as_echo "$as_me:${as_lineno-$LINENO}: result: force LIBC empty" >&5 +$as_echo "force LIBC empty" >&6; } +elif test "$withval" != yes +then LIBC=$withval + { $as_echo "$as_me:${as_lineno-$LINENO}: result: set LIBC=\"$withval\"" >&5 +$as_echo "set LIBC=\"$withval\"" >&6; } +else as_fn_error "proper usage is --with-libc=STRING" "$LINENO" 5 +fi else - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -/* Define $ac_func to an innocuous variant, in case declares $ac_func. - For example, HP-UX 11i declares gettimeofday. */ -#define $ac_func innocuous_$ac_func + { $as_echo "$as_me:${as_lineno-$LINENO}: result: default LIBC=\"$LIBC\"" >&5 +$as_echo "default LIBC=\"$LIBC\"" >&6; } +fi -/* System header to define __stub macros and hopefully few prototypes, - which can conflict with char $ac_func (); below. - Prefer to if __STDC__ is defined, since - exists even on freestanding compilers. */ -#ifdef __STDC__ -# include -#else -# include -#endif +# ************************************************** +# * Check for various properties of floating point * +# ************************************************** -#undef $ac_func +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking whether C doubles are little-endian IEEE 754 binary64" >&5 +$as_echo_n "checking whether C doubles are little-endian IEEE 754 binary64... " >&6; } +if test "${ac_cv_little_endian_double+set}" = set; then : + $as_echo_n "(cached) " >&6 +else -/* Override any GCC internal prototype to avoid an error. - Use char because int might match the return type of a GCC - builtin and then its argument prototype would still apply. */ -#ifdef __cplusplus -extern "C" -#endif -char $ac_func (); -/* The GNU C library defines this for functions which it implements - to always fail with ENOSYS. Some functions are actually named - something starting with __ and the normal name is an alias. */ -#if defined __stub_$ac_func || defined __stub___$ac_func -choke me -#endif +if test "$cross_compiling" = yes; then : + ac_cv_little_endian_double=no +else + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ -int -main () -{ -return $ac_func (); - ; - return 0; +#include +int main() { + double x = 9006104071832581.0; + if (memcmp(&x, "\x05\x04\x03\x02\x01\xff\x3f\x43", 8) == 0) + return 0; + else + return 1; } + _ACEOF -rm -f conftest.$ac_objext conftest$ac_exeext -if { (ac_try="$ac_link" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_link") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest$ac_exeext && - $as_test_x conftest$ac_exeext; then - eval "$as_ac_var=yes" +if ac_fn_c_try_run "$LINENO"; then : + ac_cv_little_endian_double=yes else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - eval "$as_ac_var=no" + ac_cv_little_endian_double=no fi - -rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \ - conftest$ac_exeext conftest.$ac_ext +rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext \ + conftest.$ac_objext conftest.beam conftest.$ac_ext fi -ac_res=`eval echo '${'$as_ac_var'}'` - { echo "$as_me:$LINENO: result: $ac_res" >&5 -echo "${ECHO_T}$ac_res" >&6; } -if test `eval echo '${'$as_ac_var'}'` = yes; then - cat >>confdefs.h <<_ACEOF -#define `echo "HAVE_$ac_func" | $as_tr_cpp` 1 -_ACEOF fi -done - +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_little_endian_double" >&5 +$as_echo "$ac_cv_little_endian_double" >&6; } +if test "$ac_cv_little_endian_double" = yes +then +$as_echo "#define DOUBLE_IS_LITTLE_ENDIAN_IEEE754 1" >>confdefs.h +fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking whether C doubles are big-endian IEEE 754 binary64" >&5 +$as_echo_n "checking whether C doubles are big-endian IEEE 754 binary64... " >&6; } +if test "${ac_cv_big_endian_double+set}" = set; then : + $as_echo_n "(cached) " >&6 +else -for ac_func in hypot lgamma log1p round tgamma -do -as_ac_var=`echo "ac_cv_func_$ac_func" | $as_tr_sh` -{ echo "$as_me:$LINENO: checking for $ac_func" >&5 -echo $ECHO_N "checking for $ac_func... $ECHO_C" >&6; } -if { as_var=$as_ac_var; eval "test \"\${$as_var+set}\" = set"; }; then - echo $ECHO_N "(cached) $ECHO_C" >&6 +if test "$cross_compiling" = yes; then : + ac_cv_big_endian_double=no else - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF + cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ -/* Define $ac_func to an innocuous variant, in case declares $ac_func. - For example, HP-UX 11i declares gettimeofday. */ -#define $ac_func innocuous_$ac_func - -/* System header to define __stub macros and hopefully few prototypes, - which can conflict with char $ac_func (); below. - Prefer to if __STDC__ is defined, since - exists even on freestanding compilers. */ - -#ifdef __STDC__ -# include -#else -# include -#endif - -#undef $ac_func - -/* Override any GCC internal prototype to avoid an error. - Use char because int might match the return type of a GCC - builtin and then its argument prototype would still apply. */ -#ifdef __cplusplus -extern "C" -#endif -char $ac_func (); -/* The GNU C library defines this for functions which it implements - to always fail with ENOSYS. Some functions are actually named - something starting with __ and the normal name is an alias. */ -#if defined __stub_$ac_func || defined __stub___$ac_func -choke me -#endif -int -main () -{ -return $ac_func (); - ; - return 0; +#include +int main() { + double x = 9006104071832581.0; + if (memcmp(&x, "\x43\x3f\xff\x01\x02\x03\x04\x05", 8) == 0) + return 0; + else + return 1; } + _ACEOF -rm -f conftest.$ac_objext conftest$ac_exeext -if { (ac_try="$ac_link" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_link") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest$ac_exeext && - $as_test_x conftest$ac_exeext; then - eval "$as_ac_var=yes" +if ac_fn_c_try_run "$LINENO"; then : + ac_cv_big_endian_double=yes else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - eval "$as_ac_var=no" + ac_cv_big_endian_double=no +fi +rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext \ + conftest.$ac_objext conftest.beam conftest.$ac_ext fi -rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \ - conftest$ac_exeext conftest.$ac_ext fi -ac_res=`eval echo '${'$as_ac_var'}'` - { echo "$as_me:$LINENO: result: $ac_res" >&5 -echo "${ECHO_T}$ac_res" >&6; } -if test `eval echo '${'$as_ac_var'}'` = yes; then - cat >>confdefs.h <<_ACEOF -#define `echo "HAVE_$ac_func" | $as_tr_cpp` 1 -_ACEOF + +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_big_endian_double" >&5 +$as_echo "$ac_cv_big_endian_double" >&6; } +if test "$ac_cv_big_endian_double" = yes +then + +$as_echo "#define DOUBLE_IS_BIG_ENDIAN_IEEE754 1" >>confdefs.h fi -done -{ echo "$as_me:$LINENO: checking whether isinf is declared" >&5 -echo $ECHO_N "checking whether isinf is declared... $ECHO_C" >&6; } -if test "${ac_cv_have_decl_isinf+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 +# Some ARM platforms use a mixed-endian representation for doubles. +# While Python doesn't currently have full support for these platforms +# (see e.g., issue 1762561), we can at least make sure that float <-> string +# conversions work. +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking whether C doubles are ARM mixed-endian IEEE 754 binary64" >&5 +$as_echo_n "checking whether C doubles are ARM mixed-endian IEEE 754 binary64... " >&6; } +if test "${ac_cv_mixed_endian_double+set}" = set; then : + $as_echo_n "(cached) " >&6 else - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -#include -int -main () -{ -#ifndef isinf - (void) isinf; -#endif +if test "$cross_compiling" = yes; then : + ac_cv_mixed_endian_double=no +else + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ - ; - return 0; +#include +int main() { + double x = 9006104071832581.0; + if (memcmp(&x, "\x01\xff\x3f\x43\x05\x04\x03\x02", 8) == 0) + return 0; + else + return 1; } + _ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - ac_cv_have_decl_isinf=yes +if ac_fn_c_try_run "$LINENO"; then : + ac_cv_mixed_endian_double=yes else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - ac_cv_have_decl_isinf=no + ac_cv_mixed_endian_double=no +fi +rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext \ + conftest.$ac_objext conftest.beam conftest.$ac_ext fi -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext fi -{ echo "$as_me:$LINENO: result: $ac_cv_have_decl_isinf" >&5 -echo "${ECHO_T}$ac_cv_have_decl_isinf" >&6; } -if test $ac_cv_have_decl_isinf = yes; then -cat >>confdefs.h <<_ACEOF -#define HAVE_DECL_ISINF 1 -_ACEOF +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_mixed_endian_double" >&5 +$as_echo "$ac_cv_mixed_endian_double" >&6; } +if test "$ac_cv_mixed_endian_double" = yes +then +$as_echo "#define DOUBLE_IS_ARM_MIXED_ENDIAN_IEEE754 1" >>confdefs.h -else - cat >>confdefs.h <<_ACEOF -#define HAVE_DECL_ISINF 0 -_ACEOF +fi +# The short float repr introduced in Python 3.1 requires the +# correctly-rounded string <-> double conversion functions from +# Python/dtoa.c, which in turn require that the FPU uses 53-bit +# rounding; this is a problem on x86, where the x87 FPU has a default +# rounding precision of 64 bits. For gcc/x86, we can fix this by +# using inline assembler to get and set the x87 FPU control word. -fi -{ echo "$as_me:$LINENO: checking whether isnan is declared" >&5 -echo $ECHO_N "checking whether isnan is declared... $ECHO_C" >&6; } -if test "${ac_cv_have_decl_isnan+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 -else - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF +# This inline assembler syntax may also work for suncc and icc, +# so we try it on all platforms. + +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking whether we can use gcc inline assembler to get and set x87 control word" >&5 +$as_echo_n "checking whether we can use gcc inline assembler to get and set x87 control word... " >&6; } +cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ -#include int main () { -#ifndef isnan - (void) isnan; -#endif + + unsigned short cw; + __asm__ __volatile__ ("fnstcw %0" : "=m" (cw)); + __asm__ __volatile__ ("fldcw %0" : : "m" (cw)); ; return 0; } _ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - ac_cv_have_decl_isnan=yes +if ac_fn_c_try_compile "$LINENO"; then : + have_gcc_asm_for_x87=yes else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - ac_cv_have_decl_isnan=no + have_gcc_asm_for_x87=no fi - rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext -fi -{ echo "$as_me:$LINENO: result: $ac_cv_have_decl_isnan" >&5 -echo "${ECHO_T}$ac_cv_have_decl_isnan" >&6; } -if test $ac_cv_have_decl_isnan = yes; then +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $have_gcc_asm_for_x87" >&5 +$as_echo "$have_gcc_asm_for_x87" >&6; } +if test "$have_gcc_asm_for_x87" = yes +then -cat >>confdefs.h <<_ACEOF -#define HAVE_DECL_ISNAN 1 -_ACEOF +$as_echo "#define HAVE_GCC_ASM_FOR_X87 1" >>confdefs.h +fi +# Detect whether system arithmetic is subject to x87-style double +# rounding issues. The result of this test has little meaning on non +# IEEE 754 platforms. On IEEE 754, test should return 1 if rounding +# mode is round-to-nearest and double rounding issues are present, and +# 0 otherwise. See http://bugs.python.org/issue2937 for more info. +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for x87-style double rounding" >&5 +$as_echo_n "checking for x87-style double rounding... " >&6; } +# $BASECFLAGS may affect the result +ac_save_cc="$CC" +CC="$CC $BASECFLAGS" +if test "$cross_compiling" = yes; then : + ac_cv_x87_double_rounding=no else - cat >>confdefs.h <<_ACEOF -#define HAVE_DECL_ISNAN 0 + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + +#include +#include +int main() { + volatile double x, y, z; + /* 1./(1-2**-53) -> 1+2**-52 (correct), 1.0 (double rounding) */ + x = 0.99999999999999989; /* 1-2**-53 */ + y = 1./x; + if (y != 1.) + exit(0); + /* 1e16+2.99999 -> 1e16+2. (correct), 1e16+4. (double rounding) */ + x = 1e16; + y = 2.99999; + z = x + y; + if (z != 1e16+4.) + exit(0); + /* both tests show evidence of double rounding */ + exit(1); +} + _ACEOF +if ac_fn_c_try_run "$LINENO"; then : + ac_cv_x87_double_rounding=no +else + ac_cv_x87_double_rounding=yes +fi +rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext \ + conftest.$ac_objext conftest.beam conftest.$ac_ext +fi + +CC="$ac_save_cc" +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_x87_double_rounding" >&5 +$as_echo "$ac_cv_x87_double_rounding" >&6; } +if test "$ac_cv_x87_double_rounding" = yes +then +$as_echo "#define X87_DOUBLE_ROUNDING 1" >>confdefs.h fi -{ echo "$as_me:$LINENO: checking whether isfinite is declared" >&5 -echo $ECHO_N "checking whether isfinite is declared... $ECHO_C" >&6; } -if test "${ac_cv_have_decl_isfinite+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 + +# ************************************ +# * Check for mathematical functions * +# ************************************ + +LIBS_SAVE=$LIBS +LIBS="$LIBS $LIBM" + +# On FreeBSD 6.2, it appears that tanh(-0.) returns 0. instead of +# -0. on some architectures. +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking whether tanh preserves the sign of zero" >&5 +$as_echo_n "checking whether tanh preserves the sign of zero... " >&6; } +if test "${ac_cv_tanh_preserves_zero_sign+set}" = set; then : + $as_echo_n "(cached) " >&6 else - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -#include -int -main () -{ -#ifndef isfinite - (void) isfinite; -#endif +if test "$cross_compiling" = yes; then : + ac_cv_tanh_preserves_zero_sign=no +else + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ - ; - return 0; +#include +#include +int main() { + /* return 0 if either negative zeros don't exist + on this platform or if negative zeros exist + and tanh(-0.) == -0. */ + if (atan2(0., -1.) == atan2(-0., -1.) || + atan2(tanh(-0.), -1.) == atan2(-0., -1.)) exit(0); + else exit(1); } + _ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - ac_cv_have_decl_isfinite=yes +if ac_fn_c_try_run "$LINENO"; then : + ac_cv_tanh_preserves_zero_sign=yes else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 + ac_cv_tanh_preserves_zero_sign=no +fi +rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext \ + conftest.$ac_objext conftest.beam conftest.$ac_ext +fi + +fi + +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_tanh_preserves_zero_sign" >&5 +$as_echo "$ac_cv_tanh_preserves_zero_sign" >&6; } +if test "$ac_cv_tanh_preserves_zero_sign" = yes +then + +$as_echo "#define TANH_PRESERVES_ZERO_SIGN 1" >>confdefs.h - ac_cv_have_decl_isfinite=no fi -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext +for ac_func in acosh asinh atanh copysign erf erfc expm1 finite gamma +do : + as_ac_var=`$as_echo "ac_cv_func_$ac_func" | $as_tr_sh` +ac_fn_c_check_func "$LINENO" "$ac_func" "$as_ac_var" +eval as_val=\$$as_ac_var + if test "x$as_val" = x""yes; then : + cat >>confdefs.h <<_ACEOF +#define `$as_echo "HAVE_$ac_func" | $as_tr_cpp` 1 +_ACEOF + fi -{ echo "$as_me:$LINENO: result: $ac_cv_have_decl_isfinite" >&5 -echo "${ECHO_T}$ac_cv_have_decl_isfinite" >&6; } -if test $ac_cv_have_decl_isfinite = yes; then +done -cat >>confdefs.h <<_ACEOF -#define HAVE_DECL_ISFINITE 1 +for ac_func in hypot lgamma log1p round tgamma +do : + as_ac_var=`$as_echo "ac_cv_func_$ac_func" | $as_tr_sh` +ac_fn_c_check_func "$LINENO" "$ac_func" "$as_ac_var" +eval as_val=\$$as_ac_var + if test "x$as_val" = x""yes; then : + cat >>confdefs.h <<_ACEOF +#define `$as_echo "HAVE_$ac_func" | $as_tr_cpp` 1 _ACEOF +fi +done +ac_fn_c_check_decl "$LINENO" "isinf" "ac_cv_have_decl_isinf" "#include +" +if test "x$ac_cv_have_decl_isinf" = x""yes; then : + ac_have_decl=1 else - cat >>confdefs.h <<_ACEOF -#define HAVE_DECL_ISFINITE 0 -_ACEOF + ac_have_decl=0 +fi +cat >>confdefs.h <<_ACEOF +#define HAVE_DECL_ISINF $ac_have_decl +_ACEOF +ac_fn_c_check_decl "$LINENO" "isnan" "ac_cv_have_decl_isnan" "#include +" +if test "x$ac_cv_have_decl_isnan" = x""yes; then : + ac_have_decl=1 +else + ac_have_decl=0 +fi +cat >>confdefs.h <<_ACEOF +#define HAVE_DECL_ISNAN $ac_have_decl +_ACEOF +ac_fn_c_check_decl "$LINENO" "isfinite" "ac_cv_have_decl_isfinite" "#include +" +if test "x$ac_cv_have_decl_isfinite" = x""yes; then : + ac_have_decl=1 +else + ac_have_decl=0 fi +cat >>confdefs.h <<_ACEOF +#define HAVE_DECL_ISFINITE $ac_have_decl +_ACEOF LIBS=$LIBS_SAVE @@ -24719,19 +12071,15 @@ # the kernel module that provides POSIX semaphores # isn't loaded by default, so an attempt to call # sem_open results in a 'Signal 12' error. -{ echo "$as_me:$LINENO: checking whether POSIX semaphores are enabled" >&5 -echo $ECHO_N "checking whether POSIX semaphores are enabled... $ECHO_C" >&6; } -if test "${ac_cv_posix_semaphores_enabled+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking whether POSIX semaphores are enabled" >&5 +$as_echo_n "checking whether POSIX semaphores are enabled... " >&6; } +if test "${ac_cv_posix_semaphores_enabled+set}" = set; then : + $as_echo_n "(cached) " >&6 else - if test "$cross_compiling" = yes; then + if test "$cross_compiling" = yes; then : ac_cv_posix_semaphores_enabled=yes else - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF + cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ #include @@ -24752,67 +12100,37 @@ } _ACEOF -rm -f conftest$ac_exeext -if { (ac_try="$ac_link" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_link") 2>&5 - ac_status=$? - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { ac_try='./conftest$ac_exeext' - { (case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_try") 2>&5 - ac_status=$? - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); }; }; then +if ac_fn_c_try_run "$LINENO"; then : ac_cv_posix_semaphores_enabled=yes else - echo "$as_me: program exited with status $ac_status" >&5 -echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - -( exit $ac_status ) -ac_cv_posix_semaphores_enabled=no + ac_cv_posix_semaphores_enabled=no fi -rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext conftest.$ac_objext conftest.$ac_ext +rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext \ + conftest.$ac_objext conftest.beam conftest.$ac_ext fi - fi -{ echo "$as_me:$LINENO: result: $ac_cv_posix_semaphores_enabled" >&5 -echo "${ECHO_T}$ac_cv_posix_semaphores_enabled" >&6; } +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_posix_semaphores_enabled" >&5 +$as_echo "$ac_cv_posix_semaphores_enabled" >&6; } if test $ac_cv_posix_semaphores_enabled = no then -cat >>confdefs.h <<\_ACEOF -#define POSIX_SEMAPHORES_NOT_ENABLED 1 -_ACEOF +$as_echo "#define POSIX_SEMAPHORES_NOT_ENABLED 1" >>confdefs.h fi # Multiprocessing check for broken sem_getvalue -{ echo "$as_me:$LINENO: checking for broken sem_getvalue" >&5 -echo $ECHO_N "checking for broken sem_getvalue... $ECHO_C" >&6; } -if test "${ac_cv_broken_sem_getvalue+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for broken sem_getvalue" >&5 +$as_echo_n "checking for broken sem_getvalue... " >&6; } +if test "${ac_cv_broken_sem_getvalue+set}" = set; then : + $as_echo_n "(cached) " >&6 else - if test "$cross_compiling" = yes; then + if test "$cross_compiling" = yes; then : ac_cv_broken_sem_getvalue=yes else - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF + cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ #include @@ -24837,638 +12155,102 @@ } _ACEOF -rm -f conftest$ac_exeext -if { (ac_try="$ac_link" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_link") 2>&5 - ac_status=$? - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { ac_try='./conftest$ac_exeext' - { (case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_try") 2>&5 - ac_status=$? - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); }; }; then +if ac_fn_c_try_run "$LINENO"; then : ac_cv_broken_sem_getvalue=no else - echo "$as_me: program exited with status $ac_status" >&5 -echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - -( exit $ac_status ) -ac_cv_broken_sem_getvalue=yes + ac_cv_broken_sem_getvalue=yes fi -rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext conftest.$ac_objext conftest.$ac_ext +rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext \ + conftest.$ac_objext conftest.beam conftest.$ac_ext fi - fi -{ echo "$as_me:$LINENO: result: $ac_cv_broken_sem_getvalue" >&5 -echo "${ECHO_T}$ac_cv_broken_sem_getvalue" >&6; } +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_broken_sem_getvalue" >&5 +$as_echo "$ac_cv_broken_sem_getvalue" >&6; } if test $ac_cv_broken_sem_getvalue = yes then -cat >>confdefs.h <<\_ACEOF -#define HAVE_BROKEN_SEM_GETVALUE 1 -_ACEOF +$as_echo "#define HAVE_BROKEN_SEM_GETVALUE 1" >>confdefs.h fi # determine what size digit to use for Python's longs -{ echo "$as_me:$LINENO: checking digit size for Python's longs" >&5 -echo $ECHO_N "checking digit size for Python's longs... $ECHO_C" >&6; } +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking digit size for Python's longs" >&5 +$as_echo_n "checking digit size for Python's longs... " >&6; } # Check whether --enable-big-digits was given. -if test "${enable_big_digits+set}" = set; then +if test "${enable_big_digits+set}" = set; then : enableval=$enable_big_digits; case $enable_big_digits in yes) enable_big_digits=30 ;; no) enable_big_digits=15 ;; -15|30) - ;; -*) - { { echo "$as_me:$LINENO: error: bad value $enable_big_digits for --enable-big-digits; value should be 15 or 30" >&5 -echo "$as_me: error: bad value $enable_big_digits for --enable-big-digits; value should be 15 or 30" >&2;} - { (exit 1); exit 1; }; } ;; -esac -{ echo "$as_me:$LINENO: result: $enable_big_digits" >&5 -echo "${ECHO_T}$enable_big_digits" >&6; } - -cat >>confdefs.h <<_ACEOF -#define PYLONG_BITS_IN_DIGIT $enable_big_digits -_ACEOF - - -else - { echo "$as_me:$LINENO: result: no value specified" >&5 -echo "${ECHO_T}no value specified" >&6; } -fi - - -# check for wchar.h -if test "${ac_cv_header_wchar_h+set}" = set; then - { echo "$as_me:$LINENO: checking for wchar.h" >&5 -echo $ECHO_N "checking for wchar.h... $ECHO_C" >&6; } -if test "${ac_cv_header_wchar_h+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 -fi -{ echo "$as_me:$LINENO: result: $ac_cv_header_wchar_h" >&5 -echo "${ECHO_T}$ac_cv_header_wchar_h" >&6; } -else - # Is the header compilable? -{ echo "$as_me:$LINENO: checking wchar.h usability" >&5 -echo $ECHO_N "checking wchar.h usability... $ECHO_C" >&6; } -cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -$ac_includes_default -#include -_ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - ac_header_compiler=yes -else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - ac_header_compiler=no -fi - -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext -{ echo "$as_me:$LINENO: result: $ac_header_compiler" >&5 -echo "${ECHO_T}$ac_header_compiler" >&6; } - -# Is the header present? -{ echo "$as_me:$LINENO: checking wchar.h presence" >&5 -echo $ECHO_N "checking wchar.h presence... $ECHO_C" >&6; } -cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -#include -_ACEOF -if { (ac_try="$ac_cpp conftest.$ac_ext" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_cpp conftest.$ac_ext") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } >/dev/null && { - test -z "$ac_c_preproc_warn_flag$ac_c_werror_flag" || - test ! -s conftest.err - }; then - ac_header_preproc=yes -else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - ac_header_preproc=no -fi - -rm -f conftest.err conftest.$ac_ext -{ echo "$as_me:$LINENO: result: $ac_header_preproc" >&5 -echo "${ECHO_T}$ac_header_preproc" >&6; } - -# So? What about this header? -case $ac_header_compiler:$ac_header_preproc:$ac_c_preproc_warn_flag in - yes:no: ) - { echo "$as_me:$LINENO: WARNING: wchar.h: accepted by the compiler, rejected by the preprocessor!" >&5 -echo "$as_me: WARNING: wchar.h: accepted by the compiler, rejected by the preprocessor!" >&2;} - { echo "$as_me:$LINENO: WARNING: wchar.h: proceeding with the compiler's result" >&5 -echo "$as_me: WARNING: wchar.h: proceeding with the compiler's result" >&2;} - ac_header_preproc=yes - ;; - no:yes:* ) - { echo "$as_me:$LINENO: WARNING: wchar.h: present but cannot be compiled" >&5 -echo "$as_me: WARNING: wchar.h: present but cannot be compiled" >&2;} - { echo "$as_me:$LINENO: WARNING: wchar.h: check for missing prerequisite headers?" >&5 -echo "$as_me: WARNING: wchar.h: check for missing prerequisite headers?" >&2;} - { echo "$as_me:$LINENO: WARNING: wchar.h: see the Autoconf documentation" >&5 -echo "$as_me: WARNING: wchar.h: see the Autoconf documentation" >&2;} - { echo "$as_me:$LINENO: WARNING: wchar.h: section \"Present But Cannot Be Compiled\"" >&5 -echo "$as_me: WARNING: wchar.h: section \"Present But Cannot Be Compiled\"" >&2;} - { echo "$as_me:$LINENO: WARNING: wchar.h: proceeding with the preprocessor's result" >&5 -echo "$as_me: WARNING: wchar.h: proceeding with the preprocessor's result" >&2;} - { echo "$as_me:$LINENO: WARNING: wchar.h: in the future, the compiler will take precedence" >&5 -echo "$as_me: WARNING: wchar.h: in the future, the compiler will take precedence" >&2;} - ( cat <<\_ASBOX -## -------------------------------------- ## -## Report this to http://bugs.python.org/ ## -## -------------------------------------- ## -_ASBOX - ) | sed "s/^/$as_me: WARNING: /" >&2 - ;; -esac -{ echo "$as_me:$LINENO: checking for wchar.h" >&5 -echo $ECHO_N "checking for wchar.h... $ECHO_C" >&6; } -if test "${ac_cv_header_wchar_h+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 -else - ac_cv_header_wchar_h=$ac_header_preproc -fi -{ echo "$as_me:$LINENO: result: $ac_cv_header_wchar_h" >&5 -echo "${ECHO_T}$ac_cv_header_wchar_h" >&6; } - -fi -if test $ac_cv_header_wchar_h = yes; then - - -cat >>confdefs.h <<\_ACEOF -#define HAVE_WCHAR_H 1 -_ACEOF - - wchar_h="yes" - -else - wchar_h="no" - -fi - - - -# determine wchar_t size -if test "$wchar_h" = yes -then - { echo "$as_me:$LINENO: checking for wchar_t" >&5 -echo $ECHO_N "checking for wchar_t... $ECHO_C" >&6; } -if test "${ac_cv_type_wchar_t+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 -else - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -#include - -typedef wchar_t ac__type_new_; -int -main () -{ -if ((ac__type_new_ *) 0) - return 0; -if (sizeof (ac__type_new_)) - return 0; - ; - return 0; -} -_ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - ac_cv_type_wchar_t=yes -else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - ac_cv_type_wchar_t=no -fi - -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext -fi -{ echo "$as_me:$LINENO: result: $ac_cv_type_wchar_t" >&5 -echo "${ECHO_T}$ac_cv_type_wchar_t" >&6; } - -# The cast to long int works around a bug in the HP C Compiler -# version HP92453-01 B.11.11.23709.GP, which incorrectly rejects -# declarations like `int a3[[(sizeof (unsigned char)) >= 0]];'. -# This bug is HP SR number 8606223364. -{ echo "$as_me:$LINENO: checking size of wchar_t" >&5 -echo $ECHO_N "checking size of wchar_t... $ECHO_C" >&6; } -if test "${ac_cv_sizeof_wchar_t+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 -else - if test "$cross_compiling" = yes; then - # Depending upon the size, compute the lo and hi bounds. -cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -#include - - typedef wchar_t ac__type_sizeof_; -int -main () -{ -static int test_array [1 - 2 * !(((long int) (sizeof (ac__type_sizeof_))) >= 0)]; -test_array [0] = 0 - - ; - return 0; -} -_ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - ac_lo=0 ac_mid=0 - while :; do - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -#include - - typedef wchar_t ac__type_sizeof_; -int -main () -{ -static int test_array [1 - 2 * !(((long int) (sizeof (ac__type_sizeof_))) <= $ac_mid)]; -test_array [0] = 0 - - ; - return 0; -} -_ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - ac_hi=$ac_mid; break -else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - ac_lo=`expr $ac_mid + 1` - if test $ac_lo -le $ac_mid; then - ac_lo= ac_hi= - break - fi - ac_mid=`expr 2 '*' $ac_mid + 1` -fi - -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext - done -else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -#include - - typedef wchar_t ac__type_sizeof_; -int -main () -{ -static int test_array [1 - 2 * !(((long int) (sizeof (ac__type_sizeof_))) < 0)]; -test_array [0] = 0 - - ; - return 0; -} -_ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - ac_hi=-1 ac_mid=-1 - while :; do - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ +15|30) + ;; +*) + as_fn_error "bad value $enable_big_digits for --enable-big-digits; value should be 15 or 30" "$LINENO" 5 ;; +esac +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $enable_big_digits" >&5 +$as_echo "$enable_big_digits" >&6; } + +cat >>confdefs.h <<_ACEOF +#define PYLONG_BITS_IN_DIGIT $enable_big_digits _ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -#include - typedef wchar_t ac__type_sizeof_; -int -main () -{ -static int test_array [1 - 2 * !(((long int) (sizeof (ac__type_sizeof_))) >= $ac_mid)]; -test_array [0] = 0 - ; - return 0; -} -_ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - ac_lo=$ac_mid; break else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - ac_hi=`expr '(' $ac_mid ')' - 1` - if test $ac_mid -le $ac_hi; then - ac_lo= ac_hi= - break - fi - ac_mid=`expr 2 '*' $ac_mid` + { $as_echo "$as_me:${as_lineno-$LINENO}: result: no value specified" >&5 +$as_echo "no value specified" >&6; } fi -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext - done -else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - ac_lo= ac_hi= -fi +# check for wchar.h +ac_fn_c_check_header_mongrel "$LINENO" "wchar.h" "ac_cv_header_wchar_h" "$ac_includes_default" +if test "x$ac_cv_header_wchar_h" = x""yes; then : -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext -fi -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext -# Binary search between lo and hi bounds. -while test "x$ac_lo" != "x$ac_hi"; do - ac_mid=`expr '(' $ac_hi - $ac_lo ')' / 2 + $ac_lo` - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -#include +$as_echo "#define HAVE_WCHAR_H 1" >>confdefs.h - typedef wchar_t ac__type_sizeof_; -int -main () -{ -static int test_array [1 - 2 * !(((long int) (sizeof (ac__type_sizeof_))) <= $ac_mid)]; -test_array [0] = 0 + wchar_h="yes" - ; - return 0; -} -_ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - ac_hi=$ac_mid else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 + wchar_h="no" - ac_lo=`expr '(' $ac_mid ')' + 1` fi -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext -done -case $ac_lo in -?*) ac_cv_sizeof_wchar_t=$ac_lo;; -'') if test "$ac_cv_type_wchar_t" = yes; then - { { echo "$as_me:$LINENO: error: cannot compute sizeof (wchar_t) -See \`config.log' for more details." >&5 -echo "$as_me: error: cannot compute sizeof (wchar_t) -See \`config.log' for more details." >&2;} - { (exit 77); exit 77; }; } - else - ac_cv_sizeof_wchar_t=0 - fi ;; -esac -else - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -#include - typedef wchar_t ac__type_sizeof_; -static long int longval () { return (long int) (sizeof (ac__type_sizeof_)); } -static unsigned long int ulongval () { return (long int) (sizeof (ac__type_sizeof_)); } -#include -#include -int -main () -{ - FILE *f = fopen ("conftest.val", "w"); - if (! f) - return 1; - if (((long int) (sizeof (ac__type_sizeof_))) < 0) - { - long int i = longval (); - if (i != ((long int) (sizeof (ac__type_sizeof_)))) - return 1; - fprintf (f, "%ld\n", i); - } - else - { - unsigned long int i = ulongval (); - if (i != ((long int) (sizeof (ac__type_sizeof_)))) - return 1; - fprintf (f, "%lu\n", i); - } - return ferror (f) || fclose (f) != 0; +# determine wchar_t size +if test "$wchar_h" = yes +then + # The cast to long int works around a bug in the HP C Compiler +# version HP92453-01 B.11.11.23709.GP, which incorrectly rejects +# declarations like `int a3[[(sizeof (unsigned char)) >= 0]];'. +# This bug is HP SR number 8606223364. +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking size of wchar_t" >&5 +$as_echo_n "checking size of wchar_t... " >&6; } +if test "${ac_cv_sizeof_wchar_t+set}" = set; then : + $as_echo_n "(cached) " >&6 +else + if ac_fn_c_compute_int "$LINENO" "(long int) (sizeof (wchar_t))" "ac_cv_sizeof_wchar_t" "#include +"; then : - ; - return 0; -} -_ACEOF -rm -f conftest$ac_exeext -if { (ac_try="$ac_link" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_link") 2>&5 - ac_status=$? - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { ac_try='./conftest$ac_exeext' - { (case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_try") 2>&5 - ac_status=$? - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); }; }; then - ac_cv_sizeof_wchar_t=`cat conftest.val` else - echo "$as_me: program exited with status $ac_status" >&5 -echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - -( exit $ac_status ) -if test "$ac_cv_type_wchar_t" = yes; then - { { echo "$as_me:$LINENO: error: cannot compute sizeof (wchar_t) -See \`config.log' for more details." >&5 -echo "$as_me: error: cannot compute sizeof (wchar_t) -See \`config.log' for more details." >&2;} - { (exit 77); exit 77; }; } + if test "$ac_cv_type_wchar_t" = yes; then + { { $as_echo "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5 +$as_echo "$as_me: error: in \`$ac_pwd':" >&2;} +{ as_fn_set_status 77 +as_fn_error "cannot compute sizeof (wchar_t) +See \`config.log' for more details." "$LINENO" 5; }; } else ac_cv_sizeof_wchar_t=0 fi fi -rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext conftest.$ac_objext conftest.$ac_ext -fi -rm -f conftest.val + fi -{ echo "$as_me:$LINENO: result: $ac_cv_sizeof_wchar_t" >&5 -echo "${ECHO_T}$ac_cv_sizeof_wchar_t" >&6; } +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_sizeof_wchar_t" >&5 +$as_echo "$ac_cv_sizeof_wchar_t" >&6; } @@ -25479,14 +12261,10 @@ fi -{ echo "$as_me:$LINENO: checking for UCS-4 tcl" >&5 -echo $ECHO_N "checking for UCS-4 tcl... $ECHO_C" >&6; } +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for UCS-4 tcl" >&5 +$as_echo_n "checking for UCS-4 tcl... " >&6; } have_ucs4_tcl=no -cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF +cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ #include @@ -25501,60 +12279,32 @@ return 0; } _ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then +if ac_fn_c_try_compile "$LINENO"; then : -cat >>confdefs.h <<\_ACEOF -#define HAVE_UCS4_TCL 1 -_ACEOF +$as_echo "#define HAVE_UCS4_TCL 1" >>confdefs.h have_ucs4_tcl=yes -else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - fi - rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext -{ echo "$as_me:$LINENO: result: $have_ucs4_tcl" >&5 -echo "${ECHO_T}$have_ucs4_tcl" >&6; } +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $have_ucs4_tcl" >&5 +$as_echo "$have_ucs4_tcl" >&6; } # check whether wchar_t is signed or not if test "$wchar_h" = yes then # check whether wchar_t is signed or not - { echo "$as_me:$LINENO: checking whether wchar_t is signed" >&5 -echo $ECHO_N "checking whether wchar_t is signed... $ECHO_C" >&6; } - if test "${ac_cv_wchar_t_signed+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 + { $as_echo "$as_me:${as_lineno-$LINENO}: checking whether wchar_t is signed" >&5 +$as_echo_n "checking whether wchar_t is signed... " >&6; } + if test "${ac_cv_wchar_t_signed+set}" = set; then : + $as_echo_n "(cached) " >&6 else - if test "$cross_compiling" = yes; then + if test "$cross_compiling" = yes; then : ac_cv_wchar_t_signed=yes else - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF + cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ #include @@ -25565,49 +12315,25 @@ } _ACEOF -rm -f conftest$ac_exeext -if { (ac_try="$ac_link" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_link") 2>&5 - ac_status=$? - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { ac_try='./conftest$ac_exeext' - { (case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_try") 2>&5 - ac_status=$? - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); }; }; then +if ac_fn_c_try_run "$LINENO"; then : ac_cv_wchar_t_signed=yes else - echo "$as_me: program exited with status $ac_status" >&5 -echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - -( exit $ac_status ) -ac_cv_wchar_t_signed=no + ac_cv_wchar_t_signed=no fi -rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext conftest.$ac_objext conftest.$ac_ext +rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext \ + conftest.$ac_objext conftest.beam conftest.$ac_ext fi - fi - { echo "$as_me:$LINENO: result: $ac_cv_wchar_t_signed" >&5 -echo "${ECHO_T}$ac_cv_wchar_t_signed" >&6; } + { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_wchar_t_signed" >&5 +$as_echo "$ac_cv_wchar_t_signed" >&6; } fi -{ echo "$as_me:$LINENO: checking what type to use for unicode" >&5 -echo $ECHO_N "checking what type to use for unicode... $ECHO_C" >&6; } +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking what type to use for unicode" >&5 +$as_echo_n "checking what type to use for unicode... " >&6; } # Check whether --enable-unicode was given. -if test "${enable_unicode+set}" = set; then +if test "${enable_unicode+set}" = set; then : enableval=$enable_unicode; else enable_unicode=yes @@ -25626,40 +12352,30 @@ fi - case "$enable_unicode" in ucs2) unicode_size="2" - cat >>confdefs.h <<\_ACEOF -#define Py_UNICODE_SIZE 2 -_ACEOF + $as_echo "#define Py_UNICODE_SIZE 2" >>confdefs.h ;; ucs4) unicode_size="4" - cat >>confdefs.h <<\_ACEOF -#define Py_UNICODE_SIZE 4 -_ACEOF + $as_echo "#define Py_UNICODE_SIZE 4" >>confdefs.h ;; -*) { { echo "$as_me:$LINENO: error: invalid value for --enable-unicode. Use either ucs2 or ucs4 (lowercase)." >&5 -echo "$as_me: error: invalid value for --enable-unicode. Use either ucs2 or ucs4 (lowercase)." >&2;} - { (exit 1); exit 1; }; } ;; +*) as_fn_error "invalid value for --enable-unicode. Use either ucs2 or ucs4 (lowercase)." "$LINENO" 5 ;; esac - if test "$enable_unicode" = "no" then UNICODE_OBJS="" - { echo "$as_me:$LINENO: result: not used" >&5 -echo "${ECHO_T}not used" >&6; } + { $as_echo "$as_me:${as_lineno-$LINENO}: result: not used" >&5 +$as_echo "not used" >&6; } else UNICODE_OBJS="Objects/unicodeobject.o Objects/unicodectype.o" -cat >>confdefs.h <<\_ACEOF -#define Py_USING_UNICODE 1 -_ACEOF +$as_echo "#define Py_USING_UNICODE 1" >>confdefs.h # wchar_t is only usable if it maps to an unsigned type @@ -25668,289 +12384,265 @@ then PY_UNICODE_TYPE="wchar_t" -cat >>confdefs.h <<\_ACEOF -#define HAVE_USABLE_WCHAR_T 1 -_ACEOF +$as_echo "#define HAVE_USABLE_WCHAR_T 1" >>confdefs.h - cat >>confdefs.h <<\_ACEOF -#define PY_UNICODE_TYPE wchar_t -_ACEOF + $as_echo "#define PY_UNICODE_TYPE wchar_t" >>confdefs.h elif test "$ac_cv_sizeof_short" = "$unicode_size" then PY_UNICODE_TYPE="unsigned short" - cat >>confdefs.h <<\_ACEOF -#define PY_UNICODE_TYPE unsigned short -_ACEOF + $as_echo "#define PY_UNICODE_TYPE unsigned short" >>confdefs.h elif test "$ac_cv_sizeof_long" = "$unicode_size" then PY_UNICODE_TYPE="unsigned long" - cat >>confdefs.h <<\_ACEOF -#define PY_UNICODE_TYPE unsigned long -_ACEOF + $as_echo "#define PY_UNICODE_TYPE unsigned long" >>confdefs.h else PY_UNICODE_TYPE="no type found" fi - { echo "$as_me:$LINENO: result: $PY_UNICODE_TYPE" >&5 -echo "${ECHO_T}$PY_UNICODE_TYPE" >&6; } + { $as_echo "$as_me:${as_lineno-$LINENO}: result: $PY_UNICODE_TYPE" >&5 +$as_echo "$PY_UNICODE_TYPE" >&6; } fi # check for endianness -{ echo "$as_me:$LINENO: checking whether byte ordering is bigendian" >&5 -echo $ECHO_N "checking whether byte ordering is bigendian... $ECHO_C" >&6; } -if test "${ac_cv_c_bigendian+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 -else - # See if sys/param.h defines the BYTE_ORDER macro. -cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ + { $as_echo "$as_me:${as_lineno-$LINENO}: checking whether byte ordering is bigendian" >&5 +$as_echo_n "checking whether byte ordering is bigendian... " >&6; } +if test "${ac_cv_c_bigendian+set}" = set; then : + $as_echo_n "(cached) " >&6 +else + ac_cv_c_bigendian=unknown + # See if we're dealing with a universal compiler. + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ +#ifndef __APPLE_CC__ + not a universal capable compiler + #endif + typedef int dummy; + _ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF +if ac_fn_c_try_compile "$LINENO"; then : + + # Check for potential -arch flags. It is not universal unless + # there are at least two -arch flags with different values. + ac_arch= + ac_prev= + for ac_word in $CC $CFLAGS $CPPFLAGS $LDFLAGS; do + if test -n "$ac_prev"; then + case $ac_word in + i?86 | x86_64 | ppc | ppc64) + if test -z "$ac_arch" || test "$ac_arch" = "$ac_word"; then + ac_arch=$ac_word + else + ac_cv_c_bigendian=universal + break + fi + ;; + esac + ac_prev= + elif test "x$ac_word" = "x-arch"; then + ac_prev=arch + fi + done +fi +rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext + if test $ac_cv_c_bigendian = unknown; then + # See if sys/param.h defines the BYTE_ORDER macro. + cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ #include -#include + #include int main () { -#if ! (defined BYTE_ORDER && defined BIG_ENDIAN && defined LITTLE_ENDIAN \ - && BYTE_ORDER && BIG_ENDIAN && LITTLE_ENDIAN) - bogus endian macros -#endif +#if ! (defined BYTE_ORDER && defined BIG_ENDIAN \ + && defined LITTLE_ENDIAN && BYTE_ORDER && BIG_ENDIAN \ + && LITTLE_ENDIAN) + bogus endian macros + #endif ; return 0; } _ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then +if ac_fn_c_try_compile "$LINENO"; then : # It does; now see whether it defined to BIG_ENDIAN or not. -cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF + cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ #include -#include + #include int main () { #if BYTE_ORDER != BIG_ENDIAN - not big endian -#endif + not big endian + #endif ; return 0; } _ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then +if ac_fn_c_try_compile "$LINENO"; then : ac_cv_c_bigendian=yes else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - ac_cv_c_bigendian=no + ac_cv_c_bigendian=no fi - rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext -else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 +fi +rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext + fi + if test $ac_cv_c_bigendian = unknown; then + # See if defines _LITTLE_ENDIAN or _BIG_ENDIAN (e.g., Solaris). + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ +#include - # It does not; compile a test program. -if test "$cross_compiling" = yes; then - # try to guess the endianness by grepping values into an object file - ac_cv_c_bigendian=unknown - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ +int +main () +{ +#if ! (defined _LITTLE_ENDIAN || defined _BIG_ENDIAN) + bogus endian macros + #endif + + ; + return 0; +} _ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF +if ac_fn_c_try_compile "$LINENO"; then : + # It does; now see whether it defined to _BIG_ENDIAN or not. + cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ -short int ascii_mm[] = { 0x4249, 0x4765, 0x6E44, 0x6961, 0x6E53, 0x7953, 0 }; -short int ascii_ii[] = { 0x694C, 0x5454, 0x656C, 0x6E45, 0x6944, 0x6E61, 0 }; -void _ascii () { char *s = (char *) ascii_mm; s = (char *) ascii_ii; } -short int ebcdic_ii[] = { 0x89D3, 0xE3E3, 0x8593, 0x95C5, 0x89C4, 0x9581, 0 }; -short int ebcdic_mm[] = { 0xC2C9, 0xC785, 0x95C4, 0x8981, 0x95E2, 0xA8E2, 0 }; -void _ebcdic () { char *s = (char *) ebcdic_mm; s = (char *) ebcdic_ii; } +#include + int main () { - _ascii (); _ebcdic (); +#ifndef _BIG_ENDIAN + not big endian + #endif + ; return 0; } _ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - if grep BIGenDianSyS conftest.$ac_objext >/dev/null ; then +if ac_fn_c_try_compile "$LINENO"; then : ac_cv_c_bigendian=yes +else + ac_cv_c_bigendian=no fi -if grep LiTTleEnDian conftest.$ac_objext >/dev/null ; then - if test "$ac_cv_c_bigendian" = unknown; then - ac_cv_c_bigendian=no - else - # finding both strings is unlikely to happen, but who knows? - ac_cv_c_bigendian=unknown - fi +rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext fi -else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - +rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext + fi + if test $ac_cv_c_bigendian = unknown; then + # Compile a test program. + if test "$cross_compiling" = yes; then : + # Try to guess by grepping values from an object file. + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ +short int ascii_mm[] = + { 0x4249, 0x4765, 0x6E44, 0x6961, 0x6E53, 0x7953, 0 }; + short int ascii_ii[] = + { 0x694C, 0x5454, 0x656C, 0x6E45, 0x6944, 0x6E61, 0 }; + int use_ascii (int i) { + return ascii_mm[i] + ascii_ii[i]; + } + short int ebcdic_ii[] = + { 0x89D3, 0xE3E3, 0x8593, 0x95C5, 0x89C4, 0x9581, 0 }; + short int ebcdic_mm[] = + { 0xC2C9, 0xC785, 0x95C4, 0x8981, 0x95E2, 0xA8E2, 0 }; + int use_ebcdic (int i) { + return ebcdic_mm[i] + ebcdic_ii[i]; + } + extern int foo; +int +main () +{ +return use_ascii (foo) == use_ebcdic (foo); + ; + return 0; +} +_ACEOF +if ac_fn_c_try_compile "$LINENO"; then : + if grep BIGenDianSyS conftest.$ac_objext >/dev/null; then + ac_cv_c_bigendian=yes + fi + if grep LiTTleEnDian conftest.$ac_objext >/dev/null ; then + if test "$ac_cv_c_bigendian" = unknown; then + ac_cv_c_bigendian=no + else + # finding both strings is unlikely to happen, but who knows? + ac_cv_c_bigendian=unknown + fi + fi fi - rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext else - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF + cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ $ac_includes_default int main () { - /* Are we little or big endian? From Harbison&Steele. */ - union - { - long int l; - char c[sizeof (long int)]; - } u; - u.l = 1; - return u.c[sizeof (long int) - 1] == 1; + /* Are we little or big endian? From Harbison&Steele. */ + union + { + long int l; + char c[sizeof (long int)]; + } u; + u.l = 1; + return u.c[sizeof (long int) - 1] == 1; ; return 0; } _ACEOF -rm -f conftest$ac_exeext -if { (ac_try="$ac_link" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_link") 2>&5 - ac_status=$? - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { ac_try='./conftest$ac_exeext' - { (case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_try") 2>&5 - ac_status=$? - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); }; }; then +if ac_fn_c_try_run "$LINENO"; then : ac_cv_c_bigendian=no else - echo "$as_me: program exited with status $ac_status" >&5 -echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - -( exit $ac_status ) -ac_cv_c_bigendian=yes -fi -rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext conftest.$ac_objext conftest.$ac_ext -fi - - + ac_cv_c_bigendian=yes fi - -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext +rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext \ + conftest.$ac_objext conftest.beam conftest.$ac_ext fi -{ echo "$as_me:$LINENO: result: $ac_cv_c_bigendian" >&5 -echo "${ECHO_T}$ac_cv_c_bigendian" >&6; } -case $ac_cv_c_bigendian in - yes) -cat >>confdefs.h <<\_ACEOF -#define WORDS_BIGENDIAN 1 -_ACEOF - ;; - no) - ;; - *) - { { echo "$as_me:$LINENO: error: unknown endianness -presetting ac_cv_c_bigendian=no (or yes) will help" >&5 -echo "$as_me: error: unknown endianness -presetting ac_cv_c_bigendian=no (or yes) will help" >&2;} - { (exit 1); exit 1; }; } ;; -esac + fi +fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_c_bigendian" >&5 +$as_echo "$ac_cv_c_bigendian" >&6; } + case $ac_cv_c_bigendian in #( + yes) + $as_echo "#define WORDS_BIGENDIAN 1" >>confdefs.h +;; #( + no) + ;; #( + universal) + +$as_echo "#define AC_APPLE_UNIVERSAL_BUILD 1" >>confdefs.h + + ;; #( + *) + as_fn_error "unknown endianness + presetting ac_cv_c_bigendian=no (or yes) will help" "$LINENO" 5 ;; + esac # Check whether right shifting a negative integer extends the sign bit # or fills with zeros (like the Cray J90, according to Tim Peters). -{ echo "$as_me:$LINENO: checking whether right shift extends the sign bit" >&5 -echo $ECHO_N "checking whether right shift extends the sign bit... $ECHO_C" >&6; } -if test "${ac_cv_rshift_extends_sign+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking whether right shift extends the sign bit" >&5 +$as_echo_n "checking whether right shift extends the sign bit... " >&6; } +if test "${ac_cv_rshift_extends_sign+set}" = set; then : + $as_echo_n "(cached) " >&6 else -if test "$cross_compiling" = yes; then +if test "$cross_compiling" = yes; then : ac_cv_rshift_extends_sign=yes else - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF + cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ int main() @@ -25959,64 +12651,34 @@ } _ACEOF -rm -f conftest$ac_exeext -if { (ac_try="$ac_link" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_link") 2>&5 - ac_status=$? - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { ac_try='./conftest$ac_exeext' - { (case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_try") 2>&5 - ac_status=$? - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); }; }; then +if ac_fn_c_try_run "$LINENO"; then : ac_cv_rshift_extends_sign=yes else - echo "$as_me: program exited with status $ac_status" >&5 -echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - -( exit $ac_status ) -ac_cv_rshift_extends_sign=no + ac_cv_rshift_extends_sign=no fi -rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext conftest.$ac_objext conftest.$ac_ext +rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext \ + conftest.$ac_objext conftest.beam conftest.$ac_ext fi - fi -{ echo "$as_me:$LINENO: result: $ac_cv_rshift_extends_sign" >&5 -echo "${ECHO_T}$ac_cv_rshift_extends_sign" >&6; } +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_rshift_extends_sign" >&5 +$as_echo "$ac_cv_rshift_extends_sign" >&6; } if test "$ac_cv_rshift_extends_sign" = no then -cat >>confdefs.h <<\_ACEOF -#define SIGNED_RIGHT_SHIFT_ZERO_FILLS 1 -_ACEOF +$as_echo "#define SIGNED_RIGHT_SHIFT_ZERO_FILLS 1" >>confdefs.h fi # check for getc_unlocked and related locking functions -{ echo "$as_me:$LINENO: checking for getc_unlocked() and friends" >&5 -echo $ECHO_N "checking for getc_unlocked() and friends... $ECHO_C" >&6; } -if test "${ac_cv_have_getc_unlocked+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for getc_unlocked() and friends" >&5 +$as_echo_n "checking for getc_unlocked() and friends... " >&6; } +if test "${ac_cv_have_getc_unlocked+set}" = set; then : + $as_echo_n "(cached) " >&6 else -cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF +cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ #include int @@ -26032,44 +12694,21 @@ return 0; } _ACEOF -rm -f conftest.$ac_objext conftest$ac_exeext -if { (ac_try="$ac_link" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_link") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest$ac_exeext && - $as_test_x conftest$ac_exeext; then +if ac_fn_c_try_link "$LINENO"; then : ac_cv_have_getc_unlocked=yes else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - ac_cv_have_getc_unlocked=no + ac_cv_have_getc_unlocked=no fi - -rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \ - conftest$ac_exeext conftest.$ac_ext +rm -f core conftest.err conftest.$ac_objext \ + conftest$ac_exeext conftest.$ac_ext fi -{ echo "$as_me:$LINENO: result: $ac_cv_have_getc_unlocked" >&5 -echo "${ECHO_T}$ac_cv_have_getc_unlocked" >&6; } +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_have_getc_unlocked" >&5 +$as_echo "$ac_cv_have_getc_unlocked" >&6; } if test "$ac_cv_have_getc_unlocked" = yes then -cat >>confdefs.h <<\_ACEOF -#define HAVE_GETC_UNLOCKED 1 -_ACEOF +$as_echo "#define HAVE_GETC_UNLOCKED 1" >>confdefs.h fi @@ -26081,8 +12720,8 @@ # library. NOTE: Keep the precedence of listed libraries synchronised # with setup.py. py_cv_lib_readline=no -{ echo "$as_me:$LINENO: checking how to link readline libs" >&5 -echo $ECHO_N "checking how to link readline libs... $ECHO_C" >&6; } +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking how to link readline libs" >&5 +$as_echo_n "checking how to link readline libs... " >&6; } for py_libtermcap in "" ncursesw ncurses curses termcap; do if test -z "$py_libtermcap"; then READLINE_LIBS="-lreadline" @@ -26090,11 +12729,7 @@ READLINE_LIBS="-lreadline -l$py_libtermcap" fi LIBS="$READLINE_LIBS $LIBS_no_readline" - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF + cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ /* Override any GCC internal prototype to avoid an error. @@ -26112,34 +12747,11 @@ return 0; } _ACEOF -rm -f conftest.$ac_objext conftest$ac_exeext -if { (ac_try="$ac_link" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_link") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest$ac_exeext && - $as_test_x conftest$ac_exeext; then +if ac_fn_c_try_link "$LINENO"; then : py_cv_lib_readline=yes -else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - fi - -rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \ - conftest$ac_exeext conftest.$ac_ext +rm -f core conftest.err conftest.$ac_objext \ + conftest$ac_exeext conftest.$ac_ext if test $py_cv_lib_readline = yes; then break fi @@ -26147,31 +12759,25 @@ # Uncomment this line if you want to use READINE_LIBS in Makefile or scripts #AC_SUBST([READLINE_LIBS]) if test $py_cv_lib_readline = no; then - { echo "$as_me:$LINENO: result: none" >&5 -echo "${ECHO_T}none" >&6; } + { $as_echo "$as_me:${as_lineno-$LINENO}: result: none" >&5 +$as_echo "none" >&6; } else - { echo "$as_me:$LINENO: result: $READLINE_LIBS" >&5 -echo "${ECHO_T}$READLINE_LIBS" >&6; } + { $as_echo "$as_me:${as_lineno-$LINENO}: result: $READLINE_LIBS" >&5 +$as_echo "$READLINE_LIBS" >&6; } -cat >>confdefs.h <<\_ACEOF -#define HAVE_LIBREADLINE 1 -_ACEOF +$as_echo "#define HAVE_LIBREADLINE 1" >>confdefs.h fi # check for readline 2.1 -{ echo "$as_me:$LINENO: checking for rl_callback_handler_install in -lreadline" >&5 -echo $ECHO_N "checking for rl_callback_handler_install in -lreadline... $ECHO_C" >&6; } -if test "${ac_cv_lib_readline_rl_callback_handler_install+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for rl_callback_handler_install in -lreadline" >&5 +$as_echo_n "checking for rl_callback_handler_install in -lreadline... " >&6; } +if test "${ac_cv_lib_readline_rl_callback_handler_install+set}" = set; then : + $as_echo_n "(cached) " >&6 else ac_check_lib_save_LIBS=$LIBS LIBS="-lreadline $READLINE_LIBS $LIBS" -cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF +cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ /* Override any GCC internal prototype to avoid an error. @@ -26189,117 +12795,59 @@ return 0; } _ACEOF -rm -f conftest.$ac_objext conftest$ac_exeext -if { (ac_try="$ac_link" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_link") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest$ac_exeext && - $as_test_x conftest$ac_exeext; then +if ac_fn_c_try_link "$LINENO"; then : ac_cv_lib_readline_rl_callback_handler_install=yes else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - ac_cv_lib_readline_rl_callback_handler_install=no + ac_cv_lib_readline_rl_callback_handler_install=no fi - -rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \ - conftest$ac_exeext conftest.$ac_ext +rm -f core conftest.err conftest.$ac_objext \ + conftest$ac_exeext conftest.$ac_ext LIBS=$ac_check_lib_save_LIBS fi -{ echo "$as_me:$LINENO: result: $ac_cv_lib_readline_rl_callback_handler_install" >&5 -echo "${ECHO_T}$ac_cv_lib_readline_rl_callback_handler_install" >&6; } -if test $ac_cv_lib_readline_rl_callback_handler_install = yes; then +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_lib_readline_rl_callback_handler_install" >&5 +$as_echo "$ac_cv_lib_readline_rl_callback_handler_install" >&6; } +if test "x$ac_cv_lib_readline_rl_callback_handler_install" = x""yes; then : -cat >>confdefs.h <<\_ACEOF -#define HAVE_RL_CALLBACK 1 -_ACEOF +$as_echo "#define HAVE_RL_CALLBACK 1" >>confdefs.h fi # check for readline 2.2 -cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF +cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ #include _ACEOF -if { (ac_try="$ac_cpp conftest.$ac_ext" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_cpp conftest.$ac_ext") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } >/dev/null && { - test -z "$ac_c_preproc_warn_flag$ac_c_werror_flag" || - test ! -s conftest.err - }; then +if ac_fn_c_try_cpp "$LINENO"; then : have_readline=yes else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - have_readline=no fi - rm -f conftest.err conftest.$ac_ext if test $have_readline = yes then - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF + cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ #include _ACEOF if (eval "$ac_cpp conftest.$ac_ext") 2>&5 | - $EGREP "extern int rl_completion_append_character;" >/dev/null 2>&1; then + $EGREP "extern int rl_completion_append_character;" >/dev/null 2>&1; then : -cat >>confdefs.h <<\_ACEOF -#define HAVE_RL_COMPLETION_APPEND_CHARACTER 1 -_ACEOF +$as_echo "#define HAVE_RL_COMPLETION_APPEND_CHARACTER 1" >>confdefs.h fi rm -f conftest* - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF + cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ #include _ACEOF if (eval "$ac_cpp conftest.$ac_ext") 2>&5 | - $EGREP "extern int rl_completion_suppress_append;" >/dev/null 2>&1; then + $EGREP "extern int rl_completion_suppress_append;" >/dev/null 2>&1; then : -cat >>confdefs.h <<\_ACEOF -#define HAVE_RL_COMPLETION_SUPPRESS_APPEND 1 -_ACEOF +$as_echo "#define HAVE_RL_COMPLETION_SUPPRESS_APPEND 1" >>confdefs.h fi rm -f conftest* @@ -26307,18 +12855,14 @@ fi # check for readline 4.0 -{ echo "$as_me:$LINENO: checking for rl_pre_input_hook in -lreadline" >&5 -echo $ECHO_N "checking for rl_pre_input_hook in -lreadline... $ECHO_C" >&6; } -if test "${ac_cv_lib_readline_rl_pre_input_hook+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for rl_pre_input_hook in -lreadline" >&5 +$as_echo_n "checking for rl_pre_input_hook in -lreadline... " >&6; } +if test "${ac_cv_lib_readline_rl_pre_input_hook+set}" = set; then : + $as_echo_n "(cached) " >&6 else ac_check_lib_save_LIBS=$LIBS LIBS="-lreadline $READLINE_LIBS $LIBS" -cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF +cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ /* Override any GCC internal prototype to avoid an error. @@ -26336,60 +12880,33 @@ return 0; } _ACEOF -rm -f conftest.$ac_objext conftest$ac_exeext -if { (ac_try="$ac_link" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_link") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest$ac_exeext && - $as_test_x conftest$ac_exeext; then +if ac_fn_c_try_link "$LINENO"; then : ac_cv_lib_readline_rl_pre_input_hook=yes else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - ac_cv_lib_readline_rl_pre_input_hook=no + ac_cv_lib_readline_rl_pre_input_hook=no fi - -rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \ - conftest$ac_exeext conftest.$ac_ext +rm -f core conftest.err conftest.$ac_objext \ + conftest$ac_exeext conftest.$ac_ext LIBS=$ac_check_lib_save_LIBS fi -{ echo "$as_me:$LINENO: result: $ac_cv_lib_readline_rl_pre_input_hook" >&5 -echo "${ECHO_T}$ac_cv_lib_readline_rl_pre_input_hook" >&6; } -if test $ac_cv_lib_readline_rl_pre_input_hook = yes; then +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_lib_readline_rl_pre_input_hook" >&5 +$as_echo "$ac_cv_lib_readline_rl_pre_input_hook" >&6; } +if test "x$ac_cv_lib_readline_rl_pre_input_hook" = x""yes; then : -cat >>confdefs.h <<\_ACEOF -#define HAVE_RL_PRE_INPUT_HOOK 1 -_ACEOF +$as_echo "#define HAVE_RL_PRE_INPUT_HOOK 1" >>confdefs.h fi # also in 4.0 -{ echo "$as_me:$LINENO: checking for rl_completion_display_matches_hook in -lreadline" >&5 -echo $ECHO_N "checking for rl_completion_display_matches_hook in -lreadline... $ECHO_C" >&6; } -if test "${ac_cv_lib_readline_rl_completion_display_matches_hook+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for rl_completion_display_matches_hook in -lreadline" >&5 +$as_echo_n "checking for rl_completion_display_matches_hook in -lreadline... " >&6; } +if test "${ac_cv_lib_readline_rl_completion_display_matches_hook+set}" = set; then : + $as_echo_n "(cached) " >&6 else ac_check_lib_save_LIBS=$LIBS LIBS="-lreadline $READLINE_LIBS $LIBS" -cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF +cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ /* Override any GCC internal prototype to avoid an error. @@ -26407,60 +12924,33 @@ return 0; } _ACEOF -rm -f conftest.$ac_objext conftest$ac_exeext -if { (ac_try="$ac_link" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_link") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest$ac_exeext && - $as_test_x conftest$ac_exeext; then +if ac_fn_c_try_link "$LINENO"; then : ac_cv_lib_readline_rl_completion_display_matches_hook=yes else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - ac_cv_lib_readline_rl_completion_display_matches_hook=no + ac_cv_lib_readline_rl_completion_display_matches_hook=no fi - -rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \ - conftest$ac_exeext conftest.$ac_ext +rm -f core conftest.err conftest.$ac_objext \ + conftest$ac_exeext conftest.$ac_ext LIBS=$ac_check_lib_save_LIBS fi -{ echo "$as_me:$LINENO: result: $ac_cv_lib_readline_rl_completion_display_matches_hook" >&5 -echo "${ECHO_T}$ac_cv_lib_readline_rl_completion_display_matches_hook" >&6; } -if test $ac_cv_lib_readline_rl_completion_display_matches_hook = yes; then +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_lib_readline_rl_completion_display_matches_hook" >&5 +$as_echo "$ac_cv_lib_readline_rl_completion_display_matches_hook" >&6; } +if test "x$ac_cv_lib_readline_rl_completion_display_matches_hook" = x""yes; then : -cat >>confdefs.h <<\_ACEOF -#define HAVE_RL_COMPLETION_DISPLAY_MATCHES_HOOK 1 -_ACEOF +$as_echo "#define HAVE_RL_COMPLETION_DISPLAY_MATCHES_HOOK 1" >>confdefs.h fi # check for readline 4.2 -{ echo "$as_me:$LINENO: checking for rl_completion_matches in -lreadline" >&5 -echo $ECHO_N "checking for rl_completion_matches in -lreadline... $ECHO_C" >&6; } -if test "${ac_cv_lib_readline_rl_completion_matches+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for rl_completion_matches in -lreadline" >&5 +$as_echo_n "checking for rl_completion_matches in -lreadline... " >&6; } +if test "${ac_cv_lib_readline_rl_completion_matches+set}" = set; then : + $as_echo_n "(cached) " >&6 else ac_check_lib_save_LIBS=$LIBS LIBS="-lreadline $READLINE_LIBS $LIBS" -cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF +cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ /* Override any GCC internal prototype to avoid an error. @@ -26478,98 +12968,46 @@ return 0; } _ACEOF -rm -f conftest.$ac_objext conftest$ac_exeext -if { (ac_try="$ac_link" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_link") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest$ac_exeext && - $as_test_x conftest$ac_exeext; then +if ac_fn_c_try_link "$LINENO"; then : ac_cv_lib_readline_rl_completion_matches=yes else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - ac_cv_lib_readline_rl_completion_matches=no + ac_cv_lib_readline_rl_completion_matches=no fi - -rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \ - conftest$ac_exeext conftest.$ac_ext +rm -f core conftest.err conftest.$ac_objext \ + conftest$ac_exeext conftest.$ac_ext LIBS=$ac_check_lib_save_LIBS fi -{ echo "$as_me:$LINENO: result: $ac_cv_lib_readline_rl_completion_matches" >&5 -echo "${ECHO_T}$ac_cv_lib_readline_rl_completion_matches" >&6; } -if test $ac_cv_lib_readline_rl_completion_matches = yes; then +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_lib_readline_rl_completion_matches" >&5 +$as_echo "$ac_cv_lib_readline_rl_completion_matches" >&6; } +if test "x$ac_cv_lib_readline_rl_completion_matches" = x""yes; then : -cat >>confdefs.h <<\_ACEOF -#define HAVE_RL_COMPLETION_MATCHES 1 -_ACEOF +$as_echo "#define HAVE_RL_COMPLETION_MATCHES 1" >>confdefs.h fi # also in readline 4.2 -cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF +cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ #include _ACEOF -if { (ac_try="$ac_cpp conftest.$ac_ext" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_cpp conftest.$ac_ext") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } >/dev/null && { - test -z "$ac_c_preproc_warn_flag$ac_c_werror_flag" || - test ! -s conftest.err - }; then +if ac_fn_c_try_cpp "$LINENO"; then : have_readline=yes else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - have_readline=no fi - rm -f conftest.err conftest.$ac_ext if test $have_readline = yes then - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF + cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ #include _ACEOF if (eval "$ac_cpp conftest.$ac_ext") 2>&5 | - $EGREP "extern int rl_catch_signals;" >/dev/null 2>&1; then + $EGREP "extern int rl_catch_signals;" >/dev/null 2>&1; then : -cat >>confdefs.h <<\_ACEOF -#define HAVE_RL_CATCH_SIGNAL 1 -_ACEOF +$as_echo "#define HAVE_RL_CATCH_SIGNAL 1" >>confdefs.h fi rm -f conftest* @@ -26579,20 +13017,16 @@ # End of readline checks: restore LIBS LIBS=$LIBS_no_readline -{ echo "$as_me:$LINENO: checking for broken nice()" >&5 -echo $ECHO_N "checking for broken nice()... $ECHO_C" >&6; } -if test "${ac_cv_broken_nice+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for broken nice()" >&5 +$as_echo_n "checking for broken nice()... " >&6; } +if test "${ac_cv_broken_nice+set}" = set; then : + $as_echo_n "(cached) " >&6 else -if test "$cross_compiling" = yes; then +if test "$cross_compiling" = yes; then : ac_cv_broken_nice=no else - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF + cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ int main() @@ -26604,329 +13038,115 @@ } _ACEOF -rm -f conftest$ac_exeext -if { (ac_try="$ac_link" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_link") 2>&5 - ac_status=$? - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { ac_try='./conftest$ac_exeext' - { (case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_try") 2>&5 - ac_status=$? - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); }; }; then +if ac_fn_c_try_run "$LINENO"; then : ac_cv_broken_nice=yes else - echo "$as_me: program exited with status $ac_status" >&5 -echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - -( exit $ac_status ) -ac_cv_broken_nice=no -fi -rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext conftest.$ac_objext conftest.$ac_ext -fi - - -fi - -{ echo "$as_me:$LINENO: result: $ac_cv_broken_nice" >&5 -echo "${ECHO_T}$ac_cv_broken_nice" >&6; } -if test "$ac_cv_broken_nice" = yes -then - -cat >>confdefs.h <<\_ACEOF -#define HAVE_BROKEN_NICE 1 -_ACEOF - -fi - -{ echo "$as_me:$LINENO: checking for broken poll()" >&5 -echo $ECHO_N "checking for broken poll()... $ECHO_C" >&6; } -if test "${ac_cv_broken_poll+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 -else - if test "$cross_compiling" = yes; then - ac_cv_broken_poll=no -else - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ - -#include - -int main() -{ - struct pollfd poll_struct = { 42, POLLIN|POLLPRI|POLLOUT, 0 }; - int poll_test; - - close (42); - - poll_test = poll(&poll_struct, 1, 0); - if (poll_test < 0) - return 0; - else if (poll_test == 0 && poll_struct.revents != POLLNVAL) - return 0; - else - return 1; -} - -_ACEOF -rm -f conftest$ac_exeext -if { (ac_try="$ac_link" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_link") 2>&5 - ac_status=$? - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { ac_try='./conftest$ac_exeext' - { (case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_try") 2>&5 - ac_status=$? - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); }; }; then - ac_cv_broken_poll=yes -else - echo "$as_me: program exited with status $ac_status" >&5 -echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - -( exit $ac_status ) -ac_cv_broken_poll=no -fi -rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext conftest.$ac_objext conftest.$ac_ext -fi - - -fi - -{ echo "$as_me:$LINENO: result: $ac_cv_broken_poll" >&5 -echo "${ECHO_T}$ac_cv_broken_poll" >&6; } -if test "$ac_cv_broken_poll" = yes -then - -cat >>confdefs.h <<\_ACEOF -#define HAVE_BROKEN_POLL 1 -_ACEOF - -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[] -{ echo "$as_me:$LINENO: checking for struct tm.tm_zone" >&5 -echo $ECHO_N "checking for struct tm.tm_zone... $ECHO_C" >&6; } -if test "${ac_cv_member_struct_tm_tm_zone+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 -else - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -#include -#include <$ac_cv_struct_tm> - - -int -main () -{ -static struct tm ac_aggr; -if (ac_aggr.tm_zone) -return 0; - ; - return 0; -} -_ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - ac_cv_member_struct_tm_tm_zone=yes -else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -#include -#include <$ac_cv_struct_tm> - - -int -main () -{ -static struct tm ac_aggr; -if (sizeof ac_aggr.tm_zone) -return 0; - ; - return 0; -} -_ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - ac_cv_member_struct_tm_tm_zone=yes -else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - ac_cv_member_struct_tm_tm_zone=no + ac_cv_broken_nice=no fi - -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext +rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext \ + conftest.$ac_objext conftest.beam conftest.$ac_ext fi -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext fi -{ echo "$as_me:$LINENO: result: $ac_cv_member_struct_tm_tm_zone" >&5 -echo "${ECHO_T}$ac_cv_member_struct_tm_tm_zone" >&6; } -if test $ac_cv_member_struct_tm_tm_zone = yes; then -cat >>confdefs.h <<_ACEOF -#define HAVE_STRUCT_TM_TM_ZONE 1 -_ACEOF +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_broken_nice" >&5 +$as_echo "$ac_cv_broken_nice" >&6; } +if test "$ac_cv_broken_nice" = yes +then +$as_echo "#define HAVE_BROKEN_NICE 1" >>confdefs.h fi -if test "$ac_cv_member_struct_tm_tm_zone" = yes; then - -cat >>confdefs.h <<\_ACEOF -#define HAVE_TM_ZONE 1 -_ACEOF - +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for broken poll()" >&5 +$as_echo_n "checking for broken poll()... " >&6; } +if test "${ac_cv_broken_poll+set}" = set; then : + $as_echo_n "(cached) " >&6 else - { echo "$as_me:$LINENO: checking whether tzname is declared" >&5 -echo $ECHO_N "checking whether tzname is declared... $ECHO_C" >&6; } -if test "${ac_cv_have_decl_tzname+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 + if test "$cross_compiling" = yes; then : + ac_cv_broken_poll=no else - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF + cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ -#include -int -main () +#include + +int main() { -#ifndef tzname - (void) tzname; -#endif + struct pollfd poll_struct = { 42, POLLIN|POLLPRI|POLLOUT, 0 }; + int poll_test; - ; - return 0; + close (42); + + poll_test = poll(&poll_struct, 1, 0); + if (poll_test < 0) + return 0; + else if (poll_test == 0 && poll_struct.revents != POLLNVAL) + return 0; + else + return 1; } + _ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - ac_cv_have_decl_tzname=yes +if ac_fn_c_try_run "$LINENO"; then : + ac_cv_broken_poll=yes else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 + ac_cv_broken_poll=no +fi +rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext \ + conftest.$ac_objext conftest.beam conftest.$ac_ext +fi - ac_cv_have_decl_tzname=no fi -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_broken_poll" >&5 +$as_echo "$ac_cv_broken_poll" >&6; } +if test "$ac_cv_broken_poll" = yes +then + +$as_echo "#define HAVE_BROKEN_POLL 1" >>confdefs.h + fi -{ echo "$as_me:$LINENO: result: $ac_cv_have_decl_tzname" >&5 -echo "${ECHO_T}$ac_cv_have_decl_tzname" >&6; } -if test $ac_cv_have_decl_tzname = yes; then -cat >>confdefs.h <<_ACEOF -#define HAVE_DECL_TZNAME 1 -_ACEOF +# 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_fn_c_check_member "$LINENO" "struct tm" "tm_zone" "ac_cv_member_struct_tm_tm_zone" "#include +#include <$ac_cv_struct_tm> +" +if test "x$ac_cv_member_struct_tm_tm_zone" = x""yes; then : -else - cat >>confdefs.h <<_ACEOF -#define HAVE_DECL_TZNAME 0 +cat >>confdefs.h <<_ACEOF +#define HAVE_STRUCT_TM_TM_ZONE 1 _ACEOF fi +if test "$ac_cv_member_struct_tm_tm_zone" = yes; then + +$as_echo "#define HAVE_TM_ZONE 1" >>confdefs.h - { echo "$as_me:$LINENO: checking for tzname" >&5 -echo $ECHO_N "checking for tzname... $ECHO_C" >&6; } -if test "${ac_cv_var_tzname+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 else - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ + ac_fn_c_check_decl "$LINENO" "tzname" "ac_cv_have_decl_tzname" "#include +" +if test "x$ac_cv_have_decl_tzname" = x""yes; then : + ac_have_decl=1 +else + ac_have_decl=0 +fi + +cat >>confdefs.h <<_ACEOF +#define HAVE_DECL_TZNAME $ac_have_decl _ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF + + { $as_echo "$as_me:${as_lineno-$LINENO}: checking for tzname" >&5 +$as_echo_n "checking for tzname... " >&6; } +if test "${ac_cv_var_tzname+set}" = set; then : + $as_echo_n "(cached) " >&6 +else + cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ #include #if !HAVE_DECL_TZNAME @@ -26941,62 +13161,35 @@ return 0; } _ACEOF -rm -f conftest.$ac_objext conftest$ac_exeext -if { (ac_try="$ac_link" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_link") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest$ac_exeext && - $as_test_x conftest$ac_exeext; then +if ac_fn_c_try_link "$LINENO"; then : ac_cv_var_tzname=yes else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - ac_cv_var_tzname=no + ac_cv_var_tzname=no fi - -rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \ - conftest$ac_exeext conftest.$ac_ext +rm -f core conftest.err conftest.$ac_objext \ + conftest$ac_exeext conftest.$ac_ext fi -{ echo "$as_me:$LINENO: result: $ac_cv_var_tzname" >&5 -echo "${ECHO_T}$ac_cv_var_tzname" >&6; } +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_var_tzname" >&5 +$as_echo "$ac_cv_var_tzname" >&6; } if test $ac_cv_var_tzname = yes; then -cat >>confdefs.h <<\_ACEOF -#define HAVE_TZNAME 1 -_ACEOF +$as_echo "#define HAVE_TZNAME 1" >>confdefs.h fi fi # check tzset(3) exists and works like we expect it to -{ echo "$as_me:$LINENO: checking for working tzset()" >&5 -echo $ECHO_N "checking for working tzset()... $ECHO_C" >&6; } -if test "${ac_cv_working_tzset+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for working tzset()" >&5 +$as_echo_n "checking for working tzset()... " >&6; } +if test "${ac_cv_working_tzset+set}" = set; then : + $as_echo_n "(cached) " >&6 else -if test "$cross_compiling" = yes; then +if test "$cross_compiling" = yes; then : ac_cv_working_tzset=no else - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF + cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ #include @@ -27063,63 +13256,33 @@ } _ACEOF -rm -f conftest$ac_exeext -if { (ac_try="$ac_link" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_link") 2>&5 - ac_status=$? - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { ac_try='./conftest$ac_exeext' - { (case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_try") 2>&5 - ac_status=$? - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); }; }; then +if ac_fn_c_try_run "$LINENO"; then : ac_cv_working_tzset=yes else - echo "$as_me: program exited with status $ac_status" >&5 -echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - -( exit $ac_status ) -ac_cv_working_tzset=no + ac_cv_working_tzset=no fi -rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext conftest.$ac_objext conftest.$ac_ext +rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext \ + conftest.$ac_objext conftest.beam conftest.$ac_ext fi - fi -{ echo "$as_me:$LINENO: result: $ac_cv_working_tzset" >&5 -echo "${ECHO_T}$ac_cv_working_tzset" >&6; } +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_working_tzset" >&5 +$as_echo "$ac_cv_working_tzset" >&6; } if test "$ac_cv_working_tzset" = yes then -cat >>confdefs.h <<\_ACEOF -#define HAVE_WORKING_TZSET 1 -_ACEOF +$as_echo "#define HAVE_WORKING_TZSET 1" >>confdefs.h fi # Look for subsecond timestamps in struct stat -{ echo "$as_me:$LINENO: checking for tv_nsec in struct stat" >&5 -echo $ECHO_N "checking for tv_nsec in struct stat... $ECHO_C" >&6; } -if test "${ac_cv_stat_tv_nsec+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for tv_nsec in struct stat" >&5 +$as_echo_n "checking for tv_nsec in struct stat... " >&6; } +if test "${ac_cv_stat_tv_nsec+set}" = set; then : + $as_echo_n "(cached) " >&6 else - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF + cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ #include int @@ -27133,56 +13296,30 @@ return 0; } _ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then +if ac_fn_c_try_compile "$LINENO"; then : ac_cv_stat_tv_nsec=yes else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - ac_cv_stat_tv_nsec=no + ac_cv_stat_tv_nsec=no fi - rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext fi -{ echo "$as_me:$LINENO: result: $ac_cv_stat_tv_nsec" >&5 -echo "${ECHO_T}$ac_cv_stat_tv_nsec" >&6; } +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_stat_tv_nsec" >&5 +$as_echo "$ac_cv_stat_tv_nsec" >&6; } if test "$ac_cv_stat_tv_nsec" = yes then -cat >>confdefs.h <<\_ACEOF -#define HAVE_STAT_TV_NSEC 1 -_ACEOF +$as_echo "#define HAVE_STAT_TV_NSEC 1" >>confdefs.h fi # Look for BSD style subsecond timestamps in struct stat -{ echo "$as_me:$LINENO: checking for tv_nsec2 in struct stat" >&5 -echo $ECHO_N "checking for tv_nsec2 in struct stat... $ECHO_C" >&6; } -if test "${ac_cv_stat_tv_nsec2+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for tv_nsec2 in struct stat" >&5 +$as_echo_n "checking for tv_nsec2 in struct stat... " >&6; } +if test "${ac_cv_stat_tv_nsec2+set}" = set; then : + $as_echo_n "(cached) " >&6 else - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF + cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ #include int @@ -27196,56 +13333,30 @@ return 0; } _ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then +if ac_fn_c_try_compile "$LINENO"; then : ac_cv_stat_tv_nsec2=yes else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - ac_cv_stat_tv_nsec2=no + ac_cv_stat_tv_nsec2=no fi - rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext fi -{ echo "$as_me:$LINENO: result: $ac_cv_stat_tv_nsec2" >&5 -echo "${ECHO_T}$ac_cv_stat_tv_nsec2" >&6; } +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_stat_tv_nsec2" >&5 +$as_echo "$ac_cv_stat_tv_nsec2" >&6; } if test "$ac_cv_stat_tv_nsec2" = yes then -cat >>confdefs.h <<\_ACEOF -#define HAVE_STAT_TV_NSEC2 1 -_ACEOF +$as_echo "#define HAVE_STAT_TV_NSEC2 1" >>confdefs.h fi # On HP/UX 11.0, mvwdelch is a block with a return statement -{ echo "$as_me:$LINENO: checking whether mvwdelch is an expression" >&5 -echo $ECHO_N "checking whether mvwdelch is an expression... $ECHO_C" >&6; } -if test "${ac_cv_mvwdelch_is_expression+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking whether mvwdelch is an expression" >&5 +$as_echo_n "checking whether mvwdelch is an expression... " >&6; } +if test "${ac_cv_mvwdelch_is_expression+set}" = set; then : + $as_echo_n "(cached) " >&6 else - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF + cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ #include int @@ -27259,56 +13370,30 @@ return 0; } _ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then +if ac_fn_c_try_compile "$LINENO"; then : ac_cv_mvwdelch_is_expression=yes else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - ac_cv_mvwdelch_is_expression=no + ac_cv_mvwdelch_is_expression=no fi - rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext fi -{ echo "$as_me:$LINENO: result: $ac_cv_mvwdelch_is_expression" >&5 -echo "${ECHO_T}$ac_cv_mvwdelch_is_expression" >&6; } +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_mvwdelch_is_expression" >&5 +$as_echo "$ac_cv_mvwdelch_is_expression" >&6; } if test "$ac_cv_mvwdelch_is_expression" = yes then -cat >>confdefs.h <<\_ACEOF -#define MVWDELCH_IS_EXPRESSION 1 -_ACEOF +$as_echo "#define MVWDELCH_IS_EXPRESSION 1" >>confdefs.h fi -{ echo "$as_me:$LINENO: checking whether WINDOW has _flags" >&5 -echo $ECHO_N "checking whether WINDOW has _flags... $ECHO_C" >&6; } -if test "${ac_cv_window_has_flags+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking whether WINDOW has _flags" >&5 +$as_echo_n "checking whether WINDOW has _flags... " >&6; } +if test "${ac_cv_window_has_flags+set}" = set; then : + $as_echo_n "(cached) " >&6 else - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF + cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ #include int @@ -27322,54 +13407,28 @@ return 0; } _ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then +if ac_fn_c_try_compile "$LINENO"; then : ac_cv_window_has_flags=yes else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - ac_cv_window_has_flags=no + ac_cv_window_has_flags=no fi - rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext fi -{ echo "$as_me:$LINENO: result: $ac_cv_window_has_flags" >&5 -echo "${ECHO_T}$ac_cv_window_has_flags" >&6; } +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_window_has_flags" >&5 +$as_echo "$ac_cv_window_has_flags" >&6; } if test "$ac_cv_window_has_flags" = yes then -cat >>confdefs.h <<\_ACEOF -#define WINDOW_HAS_FLAGS 1 -_ACEOF +$as_echo "#define WINDOW_HAS_FLAGS 1" >>confdefs.h fi -{ echo "$as_me:$LINENO: checking for is_term_resized" >&5 -echo $ECHO_N "checking for is_term_resized... $ECHO_C" >&6; } -cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for is_term_resized" >&5 +$as_echo_n "checking for is_term_resized... " >&6; } +cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ #include int @@ -27380,48 +13439,22 @@ return 0; } _ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then +if ac_fn_c_try_compile "$LINENO"; then : -cat >>confdefs.h <<\_ACEOF -#define HAVE_CURSES_IS_TERM_RESIZED 1 -_ACEOF +$as_echo "#define HAVE_CURSES_IS_TERM_RESIZED 1" >>confdefs.h - { echo "$as_me:$LINENO: result: yes" >&5 -echo "${ECHO_T}yes" >&6; } + { $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +$as_echo "yes" >&6; } else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - { echo "$as_me:$LINENO: result: no" >&5 -echo "${ECHO_T}no" >&6; } + { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 +$as_echo "no" >&6; } fi - rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext -{ echo "$as_me:$LINENO: checking for resize_term" >&5 -echo $ECHO_N "checking for resize_term... $ECHO_C" >&6; } -cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for resize_term" >&5 +$as_echo_n "checking for resize_term... " >&6; } +cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ #include int @@ -27432,48 +13465,22 @@ return 0; } _ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then +if ac_fn_c_try_compile "$LINENO"; then : -cat >>confdefs.h <<\_ACEOF -#define HAVE_CURSES_RESIZE_TERM 1 -_ACEOF +$as_echo "#define HAVE_CURSES_RESIZE_TERM 1" >>confdefs.h - { echo "$as_me:$LINENO: result: yes" >&5 -echo "${ECHO_T}yes" >&6; } + { $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +$as_echo "yes" >&6; } else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - { echo "$as_me:$LINENO: result: no" >&5 -echo "${ECHO_T}no" >&6; } + { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 +$as_echo "no" >&6; } fi - rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext -{ echo "$as_me:$LINENO: checking for resizeterm" >&5 -echo $ECHO_N "checking for resizeterm... $ECHO_C" >&6; } -cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for resizeterm" >&5 +$as_echo_n "checking for resizeterm... " >&6; } +cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ #include int @@ -27484,90 +13491,60 @@ return 0; } _ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then +if ac_fn_c_try_compile "$LINENO"; then : -cat >>confdefs.h <<\_ACEOF -#define HAVE_CURSES_RESIZETERM 1 -_ACEOF +$as_echo "#define HAVE_CURSES_RESIZETERM 1" >>confdefs.h - { echo "$as_me:$LINENO: result: yes" >&5 -echo "${ECHO_T}yes" >&6; } + { $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +$as_echo "yes" >&6; } else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - { echo "$as_me:$LINENO: result: no" >&5 -echo "${ECHO_T}no" >&6; } + { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 +$as_echo "no" >&6; } fi - rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext -{ echo "$as_me:$LINENO: checking for /dev/ptmx" >&5 -echo $ECHO_N "checking for /dev/ptmx... $ECHO_C" >&6; } +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for /dev/ptmx" >&5 +$as_echo_n "checking for /dev/ptmx... " >&6; } if test -r /dev/ptmx then - { echo "$as_me:$LINENO: result: yes" >&5 -echo "${ECHO_T}yes" >&6; } + { $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +$as_echo "yes" >&6; } -cat >>confdefs.h <<\_ACEOF -#define HAVE_DEV_PTMX 1 -_ACEOF +$as_echo "#define HAVE_DEV_PTMX 1" >>confdefs.h else - { echo "$as_me:$LINENO: result: no" >&5 -echo "${ECHO_T}no" >&6; } + { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 +$as_echo "no" >&6; } fi -{ echo "$as_me:$LINENO: checking for /dev/ptc" >&5 -echo $ECHO_N "checking for /dev/ptc... $ECHO_C" >&6; } +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for /dev/ptc" >&5 +$as_echo_n "checking for /dev/ptc... " >&6; } if test -r /dev/ptc then - { echo "$as_me:$LINENO: result: yes" >&5 -echo "${ECHO_T}yes" >&6; } + { $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +$as_echo "yes" >&6; } -cat >>confdefs.h <<\_ACEOF -#define HAVE_DEV_PTC 1 -_ACEOF +$as_echo "#define HAVE_DEV_PTC 1" >>confdefs.h else - { echo "$as_me:$LINENO: result: no" >&5 -echo "${ECHO_T}no" >&6; } + { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 +$as_echo "no" >&6; } fi if test "$have_long_long" = yes then - { echo "$as_me:$LINENO: checking for %lld and %llu printf() format support" >&5 -echo $ECHO_N "checking for %lld and %llu printf() format support... $ECHO_C" >&6; } - if test "${ac_cv_have_long_long_format+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 + { $as_echo "$as_me:${as_lineno-$LINENO}: checking for %lld and %llu printf() format support" >&5 +$as_echo_n "checking for %lld and %llu printf() format support... " >&6; } + if test "${ac_cv_have_long_long_format+set}" = set; then : + $as_echo_n "(cached) " >&6 else - if test "$cross_compiling" = yes; then + if test "$cross_compiling" = yes; then : ac_cv_have_long_long_format=no else - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF + cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ #include @@ -27601,52 +13578,26 @@ } _ACEOF -rm -f conftest$ac_exeext -if { (ac_try="$ac_link" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_link") 2>&5 - ac_status=$? - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { ac_try='./conftest$ac_exeext' - { (case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_try") 2>&5 - ac_status=$? - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); }; }; then +if ac_fn_c_try_run "$LINENO"; then : ac_cv_have_long_long_format=yes else - echo "$as_me: program exited with status $ac_status" >&5 -echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - -( exit $ac_status ) -ac_cv_have_long_long_format=no + ac_cv_have_long_long_format=no fi -rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext conftest.$ac_objext conftest.$ac_ext +rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext \ + conftest.$ac_objext conftest.beam conftest.$ac_ext fi - fi - { echo "$as_me:$LINENO: result: $ac_cv_have_long_long_format" >&5 -echo "${ECHO_T}$ac_cv_have_long_long_format" >&6; } + { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_have_long_long_format" >&5 +$as_echo "$ac_cv_have_long_long_format" >&6; } fi if test "$ac_cv_have_long_long_format" = yes then -cat >>confdefs.h <<\_ACEOF -#define PY_FORMAT_LONG_LONG "ll" -_ACEOF +$as_echo "#define PY_FORMAT_LONG_LONG \"ll\"" >>confdefs.h fi @@ -27656,20 +13607,16 @@ fi -{ echo "$as_me:$LINENO: checking for %zd printf() format support" >&5 -echo $ECHO_N "checking for %zd printf() format support... $ECHO_C" >&6; } -if test "${ac_cv_have_size_t_format+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for %zd printf() format support" >&5 +$as_echo_n "checking for %zd printf() format support... " >&6; } +if test "${ac_cv_have_size_t_format+set}" = set; then : + $as_echo_n "(cached) " >&6 else - if test "$cross_compiling" = yes; then + if test "$cross_compiling" = yes; then : ac_cv_have_size_t_format="cross -- assuming yes" else - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF + cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ #include @@ -27708,62 +13655,25 @@ } _ACEOF -rm -f conftest$ac_exeext -if { (ac_try="$ac_link" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_link") 2>&5 - ac_status=$? - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { ac_try='./conftest$ac_exeext' - { (case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_try") 2>&5 - ac_status=$? - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); }; }; then +if ac_fn_c_try_run "$LINENO"; then : ac_cv_have_size_t_format=yes else - echo "$as_me: program exited with status $ac_status" >&5 -echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - -( exit $ac_status ) -ac_cv_have_size_t_format=no + ac_cv_have_size_t_format=no fi -rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext conftest.$ac_objext conftest.$ac_ext +rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext \ + conftest.$ac_objext conftest.beam conftest.$ac_ext fi - fi -{ echo "$as_me:$LINENO: result: $ac_cv_have_size_t_format" >&5 -echo "${ECHO_T}$ac_cv_have_size_t_format" >&6; } +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_have_size_t_format" >&5 +$as_echo "$ac_cv_have_size_t_format" >&6; } if test "$ac_cv_have_size_t_format" != no ; then -cat >>confdefs.h <<\_ACEOF -#define PY_FORMAT_SIZE_T "z" -_ACEOF +$as_echo "#define PY_FORMAT_SIZE_T \"z\"" >>confdefs.h fi -{ echo "$as_me:$LINENO: checking for socklen_t" >&5 -echo $ECHO_N "checking for socklen_t... $ECHO_C" >&6; } -if test "${ac_cv_type_socklen_t+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 -else - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ - +ac_fn_c_check_type "$LINENO" "socklen_t" "ac_cv_type_socklen_t" " #ifdef HAVE_SYS_TYPES_H #include #endif @@ -27771,55 +13681,12 @@ #include #endif +" +if test "x$ac_cv_type_socklen_t" = x""yes; then : -typedef socklen_t ac__type_new_; -int -main () -{ -if ((ac__type_new_ *) 0) - return 0; -if (sizeof (ac__type_new_)) - return 0; - ; - return 0; -} -_ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - ac_cv_type_socklen_t=yes -else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - ac_cv_type_socklen_t=no -fi - -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext -fi -{ echo "$as_me:$LINENO: result: $ac_cv_type_socklen_t" >&5 -echo "${ECHO_T}$ac_cv_type_socklen_t" >&6; } -if test $ac_cv_type_socklen_t = yes; then - : else -cat >>confdefs.h <<\_ACEOF -#define socklen_t int -_ACEOF +$as_echo "#define socklen_t int" >>confdefs.h fi @@ -27833,15 +13700,15 @@ SRCDIRS="Parser Grammar Objects Python Modules Mac" -{ echo "$as_me:$LINENO: checking for build directories" >&5 -echo $ECHO_N "checking for build directories... $ECHO_C" >&6; } +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for build directories" >&5 +$as_echo_n "checking for build directories... " >&6; } for dir in $SRCDIRS; do if test ! -d $dir; then mkdir $dir fi done -{ echo "$as_me:$LINENO: result: done" >&5 -echo "${ECHO_T}done" >&6; } +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: done" >&5 +$as_echo "done" >&6; } # generate output files ac_config_files="$ac_config_files Makefile.pre Modules/Setup.config Misc/python.pc" @@ -27873,12 +13740,13 @@ case $ac_val in #( *${as_nl}*) case $ac_var in #( - *_cv_*) { echo "$as_me:$LINENO: WARNING: Cache variable $ac_var contains a newline." >&5 -echo "$as_me: WARNING: Cache variable $ac_var contains a newline." >&2;} ;; + *_cv_*) { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: cache variable $ac_var contains a newline" >&5 +$as_echo "$as_me: WARNING: cache variable $ac_var contains a newline" >&2;} ;; esac case $ac_var in #( _ | IFS | as_nl) ;; #( - *) $as_unset $ac_var ;; + BASH_ARGV | BASH_SOURCE) eval $ac_var= ;; #( + *) { eval $ac_var=; unset $ac_var;} ;; esac ;; esac done @@ -27886,8 +13754,8 @@ (set) 2>&1 | case $as_nl`(ac_space=' '; set) 2>&1` in #( *${as_nl}ac_space=\ *) - # `set' does not quote correctly, so add quotes (double-quote - # substitution turns \\\\ into \\, and sed turns \\ into \). + # `set' does not quote correctly, so add quotes: double-quote + # substitution turns \\\\ into \\, and sed turns \\ into \. sed -n \ "s/'/'\\\\''/g; s/^\\([_$as_cr_alnum]*_cv_[_$as_cr_alnum]*\\)=\\(.*\\)/\\1='\\2'/p" @@ -27910,12 +13778,12 @@ if diff "$cache_file" confcache >/dev/null 2>&1; then :; else if test -w "$cache_file"; then test "x$cache_file" != "x/dev/null" && - { echo "$as_me:$LINENO: updating cache $cache_file" >&5 -echo "$as_me: updating cache $cache_file" >&6;} + { $as_echo "$as_me:${as_lineno-$LINENO}: updating cache $cache_file" >&5 +$as_echo "$as_me: updating cache $cache_file" >&6;} cat confcache >$cache_file else - { echo "$as_me:$LINENO: not updating unwritable cache $cache_file" >&5 -echo "$as_me: not updating unwritable cache $cache_file" >&6;} + { $as_echo "$as_me:${as_lineno-$LINENO}: not updating unwritable cache $cache_file" >&5 +$as_echo "$as_me: not updating unwritable cache $cache_file" >&6;} fi fi rm -f confcache @@ -27931,11 +13799,11 @@ for ac_i in : $LIBOBJS; do test "x$ac_i" = x: && continue # 1. Remove the extension, and $U if already installed. ac_script='s/\$U\././;s/\.o$//;s/\.obj$//' - ac_i=`echo "$ac_i" | sed "$ac_script"` + ac_i=`$as_echo "$ac_i" | sed "$ac_script"` # 2. Prepend LIBOBJDIR. When used with automake>=1.10 LIBOBJDIR # will be set to the directory where LIBOBJS objects are built. - ac_libobjs="$ac_libobjs \${LIBOBJDIR}$ac_i\$U.$ac_objext" - ac_ltlibobjs="$ac_ltlibobjs \${LIBOBJDIR}$ac_i"'$U.lo' + as_fn_append ac_libobjs " \${LIBOBJDIR}$ac_i\$U.$ac_objext" + as_fn_append ac_ltlibobjs " \${LIBOBJDIR}$ac_i"'$U.lo' done LIBOBJS=$ac_libobjs @@ -27943,12 +13811,15 @@ + : ${CONFIG_STATUS=./config.status} +ac_write_fail=0 ac_clean_files_save=$ac_clean_files ac_clean_files="$ac_clean_files $CONFIG_STATUS" -{ echo "$as_me:$LINENO: creating $CONFIG_STATUS" >&5 -echo "$as_me: creating $CONFIG_STATUS" >&6;} -cat >$CONFIG_STATUS <<_ACEOF +{ $as_echo "$as_me:${as_lineno-$LINENO}: creating $CONFIG_STATUS" >&5 +$as_echo "$as_me: creating $CONFIG_STATUS" >&6;} +as_write_fail=0 +cat >$CONFIG_STATUS <<_ASEOF || as_write_fail=1 #! $SHELL # Generated by $as_me. # Run this file to recreate the current configuration. @@ -27958,59 +13829,79 @@ debug=false ac_cs_recheck=false ac_cs_silent=false -SHELL=\${CONFIG_SHELL-$SHELL} -_ACEOF -cat >>$CONFIG_STATUS <<\_ACEOF -## --------------------- ## -## M4sh Initialization. ## -## --------------------- ## +SHELL=\${CONFIG_SHELL-$SHELL} +export SHELL +_ASEOF +cat >>$CONFIG_STATUS <<\_ASEOF || as_write_fail=1 +## -------------------- ## +## M4sh Initialization. ## +## -------------------- ## # Be more Bourne compatible DUALCASE=1; export DUALCASE # for MKS sh -if test -n "${ZSH_VERSION+set}" && (emulate sh) >/dev/null 2>&1; then +if test -n "${ZSH_VERSION+set}" && (emulate sh) >/dev/null 2>&1; then : emulate sh NULLCMD=: - # Zsh 3.x and 4.x performs word splitting on ${1+"$@"}, which + # Pre-4.2 versions of Zsh do word splitting on ${1+"$@"}, which # is contrary to our usage. Disable this feature. alias -g '${1+"$@"}'='"$@"' setopt NO_GLOB_SUBST else - case `(set -o) 2>/dev/null` in - *posix*) set -o posix ;; + case `(set -o) 2>/dev/null` in #( + *posix*) : + set -o posix ;; #( + *) : + ;; esac - fi - - -# PATH needs CR -# Avoid depending upon Character Ranges. -as_cr_letters='abcdefghijklmnopqrstuvwxyz' -as_cr_LETTERS='ABCDEFGHIJKLMNOPQRSTUVWXYZ' -as_cr_Letters=$as_cr_letters$as_cr_LETTERS -as_cr_digits='0123456789' -as_cr_alnum=$as_cr_Letters$as_cr_digits - -# The user is always right. -if test "${PATH_SEPARATOR+set}" != set; then - echo "#! /bin/sh" >conf$$.sh - echo "exit 0" >>conf$$.sh - chmod +x conf$$.sh - if (PATH="/nonexistent;."; conf$$.sh) >/dev/null 2>&1; then - PATH_SEPARATOR=';' - else - PATH_SEPARATOR=: +as_nl=' +' +export as_nl +# Printing a long string crashes Solaris 7 /usr/bin/printf. +as_echo='\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\' +as_echo=$as_echo$as_echo$as_echo$as_echo$as_echo +as_echo=$as_echo$as_echo$as_echo$as_echo$as_echo$as_echo +# Prefer a ksh shell builtin over an external printf program on Solaris, +# but without wasting forks for bash or zsh. +if test -z "$BASH_VERSION$ZSH_VERSION" \ + && (test "X`print -r -- $as_echo`" = "X$as_echo") 2>/dev/null; then + as_echo='print -r --' + as_echo_n='print -rn --' +elif (test "X`printf %s $as_echo`" = "X$as_echo") 2>/dev/null; then + as_echo='printf %s\n' + as_echo_n='printf %s' +else + if test "X`(/usr/ucb/echo -n -n $as_echo) 2>/dev/null`" = "X-n $as_echo"; then + as_echo_body='eval /usr/ucb/echo -n "$1$as_nl"' + as_echo_n='/usr/ucb/echo -n' + else + as_echo_body='eval expr "X$1" : "X\\(.*\\)"' + as_echo_n_body='eval + arg=$1; + case $arg in #( + *"$as_nl"*) + expr "X$arg" : "X\\(.*\\)$as_nl"; + arg=`expr "X$arg" : ".*$as_nl\\(.*\\)"`;; + esac; + expr "X$arg" : "X\\(.*\\)" | tr -d "$as_nl" + ' + export as_echo_n_body + as_echo_n='sh -c $as_echo_n_body as_echo' fi - rm -f conf$$.sh + export as_echo_body + as_echo='sh -c $as_echo_body as_echo' fi -# Support unset when possible. -if ( (MAIL=60; unset MAIL) || exit) >/dev/null 2>&1; then - as_unset=unset -else - as_unset=false +# The user is always right. +if test "${PATH_SEPARATOR+set}" != set; then + PATH_SEPARATOR=: + (PATH='/bin;/bin'; FPATH=$PATH; sh -c :) >/dev/null 2>&1 && { + (PATH='/bin:/bin'; FPATH=$PATH; sh -c :) >/dev/null 2>&1 || + PATH_SEPARATOR=';' + } fi @@ -28019,20 +13910,18 @@ # there to prevent editors from complaining about space-tab. # (If _AS_PATH_WALK were called with IFS unset, it would disable word # splitting by setting IFS to empty value.) -as_nl=' -' IFS=" "" $as_nl" # Find who we are. Look in the path if we contain no directory separator. -case $0 in +case $0 in #(( *[\\/]* ) as_myself=$0 ;; *) as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $PATH do IFS=$as_save_IFS test -z "$as_dir" && as_dir=. - test -r "$as_dir/$0" && as_myself=$as_dir/$0 && break -done + test -r "$as_dir/$0" && as_myself=$as_dir/$0 && break + done IFS=$as_save_IFS ;; @@ -28043,32 +13932,111 @@ as_myself=$0 fi if test ! -f "$as_myself"; then - echo "$as_myself: error: cannot find myself; rerun with an absolute file name" >&2 - { (exit 1); exit 1; } + $as_echo "$as_myself: error: cannot find myself; rerun with an absolute file name" >&2 + exit 1 fi -# Work around bugs in pre-3.0 UWIN ksh. -for as_var in ENV MAIL MAILPATH -do ($as_unset $as_var) >/dev/null 2>&1 && $as_unset $as_var +# Unset variables that we do not need and which cause bugs (e.g. in +# pre-3.0 UWIN ksh). But do not cause bugs in bash 2.01; the "|| exit 1" +# suppresses any "Segmentation fault" message there. '((' could +# trigger a bug in pdksh 5.2.14. +for as_var in BASH_ENV ENV MAIL MAILPATH +do eval test x\${$as_var+set} = xset \ + && ( (unset $as_var) || exit 1) >/dev/null 2>&1 && unset $as_var || : done PS1='$ ' PS2='> ' PS4='+ ' # NLS nuisances. -for as_var in \ - LANG LANGUAGE LC_ADDRESS LC_ALL LC_COLLATE LC_CTYPE LC_IDENTIFICATION \ - LC_MEASUREMENT LC_MESSAGES LC_MONETARY LC_NAME LC_NUMERIC LC_PAPER \ - LC_TELEPHONE LC_TIME -do - if (set +x; test -z "`(eval $as_var=C; export $as_var) 2>&1`"); then - eval $as_var=C; export $as_var - else - ($as_unset $as_var) >/dev/null 2>&1 && $as_unset $as_var - fi -done +LC_ALL=C +export LC_ALL +LANGUAGE=C +export LANGUAGE + +# CDPATH. +(unset CDPATH) >/dev/null 2>&1 && unset CDPATH + + +# as_fn_error ERROR [LINENO LOG_FD] +# --------------------------------- +# Output "`basename $0`: error: ERROR" to stderr. If LINENO and LOG_FD are +# provided, also output the error to LOG_FD, referencing LINENO. Then exit the +# script with status $?, using 1 if that was 0. +as_fn_error () +{ + as_status=$?; test $as_status -eq 0 && as_status=1 + if test "$3"; then + as_lineno=${as_lineno-"$2"} as_lineno_stack=as_lineno_stack=$as_lineno_stack + $as_echo "$as_me:${as_lineno-$LINENO}: error: $1" >&$3 + fi + $as_echo "$as_me: error: $1" >&2 + as_fn_exit $as_status +} # as_fn_error + + +# as_fn_set_status STATUS +# ----------------------- +# Set $? to STATUS, without forking. +as_fn_set_status () +{ + return $1 +} # as_fn_set_status + +# as_fn_exit STATUS +# ----------------- +# Exit the shell with STATUS, even in a "trap 0" or "set -e" context. +as_fn_exit () +{ + set +e + as_fn_set_status $1 + exit $1 +} # as_fn_exit + +# as_fn_unset VAR +# --------------- +# Portably unset VAR. +as_fn_unset () +{ + { eval $1=; unset $1;} +} +as_unset=as_fn_unset +# as_fn_append VAR VALUE +# ---------------------- +# Append the text in VALUE to the end of the definition contained in VAR. Take +# advantage of any shell optimizations that allow amortized linear growth over +# repeated appends, instead of the typical quadratic growth present in naive +# implementations. +if (eval "as_var=1; as_var+=2; test x\$as_var = x12") 2>/dev/null; then : + eval 'as_fn_append () + { + eval $1+=\$2 + }' +else + as_fn_append () + { + eval $1=\$$1\$2 + } +fi # as_fn_append + +# as_fn_arith ARG... +# ------------------ +# Perform arithmetic evaluation on the ARGs, and store the result in the +# global $as_val. Take advantage of shells that can avoid forks. The arguments +# must be portable across $(()) and expr. +if (eval "test \$(( 1 + 1 )) = 2") 2>/dev/null; then : + eval 'as_fn_arith () + { + as_val=$(( $* )) + }' +else + as_fn_arith () + { + as_val=`expr "$@" || test $? -eq 1` + } +fi # as_fn_arith + -# Required to use basename. if expr a : '\(a\)' >/dev/null 2>&1 && test "X`expr 00001 : '.*\(...\)'`" = X001; then as_expr=expr @@ -28082,13 +14050,17 @@ as_basename=false fi +if (as_dir=`dirname -- /` && test "X$as_dir" = X/) >/dev/null 2>&1; then + as_dirname=dirname +else + as_dirname=false +fi -# Name of the executable. as_me=`$as_basename -- "$0" || $as_expr X/"$0" : '.*/\([^/][^/]*\)/*$' \| \ X"$0" : 'X\(//\)$' \| \ X"$0" : 'X\(/\)' \| . 2>/dev/null || -echo X/"$0" | +$as_echo X/"$0" | sed '/^.*\/\([^/][^/]*\)\/*$/{ s//\1/ q @@ -28103,104 +14075,103 @@ } s/.*/./; q'` -# CDPATH. -$as_unset CDPATH - - - - as_lineno_1=$LINENO - as_lineno_2=$LINENO - test "x$as_lineno_1" != "x$as_lineno_2" && - test "x`expr $as_lineno_1 + 1`" = "x$as_lineno_2" || { - - # Create $as_me.lineno as a copy of $as_myself, but with $LINENO - # uniformly replaced by the line number. The first 'sed' inserts a - # line-number line after each line using $LINENO; the second 'sed' - # does the real work. The second script uses 'N' to pair each - # line-number line with the line containing $LINENO, and appends - # trailing '-' during substitution so that $LINENO is not a special - # case at line end. - # (Raja R Harinath suggested sed '=', and Paul Eggert wrote the - # scripts with optimization help from Paolo Bonzini. Blame Lee - # E. McMahon (1931-1989) for sed's syntax. :-) - sed -n ' - p - /[$]LINENO/= - ' <$as_myself | - sed ' - s/[$]LINENO.*/&-/ - t lineno - b - :lineno - N - :loop - s/[$]LINENO\([^'$as_cr_alnum'_].*\n\)\(.*\)/\2\1\2/ - t loop - s/-\n.*// - ' >$as_me.lineno && - chmod +x "$as_me.lineno" || - { echo "$as_me: error: cannot create $as_me.lineno; rerun with a POSIX shell" >&2 - { (exit 1); exit 1; }; } - - # Don't try to exec as it changes $[0], causing all sort of problems - # (the dirname of $[0] is not the place where we might find the - # original and so on. Autoconf is especially sensitive to this). - . "./$as_me.lineno" - # Exit status is that of the last command. - exit -} - - -if (as_dir=`dirname -- /` && test "X$as_dir" = X/) >/dev/null 2>&1; then - as_dirname=dirname -else - as_dirname=false -fi +# Avoid depending upon Character Ranges. +as_cr_letters='abcdefghijklmnopqrstuvwxyz' +as_cr_LETTERS='ABCDEFGHIJKLMNOPQRSTUVWXYZ' +as_cr_Letters=$as_cr_letters$as_cr_LETTERS +as_cr_digits='0123456789' +as_cr_alnum=$as_cr_Letters$as_cr_digits ECHO_C= ECHO_N= ECHO_T= -case `echo -n x` in +case `echo -n x` in #((((( -n*) - case `echo 'x\c'` in + case `echo 'xy\c'` in *c*) ECHO_T=' ';; # ECHO_T is single tab character. - *) ECHO_C='\c';; + xy) ECHO_C='\c';; + *) echo `echo ksh88 bug on AIX 6.1` > /dev/null + ECHO_T=' ';; esac;; *) ECHO_N='-n';; esac -if expr a : '\(a\)' >/dev/null 2>&1 && - test "X`expr 00001 : '.*\(...\)'`" = X001; then - as_expr=expr -else - as_expr=false -fi - rm -f conf$$ conf$$.exe conf$$.file if test -d conf$$.dir; then rm -f conf$$.dir/conf$$.file else rm -f conf$$.dir - mkdir conf$$.dir + mkdir conf$$.dir 2>/dev/null fi -echo >conf$$.file -if ln -s conf$$.file conf$$ 2>/dev/null; then - as_ln_s='ln -s' - # ... but there are two gotchas: - # 1) On MSYS, both `ln -s file dir' and `ln file dir' fail. - # 2) DJGPP < 2.04 has no symlinks; `ln -s' creates a wrapper executable. - # In both cases, we have to default to `cp -p'. - ln -s conf$$.file conf$$.dir 2>/dev/null && test ! -f conf$$.exe || +if (echo >conf$$.file) 2>/dev/null; then + if ln -s conf$$.file conf$$ 2>/dev/null; then + as_ln_s='ln -s' + # ... but there are two gotchas: + # 1) On MSYS, both `ln -s file dir' and `ln file dir' fail. + # 2) DJGPP < 2.04 has no symlinks; `ln -s' creates a wrapper executable. + # In both cases, we have to default to `cp -p'. + ln -s conf$$.file conf$$.dir 2>/dev/null && test ! -f conf$$.exe || + as_ln_s='cp -p' + elif ln conf$$.file conf$$ 2>/dev/null; then + as_ln_s=ln + else as_ln_s='cp -p' -elif ln conf$$.file conf$$ 2>/dev/null; then - as_ln_s=ln + fi else as_ln_s='cp -p' fi rm -f conf$$ conf$$.exe conf$$.dir/conf$$.file conf$$.file rmdir conf$$.dir 2>/dev/null + +# as_fn_mkdir_p +# ------------- +# Create "$as_dir" as a directory, including parents if necessary. +as_fn_mkdir_p () +{ + + case $as_dir in #( + -*) as_dir=./$as_dir;; + esac + test -d "$as_dir" || eval $as_mkdir_p || { + as_dirs= + while :; do + case $as_dir in #( + *\'*) as_qdir=`$as_echo "$as_dir" | sed "s/'/'\\\\\\\\''/g"`;; #'( + *) as_qdir=$as_dir;; + esac + as_dirs="'$as_qdir' $as_dirs" + as_dir=`$as_dirname -- "$as_dir" || +$as_expr X"$as_dir" : 'X\(.*[^/]\)//*[^/][^/]*/*$' \| \ + X"$as_dir" : 'X\(//\)[^/]' \| \ + X"$as_dir" : 'X\(//\)$' \| \ + X"$as_dir" : 'X\(/\)' \| . 2>/dev/null || +$as_echo X"$as_dir" | + sed '/^X\(.*[^/]\)\/\/*[^/][^/]*\/*$/{ + s//\1/ + q + } + /^X\(\/\/\)[^/].*/{ + s//\1/ + q + } + /^X\(\/\/\)$/{ + s//\1/ + q + } + /^X\(\/\).*/{ + s//\1/ + q + } + s/.*/./; q'` + test -d "$as_dir" && break + done + test -z "$as_dirs" || eval "mkdir $as_dirs" + } || test -d "$as_dir" || as_fn_error "cannot create directory $as_dir" + + +} # as_fn_mkdir_p if mkdir -p . 2>/dev/null; then - as_mkdir_p=: + as_mkdir_p='mkdir -p "$as_dir"' else test -d ./-p && rmdir ./-p as_mkdir_p=false @@ -28217,12 +14188,12 @@ as_test_x=' eval sh -c '\'' if test -d "$1"; then - test -d "$1/."; + test -d "$1/."; else - case $1 in - -*)set "./$1";; + case $1 in #( + -*)set "./$1";; esac; - case `ls -ld'$as_ls_L_option' "$1" 2>/dev/null` in + case `ls -ld'$as_ls_L_option' "$1" 2>/dev/null` in #(( ???[sx]*):;;*)false;;esac;fi '\'' sh ' @@ -28237,13 +14208,19 @@ exec 6>&1 +## ----------------------------------- ## +## Main body of $CONFIG_STATUS script. ## +## ----------------------------------- ## +_ASEOF +test $as_write_fail = 0 && chmod +x $CONFIG_STATUS || ac_write_fail=1 -# Save the log message, to keep $[0] and so on meaningful, and to +cat >>$CONFIG_STATUS <<\_ACEOF || ac_write_fail=1 +# Save the log message, to keep $0 and so on meaningful, and to # report actual input values of CONFIG_FILES etc. instead of their # values after options handling. ac_log=" This file was extended by python $as_me 2.7, which was -generated by GNU Autoconf 2.61. Invocation command line was +generated by GNU Autoconf 2.65. Invocation command line was CONFIG_FILES = $CONFIG_FILES CONFIG_HEADERS = $CONFIG_HEADERS @@ -28256,29 +14233,41 @@ _ACEOF -cat >>$CONFIG_STATUS <<_ACEOF +case $ac_config_files in *" +"*) set x $ac_config_files; shift; ac_config_files=$*;; +esac + +case $ac_config_headers in *" +"*) set x $ac_config_headers; shift; ac_config_headers=$*;; +esac + + +cat >>$CONFIG_STATUS <<_ACEOF || ac_write_fail=1 # Files that config.status was made for. config_files="$ac_config_files" config_headers="$ac_config_headers" _ACEOF -cat >>$CONFIG_STATUS <<\_ACEOF +cat >>$CONFIG_STATUS <<\_ACEOF || ac_write_fail=1 ac_cs_usage="\ -\`$as_me' instantiates files from templates according to the -current configuration. +\`$as_me' instantiates files and other configuration actions +from templates according to the current configuration. Unless the files +and actions are specified as TAGs, all are instantiated by default. -Usage: $0 [OPTIONS] [FILE]... +Usage: $0 [OPTION]... [TAG]... -h, --help print this help, then exit -V, --version print version number and configuration settings, then exit - -q, --quiet do not print progress messages + --config print configuration, then exit + -q, --quiet, --silent + do not print progress messages -d, --debug don't remove temporary files --recheck update $as_me by reconfiguring in the same conditions - --file=FILE[:TEMPLATE] - instantiate the configuration file FILE - --header=FILE[:TEMPLATE] - instantiate the configuration header FILE + --file=FILE[:TEMPLATE] + instantiate the configuration file FILE + --header=FILE[:TEMPLATE] + instantiate the configuration header FILE Configuration files: $config_files @@ -28286,27 +14275,28 @@ Configuration headers: $config_headers -Report bugs to ." +Report bugs to ." _ACEOF -cat >>$CONFIG_STATUS <<_ACEOF +cat >>$CONFIG_STATUS <<_ACEOF || ac_write_fail=1 +ac_cs_config="`$as_echo "$ac_configure_args" | sed 's/^ //; s/[\\""\`\$]/\\\\&/g'`" ac_cs_version="\\ python config.status 2.7 -configured by $0, generated by GNU Autoconf 2.61, - with options \\"`echo "$ac_configure_args" | sed 's/^ //; s/[\\""\`\$]/\\\\&/g'`\\" +configured by $0, generated by GNU Autoconf 2.65, + with options \\"\$ac_cs_config\\" -Copyright (C) 2006 Free Software Foundation, Inc. +Copyright (C) 2009 Free Software Foundation, Inc. This config.status script is free software; the Free Software Foundation gives unlimited permission to copy, distribute and modify it." ac_pwd='$ac_pwd' srcdir='$srcdir' INSTALL='$INSTALL' +test -n "\$AWK" || AWK=awk _ACEOF -cat >>$CONFIG_STATUS <<\_ACEOF -# If no file are specified by the user, then we need to provide default -# value. By we need to know if files were specified by the user. +cat >>$CONFIG_STATUS <<\_ACEOF || ac_write_fail=1 +# The default lists apply if the user does not specify any file. ac_need_defaults=: while test $# != 0 do @@ -28328,34 +14318,40 @@ -recheck | --recheck | --rechec | --reche | --rech | --rec | --re | --r) ac_cs_recheck=: ;; --version | --versio | --versi | --vers | --ver | --ve | --v | -V ) - echo "$ac_cs_version"; exit ;; + $as_echo "$ac_cs_version"; exit ;; + --config | --confi | --conf | --con | --co | --c ) + $as_echo "$ac_cs_config"; exit ;; --debug | --debu | --deb | --de | --d | -d ) debug=: ;; --file | --fil | --fi | --f ) $ac_shift - CONFIG_FILES="$CONFIG_FILES $ac_optarg" + case $ac_optarg in + *\'*) ac_optarg=`$as_echo "$ac_optarg" | sed "s/'/'\\\\\\\\''/g"` ;; + esac + as_fn_append CONFIG_FILES " '$ac_optarg'" ac_need_defaults=false;; --header | --heade | --head | --hea ) $ac_shift - CONFIG_HEADERS="$CONFIG_HEADERS $ac_optarg" + case $ac_optarg in + *\'*) ac_optarg=`$as_echo "$ac_optarg" | sed "s/'/'\\\\\\\\''/g"` ;; + esac + as_fn_append CONFIG_HEADERS " '$ac_optarg'" ac_need_defaults=false;; --he | --h) # Conflict between --help and --header - { echo "$as_me: error: ambiguous option: $1 -Try \`$0 --help' for more information." >&2 - { (exit 1); exit 1; }; };; + as_fn_error "ambiguous option: \`$1' +Try \`$0 --help' for more information.";; --help | --hel | -h ) - echo "$ac_cs_usage"; exit ;; + $as_echo "$ac_cs_usage"; exit ;; -q | -quiet | --quiet | --quie | --qui | --qu | --q \ | -silent | --silent | --silen | --sile | --sil | --si | --s) ac_cs_silent=: ;; # This is an error. - -*) { echo "$as_me: error: unrecognized option: $1 -Try \`$0 --help' for more information." >&2 - { (exit 1); exit 1; }; } ;; + -*) as_fn_error "unrecognized option: \`$1' +Try \`$0 --help' for more information." ;; - *) ac_config_targets="$ac_config_targets $1" + *) as_fn_append ac_config_targets " $1" ac_need_defaults=false ;; esac @@ -28370,30 +14366,32 @@ fi _ACEOF -cat >>$CONFIG_STATUS <<_ACEOF +cat >>$CONFIG_STATUS <<_ACEOF || ac_write_fail=1 if \$ac_cs_recheck; then - echo "running CONFIG_SHELL=$SHELL $SHELL $0 "$ac_configure_args \$ac_configure_extra_args " --no-create --no-recursion" >&6 - CONFIG_SHELL=$SHELL + set X '$SHELL' '$0' $ac_configure_args \$ac_configure_extra_args --no-create --no-recursion + shift + \$as_echo "running CONFIG_SHELL=$SHELL \$*" >&6 + CONFIG_SHELL='$SHELL' export CONFIG_SHELL - exec $SHELL "$0"$ac_configure_args \$ac_configure_extra_args --no-create --no-recursion + exec "\$@" fi _ACEOF -cat >>$CONFIG_STATUS <<\_ACEOF +cat >>$CONFIG_STATUS <<\_ACEOF || ac_write_fail=1 exec 5>>config.log { echo sed 'h;s/./-/g;s/^.../## /;s/...$/ ##/;p;x;p;x' <<_ASBOX ## Running $as_me. ## _ASBOX - echo "$ac_log" + $as_echo "$ac_log" } >&5 _ACEOF -cat >>$CONFIG_STATUS <<_ACEOF +cat >>$CONFIG_STATUS <<_ACEOF || ac_write_fail=1 _ACEOF -cat >>$CONFIG_STATUS <<\_ACEOF +cat >>$CONFIG_STATUS <<\_ACEOF || ac_write_fail=1 # Handling of arguments. for ac_config_target in $ac_config_targets @@ -28409,9 +14407,7 @@ "Modules/Setup.config") CONFIG_FILES="$CONFIG_FILES Modules/Setup.config" ;; "Misc/python.pc") CONFIG_FILES="$CONFIG_FILES Misc/python.pc" ;; - *) { { echo "$as_me:$LINENO: error: invalid argument: $ac_config_target" >&5 -echo "$as_me: error: invalid argument: $ac_config_target" >&2;} - { (exit 1); exit 1; }; };; + *) as_fn_error "invalid argument: \`$ac_config_target'" "$LINENO" 5;; esac done @@ -28437,7 +14433,7 @@ trap 'exit_status=$? { test -z "$tmp" || test ! -d "$tmp" || rm -fr "$tmp"; } && exit $exit_status ' 0 - trap '{ (exit 1); exit 1; }' 1 2 13 15 + trap 'as_fn_exit 1' 1 2 13 15 } # Create a (secure) tmp directory for tmp files. @@ -28448,233 +14444,139 @@ { tmp=./conf$$-$RANDOM (umask 077 && mkdir "$tmp") -} || -{ - echo "$me: cannot create a temporary directory in ." >&2 - { (exit 1); exit 1; } -} - -# -# Set up the sed scripts for CONFIG_FILES section. -# +} || as_fn_error "cannot create a temporary directory in ." "$LINENO" 5 -# No need to generate the scripts if there are no CONFIG_FILES. -# This happens for instance when ./config.status config.h +# Set up the scripts for CONFIG_FILES section. +# No need to generate them if there are no CONFIG_FILES. +# This happens for instance with `./config.status config.h'. if test -n "$CONFIG_FILES"; then -_ACEOF - - - -ac_delim='%!_!# ' -for ac_last_try in false false false false false :; do - cat >conf$$subs.sed <<_ACEOF -SHELL!$SHELL$ac_delim -PATH_SEPARATOR!$PATH_SEPARATOR$ac_delim -PACKAGE_NAME!$PACKAGE_NAME$ac_delim -PACKAGE_TARNAME!$PACKAGE_TARNAME$ac_delim -PACKAGE_VERSION!$PACKAGE_VERSION$ac_delim -PACKAGE_STRING!$PACKAGE_STRING$ac_delim -PACKAGE_BUGREPORT!$PACKAGE_BUGREPORT$ac_delim -exec_prefix!$exec_prefix$ac_delim -prefix!$prefix$ac_delim -program_transform_name!$program_transform_name$ac_delim -bindir!$bindir$ac_delim -sbindir!$sbindir$ac_delim -libexecdir!$libexecdir$ac_delim -datarootdir!$datarootdir$ac_delim -datadir!$datadir$ac_delim -sysconfdir!$sysconfdir$ac_delim -sharedstatedir!$sharedstatedir$ac_delim -localstatedir!$localstatedir$ac_delim -includedir!$includedir$ac_delim -oldincludedir!$oldincludedir$ac_delim -docdir!$docdir$ac_delim -infodir!$infodir$ac_delim -htmldir!$htmldir$ac_delim -dvidir!$dvidir$ac_delim -pdfdir!$pdfdir$ac_delim -psdir!$psdir$ac_delim -libdir!$libdir$ac_delim -localedir!$localedir$ac_delim -mandir!$mandir$ac_delim -DEFS!$DEFS$ac_delim -ECHO_C!$ECHO_C$ac_delim -ECHO_N!$ECHO_N$ac_delim -ECHO_T!$ECHO_T$ac_delim -LIBS!$LIBS$ac_delim -build_alias!$build_alias$ac_delim -host_alias!$host_alias$ac_delim -target_alias!$target_alias$ac_delim -VERSION!$VERSION$ac_delim -SOVERSION!$SOVERSION$ac_delim -CONFIG_ARGS!$CONFIG_ARGS$ac_delim -UNIVERSALSDK!$UNIVERSALSDK$ac_delim -ARCH_RUN_32BIT!$ARCH_RUN_32BIT$ac_delim -LIPO_32BIT_FLAGS!$LIPO_32BIT_FLAGS$ac_delim -PYTHONFRAMEWORK!$PYTHONFRAMEWORK$ac_delim -PYTHONFRAMEWORKIDENTIFIER!$PYTHONFRAMEWORKIDENTIFIER$ac_delim -PYTHONFRAMEWORKDIR!$PYTHONFRAMEWORKDIR$ac_delim -PYTHONFRAMEWORKPREFIX!$PYTHONFRAMEWORKPREFIX$ac_delim -PYTHONFRAMEWORKINSTALLDIR!$PYTHONFRAMEWORKINSTALLDIR$ac_delim -FRAMEWORKINSTALLFIRST!$FRAMEWORKINSTALLFIRST$ac_delim -FRAMEWORKINSTALLLAST!$FRAMEWORKINSTALLLAST$ac_delim -FRAMEWORKALTINSTALLFIRST!$FRAMEWORKALTINSTALLFIRST$ac_delim -FRAMEWORKALTINSTALLLAST!$FRAMEWORKALTINSTALLLAST$ac_delim -FRAMEWORKUNIXTOOLSPREFIX!$FRAMEWORKUNIXTOOLSPREFIX$ac_delim -FRAMEWORKINSTALLAPPSPREFIX!$FRAMEWORKINSTALLAPPSPREFIX$ac_delim -MACHDEP!$MACHDEP$ac_delim -SGI_ABI!$SGI_ABI$ac_delim -EXTRAPLATDIR!$EXTRAPLATDIR$ac_delim -EXTRAMACHDEPPATH!$EXTRAMACHDEPPATH$ac_delim -CONFIGURE_MACOSX_DEPLOYMENT_TARGET!$CONFIGURE_MACOSX_DEPLOYMENT_TARGET$ac_delim -EXPORT_MACOSX_DEPLOYMENT_TARGET!$EXPORT_MACOSX_DEPLOYMENT_TARGET$ac_delim -CC!$CC$ac_delim -CFLAGS!$CFLAGS$ac_delim -LDFLAGS!$LDFLAGS$ac_delim -CPPFLAGS!$CPPFLAGS$ac_delim -ac_ct_CC!$ac_ct_CC$ac_delim -EXEEXT!$EXEEXT$ac_delim -OBJEXT!$OBJEXT$ac_delim -CXX!$CXX$ac_delim -MAINCC!$MAINCC$ac_delim -CPP!$CPP$ac_delim -GREP!$GREP$ac_delim -EGREP!$EGREP$ac_delim -BUILDEXEEXT!$BUILDEXEEXT$ac_delim -LIBRARY!$LIBRARY$ac_delim -LDLIBRARY!$LDLIBRARY$ac_delim -DLLLIBRARY!$DLLLIBRARY$ac_delim -BLDLIBRARY!$BLDLIBRARY$ac_delim -LDLIBRARYDIR!$LDLIBRARYDIR$ac_delim -INSTSONAME!$INSTSONAME$ac_delim -RUNSHARED!$RUNSHARED$ac_delim -LINKCC!$LINKCC$ac_delim -GNULD!$GNULD$ac_delim -RANLIB!$RANLIB$ac_delim -AR!$AR$ac_delim -ARFLAGS!$ARFLAGS$ac_delim -SVNVERSION!$SVNVERSION$ac_delim -INSTALL_PROGRAM!$INSTALL_PROGRAM$ac_delim -INSTALL_SCRIPT!$INSTALL_SCRIPT$ac_delim -INSTALL_DATA!$INSTALL_DATA$ac_delim -LN!$LN$ac_delim -OPT!$OPT$ac_delim -BASECFLAGS!$BASECFLAGS$ac_delim -UNIVERSAL_ARCH_FLAGS!$UNIVERSAL_ARCH_FLAGS$ac_delim -OTHER_LIBTOOL_OPT!$OTHER_LIBTOOL_OPT$ac_delim -LIBTOOL_CRUFT!$LIBTOOL_CRUFT$ac_delim -SO!$SO$ac_delim -LDSHARED!$LDSHARED$ac_delim -_ACEOF - - if test `sed -n "s/.*$ac_delim\$/X/p" conf$$subs.sed | grep -c X` = 97; then - break - elif $ac_last_try; then - { { echo "$as_me:$LINENO: error: could not make $CONFIG_STATUS" >&5 -echo "$as_me: error: could not make $CONFIG_STATUS" >&2;} - { (exit 1); exit 1; }; } - else - ac_delim="$ac_delim!$ac_delim _$ac_delim!! " - fi -done -ac_eof=`sed -n '/^CEOF[0-9]*$/s/CEOF/0/p' conf$$subs.sed` -if test -n "$ac_eof"; then - ac_eof=`echo "$ac_eof" | sort -nru | sed 1q` - ac_eof=`expr $ac_eof + 1` +ac_cr=`echo X | tr X '\015'` +# On cygwin, bash can eat \r inside `` if the user requested igncr. +# But we know of no other shell where ac_cr would be empty at this +# point, so we can use a bashism as a fallback. +if test "x$ac_cr" = x; then + eval ac_cr=\$\'\\r\' +fi +ac_cs_awk_cr=`$AWK 'BEGIN { print "a\rb" }' /dev/null` +if test "$ac_cs_awk_cr" = "a${ac_cr}b"; then + ac_cs_awk_cr='\r' +else + ac_cs_awk_cr=$ac_cr fi -cat >>$CONFIG_STATUS <<_ACEOF -cat >"\$tmp/subs-1.sed" <<\CEOF$ac_eof -/@[a-zA-Z_][a-zA-Z_0-9]*@/!b -_ACEOF -sed ' -s/[,\\&]/\\&/g; s/@/@|#_!!_#|/g -s/^/s,@/; s/!/@,|#_!!_#|/ -:n -t n -s/'"$ac_delim"'$/,g/; t -s/$/\\/; p -N; s/^.*\n//; s/[,\\&]/\\&/g; s/@/@|#_!!_#|/g; b n -' >>$CONFIG_STATUS >$CONFIG_STATUS <<_ACEOF -CEOF$ac_eof +echo 'BEGIN {' >"$tmp/subs1.awk" && _ACEOF +{ + echo "cat >conf$$subs.awk <<_ACEOF" && + echo "$ac_subst_vars" | sed 's/.*/&!$&$ac_delim/' && + echo "_ACEOF" +} >conf$$subs.sh || + as_fn_error "could not make $CONFIG_STATUS" "$LINENO" 5 +ac_delim_num=`echo "$ac_subst_vars" | grep -c '$'` ac_delim='%!_!# ' for ac_last_try in false false false false false :; do - cat >conf$$subs.sed <<_ACEOF -LDCXXSHARED!$LDCXXSHARED$ac_delim -BLDSHARED!$BLDSHARED$ac_delim -CCSHARED!$CCSHARED$ac_delim -LINKFORSHARED!$LINKFORSHARED$ac_delim -CFLAGSFORSHARED!$CFLAGSFORSHARED$ac_delim -SHLIBS!$SHLIBS$ac_delim -PKG_CONFIG!$PKG_CONFIG$ac_delim -LIBFFI_INCLUDEDIR!$LIBFFI_INCLUDEDIR$ac_delim -USE_SIGNAL_MODULE!$USE_SIGNAL_MODULE$ac_delim -SIGNAL_OBJS!$SIGNAL_OBJS$ac_delim -USE_THREAD_MODULE!$USE_THREAD_MODULE$ac_delim -LDLAST!$LDLAST$ac_delim -THREADOBJ!$THREADOBJ$ac_delim -DLINCLDIR!$DLINCLDIR$ac_delim -DYNLOADFILE!$DYNLOADFILE$ac_delim -MACHDEP_OBJS!$MACHDEP_OBJS$ac_delim -TRUE!$TRUE$ac_delim -LIBOBJS!$LIBOBJS$ac_delim -HAVE_GETHOSTBYNAME_R_6_ARG!$HAVE_GETHOSTBYNAME_R_6_ARG$ac_delim -HAVE_GETHOSTBYNAME_R_5_ARG!$HAVE_GETHOSTBYNAME_R_5_ARG$ac_delim -HAVE_GETHOSTBYNAME_R_3_ARG!$HAVE_GETHOSTBYNAME_R_3_ARG$ac_delim -HAVE_GETHOSTBYNAME_R!$HAVE_GETHOSTBYNAME_R$ac_delim -HAVE_GETHOSTBYNAME!$HAVE_GETHOSTBYNAME$ac_delim -LIBM!$LIBM$ac_delim -LIBC!$LIBC$ac_delim -UNICODE_OBJS!$UNICODE_OBJS$ac_delim -THREADHEADERS!$THREADHEADERS$ac_delim -SRCDIRS!$SRCDIRS$ac_delim -LTLIBOBJS!$LTLIBOBJS$ac_delim -_ACEOF + . ./conf$$subs.sh || + as_fn_error "could not make $CONFIG_STATUS" "$LINENO" 5 - if test `sed -n "s/.*$ac_delim\$/X/p" conf$$subs.sed | grep -c X` = 29; then + ac_delim_n=`sed -n "s/.*$ac_delim\$/X/p" conf$$subs.awk | grep -c X` + if test $ac_delim_n = $ac_delim_num; then break elif $ac_last_try; then - { { echo "$as_me:$LINENO: error: could not make $CONFIG_STATUS" >&5 -echo "$as_me: error: could not make $CONFIG_STATUS" >&2;} - { (exit 1); exit 1; }; } + as_fn_error "could not make $CONFIG_STATUS" "$LINENO" 5 else ac_delim="$ac_delim!$ac_delim _$ac_delim!! " fi done +rm -f conf$$subs.sh -ac_eof=`sed -n '/^CEOF[0-9]*$/s/CEOF/0/p' conf$$subs.sed` -if test -n "$ac_eof"; then - ac_eof=`echo "$ac_eof" | sort -nru | sed 1q` - ac_eof=`expr $ac_eof + 1` -fi - -cat >>$CONFIG_STATUS <<_ACEOF -cat >"\$tmp/subs-2.sed" <<\CEOF$ac_eof -/@[a-zA-Z_][a-zA-Z_0-9]*@/!b end -_ACEOF -sed ' -s/[,\\&]/\\&/g; s/@/@|#_!!_#|/g -s/^/s,@/; s/!/@,|#_!!_#|/ -:n -t n -s/'"$ac_delim"'$/,g/; t -s/$/\\/; p -N; s/^.*\n//; s/[,\\&]/\\&/g; s/@/@|#_!!_#|/g; b n -' >>$CONFIG_STATUS >$CONFIG_STATUS <<_ACEOF -:end -s/|#_!!_#|//g -CEOF$ac_eof +cat >>$CONFIG_STATUS <<_ACEOF || ac_write_fail=1 +cat >>"\$tmp/subs1.awk" <<\\_ACAWK && _ACEOF +sed -n ' +h +s/^/S["/; s/!.*/"]=/ +p +g +s/^[^!]*!// +:repl +t repl +s/'"$ac_delim"'$// +t delim +:nl +h +s/\(.\{148\}\)..*/\1/ +t more1 +s/["\\]/\\&/g; s/^/"/; s/$/\\n"\\/ +p +n +b repl +:more1 +s/["\\]/\\&/g; s/^/"/; s/$/"\\/ +p +g +s/.\{148\}// +t nl +:delim +h +s/\(.\{148\}\)..*/\1/ +t more2 +s/["\\]/\\&/g; s/^/"/; s/$/"/ +p +b +:more2 +s/["\\]/\\&/g; s/^/"/; s/$/"\\/ +p +g +s/.\{148\}// +t delim +' >$CONFIG_STATUS || ac_write_fail=1 +rm -f conf$$subs.awk +cat >>$CONFIG_STATUS <<_ACEOF || ac_write_fail=1 +_ACAWK +cat >>"\$tmp/subs1.awk" <<_ACAWK && + for (key in S) S_is_set[key] = 1 + FS = "" + +} +{ + line = $ 0 + nfields = split(line, field, "@") + substed = 0 + len = length(field[1]) + for (i = 2; i < nfields; i++) { + key = field[i] + keylen = length(key) + if (S_is_set[key]) { + value = S[key] + line = substr(line, 1, len) "" value "" substr(line, len + keylen + 3) + len += length(value) + length(field[++i]) + substed = 1 + } else + len += 1 + keylen + } + + print line +} +_ACAWK +_ACEOF +cat >>$CONFIG_STATUS <<\_ACEOF || ac_write_fail=1 +if sed "s/$ac_cr//" < /dev/null > /dev/null 2>&1; then + sed "s/$ac_cr\$//; s/$ac_cr/$ac_cs_awk_cr/g" +else + cat +fi < "$tmp/subs1.awk" > "$tmp/subs.awk" \ + || as_fn_error "could not setup config files machinery" "$LINENO" 5 +_ACEOF # VPATH may cause trouble with some makes, so we remove $(srcdir), # ${srcdir} and @srcdir@ from VPATH if srcdir is ".", strip leading and @@ -28691,20 +14593,128 @@ }' fi -cat >>$CONFIG_STATUS <<\_ACEOF +cat >>$CONFIG_STATUS <<\_ACEOF || ac_write_fail=1 fi # test -n "$CONFIG_FILES" +# Set up the scripts for CONFIG_HEADERS section. +# No need to generate them if there are no CONFIG_HEADERS. +# This happens for instance with `./config.status Makefile'. +if test -n "$CONFIG_HEADERS"; then +cat >"$tmp/defines.awk" <<\_ACAWK || +BEGIN { +_ACEOF + +# Transform confdefs.h into an awk script `defines.awk', embedded as +# here-document in config.status, that substitutes the proper values into +# config.h.in to produce config.h. + +# Create a delimiter string that does not exist in confdefs.h, to ease +# handling of long lines. +ac_delim='%!_!# ' +for ac_last_try in false false :; do + ac_t=`sed -n "/$ac_delim/p" confdefs.h` + if test -z "$ac_t"; then + break + elif $ac_last_try; then + as_fn_error "could not make $CONFIG_HEADERS" "$LINENO" 5 + else + ac_delim="$ac_delim!$ac_delim _$ac_delim!! " + fi +done + +# For the awk script, D is an array of macro values keyed by name, +# likewise P contains macro parameters if any. Preserve backslash +# newline sequences. + +ac_word_re=[_$as_cr_Letters][_$as_cr_alnum]* +sed -n ' +s/.\{148\}/&'"$ac_delim"'/g +t rset +:rset +s/^[ ]*#[ ]*define[ ][ ]*/ / +t def +d +:def +s/\\$// +t bsnl +s/["\\]/\\&/g +s/^ \('"$ac_word_re"'\)\(([^()]*)\)[ ]*\(.*\)/P["\1"]="\2"\ +D["\1"]=" \3"/p +s/^ \('"$ac_word_re"'\)[ ]*\(.*\)/D["\1"]=" \2"/p +d +:bsnl +s/["\\]/\\&/g +s/^ \('"$ac_word_re"'\)\(([^()]*)\)[ ]*\(.*\)/P["\1"]="\2"\ +D["\1"]=" \3\\\\\\n"\\/p +t cont +s/^ \('"$ac_word_re"'\)[ ]*\(.*\)/D["\1"]=" \2\\\\\\n"\\/p +t cont +d +:cont +n +s/.\{148\}/&'"$ac_delim"'/g +t clear +:clear +s/\\$// +t bsnlc +s/["\\]/\\&/g; s/^/"/; s/$/"/p +d +:bsnlc +s/["\\]/\\&/g; s/^/"/; s/$/\\\\\\n"\\/p +b cont +' >$CONFIG_STATUS || ac_write_fail=1 + +cat >>$CONFIG_STATUS <<_ACEOF || ac_write_fail=1 + for (key in D) D_is_set[key] = 1 + FS = "" +} +/^[\t ]*#[\t ]*(define|undef)[\t ]+$ac_word_re([\t (]|\$)/ { + line = \$ 0 + split(line, arg, " ") + if (arg[1] == "#") { + defundef = arg[2] + mac1 = arg[3] + } else { + defundef = substr(arg[1], 2) + mac1 = arg[2] + } + split(mac1, mac2, "(") #) + macro = mac2[1] + prefix = substr(line, 1, index(line, defundef) - 1) + if (D_is_set[macro]) { + # Preserve the white space surrounding the "#". + print prefix "define", macro P[macro] D[macro] + next + } else { + # Replace #undef with comments. This is necessary, for example, + # in the case of _POSIX_SOURCE, which is predefined and required + # on some systems where configure will not decide to define it. + if (defundef == "undef") { + print "/*", prefix defundef, macro, "*/" + next + } + } +} +{ print } +_ACAWK +_ACEOF +cat >>$CONFIG_STATUS <<\_ACEOF || ac_write_fail=1 + as_fn_error "could not setup config headers machinery" "$LINENO" 5 +fi # test -n "$CONFIG_HEADERS" + -for ac_tag in :F $CONFIG_FILES :H $CONFIG_HEADERS +eval set X " :F $CONFIG_FILES :H $CONFIG_HEADERS " +shift +for ac_tag do case $ac_tag in :[FHLC]) ac_mode=$ac_tag; continue;; esac case $ac_mode$ac_tag in :[FHL]*:*);; - :L* | :C*:*) { { echo "$as_me:$LINENO: error: Invalid tag $ac_tag." >&5 -echo "$as_me: error: Invalid tag $ac_tag." >&2;} - { (exit 1); exit 1; }; };; + :L* | :C*:*) as_fn_error "invalid tag \`$ac_tag'" "$LINENO" 5;; :[FH]-) ac_tag=-:-;; :[FH]*) ac_tag=$ac_tag:$ac_tag.in;; esac @@ -28732,26 +14742,34 @@ [\\/$]*) false;; *) test -f "$srcdir/$ac_f" && ac_f="$srcdir/$ac_f";; esac || - { { echo "$as_me:$LINENO: error: cannot find input file: $ac_f" >&5 -echo "$as_me: error: cannot find input file: $ac_f" >&2;} - { (exit 1); exit 1; }; };; + as_fn_error "cannot find input file: \`$ac_f'" "$LINENO" 5;; esac - ac_file_inputs="$ac_file_inputs $ac_f" + case $ac_f in *\'*) ac_f=`$as_echo "$ac_f" | sed "s/'/'\\\\\\\\''/g"`;; esac + as_fn_append ac_file_inputs " '$ac_f'" done # Let's still pretend it is `configure' which instantiates (i.e., don't # use $as_me), people would be surprised to read: # /* config.h. Generated by config.status. */ - configure_input="Generated from "`IFS=: - echo $* | sed 's|^[^:]*/||;s|:[^:]*/|, |g'`" by configure." + configure_input='Generated from '` + $as_echo "$*" | sed 's|^[^:]*/||;s|:[^:]*/|, |g' + `' by configure.' if test x"$ac_file" != x-; then configure_input="$ac_file. $configure_input" - { echo "$as_me:$LINENO: creating $ac_file" >&5 -echo "$as_me: creating $ac_file" >&6;} + { $as_echo "$as_me:${as_lineno-$LINENO}: creating $ac_file" >&5 +$as_echo "$as_me: creating $ac_file" >&6;} fi + # Neutralize special characters interpreted by sed in replacement strings. + case $configure_input in #( + *\&* | *\|* | *\\* ) + ac_sed_conf_input=`$as_echo "$configure_input" | + sed 's/[\\\\&|]/\\\\&/g'`;; #( + *) ac_sed_conf_input=$configure_input;; + esac case $ac_tag in - *:-:* | *:-) cat >"$tmp/stdin";; + *:-:* | *:-) cat >"$tmp/stdin" \ + || as_fn_error "could not create $ac_file" "$LINENO" 5 ;; esac ;; esac @@ -28761,42 +14779,7 @@ X"$ac_file" : 'X\(//\)[^/]' \| \ X"$ac_file" : 'X\(//\)$' \| \ X"$ac_file" : 'X\(/\)' \| . 2>/dev/null || -echo X"$ac_file" | - sed '/^X\(.*[^/]\)\/\/*[^/][^/]*\/*$/{ - s//\1/ - q - } - /^X\(\/\/\)[^/].*/{ - s//\1/ - q - } - /^X\(\/\/\)$/{ - s//\1/ - q - } - /^X\(\/\).*/{ - s//\1/ - q - } - s/.*/./; q'` - { as_dir="$ac_dir" - case $as_dir in #( - -*) as_dir=./$as_dir;; - esac - test -d "$as_dir" || { $as_mkdir_p && mkdir -p "$as_dir"; } || { - as_dirs= - while :; do - case $as_dir in #( - *\'*) as_qdir=`echo "$as_dir" | sed "s/'/'\\\\\\\\''/g"`;; #( - *) as_qdir=$as_dir;; - esac - as_dirs="'$as_qdir' $as_dirs" - as_dir=`$as_dirname -- "$as_dir" || -$as_expr X"$as_dir" : 'X\(.*[^/]\)//*[^/][^/]*/*$' \| \ - X"$as_dir" : 'X\(//\)[^/]' \| \ - X"$as_dir" : 'X\(//\)$' \| \ - X"$as_dir" : 'X\(/\)' \| . 2>/dev/null || -echo X"$as_dir" | +$as_echo X"$ac_file" | sed '/^X\(.*[^/]\)\/\/*[^/][^/]*\/*$/{ s//\1/ q @@ -28814,20 +14797,15 @@ q } s/.*/./; q'` - test -d "$as_dir" && break - done - test -z "$as_dirs" || eval "mkdir $as_dirs" - } || test -d "$as_dir" || { { echo "$as_me:$LINENO: error: cannot create directory $as_dir" >&5 -echo "$as_me: error: cannot create directory $as_dir" >&2;} - { (exit 1); exit 1; }; }; } + as_dir="$ac_dir"; as_fn_mkdir_p ac_builddir=. case "$ac_dir" in .) ac_dir_suffix= ac_top_builddir_sub=. ac_top_build_prefix= ;; *) - ac_dir_suffix=/`echo "$ac_dir" | sed 's,^\.[\\/],,'` + ac_dir_suffix=/`$as_echo "$ac_dir" | sed 's|^\.[\\/]||'` # A ".." for each directory in $ac_dir_suffix. - ac_top_builddir_sub=`echo "$ac_dir_suffix" | sed 's,/[^\\/]*,/..,g;s,/,,'` + ac_top_builddir_sub=`$as_echo "$ac_dir_suffix" | sed 's|/[^\\/]*|/..|g;s|/||'` case $ac_top_builddir_sub in "") ac_top_builddir_sub=. ac_top_build_prefix= ;; *) ac_top_build_prefix=$ac_top_builddir_sub/ ;; @@ -28867,12 +14845,12 @@ esac _ACEOF -cat >>$CONFIG_STATUS <<\_ACEOF +cat >>$CONFIG_STATUS <<\_ACEOF || ac_write_fail=1 # If the template does not know about datarootdir, expand it. # FIXME: This hack should be removed a few years after 2.60. ac_datarootdir_hack=; ac_datarootdir_seen= - -case `sed -n '/datarootdir/ { +ac_sed_dataroot=' +/datarootdir/ { p q } @@ -28880,36 +14858,37 @@ /@docdir@/p /@infodir@/p /@localedir@/p -/@mandir@/p -' $ac_file_inputs` in +/@mandir@/p' +case `eval "sed -n \"\$ac_sed_dataroot\" $ac_file_inputs"` in *datarootdir*) ac_datarootdir_seen=yes;; *@datadir@*|*@docdir@*|*@infodir@*|*@localedir@*|*@mandir@*) - { echo "$as_me:$LINENO: WARNING: $ac_file_inputs seems to ignore the --datarootdir setting" >&5 -echo "$as_me: WARNING: $ac_file_inputs seems to ignore the --datarootdir setting" >&2;} + { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: $ac_file_inputs seems to ignore the --datarootdir setting" >&5 +$as_echo "$as_me: WARNING: $ac_file_inputs seems to ignore the --datarootdir setting" >&2;} _ACEOF -cat >>$CONFIG_STATUS <<_ACEOF +cat >>$CONFIG_STATUS <<_ACEOF || ac_write_fail=1 ac_datarootdir_hack=' s&@datadir@&$datadir&g s&@docdir@&$docdir&g s&@infodir@&$infodir&g s&@localedir@&$localedir&g s&@mandir@&$mandir&g - s&\\\${datarootdir}&$datarootdir&g' ;; + s&\\\${datarootdir}&$datarootdir&g' ;; esac _ACEOF # Neutralize VPATH when `$srcdir' = `.'. # Shell code in configure.ac might set extrasub. # FIXME: do we really want to maintain this feature? -cat >>$CONFIG_STATUS <<_ACEOF - sed "$ac_vpsub +cat >>$CONFIG_STATUS <<_ACEOF || ac_write_fail=1 +ac_sed_extra="$ac_vpsub $extrasub _ACEOF -cat >>$CONFIG_STATUS <<\_ACEOF +cat >>$CONFIG_STATUS <<\_ACEOF || ac_write_fail=1 :t /@[a-zA-Z_][a-zA-Z_0-9]*@/!b -s&@configure_input@&$configure_input&;t t +s|@configure_input@|$ac_sed_conf_input|;t t s&@top_builddir@&$ac_top_builddir_sub&;t t +s&@top_build_prefix@&$ac_top_build_prefix&;t t s&@srcdir@&$ac_srcdir&;t t s&@abs_srcdir@&$ac_abs_srcdir&;t t s&@top_srcdir@&$ac_top_srcdir&;t t @@ -28919,119 +14898,48 @@ s&@abs_top_builddir@&$ac_abs_top_builddir&;t t s&@INSTALL@&$ac_INSTALL&;t t $ac_datarootdir_hack -" $ac_file_inputs | sed -f "$tmp/subs-1.sed" | sed -f "$tmp/subs-2.sed" >$tmp/out +" +eval sed \"\$ac_sed_extra\" "$ac_file_inputs" | $AWK -f "$tmp/subs.awk" >$tmp/out \ + || as_fn_error "could not create $ac_file" "$LINENO" 5 test -z "$ac_datarootdir_hack$ac_datarootdir_seen" && { ac_out=`sed -n '/\${datarootdir}/p' "$tmp/out"`; test -n "$ac_out"; } && { ac_out=`sed -n '/^[ ]*datarootdir[ ]*:*=/p' "$tmp/out"`; test -z "$ac_out"; } && - { echo "$as_me:$LINENO: WARNING: $ac_file contains a reference to the variable \`datarootdir' + { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: $ac_file contains a reference to the variable \`datarootdir' which seems to be undefined. Please make sure it is defined." >&5 -echo "$as_me: WARNING: $ac_file contains a reference to the variable \`datarootdir' +$as_echo "$as_me: WARNING: $ac_file contains a reference to the variable \`datarootdir' which seems to be undefined. Please make sure it is defined." >&2;} rm -f "$tmp/stdin" case $ac_file in - -) cat "$tmp/out"; rm -f "$tmp/out";; - *) rm -f "$ac_file"; mv "$tmp/out" $ac_file;; - esac + -) cat "$tmp/out" && rm -f "$tmp/out";; + *) rm -f "$ac_file" && mv "$tmp/out" "$ac_file";; + esac \ + || as_fn_error "could not create $ac_file" "$LINENO" 5 ;; :H) # # CONFIG_HEADER # -_ACEOF - -# Transform confdefs.h into a sed script `conftest.defines', that -# substitutes the proper values into config.h.in to produce config.h. -rm -f conftest.defines conftest.tail -# First, append a space to every undef/define line, to ease matching. -echo 's/$/ /' >conftest.defines -# Then, protect against being on the right side of a sed subst, or in -# an unquoted here document, in config.status. If some macros were -# called several times there might be several #defines for the same -# symbol, which is useless. But do not sort them, since the last -# AC_DEFINE must be honored. -ac_word_re=[_$as_cr_Letters][_$as_cr_alnum]* -# These sed commands are passed to sed as "A NAME B PARAMS C VALUE D", where -# NAME is the cpp macro being defined, VALUE is the value it is being given. -# PARAMS is the parameter list in the macro definition--in most cases, it's -# just an empty string. -ac_dA='s,^\\([ #]*\\)[^ ]*\\([ ]*' -ac_dB='\\)[ (].*,\\1define\\2' -ac_dC=' ' -ac_dD=' ,' - -uniq confdefs.h | - sed -n ' - t rset - :rset - s/^[ ]*#[ ]*define[ ][ ]*// - t ok - d - :ok - s/[\\&,]/\\&/g - s/^\('"$ac_word_re"'\)\(([^()]*)\)[ ]*\(.*\)/ '"$ac_dA"'\1'"$ac_dB"'\2'"${ac_dC}"'\3'"$ac_dD"'/p - s/^\('"$ac_word_re"'\)[ ]*\(.*\)/'"$ac_dA"'\1'"$ac_dB$ac_dC"'\2'"$ac_dD"'/p - ' >>conftest.defines - -# Remove the space that was appended to ease matching. -# Then replace #undef with comments. This is necessary, for -# example, in the case of _POSIX_SOURCE, which is predefined and required -# on some systems where configure will not decide to define it. -# (The regexp can be short, since the line contains either #define or #undef.) -echo 's/ $// -s,^[ #]*u.*,/* & */,' >>conftest.defines - -# Break up conftest.defines: -ac_max_sed_lines=50 - -# First sed command is: sed -f defines.sed $ac_file_inputs >"$tmp/out1" -# Second one is: sed -f defines.sed "$tmp/out1" >"$tmp/out2" -# Third one will be: sed -f defines.sed "$tmp/out2" >"$tmp/out1" -# et cetera. -ac_in='$ac_file_inputs' -ac_out='"$tmp/out1"' -ac_nxt='"$tmp/out2"' - -while : -do - # Write a here document: - cat >>$CONFIG_STATUS <<_ACEOF - # First, check the format of the line: - cat >"\$tmp/defines.sed" <<\\CEOF -/^[ ]*#[ ]*undef[ ][ ]*$ac_word_re[ ]*\$/b def -/^[ ]*#[ ]*define[ ][ ]*$ac_word_re[( ]/b def -b -:def -_ACEOF - sed ${ac_max_sed_lines}q conftest.defines >>$CONFIG_STATUS - echo 'CEOF - sed -f "$tmp/defines.sed"' "$ac_in >$ac_out" >>$CONFIG_STATUS - ac_in=$ac_out; ac_out=$ac_nxt; ac_nxt=$ac_in - sed 1,${ac_max_sed_lines}d conftest.defines >conftest.tail - grep . conftest.tail >/dev/null || break - rm -f conftest.defines - mv conftest.tail conftest.defines -done -rm -f conftest.defines conftest.tail - -echo "ac_result=$ac_in" >>$CONFIG_STATUS -cat >>$CONFIG_STATUS <<\_ACEOF if test x"$ac_file" != x-; then - echo "/* $configure_input */" >"$tmp/config.h" - cat "$ac_result" >>"$tmp/config.h" - if diff $ac_file "$tmp/config.h" >/dev/null 2>&1; then - { echo "$as_me:$LINENO: $ac_file is unchanged" >&5 -echo "$as_me: $ac_file is unchanged" >&6;} + { + $as_echo "/* $configure_input */" \ + && eval '$AWK -f "$tmp/defines.awk"' "$ac_file_inputs" + } >"$tmp/config.h" \ + || as_fn_error "could not create $ac_file" "$LINENO" 5 + if diff "$ac_file" "$tmp/config.h" >/dev/null 2>&1; then + { $as_echo "$as_me:${as_lineno-$LINENO}: $ac_file is unchanged" >&5 +$as_echo "$as_me: $ac_file is unchanged" >&6;} else - rm -f $ac_file - mv "$tmp/config.h" $ac_file + rm -f "$ac_file" + mv "$tmp/config.h" "$ac_file" \ + || as_fn_error "could not create $ac_file" "$LINENO" 5 fi else - echo "/* $configure_input */" - cat "$ac_result" + $as_echo "/* $configure_input */" \ + && eval '$AWK -f "$tmp/defines.awk"' "$ac_file_inputs" \ + || as_fn_error "could not create -" "$LINENO" 5 fi - rm -f "$tmp/out12" ;; @@ -29040,11 +14948,13 @@ done # for ac_tag -{ (exit 0); exit 0; } +as_fn_exit 0 _ACEOF -chmod +x $CONFIG_STATUS ac_clean_files=$ac_clean_files_save +test $ac_write_fail = 0 || + as_fn_error "write failure creating $CONFIG_STATUS" "$LINENO" 5 + # configure is writing to config.log, and then calls config.status. # config.status does its own redirection, appending to config.log. @@ -29064,7 +14974,11 @@ exec 5>>config.log # Use ||, not &&, to avoid exiting from the if with $? = 1, which # would make configure fail if this is the last instruction. - $ac_cs_success || { (exit 1); exit 1; } + $ac_cs_success || as_fn_exit $? +fi +if test -n "$ac_unrecognized_opts" && test "$enable_option_checking" != no; then + { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: unrecognized options: $ac_unrecognized_opts" >&5 +$as_echo "$as_me: WARNING: unrecognized options: $ac_unrecognized_opts" >&2;} fi @@ -29087,12 +15001,12 @@ case $ac_sys_system in BeOS) - { echo "$as_me:$LINENO: WARNING: + { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: Support for BeOS is deprecated as of Python 2.6. See PEP 11 for the gory details. " >&5 -echo "$as_me: WARNING: +$as_echo "$as_me: WARNING: Support for BeOS is deprecated as of Python 2.6. See PEP 11 for the gory details. Modified: python/trunk/configure.in ============================================================================== --- python/trunk/configure.in (original) +++ python/trunk/configure.in Sat May 8 12:00:28 2010 @@ -1,7 +1,6 @@ dnl *********************************************** dnl * Please run autoreconf to test your changes! * dnl *********************************************** -dnl NOTE: autoconf 2.64 doesn't seem to work (use 2.61). # Set VERSION so we only need to edit in one place (i.e., here) m4_define(PYTHON_VERSION, 2.7) @@ -13,7 +12,7 @@ [], [m4_fatal([Autoconf version $1 is required for Python], 63)]) ]) -version_required(2.61) +version_required(2.65) AC_REVISION($Revision$) AC_INIT(python, PYTHON_VERSION, http://bugs.python.org/) From python-checkins at python.org Sat May 8 12:14:46 2010 From: python-checkins at python.org (matthias.klose) Date: Sat, 8 May 2010 12:14:46 +0200 (CEST) Subject: [Python-checkins] r80965 - in python/trunk: configure configure.in Message-ID: <20100508101446.E7104EE982@mail.python.org> Author: matthias.klose Date: Sat May 8 12:14:46 2010 New Revision: 80965 Log: - configure.in: Replace AC_HELP_STRING with AS_HELP_STRING Modified: python/trunk/configure python/trunk/configure.in Modified: python/trunk/configure ============================================================================== --- python/trunk/configure (original) +++ python/trunk/configure Sat May 8 12:14:46 2010 @@ -1,5 +1,5 @@ #! /bin/sh -# From configure.in Revision: 80832 . +# From configure.in Revision: 80964 . # Guess values for system-dependent variables and create Makefiles. # Generated by GNU Autoconf 2.65 for python 2.7. # @@ -2963,8 +2963,8 @@ ##AC_ARG_WITH(dyld, -## AC_HELP_STRING(--with-dyld, -## Use (OpenStep|Rhapsody) dynamic linker)) +## AS_HELP_STRING([--with-dyld], +## [Use (OpenStep|Rhapsody) dynamic linker])) ## # Set name for machine-dependent library files Modified: python/trunk/configure.in ============================================================================== --- python/trunk/configure.in (original) +++ python/trunk/configure.in Sat May 8 12:14:46 2010 @@ -87,7 +87,7 @@ AC_MSG_CHECKING([for --enable-universalsdk]) AC_ARG_ENABLE(universalsdk, - AC_HELP_STRING([--enable-universalsdk@<:@=SDKDIR@:>@], [Build against Mac OS X 10.4u SDK (ppc/i386)]), + AS_HELP_STRING([--enable-universalsdk@<:@=SDKDIR@:>@], [Build against Mac OS X 10.4u SDK (ppc/i386)]), [ case $enableval in yes) @@ -130,7 +130,7 @@ AC_SUBST(LIPO_32BIT_FLAGS) AC_MSG_CHECKING(for --with-universal-archs) AC_ARG_WITH(universal-archs, - AC_HELP_STRING([--with-universal-archs=ARCH], [select architectures for universal build ("32-bit", "64-bit", "3-way", "intel" or "all")]), + AS_HELP_STRING([--with-universal-archs=ARCH], [select architectures for universal build ("32-bit", "64-bit", "3-way", "intel" or "all")]), [ AC_MSG_RESULT($withval) UNIVERSAL_ARCHS="$withval" @@ -147,7 +147,7 @@ AC_ARG_WITH(framework-name, - AC_HELP_STRING([--with-framework-name=FRAMEWORK], + AS_HELP_STRING([--with-framework-name=FRAMEWORK], [specify an alternate name of the framework built with --enable-framework]), [ if test "${enable_framework}"; then @@ -165,7 +165,7 @@ ]) dnl quadrigraphs "@<:@" and "@:>@" produce "[" and "]" in the output AC_ARG_ENABLE(framework, - AC_HELP_STRING([--enable-framework@<:@=INSTALLDIR@:>@], [Build (MacOSX|Darwin) framework]), + AS_HELP_STRING([--enable-framework@<:@=INSTALLDIR@:>@], [Build (MacOSX|Darwin) framework]), [ case $enableval in yes) @@ -278,8 +278,8 @@ AC_SUBST(FRAMEWORKINSTALLAPPSPREFIX) ##AC_ARG_WITH(dyld, -## AC_HELP_STRING(--with-dyld, -## Use (OpenStep|Rhapsody) dynamic linker)) +## AS_HELP_STRING([--with-dyld], +## [Use (OpenStep|Rhapsody) dynamic linker])) ## # Set name for machine-dependent library files AC_SUBST(MACHDEP) @@ -485,7 +485,7 @@ # on that fiddles with OPT and BASECFLAGS? AC_MSG_CHECKING(for --without-gcc) AC_ARG_WITH(gcc, - AC_HELP_STRING(--without-gcc,never use gcc), + AS_HELP_STRING([--without-gcc], [never use gcc]), [ case $withval in no) CC=${CC:-cc} @@ -543,7 +543,7 @@ AC_SUBST(MAINCC) AC_MSG_CHECKING(for --with-cxx-main=) AC_ARG_WITH(cxx_main, - AC_HELP_STRING([--with-cxx-main=], + AS_HELP_STRING([--with-cxx-main=], [compile main() and link python executable with C++ compiler]), [ @@ -608,7 +608,7 @@ AC_EXEEXT AC_MSG_CHECKING(for --with-suffix) AC_ARG_WITH(suffix, - AC_HELP_STRING(--with-suffix=.exe, set executable suffix), + AS_HELP_STRING([--with-suffix=.exe], [set executable suffix]), [ case $withval in no) EXEEXT=;; @@ -736,7 +736,7 @@ AC_MSG_CHECKING(for --enable-shared) AC_ARG_ENABLE(shared, - AC_HELP_STRING(--enable-shared, disable/enable building shared python library)) + AS_HELP_STRING([--enable-shared], [disable/enable building shared python library])) if test -z "$enable_shared" then @@ -751,7 +751,7 @@ AC_MSG_CHECKING(for --enable-profiling) AC_ARG_ENABLE(profiling, - AC_HELP_STRING(--enable-profiling, enable C-level code profiling), + AS_HELP_STRING([--enable-profiling], [enable C-level code profiling]), [ac_save_cc="$CC" CC="$CC -pg" AC_TRY_RUN([int main() { return 0; }], @@ -897,7 +897,7 @@ # Check for --with-pydebug AC_MSG_CHECKING(for --with-pydebug) AC_ARG_WITH(pydebug, - AC_HELP_STRING(--with-pydebug, build with Py_DEBUG defined), + AS_HELP_STRING([--with-pydebug], [build with Py_DEBUG defined]), [ if test "$withval" != no then @@ -1601,7 +1601,7 @@ AC_MSG_CHECKING(for --enable-toolbox-glue) AC_ARG_ENABLE(toolbox-glue, - AC_HELP_STRING([--enable-toolbox-glue], [disable/enable MacOSX glue code for extensions])) + AS_HELP_STRING([--enable-toolbox-glue], [disable/enable MacOSX glue code for extensions])) if test -z "$enable_toolbox_glue" then @@ -2090,7 +2090,7 @@ AC_MSG_CHECKING(for --with-libs) AC_ARG_WITH(libs, - AC_HELP_STRING([--with-libs='lib1 ...'], [link against additional libs]), + AS_HELP_STRING([--with-libs='lib1 ...'], [link against additional libs]), [ AC_MSG_RESULT($withval) LIBS="$withval $LIBS" @@ -2102,14 +2102,14 @@ # Check for use of the system expat library AC_MSG_CHECKING(for --with-system-expat) AC_ARG_WITH(system_expat, - AC_HELP_STRING([--with-system-expat], [build pyexpat module using an installed expat library])) + AS_HELP_STRING([--with-system-expat], [build pyexpat module using an installed expat library])) AC_MSG_RESULT($with_system_expat) # Check for use of the system libffi library AC_MSG_CHECKING(for --with-system-ffi) AC_ARG_WITH(system_ffi, - AC_HELP_STRING([--with-system-ffi], [build _ctypes module using an installed ffi library])) + AS_HELP_STRING([--with-system-ffi], [build _ctypes module using an installed ffi library])) if test "$with_system_ffi" = "yes" && test -n "$PKG_CONFIG"; then LIBFFI_INCLUDEDIR="`"$PKG_CONFIG" libffi --cflags-only-I 2>/dev/null | sed -e 's/^-I//;s/ *$//'`" @@ -2123,7 +2123,7 @@ # Check for --with-dbmliborder AC_MSG_CHECKING(for --with-dbmliborder) AC_ARG_WITH(dbmliborder, - AC_HELP_STRING([--with-dbmliborder=db1:db2:...], [order to check db backends for dbm. Valid value is a colon separated string with the backend names `ndbm', `gdbm' and `bdb'.]), + AS_HELP_STRING([--with-dbmliborder=db1:db2:...], [order to check db backends for dbm. Valid value is a colon separated string with the backend names `ndbm', `gdbm' and `bdb'.]), [ if test x$with_dbmliborder = xyes then @@ -2143,7 +2143,7 @@ AC_SUBST(SIGNAL_OBJS) AC_MSG_CHECKING(for --with-signal-module) AC_ARG_WITH(signal-module, - AC_HELP_STRING([--with-signal-module], [disable/enable signal module])) + AS_HELP_STRING([--with-signal-module], [disable/enable signal module])) if test -z "$with_signal_module" then with_signal_module="yes" @@ -2165,7 +2165,7 @@ AC_MSG_CHECKING(for --with-dec-threads) AC_SUBST(LDLAST) AC_ARG_WITH(dec-threads, - AC_HELP_STRING([--with-dec-threads], [use DEC Alpha/OSF1 thread-safe libraries]), + AS_HELP_STRING([--with-dec-threads], [use DEC Alpha/OSF1 thread-safe libraries]), [ AC_MSG_RESULT($withval) LDLAST=-threads @@ -2185,12 +2185,12 @@ AC_MSG_CHECKING(for --with-threads) dnl quadrigraphs "@<:@" and "@:>@" produce "[" and "]" in the output AC_ARG_WITH(threads, - AC_HELP_STRING([--with(out)-threads@<:@=DIRECTORY@:>@], [disable/enable thread support])) + AS_HELP_STRING([--with(out)-threads@<:@=DIRECTORY@:>@], [disable/enable thread support])) # --with-thread is deprecated, but check for it anyway dnl quadrigraphs "@<:@" and "@:>@" produce "[" and "]" in the output AC_ARG_WITH(thread, - AC_HELP_STRING([--with(out)-thread@<:@=DIRECTORY@:>@], [deprecated; use --with(out)-threads]), + AS_HELP_STRING([--with(out)-thread@<:@=DIRECTORY@:>@], [deprecated; use --with(out)-threads]), [with_threads=$with_thread]) if test -z "$with_threads" @@ -2271,7 +2271,7 @@ THREADOBJ="Python/thread.o"],[ AC_MSG_CHECKING(for --with-pth) AC_ARG_WITH([pth], - AC_HELP_STRING([--with-pth], [use GNU pth threading libraries]), + AS_HELP_STRING([--with-pth], [use GNU pth threading libraries]), [AC_MSG_RESULT($withval) AC_DEFINE([WITH_THREAD]) AC_DEFINE([HAVE_PTH], 1, @@ -2576,7 +2576,7 @@ # Check for --with-doc-strings AC_MSG_CHECKING(for --with-doc-strings) AC_ARG_WITH(doc-strings, - AC_HELP_STRING([--with(out)-doc-strings], [disable/enable documentation strings])) + AS_HELP_STRING([--with(out)-doc-strings], [disable/enable documentation strings])) if test -z "$with_doc_strings" then with_doc_strings="yes" @@ -2591,7 +2591,7 @@ # Check for Python-specific malloc support AC_MSG_CHECKING(for --with-tsc) AC_ARG_WITH(tsc, - AC_HELP_STRING([--with(out)-tsc],[enable/disable timestamp counter profile]),[ + AS_HELP_STRING([--with(out)-tsc],[enable/disable timestamp counter profile]),[ if test "$withval" != no then AC_DEFINE(WITH_TSC, 1, @@ -2604,7 +2604,7 @@ # Check for Python-specific malloc support AC_MSG_CHECKING(for --with-pymalloc) AC_ARG_WITH(pymalloc, - AC_HELP_STRING([--with(out)-pymalloc], [disable/enable specialized mallocs])) + AS_HELP_STRING([--with(out)-pymalloc], [disable/enable specialized mallocs])) if test -z "$with_pymalloc" then with_pymalloc="yes" @@ -2619,7 +2619,7 @@ # Check for Valgrind support AC_MSG_CHECKING([for --with-valgrind]) AC_ARG_WITH([valgrind], - AC_HELP_STRING([--with-valgrind], [Enable Valgrind support]),, + AS_HELP_STRING([--with-valgrind], [Enable Valgrind support]),, with_valgrind=no) AC_MSG_RESULT([$with_valgrind]) if test "$with_valgrind" != no; then @@ -2632,7 +2632,7 @@ # Check for --with-wctype-functions AC_MSG_CHECKING(for --with-wctype-functions) AC_ARG_WITH(wctype-functions, - AC_HELP_STRING([--with-wctype-functions], [use wctype.h functions]), + AS_HELP_STRING([--with-wctype-functions], [use wctype.h functions]), [ if test "$withval" != no then @@ -3350,7 +3350,7 @@ # Check for --with-fpectl AC_MSG_CHECKING(for --with-fpectl) AC_ARG_WITH(fpectl, - AC_HELP_STRING([--with-fpectl], [enable SIGFPE catching]), + AS_HELP_STRING([--with-fpectl], [enable SIGFPE catching]), [ if test "$withval" != no then @@ -3370,7 +3370,7 @@ esac AC_MSG_CHECKING(for --with-libm=STRING) AC_ARG_WITH(libm, - AC_HELP_STRING([--with-libm=STRING], [math library]), + AS_HELP_STRING([--with-libm=STRING], [math library]), [ if test "$withval" = no then LIBM= @@ -3386,7 +3386,7 @@ AC_SUBST(LIBC) AC_MSG_CHECKING(for --with-libc=STRING) AC_ARG_WITH(libc, - AC_HELP_STRING([--with-libc=STRING], [C library]), + AS_HELP_STRING([--with-libc=STRING], [C library]), [ if test "$withval" = no then LIBC= @@ -3651,7 +3651,7 @@ # determine what size digit to use for Python's longs AC_MSG_CHECKING([digit size for Python's longs]) AC_ARG_ENABLE(big-digits, -AC_HELP_STRING([--enable-big-digits@<:@=BITS@:>@],[use big digits for Python longs [[BITS=30]]]), +AS_HELP_STRING([--enable-big-digits@<:@=BITS@:>@],[use big digits for Python longs [[BITS=30]]]), [case $enable_big_digits in yes) enable_big_digits=30 ;; @@ -3717,7 +3717,7 @@ AC_MSG_CHECKING(what type to use for unicode) dnl quadrigraphs "@<:@" and "@:>@" produce "[" and "]" in the output AC_ARG_ENABLE(unicode, - AC_HELP_STRING([--enable-unicode@<:@=ucs@<:@24@:>@@:>@], [Enable Unicode strings (default is yes)]), + AS_HELP_STRING([--enable-unicode@<:@=ucs@<:@24@:>@@:>@], [Enable Unicode strings (default is yes)]), [], [enable_unicode=yes]) From python-checkins at python.org Sat May 8 12:17:27 2010 From: python-checkins at python.org (matthias.klose) Date: Sat, 8 May 2010 12:17:27 +0200 (CEST) Subject: [Python-checkins] r80966 - in python/trunk: configure configure.in Message-ID: <20100508101727.98D87FD3D@mail.python.org> Author: matthias.klose Date: Sat May 8 12:17:27 2010 New Revision: 80966 Log: configure.in: s/AC_AIX/AC_USE_SYSTEM_EXTENSIONS/ Modified: python/trunk/configure python/trunk/configure.in Modified: python/trunk/configure ============================================================================== --- python/trunk/configure (original) +++ python/trunk/configure Sat May 8 12:17:27 2010 @@ -1,5 +1,5 @@ #! /bin/sh -# From configure.in Revision: 80964 . +# From configure.in Revision: 80965 . # Guess values for system-dependent variables and create Makefiles. # Generated by GNU Autoconf 2.65 for python 2.7. # @@ -4685,7 +4685,6 @@ - # Check for unsupported systems case $ac_sys_system/$ac_sys_release in atheos*|Linux*/1*) Modified: python/trunk/configure.in ============================================================================== --- python/trunk/configure.in (original) +++ python/trunk/configure.in Sat May 8 12:17:27 2010 @@ -595,7 +595,7 @@ # checks for UNIX variants that set C preprocessor variables -AC_AIX +AC_USE_SYSTEM_EXTENSIONS # Check for unsupported systems case $ac_sys_system/$ac_sys_release in From python-checkins at python.org Sat May 8 12:29:06 2010 From: python-checkins at python.org (ronald.oussoren) Date: Sat, 8 May 2010 12:29:06 +0200 (CEST) Subject: [Python-checkins] r80967 - in python/trunk: Lib/site.py Lib/sysconfig.py Misc/NEWS Message-ID: <20100508102906.AE401EE982@mail.python.org> Author: ronald.oussoren Date: Sat May 8 12:29:06 2010 New Revision: 80967 Log: Issue #8084: ensure that the --user directory conforms to platforms standars on OSX when using a python framework. Modified: python/trunk/Lib/site.py python/trunk/Lib/sysconfig.py python/trunk/Misc/NEWS Modified: python/trunk/Lib/site.py ============================================================================== --- python/trunk/Lib/site.py (original) +++ python/trunk/Lib/site.py Sat May 8 12:29:06 2010 @@ -243,6 +243,13 @@ from sysconfig import get_path import os + + if sys.platform == 'darwin': + from sysconfig import get_config_var + if get_config_var('PYTHONFRAMEWORK'): + USER_SITE = get_path('purelib', 'osx_framework_user') + return USER_SITE + USER_SITE = get_path('purelib', '%s_user' % os.name) return USER_SITE @@ -289,13 +296,11 @@ if sys.platform == "darwin": # for framework builds *only* we add the standard Apple # locations. - if 'Python.framework' in prefix: - sitepackages.append( - os.path.expanduser( - os.path.join("~", "Library", "Python", - sys.version[:3], "site-packages"))) + from sysconfig import get_config_var + framework = get_config_var("PYTHONFRAMEWORK") + if framework and "/%s.framework/"%(framework,) in prefix: sitepackages.append( - os.path.join("/Library", "Python", + os.path.join("/Library", framework, sys.version[:3], "site-packages")) return sitepackages Modified: python/trunk/Lib/sysconfig.py ============================================================================== --- python/trunk/Lib/sysconfig.py (original) +++ python/trunk/Lib/sysconfig.py Sat May 8 12:29:06 2010 @@ -73,6 +73,15 @@ 'scripts': '{userbase}/bin', 'data' : '{userbase}', }, + 'osx_framework_user': { + 'stdlib': '{userbase}/lib/python', + 'platstdlib': '{userbase}/lib/python', + 'purelib': '{userbase}/lib/python/site-packages', + 'platlib': '{userbase}/lib/python/site-packages', + 'include': '{userbase}/include', + 'scripts': '{userbase}/bin', + 'data' : '{userbase}', + }, } _SCHEME_KEYS = ('stdlib', 'platstdlib', 'purelib', 'platlib', 'include', @@ -157,6 +166,12 @@ base = os.environ.get("APPDATA") or "~" return env_base if env_base else joinuser(base, "Python") + if sys.platform == "darwin": + framework = get_config_var("PYTHONFRAMEWORK") + if framework: + return joinuser("~", "Library", framework, "%d.%d"%( + sys.version_info[:2])) + return env_base if env_base else joinuser("~", ".local") @@ -398,7 +413,6 @@ _CONFIG_VARS['py_version_nodot'] = _PY_VERSION[0] + _PY_VERSION[2] _CONFIG_VARS['base'] = _PREFIX _CONFIG_VARS['platbase'] = _EXEC_PREFIX - _CONFIG_VARS['userbase'] = _getuserbase() _CONFIG_VARS['projectbase'] = _PROJECT_BASE if os.name in ('nt', 'os2'): @@ -406,6 +420,11 @@ if os.name == 'posix': _init_posix(_CONFIG_VARS) + # Setting 'userbase' is done below the call to the + # init function to enable using 'get_config_var' in + # the init-function. + _CONFIG_VARS['userbase'] = _getuserbase() + if 'srcdir' not in _CONFIG_VARS: _CONFIG_VARS['srcdir'] = _PROJECT_BASE Modified: python/trunk/Misc/NEWS ============================================================================== --- python/trunk/Misc/NEWS (original) +++ python/trunk/Misc/NEWS Sat May 8 12:29:06 2010 @@ -38,6 +38,12 @@ - Issue #8404: Fixed set operations on dictionary views. +- Issue #8084: PEP 370 now conforms to system conventions for framework + builds on MacOS X. That is, "python setup.py install --user" will install + into "~/Library/Python/2.7" instead of "~/.local". + + + Library ------- From python-checkins at python.org Sat May 8 12:49:43 2010 From: python-checkins at python.org (ronald.oussoren) Date: Sat, 8 May 2010 12:49:43 +0200 (CEST) Subject: [Python-checkins] r80968 - in python/branches/py3k: Lib/site.py Lib/sysconfig.py Misc/NEWS Message-ID: <20100508104943.42E52EE982@mail.python.org> Author: ronald.oussoren Date: Sat May 8 12:49:43 2010 New Revision: 80968 Log: Merged revisions 80967 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r80967 | ronald.oussoren | 2010-05-08 12:29:06 +0200 (Sat, 08 May 2010) | 4 lines Issue #8084: ensure that the --user directory conforms to platforms standars on OSX when using a python framework. ........ Modified: python/branches/py3k/ (props changed) python/branches/py3k/Lib/site.py python/branches/py3k/Lib/sysconfig.py python/branches/py3k/Misc/NEWS Modified: python/branches/py3k/Lib/site.py ============================================================================== --- python/branches/py3k/Lib/site.py (original) +++ python/branches/py3k/Lib/site.py Sat May 8 12:49:43 2010 @@ -240,6 +240,13 @@ from sysconfig import get_path import os + + if sys.platform == 'darwin': + from sysconfig import get_config_var + if get_config_var('PYTHONFRAMEWORK'): + USER_SITE = get_path('purelib', 'osx_framework_user') + return USER_SITE + USER_SITE = get_path('purelib', '%s_user' % os.name) return USER_SITE @@ -286,13 +293,11 @@ if sys.platform == "darwin": # for framework builds *only* we add the standard Apple # locations. - if 'Python.framework' in prefix: - sitepackages.append( - os.path.expanduser( - os.path.join("~", "Library", "Python", - sys.version[:3], "site-packages"))) + from sysconfig import get_config_var + framework = get_config_var("PYTHONFRAMEWORK") + if framework and "/%s.framework/"%(framework,) in prefix: sitepackages.append( - os.path.join("/Library", "Python", + os.path.join("/Library", framework, sys.version[:3], "site-packages")) return sitepackages Modified: python/branches/py3k/Lib/sysconfig.py ============================================================================== --- python/branches/py3k/Lib/sysconfig.py (original) +++ python/branches/py3k/Lib/sysconfig.py Sat May 8 12:49:43 2010 @@ -73,6 +73,15 @@ 'scripts': '{userbase}/bin', 'data' : '{userbase}', }, + 'osx_framework_user': { + 'stdlib': '{userbase}/lib/python', + 'platstdlib': '{userbase}/lib/python', + 'purelib': '{userbase}/lib/python/site-packages', + 'platlib': '{userbase}/lib/python/site-packages', + 'include': '{userbase}/include', + 'scripts': '{userbase}/bin', + 'data' : '{userbase}', + }, } _SCHEME_KEYS = ('stdlib', 'platstdlib', 'purelib', 'platlib', 'include', @@ -157,6 +166,12 @@ base = os.environ.get("APPDATA") or "~" return env_base if env_base else joinuser(base, "Python") + if sys.platform == "darwin": + framework = get_config_var("PYTHONFRAMEWORK") + if framework: + return joinuser("~", "Library", framework, "%d.%d"%( + sys.version_info[:2])) + return env_base if env_base else joinuser("~", ".local") @@ -400,13 +415,17 @@ _CONFIG_VARS['py_version_nodot'] = _PY_VERSION[0] + _PY_VERSION[2] _CONFIG_VARS['base'] = _PREFIX _CONFIG_VARS['platbase'] = _EXEC_PREFIX - _CONFIG_VARS['userbase'] = _getuserbase() _CONFIG_VARS['projectbase'] = _PROJECT_BASE if os.name in ('nt', 'os2'): _init_non_posix(_CONFIG_VARS) if os.name == 'posix': _init_posix(_CONFIG_VARS) + # Setting 'userbase' is done below the call to the + # init function to enable using 'get_config_var' in + # the init-function. + _CONFIG_VARS['userbase'] = _getuserbase() + if 'srcdir' not in _CONFIG_VARS: _CONFIG_VARS['srcdir'] = _PROJECT_BASE Modified: python/branches/py3k/Misc/NEWS ============================================================================== --- python/branches/py3k/Misc/NEWS (original) +++ python/branches/py3k/Misc/NEWS Sat May 8 12:49:43 2010 @@ -290,6 +290,9 @@ - Issue #7072: isspace(0xa0) is true on Mac OS X +- Issue #8084: PEP 370 now conforms to system conventions for framework + builds on MacOS X. That is, "python setup.py install --user" will install + into "~/Library/Python/2.7" instead of "~/.local". C-API ----- From python-checkins at python.org Sat May 8 13:01:40 2010 From: python-checkins at python.org (matthias.klose) Date: Sat, 8 May 2010 13:01:40 +0200 (CEST) Subject: [Python-checkins] r80969 - in python/trunk: configure configure.in Message-ID: <20100508110140.0BBA3EE99D@mail.python.org> Author: matthias.klose Date: Sat May 8 13:01:39 2010 New Revision: 80969 Log: configure.in: convert all obsolete AC_TRY_* macros to AC_*_IFELSE, only whitespace changes in generated configure (diff -uEwB). Modified: python/trunk/configure python/trunk/configure.in Modified: python/trunk/configure ============================================================================== --- python/trunk/configure (original) +++ python/trunk/configure Sat May 8 13:01:39 2010 @@ -1,5 +1,5 @@ #! /bin/sh -# From configure.in Revision: 80965 . +# From configure.in Revision: 80966 . # Guess values for system-dependent variables and create Makefiles. # Generated by GNU Autoconf 2.65 for python 2.7. # @@ -5611,6 +5611,7 @@ ac_cv_opt_olimit_ok=yes else ac_cv_opt_olimit_ok=no + fi rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext CC="$ac_save_cc" @@ -5652,6 +5653,7 @@ ac_cv_olimit_ok=yes else ac_cv_olimit_ok=no + fi rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext CC="$ac_save_cc" @@ -5675,7 +5677,6 @@ /* end confdefs.h. */ void f(char*,...)__attribute((format(PyArg_ParseTuple, 1, 2))); - int main () { @@ -5683,15 +5684,19 @@ ; return 0; } + _ACEOF if ac_fn_c_try_compile "$LINENO"; then : + $as_echo "#define HAVE_ATTRIBUTE_FORMAT_PARSETUPLE 1" >>confdefs.h - { $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5 + { $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5 $as_echo "yes" >&6; } + else - { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 + + { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 $as_echo "no" >&6; } fi @@ -7018,7 +7023,7 @@ int main () { -long double x; x = (long double)0.; +long double x; x = (long double)0; ; return 0; } @@ -7297,7 +7302,8 @@ have_pthread_t=no cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ -#include + + #include int main () { @@ -7305,6 +7311,7 @@ ; return 0; } + _ACEOF if ac_fn_c_try_compile "$LINENO"; then : have_pthread_t=yes @@ -8048,7 +8055,8 @@ $as_echo_n "checking for genuine AIX C++ extensions support... " >&6; } cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ -#include "/usr/lpp/xlC/include/load.h" + + #include "/usr/lpp/xlC/include/load.h" int main () { @@ -8056,16 +8064,21 @@ ; return 0; } + _ACEOF if ac_fn_c_try_link "$LINENO"; then : + $as_echo "#define AIX_GENUINE_CPLUSPLUS 1" >>confdefs.h - { $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5 + { $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5 $as_echo "yes" >&6; } + else - { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 + + { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 $as_echo "no" >&6; } + fi rm -f core conftest.err conftest.$ac_objext \ conftest$ac_exeext conftest.$ac_ext;; @@ -9045,6 +9058,7 @@ else if test "$cross_compiling" = yes; then : + { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 $as_echo "no" >&6; } ipv6=no @@ -9065,13 +9079,17 @@ _ACEOF if ac_fn_c_try_run "$LINENO"; then : + { $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5 $as_echo "yes" >&6; } ipv6=yes + else + { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 $as_echo "no" >&6; } ipv6=no + fi rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext \ conftest.$ac_objext conftest.beam conftest.$ac_ext @@ -9083,25 +9101,31 @@ $as_echo_n "checking if RFC2553 API is available... " >&6; } cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ -#include + + #include #include int main () { struct sockaddr_in6 x; -x.sin6_scope_id; + x.sin6_scope_id; ; return 0; } + _ACEOF if ac_fn_c_try_compile "$LINENO"; then : - { $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5 + + { $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5 $as_echo "yes" >&6; } - ipv6=yes + ipv6=yes + else - { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 + + { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 $as_echo "no" >&6; } - ipv6=no + ipv6=no + fi rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext fi @@ -9276,7 +9300,8 @@ $as_echo_n "checking for OSX 10.5 SDK or later... " >&6; } cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ -#include + + #include int main () { @@ -9286,14 +9311,14 @@ } _ACEOF if ac_fn_c_try_compile "$LINENO"; then : + ] +else + $as_echo "#define HAVE_OSX105_SDK 1" >>confdefs.h { $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5 $as_echo "yes" >&6; } -else - { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 -$as_echo "no" >&6; } fi rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext @@ -9533,7 +9558,7 @@ $as_echo "#define HAVE_CHROOT 1" >>confdefs.h - { $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5 + { $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5 $as_echo "yes" >&6; } else { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 @@ -9558,7 +9583,7 @@ $as_echo "#define HAVE_LINK 1" >>confdefs.h - { $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5 + { $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5 $as_echo "yes" >&6; } else { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 @@ -9583,7 +9608,7 @@ $as_echo "#define HAVE_SYMLINK 1" >>confdefs.h - { $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5 + { $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5 $as_echo "yes" >&6; } else { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 @@ -9608,7 +9633,7 @@ $as_echo "#define HAVE_FCHDIR 1" >>confdefs.h - { $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5 + { $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5 $as_echo "yes" >&6; } else { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 @@ -9633,7 +9658,7 @@ $as_echo "#define HAVE_FSYNC 1" >>confdefs.h - { $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5 + { $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5 $as_echo "yes" >&6; } else { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 @@ -9658,7 +9683,7 @@ $as_echo "#define HAVE_FDATASYNC 1" >>confdefs.h - { $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5 + { $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5 $as_echo "yes" >&6; } else { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 @@ -9683,7 +9708,7 @@ $as_echo "#define HAVE_EPOLL 1" >>confdefs.h - { $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5 + { $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5 $as_echo "yes" >&6; } else { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 @@ -9711,7 +9736,7 @@ $as_echo "#define HAVE_KQUEUE 1" >>confdefs.h - { $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5 + { $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5 $as_echo "yes" >&6; } else { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 @@ -9745,7 +9770,7 @@ $as_echo "#define HAVE_CTERMID_R 1" >>confdefs.h - { $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5 + { $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5 $as_echo "yes" >&6; } else { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 @@ -9774,7 +9799,7 @@ $as_echo "#define HAVE_FLOCK 1" >>confdefs.h - { $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5 + { $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5 $as_echo "yes" >&6; } else { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 @@ -9803,7 +9828,7 @@ $as_echo "#define HAVE_GETPAGESIZE 1" >>confdefs.h - { $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5 + { $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5 $as_echo "yes" >&6; } else { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 @@ -10123,7 +10148,7 @@ $as_echo "#define HAVE_HSTRERROR 1" >>confdefs.h - { $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5 + { $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5 $as_echo "yes" >&6; } else { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 @@ -10156,7 +10181,7 @@ $as_echo "#define HAVE_INET_ATON 1" >>confdefs.h - { $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5 + { $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5 $as_echo "yes" >&6; } else { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 @@ -10189,7 +10214,7 @@ $as_echo "#define HAVE_INET_PTON 1" >>confdefs.h - { $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5 + { $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5 $as_echo "yes" >&6; } else { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 @@ -10222,7 +10247,7 @@ $as_echo "#define HAVE_SETGROUPS 1" >>confdefs.h - { $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5 + { $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5 $as_echo "yes" >&6; } else { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 @@ -10499,7 +10524,6 @@ $as_echo "#define GETPGRP_HAVE_ARG 1" >>confdefs.h - fi rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext @@ -10528,7 +10552,6 @@ $as_echo "#define SETPGRP_HAVE_ARG 1" >>confdefs.h - fi rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext @@ -10988,6 +11011,7 @@ if test "${ac_cv_header_time_altzone+set}" = set; then : $as_echo_n "(cached) " >&6 else + cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ #include @@ -11005,6 +11029,7 @@ ac_cv_header_time_altzone=no fi rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext + fi { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_header_time_altzone" >&5 @@ -11052,8 +11077,7 @@ else cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ - -# include +#include int main () { @@ -11295,11 +11319,9 @@ _ACEOF if ac_fn_c_try_compile "$LINENO"; then : - $as_echo "#define HAVE_PROTOTYPES 1" >>confdefs.h - have_prototypes=yes - + have_prototypes=yes fi rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext { $as_echo "$as_me:${as_lineno-$LINENO}: result: $have_prototypes" >&5 @@ -11362,7 +11384,7 @@ $as_echo "#define HAVE_SOCKETPAIR 1" >>confdefs.h - { $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5 + { $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5 $as_echo "yes" >&6; } else { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 @@ -11396,6 +11418,7 @@ else { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 $as_echo "no" >&6; } + fi rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext @@ -11485,19 +11508,19 @@ cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ -# include +# include int main () { - char *name; - struct hostent *he; - char buffer[2048]; - int buflen = 2048; - int h_errnop; + char *name; + struct hostent *he; + char buffer[2048]; + int buflen = 2048; + int h_errnop; - (void) gethostbyname_r(name, he, buffer, buflen, &h_errnop) + (void) gethostbyname_r(name, he, buffer, buflen, &h_errnop) ; return 0; @@ -11505,34 +11528,34 @@ _ACEOF if ac_fn_c_try_compile "$LINENO"; then : - $as_echo "#define HAVE_GETHOSTBYNAME_R 1" >>confdefs.h + $as_echo "#define HAVE_GETHOSTBYNAME_R 1" >>confdefs.h $as_echo "#define HAVE_GETHOSTBYNAME_R_5_ARG 1" >>confdefs.h - { $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5 + { $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5 $as_echo "yes" >&6; } else - { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 + { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 $as_echo "no" >&6; } - { $as_echo "$as_me:${as_lineno-$LINENO}: checking gethostbyname_r with 3 args" >&5 + { $as_echo "$as_me:${as_lineno-$LINENO}: checking gethostbyname_r with 3 args" >&5 $as_echo_n "checking gethostbyname_r with 3 args... " >&6; } - cat confdefs.h - <<_ACEOF >conftest.$ac_ext + cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ -# include +# include int main () { - char *name; - struct hostent *he; - struct hostent_data data; + char *name; + struct hostent *he; + struct hostent_data data; - (void) gethostbyname_r(name, he, &data); + (void) gethostbyname_r(name, he, &data); ; return 0; @@ -11540,17 +11563,17 @@ _ACEOF if ac_fn_c_try_compile "$LINENO"; then : - $as_echo "#define HAVE_GETHOSTBYNAME_R 1" >>confdefs.h + $as_echo "#define HAVE_GETHOSTBYNAME_R 1" >>confdefs.h $as_echo "#define HAVE_GETHOSTBYNAME_R_3_ARG 1" >>confdefs.h - { $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5 + { $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5 $as_echo "yes" >&6; } else - { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 + { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 $as_echo "no" >&6; } fi @@ -12821,6 +12844,7 @@ have_readline=yes else have_readline=no + fi rm -f conftest.err conftest.$ac_ext if test $have_readline = yes @@ -12994,6 +13018,7 @@ have_readline=yes else have_readline=no + fi rm -f conftest.err conftest.$ac_ext if test $have_readline = yes @@ -13442,7 +13467,7 @@ $as_echo "#define HAVE_CURSES_IS_TERM_RESIZED 1" >>confdefs.h - { $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5 + { $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5 $as_echo "yes" >&6; } else { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 @@ -13468,7 +13493,7 @@ $as_echo "#define HAVE_CURSES_RESIZE_TERM 1" >>confdefs.h - { $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5 + { $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5 $as_echo "yes" >&6; } else { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 @@ -13494,7 +13519,7 @@ $as_echo "#define HAVE_CURSES_RESIZETERM 1" >>confdefs.h - { $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5 + { $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5 $as_echo "yes" >&6; } else { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 Modified: python/trunk/configure.in ============================================================================== --- python/trunk/configure.in (original) +++ python/trunk/configure.in Sat May 8 13:01:39 2010 @@ -754,10 +754,10 @@ AS_HELP_STRING([--enable-profiling], [enable C-level code profiling]), [ac_save_cc="$CC" CC="$CC -pg" - AC_TRY_RUN([int main() { return 0; }], - ac_enable_profiling="yes", - ac_enable_profiling="no", - ac_enable_profiling="no") + AC_RUN_IFELSE([AC_LANG_SOURCE([[int main() { return 0; }]])], + [ac_enable_profiling="yes"], + [ac_enable_profiling="no"], + [ac_enable_profiling="no"]) CC="$ac_save_cc"]) AC_MSG_RESULT($ac_enable_profiling) @@ -978,9 +978,10 @@ ac_save_cc="$CC" CC="$CC -fno-strict-aliasing" AC_CACHE_VAL(ac_cv_no_strict_aliasing_ok, - AC_TRY_COMPILE([],[int main() { return 0; }], - ac_cv_no_strict_aliasing_ok=yes, - ac_cv_no_strict_aliasing_ok=no)) + AC_COMPILE_IFELSE( + [AC_LANG_PROGRAM([[]], [[int main() { return 0; }]])], + [ac_cv_no_strict_aliasing_ok=yes], + [ac_cv_no_strict_aliasing_ok=no])) CC="$ac_save_cc" AC_MSG_RESULT($ac_cv_no_strict_aliasing_ok) if test $ac_cv_no_strict_aliasing_ok = yes @@ -1148,9 +1149,10 @@ AC_CACHE_VAL(ac_cv_opt_olimit_ok, [ac_save_cc="$CC" CC="$CC -OPT:Olimit=0" -AC_TRY_COMPILE([],[int main() { return 0; }], - ac_cv_opt_olimit_ok=yes, - ac_cv_opt_olimit_ok=no, +AC_COMPILE_IFELSE( + [AC_LANG_PROGRAM([[]], [[int main() { return 0; }]])], + [ac_cv_opt_olimit_ok=yes], + [ac_cv_opt_olimit_ok=no] ) CC="$ac_save_cc"]) AC_MSG_RESULT($ac_cv_opt_olimit_ok) @@ -1170,9 +1172,10 @@ AC_CACHE_VAL(ac_cv_olimit_ok, [ac_save_cc="$CC" CC="$CC -Olimit 1500" - AC_TRY_COMPILE([],[int main() { return 0; }], - ac_cv_olimit_ok=yes, - ac_cv_olimit_ok=no, + AC_COMPILE_IFELSE( + [AC_LANG_PROGRAM([[]], [[int main() { return 0; }]])], + [ac_cv_olimit_ok=yes], + [ac_cv_olimit_ok=no] ) CC="$ac_save_cc"]) AC_MSG_RESULT($ac_cv_olimit_ok) @@ -1187,13 +1190,15 @@ AC_MSG_CHECKING(whether gcc supports ParseTuple __format__) save_CFLAGS=$CFLAGS CFLAGS="$CFLAGS -Werror" - AC_TRY_COMPILE([ - void f(char*,...)__attribute((format(PyArg_ParseTuple, 1, 2))); - ],, - AC_DEFINE(HAVE_ATTRIBUTE_FORMAT_PARSETUPLE, 1, [Define if GCC supports __attribute__((format(PyArg_ParseTuple, 2, 3)))]) - AC_MSG_RESULT(yes), - AC_MSG_RESULT(no) - ) + AC_COMPILE_IFELSE([ + AC_LANG_PROGRAM([[void f(char*,...)__attribute((format(PyArg_ParseTuple, 1, 2)));]], [[]]) + ],[ + AC_DEFINE(HAVE_ATTRIBUTE_FORMAT_PARSETUPLE, 1, + [Define if GCC supports __attribute__((format(PyArg_ParseTuple, 2, 3)))]) + AC_MSG_RESULT(yes) + ],[ + AC_MSG_RESULT(no) + ]) CFLAGS=$save_CFLAGS fi @@ -1204,7 +1209,7 @@ # options before we can check whether -Kpthread improves anything. AC_MSG_CHECKING(whether pthreads are available without options) AC_CACHE_VAL(ac_cv_pthread_is_default, -[AC_TRY_RUN([ +[AC_RUN_IFELSE([AC_LANG_SOURCE([[ #include void* routine(void* p){return NULL;} @@ -1216,14 +1221,11 @@ (void)pthread_detach(p); return 0; } -], -[ +]])],[ ac_cv_pthread_is_default=yes ac_cv_kthread=no ac_cv_pthread=no -], - ac_cv_pthread_is_default=no, - ac_cv_pthread_is_default=no) +],[ac_cv_pthread_is_default=no],[ac_cv_pthread_is_default=no]) ]) AC_MSG_RESULT($ac_cv_pthread_is_default) @@ -1241,7 +1243,7 @@ AC_CACHE_VAL(ac_cv_kpthread, [ac_save_cc="$CC" CC="$CC -Kpthread" -AC_TRY_RUN([ +AC_RUN_IFELSE([AC_LANG_SOURCE([[ #include void* routine(void* p){return NULL;} @@ -1253,10 +1255,7 @@ (void)pthread_detach(p); return 0; } -], - ac_cv_kpthread=yes, - ac_cv_kpthread=no, - ac_cv_kpthread=no) +]])],[ac_cv_kpthread=yes],[ac_cv_kpthread=no],[ac_cv_kpthread=no]) CC="$ac_save_cc"]) AC_MSG_RESULT($ac_cv_kpthread) fi @@ -1272,7 +1271,7 @@ AC_CACHE_VAL(ac_cv_kthread, [ac_save_cc="$CC" CC="$CC -Kthread" -AC_TRY_RUN([ +AC_RUN_IFELSE([AC_LANG_SOURCE([[ #include void* routine(void* p){return NULL;} @@ -1284,10 +1283,7 @@ (void)pthread_detach(p); return 0; } -], - ac_cv_kthread=yes, - ac_cv_kthread=no, - ac_cv_kthread=no) +]])],[ac_cv_kthread=yes],[ac_cv_kthread=no],[ac_cv_kthread=no]) CC="$ac_save_cc"]) AC_MSG_RESULT($ac_cv_kthread) fi @@ -1303,7 +1299,7 @@ AC_CACHE_VAL(ac_cv_thread, [ac_save_cc="$CC" CC="$CC -pthread" -AC_TRY_RUN([ +AC_RUN_IFELSE([AC_LANG_SOURCE([[ #include void* routine(void* p){return NULL;} @@ -1315,10 +1311,7 @@ (void)pthread_detach(p); return 0; } -], - ac_cv_pthread=yes, - ac_cv_pthread=no, - ac_cv_pthread=no) +]])],[ac_cv_pthread=yes],[ac_cv_pthread=no],[ac_cv_pthread=no]) CC="$ac_save_cc"]) AC_MSG_RESULT($ac_cv_pthread) fi @@ -1364,11 +1357,11 @@ dnl # check for ANSI or K&R ("traditional") preprocessor dnl AC_MSG_CHECKING(for C preprocessor type) -dnl AC_TRY_COMPILE([ +dnl AC_COMPILE_IFELSE([AC_LANG_PROGRAM([[ dnl #define spam(name, doc) {#name, &name, #name "() -- " doc} dnl int foo; dnl struct {char *name; int *addr; char *doc;} desc = spam(foo, "something"); -dnl ], [;], cpp_type=ansi, AC_DEFINE(HAVE_OLD_CPP) cpp_type=traditional) +dnl ]], [[;]])],[cpp_type=ansi],[AC_DEFINE(HAVE_OLD_CPP) cpp_type=traditional]) dnl AC_MSG_RESULT($cpp_type) # checks for header files @@ -1415,26 +1408,24 @@ # Check whether using makedev requires defining _OSF_SOURCE AC_MSG_CHECKING(for makedev) -AC_TRY_LINK([ +AC_LINK_IFELSE([AC_LANG_PROGRAM([[ #if defined(MAJOR_IN_MKDEV) #include #elif defined(MAJOR_IN_SYSMACROS) #include #else #include -#endif ], - [ makedev(0, 0) ], - ac_cv_has_makedev=yes, - ac_cv_has_makedev=no) +#endif ]], [[ makedev(0, 0) ]])], +[ac_cv_has_makedev=yes], +[ac_cv_has_makedev=no]) if test "$ac_cv_has_makedev" = "no"; then # we didn't link, try if _OSF_SOURCE will allow us to link - AC_TRY_LINK([ + AC_LINK_IFELSE([AC_LANG_PROGRAM([[ #define _OSF_SOURCE 1 #include - ], - [ makedev(0, 0) ], - ac_cv_has_makedev=yes, - ac_cv_has_makedev=no) + ]], [[ makedev(0, 0) ]])], +[ac_cv_has_makedev=yes], +[ac_cv_has_makedev=no]) if test "$ac_cv_has_makedev" = "yes"; then AC_DEFINE(_OSF_SOURCE, 1, [Define _OSF_SOURCE to get the makedev macro.]) fi @@ -1453,11 +1444,11 @@ use_lfs=yes AC_MSG_CHECKING(Solaris LFS bug) -AC_TRY_COMPILE([ +AC_COMPILE_IFELSE([AC_LANG_PROGRAM([[ #define _LARGEFILE_SOURCE 1 #define _FILE_OFFSET_BITS 64 #include -],[struct rlimit foo;],sol_lfs_bug=no,sol_lfs_bug=yes) +]], [[struct rlimit foo;]])],[sol_lfs_bug=no],[sol_lfs_bug=yes]) AC_MSG_RESULT($sol_lfs_bug) if test "$sol_lfs_bug" = "yes"; then use_lfs=no @@ -1483,7 +1474,18 @@ AC_TYPE_MODE_T AC_TYPE_OFF_T AC_TYPE_PID_T -AC_TYPE_SIGNAL +AC_DIAGNOSE([obsolete],[your code may safely assume C89 semantics that RETSIGTYPE is void. +Remove this warning and the `AC_CACHE_CHECK' when you adjust the code.])dnl +AC_CACHE_CHECK([return type of signal handlers],[ac_cv_type_signal],[AC_COMPILE_IFELSE( +[AC_LANG_PROGRAM([#include +#include +], + [return *(signal (0, 0)) (0) == 1;])], + [ac_cv_type_signal=int], + [ac_cv_type_signal=void])]) +AC_DEFINE_UNQUOTED([RETSIGTYPE],[$ac_cv_type_signal],[Define as the return type of signal handlers + (`int' or `void').]) + AC_TYPE_SIZE_T AC_TYPE_UID_T AC_TYPE_UINT32_T @@ -1507,10 +1509,10 @@ AC_MSG_CHECKING(for long long support) have_long_long=no -AC_TRY_COMPILE([], [long long x; x = (long long)0;], [ +AC_COMPILE_IFELSE([AC_LANG_PROGRAM([[]], [[long long x; x = (long long)0;]])],[ AC_DEFINE(HAVE_LONG_LONG, 1, [Define this if you have the type long long.]) have_long_long=yes -]) +],[]) AC_MSG_RESULT($have_long_long) if test "$have_long_long" = yes ; then AC_CHECK_SIZEOF(long long, 8) @@ -1518,10 +1520,10 @@ AC_MSG_CHECKING(for long double support) have_long_double=no -AC_TRY_COMPILE([], [long double x; x = (long double)0.;], [ +AC_COMPILE_IFELSE([AC_LANG_PROGRAM([[]], [[long double x; x = (long double)0;]])],[ AC_DEFINE(HAVE_LONG_DOUBLE, 1, [Define this if you have the type long double.]) have_long_double=yes -]) +],[]) AC_MSG_RESULT($have_long_double) if test "$have_long_double" = yes ; then AC_CHECK_SIZEOF(long double, 12) @@ -1529,10 +1531,10 @@ AC_MSG_CHECKING(for _Bool support) have_c99_bool=no -AC_TRY_COMPILE([], [_Bool x; x = (_Bool)0;], [ +AC_COMPILE_IFELSE([AC_LANG_PROGRAM([[]], [[_Bool x; x = (_Bool)0;]])],[ AC_DEFINE(HAVE_C99_BOOL, 1, [Define this if you have the type _Bool.]) have_c99_bool=yes -]) +],[]) AC_MSG_RESULT($have_c99_bool) if test "$have_c99_bool" = yes ; then AC_CHECK_SIZEOF(_Bool, 1) @@ -1588,7 +1590,9 @@ fi AC_MSG_CHECKING(for pthread_t) have_pthread_t=no -AC_TRY_COMPILE([#include ], [pthread_t x; x = *(pthread_t*)0;], have_pthread_t=yes) +AC_COMPILE_IFELSE([ + AC_LANG_PROGRAM([[#include ]], [[pthread_t x; x = *(pthread_t*)0;]]) +],[have_pthread_t=yes],[]) AC_MSG_RESULT($have_pthread_t) if test "$have_pthread_t" = yes ; then AC_CHECK_SIZEOF(pthread_t, [], [ @@ -1658,7 +1662,7 @@ else LIBTOOL_CRUFT="" fi - AC_TRY_RUN([ + AC_RUN_IFELSE([AC_LANG_SOURCE([[ #include int main(int argc, char*argv[]) { @@ -1668,9 +1672,7 @@ return 1; } } - ], ac_osx_32bit=yes, - ac_osx_32bit=no, - ac_osx_32bit=yes) + ]])],[ac_osx_32bit=yes],[ac_osx_32bit=no],[ac_osx_32bit=yes]) if test "${ac_osx_32bit}" = "yes"; then case `/usr/bin/arch` in @@ -2067,13 +2069,17 @@ # checks for system dependent C++ extensions support case "$ac_sys_system" in AIX*) AC_MSG_CHECKING(for genuine AIX C++ extensions support) - AC_TRY_LINK([#include "/usr/lpp/xlC/include/load.h"], - [loadAndInit("", 0, "")], - [AC_DEFINE(AIX_GENUINE_CPLUSPLUS, 1, + AC_LINK_IFELSE([ + AC_LANG_PROGRAM([[#include "/usr/lpp/xlC/include/load.h"]], + [[loadAndInit("", 0, "")]]) + ],[ + AC_DEFINE(AIX_GENUINE_CPLUSPLUS, 1, [Define for AIX if your compiler is a genuine IBM xlC/xlC_r and you want support for AIX C++ shared extension modules.]) - AC_MSG_RESULT(yes)], - [AC_MSG_RESULT(no)]);; + AC_MSG_RESULT(yes) + ],[ + AC_MSG_RESULT(no) + ]);; *) ;; esac @@ -2286,10 +2292,10 @@ _libs=$LIBS LIBS="$LIBS -lpthread" AC_MSG_CHECKING([for pthread_create in -lpthread]) - AC_TRY_LINK([#include + AC_LINK_IFELSE([AC_LANG_PROGRAM([[#include -void * start_routine (void *arg) { exit (0); }], [ -pthread_create (NULL, NULL, start_routine, NULL)], [ +void * start_routine (void *arg) { exit (0); }]], [[ +pthread_create (NULL, NULL, start_routine, NULL)]])],[ AC_MSG_RESULT(yes) AC_DEFINE(WITH_THREAD) posix_threads=yes @@ -2369,7 +2375,7 @@ AC_MSG_CHECKING(if PTHREAD_SCOPE_SYSTEM is supported) AC_CACHE_VAL(ac_cv_pthread_system_supported, - [AC_TRY_RUN([#include + [AC_RUN_IFELSE([AC_LANG_SOURCE([[#include void *foo(void *parm) { return NULL; } @@ -2380,10 +2386,10 @@ if (pthread_attr_setscope(&attr, PTHREAD_SCOPE_SYSTEM)) exit(-1); if (pthread_create(&id, &attr, foo, NULL)) exit(-1); exit(0); - }], - ac_cv_pthread_system_supported=yes, - ac_cv_pthread_system_supported=no, - ac_cv_pthread_system_supported=no) + }]])], + [ac_cv_pthread_system_supported=yes], + [ac_cv_pthread_system_supported=no], + [ac_cv_pthread_system_supported=no]) ]) AC_MSG_RESULT($ac_cv_pthread_system_supported) if test "$ac_cv_pthread_system_supported" = "yes"; then @@ -2418,7 +2424,7 @@ [ dnl the check does not work on cross compilation case... - AC_TRY_RUN([ /* AF_INET6 available check */ + AC_RUN_IFELSE([AC_LANG_SOURCE([[ /* AF_INET6 available check */ #include #include main() @@ -2428,25 +2434,31 @@ else exit(0); } -], +]])],[ AC_MSG_RESULT(yes) - ipv6=yes, + ipv6=yes +],[ AC_MSG_RESULT(no) - ipv6=no, + ipv6=no +],[ AC_MSG_RESULT(no) ipv6=no -) +]) if test "$ipv6" = "yes"; then AC_MSG_CHECKING(if RFC2553 API is available) - AC_TRY_COMPILE([#include -#include ], - [struct sockaddr_in6 x; -x.sin6_scope_id;], - AC_MSG_RESULT(yes) - ipv6=yes, - AC_MSG_RESULT(no, IPv6 disabled) - ipv6=no) + AC_COMPILE_IFELSE([ + AC_LANG_PROGRAM([[#include +#include ]], + [[struct sockaddr_in6 x; + x.sin6_scope_id;]]) + ],[ + AC_MSG_RESULT(yes) + ipv6=yes + ],[ + AC_MSG_RESULT(no, IPv6 disabled) + ipv6=no + ]) fi if test "$ipv6" = "yes"; then @@ -2567,11 +2579,14 @@ fi AC_MSG_CHECKING(for OSX 10.5 SDK or later) -AC_TRY_COMPILE([#include ], FSIORefNum fRef = 0, +AC_COMPILE_IFELSE([ + AC_LANG_PROGRAM([[#include ]], [[FSIORefNum fRef = 0]])], +],[ AC_DEFINE(HAVE_OSX105_SDK, 1, [Define if compiling using MacOS X 10.5 SDK or later.]) - AC_MSG_RESULT(yes), + AC_MSG_RESULT(yes) +],[ AC_MSG_RESULT(no) -) +]) # Check for --with-doc-strings AC_MSG_CHECKING(for --with-doc-strings) @@ -2719,56 +2734,56 @@ # For some functions, having a definition is not sufficient, since # we want to take their address. AC_MSG_CHECKING(for chroot) -AC_TRY_COMPILE([#include ], [void *x=chroot], - AC_DEFINE(HAVE_CHROOT, 1, [Define if you have the 'chroot' function.]) - AC_MSG_RESULT(yes), - AC_MSG_RESULT(no) -) +AC_COMPILE_IFELSE([AC_LANG_PROGRAM([[#include ]], [[void *x=chroot]])], + [AC_DEFINE(HAVE_CHROOT, 1, Define if you have the 'chroot' function.) + AC_MSG_RESULT(yes)], + [AC_MSG_RESULT(no) +]) AC_MSG_CHECKING(for link) -AC_TRY_COMPILE([#include ], [void *x=link], - AC_DEFINE(HAVE_LINK, 1, [Define if you have the 'link' function.]) - AC_MSG_RESULT(yes), - AC_MSG_RESULT(no) -) +AC_COMPILE_IFELSE([AC_LANG_PROGRAM([[#include ]], [[void *x=link]])], + [AC_DEFINE(HAVE_LINK, 1, Define if you have the 'link' function.) + AC_MSG_RESULT(yes)], + [AC_MSG_RESULT(no) +]) AC_MSG_CHECKING(for symlink) -AC_TRY_COMPILE([#include ], [void *x=symlink], - AC_DEFINE(HAVE_SYMLINK, 1, [Define if you have the 'symlink' function.]) - AC_MSG_RESULT(yes), - AC_MSG_RESULT(no) -) +AC_COMPILE_IFELSE([AC_LANG_PROGRAM([[#include ]], [[void *x=symlink]])], + [AC_DEFINE(HAVE_SYMLINK, 1, Define if you have the 'symlink' function.) + AC_MSG_RESULT(yes)], + [AC_MSG_RESULT(no) +]) AC_MSG_CHECKING(for fchdir) -AC_TRY_COMPILE([#include ], [void *x=fchdir], - AC_DEFINE(HAVE_FCHDIR, 1, [Define if you have the 'fchdir' function.]) - AC_MSG_RESULT(yes), - AC_MSG_RESULT(no) -) +AC_COMPILE_IFELSE([AC_LANG_PROGRAM([[#include ]], [[void *x=fchdir]])], + [AC_DEFINE(HAVE_FCHDIR, 1, Define if you have the 'fchdir' function.) + AC_MSG_RESULT(yes)], + [AC_MSG_RESULT(no) +]) AC_MSG_CHECKING(for fsync) -AC_TRY_COMPILE([#include ], [void *x=fsync], - AC_DEFINE(HAVE_FSYNC, 1, [Define if you have the 'fsync' function.]) - AC_MSG_RESULT(yes), - AC_MSG_RESULT(no) -) +AC_COMPILE_IFELSE([AC_LANG_PROGRAM([[#include ]], [[void *x=fsync]])], + [AC_DEFINE(HAVE_FSYNC, 1, Define if you have the 'fsync' function.) + AC_MSG_RESULT(yes)], + [AC_MSG_RESULT(no) +]) AC_MSG_CHECKING(for fdatasync) -AC_TRY_COMPILE([#include ], [void *x=fdatasync], - AC_DEFINE(HAVE_FDATASYNC, 1, [Define if you have the 'fdatasync' function.]) - AC_MSG_RESULT(yes), - AC_MSG_RESULT(no) -) +AC_COMPILE_IFELSE([AC_LANG_PROGRAM([[#include ]], [[void *x=fdatasync]])], + [AC_DEFINE(HAVE_FDATASYNC, 1, Define if you have the 'fdatasync' function.) + AC_MSG_RESULT(yes)], + [AC_MSG_RESULT(no) +]) AC_MSG_CHECKING(for epoll) -AC_TRY_COMPILE([#include ], [void *x=epoll_create], - AC_DEFINE(HAVE_EPOLL, 1, [Define if you have the 'epoll' functions.]) - AC_MSG_RESULT(yes), - AC_MSG_RESULT(no) -) +AC_COMPILE_IFELSE([AC_LANG_PROGRAM([[#include ]], [[void *x=epoll_create]])], + [AC_DEFINE(HAVE_EPOLL, 1, Define if you have the 'epoll' functions.) + AC_MSG_RESULT(yes)], + [AC_MSG_RESULT(no) +]) AC_MSG_CHECKING(for kqueue) -AC_TRY_COMPILE([ +AC_COMPILE_IFELSE([AC_LANG_PROGRAM([[ #include #include - ], [int x=kqueue()], - AC_DEFINE(HAVE_KQUEUE, 1, [Define if you have the 'kqueue' functions.]) - AC_MSG_RESULT(yes), - AC_MSG_RESULT(no) -) + ]], [[int x=kqueue()]])], + [AC_DEFINE(HAVE_KQUEUE, 1, Define if you have the 'kqueue' functions.) + AC_MSG_RESULT(yes)], + [AC_MSG_RESULT(no) +]) # On some systems (eg. FreeBSD 5), we would find a definition of the # functions ctermid_r, setgroups in the library, but no prototype # (e.g. because we use _XOPEN_SOURCE). See whether we can take their @@ -2776,34 +2791,34 @@ # because of the missing prototypes. AC_MSG_CHECKING(for ctermid_r) -AC_TRY_COMPILE([ +AC_COMPILE_IFELSE([AC_LANG_PROGRAM([[ #include "confdefs.h" #include -], [void* p = ctermid_r], - AC_DEFINE(HAVE_CTERMID_R, 1, [Define if you have the 'ctermid_r' function.]) - AC_MSG_RESULT(yes), - AC_MSG_RESULT(no) -) +]], [[void* p = ctermid_r]])], + [AC_DEFINE(HAVE_CTERMID_R, 1, Define if you have the 'ctermid_r' function.) + AC_MSG_RESULT(yes)], + [AC_MSG_RESULT(no) +]) AC_MSG_CHECKING(for flock) -AC_TRY_COMPILE([ +AC_COMPILE_IFELSE([AC_LANG_PROGRAM([[ #include "confdefs.h" #include -], [void* p = flock], - AC_DEFINE(HAVE_FLOCK, 1, [Define if you have the 'flock' function.]) - AC_MSG_RESULT(yes), - AC_MSG_RESULT(no) -) +]], [[void* p = flock]])], + [AC_DEFINE(HAVE_FLOCK, 1, Define if you have the 'flock' function.) + AC_MSG_RESULT(yes)], + [AC_MSG_RESULT(no) +]) AC_MSG_CHECKING(for getpagesize) -AC_TRY_COMPILE([ +AC_COMPILE_IFELSE([AC_LANG_PROGRAM([[ #include "confdefs.h" #include -], [void* p = getpagesize], - AC_DEFINE(HAVE_GETPAGESIZE, 1, [Define if you have the 'getpagesize' function.]) - AC_MSG_RESULT(yes), - AC_MSG_RESULT(no) -) +]], [[void* p = getpagesize]])], + [AC_DEFINE(HAVE_GETPAGESIZE, 1, Define if you have the 'getpagesize' function.) + AC_MSG_RESULT(yes)], + [AC_MSG_RESULT(no) +]) dnl check for true AC_CHECK_PROGS(TRUE, true, /bin/true) @@ -2817,7 +2832,7 @@ # On Tru64, chflags seems to be present, but calling it will # exit Python AC_CACHE_CHECK([for chflags], [ac_cv_have_chflags], [dnl -AC_TRY_RUN([[ +AC_RUN_IFELSE([AC_LANG_SOURCE([[[ #include #include int main(int argc, char*argv[]) @@ -2826,9 +2841,10 @@ return 1; return 0; } -]], ac_cv_have_chflags=yes, - ac_cv_have_chflags=no, - ac_cv_have_chflags=cross) +]]])], +[ac_cv_have_chflags=yes], +[ac_cv_have_chflags=no], +[ac_cv_have_chflags=cross]) ]) if test "$ac_cv_have_chflags" = cross ; then AC_CHECK_FUNC([chflags], [ac_cv_have_chflags="yes"], [ac_cv_have_chflags="no"]) @@ -2838,7 +2854,7 @@ fi AC_CACHE_CHECK([for lchflags], [ac_cv_have_lchflags], [dnl -AC_TRY_RUN([[ +AC_RUN_IFELSE([AC_LANG_SOURCE([[[ #include #include int main(int argc, char*argv[]) @@ -2847,9 +2863,7 @@ return 1; return 0; } -]], ac_cv_have_lchflags=yes, - ac_cv_have_lchflags=no, - ac_cv_have_lchflags=cross) +]]])],[ac_cv_have_lchflags=yes],[ac_cv_have_lchflags=no],[ac_cv_have_lchflags=cross]) ]) if test "$ac_cv_have_lchflags" = cross ; then AC_CHECK_FUNC([lchflags], [ac_cv_have_lchflags="yes"], [ac_cv_have_lchflags="no"]) @@ -2888,55 +2902,54 @@ esac AC_MSG_CHECKING(for hstrerror) -AC_TRY_LINK([ +AC_LINK_IFELSE([AC_LANG_PROGRAM([[ #include "confdefs.h" #include -], [void* p = hstrerror; hstrerror(0)], - AC_DEFINE(HAVE_HSTRERROR, 1, [Define if you have the 'hstrerror' function.]) - AC_MSG_RESULT(yes), - AC_MSG_RESULT(no) -) +]], [[void* p = hstrerror; hstrerror(0)]])], + [AC_DEFINE(HAVE_HSTRERROR, 1, Define if you have the 'hstrerror' function.) + AC_MSG_RESULT(yes)], + [AC_MSG_RESULT(no) +]) AC_MSG_CHECKING(for inet_aton) -AC_TRY_LINK([ +AC_LINK_IFELSE([AC_LANG_PROGRAM([[ #include "confdefs.h" #include #include #include #include -], [void* p = inet_aton;inet_aton(0,0)], - AC_DEFINE(HAVE_INET_ATON, 1, [Define if you have the 'inet_aton' function.]) - AC_MSG_RESULT(yes), - AC_MSG_RESULT(no) -) +]], [[void* p = inet_aton;inet_aton(0,0)]])], + [AC_DEFINE(HAVE_INET_ATON, 1, Define if you have the 'inet_aton' function.) + AC_MSG_RESULT(yes)], + [AC_MSG_RESULT(no) +]) AC_MSG_CHECKING(for inet_pton) -AC_TRY_COMPILE([ +AC_COMPILE_IFELSE([AC_LANG_PROGRAM([[ #include "confdefs.h" #include #include #include #include -], [void* p = inet_pton], - AC_DEFINE(HAVE_INET_PTON, 1, [Define if you have the 'inet_pton' function.]) - AC_MSG_RESULT(yes), - AC_MSG_RESULT(no) -) +]], [[void* p = inet_pton]])], + [AC_DEFINE(HAVE_INET_PTON, 1, Define if you have the 'inet_pton' function.) + AC_MSG_RESULT(yes)], + [AC_MSG_RESULT(no) +]) # On some systems, setgroups is in unistd.h, on others, in grp.h AC_MSG_CHECKING(for setgroups) -AC_TRY_COMPILE([ +AC_COMPILE_IFELSE([AC_LANG_PROGRAM([[ #include "confdefs.h" #include #ifdef HAVE_GRP_H #include #endif -], -[void* p = setgroups], - AC_DEFINE(HAVE_SETGROUPS, 1, [Define if you have the 'setgroups' function.]) - AC_MSG_RESULT(yes), - AC_MSG_RESULT(no) -) +]], [[void* p = setgroups]])], + [AC_DEFINE(HAVE_SETGROUPS, 1, Define if you have the 'setgroups' function.) + AC_MSG_RESULT(yes)], + [AC_MSG_RESULT(no) +]) # check for openpty and forkpty @@ -2961,30 +2974,27 @@ AC_REPLACE_FUNCS(dup2 getcwd strdup) AC_CHECK_FUNCS(getpgrp, - AC_TRY_COMPILE([#include ], - [getpgrp(0);], - AC_DEFINE(GETPGRP_HAVE_ARG, 1, - [Define if getpgrp() must be called as getpgrp(0).]) - ) + AC_COMPILE_IFELSE([AC_LANG_PROGRAM([[#include ]], [[getpgrp(0);]])], + [AC_DEFINE(GETPGRP_HAVE_ARG, 1, [Define if getpgrp() must be called as getpgrp(0).])], + []) ) AC_CHECK_FUNCS(setpgrp, - AC_TRY_COMPILE([#include ], - [setpgrp(0,0);], - AC_DEFINE(SETPGRP_HAVE_ARG, 1, - [Define if setpgrp() must be called as setpgrp(0, 0).]) - ) + AC_COMPILE_IFELSE([AC_LANG_PROGRAM([[#include ]], [[setpgrp(0,0);]])], + [AC_DEFINE(SETPGRP_HAVE_ARG, 1, [Define if setpgrp() must be called as setpgrp(0, 0).])], + []) ) AC_CHECK_FUNCS(gettimeofday, - AC_TRY_COMPILE([#include ], - [gettimeofday((struct timeval*)0,(struct timezone*)0);], , - AC_DEFINE(GETTIMEOFDAY_NO_TZ, 1, - [Define if gettimeofday() does not have second (timezone) argument - This is the case on Motorola V4 (R40V4.2)]) - ) + AC_COMPILE_IFELSE([AC_LANG_PROGRAM([[#include ]], + [[gettimeofday((struct timeval*)0,(struct timezone*)0);]])], + [], + [AC_DEFINE(GETTIMEOFDAY_NO_TZ, 1, + [Define if gettimeofday() does not have second (timezone) argument + This is the case on Motorola V4 (R40V4.2)]) + ]) ) AC_MSG_CHECKING(for major, minor, and makedev) -AC_TRY_LINK([ +AC_LINK_IFELSE([AC_LANG_PROGRAM([[ #if defined(MAJOR_IN_MKDEV) #include #elif defined(MAJOR_IN_SYSMACROS) @@ -2992,9 +3002,9 @@ #else #include #endif -],[ +]], [[ makedev(major(0),minor(0)); -],[ +]])],[ AC_DEFINE(HAVE_DEVICE_MACROS, 1, [Define to 1 if you have the device macros.]) AC_MSG_RESULT(yes) @@ -3005,20 +3015,20 @@ # On OSF/1 V5.1, getaddrinfo is available, but a define # for [no]getaddrinfo in netdb.h. AC_MSG_CHECKING(for getaddrinfo) -AC_TRY_LINK([ +AC_LINK_IFELSE([AC_LANG_PROGRAM([[ #include #include #include #include -], [getaddrinfo(NULL, NULL, NULL, NULL);], -have_getaddrinfo=yes, -have_getaddrinfo=no) +]], [[getaddrinfo(NULL, NULL, NULL, NULL);]])], +[have_getaddrinfo=yes], +[have_getaddrinfo=no]) AC_MSG_RESULT($have_getaddrinfo) if test $have_getaddrinfo = yes then AC_MSG_CHECKING(getaddrinfo bug) AC_CACHE_VAL(ac_cv_buggy_getaddrinfo, - AC_TRY_RUN([[ + AC_RUN_IFELSE([AC_LANG_SOURCE([[[ #include #include #include @@ -3104,9 +3114,10 @@ freeaddrinfo(aitop); return 1; } -]], ac_cv_buggy_getaddrinfo=no, - ac_cv_buggy_getaddrinfo=yes, - ac_cv_buggy_getaddrinfo=yes)) +]]])], +[ac_cv_buggy_getaddrinfo=no], +[ac_cv_buggy_getaddrinfo=yes], +[ac_cv_buggy_getaddrinfo=yes])) fi if test $have_getaddrinfo = no -o "$ac_cv_buggy_getaddrinfo" = yes @@ -3134,10 +3145,11 @@ AC_STRUCT_ST_BLOCKS AC_MSG_CHECKING(for time.h that defines altzone) -AC_CACHE_VAL(ac_cv_header_time_altzone, -[AC_TRY_COMPILE([#include ], [return altzone;], - ac_cv_header_time_altzone=yes, - ac_cv_header_time_altzone=no)]) +AC_CACHE_VAL(ac_cv_header_time_altzone,[ + AC_COMPILE_IFELSE([AC_LANG_PROGRAM([[#include ]], [[return altzone;]])], + [ac_cv_header_time_altzone=yes], + [ac_cv_header_time_altzone=no]) + ]) AC_MSG_RESULT($ac_cv_header_time_altzone) if test $ac_cv_header_time_altzone = yes; then AC_DEFINE(HAVE_ALTZONE, 1, [Define this if your time.h defines altzone.]) @@ -3145,25 +3157,23 @@ was_it_defined=no AC_MSG_CHECKING(whether sys/select.h and sys/time.h may both be included) -AC_TRY_COMPILE([ +AC_COMPILE_IFELSE([AC_LANG_PROGRAM([[ #include #include #include -], [;], [ +]], [[;]])],[ AC_DEFINE(SYS_SELECT_WITH_SYS_TIME, 1, [Define if you can safely include both and (which you can't on SCO ODT 3.0).]) was_it_defined=yes -]) +],[]) AC_MSG_RESULT($was_it_defined) AC_MSG_CHECKING(for addrinfo) AC_CACHE_VAL(ac_cv_struct_addrinfo, -AC_TRY_COMPILE([ -# include ], - [struct addrinfo a], - ac_cv_struct_addrinfo=yes, - ac_cv_struct_addrinfo=no)) +AC_COMPILE_IFELSE([AC_LANG_PROGRAM([[#include ]], [[struct addrinfo a]])], + [ac_cv_struct_addrinfo=yes], + [ac_cv_struct_addrinfo=no])) AC_MSG_RESULT($ac_cv_struct_addrinfo) if test $ac_cv_struct_addrinfo = yes; then AC_DEFINE(HAVE_ADDRINFO, 1, [struct addrinfo (netdb.h)]) @@ -3171,12 +3181,11 @@ AC_MSG_CHECKING(for sockaddr_storage) AC_CACHE_VAL(ac_cv_struct_sockaddr_storage, -AC_TRY_COMPILE([ +AC_COMPILE_IFELSE([AC_LANG_PROGRAM([[ # include -# include ], - [struct sockaddr_storage s], - ac_cv_struct_sockaddr_storage=yes, - ac_cv_struct_sockaddr_storage=no)) +# include ]], [[struct sockaddr_storage s]])], + [ac_cv_struct_sockaddr_storage=yes], + [ac_cv_struct_sockaddr_storage=no])) AC_MSG_RESULT($ac_cv_struct_sockaddr_storage) if test $ac_cv_struct_sockaddr_storage = yes; then AC_DEFINE(HAVE_SOCKADDR_STORAGE, 1, [struct sockaddr_storage (sys/socket.h)]) @@ -3189,30 +3198,33 @@ works=no AC_MSG_CHECKING(for working volatile) -AC_TRY_COMPILE([],[volatile int x; x = 0;], works=yes, - AC_DEFINE(volatile, [], [Define to empty if the keyword does not work.]) +AC_COMPILE_IFELSE([AC_LANG_PROGRAM([[]], [[volatile int x; x = 0;]])], + [works=yes], + [AC_DEFINE(volatile, , [Define to empty if the keyword does not work.])] ) AC_MSG_RESULT($works) works=no AC_MSG_CHECKING(for working signed char) -AC_TRY_COMPILE([], [signed char c;], works=yes, - AC_DEFINE(signed, [], [Define to empty if the keyword does not work.]) +AC_COMPILE_IFELSE([AC_LANG_PROGRAM([[]], [[signed char c;]])], + [works=yes], + [AC_DEFINE(signed, , [Define to empty if the keyword does not work.])] ) AC_MSG_RESULT($works) have_prototypes=no AC_MSG_CHECKING(for prototypes) -AC_TRY_COMPILE([int foo(int x) { return 0; }], [return foo(10);],[ - AC_DEFINE(HAVE_PROTOTYPES, 1, - [Define if your compiler supports function prototype]) - have_prototypes=yes -]) +AC_COMPILE_IFELSE([AC_LANG_PROGRAM([[int foo(int x) { return 0; }]], [[return foo(10);]])], + [AC_DEFINE(HAVE_PROTOTYPES, 1, + [Define if your compiler supports function prototype]) + have_prototypes=yes], + [] +) AC_MSG_RESULT($have_prototypes) works=no AC_MSG_CHECKING(for variable length prototypes and stdarg.h) -AC_TRY_COMPILE([ +AC_COMPILE_IFELSE([AC_LANG_PROGRAM([[ #include int foo(int x, ...) { va_list va; @@ -3222,44 +3234,44 @@ va_arg(va, double); return 0; } -], [return foo(10, "", 3.14);], [ +]], [[return foo(10, "", 3.14);]])],[ AC_DEFINE(HAVE_STDARG_PROTOTYPES, 1, [Define if your compiler supports variable length function prototypes (e.g. void fprintf(FILE *, char *, ...);) *and* ]) works=yes -]) +],[]) AC_MSG_RESULT($works) # check for socketpair AC_MSG_CHECKING(for socketpair) -AC_TRY_COMPILE([ +AC_COMPILE_IFELSE([AC_LANG_PROGRAM([[ #include #include -], [void *x=socketpair], - AC_DEFINE(HAVE_SOCKETPAIR, 1, [Define if you have the 'socketpair' function.]) - AC_MSG_RESULT(yes), - AC_MSG_RESULT(no) +]], [[void *x=socketpair]])], + [AC_DEFINE(HAVE_SOCKETPAIR, 1, [Define if you have the 'socketpair' function.]) + AC_MSG_RESULT(yes)], + [AC_MSG_RESULT(no)] ) # check if sockaddr has sa_len member AC_MSG_CHECKING(if sockaddr has sa_len member) -AC_TRY_COMPILE([#include -#include ], -[struct sockaddr x; -x.sa_len = 0;], - AC_MSG_RESULT(yes) - AC_DEFINE(HAVE_SOCKADDR_SA_LEN, 1, [Define if sockaddr has sa_len member]), - AC_MSG_RESULT(no)) +AC_COMPILE_IFELSE([AC_LANG_PROGRAM([[#include +#include ]], [[struct sockaddr x; +x.sa_len = 0;]])], + [AC_MSG_RESULT(yes) + AC_DEFINE(HAVE_SOCKADDR_SA_LEN, 1, [Define if sockaddr has sa_len member])], + [AC_MSG_RESULT(no)] +) va_list_is_array=no AC_MSG_CHECKING(whether va_list is an array) -AC_TRY_COMPILE([ +AC_COMPILE_IFELSE([AC_LANG_PROGRAM([[ #ifdef HAVE_STDARG_PROTOTYPES #include #else #include #endif -], [va_list list1, list2; list1 = list2;], , [ +]], [[va_list list1, list2; list1 = list2;]])],[],[ AC_DEFINE(VA_LIST_IS_ARRAY, 1, [Define if a va_list is an array of some kind]) va_list_is_array=yes ]) @@ -3274,9 +3286,9 @@ AC_MSG_CHECKING([gethostbyname_r with 6 args]) OLD_CFLAGS=$CFLAGS CFLAGS="$CFLAGS $MY_CPPFLAGS $MY_THREAD_CPPFLAGS $MY_CFLAGS" - AC_TRY_COMPILE([ + AC_COMPILE_IFELSE([AC_LANG_PROGRAM([[ # include - ], [ + ]], [[ char *name; struct hostent *he, *res; char buffer[2048]; @@ -3284,48 +3296,50 @@ int h_errnop; (void) gethostbyname_r(name, he, buffer, buflen, &res, &h_errnop) - ], [ + ]])],[ AC_DEFINE(HAVE_GETHOSTBYNAME_R) AC_DEFINE(HAVE_GETHOSTBYNAME_R_6_ARG, 1, [Define this if you have the 6-arg version of gethostbyname_r().]) AC_MSG_RESULT(yes) - ], [ + ],[ AC_MSG_RESULT(no) AC_MSG_CHECKING([gethostbyname_r with 5 args]) - AC_TRY_COMPILE([ -# include - ], [ - char *name; - struct hostent *he; - char buffer[2048]; - int buflen = 2048; - int h_errnop; - - (void) gethostbyname_r(name, he, buffer, buflen, &h_errnop) - ], [ - AC_DEFINE(HAVE_GETHOSTBYNAME_R) - AC_DEFINE(HAVE_GETHOSTBYNAME_R_5_ARG, 1, - [Define this if you have the 5-arg version of gethostbyname_r().]) - AC_MSG_RESULT(yes) - ], [ - AC_MSG_RESULT(no) - AC_MSG_CHECKING([gethostbyname_r with 3 args]) - AC_TRY_COMPILE([ + AC_COMPILE_IFELSE([AC_LANG_PROGRAM([[ # include - ], [ + ]], [[ char *name; struct hostent *he; - struct hostent_data data; - - (void) gethostbyname_r(name, he, &data); - ], [ + char buffer[2048]; + int buflen = 2048; + int h_errnop; + + (void) gethostbyname_r(name, he, buffer, buflen, &h_errnop) + ]])], + [ AC_DEFINE(HAVE_GETHOSTBYNAME_R) - AC_DEFINE(HAVE_GETHOSTBYNAME_R_3_ARG, 1, - [Define this if you have the 3-arg version of gethostbyname_r().]) + AC_DEFINE(HAVE_GETHOSTBYNAME_R_5_ARG, 1, + [Define this if you have the 5-arg version of gethostbyname_r().]) AC_MSG_RESULT(yes) ], [ AC_MSG_RESULT(no) - ]) + AC_MSG_CHECKING([gethostbyname_r with 3 args]) + AC_COMPILE_IFELSE([AC_LANG_PROGRAM([[ +# include + ]], [[ + char *name; + struct hostent *he; + struct hostent_data data; + + (void) gethostbyname_r(name, he, &data); + ]])], + [ + AC_DEFINE(HAVE_GETHOSTBYNAME_R) + AC_DEFINE(HAVE_GETHOSTBYNAME_R_3_ARG, 1, + [Define this if you have the 3-arg version of gethostbyname_r().]) + AC_MSG_RESULT(yes) + ], [ + AC_MSG_RESULT(no) + ]) ]) ]) CFLAGS=$OLD_CFLAGS @@ -3404,7 +3418,7 @@ AC_MSG_CHECKING(whether C doubles are little-endian IEEE 754 binary64) AC_CACHE_VAL(ac_cv_little_endian_double, [ -AC_TRY_RUN([ +AC_RUN_IFELSE([AC_LANG_SOURCE([[ #include int main() { double x = 9006104071832581.0; @@ -3413,10 +3427,10 @@ else return 1; } -], -ac_cv_little_endian_double=yes, -ac_cv_little_endian_double=no, -ac_cv_little_endian_double=no)]) +]])], +[ac_cv_little_endian_double=yes], +[ac_cv_little_endian_double=no], +[ac_cv_little_endian_double=no])]) AC_MSG_RESULT($ac_cv_little_endian_double) if test "$ac_cv_little_endian_double" = yes then @@ -3427,7 +3441,7 @@ AC_MSG_CHECKING(whether C doubles are big-endian IEEE 754 binary64) AC_CACHE_VAL(ac_cv_big_endian_double, [ -AC_TRY_RUN([ +AC_RUN_IFELSE([AC_LANG_SOURCE([[ #include int main() { double x = 9006104071832581.0; @@ -3436,10 +3450,10 @@ else return 1; } -], -ac_cv_big_endian_double=yes, -ac_cv_big_endian_double=no, -ac_cv_big_endian_double=no)]) +]])], +[ac_cv_big_endian_double=yes], +[ac_cv_big_endian_double=no], +[ac_cv_big_endian_double=no])]) AC_MSG_RESULT($ac_cv_big_endian_double) if test "$ac_cv_big_endian_double" = yes then @@ -3454,7 +3468,7 @@ # conversions work. AC_MSG_CHECKING(whether C doubles are ARM mixed-endian IEEE 754 binary64) AC_CACHE_VAL(ac_cv_mixed_endian_double, [ -AC_TRY_RUN([ +AC_RUN_IFELSE([AC_LANG_SOURCE([[ #include int main() { double x = 9006104071832581.0; @@ -3463,10 +3477,10 @@ else return 1; } -], -ac_cv_mixed_endian_double=yes, -ac_cv_mixed_endian_double=no, -ac_cv_mixed_endian_double=no)]) +]])], +[ac_cv_mixed_endian_double=yes], +[ac_cv_mixed_endian_double=no], +[ac_cv_mixed_endian_double=no])]) AC_MSG_RESULT($ac_cv_mixed_endian_double) if test "$ac_cv_mixed_endian_double" = yes then @@ -3486,12 +3500,11 @@ # so we try it on all platforms. AC_MSG_CHECKING(whether we can use gcc inline assembler to get and set x87 control word) -AC_TRY_COMPILE([], [ +AC_COMPILE_IFELSE([AC_LANG_PROGRAM([[]], [[ unsigned short cw; __asm__ __volatile__ ("fnstcw %0" : "=m" (cw)); __asm__ __volatile__ ("fldcw %0" : : "m" (cw)); -], -[have_gcc_asm_for_x87=yes], [have_gcc_asm_for_x87=no]) +]])],[have_gcc_asm_for_x87=yes],[have_gcc_asm_for_x87=no]) AC_MSG_RESULT($have_gcc_asm_for_x87) if test "$have_gcc_asm_for_x87" = yes then @@ -3508,7 +3521,7 @@ # $BASECFLAGS may affect the result ac_save_cc="$CC" CC="$CC $BASECFLAGS" -AC_TRY_RUN([ +AC_RUN_IFELSE([AC_LANG_SOURCE([[ #include #include int main() { @@ -3527,10 +3540,10 @@ /* both tests show evidence of double rounding */ exit(1); } -], -ac_cv_x87_double_rounding=no, -ac_cv_x87_double_rounding=yes, -ac_cv_x87_double_rounding=no) +]])], +[ac_cv_x87_double_rounding=no], +[ac_cv_x87_double_rounding=yes], +[ac_cv_x87_double_rounding=no]) CC="$ac_save_cc" AC_MSG_RESULT($ac_cv_x87_double_rounding) if test "$ac_cv_x87_double_rounding" = yes @@ -3550,7 +3563,7 @@ # -0. on some architectures. AC_MSG_CHECKING(whether tanh preserves the sign of zero) AC_CACHE_VAL(ac_cv_tanh_preserves_zero_sign, [ -AC_TRY_RUN([ +AC_RUN_IFELSE([AC_LANG_SOURCE([[ #include #include int main() { @@ -3561,10 +3574,10 @@ atan2(tanh(-0.), -1.) == atan2(-0., -1.)) exit(0); else exit(1); } -], -ac_cv_tanh_preserves_zero_sign=yes, -ac_cv_tanh_preserves_zero_sign=no, -ac_cv_tanh_preserves_zero_sign=no)]) +]])], +[ac_cv_tanh_preserves_zero_sign=yes], +[ac_cv_tanh_preserves_zero_sign=no], +[ac_cv_tanh_preserves_zero_sign=no])]) AC_MSG_RESULT($ac_cv_tanh_preserves_zero_sign) if test "$ac_cv_tanh_preserves_zero_sign" = yes then @@ -3585,7 +3598,7 @@ # sem_open results in a 'Signal 12' error. AC_MSG_CHECKING(whether POSIX semaphores are enabled) AC_CACHE_VAL(ac_cv_posix_semaphores_enabled, -AC_TRY_RUN([ +AC_RUN_IFELSE([AC_LANG_SOURCE([[ #include #include #include @@ -3602,9 +3615,10 @@ sem_unlink("/autoconf"); return 0; } -], ac_cv_posix_semaphores_enabled=yes, - ac_cv_posix_semaphores_enabled=no, - ac_cv_posix_semaphores_enabled=yes) +]])], +[ac_cv_posix_semaphores_enabled=yes], +[ac_cv_posix_semaphores_enabled=no], +[ac_cv_posix_semaphores_enabled=yes]) ) AC_MSG_RESULT($ac_cv_posix_semaphores_enabled) if test $ac_cv_posix_semaphores_enabled = no @@ -3616,7 +3630,7 @@ # Multiprocessing check for broken sem_getvalue AC_MSG_CHECKING(for broken sem_getvalue) AC_CACHE_VAL(ac_cv_broken_sem_getvalue, -AC_TRY_RUN([ +AC_RUN_IFELSE([AC_LANG_SOURCE([[ #include #include #include @@ -3637,9 +3651,10 @@ sem_unlink("/autocftw"); return res==-1 ? 1 : 0; } -], ac_cv_broken_sem_getvalue=no, - ac_cv_broken_sem_getvalue=yes, - ac_cv_broken_sem_getvalue=yes) +]])], +[ac_cv_broken_sem_getvalue=no], +[ac_cv_broken_sem_getvalue=yes], +[ac_cv_broken_sem_getvalue=yes]) ) AC_MSG_RESULT($ac_cv_broken_sem_getvalue) if test $ac_cv_broken_sem_getvalue = yes @@ -3684,14 +3699,14 @@ AC_MSG_CHECKING(for UCS-4 tcl) have_ucs4_tcl=no -AC_TRY_COMPILE([ +AC_COMPILE_IFELSE([AC_LANG_PROGRAM([[ #include #if TCL_UTF_MAX != 6 # error "NOT UCS4_TCL" -#endif], [], [ +#endif]], [[]])],[ AC_DEFINE(HAVE_UCS4_TCL, 1, [Define this if you have tcl and TCL_UTF_MAX==6]) have_ucs4_tcl=yes -]) +],[]) AC_MSG_RESULT($have_ucs4_tcl) # check whether wchar_t is signed or not @@ -3700,17 +3715,17 @@ # check whether wchar_t is signed or not AC_MSG_CHECKING(whether wchar_t is signed) AC_CACHE_VAL(ac_cv_wchar_t_signed, [ - AC_TRY_RUN([ + AC_RUN_IFELSE([AC_LANG_SOURCE([[ #include int main() { /* Success: exit code 0 */ exit((((wchar_t) -1) < ((wchar_t) 0)) ? 0 : 1); } - ], - ac_cv_wchar_t_signed=yes, - ac_cv_wchar_t_signed=no, - ac_cv_wchar_t_signed=yes)]) + ]])], + [ac_cv_wchar_t_signed=yes], + [ac_cv_wchar_t_signed=no], + [ac_cv_wchar_t_signed=yes])]) AC_MSG_RESULT($ac_cv_wchar_t_signed) fi @@ -3788,15 +3803,15 @@ # or fills with zeros (like the Cray J90, according to Tim Peters). AC_MSG_CHECKING(whether right shift extends the sign bit) AC_CACHE_VAL(ac_cv_rshift_extends_sign, [ -AC_TRY_RUN([ +AC_RUN_IFELSE([AC_LANG_SOURCE([[ int main() { exit(((-1)>>3 == -1) ? 0 : 1); } -], -ac_cv_rshift_extends_sign=yes, -ac_cv_rshift_extends_sign=no, -ac_cv_rshift_extends_sign=yes)]) +]])], +[ac_cv_rshift_extends_sign=yes], +[ac_cv_rshift_extends_sign=no], +[ac_cv_rshift_extends_sign=yes])]) AC_MSG_RESULT($ac_cv_rshift_extends_sign) if test "$ac_cv_rshift_extends_sign" = no then @@ -3808,12 +3823,12 @@ # check for getc_unlocked and related locking functions AC_MSG_CHECKING(for getc_unlocked() and friends) AC_CACHE_VAL(ac_cv_have_getc_unlocked, [ -AC_TRY_LINK([#include ],[ +AC_LINK_IFELSE([AC_LANG_PROGRAM([[#include ]], [[ FILE *f = fopen("/dev/null", "r"); flockfile(f); getc_unlocked(f); funlockfile(f); -], ac_cv_have_getc_unlocked=yes, ac_cv_have_getc_unlocked=no)]) +]])],[ac_cv_have_getc_unlocked=yes],[ac_cv_have_getc_unlocked=no])]) AC_MSG_RESULT($ac_cv_have_getc_unlocked) if test "$ac_cv_have_getc_unlocked" = yes then @@ -3860,8 +3875,10 @@ [Define if you have readline 2.1]), ,$READLINE_LIBS) # check for readline 2.2 -AC_TRY_CPP([#include ], -have_readline=yes, have_readline=no) +AC_PREPROC_IFELSE([AC_LANG_SOURCE([[#include ]])], + [have_readline=yes], + [have_readline=no] +) if test $have_readline = yes then AC_EGREP_HEADER([extern int rl_completion_append_character;], @@ -3890,8 +3907,10 @@ [Define if you have readline 4.2]), ,$READLINE_LIBS) # also in readline 4.2 -AC_TRY_CPP([#include ], -have_readline=yes, have_readline=no) +AC_PREPROC_IFELSE([AC_LANG_SOURCE([[#include ]])], + [have_readline=yes], + [have_readline=no] +) if test $have_readline = yes then AC_EGREP_HEADER([extern int rl_catch_signals;], @@ -3905,7 +3924,7 @@ AC_MSG_CHECKING(for broken nice()) AC_CACHE_VAL(ac_cv_broken_nice, [ -AC_TRY_RUN([ +AC_RUN_IFELSE([AC_LANG_SOURCE([[ int main() { int val1 = nice(1); @@ -3913,10 +3932,10 @@ exit(0); exit(1); } -], -ac_cv_broken_nice=yes, -ac_cv_broken_nice=no, -ac_cv_broken_nice=no)]) +]])], +[ac_cv_broken_nice=yes], +[ac_cv_broken_nice=no], +[ac_cv_broken_nice=no])]) AC_MSG_RESULT($ac_cv_broken_nice) if test "$ac_cv_broken_nice" = yes then @@ -3926,7 +3945,7 @@ AC_MSG_CHECKING(for broken poll()) AC_CACHE_VAL(ac_cv_broken_poll, -AC_TRY_RUN([ +AC_RUN_IFELSE([AC_LANG_SOURCE([[ #include int main() @@ -3944,10 +3963,10 @@ else return 1; } -], -ac_cv_broken_poll=yes, -ac_cv_broken_poll=no, -ac_cv_broken_poll=no)) +]])], +[ac_cv_broken_poll=yes], +[ac_cv_broken_poll=no], +[ac_cv_broken_poll=no])) AC_MSG_RESULT($ac_cv_broken_poll) if test "$ac_cv_broken_poll" = yes then @@ -3963,7 +3982,7 @@ # check tzset(3) exists and works like we expect it to AC_MSG_CHECKING(for working tzset()) AC_CACHE_VAL(ac_cv_working_tzset, [ -AC_TRY_RUN([ +AC_RUN_IFELSE([AC_LANG_SOURCE([[ #include #include #include @@ -4026,10 +4045,10 @@ exit(0); } -], -ac_cv_working_tzset=yes, -ac_cv_working_tzset=no, -ac_cv_working_tzset=no)]) +]])], +[ac_cv_working_tzset=yes], +[ac_cv_working_tzset=no], +[ac_cv_working_tzset=no])]) AC_MSG_RESULT($ac_cv_working_tzset) if test "$ac_cv_working_tzset" = yes then @@ -4040,13 +4059,12 @@ # Look for subsecond timestamps in struct stat AC_MSG_CHECKING(for tv_nsec in struct stat) AC_CACHE_VAL(ac_cv_stat_tv_nsec, -AC_TRY_COMPILE([#include ], [ +AC_COMPILE_IFELSE([AC_LANG_PROGRAM([[#include ]], [[ struct stat st; st.st_mtim.tv_nsec = 1; -], -ac_cv_stat_tv_nsec=yes, -ac_cv_stat_tv_nsec=no, -ac_cv_stat_tv_nsec=no)) +]])], +[ac_cv_stat_tv_nsec=yes], +[ac_cv_stat_tv_nsec=no])) AC_MSG_RESULT($ac_cv_stat_tv_nsec) if test "$ac_cv_stat_tv_nsec" = yes then @@ -4057,13 +4075,12 @@ # Look for BSD style subsecond timestamps in struct stat AC_MSG_CHECKING(for tv_nsec2 in struct stat) AC_CACHE_VAL(ac_cv_stat_tv_nsec2, -AC_TRY_COMPILE([#include ], [ +AC_COMPILE_IFELSE([AC_LANG_PROGRAM([[#include ]], [[ struct stat st; st.st_mtimespec.tv_nsec = 1; -], -ac_cv_stat_tv_nsec2=yes, -ac_cv_stat_tv_nsec2=no, -ac_cv_stat_tv_nsec2=no)) +]])], +[ac_cv_stat_tv_nsec2=yes], +[ac_cv_stat_tv_nsec2=no])) AC_MSG_RESULT($ac_cv_stat_tv_nsec2) if test "$ac_cv_stat_tv_nsec2" = yes then @@ -4074,12 +4091,12 @@ # On HP/UX 11.0, mvwdelch is a block with a return statement AC_MSG_CHECKING(whether mvwdelch is an expression) AC_CACHE_VAL(ac_cv_mvwdelch_is_expression, -AC_TRY_COMPILE([#include ], [ +AC_COMPILE_IFELSE([AC_LANG_PROGRAM([[#include ]], [[ int rtn; rtn = mvwdelch(0,0,0); -], ac_cv_mvwdelch_is_expression=yes, - ac_cv_mvwdelch_is_expression=no, - ac_cv_mvwdelch_is_expression=yes)) +]])], +[ac_cv_mvwdelch_is_expression=yes], +[ac_cv_mvwdelch_is_expression=no])) AC_MSG_RESULT($ac_cv_mvwdelch_is_expression) if test "$ac_cv_mvwdelch_is_expression" = yes @@ -4090,12 +4107,12 @@ AC_MSG_CHECKING(whether WINDOW has _flags) AC_CACHE_VAL(ac_cv_window_has_flags, -AC_TRY_COMPILE([#include ], [ +AC_COMPILE_IFELSE([AC_LANG_PROGRAM([[#include ]], [[ WINDOW *w; w->_flags = 0; -], ac_cv_window_has_flags=yes, - ac_cv_window_has_flags=no, - ac_cv_window_has_flags=no)) +]])], +[ac_cv_window_has_flags=yes], +[ac_cv_window_has_flags=no])) AC_MSG_RESULT($ac_cv_window_has_flags) @@ -4106,24 +4123,24 @@ fi AC_MSG_CHECKING(for is_term_resized) -AC_TRY_COMPILE([#include ], [void *x=is_term_resized], - AC_DEFINE(HAVE_CURSES_IS_TERM_RESIZED, 1, [Define if you have the 'is_term_resized' function.]) - AC_MSG_RESULT(yes), - AC_MSG_RESULT(no) +AC_COMPILE_IFELSE([AC_LANG_PROGRAM([[#include ]], [[void *x=is_term_resized]])], + [AC_DEFINE(HAVE_CURSES_IS_TERM_RESIZED, 1, Define if you have the 'is_term_resized' function.) + AC_MSG_RESULT(yes)], + [AC_MSG_RESULT(no)] ) AC_MSG_CHECKING(for resize_term) -AC_TRY_COMPILE([#include ], [void *x=resize_term], - AC_DEFINE(HAVE_CURSES_RESIZE_TERM, 1, [Define if you have the 'resize_term' function.]) - AC_MSG_RESULT(yes), - AC_MSG_RESULT(no) +AC_COMPILE_IFELSE([AC_LANG_PROGRAM([[#include ]], [[void *x=resize_term]])], + [AC_DEFINE(HAVE_CURSES_RESIZE_TERM, 1, Define if you have the 'resize_term' function.) + AC_MSG_RESULT(yes)], + [AC_MSG_RESULT(no)] ) AC_MSG_CHECKING(for resizeterm) -AC_TRY_COMPILE([#include ], [void *x=resizeterm], - AC_DEFINE(HAVE_CURSES_RESIZETERM, 1, [Define if you have the 'resizeterm' function.]) - AC_MSG_RESULT(yes), - AC_MSG_RESULT(no) +AC_COMPILE_IFELSE([AC_LANG_PROGRAM([[#include ]], [[void *x=resizeterm]])], + [AC_DEFINE(HAVE_CURSES_RESIZETERM, 1, Define if you have the 'resizeterm' function.) + AC_MSG_RESULT(yes)], + [AC_MSG_RESULT(no)] ) AC_MSG_CHECKING(for /dev/ptmx) @@ -4152,7 +4169,7 @@ then AC_MSG_CHECKING(for %lld and %llu printf() format support) AC_CACHE_VAL(ac_cv_have_long_long_format, - AC_TRY_RUN([[ + AC_RUN_IFELSE([AC_LANG_SOURCE([[[ #include #include #include @@ -4182,9 +4199,10 @@ return 0; } - ]], ac_cv_have_long_long_format=yes, - ac_cv_have_long_long_format=no, - ac_cv_have_long_long_format=no) + ]]])], + [ac_cv_have_long_long_format=yes], + [ac_cv_have_long_long_format=no], + [ac_cv_have_long_long_format=no]) ) AC_MSG_RESULT($ac_cv_have_long_long_format) fi @@ -4202,7 +4220,7 @@ AC_CACHE_CHECK([for %zd printf() format support], ac_cv_have_size_t_format, [dnl -AC_TRY_RUN([ +AC_RUN_IFELSE([AC_LANG_SOURCE([[ #include #include #include @@ -4237,10 +4255,11 @@ return 0; } -], ac_cv_have_size_t_format=yes, - ac_cv_have_size_t_format=no, - [ac_cv_have_size_t_format="cross -- assuming yes"] -)]) +]])], +[ac_cv_have_size_t_format=yes], +[ac_cv_have_size_t_format=no], +[ac_cv_have_size_t_format="cross -- assuming yes" +])]) if test "$ac_cv_have_size_t_format" != no ; then AC_DEFINE(PY_FORMAT_SIZE_T, "z", [Define to printf format modifier for Py_ssize_t]) From python-checkins at python.org Sat May 8 13:04:18 2010 From: python-checkins at python.org (matthias.klose) Date: Sat, 8 May 2010 13:04:18 +0200 (CEST) Subject: [Python-checkins] r80970 - in python/trunk: configure configure.in pyconfig.h.in Message-ID: <20100508110418.5833AEE987@mail.python.org> Author: matthias.klose Date: Sat May 8 13:04:18 2010 New Revision: 80970 Log: configure.in: Avoid autoconf warning: Assume C89 semantics that RETSIGTYPE is always void (issue #8510). pyconfig.h: Regenerate Modified: python/trunk/configure python/trunk/configure.in python/trunk/pyconfig.h.in Modified: python/trunk/configure ============================================================================== --- python/trunk/configure (original) +++ python/trunk/configure Sat May 8 13:04:18 2010 @@ -1,5 +1,5 @@ #! /bin/sh -# From configure.in Revision: 80966 . +# From configure.in Revision: 80969 . # Guess values for system-dependent variables and create Makefiles. # Generated by GNU Autoconf 2.65 for python 2.7. # @@ -6511,39 +6511,11 @@ fi -{ $as_echo "$as_me:${as_lineno-$LINENO}: checking return type of signal handlers" >&5 -$as_echo_n "checking return type of signal handlers... " >&6; } -if test "${ac_cv_type_signal+set}" = set; then : - $as_echo_n "(cached) " >&6 -else - cat confdefs.h - <<_ACEOF >conftest.$ac_ext -/* end confdefs.h. */ -#include -#include - -int -main () -{ -return *(signal (0, 0)) (0) == 1; - ; - return 0; -} -_ACEOF -if ac_fn_c_try_compile "$LINENO"; then : - ac_cv_type_signal=int -else - ac_cv_type_signal=void -fi -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext -fi -{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_type_signal" >&5 -$as_echo "$ac_cv_type_signal" >&6; } cat >>confdefs.h <<_ACEOF -#define RETSIGTYPE $ac_cv_type_signal +#define RETSIGTYPE void _ACEOF - ac_fn_c_check_type "$LINENO" "size_t" "ac_cv_type_size_t" "$ac_includes_default" if test "x$ac_cv_type_size_t" = x""yes; then : Modified: python/trunk/configure.in ============================================================================== --- python/trunk/configure.in (original) +++ python/trunk/configure.in Sat May 8 13:04:18 2010 @@ -1474,18 +1474,7 @@ AC_TYPE_MODE_T AC_TYPE_OFF_T AC_TYPE_PID_T -AC_DIAGNOSE([obsolete],[your code may safely assume C89 semantics that RETSIGTYPE is void. -Remove this warning and the `AC_CACHE_CHECK' when you adjust the code.])dnl -AC_CACHE_CHECK([return type of signal handlers],[ac_cv_type_signal],[AC_COMPILE_IFELSE( -[AC_LANG_PROGRAM([#include -#include -], - [return *(signal (0, 0)) (0) == 1;])], - [ac_cv_type_signal=int], - [ac_cv_type_signal=void])]) -AC_DEFINE_UNQUOTED([RETSIGTYPE],[$ac_cv_type_signal],[Define as the return type of signal handlers - (`int' or `void').]) - +AC_DEFINE_UNQUOTED([RETSIGTYPE],[void],[assume C89 semantics that RETSIGTYPE is always void]) AC_TYPE_SIZE_T AC_TYPE_UID_T AC_TYPE_UINT32_T Modified: python/trunk/pyconfig.h.in ============================================================================== --- python/trunk/pyconfig.h.in (original) +++ python/trunk/pyconfig.h.in Sat May 8 13:04:18 2010 @@ -5,6 +5,9 @@ #define Py_PYCONFIG_H +/* Define if building universal (internal helper macro) */ +#undef AC_APPLE_UNIVERSAL_BUILD + /* Define for AIX if your compiler is a genuine IBM xlC/xlC_r and you want support for AIX C++ shared extension modules. */ #undef AIX_GENUINE_CPLUSPLUS @@ -674,25 +677,25 @@ /* Define to 1 if you have the header file. */ #undef HAVE_STROPTS_H -/* Define to 1 if `st_birthtime' is member of `struct stat'. */ +/* Define to 1 if `st_birthtime' is a member of `struct stat'. */ #undef HAVE_STRUCT_STAT_ST_BIRTHTIME -/* Define to 1 if `st_blksize' is member of `struct stat'. */ +/* Define to 1 if `st_blksize' is a member of `struct stat'. */ #undef HAVE_STRUCT_STAT_ST_BLKSIZE -/* Define to 1 if `st_blocks' is member of `struct stat'. */ +/* Define to 1 if `st_blocks' is a member of `struct stat'. */ #undef HAVE_STRUCT_STAT_ST_BLOCKS -/* Define to 1 if `st_flags' is member of `struct stat'. */ +/* Define to 1 if `st_flags' is a member of `struct stat'. */ #undef HAVE_STRUCT_STAT_ST_FLAGS -/* Define to 1 if `st_gen' is member of `struct stat'. */ +/* Define to 1 if `st_gen' is a member of `struct stat'. */ #undef HAVE_STRUCT_STAT_ST_GEN -/* Define to 1 if `st_rdev' is member of `struct stat'. */ +/* Define to 1 if `st_rdev' is a member of `struct stat'. */ #undef HAVE_STRUCT_STAT_ST_RDEV -/* Define to 1 if `tm_zone' is member of `struct tm'. */ +/* Define to 1 if `tm_zone' is a member of `struct tm'. */ #undef HAVE_STRUCT_TM_TM_ZONE /* Define to 1 if your `struct stat' has `st_blocks'. Deprecated, use @@ -915,6 +918,9 @@ /* Define to the one symbol short name of this package. */ #undef PACKAGE_TARNAME +/* Define to the home page for this package. */ +#undef PACKAGE_URL + /* Define to the version of this package. */ #undef PACKAGE_VERSION @@ -948,7 +954,7 @@ /* Define if you want to have a Unicode type. */ #undef Py_USING_UNICODE -/* Define as the return type of signal handlers (`int' or `void'). */ +/* assume C89 semantics that RETSIGTYPE is always void */ #undef RETSIGTYPE /* Define if setpgrp() must be called as setpgrp(0, 0). */ @@ -1027,6 +1033,28 @@ /* Define to 1 if your declares `struct tm'. */ #undef TM_IN_SYS_TIME +/* Enable extensions on AIX 3, Interix. */ +#ifndef _ALL_SOURCE +# undef _ALL_SOURCE +#endif +/* Enable GNU extensions on systems that have them. */ +#ifndef _GNU_SOURCE +# undef _GNU_SOURCE +#endif +/* Enable threading extensions on Solaris. */ +#ifndef _POSIX_PTHREAD_SEMANTICS +# undef _POSIX_PTHREAD_SEMANTICS +#endif +/* Enable extensions on HP NonStop. */ +#ifndef _TANDEM_SOURCE +# undef _TANDEM_SOURCE +#endif +/* Enable general extensions on Solaris. */ +#ifndef __EXTENSIONS__ +# undef __EXTENSIONS__ +#endif + + /* Define if you want to use MacPython modules on MacOSX in unix-Python. */ #undef USE_TOOLBOX_OBJECT_GLUE @@ -1070,20 +1098,21 @@ /* Define if you want pymalloc to be disabled when running under valgrind */ #undef WITH_VALGRIND -/* Define to 1 if your processor stores words with the most significant byte - first (like Motorola and SPARC, unlike Intel and VAX). */ -#undef WORDS_BIGENDIAN +/* Define WORDS_BIGENDIAN to 1 if your processor stores words with the most + significant byte first (like Motorola and SPARC, unlike Intel). */ +#if defined AC_APPLE_UNIVERSAL_BUILD +# if defined __BIG_ENDIAN__ +# define WORDS_BIGENDIAN 1 +# endif +#else +# ifndef WORDS_BIGENDIAN +# undef WORDS_BIGENDIAN +# endif +#endif /* Define if arithmetic is subject to x87-style double rounding issue */ #undef X87_DOUBLE_ROUNDING -/* Define to 1 if on AIX 3. - System headers sometimes define this. - We just want to avoid a redefinition error message. */ -#ifndef _ALL_SOURCE -# undef _ALL_SOURCE -#endif - /* Define on OpenBSD to activate all library features */ #undef _BSD_SOURCE @@ -1102,15 +1131,25 @@ /* This must be defined on some systems to enable large file support. */ #undef _LARGEFILE_SOURCE +/* Define to 1 if on MINIX. */ +#undef _MINIX + /* Define on NetBSD to activate all library features */ #undef _NETBSD_SOURCE /* Define _OSF_SOURCE to get the makedev macro. */ #undef _OSF_SOURCE +/* Define to 2 if the system does not provide POSIX.1 features except with + this defined. */ +#undef _POSIX_1_SOURCE + /* Define to activate features from IEEE Stds 1003.1-2001 */ #undef _POSIX_C_SOURCE +/* Define to 1 if you need to in order for `stat' and other things to work. */ +#undef _POSIX_SOURCE + /* Define if you have POSIX threads, and your system does not define that. */ #undef _POSIX_THREADS @@ -1118,12 +1157,12 @@ #undef _REENTRANT /* Define for Solaris 2.5.1 so the uint32_t typedef from , - , or is not used. If the typedef was allowed, the + , or is not used. If the typedef were allowed, the #define below would cause a syntax error. */ #undef _UINT32_T /* Define for Solaris 2.5.1 so the uint64_t typedef from , - , or is not used. If the typedef was allowed, the + , or is not used. If the typedef were allowed, the #define below would cause a syntax error. */ #undef _UINT64_T From python-checkins at python.org Sat May 8 13:10:09 2010 From: python-checkins at python.org (victor.stinner) Date: Sat, 8 May 2010 13:10:09 +0200 (CEST) Subject: [Python-checkins] r80971 - in python/branches/py3k: Doc/library/os.rst Lib/os.py Lib/subprocess.py Misc/NEWS Message-ID: <20100508111009.A2C54EE982@mail.python.org> Author: victor.stinner Date: Sat May 8 13:10:09 2010 New Revision: 80971 Log: Issue #8514: Add os.fsencode() function (Unix only): encode a string to bytes for use in the file system, environment variables or the command line. Modified: python/branches/py3k/Doc/library/os.rst python/branches/py3k/Lib/os.py python/branches/py3k/Lib/subprocess.py python/branches/py3k/Misc/NEWS Modified: python/branches/py3k/Doc/library/os.rst ============================================================================== --- python/branches/py3k/Doc/library/os.rst (original) +++ python/branches/py3k/Doc/library/os.rst Sat May 8 13:10:09 2010 @@ -155,6 +155,17 @@ These functions are described in :ref:`os-file-dir`. +.. function:: fsencode(value) + + Encode *value* to bytes for use in the file system, environment variables or + the command line. Uses :func:`sys.getfilesystemencoding` and + ``'surrogateescape'`` error handler for strings and returns bytes unchanged. + + Availability: Unix. + + .. versionadded:: 3.2 + + .. function:: get_exec_path(env=None) Returns the list of directories that will be searched for a named Modified: python/branches/py3k/Lib/os.py ============================================================================== --- python/branches/py3k/Lib/os.py (original) +++ python/branches/py3k/Lib/os.py Sat May 8 13:10:09 2010 @@ -504,6 +504,17 @@ return environb.get(key, default) __all__.append("getenvb") +if name != 'nt': + def fsencode(value): + """Encode value for use in the file system, environment variables + or the command line.""" + if isinstance(value, bytes): + return value + elif isinstance(value, str): + return value.encode(sys.getfilesystemencoding(), 'surrogateescape') + else: + raise TypeError("expect bytes or str, not %s" % type(value).__name__) + def _exists(name): return name in globals() Modified: python/branches/py3k/Lib/subprocess.py ============================================================================== --- python/branches/py3k/Lib/subprocess.py (original) +++ python/branches/py3k/Lib/subprocess.py Sat May 8 13:10:09 2010 @@ -1079,32 +1079,24 @@ self._set_cloexec_flag(errpipe_write) if _posixsubprocess: - fs_encoding = sys.getfilesystemencoding() - def fs_encode(s): - """Encode s for use in the env, fs or cmdline.""" - if isinstance(s, bytes): - return s - else: - return s.encode(fs_encoding, 'surrogateescape') - # We must avoid complex work that could involve # malloc or free in the child process to avoid # potential deadlocks, thus we do all this here. # and pass it to fork_exec() if env: - env_list = [fs_encode(k) + b'=' + fs_encode(v) + env_list = [os.fsencode(k) + b'=' + os.fsencode(v) for k, v in env.items()] else: env_list = None # Use execv instead of execve. if os.path.dirname(executable): - executable_list = (fs_encode(executable),) + executable_list = (os.fsencode(executable),) else: # This matches the behavior of os._execvpe(). path_list = os.get_exec_path(env) executable_list = (os.path.join(dir, executable) for dir in path_list) - executable_list = tuple(fs_encode(exe) + executable_list = tuple(os.fsencode(exe) for exe in executable_list) self.pid = _posixsubprocess.fork_exec( args, executable_list, Modified: python/branches/py3k/Misc/NEWS ============================================================================== --- python/branches/py3k/Misc/NEWS (original) +++ python/branches/py3k/Misc/NEWS Sat May 8 13:10:09 2010 @@ -351,6 +351,9 @@ Library ------- +- Issue #8514: Add os.fsencode() function (Unix only): encode a string to bytes + for use in the file system, environment variables or the command line. + - Issue #8571: Fix an internal error when compressing or decompressing a chunk larger than 1GB with the zlib module's compressor and decompressor objects. From python-checkins at python.org Sat May 8 13:12:21 2010 From: python-checkins at python.org (victor.stinner) Date: Sat, 8 May 2010 13:12:21 +0200 (CEST) Subject: [Python-checkins] r80972 - python/branches/release31-maint Message-ID: <20100508111221.CBA96EE982@mail.python.org> Author: victor.stinner Date: Sat May 8 13:12:21 2010 New Revision: 80972 Log: Blocked revisions 80948-80950,80971 via svnmerge ........ r80948 | victor.stinner | 2010-05-08 02:07:07 +0200 (sam., 08 mai 2010) | 2 lines err_input(): don't encode/decode the unicode message ........ r80949 | victor.stinner | 2010-05-08 02:35:33 +0200 (sam., 08 mai 2010) | 3 lines PyErr_SetFromErrnoWithFilename() decodes the filename using PyUnicode_DecodeFSDefault() instead of PyUnicode_FromString() ........ r80950 | victor.stinner | 2010-05-08 02:36:42 +0200 (sam., 08 mai 2010) | 5 lines posix_error_with_allocated_filename() decodes the filename with PyUnicode_DecodeFSDefaultAndSize() and call PyErr_SetFromErrnoWithFilenameObject() instead of PyErr_SetFromErrnoWithFilename() ........ r80971 | victor.stinner | 2010-05-08 13:10:09 +0200 (sam., 08 mai 2010) | 3 lines Issue #8514: Add os.fsencode() function (Unix only): encode a string to bytes for use in the file system, environment variables or the command line. ........ Modified: python/branches/release31-maint/ (props changed) From python-checkins at python.org Sat May 8 13:12:56 2010 From: python-checkins at python.org (matthias.klose) Date: Sat, 8 May 2010 13:12:56 +0200 (CEST) Subject: [Python-checkins] r80973 - python/branches/py3k Message-ID: <20100508111256.86D3FE8E2@mail.python.org> Author: matthias.klose Date: Sat May 8 13:12:56 2010 New Revision: 80973 Log: Blocked revisions 80964-80966,80969-80970 via svnmerge ........ r80964 | matthias.klose | 2010-05-08 12:00:28 +0200 (Sa, 08 Mai 2010) | 2 lines - Issue #8510: Update to autoconf2.65. ........ r80965 | matthias.klose | 2010-05-08 12:14:46 +0200 (Sa, 08 Mai 2010) | 2 lines - configure.in: Replace AC_HELP_STRING with AS_HELP_STRING ........ r80966 | matthias.klose | 2010-05-08 12:17:27 +0200 (Sa, 08 Mai 2010) | 2 lines configure.in: s/AC_AIX/AC_USE_SYSTEM_EXTENSIONS/ ........ r80969 | matthias.klose | 2010-05-08 13:01:39 +0200 (Sa, 08 Mai 2010) | 3 lines configure.in: convert all obsolete AC_TRY_* macros to AC_*_IFELSE, only whitespace changes in generated configure (diff -uEwB). ........ r80970 | matthias.klose | 2010-05-08 13:04:18 +0200 (Sa, 08 Mai 2010) | 4 lines configure.in: Avoid autoconf warning: Assume C89 semantics that RETSIGTYPE is always void (issue #8510). pyconfig.h: Regenerate ........ Modified: python/branches/py3k/ (props changed) From nnorwitz at gmail.com Sat May 8 13:58:01 2010 From: nnorwitz at gmail.com (Neal Norwitz) Date: Sat, 8 May 2010 07:58:01 -0400 Subject: [Python-checkins] Python Regression Test Failures refleak (2) Message-ID: <20100508115801.GA15959@kbk-i386-bb.psfb.org> More important issues: ---------------------- test_bz2 leaked [84, 0, 0] references, sum=84 test_itertools leaked [32, 0, 0] references, sum=32 Less important issues: ---------------------- From python-checkins at python.org Sat May 8 15:20:07 2010 From: python-checkins at python.org (michael.foord) Date: Sat, 8 May 2010 15:20:07 +0200 (CEST) Subject: [Python-checkins] r80974 - python/trunk/Lib/unittest/test/test_discovery.py Message-ID: <20100508132007.CFAA5EE982@mail.python.org> Author: michael.foord Date: Sat May 8 15:20:07 2010 New Revision: 80974 Log: Issue 7780. Adding a test for unittest test discovery from a dotted path. Modified: python/trunk/Lib/unittest/test/test_discovery.py Modified: python/trunk/Lib/unittest/test/test_discovery.py ============================================================================== --- python/trunk/Lib/unittest/test/test_discovery.py (original) +++ python/trunk/Lib/unittest/test/test_discovery.py Sat May 8 15:20:07 2010 @@ -341,5 +341,22 @@ self.assertEqual(sys.path[0], full_path) + def test_discovery_from_dotted_path(self): + loader = unittest.TestLoader() + + tests = [self] + expectedPath = os.path.abspath(os.path.dirname(unittest.test.__file__)) + + self.wasRun = False + def _find_tests(start_dir, pattern): + self.wasRun = True + self.assertEqual(start_dir, expectedPath) + return tests + loader._find_tests = _find_tests + suite = loader.discover('unittest.test') + self.assertTrue(self.wasRun) + self.assertEqual(suite._tests, tests) + + if __name__ == '__main__': unittest.main() From python-checkins at python.org Sat May 8 15:23:31 2010 From: python-checkins at python.org (michael.foord) Date: Sat, 8 May 2010 15:23:31 +0200 (CEST) Subject: [Python-checkins] r80975 - in python/branches/py3k: Lib/unittest/test/test_discovery.py Message-ID: <20100508132331.9FF18EE982@mail.python.org> Author: michael.foord Date: Sat May 8 15:23:31 2010 New Revision: 80975 Log: Merged revisions 80974 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r80974 | michael.foord | 2010-05-08 15:20:07 +0200 (Sat, 08 May 2010) | 1 line Issue 7780. Adding a test for unittest test discovery from a dotted path. ........ Modified: python/branches/py3k/ (props changed) python/branches/py3k/Lib/unittest/test/test_discovery.py Modified: python/branches/py3k/Lib/unittest/test/test_discovery.py ============================================================================== --- python/branches/py3k/Lib/unittest/test/test_discovery.py (original) +++ python/branches/py3k/Lib/unittest/test/test_discovery.py Sat May 8 15:23:31 2010 @@ -337,5 +337,22 @@ self.assertEqual(sys.path[0], full_path) + def test_discovery_from_dotted_path(self): + loader = unittest.TestLoader() + + tests = [self] + expectedPath = os.path.abspath(os.path.dirname(unittest.test.__file__)) + + self.wasRun = False + def _find_tests(start_dir, pattern): + self.wasRun = True + self.assertEqual(start_dir, expectedPath) + return tests + loader._find_tests = _find_tests + suite = loader.discover('unittest.test') + self.assertTrue(self.wasRun) + self.assertEqual(suite._tests, tests) + + if __name__ == '__main__': unittest.main() From python-checkins at python.org Sat May 8 15:28:03 2010 From: python-checkins at python.org (andrew.kuchling) Date: Sat, 8 May 2010 15:28:03 +0200 (CEST) Subject: [Python-checkins] r80976 - python/trunk/Doc/whatsnew/2.7.rst Message-ID: <20100508132803.83DF7EE982@mail.python.org> Author: andrew.kuchling Date: Sat May 8 15:28:03 2010 New Revision: 80976 Log: Add logging.dictConfig example; give up on writing a Ttk example Modified: python/trunk/Doc/whatsnew/2.7.rst Modified: python/trunk/Doc/whatsnew/2.7.rst ============================================================================== --- python/trunk/Doc/whatsnew/2.7.rst (original) +++ python/trunk/Doc/whatsnew/2.7.rst Sat May 8 15:28:03 2010 @@ -389,7 +389,54 @@ parse a file containing JSON, or you could use a YAML parsing library if one is installed. -XXX describe an example. +The following example configures two loggers, the root logger and a +logger named "network". Messages sent to the root logger will be +sent to the system log using the syslog protocol, and messages +to the "network" logger will be written to a :file:`network.log` file +that will be rotated once the log reaches 1Mb. + +:: + + import logging + import logging.config + + configdict = { + 'version': 1, # Must be 1 at present + 'formatters': { + 'standard': { + 'format': '%(asctime)s %(name)-15s %(levelname)-8s %(message)s'}}, + + 'handlers': {'netlog': {'backupCount': 10, + 'class': 'logging.handlers.RotatingFileHandler', + 'filename': '/logs/network.log', + 'formatter': 'standard', + 'level': 'INFO', + 'maxBytes': 1024*1024}, + 'syslog': {'class': 'logging.handlers.SysLogHandler', + 'formatter': 'standard', + 'level': 'ERROR'}}, + + # Specify all the subordinate loggers + 'loggers': { + 'network': { + 'handlers': ['netlog'] + } + }, + # Specify properties of the root logger + 'root': { + 'handlers': ['syslog'] + }, + } + + # Set up configuration + logging.config.dictConfig(configdict) + + # As an example, log two error messages + logger = logging.getLogger('/') + logger.error('Database not found') + + netlogger = logging.getLogger('network') + netlogger.error('Connection failed') Three smaller enhancements to the :mod:`logging` module, all implemented by Vinay Sajip, are: @@ -1624,8 +1671,10 @@ Consult the :mod:`sysconfig` documentation for more details and for a complete list of functions. -The Distutils package and :mod:`sysconfig` are now maintained and -renamed by Tarek Ziad?. +The Distutils package and :mod:`sysconfig` are now maintained by Tarek +Ziad?, who has also started a Distutils2 package (source repository at +http://hg.python.org/distutils2/) for developing a next-generation +version of Distutils. ttk: Themed Widgets for Tk @@ -1637,7 +1686,12 @@ set was originally called Tile, but was renamed to Ttk (for "themed Tk") on being added to Tcl/Tck release 8.5. -XXX write a brief discussion and an example here. +To learn more, read the :mod:`ttk` module documentation. You may also +wish to read Tcl/Tk manual page describing the +Ttk theme engine, available at +http://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. The :mod:`ttk` module was written by Guilherme Polo and added in :issue:`2983`. An alternate version called ``Tile.py``, written by From python-checkins at python.org Sat May 8 15:29:46 2010 From: python-checkins at python.org (andrew.kuchling) Date: Sat, 8 May 2010 15:29:46 +0200 (CEST) Subject: [Python-checkins] r80977 - python/trunk/Doc/whatsnew/2.7.rst Message-ID: <20100508132946.5C2BFEE982@mail.python.org> Author: andrew.kuchling Date: Sat May 8 15:29:46 2010 New Revision: 80977 Log: Markup fixes Modified: python/trunk/Doc/whatsnew/2.7.rst Modified: python/trunk/Doc/whatsnew/2.7.rst ============================================================================== --- python/trunk/Doc/whatsnew/2.7.rst (original) +++ python/trunk/Doc/whatsnew/2.7.rst Sat May 8 15:29:46 2010 @@ -1346,7 +1346,7 @@ will execute the code at a provided *path* argument. *path* can be the path of a Python source file (:file:`example.py`), a compiled bytecode file (:file:`example.pyc`), a directory - (:file:`./package/'), or a zip archive (:file:`example.zip`). If a + (:file:`./package/`), or a zip archive (:file:`example.zip`). If a directory or zip path is provided, it will be added to the front of ``sys.path`` and the module :mod:`__main__` will be imported. It's expected that the directory or zip contains a :file:`__main__.py`; @@ -2132,7 +2132,7 @@ Python 3.1 adds a new C datatype, :ctype:`PyCapsule`, for providing a C API to an extension module. A capsule is essentially the holder for a C ``void *`` pointer, and is bound to a module attribute; for -example, the :mod:`socket` module's API is exposed as ``socket.CAPI`, +example, the :mod:`socket` module's API is exposed as ``socket.CAPI``, and :mod:`unicodedata` calls it ``ucnhash_CAPI``. Other extensions can import the module, access its dictionary to get the capsule object, and then get the ``void *`` pointer, which will usually point From python-checkins at python.org Sat May 8 16:21:23 2010 From: python-checkins at python.org (jean-paul.calderone) Date: Sat, 8 May 2010 16:21:23 +0200 (CEST) Subject: [Python-checkins] r80978 - python/branches/siginterrupt-reset-issue8354/Misc/NEWS Message-ID: <20100508142123.DBFA5F9B6@mail.python.org> Author: jean-paul.calderone Date: Sat May 8 16:21:23 2010 New Revision: 80978 Log: It\s new Modified: python/branches/siginterrupt-reset-issue8354/Misc/NEWS Modified: python/branches/siginterrupt-reset-issue8354/Misc/NEWS ============================================================================== --- python/branches/siginterrupt-reset-issue8354/Misc/NEWS (original) +++ python/branches/siginterrupt-reset-issue8354/Misc/NEWS Sat May 8 16:21:23 2010 @@ -74,6 +74,9 @@ - Issue #4687: Fix accuracy of garbage collection runtimes displayed with gc.DEBUG_STATS. +- Issue #8354: The siginterrupt setting is now preserved for all signals, + not just SIGCHLD. + - Issue #7192: webbrowser.get("firefox") now wors on Mac OS X, as does webbrowser.get("safari"). From python-checkins at python.org Sat May 8 16:35:02 2010 From: python-checkins at python.org (mark.dickinson) Date: Sat, 8 May 2010 16:35:02 +0200 (CEST) Subject: [Python-checkins] r80979 - in python/branches/py3k: Doc/library/datetime.rst Lib/test/test_datetime.py Misc/NEWS Modules/datetimemodule.c Message-ID: <20100508143502.62BF9EE9B5@mail.python.org> Author: mark.dickinson Date: Sat May 8 16:35:02 2010 New Revision: 80979 Log: Issue #8644: Improve accuracy of timedelta.total_seconds, by doing intermediate computations with integer arithmetic instead of floating point. td.total_seconds() now agrees with td / timedelta(seconds = 1). Thanks Alexander Belopolsky for the patch. Modified: python/branches/py3k/Doc/library/datetime.rst python/branches/py3k/Lib/test/test_datetime.py python/branches/py3k/Misc/NEWS python/branches/py3k/Modules/datetimemodule.c Modified: python/branches/py3k/Doc/library/datetime.rst ============================================================================== --- python/branches/py3k/Doc/library/datetime.rst (original) +++ python/branches/py3k/Doc/library/datetime.rst Sat May 8 16:35:02 2010 @@ -287,7 +287,10 @@ .. method:: timedelta.total_seconds() Return the total number of seconds contained in the duration. Equivalent to - ``td.microseconds / 1000000 + td.seconds + td.days * 24 * 3600``. + ``td / timedelta(seconds=1)``. + + Note that for very large time intervals (greater than 270 years on + most platforms) this method will lose microsecond accuracy. .. versionadded:: 3.2 Modified: python/branches/py3k/Lib/test/test_datetime.py ============================================================================== --- python/branches/py3k/Lib/test/test_datetime.py (original) +++ python/branches/py3k/Lib/test/test_datetime.py Sat May 8 16:35:02 2010 @@ -264,6 +264,11 @@ for total_seconds in [123456.789012, -123456.789012, 0.123456, 0, 1e6]: td = timedelta(seconds=total_seconds) self.assertEqual(td.total_seconds(), total_seconds) + # Issue8644: Test that td.total_seconds() has the same + # accuracy as td / timedelta(seconds=1). + for ms in [-1, -2, -123]: + td = timedelta(microseconds=ms) + self.assertEqual(td.total_seconds(), td / timedelta(seconds=1)) def test_carries(self): t1 = timedelta(days=100, Modified: python/branches/py3k/Misc/NEWS ============================================================================== --- python/branches/py3k/Misc/NEWS (original) +++ python/branches/py3k/Misc/NEWS Sat May 8 16:35:02 2010 @@ -1105,6 +1105,11 @@ Extension Modules ----------------- +- Issue #8644: The accuracy of td.total_seconds() has been improved (by + calculating with integer arithmetic instead of float arithmetic internally): + the result is now always correctly rounded, and is equivalent to td / + timedelta(seconds=1). + - Issue #2706: Allow division of a timedelta by another timedelta: timedelta / timedelta, timedelta % timedelta, timedelta // timedelta and divmod(timedelta, timedelta) are all supported. Modified: python/branches/py3k/Modules/datetimemodule.c ============================================================================== --- python/branches/py3k/Modules/datetimemodule.c (original) +++ python/branches/py3k/Modules/datetimemodule.c Sat May 8 16:35:02 2010 @@ -2211,9 +2211,25 @@ static PyObject * delta_total_seconds(PyObject *self) { - return PyFloat_FromDouble(GET_TD_MICROSECONDS(self) / 1000000.0 + - GET_TD_SECONDS(self) + - GET_TD_DAYS(self) * 24.0 * 3600.0); + PyObject *total_seconds; + PyObject *total_microseconds; + PyObject *one_million; + + total_microseconds = delta_to_microseconds((PyDateTime_Delta *)self); + if (total_microseconds == NULL) + return NULL; + + one_million = PyLong_FromLong(1000000L); + if (one_million == NULL) { + Py_DECREF(total_microseconds); + return NULL; + } + + total_seconds = PyNumber_TrueDivide(total_microseconds, one_million); + + Py_DECREF(total_microseconds); + Py_DECREF(one_million); + return total_seconds; } static PyObject * From python-checkins at python.org Sat May 8 17:09:37 2010 From: python-checkins at python.org (michael.foord) Date: Sat, 8 May 2010 17:09:37 +0200 (CEST) Subject: [Python-checkins] r80980 - python/trunk/Doc/library/unittest.rst Message-ID: <20100508150937.B5AA7EE9DC@mail.python.org> Author: michael.foord Date: Sat May 8 17:09:37 2010 New Revision: 80980 Log: Documenting test discovery from package name and potential problems with test discovery importing tests from the wrong location. Issue 7780 and issue 8547. Modified: python/trunk/Doc/library/unittest.rst Modified: python/trunk/Doc/library/unittest.rst ============================================================================== --- python/trunk/Doc/library/unittest.rst (original) +++ python/trunk/Doc/library/unittest.rst Sat May 8 17:09:37 2010 @@ -280,6 +280,27 @@ python -m unittest discover -s project_directory -p '*_test.py' python -m unittest discover project_directory '*_test.py' +As well as being a path it is possible to pass a package name, for example +``myproject.subpackage.test``, as the start directory. The package name you +supply will then be imported and its location on the filesystem will be used +as the start directory. + +.. caution:: + + Test discovery loads tests by importing them. Once test discovery has + found all the test files from the start directory you specify it turns the + paths into package names to import. For example `foo/bar/baz.py` will be + imported as ``foo.bar.baz``. + + If you have a package installed globally and attempt test discovery on + a different copy of the package then the import *could* happen from the + wrong place. If this happens test discovery will warn you and exit. + + If you supply the start directory as a package name rather than a + path to a directory then discover assumes that whichever location it + imports from is the location you intended, so you will not get the + warning. + Test modules and packages can customize test loading and discovery by through the `load_tests protocol`_. From python-checkins at python.org Sat May 8 17:13:42 2010 From: python-checkins at python.org (michael.foord) Date: Sat, 8 May 2010 17:13:42 +0200 (CEST) Subject: [Python-checkins] r80981 - in python/branches/py3k: Doc/library/unittest.rst Message-ID: <20100508151342.7F0B9EF03@mail.python.org> Author: michael.foord Date: Sat May 8 17:13:42 2010 New Revision: 80981 Log: Merged revisions 80980 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r80980 | michael.foord | 2010-05-08 17:09:37 +0200 (Sat, 08 May 2010) | 1 line Documenting test discovery from package name and potential problems with test discovery importing tests from the wrong location. Issue 7780 and issue 8547. ........ Modified: python/branches/py3k/ (props changed) python/branches/py3k/Doc/library/unittest.rst Modified: python/branches/py3k/Doc/library/unittest.rst ============================================================================== --- python/branches/py3k/Doc/library/unittest.rst (original) +++ python/branches/py3k/Doc/library/unittest.rst Sat May 8 17:13:42 2010 @@ -276,6 +276,27 @@ python -m unittest discover -s project_directory -p '*_test.py' python -m unittest discover project_directory '*_test.py' +As well as being a path it is possible to pass a package name, for example +``myproject.subpackage.test``, as the start directory. The package name you +supply will then be imported and its location on the filesystem will be used +as the start directory. + +.. caution:: + + Test discovery loads tests by importing them. Once test discovery has + found all the test files from the start directory you specify it turns the + paths into package names to import. For example `foo/bar/baz.py` will be + imported as ``foo.bar.baz``. + + If you have a package installed globally and attempt test discovery on + a different copy of the package then the import *could* happen from the + wrong place. If this happens test discovery will warn you and exit. + + If you supply the start directory as a package name rather than a + path to a directory then discover assumes that whichever location it + imports from is the location you intended, so you will not get the + warning. + Test modules and packages can customize test loading and discovery by through the `load_tests protocol`_. From python-checkins at python.org Sat May 8 17:23:57 2010 From: python-checkins at python.org (antoine.pitrou) Date: Sat, 8 May 2010 17:23:57 +0200 (CEST) Subject: [Python-checkins] r80982 - in python/trunk: Lib/distutils/unixccompiler.py Misc/NEWS setup.py Message-ID: <20100508152357.EE7BCEE986@mail.python.org> Author: antoine.pitrou Date: Sat May 8 17:23:57 2010 New Revision: 80982 Log: Revert r80963 - it broke compilation everywhere Modified: python/trunk/Lib/distutils/unixccompiler.py python/trunk/Misc/NEWS python/trunk/setup.py Modified: python/trunk/Lib/distutils/unixccompiler.py ============================================================================== --- python/trunk/Lib/distutils/unixccompiler.py (original) +++ python/trunk/Lib/distutils/unixccompiler.py Sat May 8 17:23:57 2010 @@ -15,7 +15,7 @@ __revision__ = "$Id$" -import os, sys, re +import os, sys from types import StringType, NoneType from distutils import sysconfig @@ -305,29 +305,10 @@ dylib_f = self.library_filename(lib, lib_type='dylib') static_f = self.library_filename(lib, lib_type='static') - if sys.platform == 'darwin': - # On OSX users can specify an alternate SDK using - # '-isysroot', calculate the SDK root if it is specified - # (and use it further on) - cflags = sysconfig.get_config_var('CFLAGS') - m = re.search(r'-isysroot\s+(\S+)', cflags) - if m is None: - sysroot = '/' - else: - sysroot = m.group(1) - - - for dir in dirs: shared = os.path.join(dir, shared_f) dylib = os.path.join(dir, dylib_f) static = os.path.join(dir, static_f) - - if sys.platform == 'darwin' and (dir.startswith('/System/') or dir.startswith('/usr/')): - shared = os.path.join(sysroot, dir[1:], shared_f) - dylib = os.path.join(sysroot, dir[1:], dylib_f) - static = os.path.join(sysroot, dir[1:], static_f) - # We're second-guessing the linker here, with not much hard # data to go on: GCC seems to prefer the shared library, so I'm # assuming that *all* Unix C compilers do. And of course I'm Modified: python/trunk/Misc/NEWS ============================================================================== --- python/trunk/Misc/NEWS (original) +++ python/trunk/Misc/NEWS Sat May 8 17:23:57 2010 @@ -218,9 +218,6 @@ - Issue #3646: It is now easily possible to install a Python framework into your home directory on MacOSX, see Mac/README for more information. -- Issue #7724: Building now full honors an MacOSX SDK when specified, which - makes it possible do a working build with the OSX 10.4 SDK on MacOSX 10.6. - - Issue #8510: Update to autoconf2.65. Misc Modified: python/trunk/setup.py ============================================================================== --- python/trunk/setup.py (original) +++ python/trunk/setup.py Sat May 8 17:23:57 2010 @@ -29,27 +29,6 @@ if dir is not None and os.path.isdir(dir) and dir not in dirlist: dirlist.insert(0, dir) -def macosx_sdk_root(): - """ - Return the directory of the current OSX SDK, - or '/' if no SDK was specified. - """ - cflags = sysconfig.get_config_var('CFLAGS') - m = re.search(r'-isysroot\s+(\S+)', cflags) - if m is None: - sysroot = '/' - else: - sysroot = m.group(1) - return sysroot - -def is_macosx_sdk_path(path): - """ - Returns True if 'path' can be located in an OSX SDK - """ - return path.startswith('/usr/') or path.startswith('/System/') - - - def find_file(filename, std_dirs, paths): """Searches for the directory where a given file is located, and returns a possibly-empty list of additional directories, or None @@ -61,28 +40,15 @@ 'paths' is a list of additional locations to check; if the file is found in one of them, the resulting list will contain the directory. """ - if sys.platform == 'darwin': - # Honor the MacOSX SDK setting when one was specified. - # An SDK is a directory with the same structure as a real - # system, but with only header files and libraries. - sysroot = macosx_sdk_root() # Check the standard locations for dir in std_dirs: f = os.path.join(dir, filename) - - if sys.platform == 'darwin' and is_macosx_sdk_path(dir): - f = os.path.join(sysroot, dir[1:], filename) - if os.path.exists(f): return [] # Check the additional directories for dir in paths: f = os.path.join(dir, filename) - - if sys.platform == 'darwin' and dir.startswith('/System') or dir.startswith('/usr'): - f = os.path.join(sysroot, dir[1:], filename) - if os.path.exists(f): return [dir] @@ -94,19 +60,11 @@ if result is None: return None - if sys.platform == 'darwin': - sysroot = macosx_sdk_root() - # Check whether the found file is in one of the standard directories dirname = os.path.dirname(result) for p in std_dirs: # Ensure path doesn't end with path separator p = p.rstrip(os.sep) - - if sys.platform == 'darwin' and is_macosx_sdk_path(p): - if os.path.join(sysroot, p[1:]) == dirname: - return [ ] - if p == dirname: return [ ] @@ -115,11 +73,6 @@ for p in paths: # Ensure path doesn't end with path separator p = p.rstrip(os.sep) - - if sys.platform == 'darwin' and is_macosx_sdk_path(p): - if os.path.join(sysroot, p[1:]) == dirname: - return [ p ] - if p == dirname: return [p] else: @@ -607,7 +560,7 @@ # library and then a static library, instead of first looking # for dynamic libraries on the entiry path. # This way a staticly linked custom readline gets picked up - # before the (possibly broken) dynamic library in /usr/lib. + # before the (broken) dynamic library in /usr/lib. readline_extra_link_args = ('-Wl,-search_paths_first',) else: readline_extra_link_args = () @@ -678,20 +631,24 @@ openssl_ver = 0 openssl_ver_re = re.compile( '^\s*#\s*define\s+OPENSSL_VERSION_NUMBER\s+(0x[0-9a-fA-F]+)' ) + for ssl_inc_dir in inc_dirs + search_for_ssl_incs_in: + name = os.path.join(ssl_inc_dir, 'openssl', 'opensslv.h') + if os.path.isfile(name): + try: + incfile = open(name, 'r') + for line in incfile: + m = openssl_ver_re.match(line) + if m: + openssl_ver = eval(m.group(1)) + break + except IOError: + pass - # look for the openssl version header on the compiler search path. - opensslv_h = find_file('openssl/opensslv.h', inc_dirs, search_for_ssl_incs_in) - if opensslv_h: - name = opensslv_h[0] - try: - incfile = open(name, 'r') - for line in incfile: - m = openssl_ver_re.match(line) - if m: - openssl_ver = eval(m.group(1)) - except IOError: - pass + # first version found is what we'll use (as the compiler should) + if openssl_ver: + break + #print 'openssl_ver = 0x%08x' % openssl_ver min_openssl_ver = 0x00907000 have_any_openssl = ssl_incs is not None and ssl_libs is not None have_usable_openssl = (have_any_openssl and @@ -824,19 +781,12 @@ db_ver_inc_map = {} - if sys.platform == 'darwin': - sysroot = macosx_sdk_root() - class db_found(Exception): pass try: # See whether there is a Sleepycat header in the standard # search path. for d in inc_dirs + db_inc_paths: f = os.path.join(d, "db.h") - - if sys.platform == 'darwin' and is_macosx_sdk_path(d): - f = os.path.join(sysroot, d[1:], "db.h") - if db_setup_debug: print "db: looking for db.h in", f if os.path.exists(f): f = open(f).read() @@ -883,20 +833,7 @@ db_incdir.replace("include", 'lib64'), db_incdir.replace("include", 'lib'), ] - - if sys.platform != 'darwin': - db_dirs_to_check = filter(os.path.isdir, db_dirs_to_check) - - else: - # Same as other branch, but takes OSX SDK into account - tmp = [] - for dn in db_dirs_to_check: - if is_macosx_sdk_path(dn): - if os.path.isdir(os.path.join(sysroot, dn[1:])): - tmp.append(dn) - else: - if os.path.isdir(dn): - tmp.append(dn) + db_dirs_to_check = filter(os.path.isdir, db_dirs_to_check) # Look for a version specific db-X.Y before an ambiguoius dbX # XXX should we -ever- look for a dbX name? Do any @@ -958,15 +895,8 @@ # Scan the default include directories before the SQLite specific # ones. This allows one to override the copy of sqlite on OSX, # where /usr/include contains an old version of sqlite. - if sys.platform == 'darwin': - sysroot = macosx_sdk_root() - for d in inc_dirs + sqlite_inc_paths: f = os.path.join(d, "sqlite3.h") - - if sys.platform == 'darwin' and is_macosx_sdk_path(d): - f = os.path.join(sysroot, d[1:], "sqlite3.h") - if os.path.exists(f): if sqlite_setup_debug: print "sqlite: found %s"%f incf = open(f).read() @@ -1054,12 +984,6 @@ # the more recent berkeleydb's db.h file first in the include path # when attempting to compile and it will fail. f = "/usr/include/db.h" - - if sys.platform == 'darwin': - if is_macosx_sdk_path(f): - sysroot = macosx_sdk_root() - f = os.path.join(sysroot, f[1:]) - if os.path.exists(f) and not db_incs: data = open(f).read() m = re.search(r"#s*define\s+HASHVERSION\s+2\s*", data) @@ -1566,22 +1490,14 @@ join(os.getenv('HOME'), '/Library/Frameworks') ] - sysroot = macosx_sdk_root() - # Find the directory that contains the Tcl.framework and Tk.framework # bundles. # XXX distutils should support -F! for F in framework_dirs: # both Tcl.framework and Tk.framework should be present - - for fw in 'Tcl', 'Tk': - if is_macosx_sdk_path(F): - if not exists(join(sysroot, F[1:], fw + '.framework')): - break - else: - if not exists(join(F, fw + '.framework')): - break + if not exists(join(F, fw + '.framework')): + break else: # ok, F is now directory with both frameworks. Continure # building @@ -1611,12 +1527,7 @@ # architectures. cflags = sysconfig.get_config_vars('CFLAGS')[0] archs = re.findall('-arch\s+(\w+)', cflags) - - if is_macosx_sdk_path(F): - fp = os.popen("file %s/Tk.framework/Tk | grep 'for architecture'"%(os.path.join(sysroot, F[1:]),)) - else: - fp = os.popen("file %s/Tk.framework/Tk | grep 'for architecture'"%(F,)) - + fp = os.popen("file %s/Tk.framework/Tk | grep 'for architecture'"%(F,)) detected_archs = [] for ln in fp: a = ln.split()[-1] From python-checkins at python.org Sat May 8 17:26:30 2010 From: python-checkins at python.org (benjamin.peterson) Date: Sat, 8 May 2010 17:26:30 +0200 (CEST) Subject: [Python-checkins] r80983 - python/branches/py3k/Doc/library/weakref.rst Message-ID: <20100508152630.9D603EE98B@mail.python.org> Author: benjamin.peterson Date: Sat May 8 17:26:30 2010 New Revision: 80983 Log: replace long with int Modified: python/branches/py3k/Doc/library/weakref.rst Modified: python/branches/py3k/Doc/library/weakref.rst ============================================================================== --- python/branches/py3k/Doc/library/weakref.rst (original) +++ python/branches/py3k/Doc/library/weakref.rst Sat May 8 17:26:30 2010 @@ -72,9 +72,9 @@ obj = Dict(red=1, green=2, blue=3) # this object is weak referenceable -Other built-in types such as :class:`tuple` and :class:`long` do not support -weak references even when subclassed (This is an implementation detail and may -be different across various Python implementations.). +Other built-in types such as :class:`tuple` and :class:`int` do not support weak +references even when subclassed (This is an implementation detail and may be +different across various Python implementations.). Extension types can easily be made to support weak references; see :ref:`weakref-support`. From python-checkins at python.org Sat May 8 17:29:41 2010 From: python-checkins at python.org (benjamin.peterson) Date: Sat, 8 May 2010 17:29:41 +0200 (CEST) Subject: [Python-checkins] r80984 - in python/branches/release31-maint: Doc/library/weakref.rst Message-ID: <20100508152941.8E4FCEE98B@mail.python.org> Author: benjamin.peterson Date: Sat May 8 17:29:41 2010 New Revision: 80984 Log: Merged revisions 80983 via svnmerge from svn+ssh://pythondev at svn.python.org/python/branches/py3k ........ r80983 | benjamin.peterson | 2010-05-08 10:26:30 -0500 (Sat, 08 May 2010) | 1 line replace long with int ........ Modified: python/branches/release31-maint/ (props changed) python/branches/release31-maint/Doc/library/weakref.rst Modified: python/branches/release31-maint/Doc/library/weakref.rst ============================================================================== --- python/branches/release31-maint/Doc/library/weakref.rst (original) +++ python/branches/release31-maint/Doc/library/weakref.rst Sat May 8 17:29:41 2010 @@ -69,9 +69,9 @@ obj = Dict(red=1, green=2, blue=3) # this object is weak referenceable -Other built-in types such as :class:`tuple` and :class:`long` do not support -weak references even when subclassed (This is an implementation detail and may -be different across various Python implementations.). +Other built-in types such as :class:`tuple` and :class:`int` do not support weak +references even when subclassed (This is an implementation detail and may be +different across various Python implementations.). Extension types can easily be made to support weak references; see :ref:`weakref-support`. From python-checkins at python.org Sat May 8 17:39:46 2010 From: python-checkins at python.org (andrew.kuchling) Date: Sat, 8 May 2010 17:39:46 +0200 (CEST) Subject: [Python-checkins] r80985 - python/trunk/Doc/whatsnew/2.7.rst Message-ID: <20100508153946.873E0C7F5@mail.python.org> Author: andrew.kuchling Date: Sat May 8 17:39:46 2010 New Revision: 80985 Log: Write summary of the 2.7 release; rewrite the future section some more; mention PYTHONWARNINGS env. var; tweak some examples for readability. And with this commit, the "What's New" is done... except for a complete read-through to polish the text, and fixing any reported errors, but those tasks can easily wait until after beta2. Modified: python/trunk/Doc/whatsnew/2.7.rst Modified: python/trunk/Doc/whatsnew/2.7.rst ============================================================================== --- python/trunk/Doc/whatsnew/2.7.rst (original) +++ python/trunk/Doc/whatsnew/2.7.rst Sat May 8 17:39:46 2010 @@ -6,12 +6,10 @@ :Release: |release| :Date: |today| -.. Big jobs: pep 391 example - .. hyperlink all the methods & functions. .. T_STRING_INPLACE not described in main docs -.. XXX "Format String Syntax" in string.rst could use many more examples. +.. "Format String Syntax" in string.rst could use many more examples. .. $Id$ Rules for maintenance: @@ -58,8 +56,27 @@ release of 2.7 is currently scheduled for July 2010; the detailed schedule is described in :pep:`373`. -.. Compare with previous release in 2 - 3 sentences here. - add hyperlink when the documentation becomes available online. +Python 2.7 is planned to be the last of the 2.x releases, so we worked +on making it a good release for the long term. To help with porting +to Python 3, several new features from the Python 3.x series have been +included in 2.7. + +Numeric handling has been improved in many ways, both for +floating-point numbers and for the :class:`Decimal` class. There are +some useful additions to the standard library, such as a greatly +enhanced :mod:`unittest` module, the :mod:`argparse` module for +parsing command-line options, convenient ordered-dictionary and +:class:`Counter` classes in the :mod:`collections` module, and many +other improvements. + +This article doesn't attempt to provide a complete specification of +the new features, but instead provides a convenient overview. For +full details, you should refer to the documentation for Python 2.7 at +http://docs.python.org. If you want to understand the rationale for +the design and implementation, refer to the PEP for a particular new +feature or the issue on http://bugs.python.org in which a change was +discussed. Whenever possible, "What's New in Python" links to the +bug/patch item for each change. .. _whatsnew27-python31: @@ -76,15 +93,16 @@ * It's very likely the 2.7 release will have a longer period of maintenance compared to earlier 2.x versions. Python 2.7 will - continue to be maintained while the transition to 3.x continues. - Maintenance releases for Python 2.7 will probably be made for 5 - years. + continue to be maintained while the transition to 3.x continues, and + the developers are planning to support Python 2.7 with bug-fix + releases beyond the typical two years. * A policy decision was made to silence warnings only of interest to developers by default. :exc:`DeprecationWarning` and its descendants are now ignored unless otherwise requested, preventing - users from seeing warnings triggered by an application. (Carried - out in :issue:`7319`.) + users from seeing warnings triggered by an application. This change + was also made in the branch that will become Python 3.2. (Discussed + on stdlib-sig and carried out in :issue:`7319`.) In previous releases, :exc:`DeprecationWarning` messages were enabled by default, providing Python developers with a clear @@ -100,8 +118,10 @@ You can re-enable display of :exc:`DeprecationWarning` messages by running Python with the :option:`-Wdefault` (short form: - :option:`-Wd`) switch, or you can add - ``warnings.simplefilter('default')`` to your code. + :option:`-Wd`) switch, or by setting the :envvar:`PYTHONWARNINGS` + environment variable to ``"default"`` or ``"d"``) before running + Python. Python code can also re-enable them + by calling ``warnings.simplefilter('default')``. Python 3.1 Features @@ -114,6 +134,9 @@ A partial list of 3.1 features that were backported to 2.7: +* The syntax for set literals (``{1,2,3}`` is a mutable set). +* Dictionary and set comprehensions (``{ i: i*2 for i in range(3)}``). +* Multiple context managers in * A new version of the :mod:`io` library, rewritten in C for performance. * The ordered-dictionary type described in :ref:`pep-0372`. * The new format specifier described in :ref:`pep-0378`. @@ -602,9 +625,9 @@ 3.x, generalizing list/generator comprehensions to use the literal syntax for sets and dictionaries. - >>> {x:x*x for x in range(6)} + >>> {x: x*x for x in range(6)} {0: 0, 1: 1, 2: 4, 3: 9, 4: 16, 5: 25} - >>> {'a'*x for x in range(6)} + >>> {('a'*x) for x in range(6)} set(['', 'a', 'aa', 'aaa', 'aaaa', 'aaaaa']) Backported by Alexandre Vassalotti; :issue:`2333`. @@ -2368,5 +2391,6 @@ The author would like to thank the following people for offering suggestions, corrections and assistance with various drafts of this -article: Nick Coghlan, Ryan Lovett, R. David Murray, Hugh Secker-Walker. +article: Nick Coghlan, Philip Jenvey, Ryan Lovett, R. David Murray, +Hugh Secker-Walker. From python-checkins at python.org Sat May 8 17:41:45 2010 From: python-checkins at python.org (benjamin.peterson) Date: Sat, 8 May 2010 17:41:45 +0200 (CEST) Subject: [Python-checkins] r80986 - python/trunk/Lib/test/test_sysconfig.py Message-ID: <20100508154145.05C6BEE986@mail.python.org> Author: benjamin.peterson Date: Sat May 8 17:41:44 2010 New Revision: 80986 Log: r80967 introduced a new scheme Modified: python/trunk/Lib/test/test_sysconfig.py Modified: python/trunk/Lib/test/test_sysconfig.py ============================================================================== --- python/trunk/Lib/test/test_sysconfig.py (original) +++ python/trunk/Lib/test/test_sysconfig.py Sat May 8 17:41:44 2010 @@ -235,8 +235,8 @@ self.assertTrue(os.path.isfile(config_h), config_h) def test_get_scheme_names(self): - wanted = ('nt', 'nt_user', 'os2', 'os2_home', 'posix_home', - 'posix_prefix', 'posix_user') + wanted = ('nt', 'nt_user', 'os2', 'os2_home', 'osx_frameworkuser', + 'posix_home', 'posix_prefix', 'posix_user') self.assertEquals(get_scheme_names(), wanted) def test_symlink(self): From python-checkins at python.org Sat May 8 17:42:30 2010 From: python-checkins at python.org (benjamin.peterson) Date: Sat, 8 May 2010 17:42:30 +0200 (CEST) Subject: [Python-checkins] r80987 - python/trunk/Lib/test/test_sysconfig.py Message-ID: <20100508154230.0C964EE988@mail.python.org> Author: benjamin.peterson Date: Sat May 8 17:42:29 2010 New Revision: 80987 Log: add underscore Modified: python/trunk/Lib/test/test_sysconfig.py Modified: python/trunk/Lib/test/test_sysconfig.py ============================================================================== --- python/trunk/Lib/test/test_sysconfig.py (original) +++ python/trunk/Lib/test/test_sysconfig.py Sat May 8 17:42:29 2010 @@ -235,7 +235,7 @@ self.assertTrue(os.path.isfile(config_h), config_h) def test_get_scheme_names(self): - wanted = ('nt', 'nt_user', 'os2', 'os2_home', 'osx_frameworkuser', + wanted = ('nt', 'nt_user', 'os2', 'os2_home', 'osx_framework_user', 'posix_home', 'posix_prefix', 'posix_user') self.assertEquals(get_scheme_names(), wanted) From python-checkins at python.org Sat May 8 17:46:01 2010 From: python-checkins at python.org (benjamin.peterson) Date: Sat, 8 May 2010 17:46:01 +0200 (CEST) Subject: [Python-checkins] r80988 - in python/branches/release31-maint: Lib/lib2to3/fixes/fix_import.py Lib/lib2to3/fixes/fix_operator.py Lib/lib2to3/fixes/fix_reduce.py Lib/lib2to3/fixes/fix_tuple_params.py Lib/lib2to3/fixes/fix_xrange.py Lib/lib2to3/main.py Lib/lib2to3/pgen2/tokenize.py Lib/lib2to3/pytree.py Lib/lib2to3/refactor.py Lib/lib2to3/tests/test_fixers.py Lib/lib2to3/tests/test_parser.py Lib/lib2to3/tests/test_pytree.py Lib/lib2to3/tests/test_refactor.py Message-ID: <20100508154601.426F2DE2D@mail.python.org> Author: benjamin.peterson Date: Sat May 8 17:46:00 2010 New Revision: 80988 Log: Merged revisions 80936 via svnmerge from svn+ssh://pythondev at svn.python.org/python/branches/py3k ................ r80936 | benjamin.peterson | 2010-05-07 14:10:11 -0500 (Fri, 07 May 2010) | 76 lines Merged revisions 80934 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ................ r80934 | benjamin.peterson | 2010-05-07 13:58:23 -0500 (Fri, 07 May 2010) | 69 lines Merged revisions 79911,79916-79917,80018,80418,80572-80573,80635-80639,80668,80922 via svnmerge from svn+ssh://pythondev at svn.python.org/sandbox/trunk/2to3/lib2to3 ........ r79911 | benjamin.peterson | 2010-04-09 15:38:53 -0500 (Fri, 09 Apr 2010) | 1 line use absolute import ........ r79916 | benjamin.peterson | 2010-04-09 16:05:21 -0500 (Fri, 09 Apr 2010) | 1 line generalize detection of __future__ imports and attach them to the tree ........ r79917 | benjamin.peterson | 2010-04-09 16:11:44 -0500 (Fri, 09 Apr 2010) | 1 line don't try to 'fix' relative imports when absolute_import is enabled #8858 ........ r80018 | benjamin.peterson | 2010-04-12 16:12:12 -0500 (Mon, 12 Apr 2010) | 4 lines prevent diffs from being mangled is multiprocess mode #6409 Patch by George Boutsioukis. ........ r80418 | benjamin.peterson | 2010-04-23 16:00:03 -0500 (Fri, 23 Apr 2010) | 1 line remove unhelpful description ........ r80572 | benjamin.peterson | 2010-04-27 20:33:54 -0500 (Tue, 27 Apr 2010) | 1 line use unicode literals ........ r80573 | jeffrey.yasskin | 2010-04-27 23:08:27 -0500 (Tue, 27 Apr 2010) | 6 lines Don't transform imports that are already relative. 2to3 turned from . import refactor into from .. import refactor which broke the transformation of 2to3 itself. ........ r80635 | benjamin.peterson | 2010-04-29 16:02:23 -0500 (Thu, 29 Apr 2010) | 1 line remove imports ........ r80636 | benjamin.peterson | 2010-04-29 16:02:41 -0500 (Thu, 29 Apr 2010) | 1 line unicode literal ........ r80637 | benjamin.peterson | 2010-04-29 16:03:42 -0500 (Thu, 29 Apr 2010) | 1 line must pass a string to Number ........ r80638 | benjamin.peterson | 2010-04-29 16:05:34 -0500 (Thu, 29 Apr 2010) | 1 line unicode literals ........ r80639 | benjamin.peterson | 2010-04-29 16:06:09 -0500 (Thu, 29 Apr 2010) | 1 line pass string to Number ........ r80668 | jeffrey.yasskin | 2010-04-30 18:02:47 -0500 (Fri, 30 Apr 2010) | 4 lines Make 2to3 run under Python 2.5 so that the benchmark suite at http://hg.python.org/benchmarks/ can use it and still run on implementations that haven't gotten to 2.6 yet. Fixes issue 8566. ........ r80922 | benjamin.peterson | 2010-05-07 11:06:25 -0500 (Fri, 07 May 2010) | 1 line prevent xrange transformation from wrapping range calls it produces in list ........ ................ ................ Modified: python/branches/release31-maint/ (props changed) python/branches/release31-maint/Lib/lib2to3/fixes/fix_import.py python/branches/release31-maint/Lib/lib2to3/fixes/fix_operator.py python/branches/release31-maint/Lib/lib2to3/fixes/fix_reduce.py python/branches/release31-maint/Lib/lib2to3/fixes/fix_tuple_params.py python/branches/release31-maint/Lib/lib2to3/fixes/fix_xrange.py python/branches/release31-maint/Lib/lib2to3/main.py python/branches/release31-maint/Lib/lib2to3/pgen2/tokenize.py python/branches/release31-maint/Lib/lib2to3/pytree.py python/branches/release31-maint/Lib/lib2to3/refactor.py python/branches/release31-maint/Lib/lib2to3/tests/test_fixers.py python/branches/release31-maint/Lib/lib2to3/tests/test_parser.py python/branches/release31-maint/Lib/lib2to3/tests/test_pytree.py python/branches/release31-maint/Lib/lib2to3/tests/test_refactor.py Modified: python/branches/release31-maint/Lib/lib2to3/fixes/fix_import.py ============================================================================== --- python/branches/release31-maint/Lib/lib2to3/fixes/fix_import.py (original) +++ python/branches/release31-maint/Lib/lib2to3/fixes/fix_import.py Sat May 8 17:46:00 2010 @@ -43,7 +43,13 @@ import_name< 'import' imp=any > """ + def start_tree(self, tree, name): + super(FixImport, self).start_tree(tree, name) + self.skip = "absolute_import" in tree.future_features + def transform(self, node, results): + if self.skip: + return imp = results['imp'] if node.type == syms.import_from: @@ -71,19 +77,22 @@ self.warning(node, "absolute and local imports together") return - new = FromImport('.', [imp]) + new = FromImport(".", [imp]) new.prefix = node.prefix return new def probably_a_local_import(self, imp_name): - imp_name = imp_name.split('.', 1)[0] + if imp_name.startswith("."): + # Relative imports are certainly not local imports. + return False + imp_name = imp_name.split(".", 1)[0] base_path = dirname(self.filename) base_path = join(base_path, imp_name) # If there is no __init__.py next to the file its not in a package # so can't be a relative import. - if not exists(join(dirname(base_path), '__init__.py')): + if not exists(join(dirname(base_path), "__init__.py")): return False - for ext in ['.py', sep, '.pyc', '.so', '.sl', '.pyd']: + for ext in [".py", sep, ".pyc", ".so", ".sl", ".pyd"]: if exists(base_path + ext): return True return False Modified: python/branches/release31-maint/Lib/lib2to3/fixes/fix_operator.py ============================================================================== --- python/branches/release31-maint/Lib/lib2to3/fixes/fix_operator.py (original) +++ python/branches/release31-maint/Lib/lib2to3/fixes/fix_operator.py Sat May 8 17:46:00 2010 @@ -14,10 +14,10 @@ func = "'(' func=any ')'" PATTERN = """ power< module='operator' - trailer< '.' {methods} > trailer< {func} > > + trailer< '.' %(methods)s > trailer< %(func)s > > | - power< {methods} trailer< {func} > > - """.format(methods=methods, func=func) + power< %(methods)s trailer< %(func)s > > + """ % dict(methods=methods, func=func) def transform(self, node, results): method = results["method"][0] Modified: python/branches/release31-maint/Lib/lib2to3/fixes/fix_reduce.py ============================================================================== --- python/branches/release31-maint/Lib/lib2to3/fixes/fix_reduce.py (original) +++ python/branches/release31-maint/Lib/lib2to3/fixes/fix_reduce.py Sat May 8 17:46:00 2010 @@ -7,9 +7,8 @@ used in that module. """ -from .. import pytree -from .. import fixer_base -from ..fixer_util import Name, Attr, touch_import +from lib2to3 import fixer_base +from lib2to3.fixer_util import touch_import Modified: python/branches/release31-maint/Lib/lib2to3/fixes/fix_tuple_params.py ============================================================================== --- python/branches/release31-maint/Lib/lib2to3/fixes/fix_tuple_params.py (original) +++ python/branches/release31-maint/Lib/lib2to3/fixes/fix_tuple_params.py Sat May 8 17:46:00 2010 @@ -154,7 +154,7 @@ if d is None: d = {} for i, obj in enumerate(param_list): - trailer = [Subscript(Number(i))] + trailer = [Subscript(Number(str(i)))] if isinstance(obj, list): map_to_index(obj, trailer, d=d) else: Modified: python/branches/release31-maint/Lib/lib2to3/fixes/fix_xrange.py ============================================================================== --- python/branches/release31-maint/Lib/lib2to3/fixes/fix_xrange.py (original) +++ python/branches/release31-maint/Lib/lib2to3/fixes/fix_xrange.py Sat May 8 17:46:00 2010 @@ -17,6 +17,13 @@ rest=any* > """ + def start_tree(self, tree, filename): + super(FixXrange, self).start_tree(tree, filename) + self.transformed_xranges = set() + + def finish_tree(self, tree, filename): + self.transformed_xranges = None + def transform(self, node, results): name = results["name"] if name.value == "xrange": @@ -29,9 +36,12 @@ def transform_xrange(self, node, results): name = results["name"] name.replace(Name("range", prefix=name.prefix)) + # This prevents the new range call from being wrapped in a list later. + self.transformed_xranges.add(id(node)) def transform_range(self, node, results): - if not self.in_special_context(node): + if (id(node) not in self.transformed_xranges and + not self.in_special_context(node)): range_call = Call(Name("range"), [results["args"].clone()]) # Encase the range call in list(). list_call = Call(Name("list"), [range_call], Modified: python/branches/release31-maint/Lib/lib2to3/main.py ============================================================================== --- python/branches/release31-maint/Lib/lib2to3/main.py (original) +++ python/branches/release31-maint/Lib/lib2to3/main.py Sat May 8 17:46:00 2010 @@ -2,6 +2,8 @@ Main program for 2to3. """ +from __future__ import with_statement + import sys import os import difflib @@ -62,8 +64,14 @@ if self.show_diffs: diff_lines = diff_texts(old, new, filename) try: - for line in diff_lines: - print(line) + if self.output_lock is not None: + with self.output_lock: + for line in diff_lines: + print(line) + sys.stdout.flush() + else: + for line in diff_lines: + print(line) except UnicodeEncodeError: warn("couldn't encode %s's diff for your terminal" % (filename,)) @@ -94,7 +102,7 @@ parser.add_option("-x", "--nofix", action="append", default=[], help="Prevent a fixer from being run.") parser.add_option("-l", "--list-fixes", action="store_true", - help="List available transformations (fixes/fix_*.py)") + help="List available transformations") parser.add_option("-p", "--print-function", action="store_true", help="Modify the grammar so that print() is a function") parser.add_option("-v", "--verbose", action="store_true", Modified: python/branches/release31-maint/Lib/lib2to3/pgen2/tokenize.py ============================================================================== --- python/branches/release31-maint/Lib/lib2to3/pgen2/tokenize.py (original) +++ python/branches/release31-maint/Lib/lib2to3/pgen2/tokenize.py Sat May 8 17:46:00 2010 @@ -38,6 +38,13 @@ "generate_tokens", "untokenize"] del token +try: + bytes +except NameError: + # Support bytes type in Python <= 2.5, so 2to3 turns itself into + # valid Python 3 code. + bytes = str + def group(*choices): return '(' + '|'.join(choices) + ')' def any(*choices): return group(*choices) + '*' def maybe(*choices): return group(*choices) + '?' @@ -267,7 +274,7 @@ try: return readline() except StopIteration: - return b'' + return bytes() def find_cookie(line): try: Modified: python/branches/release31-maint/Lib/lib2to3/pytree.py ============================================================================== --- python/branches/release31-maint/Lib/lib2to3/pytree.py (original) +++ python/branches/release31-maint/Lib/lib2to3/pytree.py Sat May 8 17:46:00 2010 @@ -289,8 +289,7 @@ for node in child.post_order(): yield node - @property - def prefix(self): + def _prefix_getter(self): """ The whitespace and comments preceding this node in the input. """ @@ -298,11 +297,12 @@ return "" return self.children[0].prefix - @prefix.setter - def prefix(self, prefix): + def _prefix_setter(self, prefix): if self.children: self.children[0].prefix = prefix + prefix = property(_prefix_getter, _prefix_setter) + def set_child(self, i, child): """ Equivalent to 'node.children[i] = child'. This method also sets the @@ -390,18 +390,17 @@ """Return a pre-order iterator for the tree.""" yield self - @property - def prefix(self): + def _prefix_getter(self): """ The whitespace and comments preceding this token in the input. """ return self._prefix - @prefix.setter - def prefix(self, prefix): + def _prefix_setter(self, prefix): self.changed() self._prefix = prefix + prefix = property(_prefix_getter, _prefix_setter) def convert(gr, raw_node): """ Modified: python/branches/release31-maint/Lib/lib2to3/refactor.py ============================================================================== --- python/branches/release31-maint/Lib/lib2to3/refactor.py (original) +++ python/branches/release31-maint/Lib/lib2to3/refactor.py Sat May 8 17:46:00 2010 @@ -8,6 +8,8 @@ provides infrastructure to write your own refactoring tool. """ +from __future__ import with_statement + __author__ = "Guido van Rossum " @@ -122,13 +124,14 @@ _to_system_newlines = _identity -def _detect_future_print(source): +def _detect_future_features(source): have_docstring = False gen = tokenize.generate_tokens(io.StringIO(source).readline) def advance(): tok = next(gen) return tok[0], tok[1] ignore = frozenset((token.NEWLINE, tokenize.NL, token.COMMENT)) + features = set() try: while True: tp, value = advance() @@ -140,26 +143,25 @@ have_docstring = True elif tp == token.NAME and value == "from": tp, value = advance() - if tp != token.NAME and value != "__future__": + if tp != token.NAME or value != "__future__": break tp, value = advance() - if tp != token.NAME and value != "import": + if tp != token.NAME or value != "import": break tp, value = advance() if tp == token.OP and value == "(": tp, value = advance() while tp == token.NAME: - if value == "print_function": - return True + features.add(value) tp, value = advance() - if tp != token.OP and value != ",": + if tp != token.OP or value != ",": break tp, value = advance() else: break except StopIteration: pass - return False + return frozenset(features) class FixerError(Exception): @@ -341,7 +343,8 @@ An AST corresponding to the refactored input stream; None if there were errors during the parse. """ - if _detect_future_print(data): + features = _detect_future_features(data) + if "print_function" in features: self.driver.grammar = pygram.python_grammar_no_print_statement try: tree = self.driver.parse_string(data) @@ -351,6 +354,7 @@ return finally: self.driver.grammar = self.grammar + tree.future_features = features self.log_debug("Refactoring %s", name) self.refactor_tree(tree, name) return tree @@ -605,6 +609,7 @@ def __init__(self, *args, **kwargs): super(MultiprocessRefactoringTool, self).__init__(*args, **kwargs) self.queue = None + self.output_lock = None def refactor(self, items, write=False, doctests_only=False, num_processes=1): @@ -618,6 +623,7 @@ if self.queue is not None: raise RuntimeError("already doing multiple processes") self.queue = multiprocessing.JoinableQueue() + self.output_lock = multiprocessing.Lock() processes = [multiprocessing.Process(target=self._child) for i in range(num_processes)] try: Modified: python/branches/release31-maint/Lib/lib2to3/tests/test_fixers.py ============================================================================== --- python/branches/release31-maint/Lib/lib2to3/tests/test_fixers.py (original) +++ python/branches/release31-maint/Lib/lib2to3/tests/test_fixers.py Sat May 8 17:46:00 2010 @@ -1497,6 +1497,17 @@ for call in fixer_util.consuming_calls: self.unchanged("a = %s(range(10))" % call) +class Test_xrange_with_reduce(FixerTestCase): + + def setUp(self): + super(Test_xrange_with_reduce, self).setUp(["xrange", "reduce"]) + + def test_double_transform(self): + b = """reduce(x, xrange(5))""" + a = """from functools import reduce +reduce(x, range(5))""" + self.check(b, a) + class Test_raw_input(FixerTestCase): fixer = "raw_input" @@ -3679,7 +3690,7 @@ self.files_checked.append(name) return self.always_exists or (name in self.present_files) - from ..fixes import fix_import + from lib2to3.fixes import fix_import fix_import.exists = fake_exists def tearDown(self): @@ -3722,6 +3733,12 @@ self.present_files = set(["bar.py"]) self.unchanged(s) + def test_with_absolute_import_enabled(self): + s = "from __future__ import absolute_import\nimport bar" + self.always_exists = False + self.present_files = set(["__init__.py", "bar.py"]) + self.unchanged(s) + def test_in_package(self): b = "import bar" a = "from . import bar" @@ -3736,6 +3753,10 @@ self.present_files = set(["__init__.py", "bar" + os.path.sep]) self.check(b, a) + def test_already_relative_import(self): + s = "from . import bar" + self.unchanged(s) + def test_comments_and_indent(self): b = "import bar # Foo" a = "from . import bar # Foo" Modified: python/branches/release31-maint/Lib/lib2to3/tests/test_parser.py ============================================================================== --- python/branches/release31-maint/Lib/lib2to3/tests/test_parser.py (original) +++ python/branches/release31-maint/Lib/lib2to3/tests/test_parser.py Sat May 8 17:46:00 2010 @@ -6,6 +6,8 @@ test_grammar.py files from both Python 2 and Python 3. """ +from __future__ import with_statement + # Testing imports from . import support from .support import driver, test_dir @@ -149,10 +151,11 @@ for filepath in support.all_project_files(): with open(filepath, "rb") as fp: encoding = tokenize.detect_encoding(fp.readline)[0] - fp.seek(0) + self.assertTrue(encoding is not None, + "can't detect encoding for %s" % filepath) + with open(filepath, "r") as fp: source = fp.read() - if encoding: - source = source.decode(encoding) + source = source.decode(encoding) tree = driver.parse_string(source) new = str(tree) if encoding: @@ -199,10 +202,10 @@ self.validate(s) -def diff(fn, result): - f = open("@", "wb") +def diff(fn, result, encoding): + f = open("@", "w") try: - f.write(result) + f.write(result.encode(encoding)) finally: f.close() try: Modified: python/branches/release31-maint/Lib/lib2to3/tests/test_pytree.py ============================================================================== --- python/branches/release31-maint/Lib/lib2to3/tests/test_pytree.py (original) +++ python/branches/release31-maint/Lib/lib2to3/tests/test_pytree.py Sat May 8 17:46:00 2010 @@ -9,6 +9,9 @@ especially when debugging a test. """ +from __future__ import with_statement + +import sys import warnings # Testing imports @@ -28,20 +31,22 @@ """Unit tests for nodes (Base, Leaf, Node).""" - def test_deprecated_prefix_methods(self): - l = pytree.Leaf(100, "foo") - with warnings.catch_warnings(record=True) as w: - warnings.simplefilter("always", DeprecationWarning) - self.assertEqual(l.get_prefix(), "") - l.set_prefix("hi") - self.assertEqual(l.prefix, "hi") - self.assertEqual(len(w), 2) - for warning in w: - self.assertTrue(warning.category is DeprecationWarning) - self.assertEqual(str(w[0].message), "get_prefix() is deprecated; " \ - "use the prefix property") - self.assertEqual(str(w[1].message), "set_prefix() is deprecated; " \ - "use the prefix property") + if sys.version_info >= (2,6): + # warnings.catch_warnings is new in 2.6. + def test_deprecated_prefix_methods(self): + l = pytree.Leaf(100, "foo") + with warnings.catch_warnings(record=True) as w: + warnings.simplefilter("always", DeprecationWarning) + self.assertEqual(l.get_prefix(), "") + l.set_prefix("hi") + self.assertEqual(l.prefix, "hi") + self.assertEqual(len(w), 2) + for warning in w: + self.assertTrue(warning.category is DeprecationWarning) + self.assertEqual(str(w[0].message), "get_prefix() is deprecated; " \ + "use the prefix property") + self.assertEqual(str(w[1].message), "set_prefix() is deprecated; " \ + "use the prefix property") def test_instantiate_base(self): if __debug__: Modified: python/branches/release31-maint/Lib/lib2to3/tests/test_refactor.py ============================================================================== --- python/branches/release31-maint/Lib/lib2to3/tests/test_refactor.py (original) +++ python/branches/release31-maint/Lib/lib2to3/tests/test_refactor.py Sat May 8 17:46:00 2010 @@ -2,6 +2,8 @@ Unit tests for refactor.py. """ +from __future__ import with_statement + import sys import os import codecs @@ -61,42 +63,50 @@ self.assertEqual(full_names, ["myfixes.fix_" + name for name in contents]) - def test_detect_future_print(self): - run = refactor._detect_future_print - self.assertFalse(run("")) - self.assertTrue(run("from __future__ import print_function")) - self.assertFalse(run("from __future__ import generators")) - self.assertFalse(run("from __future__ import generators, feature")) - input = "from __future__ import generators, print_function" - self.assertTrue(run(input)) - input ="from __future__ import print_function, generators" - self.assertTrue(run(input)) - input = "from __future__ import (print_function,)" - self.assertTrue(run(input)) - input = "from __future__ import (generators, print_function)" - self.assertTrue(run(input)) - input = "from __future__ import (generators, nested_scopes)" - self.assertFalse(run(input)) - input = """from __future__ import generators + def test_detect_future_features(self): + run = refactor._detect_future_features + fs = frozenset + empty = fs() + self.assertEqual(run(""), empty) + self.assertEqual(run("from __future__ import print_function"), + fs(("print_function",))) + self.assertEqual(run("from __future__ import generators"), + fs(("generators",))) + self.assertEqual(run("from __future__ import generators, feature"), + fs(("generators", "feature"))) + inp = "from __future__ import generators, print_function" + self.assertEqual(run(inp), fs(("generators", "print_function"))) + inp ="from __future__ import print_function, generators" + self.assertEqual(run(inp), fs(("print_function", "generators"))) + inp = "from __future__ import (print_function,)" + self.assertEqual(run(inp), fs(("print_function",))) + inp = "from __future__ import (generators, print_function)" + self.assertEqual(run(inp), fs(("generators", "print_function"))) + inp = "from __future__ import (generators, nested_scopes)" + self.assertEqual(run(inp), fs(("generators", "nested_scopes"))) + inp = """from __future__ import generators from __future__ import print_function""" - self.assertTrue(run(input)) - self.assertFalse(run("from")) - self.assertFalse(run("from 4")) - self.assertFalse(run("from x")) - self.assertFalse(run("from x 5")) - self.assertFalse(run("from x im")) - self.assertFalse(run("from x import")) - self.assertFalse(run("from x import 4")) - input = "'docstring'\nfrom __future__ import print_function" - self.assertTrue(run(input)) - input = "'docstring'\n'somng'\nfrom __future__ import print_function" - self.assertFalse(run(input)) - input = "# comment\nfrom __future__ import print_function" - self.assertTrue(run(input)) - input = "# comment\n'doc'\nfrom __future__ import print_function" - self.assertTrue(run(input)) - input = "class x: pass\nfrom __future__ import print_function" - self.assertFalse(run(input)) + self.assertEqual(run(inp), fs(("generators", "print_function"))) + invalid = ("from", + "from 4", + "from x", + "from x 5", + "from x im", + "from x import", + "from x import 4", + ) + for inp in invalid: + self.assertEqual(run(inp), empty) + inp = "'docstring'\nfrom __future__ import print_function" + self.assertEqual(run(inp), fs(("print_function",))) + inp = "'docstring'\n'somng'\nfrom __future__ import print_function" + self.assertEqual(run(inp), empty) + inp = "# comment\nfrom __future__ import print_function" + self.assertEqual(run(inp), fs(("print_function",))) + inp = "# comment\n'doc'\nfrom __future__ import print_function" + self.assertEqual(run(inp), fs(("print_function",))) + inp = "class x: pass\nfrom __future__ import print_function" + self.assertEqual(run(inp), empty) def test_get_headnode_dict(self): class NoneFix(fixer_base.BaseFix): From python-checkins at python.org Sat May 8 17:51:23 2010 From: python-checkins at python.org (benjamin.peterson) Date: Sat, 8 May 2010 17:51:23 +0200 (CEST) Subject: [Python-checkins] r80989 - in python/branches/py3k: Lib/test/test_sysconfig.py Message-ID: <20100508155123.47768EE988@mail.python.org> Author: benjamin.peterson Date: Sat May 8 17:51:23 2010 New Revision: 80989 Log: Merged revisions 80986-80987 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r80986 | benjamin.peterson | 2010-05-08 10:41:44 -0500 (Sat, 08 May 2010) | 1 line r80967 introduced a new scheme ........ r80987 | benjamin.peterson | 2010-05-08 10:42:29 -0500 (Sat, 08 May 2010) | 1 line add underscore ........ Modified: python/branches/py3k/ (props changed) python/branches/py3k/Lib/test/test_sysconfig.py Modified: python/branches/py3k/Lib/test/test_sysconfig.py ============================================================================== --- python/branches/py3k/Lib/test/test_sysconfig.py (original) +++ python/branches/py3k/Lib/test/test_sysconfig.py Sat May 8 17:51:23 2010 @@ -234,8 +234,8 @@ self.assertTrue(os.path.isfile(config_h), config_h) def test_get_scheme_names(self): - wanted = ('nt', 'nt_user', 'os2', 'os2_home', 'posix_home', - 'posix_prefix', 'posix_user') + wanted = ('nt', 'nt_user', 'os2', 'os2_home', 'osx_framework_user', + 'posix_home', 'posix_prefix', 'posix_user') self.assertEquals(get_scheme_names(), wanted) def test_symlink(self): From python-checkins at python.org Sat May 8 18:40:52 2010 From: python-checkins at python.org (michael.foord) Date: Sat, 8 May 2010 18:40:52 +0200 (CEST) Subject: [Python-checkins] r80990 - in python/trunk: Doc/library/unittest.rst Lib/unittest/case.py Message-ID: <20100508164052.689FCEE986@mail.python.org> Author: michael.foord Date: Sat May 8 18:40:52 2010 New Revision: 80990 Log: Updating documentation and adding docstrings to unittest.TestCase.assertRegexpMatches and assertNotRegexpMatches. Issue 8038. Modified: python/trunk/Doc/library/unittest.rst python/trunk/Lib/unittest/case.py Modified: python/trunk/Doc/library/unittest.rst ============================================================================== --- python/trunk/Doc/library/unittest.rst (original) +++ python/trunk/Doc/library/unittest.rst Sat May 8 18:40:52 2010 @@ -907,9 +907,9 @@ .. method:: assertNotRegexpMatches(text, regexp, msg=None) Verifies that a *regexp* search does not match *text*. Fails with an error - message including the pattern and the *text*. *regexp* may be - a regular expression object or a string containing a regular expression - suitable for use by :func:`re.search`. + message including the pattern and the part of *text* that matches. *regexp* + may be a regular expression object or a string containing a regular + expression suitable for use by :func:`re.search`. .. versionadded:: 2.7 Modified: python/trunk/Lib/unittest/case.py ============================================================================== --- python/trunk/Lib/unittest/case.py (original) +++ python/trunk/Lib/unittest/case.py Sat May 8 18:40:52 2010 @@ -945,6 +945,7 @@ callable_obj(*args, **kwargs) def assertRegexpMatches(self, text, expected_regexp, msg=None): + """Fail the test unless the text matches the regular expression.""" if isinstance(expected_regexp, basestring): expected_regexp = re.compile(expected_regexp) if not expected_regexp.search(text): @@ -953,6 +954,7 @@ raise self.failureException(msg) def assertNotRegexpMatches(self, text, unexpected_regexp, msg=None): + """Fail the test if the text matches the regular expression.""" if isinstance(unexpected_regexp, basestring): unexpected_regexp = re.compile(unexpected_regexp) match = unexpected_regexp.search(text) From python-checkins at python.org Sat May 8 18:44:52 2010 From: python-checkins at python.org (benjamin.peterson) Date: Sat, 8 May 2010 18:44:52 +0200 (CEST) Subject: [Python-checkins] r80991 - python/trunk/Lib/test/test_enumerate.py Message-ID: <20100508164452.37141EE986@mail.python.org> Author: benjamin.peterson Date: Sat May 8 18:44:52 2010 New Revision: 80991 Log: run and fix enumerate start test cases #8636 Modified: python/trunk/Lib/test/test_enumerate.py Modified: python/trunk/Lib/test/test_enumerate.py ============================================================================== --- python/trunk/Lib/test/test_enumerate.py (original) +++ python/trunk/Lib/test/test_enumerate.py Sat May 8 18:44:52 2010 @@ -205,26 +205,31 @@ self.assertEqual(rc, sys.getrefcount(r)) -class TestStart(EnumerateTestCase): +class EnumerateStartTestCase(EnumerateTestCase): - enum = lambda i: enumerate(i, start=11) - seq, res = 'abc', [(1, 'a'), (2, 'b'), (3, 'c')] + def test_basicfunction(self): + e = self.enum(self.seq) + self.assertEqual(iter(e), e) + self.assertEqual(list(self.enum(self.seq)), self.res) -class TestLongStart(EnumerateTestCase): +class TestStart(EnumerateStartTestCase): - enum = lambda i: enumerate(i, start=sys.maxint+1) + enum = lambda self, i: enumerate(i, start=11) + seq, res = 'abc', [(11, 'a'), (12, 'b'), (13, 'c')] + + +class TestLongStart(EnumerateStartTestCase): + + enum = lambda self, i: enumerate(i, start=sys.maxint+1) seq, res = 'abc', [(sys.maxint+1,'a'), (sys.maxint+2,'b'), (sys.maxint+3,'c')] def test_main(verbose=None): - testclasses = (EnumerateTestCase, SubclassTestCase, TestEmpty, TestBig, - TestReversed) - test_support.run_unittest(*testclasses) + test_support.run_unittest(__name__) # verify reference counting - import sys if verbose and hasattr(sys, "gettotalrefcount"): counts = [None] * 5 for i in xrange(len(counts)): From python-checkins at python.org Sat May 8 18:46:14 2010 From: python-checkins at python.org (michael.foord) Date: Sat, 8 May 2010 18:46:14 +0200 (CEST) Subject: [Python-checkins] r80992 - in python/branches/py3k: Doc/library/unittest.rst Lib/unittest/case.py Message-ID: <20100508164614.84007EE9D7@mail.python.org> Author: michael.foord Date: Sat May 8 18:46:14 2010 New Revision: 80992 Log: Merged revisions 80990 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r80990 | michael.foord | 2010-05-08 18:40:52 +0200 (Sat, 08 May 2010) | 1 line Updating documentation and adding docstrings to unittest.TestCase.assertRegexpMatches and assertNotRegexpMatches. Issue 8038. ........ Modified: python/branches/py3k/ (props changed) python/branches/py3k/Doc/library/unittest.rst python/branches/py3k/Lib/unittest/case.py Modified: python/branches/py3k/Doc/library/unittest.rst ============================================================================== --- python/branches/py3k/Doc/library/unittest.rst (original) +++ python/branches/py3k/Doc/library/unittest.rst Sat May 8 18:46:14 2010 @@ -903,9 +903,9 @@ .. method:: assertNotRegexpMatches(text, regexp, msg=None) Verifies that a *regexp* search does not match *text*. Fails with an error - message including the pattern and the *text*. *regexp* may be - a regular expression object or a string containing a regular expression - suitable for use by :func:`re.search`. + message including the pattern and the part of *text* that matches. *regexp* + may be a regular expression object or a string containing a regular + expression suitable for use by :func:`re.search`. .. versionadded:: 3.2 Modified: python/branches/py3k/Lib/unittest/case.py ============================================================================== --- python/branches/py3k/Lib/unittest/case.py (original) +++ python/branches/py3k/Lib/unittest/case.py Sat May 8 18:46:14 2010 @@ -993,6 +993,7 @@ callable_obj(*args, **kwargs) def assertRegexpMatches(self, text, expected_regexp, msg=None): + """Fail the test unless the text matches the regular expression.""" if isinstance(expected_regexp, (str, bytes)): expected_regexp = re.compile(expected_regexp) if not expected_regexp.search(text): @@ -1001,6 +1002,7 @@ raise self.failureException(msg) def assertNotRegexpMatches(self, text, unexpected_regexp, msg=None): + """Fail the test if the text matches the regular expression.""" if isinstance(unexpected_regexp, (str, bytes)): unexpected_regexp = re.compile(unexpected_regexp) match = unexpected_regexp.search(text) From python-checkins at python.org Sat May 8 18:51:16 2010 From: python-checkins at python.org (benjamin.peterson) Date: Sat, 8 May 2010 18:51:16 +0200 (CEST) Subject: [Python-checkins] r80993 - in python/branches/py3k: Lib/test/test_enumerate.py Message-ID: <20100508165116.C95BDC7A8@mail.python.org> Author: benjamin.peterson Date: Sat May 8 18:51:16 2010 New Revision: 80993 Log: Merged revisions 80991 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r80991 | benjamin.peterson | 2010-05-08 11:44:52 -0500 (Sat, 08 May 2010) | 1 line run and fix enumerate start test cases #8636 ........ Modified: python/branches/py3k/ (props changed) python/branches/py3k/Lib/test/test_enumerate.py Modified: python/branches/py3k/Lib/test/test_enumerate.py ============================================================================== --- python/branches/py3k/Lib/test/test_enumerate.py (original) +++ python/branches/py3k/Lib/test/test_enumerate.py Sat May 8 18:51:16 2010 @@ -199,26 +199,31 @@ self.assertEqual(rc, sys.getrefcount(r)) -class TestStart(EnumerateTestCase): +class EnumerateStartTestCase(EnumerateTestCase): - enum = lambda i: enumerate(i, start=11) - seq, res = 'abc', [(1, 'a'), (2, 'b'), (3, 'c')] + def test_basicfunction(self): + e = self.enum(self.seq) + self.assertEqual(iter(e), e) + self.assertEqual(list(self.enum(self.seq)), self.res) -class TestLongStart(EnumerateTestCase): +class TestStart(EnumerateStartTestCase): - enum = lambda i: enumerate(i, start=sys.maxsize+1) + enum = lambda self, i: enumerate(i, start=11) + seq, res = 'abc', [(11, 'a'), (12, 'b'), (13, 'c')] + + +class TestLongStart(EnumerateStartTestCase): + + enum = lambda self, i: enumerate(i, start=sys.maxsize+1) seq, res = 'abc', [(sys.maxsize+1,'a'), (sys.maxsize+2,'b'), (sys.maxsize+3,'c')] def test_main(verbose=None): - testclasses = (EnumerateTestCase, SubclassTestCase, TestEmpty, TestBig, - TestReversed) - support.run_unittest(*testclasses) + support.run_unittest(__name__) # verify reference counting - import sys if verbose and hasattr(sys, "gettotalrefcount"): counts = [None] * 5 for i in range(len(counts)): From python-checkins at python.org Sat May 8 18:51:40 2010 From: python-checkins at python.org (benjamin.peterson) Date: Sat, 8 May 2010 18:51:40 +0200 (CEST) Subject: [Python-checkins] r80994 - in python/branches/release26-maint: Lib/test/test_enumerate.py Message-ID: <20100508165140.3BCF3EE9B1@mail.python.org> Author: benjamin.peterson Date: Sat May 8 18:51:40 2010 New Revision: 80994 Log: Merged revisions 80991 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r80991 | benjamin.peterson | 2010-05-08 11:44:52 -0500 (Sat, 08 May 2010) | 1 line run and fix enumerate start test cases #8636 ........ Modified: python/branches/release26-maint/ (props changed) python/branches/release26-maint/Lib/test/test_enumerate.py Modified: python/branches/release26-maint/Lib/test/test_enumerate.py ============================================================================== --- python/branches/release26-maint/Lib/test/test_enumerate.py (original) +++ python/branches/release26-maint/Lib/test/test_enumerate.py Sat May 8 18:51:40 2010 @@ -199,26 +199,31 @@ self.assertEqual(rc, sys.getrefcount(r)) -class TestStart(EnumerateTestCase): +class EnumerateStartTestCase(EnumerateTestCase): - enum = lambda i: enumerate(i, start=11) - seq, res = 'abc', [(1, 'a'), (2, 'b'), (3, 'c')] + def test_basicfunction(self): + e = self.enum(self.seq) + self.assertEqual(iter(e), e) + self.assertEqual(list(self.enum(self.seq)), self.res) -class TestLongStart(EnumerateTestCase): +class TestStart(EnumerateStartTestCase): - enum = lambda i: enumerate(i, start=sys.maxint+1) + enum = lambda self, i: enumerate(i, start=11) + seq, res = 'abc', [(11, 'a'), (12, 'b'), (13, 'c')] + + +class TestLongStart(EnumerateStartTestCase): + + enum = lambda self, i: enumerate(i, start=sys.maxint+1) seq, res = 'abc', [(sys.maxint+1,'a'), (sys.maxint+2,'b'), (sys.maxint+3,'c')] def test_main(verbose=None): - testclasses = (EnumerateTestCase, SubclassTestCase, TestEmpty, TestBig, - TestReversed) - test_support.run_unittest(*testclasses) + test_support.run_unittest(__name__) # verify reference counting - import sys if verbose and hasattr(sys, "gettotalrefcount"): counts = [None] * 5 for i in xrange(len(counts)): From python-checkins at python.org Sat May 8 18:53:50 2010 From: python-checkins at python.org (benjamin.peterson) Date: Sat, 8 May 2010 18:53:50 +0200 (CEST) Subject: [Python-checkins] r80995 - in python/branches/release31-maint: Lib/test/test_enumerate.py Message-ID: <20100508165350.C8207C7A8@mail.python.org> Author: benjamin.peterson Date: Sat May 8 18:53:50 2010 New Revision: 80995 Log: Merged revisions 80993 via svnmerge from svn+ssh://pythondev at svn.python.org/python/branches/py3k ................ r80993 | benjamin.peterson | 2010-05-08 11:51:16 -0500 (Sat, 08 May 2010) | 9 lines Merged revisions 80991 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r80991 | benjamin.peterson | 2010-05-08 11:44:52 -0500 (Sat, 08 May 2010) | 1 line run and fix enumerate start test cases #8636 ........ ................ Modified: python/branches/release31-maint/ (props changed) python/branches/release31-maint/Lib/test/test_enumerate.py Modified: python/branches/release31-maint/Lib/test/test_enumerate.py ============================================================================== --- python/branches/release31-maint/Lib/test/test_enumerate.py (original) +++ python/branches/release31-maint/Lib/test/test_enumerate.py Sat May 8 18:53:50 2010 @@ -199,26 +199,31 @@ self.assertEqual(rc, sys.getrefcount(r)) -class TestStart(EnumerateTestCase): +class EnumerateStartTestCase(EnumerateTestCase): - enum = lambda i: enumerate(i, start=11) - seq, res = 'abc', [(1, 'a'), (2, 'b'), (3, 'c')] + def test_basicfunction(self): + e = self.enum(self.seq) + self.assertEqual(iter(e), e) + self.assertEqual(list(self.enum(self.seq)), self.res) -class TestLongStart(EnumerateTestCase): +class TestStart(EnumerateStartTestCase): - enum = lambda i: enumerate(i, start=sys.maxsize+1) + enum = lambda self, i: enumerate(i, start=11) + seq, res = 'abc', [(11, 'a'), (12, 'b'), (13, 'c')] + + +class TestLongStart(EnumerateStartTestCase): + + enum = lambda self, i: enumerate(i, start=sys.maxsize+1) seq, res = 'abc', [(sys.maxsize+1,'a'), (sys.maxsize+2,'b'), (sys.maxsize+3,'c')] def test_main(verbose=None): - testclasses = (EnumerateTestCase, SubclassTestCase, TestEmpty, TestBig, - TestReversed) - support.run_unittest(*testclasses) + support.run_unittest(__name__) # verify reference counting - import sys if verbose and hasattr(sys, "gettotalrefcount"): counts = [None] * 5 for i in range(len(counts)): From python-checkins at python.org Sat May 8 19:05:19 2010 From: python-checkins at python.org (benjamin.peterson) Date: Sat, 8 May 2010 19:05:19 +0200 (CEST) Subject: [Python-checkins] r80996 - python/trunk/Lib/pydoc_data/topics.py Message-ID: <20100508170519.5E14EEE9AE@mail.python.org> Author: benjamin.peterson Date: Sat May 8 19:05:19 2010 New Revision: 80996 Log: update pydoc-topics Modified: python/trunk/Lib/pydoc_data/topics.py Modified: python/trunk/Lib/pydoc_data/topics.py ============================================================================== --- python/trunk/Lib/pydoc_data/topics.py (original) +++ python/trunk/Lib/pydoc_data/topics.py Sat May 8 19:05:19 2010 @@ -1,4 +1,4 @@ -# Autogenerated by Sphinx on Sat Apr 10 11:26:35 2010 +# Autogenerated by Sphinx on Sat May 8 12:01:30 2010 topics = {'assert': u'\nThe ``assert`` statement\n************************\n\nAssert statements are a convenient way to insert debugging assertions\ninto a program:\n\n assert_stmt ::= "assert" expression ["," expression]\n\nThe simple form, ``assert expression``, is equivalent to\n\n if __debug__:\n if not expression: raise AssertionError\n\nThe extended form, ``assert expression1, expression2``, is equivalent\nto\n\n if __debug__:\n if not expression1: raise AssertionError(expression2)\n\nThese equivalences assume that ``__debug__`` and ``AssertionError``\nrefer to the built-in variables with those names. In the current\nimplementation, the built-in variable ``__debug__`` is ``True`` under\nnormal circumstances, ``False`` when optimization is requested\n(command line option -O). The current code generator emits no code\nfor an assert statement when optimization is requested at compile\ntime. Note that it is unnecessary to include the source code for the\nexpression that failed in the error message; it will be displayed as\npart of the stack trace.\n\nAssignments to ``__debug__`` are illegal. The value for the built-in\nvariable is determined when the interpreter starts.\n', 'assignment': u'\nAssignment statements\n*********************\n\nAssignment statements are used to (re)bind names to values and to\nmodify attributes or items of mutable objects:\n\n assignment_stmt ::= (target_list "=")+ (expression_list | yield_expression)\n target_list ::= target ("," target)* [","]\n target ::= identifier\n | "(" target_list ")"\n | "[" target_list "]"\n | attributeref\n | subscription\n | slicing\n\n(See section *Primaries* for the syntax definitions for the last three\nsymbols.)\n\nAn assignment statement evaluates the expression list (remember that\nthis can be a single expression or a comma-separated list, the latter\nyielding a tuple) and assigns the single resulting object to each of\nthe target lists, from left to right.\n\nAssignment is defined recursively depending on the form of the target\n(list). When a target is part of a mutable object (an attribute\nreference, subscription or slicing), the mutable object must\nultimately perform the assignment and decide about its validity, and\nmay raise an exception if the assignment is unacceptable. The rules\nobserved by various types and the exceptions raised are given with the\ndefinition of the object types (see section *The standard type\nhierarchy*).\n\nAssignment of an object to a target list is recursively defined as\nfollows.\n\n* If the target list is a single target: The object is assigned to\n that target.\n\n* If the target list is a comma-separated list of targets: The object\n must be an iterable with the same number of items as there are\n targets in the target list, and the items are assigned, from left to\n right, to the corresponding targets. (This rule is relaxed as of\n Python 1.5; in earlier versions, the object had to be a tuple.\n Since strings are sequences, an assignment like ``a, b = "xy"`` is\n now legal as long as the string has the right length.)\n\nAssignment of an object to a single target is recursively defined as\nfollows.\n\n* If the target is an identifier (name):\n\n * If the name does not occur in a ``global`` statement in the\n current code block: the name is bound to the object in the current\n local namespace.\n\n * Otherwise: the name is bound to the object in the current global\n namespace.\n\n The name is rebound if it was already bound. This may cause the\n reference count for the object previously bound to the name to reach\n zero, causing the object to be deallocated and its destructor (if it\n has one) to be called.\n\n* If the target is a target list enclosed in parentheses or in square\n brackets: The object must be an iterable with the same number of\n items as there are targets in the target list, and its items are\n assigned, from left to right, to the corresponding targets.\n\n* If the target is an attribute reference: The primary expression in\n the reference is evaluated. It should yield an object with\n assignable attributes; if this is not the case, ``TypeError`` is\n raised. That object is then asked to assign the assigned object to\n the given attribute; if it cannot perform the assignment, it raises\n an exception (usually but not necessarily ``AttributeError``).\n\n Note: If the object is a class instance and the attribute reference\n occurs on both sides of the assignment operator, the RHS expression,\n ``a.x`` can access either an instance attribute or (if no instance\n attribute exists) a class attribute. The LHS target ``a.x`` is\n always set as an instance attribute, creating it if necessary.\n Thus, the two occurrences of ``a.x`` do not necessarily refer to the\n same attribute: if the RHS expression refers to a class attribute,\n the LHS creates a new instance attribute as the target of the\n assignment:\n\n class Cls:\n x = 3 # class variable\n inst = Cls()\n inst.x = inst.x + 1 # writes inst.x as 4 leaving Cls.x as 3\n\n This description does not necessarily apply to descriptor\n attributes, such as properties created with ``property()``.\n\n* If the target is a subscription: The primary expression in the\n reference is evaluated. It should yield either a mutable sequence\n object (such as a list) or a mapping object (such as a dictionary).\n Next, the subscript expression is evaluated.\n\n If the primary is a mutable sequence object (such as a list), the\n subscript must yield a plain integer. If it is negative, the\n sequence\'s length is added to it. The resulting value must be a\n nonnegative integer less than the sequence\'s length, and the\n sequence is asked to assign the assigned object to its item with\n that index. If the index is out of range, ``IndexError`` is raised\n (assignment to a subscripted sequence cannot add new items to a\n list).\n\n If the primary is a mapping object (such as a dictionary), the\n subscript must have a type compatible with the mapping\'s key type,\n and the mapping is then asked to create a key/datum pair which maps\n the subscript to the assigned object. This can either replace an\n existing key/value pair with the same key value, or insert a new\n key/value pair (if no key with the same value existed).\n\n* If the target is a slicing: The primary expression in the reference\n is evaluated. It should yield a mutable sequence object (such as a\n list). The assigned object should be a sequence object of the same\n type. Next, the lower and upper bound expressions are evaluated,\n insofar they are present; defaults are zero and the sequence\'s\n length. The bounds should evaluate to (small) integers. If either\n bound is negative, the sequence\'s length is added to it. The\n resulting bounds are clipped to lie between zero and the sequence\'s\n length, inclusive. Finally, the sequence object is asked to replace\n the slice with the items of the assigned sequence. The length of\n the slice may be different from the length of the assigned sequence,\n thus changing the length of the target sequence, if the object\n allows it.\n\n**CPython implementation detail:** In the current implementation, the\nsyntax for targets is taken to be the same as for expressions, and\ninvalid syntax is rejected during the code generation phase, causing\nless detailed error messages.\n\nWARNING: Although the definition of assignment implies that overlaps\nbetween the left-hand side and the right-hand side are \'safe\' (for\nexample ``a, b = b, a`` swaps two variables), overlaps *within* the\ncollection of assigned-to variables are not safe! For instance, the\nfollowing program prints ``[0, 2]``:\n\n x = [0, 1]\n i = 0\n i, x[i] = 1, 2\n print x\n\n\nAugmented assignment statements\n===============================\n\nAugmented assignment is the combination, in a single statement, of a\nbinary operation and an assignment statement:\n\n augmented_assignment_stmt ::= augtarget augop (expression_list | yield_expression)\n augtarget ::= identifier | attributeref | subscription | slicing\n augop ::= "+=" | "-=" | "*=" | "/=" | "//=" | "%=" | "**="\n | ">>=" | "<<=" | "&=" | "^=" | "|="\n\n(See section *Primaries* for the syntax definitions for the last three\nsymbols.)\n\nAn augmented assignment evaluates the target (which, unlike normal\nassignment statements, cannot be an unpacking) and the expression\nlist, performs the binary operation specific to the type of assignment\non the two operands, and assigns the result to the original target.\nThe target is only evaluated once.\n\nAn augmented assignment expression like ``x += 1`` can be rewritten as\n``x = x + 1`` to achieve a similar, but not exactly equal effect. In\nthe augmented version, ``x`` is only evaluated once. Also, when\npossible, the actual operation is performed *in-place*, meaning that\nrather than creating a new object and assigning that to the target,\nthe old object is modified instead.\n\nWith the exception of assigning to tuples and multiple targets in a\nsingle statement, the assignment done by augmented assignment\nstatements is handled the same way as normal assignments. Similarly,\nwith the exception of the possible *in-place* behavior, the binary\noperation performed by augmented assignment is the same as the normal\nbinary operations.\n\nFor targets which are attribute references, the same *caveat about\nclass and instance attributes* applies as for regular assignments.\n', 'atom-identifiers': u'\nIdentifiers (Names)\n*******************\n\nAn identifier occurring as an atom is a name. See section\n*Identifiers and keywords* for lexical definition and section *Naming\nand binding* for documentation of naming and binding.\n\nWhen the name is bound to an object, evaluation of the atom yields\nthat object. When a name is not bound, an attempt to evaluate it\nraises a ``NameError`` exception.\n\n**Private name mangling:** When an identifier that textually occurs in\na class definition begins with two or more underscore characters and\ndoes not end in two or more underscores, it is considered a *private\nname* of that class. Private names are transformed to a longer form\nbefore code is generated for them. The transformation inserts the\nclass name in front of the name, with leading underscores removed, and\na single underscore inserted in front of the class name. For example,\nthe identifier ``__spam`` occurring in a class named ``Ham`` will be\ntransformed to ``_Ham__spam``. This transformation is independent of\nthe syntactical context in which the identifier is used. If the\ntransformed name is extremely long (longer than 255 characters),\nimplementation defined truncation may happen. If the class name\nconsists only of underscores, no transformation is done.\n', @@ -63,9 +63,9 @@ 'shifting': u'\nShifting operations\n*******************\n\nThe shifting operations have lower priority than the arithmetic\noperations:\n\n shift_expr ::= a_expr | shift_expr ( "<<" | ">>" ) a_expr\n\nThese operators accept plain or long integers as arguments. The\narguments are converted to a common type. They shift the first\nargument to the left or right by the number of bits given by the\nsecond argument.\n\nA right shift by *n* bits is defined as division by ``pow(2, n)``. A\nleft shift by *n* bits is defined as multiplication with ``pow(2,\nn)``. Negative shift counts raise a ``ValueError`` exception.\n\nNote: In the current implementation, the right-hand operand is required to\n be at most ``sys.maxsize``. If the right-hand operand is larger\n than ``sys.maxsize`` an ``OverflowError`` exception is raised.\n', 'slicings': u'\nSlicings\n********\n\nA slicing selects a range of items in a sequence object (e.g., a\nstring, tuple or list). Slicings may be used as expressions or as\ntargets in assignment or ``del`` statements. The syntax for a\nslicing:\n\n slicing ::= simple_slicing | extended_slicing\n simple_slicing ::= primary "[" short_slice "]"\n extended_slicing ::= primary "[" slice_list "]"\n slice_list ::= slice_item ("," slice_item)* [","]\n slice_item ::= expression | proper_slice | ellipsis\n proper_slice ::= short_slice | long_slice\n short_slice ::= [lower_bound] ":" [upper_bound]\n long_slice ::= short_slice ":" [stride]\n lower_bound ::= expression\n upper_bound ::= expression\n stride ::= expression\n ellipsis ::= "..."\n\nThere is ambiguity in the formal syntax here: anything that looks like\nan expression list also looks like a slice list, so any subscription\ncan be interpreted as a slicing. Rather than further complicating the\nsyntax, this is disambiguated by defining that in this case the\ninterpretation as a subscription takes priority over the\ninterpretation as a slicing (this is the case if the slice list\ncontains no proper slice nor ellipses). Similarly, when the slice\nlist has exactly one short slice and no trailing comma, the\ninterpretation as a simple slicing takes priority over that as an\nextended slicing.\n\nThe semantics for a simple slicing are as follows. The primary must\nevaluate to a sequence object. The lower and upper bound expressions,\nif present, must evaluate to plain integers; defaults are zero and the\n``sys.maxint``, respectively. If either bound is negative, the\nsequence\'s length is added to it. The slicing now selects all items\nwith index *k* such that ``i <= k < j`` where *i* and *j* are the\nspecified lower and upper bounds. This may be an empty sequence. It\nis not an error if *i* or *j* lie outside the range of valid indexes\n(such items don\'t exist so they aren\'t selected).\n\nThe semantics for an extended slicing are as follows. The primary\nmust evaluate to a mapping object, and it is indexed with a key that\nis constructed from the slice list, as follows. If the slice list\ncontains at least one comma, the key is a tuple containing the\nconversion of the slice items; otherwise, the conversion of the lone\nslice item is the key. The conversion of a slice item that is an\nexpression is that expression. The conversion of an ellipsis slice\nitem is the built-in ``Ellipsis`` object. The conversion of a proper\nslice is a slice object (see section *The standard type hierarchy*)\nwhose ``start``, ``stop`` and ``step`` attributes are the values of\nthe expressions given as lower bound, upper bound and stride,\nrespectively, substituting ``None`` for missing expressions.\n', 'specialattrs': u"\nSpecial Attributes\n******************\n\nThe implementation adds a few special read-only attributes to several\nobject types, where they are relevant. Some of these are not reported\nby the ``dir()`` built-in function.\n\nobject.__dict__\n\n A dictionary or other mapping object used to store an object's\n (writable) attributes.\n\nobject.__methods__\n\n Deprecated since version 2.2: Use the built-in function ``dir()``\n to get a list of an object's attributes. This attribute is no\n longer available.\n\nobject.__members__\n\n Deprecated since version 2.2: Use the built-in function ``dir()``\n to get a list of an object's attributes. This attribute is no\n longer available.\n\ninstance.__class__\n\n The class to which a class instance belongs.\n\nclass.__bases__\n\n The tuple of base classes of a class object.\n\nclass.__name__\n\n The name of the class or type.\n\nThe following attributes are only supported by *new-style class*es.\n\nclass.__mro__\n\n This attribute is a tuple of classes that are considered when\n looking for base classes during method resolution.\n\nclass.mro()\n\n This method can be overridden by a metaclass to customize the\n method resolution order for its instances. It is called at class\n instantiation, and its result is stored in ``__mro__``.\n\nclass.__subclasses__()\n\n Each new-style class keeps a list of weak references to its\n immediate subclasses. This method returns a list of all those\n references still alive. Example:\n\n >>> int.__subclasses__()\n []\n\n-[ Footnotes ]-\n\n[1] Additional information on these special methods may be found in\n the Python Reference Manual (*Basic customization*).\n\n[2] As a consequence, the list ``[1, 2]`` is considered equal to\n ``[1.0, 2.0]``, and similarly for tuples.\n\n[3] They must have since the parser can't tell the type of the\n operands.\n\n[4] To format only a tuple you should therefore provide a singleton\n tuple whose only element is the tuple to be formatted.\n\n[5] The advantage of leaving the newline on is that returning an empty\n string is then an unambiguous EOF indication. It is also possible\n (in cases where it might matter, for example, if you want to make\n an exact copy of a file while scanning its lines) to tell whether\n the last line of a file ended in a newline or not (yes this\n happens!).\n", - 'specialnames': u'\nSpecial method names\n********************\n\nA class can implement certain operations that are invoked by special\nsyntax (such as arithmetic operations or subscripting and slicing) by\ndefining methods with special names. This is Python\'s approach to\n*operator overloading*, allowing classes to define their own behavior\nwith respect to language operators. For instance, if a class defines\na method named ``__getitem__()``, and ``x`` is an instance of this\nclass, then ``x[i]`` is roughly equivalent to ``x.__getitem__(i)`` for\nold-style classes and ``type(x).__getitem__(x, i)`` for new-style\nclasses. Except where mentioned, attempts to execute an operation\nraise an exception when no appropriate method is defined (typically\n``AttributeError`` or ``TypeError``).\n\nWhen implementing a class that emulates any built-in type, it is\nimportant that the emulation only be implemented to the degree that it\nmakes sense for the object being modelled. For example, some\nsequences may work well with retrieval of individual elements, but\nextracting a slice may not make sense. (One example of this is the\n``NodeList`` interface in the W3C\'s Document Object Model.)\n\n\nBasic customization\n===================\n\nobject.__new__(cls[, ...])\n\n Called to create a new instance of class *cls*. ``__new__()`` is a\n static method (special-cased so you need not declare it as such)\n that takes the class of which an instance was requested as its\n first argument. The remaining arguments are those passed to the\n object constructor expression (the call to the class). The return\n value of ``__new__()`` should be the new object instance (usually\n an instance of *cls*).\n\n Typical implementations create a new instance of the class by\n invoking the superclass\'s ``__new__()`` method using\n ``super(currentclass, cls).__new__(cls[, ...])`` with appropriate\n arguments and then modifying the newly-created instance as\n necessary before returning it.\n\n If ``__new__()`` returns an instance of *cls*, then the new\n instance\'s ``__init__()`` method will be invoked like\n ``__init__(self[, ...])``, where *self* is the new instance and the\n remaining arguments are the same as were passed to ``__new__()``.\n\n If ``__new__()`` does not return an instance of *cls*, then the new\n instance\'s ``__init__()`` method will not be invoked.\n\n ``__new__()`` is intended mainly to allow subclasses of immutable\n types (like int, str, or tuple) to customize instance creation. It\n is also commonly overridden in custom metaclasses in order to\n customize class creation.\n\nobject.__init__(self[, ...])\n\n Called when the instance is created. The arguments are those\n passed to the class constructor expression. If a base class has an\n ``__init__()`` method, the derived class\'s ``__init__()`` method,\n if any, must explicitly call it to ensure proper initialization of\n the base class part of the instance; for example:\n ``BaseClass.__init__(self, [args...])``. As a special constraint\n on constructors, no value may be returned; doing so will cause a\n ``TypeError`` to be raised at runtime.\n\nobject.__del__(self)\n\n Called when the instance is about to be destroyed. This is also\n called a destructor. If a base class has a ``__del__()`` method,\n the derived class\'s ``__del__()`` method, if any, must explicitly\n call it to ensure proper deletion of the base class part of the\n instance. Note that it is possible (though not recommended!) for\n the ``__del__()`` method to postpone destruction of the instance by\n creating a new reference to it. It may then be called at a later\n time when this new reference is deleted. It is not guaranteed that\n ``__del__()`` methods are called for objects that still exist when\n the interpreter exits.\n\n Note: ``del x`` doesn\'t directly call ``x.__del__()`` --- the former\n decrements the reference count for ``x`` by one, and the latter\n is only called when ``x``\'s reference count reaches zero. Some\n common situations that may prevent the reference count of an\n object from going to zero include: circular references between\n objects (e.g., a doubly-linked list or a tree data structure with\n parent and child pointers); a reference to the object on the\n stack frame of a function that caught an exception (the traceback\n stored in ``sys.exc_traceback`` keeps the stack frame alive); or\n a reference to the object on the stack frame that raised an\n unhandled exception in interactive mode (the traceback stored in\n ``sys.last_traceback`` keeps the stack frame alive). The first\n situation can only be remedied by explicitly breaking the cycles;\n the latter two situations can be resolved by storing ``None`` in\n ``sys.exc_traceback`` or ``sys.last_traceback``. Circular\n references which are garbage are detected when the option cycle\n detector is enabled (it\'s on by default), but can only be cleaned\n up if there are no Python-level ``__del__()`` methods involved.\n Refer to the documentation for the ``gc`` module for more\n information about how ``__del__()`` methods are handled by the\n cycle detector, particularly the description of the ``garbage``\n value.\n\n Warning: Due to the precarious circumstances under which ``__del__()``\n methods are invoked, exceptions that occur during their execution\n are ignored, and a warning is printed to ``sys.stderr`` instead.\n Also, when ``__del__()`` is invoked in response to a module being\n deleted (e.g., when execution of the program is done), other\n globals referenced by the ``__del__()`` method may already have\n been deleted or in the process of being torn down (e.g. the\n import machinery shutting down). For this reason, ``__del__()``\n methods should do the absolute minimum needed to maintain\n external invariants. Starting with version 1.5, Python\n guarantees that globals whose name begins with a single\n underscore are deleted from their module before other globals are\n deleted; if no other references to such globals exist, this may\n help in assuring that imported modules are still available at the\n time when the ``__del__()`` method is called.\n\nobject.__repr__(self)\n\n Called by the ``repr()`` built-in function and by string\n conversions (reverse quotes) to compute the "official" string\n representation of an object. If at all possible, this should look\n like a valid Python expression that could be used to recreate an\n object with the same value (given an appropriate environment). If\n this is not possible, a string of the form ``<...some useful\n description...>`` should be returned. The return value must be a\n string object. If a class defines ``__repr__()`` but not\n ``__str__()``, then ``__repr__()`` is also used when an "informal"\n string representation of instances of that class is required.\n\n This is typically used for debugging, so it is important that the\n representation is information-rich and unambiguous.\n\nobject.__str__(self)\n\n Called by the ``str()`` built-in function and by the ``print``\n statement to compute the "informal" string representation of an\n object. This differs from ``__repr__()`` in that it does not have\n to be a valid Python expression: a more convenient or concise\n representation may be used instead. The return value must be a\n string object.\n\nobject.__lt__(self, other)\nobject.__le__(self, other)\nobject.__eq__(self, other)\nobject.__ne__(self, other)\nobject.__gt__(self, other)\nobject.__ge__(self, other)\n\n New in version 2.1.\n\n These are the so-called "rich comparison" methods, and are called\n for comparison operators in preference to ``__cmp__()`` below. The\n correspondence between operator symbols and method names is as\n follows: ``xy`` call ``x.__ne__(y)``, ``x>y`` calls ``x.__gt__(y)``, and\n ``x>=y`` calls ``x.__ge__(y)``.\n\n A rich comparison method may return the singleton\n ``NotImplemented`` if it does not implement the operation for a\n given pair of arguments. By convention, ``False`` and ``True`` are\n returned for a successful comparison. However, these methods can\n return any value, so if the comparison operator is used in a\n Boolean context (e.g., in the condition of an ``if`` statement),\n Python will call ``bool()`` on the value to determine if the result\n is true or false.\n\n There are no implied relationships among the comparison operators.\n The truth of ``x==y`` does not imply that ``x!=y`` is false.\n Accordingly, when defining ``__eq__()``, one should also define\n ``__ne__()`` so that the operators will behave as expected. See\n the paragraph on ``__hash__()`` for some important notes on\n creating *hashable* objects which support custom comparison\n operations and are usable as dictionary keys.\n\n There are no swapped-argument versions of these methods (to be used\n when the left argument does not support the operation but the right\n argument does); rather, ``__lt__()`` and ``__gt__()`` are each\n other\'s reflection, ``__le__()`` and ``__ge__()`` are each other\'s\n reflection, and ``__eq__()`` and ``__ne__()`` are their own\n reflection.\n\n Arguments to rich comparison methods are never coerced.\n\n To automatically generate ordering operations from a single root\n operation, see ``functools.total_ordering()``.\n\nobject.__cmp__(self, other)\n\n Called by comparison operations if rich comparison (see above) is\n not defined. Should return a negative integer if ``self < other``,\n zero if ``self == other``, a positive integer if ``self > other``.\n If no ``__cmp__()``, ``__eq__()`` or ``__ne__()`` operation is\n defined, class instances are compared by object identity\n ("address"). See also the description of ``__hash__()`` for some\n important notes on creating *hashable* objects which support custom\n comparison operations and are usable as dictionary keys. (Note: the\n restriction that exceptions are not propagated by ``__cmp__()`` has\n been removed since Python 1.5.)\n\nobject.__rcmp__(self, other)\n\n Changed in version 2.1: No longer supported.\n\nobject.__hash__(self)\n\n Called by built-in function ``hash()`` and for operations on\n members of hashed collections including ``set``, ``frozenset``, and\n ``dict``. ``__hash__()`` should return an integer. The only\n required property is that objects which compare equal have the same\n hash value; it is advised to somehow mix together (e.g. using\n exclusive or) the hash values for the components of the object that\n also play a part in comparison of objects.\n\n If a class does not define a ``__cmp__()`` or ``__eq__()`` method\n it should not define a ``__hash__()`` operation either; if it\n defines ``__cmp__()`` or ``__eq__()`` but not ``__hash__()``, its\n instances will not be usable in hashed collections. If a class\n defines mutable objects and implements a ``__cmp__()`` or\n ``__eq__()`` method, it should not implement ``__hash__()``, since\n hashable collection implementations require that a object\'s hash\n value is immutable (if the object\'s hash value changes, it will be\n in the wrong hash bucket).\n\n User-defined classes have ``__cmp__()`` and ``__hash__()`` methods\n by default; with them, all objects compare unequal (except with\n themselves) and ``x.__hash__()`` returns ``id(x)``.\n\n Classes which inherit a ``__hash__()`` method from a parent class\n but change the meaning of ``__cmp__()`` or ``__eq__()`` such that\n the hash value returned is no longer appropriate (e.g. by switching\n to a value-based concept of equality instead of the default\n identity based equality) can explicitly flag themselves as being\n unhashable by setting ``__hash__ = None`` in the class definition.\n Doing so means that not only will instances of the class raise an\n appropriate ``TypeError`` when a program attempts to retrieve their\n hash value, but they will also be correctly identified as\n unhashable when checking ``isinstance(obj, collections.Hashable)``\n (unlike classes which define their own ``__hash__()`` to explicitly\n raise ``TypeError``).\n\n Changed in version 2.5: ``__hash__()`` may now also return a long\n integer object; the 32-bit integer is then derived from the hash of\n that object.\n\n Changed in version 2.6: ``__hash__`` may now be set to ``None`` to\n explicitly flag instances of a class as unhashable.\n\nobject.__nonzero__(self)\n\n Called to implement truth value testing and the built-in operation\n ``bool()``; should return ``False`` or ``True``, or their integer\n equivalents ``0`` or ``1``. When this method is not defined,\n ``__len__()`` is called, if it is defined, and the object is\n considered true if its result is nonzero. If a class defines\n neither ``__len__()`` nor ``__nonzero__()``, all its instances are\n considered true.\n\nobject.__unicode__(self)\n\n Called to implement ``unicode()`` built-in; should return a Unicode\n object. When this method is not defined, string conversion is\n attempted, and the result of string conversion is converted to\n Unicode using the system default encoding.\n\n\nCustomizing attribute access\n============================\n\nThe following methods can be defined to customize the meaning of\nattribute access (use of, assignment to, or deletion of ``x.name``)\nfor class instances.\n\nobject.__getattr__(self, name)\n\n Called when an attribute lookup has not found the attribute in the\n usual places (i.e. it is not an instance attribute nor is it found\n in the class tree for ``self``). ``name`` is the attribute name.\n This method should return the (computed) attribute value or raise\n an ``AttributeError`` exception.\n\n Note that if the attribute is found through the normal mechanism,\n ``__getattr__()`` is not called. (This is an intentional asymmetry\n between ``__getattr__()`` and ``__setattr__()``.) This is done both\n for efficiency reasons and because otherwise ``__getattr__()``\n would have no way to access other attributes of the instance. Note\n that at least for instance variables, you can fake total control by\n not inserting any values in the instance attribute dictionary (but\n instead inserting them in another object). See the\n ``__getattribute__()`` method below for a way to actually get total\n control in new-style classes.\n\nobject.__setattr__(self, name, value)\n\n Called when an attribute assignment is attempted. This is called\n instead of the normal mechanism (i.e. store the value in the\n instance dictionary). *name* is the attribute name, *value* is the\n value to be assigned to it.\n\n If ``__setattr__()`` wants to assign to an instance attribute, it\n should not simply execute ``self.name = value`` --- this would\n cause a recursive call to itself. Instead, it should insert the\n value in the dictionary of instance attributes, e.g.,\n ``self.__dict__[name] = value``. For new-style classes, rather\n than accessing the instance dictionary, it should call the base\n class method with the same name, for example,\n ``object.__setattr__(self, name, value)``.\n\nobject.__delattr__(self, name)\n\n Like ``__setattr__()`` but for attribute deletion instead of\n assignment. This should only be implemented if ``del obj.name`` is\n meaningful for the object.\n\n\nMore attribute access for new-style classes\n-------------------------------------------\n\nThe following methods only apply to new-style classes.\n\nobject.__getattribute__(self, name)\n\n Called unconditionally to implement attribute accesses for\n instances of the class. If the class also defines\n ``__getattr__()``, the latter will not be called unless\n ``__getattribute__()`` either calls it explicitly or raises an\n ``AttributeError``. This method should return the (computed)\n attribute value or raise an ``AttributeError`` exception. In order\n to avoid infinite recursion in this method, its implementation\n should always call the base class method with the same name to\n access any attributes it needs, for example,\n ``object.__getattribute__(self, name)``.\n\n Note: This method may still be bypassed when looking up special methods\n as the result of implicit invocation via language syntax or\n built-in functions. See *Special method lookup for new-style\n classes*.\n\n\nImplementing Descriptors\n------------------------\n\nThe following methods only apply when an instance of the class\ncontaining the method (a so-called *descriptor* class) appears in the\nclass dictionary of another new-style class, known as the *owner*\nclass. In the examples below, "the attribute" refers to the attribute\nwhose name is the key of the property in the owner class\'\n``__dict__``. Descriptors can only be implemented as new-style\nclasses themselves.\n\nobject.__get__(self, instance, owner)\n\n Called to get the attribute of the owner class (class attribute\n access) or of an instance of that class (instance attribute\n access). *owner* is always the owner class, while *instance* is the\n instance that the attribute was accessed through, or ``None`` when\n the attribute is accessed through the *owner*. This method should\n return the (computed) attribute value or raise an\n ``AttributeError`` exception.\n\nobject.__set__(self, instance, value)\n\n Called to set the attribute on an instance *instance* of the owner\n class to a new value, *value*.\n\nobject.__delete__(self, instance)\n\n Called to delete the attribute on an instance *instance* of the\n owner class.\n\n\nInvoking Descriptors\n--------------------\n\nIn general, a descriptor is an object attribute with "binding\nbehavior", one whose attribute access has been overridden by methods\nin the descriptor protocol: ``__get__()``, ``__set__()``, and\n``__delete__()``. If any of those methods are defined for an object,\nit is said to be a descriptor.\n\nThe default behavior for attribute access is to get, set, or delete\nthe attribute from an object\'s dictionary. For instance, ``a.x`` has a\nlookup chain starting with ``a.__dict__[\'x\']``, then\n``type(a).__dict__[\'x\']``, and continuing through the base classes of\n``type(a)`` excluding metaclasses.\n\nHowever, if the looked-up value is an object defining one of the\ndescriptor methods, then Python may override the default behavior and\ninvoke the descriptor method instead. Where this occurs in the\nprecedence chain depends on which descriptor methods were defined and\nhow they were called. Note that descriptors are only invoked for new\nstyle objects or classes (ones that subclass ``object()`` or\n``type()``).\n\nThe starting point for descriptor invocation is a binding, ``a.x``.\nHow the arguments are assembled depends on ``a``:\n\nDirect Call\n The simplest and least common call is when user code directly\n invokes a descriptor method: ``x.__get__(a)``.\n\nInstance Binding\n If binding to a new-style object instance, ``a.x`` is transformed\n into the call: ``type(a).__dict__[\'x\'].__get__(a, type(a))``.\n\nClass Binding\n If binding to a new-style class, ``A.x`` is transformed into the\n call: ``A.__dict__[\'x\'].__get__(None, A)``.\n\nSuper Binding\n If ``a`` is an instance of ``super``, then the binding ``super(B,\n obj).m()`` searches ``obj.__class__.__mro__`` for the base class\n ``A`` immediately preceding ``B`` and then invokes the descriptor\n with the call: ``A.__dict__[\'m\'].__get__(obj, A)``.\n\nFor instance bindings, the precedence of descriptor invocation depends\non the which descriptor methods are defined. A descriptor can define\nany combination of ``__get__()``, ``__set__()`` and ``__delete__()``.\nIf it does not define ``__get__()``, then accessing the attribute will\nreturn the descriptor object itself unless there is a value in the\nobject\'s instance dictionary. If the descriptor defines ``__set__()``\nand/or ``__delete__()``, it is a data descriptor; if it defines\nneither, it is a non-data descriptor. Normally, data descriptors\ndefine both ``__get__()`` and ``__set__()``, while non-data\ndescriptors have just the ``__get__()`` method. Data descriptors with\n``__set__()`` and ``__get__()`` defined always override a redefinition\nin an instance dictionary. In contrast, non-data descriptors can be\noverridden by instances.\n\nPython methods (including ``staticmethod()`` and ``classmethod()``)\nare implemented as non-data descriptors. Accordingly, instances can\nredefine and override methods. This allows individual instances to\nacquire behaviors that differ from other instances of the same class.\n\nThe ``property()`` function is implemented as a data descriptor.\nAccordingly, instances cannot override the behavior of a property.\n\n\n__slots__\n---------\n\nBy default, instances of both old and new-style classes have a\ndictionary for attribute storage. This wastes space for objects\nhaving very few instance variables. The space consumption can become\nacute when creating large numbers of instances.\n\nThe default can be overridden by defining *__slots__* in a new-style\nclass definition. The *__slots__* declaration takes a sequence of\ninstance variables and reserves just enough space in each instance to\nhold a value for each variable. Space is saved because *__dict__* is\nnot created for each instance.\n\n__slots__\n\n This class variable can be assigned a string, iterable, or sequence\n of strings with variable names used by instances. If defined in a\n new-style class, *__slots__* reserves space for the declared\n variables and prevents the automatic creation of *__dict__* and\n *__weakref__* for each instance.\n\n New in version 2.2.\n\nNotes on using *__slots__*\n\n* When inheriting from a class without *__slots__*, the *__dict__*\n attribute of that class will always be accessible, so a *__slots__*\n definition in the subclass is meaningless.\n\n* Without a *__dict__* variable, instances cannot be assigned new\n variables not listed in the *__slots__* definition. Attempts to\n assign to an unlisted variable name raises ``AttributeError``. If\n dynamic assignment of new variables is desired, then add\n ``\'__dict__\'`` to the sequence of strings in the *__slots__*\n declaration.\n\n Changed in version 2.3: Previously, adding ``\'__dict__\'`` to the\n *__slots__* declaration would not enable the assignment of new\n attributes not specifically listed in the sequence of instance\n variable names.\n\n* Without a *__weakref__* variable for each instance, classes defining\n *__slots__* do not support weak references to its instances. If weak\n reference support is needed, then add ``\'__weakref__\'`` to the\n sequence of strings in the *__slots__* declaration.\n\n Changed in version 2.3: Previously, adding ``\'__weakref__\'`` to the\n *__slots__* declaration would not enable support for weak\n references.\n\n* *__slots__* are implemented at the class level by creating\n descriptors (*Implementing Descriptors*) for each variable name. As\n a result, class attributes cannot be used to set default values for\n instance variables defined by *__slots__*; otherwise, the class\n attribute would overwrite the descriptor assignment.\n\n* The action of a *__slots__* declaration is limited to the class\n where it is defined. As a result, subclasses will have a *__dict__*\n unless they also define *__slots__* (which must only contain names\n of any *additional* slots).\n\n* If a class defines a slot also defined in a base class, the instance\n variable defined by the base class slot is inaccessible (except by\n retrieving its descriptor directly from the base class). This\n renders the meaning of the program undefined. In the future, a\n check may be added to prevent this.\n\n* Nonempty *__slots__* does not work for classes derived from\n "variable-length" built-in types such as ``long``, ``str`` and\n ``tuple``.\n\n* Any non-string iterable may be assigned to *__slots__*. Mappings may\n also be used; however, in the future, special meaning may be\n assigned to the values corresponding to each key.\n\n* *__class__* assignment works only if both classes have the same\n *__slots__*.\n\n Changed in version 2.6: Previously, *__class__* assignment raised an\n error if either new or old class had *__slots__*.\n\n\nCustomizing class creation\n==========================\n\nBy default, new-style classes are constructed using ``type()``. A\nclass definition is read into a separate namespace and the value of\nclass name is bound to the result of ``type(name, bases, dict)``.\n\nWhen the class definition is read, if *__metaclass__* is defined then\nthe callable assigned to it will be called instead of ``type()``. This\nallows classes or functions to be written which monitor or alter the\nclass creation process:\n\n* Modifying the class dictionary prior to the class being created.\n\n* Returning an instance of another class -- essentially performing the\n role of a factory function.\n\nThese steps will have to be performed in the metaclass\'s ``__new__()``\nmethod -- ``type.__new__()`` can then be called from this method to\ncreate a class with different properties. This example adds a new\nelement to the class dictionary before creating the class:\n\n class metacls(type):\n def __new__(mcs, name, bases, dict):\n dict[\'foo\'] = \'metacls was here\'\n return type.__new__(mcs, name, bases, dict)\n\nYou can of course also override other class methods (or add new\nmethods); for example defining a custom ``__call__()`` method in the\nmetaclass allows custom behavior when the class is called, e.g. not\nalways creating a new instance.\n\n__metaclass__\n\n This variable can be any callable accepting arguments for ``name``,\n ``bases``, and ``dict``. Upon class creation, the callable is used\n instead of the built-in ``type()``.\n\n New in version 2.2.\n\nThe appropriate metaclass is determined by the following precedence\nrules:\n\n* If ``dict[\'__metaclass__\']`` exists, it is used.\n\n* Otherwise, if there is at least one base class, its metaclass is\n used (this looks for a *__class__* attribute first and if not found,\n uses its type).\n\n* Otherwise, if a global variable named __metaclass__ exists, it is\n used.\n\n* Otherwise, the old-style, classic metaclass (types.ClassType) is\n used.\n\nThe potential uses for metaclasses are boundless. Some ideas that have\nbeen explored including logging, interface checking, automatic\ndelegation, automatic property creation, proxies, frameworks, and\nautomatic resource locking/synchronization.\n\n\nEmulating callable objects\n==========================\n\nobject.__call__(self[, args...])\n\n Called when the instance is "called" as a function; if this method\n is defined, ``x(arg1, arg2, ...)`` is a shorthand for\n ``x.__call__(arg1, arg2, ...)``.\n\n\nEmulating container types\n=========================\n\nThe following methods can be defined to implement container objects.\nContainers usually are sequences (such as lists or tuples) or mappings\n(like dictionaries), but can represent other containers as well. The\nfirst set of methods is used either to emulate a sequence or to\nemulate a mapping; the difference is that for a sequence, the\nallowable keys should be the integers *k* for which ``0 <= k < N``\nwhere *N* is the length of the sequence, or slice objects, which\ndefine a range of items. (For backwards compatibility, the method\n``__getslice__()`` (see below) can also be defined to handle simple,\nbut not extended slices.) It is also recommended that mappings provide\nthe methods ``keys()``, ``values()``, ``items()``, ``has_key()``,\n``get()``, ``clear()``, ``setdefault()``, ``iterkeys()``,\n``itervalues()``, ``iteritems()``, ``pop()``, ``popitem()``,\n``copy()``, and ``update()`` behaving similar to those for Python\'s\nstandard dictionary objects. The ``UserDict`` module provides a\n``DictMixin`` class to help create those methods from a base set of\n``__getitem__()``, ``__setitem__()``, ``__delitem__()``, and\n``keys()``. Mutable sequences should provide methods ``append()``,\n``count()``, ``index()``, ``extend()``, ``insert()``, ``pop()``,\n``remove()``, ``reverse()`` and ``sort()``, like Python standard list\nobjects. Finally, sequence types should implement addition (meaning\nconcatenation) and multiplication (meaning repetition) by defining the\nmethods ``__add__()``, ``__radd__()``, ``__iadd__()``, ``__mul__()``,\n``__rmul__()`` and ``__imul__()`` described below; they should not\ndefine ``__coerce__()`` or other numerical operators. It is\nrecommended that both mappings and sequences implement the\n``__contains__()`` method to allow efficient use of the ``in``\noperator; for mappings, ``in`` should be equivalent of ``has_key()``;\nfor sequences, it should search through the values. It is further\nrecommended that both mappings and sequences implement the\n``__iter__()`` method to allow efficient iteration through the\ncontainer; for mappings, ``__iter__()`` should be the same as\n``iterkeys()``; for sequences, it should iterate through the values.\n\nobject.__len__(self)\n\n Called to implement the built-in function ``len()``. Should return\n the length of the object, an integer ``>=`` 0. Also, an object\n that doesn\'t define a ``__nonzero__()`` method and whose\n ``__len__()`` method returns zero is considered to be false in a\n Boolean context.\n\nobject.__getitem__(self, key)\n\n Called to implement evaluation of ``self[key]``. For sequence\n types, the accepted keys should be integers and slice objects.\n Note that the special interpretation of negative indexes (if the\n class wishes to emulate a sequence type) is up to the\n ``__getitem__()`` method. If *key* is of an inappropriate type,\n ``TypeError`` may be raised; if of a value outside the set of\n indexes for the sequence (after any special interpretation of\n negative values), ``IndexError`` should be raised. For mapping\n types, if *key* is missing (not in the container), ``KeyError``\n should be raised.\n\n Note: ``for`` loops expect that an ``IndexError`` will be raised for\n illegal indexes to allow proper detection of the end of the\n sequence.\n\nobject.__setitem__(self, key, value)\n\n Called to implement assignment to ``self[key]``. Same note as for\n ``__getitem__()``. This should only be implemented for mappings if\n the objects support changes to the values for keys, or if new keys\n can be added, or for sequences if elements can be replaced. The\n same exceptions should be raised for improper *key* values as for\n the ``__getitem__()`` method.\n\nobject.__delitem__(self, key)\n\n Called to implement deletion of ``self[key]``. Same note as for\n ``__getitem__()``. This should only be implemented for mappings if\n the objects support removal of keys, or for sequences if elements\n can be removed from the sequence. The same exceptions should be\n raised for improper *key* values as for the ``__getitem__()``\n method.\n\nobject.__iter__(self)\n\n This method is called when an iterator is required for a container.\n This method should return a new iterator object that can iterate\n over all the objects in the container. For mappings, it should\n iterate over the keys of the container, and should also be made\n available as the method ``iterkeys()``.\n\n Iterator objects also need to implement this method; they are\n required to return themselves. For more information on iterator\n objects, see *Iterator Types*.\n\nobject.__reversed__(self)\n\n Called (if present) by the ``reversed()`` built-in to implement\n reverse iteration. It should return a new iterator object that\n iterates over all the objects in the container in reverse order.\n\n If the ``__reversed__()`` method is not provided, the\n ``reversed()`` built-in will fall back to using the sequence\n protocol (``__len__()`` and ``__getitem__()``). Objects that\n support the sequence protocol should only provide\n ``__reversed__()`` if they can provide an implementation that is\n more efficient than the one provided by ``reversed()``.\n\n New in version 2.6.\n\nThe membership test operators (``in`` and ``not in``) are normally\nimplemented as an iteration through a sequence. However, container\nobjects can supply the following special method with a more efficient\nimplementation, which also does not require the object be a sequence.\n\nobject.__contains__(self, item)\n\n Called to implement membership test operators. Should return true\n if *item* is in *self*, false otherwise. For mapping objects, this\n should consider the keys of the mapping rather than the values or\n the key-item pairs.\n\n For objects that don\'t define ``__contains__()``, the membership\n test first tries iteration via ``__iter__()``, then the old\n sequence iteration protocol via ``__getitem__()``, see *this\n section in the language reference*.\n\n\nAdditional methods for emulation of sequence types\n==================================================\n\nThe following optional methods can be defined to further emulate\nsequence objects. Immutable sequences methods should at most only\ndefine ``__getslice__()``; mutable sequences might define all three\nmethods.\n\nobject.__getslice__(self, i, j)\n\n Deprecated since version 2.0: Support slice objects as parameters\n to the ``__getitem__()`` method. (However, built-in types in\n CPython currently still implement ``__getslice__()``. Therefore,\n you have to override it in derived classes when implementing\n slicing.)\n\n Called to implement evaluation of ``self[i:j]``. The returned\n object should be of the same type as *self*. Note that missing *i*\n or *j* in the slice expression are replaced by zero or\n ``sys.maxint``, respectively. If negative indexes are used in the\n slice, the length of the sequence is added to that index. If the\n instance does not implement the ``__len__()`` method, an\n ``AttributeError`` is raised. No guarantee is made that indexes\n adjusted this way are not still negative. Indexes which are\n greater than the length of the sequence are not modified. If no\n ``__getslice__()`` is found, a slice object is created instead, and\n passed to ``__getitem__()`` instead.\n\nobject.__setslice__(self, i, j, sequence)\n\n Called to implement assignment to ``self[i:j]``. Same notes for *i*\n and *j* as for ``__getslice__()``.\n\n This method is deprecated. If no ``__setslice__()`` is found, or\n for extended slicing of the form ``self[i:j:k]``, a slice object is\n created, and passed to ``__setitem__()``, instead of\n ``__setslice__()`` being called.\n\nobject.__delslice__(self, i, j)\n\n Called to implement deletion of ``self[i:j]``. Same notes for *i*\n and *j* as for ``__getslice__()``. This method is deprecated. If no\n ``__delslice__()`` is found, or for extended slicing of the form\n ``self[i:j:k]``, a slice object is created, and passed to\n ``__delitem__()``, instead of ``__delslice__()`` being called.\n\nNotice that these methods are only invoked when a single slice with a\nsingle colon is used, and the slice method is available. For slice\noperations involving extended slice notation, or in absence of the\nslice methods, ``__getitem__()``, ``__setitem__()`` or\n``__delitem__()`` is called with a slice object as argument.\n\nThe following example demonstrate how to make your program or module\ncompatible with earlier versions of Python (assuming that methods\n``__getitem__()``, ``__setitem__()`` and ``__delitem__()`` support\nslice objects as arguments):\n\n class MyClass:\n ...\n def __getitem__(self, index):\n ...\n def __setitem__(self, index, value):\n ...\n def __delitem__(self, index):\n ...\n\n if sys.version_info < (2, 0):\n # They won\'t be defined if version is at least 2.0 final\n\n def __getslice__(self, i, j):\n return self[max(0, i):max(0, j):]\n def __setslice__(self, i, j, seq):\n self[max(0, i):max(0, j):] = seq\n def __delslice__(self, i, j):\n del self[max(0, i):max(0, j):]\n ...\n\nNote the calls to ``max()``; these are necessary because of the\nhandling of negative indices before the ``__*slice__()`` methods are\ncalled. When negative indexes are used, the ``__*item__()`` methods\nreceive them as provided, but the ``__*slice__()`` methods get a\n"cooked" form of the index values. For each negative index value, the\nlength of the sequence is added to the index before calling the method\n(which may still result in a negative index); this is the customary\nhandling of negative indexes by the built-in sequence types, and the\n``__*item__()`` methods are expected to do this as well. However,\nsince they should already be doing that, negative indexes cannot be\npassed in; they must be constrained to the bounds of the sequence\nbefore being passed to the ``__*item__()`` methods. Calling ``max(0,\ni)`` conveniently returns the proper value.\n\n\nEmulating numeric types\n=======================\n\nThe following methods can be defined to emulate numeric objects.\nMethods corresponding to operations that are not supported by the\nparticular kind of number implemented (e.g., bitwise operations for\nnon-integral numbers) should be left undefined.\n\nobject.__add__(self, other)\nobject.__sub__(self, other)\nobject.__mul__(self, other)\nobject.__floordiv__(self, other)\nobject.__mod__(self, other)\nobject.__divmod__(self, other)\nobject.__pow__(self, other[, modulo])\nobject.__lshift__(self, other)\nobject.__rshift__(self, other)\nobject.__and__(self, other)\nobject.__xor__(self, other)\nobject.__or__(self, other)\n\n These methods are called to implement the binary arithmetic\n operations (``+``, ``-``, ``*``, ``//``, ``%``, ``divmod()``,\n ``pow()``, ``**``, ``<<``, ``>>``, ``&``, ``^``, ``|``). For\n instance, to evaluate the expression ``x + y``, where *x* is an\n instance of a class that has an ``__add__()`` method,\n ``x.__add__(y)`` is called. The ``__divmod__()`` method should be\n the equivalent to using ``__floordiv__()`` and ``__mod__()``; it\n should not be related to ``__truediv__()`` (described below). Note\n that ``__pow__()`` should be defined to accept an optional third\n argument if the ternary version of the built-in ``pow()`` function\n is to be supported.\n\n If one of those methods does not support the operation with the\n supplied arguments, it should return ``NotImplemented``.\n\nobject.__div__(self, other)\nobject.__truediv__(self, other)\n\n The division operator (``/``) is implemented by these methods. The\n ``__truediv__()`` method is used when ``__future__.division`` is in\n effect, otherwise ``__div__()`` is used. If only one of these two\n methods is defined, the object will not support division in the\n alternate context; ``TypeError`` will be raised instead.\n\nobject.__radd__(self, other)\nobject.__rsub__(self, other)\nobject.__rmul__(self, other)\nobject.__rdiv__(self, other)\nobject.__rtruediv__(self, other)\nobject.__rfloordiv__(self, other)\nobject.__rmod__(self, other)\nobject.__rdivmod__(self, other)\nobject.__rpow__(self, other)\nobject.__rlshift__(self, other)\nobject.__rrshift__(self, other)\nobject.__rand__(self, other)\nobject.__rxor__(self, other)\nobject.__ror__(self, other)\n\n These methods are called to implement the binary arithmetic\n operations (``+``, ``-``, ``*``, ``/``, ``%``, ``divmod()``,\n ``pow()``, ``**``, ``<<``, ``>>``, ``&``, ``^``, ``|``) with\n reflected (swapped) operands. These functions are only called if\n the left operand does not support the corresponding operation and\n the operands are of different types. [2] For instance, to evaluate\n the expression ``x - y``, where *y* is an instance of a class that\n has an ``__rsub__()`` method, ``y.__rsub__(x)`` is called if\n ``x.__sub__(y)`` returns *NotImplemented*.\n\n Note that ternary ``pow()`` will not try calling ``__rpow__()``\n (the coercion rules would become too complicated).\n\n Note: If the right operand\'s type is a subclass of the left operand\'s\n type and that subclass provides the reflected method for the\n operation, this method will be called before the left operand\'s\n non-reflected method. This behavior allows subclasses to\n override their ancestors\' operations.\n\nobject.__iadd__(self, other)\nobject.__isub__(self, other)\nobject.__imul__(self, other)\nobject.__idiv__(self, other)\nobject.__itruediv__(self, other)\nobject.__ifloordiv__(self, other)\nobject.__imod__(self, other)\nobject.__ipow__(self, other[, modulo])\nobject.__ilshift__(self, other)\nobject.__irshift__(self, other)\nobject.__iand__(self, other)\nobject.__ixor__(self, other)\nobject.__ior__(self, other)\n\n These methods are called to implement the augmented arithmetic\n assignments (``+=``, ``-=``, ``*=``, ``/=``, ``//=``, ``%=``,\n ``**=``, ``<<=``, ``>>=``, ``&=``, ``^=``, ``|=``). These methods\n should attempt to do the operation in-place (modifying *self*) and\n return the result (which could be, but does not have to be,\n *self*). If a specific method is not defined, the augmented\n assignment falls back to the normal methods. For instance, to\n execute the statement ``x += y``, where *x* is an instance of a\n class that has an ``__iadd__()`` method, ``x.__iadd__(y)`` is\n called. If *x* is an instance of a class that does not define a\n ``__iadd__()`` method, ``x.__add__(y)`` and ``y.__radd__(x)`` are\n considered, as with the evaluation of ``x + y``.\n\nobject.__neg__(self)\nobject.__pos__(self)\nobject.__abs__(self)\nobject.__invert__(self)\n\n Called to implement the unary arithmetic operations (``-``, ``+``,\n ``abs()`` and ``~``).\n\nobject.__complex__(self)\nobject.__int__(self)\nobject.__long__(self)\nobject.__float__(self)\n\n Called to implement the built-in functions ``complex()``,\n ``int()``, ``long()``, and ``float()``. Should return a value of\n the appropriate type.\n\nobject.__oct__(self)\nobject.__hex__(self)\n\n Called to implement the built-in functions ``oct()`` and ``hex()``.\n Should return a string value.\n\nobject.__index__(self)\n\n Called to implement ``operator.index()``. Also called whenever\n Python needs an integer object (such as in slicing). Must return\n an integer (int or long).\n\n New in version 2.5.\n\nobject.__coerce__(self, other)\n\n Called to implement "mixed-mode" numeric arithmetic. Should either\n return a 2-tuple containing *self* and *other* converted to a\n common numeric type, or ``None`` if conversion is impossible. When\n the common type would be the type of ``other``, it is sufficient to\n return ``None``, since the interpreter will also ask the other\n object to attempt a coercion (but sometimes, if the implementation\n of the other type cannot be changed, it is useful to do the\n conversion to the other type here). A return value of\n ``NotImplemented`` is equivalent to returning ``None``.\n\n\nCoercion rules\n==============\n\nThis section used to document the rules for coercion. As the language\nhas evolved, the coercion rules have become hard to document\nprecisely; documenting what one version of one particular\nimplementation does is undesirable. Instead, here are some informal\nguidelines regarding coercion. In Python 3.0, coercion will not be\nsupported.\n\n* If the left operand of a % operator is a string or Unicode object,\n no coercion takes place and the string formatting operation is\n invoked instead.\n\n* It is no longer recommended to define a coercion operation. Mixed-\n mode operations on types that don\'t define coercion pass the\n original arguments to the operation.\n\n* New-style classes (those derived from ``object``) never invoke the\n ``__coerce__()`` method in response to a binary operator; the only\n time ``__coerce__()`` is invoked is when the built-in function\n ``coerce()`` is called.\n\n* For most intents and purposes, an operator that returns\n ``NotImplemented`` is treated the same as one that is not\n implemented at all.\n\n* Below, ``__op__()`` and ``__rop__()`` are used to signify the\n generic method names corresponding to an operator; ``__iop__()`` is\n used for the corresponding in-place operator. For example, for the\n operator \'``+``\', ``__add__()`` and ``__radd__()`` are used for the\n left and right variant of the binary operator, and ``__iadd__()``\n for the in-place variant.\n\n* For objects *x* and *y*, first ``x.__op__(y)`` is tried. If this is\n not implemented or returns ``NotImplemented``, ``y.__rop__(x)`` is\n tried. If this is also not implemented or returns\n ``NotImplemented``, a ``TypeError`` exception is raised. But see\n the following exception:\n\n* Exception to the previous item: if the left operand is an instance\n of a built-in type or a new-style class, and the right operand is an\n instance of a proper subclass of that type or class and overrides\n the base\'s ``__rop__()`` method, the right operand\'s ``__rop__()``\n method is tried *before* the left operand\'s ``__op__()`` method.\n\n This is done so that a subclass can completely override binary\n operators. Otherwise, the left operand\'s ``__op__()`` method would\n always accept the right operand: when an instance of a given class\n is expected, an instance of a subclass of that class is always\n acceptable.\n\n* When either operand type defines a coercion, this coercion is called\n before that type\'s ``__op__()`` or ``__rop__()`` method is called,\n but no sooner. If the coercion returns an object of a different\n type for the operand whose coercion is invoked, part of the process\n is redone using the new object.\n\n* When an in-place operator (like \'``+=``\') is used, if the left\n operand implements ``__iop__()``, it is invoked without any\n coercion. When the operation falls back to ``__op__()`` and/or\n ``__rop__()``, the normal coercion rules apply.\n\n* In ``x + y``, if *x* is a sequence that implements sequence\n concatenation, sequence concatenation is invoked.\n\n* In ``x * y``, if one operator is a sequence that implements sequence\n repetition, and the other is an integer (``int`` or ``long``),\n sequence repetition is invoked.\n\n* Rich comparisons (implemented by methods ``__eq__()`` and so on)\n never use coercion. Three-way comparison (implemented by\n ``__cmp__()``) does use coercion under the same conditions as other\n binary operations use it.\n\n* In the current implementation, the built-in numeric types ``int``,\n ``long``, ``float``, and ``complex`` do not use coercion. All these\n types implement a ``__coerce__()`` method, for use by the built-in\n ``coerce()`` function.\n\n Changed in version 2.7.\n\n\nWith Statement Context Managers\n===============================\n\nNew in version 2.5.\n\nA *context manager* is an object that defines the runtime context to\nbe established when executing a ``with`` statement. The context\nmanager handles the entry into, and the exit from, the desired runtime\ncontext for the execution of the block of code. Context managers are\nnormally invoked using the ``with`` statement (described in section\n*The with statement*), but can also be used by directly invoking their\nmethods.\n\nTypical uses of context managers include saving and restoring various\nkinds of global state, locking and unlocking resources, closing opened\nfiles, etc.\n\nFor more information on context managers, see *Context Manager Types*.\n\nobject.__enter__(self)\n\n Enter the runtime context related to this object. The ``with``\n statement will bind this method\'s return value to the target(s)\n specified in the ``as`` clause of the statement, if any.\n\nobject.__exit__(self, exc_type, exc_value, traceback)\n\n Exit the runtime context related to this object. The parameters\n describe the exception that caused the context to be exited. If the\n context was exited without an exception, all three arguments will\n be ``None``.\n\n If an exception is supplied, and the method wishes to suppress the\n exception (i.e., prevent it from being propagated), it should\n return a true value. Otherwise, the exception will be processed\n normally upon exit from this method.\n\n Note that ``__exit__()`` methods should not reraise the passed-in\n exception; this is the caller\'s responsibility.\n\nSee also:\n\n **PEP 0343** - The "with" statement\n The specification, background, and examples for the Python\n ``with`` statement.\n\n\nSpecial method lookup for old-style classes\n===========================================\n\nFor old-style classes, special methods are always looked up in exactly\nthe same way as any other method or attribute. This is the case\nregardless of whether the method is being looked up explicitly as in\n``x.__getitem__(i)`` or implicitly as in ``x[i]``.\n\nThis behaviour means that special methods may exhibit different\nbehaviour for different instances of a single old-style class if the\nappropriate special attributes are set differently:\n\n >>> class C:\n ... pass\n ...\n >>> c1 = C()\n >>> c2 = C()\n >>> c1.__len__ = lambda: 5\n >>> c2.__len__ = lambda: 9\n >>> len(c1)\n 5\n >>> len(c2)\n 9\n\n\nSpecial method lookup for new-style classes\n===========================================\n\nFor new-style classes, implicit invocations of special methods are\nonly guaranteed to work correctly if defined on an object\'s type, not\nin the object\'s instance dictionary. That behaviour is the reason why\nthe following code raises an exception (unlike the equivalent example\nwith old-style classes):\n\n >>> class C(object):\n ... pass\n ...\n >>> c = C()\n >>> c.__len__ = lambda: 5\n >>> len(c)\n Traceback (most recent call last):\n File "", line 1, in \n TypeError: object of type \'C\' has no len()\n\nThe rationale behind this behaviour lies with a number of special\nmethods such as ``__hash__()`` and ``__repr__()`` that are implemented\nby all objects, including type objects. If the implicit lookup of\nthese methods used the conventional lookup process, they would fail\nwhen invoked on the type object itself:\n\n >>> 1 .__hash__() == hash(1)\n True\n >>> int.__hash__() == hash(int)\n Traceback (most recent call last):\n File "", line 1, in \n TypeError: descriptor \'__hash__\' of \'int\' object needs an argument\n\nIncorrectly attempting to invoke an unbound method of a class in this\nway is sometimes referred to as \'metaclass confusion\', and is avoided\nby bypassing the instance when looking up special methods:\n\n >>> type(1).__hash__(1) == hash(1)\n True\n >>> type(int).__hash__(int) == hash(int)\n True\n\nIn addition to bypassing any instance attributes in the interest of\ncorrectness, implicit special method lookup generally also bypasses\nthe ``__getattribute__()`` method even of the object\'s metaclass:\n\n >>> class Meta(type):\n ... def __getattribute__(*args):\n ... print "Metaclass getattribute invoked"\n ... return type.__getattribute__(*args)\n ...\n >>> class C(object):\n ... __metaclass__ = Meta\n ... def __len__(self):\n ... return 10\n ... def __getattribute__(*args):\n ... print "Class getattribute invoked"\n ... return object.__getattribute__(*args)\n ...\n >>> c = C()\n >>> c.__len__() # Explicit lookup via instance\n Class getattribute invoked\n 10\n >>> type(c).__len__(c) # Explicit lookup via type\n Metaclass getattribute invoked\n 10\n >>> len(c) # Implicit lookup\n 10\n\nBypassing the ``__getattribute__()`` machinery in this fashion\nprovides significant scope for speed optimisations within the\ninterpreter, at the cost of some flexibility in the handling of\nspecial methods (the special method *must* be set on the class object\nitself in order to be consistently invoked by the interpreter).\n\n-[ Footnotes ]-\n\n[1] It *is* possible in some cases to change an object\'s type, under\n certain controlled conditions. It generally isn\'t a good idea\n though, since it can lead to some very strange behaviour if it is\n handled incorrectly.\n\n[2] For operands of the same type, it is assumed that if the non-\n reflected method (such as ``__add__()``) fails the operation is\n not supported, which is why the reflected method is not called.\n', + 'specialnames': u'\nSpecial method names\n********************\n\nA class can implement certain operations that are invoked by special\nsyntax (such as arithmetic operations or subscripting and slicing) by\ndefining methods with special names. This is Python\'s approach to\n*operator overloading*, allowing classes to define their own behavior\nwith respect to language operators. For instance, if a class defines\na method named ``__getitem__()``, and ``x`` is an instance of this\nclass, then ``x[i]`` is roughly equivalent to ``x.__getitem__(i)`` for\nold-style classes and ``type(x).__getitem__(x, i)`` for new-style\nclasses. Except where mentioned, attempts to execute an operation\nraise an exception when no appropriate method is defined (typically\n``AttributeError`` or ``TypeError``).\n\nWhen implementing a class that emulates any built-in type, it is\nimportant that the emulation only be implemented to the degree that it\nmakes sense for the object being modelled. For example, some\nsequences may work well with retrieval of individual elements, but\nextracting a slice may not make sense. (One example of this is the\n``NodeList`` interface in the W3C\'s Document Object Model.)\n\n\nBasic customization\n===================\n\nobject.__new__(cls[, ...])\n\n Called to create a new instance of class *cls*. ``__new__()`` is a\n static method (special-cased so you need not declare it as such)\n that takes the class of which an instance was requested as its\n first argument. The remaining arguments are those passed to the\n object constructor expression (the call to the class). The return\n value of ``__new__()`` should be the new object instance (usually\n an instance of *cls*).\n\n Typical implementations create a new instance of the class by\n invoking the superclass\'s ``__new__()`` method using\n ``super(currentclass, cls).__new__(cls[, ...])`` with appropriate\n arguments and then modifying the newly-created instance as\n necessary before returning it.\n\n If ``__new__()`` returns an instance of *cls*, then the new\n instance\'s ``__init__()`` method will be invoked like\n ``__init__(self[, ...])``, where *self* is the new instance and the\n remaining arguments are the same as were passed to ``__new__()``.\n\n If ``__new__()`` does not return an instance of *cls*, then the new\n instance\'s ``__init__()`` method will not be invoked.\n\n ``__new__()`` is intended mainly to allow subclasses of immutable\n types (like int, str, or tuple) to customize instance creation. It\n is also commonly overridden in custom metaclasses in order to\n customize class creation.\n\nobject.__init__(self[, ...])\n\n Called when the instance is created. The arguments are those\n passed to the class constructor expression. If a base class has an\n ``__init__()`` method, the derived class\'s ``__init__()`` method,\n if any, must explicitly call it to ensure proper initialization of\n the base class part of the instance; for example:\n ``BaseClass.__init__(self, [args...])``. As a special constraint\n on constructors, no value may be returned; doing so will cause a\n ``TypeError`` to be raised at runtime.\n\nobject.__del__(self)\n\n Called when the instance is about to be destroyed. This is also\n called a destructor. If a base class has a ``__del__()`` method,\n the derived class\'s ``__del__()`` method, if any, must explicitly\n call it to ensure proper deletion of the base class part of the\n instance. Note that it is possible (though not recommended!) for\n the ``__del__()`` method to postpone destruction of the instance by\n creating a new reference to it. It may then be called at a later\n time when this new reference is deleted. It is not guaranteed that\n ``__del__()`` methods are called for objects that still exist when\n the interpreter exits.\n\n Note: ``del x`` doesn\'t directly call ``x.__del__()`` --- the former\n decrements the reference count for ``x`` by one, and the latter\n is only called when ``x``\'s reference count reaches zero. Some\n common situations that may prevent the reference count of an\n object from going to zero include: circular references between\n objects (e.g., a doubly-linked list or a tree data structure with\n parent and child pointers); a reference to the object on the\n stack frame of a function that caught an exception (the traceback\n stored in ``sys.exc_traceback`` keeps the stack frame alive); or\n a reference to the object on the stack frame that raised an\n unhandled exception in interactive mode (the traceback stored in\n ``sys.last_traceback`` keeps the stack frame alive). The first\n situation can only be remedied by explicitly breaking the cycles;\n the latter two situations can be resolved by storing ``None`` in\n ``sys.exc_traceback`` or ``sys.last_traceback``. Circular\n references which are garbage are detected when the option cycle\n detector is enabled (it\'s on by default), but can only be cleaned\n up if there are no Python-level ``__del__()`` methods involved.\n Refer to the documentation for the ``gc`` module for more\n information about how ``__del__()`` methods are handled by the\n cycle detector, particularly the description of the ``garbage``\n value.\n\n Warning: Due to the precarious circumstances under which ``__del__()``\n methods are invoked, exceptions that occur during their execution\n are ignored, and a warning is printed to ``sys.stderr`` instead.\n Also, when ``__del__()`` is invoked in response to a module being\n deleted (e.g., when execution of the program is done), other\n globals referenced by the ``__del__()`` method may already have\n been deleted or in the process of being torn down (e.g. the\n import machinery shutting down). For this reason, ``__del__()``\n methods should do the absolute minimum needed to maintain\n external invariants. Starting with version 1.5, Python\n guarantees that globals whose name begins with a single\n underscore are deleted from their module before other globals are\n deleted; if no other references to such globals exist, this may\n help in assuring that imported modules are still available at the\n time when the ``__del__()`` method is called.\n\nobject.__repr__(self)\n\n Called by the ``repr()`` built-in function and by string\n conversions (reverse quotes) to compute the "official" string\n representation of an object. If at all possible, this should look\n like a valid Python expression that could be used to recreate an\n object with the same value (given an appropriate environment). If\n this is not possible, a string of the form ``<...some useful\n description...>`` should be returned. The return value must be a\n string object. If a class defines ``__repr__()`` but not\n ``__str__()``, then ``__repr__()`` is also used when an "informal"\n string representation of instances of that class is required.\n\n This is typically used for debugging, so it is important that the\n representation is information-rich and unambiguous.\n\nobject.__str__(self)\n\n Called by the ``str()`` built-in function and by the ``print``\n statement to compute the "informal" string representation of an\n object. This differs from ``__repr__()`` in that it does not have\n to be a valid Python expression: a more convenient or concise\n representation may be used instead. The return value must be a\n string object.\n\nobject.__lt__(self, other)\nobject.__le__(self, other)\nobject.__eq__(self, other)\nobject.__ne__(self, other)\nobject.__gt__(self, other)\nobject.__ge__(self, other)\n\n New in version 2.1.\n\n These are the so-called "rich comparison" methods, and are called\n for comparison operators in preference to ``__cmp__()`` below. The\n correspondence between operator symbols and method names is as\n follows: ``xy`` call ``x.__ne__(y)``, ``x>y`` calls ``x.__gt__(y)``, and\n ``x>=y`` calls ``x.__ge__(y)``.\n\n A rich comparison method may return the singleton\n ``NotImplemented`` if it does not implement the operation for a\n given pair of arguments. By convention, ``False`` and ``True`` are\n returned for a successful comparison. However, these methods can\n return any value, so if the comparison operator is used in a\n Boolean context (e.g., in the condition of an ``if`` statement),\n Python will call ``bool()`` on the value to determine if the result\n is true or false.\n\n There are no implied relationships among the comparison operators.\n The truth of ``x==y`` does not imply that ``x!=y`` is false.\n Accordingly, when defining ``__eq__()``, one should also define\n ``__ne__()`` so that the operators will behave as expected. See\n the paragraph on ``__hash__()`` for some important notes on\n creating *hashable* objects which support custom comparison\n operations and are usable as dictionary keys.\n\n There are no swapped-argument versions of these methods (to be used\n when the left argument does not support the operation but the right\n argument does); rather, ``__lt__()`` and ``__gt__()`` are each\n other\'s reflection, ``__le__()`` and ``__ge__()`` are each other\'s\n reflection, and ``__eq__()`` and ``__ne__()`` are their own\n reflection.\n\n Arguments to rich comparison methods are never coerced.\n\n To automatically generate ordering operations from a single root\n operation, see ``functools.total_ordering()``.\n\nobject.__cmp__(self, other)\n\n Called by comparison operations if rich comparison (see above) is\n not defined. Should return a negative integer if ``self < other``,\n zero if ``self == other``, a positive integer if ``self > other``.\n If no ``__cmp__()``, ``__eq__()`` or ``__ne__()`` operation is\n defined, class instances are compared by object identity\n ("address"). See also the description of ``__hash__()`` for some\n important notes on creating *hashable* objects which support custom\n comparison operations and are usable as dictionary keys. (Note: the\n restriction that exceptions are not propagated by ``__cmp__()`` has\n been removed since Python 1.5.)\n\nobject.__rcmp__(self, other)\n\n Changed in version 2.1: No longer supported.\n\nobject.__hash__(self)\n\n Called by built-in function ``hash()`` and for operations on\n members of hashed collections including ``set``, ``frozenset``, and\n ``dict``. ``__hash__()`` should return an integer. The only\n required property is that objects which compare equal have the same\n hash value; it is advised to somehow mix together (e.g. using\n exclusive or) the hash values for the components of the object that\n also play a part in comparison of objects.\n\n If a class does not define a ``__cmp__()`` or ``__eq__()`` method\n it should not define a ``__hash__()`` operation either; if it\n defines ``__cmp__()`` or ``__eq__()`` but not ``__hash__()``, its\n instances will not be usable in hashed collections. If a class\n defines mutable objects and implements a ``__cmp__()`` or\n ``__eq__()`` method, it should not implement ``__hash__()``, since\n hashable collection implementations require that a object\'s hash\n value is immutable (if the object\'s hash value changes, it will be\n in the wrong hash bucket).\n\n User-defined classes have ``__cmp__()`` and ``__hash__()`` methods\n by default; with them, all objects compare unequal (except with\n themselves) and ``x.__hash__()`` returns ``id(x)``.\n\n Classes which inherit a ``__hash__()`` method from a parent class\n but change the meaning of ``__cmp__()`` or ``__eq__()`` such that\n the hash value returned is no longer appropriate (e.g. by switching\n to a value-based concept of equality instead of the default\n identity based equality) can explicitly flag themselves as being\n unhashable by setting ``__hash__ = None`` in the class definition.\n Doing so means that not only will instances of the class raise an\n appropriate ``TypeError`` when a program attempts to retrieve their\n hash value, but they will also be correctly identified as\n unhashable when checking ``isinstance(obj, collections.Hashable)``\n (unlike classes which define their own ``__hash__()`` to explicitly\n raise ``TypeError``).\n\n Changed in version 2.5: ``__hash__()`` may now also return a long\n integer object; the 32-bit integer is then derived from the hash of\n that object.\n\n Changed in version 2.6: ``__hash__`` may now be set to ``None`` to\n explicitly flag instances of a class as unhashable.\n\nobject.__nonzero__(self)\n\n Called to implement truth value testing and the built-in operation\n ``bool()``; should return ``False`` or ``True``, or their integer\n equivalents ``0`` or ``1``. When this method is not defined,\n ``__len__()`` is called, if it is defined, and the object is\n considered true if its result is nonzero. If a class defines\n neither ``__len__()`` nor ``__nonzero__()``, all its instances are\n considered true.\n\nobject.__unicode__(self)\n\n Called to implement ``unicode()`` built-in; should return a Unicode\n object. When this method is not defined, string conversion is\n attempted, and the result of string conversion is converted to\n Unicode using the system default encoding.\n\n\nCustomizing attribute access\n============================\n\nThe following methods can be defined to customize the meaning of\nattribute access (use of, assignment to, or deletion of ``x.name``)\nfor class instances.\n\nobject.__getattr__(self, name)\n\n Called when an attribute lookup has not found the attribute in the\n usual places (i.e. it is not an instance attribute nor is it found\n in the class tree for ``self``). ``name`` is the attribute name.\n This method should return the (computed) attribute value or raise\n an ``AttributeError`` exception.\n\n Note that if the attribute is found through the normal mechanism,\n ``__getattr__()`` is not called. (This is an intentional asymmetry\n between ``__getattr__()`` and ``__setattr__()``.) This is done both\n for efficiency reasons and because otherwise ``__getattr__()``\n would have no way to access other attributes of the instance. Note\n that at least for instance variables, you can fake total control by\n not inserting any values in the instance attribute dictionary (but\n instead inserting them in another object). See the\n ``__getattribute__()`` method below for a way to actually get total\n control in new-style classes.\n\nobject.__setattr__(self, name, value)\n\n Called when an attribute assignment is attempted. This is called\n instead of the normal mechanism (i.e. store the value in the\n instance dictionary). *name* is the attribute name, *value* is the\n value to be assigned to it.\n\n If ``__setattr__()`` wants to assign to an instance attribute, it\n should not simply execute ``self.name = value`` --- this would\n cause a recursive call to itself. Instead, it should insert the\n value in the dictionary of instance attributes, e.g.,\n ``self.__dict__[name] = value``. For new-style classes, rather\n than accessing the instance dictionary, it should call the base\n class method with the same name, for example,\n ``object.__setattr__(self, name, value)``.\n\nobject.__delattr__(self, name)\n\n Like ``__setattr__()`` but for attribute deletion instead of\n assignment. This should only be implemented if ``del obj.name`` is\n meaningful for the object.\n\n\nMore attribute access for new-style classes\n-------------------------------------------\n\nThe following methods only apply to new-style classes.\n\nobject.__getattribute__(self, name)\n\n Called unconditionally to implement attribute accesses for\n instances of the class. If the class also defines\n ``__getattr__()``, the latter will not be called unless\n ``__getattribute__()`` either calls it explicitly or raises an\n ``AttributeError``. This method should return the (computed)\n attribute value or raise an ``AttributeError`` exception. In order\n to avoid infinite recursion in this method, its implementation\n should always call the base class method with the same name to\n access any attributes it needs, for example,\n ``object.__getattribute__(self, name)``.\n\n Note: This method may still be bypassed when looking up special methods\n as the result of implicit invocation via language syntax or\n built-in functions. See *Special method lookup for new-style\n classes*.\n\n\nImplementing Descriptors\n------------------------\n\nThe following methods only apply when an instance of the class\ncontaining the method (a so-called *descriptor* class) appears in the\nclass dictionary of another new-style class, known as the *owner*\nclass. In the examples below, "the attribute" refers to the attribute\nwhose name is the key of the property in the owner class\'\n``__dict__``. Descriptors can only be implemented as new-style\nclasses themselves.\n\nobject.__get__(self, instance, owner)\n\n Called to get the attribute of the owner class (class attribute\n access) or of an instance of that class (instance attribute\n access). *owner* is always the owner class, while *instance* is the\n instance that the attribute was accessed through, or ``None`` when\n the attribute is accessed through the *owner*. This method should\n return the (computed) attribute value or raise an\n ``AttributeError`` exception.\n\nobject.__set__(self, instance, value)\n\n Called to set the attribute on an instance *instance* of the owner\n class to a new value, *value*.\n\nobject.__delete__(self, instance)\n\n Called to delete the attribute on an instance *instance* of the\n owner class.\n\n\nInvoking Descriptors\n--------------------\n\nIn general, a descriptor is an object attribute with "binding\nbehavior", one whose attribute access has been overridden by methods\nin the descriptor protocol: ``__get__()``, ``__set__()``, and\n``__delete__()``. If any of those methods are defined for an object,\nit is said to be a descriptor.\n\nThe default behavior for attribute access is to get, set, or delete\nthe attribute from an object\'s dictionary. For instance, ``a.x`` has a\nlookup chain starting with ``a.__dict__[\'x\']``, then\n``type(a).__dict__[\'x\']``, and continuing through the base classes of\n``type(a)`` excluding metaclasses.\n\nHowever, if the looked-up value is an object defining one of the\ndescriptor methods, then Python may override the default behavior and\ninvoke the descriptor method instead. Where this occurs in the\nprecedence chain depends on which descriptor methods were defined and\nhow they were called. Note that descriptors are only invoked for new\nstyle objects or classes (ones that subclass ``object()`` or\n``type()``).\n\nThe starting point for descriptor invocation is a binding, ``a.x``.\nHow the arguments are assembled depends on ``a``:\n\nDirect Call\n The simplest and least common call is when user code directly\n invokes a descriptor method: ``x.__get__(a)``.\n\nInstance Binding\n If binding to a new-style object instance, ``a.x`` is transformed\n into the call: ``type(a).__dict__[\'x\'].__get__(a, type(a))``.\n\nClass Binding\n If binding to a new-style class, ``A.x`` is transformed into the\n call: ``A.__dict__[\'x\'].__get__(None, A)``.\n\nSuper Binding\n If ``a`` is an instance of ``super``, then the binding ``super(B,\n obj).m()`` searches ``obj.__class__.__mro__`` for the base class\n ``A`` immediately preceding ``B`` and then invokes the descriptor\n with the call: ``A.__dict__[\'m\'].__get__(obj, A)``.\n\nFor instance bindings, the precedence of descriptor invocation depends\non the which descriptor methods are defined. A descriptor can define\nany combination of ``__get__()``, ``__set__()`` and ``__delete__()``.\nIf it does not define ``__get__()``, then accessing the attribute will\nreturn the descriptor object itself unless there is a value in the\nobject\'s instance dictionary. If the descriptor defines ``__set__()``\nand/or ``__delete__()``, it is a data descriptor; if it defines\nneither, it is a non-data descriptor. Normally, data descriptors\ndefine both ``__get__()`` and ``__set__()``, while non-data\ndescriptors have just the ``__get__()`` method. Data descriptors with\n``__set__()`` and ``__get__()`` defined always override a redefinition\nin an instance dictionary. In contrast, non-data descriptors can be\noverridden by instances.\n\nPython methods (including ``staticmethod()`` and ``classmethod()``)\nare implemented as non-data descriptors. Accordingly, instances can\nredefine and override methods. This allows individual instances to\nacquire behaviors that differ from other instances of the same class.\n\nThe ``property()`` function is implemented as a data descriptor.\nAccordingly, instances cannot override the behavior of a property.\n\n\n__slots__\n---------\n\nBy default, instances of both old and new-style classes have a\ndictionary for attribute storage. This wastes space for objects\nhaving very few instance variables. The space consumption can become\nacute when creating large numbers of instances.\n\nThe default can be overridden by defining *__slots__* in a new-style\nclass definition. The *__slots__* declaration takes a sequence of\ninstance variables and reserves just enough space in each instance to\nhold a value for each variable. Space is saved because *__dict__* is\nnot created for each instance.\n\n__slots__\n\n This class variable can be assigned a string, iterable, or sequence\n of strings with variable names used by instances. If defined in a\n new-style class, *__slots__* reserves space for the declared\n variables and prevents the automatic creation of *__dict__* and\n *__weakref__* for each instance.\n\n New in version 2.2.\n\nNotes on using *__slots__*\n\n* When inheriting from a class without *__slots__*, the *__dict__*\n attribute of that class will always be accessible, so a *__slots__*\n definition in the subclass is meaningless.\n\n* Without a *__dict__* variable, instances cannot be assigned new\n variables not listed in the *__slots__* definition. Attempts to\n assign to an unlisted variable name raises ``AttributeError``. If\n dynamic assignment of new variables is desired, then add\n ``\'__dict__\'`` to the sequence of strings in the *__slots__*\n declaration.\n\n Changed in version 2.3: Previously, adding ``\'__dict__\'`` to the\n *__slots__* declaration would not enable the assignment of new\n attributes not specifically listed in the sequence of instance\n variable names.\n\n* Without a *__weakref__* variable for each instance, classes defining\n *__slots__* do not support weak references to its instances. If weak\n reference support is needed, then add ``\'__weakref__\'`` to the\n sequence of strings in the *__slots__* declaration.\n\n Changed in version 2.3: Previously, adding ``\'__weakref__\'`` to the\n *__slots__* declaration would not enable support for weak\n references.\n\n* *__slots__* are implemented at the class level by creating\n descriptors (*Implementing Descriptors*) for each variable name. As\n a result, class attributes cannot be used to set default values for\n instance variables defined by *__slots__*; otherwise, the class\n attribute would overwrite the descriptor assignment.\n\n* The action of a *__slots__* declaration is limited to the class\n where it is defined. As a result, subclasses will have a *__dict__*\n unless they also define *__slots__* (which must only contain names\n of any *additional* slots).\n\n* If a class defines a slot also defined in a base class, the instance\n variable defined by the base class slot is inaccessible (except by\n retrieving its descriptor directly from the base class). This\n renders the meaning of the program undefined. In the future, a\n check may be added to prevent this.\n\n* Nonempty *__slots__* does not work for classes derived from\n "variable-length" built-in types such as ``long``, ``str`` and\n ``tuple``.\n\n* Any non-string iterable may be assigned to *__slots__*. Mappings may\n also be used; however, in the future, special meaning may be\n assigned to the values corresponding to each key.\n\n* *__class__* assignment works only if both classes have the same\n *__slots__*.\n\n Changed in version 2.6: Previously, *__class__* assignment raised an\n error if either new or old class had *__slots__*.\n\n\nCustomizing class creation\n==========================\n\nBy default, new-style classes are constructed using ``type()``. A\nclass definition is read into a separate namespace and the value of\nclass name is bound to the result of ``type(name, bases, dict)``.\n\nWhen the class definition is read, if *__metaclass__* is defined then\nthe callable assigned to it will be called instead of ``type()``. This\nallows classes or functions to be written which monitor or alter the\nclass creation process:\n\n* Modifying the class dictionary prior to the class being created.\n\n* Returning an instance of another class -- essentially performing the\n role of a factory function.\n\nThese steps will have to be performed in the metaclass\'s ``__new__()``\nmethod -- ``type.__new__()`` can then be called from this method to\ncreate a class with different properties. This example adds a new\nelement to the class dictionary before creating the class:\n\n class metacls(type):\n def __new__(mcs, name, bases, dict):\n dict[\'foo\'] = \'metacls was here\'\n return type.__new__(mcs, name, bases, dict)\n\nYou can of course also override other class methods (or add new\nmethods); for example defining a custom ``__call__()`` method in the\nmetaclass allows custom behavior when the class is called, e.g. not\nalways creating a new instance.\n\n__metaclass__\n\n This variable can be any callable accepting arguments for ``name``,\n ``bases``, and ``dict``. Upon class creation, the callable is used\n instead of the built-in ``type()``.\n\n New in version 2.2.\n\nThe appropriate metaclass is determined by the following precedence\nrules:\n\n* If ``dict[\'__metaclass__\']`` exists, it is used.\n\n* Otherwise, if there is at least one base class, its metaclass is\n used (this looks for a *__class__* attribute first and if not found,\n uses its type).\n\n* Otherwise, if a global variable named __metaclass__ exists, it is\n used.\n\n* Otherwise, the old-style, classic metaclass (types.ClassType) is\n used.\n\nThe potential uses for metaclasses are boundless. Some ideas that have\nbeen explored including logging, interface checking, automatic\ndelegation, automatic property creation, proxies, frameworks, and\nautomatic resource locking/synchronization.\n\n\nCustomizing instance and subclass checks\n========================================\n\nNew in version 2.6.\n\nThe following methods are used to override the default behavior of the\n``isinstance()`` and ``issubclass()`` built-in functions.\n\nIn particular, the metaclass ``abc.ABCMeta`` implements these methods\nin order to allow the addition of Abstract Base Classes (ABCs) as\n"virtual base classes" to any class or type (including built-in\ntypes), including other ABCs.\n\nclass.__instancecheck__(self, instance)\n\n Return true if *instance* should be considered a (direct or\n indirect) instance of *class*. If defined, called to implement\n ``isinstance(instance, class)``.\n\nclass.__subclasscheck__(self, subclass)\n\n Return true if *subclass* should be considered a (direct or\n indirect) subclass of *class*. If defined, called to implement\n ``issubclass(subclass, class)``.\n\nNote that these methods are looked up on the type (metaclass) of a\nclass. They cannot be defined as class methods in the actual class.\nThis is consistent with the lookup of special methods that are called\non instances, only in this case the instance is itself a class.\n\nSee also:\n\n **PEP 3119** - Introducing Abstract Base Classes\n Includes the specification for customizing ``isinstance()`` and\n ``issubclass()`` behavior through ``__instancecheck__()`` and\n ``__subclasscheck__()``, with motivation for this functionality\n in the context of adding Abstract Base Classes (see the ``abc``\n module) to the language.\n\n\nEmulating callable objects\n==========================\n\nobject.__call__(self[, args...])\n\n Called when the instance is "called" as a function; if this method\n is defined, ``x(arg1, arg2, ...)`` is a shorthand for\n ``x.__call__(arg1, arg2, ...)``.\n\n\nEmulating container types\n=========================\n\nThe following methods can be defined to implement container objects.\nContainers usually are sequences (such as lists or tuples) or mappings\n(like dictionaries), but can represent other containers as well. The\nfirst set of methods is used either to emulate a sequence or to\nemulate a mapping; the difference is that for a sequence, the\nallowable keys should be the integers *k* for which ``0 <= k < N``\nwhere *N* is the length of the sequence, or slice objects, which\ndefine a range of items. (For backwards compatibility, the method\n``__getslice__()`` (see below) can also be defined to handle simple,\nbut not extended slices.) It is also recommended that mappings provide\nthe methods ``keys()``, ``values()``, ``items()``, ``has_key()``,\n``get()``, ``clear()``, ``setdefault()``, ``iterkeys()``,\n``itervalues()``, ``iteritems()``, ``pop()``, ``popitem()``,\n``copy()``, and ``update()`` behaving similar to those for Python\'s\nstandard dictionary objects. The ``UserDict`` module provides a\n``DictMixin`` class to help create those methods from a base set of\n``__getitem__()``, ``__setitem__()``, ``__delitem__()``, and\n``keys()``. Mutable sequences should provide methods ``append()``,\n``count()``, ``index()``, ``extend()``, ``insert()``, ``pop()``,\n``remove()``, ``reverse()`` and ``sort()``, like Python standard list\nobjects. Finally, sequence types should implement addition (meaning\nconcatenation) and multiplication (meaning repetition) by defining the\nmethods ``__add__()``, ``__radd__()``, ``__iadd__()``, ``__mul__()``,\n``__rmul__()`` and ``__imul__()`` described below; they should not\ndefine ``__coerce__()`` or other numerical operators. It is\nrecommended that both mappings and sequences implement the\n``__contains__()`` method to allow efficient use of the ``in``\noperator; for mappings, ``in`` should be equivalent of ``has_key()``;\nfor sequences, it should search through the values. It is further\nrecommended that both mappings and sequences implement the\n``__iter__()`` method to allow efficient iteration through the\ncontainer; for mappings, ``__iter__()`` should be the same as\n``iterkeys()``; for sequences, it should iterate through the values.\n\nobject.__len__(self)\n\n Called to implement the built-in function ``len()``. Should return\n the length of the object, an integer ``>=`` 0. Also, an object\n that doesn\'t define a ``__nonzero__()`` method and whose\n ``__len__()`` method returns zero is considered to be false in a\n Boolean context.\n\nobject.__getitem__(self, key)\n\n Called to implement evaluation of ``self[key]``. For sequence\n types, the accepted keys should be integers and slice objects.\n Note that the special interpretation of negative indexes (if the\n class wishes to emulate a sequence type) is up to the\n ``__getitem__()`` method. If *key* is of an inappropriate type,\n ``TypeError`` may be raised; if of a value outside the set of\n indexes for the sequence (after any special interpretation of\n negative values), ``IndexError`` should be raised. For mapping\n types, if *key* is missing (not in the container), ``KeyError``\n should be raised.\n\n Note: ``for`` loops expect that an ``IndexError`` will be raised for\n illegal indexes to allow proper detection of the end of the\n sequence.\n\nobject.__setitem__(self, key, value)\n\n Called to implement assignment to ``self[key]``. Same note as for\n ``__getitem__()``. This should only be implemented for mappings if\n the objects support changes to the values for keys, or if new keys\n can be added, or for sequences if elements can be replaced. The\n same exceptions should be raised for improper *key* values as for\n the ``__getitem__()`` method.\n\nobject.__delitem__(self, key)\n\n Called to implement deletion of ``self[key]``. Same note as for\n ``__getitem__()``. This should only be implemented for mappings if\n the objects support removal of keys, or for sequences if elements\n can be removed from the sequence. The same exceptions should be\n raised for improper *key* values as for the ``__getitem__()``\n method.\n\nobject.__iter__(self)\n\n This method is called when an iterator is required for a container.\n This method should return a new iterator object that can iterate\n over all the objects in the container. For mappings, it should\n iterate over the keys of the container, and should also be made\n available as the method ``iterkeys()``.\n\n Iterator objects also need to implement this method; they are\n required to return themselves. For more information on iterator\n objects, see *Iterator Types*.\n\nobject.__reversed__(self)\n\n Called (if present) by the ``reversed()`` built-in to implement\n reverse iteration. It should return a new iterator object that\n iterates over all the objects in the container in reverse order.\n\n If the ``__reversed__()`` method is not provided, the\n ``reversed()`` built-in will fall back to using the sequence\n protocol (``__len__()`` and ``__getitem__()``). Objects that\n support the sequence protocol should only provide\n ``__reversed__()`` if they can provide an implementation that is\n more efficient than the one provided by ``reversed()``.\n\n New in version 2.6.\n\nThe membership test operators (``in`` and ``not in``) are normally\nimplemented as an iteration through a sequence. However, container\nobjects can supply the following special method with a more efficient\nimplementation, which also does not require the object be a sequence.\n\nobject.__contains__(self, item)\n\n Called to implement membership test operators. Should return true\n if *item* is in *self*, false otherwise. For mapping objects, this\n should consider the keys of the mapping rather than the values or\n the key-item pairs.\n\n For objects that don\'t define ``__contains__()``, the membership\n test first tries iteration via ``__iter__()``, then the old\n sequence iteration protocol via ``__getitem__()``, see *this\n section in the language reference*.\n\n\nAdditional methods for emulation of sequence types\n==================================================\n\nThe following optional methods can be defined to further emulate\nsequence objects. Immutable sequences methods should at most only\ndefine ``__getslice__()``; mutable sequences might define all three\nmethods.\n\nobject.__getslice__(self, i, j)\n\n Deprecated since version 2.0: Support slice objects as parameters\n to the ``__getitem__()`` method. (However, built-in types in\n CPython currently still implement ``__getslice__()``. Therefore,\n you have to override it in derived classes when implementing\n slicing.)\n\n Called to implement evaluation of ``self[i:j]``. The returned\n object should be of the same type as *self*. Note that missing *i*\n or *j* in the slice expression are replaced by zero or\n ``sys.maxint``, respectively. If negative indexes are used in the\n slice, the length of the sequence is added to that index. If the\n instance does not implement the ``__len__()`` method, an\n ``AttributeError`` is raised. No guarantee is made that indexes\n adjusted this way are not still negative. Indexes which are\n greater than the length of the sequence are not modified. If no\n ``__getslice__()`` is found, a slice object is created instead, and\n passed to ``__getitem__()`` instead.\n\nobject.__setslice__(self, i, j, sequence)\n\n Called to implement assignment to ``self[i:j]``. Same notes for *i*\n and *j* as for ``__getslice__()``.\n\n This method is deprecated. If no ``__setslice__()`` is found, or\n for extended slicing of the form ``self[i:j:k]``, a slice object is\n created, and passed to ``__setitem__()``, instead of\n ``__setslice__()`` being called.\n\nobject.__delslice__(self, i, j)\n\n Called to implement deletion of ``self[i:j]``. Same notes for *i*\n and *j* as for ``__getslice__()``. This method is deprecated. If no\n ``__delslice__()`` is found, or for extended slicing of the form\n ``self[i:j:k]``, a slice object is created, and passed to\n ``__delitem__()``, instead of ``__delslice__()`` being called.\n\nNotice that these methods are only invoked when a single slice with a\nsingle colon is used, and the slice method is available. For slice\noperations involving extended slice notation, or in absence of the\nslice methods, ``__getitem__()``, ``__setitem__()`` or\n``__delitem__()`` is called with a slice object as argument.\n\nThe following example demonstrate how to make your program or module\ncompatible with earlier versions of Python (assuming that methods\n``__getitem__()``, ``__setitem__()`` and ``__delitem__()`` support\nslice objects as arguments):\n\n class MyClass:\n ...\n def __getitem__(self, index):\n ...\n def __setitem__(self, index, value):\n ...\n def __delitem__(self, index):\n ...\n\n if sys.version_info < (2, 0):\n # They won\'t be defined if version is at least 2.0 final\n\n def __getslice__(self, i, j):\n return self[max(0, i):max(0, j):]\n def __setslice__(self, i, j, seq):\n self[max(0, i):max(0, j):] = seq\n def __delslice__(self, i, j):\n del self[max(0, i):max(0, j):]\n ...\n\nNote the calls to ``max()``; these are necessary because of the\nhandling of negative indices before the ``__*slice__()`` methods are\ncalled. When negative indexes are used, the ``__*item__()`` methods\nreceive them as provided, but the ``__*slice__()`` methods get a\n"cooked" form of the index values. For each negative index value, the\nlength of the sequence is added to the index before calling the method\n(which may still result in a negative index); this is the customary\nhandling of negative indexes by the built-in sequence types, and the\n``__*item__()`` methods are expected to do this as well. However,\nsince they should already be doing that, negative indexes cannot be\npassed in; they must be constrained to the bounds of the sequence\nbefore being passed to the ``__*item__()`` methods. Calling ``max(0,\ni)`` conveniently returns the proper value.\n\n\nEmulating numeric types\n=======================\n\nThe following methods can be defined to emulate numeric objects.\nMethods corresponding to operations that are not supported by the\nparticular kind of number implemented (e.g., bitwise operations for\nnon-integral numbers) should be left undefined.\n\nobject.__add__(self, other)\nobject.__sub__(self, other)\nobject.__mul__(self, other)\nobject.__floordiv__(self, other)\nobject.__mod__(self, other)\nobject.__divmod__(self, other)\nobject.__pow__(self, other[, modulo])\nobject.__lshift__(self, other)\nobject.__rshift__(self, other)\nobject.__and__(self, other)\nobject.__xor__(self, other)\nobject.__or__(self, other)\n\n These methods are called to implement the binary arithmetic\n operations (``+``, ``-``, ``*``, ``//``, ``%``, ``divmod()``,\n ``pow()``, ``**``, ``<<``, ``>>``, ``&``, ``^``, ``|``). For\n instance, to evaluate the expression ``x + y``, where *x* is an\n instance of a class that has an ``__add__()`` method,\n ``x.__add__(y)`` is called. The ``__divmod__()`` method should be\n the equivalent to using ``__floordiv__()`` and ``__mod__()``; it\n should not be related to ``__truediv__()`` (described below). Note\n that ``__pow__()`` should be defined to accept an optional third\n argument if the ternary version of the built-in ``pow()`` function\n is to be supported.\n\n If one of those methods does not support the operation with the\n supplied arguments, it should return ``NotImplemented``.\n\nobject.__div__(self, other)\nobject.__truediv__(self, other)\n\n The division operator (``/``) is implemented by these methods. The\n ``__truediv__()`` method is used when ``__future__.division`` is in\n effect, otherwise ``__div__()`` is used. If only one of these two\n methods is defined, the object will not support division in the\n alternate context; ``TypeError`` will be raised instead.\n\nobject.__radd__(self, other)\nobject.__rsub__(self, other)\nobject.__rmul__(self, other)\nobject.__rdiv__(self, other)\nobject.__rtruediv__(self, other)\nobject.__rfloordiv__(self, other)\nobject.__rmod__(self, other)\nobject.__rdivmod__(self, other)\nobject.__rpow__(self, other)\nobject.__rlshift__(self, other)\nobject.__rrshift__(self, other)\nobject.__rand__(self, other)\nobject.__rxor__(self, other)\nobject.__ror__(self, other)\n\n These methods are called to implement the binary arithmetic\n operations (``+``, ``-``, ``*``, ``/``, ``%``, ``divmod()``,\n ``pow()``, ``**``, ``<<``, ``>>``, ``&``, ``^``, ``|``) with\n reflected (swapped) operands. These functions are only called if\n the left operand does not support the corresponding operation and\n the operands are of different types. [2] For instance, to evaluate\n the expression ``x - y``, where *y* is an instance of a class that\n has an ``__rsub__()`` method, ``y.__rsub__(x)`` is called if\n ``x.__sub__(y)`` returns *NotImplemented*.\n\n Note that ternary ``pow()`` will not try calling ``__rpow__()``\n (the coercion rules would become too complicated).\n\n Note: If the right operand\'s type is a subclass of the left operand\'s\n type and that subclass provides the reflected method for the\n operation, this method will be called before the left operand\'s\n non-reflected method. This behavior allows subclasses to\n override their ancestors\' operations.\n\nobject.__iadd__(self, other)\nobject.__isub__(self, other)\nobject.__imul__(self, other)\nobject.__idiv__(self, other)\nobject.__itruediv__(self, other)\nobject.__ifloordiv__(self, other)\nobject.__imod__(self, other)\nobject.__ipow__(self, other[, modulo])\nobject.__ilshift__(self, other)\nobject.__irshift__(self, other)\nobject.__iand__(self, other)\nobject.__ixor__(self, other)\nobject.__ior__(self, other)\n\n These methods are called to implement the augmented arithmetic\n assignments (``+=``, ``-=``, ``*=``, ``/=``, ``//=``, ``%=``,\n ``**=``, ``<<=``, ``>>=``, ``&=``, ``^=``, ``|=``). These methods\n should attempt to do the operation in-place (modifying *self*) and\n return the result (which could be, but does not have to be,\n *self*). If a specific method is not defined, the augmented\n assignment falls back to the normal methods. For instance, to\n execute the statement ``x += y``, where *x* is an instance of a\n class that has an ``__iadd__()`` method, ``x.__iadd__(y)`` is\n called. If *x* is an instance of a class that does not define a\n ``__iadd__()`` method, ``x.__add__(y)`` and ``y.__radd__(x)`` are\n considered, as with the evaluation of ``x + y``.\n\nobject.__neg__(self)\nobject.__pos__(self)\nobject.__abs__(self)\nobject.__invert__(self)\n\n Called to implement the unary arithmetic operations (``-``, ``+``,\n ``abs()`` and ``~``).\n\nobject.__complex__(self)\nobject.__int__(self)\nobject.__long__(self)\nobject.__float__(self)\n\n Called to implement the built-in functions ``complex()``,\n ``int()``, ``long()``, and ``float()``. Should return a value of\n the appropriate type.\n\nobject.__oct__(self)\nobject.__hex__(self)\n\n Called to implement the built-in functions ``oct()`` and ``hex()``.\n Should return a string value.\n\nobject.__index__(self)\n\n Called to implement ``operator.index()``. Also called whenever\n Python needs an integer object (such as in slicing). Must return\n an integer (int or long).\n\n New in version 2.5.\n\nobject.__coerce__(self, other)\n\n Called to implement "mixed-mode" numeric arithmetic. Should either\n return a 2-tuple containing *self* and *other* converted to a\n common numeric type, or ``None`` if conversion is impossible. When\n the common type would be the type of ``other``, it is sufficient to\n return ``None``, since the interpreter will also ask the other\n object to attempt a coercion (but sometimes, if the implementation\n of the other type cannot be changed, it is useful to do the\n conversion to the other type here). A return value of\n ``NotImplemented`` is equivalent to returning ``None``.\n\n\nCoercion rules\n==============\n\nThis section used to document the rules for coercion. As the language\nhas evolved, the coercion rules have become hard to document\nprecisely; documenting what one version of one particular\nimplementation does is undesirable. Instead, here are some informal\nguidelines regarding coercion. In Python 3.0, coercion will not be\nsupported.\n\n* If the left operand of a % operator is a string or Unicode object,\n no coercion takes place and the string formatting operation is\n invoked instead.\n\n* It is no longer recommended to define a coercion operation. Mixed-\n mode operations on types that don\'t define coercion pass the\n original arguments to the operation.\n\n* New-style classes (those derived from ``object``) never invoke the\n ``__coerce__()`` method in response to a binary operator; the only\n time ``__coerce__()`` is invoked is when the built-in function\n ``coerce()`` is called.\n\n* For most intents and purposes, an operator that returns\n ``NotImplemented`` is treated the same as one that is not\n implemented at all.\n\n* Below, ``__op__()`` and ``__rop__()`` are used to signify the\n generic method names corresponding to an operator; ``__iop__()`` is\n used for the corresponding in-place operator. For example, for the\n operator \'``+``\', ``__add__()`` and ``__radd__()`` are used for the\n left and right variant of the binary operator, and ``__iadd__()``\n for the in-place variant.\n\n* For objects *x* and *y*, first ``x.__op__(y)`` is tried. If this is\n not implemented or returns ``NotImplemented``, ``y.__rop__(x)`` is\n tried. If this is also not implemented or returns\n ``NotImplemented``, a ``TypeError`` exception is raised. But see\n the following exception:\n\n* Exception to the previous item: if the left operand is an instance\n of a built-in type or a new-style class, and the right operand is an\n instance of a proper subclass of that type or class and overrides\n the base\'s ``__rop__()`` method, the right operand\'s ``__rop__()``\n method is tried *before* the left operand\'s ``__op__()`` method.\n\n This is done so that a subclass can completely override binary\n operators. Otherwise, the left operand\'s ``__op__()`` method would\n always accept the right operand: when an instance of a given class\n is expected, an instance of a subclass of that class is always\n acceptable.\n\n* When either operand type defines a coercion, this coercion is called\n before that type\'s ``__op__()`` or ``__rop__()`` method is called,\n but no sooner. If the coercion returns an object of a different\n type for the operand whose coercion is invoked, part of the process\n is redone using the new object.\n\n* When an in-place operator (like \'``+=``\') is used, if the left\n operand implements ``__iop__()``, it is invoked without any\n coercion. When the operation falls back to ``__op__()`` and/or\n ``__rop__()``, the normal coercion rules apply.\n\n* In ``x + y``, if *x* is a sequence that implements sequence\n concatenation, sequence concatenation is invoked.\n\n* In ``x * y``, if one operator is a sequence that implements sequence\n repetition, and the other is an integer (``int`` or ``long``),\n sequence repetition is invoked.\n\n* Rich comparisons (implemented by methods ``__eq__()`` and so on)\n never use coercion. Three-way comparison (implemented by\n ``__cmp__()``) does use coercion under the same conditions as other\n binary operations use it.\n\n* In the current implementation, the built-in numeric types ``int``,\n ``long``, ``float``, and ``complex`` do not use coercion. All these\n types implement a ``__coerce__()`` method, for use by the built-in\n ``coerce()`` function.\n\n Changed in version 2.7.\n\n\nWith Statement Context Managers\n===============================\n\nNew in version 2.5.\n\nA *context manager* is an object that defines the runtime context to\nbe established when executing a ``with`` statement. The context\nmanager handles the entry into, and the exit from, the desired runtime\ncontext for the execution of the block of code. Context managers are\nnormally invoked using the ``with`` statement (described in section\n*The with statement*), but can also be used by directly invoking their\nmethods.\n\nTypical uses of context managers include saving and restoring various\nkinds of global state, locking and unlocking resources, closing opened\nfiles, etc.\n\nFor more information on context managers, see *Context Manager Types*.\n\nobject.__enter__(self)\n\n Enter the runtime context related to this object. The ``with``\n statement will bind this method\'s return value to the target(s)\n specified in the ``as`` clause of the statement, if any.\n\nobject.__exit__(self, exc_type, exc_value, traceback)\n\n Exit the runtime context related to this object. The parameters\n describe the exception that caused the context to be exited. If the\n context was exited without an exception, all three arguments will\n be ``None``.\n\n If an exception is supplied, and the method wishes to suppress the\n exception (i.e., prevent it from being propagated), it should\n return a true value. Otherwise, the exception will be processed\n normally upon exit from this method.\n\n Note that ``__exit__()`` methods should not reraise the passed-in\n exception; this is the caller\'s responsibility.\n\nSee also:\n\n **PEP 0343** - The "with" statement\n The specification, background, and examples for the Python\n ``with`` statement.\n\n\nSpecial method lookup for old-style classes\n===========================================\n\nFor old-style classes, special methods are always looked up in exactly\nthe same way as any other method or attribute. This is the case\nregardless of whether the method is being looked up explicitly as in\n``x.__getitem__(i)`` or implicitly as in ``x[i]``.\n\nThis behaviour means that special methods may exhibit different\nbehaviour for different instances of a single old-style class if the\nappropriate special attributes are set differently:\n\n >>> class C:\n ... pass\n ...\n >>> c1 = C()\n >>> c2 = C()\n >>> c1.__len__ = lambda: 5\n >>> c2.__len__ = lambda: 9\n >>> len(c1)\n 5\n >>> len(c2)\n 9\n\n\nSpecial method lookup for new-style classes\n===========================================\n\nFor new-style classes, implicit invocations of special methods are\nonly guaranteed to work correctly if defined on an object\'s type, not\nin the object\'s instance dictionary. That behaviour is the reason why\nthe following code raises an exception (unlike the equivalent example\nwith old-style classes):\n\n >>> class C(object):\n ... pass\n ...\n >>> c = C()\n >>> c.__len__ = lambda: 5\n >>> len(c)\n Traceback (most recent call last):\n File "", line 1, in \n TypeError: object of type \'C\' has no len()\n\nThe rationale behind this behaviour lies with a number of special\nmethods such as ``__hash__()`` and ``__repr__()`` that are implemented\nby all objects, including type objects. If the implicit lookup of\nthese methods used the conventional lookup process, they would fail\nwhen invoked on the type object itself:\n\n >>> 1 .__hash__() == hash(1)\n True\n >>> int.__hash__() == hash(int)\n Traceback (most recent call last):\n File "", line 1, in \n TypeError: descriptor \'__hash__\' of \'int\' object needs an argument\n\nIncorrectly attempting to invoke an unbound method of a class in this\nway is sometimes referred to as \'metaclass confusion\', and is avoided\nby bypassing the instance when looking up special methods:\n\n >>> type(1).__hash__(1) == hash(1)\n True\n >>> type(int).__hash__(int) == hash(int)\n True\n\nIn addition to bypassing any instance attributes in the interest of\ncorrectness, implicit special method lookup generally also bypasses\nthe ``__getattribute__()`` method even of the object\'s metaclass:\n\n >>> class Meta(type):\n ... def __getattribute__(*args):\n ... print "Metaclass getattribute invoked"\n ... return type.__getattribute__(*args)\n ...\n >>> class C(object):\n ... __metaclass__ = Meta\n ... def __len__(self):\n ... return 10\n ... def __getattribute__(*args):\n ... print "Class getattribute invoked"\n ... return object.__getattribute__(*args)\n ...\n >>> c = C()\n >>> c.__len__() # Explicit lookup via instance\n Class getattribute invoked\n 10\n >>> type(c).__len__(c) # Explicit lookup via type\n Metaclass getattribute invoked\n 10\n >>> len(c) # Implicit lookup\n 10\n\nBypassing the ``__getattribute__()`` machinery in this fashion\nprovides significant scope for speed optimisations within the\ninterpreter, at the cost of some flexibility in the handling of\nspecial methods (the special method *must* be set on the class object\nitself in order to be consistently invoked by the interpreter).\n\n-[ Footnotes ]-\n\n[1] It *is* possible in some cases to change an object\'s type, under\n certain controlled conditions. It generally isn\'t a good idea\n though, since it can lead to some very strange behaviour if it is\n handled incorrectly.\n\n[2] For operands of the same type, it is assumed that if the non-\n reflected method (such as ``__add__()``) fails the operation is\n not supported, which is why the reflected method is not called.\n', 'string-conversions': u'\nString conversions\n******************\n\nA string conversion is an expression list enclosed in reverse (a.k.a.\nbackward) quotes:\n\n string_conversion ::= "\'" expression_list "\'"\n\nA string conversion evaluates the contained expression list and\nconverts the resulting object into a string according to rules\nspecific to its type.\n\nIf the object is a string, a number, ``None``, or a tuple, list or\ndictionary containing only objects whose type is one of these, the\nresulting string is a valid Python expression which can be passed to\nthe built-in function ``eval()`` to yield an expression with the same\nvalue (or an approximation, if floating point numbers are involved).\n\n(In particular, converting a string adds quotes around it and converts\n"funny" characters to escape sequences that are safe to print.)\n\nRecursive objects (for example, lists or dictionaries that contain a\nreference to themselves, directly or indirectly) use ``...`` to\nindicate a recursive reference, and the result cannot be passed to\n``eval()`` to get an equal value (``SyntaxError`` will be raised\ninstead).\n\nThe built-in function ``repr()`` performs exactly the same conversion\nin its argument as enclosing it in parentheses and reverse quotes\ndoes. The built-in function ``str()`` performs a similar but more\nuser-friendly conversion.\n', - 'string-methods': u'\nString Methods\n**************\n\nBelow are listed the string methods which both 8-bit strings and\nUnicode objects support.\n\nIn addition, Python\'s strings support the sequence type methods\ndescribed in the *Sequence Types --- str, unicode, list, tuple,\nbuffer, xrange* section. To output formatted strings use template\nstrings or the ``%`` operator described in the *String Formatting\nOperations* section. Also, see the ``re`` module for string functions\nbased on regular expressions.\n\nstr.capitalize()\n\n Return a copy of the string with only its first character\n capitalized.\n\n For 8-bit strings, this method is locale-dependent.\n\nstr.center(width[, fillchar])\n\n Return centered in a string of length *width*. Padding is done\n using the specified *fillchar* (default is a space).\n\n Changed in version 2.4: Support for the *fillchar* argument.\n\nstr.count(sub[, start[, end]])\n\n Return the number of non-overlapping occurrences of substring *sub*\n in the range [*start*, *end*]. Optional arguments *start* and\n *end* are interpreted as in slice notation.\n\nstr.decode([encoding[, errors]])\n\n Decodes the string using the codec registered for *encoding*.\n *encoding* defaults to the default string encoding. *errors* may\n be given to set a different error handling scheme. The default is\n ``\'strict\'``, meaning that encoding errors raise ``UnicodeError``.\n Other possible values are ``\'ignore\'``, ``\'replace\'`` and any other\n name registered via ``codecs.register_error()``, see section *Codec\n Base Classes*.\n\n New in version 2.2.\n\n Changed in version 2.3: Support for other error handling schemes\n added.\n\n Changed in version 2.7: Support for keyword arguments added.\n\nstr.encode([encoding[, errors]])\n\n Return an encoded version of the string. Default encoding is the\n current default string encoding. *errors* may be given to set a\n different error handling scheme. The default for *errors* is\n ``\'strict\'``, meaning that encoding errors raise a\n ``UnicodeError``. Other possible values are ``\'ignore\'``,\n ``\'replace\'``, ``\'xmlcharrefreplace\'``, ``\'backslashreplace\'`` and\n any other name registered via ``codecs.register_error()``, see\n section *Codec Base Classes*. For a list of possible encodings, see\n section *Standard Encodings*.\n\n New in version 2.0.\n\n Changed in version 2.3: Support for ``\'xmlcharrefreplace\'`` and\n ``\'backslashreplace\'`` and other error handling schemes added.\n\n Changed in version 2.7: Support for keyword arguments added.\n\nstr.endswith(suffix[, start[, end]])\n\n Return ``True`` if the string ends with the specified *suffix*,\n otherwise return ``False``. *suffix* can also be a tuple of\n suffixes to look for. With optional *start*, test beginning at\n that position. With optional *end*, stop comparing at that\n position.\n\n Changed in version 2.5: Accept tuples as *suffix*.\n\nstr.expandtabs([tabsize])\n\n Return a copy of the string where all tab characters are replaced\n by one or more spaces, depending on the current column and the\n given tab size. The column number is reset to zero after each\n newline occurring in the string. If *tabsize* is not given, a tab\n size of ``8`` characters is assumed. This doesn\'t understand other\n non-printing characters or escape sequences.\n\nstr.find(sub[, start[, end]])\n\n Return the lowest index in the string where substring *sub* is\n found, such that *sub* is contained in the range [*start*, *end*].\n Optional arguments *start* and *end* are interpreted as in slice\n notation. Return ``-1`` if *sub* is not found.\n\nstr.format(*args, **kwargs)\n\n Perform a string formatting operation. The string on which this\n method is called can contain literal text or replacement fields\n delimited by braces ``{}``. Each replacement field contains either\n the numeric index of a positional argument, or the name of a\n keyword argument. Returns a copy of the string where each\n replacement field is replaced with the string value of the\n corresponding argument.\n\n >>> "The sum of 1 + 2 is {0}".format(1+2)\n \'The sum of 1 + 2 is 3\'\n\n See *Format String Syntax* for a description of the various\n formatting options that can be specified in format strings.\n\n This method of string formatting is the new standard in Python 3.0,\n and should be preferred to the ``%`` formatting described in\n *String Formatting Operations* in new code.\n\n New in version 2.6.\n\nstr.index(sub[, start[, end]])\n\n Like ``find()``, but raise ``ValueError`` when the substring is not\n found.\n\nstr.isalnum()\n\n Return true if all characters in the string are alphanumeric and\n there is at least one character, false otherwise.\n\n For 8-bit strings, this method is locale-dependent.\n\nstr.isalpha()\n\n Return true if all characters in the string are alphabetic and\n there is at least one character, false otherwise.\n\n For 8-bit strings, this method is locale-dependent.\n\nstr.isdigit()\n\n Return true if all characters in the string are digits and there is\n at least one character, false otherwise.\n\n For 8-bit strings, this method is locale-dependent.\n\nstr.islower()\n\n Return true if all cased characters in the string are lowercase and\n there is at least one cased character, false otherwise.\n\n For 8-bit strings, this method is locale-dependent.\n\nstr.isspace()\n\n Return true if there are only whitespace characters in the string\n and there is at least one character, false otherwise.\n\n For 8-bit strings, this method is locale-dependent.\n\nstr.istitle()\n\n Return true if the string is a titlecased string and there is at\n least one character, for example uppercase characters may only\n follow uncased characters and lowercase characters only cased ones.\n Return false otherwise.\n\n For 8-bit strings, this method is locale-dependent.\n\nstr.isupper()\n\n Return true if all cased characters in the string are uppercase and\n there is at least one cased character, false otherwise.\n\n For 8-bit strings, this method is locale-dependent.\n\nstr.join(iterable)\n\n Return a string which is the concatenation of the strings in the\n *iterable* *iterable*. The separator between elements is the\n string providing this method.\n\nstr.ljust(width[, fillchar])\n\n Return the string left justified in a string of length *width*.\n Padding is done using the specified *fillchar* (default is a\n space). The original string is returned if *width* is less than\n ``len(s)``.\n\n Changed in version 2.4: Support for the *fillchar* argument.\n\nstr.lower()\n\n Return a copy of the string converted to lowercase.\n\n For 8-bit strings, this method is locale-dependent.\n\nstr.lstrip([chars])\n\n Return a copy of the string with leading characters removed. The\n *chars* argument is a string specifying the set of characters to be\n removed. If omitted or ``None``, the *chars* argument defaults to\n removing whitespace. The *chars* argument is not a prefix; rather,\n all combinations of its values are stripped:\n\n >>> \' spacious \'.lstrip()\n \'spacious \'\n >>> \'www.example.com\'.lstrip(\'cmowz.\')\n \'example.com\'\n\n Changed in version 2.2.2: Support for the *chars* argument.\n\nstr.partition(sep)\n\n Split the string at the first occurrence of *sep*, and return a\n 3-tuple containing the part before the separator, the separator\n itself, and the part after the separator. If the separator is not\n found, return a 3-tuple containing the string itself, followed by\n two empty strings.\n\n New in version 2.5.\n\nstr.replace(old, new[, count])\n\n Return a copy of the string with all occurrences of substring *old*\n replaced by *new*. If the optional argument *count* is given, only\n the first *count* occurrences are replaced.\n\nstr.rfind(sub[, start[, end]])\n\n Return the highest index in the string where substring *sub* is\n found, such that *sub* is contained within s[start,end]. Optional\n arguments *start* and *end* are interpreted as in slice notation.\n Return ``-1`` on failure.\n\nstr.rindex(sub[, start[, end]])\n\n Like ``rfind()`` but raises ``ValueError`` when the substring *sub*\n is not found.\n\nstr.rjust(width[, fillchar])\n\n Return the string right justified in a string of length *width*.\n Padding is done using the specified *fillchar* (default is a\n space). The original string is returned if *width* is less than\n ``len(s)``.\n\n Changed in version 2.4: Support for the *fillchar* argument.\n\nstr.rpartition(sep)\n\n Split the string at the last occurrence of *sep*, and return a\n 3-tuple containing the part before the separator, the separator\n itself, and the part after the separator. If the separator is not\n found, return a 3-tuple containing two empty strings, followed by\n the string itself.\n\n New in version 2.5.\n\nstr.rsplit([sep[, maxsplit]])\n\n Return a list of the words in the string, using *sep* as the\n delimiter string. If *maxsplit* is given, at most *maxsplit* splits\n are done, the *rightmost* ones. If *sep* is not specified or\n ``None``, any whitespace string is a separator. Except for\n splitting from the right, ``rsplit()`` behaves like ``split()``\n which is described in detail below.\n\n New in version 2.4.\n\nstr.rstrip([chars])\n\n Return a copy of the string with trailing characters removed. The\n *chars* argument is a string specifying the set of characters to be\n removed. If omitted or ``None``, the *chars* argument defaults to\n removing whitespace. The *chars* argument is not a suffix; rather,\n all combinations of its values are stripped:\n\n >>> \' spacious \'.rstrip()\n \' spacious\'\n >>> \'mississippi\'.rstrip(\'ipz\')\n \'mississ\'\n\n Changed in version 2.2.2: Support for the *chars* argument.\n\nstr.split([sep[, maxsplit]])\n\n Return a list of the words in the string, using *sep* as the\n delimiter string. If *maxsplit* is given, at most *maxsplit*\n splits are done (thus, the list will have at most ``maxsplit+1``\n elements). If *maxsplit* is not specified, then there is no limit\n on the number of splits (all possible splits are made).\n\n If *sep* is given, consecutive delimiters are not grouped together\n and are deemed to delimit empty strings (for example,\n ``\'1,,2\'.split(\',\')`` returns ``[\'1\', \'\', \'2\']``). The *sep*\n argument may consist of multiple characters (for example,\n ``\'1<>2<>3\'.split(\'<>\')`` returns ``[\'1\', \'2\', \'3\']``). Splitting\n an empty string with a specified separator returns ``[\'\']``.\n\n If *sep* is not specified or is ``None``, a different splitting\n algorithm is applied: runs of consecutive whitespace are regarded\n as a single separator, and the result will contain no empty strings\n at the start or end if the string has leading or trailing\n whitespace. Consequently, splitting an empty string or a string\n consisting of just whitespace with a ``None`` separator returns\n ``[]``.\n\n For example, ``\' 1 2 3 \'.split()`` returns ``[\'1\', \'2\', \'3\']``,\n and ``\' 1 2 3 \'.split(None, 1)`` returns ``[\'1\', \'2 3 \']``.\n\nstr.splitlines([keepends])\n\n Return a list of the lines in the string, breaking at line\n boundaries. Line breaks are not included in the resulting list\n unless *keepends* is given and true.\n\nstr.startswith(prefix[, start[, end]])\n\n Return ``True`` if string starts with the *prefix*, otherwise\n return ``False``. *prefix* can also be a tuple of prefixes to look\n for. With optional *start*, test string beginning at that\n position. With optional *end*, stop comparing string at that\n position.\n\n Changed in version 2.5: Accept tuples as *prefix*.\n\nstr.strip([chars])\n\n Return a copy of the string with the leading and trailing\n characters removed. The *chars* argument is a string specifying the\n set of characters to be removed. If omitted or ``None``, the\n *chars* argument defaults to removing whitespace. The *chars*\n argument is not a prefix or suffix; rather, all combinations of its\n values are stripped:\n\n >>> \' spacious \'.strip()\n \'spacious\'\n >>> \'www.example.com\'.strip(\'cmowz.\')\n \'example\'\n\n Changed in version 2.2.2: Support for the *chars* argument.\n\nstr.swapcase()\n\n Return a copy of the string with uppercase characters converted to\n lowercase and vice versa.\n\n For 8-bit strings, this method is locale-dependent.\n\nstr.title()\n\n Return a titlecased version of the string where words start with an\n uppercase character and the remaining characters are lowercase.\n\n The algorithm uses a simple language-independent definition of a\n word as groups of consecutive letters. The definition works in\n many contexts but it means that apostrophes in contractions and\n possessives form word boundaries, which may not be the desired\n result:\n\n >>> "they\'re bill\'s friends from the UK".title()\n "They\'Re Bill\'S Friends From The Uk"\n\n A workaround for apostrophes can be constructed using regular\n expressions:\n\n >>> import re\n >>> def titlecase(s):\n return re.sub(r"[A-Za-z]+(\'[A-Za-z]+)?",\n lambda mo: mo.group(0)[0].upper() +\n mo.group(0)[1:].lower(),\n s)\n\n >>> titlecase("they\'re bill\'s friends.")\n "They\'re Bill\'s Friends."\n\n For 8-bit strings, this method is locale-dependent.\n\nstr.translate(table[, deletechars])\n\n Return a copy of the string where all characters occurring in the\n optional argument *deletechars* are removed, and the remaining\n characters have been mapped through the given translation table,\n which must be a string of length 256.\n\n You can use the ``maketrans()`` helper function in the ``string``\n module to create a translation table. For string objects, set the\n *table* argument to ``None`` for translations that only delete\n characters:\n\n >>> \'read this short text\'.translate(None, \'aeiou\')\n \'rd ths shrt txt\'\n\n New in version 2.6: Support for a ``None`` *table* argument.\n\n For Unicode objects, the ``translate()`` method does not accept the\n optional *deletechars* argument. Instead, it returns a copy of the\n *s* where all characters have been mapped through the given\n translation table which must be a mapping of Unicode ordinals to\n Unicode ordinals, Unicode strings or ``None``. Unmapped characters\n are left untouched. Characters mapped to ``None`` are deleted.\n Note, a more flexible approach is to create a custom character\n mapping codec using the ``codecs`` module (see ``encodings.cp1251``\n for an example).\n\nstr.upper()\n\n Return a copy of the string converted to uppercase.\n\n For 8-bit strings, this method is locale-dependent.\n\nstr.zfill(width)\n\n Return the numeric string left filled with zeros in a string of\n length *width*. A sign prefix is handled correctly. The original\n string is returned if *width* is less than ``len(s)``.\n\n New in version 2.2.2.\n\nThe following methods are present only on unicode objects:\n\nunicode.isnumeric()\n\n Return ``True`` if there are only numeric characters in S,\n ``False`` otherwise. Numeric characters include digit characters,\n and all characters that have the Unicode numeric value property,\n e.g. U+2155, VULGAR FRACTION ONE FIFTH.\n\nunicode.isdecimal()\n\n Return ``True`` if there are only decimal characters in S,\n ``False`` otherwise. Decimal characters include digit characters,\n and all characters that that can be used to form decimal-radix\n numbers, e.g. U+0660, ARABIC-INDIC DIGIT ZERO.\n', + 'string-methods': u'\nString Methods\n**************\n\nBelow are listed the string methods which both 8-bit strings and\nUnicode objects support.\n\nIn addition, Python\'s strings support the sequence type methods\ndescribed in the *Sequence Types --- str, unicode, list, tuple,\nbuffer, xrange* section. To output formatted strings use template\nstrings or the ``%`` operator described in the *String Formatting\nOperations* section. Also, see the ``re`` module for string functions\nbased on regular expressions.\n\nstr.capitalize()\n\n Return a copy of the string with only its first character\n capitalized.\n\n For 8-bit strings, this method is locale-dependent.\n\nstr.center(width[, fillchar])\n\n Return centered in a string of length *width*. Padding is done\n using the specified *fillchar* (default is a space).\n\n Changed in version 2.4: Support for the *fillchar* argument.\n\nstr.count(sub[, start[, end]])\n\n Return the number of non-overlapping occurrences of substring *sub*\n in the range [*start*, *end*]. Optional arguments *start* and\n *end* are interpreted as in slice notation.\n\nstr.decode([encoding[, errors]])\n\n Decodes the string using the codec registered for *encoding*.\n *encoding* defaults to the default string encoding. *errors* may\n be given to set a different error handling scheme. The default is\n ``\'strict\'``, meaning that encoding errors raise ``UnicodeError``.\n Other possible values are ``\'ignore\'``, ``\'replace\'`` and any other\n name registered via ``codecs.register_error()``, see section *Codec\n Base Classes*.\n\n New in version 2.2.\n\n Changed in version 2.3: Support for other error handling schemes\n added.\n\n Changed in version 2.7: Support for keyword arguments added.\n\nstr.encode([encoding[, errors]])\n\n Return an encoded version of the string. Default encoding is the\n current default string encoding. *errors* may be given to set a\n different error handling scheme. The default for *errors* is\n ``\'strict\'``, meaning that encoding errors raise a\n ``UnicodeError``. Other possible values are ``\'ignore\'``,\n ``\'replace\'``, ``\'xmlcharrefreplace\'``, ``\'backslashreplace\'`` and\n any other name registered via ``codecs.register_error()``, see\n section *Codec Base Classes*. For a list of possible encodings, see\n section *Standard Encodings*.\n\n New in version 2.0.\n\n Changed in version 2.3: Support for ``\'xmlcharrefreplace\'`` and\n ``\'backslashreplace\'`` and other error handling schemes added.\n\n Changed in version 2.7: Support for keyword arguments added.\n\nstr.endswith(suffix[, start[, end]])\n\n Return ``True`` if the string ends with the specified *suffix*,\n otherwise return ``False``. *suffix* can also be a tuple of\n suffixes to look for. With optional *start*, test beginning at\n that position. With optional *end*, stop comparing at that\n position.\n\n Changed in version 2.5: Accept tuples as *suffix*.\n\nstr.expandtabs([tabsize])\n\n Return a copy of the string where all tab characters are replaced\n by one or more spaces, depending on the current column and the\n given tab size. The column number is reset to zero after each\n newline occurring in the string. If *tabsize* is not given, a tab\n size of ``8`` characters is assumed. This doesn\'t understand other\n non-printing characters or escape sequences.\n\nstr.find(sub[, start[, end]])\n\n Return the lowest index in the string where substring *sub* is\n found, such that *sub* is contained in the slice ``s[start:end]``.\n Optional arguments *start* and *end* are interpreted as in slice\n notation. Return ``-1`` if *sub* is not found.\n\nstr.format(*args, **kwargs)\n\n Perform a string formatting operation. The string on which this\n method is called can contain literal text or replacement fields\n delimited by braces ``{}``. Each replacement field contains either\n the numeric index of a positional argument, or the name of a\n keyword argument. Returns a copy of the string where each\n replacement field is replaced with the string value of the\n corresponding argument.\n\n >>> "The sum of 1 + 2 is {0}".format(1+2)\n \'The sum of 1 + 2 is 3\'\n\n See *Format String Syntax* for a description of the various\n formatting options that can be specified in format strings.\n\n This method of string formatting is the new standard in Python 3.0,\n and should be preferred to the ``%`` formatting described in\n *String Formatting Operations* in new code.\n\n New in version 2.6.\n\nstr.index(sub[, start[, end]])\n\n Like ``find()``, but raise ``ValueError`` when the substring is not\n found.\n\nstr.isalnum()\n\n Return true if all characters in the string are alphanumeric and\n there is at least one character, false otherwise.\n\n For 8-bit strings, this method is locale-dependent.\n\nstr.isalpha()\n\n Return true if all characters in the string are alphabetic and\n there is at least one character, false otherwise.\n\n For 8-bit strings, this method is locale-dependent.\n\nstr.isdigit()\n\n Return true if all characters in the string are digits and there is\n at least one character, false otherwise.\n\n For 8-bit strings, this method is locale-dependent.\n\nstr.islower()\n\n Return true if all cased characters in the string are lowercase and\n there is at least one cased character, false otherwise.\n\n For 8-bit strings, this method is locale-dependent.\n\nstr.isspace()\n\n Return true if there are only whitespace characters in the string\n and there is at least one character, false otherwise.\n\n For 8-bit strings, this method is locale-dependent.\n\nstr.istitle()\n\n Return true if the string is a titlecased string and there is at\n least one character, for example uppercase characters may only\n follow uncased characters and lowercase characters only cased ones.\n Return false otherwise.\n\n For 8-bit strings, this method is locale-dependent.\n\nstr.isupper()\n\n Return true if all cased characters in the string are uppercase and\n there is at least one cased character, false otherwise.\n\n For 8-bit strings, this method is locale-dependent.\n\nstr.join(iterable)\n\n Return a string which is the concatenation of the strings in the\n *iterable* *iterable*. The separator between elements is the\n string providing this method.\n\nstr.ljust(width[, fillchar])\n\n Return the string left justified in a string of length *width*.\n Padding is done using the specified *fillchar* (default is a\n space). The original string is returned if *width* is less than\n ``len(s)``.\n\n Changed in version 2.4: Support for the *fillchar* argument.\n\nstr.lower()\n\n Return a copy of the string converted to lowercase.\n\n For 8-bit strings, this method is locale-dependent.\n\nstr.lstrip([chars])\n\n Return a copy of the string with leading characters removed. The\n *chars* argument is a string specifying the set of characters to be\n removed. If omitted or ``None``, the *chars* argument defaults to\n removing whitespace. The *chars* argument is not a prefix; rather,\n all combinations of its values are stripped:\n\n >>> \' spacious \'.lstrip()\n \'spacious \'\n >>> \'www.example.com\'.lstrip(\'cmowz.\')\n \'example.com\'\n\n Changed in version 2.2.2: Support for the *chars* argument.\n\nstr.partition(sep)\n\n Split the string at the first occurrence of *sep*, and return a\n 3-tuple containing the part before the separator, the separator\n itself, and the part after the separator. If the separator is not\n found, return a 3-tuple containing the string itself, followed by\n two empty strings.\n\n New in version 2.5.\n\nstr.replace(old, new[, count])\n\n Return a copy of the string with all occurrences of substring *old*\n replaced by *new*. If the optional argument *count* is given, only\n the first *count* occurrences are replaced.\n\nstr.rfind(sub[, start[, end]])\n\n Return the highest index in the string where substring *sub* is\n found, such that *sub* is contained within ``s[start:end]``.\n Optional arguments *start* and *end* are interpreted as in slice\n notation. Return ``-1`` on failure.\n\nstr.rindex(sub[, start[, end]])\n\n Like ``rfind()`` but raises ``ValueError`` when the substring *sub*\n is not found.\n\nstr.rjust(width[, fillchar])\n\n Return the string right justified in a string of length *width*.\n Padding is done using the specified *fillchar* (default is a\n space). The original string is returned if *width* is less than\n ``len(s)``.\n\n Changed in version 2.4: Support for the *fillchar* argument.\n\nstr.rpartition(sep)\n\n Split the string at the last occurrence of *sep*, and return a\n 3-tuple containing the part before the separator, the separator\n itself, and the part after the separator. If the separator is not\n found, return a 3-tuple containing two empty strings, followed by\n the string itself.\n\n New in version 2.5.\n\nstr.rsplit([sep[, maxsplit]])\n\n Return a list of the words in the string, using *sep* as the\n delimiter string. If *maxsplit* is given, at most *maxsplit* splits\n are done, the *rightmost* ones. If *sep* is not specified or\n ``None``, any whitespace string is a separator. Except for\n splitting from the right, ``rsplit()`` behaves like ``split()``\n which is described in detail below.\n\n New in version 2.4.\n\nstr.rstrip([chars])\n\n Return a copy of the string with trailing characters removed. The\n *chars* argument is a string specifying the set of characters to be\n removed. If omitted or ``None``, the *chars* argument defaults to\n removing whitespace. The *chars* argument is not a suffix; rather,\n all combinations of its values are stripped:\n\n >>> \' spacious \'.rstrip()\n \' spacious\'\n >>> \'mississippi\'.rstrip(\'ipz\')\n \'mississ\'\n\n Changed in version 2.2.2: Support for the *chars* argument.\n\nstr.split([sep[, maxsplit]])\n\n Return a list of the words in the string, using *sep* as the\n delimiter string. If *maxsplit* is given, at most *maxsplit*\n splits are done (thus, the list will have at most ``maxsplit+1``\n elements). If *maxsplit* is not specified, then there is no limit\n on the number of splits (all possible splits are made).\n\n If *sep* is given, consecutive delimiters are not grouped together\n and are deemed to delimit empty strings (for example,\n ``\'1,,2\'.split(\',\')`` returns ``[\'1\', \'\', \'2\']``). The *sep*\n argument may consist of multiple characters (for example,\n ``\'1<>2<>3\'.split(\'<>\')`` returns ``[\'1\', \'2\', \'3\']``). Splitting\n an empty string with a specified separator returns ``[\'\']``.\n\n If *sep* is not specified or is ``None``, a different splitting\n algorithm is applied: runs of consecutive whitespace are regarded\n as a single separator, and the result will contain no empty strings\n at the start or end if the string has leading or trailing\n whitespace. Consequently, splitting an empty string or a string\n consisting of just whitespace with a ``None`` separator returns\n ``[]``.\n\n For example, ``\' 1 2 3 \'.split()`` returns ``[\'1\', \'2\', \'3\']``,\n and ``\' 1 2 3 \'.split(None, 1)`` returns ``[\'1\', \'2 3 \']``.\n\nstr.splitlines([keepends])\n\n Return a list of the lines in the string, breaking at line\n boundaries. Line breaks are not included in the resulting list\n unless *keepends* is given and true.\n\nstr.startswith(prefix[, start[, end]])\n\n Return ``True`` if string starts with the *prefix*, otherwise\n return ``False``. *prefix* can also be a tuple of prefixes to look\n for. With optional *start*, test string beginning at that\n position. With optional *end*, stop comparing string at that\n position.\n\n Changed in version 2.5: Accept tuples as *prefix*.\n\nstr.strip([chars])\n\n Return a copy of the string with the leading and trailing\n characters removed. The *chars* argument is a string specifying the\n set of characters to be removed. If omitted or ``None``, the\n *chars* argument defaults to removing whitespace. The *chars*\n argument is not a prefix or suffix; rather, all combinations of its\n values are stripped:\n\n >>> \' spacious \'.strip()\n \'spacious\'\n >>> \'www.example.com\'.strip(\'cmowz.\')\n \'example\'\n\n Changed in version 2.2.2: Support for the *chars* argument.\n\nstr.swapcase()\n\n Return a copy of the string with uppercase characters converted to\n lowercase and vice versa.\n\n For 8-bit strings, this method is locale-dependent.\n\nstr.title()\n\n Return a titlecased version of the string where words start with an\n uppercase character and the remaining characters are lowercase.\n\n The algorithm uses a simple language-independent definition of a\n word as groups of consecutive letters. The definition works in\n many contexts but it means that apostrophes in contractions and\n possessives form word boundaries, which may not be the desired\n result:\n\n >>> "they\'re bill\'s friends from the UK".title()\n "They\'Re Bill\'S Friends From The Uk"\n\n A workaround for apostrophes can be constructed using regular\n expressions:\n\n >>> import re\n >>> def titlecase(s):\n return re.sub(r"[A-Za-z]+(\'[A-Za-z]+)?",\n lambda mo: mo.group(0)[0].upper() +\n mo.group(0)[1:].lower(),\n s)\n\n >>> titlecase("they\'re bill\'s friends.")\n "They\'re Bill\'s Friends."\n\n For 8-bit strings, this method is locale-dependent.\n\nstr.translate(table[, deletechars])\n\n Return a copy of the string where all characters occurring in the\n optional argument *deletechars* are removed, and the remaining\n characters have been mapped through the given translation table,\n which must be a string of length 256.\n\n You can use the ``maketrans()`` helper function in the ``string``\n module to create a translation table. For string objects, set the\n *table* argument to ``None`` for translations that only delete\n characters:\n\n >>> \'read this short text\'.translate(None, \'aeiou\')\n \'rd ths shrt txt\'\n\n New in version 2.6: Support for a ``None`` *table* argument.\n\n For Unicode objects, the ``translate()`` method does not accept the\n optional *deletechars* argument. Instead, it returns a copy of the\n *s* where all characters have been mapped through the given\n translation table which must be a mapping of Unicode ordinals to\n Unicode ordinals, Unicode strings or ``None``. Unmapped characters\n are left untouched. Characters mapped to ``None`` are deleted.\n Note, a more flexible approach is to create a custom character\n mapping codec using the ``codecs`` module (see ``encodings.cp1251``\n for an example).\n\nstr.upper()\n\n Return a copy of the string converted to uppercase.\n\n For 8-bit strings, this method is locale-dependent.\n\nstr.zfill(width)\n\n Return the numeric string left filled with zeros in a string of\n length *width*. A sign prefix is handled correctly. The original\n string is returned if *width* is less than ``len(s)``.\n\n New in version 2.2.2.\n\nThe following methods are present only on unicode objects:\n\nunicode.isnumeric()\n\n Return ``True`` if there are only numeric characters in S,\n ``False`` otherwise. Numeric characters include digit characters,\n and all characters that have the Unicode numeric value property,\n e.g. U+2155, VULGAR FRACTION ONE FIFTH.\n\nunicode.isdecimal()\n\n Return ``True`` if there are only decimal characters in S,\n ``False`` otherwise. Decimal characters include digit characters,\n and all characters that that can be used to form decimal-radix\n numbers, e.g. U+0660, ARABIC-INDIC DIGIT ZERO.\n', 'strings': u'\nString literals\n***************\n\nString literals are described by the following lexical definitions:\n\n stringliteral ::= [stringprefix](shortstring | longstring)\n stringprefix ::= "r" | "u" | "ur" | "R" | "U" | "UR" | "Ur" | "uR"\n shortstring ::= "\'" shortstringitem* "\'" | \'"\' shortstringitem* \'"\'\n longstring ::= "\'\'\'" longstringitem* "\'\'\'"\n | \'"""\' longstringitem* \'"""\'\n shortstringitem ::= shortstringchar | escapeseq\n longstringitem ::= longstringchar | escapeseq\n shortstringchar ::= \n longstringchar ::= \n escapeseq ::= "\\" \n\nOne syntactic restriction not indicated by these productions is that\nwhitespace is not allowed between the **stringprefix** and the rest of\nthe string literal. The source character set is defined by the\nencoding declaration; it is ASCII if no encoding declaration is given\nin the source file; see section *Encoding declarations*.\n\nIn plain English: String literals can be enclosed in matching single\nquotes (``\'``) or double quotes (``"``). They can also be enclosed in\nmatching groups of three single or double quotes (these are generally\nreferred to as *triple-quoted strings*). The backslash (``\\``)\ncharacter is used to escape characters that otherwise have a special\nmeaning, such as newline, backslash itself, or the quote character.\nString literals may optionally be prefixed with a letter ``\'r\'`` or\n``\'R\'``; such strings are called *raw strings* and use different rules\nfor interpreting backslash escape sequences. A prefix of ``\'u\'`` or\n``\'U\'`` makes the string a Unicode string. Unicode strings use the\nUnicode character set as defined by the Unicode Consortium and ISO\n10646. Some additional escape sequences, described below, are\navailable in Unicode strings. The two prefix characters may be\ncombined; in this case, ``\'u\'`` must appear before ``\'r\'``.\n\nIn triple-quoted strings, unescaped newlines and quotes are allowed\n(and are retained), except that three unescaped quotes in a row\nterminate the string. (A "quote" is the character used to open the\nstring, i.e. either ``\'`` or ``"``.)\n\nUnless an ``\'r\'`` or ``\'R\'`` prefix is present, escape sequences in\nstrings are interpreted according to rules similar to those used by\nStandard C. The recognized escape sequences are:\n\n+-------------------+-----------------------------------+---------+\n| Escape Sequence | Meaning | Notes |\n+===================+===================================+=========+\n| ``\\newline`` | Ignored | |\n+-------------------+-----------------------------------+---------+\n| ``\\\\`` | Backslash (``\\``) | |\n+-------------------+-----------------------------------+---------+\n| ``\\\'`` | Single quote (``\'``) | |\n+-------------------+-----------------------------------+---------+\n| ``\\"`` | Double quote (``"``) | |\n+-------------------+-----------------------------------+---------+\n| ``\\a`` | ASCII Bell (BEL) | |\n+-------------------+-----------------------------------+---------+\n| ``\\b`` | ASCII Backspace (BS) | |\n+-------------------+-----------------------------------+---------+\n| ``\\f`` | ASCII Formfeed (FF) | |\n+-------------------+-----------------------------------+---------+\n| ``\\n`` | ASCII Linefeed (LF) | |\n+-------------------+-----------------------------------+---------+\n| ``\\N{name}`` | Character named *name* in the | |\n| | Unicode database (Unicode only) | |\n+-------------------+-----------------------------------+---------+\n| ``\\r`` | ASCII Carriage Return (CR) | |\n+-------------------+-----------------------------------+---------+\n| ``\\t`` | ASCII Horizontal Tab (TAB) | |\n+-------------------+-----------------------------------+---------+\n| ``\\uxxxx`` | Character with 16-bit hex value | (1) |\n| | *xxxx* (Unicode only) | |\n+-------------------+-----------------------------------+---------+\n| ``\\Uxxxxxxxx`` | Character with 32-bit hex value | (2) |\n| | *xxxxxxxx* (Unicode only) | |\n+-------------------+-----------------------------------+---------+\n| ``\\v`` | ASCII Vertical Tab (VT) | |\n+-------------------+-----------------------------------+---------+\n| ``\\ooo`` | Character with octal value *ooo* | (3,5) |\n+-------------------+-----------------------------------+---------+\n| ``\\xhh`` | Character with hex value *hh* | (4,5) |\n+-------------------+-----------------------------------+---------+\n\nNotes:\n\n1. Individual code units which form parts of a surrogate pair can be\n encoded using this escape sequence.\n\n2. Any Unicode character can be encoded this way, but characters\n outside the Basic Multilingual Plane (BMP) will be encoded using a\n surrogate pair if Python is compiled to use 16-bit code units (the\n default). Individual code units which form parts of a surrogate\n pair can be encoded using this escape sequence.\n\n3. As in Standard C, up to three octal digits are accepted.\n\n4. Unlike in Standard C, exactly two hex digits are required.\n\n5. In a string literal, hexadecimal and octal escapes denote the byte\n with the given value; it is not necessary that the byte encodes a\n character in the source character set. In a Unicode literal, these\n escapes denote a Unicode character with the given value.\n\nUnlike Standard C, all unrecognized escape sequences are left in the\nstring unchanged, i.e., *the backslash is left in the string*. (This\nbehavior is useful when debugging: if an escape sequence is mistyped,\nthe resulting output is more easily recognized as broken.) It is also\nimportant to note that the escape sequences marked as "(Unicode only)"\nin the table above fall into the category of unrecognized escapes for\nnon-Unicode string literals.\n\nWhen an ``\'r\'`` or ``\'R\'`` prefix is present, a character following a\nbackslash is included in the string without change, and *all\nbackslashes are left in the string*. For example, the string literal\n``r"\\n"`` consists of two characters: a backslash and a lowercase\n``\'n\'``. String quotes can be escaped with a backslash, but the\nbackslash remains in the string; for example, ``r"\\""`` is a valid\nstring literal consisting of two characters: a backslash and a double\nquote; ``r"\\"`` is not a valid string literal (even a raw string\ncannot end in an odd number of backslashes). Specifically, *a raw\nstring cannot end in a single backslash* (since the backslash would\nescape the following quote character). Note also that a single\nbackslash followed by a newline is interpreted as those two characters\nas part of the string, *not* as a line continuation.\n\nWhen an ``\'r\'`` or ``\'R\'`` prefix is used in conjunction with a\n``\'u\'`` or ``\'U\'`` prefix, then the ``\\uXXXX`` and ``\\UXXXXXXXX``\nescape sequences are processed while *all other backslashes are left\nin the string*. For example, the string literal ``ur"\\u0062\\n"``\nconsists of three Unicode characters: \'LATIN SMALL LETTER B\', \'REVERSE\nSOLIDUS\', and \'LATIN SMALL LETTER N\'. Backslashes can be escaped with\na preceding backslash; however, both remain in the string. As a\nresult, ``\\uXXXX`` escape sequences are only recognized when there are\nan odd number of backslashes.\n', 'subscriptions': u'\nSubscriptions\n*************\n\nA subscription selects an item of a sequence (string, tuple or list)\nor mapping (dictionary) object:\n\n subscription ::= primary "[" expression_list "]"\n\nThe primary must evaluate to an object of a sequence or mapping type.\n\nIf the primary is a mapping, the expression list must evaluate to an\nobject whose value is one of the keys of the mapping, and the\nsubscription selects the value in the mapping that corresponds to that\nkey. (The expression list is a tuple except if it has exactly one\nitem.)\n\nIf the primary is a sequence, the expression (list) must evaluate to a\nplain integer. If this value is negative, the length of the sequence\nis added to it (so that, e.g., ``x[-1]`` selects the last item of\n``x``.) The resulting value must be a nonnegative integer less than\nthe number of items in the sequence, and the subscription selects the\nitem whose index is that value (counting from zero).\n\nA string\'s items are characters. A character is not a separate data\ntype but a string of exactly one character.\n', 'truth': u"\nTruth Value Testing\n*******************\n\nAny object can be tested for truth value, for use in an ``if`` or\n``while`` condition or as operand of the Boolean operations below. The\nfollowing values are considered false:\n\n* ``None``\n\n* ``False``\n\n* zero of any numeric type, for example, ``0``, ``0L``, ``0.0``,\n ``0j``.\n\n* any empty sequence, for example, ``''``, ``()``, ``[]``.\n\n* any empty mapping, for example, ``{}``.\n\n* instances of user-defined classes, if the class defines a\n ``__nonzero__()`` or ``__len__()`` method, when that method returns\n the integer zero or ``bool`` value ``False``. [1]\n\nAll other values are considered true --- so objects of many types are\nalways true.\n\nOperations and built-in functions that have a Boolean result always\nreturn ``0`` or ``False`` for false and ``1`` or ``True`` for true,\nunless otherwise stated. (Important exception: the Boolean operations\n``or`` and ``and`` always return one of their operands.)\n", @@ -75,7 +75,7 @@ 'typesmapping': u'\nMapping Types --- ``dict``\n**************************\n\nA *mapping* object maps *hashable* values to arbitrary objects.\nMappings are mutable objects. There is currently only one standard\nmapping type, the *dictionary*. (For other containers see the built\nin ``list``, ``set``, and ``tuple`` classes, and the ``collections``\nmodule.)\n\nA dictionary\'s keys are *almost* arbitrary values. Values that are\nnot *hashable*, that is, values containing lists, dictionaries or\nother mutable types (that are compared by value rather than by object\nidentity) may not be used as keys. Numeric types used for keys obey\nthe normal rules for numeric comparison: if two numbers compare equal\n(such as ``1`` and ``1.0``) then they can be used interchangeably to\nindex the same dictionary entry. (Note however, that since computers\nstore floating-point numbers as approximations it is usually unwise to\nuse them as dictionary keys.)\n\nDictionaries can be created by placing a comma-separated list of\n``key: value`` pairs within braces, for example: ``{\'jack\': 4098,\n\'sjoerd\': 4127}`` or ``{4098: \'jack\', 4127: \'sjoerd\'}``, or by the\n``dict`` constructor.\n\nclass class dict([arg])\n\n Return a new dictionary initialized from an optional positional\n argument or from a set of keyword arguments. If no arguments are\n given, return a new empty dictionary. If the positional argument\n *arg* is a mapping object, return a dictionary mapping the same\n keys to the same values as does the mapping object. Otherwise the\n positional argument must be a sequence, a container that supports\n iteration, or an iterator object. The elements of the argument\n must each also be of one of those kinds, and each must in turn\n contain exactly two objects. The first is used as a key in the new\n dictionary, and the second as the key\'s value. If a given key is\n seen more than once, the last value associated with it is retained\n in the new dictionary.\n\n If keyword arguments are given, the keywords themselves with their\n associated values are added as items to the dictionary. If a key is\n specified both in the positional argument and as a keyword\n argument, the value associated with the keyword is retained in the\n dictionary. For example, these all return a dictionary equal to\n ``{"one": 2, "two": 3}``:\n\n * ``dict(one=2, two=3)``\n\n * ``dict({\'one\': 2, \'two\': 3})``\n\n * ``dict(zip((\'one\', \'two\'), (2, 3)))``\n\n * ``dict([[\'two\', 3], [\'one\', 2]])``\n\n The first example only works for keys that are valid Python\n identifiers; the others work with any valid keys.\n\n New in version 2.2.\n\n Changed in version 2.3: Support for building a dictionary from\n keyword arguments added.\n\n These are the operations that dictionaries support (and therefore,\n custom mapping types should support too):\n\n len(d)\n\n Return the number of items in the dictionary *d*.\n\n d[key]\n\n Return the item of *d* with key *key*. Raises a ``KeyError`` if\n *key* is not in the map.\n\n New in version 2.5: If a subclass of dict defines a method\n ``__missing__()``, if the key *key* is not present, the\n ``d[key]`` operation calls that method with the key *key* as\n argument. The ``d[key]`` operation then returns or raises\n whatever is returned or raised by the ``__missing__(key)`` call\n if the key is not present. No other operations or methods invoke\n ``__missing__()``. If ``__missing__()`` is not defined,\n ``KeyError`` is raised. ``__missing__()`` must be a method; it\n cannot be an instance variable. For an example, see\n ``collections.defaultdict``.\n\n d[key] = value\n\n Set ``d[key]`` to *value*.\n\n del d[key]\n\n Remove ``d[key]`` from *d*. Raises a ``KeyError`` if *key* is\n not in the map.\n\n key in d\n\n Return ``True`` if *d* has a key *key*, else ``False``.\n\n New in version 2.2.\n\n key not in d\n\n Equivalent to ``not key in d``.\n\n New in version 2.2.\n\n iter(d)\n\n Return an iterator over the keys of the dictionary. This is a\n shortcut for ``iterkeys()``.\n\n clear()\n\n Remove all items from the dictionary.\n\n copy()\n\n Return a shallow copy of the dictionary.\n\n fromkeys(seq[, value])\n\n Create a new dictionary with keys from *seq* and values set to\n *value*.\n\n ``fromkeys()`` is a class method that returns a new dictionary.\n *value* defaults to ``None``.\n\n New in version 2.3.\n\n get(key[, default])\n\n Return the value for *key* if *key* is in the dictionary, else\n *default*. If *default* is not given, it defaults to ``None``,\n so that this method never raises a ``KeyError``.\n\n has_key(key)\n\n Test for the presence of *key* in the dictionary. ``has_key()``\n is deprecated in favor of ``key in d``.\n\n items()\n\n Return a copy of the dictionary\'s list of ``(key, value)``\n pairs.\n\n **CPython implementation detail:** Keys and values are listed in\n an arbitrary order which is non-random, varies across Python\n implementations, and depends on the dictionary\'s history of\n insertions and deletions.\n\n If ``items()``, ``keys()``, ``values()``, ``iteritems()``,\n ``iterkeys()``, and ``itervalues()`` are called with no\n intervening modifications to the dictionary, the lists will\n directly correspond. This allows the creation of ``(value,\n key)`` pairs using ``zip()``: ``pairs = zip(d.values(),\n d.keys())``. The same relationship holds for the ``iterkeys()``\n and ``itervalues()`` methods: ``pairs = zip(d.itervalues(),\n d.iterkeys())`` provides the same value for ``pairs``. Another\n way to create the same list is ``pairs = [(v, k) for (k, v) in\n d.iteritems()]``.\n\n iteritems()\n\n Return an iterator over the dictionary\'s ``(key, value)`` pairs.\n See the note for ``dict.items()``.\n\n Using ``iteritems()`` while adding or deleting entries in the\n dictionary may raise a ``RuntimeError`` or fail to iterate over\n all entries.\n\n New in version 2.2.\n\n iterkeys()\n\n Return an iterator over the dictionary\'s keys. See the note for\n ``dict.items()``.\n\n Using ``iterkeys()`` while adding or deleting entries in the\n dictionary may raise a ``RuntimeError`` or fail to iterate over\n all entries.\n\n New in version 2.2.\n\n itervalues()\n\n Return an iterator over the dictionary\'s values. See the note\n for ``dict.items()``.\n\n Using ``itervalues()`` while adding or deleting entries in the\n dictionary may raise a ``RuntimeError`` or fail to iterate over\n all entries.\n\n New in version 2.2.\n\n keys()\n\n Return a copy of the dictionary\'s list of keys. See the note\n for ``dict.items()``.\n\n pop(key[, default])\n\n If *key* is in the dictionary, remove it and return its value,\n else return *default*. If *default* is not given and *key* is\n not in the dictionary, a ``KeyError`` is raised.\n\n New in version 2.3.\n\n popitem()\n\n Remove and return an arbitrary ``(key, value)`` pair from the\n dictionary.\n\n ``popitem()`` is useful to destructively iterate over a\n dictionary, as often used in set algorithms. If the dictionary\n is empty, calling ``popitem()`` raises a ``KeyError``.\n\n setdefault(key[, default])\n\n If *key* is in the dictionary, return its value. If not, insert\n *key* with a value of *default* and return *default*. *default*\n defaults to ``None``.\n\n update([other])\n\n Update the dictionary with the key/value pairs from *other*,\n overwriting existing keys. Return ``None``.\n\n ``update()`` accepts either another dictionary object or an\n iterable of key/value pairs (as a tuple or other iterable of\n length two). If keyword arguments are specified, the dictionary\n is then updated with those key/value pairs: ``d.update(red=1,\n blue=2)``.\n\n Changed in version 2.4: Allowed the argument to be an iterable\n of key/value pairs and allowed keyword arguments.\n\n values()\n\n Return a copy of the dictionary\'s list of values. See the note\n for ``dict.items()``.\n\n viewitems()\n\n Return a new view of the dictionary\'s items (``(key, value)``\n pairs). See below for documentation of view objects.\n\n New in version 2.7.\n\n viewkeys()\n\n Return a new view of the dictionary\'s keys. See below for\n documentation of view objects.\n\n New in version 2.7.\n\n viewvalues()\n\n Return a new view of the dictionary\'s values. See below for\n documentation of view objects.\n\n New in version 2.7.\n\n\nDictionary view objects\n=======================\n\nThe objects returned by ``dict.viewkeys()``, ``dict.viewvalues()`` and\n``dict.viewitems()`` are *view objects*. They provide a dynamic view\non the dictionary\'s entries, which means that when the dictionary\nchanges, the view reflects these changes.\n\nDictionary views can be iterated over to yield their respective data,\nand support membership tests:\n\nlen(dictview)\n\n Return the number of entries in the dictionary.\n\niter(dictview)\n\n Return an iterator over the keys, values or items (represented as\n tuples of ``(key, value)``) in the dictionary.\n\n Keys and values are iterated over in an arbitrary order which is\n non-random, varies across Python implementations, and depends on\n the dictionary\'s history of insertions and deletions. If keys,\n values and items views are iterated over with no intervening\n modifications to the dictionary, the order of items will directly\n correspond. This allows the creation of ``(value, key)`` pairs\n using ``zip()``: ``pairs = zip(d.values(), d.keys())``. Another\n way to create the same list is ``pairs = [(v, k) for (k, v) in\n d.items()]``.\n\n Iterating views while adding or deleting entries in the dictionary\n may raise a ``RuntimeError`` or fail to iterate over all entries.\n\nx in dictview\n\n Return ``True`` if *x* is in the underlying dictionary\'s keys,\n values or items (in the latter case, *x* should be a ``(key,\n value)`` tuple).\n\nKeys views are set-like since their entries are unique and hashable.\nIf all values are hashable, so that (key, value) pairs are unique and\nhashable, then the items view is also set-like. (Values views are not\ntreated as set-like since the entries are generally not unique.) Then\nthese set operations are available ("other" refers either to another\nview or a set):\n\ndictview & other\n\n Return the intersection of the dictview and the other object as a\n new set.\n\ndictview | other\n\n Return the union of the dictview and the other object as a new set.\n\ndictview - other\n\n Return the difference between the dictview and the other object\n (all elements in *dictview* that aren\'t in *other*) as a new set.\n\ndictview ^ other\n\n Return the symmetric difference (all elements either in *dictview*\n or *other*, but not in both) of the dictview and the other object\n as a new set.\n\nAn example of dictionary view usage:\n\n >>> dishes = {\'eggs\': 2, \'sausage\': 1, \'bacon\': 1, \'spam\': 500}\n >>> keys = dishes.viewkeys()\n >>> values = dishes.viewvalues()\n\n >>> # iteration\n >>> n = 0\n >>> for val in values:\n ... n += val\n >>> print(n)\n 504\n\n >>> # keys and values are iterated over in the same order\n >>> list(keys)\n [\'eggs\', \'bacon\', \'sausage\', \'spam\']\n >>> list(values)\n [2, 1, 1, 500]\n\n >>> # view objects are dynamic and reflect dict changes\n >>> del dishes[\'eggs\']\n >>> del dishes[\'sausage\']\n >>> list(keys)\n [\'spam\', \'bacon\']\n\n >>> # set operations\n >>> keys & {\'eggs\', \'bacon\', \'salad\'}\n {\'bacon\'}\n', 'typesmethods': u"\nMethods\n*******\n\nMethods are functions that are called using the attribute notation.\nThere are two flavors: built-in methods (such as ``append()`` on\nlists) and class instance methods. Built-in methods are described\nwith the types that support them.\n\nThe implementation adds two special read-only attributes to class\ninstance methods: ``m.im_self`` is the object on which the method\noperates, and ``m.im_func`` is the function implementing the method.\nCalling ``m(arg-1, arg-2, ..., arg-n)`` is completely equivalent to\ncalling ``m.im_func(m.im_self, arg-1, arg-2, ..., arg-n)``.\n\nClass instance methods are either *bound* or *unbound*, referring to\nwhether the method was accessed through an instance or a class,\nrespectively. When a method is unbound, its ``im_self`` attribute\nwill be ``None`` and if called, an explicit ``self`` object must be\npassed as the first argument. In this case, ``self`` must be an\ninstance of the unbound method's class (or a subclass of that class),\notherwise a ``TypeError`` is raised.\n\nLike function objects, methods objects support getting arbitrary\nattributes. However, since method attributes are actually stored on\nthe underlying function object (``meth.im_func``), setting method\nattributes on either bound or unbound methods is disallowed.\nAttempting to set a method attribute results in a ``TypeError`` being\nraised. In order to set a method attribute, you need to explicitly\nset it on the underlying function object:\n\n class C:\n def method(self):\n pass\n\n c = C()\n c.method.im_func.whoami = 'my name is c'\n\nSee *The standard type hierarchy* for more information.\n", 'typesmodules': u"\nModules\n*******\n\nThe only special operation on a module is attribute access:\n``m.name``, where *m* is a module and *name* accesses a name defined\nin *m*'s symbol table. Module attributes can be assigned to. (Note\nthat the ``import`` statement is not, strictly speaking, an operation\non a module object; ``import foo`` does not require a module object\nnamed *foo* to exist, rather it requires an (external) *definition*\nfor a module named *foo* somewhere.)\n\nA special member of every module is ``__dict__``. This is the\ndictionary containing the module's symbol table. Modifying this\ndictionary will actually change the module's symbol table, but direct\nassignment to the ``__dict__`` attribute is not possible (you can\nwrite ``m.__dict__['a'] = 1``, which defines ``m.a`` to be ``1``, but\nyou can't write ``m.__dict__ = {}``). Modifying ``__dict__`` directly\nis not recommended.\n\nModules built into the interpreter are written like this: ````. If loaded from a file, they are written as\n````.\n", - 'typesseq': u'\nSequence Types --- ``str``, ``unicode``, ``list``, ``tuple``, ``buffer``, ``xrange``\n************************************************************************************\n\nThere are six sequence types: strings, Unicode strings, lists, tuples,\nbuffers, and xrange objects.\n\nFor other containers see the built in ``dict`` and ``set`` classes,\nand the ``collections`` module.\n\nString literals are written in single or double quotes: ``\'xyzzy\'``,\n``"frobozz"``. See *String literals* for more about string literals.\nUnicode strings are much like strings, but are specified in the syntax\nusing a preceding ``\'u\'`` character: ``u\'abc\'``, ``u"def"``. In\naddition to the functionality described here, there are also string-\nspecific methods described in the *String Methods* section. Lists are\nconstructed with square brackets, separating items with commas: ``[a,\nb, c]``. Tuples are constructed by the comma operator (not within\nsquare brackets), with or without enclosing parentheses, but an empty\ntuple must have the enclosing parentheses, such as ``a, b, c`` or\n``()``. A single item tuple must have a trailing comma, such as\n``(d,)``.\n\nBuffer objects are not directly supported by Python syntax, but can be\ncreated by calling the built-in function ``buffer()``. They don\'t\nsupport concatenation or repetition.\n\nObjects of type xrange are similar to buffers in that there is no\nspecific syntax to create them, but they are created using the\n``xrange()`` function. They don\'t support slicing, concatenation or\nrepetition, and using ``in``, ``not in``, ``min()`` or ``max()`` on\nthem is inefficient.\n\nMost sequence types support the following operations. The ``in`` and\n``not in`` operations have the same priorities as the comparison\noperations. The ``+`` and ``*`` operations have the same priority as\nthe corresponding numeric operations. [3] Additional methods are\nprovided for *Mutable Sequence Types*.\n\nThis table lists the sequence operations sorted in ascending priority\n(operations in the same box have the same priority). In the table,\n*s* and *t* are sequences of the same type; *n*, *i* and *j* are\nintegers:\n\n+--------------------+----------------------------------+------------+\n| Operation | Result | Notes |\n+====================+==================================+============+\n| ``x in s`` | ``True`` if an item of *s* is | (1) |\n| | equal to *x*, else ``False`` | |\n+--------------------+----------------------------------+------------+\n| ``x not in s`` | ``False`` if an item of *s* is | (1) |\n| | equal to *x*, else ``True`` | |\n+--------------------+----------------------------------+------------+\n| ``s + t`` | the concatenation of *s* and *t* | (6) |\n+--------------------+----------------------------------+------------+\n| ``s * n, n * s`` | *n* shallow copies of *s* | (2) |\n| | concatenated | |\n+--------------------+----------------------------------+------------+\n| ``s[i]`` | *i*\'th item of *s*, origin 0 | (3) |\n+--------------------+----------------------------------+------------+\n| ``s[i:j]`` | slice of *s* from *i* to *j* | (3)(4) |\n+--------------------+----------------------------------+------------+\n| ``s[i:j:k]`` | slice of *s* from *i* to *j* | (3)(5) |\n| | with step *k* | |\n+--------------------+----------------------------------+------------+\n| ``len(s)`` | length of *s* | |\n+--------------------+----------------------------------+------------+\n| ``min(s)`` | smallest item of *s* | |\n+--------------------+----------------------------------+------------+\n| ``max(s)`` | largest item of *s* | |\n+--------------------+----------------------------------+------------+\n\nSequence types also support comparisons. In particular, tuples and\nlists are compared lexicographically by comparing corresponding\nelements. This means that to compare equal, every element must compare\nequal and the two sequences must be of the same type and have the same\nlength. (For full details see *Comparisons* in the language\nreference.)\n\nNotes:\n\n1. When *s* is a string or Unicode string object the ``in`` and ``not\n in`` operations act like a substring test. In Python versions\n before 2.3, *x* had to be a string of length 1. In Python 2.3 and\n beyond, *x* may be a string of any length.\n\n2. Values of *n* less than ``0`` are treated as ``0`` (which yields an\n empty sequence of the same type as *s*). Note also that the copies\n are shallow; nested structures are not copied. This often haunts\n new Python programmers; consider:\n\n >>> lists = [[]] * 3\n >>> lists\n [[], [], []]\n >>> lists[0].append(3)\n >>> lists\n [[3], [3], [3]]\n\n What has happened is that ``[[]]`` is a one-element list containing\n an empty list, so all three elements of ``[[]] * 3`` are (pointers\n to) this single empty list. Modifying any of the elements of\n ``lists`` modifies this single list. You can create a list of\n different lists this way:\n\n >>> lists = [[] for i in range(3)]\n >>> lists[0].append(3)\n >>> lists[1].append(5)\n >>> lists[2].append(7)\n >>> lists\n [[3], [5], [7]]\n\n3. If *i* or *j* is negative, the index is relative to the end of the\n string: ``len(s) + i`` or ``len(s) + j`` is substituted. But note\n that ``-0`` is still ``0``.\n\n4. The slice of *s* from *i* to *j* is defined as the sequence of\n items with index *k* such that ``i <= k < j``. If *i* or *j* is\n greater than ``len(s)``, use ``len(s)``. If *i* is omitted or\n ``None``, use ``0``. If *j* is omitted or ``None``, use\n ``len(s)``. If *i* is greater than or equal to *j*, the slice is\n empty.\n\n5. The slice of *s* from *i* to *j* with step *k* is defined as the\n sequence of items with index ``x = i + n*k`` such that ``0 <= n <\n (j-i)/k``. In other words, the indices are ``i``, ``i+k``,\n ``i+2*k``, ``i+3*k`` and so on, stopping when *j* is reached (but\n never including *j*). If *i* or *j* is greater than ``len(s)``,\n use ``len(s)``. If *i* or *j* are omitted or ``None``, they become\n "end" values (which end depends on the sign of *k*). Note, *k*\n cannot be zero. If *k* is ``None``, it is treated like ``1``.\n\n6. **CPython implementation detail:** If *s* and *t* are both strings,\n some Python implementations such as CPython can usually perform an\n in-place optimization for assignments of the form ``s = s + t`` or\n ``s += t``. When applicable, this optimization makes quadratic\n run-time much less likely. This optimization is both version and\n implementation dependent. For performance sensitive code, it is\n preferable to use the ``str.join()`` method which assures\n consistent linear concatenation performance across versions and\n implementations.\n\n Changed in version 2.4: Formerly, string concatenation never\n occurred in-place.\n\n\nString Methods\n==============\n\nBelow are listed the string methods which both 8-bit strings and\nUnicode objects support.\n\nIn addition, Python\'s strings support the sequence type methods\ndescribed in the *Sequence Types --- str, unicode, list, tuple,\nbuffer, xrange* section. To output formatted strings use template\nstrings or the ``%`` operator described in the *String Formatting\nOperations* section. Also, see the ``re`` module for string functions\nbased on regular expressions.\n\nstr.capitalize()\n\n Return a copy of the string with only its first character\n capitalized.\n\n For 8-bit strings, this method is locale-dependent.\n\nstr.center(width[, fillchar])\n\n Return centered in a string of length *width*. Padding is done\n using the specified *fillchar* (default is a space).\n\n Changed in version 2.4: Support for the *fillchar* argument.\n\nstr.count(sub[, start[, end]])\n\n Return the number of non-overlapping occurrences of substring *sub*\n in the range [*start*, *end*]. Optional arguments *start* and\n *end* are interpreted as in slice notation.\n\nstr.decode([encoding[, errors]])\n\n Decodes the string using the codec registered for *encoding*.\n *encoding* defaults to the default string encoding. *errors* may\n be given to set a different error handling scheme. The default is\n ``\'strict\'``, meaning that encoding errors raise ``UnicodeError``.\n Other possible values are ``\'ignore\'``, ``\'replace\'`` and any other\n name registered via ``codecs.register_error()``, see section *Codec\n Base Classes*.\n\n New in version 2.2.\n\n Changed in version 2.3: Support for other error handling schemes\n added.\n\n Changed in version 2.7: Support for keyword arguments added.\n\nstr.encode([encoding[, errors]])\n\n Return an encoded version of the string. Default encoding is the\n current default string encoding. *errors* may be given to set a\n different error handling scheme. The default for *errors* is\n ``\'strict\'``, meaning that encoding errors raise a\n ``UnicodeError``. Other possible values are ``\'ignore\'``,\n ``\'replace\'``, ``\'xmlcharrefreplace\'``, ``\'backslashreplace\'`` and\n any other name registered via ``codecs.register_error()``, see\n section *Codec Base Classes*. For a list of possible encodings, see\n section *Standard Encodings*.\n\n New in version 2.0.\n\n Changed in version 2.3: Support for ``\'xmlcharrefreplace\'`` and\n ``\'backslashreplace\'`` and other error handling schemes added.\n\n Changed in version 2.7: Support for keyword arguments added.\n\nstr.endswith(suffix[, start[, end]])\n\n Return ``True`` if the string ends with the specified *suffix*,\n otherwise return ``False``. *suffix* can also be a tuple of\n suffixes to look for. With optional *start*, test beginning at\n that position. With optional *end*, stop comparing at that\n position.\n\n Changed in version 2.5: Accept tuples as *suffix*.\n\nstr.expandtabs([tabsize])\n\n Return a copy of the string where all tab characters are replaced\n by one or more spaces, depending on the current column and the\n given tab size. The column number is reset to zero after each\n newline occurring in the string. If *tabsize* is not given, a tab\n size of ``8`` characters is assumed. This doesn\'t understand other\n non-printing characters or escape sequences.\n\nstr.find(sub[, start[, end]])\n\n Return the lowest index in the string where substring *sub* is\n found, such that *sub* is contained in the range [*start*, *end*].\n Optional arguments *start* and *end* are interpreted as in slice\n notation. Return ``-1`` if *sub* is not found.\n\nstr.format(*args, **kwargs)\n\n Perform a string formatting operation. The string on which this\n method is called can contain literal text or replacement fields\n delimited by braces ``{}``. Each replacement field contains either\n the numeric index of a positional argument, or the name of a\n keyword argument. Returns a copy of the string where each\n replacement field is replaced with the string value of the\n corresponding argument.\n\n >>> "The sum of 1 + 2 is {0}".format(1+2)\n \'The sum of 1 + 2 is 3\'\n\n See *Format String Syntax* for a description of the various\n formatting options that can be specified in format strings.\n\n This method of string formatting is the new standard in Python 3.0,\n and should be preferred to the ``%`` formatting described in\n *String Formatting Operations* in new code.\n\n New in version 2.6.\n\nstr.index(sub[, start[, end]])\n\n Like ``find()``, but raise ``ValueError`` when the substring is not\n found.\n\nstr.isalnum()\n\n Return true if all characters in the string are alphanumeric and\n there is at least one character, false otherwise.\n\n For 8-bit strings, this method is locale-dependent.\n\nstr.isalpha()\n\n Return true if all characters in the string are alphabetic and\n there is at least one character, false otherwise.\n\n For 8-bit strings, this method is locale-dependent.\n\nstr.isdigit()\n\n Return true if all characters in the string are digits and there is\n at least one character, false otherwise.\n\n For 8-bit strings, this method is locale-dependent.\n\nstr.islower()\n\n Return true if all cased characters in the string are lowercase and\n there is at least one cased character, false otherwise.\n\n For 8-bit strings, this method is locale-dependent.\n\nstr.isspace()\n\n Return true if there are only whitespace characters in the string\n and there is at least one character, false otherwise.\n\n For 8-bit strings, this method is locale-dependent.\n\nstr.istitle()\n\n Return true if the string is a titlecased string and there is at\n least one character, for example uppercase characters may only\n follow uncased characters and lowercase characters only cased ones.\n Return false otherwise.\n\n For 8-bit strings, this method is locale-dependent.\n\nstr.isupper()\n\n Return true if all cased characters in the string are uppercase and\n there is at least one cased character, false otherwise.\n\n For 8-bit strings, this method is locale-dependent.\n\nstr.join(iterable)\n\n Return a string which is the concatenation of the strings in the\n *iterable* *iterable*. The separator between elements is the\n string providing this method.\n\nstr.ljust(width[, fillchar])\n\n Return the string left justified in a string of length *width*.\n Padding is done using the specified *fillchar* (default is a\n space). The original string is returned if *width* is less than\n ``len(s)``.\n\n Changed in version 2.4: Support for the *fillchar* argument.\n\nstr.lower()\n\n Return a copy of the string converted to lowercase.\n\n For 8-bit strings, this method is locale-dependent.\n\nstr.lstrip([chars])\n\n Return a copy of the string with leading characters removed. The\n *chars* argument is a string specifying the set of characters to be\n removed. If omitted or ``None``, the *chars* argument defaults to\n removing whitespace. The *chars* argument is not a prefix; rather,\n all combinations of its values are stripped:\n\n >>> \' spacious \'.lstrip()\n \'spacious \'\n >>> \'www.example.com\'.lstrip(\'cmowz.\')\n \'example.com\'\n\n Changed in version 2.2.2: Support for the *chars* argument.\n\nstr.partition(sep)\n\n Split the string at the first occurrence of *sep*, and return a\n 3-tuple containing the part before the separator, the separator\n itself, and the part after the separator. If the separator is not\n found, return a 3-tuple containing the string itself, followed by\n two empty strings.\n\n New in version 2.5.\n\nstr.replace(old, new[, count])\n\n Return a copy of the string with all occurrences of substring *old*\n replaced by *new*. If the optional argument *count* is given, only\n the first *count* occurrences are replaced.\n\nstr.rfind(sub[, start[, end]])\n\n Return the highest index in the string where substring *sub* is\n found, such that *sub* is contained within s[start,end]. Optional\n arguments *start* and *end* are interpreted as in slice notation.\n Return ``-1`` on failure.\n\nstr.rindex(sub[, start[, end]])\n\n Like ``rfind()`` but raises ``ValueError`` when the substring *sub*\n is not found.\n\nstr.rjust(width[, fillchar])\n\n Return the string right justified in a string of length *width*.\n Padding is done using the specified *fillchar* (default is a\n space). The original string is returned if *width* is less than\n ``len(s)``.\n\n Changed in version 2.4: Support for the *fillchar* argument.\n\nstr.rpartition(sep)\n\n Split the string at the last occurrence of *sep*, and return a\n 3-tuple containing the part before the separator, the separator\n itself, and the part after the separator. If the separator is not\n found, return a 3-tuple containing two empty strings, followed by\n the string itself.\n\n New in version 2.5.\n\nstr.rsplit([sep[, maxsplit]])\n\n Return a list of the words in the string, using *sep* as the\n delimiter string. If *maxsplit* is given, at most *maxsplit* splits\n are done, the *rightmost* ones. If *sep* is not specified or\n ``None``, any whitespace string is a separator. Except for\n splitting from the right, ``rsplit()`` behaves like ``split()``\n which is described in detail below.\n\n New in version 2.4.\n\nstr.rstrip([chars])\n\n Return a copy of the string with trailing characters removed. The\n *chars* argument is a string specifying the set of characters to be\n removed. If omitted or ``None``, the *chars* argument defaults to\n removing whitespace. The *chars* argument is not a suffix; rather,\n all combinations of its values are stripped:\n\n >>> \' spacious \'.rstrip()\n \' spacious\'\n >>> \'mississippi\'.rstrip(\'ipz\')\n \'mississ\'\n\n Changed in version 2.2.2: Support for the *chars* argument.\n\nstr.split([sep[, maxsplit]])\n\n Return a list of the words in the string, using *sep* as the\n delimiter string. If *maxsplit* is given, at most *maxsplit*\n splits are done (thus, the list will have at most ``maxsplit+1``\n elements). If *maxsplit* is not specified, then there is no limit\n on the number of splits (all possible splits are made).\n\n If *sep* is given, consecutive delimiters are not grouped together\n and are deemed to delimit empty strings (for example,\n ``\'1,,2\'.split(\',\')`` returns ``[\'1\', \'\', \'2\']``). The *sep*\n argument may consist of multiple characters (for example,\n ``\'1<>2<>3\'.split(\'<>\')`` returns ``[\'1\', \'2\', \'3\']``). Splitting\n an empty string with a specified separator returns ``[\'\']``.\n\n If *sep* is not specified or is ``None``, a different splitting\n algorithm is applied: runs of consecutive whitespace are regarded\n as a single separator, and the result will contain no empty strings\n at the start or end if the string has leading or trailing\n whitespace. Consequently, splitting an empty string or a string\n consisting of just whitespace with a ``None`` separator returns\n ``[]``.\n\n For example, ``\' 1 2 3 \'.split()`` returns ``[\'1\', \'2\', \'3\']``,\n and ``\' 1 2 3 \'.split(None, 1)`` returns ``[\'1\', \'2 3 \']``.\n\nstr.splitlines([keepends])\n\n Return a list of the lines in the string, breaking at line\n boundaries. Line breaks are not included in the resulting list\n unless *keepends* is given and true.\n\nstr.startswith(prefix[, start[, end]])\n\n Return ``True`` if string starts with the *prefix*, otherwise\n return ``False``. *prefix* can also be a tuple of prefixes to look\n for. With optional *start*, test string beginning at that\n position. With optional *end*, stop comparing string at that\n position.\n\n Changed in version 2.5: Accept tuples as *prefix*.\n\nstr.strip([chars])\n\n Return a copy of the string with the leading and trailing\n characters removed. The *chars* argument is a string specifying the\n set of characters to be removed. If omitted or ``None``, the\n *chars* argument defaults to removing whitespace. The *chars*\n argument is not a prefix or suffix; rather, all combinations of its\n values are stripped:\n\n >>> \' spacious \'.strip()\n \'spacious\'\n >>> \'www.example.com\'.strip(\'cmowz.\')\n \'example\'\n\n Changed in version 2.2.2: Support for the *chars* argument.\n\nstr.swapcase()\n\n Return a copy of the string with uppercase characters converted to\n lowercase and vice versa.\n\n For 8-bit strings, this method is locale-dependent.\n\nstr.title()\n\n Return a titlecased version of the string where words start with an\n uppercase character and the remaining characters are lowercase.\n\n The algorithm uses a simple language-independent definition of a\n word as groups of consecutive letters. The definition works in\n many contexts but it means that apostrophes in contractions and\n possessives form word boundaries, which may not be the desired\n result:\n\n >>> "they\'re bill\'s friends from the UK".title()\n "They\'Re Bill\'S Friends From The Uk"\n\n A workaround for apostrophes can be constructed using regular\n expressions:\n\n >>> import re\n >>> def titlecase(s):\n return re.sub(r"[A-Za-z]+(\'[A-Za-z]+)?",\n lambda mo: mo.group(0)[0].upper() +\n mo.group(0)[1:].lower(),\n s)\n\n >>> titlecase("they\'re bill\'s friends.")\n "They\'re Bill\'s Friends."\n\n For 8-bit strings, this method is locale-dependent.\n\nstr.translate(table[, deletechars])\n\n Return a copy of the string where all characters occurring in the\n optional argument *deletechars* are removed, and the remaining\n characters have been mapped through the given translation table,\n which must be a string of length 256.\n\n You can use the ``maketrans()`` helper function in the ``string``\n module to create a translation table. For string objects, set the\n *table* argument to ``None`` for translations that only delete\n characters:\n\n >>> \'read this short text\'.translate(None, \'aeiou\')\n \'rd ths shrt txt\'\n\n New in version 2.6: Support for a ``None`` *table* argument.\n\n For Unicode objects, the ``translate()`` method does not accept the\n optional *deletechars* argument. Instead, it returns a copy of the\n *s* where all characters have been mapped through the given\n translation table which must be a mapping of Unicode ordinals to\n Unicode ordinals, Unicode strings or ``None``. Unmapped characters\n are left untouched. Characters mapped to ``None`` are deleted.\n Note, a more flexible approach is to create a custom character\n mapping codec using the ``codecs`` module (see ``encodings.cp1251``\n for an example).\n\nstr.upper()\n\n Return a copy of the string converted to uppercase.\n\n For 8-bit strings, this method is locale-dependent.\n\nstr.zfill(width)\n\n Return the numeric string left filled with zeros in a string of\n length *width*. A sign prefix is handled correctly. The original\n string is returned if *width* is less than ``len(s)``.\n\n New in version 2.2.2.\n\nThe following methods are present only on unicode objects:\n\nunicode.isnumeric()\n\n Return ``True`` if there are only numeric characters in S,\n ``False`` otherwise. Numeric characters include digit characters,\n and all characters that have the Unicode numeric value property,\n e.g. U+2155, VULGAR FRACTION ONE FIFTH.\n\nunicode.isdecimal()\n\n Return ``True`` if there are only decimal characters in S,\n ``False`` otherwise. Decimal characters include digit characters,\n and all characters that that can be used to form decimal-radix\n numbers, e.g. U+0660, ARABIC-INDIC DIGIT ZERO.\n\n\nString Formatting Operations\n============================\n\nString and Unicode objects have one unique built-in operation: the\n``%`` operator (modulo). This is also known as the string\n*formatting* or *interpolation* operator. Given ``format % values``\n(where *format* is a string or Unicode object), ``%`` conversion\nspecifications in *format* are replaced with zero or more elements of\n*values*. The effect is similar to the using ``sprintf()`` in the C\nlanguage. If *format* is a Unicode object, or if any of the objects\nbeing converted using the ``%s`` conversion are Unicode objects, the\nresult will also be a Unicode object.\n\nIf *format* requires a single argument, *values* may be a single non-\ntuple object. [4] Otherwise, *values* must be a tuple with exactly\nthe number of items specified by the format string, or a single\nmapping object (for example, a dictionary).\n\nA conversion specifier contains two or more characters and has the\nfollowing components, which must occur in this order:\n\n1. The ``\'%\'`` character, which marks the start of the specifier.\n\n2. Mapping key (optional), consisting of a parenthesised sequence of\n characters (for example, ``(somename)``).\n\n3. Conversion flags (optional), which affect the result of some\n conversion types.\n\n4. Minimum field width (optional). If specified as an ``\'*\'``\n (asterisk), the actual width is read from the next element of the\n tuple in *values*, and the object to convert comes after the\n minimum field width and optional precision.\n\n5. Precision (optional), given as a ``\'.\'`` (dot) followed by the\n precision. If specified as ``\'*\'`` (an asterisk), the actual width\n is read from the next element of the tuple in *values*, and the\n value to convert comes after the precision.\n\n6. Length modifier (optional).\n\n7. Conversion type.\n\nWhen the right argument is a dictionary (or other mapping type), then\nthe formats in the string *must* include a parenthesised mapping key\ninto that dictionary inserted immediately after the ``\'%\'`` character.\nThe mapping key selects the value to be formatted from the mapping.\nFor example:\n\n>>> print \'%(language)s has %(#)03d quote types.\' % \\\n... {\'language\': "Python", "#": 2}\nPython has 002 quote types.\n\nIn this case no ``*`` specifiers may occur in a format (since they\nrequire a sequential parameter list).\n\nThe conversion flag characters are:\n\n+-----------+-----------------------------------------------------------------------+\n| Flag | Meaning |\n+===========+=======================================================================+\n| ``\'#\'`` | The value conversion will use the "alternate form" (where defined |\n| | below). |\n+-----------+-----------------------------------------------------------------------+\n| ``\'0\'`` | The conversion will be zero padded for numeric values. |\n+-----------+-----------------------------------------------------------------------+\n| ``\'-\'`` | The converted value is left adjusted (overrides the ``\'0\'`` |\n| | conversion if both are given). |\n+-----------+-----------------------------------------------------------------------+\n| ``\' \'`` | (a space) A blank should be left before a positive number (or empty |\n| | string) produced by a signed conversion. |\n+-----------+-----------------------------------------------------------------------+\n| ``\'+\'`` | A sign character (``\'+\'`` or ``\'-\'``) will precede the conversion |\n| | (overrides a "space" flag). |\n+-----------+-----------------------------------------------------------------------+\n\nA length modifier (``h``, ``l``, or ``L``) may be present, but is\nignored as it is not necessary for Python -- so e.g. ``%ld`` is\nidentical to ``%d``.\n\nThe conversion types are:\n\n+--------------+-------------------------------------------------------+---------+\n| Conversion | Meaning | Notes |\n+==============+=======================================================+=========+\n| ``\'d\'`` | Signed integer decimal. | |\n+--------------+-------------------------------------------------------+---------+\n| ``\'i\'`` | Signed integer decimal. | |\n+--------------+-------------------------------------------------------+---------+\n| ``\'o\'`` | Signed octal value. | (1) |\n+--------------+-------------------------------------------------------+---------+\n| ``\'u\'`` | Obsolete type -- it is identical to ``\'d\'``. | (7) |\n+--------------+-------------------------------------------------------+---------+\n| ``\'x\'`` | Signed hexadecimal (lowercase). | (2) |\n+--------------+-------------------------------------------------------+---------+\n| ``\'X\'`` | Signed hexadecimal (uppercase). | (2) |\n+--------------+-------------------------------------------------------+---------+\n| ``\'e\'`` | Floating point exponential format (lowercase). | (3) |\n+--------------+-------------------------------------------------------+---------+\n| ``\'E\'`` | Floating point exponential format (uppercase). | (3) |\n+--------------+-------------------------------------------------------+---------+\n| ``\'f\'`` | Floating point decimal format. | (3) |\n+--------------+-------------------------------------------------------+---------+\n| ``\'F\'`` | Floating point decimal format. | (3) |\n+--------------+-------------------------------------------------------+---------+\n| ``\'g\'`` | Floating point format. Uses lowercase exponential | (4) |\n| | format if exponent is less than -4 or not less than | |\n| | precision, decimal format otherwise. | |\n+--------------+-------------------------------------------------------+---------+\n| ``\'G\'`` | Floating point format. Uses uppercase exponential | (4) |\n| | format if exponent is less than -4 or not less than | |\n| | precision, decimal format otherwise. | |\n+--------------+-------------------------------------------------------+---------+\n| ``\'c\'`` | Single character (accepts integer or single character | |\n| | string). | |\n+--------------+-------------------------------------------------------+---------+\n| ``\'r\'`` | String (converts any Python object using ``repr()``). | (5) |\n+--------------+-------------------------------------------------------+---------+\n| ``\'s\'`` | String (converts any Python object using ``str()``). | (6) |\n+--------------+-------------------------------------------------------+---------+\n| ``\'%\'`` | No argument is converted, results in a ``\'%\'`` | |\n| | character in the result. | |\n+--------------+-------------------------------------------------------+---------+\n\nNotes:\n\n1. The alternate form causes a leading zero (``\'0\'``) to be inserted\n between left-hand padding and the formatting of the number if the\n leading character of the result is not already a zero.\n\n2. The alternate form causes a leading ``\'0x\'`` or ``\'0X\'`` (depending\n on whether the ``\'x\'`` or ``\'X\'`` format was used) to be inserted\n between left-hand padding and the formatting of the number if the\n leading character of the result is not already a zero.\n\n3. The alternate form causes the result to always contain a decimal\n point, even if no digits follow it.\n\n The precision determines the number of digits after the decimal\n point and defaults to 6.\n\n4. The alternate form causes the result to always contain a decimal\n point, and trailing zeroes are not removed as they would otherwise\n be.\n\n The precision determines the number of significant digits before\n and after the decimal point and defaults to 6.\n\n5. The ``%r`` conversion was added in Python 2.0.\n\n The precision determines the maximal number of characters used.\n\n6. If the object or format provided is a ``unicode`` string, the\n resulting string will also be ``unicode``.\n\n The precision determines the maximal number of characters used.\n\n7. See **PEP 237**.\n\nSince Python strings have an explicit length, ``%s`` conversions do\nnot assume that ``\'\\0\'`` is the end of the string.\n\nChanged in version 2.7: ``%f`` conversions for numbers whose absolute\nvalue is over 1e50 are no longer replaced by ``%g`` conversions.\n\nAdditional string operations are defined in standard modules\n``string`` and ``re``.\n\n\nXRange Type\n===========\n\nThe ``xrange`` type is an immutable sequence which is commonly used\nfor looping. The advantage of the ``xrange`` type is that an\n``xrange`` object will always take the same amount of memory, no\nmatter the size of the range it represents. There are no consistent\nperformance advantages.\n\nXRange objects have very little behavior: they only support indexing,\niteration, and the ``len()`` function.\n\n\nMutable Sequence Types\n======================\n\nList objects support additional operations that allow in-place\nmodification of the object. Other mutable sequence types (when added\nto the language) should also support these operations. Strings and\ntuples are immutable sequence types: such objects cannot be modified\nonce created. The following operations are defined on mutable sequence\ntypes (where *x* is an arbitrary object):\n\n+--------------------------------+----------------------------------+-----------------------+\n| Operation | Result | Notes |\n+================================+==================================+=======================+\n| ``s[i] = x`` | item *i* of *s* is replaced by | |\n| | *x* | |\n+--------------------------------+----------------------------------+-----------------------+\n| ``s[i:j] = t`` | slice of *s* from *i* to *j* is | |\n| | replaced by the contents of the | |\n| | iterable *t* | |\n+--------------------------------+----------------------------------+-----------------------+\n| ``del s[i:j]`` | same as ``s[i:j] = []`` | |\n+--------------------------------+----------------------------------+-----------------------+\n| ``s[i:j:k] = t`` | the elements of ``s[i:j:k]`` are | (1) |\n| | replaced by those of *t* | |\n+--------------------------------+----------------------------------+-----------------------+\n| ``del s[i:j:k]`` | removes the elements of | |\n| | ``s[i:j:k]`` from the list | |\n+--------------------------------+----------------------------------+-----------------------+\n| ``s.append(x)`` | same as ``s[len(s):len(s)] = | (2) |\n| | [x]`` | |\n+--------------------------------+----------------------------------+-----------------------+\n| ``s.extend(x)`` | same as ``s[len(s):len(s)] = x`` | (3) |\n+--------------------------------+----------------------------------+-----------------------+\n| ``s.count(x)`` | return number of *i*\'s for which | |\n| | ``s[i] == x`` | |\n+--------------------------------+----------------------------------+-----------------------+\n| ``s.index(x[, i[, j]])`` | return smallest *k* such that | (4) |\n| | ``s[k] == x`` and ``i <= k < j`` | |\n+--------------------------------+----------------------------------+-----------------------+\n| ``s.insert(i, x)`` | same as ``s[i:i] = [x]`` | (5) |\n+--------------------------------+----------------------------------+-----------------------+\n| ``s.pop([i])`` | same as ``x = s[i]; del s[i]; | (6) |\n| | return x`` | |\n+--------------------------------+----------------------------------+-----------------------+\n| ``s.remove(x)`` | same as ``del s[s.index(x)]`` | (4) |\n+--------------------------------+----------------------------------+-----------------------+\n| ``s.reverse()`` | reverses the items of *s* in | (7) |\n| | place | |\n+--------------------------------+----------------------------------+-----------------------+\n| ``s.sort([cmp[, key[, | sort the items of *s* in place | (7)(8)(9)(10) |\n| reverse]]])`` | | |\n+--------------------------------+----------------------------------+-----------------------+\n\nNotes:\n\n1. *t* must have the same length as the slice it is replacing.\n\n2. The C implementation of Python has historically accepted multiple\n parameters and implicitly joined them into a tuple; this no longer\n works in Python 2.0. Use of this misfeature has been deprecated\n since Python 1.4.\n\n3. *x* can be any iterable object.\n\n4. Raises ``ValueError`` when *x* is not found in *s*. When a negative\n index is passed as the second or third parameter to the ``index()``\n method, the list length is added, as for slice indices. If it is\n still negative, it is truncated to zero, as for slice indices.\n\n Changed in version 2.3: Previously, ``index()`` didn\'t have\n arguments for specifying start and stop positions.\n\n5. When a negative index is passed as the first parameter to the\n ``insert()`` method, the list length is added, as for slice\n indices. If it is still negative, it is truncated to zero, as for\n slice indices.\n\n Changed in version 2.3: Previously, all negative indices were\n truncated to zero.\n\n6. The ``pop()`` method is only supported by the list and array types.\n The optional argument *i* defaults to ``-1``, so that by default\n the last item is removed and returned.\n\n7. The ``sort()`` and ``reverse()`` methods modify the list in place\n for economy of space when sorting or reversing a large list. To\n remind you that they operate by side effect, they don\'t return the\n sorted or reversed list.\n\n8. The ``sort()`` method takes optional arguments for controlling the\n comparisons.\n\n *cmp* specifies a custom comparison function of two arguments (list\n items) which should return a negative, zero or positive number\n depending on whether the first argument is considered smaller than,\n equal to, or larger than the second argument: ``cmp=lambda x,y:\n cmp(x.lower(), y.lower())``. The default value is ``None``.\n\n *key* specifies a function of one argument that is used to extract\n a comparison key from each list element: ``key=str.lower``. The\n default value is ``None``.\n\n *reverse* is a boolean value. If set to ``True``, then the list\n elements are sorted as if each comparison were reversed.\n\n In general, the *key* and *reverse* conversion processes are much\n faster than specifying an equivalent *cmp* function. This is\n because *cmp* is called multiple times for each list element while\n *key* and *reverse* touch each element only once. Use\n ``functools.cmp_to_key()`` to convert an old-style *cmp* function\n to a *key* function.\n\n Changed in version 2.3: Support for ``None`` as an equivalent to\n omitting *cmp* was added.\n\n Changed in version 2.4: Support for *key* and *reverse* was added.\n\n9. Starting with Python 2.3, the ``sort()`` method is guaranteed to be\n stable. A sort is stable if it guarantees not to change the\n relative order of elements that compare equal --- this is helpful\n for sorting in multiple passes (for example, sort by department,\n then by salary grade).\n\n10. **CPython implementation detail:** While a list is being sorted,\n the effect of attempting to mutate, or even inspect, the list is\n undefined. The C implementation of Python 2.3 and newer makes the\n list appear empty for the duration, and raises ``ValueError`` if\n it can detect that the list has been mutated during a sort.\n', + 'typesseq': u'\nSequence Types --- ``str``, ``unicode``, ``list``, ``tuple``, ``buffer``, ``xrange``\n************************************************************************************\n\nThere are six sequence types: strings, Unicode strings, lists, tuples,\nbuffers, and xrange objects.\n\nFor other containers see the built in ``dict`` and ``set`` classes,\nand the ``collections`` module.\n\nString literals are written in single or double quotes: ``\'xyzzy\'``,\n``"frobozz"``. See *String literals* for more about string literals.\nUnicode strings are much like strings, but are specified in the syntax\nusing a preceding ``\'u\'`` character: ``u\'abc\'``, ``u"def"``. In\naddition to the functionality described here, there are also string-\nspecific methods described in the *String Methods* section. Lists are\nconstructed with square brackets, separating items with commas: ``[a,\nb, c]``. Tuples are constructed by the comma operator (not within\nsquare brackets), with or without enclosing parentheses, but an empty\ntuple must have the enclosing parentheses, such as ``a, b, c`` or\n``()``. A single item tuple must have a trailing comma, such as\n``(d,)``.\n\nBuffer objects are not directly supported by Python syntax, but can be\ncreated by calling the built-in function ``buffer()``. They don\'t\nsupport concatenation or repetition.\n\nObjects of type xrange are similar to buffers in that there is no\nspecific syntax to create them, but they are created using the\n``xrange()`` function. They don\'t support slicing, concatenation or\nrepetition, and using ``in``, ``not in``, ``min()`` or ``max()`` on\nthem is inefficient.\n\nMost sequence types support the following operations. The ``in`` and\n``not in`` operations have the same priorities as the comparison\noperations. The ``+`` and ``*`` operations have the same priority as\nthe corresponding numeric operations. [3] Additional methods are\nprovided for *Mutable Sequence Types*.\n\nThis table lists the sequence operations sorted in ascending priority\n(operations in the same box have the same priority). In the table,\n*s* and *t* are sequences of the same type; *n*, *i* and *j* are\nintegers:\n\n+--------------------+----------------------------------+------------+\n| Operation | Result | Notes |\n+====================+==================================+============+\n| ``x in s`` | ``True`` if an item of *s* is | (1) |\n| | equal to *x*, else ``False`` | |\n+--------------------+----------------------------------+------------+\n| ``x not in s`` | ``False`` if an item of *s* is | (1) |\n| | equal to *x*, else ``True`` | |\n+--------------------+----------------------------------+------------+\n| ``s + t`` | the concatenation of *s* and *t* | (6) |\n+--------------------+----------------------------------+------------+\n| ``s * n, n * s`` | *n* shallow copies of *s* | (2) |\n| | concatenated | |\n+--------------------+----------------------------------+------------+\n| ``s[i]`` | *i*\'th item of *s*, origin 0 | (3) |\n+--------------------+----------------------------------+------------+\n| ``s[i:j]`` | slice of *s* from *i* to *j* | (3)(4) |\n+--------------------+----------------------------------+------------+\n| ``s[i:j:k]`` | slice of *s* from *i* to *j* | (3)(5) |\n| | with step *k* | |\n+--------------------+----------------------------------+------------+\n| ``len(s)`` | length of *s* | |\n+--------------------+----------------------------------+------------+\n| ``min(s)`` | smallest item of *s* | |\n+--------------------+----------------------------------+------------+\n| ``max(s)`` | largest item of *s* | |\n+--------------------+----------------------------------+------------+\n\nSequence types also support comparisons. In particular, tuples and\nlists are compared lexicographically by comparing corresponding\nelements. This means that to compare equal, every element must compare\nequal and the two sequences must be of the same type and have the same\nlength. (For full details see *Comparisons* in the language\nreference.)\n\nNotes:\n\n1. When *s* is a string or Unicode string object the ``in`` and ``not\n in`` operations act like a substring test. In Python versions\n before 2.3, *x* had to be a string of length 1. In Python 2.3 and\n beyond, *x* may be a string of any length.\n\n2. Values of *n* less than ``0`` are treated as ``0`` (which yields an\n empty sequence of the same type as *s*). Note also that the copies\n are shallow; nested structures are not copied. This often haunts\n new Python programmers; consider:\n\n >>> lists = [[]] * 3\n >>> lists\n [[], [], []]\n >>> lists[0].append(3)\n >>> lists\n [[3], [3], [3]]\n\n What has happened is that ``[[]]`` is a one-element list containing\n an empty list, so all three elements of ``[[]] * 3`` are (pointers\n to) this single empty list. Modifying any of the elements of\n ``lists`` modifies this single list. You can create a list of\n different lists this way:\n\n >>> lists = [[] for i in range(3)]\n >>> lists[0].append(3)\n >>> lists[1].append(5)\n >>> lists[2].append(7)\n >>> lists\n [[3], [5], [7]]\n\n3. If *i* or *j* is negative, the index is relative to the end of the\n string: ``len(s) + i`` or ``len(s) + j`` is substituted. But note\n that ``-0`` is still ``0``.\n\n4. The slice of *s* from *i* to *j* is defined as the sequence of\n items with index *k* such that ``i <= k < j``. If *i* or *j* is\n greater than ``len(s)``, use ``len(s)``. If *i* is omitted or\n ``None``, use ``0``. If *j* is omitted or ``None``, use\n ``len(s)``. If *i* is greater than or equal to *j*, the slice is\n empty.\n\n5. The slice of *s* from *i* to *j* with step *k* is defined as the\n sequence of items with index ``x = i + n*k`` such that ``0 <= n <\n (j-i)/k``. In other words, the indices are ``i``, ``i+k``,\n ``i+2*k``, ``i+3*k`` and so on, stopping when *j* is reached (but\n never including *j*). If *i* or *j* is greater than ``len(s)``,\n use ``len(s)``. If *i* or *j* are omitted or ``None``, they become\n "end" values (which end depends on the sign of *k*). Note, *k*\n cannot be zero. If *k* is ``None``, it is treated like ``1``.\n\n6. **CPython implementation detail:** If *s* and *t* are both strings,\n some Python implementations such as CPython can usually perform an\n in-place optimization for assignments of the form ``s = s + t`` or\n ``s += t``. When applicable, this optimization makes quadratic\n run-time much less likely. This optimization is both version and\n implementation dependent. For performance sensitive code, it is\n preferable to use the ``str.join()`` method which assures\n consistent linear concatenation performance across versions and\n implementations.\n\n Changed in version 2.4: Formerly, string concatenation never\n occurred in-place.\n\n\nString Methods\n==============\n\nBelow are listed the string methods which both 8-bit strings and\nUnicode objects support.\n\nIn addition, Python\'s strings support the sequence type methods\ndescribed in the *Sequence Types --- str, unicode, list, tuple,\nbuffer, xrange* section. To output formatted strings use template\nstrings or the ``%`` operator described in the *String Formatting\nOperations* section. Also, see the ``re`` module for string functions\nbased on regular expressions.\n\nstr.capitalize()\n\n Return a copy of the string with only its first character\n capitalized.\n\n For 8-bit strings, this method is locale-dependent.\n\nstr.center(width[, fillchar])\n\n Return centered in a string of length *width*. Padding is done\n using the specified *fillchar* (default is a space).\n\n Changed in version 2.4: Support for the *fillchar* argument.\n\nstr.count(sub[, start[, end]])\n\n Return the number of non-overlapping occurrences of substring *sub*\n in the range [*start*, *end*]. Optional arguments *start* and\n *end* are interpreted as in slice notation.\n\nstr.decode([encoding[, errors]])\n\n Decodes the string using the codec registered for *encoding*.\n *encoding* defaults to the default string encoding. *errors* may\n be given to set a different error handling scheme. The default is\n ``\'strict\'``, meaning that encoding errors raise ``UnicodeError``.\n Other possible values are ``\'ignore\'``, ``\'replace\'`` and any other\n name registered via ``codecs.register_error()``, see section *Codec\n Base Classes*.\n\n New in version 2.2.\n\n Changed in version 2.3: Support for other error handling schemes\n added.\n\n Changed in version 2.7: Support for keyword arguments added.\n\nstr.encode([encoding[, errors]])\n\n Return an encoded version of the string. Default encoding is the\n current default string encoding. *errors* may be given to set a\n different error handling scheme. The default for *errors* is\n ``\'strict\'``, meaning that encoding errors raise a\n ``UnicodeError``. Other possible values are ``\'ignore\'``,\n ``\'replace\'``, ``\'xmlcharrefreplace\'``, ``\'backslashreplace\'`` and\n any other name registered via ``codecs.register_error()``, see\n section *Codec Base Classes*. For a list of possible encodings, see\n section *Standard Encodings*.\n\n New in version 2.0.\n\n Changed in version 2.3: Support for ``\'xmlcharrefreplace\'`` and\n ``\'backslashreplace\'`` and other error handling schemes added.\n\n Changed in version 2.7: Support for keyword arguments added.\n\nstr.endswith(suffix[, start[, end]])\n\n Return ``True`` if the string ends with the specified *suffix*,\n otherwise return ``False``. *suffix* can also be a tuple of\n suffixes to look for. With optional *start*, test beginning at\n that position. With optional *end*, stop comparing at that\n position.\n\n Changed in version 2.5: Accept tuples as *suffix*.\n\nstr.expandtabs([tabsize])\n\n Return a copy of the string where all tab characters are replaced\n by one or more spaces, depending on the current column and the\n given tab size. The column number is reset to zero after each\n newline occurring in the string. If *tabsize* is not given, a tab\n size of ``8`` characters is assumed. This doesn\'t understand other\n non-printing characters or escape sequences.\n\nstr.find(sub[, start[, end]])\n\n Return the lowest index in the string where substring *sub* is\n found, such that *sub* is contained in the slice ``s[start:end]``.\n Optional arguments *start* and *end* are interpreted as in slice\n notation. Return ``-1`` if *sub* is not found.\n\nstr.format(*args, **kwargs)\n\n Perform a string formatting operation. The string on which this\n method is called can contain literal text or replacement fields\n delimited by braces ``{}``. Each replacement field contains either\n the numeric index of a positional argument, or the name of a\n keyword argument. Returns a copy of the string where each\n replacement field is replaced with the string value of the\n corresponding argument.\n\n >>> "The sum of 1 + 2 is {0}".format(1+2)\n \'The sum of 1 + 2 is 3\'\n\n See *Format String Syntax* for a description of the various\n formatting options that can be specified in format strings.\n\n This method of string formatting is the new standard in Python 3.0,\n and should be preferred to the ``%`` formatting described in\n *String Formatting Operations* in new code.\n\n New in version 2.6.\n\nstr.index(sub[, start[, end]])\n\n Like ``find()``, but raise ``ValueError`` when the substring is not\n found.\n\nstr.isalnum()\n\n Return true if all characters in the string are alphanumeric and\n there is at least one character, false otherwise.\n\n For 8-bit strings, this method is locale-dependent.\n\nstr.isalpha()\n\n Return true if all characters in the string are alphabetic and\n there is at least one character, false otherwise.\n\n For 8-bit strings, this method is locale-dependent.\n\nstr.isdigit()\n\n Return true if all characters in the string are digits and there is\n at least one character, false otherwise.\n\n For 8-bit strings, this method is locale-dependent.\n\nstr.islower()\n\n Return true if all cased characters in the string are lowercase and\n there is at least one cased character, false otherwise.\n\n For 8-bit strings, this method is locale-dependent.\n\nstr.isspace()\n\n Return true if there are only whitespace characters in the string\n and there is at least one character, false otherwise.\n\n For 8-bit strings, this method is locale-dependent.\n\nstr.istitle()\n\n Return true if the string is a titlecased string and there is at\n least one character, for example uppercase characters may only\n follow uncased characters and lowercase characters only cased ones.\n Return false otherwise.\n\n For 8-bit strings, this method is locale-dependent.\n\nstr.isupper()\n\n Return true if all cased characters in the string are uppercase and\n there is at least one cased character, false otherwise.\n\n For 8-bit strings, this method is locale-dependent.\n\nstr.join(iterable)\n\n Return a string which is the concatenation of the strings in the\n *iterable* *iterable*. The separator between elements is the\n string providing this method.\n\nstr.ljust(width[, fillchar])\n\n Return the string left justified in a string of length *width*.\n Padding is done using the specified *fillchar* (default is a\n space). The original string is returned if *width* is less than\n ``len(s)``.\n\n Changed in version 2.4: Support for the *fillchar* argument.\n\nstr.lower()\n\n Return a copy of the string converted to lowercase.\n\n For 8-bit strings, this method is locale-dependent.\n\nstr.lstrip([chars])\n\n Return a copy of the string with leading characters removed. The\n *chars* argument is a string specifying the set of characters to be\n removed. If omitted or ``None``, the *chars* argument defaults to\n removing whitespace. The *chars* argument is not a prefix; rather,\n all combinations of its values are stripped:\n\n >>> \' spacious \'.lstrip()\n \'spacious \'\n >>> \'www.example.com\'.lstrip(\'cmowz.\')\n \'example.com\'\n\n Changed in version 2.2.2: Support for the *chars* argument.\n\nstr.partition(sep)\n\n Split the string at the first occurrence of *sep*, and return a\n 3-tuple containing the part before the separator, the separator\n itself, and the part after the separator. If the separator is not\n found, return a 3-tuple containing the string itself, followed by\n two empty strings.\n\n New in version 2.5.\n\nstr.replace(old, new[, count])\n\n Return a copy of the string with all occurrences of substring *old*\n replaced by *new*. If the optional argument *count* is given, only\n the first *count* occurrences are replaced.\n\nstr.rfind(sub[, start[, end]])\n\n Return the highest index in the string where substring *sub* is\n found, such that *sub* is contained within ``s[start:end]``.\n Optional arguments *start* and *end* are interpreted as in slice\n notation. Return ``-1`` on failure.\n\nstr.rindex(sub[, start[, end]])\n\n Like ``rfind()`` but raises ``ValueError`` when the substring *sub*\n is not found.\n\nstr.rjust(width[, fillchar])\n\n Return the string right justified in a string of length *width*.\n Padding is done using the specified *fillchar* (default is a\n space). The original string is returned if *width* is less than\n ``len(s)``.\n\n Changed in version 2.4: Support for the *fillchar* argument.\n\nstr.rpartition(sep)\n\n Split the string at the last occurrence of *sep*, and return a\n 3-tuple containing the part before the separator, the separator\n itself, and the part after the separator. If the separator is not\n found, return a 3-tuple containing two empty strings, followed by\n the string itself.\n\n New in version 2.5.\n\nstr.rsplit([sep[, maxsplit]])\n\n Return a list of the words in the string, using *sep* as the\n delimiter string. If *maxsplit* is given, at most *maxsplit* splits\n are done, the *rightmost* ones. If *sep* is not specified or\n ``None``, any whitespace string is a separator. Except for\n splitting from the right, ``rsplit()`` behaves like ``split()``\n which is described in detail below.\n\n New in version 2.4.\n\nstr.rstrip([chars])\n\n Return a copy of the string with trailing characters removed. The\n *chars* argument is a string specifying the set of characters to be\n removed. If omitted or ``None``, the *chars* argument defaults to\n removing whitespace. The *chars* argument is not a suffix; rather,\n all combinations of its values are stripped:\n\n >>> \' spacious \'.rstrip()\n \' spacious\'\n >>> \'mississippi\'.rstrip(\'ipz\')\n \'mississ\'\n\n Changed in version 2.2.2: Support for the *chars* argument.\n\nstr.split([sep[, maxsplit]])\n\n Return a list of the words in the string, using *sep* as the\n delimiter string. If *maxsplit* is given, at most *maxsplit*\n splits are done (thus, the list will have at most ``maxsplit+1``\n elements). If *maxsplit* is not specified, then there is no limit\n on the number of splits (all possible splits are made).\n\n If *sep* is given, consecutive delimiters are not grouped together\n and are deemed to delimit empty strings (for example,\n ``\'1,,2\'.split(\',\')`` returns ``[\'1\', \'\', \'2\']``). The *sep*\n argument may consist of multiple characters (for example,\n ``\'1<>2<>3\'.split(\'<>\')`` returns ``[\'1\', \'2\', \'3\']``). Splitting\n an empty string with a specified separator returns ``[\'\']``.\n\n If *sep* is not specified or is ``None``, a different splitting\n algorithm is applied: runs of consecutive whitespace are regarded\n as a single separator, and the result will contain no empty strings\n at the start or end if the string has leading or trailing\n whitespace. Consequently, splitting an empty string or a string\n consisting of just whitespace with a ``None`` separator returns\n ``[]``.\n\n For example, ``\' 1 2 3 \'.split()`` returns ``[\'1\', \'2\', \'3\']``,\n and ``\' 1 2 3 \'.split(None, 1)`` returns ``[\'1\', \'2 3 \']``.\n\nstr.splitlines([keepends])\n\n Return a list of the lines in the string, breaking at line\n boundaries. Line breaks are not included in the resulting list\n unless *keepends* is given and true.\n\nstr.startswith(prefix[, start[, end]])\n\n Return ``True`` if string starts with the *prefix*, otherwise\n return ``False``. *prefix* can also be a tuple of prefixes to look\n for. With optional *start*, test string beginning at that\n position. With optional *end*, stop comparing string at that\n position.\n\n Changed in version 2.5: Accept tuples as *prefix*.\n\nstr.strip([chars])\n\n Return a copy of the string with the leading and trailing\n characters removed. The *chars* argument is a string specifying the\n set of characters to be removed. If omitted or ``None``, the\n *chars* argument defaults to removing whitespace. The *chars*\n argument is not a prefix or suffix; rather, all combinations of its\n values are stripped:\n\n >>> \' spacious \'.strip()\n \'spacious\'\n >>> \'www.example.com\'.strip(\'cmowz.\')\n \'example\'\n\n Changed in version 2.2.2: Support for the *chars* argument.\n\nstr.swapcase()\n\n Return a copy of the string with uppercase characters converted to\n lowercase and vice versa.\n\n For 8-bit strings, this method is locale-dependent.\n\nstr.title()\n\n Return a titlecased version of the string where words start with an\n uppercase character and the remaining characters are lowercase.\n\n The algorithm uses a simple language-independent definition of a\n word as groups of consecutive letters. The definition works in\n many contexts but it means that apostrophes in contractions and\n possessives form word boundaries, which may not be the desired\n result:\n\n >>> "they\'re bill\'s friends from the UK".title()\n "They\'Re Bill\'S Friends From The Uk"\n\n A workaround for apostrophes can be constructed using regular\n expressions:\n\n >>> import re\n >>> def titlecase(s):\n return re.sub(r"[A-Za-z]+(\'[A-Za-z]+)?",\n lambda mo: mo.group(0)[0].upper() +\n mo.group(0)[1:].lower(),\n s)\n\n >>> titlecase("they\'re bill\'s friends.")\n "They\'re Bill\'s Friends."\n\n For 8-bit strings, this method is locale-dependent.\n\nstr.translate(table[, deletechars])\n\n Return a copy of the string where all characters occurring in the\n optional argument *deletechars* are removed, and the remaining\n characters have been mapped through the given translation table,\n which must be a string of length 256.\n\n You can use the ``maketrans()`` helper function in the ``string``\n module to create a translation table. For string objects, set the\n *table* argument to ``None`` for translations that only delete\n characters:\n\n >>> \'read this short text\'.translate(None, \'aeiou\')\n \'rd ths shrt txt\'\n\n New in version 2.6: Support for a ``None`` *table* argument.\n\n For Unicode objects, the ``translate()`` method does not accept the\n optional *deletechars* argument. Instead, it returns a copy of the\n *s* where all characters have been mapped through the given\n translation table which must be a mapping of Unicode ordinals to\n Unicode ordinals, Unicode strings or ``None``. Unmapped characters\n are left untouched. Characters mapped to ``None`` are deleted.\n Note, a more flexible approach is to create a custom character\n mapping codec using the ``codecs`` module (see ``encodings.cp1251``\n for an example).\n\nstr.upper()\n\n Return a copy of the string converted to uppercase.\n\n For 8-bit strings, this method is locale-dependent.\n\nstr.zfill(width)\n\n Return the numeric string left filled with zeros in a string of\n length *width*. A sign prefix is handled correctly. The original\n string is returned if *width* is less than ``len(s)``.\n\n New in version 2.2.2.\n\nThe following methods are present only on unicode objects:\n\nunicode.isnumeric()\n\n Return ``True`` if there are only numeric characters in S,\n ``False`` otherwise. Numeric characters include digit characters,\n and all characters that have the Unicode numeric value property,\n e.g. U+2155, VULGAR FRACTION ONE FIFTH.\n\nunicode.isdecimal()\n\n Return ``True`` if there are only decimal characters in S,\n ``False`` otherwise. Decimal characters include digit characters,\n and all characters that that can be used to form decimal-radix\n numbers, e.g. U+0660, ARABIC-INDIC DIGIT ZERO.\n\n\nString Formatting Operations\n============================\n\nString and Unicode objects have one unique built-in operation: the\n``%`` operator (modulo). This is also known as the string\n*formatting* or *interpolation* operator. Given ``format % values``\n(where *format* is a string or Unicode object), ``%`` conversion\nspecifications in *format* are replaced with zero or more elements of\n*values*. The effect is similar to the using ``sprintf()`` in the C\nlanguage. If *format* is a Unicode object, or if any of the objects\nbeing converted using the ``%s`` conversion are Unicode objects, the\nresult will also be a Unicode object.\n\nIf *format* requires a single argument, *values* may be a single non-\ntuple object. [4] Otherwise, *values* must be a tuple with exactly\nthe number of items specified by the format string, or a single\nmapping object (for example, a dictionary).\n\nA conversion specifier contains two or more characters and has the\nfollowing components, which must occur in this order:\n\n1. The ``\'%\'`` character, which marks the start of the specifier.\n\n2. Mapping key (optional), consisting of a parenthesised sequence of\n characters (for example, ``(somename)``).\n\n3. Conversion flags (optional), which affect the result of some\n conversion types.\n\n4. Minimum field width (optional). If specified as an ``\'*\'``\n (asterisk), the actual width is read from the next element of the\n tuple in *values*, and the object to convert comes after the\n minimum field width and optional precision.\n\n5. Precision (optional), given as a ``\'.\'`` (dot) followed by the\n precision. If specified as ``\'*\'`` (an asterisk), the actual width\n is read from the next element of the tuple in *values*, and the\n value to convert comes after the precision.\n\n6. Length modifier (optional).\n\n7. Conversion type.\n\nWhen the right argument is a dictionary (or other mapping type), then\nthe formats in the string *must* include a parenthesised mapping key\ninto that dictionary inserted immediately after the ``\'%\'`` character.\nThe mapping key selects the value to be formatted from the mapping.\nFor example:\n\n>>> print \'%(language)s has %(#)03d quote types.\' % \\\n... {\'language\': "Python", "#": 2}\nPython has 002 quote types.\n\nIn this case no ``*`` specifiers may occur in a format (since they\nrequire a sequential parameter list).\n\nThe conversion flag characters are:\n\n+-----------+-----------------------------------------------------------------------+\n| Flag | Meaning |\n+===========+=======================================================================+\n| ``\'#\'`` | The value conversion will use the "alternate form" (where defined |\n| | below). |\n+-----------+-----------------------------------------------------------------------+\n| ``\'0\'`` | The conversion will be zero padded for numeric values. |\n+-----------+-----------------------------------------------------------------------+\n| ``\'-\'`` | The converted value is left adjusted (overrides the ``\'0\'`` |\n| | conversion if both are given). |\n+-----------+-----------------------------------------------------------------------+\n| ``\' \'`` | (a space) A blank should be left before a positive number (or empty |\n| | string) produced by a signed conversion. |\n+-----------+-----------------------------------------------------------------------+\n| ``\'+\'`` | A sign character (``\'+\'`` or ``\'-\'``) will precede the conversion |\n| | (overrides a "space" flag). |\n+-----------+-----------------------------------------------------------------------+\n\nA length modifier (``h``, ``l``, or ``L``) may be present, but is\nignored as it is not necessary for Python -- so e.g. ``%ld`` is\nidentical to ``%d``.\n\nThe conversion types are:\n\n+--------------+-------------------------------------------------------+---------+\n| Conversion | Meaning | Notes |\n+==============+=======================================================+=========+\n| ``\'d\'`` | Signed integer decimal. | |\n+--------------+-------------------------------------------------------+---------+\n| ``\'i\'`` | Signed integer decimal. | |\n+--------------+-------------------------------------------------------+---------+\n| ``\'o\'`` | Signed octal value. | (1) |\n+--------------+-------------------------------------------------------+---------+\n| ``\'u\'`` | Obsolete type -- it is identical to ``\'d\'``. | (7) |\n+--------------+-------------------------------------------------------+---------+\n| ``\'x\'`` | Signed hexadecimal (lowercase). | (2) |\n+--------------+-------------------------------------------------------+---------+\n| ``\'X\'`` | Signed hexadecimal (uppercase). | (2) |\n+--------------+-------------------------------------------------------+---------+\n| ``\'e\'`` | Floating point exponential format (lowercase). | (3) |\n+--------------+-------------------------------------------------------+---------+\n| ``\'E\'`` | Floating point exponential format (uppercase). | (3) |\n+--------------+-------------------------------------------------------+---------+\n| ``\'f\'`` | Floating point decimal format. | (3) |\n+--------------+-------------------------------------------------------+---------+\n| ``\'F\'`` | Floating point decimal format. | (3) |\n+--------------+-------------------------------------------------------+---------+\n| ``\'g\'`` | Floating point format. Uses lowercase exponential | (4) |\n| | format if exponent is less than -4 or not less than | |\n| | precision, decimal format otherwise. | |\n+--------------+-------------------------------------------------------+---------+\n| ``\'G\'`` | Floating point format. Uses uppercase exponential | (4) |\n| | format if exponent is less than -4 or not less than | |\n| | precision, decimal format otherwise. | |\n+--------------+-------------------------------------------------------+---------+\n| ``\'c\'`` | Single character (accepts integer or single character | |\n| | string). | |\n+--------------+-------------------------------------------------------+---------+\n| ``\'r\'`` | String (converts any Python object using ``repr()``). | (5) |\n+--------------+-------------------------------------------------------+---------+\n| ``\'s\'`` | String (converts any Python object using ``str()``). | (6) |\n+--------------+-------------------------------------------------------+---------+\n| ``\'%\'`` | No argument is converted, results in a ``\'%\'`` | |\n| | character in the result. | |\n+--------------+-------------------------------------------------------+---------+\n\nNotes:\n\n1. The alternate form causes a leading zero (``\'0\'``) to be inserted\n between left-hand padding and the formatting of the number if the\n leading character of the result is not already a zero.\n\n2. The alternate form causes a leading ``\'0x\'`` or ``\'0X\'`` (depending\n on whether the ``\'x\'`` or ``\'X\'`` format was used) to be inserted\n between left-hand padding and the formatting of the number if the\n leading character of the result is not already a zero.\n\n3. The alternate form causes the result to always contain a decimal\n point, even if no digits follow it.\n\n The precision determines the number of digits after the decimal\n point and defaults to 6.\n\n4. The alternate form causes the result to always contain a decimal\n point, and trailing zeroes are not removed as they would otherwise\n be.\n\n The precision determines the number of significant digits before\n and after the decimal point and defaults to 6.\n\n5. The ``%r`` conversion was added in Python 2.0.\n\n The precision determines the maximal number of characters used.\n\n6. If the object or format provided is a ``unicode`` string, the\n resulting string will also be ``unicode``.\n\n The precision determines the maximal number of characters used.\n\n7. See **PEP 237**.\n\nSince Python strings have an explicit length, ``%s`` conversions do\nnot assume that ``\'\\0\'`` is the end of the string.\n\nChanged in version 2.7: ``%f`` conversions for numbers whose absolute\nvalue is over 1e50 are no longer replaced by ``%g`` conversions.\n\nAdditional string operations are defined in standard modules\n``string`` and ``re``.\n\n\nXRange Type\n===========\n\nThe ``xrange`` type is an immutable sequence which is commonly used\nfor looping. The advantage of the ``xrange`` type is that an\n``xrange`` object will always take the same amount of memory, no\nmatter the size of the range it represents. There are no consistent\nperformance advantages.\n\nXRange objects have very little behavior: they only support indexing,\niteration, and the ``len()`` function.\n\n\nMutable Sequence Types\n======================\n\nList objects support additional operations that allow in-place\nmodification of the object. Other mutable sequence types (when added\nto the language) should also support these operations. Strings and\ntuples are immutable sequence types: such objects cannot be modified\nonce created. The following operations are defined on mutable sequence\ntypes (where *x* is an arbitrary object):\n\n+--------------------------------+----------------------------------+-----------------------+\n| Operation | Result | Notes |\n+================================+==================================+=======================+\n| ``s[i] = x`` | item *i* of *s* is replaced by | |\n| | *x* | |\n+--------------------------------+----------------------------------+-----------------------+\n| ``s[i:j] = t`` | slice of *s* from *i* to *j* is | |\n| | replaced by the contents of the | |\n| | iterable *t* | |\n+--------------------------------+----------------------------------+-----------------------+\n| ``del s[i:j]`` | same as ``s[i:j] = []`` | |\n+--------------------------------+----------------------------------+-----------------------+\n| ``s[i:j:k] = t`` | the elements of ``s[i:j:k]`` are | (1) |\n| | replaced by those of *t* | |\n+--------------------------------+----------------------------------+-----------------------+\n| ``del s[i:j:k]`` | removes the elements of | |\n| | ``s[i:j:k]`` from the list | |\n+--------------------------------+----------------------------------+-----------------------+\n| ``s.append(x)`` | same as ``s[len(s):len(s)] = | (2) |\n| | [x]`` | |\n+--------------------------------+----------------------------------+-----------------------+\n| ``s.extend(x)`` | same as ``s[len(s):len(s)] = x`` | (3) |\n+--------------------------------+----------------------------------+-----------------------+\n| ``s.count(x)`` | return number of *i*\'s for which | |\n| | ``s[i] == x`` | |\n+--------------------------------+----------------------------------+-----------------------+\n| ``s.index(x[, i[, j]])`` | return smallest *k* such that | (4) |\n| | ``s[k] == x`` and ``i <= k < j`` | |\n+--------------------------------+----------------------------------+-----------------------+\n| ``s.insert(i, x)`` | same as ``s[i:i] = [x]`` | (5) |\n+--------------------------------+----------------------------------+-----------------------+\n| ``s.pop([i])`` | same as ``x = s[i]; del s[i]; | (6) |\n| | return x`` | |\n+--------------------------------+----------------------------------+-----------------------+\n| ``s.remove(x)`` | same as ``del s[s.index(x)]`` | (4) |\n+--------------------------------+----------------------------------+-----------------------+\n| ``s.reverse()`` | reverses the items of *s* in | (7) |\n| | place | |\n+--------------------------------+----------------------------------+-----------------------+\n| ``s.sort([cmp[, key[, | sort the items of *s* in place | (7)(8)(9)(10) |\n| reverse]]])`` | | |\n+--------------------------------+----------------------------------+-----------------------+\n\nNotes:\n\n1. *t* must have the same length as the slice it is replacing.\n\n2. The C implementation of Python has historically accepted multiple\n parameters and implicitly joined them into a tuple; this no longer\n works in Python 2.0. Use of this misfeature has been deprecated\n since Python 1.4.\n\n3. *x* can be any iterable object.\n\n4. Raises ``ValueError`` when *x* is not found in *s*. When a negative\n index is passed as the second or third parameter to the ``index()``\n method, the list length is added, as for slice indices. If it is\n still negative, it is truncated to zero, as for slice indices.\n\n Changed in version 2.3: Previously, ``index()`` didn\'t have\n arguments for specifying start and stop positions.\n\n5. When a negative index is passed as the first parameter to the\n ``insert()`` method, the list length is added, as for slice\n indices. If it is still negative, it is truncated to zero, as for\n slice indices.\n\n Changed in version 2.3: Previously, all negative indices were\n truncated to zero.\n\n6. The ``pop()`` method is only supported by the list and array types.\n The optional argument *i* defaults to ``-1``, so that by default\n the last item is removed and returned.\n\n7. The ``sort()`` and ``reverse()`` methods modify the list in place\n for economy of space when sorting or reversing a large list. To\n remind you that they operate by side effect, they don\'t return the\n sorted or reversed list.\n\n8. The ``sort()`` method takes optional arguments for controlling the\n comparisons.\n\n *cmp* specifies a custom comparison function of two arguments (list\n items) which should return a negative, zero or positive number\n depending on whether the first argument is considered smaller than,\n equal to, or larger than the second argument: ``cmp=lambda x,y:\n cmp(x.lower(), y.lower())``. The default value is ``None``.\n\n *key* specifies a function of one argument that is used to extract\n a comparison key from each list element: ``key=str.lower``. The\n default value is ``None``.\n\n *reverse* is a boolean value. If set to ``True``, then the list\n elements are sorted as if each comparison were reversed.\n\n In general, the *key* and *reverse* conversion processes are much\n faster than specifying an equivalent *cmp* function. This is\n because *cmp* is called multiple times for each list element while\n *key* and *reverse* touch each element only once. Use\n ``functools.cmp_to_key()`` to convert an old-style *cmp* function\n to a *key* function.\n\n Changed in version 2.3: Support for ``None`` as an equivalent to\n omitting *cmp* was added.\n\n Changed in version 2.4: Support for *key* and *reverse* was added.\n\n9. Starting with Python 2.3, the ``sort()`` method is guaranteed to be\n stable. A sort is stable if it guarantees not to change the\n relative order of elements that compare equal --- this is helpful\n for sorting in multiple passes (for example, sort by department,\n then by salary grade).\n\n10. **CPython implementation detail:** While a list is being sorted,\n the effect of attempting to mutate, or even inspect, the list is\n undefined. The C implementation of Python 2.3 and newer makes the\n list appear empty for the duration, and raises ``ValueError`` if\n it can detect that the list has been mutated during a sort.\n', 'typesseq-mutable': u"\nMutable Sequence Types\n**********************\n\nList objects support additional operations that allow in-place\nmodification of the object. Other mutable sequence types (when added\nto the language) should also support these operations. Strings and\ntuples are immutable sequence types: such objects cannot be modified\nonce created. The following operations are defined on mutable sequence\ntypes (where *x* is an arbitrary object):\n\n+--------------------------------+----------------------------------+-----------------------+\n| Operation | Result | Notes |\n+================================+==================================+=======================+\n| ``s[i] = x`` | item *i* of *s* is replaced by | |\n| | *x* | |\n+--------------------------------+----------------------------------+-----------------------+\n| ``s[i:j] = t`` | slice of *s* from *i* to *j* is | |\n| | replaced by the contents of the | |\n| | iterable *t* | |\n+--------------------------------+----------------------------------+-----------------------+\n| ``del s[i:j]`` | same as ``s[i:j] = []`` | |\n+--------------------------------+----------------------------------+-----------------------+\n| ``s[i:j:k] = t`` | the elements of ``s[i:j:k]`` are | (1) |\n| | replaced by those of *t* | |\n+--------------------------------+----------------------------------+-----------------------+\n| ``del s[i:j:k]`` | removes the elements of | |\n| | ``s[i:j:k]`` from the list | |\n+--------------------------------+----------------------------------+-----------------------+\n| ``s.append(x)`` | same as ``s[len(s):len(s)] = | (2) |\n| | [x]`` | |\n+--------------------------------+----------------------------------+-----------------------+\n| ``s.extend(x)`` | same as ``s[len(s):len(s)] = x`` | (3) |\n+--------------------------------+----------------------------------+-----------------------+\n| ``s.count(x)`` | return number of *i*'s for which | |\n| | ``s[i] == x`` | |\n+--------------------------------+----------------------------------+-----------------------+\n| ``s.index(x[, i[, j]])`` | return smallest *k* such that | (4) |\n| | ``s[k] == x`` and ``i <= k < j`` | |\n+--------------------------------+----------------------------------+-----------------------+\n| ``s.insert(i, x)`` | same as ``s[i:i] = [x]`` | (5) |\n+--------------------------------+----------------------------------+-----------------------+\n| ``s.pop([i])`` | same as ``x = s[i]; del s[i]; | (6) |\n| | return x`` | |\n+--------------------------------+----------------------------------+-----------------------+\n| ``s.remove(x)`` | same as ``del s[s.index(x)]`` | (4) |\n+--------------------------------+----------------------------------+-----------------------+\n| ``s.reverse()`` | reverses the items of *s* in | (7) |\n| | place | |\n+--------------------------------+----------------------------------+-----------------------+\n| ``s.sort([cmp[, key[, | sort the items of *s* in place | (7)(8)(9)(10) |\n| reverse]]])`` | | |\n+--------------------------------+----------------------------------+-----------------------+\n\nNotes:\n\n1. *t* must have the same length as the slice it is replacing.\n\n2. The C implementation of Python has historically accepted multiple\n parameters and implicitly joined them into a tuple; this no longer\n works in Python 2.0. Use of this misfeature has been deprecated\n since Python 1.4.\n\n3. *x* can be any iterable object.\n\n4. Raises ``ValueError`` when *x* is not found in *s*. When a negative\n index is passed as the second or third parameter to the ``index()``\n method, the list length is added, as for slice indices. If it is\n still negative, it is truncated to zero, as for slice indices.\n\n Changed in version 2.3: Previously, ``index()`` didn't have\n arguments for specifying start and stop positions.\n\n5. When a negative index is passed as the first parameter to the\n ``insert()`` method, the list length is added, as for slice\n indices. If it is still negative, it is truncated to zero, as for\n slice indices.\n\n Changed in version 2.3: Previously, all negative indices were\n truncated to zero.\n\n6. The ``pop()`` method is only supported by the list and array types.\n The optional argument *i* defaults to ``-1``, so that by default\n the last item is removed and returned.\n\n7. The ``sort()`` and ``reverse()`` methods modify the list in place\n for economy of space when sorting or reversing a large list. To\n remind you that they operate by side effect, they don't return the\n sorted or reversed list.\n\n8. The ``sort()`` method takes optional arguments for controlling the\n comparisons.\n\n *cmp* specifies a custom comparison function of two arguments (list\n items) which should return a negative, zero or positive number\n depending on whether the first argument is considered smaller than,\n equal to, or larger than the second argument: ``cmp=lambda x,y:\n cmp(x.lower(), y.lower())``. The default value is ``None``.\n\n *key* specifies a function of one argument that is used to extract\n a comparison key from each list element: ``key=str.lower``. The\n default value is ``None``.\n\n *reverse* is a boolean value. If set to ``True``, then the list\n elements are sorted as if each comparison were reversed.\n\n In general, the *key* and *reverse* conversion processes are much\n faster than specifying an equivalent *cmp* function. This is\n because *cmp* is called multiple times for each list element while\n *key* and *reverse* touch each element only once. Use\n ``functools.cmp_to_key()`` to convert an old-style *cmp* function\n to a *key* function.\n\n Changed in version 2.3: Support for ``None`` as an equivalent to\n omitting *cmp* was added.\n\n Changed in version 2.4: Support for *key* and *reverse* was added.\n\n9. Starting with Python 2.3, the ``sort()`` method is guaranteed to be\n stable. A sort is stable if it guarantees not to change the\n relative order of elements that compare equal --- this is helpful\n for sorting in multiple passes (for example, sort by department,\n then by salary grade).\n\n10. **CPython implementation detail:** While a list is being sorted,\n the effect of attempting to mutate, or even inspect, the list is\n undefined. The C implementation of Python 2.3 and newer makes the\n list appear empty for the duration, and raises ``ValueError`` if\n it can detect that the list has been mutated during a sort.\n", 'unary': u'\nUnary arithmetic and bitwise operations\n***************************************\n\nAll unary arithmetic and bitwise operations have the same priority:\n\n u_expr ::= power | "-" u_expr | "+" u_expr | "~" u_expr\n\nThe unary ``-`` (minus) operator yields the negation of its numeric\nargument.\n\nThe unary ``+`` (plus) operator yields its numeric argument unchanged.\n\nThe unary ``~`` (invert) operator yields the bitwise inversion of its\nplain or long integer argument. The bitwise inversion of ``x`` is\ndefined as ``-(x+1)``. It only applies to integral numbers.\n\nIn all three cases, if the argument does not have the proper type, a\n``TypeError`` exception is raised.\n', 'while': u'\nThe ``while`` statement\n***********************\n\nThe ``while`` statement is used for repeated execution as long as an\nexpression is true:\n\n while_stmt ::= "while" expression ":" suite\n ["else" ":" suite]\n\nThis repeatedly tests the expression and, if it is true, executes the\nfirst suite; if the expression is false (which may be the first time\nit is tested) the suite of the ``else`` clause, if present, is\nexecuted and the loop terminates.\n\nA ``break`` statement executed in the first suite terminates the loop\nwithout executing the ``else`` clause\'s suite. A ``continue``\nstatement executed in the first suite skips the rest of the suite and\ngoes back to testing the expression.\n', From python-checkins at python.org Sat May 8 19:06:25 2010 From: python-checkins at python.org (michael.foord) Date: Sat, 8 May 2010 19:06:25 +0200 (CEST) Subject: [Python-checkins] r80997 - in python/trunk/Lib/unittest: suite.py test/test_suite.py Message-ID: <20100508170625.BC6A6EE9ED@mail.python.org> Author: michael.foord Date: Sat May 8 19:06:25 2010 New Revision: 80997 Log: unittest: issue 8301. Adding functions to test suites no longer crashes. Modified: python/trunk/Lib/unittest/suite.py python/trunk/Lib/unittest/test/test_suite.py Modified: python/trunk/Lib/unittest/suite.py ============================================================================== --- python/trunk/Lib/unittest/suite.py (original) +++ python/trunk/Lib/unittest/suite.py Sat May 8 19:06:25 2010 @@ -119,7 +119,12 @@ if getattr(currentClass, "__unittest_skip__", False): return - currentClass._classSetupFailed = False + try: + currentClass._classSetupFailed = False + except TypeError: + # test may actually be a function + # so its class will be a builtin-type + pass setUpClass = getattr(currentClass, 'setUpClass', None) if setUpClass is not None: Modified: python/trunk/Lib/unittest/test/test_suite.py ============================================================================== --- python/trunk/Lib/unittest/test/test_suite.py (original) +++ python/trunk/Lib/unittest/test/test_suite.py Sat May 8 19:06:25 2010 @@ -290,6 +290,15 @@ suite = unittest.TestSuite() self.assertRaises(TypeError, suite.addTests, "foo") + def test_function_in_suite(self): + def f(_): + pass + suite = unittest.TestSuite() + suite.addTest(f) + + # when the bug is fixed this line will not crash + suite.run(unittest.TestResult()) + if __name__ == '__main__': unittest.main() From python-checkins at python.org Sat May 8 19:08:18 2010 From: python-checkins at python.org (benjamin.peterson) Date: Sat, 8 May 2010 19:08:18 +0200 (CEST) Subject: [Python-checkins] r80998 - in python/trunk: Include/patchlevel.h Lib/distutils/__init__.py Lib/idlelib/idlever.py Misc/NEWS Misc/RPM/python-2.7.spec README Message-ID: <20100508170818.21071EE9DF@mail.python.org> Author: benjamin.peterson Date: Sat May 8 19:08:17 2010 New Revision: 80998 Log: bump version to 2.7 beta 2 Modified: python/trunk/Include/patchlevel.h python/trunk/Lib/distutils/__init__.py python/trunk/Lib/idlelib/idlever.py python/trunk/Misc/NEWS python/trunk/Misc/RPM/python-2.7.spec python/trunk/README Modified: python/trunk/Include/patchlevel.h ============================================================================== --- python/trunk/Include/patchlevel.h (original) +++ python/trunk/Include/patchlevel.h Sat May 8 19:08:17 2010 @@ -24,10 +24,10 @@ #define PY_MINOR_VERSION 7 #define PY_MICRO_VERSION 0 #define PY_RELEASE_LEVEL PY_RELEASE_LEVEL_BETA -#define PY_RELEASE_SERIAL 1 +#define PY_RELEASE_SERIAL 2 /* Version as a string */ -#define PY_VERSION "2.7b1+" +#define PY_VERSION "2.7b2" /*--end constants--*/ /* Subversion Revision number of this file (not of the repository) */ Modified: python/trunk/Lib/distutils/__init__.py ============================================================================== --- python/trunk/Lib/distutils/__init__.py (original) +++ python/trunk/Lib/distutils/__init__.py Sat May 8 19:08:17 2010 @@ -15,5 +15,5 @@ # Updated automatically by the Python release process. # #--start constants-- -__version__ = "2.7b1" +__version__ = "2.7b2" #--end constants-- Modified: python/trunk/Lib/idlelib/idlever.py ============================================================================== --- python/trunk/Lib/idlelib/idlever.py (original) +++ python/trunk/Lib/idlelib/idlever.py Sat May 8 19:08:17 2010 @@ -1 +1 @@ -IDLE_VERSION = "2.7b1" +IDLE_VERSION = "2.7b2" Modified: python/trunk/Misc/NEWS ============================================================================== --- python/trunk/Misc/NEWS (original) +++ python/trunk/Misc/NEWS Sat May 8 19:08:17 2010 @@ -7,7 +7,7 @@ What's New in Python 2.7 beta 2? ================================ -*Release date: XXXX-XX-XX* +*Release date: 2010-05-08* Core and Builtins ----------------- Modified: python/trunk/Misc/RPM/python-2.7.spec ============================================================================== --- python/trunk/Misc/RPM/python-2.7.spec (original) +++ python/trunk/Misc/RPM/python-2.7.spec Sat May 8 19:08:17 2010 @@ -39,7 +39,7 @@ %define name python #--start constants-- -%define version 2.7b1 +%define version 2.7b2 %define libver 2.7 #--end constants-- %define release 1pydotorg Modified: python/trunk/README ============================================================================== --- python/trunk/README (original) +++ python/trunk/README Sat May 8 19:08:17 2010 @@ -1,4 +1,4 @@ -This is Python version 2.7 beta 1 +This is Python version 2.7 beta 2 ================================= Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010 From python-checkins at python.org Sat May 8 19:10:05 2010 From: python-checkins at python.org (michael.foord) Date: Sat, 8 May 2010 19:10:05 +0200 (CEST) Subject: [Python-checkins] r80999 - in python/branches/py3k: Lib/unittest/suite.py Lib/unittest/test/test_suite.py Message-ID: <20100508171005.9B1C1E234@mail.python.org> Author: michael.foord Date: Sat May 8 19:10:05 2010 New Revision: 80999 Log: Merged revisions 80997 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r80997 | michael.foord | 2010-05-08 19:06:25 +0200 (Sat, 08 May 2010) | 1 line unittest: issue 8301. Adding functions to test suites no longer crashes. ........ Modified: python/branches/py3k/ (props changed) python/branches/py3k/Lib/unittest/suite.py python/branches/py3k/Lib/unittest/test/test_suite.py Modified: python/branches/py3k/Lib/unittest/suite.py ============================================================================== --- python/branches/py3k/Lib/unittest/suite.py (original) +++ python/branches/py3k/Lib/unittest/suite.py Sat May 8 19:10:05 2010 @@ -116,7 +116,12 @@ if getattr(currentClass, "__unittest_skip__", False): return - currentClass._classSetupFailed = False + try: + currentClass._classSetupFailed = False + except TypeError: + # test may actually be a function + # so its class will be a builtin-type + pass setUpClass = getattr(currentClass, 'setUpClass', None) if setUpClass is not None: Modified: python/branches/py3k/Lib/unittest/test/test_suite.py ============================================================================== --- python/branches/py3k/Lib/unittest/test/test_suite.py (original) +++ python/branches/py3k/Lib/unittest/test/test_suite.py Sat May 8 19:10:05 2010 @@ -289,3 +289,16 @@ def test_addTests__string(self): suite = unittest.TestSuite() self.assertRaises(TypeError, suite.addTests, "foo") + + def test_function_in_suite(self): + def f(_): + pass + suite = unittest.TestSuite() + suite.addTest(f) + + # when the bug is fixed this line will not crash + suite.run(unittest.TestResult()) + + +if __name__ == '__main__': + unittest.main() From python-checkins at python.org Sat May 8 19:10:37 2010 From: python-checkins at python.org (benjamin.peterson) Date: Sat, 8 May 2010 19:10:37 +0200 (CEST) Subject: [Python-checkins] r81000 - python/tags/r27b2 Message-ID: <20100508171037.28359EE98D@mail.python.org> Author: benjamin.peterson Date: Sat May 8 19:10:37 2010 New Revision: 81000 Log: tag second 2.7 beta Added: python/tags/r27b2/ - copied from r80999, /python/trunk/ From python-checkins at python.org Sat May 8 20:05:46 2010 From: python-checkins at python.org (gregory.p.smith) Date: Sat, 8 May 2010 20:05:46 +0200 (CEST) Subject: [Python-checkins] r81001 - python/branches/py3k/Lib/test/test_os.py Message-ID: <20100508180546.3561AFC03@mail.python.org> Author: gregory.p.smith Date: Sat May 8 20:05:46 2010 New Revision: 81001 Log: Adds a unittest for the internal os._execvpe function. Modified: python/branches/py3k/Lib/test/test_os.py Modified: python/branches/py3k/Lib/test/test_os.py ============================================================================== --- python/branches/py3k/Lib/test/test_os.py (original) +++ python/branches/py3k/Lib/test/test_os.py Sat May 8 20:05:46 2010 @@ -633,6 +633,55 @@ def test_execvpe_with_bad_arglist(self): self.assertRaises(ValueError, os.execvpe, 'notepad', [], None) + class _stub_out_for_execvpe_test(object): + """ + Stubs out execv, execve and get_exec_path functions when + used as context manager. Records exec calls. The mock execv + and execve functions always raise an exception as they would + normally never return. + """ + def __init__(self): + # A list of tuples containing (function name, first arg, args) + # of calls to execv or execve that have been made. + self.calls = [] + def _mock_execv(self, name, *args): + self.calls.append(('execv', name, args)) + raise RuntimeError("execv called") + + def _mock_execve(self, name, *args): + self.calls.append(('execve', name, args)) + raise OSError(errno.ENOTDIR, "execve called") + + def _mock_get_exec_path(self, env=None): + return ['/p', '/pp'] + + def __enter__(self): + self.orig_execv = os.execv + self.orig_execve = os.execve + self.orig_get_exec_path = os.get_exec_path + os.execv = self._mock_execv + os.execve = self._mock_execve + os.get_exec_path = self._mock_get_exec_path + + def __exit__(self, type, value, tb): + os.execv = self.orig_execv + os.execve = self.orig_execve + os.get_exec_path = self.orig_get_exec_path + + @unittest.skipUnless(hasattr(os, '_execvpe'), + "No internal os._execvpe function to test.") + def test_internal_execvpe(self): + exec_stubbed = self._stub_out_for_execvpe_test() + with exec_stubbed: + self.assertRaises(RuntimeError, os._execvpe, '/f', ['-a']) + self.assertEqual([('execv', '/f', (['-a'],))], exec_stubbed.calls) + exec_stubbed.calls = [] + self.assertRaises(OSError, os._execvpe, 'f', ['-a'], + env={'spam': 'beans'}) + self.assertEqual([('execve', '/p/f', (['-a'], {'spam': 'beans'})), + ('execve', '/pp/f', (['-a'], {'spam': 'beans'}))], + exec_stubbed.calls) + class Win32ErrorTests(unittest.TestCase): def test_rename(self): self.assertRaises(WindowsError, os.rename, support.TESTFN, support.TESTFN+".bak") From python-checkins at python.org Sat May 8 20:53:42 2010 From: python-checkins at python.org (benjamin.peterson) Date: Sat, 8 May 2010 20:53:42 +0200 (CEST) Subject: [Python-checkins] r81002 - in python/trunk: Include/patchlevel.h Misc/NEWS Message-ID: <20100508185342.422CDEE9DB@mail.python.org> Author: benjamin.peterson Date: Sat May 8 20:53:42 2010 New Revision: 81002 Log: towards 2.7 release candidate 1 Modified: python/trunk/Include/patchlevel.h python/trunk/Misc/NEWS Modified: python/trunk/Include/patchlevel.h ============================================================================== --- python/trunk/Include/patchlevel.h (original) +++ python/trunk/Include/patchlevel.h Sat May 8 20:53:42 2010 @@ -27,7 +27,7 @@ #define PY_RELEASE_SERIAL 2 /* Version as a string */ -#define PY_VERSION "2.7b2" +#define PY_VERSION "2.7b2+" /*--end constants--*/ /* Subversion Revision number of this file (not of the repository) */ Modified: python/trunk/Misc/NEWS ============================================================================== --- python/trunk/Misc/NEWS (original) +++ python/trunk/Misc/NEWS Sat May 8 20:53:42 2010 @@ -4,6 +4,18 @@ (editors: check NEWS.help for information about editing NEWS using ReST.) +What's New in Python Release Candidate 1? +========================================= + +*Release date: XXXX-XX-XX* + +Core and Builtins +----------------- + +Library +------- + + What's New in Python 2.7 beta 2? ================================ From python-checkins at python.org Sat May 8 20:57:34 2010 From: python-checkins at python.org (benjamin.peterson) Date: Sat, 8 May 2010 20:57:34 +0200 (CEST) Subject: [Python-checkins] r81003 - python/branches/py3k Message-ID: <20100508185734.3935DEE9B6@mail.python.org> Author: benjamin.peterson Date: Sat May 8 20:57:34 2010 New Revision: 81003 Log: Blocked revisions 80996,80998,81002 via svnmerge ........ r80996 | benjamin.peterson | 2010-05-08 12:05:19 -0500 (Sat, 08 May 2010) | 1 line update pydoc-topics ........ r80998 | benjamin.peterson | 2010-05-08 12:08:17 -0500 (Sat, 08 May 2010) | 1 line bump version to 2.7 beta 2 ........ r81002 | benjamin.peterson | 2010-05-08 13:53:42 -0500 (Sat, 08 May 2010) | 1 line towards 2.7 release candidate 1 ........ Modified: python/branches/py3k/ (props changed) From python-checkins at python.org Sat May 8 21:13:21 2010 From: python-checkins at python.org (mark.dickinson) Date: Sat, 8 May 2010 21:13:21 +0200 (CEST) Subject: [Python-checkins] r81004 - in python/trunk: configure configure.in Message-ID: <20100508191321.625FBEE9E0@mail.python.org> Author: mark.dickinson Date: Sat May 8 21:13:21 2010 New Revision: 81004 Log: Fix configure bug that was misreporting availability of MacOS X 10.5 SDK as available on Linux but not on OS X. Modified: python/trunk/configure python/trunk/configure.in Modified: python/trunk/configure ============================================================================== --- python/trunk/configure (original) +++ python/trunk/configure Sat May 8 21:13:21 2010 @@ -1,5 +1,5 @@ #! /bin/sh -# From configure.in Revision: 80969 . +# From configure.in Revision: 80970 . # Guess values for system-dependent variables and create Makefiles. # Generated by GNU Autoconf 2.65 for python 2.7. # @@ -9281,10 +9281,9 @@ ; return 0; } + _ACEOF if ac_fn_c_try_compile "$LINENO"; then : - ] -else $as_echo "#define HAVE_OSX105_SDK 1" >>confdefs.h @@ -9292,6 +9291,11 @@ { $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5 $as_echo "yes" >&6; } +else + + { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 +$as_echo "no" >&6; } + fi rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext Modified: python/trunk/configure.in ============================================================================== --- python/trunk/configure.in (original) +++ python/trunk/configure.in Sat May 8 21:13:21 2010 @@ -2569,7 +2569,7 @@ AC_MSG_CHECKING(for OSX 10.5 SDK or later) AC_COMPILE_IFELSE([ - AC_LANG_PROGRAM([[#include ]], [[FSIORefNum fRef = 0]])], + AC_LANG_PROGRAM([[#include ]], [[FSIORefNum fRef = 0]]) ],[ AC_DEFINE(HAVE_OSX105_SDK, 1, [Define if compiling using MacOS X 10.5 SDK or later.]) AC_MSG_RESULT(yes) From python-checkins at python.org Sat May 8 21:52:21 2010 From: python-checkins at python.org (benjamin.peterson) Date: Sat, 8 May 2010 21:52:21 +0200 (CEST) Subject: [Python-checkins] r81005 - in python/branches/py3k/Lib: compileall.py py_compile.py Message-ID: <20100508195221.45439EEA07@mail.python.org> Author: benjamin.peterson Date: Sat May 8 21:52:21 2010 New Revision: 81005 Log: Create __pycache__ dir when the pyc path is explicitly given Patch from Arfrever Frehtes Taifersar Arahesis. Modified: python/branches/py3k/Lib/compileall.py python/branches/py3k/Lib/py_compile.py Modified: python/branches/py3k/Lib/compileall.py ============================================================================== --- python/branches/py3k/Lib/compileall.py (original) +++ python/branches/py3k/Lib/compileall.py Sat May 8 21:52:21 2010 @@ -93,12 +93,6 @@ cache_dir = os.path.dirname(cfile) head, tail = name[:-3], name[-3:] if tail == '.py': - if not legacy: - try: - os.mkdir(cache_dir) - except OSError as error: - if error.errno != errno.EEXIST: - raise if not force: try: mtime = int(os.stat(fullname).st_mtime) Modified: python/branches/py3k/Lib/py_compile.py ============================================================================== --- python/branches/py3k/Lib/py_compile.py (original) +++ python/branches/py3k/Lib/py_compile.py Sat May 8 21:52:21 2010 @@ -123,11 +123,11 @@ return if cfile is None: cfile = imp.cache_from_source(file) - try: - os.mkdir(os.path.dirname(cfile)) - except OSError as error: - if error.errno != errno.EEXIST: - raise + try: + os.makedirs(os.path.dirname(cfile)) + except OSError as error: + if error.errno != errno.EEXIST: + raise with open(cfile, 'wb') as fc: fc.write(b'\0\0\0\0') wr_long(fc, timestamp) From python-checkins at python.org Sat May 8 21:52:49 2010 From: python-checkins at python.org (benjamin.peterson) Date: Sat, 8 May 2010 21:52:49 +0200 (CEST) Subject: [Python-checkins] r81006 - python/branches/py3k/Misc/NEWS Message-ID: <20100508195249.3B3E3EE9F1@mail.python.org> Author: benjamin.peterson Date: Sat May 8 21:52:49 2010 New Revision: 81006 Log: add news for r81005 Modified: python/branches/py3k/Misc/NEWS Modified: python/branches/py3k/Misc/NEWS ============================================================================== --- python/branches/py3k/Misc/NEWS (original) +++ python/branches/py3k/Misc/NEWS Sat May 8 21:52:49 2010 @@ -351,6 +351,9 @@ Library ------- +- Issue #8664: In py_compile, create __pycache__ when the compiled path is + given. + - Issue #8514: Add os.fsencode() function (Unix only): encode a string to bytes for use in the file system, environment variables or the command line. From python-checkins at python.org Sat May 8 22:06:02 2010 From: python-checkins at python.org (jean-paul.calderone) Date: Sat, 8 May 2010 22:06:02 +0200 (CEST) Subject: [Python-checkins] r81007 - in python/trunk: Lib/test/test_signal.py Misc/NEWS Modules/signalmodule.c Python/pythonrun.c Message-ID: <20100508200602.9C3F9EE9B8@mail.python.org> Author: jean-paul.calderone Date: Sat May 8 22:06:02 2010 New Revision: 81007 Log: Skip signal handler re-installation if it is not necessary. Issue 8354. Modified: python/trunk/Lib/test/test_signal.py python/trunk/Misc/NEWS python/trunk/Modules/signalmodule.c python/trunk/Python/pythonrun.c Modified: python/trunk/Lib/test/test_signal.py ============================================================================== --- python/trunk/Lib/test/test_signal.py (original) +++ python/trunk/Lib/test/test_signal.py Sat May 8 22:06:02 2010 @@ -255,48 +255,105 @@ class SiginterruptTest(unittest.TestCase): signum = signal.SIGUSR1 - def readpipe_interrupted(self, cb): + + def setUp(self): + """Install a no-op signal handler that can be set to allow + interrupts or not, and arrange for the original signal handler to be + re-installed when the test is finished. + """ + oldhandler = signal.signal(self.signum, lambda x,y: None) + self.addCleanup(signal.signal, self.signum, oldhandler) + + def readpipe_interrupted(self): + """Perform a read during which a signal will arrive. Return True if the + read is interrupted by the signal and raises an exception. Return False + if it returns normally. + """ + # Create a pipe that can be used for the read. Also clean it up + # when the test is over, since nothing else will (but see below for + # the write end). r, w = os.pipe() + self.addCleanup(os.close, r) + + # Create another process which can send a signal to this one to try + # to interrupt the read. ppid = os.getpid() pid = os.fork() - oldhandler = signal.signal(self.signum, lambda x,y: None) - cb() - if pid==0: - # child code: sleep, kill, sleep. and then exit, - # which closes the pipe from which the parent process reads + if pid == 0: + # Child code: sleep to give the parent enough time to enter the + # read() call (there's a race here, but it's really tricky to + # eliminate it); then signal the parent process. Also, sleep + # again to make it likely that the signal is delivered to the + # parent process before the child exits. If the child exits + # first, the write end of the pipe will be closed and the test + # is invalid. try: time.sleep(0.2) os.kill(ppid, self.signum) time.sleep(0.2) finally: + # No matter what, just exit as fast as possible now. exit_subprocess() - - try: + else: + # Parent code. + # Make sure the child is eventually reaped, else it'll be a + # zombie for the rest of the test suite run. + self.addCleanup(os.waitpid, pid, 0) + + # Close the write end of the pipe. The child has a copy, so + # it's not really closed until the child exits. We need it to + # close when the child exits so that in the non-interrupt case + # the read eventually completes, otherwise we could just close + # it *after* the test. os.close(w) + # Try the read and report whether it is interrupted or not to + # the caller. try: - d=os.read(r, 1) + d = os.read(r, 1) return False except OSError, err: if err.errno != errno.EINTR: raise return True - finally: - signal.signal(self.signum, oldhandler) - os.waitpid(pid, 0) def test_without_siginterrupt(self): - i=self.readpipe_interrupted(lambda: None) - self.assertEquals(i, True) + """If a signal handler is installed and siginterrupt is not called + at all, when that signal arrives, it interrupts a syscall that's in + progress. + """ + i = self.readpipe_interrupted() + self.assertTrue(i) + # Arrival of the signal shouldn't have changed anything. + i = self.readpipe_interrupted() + self.assertTrue(i) def test_siginterrupt_on(self): - i=self.readpipe_interrupted(lambda: signal.siginterrupt(self.signum, 1)) - self.assertEquals(i, True) + """If a signal handler is installed and siginterrupt is called with + a true value for the second argument, when that signal arrives, it + interrupts a syscall that's in progress. + """ + signal.siginterrupt(self.signum, 1) + i = self.readpipe_interrupted() + self.assertTrue(i) + # Arrival of the signal shouldn't have changed anything. + i = self.readpipe_interrupted() + self.assertTrue(i) def test_siginterrupt_off(self): - i=self.readpipe_interrupted(lambda: signal.siginterrupt(self.signum, 0)) - self.assertEquals(i, False) + """If a signal handler is installed and siginterrupt is called with + a false value for the second argument, when that signal arrives, it + does not interrupt a syscall that's in progress. + """ + signal.siginterrupt(self.signum, 0) + i = self.readpipe_interrupted() + self.assertFalse(i) + # Arrival of the signal shouldn't have changed anything. + i = self.readpipe_interrupted() + self.assertFalse(i) + + class ItimerTest(unittest.TestCase): def setUp(self): Modified: python/trunk/Misc/NEWS ============================================================================== --- python/trunk/Misc/NEWS (original) +++ python/trunk/Misc/NEWS Sat May 8 22:06:02 2010 @@ -96,6 +96,9 @@ - Issue #4687: Fix accuracy of garbage collection runtimes displayed with gc.DEBUG_STATS. +- Issue #8354: The siginterrupt setting is now preserved for all signals, + not just SIGCHLD. + - Issue #7192: webbrowser.get("firefox") now wors on Mac OS X, as does webbrowser.get("safari"). Modified: python/trunk/Modules/signalmodule.c ============================================================================== --- python/trunk/Modules/signalmodule.c (original) +++ python/trunk/Modules/signalmodule.c Sat May 8 22:06:02 2010 @@ -198,7 +198,12 @@ return; } #endif +#ifndef HAVE_SIGACTION + /* If the handler was not set up with sigaction, reinstall it. See + * Python/pythonrun.c for the implementation of PyOS_setsig which + * makes this true. See also issue8354. */ PyOS_setsig(sig_num, signal_handler); +#endif } Modified: python/trunk/Python/pythonrun.c ============================================================================== --- python/trunk/Python/pythonrun.c (original) +++ python/trunk/Python/pythonrun.c Sat May 8 22:06:02 2010 @@ -1862,6 +1862,10 @@ PyOS_setsig(int sig, PyOS_sighandler_t handler) { #ifdef HAVE_SIGACTION + /* Some code in Modules/signalmodule.c depends on sigaction() being + * used here if HAVE_SIGACTION is defined. Fix that if this code + * changes to invalidate that assumption. + */ struct sigaction context, ocontext; context.sa_handler = handler; sigemptyset(&context.sa_mask); From python-checkins at python.org Sat May 8 22:59:42 2010 From: python-checkins at python.org (benjamin.peterson) Date: Sat, 8 May 2010 22:59:42 +0200 (CEST) Subject: [Python-checkins] r81008 - in python/trunk: Doc/library/copy_reg.rst Lib/ConfigParser.py Lib/Queue.py Lib/SocketServer.py Lib/copy_reg.py Lib/lib-tk/Dialog.py Lib/lib-tk/FixTk.py Lib/lib-tk/ScrolledText.py Lib/lib-tk/Tix.py Lib/lib-tk/Tkconstants.py Lib/lib-tk/Tkdnd.py Lib/lib-tk/Tkinter.py Lib/lib-tk/test/test_tkinter Lib/lib-tk/test/test_ttk Lib/lib-tk/tkColorChooser.py Lib/lib-tk/tkCommonDialog.py Lib/lib-tk/tkFont.py Lib/lib-tk/tkMessageBox.py Lib/lib-tk/turtle.py Lib/test/test_copy_reg.py Lib/test/test_ttk_guionly.py Lib/test/test_ttk_textonly.py PC/os2emx/python27.def Message-ID: <20100508205942.87A29FD8E@mail.python.org> Author: benjamin.peterson Date: Sat May 8 22:59:42 2010 New Revision: 81008 Log: remove svn:mergeinfo property Modified: python/trunk/ (props changed) python/trunk/Doc/library/copy_reg.rst (props changed) python/trunk/Lib/ConfigParser.py (props changed) python/trunk/Lib/Queue.py (props changed) python/trunk/Lib/SocketServer.py (props changed) python/trunk/Lib/copy_reg.py (props changed) python/trunk/Lib/lib-tk/Dialog.py (props changed) python/trunk/Lib/lib-tk/FixTk.py (props changed) python/trunk/Lib/lib-tk/ScrolledText.py (props changed) python/trunk/Lib/lib-tk/Tix.py (props changed) python/trunk/Lib/lib-tk/Tkconstants.py (props changed) python/trunk/Lib/lib-tk/Tkdnd.py (props changed) python/trunk/Lib/lib-tk/Tkinter.py (props changed) python/trunk/Lib/lib-tk/test/test_tkinter/ (props changed) python/trunk/Lib/lib-tk/test/test_ttk/ (props changed) python/trunk/Lib/lib-tk/tkColorChooser.py (props changed) python/trunk/Lib/lib-tk/tkCommonDialog.py (props changed) python/trunk/Lib/lib-tk/tkFont.py (props changed) python/trunk/Lib/lib-tk/tkMessageBox.py (props changed) python/trunk/Lib/lib-tk/turtle.py (props changed) python/trunk/Lib/test/test_copy_reg.py (props changed) python/trunk/Lib/test/test_ttk_guionly.py (props changed) python/trunk/Lib/test/test_ttk_textonly.py (props changed) python/trunk/PC/os2emx/python27.def (props changed) From python-checkins at python.org Sat May 8 23:03:44 2010 From: python-checkins at python.org (benjamin.peterson) Date: Sat, 8 May 2010 23:03:44 +0200 (CEST) Subject: [Python-checkins] r81009 - python/branches/py3k Message-ID: <20100508210344.92EC2EE9B4@mail.python.org> Author: benjamin.peterson Date: Sat May 8 23:03:44 2010 New Revision: 81009 Log: Blocked revisions 81008 via svnmerge ........ r81008 | benjamin.peterson | 2010-05-08 15:59:42 -0500 (Sat, 08 May 2010) | 1 line remove svn:mergeinfo property ........ Modified: python/branches/py3k/ (props changed) From python-checkins at python.org Sat May 8 23:05:35 2010 From: python-checkins at python.org (benjamin.peterson) Date: Sat, 8 May 2010 23:05:35 +0200 (CEST) Subject: [Python-checkins] r81010 - in python/branches/py3k: Doc/library/_dummy_thread.rst Doc/library/_thread.rst Doc/library/html.parser.rst Doc/library/http.client.rst Doc/library/http.cookiejar.rst Doc/library/http.cookies.rst Doc/library/http.server.rst Doc/library/tkinter.scrolledtext.rst Doc/library/tkinter.tix.rst Doc/library/tkinter.ttk.rst Doc/library/turtle.rst Doc/library/winreg.rst Doc/library/xmlrpc.client.rst Doc/library/xmlrpc.server.rst Lib/_dummy_thread.py Lib/dbm/dumb.py Lib/email/test/test_email_codecs.py Lib/http/client.py Lib/http/cookiejar.py Lib/http/cookies.py Lib/http/server.py Lib/test/test_dbm.py Lib/test/test_dbm_dumb.py Lib/test/test_dbm_gnu.py Lib/test/test_dbm_ndbm.py Lib/test/test_http_cookiejar.py Lib/test/test_http_cookies.py Lib/test/test_ttk_guionly.py Lib/test/test_ttk_textonly.py Lib/tkinter/__init__.py Lib/tkinter/_fix.py Lib/tkinter/colorchooser.py Lib/tkinter/commondialog.py Lib/tkinter/constants.py Lib/tkinter/dialog.py Lib/tkinter/dnd.py Lib/tkinter/filedialog.py Lib/tkinter/font.py Lib/tkinter/messagebox.py Lib/tkinter/scrolledtext.py Lib/tkinter/simpledialog.py Lib/tkinter/test/support.py Lib/tkinter/tix.py Lib/turtle.py Lib/xmlrpc/client.py Lib/xmlrpc/server.py Modules/_dbmmodule.c Modules/_gdbmmodule.c Modules/_io/_iomodule.c Modules/_io/_iomodule.h Modules/_io/bufferedio.c Modules/_io/bytesio.c Modules/_io/fileio.c Modules/_io/iobase.c Modules/_io/stringio.c Modules/_io/textio.c Modules/_threadmodule.c PC/os2emx/python27.def PC/winreg.c Message-ID: <20100508210535.95A52FD3D@mail.python.org> Author: benjamin.peterson Date: Sat May 8 23:05:35 2010 New Revision: 81010 Log: remove svn:mergeinfo Modified: python/branches/py3k/Doc/library/_dummy_thread.rst (props changed) python/branches/py3k/Doc/library/_thread.rst (props changed) python/branches/py3k/Doc/library/html.parser.rst (props changed) python/branches/py3k/Doc/library/http.client.rst (props changed) python/branches/py3k/Doc/library/http.cookiejar.rst (props changed) python/branches/py3k/Doc/library/http.cookies.rst (props changed) python/branches/py3k/Doc/library/http.server.rst (props changed) python/branches/py3k/Doc/library/tkinter.scrolledtext.rst (props changed) python/branches/py3k/Doc/library/tkinter.tix.rst (props changed) python/branches/py3k/Doc/library/tkinter.ttk.rst (props changed) python/branches/py3k/Doc/library/turtle.rst (props changed) python/branches/py3k/Doc/library/winreg.rst (props changed) python/branches/py3k/Doc/library/xmlrpc.client.rst (props changed) python/branches/py3k/Doc/library/xmlrpc.server.rst (props changed) python/branches/py3k/Lib/_dummy_thread.py (props changed) python/branches/py3k/Lib/dbm/dumb.py (props changed) python/branches/py3k/Lib/email/test/test_email_codecs.py (props changed) python/branches/py3k/Lib/http/client.py (props changed) python/branches/py3k/Lib/http/cookiejar.py (props changed) python/branches/py3k/Lib/http/cookies.py (props changed) python/branches/py3k/Lib/http/server.py (props changed) python/branches/py3k/Lib/test/test_dbm.py (props changed) python/branches/py3k/Lib/test/test_dbm_dumb.py (props changed) python/branches/py3k/Lib/test/test_dbm_gnu.py (props changed) python/branches/py3k/Lib/test/test_dbm_ndbm.py (props changed) python/branches/py3k/Lib/test/test_http_cookiejar.py (props changed) python/branches/py3k/Lib/test/test_http_cookies.py (props changed) python/branches/py3k/Lib/test/test_ttk_guionly.py (props changed) python/branches/py3k/Lib/test/test_ttk_textonly.py (props changed) python/branches/py3k/Lib/tkinter/__init__.py (props changed) python/branches/py3k/Lib/tkinter/_fix.py (props changed) python/branches/py3k/Lib/tkinter/colorchooser.py (props changed) python/branches/py3k/Lib/tkinter/commondialog.py (props changed) python/branches/py3k/Lib/tkinter/constants.py (props changed) python/branches/py3k/Lib/tkinter/dialog.py (props changed) python/branches/py3k/Lib/tkinter/dnd.py (props changed) python/branches/py3k/Lib/tkinter/filedialog.py (props changed) python/branches/py3k/Lib/tkinter/font.py (props changed) python/branches/py3k/Lib/tkinter/messagebox.py (props changed) python/branches/py3k/Lib/tkinter/scrolledtext.py (props changed) python/branches/py3k/Lib/tkinter/simpledialog.py (props changed) python/branches/py3k/Lib/tkinter/test/support.py (props changed) python/branches/py3k/Lib/tkinter/tix.py (props changed) python/branches/py3k/Lib/turtle.py (props changed) python/branches/py3k/Lib/xmlrpc/client.py (props changed) python/branches/py3k/Lib/xmlrpc/server.py (props changed) python/branches/py3k/Modules/_dbmmodule.c (props changed) python/branches/py3k/Modules/_gdbmmodule.c (props changed) python/branches/py3k/Modules/_io/_iomodule.c (props changed) python/branches/py3k/Modules/_io/_iomodule.h (props changed) python/branches/py3k/Modules/_io/bufferedio.c (props changed) python/branches/py3k/Modules/_io/bytesio.c (props changed) python/branches/py3k/Modules/_io/fileio.c (props changed) python/branches/py3k/Modules/_io/iobase.c (props changed) python/branches/py3k/Modules/_io/stringio.c (props changed) python/branches/py3k/Modules/_io/textio.c (props changed) python/branches/py3k/Modules/_threadmodule.c (props changed) python/branches/py3k/PC/os2emx/python27.def (props changed) python/branches/py3k/PC/winreg.c (props changed) From python-checkins at python.org Sat May 8 23:11:28 2010 From: python-checkins at python.org (jean-paul.calderone) Date: Sat, 8 May 2010 23:11:28 +0200 (CEST) Subject: [Python-checkins] r81011 - in python/branches/release26-maint: Lib/test/test_signal.py Misc/NEWS Modules/signalmodule.c Python/pythonrun.c Message-ID: <20100508211128.DF652EE9FF@mail.python.org> Author: jean-paul.calderone Date: Sat May 8 23:11:28 2010 New Revision: 81011 Log: Merged revisions 81007 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r81007 | jean-paul.calderone | 2010-05-08 16:06:02 -0400 (Sat, 08 May 2010) | 1 line Skip signal handler re-installation if it is not necessary. Issue 8354. ........ Modified: python/branches/release26-maint/ (props changed) python/branches/release26-maint/Lib/test/test_signal.py python/branches/release26-maint/Misc/NEWS python/branches/release26-maint/Modules/signalmodule.c python/branches/release26-maint/Python/pythonrun.c Modified: python/branches/release26-maint/Lib/test/test_signal.py ============================================================================== --- python/branches/release26-maint/Lib/test/test_signal.py (original) +++ python/branches/release26-maint/Lib/test/test_signal.py Sat May 8 23:11:28 2010 @@ -256,48 +256,121 @@ class SiginterruptTest(unittest.TestCase): signum = signal.SIGUSR1 - def readpipe_interrupted(self, cb): + + def setUp(self): + """Install a no-op signal handler that can be set to allow + interrupts or not, and arrange for the original signal handler to be + re-installed when the test is finished. + """ + self._cleanups = [] + oldhandler = signal.signal(self.signum, lambda x,y: None) + self.addCleanup(signal.signal, self.signum, oldhandler) + + + def tearDown(self): + """Run any cleanup functions which have been registered. + """ + for (f, a) in self._cleanups: + f(*a) + + + def addCleanup(self, f, *a): + """Register a function to be called at the end of the test method + run. + """ + self._cleanups.append((f, a)) + + + def readpipe_interrupted(self): + """Perform a read during which a signal will arrive. Return True if the + read is interrupted by the signal and raises an exception. Return False + if it returns normally. + """ + # Create a pipe that can be used for the read. Also clean it up + # when the test is over, since nothing else will (but see below for + # the write end). r, w = os.pipe() + self.addCleanup(os.close, r) + + # Create another process which can send a signal to this one to try + # to interrupt the read. ppid = os.getpid() pid = os.fork() - oldhandler = signal.signal(self.signum, lambda x,y: None) - cb() - if pid==0: - # child code: sleep, kill, sleep. and then exit, - # which closes the pipe from which the parent process reads + if pid == 0: + # Child code: sleep to give the parent enough time to enter the + # read() call (there's a race here, but it's really tricky to + # eliminate it); then signal the parent process. Also, sleep + # again to make it likely that the signal is delivered to the + # parent process before the child exits. If the child exits + # first, the write end of the pipe will be closed and the test + # is invalid. try: time.sleep(0.2) os.kill(ppid, self.signum) time.sleep(0.2) finally: + # No matter what, just exit as fast as possible now. exit_subprocess() - - try: + else: + # Parent code. + # Make sure the child is eventually reaped, else it'll be a + # zombie for the rest of the test suite run. + self.addCleanup(os.waitpid, pid, 0) + + # Close the write end of the pipe. The child has a copy, so + # it's not really closed until the child exits. We need it to + # close when the child exits so that in the non-interrupt case + # the read eventually completes, otherwise we could just close + # it *after* the test. os.close(w) + # Try the read and report whether it is interrupted or not to + # the caller. try: - d=os.read(r, 1) + d = os.read(r, 1) return False except OSError, err: if err.errno != errno.EINTR: raise return True - finally: - signal.signal(self.signum, oldhandler) - os.waitpid(pid, 0) def test_without_siginterrupt(self): - i=self.readpipe_interrupted(lambda: None) - self.assertEquals(i, True) + """If a signal handler is installed and siginterrupt is not called + at all, when that signal arrives, it interrupts a syscall that's in + progress. + """ + i = self.readpipe_interrupted() + self.assertTrue(i) + # Arrival of the signal shouldn't have changed anything. + i = self.readpipe_interrupted() + self.assertTrue(i) def test_siginterrupt_on(self): - i=self.readpipe_interrupted(lambda: signal.siginterrupt(self.signum, 1)) - self.assertEquals(i, True) + """If a signal handler is installed and siginterrupt is called with + a true value for the second argument, when that signal arrives, it + interrupts a syscall that's in progress. + """ + signal.siginterrupt(self.signum, 1) + i = self.readpipe_interrupted() + self.assertTrue(i) + # Arrival of the signal shouldn't have changed anything. + i = self.readpipe_interrupted() + self.assertTrue(i) def test_siginterrupt_off(self): - i=self.readpipe_interrupted(lambda: signal.siginterrupt(self.signum, 0)) - self.assertEquals(i, False) + """If a signal handler is installed and siginterrupt is called with + a false value for the second argument, when that signal arrives, it + does not interrupt a syscall that's in progress. + """ + signal.siginterrupt(self.signum, 0) + i = self.readpipe_interrupted() + self.assertFalse(i) + # Arrival of the signal shouldn't have changed anything. + i = self.readpipe_interrupted() + self.assertFalse(i) + + class ItimerTest(unittest.TestCase): def setUp(self): Modified: python/branches/release26-maint/Misc/NEWS ============================================================================== --- python/branches/release26-maint/Misc/NEWS (original) +++ python/branches/release26-maint/Misc/NEWS Sat May 8 23:11:28 2010 @@ -73,6 +73,9 @@ - Issue #4687: Fix accuracy of garbage collection runtimes displayed with gc.DEBUG_STATS. +- Issue #8354: The siginterrupt setting is now preserved for all signals, + not just SIGCHLD. + - Issue #8577: distutils.sysconfig.get_python_inc() now makes a difference between the build dir and the source dir when looking for "python.h" or "Include". Modified: python/branches/release26-maint/Modules/signalmodule.c ============================================================================== --- python/branches/release26-maint/Modules/signalmodule.c (original) +++ python/branches/release26-maint/Modules/signalmodule.c Sat May 8 23:11:28 2010 @@ -192,7 +192,12 @@ return; } #endif +#ifndef HAVE_SIGACTION + /* If the handler was not set up with sigaction, reinstall it. See + * Python/pythonrun.c for the implementation of PyOS_setsig which + * makes this true. See also issue8354. */ PyOS_setsig(sig_num, signal_handler); +#endif } Modified: python/branches/release26-maint/Python/pythonrun.c ============================================================================== --- python/branches/release26-maint/Python/pythonrun.c (original) +++ python/branches/release26-maint/Python/pythonrun.c Sat May 8 23:11:28 2010 @@ -1867,6 +1867,10 @@ PyOS_setsig(int sig, PyOS_sighandler_t handler) { #ifdef HAVE_SIGACTION + /* Some code in Modules/signalmodule.c depends on sigaction() being + * used here if HAVE_SIGACTION is defined. Fix that if this code + * changes to invalidate that assumption. + */ struct sigaction context, ocontext; context.sa_handler = handler; sigemptyset(&context.sa_mask); From solipsis at pitrou.net Sun May 9 01:23:12 2010 From: solipsis at pitrou.net (solipsis at pitrou.net) Date: Sun, 9 May 2010 01:23:12 +0200 (CEST) Subject: [Python-checkins] Daily py3k reference leaks (r81010): sum=0 Message-ID: <20100508232312.B3BA61770A@ns6635.ovh.net> py3k results for svn r81010 (hg cset e33bbce622a8) -------------------------------------------------- Command line was: ['./python', '-m', 'test.regrtest', '-uall', '-R', '3:3:/home/antoine/py3k/refleaks/reflogn3wwLf', '-x'] From python-checkins at python.org Sun May 9 01:38:49 2010 From: python-checkins at python.org (gregory.p.smith) Date: Sun, 9 May 2010 01:38:49 +0200 (CEST) Subject: [Python-checkins] r81012 - in python/trunk: Lib/pdb.py Lib/test/test_pdb2.py Misc/NEWS Message-ID: <20100508233849.58D8CEEA01@mail.python.org> Author: gregory.p.smith Date: Sun May 9 01:38:49 2010 New Revision: 81012 Log: Fixes [issue7245] Better Ctrl-C support in pdb. Added: python/trunk/Lib/test/test_pdb2.py Modified: python/trunk/Lib/pdb.py python/trunk/Misc/NEWS Modified: python/trunk/Lib/pdb.py ============================================================================== --- python/trunk/Lib/pdb.py (original) +++ python/trunk/Lib/pdb.py Sun May 9 01:38:49 2010 @@ -13,6 +13,7 @@ import re import pprint import traceback +import signal class Restart(Exception): @@ -72,6 +73,8 @@ import readline except ImportError: pass + self.allow_kbdint = False + signal.signal(signal.SIGINT, self.sigint_handler) # Read $HOME/.pdbrc and ./.pdbrc self.rcLines = [] @@ -104,6 +107,13 @@ self.commands_bnum = None # The breakpoint number for which we are # defining a list + def sigint_handler(self, signum, frame): + if self.allow_kbdint: + raise KeyboardInterrupt() + print >>self.stdout, "\nProgram interrupted. (Use 'cont' to resume)." + self.set_step() + self.set_trace(frame) + def reset(self): bdb.Bdb.reset(self) self.forget() @@ -176,7 +186,7 @@ if not self.commands_silent[currentbp]: self.print_stack_entry(self.stack[self.curindex]) if self.commands_doprompt[currentbp]: - self.cmdloop() + self._cmdloop() self.forget() return return 1 @@ -199,11 +209,22 @@ self.interaction(frame, exc_traceback) # General interaction function + def _cmdloop(self): + while 1: + try: + # keyboard interrupts allow for an easy way to interrupt + # the current command + self.allow_kbdint = True + self.cmdloop() + self.allow_kbdint = False + break + except KeyboardInterrupt: + print >>self.stdout, '--KeyboardInterrupt--' def interaction(self, frame, traceback): self.setup(frame, traceback) self.print_stack_entry(self.stack[self.curindex]) - self.cmdloop() + self._cmdloop() self.forget() def displayhook(self, obj): @@ -329,9 +350,22 @@ prompt_back = self.prompt self.prompt = '(com) ' self.commands_defining = True - self.cmdloop() - self.commands_defining = False - self.prompt = prompt_back + try: + self.cmdloop() + except (KeyboardInterrupt, IOError): + # It appears that that when pdb is reading input from a pipe + # we may get IOErrors, rather than KeyboardInterrupt. + # Now discard all the commands entered so far (essentially undo + # any effect of this "commands" cmd) + self.commands.pop(bnum) + self.commands_doprompt.pop(bnum) + self.commands_silent.pop(bnum) + # this will get caught by the _cmdloop and pdb will reenter + # the main command loop + raise KeyboardInterrupt() + finally: + self.commands_defining = False + self.prompt = prompt_back def do_break(self, arg, temporary = 0): # break [ ([filename:]lineno | function) [, "condition"] ] Added: python/trunk/Lib/test/test_pdb2.py ============================================================================== --- (empty file) +++ python/trunk/Lib/test/test_pdb2.py Sun May 9 01:38:49 2010 @@ -0,0 +1,197 @@ +#!/usr/bin/env python +# pdb tests in the Lib/test style +import os +import sys +import time +import re +import subprocess +import signal +from test.test_support import TESTFN +import test.test_support +import unittest + +# allow alt pdb locations, if environment variable is specified then +# the test files will be stored in t/ directory and will not be deleted +# after pdb run +DEBUG_PDB = os.environ.get("_DEBUG_PDB", None) +TMP_DIR = "./t" # dir for tmp files if DEBUG_PDB is set + +if DEBUG_PDB: + if not os.path.exists(TMP_DIR): + os.mkdir(TMP_DIR) + +def _write_test_file(testname, text): + filename = TESTFN + if DEBUG_PDB: + filename = os.path.join(TMP_DIR, testname) + with open(filename, "wt") as f: + f.write(text+"\n") + return filename + + +class PdbProcess(object): + def __init__(self, testname, testprg): + self.testname = testname + self.filename = _write_test_file(testname, testprg) + # unbuffer pdb.py output (if it gets any ideas to buffer it) + # make sure that we use the same interpreter to run tests wrapper and + # pdb itself + cmd = [sys.executable, '-u'] + if DEBUG_PDB: + cmd.append(DEBUG_PDB) + else: + cmd.extend(['-m', 'pdb']) + cmd.append(self.filename) + self.pdbhandle = subprocess.Popen(cmd, bufsize=0, + stdin=subprocess.PIPE, + stdout=subprocess.PIPE, + stderr=subprocess.STDOUT) + self.startup_msg = self.wait_for_prompt() + self.finished=0 + + + def wait_for_normal_exit(self, timeout=2): + """wait for pdb subprocess to exit, timeout is in seconds""" + step = 0.1 + for i in range(int(timeout/step)): + status=self.pdbhandle.poll() + if status is not None: + break + time.sleep(step) + if status is -1: + describe = "pdb has not exited" + elif status> 0: + describe = "pdb exited abnormally with status=%d" % status + assert status == 0, describe + + def wait_for_line(self, stopline, alt_stopline=None): + output='' + line='' + while 1 : + ch=self.pdbhandle.stdout.read(1) + # sys.stdout.write(ch) + line += ch + if line == stopline or line == alt_stopline: + return output + if ch == '\n': + output += line + line='' + if ch == '':#eof + output += line + return output + + # note: this can block if issued at the wrong time + def wait_for_prompt(self): + """collect any output from pdb session til the prompt is encountered. + Return this output (exlcuding prompt)""" + return self.wait_for_line("(Pdb) ", "(com) ") + + def send_cmd(self, cmd): + """send a command but do not wait for response""" + #print "sending:", cmd + self.pdbhandle.stdin.write(cmd+"\n") + + + def cmd(self, cmd, response_text=""): + """send a single command to pdb, collect pdb response (by waiting + for the next prompt). Verify that response contains specified + response_text""" + + self.pdbhandle.stdin.write(cmd+"\n") + response = self.wait_for_prompt() + if not response_text: + return response + + if DEBUG_PDB: + print "%s: testing response for '%s':" % (self.testname,cmd), + assert response.find(response_text) >= 0, ( + "response:\n%s\n does not contain expected substring '%s'" % + (response, response_text)) + if DEBUG_PDB: + print "Ok" + return response + + def send_kbdint(self): + # os.kill is Posix-specific. We could have used a X-platform + # send_signal method of Popen objects, but it still cann't send + # SIGINT on win32 and it's not present on python2.5 + # self.pdbhandle.send_signal(signal.SIGINT) + os.kill(self.pdbhandle.pid, signal.SIGINT) + + def __del__(self): + # if pdb is still running, kill it, leaving it running does not serve + # any useful purpose + if self.pdbhandle.poll() is None: + self.pdbhandle.send_signal(signal.SIGTERM) + if not DEBUG_PDB: + os.unlink(self.filename) + return self.pdbhandle.wait() + + +class PdbTest(unittest.TestCase): + + def test_00startup(self): + pdb = PdbProcess("pdb_t_startup", "print 'Hello, world'") + pdb.cmd("r", "Hello, world") + pdb.cmd("q") + pdb.wait_for_normal_exit() + + @unittest.skipIf(sys.platform.startswith("win"), + "test_sigint requires a posix system.") + def test_sigint(self): + pdb = PdbProcess("pdb_t_loop", """\ +for i in xrange(100000000): + print 'i=%d' %i +""" ) + # first, test Ctrl-C/kbdint handling while the program is running + # kbdint should interrupt the program and return to pdb prompt, + # the program must be resumable + pdb.send_cmd("c") + # we could use time.sleep() delays but they are not reliable so you + # end up with making them much longer than necessary (and still failing + # from time to time) + pdb.wait_for_line("i=19") + pdb.send_kbdint() + pdb.wait_for_prompt() + response = pdb.cmd('p "i=%d" % i') + m = re.search('i=(\d+)', response) + assert m, "unexpected response %s" % response + i0 = int(m.group(1)) + pdb.send_cmd("c") + pdb.wait_for_line("i=%d" % (i0+99)) + pdb.send_kbdint() + pdb.wait_for_prompt() + response = pdb.cmd('p "i=%d" % i') + m = re.search('i=(\d+)', response) + assert m, "unexpected response %s" % response + i1 = int(m.group(1)) + assert i1 > i0 + # now test kbd interrupts in interactive mode, they should interrupt + # the current cmd + # simple case: just generate kdbint + pdb.send_kbdint() + pdb.wait_for_prompt() + pdb.cmd("p 'hello'", "hello") # check that we are at prompt + # more complicated case: Ctrl-C while defining bp commands + # interrupted commands should have no effect + pdb.cmd("b 2") + pdb.cmd("commands 1") + pdb.cmd("p 'marker'") + pdb.send_kbdint() + pdb.wait_for_prompt() + pdb.cmd("p 'hello'", "hello") # check that we are back at normal prompt + pdb.send_cmd("c") + response = pdb.wait_for_prompt() + assert not re.search("marker", response, re.I), ( + "unexpected response '%s'" % response) + pdb.cmd("p 'hello'", "hello") #check that we are back at prompt + pdb.send_cmd("q") + pdb.wait_for_normal_exit() + + +def test_main(): + test.test_support.run_unittest(PdbTest) + + +if __name__ == "__main__": + test_main() Modified: python/trunk/Misc/NEWS ============================================================================== --- python/trunk/Misc/NEWS (original) +++ python/trunk/Misc/NEWS Sun May 9 01:38:49 2010 @@ -15,6 +15,8 @@ Library ------- +- [issue7245] Better Ctrl-C support in pdb. + What's New in Python 2.7 beta 2? ================================ From python-checkins at python.org Sun May 9 03:20:20 2010 From: python-checkins at python.org (gregory.p.smith) Date: Sun, 9 May 2010 03:20:20 +0200 (CEST) Subject: [Python-checkins] r81013 - in python/trunk: Lib/pdb.py Lib/test/test_pdb2.py Misc/NEWS Message-ID: <20100509012020.89AD1EE986@mail.python.org> Author: gregory.p.smith Date: Sun May 9 03:20:20 2010 New Revision: 81013 Log: Revert r81012. buildbot problems and its questionable of me to even add this to trunk while we're on the way to 2.7rc1. When fixed this can go into py3k first. Sorry. Removed: python/trunk/Lib/test/test_pdb2.py Modified: python/trunk/Lib/pdb.py python/trunk/Misc/NEWS Modified: python/trunk/Lib/pdb.py ============================================================================== --- python/trunk/Lib/pdb.py (original) +++ python/trunk/Lib/pdb.py Sun May 9 03:20:20 2010 @@ -13,7 +13,6 @@ import re import pprint import traceback -import signal class Restart(Exception): @@ -73,8 +72,6 @@ import readline except ImportError: pass - self.allow_kbdint = False - signal.signal(signal.SIGINT, self.sigint_handler) # Read $HOME/.pdbrc and ./.pdbrc self.rcLines = [] @@ -107,13 +104,6 @@ self.commands_bnum = None # The breakpoint number for which we are # defining a list - def sigint_handler(self, signum, frame): - if self.allow_kbdint: - raise KeyboardInterrupt() - print >>self.stdout, "\nProgram interrupted. (Use 'cont' to resume)." - self.set_step() - self.set_trace(frame) - def reset(self): bdb.Bdb.reset(self) self.forget() @@ -186,7 +176,7 @@ if not self.commands_silent[currentbp]: self.print_stack_entry(self.stack[self.curindex]) if self.commands_doprompt[currentbp]: - self._cmdloop() + self.cmdloop() self.forget() return return 1 @@ -209,22 +199,11 @@ self.interaction(frame, exc_traceback) # General interaction function - def _cmdloop(self): - while 1: - try: - # keyboard interrupts allow for an easy way to interrupt - # the current command - self.allow_kbdint = True - self.cmdloop() - self.allow_kbdint = False - break - except KeyboardInterrupt: - print >>self.stdout, '--KeyboardInterrupt--' def interaction(self, frame, traceback): self.setup(frame, traceback) self.print_stack_entry(self.stack[self.curindex]) - self._cmdloop() + self.cmdloop() self.forget() def displayhook(self, obj): @@ -350,22 +329,9 @@ prompt_back = self.prompt self.prompt = '(com) ' self.commands_defining = True - try: - self.cmdloop() - except (KeyboardInterrupt, IOError): - # It appears that that when pdb is reading input from a pipe - # we may get IOErrors, rather than KeyboardInterrupt. - # Now discard all the commands entered so far (essentially undo - # any effect of this "commands" cmd) - self.commands.pop(bnum) - self.commands_doprompt.pop(bnum) - self.commands_silent.pop(bnum) - # this will get caught by the _cmdloop and pdb will reenter - # the main command loop - raise KeyboardInterrupt() - finally: - self.commands_defining = False - self.prompt = prompt_back + self.cmdloop() + self.commands_defining = False + self.prompt = prompt_back def do_break(self, arg, temporary = 0): # break [ ([filename:]lineno | function) [, "condition"] ] Deleted: python/trunk/Lib/test/test_pdb2.py ============================================================================== --- python/trunk/Lib/test/test_pdb2.py Sun May 9 03:20:20 2010 +++ (empty file) @@ -1,197 +0,0 @@ -#!/usr/bin/env python -# pdb tests in the Lib/test style -import os -import sys -import time -import re -import subprocess -import signal -from test.test_support import TESTFN -import test.test_support -import unittest - -# allow alt pdb locations, if environment variable is specified then -# the test files will be stored in t/ directory and will not be deleted -# after pdb run -DEBUG_PDB = os.environ.get("_DEBUG_PDB", None) -TMP_DIR = "./t" # dir for tmp files if DEBUG_PDB is set - -if DEBUG_PDB: - if not os.path.exists(TMP_DIR): - os.mkdir(TMP_DIR) - -def _write_test_file(testname, text): - filename = TESTFN - if DEBUG_PDB: - filename = os.path.join(TMP_DIR, testname) - with open(filename, "wt") as f: - f.write(text+"\n") - return filename - - -class PdbProcess(object): - def __init__(self, testname, testprg): - self.testname = testname - self.filename = _write_test_file(testname, testprg) - # unbuffer pdb.py output (if it gets any ideas to buffer it) - # make sure that we use the same interpreter to run tests wrapper and - # pdb itself - cmd = [sys.executable, '-u'] - if DEBUG_PDB: - cmd.append(DEBUG_PDB) - else: - cmd.extend(['-m', 'pdb']) - cmd.append(self.filename) - self.pdbhandle = subprocess.Popen(cmd, bufsize=0, - stdin=subprocess.PIPE, - stdout=subprocess.PIPE, - stderr=subprocess.STDOUT) - self.startup_msg = self.wait_for_prompt() - self.finished=0 - - - def wait_for_normal_exit(self, timeout=2): - """wait for pdb subprocess to exit, timeout is in seconds""" - step = 0.1 - for i in range(int(timeout/step)): - status=self.pdbhandle.poll() - if status is not None: - break - time.sleep(step) - if status is -1: - describe = "pdb has not exited" - elif status> 0: - describe = "pdb exited abnormally with status=%d" % status - assert status == 0, describe - - def wait_for_line(self, stopline, alt_stopline=None): - output='' - line='' - while 1 : - ch=self.pdbhandle.stdout.read(1) - # sys.stdout.write(ch) - line += ch - if line == stopline or line == alt_stopline: - return output - if ch == '\n': - output += line - line='' - if ch == '':#eof - output += line - return output - - # note: this can block if issued at the wrong time - def wait_for_prompt(self): - """collect any output from pdb session til the prompt is encountered. - Return this output (exlcuding prompt)""" - return self.wait_for_line("(Pdb) ", "(com) ") - - def send_cmd(self, cmd): - """send a command but do not wait for response""" - #print "sending:", cmd - self.pdbhandle.stdin.write(cmd+"\n") - - - def cmd(self, cmd, response_text=""): - """send a single command to pdb, collect pdb response (by waiting - for the next prompt). Verify that response contains specified - response_text""" - - self.pdbhandle.stdin.write(cmd+"\n") - response = self.wait_for_prompt() - if not response_text: - return response - - if DEBUG_PDB: - print "%s: testing response for '%s':" % (self.testname,cmd), - assert response.find(response_text) >= 0, ( - "response:\n%s\n does not contain expected substring '%s'" % - (response, response_text)) - if DEBUG_PDB: - print "Ok" - return response - - def send_kbdint(self): - # os.kill is Posix-specific. We could have used a X-platform - # send_signal method of Popen objects, but it still cann't send - # SIGINT on win32 and it's not present on python2.5 - # self.pdbhandle.send_signal(signal.SIGINT) - os.kill(self.pdbhandle.pid, signal.SIGINT) - - def __del__(self): - # if pdb is still running, kill it, leaving it running does not serve - # any useful purpose - if self.pdbhandle.poll() is None: - self.pdbhandle.send_signal(signal.SIGTERM) - if not DEBUG_PDB: - os.unlink(self.filename) - return self.pdbhandle.wait() - - -class PdbTest(unittest.TestCase): - - def test_00startup(self): - pdb = PdbProcess("pdb_t_startup", "print 'Hello, world'") - pdb.cmd("r", "Hello, world") - pdb.cmd("q") - pdb.wait_for_normal_exit() - - @unittest.skipIf(sys.platform.startswith("win"), - "test_sigint requires a posix system.") - def test_sigint(self): - pdb = PdbProcess("pdb_t_loop", """\ -for i in xrange(100000000): - print 'i=%d' %i -""" ) - # first, test Ctrl-C/kbdint handling while the program is running - # kbdint should interrupt the program and return to pdb prompt, - # the program must be resumable - pdb.send_cmd("c") - # we could use time.sleep() delays but they are not reliable so you - # end up with making them much longer than necessary (and still failing - # from time to time) - pdb.wait_for_line("i=19") - pdb.send_kbdint() - pdb.wait_for_prompt() - response = pdb.cmd('p "i=%d" % i') - m = re.search('i=(\d+)', response) - assert m, "unexpected response %s" % response - i0 = int(m.group(1)) - pdb.send_cmd("c") - pdb.wait_for_line("i=%d" % (i0+99)) - pdb.send_kbdint() - pdb.wait_for_prompt() - response = pdb.cmd('p "i=%d" % i') - m = re.search('i=(\d+)', response) - assert m, "unexpected response %s" % response - i1 = int(m.group(1)) - assert i1 > i0 - # now test kbd interrupts in interactive mode, they should interrupt - # the current cmd - # simple case: just generate kdbint - pdb.send_kbdint() - pdb.wait_for_prompt() - pdb.cmd("p 'hello'", "hello") # check that we are at prompt - # more complicated case: Ctrl-C while defining bp commands - # interrupted commands should have no effect - pdb.cmd("b 2") - pdb.cmd("commands 1") - pdb.cmd("p 'marker'") - pdb.send_kbdint() - pdb.wait_for_prompt() - pdb.cmd("p 'hello'", "hello") # check that we are back at normal prompt - pdb.send_cmd("c") - response = pdb.wait_for_prompt() - assert not re.search("marker", response, re.I), ( - "unexpected response '%s'" % response) - pdb.cmd("p 'hello'", "hello") #check that we are back at prompt - pdb.send_cmd("q") - pdb.wait_for_normal_exit() - - -def test_main(): - test.test_support.run_unittest(PdbTest) - - -if __name__ == "__main__": - test_main() Modified: python/trunk/Misc/NEWS ============================================================================== --- python/trunk/Misc/NEWS (original) +++ python/trunk/Misc/NEWS Sun May 9 03:20:20 2010 @@ -15,8 +15,6 @@ Library ------- -- [issue7245] Better Ctrl-C support in pdb. - What's New in Python 2.7 beta 2? ================================ From python-checkins at python.org Sun May 9 05:15:34 2010 From: python-checkins at python.org (victor.stinner) Date: Sun, 9 May 2010 05:15:34 +0200 (CEST) Subject: [Python-checkins] r81014 - python/branches/py3k/Lib/test/test_os.py Message-ID: <20100509031534.1F01AEE9DA@mail.python.org> Author: victor.stinner Date: Sun May 9 05:15:33 2010 New Revision: 81014 Log: Write tests for the new function os.fsencode() Modified: python/branches/py3k/Lib/test/test_os.py Modified: python/branches/py3k/Lib/test/test_os.py ============================================================================== --- python/branches/py3k/Lib/test/test_os.py (original) +++ python/branches/py3k/Lib/test/test_os.py Sun May 9 05:15:33 2010 @@ -937,6 +937,13 @@ self._kill_with_event(signal.CTRL_BREAK_EVENT, "CTRL_BREAK_EVENT") +class MiscTests(unittest.TestCase): + @unittest.skipIf(sys.platform == "win32", "POSIX specific test") + def test_fsencode(self): + self.assertEquals(os.fsencode(b'ab\xff'), b'ab\xff') + self.assertEquals(os.fsencode('ab\uDCFF'), b'ab\xff') + + def test_main(): support.run_unittest( FileTests, @@ -951,7 +958,8 @@ TestInvalidFD, PosixUidGidTests, Pep383Tests, - Win32KillTests + Win32KillTests, + MiscTests, ) if __name__ == "__main__": From python-checkins at python.org Sun May 9 05:17:36 2010 From: python-checkins at python.org (victor.stinner) Date: Sun, 9 May 2010 05:17:36 +0200 (CEST) Subject: [Python-checkins] r81015 - python/branches/release31-maint Message-ID: <20100509031736.3FCDCF95A@mail.python.org> Author: victor.stinner Date: Sun May 9 05:17:36 2010 New Revision: 81015 Log: Blocked revisions 81014 via svnmerge ........ r81014 | victor.stinner | 2010-05-09 05:15:33 +0200 (dim., 09 mai 2010) | 2 lines Write tests for the new function os.fsencode() ........ Modified: python/branches/release31-maint/ (props changed) From python-checkins at python.org Sun May 9 05:18:57 2010 From: python-checkins at python.org (jean-paul.calderone) Date: Sun, 9 May 2010 05:18:57 +0200 (CEST) Subject: [Python-checkins] r81016 - in python/branches/py3k: Lib/test/test_signal.py Misc/NEWS Modules/signalmodule.c Python/pythonrun.c Message-ID: <20100509031857.E3663EE983@mail.python.org> Author: jean-paul.calderone Date: Sun May 9 05:18:57 2010 New Revision: 81016 Log: Merged revisions 81007 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r81007 | jean-paul.calderone | 2010-05-08 16:06:02 -0400 (Sat, 08 May 2010) | 1 line Skip signal handler re-installation if it is not necessary. Issue 8354. ........ Modified: python/branches/py3k/ (props changed) python/branches/py3k/Lib/test/test_signal.py python/branches/py3k/Misc/NEWS python/branches/py3k/Modules/signalmodule.c python/branches/py3k/Python/pythonrun.c Modified: python/branches/py3k/Lib/test/test_signal.py ============================================================================== --- python/branches/py3k/Lib/test/test_signal.py (original) +++ python/branches/py3k/Lib/test/test_signal.py Sun May 9 05:18:57 2010 @@ -255,48 +255,105 @@ class SiginterruptTest(unittest.TestCase): signum = signal.SIGUSR1 - def readpipe_interrupted(self, cb): + + def setUp(self): + """Install a no-op signal handler that can be set to allow + interrupts or not, and arrange for the original signal handler to be + re-installed when the test is finished. + """ + oldhandler = signal.signal(self.signum, lambda x,y: None) + self.addCleanup(signal.signal, self.signum, oldhandler) + + def readpipe_interrupted(self): + """Perform a read during which a signal will arrive. Return True if the + read is interrupted by the signal and raises an exception. Return False + if it returns normally. + """ + # Create a pipe that can be used for the read. Also clean it up + # when the test is over, since nothing else will (but see below for + # the write end). r, w = os.pipe() + self.addCleanup(os.close, r) + + # Create another process which can send a signal to this one to try + # to interrupt the read. ppid = os.getpid() pid = os.fork() - oldhandler = signal.signal(self.signum, lambda x,y: None) - cb() - if pid==0: - # child code: sleep, kill, sleep. and then exit, - # which closes the pipe from which the parent process reads + if pid == 0: + # Child code: sleep to give the parent enough time to enter the + # read() call (there's a race here, but it's really tricky to + # eliminate it); then signal the parent process. Also, sleep + # again to make it likely that the signal is delivered to the + # parent process before the child exits. If the child exits + # first, the write end of the pipe will be closed and the test + # is invalid. try: time.sleep(0.2) os.kill(ppid, self.signum) time.sleep(0.2) finally: + # No matter what, just exit as fast as possible now. exit_subprocess() - - try: + else: + # Parent code. + # Make sure the child is eventually reaped, else it'll be a + # zombie for the rest of the test suite run. + self.addCleanup(os.waitpid, pid, 0) + + # Close the write end of the pipe. The child has a copy, so + # it's not really closed until the child exits. We need it to + # close when the child exits so that in the non-interrupt case + # the read eventually completes, otherwise we could just close + # it *after* the test. os.close(w) + # Try the read and report whether it is interrupted or not to + # the caller. try: - d=os.read(r, 1) + d = os.read(r, 1) return False except OSError as err: if err.errno != errno.EINTR: raise return True - finally: - signal.signal(self.signum, oldhandler) - os.waitpid(pid, 0) def test_without_siginterrupt(self): - i=self.readpipe_interrupted(lambda: None) - self.assertEquals(i, True) + """If a signal handler is installed and siginterrupt is not called + at all, when that signal arrives, it interrupts a syscall that's in + progress. + """ + i = self.readpipe_interrupted() + self.assertTrue(i) + # Arrival of the signal shouldn't have changed anything. + i = self.readpipe_interrupted() + self.assertTrue(i) def test_siginterrupt_on(self): - i=self.readpipe_interrupted(lambda: signal.siginterrupt(self.signum, 1)) - self.assertEquals(i, True) + """If a signal handler is installed and siginterrupt is called with + a true value for the second argument, when that signal arrives, it + interrupts a syscall that's in progress. + """ + signal.siginterrupt(self.signum, 1) + i = self.readpipe_interrupted() + self.assertTrue(i) + # Arrival of the signal shouldn't have changed anything. + i = self.readpipe_interrupted() + self.assertTrue(i) def test_siginterrupt_off(self): - i=self.readpipe_interrupted(lambda: signal.siginterrupt(self.signum, 0)) - self.assertEquals(i, False) + """If a signal handler is installed and siginterrupt is called with + a false value for the second argument, when that signal arrives, it + does not interrupt a syscall that's in progress. + """ + signal.siginterrupt(self.signum, 0) + i = self.readpipe_interrupted() + self.assertFalse(i) + # Arrival of the signal shouldn't have changed anything. + i = self.readpipe_interrupted() + self.assertFalse(i) + + class ItimerTest(unittest.TestCase): def setUp(self): Modified: python/branches/py3k/Misc/NEWS ============================================================================== --- python/branches/py3k/Misc/NEWS (original) +++ python/branches/py3k/Misc/NEWS Sun May 9 05:18:57 2010 @@ -397,6 +397,9 @@ - Issue #4687: Fix accuracy of garbage collection runtimes displayed with gc.DEBUG_STATS. +- Issue #8354: The siginterrupt setting is now preserved for all signals, + not just SIGCHLD. + - Issue #7192: webbrowser.get("firefox") now wors on Mac OS X, as does webbrowser.get("safari"). Modified: python/branches/py3k/Modules/signalmodule.c ============================================================================== --- python/branches/py3k/Modules/signalmodule.c (original) +++ python/branches/py3k/Modules/signalmodule.c Sun May 9 05:18:57 2010 @@ -198,7 +198,12 @@ return; } #endif +#ifndef HAVE_SIGACTION + /* If the handler was not set up with sigaction, reinstall it. See + * Python/pythonrun.c for the implementation of PyOS_setsig which + * makes this true. See also issue8354. */ PyOS_setsig(sig_num, signal_handler); +#endif } Modified: python/branches/py3k/Python/pythonrun.c ============================================================================== --- python/branches/py3k/Python/pythonrun.c (original) +++ python/branches/py3k/Python/pythonrun.c Sun May 9 05:18:57 2010 @@ -2254,6 +2254,10 @@ PyOS_setsig(int sig, PyOS_sighandler_t handler) { #ifdef HAVE_SIGACTION + /* Some code in Modules/signalmodule.c depends on sigaction() being + * used here if HAVE_SIGACTION is defined. Fix that if this code + * changes to invalidate that assumption. + */ struct sigaction context, ocontext; context.sa_handler = handler; sigemptyset(&context.sa_mask); From python-checkins at python.org Sun May 9 05:22:58 2010 From: python-checkins at python.org (benjamin.peterson) Date: Sun, 9 May 2010 05:22:58 +0200 (CEST) Subject: [Python-checkins] r81017 - python/branches/py3k/Lib/test/test_os.py Message-ID: <20100509032258.79010EE9A0@mail.python.org> Author: benjamin.peterson Date: Sun May 9 05:22:58 2010 New Revision: 81017 Log: make condition more specific Modified: python/branches/py3k/Lib/test/test_os.py Modified: python/branches/py3k/Lib/test/test_os.py ============================================================================== --- python/branches/py3k/Lib/test/test_os.py (original) +++ python/branches/py3k/Lib/test/test_os.py Sun May 9 05:22:58 2010 @@ -938,7 +938,8 @@ class MiscTests(unittest.TestCase): - @unittest.skipIf(sys.platform == "win32", "POSIX specific test") + + @unittest.skipIf(os.name == "nt", "POSIX specific test") def test_fsencode(self): self.assertEquals(os.fsencode(b'ab\xff'), b'ab\xff') self.assertEquals(os.fsencode('ab\uDCFF'), b'ab\xff') From python-checkins at python.org Sun May 9 05:25:17 2010 From: python-checkins at python.org (jean-paul.calderone) Date: Sun, 9 May 2010 05:25:17 +0200 (CEST) Subject: [Python-checkins] r81018 - in python/branches/release31-maint: Lib/test/test_signal.py Misc/NEWS Modules/signalmodule.c Python/pythonrun.c Message-ID: <20100509032517.20206EE9F4@mail.python.org> Author: jean-paul.calderone Date: Sun May 9 05:25:16 2010 New Revision: 81018 Log: Merged revisions 81016 via svnmerge from svn+ssh://pythondev at svn.python.org/python/branches/py3k ................ r81016 | jean-paul.calderone | 2010-05-08 23:18:57 -0400 (Sat, 08 May 2010) | 9 lines Merged revisions 81007 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r81007 | jean-paul.calderone | 2010-05-08 16:06:02 -0400 (Sat, 08 May 2010) | 1 line Skip signal handler re-installation if it is not necessary. Issue 8354. ........ ................ Modified: python/branches/release31-maint/ (props changed) python/branches/release31-maint/Lib/test/test_signal.py python/branches/release31-maint/Misc/NEWS python/branches/release31-maint/Modules/signalmodule.c python/branches/release31-maint/Python/pythonrun.c Modified: python/branches/release31-maint/Lib/test/test_signal.py ============================================================================== --- python/branches/release31-maint/Lib/test/test_signal.py (original) +++ python/branches/release31-maint/Lib/test/test_signal.py Sun May 9 05:25:16 2010 @@ -255,48 +255,105 @@ class SiginterruptTest(unittest.TestCase): signum = signal.SIGUSR1 - def readpipe_interrupted(self, cb): + + def setUp(self): + """Install a no-op signal handler that can be set to allow + interrupts or not, and arrange for the original signal handler to be + re-installed when the test is finished. + """ + oldhandler = signal.signal(self.signum, lambda x,y: None) + self.addCleanup(signal.signal, self.signum, oldhandler) + + def readpipe_interrupted(self): + """Perform a read during which a signal will arrive. Return True if the + read is interrupted by the signal and raises an exception. Return False + if it returns normally. + """ + # Create a pipe that can be used for the read. Also clean it up + # when the test is over, since nothing else will (but see below for + # the write end). r, w = os.pipe() + self.addCleanup(os.close, r) + + # Create another process which can send a signal to this one to try + # to interrupt the read. ppid = os.getpid() pid = os.fork() - oldhandler = signal.signal(self.signum, lambda x,y: None) - cb() - if pid==0: - # child code: sleep, kill, sleep. and then exit, - # which closes the pipe from which the parent process reads + if pid == 0: + # Child code: sleep to give the parent enough time to enter the + # read() call (there's a race here, but it's really tricky to + # eliminate it); then signal the parent process. Also, sleep + # again to make it likely that the signal is delivered to the + # parent process before the child exits. If the child exits + # first, the write end of the pipe will be closed and the test + # is invalid. try: time.sleep(0.2) os.kill(ppid, self.signum) time.sleep(0.2) finally: + # No matter what, just exit as fast as possible now. exit_subprocess() - - try: + else: + # Parent code. + # Make sure the child is eventually reaped, else it'll be a + # zombie for the rest of the test suite run. + self.addCleanup(os.waitpid, pid, 0) + + # Close the write end of the pipe. The child has a copy, so + # it's not really closed until the child exits. We need it to + # close when the child exits so that in the non-interrupt case + # the read eventually completes, otherwise we could just close + # it *after* the test. os.close(w) + # Try the read and report whether it is interrupted or not to + # the caller. try: - d=os.read(r, 1) + d = os.read(r, 1) return False except OSError as err: if err.errno != errno.EINTR: raise return True - finally: - signal.signal(self.signum, oldhandler) - os.waitpid(pid, 0) def test_without_siginterrupt(self): - i=self.readpipe_interrupted(lambda: None) - self.assertEquals(i, True) + """If a signal handler is installed and siginterrupt is not called + at all, when that signal arrives, it interrupts a syscall that's in + progress. + """ + i = self.readpipe_interrupted() + self.assertTrue(i) + # Arrival of the signal shouldn't have changed anything. + i = self.readpipe_interrupted() + self.assertTrue(i) def test_siginterrupt_on(self): - i=self.readpipe_interrupted(lambda: signal.siginterrupt(self.signum, 1)) - self.assertEquals(i, True) + """If a signal handler is installed and siginterrupt is called with + a true value for the second argument, when that signal arrives, it + interrupts a syscall that's in progress. + """ + signal.siginterrupt(self.signum, 1) + i = self.readpipe_interrupted() + self.assertTrue(i) + # Arrival of the signal shouldn't have changed anything. + i = self.readpipe_interrupted() + self.assertTrue(i) def test_siginterrupt_off(self): - i=self.readpipe_interrupted(lambda: signal.siginterrupt(self.signum, 0)) - self.assertEquals(i, False) + """If a signal handler is installed and siginterrupt is called with + a false value for the second argument, when that signal arrives, it + does not interrupt a syscall that's in progress. + """ + signal.siginterrupt(self.signum, 0) + i = self.readpipe_interrupted() + self.assertFalse(i) + # Arrival of the signal shouldn't have changed anything. + i = self.readpipe_interrupted() + self.assertFalse(i) + + class ItimerTest(unittest.TestCase): def setUp(self): Modified: python/branches/release31-maint/Misc/NEWS ============================================================================== --- python/branches/release31-maint/Misc/NEWS (original) +++ python/branches/release31-maint/Misc/NEWS Sun May 9 05:25:16 2010 @@ -73,6 +73,9 @@ - Issue #4687: Fix accuracy of garbage collection runtimes displayed with gc.DEBUG_STATS. +- Issue #8354: The siginterrupt setting is now preserved for all signals, + not just SIGCHLD. + - Issue #8464: tarfile no longer creates files with execute permissions set when mode="w|" is used. Modified: python/branches/release31-maint/Modules/signalmodule.c ============================================================================== --- python/branches/release31-maint/Modules/signalmodule.c (original) +++ python/branches/release31-maint/Modules/signalmodule.c Sun May 9 05:25:16 2010 @@ -192,7 +192,12 @@ return; } #endif +#ifndef HAVE_SIGACTION + /* If the handler was not set up with sigaction, reinstall it. See + * Python/pythonrun.c for the implementation of PyOS_setsig which + * makes this true. See also issue8354. */ PyOS_setsig(sig_num, signal_handler); +#endif } Modified: python/branches/release31-maint/Python/pythonrun.c ============================================================================== --- python/branches/release31-maint/Python/pythonrun.c (original) +++ python/branches/release31-maint/Python/pythonrun.c Sun May 9 05:25:16 2010 @@ -2237,6 +2237,10 @@ PyOS_setsig(int sig, PyOS_sighandler_t handler) { #ifdef HAVE_SIGACTION + /* Some code in Modules/signalmodule.c depends on sigaction() being + * used here if HAVE_SIGACTION is defined. Fix that if this code + * changes to invalidate that assumption. + */ struct sigaction context, ocontext; context.sa_handler = handler; sigemptyset(&context.sa_mask); From python-checkins at python.org Sun May 9 05:36:42 2010 From: python-checkins at python.org (gregory.p.smith) Date: Sun, 9 May 2010 05:36:42 +0200 (CEST) Subject: [Python-checkins] r81019 - python/branches/py3k/Lib/test/test_os.py Message-ID: <20100509033642.822C0EE9C1@mail.python.org> Author: gregory.p.smith Date: Sun May 9 05:36:42 2010 New Revision: 81019 Log: Replace /s with os.sep in the new internal_execvpe test. Hopefully fixes this test on windows. Modified: python/branches/py3k/Lib/test/test_os.py Modified: python/branches/py3k/Lib/test/test_os.py ============================================================================== --- python/branches/py3k/Lib/test/test_os.py (original) +++ python/branches/py3k/Lib/test/test_os.py Sun May 9 05:36:42 2010 @@ -653,7 +653,7 @@ raise OSError(errno.ENOTDIR, "execve called") def _mock_get_exec_path(self, env=None): - return ['/p', '/pp'] + return [os.sep+'p', os.sep+'pp'] def __enter__(self): self.orig_execv = os.execv @@ -673,13 +673,16 @@ def test_internal_execvpe(self): exec_stubbed = self._stub_out_for_execvpe_test() with exec_stubbed: - self.assertRaises(RuntimeError, os._execvpe, '/f', ['-a']) - self.assertEqual([('execv', '/f', (['-a'],))], exec_stubbed.calls) + self.assertRaises(RuntimeError, os._execvpe, os.sep+'f', ['-a']) + self.assertEqual([('execv', os.sep+'f', (['-a'],))], + exec_stubbed.calls) exec_stubbed.calls = [] self.assertRaises(OSError, os._execvpe, 'f', ['-a'], env={'spam': 'beans'}) - self.assertEqual([('execve', '/p/f', (['-a'], {'spam': 'beans'})), - ('execve', '/pp/f', (['-a'], {'spam': 'beans'}))], + self.assertEqual([('execve', os.sep+'p'+os.sep+'f', + (['-a'], {'spam': 'beans'})), + ('execve', os.sep+'pp'+os.sep+'f', + (['-a'], {'spam': 'beans'}))], exec_stubbed.calls) class Win32ErrorTests(unittest.TestCase): From python-checkins at python.org Sun May 9 11:30:06 2010 From: python-checkins at python.org (mark.dickinson) Date: Sun, 9 May 2010 11:30:06 +0200 (CEST) Subject: [Python-checkins] r81020 - in python/trunk: Doc/library/datetime.rst Lib/test/test_datetime.py Misc/NEWS Modules/datetimemodule.c Message-ID: <20100509093006.55462EEA2A@mail.python.org> Author: mark.dickinson Date: Sun May 9 11:30:06 2010 New Revision: 81020 Log: Issue #8644: Improve accuracy of timedelta.total_seconds method. (Backport of r80979 to py3k.) Thanks Alexander Belopolsky. Modified: python/trunk/Doc/library/datetime.rst python/trunk/Lib/test/test_datetime.py python/trunk/Misc/NEWS python/trunk/Modules/datetimemodule.c Modified: python/trunk/Doc/library/datetime.rst ============================================================================== --- python/trunk/Doc/library/datetime.rst (original) +++ python/trunk/Doc/library/datetime.rst Sun May 9 11:30:06 2010 @@ -270,8 +270,12 @@ .. method:: timedelta.total_seconds() - Return the total number of seconds contained in the duration. Equivalent to - ``td.microseconds / 1000000 + td.seconds + td.days * 24 * 3600``. + Return the total number of seconds contained in the duration. + Equivalent to ``(td.microseconds + (td.seconds + td.days * 24 * + 3600) * 10**6) / 10**6`` computed with true division enabled. + + Note that for very large time intervals (greater than 270 years on + most platforms) this method will lose microsecond accuracy. .. versionadded:: 2.7 Modified: python/trunk/Lib/test/test_datetime.py ============================================================================== --- python/trunk/Lib/test/test_datetime.py (original) +++ python/trunk/Lib/test/test_datetime.py Sun May 9 11:30:06 2010 @@ -2,7 +2,7 @@ See http://www.zope.org/Members/fdrake/DateTimeWiki/TestCases """ - +from __future__ import division import os import pickle import cPickle @@ -269,6 +269,13 @@ for total_seconds in [123456.789012, -123456.789012, 0.123456, 0, 1e6]: td = timedelta(seconds=total_seconds) self.assertEqual(td.total_seconds(), total_seconds) + # Issue8644: Test that td.total_seconds() has the same + # accuracy as td / timedelta(seconds=1). + for ms in [-1, -2, -123]: + td = timedelta(microseconds=ms) + self.assertEqual(td.total_seconds(), + ((24*3600*td.days + td.seconds)*10**6 + + td.microseconds)/10**6) def test_carries(self): t1 = timedelta(days=100, Modified: python/trunk/Misc/NEWS ============================================================================== --- python/trunk/Misc/NEWS (original) +++ python/trunk/Misc/NEWS Sun May 9 11:30:06 2010 @@ -200,6 +200,8 @@ Extension Modules ----------------- +- Issue #8644: Improved accuracy of timedelta.total_seconds(). + - Use Clang 2.7's static analyzer to find places to clean up some code. - Build the ossaudio extension on GNU/kFreeBSD. Modified: python/trunk/Modules/datetimemodule.c ============================================================================== --- python/trunk/Modules/datetimemodule.c (original) +++ python/trunk/Modules/datetimemodule.c Sun May 9 11:30:06 2010 @@ -2096,9 +2096,25 @@ static PyObject * delta_total_seconds(PyObject *self) { - return PyFloat_FromDouble(GET_TD_MICROSECONDS(self) / 1000000.0 + - GET_TD_SECONDS(self) + - GET_TD_DAYS(self) * 24.0 * 3600.0); + PyObject *total_seconds; + PyObject *total_microseconds; + PyObject *one_million; + + total_microseconds = delta_to_microseconds((PyDateTime_Delta *)self); + if (total_microseconds == NULL) + return NULL; + + one_million = PyLong_FromLong(1000000L); + if (one_million == NULL) { + Py_DECREF(total_microseconds); + return NULL; + } + + total_seconds = PyNumber_TrueDivide(total_microseconds, one_million); + + Py_DECREF(total_microseconds); + Py_DECREF(one_million); + return total_seconds; } static PyObject * From python-checkins at python.org Sun May 9 11:30:54 2010 From: python-checkins at python.org (mark.dickinson) Date: Sun, 9 May 2010 11:30:54 +0200 (CEST) Subject: [Python-checkins] r81021 - python/branches/py3k Message-ID: <20100509093054.03BD9EEA38@mail.python.org> Author: mark.dickinson Date: Sun May 9 11:30:53 2010 New Revision: 81021 Log: Blocked revisions 81020 via svnmerge ........ r81020 | mark.dickinson | 2010-05-09 10:30:06 +0100 (Sun, 09 May 2010) | 3 lines Issue #8644: Improve accuracy of timedelta.total_seconds method. (Backport of r80979 to py3k.) Thanks Alexander Belopolsky. ........ Modified: python/branches/py3k/ (props changed) From python-checkins at python.org Sun May 9 11:58:25 2010 From: python-checkins at python.org (michael.foord) Date: Sun, 9 May 2010 11:58:25 +0200 (CEST) Subject: [Python-checkins] r81022 - python/trunk/Lib/unittest/test/test_suite.py Message-ID: <20100509095825.71B46EE99D@mail.python.org> Author: michael.foord Date: Sun May 9 11:58:25 2010 New Revision: 81022 Log: Adding a test for unittest.BaseTestSuite. Modified: python/trunk/Lib/unittest/test/test_suite.py Modified: python/trunk/Lib/unittest/test/test_suite.py ============================================================================== --- python/trunk/Lib/unittest/test/test_suite.py (original) +++ python/trunk/Lib/unittest/test/test_suite.py Sun May 9 11:58:25 2010 @@ -1,5 +1,6 @@ import unittest +import sys from .support import LoggingResult, TestEquality @@ -300,5 +301,49 @@ suite.run(unittest.TestResult()) + + def test_basetestsuite(self): + class Test(unittest.TestCase): + wasSetUp = False + wasTornDown = False + @classmethod + def setUpClass(cls): + cls.wasSetUp = True + @classmethod + def tearDownClass(cls): + cls.wasTornDown = True + def testPass(self): + pass + def testFail(self): + fail + class Module(object): + wasSetUp = False + wasTornDown = False + @staticmethod + def setUpModule(): + Module.wasSetUp = True + @staticmethod + def tearDownModule(): + Module.wasTornDown = True + + Test.__module__ = 'Module' + sys.modules['Module'] = Module + self.addCleanup(sys.modules.pop, 'Module') + + suite = unittest.BaseTestSuite() + suite.addTests([Test('testPass'), Test('testFail')]) + self.assertEqual(suite.countTestCases(), 2) + + result = unittest.TestResult() + suite.run(result) + self.assertFalse(Module.wasSetUp) + self.assertFalse(Module.wasTornDown) + self.assertFalse(Test.wasSetUp) + self.assertFalse(Test.wasTornDown) + self.assertEqual(len(result.errors), 1) + self.assertEqual(len(result.failures), 0) + self.assertEqual(result.testsRun, 2) + + if __name__ == '__main__': unittest.main() From python-checkins at python.org Sun May 9 11:59:35 2010 From: python-checkins at python.org (michael.foord) Date: Sun, 9 May 2010 11:59:35 +0200 (CEST) Subject: [Python-checkins] r81023 - in python/branches/py3k: Lib/unittest/test/test_suite.py Message-ID: <20100509095935.89C45EEA0A@mail.python.org> Author: michael.foord Date: Sun May 9 11:59:35 2010 New Revision: 81023 Log: Merged revisions 81022 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r81022 | michael.foord | 2010-05-09 11:58:25 +0200 (Sun, 09 May 2010) | 1 line Adding a test for unittest.BaseTestSuite. ........ Modified: python/branches/py3k/ (props changed) python/branches/py3k/Lib/unittest/test/test_suite.py Modified: python/branches/py3k/Lib/unittest/test/test_suite.py ============================================================================== --- python/branches/py3k/Lib/unittest/test/test_suite.py (original) +++ python/branches/py3k/Lib/unittest/test/test_suite.py Sun May 9 11:59:35 2010 @@ -1,5 +1,6 @@ import unittest +import sys from .support import LoggingResult, TestEquality @@ -300,5 +301,49 @@ suite.run(unittest.TestResult()) + + def test_basetestsuite(self): + class Test(unittest.TestCase): + wasSetUp = False + wasTornDown = False + @classmethod + def setUpClass(cls): + cls.wasSetUp = True + @classmethod + def tearDownClass(cls): + cls.wasTornDown = True + def testPass(self): + pass + def testFail(self): + fail + class Module(object): + wasSetUp = False + wasTornDown = False + @staticmethod + def setUpModule(): + Module.wasSetUp = True + @staticmethod + def tearDownModule(): + Module.wasTornDown = True + + Test.__module__ = 'Module' + sys.modules['Module'] = Module + self.addCleanup(sys.modules.pop, 'Module') + + suite = unittest.BaseTestSuite() + suite.addTests([Test('testPass'), Test('testFail')]) + self.assertEqual(suite.countTestCases(), 2) + + result = unittest.TestResult() + suite.run(result) + self.assertFalse(Module.wasSetUp) + self.assertFalse(Module.wasTornDown) + self.assertFalse(Test.wasSetUp) + self.assertFalse(Test.wasTornDown) + self.assertEqual(len(result.errors), 1) + self.assertEqual(len(result.failures), 0) + self.assertEqual(result.testsRun, 2) + + if __name__ == '__main__': unittest.main() From python-checkins at python.org Sun May 9 14:16:29 2010 From: python-checkins at python.org (mark.dickinson) Date: Sun, 9 May 2010 14:16:29 +0200 (CEST) Subject: [Python-checkins] r81024 - python/branches/py3k/Lib/urllib/request.py Message-ID: <20100509121629.8BF91EE985@mail.python.org> Author: mark.dickinson Date: Sun May 9 14:16:29 2010 New Revision: 81024 Log: Fix test_urllib2 failure on OS X. Modified: python/branches/py3k/Lib/urllib/request.py Modified: python/branches/py3k/Lib/urllib/request.py ============================================================================== --- python/branches/py3k/Lib/urllib/request.py (original) +++ python/branches/py3k/Lib/urllib/request.py Sun May 9 14:16:29 2010 @@ -2159,7 +2159,7 @@ def ip2num(ipAddr): parts = ipAddr.split('.') - parts = map(int, parts) + parts = list(map(int, parts)) if len(parts) != 4: parts = (parts + [0, 0, 0, 0])[:4] return (parts[0] << 24) | (parts[1] << 16) | (parts[2] << 8) | parts[3] From python-checkins at python.org Sun May 9 14:17:58 2010 From: python-checkins at python.org (mark.dickinson) Date: Sun, 9 May 2010 14:17:58 +0200 (CEST) Subject: [Python-checkins] r81025 - in python/branches/release31-maint: Lib/urllib/request.py Message-ID: <20100509121758.C453BEEA0E@mail.python.org> Author: mark.dickinson Date: Sun May 9 14:17:58 2010 New Revision: 81025 Log: Merged revisions 81024 via svnmerge from svn+ssh://pythondev at svn.python.org/python/branches/py3k ........ r81024 | mark.dickinson | 2010-05-09 13:16:29 +0100 (Sun, 09 May 2010) | 1 line Fix test_urllib2 failure on OS X. ........ Modified: python/branches/release31-maint/ (props changed) python/branches/release31-maint/Lib/urllib/request.py Modified: python/branches/release31-maint/Lib/urllib/request.py ============================================================================== --- python/branches/release31-maint/Lib/urllib/request.py (original) +++ python/branches/release31-maint/Lib/urllib/request.py Sun May 9 14:17:58 2010 @@ -2163,7 +2163,7 @@ def ip2num(ipAddr): parts = ipAddr.split('.') - parts = map(int, parts) + parts = list(map(int, parts)) if len(parts) != 4: parts = (parts + [0, 0, 0, 0])[:4] return (parts[0] << 24) | (parts[1] << 16) | (parts[2] << 8) | parts[3] From python-checkins at python.org Sun May 9 16:04:59 2010 From: python-checkins at python.org (eric.smith) Date: Sun, 9 May 2010 16:04:59 +0200 (CEST) Subject: [Python-checkins] r81026 - python/trunk/Doc/library/re.rst Message-ID: <20100509140459.BD509F9CC@mail.python.org> Author: eric.smith Date: Sun May 9 16:04:59 2010 New Revision: 81026 Log: Issue 8671: Whitespace fix. Modified: python/trunk/Doc/library/re.rst Modified: python/trunk/Doc/library/re.rst ============================================================================== --- python/trunk/Doc/library/re.rst (original) +++ python/trunk/Doc/library/re.rst Sun May 9 16:04:59 2010 @@ -319,7 +319,7 @@ Matches the empty string, but only at the beginning or end of a word. A word is defined as a sequence of alphanumeric or underscore characters, so the end of a word is indicated by whitespace or a non-alphanumeric, non-underscore character. - Note that ``\b`` is defined as the boundary between ``\w`` and ``\ W``, so the + Note that ``\b`` is defined as the boundary between ``\w`` and ``\W``, so the precise set of characters deemed to be alphanumeric depends on the values of the ``UNICODE`` and ``LOCALE`` flags. Inside a character range, ``\b`` represents the backspace character, for compatibility with Python's string literals. From python-checkins at python.org Sun May 9 16:07:57 2010 From: python-checkins at python.org (eric.smith) Date: Sun, 9 May 2010 16:07:57 +0200 (CEST) Subject: [Python-checkins] r81027 - in python/branches/release26-maint: Doc/library/re.rst Message-ID: <20100509140757.A32F9E574@mail.python.org> Author: eric.smith Date: Sun May 9 16:07:57 2010 New Revision: 81027 Log: Merged revisions 81026 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r81026 | eric.smith | 2010-05-09 10:04:59 -0400 (Sun, 09 May 2010) | 1 line Issue 8671: Whitespace fix. ........ Modified: python/branches/release26-maint/ (props changed) python/branches/release26-maint/Doc/library/re.rst Modified: python/branches/release26-maint/Doc/library/re.rst ============================================================================== --- python/branches/release26-maint/Doc/library/re.rst (original) +++ python/branches/release26-maint/Doc/library/re.rst Sun May 9 16:07:57 2010 @@ -319,7 +319,7 @@ Matches the empty string, but only at the beginning or end of a word. A word is defined as a sequence of alphanumeric or underscore characters, so the end of a word is indicated by whitespace or a non-alphanumeric, non-underscore character. - Note that ``\b`` is defined as the boundary between ``\w`` and ``\ W``, so the + Note that ``\b`` is defined as the boundary between ``\w`` and ``\W``, so the precise set of characters deemed to be alphanumeric depends on the values of the ``UNICODE`` and ``LOCALE`` flags. Inside a character range, ``\b`` represents the backspace character, for compatibility with Python's string literals. From python-checkins at python.org Sun May 9 16:09:25 2010 From: python-checkins at python.org (eric.smith) Date: Sun, 9 May 2010 16:09:25 +0200 (CEST) Subject: [Python-checkins] r81028 - python/branches/py3k Message-ID: <20100509140925.71068E574@mail.python.org> Author: eric.smith Date: Sun May 9 16:09:25 2010 New Revision: 81028 Log: Blocked revisions 81026 via svnmerge ........ r81026 | eric.smith | 2010-05-09 10:04:59 -0400 (Sun, 09 May 2010) | 1 line Issue 8671: Whitespace fix. ........ Modified: python/branches/py3k/ (props changed) From python-checkins at python.org Sun May 9 17:15:11 2010 From: python-checkins at python.org (antoine.pitrou) Date: Sun, 9 May 2010 17:15:11 +0200 (CEST) Subject: [Python-checkins] r81030 - python/trunk/PC/_msi.c Message-ID: <20100509151511.43E47EE983@mail.python.org> Author: antoine.pitrou Date: Sun May 9 17:15:11 2010 New Revision: 81030 Log: Fixup indentation of PC/_msi.c Modified: python/trunk/PC/_msi.c Modified: python/trunk/PC/_msi.c ============================================================================== --- python/trunk/PC/_msi.c (original) +++ python/trunk/PC/_msi.c Sun May 9 17:15:11 2010 @@ -26,13 +26,13 @@ For RPC_S_UUID_NO_ADDRESS, it's not clear whether we can use the result. */ if (UuidCreate(&result) == RPC_S_UUID_NO_ADDRESS) { - PyErr_SetString(PyExc_NotImplementedError, "processing 'no address' result"); - return NULL; + PyErr_SetString(PyExc_NotImplementedError, "processing 'no address' result"); + return NULL; } if (UuidToString(&result, &cresult) == RPC_S_OUT_OF_MEMORY) { - PyErr_SetString(PyExc_MemoryError, "out of memory in uuidgen"); - return NULL; + PyErr_SetString(PyExc_MemoryError, "out of memory in uuidgen"); + return NULL; } oresult = PyString_FromString(cresult); @@ -57,7 +57,7 @@ { int result = _open(pszFile, oflag, pmode); if (result == -1) - *err = errno; + *err = errno; return result; } @@ -65,7 +65,7 @@ { UINT result = (UINT)_read(hf, memory, cb); if (result != cb) - *err = errno; + *err = errno; return result; } @@ -73,7 +73,7 @@ { UINT result = (UINT)_write(hf, memory, cb); if (result != cb) - *err = errno; + *err = errno; return result; } @@ -81,7 +81,7 @@ { int result = _close(hf); if (result != 0) - *err = errno; + *err = errno; return result; } @@ -89,7 +89,7 @@ { long result = (long)_lseek(hf, dist, seektype); if (result == -1) - *err = errno; + *err = errno; return result; } @@ -97,7 +97,7 @@ { int result = remove(pszFile); if (result != 0) - *err = errno; + *err = errno; return result; } @@ -110,9 +110,9 @@ { char *name = _tempnam("", "tmp"); if ((name != NULL) && ((int)strlen(name) < cbTempName)) { - strcpy(pszTempName, name); - free(name); - return TRUE; + strcpy(pszTempName, name); + free(name); + return TRUE; } if (name) free(name); @@ -122,10 +122,10 @@ static FNFCISTATUS(cb_status) { if (pv) { - PyObject *result = PyObject_CallMethod(pv, "status", "iii", typeStatus, cb1, cb2); - if (result == NULL) - return -1; - Py_DECREF(result); + PyObject *result = PyObject_CallMethod(pv, "status", "iii", typeStatus, cb1, cb2); + if (result == NULL) + return -1; + Py_DECREF(result); } return 0; } @@ -133,18 +133,18 @@ static FNFCIGETNEXTCABINET(cb_getnextcabinet) { if (pv) { - PyObject *result = PyObject_CallMethod(pv, "getnextcabinet", "i", pccab->iCab); - if (result == NULL) - return -1; - if (!PyString_Check(result)) { - PyErr_Format(PyExc_TypeError, - "Incorrect return type %s from getnextcabinet", - result->ob_type->tp_name); - Py_DECREF(result); - return FALSE; - } - strncpy(pccab->szCab, PyString_AsString(result), sizeof(pccab->szCab)); - return TRUE; + PyObject *result = PyObject_CallMethod(pv, "getnextcabinet", "i", pccab->iCab); + if (result == NULL) + return -1; + if (!PyString_Check(result)) { + PyErr_Format(PyExc_TypeError, + "Incorrect return type %s from getnextcabinet", + result->ob_type->tp_name); + Py_DECREF(result); + return FALSE; + } + strncpy(pccab->szCab, PyString_AsString(result), sizeof(pccab->szCab)); + return TRUE; } return FALSE; } @@ -157,21 +157,21 @@ /* Need Win32 handle to get time stamps */ handle = CreateFile(pszName, GENERIC_READ, FILE_SHARE_READ, NULL, - OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL); + OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL); if (handle == INVALID_HANDLE_VALUE) - return -1; + return -1; if (GetFileInformationByHandle(handle, &bhfi) == FALSE) { - CloseHandle(handle); - return -1; + CloseHandle(handle); + return -1; } FileTimeToLocalFileTime(&bhfi.ftLastWriteTime, &filetime); FileTimeToDosDateTime(&filetime, pdate, ptime); *pattribs = (int)(bhfi.dwFileAttributes & - (_A_RDONLY | _A_SYSTEM | _A_HIDDEN | _A_ARCH)); + (_A_RDONLY | _A_SYSTEM | _A_HIDDEN | _A_ARCH)); CloseHandle(handle); @@ -189,11 +189,11 @@ if (!PyArg_ParseTuple(args, "sO:FCICreate", &cabname, &files)) - return NULL; + return NULL; if (!PyList_Check(files)) { - PyErr_SetString(PyExc_TypeError, "FCICreate expects a list"); - return NULL; + PyErr_SetString(PyExc_TypeError, "FCICreate expects a list"); + return NULL; } ccab.cb = INT_MAX; /* no need to split CAB into multiple media */ @@ -209,49 +209,49 @@ ccab.szDisk[0] = '\0'; for (i = 0, p = cabname; *p; p = CharNext(p)) - if (*p == '\\' || *p == '/') - i = p - cabname + 1; + if (*p == '\\' || *p == '/') + i = p - cabname + 1; if (i >= sizeof(ccab.szCabPath) || - strlen(cabname+i) >= sizeof(ccab.szCab)) { - PyErr_SetString(PyExc_ValueError, "path name too long"); - return 0; + strlen(cabname+i) >= sizeof(ccab.szCab)) { + PyErr_SetString(PyExc_ValueError, "path name too long"); + return 0; } if (i > 0) { - memcpy(ccab.szCabPath, cabname, i); - ccab.szCabPath[i] = '\0'; - strcpy(ccab.szCab, cabname+i); + memcpy(ccab.szCabPath, cabname, i); + ccab.szCabPath[i] = '\0'; + strcpy(ccab.szCab, cabname+i); } else { - strcpy(ccab.szCabPath, ".\\"); - strcpy(ccab.szCab, cabname); + strcpy(ccab.szCabPath, ".\\"); + strcpy(ccab.szCab, cabname); } hfci = FCICreate(&erf, cb_fileplaced, cb_alloc, cb_free, - cb_open, cb_read, cb_write, cb_close, cb_seek, cb_delete, - cb_gettempfile, &ccab, NULL); + cb_open, cb_read, cb_write, cb_close, cb_seek, cb_delete, + cb_gettempfile, &ccab, NULL); if (hfci == NULL) { - PyErr_Format(PyExc_ValueError, "FCI error %d", erf.erfOper); - return NULL; + PyErr_Format(PyExc_ValueError, "FCI error %d", erf.erfOper); + return NULL; } for (i=0; i < PyList_GET_SIZE(files); i++) { - PyObject *item = PyList_GET_ITEM(files, i); - char *filename, *cabname; - if (!PyArg_ParseTuple(item, "ss", &filename, &cabname)) - goto err; - if (!FCIAddFile(hfci, filename, cabname, FALSE, - cb_getnextcabinet, cb_status, cb_getopeninfo, - tcompTYPE_MSZIP)) - goto err; + PyObject *item = PyList_GET_ITEM(files, i); + char *filename, *cabname; + if (!PyArg_ParseTuple(item, "ss", &filename, &cabname)) + goto err; + if (!FCIAddFile(hfci, filename, cabname, FALSE, + cb_getnextcabinet, cb_status, cb_getopeninfo, + tcompTYPE_MSZIP)) + goto err; } if (!FCIFlushCabinet(hfci, FALSE, cb_getnextcabinet, cb_status)) - goto err; + goto err; if (!FCIDestroy(hfci)) - goto err; + goto err; Py_INCREF(Py_None); return Py_None; @@ -292,41 +292,41 @@ MSIHANDLE err = MsiGetLastErrorRecord(); if (err == 0) { - switch(status) { - case ERROR_ACCESS_DENIED: - PyErr_SetString(MSIError, "access denied"); - return NULL; - case ERROR_FUNCTION_FAILED: - PyErr_SetString(MSIError, "function failed"); - return NULL; - case ERROR_INVALID_DATA: - PyErr_SetString(MSIError, "invalid data"); - return NULL; - case ERROR_INVALID_HANDLE: - PyErr_SetString(MSIError, "invalid handle"); - return NULL; - case ERROR_INVALID_STATE: - PyErr_SetString(MSIError, "invalid state"); - return NULL; - case ERROR_INVALID_PARAMETER: - PyErr_SetString(MSIError, "invalid parameter"); - return NULL; - default: - PyErr_Format(MSIError, "unknown error %x", status); - return NULL; - } + switch(status) { + case ERROR_ACCESS_DENIED: + PyErr_SetString(MSIError, "access denied"); + return NULL; + case ERROR_FUNCTION_FAILED: + PyErr_SetString(MSIError, "function failed"); + return NULL; + case ERROR_INVALID_DATA: + PyErr_SetString(MSIError, "invalid data"); + return NULL; + case ERROR_INVALID_HANDLE: + PyErr_SetString(MSIError, "invalid handle"); + return NULL; + case ERROR_INVALID_STATE: + PyErr_SetString(MSIError, "invalid state"); + return NULL; + case ERROR_INVALID_PARAMETER: + PyErr_SetString(MSIError, "invalid parameter"); + return NULL; + default: + PyErr_Format(MSIError, "unknown error %x", status); + return NULL; + } } code = MsiRecordGetInteger(err, 1); /* XXX code */ if (MsiFormatRecord(0, err, res, &size) == ERROR_MORE_DATA) { - res = malloc(size+1); - MsiFormatRecord(0, err, res, &size); - res[size]='\0'; + res = malloc(size+1); + MsiFormatRecord(0, err, res, &size); + res[size]='\0'; } MsiCloseHandle(err); PyErr_SetString(MSIError, res); if (res != buf) - free(res); + free(res); return NULL; } @@ -345,11 +345,11 @@ int status; if (!PyArg_ParseTuple(args, "I:GetInteger", &field)) - return NULL; + return NULL; status = MsiRecordGetInteger(record->h, field); if (status == MSI_NULL_INTEGER){ - PyErr_SetString(MSIError, "could not convert record field to integer"); - return NULL; + PyErr_SetString(MSIError, "could not convert record field to integer"); + return NULL; } return PyInt_FromLong((long) status); } @@ -365,19 +365,19 @@ PyObject* string; if (!PyArg_ParseTuple(args, "I:GetString", &field)) - return NULL; + return NULL; status = MsiRecordGetString(record->h, field, res, &size); if (status == ERROR_MORE_DATA) { - res = (char*) malloc(size + 1); - if (res == NULL) - return PyErr_NoMemory(); - status = MsiRecordGetString(record->h, field, res, &size); + res = (char*) malloc(size + 1); + if (res == NULL) + return PyErr_NoMemory(); + status = MsiRecordGetString(record->h, field, res, &size); } if (status != ERROR_SUCCESS) - return msierror((int) status); + return msierror((int) status); string = PyString_FromString(res); if (buf != res) - free(res); + free(res); return string; } @@ -386,7 +386,7 @@ { int status = MsiRecordClearData(record->h); if (status != ERROR_SUCCESS) - return msierror(status); + return msierror(status); Py_INCREF(Py_None); return Py_None; @@ -400,10 +400,10 @@ char *data; if (!PyArg_ParseTuple(args, "is:SetString", &field, &data)) - return NULL; + return NULL; if ((status = MsiRecordSetString(record->h, field, data)) != ERROR_SUCCESS) - return msierror(status); + return msierror(status); Py_INCREF(Py_None); return Py_None; @@ -417,10 +417,10 @@ char *data; if (!PyArg_ParseTuple(args, "is:SetStream", &field, &data)) - return NULL; + return NULL; if ((status = MsiRecordSetStream(record->h, field, data)) != ERROR_SUCCESS) - return msierror(status); + return msierror(status); Py_INCREF(Py_None); return Py_None; @@ -434,10 +434,10 @@ int data; if (!PyArg_ParseTuple(args, "ii:SetInteger", &field, &data)) - return NULL; + return NULL; if ((status = MsiRecordSetInteger(record->h, field, data)) != ERROR_SUCCESS) - return msierror(status); + return msierror(status); Py_INCREF(Py_None); return Py_None; @@ -447,64 +447,64 @@ static PyMethodDef record_methods[] = { { "GetFieldCount", (PyCFunction)record_getfieldcount, METH_NOARGS, - PyDoc_STR("GetFieldCount() -> int\nWraps MsiRecordGetFieldCount")}, + PyDoc_STR("GetFieldCount() -> int\nWraps MsiRecordGetFieldCount")}, { "GetInteger", (PyCFunction)record_getinteger, METH_VARARGS, PyDoc_STR("GetInteger(field) -> int\nWraps MsiRecordGetInteger")}, { "GetString", (PyCFunction)record_getstring, METH_VARARGS, PyDoc_STR("GetString(field) -> string\nWraps MsiRecordGetString")}, { "SetString", (PyCFunction)record_setstring, METH_VARARGS, - PyDoc_STR("SetString(field,str) -> None\nWraps MsiRecordSetString")}, + PyDoc_STR("SetString(field,str) -> None\nWraps MsiRecordSetString")}, { "SetStream", (PyCFunction)record_setstream, METH_VARARGS, - PyDoc_STR("SetStream(field,filename) -> None\nWraps MsiRecordSetInteger")}, + PyDoc_STR("SetStream(field,filename) -> None\nWraps MsiRecordSetInteger")}, { "SetInteger", (PyCFunction)record_setinteger, METH_VARARGS, - PyDoc_STR("SetInteger(field,int) -> None\nWraps MsiRecordSetInteger")}, + PyDoc_STR("SetInteger(field,int) -> None\nWraps MsiRecordSetInteger")}, { "ClearData", (PyCFunction)record_cleardata, METH_NOARGS, - PyDoc_STR("ClearData() -> int\nWraps MsiRecordGClearData")}, + PyDoc_STR("ClearData() -> int\nWraps MsiRecordGClearData")}, { NULL, NULL } }; static PyTypeObject record_Type = { - PyVarObject_HEAD_INIT(NULL, 0) - "_msi.Record", /*tp_name*/ - sizeof(msiobj), /*tp_basicsize*/ - 0, /*tp_itemsize*/ - /* methods */ - (destructor)msiobj_dealloc, /*tp_dealloc*/ - 0, /*tp_print*/ - 0, /*tp_getattr*/ - 0, /*tp_setattr*/ - 0, /*tp_compare*/ - 0, /*tp_repr*/ - 0, /*tp_as_number*/ - 0, /*tp_as_sequence*/ - 0, /*tp_as_mapping*/ - 0, /*tp_hash*/ - 0, /*tp_call*/ - 0, /*tp_str*/ - PyObject_GenericGetAttr,/*tp_getattro*/ - PyObject_GenericSetAttr,/*tp_setattro*/ - 0, /*tp_as_buffer*/ - Py_TPFLAGS_DEFAULT, /*tp_flags*/ - 0, /*tp_doc*/ - 0, /*tp_traverse*/ - 0, /*tp_clear*/ - 0, /*tp_richcompare*/ - 0, /*tp_weaklistoffset*/ - 0, /*tp_iter*/ - 0, /*tp_iternext*/ - record_methods, /*tp_methods*/ - 0, /*tp_members*/ - 0, /*tp_getset*/ - 0, /*tp_base*/ - 0, /*tp_dict*/ - 0, /*tp_descr_get*/ - 0, /*tp_descr_set*/ - 0, /*tp_dictoffset*/ - 0, /*tp_init*/ - 0, /*tp_alloc*/ - 0, /*tp_new*/ - 0, /*tp_free*/ - 0, /*tp_is_gc*/ + PyVarObject_HEAD_INIT(NULL, 0) + "_msi.Record", /*tp_name*/ + sizeof(msiobj), /*tp_basicsize*/ + 0, /*tp_itemsize*/ + /* methods */ + (destructor)msiobj_dealloc, /*tp_dealloc*/ + 0, /*tp_print*/ + 0, /*tp_getattr*/ + 0, /*tp_setattr*/ + 0, /*tp_compare*/ + 0, /*tp_repr*/ + 0, /*tp_as_number*/ + 0, /*tp_as_sequence*/ + 0, /*tp_as_mapping*/ + 0, /*tp_hash*/ + 0, /*tp_call*/ + 0, /*tp_str*/ + PyObject_GenericGetAttr,/*tp_getattro*/ + PyObject_GenericSetAttr,/*tp_setattro*/ + 0, /*tp_as_buffer*/ + Py_TPFLAGS_DEFAULT, /*tp_flags*/ + 0, /*tp_doc*/ + 0, /*tp_traverse*/ + 0, /*tp_clear*/ + 0, /*tp_richcompare*/ + 0, /*tp_weaklistoffset*/ + 0, /*tp_iter*/ + 0, /*tp_iternext*/ + record_methods, /*tp_methods*/ + 0, /*tp_members*/ + 0, /*tp_getset*/ + 0, /*tp_base*/ + 0, /*tp_dict*/ + 0, /*tp_descr_get*/ + 0, /*tp_descr_set*/ + 0, /*tp_dictoffset*/ + 0, /*tp_init*/ + 0, /*tp_alloc*/ + 0, /*tp_new*/ + 0, /*tp_free*/ + 0, /*tp_is_gc*/ }; static PyObject* @@ -513,8 +513,8 @@ msiobj *result = PyObject_NEW(struct msiobj, &record_Type); if (!result) { - MsiCloseHandle(h); - return NULL; + MsiCloseHandle(h); + return NULL; } result->h = h; @@ -537,27 +537,27 @@ DWORD ssize = sizeof(sval); if (!PyArg_ParseTuple(args, "i:GetProperty", &field)) - return NULL; + return NULL; status = MsiSummaryInfoGetProperty(si->h, field, &type, &ival, - &fval, sval, &ssize); - if (status == ERROR_MORE_DATA) { - sval = malloc(ssize); - status = MsiSummaryInfoGetProperty(si->h, field, &type, &ival, &fval, sval, &ssize); + if (status == ERROR_MORE_DATA) { + sval = malloc(ssize); + status = MsiSummaryInfoGetProperty(si->h, field, &type, &ival, + &fval, sval, &ssize); } switch(type) { - case VT_I2: case VT_I4: - return PyInt_FromLong(ival); - case VT_FILETIME: - PyErr_SetString(PyExc_NotImplementedError, "FILETIME result"); - return NULL; - case VT_LPSTR: - result = PyString_FromStringAndSize(sval, ssize); - if (sval != sbuf) - free(sval); - return result; + case VT_I2: case VT_I4: + return PyInt_FromLong(ival); + case VT_FILETIME: + PyErr_SetString(PyExc_NotImplementedError, "FILETIME result"); + return NULL; + case VT_LPSTR: + result = PyString_FromStringAndSize(sval, ssize); + if (sval != sbuf) + free(sval); + return result; } PyErr_Format(PyExc_NotImplementedError, "result of type %d", type); return NULL; @@ -571,7 +571,7 @@ status = MsiSummaryInfoGetPropertyCount(si->h, &result); if (status != ERROR_SUCCESS) - return msierror(status); + return msierror(status); return PyInt_FromLong(result); } @@ -584,21 +584,21 @@ PyObject* data; if (!PyArg_ParseTuple(args, "iO:SetProperty", &field, &data)) - return NULL; + return NULL; if (PyString_Check(data)) { - status = MsiSummaryInfoSetProperty(si->h, field, VT_LPSTR, - 0, NULL, PyString_AsString(data)); + status = MsiSummaryInfoSetProperty(si->h, field, VT_LPSTR, + 0, NULL, PyString_AsString(data)); } else if (PyInt_Check(data)) { - status = MsiSummaryInfoSetProperty(si->h, field, VT_I4, - PyInt_AsLong(data), NULL, NULL); + status = MsiSummaryInfoSetProperty(si->h, field, VT_I4, + PyInt_AsLong(data), NULL, NULL); } else { - PyErr_SetString(PyExc_TypeError, "unsupported type"); - return NULL; + PyErr_SetString(PyExc_TypeError, "unsupported type"); + return NULL; } if (status != ERROR_SUCCESS) - return msierror(status); + return msierror(status); Py_INCREF(Py_None); return Py_None; @@ -612,65 +612,65 @@ status = MsiSummaryInfoPersist(si->h); if (status != ERROR_SUCCESS) - return msierror(status); + return msierror(status); Py_INCREF(Py_None); return Py_None; } static PyMethodDef summary_methods[] = { { "GetProperty", (PyCFunction)summary_getproperty, METH_VARARGS, - PyDoc_STR("GetProperty(propid) -> value\nWraps MsiSummaryInfoGetProperty")}, + PyDoc_STR("GetProperty(propid) -> value\nWraps MsiSummaryInfoGetProperty")}, { "GetPropertyCount", (PyCFunction)summary_getpropertycount, METH_NOARGS, - PyDoc_STR("GetProperty() -> int\nWraps MsiSummaryInfoGetPropertyCount")}, + PyDoc_STR("GetProperty() -> int\nWraps MsiSummaryInfoGetPropertyCount")}, { "SetProperty", (PyCFunction)summary_setproperty, METH_VARARGS, - PyDoc_STR("SetProperty(value) -> None\nWraps MsiSummaryInfoProperty")}, + PyDoc_STR("SetProperty(value) -> None\nWraps MsiSummaryInfoProperty")}, { "Persist", (PyCFunction)summary_persist, METH_NOARGS, - PyDoc_STR("Persist() -> None\nWraps MsiSummaryInfoPersist")}, + PyDoc_STR("Persist() -> None\nWraps MsiSummaryInfoPersist")}, { NULL, NULL } }; static PyTypeObject summary_Type = { - PyVarObject_HEAD_INIT(NULL, 0) - "_msi.SummaryInformation", /*tp_name*/ - sizeof(msiobj), /*tp_basicsize*/ - 0, /*tp_itemsize*/ - /* methods */ - (destructor)msiobj_dealloc, /*tp_dealloc*/ - 0, /*tp_print*/ - 0, /*tp_getattr*/ - 0, /*tp_setattr*/ - 0, /*tp_compare*/ - 0, /*tp_repr*/ - 0, /*tp_as_number*/ - 0, /*tp_as_sequence*/ - 0, /*tp_as_mapping*/ - 0, /*tp_hash*/ - 0, /*tp_call*/ - 0, /*tp_str*/ - PyObject_GenericGetAttr,/*tp_getattro*/ - PyObject_GenericSetAttr,/*tp_setattro*/ - 0, /*tp_as_buffer*/ - Py_TPFLAGS_DEFAULT, /*tp_flags*/ - 0, /*tp_doc*/ - 0, /*tp_traverse*/ - 0, /*tp_clear*/ - 0, /*tp_richcompare*/ - 0, /*tp_weaklistoffset*/ - 0, /*tp_iter*/ - 0, /*tp_iternext*/ - summary_methods, /*tp_methods*/ - 0, /*tp_members*/ - 0, /*tp_getset*/ - 0, /*tp_base*/ - 0, /*tp_dict*/ - 0, /*tp_descr_get*/ - 0, /*tp_descr_set*/ - 0, /*tp_dictoffset*/ - 0, /*tp_init*/ - 0, /*tp_alloc*/ - 0, /*tp_new*/ - 0, /*tp_free*/ - 0, /*tp_is_gc*/ + PyVarObject_HEAD_INIT(NULL, 0) + "_msi.SummaryInformation", /*tp_name*/ + sizeof(msiobj), /*tp_basicsize*/ + 0, /*tp_itemsize*/ + /* methods */ + (destructor)msiobj_dealloc, /*tp_dealloc*/ + 0, /*tp_print*/ + 0, /*tp_getattr*/ + 0, /*tp_setattr*/ + 0, /*tp_compare*/ + 0, /*tp_repr*/ + 0, /*tp_as_number*/ + 0, /*tp_as_sequence*/ + 0, /*tp_as_mapping*/ + 0, /*tp_hash*/ + 0, /*tp_call*/ + 0, /*tp_str*/ + PyObject_GenericGetAttr,/*tp_getattro*/ + PyObject_GenericSetAttr,/*tp_setattro*/ + 0, /*tp_as_buffer*/ + Py_TPFLAGS_DEFAULT, /*tp_flags*/ + 0, /*tp_doc*/ + 0, /*tp_traverse*/ + 0, /*tp_clear*/ + 0, /*tp_richcompare*/ + 0, /*tp_weaklistoffset*/ + 0, /*tp_iter*/ + 0, /*tp_iternext*/ + summary_methods, /*tp_methods*/ + 0, /*tp_members*/ + 0, /*tp_getset*/ + 0, /*tp_base*/ + 0, /*tp_dict*/ + 0, /*tp_descr_get*/ + 0, /*tp_descr_set*/ + 0, /*tp_dictoffset*/ + 0, /*tp_init*/ + 0, /*tp_alloc*/ + 0, /*tp_new*/ + 0, /*tp_free*/ + 0, /*tp_is_gc*/ }; /*************************** View objects **************/ @@ -683,19 +683,19 @@ PyObject *oparams = Py_None; if (!PyArg_ParseTuple(args, "O:Execute", &oparams)) - return NULL; + return NULL; if (oparams != Py_None) { - if (oparams->ob_type != &record_Type) { - PyErr_SetString(PyExc_TypeError, "Execute argument must be a record"); - return NULL; - } - params = ((msiobj*)oparams)->h; + if (oparams->ob_type != &record_Type) { + PyErr_SetString(PyExc_TypeError, "Execute argument must be a record"); + return NULL; + } + params = ((msiobj*)oparams)->h; } status = MsiViewExecute(view->h, params); if (status != ERROR_SUCCESS) - return msierror(status); + return msierror(status); Py_INCREF(Py_None); return Py_None; @@ -708,7 +708,7 @@ MSIHANDLE result; if ((status = MsiViewFetch(view->h, &result)) != ERROR_SUCCESS) - return msierror(status); + return msierror(status); return record_new(result); } @@ -721,10 +721,10 @@ MSIHANDLE result; if (!PyArg_ParseTuple(args, "i:GetColumnInfo", &kind)) - return NULL; + return NULL; if ((status = MsiViewGetColumnInfo(view->h, kind, &result)) != ERROR_SUCCESS) - return msierror(status); + return msierror(status); return record_new(result); } @@ -737,15 +737,15 @@ int status; if (!PyArg_ParseTuple(args, "iO:Modify", &kind, &data)) - return NULL; + return NULL; if (data->ob_type != &record_Type) { - PyErr_SetString(PyExc_TypeError, "Modify expects a record object"); - return NULL; + PyErr_SetString(PyExc_TypeError, "Modify expects a record object"); + return NULL; } if ((status = MsiViewModify(view->h, kind, ((msiobj*)data)->h)) != ERROR_SUCCESS) - return msierror(status); + return msierror(status); Py_INCREF(Py_None); return Py_None; @@ -757,7 +757,7 @@ int status; if ((status = MsiViewClose(view->h)) != ERROR_SUCCESS) - return msierror(status); + return msierror(status); Py_INCREF(Py_None); return Py_None; @@ -765,60 +765,60 @@ static PyMethodDef view_methods[] = { { "Execute", (PyCFunction)view_execute, METH_VARARGS, - PyDoc_STR("Execute(params=None) -> None\nWraps MsiViewExecute")}, + PyDoc_STR("Execute(params=None) -> None\nWraps MsiViewExecute")}, { "GetColumnInfo", (PyCFunction)view_getcolumninfo, METH_VARARGS, - PyDoc_STR("GetColumnInfo() -> result\nWraps MsiGetColumnInfo")}, + PyDoc_STR("GetColumnInfo() -> result\nWraps MsiGetColumnInfo")}, { "Fetch", (PyCFunction)view_fetch, METH_NOARGS, - PyDoc_STR("Fetch() -> result\nWraps MsiViewFetch")}, + PyDoc_STR("Fetch() -> result\nWraps MsiViewFetch")}, { "Modify", (PyCFunction)view_modify, METH_VARARGS, - PyDoc_STR("Modify(mode,record) -> None\nWraps MsiViewModify")}, + PyDoc_STR("Modify(mode,record) -> None\nWraps MsiViewModify")}, { "Close", (PyCFunction)view_close, METH_NOARGS, - PyDoc_STR("Close() -> result\nWraps MsiViewClose")}, + PyDoc_STR("Close() -> result\nWraps MsiViewClose")}, { NULL, NULL } }; static PyTypeObject msiview_Type = { - PyVarObject_HEAD_INIT(NULL, 0) - "_msi.View", /*tp_name*/ - sizeof(msiobj), /*tp_basicsize*/ - 0, /*tp_itemsize*/ - /* methods */ - (destructor)msiobj_dealloc, /*tp_dealloc*/ - 0, /*tp_print*/ - 0, /*tp_getattr*/ - 0, /*tp_setattr*/ - 0, /*tp_compare*/ - 0, /*tp_repr*/ - 0, /*tp_as_number*/ - 0, /*tp_as_sequence*/ - 0, /*tp_as_mapping*/ - 0, /*tp_hash*/ - 0, /*tp_call*/ - 0, /*tp_str*/ - PyObject_GenericGetAttr,/*tp_getattro*/ - PyObject_GenericSetAttr,/*tp_setattro*/ - 0, /*tp_as_buffer*/ - Py_TPFLAGS_DEFAULT, /*tp_flags*/ - 0, /*tp_doc*/ - 0, /*tp_traverse*/ - 0, /*tp_clear*/ - 0, /*tp_richcompare*/ - 0, /*tp_weaklistoffset*/ - 0, /*tp_iter*/ - 0, /*tp_iternext*/ - view_methods, /*tp_methods*/ - 0, /*tp_members*/ - 0, /*tp_getset*/ - 0, /*tp_base*/ - 0, /*tp_dict*/ - 0, /*tp_descr_get*/ - 0, /*tp_descr_set*/ - 0, /*tp_dictoffset*/ - 0, /*tp_init*/ - 0, /*tp_alloc*/ - 0, /*tp_new*/ - 0, /*tp_free*/ - 0, /*tp_is_gc*/ + PyVarObject_HEAD_INIT(NULL, 0) + "_msi.View", /*tp_name*/ + sizeof(msiobj), /*tp_basicsize*/ + 0, /*tp_itemsize*/ + /* methods */ + (destructor)msiobj_dealloc, /*tp_dealloc*/ + 0, /*tp_print*/ + 0, /*tp_getattr*/ + 0, /*tp_setattr*/ + 0, /*tp_compare*/ + 0, /*tp_repr*/ + 0, /*tp_as_number*/ + 0, /*tp_as_sequence*/ + 0, /*tp_as_mapping*/ + 0, /*tp_hash*/ + 0, /*tp_call*/ + 0, /*tp_str*/ + PyObject_GenericGetAttr,/*tp_getattro*/ + PyObject_GenericSetAttr,/*tp_setattro*/ + 0, /*tp_as_buffer*/ + Py_TPFLAGS_DEFAULT, /*tp_flags*/ + 0, /*tp_doc*/ + 0, /*tp_traverse*/ + 0, /*tp_clear*/ + 0, /*tp_richcompare*/ + 0, /*tp_weaklistoffset*/ + 0, /*tp_iter*/ + 0, /*tp_iternext*/ + view_methods, /*tp_methods*/ + 0, /*tp_members*/ + 0, /*tp_getset*/ + 0, /*tp_base*/ + 0, /*tp_dict*/ + 0, /*tp_descr_get*/ + 0, /*tp_descr_set*/ + 0, /*tp_dictoffset*/ + 0, /*tp_init*/ + 0, /*tp_alloc*/ + 0, /*tp_new*/ + 0, /*tp_free*/ + 0, /*tp_is_gc*/ }; /*************************** Database objects **************/ @@ -832,15 +832,15 @@ msiobj *result; if (!PyArg_ParseTuple(args, "s:OpenView", &sql)) - return NULL; + return NULL; if ((status = MsiDatabaseOpenView(msidb->h, sql, &hView)) != ERROR_SUCCESS) - return msierror(status); + return msierror(status); result = PyObject_NEW(struct msiobj, &msiview_Type); if (!result) { - MsiCloseHandle(hView); - return NULL; + MsiCloseHandle(hView); + return NULL; } result->h = hView; @@ -853,7 +853,7 @@ int status; if ((status = MsiDatabaseCommit(msidb->h)) != ERROR_SUCCESS) - return msierror(status); + return msierror(status); Py_INCREF(Py_None); return Py_None; @@ -868,16 +868,16 @@ msiobj *oresult; if (!PyArg_ParseTuple(args, "i:GetSummaryInformation", &count)) - return NULL; + return NULL; status = MsiGetSummaryInformation(db->h, NULL, count, &result); if (status != ERROR_SUCCESS) - return msierror(status); + return msierror(status); oresult = PyObject_NEW(struct msiobj, &summary_Type); if (!result) { - MsiCloseHandle(result); - return NULL; + MsiCloseHandle(result); + return NULL; } oresult->h = result; @@ -886,56 +886,56 @@ static PyMethodDef db_methods[] = { { "OpenView", (PyCFunction)msidb_openview, METH_VARARGS, - PyDoc_STR("OpenView(sql) -> viewobj\nWraps MsiDatabaseOpenView")}, + PyDoc_STR("OpenView(sql) -> viewobj\nWraps MsiDatabaseOpenView")}, { "Commit", (PyCFunction)msidb_commit, METH_NOARGS, - PyDoc_STR("Commit() -> None\nWraps MsiDatabaseCommit")}, + PyDoc_STR("Commit() -> None\nWraps MsiDatabaseCommit")}, { "GetSummaryInformation", (PyCFunction)msidb_getsummaryinformation, METH_VARARGS, - PyDoc_STR("GetSummaryInformation(updateCount) -> viewobj\nWraps MsiGetSummaryInformation")}, + PyDoc_STR("GetSummaryInformation(updateCount) -> viewobj\nWraps MsiGetSummaryInformation")}, { NULL, NULL } }; static PyTypeObject msidb_Type = { - PyVarObject_HEAD_INIT(NULL, 0) - "_msi.Database", /*tp_name*/ - sizeof(msiobj), /*tp_basicsize*/ - 0, /*tp_itemsize*/ - /* methods */ - (destructor)msiobj_dealloc, /*tp_dealloc*/ - 0, /*tp_print*/ - 0, /*tp_getattr*/ - 0, /*tp_setattr*/ - 0, /*tp_compare*/ - 0, /*tp_repr*/ - 0, /*tp_as_number*/ - 0, /*tp_as_sequence*/ - 0, /*tp_as_mapping*/ - 0, /*tp_hash*/ - 0, /*tp_call*/ - 0, /*tp_str*/ - PyObject_GenericGetAttr,/*tp_getattro*/ - PyObject_GenericSetAttr,/*tp_setattro*/ - 0, /*tp_as_buffer*/ - Py_TPFLAGS_DEFAULT, /*tp_flags*/ - 0, /*tp_doc*/ - 0, /*tp_traverse*/ - 0, /*tp_clear*/ - 0, /*tp_richcompare*/ - 0, /*tp_weaklistoffset*/ - 0, /*tp_iter*/ - 0, /*tp_iternext*/ - db_methods, /*tp_methods*/ - 0, /*tp_members*/ - 0, /*tp_getset*/ - 0, /*tp_base*/ - 0, /*tp_dict*/ - 0, /*tp_descr_get*/ - 0, /*tp_descr_set*/ - 0, /*tp_dictoffset*/ - 0, /*tp_init*/ - 0, /*tp_alloc*/ - 0, /*tp_new*/ - 0, /*tp_free*/ - 0, /*tp_is_gc*/ + PyVarObject_HEAD_INIT(NULL, 0) + "_msi.Database", /*tp_name*/ + sizeof(msiobj), /*tp_basicsize*/ + 0, /*tp_itemsize*/ + /* methods */ + (destructor)msiobj_dealloc, /*tp_dealloc*/ + 0, /*tp_print*/ + 0, /*tp_getattr*/ + 0, /*tp_setattr*/ + 0, /*tp_compare*/ + 0, /*tp_repr*/ + 0, /*tp_as_number*/ + 0, /*tp_as_sequence*/ + 0, /*tp_as_mapping*/ + 0, /*tp_hash*/ + 0, /*tp_call*/ + 0, /*tp_str*/ + PyObject_GenericGetAttr,/*tp_getattro*/ + PyObject_GenericSetAttr,/*tp_setattro*/ + 0, /*tp_as_buffer*/ + Py_TPFLAGS_DEFAULT, /*tp_flags*/ + 0, /*tp_doc*/ + 0, /*tp_traverse*/ + 0, /*tp_clear*/ + 0, /*tp_richcompare*/ + 0, /*tp_weaklistoffset*/ + 0, /*tp_iter*/ + 0, /*tp_iternext*/ + db_methods, /*tp_methods*/ + 0, /*tp_members*/ + 0, /*tp_getset*/ + 0, /*tp_base*/ + 0, /*tp_dict*/ + 0, /*tp_descr_get*/ + 0, /*tp_descr_set*/ + 0, /*tp_dictoffset*/ + 0, /*tp_init*/ + 0, /*tp_alloc*/ + 0, /*tp_new*/ + 0, /*tp_free*/ + 0, /*tp_is_gc*/ }; static PyObject* msiopendb(PyObject *obj, PyObject *args) @@ -947,16 +947,16 @@ msiobj *result; if (!PyArg_ParseTuple(args, "si:MSIOpenDatabase", &path, &persist)) - return NULL; + return NULL; - status = MsiOpenDatabase(path, (LPCSTR)persist, &h); + status = MsiOpenDatabase(path, (LPCSTR)persist, &h); if (status != ERROR_SUCCESS) - return msierror(status); + return msierror(status); result = PyObject_NEW(struct msiobj, &msidb_Type); if (!result) { - MsiCloseHandle(h); - return NULL; + MsiCloseHandle(h); + return NULL; } result->h = h; return (PyObject*)result; @@ -969,26 +969,26 @@ MSIHANDLE h; if (!PyArg_ParseTuple(args, "i:CreateRecord", &count)) - return NULL; + return NULL; h = MsiCreateRecord(count); if (h == 0) - return msierror(0); + return msierror(0); return record_new(h); } static PyMethodDef msi_methods[] = { - {"UuidCreate", (PyCFunction)uuidcreate, METH_NOARGS, - PyDoc_STR("UuidCreate() -> string")}, - {"FCICreate", (PyCFunction)fcicreate, METH_VARARGS, - PyDoc_STR("fcicreate(cabname,files) -> None")}, - {"OpenDatabase", (PyCFunction)msiopendb, METH_VARARGS, - PyDoc_STR("OpenDatabase(name, flags) -> dbobj\nWraps MsiOpenDatabase")}, - {"CreateRecord", (PyCFunction)createrecord, METH_VARARGS, - PyDoc_STR("OpenDatabase(name, flags) -> dbobj\nWraps MsiCreateRecord")}, - {NULL, NULL} /* sentinel */ + {"UuidCreate", (PyCFunction)uuidcreate, METH_NOARGS, + PyDoc_STR("UuidCreate() -> string")}, + {"FCICreate", (PyCFunction)fcicreate, METH_VARARGS, + PyDoc_STR("fcicreate(cabname,files) -> None")}, + {"OpenDatabase", (PyCFunction)msiopendb, METH_VARARGS, + PyDoc_STR("OpenDatabase(name, flags) -> dbobj\nWraps MsiOpenDatabase")}, + {"CreateRecord", (PyCFunction)createrecord, METH_VARARGS, + PyDoc_STR("OpenDatabase(name, flags) -> dbobj\nWraps MsiCreateRecord")}, + {NULL, NULL} /* sentinel */ }; static char msi_doc[] = "Documentation"; @@ -1000,7 +1000,7 @@ m = Py_InitModule3("_msi", msi_methods, msi_doc); if (m == NULL) - return; + return; PyModule_AddIntConstant(m, "MSIDBOPEN_CREATEDIRECT", (int)MSIDBOPEN_CREATEDIRECT); PyModule_AddIntConstant(m, "MSIDBOPEN_CREATE", (int)MSIDBOPEN_CREATE); @@ -1046,6 +1046,6 @@ MSIError = PyErr_NewException ("_msi.MSIError", NULL, NULL); if (!MSIError) - return; + return; PyModule_AddObject(m, "MSIError", MSIError); } From python-checkins at python.org Sun May 9 17:52:38 2010 From: python-checkins at python.org (antoine.pitrou) Date: Sun, 9 May 2010 17:52:38 +0200 (CEST) Subject: [Python-checkins] r81032 - in python/branches/py3k: Demo/embed/demo.c Demo/embed/loop.c Demo/pysvr/pysvr.c Include/abstract.h Include/ceval.h Include/datetime.h Include/descrobject.h Include/dictobject.h Include/object.h Include/objimpl.h Include/pyerrors.h Include/pymacconfig.h Include/pyport.h Include/pythonrun.h Include/setobject.h Include/structseq.h Include/symtable.h Include/unicodeobject.h Mac/Tools/pythonw.c Misc/setuid-prog.c Modules/_bisectmodule.c Modules/_codecsmodule.c Modules/_collectionsmodule.c Modules/_csv.c Modules/_ctypes/_ctypes.c Modules/_ctypes/_ctypes_test.c Modules/_ctypes/callbacks.c Modules/_ctypes/callproc.c Modules/_ctypes/cfield.c Modules/_ctypes/ctypes.h Modules/_ctypes/darwin/dlfcn_simple.c Modules/_ctypes/malloc_closure.c Modules/_ctypes/stgdict.c Modules/_curses_panel.c Modules/_dbmmodule.c Modules/_functoolsmodule.c Modules/_gdbmmodule.c Modules/_gestalt.c Modules/_heapqmodule.c Modules/_json.c Modules/_localemodule.c Modules/_lsprof.c Modules/_math.c Modules/_multiprocessing/connection.h Modules/_multiprocessing/multiprocessing.c Modules/_multiprocessing/multiprocessing.h Modules/_multiprocessing/pipe_connection.c Modules/_multiprocessing/semaphore.c Modules/_multiprocessing/socket_connection.c Modules/_multiprocessing/win32_functions.c Modules/_randommodule.c Modules/_scproxy.c Modules/_sqlite/module.c Modules/_struct.c Modules/_testcapimodule.c Modules/_threadmodule.c Modules/_tkinter.c Modules/addrinfo.h Modules/arraymodule.c Modules/audioop.c Modules/binascii.c Modules/bz2module.c Modules/cjkcodecs/_codecs_cn.c Modules/cjkcodecs/_codecs_hk.c Modules/cjkcodecs/_codecs_iso2022.c Modules/cjkcodecs/_codecs_jp.c Modules/cjkcodecs/_codecs_kr.c Modules/cjkcodecs/_codecs_tw.c Modules/cjkcodecs/alg_jisx0201.h Modules/cjkcodecs/cjkcodecs.h Modules/cjkcodecs/emu_jisx0213_2000.h Modules/cjkcodecs/multibytecodec.c Modules/cjkcodecs/multibytecodec.h Modules/cmathmodule.c Modules/cryptmodule.c Modules/datetimemodule.c Modules/errnomodule.c Modules/fcntlmodule.c Modules/fpectlmodule.c Modules/fpetestmodule.c Modules/gcmodule.c Modules/getaddrinfo.c Modules/getbuildinfo.c Modules/getnameinfo.c Modules/getpath.c Modules/grpmodule.c Modules/itertoolsmodule.c Modules/main.c Modules/mathmodule.c Modules/md5module.c Modules/mmapmodule.c Modules/nismodule.c Modules/operator.c Modules/ossaudiodev.c Modules/parsermodule.c Modules/pwdmodule.c Modules/pyexpat.c Modules/python.c Modules/readline.c Modules/resource.c Modules/rotatingtree.c Modules/selectmodule.c Modules/sha1module.c Modules/sha256module.c Modules/sha512module.c Modules/signalmodule.c Modules/socketmodule.c Modules/socketmodule.h Modules/spwdmodule.c Modules/symtablemodule.c Modules/syslogmodule.c Modules/termios.c Modules/testcapi_long.h Modules/timemodule.c Modules/tkappinit.c Modules/unicodedata.c Modules/xxmodule.c Modules/xxsubtype.c Modules/zipimport.c Modules/zlibmodule.c Objects/abstract.c Objects/boolobject.c Objects/bytes_methods.c Objects/bytesobject.c Objects/cellobject.c Objects/classobject.c Objects/codeobject.c Objects/complexobject.c Objects/descrobject.c Objects/dictobject.c Objects/enumobject.c Objects/exceptions.c Objects/fileobject.c Objects/floatobject.c Objects/frameobject.c Objects/funcobject.c Objects/genobject.c Objects/iterobject.c Objects/listobject.c Objects/longobject.c Objects/methodobject.c Objects/moduleobject.c Objects/object.c Objects/obmalloc.c Objects/rangeobject.c Objects/setobject.c Objects/sliceobject.c Objects/stringlib/eq.h Objects/stringlib/string_format.h Objects/structseq.c Objects/tupleobject.c Objects/typeobject.c Objects/weakrefobject.c PC/VS7.1/make_buildinfo.c PC/VS8.0/make_buildinfo.c PC/_msi.c PC/_subprocess.c PC/bdist_wininst/archive.h PC/bdist_wininst/extract.c PC/bdist_wininst/install.c PC/config.c PC/dl_nt.c PC/errmap.h PC/example_nt/example.c PC/frozen_dllmain.c PC/generrmap.c PC/getpathp.c PC/import_nt.c PC/make_versioninfo.c PC/msvcrtmodule.c PC/os2emx/config.c PC/os2emx/dlfcn.c PC/os2emx/dllentry.c PC/os2emx/getpathp.c PC/os2emx/pythonpm.c PC/os2vacpp/getpathp.c PC/winreg.c PC/winsound.c PCbuild/make_buildinfo.c Parser/acceler.c Parser/bitset.c Parser/firstsets.c Parser/grammar.c Parser/grammar1.c Parser/intrcheck.c Parser/listnode.c Parser/metagrammar.c Parser/myreadline.c Parser/node.c Parser/parser.c Parser/parsetok.c Parser/pgen.c Parser/pgenmain.c Parser/printgrammar.c Parser/tokenizer.c Parser/tokenizer.h Python/_warnings.c Python/asdl.c Python/ast.c Python/bltinmodule.c Python/ceval.c Python/codecs.c Python/compile.c Python/dynload_aix.c Python/dynload_hpux.c Python/dynload_next.c Python/dynload_os2.c Python/dynload_shlib.c Python/dynload_win.c Python/errors.c Python/frozen.c Python/frozenmain.c Python/future.c Python/getargs.c Python/getcwd.c Python/getopt.c Python/import.c Python/importdl.c Python/importdl.h Python/makeopcodetargets.py Python/marshal.c Python/modsupport.c Python/mysnprintf.c Python/mystrtoul.c Python/opcode_targets.h Python/peephole.c Python/pyarena.c Python/pymath.c Python/pystate.c Python/pystrcmp.c Python/pystrtod.c Python/pythonrun.c Python/structmember.c Python/symtable.c Python/sysmodule.c Python/thread.c Python/thread_cthread.h Python/thread_foobar.h Python/thread_lwp.h Python/thread_nt.h Python/thread_os2.h Python/thread_pth.h Python/thread_pthread.h Python/thread_sgi.h Python/thread_solaris.h Python/thread_wince.h Python/traceback.c Tools/msi/msisupport.c Message-ID: <20100509155238.864D7EE98B@mail.python.org> Author: antoine.pitrou Date: Sun May 9 17:52:27 2010 New Revision: 81032 Log: Recorded merge of revisions 81029 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r81029 | antoine.pitrou | 2010-05-09 16:46:46 +0200 (dim., 09 mai 2010) | 3 lines Untabify C files. Will watch buildbots. ........ Modified: python/branches/py3k/ (props changed) python/branches/py3k/Demo/embed/demo.c python/branches/py3k/Demo/embed/loop.c python/branches/py3k/Demo/pysvr/pysvr.c python/branches/py3k/Include/abstract.h python/branches/py3k/Include/ceval.h python/branches/py3k/Include/datetime.h python/branches/py3k/Include/descrobject.h python/branches/py3k/Include/dictobject.h python/branches/py3k/Include/object.h python/branches/py3k/Include/objimpl.h python/branches/py3k/Include/pyerrors.h python/branches/py3k/Include/pymacconfig.h python/branches/py3k/Include/pyport.h python/branches/py3k/Include/pythonrun.h python/branches/py3k/Include/setobject.h python/branches/py3k/Include/structseq.h python/branches/py3k/Include/symtable.h python/branches/py3k/Include/unicodeobject.h python/branches/py3k/Mac/Tools/pythonw.c python/branches/py3k/Misc/setuid-prog.c python/branches/py3k/Modules/_bisectmodule.c python/branches/py3k/Modules/_codecsmodule.c python/branches/py3k/Modules/_collectionsmodule.c python/branches/py3k/Modules/_csv.c python/branches/py3k/Modules/_ctypes/_ctypes.c python/branches/py3k/Modules/_ctypes/_ctypes_test.c python/branches/py3k/Modules/_ctypes/callbacks.c python/branches/py3k/Modules/_ctypes/callproc.c python/branches/py3k/Modules/_ctypes/cfield.c python/branches/py3k/Modules/_ctypes/ctypes.h python/branches/py3k/Modules/_ctypes/darwin/dlfcn_simple.c python/branches/py3k/Modules/_ctypes/malloc_closure.c python/branches/py3k/Modules/_ctypes/stgdict.c python/branches/py3k/Modules/_curses_panel.c python/branches/py3k/Modules/_dbmmodule.c python/branches/py3k/Modules/_functoolsmodule.c python/branches/py3k/Modules/_gdbmmodule.c python/branches/py3k/Modules/_gestalt.c python/branches/py3k/Modules/_heapqmodule.c python/branches/py3k/Modules/_json.c python/branches/py3k/Modules/_localemodule.c python/branches/py3k/Modules/_lsprof.c python/branches/py3k/Modules/_math.c python/branches/py3k/Modules/_multiprocessing/connection.h python/branches/py3k/Modules/_multiprocessing/multiprocessing.c python/branches/py3k/Modules/_multiprocessing/multiprocessing.h python/branches/py3k/Modules/_multiprocessing/pipe_connection.c python/branches/py3k/Modules/_multiprocessing/semaphore.c python/branches/py3k/Modules/_multiprocessing/socket_connection.c python/branches/py3k/Modules/_multiprocessing/win32_functions.c python/branches/py3k/Modules/_randommodule.c python/branches/py3k/Modules/_scproxy.c python/branches/py3k/Modules/_sqlite/module.c python/branches/py3k/Modules/_struct.c python/branches/py3k/Modules/_testcapimodule.c python/branches/py3k/Modules/_threadmodule.c python/branches/py3k/Modules/_tkinter.c python/branches/py3k/Modules/addrinfo.h python/branches/py3k/Modules/arraymodule.c python/branches/py3k/Modules/audioop.c python/branches/py3k/Modules/binascii.c python/branches/py3k/Modules/bz2module.c python/branches/py3k/Modules/cjkcodecs/_codecs_cn.c python/branches/py3k/Modules/cjkcodecs/_codecs_hk.c python/branches/py3k/Modules/cjkcodecs/_codecs_iso2022.c python/branches/py3k/Modules/cjkcodecs/_codecs_jp.c python/branches/py3k/Modules/cjkcodecs/_codecs_kr.c python/branches/py3k/Modules/cjkcodecs/_codecs_tw.c python/branches/py3k/Modules/cjkcodecs/alg_jisx0201.h python/branches/py3k/Modules/cjkcodecs/cjkcodecs.h python/branches/py3k/Modules/cjkcodecs/emu_jisx0213_2000.h python/branches/py3k/Modules/cjkcodecs/multibytecodec.c python/branches/py3k/Modules/cjkcodecs/multibytecodec.h python/branches/py3k/Modules/cmathmodule.c python/branches/py3k/Modules/cryptmodule.c python/branches/py3k/Modules/datetimemodule.c python/branches/py3k/Modules/errnomodule.c python/branches/py3k/Modules/fcntlmodule.c python/branches/py3k/Modules/fpectlmodule.c python/branches/py3k/Modules/fpetestmodule.c python/branches/py3k/Modules/gcmodule.c python/branches/py3k/Modules/getaddrinfo.c python/branches/py3k/Modules/getbuildinfo.c python/branches/py3k/Modules/getnameinfo.c python/branches/py3k/Modules/getpath.c python/branches/py3k/Modules/grpmodule.c python/branches/py3k/Modules/itertoolsmodule.c python/branches/py3k/Modules/main.c python/branches/py3k/Modules/mathmodule.c python/branches/py3k/Modules/md5module.c python/branches/py3k/Modules/mmapmodule.c python/branches/py3k/Modules/nismodule.c python/branches/py3k/Modules/operator.c python/branches/py3k/Modules/ossaudiodev.c python/branches/py3k/Modules/parsermodule.c python/branches/py3k/Modules/pwdmodule.c python/branches/py3k/Modules/pyexpat.c python/branches/py3k/Modules/python.c python/branches/py3k/Modules/readline.c python/branches/py3k/Modules/resource.c python/branches/py3k/Modules/rotatingtree.c python/branches/py3k/Modules/selectmodule.c python/branches/py3k/Modules/sha1module.c python/branches/py3k/Modules/sha256module.c python/branches/py3k/Modules/sha512module.c python/branches/py3k/Modules/signalmodule.c python/branches/py3k/Modules/socketmodule.c python/branches/py3k/Modules/socketmodule.h python/branches/py3k/Modules/spwdmodule.c python/branches/py3k/Modules/symtablemodule.c python/branches/py3k/Modules/syslogmodule.c python/branches/py3k/Modules/termios.c python/branches/py3k/Modules/testcapi_long.h python/branches/py3k/Modules/timemodule.c python/branches/py3k/Modules/tkappinit.c python/branches/py3k/Modules/unicodedata.c python/branches/py3k/Modules/xxmodule.c python/branches/py3k/Modules/xxsubtype.c python/branches/py3k/Modules/zipimport.c python/branches/py3k/Modules/zlibmodule.c python/branches/py3k/Objects/abstract.c python/branches/py3k/Objects/boolobject.c python/branches/py3k/Objects/bytes_methods.c python/branches/py3k/Objects/bytesobject.c python/branches/py3k/Objects/cellobject.c python/branches/py3k/Objects/classobject.c python/branches/py3k/Objects/codeobject.c python/branches/py3k/Objects/complexobject.c python/branches/py3k/Objects/descrobject.c python/branches/py3k/Objects/dictobject.c python/branches/py3k/Objects/enumobject.c python/branches/py3k/Objects/exceptions.c python/branches/py3k/Objects/fileobject.c python/branches/py3k/Objects/floatobject.c python/branches/py3k/Objects/frameobject.c python/branches/py3k/Objects/funcobject.c python/branches/py3k/Objects/genobject.c python/branches/py3k/Objects/iterobject.c python/branches/py3k/Objects/listobject.c python/branches/py3k/Objects/longobject.c python/branches/py3k/Objects/methodobject.c python/branches/py3k/Objects/moduleobject.c python/branches/py3k/Objects/object.c python/branches/py3k/Objects/obmalloc.c python/branches/py3k/Objects/rangeobject.c python/branches/py3k/Objects/setobject.c python/branches/py3k/Objects/sliceobject.c python/branches/py3k/Objects/stringlib/eq.h python/branches/py3k/Objects/stringlib/string_format.h python/branches/py3k/Objects/structseq.c python/branches/py3k/Objects/tupleobject.c python/branches/py3k/Objects/typeobject.c python/branches/py3k/Objects/weakrefobject.c python/branches/py3k/PC/VS7.1/make_buildinfo.c python/branches/py3k/PC/VS8.0/make_buildinfo.c python/branches/py3k/PC/_msi.c python/branches/py3k/PC/_subprocess.c python/branches/py3k/PC/bdist_wininst/archive.h python/branches/py3k/PC/bdist_wininst/extract.c python/branches/py3k/PC/bdist_wininst/install.c python/branches/py3k/PC/config.c python/branches/py3k/PC/dl_nt.c python/branches/py3k/PC/errmap.h python/branches/py3k/PC/example_nt/example.c python/branches/py3k/PC/frozen_dllmain.c python/branches/py3k/PC/generrmap.c python/branches/py3k/PC/getpathp.c python/branches/py3k/PC/import_nt.c python/branches/py3k/PC/make_versioninfo.c python/branches/py3k/PC/msvcrtmodule.c python/branches/py3k/PC/os2emx/config.c python/branches/py3k/PC/os2emx/dlfcn.c python/branches/py3k/PC/os2emx/dllentry.c python/branches/py3k/PC/os2emx/getpathp.c python/branches/py3k/PC/os2emx/pythonpm.c python/branches/py3k/PC/os2vacpp/getpathp.c python/branches/py3k/PC/winreg.c python/branches/py3k/PC/winsound.c python/branches/py3k/PCbuild/make_buildinfo.c python/branches/py3k/Parser/acceler.c python/branches/py3k/Parser/bitset.c python/branches/py3k/Parser/firstsets.c python/branches/py3k/Parser/grammar.c python/branches/py3k/Parser/grammar1.c python/branches/py3k/Parser/intrcheck.c python/branches/py3k/Parser/listnode.c python/branches/py3k/Parser/metagrammar.c python/branches/py3k/Parser/myreadline.c python/branches/py3k/Parser/node.c python/branches/py3k/Parser/parser.c python/branches/py3k/Parser/parsetok.c python/branches/py3k/Parser/pgen.c python/branches/py3k/Parser/pgenmain.c python/branches/py3k/Parser/printgrammar.c python/branches/py3k/Parser/tokenizer.c python/branches/py3k/Parser/tokenizer.h python/branches/py3k/Python/_warnings.c python/branches/py3k/Python/asdl.c python/branches/py3k/Python/ast.c python/branches/py3k/Python/bltinmodule.c python/branches/py3k/Python/ceval.c python/branches/py3k/Python/codecs.c python/branches/py3k/Python/compile.c python/branches/py3k/Python/dynload_aix.c python/branches/py3k/Python/dynload_hpux.c python/branches/py3k/Python/dynload_next.c python/branches/py3k/Python/dynload_os2.c python/branches/py3k/Python/dynload_shlib.c python/branches/py3k/Python/dynload_win.c python/branches/py3k/Python/errors.c python/branches/py3k/Python/frozen.c python/branches/py3k/Python/frozenmain.c python/branches/py3k/Python/future.c python/branches/py3k/Python/getargs.c python/branches/py3k/Python/getcwd.c python/branches/py3k/Python/getopt.c python/branches/py3k/Python/import.c python/branches/py3k/Python/importdl.c python/branches/py3k/Python/importdl.h python/branches/py3k/Python/makeopcodetargets.py python/branches/py3k/Python/marshal.c python/branches/py3k/Python/modsupport.c python/branches/py3k/Python/mysnprintf.c python/branches/py3k/Python/mystrtoul.c python/branches/py3k/Python/opcode_targets.h python/branches/py3k/Python/peephole.c python/branches/py3k/Python/pyarena.c python/branches/py3k/Python/pymath.c python/branches/py3k/Python/pystate.c python/branches/py3k/Python/pystrcmp.c python/branches/py3k/Python/pystrtod.c python/branches/py3k/Python/pythonrun.c python/branches/py3k/Python/structmember.c python/branches/py3k/Python/symtable.c python/branches/py3k/Python/sysmodule.c python/branches/py3k/Python/thread.c python/branches/py3k/Python/thread_cthread.h python/branches/py3k/Python/thread_foobar.h python/branches/py3k/Python/thread_lwp.h python/branches/py3k/Python/thread_nt.h python/branches/py3k/Python/thread_os2.h python/branches/py3k/Python/thread_pth.h python/branches/py3k/Python/thread_pthread.h python/branches/py3k/Python/thread_sgi.h python/branches/py3k/Python/thread_solaris.h python/branches/py3k/Python/thread_wince.h python/branches/py3k/Python/traceback.c python/branches/py3k/Tools/msi/msisupport.c Modified: python/branches/py3k/Demo/embed/demo.c ============================================================================== --- python/branches/py3k/Demo/embed/demo.c (original) +++ python/branches/py3k/Demo/embed/demo.c Sun May 9 17:52:27 2010 @@ -6,44 +6,44 @@ main(int argc, char **argv) { - /* Ignore passed-in argc/argv. If desired, conversion - should use mbstowcs to convert them. */ - wchar_t *args[] = {L"embed", L"hello", 0}; - - /* Pass argv[0] to the Python interpreter */ - Py_SetProgramName(args[0]); - - /* Add a static module */ - PyImport_AppendInittab("xyzzy", PyInit_xyzzy); - - /* Initialize the Python interpreter. Required. */ - Py_Initialize(); - - /* Define sys.argv. It is up to the application if you - want this; you can also let it undefined (since the Python - code is generally not a main program it has no business - touching sys.argv...) */ - PySys_SetArgv(2, args); - - /* Do some application specific code */ - printf("Hello, brave new world\n\n"); - - /* Execute some Python statements (in module __main__) */ - PyRun_SimpleString("import sys\n"); - PyRun_SimpleString("print(sys.builtin_module_names)\n"); - PyRun_SimpleString("print(sys.modules.keys())\n"); - PyRun_SimpleString("print(sys.executable)\n"); - PyRun_SimpleString("print(sys.argv)\n"); - - /* Note that you can call any public function of the Python - interpreter here, e.g. call_object(). */ - - /* Some more application specific code */ - printf("\nGoodbye, cruel world\n"); - - /* Exit, cleaning up the interpreter */ - Py_Exit(0); - /*NOTREACHED*/ + /* Ignore passed-in argc/argv. If desired, conversion + should use mbstowcs to convert them. */ + wchar_t *args[] = {L"embed", L"hello", 0}; + + /* Pass argv[0] to the Python interpreter */ + Py_SetProgramName(args[0]); + + /* Add a static module */ + PyImport_AppendInittab("xyzzy", PyInit_xyzzy); + + /* Initialize the Python interpreter. Required. */ + Py_Initialize(); + + /* Define sys.argv. It is up to the application if you + want this; you can also let it undefined (since the Python + code is generally not a main program it has no business + touching sys.argv...) */ + PySys_SetArgv(2, args); + + /* Do some application specific code */ + printf("Hello, brave new world\n\n"); + + /* Execute some Python statements (in module __main__) */ + PyRun_SimpleString("import sys\n"); + PyRun_SimpleString("print(sys.builtin_module_names)\n"); + PyRun_SimpleString("print(sys.modules.keys())\n"); + PyRun_SimpleString("print(sys.executable)\n"); + PyRun_SimpleString("print(sys.argv)\n"); + + /* Note that you can call any public function of the Python + interpreter here, e.g. call_object(). */ + + /* Some more application specific code */ + printf("\nGoodbye, cruel world\n"); + + /* Exit, cleaning up the interpreter */ + Py_Exit(0); + /*NOTREACHED*/ } /* A static module */ @@ -52,29 +52,29 @@ static PyObject * xyzzy_foo(PyObject *self, PyObject* args) { - return PyLong_FromLong(42L); + return PyLong_FromLong(42L); } static PyMethodDef xyzzy_methods[] = { - {"foo", xyzzy_foo, METH_NOARGS, - "Return the meaning of everything."}, - {NULL, NULL} /* sentinel */ + {"foo", xyzzy_foo, METH_NOARGS, + "Return the meaning of everything."}, + {NULL, NULL} /* sentinel */ }; static struct PyModuleDef xyzzymodule = { - {}, /* m_base */ - "xyzzy", /* m_name */ - 0, /* m_doc */ - 0, /* m_size */ - xyzzy_methods, /* m_methods */ - 0, /* m_reload */ - 0, /* m_traverse */ - 0, /* m_clear */ - 0, /* m_free */ + {}, /* m_base */ + "xyzzy", /* m_name */ + 0, /* m_doc */ + 0, /* m_size */ + xyzzy_methods, /* m_methods */ + 0, /* m_reload */ + 0, /* m_traverse */ + 0, /* m_clear */ + 0, /* m_free */ }; PyObject* PyInit_xyzzy(void) { - return PyModule_Create(&xyzzymodule); + return PyModule_Create(&xyzzymodule); } Modified: python/branches/py3k/Demo/embed/loop.c ============================================================================== --- python/branches/py3k/Demo/embed/loop.c (original) +++ python/branches/py3k/Demo/embed/loop.c Sun May 9 17:52:27 2010 @@ -6,28 +6,28 @@ main(int argc, char **argv) { - int count = -1; - char *command; + int count = -1; + char *command; - if (argc < 2 || argc > 3) { - fprintf(stderr, "usage: loop [count]\n"); - exit(2); - } - command = argv[1]; - - if (argc == 3) { - count = atoi(argv[2]); - } - - Py_SetProgramName(argv[0]); - - /* uncomment this if you don't want to load site.py */ - /* Py_NoSiteFlag = 1; */ - - while (count == -1 || --count >= 0 ) { - Py_Initialize(); - PyRun_SimpleString(command); - Py_Finalize(); - } - return 0; + if (argc < 2 || argc > 3) { + fprintf(stderr, "usage: loop [count]\n"); + exit(2); + } + command = argv[1]; + + if (argc == 3) { + count = atoi(argv[2]); + } + + Py_SetProgramName(argv[0]); + + /* uncomment this if you don't want to load site.py */ + /* Py_NoSiteFlag = 1; */ + + while (count == -1 || --count >= 0 ) { + Py_Initialize(); + PyRun_SimpleString(command); + Py_Finalize(); + } + return 0; } Modified: python/branches/py3k/Demo/pysvr/pysvr.c ============================================================================== --- python/branches/py3k/Demo/pysvr/pysvr.c (original) +++ python/branches/py3k/Demo/pysvr/pysvr.c Sun May 9 17:52:27 2010 @@ -34,8 +34,8 @@ #endif struct workorder { - int conn; - struct sockaddr_in addr; + int conn; + struct sockaddr_in addr; }; /* Forward */ @@ -55,40 +55,40 @@ main(int argc, char **argv) { - int port = PORT; - int c; + int port = PORT; + int c; - if (argc > 0 && argv[0] != NULL && argv[0][0] != '\0') - progname = argv[0]; + if (argc > 0 && argv[0] != NULL && argv[0][0] != '\0') + progname = argv[0]; - while ((c = getopt(argc, argv, "v")) != EOF) { - switch (c) { - case 'v': - Py_VerboseFlag++; - break; - default: - usage(); - } - } - - if (optind < argc) { - if (optind+1 < argc) { - oprogname(); - fprintf(stderr, "too many arguments\n"); - usage(); - } - port = atoi(argv[optind]); - if (port <= 0) { - fprintf(stderr, "bad port (%s)\n", argv[optind]); - usage(); - } - } + while ((c = getopt(argc, argv, "v")) != EOF) { + switch (c) { + case 'v': + Py_VerboseFlag++; + break; + default: + usage(); + } + } + + if (optind < argc) { + if (optind+1 < argc) { + oprogname(); + fprintf(stderr, "too many arguments\n"); + usage(); + } + port = atoi(argv[optind]); + if (port <= 0) { + fprintf(stderr, "bad port (%s)\n", argv[optind]); + usage(); + } + } - main_thread(port); + main_thread(port); - fprintf(stderr, "Bye.\n"); + fprintf(stderr, "Bye.\n"); - exit(0); + exit(0); } static char usage_line[] = "usage: %s [port]\n"; @@ -96,120 +96,120 @@ static void usage(void) { - fprintf(stderr, usage_line, progname); - exit(2); + fprintf(stderr, usage_line, progname); + exit(2); } static void main_thread(int port) { - int sock, conn, size, i; - struct sockaddr_in addr, clientaddr; + int sock, conn, size, i; + struct sockaddr_in addr, clientaddr; - sock = socket(PF_INET, SOCK_STREAM, 0); - if (sock < 0) { - oprogname(); - perror("can't create socket"); - exit(1); - } + sock = socket(PF_INET, SOCK_STREAM, 0); + if (sock < 0) { + oprogname(); + perror("can't create socket"); + exit(1); + } #ifdef SO_REUSEADDR - i = 1; - setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, (char *) &i, sizeof i); + i = 1; + setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, (char *) &i, sizeof i); #endif - memset((char *)&addr, '\0', sizeof addr); - addr.sin_family = AF_INET; - addr.sin_port = htons(port); - addr.sin_addr.s_addr = 0L; - if (bind(sock, (struct sockaddr *)&addr, sizeof addr) < 0) { - oprogname(); - perror("can't bind socket to address"); - exit(1); - } - - if (listen(sock, 5) < 0) { - oprogname(); - perror("can't listen on socket"); - exit(1); - } - - fprintf(stderr, "Listening on port %d...\n", port); - - for (i = 0; ; i++) { - size = sizeof clientaddr; - memset((char *) &clientaddr, '\0', size); - conn = accept(sock, (struct sockaddr *) &clientaddr, &size); - if (conn < 0) { - oprogname(); - perror("can't accept connection from socket"); - exit(1); - } - - size = sizeof addr; - memset((char *) &addr, '\0', size); - if (getsockname(conn, (struct sockaddr *)&addr, &size) < 0) { - oprogname(); - perror("can't get socket name of connection"); - exit(1); - } - if (clientaddr.sin_addr.s_addr != addr.sin_addr.s_addr) { - oprogname(); - perror("connection from non-local host refused"); - fprintf(stderr, "(addr=%lx, clientaddr=%lx)\n", - ntohl(addr.sin_addr.s_addr), - ntohl(clientaddr.sin_addr.s_addr)); - close(conn); - continue; - } - if (i == 4) { - close(conn); - break; - } - create_thread(conn, &clientaddr); - } - - close(sock); - - if (gtstate) { - PyEval_AcquireThread(gtstate); - gtstate = NULL; - Py_Finalize(); - /* And a second time, just because we can. */ - Py_Finalize(); /* This should be harmless. */ - } - exit(0); + memset((char *)&addr, '\0', sizeof addr); + addr.sin_family = AF_INET; + addr.sin_port = htons(port); + addr.sin_addr.s_addr = 0L; + if (bind(sock, (struct sockaddr *)&addr, sizeof addr) < 0) { + oprogname(); + perror("can't bind socket to address"); + exit(1); + } + + if (listen(sock, 5) < 0) { + oprogname(); + perror("can't listen on socket"); + exit(1); + } + + fprintf(stderr, "Listening on port %d...\n", port); + + for (i = 0; ; i++) { + size = sizeof clientaddr; + memset((char *) &clientaddr, '\0', size); + conn = accept(sock, (struct sockaddr *) &clientaddr, &size); + if (conn < 0) { + oprogname(); + perror("can't accept connection from socket"); + exit(1); + } + + size = sizeof addr; + memset((char *) &addr, '\0', size); + if (getsockname(conn, (struct sockaddr *)&addr, &size) < 0) { + oprogname(); + perror("can't get socket name of connection"); + exit(1); + } + if (clientaddr.sin_addr.s_addr != addr.sin_addr.s_addr) { + oprogname(); + perror("connection from non-local host refused"); + fprintf(stderr, "(addr=%lx, clientaddr=%lx)\n", + ntohl(addr.sin_addr.s_addr), + ntohl(clientaddr.sin_addr.s_addr)); + close(conn); + continue; + } + if (i == 4) { + close(conn); + break; + } + create_thread(conn, &clientaddr); + } + + close(sock); + + if (gtstate) { + PyEval_AcquireThread(gtstate); + gtstate = NULL; + Py_Finalize(); + /* And a second time, just because we can. */ + Py_Finalize(); /* This should be harmless. */ + } + exit(0); } static void create_thread(int conn, struct sockaddr_in *addr) { - struct workorder *work; - pthread_t tdata; + struct workorder *work; + pthread_t tdata; - work = malloc(sizeof(struct workorder)); - if (work == NULL) { - oprogname(); - fprintf(stderr, "out of memory for thread.\n"); - close(conn); - return; - } - work->conn = conn; - work->addr = *addr; - - init_python(); - - if (pthread_create(&tdata, NULL, (void *)service_thread, work) < 0) { - oprogname(); - perror("can't create new thread"); - close(conn); - return; - } - - if (pthread_detach(tdata) < 0) { - oprogname(); - perror("can't detach from thread"); - } + work = malloc(sizeof(struct workorder)); + if (work == NULL) { + oprogname(); + fprintf(stderr, "out of memory for thread.\n"); + close(conn); + return; + } + work->conn = conn; + work->addr = *addr; + + init_python(); + + if (pthread_create(&tdata, NULL, (void *)service_thread, work) < 0) { + oprogname(); + perror("can't create new thread"); + close(conn); + return; + } + + if (pthread_detach(tdata) < 0) { + oprogname(); + perror("can't detach from thread"); + } } static PyThreadState *the_tstate; @@ -219,152 +219,152 @@ static void init_python(void) { - if (gtstate) - return; - Py_Initialize(); /* Initialize the interpreter */ - PyEval_InitThreads(); /* Create (and acquire) the interpreter lock */ - gtstate = PyEval_SaveThread(); /* Release the thread state */ + if (gtstate) + return; + Py_Initialize(); /* Initialize the interpreter */ + PyEval_InitThreads(); /* Create (and acquire) the interpreter lock */ + gtstate = PyEval_SaveThread(); /* Release the thread state */ } static void * service_thread(struct workorder *work) { - FILE *input, *output; + FILE *input, *output; - fprintf(stderr, "Start thread for connection %d.\n", work->conn); + fprintf(stderr, "Start thread for connection %d.\n", work->conn); - ps(); + ps(); - input = fdopen(work->conn, "r"); - if (input == NULL) { - oprogname(); - perror("can't create input stream"); - goto done; - } - - output = fdopen(work->conn, "w"); - if (output == NULL) { - oprogname(); - perror("can't create output stream"); - fclose(input); - goto done; - } + input = fdopen(work->conn, "r"); + if (input == NULL) { + oprogname(); + perror("can't create input stream"); + goto done; + } + + output = fdopen(work->conn, "w"); + if (output == NULL) { + oprogname(); + perror("can't create output stream"); + fclose(input); + goto done; + } - setvbuf(input, NULL, _IONBF, 0); - setvbuf(output, NULL, _IONBF, 0); + setvbuf(input, NULL, _IONBF, 0); + setvbuf(output, NULL, _IONBF, 0); - run_interpreter(input, output); + run_interpreter(input, output); - fclose(input); - fclose(output); + fclose(input); + fclose(output); done: - fprintf(stderr, "End thread for connection %d.\n", work->conn); - close(work->conn); - free(work); + fprintf(stderr, "End thread for connection %d.\n", work->conn); + close(work->conn); + free(work); } static void oprogname(void) { - int save = errno; - fprintf(stderr, "%s: ", progname); - errno = save; + int save = errno; + fprintf(stderr, "%s: ", progname); + errno = save; } static void run_interpreter(FILE *input, FILE *output) { - PyThreadState *tstate; - PyObject *new_stdin, *new_stdout; - PyObject *mainmod, *globals; - char buffer[1000]; - char *p, *q; - int n, end; - - PyEval_AcquireLock(); - tstate = Py_NewInterpreter(); - if (tstate == NULL) { - fprintf(output, "Sorry -- can't create an interpreter\n"); - return; - } - - mainmod = PyImport_AddModule("__main__"); - globals = PyModule_GetDict(mainmod); - Py_INCREF(globals); - - new_stdin = PyFile_FromFile(input, "", "r", NULL); - new_stdout = PyFile_FromFile(output, "", "w", NULL); - - PySys_SetObject("stdin", new_stdin); - PySys_SetObject("stdout", new_stdout); - PySys_SetObject("stderr", new_stdout); - - for (n = 1; !PyErr_Occurred(); n++) { - Py_BEGIN_ALLOW_THREADS - fprintf(output, "%d> ", n); - p = fgets(buffer, sizeof buffer, input); - Py_END_ALLOW_THREADS - - if (p == NULL) - break; - if (p[0] == '\377' && p[1] == '\354') - break; - - q = strrchr(p, '\r'); - if (q && q[1] == '\n' && q[2] == '\0') { - *q++ = '\n'; - *q++ = '\0'; - } - - while (*p && isspace(*p)) - p++; - if (p[0] == '#' || p[0] == '\0') - continue; - - end = run_command(buffer, globals); - if (end < 0) - PyErr_Print(); - - if (end) - break; - } - - Py_XDECREF(globals); - Py_XDECREF(new_stdin); - Py_XDECREF(new_stdout); + PyThreadState *tstate; + PyObject *new_stdin, *new_stdout; + PyObject *mainmod, *globals; + char buffer[1000]; + char *p, *q; + int n, end; + + PyEval_AcquireLock(); + tstate = Py_NewInterpreter(); + if (tstate == NULL) { + fprintf(output, "Sorry -- can't create an interpreter\n"); + return; + } + + mainmod = PyImport_AddModule("__main__"); + globals = PyModule_GetDict(mainmod); + Py_INCREF(globals); + + new_stdin = PyFile_FromFile(input, "", "r", NULL); + new_stdout = PyFile_FromFile(output, "", "w", NULL); + + PySys_SetObject("stdin", new_stdin); + PySys_SetObject("stdout", new_stdout); + PySys_SetObject("stderr", new_stdout); + + for (n = 1; !PyErr_Occurred(); n++) { + Py_BEGIN_ALLOW_THREADS + fprintf(output, "%d> ", n); + p = fgets(buffer, sizeof buffer, input); + Py_END_ALLOW_THREADS + + if (p == NULL) + break; + if (p[0] == '\377' && p[1] == '\354') + break; + + q = strrchr(p, '\r'); + if (q && q[1] == '\n' && q[2] == '\0') { + *q++ = '\n'; + *q++ = '\0'; + } + + while (*p && isspace(*p)) + p++; + if (p[0] == '#' || p[0] == '\0') + continue; + + end = run_command(buffer, globals); + if (end < 0) + PyErr_Print(); + + if (end) + break; + } + + Py_XDECREF(globals); + Py_XDECREF(new_stdin); + Py_XDECREF(new_stdout); - Py_EndInterpreter(tstate); - PyEval_ReleaseLock(); + Py_EndInterpreter(tstate); + PyEval_ReleaseLock(); - fprintf(output, "Goodbye!\n"); + fprintf(output, "Goodbye!\n"); } static int run_command(char *buffer, PyObject *globals) { - PyObject *m, *d, *v; - fprintf(stderr, "run_command: %s", buffer); - if (strchr(buffer, '\n') == NULL) - fprintf(stderr, "\n"); - v = PyRun_String(buffer, Py_single_input, globals, globals); - if (v == NULL) { - if (PyErr_Occurred() == PyExc_SystemExit) { - PyErr_Clear(); - return 1; - } - PyErr_Print(); - return 0; - } - Py_DECREF(v); - return 0; + PyObject *m, *d, *v; + fprintf(stderr, "run_command: %s", buffer); + if (strchr(buffer, '\n') == NULL) + fprintf(stderr, "\n"); + v = PyRun_String(buffer, Py_single_input, globals, globals); + if (v == NULL) { + if (PyErr_Occurred() == PyExc_SystemExit) { + PyErr_Clear(); + return 1; + } + PyErr_Print(); + return 0; + } + Py_DECREF(v); + return 0; } static void ps(void) { - char buffer[100]; - PyOS_snprintf(buffer, sizeof(buffer), - "ps -l -p %d ob_type->tp_as_buffer != NULL) && \ - ((obj)->ob_type->tp_as_buffer->bf_getbuffer != NULL)) + (((obj)->ob_type->tp_as_buffer != NULL) && \ + ((obj)->ob_type->tp_as_buffer->bf_getbuffer != NULL)) - /* Return 1 if the getbuffer function is available, otherwise - return 0 */ + /* Return 1 if the getbuffer function is available, otherwise + return 0 */ - PyAPI_FUNC(int) PyObject_GetBuffer(PyObject *obj, Py_buffer *view, - int flags); + PyAPI_FUNC(int) PyObject_GetBuffer(PyObject *obj, Py_buffer *view, + int flags); - /* This is a C-API version of the getbuffer function call. It checks - to make sure object has the required function pointer and issues the - call. Returns -1 and raises an error on failure and returns 0 on - success - */ + /* This is a C-API version of the getbuffer function call. It checks + to make sure object has the required function pointer and issues the + call. Returns -1 and raises an error on failure and returns 0 on + success + */ PyAPI_FUNC(void *) PyBuffer_GetPointer(Py_buffer *view, Py_ssize_t *indices); - - /* Get the memory area pointed to by the indices for the buffer given. - Note that view->ndim is the assumed size of indices - */ + + /* Get the memory area pointed to by the indices for the buffer given. + Note that view->ndim is the assumed size of indices + */ PyAPI_FUNC(int) PyBuffer_SizeFromFormat(const char *); - - /* Return the implied itemsize of the data-format area from a - struct-style description */ - - + /* Return the implied itemsize of the data-format area from a + struct-style description */ + + + PyAPI_FUNC(int) PyBuffer_ToContiguous(void *buf, Py_buffer *view, - Py_ssize_t len, char fort); + Py_ssize_t len, char fort); - PyAPI_FUNC(int) PyBuffer_FromContiguous(Py_buffer *view, void *buf, - Py_ssize_t len, char fort); + PyAPI_FUNC(int) PyBuffer_FromContiguous(Py_buffer *view, void *buf, + Py_ssize_t len, char fort); - /* Copy len bytes of data from the contiguous chunk of memory - pointed to by buf into the buffer exported by obj. Return - 0 on success and return -1 and raise a PyBuffer_Error on - error (i.e. the object does not have a buffer interface or - it is not working). - - If fort is 'F', then if the object is multi-dimensional, - then the data will be copied into the array in - Fortran-style (first dimension varies the fastest). If - fort is 'C', then the data will be copied into the array - in C-style (last dimension varies the fastest). If fort - is 'A', then it does not matter and the copy will be made - in whatever way is more efficient. + /* Copy len bytes of data from the contiguous chunk of memory + pointed to by buf into the buffer exported by obj. Return + 0 on success and return -1 and raise a PyBuffer_Error on + error (i.e. the object does not have a buffer interface or + it is not working). + + If fort is 'F', then if the object is multi-dimensional, + then the data will be copied into the array in + Fortran-style (first dimension varies the fastest). If + fort is 'C', then the data will be copied into the array + in C-style (last dimension varies the fastest). If fort + is 'A', then it does not matter and the copy will be made + in whatever way is more efficient. - */ + */ PyAPI_FUNC(int) PyObject_CopyData(PyObject *dest, PyObject *src); - - /* Copy the data from the src buffer to the buffer of destination - */ + + /* Copy the data from the src buffer to the buffer of destination + */ PyAPI_FUNC(int) PyBuffer_IsContiguous(Py_buffer *view, char fort); - PyAPI_FUNC(void) PyBuffer_FillContiguousStrides(int ndims, - Py_ssize_t *shape, - Py_ssize_t *strides, - int itemsize, - char fort); - - /* Fill the strides array with byte-strides of a contiguous - (Fortran-style if fort is 'F' or C-style otherwise) - array of the given shape with the given number of bytes - per element. - */ + PyAPI_FUNC(void) PyBuffer_FillContiguousStrides(int ndims, + Py_ssize_t *shape, + Py_ssize_t *strides, + int itemsize, + char fort); + + /* Fill the strides array with byte-strides of a contiguous + (Fortran-style if fort is 'F' or C-style otherwise) + array of the given shape with the given number of bytes + per element. + */ PyAPI_FUNC(int) PyBuffer_FillInfo(Py_buffer *view, PyObject *o, void *buf, - Py_ssize_t len, int readonly, - int flags); + Py_ssize_t len, int readonly, + int flags); - /* Fills in a buffer-info structure correctly for an exporter - that can only share a contiguous chunk of memory of - "unsigned bytes" of the given length. Returns 0 on success - and -1 (with raising an error) on error. - */ + /* Fills in a buffer-info structure correctly for an exporter + that can only share a contiguous chunk of memory of + "unsigned bytes" of the given length. Returns 0 on success + and -1 (with raising an error) on error. + */ PyAPI_FUNC(void) PyBuffer_Release(Py_buffer *view); /* Releases a Py_buffer obtained from getbuffer ParseTuple's s*. - */ + */ PyAPI_FUNC(PyObject *) PyObject_Format(PyObject* obj, - PyObject *format_spec); + PyObject *format_spec); /* - Takes an arbitrary object and returns the result of - calling obj.__format__(format_spec). + Takes an arbitrary object and returns the result of + calling obj.__format__(format_spec). */ /* Iterators */ PyAPI_FUNC(PyObject *) PyObject_GetIter(PyObject *); /* Takes an object and returns an iterator for it. - This is typically a new iterator but if the argument - is an iterator, this returns itself. */ + This is typically a new iterator but if the argument + is an iterator, this returns itself. */ #define PyIter_Check(obj) \ ((obj)->ob_type->tp_iternext != NULL && \ @@ -594,314 +594,314 @@ PyAPI_FUNC(PyObject *) PyIter_Next(PyObject *); /* Takes an iterator object and calls its tp_iternext slot, - returning the next value. If the iterator is exhausted, - this returns NULL without setting an exception. - NULL with an exception means an error occurred. */ + returning the next value. If the iterator is exhausted, + this returns NULL without setting an exception. + NULL with an exception means an error occurred. */ /* Number Protocol:*/ PyAPI_FUNC(int) PyNumber_Check(PyObject *o); /* - Returns 1 if the object, o, provides numeric protocols, and - false otherwise. + Returns 1 if the object, o, provides numeric protocols, and + false otherwise. - This function always succeeds. + This function always succeeds. */ PyAPI_FUNC(PyObject *) PyNumber_Add(PyObject *o1, PyObject *o2); /* - Returns the result of adding o1 and o2, or null on failure. - This is the equivalent of the Python expression: o1+o2. + Returns the result of adding o1 and o2, or null on failure. + This is the equivalent of the Python expression: o1+o2. */ PyAPI_FUNC(PyObject *) PyNumber_Subtract(PyObject *o1, PyObject *o2); /* - Returns the result of subtracting o2 from o1, or null on - failure. This is the equivalent of the Python expression: - o1-o2. + Returns the result of subtracting o2 from o1, or null on + failure. This is the equivalent of the Python expression: + o1-o2. */ PyAPI_FUNC(PyObject *) PyNumber_Multiply(PyObject *o1, PyObject *o2); /* - Returns the result of multiplying o1 and o2, or null on - failure. This is the equivalent of the Python expression: - o1*o2. + Returns the result of multiplying o1 and o2, or null on + failure. This is the equivalent of the Python expression: + o1*o2. */ PyAPI_FUNC(PyObject *) PyNumber_FloorDivide(PyObject *o1, PyObject *o2); /* - Returns the result of dividing o1 by o2 giving an integral result, - or null on failure. - This is the equivalent of the Python expression: o1//o2. + Returns the result of dividing o1 by o2 giving an integral result, + or null on failure. + This is the equivalent of the Python expression: o1//o2. */ PyAPI_FUNC(PyObject *) PyNumber_TrueDivide(PyObject *o1, PyObject *o2); /* - Returns the result of dividing o1 by o2 giving a float result, - or null on failure. - This is the equivalent of the Python expression: o1/o2. + Returns the result of dividing o1 by o2 giving a float result, + or null on failure. + This is the equivalent of the Python expression: o1/o2. */ PyAPI_FUNC(PyObject *) PyNumber_Remainder(PyObject *o1, PyObject *o2); /* - Returns the remainder of dividing o1 by o2, or null on - failure. This is the equivalent of the Python expression: - o1%o2. + Returns the remainder of dividing o1 by o2, or null on + failure. This is the equivalent of the Python expression: + o1%o2. */ PyAPI_FUNC(PyObject *) PyNumber_Divmod(PyObject *o1, PyObject *o2); /* - See the built-in function divmod. Returns NULL on failure. - This is the equivalent of the Python expression: - divmod(o1,o2). + See the built-in function divmod. Returns NULL on failure. + This is the equivalent of the Python expression: + divmod(o1,o2). */ PyAPI_FUNC(PyObject *) PyNumber_Power(PyObject *o1, PyObject *o2, PyObject *o3); /* - See the built-in function pow. Returns NULL on failure. - This is the equivalent of the Python expression: - pow(o1,o2,o3), where o3 is optional. + See the built-in function pow. Returns NULL on failure. + This is the equivalent of the Python expression: + pow(o1,o2,o3), where o3 is optional. */ PyAPI_FUNC(PyObject *) PyNumber_Negative(PyObject *o); /* - Returns the negation of o on success, or null on failure. - This is the equivalent of the Python expression: -o. + Returns the negation of o on success, or null on failure. + This is the equivalent of the Python expression: -o. */ PyAPI_FUNC(PyObject *) PyNumber_Positive(PyObject *o); /* - Returns the (what?) of o on success, or NULL on failure. - This is the equivalent of the Python expression: +o. + Returns the (what?) of o on success, or NULL on failure. + This is the equivalent of the Python expression: +o. */ PyAPI_FUNC(PyObject *) PyNumber_Absolute(PyObject *o); /* - Returns the absolute value of o, or null on failure. This is - the equivalent of the Python expression: abs(o). + Returns the absolute value of o, or null on failure. This is + the equivalent of the Python expression: abs(o). */ PyAPI_FUNC(PyObject *) PyNumber_Invert(PyObject *o); /* - Returns the bitwise negation of o on success, or NULL on - failure. This is the equivalent of the Python expression: - ~o. + Returns the bitwise negation of o on success, or NULL on + failure. This is the equivalent of the Python expression: + ~o. */ PyAPI_FUNC(PyObject *) PyNumber_Lshift(PyObject *o1, PyObject *o2); /* - Returns the result of left shifting o1 by o2 on success, or - NULL on failure. This is the equivalent of the Python - expression: o1 << o2. + Returns the result of left shifting o1 by o2 on success, or + NULL on failure. This is the equivalent of the Python + expression: o1 << o2. */ PyAPI_FUNC(PyObject *) PyNumber_Rshift(PyObject *o1, PyObject *o2); /* - Returns the result of right shifting o1 by o2 on success, or - NULL on failure. This is the equivalent of the Python - expression: o1 >> o2. + Returns the result of right shifting o1 by o2 on success, or + NULL on failure. This is the equivalent of the Python + expression: o1 >> o2. */ PyAPI_FUNC(PyObject *) PyNumber_And(PyObject *o1, PyObject *o2); /* - Returns the result of bitwise and of o1 and o2 on success, or - NULL on failure. This is the equivalent of the Python - expression: o1&o2. + Returns the result of bitwise and of o1 and o2 on success, or + NULL on failure. This is the equivalent of the Python + expression: o1&o2. */ PyAPI_FUNC(PyObject *) PyNumber_Xor(PyObject *o1, PyObject *o2); /* - Returns the bitwise exclusive or of o1 by o2 on success, or - NULL on failure. This is the equivalent of the Python - expression: o1^o2. + Returns the bitwise exclusive or of o1 by o2 on success, or + NULL on failure. This is the equivalent of the Python + expression: o1^o2. */ PyAPI_FUNC(PyObject *) PyNumber_Or(PyObject *o1, PyObject *o2); /* - Returns the result of bitwise or on o1 and o2 on success, or - NULL on failure. This is the equivalent of the Python - expression: o1|o2. + Returns the result of bitwise or on o1 and o2 on success, or + NULL on failure. This is the equivalent of the Python + expression: o1|o2. */ #define PyIndex_Check(obj) \ ((obj)->ob_type->tp_as_number != NULL && \ (obj)->ob_type->tp_as_number->nb_index != NULL) - + PyAPI_FUNC(PyObject *) PyNumber_Index(PyObject *o); /* - Returns the object converted to a Python long or int - or NULL with an error raised on failure. + Returns the object converted to a Python long or int + or NULL with an error raised on failure. */ PyAPI_FUNC(Py_ssize_t) PyNumber_AsSsize_t(PyObject *o, PyObject *exc); /* - Returns the Integral instance converted to an int. The - instance is expected to be int or long or have an __int__ - method. Steals integral's reference. error_format will be - used to create the TypeError if integral isn't actually an - Integral instance. error_format should be a format string - that can accept a char* naming integral's type. + Returns the Integral instance converted to an int. The + instance is expected to be int or long or have an __int__ + method. Steals integral's reference. error_format will be + used to create the TypeError if integral isn't actually an + Integral instance. error_format should be a format string + that can accept a char* naming integral's type. */ PyAPI_FUNC(PyObject *) _PyNumber_ConvertIntegralToInt( - PyObject *integral, - const char* error_format); + PyObject *integral, + const char* error_format); /* - Returns the object converted to Py_ssize_t by going through - PyNumber_Index first. If an overflow error occurs while - converting the int-or-long to Py_ssize_t, then the second argument - is the error-type to return. If it is NULL, then the overflow error - is cleared and the value is clipped. + Returns the object converted to Py_ssize_t by going through + PyNumber_Index first. If an overflow error occurs while + converting the int-or-long to Py_ssize_t, then the second argument + is the error-type to return. If it is NULL, then the overflow error + is cleared and the value is clipped. */ PyAPI_FUNC(PyObject *) PyNumber_Long(PyObject *o); /* - Returns the o converted to an integer object on success, or - NULL on failure. This is the equivalent of the Python - expression: int(o). + Returns the o converted to an integer object on success, or + NULL on failure. This is the equivalent of the Python + expression: int(o). */ PyAPI_FUNC(PyObject *) PyNumber_Float(PyObject *o); /* - Returns the o converted to a float object on success, or NULL - on failure. This is the equivalent of the Python expression: - float(o). + Returns the o converted to a float object on success, or NULL + on failure. This is the equivalent of the Python expression: + float(o). */ - + /* In-place variants of (some of) the above number protocol functions */ PyAPI_FUNC(PyObject *) PyNumber_InPlaceAdd(PyObject *o1, PyObject *o2); /* - Returns the result of adding o2 to o1, possibly in-place, or null - on failure. This is the equivalent of the Python expression: - o1 += o2. + Returns the result of adding o2 to o1, possibly in-place, or null + on failure. This is the equivalent of the Python expression: + o1 += o2. */ PyAPI_FUNC(PyObject *) PyNumber_InPlaceSubtract(PyObject *o1, PyObject *o2); /* - Returns the result of subtracting o2 from o1, possibly in-place or - null on failure. This is the equivalent of the Python expression: - o1 -= o2. + Returns the result of subtracting o2 from o1, possibly in-place or + null on failure. This is the equivalent of the Python expression: + o1 -= o2. */ PyAPI_FUNC(PyObject *) PyNumber_InPlaceMultiply(PyObject *o1, PyObject *o2); /* - Returns the result of multiplying o1 by o2, possibly in-place, or - null on failure. This is the equivalent of the Python expression: - o1 *= o2. + Returns the result of multiplying o1 by o2, possibly in-place, or + null on failure. This is the equivalent of the Python expression: + o1 *= o2. */ PyAPI_FUNC(PyObject *) PyNumber_InPlaceFloorDivide(PyObject *o1, - PyObject *o2); + PyObject *o2); /* - Returns the result of dividing o1 by o2 giving an integral result, - possibly in-place, or null on failure. - This is the equivalent of the Python expression: - o1 /= o2. + Returns the result of dividing o1 by o2 giving an integral result, + possibly in-place, or null on failure. + This is the equivalent of the Python expression: + o1 /= o2. */ PyAPI_FUNC(PyObject *) PyNumber_InPlaceTrueDivide(PyObject *o1, - PyObject *o2); + PyObject *o2); /* - Returns the result of dividing o1 by o2 giving a float result, - possibly in-place, or null on failure. - This is the equivalent of the Python expression: - o1 /= o2. + Returns the result of dividing o1 by o2 giving a float result, + possibly in-place, or null on failure. + This is the equivalent of the Python expression: + o1 /= o2. */ PyAPI_FUNC(PyObject *) PyNumber_InPlaceRemainder(PyObject *o1, PyObject *o2); /* - Returns the remainder of dividing o1 by o2, possibly in-place, or - null on failure. This is the equivalent of the Python expression: - o1 %= o2. + Returns the remainder of dividing o1 by o2, possibly in-place, or + null on failure. This is the equivalent of the Python expression: + o1 %= o2. */ PyAPI_FUNC(PyObject *) PyNumber_InPlacePower(PyObject *o1, PyObject *o2, - PyObject *o3); + PyObject *o3); /* - Returns the result of raising o1 to the power of o2, possibly - in-place, or null on failure. This is the equivalent of the Python - expression: o1 **= o2, or pow(o1, o2, o3) if o3 is present. + Returns the result of raising o1 to the power of o2, possibly + in-place, or null on failure. This is the equivalent of the Python + expression: o1 **= o2, or pow(o1, o2, o3) if o3 is present. */ PyAPI_FUNC(PyObject *) PyNumber_InPlaceLshift(PyObject *o1, PyObject *o2); /* - Returns the result of left shifting o1 by o2, possibly in-place, or - null on failure. This is the equivalent of the Python expression: - o1 <<= o2. + Returns the result of left shifting o1 by o2, possibly in-place, or + null on failure. This is the equivalent of the Python expression: + o1 <<= o2. */ PyAPI_FUNC(PyObject *) PyNumber_InPlaceRshift(PyObject *o1, PyObject *o2); /* - Returns the result of right shifting o1 by o2, possibly in-place or - null on failure. This is the equivalent of the Python expression: - o1 >>= o2. + Returns the result of right shifting o1 by o2, possibly in-place or + null on failure. This is the equivalent of the Python expression: + o1 >>= o2. */ PyAPI_FUNC(PyObject *) PyNumber_InPlaceAnd(PyObject *o1, PyObject *o2); /* - Returns the result of bitwise and of o1 and o2, possibly in-place, - or null on failure. This is the equivalent of the Python - expression: o1 &= o2. + Returns the result of bitwise and of o1 and o2, possibly in-place, + or null on failure. This is the equivalent of the Python + expression: o1 &= o2. */ PyAPI_FUNC(PyObject *) PyNumber_InPlaceXor(PyObject *o1, PyObject *o2); /* - Returns the bitwise exclusive or of o1 by o2, possibly in-place, or - null on failure. This is the equivalent of the Python expression: - o1 ^= o2. + Returns the bitwise exclusive or of o1 by o2, possibly in-place, or + null on failure. This is the equivalent of the Python expression: + o1 ^= o2. */ PyAPI_FUNC(PyObject *) PyNumber_InPlaceOr(PyObject *o1, PyObject *o2); /* - Returns the result of bitwise or of o1 and o2, possibly in-place, - or null on failure. This is the equivalent of the Python - expression: o1 |= o2. + Returns the result of bitwise or of o1 and o2, possibly in-place, + or null on failure. This is the equivalent of the Python + expression: o1 |= o2. */ PyAPI_FUNC(PyObject *) PyNumber_ToBase(PyObject *n, int base); /* - Returns the integer n converted to a string with a base, with a base - marker of 0b, 0o or 0x prefixed if applicable. - If n is not an int object, it is converted with PyNumber_Index first. + Returns the integer n converted to a string with a base, with a base + marker of 0b, 0o or 0x prefixed if applicable. + If n is not an int object, it is converted with PyNumber_Index first. */ @@ -910,16 +910,16 @@ PyAPI_FUNC(int) PySequence_Check(PyObject *o); /* - Return 1 if the object provides sequence protocol, and zero - otherwise. + Return 1 if the object provides sequence protocol, and zero + otherwise. - This function always succeeds. + This function always succeeds. */ PyAPI_FUNC(Py_ssize_t) PySequence_Size(PyObject *o); /* - Return the size of sequence object o, or -1 on failure. + Return the size of sequence object o, or -1 on failure. */ /* For DLL compatibility */ @@ -931,147 +931,147 @@ PyAPI_FUNC(PyObject *) PySequence_Concat(PyObject *o1, PyObject *o2); /* - Return the concatenation of o1 and o2 on success, and NULL on - failure. This is the equivalent of the Python - expression: o1+o2. + Return the concatenation of o1 and o2 on success, and NULL on + failure. This is the equivalent of the Python + expression: o1+o2. */ PyAPI_FUNC(PyObject *) PySequence_Repeat(PyObject *o, Py_ssize_t count); /* - Return the result of repeating sequence object o count times, - or NULL on failure. This is the equivalent of the Python - expression: o1*count. + Return the result of repeating sequence object o count times, + or NULL on failure. This is the equivalent of the Python + expression: o1*count. */ PyAPI_FUNC(PyObject *) PySequence_GetItem(PyObject *o, Py_ssize_t i); /* - Return the ith element of o, or NULL on failure. This is the - equivalent of the Python expression: o[i]. + Return the ith element of o, or NULL on failure. This is the + equivalent of the Python expression: o[i]. */ PyAPI_FUNC(PyObject *) PySequence_GetSlice(PyObject *o, Py_ssize_t i1, Py_ssize_t i2); /* - Return the slice of sequence object o between i1 and i2, or - NULL on failure. This is the equivalent of the Python - expression: o[i1:i2]. + Return the slice of sequence object o between i1 and i2, or + NULL on failure. This is the equivalent of the Python + expression: o[i1:i2]. */ PyAPI_FUNC(int) PySequence_SetItem(PyObject *o, Py_ssize_t i, PyObject *v); /* - Assign object v to the ith element of o. Returns - -1 on failure. This is the equivalent of the Python - statement: o[i]=v. + Assign object v to the ith element of o. Returns + -1 on failure. This is the equivalent of the Python + statement: o[i]=v. */ PyAPI_FUNC(int) PySequence_DelItem(PyObject *o, Py_ssize_t i); /* - Delete the ith element of object v. Returns - -1 on failure. This is the equivalent of the Python - statement: del o[i]. + Delete the ith element of object v. Returns + -1 on failure. This is the equivalent of the Python + statement: del o[i]. */ PyAPI_FUNC(int) PySequence_SetSlice(PyObject *o, Py_ssize_t i1, Py_ssize_t i2, PyObject *v); /* - Assign the sequence object, v, to the slice in sequence - object, o, from i1 to i2. Returns -1 on failure. This is the - equivalent of the Python statement: o[i1:i2]=v. + Assign the sequence object, v, to the slice in sequence + object, o, from i1 to i2. Returns -1 on failure. This is the + equivalent of the Python statement: o[i1:i2]=v. */ PyAPI_FUNC(int) PySequence_DelSlice(PyObject *o, Py_ssize_t i1, Py_ssize_t i2); /* - Delete the slice in sequence object, o, from i1 to i2. - Returns -1 on failure. This is the equivalent of the Python - statement: del o[i1:i2]. + Delete the slice in sequence object, o, from i1 to i2. + Returns -1 on failure. This is the equivalent of the Python + statement: del o[i1:i2]. */ PyAPI_FUNC(PyObject *) PySequence_Tuple(PyObject *o); /* - Returns the sequence, o, as a tuple on success, and NULL on failure. - This is equivalent to the Python expression: tuple(o) + Returns the sequence, o, as a tuple on success, and NULL on failure. + This is equivalent to the Python expression: tuple(o) */ PyAPI_FUNC(PyObject *) PySequence_List(PyObject *o); /* - Returns the sequence, o, as a list on success, and NULL on failure. - This is equivalent to the Python expression: list(o) + Returns the sequence, o, as a list on success, and NULL on failure. + This is equivalent to the Python expression: list(o) */ PyAPI_FUNC(PyObject *) PySequence_Fast(PyObject *o, const char* m); /* - Returns the sequence, o, as a tuple, unless it's already a - tuple or list. Use PySequence_Fast_GET_ITEM to access the - members of this list, and PySequence_Fast_GET_SIZE to get its length. + Returns the sequence, o, as a tuple, unless it's already a + tuple or list. Use PySequence_Fast_GET_ITEM to access the + members of this list, and PySequence_Fast_GET_SIZE to get its length. - Returns NULL on failure. If the object does not support iteration, - raises a TypeError exception with m as the message text. + Returns NULL on failure. If the object does not support iteration, + raises a TypeError exception with m as the message text. */ #define PySequence_Fast_GET_SIZE(o) \ - (PyList_Check(o) ? PyList_GET_SIZE(o) : PyTuple_GET_SIZE(o)) + (PyList_Check(o) ? PyList_GET_SIZE(o) : PyTuple_GET_SIZE(o)) /* - Return the size of o, assuming that o was returned by - PySequence_Fast and is not NULL. + Return the size of o, assuming that o was returned by + PySequence_Fast and is not NULL. */ #define PySequence_Fast_GET_ITEM(o, i)\ (PyList_Check(o) ? PyList_GET_ITEM(o, i) : PyTuple_GET_ITEM(o, i)) /* - Return the ith element of o, assuming that o was returned by - PySequence_Fast, and that i is within bounds. + Return the ith element of o, assuming that o was returned by + PySequence_Fast, and that i is within bounds. */ #define PySequence_ITEM(o, i)\ - ( Py_TYPE(o)->tp_as_sequence->sq_item(o, i) ) + ( Py_TYPE(o)->tp_as_sequence->sq_item(o, i) ) /* Assume tp_as_sequence and sq_item exist and that i does not - need to be corrected for a negative index - */ + need to be corrected for a negative index + */ #define PySequence_Fast_ITEMS(sf) \ - (PyList_Check(sf) ? ((PyListObject *)(sf))->ob_item \ - : ((PyTupleObject *)(sf))->ob_item) - /* Return a pointer to the underlying item array for - an object retured by PySequence_Fast */ + (PyList_Check(sf) ? ((PyListObject *)(sf))->ob_item \ + : ((PyTupleObject *)(sf))->ob_item) + /* Return a pointer to the underlying item array for + an object retured by PySequence_Fast */ PyAPI_FUNC(Py_ssize_t) PySequence_Count(PyObject *o, PyObject *value); /* - Return the number of occurrences on value on o, that is, - return the number of keys for which o[key]==value. On - failure, return -1. This is equivalent to the Python - expression: o.count(value). + Return the number of occurrences on value on o, that is, + return the number of keys for which o[key]==value. On + failure, return -1. This is equivalent to the Python + expression: o.count(value). */ PyAPI_FUNC(int) PySequence_Contains(PyObject *seq, PyObject *ob); /* - Return -1 if error; 1 if ob in seq; 0 if ob not in seq. - Use __contains__ if possible, else _PySequence_IterSearch(). + Return -1 if error; 1 if ob in seq; 0 if ob not in seq. + Use __contains__ if possible, else _PySequence_IterSearch(). */ #define PY_ITERSEARCH_COUNT 1 #define PY_ITERSEARCH_INDEX 2 #define PY_ITERSEARCH_CONTAINS 3 PyAPI_FUNC(Py_ssize_t) _PySequence_IterSearch(PyObject *seq, - PyObject *obj, int operation); - /* - Iterate over seq. Result depends on the operation: - PY_ITERSEARCH_COUNT: return # of times obj appears in seq; -1 if - error. - PY_ITERSEARCH_INDEX: return 0-based index of first occurrence of - obj in seq; set ValueError and return -1 if none found; - also return -1 on error. - PY_ITERSEARCH_CONTAINS: return 1 if obj in seq, else 0; -1 on - error. - */ + PyObject *obj, int operation); + /* + Iterate over seq. Result depends on the operation: + PY_ITERSEARCH_COUNT: return # of times obj appears in seq; -1 if + error. + PY_ITERSEARCH_INDEX: return 0-based index of first occurrence of + obj in seq; set ValueError and return -1 if none found; + also return -1 on error. + PY_ITERSEARCH_CONTAINS: return 1 if obj in seq, else 0; -1 on + error. + */ /* For DLL-level backwards compatibility */ #undef PySequence_In @@ -1081,17 +1081,17 @@ #define PySequence_In PySequence_Contains /* - Determine if o contains value. If an item in o is equal to - X, return 1, otherwise return 0. On error, return -1. This - is equivalent to the Python expression: value in o. + Determine if o contains value. If an item in o is equal to + X, return 1, otherwise return 0. On error, return -1. This + is equivalent to the Python expression: value in o. */ PyAPI_FUNC(Py_ssize_t) PySequence_Index(PyObject *o, PyObject *value); /* - Return the first index for which o[i]=value. On error, - return -1. This is equivalent to the Python - expression: o.index(value). + Return the first index for which o[i]=value. On error, + return -1. This is equivalent to the Python + expression: o.index(value). */ /* In-place versions of some of the above Sequence functions. */ @@ -1099,18 +1099,18 @@ PyAPI_FUNC(PyObject *) PySequence_InPlaceConcat(PyObject *o1, PyObject *o2); /* - Append o2 to o1, in-place when possible. Return the resulting - object, which could be o1, or NULL on failure. This is the - equivalent of the Python expression: o1 += o2. + Append o2 to o1, in-place when possible. Return the resulting + object, which could be o1, or NULL on failure. This is the + equivalent of the Python expression: o1 += o2. */ PyAPI_FUNC(PyObject *) PySequence_InPlaceRepeat(PyObject *o, Py_ssize_t count); /* - Repeat o1 by count, in-place when possible. Return the resulting - object, which could be o1, or NULL on failure. This is the - equivalent of the Python expression: o1 *= count. + Repeat o1 by count, in-place when possible. Return the resulting + object, which could be o1, or NULL on failure. This is the + equivalent of the Python expression: o1 *= count. */ @@ -1119,18 +1119,18 @@ PyAPI_FUNC(int) PyMapping_Check(PyObject *o); /* - Return 1 if the object provides mapping protocol, and zero - otherwise. + Return 1 if the object provides mapping protocol, and zero + otherwise. - This function always succeeds. + This function always succeeds. */ PyAPI_FUNC(Py_ssize_t) PyMapping_Size(PyObject *o); /* - Returns the number of keys in object o on success, and -1 on - failure. For objects that do not provide sequence protocol, - this is equivalent to the Python expression: len(o). + Returns the number of keys in object o on success, and -1 on + failure. For objects that do not provide sequence protocol, + this is equivalent to the Python expression: len(o). */ /* For DLL compatibility */ @@ -1143,9 +1143,9 @@ int PyMapping_DelItemString(PyObject *o, char *key); - Remove the mapping for object, key, from the object *o. - Returns -1 on failure. This is equivalent to - the Python statement: del o[key]. + Remove the mapping for object, key, from the object *o. + Returns -1 on failure. This is equivalent to + the Python statement: del o[key]. */ #define PyMapping_DelItemString(O,K) PyObject_DelItemString((O),(K)) @@ -1153,71 +1153,71 @@ int PyMapping_DelItem(PyObject *o, PyObject *key); - Remove the mapping for object, key, from the object *o. - Returns -1 on failure. This is equivalent to - the Python statement: del o[key]. + Remove the mapping for object, key, from the object *o. + Returns -1 on failure. This is equivalent to + the Python statement: del o[key]. */ #define PyMapping_DelItem(O,K) PyObject_DelItem((O),(K)) PyAPI_FUNC(int) PyMapping_HasKeyString(PyObject *o, char *key); /* - On success, return 1 if the mapping object has the key, key, - and 0 otherwise. This is equivalent to the Python expression: - key in o. + On success, return 1 if the mapping object has the key, key, + and 0 otherwise. This is equivalent to the Python expression: + key in o. - This function always succeeds. + This function always succeeds. */ PyAPI_FUNC(int) PyMapping_HasKey(PyObject *o, PyObject *key); /* - Return 1 if the mapping object has the key, key, - and 0 otherwise. This is equivalent to the Python expression: - key in o. + Return 1 if the mapping object has the key, key, + and 0 otherwise. This is equivalent to the Python expression: + key in o. - This function always succeeds. + This function always succeeds. */ PyAPI_FUNC(PyObject *) PyMapping_Keys(PyObject *o); /* - On success, return a list or tuple of the keys in object o. - On failure, return NULL. + On success, return a list or tuple of the keys in object o. + On failure, return NULL. */ PyAPI_FUNC(PyObject *) PyMapping_Values(PyObject *o); /* - On success, return a list or tuple of the values in object o. - On failure, return NULL. + On success, return a list or tuple of the values in object o. + On failure, return NULL. */ PyAPI_FUNC(PyObject *) PyMapping_Items(PyObject *o); /* - On success, return a list or tuple of the items in object o, - where each item is a tuple containing a key-value pair. - On failure, return NULL. + On success, return a list or tuple of the items in object o, + where each item is a tuple containing a key-value pair. + On failure, return NULL. */ PyAPI_FUNC(PyObject *) PyMapping_GetItemString(PyObject *o, char *key); /* - Return element of o corresponding to the object, key, or NULL - on failure. This is the equivalent of the Python expression: - o[key]. + Return element of o corresponding to the object, key, or NULL + on failure. This is the equivalent of the Python expression: + o[key]. */ PyAPI_FUNC(int) PyMapping_SetItemString(PyObject *o, char *key, PyObject *value); /* - Map the object, key, to the value, v. Returns - -1 on failure. This is the equivalent of the Python - statement: o[key]=v. + Map the object, key, to the value, v. Returns + -1 on failure. This is the equivalent of the Python + statement: o[key]=v. */ Modified: python/branches/py3k/Include/ceval.h ============================================================================== --- python/branches/py3k/Include/ceval.h (original) +++ python/branches/py3k/Include/ceval.h Sun May 9 17:52:27 2010 @@ -8,11 +8,11 @@ /* Interface to random parts in ceval.c */ PyAPI_FUNC(PyObject *) PyEval_CallObjectWithKeywords( - PyObject *, PyObject *, PyObject *); + PyObject *, PyObject *, PyObject *); /* Inline this */ #define PyEval_CallObject(func,arg) \ - PyEval_CallObjectWithKeywords(func, arg, (PyObject *)NULL) + PyEval_CallObjectWithKeywords(func, arg, (PyObject *)NULL) PyAPI_FUNC(PyObject *) PyEval_CallFunction(PyObject *obj, const char *format, ...); @@ -45,7 +45,7 @@ exceeds the current recursion limit. It raises a RuntimeError, and sets the "overflowed" flag in the thread state structure. This flag temporarily *disables* the normal protection; this allows cleanup code - to potentially outgrow the recursion limit while processing the + to potentially outgrow the recursion limit while processing the RuntimeError. * "last chance" anti-recursion protection is triggered when the recursion level exceeds "current recursion limit + 50". By construction, this @@ -67,12 +67,12 @@ PyAPI_FUNC(int) Py_GetRecursionLimit(void); #define Py_EnterRecursiveCall(where) \ - (_Py_MakeRecCheck(PyThreadState_GET()->recursion_depth) && \ - _Py_CheckRecursiveCall(where)) -#define Py_LeaveRecursiveCall() \ + (_Py_MakeRecCheck(PyThreadState_GET()->recursion_depth) && \ + _Py_CheckRecursiveCall(where)) +#define Py_LeaveRecursiveCall() \ do{ if(_Py_MakeEndRecCheck(PyThreadState_GET()->recursion_depth)) \ - PyThreadState_GET()->overflowed = 0; \ - } while(0) + PyThreadState_GET()->overflowed = 0; \ + } while(0) PyAPI_FUNC(int) _Py_CheckRecursiveCall(char *where); PyAPI_DATA(int) _Py_CheckRecursionLimit; @@ -83,15 +83,15 @@ of _Py_CheckRecursionLimit for _Py_MakeEndRecCheck() to function properly. */ # define _Py_MakeRecCheck(x) \ - (++(x) > (_Py_CheckRecursionLimit += PyThreadState_GET()->overflowed - 1)) + (++(x) > (_Py_CheckRecursionLimit += PyThreadState_GET()->overflowed - 1)) #else # define _Py_MakeRecCheck(x) (++(x) > _Py_CheckRecursionLimit) #endif #define _Py_MakeEndRecCheck(x) \ - (--(x) < ((_Py_CheckRecursionLimit > 100) \ - ? (_Py_CheckRecursionLimit - 50) \ - : (3 * (_Py_CheckRecursionLimit >> 2)))) + (--(x) < ((_Py_CheckRecursionLimit > 100) \ + ? (_Py_CheckRecursionLimit - 50) \ + : (3 * (_Py_CheckRecursionLimit >> 2)))) #define Py_ALLOW_RECURSION \ do { unsigned char _old = PyThreadState_GET()->recursion_critical;\ @@ -114,31 +114,31 @@ that lasts a long time and doesn't touch Python data) can allow other threads to run as follows: - ...preparations here... - Py_BEGIN_ALLOW_THREADS - ...blocking system call here... - Py_END_ALLOW_THREADS - ...interpret result here... + ...preparations here... + Py_BEGIN_ALLOW_THREADS + ...blocking system call here... + Py_END_ALLOW_THREADS + ...interpret result here... The Py_BEGIN_ALLOW_THREADS/Py_END_ALLOW_THREADS pair expands to a {}-surrounded block. To leave the block in the middle (e.g., with return), you must insert a line containing Py_BLOCK_THREADS before the return, e.g. - if (...premature_exit...) { - Py_BLOCK_THREADS - PyErr_SetFromErrno(PyExc_IOError); - return NULL; - } + if (...premature_exit...) { + Py_BLOCK_THREADS + PyErr_SetFromErrno(PyExc_IOError); + return NULL; + } An alternative is: - Py_BLOCK_THREADS - if (...premature_exit...) { - PyErr_SetFromErrno(PyExc_IOError); - return NULL; - } - Py_UNBLOCK_THREADS + Py_BLOCK_THREADS + if (...premature_exit...) { + PyErr_SetFromErrno(PyExc_IOError); + return NULL; + } + Py_UNBLOCK_THREADS For convenience, that the value of 'errno' is restored across Py_END_ALLOW_THREADS and Py_BLOCK_THREADS. @@ -170,12 +170,12 @@ PyAPI_FUNC(unsigned long) _PyEval_GetSwitchInterval(void); #define Py_BEGIN_ALLOW_THREADS { \ - PyThreadState *_save; \ - _save = PyEval_SaveThread(); -#define Py_BLOCK_THREADS PyEval_RestoreThread(_save); -#define Py_UNBLOCK_THREADS _save = PyEval_SaveThread(); -#define Py_END_ALLOW_THREADS PyEval_RestoreThread(_save); \ - } + PyThreadState *_save; \ + _save = PyEval_SaveThread(); +#define Py_BLOCK_THREADS PyEval_RestoreThread(_save); +#define Py_UNBLOCK_THREADS _save = PyEval_SaveThread(); +#define Py_END_ALLOW_THREADS PyEval_RestoreThread(_save); \ + } #else /* !WITH_THREAD */ Modified: python/branches/py3k/Include/datetime.h ============================================================================== --- python/branches/py3k/Include/datetime.h (original) +++ python/branches/py3k/Include/datetime.h Sun May 9 17:52:27 2010 @@ -11,13 +11,13 @@ * big-endian, unless otherwise noted: * * byte offset - * 0 year 2 bytes, 1-9999 - * 2 month 1 byte, 1-12 - * 3 day 1 byte, 1-31 - * 4 hour 1 byte, 0-23 - * 5 minute 1 byte, 0-59 - * 6 second 1 byte, 0-59 - * 7 usecond 3 bytes, 0-999999 + * 0 year 2 bytes, 1-9999 + * 2 month 1 byte, 1-12 + * 3 day 1 byte, 1-31 + * 4 hour 1 byte, 0-23 + * 5 minute 1 byte, 0-59 + * 6 second 1 byte, 0-59 + * 7 usecond 3 bytes, 0-999999 * 10 */ @@ -33,26 +33,26 @@ typedef struct { - PyObject_HEAD - long hashcode; /* -1 when unknown */ - int days; /* -MAX_DELTA_DAYS <= days <= MAX_DELTA_DAYS */ - int seconds; /* 0 <= seconds < 24*3600 is invariant */ - int microseconds; /* 0 <= microseconds < 1000000 is invariant */ + PyObject_HEAD + long hashcode; /* -1 when unknown */ + int days; /* -MAX_DELTA_DAYS <= days <= MAX_DELTA_DAYS */ + int seconds; /* 0 <= seconds < 24*3600 is invariant */ + int microseconds; /* 0 <= microseconds < 1000000 is invariant */ } PyDateTime_Delta; typedef struct { - PyObject_HEAD /* a pure abstract base clase */ + PyObject_HEAD /* a pure abstract base clase */ } PyDateTime_TZInfo; /* The datetime and time types have hashcodes, and an optional tzinfo member, * present if and only if hastzinfo is true. */ -#define _PyTZINFO_HEAD \ - PyObject_HEAD \ - long hashcode; \ - char hastzinfo; /* boolean flag */ +#define _PyTZINFO_HEAD \ + PyObject_HEAD \ + long hashcode; \ + char hastzinfo; /* boolean flag */ /* No _PyDateTime_BaseTZInfo is allocated; it's just to have something * convenient to cast to, when getting at the hastzinfo member of objects @@ -60,7 +60,7 @@ */ typedef struct { - _PyTZINFO_HEAD + _PyTZINFO_HEAD } _PyDateTime_BaseTZInfo; /* All time objects are of PyDateTime_TimeType, but that can be allocated @@ -69,20 +69,20 @@ * internal struct used to allocate the right amount of space for the * "without" case. */ -#define _PyDateTime_TIMEHEAD \ - _PyTZINFO_HEAD \ - unsigned char data[_PyDateTime_TIME_DATASIZE]; +#define _PyDateTime_TIMEHEAD \ + _PyTZINFO_HEAD \ + unsigned char data[_PyDateTime_TIME_DATASIZE]; typedef struct { - _PyDateTime_TIMEHEAD -} _PyDateTime_BaseTime; /* hastzinfo false */ + _PyDateTime_TIMEHEAD +} _PyDateTime_BaseTime; /* hastzinfo false */ typedef struct { - _PyDateTime_TIMEHEAD - PyObject *tzinfo; -} PyDateTime_Time; /* hastzinfo true */ + _PyDateTime_TIMEHEAD + PyObject *tzinfo; +} PyDateTime_Time; /* hastzinfo true */ /* All datetime objects are of PyDateTime_DateTimeType, but that can be @@ -92,48 +92,48 @@ */ typedef struct { - _PyTZINFO_HEAD - unsigned char data[_PyDateTime_DATE_DATASIZE]; + _PyTZINFO_HEAD + unsigned char data[_PyDateTime_DATE_DATASIZE]; } PyDateTime_Date; -#define _PyDateTime_DATETIMEHEAD \ - _PyTZINFO_HEAD \ - unsigned char data[_PyDateTime_DATETIME_DATASIZE]; +#define _PyDateTime_DATETIMEHEAD \ + _PyTZINFO_HEAD \ + unsigned char data[_PyDateTime_DATETIME_DATASIZE]; typedef struct { - _PyDateTime_DATETIMEHEAD -} _PyDateTime_BaseDateTime; /* hastzinfo false */ + _PyDateTime_DATETIMEHEAD +} _PyDateTime_BaseDateTime; /* hastzinfo false */ typedef struct { - _PyDateTime_DATETIMEHEAD - PyObject *tzinfo; -} PyDateTime_DateTime; /* hastzinfo true */ + _PyDateTime_DATETIMEHEAD + PyObject *tzinfo; +} PyDateTime_DateTime; /* hastzinfo true */ /* Apply for date and datetime instances. */ #define PyDateTime_GET_YEAR(o) ((((PyDateTime_Date*)o)->data[0] << 8) | \ - ((PyDateTime_Date*)o)->data[1]) + ((PyDateTime_Date*)o)->data[1]) #define PyDateTime_GET_MONTH(o) (((PyDateTime_Date*)o)->data[2]) #define PyDateTime_GET_DAY(o) (((PyDateTime_Date*)o)->data[3]) #define PyDateTime_DATE_GET_HOUR(o) (((PyDateTime_DateTime*)o)->data[4]) #define PyDateTime_DATE_GET_MINUTE(o) (((PyDateTime_DateTime*)o)->data[5]) #define PyDateTime_DATE_GET_SECOND(o) (((PyDateTime_DateTime*)o)->data[6]) -#define PyDateTime_DATE_GET_MICROSECOND(o) \ - ((((PyDateTime_DateTime*)o)->data[7] << 16) | \ - (((PyDateTime_DateTime*)o)->data[8] << 8) | \ - ((PyDateTime_DateTime*)o)->data[9]) +#define PyDateTime_DATE_GET_MICROSECOND(o) \ + ((((PyDateTime_DateTime*)o)->data[7] << 16) | \ + (((PyDateTime_DateTime*)o)->data[8] << 8) | \ + ((PyDateTime_DateTime*)o)->data[9]) /* Apply for time instances. */ #define PyDateTime_TIME_GET_HOUR(o) (((PyDateTime_Time*)o)->data[0]) #define PyDateTime_TIME_GET_MINUTE(o) (((PyDateTime_Time*)o)->data[1]) #define PyDateTime_TIME_GET_SECOND(o) (((PyDateTime_Time*)o)->data[2]) -#define PyDateTime_TIME_GET_MICROSECOND(o) \ - ((((PyDateTime_Time*)o)->data[3] << 16) | \ - (((PyDateTime_Time*)o)->data[4] << 8) | \ - ((PyDateTime_Time*)o)->data[5]) +#define PyDateTime_TIME_GET_MICROSECOND(o) \ + ((((PyDateTime_Time*)o)->data[3] << 16) | \ + (((PyDateTime_Time*)o)->data[4] << 8) | \ + ((PyDateTime_Time*)o)->data[5]) /* Define structure for C API. */ @@ -148,7 +148,7 @@ /* constructors */ PyObject *(*Date_FromDate)(int, int, int, PyTypeObject*); PyObject *(*DateTime_FromDateAndTime)(int, int, int, int, int, int, int, - PyObject*, PyTypeObject*); + PyObject*, PyTypeObject*); PyObject *(*Time_FromTime)(int, int, int, int, PyObject*, PyTypeObject*); PyObject *(*Delta_FromDelta)(int, int, int, int, PyTypeObject*); @@ -185,7 +185,7 @@ static PyDateTime_CAPI *PyDateTimeAPI = NULL; #define PyDateTime_IMPORT \ - PyDateTimeAPI = (PyDateTime_CAPI *)PyCapsule_Import(PyDateTime_CAPSULE_NAME, 0) + PyDateTimeAPI = (PyDateTime_CAPI *)PyCapsule_Import(PyDateTime_CAPSULE_NAME, 0) /* Macros for type checking when not building the Python core. */ #define PyDate_Check(op) PyObject_TypeCheck(op, PyDateTimeAPI->DateType) @@ -205,30 +205,30 @@ /* Macros for accessing constructors in a simplified fashion. */ #define PyDate_FromDate(year, month, day) \ - PyDateTimeAPI->Date_FromDate(year, month, day, PyDateTimeAPI->DateType) + PyDateTimeAPI->Date_FromDate(year, month, day, PyDateTimeAPI->DateType) #define PyDateTime_FromDateAndTime(year, month, day, hour, min, sec, usec) \ - PyDateTimeAPI->DateTime_FromDateAndTime(year, month, day, hour, \ - min, sec, usec, Py_None, PyDateTimeAPI->DateTimeType) + PyDateTimeAPI->DateTime_FromDateAndTime(year, month, day, hour, \ + min, sec, usec, Py_None, PyDateTimeAPI->DateTimeType) #define PyTime_FromTime(hour, minute, second, usecond) \ - PyDateTimeAPI->Time_FromTime(hour, minute, second, usecond, \ - Py_None, PyDateTimeAPI->TimeType) + PyDateTimeAPI->Time_FromTime(hour, minute, second, usecond, \ + Py_None, PyDateTimeAPI->TimeType) #define PyDelta_FromDSU(days, seconds, useconds) \ - PyDateTimeAPI->Delta_FromDelta(days, seconds, useconds, 1, \ - PyDateTimeAPI->DeltaType) + PyDateTimeAPI->Delta_FromDelta(days, seconds, useconds, 1, \ + PyDateTimeAPI->DeltaType) /* Macros supporting the DB API. */ #define PyDateTime_FromTimestamp(args) \ - PyDateTimeAPI->DateTime_FromTimestamp( \ - (PyObject*) (PyDateTimeAPI->DateTimeType), args, NULL) + PyDateTimeAPI->DateTime_FromTimestamp( \ + (PyObject*) (PyDateTimeAPI->DateTimeType), args, NULL) #define PyDate_FromTimestamp(args) \ - PyDateTimeAPI->Date_FromTimestamp( \ - (PyObject*) (PyDateTimeAPI->DateType), args) + PyDateTimeAPI->Date_FromTimestamp( \ + (PyObject*) (PyDateTimeAPI->DateType), args) -#endif /* Py_BUILD_CORE */ +#endif /* Py_BUILD_CORE */ #ifdef __cplusplus } Modified: python/branches/py3k/Include/descrobject.h ============================================================================== --- python/branches/py3k/Include/descrobject.h (original) +++ python/branches/py3k/Include/descrobject.h Sun May 9 17:52:27 2010 @@ -9,27 +9,27 @@ typedef int (*setter)(PyObject *, PyObject *, void *); typedef struct PyGetSetDef { - char *name; - getter get; - setter set; - char *doc; - void *closure; + char *name; + getter get; + setter set; + char *doc; + void *closure; } PyGetSetDef; typedef PyObject *(*wrapperfunc)(PyObject *self, PyObject *args, - void *wrapped); + void *wrapped); typedef PyObject *(*wrapperfunc_kwds)(PyObject *self, PyObject *args, - void *wrapped, PyObject *kwds); + void *wrapped, PyObject *kwds); struct wrapperbase { - char *name; - int offset; - void *function; - wrapperfunc wrapper; - char *doc; - int flags; - PyObject *name_strobj; + char *name; + int offset; + void *function; + wrapperfunc wrapper; + char *doc; + int flags; + PyObject *name_strobj; }; /* Flags for above struct */ @@ -38,9 +38,9 @@ /* Various kinds of descriptor objects */ typedef struct { - PyObject_HEAD - PyTypeObject *d_type; - PyObject *d_name; + PyObject_HEAD + PyTypeObject *d_type; + PyObject *d_name; } PyDescrObject; #define PyDescr_COMMON PyDescrObject d_common @@ -49,24 +49,24 @@ #define PyDescr_NAME(x) (((PyDescrObject *)(x))->d_name) typedef struct { - PyDescr_COMMON; - PyMethodDef *d_method; + PyDescr_COMMON; + PyMethodDef *d_method; } PyMethodDescrObject; typedef struct { - PyDescr_COMMON; - struct PyMemberDef *d_member; + PyDescr_COMMON; + struct PyMemberDef *d_member; } PyMemberDescrObject; typedef struct { - PyDescr_COMMON; - PyGetSetDef *d_getset; + PyDescr_COMMON; + PyGetSetDef *d_getset; } PyGetSetDescrObject; typedef struct { - PyDescr_COMMON; - struct wrapperbase *d_base; - void *d_wrapped; /* This can be any function pointer */ + PyDescr_COMMON; + struct wrapperbase *d_base; + void *d_wrapped; /* This can be any function pointer */ } PyWrapperDescrObject; PyAPI_DATA(PyTypeObject) PyClassMethodDescr_Type; @@ -79,11 +79,11 @@ PyAPI_FUNC(PyObject *) PyDescr_NewMethod(PyTypeObject *, PyMethodDef *); PyAPI_FUNC(PyObject *) PyDescr_NewClassMethod(PyTypeObject *, PyMethodDef *); PyAPI_FUNC(PyObject *) PyDescr_NewMember(PyTypeObject *, - struct PyMemberDef *); + struct PyMemberDef *); PyAPI_FUNC(PyObject *) PyDescr_NewGetSet(PyTypeObject *, - struct PyGetSetDef *); + struct PyGetSetDef *); PyAPI_FUNC(PyObject *) PyDescr_NewWrapper(PyTypeObject *, - struct wrapperbase *, void *); + struct wrapperbase *, void *); #define PyDescr_IsData(d) (Py_TYPE(d)->tp_descr_set != NULL) PyAPI_FUNC(PyObject *) PyDictProxy_New(PyObject *); Modified: python/branches/py3k/Include/dictobject.h ============================================================================== --- python/branches/py3k/Include/dictobject.h (original) +++ python/branches/py3k/Include/dictobject.h Sun May 9 17:52:27 2010 @@ -48,13 +48,13 @@ #define PyDict_MINSIZE 8 typedef struct { - /* Cached hash code of me_key. Note that hash codes are C longs. - * We have to use Py_ssize_t instead because dict_popitem() abuses - * me_hash to hold a search finger. - */ - Py_ssize_t me_hash; - PyObject *me_key; - PyObject *me_value; + /* Cached hash code of me_key. Note that hash codes are C longs. + * We have to use Py_ssize_t instead because dict_popitem() abuses + * me_hash to hold a search finger. + */ + Py_ssize_t me_hash; + PyObject *me_key; + PyObject *me_value; } PyDictEntry; /* @@ -68,24 +68,24 @@ */ typedef struct _dictobject PyDictObject; struct _dictobject { - PyObject_HEAD - Py_ssize_t ma_fill; /* # Active + # Dummy */ - Py_ssize_t ma_used; /* # Active */ - - /* The table contains ma_mask + 1 slots, and that's a power of 2. - * We store the mask instead of the size because the mask is more - * frequently needed. - */ - Py_ssize_t ma_mask; - - /* ma_table points to ma_smalltable for small tables, else to - * additional malloc'ed memory. ma_table is never NULL! This rule - * saves repeated runtime null-tests in the workhorse getitem and - * setitem calls. - */ - PyDictEntry *ma_table; - PyDictEntry *(*ma_lookup)(PyDictObject *mp, PyObject *key, long hash); - PyDictEntry ma_smalltable[PyDict_MINSIZE]; + PyObject_HEAD + Py_ssize_t ma_fill; /* # Active + # Dummy */ + Py_ssize_t ma_used; /* # Active */ + + /* The table contains ma_mask + 1 slots, and that's a power of 2. + * We store the mask instead of the size because the mask is more + * frequently needed. + */ + Py_ssize_t ma_mask; + + /* ma_table points to ma_smalltable for small tables, else to + * additional malloc'ed memory. ma_table is never NULL! This rule + * saves repeated runtime null-tests in the workhorse getitem and + * setitem calls. + */ + PyDictEntry *ma_table; + PyDictEntry *(*ma_lookup)(PyDictObject *mp, PyObject *key, long hash); + PyDictEntry ma_smalltable[PyDict_MINSIZE]; }; PyAPI_DATA(PyTypeObject) PyDict_Type; @@ -104,7 +104,7 @@ #define PyDictValues_Check(op) (Py_TYPE(op) == &PyDictValues_Type) /* This excludes Values, since they are not sets. */ # define PyDictViewSet_Check(op) \ - (PyDictKeys_Check(op) || PyDictItems_Check(op)) + (PyDictKeys_Check(op) || PyDictItems_Check(op)) PyAPI_FUNC(PyObject *) PyDict_New(void); @@ -114,9 +114,9 @@ PyAPI_FUNC(int) PyDict_DelItem(PyObject *mp, PyObject *key); PyAPI_FUNC(void) PyDict_Clear(PyObject *mp); PyAPI_FUNC(int) PyDict_Next( - PyObject *mp, Py_ssize_t *pos, PyObject **key, PyObject **value); + PyObject *mp, Py_ssize_t *pos, PyObject **key, PyObject **value); PyAPI_FUNC(int) _PyDict_Next( - PyObject *mp, Py_ssize_t *pos, PyObject **key, PyObject **value, long *hash); + PyObject *mp, Py_ssize_t *pos, PyObject **key, PyObject **value, long *hash); PyAPI_FUNC(PyObject *) PyDict_Keys(PyObject *mp); PyAPI_FUNC(PyObject *) PyDict_Values(PyObject *mp); PyAPI_FUNC(PyObject *) PyDict_Items(PyObject *mp); @@ -137,8 +137,8 @@ dict.update(other) is equivalent to PyDict_Merge(dict, other, 1). */ PyAPI_FUNC(int) PyDict_Merge(PyObject *mp, - PyObject *other, - int override); + PyObject *other, + int override); /* PyDict_MergeFromSeq2 updates/merges from an iterable object producing iterable objects of length 2. If override is true, the last occurrence @@ -146,8 +146,8 @@ is equivalent to dict={}; PyDict_MergeFromSeq(dict, seq2, 1). */ PyAPI_FUNC(int) PyDict_MergeFromSeq2(PyObject *d, - PyObject *seq2, - int override); + PyObject *seq2, + int override); PyAPI_FUNC(PyObject *) PyDict_GetItemString(PyObject *dp, const char *key); PyAPI_FUNC(int) PyDict_SetItemString(PyObject *dp, const char *key, PyObject *item); Modified: python/branches/py3k/Include/object.h ============================================================================== --- python/branches/py3k/Include/object.h (original) +++ python/branches/py3k/Include/object.h Sun May 9 17:52:27 2010 @@ -63,9 +63,9 @@ #ifdef Py_TRACE_REFS /* Define pointers to support a doubly-linked list of all live heap objects. */ -#define _PyObject_HEAD_EXTRA \ - struct _object *_ob_next; \ - struct _object *_ob_prev; +#define _PyObject_HEAD_EXTRA \ + struct _object *_ob_next; \ + struct _object *_ob_prev; #define _PyObject_EXTRA_INIT 0, 0, @@ -75,14 +75,14 @@ #endif /* PyObject_HEAD defines the initial segment of every PyObject. */ -#define PyObject_HEAD PyObject ob_base; +#define PyObject_HEAD PyObject ob_base; -#define PyObject_HEAD_INIT(type) \ - { _PyObject_EXTRA_INIT \ - 1, type }, +#define PyObject_HEAD_INIT(type) \ + { _PyObject_EXTRA_INIT \ + 1, type }, -#define PyVarObject_HEAD_INIT(type, size) \ - { PyObject_HEAD_INIT(type) size }, +#define PyVarObject_HEAD_INIT(type, size) \ + { PyObject_HEAD_INIT(type) size }, /* PyObject_VAR_HEAD defines the initial segment of all variable-size * container objects. These end with a declaration of an array with 1 @@ -99,19 +99,19 @@ * in addition, be cast to PyVarObject*. */ typedef struct _object { - _PyObject_HEAD_EXTRA - Py_ssize_t ob_refcnt; - struct _typeobject *ob_type; + _PyObject_HEAD_EXTRA + Py_ssize_t ob_refcnt; + struct _typeobject *ob_type; } PyObject; typedef struct { - PyObject ob_base; - Py_ssize_t ob_size; /* Number of items in variable part */ + PyObject ob_base; + Py_ssize_t ob_size; /* Number of items in variable part */ } PyVarObject; -#define Py_REFCNT(ob) (((PyObject*)(ob))->ob_refcnt) -#define Py_TYPE(ob) (((PyObject*)(ob))->ob_type) -#define Py_SIZE(ob) (((PyVarObject*)(ob))->ob_size) +#define Py_REFCNT(ob) (((PyObject*)(ob))->ob_refcnt) +#define Py_TYPE(ob) (((PyObject*)(ob))->ob_type) +#define Py_SIZE(ob) (((PyVarObject*)(ob))->ob_size) /* Type objects contain a string containing the type name (to help somewhat @@ -142,26 +142,26 @@ /* buffer interface */ typedef struct bufferinfo { - void *buf; - PyObject *obj; /* owned reference */ - Py_ssize_t len; - Py_ssize_t itemsize; /* This is Py_ssize_t so it can be - pointed to by strides in simple case.*/ - int readonly; - int ndim; - char *format; - Py_ssize_t *shape; - Py_ssize_t *strides; - Py_ssize_t *suboffsets; - Py_ssize_t smalltable[2]; /* static store for shape and strides of - mono-dimensional buffers. */ - void *internal; + void *buf; + PyObject *obj; /* owned reference */ + Py_ssize_t len; + Py_ssize_t itemsize; /* This is Py_ssize_t so it can be + pointed to by strides in simple case.*/ + int readonly; + int ndim; + char *format; + Py_ssize_t *shape; + Py_ssize_t *strides; + Py_ssize_t *suboffsets; + Py_ssize_t smalltable[2]; /* static store for shape and strides of + mono-dimensional buffers. */ + void *internal; } Py_buffer; typedef int (*getbufferproc)(PyObject *, Py_buffer *, int); typedef void (*releasebufferproc)(PyObject *, Py_buffer *); - /* Flags for getting buffers */ + /* Flags for getting buffers */ #define PyBUF_SIMPLE 0 #define PyBUF_WRITABLE 0x0001 /* we used to include an E, backwards compatible alias */ @@ -198,67 +198,67 @@ typedef int (*traverseproc)(PyObject *, visitproc, void *); typedef struct { - /* Number implementations must check *both* - arguments for proper type and implement the necessary conversions - in the slot functions themselves. */ - - binaryfunc nb_add; - binaryfunc nb_subtract; - binaryfunc nb_multiply; - binaryfunc nb_remainder; - binaryfunc nb_divmod; - ternaryfunc nb_power; - unaryfunc nb_negative; - unaryfunc nb_positive; - unaryfunc nb_absolute; - inquiry nb_bool; - unaryfunc nb_invert; - binaryfunc nb_lshift; - binaryfunc nb_rshift; - binaryfunc nb_and; - binaryfunc nb_xor; - binaryfunc nb_or; - unaryfunc nb_int; - void *nb_reserved; /* the slot formerly known as nb_long */ - unaryfunc nb_float; - - binaryfunc nb_inplace_add; - binaryfunc nb_inplace_subtract; - binaryfunc nb_inplace_multiply; - binaryfunc nb_inplace_remainder; - ternaryfunc nb_inplace_power; - binaryfunc nb_inplace_lshift; - binaryfunc nb_inplace_rshift; - binaryfunc nb_inplace_and; - binaryfunc nb_inplace_xor; - binaryfunc nb_inplace_or; - - binaryfunc nb_floor_divide; - binaryfunc nb_true_divide; - binaryfunc nb_inplace_floor_divide; - binaryfunc nb_inplace_true_divide; + /* Number implementations must check *both* + arguments for proper type and implement the necessary conversions + in the slot functions themselves. */ + + binaryfunc nb_add; + binaryfunc nb_subtract; + binaryfunc nb_multiply; + binaryfunc nb_remainder; + binaryfunc nb_divmod; + ternaryfunc nb_power; + unaryfunc nb_negative; + unaryfunc nb_positive; + unaryfunc nb_absolute; + inquiry nb_bool; + unaryfunc nb_invert; + binaryfunc nb_lshift; + binaryfunc nb_rshift; + binaryfunc nb_and; + binaryfunc nb_xor; + binaryfunc nb_or; + unaryfunc nb_int; + void *nb_reserved; /* the slot formerly known as nb_long */ + unaryfunc nb_float; + + binaryfunc nb_inplace_add; + binaryfunc nb_inplace_subtract; + binaryfunc nb_inplace_multiply; + binaryfunc nb_inplace_remainder; + ternaryfunc nb_inplace_power; + binaryfunc nb_inplace_lshift; + binaryfunc nb_inplace_rshift; + binaryfunc nb_inplace_and; + binaryfunc nb_inplace_xor; + binaryfunc nb_inplace_or; + + binaryfunc nb_floor_divide; + binaryfunc nb_true_divide; + binaryfunc nb_inplace_floor_divide; + binaryfunc nb_inplace_true_divide; - unaryfunc nb_index; + unaryfunc nb_index; } PyNumberMethods; typedef struct { - lenfunc sq_length; - binaryfunc sq_concat; - ssizeargfunc sq_repeat; - ssizeargfunc sq_item; - void *was_sq_slice; - ssizeobjargproc sq_ass_item; - void *was_sq_ass_slice; - objobjproc sq_contains; + lenfunc sq_length; + binaryfunc sq_concat; + ssizeargfunc sq_repeat; + ssizeargfunc sq_item; + void *was_sq_slice; + ssizeobjargproc sq_ass_item; + void *was_sq_ass_slice; + objobjproc sq_contains; - binaryfunc sq_inplace_concat; - ssizeargfunc sq_inplace_repeat; + binaryfunc sq_inplace_concat; + ssizeargfunc sq_inplace_repeat; } PySequenceMethods; typedef struct { - lenfunc mp_length; - binaryfunc mp_subscript; - objobjargproc mp_ass_subscript; + lenfunc mp_length; + binaryfunc mp_subscript; + objobjargproc mp_ass_subscript; } PyMappingMethods; @@ -286,109 +286,109 @@ typedef PyObject *(*allocfunc)(struct _typeobject *, Py_ssize_t); typedef struct _typeobject { - PyObject_VAR_HEAD - const char *tp_name; /* For printing, in format "." */ - Py_ssize_t tp_basicsize, tp_itemsize; /* For allocation */ - - /* Methods to implement standard operations */ - - destructor tp_dealloc; - printfunc tp_print; - getattrfunc tp_getattr; - setattrfunc tp_setattr; - void *tp_reserved; /* formerly known as tp_compare */ - reprfunc tp_repr; - - /* Method suites for standard classes */ - - PyNumberMethods *tp_as_number; - PySequenceMethods *tp_as_sequence; - PyMappingMethods *tp_as_mapping; - - /* More standard operations (here for binary compatibility) */ - - hashfunc tp_hash; - ternaryfunc tp_call; - reprfunc tp_str; - getattrofunc tp_getattro; - setattrofunc tp_setattro; - - /* Functions to access object as input/output buffer */ - PyBufferProcs *tp_as_buffer; - - /* Flags to define presence of optional/expanded features */ - long tp_flags; - - const char *tp_doc; /* Documentation string */ - - /* Assigned meaning in release 2.0 */ - /* call function for all accessible objects */ - traverseproc tp_traverse; - - /* delete references to contained objects */ - inquiry tp_clear; - - /* Assigned meaning in release 2.1 */ - /* rich comparisons */ - richcmpfunc tp_richcompare; - - /* weak reference enabler */ - Py_ssize_t tp_weaklistoffset; - - /* Iterators */ - getiterfunc tp_iter; - iternextfunc tp_iternext; - - /* Attribute descriptor and subclassing stuff */ - struct PyMethodDef *tp_methods; - struct PyMemberDef *tp_members; - struct PyGetSetDef *tp_getset; - struct _typeobject *tp_base; - PyObject *tp_dict; - descrgetfunc tp_descr_get; - descrsetfunc tp_descr_set; - Py_ssize_t tp_dictoffset; - initproc tp_init; - allocfunc tp_alloc; - newfunc tp_new; - freefunc tp_free; /* Low-level free-memory routine */ - inquiry tp_is_gc; /* For PyObject_IS_GC */ - PyObject *tp_bases; - PyObject *tp_mro; /* method resolution order */ - PyObject *tp_cache; - PyObject *tp_subclasses; - PyObject *tp_weaklist; - destructor tp_del; + PyObject_VAR_HEAD + const char *tp_name; /* For printing, in format "." */ + Py_ssize_t tp_basicsize, tp_itemsize; /* For allocation */ + + /* Methods to implement standard operations */ + + destructor tp_dealloc; + printfunc tp_print; + getattrfunc tp_getattr; + setattrfunc tp_setattr; + void *tp_reserved; /* formerly known as tp_compare */ + reprfunc tp_repr; + + /* Method suites for standard classes */ + + PyNumberMethods *tp_as_number; + PySequenceMethods *tp_as_sequence; + PyMappingMethods *tp_as_mapping; + + /* More standard operations (here for binary compatibility) */ + + hashfunc tp_hash; + ternaryfunc tp_call; + reprfunc tp_str; + getattrofunc tp_getattro; + setattrofunc tp_setattro; + + /* Functions to access object as input/output buffer */ + PyBufferProcs *tp_as_buffer; + + /* Flags to define presence of optional/expanded features */ + long tp_flags; + + const char *tp_doc; /* Documentation string */ + + /* Assigned meaning in release 2.0 */ + /* call function for all accessible objects */ + traverseproc tp_traverse; + + /* delete references to contained objects */ + inquiry tp_clear; + + /* Assigned meaning in release 2.1 */ + /* rich comparisons */ + richcmpfunc tp_richcompare; + + /* weak reference enabler */ + Py_ssize_t tp_weaklistoffset; + + /* Iterators */ + getiterfunc tp_iter; + iternextfunc tp_iternext; + + /* Attribute descriptor and subclassing stuff */ + struct PyMethodDef *tp_methods; + struct PyMemberDef *tp_members; + struct PyGetSetDef *tp_getset; + struct _typeobject *tp_base; + PyObject *tp_dict; + descrgetfunc tp_descr_get; + descrsetfunc tp_descr_set; + Py_ssize_t tp_dictoffset; + initproc tp_init; + allocfunc tp_alloc; + newfunc tp_new; + freefunc tp_free; /* Low-level free-memory routine */ + inquiry tp_is_gc; /* For PyObject_IS_GC */ + PyObject *tp_bases; + PyObject *tp_mro; /* method resolution order */ + PyObject *tp_cache; + PyObject *tp_subclasses; + PyObject *tp_weaklist; + destructor tp_del; - /* Type attribute cache version tag. Added in version 2.6 */ - unsigned int tp_version_tag; + /* Type attribute cache version tag. Added in version 2.6 */ + unsigned int tp_version_tag; #ifdef COUNT_ALLOCS - /* these must be last and never explicitly initialized */ - Py_ssize_t tp_allocs; - Py_ssize_t tp_frees; - Py_ssize_t tp_maxalloc; - struct _typeobject *tp_prev; - struct _typeobject *tp_next; + /* these must be last and never explicitly initialized */ + Py_ssize_t tp_allocs; + Py_ssize_t tp_frees; + Py_ssize_t tp_maxalloc; + struct _typeobject *tp_prev; + struct _typeobject *tp_next; #endif } PyTypeObject; /* The *real* layout of a type object when allocated on the heap */ typedef struct _heaptypeobject { - /* Note: there's a dependency on the order of these members - in slotptr() in typeobject.c . */ - PyTypeObject ht_type; - PyNumberMethods as_number; - PyMappingMethods as_mapping; - PySequenceMethods as_sequence; /* as_sequence comes after as_mapping, - so that the mapping wins when both - the mapping and the sequence define - a given operator (e.g. __getitem__). - see add_operators() in typeobject.c . */ - PyBufferProcs as_buffer; - PyObject *ht_name, *ht_slots; - /* here are optional user slots, followed by the members. */ + /* Note: there's a dependency on the order of these members + in slotptr() in typeobject.c . */ + PyTypeObject ht_type; + PyNumberMethods as_number; + PyMappingMethods as_mapping; + PySequenceMethods as_sequence; /* as_sequence comes after as_mapping, + so that the mapping wins when both + the mapping and the sequence define + a given operator (e.g. __getitem__). + see add_operators() in typeobject.c . */ + PyBufferProcs as_buffer; + PyObject *ht_name, *ht_slots; + /* here are optional user slots, followed by the members. */ } PyHeapTypeObject; /* access macro to the members which are floating "behind" the object */ @@ -399,20 +399,20 @@ /* Generic type check */ PyAPI_FUNC(int) PyType_IsSubtype(PyTypeObject *, PyTypeObject *); #define PyObject_TypeCheck(ob, tp) \ - (Py_TYPE(ob) == (tp) || PyType_IsSubtype(Py_TYPE(ob), (tp))) + (Py_TYPE(ob) == (tp) || PyType_IsSubtype(Py_TYPE(ob), (tp))) PyAPI_DATA(PyTypeObject) PyType_Type; /* built-in 'type' */ PyAPI_DATA(PyTypeObject) PyBaseObject_Type; /* built-in 'object' */ PyAPI_DATA(PyTypeObject) PySuper_Type; /* built-in 'super' */ #define PyType_Check(op) \ - PyType_FastSubclass(Py_TYPE(op), Py_TPFLAGS_TYPE_SUBCLASS) + PyType_FastSubclass(Py_TYPE(op), Py_TPFLAGS_TYPE_SUBCLASS) #define PyType_CheckExact(op) (Py_TYPE(op) == &PyType_Type) PyAPI_FUNC(int) PyType_Ready(PyTypeObject *); PyAPI_FUNC(PyObject *) PyType_GenericAlloc(PyTypeObject *, Py_ssize_t); PyAPI_FUNC(PyObject *) PyType_GenericNew(PyTypeObject *, - PyObject *, PyObject *); + PyObject *, PyObject *); PyAPI_FUNC(PyObject *) _PyType_Lookup(PyTypeObject *, PyObject *); PyAPI_FUNC(PyObject *) _PyObject_LookupSpecial(PyObject *, char *, PyObject **); PyAPI_FUNC(unsigned int) PyType_ClearCache(void); @@ -439,7 +439,7 @@ PyAPI_FUNC(PyObject *) _PyObject_NextNotImplemented(PyObject *); PyAPI_FUNC(PyObject *) PyObject_GenericGetAttr(PyObject *, PyObject *); PyAPI_FUNC(int) PyObject_GenericSetAttr(PyObject *, - PyObject *, PyObject *); + PyObject *, PyObject *); PyAPI_FUNC(long) PyObject_Hash(PyObject *); PyAPI_FUNC(long) PyObject_HashNotImplemented(PyObject *); PyAPI_FUNC(int) PyObject_IsTrue(PyObject *); @@ -469,7 +469,7 @@ #define PyObject_REPR(obj) _PyUnicode_AsString(PyObject_Repr(obj)) /* Flag bits for printing: */ -#define Py_PRINT_RAW 1 /* No string quotes etc. */ +#define Py_PRINT_RAW 1 /* No string quotes etc. */ /* `Type flags (tp_flags) @@ -524,20 +524,20 @@ #define Py_TPFLAGS_IS_ABSTRACT (1L<<20) /* These flags are used to determine if a type is a subclass. */ -#define Py_TPFLAGS_INT_SUBCLASS (1L<<23) -#define Py_TPFLAGS_LONG_SUBCLASS (1L<<24) -#define Py_TPFLAGS_LIST_SUBCLASS (1L<<25) -#define Py_TPFLAGS_TUPLE_SUBCLASS (1L<<26) -#define Py_TPFLAGS_BYTES_SUBCLASS (1L<<27) -#define Py_TPFLAGS_UNICODE_SUBCLASS (1L<<28) -#define Py_TPFLAGS_DICT_SUBCLASS (1L<<29) -#define Py_TPFLAGS_BASE_EXC_SUBCLASS (1L<<30) -#define Py_TPFLAGS_TYPE_SUBCLASS (1L<<31) +#define Py_TPFLAGS_INT_SUBCLASS (1L<<23) +#define Py_TPFLAGS_LONG_SUBCLASS (1L<<24) +#define Py_TPFLAGS_LIST_SUBCLASS (1L<<25) +#define Py_TPFLAGS_TUPLE_SUBCLASS (1L<<26) +#define Py_TPFLAGS_BYTES_SUBCLASS (1L<<27) +#define Py_TPFLAGS_UNICODE_SUBCLASS (1L<<28) +#define Py_TPFLAGS_DICT_SUBCLASS (1L<<29) +#define Py_TPFLAGS_BASE_EXC_SUBCLASS (1L<<30) +#define Py_TPFLAGS_TYPE_SUBCLASS (1L<<31) #define Py_TPFLAGS_DEFAULT ( \ - Py_TPFLAGS_HAVE_STACKLESS_EXTENSION | \ - Py_TPFLAGS_HAVE_VERSION_TAG | \ - 0) + Py_TPFLAGS_HAVE_STACKLESS_EXTENSION | \ + Py_TPFLAGS_HAVE_VERSION_TAG | \ + 0) #define PyType_HasFeature(t,f) (((t)->tp_flags & (f)) != 0) #define PyType_FastSubclass(t,f) PyType_HasFeature(t,f) @@ -589,32 +589,32 @@ #ifdef Py_REF_DEBUG PyAPI_DATA(Py_ssize_t) _Py_RefTotal; PyAPI_FUNC(void) _Py_NegativeRefcount(const char *fname, - int lineno, PyObject *op); + int lineno, PyObject *op); PyAPI_FUNC(PyObject *) _PyDict_Dummy(void); PyAPI_FUNC(PyObject *) _PySet_Dummy(void); PyAPI_FUNC(Py_ssize_t) _Py_GetRefTotal(void); -#define _Py_INC_REFTOTAL _Py_RefTotal++ -#define _Py_DEC_REFTOTAL _Py_RefTotal-- -#define _Py_REF_DEBUG_COMMA , -#define _Py_CHECK_REFCNT(OP) \ -{ if (((PyObject*)OP)->ob_refcnt < 0) \ - _Py_NegativeRefcount(__FILE__, __LINE__, \ - (PyObject *)(OP)); \ +#define _Py_INC_REFTOTAL _Py_RefTotal++ +#define _Py_DEC_REFTOTAL _Py_RefTotal-- +#define _Py_REF_DEBUG_COMMA , +#define _Py_CHECK_REFCNT(OP) \ +{ if (((PyObject*)OP)->ob_refcnt < 0) \ + _Py_NegativeRefcount(__FILE__, __LINE__, \ + (PyObject *)(OP)); \ } #else #define _Py_INC_REFTOTAL #define _Py_DEC_REFTOTAL #define _Py_REF_DEBUG_COMMA -#define _Py_CHECK_REFCNT(OP) /* a semicolon */; +#define _Py_CHECK_REFCNT(OP) /* a semicolon */; #endif /* Py_REF_DEBUG */ #ifdef COUNT_ALLOCS PyAPI_FUNC(void) inc_count(PyTypeObject *); PyAPI_FUNC(void) dec_count(PyTypeObject *); -#define _Py_INC_TPALLOCS(OP) inc_count(Py_TYPE(OP)) -#define _Py_INC_TPFREES(OP) dec_count(Py_TYPE(OP)) -#define _Py_DEC_TPFREES(OP) Py_TYPE(OP)->tp_frees-- -#define _Py_COUNT_ALLOCS_COMMA , +#define _Py_INC_TPALLOCS(OP) inc_count(Py_TYPE(OP)) +#define _Py_INC_TPFREES(OP) dec_count(Py_TYPE(OP)) +#define _Py_DEC_TPFREES(OP) Py_TYPE(OP)->tp_frees-- +#define _Py_COUNT_ALLOCS_COMMA , #else #define _Py_INC_TPALLOCS(OP) #define _Py_INC_TPFREES(OP) @@ -635,30 +635,30 @@ /* Without Py_TRACE_REFS, there's little enough to do that we expand code * inline. */ -#define _Py_NewReference(op) ( \ - _Py_INC_TPALLOCS(op) _Py_COUNT_ALLOCS_COMMA \ - _Py_INC_REFTOTAL _Py_REF_DEBUG_COMMA \ - Py_REFCNT(op) = 1) +#define _Py_NewReference(op) ( \ + _Py_INC_TPALLOCS(op) _Py_COUNT_ALLOCS_COMMA \ + _Py_INC_REFTOTAL _Py_REF_DEBUG_COMMA \ + Py_REFCNT(op) = 1) #define _Py_ForgetReference(op) _Py_INC_TPFREES(op) -#define _Py_Dealloc(op) ( \ - _Py_INC_TPFREES(op) _Py_COUNT_ALLOCS_COMMA \ - (*Py_TYPE(op)->tp_dealloc)((PyObject *)(op))) +#define _Py_Dealloc(op) ( \ + _Py_INC_TPFREES(op) _Py_COUNT_ALLOCS_COMMA \ + (*Py_TYPE(op)->tp_dealloc)((PyObject *)(op))) #endif /* !Py_TRACE_REFS */ -#define Py_INCREF(op) ( \ - _Py_INC_REFTOTAL _Py_REF_DEBUG_COMMA \ - ((PyObject*)(op))->ob_refcnt++) - -#define Py_DECREF(op) \ - do { \ - if (_Py_DEC_REFTOTAL _Py_REF_DEBUG_COMMA \ - --((PyObject*)(op))->ob_refcnt != 0) \ - _Py_CHECK_REFCNT(op) \ - else \ - _Py_Dealloc((PyObject *)(op)); \ - } while (0) +#define Py_INCREF(op) ( \ + _Py_INC_REFTOTAL _Py_REF_DEBUG_COMMA \ + ((PyObject*)(op))->ob_refcnt++) + +#define Py_DECREF(op) \ + do { \ + if (_Py_DEC_REFTOTAL _Py_REF_DEBUG_COMMA \ + --((PyObject*)(op))->ob_refcnt != 0) \ + _Py_CHECK_REFCNT(op) \ + else \ + _Py_Dealloc((PyObject *)(op)); \ + } while (0) /* Safely decref `op` and set `op` to NULL, especially useful in tp_clear * and tp_dealloc implementatons. @@ -694,14 +694,14 @@ * Python integers aren't currently weakly referencable. Best practice is * to use Py_CLEAR() even if you can't think of a reason for why you need to. */ -#define Py_CLEAR(op) \ - do { \ - if (op) { \ - PyObject *_py_tmp = (PyObject *)(op); \ - (op) = NULL; \ - Py_DECREF(_py_tmp); \ - } \ - } while (0) +#define Py_CLEAR(op) \ + do { \ + if (op) { \ + PyObject *_py_tmp = (PyObject *)(op); \ + (op) = NULL; \ + Py_DECREF(_py_tmp); \ + } \ + } while (0) /* Macros to use in case the object pointer may be NULL: */ #define Py_XINCREF(op) do { if ((op) == NULL) ; else Py_INCREF(op); } while (0) @@ -813,13 +813,13 @@ static void mytype_dealloc(mytype *p) { - ... declarations go here ... + ... declarations go here ... - PyObject_GC_UnTrack(p); // must untrack first - Py_TRASHCAN_SAFE_BEGIN(p) - ... The body of the deallocator goes here, including all calls ... - ... to Py_DECREF on contained objects. ... - Py_TRASHCAN_SAFE_END(p) + PyObject_GC_UnTrack(p); // must untrack first + Py_TRASHCAN_SAFE_BEGIN(p) + ... The body of the deallocator goes here, including all calls ... + ... to Py_DECREF on contained objects. ... + Py_TRASHCAN_SAFE_END(p) } CAUTION: Never return from the middle of the body! If the body needs to @@ -849,16 +849,16 @@ #define PyTrash_UNWIND_LEVEL 50 #define Py_TRASHCAN_SAFE_BEGIN(op) \ - if (_PyTrash_delete_nesting < PyTrash_UNWIND_LEVEL) { \ - ++_PyTrash_delete_nesting; - /* The body of the deallocator is here. */ + if (_PyTrash_delete_nesting < PyTrash_UNWIND_LEVEL) { \ + ++_PyTrash_delete_nesting; + /* The body of the deallocator is here. */ #define Py_TRASHCAN_SAFE_END(op) \ - --_PyTrash_delete_nesting; \ - if (_PyTrash_delete_later && _PyTrash_delete_nesting <= 0) \ - _PyTrash_destroy_chain(); \ - } \ - else \ - _PyTrash_deposit_object((PyObject*)op); + --_PyTrash_delete_nesting; \ + if (_PyTrash_delete_later && _PyTrash_delete_nesting <= 0) \ + _PyTrash_destroy_chain(); \ + } \ + else \ + _PyTrash_deposit_object((PyObject*)op); #ifdef __cplusplus } Modified: python/branches/py3k/Include/objimpl.h ============================================================================== --- python/branches/py3k/Include/objimpl.h (original) +++ python/branches/py3k/Include/objimpl.h Sun May 9 17:52:27 2010 @@ -101,7 +101,7 @@ /* Macros */ #ifdef WITH_PYMALLOC -#ifdef PYMALLOC_DEBUG /* WITH_PYMALLOC && PYMALLOC_DEBUG */ +#ifdef PYMALLOC_DEBUG /* WITH_PYMALLOC && PYMALLOC_DEBUG */ PyAPI_FUNC(void *) _PyObject_DebugMalloc(size_t nbytes); PyAPI_FUNC(void *) _PyObject_DebugRealloc(void *p, size_t nbytes); PyAPI_FUNC(void) _PyObject_DebugFree(void *p); @@ -115,28 +115,28 @@ PyAPI_FUNC(void *) _PyMem_DebugMalloc(size_t nbytes); PyAPI_FUNC(void *) _PyMem_DebugRealloc(void *p, size_t nbytes); PyAPI_FUNC(void) _PyMem_DebugFree(void *p); -#define PyObject_MALLOC _PyObject_DebugMalloc -#define PyObject_Malloc _PyObject_DebugMalloc -#define PyObject_REALLOC _PyObject_DebugRealloc -#define PyObject_Realloc _PyObject_DebugRealloc -#define PyObject_FREE _PyObject_DebugFree -#define PyObject_Free _PyObject_DebugFree - -#else /* WITH_PYMALLOC && ! PYMALLOC_DEBUG */ -#define PyObject_MALLOC PyObject_Malloc -#define PyObject_REALLOC PyObject_Realloc -#define PyObject_FREE PyObject_Free +#define PyObject_MALLOC _PyObject_DebugMalloc +#define PyObject_Malloc _PyObject_DebugMalloc +#define PyObject_REALLOC _PyObject_DebugRealloc +#define PyObject_Realloc _PyObject_DebugRealloc +#define PyObject_FREE _PyObject_DebugFree +#define PyObject_Free _PyObject_DebugFree + +#else /* WITH_PYMALLOC && ! PYMALLOC_DEBUG */ +#define PyObject_MALLOC PyObject_Malloc +#define PyObject_REALLOC PyObject_Realloc +#define PyObject_FREE PyObject_Free #endif -#else /* ! WITH_PYMALLOC */ -#define PyObject_MALLOC PyMem_MALLOC -#define PyObject_REALLOC PyMem_REALLOC -#define PyObject_FREE PyMem_FREE +#else /* ! WITH_PYMALLOC */ +#define PyObject_MALLOC PyMem_MALLOC +#define PyObject_REALLOC PyMem_REALLOC +#define PyObject_FREE PyMem_FREE -#endif /* WITH_PYMALLOC */ +#endif /* WITH_PYMALLOC */ -#define PyObject_Del PyObject_Free -#define PyObject_DEL PyObject_FREE +#define PyObject_Del PyObject_Free +#define PyObject_DEL PyObject_FREE /* * Generic object allocator interface @@ -151,16 +151,16 @@ PyAPI_FUNC(PyVarObject *) _PyObject_NewVar(PyTypeObject *, Py_ssize_t); #define PyObject_New(type, typeobj) \ - ( (type *) _PyObject_New(typeobj) ) + ( (type *) _PyObject_New(typeobj) ) #define PyObject_NewVar(type, typeobj, n) \ - ( (type *) _PyObject_NewVar((typeobj), (n)) ) + ( (type *) _PyObject_NewVar((typeobj), (n)) ) /* Macros trading binary compatibility for speed. See also pymem.h. Note that these macros expect non-NULL object pointers.*/ #define PyObject_INIT(op, typeobj) \ - ( Py_TYPE(op) = (typeobj), _Py_NewReference((PyObject *)(op)), (op) ) + ( Py_TYPE(op) = (typeobj), _Py_NewReference((PyObject *)(op)), (op) ) #define PyObject_INIT_VAR(op, typeobj, size) \ - ( Py_SIZE(op) = (size), PyObject_INIT((op), (typeobj)) ) + ( Py_SIZE(op) = (size), PyObject_INIT((op), (typeobj)) ) #define _PyObject_SIZE(typeobj) ( (typeobj)->tp_basicsize ) @@ -178,17 +178,17 @@ # error "_PyObject_VAR_SIZE requires SIZEOF_VOID_P be a power of 2" #endif -#define _PyObject_VAR_SIZE(typeobj, nitems) \ - (size_t) \ - ( ( (typeobj)->tp_basicsize + \ - (nitems)*(typeobj)->tp_itemsize + \ - (SIZEOF_VOID_P - 1) \ - ) & ~(SIZEOF_VOID_P - 1) \ - ) +#define _PyObject_VAR_SIZE(typeobj, nitems) \ + (size_t) \ + ( ( (typeobj)->tp_basicsize + \ + (nitems)*(typeobj)->tp_itemsize + \ + (SIZEOF_VOID_P - 1) \ + ) & ~(SIZEOF_VOID_P - 1) \ + ) #define PyObject_NEW(type, typeobj) \ ( (type *) PyObject_Init( \ - (PyObject *) PyObject_MALLOC( _PyObject_SIZE(typeobj) ), (typeobj)) ) + (PyObject *) PyObject_MALLOC( _PyObject_SIZE(typeobj) ), (typeobj)) ) #define PyObject_NEW_VAR(type, typeobj, n) \ ( (type *) PyObject_InitVar( \ @@ -200,7 +200,7 @@ distinction between two steps (at least): 1) the actual allocation of the object storage; 2) the initialization of the Python specific fields - in this storage with PyObject_{Init, InitVar}. + in this storage with PyObject_{Init, InitVar}. PyObject * YourObject_New(...) @@ -209,7 +209,7 @@ op = (PyObject *) Your_Allocator(_PyObject_SIZE(YourTypeStruct)); if (op == NULL) - return PyErr_NoMemory(); + return PyErr_NoMemory(); PyObject_Init(op, &YourTypeStruct); @@ -236,44 +236,44 @@ /* Test if an object has a GC head */ #define PyObject_IS_GC(o) (PyType_IS_GC(Py_TYPE(o)) && \ - (Py_TYPE(o)->tp_is_gc == NULL || Py_TYPE(o)->tp_is_gc(o))) + (Py_TYPE(o)->tp_is_gc == NULL || Py_TYPE(o)->tp_is_gc(o))) PyAPI_FUNC(PyVarObject *) _PyObject_GC_Resize(PyVarObject *, Py_ssize_t); #define PyObject_GC_Resize(type, op, n) \ - ( (type *) _PyObject_GC_Resize((PyVarObject *)(op), (n)) ) + ( (type *) _PyObject_GC_Resize((PyVarObject *)(op), (n)) ) /* for source compatibility with 2.2 */ #define _PyObject_GC_Del PyObject_GC_Del /* GC information is stored BEFORE the object structure. */ typedef union _gc_head { - struct { - union _gc_head *gc_next; - union _gc_head *gc_prev; - Py_ssize_t gc_refs; - } gc; - long double dummy; /* force worst-case alignment */ + struct { + union _gc_head *gc_next; + union _gc_head *gc_prev; + Py_ssize_t gc_refs; + } gc; + long double dummy; /* force worst-case alignment */ } PyGC_Head; extern PyGC_Head *_PyGC_generation0; #define _Py_AS_GC(o) ((PyGC_Head *)(o)-1) -#define _PyGC_REFS_UNTRACKED (-2) -#define _PyGC_REFS_REACHABLE (-3) -#define _PyGC_REFS_TENTATIVELY_UNREACHABLE (-4) +#define _PyGC_REFS_UNTRACKED (-2) +#define _PyGC_REFS_REACHABLE (-3) +#define _PyGC_REFS_TENTATIVELY_UNREACHABLE (-4) /* Tell the GC to track this object. NB: While the object is tracked the * collector it must be safe to call the ob_traverse method. */ #define _PyObject_GC_TRACK(o) do { \ - PyGC_Head *g = _Py_AS_GC(o); \ - if (g->gc.gc_refs != _PyGC_REFS_UNTRACKED) \ - Py_FatalError("GC object already tracked"); \ - g->gc.gc_refs = _PyGC_REFS_REACHABLE; \ - g->gc.gc_next = _PyGC_generation0; \ - g->gc.gc_prev = _PyGC_generation0->gc.gc_prev; \ - g->gc.gc_prev->gc.gc_next = g; \ - _PyGC_generation0->gc.gc_prev = g; \ + PyGC_Head *g = _Py_AS_GC(o); \ + if (g->gc.gc_refs != _PyGC_REFS_UNTRACKED) \ + Py_FatalError("GC object already tracked"); \ + g->gc.gc_refs = _PyGC_REFS_REACHABLE; \ + g->gc.gc_next = _PyGC_generation0; \ + g->gc.gc_prev = _PyGC_generation0->gc.gc_prev; \ + g->gc.gc_prev->gc.gc_next = g; \ + _PyGC_generation0->gc.gc_prev = g; \ } while (0); /* Tell the GC to stop tracking this object. @@ -281,23 +281,23 @@ * way to provoke memory errors if calling code is confused. */ #define _PyObject_GC_UNTRACK(o) do { \ - PyGC_Head *g = _Py_AS_GC(o); \ - assert(g->gc.gc_refs != _PyGC_REFS_UNTRACKED); \ - g->gc.gc_refs = _PyGC_REFS_UNTRACKED; \ - g->gc.gc_prev->gc.gc_next = g->gc.gc_next; \ - g->gc.gc_next->gc.gc_prev = g->gc.gc_prev; \ - g->gc.gc_next = NULL; \ + PyGC_Head *g = _Py_AS_GC(o); \ + assert(g->gc.gc_refs != _PyGC_REFS_UNTRACKED); \ + g->gc.gc_refs = _PyGC_REFS_UNTRACKED; \ + g->gc.gc_prev->gc.gc_next = g->gc.gc_next; \ + g->gc.gc_next->gc.gc_prev = g->gc.gc_prev; \ + g->gc.gc_next = NULL; \ } while (0); /* True if the object is currently tracked by the GC. */ #define _PyObject_GC_IS_TRACKED(o) \ - ((_Py_AS_GC(o))->gc.gc_refs != _PyGC_REFS_UNTRACKED) - + ((_Py_AS_GC(o))->gc.gc_refs != _PyGC_REFS_UNTRACKED) + /* True if the object may be tracked by the GC in the future, or already is. This can be useful to implement some optimizations. */ #define _PyObject_GC_MAY_BE_TRACKED(obj) \ - (PyObject_IS_GC(obj) && \ - (!PyTuple_CheckExact(obj) || _PyObject_GC_IS_TRACKED(obj))) + (PyObject_IS_GC(obj) && \ + (!PyTuple_CheckExact(obj) || _PyObject_GC_IS_TRACKED(obj))) PyAPI_FUNC(PyObject *) _PyObject_GC_Malloc(size_t); @@ -308,9 +308,9 @@ PyAPI_FUNC(void) PyObject_GC_Del(void *); #define PyObject_GC_New(type, typeobj) \ - ( (type *) _PyObject_GC_New(typeobj) ) + ( (type *) _PyObject_GC_New(typeobj) ) #define PyObject_GC_NewVar(type, typeobj, n) \ - ( (type *) _PyObject_GC_NewVar((typeobj), (n)) ) + ( (type *) _PyObject_GC_NewVar((typeobj), (n)) ) /* Utility macro to help write tp_traverse functions. @@ -318,14 +318,14 @@ * "visit" and "arg". This is intended to keep tp_traverse functions * looking as much alike as possible. */ -#define Py_VISIT(op) \ - do { \ - if (op) { \ - int vret = visit((PyObject *)(op), arg); \ - if (vret) \ - return vret; \ - } \ - } while (0) +#define Py_VISIT(op) \ + do { \ + if (op) { \ + int vret = visit((PyObject *)(op), arg); \ + if (vret) \ + return vret; \ + } \ + } while (0) /* This is here for the sake of backwards compatibility. Extensions that * use the old GC API will still compile but the objects will not be @@ -341,7 +341,7 @@ #define PyType_SUPPORTS_WEAKREFS(t) ((t)->tp_weaklistoffset > 0) #define PyObject_GET_WEAKREFS_LISTPTR(o) \ - ((PyObject **) (((char *) (o)) + Py_TYPE(o)->tp_weaklistoffset)) + ((PyObject **) (((char *) (o)) + Py_TYPE(o)->tp_weaklistoffset)) #ifdef __cplusplus } Modified: python/branches/py3k/Include/pyerrors.h ============================================================================== --- python/branches/py3k/Include/pyerrors.h (original) +++ python/branches/py3k/Include/pyerrors.h Sun May 9 17:52:27 2010 @@ -8,8 +8,8 @@ /* PyException_HEAD defines the initial segment of every exception class. */ #define PyException_HEAD PyObject_HEAD PyObject *dict;\ - PyObject *args; PyObject *traceback;\ - PyObject *context; PyObject *cause; + PyObject *args; PyObject *traceback;\ + PyObject *context; PyObject *cause; typedef struct { PyException_HEAD @@ -92,15 +92,15 @@ /* */ -#define PyExceptionClass_Check(x) \ - (PyType_Check((x)) && \ - PyType_FastSubclass((PyTypeObject*)(x), Py_TPFLAGS_BASE_EXC_SUBCLASS)) +#define PyExceptionClass_Check(x) \ + (PyType_Check((x)) && \ + PyType_FastSubclass((PyTypeObject*)(x), Py_TPFLAGS_BASE_EXC_SUBCLASS)) -#define PyExceptionInstance_Check(x) \ - PyType_FastSubclass((x)->ob_type, Py_TPFLAGS_BASE_EXC_SUBCLASS) +#define PyExceptionInstance_Check(x) \ + PyType_FastSubclass((x)->ob_type, Py_TPFLAGS_BASE_EXC_SUBCLASS) #define PyExceptionClass_Name(x) \ - ((char *)(((PyTypeObject*)(x))->tp_name)) + ((char *)(((PyTypeObject*)(x))->tp_name)) #define PyExceptionInstance_Class(x) ((PyObject*)((x)->ob_type)) @@ -175,30 +175,30 @@ PyAPI_FUNC(PyObject *) PyErr_NoMemory(void); PyAPI_FUNC(PyObject *) PyErr_SetFromErrno(PyObject *); PyAPI_FUNC(PyObject *) PyErr_SetFromErrnoWithFilenameObject( - PyObject *, PyObject *); + PyObject *, PyObject *); PyAPI_FUNC(PyObject *) PyErr_SetFromErrnoWithFilename( - PyObject *, const char *); + PyObject *, const char *); #ifdef MS_WINDOWS PyAPI_FUNC(PyObject *) PyErr_SetFromErrnoWithUnicodeFilename( - PyObject *, const Py_UNICODE *); + PyObject *, const Py_UNICODE *); #endif /* MS_WINDOWS */ PyAPI_FUNC(PyObject *) PyErr_Format(PyObject *, const char *, ...); #ifdef MS_WINDOWS PyAPI_FUNC(PyObject *) PyErr_SetFromWindowsErrWithFilenameObject( - int, const char *); + int, const char *); PyAPI_FUNC(PyObject *) PyErr_SetFromWindowsErrWithFilename( - int, const char *); + int, const char *); PyAPI_FUNC(PyObject *) PyErr_SetFromWindowsErrWithUnicodeFilename( - int, const Py_UNICODE *); + int, const Py_UNICODE *); PyAPI_FUNC(PyObject *) PyErr_SetFromWindowsErr(int); PyAPI_FUNC(PyObject *) PyErr_SetExcFromWindowsErrWithFilenameObject( - PyObject *,int, PyObject *); + PyObject *,int, PyObject *); PyAPI_FUNC(PyObject *) PyErr_SetExcFromWindowsErrWithFilename( - PyObject *,int, const char *); + PyObject *,int, const char *); PyAPI_FUNC(PyObject *) PyErr_SetExcFromWindowsErrWithUnicodeFilename( - PyObject *,int, const Py_UNICODE *); + PyObject *,int, const Py_UNICODE *); PyAPI_FUNC(PyObject *) PyErr_SetExcFromWindowsErr(PyObject *, int); #endif /* MS_WINDOWS */ @@ -211,9 +211,9 @@ /* Function to create a new exception */ PyAPI_FUNC(PyObject *) PyErr_NewException( - const char *name, PyObject *base, PyObject *dict); + const char *name, PyObject *base, PyObject *dict); PyAPI_FUNC(PyObject *) PyErr_NewExceptionWithDoc( - const char *name, const char *doc, PyObject *base, PyObject *dict); + const char *name, const char *doc, PyObject *base, PyObject *dict); PyAPI_FUNC(void) PyErr_WriteUnraisable(PyObject *); /* In sigcheck.c or signalmodule.c */ @@ -232,15 +232,15 @@ /* create a UnicodeDecodeError object */ PyAPI_FUNC(PyObject *) PyUnicodeDecodeError_Create( - const char *, const char *, Py_ssize_t, Py_ssize_t, Py_ssize_t, const char *); + const char *, const char *, Py_ssize_t, Py_ssize_t, Py_ssize_t, const char *); /* create a UnicodeEncodeError object */ PyAPI_FUNC(PyObject *) PyUnicodeEncodeError_Create( - const char *, const Py_UNICODE *, Py_ssize_t, Py_ssize_t, Py_ssize_t, const char *); + const char *, const Py_UNICODE *, Py_ssize_t, Py_ssize_t, Py_ssize_t, const char *); /* create a UnicodeTranslateError object */ PyAPI_FUNC(PyObject *) PyUnicodeTranslateError_Create( - const Py_UNICODE *, Py_ssize_t, Py_ssize_t, Py_ssize_t, const char *); + const Py_UNICODE *, Py_ssize_t, Py_ssize_t, Py_ssize_t, const char *); /* get the encoding attribute */ PyAPI_FUNC(PyObject *) PyUnicodeEncodeError_GetEncoding(PyObject *); @@ -283,11 +283,11 @@ /* assign a new value to the reason attribute return 0 on success, -1 on failure */ PyAPI_FUNC(int) PyUnicodeEncodeError_SetReason( - PyObject *, const char *); + PyObject *, const char *); PyAPI_FUNC(int) PyUnicodeDecodeError_SetReason( - PyObject *, const char *); + PyObject *, const char *); PyAPI_FUNC(int) PyUnicodeTranslateError_SetReason( - PyObject *, const char *); + PyObject *, const char *); /* These APIs aren't really part of the error implementation, but @@ -306,9 +306,9 @@ #include PyAPI_FUNC(int) PyOS_snprintf(char *str, size_t size, const char *format, ...) - Py_GCC_ATTRIBUTE((format(printf, 3, 4))); + Py_GCC_ATTRIBUTE((format(printf, 3, 4))); PyAPI_FUNC(int) PyOS_vsnprintf(char *str, size_t size, const char *format, va_list va) - Py_GCC_ATTRIBUTE((format(printf, 3, 0))); + Py_GCC_ATTRIBUTE((format(printf, 3, 0))); #ifdef __cplusplus } Modified: python/branches/py3k/Include/pymacconfig.h ============================================================================== --- python/branches/py3k/Include/pymacconfig.h (original) +++ python/branches/py3k/Include/pymacconfig.h Sun May 9 17:52:27 2010 @@ -4,7 +4,7 @@ * This file moves some of the autoconf magic to compile-time * when building on MacOSX. This is needed for building 4-way * universal binaries and for 64-bit universal binaries because - * the values redefined below aren't configure-time constant but + * the values redefined below aren't configure-time constant but * only compile-time constant in these scenarios. */ @@ -36,40 +36,40 @@ # undef SIZEOF_LONG # ifdef __LP64__ -# define SIZEOF__BOOL 1 -# define SIZEOF__BOOL 1 -# define SIZEOF_LONG 8 -# define SIZEOF_PTHREAD_T 8 -# define SIZEOF_SIZE_T 8 -# define SIZEOF_TIME_T 8 -# define SIZEOF_VOID_P 8 -# define SIZEOF_UINTPTR_T 8 -# define SIZEOF_PTHREAD_T 8 +# define SIZEOF__BOOL 1 +# define SIZEOF__BOOL 1 +# define SIZEOF_LONG 8 +# define SIZEOF_PTHREAD_T 8 +# define SIZEOF_SIZE_T 8 +# define SIZEOF_TIME_T 8 +# define SIZEOF_VOID_P 8 +# define SIZEOF_UINTPTR_T 8 +# define SIZEOF_PTHREAD_T 8 # else # ifdef __ppc__ -# define SIZEOF__BOOL 4 +# define SIZEOF__BOOL 4 # else -# define SIZEOF__BOOL 1 +# define SIZEOF__BOOL 1 # endif -# define SIZEOF_LONG 4 -# define SIZEOF_PTHREAD_T 4 -# define SIZEOF_SIZE_T 4 -# define SIZEOF_TIME_T 4 -# define SIZEOF_VOID_P 4 -# define SIZEOF_UINTPTR_T 4 -# define SIZEOF_PTHREAD_T 4 +# define SIZEOF_LONG 4 +# define SIZEOF_PTHREAD_T 4 +# define SIZEOF_SIZE_T 4 +# define SIZEOF_TIME_T 4 +# define SIZEOF_VOID_P 4 +# define SIZEOF_UINTPTR_T 4 +# define SIZEOF_PTHREAD_T 4 # endif # if defined(__LP64__) - /* MacOSX 10.4 (the first release to suppport 64-bit code - * at all) only supports 64-bit in the UNIX layer. - * Therefore surpress the toolbox-glue in 64-bit mode. - */ - - /* In 64-bit mode setpgrp always has no argments, in 32-bit - * mode that depends on the compilation environment - */ -# undef SETPGRP_HAVE_ARG + /* MacOSX 10.4 (the first release to suppport 64-bit code + * at all) only supports 64-bit in the UNIX layer. + * Therefore surpress the toolbox-glue in 64-bit mode. + */ + + /* In 64-bit mode setpgrp always has no argments, in 32-bit + * mode that depends on the compilation environment + */ +# undef SETPGRP_HAVE_ARG # endif @@ -84,17 +84,17 @@ # define HAVE_GCC_ASM_FOR_X87 #endif - /* - * The definition in pyconfig.h is only valid on the OS release - * where configure ran on and not necessarily for all systems where - * the executable can be used on. - * - * Specifically: OSX 10.4 has limited supported for '%zd', while - * 10.5 has full support for '%zd'. A binary built on 10.5 won't - * work properly on 10.4 unless we surpress the definition - * of PY_FORMAT_SIZE_T - */ -#undef PY_FORMAT_SIZE_T + /* + * The definition in pyconfig.h is only valid on the OS release + * where configure ran on and not necessarily for all systems where + * the executable can be used on. + * + * Specifically: OSX 10.4 has limited supported for '%zd', while + * 10.5 has full support for '%zd'. A binary built on 10.5 won't + * work properly on 10.4 unless we surpress the definition + * of PY_FORMAT_SIZE_T + */ +#undef PY_FORMAT_SIZE_T #endif /* defined(_APPLE__) */ Modified: python/branches/py3k/Include/pyport.h ============================================================================== --- python/branches/py3k/Include/pyport.h (original) +++ python/branches/py3k/Include/pyport.h Sun May 9 17:52:27 2010 @@ -132,20 +132,20 @@ * integral type. */ #ifdef HAVE_UINTPTR_T -typedef uintptr_t Py_uintptr_t; -typedef intptr_t Py_intptr_t; +typedef uintptr_t Py_uintptr_t; +typedef intptr_t Py_intptr_t; #elif SIZEOF_VOID_P <= SIZEOF_INT -typedef unsigned int Py_uintptr_t; -typedef int Py_intptr_t; +typedef unsigned int Py_uintptr_t; +typedef int Py_intptr_t; #elif SIZEOF_VOID_P <= SIZEOF_LONG -typedef unsigned long Py_uintptr_t; -typedef long Py_intptr_t; +typedef unsigned long Py_uintptr_t; +typedef long Py_intptr_t; #elif defined(HAVE_LONG_LONG) && (SIZEOF_VOID_P <= SIZEOF_LONG_LONG) -typedef unsigned PY_LONG_LONG Py_uintptr_t; -typedef PY_LONG_LONG Py_intptr_t; +typedef unsigned PY_LONG_LONG Py_uintptr_t; +typedef PY_LONG_LONG Py_intptr_t; #else # error "Python needs a typedef for Py_uintptr_t in pyport.h." @@ -156,9 +156,9 @@ * unsigned integral type). See PEP 353 for details. */ #ifdef HAVE_SSIZE_T -typedef ssize_t Py_ssize_t; +typedef ssize_t Py_ssize_t; #elif SIZEOF_VOID_P == SIZEOF_SIZE_T -typedef Py_intptr_t Py_ssize_t; +typedef Py_intptr_t Py_ssize_t; #else # error "Python needs a typedef for Py_ssize_t in pyport.h." #endif @@ -166,7 +166,7 @@ /* Largest possible value of size_t. SIZE_MAX is part of C99, so it might be defined on some platforms. If it is not defined, (size_t)-1 is a portable - definition for C89, due to the way signed->unsigned + definition for C89, due to the way signed->unsigned conversion is defined. */ #ifdef SIZE_MAX #define PY_SIZE_MAX SIZE_MAX @@ -259,7 +259,7 @@ /* enable more aggressive optimization for visual studio */ #pragma optimize("agtw", on) #endif -/* ignore warnings if the compiler decides not to inline a function */ +/* ignore warnings if the compiler decides not to inline a function */ #pragma warning(disable: 4710) /* fastest possible local call under MSVC */ #define Py_LOCAL(type) static type __fastcall @@ -279,16 +279,16 @@ */ #if defined(_MSC_VER) -#define Py_MEMCPY(target, source, length) do { \ - size_t i_, n_ = (length); \ - char *t_ = (void*) (target); \ - const char *s_ = (void*) (source); \ - if (n_ >= 16) \ - memcpy(t_, s_, n_); \ - else \ - for (i_ = 0; i_ < n_; i_++) \ - t_[i_] = s_[i_]; \ - } while (0) +#define Py_MEMCPY(target, source, length) do { \ + size_t i_, n_ = (length); \ + char *t_ = (void*) (target); \ + const char *s_ = (void*) (source); \ + if (n_ >= 16) \ + memcpy(t_, s_, n_); \ + else \ + for (i_ = 0; i_ < n_; i_++) \ + t_[i_] = s_[i_]; \ + } while (0) #else #define Py_MEMCPY memcpy #endif @@ -403,7 +403,7 @@ */ #ifdef SIGNED_RIGHT_SHIFT_ZERO_FILLS #define Py_ARITHMETIC_RIGHT_SHIFT(TYPE, I, J) \ - ((I) < 0 ? -1-((-1-(I)) >> (J)) : (I) >> (J)) + ((I) < 0 ? -1-((-1-(I)) >> (J)) : (I) >> (J)) #else #define Py_ARITHMETIC_RIGHT_SHIFT(TYPE, I, J) ((I) >> (J)) #endif @@ -423,7 +423,7 @@ */ #ifdef Py_DEBUG #define Py_SAFE_DOWNCAST(VALUE, WIDE, NARROW) \ - (assert((WIDE)(NARROW)(VALUE) == (VALUE)), (NARROW)(VALUE)) + (assert((WIDE)(NARROW)(VALUE) == (VALUE)), (NARROW)(VALUE)) #else #define Py_SAFE_DOWNCAST(VALUE, WIDE, NARROW) (NARROW)(VALUE) #endif @@ -443,13 +443,13 @@ #define _Py_SET_EDOM_FOR_NAN(X) ; #endif #define Py_SET_ERRNO_ON_MATH_ERROR(X) \ - do { \ - if (errno == 0) { \ - if ((X) == Py_HUGE_VAL || (X) == -Py_HUGE_VAL) \ - errno = ERANGE; \ - else _Py_SET_EDOM_FOR_NAN(X) \ - } \ - } while(0) + do { \ + if (errno == 0) { \ + if ((X) == Py_HUGE_VAL || (X) == -Py_HUGE_VAL) \ + errno = ERANGE; \ + else _Py_SET_EDOM_FOR_NAN(X) \ + } \ + } while(0) /* Py_SET_ERANGE_ON_OVERFLOW(x) * An alias of Py_SET_ERRNO_ON_MATH_ERROR for backward-compatibility. @@ -470,26 +470,26 @@ * This isn't reliable. See Py_OVERFLOWED comments. * X and Y may be evaluated more than once. */ -#define Py_ADJUST_ERANGE1(X) \ - do { \ - if (errno == 0) { \ - if ((X) == Py_HUGE_VAL || (X) == -Py_HUGE_VAL) \ - errno = ERANGE; \ - } \ - else if (errno == ERANGE && (X) == 0.0) \ - errno = 0; \ - } while(0) - -#define Py_ADJUST_ERANGE2(X, Y) \ - do { \ - if ((X) == Py_HUGE_VAL || (X) == -Py_HUGE_VAL || \ - (Y) == Py_HUGE_VAL || (Y) == -Py_HUGE_VAL) { \ - if (errno == 0) \ - errno = ERANGE; \ - } \ - else if (errno == ERANGE) \ - errno = 0; \ - } while(0) +#define Py_ADJUST_ERANGE1(X) \ + do { \ + if (errno == 0) { \ + if ((X) == Py_HUGE_VAL || (X) == -Py_HUGE_VAL) \ + errno = ERANGE; \ + } \ + else if (errno == ERANGE && (X) == 0.0) \ + errno = 0; \ + } while(0) + +#define Py_ADJUST_ERANGE2(X, Y) \ + do { \ + if ((X) == Py_HUGE_VAL || (X) == -Py_HUGE_VAL || \ + (Y) == Py_HUGE_VAL || (Y) == -Py_HUGE_VAL) { \ + if (errno == 0) \ + errno = ERANGE; \ + } \ + else if (errno == ERANGE) \ + errno = 0; \ + } while(0) /* The functions _Py_dg_strtod and _Py_dg_dtoa in Python/dtoa.c (which are * required to support the short float repr introduced in Python 3.1) require @@ -518,18 +518,18 @@ #ifdef HAVE_GCC_ASM_FOR_X87 #define HAVE_PY_SET_53BIT_PRECISION 1 /* _Py_get/set_387controlword functions are defined in Python/pymath.c */ -#define _Py_SET_53BIT_PRECISION_HEADER \ - unsigned short old_387controlword, new_387controlword -#define _Py_SET_53BIT_PRECISION_START \ - do { \ - old_387controlword = _Py_get_387controlword(); \ - new_387controlword = (old_387controlword & ~0x0f00) | 0x0200; \ - if (new_387controlword != old_387controlword) \ - _Py_set_387controlword(new_387controlword); \ - } while (0) -#define _Py_SET_53BIT_PRECISION_END \ - if (new_387controlword != old_387controlword) \ - _Py_set_387controlword(old_387controlword) +#define _Py_SET_53BIT_PRECISION_HEADER \ + unsigned short old_387controlword, new_387controlword +#define _Py_SET_53BIT_PRECISION_START \ + do { \ + old_387controlword = _Py_get_387controlword(); \ + new_387controlword = (old_387controlword & ~0x0f00) | 0x0200; \ + if (new_387controlword != old_387controlword) \ + _Py_set_387controlword(new_387controlword); \ + } while (0) +#define _Py_SET_53BIT_PRECISION_END \ + if (new_387controlword != old_387controlword) \ + _Py_set_387controlword(old_387controlword) #endif /* default definitions are empty */ @@ -573,7 +573,7 @@ * extern int x() Py_DEPRECATED(2.5); */ #if defined(__GNUC__) && ((__GNUC__ >= 4) || \ - (__GNUC__ == 3) && (__GNUC_MINOR__ >= 1)) + (__GNUC__ == 3) && (__GNUC_MINOR__ >= 1)) #define Py_DEPRECATED(VERSION_UNUSED) __attribute__((__deprecated__)) #else #define Py_DEPRECATED(VERSION_UNUSED) @@ -593,7 +593,7 @@ #endif #ifdef HAVE__GETPTY -#include /* we need to import mode_t */ +#include /* we need to import mode_t */ extern char * _getpty(int *, int, mode_t, int); #endif @@ -674,54 +674,54 @@ linkage handling and it uses __declspec(). */ #if defined(__CYGWIN__) -# define HAVE_DECLSPEC_DLL +# define HAVE_DECLSPEC_DLL #endif /* only get special linkage if built as shared or platform is Cygwin */ #if defined(Py_ENABLE_SHARED) || defined(__CYGWIN__) -# if defined(HAVE_DECLSPEC_DLL) -# ifdef Py_BUILD_CORE -# define PyAPI_FUNC(RTYPE) __declspec(dllexport) RTYPE -# define PyAPI_DATA(RTYPE) extern __declspec(dllexport) RTYPE - /* module init functions inside the core need no external linkage */ - /* except for Cygwin to handle embedding */ -# if defined(__CYGWIN__) -# define PyMODINIT_FUNC __declspec(dllexport) PyObject* -# else /* __CYGWIN__ */ -# define PyMODINIT_FUNC PyObject* -# endif /* __CYGWIN__ */ -# else /* Py_BUILD_CORE */ - /* Building an extension module, or an embedded situation */ - /* public Python functions and data are imported */ - /* Under Cygwin, auto-import functions to prevent compilation */ - /* failures similar to http://python.org/doc/FAQ.html#3.24 */ -# if !defined(__CYGWIN__) -# define PyAPI_FUNC(RTYPE) __declspec(dllimport) RTYPE -# endif /* !__CYGWIN__ */ -# define PyAPI_DATA(RTYPE) extern __declspec(dllimport) RTYPE - /* module init functions outside the core must be exported */ -# if defined(__cplusplus) -# define PyMODINIT_FUNC extern "C" __declspec(dllexport) PyObject* -# else /* __cplusplus */ -# define PyMODINIT_FUNC __declspec(dllexport) PyObject* -# endif /* __cplusplus */ -# endif /* Py_BUILD_CORE */ -# endif /* HAVE_DECLSPEC */ +# if defined(HAVE_DECLSPEC_DLL) +# ifdef Py_BUILD_CORE +# define PyAPI_FUNC(RTYPE) __declspec(dllexport) RTYPE +# define PyAPI_DATA(RTYPE) extern __declspec(dllexport) RTYPE + /* module init functions inside the core need no external linkage */ + /* except for Cygwin to handle embedding */ +# if defined(__CYGWIN__) +# define PyMODINIT_FUNC __declspec(dllexport) PyObject* +# else /* __CYGWIN__ */ +# define PyMODINIT_FUNC PyObject* +# endif /* __CYGWIN__ */ +# else /* Py_BUILD_CORE */ + /* Building an extension module, or an embedded situation */ + /* public Python functions and data are imported */ + /* Under Cygwin, auto-import functions to prevent compilation */ + /* failures similar to http://python.org/doc/FAQ.html#3.24 */ +# if !defined(__CYGWIN__) +# define PyAPI_FUNC(RTYPE) __declspec(dllimport) RTYPE +# endif /* !__CYGWIN__ */ +# define PyAPI_DATA(RTYPE) extern __declspec(dllimport) RTYPE + /* module init functions outside the core must be exported */ +# if defined(__cplusplus) +# define PyMODINIT_FUNC extern "C" __declspec(dllexport) PyObject* +# else /* __cplusplus */ +# define PyMODINIT_FUNC __declspec(dllexport) PyObject* +# endif /* __cplusplus */ +# endif /* Py_BUILD_CORE */ +# endif /* HAVE_DECLSPEC */ #endif /* Py_ENABLE_SHARED */ /* If no external linkage macros defined by now, create defaults */ #ifndef PyAPI_FUNC -# define PyAPI_FUNC(RTYPE) RTYPE +# define PyAPI_FUNC(RTYPE) RTYPE #endif #ifndef PyAPI_DATA -# define PyAPI_DATA(RTYPE) extern RTYPE +# define PyAPI_DATA(RTYPE) extern RTYPE #endif #ifndef PyMODINIT_FUNC -# if defined(__cplusplus) -# define PyMODINIT_FUNC extern "C" PyObject* -# else /* __cplusplus */ -# define PyMODINIT_FUNC PyObject* -# endif /* __cplusplus */ +# if defined(__cplusplus) +# define PyMODINIT_FUNC extern "C" PyObject* +# else /* __cplusplus */ +# define PyMODINIT_FUNC PyObject* +# endif /* __cplusplus */ #endif /* limits.h constants that may be missing */ Modified: python/branches/py3k/Include/pythonrun.h ============================================================================== --- python/branches/py3k/Include/pythonrun.h (original) +++ python/branches/py3k/Include/pythonrun.h Sun May 9 17:52:27 2010 @@ -17,7 +17,7 @@ #define PyCF_IGNORE_COOKIE 0x0800 typedef struct { - int cf_flags; /* bitmask of CO_xxx flags relevant to future */ + int cf_flags; /* bitmask of CO_xxx flags relevant to future */ } PyCompilerFlags; PyAPI_FUNC(void) Py_SetProgramName(wchar_t *); @@ -40,33 +40,33 @@ PyAPI_FUNC(int) PyRun_InteractiveOneFlags(FILE *, const char *, PyCompilerFlags *); PyAPI_FUNC(int) PyRun_InteractiveLoopFlags(FILE *, const char *, PyCompilerFlags *); -PyAPI_FUNC(struct _mod *) PyParser_ASTFromString(const char *, const char *, - int, PyCompilerFlags *flags, +PyAPI_FUNC(struct _mod *) PyParser_ASTFromString(const char *, const char *, + int, PyCompilerFlags *flags, PyArena *); -PyAPI_FUNC(struct _mod *) PyParser_ASTFromFile(FILE *, const char *, - const char*, int, - char *, char *, +PyAPI_FUNC(struct _mod *) PyParser_ASTFromFile(FILE *, const char *, + const char*, int, + char *, char *, PyCompilerFlags *, int *, PyArena *); #define PyParser_SimpleParseString(S, B) \ - PyParser_SimpleParseStringFlags(S, B, 0) + PyParser_SimpleParseStringFlags(S, B, 0) #define PyParser_SimpleParseFile(FP, S, B) \ - PyParser_SimpleParseFileFlags(FP, S, B, 0) -PyAPI_FUNC(struct _node *) PyParser_SimpleParseStringFlags(const char *, int, - int); + PyParser_SimpleParseFileFlags(FP, S, B, 0) +PyAPI_FUNC(struct _node *) PyParser_SimpleParseStringFlags(const char *, int, + int); PyAPI_FUNC(struct _node *) PyParser_SimpleParseFileFlags(FILE *, const char *, - int, int); + int, int); -PyAPI_FUNC(PyObject *) PyRun_StringFlags(const char *, int, PyObject *, - PyObject *, PyCompilerFlags *); +PyAPI_FUNC(PyObject *) PyRun_StringFlags(const char *, int, PyObject *, + PyObject *, PyCompilerFlags *); -PyAPI_FUNC(PyObject *) PyRun_FileExFlags(FILE *, const char *, int, - PyObject *, PyObject *, int, - PyCompilerFlags *); +PyAPI_FUNC(PyObject *) PyRun_FileExFlags(FILE *, const char *, int, + PyObject *, PyObject *, int, + PyCompilerFlags *); #define Py_CompileString(str, p, s) Py_CompileStringFlags(str, p, s, NULL) PyAPI_FUNC(PyObject *) Py_CompileStringFlags(const char *, const char *, int, - PyCompilerFlags *); + PyCompilerFlags *); PyAPI_FUNC(struct symtable *) Py_SymtableString(const char *, const char *, int); PyAPI_FUNC(void) PyErr_Print(void); @@ -93,20 +93,20 @@ #define PyRun_String(str, s, g, l) PyRun_StringFlags(str, s, g, l, NULL) #define PyRun_AnyFile(fp, name) PyRun_AnyFileExFlags(fp, name, 0, NULL) #define PyRun_AnyFileEx(fp, name, closeit) \ - PyRun_AnyFileExFlags(fp, name, closeit, NULL) + PyRun_AnyFileExFlags(fp, name, closeit, NULL) #define PyRun_AnyFileFlags(fp, name, flags) \ - PyRun_AnyFileExFlags(fp, name, 0, flags) + PyRun_AnyFileExFlags(fp, name, 0, flags) #define PyRun_SimpleString(s) PyRun_SimpleStringFlags(s, NULL) #define PyRun_SimpleFile(f, p) PyRun_SimpleFileExFlags(f, p, 0, NULL) #define PyRun_SimpleFileEx(f, p, c) PyRun_SimpleFileExFlags(f, p, c, NULL) #define PyRun_InteractiveOne(f, p) PyRun_InteractiveOneFlags(f, p, NULL) #define PyRun_InteractiveLoop(f, p) PyRun_InteractiveLoopFlags(f, p, NULL) #define PyRun_File(fp, p, s, g, l) \ - PyRun_FileExFlags(fp, p, s, g, l, 0, NULL) + PyRun_FileExFlags(fp, p, s, g, l, 0, NULL) #define PyRun_FileEx(fp, p, s, g, l, c) \ - PyRun_FileExFlags(fp, p, s, g, l, c, NULL) + PyRun_FileExFlags(fp, p, s, g, l, c, NULL) #define PyRun_FileFlags(fp, p, s, g, l, flags) \ - PyRun_FileExFlags(fp, p, s, g, l, 0, flags) + PyRun_FileExFlags(fp, p, s, g, l, 0, flags) /* In getpath.c */ PyAPI_FUNC(wchar_t *) Py_GetProgramFullPath(void); Modified: python/branches/py3k/Include/setobject.h ============================================================================== --- python/branches/py3k/Include/setobject.h (original) +++ python/branches/py3k/Include/setobject.h Sun May 9 17:52:27 2010 @@ -22,8 +22,8 @@ #define PySet_MINSIZE 8 typedef struct { - long hash; /* cached hash code for the entry key */ - PyObject *key; + long hash; /* cached hash code for the entry key */ + PyObject *key; } setentry; @@ -33,27 +33,27 @@ typedef struct _setobject PySetObject; struct _setobject { - PyObject_HEAD + PyObject_HEAD - Py_ssize_t fill; /* # Active + # Dummy */ - Py_ssize_t used; /* # Active */ + Py_ssize_t fill; /* # Active + # Dummy */ + Py_ssize_t used; /* # Active */ - /* The table contains mask + 1 slots, and that's a power of 2. - * We store the mask instead of the size because the mask is more - * frequently needed. - */ - Py_ssize_t mask; - - /* table points to smalltable for small tables, else to - * additional malloc'ed memory. table is never NULL! This rule - * saves repeated runtime null-tests. - */ - setentry *table; - setentry *(*lookup)(PySetObject *so, PyObject *key, long hash); - setentry smalltable[PySet_MINSIZE]; + /* The table contains mask + 1 slots, and that's a power of 2. + * We store the mask instead of the size because the mask is more + * frequently needed. + */ + Py_ssize_t mask; + + /* table points to smalltable for small tables, else to + * additional malloc'ed memory. table is never NULL! This rule + * saves repeated runtime null-tests. + */ + setentry *table; + setentry *(*lookup)(PySetObject *so, PyObject *key, long hash); + setentry smalltable[PySet_MINSIZE]; - long hash; /* only used by frozenset objects */ - PyObject *weakreflist; /* List of weak references */ + long hash; /* only used by frozenset objects */ + PyObject *weakreflist; /* List of weak references */ }; PyAPI_DATA(PyTypeObject) PySet_Type; @@ -69,17 +69,17 @@ #define PyFrozenSet_CheckExact(ob) (Py_TYPE(ob) == &PyFrozenSet_Type) #define PyAnySet_CheckExact(ob) \ - (Py_TYPE(ob) == &PySet_Type || Py_TYPE(ob) == &PyFrozenSet_Type) + (Py_TYPE(ob) == &PySet_Type || Py_TYPE(ob) == &PyFrozenSet_Type) #define PyAnySet_Check(ob) \ - (Py_TYPE(ob) == &PySet_Type || Py_TYPE(ob) == &PyFrozenSet_Type || \ - PyType_IsSubtype(Py_TYPE(ob), &PySet_Type) || \ - PyType_IsSubtype(Py_TYPE(ob), &PyFrozenSet_Type)) + (Py_TYPE(ob) == &PySet_Type || Py_TYPE(ob) == &PyFrozenSet_Type || \ + PyType_IsSubtype(Py_TYPE(ob), &PySet_Type) || \ + PyType_IsSubtype(Py_TYPE(ob), &PyFrozenSet_Type)) #define PySet_Check(ob) \ - (Py_TYPE(ob) == &PySet_Type || \ - PyType_IsSubtype(Py_TYPE(ob), &PySet_Type)) + (Py_TYPE(ob) == &PySet_Type || \ + PyType_IsSubtype(Py_TYPE(ob), &PySet_Type)) #define PyFrozenSet_Check(ob) \ - (Py_TYPE(ob) == &PyFrozenSet_Type || \ - PyType_IsSubtype(Py_TYPE(ob), &PyFrozenSet_Type)) + (Py_TYPE(ob) == &PyFrozenSet_Type || \ + PyType_IsSubtype(Py_TYPE(ob), &PyFrozenSet_Type)) PyAPI_FUNC(PyObject *) PySet_New(PyObject *); PyAPI_FUNC(PyObject *) PyFrozenSet_New(PyObject *); Modified: python/branches/py3k/Include/structseq.h ============================================================================== --- python/branches/py3k/Include/structseq.h (original) +++ python/branches/py3k/Include/structseq.h Sun May 9 17:52:27 2010 @@ -8,35 +8,35 @@ #endif typedef struct PyStructSequence_Field { - char *name; - char *doc; + char *name; + char *doc; } PyStructSequence_Field; typedef struct PyStructSequence_Desc { - char *name; - char *doc; - struct PyStructSequence_Field *fields; - int n_in_sequence; + char *name; + char *doc; + struct PyStructSequence_Field *fields; + int n_in_sequence; } PyStructSequence_Desc; extern char* PyStructSequence_UnnamedField; PyAPI_FUNC(void) PyStructSequence_InitType(PyTypeObject *type, - PyStructSequence_Desc *desc); + PyStructSequence_Desc *desc); PyAPI_FUNC(PyObject *) PyStructSequence_New(PyTypeObject* type); typedef struct { - PyObject_VAR_HEAD - PyObject *ob_item[1]; + PyObject_VAR_HEAD + PyObject *ob_item[1]; } PyStructSequence; /* Macro, *only* to be used to fill in brand new objects */ #define PyStructSequence_SET_ITEM(op, i, v) \ - (((PyStructSequence *)(op))->ob_item[i] = v) + (((PyStructSequence *)(op))->ob_item[i] = v) #define PyStructSequence_GET_ITEM(op, i) \ - (((PyStructSequence *)(op))->ob_item[i]) + (((PyStructSequence *)(op))->ob_item[i]) #ifdef __cplusplus Modified: python/branches/py3k/Include/symtable.h ============================================================================== --- python/branches/py3k/Include/symtable.h (original) +++ python/branches/py3k/Include/symtable.h Sun May 9 17:52:27 2010 @@ -15,40 +15,40 @@ struct _symtable_entry; struct symtable { - const char *st_filename; /* name of file being compiled */ - struct _symtable_entry *st_cur; /* current symbol table entry */ - struct _symtable_entry *st_top; /* symbol table entry for module */ - PyObject *st_blocks; /* dict: map AST node addresses - * to symbol table entries */ - PyObject *st_stack; /* list: stack of namespace info */ - PyObject *st_global; /* borrowed ref to st_top->st_symbols */ - int st_nblocks; /* number of blocks used */ - PyObject *st_private; /* name of current class or NULL */ - PyFutureFeatures *st_future; /* module's future features */ + const char *st_filename; /* name of file being compiled */ + struct _symtable_entry *st_cur; /* current symbol table entry */ + struct _symtable_entry *st_top; /* symbol table entry for module */ + PyObject *st_blocks; /* dict: map AST node addresses + * to symbol table entries */ + PyObject *st_stack; /* list: stack of namespace info */ + PyObject *st_global; /* borrowed ref to st_top->st_symbols */ + int st_nblocks; /* number of blocks used */ + PyObject *st_private; /* name of current class or NULL */ + PyFutureFeatures *st_future; /* module's future features */ }; typedef struct _symtable_entry { - PyObject_HEAD - PyObject *ste_id; /* int: key in ste_table->st_blocks */ - PyObject *ste_symbols; /* dict: variable names to flags */ - PyObject *ste_name; /* string: name of current block */ - PyObject *ste_varnames; /* list of variable names */ - PyObject *ste_children; /* list of child blocks */ - _Py_block_ty ste_type; /* module, class, or function */ - int ste_unoptimized; /* false if namespace is optimized */ - int ste_nested; /* true if block is nested */ - unsigned ste_free : 1; /* true if block has free variables */ - unsigned ste_child_free : 1; /* true if a child block has free vars, - including free refs to globals */ - unsigned ste_generator : 1; /* true if namespace is a generator */ - unsigned ste_varargs : 1; /* true if block has varargs */ - unsigned ste_varkeywords : 1; /* true if block has varkeywords */ - unsigned ste_returns_value : 1; /* true if namespace uses return with - an argument */ - int ste_lineno; /* first line of block */ - int ste_opt_lineno; /* lineno of last exec or import * */ - int ste_tmpname; /* counter for listcomp temp vars */ - struct symtable *ste_table; + PyObject_HEAD + PyObject *ste_id; /* int: key in ste_table->st_blocks */ + PyObject *ste_symbols; /* dict: variable names to flags */ + PyObject *ste_name; /* string: name of current block */ + PyObject *ste_varnames; /* list of variable names */ + PyObject *ste_children; /* list of child blocks */ + _Py_block_ty ste_type; /* module, class, or function */ + int ste_unoptimized; /* false if namespace is optimized */ + int ste_nested; /* true if block is nested */ + unsigned ste_free : 1; /* true if block has free variables */ + unsigned ste_child_free : 1; /* true if a child block has free vars, + including free refs to globals */ + unsigned ste_generator : 1; /* true if namespace is a generator */ + unsigned ste_varargs : 1; /* true if block has varargs */ + unsigned ste_varkeywords : 1; /* true if block has varkeywords */ + unsigned ste_returns_value : 1; /* true if namespace uses return with + an argument */ + int ste_lineno; /* first line of block */ + int ste_opt_lineno; /* lineno of last exec or import * */ + int ste_tmpname; /* counter for listcomp temp vars */ + struct symtable *ste_table; } PySTEntryObject; PyAPI_DATA(PyTypeObject) PySTEntry_Type; @@ -57,8 +57,8 @@ PyAPI_FUNC(int) PyST_GetScope(PySTEntryObject *, PyObject *); -PyAPI_FUNC(struct symtable *) PySymtable_Build(mod_ty, const char *, - PyFutureFeatures *); +PyAPI_FUNC(struct symtable *) PySymtable_Build(mod_ty, const char *, + PyFutureFeatures *); PyAPI_FUNC(PySTEntryObject *) PySymtable_Lookup(struct symtable *, void *); PyAPI_FUNC(void) PySymtable_Free(struct symtable *); @@ -77,7 +77,7 @@ #define DEF_BOUND (DEF_LOCAL | DEF_PARAM | DEF_IMPORT) /* GLOBAL_EXPLICIT and GLOBAL_IMPLICIT are used internally by the symbol - table. GLOBAL is returned from PyST_GetScope() for either of them. + table. GLOBAL is returned from PyST_GetScope() for either of them. It is stored in ste_symbols at bits 12-15. */ #define SCOPE_OFFSET 11 Modified: python/branches/py3k/Include/unicodeobject.h ============================================================================== --- python/branches/py3k/Include/unicodeobject.h (original) +++ python/branches/py3k/Include/unicodeobject.h Sun May 9 17:52:27 2010 @@ -28,14 +28,14 @@ * * -------------------------------------------------------------------- * This Unicode String Type is - * + * * Copyright (c) 1999 by Secret Labs AB * Copyright (c) 1999 by Fredrik Lundh - * + * * By obtaining, using, and/or copying this software and/or its * associated documentation, you agree that you have read, understood, * and will comply with the following terms and conditions: - * + * * Permission to use, copy, modify, and distribute this software and its * associated documentation for any purpose and without fee is hereby * granted, provided that the above copyright notice appears in all @@ -44,7 +44,7 @@ * AB or the author not be used in advertising or publicity pertaining to * distribution of the software without specific, written prior * permission. - * + * * SECRET LABS AB AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO * THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND * FITNESS. IN NO EVENT SHALL SECRET LABS AB OR THE AUTHOR BE LIABLE FOR @@ -61,7 +61,7 @@ /* --- Internal Unicode Format -------------------------------------------- */ /* Python 3.x requires unicode */ -#define Py_USING_UNICODE +#define Py_USING_UNICODE /* FIXME: MvL's new implementation assumes that Py_UNICODE_SIZE is properly set, but the default rules below doesn't set it. I'll @@ -120,10 +120,10 @@ * Use this typedef when you need to represent a UTF-16 surrogate pair * as single unsigned integer. */ -#if SIZEOF_INT >= 4 -typedef unsigned int Py_UCS4; +#if SIZEOF_INT >= 4 +typedef unsigned int Py_UCS4; #elif SIZEOF_LONG >= 4 -typedef unsigned long Py_UCS4; +typedef unsigned long Py_UCS4; #endif /* Py_UNICODE is the native Unicode storage format (code unit) used by @@ -384,7 +384,7 @@ */ #define Py_UNICODE_ISSPACE(ch) \ - ((ch) < 128U ? _Py_ascii_whitespace[(ch)] : _PyUnicode_IsWhitespace(ch)) + ((ch) < 128U ? _Py_ascii_whitespace[(ch)] : _PyUnicode_IsWhitespace(ch)) #define Py_UNICODE_ISLOWER(ch) _PyUnicode_IsLowercase(ch) #define Py_UNICODE_ISUPPER(ch) _PyUnicode_IsUppercase(ch) @@ -410,16 +410,16 @@ #define Py_UNICODE_ISALNUM(ch) \ (Py_UNICODE_ISALPHA(ch) || \ - Py_UNICODE_ISDECIMAL(ch) || \ - Py_UNICODE_ISDIGIT(ch) || \ - Py_UNICODE_ISNUMERIC(ch)) + Py_UNICODE_ISDECIMAL(ch) || \ + Py_UNICODE_ISDIGIT(ch) || \ + Py_UNICODE_ISNUMERIC(ch)) -#define Py_UNICODE_COPY(target, source, length) \ - Py_MEMCPY((target), (source), (length)*sizeof(Py_UNICODE)) +#define Py_UNICODE_COPY(target, source, length) \ + Py_MEMCPY((target), (source), (length)*sizeof(Py_UNICODE)) #define Py_UNICODE_FILL(target, value, length) \ do {Py_ssize_t i_; Py_UNICODE *t_ = (target); Py_UNICODE v_ = (value);\ - for (i_ = 0; i_ < (length); i_++) t_[i_] = v_;\ + for (i_ = 0; i_ < (length); i_++) t_[i_] = v_;\ } while (0) /* Check if substring matches at given offset. the offset must be @@ -438,15 +438,15 @@ typedef struct { PyObject_HEAD - Py_ssize_t length; /* Length of raw Unicode data in buffer */ - Py_UNICODE *str; /* Raw Unicode buffer */ - long hash; /* Hash value; -1 if not set */ - int state; /* != 0 if interned. In this case the two - * references from the dictionary to this object - * are *not* counted in ob_refcnt. */ - PyObject *defenc; /* (Default) Encoded version as Python - string, or NULL; this is used for - implementing the buffer protocol */ + Py_ssize_t length; /* Length of raw Unicode data in buffer */ + Py_UNICODE *str; /* Raw Unicode buffer */ + long hash; /* Hash value; -1 if not set */ + int state; /* != 0 if interned. In this case the two + * references from the dictionary to this object + * are *not* counted in ob_refcnt. */ + PyObject *defenc; /* (Default) Encoded version as Python + string, or NULL; this is used for + implementing the buffer protocol */ } PyUnicodeObject; PyAPI_DATA(PyTypeObject) PyUnicode_Type; @@ -462,13 +462,13 @@ /* Fast access macros */ #define PyUnicode_GET_SIZE(op) \ - (assert(PyUnicode_Check(op)),(((PyUnicodeObject *)(op))->length)) + (assert(PyUnicode_Check(op)),(((PyUnicodeObject *)(op))->length)) #define PyUnicode_GET_DATA_SIZE(op) \ - (assert(PyUnicode_Check(op)),(((PyUnicodeObject *)(op))->length * sizeof(Py_UNICODE))) + (assert(PyUnicode_Check(op)),(((PyUnicodeObject *)(op))->length * sizeof(Py_UNICODE))) #define PyUnicode_AS_UNICODE(op) \ - (assert(PyUnicode_Check(op)),(((PyUnicodeObject *)(op))->str)) + (assert(PyUnicode_Check(op)),(((PyUnicodeObject *)(op))->str)) #define PyUnicode_AS_DATA(op) \ - (assert(PyUnicode_Check(op)),((const char *)((PyUnicodeObject *)(op))->str)) + (assert(PyUnicode_Check(op)),((const char *)((PyUnicodeObject *)(op))->str)) /* --- Constants ---------------------------------------------------------- */ @@ -484,7 +484,7 @@ /* --- Plain Py_UNICODE --------------------------------------------------- */ /* Create a Unicode Object from the Py_UNICODE buffer u of the given - size. + size. u may be NULL which causes the contents to be undefined. It is the user's responsibility to fill in the needed data afterwards. Note @@ -514,13 +514,13 @@ Py_UNICODE buffer. */ PyAPI_FUNC(Py_UNICODE *) PyUnicode_AsUnicode( - PyObject *unicode /* Unicode object */ + PyObject *unicode /* Unicode object */ ); /* Get the length of the Unicode object. */ PyAPI_FUNC(Py_ssize_t) PyUnicode_GetSize( - PyObject *unicode /* Unicode object */ + PyObject *unicode /* Unicode object */ ); /* Get the maximum ordinal for a Unicode character. */ @@ -541,8 +541,8 @@ */ PyAPI_FUNC(int) PyUnicode_Resize( - PyObject **unicode, /* Pointer to the Unicode object */ - Py_ssize_t length /* New length */ + PyObject **unicode, /* Pointer to the Unicode object */ + Py_ssize_t length /* New length */ ); /* Coerce obj to an Unicode object and return a reference with @@ -563,14 +563,14 @@ */ PyAPI_FUNC(PyObject*) PyUnicode_FromEncodedObject( - register PyObject *obj, /* Object */ + register PyObject *obj, /* Object */ const char *encoding, /* encoding */ const char *errors /* error handling */ ); /* Coerce obj to an Unicode object and return a reference with *incremented* refcount. - + Unicode objects are passed back as-is (subclasses are converted to true Unicode objects), all other objects are delegated to PyUnicode_FromEncodedObject(obj, NULL, "strict") which results in @@ -582,7 +582,7 @@ */ PyAPI_FUNC(PyObject*) PyUnicode_FromObject( - register PyObject *obj /* Object */ + register PyObject *obj /* Object */ ); PyAPI_FUNC(PyObject *) PyUnicode_FromFormatV(const char*, va_list); @@ -638,8 +638,8 @@ /* --- Unicode ordinals --------------------------------------------------- */ -/* Create a Unicode Object from the given Unicode code point ordinal. - +/* Create a Unicode Object from the given Unicode code point ordinal. + The ordinal must be in range(0x10000) on narrow Python builds (UCS2), and range(0x110000) on wide builds (UCS4). A ValueError is raised in case it is not. @@ -659,11 +659,11 @@ PyAPI_FUNC(int) PyUnicode_ClearFreeList(void); -/* === Builtin Codecs ===================================================== +/* === Builtin Codecs ===================================================== Many of these APIs take two arguments encoding and errors. These parameters encoding and errors have the same semantics as the ones - of the builtin unicode() API. + of the builtin unicode() API. Setting encoding to NULL causes the default encoding to be used. @@ -680,7 +680,7 @@ /* --- Manage the default encoding ---------------------------------------- */ /* Return a Python string holding the default encoded value of the - Unicode object. + Unicode object. The resulting string is cached in the Unicode object for subsequent usage by this function. The cached version is needed to implement @@ -712,7 +712,7 @@ */ PyAPI_FUNC(char *) _PyUnicode_AsStringAndSize( - PyObject *unicode, + PyObject *unicode, Py_ssize_t *size); /* Returns a pointer to the default encoding (normally, UTf-8) of the @@ -737,7 +737,7 @@ process global. This may change in future versions of the interpreter to become a parameter which is managed on a per-thread basis. - + */ PyAPI_FUNC(const char*) PyUnicode_GetDefaultEncoding(void); @@ -745,11 +745,11 @@ /* Sets the currently active default encoding. Returns 0 on success, -1 in case of an error. - + */ PyAPI_FUNC(int) PyUnicode_SetDefaultEncoding( - const char *encoding /* Encoding name in standard form */ + const char *encoding /* Encoding name in standard form */ ); /* --- Generic Codecs ----------------------------------------------------- */ @@ -768,21 +768,21 @@ object. */ PyAPI_FUNC(PyObject*) PyUnicode_AsDecodedObject( - PyObject *unicode, /* Unicode object */ - const char *encoding, /* encoding */ - const char *errors /* error handling */ + PyObject *unicode, /* Unicode object */ + const char *encoding, /* encoding */ + const char *errors /* error handling */ ); /* Decode a Unicode object unicode and return the result as Unicode object. */ PyAPI_FUNC(PyObject*) PyUnicode_AsDecodedUnicode( - PyObject *unicode, /* Unicode object */ - const char *encoding, /* encoding */ - const char *errors /* error handling */ + PyObject *unicode, /* Unicode object */ + const char *encoding, /* encoding */ + const char *errors /* error handling */ ); -/* Encodes a Py_UNICODE buffer of the given size and returns a +/* Encodes a Py_UNICODE buffer of the given size and returns a Python string object. */ PyAPI_FUNC(PyObject*) PyUnicode_Encode( @@ -796,27 +796,27 @@ object. */ PyAPI_FUNC(PyObject*) PyUnicode_AsEncodedObject( - PyObject *unicode, /* Unicode object */ - const char *encoding, /* encoding */ - const char *errors /* error handling */ + PyObject *unicode, /* Unicode object */ + const char *encoding, /* encoding */ + const char *errors /* error handling */ ); /* Encodes a Unicode object and returns the result as Python string object. */ PyAPI_FUNC(PyObject*) PyUnicode_AsEncodedString( - PyObject *unicode, /* Unicode object */ - const char *encoding, /* encoding */ - const char *errors /* error handling */ + PyObject *unicode, /* Unicode object */ + const char *encoding, /* encoding */ + const char *errors /* error handling */ ); /* Encodes a Unicode object and returns the result as Unicode object. */ PyAPI_FUNC(PyObject*) PyUnicode_AsEncodedUnicode( - PyObject *unicode, /* Unicode object */ - const char *encoding, /* encoding */ - const char *errors /* error handling */ + PyObject *unicode, /* Unicode object */ + const char *encoding, /* encoding */ + const char *errors /* error handling */ ); /* Build an encoding map. */ @@ -828,49 +828,49 @@ /* --- UTF-7 Codecs ------------------------------------------------------- */ PyAPI_FUNC(PyObject*) PyUnicode_DecodeUTF7( - const char *string, /* UTF-7 encoded string */ - Py_ssize_t length, /* size of string */ - const char *errors /* error handling */ + const char *string, /* UTF-7 encoded string */ + Py_ssize_t length, /* size of string */ + const char *errors /* error handling */ ); PyAPI_FUNC(PyObject*) PyUnicode_DecodeUTF7Stateful( - const char *string, /* UTF-7 encoded string */ - Py_ssize_t length, /* size of string */ - const char *errors, /* error handling */ - Py_ssize_t *consumed /* bytes consumed */ + const char *string, /* UTF-7 encoded string */ + Py_ssize_t length, /* size of string */ + const char *errors, /* error handling */ + Py_ssize_t *consumed /* bytes consumed */ ); PyAPI_FUNC(PyObject*) PyUnicode_EncodeUTF7( - const Py_UNICODE *data, /* Unicode char buffer */ - Py_ssize_t length, /* number of Py_UNICODE chars to encode */ - int base64SetO, /* Encode RFC2152 Set O characters in base64 */ - int base64WhiteSpace, /* Encode whitespace (sp, ht, nl, cr) in base64 */ - const char *errors /* error handling */ + const Py_UNICODE *data, /* Unicode char buffer */ + Py_ssize_t length, /* number of Py_UNICODE chars to encode */ + int base64SetO, /* Encode RFC2152 Set O characters in base64 */ + int base64WhiteSpace, /* Encode whitespace (sp, ht, nl, cr) in base64 */ + const char *errors /* error handling */ ); /* --- UTF-8 Codecs ------------------------------------------------------- */ PyAPI_FUNC(PyObject*) PyUnicode_DecodeUTF8( - const char *string, /* UTF-8 encoded string */ - Py_ssize_t length, /* size of string */ - const char *errors /* error handling */ + const char *string, /* UTF-8 encoded string */ + Py_ssize_t length, /* size of string */ + const char *errors /* error handling */ ); PyAPI_FUNC(PyObject*) PyUnicode_DecodeUTF8Stateful( - const char *string, /* UTF-8 encoded string */ - Py_ssize_t length, /* size of string */ - const char *errors, /* error handling */ - Py_ssize_t *consumed /* bytes consumed */ + const char *string, /* UTF-8 encoded string */ + Py_ssize_t length, /* size of string */ + const char *errors, /* error handling */ + Py_ssize_t *consumed /* bytes consumed */ ); PyAPI_FUNC(PyObject*) PyUnicode_AsUTF8String( - PyObject *unicode /* Unicode object */ + PyObject *unicode /* Unicode object */ ); PyAPI_FUNC(PyObject*) PyUnicode_EncodeUTF8( - const Py_UNICODE *data, /* Unicode char buffer */ - Py_ssize_t length, /* number of Py_UNICODE chars to encode */ - const char *errors /* error handling */ + const Py_UNICODE *data, /* Unicode char buffer */ + Py_ssize_t length, /* number of Py_UNICODE chars to encode */ + const char *errors /* error handling */ ); /* --- UTF-32 Codecs ------------------------------------------------------ */ @@ -879,14 +879,14 @@ the corresponding Unicode object. errors (if non-NULL) defines the error handling. It defaults - to "strict". + to "strict". If byteorder is non-NULL, the decoder starts decoding using the given byte order: - *byteorder == -1: little endian - *byteorder == 0: native order - *byteorder == 1: big endian + *byteorder == -1: little endian + *byteorder == 0: native order + *byteorder == 1: big endian In native mode, the first four bytes of the stream are checked for a BOM mark. If found, the BOM mark is analysed, the byte order @@ -899,29 +899,29 @@ */ PyAPI_FUNC(PyObject*) PyUnicode_DecodeUTF32( - const char *string, /* UTF-32 encoded string */ - Py_ssize_t length, /* size of string */ - const char *errors, /* error handling */ - int *byteorder /* pointer to byteorder to use - 0=native;-1=LE,1=BE; updated on - exit */ + const char *string, /* UTF-32 encoded string */ + Py_ssize_t length, /* size of string */ + const char *errors, /* error handling */ + int *byteorder /* pointer to byteorder to use + 0=native;-1=LE,1=BE; updated on + exit */ ); PyAPI_FUNC(PyObject*) PyUnicode_DecodeUTF32Stateful( - const char *string, /* UTF-32 encoded string */ - Py_ssize_t length, /* size of string */ - const char *errors, /* error handling */ - int *byteorder, /* pointer to byteorder to use - 0=native;-1=LE,1=BE; updated on - exit */ - Py_ssize_t *consumed /* bytes consumed */ + const char *string, /* UTF-32 encoded string */ + Py_ssize_t length, /* size of string */ + const char *errors, /* error handling */ + int *byteorder, /* pointer to byteorder to use + 0=native;-1=LE,1=BE; updated on + exit */ + Py_ssize_t *consumed /* bytes consumed */ ); /* Returns a Python string using the UTF-32 encoding in native byte order. The string always starts with a BOM mark. */ PyAPI_FUNC(PyObject*) PyUnicode_AsUTF32String( - PyObject *unicode /* Unicode object */ + PyObject *unicode /* Unicode object */ ); /* Returns a Python string object holding the UTF-32 encoded value of @@ -941,10 +941,10 @@ */ PyAPI_FUNC(PyObject*) PyUnicode_EncodeUTF32( - const Py_UNICODE *data, /* Unicode char buffer */ - Py_ssize_t length, /* number of Py_UNICODE chars to encode */ - const char *errors, /* error handling */ - int byteorder /* byteorder to use 0=BOM+native;-1=LE,1=BE */ + const Py_UNICODE *data, /* Unicode char buffer */ + Py_ssize_t length, /* number of Py_UNICODE chars to encode */ + const char *errors, /* error handling */ + int byteorder /* byteorder to use 0=BOM+native;-1=LE,1=BE */ ); /* --- UTF-16 Codecs ------------------------------------------------------ */ @@ -953,14 +953,14 @@ the corresponding Unicode object. errors (if non-NULL) defines the error handling. It defaults - to "strict". + to "strict". If byteorder is non-NULL, the decoder starts decoding using the given byte order: - *byteorder == -1: little endian - *byteorder == 0: native order - *byteorder == 1: big endian + *byteorder == -1: little endian + *byteorder == 0: native order + *byteorder == 1: big endian In native mode, the first two bytes of the stream are checked for a BOM mark. If found, the BOM mark is analysed, the byte order @@ -973,29 +973,29 @@ */ PyAPI_FUNC(PyObject*) PyUnicode_DecodeUTF16( - const char *string, /* UTF-16 encoded string */ - Py_ssize_t length, /* size of string */ - const char *errors, /* error handling */ - int *byteorder /* pointer to byteorder to use - 0=native;-1=LE,1=BE; updated on - exit */ + const char *string, /* UTF-16 encoded string */ + Py_ssize_t length, /* size of string */ + const char *errors, /* error handling */ + int *byteorder /* pointer to byteorder to use + 0=native;-1=LE,1=BE; updated on + exit */ ); PyAPI_FUNC(PyObject*) PyUnicode_DecodeUTF16Stateful( - const char *string, /* UTF-16 encoded string */ - Py_ssize_t length, /* size of string */ - const char *errors, /* error handling */ - int *byteorder, /* pointer to byteorder to use - 0=native;-1=LE,1=BE; updated on - exit */ - Py_ssize_t *consumed /* bytes consumed */ + const char *string, /* UTF-16 encoded string */ + Py_ssize_t length, /* size of string */ + const char *errors, /* error handling */ + int *byteorder, /* pointer to byteorder to use + 0=native;-1=LE,1=BE; updated on + exit */ + Py_ssize_t *consumed /* bytes consumed */ ); /* Returns a Python string using the UTF-16 encoding in native byte order. The string always starts with a BOM mark. */ PyAPI_FUNC(PyObject*) PyUnicode_AsUTF16String( - PyObject *unicode /* Unicode object */ + PyObject *unicode /* Unicode object */ ); /* Returns a Python string object holding the UTF-16 encoded value of @@ -1019,44 +1019,44 @@ */ PyAPI_FUNC(PyObject*) PyUnicode_EncodeUTF16( - const Py_UNICODE *data, /* Unicode char buffer */ - Py_ssize_t length, /* number of Py_UNICODE chars to encode */ - const char *errors, /* error handling */ - int byteorder /* byteorder to use 0=BOM+native;-1=LE,1=BE */ + const Py_UNICODE *data, /* Unicode char buffer */ + Py_ssize_t length, /* number of Py_UNICODE chars to encode */ + const char *errors, /* error handling */ + int byteorder /* byteorder to use 0=BOM+native;-1=LE,1=BE */ ); /* --- Unicode-Escape Codecs ---------------------------------------------- */ PyAPI_FUNC(PyObject*) PyUnicode_DecodeUnicodeEscape( - const char *string, /* Unicode-Escape encoded string */ - Py_ssize_t length, /* size of string */ - const char *errors /* error handling */ + const char *string, /* Unicode-Escape encoded string */ + Py_ssize_t length, /* size of string */ + const char *errors /* error handling */ ); PyAPI_FUNC(PyObject*) PyUnicode_AsUnicodeEscapeString( - PyObject *unicode /* Unicode object */ + PyObject *unicode /* Unicode object */ ); PyAPI_FUNC(PyObject*) PyUnicode_EncodeUnicodeEscape( - const Py_UNICODE *data, /* Unicode char buffer */ - Py_ssize_t length /* Number of Py_UNICODE chars to encode */ + const Py_UNICODE *data, /* Unicode char buffer */ + Py_ssize_t length /* Number of Py_UNICODE chars to encode */ ); /* --- Raw-Unicode-Escape Codecs ------------------------------------------ */ PyAPI_FUNC(PyObject*) PyUnicode_DecodeRawUnicodeEscape( - const char *string, /* Raw-Unicode-Escape encoded string */ - Py_ssize_t length, /* size of string */ - const char *errors /* error handling */ + const char *string, /* Raw-Unicode-Escape encoded string */ + Py_ssize_t length, /* size of string */ + const char *errors /* error handling */ ); PyAPI_FUNC(PyObject*) PyUnicode_AsRawUnicodeEscapeString( - PyObject *unicode /* Unicode object */ + PyObject *unicode /* Unicode object */ ); PyAPI_FUNC(PyObject*) PyUnicode_EncodeRawUnicodeEscape( - const Py_UNICODE *data, /* Unicode char buffer */ - Py_ssize_t length /* Number of Py_UNICODE chars to encode */ + const Py_UNICODE *data, /* Unicode char buffer */ + Py_ssize_t length /* Number of Py_UNICODE chars to encode */ ); /* --- Unicode Internal Codec --------------------------------------------- @@ -1069,53 +1069,53 @@ const char *errors ); -/* --- Latin-1 Codecs ----------------------------------------------------- +/* --- Latin-1 Codecs ----------------------------------------------------- Note: Latin-1 corresponds to the first 256 Unicode ordinals. */ PyAPI_FUNC(PyObject*) PyUnicode_DecodeLatin1( - const char *string, /* Latin-1 encoded string */ - Py_ssize_t length, /* size of string */ - const char *errors /* error handling */ + const char *string, /* Latin-1 encoded string */ + Py_ssize_t length, /* size of string */ + const char *errors /* error handling */ ); PyAPI_FUNC(PyObject*) PyUnicode_AsLatin1String( - PyObject *unicode /* Unicode object */ + PyObject *unicode /* Unicode object */ ); PyAPI_FUNC(PyObject*) PyUnicode_EncodeLatin1( - const Py_UNICODE *data, /* Unicode char buffer */ - Py_ssize_t length, /* Number of Py_UNICODE chars to encode */ - const char *errors /* error handling */ + const Py_UNICODE *data, /* Unicode char buffer */ + Py_ssize_t length, /* Number of Py_UNICODE chars to encode */ + const char *errors /* error handling */ ); -/* --- ASCII Codecs ------------------------------------------------------- +/* --- ASCII Codecs ------------------------------------------------------- Only 7-bit ASCII data is excepted. All other codes generate errors. */ PyAPI_FUNC(PyObject*) PyUnicode_DecodeASCII( - const char *string, /* ASCII encoded string */ - Py_ssize_t length, /* size of string */ - const char *errors /* error handling */ + const char *string, /* ASCII encoded string */ + Py_ssize_t length, /* size of string */ + const char *errors /* error handling */ ); PyAPI_FUNC(PyObject*) PyUnicode_AsASCIIString( - PyObject *unicode /* Unicode object */ + PyObject *unicode /* Unicode object */ ); PyAPI_FUNC(PyObject*) PyUnicode_EncodeASCII( - const Py_UNICODE *data, /* Unicode char buffer */ - Py_ssize_t length, /* Number of Py_UNICODE chars to encode */ - const char *errors /* error handling */ + const Py_UNICODE *data, /* Unicode char buffer */ + Py_ssize_t length, /* Number of Py_UNICODE chars to encode */ + const char *errors /* error handling */ ); -/* --- Character Map Codecs ----------------------------------------------- +/* --- Character Map Codecs ----------------------------------------------- - This codec uses mappings to encode and decode characters. + This codec uses mappings to encode and decode characters. Decoding mappings must map single string characters to single Unicode characters, integers (which are then interpreted as Unicode @@ -1136,25 +1136,25 @@ */ PyAPI_FUNC(PyObject*) PyUnicode_DecodeCharmap( - const char *string, /* Encoded string */ - Py_ssize_t length, /* size of string */ - PyObject *mapping, /* character mapping - (char ordinal -> unicode ordinal) */ - const char *errors /* error handling */ + const char *string, /* Encoded string */ + Py_ssize_t length, /* size of string */ + PyObject *mapping, /* character mapping + (char ordinal -> unicode ordinal) */ + const char *errors /* error handling */ ); PyAPI_FUNC(PyObject*) PyUnicode_AsCharmapString( - PyObject *unicode, /* Unicode object */ - PyObject *mapping /* character mapping - (unicode ordinal -> char ordinal) */ + PyObject *unicode, /* Unicode object */ + PyObject *mapping /* character mapping + (unicode ordinal -> char ordinal) */ ); PyAPI_FUNC(PyObject*) PyUnicode_EncodeCharmap( - const Py_UNICODE *data, /* Unicode char buffer */ - Py_ssize_t length, /* Number of Py_UNICODE chars to encode */ - PyObject *mapping, /* character mapping - (unicode ordinal -> char ordinal) */ - const char *errors /* error handling */ + const Py_UNICODE *data, /* Unicode char buffer */ + Py_ssize_t length, /* Number of Py_UNICODE chars to encode */ + PyObject *mapping, /* character mapping + (unicode ordinal -> char ordinal) */ + const char *errors /* error handling */ ); /* Translate a Py_UNICODE buffer of the given length by applying a @@ -1162,7 +1162,7 @@ object. The mapping table must map Unicode ordinal integers to Unicode - ordinal integers or None (causing deletion of the character). + ordinal integers or None (causing deletion of the character). Mapping tables may be dictionaries or sequences. Unmapped character ordinals (ones which cause a LookupError) are left untouched and @@ -1171,10 +1171,10 @@ */ PyAPI_FUNC(PyObject *) PyUnicode_TranslateCharmap( - const Py_UNICODE *data, /* Unicode char buffer */ - Py_ssize_t length, /* Number of Py_UNICODE chars to encode */ - PyObject *table, /* Translate table */ - const char *errors /* error handling */ + const Py_UNICODE *data, /* Unicode char buffer */ + Py_ssize_t length, /* Number of Py_UNICODE chars to encode */ + PyObject *table, /* Translate table */ + const char *errors /* error handling */ ); #ifdef MS_WIN32 @@ -1223,7 +1223,7 @@ NULL or "strict": raise a ValueError "ignore": ignore the wrong characters (these are not copied to the - output buffer) + output buffer) "replace": replaces illegal characters with '?' Returns 0 on success, -1 on failure. @@ -1231,10 +1231,10 @@ */ PyAPI_FUNC(int) PyUnicode_EncodeDecimal( - Py_UNICODE *s, /* Unicode buffer */ - Py_ssize_t length, /* Number of Py_UNICODE chars to encode */ - char *output, /* Output buffer; must have size >= length */ - const char *errors /* error handling */ + Py_UNICODE *s, /* Unicode buffer */ + Py_ssize_t length, /* Number of Py_UNICODE chars to encode */ + char *output, /* Output buffer; must have size >= length */ + const char *errors /* error handling */ ); /* --- File system encoding ---------------------------------------------- */ @@ -1273,24 +1273,24 @@ /* Concat two strings giving a new Unicode string. */ PyAPI_FUNC(PyObject*) PyUnicode_Concat( - PyObject *left, /* Left string */ - PyObject *right /* Right string */ + PyObject *left, /* Left string */ + PyObject *right /* Right string */ ); /* Concat two strings and put the result in *pleft (sets *pleft to NULL on error) */ PyAPI_FUNC(void) PyUnicode_Append( - PyObject **pleft, /* Pointer to left string */ - PyObject *right /* Right string */ + PyObject **pleft, /* Pointer to left string */ + PyObject *right /* Right string */ ); /* Concat two strings, put the result in *pleft and drop the right object (sets *pleft to NULL on error) */ PyAPI_FUNC(void) PyUnicode_AppendAndDel( - PyObject **pleft, /* Pointer to left string */ - PyObject *right /* Right string */ + PyObject **pleft, /* Pointer to left string */ + PyObject *right /* Right string */ ); /* Split a string giving a list of Unicode strings. @@ -1305,35 +1305,35 @@ */ PyAPI_FUNC(PyObject*) PyUnicode_Split( - PyObject *s, /* String to split */ - PyObject *sep, /* String separator */ - Py_ssize_t maxsplit /* Maxsplit count */ - ); + PyObject *s, /* String to split */ + PyObject *sep, /* String separator */ + Py_ssize_t maxsplit /* Maxsplit count */ + ); /* Dito, but split at line breaks. CRLF is considered to be one line break. Line breaks are not included in the resulting list. */ - + PyAPI_FUNC(PyObject*) PyUnicode_Splitlines( - PyObject *s, /* String to split */ - int keepends /* If true, line end markers are included */ - ); + PyObject *s, /* String to split */ + int keepends /* If true, line end markers are included */ + ); /* Partition a string using a given separator. */ PyAPI_FUNC(PyObject*) PyUnicode_Partition( - PyObject *s, /* String to partition */ - PyObject *sep /* String separator */ - ); + PyObject *s, /* String to partition */ + PyObject *sep /* String separator */ + ); /* Partition a string using a given separator, searching from the end of the string. */ PyAPI_FUNC(PyObject*) PyUnicode_RPartition( - PyObject *s, /* String to partition */ - PyObject *sep /* String separator */ - ); + PyObject *s, /* String to partition */ + PyObject *sep /* String separator */ + ); /* Split a string giving a list of Unicode strings. @@ -1349,16 +1349,16 @@ */ PyAPI_FUNC(PyObject*) PyUnicode_RSplit( - PyObject *s, /* String to split */ - PyObject *sep, /* String separator */ - Py_ssize_t maxsplit /* Maxsplit count */ - ); + PyObject *s, /* String to split */ + PyObject *sep, /* String separator */ + Py_ssize_t maxsplit /* Maxsplit count */ + ); /* Translate a string by applying a character mapping table to it and return the resulting Unicode object. The mapping table must map Unicode ordinal integers to Unicode - ordinal integers or None (causing deletion of the character). + ordinal integers or None (causing deletion of the character). Mapping tables may be dictionaries or sequences. Unmapped character ordinals (ones which cause a LookupError) are left untouched and @@ -1367,28 +1367,28 @@ */ PyAPI_FUNC(PyObject *) PyUnicode_Translate( - PyObject *str, /* String */ - PyObject *table, /* Translate table */ - const char *errors /* error handling */ + PyObject *str, /* String */ + PyObject *table, /* Translate table */ + const char *errors /* error handling */ ); /* Join a sequence of strings using the given separator and return the resulting Unicode string. */ - + PyAPI_FUNC(PyObject*) PyUnicode_Join( - PyObject *separator, /* Separator string */ - PyObject *seq /* Sequence object */ + PyObject *separator, /* Separator string */ + PyObject *seq /* Sequence object */ ); /* Return 1 if substr matches str[start:end] at the given tail end, 0 otherwise. */ PyAPI_FUNC(Py_ssize_t) PyUnicode_Tailmatch( - PyObject *str, /* String */ - PyObject *substr, /* Prefix or Suffix string */ - Py_ssize_t start, /* Start index */ - Py_ssize_t end, /* Stop index */ - int direction /* Tail end: -1 prefix, +1 suffix */ + PyObject *str, /* String */ + PyObject *substr, /* Prefix or Suffix string */ + Py_ssize_t start, /* Start index */ + Py_ssize_t end, /* Stop index */ + int direction /* Tail end: -1 prefix, +1 suffix */ ); /* Return the first position of substr in str[start:end] using the @@ -1396,39 +1396,39 @@ an error occurred and an exception is set. */ PyAPI_FUNC(Py_ssize_t) PyUnicode_Find( - PyObject *str, /* String */ - PyObject *substr, /* Substring to find */ - Py_ssize_t start, /* Start index */ - Py_ssize_t end, /* Stop index */ - int direction /* Find direction: +1 forward, -1 backward */ + PyObject *str, /* String */ + PyObject *substr, /* Substring to find */ + Py_ssize_t start, /* Start index */ + Py_ssize_t end, /* Stop index */ + int direction /* Find direction: +1 forward, -1 backward */ ); /* Count the number of occurrences of substr in str[start:end]. */ PyAPI_FUNC(Py_ssize_t) PyUnicode_Count( - PyObject *str, /* String */ - PyObject *substr, /* Substring to count */ - Py_ssize_t start, /* Start index */ - Py_ssize_t end /* Stop index */ + PyObject *str, /* String */ + PyObject *substr, /* Substring to count */ + Py_ssize_t start, /* Start index */ + Py_ssize_t end /* Stop index */ ); /* Replace at most maxcount occurrences of substr in str with replstr and return the resulting Unicode object. */ PyAPI_FUNC(PyObject *) PyUnicode_Replace( - PyObject *str, /* String */ - PyObject *substr, /* Substring to find */ - PyObject *replstr, /* Substring to replace */ - Py_ssize_t maxcount /* Max. number of replacements to apply; - -1 = all */ + PyObject *str, /* String */ + PyObject *substr, /* Substring to find */ + PyObject *replstr, /* Substring to replace */ + Py_ssize_t maxcount /* Max. number of replacements to apply; + -1 = all */ ); /* Compare two strings and return -1, 0, 1 for less than, equal, greater than resp. */ PyAPI_FUNC(int) PyUnicode_Compare( - PyObject *left, /* Left string */ - PyObject *right /* Right string */ + PyObject *left, /* Left string */ + PyObject *right /* Right string */ ); PyAPI_FUNC(int) PyUnicode_CompareWithASCIIString( @@ -1453,17 +1453,17 @@ */ PyAPI_FUNC(PyObject *) PyUnicode_RichCompare( - PyObject *left, /* Left string */ - PyObject *right, /* Right string */ - int op /* Operation: Py_EQ, Py_NE, Py_GT, etc. */ + PyObject *left, /* Left string */ + PyObject *right, /* Right string */ + int op /* Operation: Py_EQ, Py_NE, Py_GT, etc. */ ); /* Apply a argument tuple or dictionary to a format string and return the resulting Unicode string. */ PyAPI_FUNC(PyObject *) PyUnicode_Format( - PyObject *format, /* Format string */ - PyObject *args /* Argument tuple or dictionary */ + PyObject *format, /* Format string */ + PyObject *args /* Argument tuple or dictionary */ ); /* Checks whether element is contained in container and return 1/0 @@ -1473,8 +1473,8 @@ returned in case of an error. */ PyAPI_FUNC(int) PyUnicode_Contains( - PyObject *container, /* Container string */ - PyObject *element /* Element string */ + PyObject *container, /* Container string */ + PyObject *element /* Element string */ ); /* Checks whether argument is a valid identifier. */ @@ -1515,82 +1515,82 @@ PyAPI_DATA(const unsigned char) _Py_ascii_whitespace[]; /* These should not be used directly. Use the Py_UNICODE_IS* and - Py_UNICODE_TO* macros instead. + Py_UNICODE_TO* macros instead. These APIs are implemented in Objects/unicodectype.c. */ PyAPI_FUNC(int) _PyUnicode_IsLowercase( - Py_UNICODE ch /* Unicode character */ + Py_UNICODE ch /* Unicode character */ ); PyAPI_FUNC(int) _PyUnicode_IsUppercase( - Py_UNICODE ch /* Unicode character */ + Py_UNICODE ch /* Unicode character */ ); PyAPI_FUNC(int) _PyUnicode_IsTitlecase( - Py_UNICODE ch /* Unicode character */ + Py_UNICODE ch /* Unicode character */ ); PyAPI_FUNC(int) _PyUnicode_IsXidStart( - Py_UNICODE ch /* Unicode character */ + Py_UNICODE ch /* Unicode character */ ); PyAPI_FUNC(int) _PyUnicode_IsXidContinue( - Py_UNICODE ch /* Unicode character */ + Py_UNICODE ch /* Unicode character */ ); PyAPI_FUNC(int) _PyUnicode_IsWhitespace( - const Py_UNICODE ch /* Unicode character */ + const Py_UNICODE ch /* Unicode character */ ); PyAPI_FUNC(int) _PyUnicode_IsLinebreak( - const Py_UNICODE ch /* Unicode character */ + const Py_UNICODE ch /* Unicode character */ ); PyAPI_FUNC(Py_UNICODE) _PyUnicode_ToLowercase( - Py_UNICODE ch /* Unicode character */ + Py_UNICODE ch /* Unicode character */ ); PyAPI_FUNC(Py_UNICODE) _PyUnicode_ToUppercase( - Py_UNICODE ch /* Unicode character */ + Py_UNICODE ch /* Unicode character */ ); PyAPI_FUNC(Py_UNICODE) _PyUnicode_ToTitlecase( - Py_UNICODE ch /* Unicode character */ + Py_UNICODE ch /* Unicode character */ ); PyAPI_FUNC(int) _PyUnicode_ToDecimalDigit( - Py_UNICODE ch /* Unicode character */ + Py_UNICODE ch /* Unicode character */ ); PyAPI_FUNC(int) _PyUnicode_ToDigit( - Py_UNICODE ch /* Unicode character */ + Py_UNICODE ch /* Unicode character */ ); PyAPI_FUNC(double) _PyUnicode_ToNumeric( - Py_UNICODE ch /* Unicode character */ + Py_UNICODE ch /* Unicode character */ ); PyAPI_FUNC(int) _PyUnicode_IsDecimalDigit( - Py_UNICODE ch /* Unicode character */ + Py_UNICODE ch /* Unicode character */ ); PyAPI_FUNC(int) _PyUnicode_IsDigit( - Py_UNICODE ch /* Unicode character */ + Py_UNICODE ch /* Unicode character */ ); PyAPI_FUNC(int) _PyUnicode_IsNumeric( - Py_UNICODE ch /* Unicode character */ + Py_UNICODE ch /* Unicode character */ ); PyAPI_FUNC(int) _PyUnicode_IsPrintable( - Py_UNICODE ch /* Unicode character */ + Py_UNICODE ch /* Unicode character */ ); PyAPI_FUNC(int) _PyUnicode_IsAlpha( - Py_UNICODE ch /* Unicode character */ + Py_UNICODE ch /* Unicode character */ ); PyAPI_FUNC(size_t) Py_UNICODE_strlen(const Py_UNICODE *u); Modified: python/branches/py3k/Mac/Tools/pythonw.c ============================================================================== --- python/branches/py3k/Mac/Tools/pythonw.c (original) +++ python/branches/py3k/Mac/Tools/pythonw.c Sun May 9 17:52:27 2010 @@ -39,8 +39,8 @@ * In a regular framework the structure is: * * Python.framework/Versions/2.7 - * /Python - * /Resources/Python.app/Contents/MacOS/Python + * /Python + * /Resources/Python.app/Contents/MacOS/Python * * In a virtualenv style structure the expected * structure is: @@ -50,121 +50,121 @@ * /.Python <- the dylib * /.Resources/Python.app/Contents/MacOS/Python * - * NOTE: virtualenv's are not an officially supported + * NOTE: virtualenv's are not an officially supported * feature, support for that structure is provided as * a convenience. */ static char* get_python_path(void) { - size_t len; - Dl_info info; - char* end; - char* g_path; - - if (dladdr(Py_Initialize, &info) == 0) { - return NULL; - } - - len = strlen(info.dli_fname); - - g_path = malloc(len+60); - if (g_path == NULL) { - return NULL; - } - - strcpy(g_path, info.dli_fname); - end = g_path + len - 1; - while (end != g_path && *end != '/') { - end --; - } - end++; - if (*end == '.') { - end++; - } - strcpy(end, "Resources/Python.app/Contents/MacOS/" PYTHONFRAMEWORK); + size_t len; + Dl_info info; + char* end; + char* g_path; + + if (dladdr(Py_Initialize, &info) == 0) { + return NULL; + } + + len = strlen(info.dli_fname); + + g_path = malloc(len+60); + if (g_path == NULL) { + return NULL; + } + + strcpy(g_path, info.dli_fname); + end = g_path + len - 1; + while (end != g_path && *end != '/') { + end --; + } + end++; + if (*end == '.') { + end++; + } + strcpy(end, "Resources/Python.app/Contents/MacOS/" PYTHONFRAMEWORK); - return g_path; + return g_path; } #ifdef HAVE_SPAWN_H static void setup_spawnattr(posix_spawnattr_t* spawnattr) { - size_t ocount; - size_t count; - cpu_type_t cpu_types[1]; - short flags = 0; + size_t ocount; + size_t count; + cpu_type_t cpu_types[1]; + short flags = 0; #ifdef __LP64__ - int ch; + int ch; #endif - if ((errno = posix_spawnattr_init(spawnattr)) != 0) { - err(2, "posix_spawnattr_int"); - /* NOTREACHTED */ - } - - count = 1; - - /* Run the real python executable using the same architure as this - * executable, this allows users to controle the architecture using - * "arch -ppc python" - */ + if ((errno = posix_spawnattr_init(spawnattr)) != 0) { + err(2, "posix_spawnattr_int"); + /* NOTREACHTED */ + } + + count = 1; + + /* Run the real python executable using the same architure as this + * executable, this allows users to controle the architecture using + * "arch -ppc python" + */ #if defined(__ppc64__) - cpu_types[0] = CPU_TYPE_POWERPC64; + cpu_types[0] = CPU_TYPE_POWERPC64; #elif defined(__x86_64__) - cpu_types[0] = CPU_TYPE_X86_64; + cpu_types[0] = CPU_TYPE_X86_64; #elif defined(__ppc__) - cpu_types[0] = CPU_TYPE_POWERPC; + cpu_types[0] = CPU_TYPE_POWERPC; #elif defined(__i386__) - cpu_types[0] = CPU_TYPE_X86; + cpu_types[0] = CPU_TYPE_X86; #else -# error "Unknown CPU" +# error "Unknown CPU" #endif - if (posix_spawnattr_setbinpref_np(spawnattr, count, - cpu_types, &ocount) == -1) { - err(1, "posix_spawnattr_setbinpref"); - /* NOTREACHTED */ - } - if (count != ocount) { - fprintf(stderr, "posix_spawnattr_setbinpref failed to copy\n"); - exit(1); - /* NOTREACHTED */ - } - - - /* - * Set flag that causes posix_spawn to behave like execv - */ - flags |= POSIX_SPAWN_SETEXEC; - if ((errno = posix_spawnattr_setflags(spawnattr, flags)) != 0) { - err(1, "posix_spawnattr_setflags"); - /* NOTREACHTED */ - } + if (posix_spawnattr_setbinpref_np(spawnattr, count, + cpu_types, &ocount) == -1) { + err(1, "posix_spawnattr_setbinpref"); + /* NOTREACHTED */ + } + if (count != ocount) { + fprintf(stderr, "posix_spawnattr_setbinpref failed to copy\n"); + exit(1); + /* NOTREACHTED */ + } + + + /* + * Set flag that causes posix_spawn to behave like execv + */ + flags |= POSIX_SPAWN_SETEXEC; + if ((errno = posix_spawnattr_setflags(spawnattr, flags)) != 0) { + err(1, "posix_spawnattr_setflags"); + /* NOTREACHTED */ + } } #endif -int +int main(int argc, char **argv) { - char* exec_path = get_python_path(); + char* exec_path = get_python_path(); #ifdef HAVE_SPAWN_H - /* We're weak-linking to posix-spawnv to ensure that - * an executable build on 10.5 can work on 10.4. - */ - if (posix_spawn != NULL) { - posix_spawnattr_t spawnattr = NULL; - - setup_spawnattr(&spawnattr); - posix_spawn(NULL, exec_path, NULL, - &spawnattr, argv, environ); - err(1, "posix_spawn: %s", exec_path); - } + /* We're weak-linking to posix-spawnv to ensure that + * an executable build on 10.5 can work on 10.4. + */ + if (posix_spawn != NULL) { + posix_spawnattr_t spawnattr = NULL; + + setup_spawnattr(&spawnattr); + posix_spawn(NULL, exec_path, NULL, + &spawnattr, argv, environ); + err(1, "posix_spawn: %s", exec_path); + } #endif - execve(exec_path, argv, environ); - err(1, "execve: %s", argv[0]); - /* NOTREACHED */ + execve(exec_path, argv, environ); + err(1, "execve: %s", argv[0]); + /* NOTREACHED */ } Modified: python/branches/py3k/Misc/setuid-prog.c ============================================================================== --- python/branches/py3k/Misc/setuid-prog.c (original) +++ python/branches/py3k/Misc/setuid-prog.c Sun May 9 17:52:27 2010 @@ -21,28 +21,28 @@ Assuming the script is a Bourne shell script, the first line of the script should be - #!/bin/sh - + #!/bin/sh - The - is important, don't omit it. If you're using esh, the first line should be - #!/usr/local/bin/esh -f + #!/usr/local/bin/esh -f and for ksh, the first line should be - #!/usr/local/bin/ksh -p + #!/usr/local/bin/ksh -p The script should then set the variable IFS to the string consisting of , , and . After this (*not* before!), the PATH variable should be set to a reasonable value and exported. Do not expect the PATH to have a reasonable value, so do not trust the old value of PATH. You should then set the umask of the program by calling - umask 077 # or 022 if you want the files to be readable + umask 077 # or 022 if you want the files to be readable If you plan to change directories, you should either unset CDPATH or set it to a good value. Setting CDPATH to just ``.'' (dot) is a good idea. If, for some reason, you want to use csh, the first line should be - #!/bin/csh -fb + #!/bin/csh -fb You should then set the path variable to something reasonable, without trusting the inherited path. Here too, you should set the umask using the command - umask 077 # or 022 if you want the files to be readable + umask 077 # or 022 if you want the files to be readable */ #include @@ -54,14 +54,14 @@ /* CONFIGURATION SECTION */ -#ifndef FULL_PATH /* so that this can be specified from the Makefile */ +#ifndef FULL_PATH /* so that this can be specified from the Makefile */ /* Uncomment the following line: -#define FULL_PATH "/full/path/of/script" +#define FULL_PATH "/full/path/of/script" * Then comment out the #error line. */ #error "You must define FULL_PATH somewhere" #endif #ifndef UMASK -#define UMASK 077 +#define UMASK 077 #endif /* END OF CONFIGURATION SECTION */ @@ -101,76 +101,76 @@ void clean_environ(void) { - char **p; - extern char **environ; + char **p; + extern char **environ; - for (p = environ; *p; p++) { - if (strncmp(*p, "LD_", 3) == 0) - **p = 'X'; - else if (strncmp(*p, "_RLD", 4) == 0) - **p = 'X'; - else if (strncmp(*p, "PYTHON", 6) == 0) - **p = 'X'; - else if (strncmp(*p, "IFS=", 4) == 0) - *p = def_IFS; - else if (strncmp(*p, "CDPATH=", 7) == 0) - *p = def_CDPATH; - else if (strncmp(*p, "ENV=", 4) == 0) - *p = def_ENV; - } - putenv(def_PATH); + for (p = environ; *p; p++) { + if (strncmp(*p, "LD_", 3) == 0) + **p = 'X'; + else if (strncmp(*p, "_RLD", 4) == 0) + **p = 'X'; + else if (strncmp(*p, "PYTHON", 6) == 0) + **p = 'X'; + else if (strncmp(*p, "IFS=", 4) == 0) + *p = def_IFS; + else if (strncmp(*p, "CDPATH=", 7) == 0) + *p = def_CDPATH; + else if (strncmp(*p, "ENV=", 4) == 0) + *p = def_ENV; + } + putenv(def_PATH); } int main(int argc, char **argv) { - struct stat statb; - gid_t egid = getegid(); - uid_t euid = geteuid(); - - /* - Sanity check #1. - This check should be made compile-time, but that's not possible. - If you're sure that you specified a full path name for FULL_PATH, - you can omit this check. - */ - if (FULL_PATH[0] != '/') { - fprintf(stderr, "%s: %s is not a full path name\n", argv[0], - FULL_PATH); - fprintf(stderr, "You can only use this wrapper if you\n"); - fprintf(stderr, "compile it with an absolute path.\n"); - exit(1); - } - - /* - Sanity check #2. - Check that the owner of the script is equal to either the - effective uid or the super user. - */ - if (stat(FULL_PATH, &statb) < 0) { - perror("stat"); - exit(1); - } - if (statb.st_uid != 0 && statb.st_uid != euid) { - fprintf(stderr, "%s: %s has the wrong owner\n", argv[0], - FULL_PATH); - fprintf(stderr, "The script should be owned by root,\n"); - fprintf(stderr, "and shouldn't be writable by anyone.\n"); - exit(1); - } - - if (setregid(egid, egid) < 0) - perror("setregid"); - if (setreuid(euid, euid) < 0) - perror("setreuid"); - - clean_environ(); - - umask(UMASK); - - while (**argv == '-') /* don't let argv[0] start with '-' */ - (*argv)++; - execv(FULL_PATH, argv); - fprintf(stderr, "%s: could not execute the script\n", argv[0]); - exit(1); + struct stat statb; + gid_t egid = getegid(); + uid_t euid = geteuid(); + + /* + Sanity check #1. + This check should be made compile-time, but that's not possible. + If you're sure that you specified a full path name for FULL_PATH, + you can omit this check. + */ + if (FULL_PATH[0] != '/') { + fprintf(stderr, "%s: %s is not a full path name\n", argv[0], + FULL_PATH); + fprintf(stderr, "You can only use this wrapper if you\n"); + fprintf(stderr, "compile it with an absolute path.\n"); + exit(1); + } + + /* + Sanity check #2. + Check that the owner of the script is equal to either the + effective uid or the super user. + */ + if (stat(FULL_PATH, &statb) < 0) { + perror("stat"); + exit(1); + } + if (statb.st_uid != 0 && statb.st_uid != euid) { + fprintf(stderr, "%s: %s has the wrong owner\n", argv[0], + FULL_PATH); + fprintf(stderr, "The script should be owned by root,\n"); + fprintf(stderr, "and shouldn't be writable by anyone.\n"); + exit(1); + } + + if (setregid(egid, egid) < 0) + perror("setregid"); + if (setreuid(euid, euid) < 0) + perror("setreuid"); + + clean_environ(); + + umask(UMASK); + + while (**argv == '-') /* don't let argv[0] start with '-' */ + (*argv)++; + execv(FULL_PATH, argv); + fprintf(stderr, "%s: could not execute the script\n", argv[0]); + exit(1); } Modified: python/branches/py3k/Modules/_bisectmodule.c ============================================================================== --- python/branches/py3k/Modules/_bisectmodule.c (original) +++ python/branches/py3k/Modules/_bisectmodule.c Sun May 9 17:52:27 2010 @@ -8,51 +8,51 @@ static Py_ssize_t internal_bisect_right(PyObject *list, PyObject *item, Py_ssize_t lo, Py_ssize_t hi) { - PyObject *litem; - Py_ssize_t mid, res; + PyObject *litem; + Py_ssize_t mid, res; - if (lo < 0) { - PyErr_SetString(PyExc_ValueError, "lo must be non-negative"); - return -1; - } - if (hi == -1) { - hi = PySequence_Size(list); - if (hi < 0) - return -1; - } - while (lo < hi) { - mid = (lo + hi) / 2; - litem = PySequence_GetItem(list, mid); - if (litem == NULL) - return -1; - res = PyObject_RichCompareBool(item, litem, Py_LT); - Py_DECREF(litem); - if (res < 0) - return -1; - if (res) - hi = mid; - else - lo = mid + 1; - } - return lo; + if (lo < 0) { + PyErr_SetString(PyExc_ValueError, "lo must be non-negative"); + return -1; + } + if (hi == -1) { + hi = PySequence_Size(list); + if (hi < 0) + return -1; + } + while (lo < hi) { + mid = (lo + hi) / 2; + litem = PySequence_GetItem(list, mid); + if (litem == NULL) + return -1; + res = PyObject_RichCompareBool(item, litem, Py_LT); + Py_DECREF(litem); + if (res < 0) + return -1; + if (res) + hi = mid; + else + lo = mid + 1; + } + return lo; } static PyObject * bisect_right(PyObject *self, PyObject *args, PyObject *kw) { - PyObject *list, *item; - Py_ssize_t lo = 0; - Py_ssize_t hi = -1; - Py_ssize_t index; - static char *keywords[] = {"a", "x", "lo", "hi", NULL}; - - if (!PyArg_ParseTupleAndKeywords(args, kw, "OO|nn:bisect_right", - keywords, &list, &item, &lo, &hi)) - return NULL; - index = internal_bisect_right(list, item, lo, hi); - if (index < 0) - return NULL; - return PyLong_FromSsize_t(index); + PyObject *list, *item; + Py_ssize_t lo = 0; + Py_ssize_t hi = -1; + Py_ssize_t index; + static char *keywords[] = {"a", "x", "lo", "hi", NULL}; + + if (!PyArg_ParseTupleAndKeywords(args, kw, "OO|nn:bisect_right", + keywords, &list, &item, &lo, &hi)) + return NULL; + index = internal_bisect_right(list, item, lo, hi); + if (index < 0) + return NULL; + return PyLong_FromSsize_t(index); } PyDoc_STRVAR(bisect_right_doc, @@ -70,30 +70,30 @@ static PyObject * insort_right(PyObject *self, PyObject *args, PyObject *kw) { - PyObject *list, *item, *result; - Py_ssize_t lo = 0; - Py_ssize_t hi = -1; - Py_ssize_t index; - static char *keywords[] = {"a", "x", "lo", "hi", NULL}; - - if (!PyArg_ParseTupleAndKeywords(args, kw, "OO|nn:insort_right", - keywords, &list, &item, &lo, &hi)) - return NULL; - index = internal_bisect_right(list, item, lo, hi); - if (index < 0) - return NULL; - if (PyList_CheckExact(list)) { - if (PyList_Insert(list, index, item) < 0) - return NULL; - } else { - result = PyObject_CallMethod(list, "insert", "nO", - index, item); - if (result == NULL) - return NULL; - Py_DECREF(result); - } + PyObject *list, *item, *result; + Py_ssize_t lo = 0; + Py_ssize_t hi = -1; + Py_ssize_t index; + static char *keywords[] = {"a", "x", "lo", "hi", NULL}; + + if (!PyArg_ParseTupleAndKeywords(args, kw, "OO|nn:insort_right", + keywords, &list, &item, &lo, &hi)) + return NULL; + index = internal_bisect_right(list, item, lo, hi); + if (index < 0) + return NULL; + if (PyList_CheckExact(list)) { + if (PyList_Insert(list, index, item) < 0) + return NULL; + } else { + result = PyObject_CallMethod(list, "insert", "nO", + index, item); + if (result == NULL) + return NULL; + Py_DECREF(result); + } - Py_RETURN_NONE; + Py_RETURN_NONE; } PyDoc_STRVAR(insort_right_doc, @@ -109,51 +109,51 @@ static Py_ssize_t internal_bisect_left(PyObject *list, PyObject *item, Py_ssize_t lo, Py_ssize_t hi) { - PyObject *litem; - Py_ssize_t mid, res; + PyObject *litem; + Py_ssize_t mid, res; - if (lo < 0) { - PyErr_SetString(PyExc_ValueError, "lo must be non-negative"); - return -1; - } - if (hi == -1) { - hi = PySequence_Size(list); - if (hi < 0) - return -1; - } - while (lo < hi) { - mid = (lo + hi) / 2; - litem = PySequence_GetItem(list, mid); - if (litem == NULL) - return -1; - res = PyObject_RichCompareBool(litem, item, Py_LT); - Py_DECREF(litem); - if (res < 0) - return -1; - if (res) - lo = mid + 1; - else - hi = mid; - } - return lo; + if (lo < 0) { + PyErr_SetString(PyExc_ValueError, "lo must be non-negative"); + return -1; + } + if (hi == -1) { + hi = PySequence_Size(list); + if (hi < 0) + return -1; + } + while (lo < hi) { + mid = (lo + hi) / 2; + litem = PySequence_GetItem(list, mid); + if (litem == NULL) + return -1; + res = PyObject_RichCompareBool(litem, item, Py_LT); + Py_DECREF(litem); + if (res < 0) + return -1; + if (res) + lo = mid + 1; + else + hi = mid; + } + return lo; } static PyObject * bisect_left(PyObject *self, PyObject *args, PyObject *kw) { - PyObject *list, *item; - Py_ssize_t lo = 0; - Py_ssize_t hi = -1; - Py_ssize_t index; - static char *keywords[] = {"a", "x", "lo", "hi", NULL}; - - if (!PyArg_ParseTupleAndKeywords(args, kw, "OO|nn:bisect_left", - keywords, &list, &item, &lo, &hi)) - return NULL; - index = internal_bisect_left(list, item, lo, hi); - if (index < 0) - return NULL; - return PyLong_FromSsize_t(index); + PyObject *list, *item; + Py_ssize_t lo = 0; + Py_ssize_t hi = -1; + Py_ssize_t index; + static char *keywords[] = {"a", "x", "lo", "hi", NULL}; + + if (!PyArg_ParseTupleAndKeywords(args, kw, "OO|nn:bisect_left", + keywords, &list, &item, &lo, &hi)) + return NULL; + index = internal_bisect_left(list, item, lo, hi); + if (index < 0) + return NULL; + return PyLong_FromSsize_t(index); } PyDoc_STRVAR(bisect_left_doc, @@ -171,30 +171,30 @@ static PyObject * insort_left(PyObject *self, PyObject *args, PyObject *kw) { - PyObject *list, *item, *result; - Py_ssize_t lo = 0; - Py_ssize_t hi = -1; - Py_ssize_t index; - static char *keywords[] = {"a", "x", "lo", "hi", NULL}; - - if (!PyArg_ParseTupleAndKeywords(args, kw, "OO|nn:insort_left", - keywords, &list, &item, &lo, &hi)) - return NULL; - index = internal_bisect_left(list, item, lo, hi); - if (index < 0) - return NULL; - if (PyList_CheckExact(list)) { - if (PyList_Insert(list, index, item) < 0) - return NULL; - } else { - result = PyObject_CallMethod(list, "insert", "iO", - index, item); - if (result == NULL) - return NULL; - Py_DECREF(result); - } + PyObject *list, *item, *result; + Py_ssize_t lo = 0; + Py_ssize_t hi = -1; + Py_ssize_t index; + static char *keywords[] = {"a", "x", "lo", "hi", NULL}; + + if (!PyArg_ParseTupleAndKeywords(args, kw, "OO|nn:insort_left", + keywords, &list, &item, &lo, &hi)) + return NULL; + index = internal_bisect_left(list, item, lo, hi); + if (index < 0) + return NULL; + if (PyList_CheckExact(list)) { + if (PyList_Insert(list, index, item) < 0) + return NULL; + } else { + result = PyObject_CallMethod(list, "insert", "iO", + index, item); + if (result == NULL) + return NULL; + Py_DECREF(result); + } - Py_RETURN_NONE; + Py_RETURN_NONE; } PyDoc_STRVAR(insort_left_doc, @@ -211,19 +211,19 @@ PyDoc_STRVAR(insort_doc, "Alias for insort_right().\n"); static PyMethodDef bisect_methods[] = { - {"bisect_right", (PyCFunction)bisect_right, - METH_VARARGS|METH_KEYWORDS, bisect_right_doc}, - {"bisect", (PyCFunction)bisect_right, - METH_VARARGS|METH_KEYWORDS, bisect_doc}, - {"insort_right", (PyCFunction)insort_right, - METH_VARARGS|METH_KEYWORDS, insort_right_doc}, - {"insort", (PyCFunction)insort_right, - METH_VARARGS|METH_KEYWORDS, insort_doc}, - {"bisect_left", (PyCFunction)bisect_left, - METH_VARARGS|METH_KEYWORDS, bisect_left_doc}, - {"insort_left", (PyCFunction)insort_left, - METH_VARARGS|METH_KEYWORDS, insort_left_doc}, - {NULL, NULL} /* sentinel */ + {"bisect_right", (PyCFunction)bisect_right, + METH_VARARGS|METH_KEYWORDS, bisect_right_doc}, + {"bisect", (PyCFunction)bisect_right, + METH_VARARGS|METH_KEYWORDS, bisect_doc}, + {"insort_right", (PyCFunction)insort_right, + METH_VARARGS|METH_KEYWORDS, insort_right_doc}, + {"insort", (PyCFunction)insort_right, + METH_VARARGS|METH_KEYWORDS, insort_doc}, + {"bisect_left", (PyCFunction)bisect_left, + METH_VARARGS|METH_KEYWORDS, bisect_left_doc}, + {"insort_left", (PyCFunction)insort_left, + METH_VARARGS|METH_KEYWORDS, insort_left_doc}, + {NULL, NULL} /* sentinel */ }; PyDoc_STRVAR(module_doc, @@ -236,19 +236,19 @@ static struct PyModuleDef _bisectmodule = { - PyModuleDef_HEAD_INIT, - "_bisect", - module_doc, - -1, - bisect_methods, - NULL, - NULL, - NULL, - NULL + PyModuleDef_HEAD_INIT, + "_bisect", + module_doc, + -1, + bisect_methods, + NULL, + NULL, + NULL, + NULL }; PyMODINIT_FUNC PyInit__bisect(void) { - return PyModule_Create(&_bisectmodule); + return PyModule_Create(&_bisectmodule); } Modified: python/branches/py3k/Modules/_codecsmodule.c ============================================================================== --- python/branches/py3k/Modules/_codecsmodule.c (original) +++ python/branches/py3k/Modules/_codecsmodule.c Sun May 9 17:52:27 2010 @@ -15,7 +15,7 @@ The builtin Unicode codecs use the following interface: _encode(Unicode_object[,errors='strict']) -> - (string object, bytes consumed) + (string object, bytes consumed) _decode(char_buffer_obj[,errors='strict']) -> (Unicode object, bytes consumed) @@ -95,7 +95,7 @@ return NULL; if (encoding == NULL) - encoding = PyUnicode_GetDefaultEncoding(); + encoding = PyUnicode_GetDefaultEncoding(); /* Encode via the codec registry */ return PyCodec_Encode(v, encoding, errors); @@ -122,7 +122,7 @@ return NULL; if (encoding == NULL) - encoding = PyUnicode_GetDefaultEncoding(); + encoding = PyUnicode_GetDefaultEncoding(); /* Decode via the codec registry */ return PyCodec_Decode(v, encoding, errors); @@ -132,7 +132,7 @@ static PyObject *codec_tuple(PyObject *unicode, - Py_ssize_t len) + Py_ssize_t len) { PyObject *v; if (unicode == NULL) @@ -145,86 +145,86 @@ /* --- String codecs ------------------------------------------------------ */ static PyObject * escape_decode(PyObject *self, - PyObject *args) + PyObject *args) { const char *errors = NULL; const char *data; Py_ssize_t size; if (!PyArg_ParseTuple(args, "s#|z:escape_decode", - &data, &size, &errors)) - return NULL; + &data, &size, &errors)) + return NULL; return codec_tuple(PyBytes_DecodeEscape(data, size, errors, 0, NULL), - size); + size); } static PyObject * escape_encode(PyObject *self, - PyObject *args) + PyObject *args) { - static const char *hexdigits = "0123456789abcdef"; - PyObject *str; - Py_ssize_t size; - Py_ssize_t newsize; - const char *errors = NULL; - PyObject *v; - - if (!PyArg_ParseTuple(args, "O!|z:escape_encode", - &PyBytes_Type, &str, &errors)) - return NULL; - - size = PyBytes_GET_SIZE(str); - newsize = 4*size; - if (newsize > PY_SSIZE_T_MAX || newsize / 4 != size) { - PyErr_SetString(PyExc_OverflowError, - "string is too large to encode"); - return NULL; - } - v = PyBytes_FromStringAndSize(NULL, newsize); - - if (v == NULL) { - return NULL; - } - else { - register Py_ssize_t i; - register char c; - register char *p = PyBytes_AS_STRING(v); - - for (i = 0; i < size; i++) { - /* There's at least enough room for a hex escape */ - assert(newsize - (p - PyBytes_AS_STRING(v)) >= 4); - c = PyBytes_AS_STRING(str)[i]; - if (c == '\'' || 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++ = hexdigits[(c & 0xf0) >> 4]; - *p++ = hexdigits[c & 0xf]; - } - else - *p++ = c; - } - *p = '\0'; - if (_PyBytes_Resize(&v, (p - PyBytes_AS_STRING(v)))) { - return NULL; - } - } - - return codec_tuple(v, size); + static const char *hexdigits = "0123456789abcdef"; + PyObject *str; + Py_ssize_t size; + Py_ssize_t newsize; + const char *errors = NULL; + PyObject *v; + + if (!PyArg_ParseTuple(args, "O!|z:escape_encode", + &PyBytes_Type, &str, &errors)) + return NULL; + + size = PyBytes_GET_SIZE(str); + newsize = 4*size; + if (newsize > PY_SSIZE_T_MAX || newsize / 4 != size) { + PyErr_SetString(PyExc_OverflowError, + "string is too large to encode"); + return NULL; + } + v = PyBytes_FromStringAndSize(NULL, newsize); + + if (v == NULL) { + return NULL; + } + else { + register Py_ssize_t i; + register char c; + register char *p = PyBytes_AS_STRING(v); + + for (i = 0; i < size; i++) { + /* There's at least enough room for a hex escape */ + assert(newsize - (p - PyBytes_AS_STRING(v)) >= 4); + c = PyBytes_AS_STRING(str)[i]; + if (c == '\'' || 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++ = hexdigits[(c & 0xf0) >> 4]; + *p++ = hexdigits[c & 0xf]; + } + else + *p++ = c; + } + *p = '\0'; + if (_PyBytes_Resize(&v, (p - PyBytes_AS_STRING(v)))) { + return NULL; + } + } + + return codec_tuple(v, size); } /* --- Decoder ------------------------------------------------------------ */ static PyObject * unicode_internal_decode(PyObject *self, - PyObject *args) + PyObject *args) { PyObject *obj; const char *errors = NULL; @@ -232,19 +232,19 @@ Py_ssize_t size; if (!PyArg_ParseTuple(args, "O|z:unicode_internal_decode", - &obj, &errors)) - return NULL; + &obj, &errors)) + return NULL; if (PyUnicode_Check(obj)) { - Py_INCREF(obj); - return codec_tuple(obj, PyUnicode_GET_SIZE(obj)); + Py_INCREF(obj); + return codec_tuple(obj, PyUnicode_GET_SIZE(obj)); } else { - if (PyObject_AsReadBuffer(obj, (const void **)&data, &size)) - return NULL; + if (PyObject_AsReadBuffer(obj, (const void **)&data, &size)) + return NULL; - return codec_tuple(_PyUnicode_DecodeUnicodeInternal(data, size, errors), - size); + return codec_tuple(_PyUnicode_DecodeUnicodeInternal(data, size, errors), + size); } } @@ -252,20 +252,20 @@ utf_7_decode(PyObject *self, PyObject *args) { - Py_buffer pbuf; + Py_buffer pbuf; const char *errors = NULL; int final = 0; Py_ssize_t consumed; PyObject *decoded = NULL; if (!PyArg_ParseTuple(args, "y*|zi:utf_7_decode", - &pbuf, &errors, &final)) - return NULL; + &pbuf, &errors, &final)) + return NULL; consumed = pbuf.len; decoded = PyUnicode_DecodeUTF7Stateful(pbuf.buf, pbuf.len, errors, - final ? NULL : &consumed); - PyBuffer_Release(&pbuf); + final ? NULL : &consumed); + PyBuffer_Release(&pbuf); if (decoded == NULL) return NULL; return codec_tuple(decoded, consumed); @@ -273,32 +273,32 @@ static PyObject * utf_8_decode(PyObject *self, - PyObject *args) + PyObject *args) { - Py_buffer pbuf; + Py_buffer pbuf; const char *errors = NULL; int final = 0; Py_ssize_t consumed; PyObject *decoded = NULL; if (!PyArg_ParseTuple(args, "y*|zi:utf_8_decode", - &pbuf, &errors, &final)) - return NULL; + &pbuf, &errors, &final)) + return NULL; consumed = pbuf.len; decoded = PyUnicode_DecodeUTF8Stateful(pbuf.buf, pbuf.len, errors, - final ? NULL : &consumed); - PyBuffer_Release(&pbuf); + final ? NULL : &consumed); + PyBuffer_Release(&pbuf); if (decoded == NULL) - return NULL; + return NULL; return codec_tuple(decoded, consumed); } static PyObject * utf_16_decode(PyObject *self, - PyObject *args) + PyObject *args) { - Py_buffer pbuf; + Py_buffer pbuf; const char *errors = NULL; int byteorder = 0; int final = 0; @@ -306,22 +306,22 @@ PyObject *decoded; if (!PyArg_ParseTuple(args, "y*|zi:utf_16_decode", - &pbuf, &errors, &final)) - return NULL; + &pbuf, &errors, &final)) + return NULL; consumed = pbuf.len; /* This is overwritten unless final is true. */ decoded = PyUnicode_DecodeUTF16Stateful(pbuf.buf, pbuf.len, errors, - &byteorder, final ? NULL : &consumed); - PyBuffer_Release(&pbuf); + &byteorder, final ? NULL : &consumed); + PyBuffer_Release(&pbuf); if (decoded == NULL) - return NULL; + return NULL; return codec_tuple(decoded, consumed); } static PyObject * utf_16_le_decode(PyObject *self, - PyObject *args) + PyObject *args) { - Py_buffer pbuf; + Py_buffer pbuf; const char *errors = NULL; int byteorder = -1; int final = 0; @@ -329,23 +329,23 @@ PyObject *decoded = NULL; if (!PyArg_ParseTuple(args, "y*|zi:utf_16_le_decode", - &pbuf, &errors, &final)) - return NULL; + &pbuf, &errors, &final)) + return NULL; consumed = pbuf.len; /* This is overwritten unless final is true. */ decoded = PyUnicode_DecodeUTF16Stateful(pbuf.buf, pbuf.len, errors, - &byteorder, final ? NULL : &consumed); - PyBuffer_Release(&pbuf); + &byteorder, final ? NULL : &consumed); + PyBuffer_Release(&pbuf); if (decoded == NULL) - return NULL; + return NULL; return codec_tuple(decoded, consumed); } static PyObject * utf_16_be_decode(PyObject *self, - PyObject *args) + PyObject *args) { - Py_buffer pbuf; + Py_buffer pbuf; const char *errors = NULL; int byteorder = 1; int final = 0; @@ -353,15 +353,15 @@ PyObject *decoded = NULL; if (!PyArg_ParseTuple(args, "y*|zi:utf_16_be_decode", - &pbuf, &errors, &final)) - return NULL; + &pbuf, &errors, &final)) + return NULL; consumed = pbuf.len; /* This is overwritten unless final is true. */ decoded = PyUnicode_DecodeUTF16Stateful(pbuf.buf, pbuf.len, errors, - &byteorder, final ? NULL : &consumed); - PyBuffer_Release(&pbuf); + &byteorder, final ? NULL : &consumed); + PyBuffer_Release(&pbuf); if (decoded == NULL) - return NULL; + return NULL; return codec_tuple(decoded, consumed); } @@ -375,9 +375,9 @@ static PyObject * utf_16_ex_decode(PyObject *self, - PyObject *args) + PyObject *args) { - Py_buffer pbuf; + Py_buffer pbuf; const char *errors = NULL; int byteorder = 0; PyObject *unicode, *tuple; @@ -385,14 +385,14 @@ Py_ssize_t consumed; if (!PyArg_ParseTuple(args, "y*|zii:utf_16_ex_decode", - &pbuf, &errors, &byteorder, &final)) - return NULL; + &pbuf, &errors, &byteorder, &final)) + return NULL; consumed = pbuf.len; /* This is overwritten unless final is true. */ unicode = PyUnicode_DecodeUTF16Stateful(pbuf.buf, pbuf.len, errors, - &byteorder, final ? NULL : &consumed); - PyBuffer_Release(&pbuf); + &byteorder, final ? NULL : &consumed); + PyBuffer_Release(&pbuf); if (unicode == NULL) - return NULL; + return NULL; tuple = Py_BuildValue("Oni", unicode, consumed, byteorder); Py_DECREF(unicode); return tuple; @@ -400,9 +400,9 @@ static PyObject * utf_32_decode(PyObject *self, - PyObject *args) + PyObject *args) { - Py_buffer pbuf; + Py_buffer pbuf; const char *errors = NULL; int byteorder = 0; int final = 0; @@ -410,22 +410,22 @@ PyObject *decoded; if (!PyArg_ParseTuple(args, "y*|zi:utf_32_decode", - &pbuf, &errors, &final)) - return NULL; + &pbuf, &errors, &final)) + return NULL; consumed = pbuf.len; /* This is overwritten unless final is true. */ decoded = PyUnicode_DecodeUTF32Stateful(pbuf.buf, pbuf.len, errors, - &byteorder, final ? NULL : &consumed); - PyBuffer_Release(&pbuf); + &byteorder, final ? NULL : &consumed); + PyBuffer_Release(&pbuf); if (decoded == NULL) - return NULL; + return NULL; return codec_tuple(decoded, consumed); } static PyObject * utf_32_le_decode(PyObject *self, - PyObject *args) + PyObject *args) { - Py_buffer pbuf; + Py_buffer pbuf; const char *errors = NULL; int byteorder = -1; int final = 0; @@ -433,22 +433,22 @@ PyObject *decoded; if (!PyArg_ParseTuple(args, "y*|zi:utf_32_le_decode", - &pbuf, &errors, &final)) - return NULL; + &pbuf, &errors, &final)) + return NULL; consumed = pbuf.len; /* This is overwritten unless final is true. */ decoded = PyUnicode_DecodeUTF32Stateful(pbuf.buf, pbuf.len, errors, - &byteorder, final ? NULL : &consumed); - PyBuffer_Release(&pbuf); + &byteorder, final ? NULL : &consumed); + PyBuffer_Release(&pbuf); if (decoded == NULL) - return NULL; + return NULL; return codec_tuple(decoded, consumed); } static PyObject * utf_32_be_decode(PyObject *self, - PyObject *args) + PyObject *args) { - Py_buffer pbuf; + Py_buffer pbuf; const char *errors = NULL; int byteorder = 1; int final = 0; @@ -456,14 +456,14 @@ PyObject *decoded; if (!PyArg_ParseTuple(args, "y*|zi:utf_32_be_decode", - &pbuf, &errors, &final)) - return NULL; + &pbuf, &errors, &final)) + return NULL; consumed = pbuf.len; /* This is overwritten unless final is true. */ decoded = PyUnicode_DecodeUTF32Stateful(pbuf.buf, pbuf.len, errors, - &byteorder, final ? NULL : &consumed); - PyBuffer_Release(&pbuf); + &byteorder, final ? NULL : &consumed); + PyBuffer_Release(&pbuf); if (decoded == NULL) - return NULL; + return NULL; return codec_tuple(decoded, consumed); } @@ -477,9 +477,9 @@ static PyObject * utf_32_ex_decode(PyObject *self, - PyObject *args) + PyObject *args) { - Py_buffer pbuf; + Py_buffer pbuf; const char *errors = NULL; int byteorder = 0; PyObject *unicode, *tuple; @@ -487,14 +487,14 @@ Py_ssize_t consumed; if (!PyArg_ParseTuple(args, "y*|zii:utf_32_ex_decode", - &pbuf, &errors, &byteorder, &final)) - return NULL; + &pbuf, &errors, &byteorder, &final)) + return NULL; consumed = pbuf.len; /* This is overwritten unless final is true. */ unicode = PyUnicode_DecodeUTF32Stateful(pbuf.buf, pbuf.len, errors, - &byteorder, final ? NULL : &consumed); - PyBuffer_Release(&pbuf); + &byteorder, final ? NULL : &consumed); + PyBuffer_Release(&pbuf); if (unicode == NULL) - return NULL; + return NULL; tuple = Py_BuildValue("Oni", unicode, consumed, byteorder); Py_DECREF(unicode); return tuple; @@ -502,114 +502,114 @@ static PyObject * unicode_escape_decode(PyObject *self, - PyObject *args) + PyObject *args) { - Py_buffer pbuf; + Py_buffer pbuf; const char *errors = NULL; - PyObject *unicode; + PyObject *unicode; if (!PyArg_ParseTuple(args, "s*|z:unicode_escape_decode", - &pbuf, &errors)) - return NULL; + &pbuf, &errors)) + return NULL; - unicode = PyUnicode_DecodeUnicodeEscape(pbuf.buf, pbuf.len, errors); - PyBuffer_Release(&pbuf); - return codec_tuple(unicode, pbuf.len); + unicode = PyUnicode_DecodeUnicodeEscape(pbuf.buf, pbuf.len, errors); + PyBuffer_Release(&pbuf); + return codec_tuple(unicode, pbuf.len); } static PyObject * raw_unicode_escape_decode(PyObject *self, - PyObject *args) + PyObject *args) { - Py_buffer pbuf; + Py_buffer pbuf; const char *errors = NULL; - PyObject *unicode; + PyObject *unicode; if (!PyArg_ParseTuple(args, "s*|z:raw_unicode_escape_decode", - &pbuf, &errors)) - return NULL; + &pbuf, &errors)) + return NULL; - unicode = PyUnicode_DecodeRawUnicodeEscape(pbuf.buf, pbuf.len, errors); - PyBuffer_Release(&pbuf); - return codec_tuple(unicode, pbuf.len); + unicode = PyUnicode_DecodeRawUnicodeEscape(pbuf.buf, pbuf.len, errors); + PyBuffer_Release(&pbuf); + return codec_tuple(unicode, pbuf.len); } static PyObject * latin_1_decode(PyObject *self, - PyObject *args) + PyObject *args) { - Py_buffer pbuf; - PyObject *unicode; + Py_buffer pbuf; + PyObject *unicode; const char *errors = NULL; if (!PyArg_ParseTuple(args, "y*|z:latin_1_decode", - &pbuf, &errors)) - return NULL; + &pbuf, &errors)) + return NULL; - unicode = PyUnicode_DecodeLatin1(pbuf.buf, pbuf.len, errors); - PyBuffer_Release(&pbuf); - return codec_tuple(unicode, pbuf.len); + unicode = PyUnicode_DecodeLatin1(pbuf.buf, pbuf.len, errors); + PyBuffer_Release(&pbuf); + return codec_tuple(unicode, pbuf.len); } static PyObject * ascii_decode(PyObject *self, - PyObject *args) + PyObject *args) { - Py_buffer pbuf; - PyObject *unicode; + Py_buffer pbuf; + PyObject *unicode; const char *errors = NULL; if (!PyArg_ParseTuple(args, "y*|z:ascii_decode", - &pbuf, &errors)) - return NULL; + &pbuf, &errors)) + return NULL; - unicode = PyUnicode_DecodeASCII(pbuf.buf, pbuf.len, errors); - PyBuffer_Release(&pbuf); - return codec_tuple(unicode, pbuf.len); + unicode = PyUnicode_DecodeASCII(pbuf.buf, pbuf.len, errors); + PyBuffer_Release(&pbuf); + return codec_tuple(unicode, pbuf.len); } static PyObject * charmap_decode(PyObject *self, - PyObject *args) + PyObject *args) { - Py_buffer pbuf; - PyObject *unicode; + Py_buffer pbuf; + PyObject *unicode; const char *errors = NULL; PyObject *mapping = NULL; if (!PyArg_ParseTuple(args, "y*|zO:charmap_decode", - &pbuf, &errors, &mapping)) - return NULL; + &pbuf, &errors, &mapping)) + return NULL; if (mapping == Py_None) - mapping = NULL; + mapping = NULL; - unicode = PyUnicode_DecodeCharmap(pbuf.buf, pbuf.len, mapping, errors); - PyBuffer_Release(&pbuf); - return codec_tuple(unicode, pbuf.len); + unicode = PyUnicode_DecodeCharmap(pbuf.buf, pbuf.len, mapping, errors); + PyBuffer_Release(&pbuf); + return codec_tuple(unicode, pbuf.len); } #if defined(MS_WINDOWS) && defined(HAVE_USABLE_WCHAR_T) static PyObject * mbcs_decode(PyObject *self, - PyObject *args) + PyObject *args) { - Py_buffer pbuf; + Py_buffer pbuf; const char *errors = NULL; int final = 0; Py_ssize_t consumed; PyObject *decoded = NULL; if (!PyArg_ParseTuple(args, "y*|zi:mbcs_decode", - &pbuf, &errors, &final)) - return NULL; + &pbuf, &errors, &final)) + return NULL; consumed = pbuf.len; decoded = PyUnicode_DecodeMBCSStateful(pbuf.buf, pbuf.len, errors, - final ? NULL : &consumed); - PyBuffer_Release(&pbuf); + final ? NULL : &consumed); + PyBuffer_Release(&pbuf); if (decoded == NULL) - return NULL; + return NULL; return codec_tuple(decoded, consumed); } @@ -619,7 +619,7 @@ static PyObject * readbuffer_encode(PyObject *self, - PyObject *args) + PyObject *args) { Py_buffer pdata; const char *data; @@ -628,8 +628,8 @@ PyObject *result; if (!PyArg_ParseTuple(args, "s*|z:readbuffer_encode", - &pdata, &errors)) - return NULL; + &pdata, &errors)) + return NULL; data = pdata.buf; size = pdata.len; @@ -640,22 +640,22 @@ static PyObject * charbuffer_encode(PyObject *self, - PyObject *args) + PyObject *args) { const char *data; Py_ssize_t size; const char *errors = NULL; if (!PyArg_ParseTuple(args, "t#|z:charbuffer_encode", - &data, &size, &errors)) - return NULL; + &data, &size, &errors)) + return NULL; return codec_tuple(PyBytes_FromStringAndSize(data, size), size); } static PyObject * unicode_internal_encode(PyObject *self, - PyObject *args) + PyObject *args) { PyObject *obj; const char *errors = NULL; @@ -663,64 +663,64 @@ Py_ssize_t size; if (!PyArg_ParseTuple(args, "O|z:unicode_internal_encode", - &obj, &errors)) - return NULL; + &obj, &errors)) + return NULL; if (PyUnicode_Check(obj)) { - data = PyUnicode_AS_DATA(obj); - size = PyUnicode_GET_DATA_SIZE(obj); - return codec_tuple(PyBytes_FromStringAndSize(data, size), - PyUnicode_GET_SIZE(obj)); + data = PyUnicode_AS_DATA(obj); + size = PyUnicode_GET_DATA_SIZE(obj); + return codec_tuple(PyBytes_FromStringAndSize(data, size), + PyUnicode_GET_SIZE(obj)); } else { - if (PyObject_AsReadBuffer(obj, (const void **)&data, &size)) - return NULL; - return codec_tuple(PyBytes_FromStringAndSize(data, size), size); + if (PyObject_AsReadBuffer(obj, (const void **)&data, &size)) + return NULL; + return codec_tuple(PyBytes_FromStringAndSize(data, size), size); } } static PyObject * utf_7_encode(PyObject *self, - PyObject *args) + PyObject *args) { PyObject *str, *v; const char *errors = NULL; if (!PyArg_ParseTuple(args, "O|z:utf_7_encode", - &str, &errors)) - return NULL; + &str, &errors)) + return NULL; str = PyUnicode_FromObject(str); if (str == NULL) - return NULL; + return NULL; v = codec_tuple(PyUnicode_EncodeUTF7(PyUnicode_AS_UNICODE(str), - PyUnicode_GET_SIZE(str), - 0, - 0, - errors), - PyUnicode_GET_SIZE(str)); + PyUnicode_GET_SIZE(str), + 0, + 0, + errors), + PyUnicode_GET_SIZE(str)); Py_DECREF(str); return v; } static PyObject * utf_8_encode(PyObject *self, - PyObject *args) + PyObject *args) { PyObject *str, *v; const char *errors = NULL; if (!PyArg_ParseTuple(args, "O|z:utf_8_encode", - &str, &errors)) - return NULL; + &str, &errors)) + return NULL; str = PyUnicode_FromObject(str); if (str == NULL) - return NULL; + return NULL; v = codec_tuple(PyUnicode_EncodeUTF8(PyUnicode_AS_UNICODE(str), - PyUnicode_GET_SIZE(str), - errors), - PyUnicode_GET_SIZE(str)); + PyUnicode_GET_SIZE(str), + errors), + PyUnicode_GET_SIZE(str)); Py_DECREF(str); return v; } @@ -734,70 +734,70 @@ static PyObject * utf_16_encode(PyObject *self, - PyObject *args) + PyObject *args) { PyObject *str, *v; const char *errors = NULL; int byteorder = 0; if (!PyArg_ParseTuple(args, "O|zi:utf_16_encode", - &str, &errors, &byteorder)) - return NULL; + &str, &errors, &byteorder)) + return NULL; str = PyUnicode_FromObject(str); if (str == NULL) - return NULL; + return NULL; v = codec_tuple(PyUnicode_EncodeUTF16(PyUnicode_AS_UNICODE(str), - PyUnicode_GET_SIZE(str), - errors, - byteorder), - PyUnicode_GET_SIZE(str)); + PyUnicode_GET_SIZE(str), + errors, + byteorder), + PyUnicode_GET_SIZE(str)); Py_DECREF(str); return v; } static PyObject * utf_16_le_encode(PyObject *self, - PyObject *args) + PyObject *args) { PyObject *str, *v; const char *errors = NULL; if (!PyArg_ParseTuple(args, "O|z:utf_16_le_encode", - &str, &errors)) - return NULL; + &str, &errors)) + return NULL; str = PyUnicode_FromObject(str); if (str == NULL) - return NULL; + return NULL; v = codec_tuple(PyUnicode_EncodeUTF16(PyUnicode_AS_UNICODE(str), - PyUnicode_GET_SIZE(str), - errors, - -1), - PyUnicode_GET_SIZE(str)); + PyUnicode_GET_SIZE(str), + errors, + -1), + PyUnicode_GET_SIZE(str)); Py_DECREF(str); return v; } static PyObject * utf_16_be_encode(PyObject *self, - PyObject *args) + PyObject *args) { PyObject *str, *v; const char *errors = NULL; if (!PyArg_ParseTuple(args, "O|z:utf_16_be_encode", - &str, &errors)) - return NULL; + &str, &errors)) + return NULL; str = PyUnicode_FromObject(str); if (str == NULL) - return NULL; + return NULL; v = codec_tuple(PyUnicode_EncodeUTF16(PyUnicode_AS_UNICODE(str), - PyUnicode_GET_SIZE(str), - errors, - +1), - PyUnicode_GET_SIZE(str)); + PyUnicode_GET_SIZE(str), + errors, + +1), + PyUnicode_GET_SIZE(str)); Py_DECREF(str); return v; } @@ -811,186 +811,186 @@ static PyObject * utf_32_encode(PyObject *self, - PyObject *args) + PyObject *args) { PyObject *str, *v; const char *errors = NULL; int byteorder = 0; if (!PyArg_ParseTuple(args, "O|zi:utf_32_encode", - &str, &errors, &byteorder)) - return NULL; + &str, &errors, &byteorder)) + return NULL; str = PyUnicode_FromObject(str); if (str == NULL) - return NULL; + return NULL; v = codec_tuple(PyUnicode_EncodeUTF32(PyUnicode_AS_UNICODE(str), - PyUnicode_GET_SIZE(str), - errors, - byteorder), - PyUnicode_GET_SIZE(str)); + PyUnicode_GET_SIZE(str), + errors, + byteorder), + PyUnicode_GET_SIZE(str)); Py_DECREF(str); return v; } static PyObject * utf_32_le_encode(PyObject *self, - PyObject *args) + PyObject *args) { PyObject *str, *v; const char *errors = NULL; if (!PyArg_ParseTuple(args, "O|z:utf_32_le_encode", - &str, &errors)) - return NULL; + &str, &errors)) + return NULL; str = PyUnicode_FromObject(str); if (str == NULL) - return NULL; + return NULL; v = codec_tuple(PyUnicode_EncodeUTF32(PyUnicode_AS_UNICODE(str), - PyUnicode_GET_SIZE(str), - errors, - -1), - PyUnicode_GET_SIZE(str)); + PyUnicode_GET_SIZE(str), + errors, + -1), + PyUnicode_GET_SIZE(str)); Py_DECREF(str); return v; } static PyObject * utf_32_be_encode(PyObject *self, - PyObject *args) + PyObject *args) { PyObject *str, *v; const char *errors = NULL; if (!PyArg_ParseTuple(args, "O|z:utf_32_be_encode", - &str, &errors)) - return NULL; + &str, &errors)) + return NULL; str = PyUnicode_FromObject(str); if (str == NULL) - return NULL; + return NULL; v = codec_tuple(PyUnicode_EncodeUTF32(PyUnicode_AS_UNICODE(str), - PyUnicode_GET_SIZE(str), - errors, - +1), - PyUnicode_GET_SIZE(str)); + PyUnicode_GET_SIZE(str), + errors, + +1), + PyUnicode_GET_SIZE(str)); Py_DECREF(str); return v; } static PyObject * unicode_escape_encode(PyObject *self, - PyObject *args) + PyObject *args) { PyObject *str, *v; const char *errors = NULL; if (!PyArg_ParseTuple(args, "O|z:unicode_escape_encode", - &str, &errors)) - return NULL; + &str, &errors)) + return NULL; str = PyUnicode_FromObject(str); if (str == NULL) - return NULL; + return NULL; v = codec_tuple(PyUnicode_EncodeUnicodeEscape(PyUnicode_AS_UNICODE(str), - PyUnicode_GET_SIZE(str)), - PyUnicode_GET_SIZE(str)); + PyUnicode_GET_SIZE(str)), + PyUnicode_GET_SIZE(str)); Py_DECREF(str); return v; } static PyObject * raw_unicode_escape_encode(PyObject *self, - PyObject *args) + PyObject *args) { PyObject *str, *v; const char *errors = NULL; if (!PyArg_ParseTuple(args, "O|z:raw_unicode_escape_encode", - &str, &errors)) - return NULL; + &str, &errors)) + return NULL; str = PyUnicode_FromObject(str); if (str == NULL) - return NULL; + return NULL; v = codec_tuple(PyUnicode_EncodeRawUnicodeEscape( - PyUnicode_AS_UNICODE(str), - PyUnicode_GET_SIZE(str)), - PyUnicode_GET_SIZE(str)); + PyUnicode_AS_UNICODE(str), + PyUnicode_GET_SIZE(str)), + PyUnicode_GET_SIZE(str)); Py_DECREF(str); return v; } static PyObject * latin_1_encode(PyObject *self, - PyObject *args) + PyObject *args) { PyObject *str, *v; const char *errors = NULL; if (!PyArg_ParseTuple(args, "O|z:latin_1_encode", - &str, &errors)) - return NULL; + &str, &errors)) + return NULL; str = PyUnicode_FromObject(str); if (str == NULL) - return NULL; + return NULL; v = codec_tuple(PyUnicode_EncodeLatin1( - PyUnicode_AS_UNICODE(str), - PyUnicode_GET_SIZE(str), - errors), - PyUnicode_GET_SIZE(str)); + PyUnicode_AS_UNICODE(str), + PyUnicode_GET_SIZE(str), + errors), + PyUnicode_GET_SIZE(str)); Py_DECREF(str); return v; } static PyObject * ascii_encode(PyObject *self, - PyObject *args) + PyObject *args) { PyObject *str, *v; const char *errors = NULL; if (!PyArg_ParseTuple(args, "O|z:ascii_encode", - &str, &errors)) - return NULL; + &str, &errors)) + return NULL; str = PyUnicode_FromObject(str); if (str == NULL) - return NULL; + return NULL; v = codec_tuple(PyUnicode_EncodeASCII( - PyUnicode_AS_UNICODE(str), - PyUnicode_GET_SIZE(str), - errors), - PyUnicode_GET_SIZE(str)); + PyUnicode_AS_UNICODE(str), + PyUnicode_GET_SIZE(str), + errors), + PyUnicode_GET_SIZE(str)); Py_DECREF(str); return v; } static PyObject * charmap_encode(PyObject *self, - PyObject *args) + PyObject *args) { PyObject *str, *v; const char *errors = NULL; PyObject *mapping = NULL; if (!PyArg_ParseTuple(args, "O|zO:charmap_encode", - &str, &errors, &mapping)) - return NULL; + &str, &errors, &mapping)) + return NULL; if (mapping == Py_None) - mapping = NULL; + mapping = NULL; str = PyUnicode_FromObject(str); if (str == NULL) - return NULL; + return NULL; v = codec_tuple(PyUnicode_EncodeCharmap( - PyUnicode_AS_UNICODE(str), - PyUnicode_GET_SIZE(str), - mapping, - errors), - PyUnicode_GET_SIZE(str)); + PyUnicode_AS_UNICODE(str), + PyUnicode_GET_SIZE(str), + mapping, + errors), + PyUnicode_GET_SIZE(str)); Py_DECREF(str); return v; } @@ -1008,23 +1008,23 @@ static PyObject * mbcs_encode(PyObject *self, - PyObject *args) + PyObject *args) { PyObject *str, *v; const char *errors = NULL; if (!PyArg_ParseTuple(args, "O|z:mbcs_encode", - &str, &errors)) - return NULL; + &str, &errors)) + return NULL; str = PyUnicode_FromObject(str); if (str == NULL) - return NULL; + return NULL; v = codec_tuple(PyUnicode_EncodeMBCS( - PyUnicode_AS_UNICODE(str), - PyUnicode_GET_SIZE(str), - errors), - PyUnicode_GET_SIZE(str)); + PyUnicode_AS_UNICODE(str), + PyUnicode_GET_SIZE(str), + errors), + PyUnicode_GET_SIZE(str)); Py_DECREF(str); return v; } @@ -1048,8 +1048,8 @@ PyObject *handler; if (!PyArg_ParseTuple(args, "sO:register_error", - &name, &handler)) - return NULL; + &name, &handler)) + return NULL; if (PyCodec_RegisterError(name, handler)) return NULL; Py_RETURN_NONE; @@ -1066,82 +1066,82 @@ const char *name; if (!PyArg_ParseTuple(args, "s:lookup_error", - &name)) - return NULL; + &name)) + return NULL; return PyCodec_LookupError(name); } /* --- Module API --------------------------------------------------------- */ static PyMethodDef _codecs_functions[] = { - {"register", codec_register, METH_O, + {"register", codec_register, METH_O, register__doc__}, - {"lookup", codec_lookup, METH_VARARGS, + {"lookup", codec_lookup, METH_VARARGS, lookup__doc__}, - {"encode", codec_encode, METH_VARARGS, - encode__doc__}, - {"decode", codec_decode, METH_VARARGS, - decode__doc__}, - {"escape_encode", escape_encode, METH_VARARGS}, - {"escape_decode", escape_decode, METH_VARARGS}, - {"utf_8_encode", utf_8_encode, METH_VARARGS}, - {"utf_8_decode", utf_8_decode, METH_VARARGS}, - {"utf_7_encode", utf_7_encode, METH_VARARGS}, - {"utf_7_decode", utf_7_decode, METH_VARARGS}, - {"utf_16_encode", utf_16_encode, METH_VARARGS}, - {"utf_16_le_encode", utf_16_le_encode, METH_VARARGS}, - {"utf_16_be_encode", utf_16_be_encode, METH_VARARGS}, - {"utf_16_decode", utf_16_decode, METH_VARARGS}, - {"utf_16_le_decode", utf_16_le_decode, METH_VARARGS}, - {"utf_16_be_decode", utf_16_be_decode, METH_VARARGS}, - {"utf_16_ex_decode", utf_16_ex_decode, METH_VARARGS}, - {"utf_32_encode", utf_32_encode, METH_VARARGS}, - {"utf_32_le_encode", utf_32_le_encode, METH_VARARGS}, - {"utf_32_be_encode", utf_32_be_encode, METH_VARARGS}, - {"utf_32_decode", utf_32_decode, METH_VARARGS}, - {"utf_32_le_decode", utf_32_le_decode, METH_VARARGS}, - {"utf_32_be_decode", utf_32_be_decode, METH_VARARGS}, - {"utf_32_ex_decode", utf_32_ex_decode, METH_VARARGS}, - {"unicode_escape_encode", unicode_escape_encode, METH_VARARGS}, - {"unicode_escape_decode", unicode_escape_decode, METH_VARARGS}, - {"unicode_internal_encode", unicode_internal_encode, METH_VARARGS}, - {"unicode_internal_decode", unicode_internal_decode, METH_VARARGS}, - {"raw_unicode_escape_encode", raw_unicode_escape_encode, METH_VARARGS}, - {"raw_unicode_escape_decode", raw_unicode_escape_decode, METH_VARARGS}, - {"latin_1_encode", latin_1_encode, METH_VARARGS}, - {"latin_1_decode", latin_1_decode, METH_VARARGS}, - {"ascii_encode", ascii_encode, METH_VARARGS}, - {"ascii_decode", ascii_decode, METH_VARARGS}, - {"charmap_encode", charmap_encode, METH_VARARGS}, - {"charmap_decode", charmap_decode, METH_VARARGS}, - {"charmap_build", charmap_build, METH_VARARGS}, - {"readbuffer_encode", readbuffer_encode, METH_VARARGS}, - {"charbuffer_encode", charbuffer_encode, METH_VARARGS}, + {"encode", codec_encode, METH_VARARGS, + encode__doc__}, + {"decode", codec_decode, METH_VARARGS, + decode__doc__}, + {"escape_encode", escape_encode, METH_VARARGS}, + {"escape_decode", escape_decode, METH_VARARGS}, + {"utf_8_encode", utf_8_encode, METH_VARARGS}, + {"utf_8_decode", utf_8_decode, METH_VARARGS}, + {"utf_7_encode", utf_7_encode, METH_VARARGS}, + {"utf_7_decode", utf_7_decode, METH_VARARGS}, + {"utf_16_encode", utf_16_encode, METH_VARARGS}, + {"utf_16_le_encode", utf_16_le_encode, METH_VARARGS}, + {"utf_16_be_encode", utf_16_be_encode, METH_VARARGS}, + {"utf_16_decode", utf_16_decode, METH_VARARGS}, + {"utf_16_le_decode", utf_16_le_decode, METH_VARARGS}, + {"utf_16_be_decode", utf_16_be_decode, METH_VARARGS}, + {"utf_16_ex_decode", utf_16_ex_decode, METH_VARARGS}, + {"utf_32_encode", utf_32_encode, METH_VARARGS}, + {"utf_32_le_encode", utf_32_le_encode, METH_VARARGS}, + {"utf_32_be_encode", utf_32_be_encode, METH_VARARGS}, + {"utf_32_decode", utf_32_decode, METH_VARARGS}, + {"utf_32_le_decode", utf_32_le_decode, METH_VARARGS}, + {"utf_32_be_decode", utf_32_be_decode, METH_VARARGS}, + {"utf_32_ex_decode", utf_32_ex_decode, METH_VARARGS}, + {"unicode_escape_encode", unicode_escape_encode, METH_VARARGS}, + {"unicode_escape_decode", unicode_escape_decode, METH_VARARGS}, + {"unicode_internal_encode", unicode_internal_encode, METH_VARARGS}, + {"unicode_internal_decode", unicode_internal_decode, METH_VARARGS}, + {"raw_unicode_escape_encode", raw_unicode_escape_encode, METH_VARARGS}, + {"raw_unicode_escape_decode", raw_unicode_escape_decode, METH_VARARGS}, + {"latin_1_encode", latin_1_encode, METH_VARARGS}, + {"latin_1_decode", latin_1_decode, METH_VARARGS}, + {"ascii_encode", ascii_encode, METH_VARARGS}, + {"ascii_decode", ascii_decode, METH_VARARGS}, + {"charmap_encode", charmap_encode, METH_VARARGS}, + {"charmap_decode", charmap_decode, METH_VARARGS}, + {"charmap_build", charmap_build, METH_VARARGS}, + {"readbuffer_encode", readbuffer_encode, METH_VARARGS}, + {"charbuffer_encode", charbuffer_encode, METH_VARARGS}, #if defined(MS_WINDOWS) && defined(HAVE_USABLE_WCHAR_T) - {"mbcs_encode", mbcs_encode, METH_VARARGS}, - {"mbcs_decode", mbcs_decode, METH_VARARGS}, + {"mbcs_encode", mbcs_encode, METH_VARARGS}, + {"mbcs_decode", mbcs_decode, METH_VARARGS}, #endif - {"register_error", register_error, METH_VARARGS, + {"register_error", register_error, METH_VARARGS, register_error__doc__}, - {"lookup_error", lookup_error, METH_VARARGS, + {"lookup_error", lookup_error, METH_VARARGS, lookup_error__doc__}, - {NULL, NULL} /* sentinel */ + {NULL, NULL} /* sentinel */ }; static struct PyModuleDef codecsmodule = { - PyModuleDef_HEAD_INIT, - "_codecs", - NULL, - -1, - _codecs_functions, - NULL, - NULL, - NULL, - NULL + PyModuleDef_HEAD_INIT, + "_codecs", + NULL, + -1, + _codecs_functions, + NULL, + NULL, + NULL, + NULL }; PyMODINIT_FUNC PyInit__codecs(void) { - return PyModule_Create(&codecsmodule); + return PyModule_Create(&codecsmodule); } Modified: python/branches/py3k/Modules/_collectionsmodule.c ============================================================================== --- python/branches/py3k/Modules/_collectionsmodule.c (original) +++ python/branches/py3k/Modules/_collectionsmodule.c Sun May 9 17:52:27 2010 @@ -46,9 +46,9 @@ */ typedef struct BLOCK { - struct BLOCK *leftlink; - struct BLOCK *rightlink; - PyObject *data[BLOCKLEN]; + struct BLOCK *leftlink; + struct BLOCK *rightlink; + PyObject *data[BLOCKLEN]; } block; #define MAXFREEBLOCKS 10 @@ -57,71 +57,71 @@ static block * newblock(block *leftlink, block *rightlink, Py_ssize_t len) { - block *b; - /* To prevent len from overflowing PY_SSIZE_T_MAX on 64-bit machines, we - * refuse to allocate new blocks if the current len is dangerously - * close. There is some extra margin to prevent spurious arithmetic - * overflows at various places. The following check ensures that - * the blocks allocated to the deque, in the worst case, can only - * have PY_SSIZE_T_MAX-2 entries in total. - */ - if (len >= PY_SSIZE_T_MAX - 2*BLOCKLEN) { - PyErr_SetString(PyExc_OverflowError, - "cannot add more blocks to the deque"); - return NULL; - } - if (numfreeblocks) { - numfreeblocks -= 1; - b = freeblocks[numfreeblocks]; - } else { - b = PyMem_Malloc(sizeof(block)); - if (b == NULL) { - PyErr_NoMemory(); - return NULL; - } - } - b->leftlink = leftlink; - b->rightlink = rightlink; - return b; + block *b; + /* To prevent len from overflowing PY_SSIZE_T_MAX on 64-bit machines, we + * refuse to allocate new blocks if the current len is dangerously + * close. There is some extra margin to prevent spurious arithmetic + * overflows at various places. The following check ensures that + * the blocks allocated to the deque, in the worst case, can only + * have PY_SSIZE_T_MAX-2 entries in total. + */ + if (len >= PY_SSIZE_T_MAX - 2*BLOCKLEN) { + PyErr_SetString(PyExc_OverflowError, + "cannot add more blocks to the deque"); + return NULL; + } + if (numfreeblocks) { + numfreeblocks -= 1; + b = freeblocks[numfreeblocks]; + } else { + b = PyMem_Malloc(sizeof(block)); + if (b == NULL) { + PyErr_NoMemory(); + return NULL; + } + } + b->leftlink = leftlink; + b->rightlink = rightlink; + return b; } static void freeblock(block *b) { - if (numfreeblocks < MAXFREEBLOCKS) { - freeblocks[numfreeblocks] = b; - numfreeblocks++; - } else { - PyMem_Free(b); - } + if (numfreeblocks < MAXFREEBLOCKS) { + freeblocks[numfreeblocks] = b; + numfreeblocks++; + } else { + PyMem_Free(b); + } } typedef struct { - PyObject_HEAD - block *leftblock; - block *rightblock; - Py_ssize_t leftindex; /* in range(BLOCKLEN) */ - Py_ssize_t rightindex; /* in range(BLOCKLEN) */ - Py_ssize_t len; - Py_ssize_t maxlen; - long state; /* incremented whenever the indices move */ - PyObject *weakreflist; /* List of weak references */ + PyObject_HEAD + block *leftblock; + block *rightblock; + Py_ssize_t leftindex; /* in range(BLOCKLEN) */ + Py_ssize_t rightindex; /* in range(BLOCKLEN) */ + Py_ssize_t len; + Py_ssize_t maxlen; + long state; /* incremented whenever the indices move */ + PyObject *weakreflist; /* List of weak references */ } dequeobject; /* The deque's size limit is d.maxlen. The limit can be zero or positive. * If there is no limit, then d.maxlen == -1. - * + * * After an item is added to a deque, we check to see if the size has grown past * the limit. If it has, we get the size back down to the limit by popping an * item off of the opposite end. The methods that can trigger this are append(), * appendleft(), extend(), and extendleft(). */ -#define TRIM(d, popfunction) \ - if (d->maxlen != -1 && d->len > d->maxlen) { \ - PyObject *rv = popfunction(d, NULL); \ - assert(rv != NULL && d->len <= d->maxlen); \ - Py_DECREF(rv); \ +#define TRIM(d, popfunction) \ + if (d->maxlen != -1 && d->len > d->maxlen) { \ + PyObject *rv = popfunction(d, NULL); \ + assert(rv != NULL && d->len <= d->maxlen); \ + Py_DECREF(rv); \ } static PyTypeObject deque_type; @@ -129,65 +129,65 @@ static PyObject * deque_new(PyTypeObject *type, PyObject *args, PyObject *kwds) { - dequeobject *deque; - block *b; + dequeobject *deque; + block *b; + + /* create dequeobject structure */ + deque = (dequeobject *)type->tp_alloc(type, 0); + if (deque == NULL) + return NULL; + + b = newblock(NULL, NULL, 0); + if (b == NULL) { + Py_DECREF(deque); + return NULL; + } - /* create dequeobject structure */ - deque = (dequeobject *)type->tp_alloc(type, 0); - if (deque == NULL) - return NULL; - - b = newblock(NULL, NULL, 0); - if (b == NULL) { - Py_DECREF(deque); - return NULL; - } - - assert(BLOCKLEN >= 2); - deque->leftblock = b; - deque->rightblock = b; - deque->leftindex = CENTER + 1; - deque->rightindex = CENTER; - deque->len = 0; - deque->state = 0; - deque->weakreflist = NULL; - deque->maxlen = -1; + assert(BLOCKLEN >= 2); + deque->leftblock = b; + deque->rightblock = b; + deque->leftindex = CENTER + 1; + deque->rightindex = CENTER; + deque->len = 0; + deque->state = 0; + deque->weakreflist = NULL; + deque->maxlen = -1; - return (PyObject *)deque; + return (PyObject *)deque; } static PyObject * deque_pop(dequeobject *deque, PyObject *unused) { - PyObject *item; - block *prevblock; + PyObject *item; + block *prevblock; - if (deque->len == 0) { - PyErr_SetString(PyExc_IndexError, "pop from an empty deque"); - return NULL; - } - item = deque->rightblock->data[deque->rightindex]; - deque->rightindex--; - deque->len--; - deque->state++; - - if (deque->rightindex == -1) { - if (deque->len == 0) { - assert(deque->leftblock == deque->rightblock); - assert(deque->leftindex == deque->rightindex+1); - /* re-center instead of freeing a block */ - deque->leftindex = CENTER + 1; - deque->rightindex = CENTER; - } else { - prevblock = deque->rightblock->leftlink; - assert(deque->leftblock != deque->rightblock); - freeblock(deque->rightblock); - prevblock->rightlink = NULL; - deque->rightblock = prevblock; - deque->rightindex = BLOCKLEN - 1; - } - } - return item; + if (deque->len == 0) { + PyErr_SetString(PyExc_IndexError, "pop from an empty deque"); + return NULL; + } + item = deque->rightblock->data[deque->rightindex]; + deque->rightindex--; + deque->len--; + deque->state++; + + if (deque->rightindex == -1) { + if (deque->len == 0) { + assert(deque->leftblock == deque->rightblock); + assert(deque->leftindex == deque->rightindex+1); + /* re-center instead of freeing a block */ + deque->leftindex = CENTER + 1; + deque->rightindex = CENTER; + } else { + prevblock = deque->rightblock->leftlink; + assert(deque->leftblock != deque->rightblock); + freeblock(deque->rightblock); + prevblock->rightlink = NULL; + deque->rightblock = prevblock; + deque->rightindex = BLOCKLEN - 1; + } + } + return item; } PyDoc_STRVAR(pop_doc, "Remove and return the rightmost element."); @@ -195,37 +195,37 @@ static PyObject * deque_popleft(dequeobject *deque, PyObject *unused) { - PyObject *item; - block *prevblock; + PyObject *item; + block *prevblock; - if (deque->len == 0) { - PyErr_SetString(PyExc_IndexError, "pop from an empty deque"); - return NULL; - } - assert(deque->leftblock != NULL); - item = deque->leftblock->data[deque->leftindex]; - deque->leftindex++; - deque->len--; - deque->state++; - - if (deque->leftindex == BLOCKLEN) { - if (deque->len == 0) { - assert(deque->leftblock == deque->rightblock); - assert(deque->leftindex == deque->rightindex+1); - /* re-center instead of freeing a block */ - deque->leftindex = CENTER + 1; - deque->rightindex = CENTER; - } else { - assert(deque->leftblock != deque->rightblock); - prevblock = deque->leftblock->rightlink; - freeblock(deque->leftblock); - assert(prevblock != NULL); - prevblock->leftlink = NULL; - deque->leftblock = prevblock; - deque->leftindex = 0; - } - } - return item; + if (deque->len == 0) { + PyErr_SetString(PyExc_IndexError, "pop from an empty deque"); + return NULL; + } + assert(deque->leftblock != NULL); + item = deque->leftblock->data[deque->leftindex]; + deque->leftindex++; + deque->len--; + deque->state++; + + if (deque->leftindex == BLOCKLEN) { + if (deque->len == 0) { + assert(deque->leftblock == deque->rightblock); + assert(deque->leftindex == deque->rightindex+1); + /* re-center instead of freeing a block */ + deque->leftindex = CENTER + 1; + deque->rightindex = CENTER; + } else { + assert(deque->leftblock != deque->rightblock); + prevblock = deque->leftblock->rightlink; + freeblock(deque->leftblock); + assert(prevblock != NULL); + prevblock->leftlink = NULL; + deque->leftblock = prevblock; + deque->leftindex = 0; + } + } + return item; } PyDoc_STRVAR(popleft_doc, "Remove and return the leftmost element."); @@ -233,22 +233,22 @@ static PyObject * deque_append(dequeobject *deque, PyObject *item) { - deque->state++; - if (deque->rightindex == BLOCKLEN-1) { - block *b = newblock(deque->rightblock, NULL, deque->len); - if (b == NULL) - return NULL; - assert(deque->rightblock->rightlink == NULL); - deque->rightblock->rightlink = b; - deque->rightblock = b; - deque->rightindex = -1; - } - Py_INCREF(item); - deque->len++; - deque->rightindex++; - deque->rightblock->data[deque->rightindex] = item; - TRIM(deque, deque_popleft); - Py_RETURN_NONE; + deque->state++; + if (deque->rightindex == BLOCKLEN-1) { + block *b = newblock(deque->rightblock, NULL, deque->len); + if (b == NULL) + return NULL; + assert(deque->rightblock->rightlink == NULL); + deque->rightblock->rightlink = b; + deque->rightblock = b; + deque->rightindex = -1; + } + Py_INCREF(item); + deque->len++; + deque->rightindex++; + deque->rightblock->data[deque->rightindex] = item; + TRIM(deque, deque_popleft); + Py_RETURN_NONE; } PyDoc_STRVAR(append_doc, "Add an element to the right side of the deque."); @@ -256,90 +256,90 @@ static PyObject * deque_appendleft(dequeobject *deque, PyObject *item) { - deque->state++; - if (deque->leftindex == 0) { - block *b = newblock(NULL, deque->leftblock, deque->len); - if (b == NULL) - return NULL; - assert(deque->leftblock->leftlink == NULL); - deque->leftblock->leftlink = b; - deque->leftblock = b; - deque->leftindex = BLOCKLEN; - } - Py_INCREF(item); - deque->len++; - deque->leftindex--; - deque->leftblock->data[deque->leftindex] = item; - TRIM(deque, deque_pop); - Py_RETURN_NONE; + deque->state++; + if (deque->leftindex == 0) { + block *b = newblock(NULL, deque->leftblock, deque->len); + if (b == NULL) + return NULL; + assert(deque->leftblock->leftlink == NULL); + deque->leftblock->leftlink = b; + deque->leftblock = b; + deque->leftindex = BLOCKLEN; + } + Py_INCREF(item); + deque->len++; + deque->leftindex--; + deque->leftblock->data[deque->leftindex] = item; + TRIM(deque, deque_pop); + Py_RETURN_NONE; } PyDoc_STRVAR(appendleft_doc, "Add an element to the left side of the deque."); -/* Run an iterator to exhaustion. Shortcut for +/* Run an iterator to exhaustion. Shortcut for the extend/extendleft methods when maxlen == 0. */ static PyObject* consume_iterator(PyObject *it) { - PyObject *item; + PyObject *item; - while ((item = PyIter_Next(it)) != NULL) { - Py_DECREF(item); - } - Py_DECREF(it); - if (PyErr_Occurred()) - return NULL; - Py_RETURN_NONE; + while ((item = PyIter_Next(it)) != NULL) { + Py_DECREF(item); + } + Py_DECREF(it); + if (PyErr_Occurred()) + return NULL; + Py_RETURN_NONE; } static PyObject * deque_extend(dequeobject *deque, PyObject *iterable) { - PyObject *it, *item; + PyObject *it, *item; - /* Handle case where id(deque) == id(iterable) */ - if ((PyObject *)deque == iterable) { - PyObject *result; - PyObject *s = PySequence_List(iterable); - if (s == NULL) - return NULL; - result = deque_extend(deque, s); - Py_DECREF(s); - return result; - } - - it = PyObject_GetIter(iterable); - if (it == NULL) - return NULL; - - if (deque->maxlen == 0) - return consume_iterator(it); - - while ((item = PyIter_Next(it)) != NULL) { - deque->state++; - if (deque->rightindex == BLOCKLEN-1) { - block *b = newblock(deque->rightblock, NULL, - deque->len); - if (b == NULL) { - Py_DECREF(item); - Py_DECREF(it); - return NULL; - } - assert(deque->rightblock->rightlink == NULL); - deque->rightblock->rightlink = b; - deque->rightblock = b; - deque->rightindex = -1; - } - deque->len++; - deque->rightindex++; - deque->rightblock->data[deque->rightindex] = item; - TRIM(deque, deque_popleft); - } - Py_DECREF(it); - if (PyErr_Occurred()) - return NULL; - Py_RETURN_NONE; + /* Handle case where id(deque) == id(iterable) */ + if ((PyObject *)deque == iterable) { + PyObject *result; + PyObject *s = PySequence_List(iterable); + if (s == NULL) + return NULL; + result = deque_extend(deque, s); + Py_DECREF(s); + return result; + } + + it = PyObject_GetIter(iterable); + if (it == NULL) + return NULL; + + if (deque->maxlen == 0) + return consume_iterator(it); + + while ((item = PyIter_Next(it)) != NULL) { + deque->state++; + if (deque->rightindex == BLOCKLEN-1) { + block *b = newblock(deque->rightblock, NULL, + deque->len); + if (b == NULL) { + Py_DECREF(item); + Py_DECREF(it); + return NULL; + } + assert(deque->rightblock->rightlink == NULL); + deque->rightblock->rightlink = b; + deque->rightblock = b; + deque->rightindex = -1; + } + deque->len++; + deque->rightindex++; + deque->rightblock->data[deque->rightindex] = item; + TRIM(deque, deque_popleft); + } + Py_DECREF(it); + if (PyErr_Occurred()) + return NULL; + Py_RETURN_NONE; } PyDoc_STRVAR(extend_doc, @@ -348,50 +348,50 @@ static PyObject * deque_extendleft(dequeobject *deque, PyObject *iterable) { - PyObject *it, *item; + PyObject *it, *item; - /* Handle case where id(deque) == id(iterable) */ - if ((PyObject *)deque == iterable) { - PyObject *result; - PyObject *s = PySequence_List(iterable); - if (s == NULL) - return NULL; - result = deque_extendleft(deque, s); - Py_DECREF(s); - return result; - } - - it = PyObject_GetIter(iterable); - if (it == NULL) - return NULL; - - if (deque->maxlen == 0) - return consume_iterator(it); - - while ((item = PyIter_Next(it)) != NULL) { - deque->state++; - if (deque->leftindex == 0) { - block *b = newblock(NULL, deque->leftblock, - deque->len); - if (b == NULL) { - Py_DECREF(item); - Py_DECREF(it); - return NULL; - } - assert(deque->leftblock->leftlink == NULL); - deque->leftblock->leftlink = b; - deque->leftblock = b; - deque->leftindex = BLOCKLEN; - } - deque->len++; - deque->leftindex--; - deque->leftblock->data[deque->leftindex] = item; - TRIM(deque, deque_pop); - } - Py_DECREF(it); - if (PyErr_Occurred()) - return NULL; - Py_RETURN_NONE; + /* Handle case where id(deque) == id(iterable) */ + if ((PyObject *)deque == iterable) { + PyObject *result; + PyObject *s = PySequence_List(iterable); + if (s == NULL) + return NULL; + result = deque_extendleft(deque, s); + Py_DECREF(s); + return result; + } + + it = PyObject_GetIter(iterable); + if (it == NULL) + return NULL; + + if (deque->maxlen == 0) + return consume_iterator(it); + + while ((item = PyIter_Next(it)) != NULL) { + deque->state++; + if (deque->leftindex == 0) { + block *b = newblock(NULL, deque->leftblock, + deque->len); + if (b == NULL) { + Py_DECREF(item); + Py_DECREF(it); + return NULL; + } + assert(deque->leftblock->leftlink == NULL); + deque->leftblock->leftlink = b; + deque->leftblock = b; + deque->leftindex = BLOCKLEN; + } + deque->len++; + deque->leftindex--; + deque->leftblock->data[deque->leftindex] = item; + TRIM(deque, deque_pop); + } + Py_DECREF(it); + if (PyErr_Occurred()) + return NULL; + Py_RETURN_NONE; } PyDoc_STRVAR(extendleft_doc, @@ -400,63 +400,63 @@ static PyObject * deque_inplace_concat(dequeobject *deque, PyObject *other) { - PyObject *result; + PyObject *result; - result = deque_extend(deque, other); - if (result == NULL) - return result; - Py_DECREF(result); - Py_INCREF(deque); - return (PyObject *)deque; + result = deque_extend(deque, other); + if (result == NULL) + return result; + Py_DECREF(result); + Py_INCREF(deque); + return (PyObject *)deque; } static int _deque_rotate(dequeobject *deque, Py_ssize_t n) { - Py_ssize_t i, len=deque->len, halflen=(len+1)>>1; - PyObject *item, *rv; + Py_ssize_t i, len=deque->len, halflen=(len+1)>>1; + PyObject *item, *rv; + + if (len == 0) + return 0; + if (n > halflen || n < -halflen) { + n %= len; + if (n > halflen) + n -= len; + else if (n < -halflen) + n += len; + } - if (len == 0) - return 0; - if (n > halflen || n < -halflen) { - n %= len; - if (n > halflen) - n -= len; - else if (n < -halflen) - n += len; - } - - for (i=0 ; in ; i--) { - item = deque_popleft(deque, NULL); - assert (item != NULL); - rv = deque_append(deque, item); - Py_DECREF(item); - if (rv == NULL) - return -1; - Py_DECREF(rv); - } - return 0; + for (i=0 ; in ; i--) { + item = deque_popleft(deque, NULL); + assert (item != NULL); + rv = deque_append(deque, item); + Py_DECREF(item); + if (rv == NULL) + return -1; + Py_DECREF(rv); + } + return 0; } static PyObject * deque_rotate(dequeobject *deque, PyObject *args) { - Py_ssize_t n=1; + Py_ssize_t n=1; - if (!PyArg_ParseTuple(args, "|n:rotate", &n)) - return NULL; - if (_deque_rotate(deque, n) == 0) - Py_RETURN_NONE; - return NULL; + if (!PyArg_ParseTuple(args, "|n:rotate", &n)) + return NULL; + if (_deque_rotate(deque, n) == 0) + Py_RETURN_NONE; + return NULL; } PyDoc_STRVAR(rotate_doc, @@ -465,40 +465,40 @@ static PyObject * deque_reverse(dequeobject *deque, PyObject *unused) { - block *leftblock = deque->leftblock; - block *rightblock = deque->rightblock; - Py_ssize_t leftindex = deque->leftindex; - Py_ssize_t rightindex = deque->rightindex; - Py_ssize_t n = (deque->len)/2; - Py_ssize_t i; - PyObject *tmp; - - for (i=0 ; idata[leftindex]; - leftblock->data[leftindex] = rightblock->data[rightindex]; - rightblock->data[rightindex] = tmp; - - /* Advance left block/index pair */ - leftindex++; - if (leftindex == BLOCKLEN) { - assert (leftblock->rightlink != NULL); - leftblock = leftblock->rightlink; - leftindex = 0; - } - - /* Step backwards with the right block/index pair */ - rightindex--; - if (rightindex == -1) { - assert (rightblock->leftlink != NULL); - rightblock = rightblock->leftlink; - rightindex = BLOCKLEN - 1; - } - } - Py_RETURN_NONE; + block *leftblock = deque->leftblock; + block *rightblock = deque->rightblock; + Py_ssize_t leftindex = deque->leftindex; + Py_ssize_t rightindex = deque->rightindex; + Py_ssize_t n = (deque->len)/2; + Py_ssize_t i; + PyObject *tmp; + + for (i=0 ; idata[leftindex]; + leftblock->data[leftindex] = rightblock->data[rightindex]; + rightblock->data[rightindex] = tmp; + + /* Advance left block/index pair */ + leftindex++; + if (leftindex == BLOCKLEN) { + assert (leftblock->rightlink != NULL); + leftblock = leftblock->rightlink; + leftindex = 0; + } + + /* Step backwards with the right block/index pair */ + rightindex--; + if (rightindex == -1) { + assert (rightblock->leftlink != NULL); + rightblock = rightblock->leftlink; + rightindex = BLOCKLEN - 1; + } + } + Py_RETURN_NONE; } PyDoc_STRVAR(reverse_doc, @@ -507,38 +507,38 @@ static PyObject * deque_count(dequeobject *deque, PyObject *v) { - block *leftblock = deque->leftblock; - Py_ssize_t leftindex = deque->leftindex; - Py_ssize_t n = (deque->len); - Py_ssize_t i; - Py_ssize_t count = 0; - PyObject *item; - long start_state = deque->state; - int cmp; - - for (i=0 ; idata[leftindex]; - cmp = PyObject_RichCompareBool(item, v, Py_EQ); - if (cmp > 0) - count++; - else if (cmp < 0) - return NULL; - - if (start_state != deque->state) { - PyErr_SetString(PyExc_RuntimeError, - "deque mutated during iteration"); - return NULL; - } - - /* Advance left block/index pair */ - leftindex++; - if (leftindex == BLOCKLEN) { - assert (leftblock->rightlink != NULL); - leftblock = leftblock->rightlink; - leftindex = 0; - } - } - return PyLong_FromSsize_t(count); + block *leftblock = deque->leftblock; + Py_ssize_t leftindex = deque->leftindex; + Py_ssize_t n = (deque->len); + Py_ssize_t i; + Py_ssize_t count = 0; + PyObject *item; + long start_state = deque->state; + int cmp; + + for (i=0 ; idata[leftindex]; + cmp = PyObject_RichCompareBool(item, v, Py_EQ); + if (cmp > 0) + count++; + else if (cmp < 0) + return NULL; + + if (start_state != deque->state) { + PyErr_SetString(PyExc_RuntimeError, + "deque mutated during iteration"); + return NULL; + } + + /* Advance left block/index pair */ + leftindex++; + if (leftindex == BLOCKLEN) { + assert (leftblock->rightlink != NULL); + leftblock = leftblock->rightlink; + leftindex = 0; + } + } + return PyLong_FromSsize_t(count); } PyDoc_STRVAR(count_doc, @@ -547,39 +547,39 @@ static Py_ssize_t deque_len(dequeobject *deque) { - return deque->len; + return deque->len; } static PyObject * deque_remove(dequeobject *deque, PyObject *value) { - Py_ssize_t i, n=deque->len; + Py_ssize_t i, n=deque->len; - for (i=0 ; ileftblock->data[deque->leftindex]; - int cmp = PyObject_RichCompareBool(item, value, Py_EQ); - - if (deque->len != n) { - PyErr_SetString(PyExc_IndexError, - "deque mutated during remove()."); - return NULL; - } - if (cmp > 0) { - PyObject *tgt = deque_popleft(deque, NULL); - assert (tgt != NULL); - Py_DECREF(tgt); - if (_deque_rotate(deque, i) == -1) - return NULL; - Py_RETURN_NONE; - } - else if (cmp < 0) { - _deque_rotate(deque, i); - return NULL; - } - _deque_rotate(deque, -1); - } - PyErr_SetString(PyExc_ValueError, "deque.remove(x): x not in deque"); - return NULL; + for (i=0 ; ileftblock->data[deque->leftindex]; + int cmp = PyObject_RichCompareBool(item, value, Py_EQ); + + if (deque->len != n) { + PyErr_SetString(PyExc_IndexError, + "deque mutated during remove()."); + return NULL; + } + if (cmp > 0) { + PyObject *tgt = deque_popleft(deque, NULL); + assert (tgt != NULL); + Py_DECREF(tgt); + if (_deque_rotate(deque, i) == -1) + return NULL; + Py_RETURN_NONE; + } + else if (cmp < 0) { + _deque_rotate(deque, i); + return NULL; + } + _deque_rotate(deque, -1); + } + PyErr_SetString(PyExc_ValueError, "deque.remove(x): x not in deque"); + return NULL; } PyDoc_STRVAR(remove_doc, @@ -588,56 +588,56 @@ static int deque_clear(dequeobject *deque) { - PyObject *item; + PyObject *item; - while (deque->len) { - item = deque_pop(deque, NULL); - assert (item != NULL); - Py_DECREF(item); - } - assert(deque->leftblock == deque->rightblock && - deque->leftindex - 1 == deque->rightindex && - deque->len == 0); - return 0; + while (deque->len) { + item = deque_pop(deque, NULL); + assert (item != NULL); + Py_DECREF(item); + } + assert(deque->leftblock == deque->rightblock && + deque->leftindex - 1 == deque->rightindex && + deque->len == 0); + return 0; } static PyObject * deque_item(dequeobject *deque, Py_ssize_t i) { - block *b; - PyObject *item; - Py_ssize_t n, index=i; - - if (i < 0 || i >= deque->len) { - PyErr_SetString(PyExc_IndexError, - "deque index out of range"); - return NULL; - } - - if (i == 0) { - i = deque->leftindex; - b = deque->leftblock; - } else if (i == deque->len - 1) { - i = deque->rightindex; - b = deque->rightblock; - } else { - i += deque->leftindex; - n = i / BLOCKLEN; - i %= BLOCKLEN; - if (index < (deque->len >> 1)) { - b = deque->leftblock; - while (n--) - b = b->rightlink; - } else { - n = (deque->leftindex + deque->len - 1) / BLOCKLEN - n; - b = deque->rightblock; - while (n--) - b = b->leftlink; - } - } - item = b->data[i]; - Py_INCREF(item); - return item; + block *b; + PyObject *item; + Py_ssize_t n, index=i; + + if (i < 0 || i >= deque->len) { + PyErr_SetString(PyExc_IndexError, + "deque index out of range"); + return NULL; + } + + if (i == 0) { + i = deque->leftindex; + b = deque->leftblock; + } else if (i == deque->len - 1) { + i = deque->rightindex; + b = deque->rightblock; + } else { + i += deque->leftindex; + n = i / BLOCKLEN; + i %= BLOCKLEN; + if (index < (deque->len >> 1)) { + b = deque->leftblock; + while (n--) + b = b->rightlink; + } else { + n = (deque->leftindex + deque->len - 1) / BLOCKLEN - n; + b = deque->rightblock; + while (n--) + b = b->leftlink; + } + } + item = b->data[i]; + Py_INCREF(item); + return item; } /* delitem() implemented in terms of rotate for simplicity and reasonable @@ -650,62 +650,62 @@ static int deque_del_item(dequeobject *deque, Py_ssize_t i) { - PyObject *item; + PyObject *item; - assert (i >= 0 && i < deque->len); - if (_deque_rotate(deque, -i) == -1) - return -1; + assert (i >= 0 && i < deque->len); + if (_deque_rotate(deque, -i) == -1) + return -1; - item = deque_popleft(deque, NULL); - assert (item != NULL); - Py_DECREF(item); + item = deque_popleft(deque, NULL); + assert (item != NULL); + Py_DECREF(item); - return _deque_rotate(deque, i); + return _deque_rotate(deque, i); } static int deque_ass_item(dequeobject *deque, Py_ssize_t i, PyObject *v) { - PyObject *old_value; - block *b; - Py_ssize_t n, len=deque->len, halflen=(len+1)>>1, index=i; - - if (i < 0 || i >= len) { - PyErr_SetString(PyExc_IndexError, - "deque index out of range"); - return -1; - } - if (v == NULL) - return deque_del_item(deque, i); - - i += deque->leftindex; - n = i / BLOCKLEN; - i %= BLOCKLEN; - if (index <= halflen) { - b = deque->leftblock; - while (n--) - b = b->rightlink; - } else { - n = (deque->leftindex + len - 1) / BLOCKLEN - n; - b = deque->rightblock; - while (n--) - b = b->leftlink; - } - Py_INCREF(v); - old_value = b->data[i]; - b->data[i] = v; - Py_DECREF(old_value); - return 0; + PyObject *old_value; + block *b; + Py_ssize_t n, len=deque->len, halflen=(len+1)>>1, index=i; + + if (i < 0 || i >= len) { + PyErr_SetString(PyExc_IndexError, + "deque index out of range"); + return -1; + } + if (v == NULL) + return deque_del_item(deque, i); + + i += deque->leftindex; + n = i / BLOCKLEN; + i %= BLOCKLEN; + if (index <= halflen) { + b = deque->leftblock; + while (n--) + b = b->rightlink; + } else { + n = (deque->leftindex + len - 1) / BLOCKLEN - n; + b = deque->rightblock; + while (n--) + b = b->leftlink; + } + Py_INCREF(v); + old_value = b->data[i]; + b->data[i] = v; + Py_DECREF(old_value); + return 0; } static PyObject * deque_clearmethod(dequeobject *deque) { - int rv; + int rv; - rv = deque_clear(deque); - assert (rv != -1); - Py_RETURN_NONE; + rv = deque_clear(deque); + assert (rv != -1); + Py_RETURN_NONE; } PyDoc_STRVAR(clear_doc, "Remove all elements from the deque."); @@ -713,49 +713,49 @@ static void deque_dealloc(dequeobject *deque) { - PyObject_GC_UnTrack(deque); - if (deque->weakreflist != NULL) - PyObject_ClearWeakRefs((PyObject *) deque); - if (deque->leftblock != NULL) { - deque_clear(deque); - assert(deque->leftblock != NULL); - freeblock(deque->leftblock); - } - deque->leftblock = NULL; - deque->rightblock = NULL; - Py_TYPE(deque)->tp_free(deque); + PyObject_GC_UnTrack(deque); + if (deque->weakreflist != NULL) + PyObject_ClearWeakRefs((PyObject *) deque); + if (deque->leftblock != NULL) { + deque_clear(deque); + assert(deque->leftblock != NULL); + freeblock(deque->leftblock); + } + deque->leftblock = NULL; + deque->rightblock = NULL; + Py_TYPE(deque)->tp_free(deque); } static int deque_traverse(dequeobject *deque, visitproc visit, void *arg) { - block *b; - PyObject *item; - Py_ssize_t index; - Py_ssize_t indexlo = deque->leftindex; - - for (b = deque->leftblock; b != NULL; b = b->rightlink) { - const Py_ssize_t indexhi = b == deque->rightblock ? - deque->rightindex : - BLOCKLEN - 1; - - for (index = indexlo; index <= indexhi; ++index) { - item = b->data[index]; - Py_VISIT(item); - } - indexlo = 0; - } - return 0; + block *b; + PyObject *item; + Py_ssize_t index; + Py_ssize_t indexlo = deque->leftindex; + + for (b = deque->leftblock; b != NULL; b = b->rightlink) { + const Py_ssize_t indexhi = b == deque->rightblock ? + deque->rightindex : + BLOCKLEN - 1; + + for (index = indexlo; index <= indexhi; ++index) { + item = b->data[index]; + Py_VISIT(item); + } + indexlo = 0; + } + return 0; } static PyObject * deque_copy(PyObject *deque) { - if (((dequeobject *)deque)->maxlen == -1) - return PyObject_CallFunction((PyObject *)(Py_TYPE(deque)), "O", deque, NULL); - else - return PyObject_CallFunction((PyObject *)(Py_TYPE(deque)), "Oi", - deque, ((dequeobject *)deque)->maxlen, NULL); + if (((dequeobject *)deque)->maxlen == -1) + return PyObject_CallFunction((PyObject *)(Py_TYPE(deque)), "O", deque, NULL); + else + return PyObject_CallFunction((PyObject *)(Py_TYPE(deque)), "Oi", + deque, ((dequeobject *)deque)->maxlen, NULL); } PyDoc_STRVAR(copy_doc, "Return a shallow copy of a deque."); @@ -763,30 +763,30 @@ static PyObject * deque_reduce(dequeobject *deque) { - PyObject *dict, *result, *aslist; + PyObject *dict, *result, *aslist; - dict = PyObject_GetAttrString((PyObject *)deque, "__dict__"); - if (dict == NULL) - PyErr_Clear(); - aslist = PySequence_List((PyObject *)deque); - if (aslist == NULL) { - Py_XDECREF(dict); - return NULL; - } - if (dict == NULL) { - if (deque->maxlen == -1) - result = Py_BuildValue("O(O)", Py_TYPE(deque), aslist); - else - result = Py_BuildValue("O(On)", Py_TYPE(deque), aslist, deque->maxlen); - } else { - if (deque->maxlen == -1) - result = Py_BuildValue("O(OO)O", Py_TYPE(deque), aslist, Py_None, dict); - else - result = Py_BuildValue("O(On)O", Py_TYPE(deque), aslist, deque->maxlen, dict); - } - Py_XDECREF(dict); - Py_DECREF(aslist); - return result; + dict = PyObject_GetAttrString((PyObject *)deque, "__dict__"); + if (dict == NULL) + PyErr_Clear(); + aslist = PySequence_List((PyObject *)deque); + if (aslist == NULL) { + Py_XDECREF(dict); + return NULL; + } + if (dict == NULL) { + if (deque->maxlen == -1) + result = Py_BuildValue("O(O)", Py_TYPE(deque), aslist); + else + result = Py_BuildValue("O(On)", Py_TYPE(deque), aslist, deque->maxlen); + } else { + if (deque->maxlen == -1) + result = Py_BuildValue("O(OO)O", Py_TYPE(deque), aslist, Py_None, dict); + else + result = Py_BuildValue("O(On)O", Py_TYPE(deque), aslist, deque->maxlen, dict); + } + Py_XDECREF(dict); + Py_DECREF(aslist); + return result; } PyDoc_STRVAR(reduce_doc, "Return state information for pickling."); @@ -794,166 +794,166 @@ static PyObject * deque_repr(PyObject *deque) { - PyObject *aslist, *result; - int i; + PyObject *aslist, *result; + int i; + + i = Py_ReprEnter(deque); + if (i != 0) { + if (i < 0) + return NULL; + return PyUnicode_FromString("[...]"); + } - i = Py_ReprEnter(deque); - if (i != 0) { - if (i < 0) - return NULL; - return PyUnicode_FromString("[...]"); - } - - aslist = PySequence_List(deque); - if (aslist == NULL) { - Py_ReprLeave(deque); - return NULL; - } - if (((dequeobject *)deque)->maxlen != -1) - - result = PyUnicode_FromFormat("deque(%R, maxlen=%zd)", - aslist, ((dequeobject *)deque)->maxlen); - else - result = PyUnicode_FromFormat("deque(%R)", aslist); - Py_DECREF(aslist); - Py_ReprLeave(deque); - return result; + aslist = PySequence_List(deque); + if (aslist == NULL) { + Py_ReprLeave(deque); + return NULL; + } + if (((dequeobject *)deque)->maxlen != -1) + + result = PyUnicode_FromFormat("deque(%R, maxlen=%zd)", + aslist, ((dequeobject *)deque)->maxlen); + else + result = PyUnicode_FromFormat("deque(%R)", aslist); + Py_DECREF(aslist); + Py_ReprLeave(deque); + return result; } static PyObject * deque_richcompare(PyObject *v, PyObject *w, int op) { - PyObject *it1=NULL, *it2=NULL, *x, *y; - Py_ssize_t vs, ws; - int b, cmp=-1; - - if (!PyObject_TypeCheck(v, &deque_type) || - !PyObject_TypeCheck(w, &deque_type)) { - Py_INCREF(Py_NotImplemented); - return Py_NotImplemented; - } - - /* Shortcuts */ - vs = ((dequeobject *)v)->len; - ws = ((dequeobject *)w)->len; - if (op == Py_EQ) { - if (v == w) - Py_RETURN_TRUE; - if (vs != ws) - Py_RETURN_FALSE; - } - if (op == Py_NE) { - if (v == w) - Py_RETURN_FALSE; - if (vs != ws) - Py_RETURN_TRUE; - } - - /* Search for the first index where items are different */ - it1 = PyObject_GetIter(v); - if (it1 == NULL) - goto done; - it2 = PyObject_GetIter(w); - if (it2 == NULL) - goto done; - for (;;) { - x = PyIter_Next(it1); - if (x == NULL && PyErr_Occurred()) - goto done; - y = PyIter_Next(it2); - if (x == NULL || y == NULL) - break; - b = PyObject_RichCompareBool(x, y, Py_EQ); - if (b == 0) { - cmp = PyObject_RichCompareBool(x, y, op); - Py_DECREF(x); - Py_DECREF(y); - goto done; - } - Py_DECREF(x); - Py_DECREF(y); - if (b == -1) - goto done; - } - /* We reached the end of one deque or both */ - Py_XDECREF(x); - Py_XDECREF(y); - if (PyErr_Occurred()) - goto done; - switch (op) { - case Py_LT: cmp = y != NULL; break; /* if w was longer */ - case Py_LE: cmp = x == NULL; break; /* if v was not longer */ - case Py_EQ: cmp = x == y; break; /* if we reached the end of both */ - case Py_NE: cmp = x != y; break; /* if one deque continues */ - case Py_GT: cmp = x != NULL; break; /* if v was longer */ - case Py_GE: cmp = y == NULL; break; /* if w was not longer */ - } + PyObject *it1=NULL, *it2=NULL, *x, *y; + Py_ssize_t vs, ws; + int b, cmp=-1; + + if (!PyObject_TypeCheck(v, &deque_type) || + !PyObject_TypeCheck(w, &deque_type)) { + Py_INCREF(Py_NotImplemented); + return Py_NotImplemented; + } + + /* Shortcuts */ + vs = ((dequeobject *)v)->len; + ws = ((dequeobject *)w)->len; + if (op == Py_EQ) { + if (v == w) + Py_RETURN_TRUE; + if (vs != ws) + Py_RETURN_FALSE; + } + if (op == Py_NE) { + if (v == w) + Py_RETURN_FALSE; + if (vs != ws) + Py_RETURN_TRUE; + } + + /* Search for the first index where items are different */ + it1 = PyObject_GetIter(v); + if (it1 == NULL) + goto done; + it2 = PyObject_GetIter(w); + if (it2 == NULL) + goto done; + for (;;) { + x = PyIter_Next(it1); + if (x == NULL && PyErr_Occurred()) + goto done; + y = PyIter_Next(it2); + if (x == NULL || y == NULL) + break; + b = PyObject_RichCompareBool(x, y, Py_EQ); + if (b == 0) { + cmp = PyObject_RichCompareBool(x, y, op); + Py_DECREF(x); + Py_DECREF(y); + goto done; + } + Py_DECREF(x); + Py_DECREF(y); + if (b == -1) + goto done; + } + /* We reached the end of one deque or both */ + Py_XDECREF(x); + Py_XDECREF(y); + if (PyErr_Occurred()) + goto done; + switch (op) { + case Py_LT: cmp = y != NULL; break; /* if w was longer */ + case Py_LE: cmp = x == NULL; break; /* if v was not longer */ + case Py_EQ: cmp = x == y; break; /* if we reached the end of both */ + case Py_NE: cmp = x != y; break; /* if one deque continues */ + case Py_GT: cmp = x != NULL; break; /* if v was longer */ + case Py_GE: cmp = y == NULL; break; /* if w was not longer */ + } done: - Py_XDECREF(it1); - Py_XDECREF(it2); - if (cmp == 1) - Py_RETURN_TRUE; - if (cmp == 0) - Py_RETURN_FALSE; - return NULL; + Py_XDECREF(it1); + Py_XDECREF(it2); + if (cmp == 1) + Py_RETURN_TRUE; + if (cmp == 0) + Py_RETURN_FALSE; + return NULL; } static int deque_init(dequeobject *deque, PyObject *args, PyObject *kwdargs) { - PyObject *iterable = NULL; - PyObject *maxlenobj = NULL; - Py_ssize_t maxlen = -1; - char *kwlist[] = {"iterable", "maxlen", 0}; - - if (!PyArg_ParseTupleAndKeywords(args, kwdargs, "|OO:deque", kwlist, &iterable, &maxlenobj)) - return -1; - if (maxlenobj != NULL && maxlenobj != Py_None) { - maxlen = PyLong_AsSsize_t(maxlenobj); - if (maxlen == -1 && PyErr_Occurred()) - return -1; - if (maxlen < 0) { - PyErr_SetString(PyExc_ValueError, "maxlen must be non-negative"); - return -1; - } - } - deque->maxlen = maxlen; - deque_clear(deque); - if (iterable != NULL) { - PyObject *rv = deque_extend(deque, iterable); - if (rv == NULL) - return -1; - Py_DECREF(rv); - } - return 0; + PyObject *iterable = NULL; + PyObject *maxlenobj = NULL; + Py_ssize_t maxlen = -1; + char *kwlist[] = {"iterable", "maxlen", 0}; + + if (!PyArg_ParseTupleAndKeywords(args, kwdargs, "|OO:deque", kwlist, &iterable, &maxlenobj)) + return -1; + if (maxlenobj != NULL && maxlenobj != Py_None) { + maxlen = PyLong_AsSsize_t(maxlenobj); + if (maxlen == -1 && PyErr_Occurred()) + return -1; + if (maxlen < 0) { + PyErr_SetString(PyExc_ValueError, "maxlen must be non-negative"); + return -1; + } + } + deque->maxlen = maxlen; + deque_clear(deque); + if (iterable != NULL) { + PyObject *rv = deque_extend(deque, iterable); + if (rv == NULL) + return -1; + Py_DECREF(rv); + } + return 0; } static PyObject * deque_get_maxlen(dequeobject *deque) { - if (deque->maxlen == -1) - Py_RETURN_NONE; - return PyLong_FromSsize_t(deque->maxlen); + if (deque->maxlen == -1) + Py_RETURN_NONE; + return PyLong_FromSsize_t(deque->maxlen); } static PyGetSetDef deque_getset[] = { - {"maxlen", (getter)deque_get_maxlen, (setter)NULL, - "maximum size of a deque or None if unbounded"}, - {0} + {"maxlen", (getter)deque_get_maxlen, (setter)NULL, + "maximum size of a deque or None if unbounded"}, + {0} }; static PySequenceMethods deque_as_sequence = { - (lenfunc)deque_len, /* sq_length */ - 0, /* sq_concat */ - 0, /* sq_repeat */ - (ssizeargfunc)deque_item, /* sq_item */ - 0, /* sq_slice */ - (ssizeobjargproc)deque_ass_item, /* sq_ass_item */ - 0, /* sq_ass_slice */ - 0, /* sq_contains */ - (binaryfunc)deque_inplace_concat, /* sq_inplace_concat */ - 0, /* sq_inplace_repeat */ + (lenfunc)deque_len, /* sq_length */ + 0, /* sq_concat */ + 0, /* sq_repeat */ + (ssizeargfunc)deque_item, /* sq_item */ + 0, /* sq_slice */ + (ssizeobjargproc)deque_ass_item, /* sq_ass_item */ + 0, /* sq_ass_slice */ + 0, /* sq_contains */ + (binaryfunc)deque_inplace_concat, /* sq_inplace_concat */ + 0, /* sq_inplace_repeat */ }; @@ -962,38 +962,38 @@ static PyObject *deque_iter(dequeobject *deque); static PyObject *deque_reviter(dequeobject *deque); PyDoc_STRVAR(reversed_doc, - "D.__reversed__() -- return a reverse iterator over the deque"); + "D.__reversed__() -- return a reverse iterator over the deque"); static PyMethodDef deque_methods[] = { - {"append", (PyCFunction)deque_append, - METH_O, append_doc}, - {"appendleft", (PyCFunction)deque_appendleft, - METH_O, appendleft_doc}, - {"clear", (PyCFunction)deque_clearmethod, - METH_NOARGS, clear_doc}, - {"__copy__", (PyCFunction)deque_copy, - METH_NOARGS, copy_doc}, - {"count", (PyCFunction)deque_count, - METH_O, count_doc}, - {"extend", (PyCFunction)deque_extend, - METH_O, extend_doc}, - {"extendleft", (PyCFunction)deque_extendleft, - METH_O, extendleft_doc}, - {"pop", (PyCFunction)deque_pop, - METH_NOARGS, pop_doc}, - {"popleft", (PyCFunction)deque_popleft, - METH_NOARGS, popleft_doc}, - {"__reduce__", (PyCFunction)deque_reduce, - METH_NOARGS, reduce_doc}, - {"remove", (PyCFunction)deque_remove, - METH_O, remove_doc}, - {"__reversed__", (PyCFunction)deque_reviter, - METH_NOARGS, reversed_doc}, - {"reverse", (PyCFunction)deque_reverse, - METH_NOARGS, reverse_doc}, - {"rotate", (PyCFunction)deque_rotate, - METH_VARARGS, rotate_doc}, - {NULL, NULL} /* sentinel */ + {"append", (PyCFunction)deque_append, + METH_O, append_doc}, + {"appendleft", (PyCFunction)deque_appendleft, + METH_O, appendleft_doc}, + {"clear", (PyCFunction)deque_clearmethod, + METH_NOARGS, clear_doc}, + {"__copy__", (PyCFunction)deque_copy, + METH_NOARGS, copy_doc}, + {"count", (PyCFunction)deque_count, + METH_O, count_doc}, + {"extend", (PyCFunction)deque_extend, + METH_O, extend_doc}, + {"extendleft", (PyCFunction)deque_extendleft, + METH_O, extendleft_doc}, + {"pop", (PyCFunction)deque_pop, + METH_NOARGS, pop_doc}, + {"popleft", (PyCFunction)deque_popleft, + METH_NOARGS, popleft_doc}, + {"__reduce__", (PyCFunction)deque_reduce, + METH_NOARGS, reduce_doc}, + {"remove", (PyCFunction)deque_remove, + METH_O, remove_doc}, + {"__reversed__", (PyCFunction)deque_reviter, + METH_NOARGS, reversed_doc}, + {"reverse", (PyCFunction)deque_reverse, + METH_NOARGS, reverse_doc}, + {"rotate", (PyCFunction)deque_rotate, + METH_VARARGS, rotate_doc}, + {NULL, NULL} /* sentinel */ }; PyDoc_STRVAR(deque_doc, @@ -1002,58 +1002,58 @@ Build an ordered collection accessible from endpoints only."); static PyTypeObject deque_type = { - PyVarObject_HEAD_INIT(NULL, 0) - "collections.deque", /* tp_name */ - sizeof(dequeobject), /* tp_basicsize */ - 0, /* tp_itemsize */ - /* methods */ - (destructor)deque_dealloc, /* tp_dealloc */ - 0, /* tp_print */ - 0, /* tp_getattr */ - 0, /* tp_setattr */ - 0, /* tp_reserved */ - deque_repr, /* tp_repr */ - 0, /* tp_as_number */ - &deque_as_sequence, /* tp_as_sequence */ - 0, /* tp_as_mapping */ - (hashfunc)PyObject_HashNotImplemented, /* tp_hash */ - 0, /* tp_call */ - 0, /* tp_str */ - PyObject_GenericGetAttr, /* tp_getattro */ - 0, /* tp_setattro */ - 0, /* tp_as_buffer */ - Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC, - /* tp_flags */ - deque_doc, /* tp_doc */ - (traverseproc)deque_traverse, /* tp_traverse */ - (inquiry)deque_clear, /* tp_clear */ - (richcmpfunc)deque_richcompare, /* tp_richcompare */ - offsetof(dequeobject, weakreflist), /* tp_weaklistoffset*/ - (getiterfunc)deque_iter, /* tp_iter */ - 0, /* tp_iternext */ - deque_methods, /* tp_methods */ - 0, /* tp_members */ - deque_getset, /* tp_getset */ - 0, /* tp_base */ - 0, /* tp_dict */ - 0, /* tp_descr_get */ - 0, /* tp_descr_set */ - 0, /* tp_dictoffset */ - (initproc)deque_init, /* tp_init */ - PyType_GenericAlloc, /* tp_alloc */ - deque_new, /* tp_new */ - PyObject_GC_Del, /* tp_free */ + PyVarObject_HEAD_INIT(NULL, 0) + "collections.deque", /* tp_name */ + sizeof(dequeobject), /* tp_basicsize */ + 0, /* tp_itemsize */ + /* methods */ + (destructor)deque_dealloc, /* tp_dealloc */ + 0, /* tp_print */ + 0, /* tp_getattr */ + 0, /* tp_setattr */ + 0, /* tp_reserved */ + deque_repr, /* tp_repr */ + 0, /* tp_as_number */ + &deque_as_sequence, /* tp_as_sequence */ + 0, /* tp_as_mapping */ + (hashfunc)PyObject_HashNotImplemented, /* tp_hash */ + 0, /* tp_call */ + 0, /* tp_str */ + PyObject_GenericGetAttr, /* tp_getattro */ + 0, /* tp_setattro */ + 0, /* tp_as_buffer */ + Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC, + /* tp_flags */ + deque_doc, /* tp_doc */ + (traverseproc)deque_traverse, /* tp_traverse */ + (inquiry)deque_clear, /* tp_clear */ + (richcmpfunc)deque_richcompare, /* tp_richcompare */ + offsetof(dequeobject, weakreflist), /* tp_weaklistoffset*/ + (getiterfunc)deque_iter, /* tp_iter */ + 0, /* tp_iternext */ + deque_methods, /* tp_methods */ + 0, /* tp_members */ + deque_getset, /* tp_getset */ + 0, /* tp_base */ + 0, /* tp_dict */ + 0, /* tp_descr_get */ + 0, /* tp_descr_set */ + 0, /* tp_dictoffset */ + (initproc)deque_init, /* tp_init */ + PyType_GenericAlloc, /* tp_alloc */ + deque_new, /* tp_new */ + PyObject_GC_Del, /* tp_free */ }; /*********************** Deque Iterator **************************/ typedef struct { - PyObject_HEAD - Py_ssize_t index; - block *b; - dequeobject *deque; - long state; /* state when the iterator is created */ - Py_ssize_t counter; /* number of items remaining for iteration */ + PyObject_HEAD + Py_ssize_t index; + block *b; + dequeobject *deque; + long state; /* state when the iterator is created */ + Py_ssize_t counter; /* number of items remaining for iteration */ } dequeiterobject; static PyTypeObject dequeiter_type; @@ -1061,107 +1061,107 @@ static PyObject * deque_iter(dequeobject *deque) { - dequeiterobject *it; + dequeiterobject *it; - it = PyObject_GC_New(dequeiterobject, &dequeiter_type); - if (it == NULL) - return NULL; - it->b = deque->leftblock; - it->index = deque->leftindex; - Py_INCREF(deque); - it->deque = deque; - it->state = deque->state; - it->counter = deque->len; - PyObject_GC_Track(it); - return (PyObject *)it; + it = PyObject_GC_New(dequeiterobject, &dequeiter_type); + if (it == NULL) + return NULL; + it->b = deque->leftblock; + it->index = deque->leftindex; + Py_INCREF(deque); + it->deque = deque; + it->state = deque->state; + it->counter = deque->len; + PyObject_GC_Track(it); + return (PyObject *)it; } static int dequeiter_traverse(dequeiterobject *dio, visitproc visit, void *arg) { - Py_VISIT(dio->deque); - return 0; + Py_VISIT(dio->deque); + return 0; } static void dequeiter_dealloc(dequeiterobject *dio) { - Py_XDECREF(dio->deque); - PyObject_GC_Del(dio); + Py_XDECREF(dio->deque); + PyObject_GC_Del(dio); } static PyObject * dequeiter_next(dequeiterobject *it) { - PyObject *item; + PyObject *item; - if (it->deque->state != it->state) { - it->counter = 0; - PyErr_SetString(PyExc_RuntimeError, - "deque mutated during iteration"); - return NULL; - } - if (it->counter == 0) - return NULL; - assert (!(it->b == it->deque->rightblock && - it->index > it->deque->rightindex)); - - item = it->b->data[it->index]; - it->index++; - it->counter--; - if (it->index == BLOCKLEN && it->counter > 0) { - assert (it->b->rightlink != NULL); - it->b = it->b->rightlink; - it->index = 0; - } - Py_INCREF(item); - return item; + if (it->deque->state != it->state) { + it->counter = 0; + PyErr_SetString(PyExc_RuntimeError, + "deque mutated during iteration"); + return NULL; + } + if (it->counter == 0) + return NULL; + assert (!(it->b == it->deque->rightblock && + it->index > it->deque->rightindex)); + + item = it->b->data[it->index]; + it->index++; + it->counter--; + if (it->index == BLOCKLEN && it->counter > 0) { + assert (it->b->rightlink != NULL); + it->b = it->b->rightlink; + it->index = 0; + } + Py_INCREF(item); + return item; } static PyObject * dequeiter_len(dequeiterobject *it) { - return PyLong_FromLong(it->counter); + return PyLong_FromLong(it->counter); } PyDoc_STRVAR(length_hint_doc, "Private method returning an estimate of len(list(it))."); static PyMethodDef dequeiter_methods[] = { - {"__length_hint__", (PyCFunction)dequeiter_len, METH_NOARGS, length_hint_doc}, - {NULL, NULL} /* sentinel */ + {"__length_hint__", (PyCFunction)dequeiter_len, METH_NOARGS, length_hint_doc}, + {NULL, NULL} /* sentinel */ }; static PyTypeObject dequeiter_type = { - PyVarObject_HEAD_INIT(NULL, 0) - "deque_iterator", /* tp_name */ - sizeof(dequeiterobject), /* tp_basicsize */ - 0, /* tp_itemsize */ - /* methods */ - (destructor)dequeiter_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)dequeiter_traverse, /* tp_traverse */ - 0, /* tp_clear */ - 0, /* tp_richcompare */ - 0, /* tp_weaklistoffset */ - PyObject_SelfIter, /* tp_iter */ - (iternextfunc)dequeiter_next, /* tp_iternext */ - dequeiter_methods, /* tp_methods */ - 0, + PyVarObject_HEAD_INIT(NULL, 0) + "deque_iterator", /* tp_name */ + sizeof(dequeiterobject), /* tp_basicsize */ + 0, /* tp_itemsize */ + /* methods */ + (destructor)dequeiter_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)dequeiter_traverse, /* tp_traverse */ + 0, /* tp_clear */ + 0, /* tp_richcompare */ + 0, /* tp_weaklistoffset */ + PyObject_SelfIter, /* tp_iter */ + (iternextfunc)dequeiter_next, /* tp_iternext */ + dequeiter_methods, /* tp_methods */ + 0, }; /*********************** Deque Reverse Iterator **************************/ @@ -1171,87 +1171,87 @@ static PyObject * deque_reviter(dequeobject *deque) { - dequeiterobject *it; + dequeiterobject *it; - it = PyObject_GC_New(dequeiterobject, &dequereviter_type); - if (it == NULL) - return NULL; - it->b = deque->rightblock; - it->index = deque->rightindex; - Py_INCREF(deque); - it->deque = deque; - it->state = deque->state; - it->counter = deque->len; - PyObject_GC_Track(it); - return (PyObject *)it; + it = PyObject_GC_New(dequeiterobject, &dequereviter_type); + if (it == NULL) + return NULL; + it->b = deque->rightblock; + it->index = deque->rightindex; + Py_INCREF(deque); + it->deque = deque; + it->state = deque->state; + it->counter = deque->len; + PyObject_GC_Track(it); + return (PyObject *)it; } static PyObject * dequereviter_next(dequeiterobject *it) { - PyObject *item; - if (it->counter == 0) - return NULL; - - if (it->deque->state != it->state) { - it->counter = 0; - PyErr_SetString(PyExc_RuntimeError, - "deque mutated during iteration"); - return NULL; - } - assert (!(it->b == it->deque->leftblock && - it->index < it->deque->leftindex)); - - item = it->b->data[it->index]; - it->index--; - it->counter--; - if (it->index == -1 && it->counter > 0) { - assert (it->b->leftlink != NULL); - it->b = it->b->leftlink; - it->index = BLOCKLEN - 1; - } - Py_INCREF(item); - return item; + PyObject *item; + if (it->counter == 0) + return NULL; + + if (it->deque->state != it->state) { + it->counter = 0; + PyErr_SetString(PyExc_RuntimeError, + "deque mutated during iteration"); + return NULL; + } + assert (!(it->b == it->deque->leftblock && + it->index < it->deque->leftindex)); + + item = it->b->data[it->index]; + it->index--; + it->counter--; + if (it->index == -1 && it->counter > 0) { + assert (it->b->leftlink != NULL); + it->b = it->b->leftlink; + it->index = BLOCKLEN - 1; + } + Py_INCREF(item); + return item; } static PyTypeObject dequereviter_type = { - PyVarObject_HEAD_INIT(NULL, 0) - "deque_reverse_iterator", /* tp_name */ - sizeof(dequeiterobject), /* tp_basicsize */ - 0, /* tp_itemsize */ - /* methods */ - (destructor)dequeiter_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)dequeiter_traverse, /* tp_traverse */ - 0, /* tp_clear */ - 0, /* tp_richcompare */ - 0, /* tp_weaklistoffset */ - PyObject_SelfIter, /* tp_iter */ - (iternextfunc)dequereviter_next, /* tp_iternext */ - dequeiter_methods, /* tp_methods */ - 0, + PyVarObject_HEAD_INIT(NULL, 0) + "deque_reverse_iterator", /* tp_name */ + sizeof(dequeiterobject), /* tp_basicsize */ + 0, /* tp_itemsize */ + /* methods */ + (destructor)dequeiter_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)dequeiter_traverse, /* tp_traverse */ + 0, /* tp_clear */ + 0, /* tp_richcompare */ + 0, /* tp_weaklistoffset */ + PyObject_SelfIter, /* tp_iter */ + (iternextfunc)dequereviter_next, /* tp_iternext */ + dequeiter_methods, /* tp_methods */ + 0, }; /* defaultdict type *********************************************************/ typedef struct { - PyDictObject dict; - PyObject *default_factory; + PyDictObject dict; + PyObject *default_factory; } defdictobject; static PyTypeObject defdict_type; /* Forward */ @@ -1266,25 +1266,25 @@ static PyObject * defdict_missing(defdictobject *dd, PyObject *key) { - PyObject *factory = dd->default_factory; - PyObject *value; - if (factory == NULL || factory == Py_None) { - /* XXX Call dict.__missing__(key) */ - PyObject *tup; - tup = PyTuple_Pack(1, key); - if (!tup) return NULL; - PyErr_SetObject(PyExc_KeyError, tup); - Py_DECREF(tup); - return NULL; - } - value = PyEval_CallObject(factory, NULL); - if (value == NULL) - return value; - if (PyObject_SetItem((PyObject *)dd, key, value) < 0) { - Py_DECREF(value); - return NULL; - } - return value; + PyObject *factory = dd->default_factory; + PyObject *value; + if (factory == NULL || factory == Py_None) { + /* XXX Call dict.__missing__(key) */ + PyObject *tup; + tup = PyTuple_Pack(1, key); + if (!tup) return NULL; + PyErr_SetObject(PyExc_KeyError, tup); + Py_DECREF(tup); + return NULL; + } + value = PyEval_CallObject(factory, NULL); + if (value == NULL) + return value; + if (PyObject_SetItem((PyObject *)dd, key, value) < 0) { + Py_DECREF(value); + return NULL; + } + return value; } PyDoc_STRVAR(defdict_copy_doc, "D.copy() -> a shallow copy of D."); @@ -1292,175 +1292,175 @@ static PyObject * defdict_copy(defdictobject *dd) { - /* This calls the object's class. That only works for subclasses - whose class constructor has the same signature. Subclasses that - define a different constructor signature must override copy(). - */ - - if (dd->default_factory == NULL) - return PyObject_CallFunctionObjArgs((PyObject*)Py_TYPE(dd), Py_None, dd, NULL); - return PyObject_CallFunctionObjArgs((PyObject*)Py_TYPE(dd), - dd->default_factory, dd, NULL); + /* This calls the object's class. That only works for subclasses + whose class constructor has the same signature. Subclasses that + define a different constructor signature must override copy(). + */ + + if (dd->default_factory == NULL) + return PyObject_CallFunctionObjArgs((PyObject*)Py_TYPE(dd), Py_None, dd, NULL); + return PyObject_CallFunctionObjArgs((PyObject*)Py_TYPE(dd), + dd->default_factory, dd, NULL); } static PyObject * defdict_reduce(defdictobject *dd) { - /* __reduce__ must return a 5-tuple as follows: + /* __reduce__ must return a 5-tuple as follows: - - factory function - - tuple of args for the factory function - - additional state (here None) - - sequence iterator (here None) - - dictionary iterator (yielding successive (key, value) pairs - - This API is used by pickle.py and copy.py. - - For this to be useful with pickle.py, the default_factory - must be picklable; e.g., None, a built-in, or a global - function in a module or package. - - Both shallow and deep copying are supported, but for deep - copying, the default_factory must be deep-copyable; e.g. None, - or a built-in (functions are not copyable at this time). - - This only works for subclasses as long as their constructor - signature is compatible; the first argument must be the - optional default_factory, defaulting to None. - */ - PyObject *args; - PyObject *items; - PyObject *iter; - PyObject *result; - if (dd->default_factory == NULL || dd->default_factory == Py_None) - args = PyTuple_New(0); - else - args = PyTuple_Pack(1, dd->default_factory); - if (args == NULL) - return NULL; - items = PyObject_CallMethod((PyObject *)dd, "items", "()"); - if (items == NULL) { - Py_DECREF(args); - return NULL; - } - iter = PyObject_GetIter(items); - if (iter == NULL) { - Py_DECREF(items); - Py_DECREF(args); - return NULL; - } - result = PyTuple_Pack(5, Py_TYPE(dd), args, - Py_None, Py_None, iter); - Py_DECREF(iter); - Py_DECREF(items); - Py_DECREF(args); - return result; + - factory function + - tuple of args for the factory function + - additional state (here None) + - sequence iterator (here None) + - dictionary iterator (yielding successive (key, value) pairs + + This API is used by pickle.py and copy.py. + + For this to be useful with pickle.py, the default_factory + must be picklable; e.g., None, a built-in, or a global + function in a module or package. + + Both shallow and deep copying are supported, but for deep + copying, the default_factory must be deep-copyable; e.g. None, + or a built-in (functions are not copyable at this time). + + This only works for subclasses as long as their constructor + signature is compatible; the first argument must be the + optional default_factory, defaulting to None. + */ + PyObject *args; + PyObject *items; + PyObject *iter; + PyObject *result; + if (dd->default_factory == NULL || dd->default_factory == Py_None) + args = PyTuple_New(0); + else + args = PyTuple_Pack(1, dd->default_factory); + if (args == NULL) + return NULL; + items = PyObject_CallMethod((PyObject *)dd, "items", "()"); + if (items == NULL) { + Py_DECREF(args); + return NULL; + } + iter = PyObject_GetIter(items); + if (iter == NULL) { + Py_DECREF(items); + Py_DECREF(args); + return NULL; + } + result = PyTuple_Pack(5, Py_TYPE(dd), args, + Py_None, Py_None, iter); + Py_DECREF(iter); + Py_DECREF(items); + Py_DECREF(args); + return result; } static PyMethodDef defdict_methods[] = { - {"__missing__", (PyCFunction)defdict_missing, METH_O, - defdict_missing_doc}, - {"copy", (PyCFunction)defdict_copy, METH_NOARGS, - defdict_copy_doc}, - {"__copy__", (PyCFunction)defdict_copy, METH_NOARGS, - defdict_copy_doc}, - {"__reduce__", (PyCFunction)defdict_reduce, METH_NOARGS, - reduce_doc}, - {NULL} + {"__missing__", (PyCFunction)defdict_missing, METH_O, + defdict_missing_doc}, + {"copy", (PyCFunction)defdict_copy, METH_NOARGS, + defdict_copy_doc}, + {"__copy__", (PyCFunction)defdict_copy, METH_NOARGS, + defdict_copy_doc}, + {"__reduce__", (PyCFunction)defdict_reduce, METH_NOARGS, + reduce_doc}, + {NULL} }; static PyMemberDef defdict_members[] = { - {"default_factory", T_OBJECT, - offsetof(defdictobject, default_factory), 0, - PyDoc_STR("Factory for default value called by __missing__().")}, - {NULL} + {"default_factory", T_OBJECT, + offsetof(defdictobject, default_factory), 0, + PyDoc_STR("Factory for default value called by __missing__().")}, + {NULL} }; static void defdict_dealloc(defdictobject *dd) { - Py_CLEAR(dd->default_factory); - PyDict_Type.tp_dealloc((PyObject *)dd); + Py_CLEAR(dd->default_factory); + PyDict_Type.tp_dealloc((PyObject *)dd); } static PyObject * defdict_repr(defdictobject *dd) { - PyObject *baserepr; - PyObject *defrepr; - PyObject *result; - baserepr = PyDict_Type.tp_repr((PyObject *)dd); - if (baserepr == NULL) - return NULL; - if (dd->default_factory == NULL) - defrepr = PyUnicode_FromString("None"); - else - { - int status = Py_ReprEnter(dd->default_factory); - if (status != 0) { - if (status < 0) - return NULL; - defrepr = PyUnicode_FromString("..."); - } - else - defrepr = PyObject_Repr(dd->default_factory); - Py_ReprLeave(dd->default_factory); - } - if (defrepr == NULL) { - Py_DECREF(baserepr); - return NULL; - } - result = PyUnicode_FromFormat("defaultdict(%U, %U)", - defrepr, baserepr); - Py_DECREF(defrepr); - Py_DECREF(baserepr); - return result; + PyObject *baserepr; + PyObject *defrepr; + PyObject *result; + baserepr = PyDict_Type.tp_repr((PyObject *)dd); + if (baserepr == NULL) + return NULL; + if (dd->default_factory == NULL) + defrepr = PyUnicode_FromString("None"); + else + { + int status = Py_ReprEnter(dd->default_factory); + if (status != 0) { + if (status < 0) + return NULL; + defrepr = PyUnicode_FromString("..."); + } + else + defrepr = PyObject_Repr(dd->default_factory); + Py_ReprLeave(dd->default_factory); + } + if (defrepr == NULL) { + Py_DECREF(baserepr); + return NULL; + } + result = PyUnicode_FromFormat("defaultdict(%U, %U)", + defrepr, baserepr); + Py_DECREF(defrepr); + Py_DECREF(baserepr); + return result; } static int defdict_traverse(PyObject *self, visitproc visit, void *arg) { - Py_VISIT(((defdictobject *)self)->default_factory); - return PyDict_Type.tp_traverse(self, visit, arg); + Py_VISIT(((defdictobject *)self)->default_factory); + return PyDict_Type.tp_traverse(self, visit, arg); } static int defdict_tp_clear(defdictobject *dd) { - Py_CLEAR(dd->default_factory); - return PyDict_Type.tp_clear((PyObject *)dd); + Py_CLEAR(dd->default_factory); + return PyDict_Type.tp_clear((PyObject *)dd); } static int defdict_init(PyObject *self, PyObject *args, PyObject *kwds) { - defdictobject *dd = (defdictobject *)self; - PyObject *olddefault = dd->default_factory; - PyObject *newdefault = NULL; - PyObject *newargs; - int result; - if (args == NULL || !PyTuple_Check(args)) - newargs = PyTuple_New(0); - else { - Py_ssize_t n = PyTuple_GET_SIZE(args); - if (n > 0) { - newdefault = PyTuple_GET_ITEM(args, 0); - if (!PyCallable_Check(newdefault) && newdefault != Py_None) { - PyErr_SetString(PyExc_TypeError, - "first argument must be callable"); - return -1; - } - } - newargs = PySequence_GetSlice(args, 1, n); - } - if (newargs == NULL) - return -1; - Py_XINCREF(newdefault); - dd->default_factory = newdefault; - result = PyDict_Type.tp_init(self, newargs, kwds); - Py_DECREF(newargs); - Py_XDECREF(olddefault); - return result; + defdictobject *dd = (defdictobject *)self; + PyObject *olddefault = dd->default_factory; + PyObject *newdefault = NULL; + PyObject *newargs; + int result; + if (args == NULL || !PyTuple_Check(args)) + newargs = PyTuple_New(0); + else { + Py_ssize_t n = PyTuple_GET_SIZE(args); + if (n > 0) { + newdefault = PyTuple_GET_ITEM(args, 0); + if (!PyCallable_Check(newdefault) && newdefault != Py_None) { + PyErr_SetString(PyExc_TypeError, + "first argument must be callable"); + return -1; + } + } + newargs = PySequence_GetSlice(args, 1, n); + } + if (newargs == NULL) + return -1; + Py_XINCREF(newdefault); + dd->default_factory = newdefault; + result = PyDict_Type.tp_init(self, newargs, kwds); + Py_DECREF(newargs); + Py_XDECREF(olddefault); + return result; } PyDoc_STRVAR(defdict_doc, @@ -1475,47 +1475,47 @@ #define DEFERRED_ADDRESS(ADDR) 0 static PyTypeObject defdict_type = { - PyVarObject_HEAD_INIT(DEFERRED_ADDRESS(&PyType_Type), 0) - "collections.defaultdict", /* tp_name */ - sizeof(defdictobject), /* tp_basicsize */ - 0, /* tp_itemsize */ - /* methods */ - (destructor)defdict_dealloc, /* tp_dealloc */ - 0, /* tp_print */ - 0, /* tp_getattr */ - 0, /* tp_setattr */ - 0, /* tp_reserved */ - (reprfunc)defdict_repr, /* 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_BASETYPE | Py_TPFLAGS_HAVE_GC, - /* tp_flags */ - defdict_doc, /* tp_doc */ - defdict_traverse, /* tp_traverse */ - (inquiry)defdict_tp_clear, /* tp_clear */ - 0, /* tp_richcompare */ - 0, /* tp_weaklistoffset*/ - 0, /* tp_iter */ - 0, /* tp_iternext */ - defdict_methods, /* tp_methods */ - defdict_members, /* tp_members */ - 0, /* tp_getset */ - DEFERRED_ADDRESS(&PyDict_Type), /* tp_base */ - 0, /* tp_dict */ - 0, /* tp_descr_get */ - 0, /* tp_descr_set */ - 0, /* tp_dictoffset */ - defdict_init, /* tp_init */ - PyType_GenericAlloc, /* tp_alloc */ - 0, /* tp_new */ - PyObject_GC_Del, /* tp_free */ + PyVarObject_HEAD_INIT(DEFERRED_ADDRESS(&PyType_Type), 0) + "collections.defaultdict", /* tp_name */ + sizeof(defdictobject), /* tp_basicsize */ + 0, /* tp_itemsize */ + /* methods */ + (destructor)defdict_dealloc, /* tp_dealloc */ + 0, /* tp_print */ + 0, /* tp_getattr */ + 0, /* tp_setattr */ + 0, /* tp_reserved */ + (reprfunc)defdict_repr, /* 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_BASETYPE | Py_TPFLAGS_HAVE_GC, + /* tp_flags */ + defdict_doc, /* tp_doc */ + defdict_traverse, /* tp_traverse */ + (inquiry)defdict_tp_clear, /* tp_clear */ + 0, /* tp_richcompare */ + 0, /* tp_weaklistoffset*/ + 0, /* tp_iter */ + 0, /* tp_iternext */ + defdict_methods, /* tp_methods */ + defdict_members, /* tp_members */ + 0, /* tp_getset */ + DEFERRED_ADDRESS(&PyDict_Type), /* tp_base */ + 0, /* tp_dict */ + 0, /* tp_descr_get */ + 0, /* tp_descr_set */ + 0, /* tp_dictoffset */ + defdict_init, /* tp_init */ + PyType_GenericAlloc, /* tp_alloc */ + 0, /* tp_new */ + PyObject_GC_Del, /* tp_free */ }; /* module level code ********************************************************/ @@ -1528,42 +1528,42 @@ static struct PyModuleDef _collectionsmodule = { - PyModuleDef_HEAD_INIT, - "_collections", - module_doc, - -1, - NULL, - NULL, - NULL, - NULL, - NULL + PyModuleDef_HEAD_INIT, + "_collections", + module_doc, + -1, + NULL, + NULL, + NULL, + NULL, + NULL }; PyMODINIT_FUNC PyInit__collections(void) { - PyObject *m; + PyObject *m; - m = PyModule_Create(&_collectionsmodule); - if (m == NULL) - return NULL; - - if (PyType_Ready(&deque_type) < 0) - return NULL; - Py_INCREF(&deque_type); - PyModule_AddObject(m, "deque", (PyObject *)&deque_type); - - defdict_type.tp_base = &PyDict_Type; - if (PyType_Ready(&defdict_type) < 0) - return NULL; - Py_INCREF(&defdict_type); - PyModule_AddObject(m, "defaultdict", (PyObject *)&defdict_type); + m = PyModule_Create(&_collectionsmodule); + if (m == NULL) + return NULL; + + if (PyType_Ready(&deque_type) < 0) + return NULL; + Py_INCREF(&deque_type); + PyModule_AddObject(m, "deque", (PyObject *)&deque_type); + + defdict_type.tp_base = &PyDict_Type; + if (PyType_Ready(&defdict_type) < 0) + return NULL; + Py_INCREF(&defdict_type); + PyModule_AddObject(m, "defaultdict", (PyObject *)&defdict_type); - if (PyType_Ready(&dequeiter_type) < 0) - return NULL; + if (PyType_Ready(&dequeiter_type) < 0) + return NULL; - if (PyType_Ready(&dequereviter_type) < 0) - return NULL; + if (PyType_Ready(&dequereviter_type) < 0) + return NULL; - return m; + return m; } Modified: python/branches/py3k/Modules/_csv.c ============================================================================== --- python/branches/py3k/Modules/_csv.c (original) +++ python/branches/py3k/Modules/_csv.c Sun May 9 17:52:27 2010 @@ -18,65 +18,65 @@ #include "structmember.h" #define IS_BASESTRING(o) \ - PyUnicode_Check(o) + PyUnicode_Check(o) -static PyObject *error_obj; /* CSV exception */ +static PyObject *error_obj; /* CSV exception */ static PyObject *dialects; /* Dialect registry */ -static long field_limit = 128 * 1024; /* max parsed field size */ +static long field_limit = 128 * 1024; /* max parsed field size */ typedef enum { - START_RECORD, START_FIELD, ESCAPED_CHAR, IN_FIELD, - IN_QUOTED_FIELD, ESCAPE_IN_QUOTED_FIELD, QUOTE_IN_QUOTED_FIELD, - EAT_CRNL + START_RECORD, START_FIELD, ESCAPED_CHAR, IN_FIELD, + IN_QUOTED_FIELD, ESCAPE_IN_QUOTED_FIELD, QUOTE_IN_QUOTED_FIELD, + EAT_CRNL } ParserState; typedef enum { - QUOTE_MINIMAL, QUOTE_ALL, QUOTE_NONNUMERIC, QUOTE_NONE + QUOTE_MINIMAL, QUOTE_ALL, QUOTE_NONNUMERIC, QUOTE_NONE } QuoteStyle; typedef struct { - QuoteStyle style; - char *name; + QuoteStyle style; + char *name; } StyleDesc; static StyleDesc quote_styles[] = { - { QUOTE_MINIMAL, "QUOTE_MINIMAL" }, - { QUOTE_ALL, "QUOTE_ALL" }, - { QUOTE_NONNUMERIC, "QUOTE_NONNUMERIC" }, - { QUOTE_NONE, "QUOTE_NONE" }, - { 0 } + { QUOTE_MINIMAL, "QUOTE_MINIMAL" }, + { QUOTE_ALL, "QUOTE_ALL" }, + { QUOTE_NONNUMERIC, "QUOTE_NONNUMERIC" }, + { QUOTE_NONE, "QUOTE_NONE" }, + { 0 } }; typedef struct { - PyObject_HEAD + PyObject_HEAD - int doublequote; /* is " represented by ""? */ - Py_UNICODE delimiter; /* field separator */ - Py_UNICODE quotechar; /* quote character */ - Py_UNICODE escapechar; /* escape character */ - int skipinitialspace; /* ignore spaces following delimiter? */ - PyObject *lineterminator; /* string to write between records */ - int quoting; /* style of quoting to write */ + int doublequote; /* is " represented by ""? */ + Py_UNICODE delimiter; /* field separator */ + Py_UNICODE quotechar; /* quote character */ + Py_UNICODE escapechar; /* escape character */ + int skipinitialspace; /* ignore spaces following delimiter? */ + PyObject *lineterminator; /* string to write between records */ + int quoting; /* style of quoting to write */ - int strict; /* raise exception on bad CSV */ + int strict; /* raise exception on bad CSV */ } DialectObj; static PyTypeObject Dialect_Type; typedef struct { - PyObject_HEAD + PyObject_HEAD - PyObject *input_iter; /* iterate over this for input lines */ + PyObject *input_iter; /* iterate over this for input lines */ - DialectObj *dialect; /* parsing dialect */ + DialectObj *dialect; /* parsing dialect */ - PyObject *fields; /* field list for current record */ - ParserState state; /* current CSV parse state */ - Py_UNICODE *field; /* build current field in here */ - int field_size; /* size of allocated buffer */ - Py_ssize_t field_len; /* length of current field */ - int numeric_field; /* treat field as numeric */ - unsigned long line_num; /* Source-file line number */ + PyObject *fields; /* field list for current record */ + ParserState state; /* current CSV parse state */ + Py_UNICODE *field; /* build current field in here */ + int field_size; /* size of allocated buffer */ + Py_ssize_t field_len; /* length of current field */ + int numeric_field; /* treat field as numeric */ + unsigned long line_num; /* Source-file line number */ } ReaderObj; static PyTypeObject Reader_Type; @@ -84,16 +84,16 @@ #define ReaderObject_Check(v) (Py_TYPE(v) == &Reader_Type) typedef struct { - PyObject_HEAD + PyObject_HEAD - PyObject *writeline; /* write output lines to this file */ + PyObject *writeline; /* write output lines to this file */ - DialectObj *dialect; /* parsing dialect */ + DialectObj *dialect; /* parsing dialect */ - Py_UNICODE *rec; /* buffer for parser.join */ - int rec_size; /* size of allocated record */ - Py_ssize_t rec_len; /* length of record */ - int num_fields; /* number of fields in record */ + Py_UNICODE *rec; /* buffer for parser.join */ + int rec_size; /* size of allocated record */ + Py_ssize_t rec_len; /* length of record */ + int num_fields; /* number of fields in record */ } WriterObj; static PyTypeObject Writer_Type; @@ -105,375 +105,375 @@ static PyObject * get_dialect_from_registry(PyObject * name_obj) { - PyObject *dialect_obj; + PyObject *dialect_obj; - dialect_obj = PyDict_GetItem(dialects, name_obj); - if (dialect_obj == NULL) { - if (!PyErr_Occurred()) - PyErr_Format(error_obj, "unknown dialect"); - } - else - Py_INCREF(dialect_obj); - return dialect_obj; + dialect_obj = PyDict_GetItem(dialects, name_obj); + if (dialect_obj == NULL) { + if (!PyErr_Occurred()) + PyErr_Format(error_obj, "unknown dialect"); + } + else + Py_INCREF(dialect_obj); + return dialect_obj; } static PyObject * get_string(PyObject *str) { - Py_XINCREF(str); - return str; + Py_XINCREF(str); + return str; } static PyObject * get_nullchar_as_None(Py_UNICODE c) { - if (c == '\0') { - Py_INCREF(Py_None); - return Py_None; - } - else - return PyUnicode_FromUnicode((Py_UNICODE *)&c, 1); + if (c == '\0') { + Py_INCREF(Py_None); + return Py_None; + } + else + return PyUnicode_FromUnicode((Py_UNICODE *)&c, 1); } static PyObject * Dialect_get_lineterminator(DialectObj *self) { - return get_string(self->lineterminator); + return get_string(self->lineterminator); } static PyObject * Dialect_get_delimiter(DialectObj *self) { - return get_nullchar_as_None(self->delimiter); + return get_nullchar_as_None(self->delimiter); } static PyObject * Dialect_get_escapechar(DialectObj *self) { - return get_nullchar_as_None(self->escapechar); + return get_nullchar_as_None(self->escapechar); } static PyObject * Dialect_get_quotechar(DialectObj *self) { - return get_nullchar_as_None(self->quotechar); + return get_nullchar_as_None(self->quotechar); } static PyObject * Dialect_get_quoting(DialectObj *self) { - return PyLong_FromLong(self->quoting); + return PyLong_FromLong(self->quoting); } static int _set_bool(const char *name, int *target, PyObject *src, int dflt) { - if (src == NULL) - *target = dflt; - else - *target = PyObject_IsTrue(src); - return 0; + if (src == NULL) + *target = dflt; + else + *target = PyObject_IsTrue(src); + return 0; } static int _set_int(const char *name, int *target, PyObject *src, int dflt) { - if (src == NULL) - *target = dflt; - else { - long value; - if (!PyLong_CheckExact(src)) { - PyErr_Format(PyExc_TypeError, - "\"%s\" must be an integer", name); - return -1; - } - value = PyLong_AsLong(src); - if (value == -1 && PyErr_Occurred()) - return -1; + if (src == NULL) + *target = dflt; + else { + long value; + if (!PyLong_CheckExact(src)) { + PyErr_Format(PyExc_TypeError, + "\"%s\" must be an integer", name); + return -1; + } + value = PyLong_AsLong(src); + if (value == -1 && PyErr_Occurred()) + return -1; #if SIZEOF_LONG > SIZEOF_INT - if (value > INT_MAX || value < INT_MIN) { - PyErr_Format(PyExc_ValueError, - "integer out of range for \"%s\"", name); - return -1; - } + if (value > INT_MAX || value < INT_MIN) { + PyErr_Format(PyExc_ValueError, + "integer out of range for \"%s\"", name); + return -1; + } #endif - *target = (int)value; - } - return 0; + *target = (int)value; + } + return 0; } static int _set_char(const char *name, Py_UNICODE *target, PyObject *src, Py_UNICODE dflt) { - if (src == NULL) - *target = dflt; - else { - *target = '\0'; - if (src != Py_None) { - Py_UNICODE *buf; - Py_ssize_t len; - buf = PyUnicode_AsUnicode(src); - len = PyUnicode_GetSize(src); - if (buf == NULL || len > 1) { - PyErr_Format(PyExc_TypeError, - "\"%s\" must be an 1-character string", - name); - return -1; - } - if (len > 0) - *target = buf[0]; - } - } - return 0; + if (src == NULL) + *target = dflt; + else { + *target = '\0'; + if (src != Py_None) { + Py_UNICODE *buf; + Py_ssize_t len; + buf = PyUnicode_AsUnicode(src); + len = PyUnicode_GetSize(src); + if (buf == NULL || len > 1) { + PyErr_Format(PyExc_TypeError, + "\"%s\" must be an 1-character string", + name); + return -1; + } + if (len > 0) + *target = buf[0]; + } + } + return 0; } static int _set_str(const char *name, PyObject **target, PyObject *src, const char *dflt) { - if (src == NULL) - *target = PyUnicode_DecodeASCII(dflt, strlen(dflt), NULL); - else { - if (src == Py_None) - *target = NULL; - else if (!IS_BASESTRING(src)) { - PyErr_Format(PyExc_TypeError, - "\"%s\" must be a string", name); - return -1; - } - else { - Py_XDECREF(*target); - Py_INCREF(src); - *target = src; - } - } - return 0; + if (src == NULL) + *target = PyUnicode_DecodeASCII(dflt, strlen(dflt), NULL); + else { + if (src == Py_None) + *target = NULL; + else if (!IS_BASESTRING(src)) { + PyErr_Format(PyExc_TypeError, + "\"%s\" must be a string", name); + return -1; + } + else { + Py_XDECREF(*target); + Py_INCREF(src); + *target = src; + } + } + return 0; } static int dialect_check_quoting(int quoting) { - StyleDesc *qs = quote_styles; + StyleDesc *qs = quote_styles; - for (qs = quote_styles; qs->name; qs++) { - if (qs->style == quoting) - return 0; - } - PyErr_Format(PyExc_TypeError, "bad \"quoting\" value"); - return -1; + for (qs = quote_styles; qs->name; qs++) { + if (qs->style == quoting) + return 0; + } + PyErr_Format(PyExc_TypeError, "bad \"quoting\" value"); + return -1; } #define D_OFF(x) offsetof(DialectObj, x) static struct PyMemberDef Dialect_memberlist[] = { - { "skipinitialspace", T_INT, D_OFF(skipinitialspace), READONLY }, - { "doublequote", T_INT, D_OFF(doublequote), READONLY }, - { "strict", T_INT, D_OFF(strict), READONLY }, - { NULL } + { "skipinitialspace", T_INT, D_OFF(skipinitialspace), READONLY }, + { "doublequote", T_INT, D_OFF(doublequote), READONLY }, + { "strict", T_INT, D_OFF(strict), READONLY }, + { NULL } }; static PyGetSetDef Dialect_getsetlist[] = { - { "delimiter", (getter)Dialect_get_delimiter}, - { "escapechar", (getter)Dialect_get_escapechar}, - { "lineterminator", (getter)Dialect_get_lineterminator}, - { "quotechar", (getter)Dialect_get_quotechar}, - { "quoting", (getter)Dialect_get_quoting}, - {NULL}, + { "delimiter", (getter)Dialect_get_delimiter}, + { "escapechar", (getter)Dialect_get_escapechar}, + { "lineterminator", (getter)Dialect_get_lineterminator}, + { "quotechar", (getter)Dialect_get_quotechar}, + { "quoting", (getter)Dialect_get_quoting}, + {NULL}, }; static void Dialect_dealloc(DialectObj *self) { - Py_XDECREF(self->lineterminator); - Py_TYPE(self)->tp_free((PyObject *)self); + Py_XDECREF(self->lineterminator); + Py_TYPE(self)->tp_free((PyObject *)self); } static char *dialect_kws[] = { - "dialect", - "delimiter", - "doublequote", - "escapechar", - "lineterminator", - "quotechar", - "quoting", - "skipinitialspace", - "strict", - NULL + "dialect", + "delimiter", + "doublequote", + "escapechar", + "lineterminator", + "quotechar", + "quoting", + "skipinitialspace", + "strict", + NULL }; static PyObject * dialect_new(PyTypeObject *type, PyObject *args, PyObject *kwargs) { - DialectObj *self; - PyObject *ret = NULL; - PyObject *dialect = NULL; - PyObject *delimiter = NULL; - PyObject *doublequote = NULL; - PyObject *escapechar = NULL; - PyObject *lineterminator = NULL; - PyObject *quotechar = NULL; - PyObject *quoting = NULL; - PyObject *skipinitialspace = NULL; - PyObject *strict = NULL; - - if (!PyArg_ParseTupleAndKeywords(args, kwargs, - "|OOOOOOOOO", dialect_kws, - &dialect, - &delimiter, - &doublequote, - &escapechar, - &lineterminator, - "echar, - "ing, - &skipinitialspace, - &strict)) - return NULL; - - if (dialect != NULL) { - if (IS_BASESTRING(dialect)) { - dialect = get_dialect_from_registry(dialect); - if (dialect == NULL) - return NULL; - } - else - Py_INCREF(dialect); - /* Can we reuse this instance? */ - if (PyObject_TypeCheck(dialect, &Dialect_Type) && - delimiter == 0 && - doublequote == 0 && - escapechar == 0 && - lineterminator == 0 && - quotechar == 0 && - quoting == 0 && - skipinitialspace == 0 && - strict == 0) - return dialect; - } - - self = (DialectObj *)type->tp_alloc(type, 0); - if (self == NULL) { - Py_XDECREF(dialect); - return NULL; - } - self->lineterminator = NULL; - - Py_XINCREF(delimiter); - Py_XINCREF(doublequote); - Py_XINCREF(escapechar); - Py_XINCREF(lineterminator); - Py_XINCREF(quotechar); - Py_XINCREF(quoting); - Py_XINCREF(skipinitialspace); - Py_XINCREF(strict); - if (dialect != NULL) { + DialectObj *self; + PyObject *ret = NULL; + PyObject *dialect = NULL; + PyObject *delimiter = NULL; + PyObject *doublequote = NULL; + PyObject *escapechar = NULL; + PyObject *lineterminator = NULL; + PyObject *quotechar = NULL; + PyObject *quoting = NULL; + PyObject *skipinitialspace = NULL; + PyObject *strict = NULL; + + if (!PyArg_ParseTupleAndKeywords(args, kwargs, + "|OOOOOOOOO", dialect_kws, + &dialect, + &delimiter, + &doublequote, + &escapechar, + &lineterminator, + "echar, + "ing, + &skipinitialspace, + &strict)) + return NULL; + + if (dialect != NULL) { + if (IS_BASESTRING(dialect)) { + dialect = get_dialect_from_registry(dialect); + if (dialect == NULL) + return NULL; + } + else + Py_INCREF(dialect); + /* Can we reuse this instance? */ + if (PyObject_TypeCheck(dialect, &Dialect_Type) && + delimiter == 0 && + doublequote == 0 && + escapechar == 0 && + lineterminator == 0 && + quotechar == 0 && + quoting == 0 && + skipinitialspace == 0 && + strict == 0) + return dialect; + } + + self = (DialectObj *)type->tp_alloc(type, 0); + if (self == NULL) { + Py_XDECREF(dialect); + return NULL; + } + self->lineterminator = NULL; + + Py_XINCREF(delimiter); + Py_XINCREF(doublequote); + Py_XINCREF(escapechar); + Py_XINCREF(lineterminator); + Py_XINCREF(quotechar); + Py_XINCREF(quoting); + Py_XINCREF(skipinitialspace); + Py_XINCREF(strict); + if (dialect != NULL) { #define DIALECT_GETATTR(v, n) \ - if (v == NULL) \ - v = PyObject_GetAttrString(dialect, n) - DIALECT_GETATTR(delimiter, "delimiter"); - DIALECT_GETATTR(doublequote, "doublequote"); - DIALECT_GETATTR(escapechar, "escapechar"); - DIALECT_GETATTR(lineterminator, "lineterminator"); - DIALECT_GETATTR(quotechar, "quotechar"); - DIALECT_GETATTR(quoting, "quoting"); - DIALECT_GETATTR(skipinitialspace, "skipinitialspace"); - DIALECT_GETATTR(strict, "strict"); - PyErr_Clear(); - } + if (v == NULL) \ + v = PyObject_GetAttrString(dialect, n) + DIALECT_GETATTR(delimiter, "delimiter"); + DIALECT_GETATTR(doublequote, "doublequote"); + DIALECT_GETATTR(escapechar, "escapechar"); + DIALECT_GETATTR(lineterminator, "lineterminator"); + DIALECT_GETATTR(quotechar, "quotechar"); + DIALECT_GETATTR(quoting, "quoting"); + DIALECT_GETATTR(skipinitialspace, "skipinitialspace"); + DIALECT_GETATTR(strict, "strict"); + PyErr_Clear(); + } - /* check types and convert to C values */ + /* check types and convert to C values */ #define DIASET(meth, name, target, src, dflt) \ - if (meth(name, target, src, dflt)) \ - goto err - DIASET(_set_char, "delimiter", &self->delimiter, delimiter, ','); - DIASET(_set_bool, "doublequote", &self->doublequote, doublequote, 1); - DIASET(_set_char, "escapechar", &self->escapechar, escapechar, 0); - DIASET(_set_str, "lineterminator", &self->lineterminator, lineterminator, "\r\n"); - DIASET(_set_char, "quotechar", &self->quotechar, quotechar, '"'); - DIASET(_set_int, "quoting", &self->quoting, quoting, QUOTE_MINIMAL); - DIASET(_set_bool, "skipinitialspace", &self->skipinitialspace, skipinitialspace, 0); - DIASET(_set_bool, "strict", &self->strict, strict, 0); - - /* validate options */ - if (dialect_check_quoting(self->quoting)) - goto err; - if (self->delimiter == 0) { - PyErr_SetString(PyExc_TypeError, "delimiter must be set"); - goto err; - } - if (quotechar == Py_None && quoting == NULL) - self->quoting = QUOTE_NONE; - if (self->quoting != QUOTE_NONE && self->quotechar == 0) { - PyErr_SetString(PyExc_TypeError, - "quotechar must be set if quoting enabled"); - goto err; - } - if (self->lineterminator == 0) { - PyErr_SetString(PyExc_TypeError, "lineterminator must be set"); - goto err; - } + if (meth(name, target, src, dflt)) \ + goto err + DIASET(_set_char, "delimiter", &self->delimiter, delimiter, ','); + DIASET(_set_bool, "doublequote", &self->doublequote, doublequote, 1); + DIASET(_set_char, "escapechar", &self->escapechar, escapechar, 0); + DIASET(_set_str, "lineterminator", &self->lineterminator, lineterminator, "\r\n"); + DIASET(_set_char, "quotechar", &self->quotechar, quotechar, '"'); + DIASET(_set_int, "quoting", &self->quoting, quoting, QUOTE_MINIMAL); + DIASET(_set_bool, "skipinitialspace", &self->skipinitialspace, skipinitialspace, 0); + DIASET(_set_bool, "strict", &self->strict, strict, 0); + + /* validate options */ + if (dialect_check_quoting(self->quoting)) + goto err; + if (self->delimiter == 0) { + PyErr_SetString(PyExc_TypeError, "delimiter must be set"); + goto err; + } + if (quotechar == Py_None && quoting == NULL) + self->quoting = QUOTE_NONE; + if (self->quoting != QUOTE_NONE && self->quotechar == 0) { + PyErr_SetString(PyExc_TypeError, + "quotechar must be set if quoting enabled"); + goto err; + } + if (self->lineterminator == 0) { + PyErr_SetString(PyExc_TypeError, "lineterminator must be set"); + goto err; + } - ret = (PyObject *)self; - Py_INCREF(self); + ret = (PyObject *)self; + Py_INCREF(self); err: - Py_XDECREF(self); - Py_XDECREF(dialect); - Py_XDECREF(delimiter); - Py_XDECREF(doublequote); - Py_XDECREF(escapechar); - Py_XDECREF(lineterminator); - Py_XDECREF(quotechar); - Py_XDECREF(quoting); - Py_XDECREF(skipinitialspace); - Py_XDECREF(strict); - return ret; + Py_XDECREF(self); + Py_XDECREF(dialect); + Py_XDECREF(delimiter); + Py_XDECREF(doublequote); + Py_XDECREF(escapechar); + Py_XDECREF(lineterminator); + Py_XDECREF(quotechar); + Py_XDECREF(quoting); + Py_XDECREF(skipinitialspace); + Py_XDECREF(strict); + return ret; } -PyDoc_STRVAR(Dialect_Type_doc, +PyDoc_STRVAR(Dialect_Type_doc, "CSV dialect\n" "\n" "The Dialect type records CSV parsing and generation options.\n"); static PyTypeObject Dialect_Type = { - PyVarObject_HEAD_INIT(NULL, 0) - "_csv.Dialect", /* tp_name */ - sizeof(DialectObj), /* tp_basicsize */ - 0, /* tp_itemsize */ - /* methods */ - (destructor)Dialect_dealloc, /* tp_dealloc */ - (printfunc)0, /* tp_print */ - (getattrfunc)0, /* tp_getattr */ - (setattrfunc)0, /* tp_setattr */ - 0, /* tp_reserved */ - (reprfunc)0, /* tp_repr */ - 0, /* tp_as_number */ - 0, /* tp_as_sequence */ - 0, /* tp_as_mapping */ - (hashfunc)0, /* tp_hash */ - (ternaryfunc)0, /* tp_call */ - (reprfunc)0, /* tp_str */ - 0, /* tp_getattro */ - 0, /* tp_setattro */ - 0, /* tp_as_buffer */ - Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */ - Dialect_Type_doc, /* tp_doc */ - 0, /* tp_traverse */ - 0, /* tp_clear */ - 0, /* tp_richcompare */ - 0, /* tp_weaklistoffset */ - 0, /* tp_iter */ - 0, /* tp_iternext */ - 0, /* tp_methods */ - Dialect_memberlist, /* tp_members */ - Dialect_getsetlist, /* tp_getset */ - 0, /* tp_base */ - 0, /* tp_dict */ - 0, /* tp_descr_get */ - 0, /* tp_descr_set */ - 0, /* tp_dictoffset */ - 0, /* tp_init */ - 0, /* tp_alloc */ - dialect_new, /* tp_new */ - 0, /* tp_free */ + PyVarObject_HEAD_INIT(NULL, 0) + "_csv.Dialect", /* tp_name */ + sizeof(DialectObj), /* tp_basicsize */ + 0, /* tp_itemsize */ + /* methods */ + (destructor)Dialect_dealloc, /* tp_dealloc */ + (printfunc)0, /* tp_print */ + (getattrfunc)0, /* tp_getattr */ + (setattrfunc)0, /* tp_setattr */ + 0, /* tp_reserved */ + (reprfunc)0, /* tp_repr */ + 0, /* tp_as_number */ + 0, /* tp_as_sequence */ + 0, /* tp_as_mapping */ + (hashfunc)0, /* tp_hash */ + (ternaryfunc)0, /* tp_call */ + (reprfunc)0, /* tp_str */ + 0, /* tp_getattro */ + 0, /* tp_setattro */ + 0, /* tp_as_buffer */ + Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */ + Dialect_Type_doc, /* tp_doc */ + 0, /* tp_traverse */ + 0, /* tp_clear */ + 0, /* tp_richcompare */ + 0, /* tp_weaklistoffset */ + 0, /* tp_iter */ + 0, /* tp_iternext */ + 0, /* tp_methods */ + Dialect_memberlist, /* tp_members */ + Dialect_getsetlist, /* tp_getset */ + 0, /* tp_base */ + 0, /* tp_dict */ + 0, /* tp_descr_get */ + 0, /* tp_descr_set */ + 0, /* tp_dictoffset */ + 0, /* tp_init */ + 0, /* tp_alloc */ + dialect_new, /* tp_new */ + 0, /* tp_free */ }; /* @@ -483,15 +483,15 @@ static PyObject * _call_dialect(PyObject *dialect_inst, PyObject *kwargs) { - PyObject *ctor_args; - PyObject *dialect; + PyObject *ctor_args; + PyObject *dialect; - ctor_args = Py_BuildValue(dialect_inst ? "(O)" : "()", dialect_inst); - if (ctor_args == NULL) - return NULL; - dialect = PyObject_Call((PyObject *)&Dialect_Type, ctor_args, kwargs); - Py_DECREF(ctor_args); - return dialect; + ctor_args = Py_BuildValue(dialect_inst ? "(O)" : "()", dialect_inst); + if (ctor_args == NULL) + return NULL; + dialect = PyObject_Call((PyObject *)&Dialect_Type, ctor_args, kwargs); + Py_DECREF(ctor_args); + return dialect; } /* @@ -500,339 +500,339 @@ static int parse_save_field(ReaderObj *self) { - PyObject *field; + PyObject *field; - field = PyUnicode_FromUnicode(self->field, self->field_len); - if (field == NULL) - return -1; - self->field_len = 0; - if (self->numeric_field) { - PyObject *tmp; - - self->numeric_field = 0; - tmp = PyNumber_Float(field); - if (tmp == NULL) { - Py_DECREF(field); - return -1; - } - Py_DECREF(field); - field = tmp; - } - PyList_Append(self->fields, field); - Py_DECREF(field); - return 0; + field = PyUnicode_FromUnicode(self->field, self->field_len); + if (field == NULL) + return -1; + self->field_len = 0; + if (self->numeric_field) { + PyObject *tmp; + + self->numeric_field = 0; + tmp = PyNumber_Float(field); + if (tmp == NULL) { + Py_DECREF(field); + return -1; + } + Py_DECREF(field); + field = tmp; + } + PyList_Append(self->fields, field); + Py_DECREF(field); + return 0; } 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_New(Py_UNICODE, self->field_size); - } - else { - if (self->field_size > INT_MAX / 2) { - PyErr_NoMemory(); - return 0; - } - self->field_size *= 2; - self->field = PyMem_Resize(self->field, Py_UNICODE, - self->field_size); - } - if (self->field == NULL) { - PyErr_NoMemory(); - return 0; - } - return 1; + if (self->field_size == 0) { + self->field_size = 4096; + if (self->field != NULL) + PyMem_Free(self->field); + self->field = PyMem_New(Py_UNICODE, self->field_size); + } + else { + if (self->field_size > INT_MAX / 2) { + PyErr_NoMemory(); + return 0; + } + self->field_size *= 2; + self->field = PyMem_Resize(self->field, Py_UNICODE, + self->field_size); + } + if (self->field == NULL) { + PyErr_NoMemory(); + return 0; + } + return 1; } static int parse_add_char(ReaderObj *self, Py_UNICODE c) { - if (self->field_len >= field_limit) { - PyErr_Format(error_obj, "field larger than field limit (%ld)", - field_limit); - return -1; - } - if (self->field_len == self->field_size && !parse_grow_buff(self)) - return -1; - self->field[self->field_len++] = c; - return 0; + if (self->field_len >= field_limit) { + PyErr_Format(error_obj, "field larger than field limit (%ld)", + field_limit); + return -1; + } + if (self->field_len == self->field_size && !parse_grow_buff(self)) + return -1; + self->field[self->field_len++] = c; + return 0; } static int parse_process_char(ReaderObj *self, Py_UNICODE c) { - DialectObj *dialect = self->dialect; + DialectObj *dialect = self->dialect; - switch (self->state) { - case START_RECORD: - /* start of record */ - if (c == '\0') - /* empty line - return [] */ - break; - else if (c == '\n' || c == '\r') { - self->state = EAT_CRNL; - break; - } - /* normal character - handle as START_FIELD */ - self->state = START_FIELD; - /* fallthru */ - case START_FIELD: - /* expecting field */ - if (c == '\n' || c == '\r' || c == '\0') { - /* save empty field - return [fields] */ - if (parse_save_field(self) < 0) - return -1; - self->state = (c == '\0' ? START_RECORD : EAT_CRNL); - } - else if (c == dialect->quotechar && - dialect->quoting != QUOTE_NONE) { - /* start quoted field */ - self->state = IN_QUOTED_FIELD; - } - else if (c == dialect->escapechar) { - /* possible escaped character */ - self->state = ESCAPED_CHAR; - } - else if (c == ' ' && dialect->skipinitialspace) - /* ignore space at start of field */ - ; - else if (c == dialect->delimiter) { - /* save empty field */ - if (parse_save_field(self) < 0) - return -1; - } - else { - /* begin new unquoted field */ - if (dialect->quoting == QUOTE_NONNUMERIC) - self->numeric_field = 1; - if (parse_add_char(self, c) < 0) - return -1; - self->state = IN_FIELD; - } - break; - - case ESCAPED_CHAR: - if (c == '\0') - c = '\n'; - if (parse_add_char(self, c) < 0) - return -1; - self->state = IN_FIELD; - break; - - case IN_FIELD: - /* in unquoted field */ - if (c == '\n' || c == '\r' || c == '\0') { - /* end of line - return [fields] */ - if (parse_save_field(self) < 0) - return -1; - self->state = (c == '\0' ? START_RECORD : EAT_CRNL); - } - else if (c == dialect->escapechar) { - /* possible escaped character */ - self->state = ESCAPED_CHAR; - } - else if (c == dialect->delimiter) { - /* save field - wait for new field */ - if (parse_save_field(self) < 0) - return -1; - self->state = START_FIELD; - } - else { - /* normal character - save in field */ - if (parse_add_char(self, c) < 0) - return -1; - } - break; - - case IN_QUOTED_FIELD: - /* in quoted field */ - if (c == '\0') - ; - else if (c == dialect->escapechar) { - /* Possible escape character */ - self->state = ESCAPE_IN_QUOTED_FIELD; - } - else if (c == dialect->quotechar && - dialect->quoting != QUOTE_NONE) { - if (dialect->doublequote) { - /* doublequote; " represented by "" */ - self->state = QUOTE_IN_QUOTED_FIELD; - } - else { - /* end of quote part of field */ - self->state = IN_FIELD; - } - } - else { - /* normal character - save in field */ - if (parse_add_char(self, c) < 0) - return -1; - } - break; - - case ESCAPE_IN_QUOTED_FIELD: - if (c == '\0') - c = '\n'; - if (parse_add_char(self, c) < 0) - return -1; - self->state = IN_QUOTED_FIELD; - break; - - case QUOTE_IN_QUOTED_FIELD: - /* doublequote - seen a quote in an quoted field */ - if (dialect->quoting != QUOTE_NONE && - c == dialect->quotechar) { - /* save "" as " */ - if (parse_add_char(self, c) < 0) - return -1; - self->state = IN_QUOTED_FIELD; - } - else if (c == dialect->delimiter) { - /* save field - wait for new field */ - if (parse_save_field(self) < 0) - return -1; - self->state = START_FIELD; - } - else if (c == '\n' || c == '\r' || c == '\0') { - /* end of line - return [fields] */ - if (parse_save_field(self) < 0) - return -1; - self->state = (c == '\0' ? START_RECORD : EAT_CRNL); - } - else if (!dialect->strict) { - if (parse_add_char(self, c) < 0) - return -1; - self->state = IN_FIELD; - } - else { - /* illegal */ - PyErr_Format(error_obj, "'%c' expected after '%c'", - dialect->delimiter, - dialect->quotechar); - return -1; - } - break; - - case EAT_CRNL: - if (c == '\n' || c == '\r') - ; - else if (c == '\0') - self->state = START_RECORD; - else { - PyErr_Format(error_obj, "new-line character seen in unquoted field - do you need to open the file in universal-newline mode?"); - return -1; - } - break; + switch (self->state) { + case START_RECORD: + /* start of record */ + if (c == '\0') + /* empty line - return [] */ + break; + else if (c == '\n' || c == '\r') { + self->state = EAT_CRNL; + break; + } + /* normal character - handle as START_FIELD */ + self->state = START_FIELD; + /* fallthru */ + case START_FIELD: + /* expecting field */ + if (c == '\n' || c == '\r' || c == '\0') { + /* save empty field - return [fields] */ + if (parse_save_field(self) < 0) + return -1; + self->state = (c == '\0' ? START_RECORD : EAT_CRNL); + } + else if (c == dialect->quotechar && + dialect->quoting != QUOTE_NONE) { + /* start quoted field */ + self->state = IN_QUOTED_FIELD; + } + else if (c == dialect->escapechar) { + /* possible escaped character */ + self->state = ESCAPED_CHAR; + } + else if (c == ' ' && dialect->skipinitialspace) + /* ignore space at start of field */ + ; + else if (c == dialect->delimiter) { + /* save empty field */ + if (parse_save_field(self) < 0) + return -1; + } + else { + /* begin new unquoted field */ + if (dialect->quoting == QUOTE_NONNUMERIC) + self->numeric_field = 1; + if (parse_add_char(self, c) < 0) + return -1; + self->state = IN_FIELD; + } + break; - } - return 0; + case ESCAPED_CHAR: + if (c == '\0') + c = '\n'; + if (parse_add_char(self, c) < 0) + return -1; + self->state = IN_FIELD; + break; + + case IN_FIELD: + /* in unquoted field */ + if (c == '\n' || c == '\r' || c == '\0') { + /* end of line - return [fields] */ + if (parse_save_field(self) < 0) + return -1; + self->state = (c == '\0' ? START_RECORD : EAT_CRNL); + } + else if (c == dialect->escapechar) { + /* possible escaped character */ + self->state = ESCAPED_CHAR; + } + else if (c == dialect->delimiter) { + /* save field - wait for new field */ + if (parse_save_field(self) < 0) + return -1; + self->state = START_FIELD; + } + else { + /* normal character - save in field */ + if (parse_add_char(self, c) < 0) + return -1; + } + break; + + case IN_QUOTED_FIELD: + /* in quoted field */ + if (c == '\0') + ; + else if (c == dialect->escapechar) { + /* Possible escape character */ + self->state = ESCAPE_IN_QUOTED_FIELD; + } + else if (c == dialect->quotechar && + dialect->quoting != QUOTE_NONE) { + if (dialect->doublequote) { + /* doublequote; " represented by "" */ + self->state = QUOTE_IN_QUOTED_FIELD; + } + else { + /* end of quote part of field */ + self->state = IN_FIELD; + } + } + else { + /* normal character - save in field */ + if (parse_add_char(self, c) < 0) + return -1; + } + break; + + case ESCAPE_IN_QUOTED_FIELD: + if (c == '\0') + c = '\n'; + if (parse_add_char(self, c) < 0) + return -1; + self->state = IN_QUOTED_FIELD; + break; + + case QUOTE_IN_QUOTED_FIELD: + /* doublequote - seen a quote in an quoted field */ + if (dialect->quoting != QUOTE_NONE && + c == dialect->quotechar) { + /* save "" as " */ + if (parse_add_char(self, c) < 0) + return -1; + self->state = IN_QUOTED_FIELD; + } + else if (c == dialect->delimiter) { + /* save field - wait for new field */ + if (parse_save_field(self) < 0) + return -1; + self->state = START_FIELD; + } + else if (c == '\n' || c == '\r' || c == '\0') { + /* end of line - return [fields] */ + if (parse_save_field(self) < 0) + return -1; + self->state = (c == '\0' ? START_RECORD : EAT_CRNL); + } + else if (!dialect->strict) { + if (parse_add_char(self, c) < 0) + return -1; + self->state = IN_FIELD; + } + else { + /* illegal */ + PyErr_Format(error_obj, "'%c' expected after '%c'", + dialect->delimiter, + dialect->quotechar); + return -1; + } + break; + + case EAT_CRNL: + if (c == '\n' || c == '\r') + ; + else if (c == '\0') + self->state = START_RECORD; + else { + PyErr_Format(error_obj, "new-line character seen in unquoted field - do you need to open the file in universal-newline mode?"); + return -1; + } + break; + + } + return 0; } static int parse_reset(ReaderObj *self) { - Py_XDECREF(self->fields); - self->fields = PyList_New(0); - if (self->fields == NULL) - return -1; - self->field_len = 0; - self->state = START_RECORD; - self->numeric_field = 0; - return 0; + Py_XDECREF(self->fields); + self->fields = PyList_New(0); + if (self->fields == NULL) + return -1; + self->field_len = 0; + self->state = START_RECORD; + self->numeric_field = 0; + return 0; } static PyObject * Reader_iternext(ReaderObj *self) { - PyObject *lineobj; - PyObject *fields = NULL; - Py_UNICODE *line, c; - Py_ssize_t linelen; - - if (parse_reset(self) < 0) - return NULL; - do { - lineobj = PyIter_Next(self->input_iter); - if (lineobj == NULL) { - /* End of input OR exception */ - if (!PyErr_Occurred() && self->field_len != 0) - PyErr_Format(error_obj, - "newline inside string"); - return NULL; - } - if (!PyUnicode_Check(lineobj)) { - PyErr_Format(error_obj, - "iterator should return strings, " - "not %.200s " - "(did you open the file in text mode?)", - lineobj->ob_type->tp_name - ); - Py_DECREF(lineobj); - return NULL; - } - ++self->line_num; - line = PyUnicode_AsUnicode(lineobj); - linelen = PyUnicode_GetSize(lineobj); - if (line == NULL || linelen < 0) { - Py_DECREF(lineobj); - return NULL; - } - while (linelen--) { - c = *line++; - if (c == '\0') { - Py_DECREF(lineobj); - PyErr_Format(error_obj, - "line contains NULL byte"); - goto err; - } - if (parse_process_char(self, c) < 0) { - Py_DECREF(lineobj); - goto err; - } - } + PyObject *lineobj; + PyObject *fields = NULL; + Py_UNICODE *line, c; + Py_ssize_t linelen; + + if (parse_reset(self) < 0) + return NULL; + do { + lineobj = PyIter_Next(self->input_iter); + if (lineobj == NULL) { + /* End of input OR exception */ + if (!PyErr_Occurred() && self->field_len != 0) + PyErr_Format(error_obj, + "newline inside string"); + return NULL; + } + if (!PyUnicode_Check(lineobj)) { + PyErr_Format(error_obj, + "iterator should return strings, " + "not %.200s " + "(did you open the file in text mode?)", + lineobj->ob_type->tp_name + ); + Py_DECREF(lineobj); + return NULL; + } + ++self->line_num; + line = PyUnicode_AsUnicode(lineobj); + linelen = PyUnicode_GetSize(lineobj); + if (line == NULL || linelen < 0) { + Py_DECREF(lineobj); + return NULL; + } + while (linelen--) { + c = *line++; + if (c == '\0') { + Py_DECREF(lineobj); + PyErr_Format(error_obj, + "line contains NULL byte"); + goto err; + } + if (parse_process_char(self, c) < 0) { Py_DECREF(lineobj); - if (parse_process_char(self, 0) < 0) - goto err; - } while (self->state != START_RECORD); + goto err; + } + } + Py_DECREF(lineobj); + if (parse_process_char(self, 0) < 0) + goto err; + } while (self->state != START_RECORD); - fields = self->fields; - self->fields = NULL; + fields = self->fields; + self->fields = NULL; err: - return fields; + return fields; } static void Reader_dealloc(ReaderObj *self) { - PyObject_GC_UnTrack(self); - Py_XDECREF(self->dialect); - Py_XDECREF(self->input_iter); - Py_XDECREF(self->fields); - if (self->field != NULL) - PyMem_Free(self->field); - PyObject_GC_Del(self); + PyObject_GC_UnTrack(self); + Py_XDECREF(self->dialect); + Py_XDECREF(self->input_iter); + Py_XDECREF(self->fields); + if (self->field != NULL) + PyMem_Free(self->field); + PyObject_GC_Del(self); } static int Reader_traverse(ReaderObj *self, visitproc visit, void *arg) { - Py_VISIT(self->dialect); - Py_VISIT(self->input_iter); - Py_VISIT(self->fields); - return 0; + Py_VISIT(self->dialect); + Py_VISIT(self->input_iter); + Py_VISIT(self->fields); + return 0; } static int Reader_clear(ReaderObj *self) { - Py_CLEAR(self->dialect); - Py_CLEAR(self->input_iter); - Py_CLEAR(self->fields); - return 0; + Py_CLEAR(self->dialect); + Py_CLEAR(self->input_iter); + Py_CLEAR(self->fields); + return 0; } PyDoc_STRVAR(Reader_Type_doc, @@ -843,93 +843,93 @@ ); static struct PyMethodDef Reader_methods[] = { - { NULL, NULL } + { NULL, NULL } }; #define R_OFF(x) offsetof(ReaderObj, x) static struct PyMemberDef Reader_memberlist[] = { - { "dialect", T_OBJECT, R_OFF(dialect), READONLY }, - { "line_num", T_ULONG, R_OFF(line_num), READONLY }, - { NULL } + { "dialect", T_OBJECT, R_OFF(dialect), READONLY }, + { "line_num", T_ULONG, R_OFF(line_num), READONLY }, + { NULL } }; static PyTypeObject Reader_Type = { - PyVarObject_HEAD_INIT(NULL, 0) - "_csv.reader", /*tp_name*/ - sizeof(ReaderObj), /*tp_basicsize*/ - 0, /*tp_itemsize*/ - /* methods */ - (destructor)Reader_dealloc, /*tp_dealloc*/ - (printfunc)0, /*tp_print*/ - (getattrfunc)0, /*tp_getattr*/ - (setattrfunc)0, /*tp_setattr*/ - 0, /*tp_reserved*/ - (reprfunc)0, /*tp_repr*/ - 0, /*tp_as_number*/ - 0, /*tp_as_sequence*/ - 0, /*tp_as_mapping*/ - (hashfunc)0, /*tp_hash*/ - (ternaryfunc)0, /*tp_call*/ - (reprfunc)0, /*tp_str*/ - 0, /*tp_getattro*/ - 0, /*tp_setattro*/ - 0, /*tp_as_buffer*/ - Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | - Py_TPFLAGS_HAVE_GC, /*tp_flags*/ - Reader_Type_doc, /*tp_doc*/ - (traverseproc)Reader_traverse, /*tp_traverse*/ - (inquiry)Reader_clear, /*tp_clear*/ - 0, /*tp_richcompare*/ - 0, /*tp_weaklistoffset*/ - PyObject_SelfIter, /*tp_iter*/ - (getiterfunc)Reader_iternext, /*tp_iternext*/ - Reader_methods, /*tp_methods*/ - Reader_memberlist, /*tp_members*/ - 0, /*tp_getset*/ + PyVarObject_HEAD_INIT(NULL, 0) + "_csv.reader", /*tp_name*/ + sizeof(ReaderObj), /*tp_basicsize*/ + 0, /*tp_itemsize*/ + /* methods */ + (destructor)Reader_dealloc, /*tp_dealloc*/ + (printfunc)0, /*tp_print*/ + (getattrfunc)0, /*tp_getattr*/ + (setattrfunc)0, /*tp_setattr*/ + 0, /*tp_reserved*/ + (reprfunc)0, /*tp_repr*/ + 0, /*tp_as_number*/ + 0, /*tp_as_sequence*/ + 0, /*tp_as_mapping*/ + (hashfunc)0, /*tp_hash*/ + (ternaryfunc)0, /*tp_call*/ + (reprfunc)0, /*tp_str*/ + 0, /*tp_getattro*/ + 0, /*tp_setattro*/ + 0, /*tp_as_buffer*/ + Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | + Py_TPFLAGS_HAVE_GC, /*tp_flags*/ + Reader_Type_doc, /*tp_doc*/ + (traverseproc)Reader_traverse, /*tp_traverse*/ + (inquiry)Reader_clear, /*tp_clear*/ + 0, /*tp_richcompare*/ + 0, /*tp_weaklistoffset*/ + PyObject_SelfIter, /*tp_iter*/ + (getiterfunc)Reader_iternext, /*tp_iternext*/ + Reader_methods, /*tp_methods*/ + Reader_memberlist, /*tp_members*/ + 0, /*tp_getset*/ }; static PyObject * csv_reader(PyObject *module, PyObject *args, PyObject *keyword_args) { - PyObject * iterator, * dialect = NULL; - ReaderObj * self = PyObject_GC_New(ReaderObj, &Reader_Type); - - if (!self) - return NULL; + PyObject * iterator, * dialect = NULL; + ReaderObj * self = PyObject_GC_New(ReaderObj, &Reader_Type); - self->dialect = NULL; - self->fields = NULL; - self->input_iter = NULL; - self->field = NULL; - self->field_size = 0; - self->line_num = 0; + if (!self) + return NULL; - if (parse_reset(self) < 0) { - Py_DECREF(self); - return NULL; - } - - if (!PyArg_UnpackTuple(args, "", 1, 2, &iterator, &dialect)) { - Py_DECREF(self); - return NULL; - } - self->input_iter = PyObject_GetIter(iterator); - if (self->input_iter == NULL) { - PyErr_SetString(PyExc_TypeError, - "argument 1 must be an iterator"); - Py_DECREF(self); - return NULL; - } - self->dialect = (DialectObj *)_call_dialect(dialect, keyword_args); - if (self->dialect == NULL) { - Py_DECREF(self); - return NULL; - } + self->dialect = NULL; + self->fields = NULL; + self->input_iter = NULL; + self->field = NULL; + self->field_size = 0; + self->line_num = 0; + + if (parse_reset(self) < 0) { + Py_DECREF(self); + return NULL; + } + + if (!PyArg_UnpackTuple(args, "", 1, 2, &iterator, &dialect)) { + Py_DECREF(self); + return NULL; + } + self->input_iter = PyObject_GetIter(iterator); + if (self->input_iter == NULL) { + PyErr_SetString(PyExc_TypeError, + "argument 1 must be an iterator"); + Py_DECREF(self); + return NULL; + } + self->dialect = (DialectObj *)_call_dialect(dialect, keyword_args); + if (self->dialect == NULL) { + Py_DECREF(self); + return NULL; + } - PyObject_GC_Track(self); - return (PyObject *)self; + PyObject_GC_Track(self); + return (PyObject *)self; } /* @@ -939,8 +939,8 @@ static void join_reset(WriterObj *self) { - self->rec_len = 0; - self->num_fields = 0; + self->rec_len = 0; + self->num_fields = 0; } #define MEM_INCR 32768 @@ -952,90 +952,90 @@ join_append_data(WriterObj *self, Py_UNICODE *field, int quote_empty, int *quoted, int copy_phase) { - DialectObj *dialect = self->dialect; - int i; - int rec_len; - Py_UNICODE *lineterm; + DialectObj *dialect = self->dialect; + int i; + int rec_len; + Py_UNICODE *lineterm; #define ADDCH(c) \ - do {\ - if (copy_phase) \ - self->rec[rec_len] = c;\ - rec_len++;\ - } while(0) - - lineterm = PyUnicode_AsUnicode(dialect->lineterminator); - if (lineterm == NULL) - return -1; - - rec_len = self->rec_len; - - /* If this is not the first field we need a field separator */ - if (self->num_fields > 0) - ADDCH(dialect->delimiter); - - /* Handle preceding quote */ - if (copy_phase && *quoted) - ADDCH(dialect->quotechar); - - /* Copy/count field data */ - /* If field is null just pass over */ - for (i = 0; field; i++) { - Py_UNICODE c = field[i]; - int want_escape = 0; - - if (c == '\0') - break; - - if (c == dialect->delimiter || - c == dialect->escapechar || - c == dialect->quotechar || - Py_UNICODE_strchr(lineterm, c)) { - if (dialect->quoting == QUOTE_NONE) - want_escape = 1; - else { - if (c == dialect->quotechar) { - if (dialect->doublequote) - ADDCH(dialect->quotechar); - else - want_escape = 1; - } - if (!want_escape) - *quoted = 1; - } - if (want_escape) { - if (!dialect->escapechar) { - PyErr_Format(error_obj, - "need to escape, but no escapechar set"); - return -1; - } - ADDCH(dialect->escapechar); - } - } - /* Copy field character into record buffer. - */ - ADDCH(c); - } - - /* If field is empty check if it needs to be quoted. - */ - if (i == 0 && quote_empty) { - if (dialect->quoting == QUOTE_NONE) { - PyErr_Format(error_obj, - "single empty field record must be quoted"); - return -1; - } - else - *quoted = 1; - } - - if (*quoted) { - if (copy_phase) - ADDCH(dialect->quotechar); - else - rec_len += 2; - } - return rec_len; + do {\ + if (copy_phase) \ + self->rec[rec_len] = c;\ + rec_len++;\ + } while(0) + + lineterm = PyUnicode_AsUnicode(dialect->lineterminator); + if (lineterm == NULL) + return -1; + + rec_len = self->rec_len; + + /* If this is not the first field we need a field separator */ + if (self->num_fields > 0) + ADDCH(dialect->delimiter); + + /* Handle preceding quote */ + if (copy_phase && *quoted) + ADDCH(dialect->quotechar); + + /* Copy/count field data */ + /* If field is null just pass over */ + for (i = 0; field; i++) { + Py_UNICODE c = field[i]; + int want_escape = 0; + + if (c == '\0') + break; + + if (c == dialect->delimiter || + c == dialect->escapechar || + c == dialect->quotechar || + Py_UNICODE_strchr(lineterm, c)) { + if (dialect->quoting == QUOTE_NONE) + want_escape = 1; + else { + if (c == dialect->quotechar) { + if (dialect->doublequote) + ADDCH(dialect->quotechar); + else + want_escape = 1; + } + if (!want_escape) + *quoted = 1; + } + if (want_escape) { + if (!dialect->escapechar) { + PyErr_Format(error_obj, + "need to escape, but no escapechar set"); + return -1; + } + ADDCH(dialect->escapechar); + } + } + /* Copy field character into record buffer. + */ + ADDCH(c); + } + + /* If field is empty check if it needs to be quoted. + */ + if (i == 0 && quote_empty) { + if (dialect->quoting == QUOTE_NONE) { + PyErr_Format(error_obj, + "single empty field record must be quoted"); + return -1; + } + else + *quoted = 1; + } + + if (*quoted) { + if (copy_phase) + ADDCH(dialect->quotechar); + else + rec_len += 2; + } + return rec_len; #undef ADDCH } @@ -1043,76 +1043,76 @@ join_check_rec_size(WriterObj *self, int rec_len) { - if (rec_len < 0 || rec_len > INT_MAX - MEM_INCR) { - PyErr_NoMemory(); - return 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_New(Py_UNICODE, self->rec_size); - } - else { - Py_UNICODE* old_rec = self->rec; - - self->rec_size = (rec_len / MEM_INCR + 1) * MEM_INCR; - self->rec = PyMem_Resize(self->rec, Py_UNICODE, - self->rec_size); - if (self->rec == NULL) - PyMem_Free(old_rec); - } - if (self->rec == NULL) { - PyErr_NoMemory(); - return 0; - } - } - return 1; + if (rec_len < 0 || rec_len > INT_MAX - MEM_INCR) { + PyErr_NoMemory(); + return 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_New(Py_UNICODE, self->rec_size); + } + else { + Py_UNICODE* old_rec = self->rec; + + self->rec_size = (rec_len / MEM_INCR + 1) * MEM_INCR; + self->rec = PyMem_Resize(self->rec, Py_UNICODE, + self->rec_size); + if (self->rec == NULL) + PyMem_Free(old_rec); + } + if (self->rec == NULL) { + PyErr_NoMemory(); + return 0; + } + } + return 1; } static int join_append(WriterObj *self, Py_UNICODE *field, int *quoted, int quote_empty) { - int rec_len; + int rec_len; - rec_len = join_append_data(self, field, quote_empty, quoted, 0); - if (rec_len < 0) - return 0; + rec_len = join_append_data(self, field, quote_empty, quoted, 0); + if (rec_len < 0) + return 0; - /* grow record buffer if necessary */ - if (!join_check_rec_size(self, rec_len)) - return 0; + /* grow record buffer if necessary */ + if (!join_check_rec_size(self, rec_len)) + return 0; - self->rec_len = join_append_data(self, field, quote_empty, quoted, 1); - self->num_fields++; + self->rec_len = join_append_data(self, field, quote_empty, quoted, 1); + self->num_fields++; - return 1; + return 1; } static int join_append_lineterminator(WriterObj *self) { - int terminator_len; - Py_UNICODE *terminator; + int terminator_len; + Py_UNICODE *terminator; + + terminator_len = PyUnicode_GetSize(self->dialect->lineterminator); + if (terminator_len == -1) + return 0; - terminator_len = PyUnicode_GetSize(self->dialect->lineterminator); - if (terminator_len == -1) - return 0; - - /* grow record buffer if necessary */ - if (!join_check_rec_size(self, self->rec_len + terminator_len)) - return 0; - - terminator = PyUnicode_AsUnicode(self->dialect->lineterminator); - if (terminator == NULL) - return 0; - memmove(self->rec + self->rec_len, terminator, - sizeof(Py_UNICODE)*terminator_len); - self->rec_len += terminator_len; + /* grow record buffer if necessary */ + if (!join_check_rec_size(self, self->rec_len + terminator_len)) + return 0; + + terminator = PyUnicode_AsUnicode(self->dialect->lineterminator); + if (terminator == NULL) + return 0; + memmove(self->rec + self->rec_len, terminator, + sizeof(Py_UNICODE)*terminator_len); + self->rec_len += terminator_len; - return 1; + return 1; } PyDoc_STRVAR(csv_writerow_doc, @@ -1124,75 +1124,75 @@ static PyObject * csv_writerow(WriterObj *self, PyObject *seq) { - DialectObj *dialect = self->dialect; - int len, i; + DialectObj *dialect = self->dialect; + int len, i; + + if (!PySequence_Check(seq)) + return PyErr_Format(error_obj, "sequence expected"); - if (!PySequence_Check(seq)) - return PyErr_Format(error_obj, "sequence expected"); + len = PySequence_Length(seq); + if (len < 0) + return NULL; + + /* Join all fields in internal buffer. + */ + join_reset(self); + for (i = 0; i < len; i++) { + PyObject *field; + int append_ok; + int quoted; + + field = PySequence_GetItem(seq, i); + if (field == NULL) + return NULL; + + switch (dialect->quoting) { + case QUOTE_NONNUMERIC: + quoted = !PyNumber_Check(field); + break; + case QUOTE_ALL: + quoted = 1; + break; + default: + quoted = 0; + break; + } + + if (PyUnicode_Check(field)) { + append_ok = join_append(self, + PyUnicode_AS_UNICODE(field), + "ed, len == 1); + Py_DECREF(field); + } + else if (field == Py_None) { + append_ok = join_append(self, NULL, + "ed, len == 1); + Py_DECREF(field); + } + else { + PyObject *str; - len = PySequence_Length(seq); - if (len < 0) - return NULL; - - /* Join all fields in internal buffer. - */ - join_reset(self); - for (i = 0; i < len; i++) { - PyObject *field; - int append_ok; - int quoted; - - field = PySequence_GetItem(seq, i); - if (field == NULL) - return NULL; - - switch (dialect->quoting) { - case QUOTE_NONNUMERIC: - quoted = !PyNumber_Check(field); - break; - case QUOTE_ALL: - quoted = 1; - break; - default: - quoted = 0; - break; - } - - if (PyUnicode_Check(field)) { - append_ok = join_append(self, - PyUnicode_AS_UNICODE(field), - "ed, len == 1); - Py_DECREF(field); - } - else if (field == Py_None) { - append_ok = join_append(self, NULL, + str = PyObject_Str(field); + Py_DECREF(field); + if (str == NULL) + return NULL; + append_ok = join_append(self, + PyUnicode_AS_UNICODE(str), "ed, len == 1); - Py_DECREF(field); - } - else { - PyObject *str; - - str = PyObject_Str(field); - Py_DECREF(field); - if (str == NULL) - return NULL; - append_ok = join_append(self, - PyUnicode_AS_UNICODE(str), - "ed, len == 1); - Py_DECREF(str); - } - if (!append_ok) - return NULL; - } - - /* Add line terminator. - */ - if (!join_append_lineterminator(self)) - return 0; - - return PyObject_CallFunction(self->writeline, - "(u#)", self->rec, - self->rec_len); + Py_DECREF(str); + } + if (!append_ok) + return NULL; + } + + /* Add line terminator. + */ + if (!join_append_lineterminator(self)) + return 0; + + return PyObject_CallFunction(self->writeline, + "(u#)", self->rec, + self->rec_len); } PyDoc_STRVAR(csv_writerows_doc, @@ -1204,72 +1204,72 @@ static PyObject * csv_writerows(WriterObj *self, PyObject *seqseq) { - PyObject *row_iter, *row_obj, *result; + PyObject *row_iter, *row_obj, *result; - row_iter = PyObject_GetIter(seqseq); - if (row_iter == NULL) { - PyErr_SetString(PyExc_TypeError, - "writerows() argument must be iterable"); - return NULL; - } - while ((row_obj = PyIter_Next(row_iter))) { - result = csv_writerow(self, row_obj); - Py_DECREF(row_obj); - if (!result) { - Py_DECREF(row_iter); - return NULL; - } - else - Py_DECREF(result); + row_iter = PyObject_GetIter(seqseq); + if (row_iter == NULL) { + PyErr_SetString(PyExc_TypeError, + "writerows() argument must be iterable"); + return NULL; + } + while ((row_obj = PyIter_Next(row_iter))) { + result = csv_writerow(self, row_obj); + Py_DECREF(row_obj); + if (!result) { + Py_DECREF(row_iter); + return NULL; } - Py_DECREF(row_iter); - if (PyErr_Occurred()) - return NULL; - Py_INCREF(Py_None); - return Py_None; + else + Py_DECREF(result); + } + Py_DECREF(row_iter); + if (PyErr_Occurred()) + return NULL; + Py_INCREF(Py_None); + return Py_None; } static struct PyMethodDef Writer_methods[] = { - { "writerow", (PyCFunction)csv_writerow, METH_O, csv_writerow_doc}, - { "writerows", (PyCFunction)csv_writerows, METH_O, csv_writerows_doc}, - { NULL, NULL } + { "writerow", (PyCFunction)csv_writerow, METH_O, csv_writerow_doc}, + { "writerows", (PyCFunction)csv_writerows, METH_O, csv_writerows_doc}, + { NULL, NULL } }; #define W_OFF(x) offsetof(WriterObj, x) static struct PyMemberDef Writer_memberlist[] = { - { "dialect", T_OBJECT, W_OFF(dialect), READONLY }, - { NULL } + { "dialect", T_OBJECT, W_OFF(dialect), READONLY }, + { NULL } }; static void Writer_dealloc(WriterObj *self) { - PyObject_GC_UnTrack(self); - Py_XDECREF(self->dialect); - Py_XDECREF(self->writeline); - if (self->rec != NULL) - PyMem_Free(self->rec); - PyObject_GC_Del(self); + PyObject_GC_UnTrack(self); + Py_XDECREF(self->dialect); + Py_XDECREF(self->writeline); + if (self->rec != NULL) + PyMem_Free(self->rec); + PyObject_GC_Del(self); } static int Writer_traverse(WriterObj *self, visitproc visit, void *arg) { - Py_VISIT(self->dialect); - Py_VISIT(self->writeline); - return 0; + Py_VISIT(self->dialect); + Py_VISIT(self->writeline); + return 0; } static int Writer_clear(WriterObj *self) { - Py_CLEAR(self->dialect); - Py_CLEAR(self->writeline); - return 0; + Py_CLEAR(self->dialect); + Py_CLEAR(self->writeline); + return 0; } -PyDoc_STRVAR(Writer_Type_doc, +PyDoc_STRVAR(Writer_Type_doc, "CSV writer\n" "\n" "Writer objects are responsible for generating tabular data\n" @@ -1277,75 +1277,75 @@ ); static PyTypeObject Writer_Type = { - PyVarObject_HEAD_INIT(NULL, 0) - "_csv.writer", /*tp_name*/ - sizeof(WriterObj), /*tp_basicsize*/ - 0, /*tp_itemsize*/ - /* methods */ - (destructor)Writer_dealloc, /*tp_dealloc*/ - (printfunc)0, /*tp_print*/ - (getattrfunc)0, /*tp_getattr*/ - (setattrfunc)0, /*tp_setattr*/ - 0, /*tp_reserved*/ - (reprfunc)0, /*tp_repr*/ - 0, /*tp_as_number*/ - 0, /*tp_as_sequence*/ - 0, /*tp_as_mapping*/ - (hashfunc)0, /*tp_hash*/ - (ternaryfunc)0, /*tp_call*/ - (reprfunc)0, /*tp_str*/ - 0, /*tp_getattro*/ - 0, /*tp_setattro*/ - 0, /*tp_as_buffer*/ - Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | - Py_TPFLAGS_HAVE_GC, /*tp_flags*/ - Writer_Type_doc, - (traverseproc)Writer_traverse, /*tp_traverse*/ - (inquiry)Writer_clear, /*tp_clear*/ - 0, /*tp_richcompare*/ - 0, /*tp_weaklistoffset*/ - (getiterfunc)0, /*tp_iter*/ - (getiterfunc)0, /*tp_iternext*/ - Writer_methods, /*tp_methods*/ - Writer_memberlist, /*tp_members*/ - 0, /*tp_getset*/ + PyVarObject_HEAD_INIT(NULL, 0) + "_csv.writer", /*tp_name*/ + sizeof(WriterObj), /*tp_basicsize*/ + 0, /*tp_itemsize*/ + /* methods */ + (destructor)Writer_dealloc, /*tp_dealloc*/ + (printfunc)0, /*tp_print*/ + (getattrfunc)0, /*tp_getattr*/ + (setattrfunc)0, /*tp_setattr*/ + 0, /*tp_reserved*/ + (reprfunc)0, /*tp_repr*/ + 0, /*tp_as_number*/ + 0, /*tp_as_sequence*/ + 0, /*tp_as_mapping*/ + (hashfunc)0, /*tp_hash*/ + (ternaryfunc)0, /*tp_call*/ + (reprfunc)0, /*tp_str*/ + 0, /*tp_getattro*/ + 0, /*tp_setattro*/ + 0, /*tp_as_buffer*/ + Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | + Py_TPFLAGS_HAVE_GC, /*tp_flags*/ + Writer_Type_doc, + (traverseproc)Writer_traverse, /*tp_traverse*/ + (inquiry)Writer_clear, /*tp_clear*/ + 0, /*tp_richcompare*/ + 0, /*tp_weaklistoffset*/ + (getiterfunc)0, /*tp_iter*/ + (getiterfunc)0, /*tp_iternext*/ + Writer_methods, /*tp_methods*/ + Writer_memberlist, /*tp_members*/ + 0, /*tp_getset*/ }; static PyObject * csv_writer(PyObject *module, PyObject *args, PyObject *keyword_args) { - PyObject * output_file, * dialect = NULL; - WriterObj * self = PyObject_GC_New(WriterObj, &Writer_Type); + PyObject * output_file, * dialect = NULL; + WriterObj * self = PyObject_GC_New(WriterObj, &Writer_Type); - if (!self) - return NULL; - - self->dialect = NULL; - self->writeline = NULL; + if (!self) + return NULL; - self->rec = NULL; - self->rec_size = 0; - self->rec_len = 0; - self->num_fields = 0; + self->dialect = NULL; + self->writeline = NULL; - if (!PyArg_UnpackTuple(args, "", 1, 2, &output_file, &dialect)) { - Py_DECREF(self); - return NULL; - } - self->writeline = PyObject_GetAttrString(output_file, "write"); - if (self->writeline == NULL || !PyCallable_Check(self->writeline)) { - PyErr_SetString(PyExc_TypeError, - "argument 1 must have a \"write\" method"); - Py_DECREF(self); - return NULL; - } - self->dialect = (DialectObj *)_call_dialect(dialect, keyword_args); - if (self->dialect == NULL) { - Py_DECREF(self); - return NULL; - } - PyObject_GC_Track(self); - return (PyObject *)self; + self->rec = NULL; + self->rec_size = 0; + self->rec_len = 0; + self->num_fields = 0; + + if (!PyArg_UnpackTuple(args, "", 1, 2, &output_file, &dialect)) { + Py_DECREF(self); + return NULL; + } + self->writeline = PyObject_GetAttrString(output_file, "write"); + if (self->writeline == NULL || !PyCallable_Check(self->writeline)) { + PyErr_SetString(PyExc_TypeError, + "argument 1 must have a \"write\" method"); + Py_DECREF(self); + return NULL; + } + self->dialect = (DialectObj *)_call_dialect(dialect, keyword_args); + if (self->dialect == NULL) { + Py_DECREF(self); + return NULL; + } + PyObject_GC_Track(self); + return (PyObject *)self; } /* @@ -1354,70 +1354,70 @@ static PyObject * csv_list_dialects(PyObject *module, PyObject *args) { - return PyDict_Keys(dialects); + return PyDict_Keys(dialects); } static PyObject * csv_register_dialect(PyObject *module, PyObject *args, PyObject *kwargs) { - PyObject *name_obj, *dialect_obj = NULL; - PyObject *dialect; + PyObject *name_obj, *dialect_obj = NULL; + PyObject *dialect; - if (!PyArg_UnpackTuple(args, "", 1, 2, &name_obj, &dialect_obj)) - return NULL; - if (!IS_BASESTRING(name_obj)) { - PyErr_SetString(PyExc_TypeError, - "dialect name must be a string or unicode"); - return NULL; - } - dialect = _call_dialect(dialect_obj, kwargs); - if (dialect == NULL) - return NULL; - if (PyDict_SetItem(dialects, name_obj, dialect) < 0) { - Py_DECREF(dialect); - return NULL; - } - Py_DECREF(dialect); - Py_INCREF(Py_None); - return Py_None; + if (!PyArg_UnpackTuple(args, "", 1, 2, &name_obj, &dialect_obj)) + return NULL; + if (!IS_BASESTRING(name_obj)) { + PyErr_SetString(PyExc_TypeError, + "dialect name must be a string or unicode"); + return NULL; + } + dialect = _call_dialect(dialect_obj, kwargs); + if (dialect == NULL) + return NULL; + if (PyDict_SetItem(dialects, name_obj, dialect) < 0) { + Py_DECREF(dialect); + return NULL; + } + Py_DECREF(dialect); + Py_INCREF(Py_None); + return Py_None; } static PyObject * csv_unregister_dialect(PyObject *module, PyObject *name_obj) { - if (PyDict_DelItem(dialects, name_obj) < 0) - return PyErr_Format(error_obj, "unknown dialect"); - Py_INCREF(Py_None); - return Py_None; + if (PyDict_DelItem(dialects, name_obj) < 0) + return PyErr_Format(error_obj, "unknown dialect"); + Py_INCREF(Py_None); + return Py_None; } static PyObject * csv_get_dialect(PyObject *module, PyObject *name_obj) { - return get_dialect_from_registry(name_obj); + return get_dialect_from_registry(name_obj); } static PyObject * csv_field_size_limit(PyObject *module, PyObject *args) { - PyObject *new_limit = NULL; - long old_limit = field_limit; + PyObject *new_limit = NULL; + long old_limit = field_limit; - if (!PyArg_UnpackTuple(args, "field_size_limit", 0, 1, &new_limit)) - return NULL; - if (new_limit != NULL) { - if (!PyLong_CheckExact(new_limit)) { - PyErr_Format(PyExc_TypeError, - "limit must be an integer"); - return NULL; - } - field_limit = PyLong_AsLong(new_limit); - if (field_limit == -1 && PyErr_Occurred()) { - field_limit = old_limit; - return NULL; - } - } - return PyLong_FromLong(old_limit); + if (!PyArg_UnpackTuple(args, "field_size_limit", 0, 1, &new_limit)) + return NULL; + if (new_limit != NULL) { + if (!PyLong_CheckExact(new_limit)) { + PyErr_Format(PyExc_TypeError, + "limit must be an integer"); + return NULL; + } + field_limit = PyLong_AsLong(new_limit); + if (field_limit == -1 && PyErr_Occurred()) { + field_limit = old_limit; + return NULL; + } + } + return PyLong_FromLong(old_limit); } /* @@ -1535,84 +1535,84 @@ "the old limit is returned"); static struct PyMethodDef csv_methods[] = { - { "reader", (PyCFunction)csv_reader, - METH_VARARGS | METH_KEYWORDS, csv_reader_doc}, - { "writer", (PyCFunction)csv_writer, - METH_VARARGS | METH_KEYWORDS, csv_writer_doc}, - { "list_dialects", (PyCFunction)csv_list_dialects, - METH_NOARGS, csv_list_dialects_doc}, - { "register_dialect", (PyCFunction)csv_register_dialect, - METH_VARARGS | METH_KEYWORDS, csv_register_dialect_doc}, - { "unregister_dialect", (PyCFunction)csv_unregister_dialect, - METH_O, csv_unregister_dialect_doc}, - { "get_dialect", (PyCFunction)csv_get_dialect, - METH_O, csv_get_dialect_doc}, - { "field_size_limit", (PyCFunction)csv_field_size_limit, - METH_VARARGS, csv_field_size_limit_doc}, - { NULL, NULL } + { "reader", (PyCFunction)csv_reader, + METH_VARARGS | METH_KEYWORDS, csv_reader_doc}, + { "writer", (PyCFunction)csv_writer, + METH_VARARGS | METH_KEYWORDS, csv_writer_doc}, + { "list_dialects", (PyCFunction)csv_list_dialects, + METH_NOARGS, csv_list_dialects_doc}, + { "register_dialect", (PyCFunction)csv_register_dialect, + METH_VARARGS | METH_KEYWORDS, csv_register_dialect_doc}, + { "unregister_dialect", (PyCFunction)csv_unregister_dialect, + METH_O, csv_unregister_dialect_doc}, + { "get_dialect", (PyCFunction)csv_get_dialect, + METH_O, csv_get_dialect_doc}, + { "field_size_limit", (PyCFunction)csv_field_size_limit, + METH_VARARGS, csv_field_size_limit_doc}, + { NULL, NULL } }; static struct PyModuleDef _csvmodule = { - PyModuleDef_HEAD_INIT, - "_csv", - csv_module_doc, - -1, - csv_methods, - NULL, - NULL, - NULL, - NULL + PyModuleDef_HEAD_INIT, + "_csv", + csv_module_doc, + -1, + csv_methods, + NULL, + NULL, + NULL, + NULL }; PyMODINIT_FUNC PyInit__csv(void) { - PyObject *module; - StyleDesc *style; - - if (PyType_Ready(&Dialect_Type) < 0) - return NULL; + PyObject *module; + StyleDesc *style; - if (PyType_Ready(&Reader_Type) < 0) - return NULL; + if (PyType_Ready(&Dialect_Type) < 0) + return NULL; - if (PyType_Ready(&Writer_Type) < 0) - return NULL; - - /* Create the module and add the functions */ - module = PyModule_Create(&_csvmodule); - if (module == NULL) - return NULL; - - /* Add version to the module. */ - if (PyModule_AddStringConstant(module, "__version__", - MODULE_VERSION) == -1) - return NULL; - - /* Add _dialects dictionary */ - dialects = PyDict_New(); - if (dialects == NULL) - return NULL; - if (PyModule_AddObject(module, "_dialects", dialects)) - return NULL; - - /* Add quote styles into dictionary */ - for (style = quote_styles; style->name; style++) { - if (PyModule_AddIntConstant(module, style->name, - style->style) == -1) - return NULL; - } - - /* Add the Dialect type */ - Py_INCREF(&Dialect_Type); - if (PyModule_AddObject(module, "Dialect", (PyObject *)&Dialect_Type)) - return NULL; + if (PyType_Ready(&Reader_Type) < 0) + return NULL; - /* Add the CSV exception object to the module. */ - error_obj = PyErr_NewException("_csv.Error", NULL, NULL); - if (error_obj == NULL) - return NULL; - PyModule_AddObject(module, "Error", error_obj); - return module; + if (PyType_Ready(&Writer_Type) < 0) + return NULL; + + /* Create the module and add the functions */ + module = PyModule_Create(&_csvmodule); + if (module == NULL) + return NULL; + + /* Add version to the module. */ + if (PyModule_AddStringConstant(module, "__version__", + MODULE_VERSION) == -1) + return NULL; + + /* Add _dialects dictionary */ + dialects = PyDict_New(); + if (dialects == NULL) + return NULL; + if (PyModule_AddObject(module, "_dialects", dialects)) + return NULL; + + /* Add quote styles into dictionary */ + for (style = quote_styles; style->name; style++) { + if (PyModule_AddIntConstant(module, style->name, + style->style) == -1) + return NULL; + } + + /* Add the Dialect type */ + Py_INCREF(&Dialect_Type); + if (PyModule_AddObject(module, "Dialect", (PyObject *)&Dialect_Type)) + return NULL; + + /* Add the CSV exception object to the module. */ + error_obj = PyErr_NewException("_csv.Error", NULL, NULL); + if (error_obj == NULL) + return NULL; + PyModule_AddObject(module, "Error", error_obj); + return module; } Modified: python/branches/py3k/Modules/_ctypes/_ctypes.c ============================================================================== --- python/branches/py3k/Modules/_ctypes/_ctypes.c (original) +++ python/branches/py3k/Modules/_ctypes/_ctypes.c Sun May 9 17:52:27 2010 @@ -20,20 +20,20 @@ /* -Name methods, members, getsets +Name methods, members, getsets ============================================================================== -PyCStructType_Type __new__(), from_address(), __mul__(), from_param() -UnionType_Type __new__(), from_address(), __mul__(), from_param() -PyCPointerType_Type __new__(), from_address(), __mul__(), from_param(), set_type() -PyCArrayType_Type __new__(), from_address(), __mul__(), from_param() -PyCSimpleType_Type __new__(), from_address(), __mul__(), from_param() +PyCStructType_Type __new__(), from_address(), __mul__(), from_param() +UnionType_Type __new__(), from_address(), __mul__(), from_param() +PyCPointerType_Type __new__(), from_address(), __mul__(), from_param(), set_type() +PyCArrayType_Type __new__(), from_address(), __mul__(), from_param() +PyCSimpleType_Type __new__(), from_address(), __mul__(), from_param() PyCData_Type - Struct_Type __new__(), __init__() - PyCPointer_Type __new__(), __init__(), _as_parameter_, contents - PyCArray_Type __new__(), __init__(), _as_parameter_, __get/setitem__(), __len__() - Simple_Type __new__(), __init__(), _as_parameter_ + Struct_Type __new__(), __init__() + PyCPointer_Type __new__(), __init__(), _as_parameter_, contents + PyCArray_Type __new__(), __init__(), _as_parameter_, __get/setitem__(), __len__() + Simple_Type __new__(), __init__(), _as_parameter_ PyCField_Type PyCStgDict_Type @@ -45,28 +45,28 @@ It has some similarity to the byref() construct compared to pointer() from_address(addr) - - construct an instance from a given memory block (sharing this memory block) + - construct an instance from a given memory block (sharing this memory block) from_param(obj) - - typecheck and convert a Python object into a C function call parameter - the result may be an instance of the type, or an integer or tuple - (typecode, value[, obj]) + - typecheck and convert a Python object into a C function call parameter + the result may be an instance of the type, or an integer or tuple + (typecode, value[, obj]) instance methods/properties --------------------------- _as_parameter_ - - convert self into a C function call parameter - This is either an integer, or a 3-tuple (typecode, value, obj) + - convert self into a C function call parameter + This is either an integer, or a 3-tuple (typecode, value, obj) functions --------- sizeof(cdata) - - return the number of bytes the buffer contains + - return the number of bytes the buffer contains sizeof(ctype) - - return the number of bytes the buffer of an instance would contain + - return the number of bytes the buffer of an instance would contain byref(cdata) @@ -77,7 +77,7 @@ POINTER(ctype) bytes(cdata) - - return the buffer contents as a sequence of bytes (which is currently a string) + - return the buffer contents as a sequence of bytes (which is currently a string) */ @@ -98,7 +98,7 @@ * PyCField_Type * */ - + #define PY_SSIZE_T_CLEAN #include "Python.h" @@ -135,128 +135,128 @@ char *_ctypes_conversion_encoding = NULL; char *_ctypes_conversion_errors = NULL; - + /****************************************************************/ typedef struct { - PyObject_HEAD - PyObject *key; - PyObject *dict; + PyObject_HEAD + PyObject *key; + PyObject *dict; } DictRemoverObject; static void _DictRemover_dealloc(PyObject *_self) { - DictRemoverObject *self = (DictRemoverObject *)_self; - Py_XDECREF(self->key); - Py_XDECREF(self->dict); - Py_TYPE(self)->tp_free(_self); + DictRemoverObject *self = (DictRemoverObject *)_self; + Py_XDECREF(self->key); + Py_XDECREF(self->dict); + Py_TYPE(self)->tp_free(_self); } static PyObject * _DictRemover_call(PyObject *_self, PyObject *args, PyObject *kw) { - DictRemoverObject *self = (DictRemoverObject *)_self; - if (self->key && self->dict) { - if (-1 == PyDict_DelItem(self->dict, self->key)) - /* XXX Error context */ - PyErr_WriteUnraisable(Py_None); - Py_DECREF(self->key); - self->key = NULL; - Py_DECREF(self->dict); - self->dict = NULL; - } - Py_INCREF(Py_None); - return Py_None; + DictRemoverObject *self = (DictRemoverObject *)_self; + if (self->key && self->dict) { + if (-1 == PyDict_DelItem(self->dict, self->key)) + /* XXX Error context */ + PyErr_WriteUnraisable(Py_None); + Py_DECREF(self->key); + self->key = NULL; + Py_DECREF(self->dict); + self->dict = NULL; + } + Py_INCREF(Py_None); + return Py_None; } static PyTypeObject DictRemover_Type = { - PyVarObject_HEAD_INIT(NULL, 0) - "_ctypes.DictRemover", /* tp_name */ - sizeof(DictRemoverObject), /* tp_basicsize */ - 0, /* tp_itemsize */ - _DictRemover_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 */ - _DictRemover_call, /* tp_call */ - 0, /* tp_str */ - 0, /* tp_getattro */ - 0, /* tp_setattro */ - 0, /* tp_as_buffer */ + PyVarObject_HEAD_INIT(NULL, 0) + "_ctypes.DictRemover", /* tp_name */ + sizeof(DictRemoverObject), /* tp_basicsize */ + 0, /* tp_itemsize */ + _DictRemover_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 */ + _DictRemover_call, /* tp_call */ + 0, /* tp_str */ + 0, /* tp_getattro */ + 0, /* tp_setattro */ + 0, /* tp_as_buffer */ /* XXX should participate in GC? */ - Py_TPFLAGS_DEFAULT, /* tp_flags */ - "deletes a key from a dictionary", /* tp_doc */ - 0, /* tp_traverse */ - 0, /* tp_clear */ - 0, /* tp_richcompare */ - 0, /* tp_weaklistoffset */ - 0, /* tp_iter */ - 0, /* tp_iternext */ - 0, /* tp_methods */ - 0, /* tp_members */ - 0, /* tp_getset */ - 0, /* tp_base */ - 0, /* tp_dict */ - 0, /* tp_descr_get */ - 0, /* tp_descr_set */ - 0, /* tp_dictoffset */ - 0, /* tp_init */ - 0, /* tp_alloc */ - 0, /* tp_new */ - 0, /* tp_free */ + Py_TPFLAGS_DEFAULT, /* tp_flags */ + "deletes a key from a dictionary", /* tp_doc */ + 0, /* tp_traverse */ + 0, /* tp_clear */ + 0, /* tp_richcompare */ + 0, /* tp_weaklistoffset */ + 0, /* tp_iter */ + 0, /* tp_iternext */ + 0, /* tp_methods */ + 0, /* tp_members */ + 0, /* tp_getset */ + 0, /* tp_base */ + 0, /* tp_dict */ + 0, /* tp_descr_get */ + 0, /* tp_descr_set */ + 0, /* tp_dictoffset */ + 0, /* tp_init */ + 0, /* tp_alloc */ + 0, /* tp_new */ + 0, /* tp_free */ }; int PyDict_SetItemProxy(PyObject *dict, PyObject *key, PyObject *item) { - PyObject *obj; - DictRemoverObject *remover; - PyObject *proxy; - int result; - - obj = PyObject_CallObject((PyObject *)&DictRemover_Type, NULL); - if (obj == NULL) - return -1; - - remover = (DictRemoverObject *)obj; - assert(remover->key == NULL); - assert(remover->dict == NULL); - Py_INCREF(key); - remover->key = key; - Py_INCREF(dict); - remover->dict = dict; - - proxy = PyWeakref_NewProxy(item, obj); - Py_DECREF(obj); - if (proxy == NULL) - return -1; - - result = PyDict_SetItem(dict, key, proxy); - Py_DECREF(proxy); - return result; + PyObject *obj; + DictRemoverObject *remover; + PyObject *proxy; + int result; + + obj = PyObject_CallObject((PyObject *)&DictRemover_Type, NULL); + if (obj == NULL) + return -1; + + remover = (DictRemoverObject *)obj; + assert(remover->key == NULL); + assert(remover->dict == NULL); + Py_INCREF(key); + remover->key = key; + Py_INCREF(dict); + remover->dict = dict; + + proxy = PyWeakref_NewProxy(item, obj); + Py_DECREF(obj); + if (proxy == NULL) + return -1; + + result = PyDict_SetItem(dict, key, proxy); + Py_DECREF(proxy); + return result; } PyObject * PyDict_GetItemProxy(PyObject *dict, PyObject *key) { - PyObject *result; - PyObject *item = PyDict_GetItem(dict, key); + PyObject *result; + PyObject *item = PyDict_GetItem(dict, key); - if (item == NULL) - return NULL; - if (!PyWeakref_CheckProxy(item)) - return item; - result = PyWeakref_GET_OBJECT(item); - if (result == Py_None) - return NULL; - return result; + if (item == NULL) + return NULL; + if (!PyWeakref_CheckProxy(item)) + return item; + result = PyWeakref_GET_OBJECT(item); + if (result == Py_None) + return NULL; + return result; } /******************************************************************/ @@ -269,25 +269,25 @@ char * _ctypes_alloc_format_string(const char *prefix, const char *suffix) { - size_t len; - char *result; + size_t len; + char *result; - if (suffix == NULL) { - assert(PyErr_Occurred()); - return NULL; - } - len = strlen(suffix); - if (prefix) - len += strlen(prefix); - result = PyMem_Malloc(len + 1); - if (result == NULL) - return NULL; - if (prefix) - strcpy(result, prefix); - else - result[0] = '\0'; - strcat(result, suffix); - return result; + if (suffix == NULL) { + assert(PyErr_Occurred()); + return NULL; + } + len = strlen(suffix); + if (prefix) + len += strlen(prefix); + result = PyMem_Malloc(len + 1); + if (result == NULL) + return NULL; + if (prefix) + strcpy(result, prefix); + else + result[0] = '\0'; + strcat(result, suffix); + return result; } /* @@ -300,100 +300,100 @@ static PyCArgObject * StructUnionType_paramfunc(CDataObject *self) { - PyCArgObject *parg; - StgDictObject *stgdict; - - parg = PyCArgObject_new(); - if (parg == NULL) - return NULL; - - parg->tag = 'V'; - stgdict = PyObject_stgdict((PyObject *)self); - assert(stgdict); /* Cannot be NULL for structure/union instances */ - parg->pffi_type = &stgdict->ffi_type_pointer; - /* For structure parameters (by value), parg->value doesn't contain the structure - data itself, instead parg->value.p *points* to the structure's data - See also _ctypes.c, function _call_function_pointer(). - */ - parg->value.p = self->b_ptr; - parg->size = self->b_size; - Py_INCREF(self); - parg->obj = (PyObject *)self; - return parg; + PyCArgObject *parg; + StgDictObject *stgdict; + + parg = PyCArgObject_new(); + if (parg == NULL) + return NULL; + + parg->tag = 'V'; + stgdict = PyObject_stgdict((PyObject *)self); + assert(stgdict); /* Cannot be NULL for structure/union instances */ + parg->pffi_type = &stgdict->ffi_type_pointer; + /* For structure parameters (by value), parg->value doesn't contain the structure + data itself, instead parg->value.p *points* to the structure's data + See also _ctypes.c, function _call_function_pointer(). + */ + parg->value.p = self->b_ptr; + parg->size = self->b_size; + Py_INCREF(self); + parg->obj = (PyObject *)self; + return parg; } static PyObject * StructUnionType_new(PyTypeObject *type, PyObject *args, PyObject *kwds, int isStruct) { - PyTypeObject *result; - PyObject *fields; - StgDictObject *dict; - - /* create the new instance (which is a class, - since we are a metatype!) */ - result = (PyTypeObject *)PyType_Type.tp_new(type, args, kwds); - if (!result) - return NULL; - - /* keep this for bw compatibility */ - if (PyDict_GetItemString(result->tp_dict, "_abstract_")) - return (PyObject *)result; - - dict = (StgDictObject *)PyObject_CallObject((PyObject *)&PyCStgDict_Type, NULL); - if (!dict) { - Py_DECREF(result); - return NULL; - } - /* replace the class dict by our updated stgdict, which holds info - about storage requirements of the instances */ - if (-1 == PyDict_Update((PyObject *)dict, result->tp_dict)) { - Py_DECREF(result); - Py_DECREF((PyObject *)dict); - return NULL; - } - Py_DECREF(result->tp_dict); - result->tp_dict = (PyObject *)dict; - dict->format = _ctypes_alloc_format_string(NULL, "B"); - if (dict->format == NULL) { - Py_DECREF(result); - return NULL; - } - - dict->paramfunc = StructUnionType_paramfunc; - - fields = PyDict_GetItemString((PyObject *)dict, "_fields_"); - if (!fields) { - StgDictObject *basedict = PyType_stgdict((PyObject *)result->tp_base); - - if (basedict == NULL) - return (PyObject *)result; - /* copy base dict */ - if (-1 == PyCStgDict_clone(dict, basedict)) { - Py_DECREF(result); - return NULL; - } - dict->flags &= ~DICTFLAG_FINAL; /* clear the 'final' flag in the subclass dict */ - basedict->flags |= DICTFLAG_FINAL; /* set the 'final' flag in the baseclass dict */ - return (PyObject *)result; - } - - if (-1 == PyObject_SetAttrString((PyObject *)result, "_fields_", fields)) { - Py_DECREF(result); - return NULL; - } - return (PyObject *)result; + PyTypeObject *result; + PyObject *fields; + StgDictObject *dict; + + /* create the new instance (which is a class, + since we are a metatype!) */ + result = (PyTypeObject *)PyType_Type.tp_new(type, args, kwds); + if (!result) + return NULL; + + /* keep this for bw compatibility */ + if (PyDict_GetItemString(result->tp_dict, "_abstract_")) + return (PyObject *)result; + + dict = (StgDictObject *)PyObject_CallObject((PyObject *)&PyCStgDict_Type, NULL); + if (!dict) { + Py_DECREF(result); + return NULL; + } + /* replace the class dict by our updated stgdict, which holds info + about storage requirements of the instances */ + if (-1 == PyDict_Update((PyObject *)dict, result->tp_dict)) { + Py_DECREF(result); + Py_DECREF((PyObject *)dict); + return NULL; + } + Py_DECREF(result->tp_dict); + result->tp_dict = (PyObject *)dict; + dict->format = _ctypes_alloc_format_string(NULL, "B"); + if (dict->format == NULL) { + Py_DECREF(result); + return NULL; + } + + dict->paramfunc = StructUnionType_paramfunc; + + fields = PyDict_GetItemString((PyObject *)dict, "_fields_"); + if (!fields) { + StgDictObject *basedict = PyType_stgdict((PyObject *)result->tp_base); + + if (basedict == NULL) + return (PyObject *)result; + /* copy base dict */ + if (-1 == PyCStgDict_clone(dict, basedict)) { + Py_DECREF(result); + return NULL; + } + dict->flags &= ~DICTFLAG_FINAL; /* clear the 'final' flag in the subclass dict */ + basedict->flags |= DICTFLAG_FINAL; /* set the 'final' flag in the baseclass dict */ + return (PyObject *)result; + } + + if (-1 == PyObject_SetAttrString((PyObject *)result, "_fields_", fields)) { + Py_DECREF(result); + return NULL; + } + return (PyObject *)result; } static PyObject * PyCStructType_new(PyTypeObject *type, PyObject *args, PyObject *kwds) { - return StructUnionType_new(type, args, kwds, 1); + return StructUnionType_new(type, args, kwds, 1); } static PyObject * UnionType_new(PyTypeObject *type, PyObject *args, PyObject *kwds) { - return StructUnionType_new(type, args, kwds, 0); + return StructUnionType_new(type, args, kwds, 0); } static char from_address_doc[] = @@ -402,16 +402,16 @@ static PyObject * CDataType_from_address(PyObject *type, PyObject *value) { - void *buf; - if (!PyLong_Check(value)) { - PyErr_SetString(PyExc_TypeError, - "integer expected"); - return NULL; - } - buf = (void *)PyLong_AsVoidPtr(value); - if (PyErr_Occurred()) - return NULL; - return PyCData_AtAddress(type, buf); + void *buf; + if (!PyLong_Check(value)) { + PyErr_SetString(PyExc_TypeError, + "integer expected"); + return NULL; + } + buf = (void *)PyLong_AsVoidPtr(value); + if (PyErr_Occurred()) + return NULL; + return PyCData_AtAddress(type, buf); } static char from_buffer_doc[] = @@ -423,51 +423,51 @@ static PyObject * CDataType_from_buffer(PyObject *type, PyObject *args) { - void *buffer; - Py_ssize_t buffer_len; - Py_ssize_t offset = 0; - PyObject *obj, *result; - StgDictObject *dict = PyType_stgdict(type); - assert (dict); + void *buffer; + Py_ssize_t buffer_len; + Py_ssize_t offset = 0; + PyObject *obj, *result; + StgDictObject *dict = PyType_stgdict(type); + assert (dict); - if (!PyArg_ParseTuple(args, + if (!PyArg_ParseTuple(args, #if (PY_VERSION_HEX < 0x02050000) - "O|i:from_buffer", + "O|i:from_buffer", #else - "O|n:from_buffer", + "O|n:from_buffer", #endif - &obj, &offset)) - return NULL; + &obj, &offset)) + return NULL; - if (-1 == PyObject_AsWriteBuffer(obj, &buffer, &buffer_len)) - return NULL; + if (-1 == PyObject_AsWriteBuffer(obj, &buffer, &buffer_len)) + return NULL; - if (offset < 0) { - PyErr_SetString(PyExc_ValueError, - "offset cannot be negative"); - return NULL; - } - if (dict->size > buffer_len - offset) { - PyErr_Format(PyExc_ValueError, + if (offset < 0) { + PyErr_SetString(PyExc_ValueError, + "offset cannot be negative"); + return NULL; + } + if (dict->size > buffer_len - offset) { + PyErr_Format(PyExc_ValueError, #if (PY_VERSION_HEX < 0x02050000) - "Buffer size too small (%d instead of at least %d bytes)", + "Buffer size too small (%d instead of at least %d bytes)", #else - "Buffer size too small (%zd instead of at least %zd bytes)", + "Buffer size too small (%zd instead of at least %zd bytes)", #endif - buffer_len, dict->size + offset); - return NULL; - } - - result = PyCData_AtAddress(type, (char *)buffer + offset); - if (result == NULL) - return NULL; - - Py_INCREF(obj); - if (-1 == KeepRef((CDataObject *)result, -1, obj)) { - Py_DECREF(result); - return NULL; - } - return result; + buffer_len, dict->size + offset); + return NULL; + } + + result = PyCData_AtAddress(type, (char *)buffer + offset); + if (result == NULL) + return NULL; + + Py_INCREF(obj); + if (-1 == KeepRef((CDataObject *)result, -1, obj)) { + Py_DECREF(result); + return NULL; + } + return result; } static char from_buffer_copy_doc[] = @@ -479,48 +479,48 @@ static PyObject * CDataType_from_buffer_copy(PyObject *type, PyObject *args) { - const void *buffer; - Py_ssize_t buffer_len; - Py_ssize_t offset = 0; - PyObject *obj, *result; - StgDictObject *dict = PyType_stgdict(type); - assert (dict); + const void *buffer; + Py_ssize_t buffer_len; + Py_ssize_t offset = 0; + PyObject *obj, *result; + StgDictObject *dict = PyType_stgdict(type); + assert (dict); - if (!PyArg_ParseTuple(args, + if (!PyArg_ParseTuple(args, #if (PY_VERSION_HEX < 0x02050000) - "O|i:from_buffer", + "O|i:from_buffer", #else - "O|n:from_buffer", + "O|n:from_buffer", #endif - &obj, &offset)) - return NULL; + &obj, &offset)) + return NULL; - if (-1 == PyObject_AsReadBuffer(obj, (const void**)&buffer, &buffer_len)) - return NULL; + if (-1 == PyObject_AsReadBuffer(obj, (const void**)&buffer, &buffer_len)) + return NULL; - if (offset < 0) { - PyErr_SetString(PyExc_ValueError, - "offset cannot be negative"); - return NULL; - } + if (offset < 0) { + PyErr_SetString(PyExc_ValueError, + "offset cannot be negative"); + return NULL; + } - if (dict->size > buffer_len - offset) { - PyErr_Format(PyExc_ValueError, + if (dict->size > buffer_len - offset) { + PyErr_Format(PyExc_ValueError, #if (PY_VERSION_HEX < 0x02050000) - "Buffer size too small (%d instead of at least %d bytes)", + "Buffer size too small (%d instead of at least %d bytes)", #else - "Buffer size too small (%zd instead of at least %zd bytes)", + "Buffer size too small (%zd instead of at least %zd bytes)", #endif - buffer_len, dict->size + offset); - return NULL; - } - - result = GenericPyCData_new((PyTypeObject *)type, NULL, NULL); - if (result == NULL) - return NULL; - memcpy(((CDataObject *)result)->b_ptr, - (char *)buffer+offset, dict->size); - return result; + buffer_len, dict->size + offset); + return NULL; + } + + result = GenericPyCData_new((PyTypeObject *)type, NULL, NULL); + if (result == NULL) + return NULL; + memcpy(((CDataObject *)result)->b_ptr, + (char *)buffer+offset, dict->size); + return result; } static char in_dll_doc[] = @@ -529,55 +529,55 @@ static PyObject * CDataType_in_dll(PyObject *type, PyObject *args) { - PyObject *dll; - char *name; - PyObject *obj; - void *handle; - void *address; - - if (!PyArg_ParseTuple(args, "Os:in_dll", &dll, &name)) - return NULL; - - obj = PyObject_GetAttrString(dll, "_handle"); - if (!obj) - return NULL; - if (!PyLong_Check(obj)) { - PyErr_SetString(PyExc_TypeError, - "the _handle attribute of the second argument must be an integer"); - Py_DECREF(obj); - return NULL; - } - handle = (void *)PyLong_AsVoidPtr(obj); - Py_DECREF(obj); - if (PyErr_Occurred()) { - PyErr_SetString(PyExc_ValueError, - "could not convert the _handle attribute to a pointer"); - return NULL; - } + PyObject *dll; + char *name; + PyObject *obj; + void *handle; + void *address; + + if (!PyArg_ParseTuple(args, "Os:in_dll", &dll, &name)) + return NULL; + + obj = PyObject_GetAttrString(dll, "_handle"); + if (!obj) + return NULL; + if (!PyLong_Check(obj)) { + PyErr_SetString(PyExc_TypeError, + "the _handle attribute of the second argument must be an integer"); + Py_DECREF(obj); + return NULL; + } + handle = (void *)PyLong_AsVoidPtr(obj); + Py_DECREF(obj); + if (PyErr_Occurred()) { + PyErr_SetString(PyExc_ValueError, + "could not convert the _handle attribute to a pointer"); + return NULL; + } #ifdef MS_WIN32 - address = (void *)GetProcAddress(handle, name); - if (!address) { - PyErr_Format(PyExc_ValueError, - "symbol '%s' not found", - name); - return NULL; - } + address = (void *)GetProcAddress(handle, name); + if (!address) { + PyErr_Format(PyExc_ValueError, + "symbol '%s' not found", + name); + return NULL; + } #else - address = (void *)ctypes_dlsym(handle, name); - if (!address) { + address = (void *)ctypes_dlsym(handle, name); + if (!address) { #ifdef __CYGWIN__ /* dlerror() isn't very helpful on cygwin */ - PyErr_Format(PyExc_ValueError, - "symbol '%s' not found (%s) ", - name); + PyErr_Format(PyExc_ValueError, + "symbol '%s' not found (%s) ", + name); #else - PyErr_SetString(PyExc_ValueError, ctypes_dlerror()); + PyErr_SetString(PyExc_ValueError, ctypes_dlerror()); #endif - return NULL; - } + return NULL; + } #endif - return PyCData_AtAddress(type, address); + return PyCData_AtAddress(type, address); } static char from_param_doc[] = @@ -586,210 +586,210 @@ static PyObject * CDataType_from_param(PyObject *type, PyObject *value) { - PyObject *as_parameter; - if (1 == PyObject_IsInstance(value, type)) { - Py_INCREF(value); - return value; - } - if (PyCArg_CheckExact(value)) { - PyCArgObject *p = (PyCArgObject *)value; - PyObject *ob = p->obj; - const char *ob_name; - StgDictObject *dict; - dict = PyType_stgdict(type); - - /* If we got a PyCArgObject, we must check if the object packed in it - is an instance of the type's dict->proto */ - if(dict && ob - && PyObject_IsInstance(ob, dict->proto)) { - Py_INCREF(value); - return value; - } - ob_name = (ob) ? Py_TYPE(ob)->tp_name : "???"; - PyErr_Format(PyExc_TypeError, - "expected %s instance instead of pointer to %s", - ((PyTypeObject *)type)->tp_name, ob_name); - return NULL; - } - - as_parameter = PyObject_GetAttrString(value, "_as_parameter_"); - if (as_parameter) { - value = CDataType_from_param(type, as_parameter); - Py_DECREF(as_parameter); - return value; - } - PyErr_Format(PyExc_TypeError, - "expected %s instance instead of %s", - ((PyTypeObject *)type)->tp_name, - Py_TYPE(value)->tp_name); - return NULL; + PyObject *as_parameter; + if (1 == PyObject_IsInstance(value, type)) { + Py_INCREF(value); + return value; + } + if (PyCArg_CheckExact(value)) { + PyCArgObject *p = (PyCArgObject *)value; + PyObject *ob = p->obj; + const char *ob_name; + StgDictObject *dict; + dict = PyType_stgdict(type); + + /* If we got a PyCArgObject, we must check if the object packed in it + is an instance of the type's dict->proto */ + if(dict && ob + && PyObject_IsInstance(ob, dict->proto)) { + Py_INCREF(value); + return value; + } + ob_name = (ob) ? Py_TYPE(ob)->tp_name : "???"; + PyErr_Format(PyExc_TypeError, + "expected %s instance instead of pointer to %s", + ((PyTypeObject *)type)->tp_name, ob_name); + return NULL; + } + + as_parameter = PyObject_GetAttrString(value, "_as_parameter_"); + if (as_parameter) { + value = CDataType_from_param(type, as_parameter); + Py_DECREF(as_parameter); + return value; + } + PyErr_Format(PyExc_TypeError, + "expected %s instance instead of %s", + ((PyTypeObject *)type)->tp_name, + Py_TYPE(value)->tp_name); + return NULL; } static PyMethodDef CDataType_methods[] = { - { "from_param", CDataType_from_param, METH_O, from_param_doc }, - { "from_address", CDataType_from_address, METH_O, from_address_doc }, - { "from_buffer", CDataType_from_buffer, METH_VARARGS, from_buffer_doc, }, - { "from_buffer_copy", CDataType_from_buffer_copy, METH_VARARGS, from_buffer_copy_doc, }, - { "in_dll", CDataType_in_dll, METH_VARARGS, in_dll_doc }, - { NULL, NULL }, + { "from_param", CDataType_from_param, METH_O, from_param_doc }, + { "from_address", CDataType_from_address, METH_O, from_address_doc }, + { "from_buffer", CDataType_from_buffer, METH_VARARGS, from_buffer_doc, }, + { "from_buffer_copy", CDataType_from_buffer_copy, METH_VARARGS, from_buffer_copy_doc, }, + { "in_dll", CDataType_in_dll, METH_VARARGS, in_dll_doc }, + { NULL, NULL }, }; static PyObject * CDataType_repeat(PyObject *self, Py_ssize_t length) { - if (length < 0) - return PyErr_Format(PyExc_ValueError, - "Array length must be >= 0, not %zd", - length); - return PyCArrayType_from_ctype(self, length); + if (length < 0) + return PyErr_Format(PyExc_ValueError, + "Array length must be >= 0, not %zd", + length); + return PyCArrayType_from_ctype(self, length); } static PySequenceMethods CDataType_as_sequence = { - 0, /* inquiry sq_length; */ - 0, /* binaryfunc sq_concat; */ - CDataType_repeat, /* intargfunc sq_repeat; */ - 0, /* intargfunc sq_item; */ - 0, /* intintargfunc sq_slice; */ - 0, /* intobjargproc sq_ass_item; */ - 0, /* intintobjargproc sq_ass_slice; */ - 0, /* objobjproc sq_contains; */ - - 0, /* binaryfunc sq_inplace_concat; */ - 0, /* intargfunc sq_inplace_repeat; */ + 0, /* inquiry sq_length; */ + 0, /* binaryfunc sq_concat; */ + CDataType_repeat, /* intargfunc sq_repeat; */ + 0, /* intargfunc sq_item; */ + 0, /* intintargfunc sq_slice; */ + 0, /* intobjargproc sq_ass_item; */ + 0, /* intintobjargproc sq_ass_slice; */ + 0, /* objobjproc sq_contains; */ + + 0, /* binaryfunc sq_inplace_concat; */ + 0, /* intargfunc sq_inplace_repeat; */ }; static int CDataType_clear(PyTypeObject *self) { - StgDictObject *dict = PyType_stgdict((PyObject *)self); - if (dict) - Py_CLEAR(dict->proto); - return PyType_Type.tp_clear((PyObject *)self); + StgDictObject *dict = PyType_stgdict((PyObject *)self); + if (dict) + Py_CLEAR(dict->proto); + return PyType_Type.tp_clear((PyObject *)self); } static int CDataType_traverse(PyTypeObject *self, visitproc visit, void *arg) { - StgDictObject *dict = PyType_stgdict((PyObject *)self); - if (dict) - Py_VISIT(dict->proto); - return PyType_Type.tp_traverse((PyObject *)self, visit, arg); + StgDictObject *dict = PyType_stgdict((PyObject *)self); + if (dict) + Py_VISIT(dict->proto); + return PyType_Type.tp_traverse((PyObject *)self, visit, arg); } static int PyCStructType_setattro(PyObject *self, PyObject *key, PyObject *value) { - /* XXX Should we disallow deleting _fields_? */ - if (-1 == PyType_Type.tp_setattro(self, key, value)) - return -1; - - if (value && PyUnicode_Check(key) && - /* XXX struni _PyUnicode_AsString can fail (also in other places)! */ - 0 == strcmp(_PyUnicode_AsString(key), "_fields_")) - return PyCStructUnionType_update_stgdict(self, value, 1); - return 0; + /* XXX Should we disallow deleting _fields_? */ + if (-1 == PyType_Type.tp_setattro(self, key, value)) + return -1; + + if (value && PyUnicode_Check(key) && + /* XXX struni _PyUnicode_AsString can fail (also in other places)! */ + 0 == strcmp(_PyUnicode_AsString(key), "_fields_")) + return PyCStructUnionType_update_stgdict(self, value, 1); + return 0; } static int UnionType_setattro(PyObject *self, PyObject *key, PyObject *value) { - /* XXX Should we disallow deleting _fields_? */ - if (-1 == PyObject_GenericSetAttr(self, key, value)) - return -1; - - if (PyUnicode_Check(key) && - 0 == strcmp(_PyUnicode_AsString(key), "_fields_")) - return PyCStructUnionType_update_stgdict(self, value, 0); - return 0; + /* XXX Should we disallow deleting _fields_? */ + if (-1 == PyObject_GenericSetAttr(self, key, value)) + return -1; + + if (PyUnicode_Check(key) && + 0 == strcmp(_PyUnicode_AsString(key), "_fields_")) + return PyCStructUnionType_update_stgdict(self, value, 0); + return 0; } PyTypeObject PyCStructType_Type = { - PyVarObject_HEAD_INIT(NULL, 0) - "_ctypes.PyCStructType", /* tp_name */ - 0, /* tp_basicsize */ - 0, /* tp_itemsize */ - 0, /* tp_dealloc */ - 0, /* tp_print */ - 0, /* tp_getattr */ - 0, /* tp_setattr */ - 0, /* tp_reserved */ - 0, /* tp_repr */ - 0, /* tp_as_number */ - &CDataType_as_sequence, /* tp_as_sequence */ - 0, /* tp_as_mapping */ - 0, /* tp_hash */ - 0, /* tp_call */ - 0, /* tp_str */ - 0, /* tp_getattro */ - PyCStructType_setattro, /* tp_setattro */ - 0, /* tp_as_buffer */ - Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC, /* tp_flags */ - "metatype for the CData Objects", /* tp_doc */ - (traverseproc)CDataType_traverse, /* tp_traverse */ - (inquiry)CDataType_clear, /* tp_clear */ - 0, /* tp_richcompare */ - 0, /* tp_weaklistoffset */ - 0, /* tp_iter */ - 0, /* tp_iternext */ - CDataType_methods, /* tp_methods */ - 0, /* tp_members */ - 0, /* tp_getset */ - 0, /* tp_base */ - 0, /* tp_dict */ - 0, /* tp_descr_get */ - 0, /* tp_descr_set */ - 0, /* tp_dictoffset */ - 0, /* tp_init */ - 0, /* tp_alloc */ - PyCStructType_new, /* tp_new */ - 0, /* tp_free */ + PyVarObject_HEAD_INIT(NULL, 0) + "_ctypes.PyCStructType", /* tp_name */ + 0, /* tp_basicsize */ + 0, /* tp_itemsize */ + 0, /* tp_dealloc */ + 0, /* tp_print */ + 0, /* tp_getattr */ + 0, /* tp_setattr */ + 0, /* tp_reserved */ + 0, /* tp_repr */ + 0, /* tp_as_number */ + &CDataType_as_sequence, /* tp_as_sequence */ + 0, /* tp_as_mapping */ + 0, /* tp_hash */ + 0, /* tp_call */ + 0, /* tp_str */ + 0, /* tp_getattro */ + PyCStructType_setattro, /* tp_setattro */ + 0, /* tp_as_buffer */ + Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC, /* tp_flags */ + "metatype for the CData Objects", /* tp_doc */ + (traverseproc)CDataType_traverse, /* tp_traverse */ + (inquiry)CDataType_clear, /* tp_clear */ + 0, /* tp_richcompare */ + 0, /* tp_weaklistoffset */ + 0, /* tp_iter */ + 0, /* tp_iternext */ + CDataType_methods, /* tp_methods */ + 0, /* tp_members */ + 0, /* tp_getset */ + 0, /* tp_base */ + 0, /* tp_dict */ + 0, /* tp_descr_get */ + 0, /* tp_descr_set */ + 0, /* tp_dictoffset */ + 0, /* tp_init */ + 0, /* tp_alloc */ + PyCStructType_new, /* tp_new */ + 0, /* tp_free */ }; static PyTypeObject UnionType_Type = { - PyVarObject_HEAD_INIT(NULL, 0) - "_ctypes.UnionType", /* tp_name */ - 0, /* tp_basicsize */ - 0, /* tp_itemsize */ - 0, /* tp_dealloc */ - 0, /* tp_print */ - 0, /* tp_getattr */ - 0, /* tp_setattr */ - 0, /* tp_reserved */ - 0, /* tp_repr */ - 0, /* tp_as_number */ - &CDataType_as_sequence, /* tp_as_sequence */ - 0, /* tp_as_mapping */ - 0, /* tp_hash */ - 0, /* tp_call */ - 0, /* tp_str */ - 0, /* tp_getattro */ - UnionType_setattro, /* tp_setattro */ - 0, /* tp_as_buffer */ - Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC, /* tp_flags */ - "metatype for the CData Objects", /* tp_doc */ - (traverseproc)CDataType_traverse, /* tp_traverse */ - (inquiry)CDataType_clear, /* tp_clear */ - 0, /* tp_richcompare */ - 0, /* tp_weaklistoffset */ - 0, /* tp_iter */ - 0, /* tp_iternext */ - CDataType_methods, /* tp_methods */ - 0, /* tp_members */ - 0, /* tp_getset */ - 0, /* tp_base */ - 0, /* tp_dict */ - 0, /* tp_descr_get */ - 0, /* tp_descr_set */ - 0, /* tp_dictoffset */ - 0, /* tp_init */ - 0, /* tp_alloc */ - UnionType_new, /* tp_new */ - 0, /* tp_free */ + PyVarObject_HEAD_INIT(NULL, 0) + "_ctypes.UnionType", /* tp_name */ + 0, /* tp_basicsize */ + 0, /* tp_itemsize */ + 0, /* tp_dealloc */ + 0, /* tp_print */ + 0, /* tp_getattr */ + 0, /* tp_setattr */ + 0, /* tp_reserved */ + 0, /* tp_repr */ + 0, /* tp_as_number */ + &CDataType_as_sequence, /* tp_as_sequence */ + 0, /* tp_as_mapping */ + 0, /* tp_hash */ + 0, /* tp_call */ + 0, /* tp_str */ + 0, /* tp_getattro */ + UnionType_setattro, /* tp_setattro */ + 0, /* tp_as_buffer */ + Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC, /* tp_flags */ + "metatype for the CData Objects", /* tp_doc */ + (traverseproc)CDataType_traverse, /* tp_traverse */ + (inquiry)CDataType_clear, /* tp_clear */ + 0, /* tp_richcompare */ + 0, /* tp_weaklistoffset */ + 0, /* tp_iter */ + 0, /* tp_iternext */ + CDataType_methods, /* tp_methods */ + 0, /* tp_members */ + 0, /* tp_getset */ + 0, /* tp_base */ + 0, /* tp_dict */ + 0, /* tp_descr_get */ + 0, /* tp_descr_set */ + 0, /* tp_dictoffset */ + 0, /* tp_init */ + 0, /* tp_alloc */ + UnionType_new, /* tp_new */ + 0, /* tp_free */ }; - + /******************************************************************/ /* @@ -809,124 +809,124 @@ static int PyCPointerType_SetProto(StgDictObject *stgdict, PyObject *proto) { - if (!proto || !PyType_Check(proto)) { - PyErr_SetString(PyExc_TypeError, - "_type_ must be a type"); - return -1; - } - if (!PyType_stgdict(proto)) { - PyErr_SetString(PyExc_TypeError, - "_type_ must have storage info"); - return -1; - } - Py_INCREF(proto); - Py_XDECREF(stgdict->proto); - stgdict->proto = proto; - return 0; + if (!proto || !PyType_Check(proto)) { + PyErr_SetString(PyExc_TypeError, + "_type_ must be a type"); + return -1; + } + if (!PyType_stgdict(proto)) { + PyErr_SetString(PyExc_TypeError, + "_type_ must have storage info"); + return -1; + } + Py_INCREF(proto); + Py_XDECREF(stgdict->proto); + stgdict->proto = proto; + return 0; } static PyCArgObject * PyCPointerType_paramfunc(CDataObject *self) { - PyCArgObject *parg; + PyCArgObject *parg; - parg = PyCArgObject_new(); - if (parg == NULL) - return NULL; - - parg->tag = 'P'; - parg->pffi_type = &ffi_type_pointer; - Py_INCREF(self); - parg->obj = (PyObject *)self; - parg->value.p = *(void **)self->b_ptr; - return parg; + parg = PyCArgObject_new(); + if (parg == NULL) + return NULL; + + parg->tag = 'P'; + parg->pffi_type = &ffi_type_pointer; + Py_INCREF(self); + parg->obj = (PyObject *)self; + parg->value.p = *(void **)self->b_ptr; + return parg; } static PyObject * PyCPointerType_new(PyTypeObject *type, PyObject *args, PyObject *kwds) { - PyTypeObject *result; - StgDictObject *stgdict; - PyObject *proto; - PyObject *typedict; - - typedict = PyTuple_GetItem(args, 2); - if (!typedict) - return NULL; + PyTypeObject *result; + StgDictObject *stgdict; + PyObject *proto; + PyObject *typedict; + + typedict = PyTuple_GetItem(args, 2); + if (!typedict) + return NULL; /* stgdict items size, align, length contain info about pointers itself, stgdict->proto has info about the pointed to type! */ - stgdict = (StgDictObject *)PyObject_CallObject( - (PyObject *)&PyCStgDict_Type, NULL); - if (!stgdict) - return NULL; - stgdict->size = sizeof(void *); - stgdict->align = _ctypes_get_fielddesc("P")->pffi_type->alignment; - stgdict->length = 1; - stgdict->ffi_type_pointer = ffi_type_pointer; - stgdict->paramfunc = PyCPointerType_paramfunc; - stgdict->flags |= TYPEFLAG_ISPOINTER; - - proto = PyDict_GetItemString(typedict, "_type_"); /* Borrowed ref */ - if (proto && -1 == PyCPointerType_SetProto(stgdict, proto)) { - Py_DECREF((PyObject *)stgdict); - return NULL; - } - - if (proto) { - StgDictObject *itemdict = PyType_stgdict(proto); - assert(itemdict); - /* If itemdict->format is NULL, then this is a pointer to an - incomplete type. We create a generic format string - 'pointer to bytes' in this case. XXX Better would be to - fix the format string later... - */ - stgdict->format = _ctypes_alloc_format_string("&", - itemdict->format ? itemdict->format : "B"); - if (stgdict->format == NULL) { - Py_DECREF((PyObject *)stgdict); - return NULL; - } - } - - /* create the new instance (which is a class, - since we are a metatype!) */ - result = (PyTypeObject *)PyType_Type.tp_new(type, args, kwds); - if (result == NULL) { - Py_DECREF((PyObject *)stgdict); - return NULL; - } - - /* replace the class dict by our updated spam dict */ - if (-1 == PyDict_Update((PyObject *)stgdict, result->tp_dict)) { - Py_DECREF(result); - Py_DECREF((PyObject *)stgdict); - return NULL; - } - Py_DECREF(result->tp_dict); - result->tp_dict = (PyObject *)stgdict; + stgdict = (StgDictObject *)PyObject_CallObject( + (PyObject *)&PyCStgDict_Type, NULL); + if (!stgdict) + return NULL; + stgdict->size = sizeof(void *); + stgdict->align = _ctypes_get_fielddesc("P")->pffi_type->alignment; + stgdict->length = 1; + stgdict->ffi_type_pointer = ffi_type_pointer; + stgdict->paramfunc = PyCPointerType_paramfunc; + stgdict->flags |= TYPEFLAG_ISPOINTER; + + proto = PyDict_GetItemString(typedict, "_type_"); /* Borrowed ref */ + if (proto && -1 == PyCPointerType_SetProto(stgdict, proto)) { + Py_DECREF((PyObject *)stgdict); + return NULL; + } + + if (proto) { + StgDictObject *itemdict = PyType_stgdict(proto); + assert(itemdict); + /* If itemdict->format is NULL, then this is a pointer to an + incomplete type. We create a generic format string + 'pointer to bytes' in this case. XXX Better would be to + fix the format string later... + */ + stgdict->format = _ctypes_alloc_format_string("&", + itemdict->format ? itemdict->format : "B"); + if (stgdict->format == NULL) { + Py_DECREF((PyObject *)stgdict); + return NULL; + } + } + + /* create the new instance (which is a class, + since we are a metatype!) */ + result = (PyTypeObject *)PyType_Type.tp_new(type, args, kwds); + if (result == NULL) { + Py_DECREF((PyObject *)stgdict); + return NULL; + } + + /* replace the class dict by our updated spam dict */ + if (-1 == PyDict_Update((PyObject *)stgdict, result->tp_dict)) { + Py_DECREF(result); + Py_DECREF((PyObject *)stgdict); + return NULL; + } + Py_DECREF(result->tp_dict); + result->tp_dict = (PyObject *)stgdict; - return (PyObject *)result; + return (PyObject *)result; } static PyObject * PyCPointerType_set_type(PyTypeObject *self, PyObject *type) { - StgDictObject *dict; + StgDictObject *dict; - dict = PyType_stgdict((PyObject *)self); - assert(dict); + dict = PyType_stgdict((PyObject *)self); + assert(dict); - if (-1 == PyCPointerType_SetProto(dict, type)) - return NULL; + if (-1 == PyCPointerType_SetProto(dict, type)) + return NULL; - if (-1 == PyDict_SetItemString((PyObject *)dict, "_type_", type)) - return NULL; + if (-1 == PyDict_SetItemString((PyObject *)dict, "_type_", type)) + return NULL; - Py_INCREF(Py_None); - return Py_None; + Py_INCREF(Py_None); + return Py_None; } static PyObject *_byref(PyObject *); @@ -934,98 +934,98 @@ static PyObject * PyCPointerType_from_param(PyObject *type, PyObject *value) { - StgDictObject *typedict; + StgDictObject *typedict; - if (value == Py_None) { - /* ConvParam will convert to a NULL pointer later */ - Py_INCREF(value); - return value; - } - - typedict = PyType_stgdict(type); - assert(typedict); /* Cannot be NULL for pointer types */ - - /* If we expect POINTER(), but receive a instance, accept - it by calling byref(). - */ - switch (PyObject_IsInstance(value, typedict->proto)) { - case 1: - Py_INCREF(value); /* _byref steals a refcount */ - return _byref(value); - case -1: - PyErr_Clear(); - break; - default: - break; - } - - if (PointerObject_Check(value) || ArrayObject_Check(value)) { - /* Array instances are also pointers when - the item types are the same. - */ - StgDictObject *v = PyObject_stgdict(value); - assert(v); /* Cannot be NULL for pointer or array objects */ - if (PyObject_IsSubclass(v->proto, typedict->proto)) { - Py_INCREF(value); - return value; - } - } - return CDataType_from_param(type, value); + if (value == Py_None) { + /* ConvParam will convert to a NULL pointer later */ + Py_INCREF(value); + return value; + } + + typedict = PyType_stgdict(type); + assert(typedict); /* Cannot be NULL for pointer types */ + + /* If we expect POINTER(), but receive a instance, accept + it by calling byref(). + */ + switch (PyObject_IsInstance(value, typedict->proto)) { + case 1: + Py_INCREF(value); /* _byref steals a refcount */ + return _byref(value); + case -1: + PyErr_Clear(); + break; + default: + break; + } + + if (PointerObject_Check(value) || ArrayObject_Check(value)) { + /* Array instances are also pointers when + the item types are the same. + */ + StgDictObject *v = PyObject_stgdict(value); + assert(v); /* Cannot be NULL for pointer or array objects */ + if (PyObject_IsSubclass(v->proto, typedict->proto)) { + Py_INCREF(value); + return value; + } + } + return CDataType_from_param(type, value); } static PyMethodDef PyCPointerType_methods[] = { - { "from_address", CDataType_from_address, METH_O, from_address_doc }, - { "from_buffer", CDataType_from_buffer, METH_VARARGS, from_buffer_doc, }, - { "from_buffer_copy", CDataType_from_buffer_copy, METH_VARARGS, from_buffer_copy_doc, }, - { "in_dll", CDataType_in_dll, METH_VARARGS, in_dll_doc}, - { "from_param", (PyCFunction)PyCPointerType_from_param, METH_O, from_param_doc}, - { "set_type", (PyCFunction)PyCPointerType_set_type, METH_O }, - { NULL, NULL }, + { "from_address", CDataType_from_address, METH_O, from_address_doc }, + { "from_buffer", CDataType_from_buffer, METH_VARARGS, from_buffer_doc, }, + { "from_buffer_copy", CDataType_from_buffer_copy, METH_VARARGS, from_buffer_copy_doc, }, + { "in_dll", CDataType_in_dll, METH_VARARGS, in_dll_doc}, + { "from_param", (PyCFunction)PyCPointerType_from_param, METH_O, from_param_doc}, + { "set_type", (PyCFunction)PyCPointerType_set_type, METH_O }, + { NULL, NULL }, }; PyTypeObject PyCPointerType_Type = { - PyVarObject_HEAD_INIT(NULL, 0) - "_ctypes.PyCPointerType", /* tp_name */ - 0, /* tp_basicsize */ - 0, /* tp_itemsize */ - 0, /* tp_dealloc */ - 0, /* tp_print */ - 0, /* tp_getattr */ - 0, /* tp_setattr */ - 0, /* tp_reserved */ - 0, /* tp_repr */ - 0, /* tp_as_number */ - &CDataType_as_sequence, /* tp_as_sequence */ - 0, /* tp_as_mapping */ - 0, /* tp_hash */ - 0, /* tp_call */ - 0, /* tp_str */ - 0, /* tp_getattro */ - 0, /* tp_setattro */ - 0, /* tp_as_buffer */ - Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC, /* tp_flags */ - "metatype for the Pointer Objects", /* tp_doc */ - (traverseproc)CDataType_traverse, /* tp_traverse */ - (inquiry)CDataType_clear, /* tp_clear */ - 0, /* tp_richcompare */ - 0, /* tp_weaklistoffset */ - 0, /* tp_iter */ - 0, /* tp_iternext */ - PyCPointerType_methods, /* tp_methods */ - 0, /* tp_members */ - 0, /* tp_getset */ - 0, /* tp_base */ - 0, /* tp_dict */ - 0, /* tp_descr_get */ - 0, /* tp_descr_set */ - 0, /* tp_dictoffset */ - 0, /* tp_init */ - 0, /* tp_alloc */ - PyCPointerType_new, /* tp_new */ - 0, /* tp_free */ + PyVarObject_HEAD_INIT(NULL, 0) + "_ctypes.PyCPointerType", /* tp_name */ + 0, /* tp_basicsize */ + 0, /* tp_itemsize */ + 0, /* tp_dealloc */ + 0, /* tp_print */ + 0, /* tp_getattr */ + 0, /* tp_setattr */ + 0, /* tp_reserved */ + 0, /* tp_repr */ + 0, /* tp_as_number */ + &CDataType_as_sequence, /* tp_as_sequence */ + 0, /* tp_as_mapping */ + 0, /* tp_hash */ + 0, /* tp_call */ + 0, /* tp_str */ + 0, /* tp_getattro */ + 0, /* tp_setattro */ + 0, /* tp_as_buffer */ + Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC, /* tp_flags */ + "metatype for the Pointer Objects", /* tp_doc */ + (traverseproc)CDataType_traverse, /* tp_traverse */ + (inquiry)CDataType_clear, /* tp_clear */ + 0, /* tp_richcompare */ + 0, /* tp_weaklistoffset */ + 0, /* tp_iter */ + 0, /* tp_iternext */ + PyCPointerType_methods, /* tp_methods */ + 0, /* tp_members */ + 0, /* tp_getset */ + 0, /* tp_base */ + 0, /* tp_dict */ + 0, /* tp_descr_get */ + 0, /* tp_descr_set */ + 0, /* tp_dictoffset */ + 0, /* tp_init */ + 0, /* tp_alloc */ + PyCPointerType_new, /* tp_new */ + 0, /* tp_free */ }; - + /******************************************************************/ /* PyCArrayType_Type @@ -1038,152 +1038,152 @@ static int CharArray_set_raw(CDataObject *self, PyObject *value) { - char *ptr; - Py_ssize_t size; - Py_buffer view; - - if (PyObject_GetBuffer(value, &view, PyBUF_SIMPLE) < 0) - return -1; - size = view.len; - ptr = view.buf; - if (size > self->b_size) { - PyErr_SetString(PyExc_ValueError, - "string too long"); - goto fail; - } + char *ptr; + Py_ssize_t size; + Py_buffer view; + + if (PyObject_GetBuffer(value, &view, PyBUF_SIMPLE) < 0) + return -1; + size = view.len; + ptr = view.buf; + if (size > self->b_size) { + PyErr_SetString(PyExc_ValueError, + "string too long"); + goto fail; + } - memcpy(self->b_ptr, ptr, size); + memcpy(self->b_ptr, ptr, size); - PyBuffer_Release(&view); - return 0; + PyBuffer_Release(&view); + return 0; fail: - PyBuffer_Release(&view); - return -1; + PyBuffer_Release(&view); + return -1; } static PyObject * CharArray_get_raw(CDataObject *self) { - return PyBytes_FromStringAndSize(self->b_ptr, self->b_size); + return PyBytes_FromStringAndSize(self->b_ptr, self->b_size); } static PyObject * CharArray_get_value(CDataObject *self) { - int i; - char *ptr = self->b_ptr; - for (i = 0; i < self->b_size; ++i) - if (*ptr++ == '\0') - break; - return PyBytes_FromStringAndSize(self->b_ptr, i); + int i; + char *ptr = self->b_ptr; + for (i = 0; i < self->b_size; ++i) + if (*ptr++ == '\0') + break; + return PyBytes_FromStringAndSize(self->b_ptr, i); } static int CharArray_set_value(CDataObject *self, PyObject *value) { - char *ptr; - Py_ssize_t size; + char *ptr; + Py_ssize_t size; + + if (value == NULL) { + PyErr_SetString(PyExc_TypeError, + "can't delete attribute"); + return -1; + } - if (value == NULL) { - PyErr_SetString(PyExc_TypeError, - "can't delete attribute"); - return -1; - } - - if (PyUnicode_Check(value)) { - value = PyUnicode_AsEncodedString(value, - _ctypes_conversion_encoding, - _ctypes_conversion_errors); - if (!value) - return -1; - } else if (!PyBytes_Check(value)) { - PyErr_Format(PyExc_TypeError, - "str/bytes expected instead of %s instance", - Py_TYPE(value)->tp_name); - return -1; - } else - Py_INCREF(value); - size = PyBytes_GET_SIZE(value); - if (size > self->b_size) { - PyErr_SetString(PyExc_ValueError, - "string too long"); - Py_DECREF(value); - return -1; - } - - ptr = PyBytes_AS_STRING(value); - memcpy(self->b_ptr, ptr, size); - if (size < self->b_size) - self->b_ptr[size] = '\0'; - Py_DECREF(value); + if (PyUnicode_Check(value)) { + value = PyUnicode_AsEncodedString(value, + _ctypes_conversion_encoding, + _ctypes_conversion_errors); + if (!value) + return -1; + } else if (!PyBytes_Check(value)) { + PyErr_Format(PyExc_TypeError, + "str/bytes expected instead of %s instance", + Py_TYPE(value)->tp_name); + return -1; + } else + Py_INCREF(value); + size = PyBytes_GET_SIZE(value); + if (size > self->b_size) { + PyErr_SetString(PyExc_ValueError, + "string too long"); + Py_DECREF(value); + return -1; + } - return 0; + ptr = PyBytes_AS_STRING(value); + memcpy(self->b_ptr, ptr, size); + if (size < self->b_size) + self->b_ptr[size] = '\0'; + Py_DECREF(value); + + return 0; } static PyGetSetDef CharArray_getsets[] = { - { "raw", (getter)CharArray_get_raw, (setter)CharArray_set_raw, - "value", NULL }, - { "value", (getter)CharArray_get_value, (setter)CharArray_set_value, - "string value"}, - { NULL, NULL } + { "raw", (getter)CharArray_get_raw, (setter)CharArray_set_raw, + "value", NULL }, + { "value", (getter)CharArray_get_value, (setter)CharArray_set_value, + "string value"}, + { NULL, NULL } }; #ifdef CTYPES_UNICODE static PyObject * WCharArray_get_value(CDataObject *self) { - unsigned int i; - wchar_t *ptr = (wchar_t *)self->b_ptr; - for (i = 0; i < self->b_size/sizeof(wchar_t); ++i) - if (*ptr++ == (wchar_t)0) - break; - return PyUnicode_FromWideChar((wchar_t *)self->b_ptr, i); + unsigned int i; + wchar_t *ptr = (wchar_t *)self->b_ptr; + for (i = 0; i < self->b_size/sizeof(wchar_t); ++i) + if (*ptr++ == (wchar_t)0) + break; + return PyUnicode_FromWideChar((wchar_t *)self->b_ptr, i); } static int WCharArray_set_value(CDataObject *self, PyObject *value) { - Py_ssize_t result = 0; + Py_ssize_t result = 0; - if (value == NULL) { - PyErr_SetString(PyExc_TypeError, - "can't delete attribute"); - return -1; - } - if (PyBytes_Check(value)) { - value = PyUnicode_FromEncodedObject(value, - _ctypes_conversion_encoding, - _ctypes_conversion_errors); - if (!value) - return -1; - } else if (!PyUnicode_Check(value)) { - PyErr_Format(PyExc_TypeError, - "unicode string expected instead of %s instance", - Py_TYPE(value)->tp_name); - return -1; - } else - Py_INCREF(value); - if ((unsigned)PyUnicode_GET_SIZE(value) > self->b_size/sizeof(wchar_t)) { - PyErr_SetString(PyExc_ValueError, - "string too long"); - result = -1; - goto done; - } - result = PyUnicode_AsWideChar((PyUnicodeObject *)value, - (wchar_t *)self->b_ptr, - self->b_size/sizeof(wchar_t)); - if (result >= 0 && (size_t)result < self->b_size/sizeof(wchar_t)) - ((wchar_t *)self->b_ptr)[result] = (wchar_t)0; + if (value == NULL) { + PyErr_SetString(PyExc_TypeError, + "can't delete attribute"); + return -1; + } + if (PyBytes_Check(value)) { + value = PyUnicode_FromEncodedObject(value, + _ctypes_conversion_encoding, + _ctypes_conversion_errors); + if (!value) + return -1; + } else if (!PyUnicode_Check(value)) { + PyErr_Format(PyExc_TypeError, + "unicode string expected instead of %s instance", + Py_TYPE(value)->tp_name); + return -1; + } else + Py_INCREF(value); + if ((unsigned)PyUnicode_GET_SIZE(value) > self->b_size/sizeof(wchar_t)) { + PyErr_SetString(PyExc_ValueError, + "string too long"); + result = -1; + goto done; + } + result = PyUnicode_AsWideChar((PyUnicodeObject *)value, + (wchar_t *)self->b_ptr, + self->b_size/sizeof(wchar_t)); + if (result >= 0 && (size_t)result < self->b_size/sizeof(wchar_t)) + ((wchar_t *)self->b_ptr)[result] = (wchar_t)0; done: - Py_DECREF(value); + Py_DECREF(value); - return result >= 0 ? 0 : -1; + return result >= 0 ? 0 : -1; } static PyGetSetDef WCharArray_getsets[] = { - { "value", (getter)WCharArray_get_value, (setter)WCharArray_set_value, - "string value"}, - { NULL, NULL } + { "value", (getter)WCharArray_get_value, (setter)WCharArray_set_value, + "string value"}, + { NULL, NULL } }; #endif @@ -1198,236 +1198,236 @@ static int add_methods(PyTypeObject *type, PyMethodDef *meth) { - PyObject *dict = type->tp_dict; - for (; meth->ml_name != NULL; meth++) { - PyObject *descr; - descr = PyDescr_NewMethod(type, meth); - if (descr == NULL) - return -1; - if (PyDict_SetItemString(dict,meth->ml_name, descr) < 0) - return -1; - Py_DECREF(descr); - } - return 0; + PyObject *dict = type->tp_dict; + for (; meth->ml_name != NULL; meth++) { + PyObject *descr; + descr = PyDescr_NewMethod(type, meth); + if (descr == NULL) + return -1; + if (PyDict_SetItemString(dict,meth->ml_name, descr) < 0) + return -1; + Py_DECREF(descr); + } + return 0; } static int add_members(PyTypeObject *type, PyMemberDef *memb) { - PyObject *dict = type->tp_dict; - for (; memb->name != NULL; memb++) { - PyObject *descr; - descr = PyDescr_NewMember(type, memb); - if (descr == NULL) - return -1; - if (PyDict_SetItemString(dict, memb->name, descr) < 0) - return -1; - Py_DECREF(descr); - } - return 0; + PyObject *dict = type->tp_dict; + for (; memb->name != NULL; memb++) { + PyObject *descr; + descr = PyDescr_NewMember(type, memb); + if (descr == NULL) + return -1; + if (PyDict_SetItemString(dict, memb->name, descr) < 0) + return -1; + Py_DECREF(descr); + } + return 0; } */ static int add_getset(PyTypeObject *type, PyGetSetDef *gsp) { - PyObject *dict = type->tp_dict; - for (; gsp->name != NULL; gsp++) { - PyObject *descr; - descr = PyDescr_NewGetSet(type, gsp); - if (descr == NULL) - return -1; - if (PyDict_SetItemString(dict, gsp->name, descr) < 0) - return -1; - Py_DECREF(descr); - } - return 0; + PyObject *dict = type->tp_dict; + for (; gsp->name != NULL; gsp++) { + PyObject *descr; + descr = PyDescr_NewGetSet(type, gsp); + if (descr == NULL) + return -1; + if (PyDict_SetItemString(dict, gsp->name, descr) < 0) + return -1; + Py_DECREF(descr); + } + return 0; } static PyCArgObject * PyCArrayType_paramfunc(CDataObject *self) { - PyCArgObject *p = PyCArgObject_new(); - if (p == NULL) - return NULL; - p->tag = 'P'; - p->pffi_type = &ffi_type_pointer; - p->value.p = (char *)self->b_ptr; - Py_INCREF(self); - p->obj = (PyObject *)self; - return p; + PyCArgObject *p = PyCArgObject_new(); + if (p == NULL) + return NULL; + p->tag = 'P'; + p->pffi_type = &ffi_type_pointer; + p->value.p = (char *)self->b_ptr; + Py_INCREF(self); + p->obj = (PyObject *)self; + return p; } static PyObject * PyCArrayType_new(PyTypeObject *type, PyObject *args, PyObject *kwds) { - PyTypeObject *result; - StgDictObject *stgdict; - StgDictObject *itemdict; - PyObject *proto; - PyObject *typedict; - long length; - int overflow; - Py_ssize_t itemsize, itemalign; - char buf[32]; - - typedict = PyTuple_GetItem(args, 2); - if (!typedict) - return NULL; - - proto = PyDict_GetItemString(typedict, "_length_"); /* Borrowed ref */ - if (!proto || !PyLong_Check(proto)) { - PyErr_SetString(PyExc_AttributeError, - "class must define a '_length_' attribute, " - "which must be a positive integer"); - return NULL; - } - length = PyLong_AsLongAndOverflow(proto, &overflow); - if (overflow) { - PyErr_SetString(PyExc_OverflowError, - "The '_length_' attribute is too large"); - return NULL; - } - - proto = PyDict_GetItemString(typedict, "_type_"); /* Borrowed ref */ - if (!proto) { - PyErr_SetString(PyExc_AttributeError, - "class must define a '_type_' attribute"); - return NULL; - } - - stgdict = (StgDictObject *)PyObject_CallObject( - (PyObject *)&PyCStgDict_Type, NULL); - if (!stgdict) - return NULL; - - itemdict = PyType_stgdict(proto); - if (!itemdict) { - PyErr_SetString(PyExc_TypeError, - "_type_ must have storage info"); - Py_DECREF((PyObject *)stgdict); - return NULL; - } - - assert(itemdict->format); - if (itemdict->format[0] == '(') { - sprintf(buf, "(%ld,", length); - stgdict->format = _ctypes_alloc_format_string(buf, itemdict->format+1); - } else { - sprintf(buf, "(%ld)", length); - stgdict->format = _ctypes_alloc_format_string(buf, itemdict->format); - } - if (stgdict->format == NULL) { - Py_DECREF((PyObject *)stgdict); - return NULL; - } - stgdict->ndim = itemdict->ndim + 1; - stgdict->shape = PyMem_Malloc(sizeof(Py_ssize_t *) * stgdict->ndim); - if (stgdict->shape == NULL) { - Py_DECREF((PyObject *)stgdict); - return NULL; - } - stgdict->shape[0] = length; - memmove(&stgdict->shape[1], itemdict->shape, - sizeof(Py_ssize_t) * (stgdict->ndim - 1)); - - itemsize = itemdict->size; - if (length * itemsize < 0) { - PyErr_SetString(PyExc_OverflowError, - "array too large"); - return NULL; - } - - itemalign = itemdict->align; - - if (itemdict->flags & (TYPEFLAG_ISPOINTER | TYPEFLAG_HASPOINTER)) - stgdict->flags |= TYPEFLAG_HASPOINTER; - - stgdict->size = itemsize * length; - stgdict->align = itemalign; - stgdict->length = length; - Py_INCREF(proto); - stgdict->proto = proto; - - stgdict->paramfunc = &PyCArrayType_paramfunc; - - /* Arrays are passed as pointers to function calls. */ - stgdict->ffi_type_pointer = ffi_type_pointer; - - /* create the new instance (which is a class, - since we are a metatype!) */ - result = (PyTypeObject *)PyType_Type.tp_new(type, args, kwds); - if (result == NULL) - return NULL; - - /* replace the class dict by our updated spam dict */ - if (-1 == PyDict_Update((PyObject *)stgdict, result->tp_dict)) { - Py_DECREF(result); - Py_DECREF((PyObject *)stgdict); - return NULL; - } - Py_DECREF(result->tp_dict); - result->tp_dict = (PyObject *)stgdict; - - /* Special case for character arrays. - A permanent annoyance: char arrays are also strings! - */ - if (itemdict->getfunc == _ctypes_get_fielddesc("c")->getfunc) { - if (-1 == add_getset(result, CharArray_getsets)) - return NULL; + PyTypeObject *result; + StgDictObject *stgdict; + StgDictObject *itemdict; + PyObject *proto; + PyObject *typedict; + long length; + int overflow; + Py_ssize_t itemsize, itemalign; + char buf[32]; + + typedict = PyTuple_GetItem(args, 2); + if (!typedict) + return NULL; + + proto = PyDict_GetItemString(typedict, "_length_"); /* Borrowed ref */ + if (!proto || !PyLong_Check(proto)) { + PyErr_SetString(PyExc_AttributeError, + "class must define a '_length_' attribute, " + "which must be a positive integer"); + return NULL; + } + length = PyLong_AsLongAndOverflow(proto, &overflow); + if (overflow) { + PyErr_SetString(PyExc_OverflowError, + "The '_length_' attribute is too large"); + return NULL; + } + + proto = PyDict_GetItemString(typedict, "_type_"); /* Borrowed ref */ + if (!proto) { + PyErr_SetString(PyExc_AttributeError, + "class must define a '_type_' attribute"); + return NULL; + } + + stgdict = (StgDictObject *)PyObject_CallObject( + (PyObject *)&PyCStgDict_Type, NULL); + if (!stgdict) + return NULL; + + itemdict = PyType_stgdict(proto); + if (!itemdict) { + PyErr_SetString(PyExc_TypeError, + "_type_ must have storage info"); + Py_DECREF((PyObject *)stgdict); + return NULL; + } + + assert(itemdict->format); + if (itemdict->format[0] == '(') { + sprintf(buf, "(%ld,", length); + stgdict->format = _ctypes_alloc_format_string(buf, itemdict->format+1); + } else { + sprintf(buf, "(%ld)", length); + stgdict->format = _ctypes_alloc_format_string(buf, itemdict->format); + } + if (stgdict->format == NULL) { + Py_DECREF((PyObject *)stgdict); + return NULL; + } + stgdict->ndim = itemdict->ndim + 1; + stgdict->shape = PyMem_Malloc(sizeof(Py_ssize_t *) * stgdict->ndim); + if (stgdict->shape == NULL) { + Py_DECREF((PyObject *)stgdict); + return NULL; + } + stgdict->shape[0] = length; + memmove(&stgdict->shape[1], itemdict->shape, + sizeof(Py_ssize_t) * (stgdict->ndim - 1)); + + itemsize = itemdict->size; + if (length * itemsize < 0) { + PyErr_SetString(PyExc_OverflowError, + "array too large"); + return NULL; + } + + itemalign = itemdict->align; + + if (itemdict->flags & (TYPEFLAG_ISPOINTER | TYPEFLAG_HASPOINTER)) + stgdict->flags |= TYPEFLAG_HASPOINTER; + + stgdict->size = itemsize * length; + stgdict->align = itemalign; + stgdict->length = length; + Py_INCREF(proto); + stgdict->proto = proto; + + stgdict->paramfunc = &PyCArrayType_paramfunc; + + /* Arrays are passed as pointers to function calls. */ + stgdict->ffi_type_pointer = ffi_type_pointer; + + /* create the new instance (which is a class, + since we are a metatype!) */ + result = (PyTypeObject *)PyType_Type.tp_new(type, args, kwds); + if (result == NULL) + return NULL; + + /* replace the class dict by our updated spam dict */ + if (-1 == PyDict_Update((PyObject *)stgdict, result->tp_dict)) { + Py_DECREF(result); + Py_DECREF((PyObject *)stgdict); + return NULL; + } + Py_DECREF(result->tp_dict); + result->tp_dict = (PyObject *)stgdict; + + /* Special case for character arrays. + A permanent annoyance: char arrays are also strings! + */ + if (itemdict->getfunc == _ctypes_get_fielddesc("c")->getfunc) { + if (-1 == add_getset(result, CharArray_getsets)) + return NULL; #ifdef CTYPES_UNICODE - } else if (itemdict->getfunc == _ctypes_get_fielddesc("u")->getfunc) { - if (-1 == add_getset(result, WCharArray_getsets)) - return NULL; + } else if (itemdict->getfunc == _ctypes_get_fielddesc("u")->getfunc) { + if (-1 == add_getset(result, WCharArray_getsets)) + return NULL; #endif - } + } - return (PyObject *)result; + return (PyObject *)result; } PyTypeObject PyCArrayType_Type = { - PyVarObject_HEAD_INIT(NULL, 0) - "_ctypes.PyCArrayType", /* tp_name */ - 0, /* tp_basicsize */ - 0, /* tp_itemsize */ - 0, /* tp_dealloc */ - 0, /* tp_print */ - 0, /* tp_getattr */ - 0, /* tp_setattr */ - 0, /* tp_reserved */ - 0, /* tp_repr */ - 0, /* tp_as_number */ - &CDataType_as_sequence, /* tp_as_sequence */ - 0, /* tp_as_mapping */ - 0, /* tp_hash */ - 0, /* tp_call */ - 0, /* tp_str */ - 0, /* tp_getattro */ - 0, /* tp_setattro */ - 0, /* tp_as_buffer */ - Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */ - "metatype for the Array Objects", /* tp_doc */ - 0, /* tp_traverse */ - 0, /* tp_clear */ - 0, /* tp_richcompare */ - 0, /* tp_weaklistoffset */ - 0, /* tp_iter */ - 0, /* tp_iternext */ - CDataType_methods, /* tp_methods */ - 0, /* tp_members */ - 0, /* tp_getset */ - 0, /* tp_base */ - 0, /* tp_dict */ - 0, /* tp_descr_get */ - 0, /* tp_descr_set */ - 0, /* tp_dictoffset */ - 0, /* tp_init */ - 0, /* tp_alloc */ - PyCArrayType_new, /* tp_new */ - 0, /* tp_free */ + PyVarObject_HEAD_INIT(NULL, 0) + "_ctypes.PyCArrayType", /* tp_name */ + 0, /* tp_basicsize */ + 0, /* tp_itemsize */ + 0, /* tp_dealloc */ + 0, /* tp_print */ + 0, /* tp_getattr */ + 0, /* tp_setattr */ + 0, /* tp_reserved */ + 0, /* tp_repr */ + 0, /* tp_as_number */ + &CDataType_as_sequence, /* tp_as_sequence */ + 0, /* tp_as_mapping */ + 0, /* tp_hash */ + 0, /* tp_call */ + 0, /* tp_str */ + 0, /* tp_getattro */ + 0, /* tp_setattro */ + 0, /* tp_as_buffer */ + Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */ + "metatype for the Array Objects", /* tp_doc */ + 0, /* tp_traverse */ + 0, /* tp_clear */ + 0, /* tp_richcompare */ + 0, /* tp_weaklistoffset */ + 0, /* tp_iter */ + 0, /* tp_iternext */ + CDataType_methods, /* tp_methods */ + 0, /* tp_members */ + 0, /* tp_getset */ + 0, /* tp_base */ + 0, /* tp_dict */ + 0, /* tp_descr_get */ + 0, /* tp_descr_set */ + 0, /* tp_dictoffset */ + 0, /* tp_init */ + 0, /* tp_alloc */ + PyCArrayType_new, /* tp_new */ + 0, /* tp_free */ }; - + /******************************************************************/ /* PyCSimpleType_Type @@ -1444,273 +1444,273 @@ static PyObject * c_wchar_p_from_param(PyObject *type, PyObject *value) { - PyObject *as_parameter; - if (value == Py_None) { - Py_INCREF(Py_None); - return Py_None; - } - if (PyUnicode_Check(value) || PyBytes_Check(value)) { - PyCArgObject *parg; - struct fielddesc *fd = _ctypes_get_fielddesc("Z"); - - parg = PyCArgObject_new(); - if (parg == NULL) - return NULL; - parg->pffi_type = &ffi_type_pointer; - parg->tag = 'Z'; - parg->obj = fd->setfunc(&parg->value, value, 0); - if (parg->obj == NULL) { - Py_DECREF(parg); - return NULL; - } - return (PyObject *)parg; - } - if (PyObject_IsInstance(value, type)) { - Py_INCREF(value); - return value; - } - if (ArrayObject_Check(value) || PointerObject_Check(value)) { - /* c_wchar array instance or pointer(c_wchar(...)) */ - StgDictObject *dt = PyObject_stgdict(value); - StgDictObject *dict; - assert(dt); /* Cannot be NULL for pointer or array objects */ - dict = dt && dt->proto ? PyType_stgdict(dt->proto) : NULL; - if (dict && (dict->setfunc == _ctypes_get_fielddesc("u")->setfunc)) { - Py_INCREF(value); - return value; - } - } - if (PyCArg_CheckExact(value)) { - /* byref(c_char(...)) */ - PyCArgObject *a = (PyCArgObject *)value; - StgDictObject *dict = PyObject_stgdict(a->obj); - if (dict && (dict->setfunc == _ctypes_get_fielddesc("u")->setfunc)) { - Py_INCREF(value); - return value; - } - } - - as_parameter = PyObject_GetAttrString(value, "_as_parameter_"); - if (as_parameter) { - value = c_wchar_p_from_param(type, as_parameter); - Py_DECREF(as_parameter); - return value; - } - /* XXX better message */ - PyErr_SetString(PyExc_TypeError, - "wrong type"); - return NULL; + PyObject *as_parameter; + if (value == Py_None) { + Py_INCREF(Py_None); + return Py_None; + } + if (PyUnicode_Check(value) || PyBytes_Check(value)) { + PyCArgObject *parg; + struct fielddesc *fd = _ctypes_get_fielddesc("Z"); + + parg = PyCArgObject_new(); + if (parg == NULL) + return NULL; + parg->pffi_type = &ffi_type_pointer; + parg->tag = 'Z'; + parg->obj = fd->setfunc(&parg->value, value, 0); + if (parg->obj == NULL) { + Py_DECREF(parg); + return NULL; + } + return (PyObject *)parg; + } + if (PyObject_IsInstance(value, type)) { + Py_INCREF(value); + return value; + } + if (ArrayObject_Check(value) || PointerObject_Check(value)) { + /* c_wchar array instance or pointer(c_wchar(...)) */ + StgDictObject *dt = PyObject_stgdict(value); + StgDictObject *dict; + assert(dt); /* Cannot be NULL for pointer or array objects */ + dict = dt && dt->proto ? PyType_stgdict(dt->proto) : NULL; + if (dict && (dict->setfunc == _ctypes_get_fielddesc("u")->setfunc)) { + Py_INCREF(value); + return value; + } + } + if (PyCArg_CheckExact(value)) { + /* byref(c_char(...)) */ + PyCArgObject *a = (PyCArgObject *)value; + StgDictObject *dict = PyObject_stgdict(a->obj); + if (dict && (dict->setfunc == _ctypes_get_fielddesc("u")->setfunc)) { + Py_INCREF(value); + return value; + } + } + + as_parameter = PyObject_GetAttrString(value, "_as_parameter_"); + if (as_parameter) { + value = c_wchar_p_from_param(type, as_parameter); + Py_DECREF(as_parameter); + return value; + } + /* XXX better message */ + PyErr_SetString(PyExc_TypeError, + "wrong type"); + return NULL; } static PyObject * c_char_p_from_param(PyObject *type, PyObject *value) { - PyObject *as_parameter; - if (value == Py_None) { - Py_INCREF(Py_None); - return Py_None; - } - if (PyBytes_Check(value) || PyUnicode_Check(value)) { - PyCArgObject *parg; - struct fielddesc *fd = _ctypes_get_fielddesc("z"); - - parg = PyCArgObject_new(); - if (parg == NULL) - return NULL; - parg->pffi_type = &ffi_type_pointer; - parg->tag = 'z'; - parg->obj = fd->setfunc(&parg->value, value, 0); - if (parg->obj == NULL) { - Py_DECREF(parg); - return NULL; - } - return (PyObject *)parg; - } - if (PyObject_IsInstance(value, type)) { - Py_INCREF(value); - return value; - } - if (ArrayObject_Check(value) || PointerObject_Check(value)) { - /* c_char array instance or pointer(c_char(...)) */ - StgDictObject *dt = PyObject_stgdict(value); - StgDictObject *dict; - assert(dt); /* Cannot be NULL for pointer or array objects */ - dict = dt && dt->proto ? PyType_stgdict(dt->proto) : NULL; - if (dict && (dict->setfunc == _ctypes_get_fielddesc("c")->setfunc)) { - Py_INCREF(value); - return value; - } - } - if (PyCArg_CheckExact(value)) { - /* byref(c_char(...)) */ - PyCArgObject *a = (PyCArgObject *)value; - StgDictObject *dict = PyObject_stgdict(a->obj); - if (dict && (dict->setfunc == _ctypes_get_fielddesc("c")->setfunc)) { - Py_INCREF(value); - return value; - } - } - - as_parameter = PyObject_GetAttrString(value, "_as_parameter_"); - if (as_parameter) { - value = c_char_p_from_param(type, as_parameter); - Py_DECREF(as_parameter); - return value; - } - /* XXX better message */ - PyErr_SetString(PyExc_TypeError, - "wrong type"); - return NULL; + PyObject *as_parameter; + if (value == Py_None) { + Py_INCREF(Py_None); + return Py_None; + } + if (PyBytes_Check(value) || PyUnicode_Check(value)) { + PyCArgObject *parg; + struct fielddesc *fd = _ctypes_get_fielddesc("z"); + + parg = PyCArgObject_new(); + if (parg == NULL) + return NULL; + parg->pffi_type = &ffi_type_pointer; + parg->tag = 'z'; + parg->obj = fd->setfunc(&parg->value, value, 0); + if (parg->obj == NULL) { + Py_DECREF(parg); + return NULL; + } + return (PyObject *)parg; + } + if (PyObject_IsInstance(value, type)) { + Py_INCREF(value); + return value; + } + if (ArrayObject_Check(value) || PointerObject_Check(value)) { + /* c_char array instance or pointer(c_char(...)) */ + StgDictObject *dt = PyObject_stgdict(value); + StgDictObject *dict; + assert(dt); /* Cannot be NULL for pointer or array objects */ + dict = dt && dt->proto ? PyType_stgdict(dt->proto) : NULL; + if (dict && (dict->setfunc == _ctypes_get_fielddesc("c")->setfunc)) { + Py_INCREF(value); + return value; + } + } + if (PyCArg_CheckExact(value)) { + /* byref(c_char(...)) */ + PyCArgObject *a = (PyCArgObject *)value; + StgDictObject *dict = PyObject_stgdict(a->obj); + if (dict && (dict->setfunc == _ctypes_get_fielddesc("c")->setfunc)) { + Py_INCREF(value); + return value; + } + } + + as_parameter = PyObject_GetAttrString(value, "_as_parameter_"); + if (as_parameter) { + value = c_char_p_from_param(type, as_parameter); + Py_DECREF(as_parameter); + return value; + } + /* XXX better message */ + PyErr_SetString(PyExc_TypeError, + "wrong type"); + return NULL; } static PyObject * c_void_p_from_param(PyObject *type, PyObject *value) { - StgDictObject *stgd; - PyObject *as_parameter; + StgDictObject *stgd; + PyObject *as_parameter; /* None */ - if (value == Py_None) { - Py_INCREF(Py_None); - return Py_None; - } - /* Should probably allow buffer interface as well */ + if (value == Py_None) { + Py_INCREF(Py_None); + return Py_None; + } + /* Should probably allow buffer interface as well */ /* int, long */ - if (PyLong_Check(value)) { - PyCArgObject *parg; - struct fielddesc *fd = _ctypes_get_fielddesc("P"); - - parg = PyCArgObject_new(); - if (parg == NULL) - return NULL; - parg->pffi_type = &ffi_type_pointer; - parg->tag = 'P'; - parg->obj = fd->setfunc(&parg->value, value, 0); - if (parg->obj == NULL) { - Py_DECREF(parg); - return NULL; - } - return (PyObject *)parg; - } - /* XXX struni: remove later */ + if (PyLong_Check(value)) { + PyCArgObject *parg; + struct fielddesc *fd = _ctypes_get_fielddesc("P"); + + parg = PyCArgObject_new(); + if (parg == NULL) + return NULL; + parg->pffi_type = &ffi_type_pointer; + parg->tag = 'P'; + parg->obj = fd->setfunc(&parg->value, value, 0); + if (parg->obj == NULL) { + Py_DECREF(parg); + return NULL; + } + return (PyObject *)parg; + } + /* XXX struni: remove later */ /* string */ - if (PyBytes_Check(value)) { - PyCArgObject *parg; - struct fielddesc *fd = _ctypes_get_fielddesc("z"); - - parg = PyCArgObject_new(); - if (parg == NULL) - return NULL; - parg->pffi_type = &ffi_type_pointer; - parg->tag = 'z'; - parg->obj = fd->setfunc(&parg->value, value, 0); - if (parg->obj == NULL) { - Py_DECREF(parg); - return NULL; - } - return (PyObject *)parg; - } + if (PyBytes_Check(value)) { + PyCArgObject *parg; + struct fielddesc *fd = _ctypes_get_fielddesc("z"); + + parg = PyCArgObject_new(); + if (parg == NULL) + return NULL; + parg->pffi_type = &ffi_type_pointer; + parg->tag = 'z'; + parg->obj = fd->setfunc(&parg->value, value, 0); + if (parg->obj == NULL) { + Py_DECREF(parg); + return NULL; + } + return (PyObject *)parg; + } /* bytes */ - if (PyByteArray_Check(value)) { - PyCArgObject *parg; - struct fielddesc *fd = _ctypes_get_fielddesc("z"); - - parg = PyCArgObject_new(); - if (parg == NULL) - return NULL; - parg->pffi_type = &ffi_type_pointer; - parg->tag = 'z'; - parg->obj = fd->setfunc(&parg->value, value, 0); - if (parg->obj == NULL) { - Py_DECREF(parg); - return NULL; - } - return (PyObject *)parg; - } + if (PyByteArray_Check(value)) { + PyCArgObject *parg; + struct fielddesc *fd = _ctypes_get_fielddesc("z"); + + parg = PyCArgObject_new(); + if (parg == NULL) + return NULL; + parg->pffi_type = &ffi_type_pointer; + parg->tag = 'z'; + parg->obj = fd->setfunc(&parg->value, value, 0); + if (parg->obj == NULL) { + Py_DECREF(parg); + return NULL; + } + return (PyObject *)parg; + } /* unicode */ - if (PyUnicode_Check(value)) { - PyCArgObject *parg; - struct fielddesc *fd = _ctypes_get_fielddesc("Z"); - - parg = PyCArgObject_new(); - if (parg == NULL) - return NULL; - parg->pffi_type = &ffi_type_pointer; - parg->tag = 'Z'; - parg->obj = fd->setfunc(&parg->value, value, 0); - if (parg->obj == NULL) { - Py_DECREF(parg); - return NULL; - } - return (PyObject *)parg; - } + if (PyUnicode_Check(value)) { + PyCArgObject *parg; + struct fielddesc *fd = _ctypes_get_fielddesc("Z"); + + parg = PyCArgObject_new(); + if (parg == NULL) + return NULL; + parg->pffi_type = &ffi_type_pointer; + parg->tag = 'Z'; + parg->obj = fd->setfunc(&parg->value, value, 0); + if (parg->obj == NULL) { + Py_DECREF(parg); + return NULL; + } + return (PyObject *)parg; + } /* c_void_p instance (or subclass) */ - if (PyObject_IsInstance(value, type)) { - /* c_void_p instances */ - Py_INCREF(value); - return value; - } + if (PyObject_IsInstance(value, type)) { + /* c_void_p instances */ + Py_INCREF(value); + return value; + } /* ctypes array or pointer instance */ - if (ArrayObject_Check(value) || PointerObject_Check(value)) { - /* Any array or pointer is accepted */ - Py_INCREF(value); - return value; - } + if (ArrayObject_Check(value) || PointerObject_Check(value)) { + /* Any array or pointer is accepted */ + Py_INCREF(value); + return value; + } /* byref(...) */ - if (PyCArg_CheckExact(value)) { - /* byref(c_xxx()) */ - PyCArgObject *a = (PyCArgObject *)value; - if (a->tag == 'P') { - Py_INCREF(value); - return value; - } - } + if (PyCArg_CheckExact(value)) { + /* byref(c_xxx()) */ + PyCArgObject *a = (PyCArgObject *)value; + if (a->tag == 'P') { + Py_INCREF(value); + return value; + } + } /* function pointer */ - if (PyCFuncPtrObject_Check(value)) { - PyCArgObject *parg; - PyCFuncPtrObject *func; - func = (PyCFuncPtrObject *)value; - parg = PyCArgObject_new(); - if (parg == NULL) - return NULL; - parg->pffi_type = &ffi_type_pointer; - parg->tag = 'P'; - Py_INCREF(value); - parg->value.p = *(void **)func->b_ptr; - parg->obj = value; - return (PyObject *)parg; - } + if (PyCFuncPtrObject_Check(value)) { + PyCArgObject *parg; + PyCFuncPtrObject *func; + func = (PyCFuncPtrObject *)value; + parg = PyCArgObject_new(); + if (parg == NULL) + return NULL; + parg->pffi_type = &ffi_type_pointer; + parg->tag = 'P'; + Py_INCREF(value); + parg->value.p = *(void **)func->b_ptr; + parg->obj = value; + return (PyObject *)parg; + } /* c_char_p, c_wchar_p */ - stgd = PyObject_stgdict(value); - if (stgd && CDataObject_Check(value) && stgd->proto && PyUnicode_Check(stgd->proto)) { - PyCArgObject *parg; - - switch (_PyUnicode_AsString(stgd->proto)[0]) { - case 'z': /* c_char_p */ - case 'Z': /* c_wchar_p */ - parg = PyCArgObject_new(); - if (parg == NULL) - return NULL; - parg->pffi_type = &ffi_type_pointer; - parg->tag = 'Z'; - Py_INCREF(value); - parg->obj = value; - /* Remember: b_ptr points to where the pointer is stored! */ - parg->value.p = *(void **)(((CDataObject *)value)->b_ptr); - return (PyObject *)parg; - } - } - - as_parameter = PyObject_GetAttrString(value, "_as_parameter_"); - if (as_parameter) { - value = c_void_p_from_param(type, as_parameter); - Py_DECREF(as_parameter); - return value; - } - /* XXX better message */ - PyErr_SetString(PyExc_TypeError, - "wrong type"); - return NULL; + stgd = PyObject_stgdict(value); + if (stgd && CDataObject_Check(value) && stgd->proto && PyUnicode_Check(stgd->proto)) { + PyCArgObject *parg; + + switch (_PyUnicode_AsString(stgd->proto)[0]) { + case 'z': /* c_char_p */ + case 'Z': /* c_wchar_p */ + parg = PyCArgObject_new(); + if (parg == NULL) + return NULL; + parg->pffi_type = &ffi_type_pointer; + parg->tag = 'Z'; + Py_INCREF(value); + parg->obj = value; + /* Remember: b_ptr points to where the pointer is stored! */ + parg->value.p = *(void **)(((CDataObject *)value)->b_ptr); + return (PyObject *)parg; + } + } + + as_parameter = PyObject_GetAttrString(value, "_as_parameter_"); + if (as_parameter) { + value = c_void_p_from_param(type, as_parameter); + Py_DECREF(as_parameter); + return value; + } + /* XXX better message */ + PyErr_SetString(PyExc_TypeError, + "wrong type"); + return NULL; } static PyMethodDef c_void_p_method = { "from_param", c_void_p_from_param, METH_O }; @@ -1718,278 +1718,278 @@ static PyMethodDef c_wchar_p_method = { "from_param", c_wchar_p_from_param, METH_O }; static PyObject *CreateSwappedType(PyTypeObject *type, PyObject *args, PyObject *kwds, - PyObject *proto, struct fielddesc *fmt) + PyObject *proto, struct fielddesc *fmt) { - PyTypeObject *result; - StgDictObject *stgdict; - PyObject *name = PyTuple_GET_ITEM(args, 0); - PyObject *newname; - PyObject *swapped_args; - static PyObject *suffix; - Py_ssize_t i; - - swapped_args = PyTuple_New(PyTuple_GET_SIZE(args)); - if (!swapped_args) - return NULL; + PyTypeObject *result; + StgDictObject *stgdict; + PyObject *name = PyTuple_GET_ITEM(args, 0); + PyObject *newname; + PyObject *swapped_args; + static PyObject *suffix; + Py_ssize_t i; + + swapped_args = PyTuple_New(PyTuple_GET_SIZE(args)); + if (!swapped_args) + return NULL; - if (suffix == NULL) + if (suffix == NULL) #ifdef WORDS_BIGENDIAN - suffix = PyUnicode_InternFromString("_le"); + suffix = PyUnicode_InternFromString("_le"); #else - suffix = PyUnicode_InternFromString("_be"); + suffix = PyUnicode_InternFromString("_be"); #endif - newname = PyUnicode_Concat(name, suffix); - if (newname == NULL) { - return NULL; - } - - PyTuple_SET_ITEM(swapped_args, 0, newname); - for (i=1; iffi_type_pointer = *fmt->pffi_type; - stgdict->align = fmt->pffi_type->alignment; - stgdict->length = 0; - stgdict->size = fmt->pffi_type->size; - stgdict->setfunc = fmt->setfunc_swapped; - stgdict->getfunc = fmt->getfunc_swapped; - - Py_INCREF(proto); - stgdict->proto = proto; - - /* replace the class dict by our updated spam dict */ - if (-1 == PyDict_Update((PyObject *)stgdict, result->tp_dict)) { - Py_DECREF(result); - Py_DECREF((PyObject *)stgdict); - return NULL; - } - Py_DECREF(result->tp_dict); - result->tp_dict = (PyObject *)stgdict; + newname = PyUnicode_Concat(name, suffix); + if (newname == NULL) { + return NULL; + } + + PyTuple_SET_ITEM(swapped_args, 0, newname); + for (i=1; iffi_type_pointer = *fmt->pffi_type; + stgdict->align = fmt->pffi_type->alignment; + stgdict->length = 0; + stgdict->size = fmt->pffi_type->size; + stgdict->setfunc = fmt->setfunc_swapped; + stgdict->getfunc = fmt->getfunc_swapped; + + Py_INCREF(proto); + stgdict->proto = proto; + + /* replace the class dict by our updated spam dict */ + if (-1 == PyDict_Update((PyObject *)stgdict, result->tp_dict)) { + Py_DECREF(result); + Py_DECREF((PyObject *)stgdict); + return NULL; + } + Py_DECREF(result->tp_dict); + result->tp_dict = (PyObject *)stgdict; - return (PyObject *)result; + return (PyObject *)result; } static PyCArgObject * PyCSimpleType_paramfunc(CDataObject *self) { - StgDictObject *dict; - char *fmt; - PyCArgObject *parg; - struct fielddesc *fd; - - dict = PyObject_stgdict((PyObject *)self); - assert(dict); /* Cannot be NULL for CDataObject instances */ - fmt = _PyUnicode_AsString(dict->proto); - assert(fmt); - - fd = _ctypes_get_fielddesc(fmt); - assert(fd); - - parg = PyCArgObject_new(); - if (parg == NULL) - return NULL; - - parg->tag = fmt[0]; - parg->pffi_type = fd->pffi_type; - Py_INCREF(self); - parg->obj = (PyObject *)self; - memcpy(&parg->value, self->b_ptr, self->b_size); - return parg; + StgDictObject *dict; + char *fmt; + PyCArgObject *parg; + struct fielddesc *fd; + + dict = PyObject_stgdict((PyObject *)self); + assert(dict); /* Cannot be NULL for CDataObject instances */ + fmt = _PyUnicode_AsString(dict->proto); + assert(fmt); + + fd = _ctypes_get_fielddesc(fmt); + assert(fd); + + parg = PyCArgObject_new(); + if (parg == NULL) + return NULL; + + parg->tag = fmt[0]; + parg->pffi_type = fd->pffi_type; + Py_INCREF(self); + parg->obj = (PyObject *)self; + memcpy(&parg->value, self->b_ptr, self->b_size); + return parg; } static PyObject * PyCSimpleType_new(PyTypeObject *type, PyObject *args, PyObject *kwds) { - PyTypeObject *result; - StgDictObject *stgdict; - PyObject *proto; - const char *proto_str; - Py_ssize_t proto_len; - PyMethodDef *ml; - struct fielddesc *fmt; - - /* create the new instance (which is a class, - since we are a metatype!) */ - result = (PyTypeObject *)PyType_Type.tp_new(type, args, kwds); - if (result == NULL) - return NULL; - - proto = PyObject_GetAttrString((PyObject *)result, "_type_"); /* new ref */ - if (!proto) { - PyErr_SetString(PyExc_AttributeError, - "class must define a '_type_' attribute"); + PyTypeObject *result; + StgDictObject *stgdict; + PyObject *proto; + const char *proto_str; + Py_ssize_t proto_len; + PyMethodDef *ml; + struct fielddesc *fmt; + + /* create the new instance (which is a class, + since we are a metatype!) */ + result = (PyTypeObject *)PyType_Type.tp_new(type, args, kwds); + if (result == NULL) + return NULL; + + proto = PyObject_GetAttrString((PyObject *)result, "_type_"); /* new ref */ + if (!proto) { + PyErr_SetString(PyExc_AttributeError, + "class must define a '_type_' attribute"); error: - Py_XDECREF(proto); - Py_XDECREF(result); - return NULL; - } - if (PyUnicode_Check(proto)) { - PyObject *v = _PyUnicode_AsDefaultEncodedString(proto, NULL); - if (!v) - goto error; - proto_str = PyBytes_AS_STRING(v); - proto_len = PyBytes_GET_SIZE(v); - } else { - PyErr_SetString(PyExc_TypeError, - "class must define a '_type_' string attribute"); - goto error; - } - if (proto_len != 1) { - PyErr_SetString(PyExc_ValueError, - "class must define a '_type_' attribute " - "which must be a string of length 1"); - goto error; - } - if (!strchr(SIMPLE_TYPE_CHARS, *proto_str)) { - PyErr_Format(PyExc_AttributeError, - "class must define a '_type_' attribute which must be\n" - "a single character string containing one of '%s'.", - SIMPLE_TYPE_CHARS); - goto error; - } - fmt = _ctypes_get_fielddesc(proto_str); - if (fmt == NULL) { - PyErr_Format(PyExc_ValueError, - "_type_ '%s' not supported", proto_str); - goto error; - } - - stgdict = (StgDictObject *)PyObject_CallObject( - (PyObject *)&PyCStgDict_Type, NULL); - if (!stgdict) - goto error; - - stgdict->ffi_type_pointer = *fmt->pffi_type; - stgdict->align = fmt->pffi_type->alignment; - stgdict->length = 0; - stgdict->size = fmt->pffi_type->size; - stgdict->setfunc = fmt->setfunc; - stgdict->getfunc = fmt->getfunc; + Py_XDECREF(proto); + Py_XDECREF(result); + return NULL; + } + if (PyUnicode_Check(proto)) { + PyObject *v = _PyUnicode_AsDefaultEncodedString(proto, NULL); + if (!v) + goto error; + proto_str = PyBytes_AS_STRING(v); + proto_len = PyBytes_GET_SIZE(v); + } else { + PyErr_SetString(PyExc_TypeError, + "class must define a '_type_' string attribute"); + goto error; + } + if (proto_len != 1) { + PyErr_SetString(PyExc_ValueError, + "class must define a '_type_' attribute " + "which must be a string of length 1"); + goto error; + } + if (!strchr(SIMPLE_TYPE_CHARS, *proto_str)) { + PyErr_Format(PyExc_AttributeError, + "class must define a '_type_' attribute which must be\n" + "a single character string containing one of '%s'.", + SIMPLE_TYPE_CHARS); + goto error; + } + fmt = _ctypes_get_fielddesc(proto_str); + if (fmt == NULL) { + PyErr_Format(PyExc_ValueError, + "_type_ '%s' not supported", proto_str); + goto error; + } + + stgdict = (StgDictObject *)PyObject_CallObject( + (PyObject *)&PyCStgDict_Type, NULL); + if (!stgdict) + goto error; + + stgdict->ffi_type_pointer = *fmt->pffi_type; + stgdict->align = fmt->pffi_type->alignment; + stgdict->length = 0; + stgdict->size = fmt->pffi_type->size; + stgdict->setfunc = fmt->setfunc; + stgdict->getfunc = fmt->getfunc; #ifdef WORDS_BIGENDIAN - stgdict->format = _ctypes_alloc_format_string(">", proto_str); + stgdict->format = _ctypes_alloc_format_string(">", proto_str); #else - stgdict->format = _ctypes_alloc_format_string("<", proto_str); + stgdict->format = _ctypes_alloc_format_string("<", proto_str); #endif - if (stgdict->format == NULL) { - Py_DECREF(result); - Py_DECREF(proto); - Py_DECREF((PyObject *)stgdict); - return NULL; - } + if (stgdict->format == NULL) { + Py_DECREF(result); + Py_DECREF(proto); + Py_DECREF((PyObject *)stgdict); + return NULL; + } - stgdict->paramfunc = PyCSimpleType_paramfunc; + stgdict->paramfunc = PyCSimpleType_paramfunc; /* - if (result->tp_base != &Simple_Type) { - stgdict->setfunc = NULL; - stgdict->getfunc = NULL; - } + if (result->tp_base != &Simple_Type) { + stgdict->setfunc = NULL; + stgdict->getfunc = NULL; + } */ - /* This consumes the refcount on proto which we have */ - stgdict->proto = proto; + /* This consumes the refcount on proto which we have */ + stgdict->proto = proto; - /* replace the class dict by our updated spam dict */ - if (-1 == PyDict_Update((PyObject *)stgdict, result->tp_dict)) { - Py_DECREF(result); - Py_DECREF((PyObject *)stgdict); - return NULL; - } - Py_DECREF(result->tp_dict); - result->tp_dict = (PyObject *)stgdict; - - /* Install from_param class methods in ctypes base classes. - Overrides the PyCSimpleType_from_param generic method. - */ - if (result->tp_base == &Simple_Type) { - switch (*proto_str) { - case 'z': /* c_char_p */ - ml = &c_char_p_method; - stgdict->flags |= TYPEFLAG_ISPOINTER; - break; - case 'Z': /* c_wchar_p */ - ml = &c_wchar_p_method; - stgdict->flags |= TYPEFLAG_ISPOINTER; - break; - case 'P': /* c_void_p */ - ml = &c_void_p_method; - stgdict->flags |= TYPEFLAG_ISPOINTER; - break; - case 's': - case 'X': - case 'O': - ml = NULL; - stgdict->flags |= TYPEFLAG_ISPOINTER; - break; - default: - ml = NULL; - break; - } - - if (ml) { - PyObject *meth; - int x; - meth = PyDescr_NewClassMethod(result, ml); - if (!meth) - return NULL; - x = PyDict_SetItemString(result->tp_dict, - ml->ml_name, - meth); - Py_DECREF(meth); - if (x == -1) { - Py_DECREF(result); - return NULL; - } - } - } - - if (type == &PyCSimpleType_Type && fmt->setfunc_swapped && fmt->getfunc_swapped) { - PyObject *swapped = CreateSwappedType(type, args, kwds, - proto, fmt); - StgDictObject *sw_dict; - if (swapped == NULL) { - Py_DECREF(result); - return NULL; - } - sw_dict = PyType_stgdict(swapped); + /* replace the class dict by our updated spam dict */ + if (-1 == PyDict_Update((PyObject *)stgdict, result->tp_dict)) { + Py_DECREF(result); + Py_DECREF((PyObject *)stgdict); + return NULL; + } + Py_DECREF(result->tp_dict); + result->tp_dict = (PyObject *)stgdict; + + /* Install from_param class methods in ctypes base classes. + Overrides the PyCSimpleType_from_param generic method. + */ + if (result->tp_base == &Simple_Type) { + switch (*proto_str) { + case 'z': /* c_char_p */ + ml = &c_char_p_method; + stgdict->flags |= TYPEFLAG_ISPOINTER; + break; + case 'Z': /* c_wchar_p */ + ml = &c_wchar_p_method; + stgdict->flags |= TYPEFLAG_ISPOINTER; + break; + case 'P': /* c_void_p */ + ml = &c_void_p_method; + stgdict->flags |= TYPEFLAG_ISPOINTER; + break; + case 's': + case 'X': + case 'O': + ml = NULL; + stgdict->flags |= TYPEFLAG_ISPOINTER; + break; + default: + ml = NULL; + break; + } + + if (ml) { + PyObject *meth; + int x; + meth = PyDescr_NewClassMethod(result, ml); + if (!meth) + return NULL; + x = PyDict_SetItemString(result->tp_dict, + ml->ml_name, + meth); + Py_DECREF(meth); + if (x == -1) { + Py_DECREF(result); + return NULL; + } + } + } + + if (type == &PyCSimpleType_Type && fmt->setfunc_swapped && fmt->getfunc_swapped) { + PyObject *swapped = CreateSwappedType(type, args, kwds, + proto, fmt); + StgDictObject *sw_dict; + if (swapped == NULL) { + Py_DECREF(result); + return NULL; + } + sw_dict = PyType_stgdict(swapped); #ifdef WORDS_BIGENDIAN - PyObject_SetAttrString((PyObject *)result, "__ctype_le__", swapped); - PyObject_SetAttrString((PyObject *)result, "__ctype_be__", (PyObject *)result); - PyObject_SetAttrString(swapped, "__ctype_be__", (PyObject *)result); - PyObject_SetAttrString(swapped, "__ctype_le__", swapped); - /* We are creating the type for the OTHER endian */ - sw_dict->format = _ctypes_alloc_format_string("<", stgdict->format+1); + PyObject_SetAttrString((PyObject *)result, "__ctype_le__", swapped); + PyObject_SetAttrString((PyObject *)result, "__ctype_be__", (PyObject *)result); + PyObject_SetAttrString(swapped, "__ctype_be__", (PyObject *)result); + PyObject_SetAttrString(swapped, "__ctype_le__", swapped); + /* We are creating the type for the OTHER endian */ + sw_dict->format = _ctypes_alloc_format_string("<", stgdict->format+1); #else - PyObject_SetAttrString((PyObject *)result, "__ctype_be__", swapped); - PyObject_SetAttrString((PyObject *)result, "__ctype_le__", (PyObject *)result); - PyObject_SetAttrString(swapped, "__ctype_le__", (PyObject *)result); - PyObject_SetAttrString(swapped, "__ctype_be__", swapped); - /* We are creating the type for the OTHER endian */ - sw_dict->format = _ctypes_alloc_format_string(">", stgdict->format+1); + PyObject_SetAttrString((PyObject *)result, "__ctype_be__", swapped); + PyObject_SetAttrString((PyObject *)result, "__ctype_le__", (PyObject *)result); + PyObject_SetAttrString(swapped, "__ctype_le__", (PyObject *)result); + PyObject_SetAttrString(swapped, "__ctype_be__", swapped); + /* We are creating the type for the OTHER endian */ + sw_dict->format = _ctypes_alloc_format_string(">", stgdict->format+1); #endif - Py_DECREF(swapped); - if (PyErr_Occurred()) { - Py_DECREF(result); - return NULL; - } - }; + Py_DECREF(swapped); + if (PyErr_Occurred()) { + Py_DECREF(result); + return NULL; + } + }; - return (PyObject *)result; + return (PyObject *)result; } /* @@ -1999,101 +1999,101 @@ static PyObject * PyCSimpleType_from_param(PyObject *type, PyObject *value) { - StgDictObject *dict; - char *fmt; - PyCArgObject *parg; - struct fielddesc *fd; - PyObject *as_parameter; - - /* If the value is already an instance of the requested type, - we can use it as is */ - if (1 == PyObject_IsInstance(value, type)) { - Py_INCREF(value); - return value; - } - - dict = PyType_stgdict(type); - assert(dict); - - /* I think we can rely on this being a one-character string */ - fmt = _PyUnicode_AsString(dict->proto); - assert(fmt); - - fd = _ctypes_get_fielddesc(fmt); - assert(fd); - - parg = PyCArgObject_new(); - if (parg == NULL) - return NULL; - - parg->tag = fmt[0]; - parg->pffi_type = fd->pffi_type; - parg->obj = fd->setfunc(&parg->value, value, 0); - if (parg->obj) - return (PyObject *)parg; - PyErr_Clear(); - Py_DECREF(parg); - - as_parameter = PyObject_GetAttrString(value, "_as_parameter_"); - if (as_parameter) { - value = PyCSimpleType_from_param(type, as_parameter); - Py_DECREF(as_parameter); - return value; - } - PyErr_SetString(PyExc_TypeError, - "wrong type"); - return NULL; + StgDictObject *dict; + char *fmt; + PyCArgObject *parg; + struct fielddesc *fd; + PyObject *as_parameter; + + /* If the value is already an instance of the requested type, + we can use it as is */ + if (1 == PyObject_IsInstance(value, type)) { + Py_INCREF(value); + return value; + } + + dict = PyType_stgdict(type); + assert(dict); + + /* I think we can rely on this being a one-character string */ + fmt = _PyUnicode_AsString(dict->proto); + assert(fmt); + + fd = _ctypes_get_fielddesc(fmt); + assert(fd); + + parg = PyCArgObject_new(); + if (parg == NULL) + return NULL; + + parg->tag = fmt[0]; + parg->pffi_type = fd->pffi_type; + parg->obj = fd->setfunc(&parg->value, value, 0); + if (parg->obj) + return (PyObject *)parg; + PyErr_Clear(); + Py_DECREF(parg); + + as_parameter = PyObject_GetAttrString(value, "_as_parameter_"); + if (as_parameter) { + value = PyCSimpleType_from_param(type, as_parameter); + Py_DECREF(as_parameter); + return value; + } + PyErr_SetString(PyExc_TypeError, + "wrong type"); + return NULL; } static PyMethodDef PyCSimpleType_methods[] = { - { "from_param", PyCSimpleType_from_param, METH_O, from_param_doc }, - { "from_address", CDataType_from_address, METH_O, from_address_doc }, - { "from_buffer", CDataType_from_buffer, METH_VARARGS, from_buffer_doc, }, - { "from_buffer_copy", CDataType_from_buffer_copy, METH_VARARGS, from_buffer_copy_doc, }, - { "in_dll", CDataType_in_dll, METH_VARARGS, in_dll_doc}, - { NULL, NULL }, + { "from_param", PyCSimpleType_from_param, METH_O, from_param_doc }, + { "from_address", CDataType_from_address, METH_O, from_address_doc }, + { "from_buffer", CDataType_from_buffer, METH_VARARGS, from_buffer_doc, }, + { "from_buffer_copy", CDataType_from_buffer_copy, METH_VARARGS, from_buffer_copy_doc, }, + { "in_dll", CDataType_in_dll, METH_VARARGS, in_dll_doc}, + { NULL, NULL }, }; PyTypeObject PyCSimpleType_Type = { - PyVarObject_HEAD_INIT(NULL, 0) - "_ctypes.PyCSimpleType", /* tp_name */ - 0, /* tp_basicsize */ - 0, /* tp_itemsize */ - 0, /* tp_dealloc */ - 0, /* tp_print */ - 0, /* tp_getattr */ - 0, /* tp_setattr */ - 0, /* tp_reserved */ - 0, /* tp_repr */ - 0, /* tp_as_number */ - &CDataType_as_sequence, /* tp_as_sequence */ - 0, /* tp_as_mapping */ - 0, /* tp_hash */ - 0, /* tp_call */ - 0, /* tp_str */ - 0, /* tp_getattro */ - 0, /* tp_setattro */ - 0, /* tp_as_buffer */ - Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */ - "metatype for the PyCSimpleType Objects", /* tp_doc */ - 0, /* tp_traverse */ - 0, /* tp_clear */ - 0, /* tp_richcompare */ - 0, /* tp_weaklistoffset */ - 0, /* tp_iter */ - 0, /* tp_iternext */ - PyCSimpleType_methods, /* tp_methods */ - 0, /* tp_members */ - 0, /* tp_getset */ - 0, /* tp_base */ - 0, /* tp_dict */ - 0, /* tp_descr_get */ - 0, /* tp_descr_set */ - 0, /* tp_dictoffset */ - 0, /* tp_init */ - 0, /* tp_alloc */ - PyCSimpleType_new, /* tp_new */ - 0, /* tp_free */ + PyVarObject_HEAD_INIT(NULL, 0) + "_ctypes.PyCSimpleType", /* tp_name */ + 0, /* tp_basicsize */ + 0, /* tp_itemsize */ + 0, /* tp_dealloc */ + 0, /* tp_print */ + 0, /* tp_getattr */ + 0, /* tp_setattr */ + 0, /* tp_reserved */ + 0, /* tp_repr */ + 0, /* tp_as_number */ + &CDataType_as_sequence, /* tp_as_sequence */ + 0, /* tp_as_mapping */ + 0, /* tp_hash */ + 0, /* tp_call */ + 0, /* tp_str */ + 0, /* tp_getattro */ + 0, /* tp_setattro */ + 0, /* tp_as_buffer */ + Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */ + "metatype for the PyCSimpleType Objects", /* tp_doc */ + 0, /* tp_traverse */ + 0, /* tp_clear */ + 0, /* tp_richcompare */ + 0, /* tp_weaklistoffset */ + 0, /* tp_iter */ + 0, /* tp_iternext */ + PyCSimpleType_methods, /* tp_methods */ + 0, /* tp_members */ + 0, /* tp_getset */ + 0, /* tp_base */ + 0, /* tp_dict */ + 0, /* tp_descr_get */ + 0, /* tp_descr_set */ + 0, /* tp_dictoffset */ + 0, /* tp_init */ + 0, /* tp_alloc */ + PyCSimpleType_new, /* tp_new */ + 0, /* tp_free */ }; /******************************************************************/ @@ -2104,217 +2104,217 @@ static PyObject * converters_from_argtypes(PyObject *ob) { - PyObject *converters; - Py_ssize_t i; - Py_ssize_t nArgs; - - ob = PySequence_Tuple(ob); /* new reference */ - if (!ob) { - PyErr_SetString(PyExc_TypeError, - "_argtypes_ must be a sequence of types"); - return NULL; - } - - nArgs = PyTuple_GET_SIZE(ob); - converters = PyTuple_New(nArgs); - if (!converters) - return NULL; - - /* I have to check if this is correct. Using c_char, which has a size - of 1, will be assumed to be pushed as only one byte! - Aren't these promoted to integers by the C compiler and pushed as 4 bytes? - */ - - for (i = 0; i < nArgs; ++i) { - PyObject *tp = PyTuple_GET_ITEM(ob, i); - PyObject *cnv = PyObject_GetAttrString(tp, "from_param"); - if (!cnv) - goto argtypes_error_1; - PyTuple_SET_ITEM(converters, i, cnv); - } - Py_DECREF(ob); - return converters; + PyObject *converters; + Py_ssize_t i; + Py_ssize_t nArgs; + + ob = PySequence_Tuple(ob); /* new reference */ + if (!ob) { + PyErr_SetString(PyExc_TypeError, + "_argtypes_ must be a sequence of types"); + return NULL; + } + + nArgs = PyTuple_GET_SIZE(ob); + converters = PyTuple_New(nArgs); + if (!converters) + return NULL; + + /* I have to check if this is correct. Using c_char, which has a size + of 1, will be assumed to be pushed as only one byte! + Aren't these promoted to integers by the C compiler and pushed as 4 bytes? + */ + + for (i = 0; i < nArgs; ++i) { + PyObject *tp = PyTuple_GET_ITEM(ob, i); + PyObject *cnv = PyObject_GetAttrString(tp, "from_param"); + if (!cnv) + goto argtypes_error_1; + PyTuple_SET_ITEM(converters, i, cnv); + } + Py_DECREF(ob); + return converters; argtypes_error_1: - Py_XDECREF(converters); - Py_DECREF(ob); - PyErr_Format(PyExc_TypeError, - "item %zd in _argtypes_ has no from_param method", - i+1); - return NULL; + Py_XDECREF(converters); + Py_DECREF(ob); + PyErr_Format(PyExc_TypeError, + "item %zd in _argtypes_ has no from_param method", + i+1); + return NULL; } static int make_funcptrtype_dict(StgDictObject *stgdict) { - PyObject *ob; - PyObject *converters = NULL; + PyObject *ob; + PyObject *converters = NULL; - stgdict->align = _ctypes_get_fielddesc("P")->pffi_type->alignment; - stgdict->length = 1; - stgdict->size = sizeof(void *); - stgdict->setfunc = NULL; - stgdict->getfunc = NULL; - stgdict->ffi_type_pointer = ffi_type_pointer; - - ob = PyDict_GetItemString((PyObject *)stgdict, "_flags_"); - if (!ob || !PyLong_Check(ob)) { - PyErr_SetString(PyExc_TypeError, - "class must define _flags_ which must be an integer"); - return -1; - } - stgdict->flags = PyLong_AS_LONG(ob) | TYPEFLAG_ISPOINTER; - - /* _argtypes_ is optional... */ - ob = PyDict_GetItemString((PyObject *)stgdict, "_argtypes_"); - if (ob) { - converters = converters_from_argtypes(ob); - if (!converters) - goto error; - Py_INCREF(ob); - stgdict->argtypes = ob; - stgdict->converters = converters; - } - - ob = PyDict_GetItemString((PyObject *)stgdict, "_restype_"); - if (ob) { - if (ob != Py_None && !PyType_stgdict(ob) && !PyCallable_Check(ob)) { - PyErr_SetString(PyExc_TypeError, - "_restype_ must be a type, a callable, or None"); - return -1; - } - Py_INCREF(ob); - stgdict->restype = ob; - stgdict->checker = PyObject_GetAttrString(ob, "_check_retval_"); - if (stgdict->checker == NULL) - PyErr_Clear(); - } + stgdict->align = _ctypes_get_fielddesc("P")->pffi_type->alignment; + stgdict->length = 1; + stgdict->size = sizeof(void *); + stgdict->setfunc = NULL; + stgdict->getfunc = NULL; + stgdict->ffi_type_pointer = ffi_type_pointer; + + ob = PyDict_GetItemString((PyObject *)stgdict, "_flags_"); + if (!ob || !PyLong_Check(ob)) { + PyErr_SetString(PyExc_TypeError, + "class must define _flags_ which must be an integer"); + return -1; + } + stgdict->flags = PyLong_AS_LONG(ob) | TYPEFLAG_ISPOINTER; + + /* _argtypes_ is optional... */ + ob = PyDict_GetItemString((PyObject *)stgdict, "_argtypes_"); + if (ob) { + converters = converters_from_argtypes(ob); + if (!converters) + goto error; + Py_INCREF(ob); + stgdict->argtypes = ob; + stgdict->converters = converters; + } + + ob = PyDict_GetItemString((PyObject *)stgdict, "_restype_"); + if (ob) { + if (ob != Py_None && !PyType_stgdict(ob) && !PyCallable_Check(ob)) { + PyErr_SetString(PyExc_TypeError, + "_restype_ must be a type, a callable, or None"); + return -1; + } + Py_INCREF(ob); + stgdict->restype = ob; + stgdict->checker = PyObject_GetAttrString(ob, "_check_retval_"); + if (stgdict->checker == NULL) + PyErr_Clear(); + } /* XXX later, maybe. - ob = PyDict_GetItemString((PyObject *)stgdict, "_errcheck_"); - if (ob) { - if (!PyCallable_Check(ob)) { - PyErr_SetString(PyExc_TypeError, - "_errcheck_ must be callable"); - return -1; - } - Py_INCREF(ob); - stgdict->errcheck = ob; - } + ob = PyDict_GetItemString((PyObject *)stgdict, "_errcheck_"); + if (ob) { + if (!PyCallable_Check(ob)) { + PyErr_SetString(PyExc_TypeError, + "_errcheck_ must be callable"); + return -1; + } + Py_INCREF(ob); + stgdict->errcheck = ob; + } */ - return 0; + return 0; error: - Py_XDECREF(converters); - return -1; + Py_XDECREF(converters); + return -1; } static PyCArgObject * PyCFuncPtrType_paramfunc(CDataObject *self) { - PyCArgObject *parg; - - parg = PyCArgObject_new(); - if (parg == NULL) - return NULL; - - parg->tag = 'P'; - parg->pffi_type = &ffi_type_pointer; - Py_INCREF(self); - parg->obj = (PyObject *)self; - parg->value.p = *(void **)self->b_ptr; - return parg; + PyCArgObject *parg; + + parg = PyCArgObject_new(); + if (parg == NULL) + return NULL; + + parg->tag = 'P'; + parg->pffi_type = &ffi_type_pointer; + Py_INCREF(self); + parg->obj = (PyObject *)self; + parg->value.p = *(void **)self->b_ptr; + return parg; } static PyObject * PyCFuncPtrType_new(PyTypeObject *type, PyObject *args, PyObject *kwds) { - PyTypeObject *result; - StgDictObject *stgdict; + PyTypeObject *result; + StgDictObject *stgdict; - stgdict = (StgDictObject *)PyObject_CallObject( - (PyObject *)&PyCStgDict_Type, NULL); - if (!stgdict) - return NULL; - - stgdict->paramfunc = PyCFuncPtrType_paramfunc; - /* We do NOT expose the function signature in the format string. It - is impossible, generally, because the only requirement for the - argtypes items is that they have a .from_param method - we do not - know the types of the arguments (although, in practice, most - argtypes would be a ctypes type). - */ - stgdict->format = _ctypes_alloc_format_string(NULL, "X{}"); - stgdict->flags |= TYPEFLAG_ISPOINTER; - - /* create the new instance (which is a class, - since we are a metatype!) */ - result = (PyTypeObject *)PyType_Type.tp_new(type, args, kwds); - if (result == NULL) { - Py_DECREF((PyObject *)stgdict); - return NULL; - } - - /* replace the class dict by our updated storage dict */ - if (-1 == PyDict_Update((PyObject *)stgdict, result->tp_dict)) { - Py_DECREF(result); - Py_DECREF((PyObject *)stgdict); - return NULL; - } - Py_DECREF(result->tp_dict); - result->tp_dict = (PyObject *)stgdict; - - if (-1 == make_funcptrtype_dict(stgdict)) { - Py_DECREF(result); - return NULL; - } + stgdict = (StgDictObject *)PyObject_CallObject( + (PyObject *)&PyCStgDict_Type, NULL); + if (!stgdict) + return NULL; + + stgdict->paramfunc = PyCFuncPtrType_paramfunc; + /* We do NOT expose the function signature in the format string. It + is impossible, generally, because the only requirement for the + argtypes items is that they have a .from_param method - we do not + know the types of the arguments (although, in practice, most + argtypes would be a ctypes type). + */ + stgdict->format = _ctypes_alloc_format_string(NULL, "X{}"); + stgdict->flags |= TYPEFLAG_ISPOINTER; + + /* create the new instance (which is a class, + since we are a metatype!) */ + result = (PyTypeObject *)PyType_Type.tp_new(type, args, kwds); + if (result == NULL) { + Py_DECREF((PyObject *)stgdict); + return NULL; + } + + /* replace the class dict by our updated storage dict */ + if (-1 == PyDict_Update((PyObject *)stgdict, result->tp_dict)) { + Py_DECREF(result); + Py_DECREF((PyObject *)stgdict); + return NULL; + } + Py_DECREF(result->tp_dict); + result->tp_dict = (PyObject *)stgdict; + + if (-1 == make_funcptrtype_dict(stgdict)) { + Py_DECREF(result); + return NULL; + } - return (PyObject *)result; + return (PyObject *)result; } PyTypeObject PyCFuncPtrType_Type = { - PyVarObject_HEAD_INIT(NULL, 0) - "_ctypes.PyCFuncPtrType", /* tp_name */ - 0, /* tp_basicsize */ - 0, /* tp_itemsize */ - 0, /* tp_dealloc */ - 0, /* tp_print */ - 0, /* tp_getattr */ - 0, /* tp_setattr */ - 0, /* tp_reserved */ - 0, /* tp_repr */ - 0, /* tp_as_number */ - &CDataType_as_sequence, /* tp_as_sequence */ - 0, /* tp_as_mapping */ - 0, /* tp_hash */ - 0, /* tp_call */ - 0, /* tp_str */ - 0, /* tp_getattro */ - 0, /* tp_setattro */ - 0, /* tp_as_buffer */ - Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC, /* tp_flags */ - "metatype for C function pointers", /* tp_doc */ - (traverseproc)CDataType_traverse, /* tp_traverse */ - (inquiry)CDataType_clear, /* tp_clear */ - 0, /* tp_richcompare */ - 0, /* tp_weaklistoffset */ - 0, /* tp_iter */ - 0, /* tp_iternext */ - CDataType_methods, /* tp_methods */ - 0, /* tp_members */ - 0, /* tp_getset */ - 0, /* tp_base */ - 0, /* tp_dict */ - 0, /* tp_descr_get */ - 0, /* tp_descr_set */ - 0, /* tp_dictoffset */ - 0, /* tp_init */ - 0, /* tp_alloc */ - PyCFuncPtrType_new, /* tp_new */ - 0, /* tp_free */ + PyVarObject_HEAD_INIT(NULL, 0) + "_ctypes.PyCFuncPtrType", /* tp_name */ + 0, /* tp_basicsize */ + 0, /* tp_itemsize */ + 0, /* tp_dealloc */ + 0, /* tp_print */ + 0, /* tp_getattr */ + 0, /* tp_setattr */ + 0, /* tp_reserved */ + 0, /* tp_repr */ + 0, /* tp_as_number */ + &CDataType_as_sequence, /* tp_as_sequence */ + 0, /* tp_as_mapping */ + 0, /* tp_hash */ + 0, /* tp_call */ + 0, /* tp_str */ + 0, /* tp_getattro */ + 0, /* tp_setattro */ + 0, /* tp_as_buffer */ + Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC, /* tp_flags */ + "metatype for C function pointers", /* tp_doc */ + (traverseproc)CDataType_traverse, /* tp_traverse */ + (inquiry)CDataType_clear, /* tp_clear */ + 0, /* tp_richcompare */ + 0, /* tp_weaklistoffset */ + 0, /* tp_iter */ + 0, /* tp_iternext */ + CDataType_methods, /* tp_methods */ + 0, /* tp_members */ + 0, /* tp_getset */ + 0, /* tp_base */ + 0, /* tp_dict */ + 0, /* tp_descr_get */ + 0, /* tp_descr_set */ + 0, /* tp_dictoffset */ + 0, /* tp_init */ + 0, /* tp_alloc */ + PyCFuncPtrType_new, /* tp_new */ + 0, /* tp_free */ }; - + /***************************************************************** * Code to keep needed objects alive */ @@ -2322,46 +2322,46 @@ static CDataObject * PyCData_GetContainer(CDataObject *self) { - while (self->b_base) - self = self->b_base; - if (self->b_objects == NULL) { - if (self->b_length) { - self->b_objects = PyDict_New(); - } else { - Py_INCREF(Py_None); - self->b_objects = Py_None; - } - } - return self; + while (self->b_base) + self = self->b_base; + if (self->b_objects == NULL) { + if (self->b_length) { + self->b_objects = PyDict_New(); + } else { + Py_INCREF(Py_None); + self->b_objects = Py_None; + } + } + return self; } static PyObject * GetKeepedObjects(CDataObject *target) { - return PyCData_GetContainer(target)->b_objects; + return PyCData_GetContainer(target)->b_objects; } static PyObject * unique_key(CDataObject *target, Py_ssize_t index) { - char string[256]; - char *cp = string; - size_t bytes_left; - - assert(sizeof(string) - 1 > sizeof(Py_ssize_t) * 2); - cp += sprintf(cp, "%x", Py_SAFE_DOWNCAST(index, Py_ssize_t, int)); - while (target->b_base) { - bytes_left = sizeof(string) - (cp - string) - 1; - /* Hex format needs 2 characters per byte */ - if (bytes_left < sizeof(Py_ssize_t) * 2) { - PyErr_SetString(PyExc_ValueError, - "ctypes object structure too deep"); - return NULL; - } - cp += sprintf(cp, ":%x", Py_SAFE_DOWNCAST(target->b_index, Py_ssize_t, int)); - target = target->b_base; - } - return PyUnicode_FromStringAndSize(string, cp-string); + char string[256]; + char *cp = string; + size_t bytes_left; + + assert(sizeof(string) - 1 > sizeof(Py_ssize_t) * 2); + cp += sprintf(cp, "%x", Py_SAFE_DOWNCAST(index, Py_ssize_t, int)); + while (target->b_base) { + bytes_left = sizeof(string) - (cp - string) - 1; + /* Hex format needs 2 characters per byte */ + if (bytes_left < sizeof(Py_ssize_t) * 2) { + PyErr_SetString(PyExc_ValueError, + "ctypes object structure too deep"); + return NULL; + } + cp += sprintf(cp, ":%x", Py_SAFE_DOWNCAST(target->b_index, Py_ssize_t, int)); + target = target->b_base; + } + return PyUnicode_FromStringAndSize(string, cp-string); } /* @@ -2385,30 +2385,30 @@ static int KeepRef(CDataObject *target, Py_ssize_t index, PyObject *keep) { - int result; - CDataObject *ob; - PyObject *key; + int result; + CDataObject *ob; + PyObject *key; /* Optimization: no need to store None */ - if (keep == Py_None) { - Py_DECREF(Py_None); - return 0; - } - ob = PyCData_GetContainer(target); - if (ob->b_objects == NULL || !PyDict_CheckExact(ob->b_objects)) { - Py_XDECREF(ob->b_objects); - ob->b_objects = keep; /* refcount consumed */ - return 0; - } - key = unique_key(target, index); - if (key == NULL) { - Py_DECREF(keep); - return -1; - } - result = PyDict_SetItem(ob->b_objects, key, keep); - Py_DECREF(key); - Py_DECREF(keep); - return result; + if (keep == Py_None) { + Py_DECREF(Py_None); + return 0; + } + ob = PyCData_GetContainer(target); + if (ob->b_objects == NULL || !PyDict_CheckExact(ob->b_objects)) { + Py_XDECREF(ob->b_objects); + ob->b_objects = keep; /* refcount consumed */ + return 0; + } + key = unique_key(target, index); + if (key == NULL) { + Py_DECREF(keep); + return -1; + } + result = PyDict_SetItem(ob->b_objects, key, keep); + Py_DECREF(key); + Py_DECREF(keep); + return result; } /******************************************************************/ @@ -2418,75 +2418,75 @@ static int PyCData_traverse(CDataObject *self, visitproc visit, void *arg) { - Py_VISIT(self->b_objects); - Py_VISIT((PyObject *)self->b_base); - return 0; + Py_VISIT(self->b_objects); + Py_VISIT((PyObject *)self->b_base); + return 0; } static int PyCData_clear(CDataObject *self) { - StgDictObject *dict = PyObject_stgdict((PyObject *)self); - assert(dict); /* Cannot be NULL for CDataObject instances */ - Py_CLEAR(self->b_objects); - if ((self->b_needsfree) - && ((size_t)dict->size > sizeof(self->b_value))) - PyMem_Free(self->b_ptr); - self->b_ptr = NULL; - Py_CLEAR(self->b_base); - return 0; + StgDictObject *dict = PyObject_stgdict((PyObject *)self); + assert(dict); /* Cannot be NULL for CDataObject instances */ + Py_CLEAR(self->b_objects); + if ((self->b_needsfree) + && ((size_t)dict->size > sizeof(self->b_value))) + PyMem_Free(self->b_ptr); + self->b_ptr = NULL; + Py_CLEAR(self->b_base); + return 0; } static void PyCData_dealloc(PyObject *self) { - PyCData_clear((CDataObject *)self); - Py_TYPE(self)->tp_free(self); + PyCData_clear((CDataObject *)self); + Py_TYPE(self)->tp_free(self); } static PyMemberDef PyCData_members[] = { - { "_b_base_", T_OBJECT, - offsetof(CDataObject, b_base), READONLY, - "the base object" }, - { "_b_needsfree_", T_INT, - offsetof(CDataObject, b_needsfree), READONLY, - "whether the object owns the memory or not" }, - { "_objects", T_OBJECT, - offsetof(CDataObject, b_objects), READONLY, - "internal objects tree (NEVER CHANGE THIS OBJECT!)"}, - { NULL }, + { "_b_base_", T_OBJECT, + offsetof(CDataObject, b_base), READONLY, + "the base object" }, + { "_b_needsfree_", T_INT, + offsetof(CDataObject, b_needsfree), READONLY, + "whether the object owns the memory or not" }, + { "_objects", T_OBJECT, + offsetof(CDataObject, b_objects), READONLY, + "internal objects tree (NEVER CHANGE THIS OBJECT!)"}, + { NULL }, }; static int PyCData_NewGetBuffer(PyObject *_self, Py_buffer *view, int flags) { - CDataObject *self = (CDataObject *)_self; - StgDictObject *dict = PyObject_stgdict(_self); - Py_ssize_t i; - - if (view == NULL) return 0; - - view->buf = self->b_ptr; - view->obj = _self; - Py_INCREF(_self); - view->len = self->b_size; - view->readonly = 0; - /* use default format character if not set */ - view->format = dict->format ? dict->format : "B"; - view->ndim = dict->ndim; - view->shape = dict->shape; - view->itemsize = self->b_size; - for (i = 0; i < view->ndim; ++i) { - view->itemsize /= dict->shape[i]; - } - view->strides = NULL; - view->suboffsets = NULL; - view->internal = NULL; - return 0; + CDataObject *self = (CDataObject *)_self; + StgDictObject *dict = PyObject_stgdict(_self); + Py_ssize_t i; + + if (view == NULL) return 0; + + view->buf = self->b_ptr; + view->obj = _self; + Py_INCREF(_self); + view->len = self->b_size; + view->readonly = 0; + /* use default format character if not set */ + view->format = dict->format ? dict->format : "B"; + view->ndim = dict->ndim; + view->shape = dict->shape; + view->itemsize = self->b_size; + for (i = 0; i < view->ndim; ++i) { + view->itemsize /= dict->shape[i]; + } + view->strides = NULL; + view->suboffsets = NULL; + view->internal = NULL; + return 0; } static PyBufferProcs PyCData_as_buffer = { - PyCData_NewGetBuffer, - NULL, + PyCData_NewGetBuffer, + NULL, }; /* @@ -2495,47 +2495,47 @@ static long PyCData_nohash(PyObject *self) { - PyErr_SetString(PyExc_TypeError, "unhashable type"); - return -1; + PyErr_SetString(PyExc_TypeError, "unhashable type"); + return -1; } static PyObject * PyCData_reduce(PyObject *_self, PyObject *args) { - CDataObject *self = (CDataObject *)_self; + CDataObject *self = (CDataObject *)_self; - if (PyObject_stgdict(_self)->flags & (TYPEFLAG_ISPOINTER|TYPEFLAG_HASPOINTER)) { - PyErr_SetString(PyExc_ValueError, - "ctypes objects containing pointers cannot be pickled"); - return NULL; - } - return Py_BuildValue("O(O(NN))", - _unpickle, - Py_TYPE(_self), - PyObject_GetAttrString(_self, "__dict__"), - PyBytes_FromStringAndSize(self->b_ptr, self->b_size)); + if (PyObject_stgdict(_self)->flags & (TYPEFLAG_ISPOINTER|TYPEFLAG_HASPOINTER)) { + PyErr_SetString(PyExc_ValueError, + "ctypes objects containing pointers cannot be pickled"); + return NULL; + } + return Py_BuildValue("O(O(NN))", + _unpickle, + Py_TYPE(_self), + PyObject_GetAttrString(_self, "__dict__"), + PyBytes_FromStringAndSize(self->b_ptr, self->b_size)); } static PyObject * PyCData_setstate(PyObject *_self, PyObject *args) { - void *data; - Py_ssize_t len; - int res; - PyObject *dict, *mydict; - CDataObject *self = (CDataObject *)_self; - if (!PyArg_ParseTuple(args, "Os#", &dict, &data, &len)) - return NULL; - if (len > self->b_size) - len = self->b_size; - memmove(self->b_ptr, data, len); - mydict = PyObject_GetAttrString(_self, "__dict__"); - res = PyDict_Update(mydict, dict); - Py_DECREF(mydict); - if (res == -1) - return NULL; - Py_INCREF(Py_None); - return Py_None; + void *data; + Py_ssize_t len; + int res; + PyObject *dict, *mydict; + CDataObject *self = (CDataObject *)_self; + if (!PyArg_ParseTuple(args, "Os#", &dict, &data, &len)) + return NULL; + if (len > self->b_size) + len = self->b_size; + memmove(self->b_ptr, data, len); + mydict = PyObject_GetAttrString(_self, "__dict__"); + res = PyDict_Update(mydict, dict); + Py_DECREF(mydict); + if (res == -1) + return NULL; + Py_INCREF(Py_None); + return Py_None; } /* @@ -2544,124 +2544,124 @@ static PyObject * PyCData_from_outparam(PyObject *self, PyObject *args) { - Py_INCREF(self); - return self; + Py_INCREF(self); + return self; } static PyMethodDef PyCData_methods[] = { - { "__ctypes_from_outparam__", PyCData_from_outparam, METH_NOARGS, }, - { "__reduce__", PyCData_reduce, METH_NOARGS, }, - { "__setstate__", PyCData_setstate, METH_VARARGS, }, - { NULL, NULL }, + { "__ctypes_from_outparam__", PyCData_from_outparam, METH_NOARGS, }, + { "__reduce__", PyCData_reduce, METH_NOARGS, }, + { "__setstate__", PyCData_setstate, METH_VARARGS, }, + { NULL, NULL }, }; PyTypeObject PyCData_Type = { - PyVarObject_HEAD_INIT(NULL, 0) - "_ctypes._CData", - sizeof(CDataObject), /* tp_basicsize */ - 0, /* tp_itemsize */ - PyCData_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 */ - PyCData_nohash, /* tp_hash */ - 0, /* tp_call */ - 0, /* tp_str */ - 0, /* tp_getattro */ - 0, /* tp_setattro */ - &PyCData_as_buffer, /* tp_as_buffer */ - Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */ - "XXX to be provided", /* tp_doc */ - (traverseproc)PyCData_traverse, /* tp_traverse */ - (inquiry)PyCData_clear, /* tp_clear */ - 0, /* tp_richcompare */ - 0, /* tp_weaklistoffset */ - 0, /* tp_iter */ - 0, /* tp_iternext */ - PyCData_methods, /* tp_methods */ - PyCData_members, /* tp_members */ - 0, /* tp_getset */ - 0, /* tp_base */ - 0, /* tp_dict */ - 0, /* tp_descr_get */ - 0, /* tp_descr_set */ - 0, /* tp_dictoffset */ - 0, /* tp_init */ - 0, /* tp_alloc */ - 0, /* tp_new */ - 0, /* tp_free */ + PyVarObject_HEAD_INIT(NULL, 0) + "_ctypes._CData", + sizeof(CDataObject), /* tp_basicsize */ + 0, /* tp_itemsize */ + PyCData_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 */ + PyCData_nohash, /* tp_hash */ + 0, /* tp_call */ + 0, /* tp_str */ + 0, /* tp_getattro */ + 0, /* tp_setattro */ + &PyCData_as_buffer, /* tp_as_buffer */ + Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */ + "XXX to be provided", /* tp_doc */ + (traverseproc)PyCData_traverse, /* tp_traverse */ + (inquiry)PyCData_clear, /* tp_clear */ + 0, /* tp_richcompare */ + 0, /* tp_weaklistoffset */ + 0, /* tp_iter */ + 0, /* tp_iternext */ + PyCData_methods, /* tp_methods */ + PyCData_members, /* tp_members */ + 0, /* tp_getset */ + 0, /* tp_base */ + 0, /* tp_dict */ + 0, /* tp_descr_get */ + 0, /* tp_descr_set */ + 0, /* tp_dictoffset */ + 0, /* tp_init */ + 0, /* tp_alloc */ + 0, /* tp_new */ + 0, /* tp_free */ }; static int PyCData_MallocBuffer(CDataObject *obj, StgDictObject *dict) { - if ((size_t)dict->size <= sizeof(obj->b_value)) { - /* No need to call malloc, can use the default buffer */ - obj->b_ptr = (char *)&obj->b_value; - /* The b_needsfree flag does not mean that we actually did - call PyMem_Malloc to allocate the memory block; instead it - means we are the *owner* of the memory and are responsible - for freeing resources associated with the memory. This is - also the reason that b_needsfree is exposed to Python. - */ - obj->b_needsfree = 1; - } else { - /* In python 2.4, and ctypes 0.9.6, the malloc call took about - 33% of the creation time for c_int(). - */ - obj->b_ptr = (char *)PyMem_Malloc(dict->size); - if (obj->b_ptr == NULL) { - PyErr_NoMemory(); - return -1; - } - obj->b_needsfree = 1; - memset(obj->b_ptr, 0, dict->size); - } - obj->b_size = dict->size; - return 0; + if ((size_t)dict->size <= sizeof(obj->b_value)) { + /* No need to call malloc, can use the default buffer */ + obj->b_ptr = (char *)&obj->b_value; + /* The b_needsfree flag does not mean that we actually did + call PyMem_Malloc to allocate the memory block; instead it + means we are the *owner* of the memory and are responsible + for freeing resources associated with the memory. This is + also the reason that b_needsfree is exposed to Python. + */ + obj->b_needsfree = 1; + } else { + /* In python 2.4, and ctypes 0.9.6, the malloc call took about + 33% of the creation time for c_int(). + */ + obj->b_ptr = (char *)PyMem_Malloc(dict->size); + if (obj->b_ptr == NULL) { + PyErr_NoMemory(); + return -1; + } + obj->b_needsfree = 1; + memset(obj->b_ptr, 0, dict->size); + } + obj->b_size = dict->size; + return 0; } PyObject * PyCData_FromBaseObj(PyObject *type, PyObject *base, Py_ssize_t index, char *adr) { - CDataObject *cmem; - StgDictObject *dict; + CDataObject *cmem; + StgDictObject *dict; - assert(PyType_Check(type)); - dict = PyType_stgdict(type); - if (!dict) { - PyErr_SetString(PyExc_TypeError, - "abstract class"); - return NULL; - } - dict->flags |= DICTFLAG_FINAL; - cmem = (CDataObject *)((PyTypeObject *)type)->tp_alloc((PyTypeObject *)type, 0); - if (cmem == NULL) - return NULL; - assert(CDataObject_Check(cmem)); - - cmem->b_length = dict->length; - cmem->b_size = dict->size; - if (base) { /* use base's buffer */ - assert(CDataObject_Check(base)); - cmem->b_ptr = adr; - cmem->b_needsfree = 0; - Py_INCREF(base); - cmem->b_base = (CDataObject *)base; - cmem->b_index = index; - } else { /* copy contents of adr */ - if (-1 == PyCData_MallocBuffer(cmem, dict)) { - return NULL; - Py_DECREF(cmem); - } - memcpy(cmem->b_ptr, adr, dict->size); - cmem->b_index = index; - } - return (PyObject *)cmem; + assert(PyType_Check(type)); + dict = PyType_stgdict(type); + if (!dict) { + PyErr_SetString(PyExc_TypeError, + "abstract class"); + return NULL; + } + dict->flags |= DICTFLAG_FINAL; + cmem = (CDataObject *)((PyTypeObject *)type)->tp_alloc((PyTypeObject *)type, 0); + if (cmem == NULL) + return NULL; + assert(CDataObject_Check(cmem)); + + cmem->b_length = dict->length; + cmem->b_size = dict->size; + if (base) { /* use base's buffer */ + assert(CDataObject_Check(base)); + cmem->b_ptr = adr; + cmem->b_needsfree = 0; + Py_INCREF(base); + cmem->b_base = (CDataObject *)base; + cmem->b_index = index; + } else { /* copy contents of adr */ + if (-1 == PyCData_MallocBuffer(cmem, dict)) { + return NULL; + Py_DECREF(cmem); + } + memcpy(cmem->b_ptr, adr, dict->size); + cmem->b_index = index; + } + return (PyObject *)cmem; } /* @@ -2670,26 +2670,26 @@ PyObject * PyCData_AtAddress(PyObject *type, void *buf) { - CDataObject *pd; - StgDictObject *dict; + CDataObject *pd; + StgDictObject *dict; - assert(PyType_Check(type)); - dict = PyType_stgdict(type); - if (!dict) { - PyErr_SetString(PyExc_TypeError, - "abstract class"); - return NULL; - } - dict->flags |= DICTFLAG_FINAL; - - pd = (CDataObject *)((PyTypeObject *)type)->tp_alloc((PyTypeObject *)type, 0); - if (!pd) - return NULL; - assert(CDataObject_Check(pd)); - pd->b_ptr = (char *)buf; - pd->b_length = dict->length; - pd->b_size = dict->size; - return (PyObject *)pd; + assert(PyType_Check(type)); + dict = PyType_stgdict(type); + if (!dict) { + PyErr_SetString(PyExc_TypeError, + "abstract class"); + return NULL; + } + dict->flags |= DICTFLAG_FINAL; + + pd = (CDataObject *)((PyTypeObject *)type)->tp_alloc((PyTypeObject *)type, 0); + if (!pd) + return NULL; + assert(CDataObject_Check(pd)); + pd->b_ptr = (char *)buf; + pd->b_length = dict->length; + pd->b_size = dict->size; + return (PyObject *)pd; } /* @@ -2699,25 +2699,25 @@ */ int _ctypes_simple_instance(PyObject *obj) { - PyTypeObject *type = (PyTypeObject *)obj; + PyTypeObject *type = (PyTypeObject *)obj; - if (PyCSimpleTypeObject_Check(type)) - return type->tp_base != &Simple_Type; - return 0; + if (PyCSimpleTypeObject_Check(type)) + return type->tp_base != &Simple_Type; + return 0; } PyObject * PyCData_get(PyObject *type, GETFUNC getfunc, PyObject *src, - Py_ssize_t index, Py_ssize_t size, char *adr) + Py_ssize_t index, Py_ssize_t size, char *adr) { - StgDictObject *dict; - if (getfunc) - return getfunc(adr, size); - assert(type); - dict = PyType_stgdict(type); - if (dict && dict->getfunc && !_ctypes_simple_instance(type)) - return dict->getfunc(adr, size); - return PyCData_FromBaseObj(type, src, index, adr); + StgDictObject *dict; + if (getfunc) + return getfunc(adr, size); + assert(type); + dict = PyType_stgdict(type); + if (dict && dict->getfunc && !_ctypes_simple_instance(type)) + return dict->getfunc(adr, size); + return PyCData_FromBaseObj(type, src, index, adr); } /* @@ -2725,96 +2725,96 @@ */ static PyObject * _PyCData_set(CDataObject *dst, PyObject *type, SETFUNC setfunc, PyObject *value, - Py_ssize_t size, char *ptr) + Py_ssize_t size, char *ptr) { - CDataObject *src; + CDataObject *src; - if (setfunc) - return setfunc(ptr, value, size); - - if (!CDataObject_Check(value)) { - StgDictObject *dict = PyType_stgdict(type); - if (dict && dict->setfunc) - return dict->setfunc(ptr, value, size); - /* - If value is a tuple, we try to call the type with the tuple - and use the result! - */ - assert(PyType_Check(type)); - if (PyTuple_Check(value)) { - PyObject *ob; - PyObject *result; - ob = PyObject_CallObject(type, value); - if (ob == NULL) { - _ctypes_extend_error(PyExc_RuntimeError, "(%s) ", - ((PyTypeObject *)type)->tp_name); - return NULL; - } - result = _PyCData_set(dst, type, setfunc, ob, - size, ptr); - Py_DECREF(ob); - return result; - } else if (value == Py_None && PyCPointerTypeObject_Check(type)) { - *(void **)ptr = NULL; - Py_INCREF(Py_None); - return Py_None; - } else { - PyErr_Format(PyExc_TypeError, - "expected %s instance, got %s", - ((PyTypeObject *)type)->tp_name, - Py_TYPE(value)->tp_name); - return NULL; - } - } - src = (CDataObject *)value; - - if (PyObject_IsInstance(value, type)) { - memcpy(ptr, - src->b_ptr, - size); - - if (PyCPointerTypeObject_Check(type)) - /* XXX */; - - value = GetKeepedObjects(src); - Py_INCREF(value); - return value; - } - - if (PyCPointerTypeObject_Check(type) - && ArrayObject_Check(value)) { - StgDictObject *p1, *p2; - PyObject *keep; - p1 = PyObject_stgdict(value); - assert(p1); /* Cannot be NULL for array instances */ - p2 = PyType_stgdict(type); - assert(p2); /* Cannot be NULL for pointer types */ - - if (p1->proto != p2->proto) { - PyErr_Format(PyExc_TypeError, - "incompatible types, %s instance instead of %s instance", - Py_TYPE(value)->tp_name, - ((PyTypeObject *)type)->tp_name); - return NULL; - } - *(void **)ptr = src->b_ptr; - - keep = GetKeepedObjects(src); - /* - We are assigning an array object to a field which represents - a pointer. This has the same effect as converting an array - into a pointer. So, again, we have to keep the whole object - pointed to (which is the array in this case) alive, and not - only it's object list. So we create a tuple, containing - b_objects list PLUS the array itself, and return that! - */ - return PyTuple_Pack(2, keep, value); - } - PyErr_Format(PyExc_TypeError, - "incompatible types, %s instance instead of %s instance", - Py_TYPE(value)->tp_name, - ((PyTypeObject *)type)->tp_name); - return NULL; + if (setfunc) + return setfunc(ptr, value, size); + + if (!CDataObject_Check(value)) { + StgDictObject *dict = PyType_stgdict(type); + if (dict && dict->setfunc) + return dict->setfunc(ptr, value, size); + /* + If value is a tuple, we try to call the type with the tuple + and use the result! + */ + assert(PyType_Check(type)); + if (PyTuple_Check(value)) { + PyObject *ob; + PyObject *result; + ob = PyObject_CallObject(type, value); + if (ob == NULL) { + _ctypes_extend_error(PyExc_RuntimeError, "(%s) ", + ((PyTypeObject *)type)->tp_name); + return NULL; + } + result = _PyCData_set(dst, type, setfunc, ob, + size, ptr); + Py_DECREF(ob); + return result; + } else if (value == Py_None && PyCPointerTypeObject_Check(type)) { + *(void **)ptr = NULL; + Py_INCREF(Py_None); + return Py_None; + } else { + PyErr_Format(PyExc_TypeError, + "expected %s instance, got %s", + ((PyTypeObject *)type)->tp_name, + Py_TYPE(value)->tp_name); + return NULL; + } + } + src = (CDataObject *)value; + + if (PyObject_IsInstance(value, type)) { + memcpy(ptr, + src->b_ptr, + size); + + if (PyCPointerTypeObject_Check(type)) + /* XXX */; + + value = GetKeepedObjects(src); + Py_INCREF(value); + return value; + } + + if (PyCPointerTypeObject_Check(type) + && ArrayObject_Check(value)) { + StgDictObject *p1, *p2; + PyObject *keep; + p1 = PyObject_stgdict(value); + assert(p1); /* Cannot be NULL for array instances */ + p2 = PyType_stgdict(type); + assert(p2); /* Cannot be NULL for pointer types */ + + if (p1->proto != p2->proto) { + PyErr_Format(PyExc_TypeError, + "incompatible types, %s instance instead of %s instance", + Py_TYPE(value)->tp_name, + ((PyTypeObject *)type)->tp_name); + return NULL; + } + *(void **)ptr = src->b_ptr; + + keep = GetKeepedObjects(src); + /* + We are assigning an array object to a field which represents + a pointer. This has the same effect as converting an array + into a pointer. So, again, we have to keep the whole object + pointed to (which is the array in this case) alive, and not + only it's object list. So we create a tuple, containing + b_objects list PLUS the array itself, and return that! + */ + return PyTuple_Pack(2, keep, value); + } + PyErr_Format(PyExc_TypeError, + "incompatible types, %s instance instead of %s instance", + Py_TYPE(value)->tp_name, + ((PyTypeObject *)type)->tp_name); + return NULL; } /* @@ -2823,58 +2823,58 @@ */ int PyCData_set(PyObject *dst, PyObject *type, SETFUNC setfunc, PyObject *value, - Py_ssize_t index, Py_ssize_t size, char *ptr) + Py_ssize_t index, Py_ssize_t size, char *ptr) { - CDataObject *mem = (CDataObject *)dst; - PyObject *result; + CDataObject *mem = (CDataObject *)dst; + PyObject *result; - if (!CDataObject_Check(dst)) { - PyErr_SetString(PyExc_TypeError, - "not a ctype instance"); - return -1; - } + if (!CDataObject_Check(dst)) { + PyErr_SetString(PyExc_TypeError, + "not a ctype instance"); + return -1; + } - result = _PyCData_set(mem, type, setfunc, value, - size, ptr); - if (result == NULL) - return -1; + result = _PyCData_set(mem, type, setfunc, value, + size, ptr); + if (result == NULL) + return -1; - /* KeepRef steals a refcount from it's last argument */ - /* If KeepRef fails, we are stumped. The dst memory block has already - been changed */ - return KeepRef(mem, index, result); + /* KeepRef steals a refcount from it's last argument */ + /* If KeepRef fails, we are stumped. The dst memory block has already + been changed */ + return KeepRef(mem, index, result); } - + /******************************************************************/ static PyObject * GenericPyCData_new(PyTypeObject *type, PyObject *args, PyObject *kwds) { - CDataObject *obj; - StgDictObject *dict; + CDataObject *obj; + StgDictObject *dict; - dict = PyType_stgdict((PyObject *)type); - if (!dict) { - PyErr_SetString(PyExc_TypeError, - "abstract class"); - return NULL; - } - dict->flags |= DICTFLAG_FINAL; - - obj = (CDataObject *)type->tp_alloc(type, 0); - if (!obj) - return NULL; - - obj->b_base = NULL; - obj->b_index = 0; - obj->b_objects = NULL; - obj->b_length = dict->length; - - if (-1 == PyCData_MallocBuffer(obj, dict)) { - Py_DECREF(obj); - return NULL; - } - return (PyObject *)obj; + dict = PyType_stgdict((PyObject *)type); + if (!dict) { + PyErr_SetString(PyExc_TypeError, + "abstract class"); + return NULL; + } + dict->flags |= DICTFLAG_FINAL; + + obj = (CDataObject *)type->tp_alloc(type, 0); + if (!obj) + return NULL; + + obj->b_base = NULL; + obj->b_index = 0; + obj->b_objects = NULL; + obj->b_length = dict->length; + + if (-1 == PyCData_MallocBuffer(obj, dict)) { + Py_DECREF(obj); + return NULL; + } + return (PyObject *)obj; } /*****************************************************************/ /* @@ -2884,165 +2884,165 @@ static int PyCFuncPtr_set_errcheck(PyCFuncPtrObject *self, PyObject *ob) { - if (ob && !PyCallable_Check(ob)) { - PyErr_SetString(PyExc_TypeError, - "the errcheck attribute must be callable"); - return -1; - } - Py_XDECREF(self->errcheck); - Py_XINCREF(ob); - self->errcheck = ob; - return 0; + if (ob && !PyCallable_Check(ob)) { + PyErr_SetString(PyExc_TypeError, + "the errcheck attribute must be callable"); + return -1; + } + Py_XDECREF(self->errcheck); + Py_XINCREF(ob); + self->errcheck = ob; + return 0; } static PyObject * PyCFuncPtr_get_errcheck(PyCFuncPtrObject *self) { - if (self->errcheck) { - Py_INCREF(self->errcheck); - return self->errcheck; - } - Py_INCREF(Py_None); - return Py_None; + if (self->errcheck) { + Py_INCREF(self->errcheck); + return self->errcheck; + } + Py_INCREF(Py_None); + return Py_None; } static int PyCFuncPtr_set_restype(PyCFuncPtrObject *self, PyObject *ob) { - if (ob == NULL) { - Py_XDECREF(self->restype); - self->restype = NULL; - Py_XDECREF(self->checker); - self->checker = NULL; - return 0; - } - if (ob != Py_None && !PyType_stgdict(ob) && !PyCallable_Check(ob)) { - PyErr_SetString(PyExc_TypeError, - "restype must be a type, a callable, or None"); - return -1; - } - Py_XDECREF(self->checker); - Py_XDECREF(self->restype); - Py_INCREF(ob); - self->restype = ob; - self->checker = PyObject_GetAttrString(ob, "_check_retval_"); - if (self->checker == NULL) - PyErr_Clear(); - return 0; + if (ob == NULL) { + Py_XDECREF(self->restype); + self->restype = NULL; + Py_XDECREF(self->checker); + self->checker = NULL; + return 0; + } + if (ob != Py_None && !PyType_stgdict(ob) && !PyCallable_Check(ob)) { + PyErr_SetString(PyExc_TypeError, + "restype must be a type, a callable, or None"); + return -1; + } + Py_XDECREF(self->checker); + Py_XDECREF(self->restype); + Py_INCREF(ob); + self->restype = ob; + self->checker = PyObject_GetAttrString(ob, "_check_retval_"); + if (self->checker == NULL) + PyErr_Clear(); + return 0; } static PyObject * PyCFuncPtr_get_restype(PyCFuncPtrObject *self) { - StgDictObject *dict; - if (self->restype) { - Py_INCREF(self->restype); - return self->restype; - } - dict = PyObject_stgdict((PyObject *)self); - assert(dict); /* Cannot be NULL for PyCFuncPtrObject instances */ - if (dict->restype) { - Py_INCREF(dict->restype); - return dict->restype; - } else { - Py_INCREF(Py_None); - return Py_None; - } + StgDictObject *dict; + if (self->restype) { + Py_INCREF(self->restype); + return self->restype; + } + dict = PyObject_stgdict((PyObject *)self); + assert(dict); /* Cannot be NULL for PyCFuncPtrObject instances */ + if (dict->restype) { + Py_INCREF(dict->restype); + return dict->restype; + } else { + Py_INCREF(Py_None); + return Py_None; + } } static int PyCFuncPtr_set_argtypes(PyCFuncPtrObject *self, PyObject *ob) { - PyObject *converters; + PyObject *converters; - if (ob == NULL || ob == Py_None) { - Py_XDECREF(self->converters); - self->converters = NULL; - Py_XDECREF(self->argtypes); - self->argtypes = NULL; - } else { - converters = converters_from_argtypes(ob); - if (!converters) - return -1; - Py_XDECREF(self->converters); - self->converters = converters; - Py_XDECREF(self->argtypes); - Py_INCREF(ob); - self->argtypes = ob; - } - return 0; + if (ob == NULL || ob == Py_None) { + Py_XDECREF(self->converters); + self->converters = NULL; + Py_XDECREF(self->argtypes); + self->argtypes = NULL; + } else { + converters = converters_from_argtypes(ob); + if (!converters) + return -1; + Py_XDECREF(self->converters); + self->converters = converters; + Py_XDECREF(self->argtypes); + Py_INCREF(ob); + self->argtypes = ob; + } + return 0; } static PyObject * PyCFuncPtr_get_argtypes(PyCFuncPtrObject *self) { - StgDictObject *dict; - if (self->argtypes) { - Py_INCREF(self->argtypes); - return self->argtypes; - } - dict = PyObject_stgdict((PyObject *)self); - assert(dict); /* Cannot be NULL for PyCFuncPtrObject instances */ - if (dict->argtypes) { - Py_INCREF(dict->argtypes); - return dict->argtypes; - } else { - Py_INCREF(Py_None); - return Py_None; - } + StgDictObject *dict; + if (self->argtypes) { + Py_INCREF(self->argtypes); + return self->argtypes; + } + dict = PyObject_stgdict((PyObject *)self); + assert(dict); /* Cannot be NULL for PyCFuncPtrObject instances */ + if (dict->argtypes) { + Py_INCREF(dict->argtypes); + return dict->argtypes; + } else { + Py_INCREF(Py_None); + return Py_None; + } } static PyGetSetDef PyCFuncPtr_getsets[] = { - { "errcheck", (getter)PyCFuncPtr_get_errcheck, (setter)PyCFuncPtr_set_errcheck, - "a function to check for errors", NULL }, - { "restype", (getter)PyCFuncPtr_get_restype, (setter)PyCFuncPtr_set_restype, - "specify the result type", NULL }, - { "argtypes", (getter)PyCFuncPtr_get_argtypes, - (setter)PyCFuncPtr_set_argtypes, - "specify the argument types", NULL }, - { NULL, NULL } + { "errcheck", (getter)PyCFuncPtr_get_errcheck, (setter)PyCFuncPtr_set_errcheck, + "a function to check for errors", NULL }, + { "restype", (getter)PyCFuncPtr_get_restype, (setter)PyCFuncPtr_set_restype, + "specify the result type", NULL }, + { "argtypes", (getter)PyCFuncPtr_get_argtypes, + (setter)PyCFuncPtr_set_argtypes, + "specify the argument types", NULL }, + { NULL, NULL } }; #ifdef MS_WIN32 static PPROC FindAddress(void *handle, char *name, PyObject *type) { #ifdef MS_WIN64 - /* win64 has no stdcall calling conv, so it should - also not have the name mangling of it. - */ - return (PPROC)GetProcAddress(handle, name); + /* win64 has no stdcall calling conv, so it should + also not have the name mangling of it. + */ + return (PPROC)GetProcAddress(handle, name); #else - PPROC address; - char *mangled_name; - int i; - StgDictObject *dict; - - address = (PPROC)GetProcAddress(handle, name); - if (address) - return address; - if (((size_t)name & ~0xFFFF) == 0) { - return NULL; - } - - dict = PyType_stgdict((PyObject *)type); - /* It should not happen that dict is NULL, but better be safe */ - if (dict==NULL || dict->flags & FUNCFLAG_CDECL) - return address; - - /* for stdcall, try mangled names: - funcname -> _funcname@ - where n is 0, 4, 8, 12, ..., 128 - */ - mangled_name = alloca(strlen(name) + 1 + 1 + 1 + 3); /* \0 _ @ %d */ - if (!mangled_name) - return NULL; - for (i = 0; i < 32; ++i) { - sprintf(mangled_name, "_%s@%d", name, i*4); - address = (PPROC)GetProcAddress(handle, mangled_name); - if (address) - return address; - } - return NULL; + PPROC address; + char *mangled_name; + int i; + StgDictObject *dict; + + address = (PPROC)GetProcAddress(handle, name); + if (address) + return address; + if (((size_t)name & ~0xFFFF) == 0) { + return NULL; + } + + dict = PyType_stgdict((PyObject *)type); + /* It should not happen that dict is NULL, but better be safe */ + if (dict==NULL || dict->flags & FUNCFLAG_CDECL) + return address; + + /* for stdcall, try mangled names: + funcname -> _funcname@ + where n is 0, 4, 8, 12, ..., 128 + */ + mangled_name = alloca(strlen(name) + 1 + 1 + 1 + 3); /* \0 _ @ %d */ + if (!mangled_name) + return NULL; + for (i = 0; i < 32; ++i) { + sprintf(mangled_name, "_%s@%d", name, i*4); + address = (PPROC)GetProcAddress(handle, mangled_name); + if (address) + return address; + } + return NULL; #endif } #endif @@ -3051,227 +3051,227 @@ static int _check_outarg_type(PyObject *arg, Py_ssize_t index) { - StgDictObject *dict; + StgDictObject *dict; - if (PyCPointerTypeObject_Check(arg)) - return 1; + if (PyCPointerTypeObject_Check(arg)) + return 1; - if (PyCArrayTypeObject_Check(arg)) - return 1; + if (PyCArrayTypeObject_Check(arg)) + return 1; - dict = PyType_stgdict(arg); - if (dict - /* simple pointer types, c_void_p, c_wchar_p, BSTR, ... */ - && PyUnicode_Check(dict->proto) + dict = PyType_stgdict(arg); + if (dict + /* simple pointer types, c_void_p, c_wchar_p, BSTR, ... */ + && PyUnicode_Check(dict->proto) /* We only allow c_void_p, c_char_p and c_wchar_p as a simple output parameter type */ - && (strchr("PzZ", _PyUnicode_AsString(dict->proto)[0]))) { - return 1; - } - - PyErr_Format(PyExc_TypeError, - "'out' parameter %d must be a pointer type, not %s", - Py_SAFE_DOWNCAST(index, Py_ssize_t, int), - PyType_Check(arg) ? - ((PyTypeObject *)arg)->tp_name : - Py_TYPE(arg)->tp_name); - return 0; + && (strchr("PzZ", _PyUnicode_AsString(dict->proto)[0]))) { + return 1; + } + + PyErr_Format(PyExc_TypeError, + "'out' parameter %d must be a pointer type, not %s", + Py_SAFE_DOWNCAST(index, Py_ssize_t, int), + PyType_Check(arg) ? + ((PyTypeObject *)arg)->tp_name : + Py_TYPE(arg)->tp_name); + return 0; } /* Returns 1 on success, 0 on error */ static int _validate_paramflags(PyTypeObject *type, PyObject *paramflags) { - Py_ssize_t i, len; - StgDictObject *dict; - PyObject *argtypes; - - dict = PyType_stgdict((PyObject *)type); - assert(dict); /* Cannot be NULL. 'type' is a PyCFuncPtr type. */ - argtypes = dict->argtypes; - - if (paramflags == NULL || dict->argtypes == NULL) - return 1; - - if (!PyTuple_Check(paramflags)) { - PyErr_SetString(PyExc_TypeError, - "paramflags must be a tuple or None"); - return 0; - } - - len = PyTuple_GET_SIZE(paramflags); - if (len != PyTuple_GET_SIZE(dict->argtypes)) { - PyErr_SetString(PyExc_ValueError, - "paramflags must have the same length as argtypes"); - return 0; - } - - for (i = 0; i < len; ++i) { - PyObject *item = PyTuple_GET_ITEM(paramflags, i); - int flag; - char *name; - PyObject *defval; - PyObject *typ; - if (!PyArg_ParseTuple(item, "i|ZO", &flag, &name, &defval)) { - PyErr_SetString(PyExc_TypeError, - "paramflags must be a sequence of (int [,string [,value]]) tuples"); - return 0; - } - typ = PyTuple_GET_ITEM(argtypes, i); - switch (flag & (PARAMFLAG_FIN | PARAMFLAG_FOUT | PARAMFLAG_FLCID)) { - case 0: - case PARAMFLAG_FIN: - case PARAMFLAG_FIN | PARAMFLAG_FLCID: - case PARAMFLAG_FIN | PARAMFLAG_FOUT: - break; - case PARAMFLAG_FOUT: - if (!_check_outarg_type(typ, i+1)) - return 0; - break; - default: - PyErr_Format(PyExc_TypeError, - "paramflag value %d not supported", - flag); - return 0; - } - } - return 1; + Py_ssize_t i, len; + StgDictObject *dict; + PyObject *argtypes; + + dict = PyType_stgdict((PyObject *)type); + assert(dict); /* Cannot be NULL. 'type' is a PyCFuncPtr type. */ + argtypes = dict->argtypes; + + if (paramflags == NULL || dict->argtypes == NULL) + return 1; + + if (!PyTuple_Check(paramflags)) { + PyErr_SetString(PyExc_TypeError, + "paramflags must be a tuple or None"); + return 0; + } + + len = PyTuple_GET_SIZE(paramflags); + if (len != PyTuple_GET_SIZE(dict->argtypes)) { + PyErr_SetString(PyExc_ValueError, + "paramflags must have the same length as argtypes"); + return 0; + } + + for (i = 0; i < len; ++i) { + PyObject *item = PyTuple_GET_ITEM(paramflags, i); + int flag; + char *name; + PyObject *defval; + PyObject *typ; + if (!PyArg_ParseTuple(item, "i|ZO", &flag, &name, &defval)) { + PyErr_SetString(PyExc_TypeError, + "paramflags must be a sequence of (int [,string [,value]]) tuples"); + return 0; + } + typ = PyTuple_GET_ITEM(argtypes, i); + switch (flag & (PARAMFLAG_FIN | PARAMFLAG_FOUT | PARAMFLAG_FLCID)) { + case 0: + case PARAMFLAG_FIN: + case PARAMFLAG_FIN | PARAMFLAG_FLCID: + case PARAMFLAG_FIN | PARAMFLAG_FOUT: + break; + case PARAMFLAG_FOUT: + if (!_check_outarg_type(typ, i+1)) + return 0; + break; + default: + PyErr_Format(PyExc_TypeError, + "paramflag value %d not supported", + flag); + return 0; + } + } + return 1; } static int _get_name(PyObject *obj, char **pname) { #ifdef MS_WIN32 - if (PyLong_Check(obj)) { - /* We have to use MAKEINTRESOURCEA for Windows CE. - Works on Windows as well, of course. - */ - *pname = MAKEINTRESOURCEA(PyLong_AsUnsignedLongMask(obj) & 0xFFFF); - return 1; - } + if (PyLong_Check(obj)) { + /* We have to use MAKEINTRESOURCEA for Windows CE. + Works on Windows as well, of course. + */ + *pname = MAKEINTRESOURCEA(PyLong_AsUnsignedLongMask(obj) & 0xFFFF); + return 1; + } #endif - if (PyBytes_Check(obj)) { - *pname = PyBytes_AS_STRING(obj); - return *pname ? 1 : 0; - } - if (PyUnicode_Check(obj)) { - *pname = _PyUnicode_AsString(obj); - return *pname ? 1 : 0; - } - PyErr_SetString(PyExc_TypeError, - "function name must be string or integer"); - return 0; + if (PyBytes_Check(obj)) { + *pname = PyBytes_AS_STRING(obj); + return *pname ? 1 : 0; + } + if (PyUnicode_Check(obj)) { + *pname = _PyUnicode_AsString(obj); + return *pname ? 1 : 0; + } + PyErr_SetString(PyExc_TypeError, + "function name must be string or integer"); + return 0; } static PyObject * PyCFuncPtr_FromDll(PyTypeObject *type, PyObject *args, PyObject *kwds) { - char *name; - int (* address)(void); - PyObject *dll; - PyObject *obj; - PyCFuncPtrObject *self; - void *handle; - PyObject *paramflags = NULL; - - if (!PyArg_ParseTuple(args, "(O&O)|O", _get_name, &name, &dll, ¶mflags)) - return NULL; - if (paramflags == Py_None) - paramflags = NULL; - - obj = PyObject_GetAttrString(dll, "_handle"); - if (!obj) - return NULL; - if (!PyLong_Check(obj)) { - PyErr_SetString(PyExc_TypeError, - "the _handle attribute of the second argument must be an integer"); - Py_DECREF(obj); - return NULL; - } - handle = (void *)PyLong_AsVoidPtr(obj); - Py_DECREF(obj); - if (PyErr_Occurred()) { - PyErr_SetString(PyExc_ValueError, - "could not convert the _handle attribute to a pointer"); - return NULL; - } + char *name; + int (* address)(void); + PyObject *dll; + PyObject *obj; + PyCFuncPtrObject *self; + void *handle; + PyObject *paramflags = NULL; + + if (!PyArg_ParseTuple(args, "(O&O)|O", _get_name, &name, &dll, ¶mflags)) + return NULL; + if (paramflags == Py_None) + paramflags = NULL; + + obj = PyObject_GetAttrString(dll, "_handle"); + if (!obj) + return NULL; + if (!PyLong_Check(obj)) { + PyErr_SetString(PyExc_TypeError, + "the _handle attribute of the second argument must be an integer"); + Py_DECREF(obj); + return NULL; + } + handle = (void *)PyLong_AsVoidPtr(obj); + Py_DECREF(obj); + if (PyErr_Occurred()) { + PyErr_SetString(PyExc_ValueError, + "could not convert the _handle attribute to a pointer"); + return NULL; + } #ifdef MS_WIN32 - address = FindAddress(handle, name, (PyObject *)type); - if (!address) { - if (!IS_INTRESOURCE(name)) - PyErr_Format(PyExc_AttributeError, - "function '%s' not found", - name); - else - PyErr_Format(PyExc_AttributeError, - "function ordinal %d not found", - (WORD)(size_t)name); - return NULL; - } + address = FindAddress(handle, name, (PyObject *)type); + if (!address) { + if (!IS_INTRESOURCE(name)) + PyErr_Format(PyExc_AttributeError, + "function '%s' not found", + name); + else + PyErr_Format(PyExc_AttributeError, + "function ordinal %d not found", + (WORD)(size_t)name); + return NULL; + } #else - address = (PPROC)ctypes_dlsym(handle, name); - if (!address) { + address = (PPROC)ctypes_dlsym(handle, name); + if (!address) { #ifdef __CYGWIN__ /* dlerror() isn't very helpful on cygwin */ - PyErr_Format(PyExc_AttributeError, - "function '%s' not found (%s) ", - name); + PyErr_Format(PyExc_AttributeError, + "function '%s' not found (%s) ", + name); #else - PyErr_SetString(PyExc_AttributeError, ctypes_dlerror()); + PyErr_SetString(PyExc_AttributeError, ctypes_dlerror()); #endif - return NULL; - } + return NULL; + } #endif - if (!_validate_paramflags(type, paramflags)) - return NULL; + if (!_validate_paramflags(type, paramflags)) + return NULL; - self = (PyCFuncPtrObject *)GenericPyCData_new(type, args, kwds); - if (!self) - return NULL; - - Py_XINCREF(paramflags); - self->paramflags = paramflags; - - *(void **)self->b_ptr = address; - - Py_INCREF((PyObject *)dll); /* for KeepRef */ - if (-1 == KeepRef((CDataObject *)self, 0, dll)) { - Py_DECREF((PyObject *)self); - return NULL; - } - - Py_INCREF(self); - self->callable = (PyObject *)self; - return (PyObject *)self; + self = (PyCFuncPtrObject *)GenericPyCData_new(type, args, kwds); + if (!self) + return NULL; + + Py_XINCREF(paramflags); + self->paramflags = paramflags; + + *(void **)self->b_ptr = address; + + Py_INCREF((PyObject *)dll); /* for KeepRef */ + if (-1 == KeepRef((CDataObject *)self, 0, dll)) { + Py_DECREF((PyObject *)self); + return NULL; + } + + Py_INCREF(self); + self->callable = (PyObject *)self; + return (PyObject *)self; } #ifdef MS_WIN32 static PyObject * PyCFuncPtr_FromVtblIndex(PyTypeObject *type, PyObject *args, PyObject *kwds) { - PyCFuncPtrObject *self; - int index; - char *name = NULL; - PyObject *paramflags = NULL; - GUID *iid = NULL; - Py_ssize_t iid_len = 0; - - if (!PyArg_ParseTuple(args, "is|Oz#", &index, &name, ¶mflags, &iid, &iid_len)) - return NULL; - if (paramflags == Py_None) - paramflags = NULL; - - if (!_validate_paramflags(type, paramflags)) - return NULL; - - self = (PyCFuncPtrObject *)GenericPyCData_new(type, args, kwds); - self->index = index + 0x1000; - Py_XINCREF(paramflags); - self->paramflags = paramflags; - if (iid_len == sizeof(GUID)) - self->iid = iid; - return (PyObject *)self; + PyCFuncPtrObject *self; + int index; + char *name = NULL; + PyObject *paramflags = NULL; + GUID *iid = NULL; + Py_ssize_t iid_len = 0; + + if (!PyArg_ParseTuple(args, "is|Oz#", &index, &name, ¶mflags, &iid, &iid_len)) + return NULL; + if (paramflags == Py_None) + paramflags = NULL; + + if (!_validate_paramflags(type, paramflags)) + return NULL; + + self = (PyCFuncPtrObject *)GenericPyCData_new(type, args, kwds); + self->index = index + 0x1000; + Py_XINCREF(paramflags); + self->paramflags = paramflags; + if (iid_len == sizeof(GUID)) + self->iid = iid; + return (PyObject *)self; } #endif @@ -3291,90 +3291,90 @@ static PyObject * PyCFuncPtr_new(PyTypeObject *type, PyObject *args, PyObject *kwds) { - PyCFuncPtrObject *self; - PyObject *callable; - StgDictObject *dict; - CThunkObject *thunk; + PyCFuncPtrObject *self; + PyObject *callable; + StgDictObject *dict; + CThunkObject *thunk; - if (PyTuple_GET_SIZE(args) == 0) - return GenericPyCData_new(type, args, kwds); + if (PyTuple_GET_SIZE(args) == 0) + return GenericPyCData_new(type, args, kwds); - if (1 <= PyTuple_GET_SIZE(args) && PyTuple_Check(PyTuple_GET_ITEM(args, 0))) - return PyCFuncPtr_FromDll(type, args, kwds); + if (1 <= PyTuple_GET_SIZE(args) && PyTuple_Check(PyTuple_GET_ITEM(args, 0))) + return PyCFuncPtr_FromDll(type, args, kwds); #ifdef MS_WIN32 - if (2 <= PyTuple_GET_SIZE(args) && PyLong_Check(PyTuple_GET_ITEM(args, 0))) - return PyCFuncPtr_FromVtblIndex(type, args, kwds); + if (2 <= PyTuple_GET_SIZE(args) && PyLong_Check(PyTuple_GET_ITEM(args, 0))) + return PyCFuncPtr_FromVtblIndex(type, args, kwds); #endif - if (1 == PyTuple_GET_SIZE(args) - && (PyLong_Check(PyTuple_GET_ITEM(args, 0)))) { - CDataObject *ob; - void *ptr = PyLong_AsVoidPtr(PyTuple_GET_ITEM(args, 0)); - if (ptr == NULL && PyErr_Occurred()) - return NULL; - ob = (CDataObject *)GenericPyCData_new(type, args, kwds); - if (ob == NULL) - return NULL; - *(void **)ob->b_ptr = ptr; - return (PyObject *)ob; - } - - if (!PyArg_ParseTuple(args, "O", &callable)) - return NULL; - if (!PyCallable_Check(callable)) { - PyErr_SetString(PyExc_TypeError, - "argument must be callable or integer function address"); - return NULL; - } - - /* XXX XXX This would allow to pass additional options. For COM - method *implementations*, we would probably want different - behaviour than in 'normal' callback functions: return a HRESULT if - an exception occurrs in the callback, and print the traceback not - only on the console, but also to OutputDebugString() or something - like that. - */ + if (1 == PyTuple_GET_SIZE(args) + && (PyLong_Check(PyTuple_GET_ITEM(args, 0)))) { + CDataObject *ob; + void *ptr = PyLong_AsVoidPtr(PyTuple_GET_ITEM(args, 0)); + if (ptr == NULL && PyErr_Occurred()) + return NULL; + ob = (CDataObject *)GenericPyCData_new(type, args, kwds); + if (ob == NULL) + return NULL; + *(void **)ob->b_ptr = ptr; + return (PyObject *)ob; + } + + if (!PyArg_ParseTuple(args, "O", &callable)) + return NULL; + if (!PyCallable_Check(callable)) { + PyErr_SetString(PyExc_TypeError, + "argument must be callable or integer function address"); + return NULL; + } + + /* XXX XXX This would allow to pass additional options. For COM + method *implementations*, we would probably want different + behaviour than in 'normal' callback functions: return a HRESULT if + an exception occurrs in the callback, and print the traceback not + only on the console, but also to OutputDebugString() or something + like that. + */ /* - if (kwds && PyDict_GetItemString(kwds, "options")) { - ... - } + if (kwds && PyDict_GetItemString(kwds, "options")) { + ... + } */ - dict = PyType_stgdict((PyObject *)type); - /* XXXX Fails if we do: 'PyCFuncPtr(lambda x: x)' */ - if (!dict || !dict->argtypes) { - PyErr_SetString(PyExc_TypeError, - "cannot construct instance of this class:" - " no argtypes"); - return NULL; - } - - thunk = _ctypes_alloc_callback(callable, - dict->argtypes, - dict->restype, - dict->flags); - if (!thunk) - return NULL; - - self = (PyCFuncPtrObject *)GenericPyCData_new(type, args, kwds); - if (self == NULL) { - Py_DECREF(thunk); - return NULL; - } - - Py_INCREF(callable); - self->callable = callable; - - self->thunk = thunk; - *(void **)self->b_ptr = (void *)thunk->pcl; - - Py_INCREF((PyObject *)thunk); /* for KeepRef */ - if (-1 == KeepRef((CDataObject *)self, 0, (PyObject *)thunk)) { - Py_DECREF((PyObject *)self); - return NULL; - } - return (PyObject *)self; + dict = PyType_stgdict((PyObject *)type); + /* XXXX Fails if we do: 'PyCFuncPtr(lambda x: x)' */ + if (!dict || !dict->argtypes) { + PyErr_SetString(PyExc_TypeError, + "cannot construct instance of this class:" + " no argtypes"); + return NULL; + } + + thunk = _ctypes_alloc_callback(callable, + dict->argtypes, + dict->restype, + dict->flags); + if (!thunk) + return NULL; + + self = (PyCFuncPtrObject *)GenericPyCData_new(type, args, kwds); + if (self == NULL) { + Py_DECREF(thunk); + return NULL; + } + + Py_INCREF(callable); + self->callable = callable; + + self->thunk = thunk; + *(void **)self->b_ptr = (void *)thunk->pcl; + + Py_INCREF((PyObject *)thunk); /* for KeepRef */ + if (-1 == KeepRef((CDataObject *)self, 0, (PyObject *)thunk)) { + Py_DECREF((PyObject *)self); + return NULL; + } + return (PyObject *)self; } @@ -3384,54 +3384,54 @@ static PyObject * _byref(PyObject *obj) { - PyCArgObject *parg; - if (!CDataObject_Check(obj)) { - PyErr_SetString(PyExc_TypeError, - "expected CData instance"); - return NULL; - } - - parg = PyCArgObject_new(); - if (parg == NULL) { - Py_DECREF(obj); - return NULL; - } - - parg->tag = 'P'; - parg->pffi_type = &ffi_type_pointer; - parg->obj = obj; - parg->value.p = ((CDataObject *)obj)->b_ptr; - return (PyObject *)parg; + PyCArgObject *parg; + if (!CDataObject_Check(obj)) { + PyErr_SetString(PyExc_TypeError, + "expected CData instance"); + return NULL; + } + + parg = PyCArgObject_new(); + if (parg == NULL) { + Py_DECREF(obj); + return NULL; + } + + parg->tag = 'P'; + parg->pffi_type = &ffi_type_pointer; + parg->obj = obj; + parg->value.p = ((CDataObject *)obj)->b_ptr; + return (PyObject *)parg; } static PyObject * _get_arg(int *pindex, PyObject *name, PyObject *defval, PyObject *inargs, PyObject *kwds) { - PyObject *v; + PyObject *v; - if (*pindex < PyTuple_GET_SIZE(inargs)) { - v = PyTuple_GET_ITEM(inargs, *pindex); - ++*pindex; - Py_INCREF(v); - return v; - } - if (kwds && (v = PyDict_GetItem(kwds, name))) { - ++*pindex; - Py_INCREF(v); - return v; - } - if (defval) { - Py_INCREF(defval); - return defval; - } - /* we can't currently emit a better error message */ - if (name) - PyErr_Format(PyExc_TypeError, - "required argument '%S' missing", name); - else - PyErr_Format(PyExc_TypeError, - "not enough arguments"); - return NULL; + if (*pindex < PyTuple_GET_SIZE(inargs)) { + v = PyTuple_GET_ITEM(inargs, *pindex); + ++*pindex; + Py_INCREF(v); + return v; + } + if (kwds && (v = PyDict_GetItem(kwds, name))) { + ++*pindex; + Py_INCREF(v); + return v; + } + if (defval) { + Py_INCREF(defval); + return defval; + } + /* we can't currently emit a better error message */ + if (name) + PyErr_Format(PyExc_TypeError, + "required argument '%S' missing", name); + else + PyErr_Format(PyExc_TypeError, + "not enough arguments"); + return NULL; } /* @@ -3454,166 +3454,166 @@ */ static PyObject * _build_callargs(PyCFuncPtrObject *self, PyObject *argtypes, - PyObject *inargs, PyObject *kwds, - int *poutmask, int *pinoutmask, unsigned int *pnumretvals) + PyObject *inargs, PyObject *kwds, + int *poutmask, int *pinoutmask, unsigned int *pnumretvals) { - PyObject *paramflags = self->paramflags; - PyObject *callargs; - StgDictObject *dict; - Py_ssize_t i, len; - int inargs_index = 0; - /* It's a little bit difficult to determine how many arguments the - function call requires/accepts. For simplicity, we count the consumed - args and compare this to the number of supplied args. */ - Py_ssize_t actual_args; - - *poutmask = 0; - *pinoutmask = 0; - *pnumretvals = 0; + PyObject *paramflags = self->paramflags; + PyObject *callargs; + StgDictObject *dict; + Py_ssize_t i, len; + int inargs_index = 0; + /* It's a little bit difficult to determine how many arguments the + function call requires/accepts. For simplicity, we count the consumed + args and compare this to the number of supplied args. */ + Py_ssize_t actual_args; + + *poutmask = 0; + *pinoutmask = 0; + *pnumretvals = 0; - /* Trivial cases, where we either return inargs itself, or a slice of it. */ - if (argtypes == NULL || paramflags == NULL || PyTuple_GET_SIZE(argtypes) == 0) { + /* Trivial cases, where we either return inargs itself, or a slice of it. */ + if (argtypes == NULL || paramflags == NULL || PyTuple_GET_SIZE(argtypes) == 0) { #ifdef MS_WIN32 - if (self->index) - return PyTuple_GetSlice(inargs, 1, PyTuple_GET_SIZE(inargs)); + if (self->index) + return PyTuple_GetSlice(inargs, 1, PyTuple_GET_SIZE(inargs)); #endif - Py_INCREF(inargs); - return inargs; - } - - len = PyTuple_GET_SIZE(argtypes); - callargs = PyTuple_New(len); /* the argument tuple we build */ - if (callargs == NULL) - return NULL; + Py_INCREF(inargs); + return inargs; + } + + len = PyTuple_GET_SIZE(argtypes); + callargs = PyTuple_New(len); /* the argument tuple we build */ + if (callargs == NULL) + return NULL; #ifdef MS_WIN32 - /* For a COM method, skip the first arg */ - if (self->index) { - inargs_index = 1; - } + /* For a COM method, skip the first arg */ + if (self->index) { + inargs_index = 1; + } #endif - for (i = 0; i < len; ++i) { - PyObject *item = PyTuple_GET_ITEM(paramflags, i); - PyObject *ob; - int flag; - PyObject *name = NULL; - PyObject *defval = NULL; - - /* This way seems to be ~2 us faster than the PyArg_ParseTuple - calls below. */ - /* We HAVE already checked that the tuple can be parsed with "i|ZO", so... */ - Py_ssize_t tsize = PyTuple_GET_SIZE(item); - flag = PyLong_AS_LONG(PyTuple_GET_ITEM(item, 0)); - name = tsize > 1 ? PyTuple_GET_ITEM(item, 1) : NULL; - defval = tsize > 2 ? PyTuple_GET_ITEM(item, 2) : NULL; - - switch (flag & (PARAMFLAG_FIN | PARAMFLAG_FOUT | PARAMFLAG_FLCID)) { - case PARAMFLAG_FIN | PARAMFLAG_FLCID: - /* ['in', 'lcid'] parameter. Always taken from defval, - if given, else the integer 0. */ - if (defval == NULL) { - defval = PyLong_FromLong(0); - if (defval == NULL) - goto error; - } else - Py_INCREF(defval); - PyTuple_SET_ITEM(callargs, i, defval); - break; - case (PARAMFLAG_FIN | PARAMFLAG_FOUT): - *pinoutmask |= (1 << i); /* mark as inout arg */ - (*pnumretvals)++; - /* fall through to PARAMFLAG_FIN... */ - case 0: - case PARAMFLAG_FIN: - /* 'in' parameter. Copy it from inargs. */ - ob =_get_arg(&inargs_index, name, defval, inargs, kwds); - if (ob == NULL) - goto error; - PyTuple_SET_ITEM(callargs, i, ob); - break; - case PARAMFLAG_FOUT: - /* XXX Refactor this code into a separate function. */ - /* 'out' parameter. - argtypes[i] must be a POINTER to a c type. - - Cannot by supplied in inargs, but a defval will be used - if available. XXX Should we support getting it from kwds? - */ - if (defval) { - /* XXX Using mutable objects as defval will - make the function non-threadsafe, unless we - copy the object in each invocation */ - Py_INCREF(defval); - PyTuple_SET_ITEM(callargs, i, defval); - *poutmask |= (1 << i); /* mark as out arg */ - (*pnumretvals)++; - break; - } - ob = PyTuple_GET_ITEM(argtypes, i); - dict = PyType_stgdict(ob); - if (dict == NULL) { - /* Cannot happen: _validate_paramflags() - would not accept such an object */ - PyErr_Format(PyExc_RuntimeError, - "NULL stgdict unexpected"); - goto error; - } - if (PyUnicode_Check(dict->proto)) { - PyErr_Format( - PyExc_TypeError, - "%s 'out' parameter must be passed as default value", - ((PyTypeObject *)ob)->tp_name); - goto error; - } - if (PyCArrayTypeObject_Check(ob)) - ob = PyObject_CallObject(ob, NULL); - else - /* Create an instance of the pointed-to type */ - ob = PyObject_CallObject(dict->proto, NULL); - /* - XXX Is the following correct any longer? - We must not pass a byref() to the array then but - the array instance itself. Then, we cannot retrive - the result from the PyCArgObject. - */ - if (ob == NULL) - goto error; - /* The .from_param call that will ocurr later will pass this - as a byref parameter. */ - PyTuple_SET_ITEM(callargs, i, ob); - *poutmask |= (1 << i); /* mark as out arg */ - (*pnumretvals)++; - break; - default: - PyErr_Format(PyExc_ValueError, - "paramflag %d not yet implemented", flag); - goto error; - break; - } - } - - /* We have counted the arguments we have consumed in 'inargs_index'. This - must be the same as len(inargs) + len(kwds), otherwise we have - either too much or not enough arguments. */ - - actual_args = PyTuple_GET_SIZE(inargs) + (kwds ? PyDict_Size(kwds) : 0); - if (actual_args != inargs_index) { - /* When we have default values or named parameters, this error - message is misleading. See unittests/test_paramflags.py - */ - PyErr_Format(PyExc_TypeError, - "call takes exactly %d arguments (%zd given)", - inargs_index, actual_args); - goto error; - } - - /* outmask is a bitmask containing indexes into callargs. Items at - these indexes contain values to return. - */ - return callargs; + for (i = 0; i < len; ++i) { + PyObject *item = PyTuple_GET_ITEM(paramflags, i); + PyObject *ob; + int flag; + PyObject *name = NULL; + PyObject *defval = NULL; + + /* This way seems to be ~2 us faster than the PyArg_ParseTuple + calls below. */ + /* We HAVE already checked that the tuple can be parsed with "i|ZO", so... */ + Py_ssize_t tsize = PyTuple_GET_SIZE(item); + flag = PyLong_AS_LONG(PyTuple_GET_ITEM(item, 0)); + name = tsize > 1 ? PyTuple_GET_ITEM(item, 1) : NULL; + defval = tsize > 2 ? PyTuple_GET_ITEM(item, 2) : NULL; + + switch (flag & (PARAMFLAG_FIN | PARAMFLAG_FOUT | PARAMFLAG_FLCID)) { + case PARAMFLAG_FIN | PARAMFLAG_FLCID: + /* ['in', 'lcid'] parameter. Always taken from defval, + if given, else the integer 0. */ + if (defval == NULL) { + defval = PyLong_FromLong(0); + if (defval == NULL) + goto error; + } else + Py_INCREF(defval); + PyTuple_SET_ITEM(callargs, i, defval); + break; + case (PARAMFLAG_FIN | PARAMFLAG_FOUT): + *pinoutmask |= (1 << i); /* mark as inout arg */ + (*pnumretvals)++; + /* fall through to PARAMFLAG_FIN... */ + case 0: + case PARAMFLAG_FIN: + /* 'in' parameter. Copy it from inargs. */ + ob =_get_arg(&inargs_index, name, defval, inargs, kwds); + if (ob == NULL) + goto error; + PyTuple_SET_ITEM(callargs, i, ob); + break; + case PARAMFLAG_FOUT: + /* XXX Refactor this code into a separate function. */ + /* 'out' parameter. + argtypes[i] must be a POINTER to a c type. + + Cannot by supplied in inargs, but a defval will be used + if available. XXX Should we support getting it from kwds? + */ + if (defval) { + /* XXX Using mutable objects as defval will + make the function non-threadsafe, unless we + copy the object in each invocation */ + Py_INCREF(defval); + PyTuple_SET_ITEM(callargs, i, defval); + *poutmask |= (1 << i); /* mark as out arg */ + (*pnumretvals)++; + break; + } + ob = PyTuple_GET_ITEM(argtypes, i); + dict = PyType_stgdict(ob); + if (dict == NULL) { + /* Cannot happen: _validate_paramflags() + would not accept such an object */ + PyErr_Format(PyExc_RuntimeError, + "NULL stgdict unexpected"); + goto error; + } + if (PyUnicode_Check(dict->proto)) { + PyErr_Format( + PyExc_TypeError, + "%s 'out' parameter must be passed as default value", + ((PyTypeObject *)ob)->tp_name); + goto error; + } + if (PyCArrayTypeObject_Check(ob)) + ob = PyObject_CallObject(ob, NULL); + else + /* Create an instance of the pointed-to type */ + ob = PyObject_CallObject(dict->proto, NULL); + /* + XXX Is the following correct any longer? + We must not pass a byref() to the array then but + the array instance itself. Then, we cannot retrive + the result from the PyCArgObject. + */ + if (ob == NULL) + goto error; + /* The .from_param call that will ocurr later will pass this + as a byref parameter. */ + PyTuple_SET_ITEM(callargs, i, ob); + *poutmask |= (1 << i); /* mark as out arg */ + (*pnumretvals)++; + break; + default: + PyErr_Format(PyExc_ValueError, + "paramflag %d not yet implemented", flag); + goto error; + break; + } + } + + /* We have counted the arguments we have consumed in 'inargs_index'. This + must be the same as len(inargs) + len(kwds), otherwise we have + either too much or not enough arguments. */ + + actual_args = PyTuple_GET_SIZE(inargs) + (kwds ? PyDict_Size(kwds) : 0); + if (actual_args != inargs_index) { + /* When we have default values or named parameters, this error + message is misleading. See unittests/test_paramflags.py + */ + PyErr_Format(PyExc_TypeError, + "call takes exactly %d arguments (%zd given)", + inargs_index, actual_args); + goto error; + } + + /* outmask is a bitmask containing indexes into callargs. Items at + these indexes contain values to return. + */ + return callargs; error: - Py_DECREF(callargs); - return NULL; + Py_DECREF(callargs); + return NULL; } /* See also: @@ -3626,307 +3626,307 @@ */ static PyObject * _build_result(PyObject *result, PyObject *callargs, - int outmask, int inoutmask, unsigned int numretvals) + int outmask, int inoutmask, unsigned int numretvals) { - unsigned int i, index; - int bit; - PyObject *tup = NULL; - - if (callargs == NULL) - return result; - if (result == NULL || numretvals == 0) { - Py_DECREF(callargs); - return result; - } - Py_DECREF(result); - - /* tup will not be allocated if numretvals == 1 */ - /* allocate tuple to hold the result */ - if (numretvals > 1) { - tup = PyTuple_New(numretvals); - if (tup == NULL) { - Py_DECREF(callargs); - return NULL; - } - } - - index = 0; - for (bit = 1, i = 0; i < 32; ++i, bit <<= 1) { - PyObject *v; - if (bit & inoutmask) { - v = PyTuple_GET_ITEM(callargs, i); - Py_INCREF(v); - if (numretvals == 1) { - Py_DECREF(callargs); - return v; - } - PyTuple_SET_ITEM(tup, index, v); - index++; - } else if (bit & outmask) { - v = PyTuple_GET_ITEM(callargs, i); - v = PyObject_CallMethod(v, "__ctypes_from_outparam__", NULL); - if (v == NULL || numretvals == 1) { - Py_DECREF(callargs); - return v; - } - PyTuple_SET_ITEM(tup, index, v); - index++; - } - if (index == numretvals) - break; - } + unsigned int i, index; + int bit; + PyObject *tup = NULL; + + if (callargs == NULL) + return result; + if (result == NULL || numretvals == 0) { + Py_DECREF(callargs); + return result; + } + Py_DECREF(result); + + /* tup will not be allocated if numretvals == 1 */ + /* allocate tuple to hold the result */ + if (numretvals > 1) { + tup = PyTuple_New(numretvals); + if (tup == NULL) { + Py_DECREF(callargs); + return NULL; + } + } + + index = 0; + for (bit = 1, i = 0; i < 32; ++i, bit <<= 1) { + PyObject *v; + if (bit & inoutmask) { + v = PyTuple_GET_ITEM(callargs, i); + Py_INCREF(v); + if (numretvals == 1) { + Py_DECREF(callargs); + return v; + } + PyTuple_SET_ITEM(tup, index, v); + index++; + } else if (bit & outmask) { + v = PyTuple_GET_ITEM(callargs, i); + v = PyObject_CallMethod(v, "__ctypes_from_outparam__", NULL); + if (v == NULL || numretvals == 1) { + Py_DECREF(callargs); + return v; + } + PyTuple_SET_ITEM(tup, index, v); + index++; + } + if (index == numretvals) + break; + } - Py_DECREF(callargs); - return tup; + Py_DECREF(callargs); + return tup; } static PyObject * PyCFuncPtr_call(PyCFuncPtrObject *self, PyObject *inargs, PyObject *kwds) { - PyObject *restype; - PyObject *converters; - PyObject *checker; - PyObject *argtypes; - StgDictObject *dict = PyObject_stgdict((PyObject *)self); - PyObject *result; - PyObject *callargs; - PyObject *errcheck; + PyObject *restype; + PyObject *converters; + PyObject *checker; + PyObject *argtypes; + StgDictObject *dict = PyObject_stgdict((PyObject *)self); + PyObject *result; + PyObject *callargs; + PyObject *errcheck; #ifdef MS_WIN32 - IUnknown *piunk = NULL; + IUnknown *piunk = NULL; #endif - void *pProc = NULL; + void *pProc = NULL; - int inoutmask; - int outmask; - unsigned int numretvals; - - assert(dict); /* Cannot be NULL for PyCFuncPtrObject instances */ - restype = self->restype ? self->restype : dict->restype; - converters = self->converters ? self->converters : dict->converters; - checker = self->checker ? self->checker : dict->checker; - argtypes = self->argtypes ? self->argtypes : dict->argtypes; + int inoutmask; + int outmask; + unsigned int numretvals; + + assert(dict); /* Cannot be NULL for PyCFuncPtrObject instances */ + restype = self->restype ? self->restype : dict->restype; + converters = self->converters ? self->converters : dict->converters; + checker = self->checker ? self->checker : dict->checker; + argtypes = self->argtypes ? self->argtypes : dict->argtypes; /* later, we probably want to have an errcheck field in stgdict */ - errcheck = self->errcheck /* ? self->errcheck : dict->errcheck */; + errcheck = self->errcheck /* ? self->errcheck : dict->errcheck */; - pProc = *(void **)self->b_ptr; + pProc = *(void **)self->b_ptr; #ifdef MS_WIN32 - if (self->index) { - /* It's a COM method */ - CDataObject *this; - this = (CDataObject *)PyTuple_GetItem(inargs, 0); /* borrowed ref! */ - if (!this) { - PyErr_SetString(PyExc_ValueError, - "native com method call without 'this' parameter"); - return NULL; - } - if (!CDataObject_Check(this)) { - PyErr_SetString(PyExc_TypeError, - "Expected a COM this pointer as first argument"); - return NULL; - } - /* there should be more checks? No, in Python */ - /* First arg is an pointer to an interface instance */ - if (!this->b_ptr || *(void **)this->b_ptr == NULL) { - PyErr_SetString(PyExc_ValueError, - "NULL COM pointer access"); - return NULL; - } - piunk = *(IUnknown **)this->b_ptr; - if (NULL == piunk->lpVtbl) { - PyErr_SetString(PyExc_ValueError, - "COM method call without VTable"); - return NULL; - } - pProc = ((void **)piunk->lpVtbl)[self->index - 0x1000]; - } + if (self->index) { + /* It's a COM method */ + CDataObject *this; + this = (CDataObject *)PyTuple_GetItem(inargs, 0); /* borrowed ref! */ + if (!this) { + PyErr_SetString(PyExc_ValueError, + "native com method call without 'this' parameter"); + return NULL; + } + if (!CDataObject_Check(this)) { + PyErr_SetString(PyExc_TypeError, + "Expected a COM this pointer as first argument"); + return NULL; + } + /* there should be more checks? No, in Python */ + /* First arg is an pointer to an interface instance */ + if (!this->b_ptr || *(void **)this->b_ptr == NULL) { + PyErr_SetString(PyExc_ValueError, + "NULL COM pointer access"); + return NULL; + } + piunk = *(IUnknown **)this->b_ptr; + if (NULL == piunk->lpVtbl) { + PyErr_SetString(PyExc_ValueError, + "COM method call without VTable"); + return NULL; + } + pProc = ((void **)piunk->lpVtbl)[self->index - 0x1000]; + } #endif - callargs = _build_callargs(self, argtypes, - inargs, kwds, - &outmask, &inoutmask, &numretvals); - if (callargs == NULL) - return NULL; - - if (converters) { - int required = Py_SAFE_DOWNCAST(PyTuple_GET_SIZE(converters), - Py_ssize_t, int); - int actual = Py_SAFE_DOWNCAST(PyTuple_GET_SIZE(callargs), - Py_ssize_t, int); - - if ((dict->flags & FUNCFLAG_CDECL) == FUNCFLAG_CDECL) { - /* For cdecl functions, we allow more actual arguments - than the length of the argtypes tuple. - */ - if (required > actual) { - Py_DECREF(callargs); - PyErr_Format(PyExc_TypeError, - "this function takes at least %d argument%s (%d given)", - required, - required == 1 ? "" : "s", - actual); - return NULL; - } - } else if (required != actual) { - Py_DECREF(callargs); - PyErr_Format(PyExc_TypeError, - "this function takes %d argument%s (%d given)", - required, - required == 1 ? "" : "s", - actual); - return NULL; - } - } + callargs = _build_callargs(self, argtypes, + inargs, kwds, + &outmask, &inoutmask, &numretvals); + if (callargs == NULL) + return NULL; + + if (converters) { + int required = Py_SAFE_DOWNCAST(PyTuple_GET_SIZE(converters), + Py_ssize_t, int); + int actual = Py_SAFE_DOWNCAST(PyTuple_GET_SIZE(callargs), + Py_ssize_t, int); + + if ((dict->flags & FUNCFLAG_CDECL) == FUNCFLAG_CDECL) { + /* For cdecl functions, we allow more actual arguments + than the length of the argtypes tuple. + */ + if (required > actual) { + Py_DECREF(callargs); + PyErr_Format(PyExc_TypeError, + "this function takes at least %d argument%s (%d given)", + required, + required == 1 ? "" : "s", + actual); + return NULL; + } + } else if (required != actual) { + Py_DECREF(callargs); + PyErr_Format(PyExc_TypeError, + "this function takes %d argument%s (%d given)", + required, + required == 1 ? "" : "s", + actual); + return NULL; + } + } - result = _ctypes_callproc(pProc, - callargs, + result = _ctypes_callproc(pProc, + callargs, #ifdef MS_WIN32 - piunk, - self->iid, + piunk, + self->iid, #endif - dict->flags, - converters, - restype, - checker); + dict->flags, + converters, + restype, + checker); /* The 'errcheck' protocol */ - if (result != NULL && errcheck) { - PyObject *v = PyObject_CallFunctionObjArgs(errcheck, - result, - self, - callargs, - NULL); - /* If the errcheck funtion failed, return NULL. - If the errcheck function returned callargs unchanged, - continue normal processing. - If the errcheck function returned something else, - use that as result. - */ - if (v == NULL || v != callargs) { - Py_DECREF(result); - Py_DECREF(callargs); - return v; - } - Py_DECREF(v); - } + if (result != NULL && errcheck) { + PyObject *v = PyObject_CallFunctionObjArgs(errcheck, + result, + self, + callargs, + NULL); + /* If the errcheck funtion failed, return NULL. + If the errcheck function returned callargs unchanged, + continue normal processing. + If the errcheck function returned something else, + use that as result. + */ + if (v == NULL || v != callargs) { + Py_DECREF(result); + Py_DECREF(callargs); + return v; + } + Py_DECREF(v); + } - return _build_result(result, callargs, - outmask, inoutmask, numretvals); + return _build_result(result, callargs, + outmask, inoutmask, numretvals); } static int PyCFuncPtr_traverse(PyCFuncPtrObject *self, visitproc visit, void *arg) { - Py_VISIT(self->callable); - Py_VISIT(self->restype); - Py_VISIT(self->checker); - Py_VISIT(self->errcheck); - Py_VISIT(self->argtypes); - Py_VISIT(self->converters); - Py_VISIT(self->paramflags); - Py_VISIT(self->thunk); - return PyCData_traverse((CDataObject *)self, visit, arg); + Py_VISIT(self->callable); + Py_VISIT(self->restype); + Py_VISIT(self->checker); + Py_VISIT(self->errcheck); + Py_VISIT(self->argtypes); + Py_VISIT(self->converters); + Py_VISIT(self->paramflags); + Py_VISIT(self->thunk); + return PyCData_traverse((CDataObject *)self, visit, arg); } static int PyCFuncPtr_clear(PyCFuncPtrObject *self) { - Py_CLEAR(self->callable); - Py_CLEAR(self->restype); - Py_CLEAR(self->checker); - Py_CLEAR(self->errcheck); - Py_CLEAR(self->argtypes); - Py_CLEAR(self->converters); - Py_CLEAR(self->paramflags); - Py_CLEAR(self->thunk); - return PyCData_clear((CDataObject *)self); + Py_CLEAR(self->callable); + Py_CLEAR(self->restype); + Py_CLEAR(self->checker); + Py_CLEAR(self->errcheck); + Py_CLEAR(self->argtypes); + Py_CLEAR(self->converters); + Py_CLEAR(self->paramflags); + Py_CLEAR(self->thunk); + return PyCData_clear((CDataObject *)self); } static void PyCFuncPtr_dealloc(PyCFuncPtrObject *self) { - PyCFuncPtr_clear(self); - Py_TYPE(self)->tp_free((PyObject *)self); + PyCFuncPtr_clear(self); + Py_TYPE(self)->tp_free((PyObject *)self); } static PyObject * PyCFuncPtr_repr(PyCFuncPtrObject *self) { #ifdef MS_WIN32 - if (self->index) - return PyUnicode_FromFormat("", - self->index - 0x1000, - Py_TYPE(self)->tp_name, - self); + if (self->index) + return PyUnicode_FromFormat("", + self->index - 0x1000, + Py_TYPE(self)->tp_name, + self); #endif - return PyUnicode_FromFormat("<%s object at %p>", - Py_TYPE(self)->tp_name, - self); + return PyUnicode_FromFormat("<%s object at %p>", + Py_TYPE(self)->tp_name, + self); } static int PyCFuncPtr_bool(PyCFuncPtrObject *self) { - return ((*(void **)self->b_ptr != NULL) + return ((*(void **)self->b_ptr != NULL) #ifdef MS_WIN32 - || (self->index != 0) + || (self->index != 0) #endif - ); + ); } static PyNumberMethods PyCFuncPtr_as_number = { - 0, /* nb_add */ - 0, /* nb_subtract */ - 0, /* nb_multiply */ - 0, /* nb_remainder */ - 0, /* nb_divmod */ - 0, /* nb_power */ - 0, /* nb_negative */ - 0, /* nb_positive */ - 0, /* nb_absolute */ - (inquiry)PyCFuncPtr_bool, /* nb_bool */ + 0, /* nb_add */ + 0, /* nb_subtract */ + 0, /* nb_multiply */ + 0, /* nb_remainder */ + 0, /* nb_divmod */ + 0, /* nb_power */ + 0, /* nb_negative */ + 0, /* nb_positive */ + 0, /* nb_absolute */ + (inquiry)PyCFuncPtr_bool, /* nb_bool */ }; PyTypeObject PyCFuncPtr_Type = { - PyVarObject_HEAD_INIT(NULL, 0) - "_ctypes.PyCFuncPtr", - sizeof(PyCFuncPtrObject), /* tp_basicsize */ - 0, /* tp_itemsize */ - (destructor)PyCFuncPtr_dealloc, /* tp_dealloc */ - 0, /* tp_print */ - 0, /* tp_getattr */ - 0, /* tp_setattr */ - 0, /* tp_reserved */ - (reprfunc)PyCFuncPtr_repr, /* tp_repr */ - &PyCFuncPtr_as_number, /* tp_as_number */ - 0, /* tp_as_sequence */ - 0, /* tp_as_mapping */ - 0, /* tp_hash */ - (ternaryfunc)PyCFuncPtr_call, /* tp_call */ - 0, /* tp_str */ - 0, /* tp_getattro */ - 0, /* tp_setattro */ - &PyCData_as_buffer, /* tp_as_buffer */ - Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */ - "Function Pointer", /* tp_doc */ - (traverseproc)PyCFuncPtr_traverse, /* tp_traverse */ - (inquiry)PyCFuncPtr_clear, /* tp_clear */ - 0, /* tp_richcompare */ - 0, /* tp_weaklistoffset */ - 0, /* tp_iter */ - 0, /* tp_iternext */ - 0, /* tp_methods */ - 0, /* tp_members */ - PyCFuncPtr_getsets, /* tp_getset */ - 0, /* tp_base */ - 0, /* tp_dict */ - 0, /* tp_descr_get */ - 0, /* tp_descr_set */ - 0, /* tp_dictoffset */ - 0, /* tp_init */ - 0, /* tp_alloc */ - PyCFuncPtr_new, /* tp_new */ - 0, /* tp_free */ + PyVarObject_HEAD_INIT(NULL, 0) + "_ctypes.PyCFuncPtr", + sizeof(PyCFuncPtrObject), /* tp_basicsize */ + 0, /* tp_itemsize */ + (destructor)PyCFuncPtr_dealloc, /* tp_dealloc */ + 0, /* tp_print */ + 0, /* tp_getattr */ + 0, /* tp_setattr */ + 0, /* tp_reserved */ + (reprfunc)PyCFuncPtr_repr, /* tp_repr */ + &PyCFuncPtr_as_number, /* tp_as_number */ + 0, /* tp_as_sequence */ + 0, /* tp_as_mapping */ + 0, /* tp_hash */ + (ternaryfunc)PyCFuncPtr_call, /* tp_call */ + 0, /* tp_str */ + 0, /* tp_getattro */ + 0, /* tp_setattro */ + &PyCData_as_buffer, /* tp_as_buffer */ + Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */ + "Function Pointer", /* tp_doc */ + (traverseproc)PyCFuncPtr_traverse, /* tp_traverse */ + (inquiry)PyCFuncPtr_clear, /* tp_clear */ + 0, /* tp_richcompare */ + 0, /* tp_weaklistoffset */ + 0, /* tp_iter */ + 0, /* tp_iternext */ + 0, /* tp_methods */ + 0, /* tp_members */ + PyCFuncPtr_getsets, /* tp_getset */ + 0, /* tp_base */ + 0, /* tp_dict */ + 0, /* tp_descr_get */ + 0, /* tp_descr_set */ + 0, /* tp_dictoffset */ + 0, /* tp_init */ + 0, /* tp_alloc */ + PyCFuncPtr_new, /* tp_new */ + 0, /* tp_free */ }; - + /*****************************************************************/ /* Struct_Type @@ -3941,61 +3941,61 @@ */ static int _init_pos_args(PyObject *self, PyTypeObject *type, - PyObject *args, PyObject *kwds, - int index) + PyObject *args, PyObject *kwds, + int index) { - StgDictObject *dict; - PyObject *fields; - int i; - - if (PyType_stgdict((PyObject *)type->tp_base)) { - index = _init_pos_args(self, type->tp_base, - args, kwds, - index); - if (index == -1) - return -1; - } - - dict = PyType_stgdict((PyObject *)type); - fields = PyDict_GetItemString((PyObject *)dict, "_fields_"); - if (fields == NULL) - return index; - - for (i = 0; - i < dict->length && (i+index) < PyTuple_GET_SIZE(args); - ++i) { - PyObject *pair = PySequence_GetItem(fields, i); - PyObject *name, *val; - int res; - if (!pair) - return -1; - name = PySequence_GetItem(pair, 0); - if (!name) { - Py_DECREF(pair); - return -1; - } - val = PyTuple_GET_ITEM(args, i + index); - if (kwds && PyDict_GetItem(kwds, name)) { - char *field = PyBytes_AsString(name); - if (field == NULL) { - PyErr_Clear(); - field = "???"; - } - PyErr_Format(PyExc_TypeError, - "duplicate values for field '%s'", - field); - Py_DECREF(pair); - Py_DECREF(name); - return -1; - } - - res = PyObject_SetAttr(self, name, val); - Py_DECREF(pair); - Py_DECREF(name); - if (res == -1) - return -1; - } - return index + dict->length; + StgDictObject *dict; + PyObject *fields; + int i; + + if (PyType_stgdict((PyObject *)type->tp_base)) { + index = _init_pos_args(self, type->tp_base, + args, kwds, + index); + if (index == -1) + return -1; + } + + dict = PyType_stgdict((PyObject *)type); + fields = PyDict_GetItemString((PyObject *)dict, "_fields_"); + if (fields == NULL) + return index; + + for (i = 0; + i < dict->length && (i+index) < PyTuple_GET_SIZE(args); + ++i) { + PyObject *pair = PySequence_GetItem(fields, i); + PyObject *name, *val; + int res; + if (!pair) + return -1; + name = PySequence_GetItem(pair, 0); + if (!name) { + Py_DECREF(pair); + return -1; + } + val = PyTuple_GET_ITEM(args, i + index); + if (kwds && PyDict_GetItem(kwds, name)) { + char *field = PyBytes_AsString(name); + if (field == NULL) { + PyErr_Clear(); + field = "???"; + } + PyErr_Format(PyExc_TypeError, + "duplicate values for field '%s'", + field); + Py_DECREF(pair); + Py_DECREF(name); + return -1; + } + + res = PyObject_SetAttr(self, name, val); + Py_DECREF(pair); + Py_DECREF(name); + if (res == -1) + return -1; + } + return index + dict->length; } static int @@ -4004,119 +4004,119 @@ /* Optimization possible: Store the attribute names _fields_[x][0] * in C accessible fields somewhere ? */ - if (!PyTuple_Check(args)) { - PyErr_SetString(PyExc_TypeError, - "args not a tuple?"); - return -1; - } - if (PyTuple_GET_SIZE(args)) { - int res = _init_pos_args(self, Py_TYPE(self), - args, kwds, 0); - if (res == -1) - return -1; - if (res < PyTuple_GET_SIZE(args)) { - PyErr_SetString(PyExc_TypeError, - "too many initializers"); - return -1; - } - } - - if (kwds) { - PyObject *key, *value; - Py_ssize_t pos = 0; - while(PyDict_Next(kwds, &pos, &key, &value)) { - if (-1 == PyObject_SetAttr(self, key, value)) - return -1; - } - } - return 0; + if (!PyTuple_Check(args)) { + PyErr_SetString(PyExc_TypeError, + "args not a tuple?"); + return -1; + } + if (PyTuple_GET_SIZE(args)) { + int res = _init_pos_args(self, Py_TYPE(self), + args, kwds, 0); + if (res == -1) + return -1; + if (res < PyTuple_GET_SIZE(args)) { + PyErr_SetString(PyExc_TypeError, + "too many initializers"); + return -1; + } + } + + if (kwds) { + PyObject *key, *value; + Py_ssize_t pos = 0; + while(PyDict_Next(kwds, &pos, &key, &value)) { + if (-1 == PyObject_SetAttr(self, key, value)) + return -1; + } + } + return 0; } static PyTypeObject Struct_Type = { - PyVarObject_HEAD_INIT(NULL, 0) - "_ctypes.Structure", - sizeof(CDataObject), /* tp_basicsize */ - 0, /* tp_itemsize */ - 0, /* tp_dealloc */ - 0, /* tp_print */ - 0, /* tp_getattr */ - 0, /* tp_setattr */ - 0, /* tp_reserved */ - 0, /* tp_repr */ - 0, /* tp_as_number */ - 0, /* tp_as_sequence */ - 0, /* tp_as_mapping */ - 0, /* tp_hash */ - 0, /* tp_call */ - 0, /* tp_str */ - 0, /* tp_getattro */ - 0, /* tp_setattro */ - &PyCData_as_buffer, /* tp_as_buffer */ - Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */ - "Structure base class", /* tp_doc */ - (traverseproc)PyCData_traverse, /* tp_traverse */ - (inquiry)PyCData_clear, /* tp_clear */ - 0, /* tp_richcompare */ - 0, /* tp_weaklistoffset */ - 0, /* tp_iter */ - 0, /* tp_iternext */ - 0, /* tp_methods */ - 0, /* tp_members */ - 0, /* tp_getset */ - 0, /* tp_base */ - 0, /* tp_dict */ - 0, /* tp_descr_get */ - 0, /* tp_descr_set */ - 0, /* tp_dictoffset */ - Struct_init, /* tp_init */ - 0, /* tp_alloc */ - GenericPyCData_new, /* tp_new */ - 0, /* tp_free */ + PyVarObject_HEAD_INIT(NULL, 0) + "_ctypes.Structure", + sizeof(CDataObject), /* tp_basicsize */ + 0, /* tp_itemsize */ + 0, /* tp_dealloc */ + 0, /* tp_print */ + 0, /* tp_getattr */ + 0, /* tp_setattr */ + 0, /* tp_reserved */ + 0, /* tp_repr */ + 0, /* tp_as_number */ + 0, /* tp_as_sequence */ + 0, /* tp_as_mapping */ + 0, /* tp_hash */ + 0, /* tp_call */ + 0, /* tp_str */ + 0, /* tp_getattro */ + 0, /* tp_setattro */ + &PyCData_as_buffer, /* tp_as_buffer */ + Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */ + "Structure base class", /* tp_doc */ + (traverseproc)PyCData_traverse, /* tp_traverse */ + (inquiry)PyCData_clear, /* tp_clear */ + 0, /* tp_richcompare */ + 0, /* tp_weaklistoffset */ + 0, /* tp_iter */ + 0, /* tp_iternext */ + 0, /* tp_methods */ + 0, /* tp_members */ + 0, /* tp_getset */ + 0, /* tp_base */ + 0, /* tp_dict */ + 0, /* tp_descr_get */ + 0, /* tp_descr_set */ + 0, /* tp_dictoffset */ + Struct_init, /* tp_init */ + 0, /* tp_alloc */ + GenericPyCData_new, /* tp_new */ + 0, /* tp_free */ }; static PyTypeObject Union_Type = { - PyVarObject_HEAD_INIT(NULL, 0) - "_ctypes.Union", - sizeof(CDataObject), /* tp_basicsize */ - 0, /* tp_itemsize */ - 0, /* tp_dealloc */ - 0, /* tp_print */ - 0, /* tp_getattr */ - 0, /* tp_setattr */ - 0, /* tp_reserved */ - 0, /* tp_repr */ - 0, /* tp_as_number */ - 0, /* tp_as_sequence */ - 0, /* tp_as_mapping */ - 0, /* tp_hash */ - 0, /* tp_call */ - 0, /* tp_str */ - 0, /* tp_getattro */ - 0, /* tp_setattro */ - &PyCData_as_buffer, /* tp_as_buffer */ - Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */ - "Union base class", /* tp_doc */ - (traverseproc)PyCData_traverse, /* tp_traverse */ - (inquiry)PyCData_clear, /* tp_clear */ - 0, /* tp_richcompare */ - 0, /* tp_weaklistoffset */ - 0, /* tp_iter */ - 0, /* tp_iternext */ - 0, /* tp_methods */ - 0, /* tp_members */ - 0, /* tp_getset */ - 0, /* tp_base */ - 0, /* tp_dict */ - 0, /* tp_descr_get */ - 0, /* tp_descr_set */ - 0, /* tp_dictoffset */ - Struct_init, /* tp_init */ - 0, /* tp_alloc */ - GenericPyCData_new, /* tp_new */ - 0, /* tp_free */ + PyVarObject_HEAD_INIT(NULL, 0) + "_ctypes.Union", + sizeof(CDataObject), /* tp_basicsize */ + 0, /* tp_itemsize */ + 0, /* tp_dealloc */ + 0, /* tp_print */ + 0, /* tp_getattr */ + 0, /* tp_setattr */ + 0, /* tp_reserved */ + 0, /* tp_repr */ + 0, /* tp_as_number */ + 0, /* tp_as_sequence */ + 0, /* tp_as_mapping */ + 0, /* tp_hash */ + 0, /* tp_call */ + 0, /* tp_str */ + 0, /* tp_getattro */ + 0, /* tp_setattro */ + &PyCData_as_buffer, /* tp_as_buffer */ + Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */ + "Union base class", /* tp_doc */ + (traverseproc)PyCData_traverse, /* tp_traverse */ + (inquiry)PyCData_clear, /* tp_clear */ + 0, /* tp_richcompare */ + 0, /* tp_weaklistoffset */ + 0, /* tp_iter */ + 0, /* tp_iternext */ + 0, /* tp_methods */ + 0, /* tp_members */ + 0, /* tp_getset */ + 0, /* tp_base */ + 0, /* tp_dict */ + 0, /* tp_descr_get */ + 0, /* tp_descr_set */ + 0, /* tp_dictoffset */ + Struct_init, /* tp_init */ + 0, /* tp_alloc */ + GenericPyCData_new, /* tp_new */ + 0, /* tp_free */ }; - + /******************************************************************/ /* PyCArray_Type @@ -4124,371 +4124,371 @@ static int Array_init(CDataObject *self, PyObject *args, PyObject *kw) { - Py_ssize_t i; - Py_ssize_t n; + Py_ssize_t i; + Py_ssize_t n; - if (!PyTuple_Check(args)) { - PyErr_SetString(PyExc_TypeError, - "args not a tuple?"); - return -1; - } - n = PyTuple_GET_SIZE(args); - for (i = 0; i < n; ++i) { - PyObject *v; - v = PyTuple_GET_ITEM(args, i); - if (-1 == PySequence_SetItem((PyObject *)self, i, v)) - return -1; - } - return 0; + if (!PyTuple_Check(args)) { + PyErr_SetString(PyExc_TypeError, + "args not a tuple?"); + return -1; + } + n = PyTuple_GET_SIZE(args); + for (i = 0; i < n; ++i) { + PyObject *v; + v = PyTuple_GET_ITEM(args, i); + if (-1 == PySequence_SetItem((PyObject *)self, i, v)) + return -1; + } + return 0; } static PyObject * Array_item(PyObject *_self, Py_ssize_t index) { - CDataObject *self = (CDataObject *)_self; - Py_ssize_t offset, size; - StgDictObject *stgdict; - - - if (index < 0 || index >= self->b_length) { - PyErr_SetString(PyExc_IndexError, - "invalid index"); - return NULL; - } - - stgdict = PyObject_stgdict((PyObject *)self); - assert(stgdict); /* Cannot be NULL for array instances */ - /* Would it be clearer if we got the item size from - stgdict->proto's stgdict? - */ - size = stgdict->size / stgdict->length; - offset = index * size; + CDataObject *self = (CDataObject *)_self; + Py_ssize_t offset, size; + StgDictObject *stgdict; + + + if (index < 0 || index >= self->b_length) { + PyErr_SetString(PyExc_IndexError, + "invalid index"); + return NULL; + } + + stgdict = PyObject_stgdict((PyObject *)self); + assert(stgdict); /* Cannot be NULL for array instances */ + /* Would it be clearer if we got the item size from + stgdict->proto's stgdict? + */ + size = stgdict->size / stgdict->length; + offset = index * size; - return PyCData_get(stgdict->proto, stgdict->getfunc, (PyObject *)self, - index, size, self->b_ptr + offset); + return PyCData_get(stgdict->proto, stgdict->getfunc, (PyObject *)self, + index, size, self->b_ptr + offset); } static PyObject * Array_subscript(PyObject *_self, PyObject *item) { - CDataObject *self = (CDataObject *)_self; + CDataObject *self = (CDataObject *)_self; - 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 += self->b_length; - return Array_item(_self, i); - } - else if PySlice_Check(item) { - StgDictObject *stgdict, *itemdict; - PyObject *proto; - PyObject *np; - Py_ssize_t start, stop, step, slicelen, cur, i; - - if (PySlice_GetIndicesEx((PySliceObject *)item, - self->b_length, &start, &stop, - &step, &slicelen) < 0) { - return NULL; - } - - stgdict = PyObject_stgdict((PyObject *)self); - assert(stgdict); /* Cannot be NULL for array object instances */ - proto = stgdict->proto; - itemdict = PyType_stgdict(proto); - assert(itemdict); /* proto is the item type of the array, a - ctypes type, so this cannot be NULL */ - - if (itemdict->getfunc == _ctypes_get_fielddesc("c")->getfunc) { - char *ptr = (char *)self->b_ptr; - char *dest; - - if (slicelen <= 0) - return PyBytes_FromStringAndSize("", 0); - if (step == 1) { - return PyBytes_FromStringAndSize(ptr + start, - slicelen); - } - dest = (char *)PyMem_Malloc(slicelen); - - if (dest == NULL) - return PyErr_NoMemory(); - - for (cur = start, i = 0; i < slicelen; - cur += step, i++) { - dest[i] = ptr[cur]; - } - - np = PyBytes_FromStringAndSize(dest, slicelen); - PyMem_Free(dest); - return np; - } + 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 += self->b_length; + return Array_item(_self, i); + } + else if PySlice_Check(item) { + StgDictObject *stgdict, *itemdict; + PyObject *proto; + PyObject *np; + Py_ssize_t start, stop, step, slicelen, cur, i; + + if (PySlice_GetIndicesEx((PySliceObject *)item, + self->b_length, &start, &stop, + &step, &slicelen) < 0) { + return NULL; + } + + stgdict = PyObject_stgdict((PyObject *)self); + assert(stgdict); /* Cannot be NULL for array object instances */ + proto = stgdict->proto; + itemdict = PyType_stgdict(proto); + assert(itemdict); /* proto is the item type of the array, a + ctypes type, so this cannot be NULL */ + + if (itemdict->getfunc == _ctypes_get_fielddesc("c")->getfunc) { + char *ptr = (char *)self->b_ptr; + char *dest; + + if (slicelen <= 0) + return PyBytes_FromStringAndSize("", 0); + if (step == 1) { + return PyBytes_FromStringAndSize(ptr + start, + slicelen); + } + dest = (char *)PyMem_Malloc(slicelen); + + if (dest == NULL) + return PyErr_NoMemory(); + + for (cur = start, i = 0; i < slicelen; + cur += step, i++) { + dest[i] = ptr[cur]; + } + + np = PyBytes_FromStringAndSize(dest, slicelen); + PyMem_Free(dest); + return np; + } #ifdef CTYPES_UNICODE - if (itemdict->getfunc == _ctypes_get_fielddesc("u")->getfunc) { - wchar_t *ptr = (wchar_t *)self->b_ptr; - wchar_t *dest; - - if (slicelen <= 0) - return PyUnicode_FromUnicode(NULL, 0); - if (step == 1) { - return PyUnicode_FromWideChar(ptr + start, - slicelen); - } - - dest = (wchar_t *)PyMem_Malloc( - slicelen * sizeof(wchar_t)); - - for (cur = start, i = 0; i < slicelen; - cur += step, i++) { - dest[i] = ptr[cur]; - } - - np = PyUnicode_FromWideChar(dest, slicelen); - PyMem_Free(dest); - return np; - } + if (itemdict->getfunc == _ctypes_get_fielddesc("u")->getfunc) { + wchar_t *ptr = (wchar_t *)self->b_ptr; + wchar_t *dest; + + if (slicelen <= 0) + return PyUnicode_FromUnicode(NULL, 0); + if (step == 1) { + return PyUnicode_FromWideChar(ptr + start, + slicelen); + } + + dest = (wchar_t *)PyMem_Malloc( + slicelen * sizeof(wchar_t)); + + for (cur = start, i = 0; i < slicelen; + cur += step, i++) { + dest[i] = ptr[cur]; + } + + np = PyUnicode_FromWideChar(dest, slicelen); + PyMem_Free(dest); + return np; + } #endif - np = PyList_New(slicelen); - if (np == NULL) - return NULL; - - for (cur = start, i = 0; i < slicelen; - cur += step, i++) { - PyObject *v = Array_item(_self, cur); - PyList_SET_ITEM(np, i, v); - } - return np; - } - else { - PyErr_SetString(PyExc_TypeError, - "indices must be integers"); - return NULL; - } + np = PyList_New(slicelen); + if (np == NULL) + return NULL; + + for (cur = start, i = 0; i < slicelen; + cur += step, i++) { + PyObject *v = Array_item(_self, cur); + PyList_SET_ITEM(np, i, v); + } + return np; + } + else { + PyErr_SetString(PyExc_TypeError, + "indices must be integers"); + return NULL; + } } static int Array_ass_item(PyObject *_self, Py_ssize_t index, PyObject *value) { - CDataObject *self = (CDataObject *)_self; - Py_ssize_t size, offset; - StgDictObject *stgdict; - char *ptr; - - if (value == NULL) { - PyErr_SetString(PyExc_TypeError, - "Array does not support item deletion"); - return -1; - } - - stgdict = PyObject_stgdict((PyObject *)self); - assert(stgdict); /* Cannot be NULL for array object instances */ - if (index < 0 || index >= stgdict->length) { - PyErr_SetString(PyExc_IndexError, - "invalid index"); - return -1; - } - size = stgdict->size / stgdict->length; - offset = index * size; - ptr = self->b_ptr + offset; + CDataObject *self = (CDataObject *)_self; + Py_ssize_t size, offset; + StgDictObject *stgdict; + char *ptr; + + if (value == NULL) { + PyErr_SetString(PyExc_TypeError, + "Array does not support item deletion"); + return -1; + } + + stgdict = PyObject_stgdict((PyObject *)self); + assert(stgdict); /* Cannot be NULL for array object instances */ + if (index < 0 || index >= stgdict->length) { + PyErr_SetString(PyExc_IndexError, + "invalid index"); + return -1; + } + size = stgdict->size / stgdict->length; + offset = index * size; + ptr = self->b_ptr + offset; - return PyCData_set((PyObject *)self, stgdict->proto, stgdict->setfunc, value, - index, size, ptr); + return PyCData_set((PyObject *)self, stgdict->proto, stgdict->setfunc, value, + index, size, ptr); } static int Array_ass_subscript(PyObject *_self, PyObject *item, PyObject *value) { - CDataObject *self = (CDataObject *)_self; - - if (value == NULL) { - PyErr_SetString(PyExc_TypeError, - "Array does not support item deletion"); - return -1; - } - - if (PyIndex_Check(item)) { - Py_ssize_t i = PyNumber_AsSsize_t(item, PyExc_IndexError); - - if (i == -1 && PyErr_Occurred()) - return -1; - if (i < 0) - i += self->b_length; - return Array_ass_item(_self, i, value); - } - else if (PySlice_Check(item)) { - Py_ssize_t start, stop, step, slicelen, otherlen, i, cur; - - if (PySlice_GetIndicesEx((PySliceObject *)item, - self->b_length, &start, &stop, - &step, &slicelen) < 0) { - return -1; - } - if ((step < 0 && start < stop) || - (step > 0 && start > stop)) - stop = start; - - otherlen = PySequence_Length(value); - if (otherlen != slicelen) { - PyErr_SetString(PyExc_ValueError, - "Can only assign sequence of same size"); - return -1; - } - for (cur = start, i = 0; i < otherlen; cur += step, i++) { - PyObject *item = PySequence_GetItem(value, i); - int result; - if (item == NULL) - return -1; - result = Array_ass_item(_self, cur, item); - Py_DECREF(item); - if (result == -1) - return -1; - } - return 0; - } - else { - PyErr_SetString(PyExc_TypeError, - "indices must be integer"); - return -1; - } + CDataObject *self = (CDataObject *)_self; + + if (value == NULL) { + PyErr_SetString(PyExc_TypeError, + "Array does not support item deletion"); + return -1; + } + + if (PyIndex_Check(item)) { + Py_ssize_t i = PyNumber_AsSsize_t(item, PyExc_IndexError); + + if (i == -1 && PyErr_Occurred()) + return -1; + if (i < 0) + i += self->b_length; + return Array_ass_item(_self, i, value); + } + else if (PySlice_Check(item)) { + Py_ssize_t start, stop, step, slicelen, otherlen, i, cur; + + if (PySlice_GetIndicesEx((PySliceObject *)item, + self->b_length, &start, &stop, + &step, &slicelen) < 0) { + return -1; + } + if ((step < 0 && start < stop) || + (step > 0 && start > stop)) + stop = start; + + otherlen = PySequence_Length(value); + if (otherlen != slicelen) { + PyErr_SetString(PyExc_ValueError, + "Can only assign sequence of same size"); + return -1; + } + for (cur = start, i = 0; i < otherlen; cur += step, i++) { + PyObject *item = PySequence_GetItem(value, i); + int result; + if (item == NULL) + return -1; + result = Array_ass_item(_self, cur, item); + Py_DECREF(item); + if (result == -1) + return -1; + } + return 0; + } + else { + PyErr_SetString(PyExc_TypeError, + "indices must be integer"); + return -1; + } } static Py_ssize_t Array_length(PyObject *_self) { - CDataObject *self = (CDataObject *)_self; - return self->b_length; + CDataObject *self = (CDataObject *)_self; + return self->b_length; } static PySequenceMethods Array_as_sequence = { - Array_length, /* sq_length; */ - 0, /* sq_concat; */ - 0, /* sq_repeat; */ - Array_item, /* sq_item; */ - 0, /* sq_slice; */ - Array_ass_item, /* sq_ass_item; */ - 0, /* sq_ass_slice; */ - 0, /* sq_contains; */ - - 0, /* sq_inplace_concat; */ - 0, /* sq_inplace_repeat; */ + Array_length, /* sq_length; */ + 0, /* sq_concat; */ + 0, /* sq_repeat; */ + Array_item, /* sq_item; */ + 0, /* sq_slice; */ + Array_ass_item, /* sq_ass_item; */ + 0, /* sq_ass_slice; */ + 0, /* sq_contains; */ + + 0, /* sq_inplace_concat; */ + 0, /* sq_inplace_repeat; */ }; static PyMappingMethods Array_as_mapping = { - Array_length, - Array_subscript, - Array_ass_subscript, + Array_length, + Array_subscript, + Array_ass_subscript, }; PyTypeObject PyCArray_Type = { - PyVarObject_HEAD_INIT(NULL, 0) - "_ctypes.Array", - sizeof(CDataObject), /* tp_basicsize */ - 0, /* tp_itemsize */ - 0, /* tp_dealloc */ - 0, /* tp_print */ - 0, /* tp_getattr */ - 0, /* tp_setattr */ - 0, /* tp_reserved */ - 0, /* tp_repr */ - 0, /* tp_as_number */ - &Array_as_sequence, /* tp_as_sequence */ - &Array_as_mapping, /* tp_as_mapping */ - 0, /* tp_hash */ - 0, /* tp_call */ - 0, /* tp_str */ - 0, /* tp_getattro */ - 0, /* tp_setattro */ - &PyCData_as_buffer, /* tp_as_buffer */ - Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */ - "XXX to be provided", /* tp_doc */ - (traverseproc)PyCData_traverse, /* tp_traverse */ - (inquiry)PyCData_clear, /* tp_clear */ - 0, /* tp_richcompare */ - 0, /* tp_weaklistoffset */ - 0, /* tp_iter */ - 0, /* tp_iternext */ - 0, /* tp_methods */ - 0, /* tp_members */ - 0, /* tp_getset */ - 0, /* tp_base */ - 0, /* tp_dict */ - 0, /* tp_descr_get */ - 0, /* tp_descr_set */ - 0, /* tp_dictoffset */ - (initproc)Array_init, /* tp_init */ - 0, /* tp_alloc */ - GenericPyCData_new, /* tp_new */ - 0, /* tp_free */ + PyVarObject_HEAD_INIT(NULL, 0) + "_ctypes.Array", + sizeof(CDataObject), /* tp_basicsize */ + 0, /* tp_itemsize */ + 0, /* tp_dealloc */ + 0, /* tp_print */ + 0, /* tp_getattr */ + 0, /* tp_setattr */ + 0, /* tp_reserved */ + 0, /* tp_repr */ + 0, /* tp_as_number */ + &Array_as_sequence, /* tp_as_sequence */ + &Array_as_mapping, /* tp_as_mapping */ + 0, /* tp_hash */ + 0, /* tp_call */ + 0, /* tp_str */ + 0, /* tp_getattro */ + 0, /* tp_setattro */ + &PyCData_as_buffer, /* tp_as_buffer */ + Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */ + "XXX to be provided", /* tp_doc */ + (traverseproc)PyCData_traverse, /* tp_traverse */ + (inquiry)PyCData_clear, /* tp_clear */ + 0, /* tp_richcompare */ + 0, /* tp_weaklistoffset */ + 0, /* tp_iter */ + 0, /* tp_iternext */ + 0, /* tp_methods */ + 0, /* tp_members */ + 0, /* tp_getset */ + 0, /* tp_base */ + 0, /* tp_dict */ + 0, /* tp_descr_get */ + 0, /* tp_descr_set */ + 0, /* tp_dictoffset */ + (initproc)Array_init, /* tp_init */ + 0, /* tp_alloc */ + GenericPyCData_new, /* tp_new */ + 0, /* tp_free */ }; PyObject * PyCArrayType_from_ctype(PyObject *itemtype, Py_ssize_t length) { - static PyObject *cache; - PyObject *key; - PyObject *result; - char name[256]; - PyObject *len; - - if (cache == NULL) { - cache = PyDict_New(); - if (cache == NULL) - return NULL; - } - len = PyLong_FromSsize_t(length); - if (len == NULL) - return NULL; - key = PyTuple_Pack(2, itemtype, len); - Py_DECREF(len); - if (!key) - return NULL; - result = PyDict_GetItemProxy(cache, key); - if (result) { - Py_INCREF(result); - Py_DECREF(key); - return result; - } - - if (!PyType_Check(itemtype)) { - PyErr_SetString(PyExc_TypeError, - "Expected a type object"); - return NULL; - } + static PyObject *cache; + PyObject *key; + PyObject *result; + char name[256]; + PyObject *len; + + if (cache == NULL) { + cache = PyDict_New(); + if (cache == NULL) + return NULL; + } + len = PyLong_FromSsize_t(length); + if (len == NULL) + return NULL; + key = PyTuple_Pack(2, itemtype, len); + Py_DECREF(len); + if (!key) + return NULL; + result = PyDict_GetItemProxy(cache, key); + if (result) { + Py_INCREF(result); + Py_DECREF(key); + return result; + } + + if (!PyType_Check(itemtype)) { + PyErr_SetString(PyExc_TypeError, + "Expected a type object"); + return NULL; + } #ifdef MS_WIN64 - sprintf(name, "%.200s_Array_%Id", - ((PyTypeObject *)itemtype)->tp_name, length); + sprintf(name, "%.200s_Array_%Id", + ((PyTypeObject *)itemtype)->tp_name, length); #else - sprintf(name, "%.200s_Array_%ld", - ((PyTypeObject *)itemtype)->tp_name, (long)length); + sprintf(name, "%.200s_Array_%ld", + ((PyTypeObject *)itemtype)->tp_name, (long)length); #endif - result = PyObject_CallFunction((PyObject *)&PyCArrayType_Type, - "U(O){s:n,s:O}", - name, - &PyCArray_Type, - "_length_", - length, - "_type_", - itemtype - ); - if (result == NULL) { - Py_DECREF(key); - return NULL; - } - if (-1 == PyDict_SetItemProxy(cache, key, result)) { - Py_DECREF(key); - Py_DECREF(result); - return NULL; - } - Py_DECREF(key); - return result; + result = PyObject_CallFunction((PyObject *)&PyCArrayType_Type, + "U(O){s:n,s:O}", + name, + &PyCArray_Type, + "_length_", + length, + "_type_", + itemtype + ); + if (result == NULL) { + Py_DECREF(key); + return NULL; + } + if (-1 == PyDict_SetItemProxy(cache, key, result)) { + Py_DECREF(key); + Py_DECREF(result); + return NULL; + } + Py_DECREF(key); + return result; } - + /******************************************************************/ /* Simple_Type @@ -4497,166 +4497,166 @@ static int Simple_set_value(CDataObject *self, PyObject *value) { - PyObject *result; - StgDictObject *dict = PyObject_stgdict((PyObject *)self); + PyObject *result; + StgDictObject *dict = PyObject_stgdict((PyObject *)self); - if (value == NULL) { - PyErr_SetString(PyExc_TypeError, - "can't delete attribute"); - return -1; - } - assert(dict); /* Cannot be NULL for CDataObject instances */ - assert(dict->setfunc); - result = dict->setfunc(self->b_ptr, value, dict->size); - if (!result) - return -1; + if (value == NULL) { + PyErr_SetString(PyExc_TypeError, + "can't delete attribute"); + return -1; + } + assert(dict); /* Cannot be NULL for CDataObject instances */ + assert(dict->setfunc); + result = dict->setfunc(self->b_ptr, value, dict->size); + if (!result) + return -1; - /* consumes the refcount the setfunc returns */ - return KeepRef(self, 0, result); + /* consumes the refcount the setfunc returns */ + return KeepRef(self, 0, result); } static int Simple_init(CDataObject *self, PyObject *args, PyObject *kw) { - PyObject *value = NULL; - if (!PyArg_UnpackTuple(args, "__init__", 0, 1, &value)) - return -1; - if (value) - return Simple_set_value(self, value); - return 0; + PyObject *value = NULL; + if (!PyArg_UnpackTuple(args, "__init__", 0, 1, &value)) + return -1; + if (value) + return Simple_set_value(self, value); + return 0; } static PyObject * Simple_get_value(CDataObject *self) { - StgDictObject *dict; - dict = PyObject_stgdict((PyObject *)self); - assert(dict); /* Cannot be NULL for CDataObject instances */ - assert(dict->getfunc); - return dict->getfunc(self->b_ptr, self->b_size); + StgDictObject *dict; + dict = PyObject_stgdict((PyObject *)self); + assert(dict); /* Cannot be NULL for CDataObject instances */ + assert(dict->getfunc); + return dict->getfunc(self->b_ptr, self->b_size); } static PyGetSetDef Simple_getsets[] = { - { "value", (getter)Simple_get_value, (setter)Simple_set_value, - "current value", NULL }, - { NULL, NULL } + { "value", (getter)Simple_get_value, (setter)Simple_set_value, + "current value", NULL }, + { NULL, NULL } }; static PyObject * Simple_from_outparm(PyObject *self, PyObject *args) { - if (_ctypes_simple_instance((PyObject *)Py_TYPE(self))) { - Py_INCREF(self); - return self; - } - /* call stgdict->getfunc */ - return Simple_get_value((CDataObject *)self); + if (_ctypes_simple_instance((PyObject *)Py_TYPE(self))) { + Py_INCREF(self); + return self; + } + /* call stgdict->getfunc */ + return Simple_get_value((CDataObject *)self); } static PyMethodDef Simple_methods[] = { - { "__ctypes_from_outparam__", Simple_from_outparm, METH_NOARGS, }, - { NULL, NULL }, + { "__ctypes_from_outparam__", Simple_from_outparm, METH_NOARGS, }, + { NULL, NULL }, }; static int Simple_bool(CDataObject *self) { - return memcmp(self->b_ptr, "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0", self->b_size); + return memcmp(self->b_ptr, "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0", self->b_size); } static PyNumberMethods Simple_as_number = { - 0, /* nb_add */ - 0, /* nb_subtract */ - 0, /* nb_multiply */ - 0, /* nb_remainder */ - 0, /* nb_divmod */ - 0, /* nb_power */ - 0, /* nb_negative */ - 0, /* nb_positive */ - 0, /* nb_absolute */ - (inquiry)Simple_bool, /* nb_bool */ + 0, /* nb_add */ + 0, /* nb_subtract */ + 0, /* nb_multiply */ + 0, /* nb_remainder */ + 0, /* nb_divmod */ + 0, /* nb_power */ + 0, /* nb_negative */ + 0, /* nb_positive */ + 0, /* nb_absolute */ + (inquiry)Simple_bool, /* nb_bool */ }; /* "%s(%s)" % (self.__class__.__name__, self.value) */ static PyObject * Simple_repr(CDataObject *self) { - PyObject *val, *name, *args, *result; - static PyObject *format; + PyObject *val, *name, *args, *result; + static PyObject *format; - if (Py_TYPE(self)->tp_base != &Simple_Type) { - return PyUnicode_FromFormat("<%s object at %p>", - Py_TYPE(self)->tp_name, self); - } - - if (format == NULL) { - format = PyUnicode_InternFromString("%s(%r)"); - if (format == NULL) - return NULL; - } - - val = Simple_get_value(self); - if (val == NULL) - return NULL; - - name = PyUnicode_FromString(Py_TYPE(self)->tp_name); - if (name == NULL) { - Py_DECREF(val); - return NULL; - } - - args = PyTuple_Pack(2, name, val); - Py_DECREF(name); - Py_DECREF(val); - if (args == NULL) - return NULL; - - result = PyUnicode_Format(format, args); - Py_DECREF(args); - return result; + if (Py_TYPE(self)->tp_base != &Simple_Type) { + return PyUnicode_FromFormat("<%s object at %p>", + Py_TYPE(self)->tp_name, self); + } + + if (format == NULL) { + format = PyUnicode_InternFromString("%s(%r)"); + if (format == NULL) + return NULL; + } + + val = Simple_get_value(self); + if (val == NULL) + return NULL; + + name = PyUnicode_FromString(Py_TYPE(self)->tp_name); + if (name == NULL) { + Py_DECREF(val); + return NULL; + } + + args = PyTuple_Pack(2, name, val); + Py_DECREF(name); + Py_DECREF(val); + if (args == NULL) + return NULL; + + result = PyUnicode_Format(format, args); + Py_DECREF(args); + return result; } static PyTypeObject Simple_Type = { - PyVarObject_HEAD_INIT(NULL, 0) - "_ctypes._SimpleCData", - sizeof(CDataObject), /* tp_basicsize */ - 0, /* tp_itemsize */ - 0, /* tp_dealloc */ - 0, /* tp_print */ - 0, /* tp_getattr */ - 0, /* tp_setattr */ - 0, /* tp_reserved */ - (reprfunc)&Simple_repr, /* tp_repr */ - &Simple_as_number, /* tp_as_number */ - 0, /* tp_as_sequence */ - 0, /* tp_as_mapping */ - 0, /* tp_hash */ - 0, /* tp_call */ - 0, /* tp_str */ - 0, /* tp_getattro */ - 0, /* tp_setattro */ - &PyCData_as_buffer, /* tp_as_buffer */ - Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */ - "XXX to be provided", /* tp_doc */ - (traverseproc)PyCData_traverse, /* tp_traverse */ - (inquiry)PyCData_clear, /* tp_clear */ - 0, /* tp_richcompare */ - 0, /* tp_weaklistoffset */ - 0, /* tp_iter */ - 0, /* tp_iternext */ - Simple_methods, /* tp_methods */ - 0, /* tp_members */ - Simple_getsets, /* tp_getset */ - 0, /* tp_base */ - 0, /* tp_dict */ - 0, /* tp_descr_get */ - 0, /* tp_descr_set */ - 0, /* tp_dictoffset */ - (initproc)Simple_init, /* tp_init */ - 0, /* tp_alloc */ - GenericPyCData_new, /* tp_new */ - 0, /* tp_free */ + PyVarObject_HEAD_INIT(NULL, 0) + "_ctypes._SimpleCData", + sizeof(CDataObject), /* tp_basicsize */ + 0, /* tp_itemsize */ + 0, /* tp_dealloc */ + 0, /* tp_print */ + 0, /* tp_getattr */ + 0, /* tp_setattr */ + 0, /* tp_reserved */ + (reprfunc)&Simple_repr, /* tp_repr */ + &Simple_as_number, /* tp_as_number */ + 0, /* tp_as_sequence */ + 0, /* tp_as_mapping */ + 0, /* tp_hash */ + 0, /* tp_call */ + 0, /* tp_str */ + 0, /* tp_getattro */ + 0, /* tp_setattro */ + &PyCData_as_buffer, /* tp_as_buffer */ + Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */ + "XXX to be provided", /* tp_doc */ + (traverseproc)PyCData_traverse, /* tp_traverse */ + (inquiry)PyCData_clear, /* tp_clear */ + 0, /* tp_richcompare */ + 0, /* tp_weaklistoffset */ + 0, /* tp_iter */ + 0, /* tp_iternext */ + Simple_methods, /* tp_methods */ + 0, /* tp_members */ + Simple_getsets, /* tp_getset */ + 0, /* tp_base */ + 0, /* tp_dict */ + 0, /* tp_descr_get */ + 0, /* tp_descr_set */ + 0, /* tp_dictoffset */ + (initproc)Simple_init, /* tp_init */ + 0, /* tp_alloc */ + GenericPyCData_new, /* tp_new */ + 0, /* tp_free */ }; - + /******************************************************************/ /* PyCPointer_Type @@ -4664,377 +4664,377 @@ static PyObject * Pointer_item(PyObject *_self, Py_ssize_t index) { - CDataObject *self = (CDataObject *)_self; - Py_ssize_t size; - Py_ssize_t offset; - StgDictObject *stgdict, *itemdict; - PyObject *proto; - - if (*(void **)self->b_ptr == NULL) { - PyErr_SetString(PyExc_ValueError, - "NULL pointer access"); - return NULL; - } - - stgdict = PyObject_stgdict((PyObject *)self); - assert(stgdict); /* Cannot be NULL for pointer object instances */ - - proto = stgdict->proto; - assert(proto); - itemdict = PyType_stgdict(proto); - assert(itemdict); /* proto is the item type of the pointer, a ctypes - type, so this cannot be NULL */ + CDataObject *self = (CDataObject *)_self; + Py_ssize_t size; + Py_ssize_t offset; + StgDictObject *stgdict, *itemdict; + PyObject *proto; + + if (*(void **)self->b_ptr == NULL) { + PyErr_SetString(PyExc_ValueError, + "NULL pointer access"); + return NULL; + } + + stgdict = PyObject_stgdict((PyObject *)self); + assert(stgdict); /* Cannot be NULL for pointer object instances */ + + proto = stgdict->proto; + assert(proto); + itemdict = PyType_stgdict(proto); + assert(itemdict); /* proto is the item type of the pointer, a ctypes + type, so this cannot be NULL */ - size = itemdict->size; - offset = index * itemdict->size; + size = itemdict->size; + offset = index * itemdict->size; - return PyCData_get(proto, stgdict->getfunc, (PyObject *)self, - index, size, (*(char **)self->b_ptr) + offset); + return PyCData_get(proto, stgdict->getfunc, (PyObject *)self, + index, size, (*(char **)self->b_ptr) + offset); } static int Pointer_ass_item(PyObject *_self, Py_ssize_t index, PyObject *value) { - CDataObject *self = (CDataObject *)_self; - Py_ssize_t size; - Py_ssize_t offset; - StgDictObject *stgdict, *itemdict; - PyObject *proto; - - if (value == NULL) { - PyErr_SetString(PyExc_TypeError, - "Pointer does not support item deletion"); - return -1; - } - - if (*(void **)self->b_ptr == NULL) { - PyErr_SetString(PyExc_ValueError, - "NULL pointer access"); - return -1; - } - - stgdict = PyObject_stgdict((PyObject *)self); - assert(stgdict); /* Cannot be NULL fr pointer instances */ - - proto = stgdict->proto; - assert(proto); - - itemdict = PyType_stgdict(proto); - assert(itemdict); /* Cannot be NULL because the itemtype of a pointer - is always a ctypes type */ + CDataObject *self = (CDataObject *)_self; + Py_ssize_t size; + Py_ssize_t offset; + StgDictObject *stgdict, *itemdict; + PyObject *proto; + + if (value == NULL) { + PyErr_SetString(PyExc_TypeError, + "Pointer does not support item deletion"); + return -1; + } + + if (*(void **)self->b_ptr == NULL) { + PyErr_SetString(PyExc_ValueError, + "NULL pointer access"); + return -1; + } + + stgdict = PyObject_stgdict((PyObject *)self); + assert(stgdict); /* Cannot be NULL fr pointer instances */ + + proto = stgdict->proto; + assert(proto); - size = itemdict->size; - offset = index * itemdict->size; + itemdict = PyType_stgdict(proto); + assert(itemdict); /* Cannot be NULL because the itemtype of a pointer + is always a ctypes type */ - return PyCData_set((PyObject *)self, proto, stgdict->setfunc, value, - index, size, (*(char **)self->b_ptr) + offset); + size = itemdict->size; + offset = index * itemdict->size; + + return PyCData_set((PyObject *)self, proto, stgdict->setfunc, value, + index, size, (*(char **)self->b_ptr) + offset); } static PyObject * Pointer_get_contents(CDataObject *self, void *closure) { - StgDictObject *stgdict; + StgDictObject *stgdict; - if (*(void **)self->b_ptr == NULL) { - PyErr_SetString(PyExc_ValueError, - "NULL pointer access"); - return NULL; - } - - stgdict = PyObject_stgdict((PyObject *)self); - assert(stgdict); /* Cannot be NULL fr pointer instances */ - return PyCData_FromBaseObj(stgdict->proto, - (PyObject *)self, 0, - *(void **)self->b_ptr); + if (*(void **)self->b_ptr == NULL) { + PyErr_SetString(PyExc_ValueError, + "NULL pointer access"); + return NULL; + } + + stgdict = PyObject_stgdict((PyObject *)self); + assert(stgdict); /* Cannot be NULL fr pointer instances */ + return PyCData_FromBaseObj(stgdict->proto, + (PyObject *)self, 0, + *(void **)self->b_ptr); } static int Pointer_set_contents(CDataObject *self, PyObject *value, void *closure) { - StgDictObject *stgdict; - CDataObject *dst; - PyObject *keep; - - if (value == NULL) { - PyErr_SetString(PyExc_TypeError, - "Pointer does not support item deletion"); - return -1; - } - stgdict = PyObject_stgdict((PyObject *)self); - assert(stgdict); /* Cannot be NULL fr pointer instances */ - assert(stgdict->proto); - if (!CDataObject_Check(value) - || 0 == PyObject_IsInstance(value, stgdict->proto)) { - /* XXX PyObject_IsInstance could return -1! */ - PyErr_Format(PyExc_TypeError, - "expected %s instead of %s", - ((PyTypeObject *)(stgdict->proto))->tp_name, - Py_TYPE(value)->tp_name); - return -1; - } - - dst = (CDataObject *)value; - *(void **)self->b_ptr = dst->b_ptr; - - /* - A Pointer instance must keep a the value it points to alive. So, a - pointer instance has b_length set to 2 instead of 1, and we set - 'value' itself as the second item of the b_objects list, additionally. - */ - Py_INCREF(value); - if (-1 == KeepRef(self, 1, value)) - return -1; - - keep = GetKeepedObjects(dst); - Py_INCREF(keep); - return KeepRef(self, 0, keep); + StgDictObject *stgdict; + CDataObject *dst; + PyObject *keep; + + if (value == NULL) { + PyErr_SetString(PyExc_TypeError, + "Pointer does not support item deletion"); + return -1; + } + stgdict = PyObject_stgdict((PyObject *)self); + assert(stgdict); /* Cannot be NULL fr pointer instances */ + assert(stgdict->proto); + if (!CDataObject_Check(value) + || 0 == PyObject_IsInstance(value, stgdict->proto)) { + /* XXX PyObject_IsInstance could return -1! */ + PyErr_Format(PyExc_TypeError, + "expected %s instead of %s", + ((PyTypeObject *)(stgdict->proto))->tp_name, + Py_TYPE(value)->tp_name); + return -1; + } + + dst = (CDataObject *)value; + *(void **)self->b_ptr = dst->b_ptr; + + /* + A Pointer instance must keep a the value it points to alive. So, a + pointer instance has b_length set to 2 instead of 1, and we set + 'value' itself as the second item of the b_objects list, additionally. + */ + Py_INCREF(value); + if (-1 == KeepRef(self, 1, value)) + return -1; + + keep = GetKeepedObjects(dst); + Py_INCREF(keep); + return KeepRef(self, 0, keep); } static PyGetSetDef Pointer_getsets[] = { - { "contents", (getter)Pointer_get_contents, - (setter)Pointer_set_contents, - "the object this pointer points to (read-write)", NULL }, - { NULL, NULL } + { "contents", (getter)Pointer_get_contents, + (setter)Pointer_set_contents, + "the object this pointer points to (read-write)", NULL }, + { NULL, NULL } }; static int Pointer_init(CDataObject *self, PyObject *args, PyObject *kw) { - PyObject *value = NULL; + PyObject *value = NULL; - if (!PyArg_UnpackTuple(args, "POINTER", 0, 1, &value)) - return -1; - if (value == NULL) - return 0; - return Pointer_set_contents(self, value, NULL); + if (!PyArg_UnpackTuple(args, "POINTER", 0, 1, &value)) + return -1; + if (value == NULL) + return 0; + return Pointer_set_contents(self, value, NULL); } static PyObject * Pointer_new(PyTypeObject *type, PyObject *args, PyObject *kw) { - StgDictObject *dict = PyType_stgdict((PyObject *)type); - if (!dict || !dict->proto) { - PyErr_SetString(PyExc_TypeError, - "Cannot create instance: has no _type_"); - return NULL; - } - return GenericPyCData_new(type, args, kw); + StgDictObject *dict = PyType_stgdict((PyObject *)type); + if (!dict || !dict->proto) { + PyErr_SetString(PyExc_TypeError, + "Cannot create instance: has no _type_"); + return NULL; + } + return GenericPyCData_new(type, args, kw); } static PyObject * Pointer_subscript(PyObject *_self, PyObject *item) { - CDataObject *self = (CDataObject *)_self; - if (PyIndex_Check(item)) { - Py_ssize_t i = PyNumber_AsSsize_t(item, PyExc_IndexError); - if (i == -1 && PyErr_Occurred()) - return NULL; - return Pointer_item(_self, i); - } - else if (PySlice_Check(item)) { - PySliceObject *slice = (PySliceObject *)item; - Py_ssize_t start, stop, step; - PyObject *np; - StgDictObject *stgdict, *itemdict; - PyObject *proto; - Py_ssize_t i, len, cur; - - /* Since pointers have no length, and we want to apply - different semantics to negative indices than normal - slicing, we have to dissect the slice object ourselves.*/ - if (slice->step == Py_None) { - step = 1; - } - else { - step = PyNumber_AsSsize_t(slice->step, - PyExc_ValueError); - if (step == -1 && PyErr_Occurred()) - return NULL; - if (step == 0) { - PyErr_SetString(PyExc_ValueError, - "slice step cannot be zero"); - return NULL; - } - } - if (slice->start == Py_None) { - if (step < 0) { - PyErr_SetString(PyExc_ValueError, - "slice start is required " - "for step < 0"); - return NULL; - } - start = 0; - } - else { - start = PyNumber_AsSsize_t(slice->start, - PyExc_ValueError); - if (start == -1 && PyErr_Occurred()) - return NULL; - } - if (slice->stop == Py_None) { - PyErr_SetString(PyExc_ValueError, - "slice stop is required"); - return NULL; - } - stop = PyNumber_AsSsize_t(slice->stop, - PyExc_ValueError); - if (stop == -1 && PyErr_Occurred()) - return NULL; - if ((step > 0 && start > stop) || - (step < 0 && start < stop)) - len = 0; - else if (step > 0) - len = (stop - start - 1) / step + 1; - else - len = (stop - start + 1) / step + 1; - - stgdict = PyObject_stgdict((PyObject *)self); - assert(stgdict); /* Cannot be NULL for pointer instances */ - proto = stgdict->proto; - assert(proto); - itemdict = PyType_stgdict(proto); - assert(itemdict); - if (itemdict->getfunc == _ctypes_get_fielddesc("c")->getfunc) { - char *ptr = *(char **)self->b_ptr; - char *dest; - - if (len <= 0) - return PyBytes_FromStringAndSize("", 0); - if (step == 1) { - return PyBytes_FromStringAndSize(ptr + start, - len); - } - dest = (char *)PyMem_Malloc(len); - if (dest == NULL) - return PyErr_NoMemory(); - for (cur = start, i = 0; i < len; cur += step, i++) { - dest[i] = ptr[cur]; - } - np = PyBytes_FromStringAndSize(dest, len); - PyMem_Free(dest); - return np; - } + CDataObject *self = (CDataObject *)_self; + if (PyIndex_Check(item)) { + Py_ssize_t i = PyNumber_AsSsize_t(item, PyExc_IndexError); + if (i == -1 && PyErr_Occurred()) + return NULL; + return Pointer_item(_self, i); + } + else if (PySlice_Check(item)) { + PySliceObject *slice = (PySliceObject *)item; + Py_ssize_t start, stop, step; + PyObject *np; + StgDictObject *stgdict, *itemdict; + PyObject *proto; + Py_ssize_t i, len, cur; + + /* Since pointers have no length, and we want to apply + different semantics to negative indices than normal + slicing, we have to dissect the slice object ourselves.*/ + if (slice->step == Py_None) { + step = 1; + } + else { + step = PyNumber_AsSsize_t(slice->step, + PyExc_ValueError); + if (step == -1 && PyErr_Occurred()) + return NULL; + if (step == 0) { + PyErr_SetString(PyExc_ValueError, + "slice step cannot be zero"); + return NULL; + } + } + if (slice->start == Py_None) { + if (step < 0) { + PyErr_SetString(PyExc_ValueError, + "slice start is required " + "for step < 0"); + return NULL; + } + start = 0; + } + else { + start = PyNumber_AsSsize_t(slice->start, + PyExc_ValueError); + if (start == -1 && PyErr_Occurred()) + return NULL; + } + if (slice->stop == Py_None) { + PyErr_SetString(PyExc_ValueError, + "slice stop is required"); + return NULL; + } + stop = PyNumber_AsSsize_t(slice->stop, + PyExc_ValueError); + if (stop == -1 && PyErr_Occurred()) + return NULL; + if ((step > 0 && start > stop) || + (step < 0 && start < stop)) + len = 0; + else if (step > 0) + len = (stop - start - 1) / step + 1; + else + len = (stop - start + 1) / step + 1; + + stgdict = PyObject_stgdict((PyObject *)self); + assert(stgdict); /* Cannot be NULL for pointer instances */ + proto = stgdict->proto; + assert(proto); + itemdict = PyType_stgdict(proto); + assert(itemdict); + if (itemdict->getfunc == _ctypes_get_fielddesc("c")->getfunc) { + char *ptr = *(char **)self->b_ptr; + char *dest; + + if (len <= 0) + return PyBytes_FromStringAndSize("", 0); + if (step == 1) { + return PyBytes_FromStringAndSize(ptr + start, + len); + } + dest = (char *)PyMem_Malloc(len); + if (dest == NULL) + return PyErr_NoMemory(); + for (cur = start, i = 0; i < len; cur += step, i++) { + dest[i] = ptr[cur]; + } + np = PyBytes_FromStringAndSize(dest, len); + PyMem_Free(dest); + return np; + } #ifdef CTYPES_UNICODE - if (itemdict->getfunc == _ctypes_get_fielddesc("u")->getfunc) { - wchar_t *ptr = *(wchar_t **)self->b_ptr; - wchar_t *dest; - - if (len <= 0) - return PyUnicode_FromUnicode(NULL, 0); - if (step == 1) { - return PyUnicode_FromWideChar(ptr + start, - len); - } - dest = (wchar_t *)PyMem_Malloc(len * sizeof(wchar_t)); - if (dest == NULL) - return PyErr_NoMemory(); - for (cur = start, i = 0; i < len; cur += step, i++) { - dest[i] = ptr[cur]; - } - np = PyUnicode_FromWideChar(dest, len); - PyMem_Free(dest); - return np; - } + if (itemdict->getfunc == _ctypes_get_fielddesc("u")->getfunc) { + wchar_t *ptr = *(wchar_t **)self->b_ptr; + wchar_t *dest; + + if (len <= 0) + return PyUnicode_FromUnicode(NULL, 0); + if (step == 1) { + return PyUnicode_FromWideChar(ptr + start, + len); + } + dest = (wchar_t *)PyMem_Malloc(len * sizeof(wchar_t)); + if (dest == NULL) + return PyErr_NoMemory(); + for (cur = start, i = 0; i < len; cur += step, i++) { + dest[i] = ptr[cur]; + } + np = PyUnicode_FromWideChar(dest, len); + PyMem_Free(dest); + return np; + } #endif - np = PyList_New(len); - if (np == NULL) - return NULL; - - for (cur = start, i = 0; i < len; cur += step, i++) { - PyObject *v = Pointer_item(_self, cur); - PyList_SET_ITEM(np, i, v); - } - return np; - } - else { - PyErr_SetString(PyExc_TypeError, - "Pointer indices must be integer"); - return NULL; - } + np = PyList_New(len); + if (np == NULL) + return NULL; + + for (cur = start, i = 0; i < len; cur += step, i++) { + PyObject *v = Pointer_item(_self, cur); + PyList_SET_ITEM(np, i, v); + } + return np; + } + else { + PyErr_SetString(PyExc_TypeError, + "Pointer indices must be integer"); + return NULL; + } } static PySequenceMethods Pointer_as_sequence = { - 0, /* inquiry sq_length; */ - 0, /* binaryfunc sq_concat; */ - 0, /* intargfunc sq_repeat; */ - Pointer_item, /* intargfunc sq_item; */ - 0, /* intintargfunc sq_slice; */ - Pointer_ass_item, /* intobjargproc sq_ass_item; */ - 0, /* intintobjargproc sq_ass_slice; */ - 0, /* objobjproc sq_contains; */ - /* Added in release 2.0 */ - 0, /* binaryfunc sq_inplace_concat; */ - 0, /* intargfunc sq_inplace_repeat; */ + 0, /* inquiry sq_length; */ + 0, /* binaryfunc sq_concat; */ + 0, /* intargfunc sq_repeat; */ + Pointer_item, /* intargfunc sq_item; */ + 0, /* intintargfunc sq_slice; */ + Pointer_ass_item, /* intobjargproc sq_ass_item; */ + 0, /* intintobjargproc sq_ass_slice; */ + 0, /* objobjproc sq_contains; */ + /* Added in release 2.0 */ + 0, /* binaryfunc sq_inplace_concat; */ + 0, /* intargfunc sq_inplace_repeat; */ }; static PyMappingMethods Pointer_as_mapping = { - 0, - Pointer_subscript, + 0, + Pointer_subscript, }; static int Pointer_bool(CDataObject *self) { - return (*(void **)self->b_ptr != NULL); + return (*(void **)self->b_ptr != NULL); } static PyNumberMethods Pointer_as_number = { - 0, /* nb_add */ - 0, /* nb_subtract */ - 0, /* nb_multiply */ - 0, /* nb_remainder */ - 0, /* nb_divmod */ - 0, /* nb_power */ - 0, /* nb_negative */ - 0, /* nb_positive */ - 0, /* nb_absolute */ - (inquiry)Pointer_bool, /* nb_bool */ + 0, /* nb_add */ + 0, /* nb_subtract */ + 0, /* nb_multiply */ + 0, /* nb_remainder */ + 0, /* nb_divmod */ + 0, /* nb_power */ + 0, /* nb_negative */ + 0, /* nb_positive */ + 0, /* nb_absolute */ + (inquiry)Pointer_bool, /* nb_bool */ }; PyTypeObject PyCPointer_Type = { - PyVarObject_HEAD_INIT(NULL, 0) - "_ctypes._Pointer", - sizeof(CDataObject), /* tp_basicsize */ - 0, /* tp_itemsize */ - 0, /* tp_dealloc */ - 0, /* tp_print */ - 0, /* tp_getattr */ - 0, /* tp_setattr */ - 0, /* tp_reserved */ - 0, /* tp_repr */ - &Pointer_as_number, /* tp_as_number */ - &Pointer_as_sequence, /* tp_as_sequence */ - &Pointer_as_mapping, /* tp_as_mapping */ - 0, /* tp_hash */ - 0, /* tp_call */ - 0, /* tp_str */ - 0, /* tp_getattro */ - 0, /* tp_setattro */ - &PyCData_as_buffer, /* tp_as_buffer */ - Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */ - "XXX to be provided", /* tp_doc */ - (traverseproc)PyCData_traverse, /* tp_traverse */ - (inquiry)PyCData_clear, /* tp_clear */ - 0, /* tp_richcompare */ - 0, /* tp_weaklistoffset */ - 0, /* tp_iter */ - 0, /* tp_iternext */ - 0, /* tp_methods */ - 0, /* tp_members */ - Pointer_getsets, /* tp_getset */ - 0, /* tp_base */ - 0, /* tp_dict */ - 0, /* tp_descr_get */ - 0, /* tp_descr_set */ - 0, /* tp_dictoffset */ - (initproc)Pointer_init, /* tp_init */ - 0, /* tp_alloc */ - Pointer_new, /* tp_new */ - 0, /* tp_free */ + PyVarObject_HEAD_INIT(NULL, 0) + "_ctypes._Pointer", + sizeof(CDataObject), /* tp_basicsize */ + 0, /* tp_itemsize */ + 0, /* tp_dealloc */ + 0, /* tp_print */ + 0, /* tp_getattr */ + 0, /* tp_setattr */ + 0, /* tp_reserved */ + 0, /* tp_repr */ + &Pointer_as_number, /* tp_as_number */ + &Pointer_as_sequence, /* tp_as_sequence */ + &Pointer_as_mapping, /* tp_as_mapping */ + 0, /* tp_hash */ + 0, /* tp_call */ + 0, /* tp_str */ + 0, /* tp_getattro */ + 0, /* tp_setattro */ + &PyCData_as_buffer, /* tp_as_buffer */ + Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */ + "XXX to be provided", /* tp_doc */ + (traverseproc)PyCData_traverse, /* tp_traverse */ + (inquiry)PyCData_clear, /* tp_clear */ + 0, /* tp_richcompare */ + 0, /* tp_weaklistoffset */ + 0, /* tp_iter */ + 0, /* tp_iternext */ + 0, /* tp_methods */ + 0, /* tp_members */ + Pointer_getsets, /* tp_getset */ + 0, /* tp_base */ + 0, /* tp_dict */ + 0, /* tp_descr_get */ + 0, /* tp_descr_set */ + 0, /* tp_dictoffset */ + (initproc)Pointer_init, /* tp_init */ + 0, /* tp_alloc */ + Pointer_new, /* tp_new */ + 0, /* tp_free */ }; - + /******************************************************************/ /* * Module initialization. @@ -5056,27 +5056,27 @@ int status; if (!_PyArg_NoKeywords(Py_TYPE(self)->tp_name, kwds)) - return -1; + return -1; if (!PyArg_ParseTuple(args, "OOO:COMError", &hresult, &text, &details)) - return -1; + return -1; a = PySequence_GetSlice(args, 1, PySequence_Size(args)); if (!a) - return -1; + return -1; status = PyObject_SetAttrString(self, "args", a); Py_DECREF(a); if (status < 0) - return -1; + return -1; if (PyObject_SetAttrString(self, "hresult", hresult) < 0) - return -1; + return -1; if (PyObject_SetAttrString(self, "text", text) < 0) - return -1; + return -1; if (PyObject_SetAttrString(self, "details", details) < 0) - return -1; + return -1; bself = (PyBaseExceptionObject *)self; Py_DECREF(bself->args); @@ -5131,11 +5131,11 @@ static int create_comerror(void) { - PyComError_Type.tp_base = (PyTypeObject*)PyExc_Exception; - if (PyType_Ready(&PyComError_Type) < 0) - return -1; - ComError = (PyObject*)&PyComError_Type; - return 0; + PyComError_Type.tp_base = (PyTypeObject*)PyExc_Exception; + if (PyType_Ready(&PyComError_Type) < 0) + return -1; + ComError = (PyObject*)&PyComError_Type; + return 0; } #endif @@ -5143,259 +5143,259 @@ static PyObject * string_at(const char *ptr, int size) { - if (size == -1) - return PyBytes_FromStringAndSize(ptr, strlen(ptr)); - return PyBytes_FromStringAndSize(ptr, size); + if (size == -1) + return PyBytes_FromStringAndSize(ptr, strlen(ptr)); + return PyBytes_FromStringAndSize(ptr, size); } static int cast_check_pointertype(PyObject *arg) { - StgDictObject *dict; + StgDictObject *dict; - if (PyCPointerTypeObject_Check(arg)) - return 1; - if (PyCFuncPtrTypeObject_Check(arg)) - return 1; - dict = PyType_stgdict(arg); - if (dict) { - if (PyUnicode_Check(dict->proto) - && (strchr("sPzUZXO", _PyUnicode_AsString(dict->proto)[0]))) { - /* simple pointer types, c_void_p, c_wchar_p, BSTR, ... */ - return 1; - } - } - PyErr_Format(PyExc_TypeError, - "cast() argument 2 must be a pointer type, not %s", - PyType_Check(arg) - ? ((PyTypeObject *)arg)->tp_name - : Py_TYPE(arg)->tp_name); - return 0; + if (PyCPointerTypeObject_Check(arg)) + return 1; + if (PyCFuncPtrTypeObject_Check(arg)) + return 1; + dict = PyType_stgdict(arg); + if (dict) { + if (PyUnicode_Check(dict->proto) + && (strchr("sPzUZXO", _PyUnicode_AsString(dict->proto)[0]))) { + /* simple pointer types, c_void_p, c_wchar_p, BSTR, ... */ + return 1; + } + } + PyErr_Format(PyExc_TypeError, + "cast() argument 2 must be a pointer type, not %s", + PyType_Check(arg) + ? ((PyTypeObject *)arg)->tp_name + : Py_TYPE(arg)->tp_name); + return 0; } static PyObject * cast(void *ptr, PyObject *src, PyObject *ctype) { - CDataObject *result; - if (0 == cast_check_pointertype(ctype)) - return NULL; - result = (CDataObject *)PyObject_CallFunctionObjArgs(ctype, NULL); - if (result == NULL) - return NULL; - - /* - The casted objects '_objects' member: - - It must certainly contain the source objects one. - It must contain the source object itself. - */ - if (CDataObject_Check(src)) { - CDataObject *obj = (CDataObject *)src; - /* PyCData_GetContainer will initialize src.b_objects, we need - this so it can be shared */ - PyCData_GetContainer(obj); - /* But we need a dictionary! */ - if (obj->b_objects == Py_None) { - Py_DECREF(Py_None); - obj->b_objects = PyDict_New(); - if (obj->b_objects == NULL) - goto failed; - } - Py_XINCREF(obj->b_objects); - result->b_objects = obj->b_objects; - if (result->b_objects && PyDict_CheckExact(result->b_objects)) { - PyObject *index; - int rc; - index = PyLong_FromVoidPtr((void *)src); - if (index == NULL) - goto failed; - rc = PyDict_SetItem(result->b_objects, index, src); - Py_DECREF(index); - if (rc == -1) - goto failed; - } - } - /* Should we assert that result is a pointer type? */ - memcpy(result->b_ptr, &ptr, sizeof(void *)); - return (PyObject *)result; + CDataObject *result; + if (0 == cast_check_pointertype(ctype)) + return NULL; + result = (CDataObject *)PyObject_CallFunctionObjArgs(ctype, NULL); + if (result == NULL) + return NULL; + + /* + The casted objects '_objects' member: + + It must certainly contain the source objects one. + It must contain the source object itself. + */ + if (CDataObject_Check(src)) { + CDataObject *obj = (CDataObject *)src; + /* PyCData_GetContainer will initialize src.b_objects, we need + this so it can be shared */ + PyCData_GetContainer(obj); + /* But we need a dictionary! */ + if (obj->b_objects == Py_None) { + Py_DECREF(Py_None); + obj->b_objects = PyDict_New(); + if (obj->b_objects == NULL) + goto failed; + } + Py_XINCREF(obj->b_objects); + result->b_objects = obj->b_objects; + if (result->b_objects && PyDict_CheckExact(result->b_objects)) { + PyObject *index; + int rc; + index = PyLong_FromVoidPtr((void *)src); + if (index == NULL) + goto failed; + rc = PyDict_SetItem(result->b_objects, index, src); + Py_DECREF(index); + if (rc == -1) + goto failed; + } + } + /* Should we assert that result is a pointer type? */ + memcpy(result->b_ptr, &ptr, sizeof(void *)); + return (PyObject *)result; failed: - Py_DECREF(result); - return NULL; + Py_DECREF(result); + return NULL; } #ifdef CTYPES_UNICODE static PyObject * wstring_at(const wchar_t *ptr, int size) { - Py_ssize_t ssize = size; - if (ssize == -1) - ssize = wcslen(ptr); - return PyUnicode_FromWideChar(ptr, ssize); + Py_ssize_t ssize = size; + if (ssize == -1) + ssize = wcslen(ptr); + return PyUnicode_FromWideChar(ptr, ssize); } #endif static struct PyModuleDef _ctypesmodule = { - PyModuleDef_HEAD_INIT, - "_ctypes", - module_docs, - -1, - _ctypes_module_methods, - NULL, - NULL, - NULL, - NULL + PyModuleDef_HEAD_INIT, + "_ctypes", + module_docs, + -1, + _ctypes_module_methods, + NULL, + NULL, + NULL, + NULL }; PyMODINIT_FUNC PyInit__ctypes(void) { - PyObject *m; + PyObject *m; /* Note: ob_type is the metatype (the 'type'), defaults to PyType_Type, tp_base is the base type, defaults to 'object' aka PyBaseObject_Type. */ #ifdef WITH_THREAD - PyEval_InitThreads(); + PyEval_InitThreads(); #endif - m = PyModule_Create(&_ctypesmodule); - if (!m) - return NULL; - - _ctypes_ptrtype_cache = PyDict_New(); - if (_ctypes_ptrtype_cache == NULL) - return NULL; - - PyModule_AddObject(m, "_pointer_type_cache", (PyObject *)_ctypes_ptrtype_cache); - - _unpickle = PyObject_GetAttrString(m, "_unpickle"); - if (_unpickle == NULL) - return NULL; - - if (PyType_Ready(&PyCArg_Type) < 0) - return NULL; - - if (PyType_Ready(&PyCThunk_Type) < 0) - return NULL; - - /* StgDict is derived from PyDict_Type */ - PyCStgDict_Type.tp_base = &PyDict_Type; - if (PyType_Ready(&PyCStgDict_Type) < 0) - return NULL; - - /************************************************* - * - * Metaclasses - */ - - PyCStructType_Type.tp_base = &PyType_Type; - if (PyType_Ready(&PyCStructType_Type) < 0) - return NULL; - - UnionType_Type.tp_base = &PyType_Type; - if (PyType_Ready(&UnionType_Type) < 0) - return NULL; - - PyCPointerType_Type.tp_base = &PyType_Type; - if (PyType_Ready(&PyCPointerType_Type) < 0) - return NULL; - - PyCArrayType_Type.tp_base = &PyType_Type; - if (PyType_Ready(&PyCArrayType_Type) < 0) - return NULL; - - PyCSimpleType_Type.tp_base = &PyType_Type; - if (PyType_Ready(&PyCSimpleType_Type) < 0) - return NULL; - - PyCFuncPtrType_Type.tp_base = &PyType_Type; - if (PyType_Ready(&PyCFuncPtrType_Type) < 0) - return NULL; - - /************************************************* - * - * Classes using a custom metaclass - */ - - if (PyType_Ready(&PyCData_Type) < 0) - return NULL; - - Py_TYPE(&Struct_Type) = &PyCStructType_Type; - Struct_Type.tp_base = &PyCData_Type; - if (PyType_Ready(&Struct_Type) < 0) - return NULL; - PyModule_AddObject(m, "Structure", (PyObject *)&Struct_Type); - - Py_TYPE(&Union_Type) = &UnionType_Type; - Union_Type.tp_base = &PyCData_Type; - if (PyType_Ready(&Union_Type) < 0) - return NULL; - PyModule_AddObject(m, "Union", (PyObject *)&Union_Type); - - Py_TYPE(&PyCPointer_Type) = &PyCPointerType_Type; - PyCPointer_Type.tp_base = &PyCData_Type; - if (PyType_Ready(&PyCPointer_Type) < 0) - return NULL; - PyModule_AddObject(m, "_Pointer", (PyObject *)&PyCPointer_Type); - - Py_TYPE(&PyCArray_Type) = &PyCArrayType_Type; - PyCArray_Type.tp_base = &PyCData_Type; - if (PyType_Ready(&PyCArray_Type) < 0) - return NULL; - PyModule_AddObject(m, "Array", (PyObject *)&PyCArray_Type); - - Py_TYPE(&Simple_Type) = &PyCSimpleType_Type; - Simple_Type.tp_base = &PyCData_Type; - if (PyType_Ready(&Simple_Type) < 0) - return NULL; - PyModule_AddObject(m, "_SimpleCData", (PyObject *)&Simple_Type); - - Py_TYPE(&PyCFuncPtr_Type) = &PyCFuncPtrType_Type; - PyCFuncPtr_Type.tp_base = &PyCData_Type; - if (PyType_Ready(&PyCFuncPtr_Type) < 0) - return NULL; - PyModule_AddObject(m, "CFuncPtr", (PyObject *)&PyCFuncPtr_Type); - - /************************************************* - * - * Simple classes - */ - - /* PyCField_Type is derived from PyBaseObject_Type */ - if (PyType_Ready(&PyCField_Type) < 0) - return NULL; - - /************************************************* - * - * Other stuff - */ - - DictRemover_Type.tp_new = PyType_GenericNew; - if (PyType_Ready(&DictRemover_Type) < 0) - return NULL; + m = PyModule_Create(&_ctypesmodule); + if (!m) + return NULL; + + _ctypes_ptrtype_cache = PyDict_New(); + if (_ctypes_ptrtype_cache == NULL) + return NULL; + + PyModule_AddObject(m, "_pointer_type_cache", (PyObject *)_ctypes_ptrtype_cache); + + _unpickle = PyObject_GetAttrString(m, "_unpickle"); + if (_unpickle == NULL) + return NULL; + + if (PyType_Ready(&PyCArg_Type) < 0) + return NULL; + + if (PyType_Ready(&PyCThunk_Type) < 0) + return NULL; + + /* StgDict is derived from PyDict_Type */ + PyCStgDict_Type.tp_base = &PyDict_Type; + if (PyType_Ready(&PyCStgDict_Type) < 0) + return NULL; + + /************************************************* + * + * Metaclasses + */ + + PyCStructType_Type.tp_base = &PyType_Type; + if (PyType_Ready(&PyCStructType_Type) < 0) + return NULL; + + UnionType_Type.tp_base = &PyType_Type; + if (PyType_Ready(&UnionType_Type) < 0) + return NULL; + + PyCPointerType_Type.tp_base = &PyType_Type; + if (PyType_Ready(&PyCPointerType_Type) < 0) + return NULL; + + PyCArrayType_Type.tp_base = &PyType_Type; + if (PyType_Ready(&PyCArrayType_Type) < 0) + return NULL; + + PyCSimpleType_Type.tp_base = &PyType_Type; + if (PyType_Ready(&PyCSimpleType_Type) < 0) + return NULL; + + PyCFuncPtrType_Type.tp_base = &PyType_Type; + if (PyType_Ready(&PyCFuncPtrType_Type) < 0) + return NULL; + + /************************************************* + * + * Classes using a custom metaclass + */ + + if (PyType_Ready(&PyCData_Type) < 0) + return NULL; + + Py_TYPE(&Struct_Type) = &PyCStructType_Type; + Struct_Type.tp_base = &PyCData_Type; + if (PyType_Ready(&Struct_Type) < 0) + return NULL; + PyModule_AddObject(m, "Structure", (PyObject *)&Struct_Type); + + Py_TYPE(&Union_Type) = &UnionType_Type; + Union_Type.tp_base = &PyCData_Type; + if (PyType_Ready(&Union_Type) < 0) + return NULL; + PyModule_AddObject(m, "Union", (PyObject *)&Union_Type); + + Py_TYPE(&PyCPointer_Type) = &PyCPointerType_Type; + PyCPointer_Type.tp_base = &PyCData_Type; + if (PyType_Ready(&PyCPointer_Type) < 0) + return NULL; + PyModule_AddObject(m, "_Pointer", (PyObject *)&PyCPointer_Type); + + Py_TYPE(&PyCArray_Type) = &PyCArrayType_Type; + PyCArray_Type.tp_base = &PyCData_Type; + if (PyType_Ready(&PyCArray_Type) < 0) + return NULL; + PyModule_AddObject(m, "Array", (PyObject *)&PyCArray_Type); + + Py_TYPE(&Simple_Type) = &PyCSimpleType_Type; + Simple_Type.tp_base = &PyCData_Type; + if (PyType_Ready(&Simple_Type) < 0) + return NULL; + PyModule_AddObject(m, "_SimpleCData", (PyObject *)&Simple_Type); + + Py_TYPE(&PyCFuncPtr_Type) = &PyCFuncPtrType_Type; + PyCFuncPtr_Type.tp_base = &PyCData_Type; + if (PyType_Ready(&PyCFuncPtr_Type) < 0) + return NULL; + PyModule_AddObject(m, "CFuncPtr", (PyObject *)&PyCFuncPtr_Type); + + /************************************************* + * + * Simple classes + */ + + /* PyCField_Type is derived from PyBaseObject_Type */ + if (PyType_Ready(&PyCField_Type) < 0) + return NULL; + + /************************************************* + * + * Other stuff + */ + + DictRemover_Type.tp_new = PyType_GenericNew; + if (PyType_Ready(&DictRemover_Type) < 0) + return NULL; #ifdef MS_WIN32 - if (create_comerror() < 0) - return NULL; - PyModule_AddObject(m, "COMError", ComError); + if (create_comerror() < 0) + return NULL; + PyModule_AddObject(m, "COMError", ComError); - PyModule_AddObject(m, "FUNCFLAG_HRESULT", PyLong_FromLong(FUNCFLAG_HRESULT)); - PyModule_AddObject(m, "FUNCFLAG_STDCALL", PyLong_FromLong(FUNCFLAG_STDCALL)); + PyModule_AddObject(m, "FUNCFLAG_HRESULT", PyLong_FromLong(FUNCFLAG_HRESULT)); + PyModule_AddObject(m, "FUNCFLAG_STDCALL", PyLong_FromLong(FUNCFLAG_STDCALL)); #endif - PyModule_AddObject(m, "FUNCFLAG_CDECL", PyLong_FromLong(FUNCFLAG_CDECL)); - PyModule_AddObject(m, "FUNCFLAG_USE_ERRNO", PyLong_FromLong(FUNCFLAG_USE_ERRNO)); - PyModule_AddObject(m, "FUNCFLAG_USE_LASTERROR", PyLong_FromLong(FUNCFLAG_USE_LASTERROR)); - PyModule_AddObject(m, "FUNCFLAG_PYTHONAPI", PyLong_FromLong(FUNCFLAG_PYTHONAPI)); - PyModule_AddStringConstant(m, "__version__", "1.1.0"); - - PyModule_AddObject(m, "_memmove_addr", PyLong_FromVoidPtr(memmove)); - PyModule_AddObject(m, "_memset_addr", PyLong_FromVoidPtr(memset)); - PyModule_AddObject(m, "_string_at_addr", PyLong_FromVoidPtr(string_at)); - PyModule_AddObject(m, "_cast_addr", PyLong_FromVoidPtr(cast)); + PyModule_AddObject(m, "FUNCFLAG_CDECL", PyLong_FromLong(FUNCFLAG_CDECL)); + PyModule_AddObject(m, "FUNCFLAG_USE_ERRNO", PyLong_FromLong(FUNCFLAG_USE_ERRNO)); + PyModule_AddObject(m, "FUNCFLAG_USE_LASTERROR", PyLong_FromLong(FUNCFLAG_USE_LASTERROR)); + PyModule_AddObject(m, "FUNCFLAG_PYTHONAPI", PyLong_FromLong(FUNCFLAG_PYTHONAPI)); + PyModule_AddStringConstant(m, "__version__", "1.1.0"); + + PyModule_AddObject(m, "_memmove_addr", PyLong_FromVoidPtr(memmove)); + PyModule_AddObject(m, "_memset_addr", PyLong_FromVoidPtr(memset)); + PyModule_AddObject(m, "_string_at_addr", PyLong_FromVoidPtr(string_at)); + PyModule_AddObject(m, "_cast_addr", PyLong_FromVoidPtr(cast)); #ifdef CTYPES_UNICODE - PyModule_AddObject(m, "_wstring_at_addr", PyLong_FromVoidPtr(wstring_at)); + PyModule_AddObject(m, "_wstring_at_addr", PyLong_FromVoidPtr(wstring_at)); #endif /* If RTLD_LOCAL is not defined (Windows!), set it to zero. */ @@ -5410,15 +5410,15 @@ #define RTLD_GLOBAL RTLD_LOCAL #endif - PyModule_AddObject(m, "RTLD_LOCAL", PyLong_FromLong(RTLD_LOCAL)); - PyModule_AddObject(m, "RTLD_GLOBAL", PyLong_FromLong(RTLD_GLOBAL)); - - PyExc_ArgError = PyErr_NewException("ctypes.ArgumentError", NULL, NULL); - if (PyExc_ArgError) { - Py_INCREF(PyExc_ArgError); - PyModule_AddObject(m, "ArgumentError", PyExc_ArgError); - } - return m; + PyModule_AddObject(m, "RTLD_LOCAL", PyLong_FromLong(RTLD_LOCAL)); + PyModule_AddObject(m, "RTLD_GLOBAL", PyLong_FromLong(RTLD_GLOBAL)); + + PyExc_ArgError = PyErr_NewException("ctypes.ArgumentError", NULL, NULL); + if (PyExc_ArgError) { + Py_INCREF(PyExc_ArgError); + PyModule_AddObject(m, "ArgumentError", PyExc_ArgError); + } + return m; } /* Modified: python/branches/py3k/Modules/_ctypes/_ctypes_test.c ============================================================================== --- python/branches/py3k/Modules/_ctypes/_ctypes_test.c (original) +++ python/branches/py3k/Modules/_ctypes/_ctypes_test.c Sun May 9 17:52:27 2010 @@ -14,152 +14,152 @@ EXPORT(void)testfunc_array(int values[4]) { - printf("testfunc_array %d %d %d %d\n", - values[0], - values[1], - values[2], - values[3]); + printf("testfunc_array %d %d %d %d\n", + values[0], + values[1], + values[2], + values[3]); } EXPORT(long double)testfunc_Ddd(double a, double b) { - long double result = (long double)(a * b); - printf("testfunc_Ddd(%p, %p)\n", &a, &b); - printf("testfunc_Ddd(%g, %g)\n", a, b); - return result; + long double result = (long double)(a * b); + printf("testfunc_Ddd(%p, %p)\n", &a, &b); + printf("testfunc_Ddd(%g, %g)\n", a, b); + return result; } EXPORT(long double)testfunc_DDD(long double a, long double b) { - long double result = a * b; - printf("testfunc_DDD(%p, %p)\n", &a, &b); - printf("testfunc_DDD(%Lg, %Lg)\n", a, b); - return result; + long double result = a * b; + printf("testfunc_DDD(%p, %p)\n", &a, &b); + printf("testfunc_DDD(%Lg, %Lg)\n", a, b); + return result; } EXPORT(int)testfunc_iii(int a, int b) { - int result = a * b; - printf("testfunc_iii(%p, %p)\n", &a, &b); - return result; + int result = a * b; + printf("testfunc_iii(%p, %p)\n", &a, &b); + return result; } EXPORT(int)myprintf(char *fmt, ...) { - int result; - va_list argptr; - va_start(argptr, fmt); - result = vprintf(fmt, argptr); - va_end(argptr); - return result; + int result; + va_list argptr; + va_start(argptr, fmt); + result = vprintf(fmt, argptr); + va_end(argptr); + return result; } EXPORT(char *)my_strtok(char *token, const char *delim) { - return strtok(token, delim); + return strtok(token, delim); } EXPORT(char *)my_strchr(const char *s, int c) { - return strchr(s, c); + return strchr(s, c); } EXPORT(double) my_sqrt(double a) { - return sqrt(a); + return sqrt(a); } EXPORT(void) my_qsort(void *base, size_t num, size_t width, int(*compare)(const void*, const void*)) { - qsort(base, num, width, compare); + qsort(base, num, width, compare); } EXPORT(int *) _testfunc_ai8(int a[8]) { - return a; + return a; } EXPORT(void) _testfunc_v(int a, int b, int *presult) { - *presult = a + b; + *presult = a + b; } EXPORT(int) _testfunc_i_bhilfd(signed char b, short h, int i, long l, float f, double d) { -/* printf("_testfunc_i_bhilfd got %d %d %d %ld %f %f\n", - b, h, i, l, f, d); +/* printf("_testfunc_i_bhilfd got %d %d %d %ld %f %f\n", + b, h, i, l, f, d); */ - return (int)(b + h + i + l + f + d); + return (int)(b + h + i + l + f + d); } EXPORT(float) _testfunc_f_bhilfd(signed char b, short h, int i, long l, float f, double d) { -/* printf("_testfunc_f_bhilfd got %d %d %d %ld %f %f\n", - b, h, i, l, f, d); +/* printf("_testfunc_f_bhilfd got %d %d %d %ld %f %f\n", + b, h, i, l, f, d); */ - return (float)(b + h + i + l + f + d); + return (float)(b + h + i + l + f + d); } EXPORT(double) _testfunc_d_bhilfd(signed char b, short h, int i, long l, float f, double d) { -/* printf("_testfunc_d_bhilfd got %d %d %d %ld %f %f\n", - b, h, i, l, f, d); +/* printf("_testfunc_d_bhilfd got %d %d %d %ld %f %f\n", + b, h, i, l, f, d); */ - return (double)(b + h + i + l + f + d); + return (double)(b + h + i + l + f + d); } EXPORT(long double) _testfunc_D_bhilfD(signed char b, short h, int i, long l, float f, long double d) { -/* printf("_testfunc_d_bhilfd got %d %d %d %ld %f %f\n", - b, h, i, l, f, d); +/* printf("_testfunc_d_bhilfd got %d %d %d %ld %f %f\n", + b, h, i, l, f, d); */ - return (long double)(b + h + i + l + f + d); + return (long double)(b + h + i + l + f + d); } EXPORT(char *) _testfunc_p_p(void *s) { - return (char *)s; + return (char *)s; } EXPORT(void *) _testfunc_c_p_p(int *argcp, char **argv) { - return argv[(*argcp)-1]; + return argv[(*argcp)-1]; } EXPORT(void *) get_strchr(void) { - return (void *)strchr; + return (void *)strchr; } EXPORT(char *) my_strdup(char *src) { - char *dst = (char *)malloc(strlen(src)+1); - if (!dst) - return NULL; - strcpy(dst, src); - return dst; + char *dst = (char *)malloc(strlen(src)+1); + if (!dst) + return NULL; + strcpy(dst, src); + return dst; } EXPORT(void)my_free(void *ptr) { - free(ptr); + free(ptr); } #ifdef HAVE_WCHAR_H EXPORT(wchar_t *) my_wcsdup(wchar_t *src) { - size_t len = wcslen(src); - wchar_t *ptr = (wchar_t *)malloc((len + 1) * sizeof(wchar_t)); - if (ptr == NULL) - return NULL; - memcpy(ptr, src, (len+1) * sizeof(wchar_t)); - return ptr; + size_t len = wcslen(src); + wchar_t *ptr = (wchar_t *)malloc((len + 1) * sizeof(wchar_t)); + if (ptr == NULL) + return NULL; + memcpy(ptr, src, (len+1) * sizeof(wchar_t)); + return ptr; } EXPORT(size_t) my_wcslen(wchar_t *src) { - return wcslen(src); + return wcslen(src); } #endif @@ -170,158 +170,158 @@ #endif typedef struct { - int (*c)(int, int); - int (__stdcall *s)(int, int); + int (*c)(int, int); + int (__stdcall *s)(int, int); } FUNCS; EXPORT(int) _testfunc_callfuncp(FUNCS *fp) { - fp->c(1, 2); - fp->s(3, 4); - return 0; + fp->c(1, 2); + fp->s(3, 4); + return 0; } EXPORT(int) _testfunc_deref_pointer(int *pi) { - return *pi; + return *pi; } #ifdef MS_WIN32 EXPORT(int) _testfunc_piunk(IUnknown FAR *piunk) { - piunk->lpVtbl->AddRef(piunk); - return piunk->lpVtbl->Release(piunk); + piunk->lpVtbl->AddRef(piunk); + return piunk->lpVtbl->Release(piunk); } #endif EXPORT(int) _testfunc_callback_with_pointer(int (*func)(int *)) { - int table[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; + int table[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; - return (*func)(table); + return (*func)(table); } #ifdef HAVE_LONG_LONG EXPORT(PY_LONG_LONG) _testfunc_q_bhilfdq(signed char b, short h, int i, long l, float f, - double d, PY_LONG_LONG q) + double d, PY_LONG_LONG q) { - return (PY_LONG_LONG)(b + h + i + l + f + d + q); + return (PY_LONG_LONG)(b + h + i + l + f + d + q); } EXPORT(PY_LONG_LONG) _testfunc_q_bhilfd(signed char b, short h, int i, long l, float f, double d) { - return (PY_LONG_LONG)(b + h + i + l + f + d); + return (PY_LONG_LONG)(b + h + i + l + f + d); } EXPORT(int) _testfunc_callback_i_if(int value, int (*func)(int)) { - int sum = 0; - while (value != 0) { - sum += func(value); - value /= 2; - } - return sum; + int sum = 0; + while (value != 0) { + sum += func(value); + value /= 2; + } + return sum; } EXPORT(PY_LONG_LONG) _testfunc_callback_q_qf(PY_LONG_LONG value, - PY_LONG_LONG (*func)(PY_LONG_LONG)) + PY_LONG_LONG (*func)(PY_LONG_LONG)) { - PY_LONG_LONG sum = 0; + PY_LONG_LONG sum = 0; - while (value != 0) { - sum += func(value); - value /= 2; - } - return sum; + while (value != 0) { + sum += func(value); + value /= 2; + } + return sum; } #endif typedef struct { - char *name; - char *value; + char *name; + char *value; } SPAM; typedef struct { - char *name; - int num_spams; - SPAM *spams; + char *name; + int num_spams; + SPAM *spams; } EGG; SPAM my_spams[2] = { - { "name1", "value1" }, - { "name2", "value2" }, + { "name1", "value1" }, + { "name2", "value2" }, }; EGG my_eggs[1] = { - { "first egg", 1, my_spams } + { "first egg", 1, my_spams } }; EXPORT(int) getSPAMANDEGGS(EGG **eggs) { - *eggs = my_eggs; - return 1; + *eggs = my_eggs; + return 1; } typedef struct tagpoint { - int x; - int y; + int x; + int y; } point; EXPORT(int) _testfunc_byval(point in, point *pout) { - if (pout) { - pout->x = in.x; - pout->y = in.y; - } - return in.x + in.y; + if (pout) { + pout->x = in.x; + pout->y = in.y; + } + return in.x + in.y; } EXPORT (int) an_integer = 42; EXPORT(int) get_an_integer(void) { - return an_integer; + return an_integer; } EXPORT(double) integrate(double a, double b, double (*f)(double), long nstep) { - double x, sum=0.0, dx=(b-a)/(double)nstep; - for(x=a+0.5*dx; (b-x)*(x-a)>0.0; x+=dx) - sum += f(x); - return sum/(double)nstep; + double x, sum=0.0, dx=(b-a)/(double)nstep; + for(x=a+0.5*dx; (b-x)*(x-a)>0.0; x+=dx) + sum += f(x); + return sum/(double)nstep; } typedef struct { - void (*initialize)(void *(*)(int), void(*)(void *)); + void (*initialize)(void *(*)(int), void(*)(void *)); } xxx_library; static void _xxx_init(void *(*Xalloc)(int), void (*Xfree)(void *)) { - void *ptr; - - printf("_xxx_init got %p %p\n", Xalloc, Xfree); - printf("calling\n"); - ptr = Xalloc(32); - Xfree(ptr); - printf("calls done, ptr was %p\n", ptr); + void *ptr; + + printf("_xxx_init got %p %p\n", Xalloc, Xfree); + printf("calling\n"); + ptr = Xalloc(32); + Xfree(ptr); + printf("calls done, ptr was %p\n", ptr); } xxx_library _xxx_lib = { - _xxx_init + _xxx_init }; EXPORT(xxx_library) *library_get(void) { - return &_xxx_lib; + return &_xxx_lib; } #ifdef MS_WIN32 /* See Don Box (german), pp 79ff. */ EXPORT(void) GetString(BSTR *pbstr) { - *pbstr = SysAllocString(L"Goodbye!"); + *pbstr = SysAllocString(L"Goodbye!"); } #endif @@ -330,12 +330,12 @@ */ PyObject *py_func_si(PyObject *self, PyObject *args) { - char *name; - int i; - if (!PyArg_ParseTuple(args, "si", &name, &i)) - return NULL; - Py_INCREF(Py_None); - return Py_None; + char *name; + int i; + if (!PyArg_ParseTuple(args, "si", &name, &i)) + return NULL; + Py_INCREF(Py_None); + return Py_None; } EXPORT(void) _py_func_si(char *s, int i) @@ -344,8 +344,8 @@ PyObject *py_func(PyObject *self, PyObject *args) { - Py_INCREF(Py_None); - return Py_None; + Py_INCREF(Py_None); + return Py_None; } EXPORT(void) _py_func(void) @@ -356,64 +356,64 @@ EXPORT(unsigned PY_LONG_LONG) last_tf_arg_u; struct BITS { - int A: 1, B:2, C:3, D:4, E: 5, F: 6, G: 7, H: 8, I: 9; - short M: 1, N: 2, O: 3, P: 4, Q: 5, R: 6, S: 7; + int A: 1, B:2, C:3, D:4, E: 5, F: 6, G: 7, H: 8, I: 9; + short M: 1, N: 2, O: 3, P: 4, Q: 5, R: 6, S: 7; }; EXPORT(void) set_bitfields(struct BITS *bits, char name, int value) { - switch (name) { - case 'A': bits->A = value; break; - case 'B': bits->B = value; break; - case 'C': bits->C = value; break; - case 'D': bits->D = value; break; - case 'E': bits->E = value; break; - case 'F': bits->F = value; break; - case 'G': bits->G = value; break; - case 'H': bits->H = value; break; - case 'I': bits->I = value; break; - - case 'M': bits->M = value; break; - case 'N': bits->N = value; break; - case 'O': bits->O = value; break; - case 'P': bits->P = value; break; - case 'Q': bits->Q = value; break; - case 'R': bits->R = value; break; - case 'S': bits->S = value; break; - } + switch (name) { + case 'A': bits->A = value; break; + case 'B': bits->B = value; break; + case 'C': bits->C = value; break; + case 'D': bits->D = value; break; + case 'E': bits->E = value; break; + case 'F': bits->F = value; break; + case 'G': bits->G = value; break; + case 'H': bits->H = value; break; + case 'I': bits->I = value; break; + + case 'M': bits->M = value; break; + case 'N': bits->N = value; break; + case 'O': bits->O = value; break; + case 'P': bits->P = value; break; + case 'Q': bits->Q = value; break; + case 'R': bits->R = value; break; + case 'S': bits->S = value; break; + } } EXPORT(int) unpack_bitfields(struct BITS *bits, char name) { - switch (name) { - case 'A': return bits->A; - case 'B': return bits->B; - case 'C': return bits->C; - case 'D': return bits->D; - case 'E': return bits->E; - case 'F': return bits->F; - case 'G': return bits->G; - case 'H': return bits->H; - case 'I': return bits->I; - - case 'M': return bits->M; - case 'N': return bits->N; - case 'O': return bits->O; - case 'P': return bits->P; - case 'Q': return bits->Q; - case 'R': return bits->R; - case 'S': return bits->S; - } - return 0; + switch (name) { + case 'A': return bits->A; + case 'B': return bits->B; + case 'C': return bits->C; + case 'D': return bits->D; + case 'E': return bits->E; + case 'F': return bits->F; + case 'G': return bits->G; + case 'H': return bits->H; + case 'I': return bits->I; + + case 'M': return bits->M; + case 'N': return bits->N; + case 'O': return bits->O; + case 'P': return bits->P; + case 'Q': return bits->Q; + case 'R': return bits->R; + case 'S': return bits->S; + } + return 0; } static PyMethodDef module_methods[] = { -/* {"get_last_tf_arg_s", get_last_tf_arg_s, METH_NOARGS}, - {"get_last_tf_arg_u", get_last_tf_arg_u, METH_NOARGS}, +/* {"get_last_tf_arg_s", get_last_tf_arg_s, METH_NOARGS}, + {"get_last_tf_arg_u", get_last_tf_arg_u, METH_NOARGS}, */ - {"func_si", py_func_si, METH_VARARGS}, - {"func", py_func, METH_NOARGS}, - { NULL, NULL, 0, NULL}, + {"func_si", py_func_si, METH_VARARGS}, + {"func", py_func, METH_NOARGS}, + { NULL, NULL, 0, NULL}, }; #define S last_tf_arg_s = (PY_LONG_LONG)c @@ -483,80 +483,80 @@ #endif /********/ - + #ifndef MS_WIN32 typedef struct { - long x; - long y; + long x; + long y; } POINT; typedef struct { - long left; - long top; - long right; - long bottom; + long left; + long top; + long right; + long bottom; } RECT; #endif EXPORT(int) PointInRect(RECT *prc, POINT pt) { - if (pt.x < prc->left) - return 0; - if (pt.x > prc->right) - return 0; - if (pt.y < prc->top) - return 0; - if (pt.y > prc->bottom) - return 0; - return 1; + if (pt.x < prc->left) + return 0; + if (pt.x > prc->right) + return 0; + if (pt.y < prc->top) + return 0; + if (pt.y > prc->bottom) + return 0; + return 1; } typedef struct { - short x; - short y; + short x; + short y; } S2H; EXPORT(S2H) ret_2h_func(S2H inp) { - inp.x *= 2; - inp.y *= 3; - return inp; + inp.x *= 2; + inp.y *= 3; + return inp; } typedef struct { - int a, b, c, d, e, f, g, h; + int a, b, c, d, e, f, g, h; } S8I; EXPORT(S8I) ret_8i_func(S8I inp) { - inp.a *= 2; - inp.b *= 3; - inp.c *= 4; - inp.d *= 5; - inp.e *= 6; - inp.f *= 7; - inp.g *= 8; - inp.h *= 9; - return inp; + inp.a *= 2; + inp.b *= 3; + inp.c *= 4; + inp.d *= 5; + inp.e *= 6; + inp.f *= 7; + inp.g *= 8; + inp.h *= 9; + return inp; } EXPORT(int) GetRectangle(int flag, RECT *prect) { - if (flag == 0) - return 0; - prect->left = (int)flag; - prect->top = (int)flag + 1; - prect->right = (int)flag + 2; - prect->bottom = (int)flag + 3; - return 1; + if (flag == 0) + return 0; + prect->left = (int)flag; + prect->top = (int)flag + 1; + prect->right = (int)flag + 2; + prect->bottom = (int)flag + 3; + return 1; } EXPORT(void) TwoOutArgs(int a, int *pi, int b, int *pj) { - *pi += a; - *pj += b; + *pi += a; + *pj += b; } #ifdef MS_WIN32 @@ -571,32 +571,32 @@ EXPORT (HRESULT) KeepObject(IUnknown *punk) { - static IUnknown *pobj; - if (punk) - punk->lpVtbl->AddRef(punk); - if (pobj) - pobj->lpVtbl->Release(pobj); - pobj = punk; - return S_OK; + static IUnknown *pobj; + if (punk) + punk->lpVtbl->AddRef(punk); + if (pobj) + pobj->lpVtbl->Release(pobj); + pobj = punk; + return S_OK; } #endif static struct PyModuleDef _ctypes_testmodule = { - PyModuleDef_HEAD_INIT, - "_ctypes_test", - NULL, - -1, - module_methods, - NULL, - NULL, - NULL, - NULL + PyModuleDef_HEAD_INIT, + "_ctypes_test", + NULL, + -1, + module_methods, + NULL, + NULL, + NULL, + NULL }; PyMODINIT_FUNC PyInit__ctypes_test(void) { - return PyModule_Create(&_ctypes_testmodule); + return PyModule_Create(&_ctypes_testmodule); } Modified: python/branches/py3k/Modules/_ctypes/callbacks.c ============================================================================== --- python/branches/py3k/Modules/_ctypes/callbacks.c (original) +++ python/branches/py3k/Modules/_ctypes/callbacks.c Sun May 9 17:52:27 2010 @@ -12,65 +12,65 @@ static void CThunkObject_dealloc(PyObject *_self) { - CThunkObject *self = (CThunkObject *)_self; - Py_XDECREF(self->converters); - Py_XDECREF(self->callable); - Py_XDECREF(self->restype); - if (self->pcl) - _ctypes_free_closure(self->pcl); - PyObject_GC_Del(self); + CThunkObject *self = (CThunkObject *)_self; + Py_XDECREF(self->converters); + Py_XDECREF(self->callable); + Py_XDECREF(self->restype); + if (self->pcl) + _ctypes_free_closure(self->pcl); + PyObject_GC_Del(self); } static int CThunkObject_traverse(PyObject *_self, visitproc visit, void *arg) { - CThunkObject *self = (CThunkObject *)_self; - Py_VISIT(self->converters); - Py_VISIT(self->callable); - Py_VISIT(self->restype); - return 0; + CThunkObject *self = (CThunkObject *)_self; + Py_VISIT(self->converters); + Py_VISIT(self->callable); + Py_VISIT(self->restype); + return 0; } static int CThunkObject_clear(PyObject *_self) { - CThunkObject *self = (CThunkObject *)_self; - Py_CLEAR(self->converters); - Py_CLEAR(self->callable); - Py_CLEAR(self->restype); - return 0; + CThunkObject *self = (CThunkObject *)_self; + Py_CLEAR(self->converters); + Py_CLEAR(self->callable); + Py_CLEAR(self->restype); + return 0; } PyTypeObject PyCThunk_Type = { - PyVarObject_HEAD_INIT(NULL, 0) - "_ctypes.CThunkObject", - sizeof(CThunkObject), /* tp_basicsize */ - sizeof(ffi_type), /* tp_itemsize */ - CThunkObject_dealloc, /* tp_dealloc */ - 0, /* tp_print */ - 0, /* tp_getattr */ - 0, /* tp_setattr */ - 0, /* tp_reserved */ - 0, /* tp_repr */ - 0, /* tp_as_number */ - 0, /* tp_as_sequence */ - 0, /* tp_as_mapping */ - 0, /* tp_hash */ - 0, /* tp_call */ - 0, /* tp_str */ - 0, /* tp_getattro */ - 0, /* tp_setattro */ - 0, /* tp_as_buffer */ - Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC, /* tp_flags */ - "CThunkObject", /* tp_doc */ - CThunkObject_traverse, /* tp_traverse */ - CThunkObject_clear, /* tp_clear */ - 0, /* tp_richcompare */ - 0, /* tp_weaklistoffset */ - 0, /* tp_iter */ - 0, /* tp_iternext */ - 0, /* tp_methods */ - 0, /* tp_members */ + PyVarObject_HEAD_INIT(NULL, 0) + "_ctypes.CThunkObject", + sizeof(CThunkObject), /* tp_basicsize */ + sizeof(ffi_type), /* tp_itemsize */ + CThunkObject_dealloc, /* tp_dealloc */ + 0, /* tp_print */ + 0, /* tp_getattr */ + 0, /* tp_setattr */ + 0, /* tp_reserved */ + 0, /* tp_repr */ + 0, /* tp_as_number */ + 0, /* tp_as_sequence */ + 0, /* tp_as_mapping */ + 0, /* tp_hash */ + 0, /* tp_call */ + 0, /* tp_str */ + 0, /* tp_getattro */ + 0, /* tp_setattro */ + 0, /* tp_as_buffer */ + Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC, /* tp_flags */ + "CThunkObject", /* tp_doc */ + CThunkObject_traverse, /* tp_traverse */ + CThunkObject_clear, /* tp_clear */ + 0, /* tp_richcompare */ + 0, /* tp_weaklistoffset */ + 0, /* tp_iter */ + 0, /* tp_iternext */ + 0, /* tp_methods */ + 0, /* tp_members */ }; /**************************************************************/ @@ -78,43 +78,43 @@ static void PrintError(char *msg, ...) { - char buf[512]; - PyObject *f = PySys_GetObject("stderr"); - va_list marker; - - va_start(marker, msg); - vsnprintf(buf, sizeof(buf), msg, marker); - va_end(marker); - if (f != NULL && f != Py_None) - PyFile_WriteString(buf, f); - PyErr_Print(); + char buf[512]; + PyObject *f = PySys_GetObject("stderr"); + va_list marker; + + va_start(marker, msg); + vsnprintf(buf, sizeof(buf), msg, marker); + va_end(marker); + if (f != NULL && f != Py_None) + PyFile_WriteString(buf, f); + PyErr_Print(); } /* after code that pyrex generates */ void _ctypes_add_traceback(char *funcname, char *filename, int lineno) { - PyObject *py_globals = 0; - PyCodeObject *py_code = 0; - PyFrameObject *py_frame = 0; - - py_globals = PyDict_New(); - if (!py_globals) goto bad; - py_code = PyCode_NewEmpty(filename, funcname, lineno); - if (!py_code) goto bad; - py_frame = PyFrame_New( - PyThreadState_Get(), /*PyThreadState *tstate,*/ - py_code, /*PyCodeObject *code,*/ - py_globals, /*PyObject *globals,*/ - 0 /*PyObject *locals*/ - ); - if (!py_frame) goto bad; - py_frame->f_lineno = lineno; - PyTraceBack_Here(py_frame); + PyObject *py_globals = 0; + PyCodeObject *py_code = 0; + PyFrameObject *py_frame = 0; + + py_globals = PyDict_New(); + if (!py_globals) goto bad; + py_code = PyCode_NewEmpty(filename, funcname, lineno); + if (!py_code) goto bad; + py_frame = PyFrame_New( + PyThreadState_Get(), /*PyThreadState *tstate,*/ + py_code, /*PyCodeObject *code,*/ + py_globals, /*PyObject *globals,*/ + 0 /*PyObject *locals*/ + ); + if (!py_frame) goto bad; + py_frame->f_lineno = lineno; + PyTraceBack_Here(py_frame); bad: - Py_XDECREF(py_globals); - Py_XDECREF(py_code); - Py_XDECREF(py_frame); + Py_XDECREF(py_globals); + Py_XDECREF(py_code); + Py_XDECREF(py_frame); } #ifdef MS_WIN32 @@ -131,15 +131,15 @@ static void TryAddRef(StgDictObject *dict, CDataObject *obj) { - IUnknown *punk; + IUnknown *punk; - if (NULL == PyDict_GetItemString((PyObject *)dict, "_needs_com_addref_")) - return; + if (NULL == PyDict_GetItemString((PyObject *)dict, "_needs_com_addref_")) + return; - punk = *(IUnknown **)obj->b_ptr; - if (punk) - punk->lpVtbl->AddRef(punk); - return; + punk = *(IUnknown **)obj->b_ptr; + if (punk) + punk->lpVtbl->AddRef(punk); + return; } #endif @@ -149,421 +149,421 @@ * */ static void _CallPythonObject(void *mem, - ffi_type *restype, - SETFUNC setfunc, - PyObject *callable, - PyObject *converters, - int flags, - void **pArgs) -{ - Py_ssize_t i; - PyObject *result; - PyObject *arglist = NULL; - Py_ssize_t nArgs; - PyObject *error_object = NULL; - int *space; + ffi_type *restype, + SETFUNC setfunc, + PyObject *callable, + PyObject *converters, + int flags, + void **pArgs) +{ + Py_ssize_t i; + PyObject *result; + PyObject *arglist = NULL; + Py_ssize_t nArgs; + PyObject *error_object = NULL; + int *space; #ifdef WITH_THREAD - PyGILState_STATE state = PyGILState_Ensure(); + PyGILState_STATE state = PyGILState_Ensure(); #endif - nArgs = PySequence_Length(converters); - /* Hm. What to return in case of error? - For COM, 0xFFFFFFFF seems better than 0. - */ - if (nArgs < 0) { - PrintError("BUG: PySequence_Length"); - goto Done; - } - - arglist = PyTuple_New(nArgs); - if (!arglist) { - PrintError("PyTuple_New()"); - goto Done; - } - for (i = 0; i < nArgs; ++i) { - /* Note: new reference! */ - PyObject *cnv = PySequence_GetItem(converters, i); - StgDictObject *dict; - if (cnv) - dict = PyType_stgdict(cnv); - else { - PrintError("Getting argument converter %d\n", i); - goto Done; - } - - if (dict && dict->getfunc && !_ctypes_simple_instance(cnv)) { - PyObject *v = dict->getfunc(*pArgs, dict->size); - if (!v) { - PrintError("create argument %d:\n", i); - Py_DECREF(cnv); - goto Done; - } - PyTuple_SET_ITEM(arglist, i, v); - /* XXX XXX XX - We have the problem that c_byte or c_short have dict->size of - 1 resp. 4, but these parameters are pushed as sizeof(int) bytes. - BTW, the same problem occurrs when they are pushed as parameters - */ - } else if (dict) { - /* Hm, shouldn't we use PyCData_AtAddress() or something like that instead? */ - CDataObject *obj = (CDataObject *)PyObject_CallFunctionObjArgs(cnv, NULL); - if (!obj) { - PrintError("create argument %d:\n", i); - Py_DECREF(cnv); - goto Done; - } - if (!CDataObject_Check(obj)) { - Py_DECREF(obj); - Py_DECREF(cnv); - PrintError("unexpected result of create argument %d:\n", i); - goto Done; - } - memcpy(obj->b_ptr, *pArgs, dict->size); - PyTuple_SET_ITEM(arglist, i, (PyObject *)obj); + nArgs = PySequence_Length(converters); + /* Hm. What to return in case of error? + For COM, 0xFFFFFFFF seems better than 0. + */ + if (nArgs < 0) { + PrintError("BUG: PySequence_Length"); + goto Done; + } + + arglist = PyTuple_New(nArgs); + if (!arglist) { + PrintError("PyTuple_New()"); + goto Done; + } + for (i = 0; i < nArgs; ++i) { + /* Note: new reference! */ + PyObject *cnv = PySequence_GetItem(converters, i); + StgDictObject *dict; + if (cnv) + dict = PyType_stgdict(cnv); + else { + PrintError("Getting argument converter %d\n", i); + goto Done; + } + + if (dict && dict->getfunc && !_ctypes_simple_instance(cnv)) { + PyObject *v = dict->getfunc(*pArgs, dict->size); + if (!v) { + PrintError("create argument %d:\n", i); + Py_DECREF(cnv); + goto Done; + } + PyTuple_SET_ITEM(arglist, i, v); + /* XXX XXX XX + We have the problem that c_byte or c_short have dict->size of + 1 resp. 4, but these parameters are pushed as sizeof(int) bytes. + BTW, the same problem occurrs when they are pushed as parameters + */ + } else if (dict) { + /* Hm, shouldn't we use PyCData_AtAddress() or something like that instead? */ + CDataObject *obj = (CDataObject *)PyObject_CallFunctionObjArgs(cnv, NULL); + if (!obj) { + PrintError("create argument %d:\n", i); + Py_DECREF(cnv); + goto Done; + } + if (!CDataObject_Check(obj)) { + Py_DECREF(obj); + Py_DECREF(cnv); + PrintError("unexpected result of create argument %d:\n", i); + goto Done; + } + memcpy(obj->b_ptr, *pArgs, dict->size); + PyTuple_SET_ITEM(arglist, i, (PyObject *)obj); #ifdef MS_WIN32 - TryAddRef(dict, obj); + TryAddRef(dict, obj); #endif - } else { - PyErr_SetString(PyExc_TypeError, - "cannot build parameter"); - PrintError("Parsing argument %d\n", i); - Py_DECREF(cnv); - goto Done; - } - Py_DECREF(cnv); - /* XXX error handling! */ - pArgs++; - } + } else { + PyErr_SetString(PyExc_TypeError, + "cannot build parameter"); + PrintError("Parsing argument %d\n", i); + Py_DECREF(cnv); + goto Done; + } + Py_DECREF(cnv); + /* XXX error handling! */ + pArgs++; + } #define CHECK(what, x) \ if (x == NULL) _ctypes_add_traceback(what, "_ctypes/callbacks.c", __LINE__ - 1), PyErr_Print() - if (flags & (FUNCFLAG_USE_ERRNO | FUNCFLAG_USE_LASTERROR)) { - error_object = _ctypes_get_errobj(&space); - if (error_object == NULL) - goto Done; - if (flags & FUNCFLAG_USE_ERRNO) { - int temp = space[0]; - space[0] = errno; - errno = temp; - } + if (flags & (FUNCFLAG_USE_ERRNO | FUNCFLAG_USE_LASTERROR)) { + error_object = _ctypes_get_errobj(&space); + if (error_object == NULL) + goto Done; + if (flags & FUNCFLAG_USE_ERRNO) { + int temp = space[0]; + space[0] = errno; + errno = temp; + } #ifdef MS_WIN32 - if (flags & FUNCFLAG_USE_LASTERROR) { - int temp = space[1]; - space[1] = GetLastError(); - SetLastError(temp); - } + if (flags & FUNCFLAG_USE_LASTERROR) { + int temp = space[1]; + space[1] = GetLastError(); + SetLastError(temp); + } #endif - } + } - result = PyObject_CallObject(callable, arglist); - CHECK("'calling callback function'", result); + result = PyObject_CallObject(callable, arglist); + CHECK("'calling callback function'", result); #ifdef MS_WIN32 - if (flags & FUNCFLAG_USE_LASTERROR) { - int temp = space[1]; - space[1] = GetLastError(); - SetLastError(temp); - } -#endif - if (flags & FUNCFLAG_USE_ERRNO) { - int temp = space[0]; - space[0] = errno; - errno = temp; - } - Py_XDECREF(error_object); - - if ((restype != &ffi_type_void) && result) { - PyObject *keep; - assert(setfunc); + if (flags & FUNCFLAG_USE_LASTERROR) { + int temp = space[1]; + space[1] = GetLastError(); + SetLastError(temp); + } +#endif + if (flags & FUNCFLAG_USE_ERRNO) { + int temp = space[0]; + space[0] = errno; + errno = temp; + } + Py_XDECREF(error_object); + + if ((restype != &ffi_type_void) && result) { + PyObject *keep; + assert(setfunc); #ifdef WORDS_BIGENDIAN - /* See the corresponding code in callproc.c, around line 961 */ - if (restype->type != FFI_TYPE_FLOAT && restype->size < sizeof(ffi_arg)) - mem = (char *)mem + sizeof(ffi_arg) - restype->size; -#endif - keep = setfunc(mem, result, 0); - CHECK("'converting callback result'", keep); - /* keep is an object we have to keep alive so that the result - stays valid. If there is no such object, the setfunc will - have returned Py_None. - - If there is such an object, we have no choice than to keep - it alive forever - but a refcount and/or memory leak will - be the result. EXCEPT when restype is py_object - Python - itself knows how to manage the refcount of these objects. - */ - if (keep == NULL) /* Could not convert callback result. */ - PyErr_WriteUnraisable(callable); - else if (keep == Py_None) /* Nothing to keep */ - Py_DECREF(keep); - else if (setfunc != _ctypes_get_fielddesc("O")->setfunc) { - if (-1 == PyErr_WarnEx(PyExc_RuntimeWarning, - "memory leak in callback function.", - 1)) - PyErr_WriteUnraisable(callable); - } - } - Py_XDECREF(result); + /* See the corresponding code in callproc.c, around line 961 */ + if (restype->type != FFI_TYPE_FLOAT && restype->size < sizeof(ffi_arg)) + mem = (char *)mem + sizeof(ffi_arg) - restype->size; +#endif + keep = setfunc(mem, result, 0); + CHECK("'converting callback result'", keep); + /* keep is an object we have to keep alive so that the result + stays valid. If there is no such object, the setfunc will + have returned Py_None. + + If there is such an object, we have no choice than to keep + it alive forever - but a refcount and/or memory leak will + be the result. EXCEPT when restype is py_object - Python + itself knows how to manage the refcount of these objects. + */ + if (keep == NULL) /* Could not convert callback result. */ + PyErr_WriteUnraisable(callable); + else if (keep == Py_None) /* Nothing to keep */ + Py_DECREF(keep); + else if (setfunc != _ctypes_get_fielddesc("O")->setfunc) { + if (-1 == PyErr_WarnEx(PyExc_RuntimeWarning, + "memory leak in callback function.", + 1)) + PyErr_WriteUnraisable(callable); + } + } + Py_XDECREF(result); Done: - Py_XDECREF(arglist); + Py_XDECREF(arglist); #ifdef WITH_THREAD - PyGILState_Release(state); + PyGILState_Release(state); #endif } static void closure_fcn(ffi_cif *cif, - void *resp, - void **args, - void *userdata) -{ - CThunkObject *p = (CThunkObject *)userdata; - - _CallPythonObject(resp, - p->ffi_restype, - p->setfunc, - p->callable, - p->converters, - p->flags, - args); + void *resp, + void **args, + void *userdata) +{ + CThunkObject *p = (CThunkObject *)userdata; + + _CallPythonObject(resp, + p->ffi_restype, + p->setfunc, + p->callable, + p->converters, + p->flags, + args); } static CThunkObject* CThunkObject_new(Py_ssize_t nArgs) { - CThunkObject *p; - int i; + CThunkObject *p; + int i; - p = PyObject_GC_NewVar(CThunkObject, &PyCThunk_Type, nArgs); - if (p == NULL) { - PyErr_NoMemory(); - return NULL; - } - - p->pcl = NULL; - memset(&p->cif, 0, sizeof(p->cif)); - p->converters = NULL; - p->callable = NULL; - p->setfunc = NULL; - p->ffi_restype = NULL; - - for (i = 0; i < nArgs + 1; ++i) - p->atypes[i] = NULL; - PyObject_GC_Track((PyObject *)p); - return p; + p = PyObject_GC_NewVar(CThunkObject, &PyCThunk_Type, nArgs); + if (p == NULL) { + PyErr_NoMemory(); + return NULL; + } + + p->pcl = NULL; + memset(&p->cif, 0, sizeof(p->cif)); + p->converters = NULL; + p->callable = NULL; + p->setfunc = NULL; + p->ffi_restype = NULL; + + for (i = 0; i < nArgs + 1; ++i) + p->atypes[i] = NULL; + PyObject_GC_Track((PyObject *)p); + return p; } CThunkObject *_ctypes_alloc_callback(PyObject *callable, - PyObject *converters, - PyObject *restype, - int flags) -{ - int result; - CThunkObject *p; - Py_ssize_t nArgs, i; - ffi_abi cc; - - nArgs = PySequence_Size(converters); - p = CThunkObject_new(nArgs); - if (p == NULL) - return NULL; - - assert(CThunk_CheckExact((PyObject *)p)); - - p->pcl = _ctypes_alloc_closure(); - if (p->pcl == NULL) { - PyErr_NoMemory(); - goto error; - } - - p->flags = flags; - for (i = 0; i < nArgs; ++i) { - PyObject *cnv = PySequence_GetItem(converters, i); - if (cnv == NULL) - goto error; - p->atypes[i] = _ctypes_get_ffi_type(cnv); - Py_DECREF(cnv); - } - p->atypes[i] = NULL; - - Py_INCREF(restype); - p->restype = restype; - if (restype == Py_None) { - p->setfunc = NULL; - p->ffi_restype = &ffi_type_void; - } else { - StgDictObject *dict = PyType_stgdict(restype); - if (dict == NULL || dict->setfunc == NULL) { - PyErr_SetString(PyExc_TypeError, - "invalid result type for callback function"); - goto error; - } - p->setfunc = dict->setfunc; - p->ffi_restype = &dict->ffi_type_pointer; - } + PyObject *converters, + PyObject *restype, + int flags) +{ + int result; + CThunkObject *p; + Py_ssize_t nArgs, i; + ffi_abi cc; + + nArgs = PySequence_Size(converters); + p = CThunkObject_new(nArgs); + if (p == NULL) + return NULL; + + assert(CThunk_CheckExact((PyObject *)p)); + + p->pcl = _ctypes_alloc_closure(); + if (p->pcl == NULL) { + PyErr_NoMemory(); + goto error; + } + + p->flags = flags; + for (i = 0; i < nArgs; ++i) { + PyObject *cnv = PySequence_GetItem(converters, i); + if (cnv == NULL) + goto error; + p->atypes[i] = _ctypes_get_ffi_type(cnv); + Py_DECREF(cnv); + } + p->atypes[i] = NULL; + + Py_INCREF(restype); + p->restype = restype; + if (restype == Py_None) { + p->setfunc = NULL; + p->ffi_restype = &ffi_type_void; + } else { + StgDictObject *dict = PyType_stgdict(restype); + if (dict == NULL || dict->setfunc == NULL) { + PyErr_SetString(PyExc_TypeError, + "invalid result type for callback function"); + goto error; + } + p->setfunc = dict->setfunc; + p->ffi_restype = &dict->ffi_type_pointer; + } - cc = FFI_DEFAULT_ABI; + cc = FFI_DEFAULT_ABI; #if defined(MS_WIN32) && !defined(_WIN32_WCE) && !defined(MS_WIN64) - if ((flags & FUNCFLAG_CDECL) == 0) - cc = FFI_STDCALL; + if ((flags & FUNCFLAG_CDECL) == 0) + cc = FFI_STDCALL; #endif - result = ffi_prep_cif(&p->cif, cc, - Py_SAFE_DOWNCAST(nArgs, Py_ssize_t, int), - _ctypes_get_ffi_type(restype), - &p->atypes[0]); - if (result != FFI_OK) { - PyErr_Format(PyExc_RuntimeError, - "ffi_prep_cif failed with %d", result); - goto error; - } - result = ffi_prep_closure(p->pcl, &p->cif, closure_fcn, p); - if (result != FFI_OK) { - PyErr_Format(PyExc_RuntimeError, - "ffi_prep_closure failed with %d", result); - goto error; - } - - Py_INCREF(converters); - p->converters = converters; - Py_INCREF(callable); - p->callable = callable; - return p; + result = ffi_prep_cif(&p->cif, cc, + Py_SAFE_DOWNCAST(nArgs, Py_ssize_t, int), + _ctypes_get_ffi_type(restype), + &p->atypes[0]); + if (result != FFI_OK) { + PyErr_Format(PyExc_RuntimeError, + "ffi_prep_cif failed with %d", result); + goto error; + } + result = ffi_prep_closure(p->pcl, &p->cif, closure_fcn, p); + if (result != FFI_OK) { + PyErr_Format(PyExc_RuntimeError, + "ffi_prep_closure failed with %d", result); + goto error; + } + + Py_INCREF(converters); + p->converters = converters; + Py_INCREF(callable); + p->callable = callable; + return p; error: - Py_XDECREF(p); - return NULL; + Py_XDECREF(p); + return NULL; } #ifdef MS_WIN32 static void LoadPython(void) { - if (!Py_IsInitialized()) { + if (!Py_IsInitialized()) { #ifdef WITH_THREAD - PyEval_InitThreads(); + PyEval_InitThreads(); #endif - Py_Initialize(); - } + Py_Initialize(); + } } /******************************************************************/ long Call_GetClassObject(REFCLSID rclsid, REFIID riid, LPVOID *ppv) { - PyObject *mod, *func, *result; - long retval; - static PyObject *context; - - if (context == NULL) - context = PyUnicode_InternFromString("_ctypes.DllGetClassObject"); - - mod = PyImport_ImportModuleNoBlock("ctypes"); - if (!mod) { - PyErr_WriteUnraisable(context ? context : Py_None); - /* There has been a warning before about this already */ - return E_FAIL; - } - - func = PyObject_GetAttrString(mod, "DllGetClassObject"); - Py_DECREF(mod); - if (!func) { - PyErr_WriteUnraisable(context ? context : Py_None); - return E_FAIL; - } - - { - PyObject *py_rclsid = PyLong_FromVoidPtr((void *)rclsid); - PyObject *py_riid = PyLong_FromVoidPtr((void *)riid); - PyObject *py_ppv = PyLong_FromVoidPtr(ppv); - if (!py_rclsid || !py_riid || !py_ppv) { - Py_XDECREF(py_rclsid); - Py_XDECREF(py_riid); - Py_XDECREF(py_ppv); - Py_DECREF(func); - PyErr_WriteUnraisable(context ? context : Py_None); - return E_FAIL; - } - result = PyObject_CallFunctionObjArgs(func, - py_rclsid, - py_riid, - py_ppv, - NULL); - Py_DECREF(py_rclsid); - Py_DECREF(py_riid); - Py_DECREF(py_ppv); - } - Py_DECREF(func); - if (!result) { - PyErr_WriteUnraisable(context ? context : Py_None); - return E_FAIL; - } - - retval = PyLong_AsLong(result); - if (PyErr_Occurred()) { - PyErr_WriteUnraisable(context ? context : Py_None); - retval = E_FAIL; - } - Py_DECREF(result); - return retval; + PyObject *mod, *func, *result; + long retval; + static PyObject *context; + + if (context == NULL) + context = PyUnicode_InternFromString("_ctypes.DllGetClassObject"); + + mod = PyImport_ImportModuleNoBlock("ctypes"); + if (!mod) { + PyErr_WriteUnraisable(context ? context : Py_None); + /* There has been a warning before about this already */ + return E_FAIL; + } + + func = PyObject_GetAttrString(mod, "DllGetClassObject"); + Py_DECREF(mod); + if (!func) { + PyErr_WriteUnraisable(context ? context : Py_None); + return E_FAIL; + } + + { + PyObject *py_rclsid = PyLong_FromVoidPtr((void *)rclsid); + PyObject *py_riid = PyLong_FromVoidPtr((void *)riid); + PyObject *py_ppv = PyLong_FromVoidPtr(ppv); + if (!py_rclsid || !py_riid || !py_ppv) { + Py_XDECREF(py_rclsid); + Py_XDECREF(py_riid); + Py_XDECREF(py_ppv); + Py_DECREF(func); + PyErr_WriteUnraisable(context ? context : Py_None); + return E_FAIL; + } + result = PyObject_CallFunctionObjArgs(func, + py_rclsid, + py_riid, + py_ppv, + NULL); + Py_DECREF(py_rclsid); + Py_DECREF(py_riid); + Py_DECREF(py_ppv); + } + Py_DECREF(func); + if (!result) { + PyErr_WriteUnraisable(context ? context : Py_None); + return E_FAIL; + } + + retval = PyLong_AsLong(result); + if (PyErr_Occurred()) { + PyErr_WriteUnraisable(context ? context : Py_None); + retval = E_FAIL; + } + Py_DECREF(result); + return retval; } STDAPI DllGetClassObject(REFCLSID rclsid, - REFIID riid, - LPVOID *ppv) + REFIID riid, + LPVOID *ppv) { - long result; + long result; #ifdef WITH_THREAD - PyGILState_STATE state; + PyGILState_STATE state; #endif - LoadPython(); + LoadPython(); #ifdef WITH_THREAD - state = PyGILState_Ensure(); + state = PyGILState_Ensure(); #endif - result = Call_GetClassObject(rclsid, riid, ppv); + result = Call_GetClassObject(rclsid, riid, ppv); #ifdef WITH_THREAD - PyGILState_Release(state); + PyGILState_Release(state); #endif - return result; + return result; } long Call_CanUnloadNow(void) { - PyObject *mod, *func, *result; - long retval; - static PyObject *context; - - if (context == NULL) - context = PyUnicode_InternFromString("_ctypes.DllCanUnloadNow"); - - mod = PyImport_ImportModuleNoBlock("ctypes"); - if (!mod) { -/* OutputDebugString("Could not import ctypes"); */ - /* We assume that this error can only occur when shutting - down, so we silently ignore it */ - PyErr_Clear(); - return E_FAIL; - } - /* Other errors cannot be raised, but are printed to stderr */ - func = PyObject_GetAttrString(mod, "DllCanUnloadNow"); - Py_DECREF(mod); - if (!func) { - PyErr_WriteUnraisable(context ? context : Py_None); - return E_FAIL; - } - - result = PyObject_CallFunction(func, NULL); - Py_DECREF(func); - if (!result) { - PyErr_WriteUnraisable(context ? context : Py_None); - return E_FAIL; - } - - retval = PyLong_AsLong(result); - if (PyErr_Occurred()) { - PyErr_WriteUnraisable(context ? context : Py_None); - retval = E_FAIL; - } - Py_DECREF(result); - return retval; + PyObject *mod, *func, *result; + long retval; + static PyObject *context; + + if (context == NULL) + context = PyUnicode_InternFromString("_ctypes.DllCanUnloadNow"); + + mod = PyImport_ImportModuleNoBlock("ctypes"); + if (!mod) { +/* OutputDebugString("Could not import ctypes"); */ + /* We assume that this error can only occur when shutting + down, so we silently ignore it */ + PyErr_Clear(); + return E_FAIL; + } + /* Other errors cannot be raised, but are printed to stderr */ + func = PyObject_GetAttrString(mod, "DllCanUnloadNow"); + Py_DECREF(mod); + if (!func) { + PyErr_WriteUnraisable(context ? context : Py_None); + return E_FAIL; + } + + result = PyObject_CallFunction(func, NULL); + Py_DECREF(func); + if (!result) { + PyErr_WriteUnraisable(context ? context : Py_None); + return E_FAIL; + } + + retval = PyLong_AsLong(result); + if (PyErr_Occurred()) { + PyErr_WriteUnraisable(context ? context : Py_None); + retval = E_FAIL; + } + Py_DECREF(result); + return retval; } /* @@ -572,26 +572,26 @@ STDAPI DllCanUnloadNow(void) { - long result; + long result; #ifdef WITH_THREAD - PyGILState_STATE state = PyGILState_Ensure(); + PyGILState_STATE state = PyGILState_Ensure(); #endif - result = Call_CanUnloadNow(); + result = Call_CanUnloadNow(); #ifdef WITH_THREAD - PyGILState_Release(state); + PyGILState_Release(state); #endif - return result; + return result; } #ifndef Py_NO_ENABLE_SHARED BOOL WINAPI DllMain(HINSTANCE hinstDLL, DWORD fdwReason, LPVOID lpvRes) { - switch(fdwReason) { - case DLL_PROCESS_ATTACH: - DisableThreadLibraryCalls(hinstDLL); - break; - } - return TRUE; + switch(fdwReason) { + case DLL_PROCESS_ATTACH: + DisableThreadLibraryCalls(hinstDLL); + break; + } + return TRUE; } #endif Modified: python/branches/py3k/Modules/_ctypes/callproc.c ============================================================================== --- python/branches/py3k/Modules/_ctypes/callproc.c (original) +++ python/branches/py3k/Modules/_ctypes/callproc.c Sun May 9 17:52:27 2010 @@ -4,9 +4,9 @@ */ /* * Related Work: - * - calldll http://www.nightmare.com/software.html - * - libffi http://sourceware.cygnus.com/libffi/ - * - ffcall http://clisp.cons.org/~haible/packages-ffcall.html + * - calldll http://www.nightmare.com/software.html + * - libffi http://sourceware.cygnus.com/libffi/ + * - ffcall http://clisp.cons.org/~haible/packages-ffcall.html * and, of course, Don Beaudry's MESS package, but this is more ctypes * related. */ @@ -82,17 +82,17 @@ static void pymem_destructor(PyObject *ptr) { - void *p = PyCapsule_GetPointer(ptr, CTYPES_CAPSULE_NAME_PYMEM); - if (p) { - PyMem_Free(p); - } + void *p = PyCapsule_GetPointer(ptr, CTYPES_CAPSULE_NAME_PYMEM); + if (p) { + PyMem_Free(p); + } } /* ctypes maintains thread-local storage that has space for two error numbers: private copies of the system 'errno' value and, on Windows, the system error code accessed by the GetLastError() and SetLastError() api functions. - + Foreign functions created with CDLL(..., use_errno=True), when called, swap the system 'errno' value with the private copy just before the actual function call, and swapped again immediately afterwards. The 'use_errno' @@ -125,88 +125,88 @@ PyObject * _ctypes_get_errobj(int **pspace) { - PyObject *dict = PyThreadState_GetDict(); - PyObject *errobj; - static PyObject *error_object_name; - if (dict == 0) { - PyErr_SetString(PyExc_RuntimeError, - "cannot get thread state"); - return NULL; - } - if (error_object_name == NULL) { - error_object_name = PyUnicode_InternFromString("ctypes.error_object"); - if (error_object_name == NULL) - return NULL; - } - errobj = PyDict_GetItem(dict, error_object_name); - if (errobj) { - if (!PyCapsule_IsValid(errobj, CTYPES_CAPSULE_NAME_PYMEM)) { - PyErr_SetString(PyExc_RuntimeError, - "ctypes.error_object is an invalid capsule"); - return NULL; - } - Py_INCREF(errobj); - } - else { - void *space = PyMem_Malloc(sizeof(int) * 2); - if (space == NULL) - return NULL; - memset(space, 0, sizeof(int) * 2); - errobj = PyCapsule_New(space, CTYPES_CAPSULE_NAME_PYMEM, pymem_destructor); - if (errobj == NULL) - return NULL; - if (-1 == PyDict_SetItem(dict, error_object_name, - errobj)) { - Py_DECREF(errobj); - return NULL; - } - } - *pspace = (int *)PyCapsule_GetPointer(errobj, CTYPES_CAPSULE_NAME_PYMEM); - return errobj; + PyObject *dict = PyThreadState_GetDict(); + PyObject *errobj; + static PyObject *error_object_name; + if (dict == 0) { + PyErr_SetString(PyExc_RuntimeError, + "cannot get thread state"); + return NULL; + } + if (error_object_name == NULL) { + error_object_name = PyUnicode_InternFromString("ctypes.error_object"); + if (error_object_name == NULL) + return NULL; + } + errobj = PyDict_GetItem(dict, error_object_name); + if (errobj) { + if (!PyCapsule_IsValid(errobj, CTYPES_CAPSULE_NAME_PYMEM)) { + PyErr_SetString(PyExc_RuntimeError, + "ctypes.error_object is an invalid capsule"); + return NULL; + } + Py_INCREF(errobj); + } + else { + void *space = PyMem_Malloc(sizeof(int) * 2); + if (space == NULL) + return NULL; + memset(space, 0, sizeof(int) * 2); + errobj = PyCapsule_New(space, CTYPES_CAPSULE_NAME_PYMEM, pymem_destructor); + if (errobj == NULL) + return NULL; + if (-1 == PyDict_SetItem(dict, error_object_name, + errobj)) { + Py_DECREF(errobj); + return NULL; + } + } + *pspace = (int *)PyCapsule_GetPointer(errobj, CTYPES_CAPSULE_NAME_PYMEM); + return errobj; } static PyObject * get_error_internal(PyObject *self, PyObject *args, int index) { - int *space; - PyObject *errobj = _ctypes_get_errobj(&space); - PyObject *result; - - if (errobj == NULL) - return NULL; - result = PyLong_FromLong(space[index]); - Py_DECREF(errobj); - return result; + int *space; + PyObject *errobj = _ctypes_get_errobj(&space); + PyObject *result; + + if (errobj == NULL) + return NULL; + result = PyLong_FromLong(space[index]); + Py_DECREF(errobj); + return result; } static PyObject * set_error_internal(PyObject *self, PyObject *args, int index) { - int new_errno, old_errno; - PyObject *errobj; - int *space; - - if (!PyArg_ParseTuple(args, "i", &new_errno)) - return NULL; - errobj = _ctypes_get_errobj(&space); - if (errobj == NULL) - return NULL; - old_errno = space[index]; - space[index] = new_errno; - Py_DECREF(errobj); - return PyLong_FromLong(old_errno); + int new_errno, old_errno; + PyObject *errobj; + int *space; + + if (!PyArg_ParseTuple(args, "i", &new_errno)) + return NULL; + errobj = _ctypes_get_errobj(&space); + if (errobj == NULL) + return NULL; + old_errno = space[index]; + space[index] = new_errno; + Py_DECREF(errobj); + return PyLong_FromLong(old_errno); } static PyObject * get_errno(PyObject *self, PyObject *args) { - return get_error_internal(self, args, 0); + return get_error_internal(self, args, 0); } static PyObject * set_errno(PyObject *self, PyObject *args) { - return set_error_internal(self, args, 0); + return set_error_internal(self, args, 0); } #ifdef MS_WIN32 @@ -214,202 +214,202 @@ static PyObject * get_last_error(PyObject *self, PyObject *args) { - return get_error_internal(self, args, 1); + return get_error_internal(self, args, 1); } static PyObject * set_last_error(PyObject *self, PyObject *args) { - return set_error_internal(self, args, 1); + return set_error_internal(self, args, 1); } PyObject *ComError; static WCHAR *FormatError(DWORD code) { - WCHAR *lpMsgBuf; - DWORD n; - n = FormatMessageW(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM, - NULL, - code, - MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), /* Default language */ - (LPWSTR) &lpMsgBuf, - 0, - NULL); - if (n) { - while (iswspace(lpMsgBuf[n-1])) - --n; - lpMsgBuf[n] = L'\0'; /* rstrip() */ - } - return lpMsgBuf; + WCHAR *lpMsgBuf; + DWORD n; + n = FormatMessageW(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM, + NULL, + code, + MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), /* Default language */ + (LPWSTR) &lpMsgBuf, + 0, + NULL); + if (n) { + while (iswspace(lpMsgBuf[n-1])) + --n; + lpMsgBuf[n] = L'\0'; /* rstrip() */ + } + return lpMsgBuf; } #ifndef DONT_USE_SEH static void SetException(DWORD code, EXCEPTION_RECORD *pr) { - /* The 'code' is a normal win32 error code so it could be handled by - PyErr_SetFromWindowsErr(). However, for some errors, we have additional - information not included in the error code. We handle those here and - delegate all others to the generic function. */ - switch (code) { - case EXCEPTION_ACCESS_VIOLATION: - /* The thread attempted to read from or write - to a virtual address for which it does not - have the appropriate access. */ - if (pr->ExceptionInformation[0] == 0) - PyErr_Format(PyExc_WindowsError, - "exception: access violation reading %p", - pr->ExceptionInformation[1]); - else - PyErr_Format(PyExc_WindowsError, - "exception: access violation writing %p", - pr->ExceptionInformation[1]); - break; - - case EXCEPTION_BREAKPOINT: - /* A breakpoint was encountered. */ - PyErr_SetString(PyExc_WindowsError, - "exception: breakpoint encountered"); - break; - - case EXCEPTION_DATATYPE_MISALIGNMENT: - /* The thread attempted to read or write data that is - misaligned on hardware that does not provide - alignment. For example, 16-bit values must be - aligned on 2-byte boundaries, 32-bit values on - 4-byte boundaries, and so on. */ - PyErr_SetString(PyExc_WindowsError, - "exception: datatype misalignment"); - break; - - case EXCEPTION_SINGLE_STEP: - /* A trace trap or other single-instruction mechanism - signaled that one instruction has been executed. */ - PyErr_SetString(PyExc_WindowsError, - "exception: single step"); - break; - - case EXCEPTION_ARRAY_BOUNDS_EXCEEDED: - /* The thread attempted to access an array element - that is out of bounds, and the underlying hardware - supports bounds checking. */ - PyErr_SetString(PyExc_WindowsError, - "exception: array bounds exceeded"); - break; - - case EXCEPTION_FLT_DENORMAL_OPERAND: - /* One of the operands in a floating-point operation - is denormal. A denormal value is one that is too - small to represent as a standard floating-point - value. */ - PyErr_SetString(PyExc_WindowsError, - "exception: floating-point operand denormal"); - break; - - case EXCEPTION_FLT_DIVIDE_BY_ZERO: - /* The thread attempted to divide a floating-point - value by a floating-point divisor of zero. */ - PyErr_SetString(PyExc_WindowsError, - "exception: float divide by zero"); - break; - - case EXCEPTION_FLT_INEXACT_RESULT: - /* The result of a floating-point operation cannot be - represented exactly as a decimal fraction. */ - PyErr_SetString(PyExc_WindowsError, - "exception: float inexact"); - break; - - case EXCEPTION_FLT_INVALID_OPERATION: - /* This exception represents any floating-point - exception not included in this list. */ - PyErr_SetString(PyExc_WindowsError, - "exception: float invalid operation"); - break; - - case EXCEPTION_FLT_OVERFLOW: - /* The exponent of a floating-point operation is - greater than the magnitude allowed by the - corresponding type. */ - PyErr_SetString(PyExc_WindowsError, - "exception: float overflow"); - break; - - case EXCEPTION_FLT_STACK_CHECK: - /* The stack overflowed or underflowed as the result - of a floating-point operation. */ - PyErr_SetString(PyExc_WindowsError, - "exception: stack over/underflow"); - break; - - case EXCEPTION_STACK_OVERFLOW: - /* The stack overflowed or underflowed as the result - of a floating-point operation. */ - PyErr_SetString(PyExc_WindowsError, - "exception: stack overflow"); - break; - - case EXCEPTION_FLT_UNDERFLOW: - /* The exponent of a floating-point operation is less - than the magnitude allowed by the corresponding - type. */ - PyErr_SetString(PyExc_WindowsError, - "exception: float underflow"); - break; - - case EXCEPTION_INT_DIVIDE_BY_ZERO: - /* The thread attempted to divide an integer value by - an integer divisor of zero. */ - PyErr_SetString(PyExc_WindowsError, - "exception: integer divide by zero"); - break; - - case EXCEPTION_INT_OVERFLOW: - /* The result of an integer operation caused a carry - out of the most significant bit of the result. */ - PyErr_SetString(PyExc_WindowsError, - "exception: integer overflow"); - break; - - case EXCEPTION_PRIV_INSTRUCTION: - /* The thread attempted to execute an instruction - whose operation is not allowed in the current - machine mode. */ - PyErr_SetString(PyExc_WindowsError, - "exception: priviledged instruction"); - break; - - case EXCEPTION_NONCONTINUABLE_EXCEPTION: - /* The thread attempted to continue execution after a - noncontinuable exception occurred. */ - PyErr_SetString(PyExc_WindowsError, - "exception: nocontinuable"); - break; - - default: - PyErr_SetFromWindowsErr(code); - break; - } + /* The 'code' is a normal win32 error code so it could be handled by + PyErr_SetFromWindowsErr(). However, for some errors, we have additional + information not included in the error code. We handle those here and + delegate all others to the generic function. */ + switch (code) { + case EXCEPTION_ACCESS_VIOLATION: + /* The thread attempted to read from or write + to a virtual address for which it does not + have the appropriate access. */ + if (pr->ExceptionInformation[0] == 0) + PyErr_Format(PyExc_WindowsError, + "exception: access violation reading %p", + pr->ExceptionInformation[1]); + else + PyErr_Format(PyExc_WindowsError, + "exception: access violation writing %p", + pr->ExceptionInformation[1]); + break; + + case EXCEPTION_BREAKPOINT: + /* A breakpoint was encountered. */ + PyErr_SetString(PyExc_WindowsError, + "exception: breakpoint encountered"); + break; + + case EXCEPTION_DATATYPE_MISALIGNMENT: + /* The thread attempted to read or write data that is + misaligned on hardware that does not provide + alignment. For example, 16-bit values must be + aligned on 2-byte boundaries, 32-bit values on + 4-byte boundaries, and so on. */ + PyErr_SetString(PyExc_WindowsError, + "exception: datatype misalignment"); + break; + + case EXCEPTION_SINGLE_STEP: + /* A trace trap or other single-instruction mechanism + signaled that one instruction has been executed. */ + PyErr_SetString(PyExc_WindowsError, + "exception: single step"); + break; + + case EXCEPTION_ARRAY_BOUNDS_EXCEEDED: + /* The thread attempted to access an array element + that is out of bounds, and the underlying hardware + supports bounds checking. */ + PyErr_SetString(PyExc_WindowsError, + "exception: array bounds exceeded"); + break; + + case EXCEPTION_FLT_DENORMAL_OPERAND: + /* One of the operands in a floating-point operation + is denormal. A denormal value is one that is too + small to represent as a standard floating-point + value. */ + PyErr_SetString(PyExc_WindowsError, + "exception: floating-point operand denormal"); + break; + + case EXCEPTION_FLT_DIVIDE_BY_ZERO: + /* The thread attempted to divide a floating-point + value by a floating-point divisor of zero. */ + PyErr_SetString(PyExc_WindowsError, + "exception: float divide by zero"); + break; + + case EXCEPTION_FLT_INEXACT_RESULT: + /* The result of a floating-point operation cannot be + represented exactly as a decimal fraction. */ + PyErr_SetString(PyExc_WindowsError, + "exception: float inexact"); + break; + + case EXCEPTION_FLT_INVALID_OPERATION: + /* This exception represents any floating-point + exception not included in this list. */ + PyErr_SetString(PyExc_WindowsError, + "exception: float invalid operation"); + break; + + case EXCEPTION_FLT_OVERFLOW: + /* The exponent of a floating-point operation is + greater than the magnitude allowed by the + corresponding type. */ + PyErr_SetString(PyExc_WindowsError, + "exception: float overflow"); + break; + + case EXCEPTION_FLT_STACK_CHECK: + /* The stack overflowed or underflowed as the result + of a floating-point operation. */ + PyErr_SetString(PyExc_WindowsError, + "exception: stack over/underflow"); + break; + + case EXCEPTION_STACK_OVERFLOW: + /* The stack overflowed or underflowed as the result + of a floating-point operation. */ + PyErr_SetString(PyExc_WindowsError, + "exception: stack overflow"); + break; + + case EXCEPTION_FLT_UNDERFLOW: + /* The exponent of a floating-point operation is less + than the magnitude allowed by the corresponding + type. */ + PyErr_SetString(PyExc_WindowsError, + "exception: float underflow"); + break; + + case EXCEPTION_INT_DIVIDE_BY_ZERO: + /* The thread attempted to divide an integer value by + an integer divisor of zero. */ + PyErr_SetString(PyExc_WindowsError, + "exception: integer divide by zero"); + break; + + case EXCEPTION_INT_OVERFLOW: + /* The result of an integer operation caused a carry + out of the most significant bit of the result. */ + PyErr_SetString(PyExc_WindowsError, + "exception: integer overflow"); + break; + + case EXCEPTION_PRIV_INSTRUCTION: + /* The thread attempted to execute an instruction + whose operation is not allowed in the current + machine mode. */ + PyErr_SetString(PyExc_WindowsError, + "exception: priviledged instruction"); + break; + + case EXCEPTION_NONCONTINUABLE_EXCEPTION: + /* The thread attempted to continue execution after a + noncontinuable exception occurred. */ + PyErr_SetString(PyExc_WindowsError, + "exception: nocontinuable"); + break; + + default: + PyErr_SetFromWindowsErr(code); + break; + } } static DWORD HandleException(EXCEPTION_POINTERS *ptrs, - DWORD *pdw, EXCEPTION_RECORD *record) + DWORD *pdw, EXCEPTION_RECORD *record) { - *pdw = ptrs->ExceptionRecord->ExceptionCode; - *record = *ptrs->ExceptionRecord; - return EXCEPTION_EXECUTE_HANDLER; + *pdw = ptrs->ExceptionRecord->ExceptionCode; + *record = *ptrs->ExceptionRecord; + return EXCEPTION_EXECUTE_HANDLER; } #endif static PyObject * check_hresult(PyObject *self, PyObject *args) { - HRESULT hr; - if (!PyArg_ParseTuple(args, "i", &hr)) - return NULL; - if (FAILED(hr)) - return PyErr_SetFromWindowsErr(hr); - return PyLong_FromLong(hr); + HRESULT hr; + if (!PyArg_ParseTuple(args, "i", &hr)) + return NULL; + if (FAILED(hr)) + return PyErr_SetFromWindowsErr(hr); + return PyLong_FromLong(hr); } #endif @@ -419,132 +419,132 @@ PyCArgObject * PyCArgObject_new(void) { - PyCArgObject *p; - p = PyObject_New(PyCArgObject, &PyCArg_Type); - if (p == NULL) - return NULL; - p->pffi_type = NULL; - p->tag = '\0'; - p->obj = NULL; - memset(&p->value, 0, sizeof(p->value)); - return p; + PyCArgObject *p; + p = PyObject_New(PyCArgObject, &PyCArg_Type); + if (p == NULL) + return NULL; + p->pffi_type = NULL; + p->tag = '\0'; + p->obj = NULL; + memset(&p->value, 0, sizeof(p->value)); + return p; } static void PyCArg_dealloc(PyCArgObject *self) { - Py_XDECREF(self->obj); - PyObject_Del(self); + Py_XDECREF(self->obj); + PyObject_Del(self); } static PyObject * PyCArg_repr(PyCArgObject *self) { - char buffer[256]; - switch(self->tag) { - case 'b': - case 'B': - sprintf(buffer, "", - self->tag, self->value.b); - break; - case 'h': - case 'H': - sprintf(buffer, "", - self->tag, self->value.h); - break; - case 'i': - case 'I': - sprintf(buffer, "", - self->tag, self->value.i); - break; - case 'l': - case 'L': - sprintf(buffer, "", - self->tag, self->value.l); - break; - + char buffer[256]; + switch(self->tag) { + case 'b': + case 'B': + sprintf(buffer, "", + self->tag, self->value.b); + break; + case 'h': + case 'H': + sprintf(buffer, "", + self->tag, self->value.h); + break; + case 'i': + case 'I': + sprintf(buffer, "", + self->tag, self->value.i); + break; + case 'l': + case 'L': + sprintf(buffer, "", + self->tag, self->value.l); + break; + #ifdef HAVE_LONG_LONG - case 'q': - case 'Q': - sprintf(buffer, + case 'q': + case 'Q': + sprintf(buffer, #ifdef MS_WIN32 - "", + "", #else - "", + "", #endif - self->tag, self->value.q); - break; + self->tag, self->value.q); + break; #endif - case 'd': - sprintf(buffer, "", - self->tag, self->value.d); - break; - case 'f': - sprintf(buffer, "", - self->tag, self->value.f); - break; - - case 'c': - sprintf(buffer, "", - self->tag, self->value.c); - break; + case 'd': + sprintf(buffer, "", + self->tag, self->value.d); + break; + case 'f': + sprintf(buffer, "", + self->tag, self->value.f); + break; + + case 'c': + sprintf(buffer, "", + self->tag, self->value.c); + break; /* Hm, are these 'z' and 'Z' codes useful at all? Shouldn't they be replaced by the functionality of c_string and c_wstring ? */ - case 'z': - case 'Z': - case 'P': - sprintf(buffer, "", - self->tag, self->value.p); - break; - - default: - sprintf(buffer, "", - self->tag, self); - break; - } - return PyUnicode_FromString(buffer); + case 'z': + case 'Z': + case 'P': + sprintf(buffer, "", + self->tag, self->value.p); + break; + + default: + sprintf(buffer, "", + self->tag, self); + break; + } + return PyUnicode_FromString(buffer); } static PyMemberDef PyCArgType_members[] = { - { "_obj", T_OBJECT, - offsetof(PyCArgObject, obj), READONLY, - "the wrapped object" }, - { NULL }, + { "_obj", T_OBJECT, + offsetof(PyCArgObject, obj), READONLY, + "the wrapped object" }, + { NULL }, }; PyTypeObject PyCArg_Type = { - PyVarObject_HEAD_INIT(NULL, 0) - "CArgObject", - sizeof(PyCArgObject), - 0, - (destructor)PyCArg_dealloc, /* tp_dealloc */ - 0, /* tp_print */ - 0, /* tp_getattr */ - 0, /* tp_setattr */ - 0, /* tp_reserved */ - (reprfunc)PyCArg_repr, /* tp_repr */ - 0, /* tp_as_number */ - 0, /* tp_as_sequence */ - 0, /* tp_as_mapping */ - 0, /* tp_hash */ - 0, /* tp_call */ - 0, /* tp_str */ - 0, /* tp_getattro */ - 0, /* tp_setattro */ - 0, /* tp_as_buffer */ - Py_TPFLAGS_DEFAULT, /* tp_flags */ - 0, /* tp_doc */ - 0, /* tp_traverse */ - 0, /* tp_clear */ - 0, /* tp_richcompare */ - 0, /* tp_weaklistoffset */ - 0, /* tp_iter */ - 0, /* tp_iternext */ - 0, /* tp_methods */ - PyCArgType_members, /* tp_members */ + PyVarObject_HEAD_INIT(NULL, 0) + "CArgObject", + sizeof(PyCArgObject), + 0, + (destructor)PyCArg_dealloc, /* tp_dealloc */ + 0, /* tp_print */ + 0, /* tp_getattr */ + 0, /* tp_setattr */ + 0, /* tp_reserved */ + (reprfunc)PyCArg_repr, /* tp_repr */ + 0, /* tp_as_number */ + 0, /* tp_as_sequence */ + 0, /* tp_as_mapping */ + 0, /* tp_hash */ + 0, /* tp_call */ + 0, /* tp_str */ + 0, /* tp_getattro */ + 0, /* tp_setattro */ + 0, /* tp_as_buffer */ + Py_TPFLAGS_DEFAULT, /* tp_flags */ + 0, /* tp_doc */ + 0, /* tp_traverse */ + 0, /* tp_clear */ + 0, /* tp_richcompare */ + 0, /* tp_weaklistoffset */ + 0, /* tp_iter */ + 0, /* tp_iternext */ + 0, /* tp_methods */ + PyCArgType_members, /* tp_members */ }; /****************************************************************/ @@ -577,24 +577,24 @@ */ union result { - char c; - char b; - short h; - int i; - long l; + char c; + char b; + short h; + int i; + long l; #ifdef HAVE_LONG_LONG - PY_LONG_LONG q; + PY_LONG_LONG q; #endif - long double D; - double d; - float f; - void *p; + long double D; + double d; + float f; + void *p; }; struct argument { - ffi_type *ffi_type; - PyObject *keep; - union result value; + ffi_type *ffi_type; + PyObject *keep; + union result value; }; /* @@ -602,134 +602,134 @@ */ static int ConvParam(PyObject *obj, Py_ssize_t index, struct argument *pa) { - StgDictObject *dict; - pa->keep = NULL; /* so we cannot forget it later */ + StgDictObject *dict; + pa->keep = NULL; /* so we cannot forget it later */ - dict = PyObject_stgdict(obj); - if (dict) { - PyCArgObject *carg; - assert(dict->paramfunc); - /* If it has an stgdict, it is a CDataObject */ - carg = dict->paramfunc((CDataObject *)obj); - pa->ffi_type = carg->pffi_type; - memcpy(&pa->value, &carg->value, sizeof(pa->value)); - pa->keep = (PyObject *)carg; - return 0; - } - - if (PyCArg_CheckExact(obj)) { - PyCArgObject *carg = (PyCArgObject *)obj; - pa->ffi_type = carg->pffi_type; - Py_INCREF(obj); - pa->keep = obj; - memcpy(&pa->value, &carg->value, sizeof(pa->value)); - return 0; - } - - /* check for None, integer, string or unicode and use directly if successful */ - if (obj == Py_None) { - pa->ffi_type = &ffi_type_pointer; - pa->value.p = NULL; - return 0; - } - - if (PyLong_Check(obj)) { - pa->ffi_type = &ffi_type_sint; - pa->value.i = (long)PyLong_AsUnsignedLong(obj); - if (pa->value.i == -1 && PyErr_Occurred()) { - PyErr_Clear(); - pa->value.i = PyLong_AsLong(obj); - if (pa->value.i == -1 && PyErr_Occurred()) { - PyErr_SetString(PyExc_OverflowError, - "long int too long to convert"); - return -1; - } - } - return 0; - } - - if (PyBytes_Check(obj)) { - pa->ffi_type = &ffi_type_pointer; - pa->value.p = PyBytes_AsString(obj); - Py_INCREF(obj); - pa->keep = obj; - return 0; - } + dict = PyObject_stgdict(obj); + if (dict) { + PyCArgObject *carg; + assert(dict->paramfunc); + /* If it has an stgdict, it is a CDataObject */ + carg = dict->paramfunc((CDataObject *)obj); + pa->ffi_type = carg->pffi_type; + memcpy(&pa->value, &carg->value, sizeof(pa->value)); + pa->keep = (PyObject *)carg; + return 0; + } + + if (PyCArg_CheckExact(obj)) { + PyCArgObject *carg = (PyCArgObject *)obj; + pa->ffi_type = carg->pffi_type; + Py_INCREF(obj); + pa->keep = obj; + memcpy(&pa->value, &carg->value, sizeof(pa->value)); + return 0; + } + + /* check for None, integer, string or unicode and use directly if successful */ + if (obj == Py_None) { + pa->ffi_type = &ffi_type_pointer; + pa->value.p = NULL; + return 0; + } + + if (PyLong_Check(obj)) { + pa->ffi_type = &ffi_type_sint; + pa->value.i = (long)PyLong_AsUnsignedLong(obj); + if (pa->value.i == -1 && PyErr_Occurred()) { + PyErr_Clear(); + pa->value.i = PyLong_AsLong(obj); + if (pa->value.i == -1 && PyErr_Occurred()) { + PyErr_SetString(PyExc_OverflowError, + "long int too long to convert"); + return -1; + } + } + return 0; + } + + if (PyBytes_Check(obj)) { + pa->ffi_type = &ffi_type_pointer; + pa->value.p = PyBytes_AsString(obj); + Py_INCREF(obj); + pa->keep = obj; + return 0; + } #ifdef CTYPES_UNICODE - if (PyUnicode_Check(obj)) { + if (PyUnicode_Check(obj)) { #ifdef HAVE_USABLE_WCHAR_T - pa->ffi_type = &ffi_type_pointer; - pa->value.p = PyUnicode_AS_UNICODE(obj); - Py_INCREF(obj); - pa->keep = obj; - return 0; + pa->ffi_type = &ffi_type_pointer; + pa->value.p = PyUnicode_AS_UNICODE(obj); + Py_INCREF(obj); + pa->keep = obj; + return 0; #else - int size = PyUnicode_GET_SIZE(obj); - pa->ffi_type = &ffi_type_pointer; - size += 1; /* terminating NUL */ - size *= sizeof(wchar_t); - pa->value.p = PyMem_Malloc(size); - if (!pa->value.p) { - PyErr_NoMemory(); - return -1; - } - memset(pa->value.p, 0, size); - pa->keep = PyCapsule_New(pa->value.p, CTYPES_CAPSULE_NAME_PYMEM, pymem_destructor); - if (!pa->keep) { - PyMem_Free(pa->value.p); - return -1; - } - if (-1 == PyUnicode_AsWideChar((PyUnicodeObject *)obj, - pa->value.p, PyUnicode_GET_SIZE(obj))) - return -1; - return 0; -#endif - } -#endif - - { - PyObject *arg; - arg = PyObject_GetAttrString(obj, "_as_parameter_"); - /* Which types should we exactly allow here? - integers are required for using Python classes - as parameters (they have to expose the '_as_parameter_' - attribute) - */ - if (arg) { - int result; - result = ConvParam(arg, index, pa); - Py_DECREF(arg); - return result; - } - PyErr_Format(PyExc_TypeError, - "Don't know how to convert parameter %d", - Py_SAFE_DOWNCAST(index, Py_ssize_t, int)); - return -1; - } + int size = PyUnicode_GET_SIZE(obj); + pa->ffi_type = &ffi_type_pointer; + size += 1; /* terminating NUL */ + size *= sizeof(wchar_t); + pa->value.p = PyMem_Malloc(size); + if (!pa->value.p) { + PyErr_NoMemory(); + return -1; + } + memset(pa->value.p, 0, size); + pa->keep = PyCapsule_New(pa->value.p, CTYPES_CAPSULE_NAME_PYMEM, pymem_destructor); + if (!pa->keep) { + PyMem_Free(pa->value.p); + return -1; + } + if (-1 == PyUnicode_AsWideChar((PyUnicodeObject *)obj, + pa->value.p, PyUnicode_GET_SIZE(obj))) + return -1; + return 0; +#endif + } +#endif + + { + PyObject *arg; + arg = PyObject_GetAttrString(obj, "_as_parameter_"); + /* Which types should we exactly allow here? + integers are required for using Python classes + as parameters (they have to expose the '_as_parameter_' + attribute) + */ + if (arg) { + int result; + result = ConvParam(arg, index, pa); + Py_DECREF(arg); + return result; + } + PyErr_Format(PyExc_TypeError, + "Don't know how to convert parameter %d", + Py_SAFE_DOWNCAST(index, Py_ssize_t, int)); + return -1; + } } ffi_type *_ctypes_get_ffi_type(PyObject *obj) { - StgDictObject *dict; - if (obj == NULL) - return &ffi_type_sint; - dict = PyType_stgdict(obj); - if (dict == NULL) - return &ffi_type_sint; + StgDictObject *dict; + if (obj == NULL) + return &ffi_type_sint; + dict = PyType_stgdict(obj); + if (dict == NULL) + return &ffi_type_sint; #if defined(MS_WIN32) && !defined(_WIN32_WCE) - /* This little trick works correctly with MSVC. - It returns small structures in registers - */ - if (dict->ffi_type_pointer.type == FFI_TYPE_STRUCT) { - if (dict->ffi_type_pointer.size <= 4) - return &ffi_type_sint32; - else if (dict->ffi_type_pointer.size <= 8) - return &ffi_type_sint64; - } + /* This little trick works correctly with MSVC. + It returns small structures in registers + */ + if (dict->ffi_type_pointer.type == FFI_TYPE_STRUCT) { + if (dict->ffi_type_pointer.size <= 4) + return &ffi_type_sint32; + else if (dict->ffi_type_pointer.size <= 8) + return &ffi_type_sint64; + } #endif - return &dict->ffi_type_pointer; + return &dict->ffi_type_pointer; } @@ -737,7 +737,7 @@ * libffi uses: * * ffi_status ffi_prep_cif(ffi_cif *cif, ffi_abi abi, - * unsigned int nargs, + * unsigned int nargs, * ffi_type *rtype, * ffi_type **atypes); * @@ -746,108 +746,108 @@ * void ffi_call(ffi_cif *cif, void *fn, void *rvalue, void **avalues); */ static int _call_function_pointer(int flags, - PPROC pProc, - void **avalues, - ffi_type **atypes, - ffi_type *restype, - void *resmem, - int argcount) + PPROC pProc, + void **avalues, + ffi_type **atypes, + ffi_type *restype, + void *resmem, + int argcount) { #ifdef WITH_THREAD - PyThreadState *_save = NULL; /* For Py_BLOCK_THREADS and Py_UNBLOCK_THREADS */ + PyThreadState *_save = NULL; /* For Py_BLOCK_THREADS and Py_UNBLOCK_THREADS */ #endif - PyObject *error_object = NULL; - int *space; - ffi_cif cif; - int cc; + PyObject *error_object = NULL; + int *space; + ffi_cif cif; + int cc; #ifdef MS_WIN32 #ifndef DONT_USE_SEH - DWORD dwExceptionCode = 0; - EXCEPTION_RECORD record; + DWORD dwExceptionCode = 0; + EXCEPTION_RECORD record; #endif #endif - /* XXX check before here */ - if (restype == NULL) { - PyErr_SetString(PyExc_RuntimeError, - "No ffi_type for result"); - return -1; - } - - cc = FFI_DEFAULT_ABI; + /* XXX check before here */ + if (restype == NULL) { + PyErr_SetString(PyExc_RuntimeError, + "No ffi_type for result"); + return -1; + } + + cc = FFI_DEFAULT_ABI; #if defined(MS_WIN32) && !defined(MS_WIN64) && !defined(_WIN32_WCE) - if ((flags & FUNCFLAG_CDECL) == 0) - cc = FFI_STDCALL; + if ((flags & FUNCFLAG_CDECL) == 0) + cc = FFI_STDCALL; #endif - if (FFI_OK != ffi_prep_cif(&cif, - cc, - argcount, - restype, - atypes)) { - PyErr_SetString(PyExc_RuntimeError, - "ffi_prep_cif failed"); - return -1; - } - - if (flags & (FUNCFLAG_USE_ERRNO | FUNCFLAG_USE_LASTERROR)) { - error_object = _ctypes_get_errobj(&space); - if (error_object == NULL) - return -1; - } + if (FFI_OK != ffi_prep_cif(&cif, + cc, + argcount, + restype, + atypes)) { + PyErr_SetString(PyExc_RuntimeError, + "ffi_prep_cif failed"); + return -1; + } + + if (flags & (FUNCFLAG_USE_ERRNO | FUNCFLAG_USE_LASTERROR)) { + error_object = _ctypes_get_errobj(&space); + if (error_object == NULL) + return -1; + } #ifdef WITH_THREAD - if ((flags & FUNCFLAG_PYTHONAPI) == 0) - Py_UNBLOCK_THREADS + if ((flags & FUNCFLAG_PYTHONAPI) == 0) + Py_UNBLOCK_THREADS #endif - if (flags & FUNCFLAG_USE_ERRNO) { - int temp = space[0]; - space[0] = errno; - errno = temp; - } + if (flags & FUNCFLAG_USE_ERRNO) { + int temp = space[0]; + space[0] = errno; + errno = temp; + } #ifdef MS_WIN32 - if (flags & FUNCFLAG_USE_LASTERROR) { - int temp = space[1]; - space[1] = GetLastError(); - SetLastError(temp); - } + if (flags & FUNCFLAG_USE_LASTERROR) { + int temp = space[1]; + space[1] = GetLastError(); + SetLastError(temp); + } #ifndef DONT_USE_SEH - __try { + __try { #endif #endif - ffi_call(&cif, (void *)pProc, resmem, avalues); + ffi_call(&cif, (void *)pProc, resmem, avalues); #ifdef MS_WIN32 #ifndef DONT_USE_SEH - } - __except (HandleException(GetExceptionInformation(), - &dwExceptionCode, &record)) { - ; - } -#endif - if (flags & FUNCFLAG_USE_LASTERROR) { - int temp = space[1]; - space[1] = GetLastError(); - SetLastError(temp); - } -#endif - if (flags & FUNCFLAG_USE_ERRNO) { - int temp = space[0]; - space[0] = errno; - errno = temp; - } - Py_XDECREF(error_object); + } + __except (HandleException(GetExceptionInformation(), + &dwExceptionCode, &record)) { + ; + } +#endif + if (flags & FUNCFLAG_USE_LASTERROR) { + int temp = space[1]; + space[1] = GetLastError(); + SetLastError(temp); + } +#endif + if (flags & FUNCFLAG_USE_ERRNO) { + int temp = space[0]; + space[0] = errno; + errno = temp; + } + Py_XDECREF(error_object); #ifdef WITH_THREAD - if ((flags & FUNCFLAG_PYTHONAPI) == 0) - Py_BLOCK_THREADS + if ((flags & FUNCFLAG_PYTHONAPI) == 0) + Py_BLOCK_THREADS #endif #ifdef MS_WIN32 #ifndef DONT_USE_SEH - if (dwExceptionCode) { - SetException(dwExceptionCode, &record); - return -1; - } + if (dwExceptionCode) { + SetException(dwExceptionCode, &record); + return -1; + } #endif #endif - if ((flags & FUNCFLAG_PYTHONAPI) && PyErr_Occurred()) - return -1; - return 0; + if ((flags & FUNCFLAG_PYTHONAPI) && PyErr_Occurred()) + return -1; + return 0; } /* @@ -862,41 +862,41 @@ */ static PyObject *GetResult(PyObject *restype, void *result, PyObject *checker) { - StgDictObject *dict; - PyObject *retval, *v; + StgDictObject *dict; + PyObject *retval, *v; - if (restype == NULL) - return PyLong_FromLong(*(int *)result); + if (restype == NULL) + return PyLong_FromLong(*(int *)result); - if (restype == Py_None) { - Py_INCREF(Py_None); - return Py_None; - } - - dict = PyType_stgdict(restype); - if (dict == NULL) - return PyObject_CallFunction(restype, "i", *(int *)result); - - if (dict->getfunc && !_ctypes_simple_instance(restype)) { - retval = dict->getfunc(result, dict->size); - /* If restype is py_object (detected by comparing getfunc with - O_get), we have to call Py_DECREF because O_get has already - called Py_INCREF. - */ - if (dict->getfunc == _ctypes_get_fielddesc("O")->getfunc) { - Py_DECREF(retval); - } - } else - retval = PyCData_FromBaseObj(restype, NULL, 0, result); - - if (!checker || !retval) - return retval; - - v = PyObject_CallFunctionObjArgs(checker, retval, NULL); - if (v == NULL) - _ctypes_add_traceback("GetResult", "_ctypes/callproc.c", __LINE__-2); - Py_DECREF(retval); - return v; + if (restype == Py_None) { + Py_INCREF(Py_None); + return Py_None; + } + + dict = PyType_stgdict(restype); + if (dict == NULL) + return PyObject_CallFunction(restype, "i", *(int *)result); + + if (dict->getfunc && !_ctypes_simple_instance(restype)) { + retval = dict->getfunc(result, dict->size); + /* If restype is py_object (detected by comparing getfunc with + O_get), we have to call Py_DECREF because O_get has already + called Py_INCREF. + */ + if (dict->getfunc == _ctypes_get_fielddesc("O")->getfunc) { + Py_DECREF(retval); + } + } else + retval = PyCData_FromBaseObj(restype, NULL, 0, result); + + if (!checker || !retval) + return retval; + + v = PyObject_CallFunctionObjArgs(checker, retval, NULL); + if (v == NULL) + _ctypes_add_traceback("GetResult", "_ctypes/callproc.c", __LINE__-2); + Py_DECREF(retval); + return v; } /* @@ -905,40 +905,40 @@ */ void _ctypes_extend_error(PyObject *exc_class, char *fmt, ...) { - va_list vargs; - PyObject *tp, *v, *tb, *s, *cls_str, *msg_str; + va_list vargs; + PyObject *tp, *v, *tb, *s, *cls_str, *msg_str; - va_start(vargs, fmt); - s = PyUnicode_FromFormatV(fmt, vargs); - va_end(vargs); - if (!s) - return; - - PyErr_Fetch(&tp, &v, &tb); - PyErr_NormalizeException(&tp, &v, &tb); - cls_str = PyObject_Str(tp); - if (cls_str) { - PyUnicode_AppendAndDel(&s, cls_str); - PyUnicode_AppendAndDel(&s, PyUnicode_FromString(": ")); - if (s == NULL) - goto error; - } else - PyErr_Clear(); - msg_str = PyObject_Str(v); - if (msg_str) - PyUnicode_AppendAndDel(&s, msg_str); - else { - PyErr_Clear(); - PyUnicode_AppendAndDel(&s, PyUnicode_FromString("???")); - if (s == NULL) - goto error; - } - PyErr_SetObject(exc_class, s); + va_start(vargs, fmt); + s = PyUnicode_FromFormatV(fmt, vargs); + va_end(vargs); + if (!s) + return; + + PyErr_Fetch(&tp, &v, &tb); + PyErr_NormalizeException(&tp, &v, &tb); + cls_str = PyObject_Str(tp); + if (cls_str) { + PyUnicode_AppendAndDel(&s, cls_str); + PyUnicode_AppendAndDel(&s, PyUnicode_FromString(": ")); + if (s == NULL) + goto error; + } else + PyErr_Clear(); + msg_str = PyObject_Str(v); + if (msg_str) + PyUnicode_AppendAndDel(&s, msg_str); + else { + PyErr_Clear(); + PyUnicode_AppendAndDel(&s, PyUnicode_FromString("???")); + if (s == NULL) + goto error; + } + PyErr_SetObject(exc_class, s); error: - Py_XDECREF(tp); - Py_XDECREF(v); - Py_XDECREF(tb); - Py_XDECREF(s); + Py_XDECREF(tp); + Py_XDECREF(v); + Py_XDECREF(tb); + Py_XDECREF(s); } @@ -947,73 +947,73 @@ static PyObject * GetComError(HRESULT errcode, GUID *riid, IUnknown *pIunk) { - HRESULT hr; - ISupportErrorInfo *psei = NULL; - IErrorInfo *pei = NULL; - BSTR descr=NULL, helpfile=NULL, source=NULL; - GUID guid; - DWORD helpcontext=0; - LPOLESTR progid; - PyObject *obj; - LPOLESTR text; - - /* We absolutely have to release the GIL during COM method calls, - otherwise we may get a deadlock! - */ + HRESULT hr; + ISupportErrorInfo *psei = NULL; + IErrorInfo *pei = NULL; + BSTR descr=NULL, helpfile=NULL, source=NULL; + GUID guid; + DWORD helpcontext=0; + LPOLESTR progid; + PyObject *obj; + LPOLESTR text; + + /* We absolutely have to release the GIL during COM method calls, + otherwise we may get a deadlock! + */ #ifdef WITH_THREAD - Py_BEGIN_ALLOW_THREADS + Py_BEGIN_ALLOW_THREADS #endif - hr = pIunk->lpVtbl->QueryInterface(pIunk, &IID_ISupportErrorInfo, (void **)&psei); - if (FAILED(hr)) - goto failed; + hr = pIunk->lpVtbl->QueryInterface(pIunk, &IID_ISupportErrorInfo, (void **)&psei); + if (FAILED(hr)) + goto failed; - hr = psei->lpVtbl->InterfaceSupportsErrorInfo(psei, riid); - psei->lpVtbl->Release(psei); - if (FAILED(hr)) - goto failed; + hr = psei->lpVtbl->InterfaceSupportsErrorInfo(psei, riid); + psei->lpVtbl->Release(psei); + if (FAILED(hr)) + goto failed; - hr = GetErrorInfo(0, &pei); - if (hr != S_OK) - goto failed; + hr = GetErrorInfo(0, &pei); + if (hr != S_OK) + goto failed; - pei->lpVtbl->GetDescription(pei, &descr); - pei->lpVtbl->GetGUID(pei, &guid); - pei->lpVtbl->GetHelpContext(pei, &helpcontext); - pei->lpVtbl->GetHelpFile(pei, &helpfile); - pei->lpVtbl->GetSource(pei, &source); + pei->lpVtbl->GetDescription(pei, &descr); + pei->lpVtbl->GetGUID(pei, &guid); + pei->lpVtbl->GetHelpContext(pei, &helpcontext); + pei->lpVtbl->GetHelpFile(pei, &helpfile); + pei->lpVtbl->GetSource(pei, &source); - pei->lpVtbl->Release(pei); + pei->lpVtbl->Release(pei); failed: #ifdef WITH_THREAD - Py_END_ALLOW_THREADS + Py_END_ALLOW_THREADS #endif - progid = NULL; - ProgIDFromCLSID(&guid, &progid); + progid = NULL; + ProgIDFromCLSID(&guid, &progid); - text = FormatError(errcode); - obj = Py_BuildValue( - "iu(uuuiu)", - errcode, - text, - descr, source, helpfile, helpcontext, - progid); - if (obj) { - PyErr_SetObject(ComError, obj); - Py_DECREF(obj); - } - LocalFree(text); - - if (descr) - SysFreeString(descr); - if (helpfile) - SysFreeString(helpfile); - if (source) - SysFreeString(source); + text = FormatError(errcode); + obj = Py_BuildValue( + "iu(uuuiu)", + errcode, + text, + descr, source, helpfile, helpcontext, + progid); + if (obj) { + PyErr_SetObject(ComError, obj); + Py_DECREF(obj); + } + LocalFree(text); + + if (descr) + SysFreeString(descr); + if (helpfile) + SysFreeString(helpfile); + if (source) + SysFreeString(source); - return NULL; + return NULL; } #endif @@ -1025,154 +1025,154 @@ * - XXX various requirements for restype, not yet collected */ PyObject *_ctypes_callproc(PPROC pProc, - PyObject *argtuple, + PyObject *argtuple, #ifdef MS_WIN32 - IUnknown *pIunk, - GUID *iid, + IUnknown *pIunk, + GUID *iid, #endif - int flags, - PyObject *argtypes, /* misleading name: This is a tuple of - methods, not types: the .from_param - class methods of the types */ - PyObject *restype, - PyObject *checker) -{ - Py_ssize_t i, n, argcount, argtype_count; - void *resbuf; - struct argument *args, *pa; - ffi_type **atypes; - ffi_type *rtype; - void **avalues; - PyObject *retval = NULL; + int flags, + PyObject *argtypes, /* misleading name: This is a tuple of + methods, not types: the .from_param + class methods of the types */ + PyObject *restype, + PyObject *checker) +{ + Py_ssize_t i, n, argcount, argtype_count; + void *resbuf; + struct argument *args, *pa; + ffi_type **atypes; + ffi_type *rtype; + void **avalues; + PyObject *retval = NULL; - n = argcount = PyTuple_GET_SIZE(argtuple); + n = argcount = PyTuple_GET_SIZE(argtuple); #ifdef MS_WIN32 - /* an optional COM object this pointer */ - if (pIunk) - ++argcount; + /* an optional COM object this pointer */ + if (pIunk) + ++argcount; #endif - args = (struct argument *)alloca(sizeof(struct argument) * argcount); - if (!args) { - PyErr_NoMemory(); - return NULL; - } - memset(args, 0, sizeof(struct argument) * argcount); - argtype_count = argtypes ? PyTuple_GET_SIZE(argtypes) : 0; + args = (struct argument *)alloca(sizeof(struct argument) * argcount); + if (!args) { + PyErr_NoMemory(); + return NULL; + } + memset(args, 0, sizeof(struct argument) * argcount); + argtype_count = argtypes ? PyTuple_GET_SIZE(argtypes) : 0; #ifdef MS_WIN32 - if (pIunk) { - args[0].ffi_type = &ffi_type_pointer; - args[0].value.p = pIunk; - pa = &args[1]; - } else -#endif - pa = &args[0]; - - /* Convert the arguments */ - for (i = 0; i < n; ++i, ++pa) { - PyObject *converter; - PyObject *arg; - int err; - - arg = PyTuple_GET_ITEM(argtuple, i); /* borrowed ref */ - /* For cdecl functions, we allow more actual arguments - than the length of the argtypes tuple. - This is checked in _ctypes::PyCFuncPtr_Call - */ - if (argtypes && argtype_count > i) { - PyObject *v; - converter = PyTuple_GET_ITEM(argtypes, i); - v = PyObject_CallFunctionObjArgs(converter, - arg, - NULL); - if (v == NULL) { - _ctypes_extend_error(PyExc_ArgError, "argument %d: ", i+1); - goto cleanup; - } - - err = ConvParam(v, i+1, pa); - Py_DECREF(v); - if (-1 == err) { - _ctypes_extend_error(PyExc_ArgError, "argument %d: ", i+1); - goto cleanup; - } - } else { - err = ConvParam(arg, i+1, pa); - if (-1 == err) { - _ctypes_extend_error(PyExc_ArgError, "argument %d: ", i+1); - goto cleanup; /* leaking ? */ - } - } - } - - rtype = _ctypes_get_ffi_type(restype); - resbuf = alloca(max(rtype->size, sizeof(ffi_arg))); - - avalues = (void **)alloca(sizeof(void *) * argcount); - atypes = (ffi_type **)alloca(sizeof(ffi_type *) * argcount); - if (!resbuf || !avalues || !atypes) { - PyErr_NoMemory(); - goto cleanup; - } - for (i = 0; i < argcount; ++i) { - atypes[i] = args[i].ffi_type; - if (atypes[i]->type == FFI_TYPE_STRUCT) - avalues[i] = (void *)args[i].value.p; - else - avalues[i] = (void *)&args[i].value; - } - - if (-1 == _call_function_pointer(flags, pProc, avalues, atypes, - rtype, resbuf, - Py_SAFE_DOWNCAST(argcount, - Py_ssize_t, - int))) - goto cleanup; + if (pIunk) { + args[0].ffi_type = &ffi_type_pointer; + args[0].value.p = pIunk; + pa = &args[1]; + } else +#endif + pa = &args[0]; + + /* Convert the arguments */ + for (i = 0; i < n; ++i, ++pa) { + PyObject *converter; + PyObject *arg; + int err; + + arg = PyTuple_GET_ITEM(argtuple, i); /* borrowed ref */ + /* For cdecl functions, we allow more actual arguments + than the length of the argtypes tuple. + This is checked in _ctypes::PyCFuncPtr_Call + */ + if (argtypes && argtype_count > i) { + PyObject *v; + converter = PyTuple_GET_ITEM(argtypes, i); + v = PyObject_CallFunctionObjArgs(converter, + arg, + NULL); + if (v == NULL) { + _ctypes_extend_error(PyExc_ArgError, "argument %d: ", i+1); + goto cleanup; + } + + err = ConvParam(v, i+1, pa); + Py_DECREF(v); + if (-1 == err) { + _ctypes_extend_error(PyExc_ArgError, "argument %d: ", i+1); + goto cleanup; + } + } else { + err = ConvParam(arg, i+1, pa); + if (-1 == err) { + _ctypes_extend_error(PyExc_ArgError, "argument %d: ", i+1); + goto cleanup; /* leaking ? */ + } + } + } + + rtype = _ctypes_get_ffi_type(restype); + resbuf = alloca(max(rtype->size, sizeof(ffi_arg))); + + avalues = (void **)alloca(sizeof(void *) * argcount); + atypes = (ffi_type **)alloca(sizeof(ffi_type *) * argcount); + if (!resbuf || !avalues || !atypes) { + PyErr_NoMemory(); + goto cleanup; + } + for (i = 0; i < argcount; ++i) { + atypes[i] = args[i].ffi_type; + if (atypes[i]->type == FFI_TYPE_STRUCT) + avalues[i] = (void *)args[i].value.p; + else + avalues[i] = (void *)&args[i].value; + } + + if (-1 == _call_function_pointer(flags, pProc, avalues, atypes, + rtype, resbuf, + Py_SAFE_DOWNCAST(argcount, + Py_ssize_t, + int))) + goto cleanup; #ifdef WORDS_BIGENDIAN - /* libffi returns the result in a buffer with sizeof(ffi_arg). This - causes problems on big endian machines, since the result buffer - address cannot simply be used as result pointer, instead we must - adjust the pointer value: - */ - /* - XXX I should find out and clarify why this is needed at all, - especially why adjusting for ffi_type_float must be avoided on - 64-bit platforms. - */ - if (rtype->type != FFI_TYPE_FLOAT - && rtype->type != FFI_TYPE_STRUCT - && rtype->size < sizeof(ffi_arg)) - resbuf = (char *)resbuf + sizeof(ffi_arg) - rtype->size; + /* libffi returns the result in a buffer with sizeof(ffi_arg). This + causes problems on big endian machines, since the result buffer + address cannot simply be used as result pointer, instead we must + adjust the pointer value: + */ + /* + XXX I should find out and clarify why this is needed at all, + especially why adjusting for ffi_type_float must be avoided on + 64-bit platforms. + */ + if (rtype->type != FFI_TYPE_FLOAT + && rtype->type != FFI_TYPE_STRUCT + && rtype->size < sizeof(ffi_arg)) + resbuf = (char *)resbuf + sizeof(ffi_arg) - rtype->size; #endif #ifdef MS_WIN32 - if (iid && pIunk) { - if (*(int *)resbuf & 0x80000000) - retval = GetComError(*(HRESULT *)resbuf, iid, pIunk); - else - retval = PyLong_FromLong(*(int *)resbuf); - } else if (flags & FUNCFLAG_HRESULT) { - if (*(int *)resbuf & 0x80000000) - retval = PyErr_SetFromWindowsErr(*(int *)resbuf); - else - retval = PyLong_FromLong(*(int *)resbuf); - } else + if (iid && pIunk) { + if (*(int *)resbuf & 0x80000000) + retval = GetComError(*(HRESULT *)resbuf, iid, pIunk); + else + retval = PyLong_FromLong(*(int *)resbuf); + } else if (flags & FUNCFLAG_HRESULT) { + if (*(int *)resbuf & 0x80000000) + retval = PyErr_SetFromWindowsErr(*(int *)resbuf); + else + retval = PyLong_FromLong(*(int *)resbuf); + } else #endif - retval = GetResult(restype, resbuf, checker); + retval = GetResult(restype, resbuf, checker); cleanup: - for (i = 0; i < argcount; ++i) - Py_XDECREF(args[i].keep); - return retval; + for (i = 0; i < argcount; ++i) + Py_XDECREF(args[i].keep); + return retval; } static int _parse_voidp(PyObject *obj, void **address) { - *address = PyLong_AsVoidPtr(obj); - if (*address == NULL) - return 0; - return 1; + *address = PyLong_AsVoidPtr(obj); + if (*address == NULL) + return 0; + return 1; } #ifdef MS_WIN32 @@ -1184,21 +1184,21 @@ given, the return value of a call to GetLastError() is used.\n"; static PyObject *format_error(PyObject *self, PyObject *args) { - PyObject *result; - wchar_t *lpMsgBuf; - DWORD code = 0; - if (!PyArg_ParseTuple(args, "|i:FormatError", &code)) - return NULL; - if (code == 0) - code = GetLastError(); - lpMsgBuf = FormatError(code); - if (lpMsgBuf) { - result = PyUnicode_FromWideChar(lpMsgBuf, wcslen(lpMsgBuf)); - LocalFree(lpMsgBuf); - } else { - result = PyUnicode_FromString(""); - } - return result; + PyObject *result; + wchar_t *lpMsgBuf; + DWORD code = 0; + if (!PyArg_ParseTuple(args, "|i:FormatError", &code)) + return NULL; + if (code == 0) + code = GetLastError(); + lpMsgBuf = FormatError(code); + if (lpMsgBuf) { + result = PyUnicode_FromWideChar(lpMsgBuf, wcslen(lpMsgBuf)); + LocalFree(lpMsgBuf); + } else { + result = PyUnicode_FromString(""); + } + return result; } static char load_library_doc[] = @@ -1209,24 +1209,24 @@ module.\n"; static PyObject *load_library(PyObject *self, PyObject *args) { - WCHAR *name; - PyObject *nameobj; - PyObject *ignored; - HMODULE hMod; - if (!PyArg_ParseTuple(args, "O|O:LoadLibrary", &nameobj, &ignored)) - return NULL; - - name = PyUnicode_AsUnicode(nameobj); - if (!name) - return NULL; - - hMod = LoadLibraryW(name); - if (!hMod) - return PyErr_SetFromWindowsErr(GetLastError()); + WCHAR *name; + PyObject *nameobj; + PyObject *ignored; + HMODULE hMod; + if (!PyArg_ParseTuple(args, "O|O:LoadLibrary", &nameobj, &ignored)) + return NULL; + + name = PyUnicode_AsUnicode(nameobj); + if (!name) + return NULL; + + hMod = LoadLibraryW(name); + if (!hMod) + return PyErr_SetFromWindowsErr(GetLastError()); #ifdef _WIN64 - return PyLong_FromVoidPtr(hMod); + return PyLong_FromVoidPtr(hMod); #else - return Py_BuildValue("i", hMod); + return Py_BuildValue("i", hMod); #endif } @@ -1236,13 +1236,13 @@ Free the handle of an executable previously loaded by LoadLibrary.\n"; static PyObject *free_library(PyObject *self, PyObject *args) { - void *hMod; - if (!PyArg_ParseTuple(args, "O&:FreeLibrary", &_parse_voidp, &hMod)) - return NULL; - if (!FreeLibrary((HMODULE)hMod)) - return PyErr_SetFromWindowsErr(GetLastError()); - Py_INCREF(Py_None); - return Py_None; + void *hMod; + if (!PyArg_ParseTuple(args, "O&:FreeLibrary", &_parse_voidp, &hMod)) + return NULL; + if (!FreeLibrary((HMODULE)hMod)) + return PyErr_SetFromWindowsErr(GetLastError()); + Py_INCREF(Py_None); + return Py_None; } /* obsolete, should be removed */ @@ -1250,55 +1250,55 @@ static PyObject * call_commethod(PyObject *self, PyObject *args) { - IUnknown *pIunk; - int index; - PyObject *arguments; - PPROC *lpVtbl; - PyObject *result; - CDataObject *pcom; - PyObject *argtypes = NULL; - - if (!PyArg_ParseTuple(args, - "OiO!|O!", - &pcom, &index, - &PyTuple_Type, &arguments, - &PyTuple_Type, &argtypes)) - return NULL; - - if (argtypes && (PyTuple_GET_SIZE(arguments) != PyTuple_GET_SIZE(argtypes))) { - PyErr_Format(PyExc_TypeError, - "Method takes %d arguments (%d given)", - PyTuple_GET_SIZE(argtypes), PyTuple_GET_SIZE(arguments)); - return NULL; - } - - if (!CDataObject_Check(pcom) || (pcom->b_size != sizeof(void *))) { - PyErr_Format(PyExc_TypeError, - "COM Pointer expected instead of %s instance", - Py_TYPE(pcom)->tp_name); - return NULL; - } - - if ((*(void **)(pcom->b_ptr)) == NULL) { - PyErr_SetString(PyExc_ValueError, - "The COM 'this' pointer is NULL"); - return NULL; - } + IUnknown *pIunk; + int index; + PyObject *arguments; + PPROC *lpVtbl; + PyObject *result; + CDataObject *pcom; + PyObject *argtypes = NULL; + + if (!PyArg_ParseTuple(args, + "OiO!|O!", + &pcom, &index, + &PyTuple_Type, &arguments, + &PyTuple_Type, &argtypes)) + return NULL; + + if (argtypes && (PyTuple_GET_SIZE(arguments) != PyTuple_GET_SIZE(argtypes))) { + PyErr_Format(PyExc_TypeError, + "Method takes %d arguments (%d given)", + PyTuple_GET_SIZE(argtypes), PyTuple_GET_SIZE(arguments)); + return NULL; + } + + if (!CDataObject_Check(pcom) || (pcom->b_size != sizeof(void *))) { + PyErr_Format(PyExc_TypeError, + "COM Pointer expected instead of %s instance", + Py_TYPE(pcom)->tp_name); + return NULL; + } + + if ((*(void **)(pcom->b_ptr)) == NULL) { + PyErr_SetString(PyExc_ValueError, + "The COM 'this' pointer is NULL"); + return NULL; + } - pIunk = (IUnknown *)(*(void **)(pcom->b_ptr)); - lpVtbl = (PPROC *)(pIunk->lpVtbl); + pIunk = (IUnknown *)(*(void **)(pcom->b_ptr)); + lpVtbl = (PPROC *)(pIunk->lpVtbl); - result = _ctypes_callproc(lpVtbl[index], - arguments, + result = _ctypes_callproc(lpVtbl[index], + arguments, #ifdef MS_WIN32 - pIunk, - NULL, + pIunk, + NULL, #endif - FUNCFLAG_HRESULT, /* flags */ - argtypes, /* self->argtypes */ - NULL, /* self->restype */ - NULL); /* checker */ - return result; + FUNCFLAG_HRESULT, /* flags */ + argtypes, /* self->argtypes */ + NULL, /* self->restype */ + NULL); /* checker */ + return result; } static char copy_com_pointer_doc[] = @@ -1307,102 +1307,102 @@ static PyObject * copy_com_pointer(PyObject *self, PyObject *args) { - PyObject *p1, *p2, *r = NULL; - struct argument a, b; - IUnknown *src, **pdst; - if (!PyArg_ParseTuple(args, "OO:CopyComPointer", &p1, &p2)) - return NULL; - a.keep = b.keep = NULL; - - if (-1 == ConvParam(p1, 0, &a) || -1 == ConvParam(p2, 1, &b)) - goto done; - src = (IUnknown *)a.value.p; - pdst = (IUnknown **)b.value.p; - - if (pdst == NULL) - r = PyLong_FromLong(E_POINTER); - else { - if (src) - src->lpVtbl->AddRef(src); - *pdst = src; - r = PyLong_FromLong(S_OK); - } + PyObject *p1, *p2, *r = NULL; + struct argument a, b; + IUnknown *src, **pdst; + if (!PyArg_ParseTuple(args, "OO:CopyComPointer", &p1, &p2)) + return NULL; + a.keep = b.keep = NULL; + + if (-1 == ConvParam(p1, 0, &a) || -1 == ConvParam(p2, 1, &b)) + goto done; + src = (IUnknown *)a.value.p; + pdst = (IUnknown **)b.value.p; + + if (pdst == NULL) + r = PyLong_FromLong(E_POINTER); + else { + if (src) + src->lpVtbl->AddRef(src); + *pdst = src; + r = PyLong_FromLong(S_OK); + } done: - Py_XDECREF(a.keep); - Py_XDECREF(b.keep); - return r; + Py_XDECREF(a.keep); + Py_XDECREF(b.keep); + return r; } #else static PyObject *py_dl_open(PyObject *self, PyObject *args) { - PyObject *name, *name2; - char *name_str; - void * handle; -#ifdef RTLD_LOCAL - int mode = RTLD_NOW | RTLD_LOCAL; + PyObject *name, *name2; + char *name_str; + void * handle; +#ifdef RTLD_LOCAL + int mode = RTLD_NOW | RTLD_LOCAL; #else - /* cygwin doesn't define RTLD_LOCAL */ - int mode = RTLD_NOW; + /* cygwin doesn't define RTLD_LOCAL */ + int mode = RTLD_NOW; #endif - if (!PyArg_ParseTuple(args, "O|i:dlopen", &name, &mode)) - return NULL; - mode |= RTLD_NOW; - if (name != Py_None) { - if (PyUnicode_FSConverter(name, &name2) == 0) - return NULL; - if (PyBytes_Check(name2)) - name_str = PyBytes_AS_STRING(name2); - else - name_str = PyByteArray_AS_STRING(name2); - } else { - name_str = NULL; - name2 = NULL; - } - handle = ctypes_dlopen(name_str, mode); - Py_XDECREF(name2); - if (!handle) { - char *errmsg = ctypes_dlerror(); - if (!errmsg) - errmsg = "dlopen() error"; - PyErr_SetString(PyExc_OSError, - errmsg); - return NULL; - } - return PyLong_FromVoidPtr(handle); + if (!PyArg_ParseTuple(args, "O|i:dlopen", &name, &mode)) + return NULL; + mode |= RTLD_NOW; + if (name != Py_None) { + if (PyUnicode_FSConverter(name, &name2) == 0) + return NULL; + if (PyBytes_Check(name2)) + name_str = PyBytes_AS_STRING(name2); + else + name_str = PyByteArray_AS_STRING(name2); + } else { + name_str = NULL; + name2 = NULL; + } + handle = ctypes_dlopen(name_str, mode); + Py_XDECREF(name2); + if (!handle) { + char *errmsg = ctypes_dlerror(); + if (!errmsg) + errmsg = "dlopen() error"; + PyErr_SetString(PyExc_OSError, + errmsg); + return NULL; + } + return PyLong_FromVoidPtr(handle); } static PyObject *py_dl_close(PyObject *self, PyObject *args) { - void *handle; + void *handle; - if (!PyArg_ParseTuple(args, "O&:dlclose", &_parse_voidp, &handle)) - return NULL; - if (dlclose(handle)) { - PyErr_SetString(PyExc_OSError, - ctypes_dlerror()); - return NULL; - } - Py_INCREF(Py_None); - return Py_None; + if (!PyArg_ParseTuple(args, "O&:dlclose", &_parse_voidp, &handle)) + return NULL; + if (dlclose(handle)) { + PyErr_SetString(PyExc_OSError, + ctypes_dlerror()); + return NULL; + } + Py_INCREF(Py_None); + return Py_None; } static PyObject *py_dl_sym(PyObject *self, PyObject *args) { - char *name; - void *handle; - void *ptr; - - if (!PyArg_ParseTuple(args, "O&s:dlsym", - &_parse_voidp, &handle, &name)) - return NULL; - ptr = ctypes_dlsym((void*)handle, name); - if (!ptr) { - PyErr_SetString(PyExc_OSError, - ctypes_dlerror()); - return NULL; - } - return PyLong_FromVoidPtr(ptr); + char *name; + void *handle; + void *ptr; + + if (!PyArg_ParseTuple(args, "O&s:dlsym", + &_parse_voidp, &handle, &name)) + return NULL; + ptr = ctypes_dlsym((void*)handle, name); + if (!ptr) { + PyErr_SetString(PyExc_OSError, + ctypes_dlerror()); + return NULL; + } + return PyLong_FromVoidPtr(ptr); } #endif @@ -1414,27 +1414,27 @@ static PyObject * call_function(PyObject *self, PyObject *args) { - void *func; - PyObject *arguments; - PyObject *result; - - if (!PyArg_ParseTuple(args, - "O&O!", - &_parse_voidp, &func, - &PyTuple_Type, &arguments)) - return NULL; + void *func; + PyObject *arguments; + PyObject *result; + + if (!PyArg_ParseTuple(args, + "O&O!", + &_parse_voidp, &func, + &PyTuple_Type, &arguments)) + return NULL; - result = _ctypes_callproc((PPROC)func, - arguments, + result = _ctypes_callproc((PPROC)func, + arguments, #ifdef MS_WIN32 - NULL, - NULL, + NULL, + NULL, #endif - 0, /* flags */ - NULL, /* self->argtypes */ - NULL, /* self->restype */ - NULL); /* checker */ - return result; + 0, /* flags */ + NULL, /* self->argtypes */ + NULL, /* self->restype */ + NULL); /* checker */ + return result; } /* @@ -1445,27 +1445,27 @@ static PyObject * call_cdeclfunction(PyObject *self, PyObject *args) { - void *func; - PyObject *arguments; - PyObject *result; - - if (!PyArg_ParseTuple(args, - "O&O!", - &_parse_voidp, &func, - &PyTuple_Type, &arguments)) - return NULL; + void *func; + PyObject *arguments; + PyObject *result; + + if (!PyArg_ParseTuple(args, + "O&O!", + &_parse_voidp, &func, + &PyTuple_Type, &arguments)) + return NULL; - result = _ctypes_callproc((PPROC)func, - arguments, + result = _ctypes_callproc((PPROC)func, + arguments, #ifdef MS_WIN32 - NULL, - NULL, + NULL, + NULL, #endif - FUNCFLAG_CDECL, /* flags */ - NULL, /* self->argtypes */ - NULL, /* self->restype */ - NULL); /* checker */ - return result; + FUNCFLAG_CDECL, /* flags */ + NULL, /* self->argtypes */ + NULL, /* self->restype */ + NULL); /* checker */ + return result; } /***************************************************************** @@ -1479,17 +1479,17 @@ static PyObject * sizeof_func(PyObject *self, PyObject *obj) { - StgDictObject *dict; + StgDictObject *dict; - dict = PyType_stgdict(obj); - if (dict) - return PyLong_FromSsize_t(dict->size); - - if (CDataObject_Check(obj)) - return PyLong_FromSsize_t(((CDataObject *)obj)->b_size); - PyErr_SetString(PyExc_TypeError, - "this type has no size"); - return NULL; + dict = PyType_stgdict(obj); + if (dict) + return PyLong_FromSsize_t(dict->size); + + if (CDataObject_Check(obj)) + return PyLong_FromSsize_t(((CDataObject *)obj)->b_size); + PyErr_SetString(PyExc_TypeError, + "this type has no size"); + return NULL; } static char alignment_doc[] = @@ -1500,19 +1500,19 @@ static PyObject * align_func(PyObject *self, PyObject *obj) { - StgDictObject *dict; + StgDictObject *dict; - dict = PyType_stgdict(obj); - if (dict) - return PyLong_FromSsize_t(dict->align); - - dict = PyObject_stgdict(obj); - if (dict) - return PyLong_FromSsize_t(dict->align); - - PyErr_SetString(PyExc_TypeError, - "no alignment info"); - return NULL; + dict = PyType_stgdict(obj); + if (dict) + return PyLong_FromSsize_t(dict->align); + + dict = PyObject_stgdict(obj); + if (dict) + return PyLong_FromSsize_t(dict->align); + + PyErr_SetString(PyExc_TypeError, + "no alignment info"); + return NULL; } static char byref_doc[] = @@ -1527,36 +1527,36 @@ static PyObject * byref(PyObject *self, PyObject *args) { - PyCArgObject *parg; - PyObject *obj; - PyObject *pyoffset = NULL; - Py_ssize_t offset = 0; - - if (!PyArg_UnpackTuple(args, "byref", 1, 2, - &obj, &pyoffset)) - return NULL; - if (pyoffset) { - offset = PyNumber_AsSsize_t(pyoffset, NULL); - if (offset == -1 && PyErr_Occurred()) - return NULL; - } - if (!CDataObject_Check(obj)) { - PyErr_Format(PyExc_TypeError, - "byref() argument must be a ctypes instance, not '%s'", - Py_TYPE(obj)->tp_name); - return NULL; - } - - parg = PyCArgObject_new(); - if (parg == NULL) - return NULL; - - parg->tag = 'P'; - parg->pffi_type = &ffi_type_pointer; - Py_INCREF(obj); - parg->obj = obj; - parg->value.p = (char *)((CDataObject *)obj)->b_ptr + offset; - return (PyObject *)parg; + PyCArgObject *parg; + PyObject *obj; + PyObject *pyoffset = NULL; + Py_ssize_t offset = 0; + + if (!PyArg_UnpackTuple(args, "byref", 1, 2, + &obj, &pyoffset)) + return NULL; + if (pyoffset) { + offset = PyNumber_AsSsize_t(pyoffset, NULL); + if (offset == -1 && PyErr_Occurred()) + return NULL; + } + if (!CDataObject_Check(obj)) { + PyErr_Format(PyExc_TypeError, + "byref() argument must be a ctypes instance, not '%s'", + Py_TYPE(obj)->tp_name); + return NULL; + } + + parg = PyCArgObject_new(); + if (parg == NULL) + return NULL; + + parg->tag = 'P'; + parg->pffi_type = &ffi_type_pointer; + Py_INCREF(obj); + parg->obj = obj; + parg->value.p = (char *)((CDataObject *)obj)->b_ptr + offset; + return (PyObject *)parg; } static char addressof_doc[] = @@ -1566,44 +1566,44 @@ static PyObject * addressof(PyObject *self, PyObject *obj) { - if (CDataObject_Check(obj)) - return PyLong_FromVoidPtr(((CDataObject *)obj)->b_ptr); - PyErr_SetString(PyExc_TypeError, - "invalid type"); - return NULL; + if (CDataObject_Check(obj)) + return PyLong_FromVoidPtr(((CDataObject *)obj)->b_ptr); + PyErr_SetString(PyExc_TypeError, + "invalid type"); + return NULL; } static int converter(PyObject *obj, void **address) { - *address = PyLong_AsVoidPtr(obj); - return *address != NULL; + *address = PyLong_AsVoidPtr(obj); + return *address != NULL; } static PyObject * My_PyObj_FromPtr(PyObject *self, PyObject *args) { - PyObject *ob; - if (!PyArg_ParseTuple(args, "O&:PyObj_FromPtr", converter, &ob)) - return NULL; - Py_INCREF(ob); - return ob; + PyObject *ob; + if (!PyArg_ParseTuple(args, "O&:PyObj_FromPtr", converter, &ob)) + return NULL; + Py_INCREF(ob); + return ob; } static PyObject * My_Py_INCREF(PyObject *self, PyObject *arg) { - Py_INCREF(arg); /* that's what this function is for */ - Py_INCREF(arg); /* that for returning it */ - return arg; + Py_INCREF(arg); /* that's what this function is for */ + Py_INCREF(arg); /* that for returning it */ + return arg; } static PyObject * My_Py_DECREF(PyObject *self, PyObject *arg) { - Py_DECREF(arg); /* that's what this function is for */ - Py_INCREF(arg); /* that's for returning it */ - return arg; + Py_DECREF(arg); /* that's what this function is for */ + Py_INCREF(arg); /* that's for returning it */ + return arg; } #ifdef CTYPES_UNICODE @@ -1617,234 +1617,234 @@ static PyObject * set_conversion_mode(PyObject *self, PyObject *args) { - char *coding, *mode; - PyObject *result; + char *coding, *mode; + PyObject *result; - if (!PyArg_ParseTuple(args, "zs:set_conversion_mode", &coding, &mode)) - return NULL; - result = Py_BuildValue("(zz)", _ctypes_conversion_encoding, _ctypes_conversion_errors); - if (coding) { - PyMem_Free(_ctypes_conversion_encoding); - _ctypes_conversion_encoding = PyMem_Malloc(strlen(coding) + 1); - strcpy(_ctypes_conversion_encoding, coding); - } else { - _ctypes_conversion_encoding = NULL; - } - PyMem_Free(_ctypes_conversion_errors); - _ctypes_conversion_errors = PyMem_Malloc(strlen(mode) + 1); - strcpy(_ctypes_conversion_errors, mode); - return result; + if (!PyArg_ParseTuple(args, "zs:set_conversion_mode", &coding, &mode)) + return NULL; + result = Py_BuildValue("(zz)", _ctypes_conversion_encoding, _ctypes_conversion_errors); + if (coding) { + PyMem_Free(_ctypes_conversion_encoding); + _ctypes_conversion_encoding = PyMem_Malloc(strlen(coding) + 1); + strcpy(_ctypes_conversion_encoding, coding); + } else { + _ctypes_conversion_encoding = NULL; + } + PyMem_Free(_ctypes_conversion_errors); + _ctypes_conversion_errors = PyMem_Malloc(strlen(mode) + 1); + strcpy(_ctypes_conversion_errors, mode); + return result; } #endif static PyObject * resize(PyObject *self, PyObject *args) { - CDataObject *obj; - StgDictObject *dict; - Py_ssize_t size; - - if (!PyArg_ParseTuple(args, - "On:resize", - &obj, &size)) - return NULL; - - dict = PyObject_stgdict((PyObject *)obj); - if (dict == NULL) { - PyErr_SetString(PyExc_TypeError, - "excepted ctypes instance"); - return NULL; - } - if (size < dict->size) { - PyErr_Format(PyExc_ValueError, - "minimum size is %zd", - dict->size); - return NULL; - } - if (obj->b_needsfree == 0) { - PyErr_Format(PyExc_ValueError, - "Memory cannot be resized because this object doesn't own it"); - return NULL; - } - if (size <= sizeof(obj->b_value)) { - /* internal default buffer is large enough */ - obj->b_size = size; - goto done; - } - if (obj->b_size <= sizeof(obj->b_value)) { - /* We are currently using the objects default buffer, but it - isn't large enough any more. */ - void *ptr = PyMem_Malloc(size); - if (ptr == NULL) - return PyErr_NoMemory(); - memset(ptr, 0, size); - memmove(ptr, obj->b_ptr, obj->b_size); - obj->b_ptr = ptr; - obj->b_size = size; - } else { - void * ptr = PyMem_Realloc(obj->b_ptr, size); - if (ptr == NULL) - return PyErr_NoMemory(); - obj->b_ptr = ptr; - obj->b_size = size; - } + CDataObject *obj; + StgDictObject *dict; + Py_ssize_t size; + + if (!PyArg_ParseTuple(args, + "On:resize", + &obj, &size)) + return NULL; + + dict = PyObject_stgdict((PyObject *)obj); + if (dict == NULL) { + PyErr_SetString(PyExc_TypeError, + "excepted ctypes instance"); + return NULL; + } + if (size < dict->size) { + PyErr_Format(PyExc_ValueError, + "minimum size is %zd", + dict->size); + return NULL; + } + if (obj->b_needsfree == 0) { + PyErr_Format(PyExc_ValueError, + "Memory cannot be resized because this object doesn't own it"); + return NULL; + } + if (size <= sizeof(obj->b_value)) { + /* internal default buffer is large enough */ + obj->b_size = size; + goto done; + } + if (obj->b_size <= sizeof(obj->b_value)) { + /* We are currently using the objects default buffer, but it + isn't large enough any more. */ + void *ptr = PyMem_Malloc(size); + if (ptr == NULL) + return PyErr_NoMemory(); + memset(ptr, 0, size); + memmove(ptr, obj->b_ptr, obj->b_size); + obj->b_ptr = ptr; + obj->b_size = size; + } else { + void * ptr = PyMem_Realloc(obj->b_ptr, size); + if (ptr == NULL) + return PyErr_NoMemory(); + obj->b_ptr = ptr; + obj->b_size = size; + } done: - Py_INCREF(Py_None); - return Py_None; + Py_INCREF(Py_None); + return Py_None; } static PyObject * unpickle(PyObject *self, PyObject *args) { - PyObject *typ; - PyObject *state; - PyObject *result; - PyObject *tmp; - - if (!PyArg_ParseTuple(args, "OO", &typ, &state)) - return NULL; - result = PyObject_CallMethod(typ, "__new__", "O", typ); - if (result == NULL) - return NULL; - tmp = PyObject_CallMethod(result, "__setstate__", "O", state); - if (tmp == NULL) { - Py_DECREF(result); - return NULL; - } - Py_DECREF(tmp); - return result; + PyObject *typ; + PyObject *state; + PyObject *result; + PyObject *tmp; + + if (!PyArg_ParseTuple(args, "OO", &typ, &state)) + return NULL; + result = PyObject_CallMethod(typ, "__new__", "O", typ); + if (result == NULL) + return NULL; + tmp = PyObject_CallMethod(result, "__setstate__", "O", state); + if (tmp == NULL) { + Py_DECREF(result); + return NULL; + } + Py_DECREF(tmp); + return result; } static PyObject * POINTER(PyObject *self, PyObject *cls) { - PyObject *result; - PyTypeObject *typ; - PyObject *key; - char *buf; - - result = PyDict_GetItem(_ctypes_ptrtype_cache, cls); - if (result) { - Py_INCREF(result); - return result; - } - if (PyUnicode_CheckExact(cls)) { - char *name = _PyUnicode_AsString(cls); - buf = alloca(strlen(name) + 3 + 1); - sprintf(buf, "LP_%s", name); - result = PyObject_CallFunction((PyObject *)Py_TYPE(&PyCPointer_Type), - "s(O){}", - buf, - &PyCPointer_Type); - if (result == NULL) - return result; - key = PyLong_FromVoidPtr(result); - } else if (PyType_Check(cls)) { - typ = (PyTypeObject *)cls; - buf = alloca(strlen(typ->tp_name) + 3 + 1); - sprintf(buf, "LP_%s", typ->tp_name); - result = PyObject_CallFunction((PyObject *)Py_TYPE(&PyCPointer_Type), - "s(O){sO}", - buf, - &PyCPointer_Type, - "_type_", cls); - if (result == NULL) - return result; - Py_INCREF(cls); - key = cls; - } else { - PyErr_SetString(PyExc_TypeError, "must be a ctypes type"); - return NULL; - } - if (-1 == PyDict_SetItem(_ctypes_ptrtype_cache, key, result)) { - Py_DECREF(result); - Py_DECREF(key); - return NULL; - } - Py_DECREF(key); - return result; + PyObject *result; + PyTypeObject *typ; + PyObject *key; + char *buf; + + result = PyDict_GetItem(_ctypes_ptrtype_cache, cls); + if (result) { + Py_INCREF(result); + return result; + } + if (PyUnicode_CheckExact(cls)) { + char *name = _PyUnicode_AsString(cls); + buf = alloca(strlen(name) + 3 + 1); + sprintf(buf, "LP_%s", name); + result = PyObject_CallFunction((PyObject *)Py_TYPE(&PyCPointer_Type), + "s(O){}", + buf, + &PyCPointer_Type); + if (result == NULL) + return result; + key = PyLong_FromVoidPtr(result); + } else if (PyType_Check(cls)) { + typ = (PyTypeObject *)cls; + buf = alloca(strlen(typ->tp_name) + 3 + 1); + sprintf(buf, "LP_%s", typ->tp_name); + result = PyObject_CallFunction((PyObject *)Py_TYPE(&PyCPointer_Type), + "s(O){sO}", + buf, + &PyCPointer_Type, + "_type_", cls); + if (result == NULL) + return result; + Py_INCREF(cls); + key = cls; + } else { + PyErr_SetString(PyExc_TypeError, "must be a ctypes type"); + return NULL; + } + if (-1 == PyDict_SetItem(_ctypes_ptrtype_cache, key, result)) { + Py_DECREF(result); + Py_DECREF(key); + return NULL; + } + Py_DECREF(key); + return result; } static PyObject * pointer(PyObject *self, PyObject *arg) { - PyObject *result; - PyObject *typ; + PyObject *result; + PyObject *typ; - typ = PyDict_GetItem(_ctypes_ptrtype_cache, (PyObject *)Py_TYPE(arg)); - if (typ) - return PyObject_CallFunctionObjArgs(typ, arg, NULL); - typ = POINTER(NULL, (PyObject *)Py_TYPE(arg)); - if (typ == NULL) - return NULL; - result = PyObject_CallFunctionObjArgs(typ, arg, NULL); - Py_DECREF(typ); - return result; + typ = PyDict_GetItem(_ctypes_ptrtype_cache, (PyObject *)Py_TYPE(arg)); + if (typ) + return PyObject_CallFunctionObjArgs(typ, arg, NULL); + typ = POINTER(NULL, (PyObject *)Py_TYPE(arg)); + if (typ == NULL) + return NULL; + result = PyObject_CallFunctionObjArgs(typ, arg, NULL); + Py_DECREF(typ); + return result; } static PyObject * buffer_info(PyObject *self, PyObject *arg) { - StgDictObject *dict = PyType_stgdict(arg); - PyObject *shape; - Py_ssize_t i; - - if (dict == NULL) - dict = PyObject_stgdict(arg); - if (dict == NULL) { - PyErr_SetString(PyExc_TypeError, - "not a ctypes type or object"); - return NULL; - } - shape = PyTuple_New(dict->ndim); - if (shape == NULL) - return NULL; - for (i = 0; i < (int)dict->ndim; ++i) - PyTuple_SET_ITEM(shape, i, PyLong_FromSsize_t(dict->shape[i])); - - if (PyErr_Occurred()) { - Py_DECREF(shape); - return NULL; - } - return Py_BuildValue("siN", dict->format, dict->ndim, shape); + StgDictObject *dict = PyType_stgdict(arg); + PyObject *shape; + Py_ssize_t i; + + if (dict == NULL) + dict = PyObject_stgdict(arg); + if (dict == NULL) { + PyErr_SetString(PyExc_TypeError, + "not a ctypes type or object"); + return NULL; + } + shape = PyTuple_New(dict->ndim); + if (shape == NULL) + return NULL; + for (i = 0; i < (int)dict->ndim; ++i) + PyTuple_SET_ITEM(shape, i, PyLong_FromSsize_t(dict->shape[i])); + + if (PyErr_Occurred()) { + Py_DECREF(shape); + return NULL; + } + return Py_BuildValue("siN", dict->format, dict->ndim, shape); } PyMethodDef _ctypes_module_methods[] = { - {"get_errno", get_errno, METH_NOARGS}, - {"set_errno", set_errno, METH_VARARGS}, - {"POINTER", POINTER, METH_O }, - {"pointer", pointer, METH_O }, - {"_unpickle", unpickle, METH_VARARGS }, - {"buffer_info", buffer_info, METH_O, "Return buffer interface information"}, - {"resize", resize, METH_VARARGS, "Resize the memory buffer of a ctypes instance"}, + {"get_errno", get_errno, METH_NOARGS}, + {"set_errno", set_errno, METH_VARARGS}, + {"POINTER", POINTER, METH_O }, + {"pointer", pointer, METH_O }, + {"_unpickle", unpickle, METH_VARARGS }, + {"buffer_info", buffer_info, METH_O, "Return buffer interface information"}, + {"resize", resize, METH_VARARGS, "Resize the memory buffer of a ctypes instance"}, #ifdef CTYPES_UNICODE - {"set_conversion_mode", set_conversion_mode, METH_VARARGS, set_conversion_mode_doc}, + {"set_conversion_mode", set_conversion_mode, METH_VARARGS, set_conversion_mode_doc}, #endif #ifdef MS_WIN32 - {"get_last_error", get_last_error, METH_NOARGS}, - {"set_last_error", set_last_error, METH_VARARGS}, - {"CopyComPointer", copy_com_pointer, METH_VARARGS, copy_com_pointer_doc}, - {"FormatError", format_error, METH_VARARGS, format_error_doc}, - {"LoadLibrary", load_library, METH_VARARGS, load_library_doc}, - {"FreeLibrary", free_library, METH_VARARGS, free_library_doc}, - {"call_commethod", call_commethod, METH_VARARGS }, - {"_check_HRESULT", check_hresult, METH_VARARGS}, + {"get_last_error", get_last_error, METH_NOARGS}, + {"set_last_error", set_last_error, METH_VARARGS}, + {"CopyComPointer", copy_com_pointer, METH_VARARGS, copy_com_pointer_doc}, + {"FormatError", format_error, METH_VARARGS, format_error_doc}, + {"LoadLibrary", load_library, METH_VARARGS, load_library_doc}, + {"FreeLibrary", free_library, METH_VARARGS, free_library_doc}, + {"call_commethod", call_commethod, METH_VARARGS }, + {"_check_HRESULT", check_hresult, METH_VARARGS}, #else - {"dlopen", py_dl_open, METH_VARARGS, - "dlopen(name, flag={RTLD_GLOBAL|RTLD_LOCAL}) open a shared library"}, - {"dlclose", py_dl_close, METH_VARARGS, "dlclose a library"}, - {"dlsym", py_dl_sym, METH_VARARGS, "find symbol in shared library"}, -#endif - {"alignment", align_func, METH_O, alignment_doc}, - {"sizeof", sizeof_func, METH_O, sizeof_doc}, - {"byref", byref, METH_VARARGS, byref_doc}, - {"addressof", addressof, METH_O, addressof_doc}, - {"call_function", call_function, METH_VARARGS }, - {"call_cdeclfunction", call_cdeclfunction, METH_VARARGS }, - {"PyObj_FromPtr", My_PyObj_FromPtr, METH_VARARGS }, - {"Py_INCREF", My_Py_INCREF, METH_O }, - {"Py_DECREF", My_Py_DECREF, METH_O }, - {NULL, NULL} /* Sentinel */ + {"dlopen", py_dl_open, METH_VARARGS, + "dlopen(name, flag={RTLD_GLOBAL|RTLD_LOCAL}) open a shared library"}, + {"dlclose", py_dl_close, METH_VARARGS, "dlclose a library"}, + {"dlsym", py_dl_sym, METH_VARARGS, "find symbol in shared library"}, +#endif + {"alignment", align_func, METH_O, alignment_doc}, + {"sizeof", sizeof_func, METH_O, sizeof_doc}, + {"byref", byref, METH_VARARGS, byref_doc}, + {"addressof", addressof, METH_O, addressof_doc}, + {"call_function", call_function, METH_VARARGS }, + {"call_cdeclfunction", call_cdeclfunction, METH_VARARGS }, + {"PyObj_FromPtr", My_PyObj_FromPtr, METH_VARARGS }, + {"Py_INCREF", My_Py_INCREF, METH_O }, + {"Py_DECREF", My_Py_DECREF, METH_O }, + {NULL, NULL} /* Sentinel */ }; /* Modified: python/branches/py3k/Modules/_ctypes/cfield.c ============================================================================== --- python/branches/py3k/Modules/_ctypes/cfield.c (original) +++ python/branches/py3k/Modules/_ctypes/cfield.c Sun May 9 17:52:27 2010 @@ -11,10 +11,10 @@ static void pymem_destructor(PyObject *ptr) { - void *p = PyCapsule_GetPointer(ptr, CTYPES_CFIELD_CAPSULE_NAME_PYMEM); - if (p) { - PyMem_Free(p); - } + void *p = PyCapsule_GetPointer(ptr, CTYPES_CFIELD_CAPSULE_NAME_PYMEM); + if (p) { + PyMem_Free(p); + } } @@ -25,9 +25,9 @@ static PyObject * PyCField_new(PyTypeObject *type, PyObject *args, PyObject *kwds) { - CFieldObject *obj; - obj = (CFieldObject *)type->tp_alloc(type, 0); - return (PyObject *)obj; + CFieldObject *obj; + obj = (CFieldObject *)type->tp_alloc(type, 0); + return (PyObject *)obj; } /* @@ -44,297 +44,297 @@ */ PyObject * PyCField_FromDesc(PyObject *desc, Py_ssize_t index, - Py_ssize_t *pfield_size, int bitsize, int *pbitofs, - Py_ssize_t *psize, Py_ssize_t *poffset, Py_ssize_t *palign, - int pack, int big_endian) -{ - CFieldObject *self; - PyObject *proto; - Py_ssize_t size, align, length; - SETFUNC setfunc = NULL; - GETFUNC getfunc = NULL; - StgDictObject *dict; - int fieldtype; + Py_ssize_t *pfield_size, int bitsize, int *pbitofs, + Py_ssize_t *psize, Py_ssize_t *poffset, Py_ssize_t *palign, + int pack, int big_endian) +{ + CFieldObject *self; + PyObject *proto; + Py_ssize_t size, align, length; + SETFUNC setfunc = NULL; + GETFUNC getfunc = NULL; + StgDictObject *dict; + int fieldtype; #define NO_BITFIELD 0 #define NEW_BITFIELD 1 #define CONT_BITFIELD 2 #define EXPAND_BITFIELD 3 - self = (CFieldObject *)PyObject_CallObject((PyObject *)&PyCField_Type, - NULL); - if (self == NULL) - return NULL; - dict = PyType_stgdict(desc); - if (!dict) { - PyErr_SetString(PyExc_TypeError, - "has no _stginfo_"); - Py_DECREF(self); - return NULL; - } - if (bitsize /* this is a bitfield request */ - && *pfield_size /* we have a bitfield open */ + self = (CFieldObject *)PyObject_CallObject((PyObject *)&PyCField_Type, + NULL); + if (self == NULL) + return NULL; + dict = PyType_stgdict(desc); + if (!dict) { + PyErr_SetString(PyExc_TypeError, + "has no _stginfo_"); + Py_DECREF(self); + return NULL; + } + if (bitsize /* this is a bitfield request */ + && *pfield_size /* we have a bitfield open */ #ifdef MS_WIN32 - /* MSVC, GCC with -mms-bitfields */ - && dict->size * 8 == *pfield_size + /* MSVC, GCC with -mms-bitfields */ + && dict->size * 8 == *pfield_size #else - /* GCC */ - && dict->size * 8 <= *pfield_size + /* GCC */ + && dict->size * 8 <= *pfield_size #endif - && (*pbitofs + bitsize) <= *pfield_size) { - /* continue bit field */ - fieldtype = CONT_BITFIELD; + && (*pbitofs + bitsize) <= *pfield_size) { + /* continue bit field */ + fieldtype = CONT_BITFIELD; #ifndef MS_WIN32 - } else if (bitsize /* this is a bitfield request */ - && *pfield_size /* we have a bitfield open */ - && dict->size * 8 >= *pfield_size - && (*pbitofs + bitsize) <= dict->size * 8) { - /* expand bit field */ - fieldtype = EXPAND_BITFIELD; -#endif - } else if (bitsize) { - /* start new bitfield */ - fieldtype = NEW_BITFIELD; - *pbitofs = 0; - *pfield_size = dict->size * 8; - } else { - /* not a bit field */ - fieldtype = NO_BITFIELD; - *pbitofs = 0; - *pfield_size = 0; - } - - size = dict->size; - length = dict->length; - proto = desc; - - /* Field descriptors for 'c_char * n' are be scpecial cased to - return a Python string instead of an Array object instance... - */ - if (PyCArrayTypeObject_Check(proto)) { - StgDictObject *adict = PyType_stgdict(proto); - StgDictObject *idict; - if (adict && adict->proto) { - idict = PyType_stgdict(adict->proto); - if (!idict) { - PyErr_SetString(PyExc_TypeError, - "has no _stginfo_"); - Py_DECREF(self); - return NULL; - } - if (idict->getfunc == _ctypes_get_fielddesc("c")->getfunc) { - struct fielddesc *fd = _ctypes_get_fielddesc("s"); - getfunc = fd->getfunc; - setfunc = fd->setfunc; - } + } else if (bitsize /* this is a bitfield request */ + && *pfield_size /* we have a bitfield open */ + && dict->size * 8 >= *pfield_size + && (*pbitofs + bitsize) <= dict->size * 8) { + /* expand bit field */ + fieldtype = EXPAND_BITFIELD; +#endif + } else if (bitsize) { + /* start new bitfield */ + fieldtype = NEW_BITFIELD; + *pbitofs = 0; + *pfield_size = dict->size * 8; + } else { + /* not a bit field */ + fieldtype = NO_BITFIELD; + *pbitofs = 0; + *pfield_size = 0; + } + + size = dict->size; + length = dict->length; + proto = desc; + + /* Field descriptors for 'c_char * n' are be scpecial cased to + return a Python string instead of an Array object instance... + */ + if (PyCArrayTypeObject_Check(proto)) { + StgDictObject *adict = PyType_stgdict(proto); + StgDictObject *idict; + if (adict && adict->proto) { + idict = PyType_stgdict(adict->proto); + if (!idict) { + PyErr_SetString(PyExc_TypeError, + "has no _stginfo_"); + Py_DECREF(self); + return NULL; + } + if (idict->getfunc == _ctypes_get_fielddesc("c")->getfunc) { + struct fielddesc *fd = _ctypes_get_fielddesc("s"); + getfunc = fd->getfunc; + setfunc = fd->setfunc; + } #ifdef CTYPES_UNICODE - if (idict->getfunc == _ctypes_get_fielddesc("u")->getfunc) { - struct fielddesc *fd = _ctypes_get_fielddesc("U"); - getfunc = fd->getfunc; - setfunc = fd->setfunc; - } -#endif - } - } - - self->setfunc = setfunc; - self->getfunc = getfunc; - self->index = index; - - Py_INCREF(proto); - self->proto = proto; - - switch (fieldtype) { - case NEW_BITFIELD: - if (big_endian) - self->size = (bitsize << 16) + *pfield_size - *pbitofs - bitsize; - else - self->size = (bitsize << 16) + *pbitofs; - *pbitofs = bitsize; - /* fall through */ - case NO_BITFIELD: - if (pack) - align = min(pack, dict->align); - else - align = dict->align; - if (align && *poffset % align) { - Py_ssize_t delta = align - (*poffset % align); - *psize += delta; - *poffset += delta; - } - - if (bitsize == 0) - self->size = size; - *psize += size; - - self->offset = *poffset; - *poffset += size; - - *palign = align; - break; - - case EXPAND_BITFIELD: - *poffset += dict->size - *pfield_size/8; - *psize += dict->size - *pfield_size/8; - - *pfield_size = dict->size * 8; - - if (big_endian) - self->size = (bitsize << 16) + *pfield_size - *pbitofs - bitsize; - else - self->size = (bitsize << 16) + *pbitofs; - - self->offset = *poffset - size; /* poffset is already updated for the NEXT field */ - *pbitofs += bitsize; - break; - - case CONT_BITFIELD: - if (big_endian) - self->size = (bitsize << 16) + *pfield_size - *pbitofs - bitsize; - else - self->size = (bitsize << 16) + *pbitofs; - - self->offset = *poffset - size; /* poffset is already updated for the NEXT field */ - *pbitofs += bitsize; - break; - } + if (idict->getfunc == _ctypes_get_fielddesc("u")->getfunc) { + struct fielddesc *fd = _ctypes_get_fielddesc("U"); + getfunc = fd->getfunc; + setfunc = fd->setfunc; + } +#endif + } + } + + self->setfunc = setfunc; + self->getfunc = getfunc; + self->index = index; + + Py_INCREF(proto); + self->proto = proto; + + switch (fieldtype) { + case NEW_BITFIELD: + if (big_endian) + self->size = (bitsize << 16) + *pfield_size - *pbitofs - bitsize; + else + self->size = (bitsize << 16) + *pbitofs; + *pbitofs = bitsize; + /* fall through */ + case NO_BITFIELD: + if (pack) + align = min(pack, dict->align); + else + align = dict->align; + if (align && *poffset % align) { + Py_ssize_t delta = align - (*poffset % align); + *psize += delta; + *poffset += delta; + } + + if (bitsize == 0) + self->size = size; + *psize += size; + + self->offset = *poffset; + *poffset += size; + + *palign = align; + break; + + case EXPAND_BITFIELD: + *poffset += dict->size - *pfield_size/8; + *psize += dict->size - *pfield_size/8; + + *pfield_size = dict->size * 8; + + if (big_endian) + self->size = (bitsize << 16) + *pfield_size - *pbitofs - bitsize; + else + self->size = (bitsize << 16) + *pbitofs; + + self->offset = *poffset - size; /* poffset is already updated for the NEXT field */ + *pbitofs += bitsize; + break; + + case CONT_BITFIELD: + if (big_endian) + self->size = (bitsize << 16) + *pfield_size - *pbitofs - bitsize; + else + self->size = (bitsize << 16) + *pbitofs; + + self->offset = *poffset - size; /* poffset is already updated for the NEXT field */ + *pbitofs += bitsize; + break; + } - return (PyObject *)self; + return (PyObject *)self; } static int PyCField_set(CFieldObject *self, PyObject *inst, PyObject *value) { - CDataObject *dst; - char *ptr; - assert(CDataObject_Check(inst)); - dst = (CDataObject *)inst; - ptr = dst->b_ptr + self->offset; - if (value == NULL) { - PyErr_SetString(PyExc_TypeError, - "can't delete attribute"); - return -1; - } - return PyCData_set(inst, self->proto, self->setfunc, value, - self->index, self->size, ptr); + CDataObject *dst; + char *ptr; + assert(CDataObject_Check(inst)); + dst = (CDataObject *)inst; + ptr = dst->b_ptr + self->offset; + if (value == NULL) { + PyErr_SetString(PyExc_TypeError, + "can't delete attribute"); + return -1; + } + return PyCData_set(inst, self->proto, self->setfunc, value, + self->index, self->size, ptr); } static PyObject * PyCField_get(CFieldObject *self, PyObject *inst, PyTypeObject *type) { - CDataObject *src; - if (inst == NULL) { - Py_INCREF(self); - return (PyObject *)self; - } - assert(CDataObject_Check(inst)); - src = (CDataObject *)inst; - return PyCData_get(self->proto, self->getfunc, inst, - self->index, self->size, src->b_ptr + self->offset); + CDataObject *src; + if (inst == NULL) { + Py_INCREF(self); + return (PyObject *)self; + } + assert(CDataObject_Check(inst)); + src = (CDataObject *)inst; + return PyCData_get(self->proto, self->getfunc, inst, + self->index, self->size, src->b_ptr + self->offset); } static PyObject * PyCField_get_offset(PyObject *self, void *data) { - return PyLong_FromSsize_t(((CFieldObject *)self)->offset); + return PyLong_FromSsize_t(((CFieldObject *)self)->offset); } static PyObject * PyCField_get_size(PyObject *self, void *data) { - return PyLong_FromSsize_t(((CFieldObject *)self)->size); + return PyLong_FromSsize_t(((CFieldObject *)self)->size); } static PyGetSetDef PyCField_getset[] = { - { "offset", PyCField_get_offset, NULL, "offset in bytes of this field" }, - { "size", PyCField_get_size, NULL, "size in bytes of this field" }, - { NULL, NULL, NULL, NULL }, + { "offset", PyCField_get_offset, NULL, "offset in bytes of this field" }, + { "size", PyCField_get_size, NULL, "size in bytes of this field" }, + { NULL, NULL, NULL, NULL }, }; static int PyCField_traverse(CFieldObject *self, visitproc visit, void *arg) { - Py_VISIT(self->proto); - return 0; + Py_VISIT(self->proto); + return 0; } static int PyCField_clear(CFieldObject *self) { - Py_CLEAR(self->proto); - return 0; + Py_CLEAR(self->proto); + return 0; } static void PyCField_dealloc(PyObject *self) { - PyCField_clear((CFieldObject *)self); - self->ob_type->tp_free((PyObject *)self); + PyCField_clear((CFieldObject *)self); + self->ob_type->tp_free((PyObject *)self); } static PyObject * PyCField_repr(CFieldObject *self) { - PyObject *result; - Py_ssize_t bits = self->size >> 16; - Py_ssize_t size = self->size & 0xFFFF; - const char *name; - - name = ((PyTypeObject *)self->proto)->tp_name; - - if (bits) - result = PyUnicode_FromFormat( - "", - name, self->offset, size, bits); - else - result = PyUnicode_FromFormat( - "", - name, self->offset, size); - return result; + PyObject *result; + Py_ssize_t bits = self->size >> 16; + Py_ssize_t size = self->size & 0xFFFF; + const char *name; + + name = ((PyTypeObject *)self->proto)->tp_name; + + if (bits) + result = PyUnicode_FromFormat( + "", + name, self->offset, size, bits); + else + result = PyUnicode_FromFormat( + "", + name, self->offset, size); + return result; } PyTypeObject PyCField_Type = { - PyVarObject_HEAD_INIT(NULL, 0) - "_ctypes.CField", /* tp_name */ - sizeof(CFieldObject), /* tp_basicsize */ - 0, /* tp_itemsize */ - PyCField_dealloc, /* tp_dealloc */ - 0, /* tp_print */ - 0, /* tp_getattr */ - 0, /* tp_setattr */ - 0, /* tp_reserved */ - (reprfunc)PyCField_repr, /* tp_repr */ - 0, /* tp_as_number */ - 0, /* tp_as_sequence */ - 0, /* tp_as_mapping */ - 0, /* tp_hash */ - 0, /* tp_call */ - 0, /* tp_str */ - 0, /* tp_getattro */ - 0, /* tp_setattro */ - 0, /* tp_as_buffer */ - Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC, /* tp_flags */ - "Structure/Union member", /* tp_doc */ - (traverseproc)PyCField_traverse, /* tp_traverse */ - (inquiry)PyCField_clear, /* tp_clear */ - 0, /* tp_richcompare */ - 0, /* tp_weaklistoffset */ - 0, /* tp_iter */ - 0, /* tp_iternext */ - 0, /* tp_methods */ - 0, /* tp_members */ - PyCField_getset, /* tp_getset */ - 0, /* tp_base */ - 0, /* tp_dict */ - (descrgetfunc)PyCField_get, /* tp_descr_get */ - (descrsetfunc)PyCField_set, /* tp_descr_set */ - 0, /* tp_dictoffset */ - 0, /* tp_init */ - 0, /* tp_alloc */ - PyCField_new, /* tp_new */ - 0, /* tp_free */ + PyVarObject_HEAD_INIT(NULL, 0) + "_ctypes.CField", /* tp_name */ + sizeof(CFieldObject), /* tp_basicsize */ + 0, /* tp_itemsize */ + PyCField_dealloc, /* tp_dealloc */ + 0, /* tp_print */ + 0, /* tp_getattr */ + 0, /* tp_setattr */ + 0, /* tp_reserved */ + (reprfunc)PyCField_repr, /* tp_repr */ + 0, /* tp_as_number */ + 0, /* tp_as_sequence */ + 0, /* tp_as_mapping */ + 0, /* tp_hash */ + 0, /* tp_call */ + 0, /* tp_str */ + 0, /* tp_getattro */ + 0, /* tp_setattro */ + 0, /* tp_as_buffer */ + Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC, /* tp_flags */ + "Structure/Union member", /* tp_doc */ + (traverseproc)PyCField_traverse, /* tp_traverse */ + (inquiry)PyCField_clear, /* tp_clear */ + 0, /* tp_richcompare */ + 0, /* tp_weaklistoffset */ + 0, /* tp_iter */ + 0, /* tp_iternext */ + 0, /* tp_methods */ + 0, /* tp_members */ + PyCField_getset, /* tp_getset */ + 0, /* tp_base */ + 0, /* tp_dict */ + (descrgetfunc)PyCField_get, /* tp_descr_get */ + (descrsetfunc)PyCField_set, /* tp_descr_set */ + 0, /* tp_dictoffset */ + 0, /* tp_init */ + 0, /* tp_alloc */ + PyCField_new, /* tp_new */ + 0, /* tp_free */ }; - + /******************************************************************/ /* Accessor functions @@ -347,18 +347,18 @@ static int get_long(PyObject *v, long *p) { - long x; + long x; - if (PyFloat_Check(v)) { - PyErr_SetString(PyExc_TypeError, - "int expected instead of float"); - return -1; - } - x = PyLong_AsUnsignedLongMask(v); - if (x == -1 && PyErr_Occurred()) - return -1; - *p = x; - return 0; + if (PyFloat_Check(v)) { + PyErr_SetString(PyExc_TypeError, + "int expected instead of float"); + return -1; + } + x = PyLong_AsUnsignedLongMask(v); + if (x == -1 && PyErr_Occurred()) + return -1; + *p = x; + return 0; } /* Same, but handling unsigned long */ @@ -366,18 +366,18 @@ static int get_ulong(PyObject *v, unsigned long *p) { - unsigned long x; + unsigned long x; - if (PyFloat_Check(v)) { - PyErr_SetString(PyExc_TypeError, - "int expected instead of float"); - return -1; - } - x = PyLong_AsUnsignedLongMask(v); - if (x == (unsigned long)-1 && PyErr_Occurred()) - return -1; - *p = x; - return 0; + if (PyFloat_Check(v)) { + PyErr_SetString(PyExc_TypeError, + "int expected instead of float"); + return -1; + } + x = PyLong_AsUnsignedLongMask(v); + if (x == (unsigned long)-1 && PyErr_Occurred()) + return -1; + *p = x; + return 0; } #ifdef HAVE_LONG_LONG @@ -387,17 +387,17 @@ static int get_longlong(PyObject *v, PY_LONG_LONG *p) { - PY_LONG_LONG x; - if (PyFloat_Check(v)) { - PyErr_SetString(PyExc_TypeError, - "int expected instead of float"); - return -1; - } - x = PyLong_AsUnsignedLongLongMask(v); - if (x == -1 && PyErr_Occurred()) - return -1; - *p = x; - return 0; + PY_LONG_LONG x; + if (PyFloat_Check(v)) { + PyErr_SetString(PyExc_TypeError, + "int expected instead of float"); + return -1; + } + x = PyLong_AsUnsignedLongLongMask(v); + if (x == -1 && PyErr_Occurred()) + return -1; + *p = x; + return 0; } /* Same, but handling native unsigned long long. */ @@ -405,17 +405,17 @@ static int get_ulonglong(PyObject *v, unsigned PY_LONG_LONG *p) { - unsigned PY_LONG_LONG x; - if (PyFloat_Check(v)) { - PyErr_SetString(PyExc_TypeError, - "int expected instead of float"); - return -1; - } - x = PyLong_AsUnsignedLongLongMask(v); - if (x == (unsigned PY_LONG_LONG)-1 && PyErr_Occurred()) - return -1; - *p = x; - return 0; + unsigned PY_LONG_LONG x; + if (PyFloat_Check(v)) { + PyErr_SetString(PyExc_TypeError, + "int expected instead of float"); + return -1; + } + x = PyLong_AsUnsignedLongLongMask(v); + if (x == (unsigned PY_LONG_LONG)-1 && PyErr_Occurred()) + return -1; + *p = x; + return 0; } #endif @@ -438,49 +438,49 @@ /* This macro CHANGES the first parameter IN PLACE. For proper sign handling, we must first shift left, then right. */ -#define GET_BITFIELD(v, size) \ - if (NUM_BITS(size)) { \ - v <<= (sizeof(v)*8 - LOW_BIT(size) - NUM_BITS(size)); \ - v >>= (sizeof(v)*8 - NUM_BITS(size)); \ - } +#define GET_BITFIELD(v, size) \ + if (NUM_BITS(size)) { \ + v <<= (sizeof(v)*8 - LOW_BIT(size) - NUM_BITS(size)); \ + v >>= (sizeof(v)*8 - NUM_BITS(size)); \ + } /* This macro RETURNS the first parameter with the bit field CHANGED. */ -#define SET(x, v, size) \ - (NUM_BITS(size) ? \ - ( ( x & ~(BIT_MASK(size) << LOW_BIT(size)) ) | ( (v & BIT_MASK(size)) << LOW_BIT(size) ) ) \ - : v) +#define SET(x, v, size) \ + (NUM_BITS(size) ? \ + ( ( x & ~(BIT_MASK(size) << LOW_BIT(size)) ) | ( (v & BIT_MASK(size)) << LOW_BIT(size) ) ) \ + : v) /* byte swapping macros */ -#define SWAP_2(v) \ - ( ( (v >> 8) & 0x00FF) | \ - ( (v << 8) & 0xFF00) ) - -#define SWAP_4(v) \ - ( ( (v & 0x000000FF) << 24 ) | \ - ( (v & 0x0000FF00) << 8 ) | \ - ( (v & 0x00FF0000) >> 8 ) | \ - ( ((v >> 24) & 0xFF)) ) +#define SWAP_2(v) \ + ( ( (v >> 8) & 0x00FF) | \ + ( (v << 8) & 0xFF00) ) + +#define SWAP_4(v) \ + ( ( (v & 0x000000FF) << 24 ) | \ + ( (v & 0x0000FF00) << 8 ) | \ + ( (v & 0x00FF0000) >> 8 ) | \ + ( ((v >> 24) & 0xFF)) ) #ifdef _MSC_VER -#define SWAP_8(v) \ - ( ( (v & 0x00000000000000FFL) << 56 ) | \ - ( (v & 0x000000000000FF00L) << 40 ) | \ - ( (v & 0x0000000000FF0000L) << 24 ) | \ - ( (v & 0x00000000FF000000L) << 8 ) | \ - ( (v & 0x000000FF00000000L) >> 8 ) | \ - ( (v & 0x0000FF0000000000L) >> 24 ) | \ - ( (v & 0x00FF000000000000L) >> 40 ) | \ - ( ((v >> 56) & 0xFF)) ) +#define SWAP_8(v) \ + ( ( (v & 0x00000000000000FFL) << 56 ) | \ + ( (v & 0x000000000000FF00L) << 40 ) | \ + ( (v & 0x0000000000FF0000L) << 24 ) | \ + ( (v & 0x00000000FF000000L) << 8 ) | \ + ( (v & 0x000000FF00000000L) >> 8 ) | \ + ( (v & 0x0000FF0000000000L) >> 24 ) | \ + ( (v & 0x00FF000000000000L) >> 40 ) | \ + ( ((v >> 56) & 0xFF)) ) #else -#define SWAP_8(v) \ - ( ( (v & 0x00000000000000FFLL) << 56 ) | \ - ( (v & 0x000000000000FF00LL) << 40 ) | \ - ( (v & 0x0000000000FF0000LL) << 24 ) | \ - ( (v & 0x00000000FF000000LL) << 8 ) | \ - ( (v & 0x000000FF00000000LL) >> 8 ) | \ - ( (v & 0x0000FF0000000000LL) >> 24 ) | \ - ( (v & 0x00FF000000000000LL) >> 40 ) | \ - ( ((v >> 56) & 0xFF)) ) +#define SWAP_8(v) \ + ( ( (v & 0x00000000000000FFLL) << 56 ) | \ + ( (v & 0x000000000000FF00LL) << 40 ) | \ + ( (v & 0x0000000000FF0000LL) << 24 ) | \ + ( (v & 0x00000000FF000000LL) << 8 ) | \ + ( (v & 0x000000FF00000000LL) >> 8 ) | \ + ( (v & 0x0000FF0000000000LL) >> 24 ) | \ + ( (v & 0x00FF000000000000LL) >> 40 ) | \ + ( ((v >> 56) & 0xFF)) ) #endif #define SWAP_INT SWAP_4 @@ -517,184 +517,184 @@ static PyObject * b_set(void *ptr, PyObject *value, Py_ssize_t size) { - long val; - if (get_long(value, &val) < 0) - return NULL; - *(signed char *)ptr = (signed char)SET(*(signed char *)ptr, (signed char)val, size); - _RET(value); + long val; + if (get_long(value, &val) < 0) + return NULL; + *(signed char *)ptr = (signed char)SET(*(signed char *)ptr, (signed char)val, size); + _RET(value); } static PyObject * b_get(void *ptr, Py_ssize_t size) { - signed char val = *(signed char *)ptr; - GET_BITFIELD(val, size); - return PyLong_FromLong(val); + signed char val = *(signed char *)ptr; + GET_BITFIELD(val, size); + return PyLong_FromLong(val); } static PyObject * B_set(void *ptr, PyObject *value, Py_ssize_t size) { - unsigned long val; - if (get_ulong(value, &val) < 0) - return NULL; - *(unsigned char *)ptr = (unsigned char)SET(*(unsigned char*)ptr, - (unsigned short)val, size); - _RET(value); + unsigned long val; + if (get_ulong(value, &val) < 0) + return NULL; + *(unsigned char *)ptr = (unsigned char)SET(*(unsigned char*)ptr, + (unsigned short)val, size); + _RET(value); } static PyObject * B_get(void *ptr, Py_ssize_t size) { - unsigned char val = *(unsigned char *)ptr; - GET_BITFIELD(val, size); - return PyLong_FromLong(val); + unsigned char val = *(unsigned char *)ptr; + GET_BITFIELD(val, size); + return PyLong_FromLong(val); } static PyObject * h_set(void *ptr, PyObject *value, Py_ssize_t size) { - long val; - short x; - if (get_long(value, &val) < 0) - return NULL; - memcpy(&x, ptr, sizeof(x)); - x = SET(x, (short)val, size); - memcpy(ptr, &x, sizeof(x)); - _RET(value); + long val; + short x; + if (get_long(value, &val) < 0) + return NULL; + memcpy(&x, ptr, sizeof(x)); + x = SET(x, (short)val, size); + memcpy(ptr, &x, sizeof(x)); + _RET(value); } static PyObject * h_set_sw(void *ptr, PyObject *value, Py_ssize_t size) { - long val; - short field; - if (get_long(value, &val) < 0) - return NULL; - memcpy(&field, ptr, sizeof(field)); - field = SWAP_2(field); - field = SET(field, (short)val, size); - field = SWAP_2(field); - memcpy(ptr, &field, sizeof(field)); - _RET(value); + long val; + short field; + if (get_long(value, &val) < 0) + return NULL; + memcpy(&field, ptr, sizeof(field)); + field = SWAP_2(field); + field = SET(field, (short)val, size); + field = SWAP_2(field); + memcpy(ptr, &field, sizeof(field)); + _RET(value); } static PyObject * h_get(void *ptr, Py_ssize_t size) { - short val; - memcpy(&val, ptr, sizeof(val)); - GET_BITFIELD(val, size); - return PyLong_FromLong((long)val); + short val; + memcpy(&val, ptr, sizeof(val)); + GET_BITFIELD(val, size); + return PyLong_FromLong((long)val); } static PyObject * h_get_sw(void *ptr, Py_ssize_t size) { - short val; - memcpy(&val, ptr, sizeof(val)); - val = SWAP_2(val); - GET_BITFIELD(val, size); - return PyLong_FromLong(val); + short val; + memcpy(&val, ptr, sizeof(val)); + val = SWAP_2(val); + GET_BITFIELD(val, size); + return PyLong_FromLong(val); } static PyObject * H_set(void *ptr, PyObject *value, Py_ssize_t size) { - unsigned long val; - unsigned short x; - if (get_ulong(value, &val) < 0) - return NULL; - memcpy(&x, ptr, sizeof(x)); - x = SET(x, (unsigned short)val, size); - memcpy(ptr, &x, sizeof(x)); - _RET(value); + unsigned long val; + unsigned short x; + if (get_ulong(value, &val) < 0) + return NULL; + memcpy(&x, ptr, sizeof(x)); + x = SET(x, (unsigned short)val, size); + memcpy(ptr, &x, sizeof(x)); + _RET(value); } static PyObject * H_set_sw(void *ptr, PyObject *value, Py_ssize_t size) { - unsigned long val; - unsigned short field; - if (get_ulong(value, &val) < 0) - return NULL; - memcpy(&field, ptr, sizeof(field)); - field = SWAP_2(field); - field = SET(field, (unsigned short)val, size); - field = SWAP_2(field); - memcpy(ptr, &field, sizeof(field)); - _RET(value); + unsigned long val; + unsigned short field; + if (get_ulong(value, &val) < 0) + return NULL; + memcpy(&field, ptr, sizeof(field)); + field = SWAP_2(field); + field = SET(field, (unsigned short)val, size); + field = SWAP_2(field); + memcpy(ptr, &field, sizeof(field)); + _RET(value); } static PyObject * H_get(void *ptr, Py_ssize_t size) { - unsigned short val; - memcpy(&val, ptr, sizeof(val)); - GET_BITFIELD(val, size); - return PyLong_FromLong(val); + unsigned short val; + memcpy(&val, ptr, sizeof(val)); + GET_BITFIELD(val, size); + return PyLong_FromLong(val); } static PyObject * H_get_sw(void *ptr, Py_ssize_t size) { - unsigned short val; - memcpy(&val, ptr, sizeof(val)); - val = SWAP_2(val); - GET_BITFIELD(val, size); - return PyLong_FromLong(val); + unsigned short val; + memcpy(&val, ptr, sizeof(val)); + val = SWAP_2(val); + GET_BITFIELD(val, size); + return PyLong_FromLong(val); } static PyObject * i_set(void *ptr, PyObject *value, Py_ssize_t size) { - long val; - int x; - if (get_long(value, &val) < 0) - return NULL; - memcpy(&x, ptr, sizeof(x)); - x = SET(x, (int)val, size); - memcpy(ptr, &x, sizeof(x)); - _RET(value); + long val; + int x; + if (get_long(value, &val) < 0) + return NULL; + memcpy(&x, ptr, sizeof(x)); + x = SET(x, (int)val, size); + memcpy(ptr, &x, sizeof(x)); + _RET(value); } static PyObject * i_set_sw(void *ptr, PyObject *value, Py_ssize_t size) { - long val; - int field; - if (get_long(value, &val) < 0) - return NULL; - memcpy(&field, ptr, sizeof(field)); - field = SWAP_INT(field); - field = SET(field, (int)val, size); - field = SWAP_INT(field); - memcpy(ptr, &field, sizeof(field)); - _RET(value); + long val; + int field; + if (get_long(value, &val) < 0) + return NULL; + memcpy(&field, ptr, sizeof(field)); + field = SWAP_INT(field); + field = SET(field, (int)val, size); + field = SWAP_INT(field); + memcpy(ptr, &field, sizeof(field)); + _RET(value); } static PyObject * i_get(void *ptr, Py_ssize_t size) { - int val; - memcpy(&val, ptr, sizeof(val)); - GET_BITFIELD(val, size); - return PyLong_FromLong(val); + int val; + memcpy(&val, ptr, sizeof(val)); + GET_BITFIELD(val, size); + return PyLong_FromLong(val); } static PyObject * i_get_sw(void *ptr, Py_ssize_t size) { - int val; - memcpy(&val, ptr, sizeof(val)); - val = SWAP_INT(val); - GET_BITFIELD(val, size); - return PyLong_FromLong(val); + int val; + memcpy(&val, ptr, sizeof(val)); + val = SWAP_INT(val); + GET_BITFIELD(val, size); + return PyLong_FromLong(val); } #ifdef MS_WIN32 @@ -702,22 +702,22 @@ static PyObject * vBOOL_set(void *ptr, PyObject *value, Py_ssize_t size) { - switch (PyObject_IsTrue(value)) { - case -1: - return NULL; - case 0: - *(short int *)ptr = VARIANT_FALSE; - _RET(value); - default: - *(short int *)ptr = VARIANT_TRUE; - _RET(value); - } + switch (PyObject_IsTrue(value)) { + case -1: + return NULL; + case 0: + *(short int *)ptr = VARIANT_FALSE; + _RET(value); + default: + *(short int *)ptr = VARIANT_TRUE; + _RET(value); + } } static PyObject * vBOOL_get(void *ptr, Py_ssize_t size) { - return PyBool_FromLong((long)*(short int *)ptr); + return PyBool_FromLong((long)*(short int *)ptr); } #endif @@ -732,260 +732,260 @@ static PyObject * bool_set(void *ptr, PyObject *value, Py_ssize_t size) { - switch (PyObject_IsTrue(value)) { - case -1: - return NULL; - case 0: - *(BOOL_TYPE *)ptr = 0; - _RET(value); - default: - *(BOOL_TYPE *)ptr = 1; - _RET(value); - } + switch (PyObject_IsTrue(value)) { + case -1: + return NULL; + case 0: + *(BOOL_TYPE *)ptr = 0; + _RET(value); + default: + *(BOOL_TYPE *)ptr = 1; + _RET(value); + } } static PyObject * bool_get(void *ptr, Py_ssize_t size) { - return PyBool_FromLong((long)*(BOOL_TYPE *)ptr); + return PyBool_FromLong((long)*(BOOL_TYPE *)ptr); } static PyObject * I_set(void *ptr, PyObject *value, Py_ssize_t size) { - unsigned long val; - unsigned int x; - if (get_ulong(value, &val) < 0) - return NULL; - memcpy(&x, ptr, sizeof(x)); - x = SET(x, (unsigned int)val, size); - memcpy(ptr, &x, sizeof(x)); - _RET(value); + unsigned long val; + unsigned int x; + if (get_ulong(value, &val) < 0) + return NULL; + memcpy(&x, ptr, sizeof(x)); + x = SET(x, (unsigned int)val, size); + memcpy(ptr, &x, sizeof(x)); + _RET(value); } static PyObject * I_set_sw(void *ptr, PyObject *value, Py_ssize_t size) { - unsigned long val; - unsigned int field; - if (get_ulong(value, &val) < 0) - return NULL; - memcpy(&field, ptr, sizeof(field)); - field = (unsigned int)SET(field, (unsigned int)val, size); - field = SWAP_INT(field); - memcpy(ptr, &field, sizeof(field)); - _RET(value); + unsigned long val; + unsigned int field; + if (get_ulong(value, &val) < 0) + return NULL; + memcpy(&field, ptr, sizeof(field)); + field = (unsigned int)SET(field, (unsigned int)val, size); + field = SWAP_INT(field); + memcpy(ptr, &field, sizeof(field)); + _RET(value); } static PyObject * I_get(void *ptr, Py_ssize_t size) { - unsigned int val; - memcpy(&val, ptr, sizeof(val)); - GET_BITFIELD(val, size); - return PyLong_FromUnsignedLong(val); + unsigned int val; + memcpy(&val, ptr, sizeof(val)); + GET_BITFIELD(val, size); + return PyLong_FromUnsignedLong(val); } static PyObject * I_get_sw(void *ptr, Py_ssize_t size) { - unsigned int val; - memcpy(&val, ptr, sizeof(val)); - val = SWAP_INT(val); - GET_BITFIELD(val, size); - return PyLong_FromUnsignedLong(val); + unsigned int val; + memcpy(&val, ptr, sizeof(val)); + val = SWAP_INT(val); + GET_BITFIELD(val, size); + return PyLong_FromUnsignedLong(val); } static PyObject * l_set(void *ptr, PyObject *value, Py_ssize_t size) { - long val; - long x; - if (get_long(value, &val) < 0) - return NULL; - memcpy(&x, ptr, sizeof(x)); - x = SET(x, val, size); - memcpy(ptr, &x, sizeof(x)); - _RET(value); + long val; + long x; + if (get_long(value, &val) < 0) + return NULL; + memcpy(&x, ptr, sizeof(x)); + x = SET(x, val, size); + memcpy(ptr, &x, sizeof(x)); + _RET(value); } static PyObject * l_set_sw(void *ptr, PyObject *value, Py_ssize_t size) { - long val; - long field; - if (get_long(value, &val) < 0) - return NULL; - memcpy(&field, ptr, sizeof(field)); - field = SWAP_LONG(field); - field = (long)SET(field, val, size); - field = SWAP_LONG(field); - memcpy(ptr, &field, sizeof(field)); - _RET(value); + long val; + long field; + if (get_long(value, &val) < 0) + return NULL; + memcpy(&field, ptr, sizeof(field)); + field = SWAP_LONG(field); + field = (long)SET(field, val, size); + field = SWAP_LONG(field); + memcpy(ptr, &field, sizeof(field)); + _RET(value); } static PyObject * l_get(void *ptr, Py_ssize_t size) { - long val; - memcpy(&val, ptr, sizeof(val)); - GET_BITFIELD(val, size); - return PyLong_FromLong(val); + long val; + memcpy(&val, ptr, sizeof(val)); + GET_BITFIELD(val, size); + return PyLong_FromLong(val); } static PyObject * l_get_sw(void *ptr, Py_ssize_t size) { - long val; - memcpy(&val, ptr, sizeof(val)); - val = SWAP_LONG(val); - GET_BITFIELD(val, size); - return PyLong_FromLong(val); + long val; + memcpy(&val, ptr, sizeof(val)); + val = SWAP_LONG(val); + GET_BITFIELD(val, size); + return PyLong_FromLong(val); } static PyObject * L_set(void *ptr, PyObject *value, Py_ssize_t size) { - unsigned long val; - unsigned long x; - if (get_ulong(value, &val) < 0) - return NULL; - memcpy(&x, ptr, sizeof(x)); - x = SET(x, val, size); - memcpy(ptr, &x, sizeof(x)); - _RET(value); + unsigned long val; + unsigned long x; + if (get_ulong(value, &val) < 0) + return NULL; + memcpy(&x, ptr, sizeof(x)); + x = SET(x, val, size); + memcpy(ptr, &x, sizeof(x)); + _RET(value); } static PyObject * L_set_sw(void *ptr, PyObject *value, Py_ssize_t size) { - unsigned long val; - unsigned long field; - if (get_ulong(value, &val) < 0) - return NULL; - memcpy(&field, ptr, sizeof(field)); - field = SWAP_LONG(field); - field = (unsigned long)SET(field, val, size); - field = SWAP_LONG(field); - memcpy(ptr, &field, sizeof(field)); - _RET(value); + unsigned long val; + unsigned long field; + if (get_ulong(value, &val) < 0) + return NULL; + memcpy(&field, ptr, sizeof(field)); + field = SWAP_LONG(field); + field = (unsigned long)SET(field, val, size); + field = SWAP_LONG(field); + memcpy(ptr, &field, sizeof(field)); + _RET(value); } static PyObject * L_get(void *ptr, Py_ssize_t size) { - unsigned long val; - memcpy(&val, ptr, sizeof(val)); - GET_BITFIELD(val, size); - return PyLong_FromUnsignedLong(val); + unsigned long val; + memcpy(&val, ptr, sizeof(val)); + GET_BITFIELD(val, size); + return PyLong_FromUnsignedLong(val); } static PyObject * L_get_sw(void *ptr, Py_ssize_t size) { - unsigned long val; - memcpy(&val, ptr, sizeof(val)); - val = SWAP_LONG(val); - GET_BITFIELD(val, size); - return PyLong_FromUnsignedLong(val); + unsigned long val; + memcpy(&val, ptr, sizeof(val)); + val = SWAP_LONG(val); + GET_BITFIELD(val, size); + return PyLong_FromUnsignedLong(val); } #ifdef HAVE_LONG_LONG static PyObject * q_set(void *ptr, PyObject *value, Py_ssize_t size) { - PY_LONG_LONG val; - PY_LONG_LONG x; - if (get_longlong(value, &val) < 0) - return NULL; - memcpy(&x, ptr, sizeof(x)); - x = SET(x, val, size); - memcpy(ptr, &x, sizeof(x)); - _RET(value); + PY_LONG_LONG val; + PY_LONG_LONG x; + if (get_longlong(value, &val) < 0) + return NULL; + memcpy(&x, ptr, sizeof(x)); + x = SET(x, val, size); + memcpy(ptr, &x, sizeof(x)); + _RET(value); } static PyObject * q_set_sw(void *ptr, PyObject *value, Py_ssize_t size) { - PY_LONG_LONG val; - PY_LONG_LONG field; - if (get_longlong(value, &val) < 0) - return NULL; - memcpy(&field, ptr, sizeof(field)); - field = SWAP_8(field); - field = (PY_LONG_LONG)SET(field, val, size); - field = SWAP_8(field); - memcpy(ptr, &field, sizeof(field)); - _RET(value); + PY_LONG_LONG val; + PY_LONG_LONG field; + if (get_longlong(value, &val) < 0) + return NULL; + memcpy(&field, ptr, sizeof(field)); + field = SWAP_8(field); + field = (PY_LONG_LONG)SET(field, val, size); + field = SWAP_8(field); + memcpy(ptr, &field, sizeof(field)); + _RET(value); } static PyObject * q_get(void *ptr, Py_ssize_t size) { - PY_LONG_LONG val; - memcpy(&val, ptr, sizeof(val)); - GET_BITFIELD(val, size); - return PyLong_FromLongLong(val); + PY_LONG_LONG val; + memcpy(&val, ptr, sizeof(val)); + GET_BITFIELD(val, size); + return PyLong_FromLongLong(val); } static PyObject * q_get_sw(void *ptr, Py_ssize_t size) { - PY_LONG_LONG val; - memcpy(&val, ptr, sizeof(val)); - val = SWAP_8(val); - GET_BITFIELD(val, size); - return PyLong_FromLongLong(val); + PY_LONG_LONG val; + memcpy(&val, ptr, sizeof(val)); + val = SWAP_8(val); + GET_BITFIELD(val, size); + return PyLong_FromLongLong(val); } static PyObject * Q_set(void *ptr, PyObject *value, Py_ssize_t size) { - unsigned PY_LONG_LONG val; - unsigned PY_LONG_LONG x; - if (get_ulonglong(value, &val) < 0) - return NULL; - memcpy(&x, ptr, sizeof(x)); - x = SET(x, val, size); - memcpy(ptr, &x, sizeof(x)); - _RET(value); + unsigned PY_LONG_LONG val; + unsigned PY_LONG_LONG x; + if (get_ulonglong(value, &val) < 0) + return NULL; + memcpy(&x, ptr, sizeof(x)); + x = SET(x, val, size); + memcpy(ptr, &x, sizeof(x)); + _RET(value); } static PyObject * Q_set_sw(void *ptr, PyObject *value, Py_ssize_t size) { - unsigned PY_LONG_LONG val; - unsigned PY_LONG_LONG field; - if (get_ulonglong(value, &val) < 0) - return NULL; - memcpy(&field, ptr, sizeof(field)); - field = SWAP_8(field); - field = (unsigned PY_LONG_LONG)SET(field, val, size); - field = SWAP_8(field); - memcpy(ptr, &field, sizeof(field)); - _RET(value); + unsigned PY_LONG_LONG val; + unsigned PY_LONG_LONG field; + if (get_ulonglong(value, &val) < 0) + return NULL; + memcpy(&field, ptr, sizeof(field)); + field = SWAP_8(field); + field = (unsigned PY_LONG_LONG)SET(field, val, size); + field = SWAP_8(field); + memcpy(ptr, &field, sizeof(field)); + _RET(value); } static PyObject * Q_get(void *ptr, Py_ssize_t size) { - unsigned PY_LONG_LONG val; - memcpy(&val, ptr, sizeof(val)); - GET_BITFIELD(val, size); - return PyLong_FromUnsignedLongLong(val); + unsigned PY_LONG_LONG val; + memcpy(&val, ptr, sizeof(val)); + GET_BITFIELD(val, size); + return PyLong_FromUnsignedLongLong(val); } static PyObject * Q_get_sw(void *ptr, Py_ssize_t size) { - unsigned PY_LONG_LONG val; - memcpy(&val, ptr, sizeof(val)); - val = SWAP_8(val); - GET_BITFIELD(val, size); - return PyLong_FromUnsignedLongLong(val); + unsigned PY_LONG_LONG val; + memcpy(&val, ptr, sizeof(val)); + val = SWAP_8(val); + GET_BITFIELD(val, size); + return PyLong_FromUnsignedLongLong(val); } #endif @@ -997,136 +997,136 @@ static PyObject * g_set(void *ptr, PyObject *value, Py_ssize_t size) { - long double x; + long double x; - x = PyFloat_AsDouble(value); - if (x == -1 && PyErr_Occurred()) { - PyErr_Format(PyExc_TypeError, - " float expected instead of %s instance", - value->ob_type->tp_name); - return NULL; - } - memcpy(ptr, &x, sizeof(long double)); - _RET(value); + x = PyFloat_AsDouble(value); + if (x == -1 && PyErr_Occurred()) { + PyErr_Format(PyExc_TypeError, + " float expected instead of %s instance", + value->ob_type->tp_name); + return NULL; + } + memcpy(ptr, &x, sizeof(long double)); + _RET(value); } static PyObject * g_get(void *ptr, Py_ssize_t size) { - long double val; - memcpy(&val, ptr, sizeof(long double)); - return PyFloat_FromDouble(val); + long double val; + memcpy(&val, ptr, sizeof(long double)); + return PyFloat_FromDouble(val); } static PyObject * d_set(void *ptr, PyObject *value, Py_ssize_t size) { - double x; + double x; - x = PyFloat_AsDouble(value); - if (x == -1 && PyErr_Occurred()) { - PyErr_Format(PyExc_TypeError, - " float expected instead of %s instance", - value->ob_type->tp_name); - return NULL; - } - memcpy(ptr, &x, sizeof(double)); - _RET(value); + x = PyFloat_AsDouble(value); + if (x == -1 && PyErr_Occurred()) { + PyErr_Format(PyExc_TypeError, + " float expected instead of %s instance", + value->ob_type->tp_name); + return NULL; + } + memcpy(ptr, &x, sizeof(double)); + _RET(value); } static PyObject * d_get(void *ptr, Py_ssize_t size) { - double val; - memcpy(&val, ptr, sizeof(val)); - return PyFloat_FromDouble(val); + double val; + memcpy(&val, ptr, sizeof(val)); + return PyFloat_FromDouble(val); } static PyObject * d_set_sw(void *ptr, PyObject *value, Py_ssize_t size) { - double x; + double x; - x = PyFloat_AsDouble(value); - if (x == -1 && PyErr_Occurred()) { - PyErr_Format(PyExc_TypeError, - " float expected instead of %s instance", - value->ob_type->tp_name); - return NULL; - } + x = PyFloat_AsDouble(value); + if (x == -1 && PyErr_Occurred()) { + PyErr_Format(PyExc_TypeError, + " float expected instead of %s instance", + value->ob_type->tp_name); + return NULL; + } #ifdef WORDS_BIGENDIAN - if (_PyFloat_Pack8(x, (unsigned char *)ptr, 1)) - return NULL; + if (_PyFloat_Pack8(x, (unsigned char *)ptr, 1)) + return NULL; #else - if (_PyFloat_Pack8(x, (unsigned char *)ptr, 0)) - return NULL; + if (_PyFloat_Pack8(x, (unsigned char *)ptr, 0)) + return NULL; #endif - _RET(value); + _RET(value); } static PyObject * d_get_sw(void *ptr, Py_ssize_t size) { #ifdef WORDS_BIGENDIAN - return PyFloat_FromDouble(_PyFloat_Unpack8(ptr, 1)); + return PyFloat_FromDouble(_PyFloat_Unpack8(ptr, 1)); #else - return PyFloat_FromDouble(_PyFloat_Unpack8(ptr, 0)); + return PyFloat_FromDouble(_PyFloat_Unpack8(ptr, 0)); #endif } static PyObject * f_set(void *ptr, PyObject *value, Py_ssize_t size) { - float x; + float x; - x = (float)PyFloat_AsDouble(value); - if (x == -1 && PyErr_Occurred()) { - PyErr_Format(PyExc_TypeError, - " float expected instead of %s instance", - value->ob_type->tp_name); - return NULL; - } - memcpy(ptr, &x, sizeof(x)); - _RET(value); + x = (float)PyFloat_AsDouble(value); + if (x == -1 && PyErr_Occurred()) { + PyErr_Format(PyExc_TypeError, + " float expected instead of %s instance", + value->ob_type->tp_name); + return NULL; + } + memcpy(ptr, &x, sizeof(x)); + _RET(value); } static PyObject * f_get(void *ptr, Py_ssize_t size) { - float val; - memcpy(&val, ptr, sizeof(val)); - return PyFloat_FromDouble(val); + float val; + memcpy(&val, ptr, sizeof(val)); + return PyFloat_FromDouble(val); } static PyObject * f_set_sw(void *ptr, PyObject *value, Py_ssize_t size) { - float x; + float x; - x = (float)PyFloat_AsDouble(value); - if (x == -1 && PyErr_Occurred()) { - PyErr_Format(PyExc_TypeError, - " float expected instead of %s instance", - value->ob_type->tp_name); - return NULL; - } + x = (float)PyFloat_AsDouble(value); + if (x == -1 && PyErr_Occurred()) { + PyErr_Format(PyExc_TypeError, + " float expected instead of %s instance", + value->ob_type->tp_name); + return NULL; + } #ifdef WORDS_BIGENDIAN - if (_PyFloat_Pack4(x, (unsigned char *)ptr, 1)) - return NULL; + if (_PyFloat_Pack4(x, (unsigned char *)ptr, 1)) + return NULL; #else - if (_PyFloat_Pack4(x, (unsigned char *)ptr, 0)) - return NULL; + if (_PyFloat_Pack4(x, (unsigned char *)ptr, 0)) + return NULL; #endif - _RET(value); + _RET(value); } static PyObject * f_get_sw(void *ptr, Py_ssize_t size) { #ifdef WORDS_BIGENDIAN - return PyFloat_FromDouble(_PyFloat_Unpack4(ptr, 1)); + return PyFloat_FromDouble(_PyFloat_Unpack4(ptr, 1)); #else - return PyFloat_FromDouble(_PyFloat_Unpack4(ptr, 0)); + return PyFloat_FromDouble(_PyFloat_Unpack4(ptr, 0)); #endif } @@ -1143,72 +1143,72 @@ static PyObject * O_get(void *ptr, Py_ssize_t size) { - PyObject *ob = *(PyObject **)ptr; - if (ob == NULL) { - if (!PyErr_Occurred()) - /* Set an error if not yet set */ - PyErr_SetString(PyExc_ValueError, - "PyObject is NULL"); - return NULL; - } - Py_INCREF(ob); - return ob; + PyObject *ob = *(PyObject **)ptr; + if (ob == NULL) { + if (!PyErr_Occurred()) + /* Set an error if not yet set */ + PyErr_SetString(PyExc_ValueError, + "PyObject is NULL"); + return NULL; + } + Py_INCREF(ob); + return ob; } static PyObject * O_set(void *ptr, PyObject *value, Py_ssize_t size) { - /* Hm, does the memory block need it's own refcount or not? */ - *(PyObject **)ptr = value; - Py_INCREF(value); - return value; + /* Hm, does the memory block need it's own refcount or not? */ + *(PyObject **)ptr = value; + Py_INCREF(value); + return value; } static PyObject * c_set(void *ptr, PyObject *value, Py_ssize_t size) { - if (PyUnicode_Check(value)) { - value = PyUnicode_AsEncodedString(value, - _ctypes_conversion_encoding, - _ctypes_conversion_errors); - if (value == NULL) - return NULL; - if (PyBytes_GET_SIZE(value) != 1) { - Py_DECREF(value); - goto error; - } - *(char *)ptr = PyBytes_AS_STRING(value)[0]; - Py_DECREF(value); - _RET(value); - } - if (PyBytes_Check(value) && PyBytes_GET_SIZE(value) == 1) { - *(char *)ptr = PyBytes_AS_STRING(value)[0]; - _RET(value); - } - if (PyByteArray_Check(value) && PyByteArray_GET_SIZE(value) == 1) { - *(char *)ptr = PyByteArray_AS_STRING(value)[0]; - _RET(value); - } - if (PyLong_Check(value)) - { - long longval = PyLong_AS_LONG(value); - if (longval < 0 || longval >= 256) - goto error; - *(char *)ptr = (char)longval; - _RET(value); - } + if (PyUnicode_Check(value)) { + value = PyUnicode_AsEncodedString(value, + _ctypes_conversion_encoding, + _ctypes_conversion_errors); + if (value == NULL) + return NULL; + if (PyBytes_GET_SIZE(value) != 1) { + Py_DECREF(value); + goto error; + } + *(char *)ptr = PyBytes_AS_STRING(value)[0]; + Py_DECREF(value); + _RET(value); + } + if (PyBytes_Check(value) && PyBytes_GET_SIZE(value) == 1) { + *(char *)ptr = PyBytes_AS_STRING(value)[0]; + _RET(value); + } + if (PyByteArray_Check(value) && PyByteArray_GET_SIZE(value) == 1) { + *(char *)ptr = PyByteArray_AS_STRING(value)[0]; + _RET(value); + } + if (PyLong_Check(value)) + { + long longval = PyLong_AS_LONG(value); + if (longval < 0 || longval >= 256) + goto error; + *(char *)ptr = (char)longval; + _RET(value); + } error: - PyErr_Format(PyExc_TypeError, - "one character string expected"); - return NULL; + PyErr_Format(PyExc_TypeError, + "one character string expected"); + return NULL; } static PyObject * c_get(void *ptr, Py_ssize_t size) { - return PyBytes_FromStringAndSize((char *)ptr, 1); + return PyBytes_FromStringAndSize((char *)ptr, 1); } #ifdef CTYPES_UNICODE @@ -1216,107 +1216,107 @@ static PyObject * u_set(void *ptr, PyObject *value, Py_ssize_t size) { - Py_ssize_t len; - if (PyBytes_Check(value)) { - value = PyUnicode_FromEncodedObject(value, - _ctypes_conversion_encoding, - _ctypes_conversion_errors); - if (!value) - return NULL; - } else if (!PyUnicode_Check(value)) { - PyErr_Format(PyExc_TypeError, - "unicode string expected instead of %s instance", - value->ob_type->tp_name); - return NULL; - } else - Py_INCREF(value); - - len = PyUnicode_GET_SIZE(value); - if (len != 1) { - Py_DECREF(value); - PyErr_SetString(PyExc_TypeError, - "one character unicode string expected"); - return NULL; - } + Py_ssize_t len; + if (PyBytes_Check(value)) { + value = PyUnicode_FromEncodedObject(value, + _ctypes_conversion_encoding, + _ctypes_conversion_errors); + if (!value) + return NULL; + } else if (!PyUnicode_Check(value)) { + PyErr_Format(PyExc_TypeError, + "unicode string expected instead of %s instance", + value->ob_type->tp_name); + return NULL; + } else + Py_INCREF(value); + + len = PyUnicode_GET_SIZE(value); + if (len != 1) { + Py_DECREF(value); + PyErr_SetString(PyExc_TypeError, + "one character unicode string expected"); + return NULL; + } - *(wchar_t *)ptr = PyUnicode_AS_UNICODE(value)[0]; - Py_DECREF(value); + *(wchar_t *)ptr = PyUnicode_AS_UNICODE(value)[0]; + Py_DECREF(value); - _RET(value); + _RET(value); } static PyObject * u_get(void *ptr, Py_ssize_t size) { - return PyUnicode_FromWideChar((wchar_t *)ptr, 1); + return PyUnicode_FromWideChar((wchar_t *)ptr, 1); } /* U - a unicode string */ static PyObject * U_get(void *ptr, Py_ssize_t size) { - PyObject *result; - Py_ssize_t len; - Py_UNICODE *p; - - size /= sizeof(wchar_t); /* we count character units here, not bytes */ - - result = PyUnicode_FromWideChar((wchar_t *)ptr, size); - if (!result) - return NULL; - /* We need 'result' to be able to count the characters with wcslen, - since ptr may not be NUL terminated. If the length is smaller (if - it was actually NUL terminated, we construct a new one and throw - away the result. - */ - /* chop off at the first NUL character, if any. */ - p = PyUnicode_AS_UNICODE(result); - for (len = 0; len < size; ++len) - if (!p[len]) - break; - - if (len < size) { - PyObject *ob = PyUnicode_FromWideChar((wchar_t *)ptr, len); - Py_DECREF(result); - return ob; - } - return result; + PyObject *result; + Py_ssize_t len; + Py_UNICODE *p; + + size /= sizeof(wchar_t); /* we count character units here, not bytes */ + + result = PyUnicode_FromWideChar((wchar_t *)ptr, size); + if (!result) + return NULL; + /* We need 'result' to be able to count the characters with wcslen, + since ptr may not be NUL terminated. If the length is smaller (if + it was actually NUL terminated, we construct a new one and throw + away the result. + */ + /* chop off at the first NUL character, if any. */ + p = PyUnicode_AS_UNICODE(result); + for (len = 0; len < size; ++len) + if (!p[len]) + break; + + if (len < size) { + PyObject *ob = PyUnicode_FromWideChar((wchar_t *)ptr, len); + Py_DECREF(result); + return ob; + } + return result; } static PyObject * U_set(void *ptr, PyObject *value, Py_ssize_t length) { - Py_ssize_t size; + Py_ssize_t size; - /* It's easier to calculate in characters than in bytes */ - length /= sizeof(wchar_t); + /* It's easier to calculate in characters than in bytes */ + length /= sizeof(wchar_t); - if (PyBytes_Check(value)) { - value = PyUnicode_FromEncodedObject(value, - _ctypes_conversion_encoding, - _ctypes_conversion_errors); - if (!value) - return NULL; - } else if (!PyUnicode_Check(value)) { - PyErr_Format(PyExc_TypeError, - "unicode string expected instead of %s instance", - value->ob_type->tp_name); - return NULL; - } else - Py_INCREF(value); - size = PyUnicode_GET_SIZE(value); - if (size > length) { - PyErr_Format(PyExc_ValueError, - "string too long (%zd, maximum length %zd)", - size, length); - Py_DECREF(value); - return NULL; - } else if (size < length-1) - /* copy terminating NUL character if there is space */ - size += 1; - PyUnicode_AsWideChar((PyUnicodeObject *)value, (wchar_t *)ptr, size); - return value; + if (PyBytes_Check(value)) { + value = PyUnicode_FromEncodedObject(value, + _ctypes_conversion_encoding, + _ctypes_conversion_errors); + if (!value) + return NULL; + } else if (!PyUnicode_Check(value)) { + PyErr_Format(PyExc_TypeError, + "unicode string expected instead of %s instance", + value->ob_type->tp_name); + return NULL; + } else + Py_INCREF(value); + size = PyUnicode_GET_SIZE(value); + if (size > length) { + PyErr_Format(PyExc_ValueError, + "string too long (%zd, maximum length %zd)", + size, length); + Py_DECREF(value); + return NULL; + } else if (size < length-1) + /* copy terminating NUL character if there is space */ + size += 1; + PyUnicode_AsWideChar((PyUnicodeObject *)value, (wchar_t *)ptr, size); + return value; } #endif @@ -1324,210 +1324,210 @@ static PyObject * s_get(void *ptr, Py_ssize_t size) { - Py_ssize_t i; - char *p; + Py_ssize_t i; + char *p; - p = (char *)ptr; - for (i = 0; i < size; ++i) { - if (*p++ == '\0') - break; - } + p = (char *)ptr; + for (i = 0; i < size; ++i) { + if (*p++ == '\0') + break; + } - return PyUnicode_FromStringAndSize((char *)ptr, (Py_ssize_t)i); + return PyUnicode_FromStringAndSize((char *)ptr, (Py_ssize_t)i); } static PyObject * s_set(void *ptr, PyObject *value, Py_ssize_t length) { - char *data; - Py_ssize_t size; + char *data; + Py_ssize_t size; - if (PyUnicode_Check(value)) { - value = PyUnicode_AsEncodedString(value, - _ctypes_conversion_encoding, - _ctypes_conversion_errors); - if (value == NULL) - return NULL; - assert(PyBytes_Check(value)); - } else if(PyBytes_Check(value)) { - Py_INCREF(value); - } else { - PyErr_Format(PyExc_TypeError, - "expected string, %s found", - value->ob_type->tp_name); - return NULL; - } - - data = PyBytes_AS_STRING(value); - if (!data) - return NULL; - size = strlen(data); /* XXX Why not Py_SIZE(value)? */ - if (size < length) { - /* This will copy the leading NUL character - * if there is space for it. - */ - ++size; - } else if (size > length) { - PyErr_Format(PyExc_ValueError, - "string too long (%zd, maximum length %zd)", - size, length); - Py_DECREF(value); - return NULL; - } - /* Also copy the terminating NUL character if there is space */ - memcpy((char *)ptr, data, size); + if (PyUnicode_Check(value)) { + value = PyUnicode_AsEncodedString(value, + _ctypes_conversion_encoding, + _ctypes_conversion_errors); + if (value == NULL) + return NULL; + assert(PyBytes_Check(value)); + } else if(PyBytes_Check(value)) { + Py_INCREF(value); + } else { + PyErr_Format(PyExc_TypeError, + "expected string, %s found", + value->ob_type->tp_name); + return NULL; + } + + data = PyBytes_AS_STRING(value); + if (!data) + return NULL; + size = strlen(data); /* XXX Why not Py_SIZE(value)? */ + if (size < length) { + /* This will copy the leading NUL character + * if there is space for it. + */ + ++size; + } else if (size > length) { + PyErr_Format(PyExc_ValueError, + "string too long (%zd, maximum length %zd)", + size, length); + Py_DECREF(value); + return NULL; + } + /* Also copy the terminating NUL character if there is space */ + memcpy((char *)ptr, data, size); - Py_DECREF(value); - _RET(value); + Py_DECREF(value); + _RET(value); } static PyObject * z_set(void *ptr, PyObject *value, Py_ssize_t size) { - if (value == Py_None) { - *(char **)ptr = NULL; - Py_INCREF(value); - return value; - } - if (PyBytes_Check(value)) { - *(char **)ptr = PyBytes_AsString(value); - Py_INCREF(value); - return value; - } else if (PyUnicode_Check(value)) { - PyObject *str = PyUnicode_AsEncodedString(value, - _ctypes_conversion_encoding, - _ctypes_conversion_errors); - if (str == NULL) - return NULL; - *(char **)ptr = PyBytes_AS_STRING(str); - return str; - } else if (PyLong_Check(value)) { + if (value == Py_None) { + *(char **)ptr = NULL; + Py_INCREF(value); + return value; + } + if (PyBytes_Check(value)) { + *(char **)ptr = PyBytes_AsString(value); + Py_INCREF(value); + return value; + } else if (PyUnicode_Check(value)) { + PyObject *str = PyUnicode_AsEncodedString(value, + _ctypes_conversion_encoding, + _ctypes_conversion_errors); + if (str == NULL) + return NULL; + *(char **)ptr = PyBytes_AS_STRING(str); + return str; + } else if (PyLong_Check(value)) { #if SIZEOF_VOID_P == SIZEOF_LONG_LONG - *(char **)ptr = (char *)PyLong_AsUnsignedLongLongMask(value); + *(char **)ptr = (char *)PyLong_AsUnsignedLongLongMask(value); #else - *(char **)ptr = (char *)PyLong_AsUnsignedLongMask(value); + *(char **)ptr = (char *)PyLong_AsUnsignedLongMask(value); #endif - _RET(value); - } - PyErr_Format(PyExc_TypeError, - "string or integer address expected instead of %s instance", - value->ob_type->tp_name); - return NULL; + _RET(value); + } + PyErr_Format(PyExc_TypeError, + "string or integer address expected instead of %s instance", + value->ob_type->tp_name); + return NULL; } static PyObject * z_get(void *ptr, Py_ssize_t size) { - /* XXX What about invalid pointers ??? */ - if (*(void **)ptr) { + /* XXX What about invalid pointers ??? */ + if (*(void **)ptr) { #if defined(MS_WIN32) && !defined(_WIN32_WCE) - if (IsBadStringPtrA(*(char **)ptr, -1)) { - PyErr_Format(PyExc_ValueError, - "invalid string pointer %p", - *(char **)ptr); - return NULL; - } -#endif - return PyBytes_FromStringAndSize(*(char **)ptr, - strlen(*(char **)ptr)); - } else { - Py_INCREF(Py_None); - return Py_None; - } + if (IsBadStringPtrA(*(char **)ptr, -1)) { + PyErr_Format(PyExc_ValueError, + "invalid string pointer %p", + *(char **)ptr); + return NULL; + } +#endif + return PyBytes_FromStringAndSize(*(char **)ptr, + strlen(*(char **)ptr)); + } else { + Py_INCREF(Py_None); + return Py_None; + } } #ifdef CTYPES_UNICODE static PyObject * Z_set(void *ptr, PyObject *value, Py_ssize_t size) { - if (value == Py_None) { - *(wchar_t **)ptr = NULL; - Py_INCREF(value); - return value; - } - if (PyLong_Check(value) || PyLong_Check(value)) { + if (value == Py_None) { + *(wchar_t **)ptr = NULL; + Py_INCREF(value); + return value; + } + if (PyLong_Check(value) || PyLong_Check(value)) { #if SIZEOF_VOID_P == SIZEOF_LONG_LONG - *(wchar_t **)ptr = (wchar_t *)PyLong_AsUnsignedLongLongMask(value); + *(wchar_t **)ptr = (wchar_t *)PyLong_AsUnsignedLongLongMask(value); #else - *(wchar_t **)ptr = (wchar_t *)PyLong_AsUnsignedLongMask(value); + *(wchar_t **)ptr = (wchar_t *)PyLong_AsUnsignedLongMask(value); #endif - Py_INCREF(Py_None); - return Py_None; - } - if (PyBytes_Check(value)) { - value = PyUnicode_FromEncodedObject(value, - _ctypes_conversion_encoding, - _ctypes_conversion_errors); - if (!value) - return NULL; - } else if (!PyUnicode_Check(value)) { - PyErr_Format(PyExc_TypeError, - "unicode string or integer address expected instead of %s instance", - value->ob_type->tp_name); - return NULL; - } else - Py_INCREF(value); + Py_INCREF(Py_None); + return Py_None; + } + if (PyBytes_Check(value)) { + value = PyUnicode_FromEncodedObject(value, + _ctypes_conversion_encoding, + _ctypes_conversion_errors); + if (!value) + return NULL; + } else if (!PyUnicode_Check(value)) { + PyErr_Format(PyExc_TypeError, + "unicode string or integer address expected instead of %s instance", + value->ob_type->tp_name); + return NULL; + } else + Py_INCREF(value); #ifdef HAVE_USABLE_WCHAR_T - /* HAVE_USABLE_WCHAR_T means that Py_UNICODE and wchar_t is the same - type. So we can copy directly. Hm, are unicode objects always NUL - terminated in Python, internally? - */ - *(wchar_t **)ptr = PyUnicode_AS_UNICODE(value); - return value; + /* HAVE_USABLE_WCHAR_T means that Py_UNICODE and wchar_t is the same + type. So we can copy directly. Hm, are unicode objects always NUL + terminated in Python, internally? + */ + *(wchar_t **)ptr = PyUnicode_AS_UNICODE(value); + return value; #else - { - /* We must create a wchar_t* buffer from the unicode object, - and keep it alive */ - PyObject *keep; - wchar_t *buffer; - - int size = PyUnicode_GET_SIZE(value); - size += 1; /* terminating NUL */ - size *= sizeof(wchar_t); - buffer = (wchar_t *)PyMem_Malloc(size); - if (!buffer) { - Py_DECREF(value); - return PyErr_NoMemory(); - } - memset(buffer, 0, size); - keep = PyCapsule_New(buffer, CTYPES_CFIELD_CAPSULE_NAME_PYMEM, pymem_destructor); - if (!keep) { - Py_DECREF(value); - PyMem_Free(buffer); - return NULL; - } - *(wchar_t **)ptr = (wchar_t *)buffer; - if (-1 == PyUnicode_AsWideChar((PyUnicodeObject *)value, - buffer, PyUnicode_GET_SIZE(value))) { - Py_DECREF(value); - Py_DECREF(keep); - return NULL; - } - Py_DECREF(value); - return keep; - } + { + /* We must create a wchar_t* buffer from the unicode object, + and keep it alive */ + PyObject *keep; + wchar_t *buffer; + + int size = PyUnicode_GET_SIZE(value); + size += 1; /* terminating NUL */ + size *= sizeof(wchar_t); + buffer = (wchar_t *)PyMem_Malloc(size); + if (!buffer) { + Py_DECREF(value); + return PyErr_NoMemory(); + } + memset(buffer, 0, size); + keep = PyCapsule_New(buffer, CTYPES_CFIELD_CAPSULE_NAME_PYMEM, pymem_destructor); + if (!keep) { + Py_DECREF(value); + PyMem_Free(buffer); + return NULL; + } + *(wchar_t **)ptr = (wchar_t *)buffer; + if (-1 == PyUnicode_AsWideChar((PyUnicodeObject *)value, + buffer, PyUnicode_GET_SIZE(value))) { + Py_DECREF(value); + Py_DECREF(keep); + return NULL; + } + Py_DECREF(value); + return keep; + } #endif } static PyObject * Z_get(void *ptr, Py_ssize_t size) { - wchar_t *p; - p = *(wchar_t **)ptr; - if (p) { + wchar_t *p; + p = *(wchar_t **)ptr; + if (p) { #if defined(MS_WIN32) && !defined(_WIN32_WCE) - if (IsBadStringPtrW(*(wchar_t **)ptr, -1)) { - PyErr_Format(PyExc_ValueError, - "invalid string pointer %p", - *(wchar_t **)ptr); - return NULL; - } -#endif - return PyUnicode_FromWideChar(p, wcslen(p)); - } else { - Py_INCREF(Py_None); - return Py_None; - } + if (IsBadStringPtrW(*(wchar_t **)ptr, -1)) { + PyErr_Format(PyExc_ValueError, + "invalid string pointer %p", + *(wchar_t **)ptr); + return NULL; + } +#endif + return PyUnicode_FromWideChar(p, wcslen(p)); + } else { + Py_INCREF(Py_None); + return Py_None; + } } #endif @@ -1535,166 +1535,166 @@ static PyObject * BSTR_set(void *ptr, PyObject *value, Py_ssize_t size) { - BSTR bstr; + BSTR bstr; + + /* convert value into a PyUnicodeObject or NULL */ + if (Py_None == value) { + value = NULL; + } else if (PyBytes_Check(value)) { + value = PyUnicode_FromEncodedObject(value, + _ctypes_conversion_encoding, + _ctypes_conversion_errors); + if (!value) + return NULL; + } else if (PyUnicode_Check(value)) { + Py_INCREF(value); /* for the descref below */ + } else { + PyErr_Format(PyExc_TypeError, + "unicode string expected instead of %s instance", + value->ob_type->tp_name); + return NULL; + } + + /* create a BSTR from value */ + if (value) { + Py_ssize_t size = PyUnicode_GET_SIZE(value); + if ((unsigned) size != size) { + PyErr_SetString(PyExc_ValueError, "String too long for BSTR"); + return NULL; + } + bstr = SysAllocStringLen(PyUnicode_AS_UNICODE(value), + (unsigned)size); + Py_DECREF(value); + } else + bstr = NULL; + + /* free the previous contents, if any */ + if (*(BSTR *)ptr) + SysFreeString(*(BSTR *)ptr); - /* convert value into a PyUnicodeObject or NULL */ - if (Py_None == value) { - value = NULL; - } else if (PyBytes_Check(value)) { - value = PyUnicode_FromEncodedObject(value, - _ctypes_conversion_encoding, - _ctypes_conversion_errors); - if (!value) - return NULL; - } else if (PyUnicode_Check(value)) { - Py_INCREF(value); /* for the descref below */ - } else { - PyErr_Format(PyExc_TypeError, - "unicode string expected instead of %s instance", - value->ob_type->tp_name); - return NULL; - } - - /* create a BSTR from value */ - if (value) { - Py_ssize_t size = PyUnicode_GET_SIZE(value); - if ((unsigned) size != size) { - PyErr_SetString(PyExc_ValueError, "String too long for BSTR"); - return NULL; - } - bstr = SysAllocStringLen(PyUnicode_AS_UNICODE(value), - (unsigned)size); - Py_DECREF(value); - } else - bstr = NULL; - - /* free the previous contents, if any */ - if (*(BSTR *)ptr) - SysFreeString(*(BSTR *)ptr); - - /* and store it */ - *(BSTR *)ptr = bstr; + /* and store it */ + *(BSTR *)ptr = bstr; - /* We don't need to keep any other object */ - _RET(value); + /* We don't need to keep any other object */ + _RET(value); } static PyObject * BSTR_get(void *ptr, Py_ssize_t size) { - BSTR p; - p = *(BSTR *)ptr; - if (p) - return PyUnicode_FromWideChar(p, SysStringLen(p)); - else { - /* Hm, it seems NULL pointer and zero length string are the - same in BSTR, see Don Box, p 81 - */ - Py_INCREF(Py_None); - return Py_None; - } + BSTR p; + p = *(BSTR *)ptr; + if (p) + return PyUnicode_FromWideChar(p, SysStringLen(p)); + else { + /* Hm, it seems NULL pointer and zero length string are the + same in BSTR, see Don Box, p 81 + */ + Py_INCREF(Py_None); + return Py_None; + } } #endif static PyObject * P_set(void *ptr, PyObject *value, Py_ssize_t size) { - void *v; - if (value == Py_None) { - *(void **)ptr = NULL; - _RET(value); - } - - if (!PyLong_Check(value) && !PyLong_Check(value)) { - PyErr_SetString(PyExc_TypeError, - "cannot be converted to pointer"); - return NULL; - } + void *v; + if (value == Py_None) { + *(void **)ptr = NULL; + _RET(value); + } + + if (!PyLong_Check(value) && !PyLong_Check(value)) { + PyErr_SetString(PyExc_TypeError, + "cannot be converted to pointer"); + return NULL; + } #if SIZEOF_VOID_P <= SIZEOF_LONG - v = (void *)PyLong_AsUnsignedLongMask(value); + v = (void *)PyLong_AsUnsignedLongMask(value); #else #ifndef HAVE_LONG_LONG # error "PyLong_AsVoidPtr: sizeof(void*) > sizeof(long), but no long long" #elif SIZEOF_LONG_LONG < SIZEOF_VOID_P # error "PyLong_AsVoidPtr: sizeof(PY_LONG_LONG) < sizeof(void*)" #endif - v = (void *)PyLong_AsUnsignedLongLongMask(value); + v = (void *)PyLong_AsUnsignedLongLongMask(value); #endif - if (PyErr_Occurred()) - return NULL; + if (PyErr_Occurred()) + return NULL; - *(void **)ptr = v; - _RET(value); + *(void **)ptr = v; + _RET(value); } static PyObject * P_get(void *ptr, Py_ssize_t size) { - if (*(void **)ptr == NULL) { - Py_INCREF(Py_None); - return Py_None; - } - return PyLong_FromVoidPtr(*(void **)ptr); + if (*(void **)ptr == NULL) { + Py_INCREF(Py_None); + return Py_None; + } + return PyLong_FromVoidPtr(*(void **)ptr); } static struct fielddesc formattable[] = { - { 's', s_set, s_get, &ffi_type_pointer}, - { 'b', b_set, b_get, &ffi_type_schar}, - { 'B', B_set, B_get, &ffi_type_uchar}, - { 'c', c_set, c_get, &ffi_type_schar}, - { 'd', d_set, d_get, &ffi_type_double, d_set_sw, d_get_sw}, - { 'g', g_set, g_get, &ffi_type_longdouble}, - { 'f', f_set, f_get, &ffi_type_float, f_set_sw, f_get_sw}, - { 'h', h_set, h_get, &ffi_type_sshort, h_set_sw, h_get_sw}, - { 'H', H_set, H_get, &ffi_type_ushort, H_set_sw, H_get_sw}, - { 'i', i_set, i_get, &ffi_type_sint, i_set_sw, i_get_sw}, - { 'I', I_set, I_get, &ffi_type_uint, I_set_sw, I_get_sw}, + { 's', s_set, s_get, &ffi_type_pointer}, + { 'b', b_set, b_get, &ffi_type_schar}, + { 'B', B_set, B_get, &ffi_type_uchar}, + { 'c', c_set, c_get, &ffi_type_schar}, + { 'd', d_set, d_get, &ffi_type_double, d_set_sw, d_get_sw}, + { 'g', g_set, g_get, &ffi_type_longdouble}, + { 'f', f_set, f_get, &ffi_type_float, f_set_sw, f_get_sw}, + { 'h', h_set, h_get, &ffi_type_sshort, h_set_sw, h_get_sw}, + { 'H', H_set, H_get, &ffi_type_ushort, H_set_sw, H_get_sw}, + { 'i', i_set, i_get, &ffi_type_sint, i_set_sw, i_get_sw}, + { 'I', I_set, I_get, &ffi_type_uint, I_set_sw, I_get_sw}, /* XXX Hm, sizeof(int) == sizeof(long) doesn't hold on every platform */ /* As soon as we can get rid of the type codes, this is no longer a problem */ #if SIZEOF_LONG == 4 - { 'l', l_set, l_get, &ffi_type_sint32, l_set_sw, l_get_sw}, - { 'L', L_set, L_get, &ffi_type_uint32, L_set_sw, L_get_sw}, + { 'l', l_set, l_get, &ffi_type_sint32, l_set_sw, l_get_sw}, + { 'L', L_set, L_get, &ffi_type_uint32, L_set_sw, L_get_sw}, #elif SIZEOF_LONG == 8 - { 'l', l_set, l_get, &ffi_type_sint64, l_set_sw, l_get_sw}, - { 'L', L_set, L_get, &ffi_type_uint64, L_set_sw, L_get_sw}, + { 'l', l_set, l_get, &ffi_type_sint64, l_set_sw, l_get_sw}, + { 'L', L_set, L_get, &ffi_type_uint64, L_set_sw, L_get_sw}, #else # error #endif #ifdef HAVE_LONG_LONG #if SIZEOF_LONG_LONG == 8 - { 'q', q_set, q_get, &ffi_type_sint64, q_set_sw, q_get_sw}, - { 'Q', Q_set, Q_get, &ffi_type_uint64, Q_set_sw, Q_get_sw}, + { 'q', q_set, q_get, &ffi_type_sint64, q_set_sw, q_get_sw}, + { 'Q', Q_set, Q_get, &ffi_type_uint64, Q_set_sw, Q_get_sw}, #else # error #endif #endif - { 'P', P_set, P_get, &ffi_type_pointer}, - { 'z', z_set, z_get, &ffi_type_pointer}, + { 'P', P_set, P_get, &ffi_type_pointer}, + { 'z', z_set, z_get, &ffi_type_pointer}, #ifdef CTYPES_UNICODE - { 'u', u_set, u_get, NULL}, /* ffi_type set later */ - { 'U', U_set, U_get, &ffi_type_pointer}, - { 'Z', Z_set, Z_get, &ffi_type_pointer}, + { 'u', u_set, u_get, NULL}, /* ffi_type set later */ + { 'U', U_set, U_get, &ffi_type_pointer}, + { 'Z', Z_set, Z_get, &ffi_type_pointer}, #endif #ifdef MS_WIN32 - { 'X', BSTR_set, BSTR_get, &ffi_type_pointer}, - { 'v', vBOOL_set, vBOOL_get, &ffi_type_sshort}, + { 'X', BSTR_set, BSTR_get, &ffi_type_pointer}, + { 'v', vBOOL_set, vBOOL_get, &ffi_type_sshort}, #endif #if SIZEOF__BOOL == 1 - { '?', bool_set, bool_get, &ffi_type_uchar}, /* Also fallback for no native _Bool support */ + { '?', bool_set, bool_get, &ffi_type_uchar}, /* Also fallback for no native _Bool support */ #elif SIZEOF__BOOL == SIZEOF_SHORT - { '?', bool_set, bool_get, &ffi_type_ushort}, + { '?', bool_set, bool_get, &ffi_type_ushort}, #elif SIZEOF__BOOL == SIZEOF_INT - { '?', bool_set, bool_get, &ffi_type_uint, I_set_sw, I_get_sw}, + { '?', bool_set, bool_get, &ffi_type_uint, I_set_sw, I_get_sw}, #elif SIZEOF__BOOL == SIZEOF_LONG - { '?', bool_set, bool_get, &ffi_type_ulong, L_set_sw, L_get_sw}, + { '?', bool_set, bool_get, &ffi_type_ulong, L_set_sw, L_get_sw}, #elif SIZEOF__BOOL == SIZEOF_LONG_LONG - { '?', bool_set, bool_get, &ffi_type_ulong, Q_set_sw, Q_get_sw}, + { '?', bool_set, bool_get, &ffi_type_ulong, Q_set_sw, Q_get_sw}, #endif /* SIZEOF__BOOL */ - { 'O', O_set, O_get, &ffi_type_pointer}, - { 0, NULL, NULL, NULL}, + { 'O', O_set, O_get, &ffi_type_pointer}, + { 0, NULL, NULL, NULL}, }; /* @@ -1705,26 +1705,26 @@ struct fielddesc * _ctypes_get_fielddesc(const char *fmt) { - static int initialized = 0; - struct fielddesc *table = formattable; + static int initialized = 0; + struct fielddesc *table = formattable; - if (!initialized) { - initialized = 1; + if (!initialized) { + initialized = 1; #ifdef CTYPES_UNICODE - if (sizeof(wchar_t) == sizeof(short)) - _ctypes_get_fielddesc("u")->pffi_type = &ffi_type_sshort; - else if (sizeof(wchar_t) == sizeof(int)) - _ctypes_get_fielddesc("u")->pffi_type = &ffi_type_sint; - else if (sizeof(wchar_t) == sizeof(long)) - _ctypes_get_fielddesc("u")->pffi_type = &ffi_type_slong; -#endif - } - - for (; table->code; ++table) { - if (table->code == fmt[0]) - return table; - } - return NULL; + if (sizeof(wchar_t) == sizeof(short)) + _ctypes_get_fielddesc("u")->pffi_type = &ffi_type_sshort; + else if (sizeof(wchar_t) == sizeof(int)) + _ctypes_get_fielddesc("u")->pffi_type = &ffi_type_sint; + else if (sizeof(wchar_t) == sizeof(long)) + _ctypes_get_fielddesc("u")->pffi_type = &ffi_type_slong; +#endif + } + + for (; table->code; ++table) { + if (table->code == fmt[0]) + return table; + } + return NULL; } typedef struct { char c; char x; } s_char; @@ -1768,10 +1768,10 @@ /* from ffi.h: typedef struct _ffi_type { - size_t size; - unsigned short alignment; - unsigned short type; - struct _ffi_type **elements; + size_t size; + unsigned short alignment; + unsigned short type; + struct _ffi_type **elements; } ffi_type; */ @@ -1798,7 +1798,7 @@ #endif /* This is already defined on OSX */ ffi_type ffi_type_longdouble = { sizeof(long double), LONGDOUBLE_ALIGN, - FFI_TYPE_LONGDOUBLE }; + FFI_TYPE_LONGDOUBLE }; ffi_type ffi_type_pointer = { sizeof(void *), VOID_P_ALIGN, FFI_TYPE_POINTER }; Modified: python/branches/py3k/Modules/_ctypes/ctypes.h ============================================================================== --- python/branches/py3k/Modules/_ctypes/ctypes.h (original) +++ python/branches/py3k/Modules/_ctypes/ctypes.h Sun May 9 17:52:27 2010 @@ -21,16 +21,16 @@ difficult in the presence of PyCFuncPtrObject. Maybe later. */ union value { - char c[16]; - short s; - int i; - long l; - float f; - double d; + char c[16]; + short s; + int i; + long l; + float f; + double d; #ifdef HAVE_LONG_LONG - PY_LONG_LONG ll; + PY_LONG_LONG ll; #endif - long double D; + long double D; }; /* @@ -40,67 +40,67 @@ */ struct tagCDataObject { - PyObject_HEAD - char *b_ptr; /* pointer to memory block */ - int b_needsfree; /* need _we_ free the memory? */ - CDataObject *b_base; /* pointer to base object or NULL */ - Py_ssize_t b_size; /* size of memory block in bytes */ - Py_ssize_t b_length; /* number of references we need */ - Py_ssize_t b_index; /* index of this object into base's - b_object list */ - PyObject *b_objects; /* dictionary of references we need to keep, or Py_None */ - union value b_value; + PyObject_HEAD + char *b_ptr; /* pointer to memory block */ + int b_needsfree; /* need _we_ free the memory? */ + CDataObject *b_base; /* pointer to base object or NULL */ + Py_ssize_t b_size; /* size of memory block in bytes */ + Py_ssize_t b_length; /* number of references we need */ + Py_ssize_t b_index; /* index of this object into base's + b_object list */ + PyObject *b_objects; /* dictionary of references we need to keep, or Py_None */ + union value b_value; }; typedef struct { - PyObject_VAR_HEAD - ffi_closure *pcl; /* the C callable */ - ffi_cif cif; - int flags; - PyObject *converters; - PyObject *callable; - PyObject *restype; - SETFUNC setfunc; - ffi_type *ffi_restype; - ffi_type *atypes[1]; + PyObject_VAR_HEAD + ffi_closure *pcl; /* the C callable */ + ffi_cif cif; + int flags; + PyObject *converters; + PyObject *callable; + PyObject *restype; + SETFUNC setfunc; + ffi_type *ffi_restype; + ffi_type *atypes[1]; } CThunkObject; extern PyTypeObject PyCThunk_Type; -#define CThunk_CheckExact(v) ((v)->ob_type == &PyCThunk_Type) +#define CThunk_CheckExact(v) ((v)->ob_type == &PyCThunk_Type) typedef struct { - /* First part identical to tagCDataObject */ - PyObject_HEAD - char *b_ptr; /* pointer to memory block */ - int b_needsfree; /* need _we_ free the memory? */ - CDataObject *b_base; /* pointer to base object or NULL */ - Py_ssize_t b_size; /* size of memory block in bytes */ - Py_ssize_t b_length; /* number of references we need */ - Py_ssize_t b_index; /* index of this object into base's - b_object list */ - PyObject *b_objects; /* list of references we need to keep */ - union value b_value; - /* end of tagCDataObject, additional fields follow */ - - CThunkObject *thunk; - PyObject *callable; - - /* These two fields will override the ones in the type's stgdict if - they are set */ - PyObject *converters; - PyObject *argtypes; - PyObject *restype; - PyObject *checker; - PyObject *errcheck; + /* First part identical to tagCDataObject */ + PyObject_HEAD + char *b_ptr; /* pointer to memory block */ + int b_needsfree; /* need _we_ free the memory? */ + CDataObject *b_base; /* pointer to base object or NULL */ + Py_ssize_t b_size; /* size of memory block in bytes */ + Py_ssize_t b_length; /* number of references we need */ + Py_ssize_t b_index; /* index of this object into base's + b_object list */ + PyObject *b_objects; /* list of references we need to keep */ + union value b_value; + /* end of tagCDataObject, additional fields follow */ + + CThunkObject *thunk; + PyObject *callable; + + /* These two fields will override the ones in the type's stgdict if + they are set */ + PyObject *converters; + PyObject *argtypes; + PyObject *restype; + PyObject *checker; + PyObject *errcheck; #ifdef MS_WIN32 - int index; - GUID *iid; + int index; + GUID *iid; #endif - PyObject *paramflags; + PyObject *paramflags; } PyCFuncPtrObject; extern PyTypeObject PyCStgDict_Type; -#define PyCStgDict_CheckExact(v) ((v)->ob_type == &PyCStgDict_Type) -#define PyCStgDict_Check(v) PyObject_TypeCheck(v, &PyCStgDict_Type) +#define PyCStgDict_CheckExact(v) ((v)->ob_type == &PyCStgDict_Type) +#define PyCStgDict_Check(v) PyObject_TypeCheck(v, &PyCStgDict_Type) extern int PyCStructUnionType_update_stgdict(PyObject *fields, PyObject *type, int isStruct); extern int PyType_stginfo(PyTypeObject *self, Py_ssize_t *psize, Py_ssize_t *palign, Py_ssize_t *plength); @@ -109,12 +109,12 @@ extern PyTypeObject PyCData_Type; -#define CDataObject_CheckExact(v) ((v)->ob_type == &PyCData_Type) -#define CDataObject_Check(v) PyObject_TypeCheck(v, &PyCData_Type) +#define CDataObject_CheckExact(v) ((v)->ob_type == &PyCData_Type) +#define CDataObject_Check(v) PyObject_TypeCheck(v, &PyCData_Type) extern PyTypeObject PyCSimpleType_Type; -#define PyCSimpleTypeObject_CheckExact(v) ((v)->ob_type == &PyCSimpleType_Type) -#define PyCSimpleTypeObject_Check(v) PyObject_TypeCheck(v, &PyCSimpleType_Type) +#define PyCSimpleTypeObject_CheckExact(v) ((v)->ob_type == &PyCSimpleType_Type) +#define PyCSimpleTypeObject_Check(v) PyObject_TypeCheck(v, &PyCSimpleType_Type) extern PyTypeObject PyCField_Type; extern struct fielddesc *_ctypes_get_fielddesc(const char *fmt); @@ -122,9 +122,9 @@ extern PyObject * PyCField_FromDesc(PyObject *desc, Py_ssize_t index, - Py_ssize_t *pfield_size, int bitsize, int *pbitofs, - Py_ssize_t *psize, Py_ssize_t *poffset, Py_ssize_t *palign, - int pack, int is_big_endian); + Py_ssize_t *pfield_size, int bitsize, int *pbitofs, + Py_ssize_t *psize, Py_ssize_t *poffset, Py_ssize_t *palign, + int pack, int is_big_endian); extern PyObject *PyCData_AtAddress(PyObject *type, void *buf); extern PyObject *PyCData_FromBytes(PyObject *type, char *data, Py_ssize_t length); @@ -137,13 +137,13 @@ extern PyTypeObject PyCFuncPtrType_Type; extern PyTypeObject PyCStructType_Type; -#define PyCArrayTypeObject_Check(v) PyObject_TypeCheck(v, &PyCArrayType_Type) -#define ArrayObject_Check(v) PyObject_TypeCheck(v, &PyCArray_Type) -#define PointerObject_Check(v) PyObject_TypeCheck(v, &PyCPointer_Type) -#define PyCPointerTypeObject_Check(v) PyObject_TypeCheck(v, &PyCPointerType_Type) -#define PyCFuncPtrObject_Check(v) PyObject_TypeCheck(v, &PyCFuncPtr_Type) -#define PyCFuncPtrTypeObject_Check(v) PyObject_TypeCheck(v, &PyCFuncPtrType_Type) -#define PyCStructTypeObject_Check(v) PyObject_TypeCheck(v, &PyCStructType_Type) +#define PyCArrayTypeObject_Check(v) PyObject_TypeCheck(v, &PyCArrayType_Type) +#define ArrayObject_Check(v) PyObject_TypeCheck(v, &PyCArray_Type) +#define PointerObject_Check(v) PyObject_TypeCheck(v, &PyCPointer_Type) +#define PyCPointerTypeObject_Check(v) PyObject_TypeCheck(v, &PyCPointerType_Type) +#define PyCFuncPtrObject_Check(v) PyObject_TypeCheck(v, &PyCFuncPtr_Type) +#define PyCFuncPtrTypeObject_Check(v) PyObject_TypeCheck(v, &PyCFuncPtrType_Type) +#define PyCStructTypeObject_Check(v) PyObject_TypeCheck(v, &PyCStructType_Type) extern PyObject * PyCArrayType_from_ctype(PyObject *itemtype, Py_ssize_t length); @@ -151,35 +151,35 @@ extern PyMethodDef _ctypes_module_methods[]; extern CThunkObject *_ctypes_alloc_callback(PyObject *callable, - PyObject *converters, - PyObject *restype, - int flags); + PyObject *converters, + PyObject *restype, + int flags); /* a table entry describing a predefined ctypes type */ struct fielddesc { - char code; - SETFUNC setfunc; - GETFUNC getfunc; - ffi_type *pffi_type; /* always statically allocated */ - SETFUNC setfunc_swapped; - GETFUNC getfunc_swapped; + char code; + SETFUNC setfunc; + GETFUNC getfunc; + ffi_type *pffi_type; /* always statically allocated */ + SETFUNC setfunc_swapped; + GETFUNC getfunc_swapped; }; typedef struct { - PyObject_HEAD - Py_ssize_t offset; - Py_ssize_t size; - Py_ssize_t index; /* Index into CDataObject's - object array */ - PyObject *proto; /* a type or NULL */ - GETFUNC getfunc; /* getter function if proto is NULL */ - SETFUNC setfunc; /* setter function if proto is NULL */ - int anonymous; + PyObject_HEAD + Py_ssize_t offset; + Py_ssize_t size; + Py_ssize_t index; /* Index into CDataObject's + object array */ + PyObject *proto; /* a type or NULL */ + GETFUNC getfunc; /* getter function if proto is NULL */ + SETFUNC setfunc; /* setter function if proto is NULL */ + int anonymous; } CFieldObject; /* A subclass of PyDictObject, used as the instance dictionary of ctypes metatypes */ typedef struct { - PyDictObject dict; /* first part identical to PyDictObject */ + PyDictObject dict; /* first part identical to PyDictObject */ /* The size and align fields are unneeded, they are in ffi_type as well. As an experiment shows, it's trivial to get rid of them, the only thing to remember is that in PyCArrayType_new the ffi_type fields must be filled in - @@ -188,28 +188,28 @@ too much risk to change that now, and there are other fields which doen't belong into this structure anyway. Maybe in ctypes 2.0... (ctypes 2000?) */ - Py_ssize_t size; /* number of bytes */ - Py_ssize_t align; /* alignment requirements */ - Py_ssize_t length; /* number of fields */ - ffi_type ffi_type_pointer; - PyObject *proto; /* Only for Pointer/ArrayObject */ - SETFUNC setfunc; /* Only for simple objects */ - GETFUNC getfunc; /* Only for simple objects */ - PARAMFUNC paramfunc; - - /* Following fields only used by PyCFuncPtrType_Type instances */ - PyObject *argtypes; /* tuple of CDataObjects */ - PyObject *converters; /* tuple([t.from_param for t in argtypes]) */ - PyObject *restype; /* CDataObject or NULL */ - PyObject *checker; - int flags; /* calling convention and such */ - - /* pep3118 fields, pointers neeed PyMem_Free */ - char *format; - int ndim; - Py_ssize_t *shape; -/* Py_ssize_t *strides; */ /* unused in ctypes */ -/* Py_ssize_t *suboffsets; */ /* unused in ctypes */ + Py_ssize_t size; /* number of bytes */ + Py_ssize_t align; /* alignment requirements */ + Py_ssize_t length; /* number of fields */ + ffi_type ffi_type_pointer; + PyObject *proto; /* Only for Pointer/ArrayObject */ + SETFUNC setfunc; /* Only for simple objects */ + GETFUNC getfunc; /* Only for simple objects */ + PARAMFUNC paramfunc; + + /* Following fields only used by PyCFuncPtrType_Type instances */ + PyObject *argtypes; /* tuple of CDataObjects */ + PyObject *converters; /* tuple([t.from_param for t in argtypes]) */ + PyObject *restype; /* CDataObject or NULL */ + PyObject *checker; + int flags; /* calling convention and such */ + + /* pep3118 fields, pointers neeed PyMem_Free */ + char *format; + int ndim; + Py_ssize_t *shape; +/* Py_ssize_t *strides; */ /* unused in ctypes */ +/* Py_ssize_t *suboffsets; */ /* unused in ctypes */ } StgDictObject; @@ -264,16 +264,16 @@ typedef int(* PPROC)(void); PyObject *_ctypes_callproc(PPROC pProc, - PyObject *arguments, + PyObject *arguments, #ifdef MS_WIN32 - IUnknown *pIUnk, - GUID *iid, + IUnknown *pIUnk, + GUID *iid, #endif - int flags, - PyObject *argtypes, - PyObject *restype, - PyObject *checker); - + int flags, + PyObject *argtypes, + PyObject *restype, + PyObject *checker); + #define FUNCFLAG_STDCALL 0x0 #define FUNCFLAG_CDECL 0x1 @@ -288,45 +288,45 @@ #define DICTFLAG_FINAL 0x1000 struct tagPyCArgObject { - PyObject_HEAD - ffi_type *pffi_type; - char tag; - union { - char c; - char b; - short h; - int i; - long l; + PyObject_HEAD + ffi_type *pffi_type; + char tag; + union { + char c; + char b; + short h; + int i; + long l; #ifdef HAVE_LONG_LONG - PY_LONG_LONG q; + PY_LONG_LONG q; #endif - long double D; - double d; - float f; - void *p; - } value; - PyObject *obj; - Py_ssize_t size; /* for the 'V' tag */ + long double D; + double d; + float f; + void *p; + } value; + PyObject *obj; + Py_ssize_t size; /* for the 'V' tag */ }; extern PyTypeObject PyCArg_Type; -#define PyCArg_CheckExact(v) ((v)->ob_type == &PyCArg_Type) +#define PyCArg_CheckExact(v) ((v)->ob_type == &PyCArg_Type) extern PyCArgObject *PyCArgObject_new(void); extern PyObject * PyCData_get(PyObject *type, GETFUNC getfunc, PyObject *src, - Py_ssize_t index, Py_ssize_t size, char *ptr); + Py_ssize_t index, Py_ssize_t size, char *ptr); extern int PyCData_set(PyObject *dst, PyObject *type, SETFUNC setfunc, PyObject *value, - Py_ssize_t index, Py_ssize_t size, char *ptr); + Py_ssize_t index, Py_ssize_t size, char *ptr); extern void _ctypes_extend_error(PyObject *exc_class, char *fmt, ...); struct basespec { - CDataObject *base; - Py_ssize_t index; - char *adr; + CDataObject *base; + Py_ssize_t index; + char *adr; }; extern char basespec_string[]; Modified: python/branches/py3k/Modules/_ctypes/darwin/dlfcn_simple.c ============================================================================== --- python/branches/py3k/Modules/_ctypes/darwin/dlfcn_simple.c (original) +++ python/branches/py3k/Modules/_ctypes/darwin/dlfcn_simple.c Sun May 9 17:52:27 2010 @@ -81,167 +81,167 @@ /* Set and get the error string for use by dlerror */ static const char *error(int setget, const char *str, ...) { - static char errstr[ERR_STR_LEN]; - static int err_filled = 0; - const char *retval; - va_list arg; - if (setget == 0) - { - va_start(arg, str); - strncpy(errstr, "dlcompat: ", ERR_STR_LEN); - vsnprintf(errstr + 10, ERR_STR_LEN - 10, str, arg); - va_end(arg); - err_filled = 1; - retval = NULL; - } - else - { - if (!err_filled) - retval = NULL; - else - retval = errstr; - err_filled = 0; - } - return retval; + static char errstr[ERR_STR_LEN]; + static int err_filled = 0; + const char *retval; + va_list arg; + if (setget == 0) + { + va_start(arg, str); + strncpy(errstr, "dlcompat: ", ERR_STR_LEN); + vsnprintf(errstr + 10, ERR_STR_LEN - 10, str, arg); + va_end(arg); + err_filled = 1; + retval = NULL; + } + else + { + if (!err_filled) + retval = NULL; + else + retval = errstr; + err_filled = 0; + } + return retval; } /* darwin_dlopen */ static void *darwin_dlopen(const char *path, int mode) { - void *module = 0; - NSObjectFileImage ofi = 0; - NSObjectFileImageReturnCode ofirc; - - /* If we got no path, the app wants the global namespace, use -1 as the marker - in this case */ - if (!path) - return (void *)-1; - - /* Create the object file image, works for things linked with the -bundle arg to ld */ - ofirc = NSCreateObjectFileImageFromFile(path, &ofi); - switch (ofirc) - { - case NSObjectFileImageSuccess: - /* It was okay, so use NSLinkModule to link in the image */ - module = NSLinkModule(ofi, path, - NSLINKMODULE_OPTION_RETURN_ON_ERROR - | (mode & RTLD_GLOBAL) ? 0 : NSLINKMODULE_OPTION_PRIVATE - | (mode & RTLD_LAZY) ? 0 : NSLINKMODULE_OPTION_BINDNOW); - NSDestroyObjectFileImage(ofi); - break; - case NSObjectFileImageInappropriateFile: - /* It may have been a dynamic library rather than a bundle, try to load it */ - module = (void *)NSAddImage(path, NSADDIMAGE_OPTION_RETURN_ON_ERROR); - break; - default: - /* God knows what we got */ - error(0, "Can not open \"%s\"", path); - return 0; - } - if (!module) - error(0, "Can not open \"%s\"", path); - return module; + void *module = 0; + NSObjectFileImage ofi = 0; + NSObjectFileImageReturnCode ofirc; + + /* If we got no path, the app wants the global namespace, use -1 as the marker + in this case */ + if (!path) + return (void *)-1; + + /* Create the object file image, works for things linked with the -bundle arg to ld */ + ofirc = NSCreateObjectFileImageFromFile(path, &ofi); + switch (ofirc) + { + case NSObjectFileImageSuccess: + /* It was okay, so use NSLinkModule to link in the image */ + module = NSLinkModule(ofi, path, + NSLINKMODULE_OPTION_RETURN_ON_ERROR + | (mode & RTLD_GLOBAL) ? 0 : NSLINKMODULE_OPTION_PRIVATE + | (mode & RTLD_LAZY) ? 0 : NSLINKMODULE_OPTION_BINDNOW); + NSDestroyObjectFileImage(ofi); + break; + case NSObjectFileImageInappropriateFile: + /* It may have been a dynamic library rather than a bundle, try to load it */ + module = (void *)NSAddImage(path, NSADDIMAGE_OPTION_RETURN_ON_ERROR); + break; + default: + /* God knows what we got */ + error(0, "Can not open \"%s\"", path); + return 0; + } + if (!module) + error(0, "Can not open \"%s\"", path); + return module; } /* dlsymIntern is used by dlsym to find the symbol */ static void *dlsymIntern(void *handle, const char *symbol) { - NSSymbol nssym = 0; - /* If the handle is -1, if is the app global context */ - if (handle == (void *)-1) - { - /* Global context, use NSLookupAndBindSymbol */ - if (NSIsSymbolNameDefined(symbol)) - { - nssym = NSLookupAndBindSymbol(symbol); - } - - } - /* Now see if the handle is a struch mach_header* or not, use NSLookupSymbol in image - for libraries, and NSLookupSymbolInModule for bundles */ - else - { - /* Check for both possible magic numbers depending on x86/ppc byte order */ - if ((((struct mach_header *)handle)->magic == MH_MAGIC) || - (((struct mach_header *)handle)->magic == MH_CIGAM)) - { - if (NSIsSymbolNameDefinedInImage((struct mach_header *)handle, symbol)) - { - nssym = NSLookupSymbolInImage((struct mach_header *)handle, - symbol, - NSLOOKUPSYMBOLINIMAGE_OPTION_BIND - | NSLOOKUPSYMBOLINIMAGE_OPTION_RETURN_ON_ERROR); - } - - } - else - { - nssym = NSLookupSymbolInModule(handle, symbol); - } - } - if (!nssym) - { - error(0, "Symbol \"%s\" Not found", symbol); - return NULL; - } - return NSAddressOfSymbol(nssym); + NSSymbol nssym = 0; + /* If the handle is -1, if is the app global context */ + if (handle == (void *)-1) + { + /* Global context, use NSLookupAndBindSymbol */ + if (NSIsSymbolNameDefined(symbol)) + { + nssym = NSLookupAndBindSymbol(symbol); + } + + } + /* Now see if the handle is a struch mach_header* or not, use NSLookupSymbol in image + for libraries, and NSLookupSymbolInModule for bundles */ + else + { + /* Check for both possible magic numbers depending on x86/ppc byte order */ + if ((((struct mach_header *)handle)->magic == MH_MAGIC) || + (((struct mach_header *)handle)->magic == MH_CIGAM)) + { + if (NSIsSymbolNameDefinedInImage((struct mach_header *)handle, symbol)) + { + nssym = NSLookupSymbolInImage((struct mach_header *)handle, + symbol, + NSLOOKUPSYMBOLINIMAGE_OPTION_BIND + | NSLOOKUPSYMBOLINIMAGE_OPTION_RETURN_ON_ERROR); + } + + } + else + { + nssym = NSLookupSymbolInModule(handle, symbol); + } + } + if (!nssym) + { + error(0, "Symbol \"%s\" Not found", symbol); + return NULL; + } + return NSAddressOfSymbol(nssym); } static const char *darwin_dlerror(void) { - return error(1, (char *)NULL); + return error(1, (char *)NULL); } static int darwin_dlclose(void *handle) { - if ((((struct mach_header *)handle)->magic == MH_MAGIC) || - (((struct mach_header *)handle)->magic == MH_CIGAM)) - { - error(0, "Can't remove dynamic libraries on darwin"); - return 0; - } - if (!NSUnLinkModule(handle, 0)) - { - error(0, "unable to unlink module %s", NSNameOfModule(handle)); - return 1; - } - return 0; + if ((((struct mach_header *)handle)->magic == MH_MAGIC) || + (((struct mach_header *)handle)->magic == MH_CIGAM)) + { + error(0, "Can't remove dynamic libraries on darwin"); + return 0; + } + if (!NSUnLinkModule(handle, 0)) + { + error(0, "unable to unlink module %s", NSNameOfModule(handle)); + return 1; + } + return 0; } /* dlsym, prepend the underscore and call dlsymIntern */ static void *darwin_dlsym(void *handle, const char *symbol) { - static char undersym[257]; /* Saves calls to malloc(3) */ - int sym_len = strlen(symbol); - void *value = NULL; - char *malloc_sym = NULL; - - if (sym_len < 256) - { - snprintf(undersym, 256, "_%s", symbol); - value = dlsymIntern(handle, undersym); - } - else - { - malloc_sym = malloc(sym_len + 2); - if (malloc_sym) - { - sprintf(malloc_sym, "_%s", symbol); - value = dlsymIntern(handle, malloc_sym); - free(malloc_sym); - } - else - { - error(0, "Unable to allocate memory"); - } - } - return value; + static char undersym[257]; /* Saves calls to malloc(3) */ + int sym_len = strlen(symbol); + void *value = NULL; + char *malloc_sym = NULL; + + if (sym_len < 256) + { + snprintf(undersym, 256, "_%s", symbol); + value = dlsymIntern(handle, undersym); + } + else + { + malloc_sym = malloc(sym_len + 2); + if (malloc_sym) + { + sprintf(malloc_sym, "_%s", symbol); + value = dlsymIntern(handle, malloc_sym); + free(malloc_sym); + } + else + { + error(0, "Unable to allocate memory"); + } + } + return value; } static int darwin_dladdr(const void *handle, Dl_info *info) { - return 0; + return 0; } #endif /* MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_3 */ @@ -252,21 +252,21 @@ static #endif void ctypes_dlfcn_init(void) { - if (dlopen != NULL) { - ctypes_dlsym = dlsym; - ctypes_dlopen = dlopen; - ctypes_dlerror = dlerror; - ctypes_dlclose = dlclose; - ctypes_dladdr = dladdr; - } else { + if (dlopen != NULL) { + ctypes_dlsym = dlsym; + ctypes_dlopen = dlopen; + ctypes_dlerror = dlerror; + ctypes_dlclose = dlclose; + ctypes_dladdr = dladdr; + } else { #if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_3 - ctypes_dlsym = darwin_dlsym; - ctypes_dlopen = darwin_dlopen; - ctypes_dlerror = darwin_dlerror; - ctypes_dlclose = darwin_dlclose; - ctypes_dladdr = darwin_dladdr; + ctypes_dlsym = darwin_dlsym; + ctypes_dlopen = darwin_dlopen; + ctypes_dlerror = darwin_dlerror; + ctypes_dlclose = darwin_dlclose; + ctypes_dladdr = darwin_dladdr; #endif /* MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_3 */ - } + } } #endif /* CTYPES_DARWIN_DLFCN */ Modified: python/branches/py3k/Modules/_ctypes/malloc_closure.c ============================================================================== --- python/branches/py3k/Modules/_ctypes/malloc_closure.c (original) +++ python/branches/py3k/Modules/_ctypes/malloc_closure.c Sun May 9 17:52:27 2010 @@ -23,8 +23,8 @@ /******************************************************************/ typedef union _tagITEM { - ffi_closure closure; - union _tagITEM *next; + ffi_closure closure; + union _tagITEM *next; } ITEM; static ITEM *free_list; @@ -32,58 +32,58 @@ static void more_core(void) { - ITEM *item; - int count, i; + ITEM *item; + int count, i; /* determine the pagesize */ #ifdef MS_WIN32 - if (!_pagesize) { - SYSTEM_INFO systeminfo; - GetSystemInfo(&systeminfo); - _pagesize = systeminfo.dwPageSize; - } + if (!_pagesize) { + SYSTEM_INFO systeminfo; + GetSystemInfo(&systeminfo); + _pagesize = systeminfo.dwPageSize; + } #else - if (!_pagesize) { + if (!_pagesize) { #ifdef _SC_PAGESIZE - _pagesize = sysconf(_SC_PAGESIZE); + _pagesize = sysconf(_SC_PAGESIZE); #else - _pagesize = getpagesize(); + _pagesize = getpagesize(); #endif - } + } #endif - /* calculate the number of nodes to allocate */ - count = BLOCKSIZE / sizeof(ITEM); + /* calculate the number of nodes to allocate */ + count = BLOCKSIZE / sizeof(ITEM); - /* allocate a memory block */ + /* allocate a memory block */ #ifdef MS_WIN32 - item = (ITEM *)VirtualAlloc(NULL, - count * sizeof(ITEM), - MEM_COMMIT, - PAGE_EXECUTE_READWRITE); - if (item == NULL) - return; + item = (ITEM *)VirtualAlloc(NULL, + count * sizeof(ITEM), + MEM_COMMIT, + PAGE_EXECUTE_READWRITE); + if (item == NULL) + return; #else - item = (ITEM *)mmap(NULL, - count * sizeof(ITEM), - PROT_READ | PROT_WRITE | PROT_EXEC, - MAP_PRIVATE | MAP_ANONYMOUS, - -1, - 0); - if (item == (void *)MAP_FAILED) - return; + item = (ITEM *)mmap(NULL, + count * sizeof(ITEM), + PROT_READ | PROT_WRITE | PROT_EXEC, + MAP_PRIVATE | MAP_ANONYMOUS, + -1, + 0); + if (item == (void *)MAP_FAILED) + return; #endif #ifdef MALLOC_CLOSURE_DEBUG - printf("block at %p allocated (%d bytes), %d ITEMs\n", - item, count * sizeof(ITEM), count); + printf("block at %p allocated (%d bytes), %d ITEMs\n", + item, count * sizeof(ITEM), count); #endif - /* put them into the free list */ - for (i = 0; i < count; ++i) { - item->next = free_list; - free_list = item; - ++item; - } + /* put them into the free list */ + for (i = 0; i < count; ++i) { + item->next = free_list; + free_list = item; + ++item; + } } /******************************************************************/ @@ -91,20 +91,20 @@ /* put the item back into the free list */ void _ctypes_free_closure(void *p) { - ITEM *item = (ITEM *)p; - item->next = free_list; - free_list = item; + ITEM *item = (ITEM *)p; + item->next = free_list; + free_list = item; } /* return one item from the free list, allocating more if needed */ void *_ctypes_alloc_closure(void) { - ITEM *item; - if (!free_list) - more_core(); - if (!free_list) - return NULL; - item = free_list; - free_list = item->next; - return item; + ITEM *item; + if (!free_list) + more_core(); + if (!free_list) + return NULL; + item = free_list; + free_list = item->next; + return item; } Modified: python/branches/py3k/Modules/_ctypes/stgdict.c ============================================================================== --- python/branches/py3k/Modules/_ctypes/stgdict.c (original) +++ python/branches/py3k/Modules/_ctypes/stgdict.c Sun May 9 17:52:27 2010 @@ -19,143 +19,143 @@ static int PyCStgDict_init(StgDictObject *self, PyObject *args, PyObject *kwds) { - if (PyDict_Type.tp_init((PyObject *)self, args, kwds) < 0) - return -1; - self->format = NULL; - self->ndim = 0; - self->shape = NULL; - return 0; + if (PyDict_Type.tp_init((PyObject *)self, args, kwds) < 0) + return -1; + self->format = NULL; + self->ndim = 0; + self->shape = NULL; + return 0; } static int PyCStgDict_clear(StgDictObject *self) { - Py_CLEAR(self->proto); - Py_CLEAR(self->argtypes); - Py_CLEAR(self->converters); - Py_CLEAR(self->restype); - Py_CLEAR(self->checker); - return 0; + Py_CLEAR(self->proto); + Py_CLEAR(self->argtypes); + Py_CLEAR(self->converters); + Py_CLEAR(self->restype); + Py_CLEAR(self->checker); + return 0; } static void PyCStgDict_dealloc(StgDictObject *self) { - PyCStgDict_clear(self); - PyMem_Free(self->format); - PyMem_Free(self->shape); - PyMem_Free(self->ffi_type_pointer.elements); - PyDict_Type.tp_dealloc((PyObject *)self); + PyCStgDict_clear(self); + PyMem_Free(self->format); + PyMem_Free(self->shape); + PyMem_Free(self->ffi_type_pointer.elements); + PyDict_Type.tp_dealloc((PyObject *)self); } int PyCStgDict_clone(StgDictObject *dst, StgDictObject *src) { - char *d, *s; - Py_ssize_t size; + char *d, *s; + Py_ssize_t size; - PyCStgDict_clear(dst); - PyMem_Free(dst->ffi_type_pointer.elements); - PyMem_Free(dst->format); - dst->format = NULL; - PyMem_Free(dst->shape); - dst->shape = NULL; - dst->ffi_type_pointer.elements = NULL; - - d = (char *)dst; - s = (char *)src; - memcpy(d + sizeof(PyDictObject), - s + sizeof(PyDictObject), - sizeof(StgDictObject) - sizeof(PyDictObject)); - - Py_XINCREF(dst->proto); - Py_XINCREF(dst->argtypes); - Py_XINCREF(dst->converters); - Py_XINCREF(dst->restype); - Py_XINCREF(dst->checker); - - if (src->format) { - dst->format = PyMem_Malloc(strlen(src->format) + 1); - if (dst->format == NULL) - return -1; - strcpy(dst->format, src->format); - } - if (src->shape) { - dst->shape = PyMem_Malloc(sizeof(Py_ssize_t) * src->ndim); - if (dst->shape == NULL) - return -1; - memcpy(dst->shape, src->shape, - sizeof(Py_ssize_t) * src->ndim); - } - - if (src->ffi_type_pointer.elements == NULL) - return 0; - size = sizeof(ffi_type *) * (src->length + 1); - dst->ffi_type_pointer.elements = PyMem_Malloc(size); - if (dst->ffi_type_pointer.elements == NULL) { - PyErr_NoMemory(); - return -1; - } - memcpy(dst->ffi_type_pointer.elements, - src->ffi_type_pointer.elements, - size); - return 0; + PyCStgDict_clear(dst); + PyMem_Free(dst->ffi_type_pointer.elements); + PyMem_Free(dst->format); + dst->format = NULL; + PyMem_Free(dst->shape); + dst->shape = NULL; + dst->ffi_type_pointer.elements = NULL; + + d = (char *)dst; + s = (char *)src; + memcpy(d + sizeof(PyDictObject), + s + sizeof(PyDictObject), + sizeof(StgDictObject) - sizeof(PyDictObject)); + + Py_XINCREF(dst->proto); + Py_XINCREF(dst->argtypes); + Py_XINCREF(dst->converters); + Py_XINCREF(dst->restype); + Py_XINCREF(dst->checker); + + if (src->format) { + dst->format = PyMem_Malloc(strlen(src->format) + 1); + if (dst->format == NULL) + return -1; + strcpy(dst->format, src->format); + } + if (src->shape) { + dst->shape = PyMem_Malloc(sizeof(Py_ssize_t) * src->ndim); + if (dst->shape == NULL) + return -1; + memcpy(dst->shape, src->shape, + sizeof(Py_ssize_t) * src->ndim); + } + + if (src->ffi_type_pointer.elements == NULL) + return 0; + size = sizeof(ffi_type *) * (src->length + 1); + dst->ffi_type_pointer.elements = PyMem_Malloc(size); + if (dst->ffi_type_pointer.elements == NULL) { + PyErr_NoMemory(); + return -1; + } + memcpy(dst->ffi_type_pointer.elements, + src->ffi_type_pointer.elements, + size); + return 0; } PyTypeObject PyCStgDict_Type = { - PyVarObject_HEAD_INIT(NULL, 0) - "StgDict", - sizeof(StgDictObject), - 0, - (destructor)PyCStgDict_dealloc, /* tp_dealloc */ - 0, /* tp_print */ - 0, /* tp_getattr */ - 0, /* tp_setattr */ - 0, /* tp_reserved */ - 0, /* tp_repr */ - 0, /* tp_as_number */ - 0, /* tp_as_sequence */ - 0, /* tp_as_mapping */ - 0, /* tp_hash */ - 0, /* tp_call */ - 0, /* tp_str */ - 0, /* tp_getattro */ - 0, /* tp_setattro */ - 0, /* tp_as_buffer */ - Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */ - 0, /* tp_doc */ - 0, /* tp_traverse */ - 0, /* tp_clear */ - 0, /* tp_richcompare */ - 0, /* tp_weaklistoffset */ - 0, /* tp_iter */ - 0, /* tp_iternext */ - 0, /* tp_methods */ - 0, /* tp_members */ - 0, /* tp_getset */ - 0, /* tp_base */ - 0, /* tp_dict */ - 0, /* tp_descr_get */ - 0, /* tp_descr_set */ - 0, /* tp_dictoffset */ - (initproc)PyCStgDict_init, /* tp_init */ - 0, /* tp_alloc */ - 0, /* tp_new */ - 0, /* tp_free */ + PyVarObject_HEAD_INIT(NULL, 0) + "StgDict", + sizeof(StgDictObject), + 0, + (destructor)PyCStgDict_dealloc, /* tp_dealloc */ + 0, /* tp_print */ + 0, /* tp_getattr */ + 0, /* tp_setattr */ + 0, /* tp_reserved */ + 0, /* tp_repr */ + 0, /* tp_as_number */ + 0, /* tp_as_sequence */ + 0, /* tp_as_mapping */ + 0, /* tp_hash */ + 0, /* tp_call */ + 0, /* tp_str */ + 0, /* tp_getattro */ + 0, /* tp_setattro */ + 0, /* tp_as_buffer */ + Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */ + 0, /* tp_doc */ + 0, /* tp_traverse */ + 0, /* tp_clear */ + 0, /* tp_richcompare */ + 0, /* tp_weaklistoffset */ + 0, /* tp_iter */ + 0, /* tp_iternext */ + 0, /* tp_methods */ + 0, /* tp_members */ + 0, /* tp_getset */ + 0, /* tp_base */ + 0, /* tp_dict */ + 0, /* tp_descr_get */ + 0, /* tp_descr_set */ + 0, /* tp_dictoffset */ + (initproc)PyCStgDict_init, /* tp_init */ + 0, /* tp_alloc */ + 0, /* tp_new */ + 0, /* tp_free */ }; /* May return NULL, but does not set an exception! */ StgDictObject * PyType_stgdict(PyObject *obj) { - PyTypeObject *type; + PyTypeObject *type; - if (!PyType_Check(obj)) - return NULL; - type = (PyTypeObject *)obj; - if (!type->tp_dict || !PyCStgDict_CheckExact(type->tp_dict)) - return NULL; - return (StgDictObject *)type->tp_dict; + if (!PyType_Check(obj)) + return NULL; + type = (PyTypeObject *)obj; + if (!type->tp_dict || !PyCStgDict_CheckExact(type->tp_dict)) + return NULL; + return (StgDictObject *)type->tp_dict; } /* May return NULL, but does not set an exception! */ @@ -166,10 +166,10 @@ StgDictObject * PyObject_stgdict(PyObject *self) { - PyTypeObject *type = self->ob_type; - if (!type->tp_dict || !PyCStgDict_CheckExact(type->tp_dict)) - return NULL; - return (StgDictObject *)type->tp_dict; + PyTypeObject *type = self->ob_type; + if (!type->tp_dict || !PyCStgDict_CheckExact(type->tp_dict)) + return NULL; + return (StgDictObject *)type->tp_dict; } /* descr is the descriptor for a field marked as anonymous. Get all the @@ -178,78 +178,78 @@ */ static int MakeFields(PyObject *type, CFieldObject *descr, - Py_ssize_t index, Py_ssize_t offset) + Py_ssize_t index, Py_ssize_t offset) { - Py_ssize_t i; - PyObject *fields; - PyObject *fieldlist; - - fields = PyObject_GetAttrString(descr->proto, "_fields_"); - if (fields == NULL) - return -1; - fieldlist = PySequence_Fast(fields, "_fields_ must be a sequence"); - Py_DECREF(fields); - if (fieldlist == NULL) - return -1; - - for (i = 0; i < PySequence_Fast_GET_SIZE(fieldlist); ++i) { - PyObject *pair = PySequence_Fast_GET_ITEM(fieldlist, i); /* borrowed */ - PyObject *fname, *ftype, *bits; - CFieldObject *fdescr; - CFieldObject *new_descr; - /* Convert to PyArg_UnpackTuple... */ - if (!PyArg_ParseTuple(pair, "OO|O", &fname, &ftype, &bits)) { - Py_DECREF(fieldlist); - return -1; - } - fdescr = (CFieldObject *)PyObject_GetAttr(descr->proto, fname); - if (fdescr == NULL) { - Py_DECREF(fieldlist); - return -1; - } - if (Py_TYPE(fdescr) != &PyCField_Type) { - PyErr_SetString(PyExc_TypeError, "unexpected type"); - Py_DECREF(fdescr); - Py_DECREF(fieldlist); - return -1; - } - if (fdescr->anonymous) { - int rc = MakeFields(type, fdescr, - index + fdescr->index, - offset + fdescr->offset); - Py_DECREF(fdescr); - if (rc == -1) { - Py_DECREF(fieldlist); - return -1; - } - continue; - } - new_descr = (CFieldObject *)PyObject_CallObject((PyObject *)&PyCField_Type, NULL); - if (new_descr == NULL) { - Py_DECREF(fdescr); - Py_DECREF(fieldlist); - return -1; - } - assert(Py_TYPE(new_descr) == &PyCField_Type); - new_descr->size = fdescr->size; - new_descr->offset = fdescr->offset + offset; - new_descr->index = fdescr->index + index; - new_descr->proto = fdescr->proto; - Py_XINCREF(new_descr->proto); - new_descr->getfunc = fdescr->getfunc; - new_descr->setfunc = fdescr->setfunc; - - Py_DECREF(fdescr); - - if (-1 == PyObject_SetAttr(type, fname, (PyObject *)new_descr)) { - Py_DECREF(fieldlist); - Py_DECREF(new_descr); - return -1; - } - Py_DECREF(new_descr); - } - Py_DECREF(fieldlist); - return 0; + Py_ssize_t i; + PyObject *fields; + PyObject *fieldlist; + + fields = PyObject_GetAttrString(descr->proto, "_fields_"); + if (fields == NULL) + return -1; + fieldlist = PySequence_Fast(fields, "_fields_ must be a sequence"); + Py_DECREF(fields); + if (fieldlist == NULL) + return -1; + + for (i = 0; i < PySequence_Fast_GET_SIZE(fieldlist); ++i) { + PyObject *pair = PySequence_Fast_GET_ITEM(fieldlist, i); /* borrowed */ + PyObject *fname, *ftype, *bits; + CFieldObject *fdescr; + CFieldObject *new_descr; + /* Convert to PyArg_UnpackTuple... */ + if (!PyArg_ParseTuple(pair, "OO|O", &fname, &ftype, &bits)) { + Py_DECREF(fieldlist); + return -1; + } + fdescr = (CFieldObject *)PyObject_GetAttr(descr->proto, fname); + if (fdescr == NULL) { + Py_DECREF(fieldlist); + return -1; + } + if (Py_TYPE(fdescr) != &PyCField_Type) { + PyErr_SetString(PyExc_TypeError, "unexpected type"); + Py_DECREF(fdescr); + Py_DECREF(fieldlist); + return -1; + } + if (fdescr->anonymous) { + int rc = MakeFields(type, fdescr, + index + fdescr->index, + offset + fdescr->offset); + Py_DECREF(fdescr); + if (rc == -1) { + Py_DECREF(fieldlist); + return -1; + } + continue; + } + new_descr = (CFieldObject *)PyObject_CallObject((PyObject *)&PyCField_Type, NULL); + if (new_descr == NULL) { + Py_DECREF(fdescr); + Py_DECREF(fieldlist); + return -1; + } + assert(Py_TYPE(new_descr) == &PyCField_Type); + new_descr->size = fdescr->size; + new_descr->offset = fdescr->offset + offset; + new_descr->index = fdescr->index + index; + new_descr->proto = fdescr->proto; + Py_XINCREF(new_descr->proto); + new_descr->getfunc = fdescr->getfunc; + new_descr->setfunc = fdescr->setfunc; + + Py_DECREF(fdescr); + + if (-1 == PyObject_SetAttr(type, fname, (PyObject *)new_descr)) { + Py_DECREF(fieldlist); + Py_DECREF(new_descr); + return -1; + } + Py_DECREF(new_descr); + } + Py_DECREF(fieldlist); + return 0; } /* Iterate over the names in the type's _anonymous_ attribute, if present, @@ -257,43 +257,43 @@ static int MakeAnonFields(PyObject *type) { - PyObject *anon; - PyObject *anon_names; - Py_ssize_t i; - - anon = PyObject_GetAttrString(type, "_anonymous_"); - if (anon == NULL) { - PyErr_Clear(); - return 0; - } - anon_names = PySequence_Fast(anon, "_anonymous_ must be a sequence"); - Py_DECREF(anon); - if (anon_names == NULL) - return -1; - - for (i = 0; i < PySequence_Fast_GET_SIZE(anon_names); ++i) { - PyObject *fname = PySequence_Fast_GET_ITEM(anon_names, i); /* borrowed */ - CFieldObject *descr = (CFieldObject *)PyObject_GetAttr(type, fname); - if (descr == NULL) { - Py_DECREF(anon_names); - return -1; - } - assert(Py_TYPE(descr) == &PyCField_Type); - descr->anonymous = 1; - - /* descr is in the field descriptor. */ - if (-1 == MakeFields(type, (CFieldObject *)descr, - ((CFieldObject *)descr)->index, - ((CFieldObject *)descr)->offset)) { - Py_DECREF(descr); - Py_DECREF(anon_names); - return -1; - } - Py_DECREF(descr); - } + PyObject *anon; + PyObject *anon_names; + Py_ssize_t i; + + anon = PyObject_GetAttrString(type, "_anonymous_"); + if (anon == NULL) { + PyErr_Clear(); + return 0; + } + anon_names = PySequence_Fast(anon, "_anonymous_ must be a sequence"); + Py_DECREF(anon); + if (anon_names == NULL) + return -1; + + for (i = 0; i < PySequence_Fast_GET_SIZE(anon_names); ++i) { + PyObject *fname = PySequence_Fast_GET_ITEM(anon_names, i); /* borrowed */ + CFieldObject *descr = (CFieldObject *)PyObject_GetAttr(type, fname); + if (descr == NULL) { + Py_DECREF(anon_names); + return -1; + } + assert(Py_TYPE(descr) == &PyCField_Type); + descr->anonymous = 1; + + /* descr is in the field descriptor. */ + if (-1 == MakeFields(type, (CFieldObject *)descr, + ((CFieldObject *)descr)->index, + ((CFieldObject *)descr)->offset)) { + Py_DECREF(descr); + Py_DECREF(anon_names); + return -1; + } + Py_DECREF(descr); + } - Py_DECREF(anon_names); - return 0; + Py_DECREF(anon_names); + return 0; } /* @@ -303,261 +303,261 @@ int PyCStructUnionType_update_stgdict(PyObject *type, PyObject *fields, int isStruct) { - StgDictObject *stgdict, *basedict; - Py_ssize_t len, offset, size, align, i; - Py_ssize_t union_size, total_align; - Py_ssize_t field_size = 0; - int bitofs; - PyObject *isPacked; - int pack = 0; - Py_ssize_t ffi_ofs; - int big_endian; - - /* HACK Alert: I cannot be bothered to fix ctypes.com, so there has to - be a way to use the old, broken sematics: _fields_ are not extended - but replaced in subclasses. - - XXX Remove this in ctypes 1.0! - */ - int use_broken_old_ctypes_semantics; + StgDictObject *stgdict, *basedict; + Py_ssize_t len, offset, size, align, i; + Py_ssize_t union_size, total_align; + Py_ssize_t field_size = 0; + int bitofs; + PyObject *isPacked; + int pack = 0; + Py_ssize_t ffi_ofs; + int big_endian; + + /* HACK Alert: I cannot be bothered to fix ctypes.com, so there has to + be a way to use the old, broken sematics: _fields_ are not extended + but replaced in subclasses. + + XXX Remove this in ctypes 1.0! + */ + int use_broken_old_ctypes_semantics; - if (fields == NULL) - return 0; + if (fields == NULL) + return 0; #ifdef WORDS_BIGENDIAN - big_endian = PyObject_HasAttrString(type, "_swappedbytes_") ? 0 : 1; + big_endian = PyObject_HasAttrString(type, "_swappedbytes_") ? 0 : 1; #else - big_endian = PyObject_HasAttrString(type, "_swappedbytes_") ? 1 : 0; + big_endian = PyObject_HasAttrString(type, "_swappedbytes_") ? 1 : 0; #endif - use_broken_old_ctypes_semantics = \ - PyObject_HasAttrString(type, "_use_broken_old_ctypes_structure_semantics_"); + use_broken_old_ctypes_semantics = \ + PyObject_HasAttrString(type, "_use_broken_old_ctypes_structure_semantics_"); - isPacked = PyObject_GetAttrString(type, "_pack_"); - if (isPacked) { - pack = PyLong_AsLong(isPacked); - if (pack < 0 || PyErr_Occurred()) { - Py_XDECREF(isPacked); - PyErr_SetString(PyExc_ValueError, - "_pack_ must be a non-negative integer"); - return -1; - } - Py_DECREF(isPacked); - } else - PyErr_Clear(); - - len = PySequence_Length(fields); - if (len == -1) { - PyErr_SetString(PyExc_TypeError, - "'_fields_' must be a sequence of pairs"); - return -1; - } - - stgdict = PyType_stgdict(type); - if (!stgdict) - return -1; - /* If this structure/union is already marked final we cannot assign - _fields_ anymore. */ - - if (stgdict->flags & DICTFLAG_FINAL) {/* is final ? */ - PyErr_SetString(PyExc_AttributeError, - "_fields_ is final"); - return -1; - } - - if (stgdict->format) { - PyMem_Free(stgdict->format); - stgdict->format = NULL; - } - - if (stgdict->ffi_type_pointer.elements) - PyMem_Free(stgdict->ffi_type_pointer.elements); - - basedict = PyType_stgdict((PyObject *)((PyTypeObject *)type)->tp_base); - if (basedict && !use_broken_old_ctypes_semantics) { - size = offset = basedict->size; - align = basedict->align; - union_size = 0; - total_align = align ? align : 1; - stgdict->ffi_type_pointer.type = FFI_TYPE_STRUCT; - stgdict->ffi_type_pointer.elements = PyMem_Malloc(sizeof(ffi_type *) * (basedict->length + len + 1)); - if (stgdict->ffi_type_pointer.elements == NULL) { - PyErr_NoMemory(); - return -1; - } - memset(stgdict->ffi_type_pointer.elements, 0, - sizeof(ffi_type *) * (basedict->length + len + 1)); - memcpy(stgdict->ffi_type_pointer.elements, - basedict->ffi_type_pointer.elements, - sizeof(ffi_type *) * (basedict->length)); - ffi_ofs = basedict->length; - } else { - offset = 0; - size = 0; - align = 0; - union_size = 0; - total_align = 1; - stgdict->ffi_type_pointer.type = FFI_TYPE_STRUCT; - stgdict->ffi_type_pointer.elements = PyMem_Malloc(sizeof(ffi_type *) * (len + 1)); - if (stgdict->ffi_type_pointer.elements == NULL) { - PyErr_NoMemory(); - return -1; - } - memset(stgdict->ffi_type_pointer.elements, 0, - sizeof(ffi_type *) * (len + 1)); - ffi_ofs = 0; - } - - assert(stgdict->format == NULL); - if (isStruct && !isPacked) { - stgdict->format = _ctypes_alloc_format_string(NULL, "T{"); - } else { - /* PEP3118 doesn't support union, or packed structures (well, - only standard packing, but we dont support the pep for - that). Use 'B' for bytes. */ - stgdict->format = _ctypes_alloc_format_string(NULL, "B"); - } + isPacked = PyObject_GetAttrString(type, "_pack_"); + if (isPacked) { + pack = PyLong_AsLong(isPacked); + if (pack < 0 || PyErr_Occurred()) { + Py_XDECREF(isPacked); + PyErr_SetString(PyExc_ValueError, + "_pack_ must be a non-negative integer"); + return -1; + } + Py_DECREF(isPacked); + } else + PyErr_Clear(); + + len = PySequence_Length(fields); + if (len == -1) { + PyErr_SetString(PyExc_TypeError, + "'_fields_' must be a sequence of pairs"); + return -1; + } + + stgdict = PyType_stgdict(type); + if (!stgdict) + return -1; + /* If this structure/union is already marked final we cannot assign + _fields_ anymore. */ + + if (stgdict->flags & DICTFLAG_FINAL) {/* is final ? */ + PyErr_SetString(PyExc_AttributeError, + "_fields_ is final"); + return -1; + } + + if (stgdict->format) { + PyMem_Free(stgdict->format); + stgdict->format = NULL; + } + + if (stgdict->ffi_type_pointer.elements) + PyMem_Free(stgdict->ffi_type_pointer.elements); + + basedict = PyType_stgdict((PyObject *)((PyTypeObject *)type)->tp_base); + if (basedict && !use_broken_old_ctypes_semantics) { + size = offset = basedict->size; + align = basedict->align; + union_size = 0; + total_align = align ? align : 1; + stgdict->ffi_type_pointer.type = FFI_TYPE_STRUCT; + stgdict->ffi_type_pointer.elements = PyMem_Malloc(sizeof(ffi_type *) * (basedict->length + len + 1)); + if (stgdict->ffi_type_pointer.elements == NULL) { + PyErr_NoMemory(); + return -1; + } + memset(stgdict->ffi_type_pointer.elements, 0, + sizeof(ffi_type *) * (basedict->length + len + 1)); + memcpy(stgdict->ffi_type_pointer.elements, + basedict->ffi_type_pointer.elements, + sizeof(ffi_type *) * (basedict->length)); + ffi_ofs = basedict->length; + } else { + offset = 0; + size = 0; + align = 0; + union_size = 0; + total_align = 1; + stgdict->ffi_type_pointer.type = FFI_TYPE_STRUCT; + stgdict->ffi_type_pointer.elements = PyMem_Malloc(sizeof(ffi_type *) * (len + 1)); + if (stgdict->ffi_type_pointer.elements == NULL) { + PyErr_NoMemory(); + return -1; + } + memset(stgdict->ffi_type_pointer.elements, 0, + sizeof(ffi_type *) * (len + 1)); + ffi_ofs = 0; + } + + assert(stgdict->format == NULL); + if (isStruct && !isPacked) { + stgdict->format = _ctypes_alloc_format_string(NULL, "T{"); + } else { + /* PEP3118 doesn't support union, or packed structures (well, + only standard packing, but we dont support the pep for + that). Use 'B' for bytes. */ + stgdict->format = _ctypes_alloc_format_string(NULL, "B"); + } #define realdict ((PyObject *)&stgdict->dict) - for (i = 0; i < len; ++i) { - PyObject *name = NULL, *desc = NULL; - PyObject *pair = PySequence_GetItem(fields, i); - PyObject *prop; - StgDictObject *dict; - int bitsize = 0; - - if (!pair || !PyArg_ParseTuple(pair, "OO|i", &name, &desc, &bitsize)) { - PyErr_SetString(PyExc_AttributeError, - "'_fields_' must be a sequence of pairs"); - Py_XDECREF(pair); - return -1; - } - dict = PyType_stgdict(desc); - if (dict == NULL) { - Py_DECREF(pair); - PyErr_Format(PyExc_TypeError, - "second item in _fields_ tuple (index %zd) must be a C type", - i); - return -1; - } - stgdict->ffi_type_pointer.elements[ffi_ofs + i] = &dict->ffi_type_pointer; - if (dict->flags & (TYPEFLAG_ISPOINTER | TYPEFLAG_HASPOINTER)) - stgdict->flags |= TYPEFLAG_HASPOINTER; - dict->flags |= DICTFLAG_FINAL; /* mark field type final */ - if (PyTuple_Size(pair) == 3) { /* bits specified */ - switch(dict->ffi_type_pointer.type) { - case FFI_TYPE_UINT8: - case FFI_TYPE_UINT16: - case FFI_TYPE_UINT32: - case FFI_TYPE_SINT64: - case FFI_TYPE_UINT64: - break; - - case FFI_TYPE_SINT8: - case FFI_TYPE_SINT16: - case FFI_TYPE_SINT32: - if (dict->getfunc != _ctypes_get_fielddesc("c")->getfunc + for (i = 0; i < len; ++i) { + PyObject *name = NULL, *desc = NULL; + PyObject *pair = PySequence_GetItem(fields, i); + PyObject *prop; + StgDictObject *dict; + int bitsize = 0; + + if (!pair || !PyArg_ParseTuple(pair, "OO|i", &name, &desc, &bitsize)) { + PyErr_SetString(PyExc_AttributeError, + "'_fields_' must be a sequence of pairs"); + Py_XDECREF(pair); + return -1; + } + dict = PyType_stgdict(desc); + if (dict == NULL) { + Py_DECREF(pair); + PyErr_Format(PyExc_TypeError, + "second item in _fields_ tuple (index %zd) must be a C type", + i); + return -1; + } + stgdict->ffi_type_pointer.elements[ffi_ofs + i] = &dict->ffi_type_pointer; + if (dict->flags & (TYPEFLAG_ISPOINTER | TYPEFLAG_HASPOINTER)) + stgdict->flags |= TYPEFLAG_HASPOINTER; + dict->flags |= DICTFLAG_FINAL; /* mark field type final */ + if (PyTuple_Size(pair) == 3) { /* bits specified */ + switch(dict->ffi_type_pointer.type) { + case FFI_TYPE_UINT8: + case FFI_TYPE_UINT16: + case FFI_TYPE_UINT32: + case FFI_TYPE_SINT64: + case FFI_TYPE_UINT64: + break; + + case FFI_TYPE_SINT8: + case FFI_TYPE_SINT16: + case FFI_TYPE_SINT32: + if (dict->getfunc != _ctypes_get_fielddesc("c")->getfunc #ifdef CTYPES_UNICODE - && dict->getfunc != _ctypes_get_fielddesc("u")->getfunc + && dict->getfunc != _ctypes_get_fielddesc("u")->getfunc #endif - ) - break; - /* else fall through */ - default: - PyErr_Format(PyExc_TypeError, - "bit fields not allowed for type %s", - ((PyTypeObject *)desc)->tp_name); - Py_DECREF(pair); - return -1; - } - if (bitsize <= 0 || bitsize > dict->size * 8) { - PyErr_SetString(PyExc_ValueError, - "number of bits invalid for bit field"); - Py_DECREF(pair); - return -1; - } - } else - bitsize = 0; - if (isStruct && !isPacked) { - char *fieldfmt = dict->format ? dict->format : "B"; - char *fieldname = _PyUnicode_AsString(name); - char *ptr; - Py_ssize_t len = strlen(fieldname) + strlen(fieldfmt); - char *buf = alloca(len + 2 + 1); - - sprintf(buf, "%s:%s:", fieldfmt, fieldname); - - ptr = stgdict->format; - stgdict->format = _ctypes_alloc_format_string(stgdict->format, buf); - PyMem_Free(ptr); - - if (stgdict->format == NULL) { - Py_DECREF(pair); - return -1; - } - } - if (isStruct) { - prop = PyCField_FromDesc(desc, i, - &field_size, bitsize, &bitofs, - &size, &offset, &align, - pack, big_endian); - } else /* union */ { - size = 0; - offset = 0; - align = 0; - prop = PyCField_FromDesc(desc, i, - &field_size, bitsize, &bitofs, - &size, &offset, &align, - pack, big_endian); - union_size = max(size, union_size); - } - total_align = max(align, total_align); - - if (!prop) { - Py_DECREF(pair); - return -1; - } - if (-1 == PyObject_SetAttr(type, name, prop)) { - Py_DECREF(prop); - Py_DECREF(pair); - return -1; - } - Py_DECREF(pair); - Py_DECREF(prop); - } + ) + break; + /* else fall through */ + default: + PyErr_Format(PyExc_TypeError, + "bit fields not allowed for type %s", + ((PyTypeObject *)desc)->tp_name); + Py_DECREF(pair); + return -1; + } + if (bitsize <= 0 || bitsize > dict->size * 8) { + PyErr_SetString(PyExc_ValueError, + "number of bits invalid for bit field"); + Py_DECREF(pair); + return -1; + } + } else + bitsize = 0; + if (isStruct && !isPacked) { + char *fieldfmt = dict->format ? dict->format : "B"; + char *fieldname = _PyUnicode_AsString(name); + char *ptr; + Py_ssize_t len = strlen(fieldname) + strlen(fieldfmt); + char *buf = alloca(len + 2 + 1); + + sprintf(buf, "%s:%s:", fieldfmt, fieldname); + + ptr = stgdict->format; + stgdict->format = _ctypes_alloc_format_string(stgdict->format, buf); + PyMem_Free(ptr); + + if (stgdict->format == NULL) { + Py_DECREF(pair); + return -1; + } + } + if (isStruct) { + prop = PyCField_FromDesc(desc, i, + &field_size, bitsize, &bitofs, + &size, &offset, &align, + pack, big_endian); + } else /* union */ { + size = 0; + offset = 0; + align = 0; + prop = PyCField_FromDesc(desc, i, + &field_size, bitsize, &bitofs, + &size, &offset, &align, + pack, big_endian); + union_size = max(size, union_size); + } + total_align = max(align, total_align); + + if (!prop) { + Py_DECREF(pair); + return -1; + } + if (-1 == PyObject_SetAttr(type, name, prop)) { + Py_DECREF(prop); + Py_DECREF(pair); + return -1; + } + Py_DECREF(pair); + Py_DECREF(prop); + } #undef realdict - if (isStruct && !isPacked) { - char *ptr = stgdict->format; - stgdict->format = _ctypes_alloc_format_string(stgdict->format, "}"); - PyMem_Free(ptr); - if (stgdict->format == NULL) - return -1; - } - - if (!isStruct) - size = union_size; - - /* Adjust the size according to the alignment requirements */ - size = ((size + total_align - 1) / total_align) * total_align; - - stgdict->ffi_type_pointer.alignment = Py_SAFE_DOWNCAST(total_align, - Py_ssize_t, - unsigned short); - stgdict->ffi_type_pointer.size = size; - - stgdict->size = size; - stgdict->align = total_align; - stgdict->length = len; /* ADD ffi_ofs? */ - - /* We did check that this flag was NOT set above, it must not - have been set until now. */ - if (stgdict->flags & DICTFLAG_FINAL) { - PyErr_SetString(PyExc_AttributeError, - "Structure or union cannot contain itself"); - return -1; - } - stgdict->flags |= DICTFLAG_FINAL; + if (isStruct && !isPacked) { + char *ptr = stgdict->format; + stgdict->format = _ctypes_alloc_format_string(stgdict->format, "}"); + PyMem_Free(ptr); + if (stgdict->format == NULL) + return -1; + } + + if (!isStruct) + size = union_size; + + /* Adjust the size according to the alignment requirements */ + size = ((size + total_align - 1) / total_align) * total_align; + + stgdict->ffi_type_pointer.alignment = Py_SAFE_DOWNCAST(total_align, + Py_ssize_t, + unsigned short); + stgdict->ffi_type_pointer.size = size; + + stgdict->size = size; + stgdict->align = total_align; + stgdict->length = len; /* ADD ffi_ofs? */ + + /* We did check that this flag was NOT set above, it must not + have been set until now. */ + if (stgdict->flags & DICTFLAG_FINAL) { + PyErr_SetString(PyExc_AttributeError, + "Structure or union cannot contain itself"); + return -1; + } + stgdict->flags |= DICTFLAG_FINAL; - return MakeAnonFields(type); + return MakeAnonFields(type); } Modified: python/branches/py3k/Modules/_curses_panel.c ============================================================================== --- python/branches/py3k/Modules/_curses_panel.c (original) +++ python/branches/py3k/Modules/_curses_panel.c Sun May 9 17:52:27 2010 @@ -22,7 +22,7 @@ /* Utility Functions */ /* - * Check the return code from a curses function and return None + * Check the return code from a curses function and return None * or raise an exception as appropriate. */ @@ -30,15 +30,15 @@ PyCursesCheckERR(int code, char *fname) { if (code != ERR) { - Py_INCREF(Py_None); - return Py_None; + Py_INCREF(Py_None); + return Py_None; } else { - if (fname == NULL) { - PyErr_SetString(PyCursesError, catchall_ERR); - } else { - PyErr_Format(PyCursesError, "%s() returned ERR", fname); - } - return NULL; + if (fname == NULL) { + PyErr_SetString(PyCursesError, catchall_ERR); + } else { + PyErr_Format(PyCursesError, "%s() returned ERR", fname); + } + return NULL; } } @@ -51,12 +51,12 @@ typedef struct { PyObject_HEAD PANEL *pan; - PyCursesWindowObject *wo; /* for reference counts */ + PyCursesWindowObject *wo; /* for reference counts */ } PyCursesPanelObject; PyTypeObject PyCursesPanel_Type; -#define PyCursesPanel_Check(v) (Py_TYPE(v) == &PyCursesPanel_Type) +#define PyCursesPanel_Check(v) (Py_TYPE(v) == &PyCursesPanel_Type) /* Some helper functions. The problem is that there's always a window associated with a panel. To ensure that Python's GC doesn't pull @@ -88,10 +88,10 @@ insert_lop(PyCursesPanelObject *po) { list_of_panels *new; - + if ((new = (list_of_panels *)malloc(sizeof(list_of_panels))) == NULL) { - PyErr_NoMemory(); - return -1; + PyErr_NoMemory(); + return -1; } new->po = po; new->next = lop; @@ -107,17 +107,17 @@ temp = lop; if (temp->po == po) { - lop = temp->next; - free(temp); - return; + lop = temp->next; + free(temp); + return; } while (temp->next == NULL || temp->next->po != po) { - if (temp->next == NULL) { - PyErr_SetString(PyExc_RuntimeError, - "remove_lop: can't find Panel Object"); - return; - } - temp = temp->next; + if (temp->next == NULL) { + PyErr_SetString(PyExc_RuntimeError, + "remove_lop: can't find Panel Object"); + return; + } + temp = temp->next; } n = temp->next->next; free(temp->next); @@ -131,7 +131,7 @@ { list_of_panels *temp; for (temp = lop; temp->po->pan != pan; temp = temp->next) - if (temp->next == NULL) return NULL; /* not found!? */ + if (temp->next == NULL) return NULL; /* not found!? */ return temp->po; } @@ -179,9 +179,9 @@ if (po == NULL) return NULL; po->pan = pan; if (insert_lop(po) < 0) { - po->wo = NULL; - Py_DECREF(po); - return NULL; + po->wo = NULL; + Py_DECREF(po); + return NULL; } po->wo = wo; Py_INCREF(wo); @@ -193,8 +193,8 @@ { (void)del_panel(po->pan); if (po->wo != NULL) { - Py_DECREF(po->wo); - remove_lop(po); + Py_DECREF(po->wo); + remove_lop(po); } PyObject_DEL(po); } @@ -206,19 +206,19 @@ { PANEL *pan; PyCursesPanelObject *po; - + pan = panel_above(self->pan); - if (pan == NULL) { /* valid output, it means the calling panel - is on top of the stack */ - Py_INCREF(Py_None); - return Py_None; + if (pan == NULL) { /* valid output, it means the calling panel + is on top of the stack */ + Py_INCREF(Py_None); + return Py_None; } po = find_po(pan); if (po == NULL) { - PyErr_SetString(PyExc_RuntimeError, - "panel_above: can't find Panel Object"); - return NULL; + PyErr_SetString(PyExc_RuntimeError, + "panel_above: can't find Panel Object"); + return NULL; } Py_INCREF(po); return (PyObject *)po; @@ -231,19 +231,19 @@ { PANEL *pan; PyCursesPanelObject *po; - + pan = panel_below(self->pan); - - if (pan == NULL) { /* valid output, it means the calling panel - is on the bottom of the stack */ - Py_INCREF(Py_None); - return Py_None; + + if (pan == NULL) { /* valid output, it means the calling panel + is on the bottom of the stack */ + Py_INCREF(Py_None); + return Py_None; } po = find_po(pan); if (po == NULL) { - PyErr_SetString(PyExc_RuntimeError, - "panel_below: can't find Panel Object"); - return NULL; + PyErr_SetString(PyExc_RuntimeError, + "panel_below: can't find Panel Object"); + return NULL; } Py_INCREF(po); return (PyObject *)po; @@ -262,26 +262,26 @@ PyCursesPanelObject *po; PyCursesWindowObject *temp; int rtn; - + if (PyTuple_Size(args) != 1) { - PyErr_SetString(PyExc_TypeError, "replace requires one argument"); - return NULL; + PyErr_SetString(PyExc_TypeError, "replace requires one argument"); + return NULL; } if (!PyArg_ParseTuple(args, "O!;window object", - &PyCursesWindow_Type, &temp)) - return NULL; + &PyCursesWindow_Type, &temp)) + return NULL; po = find_po(self->pan); if (po == NULL) { - PyErr_SetString(PyExc_RuntimeError, - "replace_panel: can't find Panel Object"); - return NULL; + PyErr_SetString(PyExc_RuntimeError, + "replace_panel: can't find Panel Object"); + return NULL; } rtn = replace_panel(self->pan, temp->win); if (rtn == ERR) { - PyErr_SetString(PyCursesError, "replace_panel() returned ERR"); - return NULL; + PyErr_SetString(PyCursesError, "replace_panel() returned ERR"); + return NULL; } Py_DECREF(po->wo); po->wo = temp; @@ -302,11 +302,11 @@ PyCursesPanel_userptr(PyCursesPanelObject *self) { PyObject *obj; - PyCursesInitialised; + PyCursesInitialised; obj = (PyObject *) panel_userptr(self->pan); if (obj == NULL) { - PyErr_SetString(PyCursesError, "no userptr set"); - return NULL; + PyErr_SetString(PyCursesError, "no userptr set"); + return NULL; } Py_INCREF(obj); @@ -329,40 +329,40 @@ {"top", (PyCFunction)PyCursesPanel_top_panel, METH_NOARGS}, {"userptr", (PyCFunction)PyCursesPanel_userptr, METH_NOARGS}, {"window", (PyCFunction)PyCursesPanel_window, METH_NOARGS}, - {NULL, NULL} /* sentinel */ + {NULL, NULL} /* sentinel */ }; /* -------------------------------------------------------*/ PyTypeObject PyCursesPanel_Type = { PyVarObject_HEAD_INIT(NULL, 0) - "_curses_panel.curses panel", /*tp_name*/ - sizeof(PyCursesPanelObject), /*tp_basicsize*/ - 0, /*tp_itemsize*/ + "_curses_panel.curses panel", /*tp_name*/ + sizeof(PyCursesPanelObject), /*tp_basicsize*/ + 0, /*tp_itemsize*/ /* methods */ (destructor)PyCursesPanel_Dealloc, /*tp_dealloc*/ - 0, /*tp_print*/ - 0, /*tp_getattr*/ - 0, /*tp_setattr*/ - 0, /*tp_reserved*/ - 0, /*tp_repr*/ - 0, /*tp_as_number*/ - 0, /*tp_as_sequence*/ - 0, /*tp_as_mapping*/ - 0, /*tp_hash*/ - 0, /*tp_call*/ - 0, /*tp_str*/ - 0, /*tp_getattro*/ - 0, /*tp_setattro*/ - 0, /*tp_as_buffer*/ + 0, /*tp_print*/ + 0, /*tp_getattr*/ + 0, /*tp_setattr*/ + 0, /*tp_reserved*/ + 0, /*tp_repr*/ + 0, /*tp_as_number*/ + 0, /*tp_as_sequence*/ + 0, /*tp_as_mapping*/ + 0, /*tp_hash*/ + 0, /*tp_call*/ + 0, /*tp_str*/ + 0, /*tp_getattro*/ + 0, /*tp_setattro*/ + 0, /*tp_as_buffer*/ Py_TPFLAGS_DEFAULT, /*tp_flags*/ - 0, /*tp_doc*/ - 0, /*tp_traverse*/ - 0, /*tp_clear*/ - 0, /*tp_richcompare*/ - 0, /*tp_weaklistoffset*/ - 0, /*tp_iter*/ - 0, /*tp_iternext*/ + 0, /*tp_doc*/ + 0, /*tp_traverse*/ + 0, /*tp_clear*/ + 0, /*tp_richcompare*/ + 0, /*tp_weaklistoffset*/ + 0, /*tp_iter*/ + 0, /*tp_iternext*/ PyCursesPanel_Methods, /*tp_methods*/ }; @@ -380,16 +380,16 @@ pan = panel_above(NULL); - if (pan == NULL) { /* valid output, it means - there's no panel at all */ - Py_INCREF(Py_None); - return Py_None; + if (pan == NULL) { /* valid output, it means + there's no panel at all */ + Py_INCREF(Py_None); + return Py_None; } po = find_po(pan); if (po == NULL) { - PyErr_SetString(PyExc_RuntimeError, - "panel_above: can't find Panel Object"); - return NULL; + PyErr_SetString(PyExc_RuntimeError, + "panel_above: can't find Panel Object"); + return NULL; } Py_INCREF(po); return (PyObject *)po; @@ -405,8 +405,8 @@ return NULL; pan = new_panel(win->win); if (pan == NULL) { - PyErr_SetString(PyCursesError, catchall_NULL); - return NULL; + PyErr_SetString(PyCursesError, catchall_NULL); + return NULL; } return (PyObject *)PyCursesPanel_New(pan, win); } @@ -421,28 +421,28 @@ { PANEL *pan; PyCursesPanelObject *po; - + PyCursesInitialised; pan = panel_below(NULL); - if (pan == NULL) { /* valid output, it means - there's no panel at all */ - Py_INCREF(Py_None); - return Py_None; + if (pan == NULL) { /* valid output, it means + there's no panel at all */ + Py_INCREF(Py_None); + return Py_None; } po = find_po(pan); if (po == NULL) { - PyErr_SetString(PyExc_RuntimeError, - "panel_below: can't find Panel Object"); - return NULL; + PyErr_SetString(PyExc_RuntimeError, + "panel_below: can't find Panel Object"); + return NULL; } Py_INCREF(po); return (PyObject *)po; } static PyObject *PyCurses_update_panels(PyObject *self) -{ +{ PyCursesInitialised; update_panels(); Py_INCREF(Py_None); @@ -457,22 +457,22 @@ {"new_panel", (PyCFunction)PyCurses_new_panel, METH_VARARGS}, {"top_panel", (PyCFunction)PyCurses_top_panel, METH_NOARGS}, {"update_panels", (PyCFunction)PyCurses_update_panels, METH_NOARGS}, - {NULL, NULL} /* sentinel */ + {NULL, NULL} /* sentinel */ }; /* Initialization function for the module */ static struct PyModuleDef _curses_panelmodule = { - PyModuleDef_HEAD_INIT, - "_curses_panel", - NULL, - -1, - PyCurses_methods, - NULL, - NULL, - NULL, - NULL + PyModuleDef_HEAD_INIT, + "_curses_panel", + NULL, + -1, + PyCurses_methods, + NULL, + NULL, + NULL, + NULL }; PyMODINIT_FUNC @@ -489,7 +489,7 @@ /* Create the module and add the functions */ m = PyModule_Create(&_curses_panelmodule); if (m == NULL) - return NULL; + return NULL; d = PyModule_GetDict(m); /* For exception _curses_panel.error */ Modified: python/branches/py3k/Modules/_dbmmodule.c ============================================================================== --- python/branches/py3k/Modules/_dbmmodule.c (original) +++ python/branches/py3k/Modules/_dbmmodule.c Sun May 9 17:52:27 2010 @@ -33,9 +33,9 @@ #endif typedef struct { - PyObject_HEAD - int di_size; /* -1 means recompute */ - DBM *di_dbm; + PyObject_HEAD + int di_size; /* -1 means recompute */ + DBM *di_dbm; } dbmobject; static PyTypeObject Dbmtype; @@ -50,18 +50,18 @@ static PyObject * newdbmobject(char *file, int flags, int mode) { - dbmobject *dp; + dbmobject *dp; - dp = PyObject_New(dbmobject, &Dbmtype); - if (dp == NULL) - return NULL; - dp->di_size = -1; - if ( (dp->di_dbm = dbm_open(file, flags, mode)) == 0 ) { - PyErr_SetFromErrno(DbmError); - Py_DECREF(dp); - return NULL; - } - return (PyObject *)dp; + dp = PyObject_New(dbmobject, &Dbmtype); + if (dp == NULL) + return NULL; + dp->di_size = -1; + if ( (dp->di_dbm = dbm_open(file, flags, mode)) == 0 ) { + PyErr_SetFromErrno(DbmError); + Py_DECREF(dp); + return NULL; + } + return (PyObject *)dp; } /* Methods */ @@ -69,294 +69,294 @@ static void dbm_dealloc(register dbmobject *dp) { - if ( dp->di_dbm ) - dbm_close(dp->di_dbm); - PyObject_Del(dp); + if ( dp->di_dbm ) + dbm_close(dp->di_dbm); + PyObject_Del(dp); } static Py_ssize_t dbm_length(dbmobject *dp) { - if (dp->di_dbm == NULL) { - PyErr_SetString(DbmError, "DBM object has already been closed"); - return -1; - } - if ( dp->di_size < 0 ) { - datum key; - int size; - - size = 0; - for ( key=dbm_firstkey(dp->di_dbm); key.dptr; - key = dbm_nextkey(dp->di_dbm)) - size++; - dp->di_size = size; - } - return dp->di_size; + if (dp->di_dbm == NULL) { + PyErr_SetString(DbmError, "DBM object has already been closed"); + return -1; + } + if ( dp->di_size < 0 ) { + datum key; + int size; + + size = 0; + for ( key=dbm_firstkey(dp->di_dbm); key.dptr; + key = dbm_nextkey(dp->di_dbm)) + size++; + dp->di_size = size; + } + return dp->di_size; } static PyObject * dbm_subscript(dbmobject *dp, register PyObject *key) { - datum drec, krec; - Py_ssize_t tmp_size; - - if (!PyArg_Parse(key, "s#", &krec.dptr, &tmp_size) ) - return NULL; - - krec.dsize = tmp_size; - check_dbmobject_open(dp); - drec = dbm_fetch(dp->di_dbm, krec); - if ( drec.dptr == 0 ) { - PyErr_SetObject(PyExc_KeyError, key); - return NULL; - } - if ( dbm_error(dp->di_dbm) ) { - dbm_clearerr(dp->di_dbm); - PyErr_SetString(DbmError, ""); - return NULL; - } - return PyBytes_FromStringAndSize(drec.dptr, drec.dsize); + datum drec, krec; + Py_ssize_t tmp_size; + + if (!PyArg_Parse(key, "s#", &krec.dptr, &tmp_size) ) + return NULL; + + krec.dsize = tmp_size; + check_dbmobject_open(dp); + drec = dbm_fetch(dp->di_dbm, krec); + if ( drec.dptr == 0 ) { + PyErr_SetObject(PyExc_KeyError, key); + return NULL; + } + if ( dbm_error(dp->di_dbm) ) { + dbm_clearerr(dp->di_dbm); + PyErr_SetString(DbmError, ""); + return NULL; + } + return PyBytes_FromStringAndSize(drec.dptr, drec.dsize); } static int dbm_ass_sub(dbmobject *dp, PyObject *v, PyObject *w) { - datum krec, drec; - Py_ssize_t tmp_size; - - if ( !PyArg_Parse(v, "s#", &krec.dptr, &tmp_size) ) { - PyErr_SetString(PyExc_TypeError, - "dbm mappings have bytes or string keys only"); - return -1; - } - krec.dsize = tmp_size; - if (dp->di_dbm == NULL) { - PyErr_SetString(DbmError, "DBM object has already been closed"); - return -1; + datum krec, drec; + Py_ssize_t tmp_size; + + if ( !PyArg_Parse(v, "s#", &krec.dptr, &tmp_size) ) { + PyErr_SetString(PyExc_TypeError, + "dbm mappings have bytes or string keys only"); + return -1; + } + krec.dsize = tmp_size; + if (dp->di_dbm == NULL) { + PyErr_SetString(DbmError, "DBM object has already been closed"); + return -1; + } + dp->di_size = -1; + if (w == NULL) { + if ( dbm_delete(dp->di_dbm, krec) < 0 ) { + dbm_clearerr(dp->di_dbm); + PyErr_SetObject(PyExc_KeyError, v); + return -1; + } + } else { + if ( !PyArg_Parse(w, "s#", &drec.dptr, &tmp_size) ) { + PyErr_SetString(PyExc_TypeError, + "dbm mappings have byte or string elements only"); + return -1; } - dp->di_size = -1; - if (w == NULL) { - if ( dbm_delete(dp->di_dbm, krec) < 0 ) { - dbm_clearerr(dp->di_dbm); - PyErr_SetObject(PyExc_KeyError, v); - return -1; - } - } else { - if ( !PyArg_Parse(w, "s#", &drec.dptr, &tmp_size) ) { - PyErr_SetString(PyExc_TypeError, - "dbm mappings have byte or string elements only"); - return -1; - } - drec.dsize = tmp_size; - if ( dbm_store(dp->di_dbm, krec, drec, DBM_REPLACE) < 0 ) { - dbm_clearerr(dp->di_dbm); - PyErr_SetString(DbmError, - "cannot add item to database"); - return -1; - } - } - if ( dbm_error(dp->di_dbm) ) { - dbm_clearerr(dp->di_dbm); - PyErr_SetString(DbmError, ""); - return -1; - } - return 0; + drec.dsize = tmp_size; + if ( dbm_store(dp->di_dbm, krec, drec, DBM_REPLACE) < 0 ) { + dbm_clearerr(dp->di_dbm); + PyErr_SetString(DbmError, + "cannot add item to database"); + return -1; + } + } + if ( dbm_error(dp->di_dbm) ) { + dbm_clearerr(dp->di_dbm); + PyErr_SetString(DbmError, ""); + return -1; + } + return 0; } static PyMappingMethods dbm_as_mapping = { - (lenfunc)dbm_length, /*mp_length*/ - (binaryfunc)dbm_subscript, /*mp_subscript*/ - (objobjargproc)dbm_ass_sub, /*mp_ass_subscript*/ + (lenfunc)dbm_length, /*mp_length*/ + (binaryfunc)dbm_subscript, /*mp_subscript*/ + (objobjargproc)dbm_ass_sub, /*mp_ass_subscript*/ }; static PyObject * dbm__close(register dbmobject *dp, PyObject *unused) { - if (dp->di_dbm) - dbm_close(dp->di_dbm); - dp->di_dbm = NULL; - Py_INCREF(Py_None); - return Py_None; + if (dp->di_dbm) + dbm_close(dp->di_dbm); + dp->di_dbm = NULL; + Py_INCREF(Py_None); + return Py_None; } static PyObject * dbm_keys(register dbmobject *dp, PyObject *unused) { - register PyObject *v, *item; - datum key; - int err; - - check_dbmobject_open(dp); - v = PyList_New(0); - if (v == NULL) - return NULL; - for (key = dbm_firstkey(dp->di_dbm); key.dptr; - key = dbm_nextkey(dp->di_dbm)) { - item = PyBytes_FromStringAndSize(key.dptr, key.dsize); - if (item == NULL) { - Py_DECREF(v); - return NULL; - } - err = PyList_Append(v, item); - Py_DECREF(item); - if (err != 0) { - Py_DECREF(v); - return NULL; - } - } - return v; + register PyObject *v, *item; + datum key; + int err; + + check_dbmobject_open(dp); + v = PyList_New(0); + if (v == NULL) + return NULL; + for (key = dbm_firstkey(dp->di_dbm); key.dptr; + key = dbm_nextkey(dp->di_dbm)) { + item = PyBytes_FromStringAndSize(key.dptr, key.dsize); + if (item == NULL) { + Py_DECREF(v); + return NULL; + } + err = PyList_Append(v, item); + Py_DECREF(item); + if (err != 0) { + Py_DECREF(v); + return NULL; + } + } + return v; } static int dbm_contains(PyObject *self, PyObject *arg) { - dbmobject *dp = (dbmobject *)self; - datum key, val; + dbmobject *dp = (dbmobject *)self; + datum key, val; - if ((dp)->di_dbm == NULL) { - PyErr_SetString(DbmError, - "DBM object has already been closed"); - return -1; - } - if (PyUnicode_Check(arg)) { - arg = _PyUnicode_AsDefaultEncodedString(arg, NULL); - if (arg == NULL) - return -1; - } - if (!PyBytes_Check(arg)) { - PyErr_Format(PyExc_TypeError, - "dbm key must be string, not %.100s", - arg->ob_type->tp_name); - return -1; - } - key.dptr = PyBytes_AS_STRING(arg); - key.dsize = PyBytes_GET_SIZE(arg); - val = dbm_fetch(dp->di_dbm, key); - return val.dptr != NULL; + if ((dp)->di_dbm == NULL) { + PyErr_SetString(DbmError, + "DBM object has already been closed"); + return -1; + } + if (PyUnicode_Check(arg)) { + arg = _PyUnicode_AsDefaultEncodedString(arg, NULL); + if (arg == NULL) + return -1; + } + if (!PyBytes_Check(arg)) { + PyErr_Format(PyExc_TypeError, + "dbm key must be string, not %.100s", + arg->ob_type->tp_name); + return -1; + } + key.dptr = PyBytes_AS_STRING(arg); + key.dsize = PyBytes_GET_SIZE(arg); + val = dbm_fetch(dp->di_dbm, key); + return val.dptr != NULL; } static PySequenceMethods dbm_as_sequence = { - 0, /* sq_length */ - 0, /* sq_concat */ - 0, /* sq_repeat */ - 0, /* sq_item */ - 0, /* sq_slice */ - 0, /* sq_ass_item */ - 0, /* sq_ass_slice */ - dbm_contains, /* sq_contains */ - 0, /* sq_inplace_concat */ - 0, /* sq_inplace_repeat */ + 0, /* sq_length */ + 0, /* sq_concat */ + 0, /* sq_repeat */ + 0, /* sq_item */ + 0, /* sq_slice */ + 0, /* sq_ass_item */ + 0, /* sq_ass_slice */ + dbm_contains, /* sq_contains */ + 0, /* sq_inplace_concat */ + 0, /* sq_inplace_repeat */ }; static PyObject * dbm_get(register dbmobject *dp, PyObject *args) { - datum key, val; - PyObject *defvalue = Py_None; - char *tmp_ptr; - Py_ssize_t tmp_size; - - if (!PyArg_ParseTuple(args, "s#|O:get", - &tmp_ptr, &tmp_size, &defvalue)) - return NULL; - key.dptr = tmp_ptr; - key.dsize = tmp_size; - check_dbmobject_open(dp); - val = dbm_fetch(dp->di_dbm, key); - if (val.dptr != NULL) - return PyBytes_FromStringAndSize(val.dptr, val.dsize); - else { - Py_INCREF(defvalue); - return defvalue; - } + datum key, val; + PyObject *defvalue = Py_None; + char *tmp_ptr; + Py_ssize_t tmp_size; + + if (!PyArg_ParseTuple(args, "s#|O:get", + &tmp_ptr, &tmp_size, &defvalue)) + return NULL; + key.dptr = tmp_ptr; + key.dsize = tmp_size; + check_dbmobject_open(dp); + val = dbm_fetch(dp->di_dbm, key); + if (val.dptr != NULL) + return PyBytes_FromStringAndSize(val.dptr, val.dsize); + else { + Py_INCREF(defvalue); + return defvalue; + } } static PyObject * dbm_setdefault(register dbmobject *dp, PyObject *args) { - datum key, val; - PyObject *defvalue = NULL; - char *tmp_ptr; - Py_ssize_t tmp_size; - - if (!PyArg_ParseTuple(args, "s#|O:setdefault", - &tmp_ptr, &tmp_size, &defvalue)) - return NULL; - key.dptr = tmp_ptr; - key.dsize = tmp_size; - check_dbmobject_open(dp); - val = dbm_fetch(dp->di_dbm, key); - if (val.dptr != NULL) - return PyBytes_FromStringAndSize(val.dptr, val.dsize); - if (defvalue == NULL) { - defvalue = PyBytes_FromStringAndSize(NULL, 0); - if (defvalue == NULL) - return NULL; - val.dptr = NULL; - val.dsize = 0; - } - else { - if ( !PyArg_Parse(defvalue, "s#", &val.dptr, &tmp_size) ) { - PyErr_SetString(PyExc_TypeError, - "dbm mappings have byte string elements only"); - return NULL; - } - val.dsize = tmp_size; - Py_INCREF(defvalue); - } - if (dbm_store(dp->di_dbm, key, val, DBM_INSERT) < 0) { - dbm_clearerr(dp->di_dbm); - PyErr_SetString(DbmError, "cannot add item to database"); - Py_DECREF(defvalue); - return NULL; - } - return defvalue; + datum key, val; + PyObject *defvalue = NULL; + char *tmp_ptr; + Py_ssize_t tmp_size; + + if (!PyArg_ParseTuple(args, "s#|O:setdefault", + &tmp_ptr, &tmp_size, &defvalue)) + return NULL; + key.dptr = tmp_ptr; + key.dsize = tmp_size; + check_dbmobject_open(dp); + val = dbm_fetch(dp->di_dbm, key); + if (val.dptr != NULL) + return PyBytes_FromStringAndSize(val.dptr, val.dsize); + if (defvalue == NULL) { + defvalue = PyBytes_FromStringAndSize(NULL, 0); + if (defvalue == NULL) + return NULL; + val.dptr = NULL; + val.dsize = 0; + } + else { + if ( !PyArg_Parse(defvalue, "s#", &val.dptr, &tmp_size) ) { + PyErr_SetString(PyExc_TypeError, + "dbm mappings have byte string elements only"); + return NULL; + } + val.dsize = tmp_size; + Py_INCREF(defvalue); + } + if (dbm_store(dp->di_dbm, key, val, DBM_INSERT) < 0) { + dbm_clearerr(dp->di_dbm); + PyErr_SetString(DbmError, "cannot add item to database"); + Py_DECREF(defvalue); + return NULL; + } + return defvalue; } static PyMethodDef dbm_methods[] = { - {"close", (PyCFunction)dbm__close, METH_NOARGS, - "close()\nClose the database."}, - {"keys", (PyCFunction)dbm_keys, METH_NOARGS, - "keys() -> list\nReturn a list of all keys in the database."}, - {"get", (PyCFunction)dbm_get, METH_VARARGS, - "get(key[, default]) -> value\n" - "Return the value for key if present, otherwise default."}, - {"setdefault", (PyCFunction)dbm_setdefault, METH_VARARGS, - "setdefault(key[, default]) -> value\n" - "Return the value for key if present, otherwise default. If key\n" - "is not in the database, it is inserted with default as the value."}, - {NULL, NULL} /* sentinel */ + {"close", (PyCFunction)dbm__close, METH_NOARGS, + "close()\nClose the database."}, + {"keys", (PyCFunction)dbm_keys, METH_NOARGS, + "keys() -> list\nReturn a list of all keys in the database."}, + {"get", (PyCFunction)dbm_get, METH_VARARGS, + "get(key[, default]) -> value\n" + "Return the value for key if present, otherwise default."}, + {"setdefault", (PyCFunction)dbm_setdefault, METH_VARARGS, + "setdefault(key[, default]) -> value\n" + "Return the value for key if present, otherwise default. If key\n" + "is not in the database, it is inserted with default as the value."}, + {NULL, NULL} /* sentinel */ }; static PyTypeObject Dbmtype = { - PyVarObject_HEAD_INIT(NULL, 0) - "_dbm.dbm", - sizeof(dbmobject), - 0, - (destructor)dbm_dealloc, /*tp_dealloc*/ - 0, /*tp_print*/ - 0, /*tp_getattr*/ - 0, /*tp_setattr*/ - 0, /*tp_reserved*/ - 0, /*tp_repr*/ - 0, /*tp_as_number*/ - &dbm_as_sequence, /*tp_as_sequence*/ - &dbm_as_mapping, /*tp_as_mapping*/ - 0, /*tp_hash*/ - 0, /*tp_call*/ - 0, /*tp_str*/ - 0, /*tp_getattro*/ - 0, /*tp_setattro*/ - 0, /*tp_as_buffer*/ - Py_TPFLAGS_DEFAULT, /*tp_flags*/ - 0, /*tp_doc*/ - 0, /*tp_traverse*/ - 0, /*tp_clear*/ - 0, /*tp_richcompare*/ - 0, /*tp_weaklistoffset*/ - 0, /*tp_iter*/ - 0, /*tp_iternext*/ - dbm_methods, /*tp_methods*/ + PyVarObject_HEAD_INIT(NULL, 0) + "_dbm.dbm", + sizeof(dbmobject), + 0, + (destructor)dbm_dealloc, /*tp_dealloc*/ + 0, /*tp_print*/ + 0, /*tp_getattr*/ + 0, /*tp_setattr*/ + 0, /*tp_reserved*/ + 0, /*tp_repr*/ + 0, /*tp_as_number*/ + &dbm_as_sequence, /*tp_as_sequence*/ + &dbm_as_mapping, /*tp_as_mapping*/ + 0, /*tp_hash*/ + 0, /*tp_call*/ + 0, /*tp_str*/ + 0, /*tp_getattro*/ + 0, /*tp_setattro*/ + 0, /*tp_as_buffer*/ + Py_TPFLAGS_DEFAULT, /*tp_flags*/ + 0, /*tp_doc*/ + 0, /*tp_traverse*/ + 0, /*tp_clear*/ + 0, /*tp_richcompare*/ + 0, /*tp_weaklistoffset*/ + 0, /*tp_iter*/ + 0, /*tp_iternext*/ + dbm_methods, /*tp_methods*/ }; /* ----------------------------------------------------------------- */ @@ -364,74 +364,74 @@ static PyObject * dbmopen(PyObject *self, PyObject *args) { - char *name; - char *flags = "r"; - int iflags; - int mode = 0666; - - if ( !PyArg_ParseTuple(args, "s|si:open", &name, &flags, &mode) ) - return NULL; - if ( strcmp(flags, "r") == 0 ) - iflags = O_RDONLY; - else if ( strcmp(flags, "w") == 0 ) - iflags = O_RDWR; - else if ( strcmp(flags, "rw") == 0 ) /* B/W compat */ - iflags = O_RDWR|O_CREAT; - else if ( strcmp(flags, "c") == 0 ) - iflags = O_RDWR|O_CREAT; - else if ( strcmp(flags, "n") == 0 ) - iflags = O_RDWR|O_CREAT|O_TRUNC; - else { - PyErr_SetString(DbmError, - "arg 2 to open should be 'r', 'w', 'c', or 'n'"); - return NULL; - } - return newdbmobject(name, iflags, mode); + char *name; + char *flags = "r"; + int iflags; + int mode = 0666; + + if ( !PyArg_ParseTuple(args, "s|si:open", &name, &flags, &mode) ) + return NULL; + if ( strcmp(flags, "r") == 0 ) + iflags = O_RDONLY; + else if ( strcmp(flags, "w") == 0 ) + iflags = O_RDWR; + else if ( strcmp(flags, "rw") == 0 ) /* B/W compat */ + iflags = O_RDWR|O_CREAT; + else if ( strcmp(flags, "c") == 0 ) + iflags = O_RDWR|O_CREAT; + else if ( strcmp(flags, "n") == 0 ) + iflags = O_RDWR|O_CREAT|O_TRUNC; + else { + PyErr_SetString(DbmError, + "arg 2 to open should be 'r', 'w', 'c', or 'n'"); + return NULL; + } + return newdbmobject(name, iflags, mode); } static PyMethodDef dbmmodule_methods[] = { - { "open", (PyCFunction)dbmopen, METH_VARARGS, - "open(path[, flag[, mode]]) -> mapping\n" - "Return a database object."}, - { 0, 0 }, + { "open", (PyCFunction)dbmopen, METH_VARARGS, + "open(path[, flag[, mode]]) -> mapping\n" + "Return a database object."}, + { 0, 0 }, }; static struct PyModuleDef _dbmmodule = { - PyModuleDef_HEAD_INIT, - "_dbm", - NULL, - -1, - dbmmodule_methods, - NULL, - NULL, - NULL, - NULL + PyModuleDef_HEAD_INIT, + "_dbm", + NULL, + -1, + dbmmodule_methods, + NULL, + NULL, + NULL, + NULL }; PyMODINIT_FUNC PyInit__dbm(void) { - PyObject *m, *d, *s; + PyObject *m, *d, *s; - if (PyType_Ready(&Dbmtype) < 0) - return NULL; - m = PyModule_Create(&_dbmmodule); - if (m == NULL) - return NULL; - d = PyModule_GetDict(m); - if (DbmError == NULL) - DbmError = PyErr_NewException("_dbm.error", - PyExc_IOError, NULL); - s = PyUnicode_FromString(which_dbm); - if (s != NULL) { - PyDict_SetItemString(d, "library", s); - Py_DECREF(s); - } - if (DbmError != NULL) - PyDict_SetItemString(d, "error", DbmError); - if (PyErr_Occurred()) { - Py_DECREF(m); - m = NULL; - } - return m; + if (PyType_Ready(&Dbmtype) < 0) + return NULL; + m = PyModule_Create(&_dbmmodule); + if (m == NULL) + return NULL; + d = PyModule_GetDict(m); + if (DbmError == NULL) + DbmError = PyErr_NewException("_dbm.error", + PyExc_IOError, NULL); + s = PyUnicode_FromString(which_dbm); + if (s != NULL) { + PyDict_SetItemString(d, "library", s); + Py_DECREF(s); + } + if (DbmError != NULL) + PyDict_SetItemString(d, "error", DbmError); + if (PyErr_Occurred()) { + Py_DECREF(m); + m = NULL; + } + return m; } Modified: python/branches/py3k/Modules/_functoolsmodule.c ============================================================================== --- python/branches/py3k/Modules/_functoolsmodule.c (original) +++ python/branches/py3k/Modules/_functoolsmodule.c Sun May 9 17:52:27 2010 @@ -2,7 +2,7 @@ #include "Python.h" #include "structmember.h" -/* _functools module written and maintained +/* _functools module written and maintained by Hye-Shik Chang with adaptations by Raymond Hettinger Copyright (c) 2004, 2005, 2006 Python Software Foundation. @@ -12,12 +12,12 @@ /* partial object **********************************************************/ typedef struct { - PyObject_HEAD - PyObject *fn; - PyObject *args; - PyObject *kw; - PyObject *dict; - PyObject *weakreflist; /* List of weak references */ + PyObject_HEAD + PyObject *fn; + PyObject *args; + PyObject *kw; + PyObject *dict; + PyObject *weakreflist; /* List of weak references */ } partialobject; static PyTypeObject partial_type; @@ -25,175 +25,175 @@ static PyObject * partial_new(PyTypeObject *type, PyObject *args, PyObject *kw) { - PyObject *func; - partialobject *pto; + PyObject *func; + partialobject *pto; - if (PyTuple_GET_SIZE(args) < 1) { - PyErr_SetString(PyExc_TypeError, - "type 'partial' takes at least one argument"); - return NULL; - } - - func = PyTuple_GET_ITEM(args, 0); - if (!PyCallable_Check(func)) { - PyErr_SetString(PyExc_TypeError, - "the first argument must be callable"); - return NULL; - } - - /* create partialobject structure */ - pto = (partialobject *)type->tp_alloc(type, 0); - if (pto == NULL) - return NULL; - - pto->fn = func; - Py_INCREF(func); - pto->args = PyTuple_GetSlice(args, 1, PY_SSIZE_T_MAX); - if (pto->args == NULL) { - pto->kw = NULL; - Py_DECREF(pto); - return NULL; - } - if (kw != NULL) { - pto->kw = PyDict_Copy(kw); - if (pto->kw == NULL) { - Py_DECREF(pto); - return NULL; - } - } else { - pto->kw = Py_None; - Py_INCREF(Py_None); - } + if (PyTuple_GET_SIZE(args) < 1) { + PyErr_SetString(PyExc_TypeError, + "type 'partial' takes at least one argument"); + return NULL; + } + + func = PyTuple_GET_ITEM(args, 0); + if (!PyCallable_Check(func)) { + PyErr_SetString(PyExc_TypeError, + "the first argument must be callable"); + return NULL; + } + + /* create partialobject structure */ + pto = (partialobject *)type->tp_alloc(type, 0); + if (pto == NULL) + return NULL; + + pto->fn = func; + Py_INCREF(func); + pto->args = PyTuple_GetSlice(args, 1, PY_SSIZE_T_MAX); + if (pto->args == NULL) { + pto->kw = NULL; + Py_DECREF(pto); + return NULL; + } + if (kw != NULL) { + pto->kw = PyDict_Copy(kw); + if (pto->kw == NULL) { + Py_DECREF(pto); + return NULL; + } + } else { + pto->kw = Py_None; + Py_INCREF(Py_None); + } - pto->weakreflist = NULL; - pto->dict = NULL; + pto->weakreflist = NULL; + pto->dict = NULL; - return (PyObject *)pto; + return (PyObject *)pto; } static void partial_dealloc(partialobject *pto) { - PyObject_GC_UnTrack(pto); - if (pto->weakreflist != NULL) - PyObject_ClearWeakRefs((PyObject *) pto); - Py_XDECREF(pto->fn); - Py_XDECREF(pto->args); - Py_XDECREF(pto->kw); - Py_XDECREF(pto->dict); - Py_TYPE(pto)->tp_free(pto); + PyObject_GC_UnTrack(pto); + if (pto->weakreflist != NULL) + PyObject_ClearWeakRefs((PyObject *) pto); + Py_XDECREF(pto->fn); + Py_XDECREF(pto->args); + Py_XDECREF(pto->kw); + Py_XDECREF(pto->dict); + Py_TYPE(pto)->tp_free(pto); } static PyObject * partial_call(partialobject *pto, PyObject *args, PyObject *kw) { - PyObject *ret; - PyObject *argappl = NULL, *kwappl = NULL; + PyObject *ret; + PyObject *argappl = NULL, *kwappl = NULL; - assert (PyCallable_Check(pto->fn)); - assert (PyTuple_Check(pto->args)); - assert (pto->kw == Py_None || PyDict_Check(pto->kw)); - - if (PyTuple_GET_SIZE(pto->args) == 0) { - argappl = args; - Py_INCREF(args); - } else if (PyTuple_GET_SIZE(args) == 0) { - argappl = pto->args; - Py_INCREF(pto->args); - } else { - argappl = PySequence_Concat(pto->args, args); - if (argappl == NULL) - return NULL; - } - - if (pto->kw == Py_None) { - kwappl = kw; - Py_XINCREF(kw); - } else { - kwappl = PyDict_Copy(pto->kw); - if (kwappl == NULL) { - Py_DECREF(argappl); - return NULL; - } - if (kw != NULL) { - if (PyDict_Merge(kwappl, kw, 1) != 0) { - Py_DECREF(argappl); - Py_DECREF(kwappl); - return NULL; - } - } - } - - ret = PyObject_Call(pto->fn, argappl, kwappl); - Py_DECREF(argappl); - Py_XDECREF(kwappl); - return ret; + assert (PyCallable_Check(pto->fn)); + assert (PyTuple_Check(pto->args)); + assert (pto->kw == Py_None || PyDict_Check(pto->kw)); + + if (PyTuple_GET_SIZE(pto->args) == 0) { + argappl = args; + Py_INCREF(args); + } else if (PyTuple_GET_SIZE(args) == 0) { + argappl = pto->args; + Py_INCREF(pto->args); + } else { + argappl = PySequence_Concat(pto->args, args); + if (argappl == NULL) + return NULL; + } + + if (pto->kw == Py_None) { + kwappl = kw; + Py_XINCREF(kw); + } else { + kwappl = PyDict_Copy(pto->kw); + if (kwappl == NULL) { + Py_DECREF(argappl); + return NULL; + } + if (kw != NULL) { + if (PyDict_Merge(kwappl, kw, 1) != 0) { + Py_DECREF(argappl); + Py_DECREF(kwappl); + return NULL; + } + } + } + + ret = PyObject_Call(pto->fn, argappl, kwappl); + Py_DECREF(argappl); + Py_XDECREF(kwappl); + return ret; } static int partial_traverse(partialobject *pto, visitproc visit, void *arg) { - Py_VISIT(pto->fn); - Py_VISIT(pto->args); - Py_VISIT(pto->kw); - Py_VISIT(pto->dict); - return 0; + Py_VISIT(pto->fn); + Py_VISIT(pto->args); + Py_VISIT(pto->kw); + Py_VISIT(pto->dict); + return 0; } PyDoc_STRVAR(partial_doc, "partial(func, *args, **keywords) - new function with partial application\n\ - of the given arguments and keywords.\n"); + of the given arguments and keywords.\n"); #define OFF(x) offsetof(partialobject, x) static PyMemberDef partial_memberlist[] = { - {"func", T_OBJECT, OFF(fn), READONLY, - "function object to use in future partial calls"}, - {"args", T_OBJECT, OFF(args), READONLY, - "tuple of arguments to future partial calls"}, - {"keywords", T_OBJECT, OFF(kw), READONLY, - "dictionary of keyword arguments to future partial calls"}, - {NULL} /* Sentinel */ + {"func", T_OBJECT, OFF(fn), READONLY, + "function object to use in future partial calls"}, + {"args", T_OBJECT, OFF(args), READONLY, + "tuple of arguments to future partial calls"}, + {"keywords", T_OBJECT, OFF(kw), READONLY, + "dictionary of keyword arguments to future partial calls"}, + {NULL} /* Sentinel */ }; static PyObject * partial_get_dict(partialobject *pto) { - if (pto->dict == NULL) { - pto->dict = PyDict_New(); - if (pto->dict == NULL) - return NULL; - } - Py_INCREF(pto->dict); - return pto->dict; + if (pto->dict == NULL) { + pto->dict = PyDict_New(); + if (pto->dict == NULL) + return NULL; + } + Py_INCREF(pto->dict); + return pto->dict; } static int partial_set_dict(partialobject *pto, PyObject *value) { - PyObject *tmp; + PyObject *tmp; - /* It is illegal to del p.__dict__ */ - if (value == NULL) { - PyErr_SetString(PyExc_TypeError, - "a partial object's dictionary may not be deleted"); - return -1; - } - /* Can only set __dict__ to a dictionary */ - if (!PyDict_Check(value)) { - PyErr_SetString(PyExc_TypeError, - "setting partial object's dictionary to a non-dict"); - return -1; - } - tmp = pto->dict; - Py_INCREF(value); - pto->dict = value; - Py_XDECREF(tmp); - return 0; + /* It is illegal to del p.__dict__ */ + if (value == NULL) { + PyErr_SetString(PyExc_TypeError, + "a partial object's dictionary may not be deleted"); + return -1; + } + /* Can only set __dict__ to a dictionary */ + if (!PyDict_Check(value)) { + PyErr_SetString(PyExc_TypeError, + "setting partial object's dictionary to a non-dict"); + return -1; + } + tmp = pto->dict; + Py_INCREF(value); + pto->dict = value; + Py_XDECREF(tmp); + return 0; } static PyGetSetDef partial_getsetlist[] = { - {"__dict__", (getter)partial_get_dict, (setter)partial_set_dict}, - {NULL} /* Sentinel */ + {"__dict__", (getter)partial_get_dict, (setter)partial_set_dict}, + {NULL} /* Sentinel */ }; /* Pickle strategy: @@ -206,85 +206,85 @@ static PyObject * partial_reduce(partialobject *pto, PyObject *unused) { - return Py_BuildValue("O(O)(OOOO)", Py_TYPE(pto), pto->fn, pto->fn, - pto->args, pto->kw, - pto->dict ? pto->dict : Py_None); + return Py_BuildValue("O(O)(OOOO)", Py_TYPE(pto), pto->fn, pto->fn, + pto->args, pto->kw, + pto->dict ? pto->dict : Py_None); } static PyObject * partial_setstate(partialobject *pto, PyObject *args) { - PyObject *fn, *fnargs, *kw, *dict; - if (!PyArg_ParseTuple(args, "(OOOO):__setstate__", - &fn, &fnargs, &kw, &dict)) - return NULL; - Py_XDECREF(pto->fn); - Py_XDECREF(pto->args); - Py_XDECREF(pto->kw); - Py_XDECREF(pto->dict); - pto->fn = fn; - pto->args = fnargs; - pto->kw = kw; - if (dict != Py_None) { - pto->dict = dict; - Py_INCREF(dict); - } else { - pto->dict = NULL; - } - Py_INCREF(fn); - Py_INCREF(fnargs); - Py_INCREF(kw); - Py_RETURN_NONE; + PyObject *fn, *fnargs, *kw, *dict; + if (!PyArg_ParseTuple(args, "(OOOO):__setstate__", + &fn, &fnargs, &kw, &dict)) + return NULL; + Py_XDECREF(pto->fn); + Py_XDECREF(pto->args); + Py_XDECREF(pto->kw); + Py_XDECREF(pto->dict); + pto->fn = fn; + pto->args = fnargs; + pto->kw = kw; + if (dict != Py_None) { + pto->dict = dict; + Py_INCREF(dict); + } else { + pto->dict = NULL; + } + Py_INCREF(fn); + Py_INCREF(fnargs); + Py_INCREF(kw); + Py_RETURN_NONE; } static PyMethodDef partial_methods[] = { - {"__reduce__", (PyCFunction)partial_reduce, METH_NOARGS}, - {"__setstate__", (PyCFunction)partial_setstate, METH_VARARGS}, - {NULL, NULL} /* sentinel */ + {"__reduce__", (PyCFunction)partial_reduce, METH_NOARGS}, + {"__setstate__", (PyCFunction)partial_setstate, METH_VARARGS}, + {NULL, NULL} /* sentinel */ }; static PyTypeObject partial_type = { - PyVarObject_HEAD_INIT(NULL, 0) - "functools.partial", /* tp_name */ - sizeof(partialobject), /* tp_basicsize */ - 0, /* tp_itemsize */ - /* methods */ - (destructor)partial_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 */ - (ternaryfunc)partial_call, /* tp_call */ - 0, /* tp_str */ - PyObject_GenericGetAttr, /* tp_getattro */ - PyObject_GenericSetAttr, /* tp_setattro */ - 0, /* tp_as_buffer */ - Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC | - Py_TPFLAGS_BASETYPE, /* tp_flags */ - partial_doc, /* tp_doc */ - (traverseproc)partial_traverse, /* tp_traverse */ - 0, /* tp_clear */ - 0, /* tp_richcompare */ - offsetof(partialobject, weakreflist), /* tp_weaklistoffset */ - 0, /* tp_iter */ - 0, /* tp_iternext */ - partial_methods, /* tp_methods */ - partial_memberlist, /* tp_members */ - partial_getsetlist, /* tp_getset */ - 0, /* tp_base */ - 0, /* tp_dict */ - 0, /* tp_descr_get */ - 0, /* tp_descr_set */ - offsetof(partialobject, dict), /* tp_dictoffset */ - 0, /* tp_init */ - 0, /* tp_alloc */ - partial_new, /* tp_new */ - PyObject_GC_Del, /* tp_free */ + PyVarObject_HEAD_INIT(NULL, 0) + "functools.partial", /* tp_name */ + sizeof(partialobject), /* tp_basicsize */ + 0, /* tp_itemsize */ + /* methods */ + (destructor)partial_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 */ + (ternaryfunc)partial_call, /* tp_call */ + 0, /* tp_str */ + PyObject_GenericGetAttr, /* tp_getattro */ + PyObject_GenericSetAttr, /* tp_setattro */ + 0, /* tp_as_buffer */ + Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC | + Py_TPFLAGS_BASETYPE, /* tp_flags */ + partial_doc, /* tp_doc */ + (traverseproc)partial_traverse, /* tp_traverse */ + 0, /* tp_clear */ + 0, /* tp_richcompare */ + offsetof(partialobject, weakreflist), /* tp_weaklistoffset */ + 0, /* tp_iter */ + 0, /* tp_iternext */ + partial_methods, /* tp_methods */ + partial_memberlist, /* tp_members */ + partial_getsetlist, /* tp_getset */ + 0, /* tp_base */ + 0, /* tp_dict */ + 0, /* tp_descr_get */ + 0, /* tp_descr_set */ + offsetof(partialobject, dict), /* tp_dictoffset */ + 0, /* tp_init */ + 0, /* tp_alloc */ + partial_new, /* tp_new */ + PyObject_GC_Del, /* tp_free */ }; @@ -293,64 +293,64 @@ static PyObject * functools_reduce(PyObject *self, PyObject *args) { - PyObject *seq, *func, *result = NULL, *it; + PyObject *seq, *func, *result = NULL, *it; - if (!PyArg_UnpackTuple(args, "reduce", 2, 3, &func, &seq, &result)) - return NULL; - if (result != NULL) - Py_INCREF(result); - - it = PyObject_GetIter(seq); - if (it == NULL) { - PyErr_SetString(PyExc_TypeError, - "reduce() arg 2 must support iteration"); - Py_XDECREF(result); - return NULL; - } - - if ((args = PyTuple_New(2)) == NULL) - goto Fail; - - for (;;) { - PyObject *op2; - - if (args->ob_refcnt > 1) { - Py_DECREF(args); - if ((args = PyTuple_New(2)) == NULL) - goto Fail; - } - - op2 = PyIter_Next(it); - if (op2 == NULL) { - if (PyErr_Occurred()) - goto Fail; - break; - } - - if (result == NULL) - result = op2; - else { - PyTuple_SetItem(args, 0, result); - PyTuple_SetItem(args, 1, op2); - if ((result = PyEval_CallObject(func, args)) == NULL) - goto Fail; - } - } - - Py_DECREF(args); - - if (result == NULL) - PyErr_SetString(PyExc_TypeError, - "reduce() of empty sequence with no initial value"); + if (!PyArg_UnpackTuple(args, "reduce", 2, 3, &func, &seq, &result)) + return NULL; + if (result != NULL) + Py_INCREF(result); + + it = PyObject_GetIter(seq); + if (it == NULL) { + PyErr_SetString(PyExc_TypeError, + "reduce() arg 2 must support iteration"); + Py_XDECREF(result); + return NULL; + } + + if ((args = PyTuple_New(2)) == NULL) + goto Fail; + + for (;;) { + PyObject *op2; + + if (args->ob_refcnt > 1) { + Py_DECREF(args); + if ((args = PyTuple_New(2)) == NULL) + goto Fail; + } + + op2 = PyIter_Next(it); + if (op2 == NULL) { + if (PyErr_Occurred()) + goto Fail; + break; + } + + if (result == NULL) + result = op2; + else { + PyTuple_SetItem(args, 0, result); + PyTuple_SetItem(args, 1, op2); + if ((result = PyEval_CallObject(func, args)) == NULL) + goto Fail; + } + } + + Py_DECREF(args); + + if (result == NULL) + PyErr_SetString(PyExc_TypeError, + "reduce() of empty sequence with no initial value"); - Py_DECREF(it); - return result; + Py_DECREF(it); + return result; Fail: - Py_XDECREF(args); - Py_XDECREF(result); - Py_DECREF(it); - return NULL; + Py_XDECREF(args); + Py_XDECREF(result); + Py_DECREF(it); + return NULL; } PyDoc_STRVAR(functools_reduce_doc, @@ -369,47 +369,47 @@ "Tools that operate on functions."); static PyMethodDef module_methods[] = { - {"reduce", functools_reduce, METH_VARARGS, functools_reduce_doc}, - {NULL, NULL} /* sentinel */ + {"reduce", functools_reduce, METH_VARARGS, functools_reduce_doc}, + {NULL, NULL} /* sentinel */ }; static struct PyModuleDef _functoolsmodule = { - PyModuleDef_HEAD_INIT, - "_functools", - module_doc, - -1, - module_methods, - NULL, - NULL, - NULL, - NULL + PyModuleDef_HEAD_INIT, + "_functools", + module_doc, + -1, + module_methods, + NULL, + NULL, + NULL, + NULL }; PyMODINIT_FUNC PyInit__functools(void) { - int i; - PyObject *m; - char *name; - PyTypeObject *typelist[] = { - &partial_type, - NULL - }; - - m = PyModule_Create(&_functoolsmodule); - if (m == NULL) - return NULL; - - for (i=0 ; typelist[i] != NULL ; i++) { - if (PyType_Ready(typelist[i]) < 0) { - Py_DECREF(m); - return NULL; - } - name = strchr(typelist[i]->tp_name, '.'); - assert (name != NULL); - Py_INCREF(typelist[i]); - PyModule_AddObject(m, name+1, (PyObject *)typelist[i]); - } - return m; + int i; + PyObject *m; + char *name; + PyTypeObject *typelist[] = { + &partial_type, + NULL + }; + + m = PyModule_Create(&_functoolsmodule); + if (m == NULL) + return NULL; + + for (i=0 ; typelist[i] != NULL ; i++) { + if (PyType_Ready(typelist[i]) < 0) { + Py_DECREF(m); + return NULL; + } + name = strchr(typelist[i]->tp_name, '.'); + assert (name != NULL); + Py_INCREF(typelist[i]); + PyModule_AddObject(m, name+1, (PyObject *)typelist[i]); + } + return m; } Modified: python/branches/py3k/Modules/_gdbmmodule.c ============================================================================== --- python/branches/py3k/Modules/_gdbmmodule.c (original) +++ python/branches/py3k/Modules/_gdbmmodule.c Sun May 9 17:52:27 2010 @@ -30,7 +30,7 @@ typedef struct { PyObject_HEAD - int di_size; /* -1 means recompute */ + int di_size; /* -1 means recompute */ GDBM_FILE di_dbm; } dbmobject; @@ -177,7 +177,7 @@ } static PyMappingMethods dbm_as_mapping = { - (lenfunc)dbm_length, /*mp_length*/ + (lenfunc)dbm_length, /*mp_length*/ (binaryfunc)dbm_subscript, /*mp_subscript*/ (objobjargproc)dbm_ass_sub, /*mp_ass_subscript*/ }; @@ -247,15 +247,15 @@ datum key; if ((dp)->di_dbm == NULL) { - PyErr_SetString(DbmError, - "GDBM object has already been closed"); - return -1; + PyErr_SetString(DbmError, + "GDBM object has already been closed"); + return -1; } if (!PyBytes_Check(arg)) { - PyErr_Format(PyExc_TypeError, - "gdbm key must be bytes, not %.100s", - arg->ob_type->tp_name); - return -1; + PyErr_Format(PyExc_TypeError, + "gdbm key must be bytes, not %.100s", + arg->ob_type->tp_name); + return -1; } key.dptr = PyBytes_AS_STRING(arg); key.dsize = PyBytes_GET_SIZE(arg); @@ -263,16 +263,16 @@ } static PySequenceMethods dbm_as_sequence = { - 0, /* sq_length */ - 0, /* sq_concat */ - 0, /* sq_repeat */ - 0, /* sq_item */ - 0, /* sq_slice */ - 0, /* sq_ass_item */ - 0, /* sq_ass_slice */ - dbm_contains, /* sq_contains */ - 0, /* sq_inplace_concat */ - 0, /* sq_inplace_repeat */ + 0, /* sq_length */ + 0, /* sq_concat */ + 0, /* sq_repeat */ + 0, /* sq_item */ + 0, /* sq_slice */ + 0, /* sq_ass_item */ + 0, /* sq_ass_slice */ + dbm_contains, /* sq_contains */ + 0, /* sq_inplace_concat */ + 0, /* sq_inplace_repeat */ }; PyDoc_STRVAR(dbm_firstkey__doc__, @@ -372,13 +372,13 @@ } static PyMethodDef dbm_methods[] = { - {"close", (PyCFunction)dbm_close, METH_NOARGS, dbm_close__doc__}, - {"keys", (PyCFunction)dbm_keys, METH_NOARGS, dbm_keys__doc__}, + {"close", (PyCFunction)dbm_close, METH_NOARGS, dbm_close__doc__}, + {"keys", (PyCFunction)dbm_keys, METH_NOARGS, dbm_keys__doc__}, {"firstkey", (PyCFunction)dbm_firstkey,METH_NOARGS, dbm_firstkey__doc__}, - {"nextkey", (PyCFunction)dbm_nextkey, METH_VARARGS, dbm_nextkey__doc__}, + {"nextkey", (PyCFunction)dbm_nextkey, METH_VARARGS, dbm_nextkey__doc__}, {"reorganize",(PyCFunction)dbm_reorganize,METH_NOARGS, dbm_reorganize__doc__}, {"sync", (PyCFunction)dbm_sync, METH_NOARGS, dbm_sync__doc__}, - {NULL, NULL} /* sentinel */ + {NULL, NULL} /* sentinel */ }; static PyTypeObject Dbmtype = { @@ -486,7 +486,7 @@ #endif default: PyOS_snprintf(buf, sizeof(buf), "Flag '%c' is not supported.", - *flags); + *flags); PyErr_SetString(DbmError, buf); return NULL; } @@ -514,15 +514,15 @@ static struct PyModuleDef _gdbmmodule = { - PyModuleDef_HEAD_INIT, - "_gdbm", - gdbmmodule__doc__, - -1, - dbmmodule_methods, - NULL, - NULL, - NULL, - NULL + PyModuleDef_HEAD_INIT, + "_gdbm", + gdbmmodule__doc__, + -1, + dbmmodule_methods, + NULL, + NULL, + NULL, + NULL }; PyMODINIT_FUNC @@ -530,10 +530,10 @@ PyObject *m, *d, *s; if (PyType_Ready(&Dbmtype) < 0) - return NULL; + return NULL; m = PyModule_Create(&_gdbmmodule); if (m == NULL) - return NULL; + return NULL; d = PyModule_GetDict(m); DbmError = PyErr_NewException("_gdbm.error", PyExc_IOError, NULL); if (DbmError != NULL) { Modified: python/branches/py3k/Modules/_gestalt.c ============================================================================== --- python/branches/py3k/Modules/_gestalt.c (original) +++ python/branches/py3k/Modules/_gestalt.c Sun May 9 17:52:27 2010 @@ -4,10 +4,10 @@ All Rights Reserved -Permission to use, copy, modify, and distribute this software and its -documentation for any purpose and without fee is hereby granted, +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 +both that copyright notice and this permission notice appear in supporting documentation, and that the names of Stichting Mathematisch Centrum or CWI not be used in advertising or publicity pertaining to distribution of the software without specific, written prior permission. @@ -34,9 +34,9 @@ { uint32_t tmp; if (!PyUnicode_Check(v) || PyUnicode_GetSize(v) != 4) { - PyErr_SetString(PyExc_TypeError, - "OSType arg must be string of 4 chars"); - return 0; + PyErr_SetString(PyExc_TypeError, + "OSType arg must be string of 4 chars"); + return 0; } memcpy((char *)&tmp, _PyUnicode_AsString(v), 4); *pr = (OSType)ntohl(tmp); @@ -50,12 +50,12 @@ OSType selector; SInt32 response; if (!PyArg_ParseTuple(args, "O&", convert_to_OSType, &selector)) - return NULL; + return NULL; iErr = Gestalt(selector, &response); if (iErr != 0) { - PyErr_SetString(PyExc_OSError, - "non-zero exit code!"); - return NULL; + PyErr_SetString(PyExc_OSError, + "non-zero exit code!"); + return NULL; } return PyLong_FromLong(response); } @@ -66,19 +66,19 @@ }; static struct PyModuleDef gestaltmodule = { - PyModuleDef_HEAD_INIT, - "_gestalt", - NULL, - -1, - gestalt_methods, - NULL, - NULL, - NULL, - NULL + PyModuleDef_HEAD_INIT, + "_gestalt", + NULL, + -1, + gestalt_methods, + NULL, + NULL, + NULL, + NULL }; PyMODINIT_FUNC PyInit__gestalt(void) { - return PyModule_Create(&gestaltmodule); + return PyModule_Create(&gestaltmodule); } Modified: python/branches/py3k/Modules/_heapqmodule.c ============================================================================== --- python/branches/py3k/Modules/_heapqmodule.c (original) +++ python/branches/py3k/Modules/_heapqmodule.c Sun May 9 17:52:27 2010 @@ -1,4 +1,4 @@ -/* Drop in replacement for heapq.py +/* Drop in replacement for heapq.py C implementation derived directly from heapq.py in Py2.3 which was written by Kevin O'Connor, augmented by Tim Peters, @@ -11,115 +11,115 @@ static int cmp_lt(PyObject *x, PyObject *y) { - return PyObject_RichCompareBool(x, y, Py_LT); + return PyObject_RichCompareBool(x, y, Py_LT); } static int _siftdown(PyListObject *heap, Py_ssize_t startpos, Py_ssize_t pos) { - PyObject *newitem, *parent; - int cmp; - Py_ssize_t parentpos; - - assert(PyList_Check(heap)); - if (pos >= PyList_GET_SIZE(heap)) { - PyErr_SetString(PyExc_IndexError, "index out of range"); - return -1; - } - - newitem = PyList_GET_ITEM(heap, pos); - Py_INCREF(newitem); - /* Follow the path to the root, moving parents down until finding - a place newitem fits. */ - while (pos > startpos){ - parentpos = (pos - 1) >> 1; - parent = PyList_GET_ITEM(heap, parentpos); - cmp = cmp_lt(newitem, parent); - if (cmp == -1) { - Py_DECREF(newitem); - return -1; - } - if (cmp == 0) - break; - Py_INCREF(parent); - Py_DECREF(PyList_GET_ITEM(heap, pos)); - PyList_SET_ITEM(heap, pos, parent); - pos = parentpos; - } - Py_DECREF(PyList_GET_ITEM(heap, pos)); - PyList_SET_ITEM(heap, pos, newitem); - return 0; + PyObject *newitem, *parent; + int cmp; + Py_ssize_t parentpos; + + assert(PyList_Check(heap)); + if (pos >= PyList_GET_SIZE(heap)) { + PyErr_SetString(PyExc_IndexError, "index out of range"); + return -1; + } + + newitem = PyList_GET_ITEM(heap, pos); + Py_INCREF(newitem); + /* Follow the path to the root, moving parents down until finding + a place newitem fits. */ + while (pos > startpos){ + parentpos = (pos - 1) >> 1; + parent = PyList_GET_ITEM(heap, parentpos); + cmp = cmp_lt(newitem, parent); + if (cmp == -1) { + Py_DECREF(newitem); + return -1; + } + if (cmp == 0) + break; + Py_INCREF(parent); + Py_DECREF(PyList_GET_ITEM(heap, pos)); + PyList_SET_ITEM(heap, pos, parent); + pos = parentpos; + } + Py_DECREF(PyList_GET_ITEM(heap, pos)); + PyList_SET_ITEM(heap, pos, newitem); + return 0; } static int _siftup(PyListObject *heap, Py_ssize_t pos) { - Py_ssize_t startpos, endpos, childpos, rightpos; - int cmp; - PyObject *newitem, *tmp; - - assert(PyList_Check(heap)); - endpos = PyList_GET_SIZE(heap); - startpos = pos; - if (pos >= endpos) { - PyErr_SetString(PyExc_IndexError, "index out of range"); - return -1; - } - newitem = PyList_GET_ITEM(heap, pos); - Py_INCREF(newitem); - - /* Bubble up the smaller child until hitting a leaf. */ - childpos = 2*pos + 1; /* leftmost child position */ - while (childpos < endpos) { - /* Set childpos to index of smaller child. */ - rightpos = childpos + 1; - if (rightpos < endpos) { - cmp = cmp_lt( - PyList_GET_ITEM(heap, childpos), - PyList_GET_ITEM(heap, rightpos)); - if (cmp == -1) { - Py_DECREF(newitem); - return -1; - } - if (cmp == 0) - childpos = rightpos; - } - /* Move the smaller child up. */ - tmp = PyList_GET_ITEM(heap, childpos); - Py_INCREF(tmp); - Py_DECREF(PyList_GET_ITEM(heap, pos)); - PyList_SET_ITEM(heap, pos, tmp); - pos = childpos; - childpos = 2*pos + 1; - } - - /* The leaf at pos is empty now. Put newitem there, and and bubble - it up to its final resting place (by sifting its parents down). */ - Py_DECREF(PyList_GET_ITEM(heap, pos)); - PyList_SET_ITEM(heap, pos, newitem); - return _siftdown(heap, startpos, pos); + Py_ssize_t startpos, endpos, childpos, rightpos; + int cmp; + PyObject *newitem, *tmp; + + assert(PyList_Check(heap)); + endpos = PyList_GET_SIZE(heap); + startpos = pos; + if (pos >= endpos) { + PyErr_SetString(PyExc_IndexError, "index out of range"); + return -1; + } + newitem = PyList_GET_ITEM(heap, pos); + Py_INCREF(newitem); + + /* Bubble up the smaller child until hitting a leaf. */ + childpos = 2*pos + 1; /* leftmost child position */ + while (childpos < endpos) { + /* Set childpos to index of smaller child. */ + rightpos = childpos + 1; + if (rightpos < endpos) { + cmp = cmp_lt( + PyList_GET_ITEM(heap, childpos), + PyList_GET_ITEM(heap, rightpos)); + if (cmp == -1) { + Py_DECREF(newitem); + return -1; + } + if (cmp == 0) + childpos = rightpos; + } + /* Move the smaller child up. */ + tmp = PyList_GET_ITEM(heap, childpos); + Py_INCREF(tmp); + Py_DECREF(PyList_GET_ITEM(heap, pos)); + PyList_SET_ITEM(heap, pos, tmp); + pos = childpos; + childpos = 2*pos + 1; + } + + /* The leaf at pos is empty now. Put newitem there, and and bubble + it up to its final resting place (by sifting its parents down). */ + Py_DECREF(PyList_GET_ITEM(heap, pos)); + PyList_SET_ITEM(heap, pos, newitem); + return _siftdown(heap, startpos, pos); } static PyObject * heappush(PyObject *self, PyObject *args) { - PyObject *heap, *item; + PyObject *heap, *item; - if (!PyArg_UnpackTuple(args, "heappush", 2, 2, &heap, &item)) - return NULL; + if (!PyArg_UnpackTuple(args, "heappush", 2, 2, &heap, &item)) + return NULL; - if (!PyList_Check(heap)) { - PyErr_SetString(PyExc_TypeError, "heap argument must be a list"); - return NULL; - } - - if (PyList_Append(heap, item) == -1) - return NULL; - - if (_siftdown((PyListObject *)heap, 0, PyList_GET_SIZE(heap)-1) == -1) - return NULL; - Py_INCREF(Py_None); - return Py_None; + if (!PyList_Check(heap)) { + PyErr_SetString(PyExc_TypeError, "heap argument must be a list"); + return NULL; + } + + if (PyList_Append(heap, item) == -1) + return NULL; + + if (_siftdown((PyListObject *)heap, 0, PyList_GET_SIZE(heap)-1) == -1) + return NULL; + Py_INCREF(Py_None); + return Py_None; } PyDoc_STRVAR(heappush_doc, @@ -128,35 +128,35 @@ static PyObject * heappop(PyObject *self, PyObject *heap) { - PyObject *lastelt, *returnitem; - Py_ssize_t n; + PyObject *lastelt, *returnitem; + Py_ssize_t n; - if (!PyList_Check(heap)) { - PyErr_SetString(PyExc_TypeError, "heap argument must be a list"); - return NULL; - } - - /* # raises appropriate IndexError if heap is empty */ - n = PyList_GET_SIZE(heap); - if (n == 0) { - PyErr_SetString(PyExc_IndexError, "index out of range"); - return NULL; - } - - lastelt = PyList_GET_ITEM(heap, n-1) ; - Py_INCREF(lastelt); - PyList_SetSlice(heap, n-1, n, NULL); - n--; - - if (!n) - return lastelt; - returnitem = PyList_GET_ITEM(heap, 0); - PyList_SET_ITEM(heap, 0, lastelt); - if (_siftup((PyListObject *)heap, 0) == -1) { - Py_DECREF(returnitem); - return NULL; - } - return returnitem; + if (!PyList_Check(heap)) { + PyErr_SetString(PyExc_TypeError, "heap argument must be a list"); + return NULL; + } + + /* # raises appropriate IndexError if heap is empty */ + n = PyList_GET_SIZE(heap); + if (n == 0) { + PyErr_SetString(PyExc_IndexError, "index out of range"); + return NULL; + } + + lastelt = PyList_GET_ITEM(heap, n-1) ; + Py_INCREF(lastelt); + PyList_SetSlice(heap, n-1, n, NULL); + n--; + + if (!n) + return lastelt; + returnitem = PyList_GET_ITEM(heap, 0); + PyList_SET_ITEM(heap, 0, lastelt); + if (_siftup((PyListObject *)heap, 0) == -1) { + Py_DECREF(returnitem); + return NULL; + } + return returnitem; } PyDoc_STRVAR(heappop_doc, @@ -165,29 +165,29 @@ static PyObject * heapreplace(PyObject *self, PyObject *args) { - PyObject *heap, *item, *returnitem; + PyObject *heap, *item, *returnitem; - if (!PyArg_UnpackTuple(args, "heapreplace", 2, 2, &heap, &item)) - return NULL; + if (!PyArg_UnpackTuple(args, "heapreplace", 2, 2, &heap, &item)) + return NULL; - if (!PyList_Check(heap)) { - PyErr_SetString(PyExc_TypeError, "heap argument must be a list"); - return NULL; - } - - if (PyList_GET_SIZE(heap) < 1) { - PyErr_SetString(PyExc_IndexError, "index out of range"); - return NULL; - } - - returnitem = PyList_GET_ITEM(heap, 0); - Py_INCREF(item); - PyList_SET_ITEM(heap, 0, item); - if (_siftup((PyListObject *)heap, 0) == -1) { - Py_DECREF(returnitem); - return NULL; - } - return returnitem; + if (!PyList_Check(heap)) { + PyErr_SetString(PyExc_TypeError, "heap argument must be a list"); + return NULL; + } + + if (PyList_GET_SIZE(heap) < 1) { + PyErr_SetString(PyExc_IndexError, "index out of range"); + return NULL; + } + + returnitem = PyList_GET_ITEM(heap, 0); + Py_INCREF(item); + PyList_SET_ITEM(heap, 0, item); + if (_siftup((PyListObject *)heap, 0) == -1) { + Py_DECREF(returnitem); + return NULL; + } + return returnitem; } PyDoc_STRVAR(heapreplace_doc, @@ -197,44 +197,44 @@ more appropriate when using a fixed-size heap. Note that the value\n\ returned may be larger than item! That constrains reasonable uses of\n\ this routine unless written as part of a conditional replacement:\n\n\ - if item > heap[0]:\n\ - item = heapreplace(heap, item)\n"); + if item > heap[0]:\n\ + item = heapreplace(heap, item)\n"); static PyObject * heappushpop(PyObject *self, PyObject *args) { - PyObject *heap, *item, *returnitem; - int cmp; + PyObject *heap, *item, *returnitem; + int cmp; - if (!PyArg_UnpackTuple(args, "heappushpop", 2, 2, &heap, &item)) - return NULL; + if (!PyArg_UnpackTuple(args, "heappushpop", 2, 2, &heap, &item)) + return NULL; - if (!PyList_Check(heap)) { - PyErr_SetString(PyExc_TypeError, "heap argument must be a list"); - return NULL; - } - - if (PyList_GET_SIZE(heap) < 1) { - Py_INCREF(item); - return item; - } - - cmp = cmp_lt(PyList_GET_ITEM(heap, 0), item); - if (cmp == -1) - return NULL; - if (cmp == 0) { - Py_INCREF(item); - return item; - } - - returnitem = PyList_GET_ITEM(heap, 0); - Py_INCREF(item); - PyList_SET_ITEM(heap, 0, item); - if (_siftup((PyListObject *)heap, 0) == -1) { - Py_DECREF(returnitem); - return NULL; - } - return returnitem; + if (!PyList_Check(heap)) { + PyErr_SetString(PyExc_TypeError, "heap argument must be a list"); + return NULL; + } + + if (PyList_GET_SIZE(heap) < 1) { + Py_INCREF(item); + return item; + } + + cmp = cmp_lt(PyList_GET_ITEM(heap, 0), item); + if (cmp == -1) + return NULL; + if (cmp == 0) { + Py_INCREF(item); + return item; + } + + returnitem = PyList_GET_ITEM(heap, 0); + Py_INCREF(item); + PyList_SET_ITEM(heap, 0, item); + if (_siftup((PyListObject *)heap, 0) == -1) { + Py_DECREF(returnitem); + return NULL; + } + return returnitem; } PyDoc_STRVAR(heappushpop_doc, @@ -245,26 +245,26 @@ static PyObject * heapify(PyObject *self, PyObject *heap) { - Py_ssize_t i, n; + Py_ssize_t i, n; - if (!PyList_Check(heap)) { - PyErr_SetString(PyExc_TypeError, "heap argument must be a list"); - return NULL; - } - - n = PyList_GET_SIZE(heap); - /* Transform bottom-up. The largest index there's any point to - looking at is the largest with a child index in-range, so must - have 2*i + 1 < n, or i < (n-1)/2. If n is even = 2*j, this is - (2*j-1)/2 = j-1/2 so j-1 is the largest, which is n//2 - 1. If - n is odd = 2*j+1, this is (2*j+1-1)/2 = j so j-1 is the largest, - and that's again n//2-1. - */ - for (i=n/2-1 ; i>=0 ; i--) - if(_siftup((PyListObject *)heap, i) == -1) - return NULL; - Py_INCREF(Py_None); - return Py_None; + if (!PyList_Check(heap)) { + PyErr_SetString(PyExc_TypeError, "heap argument must be a list"); + return NULL; + } + + n = PyList_GET_SIZE(heap); + /* Transform bottom-up. The largest index there's any point to + looking at is the largest with a child index in-range, so must + have 2*i + 1 < n, or i < (n-1)/2. If n is even = 2*j, this is + (2*j-1)/2 = j-1/2 so j-1 is the largest, which is n//2 - 1. If + n is odd = 2*j+1, this is (2*j+1-1)/2 = j so j-1 is the largest, + and that's again n//2-1. + */ + for (i=n/2-1 ; i>=0 ; i--) + if(_siftup((PyListObject *)heap, i) == -1) + return NULL; + Py_INCREF(Py_None); + return Py_None; } PyDoc_STRVAR(heapify_doc, @@ -273,79 +273,79 @@ static PyObject * nlargest(PyObject *self, PyObject *args) { - PyObject *heap=NULL, *elem, *iterable, *sol, *it, *oldelem; - Py_ssize_t i, n; - int cmp; - - if (!PyArg_ParseTuple(args, "nO:nlargest", &n, &iterable)) - return NULL; - - it = PyObject_GetIter(iterable); - if (it == NULL) - return NULL; - - heap = PyList_New(0); - if (heap == NULL) - goto fail; - - for (i=0 ; i=0 ; i--) - if(_siftup((PyListObject *)heap, i) == -1) - goto fail; - - sol = PyList_GET_ITEM(heap, 0); - while (1) { - elem = PyIter_Next(it); - if (elem == NULL) { - if (PyErr_Occurred()) - goto fail; - else - goto sortit; - } - cmp = cmp_lt(sol, elem); - if (cmp == -1) { - Py_DECREF(elem); - goto fail; - } - if (cmp == 0) { - Py_DECREF(elem); - continue; - } - oldelem = PyList_GET_ITEM(heap, 0); - PyList_SET_ITEM(heap, 0, elem); - Py_DECREF(oldelem); - if (_siftup((PyListObject *)heap, 0) == -1) - goto fail; - sol = PyList_GET_ITEM(heap, 0); - } + PyObject *heap=NULL, *elem, *iterable, *sol, *it, *oldelem; + Py_ssize_t i, n; + int cmp; + + if (!PyArg_ParseTuple(args, "nO:nlargest", &n, &iterable)) + return NULL; + + it = PyObject_GetIter(iterable); + if (it == NULL) + return NULL; + + heap = PyList_New(0); + if (heap == NULL) + goto fail; + + for (i=0 ; i=0 ; i--) + if(_siftup((PyListObject *)heap, i) == -1) + goto fail; + + sol = PyList_GET_ITEM(heap, 0); + while (1) { + elem = PyIter_Next(it); + if (elem == NULL) { + if (PyErr_Occurred()) + goto fail; + else + goto sortit; + } + cmp = cmp_lt(sol, elem); + if (cmp == -1) { + Py_DECREF(elem); + goto fail; + } + if (cmp == 0) { + Py_DECREF(elem); + continue; + } + oldelem = PyList_GET_ITEM(heap, 0); + PyList_SET_ITEM(heap, 0, elem); + Py_DECREF(oldelem); + if (_siftup((PyListObject *)heap, 0) == -1) + goto fail; + sol = PyList_GET_ITEM(heap, 0); + } sortit: - if (PyList_Sort(heap) == -1) - goto fail; - if (PyList_Reverse(heap) == -1) - goto fail; - Py_DECREF(it); - return heap; + if (PyList_Sort(heap) == -1) + goto fail; + if (PyList_Reverse(heap) == -1) + goto fail; + Py_DECREF(it); + return heap; fail: - Py_DECREF(it); - Py_XDECREF(heap); - return NULL; + Py_DECREF(it); + Py_XDECREF(heap); + return NULL; } PyDoc_STRVAR(nlargest_doc, @@ -356,166 +356,166 @@ static int _siftdownmax(PyListObject *heap, Py_ssize_t startpos, Py_ssize_t pos) { - PyObject *newitem, *parent; - int cmp; - Py_ssize_t parentpos; - - assert(PyList_Check(heap)); - if (pos >= PyList_GET_SIZE(heap)) { - PyErr_SetString(PyExc_IndexError, "index out of range"); - return -1; - } - - newitem = PyList_GET_ITEM(heap, pos); - Py_INCREF(newitem); - /* Follow the path to the root, moving parents down until finding - a place newitem fits. */ - while (pos > startpos){ - parentpos = (pos - 1) >> 1; - parent = PyList_GET_ITEM(heap, parentpos); - cmp = cmp_lt(parent, newitem); - if (cmp == -1) { - Py_DECREF(newitem); - return -1; - } - if (cmp == 0) - break; - Py_INCREF(parent); - Py_DECREF(PyList_GET_ITEM(heap, pos)); - PyList_SET_ITEM(heap, pos, parent); - pos = parentpos; - } - Py_DECREF(PyList_GET_ITEM(heap, pos)); - PyList_SET_ITEM(heap, pos, newitem); - return 0; + PyObject *newitem, *parent; + int cmp; + Py_ssize_t parentpos; + + assert(PyList_Check(heap)); + if (pos >= PyList_GET_SIZE(heap)) { + PyErr_SetString(PyExc_IndexError, "index out of range"); + return -1; + } + + newitem = PyList_GET_ITEM(heap, pos); + Py_INCREF(newitem); + /* Follow the path to the root, moving parents down until finding + a place newitem fits. */ + while (pos > startpos){ + parentpos = (pos - 1) >> 1; + parent = PyList_GET_ITEM(heap, parentpos); + cmp = cmp_lt(parent, newitem); + if (cmp == -1) { + Py_DECREF(newitem); + return -1; + } + if (cmp == 0) + break; + Py_INCREF(parent); + Py_DECREF(PyList_GET_ITEM(heap, pos)); + PyList_SET_ITEM(heap, pos, parent); + pos = parentpos; + } + Py_DECREF(PyList_GET_ITEM(heap, pos)); + PyList_SET_ITEM(heap, pos, newitem); + return 0; } static int _siftupmax(PyListObject *heap, Py_ssize_t pos) { - Py_ssize_t startpos, endpos, childpos, rightpos; - int cmp; - PyObject *newitem, *tmp; - - assert(PyList_Check(heap)); - endpos = PyList_GET_SIZE(heap); - startpos = pos; - if (pos >= endpos) { - PyErr_SetString(PyExc_IndexError, "index out of range"); - return -1; - } - newitem = PyList_GET_ITEM(heap, pos); - Py_INCREF(newitem); - - /* Bubble up the smaller child until hitting a leaf. */ - childpos = 2*pos + 1; /* leftmost child position */ - while (childpos < endpos) { - /* Set childpos to index of smaller child. */ - rightpos = childpos + 1; - if (rightpos < endpos) { - cmp = cmp_lt( - PyList_GET_ITEM(heap, rightpos), - PyList_GET_ITEM(heap, childpos)); - if (cmp == -1) { - Py_DECREF(newitem); - return -1; - } - if (cmp == 0) - childpos = rightpos; - } - /* Move the smaller child up. */ - tmp = PyList_GET_ITEM(heap, childpos); - Py_INCREF(tmp); - Py_DECREF(PyList_GET_ITEM(heap, pos)); - PyList_SET_ITEM(heap, pos, tmp); - pos = childpos; - childpos = 2*pos + 1; - } - - /* The leaf at pos is empty now. Put newitem there, and and bubble - it up to its final resting place (by sifting its parents down). */ - Py_DECREF(PyList_GET_ITEM(heap, pos)); - PyList_SET_ITEM(heap, pos, newitem); - return _siftdownmax(heap, startpos, pos); + Py_ssize_t startpos, endpos, childpos, rightpos; + int cmp; + PyObject *newitem, *tmp; + + assert(PyList_Check(heap)); + endpos = PyList_GET_SIZE(heap); + startpos = pos; + if (pos >= endpos) { + PyErr_SetString(PyExc_IndexError, "index out of range"); + return -1; + } + newitem = PyList_GET_ITEM(heap, pos); + Py_INCREF(newitem); + + /* Bubble up the smaller child until hitting a leaf. */ + childpos = 2*pos + 1; /* leftmost child position */ + while (childpos < endpos) { + /* Set childpos to index of smaller child. */ + rightpos = childpos + 1; + if (rightpos < endpos) { + cmp = cmp_lt( + PyList_GET_ITEM(heap, rightpos), + PyList_GET_ITEM(heap, childpos)); + if (cmp == -1) { + Py_DECREF(newitem); + return -1; + } + if (cmp == 0) + childpos = rightpos; + } + /* Move the smaller child up. */ + tmp = PyList_GET_ITEM(heap, childpos); + Py_INCREF(tmp); + Py_DECREF(PyList_GET_ITEM(heap, pos)); + PyList_SET_ITEM(heap, pos, tmp); + pos = childpos; + childpos = 2*pos + 1; + } + + /* The leaf at pos is empty now. Put newitem there, and and bubble + it up to its final resting place (by sifting its parents down). */ + Py_DECREF(PyList_GET_ITEM(heap, pos)); + PyList_SET_ITEM(heap, pos, newitem); + return _siftdownmax(heap, startpos, pos); } static PyObject * nsmallest(PyObject *self, PyObject *args) { - PyObject *heap=NULL, *elem, *iterable, *los, *it, *oldelem; - Py_ssize_t i, n; - int cmp; - - if (!PyArg_ParseTuple(args, "nO:nsmallest", &n, &iterable)) - return NULL; - - it = PyObject_GetIter(iterable); - if (it == NULL) - return NULL; - - heap = PyList_New(0); - if (heap == NULL) - goto fail; - - for (i=0 ; i=0 ; i--) - if(_siftupmax((PyListObject *)heap, i) == -1) - goto fail; - - los = PyList_GET_ITEM(heap, 0); - while (1) { - elem = PyIter_Next(it); - if (elem == NULL) { - if (PyErr_Occurred()) - goto fail; - else - goto sortit; - } - cmp = cmp_lt(elem, los); - if (cmp == -1) { - Py_DECREF(elem); - goto fail; - } - if (cmp == 0) { - Py_DECREF(elem); - continue; - } - - oldelem = PyList_GET_ITEM(heap, 0); - PyList_SET_ITEM(heap, 0, elem); - Py_DECREF(oldelem); - if (_siftupmax((PyListObject *)heap, 0) == -1) - goto fail; - los = PyList_GET_ITEM(heap, 0); - } + PyObject *heap=NULL, *elem, *iterable, *los, *it, *oldelem; + Py_ssize_t i, n; + int cmp; + + if (!PyArg_ParseTuple(args, "nO:nsmallest", &n, &iterable)) + return NULL; + + it = PyObject_GetIter(iterable); + if (it == NULL) + return NULL; + + heap = PyList_New(0); + if (heap == NULL) + goto fail; + + for (i=0 ; i=0 ; i--) + if(_siftupmax((PyListObject *)heap, i) == -1) + goto fail; + + los = PyList_GET_ITEM(heap, 0); + while (1) { + elem = PyIter_Next(it); + if (elem == NULL) { + if (PyErr_Occurred()) + goto fail; + else + goto sortit; + } + cmp = cmp_lt(elem, los); + if (cmp == -1) { + Py_DECREF(elem); + goto fail; + } + if (cmp == 0) { + Py_DECREF(elem); + continue; + } + + oldelem = PyList_GET_ITEM(heap, 0); + PyList_SET_ITEM(heap, 0, elem); + Py_DECREF(oldelem); + if (_siftupmax((PyListObject *)heap, 0) == -1) + goto fail; + los = PyList_GET_ITEM(heap, 0); + } sortit: - if (PyList_Sort(heap) == -1) - goto fail; - Py_DECREF(it); - return heap; + if (PyList_Sort(heap) == -1) + goto fail; + Py_DECREF(it); + return heap; fail: - Py_DECREF(it); - Py_XDECREF(heap); - return NULL; + Py_DECREF(it); + Py_XDECREF(heap); + return NULL; } PyDoc_STRVAR(nsmallest_doc, @@ -524,21 +524,21 @@ Equivalent to: sorted(iterable)[:n]\n"); static PyMethodDef heapq_methods[] = { - {"heappush", (PyCFunction)heappush, - METH_VARARGS, heappush_doc}, - {"heappushpop", (PyCFunction)heappushpop, - METH_VARARGS, heappushpop_doc}, - {"heappop", (PyCFunction)heappop, - METH_O, heappop_doc}, - {"heapreplace", (PyCFunction)heapreplace, - METH_VARARGS, heapreplace_doc}, - {"heapify", (PyCFunction)heapify, - METH_O, heapify_doc}, - {"nlargest", (PyCFunction)nlargest, - METH_VARARGS, nlargest_doc}, - {"nsmallest", (PyCFunction)nsmallest, - METH_VARARGS, nsmallest_doc}, - {NULL, NULL} /* sentinel */ + {"heappush", (PyCFunction)heappush, + METH_VARARGS, heappush_doc}, + {"heappushpop", (PyCFunction)heappushpop, + METH_VARARGS, heappushpop_doc}, + {"heappop", (PyCFunction)heappop, + METH_O, heappop_doc}, + {"heapreplace", (PyCFunction)heapreplace, + METH_VARARGS, heapreplace_doc}, + {"heapify", (PyCFunction)heapify, + METH_O, heapify_doc}, + {"nlargest", (PyCFunction)nlargest, + METH_VARARGS, nlargest_doc}, + {"nsmallest", (PyCFunction)nsmallest, + METH_VARARGS, nsmallest_doc}, + {NULL, NULL} /* sentinel */ }; PyDoc_STRVAR(module_doc, @@ -668,27 +668,27 @@ static struct PyModuleDef _heapqmodule = { - PyModuleDef_HEAD_INIT, - "_heapq", - module_doc, - -1, - heapq_methods, - NULL, - NULL, - NULL, - NULL + PyModuleDef_HEAD_INIT, + "_heapq", + module_doc, + -1, + heapq_methods, + NULL, + NULL, + NULL, + NULL }; PyMODINIT_FUNC PyInit__heapq(void) { - PyObject *m, *about; + PyObject *m, *about; - m = PyModule_Create(&_heapqmodule); - if (m == NULL) - return NULL; - about = PyUnicode_DecodeUTF8(__about__, strlen(__about__), NULL); - PyModule_AddObject(m, "__about__", about); - return m; + m = PyModule_Create(&_heapqmodule); + if (m == NULL) + return NULL; + about = PyUnicode_DecodeUTF8(__about__, strlen(__about__), NULL); + PyModule_AddObject(m, "__about__", about); + return m; } Modified: python/branches/py3k/Modules/_json.c ============================================================================== --- python/branches/py3k/Modules/_json.c (original) +++ python/branches/py3k/Modules/_json.c Sun May 9 17:52:27 2010 @@ -511,7 +511,7 @@ rval = scanstring_unicode(pystr, end, strict, &next_end); } else { - PyErr_Format(PyExc_TypeError, + PyErr_Format(PyExc_TypeError, "first argument must be a string or bytes, not %.80s", Py_TYPE(pystr)->tp_name); return NULL; @@ -1394,7 +1394,7 @@ if (PyObject_IsTrue(s->sort_keys)) { if (code == NULL) { - code = Py_CompileString("sorted(d.items(), key=lambda kv: kv[0])", + code = Py_CompileString("sorted(d.items(), key=lambda kv: kv[0])", "_json.c", Py_eval_input); if (code == NULL) goto bail; @@ -1409,14 +1409,14 @@ } items = PyEval_EvalCode((PyCodeObject *)code, PyEval_GetGlobals(), mapping); Py_DECREF(mapping); - } else { + } else { items = PyMapping_Items(dct); - } - if (items == NULL) + } + if (items == NULL) goto bail; it = PyObject_GetIter(items); - Py_DECREF(items); - if (it == NULL) + Py_DECREF(items); + if (it == NULL) goto bail; skipkeys = PyObject_IsTrue(s->skipkeys); idx = 0; @@ -1437,8 +1437,8 @@ goto bail; } else if (key == Py_True || key == Py_False || key == Py_None) { - /* This must come before the PyLong_Check because - True and False are also 1 and 0.*/ + /* This must come before the PyLong_Check because + True and False are also 1 and 0.*/ kstr = _encoded_const(key); if (kstr == NULL) goto bail; @@ -1704,15 +1704,15 @@ "json speedups\n"); static struct PyModuleDef jsonmodule = { - PyModuleDef_HEAD_INIT, - "_json", - module_doc, - -1, - speedups_methods, - NULL, - NULL, - NULL, - NULL + PyModuleDef_HEAD_INIT, + "_json", + module_doc, + -1, + speedups_methods, + NULL, + NULL, + NULL, + NULL }; PyObject* Modified: python/branches/py3k/Modules/_localemodule.c ============================================================================== --- python/branches/py3k/Modules/_localemodule.c (original) +++ python/branches/py3k/Modules/_localemodule.c Sun May 9 17:52:27 2010 @@ -77,7 +77,7 @@ if (dest != smallbuf) PyMem_Free(dest); return res2; -} +} /* support functions for formatting floating point numbers */ @@ -243,7 +243,7 @@ PyObject *os1, *os2, *result = NULL; wchar_t *ws1 = NULL, *ws2 = NULL; Py_ssize_t len1, len2; - + if (!PyArg_ParseTuple(args, "UU:strcoll", &os1, &os2)) return NULL; /* Convert the unicode strings to wchar[]. */ @@ -373,9 +373,9 @@ #ifdef HAVE_LANGINFO_H #define LANGINFO(X) {#X, X} static struct langinfo_constant{ - char* name; - int value; -} langinfo_constants[] = + char* name; + int value; +} langinfo_constants[] = { /* These constants should exist on any langinfo implementation */ LANGINFO(DAY_1), @@ -514,10 +514,10 @@ static PyObject* PyIntl_gettext(PyObject* self, PyObject *args) { - char *in; - if (!PyArg_ParseTuple(args, "s", &in)) - return 0; - return str2uni(gettext(in)); + char *in; + if (!PyArg_ParseTuple(args, "s", &in)) + return 0; + return str2uni(gettext(in)); } PyDoc_STRVAR(dgettext__doc__, @@ -527,10 +527,10 @@ static PyObject* PyIntl_dgettext(PyObject* self, PyObject *args) { - char *domain, *in; - if (!PyArg_ParseTuple(args, "zs", &domain, &in)) - return 0; - return str2uni(dgettext(domain, in)); + char *domain, *in; + if (!PyArg_ParseTuple(args, "zs", &domain, &in)) + return 0; + return str2uni(dgettext(domain, in)); } PyDoc_STRVAR(dcgettext__doc__, @@ -540,11 +540,11 @@ static PyObject* PyIntl_dcgettext(PyObject *self, PyObject *args) { - char *domain, *msgid; - int category; - if (!PyArg_ParseTuple(args, "zsi", &domain, &msgid, &category)) - return 0; - return str2uni(dcgettext(domain,msgid,category)); + char *domain, *msgid; + int category; + if (!PyArg_ParseTuple(args, "zsi", &domain, &msgid, &category)) + return 0; + return str2uni(dcgettext(domain,msgid,category)); } PyDoc_STRVAR(textdomain__doc__, @@ -554,15 +554,15 @@ static PyObject* PyIntl_textdomain(PyObject* self, PyObject* args) { - char *domain; - if (!PyArg_ParseTuple(args, "z", &domain)) - return 0; - domain = textdomain(domain); - if (!domain) { - PyErr_SetFromErrno(PyExc_OSError); - return NULL; - } - return str2uni(domain); + char *domain; + if (!PyArg_ParseTuple(args, "z", &domain)) + return 0; + domain = textdomain(domain); + if (!domain) { + PyErr_SetFromErrno(PyExc_OSError); + return NULL; + } + return str2uni(domain); } PyDoc_STRVAR(bindtextdomain__doc__, @@ -572,19 +572,19 @@ static PyObject* PyIntl_bindtextdomain(PyObject* self,PyObject*args) { - char *domain, *dirname; - if (!PyArg_ParseTuple(args, "sz", &domain, &dirname)) - return 0; - if (!strlen(domain)) { - PyErr_SetString(Error, "domain must be a non-empty string"); - return 0; - } - dirname = bindtextdomain(domain, dirname); - if (!dirname) { - PyErr_SetFromErrno(PyExc_OSError); - return NULL; - } - return str2uni(dirname); + char *domain, *dirname; + if (!PyArg_ParseTuple(args, "sz", &domain, &dirname)) + return 0; + if (!strlen(domain)) { + PyErr_SetString(Error, "domain must be a non-empty string"); + return 0; + } + dirname = bindtextdomain(domain, dirname); + if (!dirname) { + PyErr_SetFromErrno(PyExc_OSError); + return NULL; + } + return str2uni(dirname); } #ifdef HAVE_BIND_TEXTDOMAIN_CODESET @@ -595,32 +595,32 @@ static PyObject* PyIntl_bind_textdomain_codeset(PyObject* self,PyObject*args) { - char *domain,*codeset; - if (!PyArg_ParseTuple(args, "sz", &domain, &codeset)) - return NULL; - codeset = bind_textdomain_codeset(domain, codeset); - if (codeset) - return str2uni(codeset); - Py_RETURN_NONE; + char *domain,*codeset; + if (!PyArg_ParseTuple(args, "sz", &domain, &codeset)) + return NULL; + codeset = bind_textdomain_codeset(domain, codeset); + if (codeset) + return str2uni(codeset); + Py_RETURN_NONE; } #endif #endif static struct PyMethodDef PyLocale_Methods[] = { - {"setlocale", (PyCFunction) PyLocale_setlocale, + {"setlocale", (PyCFunction) PyLocale_setlocale, METH_VARARGS, setlocale__doc__}, - {"localeconv", (PyCFunction) PyLocale_localeconv, + {"localeconv", (PyCFunction) PyLocale_localeconv, METH_NOARGS, localeconv__doc__}, #ifdef HAVE_WCSCOLL - {"strcoll", (PyCFunction) PyLocale_strcoll, + {"strcoll", (PyCFunction) PyLocale_strcoll, METH_VARARGS, strcoll__doc__}, #endif #ifdef HAVE_WCSXFRM - {"strxfrm", (PyCFunction) PyLocale_strxfrm, + {"strxfrm", (PyCFunction) PyLocale_strxfrm, METH_VARARGS, strxfrm__doc__}, #endif -#if defined(MS_WINDOWS) +#if defined(MS_WINDOWS) {"_getdefaultlocale", (PyCFunction) PyLocale_getdefaultlocale, METH_NOARGS}, #endif #ifdef HAVE_LANGINFO_H @@ -642,21 +642,21 @@ {"bind_textdomain_codeset",(PyCFunction)PyIntl_bind_textdomain_codeset, METH_VARARGS, bind_textdomain_codeset__doc__}, #endif -#endif +#endif {NULL, NULL} }; static struct PyModuleDef _localemodule = { - PyModuleDef_HEAD_INIT, - "_locale", - locale__doc__, - -1, - PyLocale_Methods, - NULL, - NULL, - NULL, - NULL + PyModuleDef_HEAD_INIT, + "_locale", + locale__doc__, + -1, + PyLocale_Methods, + NULL, + NULL, + NULL, + NULL }; PyMODINIT_FUNC @@ -669,7 +669,7 @@ m = PyModule_Create(&_localemodule); if (m == NULL) - return NULL; + return NULL; d = PyModule_GetDict(m); @@ -712,14 +712,14 @@ #ifdef HAVE_LANGINFO_H for (i = 0; langinfo_constants[i].name; i++) { - PyModule_AddIntConstant(m, langinfo_constants[i].name, - langinfo_constants[i].value); + PyModule_AddIntConstant(m, langinfo_constants[i].name, + langinfo_constants[i].value); } #endif return m; } -/* +/* Local variables: c-basic-offset: 4 indent-tabs-mode: nil Modified: python/branches/py3k/Modules/_lsprof.c ============================================================================== --- python/branches/py3k/Modules/_lsprof.c (original) +++ python/branches/py3k/Modules/_lsprof.c Sun May 9 17:52:27 2010 @@ -17,19 +17,19 @@ static PY_LONG_LONG hpTimer(void) { - LARGE_INTEGER li; - QueryPerformanceCounter(&li); - return li.QuadPart; + LARGE_INTEGER li; + QueryPerformanceCounter(&li); + return li.QuadPart; } static double hpTimerUnit(void) { - LARGE_INTEGER li; - if (QueryPerformanceFrequency(&li)) - return 1.0 / li.QuadPart; - else - return 0.000001; /* unlikely */ + LARGE_INTEGER li; + if (QueryPerformanceFrequency(&li)) + return 1.0 / li.QuadPart; + else + return 0.000001; /* unlikely */ } #else /* !MS_WINDOWS */ @@ -48,22 +48,22 @@ static PY_LONG_LONG hpTimer(void) { - struct timeval tv; - PY_LONG_LONG ret; + struct timeval tv; + PY_LONG_LONG ret; #ifdef GETTIMEOFDAY_NO_TZ - gettimeofday(&tv); + gettimeofday(&tv); #else - gettimeofday(&tv, (struct timezone *)NULL); + gettimeofday(&tv, (struct timezone *)NULL); #endif - ret = tv.tv_sec; - ret = ret * 1000000 + tv.tv_usec; - return ret; + ret = tv.tv_sec; + ret = ret * 1000000 + tv.tv_usec; + return ret; } static double hpTimerUnit(void) { - return 0.000001; + return 0.000001; } #endif /* MS_WINDOWS */ @@ -75,41 +75,41 @@ /* represents a function called from another function */ typedef struct _ProfilerSubEntry { - rotating_node_t header; - PY_LONG_LONG tt; - PY_LONG_LONG it; - long callcount; - long recursivecallcount; - long recursionLevel; + rotating_node_t header; + PY_LONG_LONG tt; + PY_LONG_LONG it; + long callcount; + long recursivecallcount; + long recursionLevel; } ProfilerSubEntry; /* represents a function or user defined block */ typedef struct _ProfilerEntry { - rotating_node_t header; - PyObject *userObj; /* PyCodeObject, or a descriptive str for builtins */ - PY_LONG_LONG tt; /* total time in this entry */ - PY_LONG_LONG it; /* inline time in this entry (not in subcalls) */ - long callcount; /* how many times this was called */ - long recursivecallcount; /* how many times called recursively */ - long recursionLevel; - rotating_node_t *calls; + rotating_node_t header; + PyObject *userObj; /* PyCodeObject, or a descriptive str for builtins */ + PY_LONG_LONG tt; /* total time in this entry */ + PY_LONG_LONG it; /* inline time in this entry (not in subcalls) */ + long callcount; /* how many times this was called */ + long recursivecallcount; /* how many times called recursively */ + long recursionLevel; + rotating_node_t *calls; } ProfilerEntry; typedef struct _ProfilerContext { - PY_LONG_LONG t0; - PY_LONG_LONG subt; - struct _ProfilerContext *previous; - ProfilerEntry *ctxEntry; + PY_LONG_LONG t0; + PY_LONG_LONG subt; + struct _ProfilerContext *previous; + ProfilerEntry *ctxEntry; } ProfilerContext; typedef struct { - PyObject_HEAD - rotating_node_t *profilerEntries; - ProfilerContext *currentProfilerContext; - ProfilerContext *freelistProfilerContext; - int flags; - PyObject *externalTimer; - double externalTimerUnit; + PyObject_HEAD + rotating_node_t *profilerEntries; + ProfilerContext *currentProfilerContext; + ProfilerContext *freelistProfilerContext; + int flags; + PyObject *externalTimer; + double externalTimerUnit; } ProfilerObject; #define POF_ENABLED 0x001 @@ -129,407 +129,407 @@ static PY_LONG_LONG CallExternalTimer(ProfilerObject *pObj) { - PY_LONG_LONG result; - PyObject *o = PyObject_Call(pObj->externalTimer, empty_tuple, NULL); - if (o == NULL) { - PyErr_WriteUnraisable(pObj->externalTimer); - return 0; - } - if (pObj->externalTimerUnit > 0.0) { - /* interpret the result as an integer that will be scaled - in profiler_getstats() */ - result = PyLong_AsLongLong(o); - } - else { - /* interpret the result as a double measured in seconds. - As the profiler works with PY_LONG_LONG internally - we convert it to a large integer */ - double val = PyFloat_AsDouble(o); - /* error handling delayed to the code below */ - result = (PY_LONG_LONG) (val * DOUBLE_TIMER_PRECISION); - } - Py_DECREF(o); - if (PyErr_Occurred()) { - PyErr_WriteUnraisable(pObj->externalTimer); - return 0; - } - return result; -} - -#define CALL_TIMER(pObj) ((pObj)->externalTimer ? \ - CallExternalTimer(pObj) : \ - hpTimer()) + PY_LONG_LONG result; + PyObject *o = PyObject_Call(pObj->externalTimer, empty_tuple, NULL); + if (o == NULL) { + PyErr_WriteUnraisable(pObj->externalTimer); + return 0; + } + if (pObj->externalTimerUnit > 0.0) { + /* interpret the result as an integer that will be scaled + in profiler_getstats() */ + result = PyLong_AsLongLong(o); + } + else { + /* interpret the result as a double measured in seconds. + As the profiler works with PY_LONG_LONG internally + we convert it to a large integer */ + double val = PyFloat_AsDouble(o); + /* error handling delayed to the code below */ + result = (PY_LONG_LONG) (val * DOUBLE_TIMER_PRECISION); + } + Py_DECREF(o); + if (PyErr_Occurred()) { + PyErr_WriteUnraisable(pObj->externalTimer); + return 0; + } + return result; +} + +#define CALL_TIMER(pObj) ((pObj)->externalTimer ? \ + CallExternalTimer(pObj) : \ + hpTimer()) /*** ProfilerObject ***/ static PyObject * normalizeUserObj(PyObject *obj) { - PyCFunctionObject *fn; - if (!PyCFunction_Check(obj)) { - Py_INCREF(obj); - return obj; - } - /* Replace built-in function objects with a descriptive string - because of built-in methods -- keeping a reference to - __self__ is probably not a good idea. */ - fn = (PyCFunctionObject *)obj; - - if (fn->m_self == NULL) { - /* built-in function: look up the module name */ - PyObject *mod = fn->m_module; - const char *modname; - if (mod && PyUnicode_Check(mod)) { - modname = _PyUnicode_AsString(mod); - } - else if (mod && PyModule_Check(mod)) { - modname = PyModule_GetName(mod); - if (modname == NULL) { - PyErr_Clear(); - modname = "builtins"; - } - } - else { - modname = "builtins"; - } - if (strcmp(modname, "builtins") != 0) - return PyUnicode_FromFormat("<%s.%s>", - modname, - fn->m_ml->ml_name); - else - return PyUnicode_FromFormat("<%s>", - fn->m_ml->ml_name); - } - else { - /* built-in method: try to return - repr(getattr(type(__self__), __name__)) - */ - PyObject *self = fn->m_self; - PyObject *name = PyUnicode_FromString(fn->m_ml->ml_name); - if (name != NULL) { - PyObject *mo = _PyType_Lookup(Py_TYPE(self), name); - Py_XINCREF(mo); - Py_DECREF(name); - if (mo != NULL) { - PyObject *res = PyObject_Repr(mo); - Py_DECREF(mo); - if (res != NULL) - return res; - } - } - PyErr_Clear(); - return PyUnicode_FromFormat("", - fn->m_ml->ml_name); - } + PyCFunctionObject *fn; + if (!PyCFunction_Check(obj)) { + Py_INCREF(obj); + return obj; + } + /* Replace built-in function objects with a descriptive string + because of built-in methods -- keeping a reference to + __self__ is probably not a good idea. */ + fn = (PyCFunctionObject *)obj; + + if (fn->m_self == NULL) { + /* built-in function: look up the module name */ + PyObject *mod = fn->m_module; + const char *modname; + if (mod && PyUnicode_Check(mod)) { + modname = _PyUnicode_AsString(mod); + } + else if (mod && PyModule_Check(mod)) { + modname = PyModule_GetName(mod); + if (modname == NULL) { + PyErr_Clear(); + modname = "builtins"; + } + } + else { + modname = "builtins"; + } + if (strcmp(modname, "builtins") != 0) + return PyUnicode_FromFormat("<%s.%s>", + modname, + fn->m_ml->ml_name); + else + return PyUnicode_FromFormat("<%s>", + fn->m_ml->ml_name); + } + else { + /* built-in method: try to return + repr(getattr(type(__self__), __name__)) + */ + PyObject *self = fn->m_self; + PyObject *name = PyUnicode_FromString(fn->m_ml->ml_name); + if (name != NULL) { + PyObject *mo = _PyType_Lookup(Py_TYPE(self), name); + Py_XINCREF(mo); + Py_DECREF(name); + if (mo != NULL) { + PyObject *res = PyObject_Repr(mo); + Py_DECREF(mo); + if (res != NULL) + return res; + } + } + PyErr_Clear(); + return PyUnicode_FromFormat("", + fn->m_ml->ml_name); + } } static ProfilerEntry* newProfilerEntry(ProfilerObject *pObj, void *key, PyObject *userObj) { - ProfilerEntry *self; - self = (ProfilerEntry*) malloc(sizeof(ProfilerEntry)); - if (self == NULL) { - pObj->flags |= POF_NOMEMORY; - return NULL; - } - userObj = normalizeUserObj(userObj); - if (userObj == NULL) { - PyErr_Clear(); - free(self); - pObj->flags |= POF_NOMEMORY; - return NULL; - } - self->header.key = key; - self->userObj = userObj; - self->tt = 0; - self->it = 0; - self->callcount = 0; - self->recursivecallcount = 0; - self->recursionLevel = 0; - self->calls = EMPTY_ROTATING_TREE; - RotatingTree_Add(&pObj->profilerEntries, &self->header); - return self; + ProfilerEntry *self; + self = (ProfilerEntry*) malloc(sizeof(ProfilerEntry)); + if (self == NULL) { + pObj->flags |= POF_NOMEMORY; + return NULL; + } + userObj = normalizeUserObj(userObj); + if (userObj == NULL) { + PyErr_Clear(); + free(self); + pObj->flags |= POF_NOMEMORY; + return NULL; + } + self->header.key = key; + self->userObj = userObj; + self->tt = 0; + self->it = 0; + self->callcount = 0; + self->recursivecallcount = 0; + self->recursionLevel = 0; + self->calls = EMPTY_ROTATING_TREE; + RotatingTree_Add(&pObj->profilerEntries, &self->header); + return self; } static ProfilerEntry* getEntry(ProfilerObject *pObj, void *key) { - return (ProfilerEntry*) RotatingTree_Get(&pObj->profilerEntries, key); + return (ProfilerEntry*) RotatingTree_Get(&pObj->profilerEntries, key); } -static ProfilerSubEntry * +static ProfilerSubEntry * getSubEntry(ProfilerObject *pObj, ProfilerEntry *caller, ProfilerEntry* entry) { - return (ProfilerSubEntry*) RotatingTree_Get(&caller->calls, - (void *)entry); + return (ProfilerSubEntry*) RotatingTree_Get(&caller->calls, + (void *)entry); } static ProfilerSubEntry * newSubEntry(ProfilerObject *pObj, ProfilerEntry *caller, ProfilerEntry* entry) { - ProfilerSubEntry *self; - self = (ProfilerSubEntry*) malloc(sizeof(ProfilerSubEntry)); - if (self == NULL) { - pObj->flags |= POF_NOMEMORY; - return NULL; - } - self->header.key = (void *)entry; - self->tt = 0; - self->it = 0; - self->callcount = 0; - self->recursivecallcount = 0; - self->recursionLevel = 0; - RotatingTree_Add(&caller->calls, &self->header); - return self; + ProfilerSubEntry *self; + self = (ProfilerSubEntry*) malloc(sizeof(ProfilerSubEntry)); + if (self == NULL) { + pObj->flags |= POF_NOMEMORY; + return NULL; + } + self->header.key = (void *)entry; + self->tt = 0; + self->it = 0; + self->callcount = 0; + self->recursivecallcount = 0; + self->recursionLevel = 0; + RotatingTree_Add(&caller->calls, &self->header); + return self; } static int freeSubEntry(rotating_node_t *header, void *arg) { - ProfilerSubEntry *subentry = (ProfilerSubEntry*) header; - free(subentry); - return 0; + ProfilerSubEntry *subentry = (ProfilerSubEntry*) header; + free(subentry); + return 0; } static int freeEntry(rotating_node_t *header, void *arg) { - ProfilerEntry *entry = (ProfilerEntry*) header; - RotatingTree_Enum(entry->calls, freeSubEntry, NULL); - Py_DECREF(entry->userObj); - free(entry); - return 0; + ProfilerEntry *entry = (ProfilerEntry*) header; + RotatingTree_Enum(entry->calls, freeSubEntry, NULL); + Py_DECREF(entry->userObj); + free(entry); + return 0; } static void clearEntries(ProfilerObject *pObj) { - RotatingTree_Enum(pObj->profilerEntries, freeEntry, NULL); - pObj->profilerEntries = EMPTY_ROTATING_TREE; - /* release the memory hold by the ProfilerContexts */ - if (pObj->currentProfilerContext) { - free(pObj->currentProfilerContext); - pObj->currentProfilerContext = NULL; - } - while (pObj->freelistProfilerContext) { - ProfilerContext *c = pObj->freelistProfilerContext; - pObj->freelistProfilerContext = c->previous; - free(c); - } - pObj->freelistProfilerContext = NULL; + RotatingTree_Enum(pObj->profilerEntries, freeEntry, NULL); + pObj->profilerEntries = EMPTY_ROTATING_TREE; + /* release the memory hold by the ProfilerContexts */ + if (pObj->currentProfilerContext) { + free(pObj->currentProfilerContext); + pObj->currentProfilerContext = NULL; + } + while (pObj->freelistProfilerContext) { + ProfilerContext *c = pObj->freelistProfilerContext; + pObj->freelistProfilerContext = c->previous; + free(c); + } + pObj->freelistProfilerContext = NULL; } static void initContext(ProfilerObject *pObj, ProfilerContext *self, ProfilerEntry *entry) { - self->ctxEntry = entry; - self->subt = 0; - self->previous = pObj->currentProfilerContext; - pObj->currentProfilerContext = self; - ++entry->recursionLevel; - if ((pObj->flags & POF_SUBCALLS) && self->previous) { - /* find or create an entry for me in my caller's entry */ - ProfilerEntry *caller = self->previous->ctxEntry; - ProfilerSubEntry *subentry = getSubEntry(pObj, caller, entry); - if (subentry == NULL) - subentry = newSubEntry(pObj, caller, entry); - if (subentry) - ++subentry->recursionLevel; - } - self->t0 = CALL_TIMER(pObj); + self->ctxEntry = entry; + self->subt = 0; + self->previous = pObj->currentProfilerContext; + pObj->currentProfilerContext = self; + ++entry->recursionLevel; + if ((pObj->flags & POF_SUBCALLS) && self->previous) { + /* find or create an entry for me in my caller's entry */ + ProfilerEntry *caller = self->previous->ctxEntry; + ProfilerSubEntry *subentry = getSubEntry(pObj, caller, entry); + if (subentry == NULL) + subentry = newSubEntry(pObj, caller, entry); + if (subentry) + ++subentry->recursionLevel; + } + self->t0 = CALL_TIMER(pObj); } static void Stop(ProfilerObject *pObj, ProfilerContext *self, ProfilerEntry *entry) { - PY_LONG_LONG tt = CALL_TIMER(pObj) - self->t0; - PY_LONG_LONG it = tt - self->subt; - if (self->previous) - self->previous->subt += tt; - pObj->currentProfilerContext = self->previous; - if (--entry->recursionLevel == 0) - entry->tt += tt; - else - ++entry->recursivecallcount; - entry->it += it; - entry->callcount++; - if ((pObj->flags & POF_SUBCALLS) && self->previous) { - /* find or create an entry for me in my caller's entry */ - ProfilerEntry *caller = self->previous->ctxEntry; - ProfilerSubEntry *subentry = getSubEntry(pObj, caller, entry); - if (subentry) { - if (--subentry->recursionLevel == 0) - subentry->tt += tt; - else - ++subentry->recursivecallcount; - subentry->it += it; - ++subentry->callcount; - } - } + PY_LONG_LONG tt = CALL_TIMER(pObj) - self->t0; + PY_LONG_LONG it = tt - self->subt; + if (self->previous) + self->previous->subt += tt; + pObj->currentProfilerContext = self->previous; + if (--entry->recursionLevel == 0) + entry->tt += tt; + else + ++entry->recursivecallcount; + entry->it += it; + entry->callcount++; + if ((pObj->flags & POF_SUBCALLS) && self->previous) { + /* find or create an entry for me in my caller's entry */ + ProfilerEntry *caller = self->previous->ctxEntry; + ProfilerSubEntry *subentry = getSubEntry(pObj, caller, entry); + if (subentry) { + if (--subentry->recursionLevel == 0) + subentry->tt += tt; + else + ++subentry->recursivecallcount; + subentry->it += it; + ++subentry->callcount; + } + } } static void ptrace_enter_call(PyObject *self, void *key, PyObject *userObj) { - /* entering a call to the function identified by 'key' - (which can be a PyCodeObject or a PyMethodDef pointer) */ - ProfilerObject *pObj = (ProfilerObject*)self; - ProfilerEntry *profEntry; - ProfilerContext *pContext; - - /* In the case of entering a generator expression frame via a - * throw (gen_send_ex(.., 1)), we may already have an - * Exception set here. We must not mess around with this - * exception, and some of the code under here assumes that - * PyErr_* is its own to mess around with, so we have to - * save and restore any current exception. */ - PyObject *last_type, *last_value, *last_tb; - PyErr_Fetch(&last_type, &last_value, &last_tb); - - profEntry = getEntry(pObj, key); - if (profEntry == NULL) { - profEntry = newProfilerEntry(pObj, key, userObj); - if (profEntry == NULL) - goto restorePyerr; - } - /* grab a ProfilerContext out of the free list */ - pContext = pObj->freelistProfilerContext; - if (pContext) { - pObj->freelistProfilerContext = pContext->previous; - } - else { - /* free list exhausted, allocate a new one */ - pContext = (ProfilerContext*) - malloc(sizeof(ProfilerContext)); - if (pContext == NULL) { - pObj->flags |= POF_NOMEMORY; - goto restorePyerr; - } - } - initContext(pObj, pContext, profEntry); + /* entering a call to the function identified by 'key' + (which can be a PyCodeObject or a PyMethodDef pointer) */ + ProfilerObject *pObj = (ProfilerObject*)self; + ProfilerEntry *profEntry; + ProfilerContext *pContext; + + /* In the case of entering a generator expression frame via a + * throw (gen_send_ex(.., 1)), we may already have an + * Exception set here. We must not mess around with this + * exception, and some of the code under here assumes that + * PyErr_* is its own to mess around with, so we have to + * save and restore any current exception. */ + PyObject *last_type, *last_value, *last_tb; + PyErr_Fetch(&last_type, &last_value, &last_tb); + + profEntry = getEntry(pObj, key); + if (profEntry == NULL) { + profEntry = newProfilerEntry(pObj, key, userObj); + if (profEntry == NULL) + goto restorePyerr; + } + /* grab a ProfilerContext out of the free list */ + pContext = pObj->freelistProfilerContext; + if (pContext) { + pObj->freelistProfilerContext = pContext->previous; + } + else { + /* free list exhausted, allocate a new one */ + pContext = (ProfilerContext*) + malloc(sizeof(ProfilerContext)); + if (pContext == NULL) { + pObj->flags |= POF_NOMEMORY; + goto restorePyerr; + } + } + initContext(pObj, pContext, profEntry); restorePyerr: - PyErr_Restore(last_type, last_value, last_tb); + PyErr_Restore(last_type, last_value, last_tb); } static void ptrace_leave_call(PyObject *self, void *key) { - /* leaving a call to the function identified by 'key' */ - ProfilerObject *pObj = (ProfilerObject*)self; - ProfilerEntry *profEntry; - ProfilerContext *pContext; - - pContext = pObj->currentProfilerContext; - if (pContext == NULL) - return; - profEntry = getEntry(pObj, key); - if (profEntry) { - Stop(pObj, pContext, profEntry); - } - else { - pObj->currentProfilerContext = pContext->previous; - } - /* put pContext into the free list */ - pContext->previous = pObj->freelistProfilerContext; - pObj->freelistProfilerContext = pContext; + /* leaving a call to the function identified by 'key' */ + ProfilerObject *pObj = (ProfilerObject*)self; + ProfilerEntry *profEntry; + ProfilerContext *pContext; + + pContext = pObj->currentProfilerContext; + if (pContext == NULL) + return; + profEntry = getEntry(pObj, key); + if (profEntry) { + Stop(pObj, pContext, profEntry); + } + else { + pObj->currentProfilerContext = pContext->previous; + } + /* put pContext into the free list */ + pContext->previous = pObj->freelistProfilerContext; + pObj->freelistProfilerContext = pContext; } static int profiler_callback(PyObject *self, PyFrameObject *frame, int what, - PyObject *arg) + PyObject *arg) { - switch (what) { + switch (what) { - /* the 'frame' of a called function is about to start its execution */ - case PyTrace_CALL: - ptrace_enter_call(self, (void *)frame->f_code, - (PyObject *)frame->f_code); - break; - - /* the 'frame' of a called function is about to finish - (either normally or with an exception) */ - case PyTrace_RETURN: - ptrace_leave_call(self, (void *)frame->f_code); - break; - - /* case PyTrace_EXCEPTION: - If the exception results in the function exiting, a - PyTrace_RETURN event will be generated, so we don't need to - handle it. */ - -#ifdef PyTrace_C_CALL /* not defined in Python <= 2.3 */ - /* the Python function 'frame' is issuing a call to the built-in - function 'arg' */ - case PyTrace_C_CALL: - if ((((ProfilerObject *)self)->flags & POF_BUILTINS) - && PyCFunction_Check(arg)) { - ptrace_enter_call(self, - ((PyCFunctionObject *)arg)->m_ml, - arg); - } - break; - - /* the call to the built-in function 'arg' is returning into its - caller 'frame' */ - case PyTrace_C_RETURN: /* ...normally */ - case PyTrace_C_EXCEPTION: /* ...with an exception set */ - if ((((ProfilerObject *)self)->flags & POF_BUILTINS) - && PyCFunction_Check(arg)) { - ptrace_leave_call(self, - ((PyCFunctionObject *)arg)->m_ml); - } - break; + /* the 'frame' of a called function is about to start its execution */ + case PyTrace_CALL: + ptrace_enter_call(self, (void *)frame->f_code, + (PyObject *)frame->f_code); + break; + + /* the 'frame' of a called function is about to finish + (either normally or with an exception) */ + case PyTrace_RETURN: + ptrace_leave_call(self, (void *)frame->f_code); + break; + + /* case PyTrace_EXCEPTION: + If the exception results in the function exiting, a + PyTrace_RETURN event will be generated, so we don't need to + handle it. */ + +#ifdef PyTrace_C_CALL /* not defined in Python <= 2.3 */ + /* the Python function 'frame' is issuing a call to the built-in + function 'arg' */ + case PyTrace_C_CALL: + if ((((ProfilerObject *)self)->flags & POF_BUILTINS) + && PyCFunction_Check(arg)) { + ptrace_enter_call(self, + ((PyCFunctionObject *)arg)->m_ml, + arg); + } + break; + + /* the call to the built-in function 'arg' is returning into its + caller 'frame' */ + case PyTrace_C_RETURN: /* ...normally */ + case PyTrace_C_EXCEPTION: /* ...with an exception set */ + if ((((ProfilerObject *)self)->flags & POF_BUILTINS) + && PyCFunction_Check(arg)) { + ptrace_leave_call(self, + ((PyCFunctionObject *)arg)->m_ml); + } + break; #endif - default: - break; - } - return 0; + default: + break; + } + return 0; } static int pending_exception(ProfilerObject *pObj) { - if (pObj->flags & POF_NOMEMORY) { - pObj->flags -= POF_NOMEMORY; - PyErr_SetString(PyExc_MemoryError, - "memory was exhausted while profiling"); - return -1; - } - return 0; + if (pObj->flags & POF_NOMEMORY) { + pObj->flags -= POF_NOMEMORY; + PyErr_SetString(PyExc_MemoryError, + "memory was exhausted while profiling"); + return -1; + } + return 0; } /************************************************************/ static PyStructSequence_Field profiler_entry_fields[] = { - {"code", "code object or built-in function name"}, - {"callcount", "how many times this was called"}, - {"reccallcount", "how many times called recursively"}, - {"totaltime", "total time in this entry"}, - {"inlinetime", "inline time in this entry (not in subcalls)"}, - {"calls", "details of the calls"}, - {0} + {"code", "code object or built-in function name"}, + {"callcount", "how many times this was called"}, + {"reccallcount", "how many times called recursively"}, + {"totaltime", "total time in this entry"}, + {"inlinetime", "inline time in this entry (not in subcalls)"}, + {"calls", "details of the calls"}, + {0} }; static PyStructSequence_Field profiler_subentry_fields[] = { - {"code", "called code object or built-in function name"}, - {"callcount", "how many times this is called"}, - {"reccallcount", "how many times this is called recursively"}, - {"totaltime", "total time spent in this call"}, - {"inlinetime", "inline time (not in further subcalls)"}, - {0} + {"code", "called code object or built-in function name"}, + {"callcount", "how many times this is called"}, + {"reccallcount", "how many times this is called recursively"}, + {"totaltime", "total time spent in this call"}, + {"inlinetime", "inline time (not in further subcalls)"}, + {0} }; static PyStructSequence_Desc profiler_entry_desc = { - "_lsprof.profiler_entry", /* name */ - NULL, /* doc */ - profiler_entry_fields, - 6 + "_lsprof.profiler_entry", /* name */ + NULL, /* doc */ + profiler_entry_fields, + 6 }; static PyStructSequence_Desc profiler_subentry_desc = { - "_lsprof.profiler_subentry", /* name */ - NULL, /* doc */ - profiler_subentry_fields, - 5 + "_lsprof.profiler_subentry", /* name */ + NULL, /* doc */ + profiler_subentry_fields, + 5 }; static int initialized; @@ -538,70 +538,70 @@ typedef struct { - PyObject *list; - PyObject *sublist; - double factor; + PyObject *list; + PyObject *sublist; + double factor; } statscollector_t; static int statsForSubEntry(rotating_node_t *node, void *arg) { - ProfilerSubEntry *sentry = (ProfilerSubEntry*) node; - statscollector_t *collect = (statscollector_t*) arg; - ProfilerEntry *entry = (ProfilerEntry*) sentry->header.key; - int err; - PyObject *sinfo; - sinfo = PyObject_CallFunction((PyObject*) &StatsSubEntryType, - "((Olldd))", - entry->userObj, - sentry->callcount, - sentry->recursivecallcount, - collect->factor * sentry->tt, - collect->factor * sentry->it); - if (sinfo == NULL) - return -1; - err = PyList_Append(collect->sublist, sinfo); - Py_DECREF(sinfo); - return err; + ProfilerSubEntry *sentry = (ProfilerSubEntry*) node; + statscollector_t *collect = (statscollector_t*) arg; + ProfilerEntry *entry = (ProfilerEntry*) sentry->header.key; + int err; + PyObject *sinfo; + sinfo = PyObject_CallFunction((PyObject*) &StatsSubEntryType, + "((Olldd))", + entry->userObj, + sentry->callcount, + sentry->recursivecallcount, + collect->factor * sentry->tt, + collect->factor * sentry->it); + if (sinfo == NULL) + return -1; + err = PyList_Append(collect->sublist, sinfo); + Py_DECREF(sinfo); + return err; } static int statsForEntry(rotating_node_t *node, void *arg) { - ProfilerEntry *entry = (ProfilerEntry*) node; - statscollector_t *collect = (statscollector_t*) arg; - PyObject *info; - int err; - if (entry->callcount == 0) - return 0; /* skip */ - - if (entry->calls != EMPTY_ROTATING_TREE) { - collect->sublist = PyList_New(0); - if (collect->sublist == NULL) - return -1; - if (RotatingTree_Enum(entry->calls, - statsForSubEntry, collect) != 0) { - Py_DECREF(collect->sublist); - return -1; - } - } - else { - Py_INCREF(Py_None); - collect->sublist = Py_None; - } - - info = PyObject_CallFunction((PyObject*) &StatsEntryType, - "((OllddO))", - entry->userObj, - entry->callcount, - entry->recursivecallcount, - collect->factor * entry->tt, - collect->factor * entry->it, - collect->sublist); - Py_DECREF(collect->sublist); - if (info == NULL) - return -1; - err = PyList_Append(collect->list, info); - Py_DECREF(info); - return err; + ProfilerEntry *entry = (ProfilerEntry*) node; + statscollector_t *collect = (statscollector_t*) arg; + PyObject *info; + int err; + if (entry->callcount == 0) + return 0; /* skip */ + + if (entry->calls != EMPTY_ROTATING_TREE) { + collect->sublist = PyList_New(0); + if (collect->sublist == NULL) + return -1; + if (RotatingTree_Enum(entry->calls, + statsForSubEntry, collect) != 0) { + Py_DECREF(collect->sublist); + return -1; + } + } + else { + Py_INCREF(Py_None); + collect->sublist = Py_None; + } + + info = PyObject_CallFunction((PyObject*) &StatsEntryType, + "((OllddO))", + entry->userObj, + entry->callcount, + entry->recursivecallcount, + collect->factor * entry->tt, + collect->factor * entry->it, + collect->sublist); + Py_DECREF(collect->sublist); + if (info == NULL) + return -1; + err = PyList_Append(collect->list, info); + Py_DECREF(info); + return err; } PyDoc_STRVAR(getstats_doc, "\ @@ -631,51 +631,51 @@ static PyObject* profiler_getstats(ProfilerObject *pObj, PyObject* noarg) { - statscollector_t collect; - if (pending_exception(pObj)) - return NULL; - if (!pObj->externalTimer) - collect.factor = hpTimerUnit(); - else if (pObj->externalTimerUnit > 0.0) - collect.factor = pObj->externalTimerUnit; - else - collect.factor = 1.0 / DOUBLE_TIMER_PRECISION; - collect.list = PyList_New(0); - if (collect.list == NULL) - return NULL; - if (RotatingTree_Enum(pObj->profilerEntries, statsForEntry, &collect) - != 0) { - Py_DECREF(collect.list); - return NULL; - } - return collect.list; + statscollector_t collect; + if (pending_exception(pObj)) + return NULL; + if (!pObj->externalTimer) + collect.factor = hpTimerUnit(); + else if (pObj->externalTimerUnit > 0.0) + collect.factor = pObj->externalTimerUnit; + else + collect.factor = 1.0 / DOUBLE_TIMER_PRECISION; + collect.list = PyList_New(0); + if (collect.list == NULL) + return NULL; + if (RotatingTree_Enum(pObj->profilerEntries, statsForEntry, &collect) + != 0) { + Py_DECREF(collect.list); + return NULL; + } + return collect.list; } static int setSubcalls(ProfilerObject *pObj, int nvalue) { - if (nvalue == 0) - pObj->flags &= ~POF_SUBCALLS; - else if (nvalue > 0) - pObj->flags |= POF_SUBCALLS; - return 0; + if (nvalue == 0) + pObj->flags &= ~POF_SUBCALLS; + else if (nvalue > 0) + pObj->flags |= POF_SUBCALLS; + return 0; } static int setBuiltins(ProfilerObject *pObj, int nvalue) { - if (nvalue == 0) - pObj->flags &= ~POF_BUILTINS; - else if (nvalue > 0) { + if (nvalue == 0) + pObj->flags &= ~POF_BUILTINS; + else if (nvalue > 0) { #ifndef PyTrace_C_CALL - PyErr_SetString(PyExc_ValueError, - "builtins=True requires Python >= 2.4"); - return -1; + PyErr_SetString(PyExc_ValueError, + "builtins=True requires Python >= 2.4"); + return -1; #else - pObj->flags |= POF_BUILTINS; + pObj->flags |= POF_BUILTINS; #endif - } - return 0; + } + return 0; } PyDoc_STRVAR(enable_doc, "\ @@ -691,33 +691,33 @@ static PyObject* profiler_enable(ProfilerObject *self, PyObject *args, PyObject *kwds) { - int subcalls = -1; - int builtins = -1; - static char *kwlist[] = {"subcalls", "builtins", 0}; - if (!PyArg_ParseTupleAndKeywords(args, kwds, "|ii:enable", - kwlist, &subcalls, &builtins)) - return NULL; - if (setSubcalls(self, subcalls) < 0 || setBuiltins(self, builtins) < 0) - return NULL; - PyEval_SetProfile(profiler_callback, (PyObject*)self); - self->flags |= POF_ENABLED; - Py_INCREF(Py_None); - return Py_None; + int subcalls = -1; + int builtins = -1; + static char *kwlist[] = {"subcalls", "builtins", 0}; + if (!PyArg_ParseTupleAndKeywords(args, kwds, "|ii:enable", + kwlist, &subcalls, &builtins)) + return NULL; + if (setSubcalls(self, subcalls) < 0 || setBuiltins(self, builtins) < 0) + return NULL; + PyEval_SetProfile(profiler_callback, (PyObject*)self); + self->flags |= POF_ENABLED; + Py_INCREF(Py_None); + return Py_None; } static void flush_unmatched(ProfilerObject *pObj) { - while (pObj->currentProfilerContext) { - ProfilerContext *pContext = pObj->currentProfilerContext; - ProfilerEntry *profEntry= pContext->ctxEntry; - if (profEntry) - Stop(pObj, pContext, profEntry); - else - pObj->currentProfilerContext = pContext->previous; - if (pContext) - free(pContext); - } + while (pObj->currentProfilerContext) { + ProfilerContext *pContext = pObj->currentProfilerContext; + ProfilerEntry *profEntry= pContext->ctxEntry; + if (profEntry) + Stop(pObj, pContext, profEntry); + else + pObj->currentProfilerContext = pContext->previous; + if (pContext) + free(pContext); + } } @@ -730,13 +730,13 @@ static PyObject* profiler_disable(ProfilerObject *self, PyObject* noarg) { - self->flags &= ~POF_ENABLED; - PyEval_SetProfile(NULL, NULL); - flush_unmatched(self); - if (pending_exception(self)) - return NULL; - Py_INCREF(Py_None); - return Py_None; + self->flags &= ~POF_ENABLED; + PyEval_SetProfile(NULL, NULL); + flush_unmatched(self); + if (pending_exception(self)) + return NULL; + Py_INCREF(Py_None); + return Py_None; } PyDoc_STRVAR(clear_doc, "\ @@ -748,62 +748,62 @@ static PyObject* profiler_clear(ProfilerObject *pObj, PyObject* noarg) { - clearEntries(pObj); - Py_INCREF(Py_None); - return Py_None; + clearEntries(pObj); + Py_INCREF(Py_None); + return Py_None; } static void profiler_dealloc(ProfilerObject *op) { - if (op->flags & POF_ENABLED) - PyEval_SetProfile(NULL, NULL); - flush_unmatched(op); - clearEntries(op); - Py_XDECREF(op->externalTimer); - Py_TYPE(op)->tp_free(op); + if (op->flags & POF_ENABLED) + PyEval_SetProfile(NULL, NULL); + flush_unmatched(op); + clearEntries(op); + Py_XDECREF(op->externalTimer); + Py_TYPE(op)->tp_free(op); } static int profiler_init(ProfilerObject *pObj, PyObject *args, PyObject *kw) { - PyObject *o; - PyObject *timer = NULL; - double timeunit = 0.0; - int subcalls = 1; + PyObject *o; + PyObject *timer = NULL; + double timeunit = 0.0; + int subcalls = 1; #ifdef PyTrace_C_CALL - int builtins = 1; + int builtins = 1; #else - int builtins = 0; + int builtins = 0; #endif - static char *kwlist[] = {"timer", "timeunit", - "subcalls", "builtins", 0}; + static char *kwlist[] = {"timer", "timeunit", + "subcalls", "builtins", 0}; - if (!PyArg_ParseTupleAndKeywords(args, kw, "|Odii:Profiler", kwlist, - &timer, &timeunit, - &subcalls, &builtins)) - return -1; - - if (setSubcalls(pObj, subcalls) < 0 || setBuiltins(pObj, builtins) < 0) - return -1; - o = pObj->externalTimer; - pObj->externalTimer = timer; - Py_XINCREF(timer); - Py_XDECREF(o); - pObj->externalTimerUnit = timeunit; - return 0; + if (!PyArg_ParseTupleAndKeywords(args, kw, "|Odii:Profiler", kwlist, + &timer, &timeunit, + &subcalls, &builtins)) + return -1; + + if (setSubcalls(pObj, subcalls) < 0 || setBuiltins(pObj, builtins) < 0) + return -1; + o = pObj->externalTimer; + pObj->externalTimer = timer; + Py_XINCREF(timer); + Py_XDECREF(o); + pObj->externalTimerUnit = timeunit; + return 0; } static PyMethodDef profiler_methods[] = { - {"getstats", (PyCFunction)profiler_getstats, - METH_NOARGS, getstats_doc}, - {"enable", (PyCFunction)profiler_enable, - METH_VARARGS | METH_KEYWORDS, enable_doc}, - {"disable", (PyCFunction)profiler_disable, - METH_NOARGS, disable_doc}, - {"clear", (PyCFunction)profiler_clear, - METH_NOARGS, clear_doc}, - {NULL, NULL} + {"getstats", (PyCFunction)profiler_getstats, + METH_NOARGS, getstats_doc}, + {"enable", (PyCFunction)profiler_enable, + METH_VARARGS | METH_KEYWORDS, enable_doc}, + {"disable", (PyCFunction)profiler_disable, + METH_NOARGS, disable_doc}, + {"clear", (PyCFunction)profiler_clear, + METH_NOARGS, clear_doc}, + {NULL, NULL} }; PyDoc_STRVAR(profiler_doc, "\ @@ -817,89 +817,89 @@ "); static PyTypeObject PyProfiler_Type = { - PyVarObject_HEAD_INIT(NULL, 0) - "_lsprof.Profiler", /* tp_name */ - sizeof(ProfilerObject), /* tp_basicsize */ - 0, /* tp_itemsize */ - (destructor)profiler_dealloc, /* tp_dealloc */ - 0, /* tp_print */ - 0, /* tp_getattr */ - 0, /* tp_setattr */ - 0, /* tp_reserved */ - 0, /* tp_repr */ - 0, /* tp_as_number */ - 0, /* tp_as_sequence */ - 0, /* tp_as_mapping */ - 0, /* tp_hash */ - 0, /* tp_call */ - 0, /* tp_str */ - 0, /* tp_getattro */ - 0, /* tp_setattro */ - 0, /* tp_as_buffer */ - Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */ - profiler_doc, /* tp_doc */ - 0, /* tp_traverse */ - 0, /* tp_clear */ - 0, /* tp_richcompare */ - 0, /* tp_weaklistoffset */ - 0, /* tp_iter */ - 0, /* tp_iternext */ - profiler_methods, /* tp_methods */ - 0, /* tp_members */ - 0, /* tp_getset */ - 0, /* tp_base */ - 0, /* tp_dict */ - 0, /* tp_descr_get */ - 0, /* tp_descr_set */ - 0, /* tp_dictoffset */ - (initproc)profiler_init, /* tp_init */ - PyType_GenericAlloc, /* tp_alloc */ - PyType_GenericNew, /* tp_new */ - PyObject_Del, /* tp_free */ + PyVarObject_HEAD_INIT(NULL, 0) + "_lsprof.Profiler", /* tp_name */ + sizeof(ProfilerObject), /* tp_basicsize */ + 0, /* tp_itemsize */ + (destructor)profiler_dealloc, /* tp_dealloc */ + 0, /* tp_print */ + 0, /* tp_getattr */ + 0, /* tp_setattr */ + 0, /* tp_reserved */ + 0, /* tp_repr */ + 0, /* tp_as_number */ + 0, /* tp_as_sequence */ + 0, /* tp_as_mapping */ + 0, /* tp_hash */ + 0, /* tp_call */ + 0, /* tp_str */ + 0, /* tp_getattro */ + 0, /* tp_setattro */ + 0, /* tp_as_buffer */ + Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */ + profiler_doc, /* tp_doc */ + 0, /* tp_traverse */ + 0, /* tp_clear */ + 0, /* tp_richcompare */ + 0, /* tp_weaklistoffset */ + 0, /* tp_iter */ + 0, /* tp_iternext */ + profiler_methods, /* tp_methods */ + 0, /* tp_members */ + 0, /* tp_getset */ + 0, /* tp_base */ + 0, /* tp_dict */ + 0, /* tp_descr_get */ + 0, /* tp_descr_set */ + 0, /* tp_dictoffset */ + (initproc)profiler_init, /* tp_init */ + PyType_GenericAlloc, /* tp_alloc */ + PyType_GenericNew, /* tp_new */ + PyObject_Del, /* tp_free */ }; static PyMethodDef moduleMethods[] = { - {NULL, NULL} + {NULL, NULL} }; static struct PyModuleDef _lsprofmodule = { - PyModuleDef_HEAD_INIT, - "_lsprof", - "Fast profiler", - -1, - moduleMethods, - NULL, - NULL, - NULL, - NULL + PyModuleDef_HEAD_INIT, + "_lsprof", + "Fast profiler", + -1, + moduleMethods, + NULL, + NULL, + NULL, + NULL }; PyMODINIT_FUNC PyInit__lsprof(void) { - PyObject *module, *d; - module = PyModule_Create(&_lsprofmodule); - if (module == NULL) - return NULL; - d = PyModule_GetDict(module); - if (PyType_Ready(&PyProfiler_Type) < 0) - return NULL; - PyDict_SetItemString(d, "Profiler", (PyObject *)&PyProfiler_Type); - - if (!initialized) { - PyStructSequence_InitType(&StatsEntryType, - &profiler_entry_desc); - PyStructSequence_InitType(&StatsSubEntryType, - &profiler_subentry_desc); - } - Py_INCREF((PyObject*) &StatsEntryType); - Py_INCREF((PyObject*) &StatsSubEntryType); - PyModule_AddObject(module, "profiler_entry", - (PyObject*) &StatsEntryType); - PyModule_AddObject(module, "profiler_subentry", - (PyObject*) &StatsSubEntryType); - empty_tuple = PyTuple_New(0); - initialized = 1; - return module; + PyObject *module, *d; + module = PyModule_Create(&_lsprofmodule); + if (module == NULL) + return NULL; + d = PyModule_GetDict(module); + if (PyType_Ready(&PyProfiler_Type) < 0) + return NULL; + PyDict_SetItemString(d, "Profiler", (PyObject *)&PyProfiler_Type); + + if (!initialized) { + PyStructSequence_InitType(&StatsEntryType, + &profiler_entry_desc); + PyStructSequence_InitType(&StatsSubEntryType, + &profiler_subentry_desc); + } + Py_INCREF((PyObject*) &StatsEntryType); + Py_INCREF((PyObject*) &StatsSubEntryType); + PyModule_AddObject(module, "profiler_entry", + (PyObject*) &StatsEntryType); + PyModule_AddObject(module, "profiler_subentry", + (PyObject*) &StatsSubEntryType); + empty_tuple = PyTuple_New(0); + initialized = 1; + return module; } Modified: python/branches/py3k/Modules/_math.c ============================================================================== --- python/branches/py3k/Modules/_math.c (original) +++ python/branches/py3k/Modules/_math.c Sun May 9 17:52:27 2010 @@ -14,7 +14,7 @@ * * Developed at SunPro, a Sun Microsystems, Inc. business. * Permission to use, copy, modify, and distribute this - * software is freely granted, provided that this notice + * software is freely granted, provided that this notice * is preserved. * ==================================================== */ @@ -27,11 +27,11 @@ /* acosh(x) * Method : * Based on - * acosh(x) = log [ x + sqrt(x*x-1) ] + * acosh(x) = log [ x + sqrt(x*x-1) ] * we have - * acosh(x) := log(x)+ln2, if x is large; else - * acosh(x) := log(2x-1/(sqrt(x*x-1)+x)) if x>2; else - * acosh(x) := log1p(t+sqrt(2.0*t+t*t)); where t=x-1. + * acosh(x) := log(x)+ln2, if x is large; else + * acosh(x) := log(2x-1/(sqrt(x*x-1)+x)) if x>2; else + * acosh(x) := log1p(t+sqrt(2.0*t+t*t)); where t=x-1. * * Special cases: * acosh(x) is NaN with signal if x<1. @@ -41,82 +41,82 @@ double _Py_acosh(double x) { - if (Py_IS_NAN(x)) { - return x+x; - } - if (x < 1.) { /* x < 1; return a signaling NaN */ - errno = EDOM; + if (Py_IS_NAN(x)) { + return x+x; + } + if (x < 1.) { /* x < 1; return a signaling NaN */ + errno = EDOM; #ifdef Py_NAN - return Py_NAN; + return Py_NAN; #else - return (x-x)/(x-x); + return (x-x)/(x-x); #endif - } - else if (x >= two_pow_p28) { /* x > 2**28 */ - if (Py_IS_INFINITY(x)) { - return x+x; - } else { - return log(x)+ln2; /* acosh(huge)=log(2x) */ - } - } - else if (x == 1.) { - return 0.0; /* acosh(1) = 0 */ - } - else if (x > 2.) { /* 2 < x < 2**28 */ - double t = x*x; - return log(2.0*x - 1.0 / (x + sqrt(t - 1.0))); - } - else { /* 1 < x <= 2 */ - double t = x - 1.0; - return m_log1p(t + sqrt(2.0*t + t*t)); - } + } + else if (x >= two_pow_p28) { /* x > 2**28 */ + if (Py_IS_INFINITY(x)) { + return x+x; + } else { + return log(x)+ln2; /* acosh(huge)=log(2x) */ + } + } + else if (x == 1.) { + return 0.0; /* acosh(1) = 0 */ + } + else if (x > 2.) { /* 2 < x < 2**28 */ + double t = x*x; + return log(2.0*x - 1.0 / (x + sqrt(t - 1.0))); + } + else { /* 1 < x <= 2 */ + double t = x - 1.0; + return m_log1p(t + sqrt(2.0*t + t*t)); + } } /* asinh(x) * Method : - * Based on - * asinh(x) = sign(x) * log [ |x| + sqrt(x*x+1) ] - * we have - * asinh(x) := x if 1+x*x=1, - * := sign(x)*(log(x)+ln2)) for large |x|, else - * := sign(x)*log(2|x|+1/(|x|+sqrt(x*x+1))) if|x|>2, else - * := sign(x)*log1p(|x| + x^2/(1 + sqrt(1+x^2))) + * Based on + * asinh(x) = sign(x) * log [ |x| + sqrt(x*x+1) ] + * we have + * asinh(x) := x if 1+x*x=1, + * := sign(x)*(log(x)+ln2)) for large |x|, else + * := sign(x)*log(2|x|+1/(|x|+sqrt(x*x+1))) if|x|>2, else + * := sign(x)*log1p(|x| + x^2/(1 + sqrt(1+x^2))) */ double _Py_asinh(double x) -{ - double w; - double absx = fabs(x); - - if (Py_IS_NAN(x) || Py_IS_INFINITY(x)) { - return x+x; - } - if (absx < two_pow_m28) { /* |x| < 2**-28 */ - return x; /* return x inexact except 0 */ - } - if (absx > two_pow_p28) { /* |x| > 2**28 */ - w = log(absx)+ln2; - } - else if (absx > 2.0) { /* 2 < |x| < 2**28 */ - w = log(2.0*absx + 1.0 / (sqrt(x*x + 1.0) + absx)); - } - else { /* 2**-28 <= |x| < 2= */ - double t = x*x; - w = m_log1p(absx + t / (1.0 + sqrt(1.0 + t))); - } - return copysign(w, x); - +{ + double w; + double absx = fabs(x); + + if (Py_IS_NAN(x) || Py_IS_INFINITY(x)) { + return x+x; + } + if (absx < two_pow_m28) { /* |x| < 2**-28 */ + return x; /* return x inexact except 0 */ + } + if (absx > two_pow_p28) { /* |x| > 2**28 */ + w = log(absx)+ln2; + } + else if (absx > 2.0) { /* 2 < |x| < 2**28 */ + w = log(2.0*absx + 1.0 / (sqrt(x*x + 1.0) + absx)); + } + else { /* 2**-28 <= |x| < 2= */ + double t = x*x; + w = m_log1p(absx + t / (1.0 + sqrt(1.0 + t))); + } + return copysign(w, x); + } /* atanh(x) * Method : * 1.Reduced x to positive by atanh(-x) = -atanh(x) * 2.For x>=0.5 - * 1 2x x + * 1 2x x * atanh(x) = --- * log(1 + -------) = 0.5 * log1p(2 * --------) - * 2 1 - x 1 - x + * 2 1 - x 1 - x * * For x<0.5 * atanh(x) = 0.5*log1p(2x+2x*x/(1-x)) @@ -130,32 +130,32 @@ double _Py_atanh(double x) { - double absx; - double t; + double absx; + double t; - if (Py_IS_NAN(x)) { - return x+x; - } - absx = fabs(x); - if (absx >= 1.) { /* |x| >= 1 */ - errno = EDOM; + if (Py_IS_NAN(x)) { + return x+x; + } + absx = fabs(x); + if (absx >= 1.) { /* |x| >= 1 */ + errno = EDOM; #ifdef Py_NAN - return Py_NAN; + return Py_NAN; #else - return x/zero; + return x/zero; #endif - } - if (absx < two_pow_m28) { /* |x| < 2**-28 */ - return x; - } - if (absx < 0.5) { /* |x| < 0.5 */ - t = absx+absx; - t = 0.5 * m_log1p(t + t*absx / (1.0 - absx)); - } - else { /* 0.5 <= |x| <= 1.0 */ - t = 0.5 * m_log1p((absx + absx) / (1.0 - absx)); - } - return copysign(t, x); + } + if (absx < two_pow_m28) { /* |x| < 2**-28 */ + return x; + } + if (absx < 0.5) { /* |x| < 0.5 */ + t = absx+absx; + t = 0.5 * m_log1p(t + t*absx / (1.0 - absx)); + } + else { /* 0.5 <= |x| <= 1.0 */ + t = 0.5 * m_log1p((absx + absx) / (1.0 - absx)); + } + return copysign(t, x); } /* Mathematically, expm1(x) = exp(x) - 1. The expm1 function is designed @@ -173,15 +173,15 @@ */ if (fabs(x) < 0.7) { - double u; - u = exp(x); - if (u == 1.0) - return x; - else - return (u - 1.0) * x / log(u); + double u; + u = exp(x); + if (u == 1.0) + return x; + else + return (u - 1.0) * x / log(u); } else - return exp(x) - 1.0; + return exp(x) - 1.0; } /* log1p(x) = log(1+x). The log1p function is designed to avoid the @@ -194,7 +194,7 @@ /* For x small, we use the following approach. Let y be the nearest float to 1+x, then - 1+x = y * (1 - (y-1-x)/y) + 1+x = y * (1 - (y-1-x)/y) so log(1+x) = log(y) + log(1-(y-1-x)/y). Since (y-1-x)/y is tiny, the second term is well approximated by (y-1-x)/y. If abs(x) >= @@ -213,17 +213,17 @@ double y; if (fabs(x) < DBL_EPSILON/2.) { - return x; + return x; } else if (-0.5 <= x && x <= 1.) { - /* WARNING: it's possible than an overeager compiler - will incorrectly optimize the following two lines - to the equivalent of "return log(1.+x)". If this - happens, then results from log1p will be inaccurate - for small x. */ - y = 1.+x; - return log(y)-((y-1.)-x)/y; + /* WARNING: it's possible than an overeager compiler + will incorrectly optimize the following two lines + to the equivalent of "return log(1.+x)". If this + happens, then results from log1p will be inaccurate + for small x. */ + y = 1.+x; + return log(y)-((y-1.)-x)/y; } else { - /* NaNs and infinities should end up here */ - return log(1.+x); + /* NaNs and infinities should end up here */ + return log(1.+x); } } Modified: python/branches/py3k/Modules/_multiprocessing/connection.h ============================================================================== --- python/branches/py3k/Modules/_multiprocessing/connection.h (original) +++ python/branches/py3k/Modules/_multiprocessing/connection.h Sun May 9 17:52:27 2010 @@ -1,5 +1,5 @@ /* - * Definition of a `Connection` type. + * Definition of a `Connection` type. * Used by `socket_connection.c` and `pipe_connection.c`. * * connection.h @@ -19,14 +19,14 @@ #define CHECK_READABLE(self) \ if (!(self->flags & READABLE)) { \ - PyErr_SetString(PyExc_IOError, "connection is write-only"); \ - return NULL; \ + PyErr_SetString(PyExc_IOError, "connection is write-only"); \ + return NULL; \ } #define CHECK_WRITABLE(self) \ if (!(self->flags & WRITABLE)) { \ - PyErr_SetString(PyExc_IOError, "connection is read-only"); \ - return NULL; \ + PyErr_SetString(PyExc_IOError, "connection is read-only"); \ + return NULL; \ } /* @@ -36,57 +36,57 @@ static PyObject * connection_new(PyTypeObject *type, PyObject *args, PyObject *kwds) { - ConnectionObject *self; - HANDLE handle; - BOOL readable = TRUE, writable = TRUE; - - static char *kwlist[] = {"handle", "readable", "writable", NULL}; - - if (!PyArg_ParseTupleAndKeywords(args, kwds, F_HANDLE "|ii", kwlist, - &handle, &readable, &writable)) - return NULL; - - if (handle == INVALID_HANDLE_VALUE || (Py_ssize_t)handle < 0) { - PyErr_Format(PyExc_IOError, "invalid handle %zd", - (Py_ssize_t)handle); - return NULL; - } - - if (!readable && !writable) { - PyErr_SetString(PyExc_ValueError, - "either readable or writable must be true"); - return NULL; - } - - self = PyObject_New(ConnectionObject, type); - if (self == NULL) - return NULL; - - self->weakreflist = NULL; - self->handle = handle; - self->flags = 0; - - if (readable) - self->flags |= READABLE; - if (writable) - self->flags |= WRITABLE; - assert(self->flags >= 1 && self->flags <= 3); + ConnectionObject *self; + HANDLE handle; + BOOL readable = TRUE, writable = TRUE; + + static char *kwlist[] = {"handle", "readable", "writable", NULL}; + + if (!PyArg_ParseTupleAndKeywords(args, kwds, F_HANDLE "|ii", kwlist, + &handle, &readable, &writable)) + return NULL; + + if (handle == INVALID_HANDLE_VALUE || (Py_ssize_t)handle < 0) { + PyErr_Format(PyExc_IOError, "invalid handle %zd", + (Py_ssize_t)handle); + return NULL; + } + + if (!readable && !writable) { + PyErr_SetString(PyExc_ValueError, + "either readable or writable must be true"); + return NULL; + } - return (PyObject*)self; + self = PyObject_New(ConnectionObject, type); + if (self == NULL) + return NULL; + + self->weakreflist = NULL; + self->handle = handle; + self->flags = 0; + + if (readable) + self->flags |= READABLE; + if (writable) + self->flags |= WRITABLE; + assert(self->flags >= 1 && self->flags <= 3); + + return (PyObject*)self; } static void connection_dealloc(ConnectionObject* self) { - if (self->weakreflist != NULL) - PyObject_ClearWeakRefs((PyObject*)self); + if (self->weakreflist != NULL) + PyObject_ClearWeakRefs((PyObject*)self); - if (self->handle != INVALID_HANDLE_VALUE) { - Py_BEGIN_ALLOW_THREADS - CLOSE(self->handle); - Py_END_ALLOW_THREADS - } - PyObject_Del(self); + if (self->handle != INVALID_HANDLE_VALUE) { + Py_BEGIN_ALLOW_THREADS + CLOSE(self->handle); + Py_END_ALLOW_THREADS + } + PyObject_Del(self); } /* @@ -96,168 +96,168 @@ static PyObject * connection_sendbytes(ConnectionObject *self, PyObject *args) { - Py_buffer pbuffer; - char *buffer; - Py_ssize_t length, offset=0, size=PY_SSIZE_T_MIN; - int res; - - if (!PyArg_ParseTuple(args, F_RBUFFER "*|" F_PY_SSIZE_T F_PY_SSIZE_T, - &pbuffer, &offset, &size)) - return NULL; - buffer = pbuffer.buf; - length = pbuffer.len; - - CHECK_WRITABLE(self); /* XXX release buffer in case of failure */ - - if (offset < 0) { - PyBuffer_Release(&pbuffer); - PyErr_SetString(PyExc_ValueError, "offset is negative"); - return NULL; - } - if (length < offset) { - PyBuffer_Release(&pbuffer); - PyErr_SetString(PyExc_ValueError, "buffer length < offset"); - return NULL; - } - - if (size == PY_SSIZE_T_MIN) { - size = length - offset; - } else { - if (size < 0) { - PyBuffer_Release(&pbuffer); - PyErr_SetString(PyExc_ValueError, "size is negative"); - return NULL; - } - if (offset + size > length) { - PyBuffer_Release(&pbuffer); - PyErr_SetString(PyExc_ValueError, - "buffer length < offset + size"); - return NULL; - } - } - - res = conn_send_string(self, buffer + offset, size); - - PyBuffer_Release(&pbuffer); - if (res < 0) { - if (PyErr_Occurred()) - return NULL; - else - return mp_SetError(PyExc_IOError, res); - } - - Py_RETURN_NONE; -} - -static PyObject * -connection_recvbytes(ConnectionObject *self, PyObject *args) -{ - char *freeme = NULL; - Py_ssize_t res, maxlength = PY_SSIZE_T_MAX; - PyObject *result = NULL; - - if (!PyArg_ParseTuple(args, "|" F_PY_SSIZE_T, &maxlength)) - return NULL; - - CHECK_READABLE(self); - - if (maxlength < 0) { - PyErr_SetString(PyExc_ValueError, "maxlength < 0"); - return NULL; - } - - res = conn_recv_string(self, self->buffer, CONNECTION_BUFFER_SIZE, - &freeme, maxlength); - - if (res < 0) { - if (res == MP_BAD_MESSAGE_LENGTH) { - if ((self->flags & WRITABLE) == 0) { - Py_BEGIN_ALLOW_THREADS - CLOSE(self->handle); - Py_END_ALLOW_THREADS - self->handle = INVALID_HANDLE_VALUE; - } else { - self->flags = WRITABLE; - } - } - mp_SetError(PyExc_IOError, res); - } else { - if (freeme == NULL) { - result = PyBytes_FromStringAndSize(self->buffer, res); - } else { - result = PyBytes_FromStringAndSize(freeme, res); - PyMem_Free(freeme); - } - } - - return result; -} - -static PyObject * -connection_recvbytes_into(ConnectionObject *self, PyObject *args) -{ - char *freeme = NULL, *buffer = NULL; - Py_ssize_t res, length, offset = 0; - PyObject *result = NULL; - Py_buffer pbuf; - - CHECK_READABLE(self); - - if (!PyArg_ParseTuple(args, "w*|" F_PY_SSIZE_T, - &pbuf, &offset)) - return NULL; - - buffer = pbuf.buf; - length = pbuf.len; - - if (offset < 0) { - PyErr_SetString(PyExc_ValueError, "negative offset"); - goto _error; - } - - if (offset > length) { - PyErr_SetString(PyExc_ValueError, "offset too large"); - goto _error; - } - - res = conn_recv_string(self, buffer+offset, length-offset, - &freeme, PY_SSIZE_T_MAX); - - if (res < 0) { - if (res == MP_BAD_MESSAGE_LENGTH) { - if ((self->flags & WRITABLE) == 0) { - Py_BEGIN_ALLOW_THREADS - CLOSE(self->handle); - Py_END_ALLOW_THREADS - self->handle = INVALID_HANDLE_VALUE; - } else { - self->flags = WRITABLE; - } - } - mp_SetError(PyExc_IOError, res); - } else { - if (freeme == NULL) { - result = PyInt_FromSsize_t(res); - } else { - result = PyObject_CallFunction(BufferTooShort, - F_RBUFFER "#", - freeme, res); - PyMem_Free(freeme); - if (result) { - PyErr_SetObject(BufferTooShort, result); - Py_DECREF(result); - } - goto _error; - } - } + Py_buffer pbuffer; + char *buffer; + Py_ssize_t length, offset=0, size=PY_SSIZE_T_MIN; + int res; + + if (!PyArg_ParseTuple(args, F_RBUFFER "*|" F_PY_SSIZE_T F_PY_SSIZE_T, + &pbuffer, &offset, &size)) + return NULL; + buffer = pbuffer.buf; + length = pbuffer.len; + + CHECK_WRITABLE(self); /* XXX release buffer in case of failure */ + + if (offset < 0) { + PyBuffer_Release(&pbuffer); + PyErr_SetString(PyExc_ValueError, "offset is negative"); + return NULL; + } + if (length < offset) { + PyBuffer_Release(&pbuffer); + PyErr_SetString(PyExc_ValueError, "buffer length < offset"); + return NULL; + } + + if (size == PY_SSIZE_T_MIN) { + size = length - offset; + } else { + if (size < 0) { + PyBuffer_Release(&pbuffer); + PyErr_SetString(PyExc_ValueError, "size is negative"); + return NULL; + } + if (offset + size > length) { + PyBuffer_Release(&pbuffer); + PyErr_SetString(PyExc_ValueError, + "buffer length < offset + size"); + return NULL; + } + } + + res = conn_send_string(self, buffer + offset, size); + + PyBuffer_Release(&pbuffer); + if (res < 0) { + if (PyErr_Occurred()) + return NULL; + else + return mp_SetError(PyExc_IOError, res); + } + + Py_RETURN_NONE; +} + +static PyObject * +connection_recvbytes(ConnectionObject *self, PyObject *args) +{ + char *freeme = NULL; + Py_ssize_t res, maxlength = PY_SSIZE_T_MAX; + PyObject *result = NULL; + + if (!PyArg_ParseTuple(args, "|" F_PY_SSIZE_T, &maxlength)) + return NULL; + + CHECK_READABLE(self); + + if (maxlength < 0) { + PyErr_SetString(PyExc_ValueError, "maxlength < 0"); + return NULL; + } + + res = conn_recv_string(self, self->buffer, CONNECTION_BUFFER_SIZE, + &freeme, maxlength); + + if (res < 0) { + if (res == MP_BAD_MESSAGE_LENGTH) { + if ((self->flags & WRITABLE) == 0) { + Py_BEGIN_ALLOW_THREADS + CLOSE(self->handle); + Py_END_ALLOW_THREADS + self->handle = INVALID_HANDLE_VALUE; + } else { + self->flags = WRITABLE; + } + } + mp_SetError(PyExc_IOError, res); + } else { + if (freeme == NULL) { + result = PyBytes_FromStringAndSize(self->buffer, res); + } else { + result = PyBytes_FromStringAndSize(freeme, res); + PyMem_Free(freeme); + } + } + + return result; +} + +static PyObject * +connection_recvbytes_into(ConnectionObject *self, PyObject *args) +{ + char *freeme = NULL, *buffer = NULL; + Py_ssize_t res, length, offset = 0; + PyObject *result = NULL; + Py_buffer pbuf; + + CHECK_READABLE(self); + + if (!PyArg_ParseTuple(args, "w*|" F_PY_SSIZE_T, + &pbuf, &offset)) + return NULL; + + buffer = pbuf.buf; + length = pbuf.len; + + if (offset < 0) { + PyErr_SetString(PyExc_ValueError, "negative offset"); + goto _error; + } + + if (offset > length) { + PyErr_SetString(PyExc_ValueError, "offset too large"); + goto _error; + } + + res = conn_recv_string(self, buffer+offset, length-offset, + &freeme, PY_SSIZE_T_MAX); + + if (res < 0) { + if (res == MP_BAD_MESSAGE_LENGTH) { + if ((self->flags & WRITABLE) == 0) { + Py_BEGIN_ALLOW_THREADS + CLOSE(self->handle); + Py_END_ALLOW_THREADS + self->handle = INVALID_HANDLE_VALUE; + } else { + self->flags = WRITABLE; + } + } + mp_SetError(PyExc_IOError, res); + } else { + if (freeme == NULL) { + result = PyInt_FromSsize_t(res); + } else { + result = PyObject_CallFunction(BufferTooShort, + F_RBUFFER "#", + freeme, res); + PyMem_Free(freeme); + if (result) { + PyErr_SetObject(BufferTooShort, result); + Py_DECREF(result); + } + goto _error; + } + } _cleanup: - PyBuffer_Release(&pbuf); - return result; + PyBuffer_Release(&pbuf); + return result; _error: - result = NULL; - goto _cleanup; + result = NULL; + goto _cleanup; } /* @@ -267,74 +267,74 @@ static PyObject * connection_send_obj(ConnectionObject *self, PyObject *obj) { - char *buffer; - int res; - Py_ssize_t length; - PyObject *pickled_string = NULL; - - CHECK_WRITABLE(self); - - pickled_string = PyObject_CallFunctionObjArgs(pickle_dumps, obj, - pickle_protocol, NULL); - if (!pickled_string) - goto failure; - - if (PyBytes_AsStringAndSize(pickled_string, &buffer, &length) < 0) - goto failure; - - res = conn_send_string(self, buffer, (int)length); - - if (res < 0) { - mp_SetError(PyExc_IOError, res); - goto failure; - } + char *buffer; + int res; + Py_ssize_t length; + PyObject *pickled_string = NULL; + + CHECK_WRITABLE(self); + + pickled_string = PyObject_CallFunctionObjArgs(pickle_dumps, obj, + pickle_protocol, NULL); + if (!pickled_string) + goto failure; + + if (PyBytes_AsStringAndSize(pickled_string, &buffer, &length) < 0) + goto failure; + + res = conn_send_string(self, buffer, (int)length); + + if (res < 0) { + mp_SetError(PyExc_IOError, res); + goto failure; + } - Py_XDECREF(pickled_string); - Py_RETURN_NONE; + Py_XDECREF(pickled_string); + Py_RETURN_NONE; failure: - Py_XDECREF(pickled_string); - return NULL; + Py_XDECREF(pickled_string); + return NULL; } static PyObject * connection_recv_obj(ConnectionObject *self) { - char *freeme = NULL; - Py_ssize_t res; - PyObject *temp = NULL, *result = NULL; - - CHECK_READABLE(self); - - res = conn_recv_string(self, self->buffer, CONNECTION_BUFFER_SIZE, - &freeme, PY_SSIZE_T_MAX); - - if (res < 0) { - if (res == MP_BAD_MESSAGE_LENGTH) { - if ((self->flags & WRITABLE) == 0) { - Py_BEGIN_ALLOW_THREADS - CLOSE(self->handle); - Py_END_ALLOW_THREADS - self->handle = INVALID_HANDLE_VALUE; - } else { - self->flags = WRITABLE; - } - } - mp_SetError(PyExc_IOError, res); - } else { - if (freeme == NULL) { - temp = PyBytes_FromStringAndSize(self->buffer, res); - } else { - temp = PyBytes_FromStringAndSize(freeme, res); - PyMem_Free(freeme); - } - } - - if (temp) - result = PyObject_CallFunctionObjArgs(pickle_loads, - temp, NULL); - Py_XDECREF(temp); - return result; + char *freeme = NULL; + Py_ssize_t res; + PyObject *temp = NULL, *result = NULL; + + CHECK_READABLE(self); + + res = conn_recv_string(self, self->buffer, CONNECTION_BUFFER_SIZE, + &freeme, PY_SSIZE_T_MAX); + + if (res < 0) { + if (res == MP_BAD_MESSAGE_LENGTH) { + if ((self->flags & WRITABLE) == 0) { + Py_BEGIN_ALLOW_THREADS + CLOSE(self->handle); + Py_END_ALLOW_THREADS + self->handle = INVALID_HANDLE_VALUE; + } else { + self->flags = WRITABLE; + } + } + mp_SetError(PyExc_IOError, res); + } else { + if (freeme == NULL) { + temp = PyBytes_FromStringAndSize(self->buffer, res); + } else { + temp = PyBytes_FromStringAndSize(freeme, res); + PyMem_Free(freeme); + } + } + + if (temp) + result = PyObject_CallFunctionObjArgs(pickle_loads, + temp, NULL); + Py_XDECREF(temp); + return result; } /* @@ -344,73 +344,73 @@ static PyObject * connection_poll(ConnectionObject *self, PyObject *args) { - PyObject *timeout_obj = NULL; - double timeout = 0.0; - int res; - - CHECK_READABLE(self); - - if (!PyArg_ParseTuple(args, "|O", &timeout_obj)) - return NULL; - - if (timeout_obj == NULL) { - timeout = 0.0; - } else if (timeout_obj == Py_None) { - timeout = -1.0; /* block forever */ - } else { - timeout = PyFloat_AsDouble(timeout_obj); - if (PyErr_Occurred()) - return NULL; - if (timeout < 0.0) - timeout = 0.0; - } - - Py_BEGIN_ALLOW_THREADS - res = conn_poll(self, timeout, _save); - Py_END_ALLOW_THREADS - - switch (res) { - case TRUE: - Py_RETURN_TRUE; - case FALSE: - Py_RETURN_FALSE; - default: - return mp_SetError(PyExc_IOError, res); - } + PyObject *timeout_obj = NULL; + double timeout = 0.0; + int res; + + CHECK_READABLE(self); + + if (!PyArg_ParseTuple(args, "|O", &timeout_obj)) + return NULL; + + if (timeout_obj == NULL) { + timeout = 0.0; + } else if (timeout_obj == Py_None) { + timeout = -1.0; /* block forever */ + } else { + timeout = PyFloat_AsDouble(timeout_obj); + if (PyErr_Occurred()) + return NULL; + if (timeout < 0.0) + timeout = 0.0; + } + + Py_BEGIN_ALLOW_THREADS + res = conn_poll(self, timeout, _save); + Py_END_ALLOW_THREADS + + switch (res) { + case TRUE: + Py_RETURN_TRUE; + case FALSE: + Py_RETURN_FALSE; + default: + return mp_SetError(PyExc_IOError, res); + } } static PyObject * connection_fileno(ConnectionObject* self) { - if (self->handle == INVALID_HANDLE_VALUE) { - PyErr_SetString(PyExc_IOError, "handle is invalid"); - return NULL; - } - return PyInt_FromLong((long)self->handle); + if (self->handle == INVALID_HANDLE_VALUE) { + PyErr_SetString(PyExc_IOError, "handle is invalid"); + return NULL; + } + return PyInt_FromLong((long)self->handle); } static PyObject * connection_close(ConnectionObject *self) { - if (self->handle != INVALID_HANDLE_VALUE) { - Py_BEGIN_ALLOW_THREADS - CLOSE(self->handle); - Py_END_ALLOW_THREADS - self->handle = INVALID_HANDLE_VALUE; - } + if (self->handle != INVALID_HANDLE_VALUE) { + Py_BEGIN_ALLOW_THREADS + CLOSE(self->handle); + Py_END_ALLOW_THREADS + self->handle = INVALID_HANDLE_VALUE; + } - Py_RETURN_NONE; + Py_RETURN_NONE; } static PyObject * connection_repr(ConnectionObject *self) { - static char *conn_type[] = {"read-only", "write-only", "read-write"}; + static char *conn_type[] = {"read-only", "write-only", "read-write"}; - assert(self->flags >= 1 && self->flags <= 3); - return FROM_FORMAT("<%s %s, handle %zd>", - conn_type[self->flags - 1], - CONNECTION_NAME, (Py_ssize_t)self->handle); + assert(self->flags >= 1 && self->flags <= 3); + return FROM_FORMAT("<%s %s, handle %zd>", + conn_type[self->flags - 1], + CONNECTION_NAME, (Py_ssize_t)self->handle); } /* @@ -420,19 +420,19 @@ static PyObject * connection_closed(ConnectionObject *self, void *closure) { - return PyBool_FromLong((long)(self->handle == INVALID_HANDLE_VALUE)); + return PyBool_FromLong((long)(self->handle == INVALID_HANDLE_VALUE)); } static PyObject * connection_readable(ConnectionObject *self, void *closure) { - return PyBool_FromLong((long)(self->flags & READABLE)); + return PyBool_FromLong((long)(self->flags & READABLE)); } static PyObject * connection_writable(ConnectionObject *self, void *closure) { - return PyBool_FromLong((long)(self->flags & WRITABLE)); + return PyBool_FromLong((long)(self->flags & WRITABLE)); } /* @@ -440,37 +440,37 @@ */ static PyMethodDef connection_methods[] = { - {"send_bytes", (PyCFunction)connection_sendbytes, METH_VARARGS, - "send the byte data from a readable buffer-like object"}, - {"recv_bytes", (PyCFunction)connection_recvbytes, METH_VARARGS, - "receive byte data as a string"}, - {"recv_bytes_into",(PyCFunction)connection_recvbytes_into,METH_VARARGS, - "receive byte data into a writeable buffer-like object\n" - "returns the number of bytes read"}, - - {"send", (PyCFunction)connection_send_obj, METH_O, - "send a (picklable) object"}, - {"recv", (PyCFunction)connection_recv_obj, METH_NOARGS, - "receive a (picklable) object"}, - - {"poll", (PyCFunction)connection_poll, METH_VARARGS, - "whether there is any input available to be read"}, - {"fileno", (PyCFunction)connection_fileno, METH_NOARGS, - "file descriptor or handle of the connection"}, - {"close", (PyCFunction)connection_close, METH_NOARGS, - "close the connection"}, + {"send_bytes", (PyCFunction)connection_sendbytes, METH_VARARGS, + "send the byte data from a readable buffer-like object"}, + {"recv_bytes", (PyCFunction)connection_recvbytes, METH_VARARGS, + "receive byte data as a string"}, + {"recv_bytes_into",(PyCFunction)connection_recvbytes_into,METH_VARARGS, + "receive byte data into a writeable buffer-like object\n" + "returns the number of bytes read"}, + + {"send", (PyCFunction)connection_send_obj, METH_O, + "send a (picklable) object"}, + {"recv", (PyCFunction)connection_recv_obj, METH_NOARGS, + "receive a (picklable) object"}, + + {"poll", (PyCFunction)connection_poll, METH_VARARGS, + "whether there is any input available to be read"}, + {"fileno", (PyCFunction)connection_fileno, METH_NOARGS, + "file descriptor or handle of the connection"}, + {"close", (PyCFunction)connection_close, METH_NOARGS, + "close the connection"}, - {NULL} /* Sentinel */ + {NULL} /* Sentinel */ }; static PyGetSetDef connection_getset[] = { - {"closed", (getter)connection_closed, NULL, - "True if the connection is closed", NULL}, - {"readable", (getter)connection_readable, NULL, - "True if the connection is readable", NULL}, - {"writable", (getter)connection_writable, NULL, - "True if the connection is writable", NULL}, - {NULL} + {"closed", (getter)connection_closed, NULL, + "True if the connection is closed", NULL}, + {"readable", (getter)connection_readable, NULL, + "True if the connection is readable", NULL}, + {"writable", (getter)connection_writable, NULL, + "True if the connection is writable", NULL}, + {NULL} }; /* @@ -478,50 +478,50 @@ */ PyDoc_STRVAR(connection_doc, - "Connection type whose constructor signature is\n\n" - " Connection(handle, readable=True, writable=True).\n\n" - "The constructor does *not* duplicate the handle."); + "Connection type whose constructor signature is\n\n" + " Connection(handle, readable=True, writable=True).\n\n" + "The constructor does *not* duplicate the handle."); PyTypeObject CONNECTION_TYPE = { - PyVarObject_HEAD_INIT(NULL, 0) - /* tp_name */ "_multiprocessing." CONNECTION_NAME, - /* tp_basicsize */ sizeof(ConnectionObject), - /* tp_itemsize */ 0, - /* tp_dealloc */ (destructor)connection_dealloc, - /* tp_print */ 0, - /* tp_getattr */ 0, - /* tp_setattr */ 0, - /* tp_reserved */ 0, - /* tp_repr */ (reprfunc)connection_repr, - /* tp_as_number */ 0, - /* tp_as_sequence */ 0, - /* tp_as_mapping */ 0, - /* tp_hash */ 0, - /* tp_call */ 0, - /* tp_str */ 0, - /* tp_getattro */ 0, - /* tp_setattro */ 0, - /* tp_as_buffer */ 0, - /* tp_flags */ Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | - Py_TPFLAGS_HAVE_WEAKREFS, - /* tp_doc */ connection_doc, - /* tp_traverse */ 0, - /* tp_clear */ 0, - /* tp_richcompare */ 0, - /* tp_weaklistoffset */ offsetof(ConnectionObject, weakreflist), - /* tp_iter */ 0, - /* tp_iternext */ 0, - /* tp_methods */ connection_methods, - /* tp_members */ 0, - /* tp_getset */ connection_getset, - /* tp_base */ 0, - /* tp_dict */ 0, - /* tp_descr_get */ 0, - /* tp_descr_set */ 0, - /* tp_dictoffset */ 0, - /* tp_init */ 0, - /* tp_alloc */ 0, - /* tp_new */ connection_new, + PyVarObject_HEAD_INIT(NULL, 0) + /* tp_name */ "_multiprocessing." CONNECTION_NAME, + /* tp_basicsize */ sizeof(ConnectionObject), + /* tp_itemsize */ 0, + /* tp_dealloc */ (destructor)connection_dealloc, + /* tp_print */ 0, + /* tp_getattr */ 0, + /* tp_setattr */ 0, + /* tp_reserved */ 0, + /* tp_repr */ (reprfunc)connection_repr, + /* tp_as_number */ 0, + /* tp_as_sequence */ 0, + /* tp_as_mapping */ 0, + /* tp_hash */ 0, + /* tp_call */ 0, + /* tp_str */ 0, + /* tp_getattro */ 0, + /* tp_setattro */ 0, + /* tp_as_buffer */ 0, + /* tp_flags */ Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | + Py_TPFLAGS_HAVE_WEAKREFS, + /* tp_doc */ connection_doc, + /* tp_traverse */ 0, + /* tp_clear */ 0, + /* tp_richcompare */ 0, + /* tp_weaklistoffset */ offsetof(ConnectionObject, weakreflist), + /* tp_iter */ 0, + /* tp_iternext */ 0, + /* tp_methods */ connection_methods, + /* tp_members */ 0, + /* tp_getset */ connection_getset, + /* tp_base */ 0, + /* tp_dict */ 0, + /* tp_descr_get */ 0, + /* tp_descr_set */ 0, + /* tp_dictoffset */ 0, + /* tp_init */ 0, + /* tp_alloc */ 0, + /* tp_new */ connection_new, }; #endif /* CONNECTION_H */ Modified: python/branches/py3k/Modules/_multiprocessing/multiprocessing.c ============================================================================== --- python/branches/py3k/Modules/_multiprocessing/multiprocessing.c (original) +++ python/branches/py3k/Modules/_multiprocessing/multiprocessing.c Sun May 9 17:52:27 2010 @@ -9,9 +9,9 @@ #include "multiprocessing.h" #ifdef SCM_RIGHTS - #define HAVE_FD_TRANSFER 1 + #define HAVE_FD_TRANSFER 1 #else - #define HAVE_FD_TRANSFER 0 + #define HAVE_FD_TRANSFER 0 #endif PyObject *create_win32_namespace(void); @@ -26,46 +26,46 @@ PyObject * mp_SetError(PyObject *Type, int num) { - switch (num) { + switch (num) { #ifdef MS_WINDOWS - case MP_STANDARD_ERROR: - if (Type == NULL) - Type = PyExc_WindowsError; - PyErr_SetExcFromWindowsErr(Type, 0); - break; - case MP_SOCKET_ERROR: - if (Type == NULL) - Type = PyExc_WindowsError; - PyErr_SetExcFromWindowsErr(Type, WSAGetLastError()); - break; + case MP_STANDARD_ERROR: + if (Type == NULL) + Type = PyExc_WindowsError; + PyErr_SetExcFromWindowsErr(Type, 0); + break; + case MP_SOCKET_ERROR: + if (Type == NULL) + Type = PyExc_WindowsError; + PyErr_SetExcFromWindowsErr(Type, WSAGetLastError()); + break; #else /* !MS_WINDOWS */ - case MP_STANDARD_ERROR: - case MP_SOCKET_ERROR: - if (Type == NULL) - Type = PyExc_OSError; - PyErr_SetFromErrno(Type); - break; + case MP_STANDARD_ERROR: + case MP_SOCKET_ERROR: + if (Type == NULL) + Type = PyExc_OSError; + PyErr_SetFromErrno(Type); + break; #endif /* !MS_WINDOWS */ - case MP_MEMORY_ERROR: - PyErr_NoMemory(); - break; - case MP_END_OF_FILE: - PyErr_SetNone(PyExc_EOFError); - break; - case MP_EARLY_END_OF_FILE: - PyErr_SetString(PyExc_IOError, - "got end of file during message"); - break; - case MP_BAD_MESSAGE_LENGTH: - PyErr_SetString(PyExc_IOError, "bad message length"); - break; - case MP_EXCEPTION_HAS_BEEN_SET: - break; - default: - PyErr_Format(PyExc_RuntimeError, - "unkown error number %d", num); - } - return NULL; + case MP_MEMORY_ERROR: + PyErr_NoMemory(); + break; + case MP_END_OF_FILE: + PyErr_SetNone(PyExc_EOFError); + break; + case MP_EARLY_END_OF_FILE: + PyErr_SetString(PyExc_IOError, + "got end of file during message"); + break; + case MP_BAD_MESSAGE_LENGTH: + PyErr_SetString(PyExc_IOError, "bad message length"); + break; + case MP_EXCEPTION_HAS_BEEN_SET: + break; + default: + PyErr_Format(PyExc_RuntimeError, + "unkown error number %d", num); + } + return NULL; } @@ -82,8 +82,8 @@ static BOOL WINAPI ProcessingCtrlHandler(DWORD dwCtrlType) { - SetEvent(sigint_event); - return FALSE; + SetEvent(sigint_event); + return FALSE; } /* @@ -101,72 +101,72 @@ static PyObject * multiprocessing_sendfd(PyObject *self, PyObject *args) { - int conn, fd, res; - char dummy_char; - char buf[CMSG_SPACE(sizeof(int))]; - struct msghdr msg = {0}; - struct iovec dummy_iov; - struct cmsghdr *cmsg; - - if (!PyArg_ParseTuple(args, "ii", &conn, &fd)) - return NULL; - - dummy_iov.iov_base = &dummy_char; - dummy_iov.iov_len = 1; - msg.msg_control = buf; - msg.msg_controllen = sizeof(buf); - msg.msg_iov = &dummy_iov; - msg.msg_iovlen = 1; - cmsg = CMSG_FIRSTHDR(&msg); - cmsg->cmsg_level = SOL_SOCKET; - cmsg->cmsg_type = SCM_RIGHTS; - cmsg->cmsg_len = CMSG_LEN(sizeof(int)); - msg.msg_controllen = cmsg->cmsg_len; - *(int*)CMSG_DATA(cmsg) = fd; - - Py_BEGIN_ALLOW_THREADS - res = sendmsg(conn, &msg, 0); - Py_END_ALLOW_THREADS - - if (res < 0) - return PyErr_SetFromErrno(PyExc_OSError); - Py_RETURN_NONE; + int conn, fd, res; + char dummy_char; + char buf[CMSG_SPACE(sizeof(int))]; + struct msghdr msg = {0}; + struct iovec dummy_iov; + struct cmsghdr *cmsg; + + if (!PyArg_ParseTuple(args, "ii", &conn, &fd)) + return NULL; + + dummy_iov.iov_base = &dummy_char; + dummy_iov.iov_len = 1; + msg.msg_control = buf; + msg.msg_controllen = sizeof(buf); + msg.msg_iov = &dummy_iov; + msg.msg_iovlen = 1; + cmsg = CMSG_FIRSTHDR(&msg); + cmsg->cmsg_level = SOL_SOCKET; + cmsg->cmsg_type = SCM_RIGHTS; + cmsg->cmsg_len = CMSG_LEN(sizeof(int)); + msg.msg_controllen = cmsg->cmsg_len; + *(int*)CMSG_DATA(cmsg) = fd; + + Py_BEGIN_ALLOW_THREADS + res = sendmsg(conn, &msg, 0); + Py_END_ALLOW_THREADS + + if (res < 0) + return PyErr_SetFromErrno(PyExc_OSError); + Py_RETURN_NONE; } static PyObject * multiprocessing_recvfd(PyObject *self, PyObject *args) { - int conn, fd, res; - char dummy_char; - char buf[CMSG_SPACE(sizeof(int))]; - struct msghdr msg = {0}; - struct iovec dummy_iov; - struct cmsghdr *cmsg; - - if (!PyArg_ParseTuple(args, "i", &conn)) - return NULL; - - dummy_iov.iov_base = &dummy_char; - dummy_iov.iov_len = 1; - msg.msg_control = buf; - msg.msg_controllen = sizeof(buf); - msg.msg_iov = &dummy_iov; - msg.msg_iovlen = 1; - cmsg = CMSG_FIRSTHDR(&msg); - cmsg->cmsg_level = SOL_SOCKET; - cmsg->cmsg_type = SCM_RIGHTS; - cmsg->cmsg_len = CMSG_LEN(sizeof(int)); - msg.msg_controllen = cmsg->cmsg_len; - - Py_BEGIN_ALLOW_THREADS - res = recvmsg(conn, &msg, 0); - Py_END_ALLOW_THREADS + int conn, fd, res; + char dummy_char; + char buf[CMSG_SPACE(sizeof(int))]; + struct msghdr msg = {0}; + struct iovec dummy_iov; + struct cmsghdr *cmsg; + + if (!PyArg_ParseTuple(args, "i", &conn)) + return NULL; + + dummy_iov.iov_base = &dummy_char; + dummy_iov.iov_len = 1; + msg.msg_control = buf; + msg.msg_controllen = sizeof(buf); + msg.msg_iov = &dummy_iov; + msg.msg_iovlen = 1; + cmsg = CMSG_FIRSTHDR(&msg); + cmsg->cmsg_level = SOL_SOCKET; + cmsg->cmsg_type = SCM_RIGHTS; + cmsg->cmsg_len = CMSG_LEN(sizeof(int)); + msg.msg_controllen = cmsg->cmsg_len; + + Py_BEGIN_ALLOW_THREADS + res = recvmsg(conn, &msg, 0); + Py_END_ALLOW_THREADS - if (res < 0) - return PyErr_SetFromErrno(PyExc_OSError); + if (res < 0) + return PyErr_SetFromErrno(PyExc_OSError); - fd = *(int*)CMSG_DATA(cmsg); - return Py_BuildValue("i", fd); + fd = *(int*)CMSG_DATA(cmsg); + return Py_BuildValue("i", fd); } #endif /* HAVE_FD_TRANSFER */ @@ -181,14 +181,14 @@ static PyObject* multiprocessing_address_of_buffer(PyObject *self, PyObject *obj) { - void *buffer; - Py_ssize_t buffer_len; + void *buffer; + Py_ssize_t buffer_len; - if (PyObject_AsWriteBuffer(obj, &buffer, &buffer_len) < 0) - return NULL; + if (PyObject_AsWriteBuffer(obj, &buffer, &buffer_len) < 0) + return NULL; - return Py_BuildValue("N" F_PY_SSIZE_T, - PyLong_FromVoidPtr(buffer), buffer_len); + return Py_BuildValue("N" F_PY_SSIZE_T, + PyLong_FromVoidPtr(buffer), buffer_len); } @@ -197,20 +197,20 @@ */ static PyMethodDef module_methods[] = { - {"address_of_buffer", multiprocessing_address_of_buffer, METH_O, - "address_of_buffer(obj) -> int\n" - "Return address of obj assuming obj supports buffer inteface"}, + {"address_of_buffer", multiprocessing_address_of_buffer, METH_O, + "address_of_buffer(obj) -> int\n" + "Return address of obj assuming obj supports buffer inteface"}, #if HAVE_FD_TRANSFER - {"sendfd", multiprocessing_sendfd, METH_VARARGS, - "sendfd(sockfd, fd) -> None\n" - "Send file descriptor given by fd over the unix domain socket\n" - "whose file decriptor is sockfd"}, - {"recvfd", multiprocessing_recvfd, METH_VARARGS, - "recvfd(sockfd) -> fd\n" - "Receive a file descriptor over a unix domain socket\n" - "whose file decriptor is sockfd"}, + {"sendfd", multiprocessing_sendfd, METH_VARARGS, + "sendfd(sockfd, fd) -> None\n" + "Send file descriptor given by fd over the unix domain socket\n" + "whose file decriptor is sockfd"}, + {"recvfd", multiprocessing_recvfd, METH_VARARGS, + "recvfd(sockfd) -> fd\n" + "Receive a file descriptor over a unix domain socket\n" + "whose file decriptor is sockfd"}, #endif - {NULL} + {NULL} }; @@ -219,117 +219,117 @@ */ static struct PyModuleDef multiprocessing_module = { - PyModuleDef_HEAD_INIT, - "_multiprocessing", - NULL, - -1, - module_methods, - NULL, - NULL, - NULL, - NULL + PyModuleDef_HEAD_INIT, + "_multiprocessing", + NULL, + -1, + module_methods, + NULL, + NULL, + NULL, + NULL }; -PyMODINIT_FUNC +PyMODINIT_FUNC PyInit__multiprocessing(void) { - PyObject *module, *temp, *value; + PyObject *module, *temp, *value; - /* Initialize module */ - module = PyModule_Create(&multiprocessing_module); - if (!module) - return NULL; - - /* Get copy of objects from pickle */ - temp = PyImport_ImportModule(PICKLE_MODULE); - if (!temp) - return NULL; - pickle_dumps = PyObject_GetAttrString(temp, "dumps"); - pickle_loads = PyObject_GetAttrString(temp, "loads"); - pickle_protocol = PyObject_GetAttrString(temp, "HIGHEST_PROTOCOL"); - Py_XDECREF(temp); - - /* Get copy of BufferTooShort */ - temp = PyImport_ImportModule("multiprocessing"); - if (!temp) - return NULL; - BufferTooShort = PyObject_GetAttrString(temp, "BufferTooShort"); - Py_XDECREF(temp); - - /* Add connection type to module */ - if (PyType_Ready(&ConnectionType) < 0) - return NULL; - Py_INCREF(&ConnectionType); - PyModule_AddObject(module, "Connection", (PyObject*)&ConnectionType); + /* Initialize module */ + module = PyModule_Create(&multiprocessing_module); + if (!module) + return NULL; + + /* Get copy of objects from pickle */ + temp = PyImport_ImportModule(PICKLE_MODULE); + if (!temp) + return NULL; + pickle_dumps = PyObject_GetAttrString(temp, "dumps"); + pickle_loads = PyObject_GetAttrString(temp, "loads"); + pickle_protocol = PyObject_GetAttrString(temp, "HIGHEST_PROTOCOL"); + Py_XDECREF(temp); + + /* Get copy of BufferTooShort */ + temp = PyImport_ImportModule("multiprocessing"); + if (!temp) + return NULL; + BufferTooShort = PyObject_GetAttrString(temp, "BufferTooShort"); + Py_XDECREF(temp); + + /* Add connection type to module */ + if (PyType_Ready(&ConnectionType) < 0) + return NULL; + Py_INCREF(&ConnectionType); + PyModule_AddObject(module, "Connection", (PyObject*)&ConnectionType); -#if defined(MS_WINDOWS) || \ +#if defined(MS_WINDOWS) || \ (defined(HAVE_SEM_OPEN) && !defined(POSIX_SEMAPHORES_NOT_ENABLED)) - /* Add SemLock type to module */ - if (PyType_Ready(&SemLockType) < 0) - return NULL; - Py_INCREF(&SemLockType); - PyDict_SetItemString(SemLockType.tp_dict, "SEM_VALUE_MAX", - Py_BuildValue("i", SEM_VALUE_MAX)); - PyModule_AddObject(module, "SemLock", (PyObject*)&SemLockType); + /* Add SemLock type to module */ + if (PyType_Ready(&SemLockType) < 0) + return NULL; + Py_INCREF(&SemLockType); + PyDict_SetItemString(SemLockType.tp_dict, "SEM_VALUE_MAX", + Py_BuildValue("i", SEM_VALUE_MAX)); + PyModule_AddObject(module, "SemLock", (PyObject*)&SemLockType); #endif #ifdef MS_WINDOWS - /* Add PipeConnection to module */ - if (PyType_Ready(&PipeConnectionType) < 0) - return NULL; - Py_INCREF(&PipeConnectionType); - PyModule_AddObject(module, "PipeConnection", - (PyObject*)&PipeConnectionType); - - /* Initialize win32 class and add to multiprocessing */ - temp = create_win32_namespace(); - if (!temp) - return NULL; - PyModule_AddObject(module, "win32", temp); - - /* Initialize the event handle used to signal Ctrl-C */ - sigint_event = CreateEvent(NULL, TRUE, FALSE, NULL); - if (!sigint_event) { - PyErr_SetFromWindowsErr(0); - return NULL; - } - if (!SetConsoleCtrlHandler(ProcessingCtrlHandler, TRUE)) { - PyErr_SetFromWindowsErr(0); - return NULL; - } + /* Add PipeConnection to module */ + if (PyType_Ready(&PipeConnectionType) < 0) + return NULL; + Py_INCREF(&PipeConnectionType); + PyModule_AddObject(module, "PipeConnection", + (PyObject*)&PipeConnectionType); + + /* Initialize win32 class and add to multiprocessing */ + temp = create_win32_namespace(); + if (!temp) + return NULL; + PyModule_AddObject(module, "win32", temp); + + /* Initialize the event handle used to signal Ctrl-C */ + sigint_event = CreateEvent(NULL, TRUE, FALSE, NULL); + if (!sigint_event) { + PyErr_SetFromWindowsErr(0); + return NULL; + } + if (!SetConsoleCtrlHandler(ProcessingCtrlHandler, TRUE)) { + PyErr_SetFromWindowsErr(0); + return NULL; + } #endif - /* Add configuration macros */ - temp = PyDict_New(); - if (!temp) - return NULL; - -#define ADD_FLAG(name) \ - value = Py_BuildValue("i", name); \ - if (value == NULL) { Py_DECREF(temp); return NULL; } \ - if (PyDict_SetItemString(temp, #name, value) < 0) { \ - Py_DECREF(temp); Py_DECREF(value); return NULL; } \ - Py_DECREF(value) - + /* Add configuration macros */ + temp = PyDict_New(); + if (!temp) + return NULL; + +#define ADD_FLAG(name) \ + value = Py_BuildValue("i", name); \ + if (value == NULL) { Py_DECREF(temp); return NULL; } \ + if (PyDict_SetItemString(temp, #name, value) < 0) { \ + Py_DECREF(temp); Py_DECREF(value); return NULL; } \ + Py_DECREF(value) + #if defined(HAVE_SEM_OPEN) && !defined(POSIX_SEMAPHORES_NOT_ENABLED) - ADD_FLAG(HAVE_SEM_OPEN); + ADD_FLAG(HAVE_SEM_OPEN); #endif #ifdef HAVE_SEM_TIMEDWAIT - ADD_FLAG(HAVE_SEM_TIMEDWAIT); + ADD_FLAG(HAVE_SEM_TIMEDWAIT); #endif #ifdef HAVE_FD_TRANSFER - ADD_FLAG(HAVE_FD_TRANSFER); + ADD_FLAG(HAVE_FD_TRANSFER); #endif #ifdef HAVE_BROKEN_SEM_GETVALUE - ADD_FLAG(HAVE_BROKEN_SEM_GETVALUE); + ADD_FLAG(HAVE_BROKEN_SEM_GETVALUE); #endif #ifdef HAVE_BROKEN_SEM_UNLINK - ADD_FLAG(HAVE_BROKEN_SEM_UNLINK); + ADD_FLAG(HAVE_BROKEN_SEM_UNLINK); #endif - if (PyModule_AddObject(module, "flags", temp) < 0) - return NULL; + if (PyModule_AddObject(module, "flags", temp) < 0) + return NULL; - return module; + return module; } Modified: python/branches/py3k/Modules/_multiprocessing/multiprocessing.h ============================================================================== --- python/branches/py3k/Modules/_multiprocessing/multiprocessing.h (original) +++ python/branches/py3k/Modules/_multiprocessing/multiprocessing.h Sun May 9 17:52:27 2010 @@ -15,7 +15,7 @@ # define WIN32_LEAN_AND_MEAN # include # include -# include /* getpid() */ +# include /* getpid() */ # ifdef Py_DEBUG # include # endif @@ -45,15 +45,15 @@ * Issue 3110 - Solaris does not define SEM_VALUE_MAX */ #ifndef SEM_VALUE_MAX - #if defined(HAVE_SYSCONF) && defined(_SC_SEM_VALUE_MAX) - # define SEM_VALUE_MAX sysconf(_SC_SEM_VALUE_MAX) - #elif defined(_SEM_VALUE_MAX) - # define SEM_VALUE_MAX _SEM_VALUE_MAX - #elif defined(_POSIX_SEM_VALUE_MAX) - # define SEM_VALUE_MAX _POSIX_SEM_VALUE_MAX - #else - # define SEM_VALUE_MAX INT_MAX - #endif + #if defined(HAVE_SYSCONF) && defined(_SC_SEM_VALUE_MAX) + # define SEM_VALUE_MAX sysconf(_SC_SEM_VALUE_MAX) + #elif defined(_SEM_VALUE_MAX) + # define SEM_VALUE_MAX _SEM_VALUE_MAX + #elif defined(_POSIX_SEM_VALUE_MAX) + # define SEM_VALUE_MAX _POSIX_SEM_VALUE_MAX + #else + # define SEM_VALUE_MAX INT_MAX + #endif #endif @@ -162,11 +162,11 @@ #define CONNECTION_BUFFER_SIZE 1024 typedef struct { - PyObject_HEAD - HANDLE handle; - int flags; - PyObject *weakreflist; - char buffer[CONNECTION_BUFFER_SIZE]; + PyObject_HEAD + HANDLE handle; + int flags; + PyObject *weakreflist; + char buffer[CONNECTION_BUFFER_SIZE]; } ConnectionObject; /* Modified: python/branches/py3k/Modules/_multiprocessing/pipe_connection.c ============================================================================== --- python/branches/py3k/Modules/_multiprocessing/pipe_connection.c (original) +++ python/branches/py3k/Modules/_multiprocessing/pipe_connection.c Sun May 9 17:52:27 2010 @@ -17,19 +17,19 @@ static Py_ssize_t conn_send_string(ConnectionObject *conn, char *string, size_t length) { - DWORD amount_written; - BOOL ret; + DWORD amount_written; + BOOL ret; - Py_BEGIN_ALLOW_THREADS - ret = WriteFile(conn->handle, string, length, &amount_written, NULL); - Py_END_ALLOW_THREADS - - if (ret == 0 && GetLastError() == ERROR_NO_SYSTEM_RESOURCES) { - PyErr_Format(PyExc_ValueError, "Cannnot send %" PY_FORMAT_SIZE_T "d bytes over connection", length); - return MP_STANDARD_ERROR; - } + Py_BEGIN_ALLOW_THREADS + ret = WriteFile(conn->handle, string, length, &amount_written, NULL); + Py_END_ALLOW_THREADS + + if (ret == 0 && GetLastError() == ERROR_NO_SYSTEM_RESOURCES) { + PyErr_Format(PyExc_ValueError, "Cannnot send %" PY_FORMAT_SIZE_T "d bytes over connection", length); + return MP_STANDARD_ERROR; + } - return ret ? MP_SUCCESS : MP_STANDARD_ERROR; + return ret ? MP_SUCCESS : MP_STANDARD_ERROR; } /* @@ -39,50 +39,50 @@ */ static Py_ssize_t -conn_recv_string(ConnectionObject *conn, char *buffer, - size_t buflength, char **newbuffer, size_t maxlength) +conn_recv_string(ConnectionObject *conn, char *buffer, + size_t buflength, char **newbuffer, size_t maxlength) { - DWORD left, length, full_length, err; - BOOL ret; - *newbuffer = NULL; - - Py_BEGIN_ALLOW_THREADS - ret = ReadFile(conn->handle, buffer, MIN(buflength, maxlength), - &length, NULL); - Py_END_ALLOW_THREADS - if (ret) - return length; - - err = GetLastError(); - if (err != ERROR_MORE_DATA) { - if (err == ERROR_BROKEN_PIPE) - return MP_END_OF_FILE; - return MP_STANDARD_ERROR; - } - - if (!PeekNamedPipe(conn->handle, NULL, 0, NULL, NULL, &left)) - return MP_STANDARD_ERROR; - - full_length = length + left; - if (full_length > maxlength) - return MP_BAD_MESSAGE_LENGTH; - - *newbuffer = PyMem_Malloc(full_length); - if (*newbuffer == NULL) - return MP_MEMORY_ERROR; - - memcpy(*newbuffer, buffer, length); - - Py_BEGIN_ALLOW_THREADS - ret = ReadFile(conn->handle, *newbuffer+length, left, &length, NULL); - Py_END_ALLOW_THREADS - if (ret) { - assert(length == left); - return full_length; - } else { - PyMem_Free(*newbuffer); - return MP_STANDARD_ERROR; - } + DWORD left, length, full_length, err; + BOOL ret; + *newbuffer = NULL; + + Py_BEGIN_ALLOW_THREADS + ret = ReadFile(conn->handle, buffer, MIN(buflength, maxlength), + &length, NULL); + Py_END_ALLOW_THREADS + if (ret) + return length; + + err = GetLastError(); + if (err != ERROR_MORE_DATA) { + if (err == ERROR_BROKEN_PIPE) + return MP_END_OF_FILE; + return MP_STANDARD_ERROR; + } + + if (!PeekNamedPipe(conn->handle, NULL, 0, NULL, NULL, &left)) + return MP_STANDARD_ERROR; + + full_length = length + left; + if (full_length > maxlength) + return MP_BAD_MESSAGE_LENGTH; + + *newbuffer = PyMem_Malloc(full_length); + if (*newbuffer == NULL) + return MP_MEMORY_ERROR; + + memcpy(*newbuffer, buffer, length); + + Py_BEGIN_ALLOW_THREADS + ret = ReadFile(conn->handle, *newbuffer+length, left, &length, NULL); + Py_END_ALLOW_THREADS + if (ret) { + assert(length == left); + return full_length; + } else { + PyMem_Free(*newbuffer); + return MP_STANDARD_ERROR; + } } /* @@ -92,51 +92,51 @@ static int conn_poll(ConnectionObject *conn, double timeout, PyThreadState *_save) { - DWORD bytes, deadline, delay; - int difference, res; - BOOL block = FALSE; - - if (!PeekNamedPipe(conn->handle, NULL, 0, NULL, &bytes, NULL)) - return MP_STANDARD_ERROR; - - if (timeout == 0.0) - return bytes > 0; - - if (timeout < 0.0) - block = TRUE; - else - /* XXX does not check for overflow */ - deadline = GetTickCount() + (DWORD)(1000 * timeout + 0.5); - - Sleep(0); - - for (delay = 1 ; ; delay += 1) { - if (!PeekNamedPipe(conn->handle, NULL, 0, NULL, &bytes, NULL)) - return MP_STANDARD_ERROR; - else if (bytes > 0) - return TRUE; - - if (!block) { - difference = deadline - GetTickCount(); - if (difference < 0) - return FALSE; - if ((int)delay > difference) - delay = difference; - } - - if (delay > 20) - delay = 20; - - Sleep(delay); - - /* check for signals */ - Py_BLOCK_THREADS - res = PyErr_CheckSignals(); - Py_UNBLOCK_THREADS - - if (res) - return MP_EXCEPTION_HAS_BEEN_SET; - } + DWORD bytes, deadline, delay; + int difference, res; + BOOL block = FALSE; + + if (!PeekNamedPipe(conn->handle, NULL, 0, NULL, &bytes, NULL)) + return MP_STANDARD_ERROR; + + if (timeout == 0.0) + return bytes > 0; + + if (timeout < 0.0) + block = TRUE; + else + /* XXX does not check for overflow */ + deadline = GetTickCount() + (DWORD)(1000 * timeout + 0.5); + + Sleep(0); + + for (delay = 1 ; ; delay += 1) { + if (!PeekNamedPipe(conn->handle, NULL, 0, NULL, &bytes, NULL)) + return MP_STANDARD_ERROR; + else if (bytes > 0) + return TRUE; + + if (!block) { + difference = deadline - GetTickCount(); + if (difference < 0) + return FALSE; + if ((int)delay > difference) + delay = difference; + } + + if (delay > 20) + delay = 20; + + Sleep(delay); + + /* check for signals */ + Py_BLOCK_THREADS + res = PyErr_CheckSignals(); + Py_UNBLOCK_THREADS + + if (res) + return MP_EXCEPTION_HAS_BEEN_SET; + } } /* Modified: python/branches/py3k/Modules/_multiprocessing/semaphore.c ============================================================================== --- python/branches/py3k/Modules/_multiprocessing/semaphore.c (original) +++ python/branches/py3k/Modules/_multiprocessing/semaphore.c Sun May 9 17:52:27 2010 @@ -11,12 +11,12 @@ enum { RECURSIVE_MUTEX, SEMAPHORE }; typedef struct { - PyObject_HEAD - SEM_HANDLE handle; - long last_tid; - int count; - int maxvalue; - int kind; + PyObject_HEAD + SEM_HANDLE handle; + long last_tid; + int count; + int maxvalue; + int kind; } SemLockObject; #define ISMINE(o) (o->count > 0 && PyThread_get_thread_ident() == o->last_tid) @@ -40,148 +40,148 @@ static int _GetSemaphoreValue(HANDLE handle, long *value) { - long previous; + long previous; - switch (WaitForSingleObject(handle, 0)) { - case WAIT_OBJECT_0: - if (!ReleaseSemaphore(handle, 1, &previous)) - return MP_STANDARD_ERROR; - *value = previous + 1; - return 0; - case WAIT_TIMEOUT: - *value = 0; - return 0; - default: - return MP_STANDARD_ERROR; - } + switch (WaitForSingleObject(handle, 0)) { + case WAIT_OBJECT_0: + if (!ReleaseSemaphore(handle, 1, &previous)) + return MP_STANDARD_ERROR; + *value = previous + 1; + return 0; + case WAIT_TIMEOUT: + *value = 0; + return 0; + default: + return MP_STANDARD_ERROR; + } } static PyObject * semlock_acquire(SemLockObject *self, PyObject *args, PyObject *kwds) { - int blocking = 1; - double timeout; - PyObject *timeout_obj = Py_None; - DWORD res, full_msecs, msecs, start, ticks; - - static char *kwlist[] = {"block", "timeout", NULL}; - - if (!PyArg_ParseTupleAndKeywords(args, kwds, "|iO", kwlist, - &blocking, &timeout_obj)) - return NULL; - - /* calculate timeout */ - if (!blocking) { - full_msecs = 0; - } else if (timeout_obj == Py_None) { - full_msecs = INFINITE; - } else { - timeout = PyFloat_AsDouble(timeout_obj); - if (PyErr_Occurred()) - return NULL; - timeout *= 1000.0; /* convert to millisecs */ - if (timeout < 0.0) { - timeout = 0.0; - } else if (timeout >= 0.5 * INFINITE) { /* 25 days */ - PyErr_SetString(PyExc_OverflowError, - "timeout is too large"); - return NULL; - } - full_msecs = (DWORD)(timeout + 0.5); - } - - /* check whether we already own the lock */ - if (self->kind == RECURSIVE_MUTEX && ISMINE(self)) { - ++self->count; - Py_RETURN_TRUE; - } - - /* check whether we can acquire without blocking */ - if (WaitForSingleObject(self->handle, 0) == WAIT_OBJECT_0) { - self->last_tid = GetCurrentThreadId(); - ++self->count; - Py_RETURN_TRUE; - } - - msecs = full_msecs; - start = GetTickCount(); - - for ( ; ; ) { - HANDLE handles[2] = {self->handle, sigint_event}; - - /* do the wait */ - Py_BEGIN_ALLOW_THREADS - ResetEvent(sigint_event); - res = WaitForMultipleObjects(2, handles, FALSE, msecs); - Py_END_ALLOW_THREADS - - /* handle result */ - if (res != WAIT_OBJECT_0 + 1) - break; - - /* got SIGINT so give signal handler a chance to run */ - Sleep(1); - - /* if this is main thread let KeyboardInterrupt be raised */ - if (PyErr_CheckSignals()) - return NULL; - - /* recalculate timeout */ - if (msecs != INFINITE) { - ticks = GetTickCount(); - if ((DWORD)(ticks - start) >= full_msecs) - Py_RETURN_FALSE; - msecs = full_msecs - (ticks - start); - } - } - - /* handle result */ - switch (res) { - case WAIT_TIMEOUT: - Py_RETURN_FALSE; - case WAIT_OBJECT_0: - self->last_tid = GetCurrentThreadId(); - ++self->count; - Py_RETURN_TRUE; - case WAIT_FAILED: - return PyErr_SetFromWindowsErr(0); - default: - PyErr_Format(PyExc_RuntimeError, "WaitForSingleObject() or " - "WaitForMultipleObjects() gave unrecognized " - "value %d", res); - return NULL; - } + int blocking = 1; + double timeout; + PyObject *timeout_obj = Py_None; + DWORD res, full_msecs, msecs, start, ticks; + + static char *kwlist[] = {"block", "timeout", NULL}; + + if (!PyArg_ParseTupleAndKeywords(args, kwds, "|iO", kwlist, + &blocking, &timeout_obj)) + return NULL; + + /* calculate timeout */ + if (!blocking) { + full_msecs = 0; + } else if (timeout_obj == Py_None) { + full_msecs = INFINITE; + } else { + timeout = PyFloat_AsDouble(timeout_obj); + if (PyErr_Occurred()) + return NULL; + timeout *= 1000.0; /* convert to millisecs */ + if (timeout < 0.0) { + timeout = 0.0; + } else if (timeout >= 0.5 * INFINITE) { /* 25 days */ + PyErr_SetString(PyExc_OverflowError, + "timeout is too large"); + return NULL; + } + full_msecs = (DWORD)(timeout + 0.5); + } + + /* check whether we already own the lock */ + if (self->kind == RECURSIVE_MUTEX && ISMINE(self)) { + ++self->count; + Py_RETURN_TRUE; + } + + /* check whether we can acquire without blocking */ + if (WaitForSingleObject(self->handle, 0) == WAIT_OBJECT_0) { + self->last_tid = GetCurrentThreadId(); + ++self->count; + Py_RETURN_TRUE; + } + + msecs = full_msecs; + start = GetTickCount(); + + for ( ; ; ) { + HANDLE handles[2] = {self->handle, sigint_event}; + + /* do the wait */ + Py_BEGIN_ALLOW_THREADS + ResetEvent(sigint_event); + res = WaitForMultipleObjects(2, handles, FALSE, msecs); + Py_END_ALLOW_THREADS + + /* handle result */ + if (res != WAIT_OBJECT_0 + 1) + break; + + /* got SIGINT so give signal handler a chance to run */ + Sleep(1); + + /* if this is main thread let KeyboardInterrupt be raised */ + if (PyErr_CheckSignals()) + return NULL; + + /* recalculate timeout */ + if (msecs != INFINITE) { + ticks = GetTickCount(); + if ((DWORD)(ticks - start) >= full_msecs) + Py_RETURN_FALSE; + msecs = full_msecs - (ticks - start); + } + } + + /* handle result */ + switch (res) { + case WAIT_TIMEOUT: + Py_RETURN_FALSE; + case WAIT_OBJECT_0: + self->last_tid = GetCurrentThreadId(); + ++self->count; + Py_RETURN_TRUE; + case WAIT_FAILED: + return PyErr_SetFromWindowsErr(0); + default: + PyErr_Format(PyExc_RuntimeError, "WaitForSingleObject() or " + "WaitForMultipleObjects() gave unrecognized " + "value %d", res); + return NULL; + } } static PyObject * semlock_release(SemLockObject *self, PyObject *args) { - if (self->kind == RECURSIVE_MUTEX) { - if (!ISMINE(self)) { - PyErr_SetString(PyExc_AssertionError, "attempt to " - "release recursive lock not owned " - "by thread"); - return NULL; - } - if (self->count > 1) { - --self->count; - Py_RETURN_NONE; - } - assert(self->count == 1); - } - - if (!ReleaseSemaphore(self->handle, 1, NULL)) { - if (GetLastError() == ERROR_TOO_MANY_POSTS) { - PyErr_SetString(PyExc_ValueError, "semaphore or lock " - "released too many times"); - return NULL; - } else { - return PyErr_SetFromWindowsErr(0); - } - } + if (self->kind == RECURSIVE_MUTEX) { + if (!ISMINE(self)) { + PyErr_SetString(PyExc_AssertionError, "attempt to " + "release recursive lock not owned " + "by thread"); + return NULL; + } + if (self->count > 1) { + --self->count; + Py_RETURN_NONE; + } + assert(self->count == 1); + } + + if (!ReleaseSemaphore(self->handle, 1, NULL)) { + if (GetLastError() == ERROR_TOO_MANY_POSTS) { + PyErr_SetString(PyExc_ValueError, "semaphore or lock " + "released too many times"); + return NULL; + } else { + return PyErr_SetFromWindowsErr(0); + } + } - --self->count; - Py_RETURN_NONE; + --self->count; + Py_RETURN_NONE; } #else /* !MS_WINDOWS */ @@ -207,59 +207,59 @@ int sem_timedwait_save(sem_t *sem, struct timespec *deadline, PyThreadState *_save) { - int res; - unsigned long delay, difference; - struct timeval now, tvdeadline, tvdelay; - - errno = 0; - tvdeadline.tv_sec = deadline->tv_sec; - tvdeadline.tv_usec = deadline->tv_nsec / 1000; - - for (delay = 0 ; ; delay += 1000) { - /* poll */ - if (sem_trywait(sem) == 0) - return 0; - else if (errno != EAGAIN) - return MP_STANDARD_ERROR; - - /* get current time */ - if (gettimeofday(&now, NULL) < 0) - return MP_STANDARD_ERROR; - - /* check for timeout */ - if (tvdeadline.tv_sec < now.tv_sec || - (tvdeadline.tv_sec == now.tv_sec && - tvdeadline.tv_usec <= now.tv_usec)) { - errno = ETIMEDOUT; - return MP_STANDARD_ERROR; - } - - /* calculate how much time is left */ - difference = (tvdeadline.tv_sec - now.tv_sec) * 1000000 + - (tvdeadline.tv_usec - now.tv_usec); - - /* check delay not too long -- maximum is 20 msecs */ - if (delay > 20000) - delay = 20000; - if (delay > difference) - delay = difference; - - /* sleep */ - tvdelay.tv_sec = delay / 1000000; - tvdelay.tv_usec = delay % 1000000; - if (select(0, NULL, NULL, NULL, &tvdelay) < 0) - return MP_STANDARD_ERROR; - - /* check for signals */ - Py_BLOCK_THREADS - res = PyErr_CheckSignals(); - Py_UNBLOCK_THREADS - - if (res) { - errno = EINTR; - return MP_EXCEPTION_HAS_BEEN_SET; - } - } + int res; + unsigned long delay, difference; + struct timeval now, tvdeadline, tvdelay; + + errno = 0; + tvdeadline.tv_sec = deadline->tv_sec; + tvdeadline.tv_usec = deadline->tv_nsec / 1000; + + for (delay = 0 ; ; delay += 1000) { + /* poll */ + if (sem_trywait(sem) == 0) + return 0; + else if (errno != EAGAIN) + return MP_STANDARD_ERROR; + + /* get current time */ + if (gettimeofday(&now, NULL) < 0) + return MP_STANDARD_ERROR; + + /* check for timeout */ + if (tvdeadline.tv_sec < now.tv_sec || + (tvdeadline.tv_sec == now.tv_sec && + tvdeadline.tv_usec <= now.tv_usec)) { + errno = ETIMEDOUT; + return MP_STANDARD_ERROR; + } + + /* calculate how much time is left */ + difference = (tvdeadline.tv_sec - now.tv_sec) * 1000000 + + (tvdeadline.tv_usec - now.tv_usec); + + /* check delay not too long -- maximum is 20 msecs */ + if (delay > 20000) + delay = 20000; + if (delay > difference) + delay = difference; + + /* sleep */ + tvdelay.tv_sec = delay / 1000000; + tvdelay.tv_usec = delay % 1000000; + if (select(0, NULL, NULL, NULL, &tvdelay) < 0) + return MP_STANDARD_ERROR; + + /* check for signals */ + Py_BLOCK_THREADS + res = PyErr_CheckSignals(); + Py_UNBLOCK_THREADS + + if (res) { + errno = EINTR; + return MP_EXCEPTION_HAS_BEEN_SET; + } + } } #endif /* !HAVE_SEM_TIMEDWAIT */ @@ -267,129 +267,129 @@ static PyObject * semlock_acquire(SemLockObject *self, PyObject *args, PyObject *kwds) { - int blocking = 1, res; - double timeout; - PyObject *timeout_obj = Py_None; - struct timespec deadline = {0}; - struct timeval now; - long sec, nsec; - - static char *kwlist[] = {"block", "timeout", NULL}; - - if (!PyArg_ParseTupleAndKeywords(args, kwds, "|iO", kwlist, - &blocking, &timeout_obj)) - return NULL; - - if (self->kind == RECURSIVE_MUTEX && ISMINE(self)) { - ++self->count; - Py_RETURN_TRUE; - } - - if (timeout_obj != Py_None) { - timeout = PyFloat_AsDouble(timeout_obj); - if (PyErr_Occurred()) - return NULL; - if (timeout < 0.0) - timeout = 0.0; - - if (gettimeofday(&now, NULL) < 0) { - PyErr_SetFromErrno(PyExc_OSError); - return NULL; - } - sec = (long) timeout; - nsec = (long) (1e9 * (timeout - sec) + 0.5); - deadline.tv_sec = now.tv_sec + sec; - deadline.tv_nsec = now.tv_usec * 1000 + nsec; - deadline.tv_sec += (deadline.tv_nsec / 1000000000); - deadline.tv_nsec %= 1000000000; - } - - do { - Py_BEGIN_ALLOW_THREADS - if (blocking && timeout_obj == Py_None) - res = sem_wait(self->handle); - else if (!blocking) - res = sem_trywait(self->handle); - else - res = sem_timedwait(self->handle, &deadline); - Py_END_ALLOW_THREADS - if (res == MP_EXCEPTION_HAS_BEEN_SET) - break; - } while (res < 0 && errno == EINTR && !PyErr_CheckSignals()); - - if (res < 0) { - if (errno == EAGAIN || errno == ETIMEDOUT) - Py_RETURN_FALSE; - else if (errno == EINTR) - return NULL; - else - return PyErr_SetFromErrno(PyExc_OSError); - } + int blocking = 1, res; + double timeout; + PyObject *timeout_obj = Py_None; + struct timespec deadline = {0}; + struct timeval now; + long sec, nsec; + + static char *kwlist[] = {"block", "timeout", NULL}; + + if (!PyArg_ParseTupleAndKeywords(args, kwds, "|iO", kwlist, + &blocking, &timeout_obj)) + return NULL; + + if (self->kind == RECURSIVE_MUTEX && ISMINE(self)) { + ++self->count; + Py_RETURN_TRUE; + } + + if (timeout_obj != Py_None) { + timeout = PyFloat_AsDouble(timeout_obj); + if (PyErr_Occurred()) + return NULL; + if (timeout < 0.0) + timeout = 0.0; + + if (gettimeofday(&now, NULL) < 0) { + PyErr_SetFromErrno(PyExc_OSError); + return NULL; + } + sec = (long) timeout; + nsec = (long) (1e9 * (timeout - sec) + 0.5); + deadline.tv_sec = now.tv_sec + sec; + deadline.tv_nsec = now.tv_usec * 1000 + nsec; + deadline.tv_sec += (deadline.tv_nsec / 1000000000); + deadline.tv_nsec %= 1000000000; + } + + do { + Py_BEGIN_ALLOW_THREADS + if (blocking && timeout_obj == Py_None) + res = sem_wait(self->handle); + else if (!blocking) + res = sem_trywait(self->handle); + else + res = sem_timedwait(self->handle, &deadline); + Py_END_ALLOW_THREADS + if (res == MP_EXCEPTION_HAS_BEEN_SET) + break; + } while (res < 0 && errno == EINTR && !PyErr_CheckSignals()); + + if (res < 0) { + if (errno == EAGAIN || errno == ETIMEDOUT) + Py_RETURN_FALSE; + else if (errno == EINTR) + return NULL; + else + return PyErr_SetFromErrno(PyExc_OSError); + } - ++self->count; - self->last_tid = PyThread_get_thread_ident(); + ++self->count; + self->last_tid = PyThread_get_thread_ident(); - Py_RETURN_TRUE; + Py_RETURN_TRUE; } static PyObject * semlock_release(SemLockObject *self, PyObject *args) { - if (self->kind == RECURSIVE_MUTEX) { - if (!ISMINE(self)) { - PyErr_SetString(PyExc_AssertionError, "attempt to " - "release recursive lock not owned " - "by thread"); - return NULL; - } - if (self->count > 1) { - --self->count; - Py_RETURN_NONE; - } - assert(self->count == 1); - } else { + if (self->kind == RECURSIVE_MUTEX) { + if (!ISMINE(self)) { + PyErr_SetString(PyExc_AssertionError, "attempt to " + "release recursive lock not owned " + "by thread"); + return NULL; + } + if (self->count > 1) { + --self->count; + Py_RETURN_NONE; + } + assert(self->count == 1); + } else { #ifdef HAVE_BROKEN_SEM_GETVALUE - /* We will only check properly the maxvalue == 1 case */ - if (self->maxvalue == 1) { - /* make sure that already locked */ - if (sem_trywait(self->handle) < 0) { - if (errno != EAGAIN) { - PyErr_SetFromErrno(PyExc_OSError); - return NULL; - } - /* it is already locked as expected */ - } else { - /* it was not locked so undo wait and raise */ - if (sem_post(self->handle) < 0) { - PyErr_SetFromErrno(PyExc_OSError); - return NULL; - } - PyErr_SetString(PyExc_ValueError, "semaphore " - "or lock released too many " - "times"); - return NULL; - } - } + /* We will only check properly the maxvalue == 1 case */ + if (self->maxvalue == 1) { + /* make sure that already locked */ + if (sem_trywait(self->handle) < 0) { + if (errno != EAGAIN) { + PyErr_SetFromErrno(PyExc_OSError); + return NULL; + } + /* it is already locked as expected */ + } else { + /* it was not locked so undo wait and raise */ + if (sem_post(self->handle) < 0) { + PyErr_SetFromErrno(PyExc_OSError); + return NULL; + } + PyErr_SetString(PyExc_ValueError, "semaphore " + "or lock released too many " + "times"); + return NULL; + } + } #else - int sval; + int sval; - /* This check is not an absolute guarantee that the semaphore - does not rise above maxvalue. */ - if (sem_getvalue(self->handle, &sval) < 0) { - return PyErr_SetFromErrno(PyExc_OSError); - } else if (sval >= self->maxvalue) { - PyErr_SetString(PyExc_ValueError, "semaphore or lock " - "released too many times"); - return NULL; - } + /* This check is not an absolute guarantee that the semaphore + does not rise above maxvalue. */ + if (sem_getvalue(self->handle, &sval) < 0) { + return PyErr_SetFromErrno(PyExc_OSError); + } else if (sval >= self->maxvalue) { + PyErr_SetString(PyExc_ValueError, "semaphore or lock " + "released too many times"); + return NULL; + } #endif - } + } - if (sem_post(self->handle) < 0) - return PyErr_SetFromErrno(PyExc_OSError); + if (sem_post(self->handle) < 0) + return PyErr_SetFromErrno(PyExc_OSError); - --self->count; - Py_RETURN_NONE; + --self->count; + Py_RETURN_NONE; } #endif /* !MS_WINDOWS */ @@ -401,111 +401,111 @@ static PyObject * newsemlockobject(PyTypeObject *type, SEM_HANDLE handle, int kind, int maxvalue) { - SemLockObject *self; + SemLockObject *self; - self = PyObject_New(SemLockObject, type); - if (!self) - return NULL; - self->handle = handle; - self->kind = kind; - self->count = 0; - self->last_tid = 0; - self->maxvalue = maxvalue; - return (PyObject*)self; + self = PyObject_New(SemLockObject, type); + if (!self) + return NULL; + self->handle = handle; + self->kind = kind; + self->count = 0; + self->last_tid = 0; + self->maxvalue = maxvalue; + return (PyObject*)self; } static PyObject * semlock_new(PyTypeObject *type, PyObject *args, PyObject *kwds) { - char buffer[256]; - SEM_HANDLE handle = SEM_FAILED; - int kind, maxvalue, value; - PyObject *result; - static char *kwlist[] = {"kind", "value", "maxvalue", NULL}; - static int counter = 0; - - if (!PyArg_ParseTupleAndKeywords(args, kwds, "iii", kwlist, - &kind, &value, &maxvalue)) - return NULL; - - if (kind != RECURSIVE_MUTEX && kind != SEMAPHORE) { - PyErr_SetString(PyExc_ValueError, "unrecognized kind"); - return NULL; - } - - PyOS_snprintf(buffer, sizeof(buffer), "/mp%d-%d", getpid(), counter++); - - SEM_CLEAR_ERROR(); - handle = SEM_CREATE(buffer, value, maxvalue); - /* On Windows we should fail if GetLastError()==ERROR_ALREADY_EXISTS */ - if (handle == SEM_FAILED || SEM_GET_LAST_ERROR() != 0) - goto failure; - - if (SEM_UNLINK(buffer) < 0) - goto failure; - - result = newsemlockobject(type, handle, kind, maxvalue); - if (!result) - goto failure; + char buffer[256]; + SEM_HANDLE handle = SEM_FAILED; + int kind, maxvalue, value; + PyObject *result; + static char *kwlist[] = {"kind", "value", "maxvalue", NULL}; + static int counter = 0; + + if (!PyArg_ParseTupleAndKeywords(args, kwds, "iii", kwlist, + &kind, &value, &maxvalue)) + return NULL; + + if (kind != RECURSIVE_MUTEX && kind != SEMAPHORE) { + PyErr_SetString(PyExc_ValueError, "unrecognized kind"); + return NULL; + } + + PyOS_snprintf(buffer, sizeof(buffer), "/mp%d-%d", getpid(), counter++); + + SEM_CLEAR_ERROR(); + handle = SEM_CREATE(buffer, value, maxvalue); + /* On Windows we should fail if GetLastError()==ERROR_ALREADY_EXISTS */ + if (handle == SEM_FAILED || SEM_GET_LAST_ERROR() != 0) + goto failure; + + if (SEM_UNLINK(buffer) < 0) + goto failure; + + result = newsemlockobject(type, handle, kind, maxvalue); + if (!result) + goto failure; - return result; + return result; failure: - if (handle != SEM_FAILED) - SEM_CLOSE(handle); - mp_SetError(NULL, MP_STANDARD_ERROR); - return NULL; + if (handle != SEM_FAILED) + SEM_CLOSE(handle); + mp_SetError(NULL, MP_STANDARD_ERROR); + return NULL; } static PyObject * semlock_rebuild(PyTypeObject *type, PyObject *args) { - SEM_HANDLE handle; - int kind, maxvalue; + SEM_HANDLE handle; + int kind, maxvalue; - if (!PyArg_ParseTuple(args, F_SEM_HANDLE "ii", - &handle, &kind, &maxvalue)) - return NULL; + if (!PyArg_ParseTuple(args, F_SEM_HANDLE "ii", + &handle, &kind, &maxvalue)) + return NULL; - return newsemlockobject(type, handle, kind, maxvalue); + return newsemlockobject(type, handle, kind, maxvalue); } static void semlock_dealloc(SemLockObject* self) { - if (self->handle != SEM_FAILED) - SEM_CLOSE(self->handle); - PyObject_Del(self); + if (self->handle != SEM_FAILED) + SEM_CLOSE(self->handle); + PyObject_Del(self); } static PyObject * semlock_count(SemLockObject *self) { - return PyInt_FromLong((long)self->count); + return PyInt_FromLong((long)self->count); } static PyObject * semlock_ismine(SemLockObject *self) { - /* only makes sense for a lock */ - return PyBool_FromLong(ISMINE(self)); + /* only makes sense for a lock */ + return PyBool_FromLong(ISMINE(self)); } static PyObject * semlock_getvalue(SemLockObject *self) { #ifdef HAVE_BROKEN_SEM_GETVALUE - PyErr_SetNone(PyExc_NotImplementedError); - return NULL; + PyErr_SetNone(PyExc_NotImplementedError); + return NULL; #else - int sval; - if (SEM_GETVALUE(self->handle, &sval) < 0) - return mp_SetError(NULL, MP_STANDARD_ERROR); - /* some posix implementations use negative numbers to indicate - the number of waiting threads */ - if (sval < 0) - sval = 0; - return PyInt_FromLong((long)sval); + int sval; + if (SEM_GETVALUE(self->handle, &sval) < 0) + return mp_SetError(NULL, MP_STANDARD_ERROR); + /* some posix implementations use negative numbers to indicate + the number of waiting threads */ + if (sval < 0) + sval = 0; + return PyInt_FromLong((long)sval); #endif } @@ -513,28 +513,28 @@ semlock_iszero(SemLockObject *self) { #ifdef HAVE_BROKEN_SEM_GETVALUE - if (sem_trywait(self->handle) < 0) { - if (errno == EAGAIN) - Py_RETURN_TRUE; - return mp_SetError(NULL, MP_STANDARD_ERROR); - } else { - if (sem_post(self->handle) < 0) - return mp_SetError(NULL, MP_STANDARD_ERROR); - Py_RETURN_FALSE; - } + if (sem_trywait(self->handle) < 0) { + if (errno == EAGAIN) + Py_RETURN_TRUE; + return mp_SetError(NULL, MP_STANDARD_ERROR); + } else { + if (sem_post(self->handle) < 0) + return mp_SetError(NULL, MP_STANDARD_ERROR); + Py_RETURN_FALSE; + } #else - int sval; - if (SEM_GETVALUE(self->handle, &sval) < 0) - return mp_SetError(NULL, MP_STANDARD_ERROR); - return PyBool_FromLong((long)sval == 0); + int sval; + if (SEM_GETVALUE(self->handle, &sval) < 0) + return mp_SetError(NULL, MP_STANDARD_ERROR); + return PyBool_FromLong((long)sval == 0); #endif } static PyObject * semlock_afterfork(SemLockObject *self) { - self->count = 0; - Py_RETURN_NONE; + self->count = 0; + Py_RETURN_NONE; } /* @@ -542,27 +542,27 @@ */ static PyMethodDef semlock_methods[] = { - {"acquire", (PyCFunction)semlock_acquire, METH_VARARGS | METH_KEYWORDS, - "acquire the semaphore/lock"}, - {"release", (PyCFunction)semlock_release, METH_NOARGS, - "release the semaphore/lock"}, + {"acquire", (PyCFunction)semlock_acquire, METH_VARARGS | METH_KEYWORDS, + "acquire the semaphore/lock"}, + {"release", (PyCFunction)semlock_release, METH_NOARGS, + "release the semaphore/lock"}, {"__enter__", (PyCFunction)semlock_acquire, METH_VARARGS | METH_KEYWORDS, - "enter the semaphore/lock"}, - {"__exit__", (PyCFunction)semlock_release, METH_VARARGS, - "exit the semaphore/lock"}, - {"_count", (PyCFunction)semlock_count, METH_NOARGS, - "num of `acquire()`s minus num of `release()`s for this process"}, - {"_is_mine", (PyCFunction)semlock_ismine, METH_NOARGS, - "whether the lock is owned by this thread"}, - {"_get_value", (PyCFunction)semlock_getvalue, METH_NOARGS, - "get the value of the semaphore"}, - {"_is_zero", (PyCFunction)semlock_iszero, METH_NOARGS, - "returns whether semaphore has value zero"}, - {"_rebuild", (PyCFunction)semlock_rebuild, METH_VARARGS | METH_CLASS, - ""}, - {"_after_fork", (PyCFunction)semlock_afterfork, METH_NOARGS, - "rezero the net acquisition count after fork()"}, - {NULL} + "enter the semaphore/lock"}, + {"__exit__", (PyCFunction)semlock_release, METH_VARARGS, + "exit the semaphore/lock"}, + {"_count", (PyCFunction)semlock_count, METH_NOARGS, + "num of `acquire()`s minus num of `release()`s for this process"}, + {"_is_mine", (PyCFunction)semlock_ismine, METH_NOARGS, + "whether the lock is owned by this thread"}, + {"_get_value", (PyCFunction)semlock_getvalue, METH_NOARGS, + "get the value of the semaphore"}, + {"_is_zero", (PyCFunction)semlock_iszero, METH_NOARGS, + "returns whether semaphore has value zero"}, + {"_rebuild", (PyCFunction)semlock_rebuild, METH_VARARGS | METH_CLASS, + ""}, + {"_after_fork", (PyCFunction)semlock_afterfork, METH_NOARGS, + "rezero the net acquisition count after fork()"}, + {NULL} }; /* @@ -570,13 +570,13 @@ */ static PyMemberDef semlock_members[] = { - {"handle", T_SEM_HANDLE, offsetof(SemLockObject, handle), READONLY, - ""}, - {"kind", T_INT, offsetof(SemLockObject, kind), READONLY, - ""}, - {"maxvalue", T_INT, offsetof(SemLockObject, maxvalue), READONLY, - ""}, - {NULL} + {"handle", T_SEM_HANDLE, offsetof(SemLockObject, handle), READONLY, + ""}, + {"kind", T_INT, offsetof(SemLockObject, kind), READONLY, + ""}, + {"maxvalue", T_INT, offsetof(SemLockObject, maxvalue), READONLY, + ""}, + {NULL} }; /* @@ -584,42 +584,42 @@ */ PyTypeObject SemLockType = { - PyVarObject_HEAD_INIT(NULL, 0) - /* tp_name */ "_multiprocessing.SemLock", - /* tp_basicsize */ sizeof(SemLockObject), - /* tp_itemsize */ 0, - /* tp_dealloc */ (destructor)semlock_dealloc, - /* tp_print */ 0, - /* tp_getattr */ 0, - /* tp_setattr */ 0, - /* tp_reserved */ 0, - /* tp_repr */ 0, - /* tp_as_number */ 0, - /* tp_as_sequence */ 0, - /* tp_as_mapping */ 0, - /* tp_hash */ 0, - /* tp_call */ 0, - /* tp_str */ 0, - /* tp_getattro */ 0, - /* tp_setattro */ 0, - /* tp_as_buffer */ 0, - /* tp_flags */ Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, - /* tp_doc */ "Semaphore/Mutex type", - /* tp_traverse */ 0, - /* tp_clear */ 0, - /* tp_richcompare */ 0, - /* tp_weaklistoffset */ 0, - /* tp_iter */ 0, - /* tp_iternext */ 0, - /* tp_methods */ semlock_methods, - /* tp_members */ semlock_members, - /* tp_getset */ 0, - /* tp_base */ 0, - /* tp_dict */ 0, - /* tp_descr_get */ 0, - /* tp_descr_set */ 0, - /* tp_dictoffset */ 0, - /* tp_init */ 0, - /* tp_alloc */ 0, - /* tp_new */ semlock_new, + PyVarObject_HEAD_INIT(NULL, 0) + /* tp_name */ "_multiprocessing.SemLock", + /* tp_basicsize */ sizeof(SemLockObject), + /* tp_itemsize */ 0, + /* tp_dealloc */ (destructor)semlock_dealloc, + /* tp_print */ 0, + /* tp_getattr */ 0, + /* tp_setattr */ 0, + /* tp_reserved */ 0, + /* tp_repr */ 0, + /* tp_as_number */ 0, + /* tp_as_sequence */ 0, + /* tp_as_mapping */ 0, + /* tp_hash */ 0, + /* tp_call */ 0, + /* tp_str */ 0, + /* tp_getattro */ 0, + /* tp_setattro */ 0, + /* tp_as_buffer */ 0, + /* tp_flags */ Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, + /* tp_doc */ "Semaphore/Mutex type", + /* tp_traverse */ 0, + /* tp_clear */ 0, + /* tp_richcompare */ 0, + /* tp_weaklistoffset */ 0, + /* tp_iter */ 0, + /* tp_iternext */ 0, + /* tp_methods */ semlock_methods, + /* tp_members */ semlock_members, + /* tp_getset */ 0, + /* tp_base */ 0, + /* tp_dict */ 0, + /* tp_descr_get */ 0, + /* tp_descr_set */ 0, + /* tp_dictoffset */ 0, + /* tp_init */ 0, + /* tp_alloc */ 0, + /* tp_new */ semlock_new, }; Modified: python/branches/py3k/Modules/_multiprocessing/socket_connection.c ============================================================================== --- python/branches/py3k/Modules/_multiprocessing/socket_connection.c (original) +++ python/branches/py3k/Modules/_multiprocessing/socket_connection.c Sun May 9 17:52:27 2010 @@ -25,45 +25,45 @@ static Py_ssize_t _conn_sendall(HANDLE h, char *string, size_t length) { - char *p = string; - Py_ssize_t res; + char *p = string; + Py_ssize_t res; - while (length > 0) { - res = WRITE(h, p, length); - if (res < 0) - return MP_SOCKET_ERROR; - length -= res; - p += res; - } + while (length > 0) { + res = WRITE(h, p, length); + if (res < 0) + return MP_SOCKET_ERROR; + length -= res; + p += res; + } - return MP_SUCCESS; + return MP_SUCCESS; } /* - * Receive string of exact length from file descriptor + * Receive string of exact length from file descriptor */ static Py_ssize_t _conn_recvall(HANDLE h, char *buffer, size_t length) { - size_t remaining = length; - Py_ssize_t temp; - char *p = buffer; - - while (remaining > 0) { - temp = READ(h, p, remaining); - if (temp <= 0) { - if (temp == 0) - return remaining == length ? - MP_END_OF_FILE : MP_EARLY_END_OF_FILE; - else - return temp; - } - remaining -= temp; - p += temp; - } + size_t remaining = length; + Py_ssize_t temp; + char *p = buffer; + + while (remaining > 0) { + temp = READ(h, p, remaining); + if (temp <= 0) { + if (temp == 0) + return remaining == length ? + MP_END_OF_FILE : MP_EARLY_END_OF_FILE; + else + return temp; + } + remaining -= temp; + p += temp; + } - return MP_SUCCESS; + return MP_SUCCESS; } /* @@ -73,38 +73,38 @@ static Py_ssize_t conn_send_string(ConnectionObject *conn, char *string, size_t length) { - Py_ssize_t res; - /* The "header" of the message is a 32 bit unsigned number (in - network order) which specifies the length of the "body". If - the message is shorter than about 16kb then it is quicker to - combine the "header" and the "body" of the message and send - them at once. */ - if (length < (16*1024)) { - char *message; - - message = PyMem_Malloc(length+4); - if (message == NULL) - return MP_MEMORY_ERROR; - - *(UINT32*)message = htonl((UINT32)length); - memcpy(message+4, string, length); - Py_BEGIN_ALLOW_THREADS - res = _conn_sendall(conn->handle, message, length+4); - Py_END_ALLOW_THREADS - PyMem_Free(message); - } else { - UINT32 lenbuff; - - if (length > MAX_MESSAGE_LENGTH) - return MP_BAD_MESSAGE_LENGTH; - - lenbuff = htonl((UINT32)length); - Py_BEGIN_ALLOW_THREADS - res = _conn_sendall(conn->handle, (char*)&lenbuff, 4) || - _conn_sendall(conn->handle, string, length); - Py_END_ALLOW_THREADS - } - return res; + Py_ssize_t res; + /* The "header" of the message is a 32 bit unsigned number (in + network order) which specifies the length of the "body". If + the message is shorter than about 16kb then it is quicker to + combine the "header" and the "body" of the message and send + them at once. */ + if (length < (16*1024)) { + char *message; + + message = PyMem_Malloc(length+4); + if (message == NULL) + return MP_MEMORY_ERROR; + + *(UINT32*)message = htonl((UINT32)length); + memcpy(message+4, string, length); + Py_BEGIN_ALLOW_THREADS + res = _conn_sendall(conn->handle, message, length+4); + Py_END_ALLOW_THREADS + PyMem_Free(message); + } else { + UINT32 lenbuff; + + if (length > MAX_MESSAGE_LENGTH) + return MP_BAD_MESSAGE_LENGTH; + + lenbuff = htonl((UINT32)length); + Py_BEGIN_ALLOW_THREADS + res = _conn_sendall(conn->handle, (char*)&lenbuff, 4) || + _conn_sendall(conn->handle, string, length); + Py_END_ALLOW_THREADS + } + return res; } /* @@ -114,38 +114,38 @@ */ static Py_ssize_t -conn_recv_string(ConnectionObject *conn, char *buffer, - size_t buflength, char **newbuffer, size_t maxlength) +conn_recv_string(ConnectionObject *conn, char *buffer, + size_t buflength, char **newbuffer, size_t maxlength) { - int res; - UINT32 ulength; + int res; + UINT32 ulength; - *newbuffer = NULL; + *newbuffer = NULL; - Py_BEGIN_ALLOW_THREADS - res = _conn_recvall(conn->handle, (char*)&ulength, 4); - Py_END_ALLOW_THREADS - if (res < 0) - return res; - - ulength = ntohl(ulength); - if (ulength > maxlength) - return MP_BAD_MESSAGE_LENGTH; - - if (ulength <= buflength) { - Py_BEGIN_ALLOW_THREADS - res = _conn_recvall(conn->handle, buffer, (size_t)ulength); - Py_END_ALLOW_THREADS - return res < 0 ? res : ulength; - } else { - *newbuffer = PyMem_Malloc((size_t)ulength); - if (*newbuffer == NULL) - return MP_MEMORY_ERROR; - Py_BEGIN_ALLOW_THREADS - res = _conn_recvall(conn->handle, *newbuffer, (size_t)ulength); - Py_END_ALLOW_THREADS - return res < 0 ? (Py_ssize_t)res : (Py_ssize_t)ulength; - } + Py_BEGIN_ALLOW_THREADS + res = _conn_recvall(conn->handle, (char*)&ulength, 4); + Py_END_ALLOW_THREADS + if (res < 0) + return res; + + ulength = ntohl(ulength); + if (ulength > maxlength) + return MP_BAD_MESSAGE_LENGTH; + + if (ulength <= buflength) { + Py_BEGIN_ALLOW_THREADS + res = _conn_recvall(conn->handle, buffer, (size_t)ulength); + Py_END_ALLOW_THREADS + return res < 0 ? res : ulength; + } else { + *newbuffer = PyMem_Malloc((size_t)ulength); + if (*newbuffer == NULL) + return MP_MEMORY_ERROR; + Py_BEGIN_ALLOW_THREADS + res = _conn_recvall(conn->handle, *newbuffer, (size_t)ulength); + Py_END_ALLOW_THREADS + return res < 0 ? (Py_ssize_t)res : (Py_ssize_t)ulength; + } } /* @@ -155,41 +155,41 @@ static int conn_poll(ConnectionObject *conn, double timeout, PyThreadState *_save) { - int res; - fd_set rfds; + int res; + fd_set rfds; - /* - * Verify the handle, issue 3321. Not required for windows. - */ - #ifndef MS_WINDOWS - if (((int)conn->handle) < 0 || ((int)conn->handle) >= FD_SETSIZE) { - Py_BLOCK_THREADS - PyErr_SetString(PyExc_IOError, "handle out of range in select()"); - Py_UNBLOCK_THREADS - return MP_EXCEPTION_HAS_BEEN_SET; - } - #endif - - FD_ZERO(&rfds); - FD_SET((SOCKET)conn->handle, &rfds); - - if (timeout < 0.0) { - res = select((int)conn->handle+1, &rfds, NULL, NULL, NULL); - } else { - struct timeval tv; - tv.tv_sec = (long)timeout; - tv.tv_usec = (long)((timeout - tv.tv_sec) * 1e6 + 0.5); - res = select((int)conn->handle+1, &rfds, NULL, NULL, &tv); - } - - if (res < 0) { - return MP_SOCKET_ERROR; - } else if (FD_ISSET(conn->handle, &rfds)) { - return TRUE; - } else { - assert(res == 0); - return FALSE; - } + /* + * Verify the handle, issue 3321. Not required for windows. + */ + #ifndef MS_WINDOWS + if (((int)conn->handle) < 0 || ((int)conn->handle) >= FD_SETSIZE) { + Py_BLOCK_THREADS + PyErr_SetString(PyExc_IOError, "handle out of range in select()"); + Py_UNBLOCK_THREADS + return MP_EXCEPTION_HAS_BEEN_SET; + } + #endif + + FD_ZERO(&rfds); + FD_SET((SOCKET)conn->handle, &rfds); + + if (timeout < 0.0) { + res = select((int)conn->handle+1, &rfds, NULL, NULL, NULL); + } else { + struct timeval tv; + tv.tv_sec = (long)timeout; + tv.tv_usec = (long)((timeout - tv.tv_sec) * 1e6 + 0.5); + res = select((int)conn->handle+1, &rfds, NULL, NULL, &tv); + } + + if (res < 0) { + return MP_SOCKET_ERROR; + } else if (FD_ISSET(conn->handle, &rfds)) { + return TRUE; + } else { + assert(res == 0); + return FALSE; + } } /* Modified: python/branches/py3k/Modules/_multiprocessing/win32_functions.c ============================================================================== --- python/branches/py3k/Modules/_multiprocessing/win32_functions.c (original) +++ python/branches/py3k/Modules/_multiprocessing/win32_functions.c Sun May 9 17:52:27 2010 @@ -19,248 +19,248 @@ static PyObject * win32_CloseHandle(PyObject *self, PyObject *args) { - HANDLE hObject; - BOOL success; + HANDLE hObject; + BOOL success; - if (!PyArg_ParseTuple(args, F_HANDLE, &hObject)) - return NULL; + if (!PyArg_ParseTuple(args, F_HANDLE, &hObject)) + return NULL; - Py_BEGIN_ALLOW_THREADS - success = CloseHandle(hObject); - Py_END_ALLOW_THREADS + Py_BEGIN_ALLOW_THREADS + success = CloseHandle(hObject); + Py_END_ALLOW_THREADS - if (!success) - return PyErr_SetFromWindowsErr(0); + if (!success) + return PyErr_SetFromWindowsErr(0); - Py_RETURN_NONE; + Py_RETURN_NONE; } static PyObject * win32_ConnectNamedPipe(PyObject *self, PyObject *args) { - HANDLE hNamedPipe; - LPOVERLAPPED lpOverlapped; - BOOL success; - - if (!PyArg_ParseTuple(args, F_HANDLE F_POINTER, - &hNamedPipe, &lpOverlapped)) - return NULL; - - Py_BEGIN_ALLOW_THREADS - success = ConnectNamedPipe(hNamedPipe, lpOverlapped); - Py_END_ALLOW_THREADS + HANDLE hNamedPipe; + LPOVERLAPPED lpOverlapped; + BOOL success; + + if (!PyArg_ParseTuple(args, F_HANDLE F_POINTER, + &hNamedPipe, &lpOverlapped)) + return NULL; + + Py_BEGIN_ALLOW_THREADS + success = ConnectNamedPipe(hNamedPipe, lpOverlapped); + Py_END_ALLOW_THREADS - if (!success) - return PyErr_SetFromWindowsErr(0); + if (!success) + return PyErr_SetFromWindowsErr(0); - Py_RETURN_NONE; + Py_RETURN_NONE; } static PyObject * win32_CreateFile(PyObject *self, PyObject *args) { - LPCTSTR lpFileName; - DWORD dwDesiredAccess; - DWORD dwShareMode; - LPSECURITY_ATTRIBUTES lpSecurityAttributes; - DWORD dwCreationDisposition; - DWORD dwFlagsAndAttributes; - HANDLE hTemplateFile; - HANDLE handle; - - if (!PyArg_ParseTuple(args, "s" F_DWORD F_DWORD F_POINTER - F_DWORD F_DWORD F_HANDLE, - &lpFileName, &dwDesiredAccess, &dwShareMode, - &lpSecurityAttributes, &dwCreationDisposition, - &dwFlagsAndAttributes, &hTemplateFile)) - return NULL; - - Py_BEGIN_ALLOW_THREADS - handle = CreateFile(lpFileName, dwDesiredAccess, - dwShareMode, lpSecurityAttributes, - dwCreationDisposition, - dwFlagsAndAttributes, hTemplateFile); - Py_END_ALLOW_THREADS + LPCTSTR lpFileName; + DWORD dwDesiredAccess; + DWORD dwShareMode; + LPSECURITY_ATTRIBUTES lpSecurityAttributes; + DWORD dwCreationDisposition; + DWORD dwFlagsAndAttributes; + HANDLE hTemplateFile; + HANDLE handle; + + if (!PyArg_ParseTuple(args, "s" F_DWORD F_DWORD F_POINTER + F_DWORD F_DWORD F_HANDLE, + &lpFileName, &dwDesiredAccess, &dwShareMode, + &lpSecurityAttributes, &dwCreationDisposition, + &dwFlagsAndAttributes, &hTemplateFile)) + return NULL; + + Py_BEGIN_ALLOW_THREADS + handle = CreateFile(lpFileName, dwDesiredAccess, + dwShareMode, lpSecurityAttributes, + dwCreationDisposition, + dwFlagsAndAttributes, hTemplateFile); + Py_END_ALLOW_THREADS - if (handle == INVALID_HANDLE_VALUE) - return PyErr_SetFromWindowsErr(0); + if (handle == INVALID_HANDLE_VALUE) + return PyErr_SetFromWindowsErr(0); - return Py_BuildValue(F_HANDLE, handle); + return Py_BuildValue(F_HANDLE, handle); } static PyObject * win32_CreateNamedPipe(PyObject *self, PyObject *args) { - LPCTSTR lpName; - DWORD dwOpenMode; - DWORD dwPipeMode; - DWORD nMaxInstances; - DWORD nOutBufferSize; - DWORD nInBufferSize; - DWORD nDefaultTimeOut; - LPSECURITY_ATTRIBUTES lpSecurityAttributes; - HANDLE handle; - - if (!PyArg_ParseTuple(args, "s" F_DWORD F_DWORD F_DWORD - F_DWORD F_DWORD F_DWORD F_POINTER, - &lpName, &dwOpenMode, &dwPipeMode, - &nMaxInstances, &nOutBufferSize, - &nInBufferSize, &nDefaultTimeOut, - &lpSecurityAttributes)) - return NULL; - - Py_BEGIN_ALLOW_THREADS - handle = CreateNamedPipe(lpName, dwOpenMode, dwPipeMode, - nMaxInstances, nOutBufferSize, - nInBufferSize, nDefaultTimeOut, - lpSecurityAttributes); - Py_END_ALLOW_THREADS + LPCTSTR lpName; + DWORD dwOpenMode; + DWORD dwPipeMode; + DWORD nMaxInstances; + DWORD nOutBufferSize; + DWORD nInBufferSize; + DWORD nDefaultTimeOut; + LPSECURITY_ATTRIBUTES lpSecurityAttributes; + HANDLE handle; + + if (!PyArg_ParseTuple(args, "s" F_DWORD F_DWORD F_DWORD + F_DWORD F_DWORD F_DWORD F_POINTER, + &lpName, &dwOpenMode, &dwPipeMode, + &nMaxInstances, &nOutBufferSize, + &nInBufferSize, &nDefaultTimeOut, + &lpSecurityAttributes)) + return NULL; + + Py_BEGIN_ALLOW_THREADS + handle = CreateNamedPipe(lpName, dwOpenMode, dwPipeMode, + nMaxInstances, nOutBufferSize, + nInBufferSize, nDefaultTimeOut, + lpSecurityAttributes); + Py_END_ALLOW_THREADS - if (handle == INVALID_HANDLE_VALUE) - return PyErr_SetFromWindowsErr(0); + if (handle == INVALID_HANDLE_VALUE) + return PyErr_SetFromWindowsErr(0); - return Py_BuildValue(F_HANDLE, handle); + return Py_BuildValue(F_HANDLE, handle); } static PyObject * win32_ExitProcess(PyObject *self, PyObject *args) { - UINT uExitCode; + UINT uExitCode; - if (!PyArg_ParseTuple(args, "I", &uExitCode)) - return NULL; + if (!PyArg_ParseTuple(args, "I", &uExitCode)) + return NULL; - #if defined(Py_DEBUG) - SetErrorMode(SEM_FAILCRITICALERRORS|SEM_NOALIGNMENTFAULTEXCEPT|SEM_NOGPFAULTERRORBOX|SEM_NOOPENFILEERRORBOX); - _CrtSetReportMode(_CRT_ASSERT, _CRTDBG_MODE_DEBUG); - #endif + #if defined(Py_DEBUG) + SetErrorMode(SEM_FAILCRITICALERRORS|SEM_NOALIGNMENTFAULTEXCEPT|SEM_NOGPFAULTERRORBOX|SEM_NOOPENFILEERRORBOX); + _CrtSetReportMode(_CRT_ASSERT, _CRTDBG_MODE_DEBUG); + #endif - ExitProcess(uExitCode); + ExitProcess(uExitCode); - return NULL; + return NULL; } static PyObject * win32_GetLastError(PyObject *self, PyObject *args) { - return Py_BuildValue(F_DWORD, GetLastError()); + return Py_BuildValue(F_DWORD, GetLastError()); } static PyObject * win32_OpenProcess(PyObject *self, PyObject *args) { - DWORD dwDesiredAccess; - BOOL bInheritHandle; - DWORD dwProcessId; - HANDLE handle; - - if (!PyArg_ParseTuple(args, F_DWORD "i" F_DWORD, - &dwDesiredAccess, &bInheritHandle, &dwProcessId)) - return NULL; - - handle = OpenProcess(dwDesiredAccess, bInheritHandle, dwProcessId); - if (handle == NULL) - return PyErr_SetFromWindowsErr(0); + DWORD dwDesiredAccess; + BOOL bInheritHandle; + DWORD dwProcessId; + HANDLE handle; + + if (!PyArg_ParseTuple(args, F_DWORD "i" F_DWORD, + &dwDesiredAccess, &bInheritHandle, &dwProcessId)) + return NULL; + + handle = OpenProcess(dwDesiredAccess, bInheritHandle, dwProcessId); + if (handle == NULL) + return PyErr_SetFromWindowsErr(0); - return Py_BuildValue(F_HANDLE, handle); + return Py_BuildValue(F_HANDLE, handle); } static PyObject * win32_SetNamedPipeHandleState(PyObject *self, PyObject *args) { - HANDLE hNamedPipe; - PyObject *oArgs[3]; - DWORD dwArgs[3], *pArgs[3] = {NULL, NULL, NULL}; - int i; - - if (!PyArg_ParseTuple(args, F_HANDLE "OOO", - &hNamedPipe, &oArgs[0], &oArgs[1], &oArgs[2])) - return NULL; - - PyErr_Clear(); - - for (i = 0 ; i < 3 ; i++) { - if (oArgs[i] != Py_None) { - dwArgs[i] = PyLong_AsUnsignedLongMask(oArgs[i]); - if (PyErr_Occurred()) - return NULL; - pArgs[i] = &dwArgs[i]; - } - } + HANDLE hNamedPipe; + PyObject *oArgs[3]; + DWORD dwArgs[3], *pArgs[3] = {NULL, NULL, NULL}; + int i; + + if (!PyArg_ParseTuple(args, F_HANDLE "OOO", + &hNamedPipe, &oArgs[0], &oArgs[1], &oArgs[2])) + return NULL; + + PyErr_Clear(); + + for (i = 0 ; i < 3 ; i++) { + if (oArgs[i] != Py_None) { + dwArgs[i] = PyLong_AsUnsignedLongMask(oArgs[i]); + if (PyErr_Occurred()) + return NULL; + pArgs[i] = &dwArgs[i]; + } + } - if (!SetNamedPipeHandleState(hNamedPipe, pArgs[0], pArgs[1], pArgs[2])) - return PyErr_SetFromWindowsErr(0); + if (!SetNamedPipeHandleState(hNamedPipe, pArgs[0], pArgs[1], pArgs[2])) + return PyErr_SetFromWindowsErr(0); - Py_RETURN_NONE; + Py_RETURN_NONE; } static PyObject * win32_WaitNamedPipe(PyObject *self, PyObject *args) { - LPCTSTR lpNamedPipeName; - DWORD nTimeOut; - BOOL success; + LPCTSTR lpNamedPipeName; + DWORD nTimeOut; + BOOL success; - if (!PyArg_ParseTuple(args, "s" F_DWORD, &lpNamedPipeName, &nTimeOut)) - return NULL; + if (!PyArg_ParseTuple(args, "s" F_DWORD, &lpNamedPipeName, &nTimeOut)) + return NULL; - Py_BEGIN_ALLOW_THREADS - success = WaitNamedPipe(lpNamedPipeName, nTimeOut); - Py_END_ALLOW_THREADS + Py_BEGIN_ALLOW_THREADS + success = WaitNamedPipe(lpNamedPipeName, nTimeOut); + Py_END_ALLOW_THREADS - if (!success) - return PyErr_SetFromWindowsErr(0); + if (!success) + return PyErr_SetFromWindowsErr(0); - Py_RETURN_NONE; + Py_RETURN_NONE; } static PyMethodDef win32_methods[] = { - WIN32_FUNCTION(CloseHandle), - WIN32_FUNCTION(GetLastError), - WIN32_FUNCTION(OpenProcess), - WIN32_FUNCTION(ExitProcess), - WIN32_FUNCTION(ConnectNamedPipe), - WIN32_FUNCTION(CreateFile), - WIN32_FUNCTION(CreateNamedPipe), - WIN32_FUNCTION(SetNamedPipeHandleState), - WIN32_FUNCTION(WaitNamedPipe), - {NULL} + WIN32_FUNCTION(CloseHandle), + WIN32_FUNCTION(GetLastError), + WIN32_FUNCTION(OpenProcess), + WIN32_FUNCTION(ExitProcess), + WIN32_FUNCTION(ConnectNamedPipe), + WIN32_FUNCTION(CreateFile), + WIN32_FUNCTION(CreateNamedPipe), + WIN32_FUNCTION(SetNamedPipeHandleState), + WIN32_FUNCTION(WaitNamedPipe), + {NULL} }; PyTypeObject Win32Type = { - PyVarObject_HEAD_INIT(NULL, 0) + PyVarObject_HEAD_INIT(NULL, 0) }; PyObject * create_win32_namespace(void) { - Win32Type.tp_name = "_multiprocessing.win32"; - Win32Type.tp_methods = win32_methods; - if (PyType_Ready(&Win32Type) < 0) - return NULL; - Py_INCREF(&Win32Type); - - WIN32_CONSTANT(F_DWORD, ERROR_ALREADY_EXISTS); - WIN32_CONSTANT(F_DWORD, ERROR_PIPE_BUSY); - WIN32_CONSTANT(F_DWORD, ERROR_PIPE_CONNECTED); - WIN32_CONSTANT(F_DWORD, ERROR_SEM_TIMEOUT); - WIN32_CONSTANT(F_DWORD, GENERIC_READ); - WIN32_CONSTANT(F_DWORD, GENERIC_WRITE); - WIN32_CONSTANT(F_DWORD, INFINITE); - WIN32_CONSTANT(F_DWORD, NMPWAIT_WAIT_FOREVER); - WIN32_CONSTANT(F_DWORD, OPEN_EXISTING); - WIN32_CONSTANT(F_DWORD, PIPE_ACCESS_DUPLEX); - WIN32_CONSTANT(F_DWORD, PIPE_ACCESS_INBOUND); - WIN32_CONSTANT(F_DWORD, PIPE_READMODE_MESSAGE); - WIN32_CONSTANT(F_DWORD, PIPE_TYPE_MESSAGE); - WIN32_CONSTANT(F_DWORD, PIPE_UNLIMITED_INSTANCES); - WIN32_CONSTANT(F_DWORD, PIPE_WAIT); - WIN32_CONSTANT(F_DWORD, PROCESS_ALL_ACCESS); + Win32Type.tp_name = "_multiprocessing.win32"; + Win32Type.tp_methods = win32_methods; + if (PyType_Ready(&Win32Type) < 0) + return NULL; + Py_INCREF(&Win32Type); + + WIN32_CONSTANT(F_DWORD, ERROR_ALREADY_EXISTS); + WIN32_CONSTANT(F_DWORD, ERROR_PIPE_BUSY); + WIN32_CONSTANT(F_DWORD, ERROR_PIPE_CONNECTED); + WIN32_CONSTANT(F_DWORD, ERROR_SEM_TIMEOUT); + WIN32_CONSTANT(F_DWORD, GENERIC_READ); + WIN32_CONSTANT(F_DWORD, GENERIC_WRITE); + WIN32_CONSTANT(F_DWORD, INFINITE); + WIN32_CONSTANT(F_DWORD, NMPWAIT_WAIT_FOREVER); + WIN32_CONSTANT(F_DWORD, OPEN_EXISTING); + WIN32_CONSTANT(F_DWORD, PIPE_ACCESS_DUPLEX); + WIN32_CONSTANT(F_DWORD, PIPE_ACCESS_INBOUND); + WIN32_CONSTANT(F_DWORD, PIPE_READMODE_MESSAGE); + WIN32_CONSTANT(F_DWORD, PIPE_TYPE_MESSAGE); + WIN32_CONSTANT(F_DWORD, PIPE_UNLIMITED_INSTANCES); + WIN32_CONSTANT(F_DWORD, PIPE_WAIT); + WIN32_CONSTANT(F_DWORD, PROCESS_ALL_ACCESS); - WIN32_CONSTANT("i", NULL); + WIN32_CONSTANT("i", NULL); - return (PyObject*)&Win32Type; + return (PyObject*)&Win32Type; } Modified: python/branches/py3k/Modules/_randommodule.c ============================================================================== --- python/branches/py3k/Modules/_randommodule.c (original) +++ python/branches/py3k/Modules/_randommodule.c Sun May 9 17:52:27 2010 @@ -2,23 +2,23 @@ /* ------------------------------------------------------------------ The code in this module was based on a download from: - http://www.math.keio.ac.jp/~matumoto/MT2002/emt19937ar.html + http://www.math.keio.ac.jp/~matumoto/MT2002/emt19937ar.html It was modified in 2002 by Raymond Hettinger as follows: - * the principal computational lines untouched except for tabbing. + * the principal computational lines untouched except for tabbing. - * renamed genrand_res53() to random_random() and wrapped - in python calling/return code. + * renamed genrand_res53() to random_random() and wrapped + in python calling/return code. - * genrand_int32() and the helper functions, init_genrand() - and init_by_array(), were declared static, wrapped in - Python calling/return code. also, their global data - references were replaced with structure references. - - * unused functions from the original were deleted. - new, original C python code was added to implement the - Random() interface. + * genrand_int32() and the helper functions, init_genrand() + and init_by_array(), were declared static, wrapped in + Python calling/return code. also, their global data + references were replaced with structure references. + + * unused functions from the original were deleted. + new, original C python code was added to implement the + Random() interface. The following are the verbatim comments from the original code: @@ -36,15 +36,15 @@ are met: 1. Redistributions of source code must retain the above copyright - notice, this list of conditions and the following disclaimer. + 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. + 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. + 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 @@ -67,24 +67,24 @@ /* ---------------------------------------------------------------*/ #include "Python.h" -#include /* for seeding to current time */ +#include /* for seeding to current time */ /* Period parameters -- These are all magic. Don't change. */ #define N 624 #define M 397 -#define MATRIX_A 0x9908b0dfUL /* constant vector a */ +#define MATRIX_A 0x9908b0dfUL /* constant vector a */ #define UPPER_MASK 0x80000000UL /* most significant w-r bits */ #define LOWER_MASK 0x7fffffffUL /* least significant r bits */ typedef struct { - PyObject_HEAD - unsigned long state[N]; - int index; + PyObject_HEAD + unsigned long state[N]; + int index; } RandomObject; static PyTypeObject Random_Type; -#define RandomObject_Check(v) (Py_TYPE(v) == &Random_Type) +#define RandomObject_Check(v) (Py_TYPE(v) == &Random_Type) /* Random methods */ @@ -94,28 +94,28 @@ static unsigned long genrand_int32(RandomObject *self) { - unsigned long y; - static unsigned long mag01[2]={0x0UL, MATRIX_A}; - /* mag01[x] = x * MATRIX_A for x=0,1 */ - unsigned long *mt; - - mt = self->state; - if (self->index >= N) { /* generate N words at one time */ - int kk; - - for (kk=0;kk> 1) ^ mag01[y & 0x1UL]; - } - for (;kk> 1) ^ mag01[y & 0x1UL]; - } - y = (mt[N-1]&UPPER_MASK)|(mt[0]&LOWER_MASK); - mt[N-1] = mt[M-1] ^ (y >> 1) ^ mag01[y & 0x1UL]; + unsigned long y; + static unsigned long mag01[2]={0x0UL, MATRIX_A}; + /* mag01[x] = x * MATRIX_A for x=0,1 */ + unsigned long *mt; + + mt = self->state; + if (self->index >= N) { /* generate N words at one time */ + int kk; + + for (kk=0;kk> 1) ^ mag01[y & 0x1UL]; + } + for (;kk> 1) ^ mag01[y & 0x1UL]; + } + y = (mt[N-1]&UPPER_MASK)|(mt[0]&LOWER_MASK); + mt[N-1] = mt[M-1] ^ (y >> 1) ^ mag01[y & 0x1UL]; - self->index = 0; - } + self->index = 0; + } y = mt[self->index++]; y ^= (y >> 11); @@ -137,31 +137,31 @@ static PyObject * random_random(RandomObject *self) { - unsigned long a=genrand_int32(self)>>5, b=genrand_int32(self)>>6; - return PyFloat_FromDouble((a*67108864.0+b)*(1.0/9007199254740992.0)); + unsigned long a=genrand_int32(self)>>5, b=genrand_int32(self)>>6; + return PyFloat_FromDouble((a*67108864.0+b)*(1.0/9007199254740992.0)); } /* initializes mt[N] with a seed */ static void init_genrand(RandomObject *self, unsigned long s) { - int mti; - unsigned long *mt; + int mti; + unsigned long *mt; - mt = self->state; - mt[0]= s & 0xffffffffUL; - for (mti=1; mti> 30)) + mti); - /* See Knuth TAOCP Vol2. 3rd Ed. P.106 for multiplier. */ - /* In the previous versions, MSBs of the seed affect */ - /* only MSBs of the array mt[]. */ - /* 2002/01/09 modified by Makoto Matsumoto */ - mt[mti] &= 0xffffffffUL; - /* for >32 bit machines */ - } - self->index = mti; - return; + mt = self->state; + mt[0]= s & 0xffffffffUL; + for (mti=1; mti> 30)) + mti); + /* See Knuth TAOCP Vol2. 3rd Ed. P.106 for multiplier. */ + /* In the previous versions, MSBs of the seed affect */ + /* only MSBs of the array mt[]. */ + /* 2002/01/09 modified by Makoto Matsumoto */ + mt[mti] &= 0xffffffffUL; + /* for >32 bit machines */ + } + self->index = mti; + return; } /* initialize by an array with array-length */ @@ -170,28 +170,28 @@ static PyObject * init_by_array(RandomObject *self, unsigned long init_key[], unsigned long key_length) { - unsigned int i, j, k; /* was signed in the original code. RDH 12/16/2002 */ - unsigned long *mt; + unsigned int i, j, k; /* was signed in the original code. RDH 12/16/2002 */ + unsigned long *mt; - mt = self->state; - init_genrand(self, 19650218UL); - i=1; j=0; - k = (N>key_length ? N : key_length); - for (; k; k--) { - mt[i] = (mt[i] ^ ((mt[i-1] ^ (mt[i-1] >> 30)) * 1664525UL)) - + init_key[j] + j; /* non linear */ - mt[i] &= 0xffffffffUL; /* for WORDSIZE > 32 machines */ - i++; j++; - if (i>=N) { mt[0] = mt[N-1]; i=1; } - if (j>=key_length) j=0; - } - for (k=N-1; k; k--) { - mt[i] = (mt[i] ^ ((mt[i-1] ^ (mt[i-1] >> 30)) * 1566083941UL)) - - i; /* non linear */ - mt[i] &= 0xffffffffUL; /* for WORDSIZE > 32 machines */ - i++; - if (i>=N) { mt[0] = mt[N-1]; i=1; } - } + mt = self->state; + init_genrand(self, 19650218UL); + i=1; j=0; + k = (N>key_length ? N : key_length); + for (; k; k--) { + mt[i] = (mt[i] ^ ((mt[i-1] ^ (mt[i-1] >> 30)) * 1664525UL)) + + init_key[j] + j; /* non linear */ + mt[i] &= 0xffffffffUL; /* for WORDSIZE > 32 machines */ + i++; j++; + if (i>=N) { mt[0] = mt[N-1]; i=1; } + if (j>=key_length) j=0; + } + for (k=N-1; k; k--) { + mt[i] = (mt[i] ^ ((mt[i-1] ^ (mt[i-1] >> 30)) * 1566083941UL)) + - i; /* non linear */ + mt[i] &= 0xffffffffUL; /* for WORDSIZE > 32 machines */ + i++; + if (i>=N) { mt[0] = mt[N-1]; i=1; } + } mt[0] = 0x80000000UL; /* MSB is 1; assuring non-zero initial array */ Py_INCREF(Py_None); @@ -206,291 +206,291 @@ static PyObject * random_seed(RandomObject *self, PyObject *args) { - PyObject *result = NULL; /* guilty until proved innocent */ - PyObject *masklower = NULL; - PyObject *thirtytwo = NULL; - PyObject *n = NULL; - unsigned long *key = NULL; - unsigned long keymax; /* # of allocated slots in key */ - unsigned long keyused; /* # of used slots in key */ - int err; - - PyObject *arg = NULL; - - if (!PyArg_UnpackTuple(args, "seed", 0, 1, &arg)) - return NULL; - - if (arg == NULL || arg == Py_None) { - time_t now; - - time(&now); - init_genrand(self, (unsigned long)now); - Py_INCREF(Py_None); - return Py_None; - } - /* If the arg is an int or long, use its absolute value; else use - * the absolute value of its hash code. - */ - if (PyLong_Check(arg)) - n = PyNumber_Absolute(arg); - else { - long hash = PyObject_Hash(arg); - if (hash == -1) - goto Done; - n = PyLong_FromUnsignedLong((unsigned long)hash); - } - if (n == NULL) - goto Done; - - /* Now split n into 32-bit chunks, from the right. Each piece is - * stored into key, which has a capacity of keymax chunks, of which - * keyused are filled. Alas, the repeated shifting makes this a - * quadratic-time algorithm; we'd really like to use - * _PyLong_AsByteArray here, but then we'd have to break into the - * long representation to figure out how big an array was needed - * in advance. - */ - keymax = 8; /* arbitrary; grows later if needed */ - keyused = 0; - key = (unsigned long *)PyMem_Malloc(keymax * sizeof(*key)); - if (key == NULL) - goto Done; - - masklower = PyLong_FromUnsignedLong(0xffffffffU); - if (masklower == NULL) - goto Done; - thirtytwo = PyLong_FromLong(32L); - if (thirtytwo == NULL) - goto Done; - while ((err=PyObject_IsTrue(n))) { - PyObject *newn; - PyObject *pychunk; - unsigned long chunk; - - if (err == -1) - goto Done; - pychunk = PyNumber_And(n, masklower); - if (pychunk == NULL) - goto Done; - chunk = PyLong_AsUnsignedLong(pychunk); - Py_DECREF(pychunk); - if (chunk == (unsigned long)-1 && PyErr_Occurred()) - goto Done; - newn = PyNumber_Rshift(n, thirtytwo); - if (newn == NULL) - goto Done; - Py_DECREF(n); - n = newn; - if (keyused >= keymax) { - unsigned long bigger = keymax << 1; - if ((bigger >> 1) != keymax) { - PyErr_NoMemory(); - goto Done; - } - key = (unsigned long *)PyMem_Realloc(key, - bigger * sizeof(*key)); - if (key == NULL) - goto Done; - keymax = bigger; - } - assert(keyused < keymax); - key[keyused++] = chunk; - } - - if (keyused == 0) - key[keyused++] = 0UL; - result = init_by_array(self, key, keyused); + PyObject *result = NULL; /* guilty until proved innocent */ + PyObject *masklower = NULL; + PyObject *thirtytwo = NULL; + PyObject *n = NULL; + unsigned long *key = NULL; + unsigned long keymax; /* # of allocated slots in key */ + unsigned long keyused; /* # of used slots in key */ + int err; + + PyObject *arg = NULL; + + if (!PyArg_UnpackTuple(args, "seed", 0, 1, &arg)) + return NULL; + + if (arg == NULL || arg == Py_None) { + time_t now; + + time(&now); + init_genrand(self, (unsigned long)now); + Py_INCREF(Py_None); + return Py_None; + } + /* If the arg is an int or long, use its absolute value; else use + * the absolute value of its hash code. + */ + if (PyLong_Check(arg)) + n = PyNumber_Absolute(arg); + else { + long hash = PyObject_Hash(arg); + if (hash == -1) + goto Done; + n = PyLong_FromUnsignedLong((unsigned long)hash); + } + if (n == NULL) + goto Done; + + /* Now split n into 32-bit chunks, from the right. Each piece is + * stored into key, which has a capacity of keymax chunks, of which + * keyused are filled. Alas, the repeated shifting makes this a + * quadratic-time algorithm; we'd really like to use + * _PyLong_AsByteArray here, but then we'd have to break into the + * long representation to figure out how big an array was needed + * in advance. + */ + keymax = 8; /* arbitrary; grows later if needed */ + keyused = 0; + key = (unsigned long *)PyMem_Malloc(keymax * sizeof(*key)); + if (key == NULL) + goto Done; + + masklower = PyLong_FromUnsignedLong(0xffffffffU); + if (masklower == NULL) + goto Done; + thirtytwo = PyLong_FromLong(32L); + if (thirtytwo == NULL) + goto Done; + while ((err=PyObject_IsTrue(n))) { + PyObject *newn; + PyObject *pychunk; + unsigned long chunk; + + if (err == -1) + goto Done; + pychunk = PyNumber_And(n, masklower); + if (pychunk == NULL) + goto Done; + chunk = PyLong_AsUnsignedLong(pychunk); + Py_DECREF(pychunk); + if (chunk == (unsigned long)-1 && PyErr_Occurred()) + goto Done; + newn = PyNumber_Rshift(n, thirtytwo); + if (newn == NULL) + goto Done; + Py_DECREF(n); + n = newn; + if (keyused >= keymax) { + unsigned long bigger = keymax << 1; + if ((bigger >> 1) != keymax) { + PyErr_NoMemory(); + goto Done; + } + key = (unsigned long *)PyMem_Realloc(key, + bigger * sizeof(*key)); + if (key == NULL) + goto Done; + keymax = bigger; + } + assert(keyused < keymax); + key[keyused++] = chunk; + } + + if (keyused == 0) + key[keyused++] = 0UL; + result = init_by_array(self, key, keyused); Done: - Py_XDECREF(masklower); - Py_XDECREF(thirtytwo); - Py_XDECREF(n); - PyMem_Free(key); - return result; + Py_XDECREF(masklower); + Py_XDECREF(thirtytwo); + Py_XDECREF(n); + PyMem_Free(key); + return result; } static PyObject * random_getstate(RandomObject *self) { - PyObject *state; - PyObject *element; - int i; - - state = PyTuple_New(N+1); - if (state == NULL) - return NULL; - for (i=0; istate[i]); - if (element == NULL) - goto Fail; - PyTuple_SET_ITEM(state, i, element); - } - element = PyLong_FromLong((long)(self->index)); - if (element == NULL) - goto Fail; - PyTuple_SET_ITEM(state, i, element); - return state; + PyObject *state; + PyObject *element; + int i; + + state = PyTuple_New(N+1); + if (state == NULL) + return NULL; + for (i=0; istate[i]); + if (element == NULL) + goto Fail; + PyTuple_SET_ITEM(state, i, element); + } + element = PyLong_FromLong((long)(self->index)); + if (element == NULL) + goto Fail; + PyTuple_SET_ITEM(state, i, element); + return state; Fail: - Py_DECREF(state); - return NULL; + Py_DECREF(state); + return NULL; } static PyObject * random_setstate(RandomObject *self, PyObject *state) { - int i; - unsigned long element; - long index; - - if (!PyTuple_Check(state)) { - PyErr_SetString(PyExc_TypeError, - "state vector must be a tuple"); - return NULL; - } - if (PyTuple_Size(state) != N+1) { - PyErr_SetString(PyExc_ValueError, - "state vector is the wrong size"); - return NULL; - } - - for (i=0; istate[i] = element & 0xffffffffUL; /* Make sure we get sane state */ - } - - index = PyLong_AsLong(PyTuple_GET_ITEM(state, i)); - if (index == -1 && PyErr_Occurred()) - return NULL; - self->index = (int)index; + int i; + unsigned long element; + long index; + + if (!PyTuple_Check(state)) { + PyErr_SetString(PyExc_TypeError, + "state vector must be a tuple"); + return NULL; + } + if (PyTuple_Size(state) != N+1) { + PyErr_SetString(PyExc_ValueError, + "state vector is the wrong size"); + return NULL; + } + + for (i=0; istate[i] = element & 0xffffffffUL; /* Make sure we get sane state */ + } + + index = PyLong_AsLong(PyTuple_GET_ITEM(state, i)); + if (index == -1 && PyErr_Occurred()) + return NULL; + self->index = (int)index; - Py_INCREF(Py_None); - return Py_None; + Py_INCREF(Py_None); + return Py_None; } static PyObject * random_getrandbits(RandomObject *self, PyObject *args) { - int k, i, bytes; - unsigned long r; - unsigned char *bytearray; - PyObject *result; - - if (!PyArg_ParseTuple(args, "i:getrandbits", &k)) - return NULL; - - if (k <= 0) { - PyErr_SetString(PyExc_ValueError, - "number of bits must be greater than zero"); - return NULL; - } - - bytes = ((k - 1) / 32 + 1) * 4; - bytearray = (unsigned char *)PyMem_Malloc(bytes); - if (bytearray == NULL) { - PyErr_NoMemory(); - return NULL; - } - - /* Fill-out whole words, byte-by-byte to avoid endianness issues */ - for (i=0 ; i>= (32 - k); - bytearray[i+0] = (unsigned char)r; - bytearray[i+1] = (unsigned char)(r >> 8); - bytearray[i+2] = (unsigned char)(r >> 16); - bytearray[i+3] = (unsigned char)(r >> 24); - } - - /* little endian order to match bytearray assignment order */ - result = _PyLong_FromByteArray(bytearray, bytes, 1, 0); - PyMem_Free(bytearray); - return result; + int k, i, bytes; + unsigned long r; + unsigned char *bytearray; + PyObject *result; + + if (!PyArg_ParseTuple(args, "i:getrandbits", &k)) + return NULL; + + if (k <= 0) { + PyErr_SetString(PyExc_ValueError, + "number of bits must be greater than zero"); + return NULL; + } + + bytes = ((k - 1) / 32 + 1) * 4; + bytearray = (unsigned char *)PyMem_Malloc(bytes); + if (bytearray == NULL) { + PyErr_NoMemory(); + return NULL; + } + + /* Fill-out whole words, byte-by-byte to avoid endianness issues */ + for (i=0 ; i>= (32 - k); + bytearray[i+0] = (unsigned char)r; + bytearray[i+1] = (unsigned char)(r >> 8); + bytearray[i+2] = (unsigned char)(r >> 16); + bytearray[i+3] = (unsigned char)(r >> 24); + } + + /* little endian order to match bytearray assignment order */ + result = _PyLong_FromByteArray(bytearray, bytes, 1, 0); + PyMem_Free(bytearray); + return result; } static PyObject * random_new(PyTypeObject *type, PyObject *args, PyObject *kwds) { - RandomObject *self; - PyObject *tmp; + RandomObject *self; + PyObject *tmp; - if (type == &Random_Type && !_PyArg_NoKeywords("Random()", kwds)) - return NULL; + if (type == &Random_Type && !_PyArg_NoKeywords("Random()", kwds)) + return NULL; - self = (RandomObject *)type->tp_alloc(type, 0); - if (self == NULL) - return NULL; - tmp = random_seed(self, args); - if (tmp == NULL) { - Py_DECREF(self); - return NULL; - } - Py_DECREF(tmp); - return (PyObject *)self; + self = (RandomObject *)type->tp_alloc(type, 0); + if (self == NULL) + return NULL; + tmp = random_seed(self, args); + if (tmp == NULL) { + Py_DECREF(self); + return NULL; + } + Py_DECREF(tmp); + return (PyObject *)self; } static PyMethodDef random_methods[] = { - {"random", (PyCFunction)random_random, METH_NOARGS, - PyDoc_STR("random() -> x in the interval [0, 1).")}, - {"seed", (PyCFunction)random_seed, METH_VARARGS, - PyDoc_STR("seed([n]) -> None. Defaults to current time.")}, - {"getstate", (PyCFunction)random_getstate, METH_NOARGS, - PyDoc_STR("getstate() -> tuple containing the current state.")}, - {"setstate", (PyCFunction)random_setstate, METH_O, - PyDoc_STR("setstate(state) -> None. Restores generator state.")}, - {"getrandbits", (PyCFunction)random_getrandbits, METH_VARARGS, - PyDoc_STR("getrandbits(k) -> x. Generates a long int with " - "k random bits.")}, - {NULL, NULL} /* sentinel */ + {"random", (PyCFunction)random_random, METH_NOARGS, + PyDoc_STR("random() -> x in the interval [0, 1).")}, + {"seed", (PyCFunction)random_seed, METH_VARARGS, + PyDoc_STR("seed([n]) -> None. Defaults to current time.")}, + {"getstate", (PyCFunction)random_getstate, METH_NOARGS, + PyDoc_STR("getstate() -> tuple containing the current state.")}, + {"setstate", (PyCFunction)random_setstate, METH_O, + PyDoc_STR("setstate(state) -> None. Restores generator state.")}, + {"getrandbits", (PyCFunction)random_getrandbits, METH_VARARGS, + PyDoc_STR("getrandbits(k) -> x. Generates a long int with " + "k random bits.")}, + {NULL, NULL} /* sentinel */ }; PyDoc_STRVAR(random_doc, "Random() -> create a random number generator with its own internal state."); static PyTypeObject Random_Type = { - PyVarObject_HEAD_INIT(NULL, 0) - "_random.Random", /*tp_name*/ - sizeof(RandomObject), /*tp_basicsize*/ - 0, /*tp_itemsize*/ - /* methods */ - 0, /*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_BASETYPE, /*tp_flags*/ - random_doc, /*tp_doc*/ - 0, /*tp_traverse*/ - 0, /*tp_clear*/ - 0, /*tp_richcompare*/ - 0, /*tp_weaklistoffset*/ - 0, /*tp_iter*/ - 0, /*tp_iternext*/ - random_methods, /*tp_methods*/ - 0, /*tp_members*/ - 0, /*tp_getset*/ - 0, /*tp_base*/ - 0, /*tp_dict*/ - 0, /*tp_descr_get*/ - 0, /*tp_descr_set*/ - 0, /*tp_dictoffset*/ - 0, /*tp_init*/ - 0, /*tp_alloc*/ - random_new, /*tp_new*/ - PyObject_Free, /*tp_free*/ - 0, /*tp_is_gc*/ + PyVarObject_HEAD_INIT(NULL, 0) + "_random.Random", /*tp_name*/ + sizeof(RandomObject), /*tp_basicsize*/ + 0, /*tp_itemsize*/ + /* methods */ + 0, /*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_BASETYPE, /*tp_flags*/ + random_doc, /*tp_doc*/ + 0, /*tp_traverse*/ + 0, /*tp_clear*/ + 0, /*tp_richcompare*/ + 0, /*tp_weaklistoffset*/ + 0, /*tp_iter*/ + 0, /*tp_iternext*/ + random_methods, /*tp_methods*/ + 0, /*tp_members*/ + 0, /*tp_getset*/ + 0, /*tp_base*/ + 0, /*tp_dict*/ + 0, /*tp_descr_get*/ + 0, /*tp_descr_set*/ + 0, /*tp_dictoffset*/ + 0, /*tp_init*/ + 0, /*tp_alloc*/ + random_new, /*tp_new*/ + PyObject_Free, /*tp_free*/ + 0, /*tp_is_gc*/ }; PyDoc_STRVAR(module_doc, @@ -498,28 +498,28 @@ static struct PyModuleDef _randommodule = { - PyModuleDef_HEAD_INIT, - "_random", - module_doc, - -1, - NULL, - NULL, - NULL, - NULL, - NULL + PyModuleDef_HEAD_INIT, + "_random", + module_doc, + -1, + NULL, + NULL, + NULL, + NULL, + NULL }; PyMODINIT_FUNC PyInit__random(void) { - PyObject *m; + PyObject *m; - if (PyType_Ready(&Random_Type) < 0) - return NULL; - m = PyModule_Create(&_randommodule); - if (m == NULL) - return NULL; - Py_INCREF(&Random_Type); - PyModule_AddObject(m, "Random", (PyObject *)&Random_Type); - return m; + if (PyType_Ready(&Random_Type) < 0) + return NULL; + m = PyModule_Create(&_randommodule); + if (m == NULL) + return NULL; + Py_INCREF(&Random_Type); + PyModule_AddObject(m, "Random", (PyObject *)&Random_Type); + return m; } Modified: python/branches/py3k/Modules/_scproxy.c ============================================================================== --- python/branches/py3k/Modules/_scproxy.c (original) +++ python/branches/py3k/Modules/_scproxy.c Sun May 9 17:52:27 2010 @@ -5,167 +5,167 @@ #include #include -static int32_t +static int32_t cfnum_to_int32(CFNumberRef num) { - int32_t result; + int32_t result; - CFNumberGetValue(num, kCFNumberSInt32Type, &result); - return result; + CFNumberGetValue(num, kCFNumberSInt32Type, &result); + return result; } static PyObject* cfstring_to_pystring(CFStringRef ref) { - const char* s; + const char* s; - s = CFStringGetCStringPtr(ref, kCFStringEncodingUTF8); - if (s) { - return PyUnicode_DecodeUTF8( - s, strlen(s), NULL); - - } else { - CFIndex len = CFStringGetLength(ref); - Boolean ok; - PyObject* result; - char* buf; - - buf = PyMem_Malloc(len*4); - if (buf == NULL) { - PyErr_NoMemory(); - return NULL; - } - - ok = CFStringGetCString(ref, - buf, len * 4, - kCFStringEncodingUTF8); - if (!ok) { - PyMem_Free(buf); - return NULL; - } else { - result = PyUnicode_DecodeUTF8( - buf, strlen(buf), NULL); - PyMem_Free(buf); - } - return result; - } + s = CFStringGetCStringPtr(ref, kCFStringEncodingUTF8); + if (s) { + return PyUnicode_DecodeUTF8( + s, strlen(s), NULL); + + } else { + CFIndex len = CFStringGetLength(ref); + Boolean ok; + PyObject* result; + char* buf; + + buf = PyMem_Malloc(len*4); + if (buf == NULL) { + PyErr_NoMemory(); + return NULL; + } + + ok = CFStringGetCString(ref, + buf, len * 4, + kCFStringEncodingUTF8); + if (!ok) { + PyMem_Free(buf); + return NULL; + } else { + result = PyUnicode_DecodeUTF8( + buf, strlen(buf), NULL); + PyMem_Free(buf); + } + return result; + } } static PyObject* get_proxy_settings(PyObject* mod __attribute__((__unused__))) { - CFDictionaryRef proxyDict = NULL; - CFNumberRef aNum = NULL; - CFArrayRef anArray = NULL; - PyObject* result = NULL; - PyObject* v; - int r; - - proxyDict = SCDynamicStoreCopyProxies(NULL); - if (!proxyDict) { - Py_INCREF(Py_None); - return Py_None; - } - - result = PyDict_New(); - if (result == NULL) goto error; - - if (&kSCPropNetProxiesExcludeSimpleHostnames != NULL) { - aNum = CFDictionaryGetValue(proxyDict, - kSCPropNetProxiesExcludeSimpleHostnames); - if (aNum == NULL) { - v = PyBool_FromLong(1); - } else { - v = PyBool_FromLong(cfnum_to_int32(aNum)); - } - } else { - v = PyBool_FromLong(1); - } - - if (v == NULL) goto error; - - r = PyDict_SetItemString(result, "exclude_simple", v); - Py_DECREF(v); v = NULL; - if (r == -1) goto error; - - anArray = CFDictionaryGetValue(proxyDict, - kSCPropNetProxiesExceptionsList); - if (anArray != NULL) { - CFIndex len = CFArrayGetCount(anArray); - CFIndex i; - v = PyTuple_New(len); - if (v == NULL) goto error; - - r = PyDict_SetItemString(result, "exceptions", v); - Py_DECREF(v); - if (r == -1) goto error; - - for (i = 0; i < len; i++) { - CFStringRef aString = NULL; - - aString = CFArrayGetValueAtIndex(anArray, i); - if (aString == NULL) { - PyTuple_SetItem(v, i, Py_None); - Py_INCREF(Py_None); - } else { - PyObject* t = cfstring_to_pystring(aString); - if (!t) { - PyTuple_SetItem(v, i, Py_None); - Py_INCREF(Py_None); - } else { - PyTuple_SetItem(v, i, t); - } - } - } - } + CFDictionaryRef proxyDict = NULL; + CFNumberRef aNum = NULL; + CFArrayRef anArray = NULL; + PyObject* result = NULL; + PyObject* v; + int r; + + proxyDict = SCDynamicStoreCopyProxies(NULL); + if (!proxyDict) { + Py_INCREF(Py_None); + return Py_None; + } + + result = PyDict_New(); + if (result == NULL) goto error; + + if (&kSCPropNetProxiesExcludeSimpleHostnames != NULL) { + aNum = CFDictionaryGetValue(proxyDict, + kSCPropNetProxiesExcludeSimpleHostnames); + if (aNum == NULL) { + v = PyBool_FromLong(1); + } else { + v = PyBool_FromLong(cfnum_to_int32(aNum)); + } + } else { + v = PyBool_FromLong(1); + } + + if (v == NULL) goto error; + + r = PyDict_SetItemString(result, "exclude_simple", v); + Py_DECREF(v); v = NULL; + if (r == -1) goto error; + + anArray = CFDictionaryGetValue(proxyDict, + kSCPropNetProxiesExceptionsList); + if (anArray != NULL) { + CFIndex len = CFArrayGetCount(anArray); + CFIndex i; + v = PyTuple_New(len); + if (v == NULL) goto error; + + r = PyDict_SetItemString(result, "exceptions", v); + Py_DECREF(v); + if (r == -1) goto error; + + for (i = 0; i < len; i++) { + CFStringRef aString = NULL; + + aString = CFArrayGetValueAtIndex(anArray, i); + if (aString == NULL) { + PyTuple_SetItem(v, i, Py_None); + Py_INCREF(Py_None); + } else { + PyObject* t = cfstring_to_pystring(aString); + if (!t) { + PyTuple_SetItem(v, i, Py_None); + Py_INCREF(Py_None); + } else { + PyTuple_SetItem(v, i, t); + } + } + } + } - CFRelease(proxyDict); - return result; + CFRelease(proxyDict); + return result; error: - if (proxyDict) CFRelease(proxyDict); - Py_XDECREF(result); - return NULL; + if (proxyDict) CFRelease(proxyDict); + Py_XDECREF(result); + return NULL; } static int set_proxy(PyObject* proxies, char* proto, CFDictionaryRef proxyDict, - CFStringRef enabledKey, - CFStringRef hostKey, CFStringRef portKey) + CFStringRef enabledKey, + CFStringRef hostKey, CFStringRef portKey) { - CFNumberRef aNum; + CFNumberRef aNum; - aNum = CFDictionaryGetValue(proxyDict, enabledKey); - if (aNum && cfnum_to_int32(aNum)) { - CFStringRef hostString; - - hostString = CFDictionaryGetValue(proxyDict, hostKey); - aNum = CFDictionaryGetValue(proxyDict, portKey); - - if (hostString) { - int r; - PyObject* h = cfstring_to_pystring(hostString); - PyObject* v; - if (h) { - if (aNum) { - int32_t port = cfnum_to_int32(aNum); - v = PyUnicode_FromFormat("http://%U:%ld", - h, (long)port); - } else { - v = PyUnicode_FromFormat("http://%U", h); - } - Py_DECREF(h); - if (!v) return -1; - r = PyDict_SetItemString(proxies, proto, - v); - Py_DECREF(v); - return r; - } - } + aNum = CFDictionaryGetValue(proxyDict, enabledKey); + if (aNum && cfnum_to_int32(aNum)) { + CFStringRef hostString; + + hostString = CFDictionaryGetValue(proxyDict, hostKey); + aNum = CFDictionaryGetValue(proxyDict, portKey); + + if (hostString) { + int r; + PyObject* h = cfstring_to_pystring(hostString); + PyObject* v; + if (h) { + if (aNum) { + int32_t port = cfnum_to_int32(aNum); + v = PyUnicode_FromFormat("http://%U:%ld", + h, (long)port); + } else { + v = PyUnicode_FromFormat("http://%U", h); + } + Py_DECREF(h); + if (!v) return -1; + r = PyDict_SetItemString(proxies, proto, + v); + Py_DECREF(v); + return r; + } + } - } - return 0; + } + return 0; } @@ -173,75 +173,75 @@ static PyObject* get_proxies(PyObject* mod __attribute__((__unused__))) { - PyObject* result = NULL; - int r; - CFDictionaryRef proxyDict = NULL; - - proxyDict = SCDynamicStoreCopyProxies(NULL); - if (proxyDict == NULL) { - return PyDict_New(); - } - - result = PyDict_New(); - if (result == NULL) goto error; - - r = set_proxy(result, "http", proxyDict, - kSCPropNetProxiesHTTPEnable, - kSCPropNetProxiesHTTPProxy, - kSCPropNetProxiesHTTPPort); - if (r == -1) goto error; - r = set_proxy(result, "https", proxyDict, - kSCPropNetProxiesHTTPSEnable, - kSCPropNetProxiesHTTPSProxy, - kSCPropNetProxiesHTTPSPort); - if (r == -1) goto error; - r = set_proxy(result, "ftp", proxyDict, - kSCPropNetProxiesFTPEnable, - kSCPropNetProxiesFTPProxy, - kSCPropNetProxiesFTPPort); - if (r == -1) goto error; - r = set_proxy(result, "gopher", proxyDict, - kSCPropNetProxiesGopherEnable, - kSCPropNetProxiesGopherProxy, - kSCPropNetProxiesGopherPort); - if (r == -1) goto error; + PyObject* result = NULL; + int r; + CFDictionaryRef proxyDict = NULL; + + proxyDict = SCDynamicStoreCopyProxies(NULL); + if (proxyDict == NULL) { + return PyDict_New(); + } + + result = PyDict_New(); + if (result == NULL) goto error; + + r = set_proxy(result, "http", proxyDict, + kSCPropNetProxiesHTTPEnable, + kSCPropNetProxiesHTTPProxy, + kSCPropNetProxiesHTTPPort); + if (r == -1) goto error; + r = set_proxy(result, "https", proxyDict, + kSCPropNetProxiesHTTPSEnable, + kSCPropNetProxiesHTTPSProxy, + kSCPropNetProxiesHTTPSPort); + if (r == -1) goto error; + r = set_proxy(result, "ftp", proxyDict, + kSCPropNetProxiesFTPEnable, + kSCPropNetProxiesFTPProxy, + kSCPropNetProxiesFTPPort); + if (r == -1) goto error; + r = set_proxy(result, "gopher", proxyDict, + kSCPropNetProxiesGopherEnable, + kSCPropNetProxiesGopherProxy, + kSCPropNetProxiesGopherPort); + if (r == -1) goto error; - CFRelease(proxyDict); - return result; + CFRelease(proxyDict); + return result; error: - if (proxyDict) CFRelease(proxyDict); - Py_XDECREF(result); - return NULL; + if (proxyDict) CFRelease(proxyDict); + Py_XDECREF(result); + return NULL; } static PyMethodDef mod_methods[] = { - { - "_get_proxy_settings", - (PyCFunction)get_proxy_settings, - METH_NOARGS, - NULL, - }, - { - "_get_proxies", - (PyCFunction)get_proxies, - METH_NOARGS, - NULL, - }, - { 0, 0, 0, 0 } + { + "_get_proxy_settings", + (PyCFunction)get_proxy_settings, + METH_NOARGS, + NULL, + }, + { + "_get_proxies", + (PyCFunction)get_proxies, + METH_NOARGS, + NULL, + }, + { 0, 0, 0, 0 } }; static struct PyModuleDef mod_module = { - PyModuleDef_HEAD_INIT, - "_scproxy", - NULL, - -1, - mod_methods, - NULL, - NULL, - NULL, - NULL + PyModuleDef_HEAD_INIT, + "_scproxy", + NULL, + -1, + mod_methods, + NULL, + NULL, + NULL, + NULL }; @@ -249,10 +249,10 @@ extern "C" { #endif -PyObject* +PyObject* PyInit__scproxy(void) { - return PyModule_Create(&mod_module); + return PyModule_Create(&mod_module); } #ifdef __cplusplus Modified: python/branches/py3k/Modules/_sqlite/module.c ============================================================================== --- python/branches/py3k/Modules/_sqlite/module.c (original) +++ python/branches/py3k/Modules/_sqlite/module.c Sun May 9 17:52:27 2010 @@ -64,7 +64,7 @@ if (!PyArg_ParseTupleAndKeywords(args, kwargs, "s|diOiOi", kwlist, &database, &timeout, &detect_types, &isolation_level, &check_same_thread, &factory, &cached_statements)) { - return NULL; + return NULL; } if (factory == NULL) { @@ -93,7 +93,7 @@ if (!PyArg_ParseTupleAndKeywords(args, kwargs, "s", kwlist, &statement)) { - return NULL; + return NULL; } if (sqlite3_complete(statement)) { @@ -122,7 +122,7 @@ if (!PyArg_ParseTupleAndKeywords(args, kwargs, "i", kwlist, &do_enable)) { - return NULL; + return NULL; } rc = sqlite3_enable_shared_cache(do_enable); @@ -302,15 +302,15 @@ static struct PyModuleDef _sqlite3module = { - PyModuleDef_HEAD_INIT, - "_sqlite3", - NULL, - -1, - module_methods, - NULL, - NULL, - NULL, - NULL + PyModuleDef_HEAD_INIT, + "_sqlite3", + NULL, + -1, + module_methods, + NULL, + NULL, + NULL, + NULL }; PyMODINIT_FUNC PyInit__sqlite3(void) @@ -329,7 +329,7 @@ (pysqlite_statement_setup_types() < 0) || (pysqlite_prepare_protocol_setup_types() < 0) ) { - Py_DECREF(module); + Py_DECREF(module); return NULL; } @@ -448,7 +448,7 @@ /* Original comment from _bsddb.c in the Python core. This is also still * needed nowadays for Python 2.3/2.4. - * + * * PyEval_InitThreads is called here due to a quirk in python 1.5 * - 2.2.1 (at least) according to Russell Williamson : * The global interpreter lock is not initialized until the first @@ -467,8 +467,8 @@ if (PyErr_Occurred()) { PyErr_SetString(PyExc_ImportError, MODULE_NAME ": init failed"); - Py_DECREF(module); - module = NULL; + Py_DECREF(module); + module = NULL; } return module; } Modified: python/branches/py3k/Modules/_struct.c ============================================================================== --- python/branches/py3k/Modules/_struct.c (original) +++ python/branches/py3k/Modules/_struct.c Sun May 9 17:52:27 2010 @@ -14,30 +14,30 @@ /* The translation function for each format character is table driven */ typedef struct _formatdef { - char format; - Py_ssize_t size; - Py_ssize_t alignment; - PyObject* (*unpack)(const char *, - const struct _formatdef *); - int (*pack)(char *, PyObject *, - const struct _formatdef *); + char format; + Py_ssize_t size; + Py_ssize_t alignment; + PyObject* (*unpack)(const char *, + const struct _formatdef *); + int (*pack)(char *, PyObject *, + const struct _formatdef *); } formatdef; typedef struct _formatcode { - const struct _formatdef *fmtdef; - Py_ssize_t offset; - Py_ssize_t size; + const struct _formatdef *fmtdef; + Py_ssize_t offset; + Py_ssize_t size; } formatcode; /* Struct object interface */ typedef struct { - PyObject_HEAD - Py_ssize_t s_size; - Py_ssize_t s_len; - formatcode *s_codes; - PyObject *s_format; - PyObject *weakreflist; /* List of weak references */ + PyObject_HEAD + Py_ssize_t s_size; + Py_ssize_t s_len; + formatcode *s_codes; + PyObject *s_format; + PyObject *weakreflist; /* List of weak references */ } PyStructObject; @@ -95,25 +95,25 @@ static PyObject * get_pylong(PyObject *v) { - assert(v != NULL); - if (!PyLong_Check(v)) { - /* Not an integer; try to use __index__ to convert. */ - if (PyIndex_Check(v)) { - v = PyNumber_Index(v); - if (v == NULL) - return NULL; - } - else { - PyErr_SetString(StructError, - "required argument is not an integer"); - return NULL; - } - } - else - Py_INCREF(v); + assert(v != NULL); + if (!PyLong_Check(v)) { + /* Not an integer; try to use __index__ to convert. */ + if (PyIndex_Check(v)) { + v = PyNumber_Index(v); + if (v == NULL) + return NULL; + } + else { + PyErr_SetString(StructError, + "required argument is not an integer"); + return NULL; + } + } + else + Py_INCREF(v); - assert(PyLong_Check(v)); - return v; + assert(PyLong_Check(v)); + return v; } /* Helper routine to get a C long and raise the appropriate error if it isn't @@ -122,22 +122,22 @@ static int get_long(PyObject *v, long *p) { - long x; + long x; - v = get_pylong(v); - if (v == NULL) - return -1; - assert(PyLong_Check(v)); - x = PyLong_AsLong(v); - Py_DECREF(v); - if (x == (long)-1 && PyErr_Occurred()) { - if (PyErr_ExceptionMatches(PyExc_OverflowError)) - PyErr_SetString(StructError, - "argument out of range"); - return -1; - } - *p = x; - return 0; + v = get_pylong(v); + if (v == NULL) + return -1; + assert(PyLong_Check(v)); + x = PyLong_AsLong(v); + Py_DECREF(v); + if (x == (long)-1 && PyErr_Occurred()) { + if (PyErr_ExceptionMatches(PyExc_OverflowError)) + PyErr_SetString(StructError, + "argument out of range"); + return -1; + } + *p = x; + return 0; } @@ -146,22 +146,22 @@ static int get_ulong(PyObject *v, unsigned long *p) { - unsigned long x; + unsigned long x; - v = get_pylong(v); - if (v == NULL) - return -1; - assert(PyLong_Check(v)); - x = PyLong_AsUnsignedLong(v); - Py_DECREF(v); - if (x == (unsigned long)-1 && PyErr_Occurred()) { - if (PyErr_ExceptionMatches(PyExc_OverflowError)) - PyErr_SetString(StructError, - "argument out of range"); - return -1; - } - *p = x; - return 0; + v = get_pylong(v); + if (v == NULL) + return -1; + assert(PyLong_Check(v)); + x = PyLong_AsUnsignedLong(v); + Py_DECREF(v); + if (x == (unsigned long)-1 && PyErr_Occurred()) { + if (PyErr_ExceptionMatches(PyExc_OverflowError)) + PyErr_SetString(StructError, + "argument out of range"); + return -1; + } + *p = x; + return 0; } #ifdef HAVE_LONG_LONG @@ -171,22 +171,22 @@ static int get_longlong(PyObject *v, PY_LONG_LONG *p) { - PY_LONG_LONG x; + PY_LONG_LONG x; - v = get_pylong(v); - if (v == NULL) - return -1; - assert(PyLong_Check(v)); - x = PyLong_AsLongLong(v); - Py_DECREF(v); - if (x == (PY_LONG_LONG)-1 && PyErr_Occurred()) { - if (PyErr_ExceptionMatches(PyExc_OverflowError)) - PyErr_SetString(StructError, - "argument out of range"); - return -1; - } - *p = x; - return 0; + v = get_pylong(v); + if (v == NULL) + return -1; + assert(PyLong_Check(v)); + x = PyLong_AsLongLong(v); + Py_DECREF(v); + if (x == (PY_LONG_LONG)-1 && PyErr_Occurred()) { + if (PyErr_ExceptionMatches(PyExc_OverflowError)) + PyErr_SetString(StructError, + "argument out of range"); + return -1; + } + *p = x; + return 0; } /* Same, but handling native unsigned long long. */ @@ -194,22 +194,22 @@ static int get_ulonglong(PyObject *v, unsigned PY_LONG_LONG *p) { - unsigned PY_LONG_LONG x; + unsigned PY_LONG_LONG x; - v = get_pylong(v); - if (v == NULL) - return -1; - assert(PyLong_Check(v)); - x = PyLong_AsUnsignedLongLong(v); - Py_DECREF(v); - if (x == (unsigned PY_LONG_LONG)-1 && PyErr_Occurred()) { - if (PyErr_ExceptionMatches(PyExc_OverflowError)) - PyErr_SetString(StructError, - "argument out of range"); - return -1; - } - *p = x; - return 0; + v = get_pylong(v); + if (v == NULL) + return -1; + assert(PyLong_Check(v)); + x = PyLong_AsUnsignedLongLong(v); + Py_DECREF(v); + if (x == (unsigned PY_LONG_LONG)-1 && PyErr_Occurred()) { + if (PyErr_ExceptionMatches(PyExc_OverflowError)) + PyErr_SetString(StructError, + "argument out of range"); + return -1; + } + *p = x; + return 0; } #endif @@ -222,57 +222,57 @@ static PyObject * unpack_float(const char *p, /* start of 4-byte string */ - int le) /* true for little-endian, false for big-endian */ + int le) /* true for little-endian, false for big-endian */ { - double x; + double x; - x = _PyFloat_Unpack4((unsigned char *)p, le); - if (x == -1.0 && PyErr_Occurred()) - return NULL; - return PyFloat_FromDouble(x); + x = _PyFloat_Unpack4((unsigned char *)p, le); + if (x == -1.0 && PyErr_Occurred()) + return NULL; + return PyFloat_FromDouble(x); } static PyObject * unpack_double(const char *p, /* start of 8-byte string */ - int le) /* true for little-endian, false for big-endian */ + int le) /* true for little-endian, false for big-endian */ { - double x; + double x; - x = _PyFloat_Unpack8((unsigned char *)p, le); - if (x == -1.0 && PyErr_Occurred()) - return NULL; - return PyFloat_FromDouble(x); + x = _PyFloat_Unpack8((unsigned char *)p, le); + if (x == -1.0 && PyErr_Occurred()) + return NULL; + return PyFloat_FromDouble(x); } /* Helper to format the range error exceptions */ static int _range_error(const formatdef *f, int is_unsigned) { - /* ulargest is the largest unsigned value with f->size bytes. - * Note that the simpler: - * ((size_t)1 << (f->size * 8)) - 1 - * doesn't work when f->size == sizeof(size_t) because C doesn't - * define what happens when a left shift count is >= the number of - * bits in the integer being shifted; e.g., on some boxes it doesn't - * shift at all when they're equal. - */ - const size_t ulargest = (size_t)-1 >> ((SIZEOF_SIZE_T - f->size)*8); - assert(f->size >= 1 && f->size <= SIZEOF_SIZE_T); - if (is_unsigned) - PyErr_Format(StructError, - "'%c' format requires 0 <= number <= %zu", - f->format, - ulargest); - else { - const Py_ssize_t largest = (Py_ssize_t)(ulargest >> 1); - PyErr_Format(StructError, - "'%c' format requires %zd <= number <= %zd", - f->format, - ~ largest, - largest); - } + /* ulargest is the largest unsigned value with f->size bytes. + * Note that the simpler: + * ((size_t)1 << (f->size * 8)) - 1 + * doesn't work when f->size == sizeof(size_t) because C doesn't + * define what happens when a left shift count is >= the number of + * bits in the integer being shifted; e.g., on some boxes it doesn't + * shift at all when they're equal. + */ + const size_t ulargest = (size_t)-1 >> ((SIZEOF_SIZE_T - f->size)*8); + assert(f->size >= 1 && f->size <= SIZEOF_SIZE_T); + if (is_unsigned) + PyErr_Format(StructError, + "'%c' format requires 0 <= number <= %zu", + f->format, + ulargest); + else { + const Py_ssize_t largest = (Py_ssize_t)(ulargest >> 1); + PyErr_Format(StructError, + "'%c' format requires %zd <= number <= %zd", + f->format, + ~ largest, + largest); + } - return -1; + return -1; } @@ -299,75 +299,75 @@ static PyObject * nu_char(const char *p, const formatdef *f) { - return PyBytes_FromStringAndSize(p, 1); + return PyBytes_FromStringAndSize(p, 1); } static PyObject * nu_byte(const char *p, const formatdef *f) { - return PyLong_FromLong((long) *(signed char *)p); + return PyLong_FromLong((long) *(signed char *)p); } static PyObject * nu_ubyte(const char *p, const formatdef *f) { - return PyLong_FromLong((long) *(unsigned char *)p); + return PyLong_FromLong((long) *(unsigned char *)p); } static PyObject * nu_short(const char *p, const formatdef *f) { - short x; - memcpy((char *)&x, p, sizeof x); - return PyLong_FromLong((long)x); + short x; + memcpy((char *)&x, p, sizeof x); + return PyLong_FromLong((long)x); } static PyObject * nu_ushort(const char *p, const formatdef *f) { - unsigned short x; - memcpy((char *)&x, p, sizeof x); - return PyLong_FromLong((long)x); + unsigned short x; + memcpy((char *)&x, p, sizeof x); + return PyLong_FromLong((long)x); } static PyObject * nu_int(const char *p, const formatdef *f) { - int x; - memcpy((char *)&x, p, sizeof x); - return PyLong_FromLong((long)x); + int x; + memcpy((char *)&x, p, sizeof x); + return PyLong_FromLong((long)x); } static PyObject * nu_uint(const char *p, const formatdef *f) { - unsigned int x; - memcpy((char *)&x, p, sizeof x); + unsigned int x; + memcpy((char *)&x, p, sizeof x); #if (SIZEOF_LONG > SIZEOF_INT) - return PyLong_FromLong((long)x); + return PyLong_FromLong((long)x); #else - if (x <= ((unsigned int)LONG_MAX)) - return PyLong_FromLong((long)x); - return PyLong_FromUnsignedLong((unsigned long)x); + if (x <= ((unsigned int)LONG_MAX)) + return PyLong_FromLong((long)x); + return PyLong_FromUnsignedLong((unsigned long)x); #endif } static PyObject * nu_long(const char *p, const formatdef *f) { - long x; - memcpy((char *)&x, p, sizeof x); - return PyLong_FromLong(x); + long x; + memcpy((char *)&x, p, sizeof x); + return PyLong_FromLong(x); } static PyObject * nu_ulong(const char *p, const formatdef *f) { - unsigned long x; - memcpy((char *)&x, p, sizeof x); - if (x <= LONG_MAX) - return PyLong_FromLong((long)x); - return PyLong_FromUnsignedLong(x); + unsigned long x; + memcpy((char *)&x, p, sizeof x); + if (x <= LONG_MAX) + return PyLong_FromLong((long)x); + return PyLong_FromUnsignedLong(x); } /* Native mode doesn't support q or Q unless the platform C supports @@ -378,21 +378,21 @@ static PyObject * nu_longlong(const char *p, const formatdef *f) { - PY_LONG_LONG x; - memcpy((char *)&x, p, sizeof x); - if (x >= LONG_MIN && x <= LONG_MAX) - return PyLong_FromLong(Py_SAFE_DOWNCAST(x, PY_LONG_LONG, long)); - return PyLong_FromLongLong(x); + PY_LONG_LONG x; + memcpy((char *)&x, p, sizeof x); + if (x >= LONG_MIN && x <= LONG_MAX) + return PyLong_FromLong(Py_SAFE_DOWNCAST(x, PY_LONG_LONG, long)); + return PyLong_FromLongLong(x); } static PyObject * nu_ulonglong(const char *p, const formatdef *f) { - unsigned PY_LONG_LONG x; - memcpy((char *)&x, p, sizeof x); - if (x <= LONG_MAX) - return PyLong_FromLong(Py_SAFE_DOWNCAST(x, unsigned PY_LONG_LONG, long)); - return PyLong_FromUnsignedLongLong(x); + unsigned PY_LONG_LONG x; + memcpy((char *)&x, p, sizeof x); + if (x <= LONG_MAX) + return PyLong_FromLong(Py_SAFE_DOWNCAST(x, unsigned PY_LONG_LONG, long)); + return PyLong_FromUnsignedLongLong(x); } #endif @@ -400,168 +400,168 @@ static PyObject * nu_bool(const char *p, const formatdef *f) { - BOOL_TYPE x; - memcpy((char *)&x, p, sizeof x); - return PyBool_FromLong(x != 0); + BOOL_TYPE x; + memcpy((char *)&x, p, sizeof x); + return PyBool_FromLong(x != 0); } static PyObject * nu_float(const char *p, const formatdef *f) { - float x; - memcpy((char *)&x, p, sizeof x); - return PyFloat_FromDouble((double)x); + float x; + memcpy((char *)&x, p, sizeof x); + return PyFloat_FromDouble((double)x); } static PyObject * nu_double(const char *p, const formatdef *f) { - double x; - memcpy((char *)&x, p, sizeof x); - return PyFloat_FromDouble(x); + double x; + memcpy((char *)&x, p, sizeof x); + return PyFloat_FromDouble(x); } static PyObject * nu_void_p(const char *p, const formatdef *f) { - void *x; - memcpy((char *)&x, p, sizeof x); - return PyLong_FromVoidPtr(x); + void *x; + memcpy((char *)&x, p, sizeof x); + return PyLong_FromVoidPtr(x); } static int np_byte(char *p, PyObject *v, const formatdef *f) { - long x; - if (get_long(v, &x) < 0) - return -1; - if (x < -128 || x > 127){ - PyErr_SetString(StructError, - "byte format requires -128 <= number <= 127"); - return -1; - } - *p = (char)x; - return 0; + long x; + if (get_long(v, &x) < 0) + return -1; + if (x < -128 || x > 127){ + PyErr_SetString(StructError, + "byte format requires -128 <= number <= 127"); + return -1; + } + *p = (char)x; + return 0; } static int np_ubyte(char *p, PyObject *v, const formatdef *f) { - long x; - if (get_long(v, &x) < 0) - return -1; - if (x < 0 || x > 255){ - PyErr_SetString(StructError, - "ubyte format requires 0 <= number <= 255"); - return -1; - } - *p = (char)x; - return 0; + long x; + if (get_long(v, &x) < 0) + return -1; + if (x < 0 || x > 255){ + PyErr_SetString(StructError, + "ubyte format requires 0 <= number <= 255"); + return -1; + } + *p = (char)x; + return 0; } static int np_char(char *p, PyObject *v, const formatdef *f) { - if (PyUnicode_Check(v)) { - v = _PyUnicode_AsDefaultEncodedString(v, NULL); - if (v == NULL) - return -1; - } - if (!PyBytes_Check(v) || PyBytes_Size(v) != 1) { - PyErr_SetString(StructError, - "char format requires bytes or string of length 1"); - return -1; - } - *p = *PyBytes_AsString(v); - return 0; + if (PyUnicode_Check(v)) { + v = _PyUnicode_AsDefaultEncodedString(v, NULL); + if (v == NULL) + return -1; + } + if (!PyBytes_Check(v) || PyBytes_Size(v) != 1) { + PyErr_SetString(StructError, + "char format requires bytes or string of length 1"); + return -1; + } + *p = *PyBytes_AsString(v); + return 0; } static int np_short(char *p, PyObject *v, const formatdef *f) { - long x; - short y; - if (get_long(v, &x) < 0) - return -1; - if (x < SHRT_MIN || x > SHRT_MAX){ - PyErr_SetString(StructError, - "short format requires " STRINGIFY(SHRT_MIN) - " <= number <= " STRINGIFY(SHRT_MAX)); - return -1; - } - y = (short)x; - memcpy(p, (char *)&y, sizeof y); - return 0; + long x; + short y; + if (get_long(v, &x) < 0) + return -1; + if (x < SHRT_MIN || x > SHRT_MAX){ + PyErr_SetString(StructError, + "short format requires " STRINGIFY(SHRT_MIN) + " <= number <= " STRINGIFY(SHRT_MAX)); + return -1; + } + y = (short)x; + memcpy(p, (char *)&y, sizeof y); + return 0; } static int np_ushort(char *p, PyObject *v, const formatdef *f) { - long x; - unsigned short y; - if (get_long(v, &x) < 0) - return -1; - if (x < 0 || x > USHRT_MAX){ - PyErr_SetString(StructError, - "ushort format requires 0 <= number <= " STRINGIFY(USHRT_MAX)); - return -1; - } - y = (unsigned short)x; - memcpy(p, (char *)&y, sizeof y); - return 0; + long x; + unsigned short y; + if (get_long(v, &x) < 0) + return -1; + if (x < 0 || x > USHRT_MAX){ + PyErr_SetString(StructError, + "ushort format requires 0 <= number <= " STRINGIFY(USHRT_MAX)); + return -1; + } + y = (unsigned short)x; + memcpy(p, (char *)&y, sizeof y); + return 0; } static int np_int(char *p, PyObject *v, const formatdef *f) { - long x; - int y; - if (get_long(v, &x) < 0) - return -1; + long x; + int y; + if (get_long(v, &x) < 0) + return -1; #if (SIZEOF_LONG > SIZEOF_INT) - if ((x < ((long)INT_MIN)) || (x > ((long)INT_MAX))) - RANGE_ERROR(x, f, 0, -1); + if ((x < ((long)INT_MIN)) || (x > ((long)INT_MAX))) + RANGE_ERROR(x, f, 0, -1); #endif - y = (int)x; - memcpy(p, (char *)&y, sizeof y); - return 0; + y = (int)x; + memcpy(p, (char *)&y, sizeof y); + return 0; } static int np_uint(char *p, PyObject *v, const formatdef *f) { - unsigned long x; - unsigned int y; - if (get_ulong(v, &x) < 0) - return -1; - y = (unsigned int)x; + unsigned long x; + unsigned int y; + if (get_ulong(v, &x) < 0) + return -1; + y = (unsigned int)x; #if (SIZEOF_LONG > SIZEOF_INT) - if (x > ((unsigned long)UINT_MAX)) - RANGE_ERROR(y, f, 1, -1); + if (x > ((unsigned long)UINT_MAX)) + RANGE_ERROR(y, f, 1, -1); #endif - memcpy(p, (char *)&y, sizeof y); - return 0; + memcpy(p, (char *)&y, sizeof y); + return 0; } static int np_long(char *p, PyObject *v, const formatdef *f) { - long x; - if (get_long(v, &x) < 0) - return -1; - memcpy(p, (char *)&x, sizeof x); - return 0; + long x; + if (get_long(v, &x) < 0) + return -1; + memcpy(p, (char *)&x, sizeof x); + return 0; } static int np_ulong(char *p, PyObject *v, const formatdef *f) { - unsigned long x; - if (get_ulong(v, &x) < 0) - return -1; - memcpy(p, (char *)&x, sizeof x); - return 0; + unsigned long x; + if (get_ulong(v, &x) < 0) + return -1; + memcpy(p, (char *)&x, sizeof x); + return 0; } #ifdef HAVE_LONG_LONG @@ -569,21 +569,21 @@ static int np_longlong(char *p, PyObject *v, const formatdef *f) { - PY_LONG_LONG x; - if (get_longlong(v, &x) < 0) - return -1; - memcpy(p, (char *)&x, sizeof x); - return 0; + PY_LONG_LONG x; + if (get_longlong(v, &x) < 0) + return -1; + memcpy(p, (char *)&x, sizeof x); + return 0; } static int np_ulonglong(char *p, PyObject *v, const formatdef *f) { - unsigned PY_LONG_LONG x; - if (get_ulonglong(v, &x) < 0) - return -1; - memcpy(p, (char *)&x, sizeof x); - return 0; + unsigned PY_LONG_LONG x; + if (get_ulonglong(v, &x) < 0) + return -1; + memcpy(p, (char *)&x, sizeof x); + return 0; } #endif @@ -591,77 +591,77 @@ static int np_bool(char *p, PyObject *v, const formatdef *f) { - BOOL_TYPE y; - y = PyObject_IsTrue(v); - memcpy(p, (char *)&y, sizeof y); - return 0; + BOOL_TYPE y; + y = PyObject_IsTrue(v); + memcpy(p, (char *)&y, sizeof y); + return 0; } static int np_float(char *p, PyObject *v, const formatdef *f) { - float x = (float)PyFloat_AsDouble(v); - if (x == -1 && PyErr_Occurred()) { - PyErr_SetString(StructError, - "required argument is not a float"); - return -1; - } - memcpy(p, (char *)&x, sizeof x); - return 0; + float x = (float)PyFloat_AsDouble(v); + if (x == -1 && PyErr_Occurred()) { + PyErr_SetString(StructError, + "required argument is not a float"); + return -1; + } + memcpy(p, (char *)&x, sizeof x); + return 0; } static int np_double(char *p, PyObject *v, const formatdef *f) { - double x = PyFloat_AsDouble(v); - if (x == -1 && PyErr_Occurred()) { - PyErr_SetString(StructError, - "required argument is not a float"); - return -1; - } - memcpy(p, (char *)&x, sizeof(double)); - return 0; + double x = PyFloat_AsDouble(v); + if (x == -1 && PyErr_Occurred()) { + PyErr_SetString(StructError, + "required argument is not a float"); + return -1; + } + memcpy(p, (char *)&x, sizeof(double)); + return 0; } static int np_void_p(char *p, PyObject *v, const formatdef *f) { - void *x; + void *x; - v = get_pylong(v); - if (v == NULL) - return -1; - assert(PyLong_Check(v)); - x = PyLong_AsVoidPtr(v); - Py_DECREF(v); - if (x == NULL && PyErr_Occurred()) - return -1; - memcpy(p, (char *)&x, sizeof x); - return 0; + v = get_pylong(v); + if (v == NULL) + return -1; + assert(PyLong_Check(v)); + x = PyLong_AsVoidPtr(v); + Py_DECREF(v); + if (x == NULL && PyErr_Occurred()) + return -1; + memcpy(p, (char *)&x, sizeof x); + return 0; } static formatdef native_table[] = { - {'x', sizeof(char), 0, NULL}, - {'b', sizeof(char), 0, nu_byte, np_byte}, - {'B', sizeof(char), 0, nu_ubyte, np_ubyte}, - {'c', sizeof(char), 0, nu_char, np_char}, - {'s', sizeof(char), 0, NULL}, - {'p', sizeof(char), 0, NULL}, - {'h', sizeof(short), SHORT_ALIGN, nu_short, np_short}, - {'H', sizeof(short), SHORT_ALIGN, nu_ushort, np_ushort}, - {'i', sizeof(int), INT_ALIGN, nu_int, np_int}, - {'I', sizeof(int), INT_ALIGN, nu_uint, np_uint}, - {'l', sizeof(long), LONG_ALIGN, nu_long, np_long}, - {'L', sizeof(long), LONG_ALIGN, nu_ulong, np_ulong}, + {'x', sizeof(char), 0, NULL}, + {'b', sizeof(char), 0, nu_byte, np_byte}, + {'B', sizeof(char), 0, nu_ubyte, np_ubyte}, + {'c', sizeof(char), 0, nu_char, np_char}, + {'s', sizeof(char), 0, NULL}, + {'p', sizeof(char), 0, NULL}, + {'h', sizeof(short), SHORT_ALIGN, nu_short, np_short}, + {'H', sizeof(short), SHORT_ALIGN, nu_ushort, np_ushort}, + {'i', sizeof(int), INT_ALIGN, nu_int, np_int}, + {'I', sizeof(int), INT_ALIGN, nu_uint, np_uint}, + {'l', sizeof(long), LONG_ALIGN, nu_long, np_long}, + {'L', sizeof(long), LONG_ALIGN, nu_ulong, np_ulong}, #ifdef HAVE_LONG_LONG - {'q', sizeof(PY_LONG_LONG), LONG_LONG_ALIGN, nu_longlong, np_longlong}, - {'Q', sizeof(PY_LONG_LONG), LONG_LONG_ALIGN, nu_ulonglong,np_ulonglong}, + {'q', sizeof(PY_LONG_LONG), LONG_LONG_ALIGN, nu_longlong, np_longlong}, + {'Q', sizeof(PY_LONG_LONG), LONG_LONG_ALIGN, nu_ulonglong,np_ulonglong}, #endif - {'?', sizeof(BOOL_TYPE), BOOL_ALIGN, nu_bool, np_bool}, - {'f', sizeof(float), FLOAT_ALIGN, nu_float, np_float}, - {'d', sizeof(double), DOUBLE_ALIGN, nu_double, np_double}, - {'P', sizeof(void *), VOID_P_ALIGN, nu_void_p, np_void_p}, - {0} + {'?', sizeof(BOOL_TYPE), BOOL_ALIGN, nu_bool, np_bool}, + {'f', sizeof(float), FLOAT_ALIGN, nu_float, np_float}, + {'d', sizeof(double), DOUBLE_ALIGN, nu_double, np_double}, + {'P', sizeof(void *), VOID_P_ALIGN, nu_void_p, np_void_p}, + {0} }; /* Big-endian routines. *****************************************************/ @@ -669,53 +669,53 @@ static PyObject * bu_int(const char *p, const formatdef *f) { - long x = 0; - Py_ssize_t i = f->size; - const unsigned char *bytes = (const unsigned char *)p; - do { - x = (x<<8) | *bytes++; - } while (--i > 0); - /* Extend the sign bit. */ - if (SIZEOF_LONG > f->size) - x |= -(x & (1L << ((8 * f->size) - 1))); - return PyLong_FromLong(x); + long x = 0; + Py_ssize_t i = f->size; + const unsigned char *bytes = (const unsigned char *)p; + do { + x = (x<<8) | *bytes++; + } while (--i > 0); + /* Extend the sign bit. */ + if (SIZEOF_LONG > f->size) + x |= -(x & (1L << ((8 * f->size) - 1))); + return PyLong_FromLong(x); } static PyObject * bu_uint(const char *p, const formatdef *f) { - unsigned long x = 0; - Py_ssize_t i = f->size; - const unsigned char *bytes = (const unsigned char *)p; - do { - x = (x<<8) | *bytes++; - } while (--i > 0); - if (x <= LONG_MAX) - return PyLong_FromLong((long)x); - return PyLong_FromUnsignedLong(x); + unsigned long x = 0; + Py_ssize_t i = f->size; + const unsigned char *bytes = (const unsigned char *)p; + do { + x = (x<<8) | *bytes++; + } while (--i > 0); + if (x <= LONG_MAX) + return PyLong_FromLong((long)x); + return PyLong_FromUnsignedLong(x); } static PyObject * bu_longlong(const char *p, const formatdef *f) { #ifdef HAVE_LONG_LONG - PY_LONG_LONG x = 0; - Py_ssize_t i = f->size; - const unsigned char *bytes = (const unsigned char *)p; - do { - x = (x<<8) | *bytes++; - } while (--i > 0); - /* Extend the sign bit. */ - if (SIZEOF_LONG_LONG > f->size) - x |= -(x & ((PY_LONG_LONG)1 << ((8 * f->size) - 1))); - if (x >= LONG_MIN && x <= LONG_MAX) - return PyLong_FromLong(Py_SAFE_DOWNCAST(x, PY_LONG_LONG, long)); - return PyLong_FromLongLong(x); + PY_LONG_LONG x = 0; + Py_ssize_t i = f->size; + const unsigned char *bytes = (const unsigned char *)p; + do { + x = (x<<8) | *bytes++; + } while (--i > 0); + /* Extend the sign bit. */ + if (SIZEOF_LONG_LONG > f->size) + x |= -(x & ((PY_LONG_LONG)1 << ((8 * f->size) - 1))); + if (x >= LONG_MIN && x <= LONG_MAX) + return PyLong_FromLong(Py_SAFE_DOWNCAST(x, PY_LONG_LONG, long)); + return PyLong_FromLongLong(x); #else - return _PyLong_FromByteArray((const unsigned char *)p, - 8, - 0, /* little-endian */ - 1 /* signed */); + return _PyLong_FromByteArray((const unsigned char *)p, + 8, + 0, /* little-endian */ + 1 /* signed */); #endif } @@ -723,171 +723,171 @@ bu_ulonglong(const char *p, const formatdef *f) { #ifdef HAVE_LONG_LONG - unsigned PY_LONG_LONG x = 0; - Py_ssize_t i = f->size; - const unsigned char *bytes = (const unsigned char *)p; - do { - x = (x<<8) | *bytes++; - } while (--i > 0); - if (x <= LONG_MAX) - return PyLong_FromLong(Py_SAFE_DOWNCAST(x, unsigned PY_LONG_LONG, long)); - return PyLong_FromUnsignedLongLong(x); + unsigned PY_LONG_LONG x = 0; + Py_ssize_t i = f->size; + const unsigned char *bytes = (const unsigned char *)p; + do { + x = (x<<8) | *bytes++; + } while (--i > 0); + if (x <= LONG_MAX) + return PyLong_FromLong(Py_SAFE_DOWNCAST(x, unsigned PY_LONG_LONG, long)); + return PyLong_FromUnsignedLongLong(x); #else - return _PyLong_FromByteArray((const unsigned char *)p, - 8, - 0, /* little-endian */ - 0 /* signed */); + return _PyLong_FromByteArray((const unsigned char *)p, + 8, + 0, /* little-endian */ + 0 /* signed */); #endif } static PyObject * bu_float(const char *p, const formatdef *f) { - return unpack_float(p, 0); + return unpack_float(p, 0); } static PyObject * bu_double(const char *p, const formatdef *f) { - return unpack_double(p, 0); + return unpack_double(p, 0); } static PyObject * bu_bool(const char *p, const formatdef *f) { - char x; - memcpy((char *)&x, p, sizeof x); - return PyBool_FromLong(x != 0); + char x; + memcpy((char *)&x, p, sizeof x); + return PyBool_FromLong(x != 0); } static int bp_int(char *p, PyObject *v, const formatdef *f) { - long x; - Py_ssize_t i; - if (get_long(v, &x) < 0) - return -1; - i = f->size; - if (i != SIZEOF_LONG) { - if ((i == 2) && (x < -32768 || x > 32767)) - RANGE_ERROR(x, f, 0, 0xffffL); + long x; + Py_ssize_t i; + if (get_long(v, &x) < 0) + return -1; + i = f->size; + if (i != SIZEOF_LONG) { + if ((i == 2) && (x < -32768 || x > 32767)) + RANGE_ERROR(x, f, 0, 0xffffL); #if (SIZEOF_LONG != 4) - else if ((i == 4) && (x < -2147483648L || x > 2147483647L)) - RANGE_ERROR(x, f, 0, 0xffffffffL); + else if ((i == 4) && (x < -2147483648L || x > 2147483647L)) + RANGE_ERROR(x, f, 0, 0xffffffffL); #endif - } - do { - p[--i] = (char)x; - x >>= 8; - } while (i > 0); - return 0; + } + do { + p[--i] = (char)x; + x >>= 8; + } while (i > 0); + return 0; } static int bp_uint(char *p, PyObject *v, const formatdef *f) { - unsigned long x; - Py_ssize_t i; - if (get_ulong(v, &x) < 0) - return -1; - i = f->size; - if (i != SIZEOF_LONG) { - unsigned long maxint = 1; - maxint <<= (unsigned long)(i * 8); - if (x >= maxint) - RANGE_ERROR(x, f, 1, maxint - 1); - } - do { - p[--i] = (char)x; - x >>= 8; - } while (i > 0); - return 0; + unsigned long x; + Py_ssize_t i; + if (get_ulong(v, &x) < 0) + return -1; + i = f->size; + if (i != SIZEOF_LONG) { + unsigned long maxint = 1; + maxint <<= (unsigned long)(i * 8); + if (x >= maxint) + RANGE_ERROR(x, f, 1, maxint - 1); + } + do { + p[--i] = (char)x; + x >>= 8; + } while (i > 0); + return 0; } static int bp_longlong(char *p, PyObject *v, const formatdef *f) { - int res; - v = get_pylong(v); - if (v == NULL) - return -1; - res = _PyLong_AsByteArray((PyLongObject *)v, - (unsigned char *)p, - 8, - 0, /* little_endian */ - 1 /* signed */); - Py_DECREF(v); - return res; + int res; + v = get_pylong(v); + if (v == NULL) + return -1; + res = _PyLong_AsByteArray((PyLongObject *)v, + (unsigned char *)p, + 8, + 0, /* little_endian */ + 1 /* signed */); + Py_DECREF(v); + return res; } static int bp_ulonglong(char *p, PyObject *v, const formatdef *f) { - int res; - v = get_pylong(v); - if (v == NULL) - return -1; - res = _PyLong_AsByteArray((PyLongObject *)v, - (unsigned char *)p, - 8, - 0, /* little_endian */ - 0 /* signed */); - Py_DECREF(v); - return res; + int res; + v = get_pylong(v); + if (v == NULL) + return -1; + res = _PyLong_AsByteArray((PyLongObject *)v, + (unsigned char *)p, + 8, + 0, /* little_endian */ + 0 /* signed */); + Py_DECREF(v); + return res; } static int bp_float(char *p, PyObject *v, const formatdef *f) { - double x = PyFloat_AsDouble(v); - if (x == -1 && PyErr_Occurred()) { - PyErr_SetString(StructError, - "required argument is not a float"); - return -1; - } - return _PyFloat_Pack4(x, (unsigned char *)p, 0); + double x = PyFloat_AsDouble(v); + if (x == -1 && PyErr_Occurred()) { + PyErr_SetString(StructError, + "required argument is not a float"); + return -1; + } + return _PyFloat_Pack4(x, (unsigned char *)p, 0); } static int bp_double(char *p, PyObject *v, const formatdef *f) { - double x = PyFloat_AsDouble(v); - if (x == -1 && PyErr_Occurred()) { - PyErr_SetString(StructError, - "required argument is not a float"); - return -1; - } - return _PyFloat_Pack8(x, (unsigned char *)p, 0); + double x = PyFloat_AsDouble(v); + if (x == -1 && PyErr_Occurred()) { + PyErr_SetString(StructError, + "required argument is not a float"); + return -1; + } + return _PyFloat_Pack8(x, (unsigned char *)p, 0); } static int bp_bool(char *p, PyObject *v, const formatdef *f) { - char y; - y = PyObject_IsTrue(v); - memcpy(p, (char *)&y, sizeof y); - return 0; + char y; + y = PyObject_IsTrue(v); + memcpy(p, (char *)&y, sizeof y); + return 0; } static formatdef bigendian_table[] = { - {'x', 1, 0, NULL}, - {'b', 1, 0, nu_byte, np_byte}, - {'B', 1, 0, nu_ubyte, np_ubyte}, - {'c', 1, 0, nu_char, np_char}, - {'s', 1, 0, NULL}, - {'p', 1, 0, NULL}, - {'h', 2, 0, bu_int, bp_int}, - {'H', 2, 0, bu_uint, bp_uint}, - {'i', 4, 0, bu_int, bp_int}, - {'I', 4, 0, bu_uint, bp_uint}, - {'l', 4, 0, bu_int, bp_int}, - {'L', 4, 0, bu_uint, bp_uint}, - {'q', 8, 0, bu_longlong, bp_longlong}, - {'Q', 8, 0, bu_ulonglong, bp_ulonglong}, - {'?', 1, 0, bu_bool, bp_bool}, - {'f', 4, 0, bu_float, bp_float}, - {'d', 8, 0, bu_double, bp_double}, - {0} + {'x', 1, 0, NULL}, + {'b', 1, 0, nu_byte, np_byte}, + {'B', 1, 0, nu_ubyte, np_ubyte}, + {'c', 1, 0, nu_char, np_char}, + {'s', 1, 0, NULL}, + {'p', 1, 0, NULL}, + {'h', 2, 0, bu_int, bp_int}, + {'H', 2, 0, bu_uint, bp_uint}, + {'i', 4, 0, bu_int, bp_int}, + {'I', 4, 0, bu_uint, bp_uint}, + {'l', 4, 0, bu_int, bp_int}, + {'L', 4, 0, bu_uint, bp_uint}, + {'q', 8, 0, bu_longlong, bp_longlong}, + {'Q', 8, 0, bu_ulonglong, bp_ulonglong}, + {'?', 1, 0, bu_bool, bp_bool}, + {'f', 4, 0, bu_float, bp_float}, + {'d', 8, 0, bu_double, bp_double}, + {0} }; /* Little-endian routines. *****************************************************/ @@ -895,53 +895,53 @@ static PyObject * lu_int(const char *p, const formatdef *f) { - long x = 0; - Py_ssize_t i = f->size; - const unsigned char *bytes = (const unsigned char *)p; - do { - x = (x<<8) | bytes[--i]; - } while (i > 0); - /* Extend the sign bit. */ - if (SIZEOF_LONG > f->size) - x |= -(x & (1L << ((8 * f->size) - 1))); - return PyLong_FromLong(x); + long x = 0; + Py_ssize_t i = f->size; + const unsigned char *bytes = (const unsigned char *)p; + do { + x = (x<<8) | bytes[--i]; + } while (i > 0); + /* Extend the sign bit. */ + if (SIZEOF_LONG > f->size) + x |= -(x & (1L << ((8 * f->size) - 1))); + return PyLong_FromLong(x); } static PyObject * lu_uint(const char *p, const formatdef *f) { - unsigned long x = 0; - Py_ssize_t i = f->size; - const unsigned char *bytes = (const unsigned char *)p; - do { - x = (x<<8) | bytes[--i]; - } while (i > 0); - if (x <= LONG_MAX) - return PyLong_FromLong((long)x); - return PyLong_FromUnsignedLong((long)x); + unsigned long x = 0; + Py_ssize_t i = f->size; + const unsigned char *bytes = (const unsigned char *)p; + do { + x = (x<<8) | bytes[--i]; + } while (i > 0); + if (x <= LONG_MAX) + return PyLong_FromLong((long)x); + return PyLong_FromUnsignedLong((long)x); } static PyObject * lu_longlong(const char *p, const formatdef *f) { #ifdef HAVE_LONG_LONG - PY_LONG_LONG x = 0; - Py_ssize_t i = f->size; - const unsigned char *bytes = (const unsigned char *)p; - do { - x = (x<<8) | bytes[--i]; - } while (i > 0); - /* Extend the sign bit. */ - if (SIZEOF_LONG_LONG > f->size) - x |= -(x & ((PY_LONG_LONG)1 << ((8 * f->size) - 1))); - if (x >= LONG_MIN && x <= LONG_MAX) - return PyLong_FromLong(Py_SAFE_DOWNCAST(x, PY_LONG_LONG, long)); - return PyLong_FromLongLong(x); + PY_LONG_LONG x = 0; + Py_ssize_t i = f->size; + const unsigned char *bytes = (const unsigned char *)p; + do { + x = (x<<8) | bytes[--i]; + } while (i > 0); + /* Extend the sign bit. */ + if (SIZEOF_LONG_LONG > f->size) + x |= -(x & ((PY_LONG_LONG)1 << ((8 * f->size) - 1))); + if (x >= LONG_MIN && x <= LONG_MAX) + return PyLong_FromLong(Py_SAFE_DOWNCAST(x, PY_LONG_LONG, long)); + return PyLong_FromLongLong(x); #else - return _PyLong_FromByteArray((const unsigned char *)p, - 8, - 1, /* little-endian */ - 1 /* signed */); + return _PyLong_FromByteArray((const unsigned char *)p, + 8, + 1, /* little-endian */ + 1 /* signed */); #endif } @@ -949,182 +949,182 @@ lu_ulonglong(const char *p, const formatdef *f) { #ifdef HAVE_LONG_LONG - unsigned PY_LONG_LONG x = 0; - Py_ssize_t i = f->size; - const unsigned char *bytes = (const unsigned char *)p; - do { - x = (x<<8) | bytes[--i]; - } while (i > 0); - if (x <= LONG_MAX) - return PyLong_FromLong(Py_SAFE_DOWNCAST(x, unsigned PY_LONG_LONG, long)); - return PyLong_FromUnsignedLongLong(x); + unsigned PY_LONG_LONG x = 0; + Py_ssize_t i = f->size; + const unsigned char *bytes = (const unsigned char *)p; + do { + x = (x<<8) | bytes[--i]; + } while (i > 0); + if (x <= LONG_MAX) + return PyLong_FromLong(Py_SAFE_DOWNCAST(x, unsigned PY_LONG_LONG, long)); + return PyLong_FromUnsignedLongLong(x); #else - return _PyLong_FromByteArray((const unsigned char *)p, - 8, - 1, /* little-endian */ - 0 /* signed */); + return _PyLong_FromByteArray((const unsigned char *)p, + 8, + 1, /* little-endian */ + 0 /* signed */); #endif } static PyObject * lu_float(const char *p, const formatdef *f) { - return unpack_float(p, 1); + return unpack_float(p, 1); } static PyObject * lu_double(const char *p, const formatdef *f) { - return unpack_double(p, 1); + return unpack_double(p, 1); } static int lp_int(char *p, PyObject *v, const formatdef *f) { - long x; - Py_ssize_t i; - if (get_long(v, &x) < 0) - return -1; - i = f->size; - if (i != SIZEOF_LONG) { - if ((i == 2) && (x < -32768 || x > 32767)) - RANGE_ERROR(x, f, 0, 0xffffL); + long x; + Py_ssize_t i; + if (get_long(v, &x) < 0) + return -1; + i = f->size; + if (i != SIZEOF_LONG) { + if ((i == 2) && (x < -32768 || x > 32767)) + RANGE_ERROR(x, f, 0, 0xffffL); #if (SIZEOF_LONG != 4) - else if ((i == 4) && (x < -2147483648L || x > 2147483647L)) - RANGE_ERROR(x, f, 0, 0xffffffffL); + else if ((i == 4) && (x < -2147483648L || x > 2147483647L)) + RANGE_ERROR(x, f, 0, 0xffffffffL); #endif - } - do { - *p++ = (char)x; - x >>= 8; - } while (--i > 0); - return 0; + } + do { + *p++ = (char)x; + x >>= 8; + } while (--i > 0); + return 0; } static int lp_uint(char *p, PyObject *v, const formatdef *f) { - unsigned long x; - Py_ssize_t i; - if (get_ulong(v, &x) < 0) - return -1; - i = f->size; - if (i != SIZEOF_LONG) { - unsigned long maxint = 1; - maxint <<= (unsigned long)(i * 8); - if (x >= maxint) - RANGE_ERROR(x, f, 1, maxint - 1); - } - do { - *p++ = (char)x; - x >>= 8; - } while (--i > 0); - return 0; + unsigned long x; + Py_ssize_t i; + if (get_ulong(v, &x) < 0) + return -1; + i = f->size; + if (i != SIZEOF_LONG) { + unsigned long maxint = 1; + maxint <<= (unsigned long)(i * 8); + if (x >= maxint) + RANGE_ERROR(x, f, 1, maxint - 1); + } + do { + *p++ = (char)x; + x >>= 8; + } while (--i > 0); + return 0; } static int lp_longlong(char *p, PyObject *v, const formatdef *f) { - int res; - v = get_pylong(v); - if (v == NULL) - return -1; - res = _PyLong_AsByteArray((PyLongObject*)v, - (unsigned char *)p, - 8, - 1, /* little_endian */ - 1 /* signed */); - Py_DECREF(v); - return res; + int res; + v = get_pylong(v); + if (v == NULL) + return -1; + res = _PyLong_AsByteArray((PyLongObject*)v, + (unsigned char *)p, + 8, + 1, /* little_endian */ + 1 /* signed */); + Py_DECREF(v); + return res; } static int lp_ulonglong(char *p, PyObject *v, const formatdef *f) { - int res; - v = get_pylong(v); - if (v == NULL) - return -1; - res = _PyLong_AsByteArray((PyLongObject*)v, - (unsigned char *)p, - 8, - 1, /* little_endian */ - 0 /* signed */); - Py_DECREF(v); - return res; + int res; + v = get_pylong(v); + if (v == NULL) + return -1; + res = _PyLong_AsByteArray((PyLongObject*)v, + (unsigned char *)p, + 8, + 1, /* little_endian */ + 0 /* signed */); + Py_DECREF(v); + return res; } static int lp_float(char *p, PyObject *v, const formatdef *f) { - double x = PyFloat_AsDouble(v); - if (x == -1 && PyErr_Occurred()) { - PyErr_SetString(StructError, - "required argument is not a float"); - return -1; - } - return _PyFloat_Pack4(x, (unsigned char *)p, 1); + double x = PyFloat_AsDouble(v); + if (x == -1 && PyErr_Occurred()) { + PyErr_SetString(StructError, + "required argument is not a float"); + return -1; + } + return _PyFloat_Pack4(x, (unsigned char *)p, 1); } static int lp_double(char *p, PyObject *v, const formatdef *f) { - double x = PyFloat_AsDouble(v); - if (x == -1 && PyErr_Occurred()) { - PyErr_SetString(StructError, - "required argument is not a float"); - return -1; - } - return _PyFloat_Pack8(x, (unsigned char *)p, 1); + double x = PyFloat_AsDouble(v); + if (x == -1 && PyErr_Occurred()) { + PyErr_SetString(StructError, + "required argument is not a float"); + return -1; + } + return _PyFloat_Pack8(x, (unsigned char *)p, 1); } static formatdef lilendian_table[] = { - {'x', 1, 0, NULL}, - {'b', 1, 0, nu_byte, np_byte}, - {'B', 1, 0, nu_ubyte, np_ubyte}, - {'c', 1, 0, nu_char, np_char}, - {'s', 1, 0, NULL}, - {'p', 1, 0, NULL}, - {'h', 2, 0, lu_int, lp_int}, - {'H', 2, 0, lu_uint, lp_uint}, - {'i', 4, 0, lu_int, lp_int}, - {'I', 4, 0, lu_uint, lp_uint}, - {'l', 4, 0, lu_int, lp_int}, - {'L', 4, 0, lu_uint, lp_uint}, - {'q', 8, 0, lu_longlong, lp_longlong}, - {'Q', 8, 0, lu_ulonglong, lp_ulonglong}, - {'?', 1, 0, bu_bool, bp_bool}, /* Std rep not endian dep, - but potentially different from native rep -- reuse bx_bool funcs. */ - {'f', 4, 0, lu_float, lp_float}, - {'d', 8, 0, lu_double, lp_double}, - {0} + {'x', 1, 0, NULL}, + {'b', 1, 0, nu_byte, np_byte}, + {'B', 1, 0, nu_ubyte, np_ubyte}, + {'c', 1, 0, nu_char, np_char}, + {'s', 1, 0, NULL}, + {'p', 1, 0, NULL}, + {'h', 2, 0, lu_int, lp_int}, + {'H', 2, 0, lu_uint, lp_uint}, + {'i', 4, 0, lu_int, lp_int}, + {'I', 4, 0, lu_uint, lp_uint}, + {'l', 4, 0, lu_int, lp_int}, + {'L', 4, 0, lu_uint, lp_uint}, + {'q', 8, 0, lu_longlong, lp_longlong}, + {'Q', 8, 0, lu_ulonglong, lp_ulonglong}, + {'?', 1, 0, bu_bool, bp_bool}, /* Std rep not endian dep, + but potentially different from native rep -- reuse bx_bool funcs. */ + {'f', 4, 0, lu_float, lp_float}, + {'d', 8, 0, lu_double, lp_double}, + {0} }; static const formatdef * whichtable(char **pfmt) { - const char *fmt = (*pfmt)++; /* May be backed out of later */ - switch (*fmt) { - case '<': - return lilendian_table; - case '>': - case '!': /* Network byte order is big-endian */ - return bigendian_table; - case '=': { /* Host byte order -- different from native in aligment! */ - int n = 1; - char *p = (char *) &n; - if (*p == 1) - return lilendian_table; - else - return bigendian_table; - } - default: - --*pfmt; /* Back out of pointer increment */ - /* Fall through */ - case '@': - return native_table; - } + const char *fmt = (*pfmt)++; /* May be backed out of later */ + switch (*fmt) { + case '<': + return lilendian_table; + case '>': + case '!': /* Network byte order is big-endian */ + return bigendian_table; + case '=': { /* Host byte order -- different from native in aligment! */ + int n = 1; + char *p = (char *) &n; + if (*p == 1) + return lilendian_table; + else + return bigendian_table; + } + default: + --*pfmt; /* Back out of pointer increment */ + /* Fall through */ + case '@': + return native_table; + } } @@ -1133,13 +1133,13 @@ static const formatdef * getentry(int c, const formatdef *f) { - for (; f->format != '\0'; f++) { - if (f->format == c) { - return f; - } - } - PyErr_SetString(StructError, "bad char in struct format"); - return NULL; + for (; f->format != '\0'; f++) { + if (f->format == c) { + return f; + } + } + PyErr_SetString(StructError, "bad char in struct format"); + return NULL; } @@ -1148,14 +1148,14 @@ static int align(Py_ssize_t size, char c, const formatdef *e) { - if (e->format == c) { - if (e->alignment) { - size = ((size + e->alignment - 1) - / e->alignment) - * e->alignment; - } - } - return size; + if (e->format == c) { + if (e->alignment) { + size = ((size + e->alignment - 1) + / e->alignment) + * e->alignment; + } + } + return size; } @@ -1164,224 +1164,224 @@ static int prepare_s(PyStructObject *self) { - const formatdef *f; - const formatdef *e; - formatcode *codes; - - const char *s; - const char *fmt; - char c; - Py_ssize_t size, len, num, itemsize, x; - - fmt = PyBytes_AS_STRING(self->s_format); - - f = whichtable((char **)&fmt); - - s = fmt; - size = 0; - len = 0; - while ((c = *s++) != '\0') { - if (isspace(Py_CHARMASK(c))) - continue; - if ('0' <= c && c <= '9') { - num = c - '0'; - while ('0' <= (c = *s++) && c <= '9') { - x = num*10 + (c - '0'); - if (x/10 != num) { - PyErr_SetString( - StructError, - "overflow in item count"); - return -1; - } - num = x; - } - if (c == '\0') - break; - } - else - num = 1; - - e = getentry(c, f); - if (e == NULL) - return -1; - - switch (c) { - case 's': /* fall through */ - case 'p': len++; break; - case 'x': break; - default: len += num; break; - } - - itemsize = e->size; - size = align(size, c, e); - x = num * itemsize; - size += x; - if (x/itemsize != num || size < 0) { - PyErr_SetString(StructError, - "total struct size too long"); - return -1; - } - } - - /* check for overflow */ - if ((len + 1) > (PY_SSIZE_T_MAX / sizeof(formatcode))) { - PyErr_NoMemory(); - return -1; - } - - self->s_size = size; - self->s_len = len; - codes = PyMem_MALLOC((len + 1) * sizeof(formatcode)); - if (codes == NULL) { - PyErr_NoMemory(); - return -1; - } - self->s_codes = codes; - - s = fmt; - size = 0; - while ((c = *s++) != '\0') { - if (isspace(Py_CHARMASK(c))) - continue; - if ('0' <= c && c <= '9') { - num = c - '0'; - while ('0' <= (c = *s++) && c <= '9') - num = num*10 + (c - '0'); - if (c == '\0') - break; - } - else - num = 1; - - e = getentry(c, f); - - size = align(size, c, e); - if (c == 's' || c == 'p') { - codes->offset = size; - codes->size = num; - codes->fmtdef = e; - codes++; - size += num; - } else if (c == 'x') { - size += num; - } else { - while (--num >= 0) { - codes->offset = size; - codes->size = e->size; - codes->fmtdef = e; - codes++; - size += e->size; - } - } - } - codes->fmtdef = NULL; - codes->offset = size; - codes->size = 0; + const formatdef *f; + const formatdef *e; + formatcode *codes; + + const char *s; + const char *fmt; + char c; + Py_ssize_t size, len, num, itemsize, x; + + fmt = PyBytes_AS_STRING(self->s_format); + + f = whichtable((char **)&fmt); + + s = fmt; + size = 0; + len = 0; + while ((c = *s++) != '\0') { + if (isspace(Py_CHARMASK(c))) + continue; + if ('0' <= c && c <= '9') { + num = c - '0'; + while ('0' <= (c = *s++) && c <= '9') { + x = num*10 + (c - '0'); + if (x/10 != num) { + PyErr_SetString( + StructError, + "overflow in item count"); + return -1; + } + num = x; + } + if (c == '\0') + break; + } + else + num = 1; + + e = getentry(c, f); + if (e == NULL) + return -1; + + switch (c) { + case 's': /* fall through */ + case 'p': len++; break; + case 'x': break; + default: len += num; break; + } + + itemsize = e->size; + size = align(size, c, e); + x = num * itemsize; + size += x; + if (x/itemsize != num || size < 0) { + PyErr_SetString(StructError, + "total struct size too long"); + return -1; + } + } + + /* check for overflow */ + if ((len + 1) > (PY_SSIZE_T_MAX / sizeof(formatcode))) { + PyErr_NoMemory(); + return -1; + } + + self->s_size = size; + self->s_len = len; + codes = PyMem_MALLOC((len + 1) * sizeof(formatcode)); + if (codes == NULL) { + PyErr_NoMemory(); + return -1; + } + self->s_codes = codes; + + s = fmt; + size = 0; + while ((c = *s++) != '\0') { + if (isspace(Py_CHARMASK(c))) + continue; + if ('0' <= c && c <= '9') { + num = c - '0'; + while ('0' <= (c = *s++) && c <= '9') + num = num*10 + (c - '0'); + if (c == '\0') + break; + } + else + num = 1; + + e = getentry(c, f); + + size = align(size, c, e); + if (c == 's' || c == 'p') { + codes->offset = size; + codes->size = num; + codes->fmtdef = e; + codes++; + size += num; + } else if (c == 'x') { + size += num; + } else { + while (--num >= 0) { + codes->offset = size; + codes->size = e->size; + codes->fmtdef = e; + codes++; + size += e->size; + } + } + } + codes->fmtdef = NULL; + codes->offset = size; + codes->size = 0; - return 0; + return 0; } static PyObject * s_new(PyTypeObject *type, PyObject *args, PyObject *kwds) { - PyObject *self; + PyObject *self; - assert(type != NULL && type->tp_alloc != NULL); + assert(type != NULL && type->tp_alloc != NULL); - self = type->tp_alloc(type, 0); - if (self != NULL) { - PyStructObject *s = (PyStructObject*)self; - Py_INCREF(Py_None); - s->s_format = Py_None; - s->s_codes = NULL; - s->s_size = -1; - s->s_len = -1; - } - return self; + self = type->tp_alloc(type, 0); + if (self != NULL) { + PyStructObject *s = (PyStructObject*)self; + Py_INCREF(Py_None); + s->s_format = Py_None; + s->s_codes = NULL; + s->s_size = -1; + s->s_len = -1; + } + return self; } static int s_init(PyObject *self, PyObject *args, PyObject *kwds) { - PyStructObject *soself = (PyStructObject *)self; - PyObject *o_format = NULL; - int ret = 0; - static char *kwlist[] = {"format", 0}; - - assert(PyStruct_Check(self)); - - if (!PyArg_ParseTupleAndKeywords(args, kwds, "O:Struct", kwlist, - &o_format)) - return -1; - - if (PyUnicode_Check(o_format)) { - o_format = PyUnicode_AsASCIIString(o_format); - if (o_format == NULL) - return -1; - } - /* XXX support buffer interface, too */ - else { - Py_INCREF(o_format); - } - - if (!PyBytes_Check(o_format)) { - Py_DECREF(o_format); - PyErr_Format(PyExc_TypeError, - "Struct() argument 1 must be bytes, not %.200s", - Py_TYPE(o_format)->tp_name); - return -1; - } + PyStructObject *soself = (PyStructObject *)self; + PyObject *o_format = NULL; + int ret = 0; + static char *kwlist[] = {"format", 0}; + + assert(PyStruct_Check(self)); + + if (!PyArg_ParseTupleAndKeywords(args, kwds, "O:Struct", kwlist, + &o_format)) + return -1; + + if (PyUnicode_Check(o_format)) { + o_format = PyUnicode_AsASCIIString(o_format); + if (o_format == NULL) + return -1; + } + /* XXX support buffer interface, too */ + else { + Py_INCREF(o_format); + } + + if (!PyBytes_Check(o_format)) { + Py_DECREF(o_format); + PyErr_Format(PyExc_TypeError, + "Struct() argument 1 must be bytes, not %.200s", + Py_TYPE(o_format)->tp_name); + return -1; + } - Py_CLEAR(soself->s_format); - soself->s_format = o_format; + Py_CLEAR(soself->s_format); + soself->s_format = o_format; - ret = prepare_s(soself); - return ret; + ret = prepare_s(soself); + return ret; } static void s_dealloc(PyStructObject *s) { - if (s->weakreflist != NULL) - PyObject_ClearWeakRefs((PyObject *)s); - if (s->s_codes != NULL) { - PyMem_FREE(s->s_codes); - } - Py_XDECREF(s->s_format); - Py_TYPE(s)->tp_free((PyObject *)s); + if (s->weakreflist != NULL) + PyObject_ClearWeakRefs((PyObject *)s); + if (s->s_codes != NULL) { + PyMem_FREE(s->s_codes); + } + Py_XDECREF(s->s_format); + Py_TYPE(s)->tp_free((PyObject *)s); } static PyObject * s_unpack_internal(PyStructObject *soself, char *startfrom) { - formatcode *code; - Py_ssize_t i = 0; - PyObject *result = PyTuple_New(soself->s_len); - if (result == NULL) - return NULL; - - for (code = soself->s_codes; code->fmtdef != NULL; code++) { - PyObject *v; - const formatdef *e = code->fmtdef; - const char *res = startfrom + code->offset; - if (e->format == 's') { - v = PyBytes_FromStringAndSize(res, code->size); - } else if (e->format == 'p') { - Py_ssize_t n = *(unsigned char*)res; - if (n >= code->size) - n = code->size - 1; - v = PyBytes_FromStringAndSize(res + 1, n); - } else { - v = e->unpack(res, e); - } - if (v == NULL) - goto fail; - PyTuple_SET_ITEM(result, i++, v); - } + formatcode *code; + Py_ssize_t i = 0; + PyObject *result = PyTuple_New(soself->s_len); + if (result == NULL) + return NULL; + + for (code = soself->s_codes; code->fmtdef != NULL; code++) { + PyObject *v; + const formatdef *e = code->fmtdef; + const char *res = startfrom + code->offset; + if (e->format == 's') { + v = PyBytes_FromStringAndSize(res, code->size); + } else if (e->format == 'p') { + Py_ssize_t n = *(unsigned char*)res; + if (n >= code->size) + n = code->size - 1; + v = PyBytes_FromStringAndSize(res + 1, n); + } else { + v = e->unpack(res, e); + } + if (v == NULL) + goto fail; + PyTuple_SET_ITEM(result, i++, v); + } - return result; + return result; fail: - Py_DECREF(result); - return NULL; + Py_DECREF(result); + return NULL; } @@ -1395,24 +1395,24 @@ static PyObject * s_unpack(PyObject *self, PyObject *input) { - Py_buffer vbuf; - PyObject *result; - PyStructObject *soself = (PyStructObject *)self; - - assert(PyStruct_Check(self)); - assert(soself->s_codes != NULL); - if (PyObject_GetBuffer(input, &vbuf, PyBUF_SIMPLE) < 0) - return NULL; - if (vbuf.len != soself->s_size) { - PyErr_Format(StructError, - "unpack requires a bytes argument of length %zd", - soself->s_size); - PyBuffer_Release(&vbuf); - return NULL; - } - result = s_unpack_internal(soself, vbuf.buf); - PyBuffer_Release(&vbuf); - return result; + Py_buffer vbuf; + PyObject *result; + PyStructObject *soself = (PyStructObject *)self; + + assert(PyStruct_Check(self)); + assert(soself->s_codes != NULL); + if (PyObject_GetBuffer(input, &vbuf, PyBUF_SIMPLE) < 0) + return NULL; + if (vbuf.len != soself->s_size) { + PyErr_Format(StructError, + "unpack requires a bytes argument of length %zd", + soself->s_size); + PyBuffer_Release(&vbuf); + return NULL; + } + result = s_unpack_internal(soself, vbuf.buf); + PyBuffer_Release(&vbuf); + return result; } PyDoc_STRVAR(s_unpack_from__doc__, @@ -1426,35 +1426,35 @@ static PyObject * s_unpack_from(PyObject *self, PyObject *args, PyObject *kwds) { - static char *kwlist[] = {"buffer", "offset", 0}; + static char *kwlist[] = {"buffer", "offset", 0}; - PyObject *input; - Py_ssize_t offset = 0; - Py_buffer vbuf; - PyObject *result; - PyStructObject *soself = (PyStructObject *)self; - - assert(PyStruct_Check(self)); - assert(soself->s_codes != NULL); - - if (!PyArg_ParseTupleAndKeywords(args, kwds, - "O|n:unpack_from", kwlist, - &input, &offset)) - return NULL; - if (PyObject_GetBuffer(input, &vbuf, PyBUF_SIMPLE) < 0) - return NULL; - if (offset < 0) - offset += vbuf.len; - if (offset < 0 || vbuf.len - offset < soself->s_size) { - PyErr_Format(StructError, - "unpack_from requires a buffer of at least %zd bytes", - soself->s_size); - PyBuffer_Release(&vbuf); - return NULL; - } - result = s_unpack_internal(soself, (char*)vbuf.buf + offset); - PyBuffer_Release(&vbuf); - return result; + PyObject *input; + Py_ssize_t offset = 0; + Py_buffer vbuf; + PyObject *result; + PyStructObject *soself = (PyStructObject *)self; + + assert(PyStruct_Check(self)); + assert(soself->s_codes != NULL); + + if (!PyArg_ParseTupleAndKeywords(args, kwds, + "O|n:unpack_from", kwlist, + &input, &offset)) + return NULL; + if (PyObject_GetBuffer(input, &vbuf, PyBUF_SIMPLE) < 0) + return NULL; + if (offset < 0) + offset += vbuf.len; + if (offset < 0 || vbuf.len - offset < soself->s_size) { + PyErr_Format(StructError, + "unpack_from requires a buffer of at least %zd bytes", + soself->s_size); + PyBuffer_Release(&vbuf); + return NULL; + } + result = s_unpack_internal(soself, (char*)vbuf.buf + offset); + PyBuffer_Release(&vbuf); + return result; } @@ -1471,85 +1471,85 @@ static int s_pack_internal(PyStructObject *soself, PyObject *args, int offset, char* buf) { - formatcode *code; - /* XXX(nnorwitz): why does i need to be a local? can we use - the offset parameter or do we need the wider width? */ - Py_ssize_t i; - - memset(buf, '\0', soself->s_size); - i = offset; - for (code = soself->s_codes; code->fmtdef != NULL; code++) { - Py_ssize_t n; - PyObject *v = PyTuple_GET_ITEM(args, i++); - const formatdef *e = code->fmtdef; - char *res = buf + code->offset; - if (e->format == 's') { - int isstring; - void *p; - if (PyUnicode_Check(v)) { - v = _PyUnicode_AsDefaultEncodedString(v, NULL); - if (v == NULL) - return -1; - } - isstring = PyBytes_Check(v); - if (!isstring && !PyByteArray_Check(v)) { - PyErr_SetString(StructError, - "argument for 's' must be a bytes or string"); - return -1; - } - if (isstring) { - n = PyBytes_GET_SIZE(v); - p = PyBytes_AS_STRING(v); - } - else { - n = PyByteArray_GET_SIZE(v); - p = PyByteArray_AS_STRING(v); - } - if (n > code->size) - n = code->size; - if (n > 0) - memcpy(res, p, n); - } else if (e->format == 'p') { - int isstring; - void *p; - if (PyUnicode_Check(v)) { - v = _PyUnicode_AsDefaultEncodedString(v, NULL); - if (v == NULL) - return -1; - } - isstring = PyBytes_Check(v); - if (!isstring && !PyByteArray_Check(v)) { - PyErr_SetString(StructError, - "argument for 'p' must be a bytes or string"); - return -1; - } - if (isstring) { - n = PyBytes_GET_SIZE(v); - p = PyBytes_AS_STRING(v); - } - else { - n = PyByteArray_GET_SIZE(v); - p = PyByteArray_AS_STRING(v); - } - if (n > (code->size - 1)) - n = code->size - 1; - if (n > 0) - memcpy(res + 1, p, n); - if (n > 255) - n = 255; - *res = Py_SAFE_DOWNCAST(n, Py_ssize_t, unsigned char); - } else { - if (e->pack(res, v, e) < 0) { - if (PyLong_Check(v) && PyErr_ExceptionMatches(PyExc_OverflowError)) - PyErr_SetString(StructError, - "long too large to convert to int"); - return -1; - } - } - } + formatcode *code; + /* XXX(nnorwitz): why does i need to be a local? can we use + the offset parameter or do we need the wider width? */ + Py_ssize_t i; + + memset(buf, '\0', soself->s_size); + i = offset; + for (code = soself->s_codes; code->fmtdef != NULL; code++) { + Py_ssize_t n; + PyObject *v = PyTuple_GET_ITEM(args, i++); + const formatdef *e = code->fmtdef; + char *res = buf + code->offset; + if (e->format == 's') { + int isstring; + void *p; + if (PyUnicode_Check(v)) { + v = _PyUnicode_AsDefaultEncodedString(v, NULL); + if (v == NULL) + return -1; + } + isstring = PyBytes_Check(v); + if (!isstring && !PyByteArray_Check(v)) { + PyErr_SetString(StructError, + "argument for 's' must be a bytes or string"); + return -1; + } + if (isstring) { + n = PyBytes_GET_SIZE(v); + p = PyBytes_AS_STRING(v); + } + else { + n = PyByteArray_GET_SIZE(v); + p = PyByteArray_AS_STRING(v); + } + if (n > code->size) + n = code->size; + if (n > 0) + memcpy(res, p, n); + } else if (e->format == 'p') { + int isstring; + void *p; + if (PyUnicode_Check(v)) { + v = _PyUnicode_AsDefaultEncodedString(v, NULL); + if (v == NULL) + return -1; + } + isstring = PyBytes_Check(v); + if (!isstring && !PyByteArray_Check(v)) { + PyErr_SetString(StructError, + "argument for 'p' must be a bytes or string"); + return -1; + } + if (isstring) { + n = PyBytes_GET_SIZE(v); + p = PyBytes_AS_STRING(v); + } + else { + n = PyByteArray_GET_SIZE(v); + p = PyByteArray_AS_STRING(v); + } + if (n > (code->size - 1)) + n = code->size - 1; + if (n > 0) + memcpy(res + 1, p, n); + if (n > 255) + n = 255; + *res = Py_SAFE_DOWNCAST(n, Py_ssize_t, unsigned char); + } else { + if (e->pack(res, v, e) < 0) { + if (PyLong_Check(v) && PyErr_ExceptionMatches(PyExc_OverflowError)) + PyErr_SetString(StructError, + "long too large to convert to int"); + return -1; + } + } + } - /* Success */ - return 0; + /* Success */ + return 0; } @@ -1562,32 +1562,32 @@ static PyObject * s_pack(PyObject *self, PyObject *args) { - PyStructObject *soself; - PyObject *result; + PyStructObject *soself; + PyObject *result; - /* Validate arguments. */ - soself = (PyStructObject *)self; - assert(PyStruct_Check(self)); - assert(soself->s_codes != NULL); - if (PyTuple_GET_SIZE(args) != soself->s_len) - { - PyErr_Format(StructError, - "pack requires exactly %zd arguments", soself->s_len); - return NULL; - } - - /* Allocate a new string */ - result = PyBytes_FromStringAndSize((char *)NULL, soself->s_size); - if (result == NULL) - return NULL; - - /* Call the guts */ - if ( s_pack_internal(soself, args, 0, PyBytes_AS_STRING(result)) != 0 ) { - Py_DECREF(result); - return NULL; - } + /* Validate arguments. */ + soself = (PyStructObject *)self; + assert(PyStruct_Check(self)); + assert(soself->s_codes != NULL); + if (PyTuple_GET_SIZE(args) != soself->s_len) + { + PyErr_Format(StructError, + "pack requires exactly %zd arguments", soself->s_len); + return NULL; + } + + /* Allocate a new string */ + result = PyBytes_FromStringAndSize((char *)NULL, soself->s_size); + if (result == NULL) + return NULL; + + /* Call the guts */ + if ( s_pack_internal(soself, args, 0, PyBytes_AS_STRING(result)) != 0 ) { + Py_DECREF(result); + return NULL; + } - return result; + return result; } PyDoc_STRVAR(s_pack_into__doc__, @@ -1601,59 +1601,59 @@ static PyObject * s_pack_into(PyObject *self, PyObject *args) { - PyStructObject *soself; - char *buffer; - Py_ssize_t buffer_len, offset; - - /* Validate arguments. +1 is for the first arg as buffer. */ - soself = (PyStructObject *)self; - assert(PyStruct_Check(self)); - assert(soself->s_codes != NULL); - if (PyTuple_GET_SIZE(args) != (soself->s_len + 2)) - { - PyErr_Format(StructError, - "pack_into requires exactly %zd arguments", - (soself->s_len + 2)); - return NULL; - } - - /* Extract a writable memory buffer from the first argument */ - if ( PyObject_AsWriteBuffer(PyTuple_GET_ITEM(args, 0), - (void**)&buffer, &buffer_len) == -1 ) { - return NULL; - } - assert( buffer_len >= 0 ); - - /* Extract the offset from the first argument */ - offset = PyNumber_AsSsize_t(PyTuple_GET_ITEM(args, 1), PyExc_IndexError); - if (offset == -1 && PyErr_Occurred()) - return NULL; - - /* Support negative offsets. */ - if (offset < 0) - offset += buffer_len; - - /* Check boundaries */ - if (offset < 0 || (buffer_len - offset) < soself->s_size) { - PyErr_Format(StructError, - "pack_into requires a buffer of at least %zd bytes", - soself->s_size); - return NULL; - } - - /* Call the guts */ - if ( s_pack_internal(soself, args, 2, buffer + offset) != 0 ) { - return NULL; - } + PyStructObject *soself; + char *buffer; + Py_ssize_t buffer_len, offset; + + /* Validate arguments. +1 is for the first arg as buffer. */ + soself = (PyStructObject *)self; + assert(PyStruct_Check(self)); + assert(soself->s_codes != NULL); + if (PyTuple_GET_SIZE(args) != (soself->s_len + 2)) + { + PyErr_Format(StructError, + "pack_into requires exactly %zd arguments", + (soself->s_len + 2)); + return NULL; + } + + /* Extract a writable memory buffer from the first argument */ + if ( PyObject_AsWriteBuffer(PyTuple_GET_ITEM(args, 0), + (void**)&buffer, &buffer_len) == -1 ) { + return NULL; + } + assert( buffer_len >= 0 ); + + /* Extract the offset from the first argument */ + offset = PyNumber_AsSsize_t(PyTuple_GET_ITEM(args, 1), PyExc_IndexError); + if (offset == -1 && PyErr_Occurred()) + return NULL; + + /* Support negative offsets. */ + if (offset < 0) + offset += buffer_len; + + /* Check boundaries */ + if (offset < 0 || (buffer_len - offset) < soself->s_size) { + PyErr_Format(StructError, + "pack_into requires a buffer of at least %zd bytes", + soself->s_size); + return NULL; + } + + /* Call the guts */ + if ( s_pack_internal(soself, args, 2, buffer + offset) != 0 ) { + return NULL; + } - Py_RETURN_NONE; + Py_RETURN_NONE; } static PyObject * s_get_format(PyStructObject *self, void *unused) { - Py_INCREF(self->s_format); - return self->s_format; + Py_INCREF(self->s_format); + return self->s_format; } static PyObject * @@ -1665,12 +1665,12 @@ /* List of functions */ static struct PyMethodDef s_methods[] = { - {"pack", s_pack, METH_VARARGS, s_pack__doc__}, - {"pack_into", s_pack_into, METH_VARARGS, s_pack_into__doc__}, - {"unpack", s_unpack, METH_O, s_unpack__doc__}, - {"unpack_from", (PyCFunction)s_unpack_from, METH_VARARGS|METH_KEYWORDS, - s_unpack_from__doc__}, - {NULL, NULL} /* sentinel */ + {"pack", s_pack, METH_VARARGS, s_pack__doc__}, + {"pack_into", s_pack_into, METH_VARARGS, s_pack_into__doc__}, + {"unpack", s_unpack, METH_O, s_unpack__doc__}, + {"unpack_from", (PyCFunction)s_unpack_from, METH_VARARGS|METH_KEYWORDS, + s_unpack_from__doc__}, + {NULL, NULL} /* sentinel */ }; PyDoc_STRVAR(s__doc__, "Compiled struct object"); @@ -1678,52 +1678,52 @@ #define OFF(x) offsetof(PyStructObject, x) static PyGetSetDef s_getsetlist[] = { - {"format", (getter)s_get_format, (setter)NULL, "struct format string", NULL}, - {"size", (getter)s_get_size, (setter)NULL, "struct size in bytes", NULL}, - {NULL} /* sentinel */ + {"format", (getter)s_get_format, (setter)NULL, "struct format string", NULL}, + {"size", (getter)s_get_size, (setter)NULL, "struct size in bytes", NULL}, + {NULL} /* sentinel */ }; static PyTypeObject PyStructType = { - PyVarObject_HEAD_INIT(NULL, 0) - "Struct", - sizeof(PyStructObject), - 0, - (destructor)s_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 */ - PyObject_GenericSetAttr, /* tp_setattro */ - 0, /* tp_as_buffer */ - Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */ - s__doc__, /* tp_doc */ - 0, /* tp_traverse */ - 0, /* tp_clear */ - 0, /* tp_richcompare */ - offsetof(PyStructObject, weakreflist), /* tp_weaklistoffset */ - 0, /* tp_iter */ - 0, /* tp_iternext */ - s_methods, /* tp_methods */ - NULL, /* tp_members */ - s_getsetlist, /* tp_getset */ - 0, /* tp_base */ - 0, /* tp_dict */ - 0, /* tp_descr_get */ - 0, /* tp_descr_set */ - 0, /* tp_dictoffset */ - s_init, /* tp_init */ - PyType_GenericAlloc,/* tp_alloc */ - s_new, /* tp_new */ - PyObject_Del, /* tp_free */ + PyVarObject_HEAD_INIT(NULL, 0) + "Struct", + sizeof(PyStructObject), + 0, + (destructor)s_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 */ + PyObject_GenericSetAttr, /* tp_setattro */ + 0, /* tp_as_buffer */ + Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */ + s__doc__, /* tp_doc */ + 0, /* tp_traverse */ + 0, /* tp_clear */ + 0, /* tp_richcompare */ + offsetof(PyStructObject, weakreflist), /* tp_weaklistoffset */ + 0, /* tp_iter */ + 0, /* tp_iternext */ + s_methods, /* tp_methods */ + NULL, /* tp_members */ + s_getsetlist, /* tp_getset */ + 0, /* tp_base */ + 0, /* tp_dict */ + 0, /* tp_descr_get */ + 0, /* tp_descr_set */ + 0, /* tp_dictoffset */ + s_init, /* tp_init */ + PyType_GenericAlloc,/* tp_alloc */ + s_new, /* tp_new */ + PyObject_Del, /* tp_free */ }; @@ -1735,29 +1735,29 @@ static PyObject * cache_struct(PyObject *fmt) { - PyObject * s_object; + PyObject * s_object; - if (cache == NULL) { - cache = PyDict_New(); - if (cache == NULL) - return NULL; - } - - s_object = PyDict_GetItem(cache, fmt); - if (s_object != NULL) { - Py_INCREF(s_object); - return s_object; - } - - s_object = PyObject_CallFunctionObjArgs((PyObject *)(&PyStructType), fmt, NULL); - if (s_object != NULL) { - if (PyDict_Size(cache) >= MAXCACHE) - PyDict_Clear(cache); - /* Attempt to cache the result */ - if (PyDict_SetItem(cache, fmt, s_object) == -1) - PyErr_Clear(); - } - return s_object; + if (cache == NULL) { + cache = PyDict_New(); + if (cache == NULL) + return NULL; + } + + s_object = PyDict_GetItem(cache, fmt); + if (s_object != NULL) { + Py_INCREF(s_object); + return s_object; + } + + s_object = PyObject_CallFunctionObjArgs((PyObject *)(&PyStructType), fmt, NULL); + if (s_object != NULL) { + if (PyDict_Size(cache) >= MAXCACHE) + PyDict_Clear(cache); + /* Attempt to cache the result */ + if (PyDict_SetItem(cache, fmt, s_object) == -1) + PyErr_Clear(); + } + return s_object; } PyDoc_STRVAR(clearcache_doc, @@ -1766,8 +1766,8 @@ static PyObject * clearcache(PyObject *self) { - Py_CLEAR(cache); - Py_RETURN_NONE; + Py_CLEAR(cache); + Py_RETURN_NONE; } PyDoc_STRVAR(calcsize_doc, @@ -1776,13 +1776,13 @@ static PyObject * calcsize(PyObject *self, PyObject *fmt) { - Py_ssize_t n; - PyObject *s_object = cache_struct(fmt); - if (s_object == NULL) - return NULL; - n = ((PyStructObject *)s_object)->s_size; - Py_DECREF(s_object); - return PyLong_FromSsize_t(n); + Py_ssize_t n; + PyObject *s_object = cache_struct(fmt); + if (s_object == NULL) + return NULL; + n = ((PyStructObject *)s_object)->s_size; + Py_DECREF(s_object); + return PyLong_FromSsize_t(n); } PyDoc_STRVAR(pack_doc, @@ -1791,27 +1791,27 @@ static PyObject * pack(PyObject *self, PyObject *args) { - PyObject *s_object, *fmt, *newargs, *result; - Py_ssize_t n = PyTuple_GET_SIZE(args); + PyObject *s_object, *fmt, *newargs, *result; + Py_ssize_t n = PyTuple_GET_SIZE(args); - if (n == 0) { - PyErr_SetString(PyExc_TypeError, "missing format argument"); - return NULL; - } - fmt = PyTuple_GET_ITEM(args, 0); - newargs = PyTuple_GetSlice(args, 1, n); - if (newargs == NULL) - return NULL; - - s_object = cache_struct(fmt); - if (s_object == NULL) { - Py_DECREF(newargs); - return NULL; - } - result = s_pack(s_object, newargs); - Py_DECREF(newargs); - Py_DECREF(s_object); - return result; + if (n == 0) { + PyErr_SetString(PyExc_TypeError, "missing format argument"); + return NULL; + } + fmt = PyTuple_GET_ITEM(args, 0); + newargs = PyTuple_GetSlice(args, 1, n); + if (newargs == NULL) + return NULL; + + s_object = cache_struct(fmt); + if (s_object == NULL) { + Py_DECREF(newargs); + return NULL; + } + result = s_pack(s_object, newargs); + Py_DECREF(newargs); + Py_DECREF(s_object); + return result; } PyDoc_STRVAR(pack_into_doc, @@ -1821,27 +1821,27 @@ static PyObject * pack_into(PyObject *self, PyObject *args) { - PyObject *s_object, *fmt, *newargs, *result; - Py_ssize_t n = PyTuple_GET_SIZE(args); + PyObject *s_object, *fmt, *newargs, *result; + Py_ssize_t n = PyTuple_GET_SIZE(args); - if (n == 0) { - PyErr_SetString(PyExc_TypeError, "missing format argument"); - return NULL; - } - fmt = PyTuple_GET_ITEM(args, 0); - newargs = PyTuple_GetSlice(args, 1, n); - if (newargs == NULL) - return NULL; - - s_object = cache_struct(fmt); - if (s_object == NULL) { - Py_DECREF(newargs); - return NULL; - } - result = s_pack_into(s_object, newargs); - Py_DECREF(newargs); - Py_DECREF(s_object); - return result; + if (n == 0) { + PyErr_SetString(PyExc_TypeError, "missing format argument"); + return NULL; + } + fmt = PyTuple_GET_ITEM(args, 0); + newargs = PyTuple_GetSlice(args, 1, n); + if (newargs == NULL) + return NULL; + + s_object = cache_struct(fmt); + if (s_object == NULL) { + Py_DECREF(newargs); + return NULL; + } + result = s_pack_into(s_object, newargs); + Py_DECREF(newargs); + Py_DECREF(s_object); + return result; } PyDoc_STRVAR(unpack_doc, @@ -1851,17 +1851,17 @@ static PyObject * unpack(PyObject *self, PyObject *args) { - PyObject *s_object, *fmt, *inputstr, *result; + PyObject *s_object, *fmt, *inputstr, *result; - if (!PyArg_UnpackTuple(args, "unpack", 2, 2, &fmt, &inputstr)) - return NULL; + if (!PyArg_UnpackTuple(args, "unpack", 2, 2, &fmt, &inputstr)) + return NULL; - s_object = cache_struct(fmt); - if (s_object == NULL) - return NULL; - result = s_unpack(s_object, inputstr); - Py_DECREF(s_object); - return result; + s_object = cache_struct(fmt); + if (s_object == NULL) + return NULL; + result = s_unpack(s_object, inputstr); + Py_DECREF(s_object); + return result; } PyDoc_STRVAR(unpack_from_doc, @@ -1871,38 +1871,38 @@ static PyObject * unpack_from(PyObject *self, PyObject *args, PyObject *kwds) { - PyObject *s_object, *fmt, *newargs, *result; - Py_ssize_t n = PyTuple_GET_SIZE(args); + PyObject *s_object, *fmt, *newargs, *result; + Py_ssize_t n = PyTuple_GET_SIZE(args); - if (n == 0) { - PyErr_SetString(PyExc_TypeError, "missing format argument"); - return NULL; - } - fmt = PyTuple_GET_ITEM(args, 0); - newargs = PyTuple_GetSlice(args, 1, n); - if (newargs == NULL) - return NULL; - - s_object = cache_struct(fmt); - if (s_object == NULL) { - Py_DECREF(newargs); - return NULL; - } - result = s_unpack_from(s_object, newargs, kwds); - Py_DECREF(newargs); - Py_DECREF(s_object); - return result; + if (n == 0) { + PyErr_SetString(PyExc_TypeError, "missing format argument"); + return NULL; + } + fmt = PyTuple_GET_ITEM(args, 0); + newargs = PyTuple_GetSlice(args, 1, n); + if (newargs == NULL) + return NULL; + + s_object = cache_struct(fmt); + if (s_object == NULL) { + Py_DECREF(newargs); + return NULL; + } + result = s_unpack_from(s_object, newargs, kwds); + Py_DECREF(newargs); + Py_DECREF(s_object); + return result; } static struct PyMethodDef module_functions[] = { - {"_clearcache", (PyCFunction)clearcache, METH_NOARGS, clearcache_doc}, - {"calcsize", calcsize, METH_O, calcsize_doc}, - {"pack", pack, METH_VARARGS, pack_doc}, - {"pack_into", pack_into, METH_VARARGS, pack_into_doc}, - {"unpack", unpack, METH_VARARGS, unpack_doc}, - {"unpack_from", (PyCFunction)unpack_from, - METH_VARARGS|METH_KEYWORDS, unpack_from_doc}, - {NULL, NULL} /* sentinel */ + {"_clearcache", (PyCFunction)clearcache, METH_NOARGS, clearcache_doc}, + {"calcsize", calcsize, METH_O, calcsize_doc}, + {"pack", pack, METH_VARARGS, pack_doc}, + {"pack_into", pack_into, METH_VARARGS, pack_into_doc}, + {"unpack", unpack, METH_VARARGS, unpack_doc}, + {"unpack_from", (PyCFunction)unpack_from, + METH_VARARGS|METH_KEYWORDS, unpack_from_doc}, + {NULL, NULL} /* sentinel */ }; @@ -1939,87 +1939,87 @@ static struct PyModuleDef _structmodule = { - PyModuleDef_HEAD_INIT, - "_struct", - module_doc, - -1, - module_functions, - NULL, - NULL, - NULL, - NULL + PyModuleDef_HEAD_INIT, + "_struct", + module_doc, + -1, + module_functions, + NULL, + NULL, + NULL, + NULL }; PyMODINIT_FUNC PyInit__struct(void) { - PyObject *ver, *m; + PyObject *ver, *m; - ver = PyBytes_FromString("0.3"); - if (ver == NULL) - return NULL; - - m = PyModule_Create(&_structmodule); - if (m == NULL) - return NULL; - - Py_TYPE(&PyStructType) = &PyType_Type; - if (PyType_Ready(&PyStructType) < 0) - return NULL; - - /* Check endian and swap in faster functions */ - { - int one = 1; - formatdef *native = native_table; - formatdef *other, *ptr; - if ((int)*(unsigned char*)&one) - other = lilendian_table; - else - other = bigendian_table; - /* Scan through the native table, find a matching - entry in the endian table and swap in the - native implementations whenever possible - (64-bit platforms may not have "standard" sizes) */ - while (native->format != '\0' && other->format != '\0') { - ptr = other; - while (ptr->format != '\0') { - if (ptr->format == native->format) { - /* Match faster when formats are - listed in the same order */ - if (ptr == other) - other++; - /* Only use the trick if the - size matches */ - if (ptr->size != native->size) - break; - /* Skip float and double, could be - "unknown" float format */ - if (ptr->format == 'd' || ptr->format == 'f') - break; - ptr->pack = native->pack; - ptr->unpack = native->unpack; - break; - } - ptr++; - } - native++; - } - } - - /* Add some symbolic constants to the module */ - if (StructError == NULL) { - StructError = PyErr_NewException("struct.error", NULL, NULL); - if (StructError == NULL) - return NULL; - } - - Py_INCREF(StructError); - PyModule_AddObject(m, "error", StructError); + ver = PyBytes_FromString("0.3"); + if (ver == NULL) + return NULL; + + m = PyModule_Create(&_structmodule); + if (m == NULL) + return NULL; + + Py_TYPE(&PyStructType) = &PyType_Type; + if (PyType_Ready(&PyStructType) < 0) + return NULL; + + /* Check endian and swap in faster functions */ + { + int one = 1; + formatdef *native = native_table; + formatdef *other, *ptr; + if ((int)*(unsigned char*)&one) + other = lilendian_table; + else + other = bigendian_table; + /* Scan through the native table, find a matching + entry in the endian table and swap in the + native implementations whenever possible + (64-bit platforms may not have "standard" sizes) */ + while (native->format != '\0' && other->format != '\0') { + ptr = other; + while (ptr->format != '\0') { + if (ptr->format == native->format) { + /* Match faster when formats are + listed in the same order */ + if (ptr == other) + other++; + /* Only use the trick if the + size matches */ + if (ptr->size != native->size) + break; + /* Skip float and double, could be + "unknown" float format */ + if (ptr->format == 'd' || ptr->format == 'f') + break; + ptr->pack = native->pack; + ptr->unpack = native->unpack; + break; + } + ptr++; + } + native++; + } + } + + /* Add some symbolic constants to the module */ + if (StructError == NULL) { + StructError = PyErr_NewException("struct.error", NULL, NULL); + if (StructError == NULL) + return NULL; + } + + Py_INCREF(StructError); + PyModule_AddObject(m, "error", StructError); - Py_INCREF((PyObject*)&PyStructType); - PyModule_AddObject(m, "Struct", (PyObject*)&PyStructType); + Py_INCREF((PyObject*)&PyStructType); + PyModule_AddObject(m, "Struct", (PyObject*)&PyStructType); - PyModule_AddObject(m, "__version__", ver); + PyModule_AddObject(m, "__version__", ver); - return m; + return m; } Modified: python/branches/py3k/Modules/_testcapimodule.c ============================================================================== --- python/branches/py3k/Modules/_testcapimodule.c (original) +++ python/branches/py3k/Modules/_testcapimodule.c Sun May 9 17:52:27 2010 @@ -15,22 +15,22 @@ #ifdef WITH_THREAD #include "pythread.h" #endif /* WITH_THREAD */ -static PyObject *TestError; /* set to exception object in init */ +static PyObject *TestError; /* set to exception object in init */ /* Raise TestError with test_name + ": " + msg, and return NULL. */ static PyObject * raiseTestError(const char* test_name, const char* msg) { - char buf[2048]; + char buf[2048]; - if (strlen(test_name) + strlen(msg) > sizeof(buf) - 50) - PyErr_SetString(TestError, "internal error msg too large"); - else { - PyOS_snprintf(buf, sizeof(buf), "%s: %s", test_name, msg); - PyErr_SetString(TestError, buf); - } - return NULL; + if (strlen(test_name) + strlen(msg) > sizeof(buf) - 50) + PyErr_SetString(TestError, "internal error msg too large"); + else { + PyOS_snprintf(buf, sizeof(buf), "%s: %s", test_name, msg); + PyErr_SetString(TestError, buf); + } + return NULL; } /* Test #defines from pyconfig.h (particularly the SIZEOF_* defines). @@ -41,138 +41,138 @@ */ static PyObject* sizeof_error(const char* fatname, const char* typname, - int expected, int got) + int expected, int got) { - char buf[1024]; - PyOS_snprintf(buf, sizeof(buf), - "%.200s #define == %d but sizeof(%.200s) == %d", - fatname, expected, typname, got); - PyErr_SetString(TestError, buf); - return (PyObject*)NULL; + char buf[1024]; + PyOS_snprintf(buf, sizeof(buf), + "%.200s #define == %d but sizeof(%.200s) == %d", + fatname, expected, typname, got); + PyErr_SetString(TestError, buf); + return (PyObject*)NULL; } static PyObject* test_config(PyObject *self) { #define CHECK_SIZEOF(FATNAME, TYPE) \ - if (FATNAME != sizeof(TYPE)) \ - return sizeof_error(#FATNAME, #TYPE, FATNAME, sizeof(TYPE)) + if (FATNAME != sizeof(TYPE)) \ + return sizeof_error(#FATNAME, #TYPE, FATNAME, sizeof(TYPE)) - CHECK_SIZEOF(SIZEOF_SHORT, short); - CHECK_SIZEOF(SIZEOF_INT, int); - CHECK_SIZEOF(SIZEOF_LONG, long); - CHECK_SIZEOF(SIZEOF_VOID_P, void*); - CHECK_SIZEOF(SIZEOF_TIME_T, time_t); + CHECK_SIZEOF(SIZEOF_SHORT, short); + CHECK_SIZEOF(SIZEOF_INT, int); + CHECK_SIZEOF(SIZEOF_LONG, long); + CHECK_SIZEOF(SIZEOF_VOID_P, void*); + CHECK_SIZEOF(SIZEOF_TIME_T, time_t); #ifdef HAVE_LONG_LONG - CHECK_SIZEOF(SIZEOF_LONG_LONG, PY_LONG_LONG); + CHECK_SIZEOF(SIZEOF_LONG_LONG, PY_LONG_LONG); #endif #undef CHECK_SIZEOF - Py_INCREF(Py_None); - return Py_None; + Py_INCREF(Py_None); + return Py_None; } static PyObject* test_list_api(PyObject *self) { - PyObject* list; - int i; + PyObject* list; + int i; - /* SF bug 132008: PyList_Reverse segfaults */ + /* SF bug 132008: PyList_Reverse segfaults */ #define NLIST 30 - list = PyList_New(NLIST); - if (list == (PyObject*)NULL) - return (PyObject*)NULL; - /* list = range(NLIST) */ - for (i = 0; i < NLIST; ++i) { - PyObject* anint = PyLong_FromLong(i); - if (anint == (PyObject*)NULL) { - Py_DECREF(list); - return (PyObject*)NULL; - } - PyList_SET_ITEM(list, i, anint); - } - /* list.reverse(), via PyList_Reverse() */ - i = PyList_Reverse(list); /* should not blow up! */ - if (i != 0) { - Py_DECREF(list); - return (PyObject*)NULL; - } - /* Check that list == range(29, -1, -1) now */ - for (i = 0; i < NLIST; ++i) { - PyObject* anint = PyList_GET_ITEM(list, i); - if (PyLong_AS_LONG(anint) != NLIST-1-i) { - PyErr_SetString(TestError, - "test_list_api: reverse screwed up"); - Py_DECREF(list); - return (PyObject*)NULL; - } - } - Py_DECREF(list); + list = PyList_New(NLIST); + if (list == (PyObject*)NULL) + return (PyObject*)NULL; + /* list = range(NLIST) */ + for (i = 0; i < NLIST; ++i) { + PyObject* anint = PyLong_FromLong(i); + if (anint == (PyObject*)NULL) { + Py_DECREF(list); + return (PyObject*)NULL; + } + PyList_SET_ITEM(list, i, anint); + } + /* list.reverse(), via PyList_Reverse() */ + i = PyList_Reverse(list); /* should not blow up! */ + if (i != 0) { + Py_DECREF(list); + return (PyObject*)NULL; + } + /* Check that list == range(29, -1, -1) now */ + for (i = 0; i < NLIST; ++i) { + PyObject* anint = PyList_GET_ITEM(list, i); + if (PyLong_AS_LONG(anint) != NLIST-1-i) { + PyErr_SetString(TestError, + "test_list_api: reverse screwed up"); + Py_DECREF(list); + return (PyObject*)NULL; + } + } + Py_DECREF(list); #undef NLIST - Py_INCREF(Py_None); - return Py_None; + Py_INCREF(Py_None); + return Py_None; } static int test_dict_inner(int count) { - Py_ssize_t pos = 0, iterations = 0; - int i; - PyObject *dict = PyDict_New(); - PyObject *v, *k; - - if (dict == NULL) - return -1; - - for (i = 0; i < count; i++) { - v = PyLong_FromLong(i); - PyDict_SetItem(dict, v, v); - Py_DECREF(v); - } - - while (PyDict_Next(dict, &pos, &k, &v)) { - PyObject *o; - iterations++; - - i = PyLong_AS_LONG(v) + 1; - o = PyLong_FromLong(i); - if (o == NULL) - return -1; - if (PyDict_SetItem(dict, k, o) < 0) { - Py_DECREF(o); - return -1; - } - Py_DECREF(o); - } - - Py_DECREF(dict); - - if (iterations != count) { - PyErr_SetString( - TestError, - "test_dict_iteration: dict iteration went wrong "); - return -1; - } else { - return 0; - } + Py_ssize_t pos = 0, iterations = 0; + int i; + PyObject *dict = PyDict_New(); + PyObject *v, *k; + + if (dict == NULL) + return -1; + + for (i = 0; i < count; i++) { + v = PyLong_FromLong(i); + PyDict_SetItem(dict, v, v); + Py_DECREF(v); + } + + while (PyDict_Next(dict, &pos, &k, &v)) { + PyObject *o; + iterations++; + + i = PyLong_AS_LONG(v) + 1; + o = PyLong_FromLong(i); + if (o == NULL) + return -1; + if (PyDict_SetItem(dict, k, o) < 0) { + Py_DECREF(o); + return -1; + } + Py_DECREF(o); + } + + Py_DECREF(dict); + + if (iterations != count) { + PyErr_SetString( + TestError, + "test_dict_iteration: dict iteration went wrong "); + return -1; + } else { + return 0; + } } static PyObject* test_dict_iteration(PyObject* self) { - int i; + int i; - for (i = 0; i < 200; i++) { - if (test_dict_inner(i) < 0) { - return NULL; - } - } + for (i = 0; i < 200; i++) { + if (test_dict_inner(i) < 0) { + return NULL; + } + } - Py_INCREF(Py_None); - return Py_None; + Py_INCREF(Py_None); + return Py_None; } @@ -180,107 +180,107 @@ * PyType_Ready if it hasn't already been called */ static PyTypeObject _HashInheritanceTester_Type = { - PyVarObject_HEAD_INIT(NULL, 0) - "hashinheritancetester", /* Name of this type */ - sizeof(PyObject), /* Basic object size */ - 0, /* Item size for varobject */ - (destructor)PyObject_Del, /* 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, /* tp_flags */ - 0, /* tp_doc */ - 0, /* tp_traverse */ - 0, /* tp_clear */ - 0, /* tp_richcompare */ - 0, /* tp_weaklistoffset */ - 0, /* tp_iter */ - 0, /* tp_iternext */ - 0, /* tp_methods */ - 0, /* tp_members */ - 0, /* tp_getset */ - 0, /* tp_base */ - 0, /* tp_dict */ - 0, /* tp_descr_get */ - 0, /* tp_descr_set */ - 0, /* tp_dictoffset */ - 0, /* tp_init */ - 0, /* tp_alloc */ - PyType_GenericNew, /* tp_new */ + PyVarObject_HEAD_INIT(NULL, 0) + "hashinheritancetester", /* Name of this type */ + sizeof(PyObject), /* Basic object size */ + 0, /* Item size for varobject */ + (destructor)PyObject_Del, /* 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, /* tp_flags */ + 0, /* tp_doc */ + 0, /* tp_traverse */ + 0, /* tp_clear */ + 0, /* tp_richcompare */ + 0, /* tp_weaklistoffset */ + 0, /* tp_iter */ + 0, /* tp_iternext */ + 0, /* tp_methods */ + 0, /* tp_members */ + 0, /* tp_getset */ + 0, /* tp_base */ + 0, /* tp_dict */ + 0, /* tp_descr_get */ + 0, /* tp_descr_set */ + 0, /* tp_dictoffset */ + 0, /* tp_init */ + 0, /* tp_alloc */ + PyType_GenericNew, /* tp_new */ }; static PyObject* test_lazy_hash_inheritance(PyObject* self) { - PyTypeObject *type; - PyObject *obj; - long hash; - - type = &_HashInheritanceTester_Type; - - if (type->tp_dict != NULL) - /* The type has already been initialized. This probably means - -R is being used. */ - Py_RETURN_NONE; - - - obj = PyObject_New(PyObject, type); - if (obj == NULL) { - PyErr_Clear(); - PyErr_SetString( - TestError, - "test_lazy_hash_inheritance: failed to create object"); - return NULL; - } - - if (type->tp_dict != NULL) { - PyErr_SetString( - TestError, - "test_lazy_hash_inheritance: type initialised too soon"); - Py_DECREF(obj); - return NULL; - } - - hash = PyObject_Hash(obj); - if ((hash == -1) && PyErr_Occurred()) { - PyErr_Clear(); - PyErr_SetString( - TestError, - "test_lazy_hash_inheritance: could not hash object"); - Py_DECREF(obj); - return NULL; - } - - if (type->tp_dict == NULL) { - PyErr_SetString( - TestError, - "test_lazy_hash_inheritance: type not initialised by hash()"); - Py_DECREF(obj); - return NULL; - } - - if (type->tp_hash != PyType_Type.tp_hash) { - PyErr_SetString( - TestError, - "test_lazy_hash_inheritance: unexpected hash function"); - Py_DECREF(obj); - return NULL; - } + PyTypeObject *type; + PyObject *obj; + long hash; + + type = &_HashInheritanceTester_Type; + + if (type->tp_dict != NULL) + /* The type has already been initialized. This probably means + -R is being used. */ + Py_RETURN_NONE; + + + obj = PyObject_New(PyObject, type); + if (obj == NULL) { + PyErr_Clear(); + PyErr_SetString( + TestError, + "test_lazy_hash_inheritance: failed to create object"); + return NULL; + } + + if (type->tp_dict != NULL) { + PyErr_SetString( + TestError, + "test_lazy_hash_inheritance: type initialised too soon"); + Py_DECREF(obj); + return NULL; + } + + hash = PyObject_Hash(obj); + if ((hash == -1) && PyErr_Occurred()) { + PyErr_Clear(); + PyErr_SetString( + TestError, + "test_lazy_hash_inheritance: could not hash object"); + Py_DECREF(obj); + return NULL; + } - Py_DECREF(obj); + if (type->tp_dict == NULL) { + PyErr_SetString( + TestError, + "test_lazy_hash_inheritance: type not initialised by hash()"); + Py_DECREF(obj); + return NULL; + } + + if (type->tp_hash != PyType_Type.tp_hash) { + PyErr_SetString( + TestError, + "test_lazy_hash_inheritance: unexpected hash function"); + Py_DECREF(obj); + return NULL; + } - Py_RETURN_NONE; + Py_DECREF(obj); + + Py_RETURN_NONE; } @@ -291,85 +291,85 @@ static int broken_buffer_getbuffer(PyObject *self, Py_buffer *view, int flags) { - PyErr_SetString( - TestError, - "test_broken_memoryview: expected error in bf_getbuffer"); - return -1; + PyErr_SetString( + TestError, + "test_broken_memoryview: expected error in bf_getbuffer"); + return -1; } static PyBufferProcs memoryviewtester_as_buffer = { - (getbufferproc)broken_buffer_getbuffer, /* bf_getbuffer */ - 0, /* bf_releasebuffer */ + (getbufferproc)broken_buffer_getbuffer, /* bf_getbuffer */ + 0, /* bf_releasebuffer */ }; static PyTypeObject _MemoryViewTester_Type = { - PyVarObject_HEAD_INIT(NULL, 0) - "memoryviewtester", /* Name of this type */ - sizeof(PyObject), /* Basic object size */ - 0, /* Item size for varobject */ - (destructor)PyObject_Del, /* tp_dealloc */ - 0, /* tp_print */ - 0, /* tp_getattr */ - 0, /* tp_setattr */ - 0, /* tp_compare */ - 0, /* tp_repr */ - 0, /* tp_as_number */ - 0, /* tp_as_sequence */ - 0, /* tp_as_mapping */ - 0, /* tp_hash */ - 0, /* tp_call */ - 0, /* tp_str */ - PyObject_GenericGetAttr, /* tp_getattro */ - 0, /* tp_setattro */ - &memoryviewtester_as_buffer, /* tp_as_buffer */ - Py_TPFLAGS_DEFAULT, /* tp_flags */ - 0, /* tp_doc */ - 0, /* tp_traverse */ - 0, /* tp_clear */ - 0, /* tp_richcompare */ - 0, /* tp_weaklistoffset */ - 0, /* tp_iter */ - 0, /* tp_iternext */ - 0, /* tp_methods */ - 0, /* tp_members */ - 0, /* tp_getset */ - 0, /* tp_base */ - 0, /* tp_dict */ - 0, /* tp_descr_get */ - 0, /* tp_descr_set */ - 0, /* tp_dictoffset */ - 0, /* tp_init */ - 0, /* tp_alloc */ - PyType_GenericNew, /* tp_new */ + PyVarObject_HEAD_INIT(NULL, 0) + "memoryviewtester", /* Name of this type */ + sizeof(PyObject), /* Basic object size */ + 0, /* Item size for varobject */ + (destructor)PyObject_Del, /* tp_dealloc */ + 0, /* tp_print */ + 0, /* tp_getattr */ + 0, /* tp_setattr */ + 0, /* tp_compare */ + 0, /* tp_repr */ + 0, /* tp_as_number */ + 0, /* tp_as_sequence */ + 0, /* tp_as_mapping */ + 0, /* tp_hash */ + 0, /* tp_call */ + 0, /* tp_str */ + PyObject_GenericGetAttr, /* tp_getattro */ + 0, /* tp_setattro */ + &memoryviewtester_as_buffer, /* tp_as_buffer */ + Py_TPFLAGS_DEFAULT, /* tp_flags */ + 0, /* tp_doc */ + 0, /* tp_traverse */ + 0, /* tp_clear */ + 0, /* tp_richcompare */ + 0, /* tp_weaklistoffset */ + 0, /* tp_iter */ + 0, /* tp_iternext */ + 0, /* tp_methods */ + 0, /* tp_members */ + 0, /* tp_getset */ + 0, /* tp_base */ + 0, /* tp_dict */ + 0, /* tp_descr_get */ + 0, /* tp_descr_set */ + 0, /* tp_dictoffset */ + 0, /* tp_init */ + 0, /* tp_alloc */ + PyType_GenericNew, /* tp_new */ }; static PyObject* test_broken_memoryview(PyObject* self) { - PyObject *obj = PyObject_New(PyObject, &_MemoryViewTester_Type); - PyObject *res; + PyObject *obj = PyObject_New(PyObject, &_MemoryViewTester_Type); + PyObject *res; - if (obj == NULL) { - PyErr_Clear(); - PyErr_SetString( - TestError, - "test_broken_memoryview: failed to create object"); - return NULL; - } - - res = PyMemoryView_FromObject(obj); - if (res || !PyErr_Occurred()){ - PyErr_SetString( - TestError, - "test_broken_memoryview: memoryview() didn't raise an Exception"); - Py_XDECREF(res); - Py_DECREF(obj); - return NULL; - } - - PyErr_Clear(); - Py_DECREF(obj); - Py_RETURN_NONE; + if (obj == NULL) { + PyErr_Clear(); + PyErr_SetString( + TestError, + "test_broken_memoryview: failed to create object"); + return NULL; + } + + res = PyMemoryView_FromObject(obj); + if (res || !PyErr_Occurred()){ + PyErr_SetString( + TestError, + "test_broken_memoryview: memoryview() didn't raise an Exception"); + Py_XDECREF(res); + Py_DECREF(obj); + return NULL; + } + + PyErr_Clear(); + Py_DECREF(obj); + Py_RETURN_NONE; } @@ -393,22 +393,22 @@ static PyObject * raise_test_long_error(const char* msg) { - return raiseTestError("test_long_api", msg); + return raiseTestError("test_long_api", msg); } -#define TESTNAME test_long_api_inner -#define TYPENAME long -#define F_S_TO_PY PyLong_FromLong -#define F_PY_TO_S PyLong_AsLong -#define F_U_TO_PY PyLong_FromUnsignedLong -#define F_PY_TO_U PyLong_AsUnsignedLong +#define TESTNAME test_long_api_inner +#define TYPENAME long +#define F_S_TO_PY PyLong_FromLong +#define F_PY_TO_S PyLong_AsLong +#define F_U_TO_PY PyLong_FromUnsignedLong +#define F_PY_TO_U PyLong_AsUnsignedLong #include "testcapi_long.h" static PyObject * test_long_api(PyObject* self) { - return TESTNAME(raise_test_long_error); + return TESTNAME(raise_test_long_error); } #undef TESTNAME @@ -423,22 +423,22 @@ static PyObject * raise_test_longlong_error(const char* msg) { - return raiseTestError("test_longlong_api", msg); + return raiseTestError("test_longlong_api", msg); } -#define TESTNAME test_longlong_api_inner -#define TYPENAME PY_LONG_LONG -#define F_S_TO_PY PyLong_FromLongLong -#define F_PY_TO_S PyLong_AsLongLong -#define F_U_TO_PY PyLong_FromUnsignedLongLong -#define F_PY_TO_U PyLong_AsUnsignedLongLong +#define TESTNAME test_longlong_api_inner +#define TYPENAME PY_LONG_LONG +#define F_S_TO_PY PyLong_FromLongLong +#define F_PY_TO_S PyLong_AsLongLong +#define F_U_TO_PY PyLong_FromUnsignedLongLong +#define F_PY_TO_U PyLong_AsUnsignedLongLong #include "testcapi_long.h" static PyObject * test_longlong_api(PyObject* self, PyObject *args) { - return TESTNAME(raise_test_longlong_error); + return TESTNAME(raise_test_longlong_error); } #undef TESTNAME @@ -456,161 +456,161 @@ static PyObject * test_long_and_overflow(PyObject *self) { - PyObject *num, *one, *temp; - long value; - int overflow; - - /* Test that overflow is set properly for a large value. */ - /* num is a number larger than LONG_MAX even on 64-bit platforms */ - num = PyLong_FromString("FFFFFFFFFFFFFFFFFFFFFFFF", NULL, 16); - if (num == NULL) - return NULL; - overflow = 1234; - value = PyLong_AsLongAndOverflow(num, &overflow); - Py_DECREF(num); - if (value == -1 && PyErr_Occurred()) - return NULL; - if (value != -1) - return raiseTestError("test_long_and_overflow", - "return value was not set to -1"); - if (overflow != 1) - return raiseTestError("test_long_and_overflow", - "overflow was not set to 1"); - - /* Same again, with num = LONG_MAX + 1 */ - num = PyLong_FromLong(LONG_MAX); - if (num == NULL) - return NULL; - one = PyLong_FromLong(1L); - if (one == NULL) { - Py_DECREF(num); - return NULL; - } - temp = PyNumber_Add(num, one); - Py_DECREF(one); - Py_DECREF(num); - num = temp; - if (num == NULL) - return NULL; - overflow = 0; - value = PyLong_AsLongAndOverflow(num, &overflow); - Py_DECREF(num); - if (value == -1 && PyErr_Occurred()) - return NULL; - if (value != -1) - return raiseTestError("test_long_and_overflow", - "return value was not set to -1"); - if (overflow != 1) - return raiseTestError("test_long_and_overflow", - "overflow was not set to 1"); - - /* Test that overflow is set properly for a large negative value. */ - /* num is a number smaller than LONG_MIN even on 64-bit platforms */ - num = PyLong_FromString("-FFFFFFFFFFFFFFFFFFFFFFFF", NULL, 16); - if (num == NULL) - return NULL; - overflow = 1234; - value = PyLong_AsLongAndOverflow(num, &overflow); - Py_DECREF(num); - if (value == -1 && PyErr_Occurred()) - return NULL; - if (value != -1) - return raiseTestError("test_long_and_overflow", - "return value was not set to -1"); - if (overflow != -1) - return raiseTestError("test_long_and_overflow", - "overflow was not set to -1"); - - /* Same again, with num = LONG_MIN - 1 */ - num = PyLong_FromLong(LONG_MIN); - if (num == NULL) - return NULL; - one = PyLong_FromLong(1L); - if (one == NULL) { - Py_DECREF(num); - return NULL; - } - temp = PyNumber_Subtract(num, one); - Py_DECREF(one); - Py_DECREF(num); - num = temp; - if (num == NULL) - return NULL; - overflow = 0; - value = PyLong_AsLongAndOverflow(num, &overflow); - Py_DECREF(num); - if (value == -1 && PyErr_Occurred()) - return NULL; - if (value != -1) - return raiseTestError("test_long_and_overflow", - "return value was not set to -1"); - if (overflow != -1) - return raiseTestError("test_long_and_overflow", - "overflow was not set to -1"); - - /* Test that overflow is cleared properly for small values. */ - num = PyLong_FromString("FF", NULL, 16); - if (num == NULL) - return NULL; - overflow = 1234; - value = PyLong_AsLongAndOverflow(num, &overflow); - Py_DECREF(num); - if (value == -1 && PyErr_Occurred()) - return NULL; - if (value != 0xFF) - return raiseTestError("test_long_and_overflow", - "expected return value 0xFF"); - if (overflow != 0) - return raiseTestError("test_long_and_overflow", - "overflow was not cleared"); - - num = PyLong_FromString("-FF", NULL, 16); - if (num == NULL) - return NULL; - overflow = 0; - value = PyLong_AsLongAndOverflow(num, &overflow); - Py_DECREF(num); - if (value == -1 && PyErr_Occurred()) - return NULL; - if (value != -0xFF) - return raiseTestError("test_long_and_overflow", - "expected return value 0xFF"); - if (overflow != 0) - return raiseTestError("test_long_and_overflow", - "overflow was set incorrectly"); - - num = PyLong_FromLong(LONG_MAX); - if (num == NULL) - return NULL; - overflow = 1234; - value = PyLong_AsLongAndOverflow(num, &overflow); - Py_DECREF(num); - if (value == -1 && PyErr_Occurred()) - return NULL; - if (value != LONG_MAX) - return raiseTestError("test_long_and_overflow", - "expected return value LONG_MAX"); - if (overflow != 0) - return raiseTestError("test_long_and_overflow", - "overflow was not cleared"); - - num = PyLong_FromLong(LONG_MIN); - if (num == NULL) - return NULL; - overflow = 0; - value = PyLong_AsLongAndOverflow(num, &overflow); - Py_DECREF(num); - if (value == -1 && PyErr_Occurred()) - return NULL; - if (value != LONG_MIN) - return raiseTestError("test_long_and_overflow", - "expected return value LONG_MIN"); - if (overflow != 0) - return raiseTestError("test_long_and_overflow", - "overflow was not cleared"); + PyObject *num, *one, *temp; + long value; + int overflow; + + /* Test that overflow is set properly for a large value. */ + /* num is a number larger than LONG_MAX even on 64-bit platforms */ + num = PyLong_FromString("FFFFFFFFFFFFFFFFFFFFFFFF", NULL, 16); + if (num == NULL) + return NULL; + overflow = 1234; + value = PyLong_AsLongAndOverflow(num, &overflow); + Py_DECREF(num); + if (value == -1 && PyErr_Occurred()) + return NULL; + if (value != -1) + return raiseTestError("test_long_and_overflow", + "return value was not set to -1"); + if (overflow != 1) + return raiseTestError("test_long_and_overflow", + "overflow was not set to 1"); + + /* Same again, with num = LONG_MAX + 1 */ + num = PyLong_FromLong(LONG_MAX); + if (num == NULL) + return NULL; + one = PyLong_FromLong(1L); + if (one == NULL) { + Py_DECREF(num); + return NULL; + } + temp = PyNumber_Add(num, one); + Py_DECREF(one); + Py_DECREF(num); + num = temp; + if (num == NULL) + return NULL; + overflow = 0; + value = PyLong_AsLongAndOverflow(num, &overflow); + Py_DECREF(num); + if (value == -1 && PyErr_Occurred()) + return NULL; + if (value != -1) + return raiseTestError("test_long_and_overflow", + "return value was not set to -1"); + if (overflow != 1) + return raiseTestError("test_long_and_overflow", + "overflow was not set to 1"); + + /* Test that overflow is set properly for a large negative value. */ + /* num is a number smaller than LONG_MIN even on 64-bit platforms */ + num = PyLong_FromString("-FFFFFFFFFFFFFFFFFFFFFFFF", NULL, 16); + if (num == NULL) + return NULL; + overflow = 1234; + value = PyLong_AsLongAndOverflow(num, &overflow); + Py_DECREF(num); + if (value == -1 && PyErr_Occurred()) + return NULL; + if (value != -1) + return raiseTestError("test_long_and_overflow", + "return value was not set to -1"); + if (overflow != -1) + return raiseTestError("test_long_and_overflow", + "overflow was not set to -1"); + + /* Same again, with num = LONG_MIN - 1 */ + num = PyLong_FromLong(LONG_MIN); + if (num == NULL) + return NULL; + one = PyLong_FromLong(1L); + if (one == NULL) { + Py_DECREF(num); + return NULL; + } + temp = PyNumber_Subtract(num, one); + Py_DECREF(one); + Py_DECREF(num); + num = temp; + if (num == NULL) + return NULL; + overflow = 0; + value = PyLong_AsLongAndOverflow(num, &overflow); + Py_DECREF(num); + if (value == -1 && PyErr_Occurred()) + return NULL; + if (value != -1) + return raiseTestError("test_long_and_overflow", + "return value was not set to -1"); + if (overflow != -1) + return raiseTestError("test_long_and_overflow", + "overflow was not set to -1"); + + /* Test that overflow is cleared properly for small values. */ + num = PyLong_FromString("FF", NULL, 16); + if (num == NULL) + return NULL; + overflow = 1234; + value = PyLong_AsLongAndOverflow(num, &overflow); + Py_DECREF(num); + if (value == -1 && PyErr_Occurred()) + return NULL; + if (value != 0xFF) + return raiseTestError("test_long_and_overflow", + "expected return value 0xFF"); + if (overflow != 0) + return raiseTestError("test_long_and_overflow", + "overflow was not cleared"); + + num = PyLong_FromString("-FF", NULL, 16); + if (num == NULL) + return NULL; + overflow = 0; + value = PyLong_AsLongAndOverflow(num, &overflow); + Py_DECREF(num); + if (value == -1 && PyErr_Occurred()) + return NULL; + if (value != -0xFF) + return raiseTestError("test_long_and_overflow", + "expected return value 0xFF"); + if (overflow != 0) + return raiseTestError("test_long_and_overflow", + "overflow was set incorrectly"); + + num = PyLong_FromLong(LONG_MAX); + if (num == NULL) + return NULL; + overflow = 1234; + value = PyLong_AsLongAndOverflow(num, &overflow); + Py_DECREF(num); + if (value == -1 && PyErr_Occurred()) + return NULL; + if (value != LONG_MAX) + return raiseTestError("test_long_and_overflow", + "expected return value LONG_MAX"); + if (overflow != 0) + return raiseTestError("test_long_and_overflow", + "overflow was not cleared"); + + num = PyLong_FromLong(LONG_MIN); + if (num == NULL) + return NULL; + overflow = 0; + value = PyLong_AsLongAndOverflow(num, &overflow); + Py_DECREF(num); + if (value == -1 && PyErr_Occurred()) + return NULL; + if (value != LONG_MIN) + return raiseTestError("test_long_and_overflow", + "expected return value LONG_MIN"); + if (overflow != 0) + return raiseTestError("test_long_and_overflow", + "overflow was not cleared"); - Py_INCREF(Py_None); - return Py_None; + Py_INCREF(Py_None); + return Py_None; } /* Test the PyLong_AsLongLongAndOverflow API. General conversion to @@ -621,161 +621,161 @@ static PyObject * test_long_long_and_overflow(PyObject *self) { - PyObject *num, *one, *temp; - PY_LONG_LONG value; - int overflow; - - /* Test that overflow is set properly for a large value. */ - /* num is a number larger than PY_LLONG_MAX on a typical machine. */ - num = PyLong_FromString("FFFFFFFFFFFFFFFFFFFFFFFF", NULL, 16); - if (num == NULL) - return NULL; - overflow = 1234; - value = PyLong_AsLongLongAndOverflow(num, &overflow); - Py_DECREF(num); - if (value == -1 && PyErr_Occurred()) - return NULL; - if (value != -1) - return raiseTestError("test_long_long_and_overflow", - "return value was not set to -1"); - if (overflow != 1) - return raiseTestError("test_long_long_and_overflow", - "overflow was not set to 1"); - - /* Same again, with num = PY_LLONG_MAX + 1 */ - num = PyLong_FromLongLong(PY_LLONG_MAX); - if (num == NULL) - return NULL; - one = PyLong_FromLong(1L); - if (one == NULL) { - Py_DECREF(num); - return NULL; - } - temp = PyNumber_Add(num, one); - Py_DECREF(one); - Py_DECREF(num); - num = temp; - if (num == NULL) - return NULL; - overflow = 0; - value = PyLong_AsLongLongAndOverflow(num, &overflow); - Py_DECREF(num); - if (value == -1 && PyErr_Occurred()) - return NULL; - if (value != -1) - return raiseTestError("test_long_long_and_overflow", - "return value was not set to -1"); - if (overflow != 1) - return raiseTestError("test_long_long_and_overflow", - "overflow was not set to 1"); - - /* Test that overflow is set properly for a large negative value. */ - /* num is a number smaller than PY_LLONG_MIN on a typical platform */ - num = PyLong_FromString("-FFFFFFFFFFFFFFFFFFFFFFFF", NULL, 16); - if (num == NULL) - return NULL; - overflow = 1234; - value = PyLong_AsLongLongAndOverflow(num, &overflow); - Py_DECREF(num); - if (value == -1 && PyErr_Occurred()) - return NULL; - if (value != -1) - return raiseTestError("test_long_long_and_overflow", - "return value was not set to -1"); - if (overflow != -1) - return raiseTestError("test_long_long_and_overflow", - "overflow was not set to -1"); - - /* Same again, with num = PY_LLONG_MIN - 1 */ - num = PyLong_FromLongLong(PY_LLONG_MIN); - if (num == NULL) - return NULL; - one = PyLong_FromLong(1L); - if (one == NULL) { - Py_DECREF(num); - return NULL; - } - temp = PyNumber_Subtract(num, one); - Py_DECREF(one); - Py_DECREF(num); - num = temp; - if (num == NULL) - return NULL; - overflow = 0; - value = PyLong_AsLongLongAndOverflow(num, &overflow); - Py_DECREF(num); - if (value == -1 && PyErr_Occurred()) - return NULL; - if (value != -1) - return raiseTestError("test_long_long_and_overflow", - "return value was not set to -1"); - if (overflow != -1) - return raiseTestError("test_long_long_and_overflow", - "overflow was not set to -1"); - - /* Test that overflow is cleared properly for small values. */ - num = PyLong_FromString("FF", NULL, 16); - if (num == NULL) - return NULL; - overflow = 1234; - value = PyLong_AsLongLongAndOverflow(num, &overflow); - Py_DECREF(num); - if (value == -1 && PyErr_Occurred()) - return NULL; - if (value != 0xFF) - return raiseTestError("test_long_long_and_overflow", - "expected return value 0xFF"); - if (overflow != 0) - return raiseTestError("test_long_long_and_overflow", - "overflow was not cleared"); - - num = PyLong_FromString("-FF", NULL, 16); - if (num == NULL) - return NULL; - overflow = 0; - value = PyLong_AsLongLongAndOverflow(num, &overflow); - Py_DECREF(num); - if (value == -1 && PyErr_Occurred()) - return NULL; - if (value != -0xFF) - return raiseTestError("test_long_long_and_overflow", - "expected return value 0xFF"); - if (overflow != 0) - return raiseTestError("test_long_long_and_overflow", - "overflow was set incorrectly"); - - num = PyLong_FromLongLong(PY_LLONG_MAX); - if (num == NULL) - return NULL; - overflow = 1234; - value = PyLong_AsLongLongAndOverflow(num, &overflow); - Py_DECREF(num); - if (value == -1 && PyErr_Occurred()) - return NULL; - if (value != PY_LLONG_MAX) - return raiseTestError("test_long_long_and_overflow", - "expected return value PY_LLONG_MAX"); - if (overflow != 0) - return raiseTestError("test_long_long_and_overflow", - "overflow was not cleared"); - - num = PyLong_FromLongLong(PY_LLONG_MIN); - if (num == NULL) - return NULL; - overflow = 0; - value = PyLong_AsLongLongAndOverflow(num, &overflow); - Py_DECREF(num); - if (value == -1 && PyErr_Occurred()) - return NULL; - if (value != PY_LLONG_MIN) - return raiseTestError("test_long_long_and_overflow", - "expected return value PY_LLONG_MIN"); - if (overflow != 0) - return raiseTestError("test_long_long_and_overflow", - "overflow was not cleared"); + PyObject *num, *one, *temp; + PY_LONG_LONG value; + int overflow; + + /* Test that overflow is set properly for a large value. */ + /* num is a number larger than PY_LLONG_MAX on a typical machine. */ + num = PyLong_FromString("FFFFFFFFFFFFFFFFFFFFFFFF", NULL, 16); + if (num == NULL) + return NULL; + overflow = 1234; + value = PyLong_AsLongLongAndOverflow(num, &overflow); + Py_DECREF(num); + if (value == -1 && PyErr_Occurred()) + return NULL; + if (value != -1) + return raiseTestError("test_long_long_and_overflow", + "return value was not set to -1"); + if (overflow != 1) + return raiseTestError("test_long_long_and_overflow", + "overflow was not set to 1"); + + /* Same again, with num = PY_LLONG_MAX + 1 */ + num = PyLong_FromLongLong(PY_LLONG_MAX); + if (num == NULL) + return NULL; + one = PyLong_FromLong(1L); + if (one == NULL) { + Py_DECREF(num); + return NULL; + } + temp = PyNumber_Add(num, one); + Py_DECREF(one); + Py_DECREF(num); + num = temp; + if (num == NULL) + return NULL; + overflow = 0; + value = PyLong_AsLongLongAndOverflow(num, &overflow); + Py_DECREF(num); + if (value == -1 && PyErr_Occurred()) + return NULL; + if (value != -1) + return raiseTestError("test_long_long_and_overflow", + "return value was not set to -1"); + if (overflow != 1) + return raiseTestError("test_long_long_and_overflow", + "overflow was not set to 1"); + + /* Test that overflow is set properly for a large negative value. */ + /* num is a number smaller than PY_LLONG_MIN on a typical platform */ + num = PyLong_FromString("-FFFFFFFFFFFFFFFFFFFFFFFF", NULL, 16); + if (num == NULL) + return NULL; + overflow = 1234; + value = PyLong_AsLongLongAndOverflow(num, &overflow); + Py_DECREF(num); + if (value == -1 && PyErr_Occurred()) + return NULL; + if (value != -1) + return raiseTestError("test_long_long_and_overflow", + "return value was not set to -1"); + if (overflow != -1) + return raiseTestError("test_long_long_and_overflow", + "overflow was not set to -1"); + + /* Same again, with num = PY_LLONG_MIN - 1 */ + num = PyLong_FromLongLong(PY_LLONG_MIN); + if (num == NULL) + return NULL; + one = PyLong_FromLong(1L); + if (one == NULL) { + Py_DECREF(num); + return NULL; + } + temp = PyNumber_Subtract(num, one); + Py_DECREF(one); + Py_DECREF(num); + num = temp; + if (num == NULL) + return NULL; + overflow = 0; + value = PyLong_AsLongLongAndOverflow(num, &overflow); + Py_DECREF(num); + if (value == -1 && PyErr_Occurred()) + return NULL; + if (value != -1) + return raiseTestError("test_long_long_and_overflow", + "return value was not set to -1"); + if (overflow != -1) + return raiseTestError("test_long_long_and_overflow", + "overflow was not set to -1"); + + /* Test that overflow is cleared properly for small values. */ + num = PyLong_FromString("FF", NULL, 16); + if (num == NULL) + return NULL; + overflow = 1234; + value = PyLong_AsLongLongAndOverflow(num, &overflow); + Py_DECREF(num); + if (value == -1 && PyErr_Occurred()) + return NULL; + if (value != 0xFF) + return raiseTestError("test_long_long_and_overflow", + "expected return value 0xFF"); + if (overflow != 0) + return raiseTestError("test_long_long_and_overflow", + "overflow was not cleared"); + + num = PyLong_FromString("-FF", NULL, 16); + if (num == NULL) + return NULL; + overflow = 0; + value = PyLong_AsLongLongAndOverflow(num, &overflow); + Py_DECREF(num); + if (value == -1 && PyErr_Occurred()) + return NULL; + if (value != -0xFF) + return raiseTestError("test_long_long_and_overflow", + "expected return value 0xFF"); + if (overflow != 0) + return raiseTestError("test_long_long_and_overflow", + "overflow was set incorrectly"); + + num = PyLong_FromLongLong(PY_LLONG_MAX); + if (num == NULL) + return NULL; + overflow = 1234; + value = PyLong_AsLongLongAndOverflow(num, &overflow); + Py_DECREF(num); + if (value == -1 && PyErr_Occurred()) + return NULL; + if (value != PY_LLONG_MAX) + return raiseTestError("test_long_long_and_overflow", + "expected return value PY_LLONG_MAX"); + if (overflow != 0) + return raiseTestError("test_long_long_and_overflow", + "overflow was not cleared"); - Py_INCREF(Py_None); - return Py_None; + num = PyLong_FromLongLong(PY_LLONG_MIN); + if (num == NULL) + return NULL; + overflow = 0; + value = PyLong_AsLongLongAndOverflow(num, &overflow); + Py_DECREF(num); + if (value == -1 && PyErr_Occurred()) + return NULL; + if (value != PY_LLONG_MIN) + return raiseTestError("test_long_long_and_overflow", + "expected return value PY_LLONG_MIN"); + if (overflow != 0) + return raiseTestError("test_long_long_and_overflow", + "overflow was not cleared"); + + Py_INCREF(Py_None); + return Py_None; } /* Test the L code for PyArg_ParseTuple. This should deliver a PY_LONG_LONG @@ -785,71 +785,71 @@ static PyObject * test_L_code(PyObject *self) { - PyObject *tuple, *num; - PY_LONG_LONG value; + PyObject *tuple, *num; + PY_LONG_LONG value; + + tuple = PyTuple_New(1); + if (tuple == NULL) + return NULL; + + num = PyLong_FromLong(42); + if (num == NULL) + return NULL; + + PyTuple_SET_ITEM(tuple, 0, num); + + value = -1; + if (PyArg_ParseTuple(tuple, "L:test_L_code", &value) < 0) + return NULL; + if (value != 42) + return raiseTestError("test_L_code", + "L code returned wrong value for long 42"); + + Py_DECREF(num); + num = PyLong_FromLong(42); + if (num == NULL) + return NULL; + + PyTuple_SET_ITEM(tuple, 0, num); + + value = -1; + if (PyArg_ParseTuple(tuple, "L:test_L_code", &value) < 0) + return NULL; + if (value != 42) + return raiseTestError("test_L_code", + "L code returned wrong value for int 42"); - tuple = PyTuple_New(1); - if (tuple == NULL) - return NULL; - - num = PyLong_FromLong(42); - if (num == NULL) - return NULL; - - PyTuple_SET_ITEM(tuple, 0, num); - - value = -1; - if (PyArg_ParseTuple(tuple, "L:test_L_code", &value) < 0) - return NULL; - if (value != 42) - return raiseTestError("test_L_code", - "L code returned wrong value for long 42"); - - Py_DECREF(num); - num = PyLong_FromLong(42); - if (num == NULL) - return NULL; - - PyTuple_SET_ITEM(tuple, 0, num); - - value = -1; - if (PyArg_ParseTuple(tuple, "L:test_L_code", &value) < 0) - return NULL; - if (value != 42) - return raiseTestError("test_L_code", - "L code returned wrong value for int 42"); - - Py_DECREF(tuple); - Py_INCREF(Py_None); - return Py_None; + Py_DECREF(tuple); + Py_INCREF(Py_None); + return Py_None; } -#endif /* ifdef HAVE_LONG_LONG */ +#endif /* ifdef HAVE_LONG_LONG */ /* Test tuple argument processing */ static PyObject * getargs_tuple(PyObject *self, PyObject *args) { - int a, b, c; - if (!PyArg_ParseTuple(args, "i(ii)", &a, &b, &c)) - return NULL; - return Py_BuildValue("iii", a, b, c); + int a, b, c; + if (!PyArg_ParseTuple(args, "i(ii)", &a, &b, &c)) + return NULL; + return Py_BuildValue("iii", a, b, c); } /* test PyArg_ParseTupleAndKeywords */ static PyObject *getargs_keywords(PyObject *self, PyObject *args, PyObject *kwargs) { - static char *keywords[] = {"arg1","arg2","arg3","arg4","arg5", NULL}; - static char *fmt="(ii)i|(i(ii))(iii)i"; - int int_args[10]={-1, -1, -1, -1, -1, -1, -1, -1, -1, -1}; - - if (!PyArg_ParseTupleAndKeywords(args, kwargs, fmt, keywords, - &int_args[0], &int_args[1], &int_args[2], &int_args[3], &int_args[4], - &int_args[5], &int_args[6], &int_args[7], &int_args[8], &int_args[9])) - return NULL; - return Py_BuildValue("iiiiiiiiii", - int_args[0], int_args[1], int_args[2], int_args[3], int_args[4], - int_args[5], int_args[6], int_args[7], int_args[8], int_args[9]); + static char *keywords[] = {"arg1","arg2","arg3","arg4","arg5", NULL}; + static char *fmt="(ii)i|(i(ii))(iii)i"; + int int_args[10]={-1, -1, -1, -1, -1, -1, -1, -1, -1, -1}; + + if (!PyArg_ParseTupleAndKeywords(args, kwargs, fmt, keywords, + &int_args[0], &int_args[1], &int_args[2], &int_args[3], &int_args[4], + &int_args[5], &int_args[6], &int_args[7], &int_args[8], &int_args[9])) + return NULL; + return Py_BuildValue("iiiiiiiiii", + int_args[0], int_args[1], int_args[2], int_args[3], int_args[4], + int_args[5], int_args[6], int_args[7], int_args[8], int_args[9]); } /* Functions to call PyArg_ParseTuple with integer format codes, @@ -858,101 +858,101 @@ static PyObject * getargs_b(PyObject *self, PyObject *args) { - unsigned char value; - if (!PyArg_ParseTuple(args, "b", &value)) - return NULL; - return PyLong_FromUnsignedLong((unsigned long)value); + unsigned char value; + if (!PyArg_ParseTuple(args, "b", &value)) + return NULL; + return PyLong_FromUnsignedLong((unsigned long)value); } static PyObject * getargs_B(PyObject *self, PyObject *args) { - unsigned char value; - if (!PyArg_ParseTuple(args, "B", &value)) - return NULL; - return PyLong_FromUnsignedLong((unsigned long)value); + unsigned char value; + if (!PyArg_ParseTuple(args, "B", &value)) + return NULL; + return PyLong_FromUnsignedLong((unsigned long)value); } static PyObject * getargs_h(PyObject *self, PyObject *args) { - short value; - if (!PyArg_ParseTuple(args, "h", &value)) - return NULL; - return PyLong_FromLong((long)value); + short value; + if (!PyArg_ParseTuple(args, "h", &value)) + return NULL; + return PyLong_FromLong((long)value); } static PyObject * getargs_H(PyObject *self, PyObject *args) { - unsigned short value; - if (!PyArg_ParseTuple(args, "H", &value)) - return NULL; - return PyLong_FromUnsignedLong((unsigned long)value); + unsigned short value; + if (!PyArg_ParseTuple(args, "H", &value)) + return NULL; + return PyLong_FromUnsignedLong((unsigned long)value); } static PyObject * getargs_I(PyObject *self, PyObject *args) { - unsigned int value; - if (!PyArg_ParseTuple(args, "I", &value)) - return NULL; - return PyLong_FromUnsignedLong((unsigned long)value); + unsigned int value; + if (!PyArg_ParseTuple(args, "I", &value)) + return NULL; + return PyLong_FromUnsignedLong((unsigned long)value); } static PyObject * getargs_k(PyObject *self, PyObject *args) { - unsigned long value; - if (!PyArg_ParseTuple(args, "k", &value)) - return NULL; - return PyLong_FromUnsignedLong(value); + unsigned long value; + if (!PyArg_ParseTuple(args, "k", &value)) + return NULL; + return PyLong_FromUnsignedLong(value); } static PyObject * getargs_i(PyObject *self, PyObject *args) { - int value; - if (!PyArg_ParseTuple(args, "i", &value)) - return NULL; - return PyLong_FromLong((long)value); + int value; + if (!PyArg_ParseTuple(args, "i", &value)) + return NULL; + return PyLong_FromLong((long)value); } static PyObject * getargs_l(PyObject *self, PyObject *args) { - long value; - if (!PyArg_ParseTuple(args, "l", &value)) - return NULL; - return PyLong_FromLong(value); + long value; + if (!PyArg_ParseTuple(args, "l", &value)) + return NULL; + return PyLong_FromLong(value); } static PyObject * getargs_n(PyObject *self, PyObject *args) { - Py_ssize_t value; - if (!PyArg_ParseTuple(args, "n", &value)) - return NULL; - return PyLong_FromSsize_t(value); + Py_ssize_t value; + if (!PyArg_ParseTuple(args, "n", &value)) + return NULL; + return PyLong_FromSsize_t(value); } #ifdef HAVE_LONG_LONG static PyObject * getargs_L(PyObject *self, PyObject *args) { - PY_LONG_LONG value; - if (!PyArg_ParseTuple(args, "L", &value)) - return NULL; - return PyLong_FromLongLong(value); + PY_LONG_LONG value; + if (!PyArg_ParseTuple(args, "L", &value)) + return NULL; + return PyLong_FromLongLong(value); } static PyObject * getargs_K(PyObject *self, PyObject *args) { - unsigned PY_LONG_LONG value; - if (!PyArg_ParseTuple(args, "K", &value)) - return NULL; - return PyLong_FromUnsignedLongLong(value); + unsigned PY_LONG_LONG value; + if (!PyArg_ParseTuple(args, "K", &value)) + return NULL; + return PyLong_FromUnsignedLongLong(value); } #endif @@ -961,54 +961,54 @@ static PyObject * test_k_code(PyObject *self) { - PyObject *tuple, *num; - unsigned long value; + PyObject *tuple, *num; + unsigned long value; + + tuple = PyTuple_New(1); + if (tuple == NULL) + return NULL; + + /* a number larger than ULONG_MAX even on 64-bit platforms */ + num = PyLong_FromString("FFFFFFFFFFFFFFFFFFFFFFFF", NULL, 16); + if (num == NULL) + return NULL; - tuple = PyTuple_New(1); - if (tuple == NULL) - return NULL; - - /* a number larger than ULONG_MAX even on 64-bit platforms */ - num = PyLong_FromString("FFFFFFFFFFFFFFFFFFFFFFFF", NULL, 16); - if (num == NULL) - return NULL; - - value = PyLong_AsUnsignedLongMask(num); - if (value != ULONG_MAX) - return raiseTestError("test_k_code", - "PyLong_AsUnsignedLongMask() returned wrong value for long 0xFFF...FFF"); - - PyTuple_SET_ITEM(tuple, 0, num); - - value = 0; - if (PyArg_ParseTuple(tuple, "k:test_k_code", &value) < 0) - return NULL; - if (value != ULONG_MAX) - return raiseTestError("test_k_code", - "k code returned wrong value for long 0xFFF...FFF"); - - Py_DECREF(num); - num = PyLong_FromString("-FFFFFFFF000000000000000042", NULL, 16); - if (num == NULL) - return NULL; - - value = PyLong_AsUnsignedLongMask(num); - if (value != (unsigned long)-0x42) - return raiseTestError("test_k_code", - "PyLong_AsUnsignedLongMask() returned wrong value for long 0xFFF...FFF"); - - PyTuple_SET_ITEM(tuple, 0, num); - - value = 0; - if (PyArg_ParseTuple(tuple, "k:test_k_code", &value) < 0) - return NULL; - if (value != (unsigned long)-0x42) - return raiseTestError("test_k_code", - "k code returned wrong value for long -0xFFF..000042"); - - Py_DECREF(tuple); - Py_INCREF(Py_None); - return Py_None; + value = PyLong_AsUnsignedLongMask(num); + if (value != ULONG_MAX) + return raiseTestError("test_k_code", + "PyLong_AsUnsignedLongMask() returned wrong value for long 0xFFF...FFF"); + + PyTuple_SET_ITEM(tuple, 0, num); + + value = 0; + if (PyArg_ParseTuple(tuple, "k:test_k_code", &value) < 0) + return NULL; + if (value != ULONG_MAX) + return raiseTestError("test_k_code", + "k code returned wrong value for long 0xFFF...FFF"); + + Py_DECREF(num); + num = PyLong_FromString("-FFFFFFFF000000000000000042", NULL, 16); + if (num == NULL) + return NULL; + + value = PyLong_AsUnsignedLongMask(num); + if (value != (unsigned long)-0x42) + return raiseTestError("test_k_code", + "PyLong_AsUnsignedLongMask() returned wrong value for long 0xFFF...FFF"); + + PyTuple_SET_ITEM(tuple, 0, num); + + value = 0; + if (PyArg_ParseTuple(tuple, "k:test_k_code", &value) < 0) + return NULL; + if (value != (unsigned long)-0x42) + return raiseTestError("test_k_code", + "k code returned wrong value for long -0xFFF..000042"); + + Py_DECREF(tuple); + Py_INCREF(Py_None); + return Py_None; } @@ -1023,23 +1023,23 @@ tuple = PyTuple_New(1); if (tuple == NULL) - return NULL; + return NULL; obj = PyUnicode_Decode("t\xeate", strlen("t\xeate"), - "latin-1", NULL); + "latin-1", NULL); if (obj == NULL) - return NULL; + return NULL; PyTuple_SET_ITEM(tuple, 0, obj); /* These two blocks used to raise a TypeError: - * "argument must be string without null bytes, not str" + * "argument must be string without null bytes, not str" */ if (PyArg_ParseTuple(tuple, "s:test_s_code1", &value) < 0) - return NULL; + return NULL; if (PyArg_ParseTuple(tuple, "z:test_s_code2", &value) < 0) - return NULL; + return NULL; Py_DECREF(tuple); Py_RETURN_NONE; @@ -1048,46 +1048,46 @@ static PyObject * test_bug_7414(PyObject *self) { - /* Issue #7414: for PyArg_ParseTupleAndKeywords, 'C' code wasn't being - skipped properly in skipitem() */ - int a = 0, b = 0, result; - char *kwlist[] = {"a", "b", NULL}; - PyObject *tuple = NULL, *dict = NULL, *b_str; - - tuple = PyTuple_New(0); - if (tuple == NULL) - goto failure; - dict = PyDict_New(); - if (dict == NULL) - goto failure; - b_str = PyUnicode_FromString("b"); - if (b_str == NULL) - goto failure; - result = PyDict_SetItemString(dict, "b", b_str); - Py_DECREF(b_str); - if (result < 0) - goto failure; - - result = PyArg_ParseTupleAndKeywords(tuple, dict, "|CC", - kwlist, &a, &b); - if (!result) - goto failure; - - if (a != 0) - return raiseTestError("test_bug_7414", - "C format code not skipped properly"); - if (b != 'b') - return raiseTestError("test_bug_7414", - "C format code returned wrong value"); - - Py_DECREF(dict); - Py_DECREF(tuple); - Py_RETURN_NONE; + /* Issue #7414: for PyArg_ParseTupleAndKeywords, 'C' code wasn't being + skipped properly in skipitem() */ + int a = 0, b = 0, result; + char *kwlist[] = {"a", "b", NULL}; + PyObject *tuple = NULL, *dict = NULL, *b_str; + + tuple = PyTuple_New(0); + if (tuple == NULL) + goto failure; + dict = PyDict_New(); + if (dict == NULL) + goto failure; + b_str = PyUnicode_FromString("b"); + if (b_str == NULL) + goto failure; + result = PyDict_SetItemString(dict, "b", b_str); + Py_DECREF(b_str); + if (result < 0) + goto failure; + + result = PyArg_ParseTupleAndKeywords(tuple, dict, "|CC", + kwlist, &a, &b); + if (!result) + goto failure; + + if (a != 0) + return raiseTestError("test_bug_7414", + "C format code not skipped properly"); + if (b != 'b') + return raiseTestError("test_bug_7414", + "C format code returned wrong value"); + + Py_DECREF(dict); + Py_DECREF(tuple); + Py_RETURN_NONE; failure: - Py_XDECREF(dict); - Py_XDECREF(tuple); - return NULL; + Py_XDECREF(dict); + Py_XDECREF(tuple); + return NULL; } @@ -1099,185 +1099,185 @@ static PyObject * test_u_code(PyObject *self) { - PyObject *tuple, *obj; - Py_UNICODE *value; - Py_ssize_t len; - - /* issue4122: Undefined reference to _Py_ascii_whitespace on Windows */ - /* Just use the macro and check that it compiles */ - x = Py_UNICODE_ISSPACE(25); - - tuple = PyTuple_New(1); - if (tuple == NULL) - return NULL; - - obj = PyUnicode_Decode("test", strlen("test"), - "ascii", NULL); - if (obj == NULL) - return NULL; - - PyTuple_SET_ITEM(tuple, 0, obj); - - value = 0; - if (PyArg_ParseTuple(tuple, "u:test_u_code", &value) < 0) - return NULL; - if (value != PyUnicode_AS_UNICODE(obj)) - return raiseTestError("test_u_code", - "u code returned wrong value for u'test'"); - value = 0; - if (PyArg_ParseTuple(tuple, "u#:test_u_code", &value, &len) < 0) - return NULL; - if (value != PyUnicode_AS_UNICODE(obj) || - len != PyUnicode_GET_SIZE(obj)) - return raiseTestError("test_u_code", - "u# code returned wrong values for u'test'"); - - Py_DECREF(tuple); - Py_INCREF(Py_None); - return Py_None; + PyObject *tuple, *obj; + Py_UNICODE *value; + Py_ssize_t len; + + /* issue4122: Undefined reference to _Py_ascii_whitespace on Windows */ + /* Just use the macro and check that it compiles */ + x = Py_UNICODE_ISSPACE(25); + + tuple = PyTuple_New(1); + if (tuple == NULL) + return NULL; + + obj = PyUnicode_Decode("test", strlen("test"), + "ascii", NULL); + if (obj == NULL) + return NULL; + + PyTuple_SET_ITEM(tuple, 0, obj); + + value = 0; + if (PyArg_ParseTuple(tuple, "u:test_u_code", &value) < 0) + return NULL; + if (value != PyUnicode_AS_UNICODE(obj)) + return raiseTestError("test_u_code", + "u code returned wrong value for u'test'"); + value = 0; + if (PyArg_ParseTuple(tuple, "u#:test_u_code", &value, &len) < 0) + return NULL; + if (value != PyUnicode_AS_UNICODE(obj) || + len != PyUnicode_GET_SIZE(obj)) + return raiseTestError("test_u_code", + "u# code returned wrong values for u'test'"); + + Py_DECREF(tuple); + Py_INCREF(Py_None); + return Py_None; } /* Test Z and Z# codes for PyArg_ParseTuple */ static PyObject * test_Z_code(PyObject *self) { - PyObject *tuple, *obj; - Py_UNICODE *value1, *value2; - Py_ssize_t len1, len2; - - tuple = PyTuple_New(2); - if (tuple == NULL) - return NULL; - - obj = PyUnicode_FromString("test"); - PyTuple_SET_ITEM(tuple, 0, obj); - Py_INCREF(Py_None); - PyTuple_SET_ITEM(tuple, 1, Py_None); - - /* swap values on purpose */ - value1 = NULL; - value2 = PyUnicode_AS_UNICODE(obj); - - /* Test Z for both values */ - if (PyArg_ParseTuple(tuple, "ZZ:test_Z_code", &value1, &value2) < 0) - return NULL; - if (value1 != PyUnicode_AS_UNICODE(obj)) - return raiseTestError("test_Z_code", - "Z code returned wrong value for 'test'"); - if (value2 != NULL) - return raiseTestError("test_Z_code", - "Z code returned wrong value for None"); - - value1 = NULL; - value2 = PyUnicode_AS_UNICODE(obj); - len1 = -1; - len2 = -1; - - /* Test Z# for both values */ - if (PyArg_ParseTuple(tuple, "Z#Z#:test_Z_code", &value1, &len1, - &value2, &len2) < 0) - return NULL; - if (value1 != PyUnicode_AS_UNICODE(obj) || - len1 != PyUnicode_GET_SIZE(obj)) - return raiseTestError("test_Z_code", - "Z# code returned wrong values for 'test'"); - if (value2 != NULL || - len2 != 0) - return raiseTestError("test_Z_code", - "Z# code returned wrong values for None'"); + PyObject *tuple, *obj; + Py_UNICODE *value1, *value2; + Py_ssize_t len1, len2; + + tuple = PyTuple_New(2); + if (tuple == NULL) + return NULL; - Py_DECREF(tuple); - Py_RETURN_NONE; + obj = PyUnicode_FromString("test"); + PyTuple_SET_ITEM(tuple, 0, obj); + Py_INCREF(Py_None); + PyTuple_SET_ITEM(tuple, 1, Py_None); + + /* swap values on purpose */ + value1 = NULL; + value2 = PyUnicode_AS_UNICODE(obj); + + /* Test Z for both values */ + if (PyArg_ParseTuple(tuple, "ZZ:test_Z_code", &value1, &value2) < 0) + return NULL; + if (value1 != PyUnicode_AS_UNICODE(obj)) + return raiseTestError("test_Z_code", + "Z code returned wrong value for 'test'"); + if (value2 != NULL) + return raiseTestError("test_Z_code", + "Z code returned wrong value for None"); + + value1 = NULL; + value2 = PyUnicode_AS_UNICODE(obj); + len1 = -1; + len2 = -1; + + /* Test Z# for both values */ + if (PyArg_ParseTuple(tuple, "Z#Z#:test_Z_code", &value1, &len1, + &value2, &len2) < 0) + return NULL; + if (value1 != PyUnicode_AS_UNICODE(obj) || + len1 != PyUnicode_GET_SIZE(obj)) + return raiseTestError("test_Z_code", + "Z# code returned wrong values for 'test'"); + if (value2 != NULL || + len2 != 0) + return raiseTestError("test_Z_code", + "Z# code returned wrong values for None'"); + + Py_DECREF(tuple); + Py_RETURN_NONE; } static PyObject * test_widechar(PyObject *self) { #if defined(SIZEOF_WCHAR_T) && (SIZEOF_WCHAR_T == 4) - const wchar_t wtext[2] = {(wchar_t)0x10ABCDu}; - size_t wtextlen = 1; + const wchar_t wtext[2] = {(wchar_t)0x10ABCDu}; + size_t wtextlen = 1; #else - const wchar_t wtext[3] = {(wchar_t)0xDBEAu, (wchar_t)0xDFCDu}; - size_t wtextlen = 2; + const wchar_t wtext[3] = {(wchar_t)0xDBEAu, (wchar_t)0xDFCDu}; + size_t wtextlen = 2; #endif - PyObject *wide, *utf8; + PyObject *wide, *utf8; + + wide = PyUnicode_FromWideChar(wtext, wtextlen); + if (wide == NULL) + return NULL; + + utf8 = PyUnicode_FromString("\xf4\x8a\xaf\x8d"); + if (utf8 == NULL) { + Py_DECREF(wide); + return NULL; + } - wide = PyUnicode_FromWideChar(wtext, wtextlen); - if (wide == NULL) - return NULL; - - utf8 = PyUnicode_FromString("\xf4\x8a\xaf\x8d"); - if (utf8 == NULL) { - Py_DECREF(wide); - return NULL; - } - - if (PyUnicode_GET_SIZE(wide) != PyUnicode_GET_SIZE(utf8)) { - Py_DECREF(wide); - Py_DECREF(utf8); - return raiseTestError("test_widechar", - "wide string and utf8 string " - "have different length"); - } - if (PyUnicode_Compare(wide, utf8)) { - Py_DECREF(wide); - Py_DECREF(utf8); - if (PyErr_Occurred()) - return NULL; - return raiseTestError("test_widechar", - "wide string and utf8 string " - "are different"); - } - - Py_DECREF(wide); - Py_DECREF(utf8); - Py_RETURN_NONE; + if (PyUnicode_GET_SIZE(wide) != PyUnicode_GET_SIZE(utf8)) { + Py_DECREF(wide); + Py_DECREF(utf8); + return raiseTestError("test_widechar", + "wide string and utf8 string " + "have different length"); + } + if (PyUnicode_Compare(wide, utf8)) { + Py_DECREF(wide); + Py_DECREF(utf8); + if (PyErr_Occurred()) + return NULL; + return raiseTestError("test_widechar", + "wide string and utf8 string " + "are different"); + } + + Py_DECREF(wide); + Py_DECREF(utf8); + Py_RETURN_NONE; } static PyObject * test_empty_argparse(PyObject *self) { - /* Test that formats can begin with '|'. See issue #4720. */ - PyObject *tuple, *dict = NULL; - static char *kwlist[] = {NULL}; - int result; - tuple = PyTuple_New(0); - if (!tuple) - return NULL; - if ((result = PyArg_ParseTuple(tuple, "|:test_empty_argparse")) < 0) - goto done; - dict = PyDict_New(); - if (!dict) - goto done; - result = PyArg_ParseTupleAndKeywords(tuple, dict, "|:test_empty_argparse", kwlist); + /* Test that formats can begin with '|'. See issue #4720. */ + PyObject *tuple, *dict = NULL; + static char *kwlist[] = {NULL}; + int result; + tuple = PyTuple_New(0); + if (!tuple) + return NULL; + if ((result = PyArg_ParseTuple(tuple, "|:test_empty_argparse")) < 0) + goto done; + dict = PyDict_New(); + if (!dict) + goto done; + result = PyArg_ParseTupleAndKeywords(tuple, dict, "|:test_empty_argparse", kwlist); done: - Py_DECREF(tuple); - Py_XDECREF(dict); - if (result < 0) - return NULL; - else { - Py_RETURN_NONE; - } + Py_DECREF(tuple); + Py_XDECREF(dict); + if (result < 0) + return NULL; + else { + Py_RETURN_NONE; + } } static PyObject * codec_incrementalencoder(PyObject *self, PyObject *args) { - const char *encoding, *errors = NULL; - if (!PyArg_ParseTuple(args, "s|s:test_incrementalencoder", - &encoding, &errors)) - return NULL; - return PyCodec_IncrementalEncoder(encoding, errors); + const char *encoding, *errors = NULL; + if (!PyArg_ParseTuple(args, "s|s:test_incrementalencoder", + &encoding, &errors)) + return NULL; + return PyCodec_IncrementalEncoder(encoding, errors); } static PyObject * codec_incrementaldecoder(PyObject *self, PyObject *args) { - const char *encoding, *errors = NULL; - if (!PyArg_ParseTuple(args, "s|s:test_incrementaldecoder", - &encoding, &errors)) - return NULL; - return PyCodec_IncrementalDecoder(encoding, errors); + const char *encoding, *errors = NULL; + if (!PyArg_ParseTuple(args, "s|s:test_incrementaldecoder", + &encoding, &errors)) + return NULL; + return PyCodec_IncrementalDecoder(encoding, errors); } @@ -1285,42 +1285,42 @@ static PyObject * test_long_numbits(PyObject *self) { - struct triple { - long input; - size_t nbits; - int sign; - } testcases[] = {{0, 0, 0}, - {1L, 1, 1}, - {-1L, 1, -1}, - {2L, 2, 1}, - {-2L, 2, -1}, - {3L, 2, 1}, - {-3L, 2, -1}, - {4L, 3, 1}, - {-4L, 3, -1}, - {0x7fffL, 15, 1}, /* one Python long digit */ - {-0x7fffL, 15, -1}, - {0xffffL, 16, 1}, - {-0xffffL, 16, -1}, - {0xfffffffL, 28, 1}, - {-0xfffffffL, 28, -1}}; - int i; - - for (i = 0; i < sizeof(testcases) / sizeof(struct triple); ++i) { - PyObject *plong = PyLong_FromLong(testcases[i].input); - size_t nbits = _PyLong_NumBits(plong); - int sign = _PyLong_Sign(plong); - - Py_DECREF(plong); - if (nbits != testcases[i].nbits) - return raiseTestError("test_long_numbits", - "wrong result for _PyLong_NumBits"); - if (sign != testcases[i].sign) - return raiseTestError("test_long_numbits", - "wrong result for _PyLong_Sign"); - } - Py_INCREF(Py_None); - return Py_None; + struct triple { + long input; + size_t nbits; + int sign; + } testcases[] = {{0, 0, 0}, + {1L, 1, 1}, + {-1L, 1, -1}, + {2L, 2, 1}, + {-2L, 2, -1}, + {3L, 2, 1}, + {-3L, 2, -1}, + {4L, 3, 1}, + {-4L, 3, -1}, + {0x7fffL, 15, 1}, /* one Python long digit */ + {-0x7fffL, 15, -1}, + {0xffffL, 16, 1}, + {-0xffffL, 16, -1}, + {0xfffffffL, 28, 1}, + {-0xfffffffL, 28, -1}}; + int i; + + for (i = 0; i < sizeof(testcases) / sizeof(struct triple); ++i) { + PyObject *plong = PyLong_FromLong(testcases[i].input); + size_t nbits = _PyLong_NumBits(plong); + int sign = _PyLong_Sign(plong); + + Py_DECREF(plong); + if (nbits != testcases[i].nbits) + return raiseTestError("test_long_numbits", + "wrong result for _PyLong_NumBits"); + if (sign != testcases[i].sign) + return raiseTestError("test_long_numbits", + "wrong result for _PyLong_Sign"); + } + Py_INCREF(Py_None); + return Py_None; } /* Example passing NULLs to PyObject_Str(NULL). */ @@ -1328,38 +1328,38 @@ static PyObject * test_null_strings(PyObject *self) { - PyObject *o1 = PyObject_Str(NULL), *o2 = PyObject_Str(NULL); - PyObject *tuple = PyTuple_Pack(2, o1, o2); - Py_XDECREF(o1); - Py_XDECREF(o2); - return tuple; + PyObject *o1 = PyObject_Str(NULL), *o2 = PyObject_Str(NULL); + PyObject *tuple = PyTuple_Pack(2, o1, o2); + Py_XDECREF(o1); + Py_XDECREF(o2); + return tuple; } static PyObject * raise_exception(PyObject *self, PyObject *args) { - PyObject *exc; - PyObject *exc_args, *v; - int num_args, i; - - if (!PyArg_ParseTuple(args, "Oi:raise_exception", - &exc, &num_args)) - return NULL; - - exc_args = PyTuple_New(num_args); - if (exc_args == NULL) - return NULL; - for (i = 0; i < num_args; ++i) { - v = PyLong_FromLong(i); - if (v == NULL) { - Py_DECREF(exc_args); - return NULL; - } - PyTuple_SET_ITEM(exc_args, i, v); - } - PyErr_SetObject(exc, exc_args); - Py_DECREF(exc_args); - return NULL; + PyObject *exc; + PyObject *exc_args, *v; + int num_args, i; + + if (!PyArg_ParseTuple(args, "Oi:raise_exception", + &exc, &num_args)) + return NULL; + + exc_args = PyTuple_New(num_args); + if (exc_args == NULL) + return NULL; + for (i = 0; i < num_args; ++i) { + v = PyLong_FromLong(i); + if (v == NULL) { + Py_DECREF(exc_args); + return NULL; + } + PyTuple_SET_ITEM(exc_args, i, v); + } + PyErr_SetObject(exc, exc_args); + Py_DECREF(exc_args); + return NULL; } @@ -1367,23 +1367,23 @@ static PyObject * test_datetime_capi(PyObject *self, PyObject *args) { - if (PyDateTimeAPI) { - if (test_run_counter) { - /* Probably regrtest.py -R */ - Py_RETURN_NONE; - } - else { - PyErr_SetString(PyExc_AssertionError, - "PyDateTime_CAPI somehow initialized"); - return NULL; - } - } - test_run_counter++; - PyDateTime_IMPORT; - if (PyDateTimeAPI) - Py_RETURN_NONE; - else - return NULL; + if (PyDateTimeAPI) { + if (test_run_counter) { + /* Probably regrtest.py -R */ + Py_RETURN_NONE; + } + else { + PyErr_SetString(PyExc_AssertionError, + "PyDateTime_CAPI somehow initialized"); + return NULL; + } + } + test_run_counter++; + PyDateTime_IMPORT; + if (PyDateTimeAPI) + Py_RETURN_NONE; + else + return NULL; } @@ -1401,14 +1401,14 @@ static int _make_call(void *callable) { - PyObject *rc; - int success; - PyGILState_STATE s = PyGILState_Ensure(); - rc = PyObject_CallFunction((PyObject *)callable, ""); - success = (rc != NULL); - Py_XDECREF(rc); - PyGILState_Release(s); - return success; + PyObject *rc; + int success; + PyGILState_STATE s = PyGILState_Ensure(); + rc = PyObject_CallFunction((PyObject *)callable, ""); + success = (rc != NULL); + Py_XDECREF(rc); + PyGILState_Release(s); + return success; } /* Same thing, but releases `thread_done` when it returns. This variant @@ -1417,70 +1417,70 @@ static void _make_call_from_thread(void *callable) { - _make_call(callable); - PyThread_release_lock(thread_done); + _make_call(callable); + PyThread_release_lock(thread_done); } static PyObject * test_thread_state(PyObject *self, PyObject *args) { - PyObject *fn; - int success = 1; + PyObject *fn; + int success = 1; - if (!PyArg_ParseTuple(args, "O:test_thread_state", &fn)) - return NULL; + if (!PyArg_ParseTuple(args, "O:test_thread_state", &fn)) + return NULL; + + if (!PyCallable_Check(fn)) { + PyErr_Format(PyExc_TypeError, "'%s' object is not callable", + fn->ob_type->tp_name); + return NULL; + } - if (!PyCallable_Check(fn)) { - PyErr_Format(PyExc_TypeError, "'%s' object is not callable", - fn->ob_type->tp_name); - return NULL; - } - - /* Ensure Python is set up for threading */ - PyEval_InitThreads(); - thread_done = PyThread_allocate_lock(); - if (thread_done == NULL) - return PyErr_NoMemory(); - PyThread_acquire_lock(thread_done, 1); - - /* Start a new thread with our callback. */ - PyThread_start_new_thread(_make_call_from_thread, fn); - /* Make the callback with the thread lock held by this thread */ - success &= _make_call(fn); - /* Do it all again, but this time with the thread-lock released */ - Py_BEGIN_ALLOW_THREADS - success &= _make_call(fn); - PyThread_acquire_lock(thread_done, 1); /* wait for thread to finish */ - Py_END_ALLOW_THREADS - - /* And once more with and without a thread - XXX - should use a lock and work out exactly what we are trying - to test - */ - Py_BEGIN_ALLOW_THREADS - PyThread_start_new_thread(_make_call_from_thread, fn); - success &= _make_call(fn); - PyThread_acquire_lock(thread_done, 1); /* wait for thread to finish */ - Py_END_ALLOW_THREADS - - /* Release lock we acquired above. This is required on HP-UX. */ - PyThread_release_lock(thread_done); - - PyThread_free_lock(thread_done); - if (!success) - return NULL; - Py_RETURN_NONE; + /* Ensure Python is set up for threading */ + PyEval_InitThreads(); + thread_done = PyThread_allocate_lock(); + if (thread_done == NULL) + return PyErr_NoMemory(); + PyThread_acquire_lock(thread_done, 1); + + /* Start a new thread with our callback. */ + PyThread_start_new_thread(_make_call_from_thread, fn); + /* Make the callback with the thread lock held by this thread */ + success &= _make_call(fn); + /* Do it all again, but this time with the thread-lock released */ + Py_BEGIN_ALLOW_THREADS + success &= _make_call(fn); + PyThread_acquire_lock(thread_done, 1); /* wait for thread to finish */ + Py_END_ALLOW_THREADS + + /* And once more with and without a thread + XXX - should use a lock and work out exactly what we are trying + to test + */ + Py_BEGIN_ALLOW_THREADS + PyThread_start_new_thread(_make_call_from_thread, fn); + success &= _make_call(fn); + PyThread_acquire_lock(thread_done, 1); /* wait for thread to finish */ + Py_END_ALLOW_THREADS + + /* Release lock we acquired above. This is required on HP-UX. */ + PyThread_release_lock(thread_done); + + PyThread_free_lock(thread_done); + if (!success) + return NULL; + Py_RETURN_NONE; } /* test Py_AddPendingCalls using threads */ static int _pending_callback(void *arg) { - /* we assume the argument is callable object to which we own a reference */ - PyObject *callable = (PyObject *)arg; - PyObject *r = PyObject_CallObject(callable, NULL); - Py_DECREF(callable); - Py_XDECREF(r); - return r != NULL ? 0 : -1; + /* we assume the argument is callable object to which we own a reference */ + PyObject *callable = (PyObject *)arg; + PyObject *r = PyObject_CallObject(callable, NULL); + Py_DECREF(callable); + Py_XDECREF(r); + return r != NULL ? 0 : -1; } /* The following requests n callbacks to _pending_callback. It can be @@ -1488,25 +1488,25 @@ */ PyObject *pending_threadfunc(PyObject *self, PyObject *arg) { - PyObject *callable; - int r; - if (PyArg_ParseTuple(arg, "O", &callable) == 0) - return NULL; - - /* create the reference for the callbackwhile we hold the lock */ - Py_INCREF(callable); - - Py_BEGIN_ALLOW_THREADS - r = Py_AddPendingCall(&_pending_callback, callable); - Py_END_ALLOW_THREADS - - if (r<0) { - Py_DECREF(callable); /* unsuccessful add, destroy the extra reference */ - Py_INCREF(Py_False); - return Py_False; - } - Py_INCREF(Py_True); - return Py_True; + PyObject *callable; + int r; + if (PyArg_ParseTuple(arg, "O", &callable) == 0) + return NULL; + + /* create the reference for the callbackwhile we hold the lock */ + Py_INCREF(callable); + + Py_BEGIN_ALLOW_THREADS + r = Py_AddPendingCall(&_pending_callback, callable); + Py_END_ALLOW_THREADS + + if (r<0) { + Py_DECREF(callable); /* unsuccessful add, destroy the extra reference */ + Py_INCREF(Py_False); + return Py_False; + } + Py_INCREF(Py_True); + return Py_True; } #endif @@ -1514,40 +1514,40 @@ static PyObject * test_string_from_format(PyObject *self, PyObject *args) { - PyObject *result; - char *msg; + PyObject *result; + char *msg; -#define CHECK_1_FORMAT(FORMAT, TYPE) \ - result = PyUnicode_FromFormat(FORMAT, (TYPE)1); \ - if (result == NULL) \ - return NULL; \ - if (strcmp(_PyUnicode_AsString(result), "1")) { \ - msg = FORMAT " failed at 1"; \ - goto Fail; \ - } \ - Py_DECREF(result) - - CHECK_1_FORMAT("%d", int); - CHECK_1_FORMAT("%ld", long); - /* The z width modifier was added in Python 2.5. */ - CHECK_1_FORMAT("%zd", Py_ssize_t); - - /* The u type code was added in Python 2.5. */ - CHECK_1_FORMAT("%u", unsigned int); - CHECK_1_FORMAT("%lu", unsigned long); - CHECK_1_FORMAT("%zu", size_t); +#define CHECK_1_FORMAT(FORMAT, TYPE) \ + result = PyUnicode_FromFormat(FORMAT, (TYPE)1); \ + if (result == NULL) \ + return NULL; \ + if (strcmp(_PyUnicode_AsString(result), "1")) { \ + msg = FORMAT " failed at 1"; \ + goto Fail; \ + } \ + Py_DECREF(result) + + CHECK_1_FORMAT("%d", int); + CHECK_1_FORMAT("%ld", long); + /* The z width modifier was added in Python 2.5. */ + CHECK_1_FORMAT("%zd", Py_ssize_t); + + /* The u type code was added in Python 2.5. */ + CHECK_1_FORMAT("%u", unsigned int); + CHECK_1_FORMAT("%lu", unsigned long); + CHECK_1_FORMAT("%zu", size_t); - /* "%lld" and "%llu" support added in Python 2.7. */ + /* "%lld" and "%llu" support added in Python 2.7. */ #ifdef HAVE_LONG_LONG - CHECK_1_FORMAT("%llu", unsigned PY_LONG_LONG); - CHECK_1_FORMAT("%lld", PY_LONG_LONG); + CHECK_1_FORMAT("%llu", unsigned PY_LONG_LONG); + CHECK_1_FORMAT("%lld", PY_LONG_LONG); #endif - Py_RETURN_NONE; + Py_RETURN_NONE; Fail: - Py_XDECREF(result); - return raiseTestError("test_string_from_format", msg); + Py_XDECREF(result); + return raiseTestError("test_string_from_format", msg); #undef CHECK_1_FORMAT } @@ -1555,70 +1555,70 @@ static PyObject * test_unicode_compare_with_ascii(PyObject *self) { - PyObject *py_s = PyUnicode_FromStringAndSize("str\0", 4); - int result; - if (py_s == NULL) - return NULL; - result = PyUnicode_CompareWithASCIIString(py_s, "str"); - Py_DECREF(py_s); - if (!result) { - PyErr_SetString(TestError, "Python string ending in NULL " - "should not compare equal to c string."); - return NULL; - } - Py_RETURN_NONE; + PyObject *py_s = PyUnicode_FromStringAndSize("str\0", 4); + int result; + if (py_s == NULL) + return NULL; + result = PyUnicode_CompareWithASCIIString(py_s, "str"); + Py_DECREF(py_s); + if (!result) { + PyErr_SetString(TestError, "Python string ending in NULL " + "should not compare equal to c string."); + return NULL; + } + Py_RETURN_NONE; }; /* This is here to provide a docstring for test_descr. */ static PyObject * test_with_docstring(PyObject *self) { - Py_RETURN_NONE; + Py_RETURN_NONE; } /* Test PyOS_string_to_double. */ static PyObject * test_string_to_double(PyObject *self) { - double result; - char *msg; + double result; + char *msg; -#define CHECK_STRING(STR, expected) \ - result = PyOS_string_to_double(STR, NULL, NULL); \ - if (result == -1.0 && PyErr_Occurred()) \ - return NULL; \ - if (result != expected) { \ - msg = "conversion of " STR " to float failed"; \ - goto fail; \ - } - -#define CHECK_INVALID(STR) \ - result = PyOS_string_to_double(STR, NULL, NULL); \ - if (result == -1.0 && PyErr_Occurred()) { \ - if (PyErr_ExceptionMatches(PyExc_ValueError)) \ - PyErr_Clear(); \ - else \ - return NULL; \ - } \ - else { \ - msg = "conversion of " STR " didn't raise ValueError"; \ - goto fail; \ - } - - CHECK_STRING("0.1", 0.1); - CHECK_STRING("1.234", 1.234); - CHECK_STRING("-1.35", -1.35); - CHECK_STRING(".1e01", 1.0); - CHECK_STRING("2.e-2", 0.02); - - CHECK_INVALID(" 0.1"); - CHECK_INVALID("\t\n-3"); - CHECK_INVALID(".123 "); - CHECK_INVALID("3\n"); - CHECK_INVALID("123abc"); +#define CHECK_STRING(STR, expected) \ + result = PyOS_string_to_double(STR, NULL, NULL); \ + if (result == -1.0 && PyErr_Occurred()) \ + return NULL; \ + if (result != expected) { \ + msg = "conversion of " STR " to float failed"; \ + goto fail; \ + } + +#define CHECK_INVALID(STR) \ + result = PyOS_string_to_double(STR, NULL, NULL); \ + if (result == -1.0 && PyErr_Occurred()) { \ + if (PyErr_ExceptionMatches(PyExc_ValueError)) \ + PyErr_Clear(); \ + else \ + return NULL; \ + } \ + else { \ + msg = "conversion of " STR " didn't raise ValueError"; \ + goto fail; \ + } + + CHECK_STRING("0.1", 0.1); + CHECK_STRING("1.234", 1.234); + CHECK_STRING("-1.35", -1.35); + CHECK_STRING(".1e01", 1.0); + CHECK_STRING("2.e-2", 0.02); + + CHECK_INVALID(" 0.1"); + CHECK_INVALID("\t\n-3"); + CHECK_INVALID(".123 "); + CHECK_INVALID("3\n"); + CHECK_INVALID("123abc"); - Py_RETURN_NONE; + Py_RETURN_NONE; fail: - return raiseTestError("test_string_to_double", msg); + return raiseTestError("test_string_to_double", msg); #undef CHECK_STRING #undef CHECK_INVALID } @@ -1635,143 +1635,143 @@ static void capsule_destructor(PyObject *o) { - capsule_destructor_call_count++; - if (PyCapsule_GetContext(o) != capsule_context) { - capsule_error = "context did not match in destructor!"; - } else if (PyCapsule_GetDestructor(o) != capsule_destructor) { - capsule_error = "destructor did not match in destructor! (woah!)"; - } else if (PyCapsule_GetName(o) != capsule_name) { - capsule_error = "name did not match in destructor!"; - } else if (PyCapsule_GetPointer(o, capsule_name) != capsule_pointer) { - capsule_error = "pointer did not match in destructor!"; - } + capsule_destructor_call_count++; + if (PyCapsule_GetContext(o) != capsule_context) { + capsule_error = "context did not match in destructor!"; + } else if (PyCapsule_GetDestructor(o) != capsule_destructor) { + capsule_error = "destructor did not match in destructor! (woah!)"; + } else if (PyCapsule_GetName(o) != capsule_name) { + capsule_error = "name did not match in destructor!"; + } else if (PyCapsule_GetPointer(o, capsule_name) != capsule_pointer) { + capsule_error = "pointer did not match in destructor!"; + } } typedef struct { - char *name; - char *module; - char *attribute; + char *name; + char *module; + char *attribute; } known_capsule; static PyObject * test_capsule(PyObject *self, PyObject *args) { - PyObject *object; - const char *error = NULL; - void *pointer; - void *pointer2; - known_capsule known_capsules[] = { - #define KNOWN_CAPSULE(module, name) { module "." name, module, name } - KNOWN_CAPSULE("_socket", "CAPI"), - KNOWN_CAPSULE("_curses", "_C_API"), - KNOWN_CAPSULE("datetime", "datetime_CAPI"), - { NULL, NULL }, - }; - known_capsule *known = &known_capsules[0]; + PyObject *object; + const char *error = NULL; + void *pointer; + void *pointer2; + known_capsule known_capsules[] = { + #define KNOWN_CAPSULE(module, name) { module "." name, module, name } + KNOWN_CAPSULE("_socket", "CAPI"), + KNOWN_CAPSULE("_curses", "_C_API"), + KNOWN_CAPSULE("datetime", "datetime_CAPI"), + { NULL, NULL }, + }; + known_capsule *known = &known_capsules[0]; #define FAIL(x) { error = (x); goto exit; } #define CHECK_DESTRUCTOR \ - if (capsule_error) { \ - FAIL(capsule_error); \ - } \ - else if (!capsule_destructor_call_count) { \ - FAIL("destructor not called!"); \ - } \ - capsule_destructor_call_count = 0; \ - - object = PyCapsule_New(capsule_pointer, capsule_name, capsule_destructor); - PyCapsule_SetContext(object, capsule_context); - capsule_destructor(object); - CHECK_DESTRUCTOR; - Py_DECREF(object); - CHECK_DESTRUCTOR; - - object = PyCapsule_New(known, "ignored", NULL); - PyCapsule_SetPointer(object, capsule_pointer); - PyCapsule_SetName(object, capsule_name); - PyCapsule_SetDestructor(object, capsule_destructor); - PyCapsule_SetContext(object, capsule_context); - capsule_destructor(object); - CHECK_DESTRUCTOR; - /* intentionally access using the wrong name */ - pointer2 = PyCapsule_GetPointer(object, "the wrong name"); - if (!PyErr_Occurred()) { - FAIL("PyCapsule_GetPointer should have failed but did not!"); - } - PyErr_Clear(); - if (pointer2) { - if (pointer2 == capsule_pointer) { - FAIL("PyCapsule_GetPointer should not have" - " returned the internal pointer!"); - } else { - FAIL("PyCapsule_GetPointer should have " - "returned NULL pointer but did not!"); - } - } - PyCapsule_SetDestructor(object, NULL); - Py_DECREF(object); - if (capsule_destructor_call_count) { - FAIL("destructor called when it should not have been!"); - } - - for (known = &known_capsules[0]; known->module != NULL; known++) { - /* yeah, ordinarily I wouldn't do this either, - but it's fine for this test harness. - */ - static char buffer[256]; + if (capsule_error) { \ + FAIL(capsule_error); \ + } \ + else if (!capsule_destructor_call_count) { \ + FAIL("destructor not called!"); \ + } \ + capsule_destructor_call_count = 0; \ + + object = PyCapsule_New(capsule_pointer, capsule_name, capsule_destructor); + PyCapsule_SetContext(object, capsule_context); + capsule_destructor(object); + CHECK_DESTRUCTOR; + Py_DECREF(object); + CHECK_DESTRUCTOR; + + object = PyCapsule_New(known, "ignored", NULL); + PyCapsule_SetPointer(object, capsule_pointer); + PyCapsule_SetName(object, capsule_name); + PyCapsule_SetDestructor(object, capsule_destructor); + PyCapsule_SetContext(object, capsule_context); + capsule_destructor(object); + CHECK_DESTRUCTOR; + /* intentionally access using the wrong name */ + pointer2 = PyCapsule_GetPointer(object, "the wrong name"); + if (!PyErr_Occurred()) { + FAIL("PyCapsule_GetPointer should have failed but did not!"); + } + PyErr_Clear(); + if (pointer2) { + if (pointer2 == capsule_pointer) { + FAIL("PyCapsule_GetPointer should not have" + " returned the internal pointer!"); + } else { + FAIL("PyCapsule_GetPointer should have " + "returned NULL pointer but did not!"); + } + } + PyCapsule_SetDestructor(object, NULL); + Py_DECREF(object); + if (capsule_destructor_call_count) { + FAIL("destructor called when it should not have been!"); + } + + for (known = &known_capsules[0]; known->module != NULL; known++) { + /* yeah, ordinarily I wouldn't do this either, + but it's fine for this test harness. + */ + static char buffer[256]; #undef FAIL #define FAIL(x) \ - { \ - sprintf(buffer, "%s module: \"%s\" attribute: \"%s\"", \ - x, known->module, known->attribute); \ - error = buffer; \ - goto exit; \ - } \ - - PyObject *module = PyImport_ImportModule(known->module); - if (module) { - pointer = PyCapsule_Import(known->name, 0); - if (!pointer) { - Py_DECREF(module); - FAIL("PyCapsule_GetPointer returned NULL unexpectedly!"); - } - object = PyObject_GetAttrString(module, known->attribute); - if (!object) { - Py_DECREF(module); - return NULL; - } - pointer2 = PyCapsule_GetPointer(object, - "weebles wobble but they don't fall down"); - if (!PyErr_Occurred()) { - Py_DECREF(object); - Py_DECREF(module); - FAIL("PyCapsule_GetPointer should have failed but did not!"); - } - PyErr_Clear(); - if (pointer2) { - Py_DECREF(module); - Py_DECREF(object); - if (pointer2 == pointer) { - FAIL("PyCapsule_GetPointer should not have" - " returned its internal pointer!"); - } else { - FAIL("PyCapsule_GetPointer should have" - " returned NULL pointer but did not!"); - } - } - Py_DECREF(object); - Py_DECREF(module); - } - else - PyErr_Clear(); - } + { \ + sprintf(buffer, "%s module: \"%s\" attribute: \"%s\"", \ + x, known->module, known->attribute); \ + error = buffer; \ + goto exit; \ + } \ + + PyObject *module = PyImport_ImportModule(known->module); + if (module) { + pointer = PyCapsule_Import(known->name, 0); + if (!pointer) { + Py_DECREF(module); + FAIL("PyCapsule_GetPointer returned NULL unexpectedly!"); + } + object = PyObject_GetAttrString(module, known->attribute); + if (!object) { + Py_DECREF(module); + return NULL; + } + pointer2 = PyCapsule_GetPointer(object, + "weebles wobble but they don't fall down"); + if (!PyErr_Occurred()) { + Py_DECREF(object); + Py_DECREF(module); + FAIL("PyCapsule_GetPointer should have failed but did not!"); + } + PyErr_Clear(); + if (pointer2) { + Py_DECREF(module); + Py_DECREF(object); + if (pointer2 == pointer) { + FAIL("PyCapsule_GetPointer should not have" + " returned its internal pointer!"); + } else { + FAIL("PyCapsule_GetPointer should have" + " returned NULL pointer but did not!"); + } + } + Py_DECREF(object); + Py_DECREF(module); + } + else + PyErr_Clear(); + } exit: - if (error) { - return raiseTestError("test_capsule", error); - } - Py_RETURN_NONE; + if (error) { + return raiseTestError("test_capsule", error); + } + Py_RETURN_NONE; #undef FAIL } @@ -1779,112 +1779,112 @@ /* Profiling of integer performance */ static void print_delta(int test, struct timeval *s, struct timeval *e) { - e->tv_sec -= s->tv_sec; - e->tv_usec -= s->tv_usec; - if (e->tv_usec < 0) { - e->tv_sec -=1; - e->tv_usec += 1000000; - } - printf("Test %d: %d.%06ds\n", test, (int)e->tv_sec, (int)e->tv_usec); + e->tv_sec -= s->tv_sec; + e->tv_usec -= s->tv_usec; + if (e->tv_usec < 0) { + e->tv_sec -=1; + e->tv_usec += 1000000; + } + printf("Test %d: %d.%06ds\n", test, (int)e->tv_sec, (int)e->tv_usec); } static PyObject * profile_int(PyObject *self, PyObject* args) { - int i, k; - struct timeval start, stop; - PyObject *single, **multiple, *op1, *result; - - /* Test 1: Allocate and immediately deallocate - many small integers */ - gettimeofday(&start, NULL); - for(k=0; k < 20000; k++) - for(i=0; i < 1000; i++) { - single = PyLong_FromLong(i); - Py_DECREF(single); - } - gettimeofday(&stop, NULL); - print_delta(1, &start, &stop); - - /* Test 2: Allocate and immediately deallocate - many large integers */ - gettimeofday(&start, NULL); - for(k=0; k < 20000; k++) - for(i=0; i < 1000; i++) { - single = PyLong_FromLong(i+1000000); - Py_DECREF(single); - } - gettimeofday(&stop, NULL); - print_delta(2, &start, &stop); - - /* Test 3: Allocate a few integers, then release - them all simultaneously. */ - multiple = malloc(sizeof(PyObject*) * 1000); - gettimeofday(&start, NULL); - for(k=0; k < 20000; k++) { - for(i=0; i < 1000; i++) { - multiple[i] = PyLong_FromLong(i+1000000); - } - for(i=0; i < 1000; i++) { - Py_DECREF(multiple[i]); - } - } - gettimeofday(&stop, NULL); - print_delta(3, &start, &stop); - - /* Test 4: Allocate many integers, then release - them all simultaneously. */ - multiple = malloc(sizeof(PyObject*) * 1000000); - gettimeofday(&start, NULL); - for(k=0; k < 20; k++) { - for(i=0; i < 1000000; i++) { - multiple[i] = PyLong_FromLong(i+1000000); - } - for(i=0; i < 1000000; i++) { - Py_DECREF(multiple[i]); - } - } - gettimeofday(&stop, NULL); - print_delta(4, &start, &stop); - - /* Test 5: Allocate many integers < 32000 */ - multiple = malloc(sizeof(PyObject*) * 1000000); - gettimeofday(&start, NULL); - for(k=0; k < 10; k++) { - for(i=0; i < 1000000; i++) { - multiple[i] = PyLong_FromLong(i+1000); - } - for(i=0; i < 1000000; i++) { - Py_DECREF(multiple[i]); - } - } - gettimeofday(&stop, NULL); - print_delta(5, &start, &stop); - - /* Test 6: Perform small int addition */ - op1 = PyLong_FromLong(1); - gettimeofday(&start, NULL); - for(i=0; i < 10000000; i++) { - result = PyNumber_Add(op1, op1); - Py_DECREF(result); - } - gettimeofday(&stop, NULL); - Py_DECREF(op1); - print_delta(6, &start, &stop); - - /* Test 7: Perform medium int addition */ - op1 = PyLong_FromLong(1000); - gettimeofday(&start, NULL); - for(i=0; i < 10000000; i++) { - result = PyNumber_Add(op1, op1); - Py_DECREF(result); - } - gettimeofday(&stop, NULL); - Py_DECREF(op1); - print_delta(7, &start, &stop); + int i, k; + struct timeval start, stop; + PyObject *single, **multiple, *op1, *result; + + /* Test 1: Allocate and immediately deallocate + many small integers */ + gettimeofday(&start, NULL); + for(k=0; k < 20000; k++) + for(i=0; i < 1000; i++) { + single = PyLong_FromLong(i); + Py_DECREF(single); + } + gettimeofday(&stop, NULL); + print_delta(1, &start, &stop); + + /* Test 2: Allocate and immediately deallocate + many large integers */ + gettimeofday(&start, NULL); + for(k=0; k < 20000; k++) + for(i=0; i < 1000; i++) { + single = PyLong_FromLong(i+1000000); + Py_DECREF(single); + } + gettimeofday(&stop, NULL); + print_delta(2, &start, &stop); + + /* Test 3: Allocate a few integers, then release + them all simultaneously. */ + multiple = malloc(sizeof(PyObject*) * 1000); + gettimeofday(&start, NULL); + for(k=0; k < 20000; k++) { + for(i=0; i < 1000; i++) { + multiple[i] = PyLong_FromLong(i+1000000); + } + for(i=0; i < 1000; i++) { + Py_DECREF(multiple[i]); + } + } + gettimeofday(&stop, NULL); + print_delta(3, &start, &stop); + + /* Test 4: Allocate many integers, then release + them all simultaneously. */ + multiple = malloc(sizeof(PyObject*) * 1000000); + gettimeofday(&start, NULL); + for(k=0; k < 20; k++) { + for(i=0; i < 1000000; i++) { + multiple[i] = PyLong_FromLong(i+1000000); + } + for(i=0; i < 1000000; i++) { + Py_DECREF(multiple[i]); + } + } + gettimeofday(&stop, NULL); + print_delta(4, &start, &stop); + + /* Test 5: Allocate many integers < 32000 */ + multiple = malloc(sizeof(PyObject*) * 1000000); + gettimeofday(&start, NULL); + for(k=0; k < 10; k++) { + for(i=0; i < 1000000; i++) { + multiple[i] = PyLong_FromLong(i+1000); + } + for(i=0; i < 1000000; i++) { + Py_DECREF(multiple[i]); + } + } + gettimeofday(&stop, NULL); + print_delta(5, &start, &stop); + + /* Test 6: Perform small int addition */ + op1 = PyLong_FromLong(1); + gettimeofday(&start, NULL); + for(i=0; i < 10000000; i++) { + result = PyNumber_Add(op1, op1); + Py_DECREF(result); + } + gettimeofday(&stop, NULL); + Py_DECREF(op1); + print_delta(6, &start, &stop); + + /* Test 7: Perform medium int addition */ + op1 = PyLong_FromLong(1000); + gettimeofday(&start, NULL); + for(i=0; i < 10000000; i++) { + result = PyNumber_Add(op1, op1); + Py_DECREF(result); + } + gettimeofday(&stop, NULL); + Py_DECREF(op1); + print_delta(7, &start, &stop); - Py_INCREF(Py_None); - return Py_None; + Py_INCREF(Py_None); + return Py_None; } #endif @@ -1892,40 +1892,40 @@ static PyObject * traceback_print(PyObject *self, PyObject *args) { - PyObject *file; - PyObject *traceback; - int result; - - if (!PyArg_ParseTuple(args, "OO:traceback_print", - &traceback, &file)) - return NULL; - - result = PyTraceBack_Print(traceback, file); - if (result < 0) - return NULL; - Py_RETURN_NONE; + PyObject *file; + PyObject *traceback; + int result; + + if (!PyArg_ParseTuple(args, "OO:traceback_print", + &traceback, &file)) + return NULL; + + result = PyTraceBack_Print(traceback, file); + if (result < 0) + return NULL; + Py_RETURN_NONE; } /* To test the format of exceptions as printed out. */ static PyObject * exception_print(PyObject *self, PyObject *args) { - PyObject *value; - PyObject *tb; + PyObject *value; + PyObject *tb; - if (!PyArg_ParseTuple(args, "O:exception_print", - &value)) - return NULL; - if (!PyExceptionInstance_Check(value)) { - PyErr_Format(PyExc_TypeError, "an exception instance is required"); - return NULL; - } - - tb = PyException_GetTraceback(value); - PyErr_Display((PyObject *) Py_TYPE(value), value, tb); - Py_XDECREF(tb); + if (!PyArg_ParseTuple(args, "O:exception_print", + &value)) + return NULL; + if (!PyExceptionInstance_Check(value)) { + PyErr_Format(PyExc_TypeError, "an exception instance is required"); + return NULL; + } - Py_RETURN_NONE; + tb = PyException_GetTraceback(value); + PyErr_Display((PyObject *) Py_TYPE(value), value, tb); + Py_XDECREF(tb); + + Py_RETURN_NONE; } @@ -1935,8 +1935,8 @@ static PyObject * raise_memoryerror(PyObject *self) { - PyErr_NoMemory(); - return NULL; + PyErr_NoMemory(); + return NULL; } /* Issue 6012 */ @@ -1944,45 +1944,45 @@ static int failing_converter(PyObject *obj, void *arg) { - /* Clone str1, then let the conversion fail. */ - assert(str1); - str2 = str1; - Py_INCREF(str2); - return 0; + /* Clone str1, then let the conversion fail. */ + assert(str1); + str2 = str1; + Py_INCREF(str2); + return 0; } static PyObject* argparsing(PyObject *o, PyObject *args) { - PyObject *res; - str1 = str2 = NULL; - if (!PyArg_ParseTuple(args, "O&O&", - PyUnicode_FSConverter, &str1, - failing_converter, &str2)) { - if (!str2) - /* argument converter not called? */ - return NULL; - /* Should be 1 */ - res = PyLong_FromLong(Py_REFCNT(str2)); - Py_DECREF(str2); - PyErr_Clear(); - return res; - } - Py_RETURN_NONE; + PyObject *res; + str1 = str2 = NULL; + if (!PyArg_ParseTuple(args, "O&O&", + PyUnicode_FSConverter, &str1, + failing_converter, &str2)) { + if (!str2) + /* argument converter not called? */ + return NULL; + /* Should be 1 */ + res = PyLong_FromLong(Py_REFCNT(str2)); + Py_DECREF(str2); + PyErr_Clear(); + return res; + } + Py_RETURN_NONE; } /* To test that the result of PyCode_NewEmpty has the right members. */ static PyObject * code_newempty(PyObject *self, PyObject *args) { - const char *filename; - const char *funcname; - int firstlineno; - - if (!PyArg_ParseTuple(args, "ssi:code_newempty", - &filename, &funcname, &firstlineno)) - return NULL; + const char *filename; + const char *funcname; + int firstlineno; - return (PyObject *)PyCode_NewEmpty(filename, funcname, firstlineno); + if (!PyArg_ParseTuple(args, "ssi:code_newempty", + &filename, &funcname, &firstlineno)) + return NULL; + + return (PyObject *)PyCode_NewEmpty(filename, funcname, firstlineno); } /* Test PyErr_NewExceptionWithDoc (also exercise PyErr_NewException). @@ -1990,302 +1990,302 @@ static PyObject * make_exception_with_doc(PyObject *self, PyObject *args, PyObject *kwargs) { - const char *name; - const char *doc = NULL; - PyObject *base = NULL; - PyObject *dict = NULL; - - static char *kwlist[] = {"name", "doc", "base", "dict", NULL}; - - if (!PyArg_ParseTupleAndKeywords(args, kwargs, - "s|sOO:make_exception_with_doc", kwlist, - &name, &doc, &base, &dict)) - return NULL; + const char *name; + const char *doc = NULL; + PyObject *base = NULL; + PyObject *dict = NULL; + + static char *kwlist[] = {"name", "doc", "base", "dict", NULL}; + + if (!PyArg_ParseTupleAndKeywords(args, kwargs, + "s|sOO:make_exception_with_doc", kwlist, + &name, &doc, &base, &dict)) + return NULL; - return PyErr_NewExceptionWithDoc(name, doc, base, dict); + return PyErr_NewExceptionWithDoc(name, doc, base, dict); } static PyMethodDef TestMethods[] = { - {"raise_exception", raise_exception, METH_VARARGS}, - {"raise_memoryerror", (PyCFunction)raise_memoryerror, METH_NOARGS}, - {"test_config", (PyCFunction)test_config, METH_NOARGS}, - {"test_datetime_capi", test_datetime_capi, METH_NOARGS}, - {"test_list_api", (PyCFunction)test_list_api, METH_NOARGS}, - {"test_dict_iteration", (PyCFunction)test_dict_iteration,METH_NOARGS}, - {"test_lazy_hash_inheritance", (PyCFunction)test_lazy_hash_inheritance,METH_NOARGS}, - {"test_broken_memoryview", (PyCFunction)test_broken_memoryview,METH_NOARGS}, - {"test_long_api", (PyCFunction)test_long_api, METH_NOARGS}, - {"test_long_and_overflow", (PyCFunction)test_long_and_overflow, - METH_NOARGS}, - {"test_long_numbits", (PyCFunction)test_long_numbits, METH_NOARGS}, - {"test_k_code", (PyCFunction)test_k_code, METH_NOARGS}, - {"test_empty_argparse", (PyCFunction)test_empty_argparse,METH_NOARGS}, - {"test_bug_7414", (PyCFunction)test_bug_7414, METH_NOARGS}, - {"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, - PyDoc_STR("This is a pretty normal docstring.")}, - {"test_string_to_double", (PyCFunction)test_string_to_double, METH_NOARGS}, - {"test_unicode_compare_with_ascii", (PyCFunction)test_unicode_compare_with_ascii, METH_NOARGS}, - {"test_capsule", (PyCFunction)test_capsule, METH_NOARGS}, - {"getargs_tuple", getargs_tuple, METH_VARARGS}, - {"getargs_keywords", (PyCFunction)getargs_keywords, - METH_VARARGS|METH_KEYWORDS}, - {"getargs_b", getargs_b, METH_VARARGS}, - {"getargs_B", getargs_B, METH_VARARGS}, - {"getargs_h", getargs_h, METH_VARARGS}, - {"getargs_H", getargs_H, METH_VARARGS}, - {"getargs_I", getargs_I, METH_VARARGS}, - {"getargs_k", getargs_k, METH_VARARGS}, - {"getargs_i", getargs_i, METH_VARARGS}, - {"getargs_l", getargs_l, METH_VARARGS}, - {"getargs_n", getargs_n, METH_VARARGS}, + {"raise_exception", raise_exception, METH_VARARGS}, + {"raise_memoryerror", (PyCFunction)raise_memoryerror, METH_NOARGS}, + {"test_config", (PyCFunction)test_config, METH_NOARGS}, + {"test_datetime_capi", test_datetime_capi, METH_NOARGS}, + {"test_list_api", (PyCFunction)test_list_api, METH_NOARGS}, + {"test_dict_iteration", (PyCFunction)test_dict_iteration,METH_NOARGS}, + {"test_lazy_hash_inheritance", (PyCFunction)test_lazy_hash_inheritance,METH_NOARGS}, + {"test_broken_memoryview", (PyCFunction)test_broken_memoryview,METH_NOARGS}, + {"test_long_api", (PyCFunction)test_long_api, METH_NOARGS}, + {"test_long_and_overflow", (PyCFunction)test_long_and_overflow, + METH_NOARGS}, + {"test_long_numbits", (PyCFunction)test_long_numbits, METH_NOARGS}, + {"test_k_code", (PyCFunction)test_k_code, METH_NOARGS}, + {"test_empty_argparse", (PyCFunction)test_empty_argparse,METH_NOARGS}, + {"test_bug_7414", (PyCFunction)test_bug_7414, METH_NOARGS}, + {"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, + PyDoc_STR("This is a pretty normal docstring.")}, + {"test_string_to_double", (PyCFunction)test_string_to_double, METH_NOARGS}, + {"test_unicode_compare_with_ascii", (PyCFunction)test_unicode_compare_with_ascii, METH_NOARGS}, + {"test_capsule", (PyCFunction)test_capsule, METH_NOARGS}, + {"getargs_tuple", getargs_tuple, METH_VARARGS}, + {"getargs_keywords", (PyCFunction)getargs_keywords, + METH_VARARGS|METH_KEYWORDS}, + {"getargs_b", getargs_b, METH_VARARGS}, + {"getargs_B", getargs_B, METH_VARARGS}, + {"getargs_h", getargs_h, METH_VARARGS}, + {"getargs_H", getargs_H, METH_VARARGS}, + {"getargs_I", getargs_I, METH_VARARGS}, + {"getargs_k", getargs_k, METH_VARARGS}, + {"getargs_i", getargs_i, METH_VARARGS}, + {"getargs_l", getargs_l, METH_VARARGS}, + {"getargs_n", getargs_n, METH_VARARGS}, #ifdef HAVE_LONG_LONG - {"getargs_L", getargs_L, METH_VARARGS}, - {"getargs_K", getargs_K, METH_VARARGS}, - {"test_longlong_api", test_longlong_api, METH_NOARGS}, - {"test_long_long_and_overflow", - (PyCFunction)test_long_long_and_overflow, METH_NOARGS}, - {"test_L_code", (PyCFunction)test_L_code, METH_NOARGS}, - {"codec_incrementalencoder", - (PyCFunction)codec_incrementalencoder, METH_VARARGS}, - {"codec_incrementaldecoder", - (PyCFunction)codec_incrementaldecoder, METH_VARARGS}, + {"getargs_L", getargs_L, METH_VARARGS}, + {"getargs_K", getargs_K, METH_VARARGS}, + {"test_longlong_api", test_longlong_api, METH_NOARGS}, + {"test_long_long_and_overflow", + (PyCFunction)test_long_long_and_overflow, METH_NOARGS}, + {"test_L_code", (PyCFunction)test_L_code, METH_NOARGS}, + {"codec_incrementalencoder", + (PyCFunction)codec_incrementalencoder, METH_VARARGS}, + {"codec_incrementaldecoder", + (PyCFunction)codec_incrementaldecoder, METH_VARARGS}, #endif - {"test_s_code", (PyCFunction)test_s_code, METH_NOARGS}, - {"test_u_code", (PyCFunction)test_u_code, METH_NOARGS}, - {"test_Z_code", (PyCFunction)test_Z_code, METH_NOARGS}, - {"test_widechar", (PyCFunction)test_widechar, METH_NOARGS}, + {"test_s_code", (PyCFunction)test_s_code, METH_NOARGS}, + {"test_u_code", (PyCFunction)test_u_code, METH_NOARGS}, + {"test_Z_code", (PyCFunction)test_Z_code, METH_NOARGS}, + {"test_widechar", (PyCFunction)test_widechar, METH_NOARGS}, #ifdef WITH_THREAD - {"_test_thread_state", test_thread_state, METH_VARARGS}, - {"_pending_threadfunc", pending_threadfunc, METH_VARARGS}, + {"_test_thread_state", test_thread_state, METH_VARARGS}, + {"_pending_threadfunc", pending_threadfunc, METH_VARARGS}, #endif #ifdef HAVE_GETTIMEOFDAY - {"profile_int", profile_int, METH_NOARGS}, + {"profile_int", profile_int, METH_NOARGS}, #endif - {"traceback_print", traceback_print, METH_VARARGS}, - {"exception_print", exception_print, METH_VARARGS}, - {"argparsing", argparsing, METH_VARARGS}, - {"code_newempty", code_newempty, METH_VARARGS}, - {"make_exception_with_doc", (PyCFunction)make_exception_with_doc, - METH_VARARGS | METH_KEYWORDS}, - {NULL, NULL} /* sentinel */ + {"traceback_print", traceback_print, METH_VARARGS}, + {"exception_print", exception_print, METH_VARARGS}, + {"argparsing", argparsing, METH_VARARGS}, + {"code_newempty", code_newempty, METH_VARARGS}, + {"make_exception_with_doc", (PyCFunction)make_exception_with_doc, + METH_VARARGS | METH_KEYWORDS}, + {NULL, NULL} /* sentinel */ }; #define AddSym(d, n, f, v) {PyObject *o = f(v); PyDict_SetItemString(d, n, o); Py_DECREF(o);} typedef struct { - char bool_member; - char byte_member; - unsigned char ubyte_member; - short short_member; - unsigned short ushort_member; - int int_member; - unsigned int uint_member; - long long_member; - unsigned long ulong_member; - Py_ssize_t pyssizet_member; - float float_member; - double double_member; - char inplace_member[6]; + char bool_member; + char byte_member; + unsigned char ubyte_member; + short short_member; + unsigned short ushort_member; + int int_member; + unsigned int uint_member; + long long_member; + unsigned long ulong_member; + Py_ssize_t pyssizet_member; + float float_member; + double double_member; + char inplace_member[6]; #ifdef HAVE_LONG_LONG - PY_LONG_LONG longlong_member; - unsigned PY_LONG_LONG ulonglong_member; + PY_LONG_LONG longlong_member; + unsigned PY_LONG_LONG ulonglong_member; #endif } all_structmembers; typedef struct { PyObject_HEAD - all_structmembers structmembers; + all_structmembers structmembers; } test_structmembers; static struct PyMemberDef test_members[] = { - {"T_BOOL", T_BOOL, offsetof(test_structmembers, structmembers.bool_member), 0, NULL}, - {"T_BYTE", T_BYTE, offsetof(test_structmembers, structmembers.byte_member), 0, NULL}, - {"T_UBYTE", T_UBYTE, offsetof(test_structmembers, structmembers.ubyte_member), 0, NULL}, - {"T_SHORT", T_SHORT, offsetof(test_structmembers, structmembers.short_member), 0, NULL}, - {"T_USHORT", T_USHORT, offsetof(test_structmembers, structmembers.ushort_member), 0, NULL}, - {"T_INT", T_INT, offsetof(test_structmembers, structmembers.int_member), 0, NULL}, - {"T_UINT", T_UINT, offsetof(test_structmembers, structmembers.uint_member), 0, NULL}, - {"T_LONG", T_LONG, offsetof(test_structmembers, structmembers.long_member), 0, NULL}, - {"T_ULONG", T_ULONG, offsetof(test_structmembers, structmembers.ulong_member), 0, NULL}, - {"T_PYSSIZET", T_PYSSIZET, offsetof(test_structmembers, structmembers.pyssizet_member), 0, NULL}, - {"T_FLOAT", T_FLOAT, offsetof(test_structmembers, structmembers.float_member), 0, NULL}, - {"T_DOUBLE", T_DOUBLE, offsetof(test_structmembers, structmembers.double_member), 0, NULL}, - {"T_STRING_INPLACE", T_STRING_INPLACE, offsetof(test_structmembers, structmembers.inplace_member), 0, NULL}, + {"T_BOOL", T_BOOL, offsetof(test_structmembers, structmembers.bool_member), 0, NULL}, + {"T_BYTE", T_BYTE, offsetof(test_structmembers, structmembers.byte_member), 0, NULL}, + {"T_UBYTE", T_UBYTE, offsetof(test_structmembers, structmembers.ubyte_member), 0, NULL}, + {"T_SHORT", T_SHORT, offsetof(test_structmembers, structmembers.short_member), 0, NULL}, + {"T_USHORT", T_USHORT, offsetof(test_structmembers, structmembers.ushort_member), 0, NULL}, + {"T_INT", T_INT, offsetof(test_structmembers, structmembers.int_member), 0, NULL}, + {"T_UINT", T_UINT, offsetof(test_structmembers, structmembers.uint_member), 0, NULL}, + {"T_LONG", T_LONG, offsetof(test_structmembers, structmembers.long_member), 0, NULL}, + {"T_ULONG", T_ULONG, offsetof(test_structmembers, structmembers.ulong_member), 0, NULL}, + {"T_PYSSIZET", T_PYSSIZET, offsetof(test_structmembers, structmembers.pyssizet_member), 0, NULL}, + {"T_FLOAT", T_FLOAT, offsetof(test_structmembers, structmembers.float_member), 0, NULL}, + {"T_DOUBLE", T_DOUBLE, offsetof(test_structmembers, structmembers.double_member), 0, NULL}, + {"T_STRING_INPLACE", T_STRING_INPLACE, offsetof(test_structmembers, structmembers.inplace_member), 0, NULL}, #ifdef HAVE_LONG_LONG - {"T_LONGLONG", T_LONGLONG, offsetof(test_structmembers, structmembers.longlong_member), 0, NULL}, - {"T_ULONGLONG", T_ULONGLONG, offsetof(test_structmembers, structmembers.ulonglong_member), 0, NULL}, + {"T_LONGLONG", T_LONGLONG, offsetof(test_structmembers, structmembers.longlong_member), 0, NULL}, + {"T_ULONGLONG", T_ULONGLONG, offsetof(test_structmembers, structmembers.ulonglong_member), 0, NULL}, #endif - {NULL} + {NULL} }; static PyObject * test_structmembers_new(PyTypeObject *type, PyObject *args, PyObject *kwargs) { - static char *keywords[] = { - "T_BOOL", "T_BYTE", "T_UBYTE", "T_SHORT", "T_USHORT", - "T_INT", "T_UINT", "T_LONG", "T_ULONG", "T_PYSSIZET", - "T_FLOAT", "T_DOUBLE", "T_STRING_INPLACE", + static char *keywords[] = { + "T_BOOL", "T_BYTE", "T_UBYTE", "T_SHORT", "T_USHORT", + "T_INT", "T_UINT", "T_LONG", "T_ULONG", "T_PYSSIZET", + "T_FLOAT", "T_DOUBLE", "T_STRING_INPLACE", #ifdef HAVE_LONG_LONG - "T_LONGLONG", "T_ULONGLONG", + "T_LONGLONG", "T_ULONGLONG", #endif - NULL}; - static char *fmt = "|bbBhHiIlknfds#" + NULL}; + static char *fmt = "|bbBhHiIlknfds#" #ifdef HAVE_LONG_LONG - "LK" + "LK" #endif - ; - test_structmembers *ob; - const char *s = NULL; - Py_ssize_t string_len = 0; - ob = PyObject_New(test_structmembers, type); - if (ob == NULL) - return NULL; - memset(&ob->structmembers, 0, sizeof(all_structmembers)); - if (!PyArg_ParseTupleAndKeywords(args, kwargs, fmt, keywords, - &ob->structmembers.bool_member, - &ob->structmembers.byte_member, - &ob->structmembers.ubyte_member, - &ob->structmembers.short_member, - &ob->structmembers.ushort_member, - &ob->structmembers.int_member, - &ob->structmembers.uint_member, - &ob->structmembers.long_member, - &ob->structmembers.ulong_member, - &ob->structmembers.pyssizet_member, - &ob->structmembers.float_member, - &ob->structmembers.double_member, - &s, &string_len + ; + test_structmembers *ob; + const char *s = NULL; + Py_ssize_t string_len = 0; + ob = PyObject_New(test_structmembers, type); + if (ob == NULL) + return NULL; + memset(&ob->structmembers, 0, sizeof(all_structmembers)); + if (!PyArg_ParseTupleAndKeywords(args, kwargs, fmt, keywords, + &ob->structmembers.bool_member, + &ob->structmembers.byte_member, + &ob->structmembers.ubyte_member, + &ob->structmembers.short_member, + &ob->structmembers.ushort_member, + &ob->structmembers.int_member, + &ob->structmembers.uint_member, + &ob->structmembers.long_member, + &ob->structmembers.ulong_member, + &ob->structmembers.pyssizet_member, + &ob->structmembers.float_member, + &ob->structmembers.double_member, + &s, &string_len #ifdef HAVE_LONG_LONG - , &ob->structmembers.longlong_member, - &ob->structmembers.ulonglong_member + , &ob->structmembers.longlong_member, + &ob->structmembers.ulonglong_member #endif - )) { - Py_DECREF(ob); - return NULL; - } - if (s != NULL) { - if (string_len > 5) { - Py_DECREF(ob); - PyErr_SetString(PyExc_ValueError, "string too long"); - return NULL; - } - strcpy(ob->structmembers.inplace_member, s); - } - else { - strcpy(ob->structmembers.inplace_member, ""); - } - return (PyObject *)ob; + )) { + Py_DECREF(ob); + return NULL; + } + if (s != NULL) { + if (string_len > 5) { + Py_DECREF(ob); + PyErr_SetString(PyExc_ValueError, "string too long"); + return NULL; + } + strcpy(ob->structmembers.inplace_member, s); + } + else { + strcpy(ob->structmembers.inplace_member, ""); + } + return (PyObject *)ob; } static void test_structmembers_free(PyObject *ob) { - PyObject_FREE(ob); + PyObject_FREE(ob); } static PyTypeObject test_structmembersType = { PyVarObject_HEAD_INIT(NULL, 0) - "test_structmembersType", - sizeof(test_structmembers), /* tp_basicsize */ - 0, /* tp_itemsize */ - test_structmembers_free, /* destructor 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 */ - PyObject_GenericSetAttr, /* tp_setattro */ - 0, /* tp_as_buffer */ - 0, /* tp_flags */ - "Type containing all structmember types", - 0, /* traverseproc tp_traverse */ - 0, /* tp_clear */ - 0, /* tp_richcompare */ - 0, /* tp_weaklistoffset */ - 0, /* tp_iter */ - 0, /* tp_iternext */ - 0, /* tp_methods */ - test_members, /* tp_members */ - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - test_structmembers_new, /* tp_new */ + "test_structmembersType", + sizeof(test_structmembers), /* tp_basicsize */ + 0, /* tp_itemsize */ + test_structmembers_free, /* destructor 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 */ + PyObject_GenericSetAttr, /* tp_setattro */ + 0, /* tp_as_buffer */ + 0, /* tp_flags */ + "Type containing all structmember types", + 0, /* traverseproc tp_traverse */ + 0, /* tp_clear */ + 0, /* tp_richcompare */ + 0, /* tp_weaklistoffset */ + 0, /* tp_iter */ + 0, /* tp_iternext */ + 0, /* tp_methods */ + test_members, /* tp_members */ + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + test_structmembers_new, /* tp_new */ }; static struct PyModuleDef _testcapimodule = { - PyModuleDef_HEAD_INIT, - "_testcapi", - NULL, - -1, - TestMethods, - NULL, - NULL, - NULL, - NULL + PyModuleDef_HEAD_INIT, + "_testcapi", + NULL, + -1, + TestMethods, + NULL, + NULL, + NULL, + NULL }; PyMODINIT_FUNC PyInit__testcapi(void) { - PyObject *m; + PyObject *m; + + m = PyModule_Create(&_testcapimodule); + if (m == NULL) + return NULL; + + Py_TYPE(&_HashInheritanceTester_Type)=&PyType_Type; + Py_TYPE(&_MemoryViewTester_Type)=&PyType_Type; - m = PyModule_Create(&_testcapimodule); - if (m == NULL) - return NULL; - - Py_TYPE(&_HashInheritanceTester_Type)=&PyType_Type; - Py_TYPE(&_MemoryViewTester_Type)=&PyType_Type; - - Py_TYPE(&test_structmembersType)=&PyType_Type; - Py_INCREF(&test_structmembersType); - /* don't use a name starting with "test", since we don't want - test_capi to automatically call this */ - PyModule_AddObject(m, "_test_structmembersType", (PyObject *)&test_structmembersType); - - PyModule_AddObject(m, "CHAR_MAX", PyLong_FromLong(CHAR_MAX)); - PyModule_AddObject(m, "CHAR_MIN", PyLong_FromLong(CHAR_MIN)); - PyModule_AddObject(m, "UCHAR_MAX", PyLong_FromLong(UCHAR_MAX)); - PyModule_AddObject(m, "SHRT_MAX", PyLong_FromLong(SHRT_MAX)); - PyModule_AddObject(m, "SHRT_MIN", PyLong_FromLong(SHRT_MIN)); - PyModule_AddObject(m, "USHRT_MAX", PyLong_FromLong(USHRT_MAX)); - PyModule_AddObject(m, "INT_MAX", PyLong_FromLong(INT_MAX)); - PyModule_AddObject(m, "INT_MIN", PyLong_FromLong(INT_MIN)); - PyModule_AddObject(m, "UINT_MAX", PyLong_FromUnsignedLong(UINT_MAX)); - PyModule_AddObject(m, "LONG_MAX", PyLong_FromLong(LONG_MAX)); - PyModule_AddObject(m, "LONG_MIN", PyLong_FromLong(LONG_MIN)); - PyModule_AddObject(m, "ULONG_MAX", PyLong_FromUnsignedLong(ULONG_MAX)); - PyModule_AddObject(m, "FLT_MAX", PyFloat_FromDouble(FLT_MAX)); - PyModule_AddObject(m, "FLT_MIN", PyFloat_FromDouble(FLT_MIN)); - PyModule_AddObject(m, "DBL_MAX", PyFloat_FromDouble(DBL_MAX)); - PyModule_AddObject(m, "DBL_MIN", PyFloat_FromDouble(DBL_MIN)); - PyModule_AddObject(m, "LLONG_MAX", PyLong_FromLongLong(PY_LLONG_MAX)); - PyModule_AddObject(m, "LLONG_MIN", PyLong_FromLongLong(PY_LLONG_MIN)); - PyModule_AddObject(m, "ULLONG_MAX", PyLong_FromUnsignedLongLong(PY_ULLONG_MAX)); - PyModule_AddObject(m, "PY_SSIZE_T_MAX", PyLong_FromSsize_t(PY_SSIZE_T_MAX)); - PyModule_AddObject(m, "PY_SSIZE_T_MIN", PyLong_FromSsize_t(PY_SSIZE_T_MIN)); - PyModule_AddObject(m, "SIZEOF_PYGC_HEAD", PyLong_FromSsize_t(sizeof(PyGC_Head))); - Py_INCREF(&PyInstanceMethod_Type); - PyModule_AddObject(m, "instancemethod", (PyObject *)&PyInstanceMethod_Type); - - TestError = PyErr_NewException("_testcapi.error", NULL, NULL); - Py_INCREF(TestError); - PyModule_AddObject(m, "error", TestError); - return m; + Py_TYPE(&test_structmembersType)=&PyType_Type; + Py_INCREF(&test_structmembersType); + /* don't use a name starting with "test", since we don't want + test_capi to automatically call this */ + PyModule_AddObject(m, "_test_structmembersType", (PyObject *)&test_structmembersType); + + PyModule_AddObject(m, "CHAR_MAX", PyLong_FromLong(CHAR_MAX)); + PyModule_AddObject(m, "CHAR_MIN", PyLong_FromLong(CHAR_MIN)); + PyModule_AddObject(m, "UCHAR_MAX", PyLong_FromLong(UCHAR_MAX)); + PyModule_AddObject(m, "SHRT_MAX", PyLong_FromLong(SHRT_MAX)); + PyModule_AddObject(m, "SHRT_MIN", PyLong_FromLong(SHRT_MIN)); + PyModule_AddObject(m, "USHRT_MAX", PyLong_FromLong(USHRT_MAX)); + PyModule_AddObject(m, "INT_MAX", PyLong_FromLong(INT_MAX)); + PyModule_AddObject(m, "INT_MIN", PyLong_FromLong(INT_MIN)); + PyModule_AddObject(m, "UINT_MAX", PyLong_FromUnsignedLong(UINT_MAX)); + PyModule_AddObject(m, "LONG_MAX", PyLong_FromLong(LONG_MAX)); + PyModule_AddObject(m, "LONG_MIN", PyLong_FromLong(LONG_MIN)); + PyModule_AddObject(m, "ULONG_MAX", PyLong_FromUnsignedLong(ULONG_MAX)); + PyModule_AddObject(m, "FLT_MAX", PyFloat_FromDouble(FLT_MAX)); + PyModule_AddObject(m, "FLT_MIN", PyFloat_FromDouble(FLT_MIN)); + PyModule_AddObject(m, "DBL_MAX", PyFloat_FromDouble(DBL_MAX)); + PyModule_AddObject(m, "DBL_MIN", PyFloat_FromDouble(DBL_MIN)); + PyModule_AddObject(m, "LLONG_MAX", PyLong_FromLongLong(PY_LLONG_MAX)); + PyModule_AddObject(m, "LLONG_MIN", PyLong_FromLongLong(PY_LLONG_MIN)); + PyModule_AddObject(m, "ULLONG_MAX", PyLong_FromUnsignedLongLong(PY_ULLONG_MAX)); + PyModule_AddObject(m, "PY_SSIZE_T_MAX", PyLong_FromSsize_t(PY_SSIZE_T_MAX)); + PyModule_AddObject(m, "PY_SSIZE_T_MIN", PyLong_FromSsize_t(PY_SSIZE_T_MIN)); + PyModule_AddObject(m, "SIZEOF_PYGC_HEAD", PyLong_FromSsize_t(sizeof(PyGC_Head))); + Py_INCREF(&PyInstanceMethod_Type); + PyModule_AddObject(m, "instancemethod", (PyObject *)&PyInstanceMethod_Type); + + TestError = PyErr_NewException("_testcapi.error", NULL, NULL); + Py_INCREF(TestError); + PyModule_AddObject(m, "error", TestError); + return m; } Modified: python/branches/py3k/Modules/_threadmodule.c ============================================================================== --- python/branches/py3k/Modules/_threadmodule.c (original) +++ python/branches/py3k/Modules/_threadmodule.c Sun May 9 17:52:27 2010 @@ -19,68 +19,68 @@ /* Lock objects */ typedef struct { - PyObject_HEAD - PyThread_type_lock lock_lock; - PyObject *in_weakreflist; + PyObject_HEAD + PyThread_type_lock lock_lock; + PyObject *in_weakreflist; } lockobject; static void lock_dealloc(lockobject *self) { - if (self->in_weakreflist != NULL) - PyObject_ClearWeakRefs((PyObject *) self); - if (self->lock_lock != NULL) { - /* Unlock the lock so it's safe to free it */ - PyThread_acquire_lock(self->lock_lock, 0); - PyThread_release_lock(self->lock_lock); - - PyThread_free_lock(self->lock_lock); - } - PyObject_Del(self); + if (self->in_weakreflist != NULL) + PyObject_ClearWeakRefs((PyObject *) self); + if (self->lock_lock != NULL) { + /* Unlock the lock so it's safe to free it */ + PyThread_acquire_lock(self->lock_lock, 0); + PyThread_release_lock(self->lock_lock); + + PyThread_free_lock(self->lock_lock); + } + PyObject_Del(self); } static PyObject * lock_PyThread_acquire_lock(lockobject *self, PyObject *args, PyObject *kwds) { - char *kwlist[] = {"blocking", "timeout", NULL}; - int blocking = 1; - double timeout = -1; - PY_TIMEOUT_T microseconds; - int r; - - if (!PyArg_ParseTupleAndKeywords(args, kwds, "|id:acquire", kwlist, - &blocking, &timeout)) - return NULL; - - if (!blocking && timeout != -1) { - PyErr_SetString(PyExc_ValueError, "can't specify a timeout " - "for a non-blocking call"); - return NULL; - } - if (timeout < 0 && timeout != -1) { - PyErr_SetString(PyExc_ValueError, "timeout value must be " - "strictly positive"); - return NULL; - } - if (!blocking) - microseconds = 0; - else if (timeout == -1) - microseconds = -1; - else { - timeout *= 1e6; - if (timeout >= (double) PY_TIMEOUT_MAX) { - PyErr_SetString(PyExc_OverflowError, - "timeout value is too large"); - return NULL; - } - microseconds = (PY_TIMEOUT_T) timeout; - } - - Py_BEGIN_ALLOW_THREADS - r = PyThread_acquire_lock_timed(self->lock_lock, microseconds); - Py_END_ALLOW_THREADS + char *kwlist[] = {"blocking", "timeout", NULL}; + int blocking = 1; + double timeout = -1; + PY_TIMEOUT_T microseconds; + int r; + + if (!PyArg_ParseTupleAndKeywords(args, kwds, "|id:acquire", kwlist, + &blocking, &timeout)) + return NULL; + + if (!blocking && timeout != -1) { + PyErr_SetString(PyExc_ValueError, "can't specify a timeout " + "for a non-blocking call"); + return NULL; + } + if (timeout < 0 && timeout != -1) { + PyErr_SetString(PyExc_ValueError, "timeout value must be " + "strictly positive"); + return NULL; + } + if (!blocking) + microseconds = 0; + else if (timeout == -1) + microseconds = -1; + else { + timeout *= 1e6; + if (timeout >= (double) PY_TIMEOUT_MAX) { + PyErr_SetString(PyExc_OverflowError, + "timeout value is too large"); + return NULL; + } + microseconds = (PY_TIMEOUT_T) timeout; + } + + Py_BEGIN_ALLOW_THREADS + r = PyThread_acquire_lock_timed(self->lock_lock, microseconds); + Py_END_ALLOW_THREADS - return PyBool_FromLong(r); + return PyBool_FromLong(r); } PyDoc_STRVAR(acquire_doc, @@ -97,16 +97,16 @@ static PyObject * lock_PyThread_release_lock(lockobject *self) { - /* Sanity check: the lock must be locked */ - if (PyThread_acquire_lock(self->lock_lock, 0)) { - PyThread_release_lock(self->lock_lock); - PyErr_SetString(ThreadError, "release unlocked lock"); - return NULL; - } - - PyThread_release_lock(self->lock_lock); - Py_INCREF(Py_None); - return Py_None; + /* Sanity check: the lock must be locked */ + if (PyThread_acquire_lock(self->lock_lock, 0)) { + PyThread_release_lock(self->lock_lock); + PyErr_SetString(ThreadError, "release unlocked lock"); + return NULL; + } + + PyThread_release_lock(self->lock_lock); + Py_INCREF(Py_None); + return Py_None; } PyDoc_STRVAR(release_doc, @@ -120,11 +120,11 @@ static PyObject * lock_locked_lock(lockobject *self) { - if (PyThread_acquire_lock(self->lock_lock, 0)) { - PyThread_release_lock(self->lock_lock); - return PyBool_FromLong(0L); - } - return PyBool_FromLong(1L); + if (PyThread_acquire_lock(self->lock_lock, 0)) { + PyThread_release_lock(self->lock_lock); + return PyBool_FromLong(0L); + } + return PyBool_FromLong(1L); } PyDoc_STRVAR(locked_doc, @@ -134,147 +134,147 @@ Return whether the lock is in the locked state."); static PyMethodDef lock_methods[] = { - {"acquire_lock", (PyCFunction)lock_PyThread_acquire_lock, - METH_VARARGS | METH_KEYWORDS, acquire_doc}, - {"acquire", (PyCFunction)lock_PyThread_acquire_lock, - METH_VARARGS | METH_KEYWORDS, acquire_doc}, - {"release_lock", (PyCFunction)lock_PyThread_release_lock, - METH_NOARGS, release_doc}, - {"release", (PyCFunction)lock_PyThread_release_lock, - METH_NOARGS, release_doc}, - {"locked_lock", (PyCFunction)lock_locked_lock, - METH_NOARGS, locked_doc}, - {"locked", (PyCFunction)lock_locked_lock, - METH_NOARGS, locked_doc}, - {"__enter__", (PyCFunction)lock_PyThread_acquire_lock, - METH_VARARGS | METH_KEYWORDS, acquire_doc}, - {"__exit__", (PyCFunction)lock_PyThread_release_lock, - METH_VARARGS, release_doc}, - {NULL, NULL} /* sentinel */ + {"acquire_lock", (PyCFunction)lock_PyThread_acquire_lock, + METH_VARARGS | METH_KEYWORDS, acquire_doc}, + {"acquire", (PyCFunction)lock_PyThread_acquire_lock, + METH_VARARGS | METH_KEYWORDS, acquire_doc}, + {"release_lock", (PyCFunction)lock_PyThread_release_lock, + METH_NOARGS, release_doc}, + {"release", (PyCFunction)lock_PyThread_release_lock, + METH_NOARGS, release_doc}, + {"locked_lock", (PyCFunction)lock_locked_lock, + METH_NOARGS, locked_doc}, + {"locked", (PyCFunction)lock_locked_lock, + METH_NOARGS, locked_doc}, + {"__enter__", (PyCFunction)lock_PyThread_acquire_lock, + METH_VARARGS | METH_KEYWORDS, acquire_doc}, + {"__exit__", (PyCFunction)lock_PyThread_release_lock, + METH_VARARGS, release_doc}, + {NULL, NULL} /* sentinel */ }; static PyTypeObject Locktype = { - PyVarObject_HEAD_INIT(&PyType_Type, 0) - "_thread.lock", /*tp_name*/ - sizeof(lockobject), /*tp_size*/ - 0, /*tp_itemsize*/ - /* methods */ - (destructor)lock_dealloc, /*tp_dealloc*/ - 0, /*tp_print*/ - 0, /*tp_getattr*/ - 0, /*tp_setattr*/ - 0, /*tp_reserved*/ - 0, /*tp_repr*/ - 0, /*tp_as_number*/ - 0, /*tp_as_sequence*/ - 0, /*tp_as_mapping*/ - 0, /*tp_hash*/ - 0, /*tp_call*/ - 0, /*tp_str*/ - 0, /*tp_getattro*/ - 0, /*tp_setattro*/ - 0, /*tp_as_buffer*/ - Py_TPFLAGS_DEFAULT, /*tp_flags*/ - 0, /*tp_doc*/ - 0, /*tp_traverse*/ - 0, /*tp_clear*/ - 0, /*tp_richcompare*/ - offsetof(lockobject, in_weakreflist), /*tp_weaklistoffset*/ - 0, /*tp_iter*/ - 0, /*tp_iternext*/ - lock_methods, /*tp_methods*/ + PyVarObject_HEAD_INIT(&PyType_Type, 0) + "_thread.lock", /*tp_name*/ + sizeof(lockobject), /*tp_size*/ + 0, /*tp_itemsize*/ + /* methods */ + (destructor)lock_dealloc, /*tp_dealloc*/ + 0, /*tp_print*/ + 0, /*tp_getattr*/ + 0, /*tp_setattr*/ + 0, /*tp_reserved*/ + 0, /*tp_repr*/ + 0, /*tp_as_number*/ + 0, /*tp_as_sequence*/ + 0, /*tp_as_mapping*/ + 0, /*tp_hash*/ + 0, /*tp_call*/ + 0, /*tp_str*/ + 0, /*tp_getattro*/ + 0, /*tp_setattro*/ + 0, /*tp_as_buffer*/ + Py_TPFLAGS_DEFAULT, /*tp_flags*/ + 0, /*tp_doc*/ + 0, /*tp_traverse*/ + 0, /*tp_clear*/ + 0, /*tp_richcompare*/ + offsetof(lockobject, in_weakreflist), /*tp_weaklistoffset*/ + 0, /*tp_iter*/ + 0, /*tp_iternext*/ + lock_methods, /*tp_methods*/ }; /* Recursive lock objects */ typedef struct { - PyObject_HEAD - PyThread_type_lock rlock_lock; - long rlock_owner; - unsigned long rlock_count; - PyObject *in_weakreflist; + PyObject_HEAD + PyThread_type_lock rlock_lock; + long rlock_owner; + unsigned long rlock_count; + PyObject *in_weakreflist; } rlockobject; static void rlock_dealloc(rlockobject *self) { - assert(self->rlock_lock); - if (self->in_weakreflist != NULL) - PyObject_ClearWeakRefs((PyObject *) self); - /* Unlock the lock so it's safe to free it */ - if (self->rlock_count > 0) - PyThread_release_lock(self->rlock_lock); - - PyThread_free_lock(self->rlock_lock); - Py_TYPE(self)->tp_free(self); + assert(self->rlock_lock); + if (self->in_weakreflist != NULL) + PyObject_ClearWeakRefs((PyObject *) self); + /* Unlock the lock so it's safe to free it */ + if (self->rlock_count > 0) + PyThread_release_lock(self->rlock_lock); + + PyThread_free_lock(self->rlock_lock); + Py_TYPE(self)->tp_free(self); } static PyObject * rlock_acquire(rlockobject *self, PyObject *args, PyObject *kwds) { - char *kwlist[] = {"blocking", "timeout", NULL}; - int blocking = 1; - double timeout = -1; - PY_TIMEOUT_T microseconds; - long tid; - int r = 1; - - if (!PyArg_ParseTupleAndKeywords(args, kwds, "|id:acquire", kwlist, - &blocking, &timeout)) - return NULL; - - if (!blocking && timeout != -1) { - PyErr_SetString(PyExc_ValueError, "can't specify a timeout " - "for a non-blocking call"); - return NULL; - } - if (timeout < 0 && timeout != -1) { - PyErr_SetString(PyExc_ValueError, "timeout value must be " - "strictly positive"); - return NULL; - } - if (!blocking) - microseconds = 0; - else if (timeout == -1) - microseconds = -1; - else { - timeout *= 1e6; - if (timeout >= (double) PY_TIMEOUT_MAX) { - PyErr_SetString(PyExc_OverflowError, - "timeout value is too large"); - return NULL; - } - microseconds = (PY_TIMEOUT_T) timeout; - } - - tid = PyThread_get_thread_ident(); - if (self->rlock_count > 0 && tid == self->rlock_owner) { - unsigned long count = self->rlock_count + 1; - if (count <= self->rlock_count) { - PyErr_SetString(PyExc_OverflowError, - "Internal lock count overflowed"); - return NULL; - } - self->rlock_count = count; - Py_RETURN_TRUE; - } - - if (self->rlock_count > 0 || - !PyThread_acquire_lock(self->rlock_lock, 0)) { - if (microseconds == 0) { - Py_RETURN_FALSE; - } - Py_BEGIN_ALLOW_THREADS - r = PyThread_acquire_lock_timed(self->rlock_lock, microseconds); - Py_END_ALLOW_THREADS - } - if (r) { - assert(self->rlock_count == 0); - self->rlock_owner = tid; - self->rlock_count = 1; - } + char *kwlist[] = {"blocking", "timeout", NULL}; + int blocking = 1; + double timeout = -1; + PY_TIMEOUT_T microseconds; + long tid; + int r = 1; + + if (!PyArg_ParseTupleAndKeywords(args, kwds, "|id:acquire", kwlist, + &blocking, &timeout)) + return NULL; + + if (!blocking && timeout != -1) { + PyErr_SetString(PyExc_ValueError, "can't specify a timeout " + "for a non-blocking call"); + return NULL; + } + if (timeout < 0 && timeout != -1) { + PyErr_SetString(PyExc_ValueError, "timeout value must be " + "strictly positive"); + return NULL; + } + if (!blocking) + microseconds = 0; + else if (timeout == -1) + microseconds = -1; + else { + timeout *= 1e6; + if (timeout >= (double) PY_TIMEOUT_MAX) { + PyErr_SetString(PyExc_OverflowError, + "timeout value is too large"); + return NULL; + } + microseconds = (PY_TIMEOUT_T) timeout; + } + + tid = PyThread_get_thread_ident(); + if (self->rlock_count > 0 && tid == self->rlock_owner) { + unsigned long count = self->rlock_count + 1; + if (count <= self->rlock_count) { + PyErr_SetString(PyExc_OverflowError, + "Internal lock count overflowed"); + return NULL; + } + self->rlock_count = count; + Py_RETURN_TRUE; + } + + if (self->rlock_count > 0 || + !PyThread_acquire_lock(self->rlock_lock, 0)) { + if (microseconds == 0) { + Py_RETURN_FALSE; + } + Py_BEGIN_ALLOW_THREADS + r = PyThread_acquire_lock_timed(self->rlock_lock, microseconds); + Py_END_ALLOW_THREADS + } + if (r) { + assert(self->rlock_count == 0); + self->rlock_owner = tid; + self->rlock_count = 1; + } - return PyBool_FromLong(r); + return PyBool_FromLong(r); } PyDoc_STRVAR(rlock_acquire_doc, @@ -296,18 +296,18 @@ static PyObject * rlock_release(rlockobject *self) { - long tid = PyThread_get_thread_ident(); + long tid = PyThread_get_thread_ident(); - if (self->rlock_count == 0 || self->rlock_owner != tid) { - PyErr_SetString(PyExc_RuntimeError, - "cannot release un-acquired lock"); - return NULL; - } - if (--self->rlock_count == 0) { - self->rlock_owner = 0; - PyThread_release_lock(self->rlock_lock); - } - Py_RETURN_NONE; + if (self->rlock_count == 0 || self->rlock_owner != tid) { + PyErr_SetString(PyExc_RuntimeError, + "cannot release un-acquired lock"); + return NULL; + } + if (--self->rlock_count == 0) { + self->rlock_owner = 0; + PyThread_release_lock(self->rlock_lock); + } + Py_RETURN_NONE; } PyDoc_STRVAR(rlock_release_doc, @@ -325,26 +325,26 @@ static PyObject * rlock_acquire_restore(rlockobject *self, PyObject *arg) { - long owner; - unsigned long count; - int r = 1; - - if (!PyArg_ParseTuple(arg, "kl:_acquire_restore", &count, &owner)) - return NULL; - - if (!PyThread_acquire_lock(self->rlock_lock, 0)) { - Py_BEGIN_ALLOW_THREADS - r = PyThread_acquire_lock(self->rlock_lock, 1); - Py_END_ALLOW_THREADS - } - if (!r) { - PyErr_SetString(ThreadError, "couldn't acquire lock"); - return NULL; - } - assert(self->rlock_count == 0); - self->rlock_owner = owner; - self->rlock_count = count; - Py_RETURN_NONE; + long owner; + unsigned long count; + int r = 1; + + if (!PyArg_ParseTuple(arg, "kl:_acquire_restore", &count, &owner)) + return NULL; + + if (!PyThread_acquire_lock(self->rlock_lock, 0)) { + Py_BEGIN_ALLOW_THREADS + r = PyThread_acquire_lock(self->rlock_lock, 1); + Py_END_ALLOW_THREADS + } + if (!r) { + PyErr_SetString(ThreadError, "couldn't acquire lock"); + return NULL; + } + assert(self->rlock_count == 0); + self->rlock_owner = owner; + self->rlock_count = count; + Py_RETURN_NONE; } PyDoc_STRVAR(rlock_acquire_restore_doc, @@ -355,15 +355,15 @@ static PyObject * rlock_release_save(rlockobject *self) { - long owner; - unsigned long count; + long owner; + unsigned long count; - owner = self->rlock_owner; - count = self->rlock_count; - self->rlock_count = 0; - self->rlock_owner = 0; - PyThread_release_lock(self->rlock_lock); - return Py_BuildValue("kl", count, owner); + owner = self->rlock_owner; + count = self->rlock_count; + self->rlock_count = 0; + self->rlock_owner = 0; + PyThread_release_lock(self->rlock_lock); + return Py_BuildValue("kl", count, owner); } PyDoc_STRVAR(rlock_release_save_doc, @@ -375,12 +375,12 @@ static PyObject * rlock_is_owned(rlockobject *self) { - long tid = PyThread_get_thread_ident(); - - if (self->rlock_count > 0 && self->rlock_owner == tid) { - Py_RETURN_TRUE; - } - Py_RETURN_FALSE; + long tid = PyThread_get_thread_ident(); + + if (self->rlock_count > 0 && self->rlock_owner == tid) { + Py_RETURN_TRUE; + } + Py_RETURN_FALSE; } PyDoc_STRVAR(rlock_is_owned_doc, @@ -391,108 +391,108 @@ static PyObject * rlock_new(PyTypeObject *type, PyObject *args, PyObject *kwds) { - rlockobject *self; + rlockobject *self; - self = (rlockobject *) type->tp_alloc(type, 0); - if (self != NULL) { - self->rlock_lock = PyThread_allocate_lock(); - if (self->rlock_lock == NULL) { - type->tp_free(self); - PyErr_SetString(ThreadError, "can't allocate lock"); - return NULL; - } - self->in_weakreflist = NULL; - self->rlock_owner = 0; - self->rlock_count = 0; - } + self = (rlockobject *) type->tp_alloc(type, 0); + if (self != NULL) { + self->rlock_lock = PyThread_allocate_lock(); + if (self->rlock_lock == NULL) { + type->tp_free(self); + PyErr_SetString(ThreadError, "can't allocate lock"); + return NULL; + } + self->in_weakreflist = NULL; + self->rlock_owner = 0; + self->rlock_count = 0; + } - return (PyObject *) self; + return (PyObject *) self; } static PyObject * rlock_repr(rlockobject *self) { - return PyUnicode_FromFormat("<%s owner=%ld count=%lu>", - Py_TYPE(self)->tp_name, self->rlock_owner, self->rlock_count); + return PyUnicode_FromFormat("<%s owner=%ld count=%lu>", + Py_TYPE(self)->tp_name, self->rlock_owner, self->rlock_count); } static PyMethodDef rlock_methods[] = { - {"acquire", (PyCFunction)rlock_acquire, - METH_VARARGS | METH_KEYWORDS, rlock_acquire_doc}, - {"release", (PyCFunction)rlock_release, - METH_NOARGS, rlock_release_doc}, - {"_is_owned", (PyCFunction)rlock_is_owned, - METH_NOARGS, rlock_is_owned_doc}, - {"_acquire_restore", (PyCFunction)rlock_acquire_restore, - METH_O, rlock_acquire_restore_doc}, - {"_release_save", (PyCFunction)rlock_release_save, - METH_NOARGS, rlock_release_save_doc}, - {"__enter__", (PyCFunction)rlock_acquire, - METH_VARARGS | METH_KEYWORDS, rlock_acquire_doc}, - {"__exit__", (PyCFunction)rlock_release, - METH_VARARGS, rlock_release_doc}, - {NULL, NULL} /* sentinel */ + {"acquire", (PyCFunction)rlock_acquire, + METH_VARARGS | METH_KEYWORDS, rlock_acquire_doc}, + {"release", (PyCFunction)rlock_release, + METH_NOARGS, rlock_release_doc}, + {"_is_owned", (PyCFunction)rlock_is_owned, + METH_NOARGS, rlock_is_owned_doc}, + {"_acquire_restore", (PyCFunction)rlock_acquire_restore, + METH_O, rlock_acquire_restore_doc}, + {"_release_save", (PyCFunction)rlock_release_save, + METH_NOARGS, rlock_release_save_doc}, + {"__enter__", (PyCFunction)rlock_acquire, + METH_VARARGS | METH_KEYWORDS, rlock_acquire_doc}, + {"__exit__", (PyCFunction)rlock_release, + METH_VARARGS, rlock_release_doc}, + {NULL, NULL} /* sentinel */ }; static PyTypeObject RLocktype = { - PyVarObject_HEAD_INIT(&PyType_Type, 0) - "_thread.RLock", /*tp_name*/ - sizeof(rlockobject), /*tp_size*/ - 0, /*tp_itemsize*/ - /* methods */ - (destructor)rlock_dealloc, /*tp_dealloc*/ - 0, /*tp_print*/ - 0, /*tp_getattr*/ - 0, /*tp_setattr*/ - 0, /*tp_reserved*/ - (reprfunc)rlock_repr, /*tp_repr*/ - 0, /*tp_as_number*/ - 0, /*tp_as_sequence*/ - 0, /*tp_as_mapping*/ - 0, /*tp_hash*/ - 0, /*tp_call*/ - 0, /*tp_str*/ - 0, /*tp_getattro*/ - 0, /*tp_setattro*/ - 0, /*tp_as_buffer*/ - Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */ - 0, /*tp_doc*/ - 0, /*tp_traverse*/ - 0, /*tp_clear*/ - 0, /*tp_richcompare*/ - offsetof(rlockobject, in_weakreflist), /*tp_weaklistoffset*/ - 0, /*tp_iter*/ - 0, /*tp_iternext*/ - rlock_methods, /*tp_methods*/ - 0, /* tp_members */ - 0, /* tp_getset */ - 0, /* tp_base */ - 0, /* tp_dict */ - 0, /* tp_descr_get */ - 0, /* tp_descr_set */ - 0, /* tp_dictoffset */ - 0, /* tp_init */ - PyType_GenericAlloc, /* tp_alloc */ - rlock_new /* tp_new */ + PyVarObject_HEAD_INIT(&PyType_Type, 0) + "_thread.RLock", /*tp_name*/ + sizeof(rlockobject), /*tp_size*/ + 0, /*tp_itemsize*/ + /* methods */ + (destructor)rlock_dealloc, /*tp_dealloc*/ + 0, /*tp_print*/ + 0, /*tp_getattr*/ + 0, /*tp_setattr*/ + 0, /*tp_reserved*/ + (reprfunc)rlock_repr, /*tp_repr*/ + 0, /*tp_as_number*/ + 0, /*tp_as_sequence*/ + 0, /*tp_as_mapping*/ + 0, /*tp_hash*/ + 0, /*tp_call*/ + 0, /*tp_str*/ + 0, /*tp_getattro*/ + 0, /*tp_setattro*/ + 0, /*tp_as_buffer*/ + Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */ + 0, /*tp_doc*/ + 0, /*tp_traverse*/ + 0, /*tp_clear*/ + 0, /*tp_richcompare*/ + offsetof(rlockobject, in_weakreflist), /*tp_weaklistoffset*/ + 0, /*tp_iter*/ + 0, /*tp_iternext*/ + rlock_methods, /*tp_methods*/ + 0, /* tp_members */ + 0, /* tp_getset */ + 0, /* tp_base */ + 0, /* tp_dict */ + 0, /* tp_descr_get */ + 0, /* tp_descr_set */ + 0, /* tp_dictoffset */ + 0, /* tp_init */ + PyType_GenericAlloc, /* tp_alloc */ + rlock_new /* tp_new */ }; static lockobject * newlockobject(void) { - lockobject *self; - self = PyObject_New(lockobject, &Locktype); - if (self == NULL) - return NULL; - self->lock_lock = PyThread_allocate_lock(); - self->in_weakreflist = NULL; - if (self->lock_lock == NULL) { - Py_DECREF(self); - PyErr_SetString(ThreadError, "can't allocate lock"); - return NULL; - } - return self; + lockobject *self; + self = PyObject_New(lockobject, &Locktype); + if (self == NULL) + return NULL; + self->lock_lock = PyThread_allocate_lock(); + self->in_weakreflist = NULL; + if (self->lock_lock == NULL) { + Py_DECREF(self); + PyErr_SetString(ThreadError, "can't allocate lock"); + return NULL; + } + return self; } /* Thread-local objects */ @@ -500,353 +500,353 @@ #include "structmember.h" typedef struct { - PyObject_HEAD - PyObject *key; - PyObject *args; - PyObject *kw; - PyObject *dict; + PyObject_HEAD + PyObject *key; + PyObject *args; + PyObject *kw; + PyObject *dict; } localobject; static PyObject * local_new(PyTypeObject *type, PyObject *args, PyObject *kw) { - localobject *self; - PyObject *tdict; + localobject *self; + PyObject *tdict; - if (type->tp_init == PyBaseObject_Type.tp_init - && ((args && PyObject_IsTrue(args)) - || (kw && PyObject_IsTrue(kw)))) { - PyErr_SetString(PyExc_TypeError, - "Initialization arguments are not supported"); - return NULL; - } - - self = (localobject *)type->tp_alloc(type, 0); - if (self == NULL) - return NULL; - - Py_XINCREF(args); - self->args = args; - Py_XINCREF(kw); - self->kw = kw; - self->dict = NULL; /* making sure */ - self->key = PyUnicode_FromFormat("thread.local.%p", self); - if (self->key == NULL) - goto err; - - self->dict = PyDict_New(); - if (self->dict == NULL) - goto err; - - tdict = PyThreadState_GetDict(); - if (tdict == NULL) { - PyErr_SetString(PyExc_SystemError, - "Couldn't get thread-state dictionary"); - goto err; - } + if (type->tp_init == PyBaseObject_Type.tp_init + && ((args && PyObject_IsTrue(args)) + || (kw && PyObject_IsTrue(kw)))) { + PyErr_SetString(PyExc_TypeError, + "Initialization arguments are not supported"); + return NULL; + } + + self = (localobject *)type->tp_alloc(type, 0); + if (self == NULL) + return NULL; + + Py_XINCREF(args); + self->args = args; + Py_XINCREF(kw); + self->kw = kw; + self->dict = NULL; /* making sure */ + self->key = PyUnicode_FromFormat("thread.local.%p", self); + if (self->key == NULL) + goto err; + + self->dict = PyDict_New(); + if (self->dict == NULL) + goto err; + + tdict = PyThreadState_GetDict(); + if (tdict == NULL) { + PyErr_SetString(PyExc_SystemError, + "Couldn't get thread-state dictionary"); + goto err; + } - if (PyDict_SetItem(tdict, self->key, self->dict) < 0) - goto err; + if (PyDict_SetItem(tdict, self->key, self->dict) < 0) + goto err; - return (PyObject *)self; + return (PyObject *)self; err: - Py_DECREF(self); - return NULL; + Py_DECREF(self); + return NULL; } static int local_traverse(localobject *self, visitproc visit, void *arg) { - Py_VISIT(self->args); - Py_VISIT(self->kw); - Py_VISIT(self->dict); - return 0; + Py_VISIT(self->args); + Py_VISIT(self->kw); + Py_VISIT(self->dict); + return 0; } static int local_clear(localobject *self) { - Py_CLEAR(self->args); - Py_CLEAR(self->kw); - Py_CLEAR(self->dict); - return 0; + Py_CLEAR(self->args); + Py_CLEAR(self->kw); + Py_CLEAR(self->dict); + return 0; } static void local_dealloc(localobject *self) { - PyThreadState *tstate; - if (self->key - && (tstate = PyThreadState_Get()) - && tstate->interp) { - for(tstate = PyInterpreterState_ThreadHead(tstate->interp); - tstate; - tstate = PyThreadState_Next(tstate)) - if (tstate->dict && - PyDict_GetItem(tstate->dict, self->key)) - PyDict_DelItem(tstate->dict, self->key); - } - - Py_XDECREF(self->key); - local_clear(self); - Py_TYPE(self)->tp_free((PyObject*)self); + PyThreadState *tstate; + if (self->key + && (tstate = PyThreadState_Get()) + && tstate->interp) { + for(tstate = PyInterpreterState_ThreadHead(tstate->interp); + tstate; + tstate = PyThreadState_Next(tstate)) + if (tstate->dict && + PyDict_GetItem(tstate->dict, self->key)) + PyDict_DelItem(tstate->dict, self->key); + } + + Py_XDECREF(self->key); + local_clear(self); + Py_TYPE(self)->tp_free((PyObject*)self); } static PyObject * _ldict(localobject *self) { - PyObject *tdict, *ldict; + PyObject *tdict, *ldict; - tdict = PyThreadState_GetDict(); - if (tdict == NULL) { - PyErr_SetString(PyExc_SystemError, - "Couldn't get thread-state dictionary"); - return NULL; - } - - ldict = PyDict_GetItem(tdict, self->key); - if (ldict == NULL) { - ldict = PyDict_New(); /* we own ldict */ - - if (ldict == NULL) - return NULL; - else { - int i = PyDict_SetItem(tdict, self->key, ldict); - Py_DECREF(ldict); /* now ldict is borrowed */ - if (i < 0) - return NULL; - } - - Py_CLEAR(self->dict); - Py_INCREF(ldict); - self->dict = ldict; /* still borrowed */ - - if (Py_TYPE(self)->tp_init != PyBaseObject_Type.tp_init && - Py_TYPE(self)->tp_init((PyObject*)self, - self->args, self->kw) < 0) { - /* we need to get rid of ldict from thread so - we create a new one the next time we do an attr - acces */ - PyDict_DelItem(tdict, self->key); - return NULL; - } - - } - - /* The call to tp_init above may have caused another thread to run. - Install our ldict again. */ - if (self->dict != ldict) { - Py_CLEAR(self->dict); - Py_INCREF(ldict); - self->dict = ldict; - } + tdict = PyThreadState_GetDict(); + if (tdict == NULL) { + PyErr_SetString(PyExc_SystemError, + "Couldn't get thread-state dictionary"); + return NULL; + } + + ldict = PyDict_GetItem(tdict, self->key); + if (ldict == NULL) { + ldict = PyDict_New(); /* we own ldict */ + + if (ldict == NULL) + return NULL; + else { + int i = PyDict_SetItem(tdict, self->key, ldict); + Py_DECREF(ldict); /* now ldict is borrowed */ + if (i < 0) + return NULL; + } + + Py_CLEAR(self->dict); + Py_INCREF(ldict); + self->dict = ldict; /* still borrowed */ + + if (Py_TYPE(self)->tp_init != PyBaseObject_Type.tp_init && + Py_TYPE(self)->tp_init((PyObject*)self, + self->args, self->kw) < 0) { + /* we need to get rid of ldict from thread so + we create a new one the next time we do an attr + acces */ + PyDict_DelItem(tdict, self->key); + return NULL; + } + + } + + /* The call to tp_init above may have caused another thread to run. + Install our ldict again. */ + if (self->dict != ldict) { + Py_CLEAR(self->dict); + Py_INCREF(ldict); + self->dict = ldict; + } - return ldict; + return ldict; } static int local_setattro(localobject *self, PyObject *name, PyObject *v) { - PyObject *ldict; - - ldict = _ldict(self); - if (ldict == NULL) - return -1; + PyObject *ldict; - return PyObject_GenericSetAttr((PyObject *)self, name, v); + ldict = _ldict(self); + if (ldict == NULL) + return -1; + + return PyObject_GenericSetAttr((PyObject *)self, name, v); } static PyObject * local_getdict(localobject *self, void *closure) { - if (self->dict == NULL) { - PyErr_SetString(PyExc_AttributeError, "__dict__"); - return NULL; - } + if (self->dict == NULL) { + PyErr_SetString(PyExc_AttributeError, "__dict__"); + return NULL; + } - Py_INCREF(self->dict); - return self->dict; + Py_INCREF(self->dict); + return self->dict; } static PyGetSetDef local_getset[] = { - {"__dict__", (getter)local_getdict, (setter)NULL, - "Local-data dictionary", NULL}, - {NULL} /* Sentinel */ + {"__dict__", (getter)local_getdict, (setter)NULL, + "Local-data dictionary", NULL}, + {NULL} /* Sentinel */ }; static PyObject *local_getattro(localobject *, PyObject *); static PyTypeObject localtype = { - PyVarObject_HEAD_INIT(NULL, 0) - /* tp_name */ "_thread._local", - /* tp_basicsize */ sizeof(localobject), - /* tp_itemsize */ 0, - /* tp_dealloc */ (destructor)local_dealloc, - /* tp_print */ 0, - /* tp_getattr */ 0, - /* tp_setattr */ 0, - /* tp_reserved */ 0, - /* tp_repr */ 0, - /* tp_as_number */ 0, - /* tp_as_sequence */ 0, - /* tp_as_mapping */ 0, - /* tp_hash */ 0, - /* tp_call */ 0, - /* tp_str */ 0, - /* tp_getattro */ (getattrofunc)local_getattro, - /* tp_setattro */ (setattrofunc)local_setattro, - /* tp_as_buffer */ 0, - /* tp_flags */ Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, - /* tp_doc */ "Thread-local data", - /* tp_traverse */ (traverseproc)local_traverse, - /* tp_clear */ (inquiry)local_clear, - /* tp_richcompare */ 0, - /* tp_weaklistoffset */ 0, - /* tp_iter */ 0, - /* tp_iternext */ 0, - /* tp_methods */ 0, - /* tp_members */ 0, - /* tp_getset */ local_getset, - /* tp_base */ 0, - /* tp_dict */ 0, /* internal use */ - /* tp_descr_get */ 0, - /* tp_descr_set */ 0, - /* tp_dictoffset */ offsetof(localobject, dict), - /* tp_init */ 0, - /* tp_alloc */ 0, - /* tp_new */ local_new, - /* tp_free */ 0, /* Low-level free-mem routine */ - /* tp_is_gc */ 0, /* For PyObject_IS_GC */ + PyVarObject_HEAD_INIT(NULL, 0) + /* tp_name */ "_thread._local", + /* tp_basicsize */ sizeof(localobject), + /* tp_itemsize */ 0, + /* tp_dealloc */ (destructor)local_dealloc, + /* tp_print */ 0, + /* tp_getattr */ 0, + /* tp_setattr */ 0, + /* tp_reserved */ 0, + /* tp_repr */ 0, + /* tp_as_number */ 0, + /* tp_as_sequence */ 0, + /* tp_as_mapping */ 0, + /* tp_hash */ 0, + /* tp_call */ 0, + /* tp_str */ 0, + /* tp_getattro */ (getattrofunc)local_getattro, + /* tp_setattro */ (setattrofunc)local_setattro, + /* tp_as_buffer */ 0, + /* tp_flags */ Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, + /* tp_doc */ "Thread-local data", + /* tp_traverse */ (traverseproc)local_traverse, + /* tp_clear */ (inquiry)local_clear, + /* tp_richcompare */ 0, + /* tp_weaklistoffset */ 0, + /* tp_iter */ 0, + /* tp_iternext */ 0, + /* tp_methods */ 0, + /* tp_members */ 0, + /* tp_getset */ local_getset, + /* tp_base */ 0, + /* tp_dict */ 0, /* internal use */ + /* tp_descr_get */ 0, + /* tp_descr_set */ 0, + /* tp_dictoffset */ offsetof(localobject, dict), + /* tp_init */ 0, + /* tp_alloc */ 0, + /* tp_new */ local_new, + /* tp_free */ 0, /* Low-level free-mem routine */ + /* tp_is_gc */ 0, /* For PyObject_IS_GC */ }; static PyObject * local_getattro(localobject *self, PyObject *name) { - PyObject *ldict, *value; + PyObject *ldict, *value; - ldict = _ldict(self); - if (ldict == NULL) - return NULL; - - if (Py_TYPE(self) != &localtype) - /* use generic lookup for subtypes */ - return PyObject_GenericGetAttr((PyObject *)self, name); - - /* Optimization: just look in dict ourselves */ - value = PyDict_GetItem(ldict, name); - if (value == NULL) - /* Fall back on generic to get __class__ and __dict__ */ - return PyObject_GenericGetAttr((PyObject *)self, name); + ldict = _ldict(self); + if (ldict == NULL) + return NULL; + + if (Py_TYPE(self) != &localtype) + /* use generic lookup for subtypes */ + return PyObject_GenericGetAttr((PyObject *)self, name); + + /* Optimization: just look in dict ourselves */ + value = PyDict_GetItem(ldict, name); + if (value == NULL) + /* Fall back on generic to get __class__ and __dict__ */ + return PyObject_GenericGetAttr((PyObject *)self, name); - Py_INCREF(value); - return value; + Py_INCREF(value); + return value; } /* Module functions */ struct bootstate { - PyInterpreterState *interp; - PyObject *func; - PyObject *args; - PyObject *keyw; - PyThreadState *tstate; + PyInterpreterState *interp; + PyObject *func; + PyObject *args; + PyObject *keyw; + PyThreadState *tstate; }; static void t_bootstrap(void *boot_raw) { - struct bootstate *boot = (struct bootstate *) boot_raw; - PyThreadState *tstate; - PyObject *res; - - tstate = boot->tstate; - tstate->thread_id = PyThread_get_thread_ident(); - _PyThreadState_Init(tstate); - PyEval_AcquireThread(tstate); - nb_threads++; - res = PyEval_CallObjectWithKeywords( - boot->func, boot->args, boot->keyw); - if (res == NULL) { - if (PyErr_ExceptionMatches(PyExc_SystemExit)) - PyErr_Clear(); - else { - PyObject *file; - PySys_WriteStderr( - "Unhandled exception in thread started by "); - file = PySys_GetObject("stderr"); - if (file != NULL && file != Py_None) - PyFile_WriteObject(boot->func, file, 0); - else - PyObject_Print(boot->func, stderr, 0); - PySys_WriteStderr("\n"); - PyErr_PrintEx(0); - } - } - else - Py_DECREF(res); - Py_DECREF(boot->func); - Py_DECREF(boot->args); - Py_XDECREF(boot->keyw); - PyMem_DEL(boot_raw); - nb_threads--; - PyThreadState_Clear(tstate); - PyThreadState_DeleteCurrent(); - PyThread_exit_thread(); + struct bootstate *boot = (struct bootstate *) boot_raw; + PyThreadState *tstate; + PyObject *res; + + tstate = boot->tstate; + tstate->thread_id = PyThread_get_thread_ident(); + _PyThreadState_Init(tstate); + PyEval_AcquireThread(tstate); + nb_threads++; + res = PyEval_CallObjectWithKeywords( + boot->func, boot->args, boot->keyw); + if (res == NULL) { + if (PyErr_ExceptionMatches(PyExc_SystemExit)) + PyErr_Clear(); + else { + PyObject *file; + PySys_WriteStderr( + "Unhandled exception in thread started by "); + file = PySys_GetObject("stderr"); + if (file != NULL && file != Py_None) + PyFile_WriteObject(boot->func, file, 0); + else + PyObject_Print(boot->func, stderr, 0); + PySys_WriteStderr("\n"); + PyErr_PrintEx(0); + } + } + else + Py_DECREF(res); + Py_DECREF(boot->func); + Py_DECREF(boot->args); + Py_XDECREF(boot->keyw); + PyMem_DEL(boot_raw); + nb_threads--; + PyThreadState_Clear(tstate); + PyThreadState_DeleteCurrent(); + PyThread_exit_thread(); } static PyObject * thread_PyThread_start_new_thread(PyObject *self, PyObject *fargs) { - PyObject *func, *args, *keyw = NULL; - struct bootstate *boot; - long ident; - - if (!PyArg_UnpackTuple(fargs, "start_new_thread", 2, 3, - &func, &args, &keyw)) - return NULL; - if (!PyCallable_Check(func)) { - PyErr_SetString(PyExc_TypeError, - "first arg must be callable"); - return NULL; - } - if (!PyTuple_Check(args)) { - PyErr_SetString(PyExc_TypeError, - "2nd arg must be a tuple"); - return NULL; - } - if (keyw != NULL && !PyDict_Check(keyw)) { - PyErr_SetString(PyExc_TypeError, - "optional 3rd arg must be a dictionary"); - return NULL; - } - boot = PyMem_NEW(struct bootstate, 1); - if (boot == NULL) - return PyErr_NoMemory(); - boot->interp = PyThreadState_GET()->interp; - boot->func = func; - boot->args = args; - boot->keyw = keyw; - boot->tstate = _PyThreadState_Prealloc(boot->interp); - if (boot->tstate == NULL) { - PyMem_DEL(boot); - return PyErr_NoMemory(); - } - Py_INCREF(func); - Py_INCREF(args); - Py_XINCREF(keyw); - PyEval_InitThreads(); /* Start the interpreter's thread-awareness */ - ident = PyThread_start_new_thread(t_bootstrap, (void*) boot); - if (ident == -1) { - PyErr_SetString(ThreadError, "can't start new thread"); - Py_DECREF(func); - Py_DECREF(args); - Py_XDECREF(keyw); - PyThreadState_Clear(boot->tstate); - PyMem_DEL(boot); - return NULL; - } - return PyLong_FromLong(ident); + PyObject *func, *args, *keyw = NULL; + struct bootstate *boot; + long ident; + + if (!PyArg_UnpackTuple(fargs, "start_new_thread", 2, 3, + &func, &args, &keyw)) + return NULL; + if (!PyCallable_Check(func)) { + PyErr_SetString(PyExc_TypeError, + "first arg must be callable"); + return NULL; + } + if (!PyTuple_Check(args)) { + PyErr_SetString(PyExc_TypeError, + "2nd arg must be a tuple"); + return NULL; + } + if (keyw != NULL && !PyDict_Check(keyw)) { + PyErr_SetString(PyExc_TypeError, + "optional 3rd arg must be a dictionary"); + return NULL; + } + boot = PyMem_NEW(struct bootstate, 1); + if (boot == NULL) + return PyErr_NoMemory(); + boot->interp = PyThreadState_GET()->interp; + boot->func = func; + boot->args = args; + boot->keyw = keyw; + boot->tstate = _PyThreadState_Prealloc(boot->interp); + if (boot->tstate == NULL) { + PyMem_DEL(boot); + return PyErr_NoMemory(); + } + Py_INCREF(func); + Py_INCREF(args); + Py_XINCREF(keyw); + PyEval_InitThreads(); /* Start the interpreter's thread-awareness */ + ident = PyThread_start_new_thread(t_bootstrap, (void*) boot); + if (ident == -1) { + PyErr_SetString(ThreadError, "can't start new thread"); + Py_DECREF(func); + Py_DECREF(args); + Py_XDECREF(keyw); + PyThreadState_Clear(boot->tstate); + PyMem_DEL(boot); + return NULL; + } + return PyLong_FromLong(ident); } PyDoc_STRVAR(start_new_doc, @@ -863,8 +863,8 @@ static PyObject * thread_PyThread_exit_thread(PyObject *self) { - PyErr_SetNone(PyExc_SystemExit); - return NULL; + PyErr_SetNone(PyExc_SystemExit); + return NULL; } PyDoc_STRVAR(exit_doc, @@ -877,9 +877,9 @@ static PyObject * thread_PyThread_interrupt_main(PyObject * self) { - PyErr_SetInterrupt(); - Py_INCREF(Py_None); - return Py_None; + PyErr_SetInterrupt(); + Py_INCREF(Py_None); + return Py_None; } PyDoc_STRVAR(interrupt_doc, @@ -894,7 +894,7 @@ static PyObject * thread_PyThread_allocate_lock(PyObject *self) { - return (PyObject *) newlockobject(); + return (PyObject *) newlockobject(); } PyDoc_STRVAR(allocate_doc, @@ -906,13 +906,13 @@ static PyObject * thread_get_ident(PyObject *self) { - long ident; - ident = PyThread_get_thread_ident(); - if (ident == -1) { - PyErr_SetString(ThreadError, "no current thread ident"); - return NULL; - } - return PyLong_FromLong(ident); + long ident; + ident = PyThread_get_thread_ident(); + if (ident == -1) { + PyErr_SetString(ThreadError, "no current thread ident"); + return NULL; + } + return PyLong_FromLong(ident); } PyDoc_STRVAR(get_ident_doc, @@ -929,7 +929,7 @@ static PyObject * thread__count(PyObject *self) { - return PyLong_FromLong(nb_threads); + return PyLong_FromLong(nb_threads); } PyDoc_STRVAR(_count_doc, @@ -947,35 +947,35 @@ static PyObject * thread_stack_size(PyObject *self, PyObject *args) { - size_t old_size; - Py_ssize_t new_size = 0; - int rc; - - if (!PyArg_ParseTuple(args, "|n:stack_size", &new_size)) - return NULL; - - if (new_size < 0) { - PyErr_SetString(PyExc_ValueError, - "size must be 0 or a positive value"); - return NULL; - } - - old_size = PyThread_get_stacksize(); - - rc = PyThread_set_stacksize((size_t) new_size); - if (rc == -1) { - PyErr_Format(PyExc_ValueError, - "size not valid: %zd bytes", - new_size); - return NULL; - } - if (rc == -2) { - PyErr_SetString(ThreadError, - "setting stack size not supported"); - return NULL; - } + size_t old_size; + Py_ssize_t new_size = 0; + int rc; + + if (!PyArg_ParseTuple(args, "|n:stack_size", &new_size)) + return NULL; + + if (new_size < 0) { + PyErr_SetString(PyExc_ValueError, + "size must be 0 or a positive value"); + return NULL; + } + + old_size = PyThread_get_stacksize(); + + rc = PyThread_set_stacksize((size_t) new_size); + if (rc == -1) { + PyErr_Format(PyExc_ValueError, + "size not valid: %zd bytes", + new_size); + return NULL; + } + if (rc == -2) { + PyErr_SetString(ThreadError, + "setting stack size not supported"); + return NULL; + } - return PyLong_FromSsize_t((Py_ssize_t) old_size); + return PyLong_FromSsize_t((Py_ssize_t) old_size); } PyDoc_STRVAR(stack_size_doc, @@ -999,30 +999,30 @@ the suggested approach in the absence of more specific information)."); static PyMethodDef thread_methods[] = { - {"start_new_thread", (PyCFunction)thread_PyThread_start_new_thread, - METH_VARARGS, - start_new_doc}, - {"start_new", (PyCFunction)thread_PyThread_start_new_thread, - METH_VARARGS, - start_new_doc}, - {"allocate_lock", (PyCFunction)thread_PyThread_allocate_lock, - METH_NOARGS, allocate_doc}, - {"allocate", (PyCFunction)thread_PyThread_allocate_lock, - METH_NOARGS, allocate_doc}, - {"exit_thread", (PyCFunction)thread_PyThread_exit_thread, - METH_NOARGS, exit_doc}, - {"exit", (PyCFunction)thread_PyThread_exit_thread, - METH_NOARGS, exit_doc}, - {"interrupt_main", (PyCFunction)thread_PyThread_interrupt_main, - METH_NOARGS, interrupt_doc}, - {"get_ident", (PyCFunction)thread_get_ident, - METH_NOARGS, get_ident_doc}, - {"_count", (PyCFunction)thread__count, - METH_NOARGS, _count_doc}, - {"stack_size", (PyCFunction)thread_stack_size, - METH_VARARGS, - stack_size_doc}, - {NULL, NULL} /* sentinel */ + {"start_new_thread", (PyCFunction)thread_PyThread_start_new_thread, + METH_VARARGS, + start_new_doc}, + {"start_new", (PyCFunction)thread_PyThread_start_new_thread, + METH_VARARGS, + start_new_doc}, + {"allocate_lock", (PyCFunction)thread_PyThread_allocate_lock, + METH_NOARGS, allocate_doc}, + {"allocate", (PyCFunction)thread_PyThread_allocate_lock, + METH_NOARGS, allocate_doc}, + {"exit_thread", (PyCFunction)thread_PyThread_exit_thread, + METH_NOARGS, exit_doc}, + {"exit", (PyCFunction)thread_PyThread_exit_thread, + METH_NOARGS, exit_doc}, + {"interrupt_main", (PyCFunction)thread_PyThread_interrupt_main, + METH_NOARGS, interrupt_doc}, + {"get_ident", (PyCFunction)thread_get_ident, + METH_NOARGS, get_ident_doc}, + {"_count", (PyCFunction)thread__count, + METH_NOARGS, _count_doc}, + {"stack_size", (PyCFunction)thread_stack_size, + METH_VARARGS, + stack_size_doc}, + {NULL, NULL} /* sentinel */ }; @@ -1045,61 +1045,61 @@ will block until another thread unlocks it. Deadlocks may ensue."); static struct PyModuleDef threadmodule = { - PyModuleDef_HEAD_INIT, - "_thread", - thread_doc, - -1, - thread_methods, - NULL, - NULL, - NULL, - NULL + PyModuleDef_HEAD_INIT, + "_thread", + thread_doc, + -1, + thread_methods, + NULL, + NULL, + NULL, + NULL }; PyMODINIT_FUNC PyInit__thread(void) { - PyObject *m, *d, *timeout_max; - - /* Initialize types: */ - if (PyType_Ready(&localtype) < 0) - return NULL; - if (PyType_Ready(&Locktype) < 0) - return NULL; - if (PyType_Ready(&RLocktype) < 0) - return NULL; - - /* Create the module and add the functions */ - m = PyModule_Create(&threadmodule); - if (m == NULL) - return NULL; - - timeout_max = PyFloat_FromDouble(PY_TIMEOUT_MAX / 1000000); - if (!timeout_max) - return NULL; - if (PyModule_AddObject(m, "TIMEOUT_MAX", timeout_max) < 0) - return NULL; - - /* Add a symbolic constant */ - d = PyModule_GetDict(m); - ThreadError = PyErr_NewException("_thread.error", NULL, NULL); - PyDict_SetItemString(d, "error", ThreadError); - Locktype.tp_doc = lock_doc; - Py_INCREF(&Locktype); - PyDict_SetItemString(d, "LockType", (PyObject *)&Locktype); - - Py_INCREF(&RLocktype); - if (PyModule_AddObject(m, "RLock", (PyObject *)&RLocktype) < 0) - return NULL; - - Py_INCREF(&localtype); - if (PyModule_AddObject(m, "_local", (PyObject *)&localtype) < 0) - return NULL; - - nb_threads = 0; - - /* Initialize the C thread library */ - PyThread_init_thread(); - return m; + PyObject *m, *d, *timeout_max; + + /* Initialize types: */ + if (PyType_Ready(&localtype) < 0) + return NULL; + if (PyType_Ready(&Locktype) < 0) + return NULL; + if (PyType_Ready(&RLocktype) < 0) + return NULL; + + /* Create the module and add the functions */ + m = PyModule_Create(&threadmodule); + if (m == NULL) + return NULL; + + timeout_max = PyFloat_FromDouble(PY_TIMEOUT_MAX / 1000000); + if (!timeout_max) + return NULL; + if (PyModule_AddObject(m, "TIMEOUT_MAX", timeout_max) < 0) + return NULL; + + /* Add a symbolic constant */ + d = PyModule_GetDict(m); + ThreadError = PyErr_NewException("_thread.error", NULL, NULL); + PyDict_SetItemString(d, "error", ThreadError); + Locktype.tp_doc = lock_doc; + Py_INCREF(&Locktype); + PyDict_SetItemString(d, "LockType", (PyObject *)&Locktype); + + Py_INCREF(&RLocktype); + if (PyModule_AddObject(m, "RLock", (PyObject *)&RLocktype) < 0) + return NULL; + + Py_INCREF(&localtype); + if (PyModule_AddObject(m, "_local", (PyObject *)&localtype) < 0) + return NULL; + + nb_threads = 0; + + /* Initialize the C thread library */ + PyThread_init_thread(); + return m; } Modified: python/branches/py3k/Modules/_tkinter.c ============================================================================== --- python/branches/py3k/Modules/_tkinter.c (original) +++ python/branches/py3k/Modules/_tkinter.c Sun May 9 17:52:27 2010 @@ -9,9 +9,9 @@ /* TCL/TK VERSION INFO: - Only Tcl/Tk 8.3.1 and later are supported. Older versions are not - supported. Use Python 2.6 or older if you cannot upgrade your - Tcl/Tk libraries. + Only Tcl/Tk 8.3.1 and later are supported. Older versions are not + supported. Use Python 2.6 or older if you cannot upgrade your + Tcl/Tk libraries. */ /* XXX Further speed-up ideas, involving Tcl 8.0 features: @@ -197,32 +197,32 @@ #endif #define ENTER_TCL \ - { PyThreadState *tstate = PyThreadState_Get(); Py_BEGIN_ALLOW_THREADS \ - if(tcl_lock)PyThread_acquire_lock(tcl_lock, 1); tcl_tstate = tstate; + { PyThreadState *tstate = PyThreadState_Get(); Py_BEGIN_ALLOW_THREADS \ + if(tcl_lock)PyThread_acquire_lock(tcl_lock, 1); tcl_tstate = tstate; #define LEAVE_TCL \ tcl_tstate = NULL; if(tcl_lock)PyThread_release_lock(tcl_lock); Py_END_ALLOW_THREADS} #define ENTER_OVERLAP \ - Py_END_ALLOW_THREADS + Py_END_ALLOW_THREADS #define LEAVE_OVERLAP_TCL \ - tcl_tstate = NULL; if(tcl_lock)PyThread_release_lock(tcl_lock); } + tcl_tstate = NULL; if(tcl_lock)PyThread_release_lock(tcl_lock); } #define ENTER_PYTHON \ - { PyThreadState *tstate = tcl_tstate; tcl_tstate = NULL; \ - if(tcl_lock)PyThread_release_lock(tcl_lock); PyEval_RestoreThread((tstate)); } + { PyThreadState *tstate = tcl_tstate; tcl_tstate = NULL; \ + if(tcl_lock)PyThread_release_lock(tcl_lock); PyEval_RestoreThread((tstate)); } #define LEAVE_PYTHON \ - { PyThreadState *tstate = PyEval_SaveThread(); \ - if(tcl_lock)PyThread_acquire_lock(tcl_lock, 1); tcl_tstate = tstate; } + { PyThreadState *tstate = PyEval_SaveThread(); \ + if(tcl_lock)PyThread_acquire_lock(tcl_lock, 1); tcl_tstate = tstate; } #define CHECK_TCL_APPARTMENT \ - if (((TkappObject *)self)->threaded && \ - ((TkappObject *)self)->thread_id != Tcl_GetCurrentThread()) { \ - PyErr_SetString(PyExc_RuntimeError, "Calling Tcl from different appartment"); \ - return 0; \ - } + if (((TkappObject *)self)->threaded && \ + ((TkappObject *)self)->thread_id != Tcl_GetCurrentThread()) { \ + PyErr_SetString(PyExc_RuntimeError, "Calling Tcl from different appartment"); \ + return 0; \ + } #else @@ -245,21 +245,21 @@ static PyTypeObject Tkapp_Type; typedef struct { - PyObject_HEAD - Tcl_Interp *interp; - int wantobjects; - int threaded; /* True if tcl_platform[threaded] */ - Tcl_ThreadId thread_id; - int dispatching; - /* We cannot include tclInt.h, as this is internal. - So we cache interesting types here. */ - Tcl_ObjType *BooleanType; - Tcl_ObjType *ByteArrayType; - Tcl_ObjType *DoubleType; - Tcl_ObjType *IntType; - Tcl_ObjType *ListType; - Tcl_ObjType *ProcBodyType; - Tcl_ObjType *StringType; + PyObject_HEAD + Tcl_Interp *interp; + int wantobjects; + int threaded; /* True if tcl_platform[threaded] */ + Tcl_ThreadId thread_id; + int dispatching; + /* We cannot include tclInt.h, as this is internal. + So we cache interesting types here. */ + Tcl_ObjType *BooleanType; + Tcl_ObjType *ByteArrayType; + Tcl_ObjType *DoubleType; + Tcl_ObjType *IntType; + Tcl_ObjType *ListType; + Tcl_ObjType *ProcBodyType; + Tcl_ObjType *StringType; } TkappObject; #define Tkapp_Check(v) (Py_TYPE(v) == &Tkapp_Type) @@ -270,7 +270,7 @@ (void *) v, Py_REFCNT(v))) - + /**** Error Handling ****/ static PyObject *Tkinter_TclError; @@ -284,16 +284,16 @@ static int tk_load_failed = 0; #endif - + static PyObject * Tkinter_Error(PyObject *v) { - PyErr_SetString(Tkinter_TclError, Tkapp_Result(v)); - return NULL; + PyErr_SetString(Tkinter_TclError, Tkapp_Result(v)); + return NULL; } - + /**** Utils ****/ static int Tkinter_busywaitinterval = 20; @@ -306,11 +306,11 @@ static void Sleep(int milli) { - /* XXX Too bad if you don't have select(). */ - struct timeval t; - t.tv_sec = milli/1000; - t.tv_usec = (milli%1000) * 1000; - select(0, (fd_set *)0, (fd_set *)0, (fd_set *)0, &t); + /* XXX Too bad if you don't have select(). */ + struct timeval t; + t.tv_sec = milli/1000; + t.tv_usec = (milli%1000) * 1000; + select(0, (fd_set *)0, (fd_set *)0, (fd_set *)0, &t); } #endif /* MS_WINDOWS */ @@ -319,172 +319,172 @@ static int WaitForMainloop(TkappObject* self) { - int i; - for (i = 0; i < 10; i++) { - if (self->dispatching) - return 1; - Py_BEGIN_ALLOW_THREADS - Sleep(100); - Py_END_ALLOW_THREADS - } - if (self->dispatching) - return 1; - PyErr_SetString(PyExc_RuntimeError, "main thread is not in main loop"); - return 0; + int i; + for (i = 0; i < 10; i++) { + if (self->dispatching) + return 1; + Py_BEGIN_ALLOW_THREADS + Sleep(100); + Py_END_ALLOW_THREADS + } + if (self->dispatching) + return 1; + PyErr_SetString(PyExc_RuntimeError, "main thread is not in main loop"); + return 0; } #endif /* WITH_THREAD */ - + static char * AsString(PyObject *value, PyObject *tmp) { - if (PyBytes_Check(value)) - return PyBytes_AsString(value); - else if (PyUnicode_Check(value)) { - PyObject *v = PyUnicode_AsUTF8String(value); - if (v == NULL) - return NULL; - if (PyList_Append(tmp, v) != 0) { - Py_DECREF(v); - return NULL; - } - Py_DECREF(v); - return PyBytes_AsString(v); - } - else { - PyObject *v = PyObject_Str(value); - if (v == NULL) - return NULL; - if (PyList_Append(tmp, v) != 0) { - Py_DECREF(v); - return NULL; - } - Py_DECREF(v); - return PyBytes_AsString(v); - } + if (PyBytes_Check(value)) + return PyBytes_AsString(value); + else if (PyUnicode_Check(value)) { + PyObject *v = PyUnicode_AsUTF8String(value); + if (v == NULL) + return NULL; + if (PyList_Append(tmp, v) != 0) { + Py_DECREF(v); + return NULL; + } + Py_DECREF(v); + return PyBytes_AsString(v); + } + else { + PyObject *v = PyObject_Str(value); + if (v == NULL) + return NULL; + if (PyList_Append(tmp, v) != 0) { + Py_DECREF(v); + return NULL; + } + Py_DECREF(v); + return PyBytes_AsString(v); + } } - + #define ARGSZ 64 static char * Merge(PyObject *args) { - PyObject *tmp = NULL; - char *argvStore[ARGSZ]; - char **argv = NULL; - int fvStore[ARGSZ]; - int *fv = NULL; - int argc = 0, fvc = 0, i; - char *res = NULL; - - if (!(tmp = PyList_New(0))) - return NULL; - - argv = argvStore; - fv = fvStore; - - if (args == NULL) - argc = 0; - - else if (!PyTuple_Check(args)) { - argc = 1; - fv[0] = 0; - if (!(argv[0] = AsString(args, tmp))) - goto finally; - } - else { - argc = PyTuple_Size(args); - - if (argc > ARGSZ) { - argv = (char **)ckalloc(argc * sizeof(char *)); - fv = (int *)ckalloc(argc * sizeof(int)); - if (argv == NULL || fv == NULL) { - PyErr_NoMemory(); - goto finally; - } - } - - for (i = 0; i < argc; i++) { - PyObject *v = PyTuple_GetItem(args, i); - if (PyTuple_Check(v)) { - fv[i] = 1; - if (!(argv[i] = Merge(v))) - goto finally; - fvc++; - } - else if (v == Py_None) { - argc = i; - break; - } - else { - fv[i] = 0; - if (!(argv[i] = AsString(v, tmp))) - goto finally; - fvc++; - } - } - } - res = Tcl_Merge(argc, argv); - if (res == NULL) - PyErr_SetString(Tkinter_TclError, "merge failed"); + PyObject *tmp = NULL; + char *argvStore[ARGSZ]; + char **argv = NULL; + int fvStore[ARGSZ]; + int *fv = NULL; + int argc = 0, fvc = 0, i; + char *res = NULL; + + if (!(tmp = PyList_New(0))) + return NULL; + + argv = argvStore; + fv = fvStore; + + if (args == NULL) + argc = 0; + + else if (!PyTuple_Check(args)) { + argc = 1; + fv[0] = 0; + if (!(argv[0] = AsString(args, tmp))) + goto finally; + } + else { + argc = PyTuple_Size(args); + + if (argc > ARGSZ) { + argv = (char **)ckalloc(argc * sizeof(char *)); + fv = (int *)ckalloc(argc * sizeof(int)); + if (argv == NULL || fv == NULL) { + PyErr_NoMemory(); + goto finally; + } + } + + for (i = 0; i < argc; i++) { + PyObject *v = PyTuple_GetItem(args, i); + if (PyTuple_Check(v)) { + fv[i] = 1; + if (!(argv[i] = Merge(v))) + goto finally; + fvc++; + } + else if (v == Py_None) { + argc = i; + break; + } + else { + fv[i] = 0; + if (!(argv[i] = AsString(v, tmp))) + goto finally; + fvc++; + } + } + } + res = Tcl_Merge(argc, argv); + if (res == NULL) + PyErr_SetString(Tkinter_TclError, "merge failed"); finally: - for (i = 0; i < fvc; i++) - if (fv[i]) { - ckfree(argv[i]); - } - if (argv != argvStore) - ckfree(FREECAST argv); - if (fv != fvStore) - ckfree(FREECAST fv); + for (i = 0; i < fvc; i++) + if (fv[i]) { + ckfree(argv[i]); + } + if (argv != argvStore) + ckfree(FREECAST argv); + if (fv != fvStore) + ckfree(FREECAST fv); - Py_DECREF(tmp); - return res; + Py_DECREF(tmp); + return res; } - + static PyObject * Split(char *list) { - int argc; - char **argv; - PyObject *v; - - if (list == NULL) { - Py_INCREF(Py_None); - return Py_None; - } - - if (Tcl_SplitList((Tcl_Interp *)NULL, list, &argc, &argv) != TCL_OK) { - /* Not a list. - * Could be a quoted string containing funnies, e.g. {"}. - * Return the string itself. - */ - return PyUnicode_FromString(list); - } - - if (argc == 0) - v = PyUnicode_FromString(""); - else if (argc == 1) - v = PyUnicode_FromString(argv[0]); - else if ((v = PyTuple_New(argc)) != NULL) { - int i; - PyObject *w; - - for (i = 0; i < argc; i++) { - if ((w = Split(argv[i])) == NULL) { - Py_DECREF(v); - v = NULL; - break; - } - PyTuple_SetItem(v, i, w); - } - } - Tcl_Free(FREECAST argv); - return v; + int argc; + char **argv; + PyObject *v; + + if (list == NULL) { + Py_INCREF(Py_None); + return Py_None; + } + + if (Tcl_SplitList((Tcl_Interp *)NULL, list, &argc, &argv) != TCL_OK) { + /* Not a list. + * Could be a quoted string containing funnies, e.g. {"}. + * Return the string itself. + */ + return PyUnicode_FromString(list); + } + + if (argc == 0) + v = PyUnicode_FromString(""); + else if (argc == 1) + v = PyUnicode_FromString(argv[0]); + else if ((v = PyTuple_New(argc)) != NULL) { + int i; + PyObject *w; + + for (i = 0; i < argc; i++) { + if ((w = Split(argv[i])) == NULL) { + Py_DECREF(v); + v = NULL; + break; + } + PyTuple_SetItem(v, i, w); + } + } + Tcl_Free(FREECAST argv); + return v; } /* In some cases, Tcl will still return strings that are supposed to be @@ -494,103 +494,103 @@ static PyObject * SplitObj(PyObject *arg) { - if (PyTuple_Check(arg)) { - int i, size; - PyObject *elem, *newelem, *result; - - size = PyTuple_Size(arg); - result = NULL; - /* Recursively invoke SplitObj for all tuple items. - If this does not return a new object, no action is - needed. */ - for(i = 0; i < size; i++) { - elem = PyTuple_GetItem(arg, i); - newelem = SplitObj(elem); - if (!newelem) { - Py_XDECREF(result); - return NULL; - } - if (!result) { - int k; - if (newelem == elem) { - Py_DECREF(newelem); - continue; - } - result = PyTuple_New(size); - if (!result) - return NULL; - for(k = 0; k < i; k++) { - elem = PyTuple_GetItem(arg, k); - Py_INCREF(elem); - PyTuple_SetItem(result, k, elem); - } - } - PyTuple_SetItem(result, i, newelem); - } - if (result) - return result; - /* Fall through, returning arg. */ - } - else if (PyBytes_Check(arg)) { - int argc; - char **argv; - char *list = PyBytes_AsString(arg); - - if (Tcl_SplitList((Tcl_Interp *)NULL, list, &argc, &argv) != TCL_OK) { - Py_INCREF(arg); - return arg; - } - Tcl_Free(FREECAST argv); - if (argc > 1) - return Split(PyBytes_AsString(arg)); - /* Fall through, returning arg. */ - } - Py_INCREF(arg); - return arg; + if (PyTuple_Check(arg)) { + int i, size; + PyObject *elem, *newelem, *result; + + size = PyTuple_Size(arg); + result = NULL; + /* Recursively invoke SplitObj for all tuple items. + If this does not return a new object, no action is + needed. */ + for(i = 0; i < size; i++) { + elem = PyTuple_GetItem(arg, i); + newelem = SplitObj(elem); + if (!newelem) { + Py_XDECREF(result); + return NULL; + } + if (!result) { + int k; + if (newelem == elem) { + Py_DECREF(newelem); + continue; + } + result = PyTuple_New(size); + if (!result) + return NULL; + for(k = 0; k < i; k++) { + elem = PyTuple_GetItem(arg, k); + Py_INCREF(elem); + PyTuple_SetItem(result, k, elem); + } + } + PyTuple_SetItem(result, i, newelem); + } + if (result) + return result; + /* Fall through, returning arg. */ + } + else if (PyBytes_Check(arg)) { + int argc; + char **argv; + char *list = PyBytes_AsString(arg); + + if (Tcl_SplitList((Tcl_Interp *)NULL, list, &argc, &argv) != TCL_OK) { + Py_INCREF(arg); + return arg; + } + Tcl_Free(FREECAST argv); + if (argc > 1) + return Split(PyBytes_AsString(arg)); + /* Fall through, returning arg. */ + } + Py_INCREF(arg); + return arg; } - + /**** Tkapp Object ****/ #ifndef WITH_APPINIT int Tcl_AppInit(Tcl_Interp *interp) { - const char * _tkinter_skip_tk_init; + const char * _tkinter_skip_tk_init; - if (Tcl_Init(interp) == TCL_ERROR) { - PySys_WriteStderr("Tcl_Init error: %s\n", Tcl_GetStringResult(interp)); - return TCL_ERROR; - } - - _tkinter_skip_tk_init = Tcl_GetVar(interp, - "_tkinter_skip_tk_init", TCL_GLOBAL_ONLY); - if (_tkinter_skip_tk_init != NULL && - strcmp(_tkinter_skip_tk_init, "1") == 0) { - return TCL_OK; - } + if (Tcl_Init(interp) == TCL_ERROR) { + PySys_WriteStderr("Tcl_Init error: %s\n", Tcl_GetStringResult(interp)); + return TCL_ERROR; + } + + _tkinter_skip_tk_init = Tcl_GetVar(interp, + "_tkinter_skip_tk_init", TCL_GLOBAL_ONLY); + if (_tkinter_skip_tk_init != NULL && + strcmp(_tkinter_skip_tk_init, "1") == 0) { + return TCL_OK; + } #ifdef TKINTER_PROTECT_LOADTK - if (tk_load_failed) { - PySys_WriteStderr("Tk_Init error: %s\n", TKINTER_LOADTK_ERRMSG); - return TCL_ERROR; - } + if (tk_load_failed) { + PySys_WriteStderr("Tk_Init error: %s\n", TKINTER_LOADTK_ERRMSG); + return TCL_ERROR; + } #endif - if (Tk_Init(interp) == TCL_ERROR) { + if (Tk_Init(interp) == TCL_ERROR) { #ifdef TKINTER_PROTECT_LOADTK - tk_load_failed = 1; + tk_load_failed = 1; #endif - PySys_WriteStderr("Tk_Init error: %s\n", Tcl_GetStringResult(interp)); - return TCL_ERROR; - } + PySys_WriteStderr("Tk_Init error: %s\n", Tcl_GetStringResult(interp)); + return TCL_ERROR; + } - return TCL_OK; + return TCL_OK; } #endif /* !WITH_APPINIT */ - + /* Initialize the Tk application; see the `main' function in * `tkMain.c'. @@ -601,189 +601,189 @@ static TkappObject * Tkapp_New(char *screenName, char *className, - int interactive, int wantobjects, int wantTk, int sync, char *use) + int interactive, int wantobjects, int wantTk, int sync, char *use) { - TkappObject *v; - char *argv0; + TkappObject *v; + char *argv0; - v = PyObject_New(TkappObject, &Tkapp_Type); - if (v == NULL) - return NULL; - - v->interp = Tcl_CreateInterp(); - v->wantobjects = wantobjects; - v->threaded = Tcl_GetVar2Ex(v->interp, "tcl_platform", "threaded", - TCL_GLOBAL_ONLY) != NULL; - v->thread_id = Tcl_GetCurrentThread(); - v->dispatching = 0; + v = PyObject_New(TkappObject, &Tkapp_Type); + if (v == NULL) + return NULL; + + v->interp = Tcl_CreateInterp(); + v->wantobjects = wantobjects; + v->threaded = Tcl_GetVar2Ex(v->interp, "tcl_platform", "threaded", + TCL_GLOBAL_ONLY) != NULL; + v->thread_id = Tcl_GetCurrentThread(); + v->dispatching = 0; #ifndef TCL_THREADS - if (v->threaded) { - PyErr_SetString(PyExc_RuntimeError, "Tcl is threaded but _tkinter is not"); - Py_DECREF(v); - return 0; - } -#endif -#ifdef WITH_THREAD - if (v->threaded && tcl_lock) { - /* If Tcl is threaded, we don't need the lock. */ - PyThread_free_lock(tcl_lock); - tcl_lock = NULL; - } -#endif - - v->BooleanType = Tcl_GetObjType("boolean"); - v->ByteArrayType = Tcl_GetObjType("bytearray"); - v->DoubleType = Tcl_GetObjType("double"); - v->IntType = Tcl_GetObjType("int"); - v->ListType = Tcl_GetObjType("list"); - v->ProcBodyType = Tcl_GetObjType("procbody"); - v->StringType = Tcl_GetObjType("string"); - - /* Delete the 'exit' command, which can screw things up */ - Tcl_DeleteCommand(v->interp, "exit"); - - if (screenName != NULL) - Tcl_SetVar2(v->interp, "env", "DISPLAY", - screenName, TCL_GLOBAL_ONLY); - - if (interactive) - Tcl_SetVar(v->interp, "tcl_interactive", "1", TCL_GLOBAL_ONLY); - else - Tcl_SetVar(v->interp, "tcl_interactive", "0", TCL_GLOBAL_ONLY); - - /* This is used to get the application class for Tk 4.1 and up */ - argv0 = (char*)ckalloc(strlen(className) + 1); - if (!argv0) { - PyErr_NoMemory(); - Py_DECREF(v); - return NULL; - } - - strcpy(argv0, className); - if (isupper(Py_CHARMASK(argv0[0]))) - argv0[0] = tolower(Py_CHARMASK(argv0[0])); - Tcl_SetVar(v->interp, "argv0", argv0, TCL_GLOBAL_ONLY); - ckfree(argv0); - - if (! wantTk) { - Tcl_SetVar(v->interp, - "_tkinter_skip_tk_init", "1", TCL_GLOBAL_ONLY); - } + if (v->threaded) { + PyErr_SetString(PyExc_RuntimeError, "Tcl is threaded but _tkinter is not"); + Py_DECREF(v); + return 0; + } +#endif +#ifdef WITH_THREAD + if (v->threaded && tcl_lock) { + /* If Tcl is threaded, we don't need the lock. */ + PyThread_free_lock(tcl_lock); + tcl_lock = NULL; + } +#endif + + v->BooleanType = Tcl_GetObjType("boolean"); + v->ByteArrayType = Tcl_GetObjType("bytearray"); + v->DoubleType = Tcl_GetObjType("double"); + v->IntType = Tcl_GetObjType("int"); + v->ListType = Tcl_GetObjType("list"); + v->ProcBodyType = Tcl_GetObjType("procbody"); + v->StringType = Tcl_GetObjType("string"); + + /* Delete the 'exit' command, which can screw things up */ + Tcl_DeleteCommand(v->interp, "exit"); + + if (screenName != NULL) + Tcl_SetVar2(v->interp, "env", "DISPLAY", + screenName, TCL_GLOBAL_ONLY); + + if (interactive) + Tcl_SetVar(v->interp, "tcl_interactive", "1", TCL_GLOBAL_ONLY); + else + Tcl_SetVar(v->interp, "tcl_interactive", "0", TCL_GLOBAL_ONLY); + + /* This is used to get the application class for Tk 4.1 and up */ + argv0 = (char*)ckalloc(strlen(className) + 1); + if (!argv0) { + PyErr_NoMemory(); + Py_DECREF(v); + return NULL; + } + + strcpy(argv0, className); + if (isupper(Py_CHARMASK(argv0[0]))) + argv0[0] = tolower(Py_CHARMASK(argv0[0])); + Tcl_SetVar(v->interp, "argv0", argv0, TCL_GLOBAL_ONLY); + ckfree(argv0); + + if (! wantTk) { + Tcl_SetVar(v->interp, + "_tkinter_skip_tk_init", "1", TCL_GLOBAL_ONLY); + } #ifdef TKINTER_PROTECT_LOADTK - else if (tk_load_failed) { - Tcl_SetVar(v->interp, - "_tkinter_tk_failed", "1", TCL_GLOBAL_ONLY); - } -#endif - - /* some initial arguments need to be in argv */ - if (sync || use) { - char *args; - int len = 0; - - if (sync) - len += sizeof "-sync"; - if (use) - len += strlen(use) + sizeof "-use "; - - args = (char*)ckalloc(len); - if (!args) { - PyErr_NoMemory(); - Py_DECREF(v); - return NULL; - } - - args[0] = '\0'; - if (sync) - strcat(args, "-sync"); - if (use) { - if (sync) - strcat(args, " "); - strcat(args, "-use "); - strcat(args, use); - } - - Tcl_SetVar(v->interp, "argv", args, TCL_GLOBAL_ONLY); - ckfree(args); - } + else if (tk_load_failed) { + Tcl_SetVar(v->interp, + "_tkinter_tk_failed", "1", TCL_GLOBAL_ONLY); + } +#endif + + /* some initial arguments need to be in argv */ + if (sync || use) { + char *args; + int len = 0; + + if (sync) + len += sizeof "-sync"; + if (use) + len += strlen(use) + sizeof "-use "; + + args = (char*)ckalloc(len); + if (!args) { + PyErr_NoMemory(); + Py_DECREF(v); + return NULL; + } + + args[0] = '\0'; + if (sync) + strcat(args, "-sync"); + if (use) { + if (sync) + strcat(args, " "); + strcat(args, "-use "); + strcat(args, use); + } + + Tcl_SetVar(v->interp, "argv", args, TCL_GLOBAL_ONLY); + ckfree(args); + } - if (Tcl_AppInit(v->interp) != TCL_OK) { - PyObject *result = Tkinter_Error((PyObject *)v); + if (Tcl_AppInit(v->interp) != TCL_OK) { + PyObject *result = Tkinter_Error((PyObject *)v); #ifdef TKINTER_PROTECT_LOADTK - if (wantTk) { - const char *_tkinter_tk_failed; - _tkinter_tk_failed = Tcl_GetVar(v->interp, - "_tkinter_tk_failed", TCL_GLOBAL_ONLY); - - if ( _tkinter_tk_failed != NULL && - strcmp(_tkinter_tk_failed, "1") == 0) { - tk_load_failed = 1; - } - } -#endif - Py_DECREF((PyObject *)v); - return (TkappObject *)result; - } + if (wantTk) { + const char *_tkinter_tk_failed; + _tkinter_tk_failed = Tcl_GetVar(v->interp, + "_tkinter_tk_failed", TCL_GLOBAL_ONLY); + + if ( _tkinter_tk_failed != NULL && + strcmp(_tkinter_tk_failed, "1") == 0) { + tk_load_failed = 1; + } + } +#endif + Py_DECREF((PyObject *)v); + return (TkappObject *)result; + } - EnableEventHook(); + EnableEventHook(); - return v; + return v; } #ifdef WITH_THREAD static void Tkapp_ThreadSend(TkappObject *self, Tcl_Event *ev, - Tcl_Condition *cond, Tcl_Mutex *mutex) + Tcl_Condition *cond, Tcl_Mutex *mutex) { - Py_BEGIN_ALLOW_THREADS; - Tcl_MutexLock(mutex); - Tcl_ThreadQueueEvent(self->thread_id, ev, TCL_QUEUE_TAIL); - Tcl_ThreadAlert(self->thread_id); - Tcl_ConditionWait(cond, mutex, NULL); - Tcl_MutexUnlock(mutex); - Py_END_ALLOW_THREADS + Py_BEGIN_ALLOW_THREADS; + Tcl_MutexLock(mutex); + Tcl_ThreadQueueEvent(self->thread_id, ev, TCL_QUEUE_TAIL); + Tcl_ThreadAlert(self->thread_id); + Tcl_ConditionWait(cond, mutex, NULL); + Tcl_MutexUnlock(mutex); + Py_END_ALLOW_THREADS } #endif - + /** Tcl Eval **/ typedef struct { - PyObject_HEAD - Tcl_Obj *value; - PyObject *string; /* This cannot cause cycles. */ + PyObject_HEAD + Tcl_Obj *value; + PyObject *string; /* This cannot cause cycles. */ } PyTclObject; static PyTypeObject PyTclObject_Type; -#define PyTclObject_Check(v) ((v)->ob_type == &PyTclObject_Type) +#define PyTclObject_Check(v) ((v)->ob_type == &PyTclObject_Type) static PyObject * newPyTclObject(Tcl_Obj *arg) { - PyTclObject *self; - self = PyObject_New(PyTclObject, &PyTclObject_Type); - if (self == NULL) - return NULL; - Tcl_IncrRefCount(arg); - self->value = arg; - self->string = NULL; - return (PyObject*)self; + PyTclObject *self; + self = PyObject_New(PyTclObject, &PyTclObject_Type); + if (self == NULL) + return NULL; + Tcl_IncrRefCount(arg); + self->value = arg; + self->string = NULL; + return (PyObject*)self; } static void PyTclObject_dealloc(PyTclObject *self) { - Tcl_DecrRefCount(self->value); - Py_XDECREF(self->string); - PyObject_Del(self); + Tcl_DecrRefCount(self->value); + Py_XDECREF(self->string); + PyObject_Del(self); } static char* PyTclObject_TclString(PyObject *self) { - return Tcl_GetString(((PyTclObject*)self)->value); + return Tcl_GetString(((PyTclObject*)self)->value); } /* Like _str, but create Unicode if necessary. */ @@ -793,37 +793,37 @@ static PyObject * PyTclObject_string(PyTclObject *self, void *ignored) { - char *s; - int len; - if (!self->string) { - s = Tcl_GetStringFromObj(self->value, &len); - self->string = PyUnicode_FromStringAndSize(s, len); - if (!self->string) - return NULL; - } - Py_INCREF(self->string); - return self->string; + char *s; + int len; + if (!self->string) { + s = Tcl_GetStringFromObj(self->value, &len); + self->string = PyUnicode_FromStringAndSize(s, len); + if (!self->string) + return NULL; + } + Py_INCREF(self->string); + return self->string; } static PyObject * PyTclObject_str(PyTclObject *self, void *ignored) { - char *s; - int len; - if (self->string && PyUnicode_Check(self->string)) { - Py_INCREF(self->string); - return self->string; - } - /* XXX Could chache result if it is non-ASCII. */ - s = Tcl_GetStringFromObj(self->value, &len); - return PyUnicode_DecodeUTF8(s, len, "strict"); + char *s; + int len; + if (self->string && PyUnicode_Check(self->string)) { + Py_INCREF(self->string); + return self->string; + } + /* XXX Could chache result if it is non-ASCII. */ + s = Tcl_GetStringFromObj(self->value, &len); + return PyUnicode_DecodeUTF8(s, len, "strict"); } static PyObject * PyTclObject_repr(PyTclObject *self) { - return PyUnicode_FromFormat("<%s object at %p>", - self->value->typePtr->name, self->value); + return PyUnicode_FromFormat("<%s object at %p>", + self->value->typePtr->name, self->value); } #define TEST_COND(cond) ((cond) ? Py_True : Py_False) @@ -831,54 +831,54 @@ static PyObject * PyTclObject_richcompare(PyObject *self, PyObject *other, int op) { - int result; - PyObject *v; + int result; + PyObject *v; - /* neither argument should be NULL, unless something's gone wrong */ - if (self == NULL || other == NULL) { - PyErr_BadInternalCall(); - return NULL; - } - - /* both arguments should be instances of PyTclObject */ - if (!PyTclObject_Check(self) || !PyTclObject_Check(other)) { - v = Py_NotImplemented; - goto finished; - } - - if (self == other) - /* fast path when self and other are identical */ - result = 0; - else - result = strcmp(Tcl_GetString(((PyTclObject *)self)->value), - Tcl_GetString(((PyTclObject *)other)->value)); - /* Convert return value to a Boolean */ - switch (op) { - case Py_EQ: - v = TEST_COND(result == 0); - break; - case Py_NE: - v = TEST_COND(result != 0); - break; - case Py_LE: - v = TEST_COND(result <= 0); - break; - case Py_GE: - v = TEST_COND(result >= 0); - break; - case Py_LT: - v = TEST_COND(result < 0); - break; - case Py_GT: - v = TEST_COND(result > 0); - break; - default: - PyErr_BadArgument(); - return NULL; - } + /* neither argument should be NULL, unless something's gone wrong */ + if (self == NULL || other == NULL) { + PyErr_BadInternalCall(); + return NULL; + } + + /* both arguments should be instances of PyTclObject */ + if (!PyTclObject_Check(self) || !PyTclObject_Check(other)) { + v = Py_NotImplemented; + goto finished; + } + + if (self == other) + /* fast path when self and other are identical */ + result = 0; + else + result = strcmp(Tcl_GetString(((PyTclObject *)self)->value), + Tcl_GetString(((PyTclObject *)other)->value)); + /* Convert return value to a Boolean */ + switch (op) { + case Py_EQ: + v = TEST_COND(result == 0); + break; + case Py_NE: + v = TEST_COND(result != 0); + break; + case Py_LE: + v = TEST_COND(result <= 0); + break; + case Py_GE: + v = TEST_COND(result >= 0); + break; + case Py_LT: + v = TEST_COND(result < 0); + break; + case Py_GT: + v = TEST_COND(result > 0); + break; + default: + PyErr_BadArgument(); + return NULL; + } finished: - Py_INCREF(v); - return v; + Py_INCREF(v); + return v; } PyDoc_STRVAR(get_typename__doc__, "name of the Tcl type"); @@ -886,230 +886,230 @@ static PyObject* get_typename(PyTclObject* obj, void* ignored) { - return PyUnicode_FromString(obj->value->typePtr->name); + return PyUnicode_FromString(obj->value->typePtr->name); } static PyGetSetDef PyTclObject_getsetlist[] = { - {"typename", (getter)get_typename, NULL, get_typename__doc__}, - {"string", (getter)PyTclObject_string, NULL, - PyTclObject_string__doc__}, - {0}, + {"typename", (getter)get_typename, NULL, get_typename__doc__}, + {"string", (getter)PyTclObject_string, NULL, + PyTclObject_string__doc__}, + {0}, }; static PyTypeObject PyTclObject_Type = { - PyVarObject_HEAD_INIT(NULL, 0) - "_tkinter.Tcl_Obj", /*tp_name*/ - sizeof(PyTclObject), /*tp_basicsize*/ - 0, /*tp_itemsize*/ - /* methods */ - (destructor)PyTclObject_dealloc,/*tp_dealloc*/ - 0, /*tp_print*/ - 0, /*tp_getattr*/ - 0, /*tp_setattr*/ - 0, /*tp_reserved*/ - (reprfunc)PyTclObject_repr, /*tp_repr*/ - 0, /*tp_as_number*/ - 0, /*tp_as_sequence*/ - 0, /*tp_as_mapping*/ - 0, /*tp_hash*/ - 0, /*tp_call*/ - (reprfunc)PyTclObject_str, /*tp_str*/ - PyObject_GenericGetAttr, /*tp_getattro*/ - 0, /*tp_setattro*/ - 0, /*tp_as_buffer*/ - Py_TPFLAGS_DEFAULT, /*tp_flags*/ - 0, /*tp_doc*/ - 0, /*tp_traverse*/ - 0, /*tp_clear*/ - PyTclObject_richcompare, /*tp_richcompare*/ - 0, /*tp_weaklistoffset*/ - 0, /*tp_iter*/ - 0, /*tp_iternext*/ - 0, /*tp_methods*/ - 0, /*tp_members*/ - PyTclObject_getsetlist, /*tp_getset*/ - 0, /*tp_base*/ - 0, /*tp_dict*/ - 0, /*tp_descr_get*/ - 0, /*tp_descr_set*/ - 0, /*tp_dictoffset*/ - 0, /*tp_init*/ - 0, /*tp_alloc*/ - 0, /*tp_new*/ - 0, /*tp_free*/ - 0, /*tp_is_gc*/ + PyVarObject_HEAD_INIT(NULL, 0) + "_tkinter.Tcl_Obj", /*tp_name*/ + sizeof(PyTclObject), /*tp_basicsize*/ + 0, /*tp_itemsize*/ + /* methods */ + (destructor)PyTclObject_dealloc,/*tp_dealloc*/ + 0, /*tp_print*/ + 0, /*tp_getattr*/ + 0, /*tp_setattr*/ + 0, /*tp_reserved*/ + (reprfunc)PyTclObject_repr, /*tp_repr*/ + 0, /*tp_as_number*/ + 0, /*tp_as_sequence*/ + 0, /*tp_as_mapping*/ + 0, /*tp_hash*/ + 0, /*tp_call*/ + (reprfunc)PyTclObject_str, /*tp_str*/ + PyObject_GenericGetAttr, /*tp_getattro*/ + 0, /*tp_setattro*/ + 0, /*tp_as_buffer*/ + Py_TPFLAGS_DEFAULT, /*tp_flags*/ + 0, /*tp_doc*/ + 0, /*tp_traverse*/ + 0, /*tp_clear*/ + PyTclObject_richcompare, /*tp_richcompare*/ + 0, /*tp_weaklistoffset*/ + 0, /*tp_iter*/ + 0, /*tp_iternext*/ + 0, /*tp_methods*/ + 0, /*tp_members*/ + PyTclObject_getsetlist, /*tp_getset*/ + 0, /*tp_base*/ + 0, /*tp_dict*/ + 0, /*tp_descr_get*/ + 0, /*tp_descr_set*/ + 0, /*tp_dictoffset*/ + 0, /*tp_init*/ + 0, /*tp_alloc*/ + 0, /*tp_new*/ + 0, /*tp_free*/ + 0, /*tp_is_gc*/ }; static Tcl_Obj* AsObj(PyObject *value) { - Tcl_Obj *result; - long longVal; - int overflow; - - if (PyBytes_Check(value)) - return Tcl_NewStringObj(PyBytes_AS_STRING(value), - PyBytes_GET_SIZE(value)); - else if (PyBool_Check(value)) - return Tcl_NewBooleanObj(PyObject_IsTrue(value)); - else if (PyLong_CheckExact(value) && - ((longVal = PyLong_AsLongAndOverflow(value, &overflow)), - !overflow)) { - /* If there is an overflow in the long conversion, - fall through to default object handling. */ - return Tcl_NewLongObj(longVal); - } - else if (PyFloat_Check(value)) - return Tcl_NewDoubleObj(PyFloat_AS_DOUBLE(value)); - else if (PyTuple_Check(value)) { - Tcl_Obj **argv = (Tcl_Obj**) - ckalloc(PyTuple_Size(value)*sizeof(Tcl_Obj*)); - int i; - if(!argv) - return 0; - for(i=0;i= size) - outbuf = (Tcl_UniChar*)ckalloc(allocsize); - /* Else overflow occurred, and we take the next exit */ - if (!outbuf) { - PyErr_NoMemory(); - return NULL; - } - for (i = 0; i < size; i++) { - if (inbuf[i] >= 0x10000) { - /* Tcl doesn't do UTF-16, yet. */ - PyErr_SetString(PyExc_ValueError, - "unsupported character"); - ckfree(FREECAST outbuf); - return NULL; - } - outbuf[i] = inbuf[i]; - } - result = Tcl_NewUnicodeObj(outbuf, size); - ckfree(FREECAST outbuf); - return result; + Tcl_UniChar *outbuf = NULL; + Py_ssize_t i; + size_t allocsize = ((size_t)size) * sizeof(Tcl_UniChar); + if (allocsize >= size) + outbuf = (Tcl_UniChar*)ckalloc(allocsize); + /* Else overflow occurred, and we take the next exit */ + if (!outbuf) { + PyErr_NoMemory(); + return NULL; + } + for (i = 0; i < size; i++) { + if (inbuf[i] >= 0x10000) { + /* Tcl doesn't do UTF-16, yet. */ + PyErr_SetString(PyExc_ValueError, + "unsupported character"); + ckfree(FREECAST outbuf); + return NULL; + } + outbuf[i] = inbuf[i]; + } + result = Tcl_NewUnicodeObj(outbuf, size); + ckfree(FREECAST outbuf); + return result; #else - return Tcl_NewUnicodeObj(inbuf, size); + return Tcl_NewUnicodeObj(inbuf, size); #endif - } - else if(PyTclObject_Check(value)) { - Tcl_Obj *v = ((PyTclObject*)value)->value; - Tcl_IncrRefCount(v); - return v; - } - else { - PyObject *v = PyObject_Str(value); - if (!v) - return 0; - result = AsObj(v); - Py_DECREF(v); - return result; - } + } + else if(PyTclObject_Check(value)) { + Tcl_Obj *v = ((PyTclObject*)value)->value; + Tcl_IncrRefCount(v); + return v; + } + else { + PyObject *v = PyObject_Str(value); + if (!v) + return 0; + result = AsObj(v); + Py_DECREF(v); + return result; + } } static PyObject* FromObj(PyObject* tkapp, Tcl_Obj *value) { - PyObject *result = NULL; - TkappObject *app = (TkappObject*)tkapp; + PyObject *result = NULL; + TkappObject *app = (TkappObject*)tkapp; - if (value->typePtr == NULL) { - return PyUnicode_FromStringAndSize(value->bytes, - value->length); - } - - if (value->typePtr == app->BooleanType) { - result = value->internalRep.longValue ? Py_True : Py_False; - Py_INCREF(result); - return result; - } - - if (value->typePtr == app->ByteArrayType) { - int size; - char *data = (char*)Tcl_GetByteArrayFromObj(value, &size); - return PyBytes_FromStringAndSize(data, size); - } - - if (value->typePtr == app->DoubleType) { - return PyFloat_FromDouble(value->internalRep.doubleValue); - } - - if (value->typePtr == app->IntType) { - return PyLong_FromLong(value->internalRep.longValue); - } - - if (value->typePtr == app->ListType) { - int size; - int i, status; - PyObject *elem; - Tcl_Obj *tcl_elem; - - status = Tcl_ListObjLength(Tkapp_Interp(tkapp), value, &size); - if (status == TCL_ERROR) - return Tkinter_Error(tkapp); - result = PyTuple_New(size); - if (!result) - return NULL; - for (i = 0; i < size; i++) { - status = Tcl_ListObjIndex(Tkapp_Interp(tkapp), - value, i, &tcl_elem); - if (status == TCL_ERROR) { - Py_DECREF(result); - return Tkinter_Error(tkapp); - } - elem = FromObj(tkapp, tcl_elem); - if (!elem) { - Py_DECREF(result); - return NULL; - } - PyTuple_SetItem(result, i, elem); - } - return result; - } - - if (value->typePtr == app->ProcBodyType) { - /* fall through: return tcl object. */ - } + if (value->typePtr == NULL) { + return PyUnicode_FromStringAndSize(value->bytes, + value->length); + } + + if (value->typePtr == app->BooleanType) { + result = value->internalRep.longValue ? Py_True : Py_False; + Py_INCREF(result); + return result; + } + + if (value->typePtr == app->ByteArrayType) { + int size; + char *data = (char*)Tcl_GetByteArrayFromObj(value, &size); + return PyBytes_FromStringAndSize(data, size); + } + + if (value->typePtr == app->DoubleType) { + return PyFloat_FromDouble(value->internalRep.doubleValue); + } + + if (value->typePtr == app->IntType) { + return PyLong_FromLong(value->internalRep.longValue); + } + + if (value->typePtr == app->ListType) { + int size; + int i, status; + PyObject *elem; + Tcl_Obj *tcl_elem; + + status = Tcl_ListObjLength(Tkapp_Interp(tkapp), value, &size); + if (status == TCL_ERROR) + return Tkinter_Error(tkapp); + result = PyTuple_New(size); + if (!result) + return NULL; + for (i = 0; i < size; i++) { + status = Tcl_ListObjIndex(Tkapp_Interp(tkapp), + value, i, &tcl_elem); + if (status == TCL_ERROR) { + Py_DECREF(result); + return Tkinter_Error(tkapp); + } + elem = FromObj(tkapp, tcl_elem); + if (!elem) { + Py_DECREF(result); + return NULL; + } + PyTuple_SetItem(result, i, elem); + } + return result; + } + + if (value->typePtr == app->ProcBodyType) { + /* fall through: return tcl object. */ + } - if (value->typePtr == app->StringType) { + if (value->typePtr == app->StringType) { #if defined(Py_UNICODE_WIDE) && TCL_UTF_MAX==3 - PyObject *result; - int size; - Tcl_UniChar *input; - Py_UNICODE *output; - - size = Tcl_GetCharLength(value); - result = PyUnicode_FromUnicode(NULL, size); - if (!result) - return NULL; - input = Tcl_GetUnicode(value); - output = PyUnicode_AS_UNICODE(result); - while (size--) - *output++ = *input++; - return result; + PyObject *result; + int size; + Tcl_UniChar *input; + Py_UNICODE *output; + + size = Tcl_GetCharLength(value); + result = PyUnicode_FromUnicode(NULL, size); + if (!result) + return NULL; + input = Tcl_GetUnicode(value); + output = PyUnicode_AS_UNICODE(result); + while (size--) + *output++ = *input++; + return result; #else - return PyUnicode_FromUnicode(Tcl_GetUnicode(value), - Tcl_GetCharLength(value)); + return PyUnicode_FromUnicode(Tcl_GetUnicode(value), + Tcl_GetCharLength(value)); #endif - } + } - return newPyTclObject(value); + return newPyTclObject(value); } #ifdef WITH_THREAD @@ -1117,24 +1117,24 @@ TCL_DECLARE_MUTEX(call_mutex) typedef struct Tkapp_CallEvent { - Tcl_Event ev; /* Must be first */ - TkappObject *self; - PyObject *args; - int flags; - PyObject **res; - PyObject **exc_type, **exc_value, **exc_tb; - Tcl_Condition *done; + Tcl_Event ev; /* Must be first */ + TkappObject *self; + PyObject *args; + int flags; + PyObject **res; + PyObject **exc_type, **exc_value, **exc_tb; + Tcl_Condition *done; } Tkapp_CallEvent; #endif void Tkapp_CallDeallocArgs(Tcl_Obj** objv, Tcl_Obj** objStore, int objc) { - int i; - for (i = 0; i < objc; i++) - Tcl_DecrRefCount(objv[i]); - if (objv != objStore) - ckfree(FREECAST objv); + int i; + for (i = 0; i < objc; i++) + Tcl_DecrRefCount(objv[i]); + if (objv != objStore) + ckfree(FREECAST objv); } /* Convert Python objects to Tcl objects. This must happen in the @@ -1143,51 +1143,51 @@ static Tcl_Obj** Tkapp_CallArgs(PyObject *args, Tcl_Obj** objStore, int *pobjc) { - Tcl_Obj **objv = objStore; - int objc = 0, i; - if (args == NULL) - /* do nothing */; - - else if (!PyTuple_Check(args)) { - objv[0] = AsObj(args); - if (objv[0] == 0) - goto finally; - objc = 1; - Tcl_IncrRefCount(objv[0]); - } - else { - objc = PyTuple_Size(args); - - if (objc > ARGSZ) { - objv = (Tcl_Obj **)ckalloc(objc * sizeof(char *)); - if (objv == NULL) { - PyErr_NoMemory(); - objc = 0; - goto finally; - } - } - - for (i = 0; i < objc; i++) { - PyObject *v = PyTuple_GetItem(args, i); - if (v == Py_None) { - objc = i; - break; - } - objv[i] = AsObj(v); - if (!objv[i]) { - /* Reset objc, so it attempts to clear - objects only up to i. */ - objc = i; - goto finally; - } - Tcl_IncrRefCount(objv[i]); - } - } - *pobjc = objc; - return objv; + Tcl_Obj **objv = objStore; + int objc = 0, i; + if (args == NULL) + /* do nothing */; + + else if (!PyTuple_Check(args)) { + objv[0] = AsObj(args); + if (objv[0] == 0) + goto finally; + objc = 1; + Tcl_IncrRefCount(objv[0]); + } + else { + objc = PyTuple_Size(args); + + if (objc > ARGSZ) { + objv = (Tcl_Obj **)ckalloc(objc * sizeof(char *)); + if (objv == NULL) { + PyErr_NoMemory(); + objc = 0; + goto finally; + } + } + + for (i = 0; i < objc; i++) { + PyObject *v = PyTuple_GetItem(args, i); + if (v == Py_None) { + objc = i; + break; + } + objv[i] = AsObj(v); + if (!objv[i]) { + /* Reset objc, so it attempts to clear + objects only up to i. */ + objc = i; + goto finally; + } + Tcl_IncrRefCount(objv[i]); + } + } + *pobjc = objc; + return objv; finally: - Tkapp_CallDeallocArgs(objv, objStore, objc); - return NULL; + Tkapp_CallDeallocArgs(objv, objStore, objc); + return NULL; } /* Convert the results of a command call into a Python objects. */ @@ -1195,22 +1195,22 @@ static PyObject* Tkapp_CallResult(TkappObject *self) { - PyObject *res = NULL; - if(self->wantobjects) { - Tcl_Obj *value = Tcl_GetObjResult(self->interp); - /* Not sure whether the IncrRef is necessary, but something - may overwrite the interpreter result while we are - converting it. */ - Tcl_IncrRefCount(value); - res = FromObj((PyObject*)self, value); - Tcl_DecrRefCount(value); - } else { - const char *s = Tcl_GetStringResult(self->interp); - const char *p = s; - - res = PyUnicode_FromStringAndSize(s, (int)(p-s)); - } - return res; + PyObject *res = NULL; + if(self->wantobjects) { + Tcl_Obj *value = Tcl_GetObjResult(self->interp); + /* Not sure whether the IncrRef is necessary, but something + may overwrite the interpreter result while we are + converting it. */ + Tcl_IncrRefCount(value); + res = FromObj((PyObject*)self, value); + Tcl_DecrRefCount(value); + } else { + const char *s = Tcl_GetStringResult(self->interp); + const char *p = s; + + res = PyUnicode_FromStringAndSize(s, (int)(p-s)); + } + return res; } #ifdef WITH_THREAD @@ -1222,41 +1222,41 @@ static int Tkapp_CallProc(Tkapp_CallEvent *e, int flags) { - Tcl_Obj *objStore[ARGSZ]; - Tcl_Obj **objv; - int objc; - int i; - ENTER_PYTHON - objv = Tkapp_CallArgs(e->args, objStore, &objc); - if (!objv) { - PyErr_Fetch(e->exc_type, e->exc_value, e->exc_tb); - *(e->res) = NULL; - } - LEAVE_PYTHON - if (!objv) - goto done; - i = Tcl_EvalObjv(e->self->interp, objc, objv, e->flags); - ENTER_PYTHON - if (i == TCL_ERROR) { - *(e->res) = NULL; - *(e->exc_type) = NULL; - *(e->exc_tb) = NULL; - *(e->exc_value) = PyObject_CallFunction( - Tkinter_TclError, "s", - Tcl_GetStringResult(e->self->interp)); - } - else { - *(e->res) = Tkapp_CallResult(e->self); - } - LEAVE_PYTHON + Tcl_Obj *objStore[ARGSZ]; + Tcl_Obj **objv; + int objc; + int i; + ENTER_PYTHON + objv = Tkapp_CallArgs(e->args, objStore, &objc); + if (!objv) { + PyErr_Fetch(e->exc_type, e->exc_value, e->exc_tb); + *(e->res) = NULL; + } + LEAVE_PYTHON + if (!objv) + goto done; + i = Tcl_EvalObjv(e->self->interp, objc, objv, e->flags); + ENTER_PYTHON + if (i == TCL_ERROR) { + *(e->res) = NULL; + *(e->exc_type) = NULL; + *(e->exc_tb) = NULL; + *(e->exc_value) = PyObject_CallFunction( + Tkinter_TclError, "s", + Tcl_GetStringResult(e->self->interp)); + } + else { + *(e->res) = Tkapp_CallResult(e->self); + } + LEAVE_PYTHON - Tkapp_CallDeallocArgs(objv, objStore, objc); + Tkapp_CallDeallocArgs(objv, objStore, objc); done: - /* Wake up calling thread. */ - Tcl_MutexLock(&call_mutex); - Tcl_ConditionNotify(e->done); - Tcl_MutexUnlock(&call_mutex); - return 1; + /* Wake up calling thread. */ + Tcl_MutexLock(&call_mutex); + Tcl_ConditionNotify(e->done); + Tcl_MutexUnlock(&call_mutex); + return 1; } #endif @@ -1276,218 +1276,218 @@ static PyObject * Tkapp_Call(PyObject *selfptr, PyObject *args) { - Tcl_Obj *objStore[ARGSZ]; - Tcl_Obj **objv = NULL; - int objc, i; - PyObject *res = NULL; - TkappObject *self = (TkappObject*)selfptr; - int flags = TCL_EVAL_DIRECT | TCL_EVAL_GLOBAL; - - /* If args is a single tuple, replace with contents of tuple */ - if (1 == PyTuple_Size(args)){ - PyObject* item = PyTuple_GetItem(args, 0); - if (PyTuple_Check(item)) - args = item; - } -#ifdef WITH_THREAD - if (self->threaded && self->thread_id != Tcl_GetCurrentThread()) { - /* We cannot call the command directly. Instead, we must - marshal the parameters to the interpreter thread. */ - Tkapp_CallEvent *ev; - Tcl_Condition cond = NULL; - PyObject *exc_type, *exc_value, *exc_tb; - if (!WaitForMainloop(self)) - return NULL; - ev = (Tkapp_CallEvent*)ckalloc(sizeof(Tkapp_CallEvent)); - ev->ev.proc = (Tcl_EventProc*)Tkapp_CallProc; - ev->self = self; - ev->args = args; - ev->res = &res; - ev->exc_type = &exc_type; - ev->exc_value = &exc_value; - ev->exc_tb = &exc_tb; - ev->done = &cond; - - Tkapp_ThreadSend(self, (Tcl_Event*)ev, &cond, &call_mutex); - - if (res == NULL) { - if (exc_type) - PyErr_Restore(exc_type, exc_value, exc_tb); - else - PyErr_SetObject(Tkinter_TclError, exc_value); - } - Tcl_ConditionFinalize(&cond); - } - else -#endif - { - - objv = Tkapp_CallArgs(args, objStore, &objc); - if (!objv) - return NULL; - - ENTER_TCL - - i = Tcl_EvalObjv(self->interp, objc, objv, flags); - - ENTER_OVERLAP - - if (i == TCL_ERROR) - Tkinter_Error(selfptr); - else - res = Tkapp_CallResult(self); - - LEAVE_OVERLAP_TCL - - Tkapp_CallDeallocArgs(objv, objStore, objc); - } - return res; + Tcl_Obj *objStore[ARGSZ]; + Tcl_Obj **objv = NULL; + int objc, i; + PyObject *res = NULL; + TkappObject *self = (TkappObject*)selfptr; + int flags = TCL_EVAL_DIRECT | TCL_EVAL_GLOBAL; + + /* If args is a single tuple, replace with contents of tuple */ + if (1 == PyTuple_Size(args)){ + PyObject* item = PyTuple_GetItem(args, 0); + if (PyTuple_Check(item)) + args = item; + } +#ifdef WITH_THREAD + if (self->threaded && self->thread_id != Tcl_GetCurrentThread()) { + /* We cannot call the command directly. Instead, we must + marshal the parameters to the interpreter thread. */ + Tkapp_CallEvent *ev; + Tcl_Condition cond = NULL; + PyObject *exc_type, *exc_value, *exc_tb; + if (!WaitForMainloop(self)) + return NULL; + ev = (Tkapp_CallEvent*)ckalloc(sizeof(Tkapp_CallEvent)); + ev->ev.proc = (Tcl_EventProc*)Tkapp_CallProc; + ev->self = self; + ev->args = args; + ev->res = &res; + ev->exc_type = &exc_type; + ev->exc_value = &exc_value; + ev->exc_tb = &exc_tb; + ev->done = &cond; + + Tkapp_ThreadSend(self, (Tcl_Event*)ev, &cond, &call_mutex); + + if (res == NULL) { + if (exc_type) + PyErr_Restore(exc_type, exc_value, exc_tb); + else + PyErr_SetObject(Tkinter_TclError, exc_value); + } + Tcl_ConditionFinalize(&cond); + } + else +#endif + { + + objv = Tkapp_CallArgs(args, objStore, &objc); + if (!objv) + return NULL; + + ENTER_TCL + + i = Tcl_EvalObjv(self->interp, objc, objv, flags); + + ENTER_OVERLAP + + if (i == TCL_ERROR) + Tkinter_Error(selfptr); + else + res = Tkapp_CallResult(self); + + LEAVE_OVERLAP_TCL + + Tkapp_CallDeallocArgs(objv, objStore, objc); + } + return res; } static PyObject * Tkapp_GlobalCall(PyObject *self, PyObject *args) { - /* Could do the same here as for Tkapp_Call(), but this is not used - much, so I can't be bothered. Unfortunately Tcl doesn't export a - way for the user to do what all its Global* variants do (save and - reset the scope pointer, call the local version, restore the saved - scope pointer). */ - - char *cmd; - PyObject *res = NULL; - - CHECK_TCL_APPARTMENT; - - cmd = Merge(args); - if (cmd) { - int err; - ENTER_TCL - err = Tcl_GlobalEval(Tkapp_Interp(self), cmd); - ENTER_OVERLAP - if (err == TCL_ERROR) - res = Tkinter_Error(self); - else - res = PyUnicode_FromString(Tkapp_Result(self)); - LEAVE_OVERLAP_TCL - ckfree(cmd); - } + /* Could do the same here as for Tkapp_Call(), but this is not used + much, so I can't be bothered. Unfortunately Tcl doesn't export a + way for the user to do what all its Global* variants do (save and + reset the scope pointer, call the local version, restore the saved + scope pointer). */ + + char *cmd; + PyObject *res = NULL; + + CHECK_TCL_APPARTMENT; + + cmd = Merge(args); + if (cmd) { + int err; + ENTER_TCL + err = Tcl_GlobalEval(Tkapp_Interp(self), cmd); + ENTER_OVERLAP + if (err == TCL_ERROR) + res = Tkinter_Error(self); + else + res = PyUnicode_FromString(Tkapp_Result(self)); + LEAVE_OVERLAP_TCL + ckfree(cmd); + } - return res; + return res; } static PyObject * Tkapp_Eval(PyObject *self, PyObject *args) { - char *script; - PyObject *res = NULL; - int err; - - if (!PyArg_ParseTuple(args, "s:eval", &script)) - return NULL; - - CHECK_TCL_APPARTMENT; - - ENTER_TCL - err = Tcl_Eval(Tkapp_Interp(self), script); - ENTER_OVERLAP - if (err == TCL_ERROR) - res = Tkinter_Error(self); - else - res = PyUnicode_FromString(Tkapp_Result(self)); - LEAVE_OVERLAP_TCL - return res; + char *script; + PyObject *res = NULL; + int err; + + if (!PyArg_ParseTuple(args, "s:eval", &script)) + return NULL; + + CHECK_TCL_APPARTMENT; + + ENTER_TCL + err = Tcl_Eval(Tkapp_Interp(self), script); + ENTER_OVERLAP + if (err == TCL_ERROR) + res = Tkinter_Error(self); + else + res = PyUnicode_FromString(Tkapp_Result(self)); + LEAVE_OVERLAP_TCL + return res; } static PyObject * Tkapp_GlobalEval(PyObject *self, PyObject *args) { - char *script; - PyObject *res = NULL; - int err; - - if (!PyArg_ParseTuple(args, "s:globaleval", &script)) - return NULL; - - CHECK_TCL_APPARTMENT; - - ENTER_TCL - err = Tcl_GlobalEval(Tkapp_Interp(self), script); - ENTER_OVERLAP - if (err == TCL_ERROR) - res = Tkinter_Error(self); - else - res = PyUnicode_FromString(Tkapp_Result(self)); - LEAVE_OVERLAP_TCL - return res; + char *script; + PyObject *res = NULL; + int err; + + if (!PyArg_ParseTuple(args, "s:globaleval", &script)) + return NULL; + + CHECK_TCL_APPARTMENT; + + ENTER_TCL + err = Tcl_GlobalEval(Tkapp_Interp(self), script); + ENTER_OVERLAP + if (err == TCL_ERROR) + res = Tkinter_Error(self); + else + res = PyUnicode_FromString(Tkapp_Result(self)); + LEAVE_OVERLAP_TCL + return res; } static PyObject * Tkapp_EvalFile(PyObject *self, PyObject *args) { - char *fileName; - PyObject *res = NULL; - int err; - - if (!PyArg_ParseTuple(args, "s:evalfile", &fileName)) - return NULL; - - CHECK_TCL_APPARTMENT; - - ENTER_TCL - err = Tcl_EvalFile(Tkapp_Interp(self), fileName); - ENTER_OVERLAP - if (err == TCL_ERROR) - res = Tkinter_Error(self); - - else - res = PyUnicode_FromString(Tkapp_Result(self)); - LEAVE_OVERLAP_TCL - return res; + char *fileName; + PyObject *res = NULL; + int err; + + if (!PyArg_ParseTuple(args, "s:evalfile", &fileName)) + return NULL; + + CHECK_TCL_APPARTMENT; + + ENTER_TCL + err = Tcl_EvalFile(Tkapp_Interp(self), fileName); + ENTER_OVERLAP + if (err == TCL_ERROR) + res = Tkinter_Error(self); + + else + res = PyUnicode_FromString(Tkapp_Result(self)); + LEAVE_OVERLAP_TCL + return res; } static PyObject * Tkapp_Record(PyObject *self, PyObject *args) { - char *script; - PyObject *res = NULL; - int err; - - if (!PyArg_ParseTuple(args, "s", &script)) - return NULL; - - CHECK_TCL_APPARTMENT; - - ENTER_TCL - err = Tcl_RecordAndEval(Tkapp_Interp(self), script, TCL_NO_EVAL); - ENTER_OVERLAP - if (err == TCL_ERROR) - res = Tkinter_Error(self); - else - res = PyUnicode_FromString(Tkapp_Result(self)); - LEAVE_OVERLAP_TCL - return res; + char *script; + PyObject *res = NULL; + int err; + + if (!PyArg_ParseTuple(args, "s", &script)) + return NULL; + + CHECK_TCL_APPARTMENT; + + ENTER_TCL + err = Tcl_RecordAndEval(Tkapp_Interp(self), script, TCL_NO_EVAL); + ENTER_OVERLAP + if (err == TCL_ERROR) + res = Tkinter_Error(self); + else + res = PyUnicode_FromString(Tkapp_Result(self)); + LEAVE_OVERLAP_TCL + return res; } static PyObject * Tkapp_AddErrorInfo(PyObject *self, PyObject *args) { - char *msg; - - if (!PyArg_ParseTuple(args, "s:adderrorinfo", &msg)) - return NULL; - CHECK_TCL_APPARTMENT; + char *msg; - ENTER_TCL - Tcl_AddErrorInfo(Tkapp_Interp(self), msg); - LEAVE_TCL + if (!PyArg_ParseTuple(args, "s:adderrorinfo", &msg)) + return NULL; + CHECK_TCL_APPARTMENT; + + ENTER_TCL + Tcl_AddErrorInfo(Tkapp_Interp(self), msg); + LEAVE_TCL - Py_INCREF(Py_None); - return Py_None; + Py_INCREF(Py_None); + return Py_None; } - + /** Tcl Variable **/ typedef PyObject* (*EventFunc)(PyObject*, PyObject *args, int flags); @@ -1496,36 +1496,36 @@ TCL_DECLARE_MUTEX(var_mutex) typedef struct VarEvent { - Tcl_Event ev; /* must be first */ - PyObject *self; - PyObject *args; - int flags; - EventFunc func; - PyObject **res; - PyObject **exc_type; - PyObject **exc_val; - Tcl_Condition *cond; + Tcl_Event ev; /* must be first */ + PyObject *self; + PyObject *args; + int flags; + EventFunc func; + PyObject **res; + PyObject **exc_type; + PyObject **exc_val; + Tcl_Condition *cond; } VarEvent; #endif static int varname_converter(PyObject *in, void *_out) { - char **out = (char**)_out; - if (PyBytes_Check(in)) { - *out = PyBytes_AsString(in); - return 1; - } - if (PyUnicode_Check(in)) { - *out = _PyUnicode_AsString(in); - return 1; - } - if (PyTclObject_Check(in)) { - *out = PyTclObject_TclString(in); - return 1; - } - /* XXX: Should give diagnostics. */ - return 0; + char **out = (char**)_out; + if (PyBytes_Check(in)) { + *out = PyBytes_AsString(in); + return 1; + } + if (PyUnicode_Check(in)) { + *out = _PyUnicode_AsString(in); + return 1; + } + if (PyTclObject_Check(in)) { + *out = PyTclObject_TclString(in); + return 1; + } + /* XXX: Should give diagnostics. */ + return 0; } #ifdef WITH_THREAD @@ -1533,28 +1533,28 @@ static void var_perform(VarEvent *ev) { - *(ev->res) = ev->func(ev->self, ev->args, ev->flags); - if (!*(ev->res)) { - PyObject *exc, *val, *tb; - PyErr_Fetch(&exc, &val, &tb); - PyErr_NormalizeException(&exc, &val, &tb); - *(ev->exc_type) = exc; - *(ev->exc_val) = val; - Py_DECREF(tb); - } + *(ev->res) = ev->func(ev->self, ev->args, ev->flags); + if (!*(ev->res)) { + PyObject *exc, *val, *tb; + PyErr_Fetch(&exc, &val, &tb); + PyErr_NormalizeException(&exc, &val, &tb); + *(ev->exc_type) = exc; + *(ev->exc_val) = val; + Py_DECREF(tb); + } } static int var_proc(VarEvent* ev, int flags) { - ENTER_PYTHON - var_perform(ev); - Tcl_MutexLock(&var_mutex); - Tcl_ConditionNotify(ev->cond); - Tcl_MutexUnlock(&var_mutex); - LEAVE_PYTHON - return 1; + ENTER_PYTHON + var_perform(ev); + Tcl_MutexLock(&var_mutex); + Tcl_ConditionNotify(ev->cond); + Tcl_MutexUnlock(&var_mutex); + LEAVE_PYTHON + return 1; } #endif @@ -1563,439 +1563,439 @@ var_invoke(EventFunc func, PyObject *selfptr, PyObject *args, int flags) { #ifdef WITH_THREAD - TkappObject *self = (TkappObject*)selfptr; - if (self->threaded && self->thread_id != Tcl_GetCurrentThread()) { - TkappObject *self = (TkappObject*)selfptr; - VarEvent *ev; - PyObject *res, *exc_type, *exc_val; - Tcl_Condition cond = NULL; - - /* The current thread is not the interpreter thread. Marshal - the call to the interpreter thread, then wait for - completion. */ - if (!WaitForMainloop(self)) - return NULL; - - ev = (VarEvent*)ckalloc(sizeof(VarEvent)); - - ev->self = selfptr; - ev->args = args; - ev->flags = flags; - ev->func = func; - ev->res = &res; - ev->exc_type = &exc_type; - ev->exc_val = &exc_val; - ev->cond = &cond; - ev->ev.proc = (Tcl_EventProc*)var_proc; - Tkapp_ThreadSend(self, (Tcl_Event*)ev, &cond, &var_mutex); - Tcl_ConditionFinalize(&cond); - if (!res) { - PyErr_SetObject(exc_type, exc_val); - Py_DECREF(exc_type); - Py_DECREF(exc_val); - return NULL; - } - return res; - } + TkappObject *self = (TkappObject*)selfptr; + if (self->threaded && self->thread_id != Tcl_GetCurrentThread()) { + TkappObject *self = (TkappObject*)selfptr; + VarEvent *ev; + PyObject *res, *exc_type, *exc_val; + Tcl_Condition cond = NULL; + + /* The current thread is not the interpreter thread. Marshal + the call to the interpreter thread, then wait for + completion. */ + if (!WaitForMainloop(self)) + return NULL; + + ev = (VarEvent*)ckalloc(sizeof(VarEvent)); + + ev->self = selfptr; + ev->args = args; + ev->flags = flags; + ev->func = func; + ev->res = &res; + ev->exc_type = &exc_type; + ev->exc_val = &exc_val; + ev->cond = &cond; + ev->ev.proc = (Tcl_EventProc*)var_proc; + Tkapp_ThreadSend(self, (Tcl_Event*)ev, &cond, &var_mutex); + Tcl_ConditionFinalize(&cond); + if (!res) { + PyErr_SetObject(exc_type, exc_val); + Py_DECREF(exc_type); + Py_DECREF(exc_val); + return NULL; + } + return res; + } #endif - /* Tcl is not threaded, or this is the interpreter thread. */ - return func(selfptr, args, flags); + /* Tcl is not threaded, or this is the interpreter thread. */ + return func(selfptr, args, flags); } static PyObject * SetVar(PyObject *self, PyObject *args, int flags) { - char *name1, *name2; - PyObject *newValue; - PyObject *res = NULL; - Tcl_Obj *newval, *ok; - - if (PyArg_ParseTuple(args, "O&O:setvar", - varname_converter, &name1, &newValue)) { - /* XXX Acquire tcl lock??? */ - newval = AsObj(newValue); - if (newval == NULL) - return NULL; - ENTER_TCL - ok = Tcl_SetVar2Ex(Tkapp_Interp(self), name1, NULL, - newval, flags); - ENTER_OVERLAP - if (!ok) - Tkinter_Error(self); - else { - res = Py_None; - Py_INCREF(res); - } - LEAVE_OVERLAP_TCL - } - else { - PyErr_Clear(); - if (PyArg_ParseTuple(args, "ssO:setvar", - &name1, &name2, &newValue)) { - /* XXX must hold tcl lock already??? */ - newval = AsObj(newValue); - ENTER_TCL - ok = Tcl_SetVar2Ex(Tkapp_Interp(self), name1, name2, newval, flags); - ENTER_OVERLAP - if (!ok) - Tkinter_Error(self); - else { - res = Py_None; - Py_INCREF(res); - } - LEAVE_OVERLAP_TCL - } - else { - return NULL; - } - } - return res; + char *name1, *name2; + PyObject *newValue; + PyObject *res = NULL; + Tcl_Obj *newval, *ok; + + if (PyArg_ParseTuple(args, "O&O:setvar", + varname_converter, &name1, &newValue)) { + /* XXX Acquire tcl lock??? */ + newval = AsObj(newValue); + if (newval == NULL) + return NULL; + ENTER_TCL + ok = Tcl_SetVar2Ex(Tkapp_Interp(self), name1, NULL, + newval, flags); + ENTER_OVERLAP + if (!ok) + Tkinter_Error(self); + else { + res = Py_None; + Py_INCREF(res); + } + LEAVE_OVERLAP_TCL + } + else { + PyErr_Clear(); + if (PyArg_ParseTuple(args, "ssO:setvar", + &name1, &name2, &newValue)) { + /* XXX must hold tcl lock already??? */ + newval = AsObj(newValue); + ENTER_TCL + ok = Tcl_SetVar2Ex(Tkapp_Interp(self), name1, name2, newval, flags); + ENTER_OVERLAP + if (!ok) + Tkinter_Error(self); + else { + res = Py_None; + Py_INCREF(res); + } + LEAVE_OVERLAP_TCL + } + else { + return NULL; + } + } + return res; } static PyObject * Tkapp_SetVar(PyObject *self, PyObject *args) { - return var_invoke(SetVar, self, args, TCL_LEAVE_ERR_MSG); + return var_invoke(SetVar, self, args, TCL_LEAVE_ERR_MSG); } static PyObject * Tkapp_GlobalSetVar(PyObject *self, PyObject *args) { - return var_invoke(SetVar, self, args, TCL_LEAVE_ERR_MSG | TCL_GLOBAL_ONLY); + return var_invoke(SetVar, self, args, TCL_LEAVE_ERR_MSG | TCL_GLOBAL_ONLY); } - + static PyObject * GetVar(PyObject *self, PyObject *args, int flags) { - char *name1, *name2=NULL; - PyObject *res = NULL; - Tcl_Obj *tres; - - if (!PyArg_ParseTuple(args, "O&|s:getvar", - varname_converter, &name1, &name2)) - return NULL; - - ENTER_TCL - tres = Tcl_GetVar2Ex(Tkapp_Interp(self), name1, name2, flags); - ENTER_OVERLAP - if (tres == NULL) { - PyErr_SetString(Tkinter_TclError, Tcl_GetStringResult(Tkapp_Interp(self))); - } else { - if (((TkappObject*)self)->wantobjects) { - res = FromObj(self, tres); - } - else { - res = PyUnicode_FromString(Tcl_GetString(tres)); - } - } - LEAVE_OVERLAP_TCL - return res; + char *name1, *name2=NULL; + PyObject *res = NULL; + Tcl_Obj *tres; + + if (!PyArg_ParseTuple(args, "O&|s:getvar", + varname_converter, &name1, &name2)) + return NULL; + + ENTER_TCL + tres = Tcl_GetVar2Ex(Tkapp_Interp(self), name1, name2, flags); + ENTER_OVERLAP + if (tres == NULL) { + PyErr_SetString(Tkinter_TclError, Tcl_GetStringResult(Tkapp_Interp(self))); + } else { + if (((TkappObject*)self)->wantobjects) { + res = FromObj(self, tres); + } + else { + res = PyUnicode_FromString(Tcl_GetString(tres)); + } + } + LEAVE_OVERLAP_TCL + return res; } static PyObject * Tkapp_GetVar(PyObject *self, PyObject *args) { - return var_invoke(GetVar, self, args, TCL_LEAVE_ERR_MSG); + return var_invoke(GetVar, self, args, TCL_LEAVE_ERR_MSG); } static PyObject * Tkapp_GlobalGetVar(PyObject *self, PyObject *args) { - return var_invoke(GetVar, self, args, TCL_LEAVE_ERR_MSG | TCL_GLOBAL_ONLY); + return var_invoke(GetVar, self, args, TCL_LEAVE_ERR_MSG | TCL_GLOBAL_ONLY); } - + static PyObject * UnsetVar(PyObject *self, PyObject *args, int flags) { - char *name1, *name2=NULL; - int code; - PyObject *res = NULL; - - if (!PyArg_ParseTuple(args, "s|s:unsetvar", &name1, &name2)) - return NULL; - - ENTER_TCL - code = Tcl_UnsetVar2(Tkapp_Interp(self), name1, name2, flags); - ENTER_OVERLAP - if (code == TCL_ERROR) - res = Tkinter_Error(self); - else { - Py_INCREF(Py_None); - res = Py_None; - } - LEAVE_OVERLAP_TCL - return res; + char *name1, *name2=NULL; + int code; + PyObject *res = NULL; + + if (!PyArg_ParseTuple(args, "s|s:unsetvar", &name1, &name2)) + return NULL; + + ENTER_TCL + code = Tcl_UnsetVar2(Tkapp_Interp(self), name1, name2, flags); + ENTER_OVERLAP + if (code == TCL_ERROR) + res = Tkinter_Error(self); + else { + Py_INCREF(Py_None); + res = Py_None; + } + LEAVE_OVERLAP_TCL + return res; } static PyObject * Tkapp_UnsetVar(PyObject *self, PyObject *args) { - return var_invoke(UnsetVar, self, args, TCL_LEAVE_ERR_MSG); + return var_invoke(UnsetVar, self, args, TCL_LEAVE_ERR_MSG); } static PyObject * Tkapp_GlobalUnsetVar(PyObject *self, PyObject *args) { - return var_invoke(UnsetVar, self, args, TCL_LEAVE_ERR_MSG | TCL_GLOBAL_ONLY); + return var_invoke(UnsetVar, self, args, TCL_LEAVE_ERR_MSG | TCL_GLOBAL_ONLY); } - + /** Tcl to Python **/ static PyObject * Tkapp_GetInt(PyObject *self, PyObject *args) { - char *s; - int v; + char *s; + int v; - if (PyTuple_Size(args) == 1) { - PyObject* o = PyTuple_GetItem(args, 0); - if (PyLong_Check(o)) { - Py_INCREF(o); - return o; - } - } - if (!PyArg_ParseTuple(args, "s:getint", &s)) - return NULL; - if (Tcl_GetInt(Tkapp_Interp(self), s, &v) == TCL_ERROR) - return Tkinter_Error(self); - return Py_BuildValue("i", v); + if (PyTuple_Size(args) == 1) { + PyObject* o = PyTuple_GetItem(args, 0); + if (PyLong_Check(o)) { + Py_INCREF(o); + return o; + } + } + if (!PyArg_ParseTuple(args, "s:getint", &s)) + return NULL; + if (Tcl_GetInt(Tkapp_Interp(self), s, &v) == TCL_ERROR) + return Tkinter_Error(self); + return Py_BuildValue("i", v); } static PyObject * Tkapp_GetDouble(PyObject *self, PyObject *args) { - char *s; - double v; + char *s; + double v; - if (PyTuple_Size(args) == 1) { - PyObject *o = PyTuple_GetItem(args, 0); - if (PyFloat_Check(o)) { - Py_INCREF(o); - return o; - } - } - if (!PyArg_ParseTuple(args, "s:getdouble", &s)) - return NULL; - if (Tcl_GetDouble(Tkapp_Interp(self), s, &v) == TCL_ERROR) - return Tkinter_Error(self); - return Py_BuildValue("d", v); + if (PyTuple_Size(args) == 1) { + PyObject *o = PyTuple_GetItem(args, 0); + if (PyFloat_Check(o)) { + Py_INCREF(o); + return o; + } + } + if (!PyArg_ParseTuple(args, "s:getdouble", &s)) + return NULL; + if (Tcl_GetDouble(Tkapp_Interp(self), s, &v) == TCL_ERROR) + return Tkinter_Error(self); + return Py_BuildValue("d", v); } static PyObject * Tkapp_GetBoolean(PyObject *self, PyObject *args) { - char *s; - int v; + char *s; + int v; - if (PyTuple_Size(args) == 1) { - PyObject *o = PyTuple_GetItem(args, 0); - if (PyLong_Check(o)) { - Py_INCREF(o); - return o; - } - } - if (!PyArg_ParseTuple(args, "s:getboolean", &s)) - return NULL; - if (Tcl_GetBoolean(Tkapp_Interp(self), s, &v) == TCL_ERROR) - return Tkinter_Error(self); - return PyBool_FromLong(v); + if (PyTuple_Size(args) == 1) { + PyObject *o = PyTuple_GetItem(args, 0); + if (PyLong_Check(o)) { + Py_INCREF(o); + return o; + } + } + if (!PyArg_ParseTuple(args, "s:getboolean", &s)) + return NULL; + if (Tcl_GetBoolean(Tkapp_Interp(self), s, &v) == TCL_ERROR) + return Tkinter_Error(self); + return PyBool_FromLong(v); } static PyObject * Tkapp_ExprString(PyObject *self, PyObject *args) { - char *s; - PyObject *res = NULL; - int retval; - - if (!PyArg_ParseTuple(args, "s:exprstring", &s)) - return NULL; - - CHECK_TCL_APPARTMENT; - - ENTER_TCL - retval = Tcl_ExprString(Tkapp_Interp(self), s); - ENTER_OVERLAP - if (retval == TCL_ERROR) - res = Tkinter_Error(self); - else - res = Py_BuildValue("s", Tkapp_Result(self)); - LEAVE_OVERLAP_TCL - return res; + char *s; + PyObject *res = NULL; + int retval; + + if (!PyArg_ParseTuple(args, "s:exprstring", &s)) + return NULL; + + CHECK_TCL_APPARTMENT; + + ENTER_TCL + retval = Tcl_ExprString(Tkapp_Interp(self), s); + ENTER_OVERLAP + if (retval == TCL_ERROR) + res = Tkinter_Error(self); + else + res = Py_BuildValue("s", Tkapp_Result(self)); + LEAVE_OVERLAP_TCL + return res; } static PyObject * Tkapp_ExprLong(PyObject *self, PyObject *args) { - char *s; - PyObject *res = NULL; - int retval; - long v; - - if (!PyArg_ParseTuple(args, "s:exprlong", &s)) - return NULL; - - CHECK_TCL_APPARTMENT; - - ENTER_TCL - retval = Tcl_ExprLong(Tkapp_Interp(self), s, &v); - ENTER_OVERLAP - if (retval == TCL_ERROR) - res = Tkinter_Error(self); - else - res = Py_BuildValue("l", v); - LEAVE_OVERLAP_TCL - return res; + char *s; + PyObject *res = NULL; + int retval; + long v; + + if (!PyArg_ParseTuple(args, "s:exprlong", &s)) + return NULL; + + CHECK_TCL_APPARTMENT; + + ENTER_TCL + retval = Tcl_ExprLong(Tkapp_Interp(self), s, &v); + ENTER_OVERLAP + if (retval == TCL_ERROR) + res = Tkinter_Error(self); + else + res = Py_BuildValue("l", v); + LEAVE_OVERLAP_TCL + return res; } static PyObject * Tkapp_ExprDouble(PyObject *self, PyObject *args) { - char *s; - PyObject *res = NULL; - double v; - int retval; - - if (!PyArg_ParseTuple(args, "s:exprdouble", &s)) - return NULL; - CHECK_TCL_APPARTMENT; - PyFPE_START_PROTECT("Tkapp_ExprDouble", return 0) - ENTER_TCL - retval = Tcl_ExprDouble(Tkapp_Interp(self), s, &v); - ENTER_OVERLAP - PyFPE_END_PROTECT(retval) - if (retval == TCL_ERROR) - res = Tkinter_Error(self); - else - res = Py_BuildValue("d", v); - LEAVE_OVERLAP_TCL - return res; + char *s; + PyObject *res = NULL; + double v; + int retval; + + if (!PyArg_ParseTuple(args, "s:exprdouble", &s)) + return NULL; + CHECK_TCL_APPARTMENT; + PyFPE_START_PROTECT("Tkapp_ExprDouble", return 0) + ENTER_TCL + retval = Tcl_ExprDouble(Tkapp_Interp(self), s, &v); + ENTER_OVERLAP + PyFPE_END_PROTECT(retval) + if (retval == TCL_ERROR) + res = Tkinter_Error(self); + else + res = Py_BuildValue("d", v); + LEAVE_OVERLAP_TCL + return res; } static PyObject * Tkapp_ExprBoolean(PyObject *self, PyObject *args) { - char *s; - PyObject *res = NULL; - int retval; - int v; - - if (!PyArg_ParseTuple(args, "s:exprboolean", &s)) - return NULL; - CHECK_TCL_APPARTMENT; - ENTER_TCL - retval = Tcl_ExprBoolean(Tkapp_Interp(self), s, &v); - ENTER_OVERLAP - if (retval == TCL_ERROR) - res = Tkinter_Error(self); - else - res = Py_BuildValue("i", v); - LEAVE_OVERLAP_TCL - return res; + char *s; + PyObject *res = NULL; + int retval; + int v; + + if (!PyArg_ParseTuple(args, "s:exprboolean", &s)) + return NULL; + CHECK_TCL_APPARTMENT; + ENTER_TCL + retval = Tcl_ExprBoolean(Tkapp_Interp(self), s, &v); + ENTER_OVERLAP + if (retval == TCL_ERROR) + res = Tkinter_Error(self); + else + res = Py_BuildValue("i", v); + LEAVE_OVERLAP_TCL + return res; } - + static PyObject * Tkapp_SplitList(PyObject *self, PyObject *args) { - char *list; - int argc; - char **argv; - PyObject *v; - int i; - - if (PyTuple_Size(args) == 1) { - v = PyTuple_GetItem(args, 0); - if (PyTuple_Check(v)) { - Py_INCREF(v); - return v; - } - } - if (!PyArg_ParseTuple(args, "et:splitlist", "utf-8", &list)) - return NULL; - - if (Tcl_SplitList(Tkapp_Interp(self), list, - &argc, &argv) == TCL_ERROR) { - PyMem_Free(list); - return Tkinter_Error(self); - } - - if (!(v = PyTuple_New(argc))) - goto finally; - - for (i = 0; i < argc; i++) { - PyObject *s = PyUnicode_FromString(argv[i]); - if (!s || PyTuple_SetItem(v, i, s)) { - Py_DECREF(v); - v = NULL; - goto finally; - } - } + char *list; + int argc; + char **argv; + PyObject *v; + int i; + + if (PyTuple_Size(args) == 1) { + v = PyTuple_GetItem(args, 0); + if (PyTuple_Check(v)) { + Py_INCREF(v); + return v; + } + } + if (!PyArg_ParseTuple(args, "et:splitlist", "utf-8", &list)) + return NULL; + + if (Tcl_SplitList(Tkapp_Interp(self), list, + &argc, &argv) == TCL_ERROR) { + PyMem_Free(list); + return Tkinter_Error(self); + } + + if (!(v = PyTuple_New(argc))) + goto finally; + + for (i = 0; i < argc; i++) { + PyObject *s = PyUnicode_FromString(argv[i]); + if (!s || PyTuple_SetItem(v, i, s)) { + Py_DECREF(v); + v = NULL; + goto finally; + } + } finally: - ckfree(FREECAST argv); - PyMem_Free(list); - return v; + ckfree(FREECAST argv); + PyMem_Free(list); + return v; } static PyObject * Tkapp_Split(PyObject *self, PyObject *args) { - PyObject *v; - char *list; + PyObject *v; + char *list; - if (PyTuple_Size(args) == 1) { - PyObject* o = PyTuple_GetItem(args, 0); - if (PyTuple_Check(o)) { - o = SplitObj(o); - return o; - } - } - if (!PyArg_ParseTuple(args, "et:split", "utf-8", &list)) - return NULL; - v = Split(list); - PyMem_Free(list); - return v; + if (PyTuple_Size(args) == 1) { + PyObject* o = PyTuple_GetItem(args, 0); + if (PyTuple_Check(o)) { + o = SplitObj(o); + return o; + } + } + if (!PyArg_ParseTuple(args, "et:split", "utf-8", &list)) + return NULL; + v = Split(list); + PyMem_Free(list); + return v; } static PyObject * Tkapp_Merge(PyObject *self, PyObject *args) { - char *s = Merge(args); - PyObject *res = NULL; + char *s = Merge(args); + PyObject *res = NULL; - if (s) { - res = PyUnicode_FromString(s); - ckfree(s); - } + if (s) { + res = PyUnicode_FromString(s); + ckfree(s); + } - return res; + return res; } - + /** Tcl Command **/ /* Client data struct */ typedef struct { - PyObject *self; - PyObject *func; + PyObject *self; + PyObject *func; } PythonCmd_ClientData; static int PythonCmd_Error(Tcl_Interp *interp) { - errorInCmd = 1; - PyErr_Fetch(&excInCmd, &valInCmd, &trbInCmd); - LEAVE_PYTHON - return TCL_ERROR; + errorInCmd = 1; + PyErr_Fetch(&excInCmd, &valInCmd, &trbInCmd); + LEAVE_PYTHON + return TCL_ERROR; } /* This is the Tcl command that acts as a wrapper for Python @@ -2004,211 +2004,211 @@ static int PythonCmd(ClientData clientData, Tcl_Interp *interp, int argc, char *argv[]) { - PythonCmd_ClientData *data = (PythonCmd_ClientData *)clientData; - PyObject *self, *func, *arg, *res; - int i, rv; - Tcl_Obj *obj_res; - - ENTER_PYTHON - - /* TBD: no error checking here since we know, via the - * Tkapp_CreateCommand() that the client data is a two-tuple - */ - self = data->self; - func = data->func; - - /* Create argument list (argv1, ..., argvN) */ - if (!(arg = PyTuple_New(argc - 1))) - return PythonCmd_Error(interp); - - for (i = 0; i < (argc - 1); i++) { - PyObject *s = PyUnicode_FromString(argv[i + 1]); - if (!s || PyTuple_SetItem(arg, i, s)) { - Py_DECREF(arg); - return PythonCmd_Error(interp); - } - } - res = PyEval_CallObject(func, arg); - Py_DECREF(arg); - - if (res == NULL) - return PythonCmd_Error(interp); - - obj_res = AsObj(res); - if (obj_res == NULL) { - Py_DECREF(res); - return PythonCmd_Error(interp); - } - else { - Tcl_SetObjResult(interp, obj_res); - rv = TCL_OK; - } + PythonCmd_ClientData *data = (PythonCmd_ClientData *)clientData; + PyObject *self, *func, *arg, *res; + int i, rv; + Tcl_Obj *obj_res; + + ENTER_PYTHON + + /* TBD: no error checking here since we know, via the + * Tkapp_CreateCommand() that the client data is a two-tuple + */ + self = data->self; + func = data->func; + + /* Create argument list (argv1, ..., argvN) */ + if (!(arg = PyTuple_New(argc - 1))) + return PythonCmd_Error(interp); + + for (i = 0; i < (argc - 1); i++) { + PyObject *s = PyUnicode_FromString(argv[i + 1]); + if (!s || PyTuple_SetItem(arg, i, s)) { + Py_DECREF(arg); + return PythonCmd_Error(interp); + } + } + res = PyEval_CallObject(func, arg); + Py_DECREF(arg); + + if (res == NULL) + return PythonCmd_Error(interp); + + obj_res = AsObj(res); + if (obj_res == NULL) { + Py_DECREF(res); + return PythonCmd_Error(interp); + } + else { + Tcl_SetObjResult(interp, obj_res); + rv = TCL_OK; + } - Py_DECREF(res); + Py_DECREF(res); - LEAVE_PYTHON + LEAVE_PYTHON - return rv; + return rv; } static void PythonCmdDelete(ClientData clientData) { - PythonCmd_ClientData *data = (PythonCmd_ClientData *)clientData; + PythonCmd_ClientData *data = (PythonCmd_ClientData *)clientData; - ENTER_PYTHON - Py_XDECREF(data->self); - Py_XDECREF(data->func); - PyMem_DEL(data); - LEAVE_PYTHON + ENTER_PYTHON + Py_XDECREF(data->self); + Py_XDECREF(data->func); + PyMem_DEL(data); + LEAVE_PYTHON } - + #ifdef WITH_THREAD TCL_DECLARE_MUTEX(command_mutex) typedef struct CommandEvent{ - Tcl_Event ev; - Tcl_Interp* interp; - char *name; - int create; - int *status; - ClientData *data; - Tcl_Condition *done; + Tcl_Event ev; + Tcl_Interp* interp; + char *name; + int create; + int *status; + ClientData *data; + Tcl_Condition *done; } CommandEvent; static int Tkapp_CommandProc(CommandEvent *ev, int flags) { - if (ev->create) - *ev->status = Tcl_CreateCommand( - ev->interp, ev->name, PythonCmd, - ev->data, PythonCmdDelete) == NULL; - else - *ev->status = Tcl_DeleteCommand(ev->interp, ev->name); - Tcl_MutexLock(&command_mutex); - Tcl_ConditionNotify(ev->done); - Tcl_MutexUnlock(&command_mutex); - return 1; + if (ev->create) + *ev->status = Tcl_CreateCommand( + ev->interp, ev->name, PythonCmd, + ev->data, PythonCmdDelete) == NULL; + else + *ev->status = Tcl_DeleteCommand(ev->interp, ev->name); + Tcl_MutexLock(&command_mutex); + Tcl_ConditionNotify(ev->done); + Tcl_MutexUnlock(&command_mutex); + return 1; } #endif static PyObject * Tkapp_CreateCommand(PyObject *selfptr, PyObject *args) { - TkappObject *self = (TkappObject*)selfptr; - PythonCmd_ClientData *data; - char *cmdName; - PyObject *func; - int err; - - if (!PyArg_ParseTuple(args, "sO:createcommand", &cmdName, &func)) - return NULL; - if (!PyCallable_Check(func)) { - PyErr_SetString(PyExc_TypeError, "command not callable"); - return NULL; - } - -#ifdef WITH_THREAD - if (self->threaded && self->thread_id != Tcl_GetCurrentThread() && - !WaitForMainloop(self)) - return NULL; -#endif - - data = PyMem_NEW(PythonCmd_ClientData, 1); - if (!data) - return PyErr_NoMemory(); - Py_INCREF(self); - Py_INCREF(func); - data->self = selfptr; - data->func = func; -#ifdef WITH_THREAD - if (self->threaded && self->thread_id != Tcl_GetCurrentThread()) { - Tcl_Condition cond = NULL; - CommandEvent *ev = (CommandEvent*)ckalloc(sizeof(CommandEvent)); - ev->ev.proc = (Tcl_EventProc*)Tkapp_CommandProc; - ev->interp = self->interp; - ev->create = 1; - ev->name = cmdName; - ev->data = (ClientData)data; - ev->status = &err; - ev->done = &cond; - Tkapp_ThreadSend(self, (Tcl_Event*)ev, &cond, &command_mutex); - Tcl_ConditionFinalize(&cond); - } - else -#endif - { - ENTER_TCL - err = Tcl_CreateCommand( - Tkapp_Interp(self), cmdName, PythonCmd, - (ClientData)data, PythonCmdDelete) == NULL; - LEAVE_TCL - } - if (err) { - PyErr_SetString(Tkinter_TclError, "can't create Tcl command"); - PyMem_DEL(data); - return NULL; - } + TkappObject *self = (TkappObject*)selfptr; + PythonCmd_ClientData *data; + char *cmdName; + PyObject *func; + int err; + + if (!PyArg_ParseTuple(args, "sO:createcommand", &cmdName, &func)) + return NULL; + if (!PyCallable_Check(func)) { + PyErr_SetString(PyExc_TypeError, "command not callable"); + return NULL; + } + +#ifdef WITH_THREAD + if (self->threaded && self->thread_id != Tcl_GetCurrentThread() && + !WaitForMainloop(self)) + return NULL; +#endif + + data = PyMem_NEW(PythonCmd_ClientData, 1); + if (!data) + return PyErr_NoMemory(); + Py_INCREF(self); + Py_INCREF(func); + data->self = selfptr; + data->func = func; +#ifdef WITH_THREAD + if (self->threaded && self->thread_id != Tcl_GetCurrentThread()) { + Tcl_Condition cond = NULL; + CommandEvent *ev = (CommandEvent*)ckalloc(sizeof(CommandEvent)); + ev->ev.proc = (Tcl_EventProc*)Tkapp_CommandProc; + ev->interp = self->interp; + ev->create = 1; + ev->name = cmdName; + ev->data = (ClientData)data; + ev->status = &err; + ev->done = &cond; + Tkapp_ThreadSend(self, (Tcl_Event*)ev, &cond, &command_mutex); + Tcl_ConditionFinalize(&cond); + } + else +#endif + { + ENTER_TCL + err = Tcl_CreateCommand( + Tkapp_Interp(self), cmdName, PythonCmd, + (ClientData)data, PythonCmdDelete) == NULL; + LEAVE_TCL + } + if (err) { + PyErr_SetString(Tkinter_TclError, "can't create Tcl command"); + PyMem_DEL(data); + return NULL; + } - Py_INCREF(Py_None); - return Py_None; + Py_INCREF(Py_None); + return Py_None; } - + static PyObject * Tkapp_DeleteCommand(PyObject *selfptr, PyObject *args) { - TkappObject *self = (TkappObject*)selfptr; - char *cmdName; - int err; - - if (!PyArg_ParseTuple(args, "s:deletecommand", &cmdName)) - return NULL; - -#ifdef WITH_THREAD - if (self->threaded && self->thread_id != Tcl_GetCurrentThread()) { - Tcl_Condition cond = NULL; - CommandEvent *ev; - ev = (CommandEvent*)ckalloc(sizeof(CommandEvent)); - ev->ev.proc = (Tcl_EventProc*)Tkapp_CommandProc; - ev->interp = self->interp; - ev->create = 0; - ev->name = cmdName; - ev->status = &err; - ev->done = &cond; - Tkapp_ThreadSend(self, (Tcl_Event*)ev, &cond, - &command_mutex); - Tcl_ConditionFinalize(&cond); - } - else -#endif - { - ENTER_TCL - err = Tcl_DeleteCommand(self->interp, cmdName); - LEAVE_TCL - } - if (err == -1) { - PyErr_SetString(Tkinter_TclError, "can't delete Tcl command"); - return NULL; - } - Py_INCREF(Py_None); - return Py_None; + TkappObject *self = (TkappObject*)selfptr; + char *cmdName; + int err; + + if (!PyArg_ParseTuple(args, "s:deletecommand", &cmdName)) + return NULL; + +#ifdef WITH_THREAD + if (self->threaded && self->thread_id != Tcl_GetCurrentThread()) { + Tcl_Condition cond = NULL; + CommandEvent *ev; + ev = (CommandEvent*)ckalloc(sizeof(CommandEvent)); + ev->ev.proc = (Tcl_EventProc*)Tkapp_CommandProc; + ev->interp = self->interp; + ev->create = 0; + ev->name = cmdName; + ev->status = &err; + ev->done = &cond; + Tkapp_ThreadSend(self, (Tcl_Event*)ev, &cond, + &command_mutex); + Tcl_ConditionFinalize(&cond); + } + else +#endif + { + ENTER_TCL + err = Tcl_DeleteCommand(self->interp, cmdName); + LEAVE_TCL + } + if (err == -1) { + PyErr_SetString(Tkinter_TclError, "can't delete Tcl command"); + return NULL; + } + Py_INCREF(Py_None); + return Py_None; } - + #ifdef HAVE_CREATEFILEHANDLER /** File Handler **/ typedef struct _fhcdata { - PyObject *func; - PyObject *file; - int id; - struct _fhcdata *next; + PyObject *func; + PyObject *file; + int id; + struct _fhcdata *next; } FileHandler_ClientData; static FileHandler_ClientData *HeadFHCD; @@ -2216,712 +2216,712 @@ static FileHandler_ClientData * NewFHCD(PyObject *func, PyObject *file, int id) { - FileHandler_ClientData *p; - p = PyMem_NEW(FileHandler_ClientData, 1); - if (p != NULL) { - Py_XINCREF(func); - Py_XINCREF(file); - p->func = func; - p->file = file; - p->id = id; - p->next = HeadFHCD; - HeadFHCD = p; - } - return p; + FileHandler_ClientData *p; + p = PyMem_NEW(FileHandler_ClientData, 1); + if (p != NULL) { + Py_XINCREF(func); + Py_XINCREF(file); + p->func = func; + p->file = file; + p->id = id; + p->next = HeadFHCD; + HeadFHCD = p; + } + return p; } static void DeleteFHCD(int id) { - FileHandler_ClientData *p, **pp; + FileHandler_ClientData *p, **pp; - pp = &HeadFHCD; - while ((p = *pp) != NULL) { - if (p->id == id) { - *pp = p->next; - Py_XDECREF(p->func); - Py_XDECREF(p->file); - PyMem_DEL(p); - } - else - pp = &p->next; - } + pp = &HeadFHCD; + while ((p = *pp) != NULL) { + if (p->id == id) { + *pp = p->next; + Py_XDECREF(p->func); + Py_XDECREF(p->file); + PyMem_DEL(p); + } + else + pp = &p->next; + } } static void FileHandler(ClientData clientData, int mask) { - FileHandler_ClientData *data = (FileHandler_ClientData *)clientData; - PyObject *func, *file, *arg, *res; + FileHandler_ClientData *data = (FileHandler_ClientData *)clientData; + PyObject *func, *file, *arg, *res; - ENTER_PYTHON - func = data->func; - file = data->file; - - arg = Py_BuildValue("(Oi)", file, (long) mask); - res = PyEval_CallObject(func, arg); - Py_DECREF(arg); - - if (res == NULL) { - errorInCmd = 1; - PyErr_Fetch(&excInCmd, &valInCmd, &trbInCmd); - } - Py_XDECREF(res); - LEAVE_PYTHON + ENTER_PYTHON + func = data->func; + file = data->file; + + arg = Py_BuildValue("(Oi)", file, (long) mask); + res = PyEval_CallObject(func, arg); + Py_DECREF(arg); + + if (res == NULL) { + errorInCmd = 1; + PyErr_Fetch(&excInCmd, &valInCmd, &trbInCmd); + } + Py_XDECREF(res); + LEAVE_PYTHON } static PyObject * Tkapp_CreateFileHandler(PyObject *self, PyObject *args) /* args is (file, mask, func) */ { - FileHandler_ClientData *data; - PyObject *file, *func; - int mask, tfile; - - if (!PyArg_ParseTuple(args, "OiO:createfilehandler", - &file, &mask, &func)) - return NULL; - - CHECK_TCL_APPARTMENT; - - tfile = PyObject_AsFileDescriptor(file); - if (tfile < 0) - return NULL; - if (!PyCallable_Check(func)) { - PyErr_SetString(PyExc_TypeError, "bad argument list"); - return NULL; - } - - data = NewFHCD(func, file, tfile); - if (data == NULL) - return NULL; - - /* Ought to check for null Tcl_File object... */ - ENTER_TCL - Tcl_CreateFileHandler(tfile, mask, FileHandler, (ClientData) data); - LEAVE_TCL - Py_INCREF(Py_None); - return Py_None; + FileHandler_ClientData *data; + PyObject *file, *func; + int mask, tfile; + + if (!PyArg_ParseTuple(args, "OiO:createfilehandler", + &file, &mask, &func)) + return NULL; + + CHECK_TCL_APPARTMENT; + + tfile = PyObject_AsFileDescriptor(file); + if (tfile < 0) + return NULL; + if (!PyCallable_Check(func)) { + PyErr_SetString(PyExc_TypeError, "bad argument list"); + return NULL; + } + + data = NewFHCD(func, file, tfile); + if (data == NULL) + return NULL; + + /* Ought to check for null Tcl_File object... */ + ENTER_TCL + Tcl_CreateFileHandler(tfile, mask, FileHandler, (ClientData) data); + LEAVE_TCL + Py_INCREF(Py_None); + return Py_None; } static PyObject * Tkapp_DeleteFileHandler(PyObject *self, PyObject *args) { - PyObject *file; - int tfile; + PyObject *file; + int tfile; - if (!PyArg_ParseTuple(args, "O:deletefilehandler", &file)) - return NULL; + if (!PyArg_ParseTuple(args, "O:deletefilehandler", &file)) + return NULL; - CHECK_TCL_APPARTMENT; + CHECK_TCL_APPARTMENT; - tfile = PyObject_AsFileDescriptor(file); - if (tfile < 0) - return NULL; - - DeleteFHCD(tfile); - - /* Ought to check for null Tcl_File object... */ - ENTER_TCL - Tcl_DeleteFileHandler(tfile); - LEAVE_TCL - Py_INCREF(Py_None); - return Py_None; + tfile = PyObject_AsFileDescriptor(file); + if (tfile < 0) + return NULL; + + DeleteFHCD(tfile); + + /* Ought to check for null Tcl_File object... */ + ENTER_TCL + Tcl_DeleteFileHandler(tfile); + LEAVE_TCL + Py_INCREF(Py_None); + return Py_None; } #endif /* HAVE_CREATEFILEHANDLER */ - + /**** Tktt Object (timer token) ****/ static PyTypeObject Tktt_Type; typedef struct { - PyObject_HEAD - Tcl_TimerToken token; - PyObject *func; + PyObject_HEAD + Tcl_TimerToken token; + PyObject *func; } TkttObject; static PyObject * Tktt_DeleteTimerHandler(PyObject *self, PyObject *args) { - TkttObject *v = (TkttObject *)self; - PyObject *func = v->func; + TkttObject *v = (TkttObject *)self; + PyObject *func = v->func; - if (!PyArg_ParseTuple(args, ":deletetimerhandler")) - return NULL; - if (v->token != NULL) { - Tcl_DeleteTimerHandler(v->token); - v->token = NULL; - } - if (func != NULL) { - v->func = NULL; - Py_DECREF(func); - Py_DECREF(v); /* See Tktt_New() */ - } - Py_INCREF(Py_None); - return Py_None; + if (!PyArg_ParseTuple(args, ":deletetimerhandler")) + return NULL; + if (v->token != NULL) { + Tcl_DeleteTimerHandler(v->token); + v->token = NULL; + } + if (func != NULL) { + v->func = NULL; + Py_DECREF(func); + Py_DECREF(v); /* See Tktt_New() */ + } + Py_INCREF(Py_None); + return Py_None; } static PyMethodDef Tktt_methods[] = { - {"deletetimerhandler", Tktt_DeleteTimerHandler, METH_VARARGS}, - {NULL, NULL} + {"deletetimerhandler", Tktt_DeleteTimerHandler, METH_VARARGS}, + {NULL, NULL} }; static TkttObject * Tktt_New(PyObject *func) { - TkttObject *v; + TkttObject *v; - v = PyObject_New(TkttObject, &Tktt_Type); - if (v == NULL) - return NULL; - - Py_INCREF(func); - v->token = NULL; - v->func = func; - - /* Extra reference, deleted when called or when handler is deleted */ - Py_INCREF(v); - return v; + v = PyObject_New(TkttObject, &Tktt_Type); + if (v == NULL) + return NULL; + + Py_INCREF(func); + v->token = NULL; + v->func = func; + + /* Extra reference, deleted when called or when handler is deleted */ + Py_INCREF(v); + return v; } static void Tktt_Dealloc(PyObject *self) { - TkttObject *v = (TkttObject *)self; - PyObject *func = v->func; + TkttObject *v = (TkttObject *)self; + PyObject *func = v->func; - Py_XDECREF(func); + Py_XDECREF(func); - PyObject_Del(self); + PyObject_Del(self); } static PyObject * Tktt_Repr(PyObject *self) { - TkttObject *v = (TkttObject *)self; - char buf[100]; + TkttObject *v = (TkttObject *)self; + char buf[100]; - PyOS_snprintf(buf, sizeof(buf), "", v, - v->func == NULL ? ", handler deleted" : ""); - return PyUnicode_FromString(buf); + PyOS_snprintf(buf, sizeof(buf), "", v, + v->func == NULL ? ", handler deleted" : ""); + return PyUnicode_FromString(buf); } static PyTypeObject Tktt_Type = { - PyVarObject_HEAD_INIT(NULL, 0) - "tktimertoken", /*tp_name */ - sizeof(TkttObject), /*tp_basicsize */ - 0, /*tp_itemsize */ - Tktt_Dealloc, /*tp_dealloc */ - 0, /*tp_print */ - 0, /*tp_getattr */ - 0, /*tp_setattr */ - 0, /*tp_reserved */ - Tktt_Repr, /*tp_repr */ - 0, /*tp_as_number */ - 0, /*tp_as_sequence */ - 0, /*tp_as_mapping */ - 0, /*tp_hash */ - 0, /*tp_call*/ - 0, /*tp_str*/ - 0, /*tp_getattro*/ - 0, /*tp_setattro*/ - 0, /*tp_as_buffer*/ - Py_TPFLAGS_DEFAULT, /*tp_flags*/ - 0, /*tp_doc*/ - 0, /*tp_traverse*/ - 0, /*tp_clear*/ - 0, /*tp_richcompare*/ - 0, /*tp_weaklistoffset*/ - 0, /*tp_iter*/ - 0, /*tp_iternext*/ - Tktt_methods, /*tp_methods*/ + PyVarObject_HEAD_INIT(NULL, 0) + "tktimertoken", /*tp_name */ + sizeof(TkttObject), /*tp_basicsize */ + 0, /*tp_itemsize */ + Tktt_Dealloc, /*tp_dealloc */ + 0, /*tp_print */ + 0, /*tp_getattr */ + 0, /*tp_setattr */ + 0, /*tp_reserved */ + Tktt_Repr, /*tp_repr */ + 0, /*tp_as_number */ + 0, /*tp_as_sequence */ + 0, /*tp_as_mapping */ + 0, /*tp_hash */ + 0, /*tp_call*/ + 0, /*tp_str*/ + 0, /*tp_getattro*/ + 0, /*tp_setattro*/ + 0, /*tp_as_buffer*/ + Py_TPFLAGS_DEFAULT, /*tp_flags*/ + 0, /*tp_doc*/ + 0, /*tp_traverse*/ + 0, /*tp_clear*/ + 0, /*tp_richcompare*/ + 0, /*tp_weaklistoffset*/ + 0, /*tp_iter*/ + 0, /*tp_iternext*/ + Tktt_methods, /*tp_methods*/ }; - + /** Timer Handler **/ static void TimerHandler(ClientData clientData) { - TkttObject *v = (TkttObject *)clientData; - PyObject *func = v->func; - PyObject *res; + TkttObject *v = (TkttObject *)clientData; + PyObject *func = v->func; + PyObject *res; - if (func == NULL) - return; + if (func == NULL) + return; - v->func = NULL; + v->func = NULL; - ENTER_PYTHON + ENTER_PYTHON - res = PyEval_CallObject(func, NULL); - Py_DECREF(func); - Py_DECREF(v); /* See Tktt_New() */ + res = PyEval_CallObject(func, NULL); + Py_DECREF(func); + Py_DECREF(v); /* See Tktt_New() */ - if (res == NULL) { - errorInCmd = 1; - PyErr_Fetch(&excInCmd, &valInCmd, &trbInCmd); - } - else - Py_DECREF(res); + if (res == NULL) { + errorInCmd = 1; + PyErr_Fetch(&excInCmd, &valInCmd, &trbInCmd); + } + else + Py_DECREF(res); - LEAVE_PYTHON + LEAVE_PYTHON } static PyObject * Tkapp_CreateTimerHandler(PyObject *self, PyObject *args) { - int milliseconds; - PyObject *func; - TkttObject *v; - - if (!PyArg_ParseTuple(args, "iO:createtimerhandler", - &milliseconds, &func)) - return NULL; - if (!PyCallable_Check(func)) { - PyErr_SetString(PyExc_TypeError, "bad argument list"); - return NULL; - } - - CHECK_TCL_APPARTMENT; - - v = Tktt_New(func); - if (v) { - v->token = Tcl_CreateTimerHandler(milliseconds, TimerHandler, - (ClientData)v); - } + int milliseconds; + PyObject *func; + TkttObject *v; + + if (!PyArg_ParseTuple(args, "iO:createtimerhandler", + &milliseconds, &func)) + return NULL; + if (!PyCallable_Check(func)) { + PyErr_SetString(PyExc_TypeError, "bad argument list"); + return NULL; + } + + CHECK_TCL_APPARTMENT; + + v = Tktt_New(func); + if (v) { + v->token = Tcl_CreateTimerHandler(milliseconds, TimerHandler, + (ClientData)v); + } - return (PyObject *) v; + return (PyObject *) v; } - + /** Event Loop **/ static PyObject * Tkapp_MainLoop(PyObject *selfptr, PyObject *args) { - int threshold = 0; - TkappObject *self = (TkappObject*)selfptr; + int threshold = 0; + TkappObject *self = (TkappObject*)selfptr; #ifdef WITH_THREAD - PyThreadState *tstate = PyThreadState_Get(); + PyThreadState *tstate = PyThreadState_Get(); #endif - if (!PyArg_ParseTuple(args, "|i:mainloop", &threshold)) - return NULL; + if (!PyArg_ParseTuple(args, "|i:mainloop", &threshold)) + return NULL; - CHECK_TCL_APPARTMENT; - self->dispatching = 1; - - quitMainLoop = 0; - while (Tk_GetNumMainWindows() > threshold && - !quitMainLoop && - !errorInCmd) - { - int result; - -#ifdef WITH_THREAD - if (self->threaded) { - /* Allow other Python threads to run. */ - ENTER_TCL - result = Tcl_DoOneEvent(0); - LEAVE_TCL - } - else { - Py_BEGIN_ALLOW_THREADS - if(tcl_lock)PyThread_acquire_lock(tcl_lock, 1); - tcl_tstate = tstate; - result = Tcl_DoOneEvent(TCL_DONT_WAIT); - tcl_tstate = NULL; - if(tcl_lock)PyThread_release_lock(tcl_lock); - if (result == 0) - Sleep(Tkinter_busywaitinterval); - Py_END_ALLOW_THREADS - } + CHECK_TCL_APPARTMENT; + self->dispatching = 1; + + quitMainLoop = 0; + while (Tk_GetNumMainWindows() > threshold && + !quitMainLoop && + !errorInCmd) + { + int result; + +#ifdef WITH_THREAD + if (self->threaded) { + /* Allow other Python threads to run. */ + ENTER_TCL + result = Tcl_DoOneEvent(0); + LEAVE_TCL + } + else { + Py_BEGIN_ALLOW_THREADS + if(tcl_lock)PyThread_acquire_lock(tcl_lock, 1); + tcl_tstate = tstate; + result = Tcl_DoOneEvent(TCL_DONT_WAIT); + tcl_tstate = NULL; + if(tcl_lock)PyThread_release_lock(tcl_lock); + if (result == 0) + Sleep(Tkinter_busywaitinterval); + Py_END_ALLOW_THREADS + } #else - result = Tcl_DoOneEvent(0); + result = Tcl_DoOneEvent(0); #endif - if (PyErr_CheckSignals() != 0) { - self->dispatching = 0; - return NULL; - } - if (result < 0) - break; - } - self->dispatching = 0; - quitMainLoop = 0; - - if (errorInCmd) { - errorInCmd = 0; - PyErr_Restore(excInCmd, valInCmd, trbInCmd); - excInCmd = valInCmd = trbInCmd = NULL; - return NULL; - } - Py_INCREF(Py_None); - return Py_None; + if (PyErr_CheckSignals() != 0) { + self->dispatching = 0; + return NULL; + } + if (result < 0) + break; + } + self->dispatching = 0; + quitMainLoop = 0; + + if (errorInCmd) { + errorInCmd = 0; + PyErr_Restore(excInCmd, valInCmd, trbInCmd); + excInCmd = valInCmd = trbInCmd = NULL; + return NULL; + } + Py_INCREF(Py_None); + return Py_None; } static PyObject * Tkapp_DoOneEvent(PyObject *self, PyObject *args) { - int flags = 0; - int rv; + int flags = 0; + int rv; - if (!PyArg_ParseTuple(args, "|i:dooneevent", &flags)) - return NULL; + if (!PyArg_ParseTuple(args, "|i:dooneevent", &flags)) + return NULL; - ENTER_TCL - rv = Tcl_DoOneEvent(flags); - LEAVE_TCL - return Py_BuildValue("i", rv); + ENTER_TCL + rv = Tcl_DoOneEvent(flags); + LEAVE_TCL + return Py_BuildValue("i", rv); } static PyObject * Tkapp_Quit(PyObject *self, PyObject *args) { - if (!PyArg_ParseTuple(args, ":quit")) - return NULL; + if (!PyArg_ParseTuple(args, ":quit")) + return NULL; - quitMainLoop = 1; - Py_INCREF(Py_None); - return Py_None; + quitMainLoop = 1; + Py_INCREF(Py_None); + return Py_None; } static PyObject * Tkapp_InterpAddr(PyObject *self, PyObject *args) { - if (!PyArg_ParseTuple(args, ":interpaddr")) - return NULL; + if (!PyArg_ParseTuple(args, ":interpaddr")) + return NULL; - return PyLong_FromLong((long)Tkapp_Interp(self)); + return PyLong_FromLong((long)Tkapp_Interp(self)); } -static PyObject * +static PyObject * Tkapp_TkInit(PyObject *self, PyObject *args) { - Tcl_Interp *interp = Tkapp_Interp(self); - const char * _tk_exists = NULL; - int err; + Tcl_Interp *interp = Tkapp_Interp(self); + const char * _tk_exists = NULL; + int err; #ifdef TKINTER_PROTECT_LOADTK - /* Up to Tk 8.4.13, Tk_Init deadlocks on the second call when the - * first call failed. - * To avoid the deadlock, we just refuse the second call through - * a static variable. - */ - if (tk_load_failed) { - PyErr_SetString(Tkinter_TclError, TKINTER_LOADTK_ERRMSG); - return NULL; - } -#endif - - /* We want to guard against calling Tk_Init() multiple times */ - CHECK_TCL_APPARTMENT; - ENTER_TCL - err = Tcl_Eval(Tkapp_Interp(self), "info exists tk_version"); - ENTER_OVERLAP - if (err == TCL_ERROR) { - /* This sets an exception, but we cannot return right - away because we need to exit the overlap first. */ - Tkinter_Error(self); - } else { - _tk_exists = Tkapp_Result(self); - } - LEAVE_OVERLAP_TCL - if (err == TCL_ERROR) { - return NULL; - } - if (_tk_exists == NULL || strcmp(_tk_exists, "1") != 0) { - if (Tk_Init(interp) == TCL_ERROR) { - PyErr_SetString(Tkinter_TclError, Tcl_GetStringResult(Tkapp_Interp(self))); + /* Up to Tk 8.4.13, Tk_Init deadlocks on the second call when the + * first call failed. + * To avoid the deadlock, we just refuse the second call through + * a static variable. + */ + if (tk_load_failed) { + PyErr_SetString(Tkinter_TclError, TKINTER_LOADTK_ERRMSG); + return NULL; + } +#endif + + /* We want to guard against calling Tk_Init() multiple times */ + CHECK_TCL_APPARTMENT; + ENTER_TCL + err = Tcl_Eval(Tkapp_Interp(self), "info exists tk_version"); + ENTER_OVERLAP + if (err == TCL_ERROR) { + /* This sets an exception, but we cannot return right + away because we need to exit the overlap first. */ + Tkinter_Error(self); + } else { + _tk_exists = Tkapp_Result(self); + } + LEAVE_OVERLAP_TCL + if (err == TCL_ERROR) { + return NULL; + } + if (_tk_exists == NULL || strcmp(_tk_exists, "1") != 0) { + if (Tk_Init(interp) == TCL_ERROR) { + PyErr_SetString(Tkinter_TclError, Tcl_GetStringResult(Tkapp_Interp(self))); #ifdef TKINTER_PROTECT_LOADTK - tk_load_failed = 1; + tk_load_failed = 1; #endif - return NULL; - } - } - Py_INCREF(Py_None); - return Py_None; + return NULL; + } + } + Py_INCREF(Py_None); + return Py_None; } static PyObject * Tkapp_WantObjects(PyObject *self, PyObject *args) { - int wantobjects = -1; - if (!PyArg_ParseTuple(args, "|i:wantobjects", &wantobjects)) - return NULL; - if (wantobjects == -1) - return PyBool_FromLong(((TkappObject*)self)->wantobjects); - ((TkappObject*)self)->wantobjects = wantobjects; + int wantobjects = -1; + if (!PyArg_ParseTuple(args, "|i:wantobjects", &wantobjects)) + return NULL; + if (wantobjects == -1) + return PyBool_FromLong(((TkappObject*)self)->wantobjects); + ((TkappObject*)self)->wantobjects = wantobjects; - Py_INCREF(Py_None); - return Py_None; + Py_INCREF(Py_None); + return Py_None; } static PyObject * Tkapp_WillDispatch(PyObject *self, PyObject *args) { - ((TkappObject*)self)->dispatching = 1; + ((TkappObject*)self)->dispatching = 1; - Py_INCREF(Py_None); - return Py_None; + Py_INCREF(Py_None); + return Py_None; } - + /**** Tkapp Method List ****/ static PyMethodDef Tkapp_methods[] = { - {"willdispatch", Tkapp_WillDispatch, METH_NOARGS}, - {"wantobjects", Tkapp_WantObjects, METH_VARARGS}, - {"call", Tkapp_Call, METH_VARARGS}, - {"globalcall", Tkapp_GlobalCall, METH_VARARGS}, - {"eval", Tkapp_Eval, METH_VARARGS}, - {"globaleval", Tkapp_GlobalEval, METH_VARARGS}, - {"evalfile", Tkapp_EvalFile, METH_VARARGS}, - {"record", Tkapp_Record, METH_VARARGS}, - {"adderrorinfo", Tkapp_AddErrorInfo, METH_VARARGS}, - {"setvar", Tkapp_SetVar, METH_VARARGS}, - {"globalsetvar", Tkapp_GlobalSetVar, METH_VARARGS}, - {"getvar", Tkapp_GetVar, METH_VARARGS}, - {"globalgetvar", Tkapp_GlobalGetVar, METH_VARARGS}, - {"unsetvar", Tkapp_UnsetVar, METH_VARARGS}, - {"globalunsetvar", Tkapp_GlobalUnsetVar, METH_VARARGS}, - {"getint", Tkapp_GetInt, METH_VARARGS}, - {"getdouble", Tkapp_GetDouble, METH_VARARGS}, - {"getboolean", Tkapp_GetBoolean, METH_VARARGS}, - {"exprstring", Tkapp_ExprString, METH_VARARGS}, - {"exprlong", Tkapp_ExprLong, METH_VARARGS}, - {"exprdouble", Tkapp_ExprDouble, METH_VARARGS}, - {"exprboolean", Tkapp_ExprBoolean, METH_VARARGS}, - {"splitlist", Tkapp_SplitList, METH_VARARGS}, - {"split", Tkapp_Split, METH_VARARGS}, - {"merge", Tkapp_Merge, METH_VARARGS}, - {"createcommand", Tkapp_CreateCommand, METH_VARARGS}, - {"deletecommand", Tkapp_DeleteCommand, METH_VARARGS}, + {"willdispatch", Tkapp_WillDispatch, METH_NOARGS}, + {"wantobjects", Tkapp_WantObjects, METH_VARARGS}, + {"call", Tkapp_Call, METH_VARARGS}, + {"globalcall", Tkapp_GlobalCall, METH_VARARGS}, + {"eval", Tkapp_Eval, METH_VARARGS}, + {"globaleval", Tkapp_GlobalEval, METH_VARARGS}, + {"evalfile", Tkapp_EvalFile, METH_VARARGS}, + {"record", Tkapp_Record, METH_VARARGS}, + {"adderrorinfo", Tkapp_AddErrorInfo, METH_VARARGS}, + {"setvar", Tkapp_SetVar, METH_VARARGS}, + {"globalsetvar", Tkapp_GlobalSetVar, METH_VARARGS}, + {"getvar", Tkapp_GetVar, METH_VARARGS}, + {"globalgetvar", Tkapp_GlobalGetVar, METH_VARARGS}, + {"unsetvar", Tkapp_UnsetVar, METH_VARARGS}, + {"globalunsetvar", Tkapp_GlobalUnsetVar, METH_VARARGS}, + {"getint", Tkapp_GetInt, METH_VARARGS}, + {"getdouble", Tkapp_GetDouble, METH_VARARGS}, + {"getboolean", Tkapp_GetBoolean, METH_VARARGS}, + {"exprstring", Tkapp_ExprString, METH_VARARGS}, + {"exprlong", Tkapp_ExprLong, METH_VARARGS}, + {"exprdouble", Tkapp_ExprDouble, METH_VARARGS}, + {"exprboolean", Tkapp_ExprBoolean, METH_VARARGS}, + {"splitlist", Tkapp_SplitList, METH_VARARGS}, + {"split", Tkapp_Split, METH_VARARGS}, + {"merge", Tkapp_Merge, METH_VARARGS}, + {"createcommand", Tkapp_CreateCommand, METH_VARARGS}, + {"deletecommand", Tkapp_DeleteCommand, METH_VARARGS}, #ifdef HAVE_CREATEFILEHANDLER - {"createfilehandler", Tkapp_CreateFileHandler, METH_VARARGS}, - {"deletefilehandler", Tkapp_DeleteFileHandler, METH_VARARGS}, + {"createfilehandler", Tkapp_CreateFileHandler, METH_VARARGS}, + {"deletefilehandler", Tkapp_DeleteFileHandler, METH_VARARGS}, #endif - {"createtimerhandler", Tkapp_CreateTimerHandler, METH_VARARGS}, - {"mainloop", Tkapp_MainLoop, METH_VARARGS}, - {"dooneevent", Tkapp_DoOneEvent, METH_VARARGS}, - {"quit", Tkapp_Quit, METH_VARARGS}, - {"interpaddr", Tkapp_InterpAddr, METH_VARARGS}, - {"loadtk", Tkapp_TkInit, METH_NOARGS}, - {NULL, NULL} + {"createtimerhandler", Tkapp_CreateTimerHandler, METH_VARARGS}, + {"mainloop", Tkapp_MainLoop, METH_VARARGS}, + {"dooneevent", Tkapp_DoOneEvent, METH_VARARGS}, + {"quit", Tkapp_Quit, METH_VARARGS}, + {"interpaddr", Tkapp_InterpAddr, METH_VARARGS}, + {"loadtk", Tkapp_TkInit, METH_NOARGS}, + {NULL, NULL} }; - + /**** Tkapp Type Methods ****/ static void Tkapp_Dealloc(PyObject *self) { - /*CHECK_TCL_APPARTMENT;*/ - ENTER_TCL - Tcl_DeleteInterp(Tkapp_Interp(self)); - LEAVE_TCL - PyObject_Del(self); - DisableEventHook(); + /*CHECK_TCL_APPARTMENT;*/ + ENTER_TCL + Tcl_DeleteInterp(Tkapp_Interp(self)); + LEAVE_TCL + PyObject_Del(self); + DisableEventHook(); } static PyTypeObject Tkapp_Type = { - PyVarObject_HEAD_INIT(NULL, 0) - "tkapp", /*tp_name */ - sizeof(TkappObject), /*tp_basicsize */ - 0, /*tp_itemsize */ - Tkapp_Dealloc, /*tp_dealloc */ - 0, /*tp_print */ - 0, /*tp_getattr */ - 0, /*tp_setattr */ - 0, /*tp_reserved */ - 0, /*tp_repr */ - 0, /*tp_as_number */ - 0, /*tp_as_sequence */ - 0, /*tp_as_mapping */ - 0, /*tp_hash */ - 0, /*tp_call*/ - 0, /*tp_str*/ - 0, /*tp_getattro*/ - 0, /*tp_setattro*/ - 0, /*tp_as_buffer*/ - Py_TPFLAGS_DEFAULT, /*tp_flags*/ - 0, /*tp_doc*/ - 0, /*tp_traverse*/ - 0, /*tp_clear*/ - 0, /*tp_richcompare*/ - 0, /*tp_weaklistoffset*/ - 0, /*tp_iter*/ - 0, /*tp_iternext*/ - Tkapp_methods, /*tp_methods*/ + PyVarObject_HEAD_INIT(NULL, 0) + "tkapp", /*tp_name */ + sizeof(TkappObject), /*tp_basicsize */ + 0, /*tp_itemsize */ + Tkapp_Dealloc, /*tp_dealloc */ + 0, /*tp_print */ + 0, /*tp_getattr */ + 0, /*tp_setattr */ + 0, /*tp_reserved */ + 0, /*tp_repr */ + 0, /*tp_as_number */ + 0, /*tp_as_sequence */ + 0, /*tp_as_mapping */ + 0, /*tp_hash */ + 0, /*tp_call*/ + 0, /*tp_str*/ + 0, /*tp_getattro*/ + 0, /*tp_setattro*/ + 0, /*tp_as_buffer*/ + Py_TPFLAGS_DEFAULT, /*tp_flags*/ + 0, /*tp_doc*/ + 0, /*tp_traverse*/ + 0, /*tp_clear*/ + 0, /*tp_richcompare*/ + 0, /*tp_weaklistoffset*/ + 0, /*tp_iter*/ + 0, /*tp_iternext*/ + Tkapp_methods, /*tp_methods*/ }; - + /**** Tkinter Module ****/ typedef struct { - PyObject* tuple; - int size; /* current size */ - int maxsize; /* allocated size */ + PyObject* tuple; + int size; /* current size */ + int maxsize; /* allocated size */ } FlattenContext; static int _bump(FlattenContext* context, int size) { - /* expand tuple to hold (at least) size new items. - return true if successful, false if an exception was raised */ + /* expand tuple to hold (at least) size new items. + return true if successful, false if an exception was raised */ - int maxsize = context->maxsize * 2; + int maxsize = context->maxsize * 2; - if (maxsize < context->size + size) - maxsize = context->size + size; + if (maxsize < context->size + size) + maxsize = context->size + size; - context->maxsize = maxsize; + context->maxsize = maxsize; - return _PyTuple_Resize(&context->tuple, maxsize) >= 0; + return _PyTuple_Resize(&context->tuple, maxsize) >= 0; } static int _flatten1(FlattenContext* context, PyObject* item, int depth) { - /* add tuple or list to argument tuple (recursively) */ + /* add tuple or list to argument tuple (recursively) */ - int i, size; + int i, size; - if (depth > 1000) { - PyErr_SetString(PyExc_ValueError, - "nesting too deep in _flatten"); - return 0; - } else if (PyList_Check(item)) { - size = PyList_GET_SIZE(item); - /* preallocate (assume no nesting) */ - if (context->size + size > context->maxsize && - !_bump(context, size)) - return 0; - /* copy items to output tuple */ - for (i = 0; i < size; i++) { - PyObject *o = PyList_GET_ITEM(item, i); - if (PyList_Check(o) || PyTuple_Check(o)) { - if (!_flatten1(context, o, depth + 1)) - return 0; - } else if (o != Py_None) { - if (context->size + 1 > context->maxsize && - !_bump(context, 1)) - return 0; - Py_INCREF(o); - PyTuple_SET_ITEM(context->tuple, - context->size++, o); - } - } - } else if (PyTuple_Check(item)) { - /* same, for tuples */ - size = PyTuple_GET_SIZE(item); - if (context->size + size > context->maxsize && - !_bump(context, size)) - return 0; - for (i = 0; i < size; i++) { - PyObject *o = PyTuple_GET_ITEM(item, i); - if (PyList_Check(o) || PyTuple_Check(o)) { - if (!_flatten1(context, o, depth + 1)) - return 0; - } else if (o != Py_None) { - if (context->size + 1 > context->maxsize && - !_bump(context, 1)) - return 0; - Py_INCREF(o); - PyTuple_SET_ITEM(context->tuple, - context->size++, o); - } - } - } else { - PyErr_SetString(PyExc_TypeError, "argument must be sequence"); - return 0; - } - return 1; + if (depth > 1000) { + PyErr_SetString(PyExc_ValueError, + "nesting too deep in _flatten"); + return 0; + } else if (PyList_Check(item)) { + size = PyList_GET_SIZE(item); + /* preallocate (assume no nesting) */ + if (context->size + size > context->maxsize && + !_bump(context, size)) + return 0; + /* copy items to output tuple */ + for (i = 0; i < size; i++) { + PyObject *o = PyList_GET_ITEM(item, i); + if (PyList_Check(o) || PyTuple_Check(o)) { + if (!_flatten1(context, o, depth + 1)) + return 0; + } else if (o != Py_None) { + if (context->size + 1 > context->maxsize && + !_bump(context, 1)) + return 0; + Py_INCREF(o); + PyTuple_SET_ITEM(context->tuple, + context->size++, o); + } + } + } else if (PyTuple_Check(item)) { + /* same, for tuples */ + size = PyTuple_GET_SIZE(item); + if (context->size + size > context->maxsize && + !_bump(context, size)) + return 0; + for (i = 0; i < size; i++) { + PyObject *o = PyTuple_GET_ITEM(item, i); + if (PyList_Check(o) || PyTuple_Check(o)) { + if (!_flatten1(context, o, depth + 1)) + return 0; + } else if (o != Py_None) { + if (context->size + 1 > context->maxsize && + !_bump(context, 1)) + return 0; + Py_INCREF(o); + PyTuple_SET_ITEM(context->tuple, + context->size++, o); + } + } + } else { + PyErr_SetString(PyExc_TypeError, "argument must be sequence"); + return 0; + } + return 1; } static PyObject * Tkinter_Flatten(PyObject* self, PyObject* args) { - FlattenContext context; - PyObject* item; + FlattenContext context; + PyObject* item; - if (!PyArg_ParseTuple(args, "O:_flatten", &item)) - return NULL; + if (!PyArg_ParseTuple(args, "O:_flatten", &item)) + return NULL; - context.maxsize = PySequence_Size(item); - if (context.maxsize < 0) - return NULL; - if (context.maxsize == 0) - return PyTuple_New(0); + context.maxsize = PySequence_Size(item); + if (context.maxsize < 0) + return NULL; + if (context.maxsize == 0) + return PyTuple_New(0); - context.tuple = PyTuple_New(context.maxsize); - if (!context.tuple) - return NULL; + context.tuple = PyTuple_New(context.maxsize); + if (!context.tuple) + return NULL; - context.size = 0; + context.size = 0; - if (!_flatten1(&context, item,0)) - return NULL; + if (!_flatten1(&context, item,0)) + return NULL; - if (_PyTuple_Resize(&context.tuple, context.size)) - return NULL; + if (_PyTuple_Resize(&context.tuple, context.size)) + return NULL; - return context.tuple; + return context.tuple; } static PyObject * Tkinter_Create(PyObject *self, PyObject *args) { - char *screenName = NULL; - char *baseName = NULL; /* XXX this is not used anymore; - try getting rid of it. */ - char *className = NULL; - int interactive = 0; - int wantobjects = 0; - int wantTk = 1; /* If false, then Tk_Init() doesn't get called */ - int sync = 0; /* pass -sync to wish */ - char *use = NULL; /* pass -use to wish */ - - className = "Tk"; - - if (!PyArg_ParseTuple(args, "|zssiiiiz:create", - &screenName, &baseName, &className, - &interactive, &wantobjects, &wantTk, - &sync, &use)) - return NULL; - - return (PyObject *) Tkapp_New(screenName, className, - interactive, wantobjects, wantTk, - sync, use); + char *screenName = NULL; + char *baseName = NULL; /* XXX this is not used anymore; + try getting rid of it. */ + char *className = NULL; + int interactive = 0; + int wantobjects = 0; + int wantTk = 1; /* If false, then Tk_Init() doesn't get called */ + int sync = 0; /* pass -sync to wish */ + char *use = NULL; /* pass -use to wish */ + + className = "Tk"; + + if (!PyArg_ParseTuple(args, "|zssiiiiz:create", + &screenName, &baseName, &className, + &interactive, &wantobjects, &wantTk, + &sync, &use)) + return NULL; + + return (PyObject *) Tkapp_New(screenName, className, + interactive, wantobjects, wantTk, + sync, use); } static PyObject * Tkinter_setbusywaitinterval(PyObject *self, PyObject *args) { - int new_val; - if (!PyArg_ParseTuple(args, "i:setbusywaitinterval", &new_val)) - return NULL; - if (new_val < 0) { - PyErr_SetString(PyExc_ValueError, - "busywaitinterval must be >= 0"); - return NULL; - } - Tkinter_busywaitinterval = new_val; - Py_INCREF(Py_None); - return Py_None; + int new_val; + if (!PyArg_ParseTuple(args, "i:setbusywaitinterval", &new_val)) + return NULL; + if (new_val < 0) { + PyErr_SetString(PyExc_ValueError, + "busywaitinterval must be >= 0"); + return NULL; + } + Tkinter_busywaitinterval = new_val; + Py_INCREF(Py_None); + return Py_None; } static char setbusywaitinterval_doc[] = @@ -2935,7 +2935,7 @@ static PyObject * Tkinter_getbusywaitinterval(PyObject *self, PyObject *args) { - return PyLong_FromLong(Tkinter_busywaitinterval); + return PyLong_FromLong(Tkinter_busywaitinterval); } static char getbusywaitinterval_doc[] = @@ -2946,13 +2946,13 @@ static PyMethodDef moduleMethods[] = { - {"_flatten", Tkinter_Flatten, METH_VARARGS}, - {"create", Tkinter_Create, METH_VARARGS}, - {"setbusywaitinterval",Tkinter_setbusywaitinterval, METH_VARARGS, - setbusywaitinterval_doc}, - {"getbusywaitinterval",(PyCFunction)Tkinter_getbusywaitinterval, - METH_NOARGS, getbusywaitinterval_doc}, - {NULL, NULL} + {"_flatten", Tkinter_Flatten, METH_VARARGS}, + {"create", Tkinter_Create, METH_VARARGS}, + {"setbusywaitinterval",Tkinter_setbusywaitinterval, METH_VARARGS, + setbusywaitinterval_doc}, + {"getbusywaitinterval",(PyCFunction)Tkinter_getbusywaitinterval, + METH_NOARGS, getbusywaitinterval_doc}, + {NULL, NULL} }; #ifdef WAIT_FOR_STDIN @@ -2963,7 +2963,7 @@ static void MyFileProc(void *clientData, int mask) { - stdin_ready = 1; + stdin_ready = 1; } #endif @@ -2975,57 +2975,57 @@ EventHook(void) { #ifndef MS_WINDOWS - int tfile; + int tfile; #endif #ifdef WITH_THREAD - PyEval_RestoreThread(event_tstate); + PyEval_RestoreThread(event_tstate); #endif - stdin_ready = 0; - errorInCmd = 0; + stdin_ready = 0; + errorInCmd = 0; #ifndef MS_WINDOWS - tfile = fileno(stdin); - Tcl_CreateFileHandler(tfile, TCL_READABLE, MyFileProc, NULL); + tfile = fileno(stdin); + Tcl_CreateFileHandler(tfile, TCL_READABLE, MyFileProc, NULL); #endif - while (!errorInCmd && !stdin_ready) { - int result; + while (!errorInCmd && !stdin_ready) { + int result; #ifdef MS_WINDOWS - if (_kbhit()) { - stdin_ready = 1; - break; - } + if (_kbhit()) { + stdin_ready = 1; + break; + } #endif #if defined(WITH_THREAD) || defined(MS_WINDOWS) - Py_BEGIN_ALLOW_THREADS - if(tcl_lock)PyThread_acquire_lock(tcl_lock, 1); - tcl_tstate = event_tstate; - - result = Tcl_DoOneEvent(TCL_DONT_WAIT); - - tcl_tstate = NULL; - if(tcl_lock)PyThread_release_lock(tcl_lock); - if (result == 0) - Sleep(Tkinter_busywaitinterval); - Py_END_ALLOW_THREADS + Py_BEGIN_ALLOW_THREADS + if(tcl_lock)PyThread_acquire_lock(tcl_lock, 1); + tcl_tstate = event_tstate; + + result = Tcl_DoOneEvent(TCL_DONT_WAIT); + + tcl_tstate = NULL; + if(tcl_lock)PyThread_release_lock(tcl_lock); + if (result == 0) + Sleep(Tkinter_busywaitinterval); + Py_END_ALLOW_THREADS #else - result = Tcl_DoOneEvent(0); + result = Tcl_DoOneEvent(0); #endif - if (result < 0) - break; - } + if (result < 0) + break; + } #ifndef MS_WINDOWS - Tcl_DeleteFileHandler(tfile); + Tcl_DeleteFileHandler(tfile); #endif - if (errorInCmd) { - errorInCmd = 0; - PyErr_Restore(excInCmd, valInCmd, trbInCmd); - excInCmd = valInCmd = trbInCmd = NULL; - PyErr_Print(); - } + if (errorInCmd) { + errorInCmd = 0; + PyErr_Restore(excInCmd, valInCmd, trbInCmd); + excInCmd = valInCmd = trbInCmd = NULL; + PyErr_Print(); + } #ifdef WITH_THREAD - PyEval_SaveThread(); + PyEval_SaveThread(); #endif - return 0; + return 0; } #endif @@ -3034,12 +3034,12 @@ EnableEventHook(void) { #ifdef WAIT_FOR_STDIN - if (PyOS_InputHook == NULL) { + if (PyOS_InputHook == NULL) { #ifdef WITH_THREAD - event_tstate = PyThreadState_Get(); + event_tstate = PyThreadState_Get(); #endif - PyOS_InputHook = EventHook; - } + PyOS_InputHook = EventHook; + } #endif } @@ -3047,9 +3047,9 @@ DisableEventHook(void) { #ifdef WAIT_FOR_STDIN - if (Tk_GetNumMainWindows() == 0 && PyOS_InputHook == EventHook) { - PyOS_InputHook = NULL; - } + if (Tk_GetNumMainWindows() == 0 && PyOS_InputHook == EventHook) { + PyOS_InputHook = NULL; + } #endif } @@ -3058,114 +3058,114 @@ static void ins_long(PyObject *d, char *name, long val) { - PyObject *v = PyLong_FromLong(val); - if (v) { - PyDict_SetItemString(d, name, v); - Py_DECREF(v); - } + PyObject *v = PyLong_FromLong(val); + if (v) { + PyDict_SetItemString(d, name, v); + Py_DECREF(v); + } } static void ins_string(PyObject *d, char *name, char *val) { - PyObject *v = PyUnicode_FromString(val); - if (v) { - PyDict_SetItemString(d, name, v); - Py_DECREF(v); - } + PyObject *v = PyUnicode_FromString(val); + if (v) { + PyDict_SetItemString(d, name, v); + Py_DECREF(v); + } } static struct PyModuleDef _tkintermodule = { - PyModuleDef_HEAD_INIT, - "_tkinter", - NULL, - -1, - moduleMethods, - NULL, - NULL, - NULL, - NULL + PyModuleDef_HEAD_INIT, + "_tkinter", + NULL, + -1, + moduleMethods, + NULL, + NULL, + NULL, + NULL }; PyMODINIT_FUNC PyInit__tkinter(void) { - PyObject *m, *d, *uexe, *cexe; + PyObject *m, *d, *uexe, *cexe; - if (PyType_Ready(&Tkapp_Type) < 0) - return NULL; + if (PyType_Ready(&Tkapp_Type) < 0) + return NULL; #ifdef WITH_THREAD - tcl_lock = PyThread_allocate_lock(); + tcl_lock = PyThread_allocate_lock(); #endif - m = PyModule_Create(&_tkintermodule); - if (m == NULL) - return NULL; + m = PyModule_Create(&_tkintermodule); + if (m == NULL) + return NULL; - d = PyModule_GetDict(m); - Tkinter_TclError = PyErr_NewException("_tkinter.TclError", NULL, NULL); - PyDict_SetItemString(d, "TclError", Tkinter_TclError); + d = PyModule_GetDict(m); + Tkinter_TclError = PyErr_NewException("_tkinter.TclError", NULL, NULL); + PyDict_SetItemString(d, "TclError", Tkinter_TclError); - ins_long(d, "READABLE", TCL_READABLE); - ins_long(d, "WRITABLE", TCL_WRITABLE); - ins_long(d, "EXCEPTION", TCL_EXCEPTION); - ins_long(d, "WINDOW_EVENTS", TCL_WINDOW_EVENTS); - ins_long(d, "FILE_EVENTS", TCL_FILE_EVENTS); - ins_long(d, "TIMER_EVENTS", TCL_TIMER_EVENTS); - ins_long(d, "IDLE_EVENTS", TCL_IDLE_EVENTS); - ins_long(d, "ALL_EVENTS", TCL_ALL_EVENTS); - ins_long(d, "DONT_WAIT", TCL_DONT_WAIT); - ins_string(d, "TK_VERSION", TK_VERSION); - ins_string(d, "TCL_VERSION", TCL_VERSION); + ins_long(d, "READABLE", TCL_READABLE); + ins_long(d, "WRITABLE", TCL_WRITABLE); + ins_long(d, "EXCEPTION", TCL_EXCEPTION); + ins_long(d, "WINDOW_EVENTS", TCL_WINDOW_EVENTS); + ins_long(d, "FILE_EVENTS", TCL_FILE_EVENTS); + ins_long(d, "TIMER_EVENTS", TCL_TIMER_EVENTS); + ins_long(d, "IDLE_EVENTS", TCL_IDLE_EVENTS); + ins_long(d, "ALL_EVENTS", TCL_ALL_EVENTS); + ins_long(d, "DONT_WAIT", TCL_DONT_WAIT); + ins_string(d, "TK_VERSION", TK_VERSION); + ins_string(d, "TCL_VERSION", TCL_VERSION); - PyDict_SetItemString(d, "TkappType", (PyObject *)&Tkapp_Type); + PyDict_SetItemString(d, "TkappType", (PyObject *)&Tkapp_Type); - if (PyType_Ready(&Tktt_Type) < 0) - return NULL; - PyDict_SetItemString(d, "TkttType", (PyObject *)&Tktt_Type); + if (PyType_Ready(&Tktt_Type) < 0) + return NULL; + PyDict_SetItemString(d, "TkttType", (PyObject *)&Tktt_Type); - Py_TYPE(&PyTclObject_Type) = &PyType_Type; - PyDict_SetItemString(d, "Tcl_Obj", (PyObject *)&PyTclObject_Type); + Py_TYPE(&PyTclObject_Type) = &PyType_Type; + PyDict_SetItemString(d, "Tcl_Obj", (PyObject *)&PyTclObject_Type); #ifdef TK_AQUA - /* Tk_MacOSXSetupTkNotifier must be called before Tcl's subsystems - * start waking up. Note that Tcl_FindExecutable will do this, this - * code must be above it! The original warning from - * tkMacOSXAppInit.c is copied below. - * - * NB - You have to swap in the Tk Notifier BEFORE you start up the - * Tcl interpreter for now. It probably should work to do this - * in the other order, but for now it doesn't seem to. - * - */ - Tk_MacOSXSetupTkNotifier(); + /* Tk_MacOSXSetupTkNotifier must be called before Tcl's subsystems + * start waking up. Note that Tcl_FindExecutable will do this, this + * code must be above it! The original warning from + * tkMacOSXAppInit.c is copied below. + * + * NB - You have to swap in the Tk Notifier BEFORE you start up the + * Tcl interpreter for now. It probably should work to do this + * in the other order, but for now it doesn't seem to. + * + */ + Tk_MacOSXSetupTkNotifier(); #endif - /* This helps the dynamic loader; in Unicode aware Tcl versions - it also helps Tcl find its encodings. */ - uexe = PyUnicode_FromWideChar(Py_GetProgramName(), -1); - if (uexe) { - cexe = PyUnicode_AsEncodedString(uexe, - Py_FileSystemDefaultEncoding, - NULL); - if (cexe) - Tcl_FindExecutable(PyBytes_AsString(cexe)); - Py_XDECREF(cexe); - Py_DECREF(uexe); - } - - if (PyErr_Occurred()) { - Py_DECREF(m); - return NULL; - } + /* This helps the dynamic loader; in Unicode aware Tcl versions + it also helps Tcl find its encodings. */ + uexe = PyUnicode_FromWideChar(Py_GetProgramName(), -1); + if (uexe) { + cexe = PyUnicode_AsEncodedString(uexe, + Py_FileSystemDefaultEncoding, + NULL); + if (cexe) + Tcl_FindExecutable(PyBytes_AsString(cexe)); + Py_XDECREF(cexe); + Py_DECREF(uexe); + } + + if (PyErr_Occurred()) { + Py_DECREF(m); + return NULL; + } #if 0 - /* This was not a good idea; through bindings, - Tcl_Finalize() may invoke Python code but at that point the - interpreter and thread state have already been destroyed! */ - Py_AtExit(Tcl_Finalize); + /* This was not a good idea; through bindings, + Tcl_Finalize() may invoke Python code but at that point the + interpreter and thread state have already been destroyed! */ + Py_AtExit(Tcl_Finalize); #endif - return m; + return m; } Modified: python/branches/py3k/Modules/addrinfo.h ============================================================================== --- python/branches/py3k/Modules/addrinfo.h (original) +++ python/branches/py3k/Modules/addrinfo.h Sun May 9 17:52:27 2010 @@ -1,7 +1,7 @@ /* * Copyright (C) 1995, 1996, 1997, 1998, and 1999 WIDE Project. * All rights reserved. - * + * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: @@ -13,7 +13,7 @@ * 3. Neither the name of the project nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. - * + * * THIS SOFTWARE IS PROVIDED BY THE PROJECT AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE @@ -55,20 +55,20 @@ #define getaddrinfo fake_getaddrinfo #endif /* EAI_ADDRFAMILY */ -#define EAI_ADDRFAMILY 1 /* address family for hostname not supported */ -#define EAI_AGAIN 2 /* temporary failure in name resolution */ -#define EAI_BADFLAGS 3 /* invalid value for ai_flags */ -#define EAI_FAIL 4 /* non-recoverable failure in name resolution */ -#define EAI_FAMILY 5 /* ai_family not supported */ -#define EAI_MEMORY 6 /* memory allocation failure */ -#define EAI_NODATA 7 /* no address associated with hostname */ -#define EAI_NONAME 8 /* hostname nor servname provided, or not known */ -#define EAI_SERVICE 9 /* servname not supported for ai_socktype */ -#define EAI_SOCKTYPE 10 /* ai_socktype not supported */ -#define EAI_SYSTEM 11 /* system error returned in errno */ -#define EAI_BADHINTS 12 -#define EAI_PROTOCOL 13 -#define EAI_MAX 14 +#define EAI_ADDRFAMILY 1 /* address family for hostname not supported */ +#define EAI_AGAIN 2 /* temporary failure in name resolution */ +#define EAI_BADFLAGS 3 /* invalid value for ai_flags */ +#define EAI_FAIL 4 /* non-recoverable failure in name resolution */ +#define EAI_FAMILY 5 /* ai_family not supported */ +#define EAI_MEMORY 6 /* memory allocation failure */ +#define EAI_NODATA 7 /* no address associated with hostname */ +#define EAI_NONAME 8 /* hostname nor servname provided, or not known */ +#define EAI_SERVICE 9 /* servname not supported for ai_socktype */ +#define EAI_SOCKTYPE 10 /* ai_socktype not supported */ +#define EAI_SYSTEM 11 /* system error returned in errno */ +#define EAI_BADHINTS 12 +#define EAI_PROTOCOL 13 +#define EAI_MAX 14 /* * Flag values for getaddrinfo() @@ -85,18 +85,18 @@ #undef AI_DEFAULT #endif /* AI_PASSIVE */ -#define AI_PASSIVE 0x00000001 /* get address to use bind() */ -#define AI_CANONNAME 0x00000002 /* fill ai_canonname */ -#define AI_NUMERICHOST 0x00000004 /* prevent name resolution */ +#define AI_PASSIVE 0x00000001 /* get address to use bind() */ +#define AI_CANONNAME 0x00000002 /* fill ai_canonname */ +#define AI_NUMERICHOST 0x00000004 /* prevent name resolution */ /* valid flags for addrinfo */ -#define AI_MASK (AI_PASSIVE | AI_CANONNAME | AI_NUMERICHOST) +#define AI_MASK (AI_PASSIVE | AI_CANONNAME | AI_NUMERICHOST) -#define AI_ALL 0x00000100 /* IPv6 and IPv4-mapped (with AI_V4MAPPED) */ -#define AI_V4MAPPED_CFG 0x00000200 /* accept IPv4-mapped if kernel supports */ -#define AI_ADDRCONFIG 0x00000400 /* only if any address is assigned */ -#define AI_V4MAPPED 0x00000800 /* accept IPv4-mapped IPv6 address */ +#define AI_ALL 0x00000100 /* IPv6 and IPv4-mapped (with AI_V4MAPPED) */ +#define AI_V4MAPPED_CFG 0x00000200 /* accept IPv4-mapped if kernel supports */ +#define AI_ADDRCONFIG 0x00000400 /* only if any address is assigned */ +#define AI_V4MAPPED 0x00000800 /* accept IPv4-mapped IPv6 address */ /* special recommended flags for getipnodebyname */ -#define AI_DEFAULT (AI_V4MAPPED_CFG | AI_ADDRCONFIG) +#define AI_DEFAULT (AI_V4MAPPED_CFG | AI_ADDRCONFIG) #endif /* !HAVE_GETADDRINFO */ @@ -106,33 +106,33 @@ * Constants for getnameinfo() */ #ifndef NI_MAXHOST -#define NI_MAXHOST 1025 -#define NI_MAXSERV 32 +#define NI_MAXHOST 1025 +#define NI_MAXSERV 32 #endif /* !NI_MAXHOST */ /* * Flag values for getnameinfo() */ #ifndef NI_NOFQDN -#define NI_NOFQDN 0x00000001 -#define NI_NUMERICHOST 0x00000002 -#define NI_NAMEREQD 0x00000004 -#define NI_NUMERICSERV 0x00000008 -#define NI_DGRAM 0x00000010 +#define NI_NOFQDN 0x00000001 +#define NI_NUMERICHOST 0x00000002 +#define NI_NAMEREQD 0x00000004 +#define NI_NUMERICSERV 0x00000008 +#define NI_DGRAM 0x00000010 #endif /* !NI_NOFQDN */ #endif /* !HAVE_GETNAMEINFO */ #ifndef HAVE_ADDRINFO struct addrinfo { - int ai_flags; /* AI_PASSIVE, AI_CANONNAME */ - int ai_family; /* PF_xxx */ - int ai_socktype; /* SOCK_xxx */ - int ai_protocol; /* 0 or IPPROTO_xxx for IPv4 and IPv6 */ - size_t ai_addrlen; /* length of ai_addr */ - char *ai_canonname; /* canonical name for hostname */ - struct sockaddr *ai_addr; /* binary address */ - struct addrinfo *ai_next; /* next structure in linked list */ + int ai_flags; /* AI_PASSIVE, AI_CANONNAME */ + int ai_family; /* PF_xxx */ + int ai_socktype; /* SOCK_xxx */ + int ai_protocol; /* 0 or IPPROTO_xxx for IPv4 and IPv6 */ + size_t ai_addrlen; /* length of ai_addr */ + char *ai_canonname; /* canonical name for hostname */ + struct sockaddr *ai_addr; /* binary address */ + struct addrinfo *ai_next; /* next structure in linked list */ }; #endif /* !HAVE_ADDRINFO */ @@ -140,30 +140,30 @@ /* * RFC 2553: protocol-independent placeholder for socket addresses */ -#define _SS_MAXSIZE 128 +#define _SS_MAXSIZE 128 #ifdef HAVE_LONG_LONG -#define _SS_ALIGNSIZE (sizeof(PY_LONG_LONG)) +#define _SS_ALIGNSIZE (sizeof(PY_LONG_LONG)) #else -#define _SS_ALIGNSIZE (sizeof(double)) +#define _SS_ALIGNSIZE (sizeof(double)) #endif /* HAVE_LONG_LONG */ -#define _SS_PAD1SIZE (_SS_ALIGNSIZE - sizeof(u_char) * 2) -#define _SS_PAD2SIZE (_SS_MAXSIZE - sizeof(u_char) * 2 - \ - _SS_PAD1SIZE - _SS_ALIGNSIZE) +#define _SS_PAD1SIZE (_SS_ALIGNSIZE - sizeof(u_char) * 2) +#define _SS_PAD2SIZE (_SS_MAXSIZE - sizeof(u_char) * 2 - \ + _SS_PAD1SIZE - _SS_ALIGNSIZE) struct sockaddr_storage { #ifdef HAVE_SOCKADDR_SA_LEN - unsigned char ss_len; /* address length */ - unsigned char ss_family; /* address family */ + unsigned char ss_len; /* address length */ + unsigned char ss_family; /* address family */ #else - unsigned short ss_family; /* address family */ + unsigned short ss_family; /* address family */ #endif /* HAVE_SOCKADDR_SA_LEN */ - char __ss_pad1[_SS_PAD1SIZE]; + char __ss_pad1[_SS_PAD1SIZE]; #ifdef HAVE_LONG_LONG - PY_LONG_LONG __ss_align; /* force desired structure storage alignment */ + PY_LONG_LONG __ss_align; /* force desired structure storage alignment */ #else - double __ss_align; /* force desired structure storage alignment */ + double __ss_align; /* force desired structure storage alignment */ #endif /* HAVE_LONG_LONG */ - char __ss_pad2[_SS_PAD2SIZE]; + char __ss_pad2[_SS_PAD2SIZE]; }; #endif /* !HAVE_SOCKADDR_STORAGE */ Modified: python/branches/py3k/Modules/arraymodule.c ============================================================================== --- python/branches/py3k/Modules/arraymodule.c (original) +++ python/branches/py3k/Modules/arraymodule.c Sun May 9 17:52:27 2010 @@ -11,7 +11,7 @@ #include #else /* !STDC_HEADERS */ #ifdef HAVE_SYS_TYPES_H -#include /* For size_t */ +#include /* For size_t */ #endif /* HAVE_SYS_TYPES_H */ #endif /* !STDC_HEADERS */ @@ -22,22 +22,22 @@ * functions aren't visible yet. */ struct arraydescr { - int typecode; - int itemsize; - PyObject * (*getitem)(struct arrayobject *, Py_ssize_t); - int (*setitem)(struct arrayobject *, Py_ssize_t, PyObject *); - char *formats; - int is_integer_type; - int is_signed; + int typecode; + int itemsize; + PyObject * (*getitem)(struct arrayobject *, Py_ssize_t); + int (*setitem)(struct arrayobject *, Py_ssize_t, PyObject *); + char *formats; + int is_integer_type; + int is_signed; }; typedef struct arrayobject { - PyObject_VAR_HEAD - char *ob_item; - Py_ssize_t allocated; - struct arraydescr *ob_descr; - PyObject *weakreflist; /* List of weak references */ - int ob_exports; /* Number of exported buffers */ + PyObject_VAR_HEAD + char *ob_item; + Py_ssize_t allocated; + struct arraydescr *ob_descr; + PyObject *weakreflist; /* List of weak references */ + int ob_exports; /* Number of exported buffers */ } arrayobject; static PyTypeObject Arraytype; @@ -48,63 +48,63 @@ static int array_resize(arrayobject *self, Py_ssize_t newsize) { - char *items; - size_t _new_size; + char *items; + size_t _new_size; - if (self->ob_exports > 0 && newsize != Py_SIZE(self)) { - PyErr_SetString(PyExc_BufferError, - "cannot resize an array that is exporting buffers"); - return -1; - } - - /* Bypass realloc() when a previous overallocation is large enough - to accommodate the newsize. If the newsize is 16 smaller than the - current size, then proceed with the realloc() to shrink the array. - */ - - if (self->allocated >= newsize && - Py_SIZE(self) < newsize + 16 && - self->ob_item != NULL) { - Py_SIZE(self) = newsize; - return 0; - } - - if (newsize == 0) { - PyMem_FREE(self->ob_item); - self->ob_item = NULL; - Py_SIZE(self) = 0; - self->allocated = 0; - return 0; - } - - /* This over-allocates proportional to the array size, making room - * for additional growth. The over-allocation is mild, but is - * enough to give linear-time amortized behavior over a long - * sequence of appends() in the presence of a poorly-performing - * system realloc(). - * The growth pattern is: 0, 4, 8, 16, 25, 34, 46, 56, 67, 79, ... - * Note, the pattern starts out the same as for lists but then - * grows at a smaller rate so that larger arrays only overallocate - * by about 1/16th -- this is done because arrays are presumed to be more - * memory critical. - */ - - _new_size = (newsize >> 4) + (Py_SIZE(self) < 8 ? 3 : 7) + newsize; - items = self->ob_item; - /* XXX The following multiplication and division does not optimize away - like it does for lists since the size is not known at compile time */ - if (_new_size <= ((~(size_t)0) / self->ob_descr->itemsize)) - PyMem_RESIZE(items, char, (_new_size * self->ob_descr->itemsize)); - else - items = NULL; - if (items == NULL) { - PyErr_NoMemory(); - return -1; - } - self->ob_item = items; - Py_SIZE(self) = newsize; - self->allocated = _new_size; - return 0; + if (self->ob_exports > 0 && newsize != Py_SIZE(self)) { + PyErr_SetString(PyExc_BufferError, + "cannot resize an array that is exporting buffers"); + return -1; + } + + /* Bypass realloc() when a previous overallocation is large enough + to accommodate the newsize. If the newsize is 16 smaller than the + current size, then proceed with the realloc() to shrink the array. + */ + + if (self->allocated >= newsize && + Py_SIZE(self) < newsize + 16 && + self->ob_item != NULL) { + Py_SIZE(self) = newsize; + return 0; + } + + if (newsize == 0) { + PyMem_FREE(self->ob_item); + self->ob_item = NULL; + Py_SIZE(self) = 0; + self->allocated = 0; + return 0; + } + + /* This over-allocates proportional to the array size, making room + * for additional growth. The over-allocation is mild, but is + * enough to give linear-time amortized behavior over a long + * sequence of appends() in the presence of a poorly-performing + * system realloc(). + * The growth pattern is: 0, 4, 8, 16, 25, 34, 46, 56, 67, 79, ... + * Note, the pattern starts out the same as for lists but then + * grows at a smaller rate so that larger arrays only overallocate + * by about 1/16th -- this is done because arrays are presumed to be more + * memory critical. + */ + + _new_size = (newsize >> 4) + (Py_SIZE(self) < 8 ? 3 : 7) + newsize; + items = self->ob_item; + /* XXX The following multiplication and division does not optimize away + like it does for lists since the size is not known at compile time */ + if (_new_size <= ((~(size_t)0) / self->ob_descr->itemsize)) + PyMem_RESIZE(items, char, (_new_size * self->ob_descr->itemsize)); + else + items = NULL; + if (items == NULL) { + PyErr_NoMemory(); + return -1; + } + self->ob_item = items; + Py_SIZE(self) = newsize; + self->allocated = _new_size; + return 0; } /**************************************************************************** @@ -122,272 +122,272 @@ static PyObject * b_getitem(arrayobject *ap, Py_ssize_t i) { - long x = ((char *)ap->ob_item)[i]; - if (x >= 128) - x -= 256; - return PyLong_FromLong(x); + long x = ((char *)ap->ob_item)[i]; + if (x >= 128) + x -= 256; + return PyLong_FromLong(x); } static int b_setitem(arrayobject *ap, Py_ssize_t i, PyObject *v) { - short x; - /* PyArg_Parse's 'b' formatter is for an unsigned char, therefore - must use the next size up that is signed ('h') and manually do - the overflow checking */ - if (!PyArg_Parse(v, "h;array item must be integer", &x)) - return -1; - else if (x < -128) { - PyErr_SetString(PyExc_OverflowError, - "signed char is less than minimum"); - return -1; - } - else if (x > 127) { - PyErr_SetString(PyExc_OverflowError, - "signed char is greater than maximum"); - return -1; - } - if (i >= 0) - ((char *)ap->ob_item)[i] = (char)x; - return 0; + short x; + /* PyArg_Parse's 'b' formatter is for an unsigned char, therefore + must use the next size up that is signed ('h') and manually do + the overflow checking */ + if (!PyArg_Parse(v, "h;array item must be integer", &x)) + return -1; + else if (x < -128) { + PyErr_SetString(PyExc_OverflowError, + "signed char is less than minimum"); + return -1; + } + else if (x > 127) { + PyErr_SetString(PyExc_OverflowError, + "signed char is greater than maximum"); + return -1; + } + if (i >= 0) + ((char *)ap->ob_item)[i] = (char)x; + return 0; } static PyObject * BB_getitem(arrayobject *ap, Py_ssize_t i) { - long x = ((unsigned char *)ap->ob_item)[i]; - return PyLong_FromLong(x); + long x = ((unsigned char *)ap->ob_item)[i]; + return PyLong_FromLong(x); } static int BB_setitem(arrayobject *ap, Py_ssize_t i, PyObject *v) { - unsigned char x; - /* 'B' == unsigned char, maps to PyArg_Parse's 'b' formatter */ - if (!PyArg_Parse(v, "b;array item must be integer", &x)) - return -1; - if (i >= 0) - ((char *)ap->ob_item)[i] = x; - return 0; + unsigned char x; + /* 'B' == unsigned char, maps to PyArg_Parse's 'b' formatter */ + if (!PyArg_Parse(v, "b;array item must be integer", &x)) + return -1; + if (i >= 0) + ((char *)ap->ob_item)[i] = x; + return 0; } static PyObject * u_getitem(arrayobject *ap, Py_ssize_t i) { - return PyUnicode_FromUnicode(&((Py_UNICODE *) ap->ob_item)[i], 1); + return PyUnicode_FromUnicode(&((Py_UNICODE *) ap->ob_item)[i], 1); } static int u_setitem(arrayobject *ap, Py_ssize_t i, PyObject *v) { - Py_UNICODE *p; - Py_ssize_t len; + Py_UNICODE *p; + Py_ssize_t len; - if (!PyArg_Parse(v, "u#;array item must be unicode character", &p, &len)) - return -1; - if (len != 1) { - PyErr_SetString(PyExc_TypeError, - "array item must be unicode character"); - return -1; - } - if (i >= 0) - ((Py_UNICODE *)ap->ob_item)[i] = p[0]; - return 0; + if (!PyArg_Parse(v, "u#;array item must be unicode character", &p, &len)) + return -1; + if (len != 1) { + PyErr_SetString(PyExc_TypeError, + "array item must be unicode character"); + return -1; + } + if (i >= 0) + ((Py_UNICODE *)ap->ob_item)[i] = p[0]; + return 0; } static PyObject * h_getitem(arrayobject *ap, Py_ssize_t i) { - return PyLong_FromLong((long) ((short *)ap->ob_item)[i]); + return PyLong_FromLong((long) ((short *)ap->ob_item)[i]); } static int h_setitem(arrayobject *ap, Py_ssize_t i, PyObject *v) { - short x; - /* 'h' == signed short, maps to PyArg_Parse's 'h' formatter */ - if (!PyArg_Parse(v, "h;array item must be integer", &x)) - return -1; - if (i >= 0) - ((short *)ap->ob_item)[i] = x; - return 0; + short x; + /* 'h' == signed short, maps to PyArg_Parse's 'h' formatter */ + if (!PyArg_Parse(v, "h;array item must be integer", &x)) + return -1; + if (i >= 0) + ((short *)ap->ob_item)[i] = x; + return 0; } static PyObject * HH_getitem(arrayobject *ap, Py_ssize_t i) { - return PyLong_FromLong((long) ((unsigned short *)ap->ob_item)[i]); + return PyLong_FromLong((long) ((unsigned short *)ap->ob_item)[i]); } static int HH_setitem(arrayobject *ap, Py_ssize_t i, PyObject *v) { - int x; - /* PyArg_Parse's 'h' formatter is for a signed short, therefore - must use the next size up and manually do the overflow checking */ - if (!PyArg_Parse(v, "i;array item must be integer", &x)) - return -1; - else if (x < 0) { - PyErr_SetString(PyExc_OverflowError, - "unsigned short is less than minimum"); - return -1; - } - else if (x > USHRT_MAX) { - PyErr_SetString(PyExc_OverflowError, - "unsigned short is greater than maximum"); - return -1; - } - if (i >= 0) - ((short *)ap->ob_item)[i] = (short)x; - return 0; + int x; + /* PyArg_Parse's 'h' formatter is for a signed short, therefore + must use the next size up and manually do the overflow checking */ + if (!PyArg_Parse(v, "i;array item must be integer", &x)) + return -1; + else if (x < 0) { + PyErr_SetString(PyExc_OverflowError, + "unsigned short is less than minimum"); + return -1; + } + else if (x > USHRT_MAX) { + PyErr_SetString(PyExc_OverflowError, + "unsigned short is greater than maximum"); + return -1; + } + if (i >= 0) + ((short *)ap->ob_item)[i] = (short)x; + return 0; } static PyObject * i_getitem(arrayobject *ap, Py_ssize_t i) { - return PyLong_FromLong((long) ((int *)ap->ob_item)[i]); + return PyLong_FromLong((long) ((int *)ap->ob_item)[i]); } static int i_setitem(arrayobject *ap, Py_ssize_t i, PyObject *v) { - int x; - /* 'i' == signed int, maps to PyArg_Parse's 'i' formatter */ - if (!PyArg_Parse(v, "i;array item must be integer", &x)) - return -1; - if (i >= 0) - ((int *)ap->ob_item)[i] = x; - return 0; + int x; + /* 'i' == signed int, maps to PyArg_Parse's 'i' formatter */ + if (!PyArg_Parse(v, "i;array item must be integer", &x)) + return -1; + if (i >= 0) + ((int *)ap->ob_item)[i] = x; + return 0; } static PyObject * II_getitem(arrayobject *ap, Py_ssize_t i) { - return PyLong_FromUnsignedLong( - (unsigned long) ((unsigned int *)ap->ob_item)[i]); + return PyLong_FromUnsignedLong( + (unsigned long) ((unsigned int *)ap->ob_item)[i]); } static int II_setitem(arrayobject *ap, Py_ssize_t i, PyObject *v) { - unsigned long x; - if (PyLong_Check(v)) { - x = PyLong_AsUnsignedLong(v); - if (x == (unsigned long) -1 && PyErr_Occurred()) - return -1; - } - else { - long y; - if (!PyArg_Parse(v, "l;array item must be integer", &y)) - return -1; - if (y < 0) { - PyErr_SetString(PyExc_OverflowError, - "unsigned int is less than minimum"); - return -1; - } - x = (unsigned long)y; - - } - if (x > UINT_MAX) { - PyErr_SetString(PyExc_OverflowError, - "unsigned int is greater than maximum"); - return -1; - } - - if (i >= 0) - ((unsigned int *)ap->ob_item)[i] = (unsigned int)x; - return 0; + unsigned long x; + if (PyLong_Check(v)) { + x = PyLong_AsUnsignedLong(v); + if (x == (unsigned long) -1 && PyErr_Occurred()) + return -1; + } + else { + long y; + if (!PyArg_Parse(v, "l;array item must be integer", &y)) + return -1; + if (y < 0) { + PyErr_SetString(PyExc_OverflowError, + "unsigned int is less than minimum"); + return -1; + } + x = (unsigned long)y; + + } + if (x > UINT_MAX) { + PyErr_SetString(PyExc_OverflowError, + "unsigned int is greater than maximum"); + return -1; + } + + if (i >= 0) + ((unsigned int *)ap->ob_item)[i] = (unsigned int)x; + return 0; } static PyObject * l_getitem(arrayobject *ap, Py_ssize_t i) { - return PyLong_FromLong(((long *)ap->ob_item)[i]); + return PyLong_FromLong(((long *)ap->ob_item)[i]); } static int l_setitem(arrayobject *ap, Py_ssize_t i, PyObject *v) { - long x; - if (!PyArg_Parse(v, "l;array item must be integer", &x)) - return -1; - if (i >= 0) - ((long *)ap->ob_item)[i] = x; - return 0; + long x; + if (!PyArg_Parse(v, "l;array item must be integer", &x)) + return -1; + if (i >= 0) + ((long *)ap->ob_item)[i] = x; + return 0; } static PyObject * LL_getitem(arrayobject *ap, Py_ssize_t i) { - return PyLong_FromUnsignedLong(((unsigned long *)ap->ob_item)[i]); + return PyLong_FromUnsignedLong(((unsigned long *)ap->ob_item)[i]); } static int LL_setitem(arrayobject *ap, Py_ssize_t i, PyObject *v) { - unsigned long x; - if (PyLong_Check(v)) { - x = PyLong_AsUnsignedLong(v); - if (x == (unsigned long) -1 && PyErr_Occurred()) - return -1; - } - else { - long y; - if (!PyArg_Parse(v, "l;array item must be integer", &y)) - return -1; - if (y < 0) { - PyErr_SetString(PyExc_OverflowError, - "unsigned long is less than minimum"); - return -1; - } - x = (unsigned long)y; - - } - if (x > ULONG_MAX) { - PyErr_SetString(PyExc_OverflowError, - "unsigned long is greater than maximum"); - return -1; - } - - if (i >= 0) - ((unsigned long *)ap->ob_item)[i] = x; - return 0; + unsigned long x; + if (PyLong_Check(v)) { + x = PyLong_AsUnsignedLong(v); + if (x == (unsigned long) -1 && PyErr_Occurred()) + return -1; + } + else { + long y; + if (!PyArg_Parse(v, "l;array item must be integer", &y)) + return -1; + if (y < 0) { + PyErr_SetString(PyExc_OverflowError, + "unsigned long is less than minimum"); + return -1; + } + x = (unsigned long)y; + + } + if (x > ULONG_MAX) { + PyErr_SetString(PyExc_OverflowError, + "unsigned long is greater than maximum"); + return -1; + } + + if (i >= 0) + ((unsigned long *)ap->ob_item)[i] = x; + return 0; } static PyObject * f_getitem(arrayobject *ap, Py_ssize_t i) { - return PyFloat_FromDouble((double) ((float *)ap->ob_item)[i]); + return PyFloat_FromDouble((double) ((float *)ap->ob_item)[i]); } static int f_setitem(arrayobject *ap, Py_ssize_t i, PyObject *v) { - float x; - if (!PyArg_Parse(v, "f;array item must be float", &x)) - return -1; - if (i >= 0) - ((float *)ap->ob_item)[i] = x; - return 0; + float x; + if (!PyArg_Parse(v, "f;array item must be float", &x)) + return -1; + if (i >= 0) + ((float *)ap->ob_item)[i] = x; + return 0; } static PyObject * d_getitem(arrayobject *ap, Py_ssize_t i) { - return PyFloat_FromDouble(((double *)ap->ob_item)[i]); + return PyFloat_FromDouble(((double *)ap->ob_item)[i]); } static int d_setitem(arrayobject *ap, Py_ssize_t i, PyObject *v) { - double x; - if (!PyArg_Parse(v, "d;array item must be float", &x)) - return -1; - if (i >= 0) - ((double *)ap->ob_item)[i] = x; - return 0; + double x; + if (!PyArg_Parse(v, "d;array item must be float", &x)) + return -1; + if (i >= 0) + ((double *)ap->ob_item)[i] = x; + return 0; } @@ -397,18 +397,18 @@ * typecode. */ static struct arraydescr descriptors[] = { - {'b', 1, b_getitem, b_setitem, "b", 1, 1}, - {'B', 1, BB_getitem, BB_setitem, "B", 1, 0}, - {'u', sizeof(Py_UNICODE), u_getitem, u_setitem, "u", 0, 0}, - {'h', sizeof(short), h_getitem, h_setitem, "h", 1, 1}, - {'H', sizeof(short), HH_getitem, HH_setitem, "H", 1, 0}, - {'i', sizeof(int), i_getitem, i_setitem, "i", 1, 1}, - {'I', sizeof(int), II_getitem, II_setitem, "I", 1, 0}, - {'l', sizeof(long), l_getitem, l_setitem, "l", 1, 1}, - {'L', sizeof(long), LL_getitem, LL_setitem, "L", 1, 0}, - {'f', sizeof(float), f_getitem, f_setitem, "f", 0, 0}, - {'d', sizeof(double), d_getitem, d_setitem, "d", 0, 0}, - {'\0', 0, 0, 0, 0, 0, 0} /* Sentinel */ + {'b', 1, b_getitem, b_setitem, "b", 1, 1}, + {'B', 1, BB_getitem, BB_setitem, "B", 1, 0}, + {'u', sizeof(Py_UNICODE), u_getitem, u_setitem, "u", 0, 0}, + {'h', sizeof(short), h_getitem, h_setitem, "h", 1, 1}, + {'H', sizeof(short), HH_getitem, HH_setitem, "H", 1, 0}, + {'i', sizeof(int), i_getitem, i_setitem, "i", 1, 1}, + {'I', sizeof(int), II_getitem, II_setitem, "I", 1, 0}, + {'l', sizeof(long), l_getitem, l_setitem, "l", 1, 1}, + {'L', sizeof(long), LL_getitem, LL_setitem, "L", 1, 0}, + {'f', sizeof(float), f_getitem, f_setitem, "f", 0, 0}, + {'d', sizeof(double), d_getitem, d_setitem, "d", 0, 0}, + {'\0', 0, 0, 0, 0, 0, 0} /* Sentinel */ }; /**************************************************************************** @@ -418,79 +418,79 @@ static PyObject * newarrayobject(PyTypeObject *type, Py_ssize_t size, struct arraydescr *descr) { - arrayobject *op; - size_t nbytes; + arrayobject *op; + size_t nbytes; - if (size < 0) { - PyErr_BadInternalCall(); - return NULL; - } - - nbytes = size * descr->itemsize; - /* Check for overflow */ - if (nbytes / descr->itemsize != (size_t)size) { - return PyErr_NoMemory(); - } - op = (arrayobject *) type->tp_alloc(type, 0); - if (op == NULL) { - return NULL; - } - op->ob_descr = descr; - op->allocated = size; - op->weakreflist = NULL; - Py_SIZE(op) = size; - if (size <= 0) { - op->ob_item = NULL; - } - else { - op->ob_item = PyMem_NEW(char, nbytes); - if (op->ob_item == NULL) { - Py_DECREF(op); - return PyErr_NoMemory(); - } - } - op->ob_exports = 0; - return (PyObject *) op; + if (size < 0) { + PyErr_BadInternalCall(); + return NULL; + } + + nbytes = size * descr->itemsize; + /* Check for overflow */ + if (nbytes / descr->itemsize != (size_t)size) { + return PyErr_NoMemory(); + } + op = (arrayobject *) type->tp_alloc(type, 0); + if (op == NULL) { + return NULL; + } + op->ob_descr = descr; + op->allocated = size; + op->weakreflist = NULL; + Py_SIZE(op) = size; + if (size <= 0) { + op->ob_item = NULL; + } + else { + op->ob_item = PyMem_NEW(char, nbytes); + if (op->ob_item == NULL) { + Py_DECREF(op); + return PyErr_NoMemory(); + } + } + op->ob_exports = 0; + return (PyObject *) op; } static PyObject * getarrayitem(PyObject *op, Py_ssize_t i) { - register arrayobject *ap; - assert(array_Check(op)); - ap = (arrayobject *)op; - assert(i>=0 && iob_descr->getitem)(ap, i); + register arrayobject *ap; + assert(array_Check(op)); + ap = (arrayobject *)op; + assert(i>=0 && iob_descr->getitem)(ap, i); } static int ins1(arrayobject *self, Py_ssize_t where, PyObject *v) { - char *items; - Py_ssize_t n = Py_SIZE(self); - if (v == NULL) { - PyErr_BadInternalCall(); - return -1; - } - if ((*self->ob_descr->setitem)(self, -1, v) < 0) - return -1; - - if (array_resize(self, n+1) == -1) - return -1; - items = self->ob_item; - if (where < 0) { - where += n; - if (where < 0) - where = 0; - } - if (where > n) - where = n; - /* appends don't need to call memmove() */ - if (where != n) - memmove(items + (where+1)*self->ob_descr->itemsize, - items + where*self->ob_descr->itemsize, - (n-where)*self->ob_descr->itemsize); - return (*self->ob_descr->setitem)(self, where, v); + char *items; + Py_ssize_t n = Py_SIZE(self); + if (v == NULL) { + PyErr_BadInternalCall(); + return -1; + } + if ((*self->ob_descr->setitem)(self, -1, v) < 0) + return -1; + + if (array_resize(self, n+1) == -1) + return -1; + items = self->ob_item; + if (where < 0) { + where += n; + if (where < 0) + where = 0; + } + if (where > n) + where = n; + /* appends don't need to call memmove() */ + if (where != n) + memmove(items + (where+1)*self->ob_descr->itemsize, + items + where*self->ob_descr->itemsize, + (n-where)*self->ob_descr->itemsize); + return (*self->ob_descr->setitem)(self, where, v); } /* Methods */ @@ -498,141 +498,141 @@ static void array_dealloc(arrayobject *op) { - if (op->weakreflist != NULL) - PyObject_ClearWeakRefs((PyObject *) op); - if (op->ob_item != NULL) - PyMem_DEL(op->ob_item); - Py_TYPE(op)->tp_free((PyObject *)op); + if (op->weakreflist != NULL) + PyObject_ClearWeakRefs((PyObject *) op); + if (op->ob_item != NULL) + PyMem_DEL(op->ob_item); + Py_TYPE(op)->tp_free((PyObject *)op); } static PyObject * array_richcompare(PyObject *v, PyObject *w, int op) { - arrayobject *va, *wa; - PyObject *vi = NULL; - PyObject *wi = NULL; - Py_ssize_t i, k; - PyObject *res; - - if (!array_Check(v) || !array_Check(w)) { - Py_INCREF(Py_NotImplemented); - return Py_NotImplemented; - } - - va = (arrayobject *)v; - wa = (arrayobject *)w; - - if (Py_SIZE(va) != Py_SIZE(wa) && (op == Py_EQ || op == Py_NE)) { - /* Shortcut: if the lengths differ, the arrays differ */ - if (op == Py_EQ) - res = Py_False; - else - res = Py_True; - Py_INCREF(res); - return res; - } - - /* Search for the first index where items are different */ - k = 1; - for (i = 0; i < Py_SIZE(va) && i < Py_SIZE(wa); i++) { - vi = getarrayitem(v, i); - wi = getarrayitem(w, i); - if (vi == NULL || wi == NULL) { - Py_XDECREF(vi); - Py_XDECREF(wi); - return NULL; - } - k = PyObject_RichCompareBool(vi, wi, Py_EQ); - if (k == 0) - break; /* Keeping vi and wi alive! */ - Py_DECREF(vi); - Py_DECREF(wi); - if (k < 0) - return NULL; - } - - if (k) { - /* No more items to compare -- compare sizes */ - Py_ssize_t vs = Py_SIZE(va); - Py_ssize_t ws = Py_SIZE(wa); - int cmp; - switch (op) { - case Py_LT: cmp = vs < ws; break; - case Py_LE: cmp = vs <= ws; break; - case Py_EQ: cmp = vs == ws; break; - case Py_NE: cmp = vs != ws; break; - case Py_GT: cmp = vs > ws; break; - case Py_GE: cmp = vs >= ws; break; - default: return NULL; /* cannot happen */ - } - if (cmp) - res = Py_True; - else - res = Py_False; - Py_INCREF(res); - return res; - } - - /* We have an item that differs. First, shortcuts for EQ/NE */ - if (op == Py_EQ) { - Py_INCREF(Py_False); - res = Py_False; - } - else if (op == Py_NE) { - Py_INCREF(Py_True); - res = Py_True; - } - else { - /* Compare the final item again using the proper operator */ - res = PyObject_RichCompare(vi, wi, op); - } - Py_DECREF(vi); - Py_DECREF(wi); - return res; + arrayobject *va, *wa; + PyObject *vi = NULL; + PyObject *wi = NULL; + Py_ssize_t i, k; + PyObject *res; + + if (!array_Check(v) || !array_Check(w)) { + Py_INCREF(Py_NotImplemented); + return Py_NotImplemented; + } + + va = (arrayobject *)v; + wa = (arrayobject *)w; + + if (Py_SIZE(va) != Py_SIZE(wa) && (op == Py_EQ || op == Py_NE)) { + /* Shortcut: if the lengths differ, the arrays differ */ + if (op == Py_EQ) + res = Py_False; + else + res = Py_True; + Py_INCREF(res); + return res; + } + + /* Search for the first index where items are different */ + k = 1; + for (i = 0; i < Py_SIZE(va) && i < Py_SIZE(wa); i++) { + vi = getarrayitem(v, i); + wi = getarrayitem(w, i); + if (vi == NULL || wi == NULL) { + Py_XDECREF(vi); + Py_XDECREF(wi); + return NULL; + } + k = PyObject_RichCompareBool(vi, wi, Py_EQ); + if (k == 0) + break; /* Keeping vi and wi alive! */ + Py_DECREF(vi); + Py_DECREF(wi); + if (k < 0) + return NULL; + } + + if (k) { + /* No more items to compare -- compare sizes */ + Py_ssize_t vs = Py_SIZE(va); + Py_ssize_t ws = Py_SIZE(wa); + int cmp; + switch (op) { + case Py_LT: cmp = vs < ws; break; + case Py_LE: cmp = vs <= ws; break; + case Py_EQ: cmp = vs == ws; break; + case Py_NE: cmp = vs != ws; break; + case Py_GT: cmp = vs > ws; break; + case Py_GE: cmp = vs >= ws; break; + default: return NULL; /* cannot happen */ + } + if (cmp) + res = Py_True; + else + res = Py_False; + Py_INCREF(res); + return res; + } + + /* We have an item that differs. First, shortcuts for EQ/NE */ + if (op == Py_EQ) { + Py_INCREF(Py_False); + res = Py_False; + } + else if (op == Py_NE) { + Py_INCREF(Py_True); + res = Py_True; + } + else { + /* Compare the final item again using the proper operator */ + res = PyObject_RichCompare(vi, wi, op); + } + Py_DECREF(vi); + Py_DECREF(wi); + return res; } static Py_ssize_t array_length(arrayobject *a) { - return Py_SIZE(a); + return Py_SIZE(a); } static PyObject * array_item(arrayobject *a, Py_ssize_t i) { - if (i < 0 || i >= Py_SIZE(a)) { - PyErr_SetString(PyExc_IndexError, "array index out of range"); - return NULL; - } - return getarrayitem((PyObject *)a, i); + if (i < 0 || i >= Py_SIZE(a)) { + PyErr_SetString(PyExc_IndexError, "array index out of range"); + return NULL; + } + return getarrayitem((PyObject *)a, i); } static PyObject * array_slice(arrayobject *a, Py_ssize_t ilow, Py_ssize_t ihigh) { - arrayobject *np; - if (ilow < 0) - ilow = 0; - else if (ilow > Py_SIZE(a)) - ilow = Py_SIZE(a); - if (ihigh < 0) - ihigh = 0; - if (ihigh < ilow) - ihigh = ilow; - else if (ihigh > Py_SIZE(a)) - ihigh = Py_SIZE(a); - np = (arrayobject *) newarrayobject(&Arraytype, ihigh - ilow, a->ob_descr); - if (np == NULL) - return NULL; - memcpy(np->ob_item, a->ob_item + ilow * a->ob_descr->itemsize, - (ihigh-ilow) * a->ob_descr->itemsize); - return (PyObject *)np; + arrayobject *np; + if (ilow < 0) + ilow = 0; + else if (ilow > Py_SIZE(a)) + ilow = Py_SIZE(a); + if (ihigh < 0) + ihigh = 0; + if (ihigh < ilow) + ihigh = ilow; + else if (ihigh > Py_SIZE(a)) + ihigh = Py_SIZE(a); + np = (arrayobject *) newarrayobject(&Arraytype, ihigh - ilow, a->ob_descr); + if (np == NULL) + return NULL; + memcpy(np->ob_item, a->ob_item + ilow * a->ob_descr->itemsize, + (ihigh-ilow) * a->ob_descr->itemsize); + return (PyObject *)np; } static PyObject * array_copy(arrayobject *a, PyObject *unused) { - return array_slice(a, 0, Py_SIZE(a)); + return array_slice(a, 0, Py_SIZE(a)); } PyDoc_STRVAR(copy_doc, @@ -643,278 +643,278 @@ static PyObject * array_concat(arrayobject *a, PyObject *bb) { - Py_ssize_t size; - arrayobject *np; - if (!array_Check(bb)) { - PyErr_Format(PyExc_TypeError, - "can only append array (not \"%.200s\") to array", - Py_TYPE(bb)->tp_name); - return NULL; - } + Py_ssize_t size; + arrayobject *np; + if (!array_Check(bb)) { + PyErr_Format(PyExc_TypeError, + "can only append array (not \"%.200s\") to array", + Py_TYPE(bb)->tp_name); + return NULL; + } #define b ((arrayobject *)bb) - if (a->ob_descr != b->ob_descr) { - PyErr_BadArgument(); - return NULL; - } - if (Py_SIZE(a) > PY_SSIZE_T_MAX - Py_SIZE(b)) { - return PyErr_NoMemory(); - } - size = Py_SIZE(a) + Py_SIZE(b); - np = (arrayobject *) newarrayobject(&Arraytype, size, a->ob_descr); - if (np == NULL) { - return NULL; - } - memcpy(np->ob_item, a->ob_item, Py_SIZE(a)*a->ob_descr->itemsize); - memcpy(np->ob_item + Py_SIZE(a)*a->ob_descr->itemsize, - b->ob_item, Py_SIZE(b)*b->ob_descr->itemsize); - return (PyObject *)np; + if (a->ob_descr != b->ob_descr) { + PyErr_BadArgument(); + return NULL; + } + if (Py_SIZE(a) > PY_SSIZE_T_MAX - Py_SIZE(b)) { + return PyErr_NoMemory(); + } + size = Py_SIZE(a) + Py_SIZE(b); + np = (arrayobject *) newarrayobject(&Arraytype, size, a->ob_descr); + if (np == NULL) { + return NULL; + } + memcpy(np->ob_item, a->ob_item, Py_SIZE(a)*a->ob_descr->itemsize); + memcpy(np->ob_item + Py_SIZE(a)*a->ob_descr->itemsize, + b->ob_item, Py_SIZE(b)*b->ob_descr->itemsize); + return (PyObject *)np; #undef b } static PyObject * array_repeat(arrayobject *a, Py_ssize_t n) { - Py_ssize_t i; - Py_ssize_t size; - arrayobject *np; - char *p; - Py_ssize_t nbytes; - if (n < 0) - n = 0; - if ((Py_SIZE(a) != 0) && (n > PY_SSIZE_T_MAX / Py_SIZE(a))) { - return PyErr_NoMemory(); - } - size = Py_SIZE(a) * n; - np = (arrayobject *) newarrayobject(&Arraytype, size, a->ob_descr); - if (np == NULL) - return NULL; - p = np->ob_item; - nbytes = Py_SIZE(a) * a->ob_descr->itemsize; - for (i = 0; i < n; i++) { - memcpy(p, a->ob_item, nbytes); - p += nbytes; - } - return (PyObject *) np; + Py_ssize_t i; + Py_ssize_t size; + arrayobject *np; + char *p; + Py_ssize_t nbytes; + if (n < 0) + n = 0; + if ((Py_SIZE(a) != 0) && (n > PY_SSIZE_T_MAX / Py_SIZE(a))) { + return PyErr_NoMemory(); + } + size = Py_SIZE(a) * n; + np = (arrayobject *) newarrayobject(&Arraytype, size, a->ob_descr); + if (np == NULL) + return NULL; + p = np->ob_item; + nbytes = Py_SIZE(a) * a->ob_descr->itemsize; + for (i = 0; i < n; i++) { + memcpy(p, a->ob_item, nbytes); + p += nbytes; + } + return (PyObject *) np; } static int array_ass_slice(arrayobject *a, Py_ssize_t ilow, Py_ssize_t ihigh, PyObject *v) { - char *item; - Py_ssize_t n; /* Size of replacement array */ - Py_ssize_t d; /* Change in size */ + char *item; + Py_ssize_t n; /* Size of replacement array */ + Py_ssize_t d; /* Change in size */ #define b ((arrayobject *)v) - if (v == NULL) - n = 0; - else if (array_Check(v)) { - n = Py_SIZE(b); - if (a == b) { - /* Special case "a[i:j] = a" -- copy b first */ - int ret; - v = array_slice(b, 0, n); - if (!v) - return -1; - ret = array_ass_slice(a, ilow, ihigh, v); - Py_DECREF(v); - return ret; - } - if (b->ob_descr != a->ob_descr) { - PyErr_BadArgument(); - return -1; - } - } - else { - PyErr_Format(PyExc_TypeError, - "can only assign array (not \"%.200s\") to array slice", - Py_TYPE(v)->tp_name); - return -1; - } - if (ilow < 0) - ilow = 0; - else if (ilow > Py_SIZE(a)) - ilow = Py_SIZE(a); - if (ihigh < 0) - ihigh = 0; - if (ihigh < ilow) - ihigh = ilow; - else if (ihigh > Py_SIZE(a)) - ihigh = Py_SIZE(a); - item = a->ob_item; - d = n - (ihigh-ilow); - /* Issue #4509: If the array has exported buffers and the slice - assignment would change the size of the array, fail early to make - sure we don't modify it. */ - if (d != 0 && a->ob_exports > 0) { - PyErr_SetString(PyExc_BufferError, - "cannot resize an array that is exporting buffers"); - return -1; - } - if (d < 0) { /* Delete -d items */ - memmove(item + (ihigh+d)*a->ob_descr->itemsize, - item + ihigh*a->ob_descr->itemsize, - (Py_SIZE(a)-ihigh)*a->ob_descr->itemsize); - if (array_resize(a, Py_SIZE(a) + d) == -1) - return -1; - } - else if (d > 0) { /* Insert d items */ - if (array_resize(a, Py_SIZE(a) + d)) - return -1; - memmove(item + (ihigh+d)*a->ob_descr->itemsize, - item + ihigh*a->ob_descr->itemsize, - (Py_SIZE(a)-ihigh)*a->ob_descr->itemsize); - } - if (n > 0) - memcpy(item + ilow*a->ob_descr->itemsize, b->ob_item, - n*b->ob_descr->itemsize); - return 0; + if (v == NULL) + n = 0; + else if (array_Check(v)) { + n = Py_SIZE(b); + if (a == b) { + /* Special case "a[i:j] = a" -- copy b first */ + int ret; + v = array_slice(b, 0, n); + if (!v) + return -1; + ret = array_ass_slice(a, ilow, ihigh, v); + Py_DECREF(v); + return ret; + } + if (b->ob_descr != a->ob_descr) { + PyErr_BadArgument(); + return -1; + } + } + else { + PyErr_Format(PyExc_TypeError, + "can only assign array (not \"%.200s\") to array slice", + Py_TYPE(v)->tp_name); + return -1; + } + if (ilow < 0) + ilow = 0; + else if (ilow > Py_SIZE(a)) + ilow = Py_SIZE(a); + if (ihigh < 0) + ihigh = 0; + if (ihigh < ilow) + ihigh = ilow; + else if (ihigh > Py_SIZE(a)) + ihigh = Py_SIZE(a); + item = a->ob_item; + d = n - (ihigh-ilow); + /* Issue #4509: If the array has exported buffers and the slice + assignment would change the size of the array, fail early to make + sure we don't modify it. */ + if (d != 0 && a->ob_exports > 0) { + PyErr_SetString(PyExc_BufferError, + "cannot resize an array that is exporting buffers"); + return -1; + } + if (d < 0) { /* Delete -d items */ + memmove(item + (ihigh+d)*a->ob_descr->itemsize, + item + ihigh*a->ob_descr->itemsize, + (Py_SIZE(a)-ihigh)*a->ob_descr->itemsize); + if (array_resize(a, Py_SIZE(a) + d) == -1) + return -1; + } + else if (d > 0) { /* Insert d items */ + if (array_resize(a, Py_SIZE(a) + d)) + return -1; + memmove(item + (ihigh+d)*a->ob_descr->itemsize, + item + ihigh*a->ob_descr->itemsize, + (Py_SIZE(a)-ihigh)*a->ob_descr->itemsize); + } + if (n > 0) + memcpy(item + ilow*a->ob_descr->itemsize, b->ob_item, + n*b->ob_descr->itemsize); + return 0; #undef b } static int array_ass_item(arrayobject *a, Py_ssize_t i, PyObject *v) { - if (i < 0 || i >= Py_SIZE(a)) { - PyErr_SetString(PyExc_IndexError, - "array assignment index out of range"); - return -1; - } - if (v == NULL) - return array_ass_slice(a, i, i+1, v); - return (*a->ob_descr->setitem)(a, i, v); + if (i < 0 || i >= Py_SIZE(a)) { + PyErr_SetString(PyExc_IndexError, + "array assignment index out of range"); + return -1; + } + if (v == NULL) + return array_ass_slice(a, i, i+1, v); + return (*a->ob_descr->setitem)(a, i, v); } static int setarrayitem(PyObject *a, Py_ssize_t i, PyObject *v) { - assert(array_Check(a)); - return array_ass_item((arrayobject *)a, i, v); + assert(array_Check(a)); + return array_ass_item((arrayobject *)a, i, v); } static int array_iter_extend(arrayobject *self, PyObject *bb) { - PyObject *it, *v; + PyObject *it, *v; - it = PyObject_GetIter(bb); - if (it == NULL) - return -1; - - while ((v = PyIter_Next(it)) != NULL) { - if (ins1(self, (int) Py_SIZE(self), v) != 0) { - Py_DECREF(v); - Py_DECREF(it); - return -1; - } - Py_DECREF(v); - } - Py_DECREF(it); - if (PyErr_Occurred()) - return -1; - return 0; + it = PyObject_GetIter(bb); + if (it == NULL) + return -1; + + while ((v = PyIter_Next(it)) != NULL) { + if (ins1(self, (int) Py_SIZE(self), v) != 0) { + Py_DECREF(v); + Py_DECREF(it); + return -1; + } + Py_DECREF(v); + } + Py_DECREF(it); + if (PyErr_Occurred()) + return -1; + return 0; } static int array_do_extend(arrayobject *self, PyObject *bb) { - Py_ssize_t size, oldsize, bbsize; - - if (!array_Check(bb)) - return array_iter_extend(self, bb); + Py_ssize_t size, oldsize, bbsize; + + if (!array_Check(bb)) + return array_iter_extend(self, bb); #define b ((arrayobject *)bb) - if (self->ob_descr != b->ob_descr) { - PyErr_SetString(PyExc_TypeError, - "can only extend with array of same kind"); - return -1; - } - if ((Py_SIZE(self) > PY_SSIZE_T_MAX - Py_SIZE(b)) || - ((Py_SIZE(self) + Py_SIZE(b)) > PY_SSIZE_T_MAX / self->ob_descr->itemsize)) { - PyErr_NoMemory(); - return -1; - } - oldsize = Py_SIZE(self); - /* Get the size of bb before resizing the array since bb could be self. */ - bbsize = Py_SIZE(bb); - size = oldsize + Py_SIZE(b); - if (array_resize(self, size) == -1) - return -1; - memcpy(self->ob_item + oldsize * self->ob_descr->itemsize, - b->ob_item, bbsize * b->ob_descr->itemsize); + if (self->ob_descr != b->ob_descr) { + PyErr_SetString(PyExc_TypeError, + "can only extend with array of same kind"); + return -1; + } + if ((Py_SIZE(self) > PY_SSIZE_T_MAX - Py_SIZE(b)) || + ((Py_SIZE(self) + Py_SIZE(b)) > PY_SSIZE_T_MAX / self->ob_descr->itemsize)) { + PyErr_NoMemory(); + return -1; + } + oldsize = Py_SIZE(self); + /* Get the size of bb before resizing the array since bb could be self. */ + bbsize = Py_SIZE(bb); + size = oldsize + Py_SIZE(b); + if (array_resize(self, size) == -1) + return -1; + memcpy(self->ob_item + oldsize * self->ob_descr->itemsize, + b->ob_item, bbsize * b->ob_descr->itemsize); - return 0; + return 0; #undef b } static PyObject * array_inplace_concat(arrayobject *self, PyObject *bb) { - if (!array_Check(bb)) { - PyErr_Format(PyExc_TypeError, - "can only extend array with array (not \"%.200s\")", - Py_TYPE(bb)->tp_name); - return NULL; - } - if (array_do_extend(self, bb) == -1) - return NULL; - Py_INCREF(self); - return (PyObject *)self; + if (!array_Check(bb)) { + PyErr_Format(PyExc_TypeError, + "can only extend array with array (not \"%.200s\")", + Py_TYPE(bb)->tp_name); + return NULL; + } + if (array_do_extend(self, bb) == -1) + return NULL; + Py_INCREF(self); + return (PyObject *)self; } static PyObject * array_inplace_repeat(arrayobject *self, Py_ssize_t n) { - char *items, *p; - Py_ssize_t size, i; + char *items, *p; + Py_ssize_t size, i; - if (Py_SIZE(self) > 0) { - if (n < 0) - n = 0; - items = self->ob_item; - if ((self->ob_descr->itemsize != 0) && - (Py_SIZE(self) > PY_SSIZE_T_MAX / self->ob_descr->itemsize)) { - return PyErr_NoMemory(); - } - size = Py_SIZE(self) * self->ob_descr->itemsize; - if (n > 0 && size > PY_SSIZE_T_MAX / n) { - return PyErr_NoMemory(); - } - if (array_resize(self, n * Py_SIZE(self)) == -1) - return NULL; - items = p = self->ob_item; - for (i = 1; i < n; i++) { - p += size; - memcpy(p, items, size); - } - } - Py_INCREF(self); - return (PyObject *)self; + if (Py_SIZE(self) > 0) { + if (n < 0) + n = 0; + items = self->ob_item; + if ((self->ob_descr->itemsize != 0) && + (Py_SIZE(self) > PY_SSIZE_T_MAX / self->ob_descr->itemsize)) { + return PyErr_NoMemory(); + } + size = Py_SIZE(self) * self->ob_descr->itemsize; + if (n > 0 && size > PY_SSIZE_T_MAX / n) { + return PyErr_NoMemory(); + } + if (array_resize(self, n * Py_SIZE(self)) == -1) + return NULL; + items = p = self->ob_item; + for (i = 1; i < n; i++) { + p += size; + memcpy(p, items, size); + } + } + Py_INCREF(self); + return (PyObject *)self; } static PyObject * ins(arrayobject *self, Py_ssize_t where, PyObject *v) { - if (ins1(self, where, v) != 0) - return NULL; - Py_INCREF(Py_None); - return Py_None; + if (ins1(self, where, v) != 0) + return NULL; + Py_INCREF(Py_None); + return Py_None; } static PyObject * array_count(arrayobject *self, PyObject *v) { - Py_ssize_t count = 0; - Py_ssize_t i; + Py_ssize_t count = 0; + Py_ssize_t i; - for (i = 0; i < Py_SIZE(self); i++) { - PyObject *selfi = getarrayitem((PyObject *)self, i); - int cmp = PyObject_RichCompareBool(selfi, v, Py_EQ); - Py_DECREF(selfi); - if (cmp > 0) - count++; - else if (cmp < 0) - return NULL; - } - return PyLong_FromSsize_t(count); + for (i = 0; i < Py_SIZE(self); i++) { + PyObject *selfi = getarrayitem((PyObject *)self, i); + int cmp = PyObject_RichCompareBool(selfi, v, Py_EQ); + Py_DECREF(selfi); + if (cmp > 0) + count++; + else if (cmp < 0) + return NULL; + } + return PyLong_FromSsize_t(count); } PyDoc_STRVAR(count_doc, @@ -925,20 +925,20 @@ static PyObject * array_index(arrayobject *self, PyObject *v) { - Py_ssize_t i; + Py_ssize_t i; - for (i = 0; i < Py_SIZE(self); i++) { - PyObject *selfi = getarrayitem((PyObject *)self, i); - int cmp = PyObject_RichCompareBool(selfi, v, Py_EQ); - Py_DECREF(selfi); - if (cmp > 0) { - return PyLong_FromLong((long)i); - } - else if (cmp < 0) - return NULL; - } - PyErr_SetString(PyExc_ValueError, "array.index(x): x not in list"); - return NULL; + for (i = 0; i < Py_SIZE(self); i++) { + PyObject *selfi = getarrayitem((PyObject *)self, i); + int cmp = PyObject_RichCompareBool(selfi, v, Py_EQ); + Py_DECREF(selfi); + if (cmp > 0) { + return PyLong_FromLong((long)i); + } + else if (cmp < 0) + return NULL; + } + PyErr_SetString(PyExc_ValueError, "array.index(x): x not in list"); + return NULL; } PyDoc_STRVAR(index_doc, @@ -949,38 +949,38 @@ static int array_contains(arrayobject *self, PyObject *v) { - Py_ssize_t i; - int cmp; + Py_ssize_t i; + int cmp; - for (i = 0, cmp = 0 ; cmp == 0 && i < Py_SIZE(self); i++) { - PyObject *selfi = getarrayitem((PyObject *)self, i); - cmp = PyObject_RichCompareBool(selfi, v, Py_EQ); - Py_DECREF(selfi); - } - return cmp; + for (i = 0, cmp = 0 ; cmp == 0 && i < Py_SIZE(self); i++) { + PyObject *selfi = getarrayitem((PyObject *)self, i); + cmp = PyObject_RichCompareBool(selfi, v, Py_EQ); + Py_DECREF(selfi); + } + return cmp; } static PyObject * array_remove(arrayobject *self, PyObject *v) { - int i; + int i; - for (i = 0; i < Py_SIZE(self); i++) { - PyObject *selfi = getarrayitem((PyObject *)self,i); - int cmp = PyObject_RichCompareBool(selfi, v, Py_EQ); - Py_DECREF(selfi); - if (cmp > 0) { - if (array_ass_slice(self, i, i+1, - (PyObject *)NULL) != 0) - return NULL; - Py_INCREF(Py_None); - return Py_None; - } - else if (cmp < 0) - return NULL; - } - PyErr_SetString(PyExc_ValueError, "array.remove(x): x not in list"); - return NULL; + for (i = 0; i < Py_SIZE(self); i++) { + PyObject *selfi = getarrayitem((PyObject *)self,i); + int cmp = PyObject_RichCompareBool(selfi, v, Py_EQ); + Py_DECREF(selfi); + if (cmp > 0) { + if (array_ass_slice(self, i, i+1, + (PyObject *)NULL) != 0) + return NULL; + Py_INCREF(Py_None); + return Py_None; + } + else if (cmp < 0) + return NULL; + } + PyErr_SetString(PyExc_ValueError, "array.remove(x): x not in list"); + return NULL; } PyDoc_STRVAR(remove_doc, @@ -991,27 +991,27 @@ static PyObject * array_pop(arrayobject *self, PyObject *args) { - Py_ssize_t i = -1; - PyObject *v; - if (!PyArg_ParseTuple(args, "|n:pop", &i)) - return NULL; - if (Py_SIZE(self) == 0) { - /* Special-case most common failure cause */ - PyErr_SetString(PyExc_IndexError, "pop from empty array"); - return NULL; - } - if (i < 0) - i += Py_SIZE(self); - if (i < 0 || i >= Py_SIZE(self)) { - PyErr_SetString(PyExc_IndexError, "pop index out of range"); - return NULL; - } - v = getarrayitem((PyObject *)self,i); - if (array_ass_slice(self, i, i+1, (PyObject *)NULL) != 0) { - Py_DECREF(v); - return NULL; - } - return v; + Py_ssize_t i = -1; + PyObject *v; + if (!PyArg_ParseTuple(args, "|n:pop", &i)) + return NULL; + if (Py_SIZE(self) == 0) { + /* Special-case most common failure cause */ + PyErr_SetString(PyExc_IndexError, "pop from empty array"); + return NULL; + } + if (i < 0) + i += Py_SIZE(self); + if (i < 0 || i >= Py_SIZE(self)) { + PyErr_SetString(PyExc_IndexError, "pop index out of range"); + return NULL; + } + v = getarrayitem((PyObject *)self,i); + if (array_ass_slice(self, i, i+1, (PyObject *)NULL) != 0) { + Py_DECREF(v); + return NULL; + } + return v; } PyDoc_STRVAR(pop_doc, @@ -1022,10 +1022,10 @@ static PyObject * array_extend(arrayobject *self, PyObject *bb) { - if (array_do_extend(self, bb) == -1) - return NULL; - Py_INCREF(Py_None); - return Py_None; + if (array_do_extend(self, bb) == -1) + return NULL; + Py_INCREF(Py_None); + return Py_None; } PyDoc_STRVAR(extend_doc, @@ -1036,11 +1036,11 @@ static PyObject * array_insert(arrayobject *self, PyObject *args) { - Py_ssize_t i; - PyObject *v; - if (!PyArg_ParseTuple(args, "nO:insert", &i, &v)) - return NULL; - return ins(self, i, v); + Py_ssize_t i; + PyObject *v; + if (!PyArg_ParseTuple(args, "nO:insert", &i, &v)) + return NULL; + return ins(self, i, v); } PyDoc_STRVAR(insert_doc, @@ -1052,15 +1052,15 @@ static PyObject * array_buffer_info(arrayobject *self, PyObject *unused) { - PyObject* retval = NULL; - retval = PyTuple_New(2); - if (!retval) - return NULL; + PyObject* retval = NULL; + retval = PyTuple_New(2); + if (!retval) + return NULL; - PyTuple_SET_ITEM(retval, 0, PyLong_FromVoidPtr(self->ob_item)); - PyTuple_SET_ITEM(retval, 1, PyLong_FromLong((long)(Py_SIZE(self)))); + PyTuple_SET_ITEM(retval, 0, PyLong_FromVoidPtr(self->ob_item)); + PyTuple_SET_ITEM(retval, 1, PyLong_FromLong((long)(Py_SIZE(self)))); - return retval; + return retval; } PyDoc_STRVAR(buffer_info_doc, @@ -1075,7 +1075,7 @@ static PyObject * array_append(arrayobject *self, PyObject *v) { - return ins(self, (int) Py_SIZE(self), v); + return ins(self, (int) Py_SIZE(self), v); } PyDoc_STRVAR(append_doc, @@ -1087,52 +1087,52 @@ static PyObject * array_byteswap(arrayobject *self, PyObject *unused) { - char *p; - Py_ssize_t i; + char *p; + Py_ssize_t i; - switch (self->ob_descr->itemsize) { - case 1: - break; - case 2: - for (p = self->ob_item, i = Py_SIZE(self); --i >= 0; p += 2) { - char p0 = p[0]; - p[0] = p[1]; - p[1] = p0; - } - break; - case 4: - for (p = self->ob_item, i = Py_SIZE(self); --i >= 0; p += 4) { - char p0 = p[0]; - char p1 = p[1]; - p[0] = p[3]; - p[1] = p[2]; - p[2] = p1; - p[3] = p0; - } - break; - case 8: - for (p = self->ob_item, i = Py_SIZE(self); --i >= 0; p += 8) { - char p0 = p[0]; - char p1 = p[1]; - char p2 = p[2]; - char p3 = p[3]; - p[0] = p[7]; - p[1] = p[6]; - p[2] = p[5]; - p[3] = p[4]; - p[4] = p3; - p[5] = p2; - p[6] = p1; - p[7] = p0; - } - break; - default: - PyErr_SetString(PyExc_RuntimeError, - "don't know how to byteswap this array type"); - return NULL; - } - Py_INCREF(Py_None); - return Py_None; + switch (self->ob_descr->itemsize) { + case 1: + break; + case 2: + for (p = self->ob_item, i = Py_SIZE(self); --i >= 0; p += 2) { + char p0 = p[0]; + p[0] = p[1]; + p[1] = p0; + } + break; + case 4: + for (p = self->ob_item, i = Py_SIZE(self); --i >= 0; p += 4) { + char p0 = p[0]; + char p1 = p[1]; + p[0] = p[3]; + p[1] = p[2]; + p[2] = p1; + p[3] = p0; + } + break; + case 8: + for (p = self->ob_item, i = Py_SIZE(self); --i >= 0; p += 8) { + char p0 = p[0]; + char p1 = p[1]; + char p2 = p[2]; + char p3 = p[3]; + p[0] = p[7]; + p[1] = p[6]; + p[2] = p[5]; + p[3] = p[4]; + p[4] = p3; + p[5] = p2; + p[6] = p1; + p[7] = p0; + } + break; + default: + PyErr_SetString(PyExc_RuntimeError, + "don't know how to byteswap this array type"); + return NULL; + } + Py_INCREF(Py_None); + return Py_None; } PyDoc_STRVAR(byteswap_doc, @@ -1144,28 +1144,28 @@ static PyObject * array_reverse(arrayobject *self, PyObject *unused) { - register Py_ssize_t itemsize = self->ob_descr->itemsize; - register char *p, *q; - /* little buffer to hold items while swapping */ - char tmp[256]; /* 8 is probably enough -- but why skimp */ - assert((size_t)itemsize <= sizeof(tmp)); - - if (Py_SIZE(self) > 1) { - for (p = self->ob_item, - q = self->ob_item + (Py_SIZE(self) - 1)*itemsize; - p < q; - p += itemsize, q -= itemsize) { - /* memory areas guaranteed disjoint, so memcpy - * is safe (& memmove may be slower). - */ - memcpy(tmp, p, itemsize); - memcpy(p, q, itemsize); - memcpy(q, tmp, itemsize); - } - } + register Py_ssize_t itemsize = self->ob_descr->itemsize; + register char *p, *q; + /* little buffer to hold items while swapping */ + char tmp[256]; /* 8 is probably enough -- but why skimp */ + assert((size_t)itemsize <= sizeof(tmp)); + + if (Py_SIZE(self) > 1) { + for (p = self->ob_item, + q = self->ob_item + (Py_SIZE(self) - 1)*itemsize; + p < q; + p += itemsize, q -= itemsize) { + /* memory areas guaranteed disjoint, so memcpy + * is safe (& memmove may be slower). + */ + memcpy(tmp, p, itemsize); + memcpy(p, q, itemsize); + memcpy(q, tmp, itemsize); + } + } - Py_INCREF(Py_None); - return Py_None; + Py_INCREF(Py_None); + return Py_None; } PyDoc_STRVAR(reverse_doc, @@ -1180,51 +1180,51 @@ static PyObject * array_fromfile(arrayobject *self, PyObject *args) { - PyObject *f, *b, *res; - Py_ssize_t itemsize = self->ob_descr->itemsize; - Py_ssize_t n, nbytes; - int not_enough_bytes; - - if (!PyArg_ParseTuple(args, "On:fromfile", &f, &n)) - return NULL; - - nbytes = n * itemsize; - if (nbytes < 0 || nbytes/itemsize != n) { - PyErr_NoMemory(); - return NULL; - } - - b = PyObject_CallMethod(f, "read", "n", nbytes); - if (b == NULL) - return NULL; - - if (!PyBytes_Check(b)) { - PyErr_SetString(PyExc_TypeError, - "read() didn't return bytes"); - Py_DECREF(b); - return NULL; - } - - not_enough_bytes = (PyBytes_GET_SIZE(b) != nbytes); - - args = Py_BuildValue("(O)", b); - Py_DECREF(b); - if (args == NULL) - return NULL; - - res = array_fromstring(self, args); - Py_DECREF(args); - if (res == NULL) - return NULL; - - if (not_enough_bytes) { - PyErr_SetString(PyExc_EOFError, - "read() didn't return enough bytes"); - Py_DECREF(res); - return NULL; - } + PyObject *f, *b, *res; + Py_ssize_t itemsize = self->ob_descr->itemsize; + Py_ssize_t n, nbytes; + int not_enough_bytes; + + if (!PyArg_ParseTuple(args, "On:fromfile", &f, &n)) + return NULL; + + nbytes = n * itemsize; + if (nbytes < 0 || nbytes/itemsize != n) { + PyErr_NoMemory(); + return NULL; + } + + b = PyObject_CallMethod(f, "read", "n", nbytes); + if (b == NULL) + return NULL; + + if (!PyBytes_Check(b)) { + PyErr_SetString(PyExc_TypeError, + "read() didn't return bytes"); + Py_DECREF(b); + return NULL; + } + + not_enough_bytes = (PyBytes_GET_SIZE(b) != nbytes); + + args = Py_BuildValue("(O)", b); + Py_DECREF(b); + if (args == NULL) + return NULL; + + res = array_fromstring(self, args); + Py_DECREF(args); + if (res == NULL) + return NULL; + + if (not_enough_bytes) { + PyErr_SetString(PyExc_EOFError, + "read() didn't return enough bytes"); + Py_DECREF(res); + return NULL; + } - return res; + return res; } PyDoc_STRVAR(fromfile_doc, @@ -1237,35 +1237,35 @@ static PyObject * array_tofile(arrayobject *self, PyObject *f) { - Py_ssize_t nbytes = Py_SIZE(self) * self->ob_descr->itemsize; - /* Write 64K blocks at a time */ - /* XXX Make the block size settable */ - int BLOCKSIZE = 64*1024; - Py_ssize_t nblocks = (nbytes + BLOCKSIZE - 1) / BLOCKSIZE; - Py_ssize_t i; - - if (Py_SIZE(self) == 0) - goto done; - - for (i = 0; i < nblocks; i++) { - char* ptr = self->ob_item + i*BLOCKSIZE; - Py_ssize_t size = BLOCKSIZE; - PyObject *bytes, *res; - if (i*BLOCKSIZE + size > nbytes) - size = nbytes - i*BLOCKSIZE; - bytes = PyBytes_FromStringAndSize(ptr, size); - if (bytes == NULL) - return NULL; - res = PyObject_CallMethod(f, "write", "O", bytes); - Py_DECREF(bytes); - if (res == NULL) - return NULL; - Py_DECREF(res); /* drop write result */ - } + Py_ssize_t nbytes = Py_SIZE(self) * self->ob_descr->itemsize; + /* Write 64K blocks at a time */ + /* XXX Make the block size settable */ + int BLOCKSIZE = 64*1024; + Py_ssize_t nblocks = (nbytes + BLOCKSIZE - 1) / BLOCKSIZE; + Py_ssize_t i; + + if (Py_SIZE(self) == 0) + goto done; + + for (i = 0; i < nblocks; i++) { + char* ptr = self->ob_item + i*BLOCKSIZE; + Py_ssize_t size = BLOCKSIZE; + PyObject *bytes, *res; + if (i*BLOCKSIZE + size > nbytes) + size = nbytes - i*BLOCKSIZE; + bytes = PyBytes_FromStringAndSize(ptr, size); + if (bytes == NULL) + return NULL; + res = PyObject_CallMethod(f, "write", "O", bytes); + Py_DECREF(bytes); + if (res == NULL) + return NULL; + Py_DECREF(res); /* drop write result */ + } done: - Py_INCREF(Py_None); - return Py_None; + Py_INCREF(Py_None); + return Py_None; } PyDoc_STRVAR(tofile_doc, @@ -1277,29 +1277,29 @@ static PyObject * array_fromlist(arrayobject *self, PyObject *list) { - Py_ssize_t n; + Py_ssize_t n; - if (!PyList_Check(list)) { - PyErr_SetString(PyExc_TypeError, "arg must be list"); - return NULL; - } - n = PyList_Size(list); - if (n > 0) { - Py_ssize_t i, old_size; - old_size = Py_SIZE(self); - if (array_resize(self, old_size + n) == -1) - return NULL; - for (i = 0; i < n; i++) { - PyObject *v = PyList_GetItem(list, i); - if ((*self->ob_descr->setitem)(self, - Py_SIZE(self) - n + i, v) != 0) { - array_resize(self, old_size); - return NULL; - } - } - } - Py_INCREF(Py_None); - return Py_None; + if (!PyList_Check(list)) { + PyErr_SetString(PyExc_TypeError, "arg must be list"); + return NULL; + } + n = PyList_Size(list); + if (n > 0) { + Py_ssize_t i, old_size; + old_size = Py_SIZE(self); + if (array_resize(self, old_size + n) == -1) + return NULL; + for (i = 0; i < n; i++) { + PyObject *v = PyList_GetItem(list, i); + if ((*self->ob_descr->setitem)(self, + Py_SIZE(self) - n + i, v) != 0) { + array_resize(self, old_size); + return NULL; + } + } + } + Py_INCREF(Py_None); + return Py_None; } PyDoc_STRVAR(fromlist_doc, @@ -1310,20 +1310,20 @@ static PyObject * array_tolist(arrayobject *self, PyObject *unused) { - PyObject *list = PyList_New(Py_SIZE(self)); - Py_ssize_t i; + PyObject *list = PyList_New(Py_SIZE(self)); + Py_ssize_t i; - if (list == NULL) - return NULL; - for (i = 0; i < Py_SIZE(self); i++) { - PyObject *v = getarrayitem((PyObject *)self, i); - if (v == NULL) { - Py_DECREF(list); - return NULL; - } - PyList_SetItem(list, i, v); - } - return list; + if (list == NULL) + return NULL; + for (i = 0; i < Py_SIZE(self); i++) { + PyObject *v = getarrayitem((PyObject *)self, i); + if (v == NULL) { + Py_DECREF(list); + return NULL; + } + PyList_SetItem(list, i, v); + } + return list; } PyDoc_STRVAR(tolist_doc, @@ -1335,30 +1335,30 @@ static PyObject * array_fromstring(arrayobject *self, PyObject *args) { - char *str; - Py_ssize_t n; - int itemsize = self->ob_descr->itemsize; - if (!PyArg_ParseTuple(args, "s#:fromstring", &str, &n)) - return NULL; - if (n % itemsize != 0) { - PyErr_SetString(PyExc_ValueError, - "string length not a multiple of item size"); - return NULL; - } - n = n / itemsize; - if (n > 0) { - Py_ssize_t old_size = Py_SIZE(self); - if ((n > PY_SSIZE_T_MAX - old_size) || - ((old_size + n) > PY_SSIZE_T_MAX / itemsize)) { - return PyErr_NoMemory(); - } - if (array_resize(self, old_size + n) == -1) - return NULL; - memcpy(self->ob_item + old_size * itemsize, - str, n * itemsize); - } - Py_INCREF(Py_None); - return Py_None; + char *str; + Py_ssize_t n; + int itemsize = self->ob_descr->itemsize; + if (!PyArg_ParseTuple(args, "s#:fromstring", &str, &n)) + return NULL; + if (n % itemsize != 0) { + PyErr_SetString(PyExc_ValueError, + "string length not a multiple of item size"); + return NULL; + } + n = n / itemsize; + if (n > 0) { + Py_ssize_t old_size = Py_SIZE(self); + if ((n > PY_SSIZE_T_MAX - old_size) || + ((old_size + n) > PY_SSIZE_T_MAX / itemsize)) { + return PyErr_NoMemory(); + } + if (array_resize(self, old_size + n) == -1) + return NULL; + memcpy(self->ob_item + old_size * itemsize, + str, n * itemsize); + } + Py_INCREF(Py_None); + return Py_None; } PyDoc_STRVAR(fromstring_doc, @@ -1371,12 +1371,12 @@ static PyObject * array_tostring(arrayobject *self, PyObject *unused) { - if (Py_SIZE(self) <= PY_SSIZE_T_MAX / self->ob_descr->itemsize) { - return PyBytes_FromStringAndSize(self->ob_item, - Py_SIZE(self) * self->ob_descr->itemsize); - } else { - return PyErr_NoMemory(); - } + if (Py_SIZE(self) <= PY_SSIZE_T_MAX / self->ob_descr->itemsize) { + return PyBytes_FromStringAndSize(self->ob_item, + Py_SIZE(self) * self->ob_descr->itemsize); + } else { + return PyErr_NoMemory(); + } } PyDoc_STRVAR(tostring_doc, @@ -1390,29 +1390,29 @@ static PyObject * array_fromunicode(arrayobject *self, PyObject *args) { - Py_UNICODE *ustr; - Py_ssize_t n; - char typecode; - - if (!PyArg_ParseTuple(args, "u#:fromunicode", &ustr, &n)) - return NULL; - typecode = self->ob_descr->typecode; - if ((typecode != 'u')) { - PyErr_SetString(PyExc_ValueError, - "fromunicode() may only be called on " - "unicode type arrays"); - return NULL; - } - if (n > 0) { - Py_ssize_t old_size = Py_SIZE(self); - if (array_resize(self, old_size + n) == -1) - return NULL; - memcpy(self->ob_item + old_size * sizeof(Py_UNICODE), - ustr, n * sizeof(Py_UNICODE)); - } + Py_UNICODE *ustr; + Py_ssize_t n; + char typecode; + + if (!PyArg_ParseTuple(args, "u#:fromunicode", &ustr, &n)) + return NULL; + typecode = self->ob_descr->typecode; + if ((typecode != 'u')) { + PyErr_SetString(PyExc_ValueError, + "fromunicode() may only be called on " + "unicode type arrays"); + return NULL; + } + if (n > 0) { + Py_ssize_t old_size = Py_SIZE(self); + if (array_resize(self, old_size + n) == -1) + return NULL; + memcpy(self->ob_item + old_size * sizeof(Py_UNICODE), + ustr, n * sizeof(Py_UNICODE)); + } - Py_INCREF(Py_None); - return Py_None; + Py_INCREF(Py_None); + return Py_None; } PyDoc_STRVAR(fromunicode_doc, @@ -1427,14 +1427,14 @@ static PyObject * array_tounicode(arrayobject *self, PyObject *unused) { - char typecode; - typecode = self->ob_descr->typecode; - if ((typecode != 'u')) { - PyErr_SetString(PyExc_ValueError, - "tounicode() may only be called on unicode type arrays"); - return NULL; - } - return PyUnicode_FromUnicode((Py_UNICODE *) self->ob_item, Py_SIZE(self)); + char typecode; + typecode = self->ob_descr->typecode; + if ((typecode != 'u')) { + PyErr_SetString(PyExc_ValueError, + "tounicode() may only be called on unicode type arrays"); + return NULL; + } + return PyUnicode_FromUnicode((Py_UNICODE *) self->ob_item, Py_SIZE(self)); } PyDoc_STRVAR(tounicode_doc, @@ -1450,71 +1450,71 @@ /*********************** Pickling support ************************/ enum machine_format_code { - UNKNOWN_FORMAT = -1, - /* UNKNOWN_FORMAT is used to indicate that the machine format for an - * array type code cannot be interpreted. When this occurs, a list of - * Python objects is used to represent the content of the array - * instead of using the memory content of the array directly. In that - * case, the array_reconstructor mechanism is bypassed completely, and - * the standard array constructor is used instead. - * - * This is will most likely occur when the machine doesn't use IEEE - * floating-point numbers. - */ - - UNSIGNED_INT8 = 0, - SIGNED_INT8 = 1, - UNSIGNED_INT16_LE = 2, - UNSIGNED_INT16_BE = 3, - SIGNED_INT16_LE = 4, - SIGNED_INT16_BE = 5, - UNSIGNED_INT32_LE = 6, - UNSIGNED_INT32_BE = 7, - SIGNED_INT32_LE = 8, - SIGNED_INT32_BE = 9, - UNSIGNED_INT64_LE = 10, - UNSIGNED_INT64_BE = 11, - SIGNED_INT64_LE = 12, - SIGNED_INT64_BE = 13, - IEEE_754_FLOAT_LE = 14, - IEEE_754_FLOAT_BE = 15, - IEEE_754_DOUBLE_LE = 16, - IEEE_754_DOUBLE_BE = 17, - UTF16_LE = 18, - UTF16_BE = 19, - UTF32_LE = 20, - UTF32_BE = 21 + UNKNOWN_FORMAT = -1, + /* UNKNOWN_FORMAT is used to indicate that the machine format for an + * array type code cannot be interpreted. When this occurs, a list of + * Python objects is used to represent the content of the array + * instead of using the memory content of the array directly. In that + * case, the array_reconstructor mechanism is bypassed completely, and + * the standard array constructor is used instead. + * + * This is will most likely occur when the machine doesn't use IEEE + * floating-point numbers. + */ + + UNSIGNED_INT8 = 0, + SIGNED_INT8 = 1, + UNSIGNED_INT16_LE = 2, + UNSIGNED_INT16_BE = 3, + SIGNED_INT16_LE = 4, + SIGNED_INT16_BE = 5, + UNSIGNED_INT32_LE = 6, + UNSIGNED_INT32_BE = 7, + SIGNED_INT32_LE = 8, + SIGNED_INT32_BE = 9, + UNSIGNED_INT64_LE = 10, + UNSIGNED_INT64_BE = 11, + SIGNED_INT64_LE = 12, + SIGNED_INT64_BE = 13, + IEEE_754_FLOAT_LE = 14, + IEEE_754_FLOAT_BE = 15, + IEEE_754_DOUBLE_LE = 16, + IEEE_754_DOUBLE_BE = 17, + UTF16_LE = 18, + UTF16_BE = 19, + UTF32_LE = 20, + UTF32_BE = 21 }; #define MACHINE_FORMAT_CODE_MIN 0 #define MACHINE_FORMAT_CODE_MAX 21 static const struct mformatdescr { - size_t size; - int is_signed; - int is_big_endian; + size_t size; + int is_signed; + int is_big_endian; } mformat_descriptors[] = { - {1, 0, 0}, /* 0: UNSIGNED_INT8 */ - {1, 1, 0}, /* 1: SIGNED_INT8 */ - {2, 0, 0}, /* 2: UNSIGNED_INT16_LE */ - {2, 0, 1}, /* 3: UNSIGNED_INT16_BE */ - {2, 1, 0}, /* 4: SIGNED_INT16_LE */ - {2, 1, 1}, /* 5: SIGNED_INT16_BE */ - {4, 0, 0}, /* 6: UNSIGNED_INT32_LE */ - {4, 0, 1}, /* 7: UNSIGNED_INT32_BE */ - {4, 1, 0}, /* 8: SIGNED_INT32_LE */ - {4, 1, 1}, /* 9: SIGNED_INT32_BE */ - {8, 0, 0}, /* 10: UNSIGNED_INT64_LE */ - {8, 0, 1}, /* 11: UNSIGNED_INT64_BE */ - {8, 1, 0}, /* 12: SIGNED_INT64_LE */ - {8, 1, 1}, /* 13: SIGNED_INT64_BE */ - {4, 0, 0}, /* 14: IEEE_754_FLOAT_LE */ - {4, 0, 1}, /* 15: IEEE_754_FLOAT_BE */ - {8, 0, 0}, /* 16: IEEE_754_DOUBLE_LE */ - {8, 0, 1}, /* 17: IEEE_754_DOUBLE_BE */ - {4, 0, 0}, /* 18: UTF16_LE */ - {4, 0, 1}, /* 19: UTF16_BE */ - {8, 0, 0}, /* 20: UTF32_LE */ - {8, 0, 1} /* 21: UTF32_BE */ + {1, 0, 0}, /* 0: UNSIGNED_INT8 */ + {1, 1, 0}, /* 1: SIGNED_INT8 */ + {2, 0, 0}, /* 2: UNSIGNED_INT16_LE */ + {2, 0, 1}, /* 3: UNSIGNED_INT16_BE */ + {2, 1, 0}, /* 4: SIGNED_INT16_LE */ + {2, 1, 1}, /* 5: SIGNED_INT16_BE */ + {4, 0, 0}, /* 6: UNSIGNED_INT32_LE */ + {4, 0, 1}, /* 7: UNSIGNED_INT32_BE */ + {4, 1, 0}, /* 8: SIGNED_INT32_LE */ + {4, 1, 1}, /* 9: SIGNED_INT32_BE */ + {8, 0, 0}, /* 10: UNSIGNED_INT64_LE */ + {8, 0, 1}, /* 11: UNSIGNED_INT64_BE */ + {8, 1, 0}, /* 12: SIGNED_INT64_LE */ + {8, 1, 1}, /* 13: SIGNED_INT64_BE */ + {4, 0, 0}, /* 14: IEEE_754_FLOAT_LE */ + {4, 0, 1}, /* 15: IEEE_754_FLOAT_BE */ + {8, 0, 0}, /* 16: IEEE_754_DOUBLE_LE */ + {8, 0, 1}, /* 17: IEEE_754_DOUBLE_BE */ + {4, 0, 0}, /* 18: UTF16_LE */ + {4, 0, 1}, /* 19: UTF16_BE */ + {8, 0, 0}, /* 20: UTF32_LE */ + {8, 0, 1} /* 21: UTF32_BE */ }; @@ -1527,86 +1527,86 @@ typecode_to_mformat_code(int typecode) { #ifdef WORDS_BIGENDIAN - const int is_big_endian = 1; + const int is_big_endian = 1; #else - const int is_big_endian = 0; + const int is_big_endian = 0; #endif - size_t intsize; - int is_signed; + size_t intsize; + int is_signed; + + switch (typecode) { + case 'b': + return SIGNED_INT8; + case 'B': + return UNSIGNED_INT8; + + case 'u': + if (sizeof(Py_UNICODE) == 2) { + return UTF16_LE + is_big_endian; + } + if (sizeof(Py_UNICODE) == 4) { + return UTF32_LE + is_big_endian; + } + return UNKNOWN_FORMAT; + + case 'f': + if (sizeof(float) == 4) { + const float y = 16711938.0; + if (memcmp(&y, "\x4b\x7f\x01\x02", 4) == 0) + return IEEE_754_FLOAT_BE; + if (memcmp(&y, "\x02\x01\x7f\x4b", 4) == 0) + return IEEE_754_FLOAT_LE; + } + return UNKNOWN_FORMAT; - switch (typecode) { - case 'b': - return SIGNED_INT8; - case 'B': - return UNSIGNED_INT8; - - case 'u': - if (sizeof(Py_UNICODE) == 2) { - return UTF16_LE + is_big_endian; - } - if (sizeof(Py_UNICODE) == 4) { - return UTF32_LE + is_big_endian; - } - return UNKNOWN_FORMAT; - - case 'f': - if (sizeof(float) == 4) { - const float y = 16711938.0; - if (memcmp(&y, "\x4b\x7f\x01\x02", 4) == 0) - return IEEE_754_FLOAT_BE; - if (memcmp(&y, "\x02\x01\x7f\x4b", 4) == 0) - return IEEE_754_FLOAT_LE; - } - return UNKNOWN_FORMAT; - - case 'd': - if (sizeof(double) == 8) { - const double x = 9006104071832581.0; - if (memcmp(&x, "\x43\x3f\xff\x01\x02\x03\x04\x05", 8) == 0) - return IEEE_754_DOUBLE_BE; - if (memcmp(&x, "\x05\x04\x03\x02\x01\xff\x3f\x43", 8) == 0) - return IEEE_754_DOUBLE_LE; - } - return UNKNOWN_FORMAT; - - /* Integers */ - case 'h': - intsize = sizeof(short); - is_signed = 1; - break; - case 'H': - intsize = sizeof(short); - is_signed = 0; - break; - case 'i': - intsize = sizeof(int); - is_signed = 1; - break; - case 'I': - intsize = sizeof(int); - is_signed = 0; - break; - case 'l': - intsize = sizeof(long); - is_signed = 1; - break; - case 'L': - intsize = sizeof(long); - is_signed = 0; - break; - default: - return UNKNOWN_FORMAT; - } - switch (intsize) { - case 2: - return UNSIGNED_INT16_LE + is_big_endian + (2 * is_signed); - case 4: - return UNSIGNED_INT32_LE + is_big_endian + (2 * is_signed); - case 8: - return UNSIGNED_INT64_LE + is_big_endian + (2 * is_signed); - default: - return UNKNOWN_FORMAT; - } + case 'd': + if (sizeof(double) == 8) { + const double x = 9006104071832581.0; + if (memcmp(&x, "\x43\x3f\xff\x01\x02\x03\x04\x05", 8) == 0) + return IEEE_754_DOUBLE_BE; + if (memcmp(&x, "\x05\x04\x03\x02\x01\xff\x3f\x43", 8) == 0) + return IEEE_754_DOUBLE_LE; + } + return UNKNOWN_FORMAT; + + /* Integers */ + case 'h': + intsize = sizeof(short); + is_signed = 1; + break; + case 'H': + intsize = sizeof(short); + is_signed = 0; + break; + case 'i': + intsize = sizeof(int); + is_signed = 1; + break; + case 'I': + intsize = sizeof(int); + is_signed = 0; + break; + case 'l': + intsize = sizeof(long); + is_signed = 1; + break; + case 'L': + intsize = sizeof(long); + is_signed = 0; + break; + default: + return UNKNOWN_FORMAT; + } + switch (intsize) { + case 2: + return UNSIGNED_INT16_LE + is_big_endian + (2 * is_signed); + case 4: + return UNSIGNED_INT32_LE + is_big_endian + (2 * is_signed); + case 8: + return UNSIGNED_INT64_LE + is_big_endian + (2 * is_signed); + default: + return UNKNOWN_FORMAT; + } } /* Forward declaration. */ @@ -1619,38 +1619,38 @@ * Unicode character value, like 'i' or 'f' for example, representing an array * type code. The items argument is a bytes or a list object from which * contains the initial value of the array. - * + * * On success, this functions returns the array object created. Otherwise, * NULL is returned to indicate a failure. */ static PyObject * make_array(PyTypeObject *arraytype, int typecode, PyObject *items) { - PyObject *new_args; - PyObject *array_obj; - PyObject *typecode_obj; - Py_UNICODE typecode_str[1] = {typecode}; - - assert(arraytype != NULL); - assert(items != NULL); - - typecode_obj = PyUnicode_FromUnicode(typecode_str, 1); - if (typecode_obj == NULL) - return NULL; - - new_args = PyTuple_New(2); - if (new_args == NULL) - return NULL; - Py_INCREF(items); - PyTuple_SET_ITEM(new_args, 0, typecode_obj); - PyTuple_SET_ITEM(new_args, 1, items); - - array_obj = array_new(arraytype, new_args, NULL); - Py_DECREF(new_args); - if (array_obj == NULL) - return NULL; + PyObject *new_args; + PyObject *array_obj; + PyObject *typecode_obj; + Py_UNICODE typecode_str[1] = {typecode}; + + assert(arraytype != NULL); + assert(items != NULL); + + typecode_obj = PyUnicode_FromUnicode(typecode_str, 1); + if (typecode_obj == NULL) + return NULL; + + new_args = PyTuple_New(2); + if (new_args == NULL) + return NULL; + Py_INCREF(items); + PyTuple_SET_ITEM(new_args, 0, typecode_obj); + PyTuple_SET_ITEM(new_args, 1, items); + + array_obj = array_new(arraytype, new_args, NULL); + Py_DECREF(new_args); + if (array_obj == NULL) + return NULL; - return array_obj; + return array_obj; } /* @@ -1660,283 +1660,283 @@ static PyObject * array_reconstructor(PyObject *self, PyObject *args) { - PyTypeObject *arraytype; - PyObject *items; - PyObject *converted_items; - PyObject *result; - int typecode; - enum machine_format_code mformat_code; - struct arraydescr *descr; - - if (!PyArg_ParseTuple(args, "OCiO:array._array_reconstructor", - &arraytype, &typecode, &mformat_code, &items)) - return NULL; - - if (!PyType_Check(arraytype)) { - PyErr_Format(PyExc_TypeError, - "first argument must a type object, not %.200s", - Py_TYPE(arraytype)->tp_name); - return NULL; - } - if (!PyType_IsSubtype(arraytype, &Arraytype)) { - PyErr_Format(PyExc_TypeError, - "%.200s is not a subtype of %.200s", - arraytype->tp_name, Arraytype.tp_name); - return NULL; - } - for (descr = descriptors; descr->typecode != '\0'; descr++) { - if (descr->typecode == typecode) - break; - } - if (descr->typecode == '\0') { - PyErr_SetString(PyExc_ValueError, - "second argument must be a valid type code"); - return NULL; - } - if (mformat_code < MACHINE_FORMAT_CODE_MIN || - mformat_code > MACHINE_FORMAT_CODE_MAX) { - PyErr_SetString(PyExc_ValueError, - "third argument must be a valid machine format code."); - return NULL; - } - if (!PyBytes_Check(items)) { - PyErr_Format(PyExc_TypeError, - "fourth argument should be bytes, not %.200s", - Py_TYPE(items)->tp_name); - return NULL; - } - - /* Fast path: No decoding has to be done. */ - if (mformat_code == typecode_to_mformat_code(typecode) || - mformat_code == UNKNOWN_FORMAT) { - return make_array(arraytype, typecode, items); - } - - /* Slow path: Decode the byte string according to the given machine - * format code. This occurs when the computer unpickling the array - * object is architecturally different from the one that pickled the - * array. - */ - if (Py_SIZE(items) % mformat_descriptors[mformat_code].size != 0) { - PyErr_SetString(PyExc_ValueError, - "string length not a multiple of item size"); - return NULL; - } - switch (mformat_code) { - case IEEE_754_FLOAT_LE: - case IEEE_754_FLOAT_BE: { - int i; - int le = (mformat_code == IEEE_754_FLOAT_LE) ? 1 : 0; - Py_ssize_t itemcount = Py_SIZE(items) / 4; - const unsigned char *memstr = - (unsigned char *)PyBytes_AS_STRING(items); - - converted_items = PyList_New(itemcount); - if (converted_items == NULL) - return NULL; - for (i = 0; i < itemcount; i++) { - PyObject *pyfloat = PyFloat_FromDouble( - _PyFloat_Unpack4(&memstr[i * 4], le)); - if (pyfloat == NULL) { - Py_DECREF(converted_items); - return NULL; - } - PyList_SET_ITEM(converted_items, i, pyfloat); - } - break; - } - case IEEE_754_DOUBLE_LE: - case IEEE_754_DOUBLE_BE: { - int i; - int le = (mformat_code == IEEE_754_DOUBLE_LE) ? 1 : 0; - Py_ssize_t itemcount = Py_SIZE(items) / 8; - const unsigned char *memstr = - (unsigned char *)PyBytes_AS_STRING(items); - - converted_items = PyList_New(itemcount); - if (converted_items == NULL) - return NULL; - for (i = 0; i < itemcount; i++) { - PyObject *pyfloat = PyFloat_FromDouble( - _PyFloat_Unpack8(&memstr[i * 8], le)); - if (pyfloat == NULL) { - Py_DECREF(converted_items); - return NULL; - } - PyList_SET_ITEM(converted_items, i, pyfloat); - } - break; - } - case UTF16_LE: - case UTF16_BE: { - int byteorder = (mformat_code == UTF16_LE) ? -1 : 1; - converted_items = PyUnicode_DecodeUTF16( - PyBytes_AS_STRING(items), Py_SIZE(items), - "strict", &byteorder); - if (converted_items == NULL) - return NULL; - break; - } - case UTF32_LE: - case UTF32_BE: { - int byteorder = (mformat_code == UTF32_LE) ? -1 : 1; - converted_items = PyUnicode_DecodeUTF32( - PyBytes_AS_STRING(items), Py_SIZE(items), - "strict", &byteorder); - if (converted_items == NULL) - return NULL; - break; - } - - case UNSIGNED_INT8: - case SIGNED_INT8: - case UNSIGNED_INT16_LE: - case UNSIGNED_INT16_BE: - case SIGNED_INT16_LE: - case SIGNED_INT16_BE: - case UNSIGNED_INT32_LE: - case UNSIGNED_INT32_BE: - case SIGNED_INT32_LE: - case SIGNED_INT32_BE: - case UNSIGNED_INT64_LE: - case UNSIGNED_INT64_BE: - case SIGNED_INT64_LE: - case SIGNED_INT64_BE: { - int i; - const struct mformatdescr mf_descr = - mformat_descriptors[mformat_code]; - Py_ssize_t itemcount = Py_SIZE(items) / mf_descr.size; - const unsigned char *memstr = - (unsigned char *)PyBytes_AS_STRING(items); - struct arraydescr *descr; - - /* If possible, try to pack array's items using a data type - * that fits better. This may result in an array with narrower - * or wider elements. - * - * For example, if a 32-bit machine pickles a L-code array of - * unsigned longs, then the array will be unpickled by 64-bit - * machine as an I-code array of unsigned ints. - * - * XXX: Is it possible to write a unit test for this? - */ - for (descr = descriptors; descr->typecode != '\0'; descr++) { - if (descr->is_integer_type && - descr->itemsize == mf_descr.size && - descr->is_signed == mf_descr.is_signed) - typecode = descr->typecode; - } - - converted_items = PyList_New(itemcount); - if (converted_items == NULL) - return NULL; - for (i = 0; i < itemcount; i++) { - PyObject *pylong; - - pylong = _PyLong_FromByteArray( - &memstr[i * mf_descr.size], - mf_descr.size, - !mf_descr.is_big_endian, - mf_descr.is_signed); - if (pylong == NULL) { - Py_DECREF(converted_items); - return NULL; - } - PyList_SET_ITEM(converted_items, i, pylong); - } - break; - } - case UNKNOWN_FORMAT: - /* Impossible, but needed to shut up GCC about the unhandled - * enumeration value. - */ - default: - PyErr_BadArgument(); - return NULL; - } - - result = make_array(arraytype, typecode, converted_items); - Py_DECREF(converted_items); - return result; + PyTypeObject *arraytype; + PyObject *items; + PyObject *converted_items; + PyObject *result; + int typecode; + enum machine_format_code mformat_code; + struct arraydescr *descr; + + if (!PyArg_ParseTuple(args, "OCiO:array._array_reconstructor", + &arraytype, &typecode, &mformat_code, &items)) + return NULL; + + if (!PyType_Check(arraytype)) { + PyErr_Format(PyExc_TypeError, + "first argument must a type object, not %.200s", + Py_TYPE(arraytype)->tp_name); + return NULL; + } + if (!PyType_IsSubtype(arraytype, &Arraytype)) { + PyErr_Format(PyExc_TypeError, + "%.200s is not a subtype of %.200s", + arraytype->tp_name, Arraytype.tp_name); + return NULL; + } + for (descr = descriptors; descr->typecode != '\0'; descr++) { + if (descr->typecode == typecode) + break; + } + if (descr->typecode == '\0') { + PyErr_SetString(PyExc_ValueError, + "second argument must be a valid type code"); + return NULL; + } + if (mformat_code < MACHINE_FORMAT_CODE_MIN || + mformat_code > MACHINE_FORMAT_CODE_MAX) { + PyErr_SetString(PyExc_ValueError, + "third argument must be a valid machine format code."); + return NULL; + } + if (!PyBytes_Check(items)) { + PyErr_Format(PyExc_TypeError, + "fourth argument should be bytes, not %.200s", + Py_TYPE(items)->tp_name); + return NULL; + } + + /* Fast path: No decoding has to be done. */ + if (mformat_code == typecode_to_mformat_code(typecode) || + mformat_code == UNKNOWN_FORMAT) { + return make_array(arraytype, typecode, items); + } + + /* Slow path: Decode the byte string according to the given machine + * format code. This occurs when the computer unpickling the array + * object is architecturally different from the one that pickled the + * array. + */ + if (Py_SIZE(items) % mformat_descriptors[mformat_code].size != 0) { + PyErr_SetString(PyExc_ValueError, + "string length not a multiple of item size"); + return NULL; + } + switch (mformat_code) { + case IEEE_754_FLOAT_LE: + case IEEE_754_FLOAT_BE: { + int i; + int le = (mformat_code == IEEE_754_FLOAT_LE) ? 1 : 0; + Py_ssize_t itemcount = Py_SIZE(items) / 4; + const unsigned char *memstr = + (unsigned char *)PyBytes_AS_STRING(items); + + converted_items = PyList_New(itemcount); + if (converted_items == NULL) + return NULL; + for (i = 0; i < itemcount; i++) { + PyObject *pyfloat = PyFloat_FromDouble( + _PyFloat_Unpack4(&memstr[i * 4], le)); + if (pyfloat == NULL) { + Py_DECREF(converted_items); + return NULL; + } + PyList_SET_ITEM(converted_items, i, pyfloat); + } + break; + } + case IEEE_754_DOUBLE_LE: + case IEEE_754_DOUBLE_BE: { + int i; + int le = (mformat_code == IEEE_754_DOUBLE_LE) ? 1 : 0; + Py_ssize_t itemcount = Py_SIZE(items) / 8; + const unsigned char *memstr = + (unsigned char *)PyBytes_AS_STRING(items); + + converted_items = PyList_New(itemcount); + if (converted_items == NULL) + return NULL; + for (i = 0; i < itemcount; i++) { + PyObject *pyfloat = PyFloat_FromDouble( + _PyFloat_Unpack8(&memstr[i * 8], le)); + if (pyfloat == NULL) { + Py_DECREF(converted_items); + return NULL; + } + PyList_SET_ITEM(converted_items, i, pyfloat); + } + break; + } + case UTF16_LE: + case UTF16_BE: { + int byteorder = (mformat_code == UTF16_LE) ? -1 : 1; + converted_items = PyUnicode_DecodeUTF16( + PyBytes_AS_STRING(items), Py_SIZE(items), + "strict", &byteorder); + if (converted_items == NULL) + return NULL; + break; + } + case UTF32_LE: + case UTF32_BE: { + int byteorder = (mformat_code == UTF32_LE) ? -1 : 1; + converted_items = PyUnicode_DecodeUTF32( + PyBytes_AS_STRING(items), Py_SIZE(items), + "strict", &byteorder); + if (converted_items == NULL) + return NULL; + break; + } + + case UNSIGNED_INT8: + case SIGNED_INT8: + case UNSIGNED_INT16_LE: + case UNSIGNED_INT16_BE: + case SIGNED_INT16_LE: + case SIGNED_INT16_BE: + case UNSIGNED_INT32_LE: + case UNSIGNED_INT32_BE: + case SIGNED_INT32_LE: + case SIGNED_INT32_BE: + case UNSIGNED_INT64_LE: + case UNSIGNED_INT64_BE: + case SIGNED_INT64_LE: + case SIGNED_INT64_BE: { + int i; + const struct mformatdescr mf_descr = + mformat_descriptors[mformat_code]; + Py_ssize_t itemcount = Py_SIZE(items) / mf_descr.size; + const unsigned char *memstr = + (unsigned char *)PyBytes_AS_STRING(items); + struct arraydescr *descr; + + /* If possible, try to pack array's items using a data type + * that fits better. This may result in an array with narrower + * or wider elements. + * + * For example, if a 32-bit machine pickles a L-code array of + * unsigned longs, then the array will be unpickled by 64-bit + * machine as an I-code array of unsigned ints. + * + * XXX: Is it possible to write a unit test for this? + */ + for (descr = descriptors; descr->typecode != '\0'; descr++) { + if (descr->is_integer_type && + descr->itemsize == mf_descr.size && + descr->is_signed == mf_descr.is_signed) + typecode = descr->typecode; + } + + converted_items = PyList_New(itemcount); + if (converted_items == NULL) + return NULL; + for (i = 0; i < itemcount; i++) { + PyObject *pylong; + + pylong = _PyLong_FromByteArray( + &memstr[i * mf_descr.size], + mf_descr.size, + !mf_descr.is_big_endian, + mf_descr.is_signed); + if (pylong == NULL) { + Py_DECREF(converted_items); + return NULL; + } + PyList_SET_ITEM(converted_items, i, pylong); + } + break; + } + case UNKNOWN_FORMAT: + /* Impossible, but needed to shut up GCC about the unhandled + * enumeration value. + */ + default: + PyErr_BadArgument(); + return NULL; + } + + result = make_array(arraytype, typecode, converted_items); + Py_DECREF(converted_items); + return result; } static PyObject * array_reduce_ex(arrayobject *array, PyObject *value) { - PyObject *dict; - PyObject *result; - PyObject *array_str; - int typecode = array->ob_descr->typecode; - int mformat_code; - static PyObject *array_reconstructor = NULL; - long protocol; - - if (array_reconstructor == NULL) { - PyObject *array_module = PyImport_ImportModule("array"); - if (array_module == NULL) - return NULL; - array_reconstructor = PyObject_GetAttrString( - array_module, - "_array_reconstructor"); - Py_DECREF(array_module); - if (array_reconstructor == NULL) - return NULL; - } - - if (!PyLong_Check(value)) { - PyErr_SetString(PyExc_TypeError, - "__reduce_ex__ argument should an integer"); - return NULL; - } - protocol = PyLong_AsLong(value); - if (protocol == -1 && PyErr_Occurred()) - return NULL; - - dict = PyObject_GetAttrString((PyObject *)array, "__dict__"); - if (dict == NULL) { - if (!PyErr_ExceptionMatches(PyExc_AttributeError)) - return NULL; - PyErr_Clear(); - dict = Py_None; - Py_INCREF(dict); - } - - mformat_code = typecode_to_mformat_code(typecode); - if (mformat_code == UNKNOWN_FORMAT || protocol < 3) { - /* Convert the array to a list if we got something weird - * (e.g., non-IEEE floats), or we are pickling the array using - * a Python 2.x compatible protocol. - * - * It is necessary to use a list representation for Python 2.x - * compatible pickle protocol, since Python 2's str objects - * are unpickled as unicode by Python 3. Thus it is impossible - * to make arrays unpicklable by Python 3 by using their memory - * representation, unless we resort to ugly hacks such as - * coercing unicode objects to bytes in array_reconstructor. - */ - PyObject *list; - list = array_tolist(array, NULL); - if (list == NULL) { - Py_DECREF(dict); - return NULL; - } - result = Py_BuildValue( - "O(CO)O", Py_TYPE(array), typecode, list, dict); - Py_DECREF(list); - Py_DECREF(dict); - return result; - } - - array_str = array_tostring(array, NULL); - if (array_str == NULL) { - Py_DECREF(dict); - return NULL; - } - result = Py_BuildValue( - "O(OCiN)O", array_reconstructor, Py_TYPE(array), typecode, - mformat_code, array_str, dict); - Py_DECREF(dict); - return result; + PyObject *dict; + PyObject *result; + PyObject *array_str; + int typecode = array->ob_descr->typecode; + int mformat_code; + static PyObject *array_reconstructor = NULL; + long protocol; + + if (array_reconstructor == NULL) { + PyObject *array_module = PyImport_ImportModule("array"); + if (array_module == NULL) + return NULL; + array_reconstructor = PyObject_GetAttrString( + array_module, + "_array_reconstructor"); + Py_DECREF(array_module); + if (array_reconstructor == NULL) + return NULL; + } + + if (!PyLong_Check(value)) { + PyErr_SetString(PyExc_TypeError, + "__reduce_ex__ argument should an integer"); + return NULL; + } + protocol = PyLong_AsLong(value); + if (protocol == -1 && PyErr_Occurred()) + return NULL; + + dict = PyObject_GetAttrString((PyObject *)array, "__dict__"); + if (dict == NULL) { + if (!PyErr_ExceptionMatches(PyExc_AttributeError)) + return NULL; + PyErr_Clear(); + dict = Py_None; + Py_INCREF(dict); + } + + mformat_code = typecode_to_mformat_code(typecode); + if (mformat_code == UNKNOWN_FORMAT || protocol < 3) { + /* Convert the array to a list if we got something weird + * (e.g., non-IEEE floats), or we are pickling the array using + * a Python 2.x compatible protocol. + * + * It is necessary to use a list representation for Python 2.x + * compatible pickle protocol, since Python 2's str objects + * are unpickled as unicode by Python 3. Thus it is impossible + * to make arrays unpicklable by Python 3 by using their memory + * representation, unless we resort to ugly hacks such as + * coercing unicode objects to bytes in array_reconstructor. + */ + PyObject *list; + list = array_tolist(array, NULL); + if (list == NULL) { + Py_DECREF(dict); + return NULL; + } + result = Py_BuildValue( + "O(CO)O", Py_TYPE(array), typecode, list, dict); + Py_DECREF(list); + Py_DECREF(dict); + return result; + } + + array_str = array_tostring(array, NULL); + if (array_str == NULL) { + Py_DECREF(dict); + return NULL; + } + result = Py_BuildValue( + "O(OCiN)O", array_reconstructor, Py_TYPE(array), typecode, + mformat_code, array_str, dict); + Py_DECREF(dict); + return result; } PyDoc_STRVAR(reduce_doc, "Return state information for pickling."); @@ -1944,313 +1944,313 @@ static PyObject * array_get_typecode(arrayobject *a, void *closure) { - char tc = a->ob_descr->typecode; - return PyUnicode_FromStringAndSize(&tc, 1); + char tc = a->ob_descr->typecode; + return PyUnicode_FromStringAndSize(&tc, 1); } static PyObject * array_get_itemsize(arrayobject *a, void *closure) { - return PyLong_FromLong((long)a->ob_descr->itemsize); + return PyLong_FromLong((long)a->ob_descr->itemsize); } static PyGetSetDef array_getsets [] = { - {"typecode", (getter) array_get_typecode, NULL, - "the typecode character used to create the array"}, - {"itemsize", (getter) array_get_itemsize, NULL, - "the size, in bytes, of one array item"}, - {NULL} + {"typecode", (getter) array_get_typecode, NULL, + "the typecode character used to create the array"}, + {"itemsize", (getter) array_get_itemsize, NULL, + "the size, in bytes, of one array item"}, + {NULL} }; static PyMethodDef array_methods[] = { - {"append", (PyCFunction)array_append, METH_O, - append_doc}, - {"buffer_info", (PyCFunction)array_buffer_info, METH_NOARGS, - buffer_info_doc}, - {"byteswap", (PyCFunction)array_byteswap, METH_NOARGS, - byteswap_doc}, - {"__copy__", (PyCFunction)array_copy, METH_NOARGS, - copy_doc}, - {"count", (PyCFunction)array_count, METH_O, - count_doc}, - {"__deepcopy__",(PyCFunction)array_copy, METH_O, - copy_doc}, - {"extend", (PyCFunction)array_extend, METH_O, - extend_doc}, - {"fromfile", (PyCFunction)array_fromfile, METH_VARARGS, - fromfile_doc}, - {"fromlist", (PyCFunction)array_fromlist, METH_O, - fromlist_doc}, - {"fromstring", (PyCFunction)array_fromstring, METH_VARARGS, - fromstring_doc}, - {"fromunicode", (PyCFunction)array_fromunicode, METH_VARARGS, - fromunicode_doc}, - {"index", (PyCFunction)array_index, METH_O, - index_doc}, - {"insert", (PyCFunction)array_insert, METH_VARARGS, - insert_doc}, - {"pop", (PyCFunction)array_pop, METH_VARARGS, - pop_doc}, - {"__reduce_ex__", (PyCFunction)array_reduce_ex, METH_O, - reduce_doc}, - {"remove", (PyCFunction)array_remove, METH_O, - remove_doc}, - {"reverse", (PyCFunction)array_reverse, METH_NOARGS, - reverse_doc}, -/* {"sort", (PyCFunction)array_sort, METH_VARARGS, - sort_doc},*/ - {"tofile", (PyCFunction)array_tofile, METH_O, - tofile_doc}, - {"tolist", (PyCFunction)array_tolist, METH_NOARGS, - tolist_doc}, - {"tostring", (PyCFunction)array_tostring, METH_NOARGS, - tostring_doc}, - {"tounicode", (PyCFunction)array_tounicode, METH_NOARGS, - tounicode_doc}, - {NULL, NULL} /* sentinel */ + {"append", (PyCFunction)array_append, METH_O, + append_doc}, + {"buffer_info", (PyCFunction)array_buffer_info, METH_NOARGS, + buffer_info_doc}, + {"byteswap", (PyCFunction)array_byteswap, METH_NOARGS, + byteswap_doc}, + {"__copy__", (PyCFunction)array_copy, METH_NOARGS, + copy_doc}, + {"count", (PyCFunction)array_count, METH_O, + count_doc}, + {"__deepcopy__",(PyCFunction)array_copy, METH_O, + copy_doc}, + {"extend", (PyCFunction)array_extend, METH_O, + extend_doc}, + {"fromfile", (PyCFunction)array_fromfile, METH_VARARGS, + fromfile_doc}, + {"fromlist", (PyCFunction)array_fromlist, METH_O, + fromlist_doc}, + {"fromstring", (PyCFunction)array_fromstring, METH_VARARGS, + fromstring_doc}, + {"fromunicode", (PyCFunction)array_fromunicode, METH_VARARGS, + fromunicode_doc}, + {"index", (PyCFunction)array_index, METH_O, + index_doc}, + {"insert", (PyCFunction)array_insert, METH_VARARGS, + insert_doc}, + {"pop", (PyCFunction)array_pop, METH_VARARGS, + pop_doc}, + {"__reduce_ex__", (PyCFunction)array_reduce_ex, METH_O, + reduce_doc}, + {"remove", (PyCFunction)array_remove, METH_O, + remove_doc}, + {"reverse", (PyCFunction)array_reverse, METH_NOARGS, + reverse_doc}, +/* {"sort", (PyCFunction)array_sort, METH_VARARGS, + sort_doc},*/ + {"tofile", (PyCFunction)array_tofile, METH_O, + tofile_doc}, + {"tolist", (PyCFunction)array_tolist, METH_NOARGS, + tolist_doc}, + {"tostring", (PyCFunction)array_tostring, METH_NOARGS, + tostring_doc}, + {"tounicode", (PyCFunction)array_tounicode, METH_NOARGS, + tounicode_doc}, + {NULL, NULL} /* sentinel */ }; static PyObject * array_repr(arrayobject *a) { - char typecode; - PyObject *s, *v = NULL; - Py_ssize_t len; - - len = Py_SIZE(a); - typecode = a->ob_descr->typecode; - if (len == 0) { - return PyUnicode_FromFormat("array('%c')", typecode); - } - if ((typecode == 'u')) - v = array_tounicode(a, NULL); - else - v = array_tolist(a, NULL); - - s = PyUnicode_FromFormat("array('%c', %R)", typecode, v); - Py_DECREF(v); - return s; + char typecode; + PyObject *s, *v = NULL; + Py_ssize_t len; + + len = Py_SIZE(a); + typecode = a->ob_descr->typecode; + if (len == 0) { + return PyUnicode_FromFormat("array('%c')", typecode); + } + if ((typecode == 'u')) + v = array_tounicode(a, NULL); + else + v = array_tolist(a, NULL); + + s = PyUnicode_FromFormat("array('%c', %R)", typecode, v); + Py_DECREF(v); + return s; } static PyObject* array_subscr(arrayobject* 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 += Py_SIZE(self); - return array_item(self, i); - } - else if (PySlice_Check(item)) { - Py_ssize_t start, stop, step, slicelength, cur, i; - PyObject* result; - arrayobject* ar; - int itemsize = self->ob_descr->itemsize; - - if (PySlice_GetIndicesEx((PySliceObject*)item, Py_SIZE(self), - &start, &stop, &step, &slicelength) < 0) { - return NULL; - } - - if (slicelength <= 0) { - return newarrayobject(&Arraytype, 0, self->ob_descr); - } - else if (step == 1) { - PyObject *result = newarrayobject(&Arraytype, - slicelength, self->ob_descr); - if (result == NULL) - return NULL; - memcpy(((arrayobject *)result)->ob_item, - self->ob_item + start * itemsize, - slicelength * itemsize); - return result; - } - else { - result = newarrayobject(&Arraytype, slicelength, self->ob_descr); - if (!result) return NULL; - - ar = (arrayobject*)result; - - for (cur = start, i = 0; i < slicelength; - cur += step, i++) { - memcpy(ar->ob_item + i*itemsize, - self->ob_item + cur*itemsize, - itemsize); - } - - return result; - } - } - else { - PyErr_SetString(PyExc_TypeError, - "array indices must be integers"); - return NULL; - } + 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 += Py_SIZE(self); + return array_item(self, i); + } + else if (PySlice_Check(item)) { + Py_ssize_t start, stop, step, slicelength, cur, i; + PyObject* result; + arrayobject* ar; + int itemsize = self->ob_descr->itemsize; + + if (PySlice_GetIndicesEx((PySliceObject*)item, Py_SIZE(self), + &start, &stop, &step, &slicelength) < 0) { + return NULL; + } + + if (slicelength <= 0) { + return newarrayobject(&Arraytype, 0, self->ob_descr); + } + else if (step == 1) { + PyObject *result = newarrayobject(&Arraytype, + slicelength, self->ob_descr); + if (result == NULL) + return NULL; + memcpy(((arrayobject *)result)->ob_item, + self->ob_item + start * itemsize, + slicelength * itemsize); + return result; + } + else { + result = newarrayobject(&Arraytype, slicelength, self->ob_descr); + if (!result) return NULL; + + ar = (arrayobject*)result; + + for (cur = start, i = 0; i < slicelength; + cur += step, i++) { + memcpy(ar->ob_item + i*itemsize, + self->ob_item + cur*itemsize, + itemsize); + } + + return result; + } + } + else { + PyErr_SetString(PyExc_TypeError, + "array indices must be integers"); + return NULL; + } } static int array_ass_subscr(arrayobject* self, PyObject* item, PyObject* value) { - Py_ssize_t start, stop, step, slicelength, needed; - arrayobject* other; - int itemsize; - - if (PyIndex_Check(item)) { - Py_ssize_t i = PyNumber_AsSsize_t(item, PyExc_IndexError); - - if (i == -1 && PyErr_Occurred()) - return -1; - if (i < 0) - i += Py_SIZE(self); - if (i < 0 || i >= Py_SIZE(self)) { - PyErr_SetString(PyExc_IndexError, - "array assignment index out of range"); - return -1; - } - if (value == NULL) { - /* Fall through to slice assignment */ - start = i; - stop = i + 1; - step = 1; - slicelength = 1; - } - else - return (*self->ob_descr->setitem)(self, i, value); - } - else if (PySlice_Check(item)) { - if (PySlice_GetIndicesEx((PySliceObject *)item, - Py_SIZE(self), &start, &stop, - &step, &slicelength) < 0) { - return -1; - } - } - else { - PyErr_SetString(PyExc_TypeError, - "array indices must be integer"); - return -1; - } - if (value == NULL) { - other = NULL; - needed = 0; - } - else if (array_Check(value)) { - other = (arrayobject *)value; - needed = Py_SIZE(other); - if (self == other) { - /* Special case "self[i:j] = self" -- copy self first */ - int ret; - value = array_slice(other, 0, needed); - if (value == NULL) - return -1; - ret = array_ass_subscr(self, item, value); - Py_DECREF(value); - return ret; - } - if (other->ob_descr != self->ob_descr) { - PyErr_BadArgument(); - return -1; - } - } - else { - PyErr_Format(PyExc_TypeError, - "can only assign array (not \"%.200s\") to array slice", - Py_TYPE(value)->tp_name); - return -1; - } - itemsize = self->ob_descr->itemsize; - /* for 'a[2:1] = ...', the insertion point is 'start', not 'stop' */ - if ((step > 0 && stop < start) || - (step < 0 && stop > start)) - stop = start; - - /* Issue #4509: If the array has exported buffers and the slice - assignment would change the size of the array, fail early to make - sure we don't modify it. */ - if ((needed == 0 || slicelength != needed) && self->ob_exports > 0) { - PyErr_SetString(PyExc_BufferError, - "cannot resize an array that is exporting buffers"); - return -1; - } - - if (step == 1) { - if (slicelength > needed) { - memmove(self->ob_item + (start + needed) * itemsize, - self->ob_item + stop * itemsize, - (Py_SIZE(self) - stop) * itemsize); - if (array_resize(self, Py_SIZE(self) + - needed - slicelength) < 0) - return -1; - } - else if (slicelength < needed) { - if (array_resize(self, Py_SIZE(self) + - needed - slicelength) < 0) - return -1; - memmove(self->ob_item + (start + needed) * itemsize, - self->ob_item + stop * itemsize, - (Py_SIZE(self) - start - needed) * itemsize); - } - if (needed > 0) - memcpy(self->ob_item + start * itemsize, - other->ob_item, needed * itemsize); - return 0; - } - else if (needed == 0) { - /* Delete slice */ - size_t cur; - Py_ssize_t i; - - if (step < 0) { - stop = start + 1; - start = stop + step * (slicelength - 1) - 1; - step = -step; - } - for (cur = start, i = 0; i < slicelength; - cur += step, i++) { - Py_ssize_t lim = step - 1; - - if (cur + step >= (size_t)Py_SIZE(self)) - lim = Py_SIZE(self) - cur - 1; - memmove(self->ob_item + (cur - i) * itemsize, - self->ob_item + (cur + 1) * itemsize, - lim * itemsize); - } - cur = start + slicelength * step; - if (cur < (size_t)Py_SIZE(self)) { - memmove(self->ob_item + (cur-slicelength) * itemsize, - self->ob_item + cur * itemsize, - (Py_SIZE(self) - cur) * itemsize); - } - if (array_resize(self, Py_SIZE(self) - slicelength) < 0) - return -1; - return 0; - } - else { - Py_ssize_t cur, i; - - if (needed != slicelength) { - PyErr_Format(PyExc_ValueError, - "attempt to assign array of size %zd " - "to extended slice of size %zd", - needed, slicelength); - return -1; - } - for (cur = start, i = 0; i < slicelength; - cur += step, i++) { - memcpy(self->ob_item + cur * itemsize, - other->ob_item + i * itemsize, - itemsize); - } - return 0; - } + Py_ssize_t start, stop, step, slicelength, needed; + arrayobject* other; + int itemsize; + + if (PyIndex_Check(item)) { + Py_ssize_t i = PyNumber_AsSsize_t(item, PyExc_IndexError); + + if (i == -1 && PyErr_Occurred()) + return -1; + if (i < 0) + i += Py_SIZE(self); + if (i < 0 || i >= Py_SIZE(self)) { + PyErr_SetString(PyExc_IndexError, + "array assignment index out of range"); + return -1; + } + if (value == NULL) { + /* Fall through to slice assignment */ + start = i; + stop = i + 1; + step = 1; + slicelength = 1; + } + else + return (*self->ob_descr->setitem)(self, i, value); + } + else if (PySlice_Check(item)) { + if (PySlice_GetIndicesEx((PySliceObject *)item, + Py_SIZE(self), &start, &stop, + &step, &slicelength) < 0) { + return -1; + } + } + else { + PyErr_SetString(PyExc_TypeError, + "array indices must be integer"); + return -1; + } + if (value == NULL) { + other = NULL; + needed = 0; + } + else if (array_Check(value)) { + other = (arrayobject *)value; + needed = Py_SIZE(other); + if (self == other) { + /* Special case "self[i:j] = self" -- copy self first */ + int ret; + value = array_slice(other, 0, needed); + if (value == NULL) + return -1; + ret = array_ass_subscr(self, item, value); + Py_DECREF(value); + return ret; + } + if (other->ob_descr != self->ob_descr) { + PyErr_BadArgument(); + return -1; + } + } + else { + PyErr_Format(PyExc_TypeError, + "can only assign array (not \"%.200s\") to array slice", + Py_TYPE(value)->tp_name); + return -1; + } + itemsize = self->ob_descr->itemsize; + /* for 'a[2:1] = ...', the insertion point is 'start', not 'stop' */ + if ((step > 0 && stop < start) || + (step < 0 && stop > start)) + stop = start; + + /* Issue #4509: If the array has exported buffers and the slice + assignment would change the size of the array, fail early to make + sure we don't modify it. */ + if ((needed == 0 || slicelength != needed) && self->ob_exports > 0) { + PyErr_SetString(PyExc_BufferError, + "cannot resize an array that is exporting buffers"); + return -1; + } + + if (step == 1) { + if (slicelength > needed) { + memmove(self->ob_item + (start + needed) * itemsize, + self->ob_item + stop * itemsize, + (Py_SIZE(self) - stop) * itemsize); + if (array_resize(self, Py_SIZE(self) + + needed - slicelength) < 0) + return -1; + } + else if (slicelength < needed) { + if (array_resize(self, Py_SIZE(self) + + needed - slicelength) < 0) + return -1; + memmove(self->ob_item + (start + needed) * itemsize, + self->ob_item + stop * itemsize, + (Py_SIZE(self) - start - needed) * itemsize); + } + if (needed > 0) + memcpy(self->ob_item + start * itemsize, + other->ob_item, needed * itemsize); + return 0; + } + else if (needed == 0) { + /* Delete slice */ + size_t cur; + Py_ssize_t i; + + if (step < 0) { + stop = start + 1; + start = stop + step * (slicelength - 1) - 1; + step = -step; + } + for (cur = start, i = 0; i < slicelength; + cur += step, i++) { + Py_ssize_t lim = step - 1; + + if (cur + step >= (size_t)Py_SIZE(self)) + lim = Py_SIZE(self) - cur - 1; + memmove(self->ob_item + (cur - i) * itemsize, + self->ob_item + (cur + 1) * itemsize, + lim * itemsize); + } + cur = start + slicelength * step; + if (cur < (size_t)Py_SIZE(self)) { + memmove(self->ob_item + (cur-slicelength) * itemsize, + self->ob_item + cur * itemsize, + (Py_SIZE(self) - cur) * itemsize); + } + if (array_resize(self, Py_SIZE(self) - slicelength) < 0) + return -1; + return 0; + } + else { + Py_ssize_t cur, i; + + if (needed != slicelength) { + PyErr_Format(PyExc_ValueError, + "attempt to assign array of size %zd " + "to extended slice of size %zd", + needed, slicelength); + return -1; + } + for (cur = start, i = 0; i < slicelength; + cur += step, i++) { + memcpy(self->ob_item + cur * itemsize, + other->ob_item + i * itemsize, + itemsize); + } + return 0; + } } static PyMappingMethods array_as_mapping = { - (lenfunc)array_length, - (binaryfunc)array_subscr, - (objobjargproc)array_ass_subscr + (lenfunc)array_length, + (binaryfunc)array_subscr, + (objobjargproc)array_ass_subscr }; static const void *emptybuf = ""; @@ -2259,173 +2259,173 @@ static int array_buffer_getbuf(arrayobject *self, Py_buffer *view, int flags) { - if (view==NULL) goto finish; + if (view==NULL) goto finish; - view->buf = (void *)self->ob_item; - view->obj = (PyObject*)self; - Py_INCREF(self); - if (view->buf == NULL) - view->buf = (void *)emptybuf; - view->len = (Py_SIZE(self)) * self->ob_descr->itemsize; - view->readonly = 0; - view->ndim = 1; - view->itemsize = self->ob_descr->itemsize; - view->suboffsets = NULL; - view->shape = NULL; - if ((flags & PyBUF_ND)==PyBUF_ND) { - view->shape = &((Py_SIZE(self))); - } - view->strides = NULL; - if ((flags & PyBUF_STRIDES)==PyBUF_STRIDES) - view->strides = &(view->itemsize); - view->format = NULL; - view->internal = NULL; - if ((flags & PyBUF_FORMAT) == PyBUF_FORMAT) { - view->format = self->ob_descr->formats; + view->buf = (void *)self->ob_item; + view->obj = (PyObject*)self; + Py_INCREF(self); + if (view->buf == NULL) + view->buf = (void *)emptybuf; + view->len = (Py_SIZE(self)) * self->ob_descr->itemsize; + view->readonly = 0; + view->ndim = 1; + view->itemsize = self->ob_descr->itemsize; + view->suboffsets = NULL; + view->shape = NULL; + if ((flags & PyBUF_ND)==PyBUF_ND) { + view->shape = &((Py_SIZE(self))); + } + view->strides = NULL; + if ((flags & PyBUF_STRIDES)==PyBUF_STRIDES) + view->strides = &(view->itemsize); + view->format = NULL; + view->internal = NULL; + if ((flags & PyBUF_FORMAT) == PyBUF_FORMAT) { + view->format = self->ob_descr->formats; #ifdef Py_UNICODE_WIDE - if (self->ob_descr->typecode == 'u') { - view->format = "w"; - } -#endif + if (self->ob_descr->typecode == 'u') { + view->format = "w"; } +#endif + } finish: - self->ob_exports++; - return 0; + self->ob_exports++; + return 0; } static void array_buffer_relbuf(arrayobject *self, Py_buffer *view) { - self->ob_exports--; + self->ob_exports--; } static PySequenceMethods array_as_sequence = { - (lenfunc)array_length, /*sq_length*/ - (binaryfunc)array_concat, /*sq_concat*/ - (ssizeargfunc)array_repeat, /*sq_repeat*/ - (ssizeargfunc)array_item, /*sq_item*/ - 0, /*sq_slice*/ - (ssizeobjargproc)array_ass_item, /*sq_ass_item*/ - 0, /*sq_ass_slice*/ - (objobjproc)array_contains, /*sq_contains*/ - (binaryfunc)array_inplace_concat, /*sq_inplace_concat*/ - (ssizeargfunc)array_inplace_repeat /*sq_inplace_repeat*/ + (lenfunc)array_length, /*sq_length*/ + (binaryfunc)array_concat, /*sq_concat*/ + (ssizeargfunc)array_repeat, /*sq_repeat*/ + (ssizeargfunc)array_item, /*sq_item*/ + 0, /*sq_slice*/ + (ssizeobjargproc)array_ass_item, /*sq_ass_item*/ + 0, /*sq_ass_slice*/ + (objobjproc)array_contains, /*sq_contains*/ + (binaryfunc)array_inplace_concat, /*sq_inplace_concat*/ + (ssizeargfunc)array_inplace_repeat /*sq_inplace_repeat*/ }; static PyBufferProcs array_as_buffer = { - (getbufferproc)array_buffer_getbuf, - (releasebufferproc)array_buffer_relbuf + (getbufferproc)array_buffer_getbuf, + (releasebufferproc)array_buffer_relbuf }; static PyObject * array_new(PyTypeObject *type, PyObject *args, PyObject *kwds) { - int c; - PyObject *initial = NULL, *it = NULL; - struct arraydescr *descr; - - if (type == &Arraytype && !_PyArg_NoKeywords("array.array()", kwds)) - return NULL; - - if (!PyArg_ParseTuple(args, "C|O:array", &c, &initial)) - return NULL; - - if (!(initial == NULL || PyList_Check(initial) - || PyByteArray_Check(initial) - || PyBytes_Check(initial) - || PyTuple_Check(initial) - || ((c=='u') && PyUnicode_Check(initial)))) { - it = PyObject_GetIter(initial); - if (it == NULL) - return NULL; - /* We set initial to NULL so that the subsequent code - will create an empty array of the appropriate type - and afterwards we can use array_iter_extend to populate - the array. - */ - initial = NULL; - } - for (descr = descriptors; descr->typecode != '\0'; descr++) { - if (descr->typecode == c) { - PyObject *a; - Py_ssize_t len; - - if (initial == NULL || !(PyList_Check(initial) - || PyTuple_Check(initial))) - len = 0; - else - len = PySequence_Size(initial); - - a = newarrayobject(type, len, descr); - if (a == NULL) - return NULL; - - if (len > 0) { - Py_ssize_t i; - for (i = 0; i < len; i++) { - PyObject *v = - PySequence_GetItem(initial, i); - if (v == NULL) { - Py_DECREF(a); - return NULL; - } - if (setarrayitem(a, i, v) != 0) { - Py_DECREF(v); - Py_DECREF(a); - return NULL; - } - Py_DECREF(v); - } - } - else if (initial != NULL && (PyByteArray_Check(initial) || - PyBytes_Check(initial))) { - PyObject *t_initial, *v; - t_initial = PyTuple_Pack(1, initial); - if (t_initial == NULL) { - Py_DECREF(a); - return NULL; - } - v = array_fromstring((arrayobject *)a, - t_initial); - Py_DECREF(t_initial); - if (v == NULL) { - Py_DECREF(a); - return NULL; - } - Py_DECREF(v); - } - else if (initial != NULL && PyUnicode_Check(initial)) { - Py_ssize_t n = PyUnicode_GET_DATA_SIZE(initial); - if (n > 0) { - arrayobject *self = (arrayobject *)a; - char *item = self->ob_item; - item = (char *)PyMem_Realloc(item, n); - if (item == NULL) { - PyErr_NoMemory(); - Py_DECREF(a); - return NULL; - } - self->ob_item = item; - Py_SIZE(self) = n / sizeof(Py_UNICODE); - memcpy(item, PyUnicode_AS_DATA(initial), n); - self->allocated = Py_SIZE(self); - } - } - if (it != NULL) { - if (array_iter_extend((arrayobject *)a, it) == -1) { - Py_DECREF(it); - Py_DECREF(a); - return NULL; - } - Py_DECREF(it); - } - return a; - } - } - PyErr_SetString(PyExc_ValueError, - "bad typecode (must be b, B, u, h, H, i, I, l, L, f or d)"); - return NULL; + int c; + PyObject *initial = NULL, *it = NULL; + struct arraydescr *descr; + + if (type == &Arraytype && !_PyArg_NoKeywords("array.array()", kwds)) + return NULL; + + if (!PyArg_ParseTuple(args, "C|O:array", &c, &initial)) + return NULL; + + if (!(initial == NULL || PyList_Check(initial) + || PyByteArray_Check(initial) + || PyBytes_Check(initial) + || PyTuple_Check(initial) + || ((c=='u') && PyUnicode_Check(initial)))) { + it = PyObject_GetIter(initial); + if (it == NULL) + return NULL; + /* We set initial to NULL so that the subsequent code + will create an empty array of the appropriate type + and afterwards we can use array_iter_extend to populate + the array. + */ + initial = NULL; + } + for (descr = descriptors; descr->typecode != '\0'; descr++) { + if (descr->typecode == c) { + PyObject *a; + Py_ssize_t len; + + if (initial == NULL || !(PyList_Check(initial) + || PyTuple_Check(initial))) + len = 0; + else + len = PySequence_Size(initial); + + a = newarrayobject(type, len, descr); + if (a == NULL) + return NULL; + + if (len > 0) { + Py_ssize_t i; + for (i = 0; i < len; i++) { + PyObject *v = + PySequence_GetItem(initial, i); + if (v == NULL) { + Py_DECREF(a); + return NULL; + } + if (setarrayitem(a, i, v) != 0) { + Py_DECREF(v); + Py_DECREF(a); + return NULL; + } + Py_DECREF(v); + } + } + else if (initial != NULL && (PyByteArray_Check(initial) || + PyBytes_Check(initial))) { + PyObject *t_initial, *v; + t_initial = PyTuple_Pack(1, initial); + if (t_initial == NULL) { + Py_DECREF(a); + return NULL; + } + v = array_fromstring((arrayobject *)a, + t_initial); + Py_DECREF(t_initial); + if (v == NULL) { + Py_DECREF(a); + return NULL; + } + Py_DECREF(v); + } + else if (initial != NULL && PyUnicode_Check(initial)) { + Py_ssize_t n = PyUnicode_GET_DATA_SIZE(initial); + if (n > 0) { + arrayobject *self = (arrayobject *)a; + char *item = self->ob_item; + item = (char *)PyMem_Realloc(item, n); + if (item == NULL) { + PyErr_NoMemory(); + Py_DECREF(a); + return NULL; + } + self->ob_item = item; + Py_SIZE(self) = n / sizeof(Py_UNICODE); + memcpy(item, PyUnicode_AS_DATA(initial), n); + self->allocated = Py_SIZE(self); + } + } + if (it != NULL) { + if (array_iter_extend((arrayobject *)a, it) == -1) { + Py_DECREF(it); + Py_DECREF(a); + return NULL; + } + Py_DECREF(it); + } + return a; + } + } + PyErr_SetString(PyExc_ValueError, + "bad typecode (must be b, B, u, h, H, i, I, l, L, f or d)"); + return NULL; } @@ -2496,55 +2496,55 @@ static PyObject *array_iter(arrayobject *ao); static PyTypeObject Arraytype = { - PyVarObject_HEAD_INIT(NULL, 0) - "array.array", - sizeof(arrayobject), - 0, - (destructor)array_dealloc, /* tp_dealloc */ - 0, /* tp_print */ - 0, /* tp_getattr */ - 0, /* tp_setattr */ - 0, /* tp_reserved */ - (reprfunc)array_repr, /* tp_repr */ - 0, /* tp_as_number*/ - &array_as_sequence, /* tp_as_sequence*/ - &array_as_mapping, /* tp_as_mapping*/ - 0, /* tp_hash */ - 0, /* tp_call */ - 0, /* tp_str */ - PyObject_GenericGetAttr, /* tp_getattro */ - 0, /* tp_setattro */ - &array_as_buffer, /* tp_as_buffer*/ - Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */ - arraytype_doc, /* tp_doc */ - 0, /* tp_traverse */ - 0, /* tp_clear */ - array_richcompare, /* tp_richcompare */ - offsetof(arrayobject, weakreflist), /* tp_weaklistoffset */ - (getiterfunc)array_iter, /* tp_iter */ - 0, /* tp_iternext */ - array_methods, /* tp_methods */ - 0, /* tp_members */ - array_getsets, /* tp_getset */ - 0, /* tp_base */ - 0, /* tp_dict */ - 0, /* tp_descr_get */ - 0, /* tp_descr_set */ - 0, /* tp_dictoffset */ - 0, /* tp_init */ - PyType_GenericAlloc, /* tp_alloc */ - array_new, /* tp_new */ - PyObject_Del, /* tp_free */ + PyVarObject_HEAD_INIT(NULL, 0) + "array.array", + sizeof(arrayobject), + 0, + (destructor)array_dealloc, /* tp_dealloc */ + 0, /* tp_print */ + 0, /* tp_getattr */ + 0, /* tp_setattr */ + 0, /* tp_reserved */ + (reprfunc)array_repr, /* tp_repr */ + 0, /* tp_as_number*/ + &array_as_sequence, /* tp_as_sequence*/ + &array_as_mapping, /* tp_as_mapping*/ + 0, /* tp_hash */ + 0, /* tp_call */ + 0, /* tp_str */ + PyObject_GenericGetAttr, /* tp_getattro */ + 0, /* tp_setattro */ + &array_as_buffer, /* tp_as_buffer*/ + Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */ + arraytype_doc, /* tp_doc */ + 0, /* tp_traverse */ + 0, /* tp_clear */ + array_richcompare, /* tp_richcompare */ + offsetof(arrayobject, weakreflist), /* tp_weaklistoffset */ + (getiterfunc)array_iter, /* tp_iter */ + 0, /* tp_iternext */ + array_methods, /* tp_methods */ + 0, /* tp_members */ + array_getsets, /* tp_getset */ + 0, /* tp_base */ + 0, /* tp_dict */ + 0, /* tp_descr_get */ + 0, /* tp_descr_set */ + 0, /* tp_dictoffset */ + 0, /* tp_init */ + PyType_GenericAlloc, /* tp_alloc */ + array_new, /* tp_new */ + PyObject_Del, /* tp_free */ }; /*********************** Array Iterator **************************/ typedef struct { - PyObject_HEAD - Py_ssize_t index; - arrayobject *ao; - PyObject * (*getitem)(struct arrayobject *, Py_ssize_t); + PyObject_HEAD + Py_ssize_t index; + arrayobject *ao; + PyObject * (*getitem)(struct arrayobject *, Py_ssize_t); } arrayiterobject; static PyTypeObject PyArrayIter_Type; @@ -2554,79 +2554,79 @@ static PyObject * array_iter(arrayobject *ao) { - arrayiterobject *it; + arrayiterobject *it; - if (!array_Check(ao)) { - PyErr_BadInternalCall(); - return NULL; - } - - it = PyObject_GC_New(arrayiterobject, &PyArrayIter_Type); - if (it == NULL) - return NULL; - - Py_INCREF(ao); - it->ao = ao; - it->index = 0; - it->getitem = ao->ob_descr->getitem; - PyObject_GC_Track(it); - return (PyObject *)it; + if (!array_Check(ao)) { + PyErr_BadInternalCall(); + return NULL; + } + + it = PyObject_GC_New(arrayiterobject, &PyArrayIter_Type); + if (it == NULL) + return NULL; + + Py_INCREF(ao); + it->ao = ao; + it->index = 0; + it->getitem = ao->ob_descr->getitem; + PyObject_GC_Track(it); + return (PyObject *)it; } static PyObject * arrayiter_next(arrayiterobject *it) { - assert(PyArrayIter_Check(it)); - if (it->index < Py_SIZE(it->ao)) - return (*it->getitem)(it->ao, it->index++); - return NULL; + assert(PyArrayIter_Check(it)); + if (it->index < Py_SIZE(it->ao)) + return (*it->getitem)(it->ao, it->index++); + return NULL; } static void arrayiter_dealloc(arrayiterobject *it) { - PyObject_GC_UnTrack(it); - Py_XDECREF(it->ao); - PyObject_GC_Del(it); + PyObject_GC_UnTrack(it); + Py_XDECREF(it->ao); + PyObject_GC_Del(it); } static int arrayiter_traverse(arrayiterobject *it, visitproc visit, void *arg) { - Py_VISIT(it->ao); - return 0; + Py_VISIT(it->ao); + return 0; } static PyTypeObject PyArrayIter_Type = { - PyVarObject_HEAD_INIT(NULL, 0) - "arrayiterator", /* tp_name */ - sizeof(arrayiterobject), /* tp_basicsize */ - 0, /* tp_itemsize */ - /* methods */ - (destructor)arrayiter_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)arrayiter_traverse, /* tp_traverse */ - 0, /* tp_clear */ - 0, /* tp_richcompare */ - 0, /* tp_weaklistoffset */ - PyObject_SelfIter, /* tp_iter */ - (iternextfunc)arrayiter_next, /* tp_iternext */ - 0, /* tp_methods */ + PyVarObject_HEAD_INIT(NULL, 0) + "arrayiterator", /* tp_name */ + sizeof(arrayiterobject), /* tp_basicsize */ + 0, /* tp_itemsize */ + /* methods */ + (destructor)arrayiter_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)arrayiter_traverse, /* tp_traverse */ + 0, /* tp_clear */ + 0, /* tp_richcompare */ + 0, /* tp_weaklistoffset */ + PyObject_SelfIter, /* tp_iter */ + (iternextfunc)arrayiter_next, /* tp_iternext */ + 0, /* tp_methods */ }; @@ -2640,54 +2640,54 @@ }; static struct PyModuleDef arraymodule = { - PyModuleDef_HEAD_INIT, - "array", - module_doc, - -1, - a_methods, - NULL, - NULL, - NULL, - NULL + PyModuleDef_HEAD_INIT, + "array", + module_doc, + -1, + a_methods, + NULL, + NULL, + NULL, + NULL }; PyMODINIT_FUNC PyInit_array(void) { - PyObject *m; - PyObject *typecodes; - Py_ssize_t size = 0; - register Py_UNICODE *p; - struct arraydescr *descr; - - if (PyType_Ready(&Arraytype) < 0) - return NULL; - Py_TYPE(&PyArrayIter_Type) = &PyType_Type; - m = PyModule_Create(&arraymodule); - if (m == NULL) - return NULL; - - Py_INCREF((PyObject *)&Arraytype); - PyModule_AddObject(m, "ArrayType", (PyObject *)&Arraytype); - Py_INCREF((PyObject *)&Arraytype); - PyModule_AddObject(m, "array", (PyObject *)&Arraytype); - - for (descr=descriptors; descr->typecode != '\0'; descr++) { - size++; - } - - typecodes = PyUnicode_FromStringAndSize(NULL, size); - p = PyUnicode_AS_UNICODE(typecodes); - for (descr = descriptors; descr->typecode != '\0'; descr++) { - *p++ = (char)descr->typecode; - } - - PyModule_AddObject(m, "typecodes", (PyObject *)typecodes); - - if (PyErr_Occurred()) { - Py_DECREF(m); - m = NULL; - } - return m; + PyObject *m; + PyObject *typecodes; + Py_ssize_t size = 0; + register Py_UNICODE *p; + struct arraydescr *descr; + + if (PyType_Ready(&Arraytype) < 0) + return NULL; + Py_TYPE(&PyArrayIter_Type) = &PyType_Type; + m = PyModule_Create(&arraymodule); + if (m == NULL) + return NULL; + + Py_INCREF((PyObject *)&Arraytype); + PyModule_AddObject(m, "ArrayType", (PyObject *)&Arraytype); + Py_INCREF((PyObject *)&Arraytype); + PyModule_AddObject(m, "array", (PyObject *)&Arraytype); + + for (descr=descriptors; descr->typecode != '\0'; descr++) { + size++; + } + + typecodes = PyUnicode_FromStringAndSize(NULL, size); + p = PyUnicode_AS_UNICODE(typecodes); + for (descr = descriptors; descr->typecode != '\0'; descr++) { + *p++ = (char)descr->typecode; + } + + PyModule_AddObject(m, "typecodes", (PyObject *)typecodes); + + if (PyErr_Occurred()) { + Py_DECREF(m); + m = NULL; + } + return m; } Modified: python/branches/py3k/Modules/audioop.c ============================================================================== --- python/branches/py3k/Modules/audioop.c (original) +++ python/branches/py3k/Modules/audioop.c Sun May 9 17:52:27 2010 @@ -53,13 +53,13 @@ static PyInt16 search(PyInt16 val, PyInt16 *table, int size) { - int i; + int i; - for (i = 0; i < size; i++) { - if (val <= *table++) - return (i); - } - return (size); + for (i = 0; i < size; i++) { + if (val <= *table++) + return (i); + } + return (size); } #define st_ulaw2linear16(uc) (_st_ulaw2linear16[uc]) #define st_alaw2linear16(uc) (_st_alaw2linear16[uc]) @@ -83,7 +83,7 @@ -228, -212, -196, -180, -164, -148, -132, -120, -112, -104, -96, -88, -80, -72, -64, -56, -48, -40, -32, -24, -16, - -8, 0, 32124, 31100, 30076, 29052, 28028, + -8, 0, 32124, 31100, 30076, 29052, 28028, 27004, 25980, 24956, 23932, 22908, 21884, 20860, 19836, 18812, 17788, 16764, 15996, 15484, 14972, 14460, 13948, 13436, 12924, 12412, 11900, 11388, @@ -100,8 +100,8 @@ 372, 356, 340, 324, 308, 292, 276, 260, 244, 228, 212, 196, 180, 164, 148, 132, 120, 112, 104, 96, 88, - 80, 72, 64, 56, 48, 40, 32, - 24, 16, 8, 0 + 80, 72, 64, 56, 48, 40, 32, + 24, 16, 8, 0 }; /* @@ -137,39 +137,39 @@ * John Wiley & Sons, pps 98-111 and 472-476. */ static unsigned char -st_14linear2ulaw(PyInt16 pcm_val) /* 2's complement (14-bit range) */ +st_14linear2ulaw(PyInt16 pcm_val) /* 2's complement (14-bit range) */ { - PyInt16 mask; - PyInt16 seg; - unsigned char uval; - - /* The original sox code does this in the calling function, not here */ - pcm_val = pcm_val >> 2; - - /* u-law inverts all bits */ - /* Get the sign and the magnitude of the value. */ - if (pcm_val < 0) { - pcm_val = -pcm_val; - mask = 0x7F; - } else { - mask = 0xFF; - } - if ( pcm_val > CLIP ) pcm_val = CLIP; /* clip the magnitude */ - pcm_val += (BIAS >> 2); - - /* Convert the scaled magnitude to segment number. */ - seg = search(pcm_val, seg_uend, 8); - - /* - * Combine the sign, segment, quantization bits; - * and complement the code word. - */ - if (seg >= 8) /* out of range, return maximum value. */ - return (unsigned char) (0x7F ^ mask); - else { - uval = (unsigned char) (seg << 4) | ((pcm_val >> (seg + 1)) & 0xF); - return (uval ^ mask); - } + PyInt16 mask; + PyInt16 seg; + unsigned char uval; + + /* The original sox code does this in the calling function, not here */ + pcm_val = pcm_val >> 2; + + /* u-law inverts all bits */ + /* Get the sign and the magnitude of the value. */ + if (pcm_val < 0) { + pcm_val = -pcm_val; + mask = 0x7F; + } else { + mask = 0xFF; + } + if ( pcm_val > CLIP ) pcm_val = CLIP; /* clip the magnitude */ + pcm_val += (BIAS >> 2); + + /* Convert the scaled magnitude to segment number. */ + seg = search(pcm_val, seg_uend, 8); + + /* + * Combine the sign, segment, quantization bits; + * and complement the code word. + */ + if (seg >= 8) /* out of range, return maximum value. */ + return (unsigned char) (0x7F ^ mask); + else { + uval = (unsigned char) (seg << 4) | ((pcm_val >> (seg + 1)) & 0xF); + return (uval ^ mask); + } } @@ -234,59 +234,59 @@ * John Wiley & Sons, pps 98-111 and 472-476. */ static unsigned char -st_linear2alaw(PyInt16 pcm_val) /* 2's complement (13-bit range) */ +st_linear2alaw(PyInt16 pcm_val) /* 2's complement (13-bit range) */ { - PyInt16 mask; - short seg; - unsigned char aval; - - /* The original sox code does this in the calling function, not here */ - pcm_val = pcm_val >> 3; - - /* A-law using even bit inversion */ - if (pcm_val >= 0) { - mask = 0xD5; /* sign (7th) bit = 1 */ - } else { - mask = 0x55; /* sign bit = 0 */ - pcm_val = -pcm_val - 1; - } - - /* Convert the scaled magnitude to segment number. */ - seg = search(pcm_val, seg_aend, 8); - - /* Combine the sign, segment, and quantization bits. */ - - if (seg >= 8) /* out of range, return maximum value. */ - return (unsigned char) (0x7F ^ mask); - else { - aval = (unsigned char) seg << SEG_SHIFT; - if (seg < 2) - aval |= (pcm_val >> 1) & QUANT_MASK; - else - aval |= (pcm_val >> seg) & QUANT_MASK; - return (aval ^ mask); - } + PyInt16 mask; + short seg; + unsigned char aval; + + /* The original sox code does this in the calling function, not here */ + pcm_val = pcm_val >> 3; + + /* A-law using even bit inversion */ + if (pcm_val >= 0) { + mask = 0xD5; /* sign (7th) bit = 1 */ + } else { + mask = 0x55; /* sign bit = 0 */ + pcm_val = -pcm_val - 1; + } + + /* Convert the scaled magnitude to segment number. */ + seg = search(pcm_val, seg_aend, 8); + + /* Combine the sign, segment, and quantization bits. */ + + if (seg >= 8) /* out of range, return maximum value. */ + return (unsigned char) (0x7F ^ mask); + else { + aval = (unsigned char) seg << SEG_SHIFT; + if (seg < 2) + aval |= (pcm_val >> 1) & QUANT_MASK; + else + aval |= (pcm_val >> seg) & QUANT_MASK; + return (aval ^ mask); + } } /* End of code taken from sox */ /* Intel ADPCM step variation table */ static int indexTable[16] = { - -1, -1, -1, -1, 2, 4, 6, 8, - -1, -1, -1, -1, 2, 4, 6, 8, + -1, -1, -1, -1, 2, 4, 6, 8, + -1, -1, -1, -1, 2, 4, 6, 8, }; static int stepsizeTable[89] = { - 7, 8, 9, 10, 11, 12, 13, 14, 16, 17, - 19, 21, 23, 25, 28, 31, 34, 37, 41, 45, - 50, 55, 60, 66, 73, 80, 88, 97, 107, 118, - 130, 143, 157, 173, 190, 209, 230, 253, 279, 307, - 337, 371, 408, 449, 494, 544, 598, 658, 724, 796, - 876, 963, 1060, 1166, 1282, 1411, 1552, 1707, 1878, 2066, - 2272, 2499, 2749, 3024, 3327, 3660, 4026, 4428, 4871, 5358, - 5894, 6484, 7132, 7845, 8630, 9493, 10442, 11487, 12635, 13899, - 15289, 16818, 18500, 20350, 22385, 24623, 27086, 29794, 32767 + 7, 8, 9, 10, 11, 12, 13, 14, 16, 17, + 19, 21, 23, 25, 28, 31, 34, 37, 41, 45, + 50, 55, 60, 66, 73, 80, 88, 97, 107, 118, + 130, 143, 157, 173, 190, 209, 230, 253, 279, 307, + 337, 371, 408, 449, 494, 544, 598, 658, 724, 796, + 876, 963, 1060, 1166, 1282, 1411, 1552, 1707, 1878, 2066, + 2272, 2499, 2749, 3024, 3327, 3660, 4026, 4428, 4871, 5358, + 5894, 6484, 7132, 7845, 8630, 9493, 10442, 11487, 12635, 13899, + 15289, 16818, 18500, 20350, 22385, 24623, 27086, 29794, 32767 }; - + #define CHARP(cp, i) ((signed char *)(cp+i)) #define SHORTP(cp, i) ((short *)(cp+i)) #define LONGP(cp, i) ((Py_Int32 *)(cp+i)) @@ -298,137 +298,137 @@ static PyObject * audioop_getsample(PyObject *self, PyObject *args) { - signed char *cp; - int len, size, val = 0; - int i; - - if ( !PyArg_ParseTuple(args, "s#ii:getsample", &cp, &len, &size, &i) ) - return 0; - if ( size != 1 && size != 2 && size != 4 ) { - PyErr_SetString(AudioopError, "Size should be 1, 2 or 4"); - return 0; - } - if ( i < 0 || i >= len/size ) { - PyErr_SetString(AudioopError, "Index out of range"); - return 0; - } - if ( size == 1 ) val = (int)*CHARP(cp, i); - else if ( size == 2 ) val = (int)*SHORTP(cp, i*2); - else if ( size == 4 ) val = (int)*LONGP(cp, i*4); - return PyLong_FromLong(val); + signed char *cp; + int len, size, val = 0; + int i; + + if ( !PyArg_ParseTuple(args, "s#ii:getsample", &cp, &len, &size, &i) ) + return 0; + if ( size != 1 && size != 2 && size != 4 ) { + PyErr_SetString(AudioopError, "Size should be 1, 2 or 4"); + return 0; + } + if ( i < 0 || i >= len/size ) { + PyErr_SetString(AudioopError, "Index out of range"); + return 0; + } + if ( size == 1 ) val = (int)*CHARP(cp, i); + else if ( size == 2 ) val = (int)*SHORTP(cp, i*2); + else if ( size == 4 ) val = (int)*LONGP(cp, i*4); + return PyLong_FromLong(val); } static PyObject * audioop_max(PyObject *self, PyObject *args) { - signed char *cp; - int len, size, val = 0; - int i; - int max = 0; - - if ( !PyArg_ParseTuple(args, "s#i:max", &cp, &len, &size) ) - return 0; - if ( size != 1 && size != 2 && size != 4 ) { - PyErr_SetString(AudioopError, "Size should be 1, 2 or 4"); - return 0; - } - for ( i=0; i max ) max = val; - } - return PyLong_FromLong(max); + signed char *cp; + int len, size, val = 0; + int i; + int max = 0; + + if ( !PyArg_ParseTuple(args, "s#i:max", &cp, &len, &size) ) + return 0; + if ( size != 1 && size != 2 && size != 4 ) { + PyErr_SetString(AudioopError, "Size should be 1, 2 or 4"); + return 0; + } + for ( i=0; i max ) max = val; + } + return PyLong_FromLong(max); } static PyObject * audioop_minmax(PyObject *self, PyObject *args) { - signed char *cp; - int len, size, val = 0; - int i; - int min = 0x7fffffff, max = -0x7fffffff; - - if (!PyArg_ParseTuple(args, "s#i:minmax", &cp, &len, &size)) - return NULL; - if (size != 1 && size != 2 && size != 4) { - PyErr_SetString(AudioopError, "Size should be 1, 2 or 4"); - return NULL; - } - for (i = 0; i < len; i += size) { - 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); - if (val > max) max = val; - if (val < min) min = val; - } - return Py_BuildValue("(ii)", min, max); + signed char *cp; + int len, size, val = 0; + int i; + int min = 0x7fffffff, max = -0x7fffffff; + + if (!PyArg_ParseTuple(args, "s#i:minmax", &cp, &len, &size)) + return NULL; + if (size != 1 && size != 2 && size != 4) { + PyErr_SetString(AudioopError, "Size should be 1, 2 or 4"); + return NULL; + } + for (i = 0; i < len; i += size) { + 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); + if (val > max) max = val; + if (val < min) min = val; + } + return Py_BuildValue("(ii)", min, max); } static PyObject * audioop_avg(PyObject *self, PyObject *args) { - signed char *cp; - int len, size, val = 0; - int i; - double avg = 0.0; - - if ( !PyArg_ParseTuple(args, "s#i:avg", &cp, &len, &size) ) - return 0; - if ( size != 1 && size != 2 && size != 4 ) { - PyErr_SetString(AudioopError, "Size should be 1, 2 or 4"); - return 0; - } - for ( i=0; i>= 1; - len2 >>= 1; - - if ( len1 < len2 ) { - PyErr_SetString(AudioopError, "First sample should be longer"); - return 0; - } - sum_ri_2 = _sum2(cp2, cp2, len2); - sum_aij_2 = _sum2(cp1, cp1, len2); - sum_aij_ri = _sum2(cp1, cp2, len2); - - result = (sum_ri_2*sum_aij_2 - sum_aij_ri*sum_aij_ri) / sum_aij_2; - - best_result = result; - best_j = 0; - j = 0; - - for ( j=1; j<=len1-len2; j++) { - aj_m1 = (double)cp1[j-1]; - aj_lm1 = (double)cp1[j+len2-1]; - - sum_aij_2 = sum_aij_2 + aj_lm1*aj_lm1 - aj_m1*aj_m1; - sum_aij_ri = _sum2(cp1+j, cp2, len2); - - result = (sum_ri_2*sum_aij_2 - sum_aij_ri*sum_aij_ri) - / sum_aij_2; - - if ( result < best_result ) { - best_result = result; - best_j = j; - } - + short *cp1, *cp2; + int len1, len2; + int j, best_j; + double aj_m1, aj_lm1; + double sum_ri_2, sum_aij_2, sum_aij_ri, result, best_result, factor; + + /* Passing a short** for an 's' argument is correct only + if the string contents is aligned for interpretation + as short[]. Due to the definition of PyBytesObject, + this is currently (Python 2.6) the case. */ + if ( !PyArg_ParseTuple(args, "s#s#:findfit", + (char**)&cp1, &len1, (char**)&cp2, &len2) ) + return 0; + if ( len1 & 1 || len2 & 1 ) { + PyErr_SetString(AudioopError, "Strings should be even-sized"); + return 0; + } + len1 >>= 1; + len2 >>= 1; + + if ( len1 < len2 ) { + PyErr_SetString(AudioopError, "First sample should be longer"); + return 0; + } + sum_ri_2 = _sum2(cp2, cp2, len2); + sum_aij_2 = _sum2(cp1, cp1, len2); + sum_aij_ri = _sum2(cp1, cp2, len2); + + result = (sum_ri_2*sum_aij_2 - sum_aij_ri*sum_aij_ri) / sum_aij_2; + + best_result = result; + best_j = 0; + j = 0; + + for ( j=1; j<=len1-len2; j++) { + aj_m1 = (double)cp1[j-1]; + aj_lm1 = (double)cp1[j+len2-1]; + + sum_aij_2 = sum_aij_2 + aj_lm1*aj_lm1 - aj_m1*aj_m1; + sum_aij_ri = _sum2(cp1+j, cp2, len2); + + result = (sum_ri_2*sum_aij_2 - sum_aij_ri*sum_aij_ri) + / sum_aij_2; + + if ( result < best_result ) { + best_result = result; + best_j = j; } - factor = _sum2(cp1+best_j, cp2, len2) / sum_ri_2; - - return Py_BuildValue("(if)", best_j, factor); + } + + factor = _sum2(cp1+best_j, cp2, len2) / sum_ri_2; + + return Py_BuildValue("(if)", best_j, factor); } /* @@ -529,28 +529,28 @@ static PyObject * audioop_findfactor(PyObject *self, PyObject *args) { - short *cp1, *cp2; - int len1, len2; - double sum_ri_2, sum_aij_ri, result; - - if ( !PyArg_ParseTuple(args, "s#s#:findfactor", - (char**)&cp1, &len1, (char**)&cp2, &len2) ) - return 0; - if ( len1 & 1 || len2 & 1 ) { - PyErr_SetString(AudioopError, "Strings should be even-sized"); - return 0; - } - if ( len1 != len2 ) { - PyErr_SetString(AudioopError, "Samples should be same size"); - return 0; - } - len2 >>= 1; - sum_ri_2 = _sum2(cp2, cp2, len2); - sum_aij_ri = _sum2(cp1, cp2, len2); + short *cp1, *cp2; + int len1, len2; + double sum_ri_2, sum_aij_ri, result; + + if ( !PyArg_ParseTuple(args, "s#s#:findfactor", + (char**)&cp1, &len1, (char**)&cp2, &len2) ) + return 0; + if ( len1 & 1 || len2 & 1 ) { + PyErr_SetString(AudioopError, "Strings should be even-sized"); + return 0; + } + if ( len1 != len2 ) { + PyErr_SetString(AudioopError, "Samples should be same size"); + return 0; + } + len2 >>= 1; + sum_ri_2 = _sum2(cp2, cp2, len2); + sum_aij_ri = _sum2(cp1, cp2, len2); - result = sum_aij_ri / sum_ri_2; + result = sum_aij_ri / sum_ri_2; - return PyFloat_FromDouble(result); + return PyFloat_FromDouble(result); } /* @@ -560,1114 +560,1114 @@ static PyObject * audioop_findmax(PyObject *self, PyObject *args) { - short *cp1; - int len1, len2; - int j, best_j; - double aj_m1, aj_lm1; - double result, best_result; - - if ( !PyArg_ParseTuple(args, "s#i:findmax", - (char**)&cp1, &len1, &len2) ) - return 0; - if ( len1 & 1 ) { - PyErr_SetString(AudioopError, "Strings should be even-sized"); - return 0; + short *cp1; + int len1, len2; + int j, best_j; + double aj_m1, aj_lm1; + double result, best_result; + + if ( !PyArg_ParseTuple(args, "s#i:findmax", + (char**)&cp1, &len1, &len2) ) + return 0; + if ( len1 & 1 ) { + PyErr_SetString(AudioopError, "Strings should be even-sized"); + return 0; + } + len1 >>= 1; + + if ( len2 < 0 || len1 < len2 ) { + PyErr_SetString(AudioopError, "Input sample should be longer"); + return 0; + } + + result = _sum2(cp1, cp1, len2); + + best_result = result; + best_j = 0; + j = 0; + + for ( j=1; j<=len1-len2; j++) { + aj_m1 = (double)cp1[j-1]; + aj_lm1 = (double)cp1[j+len2-1]; + + result = result + aj_lm1*aj_lm1 - aj_m1*aj_m1; + + if ( result > best_result ) { + best_result = result; + best_j = j; } - len1 >>= 1; - - if ( len2 < 0 || len1 < len2 ) { - PyErr_SetString(AudioopError, "Input sample should be longer"); - return 0; - } - - result = _sum2(cp1, cp1, len2); - best_result = result; - best_j = 0; - j = 0; - - for ( j=1; j<=len1-len2; j++) { - aj_m1 = (double)cp1[j-1]; - aj_lm1 = (double)cp1[j+len2-1]; - - result = result + aj_lm1*aj_lm1 - aj_m1*aj_m1; - - if ( result > best_result ) { - best_result = result; - best_j = j; - } - - } + } - return PyLong_FromLong(best_j); + return PyLong_FromLong(best_j); } static PyObject * audioop_avgpp(PyObject *self, PyObject *args) { - signed char *cp; - int len, size, val = 0, prevval = 0, prevextremevalid = 0, - prevextreme = 0; - int i; - double avg = 0.0; - int diff, prevdiff, extremediff, nextreme = 0; - - if ( !PyArg_ParseTuple(args, "s#i:avgpp", &cp, &len, &size) ) - return 0; - if ( size != 1 && size != 2 && size != 4 ) { - PyErr_SetString(AudioopError, "Size should be 1, 2 or 4"); - return 0; - } - /* Compute first delta value ahead. Also automatically makes us - ** skip the first extreme value - */ - if ( size == 1 ) prevval = (int)*CHARP(cp, 0); - else if ( size == 2 ) prevval = (int)*SHORTP(cp, 0); - else if ( size == 4 ) prevval = (int)*LONGP(cp, 0); - if ( size == 1 ) val = (int)*CHARP(cp, size); - else if ( size == 2 ) val = (int)*SHORTP(cp, size); - else if ( size == 4 ) val = (int)*LONGP(cp, size); - prevdiff = val - prevval; - - for ( i=size; i max ) - max = extremediff; - } - prevextremevalid = 1; - prevextreme = prevval; - } - prevval = val; - if ( diff != 0 ) - prevdiff = diff; - } - return PyLong_FromLong(max); + signed char *cp; + int len, size, val = 0, prevval = 0, prevextremevalid = 0, + prevextreme = 0; + int i; + int max = 0; + int diff, prevdiff, extremediff; + + if ( !PyArg_ParseTuple(args, "s#i:maxpp", &cp, &len, &size) ) + return 0; + if ( size != 1 && size != 2 && size != 4 ) { + PyErr_SetString(AudioopError, "Size should be 1, 2 or 4"); + return 0; + } + /* Compute first delta value ahead. Also automatically makes us + ** skip the first extreme value + */ + if ( size == 1 ) prevval = (int)*CHARP(cp, 0); + else if ( size == 2 ) prevval = (int)*SHORTP(cp, 0); + else if ( size == 4 ) prevval = (int)*LONGP(cp, 0); + if ( size == 1 ) val = (int)*CHARP(cp, size); + else if ( size == 2 ) val = (int)*SHORTP(cp, size); + else if ( size == 4 ) val = (int)*LONGP(cp, size); + prevdiff = val - prevval; + + for ( i=size; i max ) + max = extremediff; + } + prevextremevalid = 1; + prevextreme = prevval; + } + prevval = val; + if ( diff != 0 ) + prevdiff = diff; + } + return PyLong_FromLong(max); } static PyObject * audioop_cross(PyObject *self, PyObject *args) { - signed char *cp; - int len, size, val = 0; - int i; - int prevval, ncross; - - if ( !PyArg_ParseTuple(args, "s#i:cross", &cp, &len, &size) ) - return 0; - if ( size != 1 && size != 2 && size != 4 ) { - PyErr_SetString(AudioopError, "Size should be 1, 2 or 4"); - return 0; - } - ncross = -1; - prevval = 17; /* Anything <> 0,1 */ - for ( i=0; i> 7; - else if ( size == 2 ) val = ((int)*SHORTP(cp, i)) >> 15; - else if ( size == 4 ) val = ((int)*LONGP(cp, i)) >> 31; - val = val & 1; - if ( val != prevval ) ncross++; - prevval = val; - } - return PyLong_FromLong(ncross); + signed char *cp; + int len, size, val = 0; + int i; + int prevval, ncross; + + if ( !PyArg_ParseTuple(args, "s#i:cross", &cp, &len, &size) ) + return 0; + if ( size != 1 && size != 2 && size != 4 ) { + PyErr_SetString(AudioopError, "Size should be 1, 2 or 4"); + return 0; + } + ncross = -1; + prevval = 17; /* Anything <> 0,1 */ + for ( i=0; i> 7; + else if ( size == 2 ) val = ((int)*SHORTP(cp, i)) >> 15; + else if ( size == 4 ) val = ((int)*LONGP(cp, i)) >> 31; + val = val & 1; + if ( val != prevval ) ncross++; + prevval = val; + } + return PyLong_FromLong(ncross); } static PyObject * audioop_mul(PyObject *self, PyObject *args) { - signed char *cp, *ncp; - int len, size, val = 0; - double factor, fval, maxval; - PyObject *rv; - int i; - - if ( !PyArg_ParseTuple(args, "s#id:mul", &cp, &len, &size, &factor ) ) - return 0; - - if ( size == 1 ) maxval = (double) 0x7f; - else if ( size == 2 ) maxval = (double) 0x7fff; - else if ( size == 4 ) maxval = (double) 0x7fffffff; - else { - PyErr_SetString(AudioopError, "Size should be 1, 2 or 4"); - return 0; - } - - rv = PyBytes_FromStringAndSize(NULL, len); - if ( rv == 0 ) - return 0; - ncp = (signed char *)PyBytes_AsString(rv); - - - for ( i=0; i < len; i += size ) { - 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; - if ( fval > maxval ) fval = maxval; - else if ( fval < -maxval ) fval = -maxval; - val = (int)fval; - 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; - } - return rv; + signed char *cp, *ncp; + int len, size, val = 0; + double factor, fval, maxval; + PyObject *rv; + int i; + + if ( !PyArg_ParseTuple(args, "s#id:mul", &cp, &len, &size, &factor ) ) + return 0; + + if ( size == 1 ) maxval = (double) 0x7f; + else if ( size == 2 ) maxval = (double) 0x7fff; + else if ( size == 4 ) maxval = (double) 0x7fffffff; + else { + PyErr_SetString(AudioopError, "Size should be 1, 2 or 4"); + return 0; + } + + rv = PyBytes_FromStringAndSize(NULL, len); + if ( rv == 0 ) + return 0; + ncp = (signed char *)PyBytes_AsString(rv); + + + for ( i=0; i < len; i += size ) { + 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; + if ( fval > maxval ) fval = maxval; + else if ( fval < -maxval ) fval = -maxval; + val = (int)fval; + 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; + } + return rv; } static PyObject * audioop_tomono(PyObject *self, PyObject *args) { - Py_buffer pcp; - signed char *cp, *ncp; - int len, size, val1 = 0, val2 = 0; - double fac1, fac2, fval, maxval; - PyObject *rv; - int i; - - if ( !PyArg_ParseTuple(args, "s*idd:tomono", - &pcp, &size, &fac1, &fac2 ) ) - return 0; - cp = pcp.buf; - len = pcp.len; - - if ( size == 1 ) maxval = (double) 0x7f; - else if ( size == 2 ) maxval = (double) 0x7fff; - else if ( size == 4 ) maxval = (double) 0x7fffffff; - else { - PyBuffer_Release(&pcp); - PyErr_SetString(AudioopError, "Size should be 1, 2 or 4"); - return 0; - } - - rv = PyBytes_FromStringAndSize(NULL, len/2); - if ( rv == 0 ) - return 0; - ncp = (signed char *)PyBytes_AsString(rv); - - - for ( i=0; i < len; i += size*2 ) { - if ( size == 1 ) val1 = (int)*CHARP(cp, i); - else if ( size == 2 ) val1 = (int)*SHORTP(cp, i); - else if ( size == 4 ) val1 = (int)*LONGP(cp, i); - 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; - if ( fval > maxval ) fval = maxval; - else if ( fval < -maxval ) fval = -maxval; - val1 = (int)fval; - 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; - } - PyBuffer_Release(&pcp); - return rv; + Py_buffer pcp; + signed char *cp, *ncp; + int len, size, val1 = 0, val2 = 0; + double fac1, fac2, fval, maxval; + PyObject *rv; + int i; + + if ( !PyArg_ParseTuple(args, "s*idd:tomono", + &pcp, &size, &fac1, &fac2 ) ) + return 0; + cp = pcp.buf; + len = pcp.len; + + if ( size == 1 ) maxval = (double) 0x7f; + else if ( size == 2 ) maxval = (double) 0x7fff; + else if ( size == 4 ) maxval = (double) 0x7fffffff; + else { + PyBuffer_Release(&pcp); + PyErr_SetString(AudioopError, "Size should be 1, 2 or 4"); + return 0; + } + + rv = PyBytes_FromStringAndSize(NULL, len/2); + if ( rv == 0 ) + return 0; + ncp = (signed char *)PyBytes_AsString(rv); + + + for ( i=0; i < len; i += size*2 ) { + if ( size == 1 ) val1 = (int)*CHARP(cp, i); + else if ( size == 2 ) val1 = (int)*SHORTP(cp, i); + else if ( size == 4 ) val1 = (int)*LONGP(cp, i); + 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; + if ( fval > maxval ) fval = maxval; + else if ( fval < -maxval ) fval = -maxval; + val1 = (int)fval; + 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; + } + PyBuffer_Release(&pcp); + return rv; } static PyObject * audioop_tostereo(PyObject *self, PyObject *args) { - signed char *cp, *ncp; - int len, new_len, size, val1, val2, val = 0; - double fac1, fac2, fval, maxval; - PyObject *rv; - int i; - - if ( !PyArg_ParseTuple(args, "s#idd:tostereo", - &cp, &len, &size, &fac1, &fac2 ) ) - return 0; - - if ( size == 1 ) maxval = (double) 0x7f; - else if ( size == 2 ) maxval = (double) 0x7fff; - else if ( size == 4 ) maxval = (double) 0x7fffffff; - else { - PyErr_SetString(AudioopError, "Size should be 1, 2 or 4"); - return 0; - } - - new_len = len*2; - if (new_len < 0) { - PyErr_SetString(PyExc_MemoryError, - "not enough memory for output buffer"); - return 0; - } + signed char *cp, *ncp; + int len, new_len, size, val1, val2, val = 0; + double fac1, fac2, fval, maxval; + PyObject *rv; + int i; + + if ( !PyArg_ParseTuple(args, "s#idd:tostereo", + &cp, &len, &size, &fac1, &fac2 ) ) + return 0; + + if ( size == 1 ) maxval = (double) 0x7f; + else if ( size == 2 ) maxval = (double) 0x7fff; + else if ( size == 4 ) maxval = (double) 0x7fffffff; + else { + PyErr_SetString(AudioopError, "Size should be 1, 2 or 4"); + return 0; + } + + new_len = len*2; + if (new_len < 0) { + PyErr_SetString(PyExc_MemoryError, + "not enough memory for output buffer"); + return 0; + } + + rv = PyBytes_FromStringAndSize(NULL, new_len); + if ( rv == 0 ) + return 0; + ncp = (signed char *)PyBytes_AsString(rv); - rv = PyBytes_FromStringAndSize(NULL, new_len); - if ( rv == 0 ) - return 0; - ncp = (signed char *)PyBytes_AsString(rv); - - - for ( i=0; i < len; i += size ) { - 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*fac1; - if ( fval > maxval ) fval = maxval; - else if ( fval < -maxval ) fval = -maxval; - val1 = (int)fval; - - fval = (double)val*fac2; - if ( fval > maxval ) fval = maxval; - else if ( fval < -maxval ) fval = -maxval; - val2 = (int)fval; - - 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; - - if ( size == 1 ) *CHARP(ncp, i*2+1) = (signed char)val2; - else if ( size == 2 ) *SHORTP(ncp, i*2+2) = (short)val2; - else if ( size == 4 ) *LONGP(ncp, i*2+4) = (Py_Int32)val2; - } - return rv; + + for ( i=0; i < len; i += size ) { + 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*fac1; + if ( fval > maxval ) fval = maxval; + else if ( fval < -maxval ) fval = -maxval; + val1 = (int)fval; + + fval = (double)val*fac2; + if ( fval > maxval ) fval = maxval; + else if ( fval < -maxval ) fval = -maxval; + val2 = (int)fval; + + 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; + + if ( size == 1 ) *CHARP(ncp, i*2+1) = (signed char)val2; + else if ( size == 2 ) *SHORTP(ncp, i*2+2) = (short)val2; + else if ( size == 4 ) *LONGP(ncp, i*2+4) = (Py_Int32)val2; + } + return rv; } static PyObject * audioop_add(PyObject *self, PyObject *args) { - signed char *cp1, *cp2, *ncp; - int len1, len2, size, val1 = 0, val2 = 0, maxval, newval; - PyObject *rv; - int i; - - if ( !PyArg_ParseTuple(args, "s#s#i:add", - &cp1, &len1, &cp2, &len2, &size ) ) - return 0; - - if ( len1 != len2 ) { - PyErr_SetString(AudioopError, "Lengths should be the same"); - return 0; - } - - if ( size == 1 ) maxval = 0x7f; - else if ( size == 2 ) maxval = 0x7fff; - else if ( size == 4 ) maxval = 0x7fffffff; - else { - PyErr_SetString(AudioopError, "Size should be 1, 2 or 4"); - return 0; - } - - rv = PyBytes_FromStringAndSize(NULL, len1); - if ( rv == 0 ) - return 0; - ncp = (signed char *)PyBytes_AsString(rv); - - for ( i=0; i < len1; i += size ) { - if ( size == 1 ) val1 = (int)*CHARP(cp1, i); - else if ( size == 2 ) val1 = (int)*SHORTP(cp1, i); - else if ( size == 4 ) val1 = (int)*LONGP(cp1, i); - - if ( size == 1 ) val2 = (int)*CHARP(cp2, i); - else if ( size == 2 ) val2 = (int)*SHORTP(cp2, i); - else if ( size == 4 ) val2 = (int)*LONGP(cp2, i); - - newval = val1 + val2; - /* truncate in case of overflow */ - if (newval > maxval) newval = maxval; - else if (newval < -maxval) newval = -maxval; - else if (size == 4 && (newval^val1) < 0 && (newval^val2) < 0) - newval = val1 > 0 ? maxval : - maxval; - - if ( size == 1 ) *CHARP(ncp, i) = (signed char)newval; - else if ( size == 2 ) *SHORTP(ncp, i) = (short)newval; - else if ( size == 4 ) *LONGP(ncp, i) = (Py_Int32)newval; - } - return rv; + signed char *cp1, *cp2, *ncp; + int len1, len2, size, val1 = 0, val2 = 0, maxval, newval; + PyObject *rv; + int i; + + if ( !PyArg_ParseTuple(args, "s#s#i:add", + &cp1, &len1, &cp2, &len2, &size ) ) + return 0; + + if ( len1 != len2 ) { + PyErr_SetString(AudioopError, "Lengths should be the same"); + return 0; + } + + if ( size == 1 ) maxval = 0x7f; + else if ( size == 2 ) maxval = 0x7fff; + else if ( size == 4 ) maxval = 0x7fffffff; + else { + PyErr_SetString(AudioopError, "Size should be 1, 2 or 4"); + return 0; + } + + rv = PyBytes_FromStringAndSize(NULL, len1); + if ( rv == 0 ) + return 0; + ncp = (signed char *)PyBytes_AsString(rv); + + for ( i=0; i < len1; i += size ) { + if ( size == 1 ) val1 = (int)*CHARP(cp1, i); + else if ( size == 2 ) val1 = (int)*SHORTP(cp1, i); + else if ( size == 4 ) val1 = (int)*LONGP(cp1, i); + + if ( size == 1 ) val2 = (int)*CHARP(cp2, i); + else if ( size == 2 ) val2 = (int)*SHORTP(cp2, i); + else if ( size == 4 ) val2 = (int)*LONGP(cp2, i); + + newval = val1 + val2; + /* truncate in case of overflow */ + if (newval > maxval) newval = maxval; + else if (newval < -maxval) newval = -maxval; + else if (size == 4 && (newval^val1) < 0 && (newval^val2) < 0) + newval = val1 > 0 ? maxval : - maxval; + + if ( size == 1 ) *CHARP(ncp, i) = (signed char)newval; + else if ( size == 2 ) *SHORTP(ncp, i) = (short)newval; + else if ( size == 4 ) *LONGP(ncp, i) = (Py_Int32)newval; + } + return rv; } static PyObject * audioop_bias(PyObject *self, PyObject *args) { - signed char *cp, *ncp; - int len, size, val = 0; - PyObject *rv; - int i; - int bias; - - if ( !PyArg_ParseTuple(args, "s#ii:bias", - &cp, &len, &size , &bias) ) - return 0; - - if ( size != 1 && size != 2 && size != 4) { - PyErr_SetString(AudioopError, "Size should be 1, 2 or 4"); - return 0; - } - - rv = PyBytes_FromStringAndSize(NULL, len); - if ( rv == 0 ) - return 0; - ncp = (signed char *)PyBytes_AsString(rv); - - - for ( i=0; i < len; i += size ) { - 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); - - if ( size == 1 ) *CHARP(ncp, i) = (signed char)(val+bias); - else if ( size == 2 ) *SHORTP(ncp, i) = (short)(val+bias); - else if ( size == 4 ) *LONGP(ncp, i) = (Py_Int32)(val+bias); - } - return rv; + signed char *cp, *ncp; + int len, size, val = 0; + PyObject *rv; + int i; + int bias; + + if ( !PyArg_ParseTuple(args, "s#ii:bias", + &cp, &len, &size , &bias) ) + return 0; + + if ( size != 1 && size != 2 && size != 4) { + PyErr_SetString(AudioopError, "Size should be 1, 2 or 4"); + return 0; + } + + rv = PyBytes_FromStringAndSize(NULL, len); + if ( rv == 0 ) + return 0; + ncp = (signed char *)PyBytes_AsString(rv); + + + for ( i=0; i < len; i += size ) { + 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); + + if ( size == 1 ) *CHARP(ncp, i) = (signed char)(val+bias); + else if ( size == 2 ) *SHORTP(ncp, i) = (short)(val+bias); + else if ( size == 4 ) *LONGP(ncp, i) = (Py_Int32)(val+bias); + } + return rv; } static PyObject * audioop_reverse(PyObject *self, PyObject *args) { - signed char *cp; - unsigned char *ncp; - int len, size, val = 0; - PyObject *rv; - int i, j; - - if ( !PyArg_ParseTuple(args, "s#i:reverse", - &cp, &len, &size) ) - return 0; - - if ( size != 1 && size != 2 && size != 4 ) { - PyErr_SetString(AudioopError, "Size should be 1, 2 or 4"); - return 0; - } - - rv = PyBytes_FromStringAndSize(NULL, len); - if ( rv == 0 ) - return 0; - ncp = (unsigned char *)PyBytes_AsString(rv); - - for ( i=0; i < len; i += size ) { - if ( size == 1 ) val = ((int)*CHARP(cp, i)) << 8; - else if ( size == 2 ) val = (int)*SHORTP(cp, i); - else if ( size == 4 ) val = ((int)*LONGP(cp, i)) >> 16; - - j = len - i - size; - - if ( size == 1 ) *CHARP(ncp, j) = (signed char)(val >> 8); - else if ( size == 2 ) *SHORTP(ncp, j) = (short)(val); - else if ( size == 4 ) *LONGP(ncp, j) = (Py_Int32)(val<<16); - } - return rv; + signed char *cp; + unsigned char *ncp; + int len, size, val = 0; + PyObject *rv; + int i, j; + + if ( !PyArg_ParseTuple(args, "s#i:reverse", + &cp, &len, &size) ) + return 0; + + if ( size != 1 && size != 2 && size != 4 ) { + PyErr_SetString(AudioopError, "Size should be 1, 2 or 4"); + return 0; + } + + rv = PyBytes_FromStringAndSize(NULL, len); + if ( rv == 0 ) + return 0; + ncp = (unsigned char *)PyBytes_AsString(rv); + + for ( i=0; i < len; i += size ) { + if ( size == 1 ) val = ((int)*CHARP(cp, i)) << 8; + else if ( size == 2 ) val = (int)*SHORTP(cp, i); + else if ( size == 4 ) val = ((int)*LONGP(cp, i)) >> 16; + + j = len - i - size; + + if ( size == 1 ) *CHARP(ncp, j) = (signed char)(val >> 8); + else if ( size == 2 ) *SHORTP(ncp, j) = (short)(val); + else if ( size == 4 ) *LONGP(ncp, j) = (Py_Int32)(val<<16); + } + return rv; } static PyObject * audioop_lin2lin(PyObject *self, PyObject *args) { - signed char *cp; - unsigned char *ncp; - int len, new_len, size, size2, val = 0; - PyObject *rv; - int i, j; - - if ( !PyArg_ParseTuple(args, "s#ii:lin2lin", - &cp, &len, &size, &size2) ) - return 0; - - if ( (size != 1 && size != 2 && size != 4) || - (size2 != 1 && size2 != 2 && size2 != 4)) { - PyErr_SetString(AudioopError, "Size should be 1, 2 or 4"); - return 0; - } - - new_len = (len/size)*size2; - if (new_len < 0) { - PyErr_SetString(PyExc_MemoryError, - "not enough memory for output buffer"); - return 0; - } - rv = PyBytes_FromStringAndSize(NULL, new_len); - if ( rv == 0 ) - return 0; - ncp = (unsigned char *)PyBytes_AsString(rv); - - for ( i=0, j=0; i < len; i += size, j += size2 ) { - if ( size == 1 ) val = ((int)*CHARP(cp, i)) << 8; - else if ( size == 2 ) val = (int)*SHORTP(cp, i); - else if ( size == 4 ) val = ((int)*LONGP(cp, i)) >> 16; - - if ( size2 == 1 ) *CHARP(ncp, j) = (signed char)(val >> 8); - else if ( size2 == 2 ) *SHORTP(ncp, j) = (short)(val); - else if ( size2 == 4 ) *LONGP(ncp, j) = (Py_Int32)(val<<16); - } - return rv; + signed char *cp; + unsigned char *ncp; + int len, new_len, size, size2, val = 0; + PyObject *rv; + int i, j; + + if ( !PyArg_ParseTuple(args, "s#ii:lin2lin", + &cp, &len, &size, &size2) ) + return 0; + + if ( (size != 1 && size != 2 && size != 4) || + (size2 != 1 && size2 != 2 && size2 != 4)) { + PyErr_SetString(AudioopError, "Size should be 1, 2 or 4"); + return 0; + } + + new_len = (len/size)*size2; + if (new_len < 0) { + PyErr_SetString(PyExc_MemoryError, + "not enough memory for output buffer"); + return 0; + } + rv = PyBytes_FromStringAndSize(NULL, new_len); + if ( rv == 0 ) + return 0; + ncp = (unsigned char *)PyBytes_AsString(rv); + + for ( i=0, j=0; i < len; i += size, j += size2 ) { + if ( size == 1 ) val = ((int)*CHARP(cp, i)) << 8; + else if ( size == 2 ) val = (int)*SHORTP(cp, i); + else if ( size == 4 ) val = ((int)*LONGP(cp, i)) >> 16; + + if ( size2 == 1 ) *CHARP(ncp, j) = (signed char)(val >> 8); + else if ( size2 == 2 ) *SHORTP(ncp, j) = (short)(val); + else if ( size2 == 4 ) *LONGP(ncp, j) = (Py_Int32)(val<<16); + } + return rv; } static int gcd(int a, int b) { - while (b > 0) { - int tmp = a % b; - a = b; - b = tmp; - } - return a; + while (b > 0) { + int tmp = a % b; + a = b; + b = tmp; + } + return a; } static PyObject * audioop_ratecv(PyObject *self, PyObject *args) { - char *cp, *ncp; - int len, size, nchannels, inrate, outrate, weightA, weightB; - int chan, d, *prev_i, *cur_i, cur_o; - PyObject *state, *samps, *str, *rv = NULL; - int bytes_per_frame; - size_t alloc_size; - - weightA = 1; - weightB = 0; - if (!PyArg_ParseTuple(args, "s#iiiiO|ii:ratecv", &cp, &len, &size, - &nchannels, &inrate, &outrate, &state, - &weightA, &weightB)) - return NULL; - if (size != 1 && size != 2 && size != 4) { - PyErr_SetString(AudioopError, "Size should be 1, 2 or 4"); - return NULL; - } - if (nchannels < 1) { - PyErr_SetString(AudioopError, "# of channels should be >= 1"); - return NULL; - } - bytes_per_frame = size * nchannels; - if (bytes_per_frame / nchannels != size) { - /* This overflow test is rigorously correct because - both multiplicands are >= 1. Use the argument names - from the docs for the error msg. */ - PyErr_SetString(PyExc_OverflowError, - "width * nchannels too big for a C int"); - return NULL; - } - if (weightA < 1 || weightB < 0) { - PyErr_SetString(AudioopError, - "weightA should be >= 1, weightB should be >= 0"); - return NULL; - } - if (len % bytes_per_frame != 0) { - PyErr_SetString(AudioopError, "not a whole number of frames"); - return NULL; - } - if (inrate <= 0 || outrate <= 0) { - PyErr_SetString(AudioopError, "sampling rate not > 0"); - return NULL; - } - /* divide inrate and outrate by their greatest common divisor */ - d = gcd(inrate, outrate); - inrate /= d; - outrate /= d; - - alloc_size = sizeof(int) * (unsigned)nchannels; - if (alloc_size < (unsigned)nchannels) { - PyErr_SetString(PyExc_MemoryError, - "not enough memory for output buffer"); - return 0; - } - prev_i = (int *) malloc(alloc_size); - cur_i = (int *) malloc(alloc_size); - if (prev_i == NULL || cur_i == NULL) { - (void) PyErr_NoMemory(); + char *cp, *ncp; + int len, size, nchannels, inrate, outrate, weightA, weightB; + int chan, d, *prev_i, *cur_i, cur_o; + PyObject *state, *samps, *str, *rv = NULL; + int bytes_per_frame; + size_t alloc_size; + + weightA = 1; + weightB = 0; + if (!PyArg_ParseTuple(args, "s#iiiiO|ii:ratecv", &cp, &len, &size, + &nchannels, &inrate, &outrate, &state, + &weightA, &weightB)) + return NULL; + if (size != 1 && size != 2 && size != 4) { + PyErr_SetString(AudioopError, "Size should be 1, 2 or 4"); + return NULL; + } + if (nchannels < 1) { + PyErr_SetString(AudioopError, "# of channels should be >= 1"); + return NULL; + } + bytes_per_frame = size * nchannels; + if (bytes_per_frame / nchannels != size) { + /* This overflow test is rigorously correct because + both multiplicands are >= 1. Use the argument names + from the docs for the error msg. */ + PyErr_SetString(PyExc_OverflowError, + "width * nchannels too big for a C int"); + return NULL; + } + if (weightA < 1 || weightB < 0) { + PyErr_SetString(AudioopError, + "weightA should be >= 1, weightB should be >= 0"); + return NULL; + } + if (len % bytes_per_frame != 0) { + PyErr_SetString(AudioopError, "not a whole number of frames"); + return NULL; + } + if (inrate <= 0 || outrate <= 0) { + PyErr_SetString(AudioopError, "sampling rate not > 0"); + return NULL; + } + /* divide inrate and outrate by their greatest common divisor */ + d = gcd(inrate, outrate); + inrate /= d; + outrate /= d; + + alloc_size = sizeof(int) * (unsigned)nchannels; + if (alloc_size < (unsigned)nchannels) { + PyErr_SetString(PyExc_MemoryError, + "not enough memory for output buffer"); + return 0; + } + prev_i = (int *) malloc(alloc_size); + cur_i = (int *) malloc(alloc_size); + if (prev_i == NULL || cur_i == NULL) { + (void) PyErr_NoMemory(); + goto exit; + } + + len /= bytes_per_frame; /* # of frames */ + + if (state == Py_None) { + d = -outrate; + for (chan = 0; chan < nchannels; chan++) + prev_i[chan] = cur_i[chan] = 0; + } + else { + if (!PyArg_ParseTuple(state, + "iO!;audioop.ratecv: illegal state argument", + &d, &PyTuple_Type, &samps)) + goto exit; + if (PyTuple_Size(samps) != nchannels) { + PyErr_SetString(AudioopError, + "illegal state argument"); + goto exit; + } + for (chan = 0; chan < nchannels; chan++) { + if (!PyArg_ParseTuple(PyTuple_GetItem(samps, chan), + "ii:ratecv", &prev_i[chan], + &cur_i[chan])) goto exit; } + } - len /= bytes_per_frame; /* # of frames */ + /* str <- Space for the output buffer. */ + { + /* There are len input frames, so we need (mathematically) + ceiling(len*outrate/inrate) output frames, and each frame + requires bytes_per_frame bytes. Computing this + without spurious overflow is the challenge; we can + settle for a reasonable upper bound, though. */ + int ceiling; /* the number of output frames */ + int nbytes; /* the number of output bytes needed */ + int q = len / inrate; + /* Now len = q * inrate + r exactly (with r = len % inrate), + and this is less than q * inrate + inrate = (q+1)*inrate. + So a reasonable upper bound on len*outrate/inrate is + ((q+1)*inrate)*outrate/inrate = + (q+1)*outrate. + */ + ceiling = (q+1) * outrate; + nbytes = ceiling * bytes_per_frame; + /* See whether anything overflowed; if not, get the space. */ + if (q+1 < 0 || + ceiling / outrate != q+1 || + nbytes / bytes_per_frame != ceiling) + str = NULL; + else + str = PyBytes_FromStringAndSize(NULL, nbytes); - if (state == Py_None) { - d = -outrate; + if (str == NULL) { + PyErr_SetString(PyExc_MemoryError, + "not enough memory for output buffer"); + goto exit; + } + } + ncp = PyBytes_AsString(str); + + for (;;) { + while (d < 0) { + if (len == 0) { + samps = PyTuple_New(nchannels); + if (samps == NULL) + goto exit; for (chan = 0; chan < nchannels; chan++) - prev_i[chan] = cur_i[chan] = 0; - } - else { - if (!PyArg_ParseTuple(state, - "iO!;audioop.ratecv: illegal state argument", - &d, &PyTuple_Type, &samps)) - goto exit; - if (PyTuple_Size(samps) != nchannels) { - PyErr_SetString(AudioopError, - "illegal state argument"); - goto exit; - } - for (chan = 0; chan < nchannels; chan++) { - if (!PyArg_ParseTuple(PyTuple_GetItem(samps, chan), - "ii:ratecv", &prev_i[chan], - &cur_i[chan])) - goto exit; - } - } - - /* str <- Space for the output buffer. */ - { - /* There are len input frames, so we need (mathematically) - ceiling(len*outrate/inrate) output frames, and each frame - requires bytes_per_frame bytes. Computing this - without spurious overflow is the challenge; we can - settle for a reasonable upper bound, though. */ - int ceiling; /* the number of output frames */ - int nbytes; /* the number of output bytes needed */ - int q = len / inrate; - /* Now len = q * inrate + r exactly (with r = len % inrate), - and this is less than q * inrate + inrate = (q+1)*inrate. - So a reasonable upper bound on len*outrate/inrate is - ((q+1)*inrate)*outrate/inrate = - (q+1)*outrate. - */ - ceiling = (q+1) * outrate; - nbytes = ceiling * bytes_per_frame; - /* See whether anything overflowed; if not, get the space. */ - if (q+1 < 0 || - ceiling / outrate != q+1 || - nbytes / bytes_per_frame != ceiling) - str = NULL; - else - str = PyBytes_FromStringAndSize(NULL, nbytes); - - if (str == NULL) { - PyErr_SetString(PyExc_MemoryError, - "not enough memory for output buffer"); - goto exit; - } - } - ncp = PyBytes_AsString(str); - - for (;;) { - while (d < 0) { - if (len == 0) { - samps = PyTuple_New(nchannels); - if (samps == NULL) - goto exit; - for (chan = 0; chan < nchannels; chan++) - PyTuple_SetItem(samps, chan, - Py_BuildValue("(ii)", - prev_i[chan], - cur_i[chan])); - if (PyErr_Occurred()) - goto exit; - /* We have checked before that the length - * of the string fits into int. */ - len = (int)(ncp - PyBytes_AsString(str)); - rv = PyBytes_FromStringAndSize - (PyBytes_AsString(str), len); - Py_DECREF(str); - str = rv; - if (str == NULL) - goto exit; - rv = Py_BuildValue("(O(iO))", str, d, samps); - Py_DECREF(samps); - Py_DECREF(str); - goto exit; /* return rv */ - } - for (chan = 0; chan < nchannels; chan++) { - prev_i[chan] = cur_i[chan]; - if (size == 1) - cur_i[chan] = ((int)*CHARP(cp, 0)) << 8; - else if (size == 2) - cur_i[chan] = (int)*SHORTP(cp, 0); - else if (size == 4) - cur_i[chan] = ((int)*LONGP(cp, 0)) >> 16; - cp += size; - /* implements a simple digital filter */ - cur_i[chan] = - (weightA * cur_i[chan] + - weightB * prev_i[chan]) / - (weightA + weightB); - } - len--; - d += outrate; - } - while (d >= 0) { - for (chan = 0; chan < nchannels; chan++) { - cur_o = (prev_i[chan] * d + - cur_i[chan] * (outrate - d)) / - outrate; - if (size == 1) - *CHARP(ncp, 0) = (signed char)(cur_o >> 8); - else if (size == 2) - *SHORTP(ncp, 0) = (short)(cur_o); - else if (size == 4) - *LONGP(ncp, 0) = (Py_Int32)(cur_o<<16); - ncp += size; - } - d -= inrate; - } + PyTuple_SetItem(samps, chan, + Py_BuildValue("(ii)", + prev_i[chan], + cur_i[chan])); + if (PyErr_Occurred()) + goto exit; + /* We have checked before that the length + * of the string fits into int. */ + len = (int)(ncp - PyBytes_AsString(str)); + rv = PyBytes_FromStringAndSize + (PyBytes_AsString(str), len); + Py_DECREF(str); + str = rv; + if (str == NULL) + goto exit; + rv = Py_BuildValue("(O(iO))", str, d, samps); + Py_DECREF(samps); + Py_DECREF(str); + goto exit; /* return rv */ + } + for (chan = 0; chan < nchannels; chan++) { + prev_i[chan] = cur_i[chan]; + if (size == 1) + cur_i[chan] = ((int)*CHARP(cp, 0)) << 8; + else if (size == 2) + cur_i[chan] = (int)*SHORTP(cp, 0); + else if (size == 4) + cur_i[chan] = ((int)*LONGP(cp, 0)) >> 16; + cp += size; + /* implements a simple digital filter */ + cur_i[chan] = + (weightA * cur_i[chan] + + weightB * prev_i[chan]) / + (weightA + weightB); + } + len--; + d += outrate; + } + while (d >= 0) { + for (chan = 0; chan < nchannels; chan++) { + cur_o = (prev_i[chan] * d + + cur_i[chan] * (outrate - d)) / + outrate; + if (size == 1) + *CHARP(ncp, 0) = (signed char)(cur_o >> 8); + else if (size == 2) + *SHORTP(ncp, 0) = (short)(cur_o); + else if (size == 4) + *LONGP(ncp, 0) = (Py_Int32)(cur_o<<16); + ncp += size; + } + d -= inrate; } + } exit: - if (prev_i != NULL) - free(prev_i); - if (cur_i != NULL) - free(cur_i); - return rv; + if (prev_i != NULL) + free(prev_i); + if (cur_i != NULL) + free(cur_i); + return rv; } static PyObject * audioop_lin2ulaw(PyObject *self, PyObject *args) { - signed char *cp; - unsigned char *ncp; - int len, size, val = 0; - PyObject *rv; - int i; - - if ( !PyArg_ParseTuple(args, "s#i:lin2ulaw", - &cp, &len, &size) ) - return 0 ; - - if ( size != 1 && size != 2 && size != 4) { - PyErr_SetString(AudioopError, "Size should be 1, 2 or 4"); - return 0; - } - - rv = PyBytes_FromStringAndSize(NULL, len/size); - if ( rv == 0 ) - return 0; - ncp = (unsigned char *)PyBytes_AsString(rv); - - for ( i=0; i < len; i += size ) { - if ( size == 1 ) val = ((int)*CHARP(cp, i)) << 8; - else if ( size == 2 ) val = (int)*SHORTP(cp, i); - else if ( size == 4 ) val = ((int)*LONGP(cp, i)) >> 16; - - *ncp++ = st_14linear2ulaw(val); - } - return rv; + signed char *cp; + unsigned char *ncp; + int len, size, val = 0; + PyObject *rv; + int i; + + if ( !PyArg_ParseTuple(args, "s#i:lin2ulaw", + &cp, &len, &size) ) + return 0 ; + + if ( size != 1 && size != 2 && size != 4) { + PyErr_SetString(AudioopError, "Size should be 1, 2 or 4"); + return 0; + } + + rv = PyBytes_FromStringAndSize(NULL, len/size); + if ( rv == 0 ) + return 0; + ncp = (unsigned char *)PyBytes_AsString(rv); + + for ( i=0; i < len; i += size ) { + if ( size == 1 ) val = ((int)*CHARP(cp, i)) << 8; + else if ( size == 2 ) val = (int)*SHORTP(cp, i); + else if ( size == 4 ) val = ((int)*LONGP(cp, i)) >> 16; + + *ncp++ = st_14linear2ulaw(val); + } + return rv; } static PyObject * audioop_ulaw2lin(PyObject *self, PyObject *args) { - unsigned char *cp; - unsigned char cval; - signed char *ncp; - int len, new_len, size, val; - PyObject *rv; - int i; - - if ( !PyArg_ParseTuple(args, "s#i:ulaw2lin", - &cp, &len, &size) ) - return 0; - - if ( size != 1 && size != 2 && size != 4) { - PyErr_SetString(AudioopError, "Size should be 1, 2 or 4"); - return 0; - } - - new_len = len*size; - if (new_len < 0) { - PyErr_SetString(PyExc_MemoryError, - "not enough memory for output buffer"); - return 0; - } - rv = PyBytes_FromStringAndSize(NULL, new_len); - if ( rv == 0 ) - return 0; - ncp = (signed char *)PyBytes_AsString(rv); - - for ( i=0; i < new_len; i += size ) { - cval = *cp++; - val = st_ulaw2linear16(cval); - - if ( size == 1 ) *CHARP(ncp, i) = (signed char)(val >> 8); - else if ( size == 2 ) *SHORTP(ncp, i) = (short)(val); - else if ( size == 4 ) *LONGP(ncp, i) = (Py_Int32)(val<<16); - } - return rv; + unsigned char *cp; + unsigned char cval; + signed char *ncp; + int len, new_len, size, val; + PyObject *rv; + int i; + + if ( !PyArg_ParseTuple(args, "s#i:ulaw2lin", + &cp, &len, &size) ) + return 0; + + if ( size != 1 && size != 2 && size != 4) { + PyErr_SetString(AudioopError, "Size should be 1, 2 or 4"); + return 0; + } + + new_len = len*size; + if (new_len < 0) { + PyErr_SetString(PyExc_MemoryError, + "not enough memory for output buffer"); + return 0; + } + rv = PyBytes_FromStringAndSize(NULL, new_len); + if ( rv == 0 ) + return 0; + ncp = (signed char *)PyBytes_AsString(rv); + + for ( i=0; i < new_len; i += size ) { + cval = *cp++; + val = st_ulaw2linear16(cval); + + if ( size == 1 ) *CHARP(ncp, i) = (signed char)(val >> 8); + else if ( size == 2 ) *SHORTP(ncp, i) = (short)(val); + else if ( size == 4 ) *LONGP(ncp, i) = (Py_Int32)(val<<16); + } + return rv; } static PyObject * audioop_lin2alaw(PyObject *self, PyObject *args) { - signed char *cp; - unsigned char *ncp; - int len, size, val = 0; - PyObject *rv; - int i; - - if ( !PyArg_ParseTuple(args, "s#i:lin2alaw", - &cp, &len, &size) ) - return 0; - - if ( size != 1 && size != 2 && size != 4) { - PyErr_SetString(AudioopError, "Size should be 1, 2 or 4"); - return 0; - } - - rv = PyBytes_FromStringAndSize(NULL, len/size); - if ( rv == 0 ) - return 0; - ncp = (unsigned char *)PyBytes_AsString(rv); - - for ( i=0; i < len; i += size ) { - if ( size == 1 ) val = ((int)*CHARP(cp, i)) << 8; - else if ( size == 2 ) val = (int)*SHORTP(cp, i); - else if ( size == 4 ) val = ((int)*LONGP(cp, i)) >> 16; - - *ncp++ = st_linear2alaw(val); - } - return rv; + signed char *cp; + unsigned char *ncp; + int len, size, val = 0; + PyObject *rv; + int i; + + if ( !PyArg_ParseTuple(args, "s#i:lin2alaw", + &cp, &len, &size) ) + return 0; + + if ( size != 1 && size != 2 && size != 4) { + PyErr_SetString(AudioopError, "Size should be 1, 2 or 4"); + return 0; + } + + rv = PyBytes_FromStringAndSize(NULL, len/size); + if ( rv == 0 ) + return 0; + ncp = (unsigned char *)PyBytes_AsString(rv); + + for ( i=0; i < len; i += size ) { + if ( size == 1 ) val = ((int)*CHARP(cp, i)) << 8; + else if ( size == 2 ) val = (int)*SHORTP(cp, i); + else if ( size == 4 ) val = ((int)*LONGP(cp, i)) >> 16; + + *ncp++ = st_linear2alaw(val); + } + return rv; } static PyObject * audioop_alaw2lin(PyObject *self, PyObject *args) { - unsigned char *cp; - unsigned char cval; - signed char *ncp; - int len, new_len, size, val; - PyObject *rv; - int i; - - if ( !PyArg_ParseTuple(args, "s#i:alaw2lin", - &cp, &len, &size) ) - return 0; - - if ( size != 1 && size != 2 && size != 4) { - PyErr_SetString(AudioopError, "Size should be 1, 2 or 4"); - return 0; - } - - new_len = len*size; - if (new_len < 0) { - PyErr_SetString(PyExc_MemoryError, - "not enough memory for output buffer"); - return 0; - } - rv = PyBytes_FromStringAndSize(NULL, new_len); - if ( rv == 0 ) - return 0; - ncp = (signed char *)PyBytes_AsString(rv); - - for ( i=0; i < new_len; i += size ) { - cval = *cp++; - val = st_alaw2linear16(cval); - - if ( size == 1 ) *CHARP(ncp, i) = (signed char)(val >> 8); - else if ( size == 2 ) *SHORTP(ncp, i) = (short)(val); - else if ( size == 4 ) *LONGP(ncp, i) = (Py_Int32)(val<<16); - } - return rv; + unsigned char *cp; + unsigned char cval; + signed char *ncp; + int len, new_len, size, val; + PyObject *rv; + int i; + + if ( !PyArg_ParseTuple(args, "s#i:alaw2lin", + &cp, &len, &size) ) + return 0; + + if ( size != 1 && size != 2 && size != 4) { + PyErr_SetString(AudioopError, "Size should be 1, 2 or 4"); + return 0; + } + + new_len = len*size; + if (new_len < 0) { + PyErr_SetString(PyExc_MemoryError, + "not enough memory for output buffer"); + return 0; + } + rv = PyBytes_FromStringAndSize(NULL, new_len); + if ( rv == 0 ) + return 0; + ncp = (signed char *)PyBytes_AsString(rv); + + for ( i=0; i < new_len; i += size ) { + cval = *cp++; + val = st_alaw2linear16(cval); + + if ( size == 1 ) *CHARP(ncp, i) = (signed char)(val >> 8); + else if ( size == 2 ) *SHORTP(ncp, i) = (short)(val); + else if ( size == 4 ) *LONGP(ncp, i) = (Py_Int32)(val<<16); + } + return rv; } static PyObject * audioop_lin2adpcm(PyObject *self, PyObject *args) { - signed char *cp; - signed char *ncp; - int len, size, val = 0, step, valpred, delta, - index, sign, vpdiff, diff; - PyObject *rv, *state, *str; - int i, outputbuffer = 0, bufferstep; - - if ( !PyArg_ParseTuple(args, "s#iO:lin2adpcm", - &cp, &len, &size, &state) ) - return 0; - - - if ( size != 1 && size != 2 && size != 4) { - PyErr_SetString(AudioopError, "Size should be 1, 2 or 4"); - return 0; - } - - str = PyBytes_FromStringAndSize(NULL, len/(size*2)); - if ( str == 0 ) - return 0; - ncp = (signed char *)PyBytes_AsString(str); - - /* Decode state, should have (value, step) */ - if ( state == Py_None ) { - /* First time, it seems. Set defaults */ - valpred = 0; - step = 7; - index = 0; - } else if ( !PyArg_ParseTuple(state, "ii", &valpred, &index) ) - return 0; + signed char *cp; + signed char *ncp; + int len, size, val = 0, step, valpred, delta, + index, sign, vpdiff, diff; + PyObject *rv, *state, *str; + int i, outputbuffer = 0, bufferstep; + + if ( !PyArg_ParseTuple(args, "s#iO:lin2adpcm", + &cp, &len, &size, &state) ) + return 0; + + + if ( size != 1 && size != 2 && size != 4) { + PyErr_SetString(AudioopError, "Size should be 1, 2 or 4"); + return 0; + } + + str = PyBytes_FromStringAndSize(NULL, len/(size*2)); + if ( str == 0 ) + return 0; + ncp = (signed char *)PyBytes_AsString(str); + + /* Decode state, should have (value, step) */ + if ( state == Py_None ) { + /* First time, it seems. Set defaults */ + valpred = 0; + step = 7; + index = 0; + } else if ( !PyArg_ParseTuple(state, "ii", &valpred, &index) ) + return 0; + + step = stepsizeTable[index]; + bufferstep = 1; + + for ( i=0; i < len; i += size ) { + if ( size == 1 ) val = ((int)*CHARP(cp, i)) << 8; + else if ( size == 2 ) val = (int)*SHORTP(cp, i); + else if ( size == 4 ) val = ((int)*LONGP(cp, i)) >> 16; + + /* Step 1 - compute difference with previous value */ + diff = val - valpred; + sign = (diff < 0) ? 8 : 0; + if ( sign ) diff = (-diff); + + /* Step 2 - Divide and clamp */ + /* Note: + ** This code *approximately* computes: + ** delta = diff*4/step; + ** vpdiff = (delta+0.5)*step/4; + ** but in shift step bits are dropped. The net result of this + ** is that even if you have fast mul/div hardware you cannot + ** put it to good use since the fixup would be too expensive. + */ + delta = 0; + vpdiff = (step >> 3); + if ( diff >= step ) { + delta = 4; + diff -= step; + vpdiff += step; + } + step >>= 1; + if ( diff >= step ) { + delta |= 2; + diff -= step; + vpdiff += step; + } + step >>= 1; + if ( diff >= step ) { + delta |= 1; + vpdiff += step; + } + + /* Step 3 - Update previous value */ + if ( sign ) + valpred -= vpdiff; + else + valpred += vpdiff; + + /* Step 4 - Clamp previous value to 16 bits */ + if ( valpred > 32767 ) + valpred = 32767; + else if ( valpred < -32768 ) + valpred = -32768; + + /* Step 5 - Assemble value, update index and step values */ + delta |= sign; + + index += indexTable[delta]; + if ( index < 0 ) index = 0; + if ( index > 88 ) index = 88; step = stepsizeTable[index]; - bufferstep = 1; - for ( i=0; i < len; i += size ) { - if ( size == 1 ) val = ((int)*CHARP(cp, i)) << 8; - else if ( size == 2 ) val = (int)*SHORTP(cp, i); - else if ( size == 4 ) val = ((int)*LONGP(cp, i)) >> 16; - - /* Step 1 - compute difference with previous value */ - diff = val - valpred; - sign = (diff < 0) ? 8 : 0; - if ( sign ) diff = (-diff); - - /* Step 2 - Divide and clamp */ - /* Note: - ** This code *approximately* computes: - ** delta = diff*4/step; - ** vpdiff = (delta+0.5)*step/4; - ** but in shift step bits are dropped. The net result of this - ** is that even if you have fast mul/div hardware you cannot - ** put it to good use since the fixup would be too expensive. - */ - delta = 0; - vpdiff = (step >> 3); - - if ( diff >= step ) { - delta = 4; - diff -= step; - vpdiff += step; - } - step >>= 1; - if ( diff >= step ) { - delta |= 2; - diff -= step; - vpdiff += step; - } - step >>= 1; - if ( diff >= step ) { - delta |= 1; - vpdiff += step; - } - - /* Step 3 - Update previous value */ - if ( sign ) - valpred -= vpdiff; - else - valpred += vpdiff; - - /* Step 4 - Clamp previous value to 16 bits */ - if ( valpred > 32767 ) - valpred = 32767; - else if ( valpred < -32768 ) - valpred = -32768; - - /* Step 5 - Assemble value, update index and step values */ - delta |= sign; - - index += indexTable[delta]; - if ( index < 0 ) index = 0; - if ( index > 88 ) index = 88; - step = stepsizeTable[index]; - - /* Step 6 - Output value */ - if ( bufferstep ) { - outputbuffer = (delta << 4) & 0xf0; - } else { - *ncp++ = (delta & 0x0f) | outputbuffer; - } - bufferstep = !bufferstep; + /* Step 6 - Output value */ + if ( bufferstep ) { + outputbuffer = (delta << 4) & 0xf0; + } else { + *ncp++ = (delta & 0x0f) | outputbuffer; } - rv = Py_BuildValue("(O(ii))", str, valpred, index); - Py_DECREF(str); - return rv; + bufferstep = !bufferstep; + } + rv = Py_BuildValue("(O(ii))", str, valpred, index); + Py_DECREF(str); + return rv; } static PyObject * audioop_adpcm2lin(PyObject *self, PyObject *args) { - signed char *cp; - signed char *ncp; - int len, new_len, size, valpred, step, delta, index, sign, vpdiff; - PyObject *rv, *str, *state; - int i, inputbuffer = 0, bufferstep; - - if ( !PyArg_ParseTuple(args, "s#iO:adpcm2lin", - &cp, &len, &size, &state) ) - return 0; - - if ( size != 1 && size != 2 && size != 4) { - PyErr_SetString(AudioopError, "Size should be 1, 2 or 4"); - return 0; - } - - /* Decode state, should have (value, step) */ - if ( state == Py_None ) { - /* First time, it seems. Set defaults */ - valpred = 0; - step = 7; - index = 0; - } else if ( !PyArg_ParseTuple(state, "ii", &valpred, &index) ) - return 0; - - new_len = len*size*2; - if (new_len < 0) { - PyErr_SetString(PyExc_MemoryError, - "not enough memory for output buffer"); - return 0; + signed char *cp; + signed char *ncp; + int len, new_len, size, valpred, step, delta, index, sign, vpdiff; + PyObject *rv, *str, *state; + int i, inputbuffer = 0, bufferstep; + + if ( !PyArg_ParseTuple(args, "s#iO:adpcm2lin", + &cp, &len, &size, &state) ) + return 0; + + if ( size != 1 && size != 2 && size != 4) { + PyErr_SetString(AudioopError, "Size should be 1, 2 or 4"); + return 0; + } + + /* Decode state, should have (value, step) */ + if ( state == Py_None ) { + /* First time, it seems. Set defaults */ + valpred = 0; + step = 7; + index = 0; + } else if ( !PyArg_ParseTuple(state, "ii", &valpred, &index) ) + return 0; + + new_len = len*size*2; + if (new_len < 0) { + PyErr_SetString(PyExc_MemoryError, + "not enough memory for output buffer"); + return 0; + } + str = PyBytes_FromStringAndSize(NULL, new_len); + if ( str == 0 ) + return 0; + ncp = (signed char *)PyBytes_AsString(str); + + step = stepsizeTable[index]; + bufferstep = 0; + + for ( i=0; i < new_len; i += size ) { + /* Step 1 - get the delta value and compute next index */ + if ( bufferstep ) { + delta = inputbuffer & 0xf; + } else { + inputbuffer = *cp++; + delta = (inputbuffer >> 4) & 0xf; } - str = PyBytes_FromStringAndSize(NULL, new_len); - if ( str == 0 ) - return 0; - ncp = (signed char *)PyBytes_AsString(str); + bufferstep = !bufferstep; + + /* Step 2 - Find new index value (for later) */ + index += indexTable[delta]; + if ( index < 0 ) index = 0; + if ( index > 88 ) index = 88; + + /* Step 3 - Separate sign and magnitude */ + sign = delta & 8; + delta = delta & 7; + + /* Step 4 - Compute difference and new predicted value */ + /* + ** Computes 'vpdiff = (delta+0.5)*step/4', but see comment + ** in adpcm_coder. + */ + vpdiff = step >> 3; + if ( delta & 4 ) vpdiff += step; + if ( delta & 2 ) vpdiff += step>>1; + if ( delta & 1 ) vpdiff += step>>2; + + if ( sign ) + valpred -= vpdiff; + else + valpred += vpdiff; + + /* Step 5 - clamp output value */ + if ( valpred > 32767 ) + valpred = 32767; + else if ( valpred < -32768 ) + valpred = -32768; + + /* Step 6 - Update step value */ step = stepsizeTable[index]; - bufferstep = 0; - - for ( i=0; i < new_len; i += size ) { - /* Step 1 - get the delta value and compute next index */ - if ( bufferstep ) { - delta = inputbuffer & 0xf; - } else { - inputbuffer = *cp++; - delta = (inputbuffer >> 4) & 0xf; - } - - bufferstep = !bufferstep; - - /* Step 2 - Find new index value (for later) */ - index += indexTable[delta]; - if ( index < 0 ) index = 0; - if ( index > 88 ) index = 88; - - /* Step 3 - Separate sign and magnitude */ - sign = delta & 8; - delta = delta & 7; - - /* Step 4 - Compute difference and new predicted value */ - /* - ** Computes 'vpdiff = (delta+0.5)*step/4', but see comment - ** in adpcm_coder. - */ - vpdiff = step >> 3; - if ( delta & 4 ) vpdiff += step; - if ( delta & 2 ) vpdiff += step>>1; - if ( delta & 1 ) vpdiff += step>>2; - - if ( sign ) - valpred -= vpdiff; - else - valpred += vpdiff; - - /* Step 5 - clamp output value */ - if ( valpred > 32767 ) - valpred = 32767; - else if ( valpred < -32768 ) - valpred = -32768; - - /* Step 6 - Update step value */ - step = stepsizeTable[index]; - - /* Step 6 - Output value */ - if ( size == 1 ) *CHARP(ncp, i) = (signed char)(valpred >> 8); - else if ( size == 2 ) *SHORTP(ncp, i) = (short)(valpred); - else if ( size == 4 ) *LONGP(ncp, i) = (Py_Int32)(valpred<<16); - } - rv = Py_BuildValue("(O(ii))", str, valpred, index); - Py_DECREF(str); - return rv; + /* Step 6 - Output value */ + if ( size == 1 ) *CHARP(ncp, i) = (signed char)(valpred >> 8); + else if ( size == 2 ) *SHORTP(ncp, i) = (short)(valpred); + else if ( size == 4 ) *LONGP(ncp, i) = (Py_Int32)(valpred<<16); + } + + rv = Py_BuildValue("(O(ii))", str, valpred, index); + Py_DECREF(str); + return rv; } static PyMethodDef audioop_methods[] = { - { "max", audioop_max, METH_VARARGS }, - { "minmax", audioop_minmax, METH_VARARGS }, - { "avg", audioop_avg, METH_VARARGS }, - { "maxpp", audioop_maxpp, METH_VARARGS }, - { "avgpp", audioop_avgpp, METH_VARARGS }, - { "rms", audioop_rms, METH_VARARGS }, - { "findfit", audioop_findfit, METH_VARARGS }, - { "findmax", audioop_findmax, METH_VARARGS }, - { "findfactor", audioop_findfactor, METH_VARARGS }, - { "cross", audioop_cross, METH_VARARGS }, - { "mul", audioop_mul, METH_VARARGS }, - { "add", audioop_add, METH_VARARGS }, - { "bias", audioop_bias, METH_VARARGS }, - { "ulaw2lin", audioop_ulaw2lin, METH_VARARGS }, - { "lin2ulaw", audioop_lin2ulaw, METH_VARARGS }, - { "alaw2lin", audioop_alaw2lin, METH_VARARGS }, - { "lin2alaw", audioop_lin2alaw, METH_VARARGS }, - { "lin2lin", audioop_lin2lin, METH_VARARGS }, - { "adpcm2lin", audioop_adpcm2lin, METH_VARARGS }, - { "lin2adpcm", audioop_lin2adpcm, METH_VARARGS }, - { "tomono", audioop_tomono, METH_VARARGS }, - { "tostereo", audioop_tostereo, METH_VARARGS }, - { "getsample", audioop_getsample, METH_VARARGS }, - { "reverse", audioop_reverse, METH_VARARGS }, - { "ratecv", audioop_ratecv, METH_VARARGS }, - { 0, 0 } + { "max", audioop_max, METH_VARARGS }, + { "minmax", audioop_minmax, METH_VARARGS }, + { "avg", audioop_avg, METH_VARARGS }, + { "maxpp", audioop_maxpp, METH_VARARGS }, + { "avgpp", audioop_avgpp, METH_VARARGS }, + { "rms", audioop_rms, METH_VARARGS }, + { "findfit", audioop_findfit, METH_VARARGS }, + { "findmax", audioop_findmax, METH_VARARGS }, + { "findfactor", audioop_findfactor, METH_VARARGS }, + { "cross", audioop_cross, METH_VARARGS }, + { "mul", audioop_mul, METH_VARARGS }, + { "add", audioop_add, METH_VARARGS }, + { "bias", audioop_bias, METH_VARARGS }, + { "ulaw2lin", audioop_ulaw2lin, METH_VARARGS }, + { "lin2ulaw", audioop_lin2ulaw, METH_VARARGS }, + { "alaw2lin", audioop_alaw2lin, METH_VARARGS }, + { "lin2alaw", audioop_lin2alaw, METH_VARARGS }, + { "lin2lin", audioop_lin2lin, METH_VARARGS }, + { "adpcm2lin", audioop_adpcm2lin, METH_VARARGS }, + { "lin2adpcm", audioop_lin2adpcm, METH_VARARGS }, + { "tomono", audioop_tomono, METH_VARARGS }, + { "tostereo", audioop_tostereo, METH_VARARGS }, + { "getsample", audioop_getsample, METH_VARARGS }, + { "reverse", audioop_reverse, METH_VARARGS }, + { "ratecv", audioop_ratecv, METH_VARARGS }, + { 0, 0 } }; static struct PyModuleDef audioopmodule = { - PyModuleDef_HEAD_INIT, - "audioop", - NULL, - -1, - audioop_methods, - NULL, - NULL, - NULL, - NULL + PyModuleDef_HEAD_INIT, + "audioop", + NULL, + -1, + audioop_methods, + NULL, + NULL, + NULL, + NULL }; PyMODINIT_FUNC PyInit_audioop(void) { - PyObject *m, *d; - m = PyModule_Create(&audioopmodule); - if (m == NULL) - return NULL; - d = PyModule_GetDict(m); - if (d == NULL) - return NULL; - AudioopError = PyErr_NewException("audioop.error", NULL, NULL); - if (AudioopError != NULL) - PyDict_SetItemString(d,"error",AudioopError); - return m; + PyObject *m, *d; + m = PyModule_Create(&audioopmodule); + if (m == NULL) + return NULL; + d = PyModule_GetDict(m); + if (d == NULL) + return NULL; + AudioopError = PyErr_NewException("audioop.error", NULL, NULL); + if (AudioopError != NULL) + PyDict_SetItemString(d,"error",AudioopError); + return m; } Modified: python/branches/py3k/Modules/binascii.c ============================================================================== --- python/branches/py3k/Modules/binascii.c (original) +++ python/branches/py3k/Modules/binascii.c Sun May 9 17:52:27 2010 @@ -3,40 +3,40 @@ ** ** This module currently supports the following encodings: ** uuencode: -** each line encodes 45 bytes (except possibly the last) -** First char encodes (binary) length, rest data -** each char encodes 6 bits, as follows: -** binary: 01234567 abcdefgh ijklmnop -** ascii: 012345 67abcd efghij klmnop -** ASCII encoding method is "excess-space": 000000 is encoded as ' ', etc. -** short binary data is zero-extended (so the bits are always in the -** right place), this does *not* reflect in the length. +** each line encodes 45 bytes (except possibly the last) +** First char encodes (binary) length, rest data +** each char encodes 6 bits, as follows: +** binary: 01234567 abcdefgh ijklmnop +** ascii: 012345 67abcd efghij klmnop +** ASCII encoding method is "excess-space": 000000 is encoded as ' ', etc. +** short binary data is zero-extended (so the bits are always in the +** right place), this does *not* reflect in the length. ** base64: ** Line breaks are insignificant, but lines are at most 76 chars ** each char encodes 6 bits, in similar order as uucode/hqx. Encoding ** is done via a table. ** Short binary data is filled (in ASCII) with '='. ** hqx: -** File starts with introductory text, real data starts and ends -** with colons. -** Data consists of three similar parts: info, datafork, resourcefork. -** Each part is protected (at the end) with a 16-bit crc -** The binary data is run-length encoded, and then ascii-fied: -** binary: 01234567 abcdefgh ijklmnop -** ascii: 012345 67abcd efghij klmnop -** ASCII encoding is table-driven, see the code. -** Short binary data results in the runt ascii-byte being output with -** the bits in the right place. +** File starts with introductory text, real data starts and ends +** with colons. +** Data consists of three similar parts: info, datafork, resourcefork. +** Each part is protected (at the end) with a 16-bit crc +** The binary data is run-length encoded, and then ascii-fied: +** binary: 01234567 abcdefgh ijklmnop +** ascii: 012345 67abcd efghij klmnop +** ASCII encoding is table-driven, see the code. +** Short binary data results in the runt ascii-byte being output with +** the bits in the right place. ** ** While I was reading dozens of programs that encode or decode the formats ** here (documentation? hihi:-) I have formulated Jansen's Observation: ** -** Programs that encode binary data in ASCII are written in -** such a style that they are as unreadable as possible. Devices used -** include unnecessary global variables, burying important tables -** in unrelated sourcefiles, putting functions in include files, -** using seemingly-descriptive variable names for different purposes, -** calls to empty subroutines and a host of others. +** Programs that encode binary data in ASCII are written in +** such a style that they are as unreadable as possible. Devices used +** include unnecessary global variables, burying important tables +** in unrelated sourcefiles, putting functions in include files, +** using seemingly-descriptive variable names for different purposes, +** calls to empty subroutines and a host of others. ** ** I have attempted to break with this tradition, but I guess that that ** does make the performance sub-optimal. Oh well, too bad... @@ -75,67 +75,67 @@ static unsigned char table_a2b_hqx[256] = { /* ^@ ^A ^B ^C ^D ^E ^F ^G */ -/* 0*/ FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, +/* 0*/ FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, /* \b \t \n ^K ^L \r ^N ^O */ -/* 1*/ FAIL, FAIL, SKIP, FAIL, FAIL, SKIP, FAIL, FAIL, +/* 1*/ FAIL, FAIL, SKIP, FAIL, FAIL, SKIP, FAIL, FAIL, /* ^P ^Q ^R ^S ^T ^U ^V ^W */ -/* 2*/ FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, +/* 2*/ FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, /* ^X ^Y ^Z ^[ ^\ ^] ^^ ^_ */ -/* 3*/ FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, +/* 3*/ FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, /* ! " # $ % & ' */ -/* 4*/ FAIL, 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, +/* 4*/ FAIL, 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, /* ( ) * + , - . / */ -/* 5*/ 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, FAIL, FAIL, +/* 5*/ 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, FAIL, FAIL, /* 0 1 2 3 4 5 6 7 */ -/* 6*/ 0x0D, 0x0E, 0x0F, 0x10, 0x11, 0x12, 0x13, FAIL, +/* 6*/ 0x0D, 0x0E, 0x0F, 0x10, 0x11, 0x12, 0x13, FAIL, /* 8 9 : ; < = > ? */ -/* 7*/ 0x14, 0x15, DONE, FAIL, FAIL, FAIL, FAIL, FAIL, +/* 7*/ 0x14, 0x15, DONE, FAIL, FAIL, FAIL, FAIL, FAIL, /* @ A B C D E F G */ -/* 8*/ 0x16, 0x17, 0x18, 0x19, 0x1A, 0x1B, 0x1C, 0x1D, +/* 8*/ 0x16, 0x17, 0x18, 0x19, 0x1A, 0x1B, 0x1C, 0x1D, /* H I J K L M N O */ -/* 9*/ 0x1E, 0x1F, 0x20, 0x21, 0x22, 0x23, 0x24, FAIL, +/* 9*/ 0x1E, 0x1F, 0x20, 0x21, 0x22, 0x23, 0x24, FAIL, /* P Q R S T U V W */ -/*10*/ 0x25, 0x26, 0x27, 0x28, 0x29, 0x2A, 0x2B, FAIL, +/*10*/ 0x25, 0x26, 0x27, 0x28, 0x29, 0x2A, 0x2B, FAIL, /* X Y Z [ \ ] ^ _ */ -/*11*/ 0x2C, 0x2D, 0x2E, 0x2F, FAIL, FAIL, FAIL, FAIL, +/*11*/ 0x2C, 0x2D, 0x2E, 0x2F, FAIL, FAIL, FAIL, FAIL, /* ` a b c d e f g */ -/*12*/ 0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, FAIL, +/*12*/ 0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, FAIL, /* h i j k l m n o */ -/*13*/ 0x37, 0x38, 0x39, 0x3A, 0x3B, 0x3C, FAIL, FAIL, +/*13*/ 0x37, 0x38, 0x39, 0x3A, 0x3B, 0x3C, FAIL, FAIL, /* p q r s t u v w */ -/*14*/ 0x3D, 0x3E, 0x3F, FAIL, FAIL, FAIL, FAIL, FAIL, +/*14*/ 0x3D, 0x3E, 0x3F, FAIL, FAIL, FAIL, FAIL, FAIL, /* x y z { | } ~ ^? */ -/*15*/ FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, -/*16*/ FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, - FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, - FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, - FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, - FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, - FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, - FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, - FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, - FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, - FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, - FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, - FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, - FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, - FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, - FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, - FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, +/*15*/ FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, +/*16*/ FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, + FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, + FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, + FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, + FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, + FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, + FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, + FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, + FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, + FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, + FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, + FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, + FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, + FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, + FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, + FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, }; static unsigned char table_b2a_hqx[] = "!\"#$%&'()*+,-012345689 at ABCDEFGHIJKLMNPQRSTUVXYZ[`abcdefhijklmpqr"; static char table_a2b_base64[] = { - -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1, - -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1, - -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,62, -1,-1,-1,63, - 52,53,54,55, 56,57,58,59, 60,61,-1,-1, -1, 0,-1,-1, /* Note PAD->0 */ - -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9,10, 11,12,13,14, - 15,16,17,18, 19,20,21,22, 23,24,25,-1, -1,-1,-1,-1, - -1,26,27,28, 29,30,31,32, 33,34,35,36, 37,38,39,40, - 41,42,43,44, 45,46,47,48, 49,50,51,-1, -1,-1,-1,-1 + -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1, + -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1, + -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,62, -1,-1,-1,63, + 52,53,54,55, 56,57,58,59, 60,61,-1,-1, -1, 0,-1,-1, /* Note PAD->0 */ + -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9,10, 11,12,13,14, + 15,16,17,18, 19,20,21,22, 23,24,25,-1, -1,-1,-1,-1, + -1,26,27,28, 29,30,31,32, 33,34,35,36, 37,38,39,40, + 41,42,43,44, 45,46,47,48, 49,50,51,-1, -1,-1,-1,-1 }; #define BASE64_PAD '=' @@ -149,38 +149,38 @@ static unsigned short crctab_hqx[256] = { - 0x0000, 0x1021, 0x2042, 0x3063, 0x4084, 0x50a5, 0x60c6, 0x70e7, - 0x8108, 0x9129, 0xa14a, 0xb16b, 0xc18c, 0xd1ad, 0xe1ce, 0xf1ef, - 0x1231, 0x0210, 0x3273, 0x2252, 0x52b5, 0x4294, 0x72f7, 0x62d6, - 0x9339, 0x8318, 0xb37b, 0xa35a, 0xd3bd, 0xc39c, 0xf3ff, 0xe3de, - 0x2462, 0x3443, 0x0420, 0x1401, 0x64e6, 0x74c7, 0x44a4, 0x5485, - 0xa56a, 0xb54b, 0x8528, 0x9509, 0xe5ee, 0xf5cf, 0xc5ac, 0xd58d, - 0x3653, 0x2672, 0x1611, 0x0630, 0x76d7, 0x66f6, 0x5695, 0x46b4, - 0xb75b, 0xa77a, 0x9719, 0x8738, 0xf7df, 0xe7fe, 0xd79d, 0xc7bc, - 0x48c4, 0x58e5, 0x6886, 0x78a7, 0x0840, 0x1861, 0x2802, 0x3823, - 0xc9cc, 0xd9ed, 0xe98e, 0xf9af, 0x8948, 0x9969, 0xa90a, 0xb92b, - 0x5af5, 0x4ad4, 0x7ab7, 0x6a96, 0x1a71, 0x0a50, 0x3a33, 0x2a12, - 0xdbfd, 0xcbdc, 0xfbbf, 0xeb9e, 0x9b79, 0x8b58, 0xbb3b, 0xab1a, - 0x6ca6, 0x7c87, 0x4ce4, 0x5cc5, 0x2c22, 0x3c03, 0x0c60, 0x1c41, - 0xedae, 0xfd8f, 0xcdec, 0xddcd, 0xad2a, 0xbd0b, 0x8d68, 0x9d49, - 0x7e97, 0x6eb6, 0x5ed5, 0x4ef4, 0x3e13, 0x2e32, 0x1e51, 0x0e70, - 0xff9f, 0xefbe, 0xdfdd, 0xcffc, 0xbf1b, 0xaf3a, 0x9f59, 0x8f78, - 0x9188, 0x81a9, 0xb1ca, 0xa1eb, 0xd10c, 0xc12d, 0xf14e, 0xe16f, - 0x1080, 0x00a1, 0x30c2, 0x20e3, 0x5004, 0x4025, 0x7046, 0x6067, - 0x83b9, 0x9398, 0xa3fb, 0xb3da, 0xc33d, 0xd31c, 0xe37f, 0xf35e, - 0x02b1, 0x1290, 0x22f3, 0x32d2, 0x4235, 0x5214, 0x6277, 0x7256, - 0xb5ea, 0xa5cb, 0x95a8, 0x8589, 0xf56e, 0xe54f, 0xd52c, 0xc50d, - 0x34e2, 0x24c3, 0x14a0, 0x0481, 0x7466, 0x6447, 0x5424, 0x4405, - 0xa7db, 0xb7fa, 0x8799, 0x97b8, 0xe75f, 0xf77e, 0xc71d, 0xd73c, - 0x26d3, 0x36f2, 0x0691, 0x16b0, 0x6657, 0x7676, 0x4615, 0x5634, - 0xd94c, 0xc96d, 0xf90e, 0xe92f, 0x99c8, 0x89e9, 0xb98a, 0xa9ab, - 0x5844, 0x4865, 0x7806, 0x6827, 0x18c0, 0x08e1, 0x3882, 0x28a3, - 0xcb7d, 0xdb5c, 0xeb3f, 0xfb1e, 0x8bf9, 0x9bd8, 0xabbb, 0xbb9a, - 0x4a75, 0x5a54, 0x6a37, 0x7a16, 0x0af1, 0x1ad0, 0x2ab3, 0x3a92, - 0xfd2e, 0xed0f, 0xdd6c, 0xcd4d, 0xbdaa, 0xad8b, 0x9de8, 0x8dc9, - 0x7c26, 0x6c07, 0x5c64, 0x4c45, 0x3ca2, 0x2c83, 0x1ce0, 0x0cc1, - 0xef1f, 0xff3e, 0xcf5d, 0xdf7c, 0xaf9b, 0xbfba, 0x8fd9, 0x9ff8, - 0x6e17, 0x7e36, 0x4e55, 0x5e74, 0x2e93, 0x3eb2, 0x0ed1, 0x1ef0, + 0x0000, 0x1021, 0x2042, 0x3063, 0x4084, 0x50a5, 0x60c6, 0x70e7, + 0x8108, 0x9129, 0xa14a, 0xb16b, 0xc18c, 0xd1ad, 0xe1ce, 0xf1ef, + 0x1231, 0x0210, 0x3273, 0x2252, 0x52b5, 0x4294, 0x72f7, 0x62d6, + 0x9339, 0x8318, 0xb37b, 0xa35a, 0xd3bd, 0xc39c, 0xf3ff, 0xe3de, + 0x2462, 0x3443, 0x0420, 0x1401, 0x64e6, 0x74c7, 0x44a4, 0x5485, + 0xa56a, 0xb54b, 0x8528, 0x9509, 0xe5ee, 0xf5cf, 0xc5ac, 0xd58d, + 0x3653, 0x2672, 0x1611, 0x0630, 0x76d7, 0x66f6, 0x5695, 0x46b4, + 0xb75b, 0xa77a, 0x9719, 0x8738, 0xf7df, 0xe7fe, 0xd79d, 0xc7bc, + 0x48c4, 0x58e5, 0x6886, 0x78a7, 0x0840, 0x1861, 0x2802, 0x3823, + 0xc9cc, 0xd9ed, 0xe98e, 0xf9af, 0x8948, 0x9969, 0xa90a, 0xb92b, + 0x5af5, 0x4ad4, 0x7ab7, 0x6a96, 0x1a71, 0x0a50, 0x3a33, 0x2a12, + 0xdbfd, 0xcbdc, 0xfbbf, 0xeb9e, 0x9b79, 0x8b58, 0xbb3b, 0xab1a, + 0x6ca6, 0x7c87, 0x4ce4, 0x5cc5, 0x2c22, 0x3c03, 0x0c60, 0x1c41, + 0xedae, 0xfd8f, 0xcdec, 0xddcd, 0xad2a, 0xbd0b, 0x8d68, 0x9d49, + 0x7e97, 0x6eb6, 0x5ed5, 0x4ef4, 0x3e13, 0x2e32, 0x1e51, 0x0e70, + 0xff9f, 0xefbe, 0xdfdd, 0xcffc, 0xbf1b, 0xaf3a, 0x9f59, 0x8f78, + 0x9188, 0x81a9, 0xb1ca, 0xa1eb, 0xd10c, 0xc12d, 0xf14e, 0xe16f, + 0x1080, 0x00a1, 0x30c2, 0x20e3, 0x5004, 0x4025, 0x7046, 0x6067, + 0x83b9, 0x9398, 0xa3fb, 0xb3da, 0xc33d, 0xd31c, 0xe37f, 0xf35e, + 0x02b1, 0x1290, 0x22f3, 0x32d2, 0x4235, 0x5214, 0x6277, 0x7256, + 0xb5ea, 0xa5cb, 0x95a8, 0x8589, 0xf56e, 0xe54f, 0xd52c, 0xc50d, + 0x34e2, 0x24c3, 0x14a0, 0x0481, 0x7466, 0x6447, 0x5424, 0x4405, + 0xa7db, 0xb7fa, 0x8799, 0x97b8, 0xe75f, 0xf77e, 0xc71d, 0xd73c, + 0x26d3, 0x36f2, 0x0691, 0x16b0, 0x6657, 0x7676, 0x4615, 0x5634, + 0xd94c, 0xc96d, 0xf90e, 0xe92f, 0x99c8, 0x89e9, 0xb98a, 0xa9ab, + 0x5844, 0x4865, 0x7806, 0x6827, 0x18c0, 0x08e1, 0x3882, 0x28a3, + 0xcb7d, 0xdb5c, 0xeb3f, 0xfb1e, 0x8bf9, 0x9bd8, 0xabbb, 0xbb9a, + 0x4a75, 0x5a54, 0x6a37, 0x7a16, 0x0af1, 0x1ad0, 0x2ab3, 0x3a92, + 0xfd2e, 0xed0f, 0xdd6c, 0xcd4d, 0xbdaa, 0xad8b, 0x9de8, 0x8dc9, + 0x7c26, 0x6c07, 0x5c64, 0x4c45, 0x3ca2, 0x2c83, 0x1ce0, 0x0cc1, + 0xef1f, 0xff3e, 0xcf5d, 0xdf7c, 0xaf9b, 0xbfba, 0x8fd9, 0x9ff8, + 0x6e17, 0x7e36, 0x4e55, 0x5e74, 0x2e93, 0x3eb2, 0x0ed1, 0x1ef0, }; PyDoc_STRVAR(doc_a2b_uu, "(ascii) -> bin. Decode a line of uuencoded data"); @@ -188,85 +188,85 @@ static PyObject * binascii_a2b_uu(PyObject *self, PyObject *args) { - Py_buffer pascii; - unsigned char *ascii_data, *bin_data; - int leftbits = 0; - unsigned char this_ch; - unsigned int leftchar = 0; - PyObject *rv; - Py_ssize_t ascii_len, bin_len; - - if ( !PyArg_ParseTuple(args, "y*:a2b_uu", &pascii) ) - return NULL; - ascii_data = pascii.buf; - ascii_len = pascii.len; - - assert(ascii_len >= 0); - - /* First byte: binary data length (in bytes) */ - bin_len = (*ascii_data++ - ' ') & 077; - ascii_len--; - - /* Allocate the buffer */ - if ( (rv=PyBytes_FromStringAndSize(NULL, bin_len)) == NULL ) { - PyBuffer_Release(&pascii); - return NULL; - } - bin_data = (unsigned char *)PyBytes_AS_STRING(rv); - - for( ; bin_len > 0 ; ascii_len--, ascii_data++ ) { - /* XXX is it really best to add NULs if there's no more data */ - this_ch = (ascii_len > 0) ? *ascii_data : 0; - if ( this_ch == '\n' || this_ch == '\r' || ascii_len <= 0) { - /* - ** Whitespace. Assume some spaces got eaten at - ** end-of-line. (We check this later) - */ - this_ch = 0; - } else { - /* Check the character for legality - ** The 64 in stead of the expected 63 is because - ** there are a few uuencodes out there that use - ** '`' as zero instead of space. - */ - if ( this_ch < ' ' || this_ch > (' ' + 64)) { - PyErr_SetString(Error, "Illegal char"); - PyBuffer_Release(&pascii); - Py_DECREF(rv); - return NULL; - } - this_ch = (this_ch - ' ') & 077; - } - /* - ** Shift it in on the low end, and see if there's - ** a byte ready for output. - */ - leftchar = (leftchar << 6) | (this_ch); - leftbits += 6; - if ( leftbits >= 8 ) { - leftbits -= 8; - *bin_data++ = (leftchar >> leftbits) & 0xff; - leftchar &= ((1 << leftbits) - 1); - bin_len--; - } - } - /* - ** Finally, check that if there's anything left on the line - ** that it's whitespace only. - */ - while( ascii_len-- > 0 ) { - this_ch = *ascii_data++; - /* Extra '`' may be written as padding in some cases */ - if ( this_ch != ' ' && this_ch != ' '+64 && - this_ch != '\n' && this_ch != '\r' ) { - PyErr_SetString(Error, "Trailing garbage"); - PyBuffer_Release(&pascii); - Py_DECREF(rv); - return NULL; - } - } - PyBuffer_Release(&pascii); - return rv; + Py_buffer pascii; + unsigned char *ascii_data, *bin_data; + int leftbits = 0; + unsigned char this_ch; + unsigned int leftchar = 0; + PyObject *rv; + Py_ssize_t ascii_len, bin_len; + + if ( !PyArg_ParseTuple(args, "y*:a2b_uu", &pascii) ) + return NULL; + ascii_data = pascii.buf; + ascii_len = pascii.len; + + assert(ascii_len >= 0); + + /* First byte: binary data length (in bytes) */ + bin_len = (*ascii_data++ - ' ') & 077; + ascii_len--; + + /* Allocate the buffer */ + if ( (rv=PyBytes_FromStringAndSize(NULL, bin_len)) == NULL ) { + PyBuffer_Release(&pascii); + return NULL; + } + bin_data = (unsigned char *)PyBytes_AS_STRING(rv); + + for( ; bin_len > 0 ; ascii_len--, ascii_data++ ) { + /* XXX is it really best to add NULs if there's no more data */ + this_ch = (ascii_len > 0) ? *ascii_data : 0; + if ( this_ch == '\n' || this_ch == '\r' || ascii_len <= 0) { + /* + ** Whitespace. Assume some spaces got eaten at + ** end-of-line. (We check this later) + */ + this_ch = 0; + } else { + /* Check the character for legality + ** The 64 in stead of the expected 63 is because + ** there are a few uuencodes out there that use + ** '`' as zero instead of space. + */ + if ( this_ch < ' ' || this_ch > (' ' + 64)) { + PyErr_SetString(Error, "Illegal char"); + PyBuffer_Release(&pascii); + Py_DECREF(rv); + return NULL; + } + this_ch = (this_ch - ' ') & 077; + } + /* + ** Shift it in on the low end, and see if there's + ** a byte ready for output. + */ + leftchar = (leftchar << 6) | (this_ch); + leftbits += 6; + if ( leftbits >= 8 ) { + leftbits -= 8; + *bin_data++ = (leftchar >> leftbits) & 0xff; + leftchar &= ((1 << leftbits) - 1); + bin_len--; + } + } + /* + ** Finally, check that if there's anything left on the line + ** that it's whitespace only. + */ + while( ascii_len-- > 0 ) { + this_ch = *ascii_data++; + /* Extra '`' may be written as padding in some cases */ + if ( this_ch != ' ' && this_ch != ' '+64 && + this_ch != '\n' && this_ch != '\r' ) { + PyErr_SetString(Error, "Trailing garbage"); + PyBuffer_Release(&pascii); + Py_DECREF(rv); + return NULL; + } + } + PyBuffer_Release(&pascii); + return rv; } PyDoc_STRVAR(doc_b2a_uu, "(bin) -> ascii. Uuencode line of data"); @@ -274,86 +274,86 @@ static PyObject * binascii_b2a_uu(PyObject *self, PyObject *args) { - Py_buffer pbin; - unsigned char *ascii_data, *bin_data; - int leftbits = 0; - unsigned char this_ch; - unsigned int leftchar = 0; - PyObject *rv; - Py_ssize_t bin_len; - - if ( !PyArg_ParseTuple(args, "y*:b2a_uu", &pbin) ) - return NULL; - bin_data = pbin.buf; - bin_len = pbin.len; - if ( bin_len > 45 ) { - /* The 45 is a limit that appears in all uuencode's */ - PyErr_SetString(Error, "At most 45 bytes at once"); - PyBuffer_Release(&pbin); - return NULL; - } - - /* We're lazy and allocate to much (fixed up later) */ - if ( (rv=PyBytes_FromStringAndSize(NULL, 2 + (bin_len+2)/3*4)) == NULL ) { - PyBuffer_Release(&pbin); - return NULL; - } - ascii_data = (unsigned char *)PyBytes_AS_STRING(rv); - - /* Store the length */ - *ascii_data++ = ' ' + (bin_len & 077); - - for( ; bin_len > 0 || leftbits != 0 ; bin_len--, bin_data++ ) { - /* Shift the data (or padding) into our buffer */ - if ( bin_len > 0 ) /* Data */ - leftchar = (leftchar << 8) | *bin_data; - else /* Padding */ - leftchar <<= 8; - leftbits += 8; - - /* See if there are 6-bit groups ready */ - while ( leftbits >= 6 ) { - this_ch = (leftchar >> (leftbits-6)) & 0x3f; - leftbits -= 6; - *ascii_data++ = this_ch + ' '; - } - } - *ascii_data++ = '\n'; /* Append a courtesy newline */ - - if (_PyBytes_Resize(&rv, - (ascii_data - - (unsigned char *)PyBytes_AS_STRING(rv))) < 0) { - Py_DECREF(rv); - rv = NULL; - } - PyBuffer_Release(&pbin); - return rv; + Py_buffer pbin; + unsigned char *ascii_data, *bin_data; + int leftbits = 0; + unsigned char this_ch; + unsigned int leftchar = 0; + PyObject *rv; + Py_ssize_t bin_len; + + if ( !PyArg_ParseTuple(args, "y*:b2a_uu", &pbin) ) + return NULL; + bin_data = pbin.buf; + bin_len = pbin.len; + if ( bin_len > 45 ) { + /* The 45 is a limit that appears in all uuencode's */ + PyErr_SetString(Error, "At most 45 bytes at once"); + PyBuffer_Release(&pbin); + return NULL; + } + + /* We're lazy and allocate to much (fixed up later) */ + if ( (rv=PyBytes_FromStringAndSize(NULL, 2 + (bin_len+2)/3*4)) == NULL ) { + PyBuffer_Release(&pbin); + return NULL; + } + ascii_data = (unsigned char *)PyBytes_AS_STRING(rv); + + /* Store the length */ + *ascii_data++ = ' ' + (bin_len & 077); + + for( ; bin_len > 0 || leftbits != 0 ; bin_len--, bin_data++ ) { + /* Shift the data (or padding) into our buffer */ + if ( bin_len > 0 ) /* Data */ + leftchar = (leftchar << 8) | *bin_data; + else /* Padding */ + leftchar <<= 8; + leftbits += 8; + + /* See if there are 6-bit groups ready */ + while ( leftbits >= 6 ) { + this_ch = (leftchar >> (leftbits-6)) & 0x3f; + leftbits -= 6; + *ascii_data++ = this_ch + ' '; + } + } + *ascii_data++ = '\n'; /* Append a courtesy newline */ + + if (_PyBytes_Resize(&rv, + (ascii_data - + (unsigned char *)PyBytes_AS_STRING(rv))) < 0) { + Py_DECREF(rv); + rv = NULL; + } + PyBuffer_Release(&pbin); + return rv; } static int binascii_find_valid(unsigned char *s, Py_ssize_t slen, int num) { - /* Finds & returns the (num+1)th - ** valid character for base64, or -1 if none. - */ - - int ret = -1; - unsigned char c, b64val; - - while ((slen > 0) && (ret == -1)) { - c = *s; - b64val = table_a2b_base64[c & 0x7f]; - if ( ((c <= 0x7f) && (b64val != (unsigned char)-1)) ) { - if (num == 0) - ret = *s; - num--; - } - - s++; - slen--; - } - return ret; + /* Finds & returns the (num+1)th + ** valid character for base64, or -1 if none. + */ + + int ret = -1; + unsigned char c, b64val; + + while ((slen > 0) && (ret == -1)) { + c = *s; + b64val = table_a2b_base64[c & 0x7f]; + if ( ((c <= 0x7f) && (b64val != (unsigned char)-1)) ) { + if (num == 0) + ret = *s; + num--; + } + + s++; + slen--; + } + return ret; } PyDoc_STRVAR(doc_a2b_base64, "(ascii) -> bin. Decode a line of base64 data"); @@ -361,108 +361,108 @@ static PyObject * binascii_a2b_base64(PyObject *self, PyObject *args) { - Py_buffer pascii; - unsigned char *ascii_data, *bin_data; - int leftbits = 0; - unsigned char this_ch; - unsigned int leftchar = 0; - PyObject *rv; - Py_ssize_t ascii_len, bin_len; - int quad_pos = 0; - - if ( !PyArg_ParseTuple(args, "y*:a2b_base64", &pascii) ) - return NULL; - ascii_data = pascii.buf; - ascii_len = pascii.len; - - assert(ascii_len >= 0); - - if (ascii_len > PY_SSIZE_T_MAX - 3) { - PyBuffer_Release(&pascii); - return PyErr_NoMemory(); - } - - bin_len = ((ascii_len+3)/4)*3; /* Upper bound, corrected later */ - - /* Allocate the buffer */ - if ( (rv=PyBytes_FromStringAndSize(NULL, bin_len)) == NULL ) { - PyBuffer_Release(&pascii); - return NULL; - } - bin_data = (unsigned char *)PyBytes_AS_STRING(rv); - bin_len = 0; - - for( ; ascii_len > 0; ascii_len--, ascii_data++) { - this_ch = *ascii_data; - - if (this_ch > 0x7f || - this_ch == '\r' || this_ch == '\n' || this_ch == ' ') - continue; - - /* Check for pad sequences and ignore - ** the invalid ones. - */ - if (this_ch == BASE64_PAD) { - if ( (quad_pos < 2) || - ((quad_pos == 2) && - (binascii_find_valid(ascii_data, ascii_len, 1) - != BASE64_PAD)) ) - { - continue; - } - else { - /* A pad sequence means no more input. - ** We've already interpreted the data - ** from the quad at this point. - */ - leftbits = 0; - break; - } - } - - this_ch = table_a2b_base64[*ascii_data]; - if ( this_ch == (unsigned char) -1 ) - continue; - - /* - ** Shift it in on the low end, and see if there's - ** a byte ready for output. - */ - quad_pos = (quad_pos + 1) & 0x03; - leftchar = (leftchar << 6) | (this_ch); - leftbits += 6; - - if ( leftbits >= 8 ) { - leftbits -= 8; - *bin_data++ = (leftchar >> leftbits) & 0xff; - bin_len++; - leftchar &= ((1 << leftbits) - 1); - } - } - - if (leftbits != 0) { - PyBuffer_Release(&pascii); - PyErr_SetString(Error, "Incorrect padding"); - Py_DECREF(rv); - return NULL; - } - - /* And set string size correctly. If the result string is empty - ** (because the input was all invalid) return the shared empty - ** string instead; _PyBytes_Resize() won't do this for us. - */ - if (bin_len > 0) { - if (_PyBytes_Resize(&rv, bin_len) < 0) { - Py_DECREF(rv); - rv = NULL; - } - } - else { - Py_DECREF(rv); - rv = PyBytes_FromStringAndSize("", 0); - } - PyBuffer_Release(&pascii); - return rv; + Py_buffer pascii; + unsigned char *ascii_data, *bin_data; + int leftbits = 0; + unsigned char this_ch; + unsigned int leftchar = 0; + PyObject *rv; + Py_ssize_t ascii_len, bin_len; + int quad_pos = 0; + + if ( !PyArg_ParseTuple(args, "y*:a2b_base64", &pascii) ) + return NULL; + ascii_data = pascii.buf; + ascii_len = pascii.len; + + assert(ascii_len >= 0); + + if (ascii_len > PY_SSIZE_T_MAX - 3) { + PyBuffer_Release(&pascii); + return PyErr_NoMemory(); + } + + bin_len = ((ascii_len+3)/4)*3; /* Upper bound, corrected later */ + + /* Allocate the buffer */ + if ( (rv=PyBytes_FromStringAndSize(NULL, bin_len)) == NULL ) { + PyBuffer_Release(&pascii); + return NULL; + } + bin_data = (unsigned char *)PyBytes_AS_STRING(rv); + bin_len = 0; + + for( ; ascii_len > 0; ascii_len--, ascii_data++) { + this_ch = *ascii_data; + + if (this_ch > 0x7f || + this_ch == '\r' || this_ch == '\n' || this_ch == ' ') + continue; + + /* Check for pad sequences and ignore + ** the invalid ones. + */ + if (this_ch == BASE64_PAD) { + if ( (quad_pos < 2) || + ((quad_pos == 2) && + (binascii_find_valid(ascii_data, ascii_len, 1) + != BASE64_PAD)) ) + { + continue; + } + else { + /* A pad sequence means no more input. + ** We've already interpreted the data + ** from the quad at this point. + */ + leftbits = 0; + break; + } + } + + this_ch = table_a2b_base64[*ascii_data]; + if ( this_ch == (unsigned char) -1 ) + continue; + + /* + ** Shift it in on the low end, and see if there's + ** a byte ready for output. + */ + quad_pos = (quad_pos + 1) & 0x03; + leftchar = (leftchar << 6) | (this_ch); + leftbits += 6; + + if ( leftbits >= 8 ) { + leftbits -= 8; + *bin_data++ = (leftchar >> leftbits) & 0xff; + bin_len++; + leftchar &= ((1 << leftbits) - 1); + } + } + + if (leftbits != 0) { + PyBuffer_Release(&pascii); + PyErr_SetString(Error, "Incorrect padding"); + Py_DECREF(rv); + return NULL; + } + + /* And set string size correctly. If the result string is empty + ** (because the input was all invalid) return the shared empty + ** string instead; _PyBytes_Resize() won't do this for us. + */ + if (bin_len > 0) { + if (_PyBytes_Resize(&rv, bin_len) < 0) { + Py_DECREF(rv); + rv = NULL; + } + } + else { + Py_DECREF(rv); + rv = PyBytes_FromStringAndSize("", 0); + } + PyBuffer_Release(&pascii); + return rv; } PyDoc_STRVAR(doc_b2a_base64, "(bin) -> ascii. Base64-code line of data"); @@ -470,66 +470,66 @@ static PyObject * binascii_b2a_base64(PyObject *self, PyObject *args) { - Py_buffer pbuf; - unsigned char *ascii_data, *bin_data; - int leftbits = 0; - unsigned char this_ch; - unsigned int leftchar = 0; - PyObject *rv; - Py_ssize_t bin_len; - - if ( !PyArg_ParseTuple(args, "y*:b2a_base64", &pbuf) ) - return NULL; - bin_data = pbuf.buf; - bin_len = pbuf.len; - - assert(bin_len >= 0); - - if ( bin_len > BASE64_MAXBIN ) { - PyErr_SetString(Error, "Too much data for base64 line"); - PyBuffer_Release(&pbuf); - return NULL; - } - - /* We're lazy and allocate too much (fixed up later). - "+3" leaves room for up to two pad characters and a trailing - newline. Note that 'b' gets encoded as 'Yg==\n' (1 in, 5 out). */ - if ( (rv=PyBytes_FromStringAndSize(NULL, bin_len*2 + 3)) == NULL ) { - PyBuffer_Release(&pbuf); - return NULL; - } - ascii_data = (unsigned char *)PyBytes_AS_STRING(rv); - - for( ; bin_len > 0 ; bin_len--, bin_data++ ) { - /* Shift the data into our buffer */ - leftchar = (leftchar << 8) | *bin_data; - leftbits += 8; - - /* See if there are 6-bit groups ready */ - while ( leftbits >= 6 ) { - this_ch = (leftchar >> (leftbits-6)) & 0x3f; - leftbits -= 6; - *ascii_data++ = table_b2a_base64[this_ch]; - } - } - if ( leftbits == 2 ) { - *ascii_data++ = table_b2a_base64[(leftchar&3) << 4]; - *ascii_data++ = BASE64_PAD; - *ascii_data++ = BASE64_PAD; - } else if ( leftbits == 4 ) { - *ascii_data++ = table_b2a_base64[(leftchar&0xf) << 2]; - *ascii_data++ = BASE64_PAD; - } - *ascii_data++ = '\n'; /* Append a courtesy newline */ - - if (_PyBytes_Resize(&rv, - (ascii_data - - (unsigned char *)PyBytes_AS_STRING(rv))) < 0) { - Py_DECREF(rv); - rv = NULL; - } - PyBuffer_Release(&pbuf); - return rv; + Py_buffer pbuf; + unsigned char *ascii_data, *bin_data; + int leftbits = 0; + unsigned char this_ch; + unsigned int leftchar = 0; + PyObject *rv; + Py_ssize_t bin_len; + + if ( !PyArg_ParseTuple(args, "y*:b2a_base64", &pbuf) ) + return NULL; + bin_data = pbuf.buf; + bin_len = pbuf.len; + + assert(bin_len >= 0); + + if ( bin_len > BASE64_MAXBIN ) { + PyErr_SetString(Error, "Too much data for base64 line"); + PyBuffer_Release(&pbuf); + return NULL; + } + + /* We're lazy and allocate too much (fixed up later). + "+3" leaves room for up to two pad characters and a trailing + newline. Note that 'b' gets encoded as 'Yg==\n' (1 in, 5 out). */ + if ( (rv=PyBytes_FromStringAndSize(NULL, bin_len*2 + 3)) == NULL ) { + PyBuffer_Release(&pbuf); + return NULL; + } + ascii_data = (unsigned char *)PyBytes_AS_STRING(rv); + + for( ; bin_len > 0 ; bin_len--, bin_data++ ) { + /* Shift the data into our buffer */ + leftchar = (leftchar << 8) | *bin_data; + leftbits += 8; + + /* See if there are 6-bit groups ready */ + while ( leftbits >= 6 ) { + this_ch = (leftchar >> (leftbits-6)) & 0x3f; + leftbits -= 6; + *ascii_data++ = table_b2a_base64[this_ch]; + } + } + if ( leftbits == 2 ) { + *ascii_data++ = table_b2a_base64[(leftchar&3) << 4]; + *ascii_data++ = BASE64_PAD; + *ascii_data++ = BASE64_PAD; + } else if ( leftbits == 4 ) { + *ascii_data++ = table_b2a_base64[(leftchar&0xf) << 2]; + *ascii_data++ = BASE64_PAD; + } + *ascii_data++ = '\n'; /* Append a courtesy newline */ + + if (_PyBytes_Resize(&rv, + (ascii_data - + (unsigned char *)PyBytes_AS_STRING(rv))) < 0) { + Py_DECREF(rv); + rv = NULL; + } + PyBuffer_Release(&pbuf); + return rv; } PyDoc_STRVAR(doc_a2b_hqx, "ascii -> bin, done. Decode .hqx coding"); @@ -537,85 +537,85 @@ static PyObject * binascii_a2b_hqx(PyObject *self, PyObject *args) { - Py_buffer pascii; - unsigned char *ascii_data, *bin_data; - int leftbits = 0; - unsigned char this_ch; - unsigned int leftchar = 0; - PyObject *rv; - Py_ssize_t len; - int done = 0; - - if ( !PyArg_ParseTuple(args, "s*:a2b_hqx", &pascii) ) - return NULL; - ascii_data = pascii.buf; - len = pascii.len; - - assert(len >= 0); - - if (len > PY_SSIZE_T_MAX - 2) { - PyBuffer_Release(&pascii); - return PyErr_NoMemory(); - } - - /* Allocate a string that is too big (fixed later) - Add two to the initial length to prevent interning which - would preclude subsequent resizing. */ - if ( (rv=PyBytes_FromStringAndSize(NULL, len+2)) == NULL ) { - PyBuffer_Release(&pascii); - return NULL; - } - bin_data = (unsigned char *)PyBytes_AS_STRING(rv); - - for( ; len > 0 ; len--, ascii_data++ ) { - /* Get the byte and look it up */ - this_ch = table_a2b_hqx[*ascii_data]; - if ( this_ch == SKIP ) - continue; - if ( this_ch == FAIL ) { - PyErr_SetString(Error, "Illegal char"); - PyBuffer_Release(&pascii); - Py_DECREF(rv); - return NULL; - } - if ( this_ch == DONE ) { - /* The terminating colon */ - done = 1; - break; - } - - /* Shift it into the buffer and see if any bytes are ready */ - leftchar = (leftchar << 6) | (this_ch); - leftbits += 6; - if ( leftbits >= 8 ) { - leftbits -= 8; - *bin_data++ = (leftchar >> leftbits) & 0xff; - leftchar &= ((1 << leftbits) - 1); - } - } - - if ( leftbits && !done ) { - PyErr_SetString(Incomplete, - "String has incomplete number of bytes"); - PyBuffer_Release(&pascii); - Py_DECREF(rv); - return NULL; - } - if (_PyBytes_Resize(&rv, - (bin_data - - (unsigned char *)PyBytes_AS_STRING(rv))) < 0) { - Py_DECREF(rv); - rv = NULL; - } - if (rv) { - PyObject *rrv = Py_BuildValue("Oi", rv, done); - PyBuffer_Release(&pascii); - Py_DECREF(rv); - return rrv; - } + Py_buffer pascii; + unsigned char *ascii_data, *bin_data; + int leftbits = 0; + unsigned char this_ch; + unsigned int leftchar = 0; + PyObject *rv; + Py_ssize_t len; + int done = 0; + + if ( !PyArg_ParseTuple(args, "s*:a2b_hqx", &pascii) ) + return NULL; + ascii_data = pascii.buf; + len = pascii.len; + + assert(len >= 0); + + if (len > PY_SSIZE_T_MAX - 2) { + PyBuffer_Release(&pascii); + return PyErr_NoMemory(); + } + + /* Allocate a string that is too big (fixed later) + Add two to the initial length to prevent interning which + would preclude subsequent resizing. */ + if ( (rv=PyBytes_FromStringAndSize(NULL, len+2)) == NULL ) { + PyBuffer_Release(&pascii); + return NULL; + } + bin_data = (unsigned char *)PyBytes_AS_STRING(rv); + + for( ; len > 0 ; len--, ascii_data++ ) { + /* Get the byte and look it up */ + this_ch = table_a2b_hqx[*ascii_data]; + if ( this_ch == SKIP ) + continue; + if ( this_ch == FAIL ) { + PyErr_SetString(Error, "Illegal char"); + PyBuffer_Release(&pascii); + Py_DECREF(rv); + return NULL; + } + if ( this_ch == DONE ) { + /* The terminating colon */ + done = 1; + break; + } + + /* Shift it into the buffer and see if any bytes are ready */ + leftchar = (leftchar << 6) | (this_ch); + leftbits += 6; + if ( leftbits >= 8 ) { + leftbits -= 8; + *bin_data++ = (leftchar >> leftbits) & 0xff; + leftchar &= ((1 << leftbits) - 1); + } + } + + if ( leftbits && !done ) { + PyErr_SetString(Incomplete, + "String has incomplete number of bytes"); + PyBuffer_Release(&pascii); + Py_DECREF(rv); + return NULL; + } + if (_PyBytes_Resize(&rv, + (bin_data - + (unsigned char *)PyBytes_AS_STRING(rv))) < 0) { + Py_DECREF(rv); + rv = NULL; + } + if (rv) { + PyObject *rrv = Py_BuildValue("Oi", rv, done); + PyBuffer_Release(&pascii); + Py_DECREF(rv); + return rrv; + } - PyBuffer_Release(&pascii); - return NULL; + PyBuffer_Release(&pascii); + return NULL; } PyDoc_STRVAR(doc_rlecode_hqx, "Binhex RLE-code binary data"); @@ -623,63 +623,63 @@ static PyObject * binascii_rlecode_hqx(PyObject *self, PyObject *args) { - Py_buffer pbuf; - unsigned char *in_data, *out_data; - PyObject *rv; - unsigned char ch; - Py_ssize_t in, inend, len; - - if ( !PyArg_ParseTuple(args, "y*:rlecode_hqx", &pbuf) ) - return NULL; - in_data = pbuf.buf; - len = pbuf.len; - - assert(len >= 0); - - if (len > PY_SSIZE_T_MAX / 2 - 2) { - PyBuffer_Release(&pbuf); - return PyErr_NoMemory(); - } - - /* Worst case: output is twice as big as input (fixed later) */ - if ( (rv=PyBytes_FromStringAndSize(NULL, len*2+2)) == NULL ) { - PyBuffer_Release(&pbuf); - return NULL; - } - out_data = (unsigned char *)PyBytes_AS_STRING(rv); - - for( in=0; in 3 ) { - /* More than 3 in a row. Output RLE. */ - *out_data++ = ch; - *out_data++ = RUNCHAR; - *out_data++ = inend-in; - in = inend-1; - } else { - /* Less than 3. Output the byte itself */ - *out_data++ = ch; - } - } - } - if (_PyBytes_Resize(&rv, - (out_data - - (unsigned char *)PyBytes_AS_STRING(rv))) < 0) { - Py_DECREF(rv); - rv = NULL; - } - PyBuffer_Release(&pbuf); - return rv; + Py_buffer pbuf; + unsigned char *in_data, *out_data; + PyObject *rv; + unsigned char ch; + Py_ssize_t in, inend, len; + + if ( !PyArg_ParseTuple(args, "y*:rlecode_hqx", &pbuf) ) + return NULL; + in_data = pbuf.buf; + len = pbuf.len; + + assert(len >= 0); + + if (len > PY_SSIZE_T_MAX / 2 - 2) { + PyBuffer_Release(&pbuf); + return PyErr_NoMemory(); + } + + /* Worst case: output is twice as big as input (fixed later) */ + if ( (rv=PyBytes_FromStringAndSize(NULL, len*2+2)) == NULL ) { + PyBuffer_Release(&pbuf); + return NULL; + } + out_data = (unsigned char *)PyBytes_AS_STRING(rv); + + for( in=0; in 3 ) { + /* More than 3 in a row. Output RLE. */ + *out_data++ = ch; + *out_data++ = RUNCHAR; + *out_data++ = inend-in; + in = inend-1; + } else { + /* Less than 3. Output the byte itself */ + *out_data++ = ch; + } + } + } + if (_PyBytes_Resize(&rv, + (out_data - + (unsigned char *)PyBytes_AS_STRING(rv))) < 0) { + Py_DECREF(rv); + rv = NULL; + } + PyBuffer_Release(&pbuf); + return rv; } PyDoc_STRVAR(doc_b2a_hqx, "Encode .hqx data"); @@ -687,56 +687,56 @@ static PyObject * binascii_b2a_hqx(PyObject *self, PyObject *args) { - Py_buffer pbin; - unsigned char *ascii_data, *bin_data; - int leftbits = 0; - unsigned char this_ch; - unsigned int leftchar = 0; - PyObject *rv; - Py_ssize_t len; - - if ( !PyArg_ParseTuple(args, "y*:b2a_hqx", &pbin) ) - return NULL; - bin_data = pbin.buf; - len = pbin.len; - - assert(len >= 0); - - if (len > PY_SSIZE_T_MAX / 2 - 2) { - PyBuffer_Release(&pbin); - return PyErr_NoMemory(); - } - - /* Allocate a buffer that is at least large enough */ - if ( (rv=PyBytes_FromStringAndSize(NULL, len*2+2)) == NULL ) { - PyBuffer_Release(&pbin); - return NULL; - } - ascii_data = (unsigned char *)PyBytes_AS_STRING(rv); - - for( ; len > 0 ; len--, bin_data++ ) { - /* Shift into our buffer, and output any 6bits ready */ - leftchar = (leftchar << 8) | *bin_data; - leftbits += 8; - while ( leftbits >= 6 ) { - this_ch = (leftchar >> (leftbits-6)) & 0x3f; - leftbits -= 6; - *ascii_data++ = table_b2a_hqx[this_ch]; - } - } - /* Output a possible runt byte */ - if ( leftbits ) { - leftchar <<= (6-leftbits); - *ascii_data++ = table_b2a_hqx[leftchar & 0x3f]; - } - if (_PyBytes_Resize(&rv, - (ascii_data - - (unsigned char *)PyBytes_AS_STRING(rv))) < 0) { - Py_DECREF(rv); - rv = NULL; - } - PyBuffer_Release(&pbin); - return rv; + Py_buffer pbin; + unsigned char *ascii_data, *bin_data; + int leftbits = 0; + unsigned char this_ch; + unsigned int leftchar = 0; + PyObject *rv; + Py_ssize_t len; + + if ( !PyArg_ParseTuple(args, "y*:b2a_hqx", &pbin) ) + return NULL; + bin_data = pbin.buf; + len = pbin.len; + + assert(len >= 0); + + if (len > PY_SSIZE_T_MAX / 2 - 2) { + PyBuffer_Release(&pbin); + return PyErr_NoMemory(); + } + + /* Allocate a buffer that is at least large enough */ + if ( (rv=PyBytes_FromStringAndSize(NULL, len*2+2)) == NULL ) { + PyBuffer_Release(&pbin); + return NULL; + } + ascii_data = (unsigned char *)PyBytes_AS_STRING(rv); + + for( ; len > 0 ; len--, bin_data++ ) { + /* Shift into our buffer, and output any 6bits ready */ + leftchar = (leftchar << 8) | *bin_data; + leftbits += 8; + while ( leftbits >= 6 ) { + this_ch = (leftchar >> (leftbits-6)) & 0x3f; + leftbits -= 6; + *ascii_data++ = table_b2a_hqx[this_ch]; + } + } + /* Output a possible runt byte */ + if ( leftbits ) { + leftchar <<= (6-leftbits); + *ascii_data++ = table_b2a_hqx[leftchar & 0x3f]; + } + if (_PyBytes_Resize(&rv, + (ascii_data - + (unsigned char *)PyBytes_AS_STRING(rv))) < 0) { + Py_DECREF(rv); + rv = NULL; + } + PyBuffer_Release(&pbin); + return rv; } PyDoc_STRVAR(doc_rledecode_hqx, "Decode hexbin RLE-coded string"); @@ -744,116 +744,116 @@ static PyObject * binascii_rledecode_hqx(PyObject *self, PyObject *args) { - Py_buffer pin; - unsigned char *in_data, *out_data; - unsigned char in_byte, in_repeat; - PyObject *rv; - Py_ssize_t in_len, out_len, out_len_left; - - if ( !PyArg_ParseTuple(args, "s*:rledecode_hqx", &pin) ) - return NULL; - in_data = pin.buf; - in_len = pin.len; - - assert(in_len >= 0); - - /* Empty string is a special case */ - if ( in_len == 0 ) { - PyBuffer_Release(&pin); - return PyBytes_FromStringAndSize("", 0); - } - else if (in_len > PY_SSIZE_T_MAX / 2) { - PyBuffer_Release(&pin); - return PyErr_NoMemory(); - } - - /* Allocate a buffer of reasonable size. Resized when needed */ - out_len = in_len*2; - if ( (rv=PyBytes_FromStringAndSize(NULL, out_len)) == NULL ) { - PyBuffer_Release(&pin); - return NULL; - } - out_len_left = out_len; - out_data = (unsigned char *)PyBytes_AS_STRING(rv); - - /* - ** We need two macros here to get/put bytes and handle - ** end-of-buffer for input and output strings. - */ + Py_buffer pin; + unsigned char *in_data, *out_data; + unsigned char in_byte, in_repeat; + PyObject *rv; + Py_ssize_t in_len, out_len, out_len_left; + + if ( !PyArg_ParseTuple(args, "s*:rledecode_hqx", &pin) ) + return NULL; + in_data = pin.buf; + in_len = pin.len; + + assert(in_len >= 0); + + /* Empty string is a special case */ + if ( in_len == 0 ) { + PyBuffer_Release(&pin); + return PyBytes_FromStringAndSize("", 0); + } + else if (in_len > PY_SSIZE_T_MAX / 2) { + PyBuffer_Release(&pin); + return PyErr_NoMemory(); + } + + /* Allocate a buffer of reasonable size. Resized when needed */ + out_len = in_len*2; + if ( (rv=PyBytes_FromStringAndSize(NULL, out_len)) == NULL ) { + PyBuffer_Release(&pin); + return NULL; + } + out_len_left = out_len; + out_data = (unsigned char *)PyBytes_AS_STRING(rv); + + /* + ** We need two macros here to get/put bytes and handle + ** end-of-buffer for input and output strings. + */ #define INBYTE(b) \ - do { \ - if ( --in_len < 0 ) { \ - PyErr_SetString(Incomplete, ""); \ - Py_DECREF(rv); \ - PyBuffer_Release(&pin); \ - return NULL; \ - } \ - b = *in_data++; \ - } while(0) + do { \ + if ( --in_len < 0 ) { \ + PyErr_SetString(Incomplete, ""); \ + Py_DECREF(rv); \ + PyBuffer_Release(&pin); \ + return NULL; \ + } \ + b = *in_data++; \ + } while(0) #define OUTBYTE(b) \ - do { \ - if ( --out_len_left < 0 ) { \ - if ( out_len > PY_SSIZE_T_MAX / 2) return PyErr_NoMemory(); \ - if (_PyBytes_Resize(&rv, 2*out_len) < 0) \ - { Py_DECREF(rv); PyBuffer_Release(&pin); return NULL; } \ - out_data = (unsigned char *)PyBytes_AS_STRING(rv) \ - + out_len; \ - out_len_left = out_len-1; \ - out_len = out_len * 2; \ - } \ - *out_data++ = b; \ - } while(0) - - /* - ** Handle first byte separately (since we have to get angry - ** in case of an orphaned RLE code). - */ - INBYTE(in_byte); - - if (in_byte == RUNCHAR) { - INBYTE(in_repeat); - if (in_repeat != 0) { - /* Note Error, not Incomplete (which is at the end - ** of the string only). This is a programmer error. - */ - PyErr_SetString(Error, "Orphaned RLE code at start"); - PyBuffer_Release(&pin); - Py_DECREF(rv); - return NULL; - } - OUTBYTE(RUNCHAR); - } else { - OUTBYTE(in_byte); - } - - while( in_len > 0 ) { - INBYTE(in_byte); - - if (in_byte == RUNCHAR) { - INBYTE(in_repeat); - if ( in_repeat == 0 ) { - /* Just an escaped RUNCHAR value */ - OUTBYTE(RUNCHAR); - } else { - /* Pick up value and output a sequence of it */ - in_byte = out_data[-1]; - while ( --in_repeat > 0 ) - OUTBYTE(in_byte); - } - } else { - /* Normal byte */ - OUTBYTE(in_byte); - } - } - if (_PyBytes_Resize(&rv, - (out_data - - (unsigned char *)PyBytes_AS_STRING(rv))) < 0) { - Py_DECREF(rv); - rv = NULL; - } - PyBuffer_Release(&pin); - return rv; + do { \ + if ( --out_len_left < 0 ) { \ + if ( out_len > PY_SSIZE_T_MAX / 2) return PyErr_NoMemory(); \ + if (_PyBytes_Resize(&rv, 2*out_len) < 0) \ + { Py_DECREF(rv); PyBuffer_Release(&pin); return NULL; } \ + out_data = (unsigned char *)PyBytes_AS_STRING(rv) \ + + out_len; \ + out_len_left = out_len-1; \ + out_len = out_len * 2; \ + } \ + *out_data++ = b; \ + } while(0) + + /* + ** Handle first byte separately (since we have to get angry + ** in case of an orphaned RLE code). + */ + INBYTE(in_byte); + + if (in_byte == RUNCHAR) { + INBYTE(in_repeat); + if (in_repeat != 0) { + /* Note Error, not Incomplete (which is at the end + ** of the string only). This is a programmer error. + */ + PyErr_SetString(Error, "Orphaned RLE code at start"); + PyBuffer_Release(&pin); + Py_DECREF(rv); + return NULL; + } + OUTBYTE(RUNCHAR); + } else { + OUTBYTE(in_byte); + } + + while( in_len > 0 ) { + INBYTE(in_byte); + + if (in_byte == RUNCHAR) { + INBYTE(in_repeat); + if ( in_repeat == 0 ) { + /* Just an escaped RUNCHAR value */ + OUTBYTE(RUNCHAR); + } else { + /* Pick up value and output a sequence of it */ + in_byte = out_data[-1]; + while ( --in_repeat > 0 ) + OUTBYTE(in_byte); + } + } else { + /* Normal byte */ + OUTBYTE(in_byte); + } + } + if (_PyBytes_Resize(&rv, + (out_data - + (unsigned char *)PyBytes_AS_STRING(rv))) < 0) { + Py_DECREF(rv); + rv = NULL; + } + PyBuffer_Release(&pin); + return rv; } PyDoc_STRVAR(doc_crc_hqx, @@ -862,22 +862,22 @@ static PyObject * binascii_crc_hqx(PyObject *self, PyObject *args) { - Py_buffer pin; - unsigned char *bin_data; - unsigned int crc; - Py_ssize_t len; - - if ( !PyArg_ParseTuple(args, "y*i:crc_hqx", &pin, &crc) ) - return NULL; - bin_data = pin.buf; - len = pin.len; - - while(len-- > 0) { - crc=((crc<<8)&0xff00)^crctab_hqx[((crc>>8)&0xff)^*bin_data++]; - } + Py_buffer pin; + unsigned char *bin_data; + unsigned int crc; + Py_ssize_t len; - PyBuffer_Release(&pin); - return Py_BuildValue("i", crc); + if ( !PyArg_ParseTuple(args, "y*i:crc_hqx", &pin, &crc) ) + return NULL; + bin_data = pin.buf; + len = pin.len; + + while(len-- > 0) { + crc=((crc<<8)&0xff00)^crctab_hqx[((crc>>8)&0xff)^*bin_data++]; + } + + PyBuffer_Release(&pin); + return Py_BuildValue("i", crc); } PyDoc_STRVAR(doc_crc32, @@ -895,7 +895,7 @@ int signed_val; if (!PyArg_ParseTuple(args, "y*|I:crc32", &pbuf, &crc32val)) - return NULL; + return NULL; buf = (Byte*)pbuf.buf; len = pbuf.len; signed_val = crc32(crc32val, buf, len); @@ -1024,26 +1024,26 @@ static PyObject * binascii_crc32(PyObject *self, PyObject *args) { /* By Jim Ahlstrom; All rights transferred to CNRI */ - Py_buffer pbin; - unsigned char *bin_data; - unsigned int crc = 0; /* initial value of CRC */ - Py_ssize_t len; - unsigned int result; - - if ( !PyArg_ParseTuple(args, "y*|I:crc32", &pbin, &crc) ) - return NULL; - bin_data = pbin.buf; - len = pbin.len; - - crc = ~ crc; - while (len-- > 0) { - crc = crc_32_tab[(crc ^ *bin_data++) & 0xff] ^ (crc >> 8); - /* Note: (crc >> 8) MUST zero fill on left */ - } - - result = (crc ^ 0xFFFFFFFF); - PyBuffer_Release(&pbin); - return PyLong_FromUnsignedLong(result & 0xffffffff); + Py_buffer pbin; + unsigned char *bin_data; + unsigned int crc = 0; /* initial value of CRC */ + Py_ssize_t len; + unsigned int result; + + if ( !PyArg_ParseTuple(args, "y*|I:crc32", &pbin, &crc) ) + return NULL; + bin_data = pbin.buf; + len = pbin.len; + + crc = ~ crc; + while (len-- > 0) { + crc = crc_32_tab[(crc ^ *bin_data++) & 0xff] ^ (crc >> 8); + /* Note: (crc >> 8) MUST zero fill on left */ + } + + result = (crc ^ 0xFFFFFFFF); + PyBuffer_Release(&pbin); + return PyLong_FromUnsignedLong(result & 0xffffffff); } #endif /* USE_ZLIB_CRC32 */ @@ -1051,43 +1051,43 @@ static PyObject * binascii_hexlify(PyObject *self, PyObject *args) { - Py_buffer parg; - char* argbuf; - Py_ssize_t arglen; - PyObject *retval; - char* retbuf; - Py_ssize_t i, j; - - if (!PyArg_ParseTuple(args, "y*:b2a_hex", &parg)) - return NULL; - argbuf = parg.buf; - arglen = parg.len; - - assert(arglen >= 0); - if (arglen > PY_SSIZE_T_MAX / 2) { - PyBuffer_Release(&parg); - return PyErr_NoMemory(); - } - - retval = PyBytes_FromStringAndSize(NULL, arglen*2); - if (!retval) { - PyBuffer_Release(&parg); - return NULL; - } - retbuf = PyBytes_AS_STRING(retval); - - /* make hex version of string, taken from shamodule.c */ - for (i=j=0; i < arglen; i++) { - char c; - c = (argbuf[i] >> 4) & 0xf; - c = (c>9) ? c+'a'-10 : c + '0'; - retbuf[j++] = c; - c = argbuf[i] & 0xf; - c = (c>9) ? c+'a'-10 : c + '0'; - retbuf[j++] = c; - } - PyBuffer_Release(&parg); - return retval; + Py_buffer parg; + char* argbuf; + Py_ssize_t arglen; + PyObject *retval; + char* retbuf; + Py_ssize_t i, j; + + if (!PyArg_ParseTuple(args, "y*:b2a_hex", &parg)) + return NULL; + argbuf = parg.buf; + arglen = parg.len; + + assert(arglen >= 0); + if (arglen > PY_SSIZE_T_MAX / 2) { + PyBuffer_Release(&parg); + return PyErr_NoMemory(); + } + + retval = PyBytes_FromStringAndSize(NULL, arglen*2); + if (!retval) { + PyBuffer_Release(&parg); + return NULL; + } + retbuf = PyBytes_AS_STRING(retval); + + /* make hex version of string, taken from shamodule.c */ + for (i=j=0; i < arglen; i++) { + char c; + c = (argbuf[i] >> 4) & 0xf; + c = (c>9) ? c+'a'-10 : c + '0'; + retbuf[j++] = c; + c = argbuf[i] & 0xf; + c = (c>9) ? c+'a'-10 : c + '0'; + retbuf[j++] = c; + } + PyBuffer_Release(&parg); + return retval; } PyDoc_STRVAR(doc_hexlify, @@ -1099,69 +1099,69 @@ static int to_int(int c) { - if (isdigit(c)) - return c - '0'; - else { - if (isupper(c)) - c = tolower(c); - if (c >= 'a' && c <= 'f') - return c - 'a' + 10; - } - return -1; + if (isdigit(c)) + return c - '0'; + else { + if (isupper(c)) + c = tolower(c); + if (c >= 'a' && c <= 'f') + return c - 'a' + 10; + } + return -1; } static PyObject * binascii_unhexlify(PyObject *self, PyObject *args) { - Py_buffer parg; - char* argbuf; - Py_ssize_t arglen; - PyObject *retval; - char* retbuf; - Py_ssize_t i, j; - - if (!PyArg_ParseTuple(args, "s*:a2b_hex", &parg)) - return NULL; - argbuf = parg.buf; - arglen = parg.len; - - assert(arglen >= 0); - - /* XXX What should we do about strings with an odd length? Should - * we add an implicit leading zero, or a trailing zero? For now, - * raise an exception. - */ - if (arglen % 2) { - PyBuffer_Release(&parg); - PyErr_SetString(Error, "Odd-length string"); - return NULL; - } - - retval = PyBytes_FromStringAndSize(NULL, (arglen/2)); - if (!retval) { - PyBuffer_Release(&parg); - return NULL; - } - retbuf = PyBytes_AS_STRING(retval); - - for (i=j=0; i < arglen; i += 2) { - int top = to_int(Py_CHARMASK(argbuf[i])); - int bot = to_int(Py_CHARMASK(argbuf[i+1])); - if (top == -1 || bot == -1) { - PyErr_SetString(Error, - "Non-hexadecimal digit found"); - goto finally; - } - retbuf[j++] = (top << 4) + bot; - } - PyBuffer_Release(&parg); - return retval; + Py_buffer parg; + char* argbuf; + Py_ssize_t arglen; + PyObject *retval; + char* retbuf; + Py_ssize_t i, j; + + if (!PyArg_ParseTuple(args, "s*:a2b_hex", &parg)) + return NULL; + argbuf = parg.buf; + arglen = parg.len; + + assert(arglen >= 0); + + /* XXX What should we do about strings with an odd length? Should + * we add an implicit leading zero, or a trailing zero? For now, + * raise an exception. + */ + if (arglen % 2) { + PyBuffer_Release(&parg); + PyErr_SetString(Error, "Odd-length string"); + return NULL; + } + + retval = PyBytes_FromStringAndSize(NULL, (arglen/2)); + if (!retval) { + PyBuffer_Release(&parg); + return NULL; + } + retbuf = PyBytes_AS_STRING(retval); + + for (i=j=0; i < arglen; i += 2) { + int top = to_int(Py_CHARMASK(argbuf[i])); + int bot = to_int(Py_CHARMASK(argbuf[i+1])); + if (top == -1 || bot == -1) { + PyErr_SetString(Error, + "Non-hexadecimal digit found"); + goto finally; + } + retbuf[j++] = (top << 4) + bot; + } + PyBuffer_Release(&parg); + return retval; finally: - PyBuffer_Release(&parg); - Py_DECREF(retval); - return NULL; + PyBuffer_Release(&parg); + Py_DECREF(retval); + return NULL; } PyDoc_STRVAR(doc_unhexlify, @@ -1190,96 +1190,96 @@ static PyObject* binascii_a2b_qp(PyObject *self, PyObject *args, PyObject *kwargs) { - Py_ssize_t in, out; - char ch; - Py_buffer pdata; - unsigned char *data, *odata; - Py_ssize_t datalen = 0; - PyObject *rv; - static char *kwlist[] = {"data", "header", NULL}; - int header = 0; - - if (!PyArg_ParseTupleAndKeywords(args, kwargs, "s*|i", kwlist, &pdata, - &header)) - return NULL; - data = pdata.buf; - datalen = pdata.len; - - /* We allocate the output same size as input, this is overkill. - * The previous implementation used calloc() so we'll zero out the - * memory here too, since PyMem_Malloc() does not guarantee that. - */ - odata = (unsigned char *) PyMem_Malloc(datalen); - if (odata == NULL) { - PyBuffer_Release(&pdata); - PyErr_NoMemory(); - return NULL; - } - memset(odata, 0, datalen); - - in = out = 0; - while (in < datalen) { - if (data[in] == '=') { - in++; - if (in >= datalen) break; - /* Soft line breaks */ - if ((data[in] == '\n') || (data[in] == '\r')) { - if (data[in] != '\n') { - while (in < datalen && data[in] != '\n') in++; - } - if (in < datalen) in++; - } - else if (data[in] == '=') { - /* broken case from broken python qp */ - odata[out++] = '='; - in++; - } - else if (((data[in] >= 'A' && data[in] <= 'F') || - (data[in] >= 'a' && data[in] <= 'f') || - (data[in] >= '0' && data[in] <= '9')) && - ((data[in+1] >= 'A' && data[in+1] <= 'F') || - (data[in+1] >= 'a' && data[in+1] <= 'f') || - (data[in+1] >= '0' && data[in+1] <= '9'))) { - /* hexval */ - ch = hexval(data[in]) << 4; - in++; - ch |= hexval(data[in]); - in++; - odata[out++] = ch; - } - else { - odata[out++] = '='; - } - } - else if (header && data[in] == '_') { - odata[out++] = ' '; - in++; - } - else { - odata[out] = data[in]; - in++; - out++; - } - } - if ((rv = PyBytes_FromStringAndSize((char *)odata, out)) == NULL) { - PyBuffer_Release(&pdata); - PyMem_Free(odata); - return NULL; - } - PyBuffer_Release(&pdata); - PyMem_Free(odata); - return rv; + Py_ssize_t in, out; + char ch; + Py_buffer pdata; + unsigned char *data, *odata; + Py_ssize_t datalen = 0; + PyObject *rv; + static char *kwlist[] = {"data", "header", NULL}; + int header = 0; + + if (!PyArg_ParseTupleAndKeywords(args, kwargs, "s*|i", kwlist, &pdata, + &header)) + return NULL; + data = pdata.buf; + datalen = pdata.len; + + /* We allocate the output same size as input, this is overkill. + * The previous implementation used calloc() so we'll zero out the + * memory here too, since PyMem_Malloc() does not guarantee that. + */ + odata = (unsigned char *) PyMem_Malloc(datalen); + if (odata == NULL) { + PyBuffer_Release(&pdata); + PyErr_NoMemory(); + return NULL; + } + memset(odata, 0, datalen); + + in = out = 0; + while (in < datalen) { + if (data[in] == '=') { + in++; + if (in >= datalen) break; + /* Soft line breaks */ + if ((data[in] == '\n') || (data[in] == '\r')) { + if (data[in] != '\n') { + while (in < datalen && data[in] != '\n') in++; + } + if (in < datalen) in++; + } + else if (data[in] == '=') { + /* broken case from broken python qp */ + odata[out++] = '='; + in++; + } + else if (((data[in] >= 'A' && data[in] <= 'F') || + (data[in] >= 'a' && data[in] <= 'f') || + (data[in] >= '0' && data[in] <= '9')) && + ((data[in+1] >= 'A' && data[in+1] <= 'F') || + (data[in+1] >= 'a' && data[in+1] <= 'f') || + (data[in+1] >= '0' && data[in+1] <= '9'))) { + /* hexval */ + ch = hexval(data[in]) << 4; + in++; + ch |= hexval(data[in]); + in++; + odata[out++] = ch; + } + else { + odata[out++] = '='; + } + } + else if (header && data[in] == '_') { + odata[out++] = ' '; + in++; + } + else { + odata[out] = data[in]; + in++; + out++; + } + } + if ((rv = PyBytes_FromStringAndSize((char *)odata, out)) == NULL) { + PyBuffer_Release(&pdata); + PyMem_Free(odata); + return NULL; + } + PyBuffer_Release(&pdata); + PyMem_Free(odata); + return rv; } static int to_hex (unsigned char ch, unsigned char *s) { - unsigned int uvalue = ch; + unsigned int uvalue = ch; - s[1] = "0123456789ABCDEF"[uvalue % 16]; - uvalue = (uvalue / 16); - s[0] = "0123456789ABCDEF"[uvalue % 16]; - return 0; + s[1] = "0123456789ABCDEF"[uvalue % 16]; + uvalue = (uvalue / 16); + s[0] = "0123456789ABCDEF"[uvalue % 16]; + return 0; } PyDoc_STRVAR(doc_b2a_qp, @@ -1296,210 +1296,210 @@ static PyObject* binascii_b2a_qp (PyObject *self, PyObject *args, PyObject *kwargs) { - Py_ssize_t in, out; - Py_buffer pdata; - unsigned char *data, *odata; - Py_ssize_t datalen = 0, odatalen = 0; - PyObject *rv; - unsigned int linelen = 0; - static char *kwlist[] = {"data", "quotetabs", "istext", - "header", NULL}; - int istext = 1; - int quotetabs = 0; - int header = 0; - unsigned char ch; - int crlf = 0; - unsigned char *p; - - if (!PyArg_ParseTupleAndKeywords(args, kwargs, "y*|iii", kwlist, &pdata, - "etabs, &istext, &header)) - return NULL; - data = pdata.buf; - datalen = pdata.len; - - /* See if this string is using CRLF line ends */ - /* XXX: this function has the side effect of converting all of - * the end of lines to be the same depending on this detection - * here */ - p = (unsigned char *) memchr(data, '\n', datalen); - if ((p != NULL) && (p > data) && (*(p-1) == '\r')) - crlf = 1; - - /* First, scan to see how many characters need to be encoded */ - in = 0; - while (in < datalen) { - if ((data[in] > 126) || - (data[in] == '=') || - (header && data[in] == '_') || - ((data[in] == '.') && (linelen == 0) && - (data[in+1] == '\n' || data[in+1] == '\r' || data[in+1] == 0)) || - (!istext && ((data[in] == '\r') || (data[in] == '\n'))) || - ((data[in] == '\t' || data[in] == ' ') && (in + 1 == datalen)) || - ((data[in] < 33) && - (data[in] != '\r') && (data[in] != '\n') && - (quotetabs || - (!quotetabs && ((data[in] != '\t') && (data[in] != ' ')))))) - { - if ((linelen + 3) >= MAXLINESIZE) { - linelen = 0; - if (crlf) - odatalen += 3; - else - odatalen += 2; - } - linelen += 3; - odatalen += 3; - in++; - } - else { - if (istext && - ((data[in] == '\n') || - ((in+1 < datalen) && (data[in] == '\r') && - (data[in+1] == '\n')))) - { - linelen = 0; - /* Protect against whitespace on end of line */ - if (in && ((data[in-1] == ' ') || (data[in-1] == '\t'))) - odatalen += 2; - if (crlf) - odatalen += 2; - else - odatalen += 1; - if (data[in] == '\r') - in += 2; - else - in++; - } - else { - if ((in + 1 != datalen) && - (data[in+1] != '\n') && - (linelen + 1) >= MAXLINESIZE) { - linelen = 0; - if (crlf) - odatalen += 3; - else - odatalen += 2; - } - linelen++; - odatalen++; - in++; - } - } - } - - /* We allocate the output same size as input, this is overkill. - * The previous implementation used calloc() so we'll zero out the - * memory here too, since PyMem_Malloc() does not guarantee that. - */ - odata = (unsigned char *) PyMem_Malloc(odatalen); - if (odata == NULL) { - PyBuffer_Release(&pdata); - PyErr_NoMemory(); - return NULL; - } - memset(odata, 0, odatalen); - - in = out = linelen = 0; - while (in < datalen) { - if ((data[in] > 126) || - (data[in] == '=') || - (header && data[in] == '_') || - ((data[in] == '.') && (linelen == 0) && - (data[in+1] == '\n' || data[in+1] == '\r' || data[in+1] == 0)) || - (!istext && ((data[in] == '\r') || (data[in] == '\n'))) || - ((data[in] == '\t' || data[in] == ' ') && (in + 1 == datalen)) || - ((data[in] < 33) && - (data[in] != '\r') && (data[in] != '\n') && - (quotetabs || - (!quotetabs && ((data[in] != '\t') && (data[in] != ' ')))))) - { - if ((linelen + 3 )>= MAXLINESIZE) { - odata[out++] = '='; - if (crlf) odata[out++] = '\r'; - odata[out++] = '\n'; - linelen = 0; - } - odata[out++] = '='; - to_hex(data[in], &odata[out]); - out += 2; - in++; - linelen += 3; - } - else { - if (istext && - ((data[in] == '\n') || - ((in+1 < datalen) && (data[in] == '\r') && - (data[in+1] == '\n')))) - { - linelen = 0; - /* Protect against whitespace on end of line */ - if (out && ((odata[out-1] == ' ') || (odata[out-1] == '\t'))) { - ch = odata[out-1]; - odata[out-1] = '='; - to_hex(ch, &odata[out]); - out += 2; - } - - if (crlf) odata[out++] = '\r'; - odata[out++] = '\n'; - if (data[in] == '\r') - in += 2; - else - in++; - } - else { - if ((in + 1 != datalen) && - (data[in+1] != '\n') && - (linelen + 1) >= MAXLINESIZE) { - odata[out++] = '='; - if (crlf) odata[out++] = '\r'; - odata[out++] = '\n'; - linelen = 0; - } - linelen++; - if (header && data[in] == ' ') { - odata[out++] = '_'; - in++; - } - else { - odata[out++] = data[in++]; - } - } - } - } - if ((rv = PyBytes_FromStringAndSize((char *)odata, out)) == NULL) { - PyBuffer_Release(&pdata); - PyMem_Free(odata); - return NULL; - } - PyBuffer_Release(&pdata); - PyMem_Free(odata); - return rv; + Py_ssize_t in, out; + Py_buffer pdata; + unsigned char *data, *odata; + Py_ssize_t datalen = 0, odatalen = 0; + PyObject *rv; + unsigned int linelen = 0; + static char *kwlist[] = {"data", "quotetabs", "istext", + "header", NULL}; + int istext = 1; + int quotetabs = 0; + int header = 0; + unsigned char ch; + int crlf = 0; + unsigned char *p; + + if (!PyArg_ParseTupleAndKeywords(args, kwargs, "y*|iii", kwlist, &pdata, + "etabs, &istext, &header)) + return NULL; + data = pdata.buf; + datalen = pdata.len; + + /* See if this string is using CRLF line ends */ + /* XXX: this function has the side effect of converting all of + * the end of lines to be the same depending on this detection + * here */ + p = (unsigned char *) memchr(data, '\n', datalen); + if ((p != NULL) && (p > data) && (*(p-1) == '\r')) + crlf = 1; + + /* First, scan to see how many characters need to be encoded */ + in = 0; + while (in < datalen) { + if ((data[in] > 126) || + (data[in] == '=') || + (header && data[in] == '_') || + ((data[in] == '.') && (linelen == 0) && + (data[in+1] == '\n' || data[in+1] == '\r' || data[in+1] == 0)) || + (!istext && ((data[in] == '\r') || (data[in] == '\n'))) || + ((data[in] == '\t' || data[in] == ' ') && (in + 1 == datalen)) || + ((data[in] < 33) && + (data[in] != '\r') && (data[in] != '\n') && + (quotetabs || + (!quotetabs && ((data[in] != '\t') && (data[in] != ' ')))))) + { + if ((linelen + 3) >= MAXLINESIZE) { + linelen = 0; + if (crlf) + odatalen += 3; + else + odatalen += 2; + } + linelen += 3; + odatalen += 3; + in++; + } + else { + if (istext && + ((data[in] == '\n') || + ((in+1 < datalen) && (data[in] == '\r') && + (data[in+1] == '\n')))) + { + linelen = 0; + /* Protect against whitespace on end of line */ + if (in && ((data[in-1] == ' ') || (data[in-1] == '\t'))) + odatalen += 2; + if (crlf) + odatalen += 2; + else + odatalen += 1; + if (data[in] == '\r') + in += 2; + else + in++; + } + else { + if ((in + 1 != datalen) && + (data[in+1] != '\n') && + (linelen + 1) >= MAXLINESIZE) { + linelen = 0; + if (crlf) + odatalen += 3; + else + odatalen += 2; + } + linelen++; + odatalen++; + in++; + } + } + } + + /* We allocate the output same size as input, this is overkill. + * The previous implementation used calloc() so we'll zero out the + * memory here too, since PyMem_Malloc() does not guarantee that. + */ + odata = (unsigned char *) PyMem_Malloc(odatalen); + if (odata == NULL) { + PyBuffer_Release(&pdata); + PyErr_NoMemory(); + return NULL; + } + memset(odata, 0, odatalen); + + in = out = linelen = 0; + while (in < datalen) { + if ((data[in] > 126) || + (data[in] == '=') || + (header && data[in] == '_') || + ((data[in] == '.') && (linelen == 0) && + (data[in+1] == '\n' || data[in+1] == '\r' || data[in+1] == 0)) || + (!istext && ((data[in] == '\r') || (data[in] == '\n'))) || + ((data[in] == '\t' || data[in] == ' ') && (in + 1 == datalen)) || + ((data[in] < 33) && + (data[in] != '\r') && (data[in] != '\n') && + (quotetabs || + (!quotetabs && ((data[in] != '\t') && (data[in] != ' ')))))) + { + if ((linelen + 3 )>= MAXLINESIZE) { + odata[out++] = '='; + if (crlf) odata[out++] = '\r'; + odata[out++] = '\n'; + linelen = 0; + } + odata[out++] = '='; + to_hex(data[in], &odata[out]); + out += 2; + in++; + linelen += 3; + } + else { + if (istext && + ((data[in] == '\n') || + ((in+1 < datalen) && (data[in] == '\r') && + (data[in+1] == '\n')))) + { + linelen = 0; + /* Protect against whitespace on end of line */ + if (out && ((odata[out-1] == ' ') || (odata[out-1] == '\t'))) { + ch = odata[out-1]; + odata[out-1] = '='; + to_hex(ch, &odata[out]); + out += 2; + } + + if (crlf) odata[out++] = '\r'; + odata[out++] = '\n'; + if (data[in] == '\r') + in += 2; + else + in++; + } + else { + if ((in + 1 != datalen) && + (data[in+1] != '\n') && + (linelen + 1) >= MAXLINESIZE) { + odata[out++] = '='; + if (crlf) odata[out++] = '\r'; + odata[out++] = '\n'; + linelen = 0; + } + linelen++; + if (header && data[in] == ' ') { + odata[out++] = '_'; + in++; + } + else { + odata[out++] = data[in++]; + } + } + } + } + if ((rv = PyBytes_FromStringAndSize((char *)odata, out)) == NULL) { + PyBuffer_Release(&pdata); + PyMem_Free(odata); + return NULL; + } + PyBuffer_Release(&pdata); + PyMem_Free(odata); + return rv; } /* List of functions defined in the module */ static struct PyMethodDef binascii_module_methods[] = { - {"a2b_uu", binascii_a2b_uu, METH_VARARGS, doc_a2b_uu}, - {"b2a_uu", binascii_b2a_uu, METH_VARARGS, doc_b2a_uu}, - {"a2b_base64", binascii_a2b_base64, METH_VARARGS, doc_a2b_base64}, - {"b2a_base64", binascii_b2a_base64, METH_VARARGS, doc_b2a_base64}, - {"a2b_hqx", binascii_a2b_hqx, METH_VARARGS, doc_a2b_hqx}, - {"b2a_hqx", binascii_b2a_hqx, METH_VARARGS, doc_b2a_hqx}, - {"b2a_hex", binascii_hexlify, METH_VARARGS, doc_hexlify}, - {"a2b_hex", binascii_unhexlify, METH_VARARGS, doc_unhexlify}, - {"hexlify", binascii_hexlify, METH_VARARGS, doc_hexlify}, - {"unhexlify", binascii_unhexlify, METH_VARARGS, doc_unhexlify}, - {"rlecode_hqx", binascii_rlecode_hqx, METH_VARARGS, doc_rlecode_hqx}, - {"rledecode_hqx", binascii_rledecode_hqx, METH_VARARGS, - doc_rledecode_hqx}, - {"crc_hqx", binascii_crc_hqx, METH_VARARGS, doc_crc_hqx}, - {"crc32", binascii_crc32, METH_VARARGS, doc_crc32}, - {"a2b_qp", (PyCFunction)binascii_a2b_qp, METH_VARARGS | METH_KEYWORDS, - doc_a2b_qp}, - {"b2a_qp", (PyCFunction)binascii_b2a_qp, METH_VARARGS | METH_KEYWORDS, - doc_b2a_qp}, - {NULL, NULL} /* sentinel */ + {"a2b_uu", binascii_a2b_uu, METH_VARARGS, doc_a2b_uu}, + {"b2a_uu", binascii_b2a_uu, METH_VARARGS, doc_b2a_uu}, + {"a2b_base64", binascii_a2b_base64, METH_VARARGS, doc_a2b_base64}, + {"b2a_base64", binascii_b2a_base64, METH_VARARGS, doc_b2a_base64}, + {"a2b_hqx", binascii_a2b_hqx, METH_VARARGS, doc_a2b_hqx}, + {"b2a_hqx", binascii_b2a_hqx, METH_VARARGS, doc_b2a_hqx}, + {"b2a_hex", binascii_hexlify, METH_VARARGS, doc_hexlify}, + {"a2b_hex", binascii_unhexlify, METH_VARARGS, doc_unhexlify}, + {"hexlify", binascii_hexlify, METH_VARARGS, doc_hexlify}, + {"unhexlify", binascii_unhexlify, METH_VARARGS, doc_unhexlify}, + {"rlecode_hqx", binascii_rlecode_hqx, METH_VARARGS, doc_rlecode_hqx}, + {"rledecode_hqx", binascii_rledecode_hqx, METH_VARARGS, + doc_rledecode_hqx}, + {"crc_hqx", binascii_crc_hqx, METH_VARARGS, doc_crc_hqx}, + {"crc32", binascii_crc32, METH_VARARGS, doc_crc32}, + {"a2b_qp", (PyCFunction)binascii_a2b_qp, METH_VARARGS | METH_KEYWORDS, + doc_a2b_qp}, + {"b2a_qp", (PyCFunction)binascii_b2a_qp, METH_VARARGS | METH_KEYWORDS, + doc_b2a_qp}, + {NULL, NULL} /* sentinel */ }; @@ -1508,36 +1508,36 @@ static struct PyModuleDef binasciimodule = { - PyModuleDef_HEAD_INIT, - "binascii", - doc_binascii, - -1, - binascii_module_methods, - NULL, - NULL, - NULL, - NULL + PyModuleDef_HEAD_INIT, + "binascii", + doc_binascii, + -1, + binascii_module_methods, + NULL, + NULL, + NULL, + NULL }; PyMODINIT_FUNC PyInit_binascii(void) { - PyObject *m, *d; + PyObject *m, *d; + + /* Create the module and add the functions */ + m = PyModule_Create(&binasciimodule); + if (m == NULL) + return NULL; + + d = PyModule_GetDict(m); - /* Create the module and add the functions */ - m = PyModule_Create(&binasciimodule); - if (m == NULL) - return NULL; - - d = PyModule_GetDict(m); - - Error = PyErr_NewException("binascii.Error", PyExc_ValueError, NULL); - PyDict_SetItemString(d, "Error", Error); - Incomplete = PyErr_NewException("binascii.Incomplete", NULL, NULL); - PyDict_SetItemString(d, "Incomplete", Incomplete); - if (PyErr_Occurred()) { - Py_DECREF(m); - m = NULL; - } - return m; + Error = PyErr_NewException("binascii.Error", PyExc_ValueError, NULL); + PyDict_SetItemString(d, "Error", Error); + Incomplete = PyErr_NewException("binascii.Incomplete", NULL, NULL); + PyDict_SetItemString(d, "Incomplete", Incomplete); + if (PyErr_Occurred()) { + Py_DECREF(m); + m = NULL; + } + return m; } Modified: python/branches/py3k/Modules/bz2module.c ============================================================================== --- python/branches/py3k/Modules/bz2module.c (original) +++ python/branches/py3k/Modules/bz2module.c Sun May 9 17:52:27 2010 @@ -41,20 +41,20 @@ #define MODE_READ_EOF 2 #define MODE_WRITE 3 -#define BZ2FileObject_Check(v) (Py_TYPE(v) == &BZ2File_Type) +#define BZ2FileObject_Check(v) (Py_TYPE(v) == &BZ2File_Type) #ifdef BZ_CONFIG_ERROR #if SIZEOF_LONG >= 8 #define BZS_TOTAL_OUT(bzs) \ - (((long)bzs->total_out_hi32 << 32) + bzs->total_out_lo32) + (((long)bzs->total_out_hi32 << 32) + bzs->total_out_lo32) #elif SIZEOF_LONG_LONG >= 8 #define BZS_TOTAL_OUT(bzs) \ - (((PY_LONG_LONG)bzs->total_out_hi32 << 32) + bzs->total_out_lo32) + (((PY_LONG_LONG)bzs->total_out_hi32 << 32) + bzs->total_out_lo32) #else #define BZS_TOTAL_OUT(bzs) \ - bzs->total_out_lo32 + bzs->total_out_lo32 #endif #else /* ! BZ_CONFIG_ERROR */ @@ -79,11 +79,11 @@ #ifdef WITH_THREAD #define ACQUIRE_LOCK(obj) do { \ - if (!PyThread_acquire_lock(obj->lock, 0)) { \ - Py_BEGIN_ALLOW_THREADS \ - PyThread_acquire_lock(obj->lock, 1); \ - Py_END_ALLOW_THREADS \ - } } while(0) + if (!PyThread_acquire_lock(obj->lock, 0)) { \ + Py_BEGIN_ALLOW_THREADS \ + PyThread_acquire_lock(obj->lock, 1); \ + Py_END_ALLOW_THREADS \ + } } while(0) #define RELEASE_LOCK(obj) PyThread_release_lock(obj->lock) #else #define ACQUIRE_LOCK(obj) @@ -91,47 +91,47 @@ #endif /* Bits in f_newlinetypes */ -#define NEWLINE_UNKNOWN 0 /* No newline seen, yet */ -#define NEWLINE_CR 1 /* \r newline seen */ -#define NEWLINE_LF 2 /* \n newline seen */ -#define NEWLINE_CRLF 4 /* \r\n newline seen */ +#define NEWLINE_UNKNOWN 0 /* No newline seen, yet */ +#define NEWLINE_CR 1 /* \r newline seen */ +#define NEWLINE_LF 2 /* \n newline seen */ +#define NEWLINE_CRLF 4 /* \r\n newline seen */ /* ===================================================================== */ /* Structure definitions. */ typedef struct { - PyObject_HEAD - FILE *rawfp; + PyObject_HEAD + FILE *rawfp; - char* f_buf; /* Allocated readahead buffer */ - char* f_bufend; /* Points after last occupied position */ - char* f_bufptr; /* Current buffer position */ - - BZFILE *fp; - int mode; - Py_off_t pos; - Py_off_t size; + char* f_buf; /* Allocated readahead buffer */ + char* f_bufend; /* Points after last occupied position */ + char* f_bufptr; /* Current buffer position */ + + BZFILE *fp; + int mode; + Py_off_t pos; + Py_off_t size; #ifdef WITH_THREAD - PyThread_type_lock lock; + PyThread_type_lock lock; #endif } BZ2FileObject; typedef struct { - PyObject_HEAD - bz_stream bzs; - int running; + PyObject_HEAD + bz_stream bzs; + int running; #ifdef WITH_THREAD - PyThread_type_lock lock; + PyThread_type_lock lock; #endif } BZ2CompObject; typedef struct { - PyObject_HEAD - bz_stream bzs; - int running; - PyObject *unused_data; + PyObject_HEAD + bz_stream bzs; + int running; + PyObject *unused_data; #ifdef WITH_THREAD - PyThread_type_lock lock; + PyThread_type_lock lock; #endif } BZ2DecompObject; @@ -141,59 +141,59 @@ static int Util_CatchBZ2Error(int bzerror) { - int ret = 0; - switch(bzerror) { - case BZ_OK: - case BZ_STREAM_END: - break; + int ret = 0; + switch(bzerror) { + case BZ_OK: + case BZ_STREAM_END: + break; #ifdef BZ_CONFIG_ERROR - case BZ_CONFIG_ERROR: - PyErr_SetString(PyExc_SystemError, - "the bz2 library was not compiled " - "correctly"); - ret = 1; - break; + case BZ_CONFIG_ERROR: + PyErr_SetString(PyExc_SystemError, + "the bz2 library was not compiled " + "correctly"); + ret = 1; + break; #endif - case BZ_PARAM_ERROR: - PyErr_SetString(PyExc_ValueError, - "the bz2 library has received wrong " - "parameters"); - ret = 1; - break; - - case BZ_MEM_ERROR: - PyErr_NoMemory(); - ret = 1; - break; - - case BZ_DATA_ERROR: - case BZ_DATA_ERROR_MAGIC: - PyErr_SetString(PyExc_IOError, "invalid data stream"); - ret = 1; - break; - - case BZ_IO_ERROR: - PyErr_SetString(PyExc_IOError, "unknown IO error"); - ret = 1; - break; - - case BZ_UNEXPECTED_EOF: - PyErr_SetString(PyExc_EOFError, - "compressed file ended before the " - "logical end-of-stream was detected"); - ret = 1; - break; - - case BZ_SEQUENCE_ERROR: - PyErr_SetString(PyExc_RuntimeError, - "wrong sequence of bz2 library " - "commands used"); - ret = 1; - break; - } - return ret; + case BZ_PARAM_ERROR: + PyErr_SetString(PyExc_ValueError, + "the bz2 library has received wrong " + "parameters"); + ret = 1; + break; + + case BZ_MEM_ERROR: + PyErr_NoMemory(); + ret = 1; + break; + + case BZ_DATA_ERROR: + case BZ_DATA_ERROR_MAGIC: + PyErr_SetString(PyExc_IOError, "invalid data stream"); + ret = 1; + break; + + case BZ_IO_ERROR: + PyErr_SetString(PyExc_IOError, "unknown IO error"); + ret = 1; + break; + + case BZ_UNEXPECTED_EOF: + PyErr_SetString(PyExc_EOFError, + "compressed file ended before the " + "logical end-of-stream was detected"); + ret = 1; + break; + + case BZ_SEQUENCE_ERROR: + PyErr_SetString(PyExc_RuntimeError, + "wrong sequence of bz2 library " + "commands used"); + ret = 1; + break; + } + return ret; } #if BUFSIZ < 8192 @@ -212,134 +212,134 @@ static size_t Util_NewBufferSize(size_t currentsize) { - if (currentsize > SMALLCHUNK) { - /* Keep doubling until we reach BIGCHUNK; - then keep adding BIGCHUNK. */ - if (currentsize <= BIGCHUNK) - return currentsize + currentsize; - else - return currentsize + BIGCHUNK; - } - return currentsize + SMALLCHUNK; + if (currentsize > SMALLCHUNK) { + /* Keep doubling until we reach BIGCHUNK; + then keep adding BIGCHUNK. */ + if (currentsize <= BIGCHUNK) + return currentsize + currentsize; + else + return currentsize + BIGCHUNK; + } + return currentsize + SMALLCHUNK; } /* This is a hacked version of Python's fileobject.c:get_line(). */ static PyObject * Util_GetLine(BZ2FileObject *f, int n) { - char c; - char *buf, *end; - size_t total_v_size; /* total # of slots in buffer */ - size_t used_v_size; /* # used slots in buffer */ - size_t increment; /* amount to increment the buffer */ - PyObject *v; - int bzerror; - int bytes_read; - - total_v_size = n > 0 ? n : 100; - v = PyBytes_FromStringAndSize((char *)NULL, total_v_size); - if (v == NULL) - return NULL; - - buf = BUF(v); - end = buf + total_v_size; - - for (;;) { - Py_BEGIN_ALLOW_THREADS - do { - bytes_read = BZ2_bzRead(&bzerror, f->fp, &c, 1); - f->pos++; - if (bytes_read == 0) - break; - *buf++ = c; - } while (bzerror == BZ_OK && c != '\n' && buf != end); - Py_END_ALLOW_THREADS - if (bzerror == BZ_STREAM_END) { - f->size = f->pos; - f->mode = MODE_READ_EOF; - break; - } else if (bzerror != BZ_OK) { - Util_CatchBZ2Error(bzerror); - Py_DECREF(v); - return NULL; - } - if (c == '\n') - break; - /* Must be because buf == end */ - if (n > 0) - break; - used_v_size = total_v_size; - increment = total_v_size >> 2; /* mild exponential growth */ - total_v_size += increment; - if (total_v_size > INT_MAX) { - PyErr_SetString(PyExc_OverflowError, - "line is longer than a Python string can hold"); - Py_DECREF(v); - return NULL; - } - if (_PyBytes_Resize(&v, total_v_size) < 0) { - return NULL; - } - buf = BUF(v) + used_v_size; - end = BUF(v) + total_v_size; - } - - used_v_size = buf - BUF(v); - if (used_v_size != total_v_size) { - if (_PyBytes_Resize(&v, used_v_size) < 0) { - v = NULL; - } - } - return v; + char c; + char *buf, *end; + size_t total_v_size; /* total # of slots in buffer */ + size_t used_v_size; /* # used slots in buffer */ + size_t increment; /* amount to increment the buffer */ + PyObject *v; + int bzerror; + int bytes_read; + + total_v_size = n > 0 ? n : 100; + v = PyBytes_FromStringAndSize((char *)NULL, total_v_size); + if (v == NULL) + return NULL; + + buf = BUF(v); + end = buf + total_v_size; + + for (;;) { + Py_BEGIN_ALLOW_THREADS + do { + bytes_read = BZ2_bzRead(&bzerror, f->fp, &c, 1); + f->pos++; + if (bytes_read == 0) + break; + *buf++ = c; + } while (bzerror == BZ_OK && c != '\n' && buf != end); + Py_END_ALLOW_THREADS + if (bzerror == BZ_STREAM_END) { + f->size = f->pos; + f->mode = MODE_READ_EOF; + break; + } else if (bzerror != BZ_OK) { + Util_CatchBZ2Error(bzerror); + Py_DECREF(v); + return NULL; + } + if (c == '\n') + break; + /* Must be because buf == end */ + if (n > 0) + break; + used_v_size = total_v_size; + increment = total_v_size >> 2; /* mild exponential growth */ + total_v_size += increment; + if (total_v_size > INT_MAX) { + PyErr_SetString(PyExc_OverflowError, + "line is longer than a Python string can hold"); + Py_DECREF(v); + return NULL; + } + if (_PyBytes_Resize(&v, total_v_size) < 0) { + return NULL; + } + buf = BUF(v) + used_v_size; + end = BUF(v) + total_v_size; + } + + used_v_size = buf - BUF(v); + if (used_v_size != total_v_size) { + if (_PyBytes_Resize(&v, used_v_size) < 0) { + v = NULL; + } + } + return v; } /* This is a hacked version of Python's fileobject.c:drop_readahead(). */ static void Util_DropReadAhead(BZ2FileObject *f) { - if (f->f_buf != NULL) { - PyMem_Free(f->f_buf); - f->f_buf = NULL; - } + if (f->f_buf != NULL) { + PyMem_Free(f->f_buf); + f->f_buf = NULL; + } } /* This is a hacked version of Python's fileobject.c:readahead(). */ static int Util_ReadAhead(BZ2FileObject *f, int bufsize) { - int chunksize; - int bzerror; + int chunksize; + int bzerror; - if (f->f_buf != NULL) { - if((f->f_bufend - f->f_bufptr) >= 1) - return 0; - else - Util_DropReadAhead(f); - } - if (f->mode == MODE_READ_EOF) { - f->f_bufptr = f->f_buf; - f->f_bufend = f->f_buf; - return 0; - } - if ((f->f_buf = PyMem_Malloc(bufsize)) == NULL) { - PyErr_NoMemory(); - return -1; - } - Py_BEGIN_ALLOW_THREADS - chunksize = BZ2_bzRead(&bzerror, f->fp, f->f_buf, bufsize); - Py_END_ALLOW_THREADS - f->pos += chunksize; - if (bzerror == BZ_STREAM_END) { - f->size = f->pos; - f->mode = MODE_READ_EOF; - } else if (bzerror != BZ_OK) { - Util_CatchBZ2Error(bzerror); - Util_DropReadAhead(f); - return -1; - } - f->f_bufptr = f->f_buf; - f->f_bufend = f->f_buf + chunksize; - return 0; + if (f->f_buf != NULL) { + if((f->f_bufend - f->f_bufptr) >= 1) + return 0; + else + Util_DropReadAhead(f); + } + if (f->mode == MODE_READ_EOF) { + f->f_bufptr = f->f_buf; + f->f_bufend = f->f_buf; + return 0; + } + if ((f->f_buf = PyMem_Malloc(bufsize)) == NULL) { + PyErr_NoMemory(); + return -1; + } + Py_BEGIN_ALLOW_THREADS + chunksize = BZ2_bzRead(&bzerror, f->fp, f->f_buf, bufsize); + Py_END_ALLOW_THREADS + f->pos += chunksize; + if (bzerror == BZ_STREAM_END) { + f->size = f->pos; + f->mode = MODE_READ_EOF; + } else if (bzerror != BZ_OK) { + Util_CatchBZ2Error(bzerror); + Util_DropReadAhead(f); + return -1; + } + f->f_bufptr = f->f_buf; + f->f_bufend = f->f_buf + chunksize; + return 0; } /* This is a hacked version of Python's @@ -347,45 +347,45 @@ static PyBytesObject * Util_ReadAheadGetLineSkip(BZ2FileObject *f, int skip, int bufsize) { - PyBytesObject* s; - char *bufptr; - char *buf; - int len; - - if (f->f_buf == NULL) - if (Util_ReadAhead(f, bufsize) < 0) - return NULL; - - len = f->f_bufend - f->f_bufptr; - if (len == 0) - return (PyBytesObject *) - PyBytes_FromStringAndSize(NULL, skip); - bufptr = memchr(f->f_bufptr, '\n', len); - if (bufptr != NULL) { - bufptr++; /* Count the '\n' */ - len = bufptr - f->f_bufptr; - s = (PyBytesObject *) - PyBytes_FromStringAndSize(NULL, skip+len); - if (s == NULL) - return NULL; - memcpy(PyBytes_AS_STRING(s)+skip, f->f_bufptr, len); - f->f_bufptr = bufptr; - if (bufptr == f->f_bufend) - Util_DropReadAhead(f); - } else { - bufptr = f->f_bufptr; - buf = f->f_buf; - f->f_buf = NULL; /* Force new readahead buffer */ - s = Util_ReadAheadGetLineSkip(f, skip+len, - bufsize + (bufsize>>2)); - if (s == NULL) { - PyMem_Free(buf); - return NULL; - } - memcpy(PyBytes_AS_STRING(s)+skip, bufptr, len); - PyMem_Free(buf); - } - return s; + PyBytesObject* s; + char *bufptr; + char *buf; + int len; + + if (f->f_buf == NULL) + if (Util_ReadAhead(f, bufsize) < 0) + return NULL; + + len = f->f_bufend - f->f_bufptr; + if (len == 0) + return (PyBytesObject *) + PyBytes_FromStringAndSize(NULL, skip); + bufptr = memchr(f->f_bufptr, '\n', len); + if (bufptr != NULL) { + bufptr++; /* Count the '\n' */ + len = bufptr - f->f_bufptr; + s = (PyBytesObject *) + PyBytes_FromStringAndSize(NULL, skip+len); + if (s == NULL) + return NULL; + memcpy(PyBytes_AS_STRING(s)+skip, f->f_bufptr, len); + f->f_bufptr = bufptr; + if (bufptr == f->f_bufend) + Util_DropReadAhead(f); + } else { + bufptr = f->f_bufptr; + buf = f->f_buf; + f->f_buf = NULL; /* Force new readahead buffer */ + s = Util_ReadAheadGetLineSkip(f, skip+len, + bufsize + (bufsize>>2)); + if (s == NULL) { + PyMem_Free(buf); + return NULL; + } + memcpy(PyBytes_AS_STRING(s)+skip, bufptr, len); + PyMem_Free(buf); + } + return s; } /* ===================================================================== */ @@ -402,83 +402,83 @@ static PyObject * BZ2File_read(BZ2FileObject *self, PyObject *args) { - long bytesrequested = -1; - size_t bytesread, buffersize, chunksize; - int bzerror; - PyObject *ret = NULL; - - if (!PyArg_ParseTuple(args, "|l:read", &bytesrequested)) - return NULL; - - ACQUIRE_LOCK(self); - switch (self->mode) { - case MODE_READ: - break; - case MODE_READ_EOF: - ret = PyBytes_FromStringAndSize("", 0); - goto cleanup; - case MODE_CLOSED: - PyErr_SetString(PyExc_ValueError, - "I/O operation on closed file"); - goto cleanup; - default: - PyErr_SetString(PyExc_IOError, - "file is not ready for reading"); - goto cleanup; - } - - if (bytesrequested < 0) - buffersize = Util_NewBufferSize((size_t)0); - else - buffersize = bytesrequested; - if (buffersize > INT_MAX) { - PyErr_SetString(PyExc_OverflowError, - "requested number of bytes is " - "more than a Python string can hold"); - goto cleanup; - } - ret = PyBytes_FromStringAndSize((char *)NULL, buffersize); - if (ret == NULL || buffersize == 0) - goto cleanup; - bytesread = 0; - - for (;;) { - Py_BEGIN_ALLOW_THREADS - chunksize = BZ2_bzRead(&bzerror, self->fp, - BUF(ret)+bytesread, - buffersize-bytesread); - self->pos += chunksize; - Py_END_ALLOW_THREADS - bytesread += chunksize; - if (bzerror == BZ_STREAM_END) { - self->size = self->pos; - self->mode = MODE_READ_EOF; - break; - } else if (bzerror != BZ_OK) { - Util_CatchBZ2Error(bzerror); - Py_DECREF(ret); - ret = NULL; - goto cleanup; - } - if (bytesrequested < 0) { - buffersize = Util_NewBufferSize(buffersize); - if (_PyBytes_Resize(&ret, buffersize) < 0) { - ret = NULL; - goto cleanup; - } - } else { - break; - } - } - if (bytesread != buffersize) { - if (_PyBytes_Resize(&ret, bytesread) < 0) { - ret = NULL; - } - } + long bytesrequested = -1; + size_t bytesread, buffersize, chunksize; + int bzerror; + PyObject *ret = NULL; + + if (!PyArg_ParseTuple(args, "|l:read", &bytesrequested)) + return NULL; + + ACQUIRE_LOCK(self); + switch (self->mode) { + case MODE_READ: + break; + case MODE_READ_EOF: + ret = PyBytes_FromStringAndSize("", 0); + goto cleanup; + case MODE_CLOSED: + PyErr_SetString(PyExc_ValueError, + "I/O operation on closed file"); + goto cleanup; + default: + PyErr_SetString(PyExc_IOError, + "file is not ready for reading"); + goto cleanup; + } + + if (bytesrequested < 0) + buffersize = Util_NewBufferSize((size_t)0); + else + buffersize = bytesrequested; + if (buffersize > INT_MAX) { + PyErr_SetString(PyExc_OverflowError, + "requested number of bytes is " + "more than a Python string can hold"); + goto cleanup; + } + ret = PyBytes_FromStringAndSize((char *)NULL, buffersize); + if (ret == NULL || buffersize == 0) + goto cleanup; + bytesread = 0; + + for (;;) { + Py_BEGIN_ALLOW_THREADS + chunksize = BZ2_bzRead(&bzerror, self->fp, + BUF(ret)+bytesread, + buffersize-bytesread); + self->pos += chunksize; + Py_END_ALLOW_THREADS + bytesread += chunksize; + if (bzerror == BZ_STREAM_END) { + self->size = self->pos; + self->mode = MODE_READ_EOF; + break; + } else if (bzerror != BZ_OK) { + Util_CatchBZ2Error(bzerror); + Py_DECREF(ret); + ret = NULL; + goto cleanup; + } + if (bytesrequested < 0) { + buffersize = Util_NewBufferSize(buffersize); + if (_PyBytes_Resize(&ret, buffersize) < 0) { + ret = NULL; + goto cleanup; + } + } else { + break; + } + } + if (bytesread != buffersize) { + if (_PyBytes_Resize(&ret, bytesread) < 0) { + ret = NULL; + } + } cleanup: - RELEASE_LOCK(self); - return ret; + RELEASE_LOCK(self); + return ret; } PyDoc_STRVAR(BZ2File_readline__doc__, @@ -493,37 +493,37 @@ static PyObject * BZ2File_readline(BZ2FileObject *self, PyObject *args) { - PyObject *ret = NULL; - int sizehint = -1; + PyObject *ret = NULL; + int sizehint = -1; - if (!PyArg_ParseTuple(args, "|i:readline", &sizehint)) - return NULL; + if (!PyArg_ParseTuple(args, "|i:readline", &sizehint)) + return NULL; - ACQUIRE_LOCK(self); - switch (self->mode) { - case MODE_READ: - break; - case MODE_READ_EOF: - ret = PyBytes_FromStringAndSize("", 0); - goto cleanup; - case MODE_CLOSED: - PyErr_SetString(PyExc_ValueError, - "I/O operation on closed file"); - goto cleanup; - default: - PyErr_SetString(PyExc_IOError, - "file is not ready for reading"); - goto cleanup; - } - - if (sizehint == 0) - ret = PyBytes_FromStringAndSize("", 0); - else - ret = Util_GetLine(self, (sizehint < 0) ? 0 : sizehint); + ACQUIRE_LOCK(self); + switch (self->mode) { + case MODE_READ: + break; + case MODE_READ_EOF: + ret = PyBytes_FromStringAndSize("", 0); + goto cleanup; + case MODE_CLOSED: + PyErr_SetString(PyExc_ValueError, + "I/O operation on closed file"); + goto cleanup; + default: + PyErr_SetString(PyExc_IOError, + "file is not ready for reading"); + goto cleanup; + } + + if (sizehint == 0) + ret = PyBytes_FromStringAndSize("", 0); + else + ret = Util_GetLine(self, (sizehint < 0) ? 0 : sizehint); cleanup: - RELEASE_LOCK(self); - return ret; + RELEASE_LOCK(self); + return ret; } PyDoc_STRVAR(BZ2File_readlines__doc__, @@ -538,150 +538,150 @@ static PyObject * BZ2File_readlines(BZ2FileObject *self, PyObject *args) { - long sizehint = 0; - PyObject *list = NULL; - PyObject *line; - char small_buffer[SMALLCHUNK]; - char *buffer = small_buffer; - size_t buffersize = SMALLCHUNK; - PyObject *big_buffer = NULL; - size_t nfilled = 0; - size_t nread; - size_t totalread = 0; - char *p, *q, *end; - int err; - int shortread = 0; - int bzerror; - - if (!PyArg_ParseTuple(args, "|l:readlines", &sizehint)) - return NULL; - - ACQUIRE_LOCK(self); - switch (self->mode) { - case MODE_READ: - break; - case MODE_READ_EOF: - list = PyList_New(0); - goto cleanup; - case MODE_CLOSED: - PyErr_SetString(PyExc_ValueError, - "I/O operation on closed file"); - goto cleanup; - default: - PyErr_SetString(PyExc_IOError, - "file is not ready for reading"); - goto cleanup; - } - - if ((list = PyList_New(0)) == NULL) - goto cleanup; - - for (;;) { - Py_BEGIN_ALLOW_THREADS - nread = BZ2_bzRead(&bzerror, self->fp, - buffer+nfilled, buffersize-nfilled); - self->pos += nread; - Py_END_ALLOW_THREADS - if (bzerror == BZ_STREAM_END) { - self->size = self->pos; - self->mode = MODE_READ_EOF; - if (nread == 0) { - sizehint = 0; - break; - } - shortread = 1; - } else if (bzerror != BZ_OK) { - Util_CatchBZ2Error(bzerror); - error: - Py_DECREF(list); - list = NULL; - goto cleanup; - } - totalread += nread; - p = memchr(buffer+nfilled, '\n', nread); - if (!shortread && p == NULL) { - /* Need a larger buffer to fit this line */ - nfilled += nread; - buffersize *= 2; - if (buffersize > INT_MAX) { - PyErr_SetString(PyExc_OverflowError, - "line is longer than a Python string can hold"); - goto error; - } - if (big_buffer == NULL) { - /* Create the big buffer */ - big_buffer = PyBytes_FromStringAndSize( - NULL, buffersize); - if (big_buffer == NULL) - goto error; - buffer = PyBytes_AS_STRING(big_buffer); - memcpy(buffer, small_buffer, nfilled); - } - else { - /* Grow the big buffer */ - if (_PyBytes_Resize(&big_buffer, buffersize) < 0){ - big_buffer = NULL; - goto error; - } - buffer = PyBytes_AS_STRING(big_buffer); - } - continue; - } - end = buffer+nfilled+nread; - q = buffer; - while (p != NULL) { - /* Process complete lines */ - p++; - line = PyBytes_FromStringAndSize(q, p-q); - if (line == NULL) - goto error; - err = PyList_Append(list, line); - Py_DECREF(line); - if (err != 0) - goto error; - q = p; - p = memchr(q, '\n', end-q); - } - /* Move the remaining incomplete line to the start */ - nfilled = end-q; - memmove(buffer, q, nfilled); - if (sizehint > 0) - if (totalread >= (size_t)sizehint) - break; - if (shortread) { - sizehint = 0; - break; - } - } - if (nfilled != 0) { - /* Partial last line */ - line = PyBytes_FromStringAndSize(buffer, nfilled); - if (line == NULL) - goto error; - if (sizehint > 0) { - /* Need to complete the last line */ - PyObject *rest = Util_GetLine(self, 0); - if (rest == NULL) { - Py_DECREF(line); - goto error; - } - PyBytes_Concat(&line, rest); - Py_DECREF(rest); - if (line == NULL) - goto error; - } - err = PyList_Append(list, line); - Py_DECREF(line); - if (err != 0) - goto error; - } + long sizehint = 0; + PyObject *list = NULL; + PyObject *line; + char small_buffer[SMALLCHUNK]; + char *buffer = small_buffer; + size_t buffersize = SMALLCHUNK; + PyObject *big_buffer = NULL; + size_t nfilled = 0; + size_t nread; + size_t totalread = 0; + char *p, *q, *end; + int err; + int shortread = 0; + int bzerror; + + if (!PyArg_ParseTuple(args, "|l:readlines", &sizehint)) + return NULL; + + ACQUIRE_LOCK(self); + switch (self->mode) { + case MODE_READ: + break; + case MODE_READ_EOF: + list = PyList_New(0); + goto cleanup; + case MODE_CLOSED: + PyErr_SetString(PyExc_ValueError, + "I/O operation on closed file"); + goto cleanup; + default: + PyErr_SetString(PyExc_IOError, + "file is not ready for reading"); + goto cleanup; + } + + if ((list = PyList_New(0)) == NULL) + goto cleanup; + + for (;;) { + Py_BEGIN_ALLOW_THREADS + nread = BZ2_bzRead(&bzerror, self->fp, + buffer+nfilled, buffersize-nfilled); + self->pos += nread; + Py_END_ALLOW_THREADS + if (bzerror == BZ_STREAM_END) { + self->size = self->pos; + self->mode = MODE_READ_EOF; + if (nread == 0) { + sizehint = 0; + break; + } + shortread = 1; + } else if (bzerror != BZ_OK) { + Util_CatchBZ2Error(bzerror); + error: + Py_DECREF(list); + list = NULL; + goto cleanup; + } + totalread += nread; + p = memchr(buffer+nfilled, '\n', nread); + if (!shortread && p == NULL) { + /* Need a larger buffer to fit this line */ + nfilled += nread; + buffersize *= 2; + if (buffersize > INT_MAX) { + PyErr_SetString(PyExc_OverflowError, + "line is longer than a Python string can hold"); + goto error; + } + if (big_buffer == NULL) { + /* Create the big buffer */ + big_buffer = PyBytes_FromStringAndSize( + NULL, buffersize); + if (big_buffer == NULL) + goto error; + buffer = PyBytes_AS_STRING(big_buffer); + memcpy(buffer, small_buffer, nfilled); + } + else { + /* Grow the big buffer */ + if (_PyBytes_Resize(&big_buffer, buffersize) < 0){ + big_buffer = NULL; + goto error; + } + buffer = PyBytes_AS_STRING(big_buffer); + } + continue; + } + end = buffer+nfilled+nread; + q = buffer; + while (p != NULL) { + /* Process complete lines */ + p++; + line = PyBytes_FromStringAndSize(q, p-q); + if (line == NULL) + goto error; + err = PyList_Append(list, line); + Py_DECREF(line); + if (err != 0) + goto error; + q = p; + p = memchr(q, '\n', end-q); + } + /* Move the remaining incomplete line to the start */ + nfilled = end-q; + memmove(buffer, q, nfilled); + if (sizehint > 0) + if (totalread >= (size_t)sizehint) + break; + if (shortread) { + sizehint = 0; + break; + } + } + if (nfilled != 0) { + /* Partial last line */ + line = PyBytes_FromStringAndSize(buffer, nfilled); + if (line == NULL) + goto error; + if (sizehint > 0) { + /* Need to complete the last line */ + PyObject *rest = Util_GetLine(self, 0); + if (rest == NULL) { + Py_DECREF(line); + goto error; + } + PyBytes_Concat(&line, rest); + Py_DECREF(rest); + if (line == NULL) + goto error; + } + err = PyList_Append(list, line); + Py_DECREF(line); + if (err != 0) + goto error; + } cleanup: - RELEASE_LOCK(self); - if (big_buffer) { - Py_DECREF(big_buffer); - } - return list; + RELEASE_LOCK(self); + if (big_buffer) { + Py_DECREF(big_buffer); + } + return list; } PyDoc_STRVAR(BZ2File_write__doc__, @@ -695,50 +695,50 @@ static PyObject * BZ2File_write(BZ2FileObject *self, PyObject *args) { - PyObject *ret = NULL; - Py_buffer pbuf; - char *buf; - int len; - int bzerror; - - if (!PyArg_ParseTuple(args, "y*:write", &pbuf)) - return NULL; - buf = pbuf.buf; - len = pbuf.len; - - ACQUIRE_LOCK(self); - switch (self->mode) { - case MODE_WRITE: - break; - - case MODE_CLOSED: - PyErr_SetString(PyExc_ValueError, - "I/O operation on closed file"); - goto cleanup; - - default: - PyErr_SetString(PyExc_IOError, - "file is not ready for writing"); - goto cleanup; - } - - Py_BEGIN_ALLOW_THREADS - BZ2_bzWrite (&bzerror, self->fp, buf, len); - self->pos += len; - Py_END_ALLOW_THREADS - - if (bzerror != BZ_OK) { - Util_CatchBZ2Error(bzerror); - goto cleanup; - } + PyObject *ret = NULL; + Py_buffer pbuf; + char *buf; + int len; + int bzerror; + + if (!PyArg_ParseTuple(args, "y*:write", &pbuf)) + return NULL; + buf = pbuf.buf; + len = pbuf.len; + + ACQUIRE_LOCK(self); + switch (self->mode) { + case MODE_WRITE: + break; + + case MODE_CLOSED: + PyErr_SetString(PyExc_ValueError, + "I/O operation on closed file"); + goto cleanup; + + default: + PyErr_SetString(PyExc_IOError, + "file is not ready for writing"); + goto cleanup; + } + + Py_BEGIN_ALLOW_THREADS + BZ2_bzWrite (&bzerror, self->fp, buf, len); + self->pos += len; + Py_END_ALLOW_THREADS + + if (bzerror != BZ_OK) { + Util_CatchBZ2Error(bzerror); + goto cleanup; + } - Py_INCREF(Py_None); - ret = Py_None; + Py_INCREF(Py_None); + ret = Py_None; cleanup: - PyBuffer_Release(&pbuf); - RELEASE_LOCK(self); - return ret; + PyBuffer_Release(&pbuf); + RELEASE_LOCK(self); + return ret; } PyDoc_STRVAR(BZ2File_writelines__doc__, @@ -754,122 +754,122 @@ BZ2File_writelines(BZ2FileObject *self, PyObject *seq) { #define CHUNKSIZE 1000 - PyObject *list = NULL; - PyObject *iter = NULL; - PyObject *ret = NULL; - PyObject *line; - int i, j, index, len, islist; - int bzerror; - - ACQUIRE_LOCK(self); - switch (self->mode) { - case MODE_WRITE: - break; - - case MODE_CLOSED: - PyErr_SetString(PyExc_ValueError, - "I/O operation on closed file"); - goto error; - - default: - PyErr_SetString(PyExc_IOError, - "file is not ready for writing"); - goto error; - } - - islist = PyList_Check(seq); - if (!islist) { - iter = PyObject_GetIter(seq); - if (iter == NULL) { - PyErr_SetString(PyExc_TypeError, - "writelines() requires an iterable argument"); - goto error; - } - list = PyList_New(CHUNKSIZE); - if (list == NULL) - goto error; - } - - /* Strategy: slurp CHUNKSIZE lines into a private list, - checking that they are all strings, then write that list - without holding the interpreter lock, then come back for more. */ - for (index = 0; ; index += CHUNKSIZE) { - if (islist) { - Py_XDECREF(list); - list = PyList_GetSlice(seq, index, index+CHUNKSIZE); - if (list == NULL) - goto error; - j = PyList_GET_SIZE(list); - } - else { - for (j = 0; j < CHUNKSIZE; j++) { - line = PyIter_Next(iter); - if (line == NULL) { - if (PyErr_Occurred()) - goto error; - break; - } - PyList_SetItem(list, j, line); - } - } - if (j == 0) - break; - - /* Check that all entries are indeed byte strings. If not, - apply the same rules as for file.write() and - convert the rets to strings. This is slow, but - seems to be the only way since all conversion APIs - could potentially execute Python code. */ - for (i = 0; i < j; i++) { - PyObject *v = PyList_GET_ITEM(list, i); - if (!PyBytes_Check(v)) { - const char *buffer; - Py_ssize_t len; - if (PyObject_AsCharBuffer(v, &buffer, &len)) { - PyErr_SetString(PyExc_TypeError, - "writelines() " - "argument must be " - "a sequence of " - "bytes objects"); - goto error; - } - line = PyBytes_FromStringAndSize(buffer, - len); - if (line == NULL) - goto error; - Py_DECREF(v); - PyList_SET_ITEM(list, i, line); - } - } - - /* Since we are releasing the global lock, the - following code may *not* execute Python code. */ - Py_BEGIN_ALLOW_THREADS - for (i = 0; i < j; i++) { - line = PyList_GET_ITEM(list, i); - len = PyBytes_GET_SIZE(line); - BZ2_bzWrite (&bzerror, self->fp, - PyBytes_AS_STRING(line), len); - if (bzerror != BZ_OK) { - Py_BLOCK_THREADS - Util_CatchBZ2Error(bzerror); - goto error; - } - } - Py_END_ALLOW_THREADS - - if (j < CHUNKSIZE) - break; - } + PyObject *list = NULL; + PyObject *iter = NULL; + PyObject *ret = NULL; + PyObject *line; + int i, j, index, len, islist; + int bzerror; + + ACQUIRE_LOCK(self); + switch (self->mode) { + case MODE_WRITE: + break; + + case MODE_CLOSED: + PyErr_SetString(PyExc_ValueError, + "I/O operation on closed file"); + goto error; + + default: + PyErr_SetString(PyExc_IOError, + "file is not ready for writing"); + goto error; + } + + islist = PyList_Check(seq); + if (!islist) { + iter = PyObject_GetIter(seq); + if (iter == NULL) { + PyErr_SetString(PyExc_TypeError, + "writelines() requires an iterable argument"); + goto error; + } + list = PyList_New(CHUNKSIZE); + if (list == NULL) + goto error; + } + + /* Strategy: slurp CHUNKSIZE lines into a private list, + checking that they are all strings, then write that list + without holding the interpreter lock, then come back for more. */ + for (index = 0; ; index += CHUNKSIZE) { + if (islist) { + Py_XDECREF(list); + list = PyList_GetSlice(seq, index, index+CHUNKSIZE); + if (list == NULL) + goto error; + j = PyList_GET_SIZE(list); + } + else { + for (j = 0; j < CHUNKSIZE; j++) { + line = PyIter_Next(iter); + if (line == NULL) { + if (PyErr_Occurred()) + goto error; + break; + } + PyList_SetItem(list, j, line); + } + } + if (j == 0) + break; + + /* Check that all entries are indeed byte strings. If not, + apply the same rules as for file.write() and + convert the rets to strings. This is slow, but + seems to be the only way since all conversion APIs + could potentially execute Python code. */ + for (i = 0; i < j; i++) { + PyObject *v = PyList_GET_ITEM(list, i); + if (!PyBytes_Check(v)) { + const char *buffer; + Py_ssize_t len; + if (PyObject_AsCharBuffer(v, &buffer, &len)) { + PyErr_SetString(PyExc_TypeError, + "writelines() " + "argument must be " + "a sequence of " + "bytes objects"); + goto error; + } + line = PyBytes_FromStringAndSize(buffer, + len); + if (line == NULL) + goto error; + Py_DECREF(v); + PyList_SET_ITEM(list, i, line); + } + } + + /* Since we are releasing the global lock, the + following code may *not* execute Python code. */ + Py_BEGIN_ALLOW_THREADS + for (i = 0; i < j; i++) { + line = PyList_GET_ITEM(list, i); + len = PyBytes_GET_SIZE(line); + BZ2_bzWrite (&bzerror, self->fp, + PyBytes_AS_STRING(line), len); + if (bzerror != BZ_OK) { + Py_BLOCK_THREADS + Util_CatchBZ2Error(bzerror); + goto error; + } + } + Py_END_ALLOW_THREADS + + if (j < CHUNKSIZE) + break; + } - Py_INCREF(Py_None); - ret = Py_None; + Py_INCREF(Py_None); + ret = Py_None; error: - RELEASE_LOCK(self); - Py_XDECREF(list); - Py_XDECREF(iter); - return ret; + RELEASE_LOCK(self); + Py_XDECREF(list); + Py_XDECREF(iter); + return ret; #undef CHUNKSIZE } @@ -889,135 +889,135 @@ static PyObject * BZ2File_seek(BZ2FileObject *self, PyObject *args) { - int where = 0; - PyObject *offobj; - Py_off_t offset; - char small_buffer[SMALLCHUNK]; - char *buffer = small_buffer; - size_t buffersize = SMALLCHUNK; - Py_off_t bytesread = 0; - size_t readsize; - int chunksize; - int bzerror; - PyObject *ret = NULL; + int where = 0; + PyObject *offobj; + Py_off_t offset; + char small_buffer[SMALLCHUNK]; + char *buffer = small_buffer; + size_t buffersize = SMALLCHUNK; + Py_off_t bytesread = 0; + size_t readsize; + int chunksize; + int bzerror; + PyObject *ret = NULL; - if (!PyArg_ParseTuple(args, "O|i:seek", &offobj, &where)) - return NULL; + if (!PyArg_ParseTuple(args, "O|i:seek", &offobj, &where)) + return NULL; #if !defined(HAVE_LARGEFILE_SUPPORT) - offset = PyLong_AsLong(offobj); + offset = PyLong_AsLong(offobj); #else - offset = PyLong_Check(offobj) ? - PyLong_AsLongLong(offobj) : PyLong_AsLong(offobj); + offset = PyLong_Check(offobj) ? + PyLong_AsLongLong(offobj) : PyLong_AsLong(offobj); #endif - if (PyErr_Occurred()) - return NULL; + if (PyErr_Occurred()) + return NULL; - ACQUIRE_LOCK(self); - Util_DropReadAhead(self); - switch (self->mode) { - case MODE_READ: - case MODE_READ_EOF: - break; - - case MODE_CLOSED: - PyErr_SetString(PyExc_ValueError, - "I/O operation on closed file"); - goto cleanup; - - default: - PyErr_SetString(PyExc_IOError, - "seek works only while reading"); - goto cleanup; - } - - if (where == 2) { - if (self->size == -1) { - assert(self->mode != MODE_READ_EOF); - for (;;) { - Py_BEGIN_ALLOW_THREADS - chunksize = BZ2_bzRead(&bzerror, self->fp, - buffer, buffersize); - self->pos += chunksize; - Py_END_ALLOW_THREADS - - bytesread += chunksize; - if (bzerror == BZ_STREAM_END) { - break; - } else if (bzerror != BZ_OK) { - Util_CatchBZ2Error(bzerror); - goto cleanup; - } - } - self->mode = MODE_READ_EOF; - self->size = self->pos; - bytesread = 0; - } - offset = self->size + offset; - } else if (where == 1) { - offset = self->pos + offset; - } - - /* Before getting here, offset must be the absolute position the file - * pointer should be set to. */ - - if (offset >= self->pos) { - /* we can move forward */ - offset -= self->pos; - } else { - /* we cannot move back, so rewind the stream */ - BZ2_bzReadClose(&bzerror, self->fp); - if (bzerror != BZ_OK) { - Util_CatchBZ2Error(bzerror); - goto cleanup; - } - rewind(self->rawfp); - self->pos = 0; - self->fp = BZ2_bzReadOpen(&bzerror, self->rawfp, - 0, 0, NULL, 0); - if (bzerror != BZ_OK) { - Util_CatchBZ2Error(bzerror); - goto cleanup; - } - self->mode = MODE_READ; - } - - if (offset <= 0 || self->mode == MODE_READ_EOF) - goto exit; - - /* Before getting here, offset must be set to the number of bytes - * to walk forward. */ - for (;;) { - if (offset-bytesread > buffersize) - readsize = buffersize; - else - /* offset might be wider that readsize, but the result - * of the subtraction is bound by buffersize (see the - * condition above). buffersize is 8192. */ - readsize = (size_t)(offset-bytesread); - Py_BEGIN_ALLOW_THREADS - chunksize = BZ2_bzRead(&bzerror, self->fp, buffer, readsize); - self->pos += chunksize; - Py_END_ALLOW_THREADS - bytesread += chunksize; - if (bzerror == BZ_STREAM_END) { - self->size = self->pos; - self->mode = MODE_READ_EOF; - break; - } else if (bzerror != BZ_OK) { - Util_CatchBZ2Error(bzerror); - goto cleanup; - } - if (bytesread == offset) - break; - } + ACQUIRE_LOCK(self); + Util_DropReadAhead(self); + switch (self->mode) { + case MODE_READ: + case MODE_READ_EOF: + break; + + case MODE_CLOSED: + PyErr_SetString(PyExc_ValueError, + "I/O operation on closed file"); + goto cleanup; + + default: + PyErr_SetString(PyExc_IOError, + "seek works only while reading"); + goto cleanup; + } + + if (where == 2) { + if (self->size == -1) { + assert(self->mode != MODE_READ_EOF); + for (;;) { + Py_BEGIN_ALLOW_THREADS + chunksize = BZ2_bzRead(&bzerror, self->fp, + buffer, buffersize); + self->pos += chunksize; + Py_END_ALLOW_THREADS + + bytesread += chunksize; + if (bzerror == BZ_STREAM_END) { + break; + } else if (bzerror != BZ_OK) { + Util_CatchBZ2Error(bzerror); + goto cleanup; + } + } + self->mode = MODE_READ_EOF; + self->size = self->pos; + bytesread = 0; + } + offset = self->size + offset; + } else if (where == 1) { + offset = self->pos + offset; + } + + /* Before getting here, offset must be the absolute position the file + * pointer should be set to. */ + + if (offset >= self->pos) { + /* we can move forward */ + offset -= self->pos; + } else { + /* we cannot move back, so rewind the stream */ + BZ2_bzReadClose(&bzerror, self->fp); + if (bzerror != BZ_OK) { + Util_CatchBZ2Error(bzerror); + goto cleanup; + } + rewind(self->rawfp); + self->pos = 0; + self->fp = BZ2_bzReadOpen(&bzerror, self->rawfp, + 0, 0, NULL, 0); + if (bzerror != BZ_OK) { + Util_CatchBZ2Error(bzerror); + goto cleanup; + } + self->mode = MODE_READ; + } + + if (offset <= 0 || self->mode == MODE_READ_EOF) + goto exit; + + /* Before getting here, offset must be set to the number of bytes + * to walk forward. */ + for (;;) { + if (offset-bytesread > buffersize) + readsize = buffersize; + else + /* offset might be wider that readsize, but the result + * of the subtraction is bound by buffersize (see the + * condition above). buffersize is 8192. */ + readsize = (size_t)(offset-bytesread); + Py_BEGIN_ALLOW_THREADS + chunksize = BZ2_bzRead(&bzerror, self->fp, buffer, readsize); + self->pos += chunksize; + Py_END_ALLOW_THREADS + bytesread += chunksize; + if (bzerror == BZ_STREAM_END) { + self->size = self->pos; + self->mode = MODE_READ_EOF; + break; + } else if (bzerror != BZ_OK) { + Util_CatchBZ2Error(bzerror); + goto cleanup; + } + if (bytesread == offset) + break; + } exit: - Py_INCREF(Py_None); - ret = Py_None; + Py_INCREF(Py_None); + ret = Py_None; cleanup: - RELEASE_LOCK(self); - return ret; + RELEASE_LOCK(self); + return ret; } PyDoc_STRVAR(BZ2File_tell__doc__, @@ -1029,22 +1029,22 @@ static PyObject * BZ2File_tell(BZ2FileObject *self, PyObject *args) { - PyObject *ret = NULL; + PyObject *ret = NULL; - if (self->mode == MODE_CLOSED) { - PyErr_SetString(PyExc_ValueError, - "I/O operation on closed file"); - goto cleanup; - } + if (self->mode == MODE_CLOSED) { + PyErr_SetString(PyExc_ValueError, + "I/O operation on closed file"); + goto cleanup; + } #if !defined(HAVE_LARGEFILE_SUPPORT) - ret = PyLong_FromLong(self->pos); + ret = PyLong_FromLong(self->pos); #else - ret = PyLong_FromLongLong(self->pos); + ret = PyLong_FromLongLong(self->pos); #endif cleanup: - return ret; + return ret; } PyDoc_STRVAR(BZ2File_close__doc__, @@ -1058,37 +1058,37 @@ static PyObject * BZ2File_close(BZ2FileObject *self) { - PyObject *ret = NULL; - int bzerror = BZ_OK; + PyObject *ret = NULL; + int bzerror = BZ_OK; - if (self->mode == MODE_CLOSED) { - Py_RETURN_NONE; - } - - ACQUIRE_LOCK(self); - switch (self->mode) { - case MODE_READ: - case MODE_READ_EOF: - BZ2_bzReadClose(&bzerror, self->fp); - break; - case MODE_WRITE: - BZ2_bzWriteClose(&bzerror, self->fp, - 0, NULL, NULL); - break; - } - self->mode = MODE_CLOSED; - fclose(self->rawfp); - self->rawfp = NULL; - if (bzerror == BZ_OK) { - Py_INCREF(Py_None); - ret = Py_None; - } - else { - Util_CatchBZ2Error(bzerror); - } + if (self->mode == MODE_CLOSED) { + Py_RETURN_NONE; + } + + ACQUIRE_LOCK(self); + switch (self->mode) { + case MODE_READ: + case MODE_READ_EOF: + BZ2_bzReadClose(&bzerror, self->fp); + break; + case MODE_WRITE: + BZ2_bzWriteClose(&bzerror, self->fp, + 0, NULL, NULL); + break; + } + self->mode = MODE_CLOSED; + fclose(self->rawfp); + self->rawfp = NULL; + if (bzerror == BZ_OK) { + Py_INCREF(Py_None); + ret = Py_None; + } + else { + Util_CatchBZ2Error(bzerror); + } - RELEASE_LOCK(self); - return ret; + RELEASE_LOCK(self); + return ret; } PyDoc_STRVAR(BZ2File_enter_doc, @@ -1097,13 +1097,13 @@ static PyObject * BZ2File_enter(BZ2FileObject *self) { - if (self->mode == MODE_CLOSED) { - PyErr_SetString(PyExc_ValueError, - "I/O operation on closed file"); - return NULL; - } - Py_INCREF(self); - return (PyObject *) self; + if (self->mode == MODE_CLOSED) { + PyErr_SetString(PyExc_ValueError, + "I/O operation on closed file"); + return NULL; + } + Py_INCREF(self); + return (PyObject *) self; } PyDoc_STRVAR(BZ2File_exit_doc, @@ -1112,29 +1112,29 @@ static PyObject * BZ2File_exit(BZ2FileObject *self, PyObject *args) { - PyObject *ret = PyObject_CallMethod((PyObject *) self, "close", NULL); - if (!ret) - /* If error occurred, pass through */ - return NULL; - Py_DECREF(ret); - Py_RETURN_NONE; + PyObject *ret = PyObject_CallMethod((PyObject *) self, "close", NULL); + if (!ret) + /* If error occurred, pass through */ + return NULL; + Py_DECREF(ret); + Py_RETURN_NONE; } static PyObject *BZ2File_getiter(BZ2FileObject *self); static PyMethodDef BZ2File_methods[] = { - {"read", (PyCFunction)BZ2File_read, METH_VARARGS, BZ2File_read__doc__}, - {"readline", (PyCFunction)BZ2File_readline, METH_VARARGS, BZ2File_readline__doc__}, - {"readlines", (PyCFunction)BZ2File_readlines, METH_VARARGS, BZ2File_readlines__doc__}, - {"write", (PyCFunction)BZ2File_write, METH_VARARGS, BZ2File_write__doc__}, - {"writelines", (PyCFunction)BZ2File_writelines, METH_O, BZ2File_writelines__doc__}, - {"seek", (PyCFunction)BZ2File_seek, METH_VARARGS, BZ2File_seek__doc__}, - {"tell", (PyCFunction)BZ2File_tell, METH_NOARGS, BZ2File_tell__doc__}, - {"close", (PyCFunction)BZ2File_close, METH_NOARGS, BZ2File_close__doc__}, - {"__enter__", (PyCFunction)BZ2File_enter, METH_NOARGS, BZ2File_enter_doc}, - {"__exit__", (PyCFunction)BZ2File_exit, METH_VARARGS, BZ2File_exit_doc}, - {NULL, NULL} /* sentinel */ + {"read", (PyCFunction)BZ2File_read, METH_VARARGS, BZ2File_read__doc__}, + {"readline", (PyCFunction)BZ2File_readline, METH_VARARGS, BZ2File_readline__doc__}, + {"readlines", (PyCFunction)BZ2File_readlines, METH_VARARGS, BZ2File_readlines__doc__}, + {"write", (PyCFunction)BZ2File_write, METH_VARARGS, BZ2File_write__doc__}, + {"writelines", (PyCFunction)BZ2File_writelines, METH_O, BZ2File_writelines__doc__}, + {"seek", (PyCFunction)BZ2File_seek, METH_VARARGS, BZ2File_seek__doc__}, + {"tell", (PyCFunction)BZ2File_tell, METH_NOARGS, BZ2File_tell__doc__}, + {"close", (PyCFunction)BZ2File_close, METH_NOARGS, BZ2File_close__doc__}, + {"__enter__", (PyCFunction)BZ2File_enter, METH_NOARGS, BZ2File_enter_doc}, + {"__exit__", (PyCFunction)BZ2File_exit, METH_VARARGS, BZ2File_exit_doc}, + {NULL, NULL} /* sentinel */ }; @@ -1144,13 +1144,13 @@ static PyObject * BZ2File_get_closed(BZ2FileObject *self, void *closure) { - return PyLong_FromLong(self->mode == MODE_CLOSED); + return PyLong_FromLong(self->mode == MODE_CLOSED); } static PyGetSetDef BZ2File_getset[] = { - {"closed", (getter)BZ2File_get_closed, NULL, - "True if the file is closed"}, - {NULL} /* Sentinel */ + {"closed", (getter)BZ2File_get_closed, NULL, + "True if the file is closed"}, + {NULL} /* Sentinel */ }; @@ -1160,148 +1160,148 @@ static int BZ2File_init(BZ2FileObject *self, PyObject *args, PyObject *kwargs) { - static char *kwlist[] = {"filename", "mode", "buffering", - "compresslevel", 0}; - PyObject *name_obj = NULL; - char *name; - char *mode = "r"; - int buffering = -1; - int compresslevel = 9; - int bzerror; - int mode_char = 0; - - self->size = -1; - - if (!PyArg_ParseTupleAndKeywords(args, kwargs, "O&|sii:BZ2File", - kwlist, PyUnicode_FSConverter, &name_obj, - &mode, &buffering, - &compresslevel)) - return -1; - - name = PyBytes_AsString(name_obj); - if (compresslevel < 1 || compresslevel > 9) { - PyErr_SetString(PyExc_ValueError, - "compresslevel must be between 1 and 9"); - Py_DECREF(name_obj); - return -1; - } - - for (;;) { - int error = 0; - switch (*mode) { - case 'r': - case 'w': - if (mode_char) - error = 1; - mode_char = *mode; - break; - - case 'b': - break; - - default: - error = 1; - break; - } - if (error) { - PyErr_Format(PyExc_ValueError, - "invalid mode char %c", *mode); - Py_DECREF(name_obj); - return -1; - } - mode++; - if (*mode == '\0') - break; - } - - if (mode_char == 0) { - mode_char = 'r'; - } - - mode = (mode_char == 'r') ? "rb" : "wb"; - - self->rawfp = fopen(name, mode); - Py_DECREF(name_obj); - if (self->rawfp == NULL) { - PyErr_SetFromErrno(PyExc_IOError); - return -1; - } - /* XXX Ignore buffering */ + static char *kwlist[] = {"filename", "mode", "buffering", + "compresslevel", 0}; + PyObject *name_obj = NULL; + char *name; + char *mode = "r"; + int buffering = -1; + int compresslevel = 9; + int bzerror; + int mode_char = 0; + + self->size = -1; + + if (!PyArg_ParseTupleAndKeywords(args, kwargs, "O&|sii:BZ2File", + kwlist, PyUnicode_FSConverter, &name_obj, + &mode, &buffering, + &compresslevel)) + return -1; + + name = PyBytes_AsString(name_obj); + if (compresslevel < 1 || compresslevel > 9) { + PyErr_SetString(PyExc_ValueError, + "compresslevel must be between 1 and 9"); + Py_DECREF(name_obj); + return -1; + } + + for (;;) { + int error = 0; + switch (*mode) { + case 'r': + case 'w': + if (mode_char) + error = 1; + mode_char = *mode; + break; + + case 'b': + break; + + default: + error = 1; + break; + } + if (error) { + PyErr_Format(PyExc_ValueError, + "invalid mode char %c", *mode); + Py_DECREF(name_obj); + return -1; + } + mode++; + if (*mode == '\0') + break; + } + + if (mode_char == 0) { + mode_char = 'r'; + } + + mode = (mode_char == 'r') ? "rb" : "wb"; + + self->rawfp = fopen(name, mode); + Py_DECREF(name_obj); + if (self->rawfp == NULL) { + PyErr_SetFromErrno(PyExc_IOError); + return -1; + } + /* XXX Ignore buffering */ - /* From now on, we have stuff to dealloc, so jump to error label - * instead of returning */ + /* From now on, we have stuff to dealloc, so jump to error label + * instead of returning */ #ifdef WITH_THREAD - self->lock = PyThread_allocate_lock(); - if (!self->lock) { - PyErr_SetString(PyExc_MemoryError, "unable to allocate lock"); - goto error; - } + self->lock = PyThread_allocate_lock(); + if (!self->lock) { + PyErr_SetString(PyExc_MemoryError, "unable to allocate lock"); + goto error; + } #endif - if (mode_char == 'r') - self->fp = BZ2_bzReadOpen(&bzerror, self->rawfp, - 0, 0, NULL, 0); - else - self->fp = BZ2_bzWriteOpen(&bzerror, self->rawfp, - compresslevel, 0, 0); - - if (bzerror != BZ_OK) { - Util_CatchBZ2Error(bzerror); - goto error; - } + if (mode_char == 'r') + self->fp = BZ2_bzReadOpen(&bzerror, self->rawfp, + 0, 0, NULL, 0); + else + self->fp = BZ2_bzWriteOpen(&bzerror, self->rawfp, + compresslevel, 0, 0); + + if (bzerror != BZ_OK) { + Util_CatchBZ2Error(bzerror); + goto error; + } - self->mode = (mode_char == 'r') ? MODE_READ : MODE_WRITE; + self->mode = (mode_char == 'r') ? MODE_READ : MODE_WRITE; - return 0; + return 0; error: - fclose(self->rawfp); - self->rawfp = NULL; + fclose(self->rawfp); + self->rawfp = NULL; #ifdef WITH_THREAD - if (self->lock) { - PyThread_free_lock(self->lock); - self->lock = NULL; - } + if (self->lock) { + PyThread_free_lock(self->lock); + self->lock = NULL; + } #endif - return -1; + return -1; } static void BZ2File_dealloc(BZ2FileObject *self) { - int bzerror; + int bzerror; #ifdef WITH_THREAD - if (self->lock) - PyThread_free_lock(self->lock); + if (self->lock) + PyThread_free_lock(self->lock); #endif - switch (self->mode) { - case MODE_READ: - case MODE_READ_EOF: - BZ2_bzReadClose(&bzerror, self->fp); - break; - case MODE_WRITE: - BZ2_bzWriteClose(&bzerror, self->fp, - 0, NULL, NULL); - break; - } - Util_DropReadAhead(self); - if (self->rawfp != NULL) - fclose(self->rawfp); - Py_TYPE(self)->tp_free((PyObject *)self); + switch (self->mode) { + case MODE_READ: + case MODE_READ_EOF: + BZ2_bzReadClose(&bzerror, self->fp); + break; + case MODE_WRITE: + BZ2_bzWriteClose(&bzerror, self->fp, + 0, NULL, NULL); + break; + } + Util_DropReadAhead(self); + if (self->rawfp != NULL) + fclose(self->rawfp); + Py_TYPE(self)->tp_free((PyObject *)self); } /* This is a hacked version of Python's fileobject.c:file_getiter(). */ static PyObject * BZ2File_getiter(BZ2FileObject *self) { - if (self->mode == MODE_CLOSED) { - PyErr_SetString(PyExc_ValueError, - "I/O operation on closed file"); - return NULL; - } - Py_INCREF((PyObject*)self); - return (PyObject *)self; + if (self->mode == MODE_CLOSED) { + PyErr_SetString(PyExc_ValueError, + "I/O operation on closed file"); + return NULL; + } + Py_INCREF((PyObject*)self); + return (PyObject *)self; } /* This is a hacked version of Python's fileobject.c:file_iternext(). */ @@ -1309,21 +1309,21 @@ static PyObject * BZ2File_iternext(BZ2FileObject *self) { - PyBytesObject* ret; - ACQUIRE_LOCK(self); - if (self->mode == MODE_CLOSED) { - RELEASE_LOCK(self); - PyErr_SetString(PyExc_ValueError, - "I/O operation on closed file"); - return NULL; - } - ret = Util_ReadAheadGetLineSkip(self, 0, READAHEAD_BUFSIZE); - RELEASE_LOCK(self); - if (ret == NULL || PyBytes_GET_SIZE(ret) == 0) { - Py_XDECREF(ret); - return NULL; - } - return (PyObject *)ret; + PyBytesObject* ret; + ACQUIRE_LOCK(self); + if (self->mode == MODE_CLOSED) { + RELEASE_LOCK(self); + PyErr_SetString(PyExc_ValueError, + "I/O operation on closed file"); + return NULL; + } + ret = Util_ReadAheadGetLineSkip(self, 0, READAHEAD_BUFSIZE); + RELEASE_LOCK(self); + if (ret == NULL || PyBytes_GET_SIZE(ret) == 0) { + Py_XDECREF(ret); + return NULL; + } + return (PyObject *)ret; } /* ===================================================================== */ @@ -1342,46 +1342,46 @@ "); static PyTypeObject BZ2File_Type = { - PyVarObject_HEAD_INIT(NULL, 0) - "bz2.BZ2File", /*tp_name*/ - sizeof(BZ2FileObject), /*tp_basicsize*/ - 0, /*tp_itemsize*/ - (destructor)BZ2File_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*/ - PyObject_GenericSetAttr,/*tp_setattro*/ - 0, /*tp_as_buffer*/ - Py_TPFLAGS_DEFAULT|Py_TPFLAGS_BASETYPE, /*tp_flags*/ - BZ2File__doc__, /*tp_doc*/ - 0, /*tp_traverse*/ - 0, /*tp_clear*/ - 0, /*tp_richcompare*/ - 0, /*tp_weaklistoffset*/ - (getiterfunc)BZ2File_getiter, /*tp_iter*/ - (iternextfunc)BZ2File_iternext, /*tp_iternext*/ - BZ2File_methods, /*tp_methods*/ - 0, /*tp_members*/ - BZ2File_getset, /*tp_getset*/ - 0, /*tp_base*/ - 0, /*tp_dict*/ - 0, /*tp_descr_get*/ - 0, /*tp_descr_set*/ - 0, /*tp_dictoffset*/ - (initproc)BZ2File_init, /*tp_init*/ - PyType_GenericAlloc, /*tp_alloc*/ - PyType_GenericNew, /*tp_new*/ - PyObject_Free, /*tp_free*/ - 0, /*tp_is_gc*/ + PyVarObject_HEAD_INIT(NULL, 0) + "bz2.BZ2File", /*tp_name*/ + sizeof(BZ2FileObject), /*tp_basicsize*/ + 0, /*tp_itemsize*/ + (destructor)BZ2File_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*/ + PyObject_GenericSetAttr,/*tp_setattro*/ + 0, /*tp_as_buffer*/ + Py_TPFLAGS_DEFAULT|Py_TPFLAGS_BASETYPE, /*tp_flags*/ + BZ2File__doc__, /*tp_doc*/ + 0, /*tp_traverse*/ + 0, /*tp_clear*/ + 0, /*tp_richcompare*/ + 0, /*tp_weaklistoffset*/ + (getiterfunc)BZ2File_getiter, /*tp_iter*/ + (iternextfunc)BZ2File_iternext, /*tp_iternext*/ + BZ2File_methods, /*tp_methods*/ + 0, /*tp_members*/ + BZ2File_getset, /*tp_getset*/ + 0, /*tp_base*/ + 0, /*tp_dict*/ + 0, /*tp_descr_get*/ + 0, /*tp_descr_set*/ + 0, /*tp_dictoffset*/ + (initproc)BZ2File_init, /*tp_init*/ + PyType_GenericAlloc, /*tp_alloc*/ + PyType_GenericNew, /*tp_new*/ + PyObject_Free, /*tp_free*/ + 0, /*tp_is_gc*/ }; @@ -1400,78 +1400,78 @@ static PyObject * BZ2Comp_compress(BZ2CompObject *self, PyObject *args) { - Py_buffer pdata; - char *data; - int datasize; - int bufsize = SMALLCHUNK; - PY_LONG_LONG totalout; - PyObject *ret = NULL; - bz_stream *bzs = &self->bzs; - int bzerror; - - if (!PyArg_ParseTuple(args, "y*:compress", &pdata)) - return NULL; - data = pdata.buf; - datasize = pdata.len; - - if (datasize == 0) { - PyBuffer_Release(&pdata); - return PyBytes_FromStringAndSize("", 0); - } - - ACQUIRE_LOCK(self); - if (!self->running) { - PyErr_SetString(PyExc_ValueError, - "this object was already flushed"); - goto error; - } - - ret = PyBytes_FromStringAndSize(NULL, bufsize); - if (!ret) - goto error; - - bzs->next_in = data; - bzs->avail_in = datasize; - bzs->next_out = BUF(ret); - bzs->avail_out = bufsize; - - totalout = BZS_TOTAL_OUT(bzs); - - for (;;) { - Py_BEGIN_ALLOW_THREADS - bzerror = BZ2_bzCompress(bzs, BZ_RUN); - Py_END_ALLOW_THREADS - if (bzerror != BZ_RUN_OK) { - Util_CatchBZ2Error(bzerror); - goto error; - } - if (bzs->avail_in == 0) - break; /* no more input data */ - if (bzs->avail_out == 0) { - bufsize = Util_NewBufferSize(bufsize); - if (_PyBytes_Resize(&ret, bufsize) < 0) { - BZ2_bzCompressEnd(bzs); - goto error; - } - bzs->next_out = BUF(ret) + (BZS_TOTAL_OUT(bzs) - - totalout); - bzs->avail_out = bufsize - (bzs->next_out - BUF(ret)); - } - } - - if (_PyBytes_Resize(&ret, - (Py_ssize_t)(BZS_TOTAL_OUT(bzs) - totalout)) < 0) - goto error; - - RELEASE_LOCK(self); - PyBuffer_Release(&pdata); - return ret; + Py_buffer pdata; + char *data; + int datasize; + int bufsize = SMALLCHUNK; + PY_LONG_LONG totalout; + PyObject *ret = NULL; + bz_stream *bzs = &self->bzs; + int bzerror; + + if (!PyArg_ParseTuple(args, "y*:compress", &pdata)) + return NULL; + data = pdata.buf; + datasize = pdata.len; + + if (datasize == 0) { + PyBuffer_Release(&pdata); + return PyBytes_FromStringAndSize("", 0); + } + + ACQUIRE_LOCK(self); + if (!self->running) { + PyErr_SetString(PyExc_ValueError, + "this object was already flushed"); + goto error; + } + + ret = PyBytes_FromStringAndSize(NULL, bufsize); + if (!ret) + goto error; + + bzs->next_in = data; + bzs->avail_in = datasize; + bzs->next_out = BUF(ret); + bzs->avail_out = bufsize; + + totalout = BZS_TOTAL_OUT(bzs); + + for (;;) { + Py_BEGIN_ALLOW_THREADS + bzerror = BZ2_bzCompress(bzs, BZ_RUN); + Py_END_ALLOW_THREADS + if (bzerror != BZ_RUN_OK) { + Util_CatchBZ2Error(bzerror); + goto error; + } + if (bzs->avail_in == 0) + break; /* no more input data */ + if (bzs->avail_out == 0) { + bufsize = Util_NewBufferSize(bufsize); + if (_PyBytes_Resize(&ret, bufsize) < 0) { + BZ2_bzCompressEnd(bzs); + goto error; + } + bzs->next_out = BUF(ret) + (BZS_TOTAL_OUT(bzs) + - totalout); + bzs->avail_out = bufsize - (bzs->next_out - BUF(ret)); + } + } + + if (_PyBytes_Resize(&ret, + (Py_ssize_t)(BZS_TOTAL_OUT(bzs) - totalout)) < 0) + goto error; + + RELEASE_LOCK(self); + PyBuffer_Release(&pdata); + return ret; error: - RELEASE_LOCK(self); - PyBuffer_Release(&pdata); - Py_XDECREF(ret); - return NULL; + RELEASE_LOCK(self); + PyBuffer_Release(&pdata); + Py_XDECREF(ret); + return NULL; } PyDoc_STRVAR(BZ2Comp_flush__doc__, @@ -1484,71 +1484,71 @@ static PyObject * BZ2Comp_flush(BZ2CompObject *self) { - int bufsize = SMALLCHUNK; - PyObject *ret = NULL; - bz_stream *bzs = &self->bzs; - PY_LONG_LONG totalout; - int bzerror; - - ACQUIRE_LOCK(self); - if (!self->running) { - PyErr_SetString(PyExc_ValueError, "object was already " - "flushed"); - goto error; - } - self->running = 0; - - ret = PyBytes_FromStringAndSize(NULL, bufsize); - if (!ret) - goto error; - - bzs->next_out = BUF(ret); - bzs->avail_out = bufsize; - - totalout = BZS_TOTAL_OUT(bzs); - - for (;;) { - Py_BEGIN_ALLOW_THREADS - bzerror = BZ2_bzCompress(bzs, BZ_FINISH); - Py_END_ALLOW_THREADS - if (bzerror == BZ_STREAM_END) { - break; - } else if (bzerror != BZ_FINISH_OK) { - Util_CatchBZ2Error(bzerror); - goto error; - } - if (bzs->avail_out == 0) { - bufsize = Util_NewBufferSize(bufsize); - if (_PyBytes_Resize(&ret, bufsize) < 0) - goto error; - bzs->next_out = BUF(ret); - bzs->next_out = BUF(ret) + (BZS_TOTAL_OUT(bzs) - - totalout); - bzs->avail_out = bufsize - (bzs->next_out - BUF(ret)); - } - } - - if (bzs->avail_out != 0) { - if (_PyBytes_Resize(&ret, - (Py_ssize_t)(BZS_TOTAL_OUT(bzs) - totalout)) < 0) - goto error; - } + int bufsize = SMALLCHUNK; + PyObject *ret = NULL; + bz_stream *bzs = &self->bzs; + PY_LONG_LONG totalout; + int bzerror; + + ACQUIRE_LOCK(self); + if (!self->running) { + PyErr_SetString(PyExc_ValueError, "object was already " + "flushed"); + goto error; + } + self->running = 0; + + ret = PyBytes_FromStringAndSize(NULL, bufsize); + if (!ret) + goto error; + + bzs->next_out = BUF(ret); + bzs->avail_out = bufsize; + + totalout = BZS_TOTAL_OUT(bzs); + + for (;;) { + Py_BEGIN_ALLOW_THREADS + bzerror = BZ2_bzCompress(bzs, BZ_FINISH); + Py_END_ALLOW_THREADS + if (bzerror == BZ_STREAM_END) { + break; + } else if (bzerror != BZ_FINISH_OK) { + Util_CatchBZ2Error(bzerror); + goto error; + } + if (bzs->avail_out == 0) { + bufsize = Util_NewBufferSize(bufsize); + if (_PyBytes_Resize(&ret, bufsize) < 0) + goto error; + bzs->next_out = BUF(ret); + bzs->next_out = BUF(ret) + (BZS_TOTAL_OUT(bzs) + - totalout); + bzs->avail_out = bufsize - (bzs->next_out - BUF(ret)); + } + } + + if (bzs->avail_out != 0) { + if (_PyBytes_Resize(&ret, + (Py_ssize_t)(BZS_TOTAL_OUT(bzs) - totalout)) < 0) + goto error; + } - RELEASE_LOCK(self); - return ret; + RELEASE_LOCK(self); + return ret; error: - RELEASE_LOCK(self); - Py_XDECREF(ret); - return NULL; + RELEASE_LOCK(self); + Py_XDECREF(ret); + return NULL; } static PyMethodDef BZ2Comp_methods[] = { - {"compress", (PyCFunction)BZ2Comp_compress, METH_VARARGS, - BZ2Comp_compress__doc__}, - {"flush", (PyCFunction)BZ2Comp_flush, METH_NOARGS, - BZ2Comp_flush__doc__}, - {NULL, NULL} /* sentinel */ + {"compress", (PyCFunction)BZ2Comp_compress, METH_VARARGS, + BZ2Comp_compress__doc__}, + {"flush", (PyCFunction)BZ2Comp_flush, METH_NOARGS, + BZ2Comp_flush__doc__}, + {NULL, NULL} /* sentinel */ }; @@ -1558,57 +1558,57 @@ static int BZ2Comp_init(BZ2CompObject *self, PyObject *args, PyObject *kwargs) { - int compresslevel = 9; - int bzerror; - static char *kwlist[] = {"compresslevel", 0}; - - if (!PyArg_ParseTupleAndKeywords(args, kwargs, "|i:BZ2Compressor", - kwlist, &compresslevel)) - return -1; - - if (compresslevel < 1 || compresslevel > 9) { - PyErr_SetString(PyExc_ValueError, - "compresslevel must be between 1 and 9"); - goto error; - } + int compresslevel = 9; + int bzerror; + static char *kwlist[] = {"compresslevel", 0}; + + if (!PyArg_ParseTupleAndKeywords(args, kwargs, "|i:BZ2Compressor", + kwlist, &compresslevel)) + return -1; + + if (compresslevel < 1 || compresslevel > 9) { + PyErr_SetString(PyExc_ValueError, + "compresslevel must be between 1 and 9"); + goto error; + } #ifdef WITH_THREAD - self->lock = PyThread_allocate_lock(); - if (!self->lock) { - PyErr_SetString(PyExc_MemoryError, "unable to allocate lock"); - goto error; - } + self->lock = PyThread_allocate_lock(); + if (!self->lock) { + PyErr_SetString(PyExc_MemoryError, "unable to allocate lock"); + goto error; + } #endif - memset(&self->bzs, 0, sizeof(bz_stream)); - bzerror = BZ2_bzCompressInit(&self->bzs, compresslevel, 0, 0); - if (bzerror != BZ_OK) { - Util_CatchBZ2Error(bzerror); - goto error; - } + memset(&self->bzs, 0, sizeof(bz_stream)); + bzerror = BZ2_bzCompressInit(&self->bzs, compresslevel, 0, 0); + if (bzerror != BZ_OK) { + Util_CatchBZ2Error(bzerror); + goto error; + } - self->running = 1; + self->running = 1; - return 0; + return 0; error: #ifdef WITH_THREAD - if (self->lock) { - PyThread_free_lock(self->lock); - self->lock = NULL; - } + if (self->lock) { + PyThread_free_lock(self->lock); + self->lock = NULL; + } #endif - return -1; + return -1; } static void BZ2Comp_dealloc(BZ2CompObject *self) { #ifdef WITH_THREAD - if (self->lock) - PyThread_free_lock(self->lock); + if (self->lock) + PyThread_free_lock(self->lock); #endif - BZ2_bzCompressEnd(&self->bzs); - Py_TYPE(self)->tp_free((PyObject *)self); + BZ2_bzCompressEnd(&self->bzs); + Py_TYPE(self)->tp_free((PyObject *)self); } @@ -1625,46 +1625,46 @@ "); static PyTypeObject BZ2Comp_Type = { - PyVarObject_HEAD_INIT(NULL, 0) - "bz2.BZ2Compressor", /*tp_name*/ - sizeof(BZ2CompObject), /*tp_basicsize*/ - 0, /*tp_itemsize*/ - (destructor)BZ2Comp_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*/ - PyObject_GenericSetAttr,/*tp_setattro*/ - 0, /*tp_as_buffer*/ - Py_TPFLAGS_DEFAULT|Py_TPFLAGS_BASETYPE, /*tp_flags*/ - BZ2Comp__doc__, /*tp_doc*/ - 0, /*tp_traverse*/ - 0, /*tp_clear*/ - 0, /*tp_richcompare*/ - 0, /*tp_weaklistoffset*/ - 0, /*tp_iter*/ - 0, /*tp_iternext*/ - BZ2Comp_methods, /*tp_methods*/ - 0, /*tp_members*/ - 0, /*tp_getset*/ - 0, /*tp_base*/ - 0, /*tp_dict*/ - 0, /*tp_descr_get*/ - 0, /*tp_descr_set*/ - 0, /*tp_dictoffset*/ - (initproc)BZ2Comp_init, /*tp_init*/ - PyType_GenericAlloc, /*tp_alloc*/ - PyType_GenericNew, /*tp_new*/ - PyObject_Free, /*tp_free*/ - 0, /*tp_is_gc*/ + PyVarObject_HEAD_INIT(NULL, 0) + "bz2.BZ2Compressor", /*tp_name*/ + sizeof(BZ2CompObject), /*tp_basicsize*/ + 0, /*tp_itemsize*/ + (destructor)BZ2Comp_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*/ + PyObject_GenericSetAttr,/*tp_setattro*/ + 0, /*tp_as_buffer*/ + Py_TPFLAGS_DEFAULT|Py_TPFLAGS_BASETYPE, /*tp_flags*/ + BZ2Comp__doc__, /*tp_doc*/ + 0, /*tp_traverse*/ + 0, /*tp_clear*/ + 0, /*tp_richcompare*/ + 0, /*tp_weaklistoffset*/ + 0, /*tp_iter*/ + 0, /*tp_iternext*/ + BZ2Comp_methods, /*tp_methods*/ + 0, /*tp_members*/ + 0, /*tp_getset*/ + 0, /*tp_base*/ + 0, /*tp_dict*/ + 0, /*tp_descr_get*/ + 0, /*tp_descr_set*/ + 0, /*tp_dictoffset*/ + (initproc)BZ2Comp_init, /*tp_init*/ + PyType_GenericAlloc, /*tp_alloc*/ + PyType_GenericNew, /*tp_new*/ + PyObject_Free, /*tp_free*/ + 0, /*tp_is_gc*/ }; @@ -1675,8 +1675,8 @@ #define OFF(x) offsetof(BZ2DecompObject, x) static PyMemberDef BZ2Decomp_members[] = { - {"unused_data", T_OBJECT, OFF(unused_data), READONLY}, - {NULL} /* Sentinel */ + {"unused_data", T_OBJECT, OFF(unused_data), READONLY}, + {NULL} /* Sentinel */ }; @@ -1696,91 +1696,91 @@ static PyObject * BZ2Decomp_decompress(BZ2DecompObject *self, PyObject *args) { - Py_buffer pdata; - char *data; - int datasize; - int bufsize = SMALLCHUNK; - PY_LONG_LONG totalout; - PyObject *ret = NULL; - bz_stream *bzs = &self->bzs; - int bzerror; - - if (!PyArg_ParseTuple(args, "y*:decompress", &pdata)) - return NULL; - data = pdata.buf; - datasize = pdata.len; - - ACQUIRE_LOCK(self); - if (!self->running) { - PyErr_SetString(PyExc_EOFError, "end of stream was " - "already found"); - goto error; - } - - ret = PyBytes_FromStringAndSize(NULL, bufsize); - if (!ret) - goto error; - - bzs->next_in = data; - bzs->avail_in = datasize; - bzs->next_out = BUF(ret); - bzs->avail_out = bufsize; - - totalout = BZS_TOTAL_OUT(bzs); - - for (;;) { - Py_BEGIN_ALLOW_THREADS - bzerror = BZ2_bzDecompress(bzs); - Py_END_ALLOW_THREADS - if (bzerror == BZ_STREAM_END) { - if (bzs->avail_in != 0) { - Py_DECREF(self->unused_data); - self->unused_data = - PyBytes_FromStringAndSize(bzs->next_in, - bzs->avail_in); - } - self->running = 0; - break; - } - if (bzerror != BZ_OK) { - Util_CatchBZ2Error(bzerror); - goto error; - } - if (bzs->avail_in == 0) - break; /* no more input data */ - if (bzs->avail_out == 0) { - bufsize = Util_NewBufferSize(bufsize); - if (_PyBytes_Resize(&ret, bufsize) < 0) { - BZ2_bzDecompressEnd(bzs); - goto error; - } - bzs->next_out = BUF(ret); - bzs->next_out = BUF(ret) + (BZS_TOTAL_OUT(bzs) - - totalout); - bzs->avail_out = bufsize - (bzs->next_out - BUF(ret)); - } - } - - if (bzs->avail_out != 0) { - if (_PyBytes_Resize(&ret, - (Py_ssize_t)(BZS_TOTAL_OUT(bzs) - totalout)) < 0) - goto error; - } - - RELEASE_LOCK(self); - PyBuffer_Release(&pdata); - return ret; + Py_buffer pdata; + char *data; + int datasize; + int bufsize = SMALLCHUNK; + PY_LONG_LONG totalout; + PyObject *ret = NULL; + bz_stream *bzs = &self->bzs; + int bzerror; + + if (!PyArg_ParseTuple(args, "y*:decompress", &pdata)) + return NULL; + data = pdata.buf; + datasize = pdata.len; + + ACQUIRE_LOCK(self); + if (!self->running) { + PyErr_SetString(PyExc_EOFError, "end of stream was " + "already found"); + goto error; + } + + ret = PyBytes_FromStringAndSize(NULL, bufsize); + if (!ret) + goto error; + + bzs->next_in = data; + bzs->avail_in = datasize; + bzs->next_out = BUF(ret); + bzs->avail_out = bufsize; + + totalout = BZS_TOTAL_OUT(bzs); + + for (;;) { + Py_BEGIN_ALLOW_THREADS + bzerror = BZ2_bzDecompress(bzs); + Py_END_ALLOW_THREADS + if (bzerror == BZ_STREAM_END) { + if (bzs->avail_in != 0) { + Py_DECREF(self->unused_data); + self->unused_data = + PyBytes_FromStringAndSize(bzs->next_in, + bzs->avail_in); + } + self->running = 0; + break; + } + if (bzerror != BZ_OK) { + Util_CatchBZ2Error(bzerror); + goto error; + } + if (bzs->avail_in == 0) + break; /* no more input data */ + if (bzs->avail_out == 0) { + bufsize = Util_NewBufferSize(bufsize); + if (_PyBytes_Resize(&ret, bufsize) < 0) { + BZ2_bzDecompressEnd(bzs); + goto error; + } + bzs->next_out = BUF(ret); + bzs->next_out = BUF(ret) + (BZS_TOTAL_OUT(bzs) + - totalout); + bzs->avail_out = bufsize - (bzs->next_out - BUF(ret)); + } + } + + if (bzs->avail_out != 0) { + if (_PyBytes_Resize(&ret, + (Py_ssize_t)(BZS_TOTAL_OUT(bzs) - totalout)) < 0) + goto error; + } + + RELEASE_LOCK(self); + PyBuffer_Release(&pdata); + return ret; error: - RELEASE_LOCK(self); - PyBuffer_Release(&pdata); - Py_XDECREF(ret); - return NULL; + RELEASE_LOCK(self); + PyBuffer_Release(&pdata); + Py_XDECREF(ret); + return NULL; } static PyMethodDef BZ2Decomp_methods[] = { - {"decompress", (PyCFunction)BZ2Decomp_decompress, METH_VARARGS, BZ2Decomp_decompress__doc__}, - {NULL, NULL} /* sentinel */ + {"decompress", (PyCFunction)BZ2Decomp_decompress, METH_VARARGS, BZ2Decomp_decompress__doc__}, + {NULL, NULL} /* sentinel */ }; @@ -1790,55 +1790,55 @@ static int BZ2Decomp_init(BZ2DecompObject *self, PyObject *args, PyObject *kwargs) { - int bzerror; + int bzerror; - if (!PyArg_ParseTuple(args, ":BZ2Decompressor")) - return -1; + if (!PyArg_ParseTuple(args, ":BZ2Decompressor")) + return -1; #ifdef WITH_THREAD - self->lock = PyThread_allocate_lock(); - if (!self->lock) { - PyErr_SetString(PyExc_MemoryError, "unable to allocate lock"); - goto error; - } + self->lock = PyThread_allocate_lock(); + if (!self->lock) { + PyErr_SetString(PyExc_MemoryError, "unable to allocate lock"); + goto error; + } #endif - self->unused_data = PyBytes_FromStringAndSize("", 0); - if (!self->unused_data) - goto error; - - memset(&self->bzs, 0, sizeof(bz_stream)); - bzerror = BZ2_bzDecompressInit(&self->bzs, 0, 0); - if (bzerror != BZ_OK) { - Util_CatchBZ2Error(bzerror); - goto error; - } + self->unused_data = PyBytes_FromStringAndSize("", 0); + if (!self->unused_data) + goto error; + + memset(&self->bzs, 0, sizeof(bz_stream)); + bzerror = BZ2_bzDecompressInit(&self->bzs, 0, 0); + if (bzerror != BZ_OK) { + Util_CatchBZ2Error(bzerror); + goto error; + } - self->running = 1; + self->running = 1; - return 0; + return 0; error: #ifdef WITH_THREAD - if (self->lock) { - PyThread_free_lock(self->lock); - self->lock = NULL; - } + if (self->lock) { + PyThread_free_lock(self->lock); + self->lock = NULL; + } #endif - Py_CLEAR(self->unused_data); - return -1; + Py_CLEAR(self->unused_data); + return -1; } static void BZ2Decomp_dealloc(BZ2DecompObject *self) { #ifdef WITH_THREAD - if (self->lock) - PyThread_free_lock(self->lock); + if (self->lock) + PyThread_free_lock(self->lock); #endif - Py_XDECREF(self->unused_data); - BZ2_bzDecompressEnd(&self->bzs); - Py_TYPE(self)->tp_free((PyObject *)self); + Py_XDECREF(self->unused_data); + BZ2_bzDecompressEnd(&self->bzs); + Py_TYPE(self)->tp_free((PyObject *)self); } @@ -1854,46 +1854,46 @@ "); static PyTypeObject BZ2Decomp_Type = { - PyVarObject_HEAD_INIT(NULL, 0) - "bz2.BZ2Decompressor", /*tp_name*/ - sizeof(BZ2DecompObject), /*tp_basicsize*/ - 0, /*tp_itemsize*/ - (destructor)BZ2Decomp_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*/ - PyObject_GenericSetAttr,/*tp_setattro*/ - 0, /*tp_as_buffer*/ - Py_TPFLAGS_DEFAULT|Py_TPFLAGS_BASETYPE, /*tp_flags*/ - BZ2Decomp__doc__, /*tp_doc*/ - 0, /*tp_traverse*/ - 0, /*tp_clear*/ - 0, /*tp_richcompare*/ - 0, /*tp_weaklistoffset*/ - 0, /*tp_iter*/ - 0, /*tp_iternext*/ - BZ2Decomp_methods, /*tp_methods*/ - BZ2Decomp_members, /*tp_members*/ - 0, /*tp_getset*/ - 0, /*tp_base*/ - 0, /*tp_dict*/ - 0, /*tp_descr_get*/ - 0, /*tp_descr_set*/ - 0, /*tp_dictoffset*/ - (initproc)BZ2Decomp_init, /*tp_init*/ - PyType_GenericAlloc, /*tp_alloc*/ - PyType_GenericNew, /*tp_new*/ - PyObject_Free, /*tp_free*/ - 0, /*tp_is_gc*/ + PyVarObject_HEAD_INIT(NULL, 0) + "bz2.BZ2Decompressor", /*tp_name*/ + sizeof(BZ2DecompObject), /*tp_basicsize*/ + 0, /*tp_itemsize*/ + (destructor)BZ2Decomp_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*/ + PyObject_GenericSetAttr,/*tp_setattro*/ + 0, /*tp_as_buffer*/ + Py_TPFLAGS_DEFAULT|Py_TPFLAGS_BASETYPE, /*tp_flags*/ + BZ2Decomp__doc__, /*tp_doc*/ + 0, /*tp_traverse*/ + 0, /*tp_clear*/ + 0, /*tp_richcompare*/ + 0, /*tp_weaklistoffset*/ + 0, /*tp_iter*/ + 0, /*tp_iternext*/ + BZ2Decomp_methods, /*tp_methods*/ + BZ2Decomp_members, /*tp_members*/ + 0, /*tp_getset*/ + 0, /*tp_base*/ + 0, /*tp_dict*/ + 0, /*tp_descr_get*/ + 0, /*tp_descr_set*/ + 0, /*tp_dictoffset*/ + (initproc)BZ2Decomp_init, /*tp_init*/ + PyType_GenericAlloc, /*tp_alloc*/ + PyType_GenericNew, /*tp_new*/ + PyObject_Free, /*tp_free*/ + 0, /*tp_is_gc*/ }; @@ -1911,90 +1911,90 @@ static PyObject * bz2_compress(PyObject *self, PyObject *args, PyObject *kwargs) { - int compresslevel=9; - Py_buffer pdata; - char *data; - int datasize; - int bufsize; - PyObject *ret = NULL; - bz_stream _bzs; - bz_stream *bzs = &_bzs; - int bzerror; - static char *kwlist[] = {"data", "compresslevel", 0}; - - if (!PyArg_ParseTupleAndKeywords(args, kwargs, "y*|i", - kwlist, &pdata, - &compresslevel)) - return NULL; - data = pdata.buf; - datasize = pdata.len; - - if (compresslevel < 1 || compresslevel > 9) { - PyErr_SetString(PyExc_ValueError, - "compresslevel must be between 1 and 9"); - PyBuffer_Release(&pdata); - return NULL; - } - - /* Conforming to bz2 manual, this is large enough to fit compressed - * data in one shot. We will check it later anyway. */ - bufsize = datasize + (datasize/100+1) + 600; - - ret = PyBytes_FromStringAndSize(NULL, bufsize); - if (!ret) { - PyBuffer_Release(&pdata); - return NULL; - } - - memset(bzs, 0, sizeof(bz_stream)); - - bzs->next_in = data; - bzs->avail_in = datasize; - bzs->next_out = BUF(ret); - bzs->avail_out = bufsize; - - bzerror = BZ2_bzCompressInit(bzs, compresslevel, 0, 0); - if (bzerror != BZ_OK) { - Util_CatchBZ2Error(bzerror); - PyBuffer_Release(&pdata); - Py_DECREF(ret); - return NULL; - } - - for (;;) { - Py_BEGIN_ALLOW_THREADS - bzerror = BZ2_bzCompress(bzs, BZ_FINISH); - Py_END_ALLOW_THREADS - if (bzerror == BZ_STREAM_END) { - break; - } else if (bzerror != BZ_FINISH_OK) { - BZ2_bzCompressEnd(bzs); - Util_CatchBZ2Error(bzerror); - PyBuffer_Release(&pdata); - Py_DECREF(ret); - return NULL; - } - if (bzs->avail_out == 0) { - bufsize = Util_NewBufferSize(bufsize); - if (_PyBytes_Resize(&ret, bufsize) < 0) { - BZ2_bzCompressEnd(bzs); - PyBuffer_Release(&pdata); - return NULL; - } - bzs->next_out = BUF(ret) + BZS_TOTAL_OUT(bzs); - bzs->avail_out = bufsize - (bzs->next_out - BUF(ret)); - } - } - - if (bzs->avail_out != 0) { - if (_PyBytes_Resize(&ret, (Py_ssize_t)BZS_TOTAL_OUT(bzs)) < 0) { - ret = NULL; - } - } - BZ2_bzCompressEnd(bzs); + int compresslevel=9; + Py_buffer pdata; + char *data; + int datasize; + int bufsize; + PyObject *ret = NULL; + bz_stream _bzs; + bz_stream *bzs = &_bzs; + int bzerror; + static char *kwlist[] = {"data", "compresslevel", 0}; + + if (!PyArg_ParseTupleAndKeywords(args, kwargs, "y*|i", + kwlist, &pdata, + &compresslevel)) + return NULL; + data = pdata.buf; + datasize = pdata.len; + + if (compresslevel < 1 || compresslevel > 9) { + PyErr_SetString(PyExc_ValueError, + "compresslevel must be between 1 and 9"); + PyBuffer_Release(&pdata); + return NULL; + } + + /* Conforming to bz2 manual, this is large enough to fit compressed + * data in one shot. We will check it later anyway. */ + bufsize = datasize + (datasize/100+1) + 600; + + ret = PyBytes_FromStringAndSize(NULL, bufsize); + if (!ret) { + PyBuffer_Release(&pdata); + return NULL; + } + + memset(bzs, 0, sizeof(bz_stream)); + + bzs->next_in = data; + bzs->avail_in = datasize; + bzs->next_out = BUF(ret); + bzs->avail_out = bufsize; + + bzerror = BZ2_bzCompressInit(bzs, compresslevel, 0, 0); + if (bzerror != BZ_OK) { + Util_CatchBZ2Error(bzerror); + PyBuffer_Release(&pdata); + Py_DECREF(ret); + return NULL; + } + + for (;;) { + Py_BEGIN_ALLOW_THREADS + bzerror = BZ2_bzCompress(bzs, BZ_FINISH); + Py_END_ALLOW_THREADS + if (bzerror == BZ_STREAM_END) { + break; + } else if (bzerror != BZ_FINISH_OK) { + BZ2_bzCompressEnd(bzs); + Util_CatchBZ2Error(bzerror); + PyBuffer_Release(&pdata); + Py_DECREF(ret); + return NULL; + } + if (bzs->avail_out == 0) { + bufsize = Util_NewBufferSize(bufsize); + if (_PyBytes_Resize(&ret, bufsize) < 0) { + BZ2_bzCompressEnd(bzs); + PyBuffer_Release(&pdata); + return NULL; + } + bzs->next_out = BUF(ret) + BZS_TOTAL_OUT(bzs); + bzs->avail_out = bufsize - (bzs->next_out - BUF(ret)); + } + } + + if (bzs->avail_out != 0) { + if (_PyBytes_Resize(&ret, (Py_ssize_t)BZS_TOTAL_OUT(bzs)) < 0) { + ret = NULL; + } + } + BZ2_bzCompressEnd(bzs); - PyBuffer_Release(&pdata); - return ret; + PyBuffer_Release(&pdata); + return ret; } PyDoc_STRVAR(bz2_decompress__doc__, @@ -2007,96 +2007,96 @@ static PyObject * bz2_decompress(PyObject *self, PyObject *args) { - Py_buffer pdata; - char *data; - int datasize; - int bufsize = SMALLCHUNK; - PyObject *ret; - bz_stream _bzs; - bz_stream *bzs = &_bzs; - int bzerror; - - if (!PyArg_ParseTuple(args, "y*:decompress", &pdata)) - return NULL; - data = pdata.buf; - datasize = pdata.len; - - if (datasize == 0) { - PyBuffer_Release(&pdata); - return PyBytes_FromStringAndSize("", 0); - } - - ret = PyBytes_FromStringAndSize(NULL, bufsize); - if (!ret) { - PyBuffer_Release(&pdata); - return NULL; - } - - memset(bzs, 0, sizeof(bz_stream)); - - bzs->next_in = data; - bzs->avail_in = datasize; - bzs->next_out = BUF(ret); - bzs->avail_out = bufsize; - - bzerror = BZ2_bzDecompressInit(bzs, 0, 0); - if (bzerror != BZ_OK) { - Util_CatchBZ2Error(bzerror); - Py_DECREF(ret); - PyBuffer_Release(&pdata); - return NULL; - } - - for (;;) { - Py_BEGIN_ALLOW_THREADS - bzerror = BZ2_bzDecompress(bzs); - Py_END_ALLOW_THREADS - if (bzerror == BZ_STREAM_END) { - break; - } else if (bzerror != BZ_OK) { - BZ2_bzDecompressEnd(bzs); - Util_CatchBZ2Error(bzerror); - PyBuffer_Release(&pdata); - Py_DECREF(ret); - return NULL; - } - if (bzs->avail_in == 0) { - BZ2_bzDecompressEnd(bzs); - PyErr_SetString(PyExc_ValueError, - "couldn't find end of stream"); - PyBuffer_Release(&pdata); - Py_DECREF(ret); - return NULL; - } - if (bzs->avail_out == 0) { - bufsize = Util_NewBufferSize(bufsize); - if (_PyBytes_Resize(&ret, bufsize) < 0) { - BZ2_bzDecompressEnd(bzs); - PyBuffer_Release(&pdata); - return NULL; - } - bzs->next_out = BUF(ret) + BZS_TOTAL_OUT(bzs); - bzs->avail_out = bufsize - (bzs->next_out - BUF(ret)); - } - } - - if (bzs->avail_out != 0) { - if (_PyBytes_Resize(&ret, (Py_ssize_t)BZS_TOTAL_OUT(bzs)) < 0) { - ret = NULL; - } - } - BZ2_bzDecompressEnd(bzs); - PyBuffer_Release(&pdata); + Py_buffer pdata; + char *data; + int datasize; + int bufsize = SMALLCHUNK; + PyObject *ret; + bz_stream _bzs; + bz_stream *bzs = &_bzs; + int bzerror; + + if (!PyArg_ParseTuple(args, "y*:decompress", &pdata)) + return NULL; + data = pdata.buf; + datasize = pdata.len; + + if (datasize == 0) { + PyBuffer_Release(&pdata); + return PyBytes_FromStringAndSize("", 0); + } + + ret = PyBytes_FromStringAndSize(NULL, bufsize); + if (!ret) { + PyBuffer_Release(&pdata); + return NULL; + } + + memset(bzs, 0, sizeof(bz_stream)); + + bzs->next_in = data; + bzs->avail_in = datasize; + bzs->next_out = BUF(ret); + bzs->avail_out = bufsize; + + bzerror = BZ2_bzDecompressInit(bzs, 0, 0); + if (bzerror != BZ_OK) { + Util_CatchBZ2Error(bzerror); + Py_DECREF(ret); + PyBuffer_Release(&pdata); + return NULL; + } + + for (;;) { + Py_BEGIN_ALLOW_THREADS + bzerror = BZ2_bzDecompress(bzs); + Py_END_ALLOW_THREADS + if (bzerror == BZ_STREAM_END) { + break; + } else if (bzerror != BZ_OK) { + BZ2_bzDecompressEnd(bzs); + Util_CatchBZ2Error(bzerror); + PyBuffer_Release(&pdata); + Py_DECREF(ret); + return NULL; + } + if (bzs->avail_in == 0) { + BZ2_bzDecompressEnd(bzs); + PyErr_SetString(PyExc_ValueError, + "couldn't find end of stream"); + PyBuffer_Release(&pdata); + Py_DECREF(ret); + return NULL; + } + if (bzs->avail_out == 0) { + bufsize = Util_NewBufferSize(bufsize); + if (_PyBytes_Resize(&ret, bufsize) < 0) { + BZ2_bzDecompressEnd(bzs); + PyBuffer_Release(&pdata); + return NULL; + } + bzs->next_out = BUF(ret) + BZS_TOTAL_OUT(bzs); + bzs->avail_out = bufsize - (bzs->next_out - BUF(ret)); + } + } + + if (bzs->avail_out != 0) { + if (_PyBytes_Resize(&ret, (Py_ssize_t)BZS_TOTAL_OUT(bzs)) < 0) { + ret = NULL; + } + } + BZ2_bzDecompressEnd(bzs); + PyBuffer_Release(&pdata); - return ret; + return ret; } static PyMethodDef bz2_methods[] = { - {"compress", (PyCFunction) bz2_compress, METH_VARARGS|METH_KEYWORDS, - bz2_compress__doc__}, - {"decompress", (PyCFunction) bz2_decompress, METH_VARARGS, - bz2_decompress__doc__}, - {NULL, NULL} /* sentinel */ + {"compress", (PyCFunction) bz2_compress, METH_VARARGS|METH_KEYWORDS, + bz2_compress__doc__}, + {"decompress", (PyCFunction) bz2_decompress, METH_VARARGS, + bz2_decompress__doc__}, + {NULL, NULL} /* sentinel */ }; /* ===================================================================== */ @@ -2111,39 +2111,39 @@ static struct PyModuleDef bz2module = { - PyModuleDef_HEAD_INIT, - "bz2", - bz2__doc__, - -1, - bz2_methods, - NULL, - NULL, - NULL, - NULL + PyModuleDef_HEAD_INIT, + "bz2", + bz2__doc__, + -1, + bz2_methods, + NULL, + NULL, + NULL, + NULL }; PyMODINIT_FUNC PyInit_bz2(void) { - PyObject *m; + PyObject *m; - Py_TYPE(&BZ2File_Type) = &PyType_Type; - Py_TYPE(&BZ2Comp_Type) = &PyType_Type; - Py_TYPE(&BZ2Decomp_Type) = &PyType_Type; + Py_TYPE(&BZ2File_Type) = &PyType_Type; + Py_TYPE(&BZ2Comp_Type) = &PyType_Type; + Py_TYPE(&BZ2Decomp_Type) = &PyType_Type; - m = PyModule_Create(&bz2module); - if (m == NULL) - return NULL; + m = PyModule_Create(&bz2module); + if (m == NULL) + return NULL; - PyModule_AddObject(m, "__author__", PyUnicode_FromString(__author__)); + PyModule_AddObject(m, "__author__", PyUnicode_FromString(__author__)); - Py_INCREF(&BZ2File_Type); - PyModule_AddObject(m, "BZ2File", (PyObject *)&BZ2File_Type); + Py_INCREF(&BZ2File_Type); + PyModule_AddObject(m, "BZ2File", (PyObject *)&BZ2File_Type); - Py_INCREF(&BZ2Comp_Type); - PyModule_AddObject(m, "BZ2Compressor", (PyObject *)&BZ2Comp_Type); + Py_INCREF(&BZ2Comp_Type); + PyModule_AddObject(m, "BZ2Compressor", (PyObject *)&BZ2Comp_Type); - Py_INCREF(&BZ2Decomp_Type); - PyModule_AddObject(m, "BZ2Decompressor", (PyObject *)&BZ2Decomp_Type); - return m; + Py_INCREF(&BZ2Decomp_Type); + PyModule_AddObject(m, "BZ2Decompressor", (PyObject *)&BZ2Decomp_Type); + return m; } Modified: python/branches/py3k/Modules/cjkcodecs/_codecs_cn.c ============================================================================== --- python/branches/py3k/Modules/cjkcodecs/_codecs_cn.c (original) +++ python/branches/py3k/Modules/cjkcodecs/_codecs_cn.c Sun May 9 17:52:27 2010 @@ -17,24 +17,24 @@ /* GBK and GB2312 map differently in few codepoints that are listed below: * - * gb2312 gbk - * A1A4 U+30FB KATAKANA MIDDLE DOT U+00B7 MIDDLE DOT - * A1AA U+2015 HORIZONTAL BAR U+2014 EM DASH - * A844 undefined U+2015 HORIZONTAL BAR + * gb2312 gbk + * A1A4 U+30FB KATAKANA MIDDLE DOT U+00B7 MIDDLE DOT + * A1AA U+2015 HORIZONTAL BAR U+2014 EM DASH + * A844 undefined U+2015 HORIZONTAL BAR */ #define GBK_DECODE(dc1, dc2, assi) \ - if ((dc1) == 0xa1 && (dc2) == 0xaa) (assi) = 0x2014; \ - else if ((dc1) == 0xa8 && (dc2) == 0x44) (assi) = 0x2015; \ - else if ((dc1) == 0xa1 && (dc2) == 0xa4) (assi) = 0x00b7; \ - else TRYMAP_DEC(gb2312, assi, dc1 ^ 0x80, dc2 ^ 0x80); \ - else TRYMAP_DEC(gbkext, assi, dc1, dc2); + if ((dc1) == 0xa1 && (dc2) == 0xaa) (assi) = 0x2014; \ + else if ((dc1) == 0xa8 && (dc2) == 0x44) (assi) = 0x2015; \ + else if ((dc1) == 0xa1 && (dc2) == 0xa4) (assi) = 0x00b7; \ + else TRYMAP_DEC(gb2312, assi, dc1 ^ 0x80, dc2 ^ 0x80); \ + else TRYMAP_DEC(gbkext, assi, dc1, dc2); #define GBK_ENCODE(code, assi) \ - if ((code) == 0x2014) (assi) = 0xa1aa; \ - else if ((code) == 0x2015) (assi) = 0xa844; \ - else if ((code) == 0x00b7) (assi) = 0xa1a4; \ - else if ((code) != 0x30fb && TRYMAP_ENC_COND(gbcommon, assi, code)); + if ((code) == 0x2014) (assi) = 0xa1aa; \ + else if ((code) == 0x2015) (assi) = 0xa844; \ + else if ((code) == 0x00b7) (assi) = 0xa1a4; \ + else if ((code) != 0x30fb && TRYMAP_ENC_COND(gbcommon, assi, code)); /* * GB2312 codec @@ -42,53 +42,53 @@ ENCODER(gb2312) { - while (inleft > 0) { - Py_UNICODE c = IN1; - DBCHAR code; - - if (c < 0x80) { - WRITE1((unsigned char)c) - NEXT(1, 1) - continue; - } - UCS4INVALID(c) - - REQUIRE_OUTBUF(2) - TRYMAP_ENC(gbcommon, code, c); - else return 1; - - if (code & 0x8000) /* MSB set: GBK */ - return 1; - - OUT1((code >> 8) | 0x80) - OUT2((code & 0xFF) | 0x80) - NEXT(1, 2) - } + while (inleft > 0) { + Py_UNICODE c = IN1; + DBCHAR code; + + if (c < 0x80) { + WRITE1((unsigned char)c) + NEXT(1, 1) + continue; + } + UCS4INVALID(c) + + REQUIRE_OUTBUF(2) + TRYMAP_ENC(gbcommon, code, c); + else return 1; + + if (code & 0x8000) /* MSB set: GBK */ + return 1; + + OUT1((code >> 8) | 0x80) + OUT2((code & 0xFF) | 0x80) + NEXT(1, 2) + } - return 0; + return 0; } DECODER(gb2312) { - while (inleft > 0) { - unsigned char c = **inbuf; + while (inleft > 0) { + unsigned char c = **inbuf; - REQUIRE_OUTBUF(1) + REQUIRE_OUTBUF(1) - if (c < 0x80) { - OUT1(c) - NEXT(1, 1) - continue; - } - - REQUIRE_INBUF(2) - TRYMAP_DEC(gb2312, **outbuf, c ^ 0x80, IN2 ^ 0x80) { - NEXT(2, 1) - } - else return 2; - } + if (c < 0x80) { + OUT1(c) + NEXT(1, 1) + continue; + } + + REQUIRE_INBUF(2) + TRYMAP_DEC(gb2312, **outbuf, c ^ 0x80, IN2 ^ 0x80) { + NEXT(2, 1) + } + else return 2; + } - return 0; + return 0; } @@ -98,55 +98,55 @@ ENCODER(gbk) { - while (inleft > 0) { - Py_UNICODE c = IN1; - DBCHAR code; - - if (c < 0x80) { - WRITE1((unsigned char)c) - NEXT(1, 1) - continue; - } - UCS4INVALID(c) - - REQUIRE_OUTBUF(2) - - GBK_ENCODE(c, code) - else return 1; - - OUT1((code >> 8) | 0x80) - if (code & 0x8000) - OUT2((code & 0xFF)) /* MSB set: GBK */ - else - OUT2((code & 0xFF) | 0x80) /* MSB unset: GB2312 */ - NEXT(1, 2) - } + while (inleft > 0) { + Py_UNICODE c = IN1; + DBCHAR code; + + if (c < 0x80) { + WRITE1((unsigned char)c) + NEXT(1, 1) + continue; + } + UCS4INVALID(c) + + REQUIRE_OUTBUF(2) + + GBK_ENCODE(c, code) + else return 1; + + OUT1((code >> 8) | 0x80) + if (code & 0x8000) + OUT2((code & 0xFF)) /* MSB set: GBK */ + else + OUT2((code & 0xFF) | 0x80) /* MSB unset: GB2312 */ + NEXT(1, 2) + } - return 0; + return 0; } DECODER(gbk) { - while (inleft > 0) { - unsigned char c = IN1; + while (inleft > 0) { + unsigned char c = IN1; - REQUIRE_OUTBUF(1) + REQUIRE_OUTBUF(1) - if (c < 0x80) { - OUT1(c) - NEXT(1, 1) - continue; - } + if (c < 0x80) { + OUT1(c) + NEXT(1, 1) + continue; + } - REQUIRE_INBUF(2) + REQUIRE_INBUF(2) - GBK_DECODE(c, IN2, **outbuf) - else return 2; + GBK_DECODE(c, IN2, **outbuf) + else return 2; - NEXT(2, 1) - } + NEXT(2, 1) + } - return 0; + return 0; } @@ -156,153 +156,153 @@ ENCODER(gb18030) { - while (inleft > 0) { - ucs4_t c = IN1; - DBCHAR code; - - if (c < 0x80) { - WRITE1(c) - NEXT(1, 1) - continue; - } + while (inleft > 0) { + ucs4_t c = IN1; + DBCHAR code; + + if (c < 0x80) { + WRITE1(c) + NEXT(1, 1) + continue; + } - DECODE_SURROGATE(c) - if (c > 0x10FFFF) + DECODE_SURROGATE(c) + if (c > 0x10FFFF) #if Py_UNICODE_SIZE == 2 - return 2; /* surrogates pair */ + return 2; /* surrogates pair */ #else - return 1; + return 1; #endif - else if (c >= 0x10000) { - ucs4_t tc = c - 0x10000; + else if (c >= 0x10000) { + ucs4_t tc = c - 0x10000; - REQUIRE_OUTBUF(4) + REQUIRE_OUTBUF(4) - OUT4((unsigned char)(tc % 10) + 0x30) - tc /= 10; - OUT3((unsigned char)(tc % 126) + 0x81) - tc /= 126; - OUT2((unsigned char)(tc % 10) + 0x30) - tc /= 10; - OUT1((unsigned char)(tc + 0x90)) + OUT4((unsigned char)(tc % 10) + 0x30) + tc /= 10; + OUT3((unsigned char)(tc % 126) + 0x81) + tc /= 126; + OUT2((unsigned char)(tc % 10) + 0x30) + tc /= 10; + OUT1((unsigned char)(tc + 0x90)) #if Py_UNICODE_SIZE == 2 - NEXT(2, 4) /* surrogates pair */ + NEXT(2, 4) /* surrogates pair */ #else - NEXT(1, 4) + NEXT(1, 4) #endif - continue; - } + continue; + } - REQUIRE_OUTBUF(2) + REQUIRE_OUTBUF(2) - GBK_ENCODE(c, code) - else TRYMAP_ENC(gb18030ext, code, c); - else { - const struct _gb18030_to_unibmp_ranges *utrrange; - - REQUIRE_OUTBUF(4) - - for (utrrange = gb18030_to_unibmp_ranges; - utrrange->first != 0; - utrrange++) - if (utrrange->first <= c && - c <= utrrange->last) { - Py_UNICODE tc; - - tc = c - utrrange->first + - utrrange->base; - - OUT4((unsigned char)(tc % 10) + 0x30) - tc /= 10; - OUT3((unsigned char)(tc % 126) + 0x81) - tc /= 126; - OUT2((unsigned char)(tc % 10) + 0x30) - tc /= 10; - OUT1((unsigned char)tc + 0x81) - - NEXT(1, 4) - break; - } - - if (utrrange->first == 0) - return 1; - continue; - } - - OUT1((code >> 8) | 0x80) - if (code & 0x8000) - OUT2((code & 0xFF)) /* MSB set: GBK or GB18030ext */ - else - OUT2((code & 0xFF) | 0x80) /* MSB unset: GB2312 */ + GBK_ENCODE(c, code) + else TRYMAP_ENC(gb18030ext, code, c); + else { + const struct _gb18030_to_unibmp_ranges *utrrange; + + REQUIRE_OUTBUF(4) + + for (utrrange = gb18030_to_unibmp_ranges; + utrrange->first != 0; + utrrange++) + if (utrrange->first <= c && + c <= utrrange->last) { + Py_UNICODE tc; + + tc = c - utrrange->first + + utrrange->base; + + OUT4((unsigned char)(tc % 10) + 0x30) + tc /= 10; + OUT3((unsigned char)(tc % 126) + 0x81) + tc /= 126; + OUT2((unsigned char)(tc % 10) + 0x30) + tc /= 10; + OUT1((unsigned char)tc + 0x81) + + NEXT(1, 4) + break; + } + + if (utrrange->first == 0) + return 1; + continue; + } + + OUT1((code >> 8) | 0x80) + if (code & 0x8000) + OUT2((code & 0xFF)) /* MSB set: GBK or GB18030ext */ + else + OUT2((code & 0xFF) | 0x80) /* MSB unset: GB2312 */ - NEXT(1, 2) - } + NEXT(1, 2) + } - return 0; + return 0; } DECODER(gb18030) { - while (inleft > 0) { - unsigned char c = IN1, c2; + while (inleft > 0) { + unsigned char c = IN1, c2; - REQUIRE_OUTBUF(1) + REQUIRE_OUTBUF(1) - if (c < 0x80) { - OUT1(c) - NEXT(1, 1) - continue; - } - - REQUIRE_INBUF(2) - - c2 = IN2; - if (c2 >= 0x30 && c2 <= 0x39) { /* 4 bytes seq */ - const struct _gb18030_to_unibmp_ranges *utr; - unsigned char c3, c4; - ucs4_t lseq; - - REQUIRE_INBUF(4) - c3 = IN3; - c4 = IN4; - if (c < 0x81 || c3 < 0x81 || c4 < 0x30 || c4 > 0x39) - return 4; - c -= 0x81; c2 -= 0x30; - c3 -= 0x81; c4 -= 0x30; - - if (c < 4) { /* U+0080 - U+FFFF */ - lseq = ((ucs4_t)c * 10 + c2) * 1260 + - (ucs4_t)c3 * 10 + c4; - if (lseq < 39420) { - for (utr = gb18030_to_unibmp_ranges; - lseq >= (utr + 1)->base; - utr++) ; - OUT1(utr->first - utr->base + lseq) - NEXT(4, 1) - continue; - } - } - else if (c >= 15) { /* U+10000 - U+10FFFF */ - lseq = 0x10000 + (((ucs4_t)c-15) * 10 + c2) - * 1260 + (ucs4_t)c3 * 10 + c4; - if (lseq <= 0x10FFFF) { - WRITEUCS4(lseq); - NEXT_IN(4) - continue; - } - } - return 4; - } - - GBK_DECODE(c, c2, **outbuf) - else TRYMAP_DEC(gb18030ext, **outbuf, c, c2); - else return 2; + if (c < 0x80) { + OUT1(c) + NEXT(1, 1) + continue; + } + + REQUIRE_INBUF(2) + + c2 = IN2; + if (c2 >= 0x30 && c2 <= 0x39) { /* 4 bytes seq */ + const struct _gb18030_to_unibmp_ranges *utr; + unsigned char c3, c4; + ucs4_t lseq; + + REQUIRE_INBUF(4) + c3 = IN3; + c4 = IN4; + if (c < 0x81 || c3 < 0x81 || c4 < 0x30 || c4 > 0x39) + return 4; + c -= 0x81; c2 -= 0x30; + c3 -= 0x81; c4 -= 0x30; + + if (c < 4) { /* U+0080 - U+FFFF */ + lseq = ((ucs4_t)c * 10 + c2) * 1260 + + (ucs4_t)c3 * 10 + c4; + if (lseq < 39420) { + for (utr = gb18030_to_unibmp_ranges; + lseq >= (utr + 1)->base; + utr++) ; + OUT1(utr->first - utr->base + lseq) + NEXT(4, 1) + continue; + } + } + else if (c >= 15) { /* U+10000 - U+10FFFF */ + lseq = 0x10000 + (((ucs4_t)c-15) * 10 + c2) + * 1260 + (ucs4_t)c3 * 10 + c4; + if (lseq <= 0x10FFFF) { + WRITEUCS4(lseq); + NEXT_IN(4) + continue; + } + } + return 4; + } + + GBK_DECODE(c, c2, **outbuf) + else TRYMAP_DEC(gb18030ext, **outbuf, c, c2); + else return 2; - NEXT(2, 1) - } + NEXT(2, 1) + } - return 0; + return 0; } @@ -312,118 +312,118 @@ ENCODER_INIT(hz) { - state->i = 0; - return 0; + state->i = 0; + return 0; } ENCODER_RESET(hz) { - if (state->i != 0) { - WRITE2('~', '}') - state->i = 0; - NEXT_OUT(2) - } - return 0; + if (state->i != 0) { + WRITE2('~', '}') + state->i = 0; + NEXT_OUT(2) + } + return 0; } ENCODER(hz) { - while (inleft > 0) { - Py_UNICODE c = IN1; - DBCHAR code; - - if (c < 0x80) { - if (state->i == 0) { - WRITE1((unsigned char)c) - NEXT(1, 1) - } - else { - WRITE3('~', '}', (unsigned char)c) - NEXT(1, 3) - state->i = 0; - } - continue; - } - - UCS4INVALID(c) - - TRYMAP_ENC(gbcommon, code, c); - else return 1; - - if (code & 0x8000) /* MSB set: GBK */ - return 1; - - if (state->i == 0) { - WRITE4('~', '{', code >> 8, code & 0xff) - NEXT(1, 4) - state->i = 1; - } - else { - WRITE2(code >> 8, code & 0xff) - NEXT(1, 2) - } - } + while (inleft > 0) { + Py_UNICODE c = IN1; + DBCHAR code; + + if (c < 0x80) { + if (state->i == 0) { + WRITE1((unsigned char)c) + NEXT(1, 1) + } + else { + WRITE3('~', '}', (unsigned char)c) + NEXT(1, 3) + state->i = 0; + } + continue; + } + + UCS4INVALID(c) + + TRYMAP_ENC(gbcommon, code, c); + else return 1; + + if (code & 0x8000) /* MSB set: GBK */ + return 1; + + if (state->i == 0) { + WRITE4('~', '{', code >> 8, code & 0xff) + NEXT(1, 4) + state->i = 1; + } + else { + WRITE2(code >> 8, code & 0xff) + NEXT(1, 2) + } + } - return 0; + return 0; } DECODER_INIT(hz) { - state->i = 0; - return 0; + state->i = 0; + return 0; } DECODER_RESET(hz) { - state->i = 0; - return 0; + state->i = 0; + return 0; } DECODER(hz) { - while (inleft > 0) { - unsigned char c = IN1; + while (inleft > 0) { + unsigned char c = IN1; - if (c == '~') { - unsigned char c2 = IN2; + if (c == '~') { + unsigned char c2 = IN2; - REQUIRE_INBUF(2) - if (c2 == '~') { - WRITE1('~') - NEXT(2, 1) - continue; - } - else if (c2 == '{' && state->i == 0) - state->i = 1; /* set GB */ - else if (c2 == '}' && state->i == 1) - state->i = 0; /* set ASCII */ - else if (c2 == '\n') - ; /* line-continuation */ - else - return 2; - NEXT(2, 0); - continue; - } - - if (c & 0x80) - return 1; - - if (state->i == 0) { /* ASCII mode */ - WRITE1(c) - NEXT(1, 1) - } - else { /* GB mode */ - REQUIRE_INBUF(2) - REQUIRE_OUTBUF(1) - TRYMAP_DEC(gb2312, **outbuf, c, IN2) { - NEXT(2, 1) - } - else - return 2; - } - } + REQUIRE_INBUF(2) + if (c2 == '~') { + WRITE1('~') + NEXT(2, 1) + continue; + } + else if (c2 == '{' && state->i == 0) + state->i = 1; /* set GB */ + else if (c2 == '}' && state->i == 1) + state->i = 0; /* set ASCII */ + else if (c2 == '\n') + ; /* line-continuation */ + else + return 2; + NEXT(2, 0); + continue; + } + + if (c & 0x80) + return 1; + + if (state->i == 0) { /* ASCII mode */ + WRITE1(c) + NEXT(1, 1) + } + else { /* GB mode */ + REQUIRE_INBUF(2) + REQUIRE_OUTBUF(1) + TRYMAP_DEC(gb2312, **outbuf, c, IN2) { + NEXT(2, 1) + } + else + return 2; + } + } - return 0; + return 0; } Modified: python/branches/py3k/Modules/cjkcodecs/_codecs_hk.c ============================================================================== --- python/branches/py3k/Modules/cjkcodecs/_codecs_hk.c (original) +++ python/branches/py3k/Modules/cjkcodecs/_codecs_hk.c Sun May 9 17:52:27 2010 @@ -18,12 +18,12 @@ CODEC_INIT(big5hkscs) { - static int initialized = 0; + static int initialized = 0; - if (!initialized && IMPORT_MAP(tw, big5, &big5_encmap, &big5_decmap)) - return -1; - initialized = 1; - return 0; + if (!initialized && IMPORT_MAP(tw, big5, &big5_encmap, &big5_decmap)) + return -1; + initialized = 1; + return 0; } /* @@ -38,135 +38,135 @@ ENCODER(big5hkscs) { - while (inleft > 0) { - ucs4_t c = **inbuf; - DBCHAR code; - Py_ssize_t insize; - - if (c < 0x80) { - REQUIRE_OUTBUF(1) - **outbuf = (unsigned char)c; - NEXT(1, 1) - continue; - } - - DECODE_SURROGATE(c) - insize = GET_INSIZE(c); - - REQUIRE_OUTBUF(2) - - if (c < 0x10000) { - TRYMAP_ENC(big5hkscs_bmp, code, c) { - if (code == MULTIC) { - if (inleft >= 2 && - ((c & 0xffdf) == 0x00ca) && - (((*inbuf)[1] & 0xfff7) == 0x0304)) { - code = big5hkscs_pairenc_table[ - ((c >> 4) | - ((*inbuf)[1] >> 3)) & 3]; - insize = 2; - } - else if (inleft < 2 && - !(flags & MBENC_FLUSH)) - return MBERR_TOOFEW; - else { - if (c == 0xca) - code = 0x8866; - else /* c == 0xea */ - code = 0x88a7; - } - } - } - else TRYMAP_ENC(big5, code, c); - else return 1; - } - else if (c < 0x20000) - return insize; - else if (c < 0x30000) { - TRYMAP_ENC(big5hkscs_nonbmp, code, c & 0xffff); - else return insize; - } - else - return insize; - - OUT1(code >> 8) - OUT2(code & 0xFF) - NEXT(insize, 2) - } + while (inleft > 0) { + ucs4_t c = **inbuf; + DBCHAR code; + Py_ssize_t insize; + + if (c < 0x80) { + REQUIRE_OUTBUF(1) + **outbuf = (unsigned char)c; + NEXT(1, 1) + continue; + } + + DECODE_SURROGATE(c) + insize = GET_INSIZE(c); + + REQUIRE_OUTBUF(2) + + if (c < 0x10000) { + TRYMAP_ENC(big5hkscs_bmp, code, c) { + if (code == MULTIC) { + if (inleft >= 2 && + ((c & 0xffdf) == 0x00ca) && + (((*inbuf)[1] & 0xfff7) == 0x0304)) { + code = big5hkscs_pairenc_table[ + ((c >> 4) | + ((*inbuf)[1] >> 3)) & 3]; + insize = 2; + } + else if (inleft < 2 && + !(flags & MBENC_FLUSH)) + return MBERR_TOOFEW; + else { + if (c == 0xca) + code = 0x8866; + else /* c == 0xea */ + code = 0x88a7; + } + } + } + else TRYMAP_ENC(big5, code, c); + else return 1; + } + else if (c < 0x20000) + return insize; + else if (c < 0x30000) { + TRYMAP_ENC(big5hkscs_nonbmp, code, c & 0xffff); + else return insize; + } + else + return insize; + + OUT1(code >> 8) + OUT2(code & 0xFF) + NEXT(insize, 2) + } - return 0; + return 0; } #define BH2S(c1, c2) (((c1) - 0x87) * (0xfe - 0x40 + 1) + ((c2) - 0x40)) DECODER(big5hkscs) { - while (inleft > 0) { - unsigned char c = IN1; - ucs4_t decoded; - - REQUIRE_OUTBUF(1) - - if (c < 0x80) { - OUT1(c) - NEXT(1, 1) - continue; - } - - REQUIRE_INBUF(2) - - if (0xc6 <= c && c <= 0xc8 && (c >= 0xc7 || IN2 >= 0xa1)) - goto hkscsdec; - - TRYMAP_DEC(big5, **outbuf, c, IN2) { - NEXT(2, 1) - } - else -hkscsdec: TRYMAP_DEC(big5hkscs, decoded, c, IN2) { - int s = BH2S(c, IN2); - const unsigned char *hintbase; - - assert(0x87 <= c && c <= 0xfe); - assert(0x40 <= IN2 && IN2 <= 0xfe); - - if (BH2S(0x87, 0x40) <= s && s <= BH2S(0xa0, 0xfe)) { - hintbase = big5hkscs_phint_0; - s -= BH2S(0x87, 0x40); - } - else if (BH2S(0xc6,0xa1) <= s && s <= BH2S(0xc8,0xfe)){ - hintbase = big5hkscs_phint_12130; - s -= BH2S(0xc6, 0xa1); - } - else if (BH2S(0xf9,0xd6) <= s && s <= BH2S(0xfe,0xfe)){ - hintbase = big5hkscs_phint_21924; - s -= BH2S(0xf9, 0xd6); - } - else - return MBERR_INTERNAL; - - if (hintbase[s >> 3] & (1 << (s & 7))) { - WRITEUCS4(decoded | 0x20000) - NEXT_IN(2) - } - else { - OUT1(decoded) - NEXT(2, 1) - } - } - else { - switch ((c << 8) | IN2) { - case 0x8862: WRITE2(0x00ca, 0x0304); break; - case 0x8864: WRITE2(0x00ca, 0x030c); break; - case 0x88a3: WRITE2(0x00ea, 0x0304); break; - case 0x88a5: WRITE2(0x00ea, 0x030c); break; - default: return 2; - } - - NEXT(2, 2) /* all decoded codepoints are pairs, above. */ - } - } + while (inleft > 0) { + unsigned char c = IN1; + ucs4_t decoded; + + REQUIRE_OUTBUF(1) + + if (c < 0x80) { + OUT1(c) + NEXT(1, 1) + continue; + } + + REQUIRE_INBUF(2) + + if (0xc6 <= c && c <= 0xc8 && (c >= 0xc7 || IN2 >= 0xa1)) + goto hkscsdec; + + TRYMAP_DEC(big5, **outbuf, c, IN2) { + NEXT(2, 1) + } + else +hkscsdec: TRYMAP_DEC(big5hkscs, decoded, c, IN2) { + int s = BH2S(c, IN2); + const unsigned char *hintbase; + + assert(0x87 <= c && c <= 0xfe); + assert(0x40 <= IN2 && IN2 <= 0xfe); + + if (BH2S(0x87, 0x40) <= s && s <= BH2S(0xa0, 0xfe)) { + hintbase = big5hkscs_phint_0; + s -= BH2S(0x87, 0x40); + } + else if (BH2S(0xc6,0xa1) <= s && s <= BH2S(0xc8,0xfe)){ + hintbase = big5hkscs_phint_12130; + s -= BH2S(0xc6, 0xa1); + } + else if (BH2S(0xf9,0xd6) <= s && s <= BH2S(0xfe,0xfe)){ + hintbase = big5hkscs_phint_21924; + s -= BH2S(0xf9, 0xd6); + } + else + return MBERR_INTERNAL; + + if (hintbase[s >> 3] & (1 << (s & 7))) { + WRITEUCS4(decoded | 0x20000) + NEXT_IN(2) + } + else { + OUT1(decoded) + NEXT(2, 1) + } + } + else { + switch ((c << 8) | IN2) { + case 0x8862: WRITE2(0x00ca, 0x0304); break; + case 0x8864: WRITE2(0x00ca, 0x030c); break; + case 0x88a3: WRITE2(0x00ea, 0x0304); break; + case 0x88a5: WRITE2(0x00ea, 0x030c); break; + default: return 2; + } + + NEXT(2, 2) /* all decoded codepoints are pairs, above. */ + } + } - return 0; + return 0; } Modified: python/branches/py3k/Modules/cjkcodecs/_codecs_iso2022.c ============================================================================== --- python/branches/py3k/Modules/cjkcodecs/_codecs_iso2022.c (original) +++ python/branches/py3k/Modules/cjkcodecs/_codecs_iso2022.c Sun May 9 17:52:27 2010 @@ -19,85 +19,85 @@ state->c[0-3] - 00000000 - ||^^^^^| - |+-----+---- G0-3 Character Set - +----------- Is G0-3 double byte? + 00000000 + ||^^^^^| + |+-----+---- G0-3 Character Set + +----------- Is G0-3 double byte? state->c[4] - 00000000 - || - |+---- Locked-Shift? - +----- ESC Throughout + 00000000 + || + |+---- Locked-Shift? + +----- ESC Throughout */ -#define ESC 0x1B -#define SO 0x0E -#define SI 0x0F -#define LF 0x0A - -#define MAX_ESCSEQLEN 16 - -#define CHARSET_ISO8859_1 'A' -#define CHARSET_ASCII 'B' -#define CHARSET_ISO8859_7 'F' -#define CHARSET_JISX0201_K 'I' -#define CHARSET_JISX0201_R 'J' - -#define CHARSET_GB2312 ('A'|CHARSET_DBCS) -#define CHARSET_JISX0208 ('B'|CHARSET_DBCS) -#define CHARSET_KSX1001 ('C'|CHARSET_DBCS) -#define CHARSET_JISX0212 ('D'|CHARSET_DBCS) -#define CHARSET_GB2312_8565 ('E'|CHARSET_DBCS) -#define CHARSET_CNS11643_1 ('G'|CHARSET_DBCS) -#define CHARSET_CNS11643_2 ('H'|CHARSET_DBCS) -#define CHARSET_JISX0213_2000_1 ('O'|CHARSET_DBCS) -#define CHARSET_JISX0213_2 ('P'|CHARSET_DBCS) -#define CHARSET_JISX0213_2004_1 ('Q'|CHARSET_DBCS) -#define CHARSET_JISX0208_O ('@'|CHARSET_DBCS) +#define ESC 0x1B +#define SO 0x0E +#define SI 0x0F +#define LF 0x0A + +#define MAX_ESCSEQLEN 16 + +#define CHARSET_ISO8859_1 'A' +#define CHARSET_ASCII 'B' +#define CHARSET_ISO8859_7 'F' +#define CHARSET_JISX0201_K 'I' +#define CHARSET_JISX0201_R 'J' + +#define CHARSET_GB2312 ('A'|CHARSET_DBCS) +#define CHARSET_JISX0208 ('B'|CHARSET_DBCS) +#define CHARSET_KSX1001 ('C'|CHARSET_DBCS) +#define CHARSET_JISX0212 ('D'|CHARSET_DBCS) +#define CHARSET_GB2312_8565 ('E'|CHARSET_DBCS) +#define CHARSET_CNS11643_1 ('G'|CHARSET_DBCS) +#define CHARSET_CNS11643_2 ('H'|CHARSET_DBCS) +#define CHARSET_JISX0213_2000_1 ('O'|CHARSET_DBCS) +#define CHARSET_JISX0213_2 ('P'|CHARSET_DBCS) +#define CHARSET_JISX0213_2004_1 ('Q'|CHARSET_DBCS) +#define CHARSET_JISX0208_O ('@'|CHARSET_DBCS) -#define CHARSET_DBCS 0x80 -#define ESCMARK(mark) ((mark) & 0x7f) +#define CHARSET_DBCS 0x80 +#define ESCMARK(mark) ((mark) & 0x7f) -#define IS_ESCEND(c) (((c) >= 'A' && (c) <= 'Z') || (c) == '@') +#define IS_ESCEND(c) (((c) >= 'A' && (c) <= 'Z') || (c) == '@') #define IS_ISO2022ESC(c2) \ - ((c2) == '(' || (c2) == ')' || (c2) == '$' || \ - (c2) == '.' || (c2) == '&') - /* this is not a complete list of ISO-2022 escape sequence headers. - * but, it's enough to implement CJK instances of iso-2022. */ - -#define MAP_UNMAPPABLE 0xFFFF -#define MAP_MULTIPLE_AVAIL 0xFFFE /* for JIS X 0213 */ - -#define F_SHIFTED 0x01 -#define F_ESCTHROUGHOUT 0x02 - -#define STATE_SETG(dn, v) ((state)->c[dn]) = (v); -#define STATE_GETG(dn) ((state)->c[dn]) - -#define STATE_G0 STATE_GETG(0) -#define STATE_G1 STATE_GETG(1) -#define STATE_G2 STATE_GETG(2) -#define STATE_G3 STATE_GETG(3) -#define STATE_SETG0(v) STATE_SETG(0, v) -#define STATE_SETG1(v) STATE_SETG(1, v) -#define STATE_SETG2(v) STATE_SETG(2, v) -#define STATE_SETG3(v) STATE_SETG(3, v) - -#define STATE_SETFLAG(f) ((state)->c[4]) |= (f); -#define STATE_GETFLAG(f) ((state)->c[4] & (f)) -#define STATE_CLEARFLAG(f) ((state)->c[4]) &= ~(f); -#define STATE_CLEARFLAGS() ((state)->c[4]) = 0; - -#define ISO2022_CONFIG ((const struct iso2022_config *)config) -#define CONFIG_ISSET(flag) (ISO2022_CONFIG->flags & (flag)) -#define CONFIG_DESIGNATIONS (ISO2022_CONFIG->designations) + ((c2) == '(' || (c2) == ')' || (c2) == '$' || \ + (c2) == '.' || (c2) == '&') + /* this is not a complete list of ISO-2022 escape sequence headers. + * but, it's enough to implement CJK instances of iso-2022. */ + +#define MAP_UNMAPPABLE 0xFFFF +#define MAP_MULTIPLE_AVAIL 0xFFFE /* for JIS X 0213 */ + +#define F_SHIFTED 0x01 +#define F_ESCTHROUGHOUT 0x02 + +#define STATE_SETG(dn, v) ((state)->c[dn]) = (v); +#define STATE_GETG(dn) ((state)->c[dn]) + +#define STATE_G0 STATE_GETG(0) +#define STATE_G1 STATE_GETG(1) +#define STATE_G2 STATE_GETG(2) +#define STATE_G3 STATE_GETG(3) +#define STATE_SETG0(v) STATE_SETG(0, v) +#define STATE_SETG1(v) STATE_SETG(1, v) +#define STATE_SETG2(v) STATE_SETG(2, v) +#define STATE_SETG3(v) STATE_SETG(3, v) + +#define STATE_SETFLAG(f) ((state)->c[4]) |= (f); +#define STATE_GETFLAG(f) ((state)->c[4] & (f)) +#define STATE_CLEARFLAG(f) ((state)->c[4]) &= ~(f); +#define STATE_CLEARFLAGS() ((state)->c[4]) = 0; + +#define ISO2022_CONFIG ((const struct iso2022_config *)config) +#define CONFIG_ISSET(flag) (ISO2022_CONFIG->flags & (flag)) +#define CONFIG_DESIGNATIONS (ISO2022_CONFIG->designations) /* iso2022_config.flags */ -#define NO_SHIFT 0x01 -#define USE_G2 0x02 -#define USE_JISX0208_EXT 0x04 +#define NO_SHIFT 0x01 +#define USE_G2 0x02 +#define USE_JISX0208_EXT 0x04 /*-*- internal data structures -*-*/ @@ -106,434 +106,434 @@ typedef DBCHAR (*iso2022_encode_func)(const ucs4_t *data, Py_ssize_t *length); struct iso2022_designation { - unsigned char mark; - unsigned char plane; - unsigned char width; - iso2022_init_func initializer; - iso2022_decode_func decoder; - iso2022_encode_func encoder; + unsigned char mark; + unsigned char plane; + unsigned char width; + iso2022_init_func initializer; + iso2022_decode_func decoder; + iso2022_encode_func encoder; }; struct iso2022_config { - int flags; - const struct iso2022_designation *designations; /* non-ascii desigs */ + int flags; + const struct iso2022_designation *designations; /* non-ascii desigs */ }; /*-*- iso-2022 codec implementation -*-*/ CODEC_INIT(iso2022) { - const struct iso2022_designation *desig = CONFIG_DESIGNATIONS; - for (desig = CONFIG_DESIGNATIONS; desig->mark; desig++) - if (desig->initializer != NULL && desig->initializer() != 0) - return -1; - return 0; + const struct iso2022_designation *desig = CONFIG_DESIGNATIONS; + for (desig = CONFIG_DESIGNATIONS; desig->mark; desig++) + if (desig->initializer != NULL && desig->initializer() != 0) + return -1; + return 0; } ENCODER_INIT(iso2022) { - STATE_CLEARFLAGS() - STATE_SETG0(CHARSET_ASCII) - STATE_SETG1(CHARSET_ASCII) - return 0; + STATE_CLEARFLAGS() + STATE_SETG0(CHARSET_ASCII) + STATE_SETG1(CHARSET_ASCII) + return 0; } ENCODER_RESET(iso2022) { - if (STATE_GETFLAG(F_SHIFTED)) { - WRITE1(SI) - NEXT_OUT(1) - STATE_CLEARFLAG(F_SHIFTED) - } - if (STATE_G0 != CHARSET_ASCII) { - WRITE3(ESC, '(', 'B') - NEXT_OUT(3) - STATE_SETG0(CHARSET_ASCII) - } - return 0; + if (STATE_GETFLAG(F_SHIFTED)) { + WRITE1(SI) + NEXT_OUT(1) + STATE_CLEARFLAG(F_SHIFTED) + } + if (STATE_G0 != CHARSET_ASCII) { + WRITE3(ESC, '(', 'B') + NEXT_OUT(3) + STATE_SETG0(CHARSET_ASCII) + } + return 0; } ENCODER(iso2022) { - while (inleft > 0) { - const struct iso2022_designation *dsg; - DBCHAR encoded; - ucs4_t c = **inbuf; - Py_ssize_t insize; - - if (c < 0x80) { - if (STATE_G0 != CHARSET_ASCII) { - WRITE3(ESC, '(', 'B') - STATE_SETG0(CHARSET_ASCII) - NEXT_OUT(3) - } - if (STATE_GETFLAG(F_SHIFTED)) { - WRITE1(SI) - STATE_CLEARFLAG(F_SHIFTED) - NEXT_OUT(1) - } - WRITE1((unsigned char)c) - NEXT(1, 1) - continue; - } - - DECODE_SURROGATE(c) - insize = GET_INSIZE(c); - - encoded = MAP_UNMAPPABLE; - for (dsg = CONFIG_DESIGNATIONS; dsg->mark; dsg++) { - Py_ssize_t length = 1; - encoded = dsg->encoder(&c, &length); - if (encoded == MAP_MULTIPLE_AVAIL) { - /* this implementation won't work for pair - * of non-bmp characters. */ - if (inleft < 2) { - if (!(flags & MBENC_FLUSH)) - return MBERR_TOOFEW; - length = -1; - } - else - length = 2; + while (inleft > 0) { + const struct iso2022_designation *dsg; + DBCHAR encoded; + ucs4_t c = **inbuf; + Py_ssize_t insize; + + if (c < 0x80) { + if (STATE_G0 != CHARSET_ASCII) { + WRITE3(ESC, '(', 'B') + STATE_SETG0(CHARSET_ASCII) + NEXT_OUT(3) + } + if (STATE_GETFLAG(F_SHIFTED)) { + WRITE1(SI) + STATE_CLEARFLAG(F_SHIFTED) + NEXT_OUT(1) + } + WRITE1((unsigned char)c) + NEXT(1, 1) + continue; + } + + DECODE_SURROGATE(c) + insize = GET_INSIZE(c); + + encoded = MAP_UNMAPPABLE; + for (dsg = CONFIG_DESIGNATIONS; dsg->mark; dsg++) { + Py_ssize_t length = 1; + encoded = dsg->encoder(&c, &length); + if (encoded == MAP_MULTIPLE_AVAIL) { + /* this implementation won't work for pair + * of non-bmp characters. */ + if (inleft < 2) { + if (!(flags & MBENC_FLUSH)) + return MBERR_TOOFEW; + length = -1; + } + else + length = 2; #if Py_UNICODE_SIZE == 2 - if (length == 2) { - ucs4_t u4in[2]; - u4in[0] = (ucs4_t)IN1; - u4in[1] = (ucs4_t)IN2; - encoded = dsg->encoder(u4in, &length); - } else - encoded = dsg->encoder(&c, &length); + if (length == 2) { + ucs4_t u4in[2]; + u4in[0] = (ucs4_t)IN1; + u4in[1] = (ucs4_t)IN2; + encoded = dsg->encoder(u4in, &length); + } else + encoded = dsg->encoder(&c, &length); #else - encoded = dsg->encoder(&c, &length); + encoded = dsg->encoder(&c, &length); #endif - if (encoded != MAP_UNMAPPABLE) { - insize = length; - break; - } - } - else if (encoded != MAP_UNMAPPABLE) - break; - } - - if (!dsg->mark) - return 1; - assert(dsg->width == 1 || dsg->width == 2); - - switch (dsg->plane) { - case 0: /* G0 */ - if (STATE_GETFLAG(F_SHIFTED)) { - WRITE1(SI) - STATE_CLEARFLAG(F_SHIFTED) - NEXT_OUT(1) - } - if (STATE_G0 != dsg->mark) { - if (dsg->width == 1) { - WRITE3(ESC, '(', ESCMARK(dsg->mark)) - STATE_SETG0(dsg->mark) - NEXT_OUT(3) - } - else if (dsg->mark == CHARSET_JISX0208) { - WRITE3(ESC, '$', ESCMARK(dsg->mark)) - STATE_SETG0(dsg->mark) - NEXT_OUT(3) - } - else { - WRITE4(ESC, '$', '(', - ESCMARK(dsg->mark)) - STATE_SETG0(dsg->mark) - NEXT_OUT(4) - } - } - break; - case 1: /* G1 */ - if (STATE_G1 != dsg->mark) { - if (dsg->width == 1) { - WRITE3(ESC, ')', ESCMARK(dsg->mark)) - STATE_SETG1(dsg->mark) - NEXT_OUT(3) - } - else { - WRITE4(ESC, '$', ')', - ESCMARK(dsg->mark)) - STATE_SETG1(dsg->mark) - NEXT_OUT(4) - } - } - if (!STATE_GETFLAG(F_SHIFTED)) { - WRITE1(SO) - STATE_SETFLAG(F_SHIFTED) - NEXT_OUT(1) - } - break; - default: /* G2 and G3 is not supported: no encoding in - * CJKCodecs are using them yet */ - return MBERR_INTERNAL; - } - - if (dsg->width == 1) { - WRITE1((unsigned char)encoded) - NEXT_OUT(1) - } - else { - WRITE2(encoded >> 8, encoded & 0xff) - NEXT_OUT(2) - } - NEXT_IN(insize) - } + if (encoded != MAP_UNMAPPABLE) { + insize = length; + break; + } + } + else if (encoded != MAP_UNMAPPABLE) + break; + } + + if (!dsg->mark) + return 1; + assert(dsg->width == 1 || dsg->width == 2); + + switch (dsg->plane) { + case 0: /* G0 */ + if (STATE_GETFLAG(F_SHIFTED)) { + WRITE1(SI) + STATE_CLEARFLAG(F_SHIFTED) + NEXT_OUT(1) + } + if (STATE_G0 != dsg->mark) { + if (dsg->width == 1) { + WRITE3(ESC, '(', ESCMARK(dsg->mark)) + STATE_SETG0(dsg->mark) + NEXT_OUT(3) + } + else if (dsg->mark == CHARSET_JISX0208) { + WRITE3(ESC, '$', ESCMARK(dsg->mark)) + STATE_SETG0(dsg->mark) + NEXT_OUT(3) + } + else { + WRITE4(ESC, '$', '(', + ESCMARK(dsg->mark)) + STATE_SETG0(dsg->mark) + NEXT_OUT(4) + } + } + break; + case 1: /* G1 */ + if (STATE_G1 != dsg->mark) { + if (dsg->width == 1) { + WRITE3(ESC, ')', ESCMARK(dsg->mark)) + STATE_SETG1(dsg->mark) + NEXT_OUT(3) + } + else { + WRITE4(ESC, '$', ')', + ESCMARK(dsg->mark)) + STATE_SETG1(dsg->mark) + NEXT_OUT(4) + } + } + if (!STATE_GETFLAG(F_SHIFTED)) { + WRITE1(SO) + STATE_SETFLAG(F_SHIFTED) + NEXT_OUT(1) + } + break; + default: /* G2 and G3 is not supported: no encoding in + * CJKCodecs are using them yet */ + return MBERR_INTERNAL; + } + + if (dsg->width == 1) { + WRITE1((unsigned char)encoded) + NEXT_OUT(1) + } + else { + WRITE2(encoded >> 8, encoded & 0xff) + NEXT_OUT(2) + } + NEXT_IN(insize) + } - return 0; + return 0; } DECODER_INIT(iso2022) { - STATE_CLEARFLAGS() - STATE_SETG0(CHARSET_ASCII) - STATE_SETG1(CHARSET_ASCII) - STATE_SETG2(CHARSET_ASCII) - return 0; + STATE_CLEARFLAGS() + STATE_SETG0(CHARSET_ASCII) + STATE_SETG1(CHARSET_ASCII) + STATE_SETG2(CHARSET_ASCII) + return 0; } DECODER_RESET(iso2022) { - STATE_SETG0(CHARSET_ASCII) - STATE_CLEARFLAG(F_SHIFTED) - return 0; + STATE_SETG0(CHARSET_ASCII) + STATE_CLEARFLAG(F_SHIFTED) + return 0; } static Py_ssize_t iso2022processesc(const void *config, MultibyteCodec_State *state, - const unsigned char **inbuf, Py_ssize_t *inleft) + const unsigned char **inbuf, Py_ssize_t *inleft) { - unsigned char charset, designation; - Py_ssize_t i, esclen; + unsigned char charset, designation; + Py_ssize_t i, esclen; - for (i = 1;i < MAX_ESCSEQLEN;i++) { - if (i >= *inleft) - return MBERR_TOOFEW; - if (IS_ESCEND((*inbuf)[i])) { - esclen = i + 1; - break; - } - else if (CONFIG_ISSET(USE_JISX0208_EXT) && i+1 < *inleft && - (*inbuf)[i] == '&' && (*inbuf)[i+1] == '@') - i += 2; - } - - if (i >= MAX_ESCSEQLEN) - return 1; /* unterminated escape sequence */ - - switch (esclen) { - case 3: - if (IN2 == '$') { - charset = IN3 | CHARSET_DBCS; - designation = 0; - } - else { - charset = IN3; - if (IN2 == '(') designation = 0; - else if (IN2 == ')') designation = 1; - else if (CONFIG_ISSET(USE_G2) && IN2 == '.') - designation = 2; - else return 3; - } - break; - case 4: - if (IN2 != '$') - return 4; - - charset = IN4 | CHARSET_DBCS; - if (IN3 == '(') designation = 0; - else if (IN3 == ')') designation = 1; - else return 4; - break; - case 6: /* designation with prefix */ - if (CONFIG_ISSET(USE_JISX0208_EXT) && - (*inbuf)[3] == ESC && (*inbuf)[4] == '$' && - (*inbuf)[5] == 'B') { - charset = 'B' | CHARSET_DBCS; - designation = 0; - } - else - return 6; - break; - default: - return esclen; - } - - /* raise error when the charset is not designated for this encoding */ - if (charset != CHARSET_ASCII) { - const struct iso2022_designation *dsg; - - for (dsg = CONFIG_DESIGNATIONS; dsg->mark; dsg++) - if (dsg->mark == charset) - break; - if (!dsg->mark) - return esclen; - } - - STATE_SETG(designation, charset) - *inleft -= esclen; - (*inbuf) += esclen; - return 0; -} - -#define ISO8859_7_DECODE(c, assi) \ - if ((c) < 0xa0) (assi) = (c); \ - else if ((c) < 0xc0 && (0x288f3bc9L & (1L << ((c)-0xa0)))) \ - (assi) = (c); \ - else if ((c) >= 0xb4 && (c) <= 0xfe && ((c) >= 0xd4 || \ - (0xbffffd77L & (1L << ((c)-0xb4))))) \ - (assi) = 0x02d0 + (c); \ - else if ((c) == 0xa1) (assi) = 0x2018; \ - else if ((c) == 0xa2) (assi) = 0x2019; \ - else if ((c) == 0xaf) (assi) = 0x2015; + for (i = 1;i < MAX_ESCSEQLEN;i++) { + if (i >= *inleft) + return MBERR_TOOFEW; + if (IS_ESCEND((*inbuf)[i])) { + esclen = i + 1; + break; + } + else if (CONFIG_ISSET(USE_JISX0208_EXT) && i+1 < *inleft && + (*inbuf)[i] == '&' && (*inbuf)[i+1] == '@') + i += 2; + } + + if (i >= MAX_ESCSEQLEN) + return 1; /* unterminated escape sequence */ + + switch (esclen) { + case 3: + if (IN2 == '$') { + charset = IN3 | CHARSET_DBCS; + designation = 0; + } + else { + charset = IN3; + if (IN2 == '(') designation = 0; + else if (IN2 == ')') designation = 1; + else if (CONFIG_ISSET(USE_G2) && IN2 == '.') + designation = 2; + else return 3; + } + break; + case 4: + if (IN2 != '$') + return 4; + + charset = IN4 | CHARSET_DBCS; + if (IN3 == '(') designation = 0; + else if (IN3 == ')') designation = 1; + else return 4; + break; + case 6: /* designation with prefix */ + if (CONFIG_ISSET(USE_JISX0208_EXT) && + (*inbuf)[3] == ESC && (*inbuf)[4] == '$' && + (*inbuf)[5] == 'B') { + charset = 'B' | CHARSET_DBCS; + designation = 0; + } + else + return 6; + break; + default: + return esclen; + } + + /* raise error when the charset is not designated for this encoding */ + if (charset != CHARSET_ASCII) { + const struct iso2022_designation *dsg; + + for (dsg = CONFIG_DESIGNATIONS; dsg->mark; dsg++) + if (dsg->mark == charset) + break; + if (!dsg->mark) + return esclen; + } + + STATE_SETG(designation, charset) + *inleft -= esclen; + (*inbuf) += esclen; + return 0; +} + +#define ISO8859_7_DECODE(c, assi) \ + if ((c) < 0xa0) (assi) = (c); \ + else if ((c) < 0xc0 && (0x288f3bc9L & (1L << ((c)-0xa0)))) \ + (assi) = (c); \ + else if ((c) >= 0xb4 && (c) <= 0xfe && ((c) >= 0xd4 || \ + (0xbffffd77L & (1L << ((c)-0xb4))))) \ + (assi) = 0x02d0 + (c); \ + else if ((c) == 0xa1) (assi) = 0x2018; \ + else if ((c) == 0xa2) (assi) = 0x2019; \ + else if ((c) == 0xaf) (assi) = 0x2015; static Py_ssize_t iso2022processg2(const void *config, MultibyteCodec_State *state, - const unsigned char **inbuf, Py_ssize_t *inleft, - Py_UNICODE **outbuf, Py_ssize_t *outleft) + const unsigned char **inbuf, Py_ssize_t *inleft, + Py_UNICODE **outbuf, Py_ssize_t *outleft) { - /* not written to use encoder, decoder functions because only few - * encodings use G2 designations in CJKCodecs */ - if (STATE_G2 == CHARSET_ISO8859_1) { - if (IN3 < 0x80) - OUT1(IN3 + 0x80) - else - return 3; - } - else if (STATE_G2 == CHARSET_ISO8859_7) { - ISO8859_7_DECODE(IN3 ^ 0x80, **outbuf) - else return 3; - } - else if (STATE_G2 == CHARSET_ASCII) { - if (IN3 & 0x80) return 3; - else **outbuf = IN3; - } - else - return MBERR_INTERNAL; - - (*inbuf) += 3; - *inleft -= 3; - (*outbuf) += 1; - *outleft -= 1; - return 0; + /* not written to use encoder, decoder functions because only few + * encodings use G2 designations in CJKCodecs */ + if (STATE_G2 == CHARSET_ISO8859_1) { + if (IN3 < 0x80) + OUT1(IN3 + 0x80) + else + return 3; + } + else if (STATE_G2 == CHARSET_ISO8859_7) { + ISO8859_7_DECODE(IN3 ^ 0x80, **outbuf) + else return 3; + } + else if (STATE_G2 == CHARSET_ASCII) { + if (IN3 & 0x80) return 3; + else **outbuf = IN3; + } + else + return MBERR_INTERNAL; + + (*inbuf) += 3; + *inleft -= 3; + (*outbuf) += 1; + *outleft -= 1; + return 0; } DECODER(iso2022) { - const struct iso2022_designation *dsgcache = NULL; + const struct iso2022_designation *dsgcache = NULL; - while (inleft > 0) { - unsigned char c = IN1; - Py_ssize_t err; - - if (STATE_GETFLAG(F_ESCTHROUGHOUT)) { - /* ESC throughout mode: - * for non-iso2022 escape sequences */ - WRITE1(c) /* assume as ISO-8859-1 */ - NEXT(1, 1) - if (IS_ESCEND(c)) { - STATE_CLEARFLAG(F_ESCTHROUGHOUT) - } - continue; - } - - switch (c) { - case ESC: - REQUIRE_INBUF(2) - if (IS_ISO2022ESC(IN2)) { - err = iso2022processesc(config, state, - inbuf, &inleft); - if (err != 0) - return err; - } - else if (CONFIG_ISSET(USE_G2) && IN2 == 'N') {/* SS2 */ - REQUIRE_INBUF(3) - err = iso2022processg2(config, state, - inbuf, &inleft, outbuf, &outleft); - if (err != 0) - return err; - } - else { - WRITE1(ESC) - STATE_SETFLAG(F_ESCTHROUGHOUT) - NEXT(1, 1) - } - break; - case SI: - if (CONFIG_ISSET(NO_SHIFT)) - goto bypass; - STATE_CLEARFLAG(F_SHIFTED) - NEXT_IN(1) - break; - case SO: - if (CONFIG_ISSET(NO_SHIFT)) - goto bypass; - STATE_SETFLAG(F_SHIFTED) - NEXT_IN(1) - break; - case LF: - STATE_CLEARFLAG(F_SHIFTED) - WRITE1(LF) - NEXT(1, 1) - break; - default: - if (c < 0x20) /* C0 */ - goto bypass; - else if (c >= 0x80) - return 1; - else { - const struct iso2022_designation *dsg; - unsigned char charset; - ucs4_t decoded; - - if (STATE_GETFLAG(F_SHIFTED)) - charset = STATE_G1; - else - charset = STATE_G0; - - if (charset == CHARSET_ASCII) { -bypass: WRITE1(c) - NEXT(1, 1) - break; - } - - if (dsgcache != NULL && - dsgcache->mark == charset) - dsg = dsgcache; - else { - for (dsg = CONFIG_DESIGNATIONS; - dsg->mark != charset + while (inleft > 0) { + unsigned char c = IN1; + Py_ssize_t err; + + if (STATE_GETFLAG(F_ESCTHROUGHOUT)) { + /* ESC throughout mode: + * for non-iso2022 escape sequences */ + WRITE1(c) /* assume as ISO-8859-1 */ + NEXT(1, 1) + if (IS_ESCEND(c)) { + STATE_CLEARFLAG(F_ESCTHROUGHOUT) + } + continue; + } + + switch (c) { + case ESC: + REQUIRE_INBUF(2) + if (IS_ISO2022ESC(IN2)) { + err = iso2022processesc(config, state, + inbuf, &inleft); + if (err != 0) + return err; + } + else if (CONFIG_ISSET(USE_G2) && IN2 == 'N') {/* SS2 */ + REQUIRE_INBUF(3) + err = iso2022processg2(config, state, + inbuf, &inleft, outbuf, &outleft); + if (err != 0) + return err; + } + else { + WRITE1(ESC) + STATE_SETFLAG(F_ESCTHROUGHOUT) + NEXT(1, 1) + } + break; + case SI: + if (CONFIG_ISSET(NO_SHIFT)) + goto bypass; + STATE_CLEARFLAG(F_SHIFTED) + NEXT_IN(1) + break; + case SO: + if (CONFIG_ISSET(NO_SHIFT)) + goto bypass; + STATE_SETFLAG(F_SHIFTED) + NEXT_IN(1) + break; + case LF: + STATE_CLEARFLAG(F_SHIFTED) + WRITE1(LF) + NEXT(1, 1) + break; + default: + if (c < 0x20) /* C0 */ + goto bypass; + else if (c >= 0x80) + return 1; + else { + const struct iso2022_designation *dsg; + unsigned char charset; + ucs4_t decoded; + + if (STATE_GETFLAG(F_SHIFTED)) + charset = STATE_G1; + else + charset = STATE_G0; + + if (charset == CHARSET_ASCII) { +bypass: WRITE1(c) + NEXT(1, 1) + break; + } + + if (dsgcache != NULL && + dsgcache->mark == charset) + dsg = dsgcache; + else { + for (dsg = CONFIG_DESIGNATIONS; + dsg->mark != charset #ifdef Py_DEBUG - && dsg->mark != '\0' + && dsg->mark != '\0' #endif - ;dsg++) - /* noop */; - assert(dsg->mark != '\0'); - dsgcache = dsg; - } - - REQUIRE_INBUF(dsg->width) - decoded = dsg->decoder(*inbuf); - if (decoded == MAP_UNMAPPABLE) - return dsg->width; - - if (decoded < 0x10000) { - WRITE1(decoded) - NEXT_OUT(1) - } - else if (decoded < 0x30000) { - WRITEUCS4(decoded) - } - else { /* JIS X 0213 pairs */ - WRITE2(decoded >> 16, decoded & 0xffff) - NEXT_OUT(2) - } - NEXT_IN(dsg->width) - } - break; - } - } - return 0; + ;dsg++) + /* noop */; + assert(dsg->mark != '\0'); + dsgcache = dsg; + } + + REQUIRE_INBUF(dsg->width) + decoded = dsg->decoder(*inbuf); + if (decoded == MAP_UNMAPPABLE) + return dsg->width; + + if (decoded < 0x10000) { + WRITE1(decoded) + NEXT_OUT(1) + } + else if (decoded < 0x30000) { + WRITEUCS4(decoded) + } + else { /* JIS X 0213 pairs */ + WRITE2(decoded >> 16, decoded & 0xffff) + NEXT_OUT(2) + } + NEXT_IN(dsg->width) + } + break; + } + } + return 0; } /*-*- mapping table holders -*-*/ @@ -567,542 +567,542 @@ static int ksx1001_init(void) { - static int initialized = 0; + static int initialized = 0; - if (!initialized && ( - IMPORT_MAP(kr, cp949, &cp949_encmap, NULL) || - IMPORT_MAP(kr, ksx1001, NULL, &ksx1001_decmap))) - return -1; - initialized = 1; - return 0; + if (!initialized && ( + IMPORT_MAP(kr, cp949, &cp949_encmap, NULL) || + IMPORT_MAP(kr, ksx1001, NULL, &ksx1001_decmap))) + return -1; + initialized = 1; + return 0; } static ucs4_t ksx1001_decoder(const unsigned char *data) { - ucs4_t u; - TRYMAP_DEC(ksx1001, u, data[0], data[1]) - return u; - else - return MAP_UNMAPPABLE; + ucs4_t u; + TRYMAP_DEC(ksx1001, u, data[0], data[1]) + return u; + else + return MAP_UNMAPPABLE; } static DBCHAR ksx1001_encoder(const ucs4_t *data, Py_ssize_t *length) { - DBCHAR coded; - assert(*length == 1); - if (*data < 0x10000) { - TRYMAP_ENC(cp949, coded, *data) - if (!(coded & 0x8000)) - return coded; - } - return MAP_UNMAPPABLE; + DBCHAR coded; + assert(*length == 1); + if (*data < 0x10000) { + TRYMAP_ENC(cp949, coded, *data) + if (!(coded & 0x8000)) + return coded; + } + return MAP_UNMAPPABLE; } static int jisx0208_init(void) { - static int initialized = 0; + static int initialized = 0; - if (!initialized && ( - IMPORT_MAP(jp, jisxcommon, &jisxcommon_encmap, NULL) || - IMPORT_MAP(jp, jisx0208, NULL, &jisx0208_decmap))) - return -1; - initialized = 1; - return 0; + if (!initialized && ( + IMPORT_MAP(jp, jisxcommon, &jisxcommon_encmap, NULL) || + IMPORT_MAP(jp, jisx0208, NULL, &jisx0208_decmap))) + return -1; + initialized = 1; + return 0; } static ucs4_t jisx0208_decoder(const unsigned char *data) { - ucs4_t u; - if (data[0] == 0x21 && data[1] == 0x40) /* F/W REVERSE SOLIDUS */ - return 0xff3c; - else TRYMAP_DEC(jisx0208, u, data[0], data[1]) - return u; - else - return MAP_UNMAPPABLE; + ucs4_t u; + if (data[0] == 0x21 && data[1] == 0x40) /* F/W REVERSE SOLIDUS */ + return 0xff3c; + else TRYMAP_DEC(jisx0208, u, data[0], data[1]) + return u; + else + return MAP_UNMAPPABLE; } static DBCHAR jisx0208_encoder(const ucs4_t *data, Py_ssize_t *length) { - DBCHAR coded; - assert(*length == 1); - if (*data < 0x10000) { - if (*data == 0xff3c) /* F/W REVERSE SOLIDUS */ - return 0x2140; - else TRYMAP_ENC(jisxcommon, coded, *data) { - if (!(coded & 0x8000)) - return coded; - } - } - return MAP_UNMAPPABLE; + DBCHAR coded; + assert(*length == 1); + if (*data < 0x10000) { + if (*data == 0xff3c) /* F/W REVERSE SOLIDUS */ + return 0x2140; + else TRYMAP_ENC(jisxcommon, coded, *data) { + if (!(coded & 0x8000)) + return coded; + } + } + return MAP_UNMAPPABLE; } static int jisx0212_init(void) { - static int initialized = 0; + static int initialized = 0; - if (!initialized && ( - IMPORT_MAP(jp, jisxcommon, &jisxcommon_encmap, NULL) || - IMPORT_MAP(jp, jisx0212, NULL, &jisx0212_decmap))) - return -1; - initialized = 1; - return 0; + if (!initialized && ( + IMPORT_MAP(jp, jisxcommon, &jisxcommon_encmap, NULL) || + IMPORT_MAP(jp, jisx0212, NULL, &jisx0212_decmap))) + return -1; + initialized = 1; + return 0; } static ucs4_t jisx0212_decoder(const unsigned char *data) { - ucs4_t u; - TRYMAP_DEC(jisx0212, u, data[0], data[1]) - return u; - else - return MAP_UNMAPPABLE; + ucs4_t u; + TRYMAP_DEC(jisx0212, u, data[0], data[1]) + return u; + else + return MAP_UNMAPPABLE; } static DBCHAR jisx0212_encoder(const ucs4_t *data, Py_ssize_t *length) { - DBCHAR coded; - assert(*length == 1); - if (*data < 0x10000) { - TRYMAP_ENC(jisxcommon, coded, *data) { - if (coded & 0x8000) - return coded & 0x7fff; - } - } - return MAP_UNMAPPABLE; + DBCHAR coded; + assert(*length == 1); + if (*data < 0x10000) { + TRYMAP_ENC(jisxcommon, coded, *data) { + if (coded & 0x8000) + return coded & 0x7fff; + } + } + return MAP_UNMAPPABLE; } static int jisx0213_init(void) { - static int initialized = 0; + static int initialized = 0; - if (!initialized && ( - jisx0208_init() || - IMPORT_MAP(jp, jisx0213_bmp, - &jisx0213_bmp_encmap, NULL) || - IMPORT_MAP(jp, jisx0213_1_bmp, - NULL, &jisx0213_1_bmp_decmap) || - IMPORT_MAP(jp, jisx0213_2_bmp, - NULL, &jisx0213_2_bmp_decmap) || - IMPORT_MAP(jp, jisx0213_emp, - &jisx0213_emp_encmap, NULL) || - IMPORT_MAP(jp, jisx0213_1_emp, - NULL, &jisx0213_1_emp_decmap) || - IMPORT_MAP(jp, jisx0213_2_emp, - NULL, &jisx0213_2_emp_decmap) || - IMPORT_MAP(jp, jisx0213_pair, &jisx0213_pair_encmap, - &jisx0213_pair_decmap))) - return -1; - initialized = 1; - return 0; + if (!initialized && ( + jisx0208_init() || + IMPORT_MAP(jp, jisx0213_bmp, + &jisx0213_bmp_encmap, NULL) || + IMPORT_MAP(jp, jisx0213_1_bmp, + NULL, &jisx0213_1_bmp_decmap) || + IMPORT_MAP(jp, jisx0213_2_bmp, + NULL, &jisx0213_2_bmp_decmap) || + IMPORT_MAP(jp, jisx0213_emp, + &jisx0213_emp_encmap, NULL) || + IMPORT_MAP(jp, jisx0213_1_emp, + NULL, &jisx0213_1_emp_decmap) || + IMPORT_MAP(jp, jisx0213_2_emp, + NULL, &jisx0213_2_emp_decmap) || + IMPORT_MAP(jp, jisx0213_pair, &jisx0213_pair_encmap, + &jisx0213_pair_decmap))) + return -1; + initialized = 1; + return 0; } #define config ((void *)2000) static ucs4_t jisx0213_2000_1_decoder(const unsigned char *data) { - ucs4_t u; - EMULATE_JISX0213_2000_DECODE_PLANE1(u, data[0], data[1]) - else if (data[0] == 0x21 && data[1] == 0x40) /* F/W REVERSE SOLIDUS */ - return 0xff3c; - else TRYMAP_DEC(jisx0208, u, data[0], data[1]); - else TRYMAP_DEC(jisx0213_1_bmp, u, data[0], data[1]); - else TRYMAP_DEC(jisx0213_1_emp, u, data[0], data[1]) - u |= 0x20000; - else TRYMAP_DEC(jisx0213_pair, u, data[0], data[1]); - else - return MAP_UNMAPPABLE; - return u; + ucs4_t u; + EMULATE_JISX0213_2000_DECODE_PLANE1(u, data[0], data[1]) + else if (data[0] == 0x21 && data[1] == 0x40) /* F/W REVERSE SOLIDUS */ + return 0xff3c; + else TRYMAP_DEC(jisx0208, u, data[0], data[1]); + else TRYMAP_DEC(jisx0213_1_bmp, u, data[0], data[1]); + else TRYMAP_DEC(jisx0213_1_emp, u, data[0], data[1]) + u |= 0x20000; + else TRYMAP_DEC(jisx0213_pair, u, data[0], data[1]); + else + return MAP_UNMAPPABLE; + return u; } static ucs4_t jisx0213_2000_2_decoder(const unsigned char *data) { - ucs4_t u; - EMULATE_JISX0213_2000_DECODE_PLANE2(u, data[0], data[1]) - TRYMAP_DEC(jisx0213_2_bmp, u, data[0], data[1]); - else TRYMAP_DEC(jisx0213_2_emp, u, data[0], data[1]) - u |= 0x20000; - else - return MAP_UNMAPPABLE; - return u; + ucs4_t u; + EMULATE_JISX0213_2000_DECODE_PLANE2(u, data[0], data[1]) + TRYMAP_DEC(jisx0213_2_bmp, u, data[0], data[1]); + else TRYMAP_DEC(jisx0213_2_emp, u, data[0], data[1]) + u |= 0x20000; + else + return MAP_UNMAPPABLE; + return u; } #undef config static ucs4_t jisx0213_2004_1_decoder(const unsigned char *data) { - ucs4_t u; - if (data[0] == 0x21 && data[1] == 0x40) /* F/W REVERSE SOLIDUS */ - return 0xff3c; - else TRYMAP_DEC(jisx0208, u, data[0], data[1]); - else TRYMAP_DEC(jisx0213_1_bmp, u, data[0], data[1]); - else TRYMAP_DEC(jisx0213_1_emp, u, data[0], data[1]) - u |= 0x20000; - else TRYMAP_DEC(jisx0213_pair, u, data[0], data[1]); - else - return MAP_UNMAPPABLE; - return u; + ucs4_t u; + if (data[0] == 0x21 && data[1] == 0x40) /* F/W REVERSE SOLIDUS */ + return 0xff3c; + else TRYMAP_DEC(jisx0208, u, data[0], data[1]); + else TRYMAP_DEC(jisx0213_1_bmp, u, data[0], data[1]); + else TRYMAP_DEC(jisx0213_1_emp, u, data[0], data[1]) + u |= 0x20000; + else TRYMAP_DEC(jisx0213_pair, u, data[0], data[1]); + else + return MAP_UNMAPPABLE; + return u; } static ucs4_t jisx0213_2004_2_decoder(const unsigned char *data) { - ucs4_t u; - TRYMAP_DEC(jisx0213_2_bmp, u, data[0], data[1]); - else TRYMAP_DEC(jisx0213_2_emp, u, data[0], data[1]) - u |= 0x20000; - else - return MAP_UNMAPPABLE; - return u; + ucs4_t u; + TRYMAP_DEC(jisx0213_2_bmp, u, data[0], data[1]); + else TRYMAP_DEC(jisx0213_2_emp, u, data[0], data[1]) + u |= 0x20000; + else + return MAP_UNMAPPABLE; + return u; } static DBCHAR jisx0213_encoder(const ucs4_t *data, Py_ssize_t *length, void *config) { - DBCHAR coded; + DBCHAR coded; - switch (*length) { - case 1: /* first character */ - if (*data >= 0x10000) { - if ((*data) >> 16 == 0x20000 >> 16) { - EMULATE_JISX0213_2000_ENCODE_EMP(coded, *data) - else TRYMAP_ENC(jisx0213_emp, coded, - (*data) & 0xffff) - return coded; - } - return MAP_UNMAPPABLE; - } - - EMULATE_JISX0213_2000_ENCODE_BMP(coded, *data) - else TRYMAP_ENC(jisx0213_bmp, coded, *data) { - if (coded == MULTIC) - return MAP_MULTIPLE_AVAIL; - } - else TRYMAP_ENC(jisxcommon, coded, *data) { - if (coded & 0x8000) - return MAP_UNMAPPABLE; - } - else - return MAP_UNMAPPABLE; - return coded; - case 2: /* second character of unicode pair */ - coded = find_pairencmap((ucs2_t)data[0], (ucs2_t)data[1], - jisx0213_pair_encmap, JISX0213_ENCPAIRS); - if (coded == DBCINV) { - *length = 1; - coded = find_pairencmap((ucs2_t)data[0], 0, - jisx0213_pair_encmap, JISX0213_ENCPAIRS); - if (coded == DBCINV) - return MAP_UNMAPPABLE; - } - else - return coded; - case -1: /* flush unterminated */ - *length = 1; - coded = find_pairencmap((ucs2_t)data[0], 0, - jisx0213_pair_encmap, JISX0213_ENCPAIRS); - if (coded == DBCINV) - return MAP_UNMAPPABLE; - else - return coded; - default: - return MAP_UNMAPPABLE; - } + switch (*length) { + case 1: /* first character */ + if (*data >= 0x10000) { + if ((*data) >> 16 == 0x20000 >> 16) { + EMULATE_JISX0213_2000_ENCODE_EMP(coded, *data) + else TRYMAP_ENC(jisx0213_emp, coded, + (*data) & 0xffff) + return coded; + } + return MAP_UNMAPPABLE; + } + + EMULATE_JISX0213_2000_ENCODE_BMP(coded, *data) + else TRYMAP_ENC(jisx0213_bmp, coded, *data) { + if (coded == MULTIC) + return MAP_MULTIPLE_AVAIL; + } + else TRYMAP_ENC(jisxcommon, coded, *data) { + if (coded & 0x8000) + return MAP_UNMAPPABLE; + } + else + return MAP_UNMAPPABLE; + return coded; + case 2: /* second character of unicode pair */ + coded = find_pairencmap((ucs2_t)data[0], (ucs2_t)data[1], + jisx0213_pair_encmap, JISX0213_ENCPAIRS); + if (coded == DBCINV) { + *length = 1; + coded = find_pairencmap((ucs2_t)data[0], 0, + jisx0213_pair_encmap, JISX0213_ENCPAIRS); + if (coded == DBCINV) + return MAP_UNMAPPABLE; + } + else + return coded; + case -1: /* flush unterminated */ + *length = 1; + coded = find_pairencmap((ucs2_t)data[0], 0, + jisx0213_pair_encmap, JISX0213_ENCPAIRS); + if (coded == DBCINV) + return MAP_UNMAPPABLE; + else + return coded; + default: + return MAP_UNMAPPABLE; + } } static DBCHAR jisx0213_2000_1_encoder(const ucs4_t *data, Py_ssize_t *length) { - DBCHAR coded = jisx0213_encoder(data, length, (void *)2000); - if (coded == MAP_UNMAPPABLE || coded == MAP_MULTIPLE_AVAIL) - return coded; - else if (coded & 0x8000) - return MAP_UNMAPPABLE; - else - return coded; + DBCHAR coded = jisx0213_encoder(data, length, (void *)2000); + if (coded == MAP_UNMAPPABLE || coded == MAP_MULTIPLE_AVAIL) + return coded; + else if (coded & 0x8000) + return MAP_UNMAPPABLE; + else + return coded; } static DBCHAR jisx0213_2000_1_encoder_paironly(const ucs4_t *data, Py_ssize_t *length) { - DBCHAR coded; - Py_ssize_t ilength = *length; + DBCHAR coded; + Py_ssize_t ilength = *length; - coded = jisx0213_encoder(data, length, (void *)2000); - switch (ilength) { - case 1: - if (coded == MAP_MULTIPLE_AVAIL) - return MAP_MULTIPLE_AVAIL; - else - return MAP_UNMAPPABLE; - case 2: - if (*length != 2) - return MAP_UNMAPPABLE; - else - return coded; - default: - return MAP_UNMAPPABLE; - } + coded = jisx0213_encoder(data, length, (void *)2000); + switch (ilength) { + case 1: + if (coded == MAP_MULTIPLE_AVAIL) + return MAP_MULTIPLE_AVAIL; + else + return MAP_UNMAPPABLE; + case 2: + if (*length != 2) + return MAP_UNMAPPABLE; + else + return coded; + default: + return MAP_UNMAPPABLE; + } } static DBCHAR jisx0213_2000_2_encoder(const ucs4_t *data, Py_ssize_t *length) { - DBCHAR coded = jisx0213_encoder(data, length, (void *)2000); - if (coded == MAP_UNMAPPABLE || coded == MAP_MULTIPLE_AVAIL) - return coded; - else if (coded & 0x8000) - return coded & 0x7fff; - else - return MAP_UNMAPPABLE; + DBCHAR coded = jisx0213_encoder(data, length, (void *)2000); + if (coded == MAP_UNMAPPABLE || coded == MAP_MULTIPLE_AVAIL) + return coded; + else if (coded & 0x8000) + return coded & 0x7fff; + else + return MAP_UNMAPPABLE; } static DBCHAR jisx0213_2004_1_encoder(const ucs4_t *data, Py_ssize_t *length) { - DBCHAR coded = jisx0213_encoder(data, length, NULL); - if (coded == MAP_UNMAPPABLE || coded == MAP_MULTIPLE_AVAIL) - return coded; - else if (coded & 0x8000) - return MAP_UNMAPPABLE; - else - return coded; + DBCHAR coded = jisx0213_encoder(data, length, NULL); + if (coded == MAP_UNMAPPABLE || coded == MAP_MULTIPLE_AVAIL) + return coded; + else if (coded & 0x8000) + return MAP_UNMAPPABLE; + else + return coded; } static DBCHAR jisx0213_2004_1_encoder_paironly(const ucs4_t *data, Py_ssize_t *length) { - DBCHAR coded; - Py_ssize_t ilength = *length; + DBCHAR coded; + Py_ssize_t ilength = *length; - coded = jisx0213_encoder(data, length, NULL); - switch (ilength) { - case 1: - if (coded == MAP_MULTIPLE_AVAIL) - return MAP_MULTIPLE_AVAIL; - else - return MAP_UNMAPPABLE; - case 2: - if (*length != 2) - return MAP_UNMAPPABLE; - else - return coded; - default: - return MAP_UNMAPPABLE; - } + coded = jisx0213_encoder(data, length, NULL); + switch (ilength) { + case 1: + if (coded == MAP_MULTIPLE_AVAIL) + return MAP_MULTIPLE_AVAIL; + else + return MAP_UNMAPPABLE; + case 2: + if (*length != 2) + return MAP_UNMAPPABLE; + else + return coded; + default: + return MAP_UNMAPPABLE; + } } static DBCHAR jisx0213_2004_2_encoder(const ucs4_t *data, Py_ssize_t *length) { - DBCHAR coded = jisx0213_encoder(data, length, NULL); - if (coded == MAP_UNMAPPABLE || coded == MAP_MULTIPLE_AVAIL) - return coded; - else if (coded & 0x8000) - return coded & 0x7fff; - else - return MAP_UNMAPPABLE; + DBCHAR coded = jisx0213_encoder(data, length, NULL); + if (coded == MAP_UNMAPPABLE || coded == MAP_MULTIPLE_AVAIL) + return coded; + else if (coded & 0x8000) + return coded & 0x7fff; + else + return MAP_UNMAPPABLE; } static ucs4_t jisx0201_r_decoder(const unsigned char *data) { - ucs4_t u; - JISX0201_R_DECODE(*data, u) - else return MAP_UNMAPPABLE; - return u; + ucs4_t u; + JISX0201_R_DECODE(*data, u) + else return MAP_UNMAPPABLE; + return u; } static DBCHAR jisx0201_r_encoder(const ucs4_t *data, Py_ssize_t *length) { - DBCHAR coded; - JISX0201_R_ENCODE(*data, coded) - else return MAP_UNMAPPABLE; - return coded; + DBCHAR coded; + JISX0201_R_ENCODE(*data, coded) + else return MAP_UNMAPPABLE; + return coded; } static ucs4_t jisx0201_k_decoder(const unsigned char *data) { - ucs4_t u; - JISX0201_K_DECODE(*data ^ 0x80, u) - else return MAP_UNMAPPABLE; - return u; + ucs4_t u; + JISX0201_K_DECODE(*data ^ 0x80, u) + else return MAP_UNMAPPABLE; + return u; } static DBCHAR jisx0201_k_encoder(const ucs4_t *data, Py_ssize_t *length) { - DBCHAR coded; - JISX0201_K_ENCODE(*data, coded) - else return MAP_UNMAPPABLE; - return coded - 0x80; + DBCHAR coded; + JISX0201_K_ENCODE(*data, coded) + else return MAP_UNMAPPABLE; + return coded - 0x80; } static int gb2312_init(void) { - static int initialized = 0; + static int initialized = 0; - if (!initialized && ( - IMPORT_MAP(cn, gbcommon, &gbcommon_encmap, NULL) || - IMPORT_MAP(cn, gb2312, NULL, &gb2312_decmap))) - return -1; - initialized = 1; - return 0; + if (!initialized && ( + IMPORT_MAP(cn, gbcommon, &gbcommon_encmap, NULL) || + IMPORT_MAP(cn, gb2312, NULL, &gb2312_decmap))) + return -1; + initialized = 1; + return 0; } static ucs4_t gb2312_decoder(const unsigned char *data) { - ucs4_t u; - TRYMAP_DEC(gb2312, u, data[0], data[1]) - return u; - else - return MAP_UNMAPPABLE; + ucs4_t u; + TRYMAP_DEC(gb2312, u, data[0], data[1]) + return u; + else + return MAP_UNMAPPABLE; } static DBCHAR gb2312_encoder(const ucs4_t *data, Py_ssize_t *length) { - DBCHAR coded; - assert(*length == 1); - if (*data < 0x10000) { - TRYMAP_ENC(gbcommon, coded, *data) { - if (!(coded & 0x8000)) - return coded; - } - } - return MAP_UNMAPPABLE; + DBCHAR coded; + assert(*length == 1); + if (*data < 0x10000) { + TRYMAP_ENC(gbcommon, coded, *data) { + if (!(coded & 0x8000)) + return coded; + } + } + return MAP_UNMAPPABLE; } static ucs4_t dummy_decoder(const unsigned char *data) { - return MAP_UNMAPPABLE; + return MAP_UNMAPPABLE; } static DBCHAR dummy_encoder(const ucs4_t *data, Py_ssize_t *length) { - return MAP_UNMAPPABLE; + return MAP_UNMAPPABLE; } /*-*- registry tables -*-*/ -#define REGISTRY_KSX1001_G0 { CHARSET_KSX1001, 0, 2, \ - ksx1001_init, \ - ksx1001_decoder, ksx1001_encoder } -#define REGISTRY_KSX1001_G1 { CHARSET_KSX1001, 1, 2, \ - ksx1001_init, \ - ksx1001_decoder, ksx1001_encoder } -#define REGISTRY_JISX0201_R { CHARSET_JISX0201_R, 0, 1, \ - NULL, \ - jisx0201_r_decoder, jisx0201_r_encoder } -#define REGISTRY_JISX0201_K { CHARSET_JISX0201_K, 0, 1, \ - NULL, \ - jisx0201_k_decoder, jisx0201_k_encoder } -#define REGISTRY_JISX0208 { CHARSET_JISX0208, 0, 2, \ - jisx0208_init, \ - jisx0208_decoder, jisx0208_encoder } -#define REGISTRY_JISX0208_O { CHARSET_JISX0208_O, 0, 2, \ - jisx0208_init, \ - jisx0208_decoder, jisx0208_encoder } -#define REGISTRY_JISX0212 { CHARSET_JISX0212, 0, 2, \ - jisx0212_init, \ - jisx0212_decoder, jisx0212_encoder } -#define REGISTRY_JISX0213_2000_1 { CHARSET_JISX0213_2000_1, 0, 2, \ - jisx0213_init, \ - jisx0213_2000_1_decoder, \ - jisx0213_2000_1_encoder } +#define REGISTRY_KSX1001_G0 { CHARSET_KSX1001, 0, 2, \ + ksx1001_init, \ + ksx1001_decoder, ksx1001_encoder } +#define REGISTRY_KSX1001_G1 { CHARSET_KSX1001, 1, 2, \ + ksx1001_init, \ + ksx1001_decoder, ksx1001_encoder } +#define REGISTRY_JISX0201_R { CHARSET_JISX0201_R, 0, 1, \ + NULL, \ + jisx0201_r_decoder, jisx0201_r_encoder } +#define REGISTRY_JISX0201_K { CHARSET_JISX0201_K, 0, 1, \ + NULL, \ + jisx0201_k_decoder, jisx0201_k_encoder } +#define REGISTRY_JISX0208 { CHARSET_JISX0208, 0, 2, \ + jisx0208_init, \ + jisx0208_decoder, jisx0208_encoder } +#define REGISTRY_JISX0208_O { CHARSET_JISX0208_O, 0, 2, \ + jisx0208_init, \ + jisx0208_decoder, jisx0208_encoder } +#define REGISTRY_JISX0212 { CHARSET_JISX0212, 0, 2, \ + jisx0212_init, \ + jisx0212_decoder, jisx0212_encoder } +#define REGISTRY_JISX0213_2000_1 { CHARSET_JISX0213_2000_1, 0, 2, \ + jisx0213_init, \ + jisx0213_2000_1_decoder, \ + jisx0213_2000_1_encoder } #define REGISTRY_JISX0213_2000_1_PAIRONLY { CHARSET_JISX0213_2000_1, 0, 2, \ - jisx0213_init, \ - jisx0213_2000_1_decoder, \ - jisx0213_2000_1_encoder_paironly } -#define REGISTRY_JISX0213_2000_2 { CHARSET_JISX0213_2, 0, 2, \ - jisx0213_init, \ - jisx0213_2000_2_decoder, \ - jisx0213_2000_2_encoder } -#define REGISTRY_JISX0213_2004_1 { CHARSET_JISX0213_2004_1, 0, 2, \ - jisx0213_init, \ - jisx0213_2004_1_decoder, \ - jisx0213_2004_1_encoder } + jisx0213_init, \ + jisx0213_2000_1_decoder, \ + jisx0213_2000_1_encoder_paironly } +#define REGISTRY_JISX0213_2000_2 { CHARSET_JISX0213_2, 0, 2, \ + jisx0213_init, \ + jisx0213_2000_2_decoder, \ + jisx0213_2000_2_encoder } +#define REGISTRY_JISX0213_2004_1 { CHARSET_JISX0213_2004_1, 0, 2, \ + jisx0213_init, \ + jisx0213_2004_1_decoder, \ + jisx0213_2004_1_encoder } #define REGISTRY_JISX0213_2004_1_PAIRONLY { CHARSET_JISX0213_2004_1, 0, 2, \ - jisx0213_init, \ - jisx0213_2004_1_decoder, \ - jisx0213_2004_1_encoder_paironly } -#define REGISTRY_JISX0213_2004_2 { CHARSET_JISX0213_2, 0, 2, \ - jisx0213_init, \ - jisx0213_2004_2_decoder, \ - jisx0213_2004_2_encoder } -#define REGISTRY_GB2312 { CHARSET_GB2312, 0, 2, \ - gb2312_init, \ - gb2312_decoder, gb2312_encoder } -#define REGISTRY_CNS11643_1 { CHARSET_CNS11643_1, 1, 2, \ - cns11643_init, \ - cns11643_1_decoder, cns11643_1_encoder } -#define REGISTRY_CNS11643_2 { CHARSET_CNS11643_2, 2, 2, \ - cns11643_init, \ - cns11643_2_decoder, cns11643_2_encoder } -#define REGISTRY_ISO8859_1 { CHARSET_ISO8859_1, 2, 1, \ - NULL, dummy_decoder, dummy_encoder } -#define REGISTRY_ISO8859_7 { CHARSET_ISO8859_7, 2, 1, \ - NULL, dummy_decoder, dummy_encoder } -#define REGISTRY_SENTINEL { 0, } -#define CONFIGDEF(var, attrs) \ - static const struct iso2022_config iso2022_##var##_config = { \ - attrs, iso2022_##var##_designations \ - }; + jisx0213_init, \ + jisx0213_2004_1_decoder, \ + jisx0213_2004_1_encoder_paironly } +#define REGISTRY_JISX0213_2004_2 { CHARSET_JISX0213_2, 0, 2, \ + jisx0213_init, \ + jisx0213_2004_2_decoder, \ + jisx0213_2004_2_encoder } +#define REGISTRY_GB2312 { CHARSET_GB2312, 0, 2, \ + gb2312_init, \ + gb2312_decoder, gb2312_encoder } +#define REGISTRY_CNS11643_1 { CHARSET_CNS11643_1, 1, 2, \ + cns11643_init, \ + cns11643_1_decoder, cns11643_1_encoder } +#define REGISTRY_CNS11643_2 { CHARSET_CNS11643_2, 2, 2, \ + cns11643_init, \ + cns11643_2_decoder, cns11643_2_encoder } +#define REGISTRY_ISO8859_1 { CHARSET_ISO8859_1, 2, 1, \ + NULL, dummy_decoder, dummy_encoder } +#define REGISTRY_ISO8859_7 { CHARSET_ISO8859_7, 2, 1, \ + NULL, dummy_decoder, dummy_encoder } +#define REGISTRY_SENTINEL { 0, } +#define CONFIGDEF(var, attrs) \ + static const struct iso2022_config iso2022_##var##_config = { \ + attrs, iso2022_##var##_designations \ + }; static const struct iso2022_designation iso2022_kr_designations[] = { - REGISTRY_KSX1001_G1, REGISTRY_SENTINEL + REGISTRY_KSX1001_G1, REGISTRY_SENTINEL }; CONFIGDEF(kr, 0) static const struct iso2022_designation iso2022_jp_designations[] = { - REGISTRY_JISX0208, REGISTRY_JISX0201_R, REGISTRY_JISX0208_O, - REGISTRY_SENTINEL + REGISTRY_JISX0208, REGISTRY_JISX0201_R, REGISTRY_JISX0208_O, + REGISTRY_SENTINEL }; CONFIGDEF(jp, NO_SHIFT | USE_JISX0208_EXT) static const struct iso2022_designation iso2022_jp_1_designations[] = { - REGISTRY_JISX0208, REGISTRY_JISX0212, REGISTRY_JISX0201_R, - REGISTRY_JISX0208_O, REGISTRY_SENTINEL + REGISTRY_JISX0208, REGISTRY_JISX0212, REGISTRY_JISX0201_R, + REGISTRY_JISX0208_O, REGISTRY_SENTINEL }; CONFIGDEF(jp_1, NO_SHIFT | USE_JISX0208_EXT) static const struct iso2022_designation iso2022_jp_2_designations[] = { - REGISTRY_JISX0208, REGISTRY_JISX0212, REGISTRY_KSX1001_G0, - REGISTRY_GB2312, REGISTRY_JISX0201_R, REGISTRY_JISX0208_O, - REGISTRY_ISO8859_1, REGISTRY_ISO8859_7, REGISTRY_SENTINEL + REGISTRY_JISX0208, REGISTRY_JISX0212, REGISTRY_KSX1001_G0, + REGISTRY_GB2312, REGISTRY_JISX0201_R, REGISTRY_JISX0208_O, + REGISTRY_ISO8859_1, REGISTRY_ISO8859_7, REGISTRY_SENTINEL }; CONFIGDEF(jp_2, NO_SHIFT | USE_G2 | USE_JISX0208_EXT) static const struct iso2022_designation iso2022_jp_2004_designations[] = { - REGISTRY_JISX0213_2004_1_PAIRONLY, REGISTRY_JISX0208, - REGISTRY_JISX0213_2004_1, REGISTRY_JISX0213_2004_2, REGISTRY_SENTINEL + REGISTRY_JISX0213_2004_1_PAIRONLY, REGISTRY_JISX0208, + REGISTRY_JISX0213_2004_1, REGISTRY_JISX0213_2004_2, REGISTRY_SENTINEL }; CONFIGDEF(jp_2004, NO_SHIFT | USE_JISX0208_EXT) static const struct iso2022_designation iso2022_jp_3_designations[] = { - REGISTRY_JISX0213_2000_1_PAIRONLY, REGISTRY_JISX0208, - REGISTRY_JISX0213_2000_1, REGISTRY_JISX0213_2000_2, REGISTRY_SENTINEL + REGISTRY_JISX0213_2000_1_PAIRONLY, REGISTRY_JISX0208, + REGISTRY_JISX0213_2000_1, REGISTRY_JISX0213_2000_2, REGISTRY_SENTINEL }; CONFIGDEF(jp_3, NO_SHIFT | USE_JISX0208_EXT) static const struct iso2022_designation iso2022_jp_ext_designations[] = { - REGISTRY_JISX0208, REGISTRY_JISX0212, REGISTRY_JISX0201_R, - REGISTRY_JISX0201_K, REGISTRY_JISX0208_O, REGISTRY_SENTINEL + REGISTRY_JISX0208, REGISTRY_JISX0212, REGISTRY_JISX0201_R, + REGISTRY_JISX0201_K, REGISTRY_JISX0208_O, REGISTRY_SENTINEL }; CONFIGDEF(jp_ext, NO_SHIFT | USE_JISX0208_EXT) @@ -1111,11 +1111,11 @@ /* no mapping table here */ END_MAPPINGS_LIST -#define ISO2022_CODEC(variation) { \ - "iso2022_" #variation, \ - &iso2022_##variation##_config, \ - iso2022_codec_init, \ - _STATEFUL_METHODS(iso2022) \ +#define ISO2022_CODEC(variation) { \ + "iso2022_" #variation, \ + &iso2022_##variation##_config, \ + iso2022_codec_init, \ + _STATEFUL_METHODS(iso2022) \ }, BEGIN_CODECS_LIST Modified: python/branches/py3k/Modules/cjkcodecs/_codecs_jp.c ============================================================================== --- python/branches/py3k/Modules/cjkcodecs/_codecs_jp.c (original) +++ python/branches/py3k/Modules/cjkcodecs/_codecs_jp.c Sun May 9 17:52:27 2010 @@ -19,124 +19,124 @@ ENCODER(cp932) { - while (inleft > 0) { - Py_UNICODE c = IN1; - DBCHAR code; - unsigned char c1, c2; - - if (c <= 0x80) { - WRITE1((unsigned char)c) - NEXT(1, 1) - continue; - } - else if (c >= 0xff61 && c <= 0xff9f) { - WRITE1(c - 0xfec0) - NEXT(1, 1) - continue; - } - else if (c >= 0xf8f0 && c <= 0xf8f3) { - /* Windows compatibility */ - REQUIRE_OUTBUF(1) - if (c == 0xf8f0) - OUT1(0xa0) - else - OUT1(c - 0xfef1 + 0xfd) - NEXT(1, 1) - continue; - } - - UCS4INVALID(c) - REQUIRE_OUTBUF(2) - - TRYMAP_ENC(cp932ext, code, c) { - OUT1(code >> 8) - OUT2(code & 0xff) - } - else TRYMAP_ENC(jisxcommon, code, c) { - if (code & 0x8000) /* MSB set: JIS X 0212 */ - return 1; - - /* JIS X 0208 */ - c1 = code >> 8; - c2 = code & 0xff; - c2 = (((c1 - 0x21) & 1) ? 0x5e : 0) + (c2 - 0x21); - c1 = (c1 - 0x21) >> 1; - OUT1(c1 < 0x1f ? c1 + 0x81 : c1 + 0xc1) - OUT2(c2 < 0x3f ? c2 + 0x40 : c2 + 0x41) - } - else if (c >= 0xe000 && c < 0xe758) { - /* User-defined area */ - c1 = (Py_UNICODE)(c - 0xe000) / 188; - c2 = (Py_UNICODE)(c - 0xe000) % 188; - OUT1(c1 + 0xf0) - OUT2(c2 < 0x3f ? c2 + 0x40 : c2 + 0x41) - } - else - return 1; + while (inleft > 0) { + Py_UNICODE c = IN1; + DBCHAR code; + unsigned char c1, c2; + + if (c <= 0x80) { + WRITE1((unsigned char)c) + NEXT(1, 1) + continue; + } + else if (c >= 0xff61 && c <= 0xff9f) { + WRITE1(c - 0xfec0) + NEXT(1, 1) + continue; + } + else if (c >= 0xf8f0 && c <= 0xf8f3) { + /* Windows compatibility */ + REQUIRE_OUTBUF(1) + if (c == 0xf8f0) + OUT1(0xa0) + else + OUT1(c - 0xfef1 + 0xfd) + NEXT(1, 1) + continue; + } + + UCS4INVALID(c) + REQUIRE_OUTBUF(2) + + TRYMAP_ENC(cp932ext, code, c) { + OUT1(code >> 8) + OUT2(code & 0xff) + } + else TRYMAP_ENC(jisxcommon, code, c) { + if (code & 0x8000) /* MSB set: JIS X 0212 */ + return 1; + + /* JIS X 0208 */ + c1 = code >> 8; + c2 = code & 0xff; + c2 = (((c1 - 0x21) & 1) ? 0x5e : 0) + (c2 - 0x21); + c1 = (c1 - 0x21) >> 1; + OUT1(c1 < 0x1f ? c1 + 0x81 : c1 + 0xc1) + OUT2(c2 < 0x3f ? c2 + 0x40 : c2 + 0x41) + } + else if (c >= 0xe000 && c < 0xe758) { + /* User-defined area */ + c1 = (Py_UNICODE)(c - 0xe000) / 188; + c2 = (Py_UNICODE)(c - 0xe000) % 188; + OUT1(c1 + 0xf0) + OUT2(c2 < 0x3f ? c2 + 0x40 : c2 + 0x41) + } + else + return 1; - NEXT(1, 2) - } + NEXT(1, 2) + } - return 0; + return 0; } DECODER(cp932) { - while (inleft > 0) { - unsigned char c = IN1, c2; + while (inleft > 0) { + unsigned char c = IN1, c2; - REQUIRE_OUTBUF(1) - if (c <= 0x80) { - OUT1(c) - NEXT(1, 1) - continue; - } - else if (c >= 0xa0 && c <= 0xdf) { - if (c == 0xa0) - OUT1(0xf8f0) /* half-width katakana */ - else - OUT1(0xfec0 + c) - NEXT(1, 1) - continue; - } - else if (c >= 0xfd/* && c <= 0xff*/) { - /* Windows compatibility */ - OUT1(0xf8f1 - 0xfd + c) - NEXT(1, 1) - continue; - } - - REQUIRE_INBUF(2) - c2 = IN2; - - TRYMAP_DEC(cp932ext, **outbuf, c, c2); - else if ((c >= 0x81 && c <= 0x9f) || (c >= 0xe0 && c <= 0xea)){ - if (c2 < 0x40 || (c2 > 0x7e && c2 < 0x80) || c2 > 0xfc) - return 2; - - c = (c < 0xe0 ? c - 0x81 : c - 0xc1); - c2 = (c2 < 0x80 ? c2 - 0x40 : c2 - 0x41); - c = (2 * c + (c2 < 0x5e ? 0 : 1) + 0x21); - c2 = (c2 < 0x5e ? c2 : c2 - 0x5e) + 0x21; - - TRYMAP_DEC(jisx0208, **outbuf, c, c2); - else return 2; - } - else if (c >= 0xf0 && c <= 0xf9) { - if ((c2 >= 0x40 && c2 <= 0x7e) || - (c2 >= 0x80 && c2 <= 0xfc)) - OUT1(0xe000 + 188 * (c - 0xf0) + - (c2 < 0x80 ? c2 - 0x40 : c2 - 0x41)) - else - return 2; - } - else - return 2; + REQUIRE_OUTBUF(1) + if (c <= 0x80) { + OUT1(c) + NEXT(1, 1) + continue; + } + else if (c >= 0xa0 && c <= 0xdf) { + if (c == 0xa0) + OUT1(0xf8f0) /* half-width katakana */ + else + OUT1(0xfec0 + c) + NEXT(1, 1) + continue; + } + else if (c >= 0xfd/* && c <= 0xff*/) { + /* Windows compatibility */ + OUT1(0xf8f1 - 0xfd + c) + NEXT(1, 1) + continue; + } + + REQUIRE_INBUF(2) + c2 = IN2; + + TRYMAP_DEC(cp932ext, **outbuf, c, c2); + else if ((c >= 0x81 && c <= 0x9f) || (c >= 0xe0 && c <= 0xea)){ + if (c2 < 0x40 || (c2 > 0x7e && c2 < 0x80) || c2 > 0xfc) + return 2; + + c = (c < 0xe0 ? c - 0x81 : c - 0xc1); + c2 = (c2 < 0x80 ? c2 - 0x40 : c2 - 0x41); + c = (2 * c + (c2 < 0x5e ? 0 : 1) + 0x21); + c2 = (c2 < 0x5e ? c2 : c2 - 0x5e) + 0x21; + + TRYMAP_DEC(jisx0208, **outbuf, c, c2); + else return 2; + } + else if (c >= 0xf0 && c <= 0xf9) { + if ((c2 >= 0x40 && c2 <= 0x7e) || + (c2 >= 0x80 && c2 <= 0xfc)) + OUT1(0xe000 + 188 * (c - 0xf0) + + (c2 < 0x80 ? c2 - 0x40 : c2 - 0x41)) + else + return 2; + } + else + return 2; - NEXT(2, 1) - } + NEXT(2, 1) + } - return 0; + return 0; } @@ -146,166 +146,166 @@ ENCODER(euc_jis_2004) { - while (inleft > 0) { - ucs4_t c = IN1; - DBCHAR code; - Py_ssize_t insize; - - if (c < 0x80) { - WRITE1(c) - NEXT(1, 1) - continue; - } - - DECODE_SURROGATE(c) - insize = GET_INSIZE(c); - - if (c <= 0xFFFF) { - EMULATE_JISX0213_2000_ENCODE_BMP(code, c) - else TRYMAP_ENC(jisx0213_bmp, code, c) { - if (code == MULTIC) { - if (inleft < 2) { - if (flags & MBENC_FLUSH) { - code = find_pairencmap( - (ucs2_t)c, 0, - jisx0213_pair_encmap, - JISX0213_ENCPAIRS); - if (code == DBCINV) - return 1; - } - else - return MBERR_TOOFEW; - } - else { - code = find_pairencmap( - (ucs2_t)c, (*inbuf)[1], - jisx0213_pair_encmap, - JISX0213_ENCPAIRS); - if (code == DBCINV) { - code = find_pairencmap( - (ucs2_t)c, 0, - jisx0213_pair_encmap, - JISX0213_ENCPAIRS); - if (code == DBCINV) - return 1; - } else - insize = 2; - } - } - } - else TRYMAP_ENC(jisxcommon, code, c); - else if (c >= 0xff61 && c <= 0xff9f) { - /* JIS X 0201 half-width katakana */ - WRITE2(0x8e, c - 0xfec0) - NEXT(1, 2) - continue; - } - else if (c == 0xff3c) - /* F/W REVERSE SOLIDUS (see NOTES) */ - code = 0x2140; - else if (c == 0xff5e) - /* F/W TILDE (see NOTES) */ - code = 0x2232; - else - return 1; - } - else if (c >> 16 == EMPBASE >> 16) { - EMULATE_JISX0213_2000_ENCODE_EMP(code, c) - else TRYMAP_ENC(jisx0213_emp, code, c & 0xffff); - else return insize; - } - else - return insize; - - if (code & 0x8000) { - /* Codeset 2 */ - WRITE3(0x8f, code >> 8, (code & 0xFF) | 0x80) - NEXT(insize, 3) - } else { - /* Codeset 1 */ - WRITE2((code >> 8) | 0x80, (code & 0xFF) | 0x80) - NEXT(insize, 2) - } - } + while (inleft > 0) { + ucs4_t c = IN1; + DBCHAR code; + Py_ssize_t insize; + + if (c < 0x80) { + WRITE1(c) + NEXT(1, 1) + continue; + } + + DECODE_SURROGATE(c) + insize = GET_INSIZE(c); + + if (c <= 0xFFFF) { + EMULATE_JISX0213_2000_ENCODE_BMP(code, c) + else TRYMAP_ENC(jisx0213_bmp, code, c) { + if (code == MULTIC) { + if (inleft < 2) { + if (flags & MBENC_FLUSH) { + code = find_pairencmap( + (ucs2_t)c, 0, + jisx0213_pair_encmap, + JISX0213_ENCPAIRS); + if (code == DBCINV) + return 1; + } + else + return MBERR_TOOFEW; + } + else { + code = find_pairencmap( + (ucs2_t)c, (*inbuf)[1], + jisx0213_pair_encmap, + JISX0213_ENCPAIRS); + if (code == DBCINV) { + code = find_pairencmap( + (ucs2_t)c, 0, + jisx0213_pair_encmap, + JISX0213_ENCPAIRS); + if (code == DBCINV) + return 1; + } else + insize = 2; + } + } + } + else TRYMAP_ENC(jisxcommon, code, c); + else if (c >= 0xff61 && c <= 0xff9f) { + /* JIS X 0201 half-width katakana */ + WRITE2(0x8e, c - 0xfec0) + NEXT(1, 2) + continue; + } + else if (c == 0xff3c) + /* F/W REVERSE SOLIDUS (see NOTES) */ + code = 0x2140; + else if (c == 0xff5e) + /* F/W TILDE (see NOTES) */ + code = 0x2232; + else + return 1; + } + else if (c >> 16 == EMPBASE >> 16) { + EMULATE_JISX0213_2000_ENCODE_EMP(code, c) + else TRYMAP_ENC(jisx0213_emp, code, c & 0xffff); + else return insize; + } + else + return insize; + + if (code & 0x8000) { + /* Codeset 2 */ + WRITE3(0x8f, code >> 8, (code & 0xFF) | 0x80) + NEXT(insize, 3) + } else { + /* Codeset 1 */ + WRITE2((code >> 8) | 0x80, (code & 0xFF) | 0x80) + NEXT(insize, 2) + } + } - return 0; + return 0; } DECODER(euc_jis_2004) { - while (inleft > 0) { - unsigned char c = IN1; - ucs4_t code; - - REQUIRE_OUTBUF(1) - - if (c < 0x80) { - OUT1(c) - NEXT(1, 1) - continue; - } - - if (c == 0x8e) { - /* JIS X 0201 half-width katakana */ - unsigned char c2; - - REQUIRE_INBUF(2) - c2 = IN2; - if (c2 >= 0xa1 && c2 <= 0xdf) { - OUT1(0xfec0 + c2) - NEXT(2, 1) - } - else - return 2; - } - else if (c == 0x8f) { - unsigned char c2, c3; - - REQUIRE_INBUF(3) - c2 = IN2 ^ 0x80; - c3 = IN3 ^ 0x80; - - /* JIS X 0213 Plane 2 or JIS X 0212 (see NOTES) */ - EMULATE_JISX0213_2000_DECODE_PLANE2(**outbuf, c2, c3) - else TRYMAP_DEC(jisx0213_2_bmp, **outbuf, c2, c3) ; - else TRYMAP_DEC(jisx0213_2_emp, code, c2, c3) { - WRITEUCS4(EMPBASE | code) - NEXT_IN(3) - continue; - } - else TRYMAP_DEC(jisx0212, **outbuf, c2, c3) ; - else return 3; - NEXT(3, 1) - } - else { - unsigned char c2; - - REQUIRE_INBUF(2) - c ^= 0x80; - c2 = IN2 ^ 0x80; - - /* JIS X 0213 Plane 1 */ - EMULATE_JISX0213_2000_DECODE_PLANE1(**outbuf, c, c2) - else if (c == 0x21 && c2 == 0x40) **outbuf = 0xff3c; - else if (c == 0x22 && c2 == 0x32) **outbuf = 0xff5e; - else TRYMAP_DEC(jisx0208, **outbuf, c, c2); - else TRYMAP_DEC(jisx0213_1_bmp, **outbuf, c, c2); - else TRYMAP_DEC(jisx0213_1_emp, code, c, c2) { - WRITEUCS4(EMPBASE | code) - NEXT_IN(2) - continue; - } - else TRYMAP_DEC(jisx0213_pair, code, c, c2) { - WRITE2(code >> 16, code & 0xffff) - NEXT(2, 2) - continue; - } - else return 2; - NEXT(2, 1) - } - } + while (inleft > 0) { + unsigned char c = IN1; + ucs4_t code; + + REQUIRE_OUTBUF(1) + + if (c < 0x80) { + OUT1(c) + NEXT(1, 1) + continue; + } + + if (c == 0x8e) { + /* JIS X 0201 half-width katakana */ + unsigned char c2; + + REQUIRE_INBUF(2) + c2 = IN2; + if (c2 >= 0xa1 && c2 <= 0xdf) { + OUT1(0xfec0 + c2) + NEXT(2, 1) + } + else + return 2; + } + else if (c == 0x8f) { + unsigned char c2, c3; + + REQUIRE_INBUF(3) + c2 = IN2 ^ 0x80; + c3 = IN3 ^ 0x80; + + /* JIS X 0213 Plane 2 or JIS X 0212 (see NOTES) */ + EMULATE_JISX0213_2000_DECODE_PLANE2(**outbuf, c2, c3) + else TRYMAP_DEC(jisx0213_2_bmp, **outbuf, c2, c3) ; + else TRYMAP_DEC(jisx0213_2_emp, code, c2, c3) { + WRITEUCS4(EMPBASE | code) + NEXT_IN(3) + continue; + } + else TRYMAP_DEC(jisx0212, **outbuf, c2, c3) ; + else return 3; + NEXT(3, 1) + } + else { + unsigned char c2; + + REQUIRE_INBUF(2) + c ^= 0x80; + c2 = IN2 ^ 0x80; + + /* JIS X 0213 Plane 1 */ + EMULATE_JISX0213_2000_DECODE_PLANE1(**outbuf, c, c2) + else if (c == 0x21 && c2 == 0x40) **outbuf = 0xff3c; + else if (c == 0x22 && c2 == 0x32) **outbuf = 0xff5e; + else TRYMAP_DEC(jisx0208, **outbuf, c, c2); + else TRYMAP_DEC(jisx0213_1_bmp, **outbuf, c, c2); + else TRYMAP_DEC(jisx0213_1_emp, code, c, c2) { + WRITEUCS4(EMPBASE | code) + NEXT_IN(2) + continue; + } + else TRYMAP_DEC(jisx0213_pair, code, c, c2) { + WRITE2(code >> 16, code & 0xffff) + NEXT(2, 2) + continue; + } + else return 2; + NEXT(2, 1) + } + } - return 0; + return 0; } @@ -315,114 +315,114 @@ ENCODER(euc_jp) { - while (inleft > 0) { - Py_UNICODE c = IN1; - DBCHAR code; - - if (c < 0x80) { - WRITE1((unsigned char)c) - NEXT(1, 1) - continue; - } - - UCS4INVALID(c) - - TRYMAP_ENC(jisxcommon, code, c); - else if (c >= 0xff61 && c <= 0xff9f) { - /* JIS X 0201 half-width katakana */ - WRITE2(0x8e, c - 0xfec0) - NEXT(1, 2) - continue; - } + while (inleft > 0) { + Py_UNICODE c = IN1; + DBCHAR code; + + if (c < 0x80) { + WRITE1((unsigned char)c) + NEXT(1, 1) + continue; + } + + UCS4INVALID(c) + + TRYMAP_ENC(jisxcommon, code, c); + else if (c >= 0xff61 && c <= 0xff9f) { + /* JIS X 0201 half-width katakana */ + WRITE2(0x8e, c - 0xfec0) + NEXT(1, 2) + continue; + } #ifndef STRICT_BUILD - else if (c == 0xff3c) /* FULL-WIDTH REVERSE SOLIDUS */ - code = 0x2140; - else if (c == 0xa5) { /* YEN SIGN */ - WRITE1(0x5c); - NEXT(1, 1) - continue; - } else if (c == 0x203e) { /* OVERLINE */ - WRITE1(0x7e); - NEXT(1, 1) - continue; - } + else if (c == 0xff3c) /* FULL-WIDTH REVERSE SOLIDUS */ + code = 0x2140; + else if (c == 0xa5) { /* YEN SIGN */ + WRITE1(0x5c); + NEXT(1, 1) + continue; + } else if (c == 0x203e) { /* OVERLINE */ + WRITE1(0x7e); + NEXT(1, 1) + continue; + } #endif - else - return 1; + else + return 1; - if (code & 0x8000) { - /* JIS X 0212 */ - WRITE3(0x8f, code >> 8, (code & 0xFF) | 0x80) - NEXT(1, 3) - } else { - /* JIS X 0208 */ - WRITE2((code >> 8) | 0x80, (code & 0xFF) | 0x80) - NEXT(1, 2) - } - } + if (code & 0x8000) { + /* JIS X 0212 */ + WRITE3(0x8f, code >> 8, (code & 0xFF) | 0x80) + NEXT(1, 3) + } else { + /* JIS X 0208 */ + WRITE2((code >> 8) | 0x80, (code & 0xFF) | 0x80) + NEXT(1, 2) + } + } - return 0; + return 0; } DECODER(euc_jp) { - while (inleft > 0) { - unsigned char c = IN1; + while (inleft > 0) { + unsigned char c = IN1; - REQUIRE_OUTBUF(1) + REQUIRE_OUTBUF(1) - if (c < 0x80) { - OUT1(c) - NEXT(1, 1) - continue; - } - - if (c == 0x8e) { - /* JIS X 0201 half-width katakana */ - unsigned char c2; - - REQUIRE_INBUF(2) - c2 = IN2; - if (c2 >= 0xa1 && c2 <= 0xdf) { - OUT1(0xfec0 + c2) - NEXT(2, 1) - } - else - return 2; - } - else if (c == 0x8f) { - unsigned char c2, c3; - - REQUIRE_INBUF(3) - c2 = IN2; - c3 = IN3; - /* JIS X 0212 */ - TRYMAP_DEC(jisx0212, **outbuf, c2 ^ 0x80, c3 ^ 0x80) { - NEXT(3, 1) - } - else - return 3; - } - else { - unsigned char c2; - - REQUIRE_INBUF(2) - c2 = IN2; - /* JIS X 0208 */ + if (c < 0x80) { + OUT1(c) + NEXT(1, 1) + continue; + } + + if (c == 0x8e) { + /* JIS X 0201 half-width katakana */ + unsigned char c2; + + REQUIRE_INBUF(2) + c2 = IN2; + if (c2 >= 0xa1 && c2 <= 0xdf) { + OUT1(0xfec0 + c2) + NEXT(2, 1) + } + else + return 2; + } + else if (c == 0x8f) { + unsigned char c2, c3; + + REQUIRE_INBUF(3) + c2 = IN2; + c3 = IN3; + /* JIS X 0212 */ + TRYMAP_DEC(jisx0212, **outbuf, c2 ^ 0x80, c3 ^ 0x80) { + NEXT(3, 1) + } + else + return 3; + } + else { + unsigned char c2; + + REQUIRE_INBUF(2) + c2 = IN2; + /* JIS X 0208 */ #ifndef STRICT_BUILD - if (c == 0xa1 && c2 == 0xc0) - /* FULL-WIDTH REVERSE SOLIDUS */ - **outbuf = 0xff3c; - else + if (c == 0xa1 && c2 == 0xc0) + /* FULL-WIDTH REVERSE SOLIDUS */ + **outbuf = 0xff3c; + else #endif - TRYMAP_DEC(jisx0208, **outbuf, - c ^ 0x80, c2 ^ 0x80) ; - else return 2; - NEXT(2, 1) - } - } + TRYMAP_DEC(jisx0208, **outbuf, + c ^ 0x80, c2 ^ 0x80) ; + else return 2; + NEXT(2, 1) + } + } - return 0; + return 0; } @@ -432,105 +432,105 @@ ENCODER(shift_jis) { - while (inleft > 0) { - Py_UNICODE c = IN1; - DBCHAR code; - unsigned char c1, c2; + while (inleft > 0) { + Py_UNICODE c = IN1; + DBCHAR code; + unsigned char c1, c2; #ifdef STRICT_BUILD - JISX0201_R_ENCODE(c, code) + JISX0201_R_ENCODE(c, code) #else - if (c < 0x80) code = c; - else if (c == 0x00a5) code = 0x5c; /* YEN SIGN */ - else if (c == 0x203e) code = 0x7e; /* OVERLINE */ + if (c < 0x80) code = c; + else if (c == 0x00a5) code = 0x5c; /* YEN SIGN */ + else if (c == 0x203e) code = 0x7e; /* OVERLINE */ #endif - else JISX0201_K_ENCODE(c, code) - else UCS4INVALID(c) - else code = NOCHAR; - - if (code < 0x80 || (code >= 0xa1 && code <= 0xdf)) { - REQUIRE_OUTBUF(1) - - OUT1((unsigned char)code) - NEXT(1, 1) - continue; - } + else JISX0201_K_ENCODE(c, code) + else UCS4INVALID(c) + else code = NOCHAR; + + if (code < 0x80 || (code >= 0xa1 && code <= 0xdf)) { + REQUIRE_OUTBUF(1) + + OUT1((unsigned char)code) + NEXT(1, 1) + continue; + } - REQUIRE_OUTBUF(2) + REQUIRE_OUTBUF(2) - if (code == NOCHAR) { - TRYMAP_ENC(jisxcommon, code, c); + if (code == NOCHAR) { + TRYMAP_ENC(jisxcommon, code, c); #ifndef STRICT_BUILD - else if (c == 0xff3c) - code = 0x2140; /* FULL-WIDTH REVERSE SOLIDUS */ + else if (c == 0xff3c) + code = 0x2140; /* FULL-WIDTH REVERSE SOLIDUS */ #endif - else - return 1; + else + return 1; - if (code & 0x8000) /* MSB set: JIS X 0212 */ - return 1; - } - - c1 = code >> 8; - c2 = code & 0xff; - c2 = (((c1 - 0x21) & 1) ? 0x5e : 0) + (c2 - 0x21); - c1 = (c1 - 0x21) >> 1; - OUT1(c1 < 0x1f ? c1 + 0x81 : c1 + 0xc1) - OUT2(c2 < 0x3f ? c2 + 0x40 : c2 + 0x41) - NEXT(1, 2) - } + if (code & 0x8000) /* MSB set: JIS X 0212 */ + return 1; + } + + c1 = code >> 8; + c2 = code & 0xff; + c2 = (((c1 - 0x21) & 1) ? 0x5e : 0) + (c2 - 0x21); + c1 = (c1 - 0x21) >> 1; + OUT1(c1 < 0x1f ? c1 + 0x81 : c1 + 0xc1) + OUT2(c2 < 0x3f ? c2 + 0x40 : c2 + 0x41) + NEXT(1, 2) + } - return 0; + return 0; } DECODER(shift_jis) { - while (inleft > 0) { - unsigned char c = IN1; + while (inleft > 0) { + unsigned char c = IN1; - REQUIRE_OUTBUF(1) + REQUIRE_OUTBUF(1) #ifdef STRICT_BUILD - JISX0201_R_DECODE(c, **outbuf) + JISX0201_R_DECODE(c, **outbuf) #else - if (c < 0x80) **outbuf = c; + if (c < 0x80) **outbuf = c; #endif - else JISX0201_K_DECODE(c, **outbuf) - else if ((c >= 0x81 && c <= 0x9f) || (c >= 0xe0 && c <= 0xea)){ - unsigned char c1, c2; - - REQUIRE_INBUF(2) - c2 = IN2; - if (c2 < 0x40 || (c2 > 0x7e && c2 < 0x80) || c2 > 0xfc) - return 2; - - c1 = (c < 0xe0 ? c - 0x81 : c - 0xc1); - c2 = (c2 < 0x80 ? c2 - 0x40 : c2 - 0x41); - c1 = (2 * c1 + (c2 < 0x5e ? 0 : 1) + 0x21); - c2 = (c2 < 0x5e ? c2 : c2 - 0x5e) + 0x21; + else JISX0201_K_DECODE(c, **outbuf) + else if ((c >= 0x81 && c <= 0x9f) || (c >= 0xe0 && c <= 0xea)){ + unsigned char c1, c2; + + REQUIRE_INBUF(2) + c2 = IN2; + if (c2 < 0x40 || (c2 > 0x7e && c2 < 0x80) || c2 > 0xfc) + return 2; + + c1 = (c < 0xe0 ? c - 0x81 : c - 0xc1); + c2 = (c2 < 0x80 ? c2 - 0x40 : c2 - 0x41); + c1 = (2 * c1 + (c2 < 0x5e ? 0 : 1) + 0x21); + c2 = (c2 < 0x5e ? c2 : c2 - 0x5e) + 0x21; #ifndef STRICT_BUILD - if (c1 == 0x21 && c2 == 0x40) { - /* FULL-WIDTH REVERSE SOLIDUS */ - OUT1(0xff3c) - NEXT(2, 1) - continue; - } + if (c1 == 0x21 && c2 == 0x40) { + /* FULL-WIDTH REVERSE SOLIDUS */ + OUT1(0xff3c) + NEXT(2, 1) + continue; + } #endif - TRYMAP_DEC(jisx0208, **outbuf, c1, c2) { - NEXT(2, 1) - continue; - } - else - return 2; - } - else - return 2; + TRYMAP_DEC(jisx0208, **outbuf, c1, c2) { + NEXT(2, 1) + continue; + } + else + return 2; + } + else + return 2; - NEXT(1, 1) /* JIS X 0201 */ - } + NEXT(1, 1) /* JIS X 0201 */ + } - return 0; + return 0; } @@ -540,167 +540,167 @@ ENCODER(shift_jis_2004) { - while (inleft > 0) { - ucs4_t c = IN1; - DBCHAR code = NOCHAR; - int c1, c2; - Py_ssize_t insize; - - JISX0201_ENCODE(c, code) - else DECODE_SURROGATE(c) - - if (code < 0x80 || (code >= 0xa1 && code <= 0xdf)) { - WRITE1((unsigned char)code) - NEXT(1, 1) - continue; - } - - REQUIRE_OUTBUF(2) - insize = GET_INSIZE(c); - - if (code == NOCHAR) { - if (c <= 0xffff) { - EMULATE_JISX0213_2000_ENCODE_BMP(code, c) - else TRYMAP_ENC(jisx0213_bmp, code, c) { - if (code == MULTIC) { - if (inleft < 2) { - if (flags & MBENC_FLUSH) { - code = find_pairencmap - ((ucs2_t)c, 0, - jisx0213_pair_encmap, - JISX0213_ENCPAIRS); - if (code == DBCINV) - return 1; - } - else - return MBERR_TOOFEW; - } - else { - code = find_pairencmap( - (ucs2_t)c, IN2, - jisx0213_pair_encmap, - JISX0213_ENCPAIRS); - if (code == DBCINV) { - code = find_pairencmap( - (ucs2_t)c, 0, - jisx0213_pair_encmap, - JISX0213_ENCPAIRS); - if (code == DBCINV) - return 1; - } - else - insize = 2; - } - } - } - else TRYMAP_ENC(jisxcommon, code, c) { - /* abandon JIS X 0212 codes */ - if (code & 0x8000) - return 1; - } - else return 1; - } - else if (c >> 16 == EMPBASE >> 16) { - EMULATE_JISX0213_2000_ENCODE_EMP(code, c) - else TRYMAP_ENC(jisx0213_emp, code, c&0xffff); - else return insize; - } - else - return insize; - } - - c1 = code >> 8; - c2 = (code & 0xff) - 0x21; - - if (c1 & 0x80) { /* Plane 2 */ - if (c1 >= 0xee) c1 -= 0x87; - else if (c1 >= 0xac || c1 == 0xa8) c1 -= 0x49; - else c1 -= 0x43; - } - else /* Plane 1 */ - c1 -= 0x21; - - if (c1 & 1) c2 += 0x5e; - c1 >>= 1; - OUT1(c1 + (c1 < 0x1f ? 0x81 : 0xc1)) - OUT2(c2 + (c2 < 0x3f ? 0x40 : 0x41)) + while (inleft > 0) { + ucs4_t c = IN1; + DBCHAR code = NOCHAR; + int c1, c2; + Py_ssize_t insize; + + JISX0201_ENCODE(c, code) + else DECODE_SURROGATE(c) + + if (code < 0x80 || (code >= 0xa1 && code <= 0xdf)) { + WRITE1((unsigned char)code) + NEXT(1, 1) + continue; + } + + REQUIRE_OUTBUF(2) + insize = GET_INSIZE(c); + + if (code == NOCHAR) { + if (c <= 0xffff) { + EMULATE_JISX0213_2000_ENCODE_BMP(code, c) + else TRYMAP_ENC(jisx0213_bmp, code, c) { + if (code == MULTIC) { + if (inleft < 2) { + if (flags & MBENC_FLUSH) { + code = find_pairencmap + ((ucs2_t)c, 0, + jisx0213_pair_encmap, + JISX0213_ENCPAIRS); + if (code == DBCINV) + return 1; + } + else + return MBERR_TOOFEW; + } + else { + code = find_pairencmap( + (ucs2_t)c, IN2, + jisx0213_pair_encmap, + JISX0213_ENCPAIRS); + if (code == DBCINV) { + code = find_pairencmap( + (ucs2_t)c, 0, + jisx0213_pair_encmap, + JISX0213_ENCPAIRS); + if (code == DBCINV) + return 1; + } + else + insize = 2; + } + } + } + else TRYMAP_ENC(jisxcommon, code, c) { + /* abandon JIS X 0212 codes */ + if (code & 0x8000) + return 1; + } + else return 1; + } + else if (c >> 16 == EMPBASE >> 16) { + EMULATE_JISX0213_2000_ENCODE_EMP(code, c) + else TRYMAP_ENC(jisx0213_emp, code, c&0xffff); + else return insize; + } + else + return insize; + } + + c1 = code >> 8; + c2 = (code & 0xff) - 0x21; + + if (c1 & 0x80) { /* Plane 2 */ + if (c1 >= 0xee) c1 -= 0x87; + else if (c1 >= 0xac || c1 == 0xa8) c1 -= 0x49; + else c1 -= 0x43; + } + else /* Plane 1 */ + c1 -= 0x21; + + if (c1 & 1) c2 += 0x5e; + c1 >>= 1; + OUT1(c1 + (c1 < 0x1f ? 0x81 : 0xc1)) + OUT2(c2 + (c2 < 0x3f ? 0x40 : 0x41)) - NEXT(insize, 2) - } + NEXT(insize, 2) + } - return 0; + return 0; } DECODER(shift_jis_2004) { - while (inleft > 0) { - unsigned char c = IN1; + while (inleft > 0) { + unsigned char c = IN1; - REQUIRE_OUTBUF(1) - JISX0201_DECODE(c, **outbuf) - else if ((c >= 0x81 && c <= 0x9f) || (c >= 0xe0 && c <= 0xfc)){ - unsigned char c1, c2; - ucs4_t code; - - REQUIRE_INBUF(2) - c2 = IN2; - if (c2 < 0x40 || (c2 > 0x7e && c2 < 0x80) || c2 > 0xfc) - return 2; - - c1 = (c < 0xe0 ? c - 0x81 : c - 0xc1); - c2 = (c2 < 0x80 ? c2 - 0x40 : c2 - 0x41); - c1 = (2 * c1 + (c2 < 0x5e ? 0 : 1)); - c2 = (c2 < 0x5e ? c2 : c2 - 0x5e) + 0x21; - - if (c1 < 0x5e) { /* Plane 1 */ - c1 += 0x21; - EMULATE_JISX0213_2000_DECODE_PLANE1(**outbuf, - c1, c2) - else TRYMAP_DEC(jisx0208, **outbuf, c1, c2) { - NEXT_OUT(1) - } - else TRYMAP_DEC(jisx0213_1_bmp, **outbuf, - c1, c2) { - NEXT_OUT(1) - } - else TRYMAP_DEC(jisx0213_1_emp, code, c1, c2) { - WRITEUCS4(EMPBASE | code) - } - else TRYMAP_DEC(jisx0213_pair, code, c1, c2) { - WRITE2(code >> 16, code & 0xffff) - NEXT_OUT(2) - } - else - return 2; - NEXT_IN(2) - } - else { /* Plane 2 */ - if (c1 >= 0x67) c1 += 0x07; - else if (c1 >= 0x63 || c1 == 0x5f) c1 -= 0x37; - else c1 -= 0x3d; - - EMULATE_JISX0213_2000_DECODE_PLANE2(**outbuf, - c1, c2) - else TRYMAP_DEC(jisx0213_2_bmp, **outbuf, - c1, c2) ; - else TRYMAP_DEC(jisx0213_2_emp, code, c1, c2) { - WRITEUCS4(EMPBASE | code) - NEXT_IN(2) - continue; - } - else - return 2; - NEXT(2, 1) - } - continue; - } - else - return 2; + REQUIRE_OUTBUF(1) + JISX0201_DECODE(c, **outbuf) + else if ((c >= 0x81 && c <= 0x9f) || (c >= 0xe0 && c <= 0xfc)){ + unsigned char c1, c2; + ucs4_t code; + + REQUIRE_INBUF(2) + c2 = IN2; + if (c2 < 0x40 || (c2 > 0x7e && c2 < 0x80) || c2 > 0xfc) + return 2; + + c1 = (c < 0xe0 ? c - 0x81 : c - 0xc1); + c2 = (c2 < 0x80 ? c2 - 0x40 : c2 - 0x41); + c1 = (2 * c1 + (c2 < 0x5e ? 0 : 1)); + c2 = (c2 < 0x5e ? c2 : c2 - 0x5e) + 0x21; + + if (c1 < 0x5e) { /* Plane 1 */ + c1 += 0x21; + EMULATE_JISX0213_2000_DECODE_PLANE1(**outbuf, + c1, c2) + else TRYMAP_DEC(jisx0208, **outbuf, c1, c2) { + NEXT_OUT(1) + } + else TRYMAP_DEC(jisx0213_1_bmp, **outbuf, + c1, c2) { + NEXT_OUT(1) + } + else TRYMAP_DEC(jisx0213_1_emp, code, c1, c2) { + WRITEUCS4(EMPBASE | code) + } + else TRYMAP_DEC(jisx0213_pair, code, c1, c2) { + WRITE2(code >> 16, code & 0xffff) + NEXT_OUT(2) + } + else + return 2; + NEXT_IN(2) + } + else { /* Plane 2 */ + if (c1 >= 0x67) c1 += 0x07; + else if (c1 >= 0x63 || c1 == 0x5f) c1 -= 0x37; + else c1 -= 0x3d; + + EMULATE_JISX0213_2000_DECODE_PLANE2(**outbuf, + c1, c2) + else TRYMAP_DEC(jisx0213_2_bmp, **outbuf, + c1, c2) ; + else TRYMAP_DEC(jisx0213_2_emp, code, c1, c2) { + WRITEUCS4(EMPBASE | code) + NEXT_IN(2) + continue; + } + else + return 2; + NEXT(2, 1) + } + continue; + } + else + return 2; - NEXT(1, 1) /* JIS X 0201 */ - } + NEXT(1, 1) /* JIS X 0201 */ + } - return 0; + return 0; } Modified: python/branches/py3k/Modules/cjkcodecs/_codecs_kr.c ============================================================================== --- python/branches/py3k/Modules/cjkcodecs/_codecs_kr.c (original) +++ python/branches/py3k/Modules/cjkcodecs/_codecs_kr.c Sun May 9 17:52:27 2010 @@ -11,151 +11,151 @@ * EUC-KR codec */ -#define EUCKR_JAMO_FIRSTBYTE 0xA4 -#define EUCKR_JAMO_FILLER 0xD4 +#define EUCKR_JAMO_FIRSTBYTE 0xA4 +#define EUCKR_JAMO_FILLER 0xD4 static const unsigned char u2cgk_choseong[19] = { - 0xa1, 0xa2, 0xa4, 0xa7, 0xa8, 0xa9, 0xb1, 0xb2, - 0xb3, 0xb5, 0xb6, 0xb7, 0xb8, 0xb9, 0xba, 0xbb, - 0xbc, 0xbd, 0xbe + 0xa1, 0xa2, 0xa4, 0xa7, 0xa8, 0xa9, 0xb1, 0xb2, + 0xb3, 0xb5, 0xb6, 0xb7, 0xb8, 0xb9, 0xba, 0xbb, + 0xbc, 0xbd, 0xbe }; static const unsigned char u2cgk_jungseong[21] = { - 0xbf, 0xc0, 0xc1, 0xc2, 0xc3, 0xc4, 0xc5, 0xc6, - 0xc7, 0xc8, 0xc9, 0xca, 0xcb, 0xcc, 0xcd, 0xce, - 0xcf, 0xd0, 0xd1, 0xd2, 0xd3 + 0xbf, 0xc0, 0xc1, 0xc2, 0xc3, 0xc4, 0xc5, 0xc6, + 0xc7, 0xc8, 0xc9, 0xca, 0xcb, 0xcc, 0xcd, 0xce, + 0xcf, 0xd0, 0xd1, 0xd2, 0xd3 }; static const unsigned char u2cgk_jongseong[28] = { - 0xd4, 0xa1, 0xa2, 0xa3, 0xa4, 0xa5, 0xa6, 0xa7, - 0xa9, 0xaa, 0xab, 0xac, 0xad, 0xae, 0xaf, 0xb0, - 0xb1, 0xb2, 0xb4, 0xb5, 0xb6, 0xb7, 0xb8, 0xba, - 0xbb, 0xbc, 0xbd, 0xbe + 0xd4, 0xa1, 0xa2, 0xa3, 0xa4, 0xa5, 0xa6, 0xa7, + 0xa9, 0xaa, 0xab, 0xac, 0xad, 0xae, 0xaf, 0xb0, + 0xb1, 0xb2, 0xb4, 0xb5, 0xb6, 0xb7, 0xb8, 0xba, + 0xbb, 0xbc, 0xbd, 0xbe }; ENCODER(euc_kr) { - while (inleft > 0) { - Py_UNICODE c = IN1; - DBCHAR code; - - if (c < 0x80) { - WRITE1((unsigned char)c) - NEXT(1, 1) - continue; - } - UCS4INVALID(c) - - REQUIRE_OUTBUF(2) - TRYMAP_ENC(cp949, code, c); - else return 1; - - if ((code & 0x8000) == 0) { - /* KS X 1001 coded character */ - OUT1((code >> 8) | 0x80) - OUT2((code & 0xFF) | 0x80) - NEXT(1, 2) - } - else { /* Mapping is found in CP949 extension, - * but we encode it in KS X 1001:1998 Annex 3, - * make-up sequence for EUC-KR. */ - - REQUIRE_OUTBUF(8) - - /* syllable composition precedence */ - OUT1(EUCKR_JAMO_FIRSTBYTE) - OUT2(EUCKR_JAMO_FILLER) - - /* All codepoints in CP949 extension are in unicode - * Hangul Syllable area. */ - assert(0xac00 <= c && c <= 0xd7a3); - c -= 0xac00; - - OUT3(EUCKR_JAMO_FIRSTBYTE) - OUT4(u2cgk_choseong[c / 588]) - NEXT_OUT(4) - - OUT1(EUCKR_JAMO_FIRSTBYTE) - OUT2(u2cgk_jungseong[(c / 28) % 21]) - OUT3(EUCKR_JAMO_FIRSTBYTE) - OUT4(u2cgk_jongseong[c % 28]) - NEXT(1, 4) - } - } + while (inleft > 0) { + Py_UNICODE c = IN1; + DBCHAR code; + + if (c < 0x80) { + WRITE1((unsigned char)c) + NEXT(1, 1) + continue; + } + UCS4INVALID(c) + + REQUIRE_OUTBUF(2) + TRYMAP_ENC(cp949, code, c); + else return 1; + + if ((code & 0x8000) == 0) { + /* KS X 1001 coded character */ + OUT1((code >> 8) | 0x80) + OUT2((code & 0xFF) | 0x80) + NEXT(1, 2) + } + else { /* Mapping is found in CP949 extension, + * but we encode it in KS X 1001:1998 Annex 3, + * make-up sequence for EUC-KR. */ + + REQUIRE_OUTBUF(8) + + /* syllable composition precedence */ + OUT1(EUCKR_JAMO_FIRSTBYTE) + OUT2(EUCKR_JAMO_FILLER) + + /* All codepoints in CP949 extension are in unicode + * Hangul Syllable area. */ + assert(0xac00 <= c && c <= 0xd7a3); + c -= 0xac00; + + OUT3(EUCKR_JAMO_FIRSTBYTE) + OUT4(u2cgk_choseong[c / 588]) + NEXT_OUT(4) + + OUT1(EUCKR_JAMO_FIRSTBYTE) + OUT2(u2cgk_jungseong[(c / 28) % 21]) + OUT3(EUCKR_JAMO_FIRSTBYTE) + OUT4(u2cgk_jongseong[c % 28]) + NEXT(1, 4) + } + } - return 0; + return 0; } -#define NONE 127 +#define NONE 127 static const unsigned char cgk2u_choseong[] = { /* [A1, BE] */ - 0, 1, NONE, 2, NONE, NONE, 3, 4, - 5, NONE, NONE, NONE, NONE, NONE, NONE, NONE, - 6, 7, 8, NONE, 9, 10, 11, 12, - 13, 14, 15, 16, 17, 18 + 0, 1, NONE, 2, NONE, NONE, 3, 4, + 5, NONE, NONE, NONE, NONE, NONE, NONE, NONE, + 6, 7, 8, NONE, 9, 10, 11, 12, + 13, 14, 15, 16, 17, 18 }; static const unsigned char cgk2u_jongseong[] = { /* [A1, BE] */ - 1, 2, 3, 4, 5, 6, 7, NONE, - 8, 9, 10, 11, 12, 13, 14, 15, - 16, 17, NONE, 18, 19, 20, 21, 22, - NONE, 23, 24, 25, 26, 27 + 1, 2, 3, 4, 5, 6, 7, NONE, + 8, 9, 10, 11, 12, 13, 14, 15, + 16, 17, NONE, 18, 19, 20, 21, 22, + NONE, 23, 24, 25, 26, 27 }; DECODER(euc_kr) { - while (inleft > 0) { - unsigned char c = IN1; + while (inleft > 0) { + unsigned char c = IN1; - REQUIRE_OUTBUF(1) + REQUIRE_OUTBUF(1) - if (c < 0x80) { - OUT1(c) - NEXT(1, 1) - continue; - } - - REQUIRE_INBUF(2) - - if (c == EUCKR_JAMO_FIRSTBYTE && - IN2 == EUCKR_JAMO_FILLER) { - /* KS X 1001:1998 Annex 3 make-up sequence */ - DBCHAR cho, jung, jong; - - REQUIRE_INBUF(8) - if ((*inbuf)[2] != EUCKR_JAMO_FIRSTBYTE || - (*inbuf)[4] != EUCKR_JAMO_FIRSTBYTE || - (*inbuf)[6] != EUCKR_JAMO_FIRSTBYTE) - return 8; - - c = (*inbuf)[3]; - if (0xa1 <= c && c <= 0xbe) - cho = cgk2u_choseong[c - 0xa1]; - else - cho = NONE; - - c = (*inbuf)[5]; - jung = (0xbf <= c && c <= 0xd3) ? c - 0xbf : NONE; - - c = (*inbuf)[7]; - if (c == EUCKR_JAMO_FILLER) - jong = 0; - else if (0xa1 <= c && c <= 0xbe) - jong = cgk2u_jongseong[c - 0xa1]; - else - jong = NONE; - - if (cho == NONE || jung == NONE || jong == NONE) - return 8; - - OUT1(0xac00 + cho*588 + jung*28 + jong); - NEXT(8, 1) - } - else TRYMAP_DEC(ksx1001, **outbuf, c ^ 0x80, IN2 ^ 0x80) { - NEXT(2, 1) - } - else - return 2; - } + if (c < 0x80) { + OUT1(c) + NEXT(1, 1) + continue; + } + + REQUIRE_INBUF(2) + + if (c == EUCKR_JAMO_FIRSTBYTE && + IN2 == EUCKR_JAMO_FILLER) { + /* KS X 1001:1998 Annex 3 make-up sequence */ + DBCHAR cho, jung, jong; + + REQUIRE_INBUF(8) + if ((*inbuf)[2] != EUCKR_JAMO_FIRSTBYTE || + (*inbuf)[4] != EUCKR_JAMO_FIRSTBYTE || + (*inbuf)[6] != EUCKR_JAMO_FIRSTBYTE) + return 8; + + c = (*inbuf)[3]; + if (0xa1 <= c && c <= 0xbe) + cho = cgk2u_choseong[c - 0xa1]; + else + cho = NONE; + + c = (*inbuf)[5]; + jung = (0xbf <= c && c <= 0xd3) ? c - 0xbf : NONE; + + c = (*inbuf)[7]; + if (c == EUCKR_JAMO_FILLER) + jong = 0; + else if (0xa1 <= c && c <= 0xbe) + jong = cgk2u_jongseong[c - 0xa1]; + else + jong = NONE; + + if (cho == NONE || jung == NONE || jong == NONE) + return 8; + + OUT1(0xac00 + cho*588 + jung*28 + jong); + NEXT(8, 1) + } + else TRYMAP_DEC(ksx1001, **outbuf, c ^ 0x80, IN2 ^ 0x80) { + NEXT(2, 1) + } + else + return 2; + } - return 0; + return 0; } #undef NONE @@ -166,54 +166,54 @@ ENCODER(cp949) { - while (inleft > 0) { - Py_UNICODE c = IN1; - DBCHAR code; - - if (c < 0x80) { - WRITE1((unsigned char)c) - NEXT(1, 1) - continue; - } - UCS4INVALID(c) - - REQUIRE_OUTBUF(2) - TRYMAP_ENC(cp949, code, c); - else return 1; - - OUT1((code >> 8) | 0x80) - if (code & 0x8000) - OUT2(code & 0xFF) /* MSB set: CP949 */ - else - OUT2((code & 0xFF) | 0x80) /* MSB unset: ks x 1001 */ - NEXT(1, 2) - } + while (inleft > 0) { + Py_UNICODE c = IN1; + DBCHAR code; + + if (c < 0x80) { + WRITE1((unsigned char)c) + NEXT(1, 1) + continue; + } + UCS4INVALID(c) + + REQUIRE_OUTBUF(2) + TRYMAP_ENC(cp949, code, c); + else return 1; + + OUT1((code >> 8) | 0x80) + if (code & 0x8000) + OUT2(code & 0xFF) /* MSB set: CP949 */ + else + OUT2((code & 0xFF) | 0x80) /* MSB unset: ks x 1001 */ + NEXT(1, 2) + } - return 0; + return 0; } DECODER(cp949) { - while (inleft > 0) { - unsigned char c = IN1; + while (inleft > 0) { + unsigned char c = IN1; - REQUIRE_OUTBUF(1) + REQUIRE_OUTBUF(1) - if (c < 0x80) { - OUT1(c) - NEXT(1, 1) - continue; - } - - REQUIRE_INBUF(2) - TRYMAP_DEC(ksx1001, **outbuf, c ^ 0x80, IN2 ^ 0x80); - else TRYMAP_DEC(cp949ext, **outbuf, c, IN2); - else return 2; + if (c < 0x80) { + OUT1(c) + NEXT(1, 1) + continue; + } + + REQUIRE_INBUF(2) + TRYMAP_DEC(ksx1001, **outbuf, c ^ 0x80, IN2 ^ 0x80); + else TRYMAP_DEC(cp949ext, **outbuf, c, IN2); + else return 2; - NEXT(2, 1) - } + NEXT(2, 1) + } - return 0; + return 0; } @@ -250,58 +250,58 @@ ENCODER(johab) { - while (inleft > 0) { - Py_UNICODE c = IN1; - DBCHAR code; - - if (c < 0x80) { - WRITE1((unsigned char)c) - NEXT(1, 1) - continue; - } - UCS4INVALID(c) - - REQUIRE_OUTBUF(2) - - if (c >= 0xac00 && c <= 0xd7a3) { - c -= 0xac00; - code = 0x8000 | - (u2johabidx_choseong[c / 588] << 10) | - (u2johabidx_jungseong[(c / 28) % 21] << 5) | - u2johabidx_jongseong[c % 28]; - } - else if (c >= 0x3131 && c <= 0x3163) - code = u2johabjamo[c - 0x3131]; - else TRYMAP_ENC(cp949, code, c) { - unsigned char c1, c2, t2; - unsigned short t1; - - assert((code & 0x8000) == 0); - c1 = code >> 8; - c2 = code & 0xff; - if (((c1 >= 0x21 && c1 <= 0x2c) || - (c1 >= 0x4a && c1 <= 0x7d)) && - (c2 >= 0x21 && c2 <= 0x7e)) { - t1 = (c1 < 0x4a ? (c1 - 0x21 + 0x1b2) : - (c1 - 0x21 + 0x197)); - t2 = ((t1 & 1) ? 0x5e : 0) + (c2 - 0x21); - OUT1(t1 >> 1) - OUT2(t2 < 0x4e ? t2 + 0x31 : t2 + 0x43) - NEXT(1, 2) - continue; - } - else - return 1; - } - else - return 1; - - OUT1(code >> 8) - OUT2(code & 0xff) - NEXT(1, 2) - } + while (inleft > 0) { + Py_UNICODE c = IN1; + DBCHAR code; + + if (c < 0x80) { + WRITE1((unsigned char)c) + NEXT(1, 1) + continue; + } + UCS4INVALID(c) + + REQUIRE_OUTBUF(2) + + if (c >= 0xac00 && c <= 0xd7a3) { + c -= 0xac00; + code = 0x8000 | + (u2johabidx_choseong[c / 588] << 10) | + (u2johabidx_jungseong[(c / 28) % 21] << 5) | + u2johabidx_jongseong[c % 28]; + } + else if (c >= 0x3131 && c <= 0x3163) + code = u2johabjamo[c - 0x3131]; + else TRYMAP_ENC(cp949, code, c) { + unsigned char c1, c2, t2; + unsigned short t1; + + assert((code & 0x8000) == 0); + c1 = code >> 8; + c2 = code & 0xff; + if (((c1 >= 0x21 && c1 <= 0x2c) || + (c1 >= 0x4a && c1 <= 0x7d)) && + (c2 >= 0x21 && c2 <= 0x7e)) { + t1 = (c1 < 0x4a ? (c1 - 0x21 + 0x1b2) : + (c1 - 0x21 + 0x197)); + t2 = ((t1 & 1) ? 0x5e : 0) + (c2 - 0x21); + OUT1(t1 >> 1) + OUT2(t2 < 0x4e ? t2 + 0x31 : t2 + 0x43) + NEXT(1, 2) + continue; + } + else + return 1; + } + else + return 1; + + OUT1(code >> 8) + OUT2(code & 0xff) + NEXT(1, 2) + } - return 0; + return 0; } #define FILL 0xfd @@ -347,91 +347,91 @@ DECODER(johab) { - while (inleft > 0) { - unsigned char c = IN1, c2; + while (inleft > 0) { + unsigned char c = IN1, c2; - REQUIRE_OUTBUF(1) + REQUIRE_OUTBUF(1) - if (c < 0x80) { - OUT1(c) - NEXT(1, 1) - continue; - } - - REQUIRE_INBUF(2) - c2 = IN2; - - if (c < 0xd8) { - /* johab hangul */ - unsigned char c_cho, c_jung, c_jong; - unsigned char i_cho, i_jung, i_jong; - - c_cho = (c >> 2) & 0x1f; - c_jung = ((c << 3) | c2 >> 5) & 0x1f; - c_jong = c2 & 0x1f; - - i_cho = johabidx_choseong[c_cho]; - i_jung = johabidx_jungseong[c_jung]; - i_jong = johabidx_jongseong[c_jong]; - - if (i_cho == NONE || i_jung == NONE || i_jong == NONE) - return 2; - - /* we don't use U+1100 hangul jamo yet. */ - if (i_cho == FILL) { - if (i_jung == FILL) { - if (i_jong == FILL) - OUT1(0x3000) - else - OUT1(0x3100 | - johabjamo_jongseong[c_jong]) - } - else { - if (i_jong == FILL) - OUT1(0x3100 | - johabjamo_jungseong[c_jung]) - else - return 2; - } - } else { - if (i_jung == FILL) { - if (i_jong == FILL) - OUT1(0x3100 | - johabjamo_choseong[c_cho]) - else - return 2; - } - else - OUT1(0xac00 + - i_cho * 588 + - i_jung * 28 + - (i_jong == FILL ? 0 : i_jong)) - } - NEXT(2, 1) - } else { - /* KS X 1001 except hangul jamos and syllables */ - if (c == 0xdf || c > 0xf9 || - c2 < 0x31 || (c2 >= 0x80 && c2 < 0x91) || - (c2 & 0x7f) == 0x7f || - (c == 0xda && (c2 >= 0xa1 && c2 <= 0xd3))) - return 2; - else { - unsigned char t1, t2; - - t1 = (c < 0xe0 ? 2 * (c - 0xd9) : - 2 * c - 0x197); - t2 = (c2 < 0x91 ? c2 - 0x31 : c2 - 0x43); - t1 = t1 + (t2 < 0x5e ? 0 : 1) + 0x21; - t2 = (t2 < 0x5e ? t2 : t2 - 0x5e) + 0x21; - - TRYMAP_DEC(ksx1001, **outbuf, t1, t2); - else return 2; - NEXT(2, 1) - } - } - } + if (c < 0x80) { + OUT1(c) + NEXT(1, 1) + continue; + } + + REQUIRE_INBUF(2) + c2 = IN2; + + if (c < 0xd8) { + /* johab hangul */ + unsigned char c_cho, c_jung, c_jong; + unsigned char i_cho, i_jung, i_jong; + + c_cho = (c >> 2) & 0x1f; + c_jung = ((c << 3) | c2 >> 5) & 0x1f; + c_jong = c2 & 0x1f; + + i_cho = johabidx_choseong[c_cho]; + i_jung = johabidx_jungseong[c_jung]; + i_jong = johabidx_jongseong[c_jong]; + + if (i_cho == NONE || i_jung == NONE || i_jong == NONE) + return 2; + + /* we don't use U+1100 hangul jamo yet. */ + if (i_cho == FILL) { + if (i_jung == FILL) { + if (i_jong == FILL) + OUT1(0x3000) + else + OUT1(0x3100 | + johabjamo_jongseong[c_jong]) + } + else { + if (i_jong == FILL) + OUT1(0x3100 | + johabjamo_jungseong[c_jung]) + else + return 2; + } + } else { + if (i_jung == FILL) { + if (i_jong == FILL) + OUT1(0x3100 | + johabjamo_choseong[c_cho]) + else + return 2; + } + else + OUT1(0xac00 + + i_cho * 588 + + i_jung * 28 + + (i_jong == FILL ? 0 : i_jong)) + } + NEXT(2, 1) + } else { + /* KS X 1001 except hangul jamos and syllables */ + if (c == 0xdf || c > 0xf9 || + c2 < 0x31 || (c2 >= 0x80 && c2 < 0x91) || + (c2 & 0x7f) == 0x7f || + (c == 0xda && (c2 >= 0xa1 && c2 <= 0xd3))) + return 2; + else { + unsigned char t1, t2; + + t1 = (c < 0xe0 ? 2 * (c - 0xd9) : + 2 * c - 0x197); + t2 = (c2 < 0x91 ? c2 - 0x31 : c2 - 0x43); + t1 = t1 + (t2 < 0x5e ? 0 : 1) + 0x21; + t2 = (t2 < 0x5e ? t2 : t2 - 0x5e) + 0x21; + + TRYMAP_DEC(ksx1001, **outbuf, t1, t2); + else return 2; + NEXT(2, 1) + } + } + } - return 0; + return 0; } #undef NONE #undef FILL Modified: python/branches/py3k/Modules/cjkcodecs/_codecs_tw.c ============================================================================== --- python/branches/py3k/Modules/cjkcodecs/_codecs_tw.c (original) +++ python/branches/py3k/Modules/cjkcodecs/_codecs_tw.c Sun May 9 17:52:27 2010 @@ -13,52 +13,52 @@ ENCODER(big5) { - while (inleft > 0) { - Py_UNICODE c = **inbuf; - DBCHAR code; - - if (c < 0x80) { - REQUIRE_OUTBUF(1) - **outbuf = (unsigned char)c; - NEXT(1, 1) - continue; - } - UCS4INVALID(c) - - REQUIRE_OUTBUF(2) - - TRYMAP_ENC(big5, code, c); - else return 1; - - OUT1(code >> 8) - OUT2(code & 0xFF) - NEXT(1, 2) - } + while (inleft > 0) { + Py_UNICODE c = **inbuf; + DBCHAR code; + + if (c < 0x80) { + REQUIRE_OUTBUF(1) + **outbuf = (unsigned char)c; + NEXT(1, 1) + continue; + } + UCS4INVALID(c) + + REQUIRE_OUTBUF(2) + + TRYMAP_ENC(big5, code, c); + else return 1; + + OUT1(code >> 8) + OUT2(code & 0xFF) + NEXT(1, 2) + } - return 0; + return 0; } DECODER(big5) { - while (inleft > 0) { - unsigned char c = IN1; + while (inleft > 0) { + unsigned char c = IN1; - REQUIRE_OUTBUF(1) + REQUIRE_OUTBUF(1) - if (c < 0x80) { - OUT1(c) - NEXT(1, 1) - continue; - } - - REQUIRE_INBUF(2) - TRYMAP_DEC(big5, **outbuf, c, IN2) { - NEXT(2, 1) - } - else return 2; - } + if (c < 0x80) { + OUT1(c) + NEXT(1, 1) + continue; + } + + REQUIRE_INBUF(2) + TRYMAP_DEC(big5, **outbuf, c, IN2) { + NEXT(2, 1) + } + else return 2; + } - return 0; + return 0; } @@ -68,53 +68,53 @@ ENCODER(cp950) { - while (inleft > 0) { - Py_UNICODE c = IN1; - DBCHAR code; - - if (c < 0x80) { - WRITE1((unsigned char)c) - NEXT(1, 1) - continue; - } - UCS4INVALID(c) - - REQUIRE_OUTBUF(2) - TRYMAP_ENC(cp950ext, code, c); - else TRYMAP_ENC(big5, code, c); - else return 1; - - OUT1(code >> 8) - OUT2(code & 0xFF) - NEXT(1, 2) - } + while (inleft > 0) { + Py_UNICODE c = IN1; + DBCHAR code; + + if (c < 0x80) { + WRITE1((unsigned char)c) + NEXT(1, 1) + continue; + } + UCS4INVALID(c) + + REQUIRE_OUTBUF(2) + TRYMAP_ENC(cp950ext, code, c); + else TRYMAP_ENC(big5, code, c); + else return 1; + + OUT1(code >> 8) + OUT2(code & 0xFF) + NEXT(1, 2) + } - return 0; + return 0; } DECODER(cp950) { - while (inleft > 0) { - unsigned char c = IN1; + while (inleft > 0) { + unsigned char c = IN1; - REQUIRE_OUTBUF(1) + REQUIRE_OUTBUF(1) - if (c < 0x80) { - OUT1(c) - NEXT(1, 1) - continue; - } + if (c < 0x80) { + OUT1(c) + NEXT(1, 1) + continue; + } - REQUIRE_INBUF(2) + REQUIRE_INBUF(2) - TRYMAP_DEC(cp950ext, **outbuf, c, IN2); - else TRYMAP_DEC(big5, **outbuf, c, IN2); - else return 2; + TRYMAP_DEC(cp950ext, **outbuf, c, IN2); + else TRYMAP_DEC(big5, **outbuf, c, IN2); + else return 2; - NEXT(2, 1) - } + NEXT(2, 1) + } - return 0; + return 0; } Modified: python/branches/py3k/Modules/cjkcodecs/alg_jisx0201.h ============================================================================== --- python/branches/py3k/Modules/cjkcodecs/alg_jisx0201.h (original) +++ python/branches/py3k/Modules/cjkcodecs/alg_jisx0201.h Sun May 9 17:52:27 2010 @@ -1,24 +1,24 @@ -#define JISX0201_R_ENCODE(c, assi) \ - if ((c) < 0x80 && (c) != 0x5c && (c) != 0x7e) \ - (assi) = (c); \ - else if ((c) == 0x00a5) (assi) = 0x5c; \ - else if ((c) == 0x203e) (assi) = 0x7e; -#define JISX0201_K_ENCODE(c, assi) \ - if ((c) >= 0xff61 && (c) <= 0xff9f) \ - (assi) = (c) - 0xfec0; -#define JISX0201_ENCODE(c, assi) \ - JISX0201_R_ENCODE(c, assi) \ - else JISX0201_K_ENCODE(c, assi) +#define JISX0201_R_ENCODE(c, assi) \ + if ((c) < 0x80 && (c) != 0x5c && (c) != 0x7e) \ + (assi) = (c); \ + else if ((c) == 0x00a5) (assi) = 0x5c; \ + else if ((c) == 0x203e) (assi) = 0x7e; +#define JISX0201_K_ENCODE(c, assi) \ + if ((c) >= 0xff61 && (c) <= 0xff9f) \ + (assi) = (c) - 0xfec0; +#define JISX0201_ENCODE(c, assi) \ + JISX0201_R_ENCODE(c, assi) \ + else JISX0201_K_ENCODE(c, assi) -#define JISX0201_R_DECODE(c, assi) \ - if ((c) < 0x5c) (assi) = (c); \ - else if ((c) == 0x5c) (assi) = 0x00a5; \ - else if ((c) < 0x7e) (assi) = (c); \ - else if ((c) == 0x7e) (assi) = 0x203e; \ - else if ((c) == 0x7f) (assi) = 0x7f; -#define JISX0201_K_DECODE(c, assi) \ - if ((c) >= 0xa1 && (c) <= 0xdf) \ - (assi) = 0xfec0 + (c); -#define JISX0201_DECODE(c, assi) \ - JISX0201_R_DECODE(c, assi) \ - else JISX0201_K_DECODE(c, assi) +#define JISX0201_R_DECODE(c, assi) \ + if ((c) < 0x5c) (assi) = (c); \ + else if ((c) == 0x5c) (assi) = 0x00a5; \ + else if ((c) < 0x7e) (assi) = (c); \ + else if ((c) == 0x7e) (assi) = 0x203e; \ + else if ((c) == 0x7f) (assi) = 0x7f; +#define JISX0201_K_DECODE(c, assi) \ + if ((c) >= 0xa1 && (c) <= 0xdf) \ + (assi) = 0xfec0 + (c); +#define JISX0201_DECODE(c, assi) \ + JISX0201_R_DECODE(c, assi) \ + else JISX0201_K_DECODE(c, assi) Modified: python/branches/py3k/Modules/cjkcodecs/cjkcodecs.h ============================================================================== --- python/branches/py3k/Modules/cjkcodecs/cjkcodecs.h (original) +++ python/branches/py3k/Modules/cjkcodecs/cjkcodecs.h Sun May 9 17:52:27 2010 @@ -13,12 +13,12 @@ /* a unicode "undefined" codepoint */ -#define UNIINV 0xFFFE +#define UNIINV 0xFFFE /* internal-use DBCS codepoints which aren't used by any charsets */ -#define NOCHAR 0xFFFF -#define MULTIC 0xFFFE -#define DBCINV 0xFFFD +#define NOCHAR 0xFFFF +#define MULTIC 0xFFFE +#define DBCINV 0xFFFD /* shorter macros to save source size of mapping tables */ #define U UNIINV @@ -27,94 +27,94 @@ #define D DBCINV struct dbcs_index { - const ucs2_t *map; - unsigned char bottom, top; + const ucs2_t *map; + unsigned char bottom, top; }; typedef struct dbcs_index decode_map; struct widedbcs_index { - const ucs4_t *map; - unsigned char bottom, top; + const ucs4_t *map; + unsigned char bottom, top; }; typedef struct widedbcs_index widedecode_map; struct unim_index { - const DBCHAR *map; - unsigned char bottom, top; + const DBCHAR *map; + unsigned char bottom, top; }; typedef struct unim_index encode_map; struct unim_index_bytebased { - const unsigned char *map; - unsigned char bottom, top; + const unsigned char *map; + unsigned char bottom, top; }; struct dbcs_map { - const char *charset; - const struct unim_index *encmap; - const struct dbcs_index *decmap; + const char *charset; + const struct unim_index *encmap; + const struct dbcs_index *decmap; }; struct pair_encodemap { - ucs4_t uniseq; - DBCHAR code; + ucs4_t uniseq; + DBCHAR code; }; static const MultibyteCodec *codec_list; static const struct dbcs_map *mapping_list; -#define CODEC_INIT(encoding) \ - static int encoding##_codec_init(const void *config) +#define CODEC_INIT(encoding) \ + static int encoding##_codec_init(const void *config) -#define ENCODER_INIT(encoding) \ - static int encoding##_encode_init( \ - MultibyteCodec_State *state, const void *config) -#define ENCODER(encoding) \ - static Py_ssize_t encoding##_encode( \ - MultibyteCodec_State *state, const void *config, \ - const Py_UNICODE **inbuf, Py_ssize_t inleft, \ - unsigned char **outbuf, Py_ssize_t outleft, int flags) -#define ENCODER_RESET(encoding) \ - static Py_ssize_t encoding##_encode_reset( \ - MultibyteCodec_State *state, const void *config, \ - unsigned char **outbuf, Py_ssize_t outleft) - -#define DECODER_INIT(encoding) \ - static int encoding##_decode_init( \ - MultibyteCodec_State *state, const void *config) -#define DECODER(encoding) \ - static Py_ssize_t encoding##_decode( \ - MultibyteCodec_State *state, const void *config, \ - const unsigned char **inbuf, Py_ssize_t inleft, \ - Py_UNICODE **outbuf, Py_ssize_t outleft) -#define DECODER_RESET(encoding) \ - static Py_ssize_t encoding##_decode_reset( \ - MultibyteCodec_State *state, const void *config) +#define ENCODER_INIT(encoding) \ + static int encoding##_encode_init( \ + MultibyteCodec_State *state, const void *config) +#define ENCODER(encoding) \ + static Py_ssize_t encoding##_encode( \ + MultibyteCodec_State *state, const void *config, \ + const Py_UNICODE **inbuf, Py_ssize_t inleft, \ + unsigned char **outbuf, Py_ssize_t outleft, int flags) +#define ENCODER_RESET(encoding) \ + static Py_ssize_t encoding##_encode_reset( \ + MultibyteCodec_State *state, const void *config, \ + unsigned char **outbuf, Py_ssize_t outleft) + +#define DECODER_INIT(encoding) \ + static int encoding##_decode_init( \ + MultibyteCodec_State *state, const void *config) +#define DECODER(encoding) \ + static Py_ssize_t encoding##_decode( \ + MultibyteCodec_State *state, const void *config, \ + const unsigned char **inbuf, Py_ssize_t inleft, \ + Py_UNICODE **outbuf, Py_ssize_t outleft) +#define DECODER_RESET(encoding) \ + static Py_ssize_t encoding##_decode_reset( \ + MultibyteCodec_State *state, const void *config) #if Py_UNICODE_SIZE == 4 -#define UCS4INVALID(code) \ - if ((code) > 0xFFFF) \ - return 1; +#define UCS4INVALID(code) \ + if ((code) > 0xFFFF) \ + return 1; #else -#define UCS4INVALID(code) \ - if (0) ; +#define UCS4INVALID(code) \ + if (0) ; #endif -#define NEXT_IN(i) \ - (*inbuf) += (i); \ - (inleft) -= (i); -#define NEXT_OUT(o) \ - (*outbuf) += (o); \ - (outleft) -= (o); -#define NEXT(i, o) \ - NEXT_IN(i) NEXT_OUT(o) - -#define REQUIRE_INBUF(n) \ - if (inleft < (n)) \ - return MBERR_TOOFEW; -#define REQUIRE_OUTBUF(n) \ - if (outleft < (n)) \ - return MBERR_TOOSMALL; +#define NEXT_IN(i) \ + (*inbuf) += (i); \ + (inleft) -= (i); +#define NEXT_OUT(o) \ + (*outbuf) += (o); \ + (outleft) -= (o); +#define NEXT(i, o) \ + NEXT_IN(i) NEXT_OUT(o) + +#define REQUIRE_INBUF(n) \ + if (inleft < (n)) \ + return MBERR_TOOFEW; +#define REQUIRE_OUTBUF(n) \ + if (outleft < (n)) \ + return MBERR_TOOSMALL; #define IN1 ((*inbuf)[0]) #define IN2 ((*inbuf)[1]) @@ -126,289 +126,289 @@ #define OUT3(c) ((*outbuf)[2]) = (c); #define OUT4(c) ((*outbuf)[3]) = (c); -#define WRITE1(c1) \ - REQUIRE_OUTBUF(1) \ - (*outbuf)[0] = (c1); -#define WRITE2(c1, c2) \ - REQUIRE_OUTBUF(2) \ - (*outbuf)[0] = (c1); \ - (*outbuf)[1] = (c2); -#define WRITE3(c1, c2, c3) \ - REQUIRE_OUTBUF(3) \ - (*outbuf)[0] = (c1); \ - (*outbuf)[1] = (c2); \ - (*outbuf)[2] = (c3); -#define WRITE4(c1, c2, c3, c4) \ - REQUIRE_OUTBUF(4) \ - (*outbuf)[0] = (c1); \ - (*outbuf)[1] = (c2); \ - (*outbuf)[2] = (c3); \ - (*outbuf)[3] = (c4); +#define WRITE1(c1) \ + REQUIRE_OUTBUF(1) \ + (*outbuf)[0] = (c1); +#define WRITE2(c1, c2) \ + REQUIRE_OUTBUF(2) \ + (*outbuf)[0] = (c1); \ + (*outbuf)[1] = (c2); +#define WRITE3(c1, c2, c3) \ + REQUIRE_OUTBUF(3) \ + (*outbuf)[0] = (c1); \ + (*outbuf)[1] = (c2); \ + (*outbuf)[2] = (c3); +#define WRITE4(c1, c2, c3, c4) \ + REQUIRE_OUTBUF(4) \ + (*outbuf)[0] = (c1); \ + (*outbuf)[1] = (c2); \ + (*outbuf)[2] = (c3); \ + (*outbuf)[3] = (c4); #if Py_UNICODE_SIZE == 2 -# define WRITEUCS4(c) \ - REQUIRE_OUTBUF(2) \ - (*outbuf)[0] = 0xd800 + (((c) - 0x10000) >> 10); \ - (*outbuf)[1] = 0xdc00 + (((c) - 0x10000) & 0x3ff); \ - NEXT_OUT(2) +# define WRITEUCS4(c) \ + REQUIRE_OUTBUF(2) \ + (*outbuf)[0] = 0xd800 + (((c) - 0x10000) >> 10); \ + (*outbuf)[1] = 0xdc00 + (((c) - 0x10000) & 0x3ff); \ + NEXT_OUT(2) #else -# define WRITEUCS4(c) \ - REQUIRE_OUTBUF(1) \ - **outbuf = (Py_UNICODE)(c); \ - NEXT_OUT(1) +# define WRITEUCS4(c) \ + REQUIRE_OUTBUF(1) \ + **outbuf = (Py_UNICODE)(c); \ + NEXT_OUT(1) #endif -#define _TRYMAP_ENC(m, assi, val) \ - ((m)->map != NULL && (val) >= (m)->bottom && \ - (val)<= (m)->top && ((assi) = (m)->map[(val) - \ - (m)->bottom]) != NOCHAR) -#define TRYMAP_ENC_COND(charset, assi, uni) \ - _TRYMAP_ENC(&charset##_encmap[(uni) >> 8], assi, (uni) & 0xff) -#define TRYMAP_ENC(charset, assi, uni) \ - if TRYMAP_ENC_COND(charset, assi, uni) - -#define _TRYMAP_DEC(m, assi, val) \ - ((m)->map != NULL && (val) >= (m)->bottom && \ - (val)<= (m)->top && ((assi) = (m)->map[(val) - \ - (m)->bottom]) != UNIINV) -#define TRYMAP_DEC(charset, assi, c1, c2) \ - if _TRYMAP_DEC(&charset##_decmap[c1], assi, c2) - -#define _TRYMAP_ENC_MPLANE(m, assplane, asshi, asslo, val) \ - ((m)->map != NULL && (val) >= (m)->bottom && \ - (val)<= (m)->top && \ - ((assplane) = (m)->map[((val) - (m)->bottom)*3]) != 0 && \ - (((asshi) = (m)->map[((val) - (m)->bottom)*3 + 1]), 1) && \ - (((asslo) = (m)->map[((val) - (m)->bottom)*3 + 2]), 1)) -#define TRYMAP_ENC_MPLANE(charset, assplane, asshi, asslo, uni) \ - if _TRYMAP_ENC_MPLANE(&charset##_encmap[(uni) >> 8], \ - assplane, asshi, asslo, (uni) & 0xff) -#define TRYMAP_DEC_MPLANE(charset, assi, plane, c1, c2) \ - if _TRYMAP_DEC(&charset##_decmap[plane][c1], assi, c2) +#define _TRYMAP_ENC(m, assi, val) \ + ((m)->map != NULL && (val) >= (m)->bottom && \ + (val)<= (m)->top && ((assi) = (m)->map[(val) - \ + (m)->bottom]) != NOCHAR) +#define TRYMAP_ENC_COND(charset, assi, uni) \ + _TRYMAP_ENC(&charset##_encmap[(uni) >> 8], assi, (uni) & 0xff) +#define TRYMAP_ENC(charset, assi, uni) \ + if TRYMAP_ENC_COND(charset, assi, uni) + +#define _TRYMAP_DEC(m, assi, val) \ + ((m)->map != NULL && (val) >= (m)->bottom && \ + (val)<= (m)->top && ((assi) = (m)->map[(val) - \ + (m)->bottom]) != UNIINV) +#define TRYMAP_DEC(charset, assi, c1, c2) \ + if _TRYMAP_DEC(&charset##_decmap[c1], assi, c2) + +#define _TRYMAP_ENC_MPLANE(m, assplane, asshi, asslo, val) \ + ((m)->map != NULL && (val) >= (m)->bottom && \ + (val)<= (m)->top && \ + ((assplane) = (m)->map[((val) - (m)->bottom)*3]) != 0 && \ + (((asshi) = (m)->map[((val) - (m)->bottom)*3 + 1]), 1) && \ + (((asslo) = (m)->map[((val) - (m)->bottom)*3 + 2]), 1)) +#define TRYMAP_ENC_MPLANE(charset, assplane, asshi, asslo, uni) \ + if _TRYMAP_ENC_MPLANE(&charset##_encmap[(uni) >> 8], \ + assplane, asshi, asslo, (uni) & 0xff) +#define TRYMAP_DEC_MPLANE(charset, assi, plane, c1, c2) \ + if _TRYMAP_DEC(&charset##_decmap[plane][c1], assi, c2) #if Py_UNICODE_SIZE == 2 -#define DECODE_SURROGATE(c) \ - if (c >> 10 == 0xd800 >> 10) { /* high surrogate */ \ - REQUIRE_INBUF(2) \ - if (IN2 >> 10 == 0xdc00 >> 10) { /* low surrogate */ \ - c = 0x10000 + ((ucs4_t)(c - 0xd800) << 10) + \ - ((ucs4_t)(IN2) - 0xdc00); \ - } \ - } -#define GET_INSIZE(c) ((c) > 0xffff ? 2 : 1) +#define DECODE_SURROGATE(c) \ + if (c >> 10 == 0xd800 >> 10) { /* high surrogate */ \ + REQUIRE_INBUF(2) \ + if (IN2 >> 10 == 0xdc00 >> 10) { /* low surrogate */ \ + c = 0x10000 + ((ucs4_t)(c - 0xd800) << 10) + \ + ((ucs4_t)(IN2) - 0xdc00); \ + } \ + } +#define GET_INSIZE(c) ((c) > 0xffff ? 2 : 1) #else #define DECODE_SURROGATE(c) {;} -#define GET_INSIZE(c) 1 +#define GET_INSIZE(c) 1 #endif #define BEGIN_MAPPINGS_LIST static const struct dbcs_map _mapping_list[] = { #define MAPPING_ENCONLY(enc) {#enc, (void*)enc##_encmap, NULL}, #define MAPPING_DECONLY(enc) {#enc, NULL, (void*)enc##_decmap}, #define MAPPING_ENCDEC(enc) {#enc, (void*)enc##_encmap, (void*)enc##_decmap}, -#define END_MAPPINGS_LIST \ - {"", NULL, NULL} }; \ - static const struct dbcs_map *mapping_list = \ - (const struct dbcs_map *)_mapping_list; +#define END_MAPPINGS_LIST \ + {"", NULL, NULL} }; \ + static const struct dbcs_map *mapping_list = \ + (const struct dbcs_map *)_mapping_list; #define BEGIN_CODECS_LIST static const MultibyteCodec _codec_list[] = { -#define _STATEFUL_METHODS(enc) \ - enc##_encode, \ - enc##_encode_init, \ - enc##_encode_reset, \ - enc##_decode, \ - enc##_decode_init, \ - enc##_decode_reset, -#define _STATELESS_METHODS(enc) \ - enc##_encode, NULL, NULL, \ - enc##_decode, NULL, NULL, -#define CODEC_STATEFUL(enc) { \ - #enc, NULL, NULL, \ - _STATEFUL_METHODS(enc) \ +#define _STATEFUL_METHODS(enc) \ + enc##_encode, \ + enc##_encode_init, \ + enc##_encode_reset, \ + enc##_decode, \ + enc##_decode_init, \ + enc##_decode_reset, +#define _STATELESS_METHODS(enc) \ + enc##_encode, NULL, NULL, \ + enc##_decode, NULL, NULL, +#define CODEC_STATEFUL(enc) { \ + #enc, NULL, NULL, \ + _STATEFUL_METHODS(enc) \ }, -#define CODEC_STATELESS(enc) { \ - #enc, NULL, NULL, \ - _STATELESS_METHODS(enc) \ +#define CODEC_STATELESS(enc) { \ + #enc, NULL, NULL, \ + _STATELESS_METHODS(enc) \ }, -#define CODEC_STATELESS_WINIT(enc) { \ - #enc, NULL, \ - enc##_codec_init, \ - _STATELESS_METHODS(enc) \ +#define CODEC_STATELESS_WINIT(enc) { \ + #enc, NULL, \ + enc##_codec_init, \ + _STATELESS_METHODS(enc) \ }, -#define END_CODECS_LIST \ - {"", NULL,} }; \ - static const MultibyteCodec *codec_list = \ - (const MultibyteCodec *)_codec_list; +#define END_CODECS_LIST \ + {"", NULL,} }; \ + static const MultibyteCodec *codec_list = \ + (const MultibyteCodec *)_codec_list; static PyObject * getmultibytecodec(void) { - static PyObject *cofunc = NULL; + static PyObject *cofunc = NULL; - if (cofunc == NULL) { - PyObject *mod = PyImport_ImportModuleNoBlock("_multibytecodec"); - if (mod == NULL) - return NULL; - cofunc = PyObject_GetAttrString(mod, "__create_codec"); - Py_DECREF(mod); - } - return cofunc; + if (cofunc == NULL) { + PyObject *mod = PyImport_ImportModuleNoBlock("_multibytecodec"); + if (mod == NULL) + return NULL; + cofunc = PyObject_GetAttrString(mod, "__create_codec"); + Py_DECREF(mod); + } + return cofunc; } static PyObject * getcodec(PyObject *self, PyObject *encoding) { - PyObject *codecobj, *r, *cofunc; - const MultibyteCodec *codec; - const char *enc; - - if (!PyUnicode_Check(encoding)) { - PyErr_SetString(PyExc_TypeError, - "encoding name must be a string."); - return NULL; - } - enc = _PyUnicode_AsString(encoding); - if (enc == NULL) - return NULL; - - cofunc = getmultibytecodec(); - if (cofunc == NULL) - return NULL; - - for (codec = codec_list; codec->encoding[0]; codec++) - if (strcmp(codec->encoding, enc) == 0) - break; - - if (codec->encoding[0] == '\0') { - PyErr_SetString(PyExc_LookupError, - "no such codec is supported."); - return NULL; - } - - codecobj = PyCapsule_New((void *)codec, PyMultibyteCodec_CAPSULE_NAME, NULL); - if (codecobj == NULL) - return NULL; + PyObject *codecobj, *r, *cofunc; + const MultibyteCodec *codec; + const char *enc; + + if (!PyUnicode_Check(encoding)) { + PyErr_SetString(PyExc_TypeError, + "encoding name must be a string."); + return NULL; + } + enc = _PyUnicode_AsString(encoding); + if (enc == NULL) + return NULL; + + cofunc = getmultibytecodec(); + if (cofunc == NULL) + return NULL; + + for (codec = codec_list; codec->encoding[0]; codec++) + if (strcmp(codec->encoding, enc) == 0) + break; + + if (codec->encoding[0] == '\0') { + PyErr_SetString(PyExc_LookupError, + "no such codec is supported."); + return NULL; + } + + codecobj = PyCapsule_New((void *)codec, PyMultibyteCodec_CAPSULE_NAME, NULL); + if (codecobj == NULL) + return NULL; - r = PyObject_CallFunctionObjArgs(cofunc, codecobj, NULL); - Py_DECREF(codecobj); + r = PyObject_CallFunctionObjArgs(cofunc, codecobj, NULL); + Py_DECREF(codecobj); - return r; + return r; } static struct PyMethodDef __methods[] = { - {"getcodec", (PyCFunction)getcodec, METH_O, ""}, - {NULL, NULL}, + {"getcodec", (PyCFunction)getcodec, METH_O, ""}, + {NULL, NULL}, }; static int register_maps(PyObject *module) { - const struct dbcs_map *h; + const struct dbcs_map *h; - for (h = mapping_list; h->charset[0] != '\0'; h++) { - char mhname[256] = "__map_"; - int r; - strcpy(mhname + sizeof("__map_") - 1, h->charset); - r = PyModule_AddObject(module, mhname, - PyCapsule_New((void *)h, PyMultibyteCodec_CAPSULE_NAME, NULL)); - if (r == -1) - return -1; - } - return 0; + for (h = mapping_list; h->charset[0] != '\0'; h++) { + char mhname[256] = "__map_"; + int r; + strcpy(mhname + sizeof("__map_") - 1, h->charset); + r = PyModule_AddObject(module, mhname, + PyCapsule_New((void *)h, PyMultibyteCodec_CAPSULE_NAME, NULL)); + if (r == -1) + return -1; + } + return 0; } #ifdef USING_BINARY_PAIR_SEARCH static DBCHAR find_pairencmap(ucs2_t body, ucs2_t modifier, - const struct pair_encodemap *haystack, int haystacksize) + const struct pair_encodemap *haystack, int haystacksize) { - int pos, min, max; - ucs4_t value = body << 16 | modifier; + int pos, min, max; + ucs4_t value = body << 16 | modifier; - min = 0; - max = haystacksize; + min = 0; + max = haystacksize; - for (pos = haystacksize >> 1; min != max; pos = (min + max) >> 1) - if (value < haystack[pos].uniseq) { - if (max == pos) break; - else max = pos; - } - else if (value > haystack[pos].uniseq) { - if (min == pos) break; - else min = pos; - } - else - break; - - if (value == haystack[pos].uniseq) - return haystack[pos].code; - else - return DBCINV; + for (pos = haystacksize >> 1; min != max; pos = (min + max) >> 1) + if (value < haystack[pos].uniseq) { + if (max == pos) break; + else max = pos; + } + else if (value > haystack[pos].uniseq) { + if (min == pos) break; + else min = pos; + } + else + break; + + if (value == haystack[pos].uniseq) + return haystack[pos].code; + else + return DBCINV; } #endif #ifdef USING_IMPORTED_MAPS #define IMPORT_MAP(locale, charset, encmap, decmap) \ - importmap("_codecs_" #locale, "__map_" #charset, \ - (const void**)encmap, (const void**)decmap) + importmap("_codecs_" #locale, "__map_" #charset, \ + (const void**)encmap, (const void**)decmap) static int importmap(const char *modname, const char *symbol, - const void **encmap, const void **decmap) + const void **encmap, const void **decmap) { - PyObject *o, *mod; + PyObject *o, *mod; - mod = PyImport_ImportModule((char *)modname); - if (mod == NULL) - return -1; - - o = PyObject_GetAttrString(mod, (char*)symbol); - if (o == NULL) - goto errorexit; - else if (!PyCapsule_IsValid(o, PyMultibyteCodec_CAPSULE_NAME)) { - PyErr_SetString(PyExc_ValueError, - "map data must be a Capsule."); - goto errorexit; - } - else { - struct dbcs_map *map; - map = PyCapsule_GetPointer(o, PyMultibyteCodec_CAPSULE_NAME); - if (encmap != NULL) - *encmap = map->encmap; - if (decmap != NULL) - *decmap = map->decmap; - Py_DECREF(o); - } + mod = PyImport_ImportModule((char *)modname); + if (mod == NULL) + return -1; + + o = PyObject_GetAttrString(mod, (char*)symbol); + if (o == NULL) + goto errorexit; + else if (!PyCapsule_IsValid(o, PyMultibyteCodec_CAPSULE_NAME)) { + PyErr_SetString(PyExc_ValueError, + "map data must be a Capsule."); + goto errorexit; + } + else { + struct dbcs_map *map; + map = PyCapsule_GetPointer(o, PyMultibyteCodec_CAPSULE_NAME); + if (encmap != NULL) + *encmap = map->encmap; + if (decmap != NULL) + *decmap = map->decmap; + Py_DECREF(o); + } - Py_DECREF(mod); - return 0; + Py_DECREF(mod); + return 0; errorexit: - Py_DECREF(mod); - return -1; + Py_DECREF(mod); + return -1; } #endif -#define I_AM_A_MODULE_FOR(loc) \ - static struct PyModuleDef __module = { \ - PyModuleDef_HEAD_INIT, \ - "_codecs_"#loc, \ - NULL, \ - 0, \ - __methods, \ - NULL, \ - NULL, \ - NULL, \ - NULL \ - }; \ - PyObject* \ - PyInit__codecs_##loc(void) \ - { \ - PyObject *m = PyModule_Create(&__module); \ - if (m != NULL) \ - (void)register_maps(m); \ - return m; \ - } +#define I_AM_A_MODULE_FOR(loc) \ + static struct PyModuleDef __module = { \ + PyModuleDef_HEAD_INIT, \ + "_codecs_"#loc, \ + NULL, \ + 0, \ + __methods, \ + NULL, \ + NULL, \ + NULL, \ + NULL \ + }; \ + PyObject* \ + PyInit__codecs_##loc(void) \ + { \ + PyObject *m = PyModule_Create(&__module); \ + if (m != NULL) \ + (void)register_maps(m); \ + return m; \ + } #endif Modified: python/branches/py3k/Modules/cjkcodecs/emu_jisx0213_2000.h ============================================================================== --- python/branches/py3k/Modules/cjkcodecs/emu_jisx0213_2000.h (original) +++ python/branches/py3k/Modules/cjkcodecs/emu_jisx0213_2000.h Sun May 9 17:52:27 2010 @@ -5,39 +5,39 @@ #define EMULATE_JISX0213_2000_ENCODE_INVALID 1 #endif -#define EMULATE_JISX0213_2000_ENCODE_BMP(assi, c) \ - if (config == (void *)2000 && ( \ - (c) == 0x9B1C || (c) == 0x4FF1 || \ - (c) == 0x525D || (c) == 0x541E || \ - (c) == 0x5653 || (c) == 0x59F8 || \ - (c) == 0x5C5B || (c) == 0x5E77 || \ - (c) == 0x7626 || (c) == 0x7E6B)) \ - return EMULATE_JISX0213_2000_ENCODE_INVALID; \ - else if (config == (void *)2000 && (c) == 0x9B1D) \ - (assi) = 0x8000 | 0x7d3b; \ +#define EMULATE_JISX0213_2000_ENCODE_BMP(assi, c) \ + if (config == (void *)2000 && ( \ + (c) == 0x9B1C || (c) == 0x4FF1 || \ + (c) == 0x525D || (c) == 0x541E || \ + (c) == 0x5653 || (c) == 0x59F8 || \ + (c) == 0x5C5B || (c) == 0x5E77 || \ + (c) == 0x7626 || (c) == 0x7E6B)) \ + return EMULATE_JISX0213_2000_ENCODE_INVALID; \ + else if (config == (void *)2000 && (c) == 0x9B1D) \ + (assi) = 0x8000 | 0x7d3b; \ -#define EMULATE_JISX0213_2000_ENCODE_EMP(assi, c) \ - if (config == (void *)2000 && (c) == 0x20B9F) \ - return EMULATE_JISX0213_2000_ENCODE_INVALID; +#define EMULATE_JISX0213_2000_ENCODE_EMP(assi, c) \ + if (config == (void *)2000 && (c) == 0x20B9F) \ + return EMULATE_JISX0213_2000_ENCODE_INVALID; #ifndef EMULATE_JISX0213_2000_DECODE_INVALID #define EMULATE_JISX0213_2000_DECODE_INVALID 2 #endif -#define EMULATE_JISX0213_2000_DECODE_PLANE1(assi, c1, c2) \ - if (config == (void *)2000 && \ - (((c1) == 0x2E && (c2) == 0x21) || \ - ((c1) == 0x2F && (c2) == 0x7E) || \ - ((c1) == 0x4F && (c2) == 0x54) || \ - ((c1) == 0x4F && (c2) == 0x7E) || \ - ((c1) == 0x74 && (c2) == 0x27) || \ - ((c1) == 0x7E && (c2) == 0x7A) || \ - ((c1) == 0x7E && (c2) == 0x7B) || \ - ((c1) == 0x7E && (c2) == 0x7C) || \ - ((c1) == 0x7E && (c2) == 0x7D) || \ - ((c1) == 0x7E && (c2) == 0x7E))) \ - return EMULATE_JISX0213_2000_DECODE_INVALID; +#define EMULATE_JISX0213_2000_DECODE_PLANE1(assi, c1, c2) \ + if (config == (void *)2000 && \ + (((c1) == 0x2E && (c2) == 0x21) || \ + ((c1) == 0x2F && (c2) == 0x7E) || \ + ((c1) == 0x4F && (c2) == 0x54) || \ + ((c1) == 0x4F && (c2) == 0x7E) || \ + ((c1) == 0x74 && (c2) == 0x27) || \ + ((c1) == 0x7E && (c2) == 0x7A) || \ + ((c1) == 0x7E && (c2) == 0x7B) || \ + ((c1) == 0x7E && (c2) == 0x7C) || \ + ((c1) == 0x7E && (c2) == 0x7D) || \ + ((c1) == 0x7E && (c2) == 0x7E))) \ + return EMULATE_JISX0213_2000_DECODE_INVALID; -#define EMULATE_JISX0213_2000_DECODE_PLANE2(assi, c1, c2) \ - if (config == (void *)2000 && (c1) == 0x7D && (c2) == 0x3B) \ - (assi) = 0x9B1D; +#define EMULATE_JISX0213_2000_DECODE_PLANE2(assi, c1, c2) \ + if (config == (void *)2000 && (c1) == 0x7D && (c2) == 0x3B) \ + (assi) = 0x9B1D; Modified: python/branches/py3k/Modules/cjkcodecs/multibytecodec.c ============================================================================== --- python/branches/py3k/Modules/cjkcodecs/multibytecodec.c (original) +++ python/branches/py3k/Modules/cjkcodecs/multibytecodec.c Sun May 9 17:52:27 2010 @@ -45,179 +45,179 @@ static char *streamkwarglist[] = {"stream", "errors", NULL}; static PyObject *multibytecodec_encode(MultibyteCodec *, - MultibyteCodec_State *, const Py_UNICODE **, Py_ssize_t, - PyObject *, int); + MultibyteCodec_State *, const Py_UNICODE **, Py_ssize_t, + PyObject *, int); -#define MBENC_RESET MBENC_MAX<<1 /* reset after an encoding session */ +#define MBENC_RESET MBENC_MAX<<1 /* reset after an encoding session */ static PyObject * make_tuple(PyObject *object, Py_ssize_t len) { - PyObject *v, *w; + PyObject *v, *w; - if (object == NULL) - return NULL; + if (object == NULL) + return NULL; - v = PyTuple_New(2); - if (v == NULL) { - Py_DECREF(object); - return NULL; - } - PyTuple_SET_ITEM(v, 0, object); - - w = PyLong_FromSsize_t(len); - if (w == NULL) { - Py_DECREF(v); - return NULL; - } - PyTuple_SET_ITEM(v, 1, w); + v = PyTuple_New(2); + if (v == NULL) { + Py_DECREF(object); + return NULL; + } + PyTuple_SET_ITEM(v, 0, object); + + w = PyLong_FromSsize_t(len); + if (w == NULL) { + Py_DECREF(v); + return NULL; + } + PyTuple_SET_ITEM(v, 1, w); - return v; + return v; } static PyObject * internal_error_callback(const char *errors) { - if (errors == NULL || strcmp(errors, "strict") == 0) - return ERROR_STRICT; - else if (strcmp(errors, "ignore") == 0) - return ERROR_IGNORE; - else if (strcmp(errors, "replace") == 0) - return ERROR_REPLACE; - else - return PyUnicode_FromString(errors); + if (errors == NULL || strcmp(errors, "strict") == 0) + return ERROR_STRICT; + else if (strcmp(errors, "ignore") == 0) + return ERROR_IGNORE; + else if (strcmp(errors, "replace") == 0) + return ERROR_REPLACE; + else + return PyUnicode_FromString(errors); } static PyObject * call_error_callback(PyObject *errors, PyObject *exc) { - PyObject *args, *cb, *r; - const char *str; + PyObject *args, *cb, *r; + const char *str; - assert(PyUnicode_Check(errors)); - str = _PyUnicode_AsString(errors); - if (str == NULL) - return NULL; - cb = PyCodec_LookupError(str); - if (cb == NULL) - return NULL; - - args = PyTuple_New(1); - if (args == NULL) { - Py_DECREF(cb); - return NULL; - } - - PyTuple_SET_ITEM(args, 0, exc); - Py_INCREF(exc); - - r = PyObject_CallObject(cb, args); - Py_DECREF(args); - Py_DECREF(cb); - return r; + assert(PyUnicode_Check(errors)); + str = _PyUnicode_AsString(errors); + if (str == NULL) + return NULL; + cb = PyCodec_LookupError(str); + if (cb == NULL) + return NULL; + + args = PyTuple_New(1); + if (args == NULL) { + Py_DECREF(cb); + return NULL; + } + + PyTuple_SET_ITEM(args, 0, exc); + Py_INCREF(exc); + + r = PyObject_CallObject(cb, args); + Py_DECREF(args); + Py_DECREF(cb); + return r; } static PyObject * codecctx_errors_get(MultibyteStatefulCodecContext *self) { - const char *errors; + const char *errors; - if (self->errors == ERROR_STRICT) - errors = "strict"; - else if (self->errors == ERROR_IGNORE) - errors = "ignore"; - else if (self->errors == ERROR_REPLACE) - errors = "replace"; - else { - Py_INCREF(self->errors); - return self->errors; - } + if (self->errors == ERROR_STRICT) + errors = "strict"; + else if (self->errors == ERROR_IGNORE) + errors = "ignore"; + else if (self->errors == ERROR_REPLACE) + errors = "replace"; + else { + Py_INCREF(self->errors); + return self->errors; + } - return PyUnicode_FromString(errors); + return PyUnicode_FromString(errors); } static int codecctx_errors_set(MultibyteStatefulCodecContext *self, PyObject *value, - void *closure) + void *closure) { - PyObject *cb; - const char *str; + PyObject *cb; + const char *str; - if (!PyUnicode_Check(value)) { - PyErr_SetString(PyExc_TypeError, "errors must be a string"); - return -1; - } - - str = _PyUnicode_AsString(value); - if (str == NULL) - return -1; - - cb = internal_error_callback(str); - if (cb == NULL) - return -1; - - ERROR_DECREF(self->errors); - self->errors = cb; - return 0; + if (!PyUnicode_Check(value)) { + PyErr_SetString(PyExc_TypeError, "errors must be a string"); + return -1; + } + + str = _PyUnicode_AsString(value); + if (str == NULL) + return -1; + + cb = internal_error_callback(str); + if (cb == NULL) + return -1; + + ERROR_DECREF(self->errors); + self->errors = cb; + return 0; } /* This getset handlers list is used by all the stateful codec objects */ static PyGetSetDef codecctx_getsets[] = { - {"errors", (getter)codecctx_errors_get, - (setter)codecctx_errors_set, - PyDoc_STR("how to treat errors")}, - {NULL,} + {"errors", (getter)codecctx_errors_get, + (setter)codecctx_errors_set, + PyDoc_STR("how to treat errors")}, + {NULL,} }; static int expand_encodebuffer(MultibyteEncodeBuffer *buf, Py_ssize_t esize) { - Py_ssize_t orgpos, orgsize, incsize; + Py_ssize_t orgpos, orgsize, incsize; - orgpos = (Py_ssize_t)((char *)buf->outbuf - - PyBytes_AS_STRING(buf->outobj)); - orgsize = PyBytes_GET_SIZE(buf->outobj); - incsize = (esize < (orgsize >> 1) ? (orgsize >> 1) | 1 : esize); + orgpos = (Py_ssize_t)((char *)buf->outbuf - + PyBytes_AS_STRING(buf->outobj)); + orgsize = PyBytes_GET_SIZE(buf->outobj); + incsize = (esize < (orgsize >> 1) ? (orgsize >> 1) | 1 : esize); - if (orgsize > PY_SSIZE_T_MAX - incsize) - return -1; + if (orgsize > PY_SSIZE_T_MAX - incsize) + return -1; - if (_PyBytes_Resize(&buf->outobj, orgsize + incsize) == -1) - return -1; + if (_PyBytes_Resize(&buf->outobj, orgsize + incsize) == -1) + return -1; - buf->outbuf = (unsigned char *)PyBytes_AS_STRING(buf->outobj) +orgpos; - buf->outbuf_end = (unsigned char *)PyBytes_AS_STRING(buf->outobj) - + PyBytes_GET_SIZE(buf->outobj); + buf->outbuf = (unsigned char *)PyBytes_AS_STRING(buf->outobj) +orgpos; + buf->outbuf_end = (unsigned char *)PyBytes_AS_STRING(buf->outobj) + + PyBytes_GET_SIZE(buf->outobj); - return 0; + return 0; } -#define REQUIRE_ENCODEBUFFER(buf, s) { \ - if ((s) < 1 || (buf)->outbuf + (s) > (buf)->outbuf_end) \ - if (expand_encodebuffer(buf, s) == -1) \ - goto errorexit; \ +#define REQUIRE_ENCODEBUFFER(buf, s) { \ + if ((s) < 1 || (buf)->outbuf + (s) > (buf)->outbuf_end) \ + if (expand_encodebuffer(buf, s) == -1) \ + goto errorexit; \ } static int expand_decodebuffer(MultibyteDecodeBuffer *buf, Py_ssize_t esize) { - Py_ssize_t orgpos, orgsize; + Py_ssize_t orgpos, orgsize; - orgpos = (Py_ssize_t)(buf->outbuf - PyUnicode_AS_UNICODE(buf->outobj)); - orgsize = PyUnicode_GET_SIZE(buf->outobj); - if (PyUnicode_Resize(&buf->outobj, orgsize + ( - esize < (orgsize >> 1) ? (orgsize >> 1) | 1 : esize)) == -1) - return -1; - - buf->outbuf = PyUnicode_AS_UNICODE(buf->outobj) + orgpos; - buf->outbuf_end = PyUnicode_AS_UNICODE(buf->outobj) - + PyUnicode_GET_SIZE(buf->outobj); - - return 0; -} -#define REQUIRE_DECODEBUFFER(buf, s) { \ - if ((s) < 1 || (buf)->outbuf + (s) > (buf)->outbuf_end) \ - if (expand_decodebuffer(buf, s) == -1) \ - goto errorexit; \ + orgpos = (Py_ssize_t)(buf->outbuf - PyUnicode_AS_UNICODE(buf->outobj)); + orgsize = PyUnicode_GET_SIZE(buf->outobj); + if (PyUnicode_Resize(&buf->outobj, orgsize + ( + esize < (orgsize >> 1) ? (orgsize >> 1) | 1 : esize)) == -1) + return -1; + + buf->outbuf = PyUnicode_AS_UNICODE(buf->outobj) + orgpos; + buf->outbuf_end = PyUnicode_AS_UNICODE(buf->outobj) + + PyUnicode_GET_SIZE(buf->outobj); + + return 0; +} +#define REQUIRE_DECODEBUFFER(buf, s) { \ + if ((s) < 1 || (buf)->outbuf + (s) > (buf)->outbuf_end) \ + if (expand_decodebuffer(buf, s) == -1) \ + goto errorexit; \ } @@ -227,504 +227,504 @@ static int multibytecodec_encerror(MultibyteCodec *codec, - MultibyteCodec_State *state, - MultibyteEncodeBuffer *buf, - PyObject *errors, Py_ssize_t e) -{ - PyObject *retobj = NULL, *retstr = NULL, *tobj; - Py_ssize_t retstrsize, newpos; - Py_ssize_t esize, start, end; - const char *reason; - - if (e > 0) { - reason = "illegal multibyte sequence"; - esize = e; - } - else { - switch (e) { - case MBERR_TOOSMALL: - REQUIRE_ENCODEBUFFER(buf, -1); - return 0; /* retry it */ - case MBERR_TOOFEW: - reason = "incomplete multibyte sequence"; - esize = (Py_ssize_t)(buf->inbuf_end - buf->inbuf); - break; - case MBERR_INTERNAL: - PyErr_SetString(PyExc_RuntimeError, - "internal codec error"); - return -1; - default: - PyErr_SetString(PyExc_RuntimeError, - "unknown runtime error"); - return -1; - } - } - - if (errors == ERROR_REPLACE) { - const Py_UNICODE replchar = '?', *inbuf = &replchar; - Py_ssize_t r; - - for (;;) { - Py_ssize_t outleft; - - outleft = (Py_ssize_t)(buf->outbuf_end - buf->outbuf); - r = codec->encode(state, codec->config, &inbuf, 1, - &buf->outbuf, outleft, 0); - if (r == MBERR_TOOSMALL) { - REQUIRE_ENCODEBUFFER(buf, -1); - continue; - } - else - break; - } - - if (r != 0) { - REQUIRE_ENCODEBUFFER(buf, 1); - *buf->outbuf++ = '?'; - } - } - if (errors == ERROR_IGNORE || errors == ERROR_REPLACE) { - buf->inbuf += esize; - return 0; - } - - start = (Py_ssize_t)(buf->inbuf - buf->inbuf_top); - end = start + esize; - - /* use cached exception object if available */ - if (buf->excobj == NULL) { - buf->excobj = PyUnicodeEncodeError_Create(codec->encoding, - buf->inbuf_top, - buf->inbuf_end - buf->inbuf_top, - start, end, reason); - if (buf->excobj == NULL) - goto errorexit; - } - else - if (PyUnicodeEncodeError_SetStart(buf->excobj, start) != 0 || - PyUnicodeEncodeError_SetEnd(buf->excobj, end) != 0 || - PyUnicodeEncodeError_SetReason(buf->excobj, reason) != 0) - goto errorexit; - - if (errors == ERROR_STRICT) { - PyCodec_StrictErrors(buf->excobj); - goto errorexit; - } - - retobj = call_error_callback(errors, buf->excobj); - if (retobj == NULL) - goto errorexit; - - if (!PyTuple_Check(retobj) || PyTuple_GET_SIZE(retobj) != 2 || - !PyUnicode_Check((tobj = PyTuple_GET_ITEM(retobj, 0))) || - !PyLong_Check(PyTuple_GET_ITEM(retobj, 1))) { - PyErr_SetString(PyExc_TypeError, - "encoding error handler must return " - "(unicode, int) tuple"); - goto errorexit; - } - - { - const Py_UNICODE *uraw = PyUnicode_AS_UNICODE(tobj); - - retstr = multibytecodec_encode(codec, state, &uraw, - PyUnicode_GET_SIZE(tobj), ERROR_STRICT, - MBENC_FLUSH); - if (retstr == NULL) - goto errorexit; - } - - assert(PyBytes_Check(retstr)); - retstrsize = PyBytes_GET_SIZE(retstr); - REQUIRE_ENCODEBUFFER(buf, retstrsize); - - memcpy(buf->outbuf, PyBytes_AS_STRING(retstr), retstrsize); - buf->outbuf += retstrsize; - - newpos = PyLong_AsSsize_t(PyTuple_GET_ITEM(retobj, 1)); - if (newpos < 0 && !PyErr_Occurred()) - newpos += (Py_ssize_t)(buf->inbuf_end - buf->inbuf_top); - if (newpos < 0 || buf->inbuf_top + newpos > buf->inbuf_end) { - PyErr_Clear(); - PyErr_Format(PyExc_IndexError, - "position %zd from error handler out of bounds", - newpos); - goto errorexit; - } - buf->inbuf = buf->inbuf_top + newpos; - - Py_DECREF(retobj); - Py_DECREF(retstr); - return 0; + MultibyteCodec_State *state, + MultibyteEncodeBuffer *buf, + PyObject *errors, Py_ssize_t e) +{ + PyObject *retobj = NULL, *retstr = NULL, *tobj; + Py_ssize_t retstrsize, newpos; + Py_ssize_t esize, start, end; + const char *reason; + + if (e > 0) { + reason = "illegal multibyte sequence"; + esize = e; + } + else { + switch (e) { + case MBERR_TOOSMALL: + REQUIRE_ENCODEBUFFER(buf, -1); + return 0; /* retry it */ + case MBERR_TOOFEW: + reason = "incomplete multibyte sequence"; + esize = (Py_ssize_t)(buf->inbuf_end - buf->inbuf); + break; + case MBERR_INTERNAL: + PyErr_SetString(PyExc_RuntimeError, + "internal codec error"); + return -1; + default: + PyErr_SetString(PyExc_RuntimeError, + "unknown runtime error"); + return -1; + } + } + + if (errors == ERROR_REPLACE) { + const Py_UNICODE replchar = '?', *inbuf = &replchar; + Py_ssize_t r; + + for (;;) { + Py_ssize_t outleft; + + outleft = (Py_ssize_t)(buf->outbuf_end - buf->outbuf); + r = codec->encode(state, codec->config, &inbuf, 1, + &buf->outbuf, outleft, 0); + if (r == MBERR_TOOSMALL) { + REQUIRE_ENCODEBUFFER(buf, -1); + continue; + } + else + break; + } + + if (r != 0) { + REQUIRE_ENCODEBUFFER(buf, 1); + *buf->outbuf++ = '?'; + } + } + if (errors == ERROR_IGNORE || errors == ERROR_REPLACE) { + buf->inbuf += esize; + return 0; + } + + start = (Py_ssize_t)(buf->inbuf - buf->inbuf_top); + end = start + esize; + + /* use cached exception object if available */ + if (buf->excobj == NULL) { + buf->excobj = PyUnicodeEncodeError_Create(codec->encoding, + buf->inbuf_top, + buf->inbuf_end - buf->inbuf_top, + start, end, reason); + if (buf->excobj == NULL) + goto errorexit; + } + else + if (PyUnicodeEncodeError_SetStart(buf->excobj, start) != 0 || + PyUnicodeEncodeError_SetEnd(buf->excobj, end) != 0 || + PyUnicodeEncodeError_SetReason(buf->excobj, reason) != 0) + goto errorexit; + + if (errors == ERROR_STRICT) { + PyCodec_StrictErrors(buf->excobj); + goto errorexit; + } + + retobj = call_error_callback(errors, buf->excobj); + if (retobj == NULL) + goto errorexit; + + if (!PyTuple_Check(retobj) || PyTuple_GET_SIZE(retobj) != 2 || + !PyUnicode_Check((tobj = PyTuple_GET_ITEM(retobj, 0))) || + !PyLong_Check(PyTuple_GET_ITEM(retobj, 1))) { + PyErr_SetString(PyExc_TypeError, + "encoding error handler must return " + "(unicode, int) tuple"); + goto errorexit; + } + + { + const Py_UNICODE *uraw = PyUnicode_AS_UNICODE(tobj); + + retstr = multibytecodec_encode(codec, state, &uraw, + PyUnicode_GET_SIZE(tobj), ERROR_STRICT, + MBENC_FLUSH); + if (retstr == NULL) + goto errorexit; + } + + assert(PyBytes_Check(retstr)); + retstrsize = PyBytes_GET_SIZE(retstr); + REQUIRE_ENCODEBUFFER(buf, retstrsize); + + memcpy(buf->outbuf, PyBytes_AS_STRING(retstr), retstrsize); + buf->outbuf += retstrsize; + + newpos = PyLong_AsSsize_t(PyTuple_GET_ITEM(retobj, 1)); + if (newpos < 0 && !PyErr_Occurred()) + newpos += (Py_ssize_t)(buf->inbuf_end - buf->inbuf_top); + if (newpos < 0 || buf->inbuf_top + newpos > buf->inbuf_end) { + PyErr_Clear(); + PyErr_Format(PyExc_IndexError, + "position %zd from error handler out of bounds", + newpos); + goto errorexit; + } + buf->inbuf = buf->inbuf_top + newpos; + + Py_DECREF(retobj); + Py_DECREF(retstr); + return 0; errorexit: - Py_XDECREF(retobj); - Py_XDECREF(retstr); - return -1; + Py_XDECREF(retobj); + Py_XDECREF(retstr); + return -1; } static int multibytecodec_decerror(MultibyteCodec *codec, - MultibyteCodec_State *state, - MultibyteDecodeBuffer *buf, - PyObject *errors, Py_ssize_t e) -{ - PyObject *retobj = NULL, *retuni = NULL; - Py_ssize_t retunisize, newpos; - const char *reason; - Py_ssize_t esize, start, end; - - if (e > 0) { - reason = "illegal multibyte sequence"; - esize = e; - } - else { - switch (e) { - case MBERR_TOOSMALL: - REQUIRE_DECODEBUFFER(buf, -1); - return 0; /* retry it */ - case MBERR_TOOFEW: - reason = "incomplete multibyte sequence"; - esize = (Py_ssize_t)(buf->inbuf_end - buf->inbuf); - break; - case MBERR_INTERNAL: - PyErr_SetString(PyExc_RuntimeError, - "internal codec error"); - return -1; - default: - PyErr_SetString(PyExc_RuntimeError, - "unknown runtime error"); - return -1; - } - } - - if (errors == ERROR_REPLACE) { - REQUIRE_DECODEBUFFER(buf, 1); - *buf->outbuf++ = Py_UNICODE_REPLACEMENT_CHARACTER; - } - if (errors == ERROR_IGNORE || errors == ERROR_REPLACE) { - buf->inbuf += esize; - return 0; - } - - start = (Py_ssize_t)(buf->inbuf - buf->inbuf_top); - end = start + esize; - - /* use cached exception object if available */ - if (buf->excobj == NULL) { - buf->excobj = PyUnicodeDecodeError_Create(codec->encoding, - (const char *)buf->inbuf_top, - (Py_ssize_t)(buf->inbuf_end - buf->inbuf_top), - start, end, reason); - if (buf->excobj == NULL) - goto errorexit; - } - else - if (PyUnicodeDecodeError_SetStart(buf->excobj, start) || - PyUnicodeDecodeError_SetEnd(buf->excobj, end) || - PyUnicodeDecodeError_SetReason(buf->excobj, reason)) - goto errorexit; - - if (errors == ERROR_STRICT) { - PyCodec_StrictErrors(buf->excobj); - goto errorexit; - } - - retobj = call_error_callback(errors, buf->excobj); - if (retobj == NULL) - goto errorexit; - - if (!PyTuple_Check(retobj) || PyTuple_GET_SIZE(retobj) != 2 || - !PyUnicode_Check((retuni = PyTuple_GET_ITEM(retobj, 0))) || - !PyLong_Check(PyTuple_GET_ITEM(retobj, 1))) { - PyErr_SetString(PyExc_TypeError, - "decoding error handler must return " - "(unicode, int) tuple"); - goto errorexit; - } - - retunisize = PyUnicode_GET_SIZE(retuni); - if (retunisize > 0) { - REQUIRE_DECODEBUFFER(buf, retunisize); - memcpy((char *)buf->outbuf, PyUnicode_AS_DATA(retuni), - retunisize * Py_UNICODE_SIZE); - buf->outbuf += retunisize; - } - - newpos = PyLong_AsSsize_t(PyTuple_GET_ITEM(retobj, 1)); - if (newpos < 0 && !PyErr_Occurred()) - newpos += (Py_ssize_t)(buf->inbuf_end - buf->inbuf_top); - if (newpos < 0 || buf->inbuf_top + newpos > buf->inbuf_end) { - PyErr_Clear(); - PyErr_Format(PyExc_IndexError, - "position %zd from error handler out of bounds", - newpos); - goto errorexit; - } - buf->inbuf = buf->inbuf_top + newpos; - Py_DECREF(retobj); - return 0; + MultibyteCodec_State *state, + MultibyteDecodeBuffer *buf, + PyObject *errors, Py_ssize_t e) +{ + PyObject *retobj = NULL, *retuni = NULL; + Py_ssize_t retunisize, newpos; + const char *reason; + Py_ssize_t esize, start, end; + + if (e > 0) { + reason = "illegal multibyte sequence"; + esize = e; + } + else { + switch (e) { + case MBERR_TOOSMALL: + REQUIRE_DECODEBUFFER(buf, -1); + return 0; /* retry it */ + case MBERR_TOOFEW: + reason = "incomplete multibyte sequence"; + esize = (Py_ssize_t)(buf->inbuf_end - buf->inbuf); + break; + case MBERR_INTERNAL: + PyErr_SetString(PyExc_RuntimeError, + "internal codec error"); + return -1; + default: + PyErr_SetString(PyExc_RuntimeError, + "unknown runtime error"); + return -1; + } + } + + if (errors == ERROR_REPLACE) { + REQUIRE_DECODEBUFFER(buf, 1); + *buf->outbuf++ = Py_UNICODE_REPLACEMENT_CHARACTER; + } + if (errors == ERROR_IGNORE || errors == ERROR_REPLACE) { + buf->inbuf += esize; + return 0; + } + + start = (Py_ssize_t)(buf->inbuf - buf->inbuf_top); + end = start + esize; + + /* use cached exception object if available */ + if (buf->excobj == NULL) { + buf->excobj = PyUnicodeDecodeError_Create(codec->encoding, + (const char *)buf->inbuf_top, + (Py_ssize_t)(buf->inbuf_end - buf->inbuf_top), + start, end, reason); + if (buf->excobj == NULL) + goto errorexit; + } + else + if (PyUnicodeDecodeError_SetStart(buf->excobj, start) || + PyUnicodeDecodeError_SetEnd(buf->excobj, end) || + PyUnicodeDecodeError_SetReason(buf->excobj, reason)) + goto errorexit; + + if (errors == ERROR_STRICT) { + PyCodec_StrictErrors(buf->excobj); + goto errorexit; + } + + retobj = call_error_callback(errors, buf->excobj); + if (retobj == NULL) + goto errorexit; + + if (!PyTuple_Check(retobj) || PyTuple_GET_SIZE(retobj) != 2 || + !PyUnicode_Check((retuni = PyTuple_GET_ITEM(retobj, 0))) || + !PyLong_Check(PyTuple_GET_ITEM(retobj, 1))) { + PyErr_SetString(PyExc_TypeError, + "decoding error handler must return " + "(unicode, int) tuple"); + goto errorexit; + } + + retunisize = PyUnicode_GET_SIZE(retuni); + if (retunisize > 0) { + REQUIRE_DECODEBUFFER(buf, retunisize); + memcpy((char *)buf->outbuf, PyUnicode_AS_DATA(retuni), + retunisize * Py_UNICODE_SIZE); + buf->outbuf += retunisize; + } + + newpos = PyLong_AsSsize_t(PyTuple_GET_ITEM(retobj, 1)); + if (newpos < 0 && !PyErr_Occurred()) + newpos += (Py_ssize_t)(buf->inbuf_end - buf->inbuf_top); + if (newpos < 0 || buf->inbuf_top + newpos > buf->inbuf_end) { + PyErr_Clear(); + PyErr_Format(PyExc_IndexError, + "position %zd from error handler out of bounds", + newpos); + goto errorexit; + } + buf->inbuf = buf->inbuf_top + newpos; + Py_DECREF(retobj); + return 0; errorexit: - Py_XDECREF(retobj); - return -1; + Py_XDECREF(retobj); + return -1; } static PyObject * multibytecodec_encode(MultibyteCodec *codec, - MultibyteCodec_State *state, - const Py_UNICODE **data, Py_ssize_t datalen, - PyObject *errors, int flags) -{ - MultibyteEncodeBuffer buf; - Py_ssize_t finalsize, r = 0; - - if (datalen == 0) - return PyBytes_FromStringAndSize(NULL, 0); - - buf.excobj = NULL; - buf.inbuf = buf.inbuf_top = *data; - buf.inbuf_end = buf.inbuf_top + datalen; - - if (datalen > (PY_SSIZE_T_MAX - 16) / 2) { - PyErr_NoMemory(); - goto errorexit; - } - - buf.outobj = PyBytes_FromStringAndSize(NULL, datalen * 2 + 16); - if (buf.outobj == NULL) - goto errorexit; - buf.outbuf = (unsigned char *)PyBytes_AS_STRING(buf.outobj); - buf.outbuf_end = buf.outbuf + PyBytes_GET_SIZE(buf.outobj); - - while (buf.inbuf < buf.inbuf_end) { - Py_ssize_t inleft, outleft; - - /* we don't reuse inleft and outleft here. - * error callbacks can relocate the cursor anywhere on buffer*/ - inleft = (Py_ssize_t)(buf.inbuf_end - buf.inbuf); - outleft = (Py_ssize_t)(buf.outbuf_end - buf.outbuf); - r = codec->encode(state, codec->config, &buf.inbuf, inleft, - &buf.outbuf, outleft, flags); - if ((r == 0) || (r == MBERR_TOOFEW && !(flags & MBENC_FLUSH))) - break; - else if (multibytecodec_encerror(codec, state, &buf, errors,r)) - goto errorexit; - else if (r == MBERR_TOOFEW) - break; - } - - if (codec->encreset != NULL) - for (;;) { - Py_ssize_t outleft; - - outleft = (Py_ssize_t)(buf.outbuf_end - buf.outbuf); - r = codec->encreset(state, codec->config, &buf.outbuf, - outleft); - if (r == 0) - break; - else if (multibytecodec_encerror(codec, state, - &buf, errors, r)) - goto errorexit; - } - - finalsize = (Py_ssize_t)((char *)buf.outbuf - - PyBytes_AS_STRING(buf.outobj)); - - if (finalsize != PyBytes_GET_SIZE(buf.outobj)) - if (_PyBytes_Resize(&buf.outobj, finalsize) == -1) - goto errorexit; - - *data = buf.inbuf; - Py_XDECREF(buf.excobj); - return buf.outobj; + MultibyteCodec_State *state, + const Py_UNICODE **data, Py_ssize_t datalen, + PyObject *errors, int flags) +{ + MultibyteEncodeBuffer buf; + Py_ssize_t finalsize, r = 0; + + if (datalen == 0) + return PyBytes_FromStringAndSize(NULL, 0); + + buf.excobj = NULL; + buf.inbuf = buf.inbuf_top = *data; + buf.inbuf_end = buf.inbuf_top + datalen; + + if (datalen > (PY_SSIZE_T_MAX - 16) / 2) { + PyErr_NoMemory(); + goto errorexit; + } + + buf.outobj = PyBytes_FromStringAndSize(NULL, datalen * 2 + 16); + if (buf.outobj == NULL) + goto errorexit; + buf.outbuf = (unsigned char *)PyBytes_AS_STRING(buf.outobj); + buf.outbuf_end = buf.outbuf + PyBytes_GET_SIZE(buf.outobj); + + while (buf.inbuf < buf.inbuf_end) { + Py_ssize_t inleft, outleft; + + /* we don't reuse inleft and outleft here. + * error callbacks can relocate the cursor anywhere on buffer*/ + inleft = (Py_ssize_t)(buf.inbuf_end - buf.inbuf); + outleft = (Py_ssize_t)(buf.outbuf_end - buf.outbuf); + r = codec->encode(state, codec->config, &buf.inbuf, inleft, + &buf.outbuf, outleft, flags); + if ((r == 0) || (r == MBERR_TOOFEW && !(flags & MBENC_FLUSH))) + break; + else if (multibytecodec_encerror(codec, state, &buf, errors,r)) + goto errorexit; + else if (r == MBERR_TOOFEW) + break; + } + + if (codec->encreset != NULL) + for (;;) { + Py_ssize_t outleft; + + outleft = (Py_ssize_t)(buf.outbuf_end - buf.outbuf); + r = codec->encreset(state, codec->config, &buf.outbuf, + outleft); + if (r == 0) + break; + else if (multibytecodec_encerror(codec, state, + &buf, errors, r)) + goto errorexit; + } + + finalsize = (Py_ssize_t)((char *)buf.outbuf - + PyBytes_AS_STRING(buf.outobj)); + + if (finalsize != PyBytes_GET_SIZE(buf.outobj)) + if (_PyBytes_Resize(&buf.outobj, finalsize) == -1) + goto errorexit; + + *data = buf.inbuf; + Py_XDECREF(buf.excobj); + return buf.outobj; errorexit: - Py_XDECREF(buf.excobj); - Py_XDECREF(buf.outobj); - return NULL; + Py_XDECREF(buf.excobj); + Py_XDECREF(buf.outobj); + return NULL; } static PyObject * MultibyteCodec_Encode(MultibyteCodecObject *self, - PyObject *args, PyObject *kwargs) + PyObject *args, PyObject *kwargs) { - MultibyteCodec_State state; - Py_UNICODE *data; - PyObject *errorcb, *r, *arg, *ucvt; - const char *errors = NULL; - Py_ssize_t datalen; - - if (!PyArg_ParseTupleAndKeywords(args, kwargs, "O|z:encode", - codeckwarglist, &arg, &errors)) - return NULL; - - if (PyUnicode_Check(arg)) - ucvt = NULL; - else { - arg = ucvt = PyObject_Str(arg); - if (arg == NULL) - return NULL; - else if (!PyUnicode_Check(arg)) { - PyErr_SetString(PyExc_TypeError, - "couldn't convert the object to unicode."); - Py_DECREF(ucvt); - return NULL; - } - } - - data = PyUnicode_AS_UNICODE(arg); - datalen = PyUnicode_GET_SIZE(arg); - - errorcb = internal_error_callback(errors); - if (errorcb == NULL) { - Py_XDECREF(ucvt); - return NULL; - } - - if (self->codec->encinit != NULL && - self->codec->encinit(&state, self->codec->config) != 0) - goto errorexit; - r = multibytecodec_encode(self->codec, &state, - (const Py_UNICODE **)&data, datalen, errorcb, - MBENC_FLUSH | MBENC_RESET); - if (r == NULL) - goto errorexit; - - ERROR_DECREF(errorcb); - Py_XDECREF(ucvt); - return make_tuple(r, datalen); + MultibyteCodec_State state; + Py_UNICODE *data; + PyObject *errorcb, *r, *arg, *ucvt; + const char *errors = NULL; + Py_ssize_t datalen; + + if (!PyArg_ParseTupleAndKeywords(args, kwargs, "O|z:encode", + codeckwarglist, &arg, &errors)) + return NULL; + + if (PyUnicode_Check(arg)) + ucvt = NULL; + else { + arg = ucvt = PyObject_Str(arg); + if (arg == NULL) + return NULL; + else if (!PyUnicode_Check(arg)) { + PyErr_SetString(PyExc_TypeError, + "couldn't convert the object to unicode."); + Py_DECREF(ucvt); + return NULL; + } + } + + data = PyUnicode_AS_UNICODE(arg); + datalen = PyUnicode_GET_SIZE(arg); + + errorcb = internal_error_callback(errors); + if (errorcb == NULL) { + Py_XDECREF(ucvt); + return NULL; + } + + if (self->codec->encinit != NULL && + self->codec->encinit(&state, self->codec->config) != 0) + goto errorexit; + r = multibytecodec_encode(self->codec, &state, + (const Py_UNICODE **)&data, datalen, errorcb, + MBENC_FLUSH | MBENC_RESET); + if (r == NULL) + goto errorexit; + + ERROR_DECREF(errorcb); + Py_XDECREF(ucvt); + return make_tuple(r, datalen); errorexit: - ERROR_DECREF(errorcb); - Py_XDECREF(ucvt); - return NULL; + ERROR_DECREF(errorcb); + Py_XDECREF(ucvt); + return NULL; } static PyObject * MultibyteCodec_Decode(MultibyteCodecObject *self, - PyObject *args, PyObject *kwargs) + PyObject *args, PyObject *kwargs) { - MultibyteCodec_State state; - MultibyteDecodeBuffer buf; - PyObject *errorcb; - Py_buffer pdata; - const char *data, *errors = NULL; - Py_ssize_t datalen, finalsize; - - if (!PyArg_ParseTupleAndKeywords(args, kwargs, "y*|z:decode", - codeckwarglist, &pdata, &errors)) - return NULL; - data = pdata.buf; - datalen = pdata.len; - - errorcb = internal_error_callback(errors); - if (errorcb == NULL) { - PyBuffer_Release(&pdata); - return NULL; - } - - if (datalen == 0) { - PyBuffer_Release(&pdata); - ERROR_DECREF(errorcb); - return make_tuple(PyUnicode_FromUnicode(NULL, 0), 0); - } - - buf.excobj = NULL; - buf.inbuf = buf.inbuf_top = (unsigned char *)data; - buf.inbuf_end = buf.inbuf_top + datalen; - buf.outobj = PyUnicode_FromUnicode(NULL, datalen); - if (buf.outobj == NULL) - goto errorexit; - buf.outbuf = PyUnicode_AS_UNICODE(buf.outobj); - buf.outbuf_end = buf.outbuf + PyUnicode_GET_SIZE(buf.outobj); - - if (self->codec->decinit != NULL && - self->codec->decinit(&state, self->codec->config) != 0) - goto errorexit; - - while (buf.inbuf < buf.inbuf_end) { - Py_ssize_t inleft, outleft, r; - - inleft = (Py_ssize_t)(buf.inbuf_end - buf.inbuf); - outleft = (Py_ssize_t)(buf.outbuf_end - buf.outbuf); - - r = self->codec->decode(&state, self->codec->config, - &buf.inbuf, inleft, &buf.outbuf, outleft); - if (r == 0) - break; - else if (multibytecodec_decerror(self->codec, &state, - &buf, errorcb, r)) - goto errorexit; - } - - finalsize = (Py_ssize_t)(buf.outbuf - - PyUnicode_AS_UNICODE(buf.outobj)); - - if (finalsize != PyUnicode_GET_SIZE(buf.outobj)) - if (PyUnicode_Resize(&buf.outobj, finalsize) == -1) - goto errorexit; - - PyBuffer_Release(&pdata); - Py_XDECREF(buf.excobj); - ERROR_DECREF(errorcb); - return make_tuple(buf.outobj, datalen); + MultibyteCodec_State state; + MultibyteDecodeBuffer buf; + PyObject *errorcb; + Py_buffer pdata; + const char *data, *errors = NULL; + Py_ssize_t datalen, finalsize; + + if (!PyArg_ParseTupleAndKeywords(args, kwargs, "y*|z:decode", + codeckwarglist, &pdata, &errors)) + return NULL; + data = pdata.buf; + datalen = pdata.len; + + errorcb = internal_error_callback(errors); + if (errorcb == NULL) { + PyBuffer_Release(&pdata); + return NULL; + } + + if (datalen == 0) { + PyBuffer_Release(&pdata); + ERROR_DECREF(errorcb); + return make_tuple(PyUnicode_FromUnicode(NULL, 0), 0); + } + + buf.excobj = NULL; + buf.inbuf = buf.inbuf_top = (unsigned char *)data; + buf.inbuf_end = buf.inbuf_top + datalen; + buf.outobj = PyUnicode_FromUnicode(NULL, datalen); + if (buf.outobj == NULL) + goto errorexit; + buf.outbuf = PyUnicode_AS_UNICODE(buf.outobj); + buf.outbuf_end = buf.outbuf + PyUnicode_GET_SIZE(buf.outobj); + + if (self->codec->decinit != NULL && + self->codec->decinit(&state, self->codec->config) != 0) + goto errorexit; + + while (buf.inbuf < buf.inbuf_end) { + Py_ssize_t inleft, outleft, r; + + inleft = (Py_ssize_t)(buf.inbuf_end - buf.inbuf); + outleft = (Py_ssize_t)(buf.outbuf_end - buf.outbuf); + + r = self->codec->decode(&state, self->codec->config, + &buf.inbuf, inleft, &buf.outbuf, outleft); + if (r == 0) + break; + else if (multibytecodec_decerror(self->codec, &state, + &buf, errorcb, r)) + goto errorexit; + } + + finalsize = (Py_ssize_t)(buf.outbuf - + PyUnicode_AS_UNICODE(buf.outobj)); + + if (finalsize != PyUnicode_GET_SIZE(buf.outobj)) + if (PyUnicode_Resize(&buf.outobj, finalsize) == -1) + goto errorexit; + + PyBuffer_Release(&pdata); + Py_XDECREF(buf.excobj); + ERROR_DECREF(errorcb); + return make_tuple(buf.outobj, datalen); errorexit: - PyBuffer_Release(&pdata); - ERROR_DECREF(errorcb); - Py_XDECREF(buf.excobj); - Py_XDECREF(buf.outobj); + PyBuffer_Release(&pdata); + ERROR_DECREF(errorcb); + Py_XDECREF(buf.excobj); + Py_XDECREF(buf.outobj); - return NULL; + return NULL; } static struct PyMethodDef multibytecodec_methods[] = { - {"encode", (PyCFunction)MultibyteCodec_Encode, - METH_VARARGS | METH_KEYWORDS, - MultibyteCodec_Encode__doc__}, - {"decode", (PyCFunction)MultibyteCodec_Decode, - METH_VARARGS | METH_KEYWORDS, - MultibyteCodec_Decode__doc__}, - {NULL, NULL}, + {"encode", (PyCFunction)MultibyteCodec_Encode, + METH_VARARGS | METH_KEYWORDS, + MultibyteCodec_Encode__doc__}, + {"decode", (PyCFunction)MultibyteCodec_Decode, + METH_VARARGS | METH_KEYWORDS, + MultibyteCodec_Decode__doc__}, + {NULL, NULL}, }; static void multibytecodec_dealloc(MultibyteCodecObject *self) { - PyObject_Del(self); + PyObject_Del(self); } static PyTypeObject MultibyteCodec_Type = { - PyVarObject_HEAD_INIT(NULL, 0) - "MultibyteCodec", /* tp_name */ - sizeof(MultibyteCodecObject), /* tp_basicsize */ - 0, /* tp_itemsize */ - /* methods */ - (destructor)multibytecodec_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, /* tp_flags */ - 0, /* tp_doc */ - 0, /* tp_traverse */ - 0, /* tp_clear */ - 0, /* tp_richcompare */ - 0, /* tp_weaklistoffset */ - 0, /* tp_iter */ - 0, /* tp_iterext */ - multibytecodec_methods, /* tp_methods */ + PyVarObject_HEAD_INIT(NULL, 0) + "MultibyteCodec", /* tp_name */ + sizeof(MultibyteCodecObject), /* tp_basicsize */ + 0, /* tp_itemsize */ + /* methods */ + (destructor)multibytecodec_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, /* tp_flags */ + 0, /* tp_doc */ + 0, /* tp_traverse */ + 0, /* tp_clear */ + 0, /* tp_richcompare */ + 0, /* tp_weaklistoffset */ + 0, /* tp_iter */ + 0, /* tp_iterext */ + multibytecodec_methods, /* tp_methods */ }; @@ -732,150 +732,150 @@ * Utility functions for stateful codec mechanism */ -#define STATEFUL_DCTX(o) ((MultibyteStatefulDecoderContext *)(o)) -#define STATEFUL_ECTX(o) ((MultibyteStatefulEncoderContext *)(o)) +#define STATEFUL_DCTX(o) ((MultibyteStatefulDecoderContext *)(o)) +#define STATEFUL_ECTX(o) ((MultibyteStatefulEncoderContext *)(o)) static PyObject * encoder_encode_stateful(MultibyteStatefulEncoderContext *ctx, - PyObject *unistr, int final) + PyObject *unistr, int final) { - PyObject *ucvt, *r = NULL; - Py_UNICODE *inbuf, *inbuf_end, *inbuf_tmp = NULL; - Py_ssize_t datalen, origpending; - - if (PyUnicode_Check(unistr)) - ucvt = NULL; - else { - unistr = ucvt = PyObject_Str(unistr); - if (unistr == NULL) - return NULL; - else if (!PyUnicode_Check(unistr)) { - PyErr_SetString(PyExc_TypeError, - "couldn't convert the object to unicode."); - Py_DECREF(ucvt); - return NULL; - } - } - - datalen = PyUnicode_GET_SIZE(unistr); - origpending = ctx->pendingsize; - - if (origpending > 0) { - if (datalen > PY_SSIZE_T_MAX - ctx->pendingsize) { - PyErr_NoMemory(); - /* inbuf_tmp == NULL */ - goto errorexit; - } - inbuf_tmp = PyMem_New(Py_UNICODE, datalen + ctx->pendingsize); - if (inbuf_tmp == NULL) - goto errorexit; - memcpy(inbuf_tmp, ctx->pending, - Py_UNICODE_SIZE * ctx->pendingsize); - memcpy(inbuf_tmp + ctx->pendingsize, - PyUnicode_AS_UNICODE(unistr), - Py_UNICODE_SIZE * datalen); - datalen += ctx->pendingsize; - ctx->pendingsize = 0; - inbuf = inbuf_tmp; - } - else - inbuf = (Py_UNICODE *)PyUnicode_AS_UNICODE(unistr); - - inbuf_end = inbuf + datalen; - - r = multibytecodec_encode(ctx->codec, &ctx->state, - (const Py_UNICODE **)&inbuf, - datalen, ctx->errors, final ? MBENC_FLUSH : 0); - if (r == NULL) { - /* recover the original pending buffer */ - if (origpending > 0) - memcpy(ctx->pending, inbuf_tmp, - Py_UNICODE_SIZE * origpending); - ctx->pendingsize = origpending; - goto errorexit; - } - - if (inbuf < inbuf_end) { - ctx->pendingsize = (Py_ssize_t)(inbuf_end - inbuf); - if (ctx->pendingsize > MAXENCPENDING) { - /* normal codecs can't reach here */ - ctx->pendingsize = 0; - PyErr_SetString(PyExc_UnicodeError, - "pending buffer overflow"); - goto errorexit; - } - memcpy(ctx->pending, inbuf, - ctx->pendingsize * Py_UNICODE_SIZE); - } - - if (inbuf_tmp != NULL) - PyMem_Del(inbuf_tmp); - Py_XDECREF(ucvt); - return r; + PyObject *ucvt, *r = NULL; + Py_UNICODE *inbuf, *inbuf_end, *inbuf_tmp = NULL; + Py_ssize_t datalen, origpending; + + if (PyUnicode_Check(unistr)) + ucvt = NULL; + else { + unistr = ucvt = PyObject_Str(unistr); + if (unistr == NULL) + return NULL; + else if (!PyUnicode_Check(unistr)) { + PyErr_SetString(PyExc_TypeError, + "couldn't convert the object to unicode."); + Py_DECREF(ucvt); + return NULL; + } + } + + datalen = PyUnicode_GET_SIZE(unistr); + origpending = ctx->pendingsize; + + if (origpending > 0) { + if (datalen > PY_SSIZE_T_MAX - ctx->pendingsize) { + PyErr_NoMemory(); + /* inbuf_tmp == NULL */ + goto errorexit; + } + inbuf_tmp = PyMem_New(Py_UNICODE, datalen + ctx->pendingsize); + if (inbuf_tmp == NULL) + goto errorexit; + memcpy(inbuf_tmp, ctx->pending, + Py_UNICODE_SIZE * ctx->pendingsize); + memcpy(inbuf_tmp + ctx->pendingsize, + PyUnicode_AS_UNICODE(unistr), + Py_UNICODE_SIZE * datalen); + datalen += ctx->pendingsize; + ctx->pendingsize = 0; + inbuf = inbuf_tmp; + } + else + inbuf = (Py_UNICODE *)PyUnicode_AS_UNICODE(unistr); + + inbuf_end = inbuf + datalen; + + r = multibytecodec_encode(ctx->codec, &ctx->state, + (const Py_UNICODE **)&inbuf, + datalen, ctx->errors, final ? MBENC_FLUSH : 0); + if (r == NULL) { + /* recover the original pending buffer */ + if (origpending > 0) + memcpy(ctx->pending, inbuf_tmp, + Py_UNICODE_SIZE * origpending); + ctx->pendingsize = origpending; + goto errorexit; + } + + if (inbuf < inbuf_end) { + ctx->pendingsize = (Py_ssize_t)(inbuf_end - inbuf); + if (ctx->pendingsize > MAXENCPENDING) { + /* normal codecs can't reach here */ + ctx->pendingsize = 0; + PyErr_SetString(PyExc_UnicodeError, + "pending buffer overflow"); + goto errorexit; + } + memcpy(ctx->pending, inbuf, + ctx->pendingsize * Py_UNICODE_SIZE); + } + + if (inbuf_tmp != NULL) + PyMem_Del(inbuf_tmp); + Py_XDECREF(ucvt); + return r; errorexit: - if (inbuf_tmp != NULL) - PyMem_Del(inbuf_tmp); - Py_XDECREF(r); - Py_XDECREF(ucvt); - return NULL; + if (inbuf_tmp != NULL) + PyMem_Del(inbuf_tmp); + Py_XDECREF(r); + Py_XDECREF(ucvt); + return NULL; } static int decoder_append_pending(MultibyteStatefulDecoderContext *ctx, - MultibyteDecodeBuffer *buf) + MultibyteDecodeBuffer *buf) { - Py_ssize_t npendings; + Py_ssize_t npendings; - npendings = (Py_ssize_t)(buf->inbuf_end - buf->inbuf); - if (npendings + ctx->pendingsize > MAXDECPENDING || - npendings > PY_SSIZE_T_MAX - ctx->pendingsize) { - PyErr_SetString(PyExc_UnicodeError, "pending buffer overflow"); - return -1; - } - memcpy(ctx->pending + ctx->pendingsize, buf->inbuf, npendings); - ctx->pendingsize += npendings; - return 0; + npendings = (Py_ssize_t)(buf->inbuf_end - buf->inbuf); + if (npendings + ctx->pendingsize > MAXDECPENDING || + npendings > PY_SSIZE_T_MAX - ctx->pendingsize) { + PyErr_SetString(PyExc_UnicodeError, "pending buffer overflow"); + return -1; + } + memcpy(ctx->pending + ctx->pendingsize, buf->inbuf, npendings); + ctx->pendingsize += npendings; + return 0; } static int decoder_prepare_buffer(MultibyteDecodeBuffer *buf, const char *data, - Py_ssize_t size) + Py_ssize_t size) { - buf->inbuf = buf->inbuf_top = (const unsigned char *)data; - buf->inbuf_end = buf->inbuf_top + size; - if (buf->outobj == NULL) { /* only if outobj is not allocated yet */ - buf->outobj = PyUnicode_FromUnicode(NULL, size); - if (buf->outobj == NULL) - return -1; - buf->outbuf = PyUnicode_AS_UNICODE(buf->outobj); - buf->outbuf_end = buf->outbuf + - PyUnicode_GET_SIZE(buf->outobj); - } + buf->inbuf = buf->inbuf_top = (const unsigned char *)data; + buf->inbuf_end = buf->inbuf_top + size; + if (buf->outobj == NULL) { /* only if outobj is not allocated yet */ + buf->outobj = PyUnicode_FromUnicode(NULL, size); + if (buf->outobj == NULL) + return -1; + buf->outbuf = PyUnicode_AS_UNICODE(buf->outobj); + buf->outbuf_end = buf->outbuf + + PyUnicode_GET_SIZE(buf->outobj); + } - return 0; + return 0; } static int decoder_feed_buffer(MultibyteStatefulDecoderContext *ctx, - MultibyteDecodeBuffer *buf) + MultibyteDecodeBuffer *buf) { - while (buf->inbuf < buf->inbuf_end) { - Py_ssize_t inleft, outleft; - Py_ssize_t r; - - inleft = (Py_ssize_t)(buf->inbuf_end - buf->inbuf); - outleft = (Py_ssize_t)(buf->outbuf_end - buf->outbuf); - - r = ctx->codec->decode(&ctx->state, ctx->codec->config, - &buf->inbuf, inleft, &buf->outbuf, outleft); - if (r == 0 || r == MBERR_TOOFEW) - break; - else if (multibytecodec_decerror(ctx->codec, &ctx->state, - buf, ctx->errors, r)) - return -1; - } - return 0; + while (buf->inbuf < buf->inbuf_end) { + Py_ssize_t inleft, outleft; + Py_ssize_t r; + + inleft = (Py_ssize_t)(buf->inbuf_end - buf->inbuf); + outleft = (Py_ssize_t)(buf->outbuf_end - buf->outbuf); + + r = ctx->codec->decode(&ctx->state, ctx->codec->config, + &buf->inbuf, inleft, &buf->outbuf, outleft); + if (r == 0 || r == MBERR_TOOFEW) + break; + else if (multibytecodec_decerror(ctx->codec, &ctx->state, + buf, ctx->errors, r)) + return -1; + } + return 0; } @@ -885,142 +885,142 @@ static PyObject * mbiencoder_encode(MultibyteIncrementalEncoderObject *self, - PyObject *args, PyObject *kwargs) + PyObject *args, PyObject *kwargs) { - PyObject *data; - int final = 0; + PyObject *data; + int final = 0; - if (!PyArg_ParseTupleAndKeywords(args, kwargs, "O|i:encode", - incrementalkwarglist, &data, &final)) - return NULL; + if (!PyArg_ParseTupleAndKeywords(args, kwargs, "O|i:encode", + incrementalkwarglist, &data, &final)) + return NULL; - return encoder_encode_stateful(STATEFUL_ECTX(self), data, final); + return encoder_encode_stateful(STATEFUL_ECTX(self), data, final); } static PyObject * mbiencoder_reset(MultibyteIncrementalEncoderObject *self) { - if (self->codec->decreset != NULL && - self->codec->decreset(&self->state, self->codec->config) != 0) - return NULL; - self->pendingsize = 0; + if (self->codec->decreset != NULL && + self->codec->decreset(&self->state, self->codec->config) != 0) + return NULL; + self->pendingsize = 0; - Py_RETURN_NONE; + Py_RETURN_NONE; } static struct PyMethodDef mbiencoder_methods[] = { - {"encode", (PyCFunction)mbiencoder_encode, - METH_VARARGS | METH_KEYWORDS, NULL}, - {"reset", (PyCFunction)mbiencoder_reset, - METH_NOARGS, NULL}, - {NULL, NULL}, + {"encode", (PyCFunction)mbiencoder_encode, + METH_VARARGS | METH_KEYWORDS, NULL}, + {"reset", (PyCFunction)mbiencoder_reset, + METH_NOARGS, NULL}, + {NULL, NULL}, }; static PyObject * mbiencoder_new(PyTypeObject *type, PyObject *args, PyObject *kwds) { - MultibyteIncrementalEncoderObject *self; - PyObject *codec = NULL; - char *errors = NULL; - - if (!PyArg_ParseTupleAndKeywords(args, kwds, "|s:IncrementalEncoder", - incnewkwarglist, &errors)) - return NULL; - - self = (MultibyteIncrementalEncoderObject *)type->tp_alloc(type, 0); - if (self == NULL) - return NULL; - - codec = PyObject_GetAttrString((PyObject *)type, "codec"); - if (codec == NULL) - goto errorexit; - if (!MultibyteCodec_Check(codec)) { - PyErr_SetString(PyExc_TypeError, "codec is unexpected type"); - goto errorexit; - } - - self->codec = ((MultibyteCodecObject *)codec)->codec; - self->pendingsize = 0; - self->errors = internal_error_callback(errors); - if (self->errors == NULL) - goto errorexit; - if (self->codec->encinit != NULL && - self->codec->encinit(&self->state, self->codec->config) != 0) - goto errorexit; + MultibyteIncrementalEncoderObject *self; + PyObject *codec = NULL; + char *errors = NULL; + + if (!PyArg_ParseTupleAndKeywords(args, kwds, "|s:IncrementalEncoder", + incnewkwarglist, &errors)) + return NULL; + + self = (MultibyteIncrementalEncoderObject *)type->tp_alloc(type, 0); + if (self == NULL) + return NULL; + + codec = PyObject_GetAttrString((PyObject *)type, "codec"); + if (codec == NULL) + goto errorexit; + if (!MultibyteCodec_Check(codec)) { + PyErr_SetString(PyExc_TypeError, "codec is unexpected type"); + goto errorexit; + } + + self->codec = ((MultibyteCodecObject *)codec)->codec; + self->pendingsize = 0; + self->errors = internal_error_callback(errors); + if (self->errors == NULL) + goto errorexit; + if (self->codec->encinit != NULL && + self->codec->encinit(&self->state, self->codec->config) != 0) + goto errorexit; - Py_DECREF(codec); - return (PyObject *)self; + Py_DECREF(codec); + return (PyObject *)self; errorexit: - Py_XDECREF(self); - Py_XDECREF(codec); - return NULL; + Py_XDECREF(self); + Py_XDECREF(codec); + return NULL; } static int mbiencoder_init(PyObject *self, PyObject *args, PyObject *kwds) { - return 0; + return 0; } static int mbiencoder_traverse(MultibyteIncrementalEncoderObject *self, - visitproc visit, void *arg) + visitproc visit, void *arg) { - if (ERROR_ISCUSTOM(self->errors)) - Py_VISIT(self->errors); - return 0; + if (ERROR_ISCUSTOM(self->errors)) + Py_VISIT(self->errors); + return 0; } static void mbiencoder_dealloc(MultibyteIncrementalEncoderObject *self) { - PyObject_GC_UnTrack(self); - ERROR_DECREF(self->errors); - Py_TYPE(self)->tp_free(self); + PyObject_GC_UnTrack(self); + ERROR_DECREF(self->errors); + Py_TYPE(self)->tp_free(self); } static PyTypeObject MultibyteIncrementalEncoder_Type = { - PyVarObject_HEAD_INIT(NULL, 0) - "MultibyteIncrementalEncoder", /* tp_name */ - sizeof(MultibyteIncrementalEncoderObject), /* tp_basicsize */ - 0, /* tp_itemsize */ - /* methods */ - (destructor)mbiencoder_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 - | Py_TPFLAGS_BASETYPE, /* tp_flags */ - 0, /* tp_doc */ - (traverseproc)mbiencoder_traverse, /* tp_traverse */ - 0, /* tp_clear */ - 0, /* tp_richcompare */ - 0, /* tp_weaklistoffset */ - 0, /* tp_iter */ - 0, /* tp_iterext */ - mbiencoder_methods, /* tp_methods */ - 0, /* tp_members */ - codecctx_getsets, /* tp_getset */ - 0, /* tp_base */ - 0, /* tp_dict */ - 0, /* tp_descr_get */ - 0, /* tp_descr_set */ - 0, /* tp_dictoffset */ - mbiencoder_init, /* tp_init */ - 0, /* tp_alloc */ - mbiencoder_new, /* tp_new */ + PyVarObject_HEAD_INIT(NULL, 0) + "MultibyteIncrementalEncoder", /* tp_name */ + sizeof(MultibyteIncrementalEncoderObject), /* tp_basicsize */ + 0, /* tp_itemsize */ + /* methods */ + (destructor)mbiencoder_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 + | Py_TPFLAGS_BASETYPE, /* tp_flags */ + 0, /* tp_doc */ + (traverseproc)mbiencoder_traverse, /* tp_traverse */ + 0, /* tp_clear */ + 0, /* tp_richcompare */ + 0, /* tp_weaklistoffset */ + 0, /* tp_iter */ + 0, /* tp_iterext */ + mbiencoder_methods, /* tp_methods */ + 0, /* tp_members */ + codecctx_getsets, /* tp_getset */ + 0, /* tp_base */ + 0, /* tp_dict */ + 0, /* tp_descr_get */ + 0, /* tp_descr_set */ + 0, /* tp_dictoffset */ + mbiencoder_init, /* tp_init */ + 0, /* tp_alloc */ + mbiencoder_new, /* tp_new */ }; @@ -1030,206 +1030,206 @@ static PyObject * mbidecoder_decode(MultibyteIncrementalDecoderObject *self, - PyObject *args, PyObject *kwargs) + PyObject *args, PyObject *kwargs) { - MultibyteDecodeBuffer buf; - char *data, *wdata = NULL; - Py_buffer pdata; - Py_ssize_t wsize, finalsize = 0, size, origpending; - int final = 0; - - if (!PyArg_ParseTupleAndKeywords(args, kwargs, "y*|i:decode", - incrementalkwarglist, &pdata, &final)) - return NULL; - data = pdata.buf; - size = pdata.len; - - buf.outobj = buf.excobj = NULL; - origpending = self->pendingsize; - - if (self->pendingsize == 0) { - wsize = size; - wdata = data; - } - else { - if (size > PY_SSIZE_T_MAX - self->pendingsize) { - PyErr_NoMemory(); - goto errorexit; - } - wsize = size + self->pendingsize; - wdata = PyMem_Malloc(wsize); - if (wdata == NULL) - goto errorexit; - memcpy(wdata, self->pending, self->pendingsize); - memcpy(wdata + self->pendingsize, data, size); - self->pendingsize = 0; - } - - if (decoder_prepare_buffer(&buf, wdata, wsize) != 0) - goto errorexit; - - if (decoder_feed_buffer(STATEFUL_DCTX(self), &buf)) - goto errorexit; - - if (final && buf.inbuf < buf.inbuf_end) { - if (multibytecodec_decerror(self->codec, &self->state, - &buf, self->errors, MBERR_TOOFEW)) { - /* recover the original pending buffer */ - memcpy(self->pending, wdata, origpending); - self->pendingsize = origpending; - goto errorexit; - } - } - - if (buf.inbuf < buf.inbuf_end) { /* pending sequence still exists */ - if (decoder_append_pending(STATEFUL_DCTX(self), &buf) != 0) - goto errorexit; - } - - finalsize = (Py_ssize_t)(buf.outbuf - PyUnicode_AS_UNICODE(buf.outobj)); - if (finalsize != PyUnicode_GET_SIZE(buf.outobj)) - if (PyUnicode_Resize(&buf.outobj, finalsize) == -1) - goto errorexit; - - PyBuffer_Release(&pdata); - if (wdata != data) - PyMem_Del(wdata); - Py_XDECREF(buf.excobj); - return buf.outobj; + MultibyteDecodeBuffer buf; + char *data, *wdata = NULL; + Py_buffer pdata; + Py_ssize_t wsize, finalsize = 0, size, origpending; + int final = 0; + + if (!PyArg_ParseTupleAndKeywords(args, kwargs, "y*|i:decode", + incrementalkwarglist, &pdata, &final)) + return NULL; + data = pdata.buf; + size = pdata.len; + + buf.outobj = buf.excobj = NULL; + origpending = self->pendingsize; + + if (self->pendingsize == 0) { + wsize = size; + wdata = data; + } + else { + if (size > PY_SSIZE_T_MAX - self->pendingsize) { + PyErr_NoMemory(); + goto errorexit; + } + wsize = size + self->pendingsize; + wdata = PyMem_Malloc(wsize); + if (wdata == NULL) + goto errorexit; + memcpy(wdata, self->pending, self->pendingsize); + memcpy(wdata + self->pendingsize, data, size); + self->pendingsize = 0; + } + + if (decoder_prepare_buffer(&buf, wdata, wsize) != 0) + goto errorexit; + + if (decoder_feed_buffer(STATEFUL_DCTX(self), &buf)) + goto errorexit; + + if (final && buf.inbuf < buf.inbuf_end) { + if (multibytecodec_decerror(self->codec, &self->state, + &buf, self->errors, MBERR_TOOFEW)) { + /* recover the original pending buffer */ + memcpy(self->pending, wdata, origpending); + self->pendingsize = origpending; + goto errorexit; + } + } + + if (buf.inbuf < buf.inbuf_end) { /* pending sequence still exists */ + if (decoder_append_pending(STATEFUL_DCTX(self), &buf) != 0) + goto errorexit; + } + + finalsize = (Py_ssize_t)(buf.outbuf - PyUnicode_AS_UNICODE(buf.outobj)); + if (finalsize != PyUnicode_GET_SIZE(buf.outobj)) + if (PyUnicode_Resize(&buf.outobj, finalsize) == -1) + goto errorexit; + + PyBuffer_Release(&pdata); + if (wdata != data) + PyMem_Del(wdata); + Py_XDECREF(buf.excobj); + return buf.outobj; errorexit: - PyBuffer_Release(&pdata); - if (wdata != NULL && wdata != data) - PyMem_Del(wdata); - Py_XDECREF(buf.excobj); - Py_XDECREF(buf.outobj); - return NULL; + PyBuffer_Release(&pdata); + if (wdata != NULL && wdata != data) + PyMem_Del(wdata); + Py_XDECREF(buf.excobj); + Py_XDECREF(buf.outobj); + return NULL; } static PyObject * mbidecoder_reset(MultibyteIncrementalDecoderObject *self) { - if (self->codec->decreset != NULL && - self->codec->decreset(&self->state, self->codec->config) != 0) - return NULL; - self->pendingsize = 0; + if (self->codec->decreset != NULL && + self->codec->decreset(&self->state, self->codec->config) != 0) + return NULL; + self->pendingsize = 0; - Py_RETURN_NONE; + Py_RETURN_NONE; } static struct PyMethodDef mbidecoder_methods[] = { - {"decode", (PyCFunction)mbidecoder_decode, - METH_VARARGS | METH_KEYWORDS, NULL}, - {"reset", (PyCFunction)mbidecoder_reset, - METH_NOARGS, NULL}, - {NULL, NULL}, + {"decode", (PyCFunction)mbidecoder_decode, + METH_VARARGS | METH_KEYWORDS, NULL}, + {"reset", (PyCFunction)mbidecoder_reset, + METH_NOARGS, NULL}, + {NULL, NULL}, }; static PyObject * mbidecoder_new(PyTypeObject *type, PyObject *args, PyObject *kwds) { - MultibyteIncrementalDecoderObject *self; - PyObject *codec = NULL; - char *errors = NULL; - - if (!PyArg_ParseTupleAndKeywords(args, kwds, "|s:IncrementalDecoder", - incnewkwarglist, &errors)) - return NULL; - - self = (MultibyteIncrementalDecoderObject *)type->tp_alloc(type, 0); - if (self == NULL) - return NULL; - - codec = PyObject_GetAttrString((PyObject *)type, "codec"); - if (codec == NULL) - goto errorexit; - if (!MultibyteCodec_Check(codec)) { - PyErr_SetString(PyExc_TypeError, "codec is unexpected type"); - goto errorexit; - } - - self->codec = ((MultibyteCodecObject *)codec)->codec; - self->pendingsize = 0; - self->errors = internal_error_callback(errors); - if (self->errors == NULL) - goto errorexit; - if (self->codec->decinit != NULL && - self->codec->decinit(&self->state, self->codec->config) != 0) - goto errorexit; + MultibyteIncrementalDecoderObject *self; + PyObject *codec = NULL; + char *errors = NULL; + + if (!PyArg_ParseTupleAndKeywords(args, kwds, "|s:IncrementalDecoder", + incnewkwarglist, &errors)) + return NULL; + + self = (MultibyteIncrementalDecoderObject *)type->tp_alloc(type, 0); + if (self == NULL) + return NULL; + + codec = PyObject_GetAttrString((PyObject *)type, "codec"); + if (codec == NULL) + goto errorexit; + if (!MultibyteCodec_Check(codec)) { + PyErr_SetString(PyExc_TypeError, "codec is unexpected type"); + goto errorexit; + } + + self->codec = ((MultibyteCodecObject *)codec)->codec; + self->pendingsize = 0; + self->errors = internal_error_callback(errors); + if (self->errors == NULL) + goto errorexit; + if (self->codec->decinit != NULL && + self->codec->decinit(&self->state, self->codec->config) != 0) + goto errorexit; - Py_DECREF(codec); - return (PyObject *)self; + Py_DECREF(codec); + return (PyObject *)self; errorexit: - Py_XDECREF(self); - Py_XDECREF(codec); - return NULL; + Py_XDECREF(self); + Py_XDECREF(codec); + return NULL; } static int mbidecoder_init(PyObject *self, PyObject *args, PyObject *kwds) { - return 0; + return 0; } static int mbidecoder_traverse(MultibyteIncrementalDecoderObject *self, - visitproc visit, void *arg) + visitproc visit, void *arg) { - if (ERROR_ISCUSTOM(self->errors)) - Py_VISIT(self->errors); - return 0; + if (ERROR_ISCUSTOM(self->errors)) + Py_VISIT(self->errors); + return 0; } static void mbidecoder_dealloc(MultibyteIncrementalDecoderObject *self) { - PyObject_GC_UnTrack(self); - ERROR_DECREF(self->errors); - Py_TYPE(self)->tp_free(self); + PyObject_GC_UnTrack(self); + ERROR_DECREF(self->errors); + Py_TYPE(self)->tp_free(self); } static PyTypeObject MultibyteIncrementalDecoder_Type = { - PyVarObject_HEAD_INIT(NULL, 0) - "MultibyteIncrementalDecoder", /* tp_name */ - sizeof(MultibyteIncrementalDecoderObject), /* tp_basicsize */ - 0, /* tp_itemsize */ - /* methods */ - (destructor)mbidecoder_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 - | Py_TPFLAGS_BASETYPE, /* tp_flags */ - 0, /* tp_doc */ - (traverseproc)mbidecoder_traverse, /* tp_traverse */ - 0, /* tp_clear */ - 0, /* tp_richcompare */ - 0, /* tp_weaklistoffset */ - 0, /* tp_iter */ - 0, /* tp_iterext */ - mbidecoder_methods, /* tp_methods */ - 0, /* tp_members */ - codecctx_getsets, /* tp_getset */ - 0, /* tp_base */ - 0, /* tp_dict */ - 0, /* tp_descr_get */ - 0, /* tp_descr_set */ - 0, /* tp_dictoffset */ - mbidecoder_init, /* tp_init */ - 0, /* tp_alloc */ - mbidecoder_new, /* tp_new */ + PyVarObject_HEAD_INIT(NULL, 0) + "MultibyteIncrementalDecoder", /* tp_name */ + sizeof(MultibyteIncrementalDecoderObject), /* tp_basicsize */ + 0, /* tp_itemsize */ + /* methods */ + (destructor)mbidecoder_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 + | Py_TPFLAGS_BASETYPE, /* tp_flags */ + 0, /* tp_doc */ + (traverseproc)mbidecoder_traverse, /* tp_traverse */ + 0, /* tp_clear */ + 0, /* tp_richcompare */ + 0, /* tp_weaklistoffset */ + 0, /* tp_iter */ + 0, /* tp_iterext */ + mbidecoder_methods, /* tp_methods */ + 0, /* tp_members */ + codecctx_getsets, /* tp_getset */ + 0, /* tp_base */ + 0, /* tp_dict */ + 0, /* tp_descr_get */ + 0, /* tp_descr_set */ + 0, /* tp_dictoffset */ + mbidecoder_init, /* tp_init */ + 0, /* tp_alloc */ + mbidecoder_new, /* tp_new */ }; @@ -1239,327 +1239,327 @@ static PyObject * mbstreamreader_iread(MultibyteStreamReaderObject *self, - const char *method, Py_ssize_t sizehint) + const char *method, Py_ssize_t sizehint) { - MultibyteDecodeBuffer buf; - PyObject *cres; - Py_ssize_t rsize, finalsize = 0; - - if (sizehint == 0) - return PyUnicode_FromUnicode(NULL, 0); - - buf.outobj = buf.excobj = NULL; - cres = NULL; - - for (;;) { - int endoffile; - - if (sizehint < 0) - cres = PyObject_CallMethod(self->stream, - (char *)method, NULL); - else - cres = PyObject_CallMethod(self->stream, - (char *)method, "i", sizehint); - if (cres == NULL) - goto errorexit; - - if (!PyBytes_Check(cres)) { - PyErr_Format(PyExc_TypeError, - "stream function returned a " - "non-bytes object (%.100s)", - cres->ob_type->tp_name); - goto errorexit; - } - - endoffile = (PyBytes_GET_SIZE(cres) == 0); - - if (self->pendingsize > 0) { - PyObject *ctr; - char *ctrdata; - - if (PyBytes_GET_SIZE(cres) > PY_SSIZE_T_MAX - self->pendingsize) { - PyErr_NoMemory(); - goto errorexit; - } - rsize = PyBytes_GET_SIZE(cres) + self->pendingsize; - ctr = PyBytes_FromStringAndSize(NULL, rsize); - if (ctr == NULL) - goto errorexit; - ctrdata = PyBytes_AS_STRING(ctr); - memcpy(ctrdata, self->pending, self->pendingsize); - memcpy(ctrdata + self->pendingsize, - PyBytes_AS_STRING(cres), - PyBytes_GET_SIZE(cres)); - Py_DECREF(cres); - cres = ctr; - self->pendingsize = 0; - } - - rsize = PyBytes_GET_SIZE(cres); - if (decoder_prepare_buffer(&buf, PyBytes_AS_STRING(cres), - rsize) != 0) - goto errorexit; - - if (rsize > 0 && decoder_feed_buffer( - (MultibyteStatefulDecoderContext *)self, &buf)) - goto errorexit; - - if (endoffile || sizehint < 0) { - if (buf.inbuf < buf.inbuf_end && - multibytecodec_decerror(self->codec, &self->state, - &buf, self->errors, MBERR_TOOFEW)) - goto errorexit; - } - - if (buf.inbuf < buf.inbuf_end) { /* pending sequence exists */ - if (decoder_append_pending(STATEFUL_DCTX(self), - &buf) != 0) - goto errorexit; - } - - finalsize = (Py_ssize_t)(buf.outbuf - - PyUnicode_AS_UNICODE(buf.outobj)); - Py_DECREF(cres); - cres = NULL; - - if (sizehint < 0 || finalsize != 0 || rsize == 0) - break; - - sizehint = 1; /* read 1 more byte and retry */ - } - - if (finalsize != PyUnicode_GET_SIZE(buf.outobj)) - if (PyUnicode_Resize(&buf.outobj, finalsize) == -1) - goto errorexit; - - Py_XDECREF(cres); - Py_XDECREF(buf.excobj); - return buf.outobj; + MultibyteDecodeBuffer buf; + PyObject *cres; + Py_ssize_t rsize, finalsize = 0; + + if (sizehint == 0) + return PyUnicode_FromUnicode(NULL, 0); + + buf.outobj = buf.excobj = NULL; + cres = NULL; + + for (;;) { + int endoffile; + + if (sizehint < 0) + cres = PyObject_CallMethod(self->stream, + (char *)method, NULL); + else + cres = PyObject_CallMethod(self->stream, + (char *)method, "i", sizehint); + if (cres == NULL) + goto errorexit; + + if (!PyBytes_Check(cres)) { + PyErr_Format(PyExc_TypeError, + "stream function returned a " + "non-bytes object (%.100s)", + cres->ob_type->tp_name); + goto errorexit; + } + + endoffile = (PyBytes_GET_SIZE(cres) == 0); + + if (self->pendingsize > 0) { + PyObject *ctr; + char *ctrdata; + + if (PyBytes_GET_SIZE(cres) > PY_SSIZE_T_MAX - self->pendingsize) { + PyErr_NoMemory(); + goto errorexit; + } + rsize = PyBytes_GET_SIZE(cres) + self->pendingsize; + ctr = PyBytes_FromStringAndSize(NULL, rsize); + if (ctr == NULL) + goto errorexit; + ctrdata = PyBytes_AS_STRING(ctr); + memcpy(ctrdata, self->pending, self->pendingsize); + memcpy(ctrdata + self->pendingsize, + PyBytes_AS_STRING(cres), + PyBytes_GET_SIZE(cres)); + Py_DECREF(cres); + cres = ctr; + self->pendingsize = 0; + } + + rsize = PyBytes_GET_SIZE(cres); + if (decoder_prepare_buffer(&buf, PyBytes_AS_STRING(cres), + rsize) != 0) + goto errorexit; + + if (rsize > 0 && decoder_feed_buffer( + (MultibyteStatefulDecoderContext *)self, &buf)) + goto errorexit; + + if (endoffile || sizehint < 0) { + if (buf.inbuf < buf.inbuf_end && + multibytecodec_decerror(self->codec, &self->state, + &buf, self->errors, MBERR_TOOFEW)) + goto errorexit; + } + + if (buf.inbuf < buf.inbuf_end) { /* pending sequence exists */ + if (decoder_append_pending(STATEFUL_DCTX(self), + &buf) != 0) + goto errorexit; + } + + finalsize = (Py_ssize_t)(buf.outbuf - + PyUnicode_AS_UNICODE(buf.outobj)); + Py_DECREF(cres); + cres = NULL; + + if (sizehint < 0 || finalsize != 0 || rsize == 0) + break; + + sizehint = 1; /* read 1 more byte and retry */ + } + + if (finalsize != PyUnicode_GET_SIZE(buf.outobj)) + if (PyUnicode_Resize(&buf.outobj, finalsize) == -1) + goto errorexit; + + Py_XDECREF(cres); + Py_XDECREF(buf.excobj); + return buf.outobj; errorexit: - Py_XDECREF(cres); - Py_XDECREF(buf.excobj); - Py_XDECREF(buf.outobj); - return NULL; + Py_XDECREF(cres); + Py_XDECREF(buf.excobj); + Py_XDECREF(buf.outobj); + return NULL; } static PyObject * mbstreamreader_read(MultibyteStreamReaderObject *self, PyObject *args) { - PyObject *sizeobj = NULL; - Py_ssize_t size; + PyObject *sizeobj = NULL; + Py_ssize_t size; - if (!PyArg_UnpackTuple(args, "read", 0, 1, &sizeobj)) - return NULL; + if (!PyArg_UnpackTuple(args, "read", 0, 1, &sizeobj)) + return NULL; - if (sizeobj == Py_None || sizeobj == NULL) - size = -1; - else if (PyLong_Check(sizeobj)) - size = PyLong_AsSsize_t(sizeobj); - else { - PyErr_SetString(PyExc_TypeError, "arg 1 must be an integer"); - return NULL; - } + if (sizeobj == Py_None || sizeobj == NULL) + size = -1; + else if (PyLong_Check(sizeobj)) + size = PyLong_AsSsize_t(sizeobj); + else { + PyErr_SetString(PyExc_TypeError, "arg 1 must be an integer"); + return NULL; + } - if (size == -1 && PyErr_Occurred()) - return NULL; + if (size == -1 && PyErr_Occurred()) + return NULL; - return mbstreamreader_iread(self, "read", size); + return mbstreamreader_iread(self, "read", size); } static PyObject * mbstreamreader_readline(MultibyteStreamReaderObject *self, PyObject *args) { - PyObject *sizeobj = NULL; - Py_ssize_t size; + PyObject *sizeobj = NULL; + Py_ssize_t size; - if (!PyArg_UnpackTuple(args, "readline", 0, 1, &sizeobj)) - return NULL; + if (!PyArg_UnpackTuple(args, "readline", 0, 1, &sizeobj)) + return NULL; - if (sizeobj == Py_None || sizeobj == NULL) - size = -1; - else if (PyLong_Check(sizeobj)) - size = PyLong_AsSsize_t(sizeobj); - else { - PyErr_SetString(PyExc_TypeError, "arg 1 must be an integer"); - return NULL; - } + if (sizeobj == Py_None || sizeobj == NULL) + size = -1; + else if (PyLong_Check(sizeobj)) + size = PyLong_AsSsize_t(sizeobj); + else { + PyErr_SetString(PyExc_TypeError, "arg 1 must be an integer"); + return NULL; + } - if (size == -1 && PyErr_Occurred()) - return NULL; + if (size == -1 && PyErr_Occurred()) + return NULL; - return mbstreamreader_iread(self, "readline", size); + return mbstreamreader_iread(self, "readline", size); } static PyObject * mbstreamreader_readlines(MultibyteStreamReaderObject *self, PyObject *args) { - PyObject *sizehintobj = NULL, *r, *sr; - Py_ssize_t sizehint; + PyObject *sizehintobj = NULL, *r, *sr; + Py_ssize_t sizehint; - if (!PyArg_UnpackTuple(args, "readlines", 0, 1, &sizehintobj)) - return NULL; + if (!PyArg_UnpackTuple(args, "readlines", 0, 1, &sizehintobj)) + return NULL; - if (sizehintobj == Py_None || sizehintobj == NULL) - sizehint = -1; - else if (PyLong_Check(sizehintobj)) - sizehint = PyLong_AsSsize_t(sizehintobj); - else { - PyErr_SetString(PyExc_TypeError, "arg 1 must be an integer"); - return NULL; - } - - if (sizehint == -1 && PyErr_Occurred()) - return NULL; - - r = mbstreamreader_iread(self, "read", sizehint); - if (r == NULL) - return NULL; - - sr = PyUnicode_Splitlines(r, 1); - Py_DECREF(r); - return sr; + if (sizehintobj == Py_None || sizehintobj == NULL) + sizehint = -1; + else if (PyLong_Check(sizehintobj)) + sizehint = PyLong_AsSsize_t(sizehintobj); + else { + PyErr_SetString(PyExc_TypeError, "arg 1 must be an integer"); + return NULL; + } + + if (sizehint == -1 && PyErr_Occurred()) + return NULL; + + r = mbstreamreader_iread(self, "read", sizehint); + if (r == NULL) + return NULL; + + sr = PyUnicode_Splitlines(r, 1); + Py_DECREF(r); + return sr; } static PyObject * mbstreamreader_reset(MultibyteStreamReaderObject *self) { - if (self->codec->decreset != NULL && - self->codec->decreset(&self->state, self->codec->config) != 0) - return NULL; - self->pendingsize = 0; + if (self->codec->decreset != NULL && + self->codec->decreset(&self->state, self->codec->config) != 0) + return NULL; + self->pendingsize = 0; - Py_RETURN_NONE; + Py_RETURN_NONE; } static struct PyMethodDef mbstreamreader_methods[] = { - {"read", (PyCFunction)mbstreamreader_read, - METH_VARARGS, NULL}, - {"readline", (PyCFunction)mbstreamreader_readline, - METH_VARARGS, NULL}, - {"readlines", (PyCFunction)mbstreamreader_readlines, - METH_VARARGS, NULL}, - {"reset", (PyCFunction)mbstreamreader_reset, - METH_NOARGS, NULL}, - {NULL, NULL}, + {"read", (PyCFunction)mbstreamreader_read, + METH_VARARGS, NULL}, + {"readline", (PyCFunction)mbstreamreader_readline, + METH_VARARGS, NULL}, + {"readlines", (PyCFunction)mbstreamreader_readlines, + METH_VARARGS, NULL}, + {"reset", (PyCFunction)mbstreamreader_reset, + METH_NOARGS, NULL}, + {NULL, NULL}, }; static PyMemberDef mbstreamreader_members[] = { - {"stream", T_OBJECT, - offsetof(MultibyteStreamReaderObject, stream), - READONLY, NULL}, - {NULL,} + {"stream", T_OBJECT, + offsetof(MultibyteStreamReaderObject, stream), + READONLY, NULL}, + {NULL,} }; static PyObject * mbstreamreader_new(PyTypeObject *type, PyObject *args, PyObject *kwds) { - MultibyteStreamReaderObject *self; - PyObject *stream, *codec = NULL; - char *errors = NULL; - - if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|s:StreamReader", - streamkwarglist, &stream, &errors)) - return NULL; - - self = (MultibyteStreamReaderObject *)type->tp_alloc(type, 0); - if (self == NULL) - return NULL; - - codec = PyObject_GetAttrString((PyObject *)type, "codec"); - if (codec == NULL) - goto errorexit; - if (!MultibyteCodec_Check(codec)) { - PyErr_SetString(PyExc_TypeError, "codec is unexpected type"); - goto errorexit; - } - - self->codec = ((MultibyteCodecObject *)codec)->codec; - self->stream = stream; - Py_INCREF(stream); - self->pendingsize = 0; - self->errors = internal_error_callback(errors); - if (self->errors == NULL) - goto errorexit; - if (self->codec->decinit != NULL && - self->codec->decinit(&self->state, self->codec->config) != 0) - goto errorexit; + MultibyteStreamReaderObject *self; + PyObject *stream, *codec = NULL; + char *errors = NULL; + + if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|s:StreamReader", + streamkwarglist, &stream, &errors)) + return NULL; + + self = (MultibyteStreamReaderObject *)type->tp_alloc(type, 0); + if (self == NULL) + return NULL; + + codec = PyObject_GetAttrString((PyObject *)type, "codec"); + if (codec == NULL) + goto errorexit; + if (!MultibyteCodec_Check(codec)) { + PyErr_SetString(PyExc_TypeError, "codec is unexpected type"); + goto errorexit; + } + + self->codec = ((MultibyteCodecObject *)codec)->codec; + self->stream = stream; + Py_INCREF(stream); + self->pendingsize = 0; + self->errors = internal_error_callback(errors); + if (self->errors == NULL) + goto errorexit; + if (self->codec->decinit != NULL && + self->codec->decinit(&self->state, self->codec->config) != 0) + goto errorexit; - Py_DECREF(codec); - return (PyObject *)self; + Py_DECREF(codec); + return (PyObject *)self; errorexit: - Py_XDECREF(self); - Py_XDECREF(codec); - return NULL; + Py_XDECREF(self); + Py_XDECREF(codec); + return NULL; } static int mbstreamreader_init(PyObject *self, PyObject *args, PyObject *kwds) { - return 0; + return 0; } static int mbstreamreader_traverse(MultibyteStreamReaderObject *self, - visitproc visit, void *arg) + visitproc visit, void *arg) { - if (ERROR_ISCUSTOM(self->errors)) - Py_VISIT(self->errors); - Py_VISIT(self->stream); - return 0; + if (ERROR_ISCUSTOM(self->errors)) + Py_VISIT(self->errors); + Py_VISIT(self->stream); + return 0; } static void mbstreamreader_dealloc(MultibyteStreamReaderObject *self) { - PyObject_GC_UnTrack(self); - ERROR_DECREF(self->errors); - Py_XDECREF(self->stream); - Py_TYPE(self)->tp_free(self); + PyObject_GC_UnTrack(self); + ERROR_DECREF(self->errors); + Py_XDECREF(self->stream); + Py_TYPE(self)->tp_free(self); } static PyTypeObject MultibyteStreamReader_Type = { - PyVarObject_HEAD_INIT(NULL, 0) - "MultibyteStreamReader", /* tp_name */ - sizeof(MultibyteStreamReaderObject), /* tp_basicsize */ - 0, /* tp_itemsize */ - /* methods */ - (destructor)mbstreamreader_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 - | Py_TPFLAGS_BASETYPE, /* tp_flags */ - 0, /* tp_doc */ - (traverseproc)mbstreamreader_traverse, /* tp_traverse */ - 0, /* tp_clear */ - 0, /* tp_richcompare */ - 0, /* tp_weaklistoffset */ - 0, /* tp_iter */ - 0, /* tp_iterext */ - mbstreamreader_methods, /* tp_methods */ - mbstreamreader_members, /* tp_members */ - codecctx_getsets, /* tp_getset */ - 0, /* tp_base */ - 0, /* tp_dict */ - 0, /* tp_descr_get */ - 0, /* tp_descr_set */ - 0, /* tp_dictoffset */ - mbstreamreader_init, /* tp_init */ - 0, /* tp_alloc */ - mbstreamreader_new, /* tp_new */ + PyVarObject_HEAD_INIT(NULL, 0) + "MultibyteStreamReader", /* tp_name */ + sizeof(MultibyteStreamReaderObject), /* tp_basicsize */ + 0, /* tp_itemsize */ + /* methods */ + (destructor)mbstreamreader_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 + | Py_TPFLAGS_BASETYPE, /* tp_flags */ + 0, /* tp_doc */ + (traverseproc)mbstreamreader_traverse, /* tp_traverse */ + 0, /* tp_clear */ + 0, /* tp_richcompare */ + 0, /* tp_weaklistoffset */ + 0, /* tp_iter */ + 0, /* tp_iterext */ + mbstreamreader_methods, /* tp_methods */ + mbstreamreader_members, /* tp_members */ + codecctx_getsets, /* tp_getset */ + 0, /* tp_base */ + 0, /* tp_dict */ + 0, /* tp_descr_get */ + 0, /* tp_descr_set */ + 0, /* tp_dictoffset */ + mbstreamreader_init, /* tp_init */ + 0, /* tp_alloc */ + mbstreamreader_new, /* tp_new */ }; @@ -1569,217 +1569,217 @@ static int mbstreamwriter_iwrite(MultibyteStreamWriterObject *self, - PyObject *unistr) + PyObject *unistr) { - PyObject *str, *wr; + PyObject *str, *wr; - str = encoder_encode_stateful(STATEFUL_ECTX(self), unistr, 0); - if (str == NULL) - return -1; + str = encoder_encode_stateful(STATEFUL_ECTX(self), unistr, 0); + if (str == NULL) + return -1; - wr = PyObject_CallMethod(self->stream, "write", "O", str); - Py_DECREF(str); - if (wr == NULL) - return -1; + wr = PyObject_CallMethod(self->stream, "write", "O", str); + Py_DECREF(str); + if (wr == NULL) + return -1; - Py_DECREF(wr); - return 0; + Py_DECREF(wr); + return 0; } static PyObject * mbstreamwriter_write(MultibyteStreamWriterObject *self, PyObject *strobj) { - if (mbstreamwriter_iwrite(self, strobj)) - return NULL; - else - Py_RETURN_NONE; + if (mbstreamwriter_iwrite(self, strobj)) + return NULL; + else + Py_RETURN_NONE; } static PyObject * mbstreamwriter_writelines(MultibyteStreamWriterObject *self, PyObject *lines) { - PyObject *strobj; - int i, r; + PyObject *strobj; + int i, r; - if (!PySequence_Check(lines)) { - PyErr_SetString(PyExc_TypeError, - "arg must be a sequence object"); - return NULL; - } - - for (i = 0; i < PySequence_Length(lines); i++) { - /* length can be changed even within this loop */ - strobj = PySequence_GetItem(lines, i); - if (strobj == NULL) - return NULL; - - r = mbstreamwriter_iwrite(self, strobj); - Py_DECREF(strobj); - if (r == -1) - return NULL; - } + if (!PySequence_Check(lines)) { + PyErr_SetString(PyExc_TypeError, + "arg must be a sequence object"); + return NULL; + } + + for (i = 0; i < PySequence_Length(lines); i++) { + /* length can be changed even within this loop */ + strobj = PySequence_GetItem(lines, i); + if (strobj == NULL) + return NULL; + + r = mbstreamwriter_iwrite(self, strobj); + Py_DECREF(strobj); + if (r == -1) + return NULL; + } - Py_RETURN_NONE; + Py_RETURN_NONE; } static PyObject * mbstreamwriter_reset(MultibyteStreamWriterObject *self) { - const Py_UNICODE *pending; - PyObject *pwrt; + const Py_UNICODE *pending; + PyObject *pwrt; - pending = self->pending; - pwrt = multibytecodec_encode(self->codec, &self->state, - &pending, self->pendingsize, self->errors, - MBENC_FLUSH | MBENC_RESET); - /* some pending buffer can be truncated when UnicodeEncodeError is - * raised on 'strict' mode. but, 'reset' method is designed to - * reset the pending buffer or states so failed string sequence - * ought to be missed */ - self->pendingsize = 0; - if (pwrt == NULL) - return NULL; - - assert(PyBytes_Check(pwrt)); - if (PyBytes_Size(pwrt) > 0) { - PyObject *wr; - wr = PyObject_CallMethod(self->stream, "write", "O", pwrt); - if (wr == NULL) { - Py_DECREF(pwrt); - return NULL; - } - } - Py_DECREF(pwrt); + pending = self->pending; + pwrt = multibytecodec_encode(self->codec, &self->state, + &pending, self->pendingsize, self->errors, + MBENC_FLUSH | MBENC_RESET); + /* some pending buffer can be truncated when UnicodeEncodeError is + * raised on 'strict' mode. but, 'reset' method is designed to + * reset the pending buffer or states so failed string sequence + * ought to be missed */ + self->pendingsize = 0; + if (pwrt == NULL) + return NULL; + + assert(PyBytes_Check(pwrt)); + if (PyBytes_Size(pwrt) > 0) { + PyObject *wr; + wr = PyObject_CallMethod(self->stream, "write", "O", pwrt); + if (wr == NULL) { + Py_DECREF(pwrt); + return NULL; + } + } + Py_DECREF(pwrt); - Py_RETURN_NONE; + Py_RETURN_NONE; } static PyObject * mbstreamwriter_new(PyTypeObject *type, PyObject *args, PyObject *kwds) { - MultibyteStreamWriterObject *self; - PyObject *stream, *codec = NULL; - char *errors = NULL; - - if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|s:StreamWriter", - streamkwarglist, &stream, &errors)) - return NULL; - - self = (MultibyteStreamWriterObject *)type->tp_alloc(type, 0); - if (self == NULL) - return NULL; - - codec = PyObject_GetAttrString((PyObject *)type, "codec"); - if (codec == NULL) - goto errorexit; - if (!MultibyteCodec_Check(codec)) { - PyErr_SetString(PyExc_TypeError, "codec is unexpected type"); - goto errorexit; - } - - self->codec = ((MultibyteCodecObject *)codec)->codec; - self->stream = stream; - Py_INCREF(stream); - self->pendingsize = 0; - self->errors = internal_error_callback(errors); - if (self->errors == NULL) - goto errorexit; - if (self->codec->encinit != NULL && - self->codec->encinit(&self->state, self->codec->config) != 0) - goto errorexit; + MultibyteStreamWriterObject *self; + PyObject *stream, *codec = NULL; + char *errors = NULL; + + if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|s:StreamWriter", + streamkwarglist, &stream, &errors)) + return NULL; + + self = (MultibyteStreamWriterObject *)type->tp_alloc(type, 0); + if (self == NULL) + return NULL; + + codec = PyObject_GetAttrString((PyObject *)type, "codec"); + if (codec == NULL) + goto errorexit; + if (!MultibyteCodec_Check(codec)) { + PyErr_SetString(PyExc_TypeError, "codec is unexpected type"); + goto errorexit; + } + + self->codec = ((MultibyteCodecObject *)codec)->codec; + self->stream = stream; + Py_INCREF(stream); + self->pendingsize = 0; + self->errors = internal_error_callback(errors); + if (self->errors == NULL) + goto errorexit; + if (self->codec->encinit != NULL && + self->codec->encinit(&self->state, self->codec->config) != 0) + goto errorexit; - Py_DECREF(codec); - return (PyObject *)self; + Py_DECREF(codec); + return (PyObject *)self; errorexit: - Py_XDECREF(self); - Py_XDECREF(codec); - return NULL; + Py_XDECREF(self); + Py_XDECREF(codec); + return NULL; } static int mbstreamwriter_init(PyObject *self, PyObject *args, PyObject *kwds) { - return 0; + return 0; } static int mbstreamwriter_traverse(MultibyteStreamWriterObject *self, - visitproc visit, void *arg) + visitproc visit, void *arg) { - if (ERROR_ISCUSTOM(self->errors)) - Py_VISIT(self->errors); - Py_VISIT(self->stream); - return 0; + if (ERROR_ISCUSTOM(self->errors)) + Py_VISIT(self->errors); + Py_VISIT(self->stream); + return 0; } static void mbstreamwriter_dealloc(MultibyteStreamWriterObject *self) { - PyObject_GC_UnTrack(self); - ERROR_DECREF(self->errors); - Py_XDECREF(self->stream); - Py_TYPE(self)->tp_free(self); + PyObject_GC_UnTrack(self); + ERROR_DECREF(self->errors); + Py_XDECREF(self->stream); + Py_TYPE(self)->tp_free(self); } static struct PyMethodDef mbstreamwriter_methods[] = { - {"write", (PyCFunction)mbstreamwriter_write, - METH_O, NULL}, - {"writelines", (PyCFunction)mbstreamwriter_writelines, - METH_O, NULL}, - {"reset", (PyCFunction)mbstreamwriter_reset, - METH_NOARGS, NULL}, - {NULL, NULL}, + {"write", (PyCFunction)mbstreamwriter_write, + METH_O, NULL}, + {"writelines", (PyCFunction)mbstreamwriter_writelines, + METH_O, NULL}, + {"reset", (PyCFunction)mbstreamwriter_reset, + METH_NOARGS, NULL}, + {NULL, NULL}, }; static PyMemberDef mbstreamwriter_members[] = { - {"stream", T_OBJECT, - offsetof(MultibyteStreamWriterObject, stream), - READONLY, NULL}, - {NULL,} + {"stream", T_OBJECT, + offsetof(MultibyteStreamWriterObject, stream), + READONLY, NULL}, + {NULL,} }; static PyTypeObject MultibyteStreamWriter_Type = { - PyVarObject_HEAD_INIT(NULL, 0) - "MultibyteStreamWriter", /* tp_name */ - sizeof(MultibyteStreamWriterObject), /* tp_basicsize */ - 0, /* tp_itemsize */ - /* methods */ - (destructor)mbstreamwriter_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 - | Py_TPFLAGS_BASETYPE, /* tp_flags */ - 0, /* tp_doc */ - (traverseproc)mbstreamwriter_traverse, /* tp_traverse */ - 0, /* tp_clear */ - 0, /* tp_richcompare */ - 0, /* tp_weaklistoffset */ - 0, /* tp_iter */ - 0, /* tp_iterext */ - mbstreamwriter_methods, /* tp_methods */ - mbstreamwriter_members, /* tp_members */ - codecctx_getsets, /* tp_getset */ - 0, /* tp_base */ - 0, /* tp_dict */ - 0, /* tp_descr_get */ - 0, /* tp_descr_set */ - 0, /* tp_dictoffset */ - mbstreamwriter_init, /* tp_init */ - 0, /* tp_alloc */ - mbstreamwriter_new, /* tp_new */ + PyVarObject_HEAD_INIT(NULL, 0) + "MultibyteStreamWriter", /* tp_name */ + sizeof(MultibyteStreamWriterObject), /* tp_basicsize */ + 0, /* tp_itemsize */ + /* methods */ + (destructor)mbstreamwriter_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 + | Py_TPFLAGS_BASETYPE, /* tp_flags */ + 0, /* tp_doc */ + (traverseproc)mbstreamwriter_traverse, /* tp_traverse */ + 0, /* tp_clear */ + 0, /* tp_richcompare */ + 0, /* tp_weaklistoffset */ + 0, /* tp_iter */ + 0, /* tp_iterext */ + mbstreamwriter_methods, /* tp_methods */ + mbstreamwriter_members, /* tp_members */ + codecctx_getsets, /* tp_getset */ + 0, /* tp_base */ + 0, /* tp_dict */ + 0, /* tp_descr_get */ + 0, /* tp_descr_set */ + 0, /* tp_dictoffset */ + mbstreamwriter_init, /* tp_init */ + 0, /* tp_alloc */ + mbstreamwriter_new, /* tp_new */ }; @@ -1790,76 +1790,76 @@ static PyObject * __create_codec(PyObject *ignore, PyObject *arg) { - MultibyteCodecObject *self; - MultibyteCodec *codec; + MultibyteCodecObject *self; + MultibyteCodec *codec; - if (!PyCapsule_IsValid(arg, PyMultibyteCodec_CAPSULE_NAME)) { - PyErr_SetString(PyExc_ValueError, "argument type invalid"); - return NULL; - } - - codec = PyCapsule_GetPointer(arg, PyMultibyteCodec_CAPSULE_NAME); - if (codec->codecinit != NULL && codec->codecinit(codec->config) != 0) - return NULL; - - self = PyObject_New(MultibyteCodecObject, &MultibyteCodec_Type); - if (self == NULL) - return NULL; - self->codec = codec; + if (!PyCapsule_IsValid(arg, PyMultibyteCodec_CAPSULE_NAME)) { + PyErr_SetString(PyExc_ValueError, "argument type invalid"); + return NULL; + } + + codec = PyCapsule_GetPointer(arg, PyMultibyteCodec_CAPSULE_NAME); + if (codec->codecinit != NULL && codec->codecinit(codec->config) != 0) + return NULL; + + self = PyObject_New(MultibyteCodecObject, &MultibyteCodec_Type); + if (self == NULL) + return NULL; + self->codec = codec; - return (PyObject *)self; + return (PyObject *)self; } static struct PyMethodDef __methods[] = { - {"__create_codec", (PyCFunction)__create_codec, METH_O}, - {NULL, NULL}, + {"__create_codec", (PyCFunction)__create_codec, METH_O}, + {NULL, NULL}, }; static struct PyModuleDef _multibytecodecmodule = { - PyModuleDef_HEAD_INIT, - "_multibytecodec", - NULL, - -1, - __methods, - NULL, - NULL, - NULL, - NULL + PyModuleDef_HEAD_INIT, + "_multibytecodec", + NULL, + -1, + __methods, + NULL, + NULL, + NULL, + NULL }; PyMODINIT_FUNC PyInit__multibytecodec(void) { - int i; - PyObject *m; - PyTypeObject *typelist[] = { - &MultibyteIncrementalEncoder_Type, - &MultibyteIncrementalDecoder_Type, - &MultibyteStreamReader_Type, - &MultibyteStreamWriter_Type, - NULL - }; - - if (PyType_Ready(&MultibyteCodec_Type) < 0) - return NULL; - - m = PyModule_Create(&_multibytecodecmodule); - if (m == NULL) - return NULL; - - for (i = 0; typelist[i] != NULL; i++) { - if (PyType_Ready(typelist[i]) < 0) - return NULL; - Py_INCREF(typelist[i]); - PyModule_AddObject(m, typelist[i]->tp_name, - (PyObject *)typelist[i]); - } - - if (PyErr_Occurred()) { - Py_FatalError("can't initialize the _multibytecodec module"); - Py_DECREF(m); - m = NULL; - } - return m; + int i; + PyObject *m; + PyTypeObject *typelist[] = { + &MultibyteIncrementalEncoder_Type, + &MultibyteIncrementalDecoder_Type, + &MultibyteStreamReader_Type, + &MultibyteStreamWriter_Type, + NULL + }; + + if (PyType_Ready(&MultibyteCodec_Type) < 0) + return NULL; + + m = PyModule_Create(&_multibytecodecmodule); + if (m == NULL) + return NULL; + + for (i = 0; typelist[i] != NULL; i++) { + if (PyType_Ready(typelist[i]) < 0) + return NULL; + Py_INCREF(typelist[i]); + PyModule_AddObject(m, typelist[i]->tp_name, + (PyObject *)typelist[i]); + } + + if (PyErr_Occurred()) { + Py_FatalError("can't initialize the _multibytecodec module"); + Py_DECREF(m); + m = NULL; + } + return m; } Modified: python/branches/py3k/Modules/cjkcodecs/multibytecodec.h ============================================================================== --- python/branches/py3k/Modules/cjkcodecs/multibytecodec.h (original) +++ python/branches/py3k/Modules/cjkcodecs/multibytecodec.h Sun May 9 17:52:27 2010 @@ -23,114 +23,114 @@ #endif typedef union { - void *p; - int i; - unsigned char c[8]; - ucs2_t u2[4]; - ucs4_t u4[2]; + void *p; + int i; + unsigned char c[8]; + ucs2_t u2[4]; + ucs4_t u4[2]; } MultibyteCodec_State; typedef int (*mbcodec_init)(const void *config); typedef Py_ssize_t (*mbencode_func)(MultibyteCodec_State *state, - const void *config, - const Py_UNICODE **inbuf, Py_ssize_t inleft, - unsigned char **outbuf, Py_ssize_t outleft, - int flags); + const void *config, + const Py_UNICODE **inbuf, Py_ssize_t inleft, + unsigned char **outbuf, Py_ssize_t outleft, + int flags); typedef int (*mbencodeinit_func)(MultibyteCodec_State *state, - const void *config); + const void *config); typedef Py_ssize_t (*mbencodereset_func)(MultibyteCodec_State *state, - const void *config, - unsigned char **outbuf, Py_ssize_t outleft); + const void *config, + unsigned char **outbuf, Py_ssize_t outleft); typedef Py_ssize_t (*mbdecode_func)(MultibyteCodec_State *state, - const void *config, - const unsigned char **inbuf, Py_ssize_t inleft, - Py_UNICODE **outbuf, Py_ssize_t outleft); + const void *config, + const unsigned char **inbuf, Py_ssize_t inleft, + Py_UNICODE **outbuf, Py_ssize_t outleft); typedef int (*mbdecodeinit_func)(MultibyteCodec_State *state, - const void *config); + const void *config); typedef Py_ssize_t (*mbdecodereset_func)(MultibyteCodec_State *state, - const void *config); + const void *config); typedef struct { - const char *encoding; - const void *config; - mbcodec_init codecinit; - mbencode_func encode; - mbencodeinit_func encinit; - mbencodereset_func encreset; - mbdecode_func decode; - mbdecodeinit_func decinit; - mbdecodereset_func decreset; + const char *encoding; + const void *config; + mbcodec_init codecinit; + mbencode_func encode; + mbencodeinit_func encinit; + mbencodereset_func encreset; + mbdecode_func decode; + mbdecodeinit_func decinit; + mbdecodereset_func decreset; } MultibyteCodec; typedef struct { - PyObject_HEAD - MultibyteCodec *codec; + PyObject_HEAD + MultibyteCodec *codec; } MultibyteCodecObject; #define MultibyteCodec_Check(op) ((op)->ob_type == &MultibyteCodec_Type) -#define _MultibyteStatefulCodec_HEAD \ - PyObject_HEAD \ - MultibyteCodec *codec; \ - MultibyteCodec_State state; \ - PyObject *errors; +#define _MultibyteStatefulCodec_HEAD \ + PyObject_HEAD \ + MultibyteCodec *codec; \ + MultibyteCodec_State state; \ + PyObject *errors; typedef struct { - _MultibyteStatefulCodec_HEAD + _MultibyteStatefulCodec_HEAD } MultibyteStatefulCodecContext; -#define MAXENCPENDING 2 -#define _MultibyteStatefulEncoder_HEAD \ - _MultibyteStatefulCodec_HEAD \ - Py_UNICODE pending[MAXENCPENDING]; \ - Py_ssize_t pendingsize; +#define MAXENCPENDING 2 +#define _MultibyteStatefulEncoder_HEAD \ + _MultibyteStatefulCodec_HEAD \ + Py_UNICODE pending[MAXENCPENDING]; \ + Py_ssize_t pendingsize; typedef struct { - _MultibyteStatefulEncoder_HEAD + _MultibyteStatefulEncoder_HEAD } MultibyteStatefulEncoderContext; -#define MAXDECPENDING 8 -#define _MultibyteStatefulDecoder_HEAD \ - _MultibyteStatefulCodec_HEAD \ - unsigned char pending[MAXDECPENDING]; \ - Py_ssize_t pendingsize; +#define MAXDECPENDING 8 +#define _MultibyteStatefulDecoder_HEAD \ + _MultibyteStatefulCodec_HEAD \ + unsigned char pending[MAXDECPENDING]; \ + Py_ssize_t pendingsize; typedef struct { - _MultibyteStatefulDecoder_HEAD + _MultibyteStatefulDecoder_HEAD } MultibyteStatefulDecoderContext; typedef struct { - _MultibyteStatefulEncoder_HEAD + _MultibyteStatefulEncoder_HEAD } MultibyteIncrementalEncoderObject; typedef struct { - _MultibyteStatefulDecoder_HEAD + _MultibyteStatefulDecoder_HEAD } MultibyteIncrementalDecoderObject; typedef struct { - _MultibyteStatefulDecoder_HEAD - PyObject *stream; + _MultibyteStatefulDecoder_HEAD + PyObject *stream; } MultibyteStreamReaderObject; typedef struct { - _MultibyteStatefulEncoder_HEAD - PyObject *stream; + _MultibyteStatefulEncoder_HEAD + PyObject *stream; } MultibyteStreamWriterObject; /* positive values for illegal sequences */ -#define MBERR_TOOSMALL (-1) /* insufficient output buffer space */ -#define MBERR_TOOFEW (-2) /* incomplete input buffer */ -#define MBERR_INTERNAL (-3) /* internal runtime error */ - -#define ERROR_STRICT (PyObject *)(1) -#define ERROR_IGNORE (PyObject *)(2) -#define ERROR_REPLACE (PyObject *)(3) -#define ERROR_ISCUSTOM(p) ((p) < ERROR_STRICT || ERROR_REPLACE < (p)) -#define ERROR_DECREF(p) do { \ - if (p != NULL && ERROR_ISCUSTOM(p)) { \ - Py_DECREF(p); \ - } \ +#define MBERR_TOOSMALL (-1) /* insufficient output buffer space */ +#define MBERR_TOOFEW (-2) /* incomplete input buffer */ +#define MBERR_INTERNAL (-3) /* internal runtime error */ + +#define ERROR_STRICT (PyObject *)(1) +#define ERROR_IGNORE (PyObject *)(2) +#define ERROR_REPLACE (PyObject *)(3) +#define ERROR_ISCUSTOM(p) ((p) < ERROR_STRICT || ERROR_REPLACE < (p)) +#define ERROR_DECREF(p) do { \ + if (p != NULL && ERROR_ISCUSTOM(p)) { \ + Py_DECREF(p); \ + } \ } while (0); -#define MBENC_FLUSH 0x0001 /* encode all characters encodable */ -#define MBENC_MAX MBENC_FLUSH +#define MBENC_FLUSH 0x0001 /* encode all characters encodable */ +#define MBENC_MAX MBENC_FLUSH #define PyMultibyteCodec_CAPSULE_NAME "multibytecodec.__map_*" Modified: python/branches/py3k/Modules/cmathmodule.c ============================================================================== --- python/branches/py3k/Modules/cmathmodule.c (original) +++ python/branches/py3k/Modules/cmathmodule.c Sun May 9 17:52:27 2010 @@ -32,7 +32,7 @@ #define CM_LOG_LARGE_DOUBLE (log(CM_LARGE_DOUBLE)) #define CM_SQRT_DBL_MIN (sqrt(DBL_MIN)) -/* +/* CM_SCALE_UP is an odd integer chosen such that multiplication by 2**CM_SCALE_UP is sufficient to turn a subnormal into a normal. CM_SCALE_DOWN is (-(CM_SCALE_UP+1)/2). These scalings are used to compute @@ -63,46 +63,46 @@ */ enum special_types { - ST_NINF, /* 0, negative infinity */ - ST_NEG, /* 1, negative finite number (nonzero) */ - ST_NZERO, /* 2, -0. */ - ST_PZERO, /* 3, +0. */ - ST_POS, /* 4, positive finite number (nonzero) */ - ST_PINF, /* 5, positive infinity */ - ST_NAN /* 6, Not a Number */ + ST_NINF, /* 0, negative infinity */ + ST_NEG, /* 1, negative finite number (nonzero) */ + ST_NZERO, /* 2, -0. */ + ST_PZERO, /* 3, +0. */ + ST_POS, /* 4, positive finite number (nonzero) */ + ST_PINF, /* 5, positive infinity */ + ST_NAN /* 6, Not a Number */ }; static enum special_types special_type(double d) { - if (Py_IS_FINITE(d)) { - if (d != 0) { - if (copysign(1., d) == 1.) - return ST_POS; - else - return ST_NEG; - } - else { - if (copysign(1., d) == 1.) - return ST_PZERO; - else - return ST_NZERO; - } - } - if (Py_IS_NAN(d)) - return ST_NAN; - if (copysign(1., d) == 1.) - return ST_PINF; - else - return ST_NINF; -} - -#define SPECIAL_VALUE(z, table) \ - if (!Py_IS_FINITE((z).real) || !Py_IS_FINITE((z).imag)) { \ - errno = 0; \ - return table[special_type((z).real)] \ - [special_type((z).imag)]; \ - } + if (Py_IS_FINITE(d)) { + if (d != 0) { + if (copysign(1., d) == 1.) + return ST_POS; + else + return ST_NEG; + } + else { + if (copysign(1., d) == 1.) + return ST_PZERO; + else + return ST_NZERO; + } + } + if (Py_IS_NAN(d)) + return ST_NAN; + if (copysign(1., d) == 1.) + return ST_PINF; + else + return ST_NINF; +} + +#define SPECIAL_VALUE(z, table) \ + if (!Py_IS_FINITE((z).real) || !Py_IS_FINITE((z).imag)) { \ + errno = 0; \ + return table[special_type((z).real)] \ + [special_type((z).imag)]; \ + } #define P Py_MATH_PI #define P14 0.25*Py_MATH_PI @@ -126,34 +126,34 @@ static Py_complex c_acos(Py_complex z) { - Py_complex s1, s2, r; + Py_complex s1, s2, r; - SPECIAL_VALUE(z, acos_special_values); + SPECIAL_VALUE(z, acos_special_values); - if (fabs(z.real) > CM_LARGE_DOUBLE || fabs(z.imag) > CM_LARGE_DOUBLE) { - /* avoid unnecessary overflow for large arguments */ - r.real = atan2(fabs(z.imag), z.real); - /* split into cases to make sure that the branch cut has the - correct continuity on systems with unsigned zeros */ - if (z.real < 0.) { - r.imag = -copysign(log(hypot(z.real/2., z.imag/2.)) + - M_LN2*2., z.imag); - } else { - r.imag = copysign(log(hypot(z.real/2., z.imag/2.)) + - M_LN2*2., -z.imag); - } - } else { - s1.real = 1.-z.real; - s1.imag = -z.imag; - s1 = c_sqrt(s1); - s2.real = 1.+z.real; - s2.imag = z.imag; - s2 = c_sqrt(s2); - r.real = 2.*atan2(s1.real, s2.real); - r.imag = m_asinh(s2.real*s1.imag - s2.imag*s1.real); - } - errno = 0; - return r; + if (fabs(z.real) > CM_LARGE_DOUBLE || fabs(z.imag) > CM_LARGE_DOUBLE) { + /* avoid unnecessary overflow for large arguments */ + r.real = atan2(fabs(z.imag), z.real); + /* split into cases to make sure that the branch cut has the + correct continuity on systems with unsigned zeros */ + if (z.real < 0.) { + r.imag = -copysign(log(hypot(z.real/2., z.imag/2.)) + + M_LN2*2., z.imag); + } else { + r.imag = copysign(log(hypot(z.real/2., z.imag/2.)) + + M_LN2*2., -z.imag); + } + } else { + s1.real = 1.-z.real; + s1.imag = -z.imag; + s1 = c_sqrt(s1); + s2.real = 1.+z.real; + s2.imag = z.imag; + s2 = c_sqrt(s2); + r.real = 2.*atan2(s1.real, s2.real); + r.imag = m_asinh(s2.real*s1.imag - s2.imag*s1.real); + } + errno = 0; + return r; } PyDoc_STRVAR(c_acos_doc, @@ -167,26 +167,26 @@ static Py_complex c_acosh(Py_complex z) { - Py_complex s1, s2, r; + Py_complex s1, s2, r; - SPECIAL_VALUE(z, acosh_special_values); + SPECIAL_VALUE(z, acosh_special_values); - if (fabs(z.real) > CM_LARGE_DOUBLE || fabs(z.imag) > CM_LARGE_DOUBLE) { - /* avoid unnecessary overflow for large arguments */ - r.real = log(hypot(z.real/2., z.imag/2.)) + M_LN2*2.; - r.imag = atan2(z.imag, z.real); - } else { - s1.real = z.real - 1.; - s1.imag = z.imag; - s1 = c_sqrt(s1); - s2.real = z.real + 1.; - s2.imag = z.imag; - s2 = c_sqrt(s2); - r.real = m_asinh(s1.real*s2.real + s1.imag*s2.imag); - r.imag = 2.*atan2(s1.imag, s2.real); - } - errno = 0; - return r; + if (fabs(z.real) > CM_LARGE_DOUBLE || fabs(z.imag) > CM_LARGE_DOUBLE) { + /* avoid unnecessary overflow for large arguments */ + r.real = log(hypot(z.real/2., z.imag/2.)) + M_LN2*2.; + r.imag = atan2(z.imag, z.real); + } else { + s1.real = z.real - 1.; + s1.imag = z.imag; + s1 = c_sqrt(s1); + s2.real = z.real + 1.; + s2.imag = z.imag; + s2 = c_sqrt(s2); + r.real = m_asinh(s1.real*s2.real + s1.imag*s2.imag); + r.imag = 2.*atan2(s1.imag, s2.real); + } + errno = 0; + return r; } PyDoc_STRVAR(c_acosh_doc, @@ -198,14 +198,14 @@ static Py_complex c_asin(Py_complex z) { - /* asin(z) = -i asinh(iz) */ - Py_complex s, r; - s.real = -z.imag; - s.imag = z.real; - s = c_asinh(s); - r.real = s.imag; - r.imag = -s.real; - return r; + /* asin(z) = -i asinh(iz) */ + Py_complex s, r; + s.real = -z.imag; + s.imag = z.real; + s = c_asinh(s); + r.real = s.imag; + r.imag = -s.real; + return r; } PyDoc_STRVAR(c_asin_doc, @@ -219,31 +219,31 @@ static Py_complex c_asinh(Py_complex z) { - Py_complex s1, s2, r; + Py_complex s1, s2, r; - SPECIAL_VALUE(z, asinh_special_values); + SPECIAL_VALUE(z, asinh_special_values); - if (fabs(z.real) > CM_LARGE_DOUBLE || fabs(z.imag) > CM_LARGE_DOUBLE) { - if (z.imag >= 0.) { - r.real = copysign(log(hypot(z.real/2., z.imag/2.)) + - M_LN2*2., z.real); - } else { - r.real = -copysign(log(hypot(z.real/2., z.imag/2.)) + - M_LN2*2., -z.real); - } - r.imag = atan2(z.imag, fabs(z.real)); - } else { - s1.real = 1.+z.imag; - s1.imag = -z.real; - s1 = c_sqrt(s1); - s2.real = 1.-z.imag; - s2.imag = z.real; - s2 = c_sqrt(s2); - r.real = m_asinh(s1.real*s2.imag-s2.real*s1.imag); - r.imag = atan2(z.imag, s1.real*s2.real-s1.imag*s2.imag); - } - errno = 0; - return r; + if (fabs(z.real) > CM_LARGE_DOUBLE || fabs(z.imag) > CM_LARGE_DOUBLE) { + if (z.imag >= 0.) { + r.real = copysign(log(hypot(z.real/2., z.imag/2.)) + + M_LN2*2., z.real); + } else { + r.real = -copysign(log(hypot(z.real/2., z.imag/2.)) + + M_LN2*2., -z.real); + } + r.imag = atan2(z.imag, fabs(z.real)); + } else { + s1.real = 1.+z.imag; + s1.imag = -z.real; + s1 = c_sqrt(s1); + s2.real = 1.-z.imag; + s2.imag = z.real; + s2 = c_sqrt(s2); + r.real = m_asinh(s1.real*s2.imag-s2.real*s1.imag); + r.imag = atan2(z.imag, s1.real*s2.real-s1.imag*s2.imag); + } + errno = 0; + return r; } PyDoc_STRVAR(c_asinh_doc, @@ -255,14 +255,14 @@ static Py_complex c_atan(Py_complex z) { - /* atan(z) = -i atanh(iz) */ - Py_complex s, r; - s.real = -z.imag; - s.imag = z.real; - s = c_atanh(s); - r.real = s.imag; - r.imag = -s.real; - return r; + /* atan(z) = -i atanh(iz) */ + Py_complex s, r; + s.real = -z.imag; + s.imag = z.real; + s = c_atanh(s); + r.real = s.imag; + r.imag = -s.real; + return r; } /* Windows screws up atan2 for inf and nan, and alpha Tru64 5.1 doesn't follow @@ -270,29 +270,29 @@ static double c_atan2(Py_complex z) { - if (Py_IS_NAN(z.real) || Py_IS_NAN(z.imag)) - return Py_NAN; - if (Py_IS_INFINITY(z.imag)) { - if (Py_IS_INFINITY(z.real)) { - if (copysign(1., z.real) == 1.) - /* atan2(+-inf, +inf) == +-pi/4 */ - return copysign(0.25*Py_MATH_PI, z.imag); - else - /* atan2(+-inf, -inf) == +-pi*3/4 */ - return copysign(0.75*Py_MATH_PI, z.imag); - } - /* atan2(+-inf, x) == +-pi/2 for finite x */ - return copysign(0.5*Py_MATH_PI, z.imag); - } - if (Py_IS_INFINITY(z.real) || z.imag == 0.) { - if (copysign(1., z.real) == 1.) - /* atan2(+-y, +inf) = atan2(+-0, +x) = +-0. */ - return copysign(0., z.imag); - else - /* atan2(+-y, -inf) = atan2(+-0., -x) = +-pi. */ - return copysign(Py_MATH_PI, z.imag); - } - return atan2(z.imag, z.real); + if (Py_IS_NAN(z.real) || Py_IS_NAN(z.imag)) + return Py_NAN; + if (Py_IS_INFINITY(z.imag)) { + if (Py_IS_INFINITY(z.real)) { + if (copysign(1., z.real) == 1.) + /* atan2(+-inf, +inf) == +-pi/4 */ + return copysign(0.25*Py_MATH_PI, z.imag); + else + /* atan2(+-inf, -inf) == +-pi*3/4 */ + return copysign(0.75*Py_MATH_PI, z.imag); + } + /* atan2(+-inf, x) == +-pi/2 for finite x */ + return copysign(0.5*Py_MATH_PI, z.imag); + } + if (Py_IS_INFINITY(z.real) || z.imag == 0.) { + if (copysign(1., z.real) == 1.) + /* atan2(+-y, +inf) = atan2(+-0, +x) = +-0. */ + return copysign(0., z.imag); + else + /* atan2(+-y, -inf) = atan2(+-0., -x) = +-pi. */ + return copysign(Py_MATH_PI, z.imag); + } + return atan2(z.imag, z.real); } PyDoc_STRVAR(c_atan_doc, @@ -306,48 +306,48 @@ static Py_complex c_atanh(Py_complex z) { - Py_complex r; - double ay, h; + Py_complex r; + double ay, h; - SPECIAL_VALUE(z, atanh_special_values); + SPECIAL_VALUE(z, atanh_special_values); - /* Reduce to case where z.real >= 0., using atanh(z) = -atanh(-z). */ - if (z.real < 0.) { - return c_neg(c_atanh(c_neg(z))); - } - - ay = fabs(z.imag); - if (z.real > CM_SQRT_LARGE_DOUBLE || ay > CM_SQRT_LARGE_DOUBLE) { - /* - if abs(z) is large then we use the approximation - atanh(z) ~ 1/z +/- i*pi/2 (+/- depending on the sign - of z.imag) - */ - h = hypot(z.real/2., z.imag/2.); /* safe from overflow */ - r.real = z.real/4./h/h; - /* the two negations in the next line cancel each other out - except when working with unsigned zeros: they're there to - ensure that the branch cut has the correct continuity on - systems that don't support signed zeros */ - r.imag = -copysign(Py_MATH_PI/2., -z.imag); - errno = 0; - } else if (z.real == 1. && ay < CM_SQRT_DBL_MIN) { - /* C99 standard says: atanh(1+/-0.) should be inf +/- 0i */ - if (ay == 0.) { - r.real = INF; - r.imag = z.imag; - errno = EDOM; - } else { - r.real = -log(sqrt(ay)/sqrt(hypot(ay, 2.))); - r.imag = copysign(atan2(2., -ay)/2, z.imag); - errno = 0; - } - } else { - r.real = m_log1p(4.*z.real/((1-z.real)*(1-z.real) + ay*ay))/4.; - r.imag = -atan2(-2.*z.imag, (1-z.real)*(1+z.real) - ay*ay)/2.; - errno = 0; - } - return r; + /* Reduce to case where z.real >= 0., using atanh(z) = -atanh(-z). */ + if (z.real < 0.) { + return c_neg(c_atanh(c_neg(z))); + } + + ay = fabs(z.imag); + if (z.real > CM_SQRT_LARGE_DOUBLE || ay > CM_SQRT_LARGE_DOUBLE) { + /* + if abs(z) is large then we use the approximation + atanh(z) ~ 1/z +/- i*pi/2 (+/- depending on the sign + of z.imag) + */ + h = hypot(z.real/2., z.imag/2.); /* safe from overflow */ + r.real = z.real/4./h/h; + /* the two negations in the next line cancel each other out + except when working with unsigned zeros: they're there to + ensure that the branch cut has the correct continuity on + systems that don't support signed zeros */ + r.imag = -copysign(Py_MATH_PI/2., -z.imag); + errno = 0; + } else if (z.real == 1. && ay < CM_SQRT_DBL_MIN) { + /* C99 standard says: atanh(1+/-0.) should be inf +/- 0i */ + if (ay == 0.) { + r.real = INF; + r.imag = z.imag; + errno = EDOM; + } else { + r.real = -log(sqrt(ay)/sqrt(hypot(ay, 2.))); + r.imag = copysign(atan2(2., -ay)/2, z.imag); + errno = 0; + } + } else { + r.real = m_log1p(4.*z.real/((1-z.real)*(1-z.real) + ay*ay))/4.; + r.imag = -atan2(-2.*z.imag, (1-z.real)*(1+z.real) - ay*ay)/2.; + errno = 0; + } + return r; } PyDoc_STRVAR(c_atanh_doc, @@ -359,12 +359,12 @@ static Py_complex c_cos(Py_complex z) { - /* cos(z) = cosh(iz) */ - Py_complex r; - r.real = -z.imag; - r.imag = z.real; - r = c_cosh(r); - return r; + /* cos(z) = cosh(iz) */ + Py_complex r; + r.real = -z.imag; + r.imag = z.real; + r = c_cosh(r); + return r; } PyDoc_STRVAR(c_cos_doc, @@ -379,51 +379,51 @@ static Py_complex c_cosh(Py_complex z) { - Py_complex r; - double x_minus_one; + Py_complex r; + double x_minus_one; - /* special treatment for cosh(+/-inf + iy) if y is not a NaN */ - if (!Py_IS_FINITE(z.real) || !Py_IS_FINITE(z.imag)) { - if (Py_IS_INFINITY(z.real) && Py_IS_FINITE(z.imag) && - (z.imag != 0.)) { - if (z.real > 0) { - r.real = copysign(INF, cos(z.imag)); - r.imag = copysign(INF, sin(z.imag)); - } - else { - r.real = copysign(INF, cos(z.imag)); - r.imag = -copysign(INF, sin(z.imag)); - } - } - else { - r = cosh_special_values[special_type(z.real)] - [special_type(z.imag)]; - } - /* need to set errno = EDOM if y is +/- infinity and x is not - a NaN */ - if (Py_IS_INFINITY(z.imag) && !Py_IS_NAN(z.real)) - errno = EDOM; - else - errno = 0; - return r; - } - - if (fabs(z.real) > CM_LOG_LARGE_DOUBLE) { - /* deal correctly with cases where cosh(z.real) overflows but - cosh(z) does not. */ - x_minus_one = z.real - copysign(1., z.real); - r.real = cos(z.imag) * cosh(x_minus_one) * Py_MATH_E; - r.imag = sin(z.imag) * sinh(x_minus_one) * Py_MATH_E; - } else { - r.real = cos(z.imag) * cosh(z.real); - r.imag = sin(z.imag) * sinh(z.real); - } - /* detect overflow, and set errno accordingly */ - if (Py_IS_INFINITY(r.real) || Py_IS_INFINITY(r.imag)) - errno = ERANGE; - else - errno = 0; - return r; + /* special treatment for cosh(+/-inf + iy) if y is not a NaN */ + if (!Py_IS_FINITE(z.real) || !Py_IS_FINITE(z.imag)) { + if (Py_IS_INFINITY(z.real) && Py_IS_FINITE(z.imag) && + (z.imag != 0.)) { + if (z.real > 0) { + r.real = copysign(INF, cos(z.imag)); + r.imag = copysign(INF, sin(z.imag)); + } + else { + r.real = copysign(INF, cos(z.imag)); + r.imag = -copysign(INF, sin(z.imag)); + } + } + else { + r = cosh_special_values[special_type(z.real)] + [special_type(z.imag)]; + } + /* need to set errno = EDOM if y is +/- infinity and x is not + a NaN */ + if (Py_IS_INFINITY(z.imag) && !Py_IS_NAN(z.real)) + errno = EDOM; + else + errno = 0; + return r; + } + + if (fabs(z.real) > CM_LOG_LARGE_DOUBLE) { + /* deal correctly with cases where cosh(z.real) overflows but + cosh(z) does not. */ + x_minus_one = z.real - copysign(1., z.real); + r.real = cos(z.imag) * cosh(x_minus_one) * Py_MATH_E; + r.imag = sin(z.imag) * sinh(x_minus_one) * Py_MATH_E; + } else { + r.real = cos(z.imag) * cosh(z.real); + r.imag = sin(z.imag) * sinh(z.real); + } + /* detect overflow, and set errno accordingly */ + if (Py_IS_INFINITY(r.real) || Py_IS_INFINITY(r.imag)) + errno = ERANGE; + else + errno = 0; + return r; } PyDoc_STRVAR(c_cosh_doc, @@ -439,51 +439,51 @@ static Py_complex c_exp(Py_complex z) { - Py_complex r; - double l; + Py_complex r; + double l; - if (!Py_IS_FINITE(z.real) || !Py_IS_FINITE(z.imag)) { - if (Py_IS_INFINITY(z.real) && Py_IS_FINITE(z.imag) - && (z.imag != 0.)) { - if (z.real > 0) { - r.real = copysign(INF, cos(z.imag)); - r.imag = copysign(INF, sin(z.imag)); - } - else { - r.real = copysign(0., cos(z.imag)); - r.imag = copysign(0., sin(z.imag)); - } - } - else { - r = exp_special_values[special_type(z.real)] - [special_type(z.imag)]; - } - /* need to set errno = EDOM if y is +/- infinity and x is not - a NaN and not -infinity */ - if (Py_IS_INFINITY(z.imag) && - (Py_IS_FINITE(z.real) || - (Py_IS_INFINITY(z.real) && z.real > 0))) - errno = EDOM; - else - errno = 0; - return r; - } - - if (z.real > CM_LOG_LARGE_DOUBLE) { - l = exp(z.real-1.); - r.real = l*cos(z.imag)*Py_MATH_E; - r.imag = l*sin(z.imag)*Py_MATH_E; - } else { - l = exp(z.real); - r.real = l*cos(z.imag); - r.imag = l*sin(z.imag); - } - /* detect overflow, and set errno accordingly */ - if (Py_IS_INFINITY(r.real) || Py_IS_INFINITY(r.imag)) - errno = ERANGE; - else - errno = 0; - return r; + if (!Py_IS_FINITE(z.real) || !Py_IS_FINITE(z.imag)) { + if (Py_IS_INFINITY(z.real) && Py_IS_FINITE(z.imag) + && (z.imag != 0.)) { + if (z.real > 0) { + r.real = copysign(INF, cos(z.imag)); + r.imag = copysign(INF, sin(z.imag)); + } + else { + r.real = copysign(0., cos(z.imag)); + r.imag = copysign(0., sin(z.imag)); + } + } + else { + r = exp_special_values[special_type(z.real)] + [special_type(z.imag)]; + } + /* need to set errno = EDOM if y is +/- infinity and x is not + a NaN and not -infinity */ + if (Py_IS_INFINITY(z.imag) && + (Py_IS_FINITE(z.real) || + (Py_IS_INFINITY(z.real) && z.real > 0))) + errno = EDOM; + else + errno = 0; + return r; + } + + if (z.real > CM_LOG_LARGE_DOUBLE) { + l = exp(z.real-1.); + r.real = l*cos(z.imag)*Py_MATH_E; + r.imag = l*sin(z.imag)*Py_MATH_E; + } else { + l = exp(z.real); + r.real = l*cos(z.imag); + r.imag = l*sin(z.imag); + } + /* detect overflow, and set errno accordingly */ + if (Py_IS_INFINITY(r.real) || Py_IS_INFINITY(r.imag)) + errno = ERANGE; + else + errno = 0; + return r; } PyDoc_STRVAR(c_exp_doc, @@ -497,85 +497,85 @@ static Py_complex c_log(Py_complex z) { - /* - The usual formula for the real part is log(hypot(z.real, z.imag)). - There are four situations where this formula is potentially - problematic: - - (1) the absolute value of z is subnormal. Then hypot is subnormal, - so has fewer than the usual number of bits of accuracy, hence may - have large relative error. This then gives a large absolute error - in the log. This can be solved by rescaling z by a suitable power - of 2. - - (2) the absolute value of z is greater than DBL_MAX (e.g. when both - z.real and z.imag are within a factor of 1/sqrt(2) of DBL_MAX) - Again, rescaling solves this. - - (3) the absolute value of z is close to 1. In this case it's - difficult to achieve good accuracy, at least in part because a - change of 1ulp in the real or imaginary part of z can result in a - change of billions of ulps in the correctly rounded answer. - - (4) z = 0. The simplest thing to do here is to call the - floating-point log with an argument of 0, and let its behaviour - (returning -infinity, signaling a floating-point exception, setting - errno, or whatever) determine that of c_log. So the usual formula - is fine here. - - */ - - Py_complex r; - double ax, ay, am, an, h; - - SPECIAL_VALUE(z, log_special_values); - - ax = fabs(z.real); - ay = fabs(z.imag); - - if (ax > CM_LARGE_DOUBLE || ay > CM_LARGE_DOUBLE) { - r.real = log(hypot(ax/2., ay/2.)) + M_LN2; - } else if (ax < DBL_MIN && ay < DBL_MIN) { - if (ax > 0. || ay > 0.) { - /* catch cases where hypot(ax, ay) is subnormal */ - r.real = log(hypot(ldexp(ax, DBL_MANT_DIG), - ldexp(ay, DBL_MANT_DIG))) - DBL_MANT_DIG*M_LN2; - } - else { - /* log(+/-0. +/- 0i) */ - r.real = -INF; - r.imag = atan2(z.imag, z.real); - errno = EDOM; - return r; - } - } else { - h = hypot(ax, ay); - if (0.71 <= h && h <= 1.73) { - am = ax > ay ? ax : ay; /* max(ax, ay) */ - an = ax > ay ? ay : ax; /* min(ax, ay) */ - r.real = m_log1p((am-1)*(am+1)+an*an)/2.; - } else { - r.real = log(h); - } - } - r.imag = atan2(z.imag, z.real); - errno = 0; - return r; + /* + The usual formula for the real part is log(hypot(z.real, z.imag)). + There are four situations where this formula is potentially + problematic: + + (1) the absolute value of z is subnormal. Then hypot is subnormal, + so has fewer than the usual number of bits of accuracy, hence may + have large relative error. This then gives a large absolute error + in the log. This can be solved by rescaling z by a suitable power + of 2. + + (2) the absolute value of z is greater than DBL_MAX (e.g. when both + z.real and z.imag are within a factor of 1/sqrt(2) of DBL_MAX) + Again, rescaling solves this. + + (3) the absolute value of z is close to 1. In this case it's + difficult to achieve good accuracy, at least in part because a + change of 1ulp in the real or imaginary part of z can result in a + change of billions of ulps in the correctly rounded answer. + + (4) z = 0. The simplest thing to do here is to call the + floating-point log with an argument of 0, and let its behaviour + (returning -infinity, signaling a floating-point exception, setting + errno, or whatever) determine that of c_log. So the usual formula + is fine here. + + */ + + Py_complex r; + double ax, ay, am, an, h; + + SPECIAL_VALUE(z, log_special_values); + + ax = fabs(z.real); + ay = fabs(z.imag); + + if (ax > CM_LARGE_DOUBLE || ay > CM_LARGE_DOUBLE) { + r.real = log(hypot(ax/2., ay/2.)) + M_LN2; + } else if (ax < DBL_MIN && ay < DBL_MIN) { + if (ax > 0. || ay > 0.) { + /* catch cases where hypot(ax, ay) is subnormal */ + r.real = log(hypot(ldexp(ax, DBL_MANT_DIG), + ldexp(ay, DBL_MANT_DIG))) - DBL_MANT_DIG*M_LN2; + } + else { + /* log(+/-0. +/- 0i) */ + r.real = -INF; + r.imag = atan2(z.imag, z.real); + errno = EDOM; + return r; + } + } else { + h = hypot(ax, ay); + if (0.71 <= h && h <= 1.73) { + am = ax > ay ? ax : ay; /* max(ax, ay) */ + an = ax > ay ? ay : ax; /* min(ax, ay) */ + r.real = m_log1p((am-1)*(am+1)+an*an)/2.; + } else { + r.real = log(h); + } + } + r.imag = atan2(z.imag, z.real); + errno = 0; + return r; } static Py_complex c_log10(Py_complex z) { - Py_complex r; - int errno_save; + Py_complex r; + int errno_save; - r = c_log(z); - errno_save = errno; /* just in case the divisions affect errno */ - r.real = r.real / M_LN10; - r.imag = r.imag / M_LN10; - errno = errno_save; - return r; + r = c_log(z); + errno_save = errno; /* just in case the divisions affect errno */ + r.real = r.real / M_LN10; + r.imag = r.imag / M_LN10; + errno = errno_save; + return r; } PyDoc_STRVAR(c_log10_doc, @@ -587,14 +587,14 @@ static Py_complex c_sin(Py_complex z) { - /* sin(z) = -i sin(iz) */ - Py_complex s, r; - s.real = -z.imag; - s.imag = z.real; - s = c_sinh(s); - r.real = s.imag; - r.imag = -s.real; - return r; + /* sin(z) = -i sin(iz) */ + Py_complex s, r; + s.real = -z.imag; + s.imag = z.real; + s = c_sinh(s); + r.real = s.imag; + r.imag = -s.real; + return r; } PyDoc_STRVAR(c_sin_doc, @@ -609,50 +609,50 @@ static Py_complex c_sinh(Py_complex z) { - Py_complex r; - double x_minus_one; + Py_complex r; + double x_minus_one; - /* special treatment for sinh(+/-inf + iy) if y is finite and - nonzero */ - if (!Py_IS_FINITE(z.real) || !Py_IS_FINITE(z.imag)) { - if (Py_IS_INFINITY(z.real) && Py_IS_FINITE(z.imag) - && (z.imag != 0.)) { - if (z.real > 0) { - r.real = copysign(INF, cos(z.imag)); - r.imag = copysign(INF, sin(z.imag)); - } - else { - r.real = -copysign(INF, cos(z.imag)); - r.imag = copysign(INF, sin(z.imag)); - } - } - else { - r = sinh_special_values[special_type(z.real)] - [special_type(z.imag)]; - } - /* need to set errno = EDOM if y is +/- infinity and x is not - a NaN */ - if (Py_IS_INFINITY(z.imag) && !Py_IS_NAN(z.real)) - errno = EDOM; - else - errno = 0; - return r; - } - - if (fabs(z.real) > CM_LOG_LARGE_DOUBLE) { - x_minus_one = z.real - copysign(1., z.real); - r.real = cos(z.imag) * sinh(x_minus_one) * Py_MATH_E; - r.imag = sin(z.imag) * cosh(x_minus_one) * Py_MATH_E; - } else { - r.real = cos(z.imag) * sinh(z.real); - r.imag = sin(z.imag) * cosh(z.real); - } - /* detect overflow, and set errno accordingly */ - if (Py_IS_INFINITY(r.real) || Py_IS_INFINITY(r.imag)) - errno = ERANGE; - else - errno = 0; - return r; + /* special treatment for sinh(+/-inf + iy) if y is finite and + nonzero */ + if (!Py_IS_FINITE(z.real) || !Py_IS_FINITE(z.imag)) { + if (Py_IS_INFINITY(z.real) && Py_IS_FINITE(z.imag) + && (z.imag != 0.)) { + if (z.real > 0) { + r.real = copysign(INF, cos(z.imag)); + r.imag = copysign(INF, sin(z.imag)); + } + else { + r.real = -copysign(INF, cos(z.imag)); + r.imag = copysign(INF, sin(z.imag)); + } + } + else { + r = sinh_special_values[special_type(z.real)] + [special_type(z.imag)]; + } + /* need to set errno = EDOM if y is +/- infinity and x is not + a NaN */ + if (Py_IS_INFINITY(z.imag) && !Py_IS_NAN(z.real)) + errno = EDOM; + else + errno = 0; + return r; + } + + if (fabs(z.real) > CM_LOG_LARGE_DOUBLE) { + x_minus_one = z.real - copysign(1., z.real); + r.real = cos(z.imag) * sinh(x_minus_one) * Py_MATH_E; + r.imag = sin(z.imag) * cosh(x_minus_one) * Py_MATH_E; + } else { + r.real = cos(z.imag) * sinh(z.real); + r.imag = sin(z.imag) * cosh(z.real); + } + /* detect overflow, and set errno accordingly */ + if (Py_IS_INFINITY(r.real) || Py_IS_INFINITY(r.imag)) + errno = ERANGE; + else + errno = 0; + return r; } PyDoc_STRVAR(c_sinh_doc, @@ -666,68 +666,68 @@ static Py_complex c_sqrt(Py_complex z) { - /* - Method: use symmetries to reduce to the case when x = z.real and y - = z.imag are nonnegative. Then the real part of the result is - given by - - s = sqrt((x + hypot(x, y))/2) - - and the imaginary part is - - d = (y/2)/s - - If either x or y is very large then there's a risk of overflow in - computation of the expression x + hypot(x, y). We can avoid this - by rewriting the formula for s as: - - s = 2*sqrt(x/8 + hypot(x/8, y/8)) - - This costs us two extra multiplications/divisions, but avoids the - overhead of checking for x and y large. - - If both x and y are subnormal then hypot(x, y) may also be - subnormal, so will lack full precision. We solve this by rescaling - x and y by a sufficiently large power of 2 to ensure that x and y - are normal. - */ - - - Py_complex r; - double s,d; - double ax, ay; - - SPECIAL_VALUE(z, sqrt_special_values); - - if (z.real == 0. && z.imag == 0.) { - r.real = 0.; - r.imag = z.imag; - return r; - } - - ax = fabs(z.real); - ay = fabs(z.imag); - - if (ax < DBL_MIN && ay < DBL_MIN && (ax > 0. || ay > 0.)) { - /* here we catch cases where hypot(ax, ay) is subnormal */ - ax = ldexp(ax, CM_SCALE_UP); - s = ldexp(sqrt(ax + hypot(ax, ldexp(ay, CM_SCALE_UP))), - CM_SCALE_DOWN); - } else { - ax /= 8.; - s = 2.*sqrt(ax + hypot(ax, ay/8.)); - } - d = ay/(2.*s); - - if (z.real >= 0.) { - r.real = s; - r.imag = copysign(d, z.imag); - } else { - r.real = d; - r.imag = copysign(s, z.imag); - } - errno = 0; - return r; + /* + Method: use symmetries to reduce to the case when x = z.real and y + = z.imag are nonnegative. Then the real part of the result is + given by + + s = sqrt((x + hypot(x, y))/2) + + and the imaginary part is + + d = (y/2)/s + + If either x or y is very large then there's a risk of overflow in + computation of the expression x + hypot(x, y). We can avoid this + by rewriting the formula for s as: + + s = 2*sqrt(x/8 + hypot(x/8, y/8)) + + This costs us two extra multiplications/divisions, but avoids the + overhead of checking for x and y large. + + If both x and y are subnormal then hypot(x, y) may also be + subnormal, so will lack full precision. We solve this by rescaling + x and y by a sufficiently large power of 2 to ensure that x and y + are normal. + */ + + + Py_complex r; + double s,d; + double ax, ay; + + SPECIAL_VALUE(z, sqrt_special_values); + + if (z.real == 0. && z.imag == 0.) { + r.real = 0.; + r.imag = z.imag; + return r; + } + + ax = fabs(z.real); + ay = fabs(z.imag); + + if (ax < DBL_MIN && ay < DBL_MIN && (ax > 0. || ay > 0.)) { + /* here we catch cases where hypot(ax, ay) is subnormal */ + ax = ldexp(ax, CM_SCALE_UP); + s = ldexp(sqrt(ax + hypot(ax, ldexp(ay, CM_SCALE_UP))), + CM_SCALE_DOWN); + } else { + ax /= 8.; + s = 2.*sqrt(ax + hypot(ax, ay/8.)); + } + d = ay/(2.*s); + + if (z.real >= 0.) { + r.real = s; + r.imag = copysign(d, z.imag); + } else { + r.real = d; + r.imag = copysign(s, z.imag); + } + errno = 0; + return r; } PyDoc_STRVAR(c_sqrt_doc, @@ -739,14 +739,14 @@ static Py_complex c_tan(Py_complex z) { - /* tan(z) = -i tanh(iz) */ - Py_complex s, r; - s.real = -z.imag; - s.imag = z.real; - s = c_tanh(s); - r.real = s.imag; - r.imag = -s.real; - return r; + /* tan(z) = -i tanh(iz) */ + Py_complex s, r; + s.real = -z.imag; + s.imag = z.real; + s = c_tanh(s); + r.real = s.imag; + r.imag = -s.real; + return r; } PyDoc_STRVAR(c_tan_doc, @@ -761,65 +761,65 @@ static Py_complex c_tanh(Py_complex z) { - /* Formula: + /* Formula: - tanh(x+iy) = (tanh(x)(1+tan(y)^2) + i tan(y)(1-tanh(x))^2) / - (1+tan(y)^2 tanh(x)^2) + tanh(x+iy) = (tanh(x)(1+tan(y)^2) + i tan(y)(1-tanh(x))^2) / + (1+tan(y)^2 tanh(x)^2) - To avoid excessive roundoff error, 1-tanh(x)^2 is better computed - as 1/cosh(x)^2. When abs(x) is large, we approximate 1-tanh(x)^2 - by 4 exp(-2*x) instead, to avoid possible overflow in the - computation of cosh(x). - - */ - - Py_complex r; - double tx, ty, cx, txty, denom; - - /* special treatment for tanh(+/-inf + iy) if y is finite and - nonzero */ - if (!Py_IS_FINITE(z.real) || !Py_IS_FINITE(z.imag)) { - if (Py_IS_INFINITY(z.real) && Py_IS_FINITE(z.imag) - && (z.imag != 0.)) { - if (z.real > 0) { - r.real = 1.0; - r.imag = copysign(0., - 2.*sin(z.imag)*cos(z.imag)); - } - else { - r.real = -1.0; - r.imag = copysign(0., - 2.*sin(z.imag)*cos(z.imag)); - } - } - else { - r = tanh_special_values[special_type(z.real)] - [special_type(z.imag)]; - } - /* need to set errno = EDOM if z.imag is +/-infinity and - z.real is finite */ - if (Py_IS_INFINITY(z.imag) && Py_IS_FINITE(z.real)) - errno = EDOM; - else - errno = 0; - return r; - } - - /* danger of overflow in 2.*z.imag !*/ - if (fabs(z.real) > CM_LOG_LARGE_DOUBLE) { - r.real = copysign(1., z.real); - r.imag = 4.*sin(z.imag)*cos(z.imag)*exp(-2.*fabs(z.real)); - } else { - tx = tanh(z.real); - ty = tan(z.imag); - cx = 1./cosh(z.real); - txty = tx*ty; - denom = 1. + txty*txty; - r.real = tx*(1.+ty*ty)/denom; - r.imag = ((ty/denom)*cx)*cx; - } - errno = 0; - return r; + To avoid excessive roundoff error, 1-tanh(x)^2 is better computed + as 1/cosh(x)^2. When abs(x) is large, we approximate 1-tanh(x)^2 + by 4 exp(-2*x) instead, to avoid possible overflow in the + computation of cosh(x). + + */ + + Py_complex r; + double tx, ty, cx, txty, denom; + + /* special treatment for tanh(+/-inf + iy) if y is finite and + nonzero */ + if (!Py_IS_FINITE(z.real) || !Py_IS_FINITE(z.imag)) { + if (Py_IS_INFINITY(z.real) && Py_IS_FINITE(z.imag) + && (z.imag != 0.)) { + if (z.real > 0) { + r.real = 1.0; + r.imag = copysign(0., + 2.*sin(z.imag)*cos(z.imag)); + } + else { + r.real = -1.0; + r.imag = copysign(0., + 2.*sin(z.imag)*cos(z.imag)); + } + } + else { + r = tanh_special_values[special_type(z.real)] + [special_type(z.imag)]; + } + /* need to set errno = EDOM if z.imag is +/-infinity and + z.real is finite */ + if (Py_IS_INFINITY(z.imag) && Py_IS_FINITE(z.real)) + errno = EDOM; + else + errno = 0; + return r; + } + + /* danger of overflow in 2.*z.imag !*/ + if (fabs(z.real) > CM_LOG_LARGE_DOUBLE) { + r.real = copysign(1., z.real); + r.imag = 4.*sin(z.imag)*cos(z.imag)*exp(-2.*fabs(z.real)); + } else { + tx = tanh(z.real); + ty = tan(z.imag); + cx = 1./cosh(z.real); + txty = tx*ty; + denom = 1. + txty*txty; + r.real = tx*(1.+ty*ty)/denom; + r.imag = ((ty/denom)*cx)*cx; + } + errno = 0; + return r; } PyDoc_STRVAR(c_tanh_doc, @@ -831,23 +831,23 @@ static PyObject * cmath_log(PyObject *self, PyObject *args) { - Py_complex x; - Py_complex y; + Py_complex x; + Py_complex y; - if (!PyArg_ParseTuple(args, "D|D", &x, &y)) - return NULL; + if (!PyArg_ParseTuple(args, "D|D", &x, &y)) + return NULL; - errno = 0; - PyFPE_START_PROTECT("complex function", return 0) - x = c_log(x); - if (PyTuple_GET_SIZE(args) == 2) { - y = c_log(y); - x = c_quot(x, y); - } - PyFPE_END_PROTECT(x) - if (errno != 0) - return math_error(); - return PyComplex_FromCComplex(x); + errno = 0; + PyFPE_START_PROTECT("complex function", return 0) + x = c_log(x); + if (PyTuple_GET_SIZE(args) == 2) { + y = c_log(y); + x = c_quot(x, y); + } + PyFPE_END_PROTECT(x) + if (errno != 0) + return math_error(); + return PyComplex_FromCComplex(x); } PyDoc_STRVAR(cmath_log_doc, @@ -860,42 +860,42 @@ static PyObject * math_error(void) { - if (errno == EDOM) - PyErr_SetString(PyExc_ValueError, "math domain error"); - else if (errno == ERANGE) - PyErr_SetString(PyExc_OverflowError, "math range error"); - else /* Unexpected math error */ - PyErr_SetFromErrno(PyExc_ValueError); - return NULL; + if (errno == EDOM) + PyErr_SetString(PyExc_ValueError, "math domain error"); + else if (errno == ERANGE) + PyErr_SetString(PyExc_OverflowError, "math range error"); + else /* Unexpected math error */ + PyErr_SetFromErrno(PyExc_ValueError); + return NULL; } static PyObject * math_1(PyObject *args, Py_complex (*func)(Py_complex)) { - Py_complex x,r ; - if (!PyArg_ParseTuple(args, "D", &x)) - return NULL; - errno = 0; - PyFPE_START_PROTECT("complex function", return 0); - r = (*func)(x); - PyFPE_END_PROTECT(r); - if (errno == EDOM) { - PyErr_SetString(PyExc_ValueError, "math domain error"); - return NULL; - } - else if (errno == ERANGE) { - PyErr_SetString(PyExc_OverflowError, "math range error"); - return NULL; - } - else { - return PyComplex_FromCComplex(r); - } + Py_complex x,r ; + if (!PyArg_ParseTuple(args, "D", &x)) + return NULL; + errno = 0; + PyFPE_START_PROTECT("complex function", return 0); + r = (*func)(x); + PyFPE_END_PROTECT(r); + if (errno == EDOM) { + PyErr_SetString(PyExc_ValueError, "math domain error"); + return NULL; + } + else if (errno == ERANGE) { + PyErr_SetString(PyExc_OverflowError, "math range error"); + return NULL; + } + else { + return PyComplex_FromCComplex(r); + } } #define FUNC1(stubname, func) \ - static PyObject * stubname(PyObject *self, PyObject *args) { \ - return math_1(args, func); \ - } + static PyObject * stubname(PyObject *self, PyObject *args) { \ + return math_1(args, func); \ + } FUNC1(cmath_acos, c_acos) FUNC1(cmath_acosh, c_acosh) @@ -916,18 +916,18 @@ static PyObject * cmath_phase(PyObject *self, PyObject *args) { - Py_complex z; - double phi; - if (!PyArg_ParseTuple(args, "D:phase", &z)) - return NULL; - errno = 0; - PyFPE_START_PROTECT("arg function", return 0) - phi = c_atan2(z); - PyFPE_END_PROTECT(phi) - if (errno != 0) - return math_error(); - else - return PyFloat_FromDouble(phi); + Py_complex z; + double phi; + if (!PyArg_ParseTuple(args, "D:phase", &z)) + return NULL; + errno = 0; + PyFPE_START_PROTECT("arg function", return 0) + phi = c_atan2(z); + PyFPE_END_PROTECT(phi) + if (errno != 0) + return math_error(); + else + return PyFloat_FromDouble(phi); } PyDoc_STRVAR(cmath_phase_doc, @@ -937,18 +937,18 @@ static PyObject * cmath_polar(PyObject *self, PyObject *args) { - Py_complex z; - double r, phi; - if (!PyArg_ParseTuple(args, "D:polar", &z)) - return NULL; - PyFPE_START_PROTECT("polar function", return 0) - phi = c_atan2(z); /* should not cause any exception */ - r = c_abs(z); /* sets errno to ERANGE on overflow; otherwise 0 */ - PyFPE_END_PROTECT(r) - if (errno != 0) - return math_error(); - else - return Py_BuildValue("dd", r, phi); + Py_complex z; + double r, phi; + if (!PyArg_ParseTuple(args, "D:polar", &z)) + return NULL; + PyFPE_START_PROTECT("polar function", return 0) + phi = c_atan2(z); /* should not cause any exception */ + r = c_abs(z); /* sets errno to ERANGE on overflow; otherwise 0 */ + PyFPE_END_PROTECT(r) + if (errno != 0) + return math_error(); + else + return Py_BuildValue("dd", r, phi); } PyDoc_STRVAR(cmath_polar_doc, @@ -972,51 +972,51 @@ static PyObject * cmath_rect(PyObject *self, PyObject *args) { - Py_complex z; - double r, phi; - if (!PyArg_ParseTuple(args, "dd:rect", &r, &phi)) - return NULL; - errno = 0; - PyFPE_START_PROTECT("rect function", return 0) - - /* deal with special values */ - if (!Py_IS_FINITE(r) || !Py_IS_FINITE(phi)) { - /* if r is +/-infinity and phi is finite but nonzero then - result is (+-INF +-INF i), but we need to compute cos(phi) - and sin(phi) to figure out the signs. */ - if (Py_IS_INFINITY(r) && (Py_IS_FINITE(phi) - && (phi != 0.))) { - if (r > 0) { - z.real = copysign(INF, cos(phi)); - z.imag = copysign(INF, sin(phi)); - } - else { - z.real = -copysign(INF, cos(phi)); - z.imag = -copysign(INF, sin(phi)); - } - } - else { - z = rect_special_values[special_type(r)] - [special_type(phi)]; - } - /* need to set errno = EDOM if r is a nonzero number and phi - is infinite */ - if (r != 0. && !Py_IS_NAN(r) && Py_IS_INFINITY(phi)) - errno = EDOM; - else - errno = 0; - } - else { - z.real = r * cos(phi); - z.imag = r * sin(phi); - errno = 0; - } - - PyFPE_END_PROTECT(z) - if (errno != 0) - return math_error(); - else - return PyComplex_FromCComplex(z); + Py_complex z; + double r, phi; + if (!PyArg_ParseTuple(args, "dd:rect", &r, &phi)) + return NULL; + errno = 0; + PyFPE_START_PROTECT("rect function", return 0) + + /* deal with special values */ + if (!Py_IS_FINITE(r) || !Py_IS_FINITE(phi)) { + /* if r is +/-infinity and phi is finite but nonzero then + result is (+-INF +-INF i), but we need to compute cos(phi) + and sin(phi) to figure out the signs. */ + if (Py_IS_INFINITY(r) && (Py_IS_FINITE(phi) + && (phi != 0.))) { + if (r > 0) { + z.real = copysign(INF, cos(phi)); + z.imag = copysign(INF, sin(phi)); + } + else { + z.real = -copysign(INF, cos(phi)); + z.imag = -copysign(INF, sin(phi)); + } + } + else { + z = rect_special_values[special_type(r)] + [special_type(phi)]; + } + /* need to set errno = EDOM if r is a nonzero number and phi + is infinite */ + if (r != 0. && !Py_IS_NAN(r) && Py_IS_INFINITY(phi)) + errno = EDOM; + else + errno = 0; + } + else { + z.real = r * cos(phi); + z.imag = r * sin(phi); + errno = 0; + } + + PyFPE_END_PROTECT(z) + if (errno != 0) + return math_error(); + else + return PyComplex_FromCComplex(z); } PyDoc_STRVAR(cmath_rect_doc, @@ -1026,10 +1026,10 @@ static PyObject * cmath_isnan(PyObject *self, PyObject *args) { - Py_complex z; - if (!PyArg_ParseTuple(args, "D:isnan", &z)) - return NULL; - return PyBool_FromLong(Py_IS_NAN(z.real) || Py_IS_NAN(z.imag)); + Py_complex z; + if (!PyArg_ParseTuple(args, "D:isnan", &z)) + return NULL; + return PyBool_FromLong(Py_IS_NAN(z.real) || Py_IS_NAN(z.imag)); } PyDoc_STRVAR(cmath_isnan_doc, @@ -1039,11 +1039,11 @@ static PyObject * cmath_isinf(PyObject *self, PyObject *args) { - Py_complex z; - if (!PyArg_ParseTuple(args, "D:isnan", &z)) - return NULL; - return PyBool_FromLong(Py_IS_INFINITY(z.real) || - Py_IS_INFINITY(z.imag)); + Py_complex z; + if (!PyArg_ParseTuple(args, "D:isnan", &z)) + return NULL; + return PyBool_FromLong(Py_IS_INFINITY(z.real) || + Py_IS_INFINITY(z.imag)); } PyDoc_STRVAR(cmath_isinf_doc, @@ -1056,169 +1056,169 @@ "functions for complex numbers."); static PyMethodDef cmath_methods[] = { - {"acos", cmath_acos, METH_VARARGS, c_acos_doc}, - {"acosh", cmath_acosh, METH_VARARGS, c_acosh_doc}, - {"asin", cmath_asin, METH_VARARGS, c_asin_doc}, - {"asinh", cmath_asinh, METH_VARARGS, c_asinh_doc}, - {"atan", cmath_atan, METH_VARARGS, c_atan_doc}, - {"atanh", cmath_atanh, METH_VARARGS, c_atanh_doc}, - {"cos", cmath_cos, METH_VARARGS, c_cos_doc}, - {"cosh", cmath_cosh, METH_VARARGS, c_cosh_doc}, - {"exp", cmath_exp, METH_VARARGS, c_exp_doc}, - {"isinf", cmath_isinf, METH_VARARGS, cmath_isinf_doc}, - {"isnan", cmath_isnan, METH_VARARGS, cmath_isnan_doc}, - {"log", cmath_log, METH_VARARGS, cmath_log_doc}, - {"log10", cmath_log10, METH_VARARGS, c_log10_doc}, - {"phase", cmath_phase, METH_VARARGS, cmath_phase_doc}, - {"polar", cmath_polar, METH_VARARGS, cmath_polar_doc}, - {"rect", cmath_rect, METH_VARARGS, cmath_rect_doc}, - {"sin", cmath_sin, METH_VARARGS, c_sin_doc}, - {"sinh", cmath_sinh, METH_VARARGS, c_sinh_doc}, - {"sqrt", cmath_sqrt, METH_VARARGS, c_sqrt_doc}, - {"tan", cmath_tan, METH_VARARGS, c_tan_doc}, - {"tanh", cmath_tanh, METH_VARARGS, c_tanh_doc}, - {NULL, NULL} /* sentinel */ + {"acos", cmath_acos, METH_VARARGS, c_acos_doc}, + {"acosh", cmath_acosh, METH_VARARGS, c_acosh_doc}, + {"asin", cmath_asin, METH_VARARGS, c_asin_doc}, + {"asinh", cmath_asinh, METH_VARARGS, c_asinh_doc}, + {"atan", cmath_atan, METH_VARARGS, c_atan_doc}, + {"atanh", cmath_atanh, METH_VARARGS, c_atanh_doc}, + {"cos", cmath_cos, METH_VARARGS, c_cos_doc}, + {"cosh", cmath_cosh, METH_VARARGS, c_cosh_doc}, + {"exp", cmath_exp, METH_VARARGS, c_exp_doc}, + {"isinf", cmath_isinf, METH_VARARGS, cmath_isinf_doc}, + {"isnan", cmath_isnan, METH_VARARGS, cmath_isnan_doc}, + {"log", cmath_log, METH_VARARGS, cmath_log_doc}, + {"log10", cmath_log10, METH_VARARGS, c_log10_doc}, + {"phase", cmath_phase, METH_VARARGS, cmath_phase_doc}, + {"polar", cmath_polar, METH_VARARGS, cmath_polar_doc}, + {"rect", cmath_rect, METH_VARARGS, cmath_rect_doc}, + {"sin", cmath_sin, METH_VARARGS, c_sin_doc}, + {"sinh", cmath_sinh, METH_VARARGS, c_sinh_doc}, + {"sqrt", cmath_sqrt, METH_VARARGS, c_sqrt_doc}, + {"tan", cmath_tan, METH_VARARGS, c_tan_doc}, + {"tanh", cmath_tanh, METH_VARARGS, c_tanh_doc}, + {NULL, NULL} /* sentinel */ }; static struct PyModuleDef cmathmodule = { - PyModuleDef_HEAD_INIT, - "cmath", - module_doc, - -1, - cmath_methods, - NULL, - NULL, - NULL, - NULL + PyModuleDef_HEAD_INIT, + "cmath", + module_doc, + -1, + cmath_methods, + NULL, + NULL, + NULL, + NULL }; PyMODINIT_FUNC PyInit_cmath(void) { - PyObject *m; + PyObject *m; - m = PyModule_Create(&cmathmodule); - if (m == NULL) - return NULL; + m = PyModule_Create(&cmathmodule); + if (m == NULL) + return NULL; - PyModule_AddObject(m, "pi", - PyFloat_FromDouble(Py_MATH_PI)); - PyModule_AddObject(m, "e", PyFloat_FromDouble(Py_MATH_E)); + PyModule_AddObject(m, "pi", + PyFloat_FromDouble(Py_MATH_PI)); + PyModule_AddObject(m, "e", PyFloat_FromDouble(Py_MATH_E)); - /* initialize special value tables */ + /* initialize special value tables */ #define INIT_SPECIAL_VALUES(NAME, BODY) { Py_complex* p = (Py_complex*)NAME; BODY } #define C(REAL, IMAG) p->real = REAL; p->imag = IMAG; ++p; - INIT_SPECIAL_VALUES(acos_special_values, { - C(P34,INF) C(P,INF) C(P,INF) C(P,-INF) C(P,-INF) C(P34,-INF) C(N,INF) - C(P12,INF) C(U,U) C(U,U) C(U,U) C(U,U) C(P12,-INF) C(N,N) - C(P12,INF) C(U,U) C(P12,0.) C(P12,-0.) C(U,U) C(P12,-INF) C(P12,N) - C(P12,INF) C(U,U) C(P12,0.) C(P12,-0.) C(U,U) C(P12,-INF) C(P12,N) - C(P12,INF) C(U,U) C(U,U) C(U,U) C(U,U) C(P12,-INF) C(N,N) - C(P14,INF) C(0.,INF) C(0.,INF) C(0.,-INF) C(0.,-INF) C(P14,-INF) C(N,INF) - C(N,INF) C(N,N) C(N,N) C(N,N) C(N,N) C(N,-INF) C(N,N) - }) - - INIT_SPECIAL_VALUES(acosh_special_values, { - C(INF,-P34) C(INF,-P) C(INF,-P) C(INF,P) C(INF,P) C(INF,P34) C(INF,N) - C(INF,-P12) C(U,U) C(U,U) C(U,U) C(U,U) C(INF,P12) C(N,N) - C(INF,-P12) C(U,U) C(0.,-P12) C(0.,P12) C(U,U) C(INF,P12) C(N,N) - C(INF,-P12) C(U,U) C(0.,-P12) C(0.,P12) C(U,U) C(INF,P12) C(N,N) - C(INF,-P12) C(U,U) C(U,U) C(U,U) C(U,U) C(INF,P12) C(N,N) - C(INF,-P14) C(INF,-0.) C(INF,-0.) C(INF,0.) C(INF,0.) C(INF,P14) C(INF,N) - C(INF,N) C(N,N) C(N,N) C(N,N) C(N,N) C(INF,N) C(N,N) - }) - - INIT_SPECIAL_VALUES(asinh_special_values, { - C(-INF,-P14) C(-INF,-0.) C(-INF,-0.) C(-INF,0.) C(-INF,0.) C(-INF,P14) C(-INF,N) - C(-INF,-P12) C(U,U) C(U,U) C(U,U) C(U,U) C(-INF,P12) C(N,N) - C(-INF,-P12) C(U,U) C(-0.,-0.) C(-0.,0.) C(U,U) C(-INF,P12) C(N,N) - C(INF,-P12) C(U,U) C(0.,-0.) C(0.,0.) C(U,U) C(INF,P12) C(N,N) - C(INF,-P12) C(U,U) C(U,U) C(U,U) C(U,U) C(INF,P12) C(N,N) - C(INF,-P14) C(INF,-0.) C(INF,-0.) C(INF,0.) C(INF,0.) C(INF,P14) C(INF,N) - C(INF,N) C(N,N) C(N,-0.) C(N,0.) C(N,N) C(INF,N) C(N,N) - }) - - INIT_SPECIAL_VALUES(atanh_special_values, { - C(-0.,-P12) C(-0.,-P12) C(-0.,-P12) C(-0.,P12) C(-0.,P12) C(-0.,P12) C(-0.,N) - C(-0.,-P12) C(U,U) C(U,U) C(U,U) C(U,U) C(-0.,P12) C(N,N) - C(-0.,-P12) C(U,U) C(-0.,-0.) C(-0.,0.) C(U,U) C(-0.,P12) C(-0.,N) - C(0.,-P12) C(U,U) C(0.,-0.) C(0.,0.) C(U,U) C(0.,P12) C(0.,N) - C(0.,-P12) C(U,U) C(U,U) C(U,U) C(U,U) C(0.,P12) C(N,N) - C(0.,-P12) C(0.,-P12) C(0.,-P12) C(0.,P12) C(0.,P12) C(0.,P12) C(0.,N) - C(0.,-P12) C(N,N) C(N,N) C(N,N) C(N,N) C(0.,P12) C(N,N) - }) - - INIT_SPECIAL_VALUES(cosh_special_values, { - C(INF,N) C(U,U) C(INF,0.) C(INF,-0.) C(U,U) C(INF,N) C(INF,N) - C(N,N) C(U,U) C(U,U) C(U,U) C(U,U) C(N,N) C(N,N) - C(N,0.) C(U,U) C(1.,0.) C(1.,-0.) C(U,U) C(N,0.) C(N,0.) - C(N,0.) C(U,U) C(1.,-0.) C(1.,0.) C(U,U) C(N,0.) C(N,0.) - C(N,N) C(U,U) C(U,U) C(U,U) C(U,U) C(N,N) C(N,N) - C(INF,N) C(U,U) C(INF,-0.) C(INF,0.) C(U,U) C(INF,N) C(INF,N) - C(N,N) C(N,N) C(N,0.) C(N,0.) C(N,N) C(N,N) C(N,N) - }) - - INIT_SPECIAL_VALUES(exp_special_values, { - C(0.,0.) C(U,U) C(0.,-0.) C(0.,0.) C(U,U) C(0.,0.) C(0.,0.) - C(N,N) C(U,U) C(U,U) C(U,U) C(U,U) C(N,N) C(N,N) - C(N,N) C(U,U) C(1.,-0.) C(1.,0.) C(U,U) C(N,N) C(N,N) - C(N,N) C(U,U) C(1.,-0.) C(1.,0.) C(U,U) C(N,N) C(N,N) - C(N,N) C(U,U) C(U,U) C(U,U) C(U,U) C(N,N) C(N,N) - C(INF,N) C(U,U) C(INF,-0.) C(INF,0.) C(U,U) C(INF,N) C(INF,N) - C(N,N) C(N,N) C(N,-0.) C(N,0.) C(N,N) C(N,N) C(N,N) - }) - - INIT_SPECIAL_VALUES(log_special_values, { - C(INF,-P34) C(INF,-P) C(INF,-P) C(INF,P) C(INF,P) C(INF,P34) C(INF,N) - C(INF,-P12) C(U,U) C(U,U) C(U,U) C(U,U) C(INF,P12) C(N,N) - C(INF,-P12) C(U,U) C(-INF,-P) C(-INF,P) C(U,U) C(INF,P12) C(N,N) - C(INF,-P12) C(U,U) C(-INF,-0.) C(-INF,0.) C(U,U) C(INF,P12) C(N,N) - C(INF,-P12) C(U,U) C(U,U) C(U,U) C(U,U) C(INF,P12) C(N,N) - C(INF,-P14) C(INF,-0.) C(INF,-0.) C(INF,0.) C(INF,0.) C(INF,P14) C(INF,N) - C(INF,N) C(N,N) C(N,N) C(N,N) C(N,N) C(INF,N) C(N,N) - }) - - INIT_SPECIAL_VALUES(sinh_special_values, { - C(INF,N) C(U,U) C(-INF,-0.) C(-INF,0.) C(U,U) C(INF,N) C(INF,N) - C(N,N) C(U,U) C(U,U) C(U,U) C(U,U) C(N,N) C(N,N) - C(0.,N) C(U,U) C(-0.,-0.) C(-0.,0.) C(U,U) C(0.,N) C(0.,N) - C(0.,N) C(U,U) C(0.,-0.) C(0.,0.) C(U,U) C(0.,N) C(0.,N) - C(N,N) C(U,U) C(U,U) C(U,U) C(U,U) C(N,N) C(N,N) - C(INF,N) C(U,U) C(INF,-0.) C(INF,0.) C(U,U) C(INF,N) C(INF,N) - C(N,N) C(N,N) C(N,-0.) C(N,0.) C(N,N) C(N,N) C(N,N) - }) - - INIT_SPECIAL_VALUES(sqrt_special_values, { - C(INF,-INF) C(0.,-INF) C(0.,-INF) C(0.,INF) C(0.,INF) C(INF,INF) C(N,INF) - C(INF,-INF) C(U,U) C(U,U) C(U,U) C(U,U) C(INF,INF) C(N,N) - C(INF,-INF) C(U,U) C(0.,-0.) C(0.,0.) C(U,U) C(INF,INF) C(N,N) - C(INF,-INF) C(U,U) C(0.,-0.) C(0.,0.) C(U,U) C(INF,INF) C(N,N) - C(INF,-INF) C(U,U) C(U,U) C(U,U) C(U,U) C(INF,INF) C(N,N) - C(INF,-INF) C(INF,-0.) C(INF,-0.) C(INF,0.) C(INF,0.) C(INF,INF) C(INF,N) - C(INF,-INF) C(N,N) C(N,N) C(N,N) C(N,N) C(INF,INF) C(N,N) - }) - - INIT_SPECIAL_VALUES(tanh_special_values, { - C(-1.,0.) C(U,U) C(-1.,-0.) C(-1.,0.) C(U,U) C(-1.,0.) C(-1.,0.) - C(N,N) C(U,U) C(U,U) C(U,U) C(U,U) C(N,N) C(N,N) - C(N,N) C(U,U) C(-0.,-0.) C(-0.,0.) C(U,U) C(N,N) C(N,N) - C(N,N) C(U,U) C(0.,-0.) C(0.,0.) C(U,U) C(N,N) C(N,N) - C(N,N) C(U,U) C(U,U) C(U,U) C(U,U) C(N,N) C(N,N) - C(1.,0.) C(U,U) C(1.,-0.) C(1.,0.) C(U,U) C(1.,0.) C(1.,0.) - C(N,N) C(N,N) C(N,-0.) C(N,0.) C(N,N) C(N,N) C(N,N) - }) - - INIT_SPECIAL_VALUES(rect_special_values, { - C(INF,N) C(U,U) C(-INF,0.) C(-INF,-0.) C(U,U) C(INF,N) C(INF,N) - C(N,N) C(U,U) C(U,U) C(U,U) C(U,U) C(N,N) C(N,N) - C(0.,0.) C(U,U) C(-0.,0.) C(-0.,-0.) C(U,U) C(0.,0.) C(0.,0.) - C(0.,0.) C(U,U) C(0.,-0.) C(0.,0.) C(U,U) C(0.,0.) C(0.,0.) - C(N,N) C(U,U) C(U,U) C(U,U) C(U,U) C(N,N) C(N,N) - C(INF,N) C(U,U) C(INF,-0.) C(INF,0.) C(U,U) C(INF,N) C(INF,N) - C(N,N) C(N,N) C(N,0.) C(N,0.) C(N,N) C(N,N) C(N,N) - }) - return m; + INIT_SPECIAL_VALUES(acos_special_values, { + C(P34,INF) C(P,INF) C(P,INF) C(P,-INF) C(P,-INF) C(P34,-INF) C(N,INF) + C(P12,INF) C(U,U) C(U,U) C(U,U) C(U,U) C(P12,-INF) C(N,N) + C(P12,INF) C(U,U) C(P12,0.) C(P12,-0.) C(U,U) C(P12,-INF) C(P12,N) + C(P12,INF) C(U,U) C(P12,0.) C(P12,-0.) C(U,U) C(P12,-INF) C(P12,N) + C(P12,INF) C(U,U) C(U,U) C(U,U) C(U,U) C(P12,-INF) C(N,N) + C(P14,INF) C(0.,INF) C(0.,INF) C(0.,-INF) C(0.,-INF) C(P14,-INF) C(N,INF) + C(N,INF) C(N,N) C(N,N) C(N,N) C(N,N) C(N,-INF) C(N,N) + }) + + INIT_SPECIAL_VALUES(acosh_special_values, { + C(INF,-P34) C(INF,-P) C(INF,-P) C(INF,P) C(INF,P) C(INF,P34) C(INF,N) + C(INF,-P12) C(U,U) C(U,U) C(U,U) C(U,U) C(INF,P12) C(N,N) + C(INF,-P12) C(U,U) C(0.,-P12) C(0.,P12) C(U,U) C(INF,P12) C(N,N) + C(INF,-P12) C(U,U) C(0.,-P12) C(0.,P12) C(U,U) C(INF,P12) C(N,N) + C(INF,-P12) C(U,U) C(U,U) C(U,U) C(U,U) C(INF,P12) C(N,N) + C(INF,-P14) C(INF,-0.) C(INF,-0.) C(INF,0.) C(INF,0.) C(INF,P14) C(INF,N) + C(INF,N) C(N,N) C(N,N) C(N,N) C(N,N) C(INF,N) C(N,N) + }) + + INIT_SPECIAL_VALUES(asinh_special_values, { + C(-INF,-P14) C(-INF,-0.) C(-INF,-0.) C(-INF,0.) C(-INF,0.) C(-INF,P14) C(-INF,N) + C(-INF,-P12) C(U,U) C(U,U) C(U,U) C(U,U) C(-INF,P12) C(N,N) + C(-INF,-P12) C(U,U) C(-0.,-0.) C(-0.,0.) C(U,U) C(-INF,P12) C(N,N) + C(INF,-P12) C(U,U) C(0.,-0.) C(0.,0.) C(U,U) C(INF,P12) C(N,N) + C(INF,-P12) C(U,U) C(U,U) C(U,U) C(U,U) C(INF,P12) C(N,N) + C(INF,-P14) C(INF,-0.) C(INF,-0.) C(INF,0.) C(INF,0.) C(INF,P14) C(INF,N) + C(INF,N) C(N,N) C(N,-0.) C(N,0.) C(N,N) C(INF,N) C(N,N) + }) + + INIT_SPECIAL_VALUES(atanh_special_values, { + C(-0.,-P12) C(-0.,-P12) C(-0.,-P12) C(-0.,P12) C(-0.,P12) C(-0.,P12) C(-0.,N) + C(-0.,-P12) C(U,U) C(U,U) C(U,U) C(U,U) C(-0.,P12) C(N,N) + C(-0.,-P12) C(U,U) C(-0.,-0.) C(-0.,0.) C(U,U) C(-0.,P12) C(-0.,N) + C(0.,-P12) C(U,U) C(0.,-0.) C(0.,0.) C(U,U) C(0.,P12) C(0.,N) + C(0.,-P12) C(U,U) C(U,U) C(U,U) C(U,U) C(0.,P12) C(N,N) + C(0.,-P12) C(0.,-P12) C(0.,-P12) C(0.,P12) C(0.,P12) C(0.,P12) C(0.,N) + C(0.,-P12) C(N,N) C(N,N) C(N,N) C(N,N) C(0.,P12) C(N,N) + }) + + INIT_SPECIAL_VALUES(cosh_special_values, { + C(INF,N) C(U,U) C(INF,0.) C(INF,-0.) C(U,U) C(INF,N) C(INF,N) + C(N,N) C(U,U) C(U,U) C(U,U) C(U,U) C(N,N) C(N,N) + C(N,0.) C(U,U) C(1.,0.) C(1.,-0.) C(U,U) C(N,0.) C(N,0.) + C(N,0.) C(U,U) C(1.,-0.) C(1.,0.) C(U,U) C(N,0.) C(N,0.) + C(N,N) C(U,U) C(U,U) C(U,U) C(U,U) C(N,N) C(N,N) + C(INF,N) C(U,U) C(INF,-0.) C(INF,0.) C(U,U) C(INF,N) C(INF,N) + C(N,N) C(N,N) C(N,0.) C(N,0.) C(N,N) C(N,N) C(N,N) + }) + + INIT_SPECIAL_VALUES(exp_special_values, { + C(0.,0.) C(U,U) C(0.,-0.) C(0.,0.) C(U,U) C(0.,0.) C(0.,0.) + C(N,N) C(U,U) C(U,U) C(U,U) C(U,U) C(N,N) C(N,N) + C(N,N) C(U,U) C(1.,-0.) C(1.,0.) C(U,U) C(N,N) C(N,N) + C(N,N) C(U,U) C(1.,-0.) C(1.,0.) C(U,U) C(N,N) C(N,N) + C(N,N) C(U,U) C(U,U) C(U,U) C(U,U) C(N,N) C(N,N) + C(INF,N) C(U,U) C(INF,-0.) C(INF,0.) C(U,U) C(INF,N) C(INF,N) + C(N,N) C(N,N) C(N,-0.) C(N,0.) C(N,N) C(N,N) C(N,N) + }) + + INIT_SPECIAL_VALUES(log_special_values, { + C(INF,-P34) C(INF,-P) C(INF,-P) C(INF,P) C(INF,P) C(INF,P34) C(INF,N) + C(INF,-P12) C(U,U) C(U,U) C(U,U) C(U,U) C(INF,P12) C(N,N) + C(INF,-P12) C(U,U) C(-INF,-P) C(-INF,P) C(U,U) C(INF,P12) C(N,N) + C(INF,-P12) C(U,U) C(-INF,-0.) C(-INF,0.) C(U,U) C(INF,P12) C(N,N) + C(INF,-P12) C(U,U) C(U,U) C(U,U) C(U,U) C(INF,P12) C(N,N) + C(INF,-P14) C(INF,-0.) C(INF,-0.) C(INF,0.) C(INF,0.) C(INF,P14) C(INF,N) + C(INF,N) C(N,N) C(N,N) C(N,N) C(N,N) C(INF,N) C(N,N) + }) + + INIT_SPECIAL_VALUES(sinh_special_values, { + C(INF,N) C(U,U) C(-INF,-0.) C(-INF,0.) C(U,U) C(INF,N) C(INF,N) + C(N,N) C(U,U) C(U,U) C(U,U) C(U,U) C(N,N) C(N,N) + C(0.,N) C(U,U) C(-0.,-0.) C(-0.,0.) C(U,U) C(0.,N) C(0.,N) + C(0.,N) C(U,U) C(0.,-0.) C(0.,0.) C(U,U) C(0.,N) C(0.,N) + C(N,N) C(U,U) C(U,U) C(U,U) C(U,U) C(N,N) C(N,N) + C(INF,N) C(U,U) C(INF,-0.) C(INF,0.) C(U,U) C(INF,N) C(INF,N) + C(N,N) C(N,N) C(N,-0.) C(N,0.) C(N,N) C(N,N) C(N,N) + }) + + INIT_SPECIAL_VALUES(sqrt_special_values, { + C(INF,-INF) C(0.,-INF) C(0.,-INF) C(0.,INF) C(0.,INF) C(INF,INF) C(N,INF) + C(INF,-INF) C(U,U) C(U,U) C(U,U) C(U,U) C(INF,INF) C(N,N) + C(INF,-INF) C(U,U) C(0.,-0.) C(0.,0.) C(U,U) C(INF,INF) C(N,N) + C(INF,-INF) C(U,U) C(0.,-0.) C(0.,0.) C(U,U) C(INF,INF) C(N,N) + C(INF,-INF) C(U,U) C(U,U) C(U,U) C(U,U) C(INF,INF) C(N,N) + C(INF,-INF) C(INF,-0.) C(INF,-0.) C(INF,0.) C(INF,0.) C(INF,INF) C(INF,N) + C(INF,-INF) C(N,N) C(N,N) C(N,N) C(N,N) C(INF,INF) C(N,N) + }) + + INIT_SPECIAL_VALUES(tanh_special_values, { + C(-1.,0.) C(U,U) C(-1.,-0.) C(-1.,0.) C(U,U) C(-1.,0.) C(-1.,0.) + C(N,N) C(U,U) C(U,U) C(U,U) C(U,U) C(N,N) C(N,N) + C(N,N) C(U,U) C(-0.,-0.) C(-0.,0.) C(U,U) C(N,N) C(N,N) + C(N,N) C(U,U) C(0.,-0.) C(0.,0.) C(U,U) C(N,N) C(N,N) + C(N,N) C(U,U) C(U,U) C(U,U) C(U,U) C(N,N) C(N,N) + C(1.,0.) C(U,U) C(1.,-0.) C(1.,0.) C(U,U) C(1.,0.) C(1.,0.) + C(N,N) C(N,N) C(N,-0.) C(N,0.) C(N,N) C(N,N) C(N,N) + }) + + INIT_SPECIAL_VALUES(rect_special_values, { + C(INF,N) C(U,U) C(-INF,0.) C(-INF,-0.) C(U,U) C(INF,N) C(INF,N) + C(N,N) C(U,U) C(U,U) C(U,U) C(U,U) C(N,N) C(N,N) + C(0.,0.) C(U,U) C(-0.,0.) C(-0.,-0.) C(U,U) C(0.,0.) C(0.,0.) + C(0.,0.) C(U,U) C(0.,-0.) C(0.,0.) C(U,U) C(0.,0.) C(0.,0.) + C(N,N) C(U,U) C(U,U) C(U,U) C(U,U) C(N,N) C(N,N) + C(INF,N) C(U,U) C(INF,-0.) C(INF,0.) C(U,U) C(INF,N) C(INF,N) + C(N,N) C(N,N) C(N,0.) C(N,0.) C(N,N) C(N,N) C(N,N) + }) + return m; } Modified: python/branches/py3k/Modules/cryptmodule.c ============================================================================== --- python/branches/py3k/Modules/cryptmodule.c (original) +++ python/branches/py3k/Modules/cryptmodule.c Sun May 9 17:52:27 2010 @@ -14,17 +14,17 @@ static PyObject *crypt_crypt(PyObject *self, PyObject *args) { - char *word, *salt; + char *word, *salt; #ifndef __VMS - extern char * crypt(const char *, const char *); + extern char * crypt(const char *, const char *); #endif - if (!PyArg_ParseTuple(args, "ss:crypt", &word, &salt)) { - return NULL; - } - /* On some platforms (AtheOS) crypt returns NULL for an invalid - salt. Return None in that case. XXX Maybe raise an exception? */ - return Py_BuildValue("s", crypt(word, salt)); + if (!PyArg_ParseTuple(args, "ss:crypt", &word, &salt)) { + return NULL; + } + /* On some platforms (AtheOS) crypt returns NULL for an invalid + salt. Return None in that case. XXX Maybe raise an exception? */ + return Py_BuildValue("s", crypt(word, salt)); } @@ -38,25 +38,25 @@ static PyMethodDef crypt_methods[] = { - {"crypt", crypt_crypt, METH_VARARGS, crypt_crypt__doc__}, - {NULL, NULL} /* sentinel */ + {"crypt", crypt_crypt, METH_VARARGS, crypt_crypt__doc__}, + {NULL, NULL} /* sentinel */ }; static struct PyModuleDef cryptmodule = { - PyModuleDef_HEAD_INIT, - "crypt", - NULL, - -1, - crypt_methods, - NULL, - NULL, - NULL, - NULL + PyModuleDef_HEAD_INIT, + "crypt", + NULL, + -1, + crypt_methods, + NULL, + NULL, + NULL, + NULL }; PyMODINIT_FUNC PyInit_crypt(void) { - return PyModule_Create(&cryptmodule); + return PyModule_Create(&cryptmodule); } Modified: python/branches/py3k/Modules/datetimemodule.c ============================================================================== --- python/branches/py3k/Modules/datetimemodule.c (original) +++ python/branches/py3k/Modules/datetimemodule.c Sun May 9 17:52:27 2010 @@ -25,7 +25,7 @@ * final result fits in a C int (this can be an issue on 64-bit boxes). */ #if SIZEOF_INT < 4 -# error "datetime.c requires that C int have at least 32 bits" +# error "datetime.c requires that C int have at least 32 bits" #endif #define MINYEAR 1 @@ -39,59 +39,59 @@ #define MAX_DELTA_DAYS 999999999 /* Rename the long macros in datetime.h to more reasonable short names. */ -#define GET_YEAR PyDateTime_GET_YEAR -#define GET_MONTH PyDateTime_GET_MONTH -#define GET_DAY PyDateTime_GET_DAY -#define DATE_GET_HOUR PyDateTime_DATE_GET_HOUR -#define DATE_GET_MINUTE PyDateTime_DATE_GET_MINUTE -#define DATE_GET_SECOND PyDateTime_DATE_GET_SECOND -#define DATE_GET_MICROSECOND PyDateTime_DATE_GET_MICROSECOND +#define GET_YEAR PyDateTime_GET_YEAR +#define GET_MONTH PyDateTime_GET_MONTH +#define GET_DAY PyDateTime_GET_DAY +#define DATE_GET_HOUR PyDateTime_DATE_GET_HOUR +#define DATE_GET_MINUTE PyDateTime_DATE_GET_MINUTE +#define DATE_GET_SECOND PyDateTime_DATE_GET_SECOND +#define DATE_GET_MICROSECOND PyDateTime_DATE_GET_MICROSECOND /* Date accessors for date and datetime. */ -#define SET_YEAR(o, v) (((o)->data[0] = ((v) & 0xff00) >> 8), \ - ((o)->data[1] = ((v) & 0x00ff))) -#define SET_MONTH(o, v) (PyDateTime_GET_MONTH(o) = (v)) -#define SET_DAY(o, v) (PyDateTime_GET_DAY(o) = (v)) +#define SET_YEAR(o, v) (((o)->data[0] = ((v) & 0xff00) >> 8), \ + ((o)->data[1] = ((v) & 0x00ff))) +#define SET_MONTH(o, v) (PyDateTime_GET_MONTH(o) = (v)) +#define SET_DAY(o, v) (PyDateTime_GET_DAY(o) = (v)) /* Date/Time accessors for datetime. */ -#define DATE_SET_HOUR(o, v) (PyDateTime_DATE_GET_HOUR(o) = (v)) -#define DATE_SET_MINUTE(o, v) (PyDateTime_DATE_GET_MINUTE(o) = (v)) -#define DATE_SET_SECOND(o, v) (PyDateTime_DATE_GET_SECOND(o) = (v)) -#define DATE_SET_MICROSECOND(o, v) \ - (((o)->data[7] = ((v) & 0xff0000) >> 16), \ - ((o)->data[8] = ((v) & 0x00ff00) >> 8), \ - ((o)->data[9] = ((v) & 0x0000ff))) +#define DATE_SET_HOUR(o, v) (PyDateTime_DATE_GET_HOUR(o) = (v)) +#define DATE_SET_MINUTE(o, v) (PyDateTime_DATE_GET_MINUTE(o) = (v)) +#define DATE_SET_SECOND(o, v) (PyDateTime_DATE_GET_SECOND(o) = (v)) +#define DATE_SET_MICROSECOND(o, v) \ + (((o)->data[7] = ((v) & 0xff0000) >> 16), \ + ((o)->data[8] = ((v) & 0x00ff00) >> 8), \ + ((o)->data[9] = ((v) & 0x0000ff))) /* Time accessors for time. */ -#define TIME_GET_HOUR PyDateTime_TIME_GET_HOUR -#define TIME_GET_MINUTE PyDateTime_TIME_GET_MINUTE -#define TIME_GET_SECOND PyDateTime_TIME_GET_SECOND -#define TIME_GET_MICROSECOND PyDateTime_TIME_GET_MICROSECOND -#define TIME_SET_HOUR(o, v) (PyDateTime_TIME_GET_HOUR(o) = (v)) -#define TIME_SET_MINUTE(o, v) (PyDateTime_TIME_GET_MINUTE(o) = (v)) -#define TIME_SET_SECOND(o, v) (PyDateTime_TIME_GET_SECOND(o) = (v)) -#define TIME_SET_MICROSECOND(o, v) \ - (((o)->data[3] = ((v) & 0xff0000) >> 16), \ - ((o)->data[4] = ((v) & 0x00ff00) >> 8), \ - ((o)->data[5] = ((v) & 0x0000ff))) +#define TIME_GET_HOUR PyDateTime_TIME_GET_HOUR +#define TIME_GET_MINUTE PyDateTime_TIME_GET_MINUTE +#define TIME_GET_SECOND PyDateTime_TIME_GET_SECOND +#define TIME_GET_MICROSECOND PyDateTime_TIME_GET_MICROSECOND +#define TIME_SET_HOUR(o, v) (PyDateTime_TIME_GET_HOUR(o) = (v)) +#define TIME_SET_MINUTE(o, v) (PyDateTime_TIME_GET_MINUTE(o) = (v)) +#define TIME_SET_SECOND(o, v) (PyDateTime_TIME_GET_SECOND(o) = (v)) +#define TIME_SET_MICROSECOND(o, v) \ + (((o)->data[3] = ((v) & 0xff0000) >> 16), \ + ((o)->data[4] = ((v) & 0x00ff00) >> 8), \ + ((o)->data[5] = ((v) & 0x0000ff))) /* Delta accessors for timedelta. */ -#define GET_TD_DAYS(o) (((PyDateTime_Delta *)(o))->days) -#define GET_TD_SECONDS(o) (((PyDateTime_Delta *)(o))->seconds) -#define GET_TD_MICROSECONDS(o) (((PyDateTime_Delta *)(o))->microseconds) +#define GET_TD_DAYS(o) (((PyDateTime_Delta *)(o))->days) +#define GET_TD_SECONDS(o) (((PyDateTime_Delta *)(o))->seconds) +#define GET_TD_MICROSECONDS(o) (((PyDateTime_Delta *)(o))->microseconds) -#define SET_TD_DAYS(o, v) ((o)->days = (v)) -#define SET_TD_SECONDS(o, v) ((o)->seconds = (v)) +#define SET_TD_DAYS(o, v) ((o)->days = (v)) +#define SET_TD_SECONDS(o, v) ((o)->seconds = (v)) #define SET_TD_MICROSECONDS(o, v) ((o)->microseconds = (v)) /* p is a pointer to a time or a datetime object; HASTZINFO(p) returns * p->hastzinfo. */ -#define HASTZINFO(p) (((_PyDateTime_BaseTZInfo *)(p))->hastzinfo) +#define HASTZINFO(p) (((_PyDateTime_BaseTZInfo *)(p))->hastzinfo) /* M is a char or int claiming to be a valid month. The macro is equivalent * to the two-sided Python test - * 1 <= M <= 12 + * 1 <= M <= 12 */ #define MONTH_IS_SANE(M) ((unsigned int)(M) - 1 < 12) @@ -111,7 +111,7 @@ * iff (k^i)&(k^j) has sign bit set. */ #define SIGNED_ADD_OVERFLOWED(RESULT, I, J) \ - ((((RESULT) ^ (I)) & ((RESULT) ^ (J))) < 0) + ((((RESULT) ^ (I)) & ((RESULT) ^ (J))) < 0) /* Compute Python divmod(x, y), returning the quotient and storing the * remainder into *r. The quotient is the floor of x/y, and that's @@ -125,17 +125,17 @@ static int divmod(int x, int y, int *r) { - int quo; + int quo; - assert(y > 0); - quo = x / y; - *r = x - quo * y; - if (*r < 0) { - --quo; - *r += y; - } - assert(0 <= *r && *r < y); - return quo; + assert(y > 0); + quo = x / y; + *r = x - quo * y; + if (*r < 0) { + --quo; + *r += y; + } + assert(0 <= *r && *r < y); + return quo; } /* Round a double to the nearest long. |x| must be small enough to fit @@ -144,11 +144,11 @@ static long round_to_long(double x) { - if (x >= 0.0) - x = floor(x + 0.5); - else - x = ceil(x - 0.5); - return (long)x; + if (x >= 0.0) + x = floor(x + 0.5); + else + x = ceil(x - 0.5); + return (long)x; } /* --------------------------------------------------------------------------- @@ -160,52 +160,52 @@ * are correct for non-leap years only. */ static int _days_in_month[] = { - 0, /* unused; this vector uses 1-based indexing */ - 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 + 0, /* unused; this vector uses 1-based indexing */ + 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 }; static int _days_before_month[] = { - 0, /* unused; this vector uses 1-based indexing */ - 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334 + 0, /* unused; this vector uses 1-based indexing */ + 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334 }; /* year -> 1 if leap year, else 0. */ static int is_leap(int year) { - /* Cast year to unsigned. The result is the same either way, but - * C can generate faster code for unsigned mod than for signed - * mod (especially for % 4 -- a good compiler should just grab - * the last 2 bits when the LHS is unsigned). - */ - const unsigned int ayear = (unsigned int)year; - return ayear % 4 == 0 && (ayear % 100 != 0 || ayear % 400 == 0); + /* Cast year to unsigned. The result is the same either way, but + * C can generate faster code for unsigned mod than for signed + * mod (especially for % 4 -- a good compiler should just grab + * the last 2 bits when the LHS is unsigned). + */ + const unsigned int ayear = (unsigned int)year; + return ayear % 4 == 0 && (ayear % 100 != 0 || ayear % 400 == 0); } /* year, month -> number of days in that month in that year */ static int days_in_month(int year, int month) { - assert(month >= 1); - assert(month <= 12); - if (month == 2 && is_leap(year)) - return 29; - else - return _days_in_month[month]; + assert(month >= 1); + assert(month <= 12); + if (month == 2 && is_leap(year)) + return 29; + else + return _days_in_month[month]; } /* year, month -> number of days in year preceeding first day of month */ static int days_before_month(int year, int month) { - int days; + int days; - assert(month >= 1); - assert(month <= 12); - days = _days_before_month[month]; - if (month > 2 && is_leap(year)) - ++days; - return days; + assert(month >= 1); + assert(month <= 12); + days = _days_before_month[month]; + if (month > 2 && is_leap(year)) + ++days; + return days; } /* year -> number of days before January 1st of year. Remember that we @@ -214,124 +214,124 @@ static int days_before_year(int year) { - int y = year - 1; - /* This is incorrect if year <= 0; we really want the floor - * here. But so long as MINYEAR is 1, the smallest year this - * can see is 0 (this can happen in some normalization endcases), - * so we'll just special-case that. - */ - assert (year >= 0); - if (y >= 0) - return y*365 + y/4 - y/100 + y/400; - else { - assert(y == -1); - return -366; - } + int y = year - 1; + /* This is incorrect if year <= 0; we really want the floor + * here. But so long as MINYEAR is 1, the smallest year this + * can see is 0 (this can happen in some normalization endcases), + * so we'll just special-case that. + */ + assert (year >= 0); + if (y >= 0) + return y*365 + y/4 - y/100 + y/400; + else { + assert(y == -1); + return -366; + } } /* Number of days in 4, 100, and 400 year cycles. That these have * the correct values is asserted in the module init function. */ -#define DI4Y 1461 /* days_before_year(5); days in 4 years */ -#define DI100Y 36524 /* days_before_year(101); days in 100 years */ -#define DI400Y 146097 /* days_before_year(401); days in 400 years */ +#define DI4Y 1461 /* days_before_year(5); days in 4 years */ +#define DI100Y 36524 /* days_before_year(101); days in 100 years */ +#define DI400Y 146097 /* days_before_year(401); days in 400 years */ /* ordinal -> year, month, day, considering 01-Jan-0001 as day 1. */ static void ord_to_ymd(int ordinal, int *year, int *month, int *day) { - int n, n1, n4, n100, n400, leapyear, preceding; + int n, n1, n4, n100, n400, leapyear, preceding; - /* ordinal is a 1-based index, starting at 1-Jan-1. The pattern of - * leap years repeats exactly every 400 years. The basic strategy is - * to find the closest 400-year boundary at or before ordinal, then - * work with the offset from that boundary to ordinal. Life is much - * clearer if we subtract 1 from ordinal first -- then the values - * of ordinal at 400-year boundaries are exactly those divisible - * by DI400Y: - * - * D M Y n n-1 - * -- --- ---- ---------- ---------------- - * 31 Dec -400 -DI400Y -DI400Y -1 - * 1 Jan -399 -DI400Y +1 -DI400Y 400-year boundary - * ... - * 30 Dec 000 -1 -2 - * 31 Dec 000 0 -1 - * 1 Jan 001 1 0 400-year boundary - * 2 Jan 001 2 1 - * 3 Jan 001 3 2 - * ... - * 31 Dec 400 DI400Y DI400Y -1 - * 1 Jan 401 DI400Y +1 DI400Y 400-year boundary - */ - assert(ordinal >= 1); - --ordinal; - n400 = ordinal / DI400Y; - n = ordinal % DI400Y; - *year = n400 * 400 + 1; - - /* Now n is the (non-negative) offset, in days, from January 1 of - * year, to the desired date. Now compute how many 100-year cycles - * precede n. - * Note that it's possible for n100 to equal 4! In that case 4 full - * 100-year cycles precede the desired day, which implies the - * desired day is December 31 at the end of a 400-year cycle. - */ - n100 = n / DI100Y; - n = n % DI100Y; - - /* Now compute how many 4-year cycles precede it. */ - n4 = n / DI4Y; - n = n % DI4Y; - - /* And now how many single years. Again n1 can be 4, and again - * meaning that the desired day is December 31 at the end of the - * 4-year cycle. - */ - n1 = n / 365; - n = n % 365; - - *year += n100 * 100 + n4 * 4 + n1; - if (n1 == 4 || n100 == 4) { - assert(n == 0); - *year -= 1; - *month = 12; - *day = 31; - return; - } - - /* Now the year is correct, and n is the offset from January 1. We - * find the month via an estimate that's either exact or one too - * large. - */ - leapyear = n1 == 3 && (n4 != 24 || n100 == 3); - assert(leapyear == is_leap(*year)); - *month = (n + 50) >> 5; - preceding = (_days_before_month[*month] + (*month > 2 && leapyear)); - if (preceding > n) { - /* estimate is too large */ - *month -= 1; - preceding -= days_in_month(*year, *month); - } - n -= preceding; - assert(0 <= n); - assert(n < days_in_month(*year, *month)); + /* ordinal is a 1-based index, starting at 1-Jan-1. The pattern of + * leap years repeats exactly every 400 years. The basic strategy is + * to find the closest 400-year boundary at or before ordinal, then + * work with the offset from that boundary to ordinal. Life is much + * clearer if we subtract 1 from ordinal first -- then the values + * of ordinal at 400-year boundaries are exactly those divisible + * by DI400Y: + * + * D M Y n n-1 + * -- --- ---- ---------- ---------------- + * 31 Dec -400 -DI400Y -DI400Y -1 + * 1 Jan -399 -DI400Y +1 -DI400Y 400-year boundary + * ... + * 30 Dec 000 -1 -2 + * 31 Dec 000 0 -1 + * 1 Jan 001 1 0 400-year boundary + * 2 Jan 001 2 1 + * 3 Jan 001 3 2 + * ... + * 31 Dec 400 DI400Y DI400Y -1 + * 1 Jan 401 DI400Y +1 DI400Y 400-year boundary + */ + assert(ordinal >= 1); + --ordinal; + n400 = ordinal / DI400Y; + n = ordinal % DI400Y; + *year = n400 * 400 + 1; + + /* Now n is the (non-negative) offset, in days, from January 1 of + * year, to the desired date. Now compute how many 100-year cycles + * precede n. + * Note that it's possible for n100 to equal 4! In that case 4 full + * 100-year cycles precede the desired day, which implies the + * desired day is December 31 at the end of a 400-year cycle. + */ + n100 = n / DI100Y; + n = n % DI100Y; + + /* Now compute how many 4-year cycles precede it. */ + n4 = n / DI4Y; + n = n % DI4Y; + + /* And now how many single years. Again n1 can be 4, and again + * meaning that the desired day is December 31 at the end of the + * 4-year cycle. + */ + n1 = n / 365; + n = n % 365; + + *year += n100 * 100 + n4 * 4 + n1; + if (n1 == 4 || n100 == 4) { + assert(n == 0); + *year -= 1; + *month = 12; + *day = 31; + return; + } + + /* Now the year is correct, and n is the offset from January 1. We + * find the month via an estimate that's either exact or one too + * large. + */ + leapyear = n1 == 3 && (n4 != 24 || n100 == 3); + assert(leapyear == is_leap(*year)); + *month = (n + 50) >> 5; + preceding = (_days_before_month[*month] + (*month > 2 && leapyear)); + if (preceding > n) { + /* estimate is too large */ + *month -= 1; + preceding -= days_in_month(*year, *month); + } + n -= preceding; + assert(0 <= n); + assert(n < days_in_month(*year, *month)); - *day = n + 1; + *day = n + 1; } /* year, month, day -> ordinal, considering 01-Jan-0001 as day 1. */ static int ymd_to_ord(int year, int month, int day) { - return days_before_year(year) + days_before_month(year, month) + day; + return days_before_year(year) + days_before_month(year, month) + day; } /* Day of week, where Monday==0, ..., Sunday==6. 1/1/1 was a Monday. */ static int weekday(int year, int month, int day) { - return (ymd_to_ord(year, month, day) + 6) % 7; + return (ymd_to_ord(year, month, day) + 6) % 7; } /* Ordinal of the Monday starting week 1 of the ISO year. Week 1 is the @@ -340,15 +340,15 @@ static int iso_week1_monday(int year) { - int first_day = ymd_to_ord(year, 1, 1); /* ord of 1/1 */ - /* 0 if 1/1 is a Monday, 1 if a Tue, etc. */ - int first_weekday = (first_day + 6) % 7; - /* ordinal of closest Monday at or before 1/1 */ - int week1_monday = first_day - first_weekday; - - if (first_weekday > 3) /* if 1/1 was Fri, Sat, Sun */ - week1_monday += 7; - return week1_monday; + int first_day = ymd_to_ord(year, 1, 1); /* ord of 1/1 */ + /* 0 if 1/1 is a Monday, 1 if a Tue, etc. */ + int first_weekday = (first_day + 6) % 7; + /* ordinal of closest Monday at or before 1/1 */ + int week1_monday = first_day - first_weekday; + + if (first_weekday > 3) /* if 1/1 was Fri, Sat, Sun */ + week1_monday += 7; + return week1_monday; } /* --------------------------------------------------------------------------- @@ -361,12 +361,12 @@ static int check_delta_day_range(int days) { - if (-MAX_DELTA_DAYS <= days && days <= MAX_DELTA_DAYS) - return 0; - PyErr_Format(PyExc_OverflowError, - "days=%d; must have magnitude <= %d", - days, MAX_DELTA_DAYS); - return -1; + if (-MAX_DELTA_DAYS <= days && days <= MAX_DELTA_DAYS) + return 0; + PyErr_Format(PyExc_OverflowError, + "days=%d; must have magnitude <= %d", + days, MAX_DELTA_DAYS); + return -1; } /* Check that date arguments are in range. Return 0 if they are. If they @@ -376,22 +376,22 @@ check_date_args(int year, int month, int day) { - if (year < MINYEAR || year > MAXYEAR) { - PyErr_SetString(PyExc_ValueError, - "year is out of range"); - return -1; - } - if (month < 1 || month > 12) { - PyErr_SetString(PyExc_ValueError, - "month must be in 1..12"); - return -1; - } - if (day < 1 || day > days_in_month(year, month)) { - PyErr_SetString(PyExc_ValueError, - "day is out of range for month"); - return -1; - } - return 0; + if (year < MINYEAR || year > MAXYEAR) { + PyErr_SetString(PyExc_ValueError, + "year is out of range"); + return -1; + } + if (month < 1 || month > 12) { + PyErr_SetString(PyExc_ValueError, + "month must be in 1..12"); + return -1; + } + if (day < 1 || day > days_in_month(year, month)) { + PyErr_SetString(PyExc_ValueError, + "day is out of range for month"); + return -1; + } + return 0; } /* Check that time arguments are in range. Return 0 if they are. If they @@ -400,27 +400,27 @@ static int check_time_args(int h, int m, int s, int us) { - if (h < 0 || h > 23) { - PyErr_SetString(PyExc_ValueError, - "hour must be in 0..23"); - return -1; - } - if (m < 0 || m > 59) { - PyErr_SetString(PyExc_ValueError, - "minute must be in 0..59"); - return -1; - } - if (s < 0 || s > 59) { - PyErr_SetString(PyExc_ValueError, - "second must be in 0..59"); - return -1; - } - if (us < 0 || us > 999999) { - PyErr_SetString(PyExc_ValueError, - "microsecond must be in 0..999999"); - return -1; - } - return 0; + if (h < 0 || h > 23) { + PyErr_SetString(PyExc_ValueError, + "hour must be in 0..23"); + return -1; + } + if (m < 0 || m > 59) { + PyErr_SetString(PyExc_ValueError, + "minute must be in 0..59"); + return -1; + } + if (s < 0 || s > 59) { + PyErr_SetString(PyExc_ValueError, + "second must be in 0..59"); + return -1; + } + if (us < 0 || us > 999999) { + PyErr_SetString(PyExc_ValueError, + "microsecond must be in 0..999999"); + return -1; + } + return 0; } /* --------------------------------------------------------------------------- @@ -436,109 +436,109 @@ static void normalize_pair(int *hi, int *lo, int factor) { - assert(factor > 0); - assert(lo != hi); - if (*lo < 0 || *lo >= factor) { - const int num_hi = divmod(*lo, factor, lo); - const int new_hi = *hi + num_hi; - assert(! SIGNED_ADD_OVERFLOWED(new_hi, *hi, num_hi)); - *hi = new_hi; - } - assert(0 <= *lo && *lo < factor); + assert(factor > 0); + assert(lo != hi); + if (*lo < 0 || *lo >= factor) { + const int num_hi = divmod(*lo, factor, lo); + const int new_hi = *hi + num_hi; + assert(! SIGNED_ADD_OVERFLOWED(new_hi, *hi, num_hi)); + *hi = new_hi; + } + assert(0 <= *lo && *lo < factor); } /* Fiddle days (d), seconds (s), and microseconds (us) so that - * 0 <= *s < 24*3600 - * 0 <= *us < 1000000 + * 0 <= *s < 24*3600 + * 0 <= *us < 1000000 * The input values must be such that the internals don't overflow. * The way this routine is used, we don't get close. */ static void normalize_d_s_us(int *d, int *s, int *us) { - if (*us < 0 || *us >= 1000000) { - normalize_pair(s, us, 1000000); - /* |s| can't be bigger than about - * |original s| + |original us|/1000000 now. - */ - - } - if (*s < 0 || *s >= 24*3600) { - normalize_pair(d, s, 24*3600); - /* |d| can't be bigger than about - * |original d| + - * (|original s| + |original us|/1000000) / (24*3600) now. - */ - } - assert(0 <= *s && *s < 24*3600); - assert(0 <= *us && *us < 1000000); + if (*us < 0 || *us >= 1000000) { + normalize_pair(s, us, 1000000); + /* |s| can't be bigger than about + * |original s| + |original us|/1000000 now. + */ + + } + if (*s < 0 || *s >= 24*3600) { + normalize_pair(d, s, 24*3600); + /* |d| can't be bigger than about + * |original d| + + * (|original s| + |original us|/1000000) / (24*3600) now. + */ + } + assert(0 <= *s && *s < 24*3600); + assert(0 <= *us && *us < 1000000); } /* Fiddle years (y), months (m), and days (d) so that - * 1 <= *m <= 12 - * 1 <= *d <= days_in_month(*y, *m) + * 1 <= *m <= 12 + * 1 <= *d <= days_in_month(*y, *m) * The input values must be such that the internals don't overflow. * The way this routine is used, we don't get close. */ static void normalize_y_m_d(int *y, int *m, int *d) { - int dim; /* # of days in month */ + int dim; /* # of days in month */ - /* This gets muddy: the proper range for day can't be determined - * without knowing the correct month and year, but if day is, e.g., - * plus or minus a million, the current month and year values make - * no sense (and may also be out of bounds themselves). - * Saying 12 months == 1 year should be non-controversial. - */ - if (*m < 1 || *m > 12) { - --*m; - normalize_pair(y, m, 12); - ++*m; - /* |y| can't be bigger than about - * |original y| + |original m|/12 now. - */ - } - assert(1 <= *m && *m <= 12); - - /* Now only day can be out of bounds (year may also be out of bounds - * for a datetime object, but we don't care about that here). - * If day is out of bounds, what to do is arguable, but at least the - * method here is principled and explainable. - */ - dim = days_in_month(*y, *m); - if (*d < 1 || *d > dim) { - /* Move day-1 days from the first of the month. First try to - * get off cheap if we're only one day out of range - * (adjustments for timezone alone can't be worse than that). - */ - if (*d == 0) { - --*m; - if (*m > 0) - *d = days_in_month(*y, *m); - else { - --*y; - *m = 12; - *d = 31; - } - } - else if (*d == dim + 1) { - /* move forward a day */ - ++*m; - *d = 1; - if (*m > 12) { - *m = 1; - ++*y; - } - } - else { - int ordinal = ymd_to_ord(*y, *m, 1) + - *d - 1; - ord_to_ymd(ordinal, y, m, d); - } - } - assert(*m > 0); - assert(*d > 0); + /* This gets muddy: the proper range for day can't be determined + * without knowing the correct month and year, but if day is, e.g., + * plus or minus a million, the current month and year values make + * no sense (and may also be out of bounds themselves). + * Saying 12 months == 1 year should be non-controversial. + */ + if (*m < 1 || *m > 12) { + --*m; + normalize_pair(y, m, 12); + ++*m; + /* |y| can't be bigger than about + * |original y| + |original m|/12 now. + */ + } + assert(1 <= *m && *m <= 12); + + /* Now only day can be out of bounds (year may also be out of bounds + * for a datetime object, but we don't care about that here). + * If day is out of bounds, what to do is arguable, but at least the + * method here is principled and explainable. + */ + dim = days_in_month(*y, *m); + if (*d < 1 || *d > dim) { + /* Move day-1 days from the first of the month. First try to + * get off cheap if we're only one day out of range + * (adjustments for timezone alone can't be worse than that). + */ + if (*d == 0) { + --*m; + if (*m > 0) + *d = days_in_month(*y, *m); + else { + --*y; + *m = 12; + *d = 31; + } + } + else if (*d == dim + 1) { + /* move forward a day */ + ++*m; + *d = 1; + if (*m > 12) { + *m = 1; + ++*y; + } + } + else { + int ordinal = ymd_to_ord(*y, *m, 1) + + *d - 1; + ord_to_ymd(ordinal, y, m, d); + } + } + assert(*m > 0); + assert(*d > 0); } /* Fiddle out-of-bounds months and days so that the result makes some kind @@ -548,17 +548,17 @@ static int normalize_date(int *year, int *month, int *day) { - int result; + int result; - normalize_y_m_d(year, month, day); - if (MINYEAR <= *year && *year <= MAXYEAR) - result = 0; - else { - PyErr_SetString(PyExc_OverflowError, - "date value out of range"); - result = -1; - } - return result; + normalize_y_m_d(year, month, day); + if (MINYEAR <= *year && *year <= MAXYEAR) + result = 0; + else { + PyErr_SetString(PyExc_OverflowError, + "date value out of range"); + result = -1; + } + return result; } /* Force all the datetime fields into range. The parameters are both @@ -569,11 +569,11 @@ int *hour, int *minute, int *second, int *microsecond) { - normalize_pair(second, microsecond, 1000000); - normalize_pair(minute, second, 60); - normalize_pair(hour, minute, 60); - normalize_pair(day, hour, 24); - return normalize_date(year, month, day); + normalize_pair(second, microsecond, 1000000); + normalize_pair(minute, second, 60); + normalize_pair(hour, minute, 60); + normalize_pair(day, hour, 24); + return normalize_date(year, month, day); } /* --------------------------------------------------------------------------- @@ -600,31 +600,31 @@ static PyObject * time_alloc(PyTypeObject *type, Py_ssize_t aware) { - PyObject *self; + PyObject *self; - self = (PyObject *) - PyObject_MALLOC(aware ? - sizeof(PyDateTime_Time) : - sizeof(_PyDateTime_BaseTime)); - if (self == NULL) - return (PyObject *)PyErr_NoMemory(); - PyObject_INIT(self, type); - return self; + self = (PyObject *) + PyObject_MALLOC(aware ? + sizeof(PyDateTime_Time) : + sizeof(_PyDateTime_BaseTime)); + if (self == NULL) + return (PyObject *)PyErr_NoMemory(); + PyObject_INIT(self, type); + return self; } static PyObject * datetime_alloc(PyTypeObject *type, Py_ssize_t aware) { - PyObject *self; + PyObject *self; - self = (PyObject *) - PyObject_MALLOC(aware ? - sizeof(PyDateTime_DateTime) : - sizeof(_PyDateTime_BaseDateTime)); - if (self == NULL) - return (PyObject *)PyErr_NoMemory(); - PyObject_INIT(self, type); - return self; + self = (PyObject *) + PyObject_MALLOC(aware ? + sizeof(PyDateTime_DateTime) : + sizeof(_PyDateTime_BaseDateTime)); + if (self == NULL) + return (PyObject *)PyErr_NoMemory(); + PyObject_INIT(self, type); + return self; } /* --------------------------------------------------------------------------- @@ -636,10 +636,10 @@ static void set_date_fields(PyDateTime_Date *self, int y, int m, int d) { - self->hashcode = -1; - SET_YEAR(self, y); - SET_MONTH(self, m); - SET_DAY(self, d); + self->hashcode = -1; + SET_YEAR(self, y); + SET_MONTH(self, m); + SET_DAY(self, d); } /* --------------------------------------------------------------------------- @@ -650,71 +650,71 @@ static PyObject * new_date_ex(int year, int month, int day, PyTypeObject *type) { - PyDateTime_Date *self; + PyDateTime_Date *self; - self = (PyDateTime_Date *) (type->tp_alloc(type, 0)); - if (self != NULL) - set_date_fields(self, year, month, day); - return (PyObject *) self; + self = (PyDateTime_Date *) (type->tp_alloc(type, 0)); + if (self != NULL) + set_date_fields(self, year, month, day); + return (PyObject *) self; } #define new_date(year, month, day) \ - new_date_ex(year, month, day, &PyDateTime_DateType) + new_date_ex(year, month, day, &PyDateTime_DateType) /* Create a datetime instance with no range checking. */ static PyObject * new_datetime_ex(int year, int month, int day, int hour, int minute, - int second, int usecond, PyObject *tzinfo, PyTypeObject *type) + int second, int usecond, PyObject *tzinfo, PyTypeObject *type) { - PyDateTime_DateTime *self; - char aware = tzinfo != Py_None; + PyDateTime_DateTime *self; + char aware = tzinfo != Py_None; - self = (PyDateTime_DateTime *) (type->tp_alloc(type, aware)); - if (self != NULL) { - self->hastzinfo = aware; - set_date_fields((PyDateTime_Date *)self, year, month, day); - DATE_SET_HOUR(self, hour); - DATE_SET_MINUTE(self, minute); - DATE_SET_SECOND(self, second); - DATE_SET_MICROSECOND(self, usecond); - if (aware) { - Py_INCREF(tzinfo); - self->tzinfo = tzinfo; - } - } - return (PyObject *)self; -} - -#define new_datetime(y, m, d, hh, mm, ss, us, tzinfo) \ - new_datetime_ex(y, m, d, hh, mm, ss, us, tzinfo, \ - &PyDateTime_DateTimeType) + self = (PyDateTime_DateTime *) (type->tp_alloc(type, aware)); + if (self != NULL) { + self->hastzinfo = aware; + set_date_fields((PyDateTime_Date *)self, year, month, day); + DATE_SET_HOUR(self, hour); + DATE_SET_MINUTE(self, minute); + DATE_SET_SECOND(self, second); + DATE_SET_MICROSECOND(self, usecond); + if (aware) { + Py_INCREF(tzinfo); + self->tzinfo = tzinfo; + } + } + return (PyObject *)self; +} + +#define new_datetime(y, m, d, hh, mm, ss, us, tzinfo) \ + new_datetime_ex(y, m, d, hh, mm, ss, us, tzinfo, \ + &PyDateTime_DateTimeType) /* Create a time instance with no range checking. */ static PyObject * new_time_ex(int hour, int minute, int second, int usecond, - PyObject *tzinfo, PyTypeObject *type) + PyObject *tzinfo, PyTypeObject *type) { - PyDateTime_Time *self; - char aware = tzinfo != Py_None; + PyDateTime_Time *self; + char aware = tzinfo != Py_None; - self = (PyDateTime_Time *) (type->tp_alloc(type, aware)); - if (self != NULL) { - self->hastzinfo = aware; - self->hashcode = -1; - TIME_SET_HOUR(self, hour); - TIME_SET_MINUTE(self, minute); - TIME_SET_SECOND(self, second); - TIME_SET_MICROSECOND(self, usecond); - if (aware) { - Py_INCREF(tzinfo); - self->tzinfo = tzinfo; - } - } - return (PyObject *)self; + self = (PyDateTime_Time *) (type->tp_alloc(type, aware)); + if (self != NULL) { + self->hastzinfo = aware; + self->hashcode = -1; + TIME_SET_HOUR(self, hour); + TIME_SET_MINUTE(self, minute); + TIME_SET_SECOND(self, second); + TIME_SET_MICROSECOND(self, usecond); + if (aware) { + Py_INCREF(tzinfo); + self->tzinfo = tzinfo; + } + } + return (PyObject *)self; } -#define new_time(hh, mm, ss, us, tzinfo) \ - new_time_ex(hh, mm, ss, us, tzinfo, &PyDateTime_TimeType) +#define new_time(hh, mm, ss, us, tzinfo) \ + new_time_ex(hh, mm, ss, us, tzinfo, &PyDateTime_TimeType) /* Create a timedelta instance. Normalize the members iff normalize is * true. Passing false is a speed optimization, if you know for sure @@ -724,30 +724,30 @@ */ static PyObject * new_delta_ex(int days, int seconds, int microseconds, int normalize, - PyTypeObject *type) + PyTypeObject *type) { - PyDateTime_Delta *self; + PyDateTime_Delta *self; - if (normalize) - normalize_d_s_us(&days, &seconds, µseconds); - assert(0 <= seconds && seconds < 24*3600); - assert(0 <= microseconds && microseconds < 1000000); - - if (check_delta_day_range(days) < 0) - return NULL; - - self = (PyDateTime_Delta *) (type->tp_alloc(type, 0)); - if (self != NULL) { - self->hashcode = -1; - SET_TD_DAYS(self, days); - SET_TD_SECONDS(self, seconds); - SET_TD_MICROSECONDS(self, microseconds); - } - return (PyObject *) self; + if (normalize) + normalize_d_s_us(&days, &seconds, µseconds); + assert(0 <= seconds && seconds < 24*3600); + assert(0 <= microseconds && microseconds < 1000000); + + if (check_delta_day_range(days) < 0) + return NULL; + + self = (PyDateTime_Delta *) (type->tp_alloc(type, 0)); + if (self != NULL) { + self->hashcode = -1; + SET_TD_DAYS(self, days); + SET_TD_SECONDS(self, seconds); + SET_TD_MICROSECONDS(self, microseconds); + } + return (PyObject *) self; } -#define new_delta(d, s, us, normalize) \ - new_delta_ex(d, s, us, normalize, &PyDateTime_DeltaType) +#define new_delta(d, s, us, normalize) \ + new_delta_ex(d, s, us, normalize, &PyDateTime_DeltaType) /* --------------------------------------------------------------------------- * tzinfo helpers. @@ -759,13 +759,13 @@ static int check_tzinfo_subclass(PyObject *p) { - if (p == Py_None || PyTZInfo_Check(p)) - return 0; - PyErr_Format(PyExc_TypeError, - "tzinfo argument must be None or of a tzinfo subclass, " - "not type '%s'", - Py_TYPE(p)->tp_name); - return -1; + if (p == Py_None || PyTZInfo_Check(p)) + return 0; + PyErr_Format(PyExc_TypeError, + "tzinfo argument must be None or of a tzinfo subclass, " + "not type '%s'", + Py_TYPE(p)->tp_name); + return -1; } /* Return tzinfo.methname(tzinfoarg), without any checking of results. @@ -774,17 +774,17 @@ static PyObject * call_tzinfo_method(PyObject *tzinfo, char *methname, PyObject *tzinfoarg) { - PyObject *result; + PyObject *result; - assert(tzinfo && methname && tzinfoarg); - assert(check_tzinfo_subclass(tzinfo) >= 0); - if (tzinfo == Py_None) { - result = Py_None; - Py_INCREF(result); - } - else - result = PyObject_CallMethod(tzinfo, methname, "O", tzinfoarg); - return result; + assert(tzinfo && methname && tzinfoarg); + assert(check_tzinfo_subclass(tzinfo) >= 0); + if (tzinfo == Py_None) { + result = Py_None; + Py_INCREF(result); + } + else + result = PyObject_CallMethod(tzinfo, methname, "O", tzinfoarg); + return result; } /* If self has a tzinfo member, return a BORROWED reference to it. Else @@ -794,14 +794,14 @@ static PyObject * get_tzinfo_member(PyObject *self) { - PyObject *tzinfo = NULL; + PyObject *tzinfo = NULL; - if (PyDateTime_Check(self) && HASTZINFO(self)) - tzinfo = ((PyDateTime_DateTime *)self)->tzinfo; - else if (PyTime_Check(self) && HASTZINFO(self)) - tzinfo = ((PyDateTime_Time *)self)->tzinfo; + if (PyDateTime_Check(self) && HASTZINFO(self)) + tzinfo = ((PyDateTime_DateTime *)self)->tzinfo; + else if (PyTime_Check(self) && HASTZINFO(self)) + tzinfo = ((PyDateTime_Time *)self)->tzinfo; - return tzinfo; + return tzinfo; } /* Call getattr(tzinfo, name)(tzinfoarg), and extract an int from the @@ -814,59 +814,59 @@ */ static int call_utc_tzinfo_method(PyObject *tzinfo, char *name, PyObject *tzinfoarg, - int *none) + int *none) { - PyObject *u; - int result = -1; + PyObject *u; + int result = -1; - assert(tzinfo != NULL); - assert(PyTZInfo_Check(tzinfo)); - assert(tzinfoarg != NULL); - - *none = 0; - u = call_tzinfo_method(tzinfo, name, tzinfoarg); - if (u == NULL) - return -1; - - else if (u == Py_None) { - result = 0; - *none = 1; - } - else if (PyDelta_Check(u)) { - const int days = GET_TD_DAYS(u); - if (days < -1 || days > 0) - result = 24*60; /* trigger ValueError below */ - else { - /* next line can't overflow because we know days - * is -1 or 0 now - */ - int ss = days * 24 * 3600 + GET_TD_SECONDS(u); - result = divmod(ss, 60, &ss); - if (ss || GET_TD_MICROSECONDS(u)) { - PyErr_Format(PyExc_ValueError, - "tzinfo.%s() must return a " - "whole number of minutes", - name); - result = -1; - } - } - } - else { - PyErr_Format(PyExc_TypeError, - "tzinfo.%s() must return None or " - "timedelta, not '%s'", - name, Py_TYPE(u)->tp_name); - } - - Py_DECREF(u); - if (result < -1439 || result > 1439) { - PyErr_Format(PyExc_ValueError, - "tzinfo.%s() returned %d; must be in " - "-1439 .. 1439", - name, result); - result = -1; - } - return result; + assert(tzinfo != NULL); + assert(PyTZInfo_Check(tzinfo)); + assert(tzinfoarg != NULL); + + *none = 0; + u = call_tzinfo_method(tzinfo, name, tzinfoarg); + if (u == NULL) + return -1; + + else if (u == Py_None) { + result = 0; + *none = 1; + } + else if (PyDelta_Check(u)) { + const int days = GET_TD_DAYS(u); + if (days < -1 || days > 0) + result = 24*60; /* trigger ValueError below */ + else { + /* next line can't overflow because we know days + * is -1 or 0 now + */ + int ss = days * 24 * 3600 + GET_TD_SECONDS(u); + result = divmod(ss, 60, &ss); + if (ss || GET_TD_MICROSECONDS(u)) { + PyErr_Format(PyExc_ValueError, + "tzinfo.%s() must return a " + "whole number of minutes", + name); + result = -1; + } + } + } + else { + PyErr_Format(PyExc_TypeError, + "tzinfo.%s() must return None or " + "timedelta, not '%s'", + name, Py_TYPE(u)->tp_name); + } + + Py_DECREF(u); + if (result < -1439 || result > 1439) { + PyErr_Format(PyExc_ValueError, + "tzinfo.%s() returned %d; must be in " + "-1439 .. 1439", + name, result); + result = -1; + } + return result; } /* Call tzinfo.utcoffset(tzinfoarg), and extract an integer from the @@ -880,34 +880,34 @@ static int call_utcoffset(PyObject *tzinfo, PyObject *tzinfoarg, int *none) { - return call_utc_tzinfo_method(tzinfo, "utcoffset", tzinfoarg, none); + return call_utc_tzinfo_method(tzinfo, "utcoffset", tzinfoarg, none); } /* Call tzinfo.name(tzinfoarg), and return the offset as a timedelta or None. */ static PyObject * offset_as_timedelta(PyObject *tzinfo, char *name, PyObject *tzinfoarg) { - PyObject *result; + PyObject *result; - assert(tzinfo && name && tzinfoarg); - if (tzinfo == Py_None) { - result = Py_None; - Py_INCREF(result); - } - else { - int none; - int offset = call_utc_tzinfo_method(tzinfo, name, tzinfoarg, - &none); - if (offset < 0 && PyErr_Occurred()) - return NULL; - if (none) { - result = Py_None; - Py_INCREF(result); - } - else - result = new_delta(0, offset * 60, 0, 1); - } - return result; + assert(tzinfo && name && tzinfoarg); + if (tzinfo == Py_None) { + result = Py_None; + Py_INCREF(result); + } + else { + int none; + int offset = call_utc_tzinfo_method(tzinfo, name, tzinfoarg, + &none); + if (offset < 0 && PyErr_Occurred()) + return NULL; + if (none) { + result = Py_None; + Py_INCREF(result); + } + else + result = new_delta(0, offset * 60, 0, 1); + } + return result; } /* Call tzinfo.dst(tzinfoarg), and extract an integer from the @@ -921,7 +921,7 @@ static int call_dst(PyObject *tzinfo, PyObject *tzinfoarg, int *none) { - return call_utc_tzinfo_method(tzinfo, "dst", tzinfoarg, none); + return call_utc_tzinfo_method(tzinfo, "dst", tzinfoarg, none); } /* Call tzinfo.tzname(tzinfoarg), and return the result. tzinfo must be @@ -933,55 +933,55 @@ static PyObject * call_tzname(PyObject *tzinfo, PyObject *tzinfoarg) { - PyObject *result; + PyObject *result; - assert(tzinfo != NULL); - assert(check_tzinfo_subclass(tzinfo) >= 0); - assert(tzinfoarg != NULL); - - if (tzinfo == Py_None) { - result = Py_None; - Py_INCREF(result); - } - else - result = PyObject_CallMethod(tzinfo, "tzname", "O", tzinfoarg); - - if (result != NULL && result != Py_None) { - if (!PyUnicode_Check(result)) { - PyErr_Format(PyExc_TypeError, "tzinfo.tzname() must " - "return None or a string, not '%s'", - Py_TYPE(result)->tp_name); - Py_DECREF(result); - result = NULL; - } - else if (!PyUnicode_Check(result)) { - PyObject *temp = PyUnicode_FromObject(result); - Py_DECREF(result); - result = temp; - } - } - return result; + assert(tzinfo != NULL); + assert(check_tzinfo_subclass(tzinfo) >= 0); + assert(tzinfoarg != NULL); + + if (tzinfo == Py_None) { + result = Py_None; + Py_INCREF(result); + } + else + result = PyObject_CallMethod(tzinfo, "tzname", "O", tzinfoarg); + + if (result != NULL && result != Py_None) { + if (!PyUnicode_Check(result)) { + PyErr_Format(PyExc_TypeError, "tzinfo.tzname() must " + "return None or a string, not '%s'", + Py_TYPE(result)->tp_name); + Py_DECREF(result); + result = NULL; + } + else if (!PyUnicode_Check(result)) { + PyObject *temp = PyUnicode_FromObject(result); + Py_DECREF(result); + result = temp; + } + } + return result; } typedef enum { - /* an exception has been set; the caller should pass it on */ - OFFSET_ERROR, + /* an exception has been set; the caller should pass it on */ + OFFSET_ERROR, - /* type isn't date, datetime, or time subclass */ - OFFSET_UNKNOWN, + /* type isn't date, datetime, or time subclass */ + OFFSET_UNKNOWN, - /* date, - * datetime with !hastzinfo - * datetime with None tzinfo, - * datetime where utcoffset() returns None - * time with !hastzinfo - * time with None tzinfo, - * time where utcoffset() returns None - */ - OFFSET_NAIVE, + /* date, + * datetime with !hastzinfo + * datetime with None tzinfo, + * datetime where utcoffset() returns None + * time with !hastzinfo + * time with None tzinfo, + * time where utcoffset() returns None + */ + OFFSET_NAIVE, - /* time or datetime where utcoffset() doesn't return None */ - OFFSET_AWARE + /* time or datetime where utcoffset() doesn't return None */ + OFFSET_AWARE } naivety; /* Classify an object as to whether it's naive or offset-aware. See @@ -993,23 +993,23 @@ static naivety classify_utcoffset(PyObject *op, PyObject *tzinfoarg, int *offset) { - int none; - PyObject *tzinfo; + int none; + PyObject *tzinfo; - assert(tzinfoarg != NULL); - *offset = 0; - tzinfo = get_tzinfo_member(op); /* NULL means no tzinfo, not error */ - if (tzinfo == Py_None) - return OFFSET_NAIVE; - if (tzinfo == NULL) { - /* note that a datetime passes the PyDate_Check test */ - return (PyTime_Check(op) || PyDate_Check(op)) ? - OFFSET_NAIVE : OFFSET_UNKNOWN; - } - *offset = call_utcoffset(tzinfo, tzinfoarg, &none); - if (*offset == -1 && PyErr_Occurred()) - return OFFSET_ERROR; - return none ? OFFSET_NAIVE : OFFSET_AWARE; + assert(tzinfoarg != NULL); + *offset = 0; + tzinfo = get_tzinfo_member(op); /* NULL means no tzinfo, not error */ + if (tzinfo == Py_None) + return OFFSET_NAIVE; + if (tzinfo == NULL) { + /* note that a datetime passes the PyDate_Check test */ + return (PyTime_Check(op) || PyDate_Check(op)) ? + OFFSET_NAIVE : OFFSET_UNKNOWN; + } + *offset = call_utcoffset(tzinfo, tzinfoarg, &none); + if (*offset == -1 && PyErr_Occurred()) + return OFFSET_ERROR; + return none ? OFFSET_NAIVE : OFFSET_AWARE; } /* Classify two objects as to whether they're naive or offset-aware. @@ -1023,23 +1023,23 @@ */ static int classify_two_utcoffsets(PyObject *o1, int *offset1, naivety *n1, - PyObject *tzinfoarg1, - PyObject *o2, int *offset2, naivety *n2, - PyObject *tzinfoarg2) -{ - if (get_tzinfo_member(o1) == get_tzinfo_member(o2)) { - *offset1 = *offset2 = 0; - *n1 = *n2 = OFFSET_NAIVE; - } - else { - *n1 = classify_utcoffset(o1, tzinfoarg1, offset1); - if (*n1 == OFFSET_ERROR) - return -1; - *n2 = classify_utcoffset(o2, tzinfoarg2, offset2); - if (*n2 == OFFSET_ERROR) - return -1; - } - return 0; + PyObject *tzinfoarg1, + PyObject *o2, int *offset2, naivety *n2, + PyObject *tzinfoarg2) +{ + if (get_tzinfo_member(o1) == get_tzinfo_member(o2)) { + *offset1 = *offset2 = 0; + *n1 = *n2 = OFFSET_NAIVE; + } + else { + *n1 = classify_utcoffset(o1, tzinfoarg1, offset1); + if (*n1 == OFFSET_ERROR) + return -1; + *n2 = classify_utcoffset(o2, tzinfoarg2, offset2); + if (*n2 == OFFSET_ERROR) + return -1; + } + return 0; } /* repr is like "someclass(arg1, arg2)". If tzinfo isn't None, @@ -1050,22 +1050,22 @@ static PyObject * append_keyword_tzinfo(PyObject *repr, PyObject *tzinfo) { - PyObject *temp; + PyObject *temp; - assert(PyUnicode_Check(repr)); - assert(tzinfo); - if (tzinfo == Py_None) - return repr; - /* Get rid of the trailing ')'. */ - assert(PyUnicode_AS_UNICODE(repr)[PyUnicode_GET_SIZE(repr)-1] == ')'); - temp = PyUnicode_FromUnicode(PyUnicode_AS_UNICODE(repr), - PyUnicode_GET_SIZE(repr) - 1); - Py_DECREF(repr); - if (temp == NULL) - return NULL; - repr = PyUnicode_FromFormat("%U, tzinfo=%R)", temp, tzinfo); - Py_DECREF(temp); - return repr; + assert(PyUnicode_Check(repr)); + assert(tzinfo); + if (tzinfo == Py_None) + return repr; + /* Get rid of the trailing ')'. */ + assert(PyUnicode_AS_UNICODE(repr)[PyUnicode_GET_SIZE(repr)-1] == ')'); + temp = PyUnicode_FromUnicode(PyUnicode_AS_UNICODE(repr), + PyUnicode_GET_SIZE(repr) - 1); + Py_DECREF(repr); + if (temp == NULL) + return NULL; + repr = PyUnicode_FromFormat("%U, tzinfo=%R)", temp, tzinfo); + Py_DECREF(temp); + return repr; } /* --------------------------------------------------------------------------- @@ -1075,20 +1075,20 @@ static PyObject * format_ctime(PyDateTime_Date *date, int hours, int minutes, int seconds) { - static const char *DayNames[] = { - "Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun" - }; - static const char *MonthNames[] = { - "Jan", "Feb", "Mar", "Apr", "May", "Jun", - "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" - }; - - int wday = weekday(GET_YEAR(date), GET_MONTH(date), GET_DAY(date)); - - return PyUnicode_FromFormat("%s %s %2d %02d:%02d:%02d %04d", - DayNames[wday], MonthNames[GET_MONTH(date)-1], - GET_DAY(date), hours, minutes, seconds, - GET_YEAR(date)); + static const char *DayNames[] = { + "Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun" + }; + static const char *MonthNames[] = { + "Jan", "Feb", "Mar", "Apr", "May", "Jun", + "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" + }; + + int wday = weekday(GET_YEAR(date), GET_MONTH(date), GET_DAY(date)); + + return PyUnicode_FromFormat("%s %s %2d %02d:%02d:%02d %04d", + DayNames[wday], MonthNames[GET_MONTH(date)-1], + GET_DAY(date), hours, minutes, seconds, + GET_YEAR(date)); } /* Add an hours & minutes UTC offset string to buf. buf has no more than @@ -1103,87 +1103,87 @@ */ static int format_utcoffset(char *buf, size_t buflen, const char *sep, - PyObject *tzinfo, PyObject *tzinfoarg) + PyObject *tzinfo, PyObject *tzinfoarg) { - int offset; - int hours; - int minutes; - char sign; - int none; - - assert(buflen >= 1); - - offset = call_utcoffset(tzinfo, tzinfoarg, &none); - if (offset == -1 && PyErr_Occurred()) - return -1; - if (none) { - *buf = '\0'; - return 0; - } - sign = '+'; - if (offset < 0) { - sign = '-'; - offset = - offset; - } - hours = divmod(offset, 60, &minutes); - PyOS_snprintf(buf, buflen, "%c%02d%s%02d", sign, hours, sep, minutes); - return 0; + int offset; + int hours; + int minutes; + char sign; + int none; + + assert(buflen >= 1); + + offset = call_utcoffset(tzinfo, tzinfoarg, &none); + if (offset == -1 && PyErr_Occurred()) + return -1; + if (none) { + *buf = '\0'; + return 0; + } + sign = '+'; + if (offset < 0) { + sign = '-'; + offset = - offset; + } + hours = divmod(offset, 60, &minutes); + PyOS_snprintf(buf, buflen, "%c%02d%s%02d", sign, hours, sep, minutes); + return 0; } static PyObject * make_Zreplacement(PyObject *object, PyObject *tzinfoarg) { - PyObject *temp; - PyObject *tzinfo = get_tzinfo_member(object); - PyObject *Zreplacement = PyUnicode_FromStringAndSize(NULL, 0); - if (Zreplacement == NULL) - return NULL; - if (tzinfo == Py_None || tzinfo == NULL) - return Zreplacement; - - assert(tzinfoarg != NULL); - temp = call_tzname(tzinfo, tzinfoarg); - if (temp == NULL) - goto Error; - if (temp == Py_None) { - Py_DECREF(temp); - return Zreplacement; - } - - assert(PyUnicode_Check(temp)); - /* Since the tzname is getting stuffed into the - * format, we have to double any % signs so that - * strftime doesn't treat them as format codes. - */ - Py_DECREF(Zreplacement); - Zreplacement = PyObject_CallMethod(temp, "replace", "ss", "%", "%%"); - Py_DECREF(temp); - if (Zreplacement == NULL) - return NULL; - if (!PyUnicode_Check(Zreplacement)) { - PyErr_SetString(PyExc_TypeError, - "tzname.replace() did not return a string"); - goto Error; - } - return Zreplacement; + PyObject *temp; + PyObject *tzinfo = get_tzinfo_member(object); + PyObject *Zreplacement = PyUnicode_FromStringAndSize(NULL, 0); + if (Zreplacement == NULL) + return NULL; + if (tzinfo == Py_None || tzinfo == NULL) + return Zreplacement; + + assert(tzinfoarg != NULL); + temp = call_tzname(tzinfo, tzinfoarg); + if (temp == NULL) + goto Error; + if (temp == Py_None) { + Py_DECREF(temp); + return Zreplacement; + } + + assert(PyUnicode_Check(temp)); + /* Since the tzname is getting stuffed into the + * format, we have to double any % signs so that + * strftime doesn't treat them as format codes. + */ + Py_DECREF(Zreplacement); + Zreplacement = PyObject_CallMethod(temp, "replace", "ss", "%", "%%"); + Py_DECREF(temp); + if (Zreplacement == NULL) + return NULL; + if (!PyUnicode_Check(Zreplacement)) { + PyErr_SetString(PyExc_TypeError, + "tzname.replace() did not return a string"); + goto Error; + } + return Zreplacement; Error: - Py_DECREF(Zreplacement); - return NULL; + Py_DECREF(Zreplacement); + return NULL; } static PyObject * make_freplacement(PyObject *object) { - char freplacement[64]; - if (PyTime_Check(object)) - sprintf(freplacement, "%06d", TIME_GET_MICROSECOND(object)); - else if (PyDateTime_Check(object)) - sprintf(freplacement, "%06d", DATE_GET_MICROSECOND(object)); - else - sprintf(freplacement, "%06d", 0); + char freplacement[64]; + if (PyTime_Check(object)) + sprintf(freplacement, "%06d", TIME_GET_MICROSECOND(object)); + else if (PyDateTime_Check(object)) + sprintf(freplacement, "%06d", DATE_GET_MICROSECOND(object)); + else + sprintf(freplacement, "%06d", 0); - return PyBytes_FromStringAndSize(freplacement, strlen(freplacement)); + return PyBytes_FromStringAndSize(freplacement, strlen(freplacement)); } /* I sure don't want to reproduce the strftime code from the time module, @@ -1195,190 +1195,190 @@ */ static PyObject * wrap_strftime(PyObject *object, PyObject *format, PyObject *timetuple, - PyObject *tzinfoarg) + PyObject *tzinfoarg) { - PyObject *result = NULL; /* guilty until proved innocent */ + PyObject *result = NULL; /* guilty until proved innocent */ - PyObject *zreplacement = NULL; /* py string, replacement for %z */ - PyObject *Zreplacement = NULL; /* py string, replacement for %Z */ - PyObject *freplacement = NULL; /* py string, replacement for %f */ - - const char *pin; /* pointer to next char in input format */ - Py_ssize_t flen; /* length of input format */ - char ch; /* next char in input format */ - - PyObject *newfmt = NULL; /* py string, the output format */ - char *pnew; /* pointer to available byte in output format */ - size_t totalnew; /* number bytes total in output format buffer, - exclusive of trailing \0 */ - size_t usednew; /* number bytes used so far in output format buffer */ - - const char *ptoappend; /* ptr to string to append to output buffer */ - Py_ssize_t ntoappend; /* # of bytes to append to output buffer */ - - assert(object && format && timetuple); - assert(PyUnicode_Check(format)); - /* Convert the input format to a C string and size */ - pin = _PyUnicode_AsStringAndSize(format, &flen); - if (!pin) - return NULL; - - /* Give up if the year is before 1900. - * Python strftime() plays games with the year, and different - * games depending on whether envar PYTHON2K is set. This makes - * years before 1900 a nightmare, even if the platform strftime - * supports them (and not all do). - * We could get a lot farther here by avoiding Python's strftime - * wrapper and calling the C strftime() directly, but that isn't - * an option in the Python implementation of this module. - */ - { - long year; - PyObject *pyyear = PySequence_GetItem(timetuple, 0); - if (pyyear == NULL) return NULL; - assert(PyLong_Check(pyyear)); - year = PyLong_AsLong(pyyear); - Py_DECREF(pyyear); - if (year < 1900) { - PyErr_Format(PyExc_ValueError, "year=%ld is before " - "1900; the datetime strftime() " - "methods require year >= 1900", - year); - return NULL; - } - } - - /* Scan the input format, looking for %z/%Z/%f escapes, building - * a new format. Since computing the replacements for those codes - * is expensive, don't unless they're actually used. - */ - if (flen > INT_MAX - 1) { - PyErr_NoMemory(); - goto Done; - } - - totalnew = flen + 1; /* realistic if no %z/%Z */ - newfmt = PyBytes_FromStringAndSize(NULL, totalnew); - if (newfmt == NULL) goto Done; - pnew = PyBytes_AsString(newfmt); - usednew = 0; - - while ((ch = *pin++) != '\0') { - if (ch != '%') { - ptoappend = pin - 1; - ntoappend = 1; - } - else if ((ch = *pin++) == '\0') { - /* There's a lone trailing %; doesn't make sense. */ - PyErr_SetString(PyExc_ValueError, "strftime format " - "ends with raw %"); - goto Done; - } - /* A % has been seen and ch is the character after it. */ - else if (ch == 'z') { - if (zreplacement == NULL) { - /* format utcoffset */ - char buf[100]; - PyObject *tzinfo = get_tzinfo_member(object); - zreplacement = PyBytes_FromStringAndSize("", 0); - if (zreplacement == NULL) goto Done; - if (tzinfo != Py_None && tzinfo != NULL) { - assert(tzinfoarg != NULL); - if (format_utcoffset(buf, - sizeof(buf), - "", - tzinfo, - tzinfoarg) < 0) - goto Done; - Py_DECREF(zreplacement); - zreplacement = - PyBytes_FromStringAndSize(buf, - strlen(buf)); - if (zreplacement == NULL) - goto Done; - } - } - assert(zreplacement != NULL); - ptoappend = PyBytes_AS_STRING(zreplacement); - ntoappend = PyBytes_GET_SIZE(zreplacement); - } - else if (ch == 'Z') { - /* format tzname */ - if (Zreplacement == NULL) { - Zreplacement = make_Zreplacement(object, - tzinfoarg); - if (Zreplacement == NULL) - goto Done; - } - assert(Zreplacement != NULL); - assert(PyUnicode_Check(Zreplacement)); - ptoappend = _PyUnicode_AsStringAndSize(Zreplacement, - &ntoappend); - ntoappend = Py_SIZE(Zreplacement); - } - else if (ch == 'f') { - /* format microseconds */ - if (freplacement == NULL) { - freplacement = make_freplacement(object); - if (freplacement == NULL) - goto Done; - } - assert(freplacement != NULL); - assert(PyBytes_Check(freplacement)); - ptoappend = PyBytes_AS_STRING(freplacement); - ntoappend = PyBytes_GET_SIZE(freplacement); - } - else { - /* percent followed by neither z nor Z */ - ptoappend = pin - 2; - ntoappend = 2; - } - - /* Append the ntoappend chars starting at ptoappend to - * the new format. - */ - if (ntoappend == 0) - continue; - assert(ptoappend != NULL); - assert(ntoappend > 0); - while (usednew + ntoappend > totalnew) { - size_t bigger = totalnew << 1; - if ((bigger >> 1) != totalnew) { /* overflow */ - PyErr_NoMemory(); - goto Done; - } - if (_PyBytes_Resize(&newfmt, bigger) < 0) - goto Done; - totalnew = bigger; - pnew = PyBytes_AsString(newfmt) + usednew; - } - memcpy(pnew, ptoappend, ntoappend); - pnew += ntoappend; - usednew += ntoappend; - assert(usednew <= totalnew); - } /* end while() */ - - if (_PyBytes_Resize(&newfmt, usednew) < 0) - goto Done; - { - PyObject *format; - PyObject *time = PyImport_ImportModuleNoBlock("time"); - if (time == NULL) - goto Done; - format = PyUnicode_FromString(PyBytes_AS_STRING(newfmt)); - if (format != NULL) { - result = PyObject_CallMethod(time, "strftime", "OO", - format, timetuple); - Py_DECREF(format); - } - Py_DECREF(time); - } + PyObject *zreplacement = NULL; /* py string, replacement for %z */ + PyObject *Zreplacement = NULL; /* py string, replacement for %Z */ + PyObject *freplacement = NULL; /* py string, replacement for %f */ + + const char *pin; /* pointer to next char in input format */ + Py_ssize_t flen; /* length of input format */ + char ch; /* next char in input format */ + + PyObject *newfmt = NULL; /* py string, the output format */ + char *pnew; /* pointer to available byte in output format */ + size_t totalnew; /* number bytes total in output format buffer, + exclusive of trailing \0 */ + size_t usednew; /* number bytes used so far in output format buffer */ + + const char *ptoappend; /* ptr to string to append to output buffer */ + Py_ssize_t ntoappend; /* # of bytes to append to output buffer */ + + assert(object && format && timetuple); + assert(PyUnicode_Check(format)); + /* Convert the input format to a C string and size */ + pin = _PyUnicode_AsStringAndSize(format, &flen); + if (!pin) + return NULL; + + /* Give up if the year is before 1900. + * Python strftime() plays games with the year, and different + * games depending on whether envar PYTHON2K is set. This makes + * years before 1900 a nightmare, even if the platform strftime + * supports them (and not all do). + * We could get a lot farther here by avoiding Python's strftime + * wrapper and calling the C strftime() directly, but that isn't + * an option in the Python implementation of this module. + */ + { + long year; + PyObject *pyyear = PySequence_GetItem(timetuple, 0); + if (pyyear == NULL) return NULL; + assert(PyLong_Check(pyyear)); + year = PyLong_AsLong(pyyear); + Py_DECREF(pyyear); + if (year < 1900) { + PyErr_Format(PyExc_ValueError, "year=%ld is before " + "1900; the datetime strftime() " + "methods require year >= 1900", + year); + return NULL; + } + } + + /* Scan the input format, looking for %z/%Z/%f escapes, building + * a new format. Since computing the replacements for those codes + * is expensive, don't unless they're actually used. + */ + if (flen > INT_MAX - 1) { + PyErr_NoMemory(); + goto Done; + } + + totalnew = flen + 1; /* realistic if no %z/%Z */ + newfmt = PyBytes_FromStringAndSize(NULL, totalnew); + if (newfmt == NULL) goto Done; + pnew = PyBytes_AsString(newfmt); + usednew = 0; + + while ((ch = *pin++) != '\0') { + if (ch != '%') { + ptoappend = pin - 1; + ntoappend = 1; + } + else if ((ch = *pin++) == '\0') { + /* There's a lone trailing %; doesn't make sense. */ + PyErr_SetString(PyExc_ValueError, "strftime format " + "ends with raw %"); + goto Done; + } + /* A % has been seen and ch is the character after it. */ + else if (ch == 'z') { + if (zreplacement == NULL) { + /* format utcoffset */ + char buf[100]; + PyObject *tzinfo = get_tzinfo_member(object); + zreplacement = PyBytes_FromStringAndSize("", 0); + if (zreplacement == NULL) goto Done; + if (tzinfo != Py_None && tzinfo != NULL) { + assert(tzinfoarg != NULL); + if (format_utcoffset(buf, + sizeof(buf), + "", + tzinfo, + tzinfoarg) < 0) + goto Done; + Py_DECREF(zreplacement); + zreplacement = + PyBytes_FromStringAndSize(buf, + strlen(buf)); + if (zreplacement == NULL) + goto Done; + } + } + assert(zreplacement != NULL); + ptoappend = PyBytes_AS_STRING(zreplacement); + ntoappend = PyBytes_GET_SIZE(zreplacement); + } + else if (ch == 'Z') { + /* format tzname */ + if (Zreplacement == NULL) { + Zreplacement = make_Zreplacement(object, + tzinfoarg); + if (Zreplacement == NULL) + goto Done; + } + assert(Zreplacement != NULL); + assert(PyUnicode_Check(Zreplacement)); + ptoappend = _PyUnicode_AsStringAndSize(Zreplacement, + &ntoappend); + ntoappend = Py_SIZE(Zreplacement); + } + else if (ch == 'f') { + /* format microseconds */ + if (freplacement == NULL) { + freplacement = make_freplacement(object); + if (freplacement == NULL) + goto Done; + } + assert(freplacement != NULL); + assert(PyBytes_Check(freplacement)); + ptoappend = PyBytes_AS_STRING(freplacement); + ntoappend = PyBytes_GET_SIZE(freplacement); + } + else { + /* percent followed by neither z nor Z */ + ptoappend = pin - 2; + ntoappend = 2; + } + + /* Append the ntoappend chars starting at ptoappend to + * the new format. + */ + if (ntoappend == 0) + continue; + assert(ptoappend != NULL); + assert(ntoappend > 0); + while (usednew + ntoappend > totalnew) { + size_t bigger = totalnew << 1; + if ((bigger >> 1) != totalnew) { /* overflow */ + PyErr_NoMemory(); + goto Done; + } + if (_PyBytes_Resize(&newfmt, bigger) < 0) + goto Done; + totalnew = bigger; + pnew = PyBytes_AsString(newfmt) + usednew; + } + memcpy(pnew, ptoappend, ntoappend); + pnew += ntoappend; + usednew += ntoappend; + assert(usednew <= totalnew); + } /* end while() */ + + if (_PyBytes_Resize(&newfmt, usednew) < 0) + goto Done; + { + PyObject *format; + PyObject *time = PyImport_ImportModuleNoBlock("time"); + if (time == NULL) + goto Done; + format = PyUnicode_FromString(PyBytes_AS_STRING(newfmt)); + if (format != NULL) { + result = PyObject_CallMethod(time, "strftime", "OO", + format, timetuple); + Py_DECREF(format); + } + Py_DECREF(time); + } Done: - Py_XDECREF(freplacement); - Py_XDECREF(zreplacement); - Py_XDECREF(Zreplacement); - Py_XDECREF(newfmt); - return result; + Py_XDECREF(freplacement); + Py_XDECREF(zreplacement); + Py_XDECREF(Zreplacement); + Py_XDECREF(newfmt); + return result; } /* --------------------------------------------------------------------------- @@ -1390,14 +1390,14 @@ static PyObject * time_time(void) { - PyObject *result = NULL; - PyObject *time = PyImport_ImportModuleNoBlock("time"); + PyObject *result = NULL; + PyObject *time = PyImport_ImportModuleNoBlock("time"); - if (time != NULL) { - result = PyObject_CallMethod(time, "time", "()"); - Py_DECREF(time); - } - return result; + if (time != NULL) { + result = PyObject_CallMethod(time, "time", "()"); + Py_DECREF(time); + } + return result; } /* Build a time.struct_time. The weekday and day number are automatically @@ -1406,21 +1406,21 @@ static PyObject * build_struct_time(int y, int m, int d, int hh, int mm, int ss, int dstflag) { - PyObject *time; - PyObject *result = NULL; + PyObject *time; + PyObject *result = NULL; - time = PyImport_ImportModuleNoBlock("time"); - if (time != NULL) { - result = PyObject_CallMethod(time, "struct_time", - "((iiiiiiiii))", - y, m, d, - hh, mm, ss, - weekday(y, m, d), - days_before_month(y, m) + d, - dstflag); - Py_DECREF(time); - } - return result; + time = PyImport_ImportModuleNoBlock("time"); + if (time != NULL) { + result = PyObject_CallMethod(time, "struct_time", + "((iiiiiiiii))", + y, m, d, + hh, mm, ss, + weekday(y, m, d), + days_before_month(y, m) + d, + dstflag); + Py_DECREF(time); + } + return result; } /* --------------------------------------------------------------------------- @@ -1434,33 +1434,33 @@ static PyObject * diff_to_bool(int diff, int op) { - PyObject *result; - int istrue; + PyObject *result; + int istrue; - switch (op) { - case Py_EQ: istrue = diff == 0; break; - case Py_NE: istrue = diff != 0; break; - case Py_LE: istrue = diff <= 0; break; - case Py_GE: istrue = diff >= 0; break; - case Py_LT: istrue = diff < 0; break; - case Py_GT: istrue = diff > 0; break; - default: - assert(! "op unknown"); - istrue = 0; /* To shut up compiler */ - } - result = istrue ? Py_True : Py_False; - Py_INCREF(result); - return result; + switch (op) { + case Py_EQ: istrue = diff == 0; break; + case Py_NE: istrue = diff != 0; break; + case Py_LE: istrue = diff <= 0; break; + case Py_GE: istrue = diff >= 0; break; + case Py_LT: istrue = diff < 0; break; + case Py_GT: istrue = diff > 0; break; + default: + assert(! "op unknown"); + istrue = 0; /* To shut up compiler */ + } + result = istrue ? Py_True : Py_False; + Py_INCREF(result); + return result; } /* Raises a "can't compare" TypeError and returns NULL. */ static PyObject * cmperror(PyObject *a, PyObject *b) { - PyErr_Format(PyExc_TypeError, - "can't compare %s to %s", - Py_TYPE(a)->tp_name, Py_TYPE(b)->tp_name); - return NULL; + PyErr_Format(PyExc_TypeError, + "can't compare %s to %s", + Py_TYPE(a)->tp_name, Py_TYPE(b)->tp_name); + return NULL; } /* --------------------------------------------------------------------------- @@ -1468,13 +1468,13 @@ */ /* Conversion factors. */ -static PyObject *us_per_us = NULL; /* 1 */ -static PyObject *us_per_ms = NULL; /* 1000 */ -static PyObject *us_per_second = NULL; /* 1000000 */ -static PyObject *us_per_minute = NULL; /* 1e6 * 60 as Python int */ -static PyObject *us_per_hour = NULL; /* 1e6 * 3600 as Python long */ -static PyObject *us_per_day = NULL; /* 1e6 * 3600 * 24 as Python long */ -static PyObject *us_per_week = NULL; /* 1e6*3600*24*7 as Python long */ +static PyObject *us_per_us = NULL; /* 1 */ +static PyObject *us_per_ms = NULL; /* 1000 */ +static PyObject *us_per_second = NULL; /* 1000000 */ +static PyObject *us_per_minute = NULL; /* 1e6 * 60 as Python int */ +static PyObject *us_per_hour = NULL; /* 1e6 * 3600 as Python long */ +static PyObject *us_per_day = NULL; /* 1e6 * 3600 * 24 as Python long */ +static PyObject *us_per_week = NULL; /* 1e6*3600*24*7 as Python long */ static PyObject *seconds_per_day = NULL; /* 3600*24 as Python int */ /* --------------------------------------------------------------------------- @@ -1486,7 +1486,7 @@ */ /* Convert a timedelta to a number of us, - * (24*3600*self.days + self.seconds)*1000000 + self.microseconds + * (24*3600*self.days + self.seconds)*1000000 + self.microseconds * as a Python int or long. * Doing mixed-radix arithmetic by hand instead is excruciating in C, * due to ubiquitous overflow possibilities. @@ -1494,49 +1494,49 @@ static PyObject * delta_to_microseconds(PyDateTime_Delta *self) { - PyObject *x1 = NULL; - PyObject *x2 = NULL; - PyObject *x3 = NULL; - PyObject *result = NULL; - - x1 = PyLong_FromLong(GET_TD_DAYS(self)); - if (x1 == NULL) - goto Done; - x2 = PyNumber_Multiply(x1, seconds_per_day); /* days in seconds */ - if (x2 == NULL) - goto Done; - Py_DECREF(x1); - x1 = NULL; - - /* x2 has days in seconds */ - x1 = PyLong_FromLong(GET_TD_SECONDS(self)); /* seconds */ - if (x1 == NULL) - goto Done; - x3 = PyNumber_Add(x1, x2); /* days and seconds in seconds */ - if (x3 == NULL) - goto Done; - Py_DECREF(x1); - Py_DECREF(x2); - x1 = x2 = NULL; - - /* x3 has days+seconds in seconds */ - x1 = PyNumber_Multiply(x3, us_per_second); /* us */ - if (x1 == NULL) - goto Done; - Py_DECREF(x3); - x3 = NULL; - - /* x1 has days+seconds in us */ - x2 = PyLong_FromLong(GET_TD_MICROSECONDS(self)); - if (x2 == NULL) - goto Done; - result = PyNumber_Add(x1, x2); + PyObject *x1 = NULL; + PyObject *x2 = NULL; + PyObject *x3 = NULL; + PyObject *result = NULL; + + x1 = PyLong_FromLong(GET_TD_DAYS(self)); + if (x1 == NULL) + goto Done; + x2 = PyNumber_Multiply(x1, seconds_per_day); /* days in seconds */ + if (x2 == NULL) + goto Done; + Py_DECREF(x1); + x1 = NULL; + + /* x2 has days in seconds */ + x1 = PyLong_FromLong(GET_TD_SECONDS(self)); /* seconds */ + if (x1 == NULL) + goto Done; + x3 = PyNumber_Add(x1, x2); /* days and seconds in seconds */ + if (x3 == NULL) + goto Done; + Py_DECREF(x1); + Py_DECREF(x2); + x1 = x2 = NULL; + + /* x3 has days+seconds in seconds */ + x1 = PyNumber_Multiply(x3, us_per_second); /* us */ + if (x1 == NULL) + goto Done; + Py_DECREF(x3); + x3 = NULL; + + /* x1 has days+seconds in us */ + x2 = PyLong_FromLong(GET_TD_MICROSECONDS(self)); + if (x2 == NULL) + goto Done; + result = PyNumber_Add(x1, x2); Done: - Py_XDECREF(x1); - Py_XDECREF(x2); - Py_XDECREF(x3); - return result; + Py_XDECREF(x1); + Py_XDECREF(x2); + Py_XDECREF(x3); + return result; } /* Convert a number of us (as a Python int or long) to a timedelta. @@ -1544,270 +1544,270 @@ static PyObject * microseconds_to_delta_ex(PyObject *pyus, PyTypeObject *type) { - int us; - int s; - int d; - long temp; - - PyObject *tuple = NULL; - PyObject *num = NULL; - PyObject *result = NULL; - - tuple = PyNumber_Divmod(pyus, us_per_second); - if (tuple == NULL) - goto Done; - - num = PyTuple_GetItem(tuple, 1); /* us */ - if (num == NULL) - goto Done; - temp = PyLong_AsLong(num); - num = NULL; - if (temp == -1 && PyErr_Occurred()) - goto Done; - assert(0 <= temp && temp < 1000000); - us = (int)temp; - if (us < 0) { - /* The divisor was positive, so this must be an error. */ - assert(PyErr_Occurred()); - goto Done; - } - - num = PyTuple_GetItem(tuple, 0); /* leftover seconds */ - if (num == NULL) - goto Done; - Py_INCREF(num); - Py_DECREF(tuple); - - tuple = PyNumber_Divmod(num, seconds_per_day); - if (tuple == NULL) - goto Done; - Py_DECREF(num); - - num = PyTuple_GetItem(tuple, 1); /* seconds */ - if (num == NULL) - goto Done; - temp = PyLong_AsLong(num); - num = NULL; - if (temp == -1 && PyErr_Occurred()) - goto Done; - assert(0 <= temp && temp < 24*3600); - s = (int)temp; - - if (s < 0) { - /* The divisor was positive, so this must be an error. */ - assert(PyErr_Occurred()); - goto Done; - } - - num = PyTuple_GetItem(tuple, 0); /* leftover days */ - if (num == NULL) - goto Done; - Py_INCREF(num); - temp = PyLong_AsLong(num); - if (temp == -1 && PyErr_Occurred()) - goto Done; - d = (int)temp; - if ((long)d != temp) { - PyErr_SetString(PyExc_OverflowError, "normalized days too " - "large to fit in a C int"); - goto Done; - } - result = new_delta_ex(d, s, us, 0, type); + int us; + int s; + int d; + long temp; + + PyObject *tuple = NULL; + PyObject *num = NULL; + PyObject *result = NULL; + + tuple = PyNumber_Divmod(pyus, us_per_second); + if (tuple == NULL) + goto Done; + + num = PyTuple_GetItem(tuple, 1); /* us */ + if (num == NULL) + goto Done; + temp = PyLong_AsLong(num); + num = NULL; + if (temp == -1 && PyErr_Occurred()) + goto Done; + assert(0 <= temp && temp < 1000000); + us = (int)temp; + if (us < 0) { + /* The divisor was positive, so this must be an error. */ + assert(PyErr_Occurred()); + goto Done; + } + + num = PyTuple_GetItem(tuple, 0); /* leftover seconds */ + if (num == NULL) + goto Done; + Py_INCREF(num); + Py_DECREF(tuple); + + tuple = PyNumber_Divmod(num, seconds_per_day); + if (tuple == NULL) + goto Done; + Py_DECREF(num); + + num = PyTuple_GetItem(tuple, 1); /* seconds */ + if (num == NULL) + goto Done; + temp = PyLong_AsLong(num); + num = NULL; + if (temp == -1 && PyErr_Occurred()) + goto Done; + assert(0 <= temp && temp < 24*3600); + s = (int)temp; + + if (s < 0) { + /* The divisor was positive, so this must be an error. */ + assert(PyErr_Occurred()); + goto Done; + } + + num = PyTuple_GetItem(tuple, 0); /* leftover days */ + if (num == NULL) + goto Done; + Py_INCREF(num); + temp = PyLong_AsLong(num); + if (temp == -1 && PyErr_Occurred()) + goto Done; + d = (int)temp; + if ((long)d != temp) { + PyErr_SetString(PyExc_OverflowError, "normalized days too " + "large to fit in a C int"); + goto Done; + } + result = new_delta_ex(d, s, us, 0, type); Done: - Py_XDECREF(tuple); - Py_XDECREF(num); - return result; + Py_XDECREF(tuple); + Py_XDECREF(num); + return result; } -#define microseconds_to_delta(pymicros) \ - microseconds_to_delta_ex(pymicros, &PyDateTime_DeltaType) +#define microseconds_to_delta(pymicros) \ + microseconds_to_delta_ex(pymicros, &PyDateTime_DeltaType) static PyObject * multiply_int_timedelta(PyObject *intobj, PyDateTime_Delta *delta) { - PyObject *pyus_in; - PyObject *pyus_out; - PyObject *result; - - pyus_in = delta_to_microseconds(delta); - if (pyus_in == NULL) - return NULL; - - pyus_out = PyNumber_Multiply(pyus_in, intobj); - Py_DECREF(pyus_in); - if (pyus_out == NULL) - return NULL; - - result = microseconds_to_delta(pyus_out); - Py_DECREF(pyus_out); - return result; + PyObject *pyus_in; + PyObject *pyus_out; + PyObject *result; + + pyus_in = delta_to_microseconds(delta); + if (pyus_in == NULL) + return NULL; + + pyus_out = PyNumber_Multiply(pyus_in, intobj); + Py_DECREF(pyus_in); + if (pyus_out == NULL) + return NULL; + + result = microseconds_to_delta(pyus_out); + Py_DECREF(pyus_out); + return result; } static PyObject * divide_timedelta_int(PyDateTime_Delta *delta, PyObject *intobj) { - PyObject *pyus_in; - PyObject *pyus_out; - PyObject *result; - - pyus_in = delta_to_microseconds(delta); - if (pyus_in == NULL) - return NULL; - - pyus_out = PyNumber_FloorDivide(pyus_in, intobj); - Py_DECREF(pyus_in); - if (pyus_out == NULL) - return NULL; - - result = microseconds_to_delta(pyus_out); - Py_DECREF(pyus_out); - return result; + PyObject *pyus_in; + PyObject *pyus_out; + PyObject *result; + + pyus_in = delta_to_microseconds(delta); + if (pyus_in == NULL) + return NULL; + + pyus_out = PyNumber_FloorDivide(pyus_in, intobj); + Py_DECREF(pyus_in); + if (pyus_out == NULL) + return NULL; + + result = microseconds_to_delta(pyus_out); + Py_DECREF(pyus_out); + return result; } static PyObject * divide_timedelta_timedelta(PyDateTime_Delta *left, PyDateTime_Delta *right) { - PyObject *pyus_left; - PyObject *pyus_right; - PyObject *result; - - pyus_left = delta_to_microseconds(left); - if (pyus_left == NULL) - return NULL; - - pyus_right = delta_to_microseconds(right); - if (pyus_right == NULL) { - Py_DECREF(pyus_left); - return NULL; - } - - result = PyNumber_FloorDivide(pyus_left, pyus_right); - Py_DECREF(pyus_left); - Py_DECREF(pyus_right); - return result; + PyObject *pyus_left; + PyObject *pyus_right; + PyObject *result; + + pyus_left = delta_to_microseconds(left); + if (pyus_left == NULL) + return NULL; + + pyus_right = delta_to_microseconds(right); + if (pyus_right == NULL) { + Py_DECREF(pyus_left); + return NULL; + } + + result = PyNumber_FloorDivide(pyus_left, pyus_right); + Py_DECREF(pyus_left); + Py_DECREF(pyus_right); + return result; } static PyObject * truedivide_timedelta_timedelta(PyDateTime_Delta *left, PyDateTime_Delta *right) { - PyObject *pyus_left; - PyObject *pyus_right; - PyObject *result; - - pyus_left = delta_to_microseconds(left); - if (pyus_left == NULL) - return NULL; - - pyus_right = delta_to_microseconds(right); - if (pyus_right == NULL) { - Py_DECREF(pyus_left); - return NULL; - } - - result = PyNumber_TrueDivide(pyus_left, pyus_right); - Py_DECREF(pyus_left); - Py_DECREF(pyus_right); - return result; + PyObject *pyus_left; + PyObject *pyus_right; + PyObject *result; + + pyus_left = delta_to_microseconds(left); + if (pyus_left == NULL) + return NULL; + + pyus_right = delta_to_microseconds(right); + if (pyus_right == NULL) { + Py_DECREF(pyus_left); + return NULL; + } + + result = PyNumber_TrueDivide(pyus_left, pyus_right); + Py_DECREF(pyus_left); + Py_DECREF(pyus_right); + return result; } static PyObject * delta_add(PyObject *left, PyObject *right) { - PyObject *result = Py_NotImplemented; + PyObject *result = Py_NotImplemented; - if (PyDelta_Check(left) && PyDelta_Check(right)) { - /* delta + delta */ - /* The C-level additions can't overflow because of the - * invariant bounds. - */ - int days = GET_TD_DAYS(left) + GET_TD_DAYS(right); - int seconds = GET_TD_SECONDS(left) + GET_TD_SECONDS(right); - int microseconds = GET_TD_MICROSECONDS(left) + - GET_TD_MICROSECONDS(right); - result = new_delta(days, seconds, microseconds, 1); - } - - if (result == Py_NotImplemented) - Py_INCREF(result); - return result; + if (PyDelta_Check(left) && PyDelta_Check(right)) { + /* delta + delta */ + /* The C-level additions can't overflow because of the + * invariant bounds. + */ + int days = GET_TD_DAYS(left) + GET_TD_DAYS(right); + int seconds = GET_TD_SECONDS(left) + GET_TD_SECONDS(right); + int microseconds = GET_TD_MICROSECONDS(left) + + GET_TD_MICROSECONDS(right); + result = new_delta(days, seconds, microseconds, 1); + } + + if (result == Py_NotImplemented) + Py_INCREF(result); + return result; } static PyObject * delta_negative(PyDateTime_Delta *self) { - return new_delta(-GET_TD_DAYS(self), - -GET_TD_SECONDS(self), - -GET_TD_MICROSECONDS(self), - 1); + return new_delta(-GET_TD_DAYS(self), + -GET_TD_SECONDS(self), + -GET_TD_MICROSECONDS(self), + 1); } static PyObject * delta_positive(PyDateTime_Delta *self) { - /* Could optimize this (by returning self) if this isn't a - * subclass -- but who uses unary + ? Approximately nobody. - */ - return new_delta(GET_TD_DAYS(self), - GET_TD_SECONDS(self), - GET_TD_MICROSECONDS(self), - 0); + /* Could optimize this (by returning self) if this isn't a + * subclass -- but who uses unary + ? Approximately nobody. + */ + return new_delta(GET_TD_DAYS(self), + GET_TD_SECONDS(self), + GET_TD_MICROSECONDS(self), + 0); } static PyObject * delta_abs(PyDateTime_Delta *self) { - PyObject *result; + PyObject *result; - assert(GET_TD_MICROSECONDS(self) >= 0); - assert(GET_TD_SECONDS(self) >= 0); + assert(GET_TD_MICROSECONDS(self) >= 0); + assert(GET_TD_SECONDS(self) >= 0); - if (GET_TD_DAYS(self) < 0) - result = delta_negative(self); - else - result = delta_positive(self); + if (GET_TD_DAYS(self) < 0) + result = delta_negative(self); + else + result = delta_positive(self); - return result; + return result; } static PyObject * delta_subtract(PyObject *left, PyObject *right) { - PyObject *result = Py_NotImplemented; + PyObject *result = Py_NotImplemented; - if (PyDelta_Check(left) && PyDelta_Check(right)) { - /* delta - delta */ - PyObject *minus_right = PyNumber_Negative(right); - if (minus_right) { - result = delta_add(left, minus_right); - Py_DECREF(minus_right); - } - else - result = NULL; - } - - if (result == Py_NotImplemented) - Py_INCREF(result); - return result; + if (PyDelta_Check(left) && PyDelta_Check(right)) { + /* delta - delta */ + PyObject *minus_right = PyNumber_Negative(right); + if (minus_right) { + result = delta_add(left, minus_right); + Py_DECREF(minus_right); + } + else + result = NULL; + } + + if (result == Py_NotImplemented) + Py_INCREF(result); + return result; } static PyObject * delta_richcompare(PyObject *self, PyObject *other, int op) { - if (PyDelta_Check(other)) { - int diff = GET_TD_DAYS(self) - GET_TD_DAYS(other); - if (diff == 0) { - diff = GET_TD_SECONDS(self) - GET_TD_SECONDS(other); - if (diff == 0) - diff = GET_TD_MICROSECONDS(self) - - GET_TD_MICROSECONDS(other); - } - return diff_to_bool(diff, op); - } - else { - Py_INCREF(Py_NotImplemented); - return Py_NotImplemented; - } + if (PyDelta_Check(other)) { + int diff = GET_TD_DAYS(self) - GET_TD_DAYS(other); + if (diff == 0) { + diff = GET_TD_SECONDS(self) - GET_TD_SECONDS(other); + if (diff == 0) + diff = GET_TD_MICROSECONDS(self) - + GET_TD_MICROSECONDS(other); + } + return diff_to_bool(diff, op); + } + else { + Py_INCREF(Py_NotImplemented); + return Py_NotImplemented; + } } static PyObject *delta_getstate(PyDateTime_Delta *self); @@ -1815,152 +1815,152 @@ static long delta_hash(PyDateTime_Delta *self) { - if (self->hashcode == -1) { - PyObject *temp = delta_getstate(self); - if (temp != NULL) { - self->hashcode = PyObject_Hash(temp); - Py_DECREF(temp); - } - } - return self->hashcode; + if (self->hashcode == -1) { + PyObject *temp = delta_getstate(self); + if (temp != NULL) { + self->hashcode = PyObject_Hash(temp); + Py_DECREF(temp); + } + } + return self->hashcode; } static PyObject * delta_multiply(PyObject *left, PyObject *right) { - PyObject *result = Py_NotImplemented; + PyObject *result = Py_NotImplemented; - if (PyDelta_Check(left)) { - /* delta * ??? */ - if (PyLong_Check(right)) - result = multiply_int_timedelta(right, - (PyDateTime_Delta *) left); - } - else if (PyLong_Check(left)) - result = multiply_int_timedelta(left, - (PyDateTime_Delta *) right); - - if (result == Py_NotImplemented) - Py_INCREF(result); - return result; + if (PyDelta_Check(left)) { + /* delta * ??? */ + if (PyLong_Check(right)) + result = multiply_int_timedelta(right, + (PyDateTime_Delta *) left); + } + else if (PyLong_Check(left)) + result = multiply_int_timedelta(left, + (PyDateTime_Delta *) right); + + if (result == Py_NotImplemented) + Py_INCREF(result); + return result; } static PyObject * delta_divide(PyObject *left, PyObject *right) { - PyObject *result = Py_NotImplemented; + PyObject *result = Py_NotImplemented; - if (PyDelta_Check(left)) { - /* delta * ??? */ - if (PyLong_Check(right)) - result = divide_timedelta_int( - (PyDateTime_Delta *)left, - right); - else if (PyDelta_Check(right)) - result = divide_timedelta_timedelta( - (PyDateTime_Delta *)left, - (PyDateTime_Delta *)right); - } - - if (result == Py_NotImplemented) - Py_INCREF(result); - return result; + if (PyDelta_Check(left)) { + /* delta * ??? */ + if (PyLong_Check(right)) + result = divide_timedelta_int( + (PyDateTime_Delta *)left, + right); + else if (PyDelta_Check(right)) + result = divide_timedelta_timedelta( + (PyDateTime_Delta *)left, + (PyDateTime_Delta *)right); + } + + if (result == Py_NotImplemented) + Py_INCREF(result); + return result; } static PyObject * delta_truedivide(PyObject *left, PyObject *right) { - PyObject *result = Py_NotImplemented; + PyObject *result = Py_NotImplemented; - if (PyDelta_Check(left)) { - if (PyDelta_Check(right)) - result = truedivide_timedelta_timedelta( - (PyDateTime_Delta *)left, - (PyDateTime_Delta *)right); - } - - if (result == Py_NotImplemented) - Py_INCREF(result); - return result; + if (PyDelta_Check(left)) { + if (PyDelta_Check(right)) + result = truedivide_timedelta_timedelta( + (PyDateTime_Delta *)left, + (PyDateTime_Delta *)right); + } + + if (result == Py_NotImplemented) + Py_INCREF(result); + return result; } static PyObject * delta_remainder(PyObject *left, PyObject *right) { - PyObject *pyus_left; - PyObject *pyus_right; - PyObject *pyus_remainder; - PyObject *remainder; - - if (!PyDelta_Check(left) || !PyDelta_Check(right)) { - Py_INCREF(Py_NotImplemented); - return Py_NotImplemented; - } - - pyus_left = delta_to_microseconds((PyDateTime_Delta *)left); - if (pyus_left == NULL) - return NULL; - - pyus_right = delta_to_microseconds((PyDateTime_Delta *)right); - if (pyus_right == NULL) { - Py_DECREF(pyus_left); - return NULL; - } - - pyus_remainder = PyNumber_Remainder(pyus_left, pyus_right); - Py_DECREF(pyus_left); - Py_DECREF(pyus_right); - if (pyus_remainder == NULL) - return NULL; - - remainder = microseconds_to_delta(pyus_remainder); - Py_DECREF(pyus_remainder); - if (remainder == NULL) - return NULL; + PyObject *pyus_left; + PyObject *pyus_right; + PyObject *pyus_remainder; + PyObject *remainder; + + if (!PyDelta_Check(left) || !PyDelta_Check(right)) { + Py_INCREF(Py_NotImplemented); + return Py_NotImplemented; + } + + pyus_left = delta_to_microseconds((PyDateTime_Delta *)left); + if (pyus_left == NULL) + return NULL; + + pyus_right = delta_to_microseconds((PyDateTime_Delta *)right); + if (pyus_right == NULL) { + Py_DECREF(pyus_left); + return NULL; + } + + pyus_remainder = PyNumber_Remainder(pyus_left, pyus_right); + Py_DECREF(pyus_left); + Py_DECREF(pyus_right); + if (pyus_remainder == NULL) + return NULL; + + remainder = microseconds_to_delta(pyus_remainder); + Py_DECREF(pyus_remainder); + if (remainder == NULL) + return NULL; - return remainder; + return remainder; } static PyObject * delta_divmod(PyObject *left, PyObject *right) { - PyObject *pyus_left; - PyObject *pyus_right; - PyObject *divmod; - PyObject *delta; - PyObject *result; - - if (!PyDelta_Check(left) || !PyDelta_Check(right)) { - Py_INCREF(Py_NotImplemented); - return Py_NotImplemented; - } - - pyus_left = delta_to_microseconds((PyDateTime_Delta *)left); - if (pyus_left == NULL) - return NULL; - - pyus_right = delta_to_microseconds((PyDateTime_Delta *)right); - if (pyus_right == NULL) { - Py_DECREF(pyus_left); - return NULL; - } - - divmod = PyNumber_Divmod(pyus_left, pyus_right); - Py_DECREF(pyus_left); - Py_DECREF(pyus_right); - if (divmod == NULL) - return NULL; - - assert(PyTuple_Size(divmod) == 2); - delta = microseconds_to_delta(PyTuple_GET_ITEM(divmod, 1)); - if (delta == NULL) { - Py_DECREF(divmod); - return NULL; - } - result = PyTuple_Pack(2, PyTuple_GET_ITEM(divmod, 0), delta); - Py_DECREF(delta); - Py_DECREF(divmod); - return result; + PyObject *pyus_left; + PyObject *pyus_right; + PyObject *divmod; + PyObject *delta; + PyObject *result; + + if (!PyDelta_Check(left) || !PyDelta_Check(right)) { + Py_INCREF(Py_NotImplemented); + return Py_NotImplemented; + } + + pyus_left = delta_to_microseconds((PyDateTime_Delta *)left); + if (pyus_left == NULL) + return NULL; + + pyus_right = delta_to_microseconds((PyDateTime_Delta *)right); + if (pyus_right == NULL) { + Py_DECREF(pyus_left); + return NULL; + } + + divmod = PyNumber_Divmod(pyus_left, pyus_right); + Py_DECREF(pyus_left); + Py_DECREF(pyus_right); + if (divmod == NULL) + return NULL; + + assert(PyTuple_Size(divmod) == 2); + delta = microseconds_to_delta(PyTuple_GET_ITEM(divmod, 1)); + if (delta == NULL) { + Py_DECREF(divmod); + return NULL; + } + result = PyTuple_Pack(2, PyTuple_GET_ITEM(divmod, 0), delta); + Py_DECREF(delta); + Py_DECREF(divmod); + return result; } /* Fold in the value of the tag ("seconds", "weeks", etc) component of a @@ -1976,166 +1976,166 @@ accum(const char* tag, PyObject *sofar, PyObject *num, PyObject *factor, double *leftover) { - PyObject *prod; - PyObject *sum; + PyObject *prod; + PyObject *sum; - assert(num != NULL); + assert(num != NULL); - if (PyLong_Check(num)) { - prod = PyNumber_Multiply(num, factor); - if (prod == NULL) - return NULL; - sum = PyNumber_Add(sofar, prod); - Py_DECREF(prod); - return sum; - } - - if (PyFloat_Check(num)) { - double dnum; - double fracpart; - double intpart; - PyObject *x; - PyObject *y; - - /* The Plan: decompose num into an integer part and a - * fractional part, num = intpart + fracpart. - * Then num * factor == - * intpart * factor + fracpart * factor - * and the LHS can be computed exactly in long arithmetic. - * The RHS is again broken into an int part and frac part. - * and the frac part is added into *leftover. - */ - dnum = PyFloat_AsDouble(num); - if (dnum == -1.0 && PyErr_Occurred()) - return NULL; - fracpart = modf(dnum, &intpart); - x = PyLong_FromDouble(intpart); - if (x == NULL) - return NULL; - - prod = PyNumber_Multiply(x, factor); - Py_DECREF(x); - if (prod == NULL) - return NULL; - - sum = PyNumber_Add(sofar, prod); - Py_DECREF(prod); - if (sum == NULL) - return NULL; - - if (fracpart == 0.0) - return sum; - /* So far we've lost no information. Dealing with the - * fractional part requires float arithmetic, and may - * lose a little info. - */ - assert(PyLong_Check(factor)); - dnum = PyLong_AsDouble(factor); - - dnum *= fracpart; - fracpart = modf(dnum, &intpart); - x = PyLong_FromDouble(intpart); - if (x == NULL) { - Py_DECREF(sum); - return NULL; - } - - y = PyNumber_Add(sum, x); - Py_DECREF(sum); - Py_DECREF(x); - *leftover += fracpart; - return y; - } - - PyErr_Format(PyExc_TypeError, - "unsupported type for timedelta %s component: %s", - tag, Py_TYPE(num)->tp_name); - return NULL; + if (PyLong_Check(num)) { + prod = PyNumber_Multiply(num, factor); + if (prod == NULL) + return NULL; + sum = PyNumber_Add(sofar, prod); + Py_DECREF(prod); + return sum; + } + + if (PyFloat_Check(num)) { + double dnum; + double fracpart; + double intpart; + PyObject *x; + PyObject *y; + + /* The Plan: decompose num into an integer part and a + * fractional part, num = intpart + fracpart. + * Then num * factor == + * intpart * factor + fracpart * factor + * and the LHS can be computed exactly in long arithmetic. + * The RHS is again broken into an int part and frac part. + * and the frac part is added into *leftover. + */ + dnum = PyFloat_AsDouble(num); + if (dnum == -1.0 && PyErr_Occurred()) + return NULL; + fracpart = modf(dnum, &intpart); + x = PyLong_FromDouble(intpart); + if (x == NULL) + return NULL; + + prod = PyNumber_Multiply(x, factor); + Py_DECREF(x); + if (prod == NULL) + return NULL; + + sum = PyNumber_Add(sofar, prod); + Py_DECREF(prod); + if (sum == NULL) + return NULL; + + if (fracpart == 0.0) + return sum; + /* So far we've lost no information. Dealing with the + * fractional part requires float arithmetic, and may + * lose a little info. + */ + assert(PyLong_Check(factor)); + dnum = PyLong_AsDouble(factor); + + dnum *= fracpart; + fracpart = modf(dnum, &intpart); + x = PyLong_FromDouble(intpart); + if (x == NULL) { + Py_DECREF(sum); + return NULL; + } + + y = PyNumber_Add(sum, x); + Py_DECREF(sum); + Py_DECREF(x); + *leftover += fracpart; + return y; + } + + PyErr_Format(PyExc_TypeError, + "unsupported type for timedelta %s component: %s", + tag, Py_TYPE(num)->tp_name); + return NULL; } static PyObject * delta_new(PyTypeObject *type, PyObject *args, PyObject *kw) { - PyObject *self = NULL; + PyObject *self = NULL; - /* Argument objects. */ - PyObject *day = NULL; - PyObject *second = NULL; - PyObject *us = NULL; - PyObject *ms = NULL; - PyObject *minute = NULL; - PyObject *hour = NULL; - PyObject *week = NULL; - - PyObject *x = NULL; /* running sum of microseconds */ - PyObject *y = NULL; /* temp sum of microseconds */ - double leftover_us = 0.0; - - static char *keywords[] = { - "days", "seconds", "microseconds", "milliseconds", - "minutes", "hours", "weeks", NULL - }; - - if (PyArg_ParseTupleAndKeywords(args, kw, "|OOOOOOO:__new__", - keywords, - &day, &second, &us, - &ms, &minute, &hour, &week) == 0) - goto Done; - - x = PyLong_FromLong(0); - if (x == NULL) - goto Done; - -#define CLEANUP \ - Py_DECREF(x); \ - x = y; \ - if (x == NULL) \ - goto Done - - if (us) { - y = accum("microseconds", x, us, us_per_us, &leftover_us); - CLEANUP; - } - if (ms) { - y = accum("milliseconds", x, ms, us_per_ms, &leftover_us); - CLEANUP; - } - if (second) { - y = accum("seconds", x, second, us_per_second, &leftover_us); - CLEANUP; - } - if (minute) { - y = accum("minutes", x, minute, us_per_minute, &leftover_us); - CLEANUP; - } - if (hour) { - y = accum("hours", x, hour, us_per_hour, &leftover_us); - CLEANUP; - } - if (day) { - y = accum("days", x, day, us_per_day, &leftover_us); - CLEANUP; - } - if (week) { - y = accum("weeks", x, week, us_per_week, &leftover_us); - CLEANUP; - } - if (leftover_us) { - /* Round to nearest whole # of us, and add into x. */ - PyObject *temp = PyLong_FromLong(round_to_long(leftover_us)); - if (temp == NULL) { - Py_DECREF(x); - goto Done; - } - y = PyNumber_Add(x, temp); - Py_DECREF(temp); - CLEANUP; - } + /* Argument objects. */ + PyObject *day = NULL; + PyObject *second = NULL; + PyObject *us = NULL; + PyObject *ms = NULL; + PyObject *minute = NULL; + PyObject *hour = NULL; + PyObject *week = NULL; + + PyObject *x = NULL; /* running sum of microseconds */ + PyObject *y = NULL; /* temp sum of microseconds */ + double leftover_us = 0.0; + + static char *keywords[] = { + "days", "seconds", "microseconds", "milliseconds", + "minutes", "hours", "weeks", NULL + }; + + if (PyArg_ParseTupleAndKeywords(args, kw, "|OOOOOOO:__new__", + keywords, + &day, &second, &us, + &ms, &minute, &hour, &week) == 0) + goto Done; + + x = PyLong_FromLong(0); + if (x == NULL) + goto Done; + +#define CLEANUP \ + Py_DECREF(x); \ + x = y; \ + if (x == NULL) \ + goto Done + + if (us) { + y = accum("microseconds", x, us, us_per_us, &leftover_us); + CLEANUP; + } + if (ms) { + y = accum("milliseconds", x, ms, us_per_ms, &leftover_us); + CLEANUP; + } + if (second) { + y = accum("seconds", x, second, us_per_second, &leftover_us); + CLEANUP; + } + if (minute) { + y = accum("minutes", x, minute, us_per_minute, &leftover_us); + CLEANUP; + } + if (hour) { + y = accum("hours", x, hour, us_per_hour, &leftover_us); + CLEANUP; + } + if (day) { + y = accum("days", x, day, us_per_day, &leftover_us); + CLEANUP; + } + if (week) { + y = accum("weeks", x, week, us_per_week, &leftover_us); + CLEANUP; + } + if (leftover_us) { + /* Round to nearest whole # of us, and add into x. */ + PyObject *temp = PyLong_FromLong(round_to_long(leftover_us)); + if (temp == NULL) { + Py_DECREF(x); + goto Done; + } + y = PyNumber_Add(x, temp); + Py_DECREF(temp); + CLEANUP; + } - self = microseconds_to_delta_ex(x, type); - Py_DECREF(x); + self = microseconds_to_delta_ex(x, type); + Py_DECREF(x); Done: - return self; + return self; #undef CLEANUP } @@ -2143,57 +2143,57 @@ static int delta_bool(PyDateTime_Delta *self) { - return (GET_TD_DAYS(self) != 0 - || GET_TD_SECONDS(self) != 0 - || GET_TD_MICROSECONDS(self) != 0); + return (GET_TD_DAYS(self) != 0 + || GET_TD_SECONDS(self) != 0 + || GET_TD_MICROSECONDS(self) != 0); } static PyObject * delta_repr(PyDateTime_Delta *self) { - if (GET_TD_MICROSECONDS(self) != 0) - return PyUnicode_FromFormat("%s(%d, %d, %d)", - Py_TYPE(self)->tp_name, - GET_TD_DAYS(self), - GET_TD_SECONDS(self), - GET_TD_MICROSECONDS(self)); - if (GET_TD_SECONDS(self) != 0) - return PyUnicode_FromFormat("%s(%d, %d)", - Py_TYPE(self)->tp_name, - GET_TD_DAYS(self), - GET_TD_SECONDS(self)); - - return PyUnicode_FromFormat("%s(%d)", - Py_TYPE(self)->tp_name, - GET_TD_DAYS(self)); + if (GET_TD_MICROSECONDS(self) != 0) + return PyUnicode_FromFormat("%s(%d, %d, %d)", + Py_TYPE(self)->tp_name, + GET_TD_DAYS(self), + GET_TD_SECONDS(self), + GET_TD_MICROSECONDS(self)); + if (GET_TD_SECONDS(self) != 0) + return PyUnicode_FromFormat("%s(%d, %d)", + Py_TYPE(self)->tp_name, + GET_TD_DAYS(self), + GET_TD_SECONDS(self)); + + return PyUnicode_FromFormat("%s(%d)", + Py_TYPE(self)->tp_name, + GET_TD_DAYS(self)); } static PyObject * delta_str(PyDateTime_Delta *self) { - int us = GET_TD_MICROSECONDS(self); - int seconds = GET_TD_SECONDS(self); - int minutes = divmod(seconds, 60, &seconds); - int hours = divmod(minutes, 60, &minutes); - int days = GET_TD_DAYS(self); - - if (days) { - if (us) - return PyUnicode_FromFormat("%d day%s, %d:%02d:%02d.%06d", - days, (days == 1 || days == -1) ? "" : "s", - hours, minutes, seconds, us); - else - return PyUnicode_FromFormat("%d day%s, %d:%02d:%02d", - days, (days == 1 || days == -1) ? "" : "s", - hours, minutes, seconds); - } else { - if (us) - return PyUnicode_FromFormat("%d:%02d:%02d.%06d", - hours, minutes, seconds, us); - else - return PyUnicode_FromFormat("%d:%02d:%02d", - hours, minutes, seconds); - } + int us = GET_TD_MICROSECONDS(self); + int seconds = GET_TD_SECONDS(self); + int minutes = divmod(seconds, 60, &seconds); + int hours = divmod(minutes, 60, &minutes); + int days = GET_TD_DAYS(self); + + if (days) { + if (us) + return PyUnicode_FromFormat("%d day%s, %d:%02d:%02d.%06d", + days, (days == 1 || days == -1) ? "" : "s", + hours, minutes, seconds, us); + else + return PyUnicode_FromFormat("%d day%s, %d:%02d:%02d", + days, (days == 1 || days == -1) ? "" : "s", + hours, minutes, seconds); + } else { + if (us) + return PyUnicode_FromFormat("%d:%02d:%02d.%06d", + hours, minutes, seconds, us); + else + return PyUnicode_FromFormat("%d:%02d:%02d", + hours, minutes, seconds); + } } @@ -2203,145 +2203,145 @@ static PyObject * delta_getstate(PyDateTime_Delta *self) { - return Py_BuildValue("iii", GET_TD_DAYS(self), - GET_TD_SECONDS(self), - GET_TD_MICROSECONDS(self)); + return Py_BuildValue("iii", GET_TD_DAYS(self), + GET_TD_SECONDS(self), + GET_TD_MICROSECONDS(self)); } static PyObject * delta_total_seconds(PyObject *self) { - PyObject *total_seconds; - PyObject *total_microseconds; - PyObject *one_million; - - total_microseconds = delta_to_microseconds((PyDateTime_Delta *)self); - if (total_microseconds == NULL) - return NULL; - - one_million = PyLong_FromLong(1000000L); - if (one_million == NULL) { - Py_DECREF(total_microseconds); - return NULL; - } - - total_seconds = PyNumber_TrueDivide(total_microseconds, one_million); - - Py_DECREF(total_microseconds); - Py_DECREF(one_million); - return total_seconds; + PyObject *total_seconds; + PyObject *total_microseconds; + PyObject *one_million; + + total_microseconds = delta_to_microseconds((PyDateTime_Delta *)self); + if (total_microseconds == NULL) + return NULL; + + one_million = PyLong_FromLong(1000000L); + if (one_million == NULL) { + Py_DECREF(total_microseconds); + return NULL; + } + + total_seconds = PyNumber_TrueDivide(total_microseconds, one_million); + + Py_DECREF(total_microseconds); + Py_DECREF(one_million); + return total_seconds; } static PyObject * delta_reduce(PyDateTime_Delta* self) { - return Py_BuildValue("ON", Py_TYPE(self), delta_getstate(self)); + return Py_BuildValue("ON", Py_TYPE(self), delta_getstate(self)); } #define OFFSET(field) offsetof(PyDateTime_Delta, field) static PyMemberDef delta_members[] = { - {"days", T_INT, OFFSET(days), READONLY, - PyDoc_STR("Number of days.")}, + {"days", T_INT, OFFSET(days), READONLY, + PyDoc_STR("Number of days.")}, - {"seconds", T_INT, OFFSET(seconds), READONLY, - PyDoc_STR("Number of seconds (>= 0 and less than 1 day).")}, + {"seconds", T_INT, OFFSET(seconds), READONLY, + PyDoc_STR("Number of seconds (>= 0 and less than 1 day).")}, - {"microseconds", T_INT, OFFSET(microseconds), READONLY, - PyDoc_STR("Number of microseconds (>= 0 and less than 1 second).")}, - {NULL} + {"microseconds", T_INT, OFFSET(microseconds), READONLY, + PyDoc_STR("Number of microseconds (>= 0 and less than 1 second).")}, + {NULL} }; static PyMethodDef delta_methods[] = { - {"total_seconds", (PyCFunction)delta_total_seconds, METH_NOARGS, - PyDoc_STR("Total seconds in the duration.")}, + {"total_seconds", (PyCFunction)delta_total_seconds, METH_NOARGS, + PyDoc_STR("Total seconds in the duration.")}, - {"__reduce__", (PyCFunction)delta_reduce, METH_NOARGS, - PyDoc_STR("__reduce__() -> (cls, state)")}, + {"__reduce__", (PyCFunction)delta_reduce, METH_NOARGS, + PyDoc_STR("__reduce__() -> (cls, state)")}, - {NULL, NULL}, + {NULL, NULL}, }; static char delta_doc[] = PyDoc_STR("Difference between two datetime values."); static PyNumberMethods delta_as_number = { - delta_add, /* nb_add */ - delta_subtract, /* nb_subtract */ - delta_multiply, /* nb_multiply */ - delta_remainder, /* nb_remainder */ - delta_divmod, /* nb_divmod */ - 0, /* nb_power */ - (unaryfunc)delta_negative, /* nb_negative */ - (unaryfunc)delta_positive, /* nb_positive */ - (unaryfunc)delta_abs, /* nb_absolute */ - (inquiry)delta_bool, /* nb_bool */ - 0, /*nb_invert*/ - 0, /*nb_lshift*/ - 0, /*nb_rshift*/ - 0, /*nb_and*/ - 0, /*nb_xor*/ - 0, /*nb_or*/ - 0, /*nb_int*/ - 0, /*nb_reserved*/ - 0, /*nb_float*/ - 0, /*nb_inplace_add*/ - 0, /*nb_inplace_subtract*/ - 0, /*nb_inplace_multiply*/ - 0, /*nb_inplace_remainder*/ - 0, /*nb_inplace_power*/ - 0, /*nb_inplace_lshift*/ - 0, /*nb_inplace_rshift*/ - 0, /*nb_inplace_and*/ - 0, /*nb_inplace_xor*/ - 0, /*nb_inplace_or*/ - delta_divide, /* nb_floor_divide */ - delta_truedivide, /* nb_true_divide */ - 0, /* nb_inplace_floor_divide */ - 0, /* nb_inplace_true_divide */ + delta_add, /* nb_add */ + delta_subtract, /* nb_subtract */ + delta_multiply, /* nb_multiply */ + delta_remainder, /* nb_remainder */ + delta_divmod, /* nb_divmod */ + 0, /* nb_power */ + (unaryfunc)delta_negative, /* nb_negative */ + (unaryfunc)delta_positive, /* nb_positive */ + (unaryfunc)delta_abs, /* nb_absolute */ + (inquiry)delta_bool, /* nb_bool */ + 0, /*nb_invert*/ + 0, /*nb_lshift*/ + 0, /*nb_rshift*/ + 0, /*nb_and*/ + 0, /*nb_xor*/ + 0, /*nb_or*/ + 0, /*nb_int*/ + 0, /*nb_reserved*/ + 0, /*nb_float*/ + 0, /*nb_inplace_add*/ + 0, /*nb_inplace_subtract*/ + 0, /*nb_inplace_multiply*/ + 0, /*nb_inplace_remainder*/ + 0, /*nb_inplace_power*/ + 0, /*nb_inplace_lshift*/ + 0, /*nb_inplace_rshift*/ + 0, /*nb_inplace_and*/ + 0, /*nb_inplace_xor*/ + 0, /*nb_inplace_or*/ + delta_divide, /* nb_floor_divide */ + delta_truedivide, /* nb_true_divide */ + 0, /* nb_inplace_floor_divide */ + 0, /* nb_inplace_true_divide */ }; static PyTypeObject PyDateTime_DeltaType = { - PyVarObject_HEAD_INIT(NULL, 0) - "datetime.timedelta", /* tp_name */ - sizeof(PyDateTime_Delta), /* tp_basicsize */ - 0, /* tp_itemsize */ - 0, /* tp_dealloc */ - 0, /* tp_print */ - 0, /* tp_getattr */ - 0, /* tp_setattr */ - 0, /* tp_reserved */ - (reprfunc)delta_repr, /* tp_repr */ - &delta_as_number, /* tp_as_number */ - 0, /* tp_as_sequence */ - 0, /* tp_as_mapping */ - (hashfunc)delta_hash, /* tp_hash */ - 0, /* tp_call */ - (reprfunc)delta_str, /* tp_str */ - PyObject_GenericGetAttr, /* tp_getattro */ - 0, /* tp_setattro */ - 0, /* tp_as_buffer */ - Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */ - delta_doc, /* tp_doc */ - 0, /* tp_traverse */ - 0, /* tp_clear */ - delta_richcompare, /* tp_richcompare */ - 0, /* tp_weaklistoffset */ - 0, /* tp_iter */ - 0, /* tp_iternext */ - delta_methods, /* tp_methods */ - delta_members, /* tp_members */ - 0, /* tp_getset */ - 0, /* tp_base */ - 0, /* tp_dict */ - 0, /* tp_descr_get */ - 0, /* tp_descr_set */ - 0, /* tp_dictoffset */ - 0, /* tp_init */ - 0, /* tp_alloc */ - delta_new, /* tp_new */ - 0, /* tp_free */ + PyVarObject_HEAD_INIT(NULL, 0) + "datetime.timedelta", /* tp_name */ + sizeof(PyDateTime_Delta), /* tp_basicsize */ + 0, /* tp_itemsize */ + 0, /* tp_dealloc */ + 0, /* tp_print */ + 0, /* tp_getattr */ + 0, /* tp_setattr */ + 0, /* tp_reserved */ + (reprfunc)delta_repr, /* tp_repr */ + &delta_as_number, /* tp_as_number */ + 0, /* tp_as_sequence */ + 0, /* tp_as_mapping */ + (hashfunc)delta_hash, /* tp_hash */ + 0, /* tp_call */ + (reprfunc)delta_str, /* tp_str */ + PyObject_GenericGetAttr, /* tp_getattro */ + 0, /* tp_setattro */ + 0, /* tp_as_buffer */ + Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */ + delta_doc, /* tp_doc */ + 0, /* tp_traverse */ + 0, /* tp_clear */ + delta_richcompare, /* tp_richcompare */ + 0, /* tp_weaklistoffset */ + 0, /* tp_iter */ + 0, /* tp_iternext */ + delta_methods, /* tp_methods */ + delta_members, /* tp_members */ + 0, /* tp_getset */ + 0, /* tp_base */ + 0, /* tp_dict */ + 0, /* tp_descr_get */ + 0, /* tp_descr_set */ + 0, /* tp_dictoffset */ + 0, /* tp_init */ + 0, /* tp_alloc */ + delta_new, /* tp_new */ + 0, /* tp_free */ }; /* @@ -2353,26 +2353,26 @@ static PyObject * date_year(PyDateTime_Date *self, void *unused) { - return PyLong_FromLong(GET_YEAR(self)); + return PyLong_FromLong(GET_YEAR(self)); } static PyObject * date_month(PyDateTime_Date *self, void *unused) { - return PyLong_FromLong(GET_MONTH(self)); + return PyLong_FromLong(GET_MONTH(self)); } static PyObject * date_day(PyDateTime_Date *self, void *unused) { - return PyLong_FromLong(GET_DAY(self)); + return PyLong_FromLong(GET_DAY(self)); } static PyGetSetDef date_getset[] = { - {"year", (getter)date_year}, - {"month", (getter)date_month}, - {"day", (getter)date_day}, - {NULL} + {"year", (getter)date_year}, + {"month", (getter)date_month}, + {"day", (getter)date_day}, + {NULL} }; /* Constructors. */ @@ -2382,60 +2382,60 @@ static PyObject * date_new(PyTypeObject *type, PyObject *args, PyObject *kw) { - PyObject *self = NULL; - PyObject *state; - int year; - int month; - int day; - - /* Check for invocation from pickle with __getstate__ state */ - if (PyTuple_GET_SIZE(args) == 1 && - PyBytes_Check(state = PyTuple_GET_ITEM(args, 0)) && - PyBytes_GET_SIZE(state) == _PyDateTime_DATE_DATASIZE && - MONTH_IS_SANE(PyBytes_AS_STRING(state)[2])) - { - PyDateTime_Date *me; - - me = (PyDateTime_Date *) (type->tp_alloc(type, 0)); - if (me != NULL) { - char *pdata = PyBytes_AS_STRING(state); - memcpy(me->data, pdata, _PyDateTime_DATE_DATASIZE); - me->hashcode = -1; - } - return (PyObject *)me; - } - - if (PyArg_ParseTupleAndKeywords(args, kw, "iii", date_kws, - &year, &month, &day)) { - if (check_date_args(year, month, day) < 0) - return NULL; - self = new_date_ex(year, month, day, type); - } - return self; + PyObject *self = NULL; + PyObject *state; + int year; + int month; + int day; + + /* Check for invocation from pickle with __getstate__ state */ + if (PyTuple_GET_SIZE(args) == 1 && + PyBytes_Check(state = PyTuple_GET_ITEM(args, 0)) && + PyBytes_GET_SIZE(state) == _PyDateTime_DATE_DATASIZE && + MONTH_IS_SANE(PyBytes_AS_STRING(state)[2])) + { + PyDateTime_Date *me; + + me = (PyDateTime_Date *) (type->tp_alloc(type, 0)); + if (me != NULL) { + char *pdata = PyBytes_AS_STRING(state); + memcpy(me->data, pdata, _PyDateTime_DATE_DATASIZE); + me->hashcode = -1; + } + return (PyObject *)me; + } + + if (PyArg_ParseTupleAndKeywords(args, kw, "iii", date_kws, + &year, &month, &day)) { + if (check_date_args(year, month, day) < 0) + return NULL; + self = new_date_ex(year, month, day, type); + } + return self; } /* Return new date from localtime(t). */ static PyObject * date_local_from_time_t(PyObject *cls, double ts) { - struct tm *tm; - time_t t; - PyObject *result = NULL; - - t = _PyTime_DoubleToTimet(ts); - if (t == (time_t)-1 && PyErr_Occurred()) - return NULL; - tm = localtime(&t); - if (tm) - result = PyObject_CallFunction(cls, "iii", - tm->tm_year + 1900, - tm->tm_mon + 1, - tm->tm_mday); - else - PyErr_SetString(PyExc_ValueError, - "timestamp out of range for " - "platform localtime() function"); - return result; + struct tm *tm; + time_t t; + PyObject *result = NULL; + + t = _PyTime_DoubleToTimet(ts); + if (t == (time_t)-1 && PyErr_Occurred()) + return NULL; + tm = localtime(&t); + if (tm) + result = PyObject_CallFunction(cls, "iii", + tm->tm_year + 1900, + tm->tm_mon + 1, + tm->tm_mday); + else + PyErr_SetString(PyExc_ValueError, + "timestamp out of range for " + "platform localtime() function"); + return result; } /* Return new date from current time. @@ -2446,34 +2446,34 @@ static PyObject * date_today(PyObject *cls, PyObject *dummy) { - PyObject *time; - PyObject *result; + PyObject *time; + PyObject *result; - time = time_time(); - if (time == NULL) - return NULL; - - /* Note well: today() is a class method, so this may not call - * date.fromtimestamp. For example, it may call - * datetime.fromtimestamp. That's why we need all the accuracy - * time.time() delivers; if someone were gonzo about optimization, - * date.today() could get away with plain C time(). - */ - result = PyObject_CallMethod(cls, "fromtimestamp", "O", time); - Py_DECREF(time); - return result; + time = time_time(); + if (time == NULL) + return NULL; + + /* Note well: today() is a class method, so this may not call + * date.fromtimestamp. For example, it may call + * datetime.fromtimestamp. That's why we need all the accuracy + * time.time() delivers; if someone were gonzo about optimization, + * date.today() could get away with plain C time(). + */ + result = PyObject_CallMethod(cls, "fromtimestamp", "O", time); + Py_DECREF(time); + return result; } /* Return new date from given timestamp (Python timestamp -- a double). */ static PyObject * date_fromtimestamp(PyObject *cls, PyObject *args) { - double timestamp; - PyObject *result = NULL; + double timestamp; + PyObject *result = NULL; - if (PyArg_ParseTuple(args, "d:fromtimestamp", ×tamp)) - result = date_local_from_time_t(cls, timestamp); - return result; + if (PyArg_ParseTuple(args, "d:fromtimestamp", ×tamp)) + result = date_local_from_time_t(cls, timestamp); + return result; } /* Return new date from proleptic Gregorian ordinal. Raises ValueError if @@ -2482,24 +2482,24 @@ static PyObject * date_fromordinal(PyObject *cls, PyObject *args) { - PyObject *result = NULL; - int ordinal; + PyObject *result = NULL; + int ordinal; - if (PyArg_ParseTuple(args, "i:fromordinal", &ordinal)) { - int year; - int month; - int day; - - if (ordinal < 1) - PyErr_SetString(PyExc_ValueError, "ordinal must be " - ">= 1"); - else { - ord_to_ymd(ordinal, &year, &month, &day); - result = PyObject_CallFunction(cls, "iii", - year, month, day); - } - } - return result; + if (PyArg_ParseTuple(args, "i:fromordinal", &ordinal)) { + int year; + int month; + int day; + + if (ordinal < 1) + PyErr_SetString(PyExc_ValueError, "ordinal must be " + ">= 1"); + else { + ord_to_ymd(ordinal, &year, &month, &day); + result = PyObject_CallFunction(cls, "iii", + year, month, day); + } + } + return result; } /* @@ -2512,74 +2512,74 @@ static PyObject * add_date_timedelta(PyDateTime_Date *date, PyDateTime_Delta *delta, int negate) { - PyObject *result = NULL; - int year = GET_YEAR(date); - int month = GET_MONTH(date); - int deltadays = GET_TD_DAYS(delta); - /* C-level overflow is impossible because |deltadays| < 1e9. */ - int day = GET_DAY(date) + (negate ? -deltadays : deltadays); - - if (normalize_date(&year, &month, &day) >= 0) - result = new_date(year, month, day); - return result; + PyObject *result = NULL; + int year = GET_YEAR(date); + int month = GET_MONTH(date); + int deltadays = GET_TD_DAYS(delta); + /* C-level overflow is impossible because |deltadays| < 1e9. */ + int day = GET_DAY(date) + (negate ? -deltadays : deltadays); + + if (normalize_date(&year, &month, &day) >= 0) + result = new_date(year, month, day); + return result; } static PyObject * date_add(PyObject *left, PyObject *right) { - if (PyDateTime_Check(left) || PyDateTime_Check(right)) { - Py_INCREF(Py_NotImplemented); - return Py_NotImplemented; - } - if (PyDate_Check(left)) { - /* date + ??? */ - if (PyDelta_Check(right)) - /* date + delta */ - return add_date_timedelta((PyDateTime_Date *) left, - (PyDateTime_Delta *) right, - 0); - } - else { - /* ??? + date - * 'right' must be one of us, or we wouldn't have been called - */ - if (PyDelta_Check(left)) - /* delta + date */ - return add_date_timedelta((PyDateTime_Date *) right, - (PyDateTime_Delta *) left, - 0); - } - Py_INCREF(Py_NotImplemented); - return Py_NotImplemented; + if (PyDateTime_Check(left) || PyDateTime_Check(right)) { + Py_INCREF(Py_NotImplemented); + return Py_NotImplemented; + } + if (PyDate_Check(left)) { + /* date + ??? */ + if (PyDelta_Check(right)) + /* date + delta */ + return add_date_timedelta((PyDateTime_Date *) left, + (PyDateTime_Delta *) right, + 0); + } + else { + /* ??? + date + * 'right' must be one of us, or we wouldn't have been called + */ + if (PyDelta_Check(left)) + /* delta + date */ + return add_date_timedelta((PyDateTime_Date *) right, + (PyDateTime_Delta *) left, + 0); + } + Py_INCREF(Py_NotImplemented); + return Py_NotImplemented; } static PyObject * date_subtract(PyObject *left, PyObject *right) { - if (PyDateTime_Check(left) || PyDateTime_Check(right)) { - Py_INCREF(Py_NotImplemented); - return Py_NotImplemented; - } - if (PyDate_Check(left)) { - if (PyDate_Check(right)) { - /* date - date */ - int left_ord = ymd_to_ord(GET_YEAR(left), - GET_MONTH(left), - GET_DAY(left)); - int right_ord = ymd_to_ord(GET_YEAR(right), - GET_MONTH(right), - GET_DAY(right)); - return new_delta(left_ord - right_ord, 0, 0, 0); - } - if (PyDelta_Check(right)) { - /* date - delta */ - return add_date_timedelta((PyDateTime_Date *) left, - (PyDateTime_Delta *) right, - 1); - } - } - Py_INCREF(Py_NotImplemented); - return Py_NotImplemented; + if (PyDateTime_Check(left) || PyDateTime_Check(right)) { + Py_INCREF(Py_NotImplemented); + return Py_NotImplemented; + } + if (PyDate_Check(left)) { + if (PyDate_Check(right)) { + /* date - date */ + int left_ord = ymd_to_ord(GET_YEAR(left), + GET_MONTH(left), + GET_DAY(left)); + int right_ord = ymd_to_ord(GET_YEAR(right), + GET_MONTH(right), + GET_DAY(right)); + return new_delta(left_ord - right_ord, 0, 0, 0); + } + if (PyDelta_Check(right)) { + /* date - delta */ + return add_date_timedelta((PyDateTime_Date *) left, + (PyDateTime_Delta *) right, + 1); + } + } + Py_INCREF(Py_NotImplemented); + return Py_NotImplemented; } @@ -2588,69 +2588,69 @@ static PyObject * date_repr(PyDateTime_Date *self) { - return PyUnicode_FromFormat("%s(%d, %d, %d)", - Py_TYPE(self)->tp_name, - GET_YEAR(self), GET_MONTH(self), GET_DAY(self)); + return PyUnicode_FromFormat("%s(%d, %d, %d)", + Py_TYPE(self)->tp_name, + GET_YEAR(self), GET_MONTH(self), GET_DAY(self)); } static PyObject * date_isoformat(PyDateTime_Date *self) { - return PyUnicode_FromFormat("%04d-%02d-%02d", - GET_YEAR(self), GET_MONTH(self), GET_DAY(self)); + return PyUnicode_FromFormat("%04d-%02d-%02d", + GET_YEAR(self), GET_MONTH(self), GET_DAY(self)); } /* str() calls the appropriate isoformat() method. */ static PyObject * date_str(PyDateTime_Date *self) { - return PyObject_CallMethod((PyObject *)self, "isoformat", "()"); + return PyObject_CallMethod((PyObject *)self, "isoformat", "()"); } static PyObject * date_ctime(PyDateTime_Date *self) { - return format_ctime(self, 0, 0, 0); + return format_ctime(self, 0, 0, 0); } static PyObject * date_strftime(PyDateTime_Date *self, PyObject *args, PyObject *kw) { - /* This method can be inherited, and needs to call the - * timetuple() method appropriate to self's class. - */ - PyObject *result; - PyObject *tuple; - PyObject *format; - static char *keywords[] = {"format", NULL}; - - if (! PyArg_ParseTupleAndKeywords(args, kw, "U:strftime", keywords, - &format)) - return NULL; - - tuple = PyObject_CallMethod((PyObject *)self, "timetuple", "()"); - if (tuple == NULL) - return NULL; - result = wrap_strftime((PyObject *)self, format, tuple, - (PyObject *)self); - Py_DECREF(tuple); - return result; + /* This method can be inherited, and needs to call the + * timetuple() method appropriate to self's class. + */ + PyObject *result; + PyObject *tuple; + PyObject *format; + static char *keywords[] = {"format", NULL}; + + if (! PyArg_ParseTupleAndKeywords(args, kw, "U:strftime", keywords, + &format)) + return NULL; + + tuple = PyObject_CallMethod((PyObject *)self, "timetuple", "()"); + if (tuple == NULL) + return NULL; + result = wrap_strftime((PyObject *)self, format, tuple, + (PyObject *)self); + Py_DECREF(tuple); + return result; } static PyObject * date_format(PyDateTime_Date *self, PyObject *args) { - PyObject *format; + PyObject *format; - if (!PyArg_ParseTuple(args, "U:__format__", &format)) - return NULL; + if (!PyArg_ParseTuple(args, "U:__format__", &format)) + return NULL; - /* if the format is zero length, return str(self) */ - if (PyUnicode_GetSize(format) == 0) - return PyObject_Str((PyObject *)self); + /* if the format is zero length, return str(self) */ + if (PyUnicode_GetSize(format) == 0) + return PyObject_Str((PyObject *)self); - return PyObject_CallMethod((PyObject *)self, "strftime", "O", format); + return PyObject_CallMethod((PyObject *)self, "strftime", "O", format); } /* ISO methods. */ @@ -2658,31 +2658,31 @@ static PyObject * date_isoweekday(PyDateTime_Date *self) { - int dow = weekday(GET_YEAR(self), GET_MONTH(self), GET_DAY(self)); + int dow = weekday(GET_YEAR(self), GET_MONTH(self), GET_DAY(self)); - return PyLong_FromLong(dow + 1); + return PyLong_FromLong(dow + 1); } static PyObject * date_isocalendar(PyDateTime_Date *self) { - int year = GET_YEAR(self); - int week1_monday = iso_week1_monday(year); - int today = ymd_to_ord(year, GET_MONTH(self), GET_DAY(self)); - int week; - int day; - - week = divmod(today - week1_monday, 7, &day); - if (week < 0) { - --year; - week1_monday = iso_week1_monday(year); - week = divmod(today - week1_monday, 7, &day); - } - else if (week >= 52 && today >= iso_week1_monday(year + 1)) { - ++year; - week = 0; - } - return Py_BuildValue("iii", year, week + 1, day + 1); + int year = GET_YEAR(self); + int week1_monday = iso_week1_monday(year); + int today = ymd_to_ord(year, GET_MONTH(self), GET_DAY(self)); + int week; + int day; + + week = divmod(today - week1_monday, 7, &day); + if (week < 0) { + --year; + week1_monday = iso_week1_monday(year); + week = divmod(today - week1_monday, 7, &day); + } + else if (week >= 52 && today >= iso_week1_monday(year + 1)) { + ++year; + week = 0; + } + return Py_BuildValue("iii", year, week + 1, day + 1); } /* Miscellaneous methods. */ @@ -2690,65 +2690,65 @@ static PyObject * date_richcompare(PyObject *self, PyObject *other, int op) { - if (PyDate_Check(other)) { - int diff = memcmp(((PyDateTime_Date *)self)->data, - ((PyDateTime_Date *)other)->data, - _PyDateTime_DATE_DATASIZE); - return diff_to_bool(diff, op); - } - else { - Py_INCREF(Py_NotImplemented); - return Py_NotImplemented; - } + if (PyDate_Check(other)) { + int diff = memcmp(((PyDateTime_Date *)self)->data, + ((PyDateTime_Date *)other)->data, + _PyDateTime_DATE_DATASIZE); + return diff_to_bool(diff, op); + } + else { + Py_INCREF(Py_NotImplemented); + return Py_NotImplemented; + } } static PyObject * date_timetuple(PyDateTime_Date *self) { - return build_struct_time(GET_YEAR(self), - GET_MONTH(self), - GET_DAY(self), - 0, 0, 0, -1); + return build_struct_time(GET_YEAR(self), + GET_MONTH(self), + GET_DAY(self), + 0, 0, 0, -1); } static PyObject * date_replace(PyDateTime_Date *self, PyObject *args, PyObject *kw) { - PyObject *clone; - PyObject *tuple; - int year = GET_YEAR(self); - int month = GET_MONTH(self); - int day = GET_DAY(self); - - if (! PyArg_ParseTupleAndKeywords(args, kw, "|iii:replace", date_kws, - &year, &month, &day)) - return NULL; - tuple = Py_BuildValue("iii", year, month, day); - if (tuple == NULL) - return NULL; - clone = date_new(Py_TYPE(self), tuple, NULL); - Py_DECREF(tuple); - return clone; + PyObject *clone; + PyObject *tuple; + int year = GET_YEAR(self); + int month = GET_MONTH(self); + int day = GET_DAY(self); + + if (! PyArg_ParseTupleAndKeywords(args, kw, "|iii:replace", date_kws, + &year, &month, &day)) + return NULL; + tuple = Py_BuildValue("iii", year, month, day); + if (tuple == NULL) + return NULL; + clone = date_new(Py_TYPE(self), tuple, NULL); + Py_DECREF(tuple); + return clone; } /* - Borrowed from stringobject.c, originally it was string_hash() + Borrowed from stringobject.c, originally it was string_hash() */ static long generic_hash(unsigned char *data, int len) { - register unsigned char *p; - register long x; + register unsigned char *p; + register long x; - p = (unsigned char *) data; - x = *p << 7; - while (--len >= 0) - x = (1000003*x) ^ *p++; - x ^= len; - if (x == -1) - x = -2; + p = (unsigned char *) data; + x = *p << 7; + while (--len >= 0) + x = (1000003*x) ^ *p++; + x ^= len; + if (x == -1) + x = -2; - return x; + return x; } @@ -2757,26 +2757,26 @@ static long date_hash(PyDateTime_Date *self) { - if (self->hashcode == -1) - self->hashcode = generic_hash( - (unsigned char *)self->data, _PyDateTime_DATE_DATASIZE); + if (self->hashcode == -1) + self->hashcode = generic_hash( + (unsigned char *)self->data, _PyDateTime_DATE_DATASIZE); - return self->hashcode; + return self->hashcode; } static PyObject * date_toordinal(PyDateTime_Date *self) { - return PyLong_FromLong(ymd_to_ord(GET_YEAR(self), GET_MONTH(self), - GET_DAY(self))); + return PyLong_FromLong(ymd_to_ord(GET_YEAR(self), GET_MONTH(self), + GET_DAY(self))); } static PyObject * date_weekday(PyDateTime_Date *self) { - int dow = weekday(GET_YEAR(self), GET_MONTH(self), GET_DAY(self)); + int dow = weekday(GET_YEAR(self), GET_MONTH(self), GET_DAY(self)); - return PyLong_FromLong(dow); + return PyLong_FromLong(dow); } /* Pickle support, a simple use of __reduce__. */ @@ -2785,134 +2785,134 @@ static PyObject * date_getstate(PyDateTime_Date *self) { - PyObject* field; - field = PyBytes_FromStringAndSize((char*)self->data, - _PyDateTime_DATE_DATASIZE); - return Py_BuildValue("(N)", field); + PyObject* field; + field = PyBytes_FromStringAndSize((char*)self->data, + _PyDateTime_DATE_DATASIZE); + return Py_BuildValue("(N)", field); } static PyObject * date_reduce(PyDateTime_Date *self, PyObject *arg) { - return Py_BuildValue("(ON)", Py_TYPE(self), date_getstate(self)); + return Py_BuildValue("(ON)", Py_TYPE(self), date_getstate(self)); } static PyMethodDef date_methods[] = { - /* Class methods: */ + /* Class methods: */ - {"fromtimestamp", (PyCFunction)date_fromtimestamp, METH_VARARGS | - METH_CLASS, - PyDoc_STR("timestamp -> local date from a POSIX timestamp (like " - "time.time()).")}, + {"fromtimestamp", (PyCFunction)date_fromtimestamp, METH_VARARGS | + METH_CLASS, + PyDoc_STR("timestamp -> local date from a POSIX timestamp (like " + "time.time()).")}, - {"fromordinal", (PyCFunction)date_fromordinal, METH_VARARGS | - METH_CLASS, - PyDoc_STR("int -> date corresponding to a proleptic Gregorian " - "ordinal.")}, + {"fromordinal", (PyCFunction)date_fromordinal, METH_VARARGS | + METH_CLASS, + PyDoc_STR("int -> date corresponding to a proleptic Gregorian " + "ordinal.")}, - {"today", (PyCFunction)date_today, METH_NOARGS | METH_CLASS, - PyDoc_STR("Current date or datetime: same as " - "self.__class__.fromtimestamp(time.time()).")}, + {"today", (PyCFunction)date_today, METH_NOARGS | METH_CLASS, + PyDoc_STR("Current date or datetime: same as " + "self.__class__.fromtimestamp(time.time()).")}, - /* Instance methods: */ + /* Instance methods: */ - {"ctime", (PyCFunction)date_ctime, METH_NOARGS, - PyDoc_STR("Return ctime() style string.")}, + {"ctime", (PyCFunction)date_ctime, METH_NOARGS, + PyDoc_STR("Return ctime() style string.")}, - {"strftime", (PyCFunction)date_strftime, METH_VARARGS | METH_KEYWORDS, - PyDoc_STR("format -> strftime() style string.")}, + {"strftime", (PyCFunction)date_strftime, METH_VARARGS | METH_KEYWORDS, + PyDoc_STR("format -> strftime() style string.")}, - {"__format__", (PyCFunction)date_format, METH_VARARGS, - PyDoc_STR("Formats self with strftime.")}, + {"__format__", (PyCFunction)date_format, METH_VARARGS, + PyDoc_STR("Formats self with strftime.")}, - {"timetuple", (PyCFunction)date_timetuple, METH_NOARGS, - PyDoc_STR("Return time tuple, compatible with time.localtime().")}, + {"timetuple", (PyCFunction)date_timetuple, METH_NOARGS, + PyDoc_STR("Return time tuple, compatible with time.localtime().")}, - {"isocalendar", (PyCFunction)date_isocalendar, METH_NOARGS, - PyDoc_STR("Return a 3-tuple containing ISO year, week number, and " - "weekday.")}, + {"isocalendar", (PyCFunction)date_isocalendar, METH_NOARGS, + PyDoc_STR("Return a 3-tuple containing ISO year, week number, and " + "weekday.")}, - {"isoformat", (PyCFunction)date_isoformat, METH_NOARGS, - PyDoc_STR("Return string in ISO 8601 format, YYYY-MM-DD.")}, + {"isoformat", (PyCFunction)date_isoformat, METH_NOARGS, + PyDoc_STR("Return string in ISO 8601 format, YYYY-MM-DD.")}, - {"isoweekday", (PyCFunction)date_isoweekday, METH_NOARGS, - PyDoc_STR("Return the day of the week represented by the date.\n" - "Monday == 1 ... Sunday == 7")}, + {"isoweekday", (PyCFunction)date_isoweekday, METH_NOARGS, + PyDoc_STR("Return the day of the week represented by the date.\n" + "Monday == 1 ... Sunday == 7")}, - {"toordinal", (PyCFunction)date_toordinal, METH_NOARGS, - PyDoc_STR("Return proleptic Gregorian ordinal. January 1 of year " - "1 is day 1.")}, + {"toordinal", (PyCFunction)date_toordinal, METH_NOARGS, + PyDoc_STR("Return proleptic Gregorian ordinal. January 1 of year " + "1 is day 1.")}, - {"weekday", (PyCFunction)date_weekday, METH_NOARGS, - PyDoc_STR("Return the day of the week represented by the date.\n" - "Monday == 0 ... Sunday == 6")}, + {"weekday", (PyCFunction)date_weekday, METH_NOARGS, + PyDoc_STR("Return the day of the week represented by the date.\n" + "Monday == 0 ... Sunday == 6")}, - {"replace", (PyCFunction)date_replace, METH_VARARGS | METH_KEYWORDS, - PyDoc_STR("Return date with new specified fields.")}, + {"replace", (PyCFunction)date_replace, METH_VARARGS | METH_KEYWORDS, + PyDoc_STR("Return date with new specified fields.")}, - {"__reduce__", (PyCFunction)date_reduce, METH_NOARGS, - PyDoc_STR("__reduce__() -> (cls, state)")}, + {"__reduce__", (PyCFunction)date_reduce, METH_NOARGS, + PyDoc_STR("__reduce__() -> (cls, state)")}, - {NULL, NULL} + {NULL, NULL} }; static char date_doc[] = PyDoc_STR("date(year, month, day) --> date object"); static PyNumberMethods date_as_number = { - date_add, /* nb_add */ - date_subtract, /* nb_subtract */ - 0, /* nb_multiply */ - 0, /* nb_remainder */ - 0, /* nb_divmod */ - 0, /* nb_power */ - 0, /* nb_negative */ - 0, /* nb_positive */ - 0, /* nb_absolute */ - 0, /* nb_bool */ + date_add, /* nb_add */ + date_subtract, /* nb_subtract */ + 0, /* nb_multiply */ + 0, /* nb_remainder */ + 0, /* nb_divmod */ + 0, /* nb_power */ + 0, /* nb_negative */ + 0, /* nb_positive */ + 0, /* nb_absolute */ + 0, /* nb_bool */ }; static PyTypeObject PyDateTime_DateType = { - PyVarObject_HEAD_INIT(NULL, 0) - "datetime.date", /* tp_name */ - sizeof(PyDateTime_Date), /* tp_basicsize */ - 0, /* tp_itemsize */ - 0, /* tp_dealloc */ - 0, /* tp_print */ - 0, /* tp_getattr */ - 0, /* tp_setattr */ - 0, /* tp_reserved */ - (reprfunc)date_repr, /* tp_repr */ - &date_as_number, /* tp_as_number */ - 0, /* tp_as_sequence */ - 0, /* tp_as_mapping */ - (hashfunc)date_hash, /* tp_hash */ - 0, /* tp_call */ - (reprfunc)date_str, /* tp_str */ - PyObject_GenericGetAttr, /* tp_getattro */ - 0, /* tp_setattro */ - 0, /* tp_as_buffer */ - Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */ - date_doc, /* tp_doc */ - 0, /* tp_traverse */ - 0, /* tp_clear */ - date_richcompare, /* tp_richcompare */ - 0, /* tp_weaklistoffset */ - 0, /* tp_iter */ - 0, /* tp_iternext */ - date_methods, /* tp_methods */ - 0, /* tp_members */ - date_getset, /* tp_getset */ - 0, /* tp_base */ - 0, /* tp_dict */ - 0, /* tp_descr_get */ - 0, /* tp_descr_set */ - 0, /* tp_dictoffset */ - 0, /* tp_init */ - 0, /* tp_alloc */ - date_new, /* tp_new */ - 0, /* tp_free */ + PyVarObject_HEAD_INIT(NULL, 0) + "datetime.date", /* tp_name */ + sizeof(PyDateTime_Date), /* tp_basicsize */ + 0, /* tp_itemsize */ + 0, /* tp_dealloc */ + 0, /* tp_print */ + 0, /* tp_getattr */ + 0, /* tp_setattr */ + 0, /* tp_reserved */ + (reprfunc)date_repr, /* tp_repr */ + &date_as_number, /* tp_as_number */ + 0, /* tp_as_sequence */ + 0, /* tp_as_mapping */ + (hashfunc)date_hash, /* tp_hash */ + 0, /* tp_call */ + (reprfunc)date_str, /* tp_str */ + PyObject_GenericGetAttr, /* tp_getattro */ + 0, /* tp_setattro */ + 0, /* tp_as_buffer */ + Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */ + date_doc, /* tp_doc */ + 0, /* tp_traverse */ + 0, /* tp_clear */ + date_richcompare, /* tp_richcompare */ + 0, /* tp_weaklistoffset */ + 0, /* tp_iter */ + 0, /* tp_iternext */ + date_methods, /* tp_methods */ + 0, /* tp_members */ + date_getset, /* tp_getset */ + 0, /* tp_base */ + 0, /* tp_dict */ + 0, /* tp_descr_get */ + 0, /* tp_descr_set */ + 0, /* tp_dictoffset */ + 0, /* tp_init */ + 0, /* tp_alloc */ + date_new, /* tp_new */ + 0, /* tp_free */ }; /* @@ -2935,10 +2935,10 @@ static PyObject * tzinfo_nogo(const char* methodname) { - PyErr_Format(PyExc_NotImplementedError, - "a tzinfo subclass must implement %s()", - methodname); - return NULL; + PyErr_Format(PyExc_NotImplementedError, + "a tzinfo subclass must implement %s()", + methodname); + return NULL; } /* Methods. A subclass must implement these. */ @@ -2946,101 +2946,101 @@ static PyObject * tzinfo_tzname(PyDateTime_TZInfo *self, PyObject *dt) { - return tzinfo_nogo("tzname"); + return tzinfo_nogo("tzname"); } static PyObject * tzinfo_utcoffset(PyDateTime_TZInfo *self, PyObject *dt) { - return tzinfo_nogo("utcoffset"); + return tzinfo_nogo("utcoffset"); } static PyObject * tzinfo_dst(PyDateTime_TZInfo *self, PyObject *dt) { - return tzinfo_nogo("dst"); + return tzinfo_nogo("dst"); } static PyObject * tzinfo_fromutc(PyDateTime_TZInfo *self, PyDateTime_DateTime *dt) { - int y, m, d, hh, mm, ss, us; + int y, m, d, hh, mm, ss, us; - PyObject *result; - int off, dst; - int none; - int delta; - - if (! PyDateTime_Check(dt)) { - PyErr_SetString(PyExc_TypeError, - "fromutc: argument must be a datetime"); - return NULL; - } - if (! HASTZINFO(dt) || dt->tzinfo != (PyObject *)self) { - PyErr_SetString(PyExc_ValueError, "fromutc: dt.tzinfo " - "is not self"); - return NULL; - } - - off = call_utcoffset(dt->tzinfo, (PyObject *)dt, &none); - if (off == -1 && PyErr_Occurred()) - return NULL; - if (none) { - PyErr_SetString(PyExc_ValueError, "fromutc: non-None " - "utcoffset() result required"); - return NULL; - } - - dst = call_dst(dt->tzinfo, (PyObject *)dt, &none); - if (dst == -1 && PyErr_Occurred()) - return NULL; - if (none) { - PyErr_SetString(PyExc_ValueError, "fromutc: non-None " - "dst() result required"); - return NULL; - } - - y = GET_YEAR(dt); - m = GET_MONTH(dt); - d = GET_DAY(dt); - hh = DATE_GET_HOUR(dt); - mm = DATE_GET_MINUTE(dt); - ss = DATE_GET_SECOND(dt); - us = DATE_GET_MICROSECOND(dt); - - delta = off - dst; - mm += delta; - if ((mm < 0 || mm >= 60) && - normalize_datetime(&y, &m, &d, &hh, &mm, &ss, &us) < 0) - return NULL; - result = new_datetime(y, m, d, hh, mm, ss, us, dt->tzinfo); - if (result == NULL) - return result; - - dst = call_dst(dt->tzinfo, result, &none); - if (dst == -1 && PyErr_Occurred()) - goto Fail; - if (none) - goto Inconsistent; - if (dst == 0) - return result; - - mm += dst; - if ((mm < 0 || mm >= 60) && - normalize_datetime(&y, &m, &d, &hh, &mm, &ss, &us) < 0) - goto Fail; - Py_DECREF(result); - result = new_datetime(y, m, d, hh, mm, ss, us, dt->tzinfo); - return result; + PyObject *result; + int off, dst; + int none; + int delta; + + if (! PyDateTime_Check(dt)) { + PyErr_SetString(PyExc_TypeError, + "fromutc: argument must be a datetime"); + return NULL; + } + if (! HASTZINFO(dt) || dt->tzinfo != (PyObject *)self) { + PyErr_SetString(PyExc_ValueError, "fromutc: dt.tzinfo " + "is not self"); + return NULL; + } + + off = call_utcoffset(dt->tzinfo, (PyObject *)dt, &none); + if (off == -1 && PyErr_Occurred()) + return NULL; + if (none) { + PyErr_SetString(PyExc_ValueError, "fromutc: non-None " + "utcoffset() result required"); + return NULL; + } + + dst = call_dst(dt->tzinfo, (PyObject *)dt, &none); + if (dst == -1 && PyErr_Occurred()) + return NULL; + if (none) { + PyErr_SetString(PyExc_ValueError, "fromutc: non-None " + "dst() result required"); + return NULL; + } + + y = GET_YEAR(dt); + m = GET_MONTH(dt); + d = GET_DAY(dt); + hh = DATE_GET_HOUR(dt); + mm = DATE_GET_MINUTE(dt); + ss = DATE_GET_SECOND(dt); + us = DATE_GET_MICROSECOND(dt); + + delta = off - dst; + mm += delta; + if ((mm < 0 || mm >= 60) && + normalize_datetime(&y, &m, &d, &hh, &mm, &ss, &us) < 0) + return NULL; + result = new_datetime(y, m, d, hh, mm, ss, us, dt->tzinfo); + if (result == NULL) + return result; + + dst = call_dst(dt->tzinfo, result, &none); + if (dst == -1 && PyErr_Occurred()) + goto Fail; + if (none) + goto Inconsistent; + if (dst == 0) + return result; + + mm += dst; + if ((mm < 0 || mm >= 60) && + normalize_datetime(&y, &m, &d, &hh, &mm, &ss, &us) < 0) + goto Fail; + Py_DECREF(result); + result = new_datetime(y, m, d, hh, mm, ss, us, dt->tzinfo); + return result; Inconsistent: - PyErr_SetString(PyExc_ValueError, "fromutc: tz.dst() gave" - "inconsistent results; cannot convert"); + PyErr_SetString(PyExc_ValueError, "fromutc: tz.dst() gave" + "inconsistent results; cannot convert"); - /* fall thru to failure */ + /* fall thru to failure */ Fail: - Py_DECREF(result); - return NULL; + Py_DECREF(result); + return NULL; } /* @@ -3051,122 +3051,122 @@ static PyObject * tzinfo_reduce(PyObject *self) { - PyObject *args, *state, *tmp; - PyObject *getinitargs, *getstate; + PyObject *args, *state, *tmp; + PyObject *getinitargs, *getstate; - tmp = PyTuple_New(0); - if (tmp == NULL) - return NULL; - - getinitargs = PyObject_GetAttrString(self, "__getinitargs__"); - if (getinitargs != NULL) { - args = PyObject_CallObject(getinitargs, tmp); - Py_DECREF(getinitargs); - if (args == NULL) { - Py_DECREF(tmp); - return NULL; - } - } - else { - PyErr_Clear(); - args = tmp; - Py_INCREF(args); - } - - getstate = PyObject_GetAttrString(self, "__getstate__"); - if (getstate != NULL) { - state = PyObject_CallObject(getstate, tmp); - Py_DECREF(getstate); - if (state == NULL) { - Py_DECREF(args); - Py_DECREF(tmp); - return NULL; - } - } - else { - PyObject **dictptr; - PyErr_Clear(); - state = Py_None; - dictptr = _PyObject_GetDictPtr(self); - if (dictptr && *dictptr && PyDict_Size(*dictptr)) - state = *dictptr; - Py_INCREF(state); - } - - Py_DECREF(tmp); - - if (state == Py_None) { - Py_DECREF(state); - return Py_BuildValue("(ON)", Py_TYPE(self), args); - } - else - return Py_BuildValue("(ONN)", Py_TYPE(self), args, state); + tmp = PyTuple_New(0); + if (tmp == NULL) + return NULL; + + getinitargs = PyObject_GetAttrString(self, "__getinitargs__"); + if (getinitargs != NULL) { + args = PyObject_CallObject(getinitargs, tmp); + Py_DECREF(getinitargs); + if (args == NULL) { + Py_DECREF(tmp); + return NULL; + } + } + else { + PyErr_Clear(); + args = tmp; + Py_INCREF(args); + } + + getstate = PyObject_GetAttrString(self, "__getstate__"); + if (getstate != NULL) { + state = PyObject_CallObject(getstate, tmp); + Py_DECREF(getstate); + if (state == NULL) { + Py_DECREF(args); + Py_DECREF(tmp); + return NULL; + } + } + else { + PyObject **dictptr; + PyErr_Clear(); + state = Py_None; + dictptr = _PyObject_GetDictPtr(self); + if (dictptr && *dictptr && PyDict_Size(*dictptr)) + state = *dictptr; + Py_INCREF(state); + } + + Py_DECREF(tmp); + + if (state == Py_None) { + Py_DECREF(state); + return Py_BuildValue("(ON)", Py_TYPE(self), args); + } + else + return Py_BuildValue("(ONN)", Py_TYPE(self), args, state); } static PyMethodDef tzinfo_methods[] = { - {"tzname", (PyCFunction)tzinfo_tzname, METH_O, - PyDoc_STR("datetime -> string name of time zone.")}, + {"tzname", (PyCFunction)tzinfo_tzname, METH_O, + PyDoc_STR("datetime -> string name of time zone.")}, - {"utcoffset", (PyCFunction)tzinfo_utcoffset, METH_O, - PyDoc_STR("datetime -> minutes east of UTC (negative for " - "west of UTC).")}, + {"utcoffset", (PyCFunction)tzinfo_utcoffset, METH_O, + PyDoc_STR("datetime -> minutes east of UTC (negative for " + "west of UTC).")}, - {"dst", (PyCFunction)tzinfo_dst, METH_O, - PyDoc_STR("datetime -> DST offset in minutes east of UTC.")}, + {"dst", (PyCFunction)tzinfo_dst, METH_O, + PyDoc_STR("datetime -> DST offset in minutes east of UTC.")}, - {"fromutc", (PyCFunction)tzinfo_fromutc, METH_O, - PyDoc_STR("datetime in UTC -> datetime in local time.")}, + {"fromutc", (PyCFunction)tzinfo_fromutc, METH_O, + PyDoc_STR("datetime in UTC -> datetime in local time.")}, - {"__reduce__", (PyCFunction)tzinfo_reduce, METH_NOARGS, - PyDoc_STR("-> (cls, state)")}, + {"__reduce__", (PyCFunction)tzinfo_reduce, METH_NOARGS, + PyDoc_STR("-> (cls, state)")}, - {NULL, NULL} + {NULL, NULL} }; static char tzinfo_doc[] = PyDoc_STR("Abstract base class for time zone info objects."); static PyTypeObject PyDateTime_TZInfoType = { - PyVarObject_HEAD_INIT(NULL, 0) - "datetime.tzinfo", /* tp_name */ - sizeof(PyDateTime_TZInfo), /* tp_basicsize */ - 0, /* tp_itemsize */ - 0, /* 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_BASETYPE, /* tp_flags */ - tzinfo_doc, /* tp_doc */ - 0, /* tp_traverse */ - 0, /* tp_clear */ - 0, /* tp_richcompare */ - 0, /* tp_weaklistoffset */ - 0, /* tp_iter */ - 0, /* tp_iternext */ - tzinfo_methods, /* tp_methods */ - 0, /* tp_members */ - 0, /* tp_getset */ - 0, /* tp_base */ - 0, /* tp_dict */ - 0, /* tp_descr_get */ - 0, /* tp_descr_set */ - 0, /* tp_dictoffset */ - 0, /* tp_init */ - 0, /* tp_alloc */ - PyType_GenericNew, /* tp_new */ - 0, /* tp_free */ + PyVarObject_HEAD_INIT(NULL, 0) + "datetime.tzinfo", /* tp_name */ + sizeof(PyDateTime_TZInfo), /* tp_basicsize */ + 0, /* tp_itemsize */ + 0, /* 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_BASETYPE, /* tp_flags */ + tzinfo_doc, /* tp_doc */ + 0, /* tp_traverse */ + 0, /* tp_clear */ + 0, /* tp_richcompare */ + 0, /* tp_weaklistoffset */ + 0, /* tp_iter */ + 0, /* tp_iternext */ + tzinfo_methods, /* tp_methods */ + 0, /* tp_members */ + 0, /* tp_getset */ + 0, /* tp_base */ + 0, /* tp_dict */ + 0, /* tp_descr_get */ + 0, /* tp_descr_set */ + 0, /* tp_dictoffset */ + 0, /* tp_init */ + 0, /* tp_alloc */ + PyType_GenericNew, /* tp_new */ + 0, /* tp_free */ }; /* @@ -3179,43 +3179,43 @@ static PyObject * time_hour(PyDateTime_Time *self, void *unused) { - return PyLong_FromLong(TIME_GET_HOUR(self)); + return PyLong_FromLong(TIME_GET_HOUR(self)); } static PyObject * time_minute(PyDateTime_Time *self, void *unused) { - return PyLong_FromLong(TIME_GET_MINUTE(self)); + return PyLong_FromLong(TIME_GET_MINUTE(self)); } /* The name time_second conflicted with some platform header file. */ static PyObject * py_time_second(PyDateTime_Time *self, void *unused) { - return PyLong_FromLong(TIME_GET_SECOND(self)); + return PyLong_FromLong(TIME_GET_SECOND(self)); } static PyObject * time_microsecond(PyDateTime_Time *self, void *unused) { - return PyLong_FromLong(TIME_GET_MICROSECOND(self)); + return PyLong_FromLong(TIME_GET_MICROSECOND(self)); } static PyObject * time_tzinfo(PyDateTime_Time *self, void *unused) { - PyObject *result = HASTZINFO(self) ? self->tzinfo : Py_None; - Py_INCREF(result); - return result; + PyObject *result = HASTZINFO(self) ? self->tzinfo : Py_None; + Py_INCREF(result); + return result; } static PyGetSetDef time_getset[] = { - {"hour", (getter)time_hour}, - {"minute", (getter)time_minute}, - {"second", (getter)py_time_second}, - {"microsecond", (getter)time_microsecond}, - {"tzinfo", (getter)time_tzinfo}, - {NULL} + {"hour", (getter)time_hour}, + {"minute", (getter)time_minute}, + {"second", (getter)py_time_second}, + {"microsecond", (getter)time_microsecond}, + {"tzinfo", (getter)time_tzinfo}, + {NULL} }; /* @@ -3223,64 +3223,64 @@ */ static char *time_kws[] = {"hour", "minute", "second", "microsecond", - "tzinfo", NULL}; + "tzinfo", NULL}; static PyObject * time_new(PyTypeObject *type, PyObject *args, PyObject *kw) { - PyObject *self = NULL; - PyObject *state; - int hour = 0; - int minute = 0; - int second = 0; - int usecond = 0; - PyObject *tzinfo = Py_None; - - /* Check for invocation from pickle with __getstate__ state */ - if (PyTuple_GET_SIZE(args) >= 1 && - PyTuple_GET_SIZE(args) <= 2 && - PyBytes_Check(state = PyTuple_GET_ITEM(args, 0)) && - PyBytes_GET_SIZE(state) == _PyDateTime_TIME_DATASIZE && - ((unsigned char) (PyBytes_AS_STRING(state)[0])) < 24) - { - PyDateTime_Time *me; - char aware; - - if (PyTuple_GET_SIZE(args) == 2) { - tzinfo = PyTuple_GET_ITEM(args, 1); - if (check_tzinfo_subclass(tzinfo) < 0) { - PyErr_SetString(PyExc_TypeError, "bad " - "tzinfo state arg"); - return NULL; - } - } - aware = (char)(tzinfo != Py_None); - me = (PyDateTime_Time *) (type->tp_alloc(type, aware)); - if (me != NULL) { - char *pdata = PyBytes_AS_STRING(state); - - memcpy(me->data, pdata, _PyDateTime_TIME_DATASIZE); - me->hashcode = -1; - me->hastzinfo = aware; - if (aware) { - Py_INCREF(tzinfo); - me->tzinfo = tzinfo; - } - } - return (PyObject *)me; - } - - if (PyArg_ParseTupleAndKeywords(args, kw, "|iiiiO", time_kws, - &hour, &minute, &second, &usecond, - &tzinfo)) { - if (check_time_args(hour, minute, second, usecond) < 0) - return NULL; - if (check_tzinfo_subclass(tzinfo) < 0) - return NULL; - self = new_time_ex(hour, minute, second, usecond, tzinfo, - type); - } - return self; + PyObject *self = NULL; + PyObject *state; + int hour = 0; + int minute = 0; + int second = 0; + int usecond = 0; + PyObject *tzinfo = Py_None; + + /* Check for invocation from pickle with __getstate__ state */ + if (PyTuple_GET_SIZE(args) >= 1 && + PyTuple_GET_SIZE(args) <= 2 && + PyBytes_Check(state = PyTuple_GET_ITEM(args, 0)) && + PyBytes_GET_SIZE(state) == _PyDateTime_TIME_DATASIZE && + ((unsigned char) (PyBytes_AS_STRING(state)[0])) < 24) + { + PyDateTime_Time *me; + char aware; + + if (PyTuple_GET_SIZE(args) == 2) { + tzinfo = PyTuple_GET_ITEM(args, 1); + if (check_tzinfo_subclass(tzinfo) < 0) { + PyErr_SetString(PyExc_TypeError, "bad " + "tzinfo state arg"); + return NULL; + } + } + aware = (char)(tzinfo != Py_None); + me = (PyDateTime_Time *) (type->tp_alloc(type, aware)); + if (me != NULL) { + char *pdata = PyBytes_AS_STRING(state); + + memcpy(me->data, pdata, _PyDateTime_TIME_DATASIZE); + me->hashcode = -1; + me->hastzinfo = aware; + if (aware) { + Py_INCREF(tzinfo); + me->tzinfo = tzinfo; + } + } + return (PyObject *)me; + } + + if (PyArg_ParseTupleAndKeywords(args, kw, "|iiiiO", time_kws, + &hour, &minute, &second, &usecond, + &tzinfo)) { + if (check_time_args(hour, minute, second, usecond) < 0) + return NULL; + if (check_tzinfo_subclass(tzinfo) < 0) + return NULL; + self = new_time_ex(hour, minute, second, usecond, tzinfo, + type); + } + return self; } /* @@ -3290,10 +3290,10 @@ static void time_dealloc(PyDateTime_Time *self) { - if (HASTZINFO(self)) { - Py_XDECREF(self->tzinfo); - } - Py_TYPE(self)->tp_free((PyObject *)self); + if (HASTZINFO(self)) { + Py_XDECREF(self->tzinfo); + } + Py_TYPE(self)->tp_free((PyObject *)self); } /* @@ -3303,20 +3303,20 @@ /* These are all METH_NOARGS, so don't need to check the arglist. */ static PyObject * time_utcoffset(PyDateTime_Time *self, PyObject *unused) { - return offset_as_timedelta(HASTZINFO(self) ? self->tzinfo : Py_None, - "utcoffset", Py_None); + return offset_as_timedelta(HASTZINFO(self) ? self->tzinfo : Py_None, + "utcoffset", Py_None); } static PyObject * time_dst(PyDateTime_Time *self, PyObject *unused) { - return offset_as_timedelta(HASTZINFO(self) ? self->tzinfo : Py_None, - "dst", Py_None); + return offset_as_timedelta(HASTZINFO(self) ? self->tzinfo : Py_None, + "dst", Py_None); } static PyObject * time_tzname(PyDateTime_Time *self, PyObject *unused) { - return call_tzname(HASTZINFO(self) ? self->tzinfo : Py_None, - Py_None); + return call_tzname(HASTZINFO(self) ? self->tzinfo : Py_None, + Py_None); } /* @@ -3326,93 +3326,93 @@ static PyObject * time_repr(PyDateTime_Time *self) { - const char *type_name = Py_TYPE(self)->tp_name; - int h = TIME_GET_HOUR(self); - int m = TIME_GET_MINUTE(self); - int s = TIME_GET_SECOND(self); - int us = TIME_GET_MICROSECOND(self); - PyObject *result = NULL; - - if (us) - result = PyUnicode_FromFormat("%s(%d, %d, %d, %d)", - type_name, h, m, s, us); - else if (s) - result = PyUnicode_FromFormat("%s(%d, %d, %d)", - type_name, h, m, s); - else - result = PyUnicode_FromFormat("%s(%d, %d)", type_name, h, m); - if (result != NULL && HASTZINFO(self)) - result = append_keyword_tzinfo(result, self->tzinfo); - return result; + const char *type_name = Py_TYPE(self)->tp_name; + int h = TIME_GET_HOUR(self); + int m = TIME_GET_MINUTE(self); + int s = TIME_GET_SECOND(self); + int us = TIME_GET_MICROSECOND(self); + PyObject *result = NULL; + + if (us) + result = PyUnicode_FromFormat("%s(%d, %d, %d, %d)", + type_name, h, m, s, us); + else if (s) + result = PyUnicode_FromFormat("%s(%d, %d, %d)", + type_name, h, m, s); + else + result = PyUnicode_FromFormat("%s(%d, %d)", type_name, h, m); + if (result != NULL && HASTZINFO(self)) + result = append_keyword_tzinfo(result, self->tzinfo); + return result; } static PyObject * time_str(PyDateTime_Time *self) { - return PyObject_CallMethod((PyObject *)self, "isoformat", "()"); + return PyObject_CallMethod((PyObject *)self, "isoformat", "()"); } static PyObject * time_isoformat(PyDateTime_Time *self, PyObject *unused) { - char buf[100]; - PyObject *result; - int us = TIME_GET_MICROSECOND(self);; - - if (us) - result = PyUnicode_FromFormat("%02d:%02d:%02d.%06d", - TIME_GET_HOUR(self), - TIME_GET_MINUTE(self), - TIME_GET_SECOND(self), - us); - else - result = PyUnicode_FromFormat("%02d:%02d:%02d", - TIME_GET_HOUR(self), - TIME_GET_MINUTE(self), - TIME_GET_SECOND(self)); - - if (result == NULL || ! HASTZINFO(self) || self->tzinfo == Py_None) - return result; - - /* We need to append the UTC offset. */ - if (format_utcoffset(buf, sizeof(buf), ":", self->tzinfo, - Py_None) < 0) { - Py_DECREF(result); - return NULL; - } - PyUnicode_AppendAndDel(&result, PyUnicode_FromString(buf)); - return result; + char buf[100]; + PyObject *result; + int us = TIME_GET_MICROSECOND(self);; + + if (us) + result = PyUnicode_FromFormat("%02d:%02d:%02d.%06d", + TIME_GET_HOUR(self), + TIME_GET_MINUTE(self), + TIME_GET_SECOND(self), + us); + else + result = PyUnicode_FromFormat("%02d:%02d:%02d", + TIME_GET_HOUR(self), + TIME_GET_MINUTE(self), + TIME_GET_SECOND(self)); + + if (result == NULL || ! HASTZINFO(self) || self->tzinfo == Py_None) + return result; + + /* We need to append the UTC offset. */ + if (format_utcoffset(buf, sizeof(buf), ":", self->tzinfo, + Py_None) < 0) { + Py_DECREF(result); + return NULL; + } + PyUnicode_AppendAndDel(&result, PyUnicode_FromString(buf)); + return result; } static PyObject * time_strftime(PyDateTime_Time *self, PyObject *args, PyObject *kw) { - PyObject *result; - PyObject *tuple; - PyObject *format; - static char *keywords[] = {"format", NULL}; - - if (! PyArg_ParseTupleAndKeywords(args, kw, "U:strftime", keywords, - &format)) - return NULL; - - /* Python's strftime does insane things with the year part of the - * timetuple. The year is forced to (the otherwise nonsensical) - * 1900 to worm around that. - */ - tuple = Py_BuildValue("iiiiiiiii", - 1900, 1, 1, /* year, month, day */ - TIME_GET_HOUR(self), - TIME_GET_MINUTE(self), - TIME_GET_SECOND(self), - 0, 1, -1); /* weekday, daynum, dst */ - if (tuple == NULL) - return NULL; - assert(PyTuple_Size(tuple) == 9); - result = wrap_strftime((PyObject *)self, format, tuple, - Py_None); - Py_DECREF(tuple); - return result; + PyObject *result; + PyObject *tuple; + PyObject *format; + static char *keywords[] = {"format", NULL}; + + if (! PyArg_ParseTupleAndKeywords(args, kw, "U:strftime", keywords, + &format)) + return NULL; + + /* Python's strftime does insane things with the year part of the + * timetuple. The year is forced to (the otherwise nonsensical) + * 1900 to worm around that. + */ + tuple = Py_BuildValue("iiiiiiiii", + 1900, 1, 1, /* year, month, day */ + TIME_GET_HOUR(self), + TIME_GET_MINUTE(self), + TIME_GET_SECOND(self), + 0, 1, -1); /* weekday, daynum, dst */ + if (tuple == NULL) + return NULL; + assert(PyTuple_Size(tuple) == 9); + result = wrap_strftime((PyObject *)self, format, tuple, + Py_None); + Py_DECREF(tuple); + return result; } /* @@ -3422,144 +3422,144 @@ static PyObject * time_richcompare(PyObject *self, PyObject *other, int op) { - int diff; - naivety n1, n2; - int offset1, offset2; - - if (! PyTime_Check(other)) { - Py_INCREF(Py_NotImplemented); - return Py_NotImplemented; - } - if (classify_two_utcoffsets(self, &offset1, &n1, Py_None, - other, &offset2, &n2, Py_None) < 0) - return NULL; - assert(n1 != OFFSET_UNKNOWN && n2 != OFFSET_UNKNOWN); - /* If they're both naive, or both aware and have the same offsets, - * we get off cheap. Note that if they're both naive, offset1 == - * offset2 == 0 at this point. - */ - if (n1 == n2 && offset1 == offset2) { - diff = memcmp(((PyDateTime_Time *)self)->data, - ((PyDateTime_Time *)other)->data, - _PyDateTime_TIME_DATASIZE); - return diff_to_bool(diff, op); - } - - if (n1 == OFFSET_AWARE && n2 == OFFSET_AWARE) { - assert(offset1 != offset2); /* else last "if" handled it */ - /* Convert everything except microseconds to seconds. These - * can't overflow (no more than the # of seconds in 2 days). - */ - offset1 = TIME_GET_HOUR(self) * 3600 + - (TIME_GET_MINUTE(self) - offset1) * 60 + - TIME_GET_SECOND(self); - offset2 = TIME_GET_HOUR(other) * 3600 + - (TIME_GET_MINUTE(other) - offset2) * 60 + - TIME_GET_SECOND(other); - diff = offset1 - offset2; - if (diff == 0) - diff = TIME_GET_MICROSECOND(self) - - TIME_GET_MICROSECOND(other); - return diff_to_bool(diff, op); - } - - assert(n1 != n2); - PyErr_SetString(PyExc_TypeError, - "can't compare offset-naive and " - "offset-aware times"); - return NULL; + int diff; + naivety n1, n2; + int offset1, offset2; + + if (! PyTime_Check(other)) { + Py_INCREF(Py_NotImplemented); + return Py_NotImplemented; + } + if (classify_two_utcoffsets(self, &offset1, &n1, Py_None, + other, &offset2, &n2, Py_None) < 0) + return NULL; + assert(n1 != OFFSET_UNKNOWN && n2 != OFFSET_UNKNOWN); + /* If they're both naive, or both aware and have the same offsets, + * we get off cheap. Note that if they're both naive, offset1 == + * offset2 == 0 at this point. + */ + if (n1 == n2 && offset1 == offset2) { + diff = memcmp(((PyDateTime_Time *)self)->data, + ((PyDateTime_Time *)other)->data, + _PyDateTime_TIME_DATASIZE); + return diff_to_bool(diff, op); + } + + if (n1 == OFFSET_AWARE && n2 == OFFSET_AWARE) { + assert(offset1 != offset2); /* else last "if" handled it */ + /* Convert everything except microseconds to seconds. These + * can't overflow (no more than the # of seconds in 2 days). + */ + offset1 = TIME_GET_HOUR(self) * 3600 + + (TIME_GET_MINUTE(self) - offset1) * 60 + + TIME_GET_SECOND(self); + offset2 = TIME_GET_HOUR(other) * 3600 + + (TIME_GET_MINUTE(other) - offset2) * 60 + + TIME_GET_SECOND(other); + diff = offset1 - offset2; + if (diff == 0) + diff = TIME_GET_MICROSECOND(self) - + TIME_GET_MICROSECOND(other); + return diff_to_bool(diff, op); + } + + assert(n1 != n2); + PyErr_SetString(PyExc_TypeError, + "can't compare offset-naive and " + "offset-aware times"); + return NULL; } static long time_hash(PyDateTime_Time *self) { - if (self->hashcode == -1) { - naivety n; - int offset; - PyObject *temp; - - n = classify_utcoffset((PyObject *)self, Py_None, &offset); - assert(n != OFFSET_UNKNOWN); - if (n == OFFSET_ERROR) - return -1; - - /* Reduce this to a hash of another object. */ - if (offset == 0) { - self->hashcode = generic_hash( - (unsigned char *)self->data, _PyDateTime_TIME_DATASIZE); - return self->hashcode; - } - else { - int hour; - int minute; - - assert(n == OFFSET_AWARE); - assert(HASTZINFO(self)); - hour = divmod(TIME_GET_HOUR(self) * 60 + - TIME_GET_MINUTE(self) - offset, - 60, - &minute); - if (0 <= hour && hour < 24) - temp = new_time(hour, minute, - TIME_GET_SECOND(self), - TIME_GET_MICROSECOND(self), - Py_None); - else - temp = Py_BuildValue("iiii", - hour, minute, - TIME_GET_SECOND(self), - TIME_GET_MICROSECOND(self)); - } - if (temp != NULL) { - self->hashcode = PyObject_Hash(temp); - Py_DECREF(temp); - } - } - return self->hashcode; + if (self->hashcode == -1) { + naivety n; + int offset; + PyObject *temp; + + n = classify_utcoffset((PyObject *)self, Py_None, &offset); + assert(n != OFFSET_UNKNOWN); + if (n == OFFSET_ERROR) + return -1; + + /* Reduce this to a hash of another object. */ + if (offset == 0) { + self->hashcode = generic_hash( + (unsigned char *)self->data, _PyDateTime_TIME_DATASIZE); + return self->hashcode; + } + else { + int hour; + int minute; + + assert(n == OFFSET_AWARE); + assert(HASTZINFO(self)); + hour = divmod(TIME_GET_HOUR(self) * 60 + + TIME_GET_MINUTE(self) - offset, + 60, + &minute); + if (0 <= hour && hour < 24) + temp = new_time(hour, minute, + TIME_GET_SECOND(self), + TIME_GET_MICROSECOND(self), + Py_None); + else + temp = Py_BuildValue("iiii", + hour, minute, + TIME_GET_SECOND(self), + TIME_GET_MICROSECOND(self)); + } + if (temp != NULL) { + self->hashcode = PyObject_Hash(temp); + Py_DECREF(temp); + } + } + return self->hashcode; } static PyObject * time_replace(PyDateTime_Time *self, PyObject *args, PyObject *kw) { - PyObject *clone; - PyObject *tuple; - int hh = TIME_GET_HOUR(self); - int mm = TIME_GET_MINUTE(self); - int ss = TIME_GET_SECOND(self); - int us = TIME_GET_MICROSECOND(self); - PyObject *tzinfo = HASTZINFO(self) ? self->tzinfo : Py_None; - - if (! PyArg_ParseTupleAndKeywords(args, kw, "|iiiiO:replace", - time_kws, - &hh, &mm, &ss, &us, &tzinfo)) - return NULL; - tuple = Py_BuildValue("iiiiO", hh, mm, ss, us, tzinfo); - if (tuple == NULL) - return NULL; - clone = time_new(Py_TYPE(self), tuple, NULL); - Py_DECREF(tuple); - return clone; + PyObject *clone; + PyObject *tuple; + int hh = TIME_GET_HOUR(self); + int mm = TIME_GET_MINUTE(self); + int ss = TIME_GET_SECOND(self); + int us = TIME_GET_MICROSECOND(self); + PyObject *tzinfo = HASTZINFO(self) ? self->tzinfo : Py_None; + + if (! PyArg_ParseTupleAndKeywords(args, kw, "|iiiiO:replace", + time_kws, + &hh, &mm, &ss, &us, &tzinfo)) + return NULL; + tuple = Py_BuildValue("iiiiO", hh, mm, ss, us, tzinfo); + if (tuple == NULL) + return NULL; + clone = time_new(Py_TYPE(self), tuple, NULL); + Py_DECREF(tuple); + return clone; } static int time_bool(PyDateTime_Time *self) { - int offset; - int none; + int offset; + int none; - if (TIME_GET_SECOND(self) || TIME_GET_MICROSECOND(self)) { - /* Since utcoffset is in whole minutes, nothing can - * alter the conclusion that this is nonzero. - */ - return 1; - } - offset = 0; - if (HASTZINFO(self) && self->tzinfo != Py_None) { - offset = call_utcoffset(self->tzinfo, Py_None, &none); - if (offset == -1 && PyErr_Occurred()) - return -1; - } - return (TIME_GET_MINUTE(self) - offset + TIME_GET_HOUR(self)*60) != 0; + if (TIME_GET_SECOND(self) || TIME_GET_MICROSECOND(self)) { + /* Since utcoffset is in whole minutes, nothing can + * alter the conclusion that this is nonzero. + */ + return 1; + } + offset = 0; + if (HASTZINFO(self) && self->tzinfo != Py_None) { + offset = call_utcoffset(self->tzinfo, Py_None, &none); + if (offset == -1 && PyErr_Occurred()) + return -1; + } + return (TIME_GET_MINUTE(self) - offset + TIME_GET_HOUR(self)*60) != 0; } /* Pickle support, a simple use of __reduce__. */ @@ -3572,55 +3572,55 @@ static PyObject * time_getstate(PyDateTime_Time *self) { - PyObject *basestate; - PyObject *result = NULL; + PyObject *basestate; + PyObject *result = NULL; - basestate = PyBytes_FromStringAndSize((char *)self->data, - _PyDateTime_TIME_DATASIZE); - if (basestate != NULL) { - if (! HASTZINFO(self) || self->tzinfo == Py_None) - result = PyTuple_Pack(1, basestate); - else - result = PyTuple_Pack(2, basestate, self->tzinfo); - Py_DECREF(basestate); - } - return result; + basestate = PyBytes_FromStringAndSize((char *)self->data, + _PyDateTime_TIME_DATASIZE); + if (basestate != NULL) { + if (! HASTZINFO(self) || self->tzinfo == Py_None) + result = PyTuple_Pack(1, basestate); + else + result = PyTuple_Pack(2, basestate, self->tzinfo); + Py_DECREF(basestate); + } + return result; } static PyObject * time_reduce(PyDateTime_Time *self, PyObject *arg) { - return Py_BuildValue("(ON)", Py_TYPE(self), time_getstate(self)); + return Py_BuildValue("(ON)", Py_TYPE(self), time_getstate(self)); } static PyMethodDef time_methods[] = { - {"isoformat", (PyCFunction)time_isoformat, METH_NOARGS, - PyDoc_STR("Return string in ISO 8601 format, HH:MM:SS[.mmmmmm]" - "[+HH:MM].")}, + {"isoformat", (PyCFunction)time_isoformat, METH_NOARGS, + PyDoc_STR("Return string in ISO 8601 format, HH:MM:SS[.mmmmmm]" + "[+HH:MM].")}, - {"strftime", (PyCFunction)time_strftime, METH_VARARGS | METH_KEYWORDS, - PyDoc_STR("format -> strftime() style string.")}, + {"strftime", (PyCFunction)time_strftime, METH_VARARGS | METH_KEYWORDS, + PyDoc_STR("format -> strftime() style string.")}, - {"__format__", (PyCFunction)date_format, METH_VARARGS, - PyDoc_STR("Formats self with strftime.")}, + {"__format__", (PyCFunction)date_format, METH_VARARGS, + PyDoc_STR("Formats self with strftime.")}, - {"utcoffset", (PyCFunction)time_utcoffset, METH_NOARGS, - PyDoc_STR("Return self.tzinfo.utcoffset(self).")}, + {"utcoffset", (PyCFunction)time_utcoffset, METH_NOARGS, + PyDoc_STR("Return self.tzinfo.utcoffset(self).")}, - {"tzname", (PyCFunction)time_tzname, METH_NOARGS, - PyDoc_STR("Return self.tzinfo.tzname(self).")}, + {"tzname", (PyCFunction)time_tzname, METH_NOARGS, + PyDoc_STR("Return self.tzinfo.tzname(self).")}, - {"dst", (PyCFunction)time_dst, METH_NOARGS, - PyDoc_STR("Return self.tzinfo.dst(self).")}, + {"dst", (PyCFunction)time_dst, METH_NOARGS, + PyDoc_STR("Return self.tzinfo.dst(self).")}, - {"replace", (PyCFunction)time_replace, METH_VARARGS | METH_KEYWORDS, - PyDoc_STR("Return time with new specified fields.")}, + {"replace", (PyCFunction)time_replace, METH_VARARGS | METH_KEYWORDS, + PyDoc_STR("Return time with new specified fields.")}, - {"__reduce__", (PyCFunction)time_reduce, METH_NOARGS, - PyDoc_STR("__reduce__() -> (cls, state)")}, + {"__reduce__", (PyCFunction)time_reduce, METH_NOARGS, + PyDoc_STR("__reduce__() -> (cls, state)")}, - {NULL, NULL} + {NULL, NULL} }; static char time_doc[] = @@ -3630,58 +3630,58 @@ a tzinfo subclass. The remaining arguments may be ints or longs.\n"); static PyNumberMethods time_as_number = { - 0, /* nb_add */ - 0, /* nb_subtract */ - 0, /* nb_multiply */ - 0, /* nb_remainder */ - 0, /* nb_divmod */ - 0, /* nb_power */ - 0, /* nb_negative */ - 0, /* nb_positive */ - 0, /* nb_absolute */ - (inquiry)time_bool, /* nb_bool */ + 0, /* nb_add */ + 0, /* nb_subtract */ + 0, /* nb_multiply */ + 0, /* nb_remainder */ + 0, /* nb_divmod */ + 0, /* nb_power */ + 0, /* nb_negative */ + 0, /* nb_positive */ + 0, /* nb_absolute */ + (inquiry)time_bool, /* nb_bool */ }; static PyTypeObject PyDateTime_TimeType = { - PyVarObject_HEAD_INIT(NULL, 0) - "datetime.time", /* tp_name */ - sizeof(PyDateTime_Time), /* tp_basicsize */ - 0, /* tp_itemsize */ - (destructor)time_dealloc, /* tp_dealloc */ - 0, /* tp_print */ - 0, /* tp_getattr */ - 0, /* tp_setattr */ - 0, /* tp_reserved */ - (reprfunc)time_repr, /* tp_repr */ - &time_as_number, /* tp_as_number */ - 0, /* tp_as_sequence */ - 0, /* tp_as_mapping */ - (hashfunc)time_hash, /* tp_hash */ - 0, /* tp_call */ - (reprfunc)time_str, /* tp_str */ - PyObject_GenericGetAttr, /* tp_getattro */ - 0, /* tp_setattro */ - 0, /* tp_as_buffer */ - Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */ - time_doc, /* tp_doc */ - 0, /* tp_traverse */ - 0, /* tp_clear */ - time_richcompare, /* tp_richcompare */ - 0, /* tp_weaklistoffset */ - 0, /* tp_iter */ - 0, /* tp_iternext */ - time_methods, /* tp_methods */ - 0, /* tp_members */ - time_getset, /* tp_getset */ - 0, /* tp_base */ - 0, /* tp_dict */ - 0, /* tp_descr_get */ - 0, /* tp_descr_set */ - 0, /* tp_dictoffset */ - 0, /* tp_init */ - time_alloc, /* tp_alloc */ - time_new, /* tp_new */ - 0, /* tp_free */ + PyVarObject_HEAD_INIT(NULL, 0) + "datetime.time", /* tp_name */ + sizeof(PyDateTime_Time), /* tp_basicsize */ + 0, /* tp_itemsize */ + (destructor)time_dealloc, /* tp_dealloc */ + 0, /* tp_print */ + 0, /* tp_getattr */ + 0, /* tp_setattr */ + 0, /* tp_reserved */ + (reprfunc)time_repr, /* tp_repr */ + &time_as_number, /* tp_as_number */ + 0, /* tp_as_sequence */ + 0, /* tp_as_mapping */ + (hashfunc)time_hash, /* tp_hash */ + 0, /* tp_call */ + (reprfunc)time_str, /* tp_str */ + PyObject_GenericGetAttr, /* tp_getattro */ + 0, /* tp_setattro */ + 0, /* tp_as_buffer */ + Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */ + time_doc, /* tp_doc */ + 0, /* tp_traverse */ + 0, /* tp_clear */ + time_richcompare, /* tp_richcompare */ + 0, /* tp_weaklistoffset */ + 0, /* tp_iter */ + 0, /* tp_iternext */ + time_methods, /* tp_methods */ + 0, /* tp_members */ + time_getset, /* tp_getset */ + 0, /* tp_base */ + 0, /* tp_dict */ + 0, /* tp_descr_get */ + 0, /* tp_descr_set */ + 0, /* tp_dictoffset */ + 0, /* tp_init */ + time_alloc, /* tp_alloc */ + time_new, /* tp_new */ + 0, /* tp_free */ }; /* @@ -3695,42 +3695,42 @@ static PyObject * datetime_hour(PyDateTime_DateTime *self, void *unused) { - return PyLong_FromLong(DATE_GET_HOUR(self)); + return PyLong_FromLong(DATE_GET_HOUR(self)); } static PyObject * datetime_minute(PyDateTime_DateTime *self, void *unused) { - return PyLong_FromLong(DATE_GET_MINUTE(self)); + return PyLong_FromLong(DATE_GET_MINUTE(self)); } static PyObject * datetime_second(PyDateTime_DateTime *self, void *unused) { - return PyLong_FromLong(DATE_GET_SECOND(self)); + return PyLong_FromLong(DATE_GET_SECOND(self)); } static PyObject * datetime_microsecond(PyDateTime_DateTime *self, void *unused) { - return PyLong_FromLong(DATE_GET_MICROSECOND(self)); + return PyLong_FromLong(DATE_GET_MICROSECOND(self)); } static PyObject * datetime_tzinfo(PyDateTime_DateTime *self, void *unused) { - PyObject *result = HASTZINFO(self) ? self->tzinfo : Py_None; - Py_INCREF(result); - return result; + PyObject *result = HASTZINFO(self) ? self->tzinfo : Py_None; + Py_INCREF(result); + return result; } static PyGetSetDef datetime_getset[] = { - {"hour", (getter)datetime_hour}, - {"minute", (getter)datetime_minute}, - {"second", (getter)datetime_second}, - {"microsecond", (getter)datetime_microsecond}, - {"tzinfo", (getter)datetime_tzinfo}, - {NULL} + {"hour", (getter)datetime_hour}, + {"minute", (getter)datetime_minute}, + {"second", (getter)datetime_second}, + {"microsecond", (getter)datetime_microsecond}, + {"tzinfo", (getter)datetime_tzinfo}, + {NULL} }; /* @@ -3738,72 +3738,72 @@ */ static char *datetime_kws[] = { - "year", "month", "day", "hour", "minute", "second", - "microsecond", "tzinfo", NULL + "year", "month", "day", "hour", "minute", "second", + "microsecond", "tzinfo", NULL }; static PyObject * datetime_new(PyTypeObject *type, PyObject *args, PyObject *kw) { - PyObject *self = NULL; - PyObject *state; - int year; - int month; - int day; - int hour = 0; - int minute = 0; - int second = 0; - int usecond = 0; - PyObject *tzinfo = Py_None; - - /* Check for invocation from pickle with __getstate__ state */ - if (PyTuple_GET_SIZE(args) >= 1 && - PyTuple_GET_SIZE(args) <= 2 && - PyBytes_Check(state = PyTuple_GET_ITEM(args, 0)) && - PyBytes_GET_SIZE(state) == _PyDateTime_DATETIME_DATASIZE && - MONTH_IS_SANE(PyBytes_AS_STRING(state)[2])) - { - PyDateTime_DateTime *me; - char aware; - - if (PyTuple_GET_SIZE(args) == 2) { - tzinfo = PyTuple_GET_ITEM(args, 1); - if (check_tzinfo_subclass(tzinfo) < 0) { - PyErr_SetString(PyExc_TypeError, "bad " - "tzinfo state arg"); - return NULL; - } - } - aware = (char)(tzinfo != Py_None); - me = (PyDateTime_DateTime *) (type->tp_alloc(type , aware)); - if (me != NULL) { - char *pdata = PyBytes_AS_STRING(state); - - memcpy(me->data, pdata, _PyDateTime_DATETIME_DATASIZE); - me->hashcode = -1; - me->hastzinfo = aware; - if (aware) { - Py_INCREF(tzinfo); - me->tzinfo = tzinfo; - } - } - return (PyObject *)me; - } - - if (PyArg_ParseTupleAndKeywords(args, kw, "iii|iiiiO", datetime_kws, - &year, &month, &day, &hour, &minute, - &second, &usecond, &tzinfo)) { - if (check_date_args(year, month, day) < 0) - return NULL; - if (check_time_args(hour, minute, second, usecond) < 0) - return NULL; - if (check_tzinfo_subclass(tzinfo) < 0) - return NULL; - self = new_datetime_ex(year, month, day, - hour, minute, second, usecond, - tzinfo, type); - } - return self; + PyObject *self = NULL; + PyObject *state; + int year; + int month; + int day; + int hour = 0; + int minute = 0; + int second = 0; + int usecond = 0; + PyObject *tzinfo = Py_None; + + /* Check for invocation from pickle with __getstate__ state */ + if (PyTuple_GET_SIZE(args) >= 1 && + PyTuple_GET_SIZE(args) <= 2 && + PyBytes_Check(state = PyTuple_GET_ITEM(args, 0)) && + PyBytes_GET_SIZE(state) == _PyDateTime_DATETIME_DATASIZE && + MONTH_IS_SANE(PyBytes_AS_STRING(state)[2])) + { + PyDateTime_DateTime *me; + char aware; + + if (PyTuple_GET_SIZE(args) == 2) { + tzinfo = PyTuple_GET_ITEM(args, 1); + if (check_tzinfo_subclass(tzinfo) < 0) { + PyErr_SetString(PyExc_TypeError, "bad " + "tzinfo state arg"); + return NULL; + } + } + aware = (char)(tzinfo != Py_None); + me = (PyDateTime_DateTime *) (type->tp_alloc(type , aware)); + if (me != NULL) { + char *pdata = PyBytes_AS_STRING(state); + + memcpy(me->data, pdata, _PyDateTime_DATETIME_DATASIZE); + me->hashcode = -1; + me->hastzinfo = aware; + if (aware) { + Py_INCREF(tzinfo); + me->tzinfo = tzinfo; + } + } + return (PyObject *)me; + } + + if (PyArg_ParseTupleAndKeywords(args, kw, "iii|iiiiO", datetime_kws, + &year, &month, &day, &hour, &minute, + &second, &usecond, &tzinfo)) { + if (check_date_args(year, month, day) < 0) + return NULL; + if (check_time_args(hour, minute, second, usecond) < 0) + return NULL; + if (check_tzinfo_subclass(tzinfo) < 0) + return NULL; + self = new_datetime_ex(year, month, day, + hour, minute, second, usecond, + tzinfo, type); + } + return self; } /* TM_FUNC is the shared type of localtime() and gmtime(). */ @@ -3815,36 +3815,36 @@ */ static PyObject * datetime_from_timet_and_us(PyObject *cls, TM_FUNC f, time_t timet, int us, - PyObject *tzinfo) + PyObject *tzinfo) { - struct tm *tm; - PyObject *result = NULL; + struct tm *tm; + PyObject *result = NULL; - tm = f(&timet); - if (tm) { - /* The platform localtime/gmtime may insert leap seconds, - * indicated by tm->tm_sec > 59. We don't care about them, - * except to the extent that passing them on to the datetime - * constructor would raise ValueError for a reason that - * made no sense to the user. - */ - if (tm->tm_sec > 59) - tm->tm_sec = 59; - result = PyObject_CallFunction(cls, "iiiiiiiO", - tm->tm_year + 1900, - tm->tm_mon + 1, - tm->tm_mday, - tm->tm_hour, - tm->tm_min, - tm->tm_sec, - us, - tzinfo); - } - else - PyErr_SetString(PyExc_ValueError, - "timestamp out of range for " - "platform localtime()/gmtime() function"); - return result; + tm = f(&timet); + if (tm) { + /* The platform localtime/gmtime may insert leap seconds, + * indicated by tm->tm_sec > 59. We don't care about them, + * except to the extent that passing them on to the datetime + * constructor would raise ValueError for a reason that + * made no sense to the user. + */ + if (tm->tm_sec > 59) + tm->tm_sec = 59; + result = PyObject_CallFunction(cls, "iiiiiiiO", + tm->tm_year + 1900, + tm->tm_mon + 1, + tm->tm_mday, + tm->tm_hour, + tm->tm_min, + tm->tm_sec, + us, + tzinfo); + } + else + PyErr_SetString(PyExc_ValueError, + "timestamp out of range for " + "platform localtime()/gmtime() function"); + return result; } /* Internal helper. @@ -3856,31 +3856,31 @@ */ static PyObject * datetime_from_timestamp(PyObject *cls, TM_FUNC f, double timestamp, - PyObject *tzinfo) + PyObject *tzinfo) { - time_t timet; - double fraction; - int us; - - timet = _PyTime_DoubleToTimet(timestamp); - if (timet == (time_t)-1 && PyErr_Occurred()) - return NULL; - fraction = timestamp - (double)timet; - us = (int)round_to_long(fraction * 1e6); - if (us < 0) { - /* Truncation towards zero is not what we wanted - for negative numbers (Python's mod semantics) */ - timet -= 1; - us += 1000000; - } - /* If timestamp is less than one microsecond smaller than a - * full second, round up. Otherwise, ValueErrors are raised - * for some floats. */ - if (us == 1000000) { - timet += 1; - us = 0; - } - return datetime_from_timet_and_us(cls, f, timet, us, tzinfo); + time_t timet; + double fraction; + int us; + + timet = _PyTime_DoubleToTimet(timestamp); + if (timet == (time_t)-1 && PyErr_Occurred()) + return NULL; + fraction = timestamp - (double)timet; + us = (int)round_to_long(fraction * 1e6); + if (us < 0) { + /* Truncation towards zero is not what we wanted + for negative numbers (Python's mod semantics) */ + timet -= 1; + us += 1000000; + } + /* If timestamp is less than one microsecond smaller than a + * full second, round up. Otherwise, ValueErrors are raised + * for some floats. */ + if (us == 1000000) { + timet += 1; + us = 0; + } + return datetime_from_timet_and_us(cls, f, timet, us, tzinfo); } /* Internal helper. @@ -3891,36 +3891,36 @@ datetime_best_possible(PyObject *cls, TM_FUNC f, PyObject *tzinfo) { #ifdef HAVE_GETTIMEOFDAY - struct timeval t; + struct timeval t; #ifdef GETTIMEOFDAY_NO_TZ - gettimeofday(&t); + gettimeofday(&t); #else - gettimeofday(&t, (struct timezone *)NULL); + gettimeofday(&t, (struct timezone *)NULL); #endif - return datetime_from_timet_and_us(cls, f, t.tv_sec, (int)t.tv_usec, - tzinfo); + return datetime_from_timet_and_us(cls, f, t.tv_sec, (int)t.tv_usec, + tzinfo); -#else /* ! HAVE_GETTIMEOFDAY */ - /* No flavor of gettimeofday exists on this platform. Python's - * time.time() does a lot of other platform tricks to get the - * best time it can on the platform, and we're not going to do - * better than that (if we could, the better code would belong - * in time.time()!) We're limited by the precision of a double, - * though. - */ - PyObject *time; - double dtime; - - time = time_time(); - if (time == NULL) - return NULL; - dtime = PyFloat_AsDouble(time); - Py_DECREF(time); - if (dtime == -1.0 && PyErr_Occurred()) - return NULL; - return datetime_from_timestamp(cls, f, dtime, tzinfo); -#endif /* ! HAVE_GETTIMEOFDAY */ +#else /* ! HAVE_GETTIMEOFDAY */ + /* No flavor of gettimeofday exists on this platform. Python's + * time.time() does a lot of other platform tricks to get the + * best time it can on the platform, and we're not going to do + * better than that (if we could, the better code would belong + * in time.time()!) We're limited by the precision of a double, + * though. + */ + PyObject *time; + double dtime; + + time = time_time(); + if (time == NULL) + return NULL; + dtime = PyFloat_AsDouble(time); + Py_DECREF(time); + if (dtime == -1.0 && PyErr_Occurred()) + return NULL; + return datetime_from_timestamp(cls, f, dtime, tzinfo); +#endif /* ! HAVE_GETTIMEOFDAY */ } /* Return best possible local time -- this isn't constrained by the @@ -3929,26 +3929,26 @@ static PyObject * datetime_now(PyObject *cls, PyObject *args, PyObject *kw) { - PyObject *self; - PyObject *tzinfo = Py_None; - static char *keywords[] = {"tz", NULL}; - - if (! PyArg_ParseTupleAndKeywords(args, kw, "|O:now", keywords, - &tzinfo)) - return NULL; - if (check_tzinfo_subclass(tzinfo) < 0) - return NULL; - - self = datetime_best_possible(cls, - tzinfo == Py_None ? localtime : gmtime, - tzinfo); - if (self != NULL && tzinfo != Py_None) { - /* Convert UTC to tzinfo's zone. */ - PyObject *temp = self; - self = PyObject_CallMethod(tzinfo, "fromutc", "O", self); - Py_DECREF(temp); - } - return self; + PyObject *self; + PyObject *tzinfo = Py_None; + static char *keywords[] = {"tz", NULL}; + + if (! PyArg_ParseTupleAndKeywords(args, kw, "|O:now", keywords, + &tzinfo)) + return NULL; + if (check_tzinfo_subclass(tzinfo) < 0) + return NULL; + + self = datetime_best_possible(cls, + tzinfo == Py_None ? localtime : gmtime, + tzinfo); + if (self != NULL && tzinfo != Py_None) { + /* Convert UTC to tzinfo's zone. */ + PyObject *temp = self; + self = PyObject_CallMethod(tzinfo, "fromutc", "O", self); + Py_DECREF(temp); + } + return self; } /* Return best possible UTC time -- this isn't constrained by the @@ -3957,155 +3957,155 @@ static PyObject * datetime_utcnow(PyObject *cls, PyObject *dummy) { - return datetime_best_possible(cls, gmtime, Py_None); + return datetime_best_possible(cls, gmtime, Py_None); } /* Return new local datetime from timestamp (Python timestamp -- a double). */ static PyObject * datetime_fromtimestamp(PyObject *cls, PyObject *args, PyObject *kw) { - PyObject *self; - double timestamp; - PyObject *tzinfo = Py_None; - static char *keywords[] = {"timestamp", "tz", NULL}; - - if (! PyArg_ParseTupleAndKeywords(args, kw, "d|O:fromtimestamp", - keywords, ×tamp, &tzinfo)) - return NULL; - if (check_tzinfo_subclass(tzinfo) < 0) - return NULL; - - self = datetime_from_timestamp(cls, - tzinfo == Py_None ? localtime : gmtime, - timestamp, - tzinfo); - if (self != NULL && tzinfo != Py_None) { - /* Convert UTC to tzinfo's zone. */ - PyObject *temp = self; - self = PyObject_CallMethod(tzinfo, "fromutc", "O", self); - Py_DECREF(temp); - } - return self; + PyObject *self; + double timestamp; + PyObject *tzinfo = Py_None; + static char *keywords[] = {"timestamp", "tz", NULL}; + + if (! PyArg_ParseTupleAndKeywords(args, kw, "d|O:fromtimestamp", + keywords, ×tamp, &tzinfo)) + return NULL; + if (check_tzinfo_subclass(tzinfo) < 0) + return NULL; + + self = datetime_from_timestamp(cls, + tzinfo == Py_None ? localtime : gmtime, + timestamp, + tzinfo); + if (self != NULL && tzinfo != Py_None) { + /* Convert UTC to tzinfo's zone. */ + PyObject *temp = self; + self = PyObject_CallMethod(tzinfo, "fromutc", "O", self); + Py_DECREF(temp); + } + return self; } /* Return new UTC datetime from timestamp (Python timestamp -- a double). */ static PyObject * datetime_utcfromtimestamp(PyObject *cls, PyObject *args) { - double timestamp; - PyObject *result = NULL; + double timestamp; + PyObject *result = NULL; - if (PyArg_ParseTuple(args, "d:utcfromtimestamp", ×tamp)) - result = datetime_from_timestamp(cls, gmtime, timestamp, - Py_None); - return result; + if (PyArg_ParseTuple(args, "d:utcfromtimestamp", ×tamp)) + result = datetime_from_timestamp(cls, gmtime, timestamp, + Py_None); + return result; } /* Return new datetime from time.strptime(). */ static PyObject * datetime_strptime(PyObject *cls, PyObject *args) { - static PyObject *module = NULL; - PyObject *result = NULL, *obj, *st = NULL, *frac = NULL; - const Py_UNICODE *string, *format; - - if (!PyArg_ParseTuple(args, "uu:strptime", &string, &format)) - return NULL; - - if (module == NULL && - (module = PyImport_ImportModuleNoBlock("_strptime")) == NULL) - return NULL; - - /* _strptime._strptime returns a two-element tuple. The first - element is a time.struct_time object. The second is the - microseconds (which are not defined for time.struct_time). */ - obj = PyObject_CallMethod(module, "_strptime", "uu", string, format); - if (obj != NULL) { - int i, good_timetuple = 1; - long int ia[7]; - if (PySequence_Check(obj) && PySequence_Size(obj) == 2) { - st = PySequence_GetItem(obj, 0); - frac = PySequence_GetItem(obj, 1); - if (st == NULL || frac == NULL) - good_timetuple = 0; - /* copy y/m/d/h/m/s values out of the - time.struct_time */ - if (good_timetuple && - PySequence_Check(st) && - PySequence_Size(st) >= 6) { - for (i=0; i < 6; i++) { - PyObject *p = PySequence_GetItem(st, i); - if (p == NULL) { - good_timetuple = 0; - break; - } - if (PyLong_Check(p)) - ia[i] = PyLong_AsLong(p); - else - good_timetuple = 0; - Py_DECREF(p); - } -/* if (PyLong_CheckExact(p)) { - ia[i] = PyLong_AsLongAndOverflow(p, &overflow); - if (overflow) - good_timetuple = 0; - } - else - good_timetuple = 0; - Py_DECREF(p); -*/ } - else - good_timetuple = 0; - /* follow that up with a little dose of microseconds */ - if (PyLong_Check(frac)) - ia[6] = PyLong_AsLong(frac); - else - good_timetuple = 0; - } - else - good_timetuple = 0; - if (good_timetuple) - result = PyObject_CallFunction(cls, "iiiiiii", - ia[0], ia[1], ia[2], - ia[3], ia[4], ia[5], - ia[6]); - else - PyErr_SetString(PyExc_ValueError, - "unexpected value from _strptime._strptime"); - } - Py_XDECREF(obj); - Py_XDECREF(st); - Py_XDECREF(frac); - return result; + static PyObject *module = NULL; + PyObject *result = NULL, *obj, *st = NULL, *frac = NULL; + const Py_UNICODE *string, *format; + + if (!PyArg_ParseTuple(args, "uu:strptime", &string, &format)) + return NULL; + + if (module == NULL && + (module = PyImport_ImportModuleNoBlock("_strptime")) == NULL) + return NULL; + + /* _strptime._strptime returns a two-element tuple. The first + element is a time.struct_time object. The second is the + microseconds (which are not defined for time.struct_time). */ + obj = PyObject_CallMethod(module, "_strptime", "uu", string, format); + if (obj != NULL) { + int i, good_timetuple = 1; + long int ia[7]; + if (PySequence_Check(obj) && PySequence_Size(obj) == 2) { + st = PySequence_GetItem(obj, 0); + frac = PySequence_GetItem(obj, 1); + if (st == NULL || frac == NULL) + good_timetuple = 0; + /* copy y/m/d/h/m/s values out of the + time.struct_time */ + if (good_timetuple && + PySequence_Check(st) && + PySequence_Size(st) >= 6) { + for (i=0; i < 6; i++) { + PyObject *p = PySequence_GetItem(st, i); + if (p == NULL) { + good_timetuple = 0; + break; + } + if (PyLong_Check(p)) + ia[i] = PyLong_AsLong(p); + else + good_timetuple = 0; + Py_DECREF(p); + } +/* if (PyLong_CheckExact(p)) { + ia[i] = PyLong_AsLongAndOverflow(p, &overflow); + if (overflow) + good_timetuple = 0; + } + else + good_timetuple = 0; + Py_DECREF(p); +*/ } + else + good_timetuple = 0; + /* follow that up with a little dose of microseconds */ + if (PyLong_Check(frac)) + ia[6] = PyLong_AsLong(frac); + else + good_timetuple = 0; + } + else + good_timetuple = 0; + if (good_timetuple) + result = PyObject_CallFunction(cls, "iiiiiii", + ia[0], ia[1], ia[2], + ia[3], ia[4], ia[5], + ia[6]); + else + PyErr_SetString(PyExc_ValueError, + "unexpected value from _strptime._strptime"); + } + Py_XDECREF(obj); + Py_XDECREF(st); + Py_XDECREF(frac); + return result; } /* Return new datetime from date/datetime and time arguments. */ static PyObject * datetime_combine(PyObject *cls, PyObject *args, PyObject *kw) { - static char *keywords[] = {"date", "time", NULL}; - PyObject *date; - PyObject *time; - PyObject *result = NULL; - - if (PyArg_ParseTupleAndKeywords(args, kw, "O!O!:combine", keywords, - &PyDateTime_DateType, &date, - &PyDateTime_TimeType, &time)) { - PyObject *tzinfo = Py_None; - - if (HASTZINFO(time)) - tzinfo = ((PyDateTime_Time *)time)->tzinfo; - result = PyObject_CallFunction(cls, "iiiiiiiO", - GET_YEAR(date), - GET_MONTH(date), - GET_DAY(date), - TIME_GET_HOUR(time), - TIME_GET_MINUTE(time), - TIME_GET_SECOND(time), - TIME_GET_MICROSECOND(time), - tzinfo); - } - return result; + static char *keywords[] = {"date", "time", NULL}; + PyObject *date; + PyObject *time; + PyObject *result = NULL; + + if (PyArg_ParseTupleAndKeywords(args, kw, "O!O!:combine", keywords, + &PyDateTime_DateType, &date, + &PyDateTime_TimeType, &time)) { + PyObject *tzinfo = Py_None; + + if (HASTZINFO(time)) + tzinfo = ((PyDateTime_Time *)time)->tzinfo; + result = PyObject_CallFunction(cls, "iiiiiiiO", + GET_YEAR(date), + GET_MONTH(date), + GET_DAY(date), + TIME_GET_HOUR(time), + TIME_GET_MINUTE(time), + TIME_GET_SECOND(time), + TIME_GET_MICROSECOND(time), + tzinfo); + } + return result; } /* @@ -4115,10 +4115,10 @@ static void datetime_dealloc(PyDateTime_DateTime *self) { - if (HASTZINFO(self)) { - Py_XDECREF(self->tzinfo); - } - Py_TYPE(self)->tp_free((PyObject *)self); + if (HASTZINFO(self)) { + Py_XDECREF(self->tzinfo); + } + Py_TYPE(self)->tp_free((PyObject *)self); } /* @@ -4128,20 +4128,20 @@ /* These are all METH_NOARGS, so don't need to check the arglist. */ static PyObject * datetime_utcoffset(PyDateTime_DateTime *self, PyObject *unused) { - return offset_as_timedelta(HASTZINFO(self) ? self->tzinfo : Py_None, - "utcoffset", (PyObject *)self); + return offset_as_timedelta(HASTZINFO(self) ? self->tzinfo : Py_None, + "utcoffset", (PyObject *)self); } static PyObject * datetime_dst(PyDateTime_DateTime *self, PyObject *unused) { - return offset_as_timedelta(HASTZINFO(self) ? self->tzinfo : Py_None, - "dst", (PyObject *)self); + return offset_as_timedelta(HASTZINFO(self) ? self->tzinfo : Py_None, + "dst", (PyObject *)self); } static PyObject * datetime_tzname(PyDateTime_DateTime *self, PyObject *unused) { - return call_tzname(HASTZINFO(self) ? self->tzinfo : Py_None, - (PyObject *)self); + return call_tzname(HASTZINFO(self) ? self->tzinfo : Py_None, + (PyObject *)self); } /* @@ -4153,112 +4153,112 @@ */ static PyObject * add_datetime_timedelta(PyDateTime_DateTime *date, PyDateTime_Delta *delta, - int factor) + int factor) { - /* Note that the C-level additions can't overflow, because of - * invariant bounds on the member values. - */ - int year = GET_YEAR(date); - int month = GET_MONTH(date); - int day = GET_DAY(date) + GET_TD_DAYS(delta) * factor; - int hour = DATE_GET_HOUR(date); - int minute = DATE_GET_MINUTE(date); - int second = DATE_GET_SECOND(date) + GET_TD_SECONDS(delta) * factor; - int microsecond = DATE_GET_MICROSECOND(date) + - GET_TD_MICROSECONDS(delta) * factor; - - assert(factor == 1 || factor == -1); - if (normalize_datetime(&year, &month, &day, - &hour, &minute, &second, µsecond) < 0) - return NULL; - else - return new_datetime(year, month, day, - hour, minute, second, microsecond, - HASTZINFO(date) ? date->tzinfo : Py_None); + /* Note that the C-level additions can't overflow, because of + * invariant bounds on the member values. + */ + int year = GET_YEAR(date); + int month = GET_MONTH(date); + int day = GET_DAY(date) + GET_TD_DAYS(delta) * factor; + int hour = DATE_GET_HOUR(date); + int minute = DATE_GET_MINUTE(date); + int second = DATE_GET_SECOND(date) + GET_TD_SECONDS(delta) * factor; + int microsecond = DATE_GET_MICROSECOND(date) + + GET_TD_MICROSECONDS(delta) * factor; + + assert(factor == 1 || factor == -1); + if (normalize_datetime(&year, &month, &day, + &hour, &minute, &second, µsecond) < 0) + return NULL; + else + return new_datetime(year, month, day, + hour, minute, second, microsecond, + HASTZINFO(date) ? date->tzinfo : Py_None); } static PyObject * datetime_add(PyObject *left, PyObject *right) { - if (PyDateTime_Check(left)) { - /* datetime + ??? */ - if (PyDelta_Check(right)) - /* datetime + delta */ - return add_datetime_timedelta( - (PyDateTime_DateTime *)left, - (PyDateTime_Delta *)right, - 1); - } - else if (PyDelta_Check(left)) { - /* delta + datetime */ - return add_datetime_timedelta((PyDateTime_DateTime *) right, - (PyDateTime_Delta *) left, - 1); - } - Py_INCREF(Py_NotImplemented); - return Py_NotImplemented; + if (PyDateTime_Check(left)) { + /* datetime + ??? */ + if (PyDelta_Check(right)) + /* datetime + delta */ + return add_datetime_timedelta( + (PyDateTime_DateTime *)left, + (PyDateTime_Delta *)right, + 1); + } + else if (PyDelta_Check(left)) { + /* delta + datetime */ + return add_datetime_timedelta((PyDateTime_DateTime *) right, + (PyDateTime_Delta *) left, + 1); + } + Py_INCREF(Py_NotImplemented); + return Py_NotImplemented; } static PyObject * datetime_subtract(PyObject *left, PyObject *right) { - PyObject *result = Py_NotImplemented; + PyObject *result = Py_NotImplemented; - if (PyDateTime_Check(left)) { - /* datetime - ??? */ - if (PyDateTime_Check(right)) { - /* datetime - datetime */ - naivety n1, n2; - int offset1, offset2; - int delta_d, delta_s, delta_us; - - if (classify_two_utcoffsets(left, &offset1, &n1, left, - right, &offset2, &n2, - right) < 0) - return NULL; - assert(n1 != OFFSET_UNKNOWN && n2 != OFFSET_UNKNOWN); - if (n1 != n2) { - PyErr_SetString(PyExc_TypeError, - "can't subtract offset-naive and " - "offset-aware datetimes"); - return NULL; - } - delta_d = ymd_to_ord(GET_YEAR(left), - GET_MONTH(left), - GET_DAY(left)) - - ymd_to_ord(GET_YEAR(right), - GET_MONTH(right), - GET_DAY(right)); - /* These can't overflow, since the values are - * normalized. At most this gives the number of - * seconds in one day. - */ - delta_s = (DATE_GET_HOUR(left) - - DATE_GET_HOUR(right)) * 3600 + - (DATE_GET_MINUTE(left) - - DATE_GET_MINUTE(right)) * 60 + - (DATE_GET_SECOND(left) - - DATE_GET_SECOND(right)); - delta_us = DATE_GET_MICROSECOND(left) - - DATE_GET_MICROSECOND(right); - /* (left - offset1) - (right - offset2) = - * (left - right) + (offset2 - offset1) - */ - delta_s += (offset2 - offset1) * 60; - result = new_delta(delta_d, delta_s, delta_us, 1); - } - else if (PyDelta_Check(right)) { - /* datetime - delta */ - result = add_datetime_timedelta( - (PyDateTime_DateTime *)left, - (PyDateTime_Delta *)right, - -1); - } - } - - if (result == Py_NotImplemented) - Py_INCREF(result); - return result; + if (PyDateTime_Check(left)) { + /* datetime - ??? */ + if (PyDateTime_Check(right)) { + /* datetime - datetime */ + naivety n1, n2; + int offset1, offset2; + int delta_d, delta_s, delta_us; + + if (classify_two_utcoffsets(left, &offset1, &n1, left, + right, &offset2, &n2, + right) < 0) + return NULL; + assert(n1 != OFFSET_UNKNOWN && n2 != OFFSET_UNKNOWN); + if (n1 != n2) { + PyErr_SetString(PyExc_TypeError, + "can't subtract offset-naive and " + "offset-aware datetimes"); + return NULL; + } + delta_d = ymd_to_ord(GET_YEAR(left), + GET_MONTH(left), + GET_DAY(left)) - + ymd_to_ord(GET_YEAR(right), + GET_MONTH(right), + GET_DAY(right)); + /* These can't overflow, since the values are + * normalized. At most this gives the number of + * seconds in one day. + */ + delta_s = (DATE_GET_HOUR(left) - + DATE_GET_HOUR(right)) * 3600 + + (DATE_GET_MINUTE(left) - + DATE_GET_MINUTE(right)) * 60 + + (DATE_GET_SECOND(left) - + DATE_GET_SECOND(right)); + delta_us = DATE_GET_MICROSECOND(left) - + DATE_GET_MICROSECOND(right); + /* (left - offset1) - (right - offset2) = + * (left - right) + (offset2 - offset1) + */ + delta_s += (offset2 - offset1) * 60; + result = new_delta(delta_d, delta_s, delta_us, 1); + } + else if (PyDelta_Check(right)) { + /* datetime - delta */ + result = add_datetime_timedelta( + (PyDateTime_DateTime *)left, + (PyDateTime_Delta *)right, + -1); + } + } + + if (result == Py_NotImplemented) + Py_INCREF(result); + return result; } /* Various ways to turn a datetime into a string. */ @@ -4266,88 +4266,88 @@ static PyObject * datetime_repr(PyDateTime_DateTime *self) { - const char *type_name = Py_TYPE(self)->tp_name; - PyObject *baserepr; + const char *type_name = Py_TYPE(self)->tp_name; + PyObject *baserepr; - if (DATE_GET_MICROSECOND(self)) { - baserepr = PyUnicode_FromFormat( - "%s(%d, %d, %d, %d, %d, %d, %d)", - type_name, - GET_YEAR(self), GET_MONTH(self), GET_DAY(self), - DATE_GET_HOUR(self), DATE_GET_MINUTE(self), - DATE_GET_SECOND(self), - DATE_GET_MICROSECOND(self)); - } - else if (DATE_GET_SECOND(self)) { - baserepr = PyUnicode_FromFormat( - "%s(%d, %d, %d, %d, %d, %d)", - type_name, - GET_YEAR(self), GET_MONTH(self), GET_DAY(self), - DATE_GET_HOUR(self), DATE_GET_MINUTE(self), - DATE_GET_SECOND(self)); - } - else { - baserepr = PyUnicode_FromFormat( - "%s(%d, %d, %d, %d, %d)", - type_name, - GET_YEAR(self), GET_MONTH(self), GET_DAY(self), - DATE_GET_HOUR(self), DATE_GET_MINUTE(self)); - } - if (baserepr == NULL || ! HASTZINFO(self)) - return baserepr; - return append_keyword_tzinfo(baserepr, self->tzinfo); + if (DATE_GET_MICROSECOND(self)) { + baserepr = PyUnicode_FromFormat( + "%s(%d, %d, %d, %d, %d, %d, %d)", + type_name, + GET_YEAR(self), GET_MONTH(self), GET_DAY(self), + DATE_GET_HOUR(self), DATE_GET_MINUTE(self), + DATE_GET_SECOND(self), + DATE_GET_MICROSECOND(self)); + } + else if (DATE_GET_SECOND(self)) { + baserepr = PyUnicode_FromFormat( + "%s(%d, %d, %d, %d, %d, %d)", + type_name, + GET_YEAR(self), GET_MONTH(self), GET_DAY(self), + DATE_GET_HOUR(self), DATE_GET_MINUTE(self), + DATE_GET_SECOND(self)); + } + else { + baserepr = PyUnicode_FromFormat( + "%s(%d, %d, %d, %d, %d)", + type_name, + GET_YEAR(self), GET_MONTH(self), GET_DAY(self), + DATE_GET_HOUR(self), DATE_GET_MINUTE(self)); + } + if (baserepr == NULL || ! HASTZINFO(self)) + return baserepr; + return append_keyword_tzinfo(baserepr, self->tzinfo); } static PyObject * datetime_str(PyDateTime_DateTime *self) { - return PyObject_CallMethod((PyObject *)self, "isoformat", "(s)", " "); + return PyObject_CallMethod((PyObject *)self, "isoformat", "(s)", " "); } static PyObject * datetime_isoformat(PyDateTime_DateTime *self, PyObject *args, PyObject *kw) { - int sep = 'T'; - static char *keywords[] = {"sep", NULL}; - char buffer[100]; - PyObject *result; - int us = DATE_GET_MICROSECOND(self); - - if (!PyArg_ParseTupleAndKeywords(args, kw, "|C:isoformat", keywords, &sep)) - return NULL; - if (us) - result = PyUnicode_FromFormat("%04d-%02d-%02d%c%02d:%02d:%02d.%06d", - GET_YEAR(self), GET_MONTH(self), - GET_DAY(self), (int)sep, - DATE_GET_HOUR(self), DATE_GET_MINUTE(self), - DATE_GET_SECOND(self), us); - else - result = PyUnicode_FromFormat("%04d-%02d-%02d%c%02d:%02d:%02d", - GET_YEAR(self), GET_MONTH(self), - GET_DAY(self), (int)sep, - DATE_GET_HOUR(self), DATE_GET_MINUTE(self), - DATE_GET_SECOND(self)); - - if (!result || !HASTZINFO(self)) - return result; - - /* We need to append the UTC offset. */ - if (format_utcoffset(buffer, sizeof(buffer), ":", self->tzinfo, - (PyObject *)self) < 0) { - Py_DECREF(result); - return NULL; - } - PyUnicode_AppendAndDel(&result, PyUnicode_FromString(buffer)); - return result; + int sep = 'T'; + static char *keywords[] = {"sep", NULL}; + char buffer[100]; + PyObject *result; + int us = DATE_GET_MICROSECOND(self); + + if (!PyArg_ParseTupleAndKeywords(args, kw, "|C:isoformat", keywords, &sep)) + return NULL; + if (us) + result = PyUnicode_FromFormat("%04d-%02d-%02d%c%02d:%02d:%02d.%06d", + GET_YEAR(self), GET_MONTH(self), + GET_DAY(self), (int)sep, + DATE_GET_HOUR(self), DATE_GET_MINUTE(self), + DATE_GET_SECOND(self), us); + else + result = PyUnicode_FromFormat("%04d-%02d-%02d%c%02d:%02d:%02d", + GET_YEAR(self), GET_MONTH(self), + GET_DAY(self), (int)sep, + DATE_GET_HOUR(self), DATE_GET_MINUTE(self), + DATE_GET_SECOND(self)); + + if (!result || !HASTZINFO(self)) + return result; + + /* We need to append the UTC offset. */ + if (format_utcoffset(buffer, sizeof(buffer), ":", self->tzinfo, + (PyObject *)self) < 0) { + Py_DECREF(result); + return NULL; + } + PyUnicode_AppendAndDel(&result, PyUnicode_FromString(buffer)); + return result; } static PyObject * datetime_ctime(PyDateTime_DateTime *self) { - return format_ctime((PyDateTime_Date *)self, - DATE_GET_HOUR(self), - DATE_GET_MINUTE(self), - DATE_GET_SECOND(self)); + return format_ctime((PyDateTime_Date *)self, + DATE_GET_HOUR(self), + DATE_GET_MINUTE(self), + DATE_GET_SECOND(self)); } /* Miscellaneous methods. */ @@ -4355,292 +4355,292 @@ static PyObject * datetime_richcompare(PyObject *self, PyObject *other, int op) { - int diff; - naivety n1, n2; - int offset1, offset2; - - if (! PyDateTime_Check(other)) { - if (PyDate_Check(other)) { - /* Prevent invocation of date_richcompare. We want to - return NotImplemented here to give the other object - a chance. But since DateTime is a subclass of - Date, if the other object is a Date, it would - compute an ordering based on the date part alone, - and we don't want that. So force unequal or - uncomparable here in that case. */ - if (op == Py_EQ) - Py_RETURN_FALSE; - if (op == Py_NE) - Py_RETURN_TRUE; - return cmperror(self, other); - } - Py_INCREF(Py_NotImplemented); - return Py_NotImplemented; - } - - if (classify_two_utcoffsets(self, &offset1, &n1, self, - other, &offset2, &n2, other) < 0) - return NULL; - assert(n1 != OFFSET_UNKNOWN && n2 != OFFSET_UNKNOWN); - /* If they're both naive, or both aware and have the same offsets, - * we get off cheap. Note that if they're both naive, offset1 == - * offset2 == 0 at this point. - */ - if (n1 == n2 && offset1 == offset2) { - diff = memcmp(((PyDateTime_DateTime *)self)->data, - ((PyDateTime_DateTime *)other)->data, - _PyDateTime_DATETIME_DATASIZE); - return diff_to_bool(diff, op); - } - - if (n1 == OFFSET_AWARE && n2 == OFFSET_AWARE) { - PyDateTime_Delta *delta; - - assert(offset1 != offset2); /* else last "if" handled it */ - delta = (PyDateTime_Delta *)datetime_subtract((PyObject *)self, - other); - if (delta == NULL) - return NULL; - diff = GET_TD_DAYS(delta); - if (diff == 0) - diff = GET_TD_SECONDS(delta) | - GET_TD_MICROSECONDS(delta); - Py_DECREF(delta); - return diff_to_bool(diff, op); - } - - assert(n1 != n2); - PyErr_SetString(PyExc_TypeError, - "can't compare offset-naive and " - "offset-aware datetimes"); - return NULL; + int diff; + naivety n1, n2; + int offset1, offset2; + + if (! PyDateTime_Check(other)) { + if (PyDate_Check(other)) { + /* Prevent invocation of date_richcompare. We want to + return NotImplemented here to give the other object + a chance. But since DateTime is a subclass of + Date, if the other object is a Date, it would + compute an ordering based on the date part alone, + and we don't want that. So force unequal or + uncomparable here in that case. */ + if (op == Py_EQ) + Py_RETURN_FALSE; + if (op == Py_NE) + Py_RETURN_TRUE; + return cmperror(self, other); + } + Py_INCREF(Py_NotImplemented); + return Py_NotImplemented; + } + + if (classify_two_utcoffsets(self, &offset1, &n1, self, + other, &offset2, &n2, other) < 0) + return NULL; + assert(n1 != OFFSET_UNKNOWN && n2 != OFFSET_UNKNOWN); + /* If they're both naive, or both aware and have the same offsets, + * we get off cheap. Note that if they're both naive, offset1 == + * offset2 == 0 at this point. + */ + if (n1 == n2 && offset1 == offset2) { + diff = memcmp(((PyDateTime_DateTime *)self)->data, + ((PyDateTime_DateTime *)other)->data, + _PyDateTime_DATETIME_DATASIZE); + return diff_to_bool(diff, op); + } + + if (n1 == OFFSET_AWARE && n2 == OFFSET_AWARE) { + PyDateTime_Delta *delta; + + assert(offset1 != offset2); /* else last "if" handled it */ + delta = (PyDateTime_Delta *)datetime_subtract((PyObject *)self, + other); + if (delta == NULL) + return NULL; + diff = GET_TD_DAYS(delta); + if (diff == 0) + diff = GET_TD_SECONDS(delta) | + GET_TD_MICROSECONDS(delta); + Py_DECREF(delta); + return diff_to_bool(diff, op); + } + + assert(n1 != n2); + PyErr_SetString(PyExc_TypeError, + "can't compare offset-naive and " + "offset-aware datetimes"); + return NULL; } static long datetime_hash(PyDateTime_DateTime *self) { - if (self->hashcode == -1) { - naivety n; - int offset; - PyObject *temp; - - n = classify_utcoffset((PyObject *)self, (PyObject *)self, - &offset); - assert(n != OFFSET_UNKNOWN); - if (n == OFFSET_ERROR) - return -1; - - /* Reduce this to a hash of another object. */ - if (n == OFFSET_NAIVE) { - self->hashcode = generic_hash( - (unsigned char *)self->data, _PyDateTime_DATETIME_DATASIZE); - return self->hashcode; - } - else { - int days; - int seconds; - - assert(n == OFFSET_AWARE); - assert(HASTZINFO(self)); - days = ymd_to_ord(GET_YEAR(self), - GET_MONTH(self), - GET_DAY(self)); - seconds = DATE_GET_HOUR(self) * 3600 + - (DATE_GET_MINUTE(self) - offset) * 60 + - DATE_GET_SECOND(self); - temp = new_delta(days, - seconds, - DATE_GET_MICROSECOND(self), - 1); - } - if (temp != NULL) { - self->hashcode = PyObject_Hash(temp); - Py_DECREF(temp); - } - } - return self->hashcode; + if (self->hashcode == -1) { + naivety n; + int offset; + PyObject *temp; + + n = classify_utcoffset((PyObject *)self, (PyObject *)self, + &offset); + assert(n != OFFSET_UNKNOWN); + if (n == OFFSET_ERROR) + return -1; + + /* Reduce this to a hash of another object. */ + if (n == OFFSET_NAIVE) { + self->hashcode = generic_hash( + (unsigned char *)self->data, _PyDateTime_DATETIME_DATASIZE); + return self->hashcode; + } + else { + int days; + int seconds; + + assert(n == OFFSET_AWARE); + assert(HASTZINFO(self)); + days = ymd_to_ord(GET_YEAR(self), + GET_MONTH(self), + GET_DAY(self)); + seconds = DATE_GET_HOUR(self) * 3600 + + (DATE_GET_MINUTE(self) - offset) * 60 + + DATE_GET_SECOND(self); + temp = new_delta(days, + seconds, + DATE_GET_MICROSECOND(self), + 1); + } + if (temp != NULL) { + self->hashcode = PyObject_Hash(temp); + Py_DECREF(temp); + } + } + return self->hashcode; } static PyObject * datetime_replace(PyDateTime_DateTime *self, PyObject *args, PyObject *kw) { - PyObject *clone; - PyObject *tuple; - int y = GET_YEAR(self); - int m = GET_MONTH(self); - int d = GET_DAY(self); - int hh = DATE_GET_HOUR(self); - int mm = DATE_GET_MINUTE(self); - int ss = DATE_GET_SECOND(self); - int us = DATE_GET_MICROSECOND(self); - PyObject *tzinfo = HASTZINFO(self) ? self->tzinfo : Py_None; - - if (! PyArg_ParseTupleAndKeywords(args, kw, "|iiiiiiiO:replace", - datetime_kws, - &y, &m, &d, &hh, &mm, &ss, &us, - &tzinfo)) - return NULL; - tuple = Py_BuildValue("iiiiiiiO", y, m, d, hh, mm, ss, us, tzinfo); - if (tuple == NULL) - return NULL; - clone = datetime_new(Py_TYPE(self), tuple, NULL); - Py_DECREF(tuple); - return clone; + PyObject *clone; + PyObject *tuple; + int y = GET_YEAR(self); + int m = GET_MONTH(self); + int d = GET_DAY(self); + int hh = DATE_GET_HOUR(self); + int mm = DATE_GET_MINUTE(self); + int ss = DATE_GET_SECOND(self); + int us = DATE_GET_MICROSECOND(self); + PyObject *tzinfo = HASTZINFO(self) ? self->tzinfo : Py_None; + + if (! PyArg_ParseTupleAndKeywords(args, kw, "|iiiiiiiO:replace", + datetime_kws, + &y, &m, &d, &hh, &mm, &ss, &us, + &tzinfo)) + return NULL; + tuple = Py_BuildValue("iiiiiiiO", y, m, d, hh, mm, ss, us, tzinfo); + if (tuple == NULL) + return NULL; + clone = datetime_new(Py_TYPE(self), tuple, NULL); + Py_DECREF(tuple); + return clone; } static PyObject * datetime_astimezone(PyDateTime_DateTime *self, PyObject *args, PyObject *kw) { - int y, m, d, hh, mm, ss, us; - PyObject *result; - int offset, none; - - PyObject *tzinfo; - static char *keywords[] = {"tz", NULL}; - - if (! PyArg_ParseTupleAndKeywords(args, kw, "O!:astimezone", keywords, - &PyDateTime_TZInfoType, &tzinfo)) - return NULL; - - if (!HASTZINFO(self) || self->tzinfo == Py_None) - goto NeedAware; - - /* Conversion to self's own time zone is a NOP. */ - if (self->tzinfo == tzinfo) { - Py_INCREF(self); - return (PyObject *)self; - } - - /* Convert self to UTC. */ - offset = call_utcoffset(self->tzinfo, (PyObject *)self, &none); - if (offset == -1 && PyErr_Occurred()) - return NULL; - if (none) - goto NeedAware; - - y = GET_YEAR(self); - m = GET_MONTH(self); - d = GET_DAY(self); - hh = DATE_GET_HOUR(self); - mm = DATE_GET_MINUTE(self); - ss = DATE_GET_SECOND(self); - us = DATE_GET_MICROSECOND(self); - - mm -= offset; - if ((mm < 0 || mm >= 60) && - normalize_datetime(&y, &m, &d, &hh, &mm, &ss, &us) < 0) - return NULL; - - /* Attach new tzinfo and let fromutc() do the rest. */ - result = new_datetime(y, m, d, hh, mm, ss, us, tzinfo); - if (result != NULL) { - PyObject *temp = result; - - result = PyObject_CallMethod(tzinfo, "fromutc", "O", temp); - Py_DECREF(temp); - } - return result; + int y, m, d, hh, mm, ss, us; + PyObject *result; + int offset, none; + + PyObject *tzinfo; + static char *keywords[] = {"tz", NULL}; + + if (! PyArg_ParseTupleAndKeywords(args, kw, "O!:astimezone", keywords, + &PyDateTime_TZInfoType, &tzinfo)) + return NULL; + + if (!HASTZINFO(self) || self->tzinfo == Py_None) + goto NeedAware; + + /* Conversion to self's own time zone is a NOP. */ + if (self->tzinfo == tzinfo) { + Py_INCREF(self); + return (PyObject *)self; + } + + /* Convert self to UTC. */ + offset = call_utcoffset(self->tzinfo, (PyObject *)self, &none); + if (offset == -1 && PyErr_Occurred()) + return NULL; + if (none) + goto NeedAware; + + y = GET_YEAR(self); + m = GET_MONTH(self); + d = GET_DAY(self); + hh = DATE_GET_HOUR(self); + mm = DATE_GET_MINUTE(self); + ss = DATE_GET_SECOND(self); + us = DATE_GET_MICROSECOND(self); + + mm -= offset; + if ((mm < 0 || mm >= 60) && + normalize_datetime(&y, &m, &d, &hh, &mm, &ss, &us) < 0) + return NULL; + + /* Attach new tzinfo and let fromutc() do the rest. */ + result = new_datetime(y, m, d, hh, mm, ss, us, tzinfo); + if (result != NULL) { + PyObject *temp = result; + + result = PyObject_CallMethod(tzinfo, "fromutc", "O", temp); + Py_DECREF(temp); + } + return result; NeedAware: - PyErr_SetString(PyExc_ValueError, "astimezone() cannot be applied to " - "a naive datetime"); - return NULL; + PyErr_SetString(PyExc_ValueError, "astimezone() cannot be applied to " + "a naive datetime"); + return NULL; } static PyObject * datetime_timetuple(PyDateTime_DateTime *self) { - int dstflag = -1; + int dstflag = -1; - if (HASTZINFO(self) && self->tzinfo != Py_None) { - int none; + if (HASTZINFO(self) && self->tzinfo != Py_None) { + int none; - dstflag = call_dst(self->tzinfo, (PyObject *)self, &none); - if (dstflag == -1 && PyErr_Occurred()) - return NULL; - - if (none) - dstflag = -1; - else if (dstflag != 0) - dstflag = 1; - - } - return build_struct_time(GET_YEAR(self), - GET_MONTH(self), - GET_DAY(self), - DATE_GET_HOUR(self), - DATE_GET_MINUTE(self), - DATE_GET_SECOND(self), - dstflag); + dstflag = call_dst(self->tzinfo, (PyObject *)self, &none); + if (dstflag == -1 && PyErr_Occurred()) + return NULL; + + if (none) + dstflag = -1; + else if (dstflag != 0) + dstflag = 1; + + } + return build_struct_time(GET_YEAR(self), + GET_MONTH(self), + GET_DAY(self), + DATE_GET_HOUR(self), + DATE_GET_MINUTE(self), + DATE_GET_SECOND(self), + dstflag); } static PyObject * datetime_getdate(PyDateTime_DateTime *self) { - return new_date(GET_YEAR(self), - GET_MONTH(self), - GET_DAY(self)); + return new_date(GET_YEAR(self), + GET_MONTH(self), + GET_DAY(self)); } static PyObject * datetime_gettime(PyDateTime_DateTime *self) { - return new_time(DATE_GET_HOUR(self), - DATE_GET_MINUTE(self), - DATE_GET_SECOND(self), - DATE_GET_MICROSECOND(self), - Py_None); + return new_time(DATE_GET_HOUR(self), + DATE_GET_MINUTE(self), + DATE_GET_SECOND(self), + DATE_GET_MICROSECOND(self), + Py_None); } static PyObject * datetime_gettimetz(PyDateTime_DateTime *self) { - return new_time(DATE_GET_HOUR(self), - DATE_GET_MINUTE(self), - DATE_GET_SECOND(self), - DATE_GET_MICROSECOND(self), - HASTZINFO(self) ? self->tzinfo : Py_None); + return new_time(DATE_GET_HOUR(self), + DATE_GET_MINUTE(self), + DATE_GET_SECOND(self), + DATE_GET_MICROSECOND(self), + HASTZINFO(self) ? self->tzinfo : Py_None); } static PyObject * datetime_utctimetuple(PyDateTime_DateTime *self) { - int y = GET_YEAR(self); - int m = GET_MONTH(self); - int d = GET_DAY(self); - int hh = DATE_GET_HOUR(self); - int mm = DATE_GET_MINUTE(self); - int ss = DATE_GET_SECOND(self); - int us = 0; /* microseconds are ignored in a timetuple */ - int offset = 0; - - if (HASTZINFO(self) && self->tzinfo != Py_None) { - int none; - - offset = call_utcoffset(self->tzinfo, (PyObject *)self, &none); - if (offset == -1 && PyErr_Occurred()) - return NULL; - } - /* Even if offset is 0, don't call timetuple() -- tm_isdst should be - * 0 in a UTC timetuple regardless of what dst() says. - */ - if (offset) { - /* Subtract offset minutes & normalize. */ - int stat; - - mm -= offset; - stat = normalize_datetime(&y, &m, &d, &hh, &mm, &ss, &us); - if (stat < 0) { - /* At the edges, it's possible we overflowed - * beyond MINYEAR or MAXYEAR. - */ - if (PyErr_ExceptionMatches(PyExc_OverflowError)) - PyErr_Clear(); - else - return NULL; - } - } - return build_struct_time(y, m, d, hh, mm, ss, 0); + int y = GET_YEAR(self); + int m = GET_MONTH(self); + int d = GET_DAY(self); + int hh = DATE_GET_HOUR(self); + int mm = DATE_GET_MINUTE(self); + int ss = DATE_GET_SECOND(self); + int us = 0; /* microseconds are ignored in a timetuple */ + int offset = 0; + + if (HASTZINFO(self) && self->tzinfo != Py_None) { + int none; + + offset = call_utcoffset(self->tzinfo, (PyObject *)self, &none); + if (offset == -1 && PyErr_Occurred()) + return NULL; + } + /* Even if offset is 0, don't call timetuple() -- tm_isdst should be + * 0 in a UTC timetuple regardless of what dst() says. + */ + if (offset) { + /* Subtract offset minutes & normalize. */ + int stat; + + mm -= offset; + stat = normalize_datetime(&y, &m, &d, &hh, &mm, &ss, &us); + if (stat < 0) { + /* At the edges, it's possible we overflowed + * beyond MINYEAR or MAXYEAR. + */ + if (PyErr_ExceptionMatches(PyExc_OverflowError)) + PyErr_Clear(); + else + return NULL; + } + } + return build_struct_time(y, m, d, hh, mm, ss, 0); } /* Pickle support, a simple use of __reduce__. */ @@ -4653,102 +4653,102 @@ static PyObject * datetime_getstate(PyDateTime_DateTime *self) { - PyObject *basestate; - PyObject *result = NULL; + PyObject *basestate; + PyObject *result = NULL; - basestate = PyBytes_FromStringAndSize((char *)self->data, - _PyDateTime_DATETIME_DATASIZE); - if (basestate != NULL) { - if (! HASTZINFO(self) || self->tzinfo == Py_None) - result = PyTuple_Pack(1, basestate); - else - result = PyTuple_Pack(2, basestate, self->tzinfo); - Py_DECREF(basestate); - } - return result; + basestate = PyBytes_FromStringAndSize((char *)self->data, + _PyDateTime_DATETIME_DATASIZE); + if (basestate != NULL) { + if (! HASTZINFO(self) || self->tzinfo == Py_None) + result = PyTuple_Pack(1, basestate); + else + result = PyTuple_Pack(2, basestate, self->tzinfo); + Py_DECREF(basestate); + } + return result; } static PyObject * datetime_reduce(PyDateTime_DateTime *self, PyObject *arg) { - return Py_BuildValue("(ON)", Py_TYPE(self), datetime_getstate(self)); + return Py_BuildValue("(ON)", Py_TYPE(self), datetime_getstate(self)); } static PyMethodDef datetime_methods[] = { - /* Class methods: */ + /* Class methods: */ - {"now", (PyCFunction)datetime_now, - METH_VARARGS | METH_KEYWORDS | METH_CLASS, - PyDoc_STR("[tz] -> new datetime with tz's local day and time.")}, + {"now", (PyCFunction)datetime_now, + METH_VARARGS | METH_KEYWORDS | METH_CLASS, + PyDoc_STR("[tz] -> new datetime with tz's local day and time.")}, - {"utcnow", (PyCFunction)datetime_utcnow, - METH_NOARGS | METH_CLASS, - PyDoc_STR("Return a new datetime representing UTC day and time.")}, + {"utcnow", (PyCFunction)datetime_utcnow, + METH_NOARGS | METH_CLASS, + PyDoc_STR("Return a new datetime representing UTC day and time.")}, - {"fromtimestamp", (PyCFunction)datetime_fromtimestamp, - METH_VARARGS | METH_KEYWORDS | METH_CLASS, - PyDoc_STR("timestamp[, tz] -> tz's local time from POSIX timestamp.")}, + {"fromtimestamp", (PyCFunction)datetime_fromtimestamp, + METH_VARARGS | METH_KEYWORDS | METH_CLASS, + PyDoc_STR("timestamp[, tz] -> tz's local time from POSIX timestamp.")}, - {"utcfromtimestamp", (PyCFunction)datetime_utcfromtimestamp, - METH_VARARGS | METH_CLASS, - PyDoc_STR("timestamp -> UTC datetime from a POSIX timestamp " - "(like time.time()).")}, + {"utcfromtimestamp", (PyCFunction)datetime_utcfromtimestamp, + METH_VARARGS | METH_CLASS, + PyDoc_STR("timestamp -> UTC datetime from a POSIX timestamp " + "(like time.time()).")}, - {"strptime", (PyCFunction)datetime_strptime, - METH_VARARGS | METH_CLASS, - PyDoc_STR("string, format -> new datetime parsed from a string " - "(like time.strptime()).")}, + {"strptime", (PyCFunction)datetime_strptime, + METH_VARARGS | METH_CLASS, + PyDoc_STR("string, format -> new datetime parsed from a string " + "(like time.strptime()).")}, - {"combine", (PyCFunction)datetime_combine, - METH_VARARGS | METH_KEYWORDS | METH_CLASS, - PyDoc_STR("date, time -> datetime with same date and time fields")}, + {"combine", (PyCFunction)datetime_combine, + METH_VARARGS | METH_KEYWORDS | METH_CLASS, + PyDoc_STR("date, time -> datetime with same date and time fields")}, - /* Instance methods: */ + /* Instance methods: */ - {"date", (PyCFunction)datetime_getdate, METH_NOARGS, - PyDoc_STR("Return date object with same year, month and day.")}, + {"date", (PyCFunction)datetime_getdate, METH_NOARGS, + PyDoc_STR("Return date object with same year, month and day.")}, - {"time", (PyCFunction)datetime_gettime, METH_NOARGS, - PyDoc_STR("Return time object with same time but with tzinfo=None.")}, + {"time", (PyCFunction)datetime_gettime, METH_NOARGS, + PyDoc_STR("Return time object with same time but with tzinfo=None.")}, - {"timetz", (PyCFunction)datetime_gettimetz, METH_NOARGS, - PyDoc_STR("Return time object with same time and tzinfo.")}, + {"timetz", (PyCFunction)datetime_gettimetz, METH_NOARGS, + PyDoc_STR("Return time object with same time and tzinfo.")}, - {"ctime", (PyCFunction)datetime_ctime, METH_NOARGS, - PyDoc_STR("Return ctime() style string.")}, + {"ctime", (PyCFunction)datetime_ctime, METH_NOARGS, + PyDoc_STR("Return ctime() style string.")}, - {"timetuple", (PyCFunction)datetime_timetuple, METH_NOARGS, - PyDoc_STR("Return time tuple, compatible with time.localtime().")}, + {"timetuple", (PyCFunction)datetime_timetuple, METH_NOARGS, + PyDoc_STR("Return time tuple, compatible with time.localtime().")}, - {"utctimetuple", (PyCFunction)datetime_utctimetuple, METH_NOARGS, - PyDoc_STR("Return UTC time tuple, compatible with time.localtime().")}, + {"utctimetuple", (PyCFunction)datetime_utctimetuple, METH_NOARGS, + PyDoc_STR("Return UTC time tuple, compatible with time.localtime().")}, - {"isoformat", (PyCFunction)datetime_isoformat, METH_VARARGS | METH_KEYWORDS, - PyDoc_STR("[sep] -> string in ISO 8601 format, " - "YYYY-MM-DDTHH:MM:SS[.mmmmmm][+HH:MM].\n\n" - "sep is used to separate the year from the time, and " - "defaults to 'T'.")}, + {"isoformat", (PyCFunction)datetime_isoformat, METH_VARARGS | METH_KEYWORDS, + PyDoc_STR("[sep] -> string in ISO 8601 format, " + "YYYY-MM-DDTHH:MM:SS[.mmmmmm][+HH:MM].\n\n" + "sep is used to separate the year from the time, and " + "defaults to 'T'.")}, - {"utcoffset", (PyCFunction)datetime_utcoffset, METH_NOARGS, - PyDoc_STR("Return self.tzinfo.utcoffset(self).")}, + {"utcoffset", (PyCFunction)datetime_utcoffset, METH_NOARGS, + PyDoc_STR("Return self.tzinfo.utcoffset(self).")}, - {"tzname", (PyCFunction)datetime_tzname, METH_NOARGS, - PyDoc_STR("Return self.tzinfo.tzname(self).")}, + {"tzname", (PyCFunction)datetime_tzname, METH_NOARGS, + PyDoc_STR("Return self.tzinfo.tzname(self).")}, - {"dst", (PyCFunction)datetime_dst, METH_NOARGS, - PyDoc_STR("Return self.tzinfo.dst(self).")}, + {"dst", (PyCFunction)datetime_dst, METH_NOARGS, + PyDoc_STR("Return self.tzinfo.dst(self).")}, - {"replace", (PyCFunction)datetime_replace, METH_VARARGS | METH_KEYWORDS, - PyDoc_STR("Return datetime with new specified fields.")}, + {"replace", (PyCFunction)datetime_replace, METH_VARARGS | METH_KEYWORDS, + PyDoc_STR("Return datetime with new specified fields.")}, - {"astimezone", (PyCFunction)datetime_astimezone, METH_VARARGS | METH_KEYWORDS, - PyDoc_STR("tz -> convert to local time in new timezone tz\n")}, + {"astimezone", (PyCFunction)datetime_astimezone, METH_VARARGS | METH_KEYWORDS, + PyDoc_STR("tz -> convert to local time in new timezone tz\n")}, - {"__reduce__", (PyCFunction)datetime_reduce, METH_NOARGS, - PyDoc_STR("__reduce__() -> (cls, state)")}, + {"__reduce__", (PyCFunction)datetime_reduce, METH_NOARGS, + PyDoc_STR("__reduce__() -> (cls, state)")}, - {NULL, NULL} + {NULL, NULL} }; static char datetime_doc[] = @@ -4758,58 +4758,58 @@ instance of a tzinfo subclass. The remaining arguments may be ints or longs.\n"); static PyNumberMethods datetime_as_number = { - datetime_add, /* nb_add */ - datetime_subtract, /* nb_subtract */ - 0, /* nb_multiply */ - 0, /* nb_remainder */ - 0, /* nb_divmod */ - 0, /* nb_power */ - 0, /* nb_negative */ - 0, /* nb_positive */ - 0, /* nb_absolute */ - 0, /* nb_bool */ + datetime_add, /* nb_add */ + datetime_subtract, /* nb_subtract */ + 0, /* nb_multiply */ + 0, /* nb_remainder */ + 0, /* nb_divmod */ + 0, /* nb_power */ + 0, /* nb_negative */ + 0, /* nb_positive */ + 0, /* nb_absolute */ + 0, /* nb_bool */ }; static PyTypeObject PyDateTime_DateTimeType = { - PyVarObject_HEAD_INIT(NULL, 0) - "datetime.datetime", /* tp_name */ - sizeof(PyDateTime_DateTime), /* tp_basicsize */ - 0, /* tp_itemsize */ - (destructor)datetime_dealloc, /* tp_dealloc */ - 0, /* tp_print */ - 0, /* tp_getattr */ - 0, /* tp_setattr */ - 0, /* tp_reserved */ - (reprfunc)datetime_repr, /* tp_repr */ - &datetime_as_number, /* tp_as_number */ - 0, /* tp_as_sequence */ - 0, /* tp_as_mapping */ - (hashfunc)datetime_hash, /* tp_hash */ - 0, /* tp_call */ - (reprfunc)datetime_str, /* tp_str */ - PyObject_GenericGetAttr, /* tp_getattro */ - 0, /* tp_setattro */ - 0, /* tp_as_buffer */ - Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */ - datetime_doc, /* tp_doc */ - 0, /* tp_traverse */ - 0, /* tp_clear */ - datetime_richcompare, /* tp_richcompare */ - 0, /* tp_weaklistoffset */ - 0, /* tp_iter */ - 0, /* tp_iternext */ - datetime_methods, /* tp_methods */ - 0, /* tp_members */ - datetime_getset, /* tp_getset */ - &PyDateTime_DateType, /* tp_base */ - 0, /* tp_dict */ - 0, /* tp_descr_get */ - 0, /* tp_descr_set */ - 0, /* tp_dictoffset */ - 0, /* tp_init */ - datetime_alloc, /* tp_alloc */ - datetime_new, /* tp_new */ - 0, /* tp_free */ + PyVarObject_HEAD_INIT(NULL, 0) + "datetime.datetime", /* tp_name */ + sizeof(PyDateTime_DateTime), /* tp_basicsize */ + 0, /* tp_itemsize */ + (destructor)datetime_dealloc, /* tp_dealloc */ + 0, /* tp_print */ + 0, /* tp_getattr */ + 0, /* tp_setattr */ + 0, /* tp_reserved */ + (reprfunc)datetime_repr, /* tp_repr */ + &datetime_as_number, /* tp_as_number */ + 0, /* tp_as_sequence */ + 0, /* tp_as_mapping */ + (hashfunc)datetime_hash, /* tp_hash */ + 0, /* tp_call */ + (reprfunc)datetime_str, /* tp_str */ + PyObject_GenericGetAttr, /* tp_getattro */ + 0, /* tp_setattro */ + 0, /* tp_as_buffer */ + Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */ + datetime_doc, /* tp_doc */ + 0, /* tp_traverse */ + 0, /* tp_clear */ + datetime_richcompare, /* tp_richcompare */ + 0, /* tp_weaklistoffset */ + 0, /* tp_iter */ + 0, /* tp_iternext */ + datetime_methods, /* tp_methods */ + 0, /* tp_members */ + datetime_getset, /* tp_getset */ + &PyDateTime_DateType, /* tp_base */ + 0, /* tp_dict */ + 0, /* tp_descr_get */ + 0, /* tp_descr_set */ + 0, /* tp_dictoffset */ + 0, /* tp_init */ + datetime_alloc, /* tp_alloc */ + datetime_new, /* tp_new */ + 0, /* tp_free */ }; /* --------------------------------------------------------------------------- @@ -4817,204 +4817,204 @@ */ static PyMethodDef module_methods[] = { - {NULL, NULL} + {NULL, NULL} }; /* C API. Clients get at this via PyDateTime_IMPORT, defined in * datetime.h. */ static PyDateTime_CAPI CAPI = { - &PyDateTime_DateType, - &PyDateTime_DateTimeType, - &PyDateTime_TimeType, - &PyDateTime_DeltaType, - &PyDateTime_TZInfoType, - new_date_ex, - new_datetime_ex, - new_time_ex, - new_delta_ex, - datetime_fromtimestamp, - date_fromtimestamp + &PyDateTime_DateType, + &PyDateTime_DateTimeType, + &PyDateTime_TimeType, + &PyDateTime_DeltaType, + &PyDateTime_TZInfoType, + new_date_ex, + new_datetime_ex, + new_time_ex, + new_delta_ex, + datetime_fromtimestamp, + date_fromtimestamp }; static struct PyModuleDef datetimemodule = { - PyModuleDef_HEAD_INIT, - "datetime", - "Fast implementation of the datetime type.", - -1, - module_methods, - NULL, - NULL, - NULL, - NULL + PyModuleDef_HEAD_INIT, + "datetime", + "Fast implementation of the datetime type.", + -1, + module_methods, + NULL, + NULL, + NULL, + NULL }; PyMODINIT_FUNC PyInit_datetime(void) { - PyObject *m; /* a module object */ - PyObject *d; /* its dict */ - PyObject *x; - - m = PyModule_Create(&datetimemodule); - if (m == NULL) - return NULL; - - if (PyType_Ready(&PyDateTime_DateType) < 0) - return NULL; - if (PyType_Ready(&PyDateTime_DateTimeType) < 0) - return NULL; - if (PyType_Ready(&PyDateTime_DeltaType) < 0) - return NULL; - if (PyType_Ready(&PyDateTime_TimeType) < 0) - return NULL; - if (PyType_Ready(&PyDateTime_TZInfoType) < 0) - return NULL; - - /* timedelta values */ - d = PyDateTime_DeltaType.tp_dict; - - x = new_delta(0, 0, 1, 0); - if (x == NULL || PyDict_SetItemString(d, "resolution", x) < 0) - return NULL; - Py_DECREF(x); - - x = new_delta(-MAX_DELTA_DAYS, 0, 0, 0); - if (x == NULL || PyDict_SetItemString(d, "min", x) < 0) - return NULL; - Py_DECREF(x); - - x = new_delta(MAX_DELTA_DAYS, 24*3600-1, 1000000-1, 0); - if (x == NULL || PyDict_SetItemString(d, "max", x) < 0) - return NULL; - Py_DECREF(x); - - /* date values */ - d = PyDateTime_DateType.tp_dict; - - x = new_date(1, 1, 1); - if (x == NULL || PyDict_SetItemString(d, "min", x) < 0) - return NULL; - Py_DECREF(x); - - x = new_date(MAXYEAR, 12, 31); - if (x == NULL || PyDict_SetItemString(d, "max", x) < 0) - return NULL; - Py_DECREF(x); - - x = new_delta(1, 0, 0, 0); - if (x == NULL || PyDict_SetItemString(d, "resolution", x) < 0) - return NULL; - Py_DECREF(x); - - /* time values */ - d = PyDateTime_TimeType.tp_dict; - - x = new_time(0, 0, 0, 0, Py_None); - if (x == NULL || PyDict_SetItemString(d, "min", x) < 0) - return NULL; - Py_DECREF(x); - - x = new_time(23, 59, 59, 999999, Py_None); - if (x == NULL || PyDict_SetItemString(d, "max", x) < 0) - return NULL; - Py_DECREF(x); - - x = new_delta(0, 0, 1, 0); - if (x == NULL || PyDict_SetItemString(d, "resolution", x) < 0) - return NULL; - Py_DECREF(x); - - /* datetime values */ - d = PyDateTime_DateTimeType.tp_dict; - - x = new_datetime(1, 1, 1, 0, 0, 0, 0, Py_None); - if (x == NULL || PyDict_SetItemString(d, "min", x) < 0) - return NULL; - Py_DECREF(x); - - x = new_datetime(MAXYEAR, 12, 31, 23, 59, 59, 999999, Py_None); - if (x == NULL || PyDict_SetItemString(d, "max", x) < 0) - return NULL; - Py_DECREF(x); - - x = new_delta(0, 0, 1, 0); - if (x == NULL || PyDict_SetItemString(d, "resolution", x) < 0) - return NULL; - Py_DECREF(x); - - /* module initialization */ - PyModule_AddIntConstant(m, "MINYEAR", MINYEAR); - PyModule_AddIntConstant(m, "MAXYEAR", MAXYEAR); - - Py_INCREF(&PyDateTime_DateType); - PyModule_AddObject(m, "date", (PyObject *) &PyDateTime_DateType); - - Py_INCREF(&PyDateTime_DateTimeType); - PyModule_AddObject(m, "datetime", - (PyObject *)&PyDateTime_DateTimeType); - - Py_INCREF(&PyDateTime_TimeType); - PyModule_AddObject(m, "time", (PyObject *) &PyDateTime_TimeType); - - Py_INCREF(&PyDateTime_DeltaType); - PyModule_AddObject(m, "timedelta", (PyObject *) &PyDateTime_DeltaType); - - Py_INCREF(&PyDateTime_TZInfoType); - PyModule_AddObject(m, "tzinfo", (PyObject *) &PyDateTime_TZInfoType); - - x = PyCapsule_New(&CAPI, PyDateTime_CAPSULE_NAME, NULL); - if (x == NULL) - return NULL; - PyModule_AddObject(m, "datetime_CAPI", x); - - /* A 4-year cycle has an extra leap day over what we'd get from - * pasting together 4 single years. - */ - assert(DI4Y == 4 * 365 + 1); - assert(DI4Y == days_before_year(4+1)); - - /* Similarly, a 400-year cycle has an extra leap day over what we'd - * get from pasting together 4 100-year cycles. - */ - assert(DI400Y == 4 * DI100Y + 1); - assert(DI400Y == days_before_year(400+1)); - - /* OTOH, a 100-year cycle has one fewer leap day than we'd get from - * pasting together 25 4-year cycles. - */ - assert(DI100Y == 25 * DI4Y - 1); - assert(DI100Y == days_before_year(100+1)); - - us_per_us = PyLong_FromLong(1); - us_per_ms = PyLong_FromLong(1000); - us_per_second = PyLong_FromLong(1000000); - us_per_minute = PyLong_FromLong(60000000); - seconds_per_day = PyLong_FromLong(24 * 3600); - if (us_per_us == NULL || us_per_ms == NULL || us_per_second == NULL || - us_per_minute == NULL || seconds_per_day == NULL) - return NULL; - - /* The rest are too big for 32-bit ints, but even - * us_per_week fits in 40 bits, so doubles should be exact. - */ - us_per_hour = PyLong_FromDouble(3600000000.0); - us_per_day = PyLong_FromDouble(86400000000.0); - us_per_week = PyLong_FromDouble(604800000000.0); - if (us_per_hour == NULL || us_per_day == NULL || us_per_week == NULL) - return NULL; - return m; + PyObject *m; /* a module object */ + PyObject *d; /* its dict */ + PyObject *x; + + m = PyModule_Create(&datetimemodule); + if (m == NULL) + return NULL; + + if (PyType_Ready(&PyDateTime_DateType) < 0) + return NULL; + if (PyType_Ready(&PyDateTime_DateTimeType) < 0) + return NULL; + if (PyType_Ready(&PyDateTime_DeltaType) < 0) + return NULL; + if (PyType_Ready(&PyDateTime_TimeType) < 0) + return NULL; + if (PyType_Ready(&PyDateTime_TZInfoType) < 0) + return NULL; + + /* timedelta values */ + d = PyDateTime_DeltaType.tp_dict; + + x = new_delta(0, 0, 1, 0); + if (x == NULL || PyDict_SetItemString(d, "resolution", x) < 0) + return NULL; + Py_DECREF(x); + + x = new_delta(-MAX_DELTA_DAYS, 0, 0, 0); + if (x == NULL || PyDict_SetItemString(d, "min", x) < 0) + return NULL; + Py_DECREF(x); + + x = new_delta(MAX_DELTA_DAYS, 24*3600-1, 1000000-1, 0); + if (x == NULL || PyDict_SetItemString(d, "max", x) < 0) + return NULL; + Py_DECREF(x); + + /* date values */ + d = PyDateTime_DateType.tp_dict; + + x = new_date(1, 1, 1); + if (x == NULL || PyDict_SetItemString(d, "min", x) < 0) + return NULL; + Py_DECREF(x); + + x = new_date(MAXYEAR, 12, 31); + if (x == NULL || PyDict_SetItemString(d, "max", x) < 0) + return NULL; + Py_DECREF(x); + + x = new_delta(1, 0, 0, 0); + if (x == NULL || PyDict_SetItemString(d, "resolution", x) < 0) + return NULL; + Py_DECREF(x); + + /* time values */ + d = PyDateTime_TimeType.tp_dict; + + x = new_time(0, 0, 0, 0, Py_None); + if (x == NULL || PyDict_SetItemString(d, "min", x) < 0) + return NULL; + Py_DECREF(x); + + x = new_time(23, 59, 59, 999999, Py_None); + if (x == NULL || PyDict_SetItemString(d, "max", x) < 0) + return NULL; + Py_DECREF(x); + + x = new_delta(0, 0, 1, 0); + if (x == NULL || PyDict_SetItemString(d, "resolution", x) < 0) + return NULL; + Py_DECREF(x); + + /* datetime values */ + d = PyDateTime_DateTimeType.tp_dict; + + x = new_datetime(1, 1, 1, 0, 0, 0, 0, Py_None); + if (x == NULL || PyDict_SetItemString(d, "min", x) < 0) + return NULL; + Py_DECREF(x); + + x = new_datetime(MAXYEAR, 12, 31, 23, 59, 59, 999999, Py_None); + if (x == NULL || PyDict_SetItemString(d, "max", x) < 0) + return NULL; + Py_DECREF(x); + + x = new_delta(0, 0, 1, 0); + if (x == NULL || PyDict_SetItemString(d, "resolution", x) < 0) + return NULL; + Py_DECREF(x); + + /* module initialization */ + PyModule_AddIntConstant(m, "MINYEAR", MINYEAR); + PyModule_AddIntConstant(m, "MAXYEAR", MAXYEAR); + + Py_INCREF(&PyDateTime_DateType); + PyModule_AddObject(m, "date", (PyObject *) &PyDateTime_DateType); + + Py_INCREF(&PyDateTime_DateTimeType); + PyModule_AddObject(m, "datetime", + (PyObject *)&PyDateTime_DateTimeType); + + Py_INCREF(&PyDateTime_TimeType); + PyModule_AddObject(m, "time", (PyObject *) &PyDateTime_TimeType); + + Py_INCREF(&PyDateTime_DeltaType); + PyModule_AddObject(m, "timedelta", (PyObject *) &PyDateTime_DeltaType); + + Py_INCREF(&PyDateTime_TZInfoType); + PyModule_AddObject(m, "tzinfo", (PyObject *) &PyDateTime_TZInfoType); + + x = PyCapsule_New(&CAPI, PyDateTime_CAPSULE_NAME, NULL); + if (x == NULL) + return NULL; + PyModule_AddObject(m, "datetime_CAPI", x); + + /* A 4-year cycle has an extra leap day over what we'd get from + * pasting together 4 single years. + */ + assert(DI4Y == 4 * 365 + 1); + assert(DI4Y == days_before_year(4+1)); + + /* Similarly, a 400-year cycle has an extra leap day over what we'd + * get from pasting together 4 100-year cycles. + */ + assert(DI400Y == 4 * DI100Y + 1); + assert(DI400Y == days_before_year(400+1)); + + /* OTOH, a 100-year cycle has one fewer leap day than we'd get from + * pasting together 25 4-year cycles. + */ + assert(DI100Y == 25 * DI4Y - 1); + assert(DI100Y == days_before_year(100+1)); + + us_per_us = PyLong_FromLong(1); + us_per_ms = PyLong_FromLong(1000); + us_per_second = PyLong_FromLong(1000000); + us_per_minute = PyLong_FromLong(60000000); + seconds_per_day = PyLong_FromLong(24 * 3600); + if (us_per_us == NULL || us_per_ms == NULL || us_per_second == NULL || + us_per_minute == NULL || seconds_per_day == NULL) + return NULL; + + /* The rest are too big for 32-bit ints, but even + * us_per_week fits in 40 bits, so doubles should be exact. + */ + us_per_hour = PyLong_FromDouble(3600000000.0); + us_per_day = PyLong_FromDouble(86400000000.0); + us_per_week = PyLong_FromDouble(604800000000.0); + if (us_per_hour == NULL || us_per_day == NULL || us_per_week == NULL) + return NULL; + return m; } /* --------------------------------------------------------------------------- Some time zone algebra. For a datetime x, let x.n = x stripped of its timezone -- its naive time. x.o = x.utcoffset(), and assuming that doesn't raise an exception or - return None + return None x.d = x.dst(), and assuming that doesn't raise an exception or - return None + return None x.s = x's standard offset, x.o - x.d Now some derived rules, where k is a duration (timedelta). @@ -5136,13 +5136,13 @@ already): diff' = x.n - (z'.n - z'.o) = replacing z'.n via [7] - x.n - (z.n + diff - z'.o) = replacing diff via [6] - x.n - (z.n + x.n - (z.n - z.o) - z'.o) = - x.n - z.n - x.n + z.n - z.o + z'.o = cancel x.n - - z.n + z.n - z.o + z'.o = cancel z.n - - z.o + z'.o = #1 twice - -z.s - z.d + z'.s + z'.d = z and z' have same tzinfo - z'.d - z.d + x.n - (z.n + diff - z'.o) = replacing diff via [6] + x.n - (z.n + x.n - (z.n - z.o) - z'.o) = + x.n - z.n - x.n + z.n - z.o + z'.o = cancel x.n + - z.n + z.n - z.o + z'.o = cancel z.n + - z.o + z'.o = #1 twice + -z.s - z.d + z'.s + z'.d = z and z' have same tzinfo + z'.d - z.d So z' is UTC-equivalent to x iff z'.d = z.d at this point. If they are equal, we've found the UTC-equivalent so are done. In fact, we stop with [7] and Modified: python/branches/py3k/Modules/errnomodule.c ============================================================================== --- python/branches/py3k/Modules/errnomodule.c (original) +++ python/branches/py3k/Modules/errnomodule.c Sun May 9 17:52:27 2010 @@ -11,10 +11,10 @@ /* * Pull in the system error definitions - */ + */ static PyMethodDef errno_methods[] = { - {NULL, NULL} + {NULL, NULL} }; /* Helper function doing the dictionary inserting */ @@ -22,21 +22,21 @@ static void _inscode(PyObject *d, PyObject *de, const char *name, int code) { - PyObject *u = PyUnicode_FromString(name); - PyObject *v = PyLong_FromLong((long) code); + PyObject *u = PyUnicode_FromString(name); + PyObject *v = PyLong_FromLong((long) code); - /* Don't bother checking for errors; they'll be caught at the end - * of the module initialization function by the caller of - * initerrno(). - */ - if (u && v) { - /* insert in modules dict */ - PyDict_SetItem(d, u, v); - /* insert in errorcode dict */ - PyDict_SetItem(de, v, u); - } - Py_XDECREF(u); - Py_XDECREF(v); + /* Don't bother checking for errors; they'll be caught at the end + * of the module initialization function by the caller of + * initerrno(). + */ + if (u && v) { + /* insert in modules dict */ + PyDict_SetItem(d, u, v); + /* insert in errorcode dict */ + PyDict_SetItem(de, v, u); + } + Py_XDECREF(u); + Py_XDECREF(v); } PyDoc_STRVAR(errno__doc__, @@ -54,749 +54,749 @@ e.g. os.strerror(2) could return 'No such file or directory'."); static struct PyModuleDef errnomodule = { - PyModuleDef_HEAD_INIT, - "errno", - errno__doc__, - -1, - errno_methods, - NULL, - NULL, - NULL, - NULL + PyModuleDef_HEAD_INIT, + "errno", + errno__doc__, + -1, + errno_methods, + NULL, + NULL, + NULL, + NULL }; PyMODINIT_FUNC PyInit_errno(void) { - PyObject *m, *d, *de; - m = PyModule_Create(&errnomodule); - if (m == NULL) - return NULL; - d = PyModule_GetDict(m); - de = PyDict_New(); - if (!d || !de || PyDict_SetItemString(d, "errorcode", de) < 0) - return NULL; + PyObject *m, *d, *de; + m = PyModule_Create(&errnomodule); + if (m == NULL) + return NULL; + d = PyModule_GetDict(m); + de = PyDict_New(); + if (!d || !de || PyDict_SetItemString(d, "errorcode", de) < 0) + return NULL; /* Macro so I don't have to edit each and every line below... */ #define inscode(d, ds, de, name, code, comment) _inscode(d, de, name, code) - /* - * The names and comments are borrowed from linux/include/errno.h, - * which should be pretty all-inclusive - */ + /* + * The names and comments are borrowed from linux/include/errno.h, + * which should be pretty all-inclusive + */ #ifdef ENODEV - inscode(d, ds, de, "ENODEV", ENODEV, "No such device"); + inscode(d, ds, de, "ENODEV", ENODEV, "No such device"); #endif #ifdef ENOCSI - inscode(d, ds, de, "ENOCSI", ENOCSI, "No CSI structure available"); + inscode(d, ds, de, "ENOCSI", ENOCSI, "No CSI structure available"); #endif #ifdef EHOSTUNREACH - inscode(d, ds, de, "EHOSTUNREACH", EHOSTUNREACH, "No route to host"); + inscode(d, ds, de, "EHOSTUNREACH", EHOSTUNREACH, "No route to host"); #else #ifdef WSAEHOSTUNREACH - inscode(d, ds, de, "EHOSTUNREACH", WSAEHOSTUNREACH, "No route to host"); + inscode(d, ds, de, "EHOSTUNREACH", WSAEHOSTUNREACH, "No route to host"); #endif #endif #ifdef ENOMSG - inscode(d, ds, de, "ENOMSG", ENOMSG, "No message of desired type"); + inscode(d, ds, de, "ENOMSG", ENOMSG, "No message of desired type"); #endif #ifdef EUCLEAN - inscode(d, ds, de, "EUCLEAN", EUCLEAN, "Structure needs cleaning"); + inscode(d, ds, de, "EUCLEAN", EUCLEAN, "Structure needs cleaning"); #endif #ifdef EL2NSYNC - inscode(d, ds, de, "EL2NSYNC", EL2NSYNC, "Level 2 not synchronized"); + inscode(d, ds, de, "EL2NSYNC", EL2NSYNC, "Level 2 not synchronized"); #endif #ifdef EL2HLT - inscode(d, ds, de, "EL2HLT", EL2HLT, "Level 2 halted"); + inscode(d, ds, de, "EL2HLT", EL2HLT, "Level 2 halted"); #endif #ifdef ENODATA - inscode(d, ds, de, "ENODATA", ENODATA, "No data available"); + inscode(d, ds, de, "ENODATA", ENODATA, "No data available"); #endif #ifdef ENOTBLK - inscode(d, ds, de, "ENOTBLK", ENOTBLK, "Block device required"); + inscode(d, ds, de, "ENOTBLK", ENOTBLK, "Block device required"); #endif #ifdef ENOSYS - inscode(d, ds, de, "ENOSYS", ENOSYS, "Function not implemented"); + inscode(d, ds, de, "ENOSYS", ENOSYS, "Function not implemented"); #endif #ifdef EPIPE - inscode(d, ds, de, "EPIPE", EPIPE, "Broken pipe"); + inscode(d, ds, de, "EPIPE", EPIPE, "Broken pipe"); #endif #ifdef EINVAL - inscode(d, ds, de, "EINVAL", EINVAL, "Invalid argument"); + inscode(d, ds, de, "EINVAL", EINVAL, "Invalid argument"); #else #ifdef WSAEINVAL - inscode(d, ds, de, "EINVAL", WSAEINVAL, "Invalid argument"); + inscode(d, ds, de, "EINVAL", WSAEINVAL, "Invalid argument"); #endif #endif #ifdef EOVERFLOW - inscode(d, ds, de, "EOVERFLOW", EOVERFLOW, "Value too large for defined data type"); + inscode(d, ds, de, "EOVERFLOW", EOVERFLOW, "Value too large for defined data type"); #endif #ifdef EADV - inscode(d, ds, de, "EADV", EADV, "Advertise error"); + inscode(d, ds, de, "EADV", EADV, "Advertise error"); #endif #ifdef EINTR - inscode(d, ds, de, "EINTR", EINTR, "Interrupted system call"); + inscode(d, ds, de, "EINTR", EINTR, "Interrupted system call"); #else #ifdef WSAEINTR - inscode(d, ds, de, "EINTR", WSAEINTR, "Interrupted system call"); + inscode(d, ds, de, "EINTR", WSAEINTR, "Interrupted system call"); #endif #endif #ifdef EUSERS - inscode(d, ds, de, "EUSERS", EUSERS, "Too many users"); + inscode(d, ds, de, "EUSERS", EUSERS, "Too many users"); #else #ifdef WSAEUSERS - inscode(d, ds, de, "EUSERS", WSAEUSERS, "Too many users"); + inscode(d, ds, de, "EUSERS", WSAEUSERS, "Too many users"); #endif #endif #ifdef ENOTEMPTY - inscode(d, ds, de, "ENOTEMPTY", ENOTEMPTY, "Directory not empty"); + inscode(d, ds, de, "ENOTEMPTY", ENOTEMPTY, "Directory not empty"); #else #ifdef WSAENOTEMPTY - inscode(d, ds, de, "ENOTEMPTY", WSAENOTEMPTY, "Directory not empty"); + inscode(d, ds, de, "ENOTEMPTY", WSAENOTEMPTY, "Directory not empty"); #endif #endif #ifdef ENOBUFS - inscode(d, ds, de, "ENOBUFS", ENOBUFS, "No buffer space available"); + inscode(d, ds, de, "ENOBUFS", ENOBUFS, "No buffer space available"); #else #ifdef WSAENOBUFS - inscode(d, ds, de, "ENOBUFS", WSAENOBUFS, "No buffer space available"); + inscode(d, ds, de, "ENOBUFS", WSAENOBUFS, "No buffer space available"); #endif #endif #ifdef EPROTO - inscode(d, ds, de, "EPROTO", EPROTO, "Protocol error"); + inscode(d, ds, de, "EPROTO", EPROTO, "Protocol error"); #endif #ifdef EREMOTE - inscode(d, ds, de, "EREMOTE", EREMOTE, "Object is remote"); + inscode(d, ds, de, "EREMOTE", EREMOTE, "Object is remote"); #else #ifdef WSAEREMOTE - inscode(d, ds, de, "EREMOTE", WSAEREMOTE, "Object is remote"); + inscode(d, ds, de, "EREMOTE", WSAEREMOTE, "Object is remote"); #endif #endif #ifdef ENAVAIL - inscode(d, ds, de, "ENAVAIL", ENAVAIL, "No XENIX semaphores available"); + inscode(d, ds, de, "ENAVAIL", ENAVAIL, "No XENIX semaphores available"); #endif #ifdef ECHILD - inscode(d, ds, de, "ECHILD", ECHILD, "No child processes"); + inscode(d, ds, de, "ECHILD", ECHILD, "No child processes"); #endif #ifdef ELOOP - inscode(d, ds, de, "ELOOP", ELOOP, "Too many symbolic links encountered"); + inscode(d, ds, de, "ELOOP", ELOOP, "Too many symbolic links encountered"); #else #ifdef WSAELOOP - inscode(d, ds, de, "ELOOP", WSAELOOP, "Too many symbolic links encountered"); + inscode(d, ds, de, "ELOOP", WSAELOOP, "Too many symbolic links encountered"); #endif #endif #ifdef EXDEV - inscode(d, ds, de, "EXDEV", EXDEV, "Cross-device link"); + inscode(d, ds, de, "EXDEV", EXDEV, "Cross-device link"); #endif #ifdef E2BIG - inscode(d, ds, de, "E2BIG", E2BIG, "Arg list too long"); + inscode(d, ds, de, "E2BIG", E2BIG, "Arg list too long"); #endif #ifdef ESRCH - inscode(d, ds, de, "ESRCH", ESRCH, "No such process"); + inscode(d, ds, de, "ESRCH", ESRCH, "No such process"); #endif #ifdef EMSGSIZE - inscode(d, ds, de, "EMSGSIZE", EMSGSIZE, "Message too long"); + inscode(d, ds, de, "EMSGSIZE", EMSGSIZE, "Message too long"); #else #ifdef WSAEMSGSIZE - inscode(d, ds, de, "EMSGSIZE", WSAEMSGSIZE, "Message too long"); + inscode(d, ds, de, "EMSGSIZE", WSAEMSGSIZE, "Message too long"); #endif #endif #ifdef EAFNOSUPPORT - inscode(d, ds, de, "EAFNOSUPPORT", EAFNOSUPPORT, "Address family not supported by protocol"); + inscode(d, ds, de, "EAFNOSUPPORT", EAFNOSUPPORT, "Address family not supported by protocol"); #else #ifdef WSAEAFNOSUPPORT - inscode(d, ds, de, "EAFNOSUPPORT", WSAEAFNOSUPPORT, "Address family not supported by protocol"); + inscode(d, ds, de, "EAFNOSUPPORT", WSAEAFNOSUPPORT, "Address family not supported by protocol"); #endif #endif #ifdef EBADR - inscode(d, ds, de, "EBADR", EBADR, "Invalid request descriptor"); + inscode(d, ds, de, "EBADR", EBADR, "Invalid request descriptor"); #endif #ifdef EHOSTDOWN - inscode(d, ds, de, "EHOSTDOWN", EHOSTDOWN, "Host is down"); + inscode(d, ds, de, "EHOSTDOWN", EHOSTDOWN, "Host is down"); #else #ifdef WSAEHOSTDOWN - inscode(d, ds, de, "EHOSTDOWN", WSAEHOSTDOWN, "Host is down"); + inscode(d, ds, de, "EHOSTDOWN", WSAEHOSTDOWN, "Host is down"); #endif #endif #ifdef EPFNOSUPPORT - inscode(d, ds, de, "EPFNOSUPPORT", EPFNOSUPPORT, "Protocol family not supported"); + inscode(d, ds, de, "EPFNOSUPPORT", EPFNOSUPPORT, "Protocol family not supported"); #else #ifdef WSAEPFNOSUPPORT - inscode(d, ds, de, "EPFNOSUPPORT", WSAEPFNOSUPPORT, "Protocol family not supported"); + inscode(d, ds, de, "EPFNOSUPPORT", WSAEPFNOSUPPORT, "Protocol family not supported"); #endif #endif #ifdef ENOPROTOOPT - inscode(d, ds, de, "ENOPROTOOPT", ENOPROTOOPT, "Protocol not available"); + inscode(d, ds, de, "ENOPROTOOPT", ENOPROTOOPT, "Protocol not available"); #else #ifdef WSAENOPROTOOPT - inscode(d, ds, de, "ENOPROTOOPT", WSAENOPROTOOPT, "Protocol not available"); + inscode(d, ds, de, "ENOPROTOOPT", WSAENOPROTOOPT, "Protocol not available"); #endif #endif #ifdef EBUSY - inscode(d, ds, de, "EBUSY", EBUSY, "Device or resource busy"); + inscode(d, ds, de, "EBUSY", EBUSY, "Device or resource busy"); #endif #ifdef EWOULDBLOCK - inscode(d, ds, de, "EWOULDBLOCK", EWOULDBLOCK, "Operation would block"); + inscode(d, ds, de, "EWOULDBLOCK", EWOULDBLOCK, "Operation would block"); #else #ifdef WSAEWOULDBLOCK - inscode(d, ds, de, "EWOULDBLOCK", WSAEWOULDBLOCK, "Operation would block"); + inscode(d, ds, de, "EWOULDBLOCK", WSAEWOULDBLOCK, "Operation would block"); #endif #endif #ifdef EBADFD - inscode(d, ds, de, "EBADFD", EBADFD, "File descriptor in bad state"); + inscode(d, ds, de, "EBADFD", EBADFD, "File descriptor in bad state"); #endif #ifdef EDOTDOT - inscode(d, ds, de, "EDOTDOT", EDOTDOT, "RFS specific error"); + inscode(d, ds, de, "EDOTDOT", EDOTDOT, "RFS specific error"); #endif #ifdef EISCONN - inscode(d, ds, de, "EISCONN", EISCONN, "Transport endpoint is already connected"); + inscode(d, ds, de, "EISCONN", EISCONN, "Transport endpoint is already connected"); #else #ifdef WSAEISCONN - inscode(d, ds, de, "EISCONN", WSAEISCONN, "Transport endpoint is already connected"); + inscode(d, ds, de, "EISCONN", WSAEISCONN, "Transport endpoint is already connected"); #endif #endif #ifdef ENOANO - inscode(d, ds, de, "ENOANO", ENOANO, "No anode"); + inscode(d, ds, de, "ENOANO", ENOANO, "No anode"); #endif #ifdef ESHUTDOWN - inscode(d, ds, de, "ESHUTDOWN", ESHUTDOWN, "Cannot send after transport endpoint shutdown"); + inscode(d, ds, de, "ESHUTDOWN", ESHUTDOWN, "Cannot send after transport endpoint shutdown"); #else #ifdef WSAESHUTDOWN - inscode(d, ds, de, "ESHUTDOWN", WSAESHUTDOWN, "Cannot send after transport endpoint shutdown"); + inscode(d, ds, de, "ESHUTDOWN", WSAESHUTDOWN, "Cannot send after transport endpoint shutdown"); #endif #endif #ifdef ECHRNG - inscode(d, ds, de, "ECHRNG", ECHRNG, "Channel number out of range"); + inscode(d, ds, de, "ECHRNG", ECHRNG, "Channel number out of range"); #endif #ifdef ELIBBAD - inscode(d, ds, de, "ELIBBAD", ELIBBAD, "Accessing a corrupted shared library"); + inscode(d, ds, de, "ELIBBAD", ELIBBAD, "Accessing a corrupted shared library"); #endif #ifdef ENONET - inscode(d, ds, de, "ENONET", ENONET, "Machine is not on the network"); + inscode(d, ds, de, "ENONET", ENONET, "Machine is not on the network"); #endif #ifdef EBADE - inscode(d, ds, de, "EBADE", EBADE, "Invalid exchange"); + inscode(d, ds, de, "EBADE", EBADE, "Invalid exchange"); #endif #ifdef EBADF - inscode(d, ds, de, "EBADF", EBADF, "Bad file number"); + inscode(d, ds, de, "EBADF", EBADF, "Bad file number"); #else #ifdef WSAEBADF - inscode(d, ds, de, "EBADF", WSAEBADF, "Bad file number"); + inscode(d, ds, de, "EBADF", WSAEBADF, "Bad file number"); #endif #endif #ifdef EMULTIHOP - inscode(d, ds, de, "EMULTIHOP", EMULTIHOP, "Multihop attempted"); + inscode(d, ds, de, "EMULTIHOP", EMULTIHOP, "Multihop attempted"); #endif #ifdef EIO - inscode(d, ds, de, "EIO", EIO, "I/O error"); + inscode(d, ds, de, "EIO", EIO, "I/O error"); #endif #ifdef EUNATCH - inscode(d, ds, de, "EUNATCH", EUNATCH, "Protocol driver not attached"); + inscode(d, ds, de, "EUNATCH", EUNATCH, "Protocol driver not attached"); #endif #ifdef EPROTOTYPE - inscode(d, ds, de, "EPROTOTYPE", EPROTOTYPE, "Protocol wrong type for socket"); + inscode(d, ds, de, "EPROTOTYPE", EPROTOTYPE, "Protocol wrong type for socket"); #else #ifdef WSAEPROTOTYPE - inscode(d, ds, de, "EPROTOTYPE", WSAEPROTOTYPE, "Protocol wrong type for socket"); + inscode(d, ds, de, "EPROTOTYPE", WSAEPROTOTYPE, "Protocol wrong type for socket"); #endif #endif #ifdef ENOSPC - inscode(d, ds, de, "ENOSPC", ENOSPC, "No space left on device"); + inscode(d, ds, de, "ENOSPC", ENOSPC, "No space left on device"); #endif #ifdef ENOEXEC - inscode(d, ds, de, "ENOEXEC", ENOEXEC, "Exec format error"); + inscode(d, ds, de, "ENOEXEC", ENOEXEC, "Exec format error"); #endif #ifdef EALREADY - inscode(d, ds, de, "EALREADY", EALREADY, "Operation already in progress"); + inscode(d, ds, de, "EALREADY", EALREADY, "Operation already in progress"); #else #ifdef WSAEALREADY - inscode(d, ds, de, "EALREADY", WSAEALREADY, "Operation already in progress"); + inscode(d, ds, de, "EALREADY", WSAEALREADY, "Operation already in progress"); #endif #endif #ifdef ENETDOWN - inscode(d, ds, de, "ENETDOWN", ENETDOWN, "Network is down"); + inscode(d, ds, de, "ENETDOWN", ENETDOWN, "Network is down"); #else #ifdef WSAENETDOWN - inscode(d, ds, de, "ENETDOWN", WSAENETDOWN, "Network is down"); + inscode(d, ds, de, "ENETDOWN", WSAENETDOWN, "Network is down"); #endif #endif #ifdef ENOTNAM - inscode(d, ds, de, "ENOTNAM", ENOTNAM, "Not a XENIX named type file"); + inscode(d, ds, de, "ENOTNAM", ENOTNAM, "Not a XENIX named type file"); #endif #ifdef EACCES - inscode(d, ds, de, "EACCES", EACCES, "Permission denied"); + inscode(d, ds, de, "EACCES", EACCES, "Permission denied"); #else #ifdef WSAEACCES - inscode(d, ds, de, "EACCES", WSAEACCES, "Permission denied"); + inscode(d, ds, de, "EACCES", WSAEACCES, "Permission denied"); #endif #endif #ifdef ELNRNG - inscode(d, ds, de, "ELNRNG", ELNRNG, "Link number out of range"); + inscode(d, ds, de, "ELNRNG", ELNRNG, "Link number out of range"); #endif #ifdef EILSEQ - inscode(d, ds, de, "EILSEQ", EILSEQ, "Illegal byte sequence"); + inscode(d, ds, de, "EILSEQ", EILSEQ, "Illegal byte sequence"); #endif #ifdef ENOTDIR - inscode(d, ds, de, "ENOTDIR", ENOTDIR, "Not a directory"); + inscode(d, ds, de, "ENOTDIR", ENOTDIR, "Not a directory"); #endif #ifdef ENOTUNIQ - inscode(d, ds, de, "ENOTUNIQ", ENOTUNIQ, "Name not unique on network"); + inscode(d, ds, de, "ENOTUNIQ", ENOTUNIQ, "Name not unique on network"); #endif #ifdef EPERM - inscode(d, ds, de, "EPERM", EPERM, "Operation not permitted"); + inscode(d, ds, de, "EPERM", EPERM, "Operation not permitted"); #endif #ifdef EDOM - inscode(d, ds, de, "EDOM", EDOM, "Math argument out of domain of func"); + inscode(d, ds, de, "EDOM", EDOM, "Math argument out of domain of func"); #endif #ifdef EXFULL - inscode(d, ds, de, "EXFULL", EXFULL, "Exchange full"); + inscode(d, ds, de, "EXFULL", EXFULL, "Exchange full"); #endif #ifdef ECONNREFUSED - inscode(d, ds, de, "ECONNREFUSED", ECONNREFUSED, "Connection refused"); + inscode(d, ds, de, "ECONNREFUSED", ECONNREFUSED, "Connection refused"); #else #ifdef WSAECONNREFUSED - inscode(d, ds, de, "ECONNREFUSED", WSAECONNREFUSED, "Connection refused"); + inscode(d, ds, de, "ECONNREFUSED", WSAECONNREFUSED, "Connection refused"); #endif #endif #ifdef EISDIR - inscode(d, ds, de, "EISDIR", EISDIR, "Is a directory"); + inscode(d, ds, de, "EISDIR", EISDIR, "Is a directory"); #endif #ifdef EPROTONOSUPPORT - inscode(d, ds, de, "EPROTONOSUPPORT", EPROTONOSUPPORT, "Protocol not supported"); + inscode(d, ds, de, "EPROTONOSUPPORT", EPROTONOSUPPORT, "Protocol not supported"); #else #ifdef WSAEPROTONOSUPPORT - inscode(d, ds, de, "EPROTONOSUPPORT", WSAEPROTONOSUPPORT, "Protocol not supported"); + inscode(d, ds, de, "EPROTONOSUPPORT", WSAEPROTONOSUPPORT, "Protocol not supported"); #endif #endif #ifdef EROFS - inscode(d, ds, de, "EROFS", EROFS, "Read-only file system"); + inscode(d, ds, de, "EROFS", EROFS, "Read-only file system"); #endif #ifdef EADDRNOTAVAIL - inscode(d, ds, de, "EADDRNOTAVAIL", EADDRNOTAVAIL, "Cannot assign requested address"); + inscode(d, ds, de, "EADDRNOTAVAIL", EADDRNOTAVAIL, "Cannot assign requested address"); #else #ifdef WSAEADDRNOTAVAIL - inscode(d, ds, de, "EADDRNOTAVAIL", WSAEADDRNOTAVAIL, "Cannot assign requested address"); + inscode(d, ds, de, "EADDRNOTAVAIL", WSAEADDRNOTAVAIL, "Cannot assign requested address"); #endif #endif #ifdef EIDRM - inscode(d, ds, de, "EIDRM", EIDRM, "Identifier removed"); + inscode(d, ds, de, "EIDRM", EIDRM, "Identifier removed"); #endif #ifdef ECOMM - inscode(d, ds, de, "ECOMM", ECOMM, "Communication error on send"); + inscode(d, ds, de, "ECOMM", ECOMM, "Communication error on send"); #endif #ifdef ESRMNT - inscode(d, ds, de, "ESRMNT", ESRMNT, "Srmount error"); + inscode(d, ds, de, "ESRMNT", ESRMNT, "Srmount error"); #endif #ifdef EREMOTEIO - inscode(d, ds, de, "EREMOTEIO", EREMOTEIO, "Remote I/O error"); + inscode(d, ds, de, "EREMOTEIO", EREMOTEIO, "Remote I/O error"); #endif #ifdef EL3RST - inscode(d, ds, de, "EL3RST", EL3RST, "Level 3 reset"); + inscode(d, ds, de, "EL3RST", EL3RST, "Level 3 reset"); #endif #ifdef EBADMSG - inscode(d, ds, de, "EBADMSG", EBADMSG, "Not a data message"); + inscode(d, ds, de, "EBADMSG", EBADMSG, "Not a data message"); #endif #ifdef ENFILE - inscode(d, ds, de, "ENFILE", ENFILE, "File table overflow"); + inscode(d, ds, de, "ENFILE", ENFILE, "File table overflow"); #endif #ifdef ELIBMAX - inscode(d, ds, de, "ELIBMAX", ELIBMAX, "Attempting to link in too many shared libraries"); + inscode(d, ds, de, "ELIBMAX", ELIBMAX, "Attempting to link in too many shared libraries"); #endif #ifdef ESPIPE - inscode(d, ds, de, "ESPIPE", ESPIPE, "Illegal seek"); + inscode(d, ds, de, "ESPIPE", ESPIPE, "Illegal seek"); #endif #ifdef ENOLINK - inscode(d, ds, de, "ENOLINK", ENOLINK, "Link has been severed"); + inscode(d, ds, de, "ENOLINK", ENOLINK, "Link has been severed"); #endif #ifdef ENETRESET - inscode(d, ds, de, "ENETRESET", ENETRESET, "Network dropped connection because of reset"); + inscode(d, ds, de, "ENETRESET", ENETRESET, "Network dropped connection because of reset"); #else #ifdef WSAENETRESET - inscode(d, ds, de, "ENETRESET", WSAENETRESET, "Network dropped connection because of reset"); + inscode(d, ds, de, "ENETRESET", WSAENETRESET, "Network dropped connection because of reset"); #endif #endif #ifdef ETIMEDOUT - inscode(d, ds, de, "ETIMEDOUT", ETIMEDOUT, "Connection timed out"); + inscode(d, ds, de, "ETIMEDOUT", ETIMEDOUT, "Connection timed out"); #else #ifdef WSAETIMEDOUT - inscode(d, ds, de, "ETIMEDOUT", WSAETIMEDOUT, "Connection timed out"); + inscode(d, ds, de, "ETIMEDOUT", WSAETIMEDOUT, "Connection timed out"); #endif #endif #ifdef ENOENT - inscode(d, ds, de, "ENOENT", ENOENT, "No such file or directory"); + inscode(d, ds, de, "ENOENT", ENOENT, "No such file or directory"); #endif #ifdef EEXIST - inscode(d, ds, de, "EEXIST", EEXIST, "File exists"); + inscode(d, ds, de, "EEXIST", EEXIST, "File exists"); #endif #ifdef EDQUOT - inscode(d, ds, de, "EDQUOT", EDQUOT, "Quota exceeded"); + inscode(d, ds, de, "EDQUOT", EDQUOT, "Quota exceeded"); #else #ifdef WSAEDQUOT - inscode(d, ds, de, "EDQUOT", WSAEDQUOT, "Quota exceeded"); + inscode(d, ds, de, "EDQUOT", WSAEDQUOT, "Quota exceeded"); #endif #endif #ifdef ENOSTR - inscode(d, ds, de, "ENOSTR", ENOSTR, "Device not a stream"); + inscode(d, ds, de, "ENOSTR", ENOSTR, "Device not a stream"); #endif #ifdef EBADSLT - inscode(d, ds, de, "EBADSLT", EBADSLT, "Invalid slot"); + inscode(d, ds, de, "EBADSLT", EBADSLT, "Invalid slot"); #endif #ifdef EBADRQC - inscode(d, ds, de, "EBADRQC", EBADRQC, "Invalid request code"); + inscode(d, ds, de, "EBADRQC", EBADRQC, "Invalid request code"); #endif #ifdef ELIBACC - inscode(d, ds, de, "ELIBACC", ELIBACC, "Can not access a needed shared library"); + inscode(d, ds, de, "ELIBACC", ELIBACC, "Can not access a needed shared library"); #endif #ifdef EFAULT - inscode(d, ds, de, "EFAULT", EFAULT, "Bad address"); + inscode(d, ds, de, "EFAULT", EFAULT, "Bad address"); #else #ifdef WSAEFAULT - inscode(d, ds, de, "EFAULT", WSAEFAULT, "Bad address"); + inscode(d, ds, de, "EFAULT", WSAEFAULT, "Bad address"); #endif #endif #ifdef EFBIG - inscode(d, ds, de, "EFBIG", EFBIG, "File too large"); + inscode(d, ds, de, "EFBIG", EFBIG, "File too large"); #endif #ifdef EDEADLK - inscode(d, ds, de, "EDEADLK", EDEADLK, "Resource deadlock would occur"); + inscode(d, ds, de, "EDEADLK", EDEADLK, "Resource deadlock would occur"); #endif #ifdef ENOTCONN - inscode(d, ds, de, "ENOTCONN", ENOTCONN, "Transport endpoint is not connected"); + inscode(d, ds, de, "ENOTCONN", ENOTCONN, "Transport endpoint is not connected"); #else #ifdef WSAENOTCONN - inscode(d, ds, de, "ENOTCONN", WSAENOTCONN, "Transport endpoint is not connected"); + inscode(d, ds, de, "ENOTCONN", WSAENOTCONN, "Transport endpoint is not connected"); #endif #endif #ifdef EDESTADDRREQ - inscode(d, ds, de, "EDESTADDRREQ", EDESTADDRREQ, "Destination address required"); + inscode(d, ds, de, "EDESTADDRREQ", EDESTADDRREQ, "Destination address required"); #else #ifdef WSAEDESTADDRREQ - inscode(d, ds, de, "EDESTADDRREQ", WSAEDESTADDRREQ, "Destination address required"); + inscode(d, ds, de, "EDESTADDRREQ", WSAEDESTADDRREQ, "Destination address required"); #endif #endif #ifdef ELIBSCN - inscode(d, ds, de, "ELIBSCN", ELIBSCN, ".lib section in a.out corrupted"); + inscode(d, ds, de, "ELIBSCN", ELIBSCN, ".lib section in a.out corrupted"); #endif #ifdef ENOLCK - inscode(d, ds, de, "ENOLCK", ENOLCK, "No record locks available"); + inscode(d, ds, de, "ENOLCK", ENOLCK, "No record locks available"); #endif #ifdef EISNAM - inscode(d, ds, de, "EISNAM", EISNAM, "Is a named type file"); + inscode(d, ds, de, "EISNAM", EISNAM, "Is a named type file"); #endif #ifdef ECONNABORTED - inscode(d, ds, de, "ECONNABORTED", ECONNABORTED, "Software caused connection abort"); + inscode(d, ds, de, "ECONNABORTED", ECONNABORTED, "Software caused connection abort"); #else #ifdef WSAECONNABORTED - inscode(d, ds, de, "ECONNABORTED", WSAECONNABORTED, "Software caused connection abort"); + inscode(d, ds, de, "ECONNABORTED", WSAECONNABORTED, "Software caused connection abort"); #endif #endif #ifdef ENETUNREACH - inscode(d, ds, de, "ENETUNREACH", ENETUNREACH, "Network is unreachable"); + inscode(d, ds, de, "ENETUNREACH", ENETUNREACH, "Network is unreachable"); #else #ifdef WSAENETUNREACH - inscode(d, ds, de, "ENETUNREACH", WSAENETUNREACH, "Network is unreachable"); + inscode(d, ds, de, "ENETUNREACH", WSAENETUNREACH, "Network is unreachable"); #endif #endif #ifdef ESTALE - inscode(d, ds, de, "ESTALE", ESTALE, "Stale NFS file handle"); + inscode(d, ds, de, "ESTALE", ESTALE, "Stale NFS file handle"); #else #ifdef WSAESTALE - inscode(d, ds, de, "ESTALE", WSAESTALE, "Stale NFS file handle"); + inscode(d, ds, de, "ESTALE", WSAESTALE, "Stale NFS file handle"); #endif #endif #ifdef ENOSR - inscode(d, ds, de, "ENOSR", ENOSR, "Out of streams resources"); + inscode(d, ds, de, "ENOSR", ENOSR, "Out of streams resources"); #endif #ifdef ENOMEM - inscode(d, ds, de, "ENOMEM", ENOMEM, "Out of memory"); + inscode(d, ds, de, "ENOMEM", ENOMEM, "Out of memory"); #endif #ifdef ENOTSOCK - inscode(d, ds, de, "ENOTSOCK", ENOTSOCK, "Socket operation on non-socket"); + inscode(d, ds, de, "ENOTSOCK", ENOTSOCK, "Socket operation on non-socket"); #else #ifdef WSAENOTSOCK - inscode(d, ds, de, "ENOTSOCK", WSAENOTSOCK, "Socket operation on non-socket"); + inscode(d, ds, de, "ENOTSOCK", WSAENOTSOCK, "Socket operation on non-socket"); #endif #endif #ifdef ESTRPIPE - inscode(d, ds, de, "ESTRPIPE", ESTRPIPE, "Streams pipe error"); + inscode(d, ds, de, "ESTRPIPE", ESTRPIPE, "Streams pipe error"); #endif #ifdef EMLINK - inscode(d, ds, de, "EMLINK", EMLINK, "Too many links"); + inscode(d, ds, de, "EMLINK", EMLINK, "Too many links"); #endif #ifdef ERANGE - inscode(d, ds, de, "ERANGE", ERANGE, "Math result not representable"); + inscode(d, ds, de, "ERANGE", ERANGE, "Math result not representable"); #endif #ifdef ELIBEXEC - inscode(d, ds, de, "ELIBEXEC", ELIBEXEC, "Cannot exec a shared library directly"); + inscode(d, ds, de, "ELIBEXEC", ELIBEXEC, "Cannot exec a shared library directly"); #endif #ifdef EL3HLT - inscode(d, ds, de, "EL3HLT", EL3HLT, "Level 3 halted"); + inscode(d, ds, de, "EL3HLT", EL3HLT, "Level 3 halted"); #endif #ifdef ECONNRESET - inscode(d, ds, de, "ECONNRESET", ECONNRESET, "Connection reset by peer"); + inscode(d, ds, de, "ECONNRESET", ECONNRESET, "Connection reset by peer"); #else #ifdef WSAECONNRESET - inscode(d, ds, de, "ECONNRESET", WSAECONNRESET, "Connection reset by peer"); + inscode(d, ds, de, "ECONNRESET", WSAECONNRESET, "Connection reset by peer"); #endif #endif #ifdef EADDRINUSE - inscode(d, ds, de, "EADDRINUSE", EADDRINUSE, "Address already in use"); + inscode(d, ds, de, "EADDRINUSE", EADDRINUSE, "Address already in use"); #else #ifdef WSAEADDRINUSE - inscode(d, ds, de, "EADDRINUSE", WSAEADDRINUSE, "Address already in use"); + inscode(d, ds, de, "EADDRINUSE", WSAEADDRINUSE, "Address already in use"); #endif #endif #ifdef EOPNOTSUPP - inscode(d, ds, de, "EOPNOTSUPP", EOPNOTSUPP, "Operation not supported on transport endpoint"); + inscode(d, ds, de, "EOPNOTSUPP", EOPNOTSUPP, "Operation not supported on transport endpoint"); #else #ifdef WSAEOPNOTSUPP - inscode(d, ds, de, "EOPNOTSUPP", WSAEOPNOTSUPP, "Operation not supported on transport endpoint"); + inscode(d, ds, de, "EOPNOTSUPP", WSAEOPNOTSUPP, "Operation not supported on transport endpoint"); #endif #endif #ifdef EREMCHG - inscode(d, ds, de, "EREMCHG", EREMCHG, "Remote address changed"); + inscode(d, ds, de, "EREMCHG", EREMCHG, "Remote address changed"); #endif #ifdef EAGAIN - inscode(d, ds, de, "EAGAIN", EAGAIN, "Try again"); + inscode(d, ds, de, "EAGAIN", EAGAIN, "Try again"); #endif #ifdef ENAMETOOLONG - inscode(d, ds, de, "ENAMETOOLONG", ENAMETOOLONG, "File name too long"); + inscode(d, ds, de, "ENAMETOOLONG", ENAMETOOLONG, "File name too long"); #else #ifdef WSAENAMETOOLONG - inscode(d, ds, de, "ENAMETOOLONG", WSAENAMETOOLONG, "File name too long"); + inscode(d, ds, de, "ENAMETOOLONG", WSAENAMETOOLONG, "File name too long"); #endif #endif #ifdef ENOTTY - inscode(d, ds, de, "ENOTTY", ENOTTY, "Not a typewriter"); + inscode(d, ds, de, "ENOTTY", ENOTTY, "Not a typewriter"); #endif #ifdef ERESTART - inscode(d, ds, de, "ERESTART", ERESTART, "Interrupted system call should be restarted"); + inscode(d, ds, de, "ERESTART", ERESTART, "Interrupted system call should be restarted"); #endif #ifdef ESOCKTNOSUPPORT - inscode(d, ds, de, "ESOCKTNOSUPPORT", ESOCKTNOSUPPORT, "Socket type not supported"); + inscode(d, ds, de, "ESOCKTNOSUPPORT", ESOCKTNOSUPPORT, "Socket type not supported"); #else #ifdef WSAESOCKTNOSUPPORT - inscode(d, ds, de, "ESOCKTNOSUPPORT", WSAESOCKTNOSUPPORT, "Socket type not supported"); + inscode(d, ds, de, "ESOCKTNOSUPPORT", WSAESOCKTNOSUPPORT, "Socket type not supported"); #endif #endif #ifdef ETIME - inscode(d, ds, de, "ETIME", ETIME, "Timer expired"); + inscode(d, ds, de, "ETIME", ETIME, "Timer expired"); #endif #ifdef EBFONT - inscode(d, ds, de, "EBFONT", EBFONT, "Bad font file format"); + inscode(d, ds, de, "EBFONT", EBFONT, "Bad font file format"); #endif #ifdef EDEADLOCK - inscode(d, ds, de, "EDEADLOCK", EDEADLOCK, "Error EDEADLOCK"); + inscode(d, ds, de, "EDEADLOCK", EDEADLOCK, "Error EDEADLOCK"); #endif #ifdef ETOOMANYREFS - inscode(d, ds, de, "ETOOMANYREFS", ETOOMANYREFS, "Too many references: cannot splice"); + inscode(d, ds, de, "ETOOMANYREFS", ETOOMANYREFS, "Too many references: cannot splice"); #else #ifdef WSAETOOMANYREFS - inscode(d, ds, de, "ETOOMANYREFS", WSAETOOMANYREFS, "Too many references: cannot splice"); + inscode(d, ds, de, "ETOOMANYREFS", WSAETOOMANYREFS, "Too many references: cannot splice"); #endif #endif #ifdef EMFILE - inscode(d, ds, de, "EMFILE", EMFILE, "Too many open files"); + inscode(d, ds, de, "EMFILE", EMFILE, "Too many open files"); #else #ifdef WSAEMFILE - inscode(d, ds, de, "EMFILE", WSAEMFILE, "Too many open files"); + inscode(d, ds, de, "EMFILE", WSAEMFILE, "Too many open files"); #endif #endif #ifdef ETXTBSY - inscode(d, ds, de, "ETXTBSY", ETXTBSY, "Text file busy"); + inscode(d, ds, de, "ETXTBSY", ETXTBSY, "Text file busy"); #endif #ifdef EINPROGRESS - inscode(d, ds, de, "EINPROGRESS", EINPROGRESS, "Operation now in progress"); + inscode(d, ds, de, "EINPROGRESS", EINPROGRESS, "Operation now in progress"); #else #ifdef WSAEINPROGRESS - inscode(d, ds, de, "EINPROGRESS", WSAEINPROGRESS, "Operation now in progress"); + inscode(d, ds, de, "EINPROGRESS", WSAEINPROGRESS, "Operation now in progress"); #endif #endif #ifdef ENXIO - inscode(d, ds, de, "ENXIO", ENXIO, "No such device or address"); + inscode(d, ds, de, "ENXIO", ENXIO, "No such device or address"); #endif #ifdef ENOPKG - inscode(d, ds, de, "ENOPKG", ENOPKG, "Package not installed"); + inscode(d, ds, de, "ENOPKG", ENOPKG, "Package not installed"); #endif #ifdef WSASY - inscode(d, ds, de, "WSASY", WSASY, "Error WSASY"); + inscode(d, ds, de, "WSASY", WSASY, "Error WSASY"); #endif #ifdef WSAEHOSTDOWN - inscode(d, ds, de, "WSAEHOSTDOWN", WSAEHOSTDOWN, "Host is down"); + inscode(d, ds, de, "WSAEHOSTDOWN", WSAEHOSTDOWN, "Host is down"); #endif #ifdef WSAENETDOWN - inscode(d, ds, de, "WSAENETDOWN", WSAENETDOWN, "Network is down"); + inscode(d, ds, de, "WSAENETDOWN", WSAENETDOWN, "Network is down"); #endif #ifdef WSAENOTSOCK - inscode(d, ds, de, "WSAENOTSOCK", WSAENOTSOCK, "Socket operation on non-socket"); + inscode(d, ds, de, "WSAENOTSOCK", WSAENOTSOCK, "Socket operation on non-socket"); #endif #ifdef WSAEHOSTUNREACH - inscode(d, ds, de, "WSAEHOSTUNREACH", WSAEHOSTUNREACH, "No route to host"); + inscode(d, ds, de, "WSAEHOSTUNREACH", WSAEHOSTUNREACH, "No route to host"); #endif #ifdef WSAELOOP - inscode(d, ds, de, "WSAELOOP", WSAELOOP, "Too many symbolic links encountered"); + inscode(d, ds, de, "WSAELOOP", WSAELOOP, "Too many symbolic links encountered"); #endif #ifdef WSAEMFILE - inscode(d, ds, de, "WSAEMFILE", WSAEMFILE, "Too many open files"); + inscode(d, ds, de, "WSAEMFILE", WSAEMFILE, "Too many open files"); #endif #ifdef WSAESTALE - inscode(d, ds, de, "WSAESTALE", WSAESTALE, "Stale NFS file handle"); + inscode(d, ds, de, "WSAESTALE", WSAESTALE, "Stale NFS file handle"); #endif #ifdef WSAVERNOTSUPPORTED - inscode(d, ds, de, "WSAVERNOTSUPPORTED", WSAVERNOTSUPPORTED, "Error WSAVERNOTSUPPORTED"); + inscode(d, ds, de, "WSAVERNOTSUPPORTED", WSAVERNOTSUPPORTED, "Error WSAVERNOTSUPPORTED"); #endif #ifdef WSAENETUNREACH - inscode(d, ds, de, "WSAENETUNREACH", WSAENETUNREACH, "Network is unreachable"); + inscode(d, ds, de, "WSAENETUNREACH", WSAENETUNREACH, "Network is unreachable"); #endif #ifdef WSAEPROCLIM - inscode(d, ds, de, "WSAEPROCLIM", WSAEPROCLIM, "Error WSAEPROCLIM"); + inscode(d, ds, de, "WSAEPROCLIM", WSAEPROCLIM, "Error WSAEPROCLIM"); #endif #ifdef WSAEFAULT - inscode(d, ds, de, "WSAEFAULT", WSAEFAULT, "Bad address"); + inscode(d, ds, de, "WSAEFAULT", WSAEFAULT, "Bad address"); #endif #ifdef WSANOTINITIALISED - inscode(d, ds, de, "WSANOTINITIALISED", WSANOTINITIALISED, "Error WSANOTINITIALISED"); + inscode(d, ds, de, "WSANOTINITIALISED", WSANOTINITIALISED, "Error WSANOTINITIALISED"); #endif #ifdef WSAEUSERS - inscode(d, ds, de, "WSAEUSERS", WSAEUSERS, "Too many users"); + inscode(d, ds, de, "WSAEUSERS", WSAEUSERS, "Too many users"); #endif #ifdef WSAMAKEASYNCREPL - inscode(d, ds, de, "WSAMAKEASYNCREPL", WSAMAKEASYNCREPL, "Error WSAMAKEASYNCREPL"); + inscode(d, ds, de, "WSAMAKEASYNCREPL", WSAMAKEASYNCREPL, "Error WSAMAKEASYNCREPL"); #endif #ifdef WSAENOPROTOOPT - inscode(d, ds, de, "WSAENOPROTOOPT", WSAENOPROTOOPT, "Protocol not available"); + inscode(d, ds, de, "WSAENOPROTOOPT", WSAENOPROTOOPT, "Protocol not available"); #endif #ifdef WSAECONNABORTED - inscode(d, ds, de, "WSAECONNABORTED", WSAECONNABORTED, "Software caused connection abort"); + inscode(d, ds, de, "WSAECONNABORTED", WSAECONNABORTED, "Software caused connection abort"); #endif #ifdef WSAENAMETOOLONG - inscode(d, ds, de, "WSAENAMETOOLONG", WSAENAMETOOLONG, "File name too long"); + inscode(d, ds, de, "WSAENAMETOOLONG", WSAENAMETOOLONG, "File name too long"); #endif #ifdef WSAENOTEMPTY - inscode(d, ds, de, "WSAENOTEMPTY", WSAENOTEMPTY, "Directory not empty"); + inscode(d, ds, de, "WSAENOTEMPTY", WSAENOTEMPTY, "Directory not empty"); #endif #ifdef WSAESHUTDOWN - inscode(d, ds, de, "WSAESHUTDOWN", WSAESHUTDOWN, "Cannot send after transport endpoint shutdown"); + inscode(d, ds, de, "WSAESHUTDOWN", WSAESHUTDOWN, "Cannot send after transport endpoint shutdown"); #endif #ifdef WSAEAFNOSUPPORT - inscode(d, ds, de, "WSAEAFNOSUPPORT", WSAEAFNOSUPPORT, "Address family not supported by protocol"); + inscode(d, ds, de, "WSAEAFNOSUPPORT", WSAEAFNOSUPPORT, "Address family not supported by protocol"); #endif #ifdef WSAETOOMANYREFS - inscode(d, ds, de, "WSAETOOMANYREFS", WSAETOOMANYREFS, "Too many references: cannot splice"); + inscode(d, ds, de, "WSAETOOMANYREFS", WSAETOOMANYREFS, "Too many references: cannot splice"); #endif #ifdef WSAEACCES - inscode(d, ds, de, "WSAEACCES", WSAEACCES, "Permission denied"); + inscode(d, ds, de, "WSAEACCES", WSAEACCES, "Permission denied"); #endif #ifdef WSATR - inscode(d, ds, de, "WSATR", WSATR, "Error WSATR"); + inscode(d, ds, de, "WSATR", WSATR, "Error WSATR"); #endif #ifdef WSABASEERR - inscode(d, ds, de, "WSABASEERR", WSABASEERR, "Error WSABASEERR"); + inscode(d, ds, de, "WSABASEERR", WSABASEERR, "Error WSABASEERR"); #endif #ifdef WSADESCRIPTIO - inscode(d, ds, de, "WSADESCRIPTIO", WSADESCRIPTIO, "Error WSADESCRIPTIO"); + inscode(d, ds, de, "WSADESCRIPTIO", WSADESCRIPTIO, "Error WSADESCRIPTIO"); #endif #ifdef WSAEMSGSIZE - inscode(d, ds, de, "WSAEMSGSIZE", WSAEMSGSIZE, "Message too long"); + inscode(d, ds, de, "WSAEMSGSIZE", WSAEMSGSIZE, "Message too long"); #endif #ifdef WSAEBADF - inscode(d, ds, de, "WSAEBADF", WSAEBADF, "Bad file number"); + inscode(d, ds, de, "WSAEBADF", WSAEBADF, "Bad file number"); #endif #ifdef WSAECONNRESET - inscode(d, ds, de, "WSAECONNRESET", WSAECONNRESET, "Connection reset by peer"); + inscode(d, ds, de, "WSAECONNRESET", WSAECONNRESET, "Connection reset by peer"); #endif #ifdef WSAGETSELECTERRO - inscode(d, ds, de, "WSAGETSELECTERRO", WSAGETSELECTERRO, "Error WSAGETSELECTERRO"); + inscode(d, ds, de, "WSAGETSELECTERRO", WSAGETSELECTERRO, "Error WSAGETSELECTERRO"); #endif #ifdef WSAETIMEDOUT - inscode(d, ds, de, "WSAETIMEDOUT", WSAETIMEDOUT, "Connection timed out"); + inscode(d, ds, de, "WSAETIMEDOUT", WSAETIMEDOUT, "Connection timed out"); #endif #ifdef WSAENOBUFS - inscode(d, ds, de, "WSAENOBUFS", WSAENOBUFS, "No buffer space available"); + inscode(d, ds, de, "WSAENOBUFS", WSAENOBUFS, "No buffer space available"); #endif #ifdef WSAEDISCON - inscode(d, ds, de, "WSAEDISCON", WSAEDISCON, "Error WSAEDISCON"); + inscode(d, ds, de, "WSAEDISCON", WSAEDISCON, "Error WSAEDISCON"); #endif #ifdef WSAEINTR - inscode(d, ds, de, "WSAEINTR", WSAEINTR, "Interrupted system call"); + inscode(d, ds, de, "WSAEINTR", WSAEINTR, "Interrupted system call"); #endif #ifdef WSAEPROTOTYPE - inscode(d, ds, de, "WSAEPROTOTYPE", WSAEPROTOTYPE, "Protocol wrong type for socket"); + inscode(d, ds, de, "WSAEPROTOTYPE", WSAEPROTOTYPE, "Protocol wrong type for socket"); #endif #ifdef WSAHOS - inscode(d, ds, de, "WSAHOS", WSAHOS, "Error WSAHOS"); + inscode(d, ds, de, "WSAHOS", WSAHOS, "Error WSAHOS"); #endif #ifdef WSAEADDRINUSE - inscode(d, ds, de, "WSAEADDRINUSE", WSAEADDRINUSE, "Address already in use"); + inscode(d, ds, de, "WSAEADDRINUSE", WSAEADDRINUSE, "Address already in use"); #endif #ifdef WSAEADDRNOTAVAIL - inscode(d, ds, de, "WSAEADDRNOTAVAIL", WSAEADDRNOTAVAIL, "Cannot assign requested address"); + inscode(d, ds, de, "WSAEADDRNOTAVAIL", WSAEADDRNOTAVAIL, "Cannot assign requested address"); #endif #ifdef WSAEALREADY - inscode(d, ds, de, "WSAEALREADY", WSAEALREADY, "Operation already in progress"); + inscode(d, ds, de, "WSAEALREADY", WSAEALREADY, "Operation already in progress"); #endif #ifdef WSAEPROTONOSUPPORT - inscode(d, ds, de, "WSAEPROTONOSUPPORT", WSAEPROTONOSUPPORT, "Protocol not supported"); + inscode(d, ds, de, "WSAEPROTONOSUPPORT", WSAEPROTONOSUPPORT, "Protocol not supported"); #endif #ifdef WSASYSNOTREADY - inscode(d, ds, de, "WSASYSNOTREADY", WSASYSNOTREADY, "Error WSASYSNOTREADY"); + inscode(d, ds, de, "WSASYSNOTREADY", WSASYSNOTREADY, "Error WSASYSNOTREADY"); #endif #ifdef WSAEWOULDBLOCK - inscode(d, ds, de, "WSAEWOULDBLOCK", WSAEWOULDBLOCK, "Operation would block"); + inscode(d, ds, de, "WSAEWOULDBLOCK", WSAEWOULDBLOCK, "Operation would block"); #endif #ifdef WSAEPFNOSUPPORT - inscode(d, ds, de, "WSAEPFNOSUPPORT", WSAEPFNOSUPPORT, "Protocol family not supported"); + inscode(d, ds, de, "WSAEPFNOSUPPORT", WSAEPFNOSUPPORT, "Protocol family not supported"); #endif #ifdef WSAEOPNOTSUPP - inscode(d, ds, de, "WSAEOPNOTSUPP", WSAEOPNOTSUPP, "Operation not supported on transport endpoint"); + inscode(d, ds, de, "WSAEOPNOTSUPP", WSAEOPNOTSUPP, "Operation not supported on transport endpoint"); #endif #ifdef WSAEISCONN - inscode(d, ds, de, "WSAEISCONN", WSAEISCONN, "Transport endpoint is already connected"); + inscode(d, ds, de, "WSAEISCONN", WSAEISCONN, "Transport endpoint is already connected"); #endif #ifdef WSAEDQUOT - inscode(d, ds, de, "WSAEDQUOT", WSAEDQUOT, "Quota exceeded"); + inscode(d, ds, de, "WSAEDQUOT", WSAEDQUOT, "Quota exceeded"); #endif #ifdef WSAENOTCONN - inscode(d, ds, de, "WSAENOTCONN", WSAENOTCONN, "Transport endpoint is not connected"); + inscode(d, ds, de, "WSAENOTCONN", WSAENOTCONN, "Transport endpoint is not connected"); #endif #ifdef WSAEREMOTE - inscode(d, ds, de, "WSAEREMOTE", WSAEREMOTE, "Object is remote"); + inscode(d, ds, de, "WSAEREMOTE", WSAEREMOTE, "Object is remote"); #endif #ifdef WSAEINVAL - inscode(d, ds, de, "WSAEINVAL", WSAEINVAL, "Invalid argument"); + inscode(d, ds, de, "WSAEINVAL", WSAEINVAL, "Invalid argument"); #endif #ifdef WSAEINPROGRESS - inscode(d, ds, de, "WSAEINPROGRESS", WSAEINPROGRESS, "Operation now in progress"); + inscode(d, ds, de, "WSAEINPROGRESS", WSAEINPROGRESS, "Operation now in progress"); #endif #ifdef WSAGETSELECTEVEN - inscode(d, ds, de, "WSAGETSELECTEVEN", WSAGETSELECTEVEN, "Error WSAGETSELECTEVEN"); + inscode(d, ds, de, "WSAGETSELECTEVEN", WSAGETSELECTEVEN, "Error WSAGETSELECTEVEN"); #endif #ifdef WSAESOCKTNOSUPPORT - inscode(d, ds, de, "WSAESOCKTNOSUPPORT", WSAESOCKTNOSUPPORT, "Socket type not supported"); + inscode(d, ds, de, "WSAESOCKTNOSUPPORT", WSAESOCKTNOSUPPORT, "Socket type not supported"); #endif #ifdef WSAGETASYNCERRO - inscode(d, ds, de, "WSAGETASYNCERRO", WSAGETASYNCERRO, "Error WSAGETASYNCERRO"); + inscode(d, ds, de, "WSAGETASYNCERRO", WSAGETASYNCERRO, "Error WSAGETASYNCERRO"); #endif #ifdef WSAMAKESELECTREPL - inscode(d, ds, de, "WSAMAKESELECTREPL", WSAMAKESELECTREPL, "Error WSAMAKESELECTREPL"); + inscode(d, ds, de, "WSAMAKESELECTREPL", WSAMAKESELECTREPL, "Error WSAMAKESELECTREPL"); #endif #ifdef WSAGETASYNCBUFLE - inscode(d, ds, de, "WSAGETASYNCBUFLE", WSAGETASYNCBUFLE, "Error WSAGETASYNCBUFLE"); + inscode(d, ds, de, "WSAGETASYNCBUFLE", WSAGETASYNCBUFLE, "Error WSAGETASYNCBUFLE"); #endif #ifdef WSAEDESTADDRREQ - inscode(d, ds, de, "WSAEDESTADDRREQ", WSAEDESTADDRREQ, "Destination address required"); + inscode(d, ds, de, "WSAEDESTADDRREQ", WSAEDESTADDRREQ, "Destination address required"); #endif #ifdef WSAECONNREFUSED - inscode(d, ds, de, "WSAECONNREFUSED", WSAECONNREFUSED, "Connection refused"); + inscode(d, ds, de, "WSAECONNREFUSED", WSAECONNREFUSED, "Connection refused"); #endif #ifdef WSAENETRESET - inscode(d, ds, de, "WSAENETRESET", WSAENETRESET, "Network dropped connection because of reset"); + inscode(d, ds, de, "WSAENETRESET", WSAENETRESET, "Network dropped connection because of reset"); #endif #ifdef WSAN - inscode(d, ds, de, "WSAN", WSAN, "Error WSAN"); + inscode(d, ds, de, "WSAN", WSAN, "Error WSAN"); #endif - Py_DECREF(de); - return m; + Py_DECREF(de); + return m; } Modified: python/branches/py3k/Modules/fcntlmodule.c ============================================================================== --- python/branches/py3k/Modules/fcntlmodule.c (original) +++ python/branches/py3k/Modules/fcntlmodule.c Sun May 9 17:52:27 2010 @@ -21,7 +21,7 @@ int fd = PyObject_AsFileDescriptor(object); if (fd < 0) - return 0; + return 0; *target = fd; return 1; } @@ -32,48 +32,48 @@ static PyObject * fcntl_fcntl(PyObject *self, PyObject *args) { - int fd; - int code; - long arg; - int ret; - char *str; - Py_ssize_t len; - char buf[1024]; - - if (PyArg_ParseTuple(args, "O&is#:fcntl", - conv_descriptor, &fd, &code, &str, &len)) { - if (len > sizeof buf) { - PyErr_SetString(PyExc_ValueError, - "fcntl string arg too long"); - return NULL; - } - memcpy(buf, str, len); - Py_BEGIN_ALLOW_THREADS - ret = fcntl(fd, code, buf); - Py_END_ALLOW_THREADS - if (ret < 0) { - PyErr_SetFromErrno(PyExc_IOError); - return NULL; - } - return PyBytes_FromStringAndSize(buf, len); - } - - PyErr_Clear(); - arg = 0; - if (!PyArg_ParseTuple(args, - "O&i|l;fcntl requires a file or file descriptor," - " an integer and optionally a third integer or a string", - conv_descriptor, &fd, &code, &arg)) { - return NULL; - } - Py_BEGIN_ALLOW_THREADS - ret = fcntl(fd, code, arg); - Py_END_ALLOW_THREADS - if (ret < 0) { - PyErr_SetFromErrno(PyExc_IOError); - return NULL; - } - return PyLong_FromLong((long)ret); + int fd; + int code; + long arg; + int ret; + char *str; + Py_ssize_t len; + char buf[1024]; + + if (PyArg_ParseTuple(args, "O&is#:fcntl", + conv_descriptor, &fd, &code, &str, &len)) { + if (len > sizeof buf) { + PyErr_SetString(PyExc_ValueError, + "fcntl string arg too long"); + return NULL; + } + memcpy(buf, str, len); + Py_BEGIN_ALLOW_THREADS + ret = fcntl(fd, code, buf); + Py_END_ALLOW_THREADS + if (ret < 0) { + PyErr_SetFromErrno(PyExc_IOError); + return NULL; + } + return PyBytes_FromStringAndSize(buf, len); + } + + PyErr_Clear(); + arg = 0; + if (!PyArg_ParseTuple(args, + "O&i|l;fcntl requires a file or file descriptor," + " an integer and optionally a third integer or a string", + conv_descriptor, &fd, &code, &arg)) { + return NULL; + } + Py_BEGIN_ALLOW_THREADS + ret = fcntl(fd, code, arg); + Py_END_ALLOW_THREADS + if (ret < 0) { + PyErr_SetFromErrno(PyExc_IOError); + return NULL; + } + return PyLong_FromLong((long)ret); } PyDoc_STRVAR(fcntl_doc, @@ -96,128 +96,128 @@ fcntl_ioctl(PyObject *self, PyObject *args) { #define IOCTL_BUFSZ 1024 - int fd; - /* In PyArg_ParseTuple below, we use the unsigned non-checked 'I' - format for the 'code' parameter because Python turns 0x8000000 - into either a large positive number (PyLong or PyInt on 64-bit - platforms) or a negative number on others (32-bit PyInt) - whereas the system expects it to be a 32bit bit field value - regardless of it being passed as an int or unsigned long on - various platforms. See the termios.TIOCSWINSZ constant across - platforms for an example of thise. - - If any of the 64bit platforms ever decide to use more than 32bits - in their unsigned long ioctl codes this will break and need - special casing based on the platform being built on. - */ - unsigned int code; - int arg; - int ret; - Py_buffer pstr; - char *str; - Py_ssize_t len; - int mutate_arg = 1; - char buf[IOCTL_BUFSZ+1]; /* argument plus NUL byte */ - - if (PyArg_ParseTuple(args, "O&Iw*|i:ioctl", - conv_descriptor, &fd, &code, - &pstr, &mutate_arg)) { - char *arg; - str = pstr.buf; - len = pstr.len; - - if (mutate_arg) { - if (len <= IOCTL_BUFSZ) { - memcpy(buf, str, len); - buf[len] = '\0'; - arg = buf; - } - else { - arg = str; - } - } - else { - if (len > IOCTL_BUFSZ) { - PyBuffer_Release(&pstr); - PyErr_SetString(PyExc_ValueError, - "ioctl string arg too long"); - return NULL; - } - else { - memcpy(buf, str, len); - buf[len] = '\0'; - arg = buf; - } - } - if (buf == arg) { - Py_BEGIN_ALLOW_THREADS /* think array.resize() */ - ret = ioctl(fd, code, arg); - Py_END_ALLOW_THREADS - } - else { - ret = ioctl(fd, code, arg); - } - if (mutate_arg && (len < IOCTL_BUFSZ)) { - memcpy(str, buf, len); - } - PyBuffer_Release(&pstr); /* No further access to str below this point */ - if (ret < 0) { - PyErr_SetFromErrno(PyExc_IOError); - return NULL; - } - if (mutate_arg) { - return PyLong_FromLong(ret); - } - else { - return PyBytes_FromStringAndSize(buf, len); - } - } - - PyErr_Clear(); - if (PyArg_ParseTuple(args, "O&Is*:ioctl", - conv_descriptor, &fd, &code, &pstr)) { - str = pstr.buf; - len = pstr.len; - if (len > IOCTL_BUFSZ) { - PyBuffer_Release(&pstr); - PyErr_SetString(PyExc_ValueError, - "ioctl string arg too long"); - return NULL; - } - memcpy(buf, str, len); - buf[len] = '\0'; - Py_BEGIN_ALLOW_THREADS - ret = ioctl(fd, code, buf); - Py_END_ALLOW_THREADS - if (ret < 0) { - PyBuffer_Release(&pstr); - PyErr_SetFromErrno(PyExc_IOError); - return NULL; - } - PyBuffer_Release(&pstr); - return PyBytes_FromStringAndSize(buf, len); - } - - PyErr_Clear(); - arg = 0; - if (!PyArg_ParseTuple(args, - "O&I|i;ioctl requires a file or file descriptor," - " an integer and optionally an integer or buffer argument", - conv_descriptor, &fd, &code, &arg)) { - return NULL; - } - Py_BEGIN_ALLOW_THREADS + int fd; + /* In PyArg_ParseTuple below, we use the unsigned non-checked 'I' + format for the 'code' parameter because Python turns 0x8000000 + into either a large positive number (PyLong or PyInt on 64-bit + platforms) or a negative number on others (32-bit PyInt) + whereas the system expects it to be a 32bit bit field value + regardless of it being passed as an int or unsigned long on + various platforms. See the termios.TIOCSWINSZ constant across + platforms for an example of thise. + + If any of the 64bit platforms ever decide to use more than 32bits + in their unsigned long ioctl codes this will break and need + special casing based on the platform being built on. + */ + unsigned int code; + int arg; + int ret; + Py_buffer pstr; + char *str; + Py_ssize_t len; + int mutate_arg = 1; + char buf[IOCTL_BUFSZ+1]; /* argument plus NUL byte */ + + if (PyArg_ParseTuple(args, "O&Iw*|i:ioctl", + conv_descriptor, &fd, &code, + &pstr, &mutate_arg)) { + char *arg; + str = pstr.buf; + len = pstr.len; + + if (mutate_arg) { + if (len <= IOCTL_BUFSZ) { + memcpy(buf, str, len); + buf[len] = '\0'; + arg = buf; + } + else { + arg = str; + } + } + else { + if (len > IOCTL_BUFSZ) { + PyBuffer_Release(&pstr); + PyErr_SetString(PyExc_ValueError, + "ioctl string arg too long"); + return NULL; + } + else { + memcpy(buf, str, len); + buf[len] = '\0'; + arg = buf; + } + } + if (buf == arg) { + Py_BEGIN_ALLOW_THREADS /* think array.resize() */ + ret = ioctl(fd, code, arg); + Py_END_ALLOW_THREADS + } + else { + ret = ioctl(fd, code, arg); + } + if (mutate_arg && (len < IOCTL_BUFSZ)) { + memcpy(str, buf, len); + } + PyBuffer_Release(&pstr); /* No further access to str below this point */ + if (ret < 0) { + PyErr_SetFromErrno(PyExc_IOError); + return NULL; + } + if (mutate_arg) { + return PyLong_FromLong(ret); + } + else { + return PyBytes_FromStringAndSize(buf, len); + } + } + + PyErr_Clear(); + if (PyArg_ParseTuple(args, "O&Is*:ioctl", + conv_descriptor, &fd, &code, &pstr)) { + str = pstr.buf; + len = pstr.len; + if (len > IOCTL_BUFSZ) { + PyBuffer_Release(&pstr); + PyErr_SetString(PyExc_ValueError, + "ioctl string arg too long"); + return NULL; + } + memcpy(buf, str, len); + buf[len] = '\0'; + Py_BEGIN_ALLOW_THREADS + ret = ioctl(fd, code, buf); + Py_END_ALLOW_THREADS + if (ret < 0) { + PyBuffer_Release(&pstr); + PyErr_SetFromErrno(PyExc_IOError); + return NULL; + } + PyBuffer_Release(&pstr); + return PyBytes_FromStringAndSize(buf, len); + } + + PyErr_Clear(); + arg = 0; + if (!PyArg_ParseTuple(args, + "O&I|i;ioctl requires a file or file descriptor," + " an integer and optionally an integer or buffer argument", + conv_descriptor, &fd, &code, &arg)) { + return NULL; + } + Py_BEGIN_ALLOW_THREADS #ifdef __VMS - ret = ioctl(fd, code, (void *)arg); + ret = ioctl(fd, code, (void *)arg); #else - ret = ioctl(fd, code, arg); + ret = ioctl(fd, code, arg); #endif - Py_END_ALLOW_THREADS - if (ret < 0) { - PyErr_SetFromErrno(PyExc_IOError); - return NULL; - } - return PyLong_FromLong((long)ret); + Py_END_ALLOW_THREADS + if (ret < 0) { + PyErr_SetFromErrno(PyExc_IOError); + return NULL; + } + return PyLong_FromLong((long)ret); #undef IOCTL_BUFSZ } @@ -258,51 +258,51 @@ static PyObject * fcntl_flock(PyObject *self, PyObject *args) { - int fd; - int code; - int ret; - - if (!PyArg_ParseTuple(args, "O&i:flock", - conv_descriptor, &fd, &code)) - return NULL; + int fd; + int code; + int ret; + + if (!PyArg_ParseTuple(args, "O&i:flock", + conv_descriptor, &fd, &code)) + return NULL; #ifdef HAVE_FLOCK - Py_BEGIN_ALLOW_THREADS - ret = flock(fd, code); - Py_END_ALLOW_THREADS + Py_BEGIN_ALLOW_THREADS + ret = flock(fd, code); + Py_END_ALLOW_THREADS #else #ifndef LOCK_SH -#define LOCK_SH 1 /* shared lock */ -#define LOCK_EX 2 /* exclusive lock */ -#define LOCK_NB 4 /* don't block when locking */ -#define LOCK_UN 8 /* unlock */ -#endif - { - struct flock l; - if (code == LOCK_UN) - l.l_type = F_UNLCK; - else if (code & LOCK_SH) - l.l_type = F_RDLCK; - else if (code & LOCK_EX) - l.l_type = F_WRLCK; - else { - PyErr_SetString(PyExc_ValueError, - "unrecognized flock argument"); - return NULL; - } - l.l_whence = l.l_start = l.l_len = 0; - Py_BEGIN_ALLOW_THREADS - ret = fcntl(fd, (code & LOCK_NB) ? F_SETLK : F_SETLKW, &l); - Py_END_ALLOW_THREADS - } +#define LOCK_SH 1 /* shared lock */ +#define LOCK_EX 2 /* exclusive lock */ +#define LOCK_NB 4 /* don't block when locking */ +#define LOCK_UN 8 /* unlock */ +#endif + { + struct flock l; + if (code == LOCK_UN) + l.l_type = F_UNLCK; + else if (code & LOCK_SH) + l.l_type = F_RDLCK; + else if (code & LOCK_EX) + l.l_type = F_WRLCK; + else { + PyErr_SetString(PyExc_ValueError, + "unrecognized flock argument"); + return NULL; + } + l.l_whence = l.l_start = l.l_len = 0; + Py_BEGIN_ALLOW_THREADS + ret = fcntl(fd, (code & LOCK_NB) ? F_SETLK : F_SETLKW, &l); + Py_END_ALLOW_THREADS + } #endif /* HAVE_FLOCK */ - if (ret < 0) { - PyErr_SetFromErrno(PyExc_IOError); - return NULL; - } - Py_INCREF(Py_None); - return Py_None; + if (ret < 0) { + PyErr_SetFromErrno(PyExc_IOError); + return NULL; + } + Py_INCREF(Py_None); + return Py_None; } PyDoc_STRVAR(flock_doc, @@ -317,72 +317,72 @@ static PyObject * fcntl_lockf(PyObject *self, PyObject *args) { - int fd, code, ret, whence = 0; - PyObject *lenobj = NULL, *startobj = NULL; + int fd, code, ret, whence = 0; + PyObject *lenobj = NULL, *startobj = NULL; - if (!PyArg_ParseTuple(args, "O&i|OOi:lockf", - conv_descriptor, &fd, &code, - &lenobj, &startobj, &whence)) - return NULL; + if (!PyArg_ParseTuple(args, "O&i|OOi:lockf", + conv_descriptor, &fd, &code, + &lenobj, &startobj, &whence)) + return NULL; #if defined(PYOS_OS2) && defined(PYCC_GCC) - PyErr_SetString(PyExc_NotImplementedError, - "lockf not supported on OS/2 (EMX)"); - return NULL; + PyErr_SetString(PyExc_NotImplementedError, + "lockf not supported on OS/2 (EMX)"); + return NULL; #else #ifndef LOCK_SH -#define LOCK_SH 1 /* shared lock */ -#define LOCK_EX 2 /* exclusive lock */ -#define LOCK_NB 4 /* don't block when locking */ -#define LOCK_UN 8 /* unlock */ +#define LOCK_SH 1 /* shared lock */ +#define LOCK_EX 2 /* exclusive lock */ +#define LOCK_NB 4 /* don't block when locking */ +#define LOCK_UN 8 /* unlock */ #endif /* LOCK_SH */ - { - struct flock l; - if (code == LOCK_UN) - l.l_type = F_UNLCK; - else if (code & LOCK_SH) - l.l_type = F_RDLCK; - else if (code & LOCK_EX) - l.l_type = F_WRLCK; - else { - PyErr_SetString(PyExc_ValueError, - "unrecognized lockf argument"); - return NULL; - } - l.l_start = l.l_len = 0; - if (startobj != NULL) { + { + struct flock l; + if (code == LOCK_UN) + l.l_type = F_UNLCK; + else if (code & LOCK_SH) + l.l_type = F_RDLCK; + else if (code & LOCK_EX) + l.l_type = F_WRLCK; + else { + PyErr_SetString(PyExc_ValueError, + "unrecognized lockf argument"); + return NULL; + } + l.l_start = l.l_len = 0; + if (startobj != NULL) { #if !defined(HAVE_LARGEFILE_SUPPORT) - l.l_start = PyLong_AsLong(startobj); + l.l_start = PyLong_AsLong(startobj); #else - l.l_start = PyLong_Check(startobj) ? - PyLong_AsLongLong(startobj) : - PyLong_AsLong(startobj); -#endif - if (PyErr_Occurred()) - return NULL; - } - if (lenobj != NULL) { + l.l_start = PyLong_Check(startobj) ? + PyLong_AsLongLong(startobj) : + PyLong_AsLong(startobj); +#endif + if (PyErr_Occurred()) + return NULL; + } + if (lenobj != NULL) { #if !defined(HAVE_LARGEFILE_SUPPORT) - l.l_len = PyLong_AsLong(lenobj); + l.l_len = PyLong_AsLong(lenobj); #else - l.l_len = PyLong_Check(lenobj) ? - PyLong_AsLongLong(lenobj) : - PyLong_AsLong(lenobj); -#endif - if (PyErr_Occurred()) - return NULL; - } - l.l_whence = whence; - Py_BEGIN_ALLOW_THREADS - ret = fcntl(fd, (code & LOCK_NB) ? F_SETLK : F_SETLKW, &l); - Py_END_ALLOW_THREADS - } - if (ret < 0) { - PyErr_SetFromErrno(PyExc_IOError); - return NULL; - } - Py_INCREF(Py_None); - return Py_None; + l.l_len = PyLong_Check(lenobj) ? + PyLong_AsLongLong(lenobj) : + PyLong_AsLong(lenobj); +#endif + if (PyErr_Occurred()) + return NULL; + } + l.l_whence = whence; + Py_BEGIN_ALLOW_THREADS + ret = fcntl(fd, (code & LOCK_NB) ? F_SETLK : F_SETLKW, &l); + Py_END_ALLOW_THREADS + } + if (ret < 0) { + PyErr_SetFromErrno(PyExc_IOError); + return NULL; + } + Py_INCREF(Py_None); + return Py_None; #endif /* defined(PYOS_OS2) && defined(PYCC_GCC) */ } @@ -414,11 +414,11 @@ /* List of functions */ static PyMethodDef fcntl_methods[] = { - {"fcntl", fcntl_fcntl, METH_VARARGS, fcntl_doc}, - {"ioctl", fcntl_ioctl, METH_VARARGS, ioctl_doc}, - {"flock", fcntl_flock, METH_VARARGS, flock_doc}, - {"lockf", fcntl_lockf, METH_VARARGS, lockf_doc}, - {NULL, NULL} /* sentinel */ + {"fcntl", fcntl_fcntl, METH_VARARGS, fcntl_doc}, + {"ioctl", fcntl_ioctl, METH_VARARGS, ioctl_doc}, + {"flock", fcntl_flock, METH_VARARGS, flock_doc}, + {"lockf", fcntl_lockf, METH_VARARGS, lockf_doc}, + {NULL, NULL} /* sentinel */ }; @@ -433,12 +433,12 @@ static int ins(PyObject* d, char* symbol, long value) { - PyObject* v = PyLong_FromLong(value); - if (!v || PyDict_SetItemString(d, symbol, v) < 0) - return -1; + PyObject* v = PyLong_FromLong(value); + if (!v || PyDict_SetItemString(d, symbol, v) < 0) + return -1; - Py_DECREF(v); - return 0; + Py_DECREF(v); + return 0; } #define INS(x) if (ins(d, #x, (long)x)) return -1 @@ -446,199 +446,199 @@ static int all_ins(PyObject* d) { - if (ins(d, "LOCK_SH", (long)LOCK_SH)) return -1; - if (ins(d, "LOCK_EX", (long)LOCK_EX)) return -1; - if (ins(d, "LOCK_NB", (long)LOCK_NB)) return -1; - if (ins(d, "LOCK_UN", (long)LOCK_UN)) return -1; + if (ins(d, "LOCK_SH", (long)LOCK_SH)) return -1; + if (ins(d, "LOCK_EX", (long)LOCK_EX)) return -1; + if (ins(d, "LOCK_NB", (long)LOCK_NB)) return -1; + if (ins(d, "LOCK_UN", (long)LOCK_UN)) return -1; /* GNU extensions, as of glibc 2.2.4 */ #ifdef LOCK_MAND - if (ins(d, "LOCK_MAND", (long)LOCK_MAND)) return -1; + if (ins(d, "LOCK_MAND", (long)LOCK_MAND)) return -1; #endif #ifdef LOCK_READ - if (ins(d, "LOCK_READ", (long)LOCK_READ)) return -1; + if (ins(d, "LOCK_READ", (long)LOCK_READ)) return -1; #endif #ifdef LOCK_WRITE - if (ins(d, "LOCK_WRITE", (long)LOCK_WRITE)) return -1; + if (ins(d, "LOCK_WRITE", (long)LOCK_WRITE)) return -1; #endif #ifdef LOCK_RW - if (ins(d, "LOCK_RW", (long)LOCK_RW)) return -1; + if (ins(d, "LOCK_RW", (long)LOCK_RW)) return -1; #endif #ifdef F_DUPFD - if (ins(d, "F_DUPFD", (long)F_DUPFD)) return -1; + if (ins(d, "F_DUPFD", (long)F_DUPFD)) return -1; #endif #ifdef F_GETFD - if (ins(d, "F_GETFD", (long)F_GETFD)) return -1; + if (ins(d, "F_GETFD", (long)F_GETFD)) return -1; #endif #ifdef F_SETFD - if (ins(d, "F_SETFD", (long)F_SETFD)) return -1; + if (ins(d, "F_SETFD", (long)F_SETFD)) return -1; #endif #ifdef F_GETFL - if (ins(d, "F_GETFL", (long)F_GETFL)) return -1; + if (ins(d, "F_GETFL", (long)F_GETFL)) return -1; #endif #ifdef F_SETFL - if (ins(d, "F_SETFL", (long)F_SETFL)) return -1; + if (ins(d, "F_SETFL", (long)F_SETFL)) return -1; #endif #ifdef F_GETLK - if (ins(d, "F_GETLK", (long)F_GETLK)) return -1; + if (ins(d, "F_GETLK", (long)F_GETLK)) return -1; #endif #ifdef F_SETLK - if (ins(d, "F_SETLK", (long)F_SETLK)) return -1; + if (ins(d, "F_SETLK", (long)F_SETLK)) return -1; #endif #ifdef F_SETLKW - if (ins(d, "F_SETLKW", (long)F_SETLKW)) return -1; + if (ins(d, "F_SETLKW", (long)F_SETLKW)) return -1; #endif #ifdef F_GETOWN - if (ins(d, "F_GETOWN", (long)F_GETOWN)) return -1; + if (ins(d, "F_GETOWN", (long)F_GETOWN)) return -1; #endif #ifdef F_SETOWN - if (ins(d, "F_SETOWN", (long)F_SETOWN)) return -1; + if (ins(d, "F_SETOWN", (long)F_SETOWN)) return -1; #endif #ifdef F_GETSIG - if (ins(d, "F_GETSIG", (long)F_GETSIG)) return -1; + if (ins(d, "F_GETSIG", (long)F_GETSIG)) return -1; #endif #ifdef F_SETSIG - if (ins(d, "F_SETSIG", (long)F_SETSIG)) return -1; + if (ins(d, "F_SETSIG", (long)F_SETSIG)) return -1; #endif #ifdef F_RDLCK - if (ins(d, "F_RDLCK", (long)F_RDLCK)) return -1; + if (ins(d, "F_RDLCK", (long)F_RDLCK)) return -1; #endif #ifdef F_WRLCK - if (ins(d, "F_WRLCK", (long)F_WRLCK)) return -1; + if (ins(d, "F_WRLCK", (long)F_WRLCK)) return -1; #endif #ifdef F_UNLCK - if (ins(d, "F_UNLCK", (long)F_UNLCK)) return -1; + if (ins(d, "F_UNLCK", (long)F_UNLCK)) return -1; #endif /* LFS constants */ #ifdef F_GETLK64 - if (ins(d, "F_GETLK64", (long)F_GETLK64)) return -1; + if (ins(d, "F_GETLK64", (long)F_GETLK64)) return -1; #endif #ifdef F_SETLK64 - if (ins(d, "F_SETLK64", (long)F_SETLK64)) return -1; + if (ins(d, "F_SETLK64", (long)F_SETLK64)) return -1; #endif #ifdef F_SETLKW64 - if (ins(d, "F_SETLKW64", (long)F_SETLKW64)) return -1; + if (ins(d, "F_SETLKW64", (long)F_SETLKW64)) return -1; #endif /* GNU extensions, as of glibc 2.2.4. */ #ifdef FASYNC - if (ins(d, "FASYNC", (long)FASYNC)) return -1; + if (ins(d, "FASYNC", (long)FASYNC)) return -1; #endif #ifdef F_SETLEASE - if (ins(d, "F_SETLEASE", (long)F_SETLEASE)) return -1; + if (ins(d, "F_SETLEASE", (long)F_SETLEASE)) return -1; #endif #ifdef F_GETLEASE - if (ins(d, "F_GETLEASE", (long)F_GETLEASE)) return -1; + if (ins(d, "F_GETLEASE", (long)F_GETLEASE)) return -1; #endif #ifdef F_NOTIFY - if (ins(d, "F_NOTIFY", (long)F_NOTIFY)) return -1; + if (ins(d, "F_NOTIFY", (long)F_NOTIFY)) return -1; #endif /* Old BSD flock(). */ #ifdef F_EXLCK - if (ins(d, "F_EXLCK", (long)F_EXLCK)) return -1; + if (ins(d, "F_EXLCK", (long)F_EXLCK)) return -1; #endif #ifdef F_SHLCK - if (ins(d, "F_SHLCK", (long)F_SHLCK)) return -1; + if (ins(d, "F_SHLCK", (long)F_SHLCK)) return -1; #endif /* OS X (and maybe others) let you tell the storage device to flush to physical media */ #ifdef F_FULLFSYNC - if (ins(d, "F_FULLFSYNC", (long)F_FULLFSYNC)) return -1; + if (ins(d, "F_FULLFSYNC", (long)F_FULLFSYNC)) return -1; #endif /* For F_{GET|SET}FL */ #ifdef FD_CLOEXEC - if (ins(d, "FD_CLOEXEC", (long)FD_CLOEXEC)) return -1; + if (ins(d, "FD_CLOEXEC", (long)FD_CLOEXEC)) return -1; #endif /* For F_NOTIFY */ #ifdef DN_ACCESS - if (ins(d, "DN_ACCESS", (long)DN_ACCESS)) return -1; + if (ins(d, "DN_ACCESS", (long)DN_ACCESS)) return -1; #endif #ifdef DN_MODIFY - if (ins(d, "DN_MODIFY", (long)DN_MODIFY)) return -1; + if (ins(d, "DN_MODIFY", (long)DN_MODIFY)) return -1; #endif #ifdef DN_CREATE - if (ins(d, "DN_CREATE", (long)DN_CREATE)) return -1; + if (ins(d, "DN_CREATE", (long)DN_CREATE)) return -1; #endif #ifdef DN_DELETE - if (ins(d, "DN_DELETE", (long)DN_DELETE)) return -1; + if (ins(d, "DN_DELETE", (long)DN_DELETE)) return -1; #endif #ifdef DN_RENAME - if (ins(d, "DN_RENAME", (long)DN_RENAME)) return -1; + if (ins(d, "DN_RENAME", (long)DN_RENAME)) return -1; #endif #ifdef DN_ATTRIB - if (ins(d, "DN_ATTRIB", (long)DN_ATTRIB)) return -1; + if (ins(d, "DN_ATTRIB", (long)DN_ATTRIB)) return -1; #endif #ifdef DN_MULTISHOT - if (ins(d, "DN_MULTISHOT", (long)DN_MULTISHOT)) return -1; + if (ins(d, "DN_MULTISHOT", (long)DN_MULTISHOT)) return -1; #endif #ifdef HAVE_STROPTS_H - /* Unix 98 guarantees that these are in stropts.h. */ - INS(I_PUSH); - INS(I_POP); - INS(I_LOOK); - INS(I_FLUSH); - INS(I_FLUSHBAND); - INS(I_SETSIG); - INS(I_GETSIG); - INS(I_FIND); - INS(I_PEEK); - INS(I_SRDOPT); - INS(I_GRDOPT); - INS(I_NREAD); - INS(I_FDINSERT); - INS(I_STR); - INS(I_SWROPT); + /* Unix 98 guarantees that these are in stropts.h. */ + INS(I_PUSH); + INS(I_POP); + INS(I_LOOK); + INS(I_FLUSH); + INS(I_FLUSHBAND); + INS(I_SETSIG); + INS(I_GETSIG); + INS(I_FIND); + INS(I_PEEK); + INS(I_SRDOPT); + INS(I_GRDOPT); + INS(I_NREAD); + INS(I_FDINSERT); + INS(I_STR); + INS(I_SWROPT); #ifdef I_GWROPT - /* despite the comment above, old-ish glibcs miss a couple... */ - INS(I_GWROPT); + /* despite the comment above, old-ish glibcs miss a couple... */ + INS(I_GWROPT); #endif - INS(I_SENDFD); - INS(I_RECVFD); - INS(I_LIST); - INS(I_ATMARK); - INS(I_CKBAND); - INS(I_GETBAND); - INS(I_CANPUT); - INS(I_SETCLTIME); + INS(I_SENDFD); + INS(I_RECVFD); + INS(I_LIST); + INS(I_ATMARK); + INS(I_CKBAND); + INS(I_GETBAND); + INS(I_CANPUT); + INS(I_SETCLTIME); #ifdef I_GETCLTIME - INS(I_GETCLTIME); + INS(I_GETCLTIME); #endif - INS(I_LINK); - INS(I_UNLINK); - INS(I_PLINK); - INS(I_PUNLINK); + INS(I_LINK); + INS(I_UNLINK); + INS(I_PLINK); + INS(I_PUNLINK); #endif - - return 0; + + return 0; } static struct PyModuleDef fcntlmodule = { - PyModuleDef_HEAD_INIT, - "fcntl", - module_doc, - -1, - fcntl_methods, - NULL, - NULL, - NULL, - NULL + PyModuleDef_HEAD_INIT, + "fcntl", + module_doc, + -1, + fcntl_methods, + NULL, + NULL, + NULL, + NULL }; PyMODINIT_FUNC PyInit_fcntl(void) { - PyObject *m, *d; + PyObject *m, *d; - /* Create the module and add the functions and documentation */ - m = PyModule_Create(&fcntlmodule); - if (m == NULL) - return NULL; - - /* Add some symbolic constants to the module */ - d = PyModule_GetDict(m); - all_ins(d); - return m; + /* Create the module and add the functions and documentation */ + m = PyModule_Create(&fcntlmodule); + if (m == NULL) + return NULL; + + /* Add some symbolic constants to the module */ + d = PyModule_GetDict(m); + all_ins(d); + return m; } Modified: python/branches/py3k/Modules/fpectlmodule.c ============================================================================== --- python/branches/py3k/Modules/fpectlmodule.c (original) +++ python/branches/py3k/Modules/fpectlmodule.c Sun May 9 17:52:27 2010 @@ -1,6 +1,6 @@ /* - --------------------------------------------------------------------- - / Copyright (c) 1996. \ + --------------------------------------------------------------------- + / Copyright (c) 1996. \ | The Regents of the University of California. | | All rights reserved. | | | @@ -32,12 +32,12 @@ | 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. / - --------------------------------------------------------------------- + \ endorsement purposes. / + --------------------------------------------------------------------- */ /* - Floating point exception control module. + Floating point exception control module. This Python module provides bare-bones control over floating point units from several hardware manufacturers. Specifically, it allows @@ -96,8 +96,8 @@ static PyObject *turnoff_sigfpe (PyObject *self,PyObject *args); static PyMethodDef fpectl_methods[] = { - {"turnon_sigfpe", (PyCFunction) turnon_sigfpe, METH_VARARGS}, - {"turnoff_sigfpe", (PyCFunction) turnoff_sigfpe, METH_VARARGS}, + {"turnon_sigfpe", (PyCFunction) turnon_sigfpe, METH_VARARGS}, + {"turnoff_sigfpe", (PyCFunction) turnoff_sigfpe, METH_VARARGS}, {0,0} }; @@ -122,19 +122,19 @@ * My usage doesn't follow the man page exactly. Maybe somebody * else can explain handle_sigfpes to me.... * cc -c -I/usr/local/python/include fpectlmodule.c - * ld -shared -o fpectlmodule.so fpectlmodule.o -lfpe + * ld -shared -o fpectlmodule.so fpectlmodule.o -lfpe */ #include typedef void user_routine (unsigned[5], int[2]); typedef void abort_routine (unsigned long); handle_sigfpes(_OFF, 0, - (user_routine *)0, - _TURN_OFF_HANDLER_ON_ERROR, - NULL); + (user_routine *)0, + _TURN_OFF_HANDLER_ON_ERROR, + NULL); handle_sigfpes(_ON, _EN_OVERFL | _EN_DIVZERO | _EN_INVALID, - (user_routine *)0, - _ABORT_ON_ERROR, - NULL); + (user_routine *)0, + _ABORT_ON_ERROR, + NULL); PyOS_setsig(SIGFPE, handler); /*-- SunOS and Solaris ----------------------------------------------------*/ @@ -195,16 +195,16 @@ /*-- DEC ALPHA VMS --------------------------------------------------------*/ #elif defined(__ALPHA) && defined(__VMS) - IEEE clrmsk; - IEEE setmsk; - clrmsk.ieee$q_flags = - IEEE$M_TRAP_ENABLE_UNF | IEEE$M_TRAP_ENABLE_INE | - IEEE$M_MAP_UMZ; - setmsk.ieee$q_flags = - IEEE$M_TRAP_ENABLE_INV | IEEE$M_TRAP_ENABLE_DZE | - IEEE$M_TRAP_ENABLE_OVF; - sys$ieee_set_fp_control(&clrmsk, &setmsk, 0); - PyOS_setsig(SIGFPE, handler); + IEEE clrmsk; + IEEE setmsk; + clrmsk.ieee$q_flags = + IEEE$M_TRAP_ENABLE_UNF | IEEE$M_TRAP_ENABLE_INE | + IEEE$M_MAP_UMZ; + setmsk.ieee$q_flags = + IEEE$M_TRAP_ENABLE_INV | IEEE$M_TRAP_ENABLE_DZE | + IEEE$M_TRAP_ENABLE_OVF; + sys$ieee_set_fp_control(&clrmsk, &setmsk, 0); + PyOS_setsig(SIGFPE, handler); /*-- HP IA64 VMS --------------------------------------------------------*/ #elif defined(__ia64) && defined(__VMS) @@ -263,13 +263,13 @@ fpresetsticky(fpgetsticky()); fpsetmask(0); #elif defined(__VMS) - IEEE clrmsk; - clrmsk.ieee$q_flags = - IEEE$M_TRAP_ENABLE_UNF | IEEE$M_TRAP_ENABLE_INE | - IEEE$M_MAP_UMZ | IEEE$M_TRAP_ENABLE_INV | - IEEE$M_TRAP_ENABLE_DZE | IEEE$M_TRAP_ENABLE_OVF | - IEEE$M_INHERIT; - sys$ieee_set_fp_control(&clrmsk, 0, 0); + IEEE clrmsk; + clrmsk.ieee$q_flags = + IEEE$M_TRAP_ENABLE_UNF | IEEE$M_TRAP_ENABLE_INE | + IEEE$M_MAP_UMZ | IEEE$M_TRAP_ENABLE_INV | + IEEE$M_TRAP_ENABLE_DZE | IEEE$M_TRAP_ENABLE_OVF | + IEEE$M_INHERIT; + sys$ieee_set_fp_control(&clrmsk, 0, 0); #else fputs("Operation not implemented\n", stderr); #endif @@ -288,15 +288,15 @@ } static struct PyModuleDef fpectlmodule = { - PyModuleDef_HEAD_INIT, - "fpectl", - NULL, - -1, - fpectl_methods, - NULL, - NULL, - NULL, - NULL + PyModuleDef_HEAD_INIT, + "fpectl", + NULL, + -1, + fpectl_methods, + NULL, + NULL, + NULL, + NULL }; PyMODINIT_FUNC PyInit_fpectl(void) @@ -304,11 +304,11 @@ PyObject *m, *d; m = PyModule_Create(&fpectlmodule); if (m == NULL) - return NULL; + return NULL; d = PyModule_GetDict(m); fpe_error = PyErr_NewException("fpectl.error", NULL, NULL); if (fpe_error != NULL) - PyDict_SetItemString(d, "error", fpe_error); + PyDict_SetItemString(d, "error", fpe_error); return m; } Modified: python/branches/py3k/Modules/fpetestmodule.c ============================================================================== --- python/branches/py3k/Modules/fpetestmodule.c (original) +++ python/branches/py3k/Modules/fpetestmodule.c Sun May 9 17:52:27 2010 @@ -1,6 +1,6 @@ /* - --------------------------------------------------------------------- - / Copyright (c) 1996. \ + --------------------------------------------------------------------- + / Copyright (c) 1996. \ | The Regents of the University of California. | | All rights reserved. | | | @@ -32,12 +32,12 @@ | 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. / - --------------------------------------------------------------------- + \ endorsement purposes. / + --------------------------------------------------------------------- */ /* - Floating point exception test module. + Floating point exception test module. */ @@ -55,7 +55,7 @@ static void printerr(double); static PyMethodDef fpetest_methods[] = { - {"test", (PyCFunction) test, METH_VARARGS}, + {"test", (PyCFunction) test, METH_VARARGS}, {0,0} }; @@ -174,15 +174,15 @@ } static struct PyModuleDef fpetestmodule = { - PyModuleDef_HEAD_INIT, - "fpetest", - NULL, - -1, - fpetest_methods, - NULL, - NULL, - NULL, - NULL + PyModuleDef_HEAD_INIT, + "fpetest", + NULL, + -1, + fpetest_methods, + NULL, + NULL, + NULL, + NULL }; PyMODINIT_FUNC PyInit_fpetest(void) @@ -191,10 +191,10 @@ m = PyModule_Create(&fpetestmodule); if (m == NULL) - return NULL; + return NULL; d = PyModule_GetDict(m); fpe_error = PyErr_NewException("fpetest.error", NULL, NULL); if (fpe_error != NULL) - PyDict_SetItemString(d, "error", fpe_error); + PyDict_SetItemString(d, "error", fpe_error); return m; } Modified: python/branches/py3k/Modules/gcmodule.c ============================================================================== --- python/branches/py3k/Modules/gcmodule.c (original) +++ python/branches/py3k/Modules/gcmodule.c Sun May 9 17:52:27 2010 @@ -24,7 +24,7 @@ */ #include "Python.h" -#include "frameobject.h" /* for PyFrame_ClearFreeList */ +#include "frameobject.h" /* for PyFrame_ClearFreeList */ /* Get an object's GC head */ #define AS_GC(o) ((PyGC_Head *)(o)-1) @@ -35,10 +35,10 @@ /*** Global GC state ***/ struct gc_generation { - PyGC_Head head; - int threshold; /* collection threshold */ - int count; /* count of allocations or collections of younger - generations */ + PyGC_Head head; + int threshold; /* collection threshold */ + int count; /* count of allocations or collections of younger + generations */ }; #define NUM_GENERATIONS 3 @@ -46,10 +46,10 @@ /* linked lists of container objects */ static struct gc_generation generations[NUM_GENERATIONS] = { - /* PyGC_Head, threshold, count */ - {{{GEN_HEAD(0), GEN_HEAD(0), 0}}, 700, 0}, - {{{GEN_HEAD(1), GEN_HEAD(1), 0}}, 10, 0}, - {{{GEN_HEAD(2), GEN_HEAD(2), 0}}, 10, 0}, + /* PyGC_Head, threshold, count */ + {{{GEN_HEAD(0), GEN_HEAD(0), 0}}, 700, 0}, + {{{GEN_HEAD(1), GEN_HEAD(1), 0}}, 10, 0}, + {{{GEN_HEAD(2), GEN_HEAD(2), 0}}, 10, 0}, }; PyGC_Head *_PyGC_generation0 = GEN_HEAD(0); @@ -91,7 +91,7 @@ In addition to the various configurable thresholds, we only trigger a full collection if the ratio - long_lived_pending / long_lived_total + long_lived_pending / long_lived_total is above a given value (hardwired to 25%). The reason is that, while "non-full" collections (i.e., collections of @@ -113,18 +113,18 @@ This heuristic was suggested by Martin von L?wis on python-dev in June 2008. His original analysis and proposal can be found at: - http://mail.python.org/pipermail/python-dev/2008-June/080579.html + http://mail.python.org/pipermail/python-dev/2008-June/080579.html */ /* set for debugging information */ -#define DEBUG_STATS (1<<0) /* print collection statistics */ -#define DEBUG_COLLECTABLE (1<<1) /* print collectable objects */ -#define DEBUG_UNCOLLECTABLE (1<<2) /* print uncollectable objects */ -#define DEBUG_SAVEALL (1<<5) /* save all garbage in gc.garbage */ -#define DEBUG_LEAK DEBUG_COLLECTABLE | \ - DEBUG_UNCOLLECTABLE | \ - DEBUG_SAVEALL +#define DEBUG_STATS (1<<0) /* print collection statistics */ +#define DEBUG_COLLECTABLE (1<<1) /* print collectable objects */ +#define DEBUG_UNCOLLECTABLE (1<<2) /* print uncollectable objects */ +#define DEBUG_SAVEALL (1<<5) /* save all garbage in gc.garbage */ +#define DEBUG_LEAK DEBUG_COLLECTABLE | \ + DEBUG_UNCOLLECTABLE | \ + DEBUG_SAVEALL static int debug; static PyObject *tmod = NULL; @@ -167,28 +167,28 @@ it has a __del__ method), its gc_refs is restored to GC_REACHABLE again. ---------------------------------------------------------------------------- */ -#define GC_UNTRACKED _PyGC_REFS_UNTRACKED -#define GC_REACHABLE _PyGC_REFS_REACHABLE -#define GC_TENTATIVELY_UNREACHABLE _PyGC_REFS_TENTATIVELY_UNREACHABLE +#define GC_UNTRACKED _PyGC_REFS_UNTRACKED +#define GC_REACHABLE _PyGC_REFS_REACHABLE +#define GC_TENTATIVELY_UNREACHABLE _PyGC_REFS_TENTATIVELY_UNREACHABLE #define IS_TRACKED(o) ((AS_GC(o))->gc.gc_refs != GC_UNTRACKED) #define IS_REACHABLE(o) ((AS_GC(o))->gc.gc_refs == GC_REACHABLE) #define IS_TENTATIVELY_UNREACHABLE(o) ( \ - (AS_GC(o))->gc.gc_refs == GC_TENTATIVELY_UNREACHABLE) + (AS_GC(o))->gc.gc_refs == GC_TENTATIVELY_UNREACHABLE) /*** list functions ***/ static void gc_list_init(PyGC_Head *list) { - list->gc.gc_prev = list; - list->gc.gc_next = list; + list->gc.gc_prev = list; + list->gc.gc_next = list; } static int gc_list_is_empty(PyGC_Head *list) { - return (list->gc.gc_next == list); + return (list->gc.gc_next == list); } #if 0 @@ -197,10 +197,10 @@ static void gc_list_append(PyGC_Head *node, PyGC_Head *list) { - node->gc.gc_next = list; - node->gc.gc_prev = list->gc.gc_prev; - node->gc.gc_prev->gc.gc_next = node; - list->gc.gc_prev = node; + node->gc.gc_next = list; + node->gc.gc_prev = list->gc.gc_prev; + node->gc.gc_prev->gc.gc_next = node; + list->gc.gc_prev = node; } #endif @@ -208,9 +208,9 @@ static void gc_list_remove(PyGC_Head *node) { - node->gc.gc_prev->gc.gc_next = node->gc.gc_next; - node->gc.gc_next->gc.gc_prev = node->gc.gc_prev; - node->gc.gc_next = NULL; /* object is not currently tracked */ + node->gc.gc_prev->gc.gc_next = node->gc.gc_next; + node->gc.gc_next->gc.gc_prev = node->gc.gc_prev; + node->gc.gc_next = NULL; /* object is not currently tracked */ } /* Move `node` from the gc list it's currently in (which is not explicitly @@ -220,43 +220,43 @@ static void gc_list_move(PyGC_Head *node, PyGC_Head *list) { - PyGC_Head *new_prev; - PyGC_Head *current_prev = node->gc.gc_prev; - PyGC_Head *current_next = node->gc.gc_next; - /* Unlink from current list. */ - current_prev->gc.gc_next = current_next; - current_next->gc.gc_prev = current_prev; - /* Relink at end of new list. */ - new_prev = node->gc.gc_prev = list->gc.gc_prev; - new_prev->gc.gc_next = list->gc.gc_prev = node; - node->gc.gc_next = list; + PyGC_Head *new_prev; + PyGC_Head *current_prev = node->gc.gc_prev; + PyGC_Head *current_next = node->gc.gc_next; + /* Unlink from current list. */ + current_prev->gc.gc_next = current_next; + current_next->gc.gc_prev = current_prev; + /* Relink at end of new list. */ + new_prev = node->gc.gc_prev = list->gc.gc_prev; + new_prev->gc.gc_next = list->gc.gc_prev = node; + node->gc.gc_next = list; } /* append list `from` onto list `to`; `from` becomes an empty list */ static void gc_list_merge(PyGC_Head *from, PyGC_Head *to) { - PyGC_Head *tail; - assert(from != to); - if (!gc_list_is_empty(from)) { - tail = to->gc.gc_prev; - tail->gc.gc_next = from->gc.gc_next; - tail->gc.gc_next->gc.gc_prev = tail; - to->gc.gc_prev = from->gc.gc_prev; - to->gc.gc_prev->gc.gc_next = to; - } - gc_list_init(from); + PyGC_Head *tail; + assert(from != to); + if (!gc_list_is_empty(from)) { + tail = to->gc.gc_prev; + tail->gc.gc_next = from->gc.gc_next; + tail->gc.gc_next->gc.gc_prev = tail; + to->gc.gc_prev = from->gc.gc_prev; + to->gc.gc_prev->gc.gc_next = to; + } + gc_list_init(from); } static Py_ssize_t gc_list_size(PyGC_Head *list) { - PyGC_Head *gc; - Py_ssize_t n = 0; - for (gc = list->gc.gc_next; gc != list; gc = gc->gc.gc_next) { - n++; - } - return n; + PyGC_Head *gc; + Py_ssize_t n = 0; + for (gc = list->gc.gc_next; gc != list; gc = gc->gc.gc_next) { + n++; + } + return n; } /* Append objects in a GC list to a Python list. @@ -265,16 +265,16 @@ static int append_objects(PyObject *py_list, PyGC_Head *gc_list) { - PyGC_Head *gc; - for (gc = gc_list->gc.gc_next; gc != gc_list; gc = gc->gc.gc_next) { - PyObject *op = FROM_GC(gc); - if (op != py_list) { - if (PyList_Append(py_list, op)) { - return -1; /* exception */ - } - } - } - return 0; + PyGC_Head *gc; + for (gc = gc_list->gc.gc_next; gc != gc_list; gc = gc->gc.gc_next) { + PyObject *op = FROM_GC(gc); + if (op != py_list) { + if (PyList_Append(py_list, op)) { + return -1; /* exception */ + } + } + } + return 0; } /*** end of list stuff ***/ @@ -287,48 +287,48 @@ static void update_refs(PyGC_Head *containers) { - PyGC_Head *gc = containers->gc.gc_next; - for (; gc != containers; gc = gc->gc.gc_next) { - assert(gc->gc.gc_refs == GC_REACHABLE); - gc->gc.gc_refs = Py_REFCNT(FROM_GC(gc)); - /* Python's cyclic gc should never see an incoming refcount - * of 0: if something decref'ed to 0, it should have been - * deallocated immediately at that time. - * Possible cause (if the assert triggers): a tp_dealloc - * routine left a gc-aware object tracked during its teardown - * phase, and did something-- or allowed something to happen -- - * that called back into Python. gc can trigger then, and may - * see the still-tracked dying object. Before this assert - * was added, such mistakes went on to allow gc to try to - * delete the object again. In a debug build, that caused - * a mysterious segfault, when _Py_ForgetReference tried - * to remove the object from the doubly-linked list of all - * objects a second time. In a release build, an actual - * double deallocation occurred, which leads to corruption - * of the allocator's internal bookkeeping pointers. That's - * so serious that maybe this should be a release-build - * check instead of an assert? - */ - assert(gc->gc.gc_refs != 0); - } + PyGC_Head *gc = containers->gc.gc_next; + for (; gc != containers; gc = gc->gc.gc_next) { + assert(gc->gc.gc_refs == GC_REACHABLE); + gc->gc.gc_refs = Py_REFCNT(FROM_GC(gc)); + /* Python's cyclic gc should never see an incoming refcount + * of 0: if something decref'ed to 0, it should have been + * deallocated immediately at that time. + * Possible cause (if the assert triggers): a tp_dealloc + * routine left a gc-aware object tracked during its teardown + * phase, and did something-- or allowed something to happen -- + * that called back into Python. gc can trigger then, and may + * see the still-tracked dying object. Before this assert + * was added, such mistakes went on to allow gc to try to + * delete the object again. In a debug build, that caused + * a mysterious segfault, when _Py_ForgetReference tried + * to remove the object from the doubly-linked list of all + * objects a second time. In a release build, an actual + * double deallocation occurred, which leads to corruption + * of the allocator's internal bookkeeping pointers. That's + * so serious that maybe this should be a release-build + * check instead of an assert? + */ + assert(gc->gc.gc_refs != 0); + } } /* A traversal callback for subtract_refs. */ static int visit_decref(PyObject *op, void *data) { - assert(op != NULL); - if (PyObject_IS_GC(op)) { - PyGC_Head *gc = AS_GC(op); - /* We're only interested in gc_refs for objects in the - * generation being collected, which can be recognized - * because only they have positive gc_refs. - */ - assert(gc->gc.gc_refs != 0); /* else refcount was too small */ - if (gc->gc.gc_refs > 0) - gc->gc.gc_refs--; - } - return 0; + assert(op != NULL); + if (PyObject_IS_GC(op)) { + PyGC_Head *gc = AS_GC(op); + /* We're only interested in gc_refs for objects in the + * generation being collected, which can be recognized + * because only they have positive gc_refs. + */ + assert(gc->gc.gc_refs != 0); /* else refcount was too small */ + if (gc->gc.gc_refs > 0) + gc->gc.gc_refs--; + } + return 0; } /* Subtract internal references from gc_refs. After this, gc_refs is >= 0 @@ -339,57 +339,57 @@ static void subtract_refs(PyGC_Head *containers) { - traverseproc traverse; - PyGC_Head *gc = containers->gc.gc_next; - for (; gc != containers; gc=gc->gc.gc_next) { - traverse = Py_TYPE(FROM_GC(gc))->tp_traverse; - (void) traverse(FROM_GC(gc), - (visitproc)visit_decref, - NULL); - } + traverseproc traverse; + PyGC_Head *gc = containers->gc.gc_next; + for (; gc != containers; gc=gc->gc.gc_next) { + traverse = Py_TYPE(FROM_GC(gc))->tp_traverse; + (void) traverse(FROM_GC(gc), + (visitproc)visit_decref, + NULL); + } } /* A traversal callback for move_unreachable. */ static int visit_reachable(PyObject *op, PyGC_Head *reachable) { - if (PyObject_IS_GC(op)) { - PyGC_Head *gc = AS_GC(op); - const Py_ssize_t gc_refs = gc->gc.gc_refs; - - if (gc_refs == 0) { - /* This is in move_unreachable's 'young' list, but - * the traversal hasn't yet gotten to it. All - * we need to do is tell move_unreachable that it's - * reachable. - */ - gc->gc.gc_refs = 1; - } - else if (gc_refs == GC_TENTATIVELY_UNREACHABLE) { - /* This had gc_refs = 0 when move_unreachable got - * to it, but turns out it's reachable after all. - * Move it back to move_unreachable's 'young' list, - * and move_unreachable will eventually get to it - * again. - */ - gc_list_move(gc, reachable); - gc->gc.gc_refs = 1; - } - /* Else there's nothing to do. - * If gc_refs > 0, it must be in move_unreachable's 'young' - * list, and move_unreachable will eventually get to it. - * If gc_refs == GC_REACHABLE, it's either in some other - * generation so we don't care about it, or move_unreachable - * already dealt with it. - * If gc_refs == GC_UNTRACKED, it must be ignored. - */ - else { - assert(gc_refs > 0 - || gc_refs == GC_REACHABLE - || gc_refs == GC_UNTRACKED); - } - } - return 0; + if (PyObject_IS_GC(op)) { + PyGC_Head *gc = AS_GC(op); + const Py_ssize_t gc_refs = gc->gc.gc_refs; + + if (gc_refs == 0) { + /* This is in move_unreachable's 'young' list, but + * the traversal hasn't yet gotten to it. All + * we need to do is tell move_unreachable that it's + * reachable. + */ + gc->gc.gc_refs = 1; + } + else if (gc_refs == GC_TENTATIVELY_UNREACHABLE) { + /* This had gc_refs = 0 when move_unreachable got + * to it, but turns out it's reachable after all. + * Move it back to move_unreachable's 'young' list, + * and move_unreachable will eventually get to it + * again. + */ + gc_list_move(gc, reachable); + gc->gc.gc_refs = 1; + } + /* Else there's nothing to do. + * If gc_refs > 0, it must be in move_unreachable's 'young' + * list, and move_unreachable will eventually get to it. + * If gc_refs == GC_REACHABLE, it's either in some other + * generation so we don't care about it, or move_unreachable + * already dealt with it. + * If gc_refs == GC_UNTRACKED, it must be ignored. + */ + else { + assert(gc_refs > 0 + || gc_refs == GC_REACHABLE + || gc_refs == GC_UNTRACKED); + } + } + return 0; } /* Move the unreachable objects from young to unreachable. After this, @@ -403,68 +403,68 @@ static void move_unreachable(PyGC_Head *young, PyGC_Head *unreachable) { - PyGC_Head *gc = young->gc.gc_next; + PyGC_Head *gc = young->gc.gc_next; - /* Invariants: all objects "to the left" of us in young have gc_refs - * = GC_REACHABLE, and are indeed reachable (directly or indirectly) - * from outside the young list as it was at entry. All other objects - * from the original young "to the left" of us are in unreachable now, - * and have gc_refs = GC_TENTATIVELY_UNREACHABLE. All objects to the - * left of us in 'young' now have been scanned, and no objects here - * or to the right have been scanned yet. - */ - - while (gc != young) { - PyGC_Head *next; - - if (gc->gc.gc_refs) { - /* gc is definitely reachable from outside the - * original 'young'. Mark it as such, and traverse - * its pointers to find any other objects that may - * be directly reachable from it. Note that the - * call to tp_traverse may append objects to young, - * so we have to wait until it returns to determine - * the next object to visit. - */ - PyObject *op = FROM_GC(gc); - traverseproc traverse = Py_TYPE(op)->tp_traverse; - assert(gc->gc.gc_refs > 0); - gc->gc.gc_refs = GC_REACHABLE; - (void) traverse(op, - (visitproc)visit_reachable, - (void *)young); - next = gc->gc.gc_next; - if (PyTuple_CheckExact(op)) { - _PyTuple_MaybeUntrack(op); - } - else if (PyDict_CheckExact(op)) { - _PyDict_MaybeUntrack(op); - } - } - else { - /* This *may* be unreachable. To make progress, - * assume it is. gc isn't directly reachable from - * any object we've already traversed, but may be - * reachable from an object we haven't gotten to yet. - * visit_reachable will eventually move gc back into - * young if that's so, and we'll see it again. - */ - next = gc->gc.gc_next; - gc_list_move(gc, unreachable); - gc->gc.gc_refs = GC_TENTATIVELY_UNREACHABLE; - } - gc = next; - } + /* Invariants: all objects "to the left" of us in young have gc_refs + * = GC_REACHABLE, and are indeed reachable (directly or indirectly) + * from outside the young list as it was at entry. All other objects + * from the original young "to the left" of us are in unreachable now, + * and have gc_refs = GC_TENTATIVELY_UNREACHABLE. All objects to the + * left of us in 'young' now have been scanned, and no objects here + * or to the right have been scanned yet. + */ + + while (gc != young) { + PyGC_Head *next; + + if (gc->gc.gc_refs) { + /* gc is definitely reachable from outside the + * original 'young'. Mark it as such, and traverse + * its pointers to find any other objects that may + * be directly reachable from it. Note that the + * call to tp_traverse may append objects to young, + * so we have to wait until it returns to determine + * the next object to visit. + */ + PyObject *op = FROM_GC(gc); + traverseproc traverse = Py_TYPE(op)->tp_traverse; + assert(gc->gc.gc_refs > 0); + gc->gc.gc_refs = GC_REACHABLE; + (void) traverse(op, + (visitproc)visit_reachable, + (void *)young); + next = gc->gc.gc_next; + if (PyTuple_CheckExact(op)) { + _PyTuple_MaybeUntrack(op); + } + else if (PyDict_CheckExact(op)) { + _PyDict_MaybeUntrack(op); + } + } + else { + /* This *may* be unreachable. To make progress, + * assume it is. gc isn't directly reachable from + * any object we've already traversed, but may be + * reachable from an object we haven't gotten to yet. + * visit_reachable will eventually move gc back into + * young if that's so, and we'll see it again. + */ + next = gc->gc.gc_next; + gc_list_move(gc, unreachable); + gc->gc.gc_refs = GC_TENTATIVELY_UNREACHABLE; + } + gc = next; + } } /* Return true if object has a finalization method. */ static int has_finalizer(PyObject *op) { - if (PyGen_CheckExact(op)) - return PyGen_NeedsFinalizing((PyGenObject *)op); - else - return op->ob_type->tp_del != NULL; + if (PyGen_CheckExact(op)) + return PyGen_NeedsFinalizing((PyGenObject *)op); + else + return op->ob_type->tp_del != NULL; } /* Move the objects in unreachable with __del__ methods into `finalizers`. @@ -474,37 +474,37 @@ static void move_finalizers(PyGC_Head *unreachable, PyGC_Head *finalizers) { - PyGC_Head *gc; - PyGC_Head *next; + PyGC_Head *gc; + PyGC_Head *next; - /* March over unreachable. Move objects with finalizers into - * `finalizers`. - */ - for (gc = unreachable->gc.gc_next; gc != unreachable; gc = next) { - PyObject *op = FROM_GC(gc); - - assert(IS_TENTATIVELY_UNREACHABLE(op)); - next = gc->gc.gc_next; - - if (has_finalizer(op)) { - gc_list_move(gc, finalizers); - gc->gc.gc_refs = GC_REACHABLE; - } - } + /* March over unreachable. Move objects with finalizers into + * `finalizers`. + */ + for (gc = unreachable->gc.gc_next; gc != unreachable; gc = next) { + PyObject *op = FROM_GC(gc); + + assert(IS_TENTATIVELY_UNREACHABLE(op)); + next = gc->gc.gc_next; + + if (has_finalizer(op)) { + gc_list_move(gc, finalizers); + gc->gc.gc_refs = GC_REACHABLE; + } + } } /* A traversal callback for move_finalizer_reachable. */ static int visit_move(PyObject *op, PyGC_Head *tolist) { - if (PyObject_IS_GC(op)) { - if (IS_TENTATIVELY_UNREACHABLE(op)) { - PyGC_Head *gc = AS_GC(op); - gc_list_move(gc, tolist); - gc->gc.gc_refs = GC_REACHABLE; - } - } - return 0; + if (PyObject_IS_GC(op)) { + if (IS_TENTATIVELY_UNREACHABLE(op)) { + PyGC_Head *gc = AS_GC(op); + gc_list_move(gc, tolist); + gc->gc.gc_refs = GC_REACHABLE; + } + } + return 0; } /* Move objects that are reachable from finalizers, from the unreachable set @@ -513,15 +513,15 @@ static void move_finalizer_reachable(PyGC_Head *finalizers) { - traverseproc traverse; - PyGC_Head *gc = finalizers->gc.gc_next; - for (; gc != finalizers; gc = gc->gc.gc_next) { - /* Note that the finalizers list may grow during this. */ - traverse = Py_TYPE(FROM_GC(gc))->tp_traverse; - (void) traverse(FROM_GC(gc), - (visitproc)visit_move, - (void *)finalizers); - } + traverseproc traverse; + PyGC_Head *gc = finalizers->gc.gc_next; + for (; gc != finalizers; gc = gc->gc.gc_next) { + /* Note that the finalizers list may grow during this. */ + traverse = Py_TYPE(FROM_GC(gc))->tp_traverse; + (void) traverse(FROM_GC(gc), + (visitproc)visit_move, + (void *)finalizers); + } } /* Clear all weakrefs to unreachable objects, and if such a weakref has a @@ -538,150 +538,150 @@ static int handle_weakrefs(PyGC_Head *unreachable, PyGC_Head *old) { - PyGC_Head *gc; - PyObject *op; /* generally FROM_GC(gc) */ - PyWeakReference *wr; /* generally a cast of op */ - PyGC_Head wrcb_to_call; /* weakrefs with callbacks to call */ - PyGC_Head *next; - int num_freed = 0; - - gc_list_init(&wrcb_to_call); - - /* Clear all weakrefs to the objects in unreachable. If such a weakref - * also has a callback, move it into `wrcb_to_call` if the callback - * needs to be invoked. Note that we cannot invoke any callbacks until - * all weakrefs to unreachable objects are cleared, lest the callback - * resurrect an unreachable object via a still-active weakref. We - * make another pass over wrcb_to_call, invoking callbacks, after this - * pass completes. - */ - for (gc = unreachable->gc.gc_next; gc != unreachable; gc = next) { - PyWeakReference **wrlist; - - op = FROM_GC(gc); - assert(IS_TENTATIVELY_UNREACHABLE(op)); - next = gc->gc.gc_next; - - if (! PyType_SUPPORTS_WEAKREFS(Py_TYPE(op))) - continue; - - /* It supports weakrefs. Does it have any? */ - wrlist = (PyWeakReference **) - PyObject_GET_WEAKREFS_LISTPTR(op); - - /* `op` may have some weakrefs. March over the list, clear - * all the weakrefs, and move the weakrefs with callbacks - * that must be called into wrcb_to_call. - */ - for (wr = *wrlist; wr != NULL; wr = *wrlist) { - PyGC_Head *wrasgc; /* AS_GC(wr) */ - - /* _PyWeakref_ClearRef clears the weakref but leaves - * the callback pointer intact. Obscure: it also - * changes *wrlist. - */ - assert(wr->wr_object == op); - _PyWeakref_ClearRef(wr); - assert(wr->wr_object == Py_None); - if (wr->wr_callback == NULL) - continue; /* no callback */ - - /* Headache time. `op` is going away, and is weakly referenced by - * `wr`, which has a callback. Should the callback be invoked? If wr - * is also trash, no: - * - * 1. There's no need to call it. The object and the weakref are - * both going away, so it's legitimate to pretend the weakref is - * going away first. The user has to ensure a weakref outlives its - * referent if they want a guarantee that the wr callback will get - * invoked. - * - * 2. It may be catastrophic to call it. If the callback is also in - * cyclic trash (CT), then although the CT is unreachable from - * outside the current generation, CT may be reachable from the - * callback. Then the callback could resurrect insane objects. - * - * Since the callback is never needed and may be unsafe in this case, - * wr is simply left in the unreachable set. Note that because we - * already called _PyWeakref_ClearRef(wr), its callback will never - * trigger. - * - * OTOH, if wr isn't part of CT, we should invoke the callback: the - * weakref outlived the trash. Note that since wr isn't CT in this - * case, its callback can't be CT either -- wr acted as an external - * root to this generation, and therefore its callback did too. So - * nothing in CT is reachable from the callback either, so it's hard - * to imagine how calling it later could create a problem for us. wr - * is moved to wrcb_to_call in this case. - */ - if (IS_TENTATIVELY_UNREACHABLE(wr)) - continue; - assert(IS_REACHABLE(wr)); - - /* Create a new reference so that wr can't go away - * before we can process it again. - */ - Py_INCREF(wr); - - /* Move wr to wrcb_to_call, for the next pass. */ - wrasgc = AS_GC(wr); - assert(wrasgc != next); /* wrasgc is reachable, but - next isn't, so they can't - be the same */ - gc_list_move(wrasgc, &wrcb_to_call); - } - } - - /* Invoke the callbacks we decided to honor. It's safe to invoke them - * because they can't reference unreachable objects. - */ - while (! gc_list_is_empty(&wrcb_to_call)) { - PyObject *temp; - PyObject *callback; - - gc = wrcb_to_call.gc.gc_next; - op = FROM_GC(gc); - assert(IS_REACHABLE(op)); - assert(PyWeakref_Check(op)); - wr = (PyWeakReference *)op; - callback = wr->wr_callback; - assert(callback != NULL); - - /* copy-paste of weakrefobject.c's handle_callback() */ - temp = PyObject_CallFunctionObjArgs(callback, wr, NULL); - if (temp == NULL) - PyErr_WriteUnraisable(callback); - else - Py_DECREF(temp); - - /* Give up the reference we created in the first pass. When - * op's refcount hits 0 (which it may or may not do right now), - * op's tp_dealloc will decref op->wr_callback too. Note - * that the refcount probably will hit 0 now, and because this - * weakref was reachable to begin with, gc didn't already - * add it to its count of freed objects. Example: a reachable - * weak value dict maps some key to this reachable weakref. - * The callback removes this key->weakref mapping from the - * dict, leaving no other references to the weakref (excepting - * ours). - */ - Py_DECREF(op); - if (wrcb_to_call.gc.gc_next == gc) { - /* object is still alive -- move it */ - gc_list_move(gc, old); - } - else - ++num_freed; - } + PyGC_Head *gc; + PyObject *op; /* generally FROM_GC(gc) */ + PyWeakReference *wr; /* generally a cast of op */ + PyGC_Head wrcb_to_call; /* weakrefs with callbacks to call */ + PyGC_Head *next; + int num_freed = 0; + + gc_list_init(&wrcb_to_call); + + /* Clear all weakrefs to the objects in unreachable. If such a weakref + * also has a callback, move it into `wrcb_to_call` if the callback + * needs to be invoked. Note that we cannot invoke any callbacks until + * all weakrefs to unreachable objects are cleared, lest the callback + * resurrect an unreachable object via a still-active weakref. We + * make another pass over wrcb_to_call, invoking callbacks, after this + * pass completes. + */ + for (gc = unreachable->gc.gc_next; gc != unreachable; gc = next) { + PyWeakReference **wrlist; + + op = FROM_GC(gc); + assert(IS_TENTATIVELY_UNREACHABLE(op)); + next = gc->gc.gc_next; + + if (! PyType_SUPPORTS_WEAKREFS(Py_TYPE(op))) + continue; + + /* It supports weakrefs. Does it have any? */ + wrlist = (PyWeakReference **) + PyObject_GET_WEAKREFS_LISTPTR(op); + + /* `op` may have some weakrefs. March over the list, clear + * all the weakrefs, and move the weakrefs with callbacks + * that must be called into wrcb_to_call. + */ + for (wr = *wrlist; wr != NULL; wr = *wrlist) { + PyGC_Head *wrasgc; /* AS_GC(wr) */ + + /* _PyWeakref_ClearRef clears the weakref but leaves + * the callback pointer intact. Obscure: it also + * changes *wrlist. + */ + assert(wr->wr_object == op); + _PyWeakref_ClearRef(wr); + assert(wr->wr_object == Py_None); + if (wr->wr_callback == NULL) + continue; /* no callback */ + + /* Headache time. `op` is going away, and is weakly referenced by + * `wr`, which has a callback. Should the callback be invoked? If wr + * is also trash, no: + * + * 1. There's no need to call it. The object and the weakref are + * both going away, so it's legitimate to pretend the weakref is + * going away first. The user has to ensure a weakref outlives its + * referent if they want a guarantee that the wr callback will get + * invoked. + * + * 2. It may be catastrophic to call it. If the callback is also in + * cyclic trash (CT), then although the CT is unreachable from + * outside the current generation, CT may be reachable from the + * callback. Then the callback could resurrect insane objects. + * + * Since the callback is never needed and may be unsafe in this case, + * wr is simply left in the unreachable set. Note that because we + * already called _PyWeakref_ClearRef(wr), its callback will never + * trigger. + * + * OTOH, if wr isn't part of CT, we should invoke the callback: the + * weakref outlived the trash. Note that since wr isn't CT in this + * case, its callback can't be CT either -- wr acted as an external + * root to this generation, and therefore its callback did too. So + * nothing in CT is reachable from the callback either, so it's hard + * to imagine how calling it later could create a problem for us. wr + * is moved to wrcb_to_call in this case. + */ + if (IS_TENTATIVELY_UNREACHABLE(wr)) + continue; + assert(IS_REACHABLE(wr)); + + /* Create a new reference so that wr can't go away + * before we can process it again. + */ + Py_INCREF(wr); + + /* Move wr to wrcb_to_call, for the next pass. */ + wrasgc = AS_GC(wr); + assert(wrasgc != next); /* wrasgc is reachable, but + next isn't, so they can't + be the same */ + gc_list_move(wrasgc, &wrcb_to_call); + } + } + + /* Invoke the callbacks we decided to honor. It's safe to invoke them + * because they can't reference unreachable objects. + */ + while (! gc_list_is_empty(&wrcb_to_call)) { + PyObject *temp; + PyObject *callback; + + gc = wrcb_to_call.gc.gc_next; + op = FROM_GC(gc); + assert(IS_REACHABLE(op)); + assert(PyWeakref_Check(op)); + wr = (PyWeakReference *)op; + callback = wr->wr_callback; + assert(callback != NULL); + + /* copy-paste of weakrefobject.c's handle_callback() */ + temp = PyObject_CallFunctionObjArgs(callback, wr, NULL); + if (temp == NULL) + PyErr_WriteUnraisable(callback); + else + Py_DECREF(temp); + + /* Give up the reference we created in the first pass. When + * op's refcount hits 0 (which it may or may not do right now), + * op's tp_dealloc will decref op->wr_callback too. Note + * that the refcount probably will hit 0 now, and because this + * weakref was reachable to begin with, gc didn't already + * add it to its count of freed objects. Example: a reachable + * weak value dict maps some key to this reachable weakref. + * The callback removes this key->weakref mapping from the + * dict, leaving no other references to the weakref (excepting + * ours). + */ + Py_DECREF(op); + if (wrcb_to_call.gc.gc_next == gc) { + /* object is still alive -- move it */ + gc_list_move(gc, old); + } + else + ++num_freed; + } - return num_freed; + return num_freed; } static void debug_cycle(char *msg, PyObject *op) { - PySys_WriteStderr("gc: %.100s <%.100s %p>\n", - msg, Py_TYPE(op)->tp_name, op); + PySys_WriteStderr("gc: %.100s <%.100s %p>\n", + msg, Py_TYPE(op)->tp_name, op); } /* Handle uncollectable garbage (cycles with finalizers, and stuff reachable @@ -696,56 +696,56 @@ static int handle_finalizers(PyGC_Head *finalizers, PyGC_Head *old) { - PyGC_Head *gc = finalizers->gc.gc_next; + PyGC_Head *gc = finalizers->gc.gc_next; - if (garbage == NULL) { - garbage = PyList_New(0); - if (garbage == NULL) - Py_FatalError("gc couldn't create gc.garbage list"); - } - for (; gc != finalizers; gc = gc->gc.gc_next) { - PyObject *op = FROM_GC(gc); - - if ((debug & DEBUG_SAVEALL) || has_finalizer(op)) { - if (PyList_Append(garbage, op) < 0) - return -1; - } - } + if (garbage == NULL) { + garbage = PyList_New(0); + if (garbage == NULL) + Py_FatalError("gc couldn't create gc.garbage list"); + } + for (; gc != finalizers; gc = gc->gc.gc_next) { + PyObject *op = FROM_GC(gc); + + if ((debug & DEBUG_SAVEALL) || has_finalizer(op)) { + if (PyList_Append(garbage, op) < 0) + return -1; + } + } - gc_list_merge(finalizers, old); - return 0; + gc_list_merge(finalizers, old); + return 0; } -/* Break reference cycles by clearing the containers involved. This is +/* Break reference cycles by clearing the containers involved. This is * tricky business as the lists can be changing and we don't know which * objects may be freed. It is possible I screwed something up here. */ static void delete_garbage(PyGC_Head *collectable, PyGC_Head *old) { - inquiry clear; + inquiry clear; - while (!gc_list_is_empty(collectable)) { - PyGC_Head *gc = collectable->gc.gc_next; - PyObject *op = FROM_GC(gc); - - assert(IS_TENTATIVELY_UNREACHABLE(op)); - if (debug & DEBUG_SAVEALL) { - PyList_Append(garbage, op); - } - else { - if ((clear = Py_TYPE(op)->tp_clear) != NULL) { - Py_INCREF(op); - clear(op); - Py_DECREF(op); - } - } - if (collectable->gc.gc_next == gc) { - /* object is still alive, move it, it may die later */ - gc_list_move(gc, old); - gc->gc.gc_refs = GC_REACHABLE; - } - } + while (!gc_list_is_empty(collectable)) { + PyGC_Head *gc = collectable->gc.gc_next; + PyObject *op = FROM_GC(gc); + + assert(IS_TENTATIVELY_UNREACHABLE(op)); + if (debug & DEBUG_SAVEALL) { + PyList_Append(garbage, op); + } + else { + if ((clear = Py_TYPE(op)->tp_clear) != NULL) { + Py_INCREF(op); + clear(op); + Py_DECREF(op); + } + } + if (collectable->gc.gc_next == gc) { + /* object is still alive, move it, it may die later */ + gc_list_move(gc, old); + gc->gc.gc_refs = GC_REACHABLE; + } + } } /* Clear all free lists @@ -756,30 +756,30 @@ static void clear_freelists(void) { - (void)PyMethod_ClearFreeList(); - (void)PyFrame_ClearFreeList(); - (void)PyCFunction_ClearFreeList(); - (void)PyTuple_ClearFreeList(); - (void)PyUnicode_ClearFreeList(); - (void)PyFloat_ClearFreeList(); + (void)PyMethod_ClearFreeList(); + (void)PyFrame_ClearFreeList(); + (void)PyCFunction_ClearFreeList(); + (void)PyTuple_ClearFreeList(); + (void)PyUnicode_ClearFreeList(); + (void)PyFloat_ClearFreeList(); } static double get_time(void) { - double result = 0; - if (tmod != NULL) { - PyObject *f = PyObject_CallMethod(tmod, "time", NULL); - if (f == NULL) { - PyErr_Clear(); - } - else { - if (PyFloat_Check(f)) - result = PyFloat_AsDouble(f); - Py_DECREF(f); - } - } - return result; + double result = 0; + if (tmod != NULL) { + PyObject *f = PyObject_CallMethod(tmod, "time", NULL); + if (f == NULL) { + PyErr_Clear(); + } + else { + if (PyFloat_Check(f)) + result = PyFloat_AsDouble(f); + Py_DECREF(f); + } + } + return result; } /* This is the main function. Read this to understand how the @@ -787,184 +787,184 @@ static Py_ssize_t collect(int generation) { - int i; - Py_ssize_t m = 0; /* # objects collected */ - Py_ssize_t n = 0; /* # unreachable objects that couldn't be collected */ - PyGC_Head *young; /* the generation we are examining */ - PyGC_Head *old; /* next older generation */ - PyGC_Head unreachable; /* non-problematic unreachable trash */ - PyGC_Head finalizers; /* objects with, & reachable from, __del__ */ - PyGC_Head *gc; - double t1 = 0.0; - - if (delstr == NULL) { - delstr = PyUnicode_InternFromString("__del__"); - if (delstr == NULL) - Py_FatalError("gc couldn't allocate \"__del__\""); - } - - if (debug & DEBUG_STATS) { - PySys_WriteStderr("gc: collecting generation %d...\n", - generation); - PySys_WriteStderr("gc: objects in each generation:"); - for (i = 0; i < NUM_GENERATIONS; i++) - PySys_WriteStderr(" %" PY_FORMAT_SIZE_T "d", - gc_list_size(GEN_HEAD(i))); - t1 = get_time(); - PySys_WriteStderr("\n"); - } - - /* update collection and allocation counters */ - if (generation+1 < NUM_GENERATIONS) - generations[generation+1].count += 1; - for (i = 0; i <= generation; i++) - generations[i].count = 0; - - /* merge younger generations with one we are currently collecting */ - for (i = 0; i < generation; i++) { - gc_list_merge(GEN_HEAD(i), GEN_HEAD(generation)); - } - - /* handy references */ - young = GEN_HEAD(generation); - if (generation < NUM_GENERATIONS-1) - old = GEN_HEAD(generation+1); - else - old = young; - - /* Using ob_refcnt and gc_refs, calculate which objects in the - * container set are reachable from outside the set (i.e., have a - * refcount greater than 0 when all the references within the - * set are taken into account). - */ - update_refs(young); - subtract_refs(young); - - /* Leave everything reachable from outside young in young, and move - * everything else (in young) to unreachable. - * NOTE: This used to move the reachable objects into a reachable - * set instead. But most things usually turn out to be reachable, - * so it's more efficient to move the unreachable things. - */ - gc_list_init(&unreachable); - move_unreachable(young, &unreachable); - - /* Move reachable objects to next generation. */ - if (young != old) { - if (generation == NUM_GENERATIONS - 2) { - long_lived_pending += gc_list_size(young); - } - gc_list_merge(young, old); - } - else { - long_lived_pending = 0; - long_lived_total = gc_list_size(young); - } - - /* All objects in unreachable are trash, but objects reachable from - * finalizers can't safely be deleted. Python programmers should take - * care not to create such things. For Python, finalizers means - * instance objects with __del__ methods. Weakrefs with callbacks - * can also call arbitrary Python code but they will be dealt with by - * handle_weakrefs(). - */ - gc_list_init(&finalizers); - move_finalizers(&unreachable, &finalizers); - /* finalizers contains the unreachable objects with a finalizer; - * unreachable objects reachable *from* those are also uncollectable, - * and we move those into the finalizers list too. - */ - move_finalizer_reachable(&finalizers); - - /* Collect statistics on collectable objects found and print - * debugging information. - */ - for (gc = unreachable.gc.gc_next; gc != &unreachable; - gc = gc->gc.gc_next) { - m++; - if (debug & DEBUG_COLLECTABLE) { - debug_cycle("collectable", FROM_GC(gc)); - } - } - - /* Clear weakrefs and invoke callbacks as necessary. */ - m += handle_weakrefs(&unreachable, old); - - /* Call tp_clear on objects in the unreachable set. This will cause - * the reference cycles to be broken. It may also cause some objects - * in finalizers to be freed. - */ - delete_garbage(&unreachable, old); - - /* Collect statistics on uncollectable objects found and print - * debugging information. */ - for (gc = finalizers.gc.gc_next; - gc != &finalizers; - gc = gc->gc.gc_next) { - n++; - if (debug & DEBUG_UNCOLLECTABLE) - debug_cycle("uncollectable", FROM_GC(gc)); - } - if (debug & DEBUG_STATS) { - double t2 = get_time(); - if (m == 0 && n == 0) - PySys_WriteStderr("gc: done"); - else - PySys_WriteStderr( - "gc: done, " - "%" PY_FORMAT_SIZE_T "d unreachable, " - "%" PY_FORMAT_SIZE_T "d uncollectable", - n+m, n); - if (t1 && t2) { - PySys_WriteStderr(", %.4fs elapsed", t2-t1); - } - PySys_WriteStderr(".\n"); - } - - /* Append instances in the uncollectable set to a Python - * 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); - - /* Clear free list only during the collection of the highest - * generation */ - if (generation == NUM_GENERATIONS-1) { - clear_freelists(); - } - - if (PyErr_Occurred()) { - if (gc_str == NULL) - gc_str = PyUnicode_FromString("garbage collection"); - PyErr_WriteUnraisable(gc_str); - Py_FatalError("unexpected exception during garbage collection"); - } - return n+m; + int i; + Py_ssize_t m = 0; /* # objects collected */ + Py_ssize_t n = 0; /* # unreachable objects that couldn't be collected */ + PyGC_Head *young; /* the generation we are examining */ + PyGC_Head *old; /* next older generation */ + PyGC_Head unreachable; /* non-problematic unreachable trash */ + PyGC_Head finalizers; /* objects with, & reachable from, __del__ */ + PyGC_Head *gc; + double t1 = 0.0; + + if (delstr == NULL) { + delstr = PyUnicode_InternFromString("__del__"); + if (delstr == NULL) + Py_FatalError("gc couldn't allocate \"__del__\""); + } + + if (debug & DEBUG_STATS) { + PySys_WriteStderr("gc: collecting generation %d...\n", + generation); + PySys_WriteStderr("gc: objects in each generation:"); + for (i = 0; i < NUM_GENERATIONS; i++) + PySys_WriteStderr(" %" PY_FORMAT_SIZE_T "d", + gc_list_size(GEN_HEAD(i))); + t1 = get_time(); + PySys_WriteStderr("\n"); + } + + /* update collection and allocation counters */ + if (generation+1 < NUM_GENERATIONS) + generations[generation+1].count += 1; + for (i = 0; i <= generation; i++) + generations[i].count = 0; + + /* merge younger generations with one we are currently collecting */ + for (i = 0; i < generation; i++) { + gc_list_merge(GEN_HEAD(i), GEN_HEAD(generation)); + } + + /* handy references */ + young = GEN_HEAD(generation); + if (generation < NUM_GENERATIONS-1) + old = GEN_HEAD(generation+1); + else + old = young; + + /* Using ob_refcnt and gc_refs, calculate which objects in the + * container set are reachable from outside the set (i.e., have a + * refcount greater than 0 when all the references within the + * set are taken into account). + */ + update_refs(young); + subtract_refs(young); + + /* Leave everything reachable from outside young in young, and move + * everything else (in young) to unreachable. + * NOTE: This used to move the reachable objects into a reachable + * set instead. But most things usually turn out to be reachable, + * so it's more efficient to move the unreachable things. + */ + gc_list_init(&unreachable); + move_unreachable(young, &unreachable); + + /* Move reachable objects to next generation. */ + if (young != old) { + if (generation == NUM_GENERATIONS - 2) { + long_lived_pending += gc_list_size(young); + } + gc_list_merge(young, old); + } + else { + long_lived_pending = 0; + long_lived_total = gc_list_size(young); + } + + /* All objects in unreachable are trash, but objects reachable from + * finalizers can't safely be deleted. Python programmers should take + * care not to create such things. For Python, finalizers means + * instance objects with __del__ methods. Weakrefs with callbacks + * can also call arbitrary Python code but they will be dealt with by + * handle_weakrefs(). + */ + gc_list_init(&finalizers); + move_finalizers(&unreachable, &finalizers); + /* finalizers contains the unreachable objects with a finalizer; + * unreachable objects reachable *from* those are also uncollectable, + * and we move those into the finalizers list too. + */ + move_finalizer_reachable(&finalizers); + + /* Collect statistics on collectable objects found and print + * debugging information. + */ + for (gc = unreachable.gc.gc_next; gc != &unreachable; + gc = gc->gc.gc_next) { + m++; + if (debug & DEBUG_COLLECTABLE) { + debug_cycle("collectable", FROM_GC(gc)); + } + } + + /* Clear weakrefs and invoke callbacks as necessary. */ + m += handle_weakrefs(&unreachable, old); + + /* Call tp_clear on objects in the unreachable set. This will cause + * the reference cycles to be broken. It may also cause some objects + * in finalizers to be freed. + */ + delete_garbage(&unreachable, old); + + /* Collect statistics on uncollectable objects found and print + * debugging information. */ + for (gc = finalizers.gc.gc_next; + gc != &finalizers; + gc = gc->gc.gc_next) { + n++; + if (debug & DEBUG_UNCOLLECTABLE) + debug_cycle("uncollectable", FROM_GC(gc)); + } + if (debug & DEBUG_STATS) { + double t2 = get_time(); + if (m == 0 && n == 0) + PySys_WriteStderr("gc: done"); + else + PySys_WriteStderr( + "gc: done, " + "%" PY_FORMAT_SIZE_T "d unreachable, " + "%" PY_FORMAT_SIZE_T "d uncollectable", + n+m, n); + if (t1 && t2) { + PySys_WriteStderr(", %.4fs elapsed", t2-t1); + } + PySys_WriteStderr(".\n"); + } + + /* Append instances in the uncollectable set to a Python + * 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); + + /* Clear free list only during the collection of the highest + * generation */ + if (generation == NUM_GENERATIONS-1) { + clear_freelists(); + } + + if (PyErr_Occurred()) { + if (gc_str == NULL) + gc_str = PyUnicode_FromString("garbage collection"); + PyErr_WriteUnraisable(gc_str); + Py_FatalError("unexpected exception during garbage collection"); + } + return n+m; } static Py_ssize_t collect_generations(void) { - int i; - Py_ssize_t n = 0; + int i; + Py_ssize_t n = 0; - /* Find the oldest generation (highest numbered) where the count - * exceeds the threshold. Objects in the that generation and - * generations younger than it will be collected. */ - for (i = NUM_GENERATIONS-1; i >= 0; i--) { - if (generations[i].count > generations[i].threshold) { - /* Avoid quadratic performance degradation in number - of tracked objects. See comments at the beginning - of this file, and issue #4074. - */ - if (i == NUM_GENERATIONS - 1 - && long_lived_pending < long_lived_total / 4) - continue; - n = collect(i); - break; - } - } - return n; + /* Find the oldest generation (highest numbered) where the count + * exceeds the threshold. Objects in the that generation and + * generations younger than it will be collected. */ + for (i = NUM_GENERATIONS-1; i >= 0; i--) { + if (generations[i].count > generations[i].threshold) { + /* Avoid quadratic performance degradation in number + of tracked objects. See comments at the beginning + of this file, and issue #4074. + */ + if (i == NUM_GENERATIONS - 1 + && long_lived_pending < long_lived_total / 4) + continue; + n = collect(i); + break; + } + } + return n; } PyDoc_STRVAR(gc_enable__doc__, @@ -975,9 +975,9 @@ static PyObject * gc_enable(PyObject *self, PyObject *noargs) { - enabled = 1; - Py_INCREF(Py_None); - return Py_None; + enabled = 1; + Py_INCREF(Py_None); + return Py_None; } PyDoc_STRVAR(gc_disable__doc__, @@ -988,9 +988,9 @@ static PyObject * gc_disable(PyObject *self, PyObject *noargs) { - enabled = 0; - Py_INCREF(Py_None); - return Py_None; + enabled = 0; + Py_INCREF(Py_None); + return Py_None; } PyDoc_STRVAR(gc_isenabled__doc__, @@ -1001,7 +1001,7 @@ static PyObject * gc_isenabled(PyObject *self, PyObject *noargs) { - return PyBool_FromLong((long)enabled); + return PyBool_FromLong((long)enabled); } PyDoc_STRVAR(gc_collect__doc__, @@ -1015,27 +1015,27 @@ static PyObject * gc_collect(PyObject *self, PyObject *args, PyObject *kws) { - static char *keywords[] = {"generation", NULL}; - int genarg = NUM_GENERATIONS - 1; - Py_ssize_t n; - - if (!PyArg_ParseTupleAndKeywords(args, kws, "|i", keywords, &genarg)) - return NULL; - - else if (genarg < 0 || genarg >= NUM_GENERATIONS) { - PyErr_SetString(PyExc_ValueError, "invalid generation"); - return NULL; - } - - if (collecting) - n = 0; /* already collecting, don't do anything */ - else { - collecting = 1; - n = collect(genarg); - collecting = 0; - } + static char *keywords[] = {"generation", NULL}; + int genarg = NUM_GENERATIONS - 1; + Py_ssize_t n; + + if (!PyArg_ParseTupleAndKeywords(args, kws, "|i", keywords, &genarg)) + return NULL; + + else if (genarg < 0 || genarg >= NUM_GENERATIONS) { + PyErr_SetString(PyExc_ValueError, "invalid generation"); + return NULL; + } + + if (collecting) + n = 0; /* already collecting, don't do anything */ + else { + collecting = 1; + n = collect(genarg); + collecting = 0; + } - return PyLong_FromSsize_t(n); + return PyLong_FromSsize_t(n); } PyDoc_STRVAR(gc_set_debug__doc__, @@ -1055,11 +1055,11 @@ static PyObject * gc_set_debug(PyObject *self, PyObject *args) { - if (!PyArg_ParseTuple(args, "i:set_debug", &debug)) - return NULL; + if (!PyArg_ParseTuple(args, "i:set_debug", &debug)) + return NULL; - Py_INCREF(Py_None); - return Py_None; + Py_INCREF(Py_None); + return Py_None; } PyDoc_STRVAR(gc_get_debug__doc__, @@ -1070,7 +1070,7 @@ static PyObject * gc_get_debug(PyObject *self, PyObject *noargs) { - return Py_BuildValue("i", debug); + return Py_BuildValue("i", debug); } PyDoc_STRVAR(gc_set_thresh__doc__, @@ -1082,19 +1082,19 @@ static PyObject * gc_set_thresh(PyObject *self, PyObject *args) { - int i; - if (!PyArg_ParseTuple(args, "i|ii:set_threshold", - &generations[0].threshold, - &generations[1].threshold, - &generations[2].threshold)) - return NULL; - for (i = 2; i < NUM_GENERATIONS; i++) { - /* generations higher than 2 get the same threshold */ - generations[i].threshold = generations[2].threshold; - } + int i; + if (!PyArg_ParseTuple(args, "i|ii:set_threshold", + &generations[0].threshold, + &generations[1].threshold, + &generations[2].threshold)) + return NULL; + for (i = 2; i < NUM_GENERATIONS; i++) { + /* generations higher than 2 get the same threshold */ + generations[i].threshold = generations[2].threshold; + } - Py_INCREF(Py_None); - return Py_None; + Py_INCREF(Py_None); + return Py_None; } PyDoc_STRVAR(gc_get_thresh__doc__, @@ -1105,10 +1105,10 @@ static PyObject * gc_get_thresh(PyObject *self, PyObject *noargs) { - return Py_BuildValue("(iii)", - generations[0].threshold, - generations[1].threshold, - generations[2].threshold); + return Py_BuildValue("(iii)", + generations[0].threshold, + generations[1].threshold, + generations[2].threshold); } PyDoc_STRVAR(gc_get_count__doc__, @@ -1119,39 +1119,39 @@ static PyObject * gc_get_count(PyObject *self, PyObject *noargs) { - return Py_BuildValue("(iii)", - generations[0].count, - generations[1].count, - generations[2].count); + return Py_BuildValue("(iii)", + generations[0].count, + generations[1].count, + generations[2].count); } static int referrersvisit(PyObject* obj, PyObject *objs) { - Py_ssize_t i; - for (i = 0; i < PyTuple_GET_SIZE(objs); i++) - if (PyTuple_GET_ITEM(objs, i) == obj) - return 1; - return 0; + Py_ssize_t i; + for (i = 0; i < PyTuple_GET_SIZE(objs); i++) + if (PyTuple_GET_ITEM(objs, i) == obj) + return 1; + return 0; } static int gc_referrers_for(PyObject *objs, PyGC_Head *list, PyObject *resultlist) { - PyGC_Head *gc; - PyObject *obj; - traverseproc traverse; - for (gc = list->gc.gc_next; gc != list; gc = gc->gc.gc_next) { - obj = FROM_GC(gc); - traverse = Py_TYPE(obj)->tp_traverse; - if (obj == objs || obj == resultlist) - continue; - if (traverse(obj, (visitproc)referrersvisit, objs)) { - if (PyList_Append(resultlist, obj) < 0) - return 0; /* error */ - } - } - return 1; /* no error */ + PyGC_Head *gc; + PyObject *obj; + traverseproc traverse; + for (gc = list->gc.gc_next; gc != list; gc = gc->gc.gc_next) { + obj = FROM_GC(gc); + traverse = Py_TYPE(obj)->tp_traverse; + if (obj == objs || obj == resultlist) + continue; + if (traverse(obj, (visitproc)referrersvisit, objs)) { + if (PyList_Append(resultlist, obj) < 0) + return 0; /* error */ + } + } + return 1; /* no error */ } PyDoc_STRVAR(gc_get_referrers__doc__, @@ -1161,24 +1161,24 @@ static PyObject * gc_get_referrers(PyObject *self, PyObject *args) { - int i; - PyObject *result = PyList_New(0); - if (!result) return NULL; - - for (i = 0; i < NUM_GENERATIONS; i++) { - if (!(gc_referrers_for(args, GEN_HEAD(i), result))) { - Py_DECREF(result); - return NULL; - } - } - return result; + int i; + PyObject *result = PyList_New(0); + if (!result) return NULL; + + for (i = 0; i < NUM_GENERATIONS; i++) { + if (!(gc_referrers_for(args, GEN_HEAD(i), result))) { + Py_DECREF(result); + return NULL; + } + } + return result; } /* Append obj to list; return true if error (out of memory), false if OK. */ static int referentsvisit(PyObject *obj, PyObject *list) { - return PyList_Append(list, obj) < 0; + return PyList_Append(list, obj) < 0; } PyDoc_STRVAR(gc_get_referents__doc__, @@ -1188,27 +1188,27 @@ static PyObject * gc_get_referents(PyObject *self, PyObject *args) { - Py_ssize_t i; - PyObject *result = PyList_New(0); + Py_ssize_t i; + PyObject *result = PyList_New(0); - if (result == NULL) - return NULL; + if (result == NULL) + return NULL; - for (i = 0; i < PyTuple_GET_SIZE(args); i++) { - traverseproc traverse; - PyObject *obj = PyTuple_GET_ITEM(args, i); - - if (! PyObject_IS_GC(obj)) - continue; - traverse = Py_TYPE(obj)->tp_traverse; - if (! traverse) - continue; - if (traverse(obj, (visitproc)referentsvisit, result)) { - Py_DECREF(result); - return NULL; - } - } - return result; + for (i = 0; i < PyTuple_GET_SIZE(args); i++) { + traverseproc traverse; + PyObject *obj = PyTuple_GET_ITEM(args, i); + + if (! PyObject_IS_GC(obj)) + continue; + traverse = Py_TYPE(obj)->tp_traverse; + if (! traverse) + continue; + if (traverse(obj, (visitproc)referentsvisit, result)) { + Py_DECREF(result); + return NULL; + } + } + return result; } PyDoc_STRVAR(gc_get_objects__doc__, @@ -1220,19 +1220,19 @@ static PyObject * gc_get_objects(PyObject *self, PyObject *noargs) { - int i; - PyObject* result; + int i; + PyObject* result; - result = PyList_New(0); - if (result == NULL) - return NULL; - for (i = 0; i < NUM_GENERATIONS; i++) { - if (append_objects(result, GEN_HEAD(i))) { - Py_DECREF(result); - return NULL; - } - } - return result; + result = PyList_New(0); + if (result == NULL) + return NULL; + for (i = 0; i < NUM_GENERATIONS; i++) { + if (append_objects(result, GEN_HEAD(i))) { + Py_DECREF(result); + return NULL; + } + } + return result; } PyDoc_STRVAR(gc_is_tracked__doc__, @@ -1245,14 +1245,14 @@ static PyObject * gc_is_tracked(PyObject *self, PyObject *obj) { - PyObject *result; - - if (PyObject_IS_GC(obj) && IS_TRACKED(obj)) - result = Py_True; - else - result = Py_False; - Py_INCREF(result); - return result; + PyObject *result; + + if (PyObject_IS_GC(obj) && IS_TRACKED(obj)) + result = Py_True; + else + result = Py_False; + Py_INCREF(result); + return result; } @@ -1274,101 +1274,101 @@ "get_referents() -- Return the list of objects that an object refers to.\n"); static PyMethodDef GcMethods[] = { - {"enable", gc_enable, METH_NOARGS, gc_enable__doc__}, - {"disable", gc_disable, METH_NOARGS, gc_disable__doc__}, - {"isenabled", gc_isenabled, METH_NOARGS, gc_isenabled__doc__}, - {"set_debug", gc_set_debug, METH_VARARGS, gc_set_debug__doc__}, - {"get_debug", gc_get_debug, METH_NOARGS, gc_get_debug__doc__}, - {"get_count", gc_get_count, METH_NOARGS, gc_get_count__doc__}, - {"set_threshold", gc_set_thresh, METH_VARARGS, gc_set_thresh__doc__}, - {"get_threshold", gc_get_thresh, METH_NOARGS, gc_get_thresh__doc__}, - {"collect", (PyCFunction)gc_collect, - METH_VARARGS | METH_KEYWORDS, gc_collect__doc__}, - {"get_objects", gc_get_objects,METH_NOARGS, gc_get_objects__doc__}, - {"is_tracked", gc_is_tracked, METH_O, gc_is_tracked__doc__}, - {"get_referrers", gc_get_referrers, METH_VARARGS, - gc_get_referrers__doc__}, - {"get_referents", gc_get_referents, METH_VARARGS, - gc_get_referents__doc__}, - {NULL, NULL} /* Sentinel */ + {"enable", gc_enable, METH_NOARGS, gc_enable__doc__}, + {"disable", gc_disable, METH_NOARGS, gc_disable__doc__}, + {"isenabled", gc_isenabled, METH_NOARGS, gc_isenabled__doc__}, + {"set_debug", gc_set_debug, METH_VARARGS, gc_set_debug__doc__}, + {"get_debug", gc_get_debug, METH_NOARGS, gc_get_debug__doc__}, + {"get_count", gc_get_count, METH_NOARGS, gc_get_count__doc__}, + {"set_threshold", gc_set_thresh, METH_VARARGS, gc_set_thresh__doc__}, + {"get_threshold", gc_get_thresh, METH_NOARGS, gc_get_thresh__doc__}, + {"collect", (PyCFunction)gc_collect, + METH_VARARGS | METH_KEYWORDS, gc_collect__doc__}, + {"get_objects", gc_get_objects,METH_NOARGS, gc_get_objects__doc__}, + {"is_tracked", gc_is_tracked, METH_O, gc_is_tracked__doc__}, + {"get_referrers", gc_get_referrers, METH_VARARGS, + gc_get_referrers__doc__}, + {"get_referents", gc_get_referents, METH_VARARGS, + gc_get_referents__doc__}, + {NULL, NULL} /* Sentinel */ }; static struct PyModuleDef gcmodule = { - PyModuleDef_HEAD_INIT, - "gc", - gc__doc__, - -1, - GcMethods, - NULL, - NULL, - NULL, - NULL + PyModuleDef_HEAD_INIT, + "gc", + gc__doc__, + -1, + GcMethods, + NULL, + NULL, + NULL, + NULL }; PyMODINIT_FUNC PyInit_gc(void) { - PyObject *m; + PyObject *m; - m = PyModule_Create(&gcmodule); + m = PyModule_Create(&gcmodule); - if (m == NULL) - return NULL; + if (m == NULL) + return NULL; - if (garbage == NULL) { - garbage = PyList_New(0); - if (garbage == NULL) - return NULL; - } - Py_INCREF(garbage); - if (PyModule_AddObject(m, "garbage", garbage) < 0) - return NULL; - - /* Importing can't be done in collect() because collect() - * can be called via PyGC_Collect() in Py_Finalize(). - * This wouldn't be a problem, except that is - * reset to 0 before calling collect which trips up - * the import and triggers an assertion. - */ - if (tmod == NULL) { - tmod = PyImport_ImportModuleNoBlock("time"); - if (tmod == NULL) - PyErr_Clear(); - } + if (garbage == NULL) { + garbage = PyList_New(0); + if (garbage == NULL) + return NULL; + } + Py_INCREF(garbage); + if (PyModule_AddObject(m, "garbage", garbage) < 0) + return NULL; + + /* Importing can't be done in collect() because collect() + * can be called via PyGC_Collect() in Py_Finalize(). + * This wouldn't be a problem, except that is + * reset to 0 before calling collect which trips up + * the import and triggers an assertion. + */ + if (tmod == NULL) { + tmod = PyImport_ImportModuleNoBlock("time"); + if (tmod == NULL) + PyErr_Clear(); + } #define ADD_INT(NAME) if (PyModule_AddIntConstant(m, #NAME, NAME) < 0) return NULL - ADD_INT(DEBUG_STATS); - ADD_INT(DEBUG_COLLECTABLE); - ADD_INT(DEBUG_UNCOLLECTABLE); - ADD_INT(DEBUG_SAVEALL); - ADD_INT(DEBUG_LEAK); + ADD_INT(DEBUG_STATS); + ADD_INT(DEBUG_COLLECTABLE); + ADD_INT(DEBUG_UNCOLLECTABLE); + ADD_INT(DEBUG_SAVEALL); + ADD_INT(DEBUG_LEAK); #undef ADD_INT - return m; + return m; } /* API to invoke gc.collect() from C */ Py_ssize_t PyGC_Collect(void) { - Py_ssize_t n; + Py_ssize_t n; - if (collecting) - n = 0; /* already collecting, don't do anything */ - else { - collecting = 1; - n = collect(NUM_GENERATIONS - 1); - collecting = 0; - } + if (collecting) + n = 0; /* already collecting, don't do anything */ + else { + collecting = 1; + n = collect(NUM_GENERATIONS - 1); + collecting = 0; + } - return n; + return n; } /* for debugging */ void _PyGC_Dump(PyGC_Head *g) { - _PyObject_Dump(FROM_GC(g)); + _PyObject_Dump(FROM_GC(g)); } /* extension modules might be compiled with GC support so these @@ -1382,7 +1382,7 @@ void PyObject_GC_Track(void *op) { - _PyObject_GC_TRACK(op); + _PyObject_GC_TRACK(op); } /* for binary compatibility with 2.2 */ @@ -1395,11 +1395,11 @@ void PyObject_GC_UnTrack(void *op) { - /* Obscure: the Py_TRASHCAN mechanism requires that we be able to - * call PyObject_GC_UnTrack twice on an object. - */ - if (IS_TRACKED(op)) - _PyObject_GC_UNTRACK(op); + /* Obscure: the Py_TRASHCAN mechanism requires that we be able to + * call PyObject_GC_UnTrack twice on an object. + */ + if (IS_TRACKED(op)) + _PyObject_GC_UNTRACK(op); } /* for binary compatibility with 2.2 */ @@ -1412,73 +1412,73 @@ PyObject * _PyObject_GC_Malloc(size_t basicsize) { - PyObject *op; - PyGC_Head *g; - if (basicsize > PY_SSIZE_T_MAX - sizeof(PyGC_Head)) - return PyErr_NoMemory(); - g = (PyGC_Head *)PyObject_MALLOC( - sizeof(PyGC_Head) + basicsize); - if (g == NULL) - return PyErr_NoMemory(); - g->gc.gc_refs = GC_UNTRACKED; - generations[0].count++; /* number of allocated GC objects */ - if (generations[0].count > generations[0].threshold && - enabled && - generations[0].threshold && - !collecting && - !PyErr_Occurred()) { - collecting = 1; - collect_generations(); - collecting = 0; - } - op = FROM_GC(g); - return op; + PyObject *op; + PyGC_Head *g; + if (basicsize > PY_SSIZE_T_MAX - sizeof(PyGC_Head)) + return PyErr_NoMemory(); + g = (PyGC_Head *)PyObject_MALLOC( + sizeof(PyGC_Head) + basicsize); + if (g == NULL) + return PyErr_NoMemory(); + g->gc.gc_refs = GC_UNTRACKED; + generations[0].count++; /* number of allocated GC objects */ + if (generations[0].count > generations[0].threshold && + enabled && + generations[0].threshold && + !collecting && + !PyErr_Occurred()) { + collecting = 1; + collect_generations(); + collecting = 0; + } + op = FROM_GC(g); + return op; } PyObject * _PyObject_GC_New(PyTypeObject *tp) { - PyObject *op = _PyObject_GC_Malloc(_PyObject_SIZE(tp)); - if (op != NULL) - op = PyObject_INIT(op, tp); - return op; + PyObject *op = _PyObject_GC_Malloc(_PyObject_SIZE(tp)); + if (op != NULL) + op = PyObject_INIT(op, tp); + return op; } PyVarObject * _PyObject_GC_NewVar(PyTypeObject *tp, Py_ssize_t nitems) { - const size_t size = _PyObject_VAR_SIZE(tp, nitems); - PyVarObject *op = (PyVarObject *) _PyObject_GC_Malloc(size); - if (op != NULL) - op = PyObject_INIT_VAR(op, tp, nitems); - return op; + const size_t size = _PyObject_VAR_SIZE(tp, nitems); + PyVarObject *op = (PyVarObject *) _PyObject_GC_Malloc(size); + if (op != NULL) + op = PyObject_INIT_VAR(op, tp, nitems); + return op; } PyVarObject * _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); - if (basicsize > PY_SSIZE_T_MAX - sizeof(PyGC_Head)) - return (PyVarObject *)PyErr_NoMemory(); - g = (PyGC_Head *)PyObject_REALLOC(g, sizeof(PyGC_Head) + basicsize); - if (g == NULL) - return (PyVarObject *)PyErr_NoMemory(); - op = (PyVarObject *) FROM_GC(g); - Py_SIZE(op) = nitems; - return op; + const size_t basicsize = _PyObject_VAR_SIZE(Py_TYPE(op), nitems); + PyGC_Head *g = AS_GC(op); + if (basicsize > PY_SSIZE_T_MAX - sizeof(PyGC_Head)) + return (PyVarObject *)PyErr_NoMemory(); + g = (PyGC_Head *)PyObject_REALLOC(g, sizeof(PyGC_Head) + basicsize); + if (g == NULL) + return (PyVarObject *)PyErr_NoMemory(); + op = (PyVarObject *) FROM_GC(g); + Py_SIZE(op) = nitems; + return op; } void PyObject_GC_Del(void *op) { - PyGC_Head *g = AS_GC(op); - if (IS_TRACKED(op)) - gc_list_remove(g); - if (generations[0].count > 0) { - generations[0].count--; - } - PyObject_FREE(g); + PyGC_Head *g = AS_GC(op); + if (IS_TRACKED(op)) + gc_list_remove(g); + if (generations[0].count > 0) { + generations[0].count--; + } + PyObject_FREE(g); } /* for binary compatibility with 2.2 */ Modified: python/branches/py3k/Modules/getaddrinfo.c ============================================================================== --- python/branches/py3k/Modules/getaddrinfo.c (original) +++ python/branches/py3k/Modules/getaddrinfo.c Sun May 9 17:52:27 2010 @@ -1,7 +1,7 @@ /* * 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: @@ -13,7 +13,7 @@ * 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 @@ -73,52 +73,52 @@ static const char in_addrany[] = { 0, 0, 0, 0 }; static const char in6_addrany[] = { - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }; -static const char in_loopback[] = { 127, 0, 0, 1 }; +static const char in_loopback[] = { 127, 0, 0, 1 }; static const char in6_loopback[] = { - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1 + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1 }; struct sockinet { - u_char si_len; - u_char si_family; - u_short si_port; + u_char si_len; + u_char si_family; + u_short si_port; }; static struct gai_afd { - int a_af; - int a_addrlen; - int a_socklen; - int a_off; - const char *a_addrany; - const char *a_loopback; + int a_af; + int a_addrlen; + int a_socklen; + int a_off; + const char *a_addrany; + const char *a_loopback; } gai_afdl [] = { #ifdef ENABLE_IPV6 #define N_INET6 0 - {PF_INET6, sizeof(struct in6_addr), - sizeof(struct sockaddr_in6), - offsetof(struct sockaddr_in6, sin6_addr), - in6_addrany, in6_loopback}, + {PF_INET6, sizeof(struct in6_addr), + sizeof(struct sockaddr_in6), + offsetof(struct sockaddr_in6, sin6_addr), + in6_addrany, in6_loopback}, #define N_INET 1 #else #define N_INET 0 #endif - {PF_INET, sizeof(struct in_addr), - sizeof(struct sockaddr_in), - offsetof(struct sockaddr_in, sin_addr), - in_addrany, in_loopback}, - {0, 0, 0, 0, NULL, NULL}, + {PF_INET, sizeof(struct in_addr), + sizeof(struct sockaddr_in), + offsetof(struct sockaddr_in, sin_addr), + in_addrany, in_loopback}, + {0, 0, 0, 0, NULL, NULL}, }; #ifdef ENABLE_IPV6 -#define PTON_MAX 16 +#define PTON_MAX 16 #else -#define PTON_MAX 4 +#define PTON_MAX 4 #endif #ifndef IN_MULTICAST -#define IN_MULTICAST(i) (((i) & 0xf0000000U) == 0xe0000000U) +#define IN_MULTICAST(i) (((i) & 0xf0000000U) == 0xe0000000U) #endif #ifndef IN_EXPERIMENTAL @@ -126,73 +126,73 @@ #endif #ifndef IN_LOOPBACKNET -#define IN_LOOPBACKNET 127 +#define IN_LOOPBACKNET 127 #endif static int get_name(const char *, struct gai_afd *, - struct addrinfo **, char *, struct addrinfo *, - int); + struct addrinfo **, char *, struct addrinfo *, + int); static int get_addr(const char *, int, struct addrinfo **, - struct addrinfo *, int); + struct addrinfo *, int); static int str_isnumber(const char *); - + static char *ai_errlist[] = { - "success.", - "address family for hostname not supported.", /* EAI_ADDRFAMILY */ - "temporary failure in name resolution.", /* EAI_AGAIN */ - "invalid value for ai_flags.", /* EAI_BADFLAGS */ - "non-recoverable failure in name resolution.", /* EAI_FAIL */ - "ai_family not supported.", /* EAI_FAMILY */ - "memory allocation failure.", /* EAI_MEMORY */ - "no address associated with hostname.", /* EAI_NODATA */ - "hostname nor servname provided, or not known.",/* EAI_NONAME */ - "servname not supported for ai_socktype.", /* EAI_SERVICE */ - "ai_socktype not supported.", /* EAI_SOCKTYPE */ - "system error returned in errno.", /* EAI_SYSTEM */ - "invalid value for hints.", /* EAI_BADHINTS */ - "resolved protocol is unknown.", /* EAI_PROTOCOL */ - "unknown error.", /* EAI_MAX */ + "success.", + "address family for hostname not supported.", /* EAI_ADDRFAMILY */ + "temporary failure in name resolution.", /* EAI_AGAIN */ + "invalid value for ai_flags.", /* EAI_BADFLAGS */ + "non-recoverable failure in name resolution.", /* EAI_FAIL */ + "ai_family not supported.", /* EAI_FAMILY */ + "memory allocation failure.", /* EAI_MEMORY */ + "no address associated with hostname.", /* EAI_NODATA */ + "hostname nor servname provided, or not known.",/* EAI_NONAME */ + "servname not supported for ai_socktype.", /* EAI_SERVICE */ + "ai_socktype not supported.", /* EAI_SOCKTYPE */ + "system error returned in errno.", /* EAI_SYSTEM */ + "invalid value for hints.", /* EAI_BADHINTS */ + "resolved protocol is unknown.", /* EAI_PROTOCOL */ + "unknown error.", /* EAI_MAX */ }; #define GET_CANONNAME(ai, str) \ if (pai->ai_flags & AI_CANONNAME) {\ - if (((ai)->ai_canonname = (char *)malloc(strlen(str) + 1)) != NULL) {\ - strcpy((ai)->ai_canonname, (str));\ - } else {\ - error = EAI_MEMORY;\ - goto free;\ - }\ + if (((ai)->ai_canonname = (char *)malloc(strlen(str) + 1)) != NULL) {\ + strcpy((ai)->ai_canonname, (str));\ + } else {\ + error = EAI_MEMORY;\ + goto free;\ + }\ } #ifdef HAVE_SOCKADDR_SA_LEN #define GET_AI(ai, gai_afd, addr, port) {\ - char *p;\ - if (((ai) = (struct addrinfo *)malloc(sizeof(struct addrinfo) +\ - ((gai_afd)->a_socklen)))\ - == NULL) goto free;\ - memcpy(ai, pai, sizeof(struct addrinfo));\ - (ai)->ai_addr = (struct sockaddr *)((ai) + 1);\ - memset((ai)->ai_addr, 0, (gai_afd)->a_socklen);\ - (ai)->ai_addr->sa_len = (ai)->ai_addrlen = (gai_afd)->a_socklen;\ - (ai)->ai_addr->sa_family = (ai)->ai_family = (gai_afd)->a_af;\ - ((struct sockinet *)(ai)->ai_addr)->si_port = port;\ - p = (char *)((ai)->ai_addr);\ - memcpy(p + (gai_afd)->a_off, (addr), (gai_afd)->a_addrlen);\ + char *p;\ + if (((ai) = (struct addrinfo *)malloc(sizeof(struct addrinfo) +\ + ((gai_afd)->a_socklen)))\ + == NULL) goto free;\ + memcpy(ai, pai, sizeof(struct addrinfo));\ + (ai)->ai_addr = (struct sockaddr *)((ai) + 1);\ + memset((ai)->ai_addr, 0, (gai_afd)->a_socklen);\ + (ai)->ai_addr->sa_len = (ai)->ai_addrlen = (gai_afd)->a_socklen;\ + (ai)->ai_addr->sa_family = (ai)->ai_family = (gai_afd)->a_af;\ + ((struct sockinet *)(ai)->ai_addr)->si_port = port;\ + p = (char *)((ai)->ai_addr);\ + memcpy(p + (gai_afd)->a_off, (addr), (gai_afd)->a_addrlen);\ } #else #define GET_AI(ai, gai_afd, addr, port) {\ - char *p;\ - if (((ai) = (struct addrinfo *)malloc(sizeof(struct addrinfo) +\ - ((gai_afd)->a_socklen)))\ - == NULL) goto free;\ - memcpy(ai, pai, sizeof(struct addrinfo));\ - (ai)->ai_addr = (struct sockaddr *)((ai) + 1);\ - memset((ai)->ai_addr, 0, (gai_afd)->a_socklen);\ - (ai)->ai_addrlen = (gai_afd)->a_socklen;\ - (ai)->ai_addr->sa_family = (ai)->ai_family = (gai_afd)->a_af;\ - ((struct sockinet *)(ai)->ai_addr)->si_port = port;\ - p = (char *)((ai)->ai_addr);\ - memcpy(p + (gai_afd)->a_off, (addr), (gai_afd)->a_addrlen);\ + char *p;\ + if (((ai) = (struct addrinfo *)malloc(sizeof(struct addrinfo) +\ + ((gai_afd)->a_socklen)))\ + == NULL) goto free;\ + memcpy(ai, pai, sizeof(struct addrinfo));\ + (ai)->ai_addr = (struct sockaddr *)((ai) + 1);\ + memset((ai)->ai_addr, 0, (gai_afd)->a_socklen);\ + (ai)->ai_addrlen = (gai_afd)->a_socklen;\ + (ai)->ai_addr->sa_family = (ai)->ai_family = (gai_afd)->a_af;\ + ((struct sockinet *)(ai)->ai_addr)->si_port = port;\ + p = (char *)((ai)->ai_addr);\ + memcpy(p + (gai_afd)->a_off, (addr), (gai_afd)->a_addrlen);\ } #endif @@ -201,438 +201,438 @@ char * gai_strerror(int ecode) { - if (ecode < 0 || ecode > EAI_MAX) - ecode = EAI_MAX; - return ai_errlist[ecode]; + if (ecode < 0 || ecode > EAI_MAX) + ecode = EAI_MAX; + return ai_errlist[ecode]; } void freeaddrinfo(struct addrinfo *ai) { - struct addrinfo *next; + struct addrinfo *next; - do { - next = ai->ai_next; - if (ai->ai_canonname) - free(ai->ai_canonname); - /* no need to free(ai->ai_addr) */ - free(ai); - } while ((ai = next) != NULL); + do { + next = ai->ai_next; + if (ai->ai_canonname) + free(ai->ai_canonname); + /* no need to free(ai->ai_addr) */ + free(ai); + } while ((ai = next) != NULL); } static int str_isnumber(const char *p) { - unsigned char *q = (unsigned char *)p; - while (*q) { - if (! isdigit(*q)) - return NO; - q++; - } - return YES; + unsigned char *q = (unsigned char *)p; + while (*q) { + if (! isdigit(*q)) + return NO; + q++; + } + return YES; } int getaddrinfo(const char*hostname, const char*servname, const struct addrinfo *hints, struct addrinfo **res) { - struct addrinfo sentinel; - struct addrinfo *top = NULL; - struct addrinfo *cur; - int i, error = 0; - char pton[PTON_MAX]; - struct addrinfo ai; - struct addrinfo *pai; - u_short port; + struct addrinfo sentinel; + struct addrinfo *top = NULL; + struct addrinfo *cur; + int i, error = 0; + char pton[PTON_MAX]; + struct addrinfo ai; + struct addrinfo *pai; + u_short port; #ifdef FAITH - static int firsttime = 1; + static int firsttime = 1; - if (firsttime) { - /* translator hack */ - { - char *q = getenv("GAI"); - if (q && inet_pton(AF_INET6, q, &faith_prefix) == 1) - translate = YES; - } - firsttime = 0; - } -#endif - - /* initialize file static vars */ - sentinel.ai_next = NULL; - cur = &sentinel; - pai = &ai; - pai->ai_flags = 0; - pai->ai_family = PF_UNSPEC; - pai->ai_socktype = GAI_ANY; - pai->ai_protocol = GAI_ANY; - pai->ai_addrlen = 0; - pai->ai_canonname = NULL; - pai->ai_addr = NULL; - pai->ai_next = NULL; - port = GAI_ANY; - - if (hostname == NULL && servname == NULL) - return EAI_NONAME; - if (hints) { - /* error check for hints */ - if (hints->ai_addrlen || hints->ai_canonname || - hints->ai_addr || hints->ai_next) - ERR(EAI_BADHINTS); /* xxx */ - if (hints->ai_flags & ~AI_MASK) - ERR(EAI_BADFLAGS); - switch (hints->ai_family) { - case PF_UNSPEC: - case PF_INET: -#ifdef ENABLE_IPV6 - case PF_INET6: -#endif - break; - default: - ERR(EAI_FAMILY); - } - memcpy(pai, hints, sizeof(*pai)); - switch (pai->ai_socktype) { - case GAI_ANY: - switch (pai->ai_protocol) { - case GAI_ANY: - break; - case IPPROTO_UDP: - pai->ai_socktype = SOCK_DGRAM; - break; - case IPPROTO_TCP: - pai->ai_socktype = SOCK_STREAM; - break; - default: - pai->ai_socktype = SOCK_RAW; - break; - } - break; - case SOCK_RAW: - break; - case SOCK_DGRAM: - if (pai->ai_protocol != IPPROTO_UDP && - pai->ai_protocol != GAI_ANY) - ERR(EAI_BADHINTS); /*xxx*/ - pai->ai_protocol = IPPROTO_UDP; - break; - case SOCK_STREAM: - if (pai->ai_protocol != IPPROTO_TCP && - pai->ai_protocol != GAI_ANY) - ERR(EAI_BADHINTS); /*xxx*/ - pai->ai_protocol = IPPROTO_TCP; - break; - default: - ERR(EAI_SOCKTYPE); - /* unreachable */ - } - } - - /* - * service port - */ - if (servname) { - if (str_isnumber(servname)) { - if (pai->ai_socktype == GAI_ANY) { - /* caller accept *GAI_ANY* socktype */ - pai->ai_socktype = SOCK_DGRAM; - pai->ai_protocol = IPPROTO_UDP; - } - port = htons((u_short)atoi(servname)); - } else { - struct servent *sp; - char *proto; - - proto = NULL; - switch (pai->ai_socktype) { - case GAI_ANY: - proto = NULL; - break; - case SOCK_DGRAM: - proto = "udp"; - break; - case SOCK_STREAM: - proto = "tcp"; - break; - default: - fprintf(stderr, "panic!\n"); - break; - } - if ((sp = getservbyname(servname, proto)) == NULL) - ERR(EAI_SERVICE); - port = sp->s_port; - if (pai->ai_socktype == GAI_ANY) { - if (strcmp(sp->s_proto, "udp") == 0) { - pai->ai_socktype = SOCK_DGRAM; - pai->ai_protocol = IPPROTO_UDP; - } else if (strcmp(sp->s_proto, "tcp") == 0) { - pai->ai_socktype = SOCK_STREAM; - pai->ai_protocol = IPPROTO_TCP; - } else - ERR(EAI_PROTOCOL); /*xxx*/ - } - } - } - - /* - * hostname == NULL. - * passive socket -> anyaddr (0.0.0.0 or ::) - * non-passive socket -> localhost (127.0.0.1 or ::1) - */ - if (hostname == NULL) { - struct gai_afd *gai_afd; - - for (gai_afd = &gai_afdl[0]; gai_afd->a_af; gai_afd++) { - if (!(pai->ai_family == PF_UNSPEC - || pai->ai_family == gai_afd->a_af)) { - continue; - } - - if (pai->ai_flags & AI_PASSIVE) { - GET_AI(cur->ai_next, gai_afd, gai_afd->a_addrany, port); - /* xxx meaningless? - * GET_CANONNAME(cur->ai_next, "anyaddr"); - */ - } else { - GET_AI(cur->ai_next, gai_afd, gai_afd->a_loopback, - port); - /* xxx meaningless? - * GET_CANONNAME(cur->ai_next, "localhost"); - */ - } - cur = cur->ai_next; - } - top = sentinel.ai_next; - if (top) - goto good; - else - ERR(EAI_FAMILY); - } - - /* hostname as numeric name */ - for (i = 0; gai_afdl[i].a_af; i++) { - if (inet_pton(gai_afdl[i].a_af, hostname, pton)) { - u_long v4a; -#ifdef ENABLE_IPV6 - u_char pfx; -#endif - - switch (gai_afdl[i].a_af) { - case AF_INET: - v4a = ((struct in_addr *)pton)->s_addr; - v4a = ntohl(v4a); - if (IN_MULTICAST(v4a) || IN_EXPERIMENTAL(v4a)) - pai->ai_flags &= ~AI_CANONNAME; - v4a >>= IN_CLASSA_NSHIFT; - if (v4a == 0 || v4a == IN_LOOPBACKNET) - pai->ai_flags &= ~AI_CANONNAME; - break; -#ifdef ENABLE_IPV6 - case AF_INET6: - pfx = ((struct in6_addr *)pton)->s6_addr8[0]; - if (pfx == 0 || pfx == 0xfe || pfx == 0xff) - pai->ai_flags &= ~AI_CANONNAME; - break; -#endif - } - - if (pai->ai_family == gai_afdl[i].a_af || - pai->ai_family == PF_UNSPEC) { - if (! (pai->ai_flags & AI_CANONNAME)) { - GET_AI(top, &gai_afdl[i], pton, port); - goto good; - } - /* - * if AI_CANONNAME and if reverse lookup - * fail, return ai anyway to pacify - * calling application. - * - * XXX getaddrinfo() is a name->address - * translation function, and it looks strange - * that we do addr->name translation here. - */ - get_name(pton, &gai_afdl[i], &top, pton, pai, port); - goto good; - } else - ERR(EAI_FAMILY); /*xxx*/ - } - } - - if (pai->ai_flags & AI_NUMERICHOST) - ERR(EAI_NONAME); - - /* hostname as alphabetical name */ - error = get_addr(hostname, pai->ai_family, &top, pai, port); - if (error == 0) { - if (top) { + if (firsttime) { + /* translator hack */ + { + char *q = getenv("GAI"); + if (q && inet_pton(AF_INET6, q, &faith_prefix) == 1) + translate = YES; + } + firsttime = 0; + } +#endif + + /* initialize file static vars */ + sentinel.ai_next = NULL; + cur = &sentinel; + pai = &ai; + pai->ai_flags = 0; + pai->ai_family = PF_UNSPEC; + pai->ai_socktype = GAI_ANY; + pai->ai_protocol = GAI_ANY; + pai->ai_addrlen = 0; + pai->ai_canonname = NULL; + pai->ai_addr = NULL; + pai->ai_next = NULL; + port = GAI_ANY; + + if (hostname == NULL && servname == NULL) + return EAI_NONAME; + if (hints) { + /* error check for hints */ + if (hints->ai_addrlen || hints->ai_canonname || + hints->ai_addr || hints->ai_next) + ERR(EAI_BADHINTS); /* xxx */ + if (hints->ai_flags & ~AI_MASK) + ERR(EAI_BADFLAGS); + switch (hints->ai_family) { + case PF_UNSPEC: + case PF_INET: +#ifdef ENABLE_IPV6 + case PF_INET6: +#endif + break; + default: + ERR(EAI_FAMILY); + } + memcpy(pai, hints, sizeof(*pai)); + switch (pai->ai_socktype) { + case GAI_ANY: + switch (pai->ai_protocol) { + case GAI_ANY: + break; + case IPPROTO_UDP: + pai->ai_socktype = SOCK_DGRAM; + break; + case IPPROTO_TCP: + pai->ai_socktype = SOCK_STREAM; + break; + default: + pai->ai_socktype = SOCK_RAW; + break; + } + break; + case SOCK_RAW: + break; + case SOCK_DGRAM: + if (pai->ai_protocol != IPPROTO_UDP && + pai->ai_protocol != GAI_ANY) + ERR(EAI_BADHINTS); /*xxx*/ + pai->ai_protocol = IPPROTO_UDP; + break; + case SOCK_STREAM: + if (pai->ai_protocol != IPPROTO_TCP && + pai->ai_protocol != GAI_ANY) + ERR(EAI_BADHINTS); /*xxx*/ + pai->ai_protocol = IPPROTO_TCP; + break; + default: + ERR(EAI_SOCKTYPE); + /* unreachable */ + } + } + + /* + * service port + */ + if (servname) { + if (str_isnumber(servname)) { + if (pai->ai_socktype == GAI_ANY) { + /* caller accept *GAI_ANY* socktype */ + pai->ai_socktype = SOCK_DGRAM; + pai->ai_protocol = IPPROTO_UDP; + } + port = htons((u_short)atoi(servname)); + } else { + struct servent *sp; + char *proto; + + proto = NULL; + switch (pai->ai_socktype) { + case GAI_ANY: + proto = NULL; + break; + case SOCK_DGRAM: + proto = "udp"; + break; + case SOCK_STREAM: + proto = "tcp"; + break; + default: + fprintf(stderr, "panic!\n"); + break; + } + if ((sp = getservbyname(servname, proto)) == NULL) + ERR(EAI_SERVICE); + port = sp->s_port; + if (pai->ai_socktype == GAI_ANY) { + if (strcmp(sp->s_proto, "udp") == 0) { + pai->ai_socktype = SOCK_DGRAM; + pai->ai_protocol = IPPROTO_UDP; + } else if (strcmp(sp->s_proto, "tcp") == 0) { + pai->ai_socktype = SOCK_STREAM; + pai->ai_protocol = IPPROTO_TCP; + } else + ERR(EAI_PROTOCOL); /*xxx*/ + } + } + } + + /* + * hostname == NULL. + * passive socket -> anyaddr (0.0.0.0 or ::) + * non-passive socket -> localhost (127.0.0.1 or ::1) + */ + if (hostname == NULL) { + struct gai_afd *gai_afd; + + for (gai_afd = &gai_afdl[0]; gai_afd->a_af; gai_afd++) { + if (!(pai->ai_family == PF_UNSPEC + || pai->ai_family == gai_afd->a_af)) { + continue; + } + + if (pai->ai_flags & AI_PASSIVE) { + GET_AI(cur->ai_next, gai_afd, gai_afd->a_addrany, port); + /* xxx meaningless? + * GET_CANONNAME(cur->ai_next, "anyaddr"); + */ + } else { + GET_AI(cur->ai_next, gai_afd, gai_afd->a_loopback, + port); + /* xxx meaningless? + * GET_CANONNAME(cur->ai_next, "localhost"); + */ + } + cur = cur->ai_next; + } + top = sentinel.ai_next; + if (top) + goto good; + else + ERR(EAI_FAMILY); + } + + /* hostname as numeric name */ + for (i = 0; gai_afdl[i].a_af; i++) { + if (inet_pton(gai_afdl[i].a_af, hostname, pton)) { + u_long v4a; +#ifdef ENABLE_IPV6 + u_char pfx; +#endif + + switch (gai_afdl[i].a_af) { + case AF_INET: + v4a = ((struct in_addr *)pton)->s_addr; + v4a = ntohl(v4a); + if (IN_MULTICAST(v4a) || IN_EXPERIMENTAL(v4a)) + pai->ai_flags &= ~AI_CANONNAME; + v4a >>= IN_CLASSA_NSHIFT; + if (v4a == 0 || v4a == IN_LOOPBACKNET) + pai->ai_flags &= ~AI_CANONNAME; + break; +#ifdef ENABLE_IPV6 + case AF_INET6: + pfx = ((struct in6_addr *)pton)->s6_addr8[0]; + if (pfx == 0 || pfx == 0xfe || pfx == 0xff) + pai->ai_flags &= ~AI_CANONNAME; + break; +#endif + } + + if (pai->ai_family == gai_afdl[i].a_af || + pai->ai_family == PF_UNSPEC) { + if (! (pai->ai_flags & AI_CANONNAME)) { + GET_AI(top, &gai_afdl[i], pton, port); + goto good; + } + /* + * if AI_CANONNAME and if reverse lookup + * fail, return ai anyway to pacify + * calling application. + * + * XXX getaddrinfo() is a name->address + * translation function, and it looks strange + * that we do addr->name translation here. + */ + get_name(pton, &gai_afdl[i], &top, pton, pai, port); + goto good; + } else + ERR(EAI_FAMILY); /*xxx*/ + } + } + + if (pai->ai_flags & AI_NUMERICHOST) + ERR(EAI_NONAME); + + /* hostname as alphabetical name */ + error = get_addr(hostname, pai->ai_family, &top, pai, port); + if (error == 0) { + if (top) { good: - *res = top; - return SUCCESS; - } else - error = EAI_FAIL; - } + *res = top; + return SUCCESS; + } else + error = EAI_FAIL; + } free: - if (top) - freeaddrinfo(top); + if (top) + freeaddrinfo(top); bad: - *res = NULL; - return error; + *res = NULL; + return error; } static int get_name(addr, gai_afd, res, numaddr, pai, port0) - const char *addr; - struct gai_afd *gai_afd; - struct addrinfo **res; - char *numaddr; - struct addrinfo *pai; - int port0; + const char *addr; + struct gai_afd *gai_afd; + struct addrinfo **res; + char *numaddr; + struct addrinfo *pai; + int port0; { - u_short port = port0 & 0xffff; - struct hostent *hp; - struct addrinfo *cur; - int error = 0; + u_short port = port0 & 0xffff; + struct hostent *hp; + struct addrinfo *cur; + int error = 0; #ifdef ENABLE_IPV6 - int h_error; + int h_error; #endif - + #ifdef ENABLE_IPV6 - hp = getipnodebyaddr(addr, gai_afd->a_addrlen, gai_afd->a_af, &h_error); + hp = getipnodebyaddr(addr, gai_afd->a_addrlen, gai_afd->a_af, &h_error); #else - hp = gethostbyaddr(addr, gai_afd->a_addrlen, AF_INET); + hp = gethostbyaddr(addr, gai_afd->a_addrlen, AF_INET); #endif - if (hp && hp->h_name && hp->h_name[0] && hp->h_addr_list[0]) { - GET_AI(cur, gai_afd, hp->h_addr_list[0], port); - GET_CANONNAME(cur, hp->h_name); - } else - GET_AI(cur, gai_afd, numaddr, port); - + if (hp && hp->h_name && hp->h_name[0] && hp->h_addr_list[0]) { + GET_AI(cur, gai_afd, hp->h_addr_list[0], port); + GET_CANONNAME(cur, hp->h_name); + } else + GET_AI(cur, gai_afd, numaddr, port); + #ifdef ENABLE_IPV6 - if (hp) - freehostent(hp); + if (hp) + freehostent(hp); #endif - *res = cur; - return SUCCESS; + *res = cur; + return SUCCESS; free: - if (cur) - freeaddrinfo(cur); + if (cur) + freeaddrinfo(cur); #ifdef ENABLE_IPV6 - if (hp) - freehostent(hp); + if (hp) + freehostent(hp); #endif /* bad: */ - *res = NULL; - return error; + *res = NULL; + return error; } static int get_addr(hostname, af, res, pai, port0) - const char *hostname; - int af; - struct addrinfo **res; - struct addrinfo *pai; - int port0; + const char *hostname; + int af; + struct addrinfo **res; + struct addrinfo *pai; + int port0; { - u_short port = port0 & 0xffff; - struct addrinfo sentinel; - struct hostent *hp; - struct addrinfo *top, *cur; - struct gai_afd *gai_afd; - int i, error = 0, h_error; - char *ap; - - top = NULL; - sentinel.ai_next = NULL; - cur = &sentinel; -#ifdef ENABLE_IPV6 - if (af == AF_UNSPEC) { - hp = getipnodebyname(hostname, AF_INET6, - AI_ADDRCONFIG|AI_ALL|AI_V4MAPPED, &h_error); - } else - hp = getipnodebyname(hostname, af, AI_ADDRCONFIG, &h_error); + u_short port = port0 & 0xffff; + struct addrinfo sentinel; + struct hostent *hp; + struct addrinfo *top, *cur; + struct gai_afd *gai_afd; + int i, error = 0, h_error; + char *ap; + + top = NULL; + sentinel.ai_next = NULL; + cur = &sentinel; +#ifdef ENABLE_IPV6 + if (af == AF_UNSPEC) { + hp = getipnodebyname(hostname, AF_INET6, + AI_ADDRCONFIG|AI_ALL|AI_V4MAPPED, &h_error); + } else + hp = getipnodebyname(hostname, af, AI_ADDRCONFIG, &h_error); #else - hp = gethostbyname(hostname); - h_error = h_errno; + hp = gethostbyname(hostname); + h_error = h_errno; #endif - if (hp == NULL) { - switch (h_error) { - case HOST_NOT_FOUND: - case NO_DATA: - error = EAI_NODATA; - break; - case TRY_AGAIN: - error = EAI_AGAIN; - break; - case NO_RECOVERY: - default: - error = EAI_FAIL; - break; - } - goto free; - } - - if ((hp->h_name == NULL) || (hp->h_name[0] == 0) || - (hp->h_addr_list[0] == NULL)) { - error = EAI_FAIL; - goto free; - } - - for (i = 0; (ap = hp->h_addr_list[i]) != NULL; i++) { - switch (af) { -#ifdef ENABLE_IPV6 - case AF_INET6: - gai_afd = &gai_afdl[N_INET6]; - break; + if (hp == NULL) { + switch (h_error) { + case HOST_NOT_FOUND: + case NO_DATA: + error = EAI_NODATA; + break; + case TRY_AGAIN: + error = EAI_AGAIN; + break; + case NO_RECOVERY: + default: + error = EAI_FAIL; + break; + } + goto free; + } + + if ((hp->h_name == NULL) || (hp->h_name[0] == 0) || + (hp->h_addr_list[0] == NULL)) { + error = EAI_FAIL; + goto free; + } + + for (i = 0; (ap = hp->h_addr_list[i]) != NULL; i++) { + switch (af) { +#ifdef ENABLE_IPV6 + case AF_INET6: + gai_afd = &gai_afdl[N_INET6]; + break; #endif #ifndef ENABLE_IPV6 - default: /* AF_UNSPEC */ + default: /* AF_UNSPEC */ #endif - case AF_INET: - gai_afd = &gai_afdl[N_INET]; - break; -#ifdef ENABLE_IPV6 - default: /* AF_UNSPEC */ - if (IN6_IS_ADDR_V4MAPPED((struct in6_addr *)ap)) { - ap += sizeof(struct in6_addr) - - sizeof(struct in_addr); - gai_afd = &gai_afdl[N_INET]; - } else - gai_afd = &gai_afdl[N_INET6]; - break; + case AF_INET: + gai_afd = &gai_afdl[N_INET]; + break; +#ifdef ENABLE_IPV6 + default: /* AF_UNSPEC */ + if (IN6_IS_ADDR_V4MAPPED((struct in6_addr *)ap)) { + ap += sizeof(struct in6_addr) - + sizeof(struct in_addr); + gai_afd = &gai_afdl[N_INET]; + } else + gai_afd = &gai_afdl[N_INET6]; + break; #endif - } + } #ifdef FAITH - if (translate && gai_afd->a_af == AF_INET) { - struct in6_addr *in6; + if (translate && gai_afd->a_af == AF_INET) { + struct in6_addr *in6; - GET_AI(cur->ai_next, &gai_afdl[N_INET6], ap, port); - in6 = &((struct sockaddr_in6 *)cur->ai_next->ai_addr)->sin6_addr; - memcpy(&in6->s6_addr32[0], &faith_prefix, - sizeof(struct in6_addr) - sizeof(struct in_addr)); - memcpy(&in6->s6_addr32[3], ap, sizeof(struct in_addr)); - } else + GET_AI(cur->ai_next, &gai_afdl[N_INET6], ap, port); + in6 = &((struct sockaddr_in6 *)cur->ai_next->ai_addr)->sin6_addr; + memcpy(&in6->s6_addr32[0], &faith_prefix, + sizeof(struct in6_addr) - sizeof(struct in_addr)); + memcpy(&in6->s6_addr32[3], ap, sizeof(struct in_addr)); + } else #endif /* FAITH */ - GET_AI(cur->ai_next, gai_afd, ap, port); - if (cur == &sentinel) { - top = cur->ai_next; - GET_CANONNAME(top, hp->h_name); - } - cur = cur->ai_next; - } + GET_AI(cur->ai_next, gai_afd, ap, port); + if (cur == &sentinel) { + top = cur->ai_next; + GET_CANONNAME(top, hp->h_name); + } + cur = cur->ai_next; + } #ifdef ENABLE_IPV6 - freehostent(hp); + freehostent(hp); #endif - *res = top; - return SUCCESS; + *res = top; + return SUCCESS; free: - if (top) - freeaddrinfo(top); + if (top) + freeaddrinfo(top); #ifdef ENABLE_IPV6 - if (hp) - freehostent(hp); + if (hp) + freehostent(hp); #endif /* bad: */ - *res = NULL; - return error; + *res = NULL; + return error; } Modified: python/branches/py3k/Modules/getbuildinfo.c ============================================================================== --- python/branches/py3k/Modules/getbuildinfo.c (original) +++ python/branches/py3k/Modules/getbuildinfo.c Sun May 9 17:52:27 2010 @@ -31,22 +31,22 @@ const char * Py_GetBuildInfo(void) { - static char buildinfo[50]; - const char *revision = Py_SubversionRevision(); - const char *sep = *revision ? ":" : ""; - const char *branch = Py_SubversionShortBranch(); - PyOS_snprintf(buildinfo, sizeof(buildinfo), - "%s%s%s, %.20s, %.9s", branch, sep, revision, - DATE, TIME); - return buildinfo; + static char buildinfo[50]; + const char *revision = Py_SubversionRevision(); + const char *sep = *revision ? ":" : ""; + const char *branch = Py_SubversionShortBranch(); + PyOS_snprintf(buildinfo, sizeof(buildinfo), + "%s%s%s, %.20s, %.9s", branch, sep, revision, + DATE, TIME); + return buildinfo; } const char * _Py_svnversion(void) { - /* the following string can be modified by subwcrev.exe */ - static const char svnversion[] = SVNVERSION; - if (svnversion[0] != '$') - return svnversion; /* it was interpolated, or passed on command line */ - return "Unversioned directory"; + /* the following string can be modified by subwcrev.exe */ + static const char svnversion[] = SVNVERSION; + if (svnversion[0] != '$') + return svnversion; /* it was interpolated, or passed on command line */ + return "Unversioned directory"; } Modified: python/branches/py3k/Modules/getnameinfo.c ============================================================================== --- python/branches/py3k/Modules/getnameinfo.c (original) +++ python/branches/py3k/Modules/getnameinfo.c Sun May 9 17:52:27 2010 @@ -1,7 +1,7 @@ /* * 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: @@ -13,7 +13,7 @@ * 3. Neither the name of the project nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. - * + * * THIS SOFTWARE IS PROVIDED BY THE PROJECT AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE @@ -53,162 +53,162 @@ #define NO 0 static struct gni_afd { - int a_af; - int a_addrlen; - int a_socklen; - int a_off; + int a_af; + int a_addrlen; + int a_socklen; + int a_off; } gni_afdl [] = { #ifdef ENABLE_IPV6 - {PF_INET6, sizeof(struct in6_addr), sizeof(struct sockaddr_in6), - offsetof(struct sockaddr_in6, sin6_addr)}, + {PF_INET6, sizeof(struct in6_addr), sizeof(struct sockaddr_in6), + offsetof(struct sockaddr_in6, sin6_addr)}, #endif - {PF_INET, sizeof(struct in_addr), sizeof(struct sockaddr_in), - offsetof(struct sockaddr_in, sin_addr)}, - {0, 0, 0}, + {PF_INET, sizeof(struct in_addr), sizeof(struct sockaddr_in), + offsetof(struct sockaddr_in, sin_addr)}, + {0, 0, 0}, }; struct gni_sockinet { - u_char si_len; - u_char si_family; - u_short si_port; + u_char si_len; + u_char si_family; + u_short si_port; }; -#define ENI_NOSOCKET 0 -#define ENI_NOSERVNAME 1 -#define ENI_NOHOSTNAME 2 -#define ENI_MEMORY 3 -#define ENI_SYSTEM 4 -#define ENI_FAMILY 5 -#define ENI_SALEN 6 +#define ENI_NOSOCKET 0 +#define ENI_NOSERVNAME 1 +#define ENI_NOHOSTNAME 2 +#define ENI_MEMORY 3 +#define ENI_SYSTEM 4 +#define ENI_FAMILY 5 +#define ENI_SALEN 6 /* forward declaration to make gcc happy */ int getnameinfo(const struct sockaddr *, size_t, char *, size_t, - char *, size_t, int); + char *, size_t, int); int getnameinfo(sa, salen, host, hostlen, serv, servlen, flags) - const struct sockaddr *sa; - size_t salen; - char *host; - size_t hostlen; - char *serv; - size_t servlen; - int flags; + const struct sockaddr *sa; + size_t salen; + char *host; + size_t hostlen; + char *serv; + size_t servlen; + int flags; { - struct gni_afd *gni_afd; - struct servent *sp; - struct hostent *hp; - u_short port; - int family, len, i; - char *addr, *p; - u_long v4a; -#ifdef ENABLE_IPV6 - u_char pfx; -#endif - int h_error; - char numserv[512]; - char numaddr[512]; + struct gni_afd *gni_afd; + struct servent *sp; + struct hostent *hp; + u_short port; + int family, len, i; + char *addr, *p; + u_long v4a; +#ifdef ENABLE_IPV6 + u_char pfx; +#endif + int h_error; + char numserv[512]; + char numaddr[512]; - if (sa == NULL) - return ENI_NOSOCKET; + if (sa == NULL) + return ENI_NOSOCKET; #ifdef HAVE_SOCKADDR_SA_LEN - len = sa->sa_len; - if (len != salen) return ENI_SALEN; + len = sa->sa_len; + if (len != salen) return ENI_SALEN; #else - len = salen; + len = salen; #endif - - family = sa->sa_family; - for (i = 0; gni_afdl[i].a_af; i++) - if (gni_afdl[i].a_af == family) { - gni_afd = &gni_afdl[i]; - goto found; - } - return ENI_FAMILY; - + + family = sa->sa_family; + for (i = 0; gni_afdl[i].a_af; i++) + if (gni_afdl[i].a_af == family) { + gni_afd = &gni_afdl[i]; + goto found; + } + return ENI_FAMILY; + found: - if (len != gni_afd->a_socklen) return ENI_SALEN; - - port = ((struct gni_sockinet *)sa)->si_port; /* network byte order */ - addr = (char *)sa + gni_afd->a_off; - - if (serv == NULL || servlen == 0) { - /* what we should do? */ - } else if (flags & NI_NUMERICSERV) { - sprintf(numserv, "%d", ntohs(port)); - if (strlen(numserv) > servlen) - return ENI_MEMORY; - strcpy(serv, numserv); - } else { - sp = getservbyport(port, (flags & NI_DGRAM) ? "udp" : "tcp"); - if (sp) { - if (strlen(sp->s_name) > servlen) - return ENI_MEMORY; - strcpy(serv, sp->s_name); - } else - return ENI_NOSERVNAME; - } - - switch (sa->sa_family) { - case AF_INET: - v4a = ((struct sockaddr_in *)sa)->sin_addr.s_addr; - if (IN_MULTICAST(v4a) || IN_EXPERIMENTAL(v4a)) - flags |= NI_NUMERICHOST; - v4a >>= IN_CLASSA_NSHIFT; - if (v4a == 0 || v4a == IN_LOOPBACKNET) - flags |= NI_NUMERICHOST; - break; -#ifdef ENABLE_IPV6 - case AF_INET6: - pfx = ((struct sockaddr_in6 *)sa)->sin6_addr.s6_addr8[0]; - if (pfx == 0 || pfx == 0xfe || pfx == 0xff) - flags |= NI_NUMERICHOST; - break; -#endif - } - if (host == NULL || hostlen == 0) { - /* what should we do? */ - } else if (flags & NI_NUMERICHOST) { - if (inet_ntop(gni_afd->a_af, addr, numaddr, sizeof(numaddr)) - == NULL) - return ENI_SYSTEM; - if (strlen(numaddr) > hostlen) - return ENI_MEMORY; - strcpy(host, numaddr); - } else { + if (len != gni_afd->a_socklen) return ENI_SALEN; + + port = ((struct gni_sockinet *)sa)->si_port; /* network byte order */ + addr = (char *)sa + gni_afd->a_off; + + if (serv == NULL || servlen == 0) { + /* what we should do? */ + } else if (flags & NI_NUMERICSERV) { + sprintf(numserv, "%d", ntohs(port)); + if (strlen(numserv) > servlen) + return ENI_MEMORY; + strcpy(serv, numserv); + } else { + sp = getservbyport(port, (flags & NI_DGRAM) ? "udp" : "tcp"); + if (sp) { + if (strlen(sp->s_name) > servlen) + return ENI_MEMORY; + strcpy(serv, sp->s_name); + } else + return ENI_NOSERVNAME; + } + + switch (sa->sa_family) { + case AF_INET: + v4a = ((struct sockaddr_in *)sa)->sin_addr.s_addr; + if (IN_MULTICAST(v4a) || IN_EXPERIMENTAL(v4a)) + flags |= NI_NUMERICHOST; + v4a >>= IN_CLASSA_NSHIFT; + if (v4a == 0 || v4a == IN_LOOPBACKNET) + flags |= NI_NUMERICHOST; + break; +#ifdef ENABLE_IPV6 + case AF_INET6: + pfx = ((struct sockaddr_in6 *)sa)->sin6_addr.s6_addr8[0]; + if (pfx == 0 || pfx == 0xfe || pfx == 0xff) + flags |= NI_NUMERICHOST; + break; +#endif + } + if (host == NULL || hostlen == 0) { + /* what should we do? */ + } else if (flags & NI_NUMERICHOST) { + if (inet_ntop(gni_afd->a_af, addr, numaddr, sizeof(numaddr)) + == NULL) + return ENI_SYSTEM; + if (strlen(numaddr) > hostlen) + return ENI_MEMORY; + strcpy(host, numaddr); + } else { #ifdef ENABLE_IPV6 - hp = getipnodebyaddr(addr, gni_afd->a_addrlen, gni_afd->a_af, &h_error); + hp = getipnodebyaddr(addr, gni_afd->a_addrlen, gni_afd->a_af, &h_error); #else - hp = gethostbyaddr(addr, gni_afd->a_addrlen, gni_afd->a_af); - h_error = h_errno; + hp = gethostbyaddr(addr, gni_afd->a_addrlen, gni_afd->a_af); + h_error = h_errno; #endif - if (hp) { - if (flags & NI_NOFQDN) { - p = strchr(hp->h_name, '.'); - if (p) *p = '\0'; - } - if (strlen(hp->h_name) > hostlen) { -#ifdef ENABLE_IPV6 - freehostent(hp); -#endif - return ENI_MEMORY; - } - strcpy(host, hp->h_name); -#ifdef ENABLE_IPV6 - freehostent(hp); -#endif - } else { - if (flags & NI_NAMEREQD) - return ENI_NOHOSTNAME; - if (inet_ntop(gni_afd->a_af, addr, numaddr, sizeof(numaddr)) - == NULL) - return ENI_NOHOSTNAME; - if (strlen(numaddr) > hostlen) - return ENI_MEMORY; - strcpy(host, numaddr); - } - } - return SUCCESS; + if (hp) { + if (flags & NI_NOFQDN) { + p = strchr(hp->h_name, '.'); + if (p) *p = '\0'; + } + if (strlen(hp->h_name) > hostlen) { +#ifdef ENABLE_IPV6 + freehostent(hp); +#endif + return ENI_MEMORY; + } + strcpy(host, hp->h_name); +#ifdef ENABLE_IPV6 + freehostent(hp); +#endif + } else { + if (flags & NI_NAMEREQD) + return ENI_NOHOSTNAME; + if (inet_ntop(gni_afd->a_af, addr, numaddr, sizeof(numaddr)) + == NULL) + return ENI_NOHOSTNAME; + if (strlen(numaddr) > hostlen) + return ENI_MEMORY; + strcpy(host, numaddr); + } + } + return SUCCESS; } Modified: python/branches/py3k/Modules/getpath.c ============================================================================== --- python/branches/py3k/Modules/getpath.c (original) +++ python/branches/py3k/Modules/getpath.c Sun May 9 17:52:27 2010 @@ -142,8 +142,8 @@ char fname[PATH_MAX]; size_t res = wcstombs(fname, path, sizeof(fname)); if (res == (size_t)-1) { - errno = EINVAL; - return -1; + errno = EINVAL; + return -1; } return stat(fname, buf); } @@ -155,17 +155,17 @@ { char fname[PATH_MAX]; if (getcwd(fname, PATH_MAX) == NULL) - return NULL; + return NULL; if (mbstowcs(buf, fname, size) >= size) { - errno = ERANGE; - return NULL; + errno = ERANGE; + return NULL; } return buf; } #endif #ifdef HAVE_READLINK -int +int _Py_wreadlink(const wchar_t *path, wchar_t *buf, size_t bufsiz) { char cbuf[PATH_MAX]; @@ -173,24 +173,24 @@ int res; size_t r1 = wcstombs(cpath, path, PATH_MAX); if (r1 == (size_t)-1 || r1 >= PATH_MAX) { - errno = EINVAL; - return -1; + errno = EINVAL; + return -1; } res = (int)readlink(cpath, cbuf, PATH_MAX); if (res == -1) - return -1; + return -1; if (res == PATH_MAX) { - errno = EINVAL; - return -1; + errno = EINVAL; + return -1; } cbuf[res] = '\0'; /* buf will be null terminated */ r1 = mbstowcs(buf, cbuf, bufsiz); if (r1 == -1) { - errno = EINVAL; - return -1; + errno = EINVAL; + return -1; } return (int)r1; - + } #endif @@ -279,7 +279,7 @@ buffer[n++] = SEP; } if (n > MAXPATHLEN) - Py_FatalError("buffer overflow in getpath.c's joinpath()"); + Py_FatalError("buffer overflow in getpath.c's joinpath()"); k = wcslen(stuff); if (n + k > MAXPATHLEN) k = MAXPATHLEN - n; @@ -457,25 +457,25 @@ #else unsigned long nsexeclength = MAXPATHLEN; #endif - char execpath[MAXPATHLEN+1]; + char execpath[MAXPATHLEN+1]; #endif if (_path) { - size_t r = mbstowcs(wpath, _path, MAXPATHLEN+1); - path = wpath; - if (r == (size_t)-1 || r > MAXPATHLEN) { - /* Could not convert PATH, or it's too long. */ - path = NULL; - } + size_t r = mbstowcs(wpath, _path, MAXPATHLEN+1); + path = wpath; + if (r == (size_t)-1 || r > MAXPATHLEN) { + /* Could not convert PATH, or it's too long. */ + path = NULL; + } } - /* If there is no slash in the argv0 path, then we have to - * assume python is on the user's $PATH, since there's no - * other way to find a directory to start the search from. If - * $PATH isn't exported, you lose. - */ - if (wcschr(prog, SEP)) - wcsncpy(progpath, prog, MAXPATHLEN); + /* If there is no slash in the argv0 path, then we have to + * assume python is on the user's $PATH, since there's no + * other way to find a directory to start the search from. If + * $PATH isn't exported, you lose. + */ + if (wcschr(prog, SEP)) + wcsncpy(progpath, prog, MAXPATHLEN); #ifdef __APPLE__ /* On Mac OS X, if a script uses an interpreter of the form * "#!/opt/python2.3/bin/python", the kernel only passes "python" @@ -487,52 +487,52 @@ * will fail if a relative path was used. but in that case, * absolutize() should help us out below */ - else if(0 == _NSGetExecutablePath(execpath, &nsexeclength) && execpath[0] == SEP) { - size_t r = mbstowcs(progpath, execpath, MAXPATHLEN+1); - if (r == (size_t)-1 || r > MAXPATHLEN) { - /* Could not convert execpath, or it's too long. */ - progpath[0] = '\0'; - } - } + else if(0 == _NSGetExecutablePath(execpath, &nsexeclength) && execpath[0] == SEP) { + size_t r = mbstowcs(progpath, execpath, MAXPATHLEN+1); + if (r == (size_t)-1 || r > MAXPATHLEN) { + /* Could not convert execpath, or it's too long. */ + progpath[0] = '\0'; + } + } #endif /* __APPLE__ */ - else if (path) { - while (1) { - wchar_t *delim = wcschr(path, DELIM); - - if (delim) { - size_t len = delim - path; - if (len > MAXPATHLEN) - len = MAXPATHLEN; - wcsncpy(progpath, path, len); - *(progpath + len) = '\0'; - } - else - wcsncpy(progpath, path, MAXPATHLEN); - - joinpath(progpath, prog); - if (isxfile(progpath)) - break; - - if (!delim) { - progpath[0] = L'\0'; - break; - } - path = delim + 1; - } - } - else - progpath[0] = '\0'; - if (progpath[0] != SEP && progpath[0] != '\0') - absolutize(progpath); - wcsncpy(argv0_path, progpath, MAXPATHLEN); - argv0_path[MAXPATHLEN] = '\0'; + else if (path) { + while (1) { + wchar_t *delim = wcschr(path, DELIM); + + if (delim) { + size_t len = delim - path; + if (len > MAXPATHLEN) + len = MAXPATHLEN; + wcsncpy(progpath, path, len); + *(progpath + len) = '\0'; + } + else + wcsncpy(progpath, path, MAXPATHLEN); + + joinpath(progpath, prog); + if (isxfile(progpath)) + break; + + if (!delim) { + progpath[0] = L'\0'; + break; + } + path = delim + 1; + } + } + else + progpath[0] = '\0'; + if (progpath[0] != SEP && progpath[0] != '\0') + absolutize(progpath); + wcsncpy(argv0_path, progpath, MAXPATHLEN); + argv0_path[MAXPATHLEN] = '\0'; #ifdef WITH_NEXT_FRAMEWORK - /* On Mac OS X we have a special case if we're running from a framework. - ** This is because the python home should be set relative to the library, - ** which is in the framework, not relative to the executable, which may - ** be outside of the framework. Except when we're in the build directory... - */ + /* On Mac OS X we have a special case if we're running from a framework. + ** This is because the python home should be set relative to the library, + ** which is in the framework, not relative to the executable, which may + ** be outside of the framework. Except when we're in the build directory... + */ pythonModule = NSModuleForSymbol(NSLookupAndBindSymbol("_Py_Initialize")); /* Use dylib functions to find out where the framework was loaded from */ buf = (wchar_t *)NSLibraryNameForModule(pythonModule); @@ -604,7 +604,7 @@ else wcsncpy(zip_path, L"" PREFIX, MAXPATHLEN); joinpath(zip_path, L"lib/python00.zip"); - bufsz = wcslen(zip_path); /* Replace "00" with version */ + bufsz = wcslen(zip_path); /* Replace "00" with version */ zip_path[bufsz - 6] = VERSION[0]; zip_path[bufsz - 5] = VERSION[2]; @@ -626,12 +626,12 @@ bufsz = 0; if (_rtpypath) { - size_t s = mbstowcs(rtpypath, _rtpypath, sizeof(rtpypath)/sizeof(wchar_t)); - if (s == (size_t)-1 || s >=sizeof(rtpypath)) - /* XXX deal with errors more gracefully */ - _rtpypath = NULL; - if (_rtpypath) - bufsz += wcslen(rtpypath) + 1; + size_t s = mbstowcs(rtpypath, _rtpypath, sizeof(rtpypath)/sizeof(wchar_t)); + if (s == (size_t)-1 || s >=sizeof(rtpypath)) + /* XXX deal with errors more gracefully */ + _rtpypath = NULL; + if (_rtpypath) + bufsz += wcslen(rtpypath) + 1; } prefixsz = wcslen(prefix) + 1; @@ -718,10 +718,10 @@ if (pfound > 0) { reduce(prefix); reduce(prefix); - /* The prefix is the root directory, but reduce() chopped - * off the "/". */ - if (!prefix[0]) - wcscpy(prefix, separator); + /* The prefix is the root directory, but reduce() chopped + * off the "/". */ + if (!prefix[0]) + wcscpy(prefix, separator); } else wcsncpy(prefix, L"" PREFIX, MAXPATHLEN); @@ -730,8 +730,8 @@ reduce(exec_prefix); reduce(exec_prefix); reduce(exec_prefix); - if (!exec_prefix[0]) - wcscpy(exec_prefix, separator); + if (!exec_prefix[0]) + wcscpy(exec_prefix, separator); } else wcsncpy(exec_prefix, L"" EXEC_PREFIX, MAXPATHLEN); Modified: python/branches/py3k/Modules/grpmodule.c ============================================================================== --- python/branches/py3k/Modules/grpmodule.c (original) +++ python/branches/py3k/Modules/grpmodule.c Sun May 9 17:52:27 2010 @@ -10,8 +10,8 @@ static PyStructSequence_Field struct_group_type_fields[] = { {"gr_name", "group name"}, {"gr_passwd", "password"}, - {"gr_gid", "group id"}, - {"gr_mem", "group memebers"}, + {"gr_gid", "group id"}, + {"gr_mem", "group memebers"}, {0} }; @@ -64,10 +64,10 @@ Py_INCREF(Py_None); #else if (p->gr_passwd) - SET(setIndex++, PyUnicode_DecodeFSDefault(p->gr_passwd)); + SET(setIndex++, PyUnicode_DecodeFSDefault(p->gr_passwd)); else { - SET(setIndex++, Py_None); - Py_INCREF(Py_None); + SET(setIndex++, Py_None); + Py_INCREF(Py_None); } #endif SET(setIndex++, PyLong_FromLong((long) p->gr_gid)); @@ -91,12 +91,12 @@ py_int_id = PyNumber_Long(pyo_id); if (!py_int_id) - return NULL; + return NULL; gid = PyLong_AS_LONG(py_int_id); Py_DECREF(py_int_id); if ((p = getgrgid(gid)) == NULL) { - PyErr_Format(PyExc_KeyError, "getgrgid(): gid not found: %d", gid); + PyErr_Format(PyExc_KeyError, "getgrgid(): gid not found: %d", gid); return NULL; } return mkgrent(p); @@ -116,9 +116,9 @@ return NULL; if (PyBytes_AsStringAndSize(bytes, &name, NULL) == -1) goto out; - + if ((p = getgrnam(name)) == NULL) { - PyErr_Format(PyExc_KeyError, "getgrnam(): name not found: %s", name); + PyErr_Format(PyExc_KeyError, "getgrnam(): name not found: %s", name); goto out; } retval = mkgrent(p); @@ -151,18 +151,18 @@ } static PyMethodDef grp_methods[] = { - {"getgrgid", grp_getgrgid, METH_O, + {"getgrgid", grp_getgrgid, METH_O, "getgrgid(id) -> tuple\n\ Return the group database entry for the given numeric group ID. If\n\ id is not valid, raise KeyError."}, - {"getgrnam", grp_getgrnam, METH_VARARGS, + {"getgrnam", grp_getgrnam, METH_VARARGS, "getgrnam(name) -> tuple\n\ Return the group database entry for the given group name. If\n\ name is not valid, raise KeyError."}, - {"getgrall", grp_getgrall, METH_NOARGS, + {"getgrall", grp_getgrall, METH_NOARGS, "getgrall() -> list of tuples\n\ Return a list of all available group entries, in arbitrary order."}, - {NULL, NULL} /* sentinel */ + {NULL, NULL} /* sentinel */ }; PyDoc_STRVAR(grp__doc__, @@ -184,15 +184,15 @@ static struct PyModuleDef grpmodule = { - PyModuleDef_HEAD_INIT, - "grp", - grp__doc__, - -1, - grp_methods, - NULL, - NULL, - NULL, - NULL + PyModuleDef_HEAD_INIT, + "grp", + grp__doc__, + -1, + grp_methods, + NULL, + NULL, + NULL, + NULL }; PyMODINIT_FUNC @@ -204,7 +204,7 @@ return NULL; d = PyModule_GetDict(m); if (!initialized) - PyStructSequence_InitType(&StructGrpType, &struct_group_type_desc); + PyStructSequence_InitType(&StructGrpType, &struct_group_type_desc); PyDict_SetItemString(d, "struct_group", (PyObject *) &StructGrpType); initialized = 1; return m; Modified: python/branches/py3k/Modules/itertoolsmodule.c ============================================================================== --- python/branches/py3k/Modules/itertoolsmodule.c (original) +++ python/branches/py3k/Modules/itertoolsmodule.c Sun May 9 17:52:27 2010 @@ -2,7 +2,7 @@ #include "Python.h" #include "structmember.h" -/* Itertools module written and maintained +/* Itertools module written and maintained by Raymond D. Hettinger Copyright (c) 2003 Python Software Foundation. All rights reserved. @@ -12,12 +12,12 @@ /* groupby object ***********************************************************/ typedef struct { - PyObject_HEAD - PyObject *it; - PyObject *keyfunc; - PyObject *tgtkey; - PyObject *currkey; - PyObject *currvalue; + PyObject_HEAD + PyObject *it; + PyObject *keyfunc; + PyObject *tgtkey; + PyObject *currkey; + PyObject *currvalue; } groupbyobject; static PyTypeObject groupby_type; @@ -26,112 +26,112 @@ static PyObject * groupby_new(PyTypeObject *type, PyObject *args, PyObject *kwds) { - static char *kwargs[] = {"iterable", "key", NULL}; - groupbyobject *gbo; - PyObject *it, *keyfunc = Py_None; - - if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|O:groupby", kwargs, - &it, &keyfunc)) - return NULL; - - gbo = (groupbyobject *)type->tp_alloc(type, 0); - if (gbo == NULL) - return NULL; - gbo->tgtkey = NULL; - gbo->currkey = NULL; - gbo->currvalue = NULL; - gbo->keyfunc = keyfunc; - Py_INCREF(keyfunc); - gbo->it = PyObject_GetIter(it); - if (gbo->it == NULL) { - Py_DECREF(gbo); - return NULL; - } - return (PyObject *)gbo; + static char *kwargs[] = {"iterable", "key", NULL}; + groupbyobject *gbo; + PyObject *it, *keyfunc = Py_None; + + if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|O:groupby", kwargs, + &it, &keyfunc)) + return NULL; + + gbo = (groupbyobject *)type->tp_alloc(type, 0); + if (gbo == NULL) + return NULL; + gbo->tgtkey = NULL; + gbo->currkey = NULL; + gbo->currvalue = NULL; + gbo->keyfunc = keyfunc; + Py_INCREF(keyfunc); + gbo->it = PyObject_GetIter(it); + if (gbo->it == NULL) { + Py_DECREF(gbo); + return NULL; + } + return (PyObject *)gbo; } static void groupby_dealloc(groupbyobject *gbo) { - PyObject_GC_UnTrack(gbo); - Py_XDECREF(gbo->it); - Py_XDECREF(gbo->keyfunc); - Py_XDECREF(gbo->tgtkey); - Py_XDECREF(gbo->currkey); - Py_XDECREF(gbo->currvalue); - Py_TYPE(gbo)->tp_free(gbo); + PyObject_GC_UnTrack(gbo); + Py_XDECREF(gbo->it); + Py_XDECREF(gbo->keyfunc); + Py_XDECREF(gbo->tgtkey); + Py_XDECREF(gbo->currkey); + Py_XDECREF(gbo->currvalue); + Py_TYPE(gbo)->tp_free(gbo); } static int groupby_traverse(groupbyobject *gbo, visitproc visit, void *arg) { - Py_VISIT(gbo->it); - Py_VISIT(gbo->keyfunc); - Py_VISIT(gbo->tgtkey); - Py_VISIT(gbo->currkey); - Py_VISIT(gbo->currvalue); - return 0; + Py_VISIT(gbo->it); + Py_VISIT(gbo->keyfunc); + Py_VISIT(gbo->tgtkey); + Py_VISIT(gbo->currkey); + Py_VISIT(gbo->currvalue); + return 0; } static PyObject * groupby_next(groupbyobject *gbo) { - PyObject *newvalue, *newkey, *r, *grouper, *tmp; + PyObject *newvalue, *newkey, *r, *grouper, *tmp; - /* skip to next iteration group */ - for (;;) { - if (gbo->currkey == NULL) - /* pass */; - else if (gbo->tgtkey == NULL) - break; - else { - int rcmp; - - rcmp = PyObject_RichCompareBool(gbo->tgtkey, - gbo->currkey, Py_EQ); - if (rcmp == -1) - return NULL; - else if (rcmp == 0) - break; - } - - newvalue = PyIter_Next(gbo->it); - if (newvalue == NULL) - return NULL; - - if (gbo->keyfunc == Py_None) { - newkey = newvalue; - Py_INCREF(newvalue); - } else { - newkey = PyObject_CallFunctionObjArgs(gbo->keyfunc, - newvalue, NULL); - if (newkey == NULL) { - Py_DECREF(newvalue); - return NULL; - } - } - - tmp = gbo->currkey; - gbo->currkey = newkey; - Py_XDECREF(tmp); - - tmp = gbo->currvalue; - gbo->currvalue = newvalue; - Py_XDECREF(tmp); - } - - Py_INCREF(gbo->currkey); - tmp = gbo->tgtkey; - gbo->tgtkey = gbo->currkey; - Py_XDECREF(tmp); - - grouper = _grouper_create(gbo, gbo->tgtkey); - if (grouper == NULL) - return NULL; - - r = PyTuple_Pack(2, gbo->currkey, grouper); - Py_DECREF(grouper); - return r; + /* skip to next iteration group */ + for (;;) { + if (gbo->currkey == NULL) + /* pass */; + else if (gbo->tgtkey == NULL) + break; + else { + int rcmp; + + rcmp = PyObject_RichCompareBool(gbo->tgtkey, + gbo->currkey, Py_EQ); + if (rcmp == -1) + return NULL; + else if (rcmp == 0) + break; + } + + newvalue = PyIter_Next(gbo->it); + if (newvalue == NULL) + return NULL; + + if (gbo->keyfunc == Py_None) { + newkey = newvalue; + Py_INCREF(newvalue); + } else { + newkey = PyObject_CallFunctionObjArgs(gbo->keyfunc, + newvalue, NULL); + if (newkey == NULL) { + Py_DECREF(newvalue); + return NULL; + } + } + + tmp = gbo->currkey; + gbo->currkey = newkey; + Py_XDECREF(tmp); + + tmp = gbo->currvalue; + gbo->currvalue = newvalue; + Py_XDECREF(tmp); + } + + Py_INCREF(gbo->currkey); + tmp = gbo->tgtkey; + gbo->tgtkey = gbo->currkey; + Py_XDECREF(tmp); + + grouper = _grouper_create(gbo, gbo->tgtkey); + if (grouper == NULL) + return NULL; + + r = PyTuple_Pack(2, gbo->currkey, grouper); + Py_DECREF(grouper); + return r; } PyDoc_STRVAR(groupby_doc, @@ -139,56 +139,56 @@ (key, sub-iterator) grouped by each value of key(value).\n"); static PyTypeObject groupby_type = { - PyVarObject_HEAD_INIT(NULL, 0) - "itertools.groupby", /* tp_name */ - sizeof(groupbyobject), /* tp_basicsize */ - 0, /* tp_itemsize */ - /* methods */ - (destructor)groupby_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 | - Py_TPFLAGS_BASETYPE, /* tp_flags */ - groupby_doc, /* tp_doc */ - (traverseproc)groupby_traverse, /* tp_traverse */ - 0, /* tp_clear */ - 0, /* tp_richcompare */ - 0, /* tp_weaklistoffset */ - PyObject_SelfIter, /* tp_iter */ - (iternextfunc)groupby_next, /* tp_iternext */ - 0, /* tp_methods */ - 0, /* tp_members */ - 0, /* tp_getset */ - 0, /* tp_base */ - 0, /* tp_dict */ - 0, /* tp_descr_get */ - 0, /* tp_descr_set */ - 0, /* tp_dictoffset */ - 0, /* tp_init */ - 0, /* tp_alloc */ - groupby_new, /* tp_new */ - PyObject_GC_Del, /* tp_free */ + PyVarObject_HEAD_INIT(NULL, 0) + "itertools.groupby", /* tp_name */ + sizeof(groupbyobject), /* tp_basicsize */ + 0, /* tp_itemsize */ + /* methods */ + (destructor)groupby_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 | + Py_TPFLAGS_BASETYPE, /* tp_flags */ + groupby_doc, /* tp_doc */ + (traverseproc)groupby_traverse, /* tp_traverse */ + 0, /* tp_clear */ + 0, /* tp_richcompare */ + 0, /* tp_weaklistoffset */ + PyObject_SelfIter, /* tp_iter */ + (iternextfunc)groupby_next, /* tp_iternext */ + 0, /* tp_methods */ + 0, /* tp_members */ + 0, /* tp_getset */ + 0, /* tp_base */ + 0, /* tp_dict */ + 0, /* tp_descr_get */ + 0, /* tp_descr_set */ + 0, /* tp_dictoffset */ + 0, /* tp_init */ + 0, /* tp_alloc */ + groupby_new, /* tp_new */ + PyObject_GC_Del, /* tp_free */ }; /* _grouper object (internal) ************************************************/ typedef struct { - PyObject_HEAD - PyObject *parent; - PyObject *tgtkey; + PyObject_HEAD + PyObject *parent; + PyObject *tgtkey; } _grouperobject; static PyTypeObject _grouper_type; @@ -196,129 +196,129 @@ static PyObject * _grouper_create(groupbyobject *parent, PyObject *tgtkey) { - _grouperobject *igo; + _grouperobject *igo; - igo = PyObject_GC_New(_grouperobject, &_grouper_type); - if (igo == NULL) - return NULL; - igo->parent = (PyObject *)parent; - Py_INCREF(parent); - igo->tgtkey = tgtkey; - Py_INCREF(tgtkey); + igo = PyObject_GC_New(_grouperobject, &_grouper_type); + if (igo == NULL) + return NULL; + igo->parent = (PyObject *)parent; + Py_INCREF(parent); + igo->tgtkey = tgtkey; + Py_INCREF(tgtkey); - PyObject_GC_Track(igo); - return (PyObject *)igo; + PyObject_GC_Track(igo); + return (PyObject *)igo; } static void _grouper_dealloc(_grouperobject *igo) { - PyObject_GC_UnTrack(igo); - Py_DECREF(igo->parent); - Py_DECREF(igo->tgtkey); - PyObject_GC_Del(igo); + PyObject_GC_UnTrack(igo); + Py_DECREF(igo->parent); + Py_DECREF(igo->tgtkey); + PyObject_GC_Del(igo); } static int _grouper_traverse(_grouperobject *igo, visitproc visit, void *arg) { - Py_VISIT(igo->parent); - Py_VISIT(igo->tgtkey); - return 0; + Py_VISIT(igo->parent); + Py_VISIT(igo->tgtkey); + return 0; } static PyObject * _grouper_next(_grouperobject *igo) { - groupbyobject *gbo = (groupbyobject *)igo->parent; - PyObject *newvalue, *newkey, *r; - int rcmp; - - if (gbo->currvalue == NULL) { - newvalue = PyIter_Next(gbo->it); - if (newvalue == NULL) - return NULL; - - if (gbo->keyfunc == Py_None) { - newkey = newvalue; - Py_INCREF(newvalue); - } else { - newkey = PyObject_CallFunctionObjArgs(gbo->keyfunc, - newvalue, NULL); - if (newkey == NULL) { - Py_DECREF(newvalue); - return NULL; - } - } - - assert(gbo->currkey == NULL); - gbo->currkey = newkey; - gbo->currvalue = newvalue; - } - - assert(gbo->currkey != NULL); - rcmp = PyObject_RichCompareBool(igo->tgtkey, gbo->currkey, Py_EQ); - if (rcmp <= 0) - /* got any error or current group is end */ - return NULL; - - r = gbo->currvalue; - gbo->currvalue = NULL; - Py_CLEAR(gbo->currkey); + groupbyobject *gbo = (groupbyobject *)igo->parent; + PyObject *newvalue, *newkey, *r; + int rcmp; + + if (gbo->currvalue == NULL) { + newvalue = PyIter_Next(gbo->it); + if (newvalue == NULL) + return NULL; + + if (gbo->keyfunc == Py_None) { + newkey = newvalue; + Py_INCREF(newvalue); + } else { + newkey = PyObject_CallFunctionObjArgs(gbo->keyfunc, + newvalue, NULL); + if (newkey == NULL) { + Py_DECREF(newvalue); + return NULL; + } + } + + assert(gbo->currkey == NULL); + gbo->currkey = newkey; + gbo->currvalue = newvalue; + } + + assert(gbo->currkey != NULL); + rcmp = PyObject_RichCompareBool(igo->tgtkey, gbo->currkey, Py_EQ); + if (rcmp <= 0) + /* got any error or current group is end */ + return NULL; + + r = gbo->currvalue; + gbo->currvalue = NULL; + Py_CLEAR(gbo->currkey); - return r; + return r; } static PyTypeObject _grouper_type = { - PyVarObject_HEAD_INIT(NULL, 0) - "itertools._grouper", /* tp_name */ - sizeof(_grouperobject), /* tp_basicsize */ - 0, /* tp_itemsize */ - /* methods */ - (destructor)_grouper_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)_grouper_traverse,/* tp_traverse */ - 0, /* tp_clear */ - 0, /* tp_richcompare */ - 0, /* tp_weaklistoffset */ - PyObject_SelfIter, /* tp_iter */ - (iternextfunc)_grouper_next, /* tp_iternext */ - 0, /* tp_methods */ - 0, /* tp_members */ - 0, /* tp_getset */ - 0, /* tp_base */ - 0, /* tp_dict */ - 0, /* tp_descr_get */ - 0, /* tp_descr_set */ - 0, /* tp_dictoffset */ - 0, /* tp_init */ - 0, /* tp_alloc */ - 0, /* tp_new */ - PyObject_GC_Del, /* tp_free */ + PyVarObject_HEAD_INIT(NULL, 0) + "itertools._grouper", /* tp_name */ + sizeof(_grouperobject), /* tp_basicsize */ + 0, /* tp_itemsize */ + /* methods */ + (destructor)_grouper_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)_grouper_traverse,/* tp_traverse */ + 0, /* tp_clear */ + 0, /* tp_richcompare */ + 0, /* tp_weaklistoffset */ + PyObject_SelfIter, /* tp_iter */ + (iternextfunc)_grouper_next, /* tp_iternext */ + 0, /* tp_methods */ + 0, /* tp_members */ + 0, /* tp_getset */ + 0, /* tp_base */ + 0, /* tp_dict */ + 0, /* tp_descr_get */ + 0, /* tp_descr_set */ + 0, /* tp_dictoffset */ + 0, /* tp_init */ + 0, /* tp_alloc */ + 0, /* tp_new */ + PyObject_GC_Del, /* tp_free */ }; - + /* tee object and with supporting function and objects ***************/ /* The teedataobject pre-allocates space for LINKCELLS number of objects. To help the object fit neatly inside cache lines (space for 16 to 32 - pointers), the value should be a multiple of 16 minus space for + pointers), the value should be a multiple of 16 minus space for the other structure members including PyHEAD overhead. The larger the value, the less memory overhead per object and the less time spent allocating/deallocating new links. The smaller the number, the less @@ -327,18 +327,18 @@ #define LINKCELLS 57 typedef struct { - PyObject_HEAD - PyObject *it; - int numread; - PyObject *nextlink; - PyObject *(values[LINKCELLS]); + PyObject_HEAD + PyObject *it; + int numread; + PyObject *nextlink; + PyObject *(values[LINKCELLS]); } teedataobject; typedef struct { - PyObject_HEAD - teedataobject *dataobj; - int index; - PyObject *weakreflist; + PyObject_HEAD + teedataobject *dataobj; + int index; + PyObject *weakreflist; } teeobject; static PyTypeObject teedataobject_type; @@ -346,123 +346,123 @@ static PyObject * teedataobject_new(PyObject *it) { - teedataobject *tdo; + teedataobject *tdo; - tdo = PyObject_GC_New(teedataobject, &teedataobject_type); - if (tdo == NULL) - return NULL; - - tdo->numread = 0; - tdo->nextlink = NULL; - Py_INCREF(it); - tdo->it = it; - PyObject_GC_Track(tdo); - return (PyObject *)tdo; + tdo = PyObject_GC_New(teedataobject, &teedataobject_type); + if (tdo == NULL) + return NULL; + + tdo->numread = 0; + tdo->nextlink = NULL; + Py_INCREF(it); + tdo->it = it; + PyObject_GC_Track(tdo); + return (PyObject *)tdo; } static PyObject * teedataobject_jumplink(teedataobject *tdo) { - if (tdo->nextlink == NULL) - tdo->nextlink = teedataobject_new(tdo->it); - Py_XINCREF(tdo->nextlink); - return tdo->nextlink; + if (tdo->nextlink == NULL) + tdo->nextlink = teedataobject_new(tdo->it); + Py_XINCREF(tdo->nextlink); + return tdo->nextlink; } static PyObject * teedataobject_getitem(teedataobject *tdo, int i) { - PyObject *value; + PyObject *value; - assert(i < LINKCELLS); - if (i < tdo->numread) - value = tdo->values[i]; - else { - /* this is the lead iterator, so fetch more data */ - assert(i == tdo->numread); - value = PyIter_Next(tdo->it); - if (value == NULL) - return NULL; - tdo->numread++; - tdo->values[i] = value; - } - Py_INCREF(value); - return value; + assert(i < LINKCELLS); + if (i < tdo->numread) + value = tdo->values[i]; + else { + /* this is the lead iterator, so fetch more data */ + assert(i == tdo->numread); + value = PyIter_Next(tdo->it); + if (value == NULL) + return NULL; + tdo->numread++; + tdo->values[i] = value; + } + Py_INCREF(value); + return value; } static int teedataobject_traverse(teedataobject *tdo, visitproc visit, void * arg) { - int i; - Py_VISIT(tdo->it); - for (i = 0; i < tdo->numread; i++) - Py_VISIT(tdo->values[i]); - Py_VISIT(tdo->nextlink); - return 0; + int i; + Py_VISIT(tdo->it); + for (i = 0; i < tdo->numread; i++) + Py_VISIT(tdo->values[i]); + Py_VISIT(tdo->nextlink); + return 0; } static int teedataobject_clear(teedataobject *tdo) { - int i; - Py_CLEAR(tdo->it); - for (i=0 ; inumread ; i++) - Py_CLEAR(tdo->values[i]); - Py_CLEAR(tdo->nextlink); - return 0; + int i; + Py_CLEAR(tdo->it); + for (i=0 ; inumread ; i++) + Py_CLEAR(tdo->values[i]); + Py_CLEAR(tdo->nextlink); + return 0; } static void teedataobject_dealloc(teedataobject *tdo) { - PyObject_GC_UnTrack(tdo); - teedataobject_clear(tdo); - PyObject_GC_Del(tdo); + PyObject_GC_UnTrack(tdo); + teedataobject_clear(tdo); + PyObject_GC_Del(tdo); } PyDoc_STRVAR(teedataobject_doc, "Data container common to multiple tee objects."); static PyTypeObject teedataobject_type = { - PyVarObject_HEAD_INIT(0, 0) /* Must fill in type value later */ - "itertools.tee_dataobject", /* tp_name */ - sizeof(teedataobject), /* tp_basicsize */ - 0, /* tp_itemsize */ - /* methods */ - (destructor)teedataobject_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 */ - teedataobject_doc, /* tp_doc */ - (traverseproc)teedataobject_traverse, /* tp_traverse */ - (inquiry)teedataobject_clear, /* tp_clear */ - 0, /* tp_richcompare */ - 0, /* tp_weaklistoffset */ - 0, /* tp_iter */ - 0, /* tp_iternext */ - 0, /* tp_methods */ - 0, /* tp_members */ - 0, /* tp_getset */ - 0, /* tp_base */ - 0, /* tp_dict */ - 0, /* tp_descr_get */ - 0, /* tp_descr_set */ - 0, /* tp_dictoffset */ - 0, /* tp_init */ - 0, /* tp_alloc */ - 0, /* tp_new */ - PyObject_GC_Del, /* tp_free */ + PyVarObject_HEAD_INIT(0, 0) /* Must fill in type value later */ + "itertools.tee_dataobject", /* tp_name */ + sizeof(teedataobject), /* tp_basicsize */ + 0, /* tp_itemsize */ + /* methods */ + (destructor)teedataobject_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 */ + teedataobject_doc, /* tp_doc */ + (traverseproc)teedataobject_traverse, /* tp_traverse */ + (inquiry)teedataobject_clear, /* tp_clear */ + 0, /* tp_richcompare */ + 0, /* tp_weaklistoffset */ + 0, /* tp_iter */ + 0, /* tp_iternext */ + 0, /* tp_methods */ + 0, /* tp_members */ + 0, /* tp_getset */ + 0, /* tp_base */ + 0, /* tp_dict */ + 0, /* tp_descr_get */ + 0, /* tp_descr_set */ + 0, /* tp_dictoffset */ + 0, /* tp_init */ + 0, /* tp_alloc */ + 0, /* tp_new */ + PyObject_GC_Del, /* tp_free */ }; @@ -471,42 +471,42 @@ static PyObject * tee_next(teeobject *to) { - PyObject *value, *link; + PyObject *value, *link; - if (to->index >= LINKCELLS) { - link = teedataobject_jumplink(to->dataobj); - Py_DECREF(to->dataobj); - to->dataobj = (teedataobject *)link; - to->index = 0; - } - value = teedataobject_getitem(to->dataobj, to->index); - if (value == NULL) - return NULL; - to->index++; - return value; + if (to->index >= LINKCELLS) { + link = teedataobject_jumplink(to->dataobj); + Py_DECREF(to->dataobj); + to->dataobj = (teedataobject *)link; + to->index = 0; + } + value = teedataobject_getitem(to->dataobj, to->index); + if (value == NULL) + return NULL; + to->index++; + return value; } static int tee_traverse(teeobject *to, visitproc visit, void *arg) { - Py_VISIT((PyObject *)to->dataobj); - return 0; + Py_VISIT((PyObject *)to->dataobj); + return 0; } static PyObject * tee_copy(teeobject *to) { - teeobject *newto; + teeobject *newto; - newto = PyObject_GC_New(teeobject, &tee_type); - if (newto == NULL) - return NULL; - Py_INCREF(to->dataobj); - newto->dataobj = to->dataobj; - newto->index = to->index; - newto->weakreflist = NULL; - PyObject_GC_Track(newto); - return (PyObject *)newto; + newto = PyObject_GC_New(teeobject, &tee_type); + if (newto == NULL) + return NULL; + Py_INCREF(to->dataobj); + newto->dataobj = to->dataobj; + newto->index = to->index; + newto->weakreflist = NULL; + PyObject_GC_Track(newto); + return (PyObject *)newto; } PyDoc_STRVAR(teecopy_doc, "Returns an independent iterator."); @@ -514,154 +514,154 @@ static PyObject * tee_fromiterable(PyObject *iterable) { - teeobject *to; - PyObject *it = NULL; + teeobject *to; + PyObject *it = NULL; - it = PyObject_GetIter(iterable); - if (it == NULL) - return NULL; - if (PyObject_TypeCheck(it, &tee_type)) { - to = (teeobject *)tee_copy((teeobject *)it); - goto done; - } - - to = PyObject_GC_New(teeobject, &tee_type); - if (to == NULL) - goto done; - to->dataobj = (teedataobject *)teedataobject_new(it); - if (!to->dataobj) { - PyObject_GC_Del(to); - to = NULL; - goto done; - } - - to->index = 0; - to->weakreflist = NULL; - PyObject_GC_Track(to); + it = PyObject_GetIter(iterable); + if (it == NULL) + return NULL; + if (PyObject_TypeCheck(it, &tee_type)) { + to = (teeobject *)tee_copy((teeobject *)it); + goto done; + } + + to = PyObject_GC_New(teeobject, &tee_type); + if (to == NULL) + goto done; + to->dataobj = (teedataobject *)teedataobject_new(it); + if (!to->dataobj) { + PyObject_GC_Del(to); + to = NULL; + goto done; + } + + to->index = 0; + to->weakreflist = NULL; + PyObject_GC_Track(to); done: - Py_XDECREF(it); - return (PyObject *)to; + Py_XDECREF(it); + return (PyObject *)to; } static PyObject * tee_new(PyTypeObject *type, PyObject *args, PyObject *kw) { - PyObject *iterable; + PyObject *iterable; - if (!PyArg_UnpackTuple(args, "tee", 1, 1, &iterable)) - return NULL; - return tee_fromiterable(iterable); + if (!PyArg_UnpackTuple(args, "tee", 1, 1, &iterable)) + return NULL; + return tee_fromiterable(iterable); } static int tee_clear(teeobject *to) { - if (to->weakreflist != NULL) - PyObject_ClearWeakRefs((PyObject *) to); - Py_CLEAR(to->dataobj); - return 0; + if (to->weakreflist != NULL) + PyObject_ClearWeakRefs((PyObject *) to); + Py_CLEAR(to->dataobj); + return 0; } static void tee_dealloc(teeobject *to) { - PyObject_GC_UnTrack(to); - tee_clear(to); - PyObject_GC_Del(to); + PyObject_GC_UnTrack(to); + tee_clear(to); + PyObject_GC_Del(to); } PyDoc_STRVAR(teeobject_doc, "Iterator wrapped to make it copyable"); static PyMethodDef tee_methods[] = { - {"__copy__", (PyCFunction)tee_copy, METH_NOARGS, teecopy_doc}, - {NULL, NULL} /* sentinel */ + {"__copy__", (PyCFunction)tee_copy, METH_NOARGS, teecopy_doc}, + {NULL, NULL} /* sentinel */ }; static PyTypeObject tee_type = { - PyVarObject_HEAD_INIT(NULL, 0) - "itertools.tee", /* tp_name */ - sizeof(teeobject), /* tp_basicsize */ - 0, /* tp_itemsize */ - /* methods */ - (destructor)tee_dealloc, /* tp_dealloc */ - 0, /* tp_print */ - 0, /* tp_getattr */ - 0, /* tp_setattr */ - 0, /* tp_reserved */ - 0, /* tp_repr */ - 0, /* tp_as_number */ - 0, /* tp_as_sequence */ - 0, /* tp_as_mapping */ - 0, /* tp_hash */ - 0, /* tp_call */ - 0, /* tp_str */ - 0, /* tp_getattro */ - 0, /* tp_setattro */ - 0, /* tp_as_buffer */ - Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC, /* tp_flags */ - teeobject_doc, /* tp_doc */ - (traverseproc)tee_traverse, /* tp_traverse */ - (inquiry)tee_clear, /* tp_clear */ - 0, /* tp_richcompare */ - offsetof(teeobject, weakreflist), /* tp_weaklistoffset */ - PyObject_SelfIter, /* tp_iter */ - (iternextfunc)tee_next, /* tp_iternext */ - tee_methods, /* tp_methods */ - 0, /* tp_members */ - 0, /* tp_getset */ - 0, /* tp_base */ - 0, /* tp_dict */ - 0, /* tp_descr_get */ - 0, /* tp_descr_set */ - 0, /* tp_dictoffset */ - 0, /* tp_init */ - 0, /* tp_alloc */ - tee_new, /* tp_new */ - PyObject_GC_Del, /* tp_free */ + PyVarObject_HEAD_INIT(NULL, 0) + "itertools.tee", /* tp_name */ + sizeof(teeobject), /* tp_basicsize */ + 0, /* tp_itemsize */ + /* methods */ + (destructor)tee_dealloc, /* tp_dealloc */ + 0, /* tp_print */ + 0, /* tp_getattr */ + 0, /* tp_setattr */ + 0, /* tp_reserved */ + 0, /* tp_repr */ + 0, /* tp_as_number */ + 0, /* tp_as_sequence */ + 0, /* tp_as_mapping */ + 0, /* tp_hash */ + 0, /* tp_call */ + 0, /* tp_str */ + 0, /* tp_getattro */ + 0, /* tp_setattro */ + 0, /* tp_as_buffer */ + Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC, /* tp_flags */ + teeobject_doc, /* tp_doc */ + (traverseproc)tee_traverse, /* tp_traverse */ + (inquiry)tee_clear, /* tp_clear */ + 0, /* tp_richcompare */ + offsetof(teeobject, weakreflist), /* tp_weaklistoffset */ + PyObject_SelfIter, /* tp_iter */ + (iternextfunc)tee_next, /* tp_iternext */ + tee_methods, /* tp_methods */ + 0, /* tp_members */ + 0, /* tp_getset */ + 0, /* tp_base */ + 0, /* tp_dict */ + 0, /* tp_descr_get */ + 0, /* tp_descr_set */ + 0, /* tp_dictoffset */ + 0, /* tp_init */ + 0, /* tp_alloc */ + tee_new, /* tp_new */ + PyObject_GC_Del, /* tp_free */ }; static PyObject * tee(PyObject *self, PyObject *args) { - Py_ssize_t i, n=2; - PyObject *it, *iterable, *copyable, *result; + Py_ssize_t i, n=2; + PyObject *it, *iterable, *copyable, *result; - if (!PyArg_ParseTuple(args, "O|n", &iterable, &n)) - return NULL; - if (n < 0) { - PyErr_SetString(PyExc_ValueError, "n must be >= 0"); - return NULL; - } - result = PyTuple_New(n); - if (result == NULL) - return NULL; - if (n == 0) - return result; - it = PyObject_GetIter(iterable); - if (it == NULL) { - Py_DECREF(result); - return NULL; - } - if (!PyObject_HasAttrString(it, "__copy__")) { - copyable = tee_fromiterable(it); - Py_DECREF(it); - if (copyable == NULL) { - Py_DECREF(result); - return NULL; - } - } else - copyable = it; - PyTuple_SET_ITEM(result, 0, copyable); - for (i=1 ; i= 0"); + return NULL; + } + result = PyTuple_New(n); + if (result == NULL) + return NULL; + if (n == 0) + return result; + it = PyObject_GetIter(iterable); + if (it == NULL) { + Py_DECREF(result); + return NULL; + } + if (!PyObject_HasAttrString(it, "__copy__")) { + copyable = tee_fromiterable(it); + Py_DECREF(it); + if (copyable == NULL) { + Py_DECREF(result); + return NULL; + } + } else + copyable = it; + PyTuple_SET_ITEM(result, 0, copyable); + for (i=1 ; itp_alloc(type, 0); - if (lz == NULL) { - Py_DECREF(it); - Py_DECREF(saved); - return NULL; - } - lz->it = it; - lz->saved = saved; - lz->firstpass = 0; + PyObject *it; + PyObject *iterable; + PyObject *saved; + cycleobject *lz; + + if (type == &cycle_type && !_PyArg_NoKeywords("cycle()", kwds)) + return NULL; + + if (!PyArg_UnpackTuple(args, "cycle", 1, 1, &iterable)) + return NULL; + + /* Get iterator. */ + it = PyObject_GetIter(iterable); + if (it == NULL) + return NULL; + + saved = PyList_New(0); + if (saved == NULL) { + Py_DECREF(it); + return NULL; + } + + /* create cycleobject structure */ + lz = (cycleobject *)type->tp_alloc(type, 0); + if (lz == NULL) { + Py_DECREF(it); + Py_DECREF(saved); + return NULL; + } + lz->it = it; + lz->saved = saved; + lz->firstpass = 0; - return (PyObject *)lz; + return (PyObject *)lz; } static void cycle_dealloc(cycleobject *lz) { - PyObject_GC_UnTrack(lz); - Py_XDECREF(lz->saved); - Py_XDECREF(lz->it); - Py_TYPE(lz)->tp_free(lz); + PyObject_GC_UnTrack(lz); + Py_XDECREF(lz->saved); + Py_XDECREF(lz->it); + Py_TYPE(lz)->tp_free(lz); } static int cycle_traverse(cycleobject *lz, visitproc visit, void *arg) { - Py_VISIT(lz->it); - Py_VISIT(lz->saved); - return 0; + Py_VISIT(lz->it); + Py_VISIT(lz->saved); + return 0; } static PyObject * cycle_next(cycleobject *lz) { - PyObject *item; - PyObject *it; - PyObject *tmp; - - while (1) { - item = PyIter_Next(lz->it); - if (item != NULL) { - if (!lz->firstpass && PyList_Append(lz->saved, item)) { - Py_DECREF(item); - return NULL; - } - return item; - } - if (PyErr_Occurred()) { - if (PyErr_ExceptionMatches(PyExc_StopIteration)) - PyErr_Clear(); - else - return NULL; - } - if (PyList_Size(lz->saved) == 0) - return NULL; - it = PyObject_GetIter(lz->saved); - if (it == NULL) - return NULL; - tmp = lz->it; - lz->it = it; - lz->firstpass = 1; - Py_DECREF(tmp); - } + PyObject *item; + PyObject *it; + PyObject *tmp; + + while (1) { + item = PyIter_Next(lz->it); + if (item != NULL) { + if (!lz->firstpass && PyList_Append(lz->saved, item)) { + Py_DECREF(item); + return NULL; + } + return item; + } + if (PyErr_Occurred()) { + if (PyErr_ExceptionMatches(PyExc_StopIteration)) + PyErr_Clear(); + else + return NULL; + } + if (PyList_Size(lz->saved) == 0) + return NULL; + it = PyObject_GetIter(lz->saved); + if (it == NULL) + return NULL; + tmp = lz->it; + lz->it = it; + lz->firstpass = 1; + Py_DECREF(tmp); + } } PyDoc_STRVAR(cycle_doc, @@ -776,57 +776,57 @@ Then repeat the sequence indefinitely."); static PyTypeObject cycle_type = { - PyVarObject_HEAD_INIT(NULL, 0) - "itertools.cycle", /* tp_name */ - sizeof(cycleobject), /* tp_basicsize */ - 0, /* tp_itemsize */ - /* methods */ - (destructor)cycle_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 | - Py_TPFLAGS_BASETYPE, /* tp_flags */ - cycle_doc, /* tp_doc */ - (traverseproc)cycle_traverse, /* tp_traverse */ - 0, /* tp_clear */ - 0, /* tp_richcompare */ - 0, /* tp_weaklistoffset */ - PyObject_SelfIter, /* tp_iter */ - (iternextfunc)cycle_next, /* tp_iternext */ - 0, /* tp_methods */ - 0, /* tp_members */ - 0, /* tp_getset */ - 0, /* tp_base */ - 0, /* tp_dict */ - 0, /* tp_descr_get */ - 0, /* tp_descr_set */ - 0, /* tp_dictoffset */ - 0, /* tp_init */ - 0, /* tp_alloc */ - cycle_new, /* tp_new */ - PyObject_GC_Del, /* tp_free */ + PyVarObject_HEAD_INIT(NULL, 0) + "itertools.cycle", /* tp_name */ + sizeof(cycleobject), /* tp_basicsize */ + 0, /* tp_itemsize */ + /* methods */ + (destructor)cycle_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 | + Py_TPFLAGS_BASETYPE, /* tp_flags */ + cycle_doc, /* tp_doc */ + (traverseproc)cycle_traverse, /* tp_traverse */ + 0, /* tp_clear */ + 0, /* tp_richcompare */ + 0, /* tp_weaklistoffset */ + PyObject_SelfIter, /* tp_iter */ + (iternextfunc)cycle_next, /* tp_iternext */ + 0, /* tp_methods */ + 0, /* tp_members */ + 0, /* tp_getset */ + 0, /* tp_base */ + 0, /* tp_dict */ + 0, /* tp_descr_get */ + 0, /* tp_descr_set */ + 0, /* tp_dictoffset */ + 0, /* tp_init */ + 0, /* tp_alloc */ + cycle_new, /* tp_new */ + PyObject_GC_Del, /* tp_free */ }; /* dropwhile object **********************************************************/ typedef struct { - PyObject_HEAD - PyObject *func; - PyObject *it; - long start; + PyObject_HEAD + PyObject *func; + PyObject *it; + long start; } dropwhileobject; static PyTypeObject dropwhile_type; @@ -834,81 +834,81 @@ static PyObject * dropwhile_new(PyTypeObject *type, PyObject *args, PyObject *kwds) { - PyObject *func, *seq; - PyObject *it; - dropwhileobject *lz; - - if (type == &dropwhile_type && !_PyArg_NoKeywords("dropwhile()", kwds)) - return NULL; - - if (!PyArg_UnpackTuple(args, "dropwhile", 2, 2, &func, &seq)) - return NULL; - - /* Get iterator. */ - it = PyObject_GetIter(seq); - if (it == NULL) - return NULL; - - /* create dropwhileobject structure */ - lz = (dropwhileobject *)type->tp_alloc(type, 0); - if (lz == NULL) { - Py_DECREF(it); - return NULL; - } - Py_INCREF(func); - lz->func = func; - lz->it = it; - lz->start = 0; + PyObject *func, *seq; + PyObject *it; + dropwhileobject *lz; + + if (type == &dropwhile_type && !_PyArg_NoKeywords("dropwhile()", kwds)) + return NULL; + + if (!PyArg_UnpackTuple(args, "dropwhile", 2, 2, &func, &seq)) + return NULL; + + /* Get iterator. */ + it = PyObject_GetIter(seq); + if (it == NULL) + return NULL; + + /* create dropwhileobject structure */ + lz = (dropwhileobject *)type->tp_alloc(type, 0); + if (lz == NULL) { + Py_DECREF(it); + return NULL; + } + Py_INCREF(func); + lz->func = func; + lz->it = it; + lz->start = 0; - return (PyObject *)lz; + return (PyObject *)lz; } static void dropwhile_dealloc(dropwhileobject *lz) { - PyObject_GC_UnTrack(lz); - Py_XDECREF(lz->func); - Py_XDECREF(lz->it); - Py_TYPE(lz)->tp_free(lz); + PyObject_GC_UnTrack(lz); + Py_XDECREF(lz->func); + Py_XDECREF(lz->it); + Py_TYPE(lz)->tp_free(lz); } static int dropwhile_traverse(dropwhileobject *lz, visitproc visit, void *arg) { - Py_VISIT(lz->it); - Py_VISIT(lz->func); - return 0; + Py_VISIT(lz->it); + Py_VISIT(lz->func); + return 0; } static PyObject * dropwhile_next(dropwhileobject *lz) { - PyObject *item, *good; - PyObject *it = lz->it; - long ok; - PyObject *(*iternext)(PyObject *); - - iternext = *Py_TYPE(it)->tp_iternext; - for (;;) { - item = iternext(it); - if (item == NULL) - return NULL; - if (lz->start == 1) - return item; - - good = PyObject_CallFunctionObjArgs(lz->func, item, NULL); - if (good == NULL) { - Py_DECREF(item); - return NULL; - } - ok = PyObject_IsTrue(good); - Py_DECREF(good); - if (!ok) { - lz->start = 1; - return item; - } - Py_DECREF(item); - } + PyObject *item, *good; + PyObject *it = lz->it; + long ok; + PyObject *(*iternext)(PyObject *); + + iternext = *Py_TYPE(it)->tp_iternext; + for (;;) { + item = iternext(it); + if (item == NULL) + return NULL; + if (lz->start == 1) + return item; + + good = PyObject_CallFunctionObjArgs(lz->func, item, NULL); + if (good == NULL) { + Py_DECREF(item); + return NULL; + } + ok = PyObject_IsTrue(good); + Py_DECREF(good); + if (!ok) { + lz->start = 1; + return item; + } + Py_DECREF(item); + } } PyDoc_STRVAR(dropwhile_doc, @@ -918,57 +918,57 @@ Afterwards, return every element until the iterable is exhausted."); static PyTypeObject dropwhile_type = { - PyVarObject_HEAD_INIT(NULL, 0) - "itertools.dropwhile", /* tp_name */ - sizeof(dropwhileobject), /* tp_basicsize */ - 0, /* tp_itemsize */ - /* methods */ - (destructor)dropwhile_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 | - Py_TPFLAGS_BASETYPE, /* tp_flags */ - dropwhile_doc, /* tp_doc */ - (traverseproc)dropwhile_traverse, /* tp_traverse */ - 0, /* tp_clear */ - 0, /* tp_richcompare */ - 0, /* tp_weaklistoffset */ - PyObject_SelfIter, /* tp_iter */ - (iternextfunc)dropwhile_next, /* tp_iternext */ - 0, /* tp_methods */ - 0, /* tp_members */ - 0, /* tp_getset */ - 0, /* tp_base */ - 0, /* tp_dict */ - 0, /* tp_descr_get */ - 0, /* tp_descr_set */ - 0, /* tp_dictoffset */ - 0, /* tp_init */ - 0, /* tp_alloc */ - dropwhile_new, /* tp_new */ - PyObject_GC_Del, /* tp_free */ + PyVarObject_HEAD_INIT(NULL, 0) + "itertools.dropwhile", /* tp_name */ + sizeof(dropwhileobject), /* tp_basicsize */ + 0, /* tp_itemsize */ + /* methods */ + (destructor)dropwhile_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 | + Py_TPFLAGS_BASETYPE, /* tp_flags */ + dropwhile_doc, /* tp_doc */ + (traverseproc)dropwhile_traverse, /* tp_traverse */ + 0, /* tp_clear */ + 0, /* tp_richcompare */ + 0, /* tp_weaklistoffset */ + PyObject_SelfIter, /* tp_iter */ + (iternextfunc)dropwhile_next, /* tp_iternext */ + 0, /* tp_methods */ + 0, /* tp_members */ + 0, /* tp_getset */ + 0, /* tp_base */ + 0, /* tp_dict */ + 0, /* tp_descr_get */ + 0, /* tp_descr_set */ + 0, /* tp_dictoffset */ + 0, /* tp_init */ + 0, /* tp_alloc */ + dropwhile_new, /* tp_new */ + PyObject_GC_Del, /* tp_free */ }; /* takewhile object **********************************************************/ typedef struct { - PyObject_HEAD - PyObject *func; - PyObject *it; - long stop; + PyObject_HEAD + PyObject *func; + PyObject *it; + long stop; } takewhileobject; static PyTypeObject takewhile_type; @@ -976,78 +976,78 @@ static PyObject * takewhile_new(PyTypeObject *type, PyObject *args, PyObject *kwds) { - PyObject *func, *seq; - PyObject *it; - takewhileobject *lz; - - if (type == &takewhile_type && !_PyArg_NoKeywords("takewhile()", kwds)) - return NULL; - - if (!PyArg_UnpackTuple(args, "takewhile", 2, 2, &func, &seq)) - return NULL; - - /* Get iterator. */ - it = PyObject_GetIter(seq); - if (it == NULL) - return NULL; - - /* create takewhileobject structure */ - lz = (takewhileobject *)type->tp_alloc(type, 0); - if (lz == NULL) { - Py_DECREF(it); - return NULL; - } - Py_INCREF(func); - lz->func = func; - lz->it = it; - lz->stop = 0; + PyObject *func, *seq; + PyObject *it; + takewhileobject *lz; + + if (type == &takewhile_type && !_PyArg_NoKeywords("takewhile()", kwds)) + return NULL; + + if (!PyArg_UnpackTuple(args, "takewhile", 2, 2, &func, &seq)) + return NULL; + + /* Get iterator. */ + it = PyObject_GetIter(seq); + if (it == NULL) + return NULL; + + /* create takewhileobject structure */ + lz = (takewhileobject *)type->tp_alloc(type, 0); + if (lz == NULL) { + Py_DECREF(it); + return NULL; + } + Py_INCREF(func); + lz->func = func; + lz->it = it; + lz->stop = 0; - return (PyObject *)lz; + return (PyObject *)lz; } static void takewhile_dealloc(takewhileobject *lz) { - PyObject_GC_UnTrack(lz); - Py_XDECREF(lz->func); - Py_XDECREF(lz->it); - Py_TYPE(lz)->tp_free(lz); + PyObject_GC_UnTrack(lz); + Py_XDECREF(lz->func); + Py_XDECREF(lz->it); + Py_TYPE(lz)->tp_free(lz); } static int takewhile_traverse(takewhileobject *lz, visitproc visit, void *arg) { - Py_VISIT(lz->it); - Py_VISIT(lz->func); - return 0; + Py_VISIT(lz->it); + Py_VISIT(lz->func); + return 0; } static PyObject * takewhile_next(takewhileobject *lz) { - PyObject *item, *good; - PyObject *it = lz->it; - long ok; - - if (lz->stop == 1) - return NULL; - - item = (*Py_TYPE(it)->tp_iternext)(it); - if (item == NULL) - return NULL; - - good = PyObject_CallFunctionObjArgs(lz->func, item, NULL); - if (good == NULL) { - Py_DECREF(item); - return NULL; - } - ok = PyObject_IsTrue(good); - Py_DECREF(good); - if (ok) - return item; - Py_DECREF(item); - lz->stop = 1; - return NULL; + PyObject *item, *good; + PyObject *it = lz->it; + long ok; + + if (lz->stop == 1) + return NULL; + + item = (*Py_TYPE(it)->tp_iternext)(it); + if (item == NULL) + return NULL; + + good = PyObject_CallFunctionObjArgs(lz->func, item, NULL); + if (good == NULL) { + Py_DECREF(item); + return NULL; + } + ok = PyObject_IsTrue(good); + Py_DECREF(good); + if (ok) + return item; + Py_DECREF(item); + lz->stop = 1; + return NULL; } PyDoc_STRVAR(takewhile_doc, @@ -1057,59 +1057,59 @@ predicate evaluates to true for each entry."); static PyTypeObject takewhile_type = { - PyVarObject_HEAD_INIT(NULL, 0) - "itertools.takewhile", /* tp_name */ - sizeof(takewhileobject), /* tp_basicsize */ - 0, /* tp_itemsize */ - /* methods */ - (destructor)takewhile_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 | - Py_TPFLAGS_BASETYPE, /* tp_flags */ - takewhile_doc, /* tp_doc */ - (traverseproc)takewhile_traverse, /* tp_traverse */ - 0, /* tp_clear */ - 0, /* tp_richcompare */ - 0, /* tp_weaklistoffset */ - PyObject_SelfIter, /* tp_iter */ - (iternextfunc)takewhile_next, /* tp_iternext */ - 0, /* tp_methods */ - 0, /* tp_members */ - 0, /* tp_getset */ - 0, /* tp_base */ - 0, /* tp_dict */ - 0, /* tp_descr_get */ - 0, /* tp_descr_set */ - 0, /* tp_dictoffset */ - 0, /* tp_init */ - 0, /* tp_alloc */ - takewhile_new, /* tp_new */ - PyObject_GC_Del, /* tp_free */ + PyVarObject_HEAD_INIT(NULL, 0) + "itertools.takewhile", /* tp_name */ + sizeof(takewhileobject), /* tp_basicsize */ + 0, /* tp_itemsize */ + /* methods */ + (destructor)takewhile_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 | + Py_TPFLAGS_BASETYPE, /* tp_flags */ + takewhile_doc, /* tp_doc */ + (traverseproc)takewhile_traverse, /* tp_traverse */ + 0, /* tp_clear */ + 0, /* tp_richcompare */ + 0, /* tp_weaklistoffset */ + PyObject_SelfIter, /* tp_iter */ + (iternextfunc)takewhile_next, /* tp_iternext */ + 0, /* tp_methods */ + 0, /* tp_members */ + 0, /* tp_getset */ + 0, /* tp_base */ + 0, /* tp_dict */ + 0, /* tp_descr_get */ + 0, /* tp_descr_set */ + 0, /* tp_dictoffset */ + 0, /* tp_init */ + 0, /* tp_alloc */ + takewhile_new, /* tp_new */ + PyObject_GC_Del, /* tp_free */ }; /* islice object ************************************************************/ typedef struct { - PyObject_HEAD - PyObject *it; - Py_ssize_t next; - Py_ssize_t stop; - Py_ssize_t step; - Py_ssize_t cnt; + PyObject_HEAD + PyObject *it; + Py_ssize_t next; + Py_ssize_t stop; + Py_ssize_t step; + Py_ssize_t cnt; } isliceobject; static PyTypeObject islice_type; @@ -1117,126 +1117,126 @@ static PyObject * islice_new(PyTypeObject *type, PyObject *args, PyObject *kwds) { - PyObject *seq; - Py_ssize_t start=0, stop=-1, step=1; - PyObject *it, *a1=NULL, *a2=NULL, *a3=NULL; - Py_ssize_t numargs; - isliceobject *lz; - - if (type == &islice_type && !_PyArg_NoKeywords("islice()", kwds)) - return NULL; - - if (!PyArg_UnpackTuple(args, "islice", 2, 4, &seq, &a1, &a2, &a3)) - return NULL; - - numargs = PyTuple_Size(args); - if (numargs == 2) { - if (a1 != Py_None) { - stop = PyLong_AsSsize_t(a1); - if (stop == -1) { - if (PyErr_Occurred()) - PyErr_Clear(); - PyErr_SetString(PyExc_ValueError, - "Stop argument for islice() must be None or an integer: 0 <= x <= sys.maxsize."); - return NULL; - } - } - } else { - if (a1 != Py_None) - start = PyLong_AsSsize_t(a1); - if (start == -1 && PyErr_Occurred()) - PyErr_Clear(); - if (a2 != Py_None) { - stop = PyLong_AsSsize_t(a2); - if (stop == -1) { - if (PyErr_Occurred()) - PyErr_Clear(); - PyErr_SetString(PyExc_ValueError, - "Stop argument for islice() must be None or an integer: 0 <= x <= sys.maxsize."); - return NULL; - } - } - } - if (start<0 || stop<-1) { - PyErr_SetString(PyExc_ValueError, - "Indices for islice() must be None or an integer: 0 <= x <= sys.maxsize."); - return NULL; - } - - if (a3 != NULL) { - if (a3 != Py_None) - step = PyLong_AsSsize_t(a3); - if (step == -1 && PyErr_Occurred()) - PyErr_Clear(); - } - if (step<1) { - PyErr_SetString(PyExc_ValueError, - "Step for islice() must be a positive integer or None."); - return NULL; - } - - /* Get iterator. */ - it = PyObject_GetIter(seq); - if (it == NULL) - return NULL; - - /* create isliceobject structure */ - lz = (isliceobject *)type->tp_alloc(type, 0); - if (lz == NULL) { - Py_DECREF(it); - return NULL; - } - lz->it = it; - lz->next = start; - lz->stop = stop; - lz->step = step; - lz->cnt = 0L; + PyObject *seq; + Py_ssize_t start=0, stop=-1, step=1; + PyObject *it, *a1=NULL, *a2=NULL, *a3=NULL; + Py_ssize_t numargs; + isliceobject *lz; + + if (type == &islice_type && !_PyArg_NoKeywords("islice()", kwds)) + return NULL; + + if (!PyArg_UnpackTuple(args, "islice", 2, 4, &seq, &a1, &a2, &a3)) + return NULL; + + numargs = PyTuple_Size(args); + if (numargs == 2) { + if (a1 != Py_None) { + stop = PyLong_AsSsize_t(a1); + if (stop == -1) { + if (PyErr_Occurred()) + PyErr_Clear(); + PyErr_SetString(PyExc_ValueError, + "Stop argument for islice() must be None or an integer: 0 <= x <= sys.maxsize."); + return NULL; + } + } + } else { + if (a1 != Py_None) + start = PyLong_AsSsize_t(a1); + if (start == -1 && PyErr_Occurred()) + PyErr_Clear(); + if (a2 != Py_None) { + stop = PyLong_AsSsize_t(a2); + if (stop == -1) { + if (PyErr_Occurred()) + PyErr_Clear(); + PyErr_SetString(PyExc_ValueError, + "Stop argument for islice() must be None or an integer: 0 <= x <= sys.maxsize."); + return NULL; + } + } + } + if (start<0 || stop<-1) { + PyErr_SetString(PyExc_ValueError, + "Indices for islice() must be None or an integer: 0 <= x <= sys.maxsize."); + return NULL; + } + + if (a3 != NULL) { + if (a3 != Py_None) + step = PyLong_AsSsize_t(a3); + if (step == -1 && PyErr_Occurred()) + PyErr_Clear(); + } + if (step<1) { + PyErr_SetString(PyExc_ValueError, + "Step for islice() must be a positive integer or None."); + return NULL; + } + + /* Get iterator. */ + it = PyObject_GetIter(seq); + if (it == NULL) + return NULL; + + /* create isliceobject structure */ + lz = (isliceobject *)type->tp_alloc(type, 0); + if (lz == NULL) { + Py_DECREF(it); + return NULL; + } + lz->it = it; + lz->next = start; + lz->stop = stop; + lz->step = step; + lz->cnt = 0L; - return (PyObject *)lz; + return (PyObject *)lz; } static void islice_dealloc(isliceobject *lz) { - PyObject_GC_UnTrack(lz); - Py_XDECREF(lz->it); - Py_TYPE(lz)->tp_free(lz); + PyObject_GC_UnTrack(lz); + Py_XDECREF(lz->it); + Py_TYPE(lz)->tp_free(lz); } static int islice_traverse(isliceobject *lz, visitproc visit, void *arg) { - Py_VISIT(lz->it); - return 0; + Py_VISIT(lz->it); + return 0; } static PyObject * islice_next(isliceobject *lz) { - PyObject *item; - PyObject *it = lz->it; - Py_ssize_t oldnext; - PyObject *(*iternext)(PyObject *); - - iternext = *Py_TYPE(it)->tp_iternext; - while (lz->cnt < lz->next) { - item = iternext(it); - if (item == NULL) - return NULL; - Py_DECREF(item); - lz->cnt++; - } - if (lz->stop != -1 && lz->cnt >= lz->stop) - return NULL; - item = iternext(it); - if (item == NULL) - return NULL; - lz->cnt++; - oldnext = lz->next; - lz->next += lz->step; - if (lz->next < oldnext) /* Check for overflow */ - lz->next = lz->stop; - return item; + PyObject *item; + PyObject *it = lz->it; + Py_ssize_t oldnext; + PyObject *(*iternext)(PyObject *); + + iternext = *Py_TYPE(it)->tp_iternext; + while (lz->cnt < lz->next) { + item = iternext(it); + if (item == NULL) + return NULL; + Py_DECREF(item); + lz->cnt++; + } + if (lz->stop != -1 && lz->cnt >= lz->stop) + return NULL; + item = iternext(it); + if (item == NULL) + return NULL; + lz->cnt++; + oldnext = lz->next; + lz->next += lz->step; + if (lz->next < oldnext) /* Check for overflow */ + lz->next = lz->stop; + return item; } PyDoc_STRVAR(islice_doc, @@ -1250,56 +1250,56 @@ but returns an iterator."); static PyTypeObject islice_type = { - PyVarObject_HEAD_INIT(NULL, 0) - "itertools.islice", /* tp_name */ - sizeof(isliceobject), /* tp_basicsize */ - 0, /* tp_itemsize */ - /* methods */ - (destructor)islice_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 | - Py_TPFLAGS_BASETYPE, /* tp_flags */ - islice_doc, /* tp_doc */ - (traverseproc)islice_traverse, /* tp_traverse */ - 0, /* tp_clear */ - 0, /* tp_richcompare */ - 0, /* tp_weaklistoffset */ - PyObject_SelfIter, /* tp_iter */ - (iternextfunc)islice_next, /* tp_iternext */ - 0, /* tp_methods */ - 0, /* tp_members */ - 0, /* tp_getset */ - 0, /* tp_base */ - 0, /* tp_dict */ - 0, /* tp_descr_get */ - 0, /* tp_descr_set */ - 0, /* tp_dictoffset */ - 0, /* tp_init */ - 0, /* tp_alloc */ - islice_new, /* tp_new */ - PyObject_GC_Del, /* tp_free */ + PyVarObject_HEAD_INIT(NULL, 0) + "itertools.islice", /* tp_name */ + sizeof(isliceobject), /* tp_basicsize */ + 0, /* tp_itemsize */ + /* methods */ + (destructor)islice_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 | + Py_TPFLAGS_BASETYPE, /* tp_flags */ + islice_doc, /* tp_doc */ + (traverseproc)islice_traverse, /* tp_traverse */ + 0, /* tp_clear */ + 0, /* tp_richcompare */ + 0, /* tp_weaklistoffset */ + PyObject_SelfIter, /* tp_iter */ + (iternextfunc)islice_next, /* tp_iternext */ + 0, /* tp_methods */ + 0, /* tp_members */ + 0, /* tp_getset */ + 0, /* tp_base */ + 0, /* tp_dict */ + 0, /* tp_descr_get */ + 0, /* tp_descr_set */ + 0, /* tp_dictoffset */ + 0, /* tp_init */ + 0, /* tp_alloc */ + islice_new, /* tp_new */ + PyObject_GC_Del, /* tp_free */ }; /* starmap object ************************************************************/ typedef struct { - PyObject_HEAD - PyObject *func; - PyObject *it; + PyObject_HEAD + PyObject *func; + PyObject *it; } starmapobject; static PyTypeObject starmap_type; @@ -1307,71 +1307,71 @@ static PyObject * starmap_new(PyTypeObject *type, PyObject *args, PyObject *kwds) { - PyObject *func, *seq; - PyObject *it; - starmapobject *lz; - - if (type == &starmap_type && !_PyArg_NoKeywords("starmap()", kwds)) - return NULL; - - if (!PyArg_UnpackTuple(args, "starmap", 2, 2, &func, &seq)) - return NULL; - - /* Get iterator. */ - it = PyObject_GetIter(seq); - if (it == NULL) - return NULL; - - /* create starmapobject structure */ - lz = (starmapobject *)type->tp_alloc(type, 0); - if (lz == NULL) { - Py_DECREF(it); - return NULL; - } - Py_INCREF(func); - lz->func = func; - lz->it = it; + PyObject *func, *seq; + PyObject *it; + starmapobject *lz; + + if (type == &starmap_type && !_PyArg_NoKeywords("starmap()", kwds)) + return NULL; + + if (!PyArg_UnpackTuple(args, "starmap", 2, 2, &func, &seq)) + return NULL; + + /* Get iterator. */ + it = PyObject_GetIter(seq); + if (it == NULL) + return NULL; + + /* create starmapobject structure */ + lz = (starmapobject *)type->tp_alloc(type, 0); + if (lz == NULL) { + Py_DECREF(it); + return NULL; + } + Py_INCREF(func); + lz->func = func; + lz->it = it; - return (PyObject *)lz; + return (PyObject *)lz; } static void starmap_dealloc(starmapobject *lz) { - PyObject_GC_UnTrack(lz); - Py_XDECREF(lz->func); - Py_XDECREF(lz->it); - Py_TYPE(lz)->tp_free(lz); + PyObject_GC_UnTrack(lz); + Py_XDECREF(lz->func); + Py_XDECREF(lz->it); + Py_TYPE(lz)->tp_free(lz); } static int starmap_traverse(starmapobject *lz, visitproc visit, void *arg) { - Py_VISIT(lz->it); - Py_VISIT(lz->func); - return 0; + Py_VISIT(lz->it); + Py_VISIT(lz->func); + return 0; } static PyObject * starmap_next(starmapobject *lz) { - PyObject *args; - PyObject *result; - PyObject *it = lz->it; - - args = (*Py_TYPE(it)->tp_iternext)(it); - if (args == NULL) - return NULL; - if (!PyTuple_CheckExact(args)) { - PyObject *newargs = PySequence_Tuple(args); - Py_DECREF(args); - if (newargs == NULL) - return NULL; - args = newargs; - } - result = PyObject_Call(lz->func, args, NULL); - Py_DECREF(args); - return result; + PyObject *args; + PyObject *result; + PyObject *it = lz->it; + + args = (*Py_TYPE(it)->tp_iternext)(it); + if (args == NULL) + return NULL; + if (!PyTuple_CheckExact(args)) { + PyObject *newargs = PySequence_Tuple(args); + Py_DECREF(args); + if (newargs == NULL) + return NULL; + args = newargs; + } + result = PyObject_Call(lz->func, args, NULL); + Py_DECREF(args); + return result; } PyDoc_STRVAR(starmap_doc, @@ -1381,152 +1381,152 @@ with a argument tuple taken from the given sequence."); static PyTypeObject starmap_type = { - PyVarObject_HEAD_INIT(NULL, 0) - "itertools.starmap", /* tp_name */ - sizeof(starmapobject), /* tp_basicsize */ - 0, /* tp_itemsize */ - /* methods */ - (destructor)starmap_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 | - Py_TPFLAGS_BASETYPE, /* tp_flags */ - starmap_doc, /* tp_doc */ - (traverseproc)starmap_traverse, /* tp_traverse */ - 0, /* tp_clear */ - 0, /* tp_richcompare */ - 0, /* tp_weaklistoffset */ - PyObject_SelfIter, /* tp_iter */ - (iternextfunc)starmap_next, /* tp_iternext */ - 0, /* tp_methods */ - 0, /* tp_members */ - 0, /* tp_getset */ - 0, /* tp_base */ - 0, /* tp_dict */ - 0, /* tp_descr_get */ - 0, /* tp_descr_set */ - 0, /* tp_dictoffset */ - 0, /* tp_init */ - 0, /* tp_alloc */ - starmap_new, /* tp_new */ - PyObject_GC_Del, /* tp_free */ + PyVarObject_HEAD_INIT(NULL, 0) + "itertools.starmap", /* tp_name */ + sizeof(starmapobject), /* tp_basicsize */ + 0, /* tp_itemsize */ + /* methods */ + (destructor)starmap_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 | + Py_TPFLAGS_BASETYPE, /* tp_flags */ + starmap_doc, /* tp_doc */ + (traverseproc)starmap_traverse, /* tp_traverse */ + 0, /* tp_clear */ + 0, /* tp_richcompare */ + 0, /* tp_weaklistoffset */ + PyObject_SelfIter, /* tp_iter */ + (iternextfunc)starmap_next, /* tp_iternext */ + 0, /* tp_methods */ + 0, /* tp_members */ + 0, /* tp_getset */ + 0, /* tp_base */ + 0, /* tp_dict */ + 0, /* tp_descr_get */ + 0, /* tp_descr_set */ + 0, /* tp_dictoffset */ + 0, /* tp_init */ + 0, /* tp_alloc */ + starmap_new, /* tp_new */ + PyObject_GC_Del, /* tp_free */ }; /* chain object ************************************************************/ typedef struct { - PyObject_HEAD - PyObject *source; /* Iterator over input iterables */ - PyObject *active; /* Currently running input iterator */ + PyObject_HEAD + PyObject *source; /* Iterator over input iterables */ + PyObject *active; /* Currently running input iterator */ } chainobject; static PyTypeObject chain_type; -static PyObject * +static PyObject * chain_new_internal(PyTypeObject *type, PyObject *source) { - chainobject *lz; + chainobject *lz; - lz = (chainobject *)type->tp_alloc(type, 0); - if (lz == NULL) { - Py_DECREF(source); - return NULL; - } - - lz->source = source; - lz->active = NULL; - return (PyObject *)lz; + lz = (chainobject *)type->tp_alloc(type, 0); + if (lz == NULL) { + Py_DECREF(source); + return NULL; + } + + lz->source = source; + lz->active = NULL; + return (PyObject *)lz; } static PyObject * chain_new(PyTypeObject *type, PyObject *args, PyObject *kwds) { - PyObject *source; + PyObject *source; + + if (type == &chain_type && !_PyArg_NoKeywords("chain()", kwds)) + return NULL; - if (type == &chain_type && !_PyArg_NoKeywords("chain()", kwds)) - return NULL; - - source = PyObject_GetIter(args); - if (source == NULL) - return NULL; + source = PyObject_GetIter(args); + if (source == NULL) + return NULL; - return chain_new_internal(type, source); + return chain_new_internal(type, source); } static PyObject * chain_new_from_iterable(PyTypeObject *type, PyObject *arg) { - PyObject *source; - - source = PyObject_GetIter(arg); - if (source == NULL) - return NULL; + PyObject *source; + + source = PyObject_GetIter(arg); + if (source == NULL) + return NULL; - return chain_new_internal(type, source); + return chain_new_internal(type, source); } static void chain_dealloc(chainobject *lz) { - PyObject_GC_UnTrack(lz); - Py_XDECREF(lz->active); - Py_XDECREF(lz->source); - Py_TYPE(lz)->tp_free(lz); + PyObject_GC_UnTrack(lz); + Py_XDECREF(lz->active); + Py_XDECREF(lz->source); + Py_TYPE(lz)->tp_free(lz); } static int chain_traverse(chainobject *lz, visitproc visit, void *arg) { - Py_VISIT(lz->source); - Py_VISIT(lz->active); - return 0; + Py_VISIT(lz->source); + Py_VISIT(lz->active); + return 0; } static PyObject * chain_next(chainobject *lz) { - PyObject *item; + PyObject *item; - if (lz->source == NULL) - return NULL; /* already stopped */ + if (lz->source == NULL) + return NULL; /* already stopped */ - if (lz->active == NULL) { - PyObject *iterable = PyIter_Next(lz->source); - if (iterable == NULL) { - Py_CLEAR(lz->source); - return NULL; /* no more input sources */ - } - lz->active = PyObject_GetIter(iterable); - Py_DECREF(iterable); - if (lz->active == NULL) { - Py_CLEAR(lz->source); - return NULL; /* input not iterable */ - } - } - item = PyIter_Next(lz->active); - if (item != NULL) - return item; - if (PyErr_Occurred()) { - if (PyErr_ExceptionMatches(PyExc_StopIteration)) - PyErr_Clear(); - else - return NULL; /* input raised an exception */ - } - Py_CLEAR(lz->active); - return chain_next(lz); /* recurse and use next active */ + if (lz->active == NULL) { + PyObject *iterable = PyIter_Next(lz->source); + if (iterable == NULL) { + Py_CLEAR(lz->source); + return NULL; /* no more input sources */ + } + lz->active = PyObject_GetIter(iterable); + Py_DECREF(iterable); + if (lz->active == NULL) { + Py_CLEAR(lz->source); + return NULL; /* input not iterable */ + } + } + item = PyIter_Next(lz->active); + if (item != NULL) + return item; + if (PyErr_Occurred()) { + if (PyErr_ExceptionMatches(PyExc_StopIteration)) + PyErr_Clear(); + else + return NULL; /* input raised an exception */ + } + Py_CLEAR(lz->active); + return chain_next(lz); /* recurse and use next active */ } PyDoc_STRVAR(chain_doc, @@ -1543,64 +1543,64 @@ that evaluates lazily."); static PyMethodDef chain_methods[] = { - {"from_iterable", (PyCFunction) chain_new_from_iterable, METH_O | METH_CLASS, - chain_from_iterable_doc}, - {NULL, NULL} /* sentinel */ + {"from_iterable", (PyCFunction) chain_new_from_iterable, METH_O | METH_CLASS, + chain_from_iterable_doc}, + {NULL, NULL} /* sentinel */ }; static PyTypeObject chain_type = { - PyVarObject_HEAD_INIT(NULL, 0) - "itertools.chain", /* tp_name */ - sizeof(chainobject), /* tp_basicsize */ - 0, /* tp_itemsize */ - /* methods */ - (destructor)chain_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 | - Py_TPFLAGS_BASETYPE, /* tp_flags */ - chain_doc, /* tp_doc */ - (traverseproc)chain_traverse, /* tp_traverse */ - 0, /* tp_clear */ - 0, /* tp_richcompare */ - 0, /* tp_weaklistoffset */ - PyObject_SelfIter, /* tp_iter */ - (iternextfunc)chain_next, /* tp_iternext */ - chain_methods, /* tp_methods */ - 0, /* tp_members */ - 0, /* tp_getset */ - 0, /* tp_base */ - 0, /* tp_dict */ - 0, /* tp_descr_get */ - 0, /* tp_descr_set */ - 0, /* tp_dictoffset */ - 0, /* tp_init */ - 0, /* tp_alloc */ - chain_new, /* tp_new */ - PyObject_GC_Del, /* tp_free */ + PyVarObject_HEAD_INIT(NULL, 0) + "itertools.chain", /* tp_name */ + sizeof(chainobject), /* tp_basicsize */ + 0, /* tp_itemsize */ + /* methods */ + (destructor)chain_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 | + Py_TPFLAGS_BASETYPE, /* tp_flags */ + chain_doc, /* tp_doc */ + (traverseproc)chain_traverse, /* tp_traverse */ + 0, /* tp_clear */ + 0, /* tp_richcompare */ + 0, /* tp_weaklistoffset */ + PyObject_SelfIter, /* tp_iter */ + (iternextfunc)chain_next, /* tp_iternext */ + chain_methods, /* tp_methods */ + 0, /* tp_members */ + 0, /* tp_getset */ + 0, /* tp_base */ + 0, /* tp_dict */ + 0, /* tp_descr_get */ + 0, /* tp_descr_set */ + 0, /* tp_dictoffset */ + 0, /* tp_init */ + 0, /* tp_alloc */ + chain_new, /* tp_new */ + PyObject_GC_Del, /* tp_free */ }; /* product object ************************************************************/ typedef struct { - PyObject_HEAD - PyObject *pools; /* tuple of pool tuples */ - Py_ssize_t *indices; /* one index per pool */ - PyObject *result; /* most recently returned result tuple */ - int stopped; /* set to 1 when the product iterator is exhausted */ + PyObject_HEAD + PyObject *pools; /* tuple of pool tuples */ + Py_ssize_t *indices; /* one index per pool */ + PyObject *result; /* most recently returned result tuple */ + int stopped; /* set to 1 when the product iterator is exhausted */ } productobject; static PyTypeObject product_type; @@ -1608,181 +1608,181 @@ static PyObject * product_new(PyTypeObject *type, PyObject *args, PyObject *kwds) { - productobject *lz; - Py_ssize_t nargs, npools, repeat=1; - PyObject *pools = NULL; - Py_ssize_t *indices = NULL; - Py_ssize_t i; - - if (kwds != NULL) { - char *kwlist[] = {"repeat", 0}; - PyObject *tmpargs = PyTuple_New(0); - if (tmpargs == NULL) - return NULL; - if (!PyArg_ParseTupleAndKeywords(tmpargs, kwds, "|n:product", kwlist, &repeat)) { - Py_DECREF(tmpargs); - return NULL; - } - Py_DECREF(tmpargs); - if (repeat < 0) { - PyErr_SetString(PyExc_ValueError, - "repeat argument cannot be negative"); - return NULL; - } - } - - assert(PyTuple_Check(args)); - nargs = (repeat == 0) ? 0 : PyTuple_GET_SIZE(args); - npools = nargs * repeat; - - indices = PyMem_Malloc(npools * sizeof(Py_ssize_t)); - if (indices == NULL) { - PyErr_NoMemory(); - goto error; - } - - pools = PyTuple_New(npools); - if (pools == NULL) - goto error; - - for (i=0; i < nargs ; ++i) { - PyObject *item = PyTuple_GET_ITEM(args, i); - PyObject *pool = PySequence_Tuple(item); - if (pool == NULL) - goto error; - PyTuple_SET_ITEM(pools, i, pool); - indices[i] = 0; - } - for ( ; i < npools; ++i) { - PyObject *pool = PyTuple_GET_ITEM(pools, i - nargs); - Py_INCREF(pool); - PyTuple_SET_ITEM(pools, i, pool); - indices[i] = 0; - } - - /* create productobject structure */ - lz = (productobject *)type->tp_alloc(type, 0); - if (lz == NULL) - goto error; - - lz->pools = pools; - lz->indices = indices; - lz->result = NULL; - lz->stopped = 0; + productobject *lz; + Py_ssize_t nargs, npools, repeat=1; + PyObject *pools = NULL; + Py_ssize_t *indices = NULL; + Py_ssize_t i; + + if (kwds != NULL) { + char *kwlist[] = {"repeat", 0}; + PyObject *tmpargs = PyTuple_New(0); + if (tmpargs == NULL) + return NULL; + if (!PyArg_ParseTupleAndKeywords(tmpargs, kwds, "|n:product", kwlist, &repeat)) { + Py_DECREF(tmpargs); + return NULL; + } + Py_DECREF(tmpargs); + if (repeat < 0) { + PyErr_SetString(PyExc_ValueError, + "repeat argument cannot be negative"); + return NULL; + } + } + + assert(PyTuple_Check(args)); + nargs = (repeat == 0) ? 0 : PyTuple_GET_SIZE(args); + npools = nargs * repeat; + + indices = PyMem_Malloc(npools * sizeof(Py_ssize_t)); + if (indices == NULL) { + PyErr_NoMemory(); + goto error; + } + + pools = PyTuple_New(npools); + if (pools == NULL) + goto error; + + for (i=0; i < nargs ; ++i) { + PyObject *item = PyTuple_GET_ITEM(args, i); + PyObject *pool = PySequence_Tuple(item); + if (pool == NULL) + goto error; + PyTuple_SET_ITEM(pools, i, pool); + indices[i] = 0; + } + for ( ; i < npools; ++i) { + PyObject *pool = PyTuple_GET_ITEM(pools, i - nargs); + Py_INCREF(pool); + PyTuple_SET_ITEM(pools, i, pool); + indices[i] = 0; + } + + /* create productobject structure */ + lz = (productobject *)type->tp_alloc(type, 0); + if (lz == NULL) + goto error; + + lz->pools = pools; + lz->indices = indices; + lz->result = NULL; + lz->stopped = 0; - return (PyObject *)lz; + return (PyObject *)lz; error: - if (indices != NULL) - PyMem_Free(indices); - Py_XDECREF(pools); - return NULL; + if (indices != NULL) + PyMem_Free(indices); + Py_XDECREF(pools); + return NULL; } static void product_dealloc(productobject *lz) { - PyObject_GC_UnTrack(lz); - Py_XDECREF(lz->pools); - Py_XDECREF(lz->result); - if (lz->indices != NULL) - PyMem_Free(lz->indices); - Py_TYPE(lz)->tp_free(lz); + PyObject_GC_UnTrack(lz); + Py_XDECREF(lz->pools); + Py_XDECREF(lz->result); + if (lz->indices != NULL) + PyMem_Free(lz->indices); + Py_TYPE(lz)->tp_free(lz); } static int product_traverse(productobject *lz, visitproc visit, void *arg) { - Py_VISIT(lz->pools); - Py_VISIT(lz->result); - return 0; + Py_VISIT(lz->pools); + Py_VISIT(lz->result); + return 0; } static PyObject * product_next(productobject *lz) { - PyObject *pool; - PyObject *elem; - PyObject *oldelem; - PyObject *pools = lz->pools; - PyObject *result = lz->result; - Py_ssize_t npools = PyTuple_GET_SIZE(pools); - Py_ssize_t i; - - if (lz->stopped) - return NULL; - - if (result == NULL) { - /* On the first pass, return an initial tuple filled with the - first element from each pool. */ - result = PyTuple_New(npools); - if (result == NULL) - goto empty; - lz->result = result; - for (i=0; i < npools; i++) { - pool = PyTuple_GET_ITEM(pools, i); - if (PyTuple_GET_SIZE(pool) == 0) - goto empty; - elem = PyTuple_GET_ITEM(pool, 0); - Py_INCREF(elem); - PyTuple_SET_ITEM(result, i, elem); - } - } else { - Py_ssize_t *indices = lz->indices; - - /* Copy the previous result tuple or re-use it if available */ - if (Py_REFCNT(result) > 1) { - PyObject *old_result = result; - result = PyTuple_New(npools); - if (result == NULL) - goto empty; - lz->result = result; - for (i=0; i < npools; i++) { - elem = PyTuple_GET_ITEM(old_result, i); - Py_INCREF(elem); - PyTuple_SET_ITEM(result, i, elem); - } - Py_DECREF(old_result); - } - /* Now, we've got the only copy so we can update it in-place */ - assert (npools==0 || Py_REFCNT(result) == 1); - - /* Update the pool indices right-to-left. Only advance to the - next pool when the previous one rolls-over */ - for (i=npools-1 ; i >= 0 ; i--) { - pool = PyTuple_GET_ITEM(pools, i); - indices[i]++; - if (indices[i] == PyTuple_GET_SIZE(pool)) { - /* Roll-over and advance to next pool */ - indices[i] = 0; - elem = PyTuple_GET_ITEM(pool, 0); - Py_INCREF(elem); - oldelem = PyTuple_GET_ITEM(result, i); - PyTuple_SET_ITEM(result, i, elem); - Py_DECREF(oldelem); - } else { - /* No rollover. Just increment and stop here. */ - elem = PyTuple_GET_ITEM(pool, indices[i]); - Py_INCREF(elem); - oldelem = PyTuple_GET_ITEM(result, i); - PyTuple_SET_ITEM(result, i, elem); - Py_DECREF(oldelem); - break; - } - } - - /* If i is negative, then the indices have all rolled-over - and we're done. */ - if (i < 0) - goto empty; - } + PyObject *pool; + PyObject *elem; + PyObject *oldelem; + PyObject *pools = lz->pools; + PyObject *result = lz->result; + Py_ssize_t npools = PyTuple_GET_SIZE(pools); + Py_ssize_t i; + + if (lz->stopped) + return NULL; + + if (result == NULL) { + /* On the first pass, return an initial tuple filled with the + first element from each pool. */ + result = PyTuple_New(npools); + if (result == NULL) + goto empty; + lz->result = result; + for (i=0; i < npools; i++) { + pool = PyTuple_GET_ITEM(pools, i); + if (PyTuple_GET_SIZE(pool) == 0) + goto empty; + elem = PyTuple_GET_ITEM(pool, 0); + Py_INCREF(elem); + PyTuple_SET_ITEM(result, i, elem); + } + } else { + Py_ssize_t *indices = lz->indices; + + /* Copy the previous result tuple or re-use it if available */ + if (Py_REFCNT(result) > 1) { + PyObject *old_result = result; + result = PyTuple_New(npools); + if (result == NULL) + goto empty; + lz->result = result; + for (i=0; i < npools; i++) { + elem = PyTuple_GET_ITEM(old_result, i); + Py_INCREF(elem); + PyTuple_SET_ITEM(result, i, elem); + } + Py_DECREF(old_result); + } + /* Now, we've got the only copy so we can update it in-place */ + assert (npools==0 || Py_REFCNT(result) == 1); + + /* Update the pool indices right-to-left. Only advance to the + next pool when the previous one rolls-over */ + for (i=npools-1 ; i >= 0 ; i--) { + pool = PyTuple_GET_ITEM(pools, i); + indices[i]++; + if (indices[i] == PyTuple_GET_SIZE(pool)) { + /* Roll-over and advance to next pool */ + indices[i] = 0; + elem = PyTuple_GET_ITEM(pool, 0); + Py_INCREF(elem); + oldelem = PyTuple_GET_ITEM(result, i); + PyTuple_SET_ITEM(result, i, elem); + Py_DECREF(oldelem); + } else { + /* No rollover. Just increment and stop here. */ + elem = PyTuple_GET_ITEM(pool, indices[i]); + Py_INCREF(elem); + oldelem = PyTuple_GET_ITEM(result, i); + PyTuple_SET_ITEM(result, i, elem); + Py_DECREF(oldelem); + break; + } + } - Py_INCREF(result); - return result; + /* If i is negative, then the indices have all rolled-over + and we're done. */ + if (i < 0) + goto empty; + } + + Py_INCREF(result); + return result; empty: - lz->stopped = 1; - return NULL; + lz->stopped = 1; + return NULL; } PyDoc_STRVAR(product_doc, @@ -1800,59 +1800,59 @@ product((0,1), (0,1), (0,1)) --> (0,0,0) (0,0,1) (0,1,0) (0,1,1) (1,0,0) ..."); static PyTypeObject product_type = { - PyVarObject_HEAD_INIT(NULL, 0) - "itertools.product", /* tp_name */ - sizeof(productobject), /* tp_basicsize */ - 0, /* tp_itemsize */ - /* methods */ - (destructor)product_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 | - Py_TPFLAGS_BASETYPE, /* tp_flags */ - product_doc, /* tp_doc */ - (traverseproc)product_traverse, /* tp_traverse */ - 0, /* tp_clear */ - 0, /* tp_richcompare */ - 0, /* tp_weaklistoffset */ - PyObject_SelfIter, /* tp_iter */ - (iternextfunc)product_next, /* tp_iternext */ - 0, /* tp_methods */ - 0, /* tp_members */ - 0, /* tp_getset */ - 0, /* tp_base */ - 0, /* tp_dict */ - 0, /* tp_descr_get */ - 0, /* tp_descr_set */ - 0, /* tp_dictoffset */ - 0, /* tp_init */ - 0, /* tp_alloc */ - product_new, /* tp_new */ - PyObject_GC_Del, /* tp_free */ + PyVarObject_HEAD_INIT(NULL, 0) + "itertools.product", /* tp_name */ + sizeof(productobject), /* tp_basicsize */ + 0, /* tp_itemsize */ + /* methods */ + (destructor)product_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 | + Py_TPFLAGS_BASETYPE, /* tp_flags */ + product_doc, /* tp_doc */ + (traverseproc)product_traverse, /* tp_traverse */ + 0, /* tp_clear */ + 0, /* tp_richcompare */ + 0, /* tp_weaklistoffset */ + PyObject_SelfIter, /* tp_iter */ + (iternextfunc)product_next, /* tp_iternext */ + 0, /* tp_methods */ + 0, /* tp_members */ + 0, /* tp_getset */ + 0, /* tp_base */ + 0, /* tp_dict */ + 0, /* tp_descr_get */ + 0, /* tp_descr_set */ + 0, /* tp_dictoffset */ + 0, /* tp_init */ + 0, /* tp_alloc */ + product_new, /* tp_new */ + PyObject_GC_Del, /* tp_free */ }; /* combinations object ************************************************************/ typedef struct { - PyObject_HEAD - PyObject *pool; /* input converted to a tuple */ - Py_ssize_t *indices; /* one index per result element */ - PyObject *result; /* most recently returned result tuple */ - Py_ssize_t r; /* size of result tuple */ - int stopped; /* set to 1 when the combinations iterator is exhausted */ + PyObject_HEAD + PyObject *pool; /* input converted to a tuple */ + Py_ssize_t *indices; /* one index per result element */ + PyObject *result; /* most recently returned result tuple */ + Py_ssize_t r; /* size of result tuple */ + int stopped; /* set to 1 when the combinations iterator is exhausted */ } combinationsobject; static PyTypeObject combinations_type; @@ -1860,160 +1860,160 @@ static PyObject * combinations_new(PyTypeObject *type, PyObject *args, PyObject *kwds) { - combinationsobject *co; - Py_ssize_t n; - Py_ssize_t r; - PyObject *pool = NULL; - PyObject *iterable = NULL; - Py_ssize_t *indices = NULL; - Py_ssize_t i; - static char *kwargs[] = {"iterable", "r", NULL}; - - if (!PyArg_ParseTupleAndKeywords(args, kwds, "On:combinations", kwargs, - &iterable, &r)) - return NULL; - - pool = PySequence_Tuple(iterable); - if (pool == NULL) - goto error; - n = PyTuple_GET_SIZE(pool); - if (r < 0) { - PyErr_SetString(PyExc_ValueError, "r must be non-negative"); - goto error; - } - - indices = PyMem_Malloc(r * sizeof(Py_ssize_t)); - if (indices == NULL) { - PyErr_NoMemory(); - goto error; - } - - for (i=0 ; itp_alloc(type, 0); - if (co == NULL) - goto error; - - co->pool = pool; - co->indices = indices; - co->result = NULL; - co->r = r; - co->stopped = r > n ? 1 : 0; + combinationsobject *co; + Py_ssize_t n; + Py_ssize_t r; + PyObject *pool = NULL; + PyObject *iterable = NULL; + Py_ssize_t *indices = NULL; + Py_ssize_t i; + static char *kwargs[] = {"iterable", "r", NULL}; + + if (!PyArg_ParseTupleAndKeywords(args, kwds, "On:combinations", kwargs, + &iterable, &r)) + return NULL; + + pool = PySequence_Tuple(iterable); + if (pool == NULL) + goto error; + n = PyTuple_GET_SIZE(pool); + if (r < 0) { + PyErr_SetString(PyExc_ValueError, "r must be non-negative"); + goto error; + } + + indices = PyMem_Malloc(r * sizeof(Py_ssize_t)); + if (indices == NULL) { + PyErr_NoMemory(); + goto error; + } + + for (i=0 ; itp_alloc(type, 0); + if (co == NULL) + goto error; + + co->pool = pool; + co->indices = indices; + co->result = NULL; + co->r = r; + co->stopped = r > n ? 1 : 0; - return (PyObject *)co; + return (PyObject *)co; error: - if (indices != NULL) - PyMem_Free(indices); - Py_XDECREF(pool); - return NULL; + if (indices != NULL) + PyMem_Free(indices); + Py_XDECREF(pool); + return NULL; } static void combinations_dealloc(combinationsobject *co) { - PyObject_GC_UnTrack(co); - Py_XDECREF(co->pool); - Py_XDECREF(co->result); - if (co->indices != NULL) - PyMem_Free(co->indices); - Py_TYPE(co)->tp_free(co); + PyObject_GC_UnTrack(co); + Py_XDECREF(co->pool); + Py_XDECREF(co->result); + if (co->indices != NULL) + PyMem_Free(co->indices); + Py_TYPE(co)->tp_free(co); } static int combinations_traverse(combinationsobject *co, visitproc visit, void *arg) { - Py_VISIT(co->pool); - Py_VISIT(co->result); - return 0; + Py_VISIT(co->pool); + Py_VISIT(co->result); + return 0; } static PyObject * combinations_next(combinationsobject *co) { - PyObject *elem; - PyObject *oldelem; - PyObject *pool = co->pool; - Py_ssize_t *indices = co->indices; - PyObject *result = co->result; - Py_ssize_t n = PyTuple_GET_SIZE(pool); - Py_ssize_t r = co->r; - Py_ssize_t i, j, index; - - if (co->stopped) - return NULL; - - if (result == NULL) { - /* On the first pass, initialize result tuple using the indices */ - result = PyTuple_New(r); - if (result == NULL) - goto empty; - co->result = result; - for (i=0; i 1) { - PyObject *old_result = result; - result = PyTuple_New(r); - if (result == NULL) - goto empty; - co->result = result; - for (i=0; i= 0 && indices[i] == i+n-r ; i--) - ; - - /* If i is negative, then the indices are all at - their maximum value and we're done. */ - if (i < 0) - goto empty; - - /* Increment the current index which we know is not at its - maximum. Then move back to the right setting each index - to its lowest possible value (one higher than the index - to its left -- this maintains the sort order invariant). */ - indices[i]++; - for (j=i+1 ; jpool; + Py_ssize_t *indices = co->indices; + PyObject *result = co->result; + Py_ssize_t n = PyTuple_GET_SIZE(pool); + Py_ssize_t r = co->r; + Py_ssize_t i, j, index; + + if (co->stopped) + return NULL; + + if (result == NULL) { + /* On the first pass, initialize result tuple using the indices */ + result = PyTuple_New(r); + if (result == NULL) + goto empty; + co->result = result; + for (i=0; i 1) { + PyObject *old_result = result; + result = PyTuple_New(r); + if (result == NULL) + goto empty; + co->result = result; + for (i=0; i= 0 && indices[i] == i+n-r ; i--) + ; + + /* If i is negative, then the indices are all at + their maximum value and we're done. */ + if (i < 0) + goto empty; + + /* Increment the current index which we know is not at its + maximum. Then move back to the right setting each index + to its lowest possible value (one higher than the index + to its left -- this maintains the sort order invariant). */ + indices[i]++; + for (j=i+1 ; jstopped = 1; - return NULL; + co->stopped = 1; + return NULL; } PyDoc_STRVAR(combinations_doc, @@ -2023,47 +2023,47 @@ combinations(range(4), 3) --> (0,1,2), (0,1,3), (0,2,3), (1,2,3)"); static PyTypeObject combinations_type = { - PyVarObject_HEAD_INIT(NULL, 0) - "itertools.combinations", /* tp_name */ - sizeof(combinationsobject), /* tp_basicsize */ - 0, /* tp_itemsize */ - /* methods */ - (destructor)combinations_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 | - Py_TPFLAGS_BASETYPE, /* tp_flags */ - combinations_doc, /* tp_doc */ - (traverseproc)combinations_traverse, /* tp_traverse */ - 0, /* tp_clear */ - 0, /* tp_richcompare */ - 0, /* tp_weaklistoffset */ - PyObject_SelfIter, /* tp_iter */ - (iternextfunc)combinations_next, /* tp_iternext */ - 0, /* tp_methods */ - 0, /* tp_members */ - 0, /* tp_getset */ - 0, /* tp_base */ - 0, /* tp_dict */ - 0, /* tp_descr_get */ - 0, /* tp_descr_set */ - 0, /* tp_dictoffset */ - 0, /* tp_init */ - 0, /* tp_alloc */ - combinations_new, /* tp_new */ - PyObject_GC_Del, /* tp_free */ + PyVarObject_HEAD_INIT(NULL, 0) + "itertools.combinations", /* tp_name */ + sizeof(combinationsobject), /* tp_basicsize */ + 0, /* tp_itemsize */ + /* methods */ + (destructor)combinations_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 | + Py_TPFLAGS_BASETYPE, /* tp_flags */ + combinations_doc, /* tp_doc */ + (traverseproc)combinations_traverse, /* tp_traverse */ + 0, /* tp_clear */ + 0, /* tp_richcompare */ + 0, /* tp_weaklistoffset */ + PyObject_SelfIter, /* tp_iter */ + (iternextfunc)combinations_next, /* tp_iternext */ + 0, /* tp_methods */ + 0, /* tp_members */ + 0, /* tp_getset */ + 0, /* tp_base */ + 0, /* tp_dict */ + 0, /* tp_descr_get */ + 0, /* tp_descr_set */ + 0, /* tp_dictoffset */ + 0, /* tp_init */ + 0, /* tp_alloc */ + combinations_new, /* tp_new */ + PyObject_GC_Del, /* tp_free */ }; @@ -2071,37 +2071,37 @@ /* Equivalent to: - def combinations_with_replacement(iterable, r): - "combinations_with_replacement('ABC', 2) --> AA AB AC BB BC CC" - # number items returned: (n+r-1)! / r! / (n-1)! - pool = tuple(iterable) - n = len(pool) - indices = [0] * r - yield tuple(pool[i] for i in indices) - while 1: - for i in reversed(range(r)): - if indices[i] != n - 1: - break - else: - return - indices[i:] = [indices[i] + 1] * (r - i) - yield tuple(pool[i] for i in indices) - - def combinations_with_replacement2(iterable, r): - 'Alternate version that filters from product()' - pool = tuple(iterable) - n = len(pool) - for indices in product(range(n), repeat=r): - if sorted(indices) == list(indices): - yield tuple(pool[i] for i in indices) + def combinations_with_replacement(iterable, r): + "combinations_with_replacement('ABC', 2) --> AA AB AC BB BC CC" + # number items returned: (n+r-1)! / r! / (n-1)! + pool = tuple(iterable) + n = len(pool) + indices = [0] * r + yield tuple(pool[i] for i in indices) + while 1: + for i in reversed(range(r)): + if indices[i] != n - 1: + break + else: + return + indices[i:] = [indices[i] + 1] * (r - i) + yield tuple(pool[i] for i in indices) + + def combinations_with_replacement2(iterable, r): + 'Alternate version that filters from product()' + pool = tuple(iterable) + n = len(pool) + for indices in product(range(n), repeat=r): + if sorted(indices) == list(indices): + yield tuple(pool[i] for i in indices) */ typedef struct { - PyObject_HEAD - PyObject *pool; /* input converted to a tuple */ - Py_ssize_t *indices; /* one index per result element */ - PyObject *result; /* most recently returned result tuple */ - Py_ssize_t r; /* size of result tuple */ - int stopped; /* set to 1 when the cwr iterator is exhausted */ + PyObject_HEAD + PyObject *pool; /* input converted to a tuple */ + Py_ssize_t *indices; /* one index per result element */ + PyObject *result; /* most recently returned result tuple */ + Py_ssize_t r; /* size of result tuple */ + int stopped; /* set to 1 when the cwr iterator is exhausted */ } cwrobject; static PyTypeObject cwr_type; @@ -2109,156 +2109,156 @@ static PyObject * cwr_new(PyTypeObject *type, PyObject *args, PyObject *kwds) { - cwrobject *co; - Py_ssize_t n; - Py_ssize_t r; - PyObject *pool = NULL; - PyObject *iterable = NULL; - Py_ssize_t *indices = NULL; - Py_ssize_t i; - static char *kwargs[] = {"iterable", "r", NULL}; - - if (!PyArg_ParseTupleAndKeywords(args, kwds, "On:combinations_with_replacement", kwargs, - &iterable, &r)) - return NULL; - - pool = PySequence_Tuple(iterable); - if (pool == NULL) - goto error; - n = PyTuple_GET_SIZE(pool); - if (r < 0) { - PyErr_SetString(PyExc_ValueError, "r must be non-negative"); - goto error; - } - - indices = PyMem_Malloc(r * sizeof(Py_ssize_t)); - if (indices == NULL) { - PyErr_NoMemory(); - goto error; - } - - for (i=0 ; itp_alloc(type, 0); - if (co == NULL) - goto error; - - co->pool = pool; - co->indices = indices; - co->result = NULL; - co->r = r; - co->stopped = !n && r; + cwrobject *co; + Py_ssize_t n; + Py_ssize_t r; + PyObject *pool = NULL; + PyObject *iterable = NULL; + Py_ssize_t *indices = NULL; + Py_ssize_t i; + static char *kwargs[] = {"iterable", "r", NULL}; + + if (!PyArg_ParseTupleAndKeywords(args, kwds, "On:combinations_with_replacement", kwargs, + &iterable, &r)) + return NULL; + + pool = PySequence_Tuple(iterable); + if (pool == NULL) + goto error; + n = PyTuple_GET_SIZE(pool); + if (r < 0) { + PyErr_SetString(PyExc_ValueError, "r must be non-negative"); + goto error; + } + + indices = PyMem_Malloc(r * sizeof(Py_ssize_t)); + if (indices == NULL) { + PyErr_NoMemory(); + goto error; + } + + for (i=0 ; itp_alloc(type, 0); + if (co == NULL) + goto error; + + co->pool = pool; + co->indices = indices; + co->result = NULL; + co->r = r; + co->stopped = !n && r; - return (PyObject *)co; + return (PyObject *)co; error: - if (indices != NULL) - PyMem_Free(indices); - Py_XDECREF(pool); - return NULL; + if (indices != NULL) + PyMem_Free(indices); + Py_XDECREF(pool); + return NULL; } static void cwr_dealloc(cwrobject *co) { - PyObject_GC_UnTrack(co); - Py_XDECREF(co->pool); - Py_XDECREF(co->result); - if (co->indices != NULL) - PyMem_Free(co->indices); - Py_TYPE(co)->tp_free(co); + PyObject_GC_UnTrack(co); + Py_XDECREF(co->pool); + Py_XDECREF(co->result); + if (co->indices != NULL) + PyMem_Free(co->indices); + Py_TYPE(co)->tp_free(co); } static int cwr_traverse(cwrobject *co, visitproc visit, void *arg) { - Py_VISIT(co->pool); - Py_VISIT(co->result); - return 0; + Py_VISIT(co->pool); + Py_VISIT(co->result); + return 0; } static PyObject * cwr_next(cwrobject *co) { - PyObject *elem; - PyObject *oldelem; - PyObject *pool = co->pool; - Py_ssize_t *indices = co->indices; - PyObject *result = co->result; - Py_ssize_t n = PyTuple_GET_SIZE(pool); - Py_ssize_t r = co->r; - Py_ssize_t i, j, index; - - if (co->stopped) - return NULL; - - if (result == NULL) { - /* On the first pass, initialize result tuple using the indices */ - result = PyTuple_New(r); - if (result == NULL) - goto empty; - co->result = result; - for (i=0; i 1) { - PyObject *old_result = result; - result = PyTuple_New(r); - if (result == NULL) - goto empty; - co->result = result; - for (i=0; i= 0 && indices[i] == n-1; i--) - ; - - /* If i is negative, then the indices are all at - their maximum value and we're done. */ - if (i < 0) - goto empty; - - /* Increment the current index which we know is not at its - maximum. Then set all to the right to the same value. */ - indices[i]++; - for (j=i+1 ; jpool; + Py_ssize_t *indices = co->indices; + PyObject *result = co->result; + Py_ssize_t n = PyTuple_GET_SIZE(pool); + Py_ssize_t r = co->r; + Py_ssize_t i, j, index; + + if (co->stopped) + return NULL; + + if (result == NULL) { + /* On the first pass, initialize result tuple using the indices */ + result = PyTuple_New(r); + if (result == NULL) + goto empty; + co->result = result; + for (i=0; i 1) { + PyObject *old_result = result; + result = PyTuple_New(r); + if (result == NULL) + goto empty; + co->result = result; + for (i=0; i= 0 && indices[i] == n-1; i--) + ; + + /* If i is negative, then the indices are all at + their maximum value and we're done. */ + if (i < 0) + goto empty; + + /* Increment the current index which we know is not at its + maximum. Then set all to the right to the same value. */ + indices[i]++; + for (j=i+1 ; jstopped = 1; - return NULL; + co->stopped = 1; + return NULL; } PyDoc_STRVAR(cwr_doc, @@ -2269,52 +2269,52 @@ combinations_with_replacement('ABC', 2) --> AA AB AC BB BC CC"); static PyTypeObject cwr_type = { - PyVarObject_HEAD_INIT(NULL, 0) - "itertools.combinations_with_replacement", /* tp_name */ - sizeof(cwrobject), /* tp_basicsize */ - 0, /* tp_itemsize */ - /* methods */ - (destructor)cwr_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 | - Py_TPFLAGS_BASETYPE, /* tp_flags */ - cwr_doc, /* tp_doc */ - (traverseproc)cwr_traverse, /* tp_traverse */ - 0, /* tp_clear */ - 0, /* tp_richcompare */ - 0, /* tp_weaklistoffset */ - PyObject_SelfIter, /* tp_iter */ - (iternextfunc)cwr_next, /* tp_iternext */ - 0, /* tp_methods */ - 0, /* tp_members */ - 0, /* tp_getset */ - 0, /* tp_base */ - 0, /* tp_dict */ - 0, /* tp_descr_get */ - 0, /* tp_descr_set */ - 0, /* tp_dictoffset */ - 0, /* tp_init */ - 0, /* tp_alloc */ - cwr_new, /* tp_new */ - PyObject_GC_Del, /* tp_free */ + PyVarObject_HEAD_INIT(NULL, 0) + "itertools.combinations_with_replacement", /* tp_name */ + sizeof(cwrobject), /* tp_basicsize */ + 0, /* tp_itemsize */ + /* methods */ + (destructor)cwr_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 | + Py_TPFLAGS_BASETYPE, /* tp_flags */ + cwr_doc, /* tp_doc */ + (traverseproc)cwr_traverse, /* tp_traverse */ + 0, /* tp_clear */ + 0, /* tp_richcompare */ + 0, /* tp_weaklistoffset */ + PyObject_SelfIter, /* tp_iter */ + (iternextfunc)cwr_next, /* tp_iternext */ + 0, /* tp_methods */ + 0, /* tp_members */ + 0, /* tp_getset */ + 0, /* tp_base */ + 0, /* tp_dict */ + 0, /* tp_descr_get */ + 0, /* tp_descr_set */ + 0, /* tp_dictoffset */ + 0, /* tp_init */ + 0, /* tp_alloc */ + cwr_new, /* tp_new */ + PyObject_GC_Del, /* tp_free */ }; /* permutations object ************************************************************ - + def permutations(iterable, r=None): 'permutations(range(3), 2) --> (0,1) (0,2) (1,0) (1,2) (2,0) (2,1)' pool = tuple(iterable) @@ -2324,28 +2324,28 @@ cycles = range(n-r+1, n+1)[::-1] yield tuple(pool[i] for i in indices[:r]) while n: - for i in reversed(range(r)): - cycles[i] -= 1 - if cycles[i] == 0: - indices[i:] = indices[i+1:] + indices[i:i+1] - cycles[i] = n - i - else: - j = cycles[i] - indices[i], indices[-j] = indices[-j], indices[i] - yield tuple(pool[i] for i in indices[:r]) - break + for i in reversed(range(r)): + cycles[i] -= 1 + if cycles[i] == 0: + indices[i:] = indices[i+1:] + indices[i:i+1] + cycles[i] = n - i else: - return + j = cycles[i] + indices[i], indices[-j] = indices[-j], indices[i] + yield tuple(pool[i] for i in indices[:r]) + break + else: + return */ typedef struct { - PyObject_HEAD - PyObject *pool; /* input converted to a tuple */ - Py_ssize_t *indices; /* one index per element in the pool */ - Py_ssize_t *cycles; /* one rollover counter per element in the result */ - PyObject *result; /* most recently returned result tuple */ - Py_ssize_t r; /* size of result tuple */ - int stopped; /* set to 1 when the permutations iterator is exhausted */ + PyObject_HEAD + PyObject *pool; /* input converted to a tuple */ + Py_ssize_t *indices; /* one index per element in the pool */ + Py_ssize_t *cycles; /* one rollover counter per element in the result */ + PyObject *result; /* most recently returned result tuple */ + Py_ssize_t r; /* size of result tuple */ + int stopped; /* set to 1 when the permutations iterator is exhausted */ } permutationsobject; static PyTypeObject permutations_type; @@ -2353,184 +2353,184 @@ static PyObject * permutations_new(PyTypeObject *type, PyObject *args, PyObject *kwds) { - permutationsobject *po; - Py_ssize_t n; - Py_ssize_t r; - PyObject *robj = Py_None; - PyObject *pool = NULL; - PyObject *iterable = NULL; - Py_ssize_t *indices = NULL; - Py_ssize_t *cycles = NULL; - Py_ssize_t i; - static char *kwargs[] = {"iterable", "r", NULL}; - - if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|O:permutations", kwargs, - &iterable, &robj)) - return NULL; - - pool = PySequence_Tuple(iterable); - if (pool == NULL) - goto error; - n = PyTuple_GET_SIZE(pool); - - r = n; - if (robj != Py_None) { - if (!PyLong_Check(robj)) { - PyErr_SetString(PyExc_TypeError, "Expected int as r"); - goto error; - } - r = PyLong_AsSsize_t(robj); - if (r == -1 && PyErr_Occurred()) - goto error; - } - if (r < 0) { - PyErr_SetString(PyExc_ValueError, "r must be non-negative"); - goto error; - } - - indices = PyMem_Malloc(n * sizeof(Py_ssize_t)); - cycles = PyMem_Malloc(r * sizeof(Py_ssize_t)); - if (indices == NULL || cycles == NULL) { - PyErr_NoMemory(); - goto error; - } - - for (i=0 ; itp_alloc(type, 0); - if (po == NULL) - goto error; - - po->pool = pool; - po->indices = indices; - po->cycles = cycles; - po->result = NULL; - po->r = r; - po->stopped = r > n ? 1 : 0; + permutationsobject *po; + Py_ssize_t n; + Py_ssize_t r; + PyObject *robj = Py_None; + PyObject *pool = NULL; + PyObject *iterable = NULL; + Py_ssize_t *indices = NULL; + Py_ssize_t *cycles = NULL; + Py_ssize_t i; + static char *kwargs[] = {"iterable", "r", NULL}; + + if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|O:permutations", kwargs, + &iterable, &robj)) + return NULL; + + pool = PySequence_Tuple(iterable); + if (pool == NULL) + goto error; + n = PyTuple_GET_SIZE(pool); + + r = n; + if (robj != Py_None) { + if (!PyLong_Check(robj)) { + PyErr_SetString(PyExc_TypeError, "Expected int as r"); + goto error; + } + r = PyLong_AsSsize_t(robj); + if (r == -1 && PyErr_Occurred()) + goto error; + } + if (r < 0) { + PyErr_SetString(PyExc_ValueError, "r must be non-negative"); + goto error; + } + + indices = PyMem_Malloc(n * sizeof(Py_ssize_t)); + cycles = PyMem_Malloc(r * sizeof(Py_ssize_t)); + if (indices == NULL || cycles == NULL) { + PyErr_NoMemory(); + goto error; + } + + for (i=0 ; itp_alloc(type, 0); + if (po == NULL) + goto error; + + po->pool = pool; + po->indices = indices; + po->cycles = cycles; + po->result = NULL; + po->r = r; + po->stopped = r > n ? 1 : 0; - return (PyObject *)po; + return (PyObject *)po; error: - if (indices != NULL) - PyMem_Free(indices); - if (cycles != NULL) - PyMem_Free(cycles); - Py_XDECREF(pool); - return NULL; + if (indices != NULL) + PyMem_Free(indices); + if (cycles != NULL) + PyMem_Free(cycles); + Py_XDECREF(pool); + return NULL; } static void permutations_dealloc(permutationsobject *po) { - PyObject_GC_UnTrack(po); - Py_XDECREF(po->pool); - Py_XDECREF(po->result); - PyMem_Free(po->indices); - PyMem_Free(po->cycles); - Py_TYPE(po)->tp_free(po); + PyObject_GC_UnTrack(po); + Py_XDECREF(po->pool); + Py_XDECREF(po->result); + PyMem_Free(po->indices); + PyMem_Free(po->cycles); + Py_TYPE(po)->tp_free(po); } static int permutations_traverse(permutationsobject *po, visitproc visit, void *arg) { - Py_VISIT(po->pool); - Py_VISIT(po->result); - return 0; + Py_VISIT(po->pool); + Py_VISIT(po->result); + return 0; } static PyObject * permutations_next(permutationsobject *po) { - PyObject *elem; - PyObject *oldelem; - PyObject *pool = po->pool; - Py_ssize_t *indices = po->indices; - Py_ssize_t *cycles = po->cycles; - PyObject *result = po->result; - Py_ssize_t n = PyTuple_GET_SIZE(pool); - Py_ssize_t r = po->r; - Py_ssize_t i, j, k, index; - - if (po->stopped) - return NULL; - - if (result == NULL) { - /* On the first pass, initialize result tuple using the indices */ - result = PyTuple_New(r); - if (result == NULL) - goto empty; - po->result = result; - for (i=0; i 1) { - PyObject *old_result = result; - result = PyTuple_New(r); - if (result == NULL) - goto empty; - po->result = result; - for (i=0; i=0 ; i--) { - cycles[i] -= 1; - if (cycles[i] == 0) { - /* rotatation: indices[i:] = indices[i+1:] + indices[i:i+1] */ - index = indices[i]; - for (j=i ; jpool; + Py_ssize_t *indices = po->indices; + Py_ssize_t *cycles = po->cycles; + PyObject *result = po->result; + Py_ssize_t n = PyTuple_GET_SIZE(pool); + Py_ssize_t r = po->r; + Py_ssize_t i, j, k, index; + + if (po->stopped) + return NULL; + + if (result == NULL) { + /* On the first pass, initialize result tuple using the indices */ + result = PyTuple_New(r); + if (result == NULL) + goto empty; + po->result = result; + for (i=0; i 1) { + PyObject *old_result = result; + result = PyTuple_New(r); + if (result == NULL) + goto empty; + po->result = result; + for (i=0; i=0 ; i--) { + cycles[i] -= 1; + if (cycles[i] == 0) { + /* rotatation: indices[i:] = indices[i+1:] + indices[i:i+1] */ + index = indices[i]; + for (j=i ; jstopped = 1; - return NULL; + po->stopped = 1; + return NULL; } PyDoc_STRVAR(permutations_doc, @@ -2540,47 +2540,47 @@ permutations(range(3), 2) --> (0,1), (0,2), (1,0), (1,2), (2,0), (2,1)"); static PyTypeObject permutations_type = { - PyVarObject_HEAD_INIT(NULL, 0) - "itertools.permutations", /* tp_name */ - sizeof(permutationsobject), /* tp_basicsize */ - 0, /* tp_itemsize */ - /* methods */ - (destructor)permutations_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 | - Py_TPFLAGS_BASETYPE, /* tp_flags */ - permutations_doc, /* tp_doc */ - (traverseproc)permutations_traverse, /* tp_traverse */ - 0, /* tp_clear */ - 0, /* tp_richcompare */ - 0, /* tp_weaklistoffset */ - PyObject_SelfIter, /* tp_iter */ - (iternextfunc)permutations_next, /* tp_iternext */ - 0, /* tp_methods */ - 0, /* tp_members */ - 0, /* tp_getset */ - 0, /* tp_base */ - 0, /* tp_dict */ - 0, /* tp_descr_get */ - 0, /* tp_descr_set */ - 0, /* tp_dictoffset */ - 0, /* tp_init */ - 0, /* tp_alloc */ - permutations_new, /* tp_new */ - PyObject_GC_Del, /* tp_free */ + PyVarObject_HEAD_INIT(NULL, 0) + "itertools.permutations", /* tp_name */ + sizeof(permutationsobject), /* tp_basicsize */ + 0, /* tp_itemsize */ + /* methods */ + (destructor)permutations_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 | + Py_TPFLAGS_BASETYPE, /* tp_flags */ + permutations_doc, /* tp_doc */ + (traverseproc)permutations_traverse, /* tp_traverse */ + 0, /* tp_clear */ + 0, /* tp_richcompare */ + 0, /* tp_weaklistoffset */ + PyObject_SelfIter, /* tp_iter */ + (iternextfunc)permutations_next, /* tp_iternext */ + 0, /* tp_methods */ + 0, /* tp_members */ + 0, /* tp_getset */ + 0, /* tp_base */ + 0, /* tp_dict */ + 0, /* tp_descr_get */ + 0, /* tp_descr_set */ + 0, /* tp_dictoffset */ + 0, /* tp_init */ + 0, /* tp_alloc */ + permutations_new, /* tp_new */ + PyObject_GC_Del, /* tp_free */ }; @@ -2588,15 +2588,15 @@ /* Equivalent to: - def compress(data, selectors): - "compress('ABCDEF', [1,0,1,0,1,1]) --> A C E F" - return (d for d, s in zip(data, selectors) if s) + def compress(data, selectors): + "compress('ABCDEF', [1,0,1,0,1,1]) --> A C E F" + return (d for d, s in zip(data, selectors) if s) */ typedef struct { - PyObject_HEAD - PyObject *data; - PyObject *selectors; + PyObject_HEAD + PyObject *data; + PyObject *selectors; } compressobject; static PyTypeObject compress_type; @@ -2604,86 +2604,86 @@ static PyObject * compress_new(PyTypeObject *type, PyObject *args, PyObject *kwds) { - PyObject *seq1, *seq2; - PyObject *data=NULL, *selectors=NULL; - compressobject *lz; - static char *kwargs[] = {"data", "selectors", NULL}; - - if (!PyArg_ParseTupleAndKeywords(args, kwds, "OO:compress", kwargs, &seq1, &seq2)) - return NULL; - - data = PyObject_GetIter(seq1); - if (data == NULL) - goto fail; - selectors = PyObject_GetIter(seq2); - if (selectors == NULL) - goto fail; - - /* create compressobject structure */ - lz = (compressobject *)type->tp_alloc(type, 0); - if (lz == NULL) - goto fail; - lz->data = data; - lz->selectors = selectors; - return (PyObject *)lz; + PyObject *seq1, *seq2; + PyObject *data=NULL, *selectors=NULL; + compressobject *lz; + static char *kwargs[] = {"data", "selectors", NULL}; + + if (!PyArg_ParseTupleAndKeywords(args, kwds, "OO:compress", kwargs, &seq1, &seq2)) + return NULL; + + data = PyObject_GetIter(seq1); + if (data == NULL) + goto fail; + selectors = PyObject_GetIter(seq2); + if (selectors == NULL) + goto fail; + + /* create compressobject structure */ + lz = (compressobject *)type->tp_alloc(type, 0); + if (lz == NULL) + goto fail; + lz->data = data; + lz->selectors = selectors; + return (PyObject *)lz; fail: - Py_XDECREF(data); - Py_XDECREF(selectors); - return NULL; + Py_XDECREF(data); + Py_XDECREF(selectors); + return NULL; } static void compress_dealloc(compressobject *lz) { - PyObject_GC_UnTrack(lz); - Py_XDECREF(lz->data); - Py_XDECREF(lz->selectors); - Py_TYPE(lz)->tp_free(lz); + PyObject_GC_UnTrack(lz); + Py_XDECREF(lz->data); + Py_XDECREF(lz->selectors); + Py_TYPE(lz)->tp_free(lz); } static int compress_traverse(compressobject *lz, visitproc visit, void *arg) { - Py_VISIT(lz->data); - Py_VISIT(lz->selectors); - return 0; + Py_VISIT(lz->data); + Py_VISIT(lz->selectors); + return 0; } static PyObject * compress_next(compressobject *lz) { - PyObject *data = lz->data, *selectors = lz->selectors; - PyObject *datum, *selector; - PyObject *(*datanext)(PyObject *) = *Py_TYPE(data)->tp_iternext; - PyObject *(*selectornext)(PyObject *) = *Py_TYPE(selectors)->tp_iternext; - int ok; - - while (1) { - /* Steps: get datum, get selector, evaluate selector. - Order is important (to match the pure python version - in terms of which input gets a chance to raise an - exception first). - */ - - datum = datanext(data); - if (datum == NULL) - return NULL; - - selector = selectornext(selectors); - if (selector == NULL) { - Py_DECREF(datum); - return NULL; - } - - ok = PyObject_IsTrue(selector); - Py_DECREF(selector); - if (ok == 1) - return datum; - Py_DECREF(datum); - if (ok == -1) - return NULL; - } + PyObject *data = lz->data, *selectors = lz->selectors; + PyObject *datum, *selector; + PyObject *(*datanext)(PyObject *) = *Py_TYPE(data)->tp_iternext; + PyObject *(*selectornext)(PyObject *) = *Py_TYPE(selectors)->tp_iternext; + int ok; + + while (1) { + /* Steps: get datum, get selector, evaluate selector. + Order is important (to match the pure python version + in terms of which input gets a chance to raise an + exception first). + */ + + datum = datanext(data); + if (datum == NULL) + return NULL; + + selector = selectornext(selectors); + if (selector == NULL) { + Py_DECREF(datum); + return NULL; + } + + ok = PyObject_IsTrue(selector); + Py_DECREF(selector); + if (ok == 1) + return datum; + Py_DECREF(datum); + if (ok == -1) + return NULL; + } } PyDoc_STRVAR(compress_doc, @@ -2694,56 +2694,56 @@ selectors to choose the data elements."); static PyTypeObject compress_type = { - PyVarObject_HEAD_INIT(NULL, 0) - "itertools.compress", /* tp_name */ - sizeof(compressobject), /* tp_basicsize */ - 0, /* tp_itemsize */ - /* methods */ - (destructor)compress_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 | - Py_TPFLAGS_BASETYPE, /* tp_flags */ - compress_doc, /* tp_doc */ - (traverseproc)compress_traverse, /* tp_traverse */ - 0, /* tp_clear */ - 0, /* tp_richcompare */ - 0, /* tp_weaklistoffset */ - PyObject_SelfIter, /* tp_iter */ - (iternextfunc)compress_next, /* tp_iternext */ - 0, /* tp_methods */ - 0, /* tp_members */ - 0, /* tp_getset */ - 0, /* tp_base */ - 0, /* tp_dict */ - 0, /* tp_descr_get */ - 0, /* tp_descr_set */ - 0, /* tp_dictoffset */ - 0, /* tp_init */ - 0, /* tp_alloc */ - compress_new, /* tp_new */ - PyObject_GC_Del, /* tp_free */ + PyVarObject_HEAD_INIT(NULL, 0) + "itertools.compress", /* tp_name */ + sizeof(compressobject), /* tp_basicsize */ + 0, /* tp_itemsize */ + /* methods */ + (destructor)compress_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 | + Py_TPFLAGS_BASETYPE, /* tp_flags */ + compress_doc, /* tp_doc */ + (traverseproc)compress_traverse, /* tp_traverse */ + 0, /* tp_clear */ + 0, /* tp_richcompare */ + 0, /* tp_weaklistoffset */ + PyObject_SelfIter, /* tp_iter */ + (iternextfunc)compress_next, /* tp_iternext */ + 0, /* tp_methods */ + 0, /* tp_members */ + 0, /* tp_getset */ + 0, /* tp_base */ + 0, /* tp_dict */ + 0, /* tp_descr_get */ + 0, /* tp_descr_set */ + 0, /* tp_dictoffset */ + 0, /* tp_init */ + 0, /* tp_alloc */ + compress_new, /* tp_new */ + PyObject_GC_Del, /* tp_free */ }; /* filterfalse object ************************************************************/ typedef struct { - PyObject_HEAD - PyObject *func; - PyObject *it; + PyObject_HEAD + PyObject *func; + PyObject *it; } filterfalseobject; static PyTypeObject filterfalse_type; @@ -2751,83 +2751,83 @@ static PyObject * filterfalse_new(PyTypeObject *type, PyObject *args, PyObject *kwds) { - PyObject *func, *seq; - PyObject *it; - filterfalseobject *lz; - - if (type == &filterfalse_type && - !_PyArg_NoKeywords("filterfalse()", kwds)) - return NULL; - - if (!PyArg_UnpackTuple(args, "filterfalse", 2, 2, &func, &seq)) - return NULL; - - /* Get iterator. */ - it = PyObject_GetIter(seq); - if (it == NULL) - return NULL; - - /* create filterfalseobject structure */ - lz = (filterfalseobject *)type->tp_alloc(type, 0); - if (lz == NULL) { - Py_DECREF(it); - return NULL; - } - Py_INCREF(func); - lz->func = func; - lz->it = it; + PyObject *func, *seq; + PyObject *it; + filterfalseobject *lz; + + if (type == &filterfalse_type && + !_PyArg_NoKeywords("filterfalse()", kwds)) + return NULL; + + if (!PyArg_UnpackTuple(args, "filterfalse", 2, 2, &func, &seq)) + return NULL; + + /* Get iterator. */ + it = PyObject_GetIter(seq); + if (it == NULL) + return NULL; + + /* create filterfalseobject structure */ + lz = (filterfalseobject *)type->tp_alloc(type, 0); + if (lz == NULL) { + Py_DECREF(it); + return NULL; + } + Py_INCREF(func); + lz->func = func; + lz->it = it; - return (PyObject *)lz; + return (PyObject *)lz; } static void filterfalse_dealloc(filterfalseobject *lz) { - PyObject_GC_UnTrack(lz); - Py_XDECREF(lz->func); - Py_XDECREF(lz->it); - Py_TYPE(lz)->tp_free(lz); + PyObject_GC_UnTrack(lz); + Py_XDECREF(lz->func); + Py_XDECREF(lz->it); + Py_TYPE(lz)->tp_free(lz); } static int filterfalse_traverse(filterfalseobject *lz, visitproc visit, void *arg) { - Py_VISIT(lz->it); - Py_VISIT(lz->func); - return 0; + Py_VISIT(lz->it); + Py_VISIT(lz->func); + return 0; } static PyObject * filterfalse_next(filterfalseobject *lz) { - PyObject *item; - PyObject *it = lz->it; - long ok; - PyObject *(*iternext)(PyObject *); - - iternext = *Py_TYPE(it)->tp_iternext; - for (;;) { - item = iternext(it); - if (item == NULL) - return NULL; - - if (lz->func == Py_None || lz->func == (PyObject *)&PyBool_Type) { - ok = PyObject_IsTrue(item); - } else { - PyObject *good; - good = PyObject_CallFunctionObjArgs(lz->func, - item, NULL); - if (good == NULL) { - Py_DECREF(item); - return NULL; - } - ok = PyObject_IsTrue(good); - Py_DECREF(good); - } - if (!ok) - return item; - Py_DECREF(item); - } + PyObject *item; + PyObject *it = lz->it; + long ok; + PyObject *(*iternext)(PyObject *); + + iternext = *Py_TYPE(it)->tp_iternext; + for (;;) { + item = iternext(it); + if (item == NULL) + return NULL; + + if (lz->func == Py_None || lz->func == (PyObject *)&PyBool_Type) { + ok = PyObject_IsTrue(item); + } else { + PyObject *good; + good = PyObject_CallFunctionObjArgs(lz->func, + item, NULL); + if (good == NULL) { + Py_DECREF(item); + return NULL; + } + ok = PyObject_IsTrue(good); + Py_DECREF(good); + } + if (!ok) + return item; + Py_DECREF(item); + } } PyDoc_STRVAR(filterfalse_doc, @@ -2837,74 +2837,74 @@ If function is None, return the items that are false."); static PyTypeObject filterfalse_type = { - PyVarObject_HEAD_INIT(NULL, 0) - "itertools.filterfalse", /* tp_name */ - sizeof(filterfalseobject), /* tp_basicsize */ - 0, /* tp_itemsize */ - /* methods */ - (destructor)filterfalse_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 | - Py_TPFLAGS_BASETYPE, /* tp_flags */ - filterfalse_doc, /* tp_doc */ - (traverseproc)filterfalse_traverse, /* tp_traverse */ - 0, /* tp_clear */ - 0, /* tp_richcompare */ - 0, /* tp_weaklistoffset */ - PyObject_SelfIter, /* tp_iter */ - (iternextfunc)filterfalse_next, /* tp_iternext */ - 0, /* tp_methods */ - 0, /* tp_members */ - 0, /* tp_getset */ - 0, /* tp_base */ - 0, /* tp_dict */ - 0, /* tp_descr_get */ - 0, /* tp_descr_set */ - 0, /* tp_dictoffset */ - 0, /* tp_init */ - 0, /* tp_alloc */ - filterfalse_new, /* tp_new */ - PyObject_GC_Del, /* tp_free */ + PyVarObject_HEAD_INIT(NULL, 0) + "itertools.filterfalse", /* tp_name */ + sizeof(filterfalseobject), /* tp_basicsize */ + 0, /* tp_itemsize */ + /* methods */ + (destructor)filterfalse_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 | + Py_TPFLAGS_BASETYPE, /* tp_flags */ + filterfalse_doc, /* tp_doc */ + (traverseproc)filterfalse_traverse, /* tp_traverse */ + 0, /* tp_clear */ + 0, /* tp_richcompare */ + 0, /* tp_weaklistoffset */ + PyObject_SelfIter, /* tp_iter */ + (iternextfunc)filterfalse_next, /* tp_iternext */ + 0, /* tp_methods */ + 0, /* tp_members */ + 0, /* tp_getset */ + 0, /* tp_base */ + 0, /* tp_dict */ + 0, /* tp_descr_get */ + 0, /* tp_descr_set */ + 0, /* tp_dictoffset */ + 0, /* tp_init */ + 0, /* tp_alloc */ + filterfalse_new, /* tp_new */ + PyObject_GC_Del, /* tp_free */ }; /* count object ************************************************************/ typedef struct { - PyObject_HEAD - Py_ssize_t cnt; - PyObject *long_cnt; - PyObject *long_step; + PyObject_HEAD + Py_ssize_t cnt; + PyObject *long_cnt; + PyObject *long_step; } countobject; /* Counting logic and invariants: fast_mode: when cnt an integer < PY_SSIZE_T_MAX and no step is specified. - assert(cnt != PY_SSIZE_T_MAX && long_cnt == NULL && long_step==PyInt(1)); - Advances with: cnt += 1 - When count hits Y_SSIZE_T_MAX, switch to slow_mode. + assert(cnt != PY_SSIZE_T_MAX && long_cnt == NULL && long_step==PyInt(1)); + Advances with: cnt += 1 + When count hits Y_SSIZE_T_MAX, switch to slow_mode. slow_mode: when cnt == PY_SSIZE_T_MAX, step is not int(1), or cnt is a float. - assert(cnt == PY_SSIZE_T_MAX && long_cnt != NULL && long_step != NULL); - All counting is done with python objects (no overflows or underflows). - Advances with: long_cnt += long_step - Step may be zero -- effectively a slow version of repeat(cnt). - Either long_cnt or long_step may be a float, Fraction, or Decimal. + assert(cnt == PY_SSIZE_T_MAX && long_cnt != NULL && long_step != NULL); + All counting is done with python objects (no overflows or underflows). + Advances with: long_cnt += long_step + Step may be zero -- effectively a slow version of repeat(cnt). + Either long_cnt or long_step may be a float, Fraction, or Decimal. */ static PyTypeObject count_type; @@ -2912,221 +2912,221 @@ static PyObject * count_new(PyTypeObject *type, PyObject *args, PyObject *kwds) { - countobject *lz; - int slow_mode = 0; - Py_ssize_t cnt = 0; - PyObject *long_cnt = NULL; - PyObject *long_step = NULL; - static char *kwlist[] = {"start", "step", 0}; - - if (!PyArg_ParseTupleAndKeywords(args, kwds, "|OO:count", - kwlist, &long_cnt, &long_step)) - return NULL; - - if ((long_cnt != NULL && !PyNumber_Check(long_cnt)) || - (long_step != NULL && !PyNumber_Check(long_step))) { - PyErr_SetString(PyExc_TypeError, "a number is required"); - return NULL; - } - - if (long_cnt != NULL) { - cnt = PyLong_AsSsize_t(long_cnt); - if ((cnt == -1 && PyErr_Occurred()) || !PyLong_Check(long_cnt)) { - PyErr_Clear(); - slow_mode = 1; - } - Py_INCREF(long_cnt); - } else { - cnt = 0; - long_cnt = PyLong_FromLong(0); - } - - /* If not specified, step defaults to 1 */ - if (long_step == NULL) { - long_step = PyLong_FromLong(1); - if (long_step == NULL) { - Py_DECREF(long_cnt); - return NULL; - } - } else - Py_INCREF(long_step); - - assert(long_cnt != NULL && long_step != NULL); - - /* Fast mode only works when the step is 1 */ - if (!PyLong_Check(long_step) || - PyLong_AS_LONG(long_step) != 1) { - slow_mode = 1; - } - - if (slow_mode) - cnt = PY_SSIZE_T_MAX; - else - Py_CLEAR(long_cnt); - - assert((cnt != PY_SSIZE_T_MAX && long_cnt == NULL && !slow_mode) || - (cnt == PY_SSIZE_T_MAX && long_cnt != NULL && slow_mode)); - assert(slow_mode || - (PyLong_Check(long_step) && PyLong_AS_LONG(long_step) == 1)); - - /* create countobject structure */ - lz = (countobject *)type->tp_alloc(type, 0); - if (lz == NULL) { - Py_XDECREF(long_cnt); - return NULL; - } - lz->cnt = cnt; - lz->long_cnt = long_cnt; - lz->long_step = long_step; + countobject *lz; + int slow_mode = 0; + Py_ssize_t cnt = 0; + PyObject *long_cnt = NULL; + PyObject *long_step = NULL; + static char *kwlist[] = {"start", "step", 0}; + + if (!PyArg_ParseTupleAndKeywords(args, kwds, "|OO:count", + kwlist, &long_cnt, &long_step)) + return NULL; + + if ((long_cnt != NULL && !PyNumber_Check(long_cnt)) || + (long_step != NULL && !PyNumber_Check(long_step))) { + PyErr_SetString(PyExc_TypeError, "a number is required"); + return NULL; + } + + if (long_cnt != NULL) { + cnt = PyLong_AsSsize_t(long_cnt); + if ((cnt == -1 && PyErr_Occurred()) || !PyLong_Check(long_cnt)) { + PyErr_Clear(); + slow_mode = 1; + } + Py_INCREF(long_cnt); + } else { + cnt = 0; + long_cnt = PyLong_FromLong(0); + } + + /* If not specified, step defaults to 1 */ + if (long_step == NULL) { + long_step = PyLong_FromLong(1); + if (long_step == NULL) { + Py_DECREF(long_cnt); + return NULL; + } + } else + Py_INCREF(long_step); - return (PyObject *)lz; + assert(long_cnt != NULL && long_step != NULL); + + /* Fast mode only works when the step is 1 */ + if (!PyLong_Check(long_step) || + PyLong_AS_LONG(long_step) != 1) { + slow_mode = 1; + } + + if (slow_mode) + cnt = PY_SSIZE_T_MAX; + else + Py_CLEAR(long_cnt); + + assert((cnt != PY_SSIZE_T_MAX && long_cnt == NULL && !slow_mode) || + (cnt == PY_SSIZE_T_MAX && long_cnt != NULL && slow_mode)); + assert(slow_mode || + (PyLong_Check(long_step) && PyLong_AS_LONG(long_step) == 1)); + + /* create countobject structure */ + lz = (countobject *)type->tp_alloc(type, 0); + if (lz == NULL) { + Py_XDECREF(long_cnt); + return NULL; + } + lz->cnt = cnt; + lz->long_cnt = long_cnt; + lz->long_step = long_step; + + return (PyObject *)lz; } static void count_dealloc(countobject *lz) { - PyObject_GC_UnTrack(lz); - Py_XDECREF(lz->long_cnt); - Py_XDECREF(lz->long_step); - Py_TYPE(lz)->tp_free(lz); + PyObject_GC_UnTrack(lz); + Py_XDECREF(lz->long_cnt); + Py_XDECREF(lz->long_step); + Py_TYPE(lz)->tp_free(lz); } static int count_traverse(countobject *lz, visitproc visit, void *arg) { - Py_VISIT(lz->long_cnt); - Py_VISIT(lz->long_step); - return 0; + Py_VISIT(lz->long_cnt); + Py_VISIT(lz->long_step); + return 0; } static PyObject * count_nextlong(countobject *lz) { - PyObject *long_cnt; - PyObject *stepped_up; + PyObject *long_cnt; + PyObject *stepped_up; - long_cnt = lz->long_cnt; - if (long_cnt == NULL) { - /* Switch to slow_mode */ - long_cnt = PyLong_FromSsize_t(PY_SSIZE_T_MAX); - if (long_cnt == NULL) - return NULL; - } - assert(lz->cnt == PY_SSIZE_T_MAX && long_cnt != NULL); - - stepped_up = PyNumber_Add(long_cnt, lz->long_step); - if (stepped_up == NULL) - return NULL; - lz->long_cnt = stepped_up; - return long_cnt; + long_cnt = lz->long_cnt; + if (long_cnt == NULL) { + /* Switch to slow_mode */ + long_cnt = PyLong_FromSsize_t(PY_SSIZE_T_MAX); + if (long_cnt == NULL) + return NULL; + } + assert(lz->cnt == PY_SSIZE_T_MAX && long_cnt != NULL); + + stepped_up = PyNumber_Add(long_cnt, lz->long_step); + if (stepped_up == NULL) + return NULL; + lz->long_cnt = stepped_up; + return long_cnt; } static PyObject * count_next(countobject *lz) { - if (lz->cnt == PY_SSIZE_T_MAX) - return count_nextlong(lz); - return PyLong_FromSsize_t(lz->cnt++); + if (lz->cnt == PY_SSIZE_T_MAX) + return count_nextlong(lz); + return PyLong_FromSsize_t(lz->cnt++); } static PyObject * count_repr(countobject *lz) { - if (lz->cnt != PY_SSIZE_T_MAX) - return PyUnicode_FromFormat("count(%zd)", lz->cnt); + if (lz->cnt != PY_SSIZE_T_MAX) + return PyUnicode_FromFormat("count(%zd)", lz->cnt); - if (PyLong_Check(lz->long_step)) { - long step = PyLong_AsLong(lz->long_step); - if (step == -1 && PyErr_Occurred()) { - PyErr_Clear(); - } - if (step == 1) { - /* Don't display step when it is an integer equal to 1 */ - return PyUnicode_FromFormat("count(%R)", lz->long_cnt); - } - } - return PyUnicode_FromFormat("count(%R, %R)", - lz->long_cnt, lz->long_step); + if (PyLong_Check(lz->long_step)) { + long step = PyLong_AsLong(lz->long_step); + if (step == -1 && PyErr_Occurred()) { + PyErr_Clear(); + } + if (step == 1) { + /* Don't display step when it is an integer equal to 1 */ + return PyUnicode_FromFormat("count(%R)", lz->long_cnt); + } + } + return PyUnicode_FromFormat("count(%R, %R)", + lz->long_cnt, lz->long_step); } static PyObject * count_reduce(countobject *lz) { - if (lz->cnt == PY_SSIZE_T_MAX) - return Py_BuildValue("O(OO)", Py_TYPE(lz), lz->long_cnt, lz->long_step); - return Py_BuildValue("O(n)", Py_TYPE(lz), lz->cnt); + if (lz->cnt == PY_SSIZE_T_MAX) + return Py_BuildValue("O(OO)", Py_TYPE(lz), lz->long_cnt, lz->long_step); + return Py_BuildValue("O(n)", Py_TYPE(lz), lz->cnt); } PyDoc_STRVAR(count_reduce_doc, "Return state information for pickling."); static PyMethodDef count_methods[] = { - {"__reduce__", (PyCFunction)count_reduce, METH_NOARGS, - count_reduce_doc}, - {NULL, NULL} /* sentinel */ + {"__reduce__", (PyCFunction)count_reduce, METH_NOARGS, + count_reduce_doc}, + {NULL, NULL} /* sentinel */ }; PyDoc_STRVAR(count_doc, - "count(start=0, step=1]) --> count object\n\ + "count(start=0, step=1]) --> count object\n\ \n\ Return a count object whose .__next__() method returns consecutive values.\n\ Equivalent to:\n\n\ def count(firstval=0, step=1):\n\ - x = firstval\n\ - while 1:\n\ - yield x\n\ - x += step\n"); + x = firstval\n\ + while 1:\n\ + yield x\n\ + x += step\n"); static PyTypeObject count_type = { - PyVarObject_HEAD_INIT(NULL, 0) - "itertools.count", /* tp_name */ - sizeof(countobject), /* tp_basicsize */ - 0, /* tp_itemsize */ - /* methods */ - (destructor)count_dealloc, /* tp_dealloc */ - 0, /* tp_print */ - 0, /* tp_getattr */ - 0, /* tp_setattr */ - 0, /* tp_reserved */ - (reprfunc)count_repr, /* 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 | - Py_TPFLAGS_BASETYPE, /* tp_flags */ - count_doc, /* tp_doc */ - (traverseproc)count_traverse, /* tp_traverse */ - 0, /* tp_clear */ - 0, /* tp_richcompare */ - 0, /* tp_weaklistoffset */ - PyObject_SelfIter, /* tp_iter */ - (iternextfunc)count_next, /* tp_iternext */ - count_methods, /* tp_methods */ - 0, /* tp_members */ - 0, /* tp_getset */ - 0, /* tp_base */ - 0, /* tp_dict */ - 0, /* tp_descr_get */ - 0, /* tp_descr_set */ - 0, /* tp_dictoffset */ - 0, /* tp_init */ - 0, /* tp_alloc */ - count_new, /* tp_new */ - PyObject_GC_Del, /* tp_free */ + PyVarObject_HEAD_INIT(NULL, 0) + "itertools.count", /* tp_name */ + sizeof(countobject), /* tp_basicsize */ + 0, /* tp_itemsize */ + /* methods */ + (destructor)count_dealloc, /* tp_dealloc */ + 0, /* tp_print */ + 0, /* tp_getattr */ + 0, /* tp_setattr */ + 0, /* tp_reserved */ + (reprfunc)count_repr, /* 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 | + Py_TPFLAGS_BASETYPE, /* tp_flags */ + count_doc, /* tp_doc */ + (traverseproc)count_traverse, /* tp_traverse */ + 0, /* tp_clear */ + 0, /* tp_richcompare */ + 0, /* tp_weaklistoffset */ + PyObject_SelfIter, /* tp_iter */ + (iternextfunc)count_next, /* tp_iternext */ + count_methods, /* tp_methods */ + 0, /* tp_members */ + 0, /* tp_getset */ + 0, /* tp_base */ + 0, /* tp_dict */ + 0, /* tp_descr_get */ + 0, /* tp_descr_set */ + 0, /* tp_dictoffset */ + 0, /* tp_init */ + 0, /* tp_alloc */ + count_new, /* tp_new */ + PyObject_GC_Del, /* tp_free */ }; /* repeat object ************************************************************/ typedef struct { - PyObject_HEAD - PyObject *element; - Py_ssize_t cnt; + PyObject_HEAD + PyObject *element; + Py_ssize_t cnt; } repeatobject; static PyTypeObject repeat_type; @@ -3134,77 +3134,77 @@ static PyObject * repeat_new(PyTypeObject *type, PyObject *args, PyObject *kwds) { - repeatobject *ro; - PyObject *element; - Py_ssize_t cnt = -1; - static char *kwargs[] = {"object", "times", NULL}; - - if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|n:repeat", kwargs, - &element, &cnt)) - return NULL; - - if (PyTuple_Size(args) == 2 && cnt < 0) - cnt = 0; - - ro = (repeatobject *)type->tp_alloc(type, 0); - if (ro == NULL) - return NULL; - Py_INCREF(element); - ro->element = element; - ro->cnt = cnt; - return (PyObject *)ro; + repeatobject *ro; + PyObject *element; + Py_ssize_t cnt = -1; + static char *kwargs[] = {"object", "times", NULL}; + + if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|n:repeat", kwargs, + &element, &cnt)) + return NULL; + + if (PyTuple_Size(args) == 2 && cnt < 0) + cnt = 0; + + ro = (repeatobject *)type->tp_alloc(type, 0); + if (ro == NULL) + return NULL; + Py_INCREF(element); + ro->element = element; + ro->cnt = cnt; + return (PyObject *)ro; } static void repeat_dealloc(repeatobject *ro) { - PyObject_GC_UnTrack(ro); - Py_XDECREF(ro->element); - Py_TYPE(ro)->tp_free(ro); + PyObject_GC_UnTrack(ro); + Py_XDECREF(ro->element); + Py_TYPE(ro)->tp_free(ro); } static int repeat_traverse(repeatobject *ro, visitproc visit, void *arg) { - Py_VISIT(ro->element); - return 0; + Py_VISIT(ro->element); + return 0; } static PyObject * repeat_next(repeatobject *ro) { - if (ro->cnt == 0) - return NULL; - if (ro->cnt > 0) - ro->cnt--; - Py_INCREF(ro->element); - return ro->element; + if (ro->cnt == 0) + return NULL; + if (ro->cnt > 0) + ro->cnt--; + Py_INCREF(ro->element); + return ro->element; } static PyObject * repeat_repr(repeatobject *ro) { - if (ro->cnt == -1) - return PyUnicode_FromFormat("repeat(%R)", ro->element); - else - return PyUnicode_FromFormat("repeat(%R, %zd)", ro->element, ro->cnt); -} + if (ro->cnt == -1) + return PyUnicode_FromFormat("repeat(%R)", ro->element); + else + return PyUnicode_FromFormat("repeat(%R, %zd)", ro->element, ro->cnt); +} static PyObject * repeat_len(repeatobject *ro) { - if (ro->cnt == -1) { - PyErr_SetString(PyExc_TypeError, "len() of unsized object"); - return NULL; - } - return PyLong_FromSize_t(ro->cnt); + if (ro->cnt == -1) { + PyErr_SetString(PyExc_TypeError, "len() of unsized object"); + return NULL; + } + return PyLong_FromSize_t(ro->cnt); } PyDoc_STRVAR(length_hint_doc, "Private method returning an estimate of len(list(it))."); static PyMethodDef repeat_methods[] = { - {"__length_hint__", (PyCFunction)repeat_len, METH_NOARGS, length_hint_doc}, - {NULL, NULL} /* sentinel */ + {"__length_hint__", (PyCFunction)repeat_len, METH_NOARGS, length_hint_doc}, + {NULL, NULL} /* sentinel */ }; PyDoc_STRVAR(repeat_doc, @@ -3213,47 +3213,47 @@ endlessly."); static PyTypeObject repeat_type = { - PyVarObject_HEAD_INIT(NULL, 0) - "itertools.repeat", /* tp_name */ - sizeof(repeatobject), /* tp_basicsize */ - 0, /* tp_itemsize */ - /* methods */ - (destructor)repeat_dealloc, /* tp_dealloc */ - 0, /* tp_print */ - 0, /* tp_getattr */ - 0, /* tp_setattr */ - 0, /* tp_reserved */ - (reprfunc)repeat_repr, /* 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 | - Py_TPFLAGS_BASETYPE, /* tp_flags */ - repeat_doc, /* tp_doc */ - (traverseproc)repeat_traverse, /* tp_traverse */ - 0, /* tp_clear */ - 0, /* tp_richcompare */ - 0, /* tp_weaklistoffset */ - PyObject_SelfIter, /* tp_iter */ - (iternextfunc)repeat_next, /* tp_iternext */ - repeat_methods, /* tp_methods */ - 0, /* tp_members */ - 0, /* tp_getset */ - 0, /* tp_base */ - 0, /* tp_dict */ - 0, /* tp_descr_get */ - 0, /* tp_descr_set */ - 0, /* tp_dictoffset */ - 0, /* tp_init */ - 0, /* tp_alloc */ - repeat_new, /* tp_new */ - PyObject_GC_Del, /* tp_free */ + PyVarObject_HEAD_INIT(NULL, 0) + "itertools.repeat", /* tp_name */ + sizeof(repeatobject), /* tp_basicsize */ + 0, /* tp_itemsize */ + /* methods */ + (destructor)repeat_dealloc, /* tp_dealloc */ + 0, /* tp_print */ + 0, /* tp_getattr */ + 0, /* tp_setattr */ + 0, /* tp_reserved */ + (reprfunc)repeat_repr, /* 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 | + Py_TPFLAGS_BASETYPE, /* tp_flags */ + repeat_doc, /* tp_doc */ + (traverseproc)repeat_traverse, /* tp_traverse */ + 0, /* tp_clear */ + 0, /* tp_richcompare */ + 0, /* tp_weaklistoffset */ + PyObject_SelfIter, /* tp_iter */ + (iternextfunc)repeat_next, /* tp_iternext */ + repeat_methods, /* tp_methods */ + 0, /* tp_members */ + 0, /* tp_getset */ + 0, /* tp_base */ + 0, /* tp_dict */ + 0, /* tp_descr_get */ + 0, /* tp_descr_set */ + 0, /* tp_dictoffset */ + 0, /* tp_init */ + 0, /* tp_alloc */ + repeat_new, /* tp_new */ + PyObject_GC_Del, /* tp_free */ }; /* ziplongest object ************************************************************/ @@ -3261,12 +3261,12 @@ #include "Python.h" typedef struct { - PyObject_HEAD - Py_ssize_t tuplesize; - Py_ssize_t numactive; - PyObject *ittuple; /* tuple of iterators */ - PyObject *result; - PyObject *fillvalue; + PyObject_HEAD + Py_ssize_t tuplesize; + Py_ssize_t numactive; + PyObject *ittuple; /* tuple of iterators */ + PyObject *result; + PyObject *fillvalue; } ziplongestobject; static PyTypeObject ziplongest_type; @@ -3274,159 +3274,159 @@ static PyObject * zip_longest_new(PyTypeObject *type, PyObject *args, PyObject *kwds) { - ziplongestobject *lz; - Py_ssize_t i; - PyObject *ittuple; /* tuple of iterators */ - PyObject *result; - PyObject *fillvalue = Py_None; - Py_ssize_t tuplesize = PySequence_Length(args); - - if (kwds != NULL && PyDict_CheckExact(kwds) && PyDict_Size(kwds) > 0) { - fillvalue = PyDict_GetItemString(kwds, "fillvalue"); - if (fillvalue == NULL || PyDict_Size(kwds) > 1) { - PyErr_SetString(PyExc_TypeError, - "zip_longest() got an unexpected keyword argument"); - return NULL; - } + ziplongestobject *lz; + Py_ssize_t i; + PyObject *ittuple; /* tuple of iterators */ + PyObject *result; + PyObject *fillvalue = Py_None; + Py_ssize_t tuplesize = PySequence_Length(args); + + if (kwds != NULL && PyDict_CheckExact(kwds) && PyDict_Size(kwds) > 0) { + fillvalue = PyDict_GetItemString(kwds, "fillvalue"); + if (fillvalue == NULL || PyDict_Size(kwds) > 1) { + PyErr_SetString(PyExc_TypeError, + "zip_longest() got an unexpected keyword argument"); + return NULL; } + } + + /* args must be a tuple */ + assert(PyTuple_Check(args)); - /* args must be a tuple */ - assert(PyTuple_Check(args)); + /* obtain iterators */ + ittuple = PyTuple_New(tuplesize); + if (ittuple == NULL) + return NULL; + for (i=0; i < tuplesize; ++i) { + PyObject *item = PyTuple_GET_ITEM(args, i); + PyObject *it = PyObject_GetIter(item); + if (it == NULL) { + if (PyErr_ExceptionMatches(PyExc_TypeError)) + PyErr_Format(PyExc_TypeError, + "zip_longest argument #%zd must support iteration", + i+1); + Py_DECREF(ittuple); + return NULL; + } + PyTuple_SET_ITEM(ittuple, i, it); + } - /* obtain iterators */ - ittuple = PyTuple_New(tuplesize); - if (ittuple == NULL) - return NULL; - for (i=0; i < tuplesize; ++i) { - PyObject *item = PyTuple_GET_ITEM(args, i); - PyObject *it = PyObject_GetIter(item); - if (it == NULL) { - if (PyErr_ExceptionMatches(PyExc_TypeError)) - PyErr_Format(PyExc_TypeError, - "zip_longest argument #%zd must support iteration", - i+1); - Py_DECREF(ittuple); - return NULL; - } - PyTuple_SET_ITEM(ittuple, i, it); - } - - /* create a result holder */ - result = PyTuple_New(tuplesize); - if (result == NULL) { - Py_DECREF(ittuple); - return NULL; - } - for (i=0 ; i < tuplesize ; i++) { - Py_INCREF(Py_None); - PyTuple_SET_ITEM(result, i, Py_None); - } - - /* create ziplongestobject structure */ - lz = (ziplongestobject *)type->tp_alloc(type, 0); - if (lz == NULL) { - Py_DECREF(ittuple); - Py_DECREF(result); - return NULL; - } - lz->ittuple = ittuple; - lz->tuplesize = tuplesize; - lz->numactive = tuplesize; - lz->result = result; - Py_INCREF(fillvalue); - lz->fillvalue = fillvalue; - return (PyObject *)lz; + /* create a result holder */ + result = PyTuple_New(tuplesize); + if (result == NULL) { + Py_DECREF(ittuple); + return NULL; + } + for (i=0 ; i < tuplesize ; i++) { + Py_INCREF(Py_None); + PyTuple_SET_ITEM(result, i, Py_None); + } + + /* create ziplongestobject structure */ + lz = (ziplongestobject *)type->tp_alloc(type, 0); + if (lz == NULL) { + Py_DECREF(ittuple); + Py_DECREF(result); + return NULL; + } + lz->ittuple = ittuple; + lz->tuplesize = tuplesize; + lz->numactive = tuplesize; + lz->result = result; + Py_INCREF(fillvalue); + lz->fillvalue = fillvalue; + return (PyObject *)lz; } static void zip_longest_dealloc(ziplongestobject *lz) { - PyObject_GC_UnTrack(lz); - Py_XDECREF(lz->ittuple); - Py_XDECREF(lz->result); - Py_XDECREF(lz->fillvalue); - Py_TYPE(lz)->tp_free(lz); + PyObject_GC_UnTrack(lz); + Py_XDECREF(lz->ittuple); + Py_XDECREF(lz->result); + Py_XDECREF(lz->fillvalue); + Py_TYPE(lz)->tp_free(lz); } static int zip_longest_traverse(ziplongestobject *lz, visitproc visit, void *arg) { - Py_VISIT(lz->ittuple); - Py_VISIT(lz->result); - Py_VISIT(lz->fillvalue); - return 0; + Py_VISIT(lz->ittuple); + Py_VISIT(lz->result); + Py_VISIT(lz->fillvalue); + return 0; } static PyObject * zip_longest_next(ziplongestobject *lz) { - Py_ssize_t i; - Py_ssize_t tuplesize = lz->tuplesize; - PyObject *result = lz->result; - PyObject *it; - PyObject *item; - PyObject *olditem; - - if (tuplesize == 0) - return NULL; - if (lz->numactive == 0) - return NULL; - if (Py_REFCNT(result) == 1) { - Py_INCREF(result); - for (i=0 ; i < tuplesize ; i++) { - it = PyTuple_GET_ITEM(lz->ittuple, i); - if (it == NULL) { - Py_INCREF(lz->fillvalue); - item = lz->fillvalue; - } else { - item = PyIter_Next(it); - if (item == NULL) { - lz->numactive -= 1; - if (lz->numactive == 0 || PyErr_Occurred()) { - lz->numactive = 0; - Py_DECREF(result); - return NULL; - } else { - Py_INCREF(lz->fillvalue); - item = lz->fillvalue; - PyTuple_SET_ITEM(lz->ittuple, i, NULL); - Py_DECREF(it); - } - } - } - olditem = PyTuple_GET_ITEM(result, i); - PyTuple_SET_ITEM(result, i, item); - Py_DECREF(olditem); + Py_ssize_t i; + Py_ssize_t tuplesize = lz->tuplesize; + PyObject *result = lz->result; + PyObject *it; + PyObject *item; + PyObject *olditem; + + if (tuplesize == 0) + return NULL; + if (lz->numactive == 0) + return NULL; + if (Py_REFCNT(result) == 1) { + Py_INCREF(result); + for (i=0 ; i < tuplesize ; i++) { + it = PyTuple_GET_ITEM(lz->ittuple, i); + if (it == NULL) { + Py_INCREF(lz->fillvalue); + item = lz->fillvalue; + } else { + item = PyIter_Next(it); + if (item == NULL) { + lz->numactive -= 1; + if (lz->numactive == 0 || PyErr_Occurred()) { + lz->numactive = 0; + Py_DECREF(result); + return NULL; + } else { + Py_INCREF(lz->fillvalue); + item = lz->fillvalue; + PyTuple_SET_ITEM(lz->ittuple, i, NULL); + Py_DECREF(it); + } } - } else { - result = PyTuple_New(tuplesize); - if (result == NULL) + } + olditem = PyTuple_GET_ITEM(result, i); + PyTuple_SET_ITEM(result, i, item); + Py_DECREF(olditem); + } + } else { + result = PyTuple_New(tuplesize); + if (result == NULL) + return NULL; + for (i=0 ; i < tuplesize ; i++) { + it = PyTuple_GET_ITEM(lz->ittuple, i); + if (it == NULL) { + Py_INCREF(lz->fillvalue); + item = lz->fillvalue; + } else { + item = PyIter_Next(it); + if (item == NULL) { + lz->numactive -= 1; + if (lz->numactive == 0 || PyErr_Occurred()) { + lz->numactive = 0; + Py_DECREF(result); return NULL; - for (i=0 ; i < tuplesize ; i++) { - it = PyTuple_GET_ITEM(lz->ittuple, i); - if (it == NULL) { - Py_INCREF(lz->fillvalue); - item = lz->fillvalue; - } else { - item = PyIter_Next(it); - if (item == NULL) { - lz->numactive -= 1; - if (lz->numactive == 0 || PyErr_Occurred()) { - lz->numactive = 0; - Py_DECREF(result); - return NULL; - } else { - Py_INCREF(lz->fillvalue); - item = lz->fillvalue; - PyTuple_SET_ITEM(lz->ittuple, i, NULL); - Py_DECREF(it); - } - } - } - PyTuple_SET_ITEM(result, i, item); + } else { + Py_INCREF(lz->fillvalue); + item = lz->fillvalue; + PyTuple_SET_ITEM(lz->ittuple, i, NULL); + Py_DECREF(it); + } } + } + PyTuple_SET_ITEM(result, i, item); } - return result; + } + return result; } PyDoc_STRVAR(zip_longest_doc, @@ -3441,47 +3441,47 @@ "); static PyTypeObject ziplongest_type = { - PyVarObject_HEAD_INIT(NULL, 0) - "itertools.zip_longest", /* tp_name */ - sizeof(ziplongestobject), /* tp_basicsize */ - 0, /* tp_itemsize */ - /* methods */ - (destructor)zip_longest_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 | - Py_TPFLAGS_BASETYPE, /* tp_flags */ - zip_longest_doc, /* tp_doc */ - (traverseproc)zip_longest_traverse, /* tp_traverse */ - 0, /* tp_clear */ - 0, /* tp_richcompare */ - 0, /* tp_weaklistoffset */ - PyObject_SelfIter, /* tp_iter */ - (iternextfunc)zip_longest_next, /* tp_iternext */ - 0, /* tp_methods */ - 0, /* tp_members */ - 0, /* tp_getset */ - 0, /* tp_base */ - 0, /* tp_dict */ - 0, /* tp_descr_get */ - 0, /* tp_descr_set */ - 0, /* tp_dictoffset */ - 0, /* tp_init */ - 0, /* tp_alloc */ - zip_longest_new, /* tp_new */ - PyObject_GC_Del, /* tp_free */ + PyVarObject_HEAD_INIT(NULL, 0) + "itertools.zip_longest", /* tp_name */ + sizeof(ziplongestobject), /* tp_basicsize */ + 0, /* tp_itemsize */ + /* methods */ + (destructor)zip_longest_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 | + Py_TPFLAGS_BASETYPE, /* tp_flags */ + zip_longest_doc, /* tp_doc */ + (traverseproc)zip_longest_traverse, /* tp_traverse */ + 0, /* tp_clear */ + 0, /* tp_richcompare */ + 0, /* tp_weaklistoffset */ + PyObject_SelfIter, /* tp_iter */ + (iternextfunc)zip_longest_next, /* tp_iternext */ + 0, /* tp_methods */ + 0, /* tp_members */ + 0, /* tp_getset */ + 0, /* tp_base */ + 0, /* tp_dict */ + 0, /* tp_descr_get */ + 0, /* tp_descr_set */ + 0, /* tp_dictoffset */ + 0, /* tp_init */ + 0, /* tp_alloc */ + zip_longest_new, /* tp_new */ + PyObject_GC_Del, /* tp_free */ }; /* module level code ********************************************************/ @@ -3516,68 +3516,68 @@ static PyMethodDef module_methods[] = { - {"tee", (PyCFunction)tee, METH_VARARGS, tee_doc}, - {NULL, NULL} /* sentinel */ + {"tee", (PyCFunction)tee, METH_VARARGS, tee_doc}, + {NULL, NULL} /* sentinel */ }; static struct PyModuleDef itertoolsmodule = { - PyModuleDef_HEAD_INIT, - "itertools", - module_doc, - -1, - module_methods, - NULL, - NULL, - NULL, - NULL + PyModuleDef_HEAD_INIT, + "itertools", + module_doc, + -1, + module_methods, + NULL, + NULL, + NULL, + NULL }; PyMODINIT_FUNC PyInit_itertools(void) { - int i; - PyObject *m; - char *name; - PyTypeObject *typelist[] = { - &combinations_type, - &cwr_type, - &cycle_type, - &dropwhile_type, - &takewhile_type, - &islice_type, - &starmap_type, - &chain_type, - &compress_type, - &filterfalse_type, - &count_type, - &ziplongest_type, - &permutations_type, - &product_type, - &repeat_type, - &groupby_type, - NULL - }; - - Py_TYPE(&teedataobject_type) = &PyType_Type; - m = PyModule_Create(&itertoolsmodule); - if (m == NULL) - return NULL; - - for (i=0 ; typelist[i] != NULL ; i++) { - if (PyType_Ready(typelist[i]) < 0) - return NULL; - name = strchr(typelist[i]->tp_name, '.'); - assert (name != NULL); - Py_INCREF(typelist[i]); - PyModule_AddObject(m, name+1, (PyObject *)typelist[i]); - } - - if (PyType_Ready(&teedataobject_type) < 0) - return NULL; - if (PyType_Ready(&tee_type) < 0) - return NULL; - if (PyType_Ready(&_grouper_type) < 0) - return NULL; - return m; + int i; + PyObject *m; + char *name; + PyTypeObject *typelist[] = { + &combinations_type, + &cwr_type, + &cycle_type, + &dropwhile_type, + &takewhile_type, + &islice_type, + &starmap_type, + &chain_type, + &compress_type, + &filterfalse_type, + &count_type, + &ziplongest_type, + &permutations_type, + &product_type, + &repeat_type, + &groupby_type, + NULL + }; + + Py_TYPE(&teedataobject_type) = &PyType_Type; + m = PyModule_Create(&itertoolsmodule); + if (m == NULL) + return NULL; + + for (i=0 ; typelist[i] != NULL ; i++) { + if (PyType_Ready(typelist[i]) < 0) + return NULL; + name = strchr(typelist[i]->tp_name, '.'); + assert (name != NULL); + Py_INCREF(typelist[i]); + PyModule_AddObject(m, name+1, (PyObject *)typelist[i]); + } + + if (PyType_Ready(&teedataobject_type) < 0) + return NULL; + if (PyType_Ready(&tee_type) < 0) + return NULL; + if (PyType_Ready(&_grouper_type) < 0) + return NULL; + return m; } Modified: python/branches/py3k/Modules/main.c ============================================================================== --- python/branches/py3k/Modules/main.c (original) +++ python/branches/py3k/Modules/main.c Sun May 9 17:52:27 2010 @@ -105,20 +105,20 @@ static FILE* _wfopen(const wchar_t *path, const wchar_t *mode) { - char cpath[PATH_MAX]; - char cmode[10]; - size_t r; - r = wcstombs(cpath, path, PATH_MAX); - if (r == (size_t)-1 || r >= PATH_MAX) { - errno = EINVAL; - return NULL; - } - r = wcstombs(cmode, mode, 10); - if (r == (size_t)-1 || r >= 10) { - errno = EINVAL; - return NULL; - } - return fopen(cpath, cmode); + char cpath[PATH_MAX]; + char cmode[10]; + size_t r; + r = wcstombs(cpath, path, PATH_MAX); + if (r == (size_t)-1 || r >= PATH_MAX) { + errno = EINVAL; + return NULL; + } + r = wcstombs(cmode, mode, 10); + if (r == (size_t)-1 || r >= 10) { + errno = EINVAL; + return NULL; + } + return fopen(cpath, cmode); } #endif @@ -126,131 +126,131 @@ static int usage(int exitcode, wchar_t* program) { - FILE *f = exitcode ? stderr : stdout; + FILE *f = exitcode ? stderr : stdout; - fprintf(f, usage_line, program); - if (exitcode) - fprintf(f, "Try `python -h' for more information.\n"); - else { - fputs(usage_1, f); - fputs(usage_2, f); - fputs(usage_3, f); - fprintf(f, usage_4, DELIM); - fprintf(f, usage_5, DELIM, PYTHONHOMEHELP); - } + fprintf(f, usage_line, program); + if (exitcode) + fprintf(f, "Try `python -h' for more information.\n"); + else { + fputs(usage_1, f); + fputs(usage_2, f); + fputs(usage_3, f); + fprintf(f, usage_4, DELIM); + fprintf(f, usage_5, DELIM, PYTHONHOMEHELP); + } #if defined(__VMS) - if (exitcode == 0) { - /* suppress 'error' message */ - return 1; - } - else { - /* STS$M_INHIB_MSG + SS$_ABORT */ - return 0x1000002c; - } + if (exitcode == 0) { + /* suppress 'error' message */ + return 1; + } + else { + /* STS$M_INHIB_MSG + SS$_ABORT */ + return 0x1000002c; + } #else - return exitcode; + return exitcode; #endif - /*NOTREACHED*/ + /*NOTREACHED*/ } static void RunStartupFile(PyCompilerFlags *cf) { - char *startup = Py_GETENV("PYTHONSTARTUP"); - if (startup != NULL && startup[0] != '\0') { - FILE *fp = fopen(startup, "r"); - if (fp != NULL) { - (void) PyRun_SimpleFileExFlags(fp, startup, 0, cf); - PyErr_Clear(); - fclose(fp); - } else { - int save_errno; - - save_errno = errno; - PySys_WriteStderr("Could not open PYTHONSTARTUP\n"); - errno = save_errno; - PyErr_SetFromErrnoWithFilename(PyExc_IOError, - startup); - PyErr_Print(); - PyErr_Clear(); - } - } + char *startup = Py_GETENV("PYTHONSTARTUP"); + if (startup != NULL && startup[0] != '\0') { + FILE *fp = fopen(startup, "r"); + if (fp != NULL) { + (void) PyRun_SimpleFileExFlags(fp, startup, 0, cf); + PyErr_Clear(); + fclose(fp); + } else { + int save_errno; + + save_errno = errno; + PySys_WriteStderr("Could not open PYTHONSTARTUP\n"); + errno = save_errno; + PyErr_SetFromErrnoWithFilename(PyExc_IOError, + startup); + PyErr_Print(); + PyErr_Clear(); + } + } } static int RunModule(wchar_t *modname, int set_argv0) { - PyObject *module, *runpy, *runmodule, *runargs, *result; - runpy = PyImport_ImportModule("runpy"); - if (runpy == NULL) { - fprintf(stderr, "Could not import runpy module\n"); - return -1; - } - runmodule = PyObject_GetAttrString(runpy, "_run_module_as_main"); - if (runmodule == NULL) { - fprintf(stderr, "Could not access runpy._run_module_as_main\n"); - Py_DECREF(runpy); - return -1; - } - module = PyUnicode_FromWideChar(modname, wcslen(modname)); - if (module == NULL) { - fprintf(stderr, "Could not convert module name to unicode\n"); - Py_DECREF(runpy); - Py_DECREF(runmodule); - return -1; - } - runargs = Py_BuildValue("(Oi)", module, set_argv0); - if (runargs == NULL) { - fprintf(stderr, - "Could not create arguments for runpy._run_module_as_main\n"); - Py_DECREF(runpy); - Py_DECREF(runmodule); - Py_DECREF(module); - return -1; - } - result = PyObject_Call(runmodule, runargs, NULL); - if (result == NULL) { - PyErr_Print(); - } - Py_DECREF(runpy); - Py_DECREF(runmodule); - Py_DECREF(module); - Py_DECREF(runargs); - if (result == NULL) { - return -1; - } - Py_DECREF(result); - return 0; + PyObject *module, *runpy, *runmodule, *runargs, *result; + runpy = PyImport_ImportModule("runpy"); + if (runpy == NULL) { + fprintf(stderr, "Could not import runpy module\n"); + return -1; + } + runmodule = PyObject_GetAttrString(runpy, "_run_module_as_main"); + if (runmodule == NULL) { + fprintf(stderr, "Could not access runpy._run_module_as_main\n"); + Py_DECREF(runpy); + return -1; + } + module = PyUnicode_FromWideChar(modname, wcslen(modname)); + if (module == NULL) { + fprintf(stderr, "Could not convert module name to unicode\n"); + Py_DECREF(runpy); + Py_DECREF(runmodule); + return -1; + } + runargs = Py_BuildValue("(Oi)", module, set_argv0); + if (runargs == NULL) { + fprintf(stderr, + "Could not create arguments for runpy._run_module_as_main\n"); + Py_DECREF(runpy); + Py_DECREF(runmodule); + Py_DECREF(module); + return -1; + } + result = PyObject_Call(runmodule, runargs, NULL); + if (result == NULL) { + PyErr_Print(); + } + Py_DECREF(runpy); + Py_DECREF(runmodule); + Py_DECREF(module); + Py_DECREF(runargs); + if (result == NULL) { + return -1; + } + Py_DECREF(result); + return 0; } static int RunMainFromImporter(wchar_t *filename) { - PyObject *argv0 = NULL, *importer = NULL; + PyObject *argv0 = NULL, *importer = NULL; - if ((argv0 = PyUnicode_FromWideChar(filename,wcslen(filename))) && - (importer = PyImport_GetImporter(argv0)) && - (importer->ob_type != &PyNullImporter_Type)) - { - /* argv0 is usable as an import source, so - put it in sys.path[0] and import __main__ */ - PyObject *sys_path = NULL; - if ((sys_path = PySys_GetObject("path")) && - !PyList_SetItem(sys_path, 0, argv0)) - { - Py_INCREF(argv0); - Py_DECREF(importer); - sys_path = NULL; - return RunModule(L"__main__", 0) != 0; - } - } - Py_XDECREF(argv0); - Py_XDECREF(importer); - if (PyErr_Occurred()) { - PyErr_Print(); - return 1; - } - else { - return -1; - } + if ((argv0 = PyUnicode_FromWideChar(filename,wcslen(filename))) && + (importer = PyImport_GetImporter(argv0)) && + (importer->ob_type != &PyNullImporter_Type)) + { + /* argv0 is usable as an import source, so + put it in sys.path[0] and import __main__ */ + PyObject *sys_path = NULL; + if ((sys_path = PySys_GetObject("path")) && + !PyList_SetItem(sys_path, 0, argv0)) + { + Py_INCREF(argv0); + Py_DECREF(importer); + sys_path = NULL; + return RunModule(L"__main__", 0) != 0; + } + } + Py_XDECREF(argv0); + Py_XDECREF(importer); + if (PyErr_Occurred()) { + PyErr_Print(); + return 1; + } + else { + return -1; + } } @@ -259,437 +259,437 @@ int Py_Main(int argc, wchar_t **argv) { - int c; - int sts; - wchar_t *command = NULL; - wchar_t *filename = NULL; - wchar_t *module = NULL; - FILE *fp = stdin; - char *p; + int c; + int sts; + wchar_t *command = NULL; + wchar_t *filename = NULL; + wchar_t *module = NULL; + FILE *fp = stdin; + char *p; #ifdef MS_WINDOWS - wchar_t *wp; + wchar_t *wp; #endif - int skipfirstline = 0; - int stdin_is_interactive = 0; - int help = 0; - int version = 0; - int saw_unbuffered_flag = 0; - PyCompilerFlags cf; - - cf.cf_flags = 0; - - orig_argc = argc; /* For Py_GetArgcArgv() */ - orig_argv = argv; - - PySys_ResetWarnOptions(); - - while ((c = _PyOS_GetOpt(argc, argv, PROGRAM_OPTS)) != EOF) { - if (c == 'c') { - size_t len; - /* -c is the last option; following arguments - that look like options are left for the - command to interpret. */ - - len = wcslen(_PyOS_optarg) + 1 + 1; - command = (wchar_t *)malloc(sizeof(wchar_t) * len); - if (command == NULL) - Py_FatalError( - "not enough memory to copy -c argument"); - wcscpy(command, _PyOS_optarg); - command[len - 2] = '\n'; - command[len - 1] = 0; - break; - } - - if (c == 'm') { - /* -m is the last option; following arguments - that look like options are left for the - module to interpret. */ - module = _PyOS_optarg; - break; - } - - switch (c) { - case 'b': - Py_BytesWarningFlag++; - break; - - case 'd': - Py_DebugFlag++; - break; - - case 'i': - Py_InspectFlag++; - Py_InteractiveFlag++; - break; - - /* case 'J': reserved for Jython */ - - case 'O': - Py_OptimizeFlag++; - break; - - case 'B': - Py_DontWriteBytecodeFlag++; - break; - - case 's': - Py_NoUserSiteDirectory++; - break; - - case 'S': - Py_NoSiteFlag++; - break; - - case 'E': - Py_IgnoreEnvironmentFlag++; - break; - - case 't': - /* ignored for backwards compatibility */ - break; - - case 'u': - Py_UnbufferedStdioFlag = 1; - saw_unbuffered_flag = 1; - break; - - case 'v': - Py_VerboseFlag++; - break; - - case 'x': - skipfirstline = 1; - break; - - /* case 'X': reserved for implementation-specific arguments */ - - case 'h': - case '?': - help++; - break; - - case 'V': - version++; - break; - - case 'W': - PySys_AddWarnOption(_PyOS_optarg); - break; - - /* This space reserved for other options */ - - default: - return usage(2, argv[0]); - /*NOTREACHED*/ - - } - } - - if (help) - return usage(0, argv[0]); - - if (version) { - fprintf(stderr, "Python %s\n", PY_VERSION); - return 0; - } - - if (!Py_InspectFlag && - (p = Py_GETENV("PYTHONINSPECT")) && *p != '\0') - Py_InspectFlag = 1; - if (!saw_unbuffered_flag && - (p = Py_GETENV("PYTHONUNBUFFERED")) && *p != '\0') - Py_UnbufferedStdioFlag = 1; - - if (!Py_NoUserSiteDirectory && - (p = Py_GETENV("PYTHONNOUSERSITE")) && *p != '\0') - Py_NoUserSiteDirectory = 1; + int skipfirstline = 0; + int stdin_is_interactive = 0; + int help = 0; + int version = 0; + int saw_unbuffered_flag = 0; + PyCompilerFlags cf; + + cf.cf_flags = 0; + + orig_argc = argc; /* For Py_GetArgcArgv() */ + orig_argv = argv; + + PySys_ResetWarnOptions(); + + while ((c = _PyOS_GetOpt(argc, argv, PROGRAM_OPTS)) != EOF) { + if (c == 'c') { + size_t len; + /* -c is the last option; following arguments + that look like options are left for the + command to interpret. */ + + len = wcslen(_PyOS_optarg) + 1 + 1; + command = (wchar_t *)malloc(sizeof(wchar_t) * len); + if (command == NULL) + Py_FatalError( + "not enough memory to copy -c argument"); + wcscpy(command, _PyOS_optarg); + command[len - 2] = '\n'; + command[len - 1] = 0; + break; + } + + if (c == 'm') { + /* -m is the last option; following arguments + that look like options are left for the + module to interpret. */ + module = _PyOS_optarg; + break; + } + + switch (c) { + case 'b': + Py_BytesWarningFlag++; + break; + + case 'd': + Py_DebugFlag++; + break; + + case 'i': + Py_InspectFlag++; + Py_InteractiveFlag++; + break; + + /* case 'J': reserved for Jython */ + + case 'O': + Py_OptimizeFlag++; + break; + + case 'B': + Py_DontWriteBytecodeFlag++; + break; + + case 's': + Py_NoUserSiteDirectory++; + break; + + case 'S': + Py_NoSiteFlag++; + break; + + case 'E': + Py_IgnoreEnvironmentFlag++; + break; + + case 't': + /* ignored for backwards compatibility */ + break; + + case 'u': + Py_UnbufferedStdioFlag = 1; + saw_unbuffered_flag = 1; + break; + + case 'v': + Py_VerboseFlag++; + break; + + case 'x': + skipfirstline = 1; + break; + + /* case 'X': reserved for implementation-specific arguments */ + + case 'h': + case '?': + help++; + break; + + case 'V': + version++; + break; + + case 'W': + PySys_AddWarnOption(_PyOS_optarg); + break; + + /* This space reserved for other options */ + + default: + return usage(2, argv[0]); + /*NOTREACHED*/ + + } + } + + if (help) + return usage(0, argv[0]); + + if (version) { + fprintf(stderr, "Python %s\n", PY_VERSION); + return 0; + } + + if (!Py_InspectFlag && + (p = Py_GETENV("PYTHONINSPECT")) && *p != '\0') + Py_InspectFlag = 1; + if (!saw_unbuffered_flag && + (p = Py_GETENV("PYTHONUNBUFFERED")) && *p != '\0') + Py_UnbufferedStdioFlag = 1; + + if (!Py_NoUserSiteDirectory && + (p = Py_GETENV("PYTHONNOUSERSITE")) && *p != '\0') + Py_NoUserSiteDirectory = 1; #ifdef MS_WINDOWS - if (!Py_IgnoreEnvironmentFlag && (wp = _wgetenv(L"PYTHONWARNINGS")) && - *wp != L'\0') { - wchar_t *buf, *warning; - - buf = (wchar_t *)malloc((wcslen(wp) + 1) * sizeof(wchar_t)); - if (buf == NULL) - Py_FatalError( - "not enough memory to copy PYTHONWARNINGS"); - wcscpy(buf, wp); - for (warning = wcstok(buf, L","); - warning != NULL; - warning = wcstok(NULL, L",")) { - PySys_AddWarnOption(warning); - } - free(buf); - } + if (!Py_IgnoreEnvironmentFlag && (wp = _wgetenv(L"PYTHONWARNINGS")) && + *wp != L'\0') { + wchar_t *buf, *warning; + + buf = (wchar_t *)malloc((wcslen(wp) + 1) * sizeof(wchar_t)); + if (buf == NULL) + Py_FatalError( + "not enough memory to copy PYTHONWARNINGS"); + wcscpy(buf, wp); + for (warning = wcstok(buf, L","); + warning != NULL; + warning = wcstok(NULL, L",")) { + PySys_AddWarnOption(warning); + } + free(buf); + } #else - if ((p = Py_GETENV("PYTHONWARNINGS")) && *p != '\0') { - char *buf, *oldloc; - wchar_t *warning; - - /* settle for strtok here as there's no one standard - C89 wcstok */ - buf = (char *)malloc(strlen(p) + 1); - if (buf == NULL) - Py_FatalError( - "not enough memory to copy PYTHONWARNINGS"); - strcpy(buf, p); - oldloc = strdup(setlocale(LC_ALL, NULL)); - setlocale(LC_ALL, ""); - for (p = strtok(buf, ","); p != NULL; p = strtok(NULL, ",")) { - if ((warning = _Py_char2wchar(p)) != NULL) { - PySys_AddWarnOption(warning); - PyMem_Free(warning); - } - } - setlocale(LC_ALL, oldloc); - free(oldloc); - free(buf); - } -#endif - - if (command == NULL && module == NULL && _PyOS_optind < argc && - wcscmp(argv[_PyOS_optind], L"-") != 0) - { + if ((p = Py_GETENV("PYTHONWARNINGS")) && *p != '\0') { + char *buf, *oldloc; + wchar_t *warning; + + /* settle for strtok here as there's no one standard + C89 wcstok */ + buf = (char *)malloc(strlen(p) + 1); + if (buf == NULL) + Py_FatalError( + "not enough memory to copy PYTHONWARNINGS"); + strcpy(buf, p); + oldloc = strdup(setlocale(LC_ALL, NULL)); + setlocale(LC_ALL, ""); + for (p = strtok(buf, ","); p != NULL; p = strtok(NULL, ",")) { + if ((warning = _Py_char2wchar(p)) != NULL) { + PySys_AddWarnOption(warning); + PyMem_Free(warning); + } + } + setlocale(LC_ALL, oldloc); + free(oldloc); + free(buf); + } +#endif + + if (command == NULL && module == NULL && _PyOS_optind < argc && + wcscmp(argv[_PyOS_optind], L"-") != 0) + { #ifdef __VMS - filename = decc$translate_vms(argv[_PyOS_optind]); - if (filename == (char *)0 || filename == (char *)-1) - filename = argv[_PyOS_optind]; + filename = decc$translate_vms(argv[_PyOS_optind]); + if (filename == (char *)0 || filename == (char *)-1) + filename = argv[_PyOS_optind]; #else - filename = argv[_PyOS_optind]; + filename = argv[_PyOS_optind]; #endif - } + } - stdin_is_interactive = Py_FdIsInteractive(stdin, (char *)0); + stdin_is_interactive = Py_FdIsInteractive(stdin, (char *)0); - if (Py_UnbufferedStdioFlag) { + if (Py_UnbufferedStdioFlag) { #if defined(MS_WINDOWS) || defined(__CYGWIN__) - _setmode(fileno(stdin), O_BINARY); - _setmode(fileno(stdout), O_BINARY); + _setmode(fileno(stdin), O_BINARY); + _setmode(fileno(stdout), O_BINARY); #endif #ifdef HAVE_SETVBUF - setvbuf(stdin, (char *)NULL, _IONBF, BUFSIZ); - setvbuf(stdout, (char *)NULL, _IONBF, BUFSIZ); - setvbuf(stderr, (char *)NULL, _IONBF, BUFSIZ); + setvbuf(stdin, (char *)NULL, _IONBF, BUFSIZ); + setvbuf(stdout, (char *)NULL, _IONBF, BUFSIZ); + setvbuf(stderr, (char *)NULL, _IONBF, BUFSIZ); #else /* !HAVE_SETVBUF */ - setbuf(stdin, (char *)NULL); - setbuf(stdout, (char *)NULL); - setbuf(stderr, (char *)NULL); + setbuf(stdin, (char *)NULL); + setbuf(stdout, (char *)NULL); + setbuf(stderr, (char *)NULL); #endif /* !HAVE_SETVBUF */ - } - else if (Py_InteractiveFlag) { + } + else if (Py_InteractiveFlag) { #ifdef MS_WINDOWS - /* Doesn't have to have line-buffered -- use unbuffered */ - /* Any set[v]buf(stdin, ...) screws up Tkinter :-( */ - setvbuf(stdout, (char *)NULL, _IONBF, BUFSIZ); + /* Doesn't have to have line-buffered -- use unbuffered */ + /* Any set[v]buf(stdin, ...) screws up Tkinter :-( */ + setvbuf(stdout, (char *)NULL, _IONBF, BUFSIZ); #else /* !MS_WINDOWS */ #ifdef HAVE_SETVBUF - setvbuf(stdin, (char *)NULL, _IOLBF, BUFSIZ); - setvbuf(stdout, (char *)NULL, _IOLBF, BUFSIZ); + setvbuf(stdin, (char *)NULL, _IOLBF, BUFSIZ); + setvbuf(stdout, (char *)NULL, _IOLBF, BUFSIZ); #endif /* HAVE_SETVBUF */ #endif /* !MS_WINDOWS */ - /* Leave stderr alone - it should be unbuffered anyway. */ - } + /* Leave stderr alone - it should be unbuffered anyway. */ + } #ifdef __VMS - else { - setvbuf (stdout, (char *)NULL, _IOLBF, BUFSIZ); - } + else { + setvbuf (stdout, (char *)NULL, _IOLBF, BUFSIZ); + } #endif /* __VMS */ #ifdef __APPLE__ - /* On MacOS X, when the Python interpreter is embedded in an - application bundle, it gets executed by a bootstrapping script - that does os.execve() with an argv[0] that's different from the - actual Python executable. This is needed to keep the Finder happy, - or rather, to work around Apple's overly strict requirements of - the process name. However, we still need a usable sys.executable, - so the actual executable path is passed in an environment variable. - See Lib/plat-mac/bundlebuiler.py for details about the bootstrap - script. */ - if ((p = Py_GETENV("PYTHONEXECUTABLE")) && *p != '\0') { - wchar_t* buffer; - size_t len = strlen(p); - size_t r; - - buffer = malloc(len * sizeof(wchar_t)); - if (buffer == NULL) { - Py_FatalError( - "not enough memory to copy PYTHONEXECUTABLE"); - } - - r = mbstowcs(buffer, p, len); - Py_SetProgramName(buffer); - /* buffer is now handed off - do not free */ - } else { - Py_SetProgramName(argv[0]); - } + /* On MacOS X, when the Python interpreter is embedded in an + application bundle, it gets executed by a bootstrapping script + that does os.execve() with an argv[0] that's different from the + actual Python executable. This is needed to keep the Finder happy, + or rather, to work around Apple's overly strict requirements of + the process name. However, we still need a usable sys.executable, + so the actual executable path is passed in an environment variable. + See Lib/plat-mac/bundlebuiler.py for details about the bootstrap + script. */ + if ((p = Py_GETENV("PYTHONEXECUTABLE")) && *p != '\0') { + wchar_t* buffer; + size_t len = strlen(p); + size_t r; + + buffer = malloc(len * sizeof(wchar_t)); + if (buffer == NULL) { + Py_FatalError( + "not enough memory to copy PYTHONEXECUTABLE"); + } + + r = mbstowcs(buffer, p, len); + Py_SetProgramName(buffer); + /* buffer is now handed off - do not free */ + } else { + Py_SetProgramName(argv[0]); + } #else - Py_SetProgramName(argv[0]); + Py_SetProgramName(argv[0]); #endif - Py_Initialize(); + Py_Initialize(); - if (Py_VerboseFlag || - (command == NULL && filename == NULL && module == NULL && stdin_is_interactive)) { - fprintf(stderr, "Python %s on %s\n", - Py_GetVersion(), Py_GetPlatform()); - if (!Py_NoSiteFlag) - fprintf(stderr, "%s\n", COPYRIGHT); - } - - if (command != NULL) { - /* Backup _PyOS_optind and force sys.argv[0] = '-c' */ - _PyOS_optind--; - argv[_PyOS_optind] = L"-c"; - } - - if (module != NULL) { - /* Backup _PyOS_optind and force sys.argv[0] = '-c' - so that PySys_SetArgv correctly sets sys.path[0] to ''*/ - _PyOS_optind--; - argv[_PyOS_optind] = L"-c"; - } - - PySys_SetArgv(argc-_PyOS_optind, argv+_PyOS_optind); - - if ((Py_InspectFlag || (command == NULL && filename == NULL && module == NULL)) && - isatty(fileno(stdin))) { - PyObject *v; - v = PyImport_ImportModule("readline"); - if (v == NULL) - PyErr_Clear(); - else - Py_DECREF(v); - } - - if (command) { - PyObject *commandObj = PyUnicode_FromWideChar( - command, wcslen(command)); - free(command); - if (commandObj != NULL) { - sts = PyRun_SimpleStringFlags( - _PyUnicode_AsString(commandObj), &cf) != 0; - } - else { - PyErr_Print(); - sts = 1; - } - Py_DECREF(commandObj); - } else if (module) { - sts = RunModule(module, 1); - } - else { - - if (filename == NULL && stdin_is_interactive) { - Py_InspectFlag = 0; /* do exit on SystemExit */ - RunStartupFile(&cf); - } - /* XXX */ - - sts = -1; /* keep track of whether we've already run __main__ */ - - if (filename != NULL) { - sts = RunMainFromImporter(filename); - } - - if (sts==-1 && filename!=NULL) { - if ((fp = _wfopen(filename, L"r")) == NULL) { - char cfilename[PATH_MAX]; - size_t r = wcstombs(cfilename, filename, PATH_MAX); - if (r == PATH_MAX) - /* cfilename is not null-terminated; - * forcefully null-terminating it - * might break the shift state */ - strcpy(cfilename, ""); - if (r == ((size_t)-1)) - strcpy(cfilename, ""); - fprintf(stderr, "%ls: can't open file '%s': [Errno %d] %s\n", - argv[0], cfilename, errno, strerror(errno)); - - return 2; - } - else if (skipfirstline) { - int ch; - /* Push back first newline so line numbers - remain the same */ - while ((ch = getc(fp)) != EOF) { - if (ch == '\n') { - (void)ungetc(ch, fp); - break; - } - } - } - { - /* XXX: does this work on Win/Win64? (see posix_fstat) */ - struct stat sb; - if (fstat(fileno(fp), &sb) == 0 && - S_ISDIR(sb.st_mode)) { - fprintf(stderr, "%ls: '%ls' is a directory, cannot continue\n", argv[0], filename); - fclose(fp); - return 1; - } - } - } - - if (sts==-1) { - PyObject *filenameObj = NULL; - char *p_cfilename = ""; - if (filename) { - filenameObj = PyUnicode_FromWideChar( - filename, wcslen(filename)); - if (filenameObj != NULL) - p_cfilename = _PyUnicode_AsString(filenameObj); - else - p_cfilename = ""; - } - /* call pending calls like signal handlers (SIGINT) */ - if (Py_MakePendingCalls() == -1) { - PyErr_Print(); - sts = 1; - } else { - sts = PyRun_AnyFileExFlags( - fp, - p_cfilename, - filename != NULL, &cf) != 0; - } - Py_XDECREF(filenameObj); - } - - } - - /* Check this environment variable at the end, to give programs the - * opportunity to set it from Python. - */ - if (!Py_InspectFlag && - (p = Py_GETENV("PYTHONINSPECT")) && *p != '\0') - { - Py_InspectFlag = 1; - } - - if (Py_InspectFlag && stdin_is_interactive && - (filename != NULL || command != NULL || module != NULL)) { - Py_InspectFlag = 0; - /* XXX */ - sts = PyRun_AnyFileFlags(stdin, "", &cf) != 0; - } + if (Py_VerboseFlag || + (command == NULL && filename == NULL && module == NULL && stdin_is_interactive)) { + fprintf(stderr, "Python %s on %s\n", + Py_GetVersion(), Py_GetPlatform()); + if (!Py_NoSiteFlag) + fprintf(stderr, "%s\n", COPYRIGHT); + } + + if (command != NULL) { + /* Backup _PyOS_optind and force sys.argv[0] = '-c' */ + _PyOS_optind--; + argv[_PyOS_optind] = L"-c"; + } + + if (module != NULL) { + /* Backup _PyOS_optind and force sys.argv[0] = '-c' + so that PySys_SetArgv correctly sets sys.path[0] to ''*/ + _PyOS_optind--; + argv[_PyOS_optind] = L"-c"; + } + + PySys_SetArgv(argc-_PyOS_optind, argv+_PyOS_optind); + + if ((Py_InspectFlag || (command == NULL && filename == NULL && module == NULL)) && + isatty(fileno(stdin))) { + PyObject *v; + v = PyImport_ImportModule("readline"); + if (v == NULL) + PyErr_Clear(); + else + Py_DECREF(v); + } + + if (command) { + PyObject *commandObj = PyUnicode_FromWideChar( + command, wcslen(command)); + free(command); + if (commandObj != NULL) { + sts = PyRun_SimpleStringFlags( + _PyUnicode_AsString(commandObj), &cf) != 0; + } + else { + PyErr_Print(); + sts = 1; + } + Py_DECREF(commandObj); + } else if (module) { + sts = RunModule(module, 1); + } + else { + + if (filename == NULL && stdin_is_interactive) { + Py_InspectFlag = 0; /* do exit on SystemExit */ + RunStartupFile(&cf); + } + /* XXX */ + + sts = -1; /* keep track of whether we've already run __main__ */ + + if (filename != NULL) { + sts = RunMainFromImporter(filename); + } + + if (sts==-1 && filename!=NULL) { + if ((fp = _wfopen(filename, L"r")) == NULL) { + char cfilename[PATH_MAX]; + size_t r = wcstombs(cfilename, filename, PATH_MAX); + if (r == PATH_MAX) + /* cfilename is not null-terminated; + * forcefully null-terminating it + * might break the shift state */ + strcpy(cfilename, ""); + if (r == ((size_t)-1)) + strcpy(cfilename, ""); + fprintf(stderr, "%ls: can't open file '%s': [Errno %d] %s\n", + argv[0], cfilename, errno, strerror(errno)); + + return 2; + } + else if (skipfirstline) { + int ch; + /* Push back first newline so line numbers + remain the same */ + while ((ch = getc(fp)) != EOF) { + if (ch == '\n') { + (void)ungetc(ch, fp); + break; + } + } + } + { + /* XXX: does this work on Win/Win64? (see posix_fstat) */ + struct stat sb; + if (fstat(fileno(fp), &sb) == 0 && + S_ISDIR(sb.st_mode)) { + fprintf(stderr, "%ls: '%ls' is a directory, cannot continue\n", argv[0], filename); + fclose(fp); + return 1; + } + } + } + + if (sts==-1) { + PyObject *filenameObj = NULL; + char *p_cfilename = ""; + if (filename) { + filenameObj = PyUnicode_FromWideChar( + filename, wcslen(filename)); + if (filenameObj != NULL) + p_cfilename = _PyUnicode_AsString(filenameObj); + else + p_cfilename = ""; + } + /* call pending calls like signal handlers (SIGINT) */ + if (Py_MakePendingCalls() == -1) { + PyErr_Print(); + sts = 1; + } else { + sts = PyRun_AnyFileExFlags( + fp, + p_cfilename, + filename != NULL, &cf) != 0; + } + Py_XDECREF(filenameObj); + } + + } - Py_Finalize(); + /* Check this environment variable at the end, to give programs the + * opportunity to set it from Python. + */ + if (!Py_InspectFlag && + (p = Py_GETENV("PYTHONINSPECT")) && *p != '\0') + { + Py_InspectFlag = 1; + } + + if (Py_InspectFlag && stdin_is_interactive && + (filename != NULL || command != NULL || module != NULL)) { + Py_InspectFlag = 0; + /* XXX */ + sts = PyRun_AnyFileFlags(stdin, "", &cf) != 0; + } + + Py_Finalize(); #ifdef __INSURE__ - /* Insure++ is a memory analysis tool that aids in discovering - * memory leaks and other memory problems. On Python exit, the - * interned string dictionaries are flagged as being in use at exit - * (which it is). Under normal circumstances, this is fine because - * the memory will be automatically reclaimed by the system. Under - * memory debugging, it's a huge source of useless noise, so we - * trade off slower shutdown for less distraction in the memory - * reports. -baw - */ - _Py_ReleaseInternedStrings(); - _Py_ReleaseInternedUnicodeStrings(); + /* Insure++ is a memory analysis tool that aids in discovering + * memory leaks and other memory problems. On Python exit, the + * interned string dictionaries are flagged as being in use at exit + * (which it is). Under normal circumstances, this is fine because + * the memory will be automatically reclaimed by the system. Under + * memory debugging, it's a huge source of useless noise, so we + * trade off slower shutdown for less distraction in the memory + * reports. -baw + */ + _Py_ReleaseInternedStrings(); + _Py_ReleaseInternedUnicodeStrings(); #endif /* __INSURE__ */ - return sts; + return sts; } /* this is gonna seem *real weird*, but if you put some other code between @@ -702,112 +702,112 @@ void Py_GetArgcArgv(int *argc, wchar_t ***argv) { - *argc = orig_argc; - *argv = orig_argv; + *argc = orig_argc; + *argv = orig_argv; } wchar_t* _Py_char2wchar(char* arg) { - wchar_t *res; + wchar_t *res; #ifdef HAVE_BROKEN_MBSTOWCS - /* Some platforms have a broken implementation of - * mbstowcs which does not count the characters that - * would result from conversion. Use an upper bound. - */ - size_t argsize = strlen(arg); + /* Some platforms have a broken implementation of + * mbstowcs which does not count the characters that + * would result from conversion. Use an upper bound. + */ + size_t argsize = strlen(arg); #else - size_t argsize = mbstowcs(NULL, arg, 0); + size_t argsize = mbstowcs(NULL, arg, 0); #endif - size_t count; - unsigned char *in; - wchar_t *out; + size_t count; + unsigned char *in; + wchar_t *out; #ifdef HAVE_MBRTOWC - mbstate_t mbs; + mbstate_t mbs; #endif - if (argsize != (size_t)-1) { - res = (wchar_t *)PyMem_Malloc((argsize+1)*sizeof(wchar_t)); - if (!res) - goto oom; - count = mbstowcs(res, arg, argsize+1); - if (count != (size_t)-1) { - wchar_t *tmp; - /* Only use the result if it contains no - surrogate characters. */ - for (tmp = res; *tmp != 0 && - (*tmp < 0xd800 || *tmp > 0xdfff); tmp++) - ; - if (*tmp == 0) - return res; - } - PyMem_Free(res); - } - /* Conversion failed. Fall back to escaping with surrogateescape. */ + if (argsize != (size_t)-1) { + res = (wchar_t *)PyMem_Malloc((argsize+1)*sizeof(wchar_t)); + if (!res) + goto oom; + count = mbstowcs(res, arg, argsize+1); + if (count != (size_t)-1) { + wchar_t *tmp; + /* Only use the result if it contains no + surrogate characters. */ + for (tmp = res; *tmp != 0 && + (*tmp < 0xd800 || *tmp > 0xdfff); tmp++) + ; + if (*tmp == 0) + return res; + } + PyMem_Free(res); + } + /* Conversion failed. Fall back to escaping with surrogateescape. */ #ifdef HAVE_MBRTOWC - /* Try conversion with mbrtwoc (C99), and escape non-decodable bytes. */ - - /* Overallocate; as multi-byte characters are in the argument, the - actual output could use less memory. */ - argsize = strlen(arg) + 1; - res = (wchar_t*)PyMem_Malloc(argsize*sizeof(wchar_t)); - if (!res) goto oom; - in = (unsigned char*)arg; - out = res; - memset(&mbs, 0, sizeof mbs); - while (argsize) { - size_t converted = mbrtowc(out, (char*)in, argsize, &mbs); - if (converted == 0) - /* Reached end of string; null char stored. */ - break; - if (converted == (size_t)-2) { - /* Incomplete character. This should never happen, - since we provide everything that we have - - unless there is a bug in the C library, or I - misunderstood how mbrtowc works. */ - fprintf(stderr, "unexpected mbrtowc result -2\n"); - return NULL; - } - if (converted == (size_t)-1) { - /* Conversion error. Escape as UTF-8b, and start over - in the initial shift state. */ - *out++ = 0xdc00 + *in++; - argsize--; - memset(&mbs, 0, sizeof mbs); - continue; - } - if (*out >= 0xd800 && *out <= 0xdfff) { - /* Surrogate character. Escape the original - byte sequence with surrogateescape. */ - argsize -= converted; - while (converted--) - *out++ = 0xdc00 + *in++; - continue; - } - /* successfully converted some bytes */ - in += converted; - argsize -= converted; - out++; - } + /* Try conversion with mbrtwoc (C99), and escape non-decodable bytes. */ + + /* Overallocate; as multi-byte characters are in the argument, the + actual output could use less memory. */ + argsize = strlen(arg) + 1; + res = (wchar_t*)PyMem_Malloc(argsize*sizeof(wchar_t)); + if (!res) goto oom; + in = (unsigned char*)arg; + out = res; + memset(&mbs, 0, sizeof mbs); + while (argsize) { + size_t converted = mbrtowc(out, (char*)in, argsize, &mbs); + if (converted == 0) + /* Reached end of string; null char stored. */ + break; + if (converted == (size_t)-2) { + /* Incomplete character. This should never happen, + since we provide everything that we have - + unless there is a bug in the C library, or I + misunderstood how mbrtowc works. */ + fprintf(stderr, "unexpected mbrtowc result -2\n"); + return NULL; + } + if (converted == (size_t)-1) { + /* Conversion error. Escape as UTF-8b, and start over + in the initial shift state. */ + *out++ = 0xdc00 + *in++; + argsize--; + memset(&mbs, 0, sizeof mbs); + continue; + } + if (*out >= 0xd800 && *out <= 0xdfff) { + /* Surrogate character. Escape the original + byte sequence with surrogateescape. */ + argsize -= converted; + while (converted--) + *out++ = 0xdc00 + *in++; + continue; + } + /* successfully converted some bytes */ + in += converted; + argsize -= converted; + out++; + } #else - /* Cannot use C locale for escaping; manually escape as if charset - is ASCII (i.e. escape all bytes > 128. This will still roundtrip - correctly in the locale's charset, which must be an ASCII superset. */ - res = PyMem_Malloc((strlen(arg)+1)*sizeof(wchar_t)); - if (!res) goto oom; - in = (unsigned char*)arg; - out = res; - while(*in) - if(*in < 128) - *out++ = *in++; - else - *out++ = 0xdc00 + *in++; - *out = 0; + /* Cannot use C locale for escaping; manually escape as if charset + is ASCII (i.e. escape all bytes > 128. This will still roundtrip + correctly in the locale's charset, which must be an ASCII superset. */ + res = PyMem_Malloc((strlen(arg)+1)*sizeof(wchar_t)); + if (!res) goto oom; + in = (unsigned char*)arg; + out = res; + while(*in) + if(*in < 128) + *out++ = *in++; + else + *out++ = 0xdc00 + *in++; + *out = 0; #endif - return res; + return res; oom: - fprintf(stderr, "out of memory\n"); - return NULL; + fprintf(stderr, "out of memory\n"); + return NULL; } #ifdef __cplusplus Modified: python/branches/py3k/Modules/mathmodule.c ============================================================================== --- python/branches/py3k/Modules/mathmodule.c (original) +++ python/branches/py3k/Modules/mathmodule.c Sun May 9 17:52:27 2010 @@ -73,36 +73,36 @@ static double sinpi(double x) { - double y, r; - int n; - /* this function should only ever be called for finite arguments */ - assert(Py_IS_FINITE(x)); - y = fmod(fabs(x), 2.0); - n = (int)round(2.0*y); - assert(0 <= n && n <= 4); - switch (n) { - case 0: - r = sin(pi*y); - break; - case 1: - r = cos(pi*(y-0.5)); - break; - case 2: - /* N.B. -sin(pi*(y-1.0)) is *not* equivalent: it would give - -0.0 instead of 0.0 when y == 1.0. */ - r = sin(pi*(1.0-y)); - break; - case 3: - r = -cos(pi*(y-1.5)); - break; - case 4: - r = sin(pi*(y-2.0)); - break; - default: - assert(0); /* should never get here */ - r = -1.23e200; /* silence gcc warning */ - } - return copysign(1.0, x)*r; + double y, r; + int n; + /* this function should only ever be called for finite arguments */ + assert(Py_IS_FINITE(x)); + y = fmod(fabs(x), 2.0); + n = (int)round(2.0*y); + assert(0 <= n && n <= 4); + switch (n) { + case 0: + r = sin(pi*y); + break; + case 1: + r = cos(pi*(y-0.5)); + break; + case 2: + /* N.B. -sin(pi*(y-1.0)) is *not* equivalent: it would give + -0.0 instead of 0.0 when y == 1.0. */ + r = sin(pi*(1.0-y)); + break; + case 3: + r = -cos(pi*(y-1.5)); + break; + case 4: + r = sin(pi*(y-2.0)); + break; + default: + assert(0); /* should never get here */ + r = -1.23e200; /* silence gcc warning */ + } + return copysign(1.0, x)*r; } /* Implementation of the real gamma function. In extensive but non-exhaustive @@ -166,34 +166,34 @@ static const double lanczos_g = 6.024680040776729583740234375; static const double lanczos_g_minus_half = 5.524680040776729583740234375; static const double lanczos_num_coeffs[LANCZOS_N] = { - 23531376880.410759688572007674451636754734846804940, - 42919803642.649098768957899047001988850926355848959, - 35711959237.355668049440185451547166705960488635843, - 17921034426.037209699919755754458931112671403265390, - 6039542586.3520280050642916443072979210699388420708, - 1439720407.3117216736632230727949123939715485786772, - 248874557.86205415651146038641322942321632125127801, - 31426415.585400194380614231628318205362874684987640, - 2876370.6289353724412254090516208496135991145378768, - 186056.26539522349504029498971604569928220784236328, - 8071.6720023658162106380029022722506138218516325024, - 210.82427775157934587250973392071336271166969580291, - 2.5066282746310002701649081771338373386264310793408 + 23531376880.410759688572007674451636754734846804940, + 42919803642.649098768957899047001988850926355848959, + 35711959237.355668049440185451547166705960488635843, + 17921034426.037209699919755754458931112671403265390, + 6039542586.3520280050642916443072979210699388420708, + 1439720407.3117216736632230727949123939715485786772, + 248874557.86205415651146038641322942321632125127801, + 31426415.585400194380614231628318205362874684987640, + 2876370.6289353724412254090516208496135991145378768, + 186056.26539522349504029498971604569928220784236328, + 8071.6720023658162106380029022722506138218516325024, + 210.82427775157934587250973392071336271166969580291, + 2.5066282746310002701649081771338373386264310793408 }; /* denominator is x*(x+1)*...*(x+LANCZOS_N-2) */ static const double lanczos_den_coeffs[LANCZOS_N] = { - 0.0, 39916800.0, 120543840.0, 150917976.0, 105258076.0, 45995730.0, - 13339535.0, 2637558.0, 357423.0, 32670.0, 1925.0, 66.0, 1.0}; + 0.0, 39916800.0, 120543840.0, 150917976.0, 105258076.0, 45995730.0, + 13339535.0, 2637558.0, 357423.0, 32670.0, 1925.0, 66.0, 1.0}; /* gamma values for small positive integers, 1 though NGAMMA_INTEGRAL */ #define NGAMMA_INTEGRAL 23 static const double gamma_integral[NGAMMA_INTEGRAL] = { - 1.0, 1.0, 2.0, 6.0, 24.0, 120.0, 720.0, 5040.0, 40320.0, 362880.0, - 3628800.0, 39916800.0, 479001600.0, 6227020800.0, 87178291200.0, - 1307674368000.0, 20922789888000.0, 355687428096000.0, - 6402373705728000.0, 121645100408832000.0, 2432902008176640000.0, - 51090942171709440000.0, 1124000727777607680000.0, + 1.0, 1.0, 2.0, 6.0, 24.0, 120.0, 720.0, 5040.0, 40320.0, 362880.0, + 3628800.0, 39916800.0, 479001600.0, 6227020800.0, 87178291200.0, + 1307674368000.0, 20922789888000.0, 355687428096000.0, + 6402373705728000.0, 121645100408832000.0, 2432902008176640000.0, + 51090942171709440000.0, 1124000727777607680000.0, }; /* Lanczos' sum L_g(x), for positive x */ @@ -201,125 +201,125 @@ static double lanczos_sum(double x) { - double num = 0.0, den = 0.0; - int i; - assert(x > 0.0); - /* evaluate the rational function lanczos_sum(x). For large - x, the obvious algorithm risks overflow, so we instead - rescale the denominator and numerator of the rational - function by x**(1-LANCZOS_N) and treat this as a - rational function in 1/x. This also reduces the error for - larger x values. The choice of cutoff point (5.0 below) is - somewhat arbitrary; in tests, smaller cutoff values than - this resulted in lower accuracy. */ - if (x < 5.0) { - for (i = LANCZOS_N; --i >= 0; ) { - num = num * x + lanczos_num_coeffs[i]; - den = den * x + lanczos_den_coeffs[i]; - } - } - else { - for (i = 0; i < LANCZOS_N; i++) { - num = num / x + lanczos_num_coeffs[i]; - den = den / x + lanczos_den_coeffs[i]; - } - } - return num/den; + double num = 0.0, den = 0.0; + int i; + assert(x > 0.0); + /* evaluate the rational function lanczos_sum(x). For large + x, the obvious algorithm risks overflow, so we instead + rescale the denominator and numerator of the rational + function by x**(1-LANCZOS_N) and treat this as a + rational function in 1/x. This also reduces the error for + larger x values. The choice of cutoff point (5.0 below) is + somewhat arbitrary; in tests, smaller cutoff values than + this resulted in lower accuracy. */ + if (x < 5.0) { + for (i = LANCZOS_N; --i >= 0; ) { + num = num * x + lanczos_num_coeffs[i]; + den = den * x + lanczos_den_coeffs[i]; + } + } + else { + for (i = 0; i < LANCZOS_N; i++) { + num = num / x + lanczos_num_coeffs[i]; + den = den / x + lanczos_den_coeffs[i]; + } + } + return num/den; } static double m_tgamma(double x) { - double absx, r, y, z, sqrtpow; + double absx, r, y, z, sqrtpow; - /* special cases */ - if (!Py_IS_FINITE(x)) { - if (Py_IS_NAN(x) || x > 0.0) - return x; /* tgamma(nan) = nan, tgamma(inf) = inf */ - else { - errno = EDOM; - return Py_NAN; /* tgamma(-inf) = nan, invalid */ - } - } - if (x == 0.0) { - errno = EDOM; - return 1.0/x; /* tgamma(+-0.0) = +-inf, divide-by-zero */ - } - - /* integer arguments */ - if (x == floor(x)) { - if (x < 0.0) { - errno = EDOM; /* tgamma(n) = nan, invalid for */ - return Py_NAN; /* negative integers n */ - } - if (x <= NGAMMA_INTEGRAL) - return gamma_integral[(int)x - 1]; - } - absx = fabs(x); - - /* tiny arguments: tgamma(x) ~ 1/x for x near 0 */ - if (absx < 1e-20) { - r = 1.0/x; - if (Py_IS_INFINITY(r)) - errno = ERANGE; - return r; - } - - /* large arguments: assuming IEEE 754 doubles, tgamma(x) overflows for - x > 200, and underflows to +-0.0 for x < -200, not a negative - integer. */ - if (absx > 200.0) { - if (x < 0.0) { - return 0.0/sinpi(x); - } - else { - errno = ERANGE; - return Py_HUGE_VAL; - } - } - - y = absx + lanczos_g_minus_half; - /* compute error in sum */ - if (absx > lanczos_g_minus_half) { - /* note: the correction can be foiled by an optimizing - compiler that (incorrectly) thinks that an expression like - a + b - a - b can be optimized to 0.0. This shouldn't - happen in a standards-conforming compiler. */ - double q = y - absx; - z = q - lanczos_g_minus_half; - } - else { - double q = y - lanczos_g_minus_half; - z = q - absx; - } - z = z * lanczos_g / y; - if (x < 0.0) { - r = -pi / sinpi(absx) / absx * exp(y) / lanczos_sum(absx); - r -= z * r; - if (absx < 140.0) { - r /= pow(y, absx - 0.5); - } - else { - sqrtpow = pow(y, absx / 2.0 - 0.25); - r /= sqrtpow; - r /= sqrtpow; - } - } - else { - r = lanczos_sum(absx) / exp(y); - r += z * r; - if (absx < 140.0) { - r *= pow(y, absx - 0.5); - } - else { - sqrtpow = pow(y, absx / 2.0 - 0.25); - r *= sqrtpow; - r *= sqrtpow; - } - } - if (Py_IS_INFINITY(r)) - errno = ERANGE; - return r; + /* special cases */ + if (!Py_IS_FINITE(x)) { + if (Py_IS_NAN(x) || x > 0.0) + return x; /* tgamma(nan) = nan, tgamma(inf) = inf */ + else { + errno = EDOM; + return Py_NAN; /* tgamma(-inf) = nan, invalid */ + } + } + if (x == 0.0) { + errno = EDOM; + return 1.0/x; /* tgamma(+-0.0) = +-inf, divide-by-zero */ + } + + /* integer arguments */ + if (x == floor(x)) { + if (x < 0.0) { + errno = EDOM; /* tgamma(n) = nan, invalid for */ + return Py_NAN; /* negative integers n */ + } + if (x <= NGAMMA_INTEGRAL) + return gamma_integral[(int)x - 1]; + } + absx = fabs(x); + + /* tiny arguments: tgamma(x) ~ 1/x for x near 0 */ + if (absx < 1e-20) { + r = 1.0/x; + if (Py_IS_INFINITY(r)) + errno = ERANGE; + return r; + } + + /* large arguments: assuming IEEE 754 doubles, tgamma(x) overflows for + x > 200, and underflows to +-0.0 for x < -200, not a negative + integer. */ + if (absx > 200.0) { + if (x < 0.0) { + return 0.0/sinpi(x); + } + else { + errno = ERANGE; + return Py_HUGE_VAL; + } + } + + y = absx + lanczos_g_minus_half; + /* compute error in sum */ + if (absx > lanczos_g_minus_half) { + /* note: the correction can be foiled by an optimizing + compiler that (incorrectly) thinks that an expression like + a + b - a - b can be optimized to 0.0. This shouldn't + happen in a standards-conforming compiler. */ + double q = y - absx; + z = q - lanczos_g_minus_half; + } + else { + double q = y - lanczos_g_minus_half; + z = q - absx; + } + z = z * lanczos_g / y; + if (x < 0.0) { + r = -pi / sinpi(absx) / absx * exp(y) / lanczos_sum(absx); + r -= z * r; + if (absx < 140.0) { + r /= pow(y, absx - 0.5); + } + else { + sqrtpow = pow(y, absx / 2.0 - 0.25); + r /= sqrtpow; + r /= sqrtpow; + } + } + else { + r = lanczos_sum(absx) / exp(y); + r += z * r; + if (absx < 140.0) { + r *= pow(y, absx - 0.5); + } + else { + sqrtpow = pow(y, absx / 2.0 - 0.25); + r *= sqrtpow; + r *= sqrtpow; + } + } + if (Py_IS_INFINITY(r)) + errno = ERANGE; + return r; } /* @@ -330,49 +330,49 @@ static double m_lgamma(double x) { - double r, absx; + double r, absx; - /* special cases */ - if (!Py_IS_FINITE(x)) { - if (Py_IS_NAN(x)) - return x; /* lgamma(nan) = nan */ - else - return Py_HUGE_VAL; /* lgamma(+-inf) = +inf */ - } - - /* integer arguments */ - if (x == floor(x) && x <= 2.0) { - if (x <= 0.0) { - errno = EDOM; /* lgamma(n) = inf, divide-by-zero for */ - return Py_HUGE_VAL; /* integers n <= 0 */ - } - else { - return 0.0; /* lgamma(1) = lgamma(2) = 0.0 */ - } - } - - absx = fabs(x); - /* tiny arguments: lgamma(x) ~ -log(fabs(x)) for small x */ - if (absx < 1e-20) - return -log(absx); - - /* Lanczos' formula */ - if (x > 0.0) { - /* we could save a fraction of a ulp in accuracy by having a - second set of numerator coefficients for lanczos_sum that - absorbed the exp(-lanczos_g) term, and throwing out the - lanczos_g subtraction below; it's probably not worth it. */ - r = log(lanczos_sum(x)) - lanczos_g + - (x-0.5)*(log(x+lanczos_g-0.5)-1); - } - else { - r = log(pi) - log(fabs(sinpi(absx))) - log(absx) - - (log(lanczos_sum(absx)) - lanczos_g + - (absx-0.5)*(log(absx+lanczos_g-0.5)-1)); - } - if (Py_IS_INFINITY(r)) - errno = ERANGE; - return r; + /* special cases */ + if (!Py_IS_FINITE(x)) { + if (Py_IS_NAN(x)) + return x; /* lgamma(nan) = nan */ + else + return Py_HUGE_VAL; /* lgamma(+-inf) = +inf */ + } + + /* integer arguments */ + if (x == floor(x) && x <= 2.0) { + if (x <= 0.0) { + errno = EDOM; /* lgamma(n) = inf, divide-by-zero for */ + return Py_HUGE_VAL; /* integers n <= 0 */ + } + else { + return 0.0; /* lgamma(1) = lgamma(2) = 0.0 */ + } + } + + absx = fabs(x); + /* tiny arguments: lgamma(x) ~ -log(fabs(x)) for small x */ + if (absx < 1e-20) + return -log(absx); + + /* Lanczos' formula */ + if (x > 0.0) { + /* we could save a fraction of a ulp in accuracy by having a + second set of numerator coefficients for lanczos_sum that + absorbed the exp(-lanczos_g) term, and throwing out the + lanczos_g subtraction below; it's probably not worth it. */ + r = log(lanczos_sum(x)) - lanczos_g + + (x-0.5)*(log(x+lanczos_g-0.5)-1); + } + else { + r = log(pi) - log(fabs(sinpi(absx))) - log(absx) - + (log(lanczos_sum(absx)) - lanczos_g + + (absx-0.5)*(log(absx+lanczos_g-0.5)-1)); + } + if (Py_IS_INFINITY(r)) + errno = ERANGE; + return r; } /* @@ -428,17 +428,17 @@ static double m_erf_series(double x) { - double x2, acc, fk; - int i; + double x2, acc, fk; + int i; - x2 = x * x; - acc = 0.0; - fk = (double)ERF_SERIES_TERMS + 0.5; - for (i = 0; i < ERF_SERIES_TERMS; i++) { - acc = 2.0 + x2 * acc / fk; - fk -= 1.0; - } - return acc * x * exp(-x2) / sqrtpi; + x2 = x * x; + acc = 0.0; + fk = (double)ERF_SERIES_TERMS + 0.5; + for (i = 0; i < ERF_SERIES_TERMS; i++) { + acc = 2.0 + x2 * acc / fk; + fk -= 1.0; + } + return acc * x * exp(-x2) / sqrtpi; } /* @@ -453,26 +453,26 @@ static double m_erfc_contfrac(double x) { - double x2, a, da, p, p_last, q, q_last, b; - int i; + double x2, a, da, p, p_last, q, q_last, b; + int i; - if (x >= ERFC_CONTFRAC_CUTOFF) - return 0.0; + if (x >= ERFC_CONTFRAC_CUTOFF) + return 0.0; - x2 = x*x; - a = 0.0; - da = 0.5; - p = 1.0; p_last = 0.0; - q = da + x2; q_last = 1.0; - for (i = 0; i < ERFC_CONTFRAC_TERMS; i++) { - double temp; - a += da; - da += 2.0; - b = da + x2; - temp = p; p = b*p - a*p_last; p_last = temp; - temp = q; q = b*q - a*q_last; q_last = temp; - } - return p / q * x * exp(-x2) / sqrtpi; + x2 = x*x; + a = 0.0; + da = 0.5; + p = 1.0; p_last = 0.0; + q = da + x2; q_last = 1.0; + for (i = 0; i < ERFC_CONTFRAC_TERMS; i++) { + double temp; + a += da; + da += 2.0; + b = da + x2; + temp = p; p = b*p - a*p_last; p_last = temp; + temp = q; q = b*q - a*q_last; q_last = temp; + } + return p / q * x * exp(-x2) / sqrtpi; } /* Error function erf(x), for general x */ @@ -480,17 +480,17 @@ static double m_erf(double x) { - double absx, cf; + double absx, cf; - if (Py_IS_NAN(x)) - return x; - absx = fabs(x); - if (absx < ERF_SERIES_CUTOFF) - return m_erf_series(x); - else { - cf = m_erfc_contfrac(absx); - return x > 0.0 ? 1.0 - cf : cf - 1.0; - } + if (Py_IS_NAN(x)) + return x; + absx = fabs(x); + if (absx < ERF_SERIES_CUTOFF) + return m_erf_series(x); + else { + cf = m_erfc_contfrac(absx); + return x > 0.0 ? 1.0 - cf : cf - 1.0; + } } /* Complementary error function erfc(x), for general x. */ @@ -498,17 +498,17 @@ static double m_erfc(double x) { - double absx, cf; + double absx, cf; - if (Py_IS_NAN(x)) - return x; - absx = fabs(x); - if (absx < ERF_SERIES_CUTOFF) - return 1.0 - m_erf_series(x); - else { - cf = m_erfc_contfrac(absx); - return x > 0.0 ? cf : 2.0 - cf; - } + if (Py_IS_NAN(x)) + return x; + absx = fabs(x); + if (absx < ERF_SERIES_CUTOFF) + return 1.0 - m_erf_series(x); + else { + cf = m_erfc_contfrac(absx); + return x > 0.0 ? cf : 2.0 - cf; + } } /* @@ -522,29 +522,29 @@ static double m_atan2(double y, double x) { - if (Py_IS_NAN(x) || Py_IS_NAN(y)) - return Py_NAN; - if (Py_IS_INFINITY(y)) { - if (Py_IS_INFINITY(x)) { - if (copysign(1., x) == 1.) - /* atan2(+-inf, +inf) == +-pi/4 */ - return copysign(0.25*Py_MATH_PI, y); - else - /* atan2(+-inf, -inf) == +-pi*3/4 */ - return copysign(0.75*Py_MATH_PI, y); - } - /* atan2(+-inf, x) == +-pi/2 for finite x */ - return copysign(0.5*Py_MATH_PI, y); - } - if (Py_IS_INFINITY(x) || y == 0.) { - if (copysign(1., x) == 1.) - /* atan2(+-y, +inf) = atan2(+-0, +x) = +-0. */ - return copysign(0., y); - else - /* atan2(+-y, -inf) = atan2(+-0., -x) = +-pi. */ - return copysign(Py_MATH_PI, y); - } - return atan2(y, x); + if (Py_IS_NAN(x) || Py_IS_NAN(y)) + return Py_NAN; + if (Py_IS_INFINITY(y)) { + if (Py_IS_INFINITY(x)) { + if (copysign(1., x) == 1.) + /* atan2(+-inf, +inf) == +-pi/4 */ + return copysign(0.25*Py_MATH_PI, y); + else + /* atan2(+-inf, -inf) == +-pi*3/4 */ + return copysign(0.75*Py_MATH_PI, y); + } + /* atan2(+-inf, x) == +-pi/2 for finite x */ + return copysign(0.5*Py_MATH_PI, y); + } + if (Py_IS_INFINITY(x) || y == 0.) { + if (copysign(1., x) == 1.) + /* atan2(+-y, +inf) = atan2(+-0, +x) = +-0. */ + return copysign(0., y); + else + /* atan2(+-y, -inf) = atan2(+-0., -x) = +-pi. */ + return copysign(Py_MATH_PI, y); + } + return atan2(y, x); } /* @@ -557,45 +557,45 @@ static double m_log(double x) { - if (Py_IS_FINITE(x)) { - if (x > 0.0) - return log(x); - errno = EDOM; - if (x == 0.0) - return -Py_HUGE_VAL; /* log(0) = -inf */ - else - return Py_NAN; /* log(-ve) = nan */ - } - else if (Py_IS_NAN(x)) - return x; /* log(nan) = nan */ - else if (x > 0.0) - return x; /* log(inf) = inf */ - else { - errno = EDOM; - return Py_NAN; /* log(-inf) = nan */ - } + if (Py_IS_FINITE(x)) { + if (x > 0.0) + return log(x); + errno = EDOM; + if (x == 0.0) + return -Py_HUGE_VAL; /* log(0) = -inf */ + else + return Py_NAN; /* log(-ve) = nan */ + } + else if (Py_IS_NAN(x)) + return x; /* log(nan) = nan */ + else if (x > 0.0) + return x; /* log(inf) = inf */ + else { + errno = EDOM; + return Py_NAN; /* log(-inf) = nan */ + } } static double m_log10(double x) { - if (Py_IS_FINITE(x)) { - if (x > 0.0) - return log10(x); - errno = EDOM; - if (x == 0.0) - return -Py_HUGE_VAL; /* log10(0) = -inf */ - else - return Py_NAN; /* log10(-ve) = nan */ - } - else if (Py_IS_NAN(x)) - return x; /* log10(nan) = nan */ - else if (x > 0.0) - return x; /* log10(inf) = inf */ - else { - errno = EDOM; - return Py_NAN; /* log10(-inf) = nan */ - } + if (Py_IS_FINITE(x)) { + if (x > 0.0) + return log10(x); + errno = EDOM; + if (x == 0.0) + return -Py_HUGE_VAL; /* log10(0) = -inf */ + else + return Py_NAN; /* log10(-ve) = nan */ + } + else if (Py_IS_NAN(x)) + return x; /* log10(nan) = nan */ + else if (x > 0.0) + return x; /* log10(inf) = inf */ + else { + errno = EDOM; + return Py_NAN; /* log10(-inf) = nan */ + } } @@ -606,37 +606,37 @@ static int is_error(double x) { - int result = 1; /* presumption of guilt */ - assert(errno); /* non-zero errno is a precondition for calling */ - if (errno == EDOM) - PyErr_SetString(PyExc_ValueError, "math domain error"); - - else if (errno == ERANGE) { - /* ANSI C generally requires libm functions to set ERANGE - * on overflow, but also generally *allows* them to set - * ERANGE on underflow too. There's no consistency about - * the latter across platforms. - * Alas, C99 never requires that errno be set. - * Here we suppress the underflow errors (libm functions - * should return a zero on underflow, and +- HUGE_VAL on - * overflow, so testing the result for zero suffices to - * distinguish the cases). - * - * On some platforms (Ubuntu/ia64) it seems that errno can be - * set to ERANGE for subnormal results that do *not* underflow - * to zero. So to be safe, we'll ignore ERANGE whenever the - * function result is less than one in absolute value. - */ - if (fabs(x) < 1.0) - result = 0; - else - PyErr_SetString(PyExc_OverflowError, - "math range error"); - } - else - /* Unexpected math error */ - PyErr_SetFromErrno(PyExc_ValueError); - return result; + int result = 1; /* presumption of guilt */ + assert(errno); /* non-zero errno is a precondition for calling */ + if (errno == EDOM) + PyErr_SetString(PyExc_ValueError, "math domain error"); + + else if (errno == ERANGE) { + /* ANSI C generally requires libm functions to set ERANGE + * on overflow, but also generally *allows* them to set + * ERANGE on underflow too. There's no consistency about + * the latter across platforms. + * Alas, C99 never requires that errno be set. + * Here we suppress the underflow errors (libm functions + * should return a zero on underflow, and +- HUGE_VAL on + * overflow, so testing the result for zero suffices to + * distinguish the cases). + * + * On some platforms (Ubuntu/ia64) it seems that errno can be + * set to ERANGE for subnormal results that do *not* underflow + * to zero. So to be safe, we'll ignore ERANGE whenever the + * function result is less than one in absolute value. + */ + if (fabs(x) < 1.0) + result = 0; + else + PyErr_SetString(PyExc_OverflowError, + "math range error"); + } + else + /* Unexpected math error */ + PyErr_SetFromErrno(PyExc_ValueError); + return result; } /* @@ -674,33 +674,33 @@ PyObject *(*from_double_func) (double), int can_overflow) { - double x, r; - x = PyFloat_AsDouble(arg); - if (x == -1.0 && PyErr_Occurred()) - return NULL; - errno = 0; - PyFPE_START_PROTECT("in math_1", return 0); - r = (*func)(x); - PyFPE_END_PROTECT(r); - if (Py_IS_NAN(r) && !Py_IS_NAN(x)) { - PyErr_SetString(PyExc_ValueError, - "math domain error"); /* invalid arg */ - return NULL; - } - if (Py_IS_INFINITY(r) && Py_IS_FINITE(x)) { - if (can_overflow) - PyErr_SetString(PyExc_OverflowError, - "math range error"); /* overflow */ - else - PyErr_SetString(PyExc_ValueError, - "math domain error"); /* singularity */ - return NULL; - } - if (Py_IS_FINITE(r) && errno && is_error(r)) - /* this branch unnecessary on most platforms */ - return NULL; + double x, r; + x = PyFloat_AsDouble(arg); + if (x == -1.0 && PyErr_Occurred()) + return NULL; + errno = 0; + PyFPE_START_PROTECT("in math_1", return 0); + r = (*func)(x); + PyFPE_END_PROTECT(r); + if (Py_IS_NAN(r) && !Py_IS_NAN(x)) { + PyErr_SetString(PyExc_ValueError, + "math domain error"); /* invalid arg */ + return NULL; + } + if (Py_IS_INFINITY(r) && Py_IS_FINITE(x)) { + if (can_overflow) + PyErr_SetString(PyExc_OverflowError, + "math range error"); /* overflow */ + else + PyErr_SetString(PyExc_ValueError, + "math domain error"); /* singularity */ + return NULL; + } + if (Py_IS_FINITE(r) && errno && is_error(r)) + /* this branch unnecessary on most platforms */ + return NULL; - return (*from_double_func)(r); + return (*from_double_func)(r); } /* variant of math_1, to be used when the function being wrapped is known to @@ -710,17 +710,17 @@ static PyObject * math_1a(PyObject *arg, double (*func) (double)) { - double x, r; - x = PyFloat_AsDouble(arg); - if (x == -1.0 && PyErr_Occurred()) - return NULL; - errno = 0; - PyFPE_START_PROTECT("in math_1a", return 0); - r = (*func)(x); - PyFPE_END_PROTECT(r); - if (errno && is_error(r)) - return NULL; - return PyFloat_FromDouble(r); + double x, r; + x = PyFloat_AsDouble(arg); + if (x == -1.0 && PyErr_Occurred()) + return NULL; + errno = 0; + PyFPE_START_PROTECT("in math_1a", return 0); + r = (*func)(x); + PyFPE_END_PROTECT(r); + if (errno && is_error(r)) + return NULL; + return PyFloat_FromDouble(r); } /* @@ -753,65 +753,65 @@ static PyObject * math_1(PyObject *arg, double (*func) (double), int can_overflow) { - return math_1_to_whatever(arg, func, PyFloat_FromDouble, can_overflow); + return math_1_to_whatever(arg, func, PyFloat_FromDouble, can_overflow); } static PyObject * math_1_to_int(PyObject *arg, double (*func) (double), int can_overflow) { - return math_1_to_whatever(arg, func, PyLong_FromDouble, can_overflow); + return math_1_to_whatever(arg, func, PyLong_FromDouble, can_overflow); } static PyObject * math_2(PyObject *args, double (*func) (double, double), char *funcname) { - PyObject *ox, *oy; - double x, y, r; - if (! PyArg_UnpackTuple(args, funcname, 2, 2, &ox, &oy)) - return NULL; - x = PyFloat_AsDouble(ox); - y = PyFloat_AsDouble(oy); - if ((x == -1.0 || y == -1.0) && PyErr_Occurred()) - return NULL; - errno = 0; - PyFPE_START_PROTECT("in math_2", return 0); - r = (*func)(x, y); - PyFPE_END_PROTECT(r); - if (Py_IS_NAN(r)) { - if (!Py_IS_NAN(x) && !Py_IS_NAN(y)) - errno = EDOM; - else - errno = 0; - } - else if (Py_IS_INFINITY(r)) { - if (Py_IS_FINITE(x) && Py_IS_FINITE(y)) - errno = ERANGE; - else - errno = 0; - } - if (errno && is_error(r)) - return NULL; - else - return PyFloat_FromDouble(r); -} - -#define FUNC1(funcname, func, can_overflow, docstring) \ - static PyObject * math_##funcname(PyObject *self, PyObject *args) { \ - return math_1(args, func, can_overflow); \ - }\ - PyDoc_STRVAR(math_##funcname##_doc, docstring); - -#define FUNC1A(funcname, func, docstring) \ - static PyObject * math_##funcname(PyObject *self, PyObject *args) { \ - return math_1a(args, func); \ - }\ - PyDoc_STRVAR(math_##funcname##_doc, docstring); + PyObject *ox, *oy; + double x, y, r; + if (! PyArg_UnpackTuple(args, funcname, 2, 2, &ox, &oy)) + return NULL; + x = PyFloat_AsDouble(ox); + y = PyFloat_AsDouble(oy); + if ((x == -1.0 || y == -1.0) && PyErr_Occurred()) + return NULL; + errno = 0; + PyFPE_START_PROTECT("in math_2", return 0); + r = (*func)(x, y); + PyFPE_END_PROTECT(r); + if (Py_IS_NAN(r)) { + if (!Py_IS_NAN(x) && !Py_IS_NAN(y)) + errno = EDOM; + else + errno = 0; + } + else if (Py_IS_INFINITY(r)) { + if (Py_IS_FINITE(x) && Py_IS_FINITE(y)) + errno = ERANGE; + else + errno = 0; + } + if (errno && is_error(r)) + return NULL; + else + return PyFloat_FromDouble(r); +} + +#define FUNC1(funcname, func, can_overflow, docstring) \ + static PyObject * math_##funcname(PyObject *self, PyObject *args) { \ + return math_1(args, func, can_overflow); \ + }\ + PyDoc_STRVAR(math_##funcname##_doc, docstring); + +#define FUNC1A(funcname, func, docstring) \ + static PyObject * math_##funcname(PyObject *self, PyObject *args) { \ + return math_1a(args, func); \ + }\ + PyDoc_STRVAR(math_##funcname##_doc, docstring); #define FUNC2(funcname, func, docstring) \ - static PyObject * math_##funcname(PyObject *self, PyObject *args) { \ - return math_2(args, func, #funcname); \ - }\ - PyDoc_STRVAR(math_##funcname##_doc, docstring); + static PyObject * math_##funcname(PyObject *self, PyObject *args) { \ + return math_2(args, func, #funcname); \ + }\ + PyDoc_STRVAR(math_##funcname##_doc, docstring); FUNC1(acos, acos, 0, "acos(x)\n\nReturn the arc cosine (measured in radians) of x.") @@ -830,25 +830,25 @@ "atanh(x)\n\nReturn the hyperbolic arc tangent (measured in radians) of x.") static PyObject * math_ceil(PyObject *self, PyObject *number) { - static PyObject *ceil_str = NULL; - PyObject *method; + static PyObject *ceil_str = NULL; + PyObject *method; - if (ceil_str == NULL) { - ceil_str = PyUnicode_InternFromString("__ceil__"); - if (ceil_str == NULL) - return NULL; - } - - method = _PyType_Lookup(Py_TYPE(number), ceil_str); - if (method == NULL) - return math_1_to_int(number, ceil, 0); - else - return PyObject_CallFunction(method, "O", number); + if (ceil_str == NULL) { + ceil_str = PyUnicode_InternFromString("__ceil__"); + if (ceil_str == NULL) + return NULL; + } + + method = _PyType_Lookup(Py_TYPE(number), ceil_str); + if (method == NULL) + return math_1_to_int(number, ceil, 0); + else + return PyObject_CallFunction(method, "O", number); } PyDoc_STRVAR(math_ceil_doc, - "ceil(x)\n\nReturn the ceiling of x as an int.\n" - "This is the smallest integral value >= x."); + "ceil(x)\n\nReturn the ceiling of x as an int.\n" + "This is the smallest integral value >= x."); FUNC2(copysign, copysign, "copysign(x, y)\n\nReturn x with the sign of y.") @@ -870,25 +870,25 @@ "fabs(x)\n\nReturn the absolute value of the float x.") static PyObject * math_floor(PyObject *self, PyObject *number) { - static PyObject *floor_str = NULL; - PyObject *method; + static PyObject *floor_str = NULL; + PyObject *method; - if (floor_str == NULL) { - floor_str = PyUnicode_InternFromString("__floor__"); - if (floor_str == NULL) - return NULL; - } - - method = _PyType_Lookup(Py_TYPE(number), floor_str); - if (method == NULL) - return math_1_to_int(number, floor, 0); - else - return PyObject_CallFunction(method, "O", number); + if (floor_str == NULL) { + floor_str = PyUnicode_InternFromString("__floor__"); + if (floor_str == NULL) + return NULL; + } + + method = _PyType_Lookup(Py_TYPE(number), floor_str); + if (method == NULL) + return math_1_to_int(number, floor, 0); + else + return PyObject_CallFunction(method, "O", number); } PyDoc_STRVAR(math_floor_doc, - "floor(x)\n\nReturn the floor of x as an int.\n" - "This is the largest integral value <= x."); + "floor(x)\n\nReturn the floor of x as an int.\n" + "This is the largest integral value <= x."); FUNC1A(gamma, m_tgamma, "gamma(x)\n\nGamma function at x.") @@ -928,7 +928,7 @@ Also, the volatile declaration forces the values to be stored in memory as regular doubles instead of extended long precision (80-bit) values. This prevents double rounding because any addition or subtraction of two doubles - can be resolved exactly into double-sized hi and lo values. As long as the + can be resolved exactly into double-sized hi and lo values. As long as the hi value gets forced into a double before yr and lo are computed, the extra bits in downstream extended precision operations (x87 for example) will be exactly zero and therefore can be losslessly stored back into a double, @@ -951,27 +951,27 @@ _fsum_realloc(double **p_ptr, Py_ssize_t n, double *ps, Py_ssize_t *m_ptr) { - void *v = NULL; - Py_ssize_t m = *m_ptr; + void *v = NULL; + Py_ssize_t m = *m_ptr; - m += m; /* double */ - if (n < m && m < (PY_SSIZE_T_MAX / sizeof(double))) { - double *p = *p_ptr; - if (p == ps) { - v = PyMem_Malloc(sizeof(double) * m); - if (v != NULL) - memcpy(v, ps, sizeof(double) * n); - } - else - v = PyMem_Realloc(p, sizeof(double) * m); - } - if (v == NULL) { /* size overflow or no memory */ - PyErr_SetString(PyExc_MemoryError, "math.fsum partials"); - return 1; - } - *p_ptr = (double*) v; - *m_ptr = m; - return 0; + m += m; /* double */ + if (n < m && m < (PY_SSIZE_T_MAX / sizeof(double))) { + double *p = *p_ptr; + if (p == ps) { + v = PyMem_Malloc(sizeof(double) * m); + if (v != NULL) + memcpy(v, ps, sizeof(double) * n); + } + else + v = PyMem_Realloc(p, sizeof(double) * m); + } + if (v == NULL) { /* size overflow or no memory */ + PyErr_SetString(PyExc_MemoryError, "math.fsum partials"); + return 1; + } + *p_ptr = (double*) v; + *m_ptr = m; + return 0; } /* Full precision summation of a sequence of floats. @@ -979,17 +979,17 @@ def msum(iterable): partials = [] # sorted, non-overlapping partial sums for x in iterable: - i = 0 - for y in partials: - if abs(x) < abs(y): - x, y = y, x - hi = x + y - lo = y - (hi - x) - if lo: - partials[i] = lo - i += 1 - x = hi - partials[i:] = [x] + i = 0 + for y in partials: + if abs(x) < abs(y): + x, y = y, x + hi = x + y + lo = y - (hi - x) + if lo: + partials[i] = lo + i += 1 + x = hi + partials[i:] = [x] return sum_exact(partials) Rounded x+y stored in hi with the roundoff stored in lo. Together hi+lo @@ -1007,119 +1007,119 @@ static PyObject* math_fsum(PyObject *self, PyObject *seq) { - PyObject *item, *iter, *sum = NULL; - Py_ssize_t i, j, n = 0, m = NUM_PARTIALS; - double x, y, t, ps[NUM_PARTIALS], *p = ps; - double xsave, special_sum = 0.0, inf_sum = 0.0; - volatile double hi, yr, lo; - - iter = PyObject_GetIter(seq); - if (iter == NULL) - return NULL; - - PyFPE_START_PROTECT("fsum", Py_DECREF(iter); return NULL) - - for(;;) { /* for x in iterable */ - assert(0 <= n && n <= m); - assert((m == NUM_PARTIALS && p == ps) || - (m > NUM_PARTIALS && p != NULL)); - - item = PyIter_Next(iter); - if (item == NULL) { - if (PyErr_Occurred()) - goto _fsum_error; - break; - } - x = PyFloat_AsDouble(item); - Py_DECREF(item); - if (PyErr_Occurred()) - goto _fsum_error; - - xsave = x; - for (i = j = 0; j < n; j++) { /* for y in partials */ - y = p[j]; - if (fabs(x) < fabs(y)) { - t = x; x = y; y = t; - } - hi = x + y; - yr = hi - x; - lo = y - yr; - if (lo != 0.0) - p[i++] = lo; - x = hi; - } - - n = i; /* ps[i:] = [x] */ - if (x != 0.0) { - if (! Py_IS_FINITE(x)) { - /* a nonfinite x could arise either as - a result of intermediate overflow, or - as a result of a nan or inf in the - summands */ - if (Py_IS_FINITE(xsave)) { - PyErr_SetString(PyExc_OverflowError, - "intermediate overflow in fsum"); - goto _fsum_error; - } - if (Py_IS_INFINITY(xsave)) - inf_sum += xsave; - special_sum += xsave; - /* reset partials */ - n = 0; - } - else if (n >= m && _fsum_realloc(&p, n, ps, &m)) - goto _fsum_error; - else - p[n++] = x; - } - } - - if (special_sum != 0.0) { - if (Py_IS_NAN(inf_sum)) - PyErr_SetString(PyExc_ValueError, - "-inf + inf in fsum"); - else - sum = PyFloat_FromDouble(special_sum); - goto _fsum_error; - } - - hi = 0.0; - if (n > 0) { - hi = p[--n]; - /* sum_exact(ps, hi) from the top, stop when the sum becomes - inexact. */ - while (n > 0) { - x = hi; - y = p[--n]; - assert(fabs(y) < fabs(x)); - hi = x + y; - yr = hi - x; - lo = y - yr; - if (lo != 0.0) - break; - } - /* Make half-even rounding work across multiple partials. - Needed so that sum([1e-16, 1, 1e16]) will round-up the last - digit to two instead of down to zero (the 1e-16 makes the 1 - slightly closer to two). With a potential 1 ULP rounding - error fixed-up, math.fsum() can guarantee commutativity. */ - if (n > 0 && ((lo < 0.0 && p[n-1] < 0.0) || - (lo > 0.0 && p[n-1] > 0.0))) { - y = lo * 2.0; - x = hi + y; - yr = x - hi; - if (y == yr) - hi = x; - } - } - sum = PyFloat_FromDouble(hi); + PyObject *item, *iter, *sum = NULL; + Py_ssize_t i, j, n = 0, m = NUM_PARTIALS; + double x, y, t, ps[NUM_PARTIALS], *p = ps; + double xsave, special_sum = 0.0, inf_sum = 0.0; + volatile double hi, yr, lo; + + iter = PyObject_GetIter(seq); + if (iter == NULL) + return NULL; + + PyFPE_START_PROTECT("fsum", Py_DECREF(iter); return NULL) + + for(;;) { /* for x in iterable */ + assert(0 <= n && n <= m); + assert((m == NUM_PARTIALS && p == ps) || + (m > NUM_PARTIALS && p != NULL)); + + item = PyIter_Next(iter); + if (item == NULL) { + if (PyErr_Occurred()) + goto _fsum_error; + break; + } + x = PyFloat_AsDouble(item); + Py_DECREF(item); + if (PyErr_Occurred()) + goto _fsum_error; + + xsave = x; + for (i = j = 0; j < n; j++) { /* for y in partials */ + y = p[j]; + if (fabs(x) < fabs(y)) { + t = x; x = y; y = t; + } + hi = x + y; + yr = hi - x; + lo = y - yr; + if (lo != 0.0) + p[i++] = lo; + x = hi; + } + + n = i; /* ps[i:] = [x] */ + if (x != 0.0) { + if (! Py_IS_FINITE(x)) { + /* a nonfinite x could arise either as + a result of intermediate overflow, or + as a result of a nan or inf in the + summands */ + if (Py_IS_FINITE(xsave)) { + PyErr_SetString(PyExc_OverflowError, + "intermediate overflow in fsum"); + goto _fsum_error; + } + if (Py_IS_INFINITY(xsave)) + inf_sum += xsave; + special_sum += xsave; + /* reset partials */ + n = 0; + } + else if (n >= m && _fsum_realloc(&p, n, ps, &m)) + goto _fsum_error; + else + p[n++] = x; + } + } + + if (special_sum != 0.0) { + if (Py_IS_NAN(inf_sum)) + PyErr_SetString(PyExc_ValueError, + "-inf + inf in fsum"); + else + sum = PyFloat_FromDouble(special_sum); + goto _fsum_error; + } + + hi = 0.0; + if (n > 0) { + hi = p[--n]; + /* sum_exact(ps, hi) from the top, stop when the sum becomes + inexact. */ + while (n > 0) { + x = hi; + y = p[--n]; + assert(fabs(y) < fabs(x)); + hi = x + y; + yr = hi - x; + lo = y - yr; + if (lo != 0.0) + break; + } + /* Make half-even rounding work across multiple partials. + Needed so that sum([1e-16, 1, 1e16]) will round-up the last + digit to two instead of down to zero (the 1e-16 makes the 1 + slightly closer to two). With a potential 1 ULP rounding + error fixed-up, math.fsum() can guarantee commutativity. */ + if (n > 0 && ((lo < 0.0 && p[n-1] < 0.0) || + (lo > 0.0 && p[n-1] > 0.0))) { + y = lo * 2.0; + x = hi + y; + yr = x - hi; + if (y == yr) + hi = x; + } + } + sum = PyFloat_FromDouble(hi); _fsum_error: - PyFPE_END_PROTECT(hi) - Py_DECREF(iter); - if (p != ps) - PyMem_Free(p); - return sum; + PyFPE_END_PROTECT(hi) + Py_DECREF(iter); + if (p != ps) + PyMem_Free(p); + return sum; } #undef NUM_PARTIALS @@ -1132,53 +1132,53 @@ static PyObject * math_factorial(PyObject *self, PyObject *arg) { - long i, x; - PyObject *result, *iobj, *newresult; + long i, x; + PyObject *result, *iobj, *newresult; - if (PyFloat_Check(arg)) { - PyObject *lx; - double dx = PyFloat_AS_DOUBLE((PyFloatObject *)arg); - if (!(Py_IS_FINITE(dx) && dx == floor(dx))) { - PyErr_SetString(PyExc_ValueError, - "factorial() only accepts integral values"); - return NULL; - } - lx = PyLong_FromDouble(dx); - if (lx == NULL) - return NULL; - x = PyLong_AsLong(lx); - Py_DECREF(lx); - } - else - x = PyLong_AsLong(arg); - - if (x == -1 && PyErr_Occurred()) - return NULL; - if (x < 0) { - PyErr_SetString(PyExc_ValueError, - "factorial() not defined for negative values"); - return NULL; - } - - result = (PyObject *)PyLong_FromLong(1); - if (result == NULL) - return NULL; - for (i=1 ; i<=x ; i++) { - iobj = (PyObject *)PyLong_FromLong(i); - if (iobj == NULL) - goto error; - newresult = PyNumber_Multiply(result, iobj); - Py_DECREF(iobj); - if (newresult == NULL) - goto error; - Py_DECREF(result); - result = newresult; - } - return result; + if (PyFloat_Check(arg)) { + PyObject *lx; + double dx = PyFloat_AS_DOUBLE((PyFloatObject *)arg); + if (!(Py_IS_FINITE(dx) && dx == floor(dx))) { + PyErr_SetString(PyExc_ValueError, + "factorial() only accepts integral values"); + return NULL; + } + lx = PyLong_FromDouble(dx); + if (lx == NULL) + return NULL; + x = PyLong_AsLong(lx); + Py_DECREF(lx); + } + else + x = PyLong_AsLong(arg); + + if (x == -1 && PyErr_Occurred()) + return NULL; + if (x < 0) { + PyErr_SetString(PyExc_ValueError, + "factorial() not defined for negative values"); + return NULL; + } + + result = (PyObject *)PyLong_FromLong(1); + if (result == NULL) + return NULL; + for (i=1 ; i<=x ; i++) { + iobj = (PyObject *)PyLong_FromLong(i); + if (iobj == NULL) + goto error; + newresult = PyNumber_Multiply(result, iobj); + Py_DECREF(iobj); + if (newresult == NULL) + goto error; + Py_DECREF(result); + result = newresult; + } + return result; error: - Py_DECREF(result); - return NULL; + Py_DECREF(result); + return NULL; } PyDoc_STRVAR(math_factorial_doc, @@ -1189,28 +1189,28 @@ static PyObject * math_trunc(PyObject *self, PyObject *number) { - static PyObject *trunc_str = NULL; - PyObject *trunc; + static PyObject *trunc_str = NULL; + PyObject *trunc; - if (Py_TYPE(number)->tp_dict == NULL) { - if (PyType_Ready(Py_TYPE(number)) < 0) - return NULL; - } - - if (trunc_str == NULL) { - trunc_str = PyUnicode_InternFromString("__trunc__"); - if (trunc_str == NULL) - return NULL; - } - - trunc = _PyType_Lookup(Py_TYPE(number), trunc_str); - if (trunc == NULL) { - PyErr_Format(PyExc_TypeError, - "type %.100s doesn't define __trunc__ method", - Py_TYPE(number)->tp_name); - return NULL; - } - return PyObject_CallFunctionObjArgs(trunc, number, NULL); + if (Py_TYPE(number)->tp_dict == NULL) { + if (PyType_Ready(Py_TYPE(number)) < 0) + return NULL; + } + + if (trunc_str == NULL) { + trunc_str = PyUnicode_InternFromString("__trunc__"); + if (trunc_str == NULL) + return NULL; + } + + trunc = _PyType_Lookup(Py_TYPE(number), trunc_str); + if (trunc == NULL) { + PyErr_Format(PyExc_TypeError, + "type %.100s doesn't define __trunc__ method", + Py_TYPE(number)->tp_name); + return NULL; + } + return PyObject_CallFunctionObjArgs(trunc, number, NULL); } PyDoc_STRVAR(math_trunc_doc, @@ -1221,21 +1221,21 @@ static PyObject * math_frexp(PyObject *self, PyObject *arg) { - int i; - double x = PyFloat_AsDouble(arg); - if (x == -1.0 && PyErr_Occurred()) - return NULL; - /* deal with special cases directly, to sidestep platform - differences */ - if (Py_IS_NAN(x) || Py_IS_INFINITY(x) || !x) { - i = 0; - } - else { - PyFPE_START_PROTECT("in math_frexp", return 0); - x = frexp(x, &i); - PyFPE_END_PROTECT(x); - } - return Py_BuildValue("(di)", x, i); + int i; + double x = PyFloat_AsDouble(arg); + if (x == -1.0 && PyErr_Occurred()) + return NULL; + /* deal with special cases directly, to sidestep platform + differences */ + if (Py_IS_NAN(x) || Py_IS_INFINITY(x) || !x) { + i = 0; + } + else { + PyFPE_START_PROTECT("in math_frexp", return 0); + x = frexp(x, &i); + PyFPE_END_PROTECT(x); + } + return Py_BuildValue("(di)", x, i); } PyDoc_STRVAR(math_frexp_doc, @@ -1248,53 +1248,53 @@ static PyObject * math_ldexp(PyObject *self, PyObject *args) { - double x, r; - PyObject *oexp; - long exp; - int overflow; - if (! PyArg_ParseTuple(args, "dO:ldexp", &x, &oexp)) - return NULL; - - if (PyLong_Check(oexp)) { - /* on overflow, replace exponent with either LONG_MAX - or LONG_MIN, depending on the sign. */ - exp = PyLong_AsLongAndOverflow(oexp, &overflow); - if (exp == -1 && PyErr_Occurred()) - return NULL; - if (overflow) - exp = overflow < 0 ? LONG_MIN : LONG_MAX; - } - else { - PyErr_SetString(PyExc_TypeError, - "Expected an int or long as second argument " - "to ldexp."); - return NULL; - } - - if (x == 0. || !Py_IS_FINITE(x)) { - /* NaNs, zeros and infinities are returned unchanged */ - r = x; - errno = 0; - } else if (exp > INT_MAX) { - /* overflow */ - r = copysign(Py_HUGE_VAL, x); - errno = ERANGE; - } else if (exp < INT_MIN) { - /* underflow to +-0 */ - r = copysign(0., x); - errno = 0; - } else { - errno = 0; - PyFPE_START_PROTECT("in math_ldexp", return 0); - r = ldexp(x, (int)exp); - PyFPE_END_PROTECT(r); - if (Py_IS_INFINITY(r)) - errno = ERANGE; - } - - if (errno && is_error(r)) - return NULL; - return PyFloat_FromDouble(r); + double x, r; + PyObject *oexp; + long exp; + int overflow; + if (! PyArg_ParseTuple(args, "dO:ldexp", &x, &oexp)) + return NULL; + + if (PyLong_Check(oexp)) { + /* on overflow, replace exponent with either LONG_MAX + or LONG_MIN, depending on the sign. */ + exp = PyLong_AsLongAndOverflow(oexp, &overflow); + if (exp == -1 && PyErr_Occurred()) + return NULL; + if (overflow) + exp = overflow < 0 ? LONG_MIN : LONG_MAX; + } + else { + PyErr_SetString(PyExc_TypeError, + "Expected an int or long as second argument " + "to ldexp."); + return NULL; + } + + if (x == 0. || !Py_IS_FINITE(x)) { + /* NaNs, zeros and infinities are returned unchanged */ + r = x; + errno = 0; + } else if (exp > INT_MAX) { + /* overflow */ + r = copysign(Py_HUGE_VAL, x); + errno = ERANGE; + } else if (exp < INT_MIN) { + /* underflow to +-0 */ + r = copysign(0., x); + errno = 0; + } else { + errno = 0; + PyFPE_START_PROTECT("in math_ldexp", return 0); + r = ldexp(x, (int)exp); + PyFPE_END_PROTECT(r); + if (Py_IS_INFINITY(r)) + errno = ERANGE; + } + + if (errno && is_error(r)) + return NULL; + return PyFloat_FromDouble(r); } PyDoc_STRVAR(math_ldexp_doc, @@ -1304,23 +1304,23 @@ static PyObject * math_modf(PyObject *self, PyObject *arg) { - double y, x = PyFloat_AsDouble(arg); - if (x == -1.0 && PyErr_Occurred()) - return NULL; - /* some platforms don't do the right thing for NaNs and - infinities, so we take care of special cases directly. */ - if (!Py_IS_FINITE(x)) { - if (Py_IS_INFINITY(x)) - return Py_BuildValue("(dd)", copysign(0., x), x); - else if (Py_IS_NAN(x)) - return Py_BuildValue("(dd)", x, x); - } - - errno = 0; - PyFPE_START_PROTECT("in math_modf", return 0); - x = modf(x, &y); - PyFPE_END_PROTECT(x); - return Py_BuildValue("(dd)", x, y); + double y, x = PyFloat_AsDouble(arg); + if (x == -1.0 && PyErr_Occurred()) + return NULL; + /* some platforms don't do the right thing for NaNs and + infinities, so we take care of special cases directly. */ + if (!Py_IS_FINITE(x)) { + if (Py_IS_INFINITY(x)) + return Py_BuildValue("(dd)", copysign(0., x), x); + else if (Py_IS_NAN(x)) + return Py_BuildValue("(dd)", x, x); + } + + errno = 0; + PyFPE_START_PROTECT("in math_modf", return 0); + x = modf(x, &y); + PyFPE_END_PROTECT(x); + return Py_BuildValue("(dd)", x, y); } PyDoc_STRVAR(math_modf_doc, @@ -1341,56 +1341,56 @@ static PyObject* loghelper(PyObject* arg, double (*func)(double), char *funcname) { - /* If it is long, do it ourselves. */ - if (PyLong_Check(arg)) { - double x; - Py_ssize_t e; - x = _PyLong_Frexp((PyLongObject *)arg, &e); - if (x == -1.0 && PyErr_Occurred()) - return NULL; - if (x <= 0.0) { - PyErr_SetString(PyExc_ValueError, - "math domain error"); - return NULL; - } - /* Special case for log(1), to make sure we get an - exact result there. */ - if (e == 1 && x == 0.5) - return PyFloat_FromDouble(0.0); - /* Value is ~= x * 2**e, so the log ~= log(x) + log(2) * e. */ - x = func(x) + func(2.0) * e; - return PyFloat_FromDouble(x); - } + /* If it is long, do it ourselves. */ + if (PyLong_Check(arg)) { + double x; + Py_ssize_t e; + x = _PyLong_Frexp((PyLongObject *)arg, &e); + if (x == -1.0 && PyErr_Occurred()) + return NULL; + if (x <= 0.0) { + PyErr_SetString(PyExc_ValueError, + "math domain error"); + return NULL; + } + /* Special case for log(1), to make sure we get an + exact result there. */ + if (e == 1 && x == 0.5) + return PyFloat_FromDouble(0.0); + /* Value is ~= x * 2**e, so the log ~= log(x) + log(2) * e. */ + x = func(x) + func(2.0) * e; + return PyFloat_FromDouble(x); + } - /* Else let libm handle it by itself. */ - return math_1(arg, func, 0); + /* Else let libm handle it by itself. */ + return math_1(arg, func, 0); } static PyObject * math_log(PyObject *self, PyObject *args) { - PyObject *arg; - PyObject *base = NULL; - PyObject *num, *den; - PyObject *ans; - - if (!PyArg_UnpackTuple(args, "log", 1, 2, &arg, &base)) - return NULL; - - num = loghelper(arg, m_log, "log"); - if (num == NULL || base == NULL) - return num; - - den = loghelper(base, m_log, "log"); - if (den == NULL) { - Py_DECREF(num); - return NULL; - } - - ans = PyNumber_TrueDivide(num, den); - Py_DECREF(num); - Py_DECREF(den); - return ans; + PyObject *arg; + PyObject *base = NULL; + PyObject *num, *den; + PyObject *ans; + + if (!PyArg_UnpackTuple(args, "log", 1, 2, &arg, &base)) + return NULL; + + num = loghelper(arg, m_log, "log"); + if (num == NULL || base == NULL) + return num; + + den = loghelper(base, m_log, "log"); + if (den == NULL) { + Py_DECREF(num); + return NULL; + } + + ans = PyNumber_TrueDivide(num, den); + Py_DECREF(num); + Py_DECREF(den); + return ans; } PyDoc_STRVAR(math_log_doc, @@ -1401,7 +1401,7 @@ static PyObject * math_log10(PyObject *self, PyObject *arg) { - return loghelper(arg, m_log10, "log10"); + return loghelper(arg, m_log10, "log10"); } PyDoc_STRVAR(math_log10_doc, @@ -1410,31 +1410,31 @@ static PyObject * math_fmod(PyObject *self, PyObject *args) { - PyObject *ox, *oy; - double r, x, y; - if (! PyArg_UnpackTuple(args, "fmod", 2, 2, &ox, &oy)) - return NULL; - x = PyFloat_AsDouble(ox); - y = PyFloat_AsDouble(oy); - if ((x == -1.0 || y == -1.0) && PyErr_Occurred()) - return NULL; - /* fmod(x, +/-Inf) returns x for finite x. */ - if (Py_IS_INFINITY(y) && Py_IS_FINITE(x)) - return PyFloat_FromDouble(x); - errno = 0; - PyFPE_START_PROTECT("in math_fmod", return 0); - r = fmod(x, y); - PyFPE_END_PROTECT(r); - if (Py_IS_NAN(r)) { - if (!Py_IS_NAN(x) && !Py_IS_NAN(y)) - errno = EDOM; - else - errno = 0; - } - if (errno && is_error(r)) - return NULL; - else - return PyFloat_FromDouble(r); + PyObject *ox, *oy; + double r, x, y; + if (! PyArg_UnpackTuple(args, "fmod", 2, 2, &ox, &oy)) + return NULL; + x = PyFloat_AsDouble(ox); + y = PyFloat_AsDouble(oy); + if ((x == -1.0 || y == -1.0) && PyErr_Occurred()) + return NULL; + /* fmod(x, +/-Inf) returns x for finite x. */ + if (Py_IS_INFINITY(y) && Py_IS_FINITE(x)) + return PyFloat_FromDouble(x); + errno = 0; + PyFPE_START_PROTECT("in math_fmod", return 0); + r = fmod(x, y); + PyFPE_END_PROTECT(r); + if (Py_IS_NAN(r)) { + if (!Py_IS_NAN(x) && !Py_IS_NAN(y)) + errno = EDOM; + else + errno = 0; + } + if (errno && is_error(r)) + return NULL; + else + return PyFloat_FromDouble(r); } PyDoc_STRVAR(math_fmod_doc, @@ -1444,39 +1444,39 @@ static PyObject * math_hypot(PyObject *self, PyObject *args) { - PyObject *ox, *oy; - double r, x, y; - if (! PyArg_UnpackTuple(args, "hypot", 2, 2, &ox, &oy)) - return NULL; - x = PyFloat_AsDouble(ox); - y = PyFloat_AsDouble(oy); - if ((x == -1.0 || y == -1.0) && PyErr_Occurred()) - return NULL; - /* hypot(x, +/-Inf) returns Inf, even if x is a NaN. */ - if (Py_IS_INFINITY(x)) - return PyFloat_FromDouble(fabs(x)); - if (Py_IS_INFINITY(y)) - return PyFloat_FromDouble(fabs(y)); - errno = 0; - PyFPE_START_PROTECT("in math_hypot", return 0); - r = hypot(x, y); - PyFPE_END_PROTECT(r); - if (Py_IS_NAN(r)) { - if (!Py_IS_NAN(x) && !Py_IS_NAN(y)) - errno = EDOM; - else - errno = 0; - } - else if (Py_IS_INFINITY(r)) { - if (Py_IS_FINITE(x) && Py_IS_FINITE(y)) - errno = ERANGE; - else - errno = 0; - } - if (errno && is_error(r)) - return NULL; - else - return PyFloat_FromDouble(r); + PyObject *ox, *oy; + double r, x, y; + if (! PyArg_UnpackTuple(args, "hypot", 2, 2, &ox, &oy)) + return NULL; + x = PyFloat_AsDouble(ox); + y = PyFloat_AsDouble(oy); + if ((x == -1.0 || y == -1.0) && PyErr_Occurred()) + return NULL; + /* hypot(x, +/-Inf) returns Inf, even if x is a NaN. */ + if (Py_IS_INFINITY(x)) + return PyFloat_FromDouble(fabs(x)); + if (Py_IS_INFINITY(y)) + return PyFloat_FromDouble(fabs(y)); + errno = 0; + PyFPE_START_PROTECT("in math_hypot", return 0); + r = hypot(x, y); + PyFPE_END_PROTECT(r); + if (Py_IS_NAN(r)) { + if (!Py_IS_NAN(x) && !Py_IS_NAN(y)) + errno = EDOM; + else + errno = 0; + } + else if (Py_IS_INFINITY(r)) { + if (Py_IS_FINITE(x) && Py_IS_FINITE(y)) + errno = ERANGE; + else + errno = 0; + } + if (errno && is_error(r)) + return NULL; + else + return PyFloat_FromDouble(r); } PyDoc_STRVAR(math_hypot_doc, @@ -1491,79 +1491,79 @@ static PyObject * math_pow(PyObject *self, PyObject *args) { - PyObject *ox, *oy; - double r, x, y; - int odd_y; - - if (! PyArg_UnpackTuple(args, "pow", 2, 2, &ox, &oy)) - return NULL; - x = PyFloat_AsDouble(ox); - y = PyFloat_AsDouble(oy); - if ((x == -1.0 || y == -1.0) && PyErr_Occurred()) - return NULL; - - /* deal directly with IEEE specials, to cope with problems on various - platforms whose semantics don't exactly match C99 */ - r = 0.; /* silence compiler warning */ - if (!Py_IS_FINITE(x) || !Py_IS_FINITE(y)) { - errno = 0; - if (Py_IS_NAN(x)) - r = y == 0. ? 1. : x; /* NaN**0 = 1 */ - else if (Py_IS_NAN(y)) - r = x == 1. ? 1. : y; /* 1**NaN = 1 */ - else if (Py_IS_INFINITY(x)) { - odd_y = Py_IS_FINITE(y) && fmod(fabs(y), 2.0) == 1.0; - if (y > 0.) - r = odd_y ? x : fabs(x); - else if (y == 0.) - r = 1.; - else /* y < 0. */ - r = odd_y ? copysign(0., x) : 0.; - } - else if (Py_IS_INFINITY(y)) { - if (fabs(x) == 1.0) - r = 1.; - else if (y > 0. && fabs(x) > 1.0) - r = y; - else if (y < 0. && fabs(x) < 1.0) { - r = -y; /* result is +inf */ - if (x == 0.) /* 0**-inf: divide-by-zero */ - errno = EDOM; - } - else - r = 0.; - } - } - else { - /* let libm handle finite**finite */ - errno = 0; - PyFPE_START_PROTECT("in math_pow", return 0); - r = pow(x, y); - PyFPE_END_PROTECT(r); - /* a NaN result should arise only from (-ve)**(finite - non-integer); in this case we want to raise ValueError. */ - if (!Py_IS_FINITE(r)) { - if (Py_IS_NAN(r)) { - errno = EDOM; - } - /* - an infinite result here arises either from: - (A) (+/-0.)**negative (-> divide-by-zero) - (B) overflow of x**y with x and y finite - */ - else if (Py_IS_INFINITY(r)) { - if (x == 0.) - errno = EDOM; - else - errno = ERANGE; - } - } - } - - if (errno && is_error(r)) - return NULL; - else - return PyFloat_FromDouble(r); + PyObject *ox, *oy; + double r, x, y; + int odd_y; + + if (! PyArg_UnpackTuple(args, "pow", 2, 2, &ox, &oy)) + return NULL; + x = PyFloat_AsDouble(ox); + y = PyFloat_AsDouble(oy); + if ((x == -1.0 || y == -1.0) && PyErr_Occurred()) + return NULL; + + /* deal directly with IEEE specials, to cope with problems on various + platforms whose semantics don't exactly match C99 */ + r = 0.; /* silence compiler warning */ + if (!Py_IS_FINITE(x) || !Py_IS_FINITE(y)) { + errno = 0; + if (Py_IS_NAN(x)) + r = y == 0. ? 1. : x; /* NaN**0 = 1 */ + else if (Py_IS_NAN(y)) + r = x == 1. ? 1. : y; /* 1**NaN = 1 */ + else if (Py_IS_INFINITY(x)) { + odd_y = Py_IS_FINITE(y) && fmod(fabs(y), 2.0) == 1.0; + if (y > 0.) + r = odd_y ? x : fabs(x); + else if (y == 0.) + r = 1.; + else /* y < 0. */ + r = odd_y ? copysign(0., x) : 0.; + } + else if (Py_IS_INFINITY(y)) { + if (fabs(x) == 1.0) + r = 1.; + else if (y > 0. && fabs(x) > 1.0) + r = y; + else if (y < 0. && fabs(x) < 1.0) { + r = -y; /* result is +inf */ + if (x == 0.) /* 0**-inf: divide-by-zero */ + errno = EDOM; + } + else + r = 0.; + } + } + else { + /* let libm handle finite**finite */ + errno = 0; + PyFPE_START_PROTECT("in math_pow", return 0); + r = pow(x, y); + PyFPE_END_PROTECT(r); + /* a NaN result should arise only from (-ve)**(finite + non-integer); in this case we want to raise ValueError. */ + if (!Py_IS_FINITE(r)) { + if (Py_IS_NAN(r)) { + errno = EDOM; + } + /* + an infinite result here arises either from: + (A) (+/-0.)**negative (-> divide-by-zero) + (B) overflow of x**y with x and y finite + */ + else if (Py_IS_INFINITY(r)) { + if (x == 0.) + errno = EDOM; + else + errno = ERANGE; + } + } + } + + if (errno && is_error(r)) + return NULL; + else + return PyFloat_FromDouble(r); } PyDoc_STRVAR(math_pow_doc, @@ -1575,10 +1575,10 @@ static PyObject * math_degrees(PyObject *self, PyObject *arg) { - double x = PyFloat_AsDouble(arg); - if (x == -1.0 && PyErr_Occurred()) - return NULL; - return PyFloat_FromDouble(x * radToDeg); + double x = PyFloat_AsDouble(arg); + if (x == -1.0 && PyErr_Occurred()) + return NULL; + return PyFloat_FromDouble(x * radToDeg); } PyDoc_STRVAR(math_degrees_doc, @@ -1588,10 +1588,10 @@ static PyObject * math_radians(PyObject *self, PyObject *arg) { - double x = PyFloat_AsDouble(arg); - if (x == -1.0 && PyErr_Occurred()) - return NULL; - return PyFloat_FromDouble(x * degToRad); + double x = PyFloat_AsDouble(arg); + if (x == -1.0 && PyErr_Occurred()) + return NULL; + return PyFloat_FromDouble(x * degToRad); } PyDoc_STRVAR(math_radians_doc, @@ -1601,10 +1601,10 @@ static PyObject * math_isnan(PyObject *self, PyObject *arg) { - double x = PyFloat_AsDouble(arg); - if (x == -1.0 && PyErr_Occurred()) - return NULL; - return PyBool_FromLong((long)Py_IS_NAN(x)); + double x = PyFloat_AsDouble(arg); + if (x == -1.0 && PyErr_Occurred()) + return NULL; + return PyBool_FromLong((long)Py_IS_NAN(x)); } PyDoc_STRVAR(math_isnan_doc, @@ -1614,10 +1614,10 @@ static PyObject * math_isinf(PyObject *self, PyObject *arg) { - double x = PyFloat_AsDouble(arg); - if (x == -1.0 && PyErr_Occurred()) - return NULL; - return PyBool_FromLong((long)Py_IS_INFINITY(x)); + double x = PyFloat_AsDouble(arg); + if (x == -1.0 && PyErr_Occurred()) + return NULL; + return PyBool_FromLong((long)Py_IS_INFINITY(x)); } PyDoc_STRVAR(math_isinf_doc, @@ -1625,47 +1625,47 @@ Check if float x is infinite (positive or negative)."); static PyMethodDef math_methods[] = { - {"acos", math_acos, METH_O, math_acos_doc}, - {"acosh", math_acosh, METH_O, math_acosh_doc}, - {"asin", math_asin, METH_O, math_asin_doc}, - {"asinh", math_asinh, METH_O, math_asinh_doc}, - {"atan", math_atan, METH_O, math_atan_doc}, - {"atan2", math_atan2, METH_VARARGS, math_atan2_doc}, - {"atanh", math_atanh, METH_O, math_atanh_doc}, - {"ceil", math_ceil, METH_O, math_ceil_doc}, - {"copysign", math_copysign, METH_VARARGS, math_copysign_doc}, - {"cos", math_cos, METH_O, math_cos_doc}, - {"cosh", math_cosh, METH_O, math_cosh_doc}, - {"degrees", math_degrees, METH_O, math_degrees_doc}, - {"erf", math_erf, METH_O, math_erf_doc}, - {"erfc", math_erfc, METH_O, math_erfc_doc}, - {"exp", math_exp, METH_O, math_exp_doc}, - {"expm1", math_expm1, METH_O, math_expm1_doc}, - {"fabs", math_fabs, METH_O, math_fabs_doc}, - {"factorial", math_factorial, METH_O, math_factorial_doc}, - {"floor", math_floor, METH_O, math_floor_doc}, - {"fmod", math_fmod, METH_VARARGS, math_fmod_doc}, - {"frexp", math_frexp, METH_O, math_frexp_doc}, - {"fsum", math_fsum, METH_O, math_fsum_doc}, - {"gamma", math_gamma, METH_O, math_gamma_doc}, - {"hypot", math_hypot, METH_VARARGS, math_hypot_doc}, - {"isinf", math_isinf, METH_O, math_isinf_doc}, - {"isnan", math_isnan, METH_O, math_isnan_doc}, - {"ldexp", math_ldexp, METH_VARARGS, math_ldexp_doc}, - {"lgamma", math_lgamma, METH_O, math_lgamma_doc}, - {"log", math_log, METH_VARARGS, math_log_doc}, - {"log1p", math_log1p, METH_O, math_log1p_doc}, - {"log10", math_log10, METH_O, math_log10_doc}, - {"modf", math_modf, METH_O, math_modf_doc}, - {"pow", math_pow, METH_VARARGS, math_pow_doc}, - {"radians", math_radians, METH_O, math_radians_doc}, - {"sin", math_sin, METH_O, math_sin_doc}, - {"sinh", math_sinh, METH_O, math_sinh_doc}, - {"sqrt", math_sqrt, METH_O, math_sqrt_doc}, - {"tan", math_tan, METH_O, math_tan_doc}, - {"tanh", math_tanh, METH_O, math_tanh_doc}, - {"trunc", math_trunc, METH_O, math_trunc_doc}, - {NULL, NULL} /* sentinel */ + {"acos", math_acos, METH_O, math_acos_doc}, + {"acosh", math_acosh, METH_O, math_acosh_doc}, + {"asin", math_asin, METH_O, math_asin_doc}, + {"asinh", math_asinh, METH_O, math_asinh_doc}, + {"atan", math_atan, METH_O, math_atan_doc}, + {"atan2", math_atan2, METH_VARARGS, math_atan2_doc}, + {"atanh", math_atanh, METH_O, math_atanh_doc}, + {"ceil", math_ceil, METH_O, math_ceil_doc}, + {"copysign", math_copysign, METH_VARARGS, math_copysign_doc}, + {"cos", math_cos, METH_O, math_cos_doc}, + {"cosh", math_cosh, METH_O, math_cosh_doc}, + {"degrees", math_degrees, METH_O, math_degrees_doc}, + {"erf", math_erf, METH_O, math_erf_doc}, + {"erfc", math_erfc, METH_O, math_erfc_doc}, + {"exp", math_exp, METH_O, math_exp_doc}, + {"expm1", math_expm1, METH_O, math_expm1_doc}, + {"fabs", math_fabs, METH_O, math_fabs_doc}, + {"factorial", math_factorial, METH_O, math_factorial_doc}, + {"floor", math_floor, METH_O, math_floor_doc}, + {"fmod", math_fmod, METH_VARARGS, math_fmod_doc}, + {"frexp", math_frexp, METH_O, math_frexp_doc}, + {"fsum", math_fsum, METH_O, math_fsum_doc}, + {"gamma", math_gamma, METH_O, math_gamma_doc}, + {"hypot", math_hypot, METH_VARARGS, math_hypot_doc}, + {"isinf", math_isinf, METH_O, math_isinf_doc}, + {"isnan", math_isnan, METH_O, math_isnan_doc}, + {"ldexp", math_ldexp, METH_VARARGS, math_ldexp_doc}, + {"lgamma", math_lgamma, METH_O, math_lgamma_doc}, + {"log", math_log, METH_VARARGS, math_log_doc}, + {"log1p", math_log1p, METH_O, math_log1p_doc}, + {"log10", math_log10, METH_O, math_log10_doc}, + {"modf", math_modf, METH_O, math_modf_doc}, + {"pow", math_pow, METH_VARARGS, math_pow_doc}, + {"radians", math_radians, METH_O, math_radians_doc}, + {"sin", math_sin, METH_O, math_sin_doc}, + {"sinh", math_sinh, METH_O, math_sinh_doc}, + {"sqrt", math_sqrt, METH_O, math_sqrt_doc}, + {"tan", math_tan, METH_O, math_tan_doc}, + {"tanh", math_tanh, METH_O, math_tanh_doc}, + {"trunc", math_trunc, METH_O, math_trunc_doc}, + {NULL, NULL} /* sentinel */ }; @@ -1675,29 +1675,29 @@ static struct PyModuleDef mathmodule = { - PyModuleDef_HEAD_INIT, - "math", - module_doc, - -1, - math_methods, - NULL, - NULL, - NULL, - NULL + PyModuleDef_HEAD_INIT, + "math", + module_doc, + -1, + math_methods, + NULL, + NULL, + NULL, + NULL }; PyMODINIT_FUNC PyInit_math(void) { - PyObject *m; + PyObject *m; - m = PyModule_Create(&mathmodule); - if (m == NULL) - goto finally; + m = PyModule_Create(&mathmodule); + if (m == NULL) + goto finally; - PyModule_AddObject(m, "pi", PyFloat_FromDouble(Py_MATH_PI)); - PyModule_AddObject(m, "e", PyFloat_FromDouble(Py_MATH_E)); + PyModule_AddObject(m, "pi", PyFloat_FromDouble(Py_MATH_PI)); + PyModule_AddObject(m, "e", PyFloat_FromDouble(Py_MATH_E)); finally: - return m; + return m; } Modified: python/branches/py3k/Modules/md5module.c ============================================================================== --- python/branches/py3k/Modules/md5module.c (original) +++ python/branches/py3k/Modules/md5module.c Sun May 9 17:52:27 2010 @@ -23,8 +23,8 @@ /* Some useful types */ #if SIZEOF_INT == 4 -typedef unsigned int MD5_INT32; /* 32-bit integer */ -typedef PY_LONG_LONG MD5_INT64; /* 64-bit integer */ +typedef unsigned int MD5_INT32; /* 32-bit integer */ +typedef PY_LONG_LONG MD5_INT64; /* 64-bit integer */ #else /* not defined. compilation will die. */ #endif @@ -127,7 +127,7 @@ for (i = 0; i < 16; i++) { LOAD32L(W[i], buf + (4*i)); } - + /* copy state */ a = md5->state[0]; b = md5->state[1]; @@ -386,21 +386,21 @@ /* Create a new string */ retval = PyUnicode_FromStringAndSize(NULL, MD5_DIGESTSIZE * 2); if (!retval) - return NULL; + return NULL; hex_digest = PyUnicode_AS_UNICODE(retval); if (!hex_digest) { - Py_DECREF(retval); - return NULL; + Py_DECREF(retval); + return NULL; } /* Make hex version of the digest */ for(i=j=0; i> 4) & 0xf; - c = (c>9) ? c+'a'-10 : c + '0'; + c = (c>9) ? c+'a'-10 : c + '0'; hex_digest[j++] = c; c = (digest[i] & 0xf); - c = (c>9) ? c+'a'-10 : c + '0'; + c = (c>9) ? c+'a'-10 : c + '0'; hex_digest[j++] = c; } return retval; @@ -414,7 +414,7 @@ { PyObject *obj; Py_buffer buf; - + if (!PyArg_ParseTuple(args, "O:update", &obj)) return NULL; @@ -428,11 +428,11 @@ } static PyMethodDef MD5_methods[] = { - {"copy", (PyCFunction)MD5_copy, METH_NOARGS, MD5_copy__doc__}, - {"digest", (PyCFunction)MD5_digest, METH_NOARGS, MD5_digest__doc__}, + {"copy", (PyCFunction)MD5_copy, METH_NOARGS, MD5_copy__doc__}, + {"digest", (PyCFunction)MD5_digest, METH_NOARGS, MD5_digest__doc__}, {"hexdigest", (PyCFunction)MD5_hexdigest, METH_NOARGS, MD5_hexdigest__doc__}, - {"update", (PyCFunction)MD5_update, METH_VARARGS, MD5_update__doc__}, - {NULL, NULL} /* sentinel */ + {"update", (PyCFunction)MD5_update, METH_VARARGS, MD5_update__doc__}, + {NULL, NULL} /* sentinel */ }; static PyObject * @@ -472,13 +472,13 @@ static PyTypeObject MD5type = { PyVarObject_HEAD_INIT(NULL, 0) - "_md5.md5", /*tp_name*/ - sizeof(MD5object), /*tp_size*/ - 0, /*tp_itemsize*/ + "_md5.md5", /*tp_name*/ + sizeof(MD5object), /*tp_size*/ + 0, /*tp_itemsize*/ /* methods */ - MD5_dealloc, /*tp_dealloc*/ - 0, /*tp_print*/ - 0, /*tp_getattr*/ + MD5_dealloc, /*tp_dealloc*/ + 0, /*tp_print*/ + 0, /*tp_getattr*/ 0, /*tp_setattr*/ 0, /*tp_reserved*/ 0, /*tp_repr*/ @@ -494,13 +494,13 @@ Py_TPFLAGS_DEFAULT, /*tp_flags*/ 0, /*tp_doc*/ 0, /*tp_traverse*/ - 0, /*tp_clear*/ - 0, /*tp_richcompare*/ - 0, /*tp_weaklistoffset*/ - 0, /*tp_iter*/ - 0, /*tp_iternext*/ - MD5_methods, /* tp_methods */ - NULL, /* tp_members */ + 0, /*tp_clear*/ + 0, /*tp_richcompare*/ + 0, /*tp_weaklistoffset*/ + 0, /*tp_iter*/ + 0, /*tp_iternext*/ + MD5_methods, /* tp_methods */ + NULL, /* tp_members */ MD5_getseters, /* tp_getset */ }; @@ -553,7 +553,7 @@ static struct PyMethodDef MD5_functions[] = { {"md5", (PyCFunction)MD5_new, METH_VARARGS|METH_KEYWORDS, MD5_new__doc__}, - {NULL, NULL} /* Sentinel */ + {NULL, NULL} /* Sentinel */ }; @@ -563,15 +563,15 @@ static struct PyModuleDef _md5module = { - PyModuleDef_HEAD_INIT, - "_md5", - NULL, - -1, - MD5_functions, - NULL, - NULL, - NULL, - NULL + PyModuleDef_HEAD_INIT, + "_md5", + NULL, + -1, + MD5_functions, + NULL, + NULL, + NULL, + NULL }; PyMODINIT_FUNC Modified: python/branches/py3k/Modules/mmapmodule.c ============================================================================== --- python/branches/py3k/Modules/mmapmodule.c (original) +++ python/branches/py3k/Modules/mmapmodule.c Sun May 9 17:52:27 2010 @@ -30,18 +30,18 @@ static int my_getpagesize(void) { - SYSTEM_INFO si; - GetSystemInfo(&si); - return si.dwPageSize; + SYSTEM_INFO si; + GetSystemInfo(&si); + return si.dwPageSize; } static int my_getallocationgranularity (void) { - SYSTEM_INFO si; - GetSystemInfo(&si); - return si.dwAllocationGranularity; + SYSTEM_INFO si; + GetSystemInfo(&si); + return si.dwAllocationGranularity; } #endif @@ -54,7 +54,7 @@ static int my_getpagesize(void) { - return sysconf(_SC_PAGESIZE); + return sysconf(_SC_PAGESIZE); } #define my_getallocationgranularity my_getpagesize @@ -79,31 +79,31 @@ typedef enum { - ACCESS_DEFAULT, - ACCESS_READ, - ACCESS_WRITE, - ACCESS_COPY + ACCESS_DEFAULT, + ACCESS_READ, + ACCESS_WRITE, + ACCESS_COPY } access_mode; typedef struct { - PyObject_HEAD - char * data; - size_t size; - size_t pos; /* relative to offset */ - size_t offset; - int exports; + PyObject_HEAD + char * data; + size_t size; + size_t pos; /* relative to offset */ + size_t offset; + int exports; #ifdef MS_WINDOWS - HANDLE map_handle; - HANDLE file_handle; - char * tagname; + HANDLE map_handle; + HANDLE file_handle; + char * tagname; #endif #ifdef UNIX - int fd; + int fd; #endif - access_mode access; + access_mode access; } mmap_object; @@ -111,331 +111,331 @@ mmap_object_dealloc(mmap_object *m_obj) { #ifdef MS_WINDOWS - if (m_obj->data != NULL) - UnmapViewOfFile (m_obj->data); - if (m_obj->map_handle != NULL) - CloseHandle (m_obj->map_handle); - if (m_obj->file_handle != INVALID_HANDLE_VALUE) - CloseHandle (m_obj->file_handle); - if (m_obj->tagname) - PyMem_Free(m_obj->tagname); + if (m_obj->data != NULL) + UnmapViewOfFile (m_obj->data); + if (m_obj->map_handle != NULL) + CloseHandle (m_obj->map_handle); + if (m_obj->file_handle != INVALID_HANDLE_VALUE) + CloseHandle (m_obj->file_handle); + if (m_obj->tagname) + PyMem_Free(m_obj->tagname); #endif /* MS_WINDOWS */ #ifdef UNIX - if (m_obj->fd >= 0) - (void) close(m_obj->fd); - if (m_obj->data!=NULL) { - msync(m_obj->data, m_obj->size, MS_SYNC); - munmap(m_obj->data, m_obj->size); - } + if (m_obj->fd >= 0) + (void) close(m_obj->fd); + if (m_obj->data!=NULL) { + msync(m_obj->data, m_obj->size, MS_SYNC); + munmap(m_obj->data, m_obj->size); + } #endif /* UNIX */ - Py_TYPE(m_obj)->tp_free((PyObject*)m_obj); + Py_TYPE(m_obj)->tp_free((PyObject*)m_obj); } static PyObject * mmap_close_method(mmap_object *self, PyObject *unused) { - if (self->exports > 0) { - PyErr_SetString(PyExc_BufferError, "cannot close "\ - "exported pointers exist"); - return NULL; - } + if (self->exports > 0) { + PyErr_SetString(PyExc_BufferError, "cannot close "\ + "exported pointers exist"); + return NULL; + } #ifdef MS_WINDOWS - /* For each resource we maintain, we need to check - the value is valid, and if so, free the resource - and set the member value to an invalid value so - the dealloc does not attempt to resource clearing - again. - TODO - should we check for errors in the close operations??? - */ - if (self->data != NULL) { - UnmapViewOfFile(self->data); - self->data = NULL; - } - if (self->map_handle != NULL) { - CloseHandle(self->map_handle); - self->map_handle = NULL; - } - if (self->file_handle != INVALID_HANDLE_VALUE) { - CloseHandle(self->file_handle); - self->file_handle = INVALID_HANDLE_VALUE; - } + /* For each resource we maintain, we need to check + the value is valid, and if so, free the resource + and set the member value to an invalid value so + the dealloc does not attempt to resource clearing + again. + TODO - should we check for errors in the close operations??? + */ + if (self->data != NULL) { + UnmapViewOfFile(self->data); + self->data = NULL; + } + if (self->map_handle != NULL) { + CloseHandle(self->map_handle); + self->map_handle = NULL; + } + if (self->file_handle != INVALID_HANDLE_VALUE) { + CloseHandle(self->file_handle); + self->file_handle = INVALID_HANDLE_VALUE; + } #endif /* MS_WINDOWS */ #ifdef UNIX - if (0 <= self->fd) - (void) close(self->fd); - self->fd = -1; - if (self->data != NULL) { - munmap(self->data, self->size); - self->data = NULL; - } + if (0 <= self->fd) + (void) close(self->fd); + self->fd = -1; + if (self->data != NULL) { + munmap(self->data, self->size); + self->data = NULL; + } #endif - Py_INCREF(Py_None); - return Py_None; + Py_INCREF(Py_None); + return Py_None; } #ifdef MS_WINDOWS -#define CHECK_VALID(err) \ -do { \ - if (self->map_handle == NULL) { \ - PyErr_SetString(PyExc_ValueError, "mmap closed or invalid"); \ - return err; \ - } \ +#define CHECK_VALID(err) \ +do { \ + if (self->map_handle == NULL) { \ + PyErr_SetString(PyExc_ValueError, "mmap closed or invalid"); \ + return err; \ + } \ } while (0) #endif /* MS_WINDOWS */ #ifdef UNIX -#define CHECK_VALID(err) \ -do { \ - if (self->data == NULL) { \ - PyErr_SetString(PyExc_ValueError, "mmap closed or invalid"); \ - return err; \ - } \ +#define CHECK_VALID(err) \ +do { \ + if (self->data == NULL) { \ + PyErr_SetString(PyExc_ValueError, "mmap closed or invalid"); \ + return err; \ + } \ } while (0) #endif /* UNIX */ static PyObject * mmap_read_byte_method(mmap_object *self, - PyObject *unused) + PyObject *unused) { - CHECK_VALID(NULL); - if (self->pos < self->size) { - char value = self->data[self->pos]; - self->pos += 1; - return Py_BuildValue("b", value); - } else { - PyErr_SetString(PyExc_ValueError, "read byte out of range"); - return NULL; - } + CHECK_VALID(NULL); + if (self->pos < self->size) { + char value = self->data[self->pos]; + self->pos += 1; + return Py_BuildValue("b", value); + } else { + PyErr_SetString(PyExc_ValueError, "read byte out of range"); + return NULL; + } } static PyObject * mmap_read_line_method(mmap_object *self, - PyObject *unused) + PyObject *unused) { - char *start = self->data+self->pos; - char *eof = self->data+self->size; - char *eol; - PyObject *result; - - CHECK_VALID(NULL); - - eol = memchr(start, '\n', self->size - self->pos); - if (!eol) - eol = eof; - else - ++eol; /* we're interested in the position after the - newline. */ - result = PyBytes_FromStringAndSize(start, (eol - start)); - self->pos += (eol - start); - return result; + char *start = self->data+self->pos; + char *eof = self->data+self->size; + char *eol; + PyObject *result; + + CHECK_VALID(NULL); + + eol = memchr(start, '\n', self->size - self->pos); + if (!eol) + eol = eof; + else + ++eol; /* we're interested in the position after the + newline. */ + result = PyBytes_FromStringAndSize(start, (eol - start)); + self->pos += (eol - start); + return result; } static PyObject * mmap_read_method(mmap_object *self, - PyObject *args) + PyObject *args) { - Py_ssize_t num_bytes, n; - PyObject *result; + Py_ssize_t num_bytes, n; + PyObject *result; - CHECK_VALID(NULL); - if (!PyArg_ParseTuple(args, "n:read", &num_bytes)) - return(NULL); - - /* silently 'adjust' out-of-range requests */ - assert(self->size >= self->pos); - n = self->size - self->pos; - /* The difference can overflow, only if self->size is greater than - * PY_SSIZE_T_MAX. But then the operation cannot possibly succeed, - * because the mapped area and the returned string each need more - * than half of the addressable memory. So we clip the size, and let - * the code below raise MemoryError. - */ - if (n < 0) - n = PY_SSIZE_T_MAX; - if (num_bytes < 0 || num_bytes > n) { - num_bytes = n; - } - result = PyBytes_FromStringAndSize(self->data+self->pos, num_bytes); - self->pos += num_bytes; - return result; + CHECK_VALID(NULL); + if (!PyArg_ParseTuple(args, "n:read", &num_bytes)) + return(NULL); + + /* silently 'adjust' out-of-range requests */ + assert(self->size >= self->pos); + n = self->size - self->pos; + /* The difference can overflow, only if self->size is greater than + * PY_SSIZE_T_MAX. But then the operation cannot possibly succeed, + * because the mapped area and the returned string each need more + * than half of the addressable memory. So we clip the size, and let + * the code below raise MemoryError. + */ + if (n < 0) + n = PY_SSIZE_T_MAX; + if (num_bytes < 0 || num_bytes > n) { + num_bytes = n; + } + result = PyBytes_FromStringAndSize(self->data+self->pos, num_bytes); + self->pos += num_bytes; + return result; } static PyObject * mmap_gfind(mmap_object *self, - PyObject *args, - int reverse) + PyObject *args, + int reverse) { - Py_ssize_t start = self->pos; - Py_ssize_t end = self->size; - const char *needle; - Py_ssize_t len; - - CHECK_VALID(NULL); - if (!PyArg_ParseTuple(args, reverse ? "y#|nn:rfind" : "y#|nn:find", - &needle, &len, &start, &end)) { - return NULL; - } else { - const char *p, *start_p, *end_p; - int sign = reverse ? -1 : 1; - - if (start < 0) - start += self->size; - if (start < 0) - start = 0; - else if ((size_t)start > self->size) - start = self->size; - - if (end < 0) - end += self->size; - if (end < 0) - end = 0; - else if ((size_t)end > self->size) - end = self->size; - - start_p = self->data + start; - end_p = self->data + end; - - for (p = (reverse ? end_p - len : start_p); - (p >= start_p) && (p + len <= end_p); p += sign) { - Py_ssize_t i; - for (i = 0; i < len && needle[i] == p[i]; ++i) - /* nothing */; - if (i == len) { - return PyLong_FromSsize_t(p - self->data); - } - } - return PyLong_FromLong(-1); - } + Py_ssize_t start = self->pos; + Py_ssize_t end = self->size; + const char *needle; + Py_ssize_t len; + + CHECK_VALID(NULL); + if (!PyArg_ParseTuple(args, reverse ? "y#|nn:rfind" : "y#|nn:find", + &needle, &len, &start, &end)) { + return NULL; + } else { + const char *p, *start_p, *end_p; + int sign = reverse ? -1 : 1; + + if (start < 0) + start += self->size; + if (start < 0) + start = 0; + else if ((size_t)start > self->size) + start = self->size; + + if (end < 0) + end += self->size; + if (end < 0) + end = 0; + else if ((size_t)end > self->size) + end = self->size; + + start_p = self->data + start; + end_p = self->data + end; + + for (p = (reverse ? end_p - len : start_p); + (p >= start_p) && (p + len <= end_p); p += sign) { + Py_ssize_t i; + for (i = 0; i < len && needle[i] == p[i]; ++i) + /* nothing */; + if (i == len) { + return PyLong_FromSsize_t(p - self->data); + } + } + return PyLong_FromLong(-1); + } } static PyObject * mmap_find_method(mmap_object *self, - PyObject *args) + PyObject *args) { - return mmap_gfind(self, args, 0); + return mmap_gfind(self, args, 0); } static PyObject * mmap_rfind_method(mmap_object *self, - PyObject *args) + PyObject *args) { - return mmap_gfind(self, args, 1); + return mmap_gfind(self, args, 1); } static int is_writable(mmap_object *self) { - if (self->access != ACCESS_READ) - return 1; - PyErr_Format(PyExc_TypeError, "mmap can't modify a readonly memory map."); - return 0; + if (self->access != ACCESS_READ) + return 1; + PyErr_Format(PyExc_TypeError, "mmap can't modify a readonly memory map."); + return 0; } static int is_resizeable(mmap_object *self) { - if (self->exports > 0) { - PyErr_SetString(PyExc_BufferError, - "mmap can't resize with extant buffers exported."); - return 0; - } - if ((self->access == ACCESS_WRITE) || (self->access == ACCESS_DEFAULT)) - return 1; - PyErr_Format(PyExc_TypeError, - "mmap can't resize a readonly or copy-on-write memory map."); - return 0; + if (self->exports > 0) { + PyErr_SetString(PyExc_BufferError, + "mmap can't resize with extant buffers exported."); + return 0; + } + if ((self->access == ACCESS_WRITE) || (self->access == ACCESS_DEFAULT)) + return 1; + PyErr_Format(PyExc_TypeError, + "mmap can't resize a readonly or copy-on-write memory map."); + return 0; } static PyObject * mmap_write_method(mmap_object *self, - PyObject *args) + PyObject *args) { - Py_ssize_t length; - char *data; + Py_ssize_t length; + char *data; - CHECK_VALID(NULL); - if (!PyArg_ParseTuple(args, "y#:write", &data, &length)) - return(NULL); - - if (!is_writable(self)) - return NULL; - - if ((self->pos + length) > self->size) { - PyErr_SetString(PyExc_ValueError, "data out of range"); - return NULL; - } - memcpy(self->data+self->pos, data, length); - self->pos = self->pos+length; - Py_INCREF(Py_None); - return Py_None; + CHECK_VALID(NULL); + if (!PyArg_ParseTuple(args, "y#:write", &data, &length)) + return(NULL); + + if (!is_writable(self)) + return NULL; + + if ((self->pos + length) > self->size) { + PyErr_SetString(PyExc_ValueError, "data out of range"); + return NULL; + } + memcpy(self->data+self->pos, data, length); + self->pos = self->pos+length; + Py_INCREF(Py_None); + return Py_None; } static PyObject * mmap_write_byte_method(mmap_object *self, - PyObject *args) + PyObject *args) { - char value; + char value; - CHECK_VALID(NULL); - if (!PyArg_ParseTuple(args, "b:write_byte", &value)) - return(NULL); - - if (!is_writable(self)) - return NULL; - - if (self->pos < self->size) { - *(self->data+self->pos) = value; - self->pos += 1; - Py_INCREF(Py_None); - return Py_None; - } - else { - PyErr_SetString(PyExc_ValueError, "write byte out of range"); - return NULL; - } + CHECK_VALID(NULL); + if (!PyArg_ParseTuple(args, "b:write_byte", &value)) + return(NULL); + + if (!is_writable(self)) + return NULL; + + if (self->pos < self->size) { + *(self->data+self->pos) = value; + self->pos += 1; + Py_INCREF(Py_None); + return Py_None; + } + else { + PyErr_SetString(PyExc_ValueError, "write byte out of range"); + return NULL; + } } static PyObject * mmap_size_method(mmap_object *self, - PyObject *unused) + PyObject *unused) { - CHECK_VALID(NULL); + CHECK_VALID(NULL); #ifdef MS_WINDOWS - if (self->file_handle != INVALID_HANDLE_VALUE) { - DWORD low,high; - PY_LONG_LONG size; - low = GetFileSize(self->file_handle, &high); - if (low == INVALID_FILE_SIZE) { - /* It might be that the function appears to have failed, - when indeed its size equals INVALID_FILE_SIZE */ - DWORD error = GetLastError(); - if (error != NO_ERROR) - return PyErr_SetFromWindowsErr(error); - } - if (!high && low < LONG_MAX) - return PyLong_FromLong((long)low); - size = (((PY_LONG_LONG)high)<<32) + low; - return PyLong_FromLongLong(size); - } else { - return PyLong_FromSsize_t(self->size); - } + if (self->file_handle != INVALID_HANDLE_VALUE) { + DWORD low,high; + PY_LONG_LONG size; + low = GetFileSize(self->file_handle, &high); + if (low == INVALID_FILE_SIZE) { + /* It might be that the function appears to have failed, + when indeed its size equals INVALID_FILE_SIZE */ + DWORD error = GetLastError(); + if (error != NO_ERROR) + return PyErr_SetFromWindowsErr(error); + } + if (!high && low < LONG_MAX) + return PyLong_FromLong((long)low); + size = (((PY_LONG_LONG)high)<<32) + low; + return PyLong_FromLongLong(size); + } else { + return PyLong_FromSsize_t(self->size); + } #endif /* MS_WINDOWS */ #ifdef UNIX - { - struct stat buf; - if (-1 == fstat(self->fd, &buf)) { - PyErr_SetFromErrno(mmap_module_error); - return NULL; - } - return PyLong_FromSsize_t(buf.st_size); - } + { + struct stat buf; + if (-1 == fstat(self->fd, &buf)) { + PyErr_SetFromErrno(mmap_module_error); + return NULL; + } + return PyLong_FromSsize_t(buf.st_size); + } #endif /* UNIX */ } @@ -450,223 +450,223 @@ static PyObject * mmap_resize_method(mmap_object *self, - PyObject *args) + PyObject *args) { - Py_ssize_t new_size; - CHECK_VALID(NULL); - if (!PyArg_ParseTuple(args, "n:resize", &new_size) || - !is_resizeable(self)) { - return NULL; + Py_ssize_t new_size; + CHECK_VALID(NULL); + if (!PyArg_ParseTuple(args, "n:resize", &new_size) || + !is_resizeable(self)) { + return NULL; #ifdef MS_WINDOWS - } else { - DWORD dwErrCode = 0; - DWORD off_hi, off_lo, newSizeLow, newSizeHigh; - /* First, unmap the file view */ - UnmapViewOfFile(self->data); - self->data = NULL; - /* Close the mapping object */ - CloseHandle(self->map_handle); - self->map_handle = NULL; - /* Move to the desired EOF position */ + } else { + DWORD dwErrCode = 0; + DWORD off_hi, off_lo, newSizeLow, newSizeHigh; + /* First, unmap the file view */ + UnmapViewOfFile(self->data); + self->data = NULL; + /* Close the mapping object */ + CloseHandle(self->map_handle); + self->map_handle = NULL; + /* Move to the desired EOF position */ #if SIZEOF_SIZE_T > 4 - newSizeHigh = (DWORD)((self->offset + new_size) >> 32); - newSizeLow = (DWORD)((self->offset + new_size) & 0xFFFFFFFF); - off_hi = (DWORD)(self->offset >> 32); - off_lo = (DWORD)(self->offset & 0xFFFFFFFF); + newSizeHigh = (DWORD)((self->offset + new_size) >> 32); + newSizeLow = (DWORD)((self->offset + new_size) & 0xFFFFFFFF); + off_hi = (DWORD)(self->offset >> 32); + off_lo = (DWORD)(self->offset & 0xFFFFFFFF); #else - newSizeHigh = 0; - newSizeLow = (DWORD)(self->offset + new_size); - off_hi = 0; - off_lo = (DWORD)self->offset; -#endif - SetFilePointer(self->file_handle, - newSizeLow, &newSizeHigh, FILE_BEGIN); - /* Change the size of the file */ - SetEndOfFile(self->file_handle); - /* Create another mapping object and remap the file view */ - self->map_handle = CreateFileMapping( - self->file_handle, - NULL, - PAGE_READWRITE, - 0, - 0, - self->tagname); - if (self->map_handle != NULL) { - self->data = (char *) MapViewOfFile(self->map_handle, - FILE_MAP_WRITE, - off_hi, - off_lo, - new_size); - if (self->data != NULL) { - self->size = new_size; - Py_INCREF(Py_None); - return Py_None; - } else { - dwErrCode = GetLastError(); - CloseHandle(self->map_handle); - self->map_handle = NULL; - } - } else { - dwErrCode = GetLastError(); - } - PyErr_SetFromWindowsErr(dwErrCode); - return NULL; + newSizeHigh = 0; + newSizeLow = (DWORD)(self->offset + new_size); + off_hi = 0; + off_lo = (DWORD)self->offset; +#endif + SetFilePointer(self->file_handle, + newSizeLow, &newSizeHigh, FILE_BEGIN); + /* Change the size of the file */ + SetEndOfFile(self->file_handle); + /* Create another mapping object and remap the file view */ + self->map_handle = CreateFileMapping( + self->file_handle, + NULL, + PAGE_READWRITE, + 0, + 0, + self->tagname); + if (self->map_handle != NULL) { + self->data = (char *) MapViewOfFile(self->map_handle, + FILE_MAP_WRITE, + off_hi, + off_lo, + new_size); + if (self->data != NULL) { + self->size = new_size; + Py_INCREF(Py_None); + return Py_None; + } else { + dwErrCode = GetLastError(); + CloseHandle(self->map_handle); + self->map_handle = NULL; + } + } else { + dwErrCode = GetLastError(); + } + PyErr_SetFromWindowsErr(dwErrCode); + return NULL; #endif /* MS_WINDOWS */ #ifdef UNIX #ifndef HAVE_MREMAP - } else { - PyErr_SetString(PyExc_SystemError, - "mmap: resizing not available--no mremap()"); - return NULL; + } else { + PyErr_SetString(PyExc_SystemError, + "mmap: resizing not available--no mremap()"); + return NULL; #else - } else { - void *newmap; + } else { + void *newmap; - if (ftruncate(self->fd, self->offset + new_size) == -1) { - PyErr_SetFromErrno(mmap_module_error); - return NULL; - } + if (ftruncate(self->fd, self->offset + new_size) == -1) { + PyErr_SetFromErrno(mmap_module_error); + return NULL; + } #ifdef MREMAP_MAYMOVE - newmap = mremap(self->data, self->size, new_size, MREMAP_MAYMOVE); + newmap = mremap(self->data, self->size, new_size, MREMAP_MAYMOVE); #else - #if defined(__NetBSD__) - newmap = mremap(self->data, self->size, self->data, new_size, 0); - #else - newmap = mremap(self->data, self->size, new_size, 0); - #endif /* __NetBSD__ */ -#endif - if (newmap == (void *)-1) - { - PyErr_SetFromErrno(mmap_module_error); - return NULL; - } - self->data = newmap; - self->size = new_size; - Py_INCREF(Py_None); - return Py_None; + #if defined(__NetBSD__) + newmap = mremap(self->data, self->size, self->data, new_size, 0); + #else + newmap = mremap(self->data, self->size, new_size, 0); + #endif /* __NetBSD__ */ +#endif + if (newmap == (void *)-1) + { + PyErr_SetFromErrno(mmap_module_error); + return NULL; + } + self->data = newmap; + self->size = new_size; + Py_INCREF(Py_None); + return Py_None; #endif /* HAVE_MREMAP */ #endif /* UNIX */ - } + } } static PyObject * mmap_tell_method(mmap_object *self, PyObject *unused) { - CHECK_VALID(NULL); - return PyLong_FromSize_t(self->pos); + CHECK_VALID(NULL); + return PyLong_FromSize_t(self->pos); } static PyObject * mmap_flush_method(mmap_object *self, PyObject *args) { - Py_ssize_t offset = 0; - Py_ssize_t size = self->size; - CHECK_VALID(NULL); - if (!PyArg_ParseTuple(args, "|nn:flush", &offset, &size)) - return NULL; - if ((size_t)(offset + size) > self->size) { - PyErr_SetString(PyExc_ValueError, "flush values out of range"); - return NULL; - } + Py_ssize_t offset = 0; + Py_ssize_t size = self->size; + CHECK_VALID(NULL); + if (!PyArg_ParseTuple(args, "|nn:flush", &offset, &size)) + return NULL; + if ((size_t)(offset + size) > self->size) { + PyErr_SetString(PyExc_ValueError, "flush values out of range"); + return NULL; + } #ifdef MS_WINDOWS - return PyLong_FromLong((long) FlushViewOfFile(self->data+offset, size)); + return PyLong_FromLong((long) FlushViewOfFile(self->data+offset, size)); #elif defined(UNIX) - /* XXX semantics of return value? */ - /* XXX flags for msync? */ - if (-1 == msync(self->data + offset, size, MS_SYNC)) { - PyErr_SetFromErrno(mmap_module_error); - return NULL; - } - return PyLong_FromLong(0); + /* XXX semantics of return value? */ + /* XXX flags for msync? */ + if (-1 == msync(self->data + offset, size, MS_SYNC)) { + PyErr_SetFromErrno(mmap_module_error); + return NULL; + } + return PyLong_FromLong(0); #else - PyErr_SetString(PyExc_ValueError, "flush not supported on this system"); - return NULL; + PyErr_SetString(PyExc_ValueError, "flush not supported on this system"); + return NULL; #endif } static PyObject * mmap_seek_method(mmap_object *self, PyObject *args) { - Py_ssize_t dist; - int how=0; - CHECK_VALID(NULL); - if (!PyArg_ParseTuple(args, "n|i:seek", &dist, &how)) - return NULL; - else { - size_t where; - switch (how) { - case 0: /* relative to start */ - if (dist < 0) - goto onoutofrange; - where = dist; - break; - case 1: /* relative to current position */ - if ((Py_ssize_t)self->pos + dist < 0) - goto onoutofrange; - where = self->pos + dist; - break; - case 2: /* relative to end */ - if ((Py_ssize_t)self->size + dist < 0) - goto onoutofrange; - where = self->size + dist; - break; - default: - PyErr_SetString(PyExc_ValueError, "unknown seek type"); - return NULL; - } - if (where > self->size) - goto onoutofrange; - self->pos = where; - Py_INCREF(Py_None); - return Py_None; - } + Py_ssize_t dist; + int how=0; + CHECK_VALID(NULL); + if (!PyArg_ParseTuple(args, "n|i:seek", &dist, &how)) + return NULL; + else { + size_t where; + switch (how) { + case 0: /* relative to start */ + if (dist < 0) + goto onoutofrange; + where = dist; + break; + case 1: /* relative to current position */ + if ((Py_ssize_t)self->pos + dist < 0) + goto onoutofrange; + where = self->pos + dist; + break; + case 2: /* relative to end */ + if ((Py_ssize_t)self->size + dist < 0) + goto onoutofrange; + where = self->size + dist; + break; + default: + PyErr_SetString(PyExc_ValueError, "unknown seek type"); + return NULL; + } + if (where > self->size) + goto onoutofrange; + self->pos = where; + Py_INCREF(Py_None); + return Py_None; + } onoutofrange: - PyErr_SetString(PyExc_ValueError, "seek out of range"); - return NULL; + PyErr_SetString(PyExc_ValueError, "seek out of range"); + return NULL; } static PyObject * mmap_move_method(mmap_object *self, PyObject *args) { - unsigned long dest, src, cnt; - CHECK_VALID(NULL); - if (!PyArg_ParseTuple(args, "kkk:move", &dest, &src, &cnt) || - !is_writable(self)) { - return NULL; - } else { - /* bounds check the values */ - if (cnt < 0 || (cnt + dest) < cnt || (cnt + src) < cnt || - src < 0 || src > self->size || (src + cnt) > self->size || - dest < 0 || dest > self->size || (dest + cnt) > self->size) { - PyErr_SetString(PyExc_ValueError, - "source, destination, or count out of range"); - return NULL; - } - memmove(self->data+dest, self->data+src, cnt); - Py_INCREF(Py_None); - return Py_None; - } + unsigned long dest, src, cnt; + CHECK_VALID(NULL); + if (!PyArg_ParseTuple(args, "kkk:move", &dest, &src, &cnt) || + !is_writable(self)) { + return NULL; + } else { + /* bounds check the values */ + if (cnt < 0 || (cnt + dest) < cnt || (cnt + src) < cnt || + src < 0 || src > self->size || (src + cnt) > self->size || + dest < 0 || dest > self->size || (dest + cnt) > self->size) { + PyErr_SetString(PyExc_ValueError, + "source, destination, or count out of range"); + return NULL; + } + memmove(self->data+dest, self->data+src, cnt); + Py_INCREF(Py_None); + return Py_None; + } } static struct PyMethodDef mmap_object_methods[] = { - {"close", (PyCFunction) mmap_close_method, METH_NOARGS}, - {"find", (PyCFunction) mmap_find_method, METH_VARARGS}, - {"rfind", (PyCFunction) mmap_rfind_method, METH_VARARGS}, - {"flush", (PyCFunction) mmap_flush_method, METH_VARARGS}, - {"move", (PyCFunction) mmap_move_method, METH_VARARGS}, - {"read", (PyCFunction) mmap_read_method, METH_VARARGS}, - {"read_byte", (PyCFunction) mmap_read_byte_method, METH_NOARGS}, - {"readline", (PyCFunction) mmap_read_line_method, METH_NOARGS}, - {"resize", (PyCFunction) mmap_resize_method, METH_VARARGS}, - {"seek", (PyCFunction) mmap_seek_method, METH_VARARGS}, - {"size", (PyCFunction) mmap_size_method, METH_NOARGS}, - {"tell", (PyCFunction) mmap_tell_method, METH_NOARGS}, - {"write", (PyCFunction) mmap_write_method, METH_VARARGS}, - {"write_byte", (PyCFunction) mmap_write_byte_method, METH_VARARGS}, - {NULL, NULL} /* sentinel */ + {"close", (PyCFunction) mmap_close_method, METH_NOARGS}, + {"find", (PyCFunction) mmap_find_method, METH_VARARGS}, + {"rfind", (PyCFunction) mmap_rfind_method, METH_VARARGS}, + {"flush", (PyCFunction) mmap_flush_method, METH_VARARGS}, + {"move", (PyCFunction) mmap_move_method, METH_VARARGS}, + {"read", (PyCFunction) mmap_read_method, METH_VARARGS}, + {"read_byte", (PyCFunction) mmap_read_byte_method, METH_NOARGS}, + {"readline", (PyCFunction) mmap_read_line_method, METH_NOARGS}, + {"resize", (PyCFunction) mmap_resize_method, METH_VARARGS}, + {"seek", (PyCFunction) mmap_seek_method, METH_VARARGS}, + {"size", (PyCFunction) mmap_size_method, METH_NOARGS}, + {"tell", (PyCFunction) mmap_tell_method, METH_NOARGS}, + {"write", (PyCFunction) mmap_write_method, METH_VARARGS}, + {"write_byte", (PyCFunction) mmap_write_byte_method, METH_VARARGS}, + {NULL, NULL} /* sentinel */ }; /* Functions for treating an mmap'ed file as a buffer */ @@ -674,247 +674,247 @@ static int mmap_buffer_getbuf(mmap_object *self, Py_buffer *view, int flags) { - CHECK_VALID(-1); - if (PyBuffer_FillInfo(view, (PyObject*)self, self->data, self->size, - (self->access == ACCESS_READ), flags) < 0) - return -1; - self->exports++; - return 0; + CHECK_VALID(-1); + if (PyBuffer_FillInfo(view, (PyObject*)self, self->data, self->size, + (self->access == ACCESS_READ), flags) < 0) + return -1; + self->exports++; + return 0; } static void mmap_buffer_releasebuf(mmap_object *self, Py_buffer *view) { - self->exports--; + self->exports--; } static Py_ssize_t mmap_length(mmap_object *self) { - CHECK_VALID(-1); - return self->size; + CHECK_VALID(-1); + return self->size; } static PyObject * mmap_item(mmap_object *self, Py_ssize_t i) { - CHECK_VALID(NULL); - if (i < 0 || (size_t)i >= self->size) { - PyErr_SetString(PyExc_IndexError, "mmap index out of range"); - return NULL; - } - return PyBytes_FromStringAndSize(self->data + i, 1); + CHECK_VALID(NULL); + if (i < 0 || (size_t)i >= self->size) { + PyErr_SetString(PyExc_IndexError, "mmap index out of range"); + return NULL; + } + return PyBytes_FromStringAndSize(self->data + i, 1); } static PyObject * mmap_subscript(mmap_object *self, PyObject *item) { - CHECK_VALID(NULL); - 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 += self->size; - if (i < 0 || (size_t)i >= self->size) { - PyErr_SetString(PyExc_IndexError, - "mmap index out of range"); - return NULL; - } - return PyLong_FromLong(Py_CHARMASK(self->data[i])); - } - else if (PySlice_Check(item)) { - Py_ssize_t start, stop, step, slicelen; - - if (PySlice_GetIndicesEx((PySliceObject *)item, self->size, - &start, &stop, &step, &slicelen) < 0) { - return NULL; - } - - if (slicelen <= 0) - return PyBytes_FromStringAndSize("", 0); - else if (step == 1) - return PyBytes_FromStringAndSize(self->data + start, - slicelen); - else { - char *result_buf = (char *)PyMem_Malloc(slicelen); - Py_ssize_t cur, i; - PyObject *result; - - if (result_buf == NULL) - return PyErr_NoMemory(); - for (cur = start, i = 0; i < slicelen; - cur += step, i++) { - result_buf[i] = self->data[cur]; - } - result = PyBytes_FromStringAndSize(result_buf, - slicelen); - PyMem_Free(result_buf); - return result; - } - } - else { - PyErr_SetString(PyExc_TypeError, - "mmap indices must be integers"); - return NULL; - } + CHECK_VALID(NULL); + 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 += self->size; + if (i < 0 || (size_t)i >= self->size) { + PyErr_SetString(PyExc_IndexError, + "mmap index out of range"); + return NULL; + } + return PyLong_FromLong(Py_CHARMASK(self->data[i])); + } + else if (PySlice_Check(item)) { + Py_ssize_t start, stop, step, slicelen; + + if (PySlice_GetIndicesEx((PySliceObject *)item, self->size, + &start, &stop, &step, &slicelen) < 0) { + return NULL; + } + + if (slicelen <= 0) + return PyBytes_FromStringAndSize("", 0); + else if (step == 1) + return PyBytes_FromStringAndSize(self->data + start, + slicelen); + else { + char *result_buf = (char *)PyMem_Malloc(slicelen); + Py_ssize_t cur, i; + PyObject *result; + + if (result_buf == NULL) + return PyErr_NoMemory(); + for (cur = start, i = 0; i < slicelen; + cur += step, i++) { + result_buf[i] = self->data[cur]; + } + result = PyBytes_FromStringAndSize(result_buf, + slicelen); + PyMem_Free(result_buf); + return result; + } + } + else { + PyErr_SetString(PyExc_TypeError, + "mmap indices must be integers"); + return NULL; + } } static PyObject * mmap_concat(mmap_object *self, PyObject *bb) { - CHECK_VALID(NULL); - PyErr_SetString(PyExc_SystemError, - "mmaps don't support concatenation"); - return NULL; + 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; + CHECK_VALID(NULL); + PyErr_SetString(PyExc_SystemError, + "mmaps don't support repeat operation"); + return NULL; } static int mmap_ass_item(mmap_object *self, Py_ssize_t i, PyObject *v) { - const char *buf; + const char *buf; - CHECK_VALID(-1); - if (i < 0 || (size_t)i >= self->size) { - PyErr_SetString(PyExc_IndexError, "mmap index out of range"); - return -1; - } - if (v == NULL) { - PyErr_SetString(PyExc_TypeError, - "mmap object doesn't support item deletion"); - return -1; - } - if (! (PyBytes_Check(v) && PyBytes_Size(v)==1) ) { - PyErr_SetString(PyExc_IndexError, - "mmap assignment must be length-1 bytes()"); - return -1; - } - if (!is_writable(self)) - return -1; - buf = PyBytes_AsString(v); - self->data[i] = buf[0]; - return 0; + CHECK_VALID(-1); + if (i < 0 || (size_t)i >= self->size) { + PyErr_SetString(PyExc_IndexError, "mmap index out of range"); + return -1; + } + if (v == NULL) { + PyErr_SetString(PyExc_TypeError, + "mmap object doesn't support item deletion"); + return -1; + } + if (! (PyBytes_Check(v) && PyBytes_Size(v)==1) ) { + PyErr_SetString(PyExc_IndexError, + "mmap assignment must be length-1 bytes()"); + return -1; + } + if (!is_writable(self)) + return -1; + buf = PyBytes_AsString(v); + self->data[i] = buf[0]; + return 0; } static int mmap_ass_subscript(mmap_object *self, PyObject *item, PyObject *value) { - CHECK_VALID(-1); + CHECK_VALID(-1); + + if (!is_writable(self)) + return -1; + + if (PyIndex_Check(item)) { + Py_ssize_t i = PyNumber_AsSsize_t(item, PyExc_IndexError); + Py_ssize_t v; + + if (i == -1 && PyErr_Occurred()) + return -1; + if (i < 0) + i += self->size; + if (i < 0 || (size_t)i >= self->size) { + PyErr_SetString(PyExc_IndexError, + "mmap index out of range"); + return -1; + } + if (value == NULL) { + PyErr_SetString(PyExc_TypeError, + "mmap doesn't support item deletion"); + return -1; + } + if (!PyIndex_Check(value)) { + PyErr_SetString(PyExc_TypeError, + "mmap item value must be an int"); + return -1; + } + v = PyNumber_AsSsize_t(value, PyExc_TypeError); + if (v == -1 && PyErr_Occurred()) + return -1; + if (v < 0 || v > 255) { + PyErr_SetString(PyExc_ValueError, + "mmap item value must be " + "in range(0, 256)"); + return -1; + } + self->data[i] = v; + return 0; + } + else if (PySlice_Check(item)) { + Py_ssize_t start, stop, step, slicelen; + Py_buffer vbuf; + + if (PySlice_GetIndicesEx((PySliceObject *)item, + self->size, &start, &stop, + &step, &slicelen) < 0) { + return -1; + } + if (value == NULL) { + PyErr_SetString(PyExc_TypeError, + "mmap object doesn't support slice deletion"); + return -1; + } + if (PyObject_GetBuffer(value, &vbuf, PyBUF_SIMPLE) < 0) + return -1; + if (vbuf.len != slicelen) { + PyErr_SetString(PyExc_IndexError, + "mmap slice assignment is wrong size"); + PyBuffer_Release(&vbuf); + return -1; + } - if (!is_writable(self)) - return -1; + if (slicelen == 0) { + } + else if (step == 1) { + memcpy(self->data + start, vbuf.buf, slicelen); + } + else { + Py_ssize_t cur, i; - if (PyIndex_Check(item)) { - Py_ssize_t i = PyNumber_AsSsize_t(item, PyExc_IndexError); - Py_ssize_t v; - - if (i == -1 && PyErr_Occurred()) - return -1; - if (i < 0) - i += self->size; - if (i < 0 || (size_t)i >= self->size) { - PyErr_SetString(PyExc_IndexError, - "mmap index out of range"); - return -1; - } - if (value == NULL) { - PyErr_SetString(PyExc_TypeError, - "mmap doesn't support item deletion"); - return -1; - } - if (!PyIndex_Check(value)) { - PyErr_SetString(PyExc_TypeError, - "mmap item value must be an int"); - return -1; - } - v = PyNumber_AsSsize_t(value, PyExc_TypeError); - if (v == -1 && PyErr_Occurred()) - return -1; - if (v < 0 || v > 255) { - PyErr_SetString(PyExc_ValueError, - "mmap item value must be " - "in range(0, 256)"); - return -1; - } - self->data[i] = v; - return 0; - } - else if (PySlice_Check(item)) { - Py_ssize_t start, stop, step, slicelen; - Py_buffer vbuf; - - if (PySlice_GetIndicesEx((PySliceObject *)item, - self->size, &start, &stop, - &step, &slicelen) < 0) { - return -1; - } - if (value == NULL) { - PyErr_SetString(PyExc_TypeError, - "mmap object doesn't support slice deletion"); - return -1; - } - if (PyObject_GetBuffer(value, &vbuf, PyBUF_SIMPLE) < 0) - return -1; - if (vbuf.len != slicelen) { - PyErr_SetString(PyExc_IndexError, - "mmap slice assignment is wrong size"); - PyBuffer_Release(&vbuf); - return -1; - } - - if (slicelen == 0) { - } - else if (step == 1) { - memcpy(self->data + start, vbuf.buf, slicelen); - } - else { - Py_ssize_t cur, i; - - for (cur = start, i = 0; - i < slicelen; - cur += step, i++) - { - self->data[cur] = ((char *)vbuf.buf)[i]; - } - } - PyBuffer_Release(&vbuf); - return 0; - } - else { - PyErr_SetString(PyExc_TypeError, - "mmap indices must be integer"); - return -1; - } + for (cur = start, i = 0; + i < slicelen; + cur += step, i++) + { + self->data[cur] = ((char *)vbuf.buf)[i]; + } + } + PyBuffer_Release(&vbuf); + return 0; + } + else { + PyErr_SetString(PyExc_TypeError, + "mmap indices must be integer"); + return -1; + } } 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_slice*/ - (ssizeobjargproc)mmap_ass_item, /*sq_ass_item*/ - 0, /*sq_ass_slice*/ + (lenfunc)mmap_length, /*sq_length*/ + (binaryfunc)mmap_concat, /*sq_concat*/ + (ssizeargfunc)mmap_repeat, /*sq_repeat*/ + (ssizeargfunc)mmap_item, /*sq_item*/ + 0, /*sq_slice*/ + (ssizeobjargproc)mmap_ass_item, /*sq_ass_item*/ + 0, /*sq_ass_slice*/ }; static PyMappingMethods mmap_as_mapping = { - (lenfunc)mmap_length, - (binaryfunc)mmap_subscript, - (objobjargproc)mmap_ass_subscript, + (lenfunc)mmap_length, + (binaryfunc)mmap_subscript, + (objobjargproc)mmap_ass_subscript, }; static PyBufferProcs mmap_as_buffer = { - (getbufferproc)mmap_buffer_getbuf, - (releasebufferproc)mmap_buffer_releasebuf, + (getbufferproc)mmap_buffer_getbuf, + (releasebufferproc)mmap_buffer_releasebuf, }; static PyObject * @@ -945,46 +945,46 @@ static PyTypeObject mmap_object_type = { - PyVarObject_HEAD_INIT(NULL, 0) - "mmap.mmap", /* tp_name */ - sizeof(mmap_object), /* tp_size */ - 0, /* tp_itemsize */ - /* methods */ - (destructor) mmap_object_dealloc, /* tp_dealloc */ - 0, /* tp_print */ - 0, /* tp_getattr */ - 0, /* tp_setattr */ - 0, /* tp_reserved */ - 0, /* tp_repr */ - 0, /* tp_as_number */ - &mmap_as_sequence, /*tp_as_sequence*/ - &mmap_as_mapping, /*tp_as_mapping*/ - 0, /*tp_hash*/ - 0, /*tp_call*/ - 0, /*tp_str*/ - PyObject_GenericGetAttr, /*tp_getattro*/ - 0, /*tp_setattro*/ - &mmap_as_buffer, /*tp_as_buffer*/ - Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /*tp_flags*/ - mmap_doc, /*tp_doc*/ - 0, /* tp_traverse */ - 0, /* tp_clear */ - 0, /* tp_richcompare */ - 0, /* tp_weaklistoffset */ - 0, /* tp_iter */ - 0, /* tp_iternext */ - mmap_object_methods, /* tp_methods */ - 0, /* tp_members */ - 0, /* tp_getset */ - 0, /* tp_base */ - 0, /* tp_dict */ - 0, /* tp_descr_get */ - 0, /* tp_descr_set */ - 0, /* tp_dictoffset */ - 0, /* tp_init */ - PyType_GenericAlloc, /* tp_alloc */ - new_mmap_object, /* tp_new */ - PyObject_Del, /* tp_free */ + PyVarObject_HEAD_INIT(NULL, 0) + "mmap.mmap", /* tp_name */ + sizeof(mmap_object), /* tp_size */ + 0, /* tp_itemsize */ + /* methods */ + (destructor) mmap_object_dealloc, /* tp_dealloc */ + 0, /* tp_print */ + 0, /* tp_getattr */ + 0, /* tp_setattr */ + 0, /* tp_reserved */ + 0, /* tp_repr */ + 0, /* tp_as_number */ + &mmap_as_sequence, /*tp_as_sequence*/ + &mmap_as_mapping, /*tp_as_mapping*/ + 0, /*tp_hash*/ + 0, /*tp_call*/ + 0, /*tp_str*/ + PyObject_GenericGetAttr, /*tp_getattro*/ + 0, /*tp_setattro*/ + &mmap_as_buffer, /*tp_as_buffer*/ + Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /*tp_flags*/ + mmap_doc, /*tp_doc*/ + 0, /* tp_traverse */ + 0, /* tp_clear */ + 0, /* tp_richcompare */ + 0, /* tp_weaklistoffset */ + 0, /* tp_iter */ + 0, /* tp_iternext */ + mmap_object_methods, /* tp_methods */ + 0, /* tp_members */ + 0, /* tp_getset */ + 0, /* tp_base */ + 0, /* tp_dict */ + 0, /* tp_descr_get */ + 0, /* tp_descr_set */ + 0, /* tp_dictoffset */ + 0, /* tp_init */ + PyType_GenericAlloc, /* tp_alloc */ + new_mmap_object, /* tp_new */ + PyObject_Del, /* tp_free */ }; @@ -995,23 +995,23 @@ static Py_ssize_t _GetMapSize(PyObject *o, const char* param) { - if (o == NULL) - return 0; - if (PyIndex_Check(o)) { - Py_ssize_t i = PyNumber_AsSsize_t(o, PyExc_OverflowError); - if (i==-1 && PyErr_Occurred()) - return -1; - if (i < 0) { - PyErr_Format(PyExc_OverflowError, - "memory mapped %s must be positive", - param); - return -1; - } - return i; - } + if (o == NULL) + return 0; + if (PyIndex_Check(o)) { + Py_ssize_t i = PyNumber_AsSsize_t(o, PyExc_OverflowError); + if (i==-1 && PyErr_Occurred()) + return -1; + if (i < 0) { + PyErr_Format(PyExc_OverflowError, + "memory mapped %s must be positive", + param); + return -1; + } + return i; + } - PyErr_SetString(PyExc_TypeError, "map size must be an integral value"); - return -1; + PyErr_SetString(PyExc_TypeError, "map size must be an integral value"); + return -1; } #ifdef UNIX @@ -1019,125 +1019,125 @@ new_mmap_object(PyTypeObject *type, PyObject *args, PyObject *kwdict) { #ifdef HAVE_FSTAT - struct stat st; + struct stat st; #endif - mmap_object *m_obj; - PyObject *map_size_obj = NULL, *offset_obj = NULL; - Py_ssize_t map_size, offset; - int fd, flags = MAP_SHARED, prot = PROT_WRITE | PROT_READ; - int devzero = -1; - int access = (int)ACCESS_DEFAULT; - static char *keywords[] = {"fileno", "length", - "flags", "prot", - "access", "offset", NULL}; - - if (!PyArg_ParseTupleAndKeywords(args, kwdict, "iO|iiiO", keywords, - &fd, &map_size_obj, &flags, &prot, - &access, &offset_obj)) - return NULL; - map_size = _GetMapSize(map_size_obj, "size"); - if (map_size < 0) - return NULL; - offset = _GetMapSize(offset_obj, "offset"); - if (offset < 0) - return NULL; - - if ((access != (int)ACCESS_DEFAULT) && - ((flags != MAP_SHARED) || (prot != (PROT_WRITE | PROT_READ)))) - return PyErr_Format(PyExc_ValueError, - "mmap can't specify both access and flags, prot."); - switch ((access_mode)access) { - case ACCESS_READ: - flags = MAP_SHARED; - prot = PROT_READ; - break; - case ACCESS_WRITE: - flags = MAP_SHARED; - prot = PROT_READ | PROT_WRITE; - break; - case ACCESS_COPY: - flags = MAP_PRIVATE; - prot = PROT_READ | PROT_WRITE; - break; - case ACCESS_DEFAULT: - /* use the specified or default values of flags and prot */ - break; - default: - return PyErr_Format(PyExc_ValueError, - "mmap invalid access parameter."); - } + mmap_object *m_obj; + PyObject *map_size_obj = NULL, *offset_obj = NULL; + Py_ssize_t map_size, offset; + int fd, flags = MAP_SHARED, prot = PROT_WRITE | PROT_READ; + int devzero = -1; + int access = (int)ACCESS_DEFAULT; + static char *keywords[] = {"fileno", "length", + "flags", "prot", + "access", "offset", NULL}; + + if (!PyArg_ParseTupleAndKeywords(args, kwdict, "iO|iiiO", keywords, + &fd, &map_size_obj, &flags, &prot, + &access, &offset_obj)) + return NULL; + map_size = _GetMapSize(map_size_obj, "size"); + if (map_size < 0) + return NULL; + offset = _GetMapSize(offset_obj, "offset"); + if (offset < 0) + return NULL; + + if ((access != (int)ACCESS_DEFAULT) && + ((flags != MAP_SHARED) || (prot != (PROT_WRITE | PROT_READ)))) + return PyErr_Format(PyExc_ValueError, + "mmap can't specify both access and flags, prot."); + switch ((access_mode)access) { + case ACCESS_READ: + flags = MAP_SHARED; + prot = PROT_READ; + break; + case ACCESS_WRITE: + flags = MAP_SHARED; + prot = PROT_READ | PROT_WRITE; + break; + case ACCESS_COPY: + flags = MAP_PRIVATE; + prot = PROT_READ | PROT_WRITE; + break; + case ACCESS_DEFAULT: + /* use the specified or default values of flags and prot */ + break; + default: + return PyErr_Format(PyExc_ValueError, + "mmap invalid access parameter."); + } if (prot == PROT_READ) { - access = ACCESS_READ; + access = ACCESS_READ; } #ifdef HAVE_FSTAT # ifdef __VMS - /* on OpenVMS we must ensure that all bytes are written to the file */ - if (fd != -1) { - fsync(fd); - } + /* on OpenVMS we must ensure that all bytes are written to the file */ + if (fd != -1) { + fsync(fd); + } # endif - if (fd != -1 && fstat(fd, &st) == 0 && S_ISREG(st.st_mode)) { - if (map_size == 0) { - map_size = st.st_size; - } else if ((size_t)offset + (size_t)map_size > st.st_size) { - PyErr_SetString(PyExc_ValueError, - "mmap length is greater than file size"); - return NULL; - } - } -#endif - m_obj = (mmap_object *)type->tp_alloc(type, 0); - if (m_obj == NULL) {return NULL;} - m_obj->data = NULL; - m_obj->size = (size_t) map_size; - m_obj->pos = (size_t) 0; - m_obj->exports = 0; - m_obj->offset = offset; - if (fd == -1) { - m_obj->fd = -1; - /* Assume the caller wants to map anonymous memory. - This is the same behaviour as Windows. mmap.mmap(-1, size) - on both Windows and Unix map anonymous memory. - */ + if (fd != -1 && fstat(fd, &st) == 0 && S_ISREG(st.st_mode)) { + if (map_size == 0) { + map_size = st.st_size; + } else if ((size_t)offset + (size_t)map_size > st.st_size) { + PyErr_SetString(PyExc_ValueError, + "mmap length is greater than file size"); + return NULL; + } + } +#endif + m_obj = (mmap_object *)type->tp_alloc(type, 0); + if (m_obj == NULL) {return NULL;} + m_obj->data = NULL; + m_obj->size = (size_t) map_size; + m_obj->pos = (size_t) 0; + m_obj->exports = 0; + m_obj->offset = offset; + if (fd == -1) { + m_obj->fd = -1; + /* Assume the caller wants to map anonymous memory. + This is the same behaviour as Windows. mmap.mmap(-1, size) + on both Windows and Unix map anonymous memory. + */ #ifdef MAP_ANONYMOUS - /* BSD way to map anonymous memory */ - flags |= MAP_ANONYMOUS; + /* BSD way to map anonymous memory */ + flags |= MAP_ANONYMOUS; #else - /* SVR4 method to map anonymous memory is to open /dev/zero */ - fd = devzero = open("/dev/zero", O_RDWR); - if (devzero == -1) { - Py_DECREF(m_obj); - PyErr_SetFromErrno(mmap_module_error); - return NULL; - } -#endif - } else { - m_obj->fd = dup(fd); - if (m_obj->fd == -1) { - Py_DECREF(m_obj); - PyErr_SetFromErrno(mmap_module_error); - return NULL; - } - } - - m_obj->data = mmap(NULL, map_size, - prot, flags, - fd, offset); - - if (devzero != -1) { - close(devzero); - } - - if (m_obj->data == (char *)-1) { - m_obj->data = NULL; - Py_DECREF(m_obj); - PyErr_SetFromErrno(mmap_module_error); - return NULL; - } - m_obj->access = (access_mode)access; - return (PyObject *)m_obj; + /* SVR4 method to map anonymous memory is to open /dev/zero */ + fd = devzero = open("/dev/zero", O_RDWR); + if (devzero == -1) { + Py_DECREF(m_obj); + PyErr_SetFromErrno(mmap_module_error); + return NULL; + } +#endif + } else { + m_obj->fd = dup(fd); + if (m_obj->fd == -1) { + Py_DECREF(m_obj); + PyErr_SetFromErrno(mmap_module_error); + return NULL; + } + } + + m_obj->data = mmap(NULL, map_size, + prot, flags, + fd, offset); + + if (devzero != -1) { + close(devzero); + } + + if (m_obj->data == (char *)-1) { + m_obj->data = NULL; + Py_DECREF(m_obj); + PyErr_SetFromErrno(mmap_module_error); + return NULL; + } + m_obj->access = (access_mode)access; + return (PyObject *)m_obj; } #endif /* UNIX */ @@ -1145,266 +1145,266 @@ static PyObject * new_mmap_object(PyTypeObject *type, PyObject *args, PyObject *kwdict) { - mmap_object *m_obj; - PyObject *map_size_obj = NULL, *offset_obj = NULL; - Py_ssize_t map_size, offset; - DWORD off_hi; /* upper 32 bits of offset */ - DWORD off_lo; /* lower 32 bits of offset */ - DWORD size_hi; /* upper 32 bits of size */ - DWORD size_lo; /* lower 32 bits of size */ - char *tagname = ""; - DWORD dwErr = 0; - int fileno; - HANDLE fh = 0; - int access = (access_mode)ACCESS_DEFAULT; - DWORD flProtect, dwDesiredAccess; - static char *keywords[] = { "fileno", "length", - "tagname", - "access", "offset", NULL }; - - if (!PyArg_ParseTupleAndKeywords(args, kwdict, "iO|ziO", keywords, - &fileno, &map_size_obj, - &tagname, &access, &offset_obj)) { - return NULL; - } - - switch((access_mode)access) { - case ACCESS_READ: - flProtect = PAGE_READONLY; - dwDesiredAccess = FILE_MAP_READ; - break; - case ACCESS_DEFAULT: case ACCESS_WRITE: - flProtect = PAGE_READWRITE; - dwDesiredAccess = FILE_MAP_WRITE; - break; - case ACCESS_COPY: - flProtect = PAGE_WRITECOPY; - dwDesiredAccess = FILE_MAP_COPY; - break; - default: - return PyErr_Format(PyExc_ValueError, - "mmap invalid access parameter."); - } - - map_size = _GetMapSize(map_size_obj, "size"); - if (map_size < 0) - return NULL; - offset = _GetMapSize(offset_obj, "offset"); - if (offset < 0) - return NULL; - - /* assume -1 and 0 both mean invalid filedescriptor - to 'anonymously' map memory. - XXX: fileno == 0 is a valid fd, but was accepted prior to 2.5. - XXX: Should this code be added? - if (fileno == 0) - PyErr_WarnEx(PyExc_DeprecationWarning, - "don't use 0 for anonymous memory", - 1); - */ - if (fileno != -1 && fileno != 0) { - fh = (HANDLE)_get_osfhandle(fileno); - if (fh==(HANDLE)-1) { - PyErr_SetFromErrno(mmap_module_error); - return NULL; - } - /* Win9x appears to need us seeked to zero */ - lseek(fileno, 0, SEEK_SET); - } - - m_obj = (mmap_object *)type->tp_alloc(type, 0); - if (m_obj == NULL) - return NULL; - /* Set every field to an invalid marker, so we can safely - destruct the object in the face of failure */ - m_obj->data = NULL; - m_obj->file_handle = INVALID_HANDLE_VALUE; - m_obj->map_handle = NULL; - m_obj->tagname = NULL; - m_obj->offset = offset; - - if (fh) { - /* It is necessary to duplicate the handle, so the - Python code can close it on us */ - if (!DuplicateHandle( - GetCurrentProcess(), /* source process handle */ - fh, /* handle to be duplicated */ - GetCurrentProcess(), /* target proc handle */ - (LPHANDLE)&m_obj->file_handle, /* result */ - 0, /* access - ignored due to options value */ - FALSE, /* inherited by child processes? */ - DUPLICATE_SAME_ACCESS)) { /* options */ - dwErr = GetLastError(); - Py_DECREF(m_obj); - PyErr_SetFromWindowsErr(dwErr); - return NULL; - } - if (!map_size) { - DWORD low,high; - low = GetFileSize(fh, &high); - /* low might just happen to have the value INVALID_FILE_SIZE; - so we need to check the last error also. */ - if (low == INVALID_FILE_SIZE && - (dwErr = GetLastError()) != NO_ERROR) { - Py_DECREF(m_obj); - return PyErr_SetFromWindowsErr(dwErr); - } + mmap_object *m_obj; + PyObject *map_size_obj = NULL, *offset_obj = NULL; + Py_ssize_t map_size, offset; + DWORD off_hi; /* upper 32 bits of offset */ + DWORD off_lo; /* lower 32 bits of offset */ + DWORD size_hi; /* upper 32 bits of size */ + DWORD size_lo; /* lower 32 bits of size */ + char *tagname = ""; + DWORD dwErr = 0; + int fileno; + HANDLE fh = 0; + int access = (access_mode)ACCESS_DEFAULT; + DWORD flProtect, dwDesiredAccess; + static char *keywords[] = { "fileno", "length", + "tagname", + "access", "offset", NULL }; + + if (!PyArg_ParseTupleAndKeywords(args, kwdict, "iO|ziO", keywords, + &fileno, &map_size_obj, + &tagname, &access, &offset_obj)) { + return NULL; + } + + switch((access_mode)access) { + case ACCESS_READ: + flProtect = PAGE_READONLY; + dwDesiredAccess = FILE_MAP_READ; + break; + case ACCESS_DEFAULT: case ACCESS_WRITE: + flProtect = PAGE_READWRITE; + dwDesiredAccess = FILE_MAP_WRITE; + break; + case ACCESS_COPY: + flProtect = PAGE_WRITECOPY; + dwDesiredAccess = FILE_MAP_COPY; + break; + default: + return PyErr_Format(PyExc_ValueError, + "mmap invalid access parameter."); + } + + map_size = _GetMapSize(map_size_obj, "size"); + if (map_size < 0) + return NULL; + offset = _GetMapSize(offset_obj, "offset"); + if (offset < 0) + return NULL; + + /* assume -1 and 0 both mean invalid filedescriptor + to 'anonymously' map memory. + XXX: fileno == 0 is a valid fd, but was accepted prior to 2.5. + XXX: Should this code be added? + if (fileno == 0) + PyErr_WarnEx(PyExc_DeprecationWarning, + "don't use 0 for anonymous memory", + 1); + */ + if (fileno != -1 && fileno != 0) { + fh = (HANDLE)_get_osfhandle(fileno); + if (fh==(HANDLE)-1) { + PyErr_SetFromErrno(mmap_module_error); + return NULL; + } + /* Win9x appears to need us seeked to zero */ + lseek(fileno, 0, SEEK_SET); + } + + m_obj = (mmap_object *)type->tp_alloc(type, 0); + if (m_obj == NULL) + return NULL; + /* Set every field to an invalid marker, so we can safely + destruct the object in the face of failure */ + m_obj->data = NULL; + m_obj->file_handle = INVALID_HANDLE_VALUE; + m_obj->map_handle = NULL; + m_obj->tagname = NULL; + m_obj->offset = offset; + + if (fh) { + /* It is necessary to duplicate the handle, so the + Python code can close it on us */ + if (!DuplicateHandle( + GetCurrentProcess(), /* source process handle */ + fh, /* handle to be duplicated */ + GetCurrentProcess(), /* target proc handle */ + (LPHANDLE)&m_obj->file_handle, /* result */ + 0, /* access - ignored due to options value */ + FALSE, /* inherited by child processes? */ + DUPLICATE_SAME_ACCESS)) { /* options */ + dwErr = GetLastError(); + Py_DECREF(m_obj); + PyErr_SetFromWindowsErr(dwErr); + return NULL; + } + if (!map_size) { + DWORD low,high; + low = GetFileSize(fh, &high); + /* low might just happen to have the value INVALID_FILE_SIZE; + so we need to check the last error also. */ + if (low == INVALID_FILE_SIZE && + (dwErr = GetLastError()) != NO_ERROR) { + Py_DECREF(m_obj); + return PyErr_SetFromWindowsErr(dwErr); + } #if SIZEOF_SIZE_T > 4 - m_obj->size = (((size_t)high)<<32) + low; + m_obj->size = (((size_t)high)<<32) + low; #else - if (high) - /* File is too large to map completely */ - m_obj->size = (size_t)-1; - else - m_obj->size = low; -#endif - } else { - m_obj->size = map_size; - } - } - else { - m_obj->size = map_size; - } - - /* set the initial position */ - m_obj->pos = (size_t) 0; - - m_obj->exports = 0; - /* set the tag name */ - if (tagname != NULL && *tagname != '\0') { - m_obj->tagname = PyMem_Malloc(strlen(tagname)+1); - if (m_obj->tagname == NULL) { - PyErr_NoMemory(); - Py_DECREF(m_obj); - return NULL; - } - strcpy(m_obj->tagname, tagname); - } - else - m_obj->tagname = NULL; - - m_obj->access = (access_mode)access; - /* DWORD is a 4-byte int. If we're on a box where size_t consumes - * more than 4 bytes, we need to break it apart. Else (size_t - * consumes 4 bytes), C doesn't define what happens if we shift - * right by 32, so we need different code. - */ + if (high) + /* File is too large to map completely */ + m_obj->size = (size_t)-1; + else + m_obj->size = low; +#endif + } else { + m_obj->size = map_size; + } + } + else { + m_obj->size = map_size; + } + + /* set the initial position */ + m_obj->pos = (size_t) 0; + + m_obj->exports = 0; + /* set the tag name */ + if (tagname != NULL && *tagname != '\0') { + m_obj->tagname = PyMem_Malloc(strlen(tagname)+1); + if (m_obj->tagname == NULL) { + PyErr_NoMemory(); + Py_DECREF(m_obj); + return NULL; + } + strcpy(m_obj->tagname, tagname); + } + else + m_obj->tagname = NULL; + + m_obj->access = (access_mode)access; + /* DWORD is a 4-byte int. If we're on a box where size_t consumes + * more than 4 bytes, we need to break it apart. Else (size_t + * consumes 4 bytes), C doesn't define what happens if we shift + * right by 32, so we need different code. + */ #if SIZEOF_SIZE_T > 4 - size_hi = (DWORD)((offset + m_obj->size) >> 32); - size_lo = (DWORD)((offset + m_obj->size) & 0xFFFFFFFF); - off_hi = (DWORD)(offset >> 32); - off_lo = (DWORD)(offset & 0xFFFFFFFF); + size_hi = (DWORD)((offset + m_obj->size) >> 32); + size_lo = (DWORD)((offset + m_obj->size) & 0xFFFFFFFF); + off_hi = (DWORD)(offset >> 32); + off_lo = (DWORD)(offset & 0xFFFFFFFF); #else - size_hi = 0; - size_lo = (DWORD)(offset + m_obj->size); - off_hi = 0; - off_lo = (DWORD)offset; -#endif - /* For files, it would be sufficient to pass 0 as size. - For anonymous maps, we have to pass the size explicitly. */ - m_obj->map_handle = CreateFileMapping(m_obj->file_handle, - NULL, - flProtect, - size_hi, - size_lo, - m_obj->tagname); - if (m_obj->map_handle != NULL) { - m_obj->data = (char *) MapViewOfFile(m_obj->map_handle, - dwDesiredAccess, - off_hi, - off_lo, - m_obj->size); - if (m_obj->data != NULL) - return (PyObject *)m_obj; - else { - dwErr = GetLastError(); - CloseHandle(m_obj->map_handle); - m_obj->map_handle = NULL; - } - } else - dwErr = GetLastError(); - Py_DECREF(m_obj); - PyErr_SetFromWindowsErr(dwErr); - return NULL; + size_hi = 0; + size_lo = (DWORD)(offset + m_obj->size); + off_hi = 0; + off_lo = (DWORD)offset; +#endif + /* For files, it would be sufficient to pass 0 as size. + For anonymous maps, we have to pass the size explicitly. */ + m_obj->map_handle = CreateFileMapping(m_obj->file_handle, + NULL, + flProtect, + size_hi, + size_lo, + m_obj->tagname); + if (m_obj->map_handle != NULL) { + m_obj->data = (char *) MapViewOfFile(m_obj->map_handle, + dwDesiredAccess, + off_hi, + off_lo, + m_obj->size); + if (m_obj->data != NULL) + return (PyObject *)m_obj; + else { + dwErr = GetLastError(); + CloseHandle(m_obj->map_handle); + m_obj->map_handle = NULL; + } + } else + dwErr = GetLastError(); + Py_DECREF(m_obj); + PyErr_SetFromWindowsErr(dwErr); + return NULL; } #endif /* MS_WINDOWS */ static void setint(PyObject *d, const char *name, long value) { - PyObject *o = PyLong_FromLong(value); - if (o && PyDict_SetItemString(d, name, o) == 0) { - Py_DECREF(o); - } + PyObject *o = PyLong_FromLong(value); + if (o && PyDict_SetItemString(d, name, o) == 0) { + Py_DECREF(o); + } } static struct PyModuleDef mmapmodule = { - PyModuleDef_HEAD_INIT, - "mmap", - NULL, - -1, - NULL, - NULL, - NULL, - NULL, - NULL + PyModuleDef_HEAD_INIT, + "mmap", + NULL, + -1, + NULL, + NULL, + NULL, + NULL, + NULL }; PyMODINIT_FUNC PyInit_mmap(void) { - PyObject *dict, *module; + PyObject *dict, *module; - if (PyType_Ready(&mmap_object_type) < 0) - return NULL; + if (PyType_Ready(&mmap_object_type) < 0) + return NULL; - module = PyModule_Create(&mmapmodule); - if (module == NULL) - return NULL; - dict = PyModule_GetDict(module); - if (!dict) - return NULL; - mmap_module_error = PyErr_NewException("mmap.error", - PyExc_EnvironmentError , NULL); - if (mmap_module_error == NULL) - return NULL; - PyDict_SetItemString(dict, "error", mmap_module_error); - PyDict_SetItemString(dict, "mmap", (PyObject*) &mmap_object_type); + module = PyModule_Create(&mmapmodule); + if (module == NULL) + return NULL; + dict = PyModule_GetDict(module); + if (!dict) + return NULL; + mmap_module_error = PyErr_NewException("mmap.error", + PyExc_EnvironmentError , NULL); + if (mmap_module_error == NULL) + return NULL; + PyDict_SetItemString(dict, "error", mmap_module_error); + PyDict_SetItemString(dict, "mmap", (PyObject*) &mmap_object_type); #ifdef PROT_EXEC - setint(dict, "PROT_EXEC", PROT_EXEC); + setint(dict, "PROT_EXEC", PROT_EXEC); #endif #ifdef PROT_READ - setint(dict, "PROT_READ", PROT_READ); + setint(dict, "PROT_READ", PROT_READ); #endif #ifdef PROT_WRITE - setint(dict, "PROT_WRITE", PROT_WRITE); + setint(dict, "PROT_WRITE", PROT_WRITE); #endif #ifdef MAP_SHARED - setint(dict, "MAP_SHARED", MAP_SHARED); + setint(dict, "MAP_SHARED", MAP_SHARED); #endif #ifdef MAP_PRIVATE - setint(dict, "MAP_PRIVATE", MAP_PRIVATE); + setint(dict, "MAP_PRIVATE", MAP_PRIVATE); #endif #ifdef MAP_DENYWRITE - setint(dict, "MAP_DENYWRITE", MAP_DENYWRITE); + setint(dict, "MAP_DENYWRITE", MAP_DENYWRITE); #endif #ifdef MAP_EXECUTABLE - setint(dict, "MAP_EXECUTABLE", MAP_EXECUTABLE); + setint(dict, "MAP_EXECUTABLE", MAP_EXECUTABLE); #endif #ifdef MAP_ANONYMOUS - setint(dict, "MAP_ANON", MAP_ANONYMOUS); - setint(dict, "MAP_ANONYMOUS", MAP_ANONYMOUS); + setint(dict, "MAP_ANON", MAP_ANONYMOUS); + setint(dict, "MAP_ANONYMOUS", MAP_ANONYMOUS); #endif - setint(dict, "PAGESIZE", (long)my_getpagesize()); + setint(dict, "PAGESIZE", (long)my_getpagesize()); - setint(dict, "ALLOCATIONGRANULARITY", (long)my_getallocationgranularity()); + setint(dict, "ALLOCATIONGRANULARITY", (long)my_getallocationgranularity()); - setint(dict, "ACCESS_READ", ACCESS_READ); - setint(dict, "ACCESS_WRITE", ACCESS_WRITE); - setint(dict, "ACCESS_COPY", ACCESS_COPY); - return module; + setint(dict, "ACCESS_READ", ACCESS_READ); + setint(dict, "ACCESS_WRITE", ACCESS_WRITE); + setint(dict, "ACCESS_COPY", ACCESS_COPY); + return module; } Modified: python/branches/py3k/Modules/nismodule.c ============================================================================== --- python/branches/py3k/Modules/nismodule.c (original) +++ python/branches/py3k/Modules/nismodule.c Sun May 9 17:52:27 2010 @@ -1,11 +1,11 @@ /*********************************************************** Written by: - Fred Gansevles - B&O group, - Faculteit der Informatica, - Universiteit Twente, - Enschede, - the Netherlands. + Fred Gansevles + B&O group, + Faculteit der Informatica, + Universiteit Twente, + Enschede, + the Netherlands. ******************************************************************/ /* NIS module implementation */ @@ -23,7 +23,7 @@ extern int yp_get_default_domain(char **); #endif -PyDoc_STRVAR(get_default_domain__doc__, +PyDoc_STRVAR(get_default_domain__doc__, "get_default_domain() -> str\n\ Corresponds to the C library yp_get_default_domain() call, returning\n\ the default NIS domain.\n"); @@ -49,44 +49,44 @@ static PyObject * nis_error (int err) { - PyErr_SetString(NisError, yperr_string(err)); - return NULL; + PyErr_SetString(NisError, yperr_string(err)); + return NULL; } static struct nis_map { - char *alias; - char *map; - int fix; + char *alias; + char *map; + int fix; } aliases [] = { - {"passwd", "passwd.byname", 0}, - {"group", "group.byname", 0}, - {"networks", "networks.byaddr", 0}, - {"hosts", "hosts.byname", 0}, - {"protocols", "protocols.bynumber", 0}, - {"services", "services.byname", 0}, - {"aliases", "mail.aliases", 1}, /* created with 'makedbm -a' */ - {"ethers", "ethers.byname", 0}, - {0L, 0L, 0} + {"passwd", "passwd.byname", 0}, + {"group", "group.byname", 0}, + {"networks", "networks.byaddr", 0}, + {"hosts", "hosts.byname", 0}, + {"protocols", "protocols.bynumber", 0}, + {"services", "services.byname", 0}, + {"aliases", "mail.aliases", 1}, /* created with 'makedbm -a' */ + {"ethers", "ethers.byname", 0}, + {0L, 0L, 0} }; static char * nis_mapname (char *map, int *pfix) { - int i; + int i; - *pfix = 0; - for (i=0; aliases[i].alias != 0L; i++) { - if (!strcmp (aliases[i].alias, map)) { - *pfix = aliases[i].fix; - return aliases[i].map; - } - if (!strcmp (aliases[i].map, map)) { - *pfix = aliases[i].fix; - return aliases[i].map; - } - } + *pfix = 0; + for (i=0; aliases[i].alias != 0L; i++) { + if (!strcmp (aliases[i].alias, map)) { + *pfix = aliases[i].fix; + return aliases[i].map; + } + if (!strcmp (aliases[i].map, map)) { + *pfix = aliases[i].fix; + return aliases[i].map; + } + } - return map; + return map; } #if defined(__APPLE__) || defined(__OpenBSD__) || defined(__FreeBSD__) @@ -96,168 +96,168 @@ #endif struct ypcallback_data { - PyObject *dict; - int fix; - PyThreadState *state; + PyObject *dict; + int fix; + PyThreadState *state; }; static int nis_foreach (int instatus, char *inkey, int inkeylen, char *inval, int invallen, struct ypcallback_data *indata) { - if (instatus == YP_TRUE) { - PyObject *key; - PyObject *val; - int err; - - PyEval_RestoreThread(indata->state); - if (indata->fix) { - if (inkeylen > 0 && inkey[inkeylen-1] == '\0') - inkeylen--; - if (invallen > 0 && inval[invallen-1] == '\0') - invallen--; - } - key = PyUnicode_FromStringAndSize(inkey, inkeylen); - val = PyUnicode_FromStringAndSize(inval, invallen); - if (key == NULL || val == NULL) { - /* XXX error -- don't know how to handle */ - PyErr_Clear(); - Py_XDECREF(key); - Py_XDECREF(val); - return 1; - } - err = PyDict_SetItem(indata->dict, key, val); - Py_DECREF(key); - Py_DECREF(val); - if (err != 0) - PyErr_Clear(); - indata->state = PyEval_SaveThread(); - if (err != 0) - return 1; - return 0; - } - return 1; + if (instatus == YP_TRUE) { + PyObject *key; + PyObject *val; + int err; + + PyEval_RestoreThread(indata->state); + if (indata->fix) { + if (inkeylen > 0 && inkey[inkeylen-1] == '\0') + inkeylen--; + if (invallen > 0 && inval[invallen-1] == '\0') + invallen--; + } + key = PyUnicode_FromStringAndSize(inkey, inkeylen); + val = PyUnicode_FromStringAndSize(inval, invallen); + if (key == NULL || val == NULL) { + /* XXX error -- don't know how to handle */ + PyErr_Clear(); + Py_XDECREF(key); + Py_XDECREF(val); + return 1; + } + err = PyDict_SetItem(indata->dict, key, val); + Py_DECREF(key); + Py_DECREF(val); + if (err != 0) + PyErr_Clear(); + indata->state = PyEval_SaveThread(); + if (err != 0) + return 1; + return 0; + } + return 1; } static PyObject * nis_get_default_domain (PyObject *self) { - char *domain; - int err; - PyObject *res; + char *domain; + int err; + PyObject *res; - if ((err = yp_get_default_domain(&domain)) != 0) - return nis_error(err); + if ((err = yp_get_default_domain(&domain)) != 0) + return nis_error(err); - res = PyUnicode_FromStringAndSize (domain, strlen(domain)); - return res; + res = PyUnicode_FromStringAndSize (domain, strlen(domain)); + return res; } static PyObject * nis_match (PyObject *self, PyObject *args, PyObject *kwdict) { - char *match; - char *domain = NULL; - int keylen, len; - char *key, *map; - int err; - PyObject *res; - int fix; - static char *kwlist[] = {"key", "map", "domain", NULL}; - - if (!PyArg_ParseTupleAndKeywords(args, kwdict, - "s#s|s:match", kwlist, - &key, &keylen, &map, &domain)) - return NULL; - if (!domain && ((err = yp_get_default_domain(&domain)) != 0)) - return nis_error(err); - map = nis_mapname (map, &fix); - if (fix) - keylen++; - Py_BEGIN_ALLOW_THREADS - err = yp_match (domain, map, key, keylen, &match, &len); - Py_END_ALLOW_THREADS - if (fix) - len--; - if (err != 0) - return nis_error(err); - res = PyUnicode_FromStringAndSize (match, len); - free (match); - return res; + char *match; + char *domain = NULL; + int keylen, len; + char *key, *map; + int err; + PyObject *res; + int fix; + static char *kwlist[] = {"key", "map", "domain", NULL}; + + if (!PyArg_ParseTupleAndKeywords(args, kwdict, + "s#s|s:match", kwlist, + &key, &keylen, &map, &domain)) + return NULL; + if (!domain && ((err = yp_get_default_domain(&domain)) != 0)) + return nis_error(err); + map = nis_mapname (map, &fix); + if (fix) + keylen++; + Py_BEGIN_ALLOW_THREADS + err = yp_match (domain, map, key, keylen, &match, &len); + Py_END_ALLOW_THREADS + if (fix) + len--; + if (err != 0) + return nis_error(err); + res = PyUnicode_FromStringAndSize (match, len); + free (match); + return res; } static PyObject * nis_cat (PyObject *self, PyObject *args, PyObject *kwdict) { - char *domain = NULL; - char *map; - struct ypall_callback cb; - struct ypcallback_data data; - PyObject *dict; - int err; - static char *kwlist[] = {"map", "domain", NULL}; - - if (!PyArg_ParseTupleAndKeywords(args, kwdict, "s|s:cat", - kwlist, &map, &domain)) - return NULL; - if (!domain && ((err = yp_get_default_domain(&domain)) != 0)) - return nis_error(err); - dict = PyDict_New (); - if (dict == NULL) - return NULL; - cb.foreach = (foreachfunc)nis_foreach; - data.dict = dict; - map = nis_mapname (map, &data.fix); - cb.data = (char *)&data; - data.state = PyEval_SaveThread(); - err = yp_all (domain, map, &cb); - PyEval_RestoreThread(data.state); - if (err != 0) { - Py_DECREF(dict); - return nis_error(err); - } - return dict; + char *domain = NULL; + char *map; + struct ypall_callback cb; + struct ypcallback_data data; + PyObject *dict; + int err; + static char *kwlist[] = {"map", "domain", NULL}; + + if (!PyArg_ParseTupleAndKeywords(args, kwdict, "s|s:cat", + kwlist, &map, &domain)) + return NULL; + if (!domain && ((err = yp_get_default_domain(&domain)) != 0)) + return nis_error(err); + dict = PyDict_New (); + if (dict == NULL) + return NULL; + cb.foreach = (foreachfunc)nis_foreach; + data.dict = dict; + map = nis_mapname (map, &data.fix); + cb.data = (char *)&data; + data.state = PyEval_SaveThread(); + err = yp_all (domain, map, &cb); + PyEval_RestoreThread(data.state); + if (err != 0) { + Py_DECREF(dict); + return nis_error(err); + } + return dict; } /* These should be u_long on Sun h/w but not on 64-bit h/w. This is not portable to machines with 16-bit ints and no prototypes */ #ifndef YPPROC_MAPLIST -#define YPPROC_MAPLIST 11 +#define YPPROC_MAPLIST 11 #endif #ifndef YPPROG -#define YPPROG 100004 +#define YPPROG 100004 #endif #ifndef YPVERS -#define YPVERS 2 +#define YPVERS 2 #endif typedef char *domainname; typedef char *mapname; enum nisstat { - NIS_TRUE = 1, - NIS_NOMORE = 2, - NIS_FALSE = 0, - NIS_NOMAP = -1, - NIS_NODOM = -2, - NIS_NOKEY = -3, - NIS_BADOP = -4, - NIS_BADDB = -5, - NIS_YPERR = -6, - NIS_BADARGS = -7, - NIS_VERS = -8 + NIS_TRUE = 1, + NIS_NOMORE = 2, + NIS_FALSE = 0, + NIS_NOMAP = -1, + NIS_NODOM = -2, + NIS_NOKEY = -3, + NIS_BADOP = -4, + NIS_BADDB = -5, + NIS_YPERR = -6, + NIS_BADARGS = -7, + NIS_VERS = -8 }; typedef enum nisstat nisstat; struct nismaplist { - mapname map; - struct nismaplist *next; + mapname map; + struct nismaplist *next; }; typedef struct nismaplist nismaplist; struct nisresp_maplist { - nisstat stat; - nismaplist *maps; + nisstat stat; + nismaplist *maps; }; typedef struct nisresp_maplist nisresp_maplist; @@ -267,45 +267,45 @@ bool_t nis_xdr_domainname(XDR *xdrs, domainname *objp) { - if (!xdr_string(xdrs, objp, YPMAXDOMAIN)) { - return (FALSE); - } - return (TRUE); + if (!xdr_string(xdrs, objp, YPMAXDOMAIN)) { + return (FALSE); + } + return (TRUE); } static bool_t nis_xdr_mapname(XDR *xdrs, mapname *objp) { - if (!xdr_string(xdrs, objp, YPMAXMAP)) { - return (FALSE); - } - return (TRUE); + if (!xdr_string(xdrs, objp, YPMAXMAP)) { + return (FALSE); + } + return (TRUE); } static bool_t nis_xdr_ypmaplist(XDR *xdrs, nismaplist *objp) { - if (!nis_xdr_mapname(xdrs, &objp->map)) { - return (FALSE); - } - if (!xdr_pointer(xdrs, (char **)&objp->next, - sizeof(nismaplist), (xdrproc_t)nis_xdr_ypmaplist)) - { - return (FALSE); - } - return (TRUE); + if (!nis_xdr_mapname(xdrs, &objp->map)) { + return (FALSE); + } + if (!xdr_pointer(xdrs, (char **)&objp->next, + sizeof(nismaplist), (xdrproc_t)nis_xdr_ypmaplist)) + { + return (FALSE); + } + return (TRUE); } static bool_t nis_xdr_ypstat(XDR *xdrs, nisstat *objp) { - if (!xdr_enum(xdrs, (enum_t *)objp)) { - return (FALSE); - } - return (TRUE); + if (!xdr_enum(xdrs, (enum_t *)objp)) { + return (FALSE); + } + return (TRUE); } @@ -313,15 +313,15 @@ bool_t nis_xdr_ypresp_maplist(XDR *xdrs, nisresp_maplist *objp) { - if (!nis_xdr_ypstat(xdrs, &objp->stat)) { - return (FALSE); - } - if (!xdr_pointer(xdrs, (char **)&objp->maps, - sizeof(nismaplist), (xdrproc_t)nis_xdr_ypmaplist)) - { - return (FALSE); - } - return (TRUE); + if (!nis_xdr_ypstat(xdrs, &objp->stat)) { + return (FALSE); + } + if (!xdr_pointer(xdrs, (char **)&objp->maps, + sizeof(nismaplist), (xdrproc_t)nis_xdr_ypmaplist)) + { + return (FALSE); + } + return (TRUE); } @@ -329,132 +329,132 @@ nisresp_maplist * nisproc_maplist_2(domainname *argp, CLIENT *clnt) { - static nisresp_maplist res; + static nisresp_maplist res; - memset(&res, 0, sizeof(res)); - if (clnt_call(clnt, YPPROC_MAPLIST, - (xdrproc_t)nis_xdr_domainname, (caddr_t)argp, - (xdrproc_t)nis_xdr_ypresp_maplist, (caddr_t)&res, - TIMEOUT) != RPC_SUCCESS) - { - return (NULL); - } - return (&res); + memset(&res, 0, sizeof(res)); + if (clnt_call(clnt, YPPROC_MAPLIST, + (xdrproc_t)nis_xdr_domainname, (caddr_t)argp, + (xdrproc_t)nis_xdr_ypresp_maplist, (caddr_t)&res, + TIMEOUT) != RPC_SUCCESS) + { + return (NULL); + } + return (&res); } static nismaplist * nis_maplist (char *dom) { - nisresp_maplist *list; - CLIENT *cl; - char *server = NULL; - int mapi = 0; - - while (!server && aliases[mapi].map != 0L) { - yp_master (dom, aliases[mapi].map, &server); - mapi++; - } - if (!server) { - PyErr_SetString(NisError, "No NIS master found for any map"); - return NULL; - } - cl = clnt_create(server, YPPROG, YPVERS, "tcp"); - if (cl == NULL) { - PyErr_SetString(NisError, clnt_spcreateerror(server)); - goto finally; - } - list = nisproc_maplist_2 (&dom, cl); - clnt_destroy(cl); - if (list == NULL) - goto finally; - if (list->stat != NIS_TRUE) - goto finally; + nisresp_maplist *list; + CLIENT *cl; + char *server = NULL; + int mapi = 0; + + while (!server && aliases[mapi].map != 0L) { + yp_master (dom, aliases[mapi].map, &server); + mapi++; + } + if (!server) { + PyErr_SetString(NisError, "No NIS master found for any map"); + return NULL; + } + cl = clnt_create(server, YPPROG, YPVERS, "tcp"); + if (cl == NULL) { + PyErr_SetString(NisError, clnt_spcreateerror(server)); + goto finally; + } + list = nisproc_maplist_2 (&dom, cl); + clnt_destroy(cl); + if (list == NULL) + goto finally; + if (list->stat != NIS_TRUE) + goto finally; - free(server); - return list->maps; + free(server); + return list->maps; finally: - free(server); - return NULL; + free(server); + return NULL; } static PyObject * nis_maps (PyObject *self, PyObject *args, PyObject *kwdict) { - char *domain = NULL; - nismaplist *maps; - PyObject *list; - int err; - static char *kwlist[] = {"domain", NULL}; - - if (!PyArg_ParseTupleAndKeywords(args, kwdict, - "|s:maps", kwlist, &domain)) - return NULL; - if (!domain && ((err = yp_get_default_domain (&domain)) != 0)) { - nis_error(err); - return NULL; - } - - if ((maps = nis_maplist (domain)) == NULL) - return NULL; - if ((list = PyList_New(0)) == NULL) - return NULL; - for (maps = maps; maps; maps = maps->next) { - PyObject *str = PyUnicode_FromString(maps->map); - if (!str || PyList_Append(list, str) < 0) - { - Py_DECREF(list); - list = NULL; - break; - } - Py_DECREF(str); - } - /* XXX Shouldn't we free the list of maps now? */ - return list; + char *domain = NULL; + nismaplist *maps; + PyObject *list; + int err; + static char *kwlist[] = {"domain", NULL}; + + if (!PyArg_ParseTupleAndKeywords(args, kwdict, + "|s:maps", kwlist, &domain)) + return NULL; + if (!domain && ((err = yp_get_default_domain (&domain)) != 0)) { + nis_error(err); + return NULL; + } + + if ((maps = nis_maplist (domain)) == NULL) + return NULL; + if ((list = PyList_New(0)) == NULL) + return NULL; + for (maps = maps; maps; maps = maps->next) { + PyObject *str = PyUnicode_FromString(maps->map); + if (!str || PyList_Append(list, str) < 0) + { + Py_DECREF(list); + list = NULL; + break; + } + Py_DECREF(str); + } + /* XXX Shouldn't we free the list of maps now? */ + return list; } static PyMethodDef nis_methods[] = { - {"match", (PyCFunction)nis_match, - METH_VARARGS | METH_KEYWORDS, - match__doc__}, - {"cat", (PyCFunction)nis_cat, - METH_VARARGS | METH_KEYWORDS, - cat__doc__}, - {"maps", (PyCFunction)nis_maps, - METH_VARARGS | METH_KEYWORDS, - maps__doc__}, - {"get_default_domain", (PyCFunction)nis_get_default_domain, - METH_NOARGS, - get_default_domain__doc__}, - {NULL, NULL} /* Sentinel */ + {"match", (PyCFunction)nis_match, + METH_VARARGS | METH_KEYWORDS, + match__doc__}, + {"cat", (PyCFunction)nis_cat, + METH_VARARGS | METH_KEYWORDS, + cat__doc__}, + {"maps", (PyCFunction)nis_maps, + METH_VARARGS | METH_KEYWORDS, + maps__doc__}, + {"get_default_domain", (PyCFunction)nis_get_default_domain, + METH_NOARGS, + get_default_domain__doc__}, + {NULL, NULL} /* Sentinel */ }; PyDoc_STRVAR(nis__doc__, "This module contains functions for accessing NIS maps.\n"); static struct PyModuleDef nismodule = { - PyModuleDef_HEAD_INIT, - "nis", - nis__doc__, - -1, - nis_methods, - NULL, - NULL, - NULL, - NULL + PyModuleDef_HEAD_INIT, + "nis", + nis__doc__, + -1, + nis_methods, + NULL, + NULL, + NULL, + NULL }; PyObject* PyInit_nis (void) { - PyObject *m, *d; - m = PyModule_Create(&nismodule); - if (m == NULL) - return NULL; - d = PyModule_GetDict(m); - NisError = PyErr_NewException("nis.error", NULL, NULL); - if (NisError != NULL) - PyDict_SetItemString(d, "error", NisError); - return m; + PyObject *m, *d; + m = PyModule_Create(&nismodule); + if (m == NULL) + return NULL; + d = PyModule_GetDict(m); + NisError = PyErr_NewException("nis.error", NULL, NULL); + if (NisError != NULL) + PyDict_SetItemString(d, "error", NisError); + return m; } Modified: python/branches/py3k/Modules/operator.c ============================================================================== --- python/branches/py3k/Modules/operator.c (original) +++ python/branches/py3k/Modules/operator.c Sun May 9 17:52:27 2010 @@ -112,47 +112,47 @@ static PyObject* op_pow(PyObject *s, PyObject *a) { - PyObject *a1, *a2; - if (PyArg_UnpackTuple(a,"pow", 2, 2, &a1, &a2)) - return PyNumber_Power(a1, a2, Py_None); - return NULL; + PyObject *a1, *a2; + if (PyArg_UnpackTuple(a,"pow", 2, 2, &a1, &a2)) + return PyNumber_Power(a1, a2, Py_None); + return NULL; } static PyObject* op_ipow(PyObject *s, PyObject *a) { - PyObject *a1, *a2; - if (PyArg_UnpackTuple(a,"ipow", 2, 2, &a1, &a2)) - return PyNumber_InPlacePower(a1, a2, Py_None); - return NULL; + PyObject *a1, *a2; + if (PyArg_UnpackTuple(a,"ipow", 2, 2, &a1, &a2)) + return PyNumber_InPlacePower(a1, a2, Py_None); + return NULL; } static PyObject * op_index(PyObject *s, PyObject *a) { - return PyNumber_Index(a); + return PyNumber_Index(a); } static PyObject* is_(PyObject *s, PyObject *a) { - PyObject *a1, *a2, *result = NULL; - if (PyArg_UnpackTuple(a,"is_", 2, 2, &a1, &a2)) { - result = (a1 == a2) ? Py_True : Py_False; - Py_INCREF(result); - } - return result; + PyObject *a1, *a2, *result = NULL; + if (PyArg_UnpackTuple(a,"is_", 2, 2, &a1, &a2)) { + result = (a1 == a2) ? Py_True : Py_False; + Py_INCREF(result); + } + return result; } static PyObject* is_not(PyObject *s, PyObject *a) { - PyObject *a1, *a2, *result = NULL; - if (PyArg_UnpackTuple(a,"is_not", 2, 2, &a1, &a2)) { - result = (a1 != a2) ? Py_True : Py_False; - Py_INCREF(result); - } - return result; + PyObject *a1, *a2, *result = NULL; + if (PyArg_UnpackTuple(a,"is_not", 2, 2, &a1, &a2)) { + result = (a1 != a2) ? Py_True : Py_False; + Py_INCREF(result); + } + return result; } #undef spam1 @@ -161,10 +161,10 @@ #undef spam1o #define spam1(OP,DOC) {#OP, OP, METH_VARARGS, PyDoc_STR(DOC)}, #define spam2(OP,ALTOP,DOC) {#OP, op_##OP, METH_VARARGS, PyDoc_STR(DOC)}, \ - {#ALTOP, op_##OP, METH_VARARGS, PyDoc_STR(DOC)}, + {#ALTOP, op_##OP, METH_VARARGS, PyDoc_STR(DOC)}, #define spam1o(OP,DOC) {#OP, OP, METH_O, PyDoc_STR(DOC)}, #define spam2o(OP,ALTOP,DOC) {#OP, op_##OP, METH_O, PyDoc_STR(DOC)}, \ - {#ALTOP, op_##OP, METH_O, PyDoc_STR(DOC)}, + {#ALTOP, op_##OP, METH_O, PyDoc_STR(DOC)}, static struct PyMethodDef operator_methods[] = { @@ -227,16 +227,16 @@ spam2(gt,__gt__, "gt(a, b) -- Same as a>b.") spam2(ge,__ge__, "ge(a, b) -- Same as a>=b.") - {NULL, NULL} /* sentinel */ + {NULL, NULL} /* sentinel */ }; /* itemgetter object **********************************************************/ typedef struct { - PyObject_HEAD - Py_ssize_t nitems; - PyObject *item; + PyObject_HEAD + Py_ssize_t nitems; + PyObject *item; } itemgetterobject; static PyTypeObject itemgetter_type; @@ -244,77 +244,77 @@ static PyObject * itemgetter_new(PyTypeObject *type, PyObject *args, PyObject *kwds) { - itemgetterobject *ig; - PyObject *item; - Py_ssize_t nitems; - - if (!_PyArg_NoKeywords("itemgetter()", kwds)) - return NULL; - - nitems = PyTuple_GET_SIZE(args); - if (nitems <= 1) { - if (!PyArg_UnpackTuple(args, "itemgetter", 1, 1, &item)) - return NULL; - } else - item = args; - - /* create itemgetterobject structure */ - ig = PyObject_GC_New(itemgetterobject, &itemgetter_type); - if (ig == NULL) - return NULL; - - Py_INCREF(item); - ig->item = item; - ig->nitems = nitems; + itemgetterobject *ig; + PyObject *item; + Py_ssize_t nitems; + + if (!_PyArg_NoKeywords("itemgetter()", kwds)) + return NULL; + + nitems = PyTuple_GET_SIZE(args); + if (nitems <= 1) { + if (!PyArg_UnpackTuple(args, "itemgetter", 1, 1, &item)) + return NULL; + } else + item = args; + + /* create itemgetterobject structure */ + ig = PyObject_GC_New(itemgetterobject, &itemgetter_type); + if (ig == NULL) + return NULL; + + Py_INCREF(item); + ig->item = item; + ig->nitems = nitems; - PyObject_GC_Track(ig); - return (PyObject *)ig; + PyObject_GC_Track(ig); + return (PyObject *)ig; } static void itemgetter_dealloc(itemgetterobject *ig) { - PyObject_GC_UnTrack(ig); - Py_XDECREF(ig->item); - PyObject_GC_Del(ig); + PyObject_GC_UnTrack(ig); + Py_XDECREF(ig->item); + PyObject_GC_Del(ig); } static int itemgetter_traverse(itemgetterobject *ig, visitproc visit, void *arg) { - Py_VISIT(ig->item); - return 0; + Py_VISIT(ig->item); + return 0; } static PyObject * itemgetter_call(itemgetterobject *ig, PyObject *args, PyObject *kw) { - PyObject *obj, *result; - Py_ssize_t i, nitems=ig->nitems; + PyObject *obj, *result; + Py_ssize_t i, nitems=ig->nitems; - if (!PyArg_UnpackTuple(args, "itemgetter", 1, 1, &obj)) - return NULL; - if (nitems == 1) - return PyObject_GetItem(obj, ig->item); - - assert(PyTuple_Check(ig->item)); - assert(PyTuple_GET_SIZE(ig->item) == nitems); - - result = PyTuple_New(nitems); - if (result == NULL) - return NULL; - - for (i=0 ; i < nitems ; i++) { - PyObject *item, *val; - item = PyTuple_GET_ITEM(ig->item, i); - val = PyObject_GetItem(obj, item); - if (val == NULL) { - Py_DECREF(result); - return NULL; - } - PyTuple_SET_ITEM(result, i, val); - } - return result; + if (!PyArg_UnpackTuple(args, "itemgetter", 1, 1, &obj)) + return NULL; + if (nitems == 1) + return PyObject_GetItem(obj, ig->item); + + assert(PyTuple_Check(ig->item)); + assert(PyTuple_GET_SIZE(ig->item) == nitems); + + result = PyTuple_New(nitems); + if (result == NULL) + return NULL; + + for (i=0 ; i < nitems ; i++) { + PyObject *item, *val; + item = PyTuple_GET_ITEM(ig->item, i); + val = PyObject_GetItem(obj, item); + if (val == NULL) { + Py_DECREF(result); + return NULL; + } + PyTuple_SET_ITEM(result, i, val); + } + return result; } PyDoc_STRVAR(itemgetter_doc, @@ -325,55 +325,55 @@ After, g=itemgetter(2,5,3), the call g(r) returns (r[2], r[5], r[3])"); static PyTypeObject itemgetter_type = { - PyVarObject_HEAD_INIT(NULL, 0) - "operator.itemgetter", /* tp_name */ - sizeof(itemgetterobject), /* tp_basicsize */ - 0, /* tp_itemsize */ - /* methods */ - (destructor)itemgetter_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 */ - (ternaryfunc)itemgetter_call, /* 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 */ - itemgetter_doc, /* tp_doc */ - (traverseproc)itemgetter_traverse, /* tp_traverse */ - 0, /* tp_clear */ - 0, /* tp_richcompare */ - 0, /* tp_weaklistoffset */ - 0, /* tp_iter */ - 0, /* tp_iternext */ - 0, /* tp_methods */ - 0, /* tp_members */ - 0, /* tp_getset */ - 0, /* tp_base */ - 0, /* tp_dict */ - 0, /* tp_descr_get */ - 0, /* tp_descr_set */ - 0, /* tp_dictoffset */ - 0, /* tp_init */ - 0, /* tp_alloc */ - itemgetter_new, /* tp_new */ - 0, /* tp_free */ + PyVarObject_HEAD_INIT(NULL, 0) + "operator.itemgetter", /* tp_name */ + sizeof(itemgetterobject), /* tp_basicsize */ + 0, /* tp_itemsize */ + /* methods */ + (destructor)itemgetter_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 */ + (ternaryfunc)itemgetter_call, /* 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 */ + itemgetter_doc, /* tp_doc */ + (traverseproc)itemgetter_traverse, /* tp_traverse */ + 0, /* tp_clear */ + 0, /* tp_richcompare */ + 0, /* tp_weaklistoffset */ + 0, /* tp_iter */ + 0, /* tp_iternext */ + 0, /* tp_methods */ + 0, /* tp_members */ + 0, /* tp_getset */ + 0, /* tp_base */ + 0, /* tp_dict */ + 0, /* tp_descr_get */ + 0, /* tp_descr_set */ + 0, /* tp_dictoffset */ + 0, /* tp_init */ + 0, /* tp_alloc */ + itemgetter_new, /* tp_new */ + 0, /* tp_free */ }; /* attrgetter object **********************************************************/ typedef struct { - PyObject_HEAD - Py_ssize_t nattrs; - PyObject *attr; + PyObject_HEAD + Py_ssize_t nattrs; + PyObject *attr; } attrgetterobject; static PyTypeObject attrgetter_type; @@ -381,112 +381,112 @@ static PyObject * attrgetter_new(PyTypeObject *type, PyObject *args, PyObject *kwds) { - attrgetterobject *ag; - PyObject *attr; - Py_ssize_t nattrs; - - if (!_PyArg_NoKeywords("attrgetter()", kwds)) - return NULL; - - nattrs = PyTuple_GET_SIZE(args); - if (nattrs <= 1) { - if (!PyArg_UnpackTuple(args, "attrgetter", 1, 1, &attr)) - return NULL; - } else - attr = args; - - /* create attrgetterobject structure */ - ag = PyObject_GC_New(attrgetterobject, &attrgetter_type); - if (ag == NULL) - return NULL; - - Py_INCREF(attr); - ag->attr = attr; - ag->nattrs = nattrs; + attrgetterobject *ag; + PyObject *attr; + Py_ssize_t nattrs; + + if (!_PyArg_NoKeywords("attrgetter()", kwds)) + return NULL; + + nattrs = PyTuple_GET_SIZE(args); + if (nattrs <= 1) { + if (!PyArg_UnpackTuple(args, "attrgetter", 1, 1, &attr)) + return NULL; + } else + attr = args; + + /* create attrgetterobject structure */ + ag = PyObject_GC_New(attrgetterobject, &attrgetter_type); + if (ag == NULL) + return NULL; + + Py_INCREF(attr); + ag->attr = attr; + ag->nattrs = nattrs; - PyObject_GC_Track(ag); - return (PyObject *)ag; + PyObject_GC_Track(ag); + return (PyObject *)ag; } static void attrgetter_dealloc(attrgetterobject *ag) { - PyObject_GC_UnTrack(ag); - Py_XDECREF(ag->attr); - PyObject_GC_Del(ag); + PyObject_GC_UnTrack(ag); + Py_XDECREF(ag->attr); + PyObject_GC_Del(ag); } static int attrgetter_traverse(attrgetterobject *ag, visitproc visit, void *arg) { - Py_VISIT(ag->attr); - return 0; + Py_VISIT(ag->attr); + return 0; } static PyObject * dotted_getattr(PyObject *obj, PyObject *attr) { - char *s, *p; + char *s, *p; - if (!PyUnicode_Check(attr)) { - PyErr_SetString(PyExc_TypeError, - "attribute name must be a string"); - return NULL; - } - - s = _PyUnicode_AsString(attr); - Py_INCREF(obj); - for (;;) { - PyObject *newobj, *str; - p = strchr(s, '.'); - str = p ? PyUnicode_FromStringAndSize(s, (p-s)) : - PyUnicode_FromString(s); - if (str == NULL) { - Py_DECREF(obj); - return NULL; - } - newobj = PyObject_GetAttr(obj, str); - Py_DECREF(str); - Py_DECREF(obj); - if (newobj == NULL) - return NULL; - obj = newobj; - if (p == NULL) break; - s = p+1; - } + if (!PyUnicode_Check(attr)) { + PyErr_SetString(PyExc_TypeError, + "attribute name must be a string"); + return NULL; + } + + s = _PyUnicode_AsString(attr); + Py_INCREF(obj); + for (;;) { + PyObject *newobj, *str; + p = strchr(s, '.'); + str = p ? PyUnicode_FromStringAndSize(s, (p-s)) : + PyUnicode_FromString(s); + if (str == NULL) { + Py_DECREF(obj); + return NULL; + } + newobj = PyObject_GetAttr(obj, str); + Py_DECREF(str); + Py_DECREF(obj); + if (newobj == NULL) + return NULL; + obj = newobj; + if (p == NULL) break; + s = p+1; + } - return obj; + return obj; } static PyObject * attrgetter_call(attrgetterobject *ag, PyObject *args, PyObject *kw) { - PyObject *obj, *result; - Py_ssize_t i, nattrs=ag->nattrs; + PyObject *obj, *result; + Py_ssize_t i, nattrs=ag->nattrs; - if (!PyArg_UnpackTuple(args, "attrgetter", 1, 1, &obj)) - return NULL; - if (ag->nattrs == 1) - return dotted_getattr(obj, ag->attr); - - assert(PyTuple_Check(ag->attr)); - assert(PyTuple_GET_SIZE(ag->attr) == nattrs); - - result = PyTuple_New(nattrs); - if (result == NULL) - return NULL; - - for (i=0 ; i < nattrs ; i++) { - PyObject *attr, *val; - attr = PyTuple_GET_ITEM(ag->attr, i); - val = dotted_getattr(obj, attr); - if (val == NULL) { - Py_DECREF(result); - return NULL; - } - PyTuple_SET_ITEM(result, i, val); - } - return result; + if (!PyArg_UnpackTuple(args, "attrgetter", 1, 1, &obj)) + return NULL; + if (ag->nattrs == 1) + return dotted_getattr(obj, ag->attr); + + assert(PyTuple_Check(ag->attr)); + assert(PyTuple_GET_SIZE(ag->attr) == nattrs); + + result = PyTuple_New(nattrs); + if (result == NULL) + return NULL; + + for (i=0 ; i < nattrs ; i++) { + PyObject *attr, *val; + attr = PyTuple_GET_ITEM(ag->attr, i); + val = dotted_getattr(obj, attr); + if (val == NULL) { + Py_DECREF(result); + return NULL; + } + PyTuple_SET_ITEM(result, i, val); + } + return result; } PyDoc_STRVAR(attrgetter_doc, @@ -499,56 +499,56 @@ (r.name.first, r.name.last)."); static PyTypeObject attrgetter_type = { - PyVarObject_HEAD_INIT(NULL, 0) - "operator.attrgetter", /* tp_name */ - sizeof(attrgetterobject), /* tp_basicsize */ - 0, /* tp_itemsize */ - /* methods */ - (destructor)attrgetter_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 */ - (ternaryfunc)attrgetter_call, /* 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 */ - attrgetter_doc, /* tp_doc */ - (traverseproc)attrgetter_traverse, /* tp_traverse */ - 0, /* tp_clear */ - 0, /* tp_richcompare */ - 0, /* tp_weaklistoffset */ - 0, /* tp_iter */ - 0, /* tp_iternext */ - 0, /* tp_methods */ - 0, /* tp_members */ - 0, /* tp_getset */ - 0, /* tp_base */ - 0, /* tp_dict */ - 0, /* tp_descr_get */ - 0, /* tp_descr_set */ - 0, /* tp_dictoffset */ - 0, /* tp_init */ - 0, /* tp_alloc */ - attrgetter_new, /* tp_new */ - 0, /* tp_free */ + PyVarObject_HEAD_INIT(NULL, 0) + "operator.attrgetter", /* tp_name */ + sizeof(attrgetterobject), /* tp_basicsize */ + 0, /* tp_itemsize */ + /* methods */ + (destructor)attrgetter_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 */ + (ternaryfunc)attrgetter_call, /* 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 */ + attrgetter_doc, /* tp_doc */ + (traverseproc)attrgetter_traverse, /* tp_traverse */ + 0, /* tp_clear */ + 0, /* tp_richcompare */ + 0, /* tp_weaklistoffset */ + 0, /* tp_iter */ + 0, /* tp_iternext */ + 0, /* tp_methods */ + 0, /* tp_members */ + 0, /* tp_getset */ + 0, /* tp_base */ + 0, /* tp_dict */ + 0, /* tp_descr_get */ + 0, /* tp_descr_set */ + 0, /* tp_dictoffset */ + 0, /* tp_init */ + 0, /* tp_alloc */ + attrgetter_new, /* tp_new */ + 0, /* tp_free */ }; /* methodcaller object **********************************************************/ typedef struct { - PyObject_HEAD - PyObject *name; - PyObject *args; - PyObject *kwds; + PyObject_HEAD + PyObject *name; + PyObject *args; + PyObject *kwds; } methodcallerobject; static PyTypeObject methodcaller_type; @@ -556,69 +556,69 @@ static PyObject * methodcaller_new(PyTypeObject *type, PyObject *args, PyObject *kwds) { - methodcallerobject *mc; - PyObject *name, *newargs; + methodcallerobject *mc; + PyObject *name, *newargs; - if (PyTuple_GET_SIZE(args) < 1) { - PyErr_SetString(PyExc_TypeError, "methodcaller needs at least " - "one argument, the method name"); - return NULL; - } - - /* create methodcallerobject structure */ - mc = PyObject_GC_New(methodcallerobject, &methodcaller_type); - if (mc == NULL) - return NULL; - - newargs = PyTuple_GetSlice(args, 1, PyTuple_GET_SIZE(args)); - if (newargs == NULL) { - Py_DECREF(mc); - return NULL; - } - mc->args = newargs; - - name = PyTuple_GET_ITEM(args, 0); - Py_INCREF(name); - mc->name = name; + if (PyTuple_GET_SIZE(args) < 1) { + PyErr_SetString(PyExc_TypeError, "methodcaller needs at least " + "one argument, the method name"); + return NULL; + } + + /* create methodcallerobject structure */ + mc = PyObject_GC_New(methodcallerobject, &methodcaller_type); + if (mc == NULL) + return NULL; + + newargs = PyTuple_GetSlice(args, 1, PyTuple_GET_SIZE(args)); + if (newargs == NULL) { + Py_DECREF(mc); + return NULL; + } + mc->args = newargs; + + name = PyTuple_GET_ITEM(args, 0); + Py_INCREF(name); + mc->name = name; - Py_XINCREF(kwds); - mc->kwds = kwds; + Py_XINCREF(kwds); + mc->kwds = kwds; - PyObject_GC_Track(mc); - return (PyObject *)mc; + PyObject_GC_Track(mc); + return (PyObject *)mc; } static void methodcaller_dealloc(methodcallerobject *mc) { - PyObject_GC_UnTrack(mc); - Py_XDECREF(mc->name); - Py_XDECREF(mc->args); - Py_XDECREF(mc->kwds); - PyObject_GC_Del(mc); + PyObject_GC_UnTrack(mc); + Py_XDECREF(mc->name); + Py_XDECREF(mc->args); + Py_XDECREF(mc->kwds); + PyObject_GC_Del(mc); } static int methodcaller_traverse(methodcallerobject *mc, visitproc visit, void *arg) { - Py_VISIT(mc->args); - Py_VISIT(mc->kwds); - return 0; + Py_VISIT(mc->args); + Py_VISIT(mc->kwds); + return 0; } static PyObject * methodcaller_call(methodcallerobject *mc, PyObject *args, PyObject *kw) { - PyObject *method, *obj, *result; + PyObject *method, *obj, *result; - if (!PyArg_UnpackTuple(args, "methodcaller", 1, 1, &obj)) - return NULL; - method = PyObject_GetAttr(obj, mc->name); - if (method == NULL) - return NULL; - result = PyObject_Call(method, mc->args, mc->kwds); - Py_DECREF(method); - return result; + if (!PyArg_UnpackTuple(args, "methodcaller", 1, 1, &obj)) + return NULL; + method = PyObject_GetAttr(obj, mc->name); + if (method == NULL) + return NULL; + result = PyObject_Call(method, mc->args, mc->kwds); + Py_DECREF(method); + return result; } PyDoc_STRVAR(methodcaller_doc, @@ -630,46 +630,46 @@ r.name('date', foo=1)."); static PyTypeObject methodcaller_type = { - PyVarObject_HEAD_INIT(NULL, 0) - "operator.methodcaller", /* tp_name */ - sizeof(methodcallerobject), /* tp_basicsize */ - 0, /* tp_itemsize */ - /* methods */ - (destructor)methodcaller_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 */ - (ternaryfunc)methodcaller_call, /* 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 */ - methodcaller_doc, /* tp_doc */ - (traverseproc)methodcaller_traverse, /* tp_traverse */ - 0, /* tp_clear */ - 0, /* tp_richcompare */ - 0, /* tp_weaklistoffset */ - 0, /* tp_iter */ - 0, /* tp_iternext */ - 0, /* tp_methods */ - 0, /* tp_members */ - 0, /* tp_getset */ - 0, /* tp_base */ - 0, /* tp_dict */ - 0, /* tp_descr_get */ - 0, /* tp_descr_set */ - 0, /* tp_dictoffset */ - 0, /* tp_init */ - 0, /* tp_alloc */ - methodcaller_new, /* tp_new */ - 0, /* tp_free */ + PyVarObject_HEAD_INIT(NULL, 0) + "operator.methodcaller", /* tp_name */ + sizeof(methodcallerobject), /* tp_basicsize */ + 0, /* tp_itemsize */ + /* methods */ + (destructor)methodcaller_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 */ + (ternaryfunc)methodcaller_call, /* 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 */ + methodcaller_doc, /* tp_doc */ + (traverseproc)methodcaller_traverse, /* tp_traverse */ + 0, /* tp_clear */ + 0, /* tp_richcompare */ + 0, /* tp_weaklistoffset */ + 0, /* tp_iter */ + 0, /* tp_iternext */ + 0, /* tp_methods */ + 0, /* tp_members */ + 0, /* tp_getset */ + 0, /* tp_base */ + 0, /* tp_dict */ + 0, /* tp_descr_get */ + 0, /* tp_descr_set */ + 0, /* tp_dictoffset */ + 0, /* tp_init */ + 0, /* tp_alloc */ + methodcaller_new, /* tp_new */ + 0, /* tp_free */ }; @@ -677,40 +677,40 @@ static struct PyModuleDef operatormodule = { - PyModuleDef_HEAD_INIT, - "operator", - operator_doc, - -1, - operator_methods, - NULL, - NULL, - NULL, - NULL + PyModuleDef_HEAD_INIT, + "operator", + operator_doc, + -1, + operator_methods, + NULL, + NULL, + NULL, + NULL }; PyMODINIT_FUNC PyInit_operator(void) { - PyObject *m; - - /* Create the module and add the functions */ - m = PyModule_Create(&operatormodule); - if (m == NULL) - return NULL; - - if (PyType_Ready(&itemgetter_type) < 0) - return NULL; - Py_INCREF(&itemgetter_type); - PyModule_AddObject(m, "itemgetter", (PyObject *)&itemgetter_type); - - if (PyType_Ready(&attrgetter_type) < 0) - return NULL; - Py_INCREF(&attrgetter_type); - PyModule_AddObject(m, "attrgetter", (PyObject *)&attrgetter_type); - - if (PyType_Ready(&methodcaller_type) < 0) - return NULL; - Py_INCREF(&methodcaller_type); - PyModule_AddObject(m, "methodcaller", (PyObject *)&methodcaller_type); - return m; + PyObject *m; + + /* Create the module and add the functions */ + m = PyModule_Create(&operatormodule); + if (m == NULL) + return NULL; + + if (PyType_Ready(&itemgetter_type) < 0) + return NULL; + Py_INCREF(&itemgetter_type); + PyModule_AddObject(m, "itemgetter", (PyObject *)&itemgetter_type); + + if (PyType_Ready(&attrgetter_type) < 0) + return NULL; + Py_INCREF(&attrgetter_type); + PyModule_AddObject(m, "attrgetter", (PyObject *)&attrgetter_type); + + if (PyType_Ready(&methodcaller_type) < 0) + return NULL; + Py_INCREF(&methodcaller_type); + PyModule_AddObject(m, "methodcaller", (PyObject *)&methodcaller_type); + return m; } Modified: python/branches/py3k/Modules/ossaudiodev.c ============================================================================== --- python/branches/py3k/Modules/ossaudiodev.c (original) +++ python/branches/py3k/Modules/ossaudiodev.c Sun May 9 17:52:27 2010 @@ -809,8 +809,8 @@ PyObject * rval = NULL; if (PyUnicode_Check(nameobj)) - name = _PyUnicode_AsString(nameobj); - + name = _PyUnicode_AsString(nameobj); + if (strcmp(name, "closed") == 0) { rval = (self->fd == -1) ? Py_True : Py_False; Py_INCREF(rval); @@ -975,15 +975,15 @@ static struct PyModuleDef ossaudiodevmodule = { - PyModuleDef_HEAD_INIT, - "ossaudiodev", - NULL, - -1, - ossaudiodev_methods, - NULL, - NULL, - NULL, - NULL + PyModuleDef_HEAD_INIT, + "ossaudiodev", + NULL, + -1, + ossaudiodev_methods, + NULL, + NULL, + NULL, + NULL }; PyMODINIT_FUNC @@ -999,10 +999,10 @@ m = PyModule_Create(&ossaudiodevmodule); if (m == NULL) - return NULL; + return NULL; OSSAudioError = PyErr_NewException("ossaudiodev.OSSAudioError", - NULL, NULL); + NULL, NULL); if (OSSAudioError) { /* Each call to PyModule_AddObject decrefs it; compensate: */ Py_INCREF(OSSAudioError); Modified: python/branches/py3k/Modules/parsermodule.c ============================================================================== --- python/branches/py3k/Modules/parsermodule.c (original) +++ python/branches/py3k/Modules/parsermodule.c Sun May 9 17:52:27 2010 @@ -578,8 +578,8 @@ ? eval_input : file_input, &err, &flags); - if (n) { - res = parser_newstobject(n, type); + if (n) { + res = parser_newstobject(n, type); if (res) ((PyST_Object *)res)->st_flags.cf_flags = flags & PyCF_MASK; } @@ -784,7 +784,7 @@ PyErr_Format(parser_error, "third item in terminal node must be an" " integer, found %s", - Py_TYPE(temp)->tp_name); + Py_TYPE(temp)->tp_name); Py_DECREF(o); Py_DECREF(temp); Py_DECREF(elem); @@ -1051,7 +1051,7 @@ { int nch = NCH(tree); int res = (validate_ntype(tree, classdef) && - ((nch == 4) || (nch == 6) || (nch == 7))); + ((nch == 4) || (nch == 6) || (nch == 7))); if (res) { res = (validate_name(CHILD(tree, 0), "class") @@ -1064,15 +1064,15 @@ } if (res) { - if (nch == 7) { - res = ((validate_lparen(CHILD(tree, 2)) && - validate_arglist(CHILD(tree, 3)) && - validate_rparen(CHILD(tree, 4)))); - } - else if (nch == 6) { - res = (validate_lparen(CHILD(tree,2)) && - validate_rparen(CHILD(tree,3))); - } + if (nch == 7) { + res = ((validate_lparen(CHILD(tree, 2)) && + validate_arglist(CHILD(tree, 3)) && + validate_rparen(CHILD(tree, 4)))); + } + else if (nch == 6) { + res = (validate_lparen(CHILD(tree,2)) && + validate_rparen(CHILD(tree,3))); + } } return (res); } @@ -1244,10 +1244,10 @@ else { /* skip over vfpdef (',' vfpdef ['=' test])* */ i = start + 1; - if (TYPE(CHILD(tree, i)) == vfpdef || - TYPE(CHILD(tree, i)) == tfpdef) { /* skip over vfpdef or tfpdef */ - i += 1; - } + if (TYPE(CHILD(tree, i)) == vfpdef || + TYPE(CHILD(tree, i)) == tfpdef) { /* skip over vfpdef or tfpdef */ + i += 1; + } while (res && i+1 < nch) { /* validate (',' vfpdef ['=' test])* */ res = validate_comma(CHILD(tree, i)); if (TYPE(CHILD(tree, i+1)) == DOUBLESTAR) @@ -1718,14 +1718,14 @@ static int validate_dotted_as_names(node *tree) { - int nch = NCH(tree); - int res = is_odd(nch) && validate_dotted_as_name(CHILD(tree, 0)); - int i; - - for (i = 1; res && (i < nch); i += 2) - res = (validate_comma(CHILD(tree, i)) - && validate_dotted_as_name(CHILD(tree, i + 1))); - return (res); + int nch = NCH(tree); + int res = is_odd(nch) && validate_dotted_as_name(CHILD(tree, 0)); + int i; + + for (i = 1; res && (i < nch); i += 2) + res = (validate_comma(CHILD(tree, i)) + && validate_dotted_as_name(CHILD(tree, i + 1))); + return (res); } @@ -1738,8 +1738,8 @@ int i; for (i = 1; res && (i + 1 < nch); i += 2) - res = (validate_comma(CHILD(tree, i)) - && validate_import_as_name(CHILD(tree, i + 1))); + res = (validate_comma(CHILD(tree, i)) + && validate_import_as_name(CHILD(tree, i + 1))); return (res); } @@ -1748,10 +1748,10 @@ static int validate_import_name(node *tree) { - return (validate_ntype(tree, import_name) - && validate_numnodes(tree, 2, "import_name") - && validate_name(CHILD(tree, 0), "import") - && validate_dotted_as_names(CHILD(tree, 1))); + return (validate_ntype(tree, import_name) + && validate_numnodes(tree, 2, "import_name") + && validate_name(CHILD(tree, 0), "import") + && validate_dotted_as_names(CHILD(tree, 1))); } /* Helper function to count the number of leading dots in @@ -1762,8 +1762,8 @@ { int i; for (i = 1; i < NCH(tree); i++) - if (TYPE(CHILD(tree, i)) != DOT) - break; + if (TYPE(CHILD(tree, i)) != DOT) + break; return i-1; } @@ -1773,24 +1773,24 @@ static int validate_import_from(node *tree) { - int nch = NCH(tree); - int ndots = count_from_dots(tree); - int havename = (TYPE(CHILD(tree, ndots + 1)) == dotted_name); - int offset = ndots + havename; - int res = validate_ntype(tree, import_from) - && (nch >= 4 + ndots) - && validate_name(CHILD(tree, 0), "from") - && (!havename || validate_dotted_name(CHILD(tree, ndots + 1))) - && validate_name(CHILD(tree, offset + 1), "import"); - - if (res && TYPE(CHILD(tree, offset + 2)) == LPAR) - res = ((nch == offset + 5) - && validate_lparen(CHILD(tree, offset + 2)) - && validate_import_as_names(CHILD(tree, offset + 3)) - && validate_rparen(CHILD(tree, offset + 4))); - else if (res && TYPE(CHILD(tree, offset + 2)) != STAR) - res = validate_import_as_names(CHILD(tree, offset + 2)); - return (res); + int nch = NCH(tree); + int ndots = count_from_dots(tree); + int havename = (TYPE(CHILD(tree, ndots + 1)) == dotted_name); + int offset = ndots + havename; + int res = validate_ntype(tree, import_from) + && (nch >= 4 + ndots) + && validate_name(CHILD(tree, 0), "from") + && (!havename || validate_dotted_name(CHILD(tree, ndots + 1))) + && validate_name(CHILD(tree, offset + 1), "import"); + + if (res && TYPE(CHILD(tree, offset + 2)) == LPAR) + res = ((nch == offset + 5) + && validate_lparen(CHILD(tree, offset + 2)) + && validate_import_as_names(CHILD(tree, offset + 3)) + && validate_rparen(CHILD(tree, offset + 4))); + else if (res && TYPE(CHILD(tree, offset + 2)) != STAR) + res = validate_import_as_names(CHILD(tree, offset + 2)); + return (res); } @@ -1802,9 +1802,9 @@ int res = validate_numnodes(tree, 1, "import_stmt"); if (res) { - int ntype = TYPE(CHILD(tree, 0)); + int ntype = TYPE(CHILD(tree, 0)); - if (ntype == import_name || ntype == import_from) + if (ntype == import_name || ntype == import_from) res = validate_node(CHILD(tree, 0)); else { res = 0; @@ -2323,11 +2323,11 @@ && (validate_rparen(CHILD(tree, nch - 1)))); if (res && (nch == 3)) { - if (TYPE(CHILD(tree, 1))==yield_expr) - res = validate_yield_expr(CHILD(tree, 1)); - else - res = validate_testlist_comp(CHILD(tree, 1)); - } + if (TYPE(CHILD(tree, 1))==yield_expr) + res = validate_yield_expr(CHILD(tree, 1)); + else + res = validate_testlist_comp(CHILD(tree, 1)); + } break; case LSQB: if (nch == 2) @@ -2355,11 +2355,11 @@ for (pos = 1; res && (pos < nch); ++pos) res = validate_ntype(CHILD(tree, pos), STRING); break; - case DOT: - res = (nch == 3 && - validate_ntype(CHILD(tree, 1), DOT) && - validate_ntype(CHILD(tree, 2), DOT)); - break; + case DOT: + res = (nch == 3 && + validate_ntype(CHILD(tree, 1), DOT) && + validate_ntype(CHILD(tree, 2), DOT)); + break; default: res = 0; break; @@ -2416,17 +2416,17 @@ int ok; int nch = NCH(tree); ok = (validate_ntype(tree, decorator) && - (nch == 3 || nch == 5 || nch == 6) && - validate_at(CHILD(tree, 0)) && - validate_dotted_name(CHILD(tree, 1)) && - validate_newline(RCHILD(tree, -1))); + (nch == 3 || nch == 5 || nch == 6) && + validate_at(CHILD(tree, 0)) && + validate_dotted_name(CHILD(tree, 1)) && + validate_newline(RCHILD(tree, -1))); if (ok && nch != 3) { - ok = (validate_lparen(CHILD(tree, 2)) && - validate_rparen(RCHILD(tree, -2))); + ok = (validate_lparen(CHILD(tree, 2)) && + validate_rparen(RCHILD(tree, -2))); - if (ok && nch == 6) - ok = validate_arglist(CHILD(tree, 3)); + if (ok && nch == 6) + ok = validate_arglist(CHILD(tree, 3)); } return ok; @@ -2443,7 +2443,7 @@ ok = validate_ntype(tree, decorators) && nch >= 1; for (i = 0; ok && i < nch; ++i) - ok = validate_decorator(CHILD(tree, i)); + ok = validate_decorator(CHILD(tree, i)); return ok; } @@ -2458,7 +2458,7 @@ int ok = (validate_ntype(tree, with_item) && (nch == 1 || nch == 3) && validate_test(CHILD(tree, 0))); - if (ok && nch == 3) + if (ok && nch == 3) ok = (validate_name(CHILD(tree, 1), "as") && validate_expr(CHILD(tree, 2))); return ok; @@ -2493,12 +2493,12 @@ { int nch = NCH(tree); int ok = (validate_ntype(tree, funcdef) - && (nch == 5) - && validate_name(RCHILD(tree, -5), "def") - && validate_ntype(RCHILD(tree, -4), NAME) - && validate_colon(RCHILD(tree, -2)) - && validate_parameters(RCHILD(tree, -3)) - && validate_suite(RCHILD(tree, -1))); + && (nch == 5) + && validate_name(RCHILD(tree, -5), "def") + && validate_ntype(RCHILD(tree, -4), NAME) + && validate_colon(RCHILD(tree, -2)) + && validate_parameters(RCHILD(tree, -3)) + && validate_suite(RCHILD(tree, -1))); return ok; } @@ -2511,11 +2511,11 @@ { int nch = NCH(tree); int ok = (validate_ntype(tree, decorated) - && (nch == 2) - && validate_decorators(RCHILD(tree, -2)) - && (validate_funcdef(RCHILD(tree, -1)) - || validate_class(RCHILD(tree, -1))) - ); + && (nch == 2) + && validate_decorators(RCHILD(tree, -2)) + && (validate_funcdef(RCHILD(tree, -1)) + || validate_class(RCHILD(tree, -1))) + ); return ok; } @@ -2882,9 +2882,9 @@ case classdef: res = validate_class(tree); break; - case decorated: - res = validate_decorated(tree); - break; + case decorated: + res = validate_decorated(tree); + break; /* * "Trivial" parse tree nodes. * (Why did I call these trivial?) @@ -2953,12 +2953,12 @@ case import_stmt: res = validate_import_stmt(tree); break; - case import_name: - res = validate_import_name(tree); - break; - case import_from: - res = validate_import_from(tree); - break; + case import_name: + res = validate_import_name(tree); + break; + case import_from: + res = validate_import_from(tree); + break; case global_stmt: res = validate_global_stmt(tree); break; @@ -3170,15 +3170,15 @@ static struct PyModuleDef parsermodule = { - PyModuleDef_HEAD_INIT, - "parser", - NULL, - -1, - parser_functions, - NULL, - NULL, - NULL, - NULL + PyModuleDef_HEAD_INIT, + "parser", + NULL, + -1, + parser_functions, + NULL, + NULL, + NULL, + NULL }; PyMODINIT_FUNC PyInit_parser(void); /* supply a prototype */ @@ -3192,7 +3192,7 @@ return NULL; module = PyModule_Create(&parsermodule); if (module == NULL) - return NULL; + return NULL; if (parser_error == 0) parser_error = PyErr_NewException("parser.ParserError", NULL, NULL); Modified: python/branches/py3k/Modules/pwdmodule.c ============================================================================== --- python/branches/py3k/Modules/pwdmodule.c (original) +++ python/branches/py3k/Modules/pwdmodule.c Sun May 9 17:52:27 2010 @@ -8,14 +8,14 @@ #include static PyStructSequence_Field struct_pwd_type_fields[] = { - {"pw_name", "user name"}, - {"pw_passwd", "password"}, - {"pw_uid", "user id"}, - {"pw_gid", "group id"}, - {"pw_gecos", "real name"}, - {"pw_dir", "home directory"}, - {"pw_shell", "shell program"}, - {0} + {"pw_name", "user name"}, + {"pw_passwd", "password"}, + {"pw_uid", "user id"}, + {"pw_gid", "group id"}, + {"pw_gecos", "real name"}, + {"pw_dir", "home directory"}, + {"pw_shell", "shell program"}, + {0} }; PyDoc_STRVAR(struct_passwd__doc__, @@ -25,10 +25,10 @@ or via the object attributes as named in the above tuple."); static PyStructSequence_Desc struct_pwd_type_desc = { - "pwd.struct_passwd", - struct_passwd__doc__, - struct_pwd_type_fields, - 7, + "pwd.struct_passwd", + struct_passwd__doc__, + struct_pwd_type_fields, + 7, }; PyDoc_STRVAR(pwd__doc__, @@ -41,7 +41,7 @@ The uid and gid items are integers, all others are strings. An\n\ exception is raised if the entry asked for cannot be found."); - + static int initialized; static PyTypeObject StructPwdType; @@ -49,51 +49,51 @@ sets(PyObject *v, int i, const char* val) { if (val) { - PyObject *o = PyUnicode_DecodeFSDefault(val); - PyStructSequence_SET_ITEM(v, i, o); + PyObject *o = PyUnicode_DecodeFSDefault(val); + PyStructSequence_SET_ITEM(v, i, o); } else { - PyStructSequence_SET_ITEM(v, i, Py_None); - Py_INCREF(Py_None); + PyStructSequence_SET_ITEM(v, i, Py_None); + Py_INCREF(Py_None); } } static PyObject * mkpwent(struct passwd *p) { - int setIndex = 0; - PyObject *v = PyStructSequence_New(&StructPwdType); - if (v == NULL) - return NULL; + int setIndex = 0; + PyObject *v = PyStructSequence_New(&StructPwdType); + if (v == NULL) + return NULL; #define SETI(i,val) PyStructSequence_SET_ITEM(v, i, PyLong_FromLong((long) val)) #define SETS(i,val) sets(v, i, val) - SETS(setIndex++, p->pw_name); + SETS(setIndex++, p->pw_name); #ifdef __VMS - SETS(setIndex++, ""); + SETS(setIndex++, ""); #else - SETS(setIndex++, p->pw_passwd); + SETS(setIndex++, p->pw_passwd); #endif - SETI(setIndex++, p->pw_uid); - SETI(setIndex++, p->pw_gid); + SETI(setIndex++, p->pw_uid); + SETI(setIndex++, p->pw_gid); #ifdef __VMS - SETS(setIndex++, ""); + SETS(setIndex++, ""); #else - SETS(setIndex++, p->pw_gecos); + SETS(setIndex++, p->pw_gecos); #endif - SETS(setIndex++, p->pw_dir); - SETS(setIndex++, p->pw_shell); + SETS(setIndex++, p->pw_dir); + SETS(setIndex++, p->pw_shell); #undef SETS #undef SETI - if (PyErr_Occurred()) { - Py_XDECREF(v); - return NULL; - } + if (PyErr_Occurred()) { + Py_XDECREF(v); + return NULL; + } - return v; + return v; } PyDoc_STRVAR(pwd_getpwuid__doc__, @@ -105,16 +105,16 @@ static PyObject * pwd_getpwuid(PyObject *self, PyObject *args) { - unsigned int uid; - struct passwd *p; - if (!PyArg_ParseTuple(args, "I:getpwuid", &uid)) - return NULL; - if ((p = getpwuid(uid)) == NULL) { - PyErr_Format(PyExc_KeyError, - "getpwuid(): uid not found: %d", uid); - return NULL; - } - return mkpwent(p); + unsigned int uid; + struct passwd *p; + if (!PyArg_ParseTuple(args, "I:getpwuid", &uid)) + return NULL; + if ((p = getpwuid(uid)) == NULL) { + PyErr_Format(PyExc_KeyError, + "getpwuid(): uid not found: %d", uid); + return NULL; + } + return mkpwent(p); } PyDoc_STRVAR(pwd_getpwnam__doc__, @@ -126,27 +126,27 @@ static PyObject * pwd_getpwnam(PyObject *self, PyObject *args) { - char *name; - struct passwd *p; - PyObject *arg, *bytes, *retval = NULL; - - if (!PyArg_ParseTuple(args, "U:getpwnam", &arg)) - return NULL; - if ((bytes = PyUnicode_AsEncodedString(arg, - Py_FileSystemDefaultEncoding, - "surrogateescape")) == NULL) - return NULL; - if (PyBytes_AsStringAndSize(bytes, &name, NULL) == -1) - goto out; - if ((p = getpwnam(name)) == NULL) { - PyErr_Format(PyExc_KeyError, - "getpwnam(): name not found: %s", name); - goto out; - } - retval = mkpwent(p); + char *name; + struct passwd *p; + PyObject *arg, *bytes, *retval = NULL; + + if (!PyArg_ParseTuple(args, "U:getpwnam", &arg)) + return NULL; + if ((bytes = PyUnicode_AsEncodedString(arg, + Py_FileSystemDefaultEncoding, + "surrogateescape")) == NULL) + return NULL; + if (PyBytes_AsStringAndSize(bytes, &name, NULL) == -1) + goto out; + if ((p = getpwnam(name)) == NULL) { + PyErr_Format(PyExc_KeyError, + "getpwnam(): name not found: %s", name); + goto out; + } + retval = mkpwent(p); out: - Py_DECREF(bytes); - return retval; + Py_DECREF(bytes); + return retval; } #ifdef HAVE_GETPWENT @@ -159,67 +159,67 @@ static PyObject * pwd_getpwall(PyObject *self) { - PyObject *d; - struct passwd *p; - if ((d = PyList_New(0)) == NULL) - return NULL; + PyObject *d; + struct passwd *p; + if ((d = PyList_New(0)) == NULL) + return NULL; #if defined(PYOS_OS2) && defined(PYCC_GCC) - if ((p = getpwuid(0)) != NULL) { + if ((p = getpwuid(0)) != NULL) { #else - setpwent(); - while ((p = getpwent()) != NULL) { + setpwent(); + while ((p = getpwent()) != NULL) { #endif - PyObject *v = mkpwent(p); - if (v == NULL || PyList_Append(d, v) != 0) { - Py_XDECREF(v); - Py_DECREF(d); - endpwent(); - return NULL; - } - Py_DECREF(v); - } - endpwent(); - return d; + PyObject *v = mkpwent(p); + if (v == NULL || PyList_Append(d, v) != 0) { + Py_XDECREF(v); + Py_DECREF(d); + endpwent(); + return NULL; + } + Py_DECREF(v); + } + endpwent(); + return d; } #endif static PyMethodDef pwd_methods[] = { - {"getpwuid", pwd_getpwuid, METH_VARARGS, pwd_getpwuid__doc__}, - {"getpwnam", pwd_getpwnam, METH_VARARGS, pwd_getpwnam__doc__}, + {"getpwuid", pwd_getpwuid, METH_VARARGS, pwd_getpwuid__doc__}, + {"getpwnam", pwd_getpwnam, METH_VARARGS, pwd_getpwnam__doc__}, #ifdef HAVE_GETPWENT - {"getpwall", (PyCFunction)pwd_getpwall, - METH_NOARGS, pwd_getpwall__doc__}, + {"getpwall", (PyCFunction)pwd_getpwall, + METH_NOARGS, pwd_getpwall__doc__}, #endif - {NULL, NULL} /* sentinel */ + {NULL, NULL} /* sentinel */ }; static struct PyModuleDef pwdmodule = { - PyModuleDef_HEAD_INIT, - "pwd", - pwd__doc__, - -1, - pwd_methods, - NULL, - NULL, - NULL, - NULL + PyModuleDef_HEAD_INIT, + "pwd", + pwd__doc__, + -1, + pwd_methods, + NULL, + NULL, + NULL, + NULL }; PyMODINIT_FUNC PyInit_pwd(void) { - PyObject *m; - m = PyModule_Create(&pwdmodule); - if (m == NULL) - return NULL; - - if (!initialized) { - PyStructSequence_InitType(&StructPwdType, - &struct_pwd_type_desc); - initialized = 1; - } - Py_INCREF((PyObject *) &StructPwdType); - PyModule_AddObject(m, "struct_passwd", (PyObject *) &StructPwdType); - return m; + PyObject *m; + m = PyModule_Create(&pwdmodule); + if (m == NULL) + return NULL; + + if (!initialized) { + PyStructSequence_InitType(&StructPwdType, + &struct_pwd_type_desc); + initialized = 1; + } + Py_INCREF((PyObject *) &StructPwdType); + PyModule_AddObject(m, "struct_passwd", (PyObject *) &StructPwdType); + return m; } Modified: python/branches/py3k/Modules/pyexpat.c ============================================================================== --- python/branches/py3k/Modules/pyexpat.c (original) +++ python/branches/py3k/Modules/pyexpat.c Sun May 9 17:52:27 2010 @@ -193,7 +193,7 @@ used only from the character data handler trampoline, and must be used right after `flag_error()` is called. */ static void -noop_character_data_handler(void *userData, const XML_Char *data, int len) +noop_character_data_handler(void *userData, const XML_Char *data, int len) { /* Do nothing. */ } @@ -222,25 +222,25 @@ { int result = 0; if (!tstate->use_tracing || tstate->tracing) - return 0; + return 0; if (tstate->c_profilefunc != NULL) { - tstate->tracing++; - result = tstate->c_profilefunc(tstate->c_profileobj, - f, code , val); - tstate->use_tracing = ((tstate->c_tracefunc != NULL) - || (tstate->c_profilefunc != NULL)); - tstate->tracing--; - if (result) - return result; + tstate->tracing++; + result = tstate->c_profilefunc(tstate->c_profileobj, + f, code , val); + tstate->use_tracing = ((tstate->c_tracefunc != NULL) + || (tstate->c_profilefunc != NULL)); + tstate->tracing--; + if (result) + return result; } if (tstate->c_tracefunc != NULL) { - tstate->tracing++; - result = tstate->c_tracefunc(tstate->c_traceobj, - f, code , val); - tstate->use_tracing = ((tstate->c_tracefunc != NULL) - || (tstate->c_profilefunc != NULL)); - tstate->tracing--; - } + tstate->tracing++; + result = tstate->c_tracefunc(tstate->c_traceobj, + f, code , val); + tstate->use_tracing = ((tstate->c_tracefunc != NULL) + || (tstate->c_profilefunc != NULL)); + tstate->tracing--; + } return result; } @@ -251,12 +251,12 @@ int err; if (tstate->c_tracefunc == NULL) - return 0; + return 0; PyErr_Fetch(&type, &value, &traceback); if (value == NULL) { - value = Py_None; - Py_INCREF(value); + value = Py_None; + Py_INCREF(value); } #if PY_VERSION_HEX < 0x02040000 arg = Py_BuildValue("(OOO)", type, value, traceback); @@ -264,17 +264,17 @@ arg = PyTuple_Pack(3, type, value, traceback); #endif if (arg == NULL) { - PyErr_Restore(type, value, traceback); - return 0; + PyErr_Restore(type, value, traceback); + return 0; } err = trace_frame(tstate, f, PyTrace_EXCEPTION, arg); Py_DECREF(arg); if (err == 0) - PyErr_Restore(type, value, traceback); + PyErr_Restore(type, value, traceback); else { - Py_XDECREF(type); - Py_XDECREF(value); - Py_XDECREF(traceback); + Py_XDECREF(type); + Py_XDECREF(value); + Py_XDECREF(traceback); } return err; } @@ -290,31 +290,31 @@ if (c == NULL) return NULL; - + f = PyFrame_New(tstate, c, PyEval_GetGlobals(), NULL); if (f == NULL) return NULL; tstate->frame = f; #ifdef FIX_TRACE if (trace_frame(tstate, f, PyTrace_CALL, Py_None) < 0) { - return NULL; + return NULL; } #endif res = PyEval_CallObject(func, args); if (res == NULL) { - if (tstate->curexc_traceback == NULL) - PyTraceBack_Here(f); + if (tstate->curexc_traceback == NULL) + PyTraceBack_Here(f); XML_StopParser(self->itself, XML_FALSE); #ifdef FIX_TRACE - if (trace_frame_exc(tstate, f) < 0) { - return NULL; - } + if (trace_frame_exc(tstate, f) < 0) { + return NULL; + } } else { - if (trace_frame(tstate, f, PyTrace_RETURN, res) < 0) { - Py_XDECREF(res); - res = NULL; - } + if (trace_frame(tstate, f, PyTrace_RETURN, res) < 0) { + Py_XDECREF(res); + res = NULL; + } } #else } @@ -331,12 +331,12 @@ PyObject *value; /* result can be NULL if the unicode conversion failed. */ if (!result) - return result; + return result; if (!self->intern) - return result; + return result; value = PyDict_GetItem(self->intern, result); if (!value) { - if (PyDict_SetItem(self->intern, result, result) == 0) + if (PyDict_SetItem(self->intern, result, result) == 0) return result; else return NULL; @@ -396,7 +396,7 @@ } static void -my_CharacterDataHandler(void *userData, const XML_Char *data, int len) +my_CharacterDataHandler(void *userData, const XML_Char *data, int len) { xmlparseobject *self = (xmlparseobject *) userData; if (self->buffer == NULL) @@ -536,13 +536,13 @@ } #define VOID_HANDLER(NAME, PARAMS, PARAM_FORMAT) \ - RC_HANDLER(void, NAME, PARAMS, ;, PARAM_FORMAT, ;, ;,\ - (xmlparseobject *)userData) + RC_HANDLER(void, NAME, PARAMS, ;, PARAM_FORMAT, ;, ;,\ + (xmlparseobject *)userData) #define INT_HANDLER(NAME, PARAMS, PARAM_FORMAT)\ - RC_HANDLER(int, NAME, PARAMS, int rc=0;, PARAM_FORMAT, \ - rc = PyLong_AsLong(rv);, rc, \ - (xmlparseobject *)userData) + RC_HANDLER(int, NAME, PARAMS, int rc=0;, PARAM_FORMAT, \ + rc = PyLong_AsLong(rv);, rc, \ + (xmlparseobject *)userData) VOID_HANDLER(EndElement, (void *userData, const XML_Char *name), @@ -687,25 +687,25 @@ #endif VOID_HANDLER(NotationDecl, - (void *userData, - const XML_Char *notationName, - const XML_Char *base, - const XML_Char *systemId, - const XML_Char *publicId), + (void *userData, + const XML_Char *notationName, + const XML_Char *base, + const XML_Char *systemId, + const XML_Char *publicId), ("(NNNN)", - string_intern(self, notationName), string_intern(self, base), - string_intern(self, systemId), string_intern(self, publicId))) + string_intern(self, notationName), string_intern(self, base), + string_intern(self, systemId), string_intern(self, publicId))) VOID_HANDLER(StartNamespaceDecl, - (void *userData, - const XML_Char *prefix, - const XML_Char *uri), + (void *userData, + const XML_Char *prefix, + const XML_Char *uri), ("(NN)", string_intern(self, prefix), string_intern(self, uri))) VOID_HANDLER(EndNamespaceDecl, - (void *userData, - const XML_Char *prefix), + (void *userData, + const XML_Char *prefix), ("(N)", string_intern(self, prefix))) VOID_HANDLER(Comment, @@ -714,36 +714,36 @@ VOID_HANDLER(StartCdataSection, (void *userData), - ("()")) + ("()")) VOID_HANDLER(EndCdataSection, (void *userData), - ("()")) + ("()")) VOID_HANDLER(Default, - (void *userData, const XML_Char *s, int len), - ("(N)", (conv_string_len_to_unicode(s,len)))) + (void *userData, const XML_Char *s, int len), + ("(N)", (conv_string_len_to_unicode(s,len)))) VOID_HANDLER(DefaultHandlerExpand, - (void *userData, const XML_Char *s, int len), - ("(N)", (conv_string_len_to_unicode(s,len)))) + (void *userData, const XML_Char *s, int len), + ("(N)", (conv_string_len_to_unicode(s,len)))) INT_HANDLER(NotStandalone, - (void *userData), - ("()")) + (void *userData), + ("()")) RC_HANDLER(int, ExternalEntityRef, - (XML_Parser parser, - const XML_Char *context, - const XML_Char *base, - const XML_Char *systemId, - const XML_Char *publicId), - int rc=0;, + (XML_Parser parser, + const XML_Char *context, + const XML_Char *base, + const XML_Char *systemId, + const XML_Char *publicId), + int rc=0;, ("(O&NNN)", - conv_string_to_unicode ,context, string_intern(self, base), - string_intern(self, systemId), string_intern(self, publicId)), - rc = PyLong_AsLong(rv);, rc, - XML_GetUserData(parser)) + conv_string_to_unicode ,context, string_intern(self, base), + string_intern(self, systemId), string_intern(self, publicId)), + rc = PyLong_AsLong(rv);, rc, + XML_GetUserData(parser)) /* XXX UnknownEncodingHandler */ @@ -915,7 +915,7 @@ if (!PyArg_ParseTuple(args, "s:SetBase", &base)) return NULL; if (!XML_SetBase(self->itself, base)) { - return PyErr_NoMemory(); + return PyErr_NoMemory(); } Py_INCREF(Py_None); return Py_None; @@ -1005,7 +1005,7 @@ new_parser->in_callback = 0; new_parser->ns_prefixes = self->ns_prefixes; new_parser->itself = XML_ExternalEntityParserCreate(self->itself, context, - encoding); + encoding); new_parser->handlers = 0; new_parser->intern = self->intern; Py_XINCREF(new_parser->intern); @@ -1096,26 +1096,26 @@ static PyObject *xmlparse_dir(PyObject *self, PyObject* noargs); static struct PyMethodDef xmlparse_methods[] = { - {"Parse", (PyCFunction)xmlparse_Parse, - METH_VARARGS, xmlparse_Parse__doc__}, + {"Parse", (PyCFunction)xmlparse_Parse, + METH_VARARGS, xmlparse_Parse__doc__}, {"ParseFile", (PyCFunction)xmlparse_ParseFile, - METH_O, xmlparse_ParseFile__doc__}, + METH_O, xmlparse_ParseFile__doc__}, {"SetBase", (PyCFunction)xmlparse_SetBase, - METH_VARARGS, xmlparse_SetBase__doc__}, + METH_VARARGS, xmlparse_SetBase__doc__}, {"GetBase", (PyCFunction)xmlparse_GetBase, - METH_NOARGS, xmlparse_GetBase__doc__}, + METH_NOARGS, xmlparse_GetBase__doc__}, {"ExternalEntityParserCreate", (PyCFunction)xmlparse_ExternalEntityParserCreate, - METH_VARARGS, xmlparse_ExternalEntityParserCreate__doc__}, + METH_VARARGS, xmlparse_ExternalEntityParserCreate__doc__}, {"SetParamEntityParsing", (PyCFunction)xmlparse_SetParamEntityParsing, - METH_VARARGS, xmlparse_SetParamEntityParsing__doc__}, + METH_VARARGS, xmlparse_SetParamEntityParsing__doc__}, {"GetInputContext", (PyCFunction)xmlparse_GetInputContext, - METH_NOARGS, xmlparse_GetInputContext__doc__}, + METH_NOARGS, xmlparse_GetInputContext__doc__}, #if XML_COMBINED_VERSION >= 19505 {"UseForeignDTD", (PyCFunction)xmlparse_UseForeignDTD, - METH_VARARGS, xmlparse_UseForeignDTD__doc__}, + METH_VARARGS, xmlparse_UseForeignDTD__doc__}, #endif {"__dir__", xmlparse_dir, METH_NOARGS}, - {NULL, NULL} /* sentinel */ + {NULL, NULL} /* sentinel */ }; /* ---------- */ @@ -1133,7 +1133,7 @@ { int i; for (i = 0; i < 256; i++) { - template_buffer[i] = i; + template_buffer[i] = i; } template_buffer[256] = 0; } @@ -1152,15 +1152,15 @@ PyUnicode_Decode(template_buffer, 256, name, "replace"); if (_u_string == NULL) - return result; + return result; for (i = 0; i < 256; i++) { - /* Stupid to access directly, but fast */ - Py_UNICODE c = _u_string->str[i]; - if (c == Py_UNICODE_REPLACEMENT_CHARACTER) - info->map[i] = -1; - else - info->map[i] = c; + /* Stupid to access directly, but fast */ + Py_UNICODE c = _u_string->str[i]; + if (c == Py_UNICODE_REPLACEMENT_CHARACTER) + info->map[i] = -1; + else + info->map[i] = c; } info->data = NULL; info->convert = NULL; @@ -1295,8 +1295,8 @@ int handlernum = -1; if (PyUnicode_Check(nameobj)) - name = _PyUnicode_AsString(nameobj); - + name = _PyUnicode_AsString(nameobj); + handlernum = handlername2int(name); if (handlernum != -1) { @@ -1362,18 +1362,18 @@ static PyObject * xmlparse_dir(PyObject *self, PyObject* noargs) { -#define APPEND(list, str) \ - do { \ - PyObject *o = PyUnicode_FromString(str); \ - if (o != NULL) \ - PyList_Append(list, o); \ - Py_XDECREF(o); \ +#define APPEND(list, str) \ + do { \ + PyObject *o = PyUnicode_FromString(str); \ + if (o != NULL) \ + PyList_Append(list, o); \ + Py_XDECREF(o); \ } while (0) int i; PyObject *rc = PyList_New(0); if (!rc) - return NULL; + return NULL; for (i = 0; handler_info[i].name != NULL; i++) { PyObject *o = get_handler_name(&handler_info[i]); if (o != NULL) @@ -1494,42 +1494,42 @@ if (strcmp(name, "buffer_size") == 0) { long new_buffer_size; if (!PyLong_Check(v)) { - PyErr_SetString(PyExc_TypeError, "buffer_size must be an integer"); - return -1; + PyErr_SetString(PyExc_TypeError, "buffer_size must be an integer"); + return -1; } new_buffer_size=PyLong_AS_LONG(v); /* trivial case -- no change */ if (new_buffer_size == self->buffer_size) { - return 0; + return 0; } if (new_buffer_size <= 0) { - PyErr_SetString(PyExc_ValueError, "buffer_size must be greater than zero"); - return -1; + PyErr_SetString(PyExc_ValueError, "buffer_size must be greater than zero"); + return -1; } /* check maximum */ if (new_buffer_size > INT_MAX) { - char errmsg[100]; - sprintf(errmsg, "buffer_size must not be greater than %i", INT_MAX); - PyErr_SetString(PyExc_ValueError, errmsg); - return -1; + char errmsg[100]; + sprintf(errmsg, "buffer_size must not be greater than %i", INT_MAX); + PyErr_SetString(PyExc_ValueError, errmsg); + return -1; } if (self->buffer != NULL) { - /* there is already a buffer */ - if (self->buffer_used != 0) { - flush_character_buffer(self); - } - /* free existing buffer */ - free(self->buffer); + /* there is already a buffer */ + if (self->buffer_used != 0) { + flush_character_buffer(self); + } + /* free existing buffer */ + free(self->buffer); } self->buffer = malloc(new_buffer_size); if (self->buffer == NULL) { - PyErr_NoMemory(); - return -1; - } + PyErr_NoMemory(); + return -1; + } self->buffer_size = new_buffer_size; return 0; } @@ -1570,39 +1570,39 @@ PyDoc_STRVAR(Xmlparsetype__doc__, "XML parser"); static PyTypeObject Xmlparsetype = { - PyVarObject_HEAD_INIT(NULL, 0) - "pyexpat.xmlparser", /*tp_name*/ - sizeof(xmlparseobject) + PyGC_HEAD_SIZE,/*tp_basicsize*/ - 0, /*tp_itemsize*/ - /* methods */ - (destructor)xmlparse_dealloc, /*tp_dealloc*/ - (printfunc)0, /*tp_print*/ - 0, /*tp_getattr*/ - (setattrfunc)xmlparse_setattr, /*tp_setattr*/ - 0, /*tp_reserved*/ - (reprfunc)0, /*tp_repr*/ - 0, /*tp_as_number*/ - 0, /*tp_as_sequence*/ - 0, /*tp_as_mapping*/ - (hashfunc)0, /*tp_hash*/ - (ternaryfunc)0, /*tp_call*/ - (reprfunc)0, /*tp_str*/ - (getattrofunc)xmlparse_getattro, /* tp_getattro */ - 0, /* tp_setattro */ - 0, /* tp_as_buffer */ + PyVarObject_HEAD_INIT(NULL, 0) + "pyexpat.xmlparser", /*tp_name*/ + sizeof(xmlparseobject) + PyGC_HEAD_SIZE,/*tp_basicsize*/ + 0, /*tp_itemsize*/ + /* methods */ + (destructor)xmlparse_dealloc, /*tp_dealloc*/ + (printfunc)0, /*tp_print*/ + 0, /*tp_getattr*/ + (setattrfunc)xmlparse_setattr, /*tp_setattr*/ + 0, /*tp_reserved*/ + (reprfunc)0, /*tp_repr*/ + 0, /*tp_as_number*/ + 0, /*tp_as_sequence*/ + 0, /*tp_as_mapping*/ + (hashfunc)0, /*tp_hash*/ + (ternaryfunc)0, /*tp_call*/ + (reprfunc)0, /*tp_str*/ + (getattrofunc)xmlparse_getattro, /* tp_getattro */ + 0, /* tp_setattro */ + 0, /* tp_as_buffer */ #ifdef Py_TPFLAGS_HAVE_GC - Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC, /*tp_flags*/ + Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC, /*tp_flags*/ #else - Py_TPFLAGS_DEFAULT | Py_TPFLAGS_GC, /*tp_flags*/ + Py_TPFLAGS_DEFAULT | Py_TPFLAGS_GC, /*tp_flags*/ #endif - Xmlparsetype__doc__, /* tp_doc - Documentation string */ - (traverseproc)xmlparse_traverse, /* tp_traverse */ - (inquiry)xmlparse_clear, /* tp_clear */ - 0, /* tp_richcompare */ - 0, /* tp_weaklistoffset */ - 0, /* tp_iter */ - 0, /* tp_iternext */ - xmlparse_methods, /* tp_methods */ + Xmlparsetype__doc__, /* tp_doc - Documentation string */ + (traverseproc)xmlparse_traverse, /* tp_traverse */ + (inquiry)xmlparse_clear, /* tp_clear */ + 0, /* tp_richcompare */ + 0, /* tp_weaklistoffset */ + 0, /* tp_iter */ + 0, /* tp_iternext */ + xmlparse_methods, /* tp_methods */ }; /* End of code for xmlparser objects */ @@ -1636,21 +1636,21 @@ /* Explicitly passing None means no interning is desired. Not passing anything means that a new dictionary is used. */ if (intern == Py_None) - intern = NULL; + intern = NULL; else if (intern == NULL) { - intern = PyDict_New(); - if (!intern) - return NULL; - intern_decref = 1; + intern = PyDict_New(); + if (!intern) + return NULL; + intern_decref = 1; } else if (!PyDict_Check(intern)) { - PyErr_SetString(PyExc_TypeError, "intern must be a dictionary"); - return NULL; + PyErr_SetString(PyExc_TypeError, "intern must be a dictionary"); + return NULL; } result = newxmlparseobject(encoding, namespace_separator, intern); if (intern_decref) { - Py_DECREF(intern); + Py_DECREF(intern); } return result; } @@ -1672,12 +1672,12 @@ /* List of methods defined in the module */ static struct PyMethodDef pyexpat_methods[] = { - {"ParserCreate", (PyCFunction)pyexpat_ParserCreate, + {"ParserCreate", (PyCFunction)pyexpat_ParserCreate, METH_VARARGS|METH_KEYWORDS, pyexpat_ParserCreate__doc__}, - {"ErrorString", (PyCFunction)pyexpat_ErrorString, - METH_VARARGS, pyexpat_ErrorString__doc__}, + {"ErrorString", (PyCFunction)pyexpat_ErrorString, + METH_VARARGS, pyexpat_ErrorString__doc__}, - {NULL, (PyCFunction)NULL, 0, NULL} /* sentinel */ + {NULL, (PyCFunction)NULL, 0, NULL} /* sentinel */ }; /* Module docstring */ @@ -1726,15 +1726,15 @@ PyMODINIT_FUNC MODULE_INITFUNC(void); /* avoid compiler warnings */ static struct PyModuleDef pyexpatmodule = { - PyModuleDef_HEAD_INIT, - MODULE_NAME, - pyexpat_module_documentation, - -1, - pyexpat_methods, - NULL, - NULL, - NULL, - NULL + PyModuleDef_HEAD_INIT, + MODULE_NAME, + pyexpat_module_documentation, + -1, + pyexpat_methods, + NULL, + NULL, + NULL, + NULL }; PyMODINIT_FUNC @@ -1756,12 +1756,12 @@ return NULL; if (PyType_Ready(&Xmlparsetype) < 0) - return NULL; + return NULL; /* Create the module and add the functions */ m = PyModule_Create(&pyexpatmodule); if (m == NULL) - return NULL; + return NULL; /* Add some symbolic constants to the module */ if (ErrorObject == NULL) { @@ -1818,7 +1818,7 @@ if (errors_module == NULL || model_module == NULL) /* Don't core dump later! */ return NULL; - + #if XML_COMBINED_VERSION > 19505 { const XML_Feature *features = XML_GetFeatureList(); @@ -1943,7 +1943,7 @@ capi.SetProcessingInstructionHandler = XML_SetProcessingInstructionHandler; capi.SetUnknownEncodingHandler = XML_SetUnknownEncodingHandler; capi.SetUserData = XML_SetUserData; - + /* export using capsule */ capi_object = PyCapsule_New(&capi, PyExpat_CAPSULE_NAME, NULL); if (capi_object) @@ -1959,12 +1959,12 @@ for (; handler_info[i].name != NULL; i++) { if (initial) - self->handlers[i] = NULL; - else { + self->handlers[i] = NULL; + else { temp = self->handlers[i]; self->handlers[i] = NULL; Py_XDECREF(temp); - handler_info[i].setter(self->itself, NULL); + handler_info[i].setter(self->itself, NULL); } } } Modified: python/branches/py3k/Modules/python.c ============================================================================== --- python/branches/py3k/Modules/python.c (original) +++ python/branches/py3k/Modules/python.c Sun May 9 17:52:27 2010 @@ -11,48 +11,48 @@ int wmain(int argc, wchar_t **argv) { - return Py_Main(argc, argv); + return Py_Main(argc, argv); } #else int main(int argc, char **argv) { - wchar_t **argv_copy = (wchar_t **)PyMem_Malloc(sizeof(wchar_t*)*argc); - /* We need a second copies, as Python might modify the first one. */ - wchar_t **argv_copy2 = (wchar_t **)PyMem_Malloc(sizeof(wchar_t*)*argc); - int i, res; - char *oldloc; - /* 754 requires that FP exceptions run in "no stop" mode by default, - * and until C vendors implement C99's ways to control FP exceptions, - * Python requires non-stop mode. Alas, some platforms enable FP - * exceptions by default. Here we disable them. - */ + wchar_t **argv_copy = (wchar_t **)PyMem_Malloc(sizeof(wchar_t*)*argc); + /* We need a second copies, as Python might modify the first one. */ + wchar_t **argv_copy2 = (wchar_t **)PyMem_Malloc(sizeof(wchar_t*)*argc); + int i, res; + char *oldloc; + /* 754 requires that FP exceptions run in "no stop" mode by default, + * and until C vendors implement C99's ways to control FP exceptions, + * Python requires non-stop mode. Alas, some platforms enable FP + * exceptions by default. Here we disable them. + */ #ifdef __FreeBSD__ - fp_except_t m; + fp_except_t m; - m = fpgetmask(); - fpsetmask(m & ~FP_X_OFL); + m = fpgetmask(); + fpsetmask(m & ~FP_X_OFL); #endif - if (!argv_copy || !argv_copy2) { - fprintf(stderr, "out of memory\n"); - return 1; - } - oldloc = strdup(setlocale(LC_ALL, NULL)); - setlocale(LC_ALL, ""); - for (i = 0; i < argc; i++) { - argv_copy2[i] = argv_copy[i] = _Py_char2wchar(argv[i]); - if (!argv_copy[i]) - return 1; - } - setlocale(LC_ALL, oldloc); - free(oldloc); - res = Py_Main(argc, argv_copy); - for (i = 0; i < argc; i++) { - PyMem_Free(argv_copy2[i]); - } - PyMem_Free(argv_copy); - PyMem_Free(argv_copy2); - return res; + if (!argv_copy || !argv_copy2) { + fprintf(stderr, "out of memory\n"); + return 1; + } + oldloc = strdup(setlocale(LC_ALL, NULL)); + setlocale(LC_ALL, ""); + for (i = 0; i < argc; i++) { + argv_copy2[i] = argv_copy[i] = _Py_char2wchar(argv[i]); + if (!argv_copy[i]) + return 1; + } + setlocale(LC_ALL, oldloc); + free(oldloc); + res = Py_Main(argc, argv_copy); + for (i = 0; i < argc; i++) { + PyMem_Free(argv_copy2[i]); + } + PyMem_Free(argv_copy); + PyMem_Free(argv_copy2); + return res; } #endif Modified: python/branches/py3k/Modules/readline.c ============================================================================== --- python/branches/py3k/Modules/readline.c (original) +++ python/branches/py3k/Modules/readline.c Sun May 9 17:52:27 2010 @@ -23,7 +23,7 @@ #ifdef SAVE_LOCALE # define RESTORE_LOCALE(sl) { setlocale(LC_CTYPE, sl); free(sl); } #else -# define RESTORE_LOCALE(sl) +# define RESTORE_LOCALE(sl) #endif /* GNU readline definitions */ @@ -33,7 +33,7 @@ #ifdef HAVE_RL_COMPLETION_MATCHES #define completion_matches(x, y) \ - rl_completion_matches((x), ((rl_compentry_func_t *)(y))) + rl_completion_matches((x), ((rl_compentry_func_t *)(y))) #else #if defined(_RL_FUNCTION_TYPEDEF) extern char **completion_matches(char *, rl_compentry_func_t *); @@ -48,13 +48,13 @@ #ifdef __APPLE__ /* * It is possible to link the readline module to the readline - * emulation library of editline/libedit. - * + * emulation library of editline/libedit. + * * On OSX this emulation library is not 100% API compatible * with the "real" readline and cannot be detected at compile-time, * hence we use a runtime check to detect if we're using libedit * - * Currently there is one know API incompatibility: + * Currently there is one know API incompatibility: * - 'get_history' has a 1-based index with GNU readline, and a 0-based * index with libedit's emulation. * - Note that replace_history and remove_history use a 0-based index @@ -66,7 +66,7 @@ static void on_completion_display_matches_hook(char **matches, - int num_matches, int max_length); + int num_matches, int max_length); /* Exported function to send one line to readline's init file parser */ @@ -74,18 +74,18 @@ static PyObject * parse_and_bind(PyObject *self, PyObject *args) { - char *s, *copy; - if (!PyArg_ParseTuple(args, "s:parse_and_bind", &s)) - return NULL; - /* Make a copy -- rl_parse_and_bind() modifies its argument */ - /* Bernard Herzog */ - copy = malloc(1 + strlen(s)); - if (copy == NULL) - return PyErr_NoMemory(); - strcpy(copy, s); - rl_parse_and_bind(copy); - free(copy); /* Free the copy */ - Py_RETURN_NONE; + char *s, *copy; + if (!PyArg_ParseTuple(args, "s:parse_and_bind", &s)) + return NULL; + /* Make a copy -- rl_parse_and_bind() modifies its argument */ + /* Bernard Herzog */ + copy = malloc(1 + strlen(s)); + if (copy == NULL) + return PyErr_NoMemory(); + strcpy(copy, s); + rl_parse_and_bind(copy); + free(copy); /* Free the copy */ + Py_RETURN_NONE; } PyDoc_STRVAR(doc_parse_and_bind, @@ -98,13 +98,13 @@ static PyObject * read_init_file(PyObject *self, PyObject *args) { - char *s = NULL; - if (!PyArg_ParseTuple(args, "|z:read_init_file", &s)) - return NULL; - errno = rl_read_init_file(s); - if (errno) - return PyErr_SetFromErrno(PyExc_IOError); - Py_RETURN_NONE; + char *s = NULL; + if (!PyArg_ParseTuple(args, "|z:read_init_file", &s)) + return NULL; + errno = rl_read_init_file(s); + if (errno) + return PyErr_SetFromErrno(PyExc_IOError); + Py_RETURN_NONE; } PyDoc_STRVAR(doc_read_init_file, @@ -118,13 +118,13 @@ static PyObject * read_history_file(PyObject *self, PyObject *args) { - char *s = NULL; - if (!PyArg_ParseTuple(args, "|z:read_history_file", &s)) - return NULL; - errno = read_history(s); - if (errno) - return PyErr_SetFromErrno(PyExc_IOError); - Py_RETURN_NONE; + char *s = NULL; + if (!PyArg_ParseTuple(args, "|z:read_history_file", &s)) + return NULL; + errno = read_history(s); + if (errno) + return PyErr_SetFromErrno(PyExc_IOError); + Py_RETURN_NONE; } static int _history_length = -1; /* do not truncate history by default */ @@ -139,15 +139,15 @@ static PyObject * write_history_file(PyObject *self, PyObject *args) { - char *s = NULL; - if (!PyArg_ParseTuple(args, "|z:write_history_file", &s)) - return NULL; - errno = write_history(s); - if (!errno && _history_length >= 0) - history_truncate_file(s, _history_length); - if (errno) - return PyErr_SetFromErrno(PyExc_IOError); - Py_RETURN_NONE; + char *s = NULL; + if (!PyArg_ParseTuple(args, "|z:write_history_file", &s)) + return NULL; + errno = write_history(s); + if (!errno && _history_length >= 0) + history_truncate_file(s, _history_length); + if (errno) + return PyErr_SetFromErrno(PyExc_IOError); + Py_RETURN_NONE; } PyDoc_STRVAR(doc_write_history_file, @@ -161,11 +161,11 @@ static PyObject* set_history_length(PyObject *self, PyObject *args) { - int length = _history_length; - if (!PyArg_ParseTuple(args, "i:set_history_length", &length)) - return NULL; - _history_length = length; - Py_RETURN_NONE; + int length = _history_length; + if (!PyArg_ParseTuple(args, "i:set_history_length", &length)) + return NULL; + _history_length = length; + Py_RETURN_NONE; } PyDoc_STRVAR(set_history_length_doc, @@ -180,7 +180,7 @@ static PyObject* get_history_length(PyObject *self, PyObject *noarg) { - return PyLong_FromLong(_history_length); + return PyLong_FromLong(_history_length); } PyDoc_STRVAR(get_history_length_doc, @@ -194,29 +194,29 @@ static PyObject * set_hook(const char *funcname, PyObject **hook_var, PyObject *args) { - PyObject *function = Py_None; - char buf[80]; - PyOS_snprintf(buf, sizeof(buf), "|O:set_%.50s", funcname); - if (!PyArg_ParseTuple(args, buf, &function)) - return NULL; - if (function == Py_None) { - Py_XDECREF(*hook_var); - *hook_var = NULL; - } - else if (PyCallable_Check(function)) { - PyObject *tmp = *hook_var; - Py_INCREF(function); - *hook_var = function; - Py_XDECREF(tmp); - } - else { - PyOS_snprintf(buf, sizeof(buf), - "set_%.50s(func): argument not callable", - funcname); - PyErr_SetString(PyExc_TypeError, buf); - return NULL; - } - Py_RETURN_NONE; + PyObject *function = Py_None; + char buf[80]; + PyOS_snprintf(buf, sizeof(buf), "|O:set_%.50s", funcname); + if (!PyArg_ParseTuple(args, buf, &function)) + return NULL; + if (function == Py_None) { + Py_XDECREF(*hook_var); + *hook_var = NULL; + } + else if (PyCallable_Check(function)) { + PyObject *tmp = *hook_var; + Py_INCREF(function); + *hook_var = function; + Py_XDECREF(tmp); + } + else { + PyOS_snprintf(buf, sizeof(buf), + "set_%.50s(func): argument not callable", + funcname); + PyErr_SetString(PyExc_TypeError, buf); + return NULL; + } + Py_RETURN_NONE; } @@ -232,20 +232,20 @@ static PyObject * set_completion_display_matches_hook(PyObject *self, PyObject *args) { - PyObject *result = set_hook("completion_display_matches_hook", - &completion_display_matches_hook, args); + PyObject *result = set_hook("completion_display_matches_hook", + &completion_display_matches_hook, args); #ifdef HAVE_RL_COMPLETION_DISPLAY_MATCHES_HOOK - /* We cannot set this hook globally, since it replaces the - default completion display. */ - rl_completion_display_matches_hook = - completion_display_matches_hook ? + /* We cannot set this hook globally, since it replaces the + default completion display. */ + rl_completion_display_matches_hook = + completion_display_matches_hook ? #if defined(_RL_FUNCTION_TYPEDEF) - (rl_compdisp_func_t *)on_completion_display_matches_hook : 0; + (rl_compdisp_func_t *)on_completion_display_matches_hook : 0; #else - (VFunction *)on_completion_display_matches_hook : 0; + (VFunction *)on_completion_display_matches_hook : 0; #endif #endif - return result; + return result; } @@ -259,7 +259,7 @@ static PyObject * set_startup_hook(PyObject *self, PyObject *args) { - return set_hook("startup_hook", &startup_hook, args); + return set_hook("startup_hook", &startup_hook, args); } PyDoc_STRVAR(doc_set_startup_hook, @@ -276,7 +276,7 @@ static PyObject * set_pre_input_hook(PyObject *self, PyObject *args) { - return set_hook("pre_input_hook", &pre_input_hook, args); + return set_hook("pre_input_hook", &pre_input_hook, args); } PyDoc_STRVAR(doc_set_pre_input_hook, @@ -314,8 +314,8 @@ static PyObject * get_begidx(PyObject *self, PyObject *noarg) { - Py_INCREF(begidx); - return begidx; + Py_INCREF(begidx); + return begidx; } PyDoc_STRVAR(doc_get_begidx, @@ -328,8 +328,8 @@ static PyObject * get_endidx(PyObject *self, PyObject *noarg) { - Py_INCREF(endidx); - return endidx; + Py_INCREF(endidx); + return endidx; } PyDoc_STRVAR(doc_get_endidx, @@ -342,14 +342,14 @@ static PyObject * set_completer_delims(PyObject *self, PyObject *args) { - char *break_chars; + char *break_chars; - if(!PyArg_ParseTuple(args, "s:set_completer_delims", &break_chars)) { - return NULL; - } - free((void*)rl_completer_word_break_characters); - rl_completer_word_break_characters = strdup(break_chars); - Py_RETURN_NONE; + if(!PyArg_ParseTuple(args, "s:set_completer_delims", &break_chars)) { + return NULL; + } + free((void*)rl_completer_word_break_characters); + rl_completer_word_break_characters = strdup(break_chars); + Py_RETURN_NONE; } PyDoc_STRVAR(doc_set_completer_delims, @@ -359,31 +359,31 @@ static PyObject * py_remove_history(PyObject *self, PyObject *args) { - int entry_number; - HIST_ENTRY *entry; + int entry_number; + HIST_ENTRY *entry; - if (!PyArg_ParseTuple(args, "i:remove_history", &entry_number)) - return NULL; - if (entry_number < 0) { - PyErr_SetString(PyExc_ValueError, - "History index cannot be negative"); - return NULL; - } - entry = remove_history(entry_number); - if (!entry) { - PyErr_Format(PyExc_ValueError, - "No history item at position %d", - entry_number); - return NULL; - } - /* free memory allocated for the history entry */ - if (entry->line) - free(entry->line); - if (entry->data) - free(entry->data); - free(entry); + if (!PyArg_ParseTuple(args, "i:remove_history", &entry_number)) + return NULL; + if (entry_number < 0) { + PyErr_SetString(PyExc_ValueError, + "History index cannot be negative"); + return NULL; + } + entry = remove_history(entry_number); + if (!entry) { + PyErr_Format(PyExc_ValueError, + "No history item at position %d", + entry_number); + return NULL; + } + /* free memory allocated for the history entry */ + if (entry->line) + free(entry->line); + if (entry->data) + free(entry->data); + free(entry); - Py_RETURN_NONE; + Py_RETURN_NONE; } PyDoc_STRVAR(doc_remove_history, @@ -393,34 +393,34 @@ static PyObject * py_replace_history(PyObject *self, PyObject *args) { - int entry_number; - char *line; - HIST_ENTRY *old_entry; - - if (!PyArg_ParseTuple(args, "is:replace_history", &entry_number, - &line)) { - return NULL; - } - if (entry_number < 0) { - PyErr_SetString(PyExc_ValueError, - "History index cannot be negative"); - return NULL; - } - old_entry = replace_history_entry(entry_number, line, (void *)NULL); - if (!old_entry) { - PyErr_Format(PyExc_ValueError, - "No history item at position %d", - entry_number); - return NULL; - } - /* free memory allocated for the old history entry */ - if (old_entry->line) - free(old_entry->line); - if (old_entry->data) - free(old_entry->data); - free(old_entry); + int entry_number; + char *line; + HIST_ENTRY *old_entry; + + if (!PyArg_ParseTuple(args, "is:replace_history", &entry_number, + &line)) { + return NULL; + } + if (entry_number < 0) { + PyErr_SetString(PyExc_ValueError, + "History index cannot be negative"); + return NULL; + } + old_entry = replace_history_entry(entry_number, line, (void *)NULL); + if (!old_entry) { + PyErr_Format(PyExc_ValueError, + "No history item at position %d", + entry_number); + return NULL; + } + /* free memory allocated for the old history entry */ + if (old_entry->line) + free(old_entry->line); + if (old_entry->data) + free(old_entry->data); + free(old_entry); - Py_RETURN_NONE; + Py_RETURN_NONE; } PyDoc_STRVAR(doc_replace_history, @@ -432,13 +432,13 @@ static PyObject * py_add_history(PyObject *self, PyObject *args) { - char *line; + char *line; - if(!PyArg_ParseTuple(args, "s:add_history", &line)) { - return NULL; - } - add_history(line); - Py_RETURN_NONE; + if(!PyArg_ParseTuple(args, "s:add_history", &line)) { + return NULL; + } + add_history(line); + Py_RETURN_NONE; } PyDoc_STRVAR(doc_add_history, @@ -451,7 +451,7 @@ static PyObject * get_completer_delims(PyObject *self, PyObject *noarg) { - return PyUnicode_FromString(rl_completer_word_break_characters); + return PyUnicode_FromString(rl_completer_word_break_characters); } PyDoc_STRVAR(doc_get_completer_delims, @@ -464,7 +464,7 @@ static PyObject * set_completer(PyObject *self, PyObject *args) { - return set_hook("completer", &completer, args); + return set_hook("completer", &completer, args); } PyDoc_STRVAR(doc_set_completer, @@ -478,11 +478,11 @@ static PyObject * get_completer(PyObject *self, PyObject *noargs) { - if (completer == NULL) { - Py_RETURN_NONE; - } - Py_INCREF(completer); - return completer; + if (completer == NULL) { + Py_RETURN_NONE; + } + Py_INCREF(completer); + return completer; } PyDoc_STRVAR(doc_get_completer, @@ -495,39 +495,39 @@ static PyObject * get_history_item(PyObject *self, PyObject *args) { - int idx = 0; - HIST_ENTRY *hist_ent; + int idx = 0; + HIST_ENTRY *hist_ent; - if (!PyArg_ParseTuple(args, "i:index", &idx)) - return NULL; + if (!PyArg_ParseTuple(args, "i:index", &idx)) + return NULL; #ifdef __APPLE__ - if (using_libedit_emulation) { - /* Libedit emulation uses 0-based indexes, - * the real one uses 1-based indexes, - * adjust the index to ensure that Python - * code doesn't have to worry about the - * difference. - */ - HISTORY_STATE *hist_st; - hist_st = history_get_history_state(); - - idx --; - - /* - * Apple's readline emulation crashes when - * the index is out of range, therefore - * test for that and fail gracefully. - */ - if (idx < 0 || idx >= hist_st->length) { - Py_RETURN_NONE; - } - } + if (using_libedit_emulation) { + /* Libedit emulation uses 0-based indexes, + * the real one uses 1-based indexes, + * adjust the index to ensure that Python + * code doesn't have to worry about the + * difference. + */ + HISTORY_STATE *hist_st; + hist_st = history_get_history_state(); + + idx --; + + /* + * Apple's readline emulation crashes when + * the index is out of range, therefore + * test for that and fail gracefully. + */ + if (idx < 0 || idx >= hist_st->length) { + Py_RETURN_NONE; + } + } #endif /* __APPLE__ */ - if ((hist_ent = history_get(idx))) - return PyUnicode_FromString(hist_ent->line); - else { - Py_RETURN_NONE; - } + if ((hist_ent = history_get(idx))) + return PyUnicode_FromString(hist_ent->line); + else { + Py_RETURN_NONE; + } } PyDoc_STRVAR(doc_get_history_item, @@ -540,10 +540,10 @@ static PyObject * get_current_history_length(PyObject *self, PyObject *noarg) { - HISTORY_STATE *hist_st; + HISTORY_STATE *hist_st; - hist_st = history_get_history_state(); - return PyLong_FromLong(hist_st ? (long) hist_st->length : (long) 0); + hist_st = history_get_history_state(); + return PyLong_FromLong(hist_st ? (long) hist_st->length : (long) 0); } PyDoc_STRVAR(doc_get_current_history_length, @@ -556,7 +556,7 @@ static PyObject * get_line_buffer(PyObject *self, PyObject *noarg) { - return PyUnicode_FromString(rl_line_buffer); + return PyUnicode_FromString(rl_line_buffer); } PyDoc_STRVAR(doc_get_line_buffer, @@ -571,8 +571,8 @@ static PyObject * py_clear_history(PyObject *self, PyObject *noarg) { - clear_history(); - Py_RETURN_NONE; + clear_history(); + Py_RETURN_NONE; } PyDoc_STRVAR(doc_clear_history, @@ -586,11 +586,11 @@ static PyObject * insert_text(PyObject *self, PyObject *args) { - char *s; - if (!PyArg_ParseTuple(args, "s:insert_text", &s)) - return NULL; - rl_insert_text(s); - Py_RETURN_NONE; + char *s; + if (!PyArg_ParseTuple(args, "s:insert_text", &s)) + return NULL; + rl_insert_text(s); + Py_RETURN_NONE; } PyDoc_STRVAR(doc_insert_text, @@ -603,8 +603,8 @@ static PyObject * redisplay(PyObject *self, PyObject *noarg) { - rl_redisplay(); - Py_RETURN_NONE; + rl_redisplay(); + Py_RETURN_NONE; } PyDoc_STRVAR(doc_redisplay, @@ -617,50 +617,50 @@ static struct PyMethodDef readline_methods[] = { - {"parse_and_bind", parse_and_bind, METH_VARARGS, doc_parse_and_bind}, - {"get_line_buffer", get_line_buffer, METH_NOARGS, doc_get_line_buffer}, - {"insert_text", insert_text, METH_VARARGS, doc_insert_text}, - {"redisplay", redisplay, METH_NOARGS, doc_redisplay}, - {"read_init_file", read_init_file, METH_VARARGS, doc_read_init_file}, - {"read_history_file", read_history_file, - METH_VARARGS, doc_read_history_file}, - {"write_history_file", write_history_file, - METH_VARARGS, doc_write_history_file}, - {"get_history_item", get_history_item, - METH_VARARGS, doc_get_history_item}, - {"get_current_history_length", (PyCFunction)get_current_history_length, - METH_NOARGS, doc_get_current_history_length}, - {"set_history_length", set_history_length, - METH_VARARGS, set_history_length_doc}, - {"get_history_length", get_history_length, - METH_NOARGS, get_history_length_doc}, - {"set_completer", set_completer, METH_VARARGS, doc_set_completer}, - {"get_completer", get_completer, METH_NOARGS, doc_get_completer}, - {"get_completion_type", get_completion_type, - METH_NOARGS, doc_get_completion_type}, - {"get_begidx", get_begidx, METH_NOARGS, doc_get_begidx}, - {"get_endidx", get_endidx, METH_NOARGS, doc_get_endidx}, - - {"set_completer_delims", set_completer_delims, - METH_VARARGS, doc_set_completer_delims}, - {"add_history", py_add_history, METH_VARARGS, doc_add_history}, - {"remove_history_item", py_remove_history, METH_VARARGS, doc_remove_history}, - {"replace_history_item", py_replace_history, METH_VARARGS, doc_replace_history}, - {"get_completer_delims", get_completer_delims, - METH_NOARGS, doc_get_completer_delims}, - - {"set_completion_display_matches_hook", set_completion_display_matches_hook, - METH_VARARGS, doc_set_completion_display_matches_hook}, - {"set_startup_hook", set_startup_hook, - METH_VARARGS, doc_set_startup_hook}, + {"parse_and_bind", parse_and_bind, METH_VARARGS, doc_parse_and_bind}, + {"get_line_buffer", get_line_buffer, METH_NOARGS, doc_get_line_buffer}, + {"insert_text", insert_text, METH_VARARGS, doc_insert_text}, + {"redisplay", redisplay, METH_NOARGS, doc_redisplay}, + {"read_init_file", read_init_file, METH_VARARGS, doc_read_init_file}, + {"read_history_file", read_history_file, + METH_VARARGS, doc_read_history_file}, + {"write_history_file", write_history_file, + METH_VARARGS, doc_write_history_file}, + {"get_history_item", get_history_item, + METH_VARARGS, doc_get_history_item}, + {"get_current_history_length", (PyCFunction)get_current_history_length, + METH_NOARGS, doc_get_current_history_length}, + {"set_history_length", set_history_length, + METH_VARARGS, set_history_length_doc}, + {"get_history_length", get_history_length, + METH_NOARGS, get_history_length_doc}, + {"set_completer", set_completer, METH_VARARGS, doc_set_completer}, + {"get_completer", get_completer, METH_NOARGS, doc_get_completer}, + {"get_completion_type", get_completion_type, + METH_NOARGS, doc_get_completion_type}, + {"get_begidx", get_begidx, METH_NOARGS, doc_get_begidx}, + {"get_endidx", get_endidx, METH_NOARGS, doc_get_endidx}, + + {"set_completer_delims", set_completer_delims, + METH_VARARGS, doc_set_completer_delims}, + {"add_history", py_add_history, METH_VARARGS, doc_add_history}, + {"remove_history_item", py_remove_history, METH_VARARGS, doc_remove_history}, + {"replace_history_item", py_replace_history, METH_VARARGS, doc_replace_history}, + {"get_completer_delims", get_completer_delims, + METH_NOARGS, doc_get_completer_delims}, + + {"set_completion_display_matches_hook", set_completion_display_matches_hook, + METH_VARARGS, doc_set_completion_display_matches_hook}, + {"set_startup_hook", set_startup_hook, + METH_VARARGS, doc_set_startup_hook}, #ifdef HAVE_RL_PRE_INPUT_HOOK - {"set_pre_input_hook", set_pre_input_hook, - METH_VARARGS, doc_set_pre_input_hook}, + {"set_pre_input_hook", set_pre_input_hook, + METH_VARARGS, doc_set_pre_input_hook}, #endif #ifdef HAVE_RL_COMPLETION_APPEND_CHARACTER - {"clear_history", py_clear_history, METH_NOARGS, doc_clear_history}, + {"clear_history", py_clear_history, METH_NOARGS, doc_clear_history}, #endif - {0, 0} + {0, 0} }; @@ -669,47 +669,47 @@ static int on_hook(PyObject *func) { - int result = 0; - if (func != NULL) { - PyObject *r; + int result = 0; + if (func != NULL) { + PyObject *r; #ifdef WITH_THREAD - PyGILState_STATE gilstate = PyGILState_Ensure(); + PyGILState_STATE gilstate = PyGILState_Ensure(); #endif - r = PyObject_CallFunction(func, NULL); - if (r == NULL) - goto error; - if (r == Py_None) - result = 0; - else { - result = PyLong_AsLong(r); - if (result == -1 && PyErr_Occurred()) - goto error; - } - Py_DECREF(r); - goto done; - error: - PyErr_Clear(); - Py_XDECREF(r); - done: + r = PyObject_CallFunction(func, NULL); + if (r == NULL) + goto error; + if (r == Py_None) + result = 0; + else { + result = PyLong_AsLong(r); + if (result == -1 && PyErr_Occurred()) + goto error; + } + Py_DECREF(r); + goto done; + error: + PyErr_Clear(); + Py_XDECREF(r); + done: #ifdef WITH_THREAD - PyGILState_Release(gilstate); + PyGILState_Release(gilstate); #endif - return result; - } - return result; + return result; + } + return result; } static int on_startup_hook(void) { - return on_hook(startup_hook); + return on_hook(startup_hook); } #ifdef HAVE_RL_PRE_INPUT_HOOK static int on_pre_input_hook(void) { - return on_hook(pre_input_hook); + return on_hook(pre_input_hook); } #endif @@ -718,42 +718,42 @@ static void on_completion_display_matches_hook(char **matches, - int num_matches, int max_length) + int num_matches, int max_length) { - int i; - PyObject *m=NULL, *s=NULL, *r=NULL; + int i; + PyObject *m=NULL, *s=NULL, *r=NULL; #ifdef WITH_THREAD - PyGILState_STATE gilstate = PyGILState_Ensure(); + PyGILState_STATE gilstate = PyGILState_Ensure(); #endif - m = PyList_New(num_matches); - if (m == NULL) - goto error; - for (i = 0; i < num_matches; i++) { - s = PyUnicode_FromString(matches[i+1]); - if (s == NULL) - goto error; - if (PyList_SetItem(m, i, s) == -1) - goto error; - } - r = PyObject_CallFunction(completion_display_matches_hook, - "sOi", matches[0], m, max_length); - - Py_DECREF(m); m=NULL; - - if (r == NULL || - (r != Py_None && PyLong_AsLong(r) == -1 && PyErr_Occurred())) { - goto error; - } - Py_XDECREF(r); r=NULL; - - if (0) { - error: - PyErr_Clear(); - Py_XDECREF(m); - Py_XDECREF(r); - } + m = PyList_New(num_matches); + if (m == NULL) + goto error; + for (i = 0; i < num_matches; i++) { + s = PyUnicode_FromString(matches[i+1]); + if (s == NULL) + goto error; + if (PyList_SetItem(m, i, s) == -1) + goto error; + } + r = PyObject_CallFunction(completion_display_matches_hook, + "sOi", matches[0], m, max_length); + + Py_DECREF(m); m=NULL; + + if (r == NULL || + (r != Py_None && PyLong_AsLong(r) == -1 && PyErr_Occurred())) { + goto error; + } + Py_XDECREF(r); r=NULL; + + if (0) { + error: + PyErr_Clear(); + Py_XDECREF(m); + Py_XDECREF(r); + } #ifdef WITH_THREAD - PyGILState_Release(gilstate); + PyGILState_Release(gilstate); #endif } @@ -763,37 +763,37 @@ static char * on_completion(const char *text, int state) { - char *result = NULL; - if (completer != NULL) { - PyObject *r; + char *result = NULL; + if (completer != NULL) { + PyObject *r; #ifdef WITH_THREAD - PyGILState_STATE gilstate = PyGILState_Ensure(); + PyGILState_STATE gilstate = PyGILState_Ensure(); #endif - rl_attempted_completion_over = 1; - r = PyObject_CallFunction(completer, "si", text, state); - if (r == NULL) - goto error; - if (r == Py_None) { - result = NULL; - } - else { - char *s = _PyUnicode_AsString(r); - if (s == NULL) - goto error; - result = strdup(s); - } - Py_DECREF(r); - goto done; - error: - PyErr_Clear(); - Py_XDECREF(r); - done: + rl_attempted_completion_over = 1; + r = PyObject_CallFunction(completer, "si", text, state); + if (r == NULL) + goto error; + if (r == Py_None) { + result = NULL; + } + else { + char *s = _PyUnicode_AsString(r); + if (s == NULL) + goto error; + result = strdup(s); + } + Py_DECREF(r); + goto done; + error: + PyErr_Clear(); + Py_XDECREF(r); + done: #ifdef WITH_THREAD - PyGILState_Release(gilstate); + PyGILState_Release(gilstate); #endif - return result; - } - return result; + return result; + } + return result; } @@ -804,16 +804,16 @@ flex_complete(char *text, int start, int end) { #ifdef HAVE_RL_COMPLETION_APPEND_CHARACTER - rl_completion_append_character ='\0'; + rl_completion_append_character ='\0'; #endif #ifdef HAVE_RL_COMPLETION_SUPPRESS_APPEND - rl_completion_suppress_append = 0; + rl_completion_suppress_append = 0; #endif - Py_XDECREF(begidx); - Py_XDECREF(endidx); - begidx = PyLong_FromLong((long) start); - endidx = PyLong_FromLong((long) end); - return completion_matches(text, *on_completion); + Py_XDECREF(begidx); + Py_XDECREF(endidx); + begidx = PyLong_FromLong((long) start); + endidx = PyLong_FromLong((long) end); + return completion_matches(text, *on_completion); } @@ -823,45 +823,45 @@ setup_readline(void) { #ifdef SAVE_LOCALE - char *saved_locale = strdup(setlocale(LC_CTYPE, NULL)); - if (!saved_locale) - Py_FatalError("not enough memory to save locale"); + char *saved_locale = strdup(setlocale(LC_CTYPE, NULL)); + if (!saved_locale) + Py_FatalError("not enough memory to save locale"); #endif - using_history(); + using_history(); - rl_readline_name = "python"; + rl_readline_name = "python"; #if defined(PYOS_OS2) && defined(PYCC_GCC) - /* Allow $if term= in .inputrc to work */ - rl_terminal_name = getenv("TERM"); + /* Allow $if term= in .inputrc to work */ + rl_terminal_name = getenv("TERM"); #endif - /* Force rebind of TAB to insert-tab */ - rl_bind_key('\t', rl_insert); - /* Bind both ESC-TAB and ESC-ESC to the completion function */ - rl_bind_key_in_map ('\t', rl_complete, emacs_meta_keymap); - rl_bind_key_in_map ('\033', rl_complete, emacs_meta_keymap); - /* Set our hook functions */ - rl_startup_hook = (Function *)on_startup_hook; + /* Force rebind of TAB to insert-tab */ + rl_bind_key('\t', rl_insert); + /* Bind both ESC-TAB and ESC-ESC to the completion function */ + rl_bind_key_in_map ('\t', rl_complete, emacs_meta_keymap); + rl_bind_key_in_map ('\033', rl_complete, emacs_meta_keymap); + /* Set our hook functions */ + rl_startup_hook = (Function *)on_startup_hook; #ifdef HAVE_RL_PRE_INPUT_HOOK - rl_pre_input_hook = (Function *)on_pre_input_hook; + rl_pre_input_hook = (Function *)on_pre_input_hook; #endif - /* Set our completion function */ - rl_attempted_completion_function = (CPPFunction *)flex_complete; - /* Set Python word break characters */ - rl_completer_word_break_characters = - strdup(" \t\n`~!@#$%^&*()-=+[{]}\\|;:'\",<>/?"); - /* All nonalphanums except '.' */ - - begidx = PyLong_FromLong(0L); - endidx = PyLong_FromLong(0L); - /* Initialize (allows .inputrc to override) - * - * XXX: A bug in the readline-2.2 library causes a memory leak - * inside this function. Nothing we can do about it. - */ - rl_initialize(); + /* Set our completion function */ + rl_attempted_completion_function = (CPPFunction *)flex_complete; + /* Set Python word break characters */ + rl_completer_word_break_characters = + strdup(" \t\n`~!@#$%^&*()-=+[{]}\\|;:'\",<>/?"); + /* All nonalphanums except '.' */ + + begidx = PyLong_FromLong(0L); + endidx = PyLong_FromLong(0L); + /* Initialize (allows .inputrc to override) + * + * XXX: A bug in the readline-2.2 library causes a memory leak + * inside this function. Nothing we can do about it. + */ + rl_initialize(); - RESTORE_LOCALE(saved_locale) + RESTORE_LOCALE(saved_locale) } /* Wrapper around GNU readline that handles signals differently. */ @@ -869,12 +869,12 @@ #if defined(HAVE_RL_CALLBACK) && defined(HAVE_SELECT) -static char *completed_input_string; +static char *completed_input_string; static void rlhandler(char *text) { - completed_input_string = text; - rl_callback_handler_remove(); + completed_input_string = text; + rl_callback_handler_remove(); } extern PyThreadState* _PyOS_ReadlineTState; @@ -882,60 +882,60 @@ static char * readline_until_enter_or_signal(char *prompt, int *signal) { - char * not_done_reading = ""; - fd_set selectset; + char * not_done_reading = ""; + fd_set selectset; - *signal = 0; + *signal = 0; #ifdef HAVE_RL_CATCH_SIGNAL - rl_catch_signals = 0; + rl_catch_signals = 0; #endif - rl_callback_handler_install (prompt, rlhandler); - FD_ZERO(&selectset); - - completed_input_string = not_done_reading; - - while (completed_input_string == not_done_reading) { - int has_input = 0; - - while (!has_input) - { struct timeval timeout = {0, 100000}; /* 0.1 seconds */ - - /* [Bug #1552726] Only limit the pause if an input hook has been - defined. */ - struct timeval *timeoutp = NULL; - if (PyOS_InputHook) - timeoutp = &timeout; - FD_SET(fileno(rl_instream), &selectset); - /* select resets selectset if no input was available */ - has_input = select(fileno(rl_instream) + 1, &selectset, - NULL, NULL, timeoutp); - if(PyOS_InputHook) PyOS_InputHook(); - } - - if(has_input > 0) { - rl_callback_read_char(); - } - else if (errno == EINTR) { - int s; + rl_callback_handler_install (prompt, rlhandler); + FD_ZERO(&selectset); + + completed_input_string = not_done_reading; + + while (completed_input_string == not_done_reading) { + int has_input = 0; + + while (!has_input) + { struct timeval timeout = {0, 100000}; /* 0.1 seconds */ + + /* [Bug #1552726] Only limit the pause if an input hook has been + defined. */ + struct timeval *timeoutp = NULL; + if (PyOS_InputHook) + timeoutp = &timeout; + FD_SET(fileno(rl_instream), &selectset); + /* select resets selectset if no input was available */ + has_input = select(fileno(rl_instream) + 1, &selectset, + NULL, NULL, timeoutp); + if(PyOS_InputHook) PyOS_InputHook(); + } + + if(has_input > 0) { + rl_callback_read_char(); + } + else if (errno == EINTR) { + int s; #ifdef WITH_THREAD - PyEval_RestoreThread(_PyOS_ReadlineTState); + PyEval_RestoreThread(_PyOS_ReadlineTState); #endif - s = PyErr_CheckSignals(); + s = PyErr_CheckSignals(); #ifdef WITH_THREAD - PyEval_SaveThread(); + PyEval_SaveThread(); #endif - if (s < 0) { - rl_free_line_state(); - rl_cleanup_after_signal(); - rl_callback_handler_remove(); - *signal = 1; - completed_input_string = NULL; - } - } - } + if (s < 0) { + rl_free_line_state(); + rl_cleanup_after_signal(); + rl_callback_handler_remove(); + *signal = 1; + completed_input_string = NULL; + } + } + } - return completed_input_string; + return completed_input_string; } @@ -949,31 +949,31 @@ static void onintr(int sig) { - longjmp(jbuf, 1); + longjmp(jbuf, 1); } static char * readline_until_enter_or_signal(char *prompt, int *signal) { - PyOS_sighandler_t old_inthandler; - char *p; - - *signal = 0; + PyOS_sighandler_t old_inthandler; + char *p; - old_inthandler = PyOS_setsig(SIGINT, onintr); - if (setjmp(jbuf)) { + *signal = 0; + + old_inthandler = PyOS_setsig(SIGINT, onintr); + if (setjmp(jbuf)) { #ifdef HAVE_SIGRELSE - /* This seems necessary on SunOS 4.1 (Rasmus Hahn) */ - sigrelse(SIGINT); + /* This seems necessary on SunOS 4.1 (Rasmus Hahn) */ + sigrelse(SIGINT); #endif - PyOS_setsig(SIGINT, old_inthandler); - *signal = 1; - return NULL; - } - rl_event_hook = PyOS_InputHook; - p = readline(prompt); - PyOS_setsig(SIGINT, old_inthandler); + PyOS_setsig(SIGINT, old_inthandler); + *signal = 1; + return NULL; + } + rl_event_hook = PyOS_InputHook; + p = readline(prompt); + PyOS_setsig(SIGINT, old_inthandler); return p; } @@ -983,82 +983,82 @@ static char * call_readline(FILE *sys_stdin, FILE *sys_stdout, char *prompt) { - size_t n; - char *p, *q; - int signal; + size_t n; + char *p, *q; + int signal; #ifdef SAVE_LOCALE - char *saved_locale = strdup(setlocale(LC_CTYPE, NULL)); - if (!saved_locale) - Py_FatalError("not enough memory to save locale"); - setlocale(LC_CTYPE, ""); + char *saved_locale = strdup(setlocale(LC_CTYPE, NULL)); + if (!saved_locale) + Py_FatalError("not enough memory to save locale"); + setlocale(LC_CTYPE, ""); #endif - if (sys_stdin != rl_instream || sys_stdout != rl_outstream) { - rl_instream = sys_stdin; - rl_outstream = sys_stdout; + if (sys_stdin != rl_instream || sys_stdout != rl_outstream) { + rl_instream = sys_stdin; + rl_outstream = sys_stdout; #ifdef HAVE_RL_COMPLETION_APPEND_CHARACTER - rl_prep_terminal (1); + rl_prep_terminal (1); #endif - } + } + + p = readline_until_enter_or_signal(prompt, &signal); - p = readline_until_enter_or_signal(prompt, &signal); - - /* we got an interrupt signal */ - if (signal) { - RESTORE_LOCALE(saved_locale) - return NULL; - } - - /* We got an EOF, return a empty string. */ - if (p == NULL) { - p = PyMem_Malloc(1); - if (p != NULL) - *p = '\0'; - RESTORE_LOCALE(saved_locale) - return p; - } - - /* we have a valid line */ - n = strlen(p); - if (n > 0) { - char *line; - HISTORY_STATE *state = history_get_history_state(); - if (state->length > 0) + /* we got an interrupt signal */ + if (signal) { + RESTORE_LOCALE(saved_locale) + return NULL; + } + + /* We got an EOF, return a empty string. */ + if (p == NULL) { + p = PyMem_Malloc(1); + if (p != NULL) + *p = '\0'; + RESTORE_LOCALE(saved_locale) + return p; + } + + /* we have a valid line */ + n = strlen(p); + if (n > 0) { + char *line; + HISTORY_STATE *state = history_get_history_state(); + if (state->length > 0) #ifdef __APPLE__ - if (using_libedit_emulation) { - /* - * Libedit's emulation uses 0-based indexes, - * the real readline uses 1-based indexes. - */ - line = history_get(state->length - 1)->line; - } else + if (using_libedit_emulation) { + /* + * Libedit's emulation uses 0-based indexes, + * the real readline uses 1-based indexes. + */ + line = history_get(state->length - 1)->line; + } else #endif /* __APPLE__ */ - line = history_get(state->length)->line; - else - line = ""; - if (strcmp(p, line)) - add_history(p); - /* the history docs don't say so, but the address of state - changes each time history_get_history_state is called - which makes me think it's freshly malloc'd memory... - on the other hand, the address of the last line stays the - same as long as history isn't extended, so it appears to - be malloc'd but managed by the history package... */ - free(state); - } - /* Copy the malloc'ed buffer into a PyMem_Malloc'ed one and - release the original. */ - q = p; - p = PyMem_Malloc(n+2); - if (p != NULL) { - strncpy(p, q, n); - p[n] = '\n'; - p[n+1] = '\0'; - } - free(q); - RESTORE_LOCALE(saved_locale) - return p; + line = history_get(state->length)->line; + else + line = ""; + if (strcmp(p, line)) + add_history(p); + /* the history docs don't say so, but the address of state + changes each time history_get_history_state is called + which makes me think it's freshly malloc'd memory... + on the other hand, the address of the last line stays the + same as long as history isn't extended, so it appears to + be malloc'd but managed by the history package... */ + free(state); + } + /* Copy the malloc'ed buffer into a PyMem_Malloc'ed one and + release the original. */ + q = p; + p = PyMem_Malloc(n+2); + if (p != NULL) { + strncpy(p, q, n); + p[n] = '\n'; + p[n+1] = '\0'; + } + free(q); + RESTORE_LOCALE(saved_locale) + return p; } @@ -1073,41 +1073,41 @@ #endif /* __APPLE__ */ static struct PyModuleDef readlinemodule = { - PyModuleDef_HEAD_INIT, - "readline", - doc_module, - -1, - readline_methods, - NULL, - NULL, - NULL, - NULL + PyModuleDef_HEAD_INIT, + "readline", + doc_module, + -1, + readline_methods, + NULL, + NULL, + NULL, + NULL }; PyMODINIT_FUNC PyInit_readline(void) { - PyObject *m; + PyObject *m; #ifdef __APPLE__ - if (strncmp(rl_library_version, libedit_version_tag, strlen(libedit_version_tag)) == 0) { - using_libedit_emulation = 1; - } + if (strncmp(rl_library_version, libedit_version_tag, strlen(libedit_version_tag)) == 0) { + using_libedit_emulation = 1; + } - if (using_libedit_emulation) - readlinemodule.m_doc = doc_module_le; + if (using_libedit_emulation) + readlinemodule.m_doc = doc_module_le; #endif /* __APPLE__ */ - m = PyModule_Create(&readlinemodule); + m = PyModule_Create(&readlinemodule); - if (m == NULL) - return NULL; + if (m == NULL) + return NULL; - PyOS_ReadlineFunctionPointer = call_readline; - setup_readline(); - return m; + PyOS_ReadlineFunctionPointer = call_readline; + setup_readline(); + return m; } Modified: python/branches/py3k/Modules/resource.c ============================================================================== --- python/branches/py3k/Modules/resource.c (original) +++ python/branches/py3k/Modules/resource.c Sun May 9 17:52:27 2010 @@ -29,30 +29,30 @@ "or via the attributes ru_utime, ru_stime, ru_maxrss, and so on."); static PyStructSequence_Field struct_rusage_fields[] = { - {"ru_utime", "user time used"}, - {"ru_stime", "system time used"}, - {"ru_maxrss", "max. resident set size"}, - {"ru_ixrss", "shared memory size"}, - {"ru_idrss", "unshared data size"}, - {"ru_isrss", "unshared stack size"}, - {"ru_minflt", "page faults not requiring I/O"}, - {"ru_majflt", "page faults requiring I/O"}, - {"ru_nswap", "number of swap outs"}, - {"ru_inblock", "block input operations"}, - {"ru_oublock", "block output operations"}, - {"ru_msgsnd", "IPC messages sent"}, - {"ru_msgrcv", "IPC messages received"}, - {"ru_nsignals", "signals received"}, - {"ru_nvcsw", "voluntary context switches"}, - {"ru_nivcsw", "involuntary context switches"}, - {0} + {"ru_utime", "user time used"}, + {"ru_stime", "system time used"}, + {"ru_maxrss", "max. resident set size"}, + {"ru_ixrss", "shared memory size"}, + {"ru_idrss", "unshared data size"}, + {"ru_isrss", "unshared stack size"}, + {"ru_minflt", "page faults not requiring I/O"}, + {"ru_majflt", "page faults requiring I/O"}, + {"ru_nswap", "number of swap outs"}, + {"ru_inblock", "block input operations"}, + {"ru_oublock", "block output operations"}, + {"ru_msgsnd", "IPC messages sent"}, + {"ru_msgrcv", "IPC messages received"}, + {"ru_nsignals", "signals received"}, + {"ru_nvcsw", "voluntary context switches"}, + {"ru_nivcsw", "involuntary context switches"}, + {0} }; static PyStructSequence_Desc struct_rusage_desc = { - "resource.struct_rusage", /* name */ - struct_rusage__doc__, /* doc */ - struct_rusage_fields, /* fields */ - 16 /* n_in_sequence */ + "resource.struct_rusage", /* name */ + struct_rusage__doc__, /* doc */ + struct_rusage_fields, /* fields */ + 16 /* n_in_sequence */ }; static int initialized; @@ -61,151 +61,151 @@ static PyObject * resource_getrusage(PyObject *self, PyObject *args) { - int who; - struct rusage ru; - PyObject *result; - - if (!PyArg_ParseTuple(args, "i:getrusage", &who)) - return NULL; - - if (getrusage(who, &ru) == -1) { - if (errno == EINVAL) { - PyErr_SetString(PyExc_ValueError, - "invalid who parameter"); - return NULL; - } - PyErr_SetFromErrno(ResourceError); - return NULL; - } - - result = PyStructSequence_New(&StructRUsageType); - if (!result) - return NULL; - - PyStructSequence_SET_ITEM(result, 0, - PyFloat_FromDouble(doubletime(ru.ru_utime))); - PyStructSequence_SET_ITEM(result, 1, - PyFloat_FromDouble(doubletime(ru.ru_stime))); - PyStructSequence_SET_ITEM(result, 2, PyLong_FromLong(ru.ru_maxrss)); - PyStructSequence_SET_ITEM(result, 3, PyLong_FromLong(ru.ru_ixrss)); - PyStructSequence_SET_ITEM(result, 4, PyLong_FromLong(ru.ru_idrss)); - PyStructSequence_SET_ITEM(result, 5, PyLong_FromLong(ru.ru_isrss)); - PyStructSequence_SET_ITEM(result, 6, PyLong_FromLong(ru.ru_minflt)); - PyStructSequence_SET_ITEM(result, 7, PyLong_FromLong(ru.ru_majflt)); - PyStructSequence_SET_ITEM(result, 8, PyLong_FromLong(ru.ru_nswap)); - PyStructSequence_SET_ITEM(result, 9, PyLong_FromLong(ru.ru_inblock)); - PyStructSequence_SET_ITEM(result, 10, PyLong_FromLong(ru.ru_oublock)); - PyStructSequence_SET_ITEM(result, 11, PyLong_FromLong(ru.ru_msgsnd)); - PyStructSequence_SET_ITEM(result, 12, PyLong_FromLong(ru.ru_msgrcv)); - PyStructSequence_SET_ITEM(result, 13, PyLong_FromLong(ru.ru_nsignals)); - PyStructSequence_SET_ITEM(result, 14, PyLong_FromLong(ru.ru_nvcsw)); - PyStructSequence_SET_ITEM(result, 15, PyLong_FromLong(ru.ru_nivcsw)); - - if (PyErr_Occurred()) { - Py_DECREF(result); - return NULL; - } + int who; + struct rusage ru; + PyObject *result; + + if (!PyArg_ParseTuple(args, "i:getrusage", &who)) + return NULL; + + if (getrusage(who, &ru) == -1) { + if (errno == EINVAL) { + PyErr_SetString(PyExc_ValueError, + "invalid who parameter"); + return NULL; + } + PyErr_SetFromErrno(ResourceError); + return NULL; + } + + result = PyStructSequence_New(&StructRUsageType); + if (!result) + return NULL; + + PyStructSequence_SET_ITEM(result, 0, + PyFloat_FromDouble(doubletime(ru.ru_utime))); + PyStructSequence_SET_ITEM(result, 1, + PyFloat_FromDouble(doubletime(ru.ru_stime))); + PyStructSequence_SET_ITEM(result, 2, PyLong_FromLong(ru.ru_maxrss)); + PyStructSequence_SET_ITEM(result, 3, PyLong_FromLong(ru.ru_ixrss)); + PyStructSequence_SET_ITEM(result, 4, PyLong_FromLong(ru.ru_idrss)); + PyStructSequence_SET_ITEM(result, 5, PyLong_FromLong(ru.ru_isrss)); + PyStructSequence_SET_ITEM(result, 6, PyLong_FromLong(ru.ru_minflt)); + PyStructSequence_SET_ITEM(result, 7, PyLong_FromLong(ru.ru_majflt)); + PyStructSequence_SET_ITEM(result, 8, PyLong_FromLong(ru.ru_nswap)); + PyStructSequence_SET_ITEM(result, 9, PyLong_FromLong(ru.ru_inblock)); + PyStructSequence_SET_ITEM(result, 10, PyLong_FromLong(ru.ru_oublock)); + PyStructSequence_SET_ITEM(result, 11, PyLong_FromLong(ru.ru_msgsnd)); + PyStructSequence_SET_ITEM(result, 12, PyLong_FromLong(ru.ru_msgrcv)); + PyStructSequence_SET_ITEM(result, 13, PyLong_FromLong(ru.ru_nsignals)); + PyStructSequence_SET_ITEM(result, 14, PyLong_FromLong(ru.ru_nvcsw)); + PyStructSequence_SET_ITEM(result, 15, PyLong_FromLong(ru.ru_nivcsw)); + + if (PyErr_Occurred()) { + Py_DECREF(result); + return NULL; + } - return result; + return result; } static PyObject * resource_getrlimit(PyObject *self, PyObject *args) { - struct rlimit rl; - int resource; + struct rlimit rl; + int resource; - if (!PyArg_ParseTuple(args, "i:getrlimit", &resource)) - return NULL; + if (!PyArg_ParseTuple(args, "i:getrlimit", &resource)) + return NULL; - if (resource < 0 || resource >= RLIM_NLIMITS) { - PyErr_SetString(PyExc_ValueError, - "invalid resource specified"); - return NULL; - } - - if (getrlimit(resource, &rl) == -1) { - PyErr_SetFromErrno(ResourceError); - return NULL; - } + if (resource < 0 || resource >= RLIM_NLIMITS) { + PyErr_SetString(PyExc_ValueError, + "invalid resource specified"); + return NULL; + } + + if (getrlimit(resource, &rl) == -1) { + PyErr_SetFromErrno(ResourceError); + return NULL; + } #if defined(HAVE_LONG_LONG) - if (sizeof(rl.rlim_cur) > sizeof(long)) { - return Py_BuildValue("LL", - (PY_LONG_LONG) rl.rlim_cur, - (PY_LONG_LONG) rl.rlim_max); - } + if (sizeof(rl.rlim_cur) > sizeof(long)) { + return Py_BuildValue("LL", + (PY_LONG_LONG) rl.rlim_cur, + (PY_LONG_LONG) rl.rlim_max); + } #endif - return Py_BuildValue("ll", (long) rl.rlim_cur, (long) rl.rlim_max); + return Py_BuildValue("ll", (long) rl.rlim_cur, (long) rl.rlim_max); } static PyObject * resource_setrlimit(PyObject *self, PyObject *args) { - struct rlimit rl; - int resource; - PyObject *curobj, *maxobj; - - if (!PyArg_ParseTuple(args, "i(OO):setrlimit", - &resource, &curobj, &maxobj)) - return NULL; - - if (resource < 0 || resource >= RLIM_NLIMITS) { - PyErr_SetString(PyExc_ValueError, - "invalid resource specified"); - return NULL; - } + struct rlimit rl; + int resource; + PyObject *curobj, *maxobj; + + if (!PyArg_ParseTuple(args, "i(OO):setrlimit", + &resource, &curobj, &maxobj)) + return NULL; + + if (resource < 0 || resource >= RLIM_NLIMITS) { + PyErr_SetString(PyExc_ValueError, + "invalid resource specified"); + return NULL; + } #if !defined(HAVE_LARGEFILE_SUPPORT) - rl.rlim_cur = PyLong_AsLong(curobj); - if (rl.rlim_cur == (rlim_t)-1 && PyErr_Occurred()) - return NULL; - rl.rlim_max = PyLong_AsLong(maxobj); - if (rl.rlim_max == (rlim_t)-1 && PyErr_Occurred()) - return NULL; + rl.rlim_cur = PyLong_AsLong(curobj); + if (rl.rlim_cur == (rlim_t)-1 && PyErr_Occurred()) + return NULL; + rl.rlim_max = PyLong_AsLong(maxobj); + if (rl.rlim_max == (rlim_t)-1 && PyErr_Occurred()) + return NULL; #else - /* The limits are probably bigger than a long */ - rl.rlim_cur = PyLong_AsLongLong(curobj); - if (rl.rlim_cur == (rlim_t)-1 && PyErr_Occurred()) - return NULL; - rl.rlim_max = PyLong_AsLongLong(maxobj); - if (rl.rlim_max == (rlim_t)-1 && PyErr_Occurred()) - return NULL; -#endif - - rl.rlim_cur = rl.rlim_cur & RLIM_INFINITY; - rl.rlim_max = rl.rlim_max & RLIM_INFINITY; - if (setrlimit(resource, &rl) == -1) { - if (errno == EINVAL) - PyErr_SetString(PyExc_ValueError, - "current limit exceeds maximum limit"); - else if (errno == EPERM) - PyErr_SetString(PyExc_ValueError, - "not allowed to raise maximum limit"); - else - PyErr_SetFromErrno(ResourceError); - return NULL; - } - Py_INCREF(Py_None); - return Py_None; + /* The limits are probably bigger than a long */ + rl.rlim_cur = PyLong_AsLongLong(curobj); + if (rl.rlim_cur == (rlim_t)-1 && PyErr_Occurred()) + return NULL; + rl.rlim_max = PyLong_AsLongLong(maxobj); + if (rl.rlim_max == (rlim_t)-1 && PyErr_Occurred()) + return NULL; +#endif + + rl.rlim_cur = rl.rlim_cur & RLIM_INFINITY; + rl.rlim_max = rl.rlim_max & RLIM_INFINITY; + if (setrlimit(resource, &rl) == -1) { + if (errno == EINVAL) + PyErr_SetString(PyExc_ValueError, + "current limit exceeds maximum limit"); + else if (errno == EPERM) + PyErr_SetString(PyExc_ValueError, + "not allowed to raise maximum limit"); + else + PyErr_SetFromErrno(ResourceError); + return NULL; + } + Py_INCREF(Py_None); + return Py_None; } static PyObject * resource_getpagesize(PyObject *self, PyObject *unused) { - long pagesize = 0; + long pagesize = 0; #if defined(HAVE_GETPAGESIZE) - pagesize = getpagesize(); + pagesize = getpagesize(); #elif defined(HAVE_SYSCONF) #if defined(_SC_PAGE_SIZE) - pagesize = sysconf(_SC_PAGE_SIZE); + pagesize = sysconf(_SC_PAGE_SIZE); #else - /* Irix 5.3 has _SC_PAGESIZE, but not _SC_PAGE_SIZE */ - pagesize = sysconf(_SC_PAGESIZE); + /* Irix 5.3 has _SC_PAGESIZE, but not _SC_PAGE_SIZE */ + pagesize = sysconf(_SC_PAGESIZE); #endif #endif - return Py_BuildValue("i", pagesize); + return Py_BuildValue("i", pagesize); } @@ -213,11 +213,11 @@ static struct PyMethodDef resource_methods[] = { - {"getrusage", resource_getrusage, METH_VARARGS}, - {"getrlimit", resource_getrlimit, METH_VARARGS}, - {"setrlimit", resource_setrlimit, METH_VARARGS}, - {"getpagesize", resource_getpagesize, METH_NOARGS}, - {NULL, NULL} /* sentinel */ + {"getrusage", resource_getrusage, METH_VARARGS}, + {"getrlimit", resource_getrlimit, METH_VARARGS}, + {"setrlimit", resource_setrlimit, METH_VARARGS}, + {"getpagesize", resource_getpagesize, METH_NOARGS}, + {NULL, NULL} /* sentinel */ }; @@ -225,117 +225,117 @@ static struct PyModuleDef resourcemodule = { - PyModuleDef_HEAD_INIT, - "resource", - NULL, - -1, - resource_methods, - NULL, - NULL, - NULL, - NULL + PyModuleDef_HEAD_INIT, + "resource", + NULL, + -1, + resource_methods, + NULL, + NULL, + NULL, + NULL }; PyMODINIT_FUNC PyInit_resource(void) { - PyObject *m, *v; + PyObject *m, *v; - /* Create the module and add the functions */ - m = PyModule_Create(&resourcemodule); - if (m == NULL) - return NULL; - - /* Add some symbolic constants to the module */ - if (ResourceError == NULL) { - ResourceError = PyErr_NewException("resource.error", - NULL, NULL); - } - Py_INCREF(ResourceError); - PyModule_AddObject(m, "error", ResourceError); - if (!initialized) - PyStructSequence_InitType(&StructRUsageType, - &struct_rusage_desc); - Py_INCREF(&StructRUsageType); - PyModule_AddObject(m, "struct_rusage", - (PyObject*) &StructRUsageType); + /* Create the module and add the functions */ + m = PyModule_Create(&resourcemodule); + if (m == NULL) + return NULL; + + /* Add some symbolic constants to the module */ + if (ResourceError == NULL) { + ResourceError = PyErr_NewException("resource.error", + NULL, NULL); + } + Py_INCREF(ResourceError); + PyModule_AddObject(m, "error", ResourceError); + if (!initialized) + PyStructSequence_InitType(&StructRUsageType, + &struct_rusage_desc); + Py_INCREF(&StructRUsageType); + PyModule_AddObject(m, "struct_rusage", + (PyObject*) &StructRUsageType); - /* insert constants */ + /* insert constants */ #ifdef RLIMIT_CPU - PyModule_AddIntConstant(m, "RLIMIT_CPU", RLIMIT_CPU); + PyModule_AddIntConstant(m, "RLIMIT_CPU", RLIMIT_CPU); #endif #ifdef RLIMIT_FSIZE - PyModule_AddIntConstant(m, "RLIMIT_FSIZE", RLIMIT_FSIZE); + PyModule_AddIntConstant(m, "RLIMIT_FSIZE", RLIMIT_FSIZE); #endif #ifdef RLIMIT_DATA - PyModule_AddIntConstant(m, "RLIMIT_DATA", RLIMIT_DATA); + PyModule_AddIntConstant(m, "RLIMIT_DATA", RLIMIT_DATA); #endif #ifdef RLIMIT_STACK - PyModule_AddIntConstant(m, "RLIMIT_STACK", RLIMIT_STACK); + PyModule_AddIntConstant(m, "RLIMIT_STACK", RLIMIT_STACK); #endif #ifdef RLIMIT_CORE - PyModule_AddIntConstant(m, "RLIMIT_CORE", RLIMIT_CORE); + PyModule_AddIntConstant(m, "RLIMIT_CORE", RLIMIT_CORE); #endif #ifdef RLIMIT_NOFILE - PyModule_AddIntConstant(m, "RLIMIT_NOFILE", RLIMIT_NOFILE); + PyModule_AddIntConstant(m, "RLIMIT_NOFILE", RLIMIT_NOFILE); #endif #ifdef RLIMIT_OFILE - PyModule_AddIntConstant(m, "RLIMIT_OFILE", RLIMIT_OFILE); + PyModule_AddIntConstant(m, "RLIMIT_OFILE", RLIMIT_OFILE); #endif #ifdef RLIMIT_VMEM - PyModule_AddIntConstant(m, "RLIMIT_VMEM", RLIMIT_VMEM); + PyModule_AddIntConstant(m, "RLIMIT_VMEM", RLIMIT_VMEM); #endif #ifdef RLIMIT_AS - PyModule_AddIntConstant(m, "RLIMIT_AS", RLIMIT_AS); + PyModule_AddIntConstant(m, "RLIMIT_AS", RLIMIT_AS); #endif #ifdef RLIMIT_RSS - PyModule_AddIntConstant(m, "RLIMIT_RSS", RLIMIT_RSS); + PyModule_AddIntConstant(m, "RLIMIT_RSS", RLIMIT_RSS); #endif #ifdef RLIMIT_NPROC - PyModule_AddIntConstant(m, "RLIMIT_NPROC", RLIMIT_NPROC); + PyModule_AddIntConstant(m, "RLIMIT_NPROC", RLIMIT_NPROC); #endif #ifdef RLIMIT_MEMLOCK - PyModule_AddIntConstant(m, "RLIMIT_MEMLOCK", RLIMIT_MEMLOCK); + PyModule_AddIntConstant(m, "RLIMIT_MEMLOCK", RLIMIT_MEMLOCK); #endif #ifdef RLIMIT_SBSIZE - PyModule_AddIntConstant(m, "RLIMIT_SBSIZE", RLIMIT_SBSIZE); + PyModule_AddIntConstant(m, "RLIMIT_SBSIZE", RLIMIT_SBSIZE); #endif #ifdef RUSAGE_SELF - PyModule_AddIntConstant(m, "RUSAGE_SELF", RUSAGE_SELF); + PyModule_AddIntConstant(m, "RUSAGE_SELF", RUSAGE_SELF); #endif #ifdef RUSAGE_CHILDREN - PyModule_AddIntConstant(m, "RUSAGE_CHILDREN", RUSAGE_CHILDREN); + PyModule_AddIntConstant(m, "RUSAGE_CHILDREN", RUSAGE_CHILDREN); #endif #ifdef RUSAGE_BOTH - PyModule_AddIntConstant(m, "RUSAGE_BOTH", RUSAGE_BOTH); + PyModule_AddIntConstant(m, "RUSAGE_BOTH", RUSAGE_BOTH); #endif #if defined(HAVE_LONG_LONG) - if (sizeof(RLIM_INFINITY) > sizeof(long)) { - v = PyLong_FromLongLong((PY_LONG_LONG) RLIM_INFINITY); - } else -#endif - { - v = PyLong_FromLong((long) RLIM_INFINITY); - } - if (v) { - PyModule_AddObject(m, "RLIM_INFINITY", v); - } - initialized = 1; - return m; + if (sizeof(RLIM_INFINITY) > sizeof(long)) { + v = PyLong_FromLongLong((PY_LONG_LONG) RLIM_INFINITY); + } else +#endif + { + v = PyLong_FromLong((long) RLIM_INFINITY); + } + if (v) { + PyModule_AddObject(m, "RLIM_INFINITY", v); + } + initialized = 1; + return m; } Modified: python/branches/py3k/Modules/rotatingtree.c ============================================================================== --- python/branches/py3k/Modules/rotatingtree.c (original) +++ python/branches/py3k/Modules/rotatingtree.c Sun May 9 17:52:27 2010 @@ -14,14 +14,14 @@ static int randombits(int bits) { - int result; - if (random_stream < (1U << bits)) { - random_value *= 1082527; - random_stream = random_value; - } - result = random_stream & ((1<>= bits; - return result; + int result; + if (random_stream < (1U << bits)) { + random_value *= 1082527; + random_stream = random_value; + } + result = random_stream & ((1<>= bits; + return result; } @@ -30,15 +30,15 @@ void RotatingTree_Add(rotating_node_t **root, rotating_node_t *node) { - while (*root != NULL) { - if (KEY_LOWER_THAN(node->key, (*root)->key)) - root = &((*root)->left); - else - root = &((*root)->right); - } - node->left = NULL; - node->right = NULL; - *root = node; + while (*root != NULL) { + if (KEY_LOWER_THAN(node->key, (*root)->key)) + root = &((*root)->left); + else + root = &((*root)->right); + } + node->left = NULL; + node->right = NULL; + *root = node; } /* Locate the node with the given key. This is the most complicated @@ -47,57 +47,57 @@ rotating_node_t * RotatingTree_Get(rotating_node_t **root, void *key) { - if (randombits(3) != 4) { - /* Fast path, no rebalancing */ - rotating_node_t *node = *root; - while (node != NULL) { - if (node->key == key) - return node; - if (KEY_LOWER_THAN(key, node->key)) - node = node->left; - else - node = node->right; - } - return NULL; - } - else { - rotating_node_t **pnode = root; - rotating_node_t *node = *pnode; - rotating_node_t *next; - int rotate; - if (node == NULL) - return NULL; - while (1) { - if (node->key == key) - return node; - rotate = !randombits(1); - if (KEY_LOWER_THAN(key, node->key)) { - next = node->left; - if (next == NULL) - return NULL; - if (rotate) { - node->left = next->right; - next->right = node; - *pnode = next; - } - else - pnode = &(node->left); - } - else { - next = node->right; - if (next == NULL) - return NULL; - if (rotate) { - node->right = next->left; - next->left = node; - *pnode = next; - } - else - pnode = &(node->right); - } - node = next; - } - } + if (randombits(3) != 4) { + /* Fast path, no rebalancing */ + rotating_node_t *node = *root; + while (node != NULL) { + if (node->key == key) + return node; + if (KEY_LOWER_THAN(key, node->key)) + node = node->left; + else + node = node->right; + } + return NULL; + } + else { + rotating_node_t **pnode = root; + rotating_node_t *node = *pnode; + rotating_node_t *next; + int rotate; + if (node == NULL) + return NULL; + while (1) { + if (node->key == key) + return node; + rotate = !randombits(1); + if (KEY_LOWER_THAN(key, node->key)) { + next = node->left; + if (next == NULL) + return NULL; + if (rotate) { + node->left = next->right; + next->right = node; + *pnode = next; + } + else + pnode = &(node->left); + } + else { + next = node->right; + if (next == NULL) + return NULL; + if (rotate) { + node->right = next->left; + next->left = node; + *pnode = next; + } + else + pnode = &(node->right); + } + node = next; + } + } } /* Enumerate all nodes in the tree. The callback enumfn() should return @@ -105,17 +105,17 @@ A non-zero value is directly returned by RotatingTree_Enum(). */ int RotatingTree_Enum(rotating_node_t *root, rotating_tree_enum_fn enumfn, - void *arg) + void *arg) { - int result; - rotating_node_t *node; - while (root != NULL) { - result = RotatingTree_Enum(root->left, enumfn, arg); - if (result != 0) return result; - node = root->right; - result = enumfn(root, arg); - if (result != 0) return result; - root = node; - } - return 0; + int result; + rotating_node_t *node; + while (root != NULL) { + result = RotatingTree_Enum(root->left, enumfn, arg); + if (result != 0) return result; + node = root->right; + result = enumfn(root, arg); + if (result != 0) return result; + root = node; + } + return 0; } Modified: python/branches/py3k/Modules/selectmodule.c ============================================================================== --- python/branches/py3k/Modules/selectmodule.c (original) +++ python/branches/py3k/Modules/selectmodule.c Sun May 9 17:52:27 2010 @@ -22,7 +22,7 @@ */ #if defined(MS_WINDOWS) && !defined(FD_SETSIZE) #define FD_SETSIZE 512 -#endif +#endif #if defined(HAVE_POLL_H) #include @@ -58,20 +58,20 @@ /* list of Python objects and their file descriptor */ typedef struct { - PyObject *obj; /* owned reference */ - SOCKET fd; - int sentinel; /* -1 == sentinel */ + PyObject *obj; /* owned reference */ + SOCKET fd; + int sentinel; /* -1 == sentinel */ } pylist; static void reap_obj(pylist fd2obj[FD_SETSIZE + 1]) { - int i; - for (i = 0; i < FD_SETSIZE + 1 && fd2obj[i].sentinel >= 0; i++) { - Py_XDECREF(fd2obj[i].obj); - fd2obj[i].obj = NULL; - } - fd2obj[0].sentinel = -1; + int i; + for (i = 0; i < FD_SETSIZE + 1 && fd2obj[i].sentinel >= 0; i++) { + Py_XDECREF(fd2obj[i].obj); + fd2obj[i].obj = NULL; + } + fd2obj[0].sentinel = -1; } @@ -81,106 +81,106 @@ static int seq2set(PyObject *seq, fd_set *set, pylist fd2obj[FD_SETSIZE + 1]) { - int i; - int max = -1; - int index = 0; - int len = -1; - PyObject* fast_seq = NULL; - PyObject* o = NULL; - - fd2obj[0].obj = (PyObject*)0; /* set list to zero size */ - FD_ZERO(set); + int i; + int max = -1; + int index = 0; + int len = -1; + PyObject* fast_seq = NULL; + PyObject* o = NULL; + + fd2obj[0].obj = (PyObject*)0; /* set list to zero size */ + FD_ZERO(set); + + fast_seq=PySequence_Fast(seq, "arguments 1-3 must be sequences"); + if (!fast_seq) + return -1; - fast_seq=PySequence_Fast(seq, "arguments 1-3 must be sequences"); - if (!fast_seq) - return -1; + len = PySequence_Fast_GET_SIZE(fast_seq); - len = PySequence_Fast_GET_SIZE(fast_seq); + for (i = 0; i < len; i++) { + SOCKET v; - for (i = 0; i < len; i++) { - SOCKET v; + /* any intervening fileno() calls could decr this refcnt */ + if (!(o = PySequence_Fast_GET_ITEM(fast_seq, i))) + return -1; - /* any intervening fileno() calls could decr this refcnt */ - if (!(o = PySequence_Fast_GET_ITEM(fast_seq, i))) - return -1; - - Py_INCREF(o); - v = PyObject_AsFileDescriptor( o ); - if (v == -1) goto finally; + Py_INCREF(o); + v = PyObject_AsFileDescriptor( o ); + if (v == -1) goto finally; #if defined(_MSC_VER) - max = 0; /* not used for Win32 */ + max = 0; /* not used for Win32 */ #else /* !_MSC_VER */ - if (v < 0 || v >= FD_SETSIZE) { - PyErr_SetString(PyExc_ValueError, - "filedescriptor out of range in select()"); - goto finally; - } - if (v > max) - max = v; + if (v < 0 || v >= FD_SETSIZE) { + PyErr_SetString(PyExc_ValueError, + "filedescriptor out of range in select()"); + goto finally; + } + if (v > max) + max = v; #endif /* _MSC_VER */ - FD_SET(v, set); + FD_SET(v, set); - /* add object and its file descriptor to the list */ - if (index >= FD_SETSIZE) { - PyErr_SetString(PyExc_ValueError, - "too many file descriptors in select()"); - goto finally; - } - fd2obj[index].obj = o; - fd2obj[index].fd = v; - fd2obj[index].sentinel = 0; - fd2obj[++index].sentinel = -1; - } - Py_DECREF(fast_seq); - return max+1; + /* add object and its file descriptor to the list */ + if (index >= FD_SETSIZE) { + PyErr_SetString(PyExc_ValueError, + "too many file descriptors in select()"); + goto finally; + } + fd2obj[index].obj = o; + fd2obj[index].fd = v; + fd2obj[index].sentinel = 0; + fd2obj[++index].sentinel = -1; + } + Py_DECREF(fast_seq); + return max+1; finally: - Py_XDECREF(o); - Py_DECREF(fast_seq); - return -1; + Py_XDECREF(o); + Py_DECREF(fast_seq); + return -1; } /* returns NULL and sets the Python exception if an error occurred */ static PyObject * set2list(fd_set *set, pylist fd2obj[FD_SETSIZE + 1]) { - int i, j, count=0; - PyObject *list, *o; - SOCKET fd; - - for (j = 0; fd2obj[j].sentinel >= 0; j++) { - if (FD_ISSET(fd2obj[j].fd, set)) - count++; - } - list = PyList_New(count); - if (!list) - return NULL; - - i = 0; - for (j = 0; fd2obj[j].sentinel >= 0; j++) { - fd = fd2obj[j].fd; - if (FD_ISSET(fd, set)) { + int i, j, count=0; + PyObject *list, *o; + SOCKET fd; + + for (j = 0; fd2obj[j].sentinel >= 0; j++) { + if (FD_ISSET(fd2obj[j].fd, set)) + count++; + } + list = PyList_New(count); + if (!list) + return NULL; + + i = 0; + for (j = 0; fd2obj[j].sentinel >= 0; j++) { + fd = fd2obj[j].fd; + if (FD_ISSET(fd, set)) { #ifndef _MSC_VER - if (fd > FD_SETSIZE) { - PyErr_SetString(PyExc_SystemError, - "filedescriptor out of range returned in select()"); - goto finally; - } -#endif - o = fd2obj[j].obj; - fd2obj[j].obj = NULL; - /* transfer ownership */ - if (PyList_SetItem(list, i, o) < 0) - goto finally; - - i++; - } - } - return list; + if (fd > FD_SETSIZE) { + PyErr_SetString(PyExc_SystemError, + "filedescriptor out of range returned in select()"); + goto finally; + } +#endif + o = fd2obj[j].obj; + fd2obj[j].obj = NULL; + /* transfer ownership */ + if (PyList_SetItem(list, i, o) < 0) + goto finally; + + i++; + } + } + return list; finally: - Py_DECREF(list); - return NULL; + Py_DECREF(list); + return NULL; } #undef SELECT_USES_HEAP @@ -192,170 +192,170 @@ select_select(PyObject *self, PyObject *args) { #ifdef SELECT_USES_HEAP - pylist *rfd2obj, *wfd2obj, *efd2obj; + pylist *rfd2obj, *wfd2obj, *efd2obj; #else /* !SELECT_USES_HEAP */ - /* XXX: All this should probably be implemented as follows: - * - find the highest descriptor we're interested in - * - add one - * - that's the size - * See: Stevens, APitUE, $12.5.1 - */ - pylist rfd2obj[FD_SETSIZE + 1]; - pylist wfd2obj[FD_SETSIZE + 1]; - pylist efd2obj[FD_SETSIZE + 1]; + /* XXX: All this should probably be implemented as follows: + * - find the highest descriptor we're interested in + * - add one + * - that's the size + * See: Stevens, APitUE, $12.5.1 + */ + pylist rfd2obj[FD_SETSIZE + 1]; + pylist wfd2obj[FD_SETSIZE + 1]; + pylist efd2obj[FD_SETSIZE + 1]; #endif /* SELECT_USES_HEAP */ - PyObject *ifdlist, *ofdlist, *efdlist; - PyObject *ret = NULL; - PyObject *tout = Py_None; - fd_set ifdset, ofdset, efdset; - double timeout; - struct timeval tv, *tvp; - long seconds; - int imax, omax, emax, max; - int n; - - /* convert arguments */ - if (!PyArg_UnpackTuple(args, "select", 3, 4, - &ifdlist, &ofdlist, &efdlist, &tout)) - return NULL; - - if (tout == Py_None) - tvp = (struct timeval *)0; - else if (!PyNumber_Check(tout)) { - PyErr_SetString(PyExc_TypeError, - "timeout must be a float or None"); - return NULL; - } - else { - timeout = PyFloat_AsDouble(tout); - if (timeout == -1 && PyErr_Occurred()) - return NULL; - if (timeout > (double)LONG_MAX) { - PyErr_SetString(PyExc_OverflowError, - "timeout period too long"); - return NULL; - } - seconds = (long)timeout; - timeout = timeout - (double)seconds; - tv.tv_sec = seconds; - tv.tv_usec = (long)(timeout * 1E6); - tvp = &tv; - } + PyObject *ifdlist, *ofdlist, *efdlist; + PyObject *ret = NULL; + PyObject *tout = Py_None; + fd_set ifdset, ofdset, efdset; + double timeout; + struct timeval tv, *tvp; + long seconds; + int imax, omax, emax, max; + int n; + + /* convert arguments */ + if (!PyArg_UnpackTuple(args, "select", 3, 4, + &ifdlist, &ofdlist, &efdlist, &tout)) + return NULL; + + if (tout == Py_None) + tvp = (struct timeval *)0; + else if (!PyNumber_Check(tout)) { + PyErr_SetString(PyExc_TypeError, + "timeout must be a float or None"); + return NULL; + } + else { + timeout = PyFloat_AsDouble(tout); + if (timeout == -1 && PyErr_Occurred()) + return NULL; + if (timeout > (double)LONG_MAX) { + PyErr_SetString(PyExc_OverflowError, + "timeout period too long"); + return NULL; + } + seconds = (long)timeout; + timeout = timeout - (double)seconds; + tv.tv_sec = seconds; + tv.tv_usec = (long)(timeout * 1E6); + tvp = &tv; + } #ifdef SELECT_USES_HEAP - /* Allocate memory for the lists */ - rfd2obj = PyMem_NEW(pylist, FD_SETSIZE + 1); - wfd2obj = PyMem_NEW(pylist, FD_SETSIZE + 1); - efd2obj = PyMem_NEW(pylist, FD_SETSIZE + 1); - if (rfd2obj == NULL || wfd2obj == NULL || efd2obj == NULL) { - if (rfd2obj) PyMem_DEL(rfd2obj); - if (wfd2obj) PyMem_DEL(wfd2obj); - if (efd2obj) PyMem_DEL(efd2obj); - return PyErr_NoMemory(); - } + /* Allocate memory for the lists */ + rfd2obj = PyMem_NEW(pylist, FD_SETSIZE + 1); + wfd2obj = PyMem_NEW(pylist, FD_SETSIZE + 1); + efd2obj = PyMem_NEW(pylist, FD_SETSIZE + 1); + if (rfd2obj == NULL || wfd2obj == NULL || efd2obj == NULL) { + if (rfd2obj) PyMem_DEL(rfd2obj); + if (wfd2obj) PyMem_DEL(wfd2obj); + if (efd2obj) PyMem_DEL(efd2obj); + return PyErr_NoMemory(); + } #endif /* SELECT_USES_HEAP */ - /* Convert sequences to fd_sets, and get maximum fd number - * propagates the Python exception set in seq2set() - */ - rfd2obj[0].sentinel = -1; - wfd2obj[0].sentinel = -1; - efd2obj[0].sentinel = -1; - if ((imax=seq2set(ifdlist, &ifdset, rfd2obj)) < 0) - goto finally; - if ((omax=seq2set(ofdlist, &ofdset, wfd2obj)) < 0) - goto finally; - if ((emax=seq2set(efdlist, &efdset, efd2obj)) < 0) - goto finally; - max = imax; - if (omax > max) max = omax; - if (emax > max) max = emax; - - Py_BEGIN_ALLOW_THREADS - n = select(max, &ifdset, &ofdset, &efdset, tvp); - Py_END_ALLOW_THREADS + /* Convert sequences to fd_sets, and get maximum fd number + * propagates the Python exception set in seq2set() + */ + rfd2obj[0].sentinel = -1; + wfd2obj[0].sentinel = -1; + efd2obj[0].sentinel = -1; + if ((imax=seq2set(ifdlist, &ifdset, rfd2obj)) < 0) + goto finally; + if ((omax=seq2set(ofdlist, &ofdset, wfd2obj)) < 0) + goto finally; + if ((emax=seq2set(efdlist, &efdset, efd2obj)) < 0) + goto finally; + max = imax; + if (omax > max) max = omax; + if (emax > max) max = emax; + + Py_BEGIN_ALLOW_THREADS + n = select(max, &ifdset, &ofdset, &efdset, tvp); + Py_END_ALLOW_THREADS #ifdef MS_WINDOWS - if (n == SOCKET_ERROR) { - PyErr_SetExcFromWindowsErr(SelectError, WSAGetLastError()); - } + if (n == SOCKET_ERROR) { + PyErr_SetExcFromWindowsErr(SelectError, WSAGetLastError()); + } #else - if (n < 0) { - PyErr_SetFromErrno(SelectError); - } -#endif - else { - /* any of these three calls can raise an exception. it's more - convenient to test for this after all three calls... but - is that acceptable? - */ - ifdlist = set2list(&ifdset, rfd2obj); - ofdlist = set2list(&ofdset, wfd2obj); - efdlist = set2list(&efdset, efd2obj); - if (PyErr_Occurred()) - ret = NULL; - else - ret = PyTuple_Pack(3, ifdlist, ofdlist, efdlist); - - Py_DECREF(ifdlist); - Py_DECREF(ofdlist); - Py_DECREF(efdlist); - } - + if (n < 0) { + PyErr_SetFromErrno(SelectError); + } +#endif + else { + /* any of these three calls can raise an exception. it's more + convenient to test for this after all three calls... but + is that acceptable? + */ + ifdlist = set2list(&ifdset, rfd2obj); + ofdlist = set2list(&ofdset, wfd2obj); + efdlist = set2list(&efdset, efd2obj); + if (PyErr_Occurred()) + ret = NULL; + else + ret = PyTuple_Pack(3, ifdlist, ofdlist, efdlist); + + Py_DECREF(ifdlist); + Py_DECREF(ofdlist); + Py_DECREF(efdlist); + } + finally: - reap_obj(rfd2obj); - reap_obj(wfd2obj); - reap_obj(efd2obj); + reap_obj(rfd2obj); + reap_obj(wfd2obj); + reap_obj(efd2obj); #ifdef SELECT_USES_HEAP - PyMem_DEL(rfd2obj); - PyMem_DEL(wfd2obj); - PyMem_DEL(efd2obj); + PyMem_DEL(rfd2obj); + PyMem_DEL(wfd2obj); + PyMem_DEL(efd2obj); #endif /* SELECT_USES_HEAP */ - return ret; + return ret; } #if defined(HAVE_POLL) && !defined(HAVE_BROKEN_POLL) -/* +/* * poll() support */ typedef struct { - PyObject_HEAD - PyObject *dict; - int ufd_uptodate; - int ufd_len; - struct pollfd *ufds; + PyObject_HEAD + PyObject *dict; + int ufd_uptodate; + int ufd_len; + struct pollfd *ufds; } pollObject; static PyTypeObject poll_Type; -/* Update the malloc'ed array of pollfds to match the dictionary +/* Update the malloc'ed array of pollfds to match the dictionary contained within a pollObject. Return 1 on success, 0 on an error. */ static int update_ufd_array(pollObject *self) { - Py_ssize_t i, pos; - PyObject *key, *value; - struct pollfd *old_ufds = self->ufds; - - self->ufd_len = PyDict_Size(self->dict); - PyMem_RESIZE(self->ufds, struct pollfd, self->ufd_len); - if (self->ufds == NULL) { - self->ufds = old_ufds; - PyErr_NoMemory(); - return 0; - } - - i = pos = 0; - while (PyDict_Next(self->dict, &pos, &key, &value)) { - self->ufds[i].fd = PyLong_AsLong(key); - self->ufds[i].events = (short)PyLong_AsLong(value); - i++; - } - self->ufd_uptodate = 1; - return 1; + Py_ssize_t i, pos; + PyObject *key, *value; + struct pollfd *old_ufds = self->ufds; + + self->ufd_len = PyDict_Size(self->dict); + PyMem_RESIZE(self->ufds, struct pollfd, self->ufd_len); + if (self->ufds == NULL) { + self->ufds = old_ufds; + PyErr_NoMemory(); + return 0; + } + + i = pos = 0; + while (PyDict_Next(self->dict, &pos, &key, &value)) { + self->ufds[i].fd = PyLong_AsLong(key); + self->ufds[i].events = (short)PyLong_AsLong(value); + i++; + } + self->ufd_uptodate = 1; + return 1; } PyDoc_STRVAR(poll_register_doc, @@ -366,39 +366,39 @@ events -- an optional bitmask describing the type of events to check for"); static PyObject * -poll_register(pollObject *self, PyObject *args) +poll_register(pollObject *self, PyObject *args) { - PyObject *o, *key, *value; - int fd, events = POLLIN | POLLPRI | POLLOUT; - int err; - - if (!PyArg_ParseTuple(args, "O|i:register", &o, &events)) { - return NULL; - } - - fd = PyObject_AsFileDescriptor(o); - if (fd == -1) return NULL; - - /* Add entry to the internal dictionary: the key is the - file descriptor, and the value is the event mask. */ - key = PyLong_FromLong(fd); - if (key == NULL) - return NULL; - value = PyLong_FromLong(events); - if (value == NULL) { - Py_DECREF(key); - return NULL; - } - err = PyDict_SetItem(self->dict, key, value); - Py_DECREF(key); - Py_DECREF(value); - if (err < 0) - return NULL; + PyObject *o, *key, *value; + int fd, events = POLLIN | POLLPRI | POLLOUT; + int err; + + if (!PyArg_ParseTuple(args, "O|i:register", &o, &events)) { + return NULL; + } + + fd = PyObject_AsFileDescriptor(o); + if (fd == -1) return NULL; + + /* Add entry to the internal dictionary: the key is the + file descriptor, and the value is the event mask. */ + key = PyLong_FromLong(fd); + if (key == NULL) + return NULL; + value = PyLong_FromLong(events); + if (value == NULL) { + Py_DECREF(key); + return NULL; + } + err = PyDict_SetItem(self->dict, key, value); + Py_DECREF(key); + Py_DECREF(value); + if (err < 0) + return NULL; - self->ufd_uptodate = 0; + self->ufd_uptodate = 0; - Py_INCREF(Py_None); - return Py_None; + Py_INCREF(Py_None); + return Py_None; } PyDoc_STRVAR(poll_modify_doc, @@ -411,41 +411,41 @@ static PyObject * poll_modify(pollObject *self, PyObject *args) { - PyObject *o, *key, *value; - int fd, events; - int err; - - if (!PyArg_ParseTuple(args, "Oi:modify", &o, &events)) { - return NULL; - } - - fd = PyObject_AsFileDescriptor(o); - if (fd == -1) return NULL; - - /* Modify registered fd */ - key = PyLong_FromLong(fd); - if (key == NULL) - return NULL; - if (PyDict_GetItem(self->dict, key) == NULL) { - errno = ENOENT; - PyErr_SetFromErrno(PyExc_IOError); - return NULL; - } - value = PyLong_FromLong(events); - if (value == NULL) { - Py_DECREF(key); - return NULL; - } - err = PyDict_SetItem(self->dict, key, value); - Py_DECREF(key); - Py_DECREF(value); - if (err < 0) - return NULL; + PyObject *o, *key, *value; + int fd, events; + int err; + + if (!PyArg_ParseTuple(args, "Oi:modify", &o, &events)) { + return NULL; + } + + fd = PyObject_AsFileDescriptor(o); + if (fd == -1) return NULL; + + /* Modify registered fd */ + key = PyLong_FromLong(fd); + if (key == NULL) + return NULL; + if (PyDict_GetItem(self->dict, key) == NULL) { + errno = ENOENT; + PyErr_SetFromErrno(PyExc_IOError); + return NULL; + } + value = PyLong_FromLong(events); + if (value == NULL) { + Py_DECREF(key); + return NULL; + } + err = PyDict_SetItem(self->dict, key, value); + Py_DECREF(key); + Py_DECREF(value); + if (err < 0) + return NULL; - self->ufd_uptodate = 0; + self->ufd_uptodate = 0; - Py_INCREF(Py_None); - return Py_None; + Py_INCREF(Py_None); + return Py_None; } @@ -454,32 +454,32 @@ Remove a file descriptor being tracked by the polling object."); static PyObject * -poll_unregister(pollObject *self, PyObject *o) +poll_unregister(pollObject *self, PyObject *o) { - PyObject *key; - int fd; + PyObject *key; + int fd; - fd = PyObject_AsFileDescriptor( o ); - if (fd == -1) - return NULL; - - /* Check whether the fd is already in the array */ - key = PyLong_FromLong(fd); - if (key == NULL) - return NULL; - - if (PyDict_DelItem(self->dict, key) == -1) { - Py_DECREF(key); - /* This will simply raise the KeyError set by PyDict_DelItem - if the file descriptor isn't registered. */ - return NULL; - } + fd = PyObject_AsFileDescriptor( o ); + if (fd == -1) + return NULL; + + /* Check whether the fd is already in the array */ + key = PyLong_FromLong(fd); + if (key == NULL) + return NULL; + + if (PyDict_DelItem(self->dict, key) == -1) { + Py_DECREF(key); + /* This will simply raise the KeyError set by PyDict_DelItem + if the file descriptor isn't registered. */ + return NULL; + } - Py_DECREF(key); - self->ufd_uptodate = 0; + Py_DECREF(key); + self->ufd_uptodate = 0; - Py_INCREF(Py_None); - return Py_None; + Py_INCREF(Py_None); + return Py_None; } PyDoc_STRVAR(poll_poll_doc, @@ -488,169 +488,169 @@ any descriptors that have events or errors to report."); static PyObject * -poll_poll(pollObject *self, PyObject *args) +poll_poll(pollObject *self, PyObject *args) { - PyObject *result_list = NULL, *tout = NULL; - int timeout = 0, poll_result, i, j; - PyObject *value = NULL, *num = NULL; - - if (!PyArg_UnpackTuple(args, "poll", 0, 1, &tout)) { - return NULL; - } - - /* Check values for timeout */ - if (tout == NULL || tout == Py_None) - timeout = -1; - else if (!PyNumber_Check(tout)) { - PyErr_SetString(PyExc_TypeError, - "timeout must be an integer or None"); - return NULL; - } - else { - tout = PyNumber_Long(tout); - if (!tout) - return NULL; - timeout = PyLong_AsLong(tout); - Py_DECREF(tout); - if (timeout == -1 && PyErr_Occurred()) - return NULL; - } - - /* Ensure the ufd array is up to date */ - if (!self->ufd_uptodate) - if (update_ufd_array(self) == 0) - return NULL; - - /* call poll() */ - Py_BEGIN_ALLOW_THREADS - poll_result = poll(self->ufds, self->ufd_len, timeout); - Py_END_ALLOW_THREADS - - if (poll_result < 0) { - PyErr_SetFromErrno(SelectError); - return NULL; - } - - /* build the result list */ - - result_list = PyList_New(poll_result); - if (!result_list) - return NULL; - else { - for (i = 0, j = 0; j < poll_result; j++) { - /* skip to the next fired descriptor */ - while (!self->ufds[i].revents) { - i++; - } - /* if we hit a NULL return, set value to NULL - and break out of loop; code at end will - clean up result_list */ - value = PyTuple_New(2); - if (value == NULL) - goto error; - num = PyLong_FromLong(self->ufds[i].fd); - if (num == NULL) { - Py_DECREF(value); - goto error; - } - PyTuple_SET_ITEM(value, 0, num); - - /* The &0xffff is a workaround for AIX. 'revents' - is a 16-bit short, and IBM assigned POLLNVAL - to be 0x8000, so the conversion to int results - in a negative number. See SF bug #923315. */ - num = PyLong_FromLong(self->ufds[i].revents & 0xffff); - if (num == NULL) { - Py_DECREF(value); - goto error; - } - PyTuple_SET_ITEM(value, 1, num); - if ((PyList_SetItem(result_list, j, value)) == -1) { - Py_DECREF(value); - goto error; - } - i++; - } - } - return result_list; + PyObject *result_list = NULL, *tout = NULL; + int timeout = 0, poll_result, i, j; + PyObject *value = NULL, *num = NULL; + + if (!PyArg_UnpackTuple(args, "poll", 0, 1, &tout)) { + return NULL; + } + + /* Check values for timeout */ + if (tout == NULL || tout == Py_None) + timeout = -1; + else if (!PyNumber_Check(tout)) { + PyErr_SetString(PyExc_TypeError, + "timeout must be an integer or None"); + return NULL; + } + else { + tout = PyNumber_Long(tout); + if (!tout) + return NULL; + timeout = PyLong_AsLong(tout); + Py_DECREF(tout); + if (timeout == -1 && PyErr_Occurred()) + return NULL; + } + + /* Ensure the ufd array is up to date */ + if (!self->ufd_uptodate) + if (update_ufd_array(self) == 0) + return NULL; + + /* call poll() */ + Py_BEGIN_ALLOW_THREADS + poll_result = poll(self->ufds, self->ufd_len, timeout); + Py_END_ALLOW_THREADS + + if (poll_result < 0) { + PyErr_SetFromErrno(SelectError); + return NULL; + } + + /* build the result list */ + + result_list = PyList_New(poll_result); + if (!result_list) + return NULL; + else { + for (i = 0, j = 0; j < poll_result; j++) { + /* skip to the next fired descriptor */ + while (!self->ufds[i].revents) { + i++; + } + /* if we hit a NULL return, set value to NULL + and break out of loop; code at end will + clean up result_list */ + value = PyTuple_New(2); + if (value == NULL) + goto error; + num = PyLong_FromLong(self->ufds[i].fd); + if (num == NULL) { + Py_DECREF(value); + goto error; + } + PyTuple_SET_ITEM(value, 0, num); + + /* The &0xffff is a workaround for AIX. 'revents' + is a 16-bit short, and IBM assigned POLLNVAL + to be 0x8000, so the conversion to int results + in a negative number. See SF bug #923315. */ + num = PyLong_FromLong(self->ufds[i].revents & 0xffff); + if (num == NULL) { + Py_DECREF(value); + goto error; + } + PyTuple_SET_ITEM(value, 1, num); + if ((PyList_SetItem(result_list, j, value)) == -1) { + Py_DECREF(value); + goto error; + } + i++; + } + } + return result_list; error: - Py_DECREF(result_list); - return NULL; + Py_DECREF(result_list); + return NULL; } static PyMethodDef poll_methods[] = { - {"register", (PyCFunction)poll_register, - METH_VARARGS, poll_register_doc}, - {"modify", (PyCFunction)poll_modify, - METH_VARARGS, poll_modify_doc}, - {"unregister", (PyCFunction)poll_unregister, - METH_O, poll_unregister_doc}, - {"poll", (PyCFunction)poll_poll, - METH_VARARGS, poll_poll_doc}, - {NULL, NULL} /* sentinel */ + {"register", (PyCFunction)poll_register, + METH_VARARGS, poll_register_doc}, + {"modify", (PyCFunction)poll_modify, + METH_VARARGS, poll_modify_doc}, + {"unregister", (PyCFunction)poll_unregister, + METH_O, poll_unregister_doc}, + {"poll", (PyCFunction)poll_poll, + METH_VARARGS, poll_poll_doc}, + {NULL, NULL} /* sentinel */ }; static pollObject * newPollObject(void) { - pollObject *self; - self = PyObject_New(pollObject, &poll_Type); - if (self == NULL) - return NULL; - /* ufd_uptodate is a Boolean, denoting whether the - array pointed to by ufds matches the contents of the dictionary. */ - self->ufd_uptodate = 0; - self->ufds = NULL; - self->dict = PyDict_New(); - if (self->dict == NULL) { - Py_DECREF(self); - return NULL; - } - return self; + pollObject *self; + self = PyObject_New(pollObject, &poll_Type); + if (self == NULL) + return NULL; + /* ufd_uptodate is a Boolean, denoting whether the + array pointed to by ufds matches the contents of the dictionary. */ + self->ufd_uptodate = 0; + self->ufds = NULL; + self->dict = PyDict_New(); + if (self->dict == NULL) { + Py_DECREF(self); + return NULL; + } + return self; } static void poll_dealloc(pollObject *self) { - if (self->ufds != NULL) - PyMem_DEL(self->ufds); - Py_XDECREF(self->dict); - PyObject_Del(self); + if (self->ufds != NULL) + PyMem_DEL(self->ufds); + Py_XDECREF(self->dict); + PyObject_Del(self); } static PyTypeObject poll_Type = { - /* The ob_type field must be initialized in the module init function - * to be portable to Windows without using C++. */ - PyVarObject_HEAD_INIT(NULL, 0) - "select.poll", /*tp_name*/ - sizeof(pollObject), /*tp_basicsize*/ - 0, /*tp_itemsize*/ - /* methods */ - (destructor)poll_dealloc, /*tp_dealloc*/ - 0, /*tp_print*/ - 0, /*tp_getattr*/ - 0, /*tp_setattr*/ - 0, /*tp_reserved*/ - 0, /*tp_repr*/ - 0, /*tp_as_number*/ - 0, /*tp_as_sequence*/ - 0, /*tp_as_mapping*/ - 0, /*tp_hash*/ - 0, /*tp_call*/ - 0, /*tp_str*/ - 0, /*tp_getattro*/ - 0, /*tp_setattro*/ - 0, /*tp_as_buffer*/ - Py_TPFLAGS_DEFAULT, /*tp_flags*/ - 0, /*tp_doc*/ - 0, /*tp_traverse*/ - 0, /*tp_clear*/ - 0, /*tp_richcompare*/ - 0, /*tp_weaklistoffset*/ - 0, /*tp_iter*/ - 0, /*tp_iternext*/ - poll_methods, /*tp_methods*/ + /* The ob_type field must be initialized in the module init function + * to be portable to Windows without using C++. */ + PyVarObject_HEAD_INIT(NULL, 0) + "select.poll", /*tp_name*/ + sizeof(pollObject), /*tp_basicsize*/ + 0, /*tp_itemsize*/ + /* methods */ + (destructor)poll_dealloc, /*tp_dealloc*/ + 0, /*tp_print*/ + 0, /*tp_getattr*/ + 0, /*tp_setattr*/ + 0, /*tp_reserved*/ + 0, /*tp_repr*/ + 0, /*tp_as_number*/ + 0, /*tp_as_sequence*/ + 0, /*tp_as_mapping*/ + 0, /*tp_hash*/ + 0, /*tp_call*/ + 0, /*tp_str*/ + 0, /*tp_getattro*/ + 0, /*tp_setattro*/ + 0, /*tp_as_buffer*/ + Py_TPFLAGS_DEFAULT, /*tp_flags*/ + 0, /*tp_doc*/ + 0, /*tp_traverse*/ + 0, /*tp_clear*/ + 0, /*tp_richcompare*/ + 0, /*tp_weaklistoffset*/ + 0, /*tp_iter*/ + 0, /*tp_iternext*/ + poll_methods, /*tp_methods*/ }; PyDoc_STRVAR(poll_doc, @@ -660,36 +660,36 @@ static PyObject * select_poll(PyObject *self, PyObject *unused) { - return (PyObject *)newPollObject(); + return (PyObject *)newPollObject(); } #ifdef __APPLE__ -/* +/* * On some systems poll() sets errno on invalid file descriptors. We test * for this at runtime because this bug may be fixed or introduced between * OS releases. */ static int select_have_broken_poll(void) { - int poll_test; - int filedes[2]; + int poll_test; + int filedes[2]; - struct pollfd poll_struct = { 0, POLLIN|POLLPRI|POLLOUT, 0 }; + struct pollfd poll_struct = { 0, POLLIN|POLLPRI|POLLOUT, 0 }; - /* Create a file descriptor to make invalid */ - if (pipe(filedes) < 0) { - return 1; - } - poll_struct.fd = filedes[0]; - close(filedes[0]); - close(filedes[1]); - poll_test = poll(&poll_struct, 1, 0); - if (poll_test < 0) { - return 1; - } else if (poll_test == 0 && poll_struct.revents != POLLNVAL) { - return 1; - } - return 0; + /* Create a file descriptor to make invalid */ + if (pipe(filedes) < 0) { + return 1; + } + poll_struct.fd = filedes[0]; + close(filedes[0]); + close(filedes[1]); + poll_test = poll(&poll_struct, 1, 0); + if (poll_test < 0) { + return 1; + } else if (poll_test == 0 && poll_struct.revents != POLLNVAL) { + return 1; + } + return 0; } #endif /* __APPLE__ */ @@ -708,8 +708,8 @@ #endif typedef struct { - PyObject_HEAD - SOCKET epfd; /* epoll control file descriptor */ + PyObject_HEAD + SOCKET epfd; /* epoll control file descriptor */ } pyEpoll_Object; static PyTypeObject pyEpoll_Type; @@ -718,92 +718,92 @@ static PyObject * pyepoll_err_closed(void) { - PyErr_SetString(PyExc_ValueError, "I/O operation on closed epoll fd"); - return NULL; + PyErr_SetString(PyExc_ValueError, "I/O operation on closed epoll fd"); + return NULL; } static int pyepoll_internal_close(pyEpoll_Object *self) { - int save_errno = 0; - if (self->epfd >= 0) { - int epfd = self->epfd; - self->epfd = -1; - Py_BEGIN_ALLOW_THREADS - if (close(epfd) < 0) - save_errno = errno; - Py_END_ALLOW_THREADS - } - return save_errno; + int save_errno = 0; + if (self->epfd >= 0) { + int epfd = self->epfd; + self->epfd = -1; + Py_BEGIN_ALLOW_THREADS + if (close(epfd) < 0) + save_errno = errno; + Py_END_ALLOW_THREADS + } + return save_errno; } static PyObject * newPyEpoll_Object(PyTypeObject *type, int sizehint, SOCKET fd) { - pyEpoll_Object *self; - - if (sizehint == -1) { - sizehint = FD_SETSIZE-1; - } - else if (sizehint < 1) { - PyErr_Format(PyExc_ValueError, - "sizehint must be greater zero, got %d", - sizehint); - return NULL; - } - - assert(type != NULL && type->tp_alloc != NULL); - self = (pyEpoll_Object *) type->tp_alloc(type, 0); - if (self == NULL) - return NULL; - - if (fd == -1) { - Py_BEGIN_ALLOW_THREADS - self->epfd = epoll_create(sizehint); - Py_END_ALLOW_THREADS - } - else { - self->epfd = fd; - } - if (self->epfd < 0) { - Py_DECREF(self); - PyErr_SetFromErrno(PyExc_IOError); - return NULL; - } - return (PyObject *)self; + pyEpoll_Object *self; + + if (sizehint == -1) { + sizehint = FD_SETSIZE-1; + } + else if (sizehint < 1) { + PyErr_Format(PyExc_ValueError, + "sizehint must be greater zero, got %d", + sizehint); + return NULL; + } + + assert(type != NULL && type->tp_alloc != NULL); + self = (pyEpoll_Object *) type->tp_alloc(type, 0); + if (self == NULL) + return NULL; + + if (fd == -1) { + Py_BEGIN_ALLOW_THREADS + self->epfd = epoll_create(sizehint); + Py_END_ALLOW_THREADS + } + else { + self->epfd = fd; + } + if (self->epfd < 0) { + Py_DECREF(self); + PyErr_SetFromErrno(PyExc_IOError); + return NULL; + } + return (PyObject *)self; } static PyObject * pyepoll_new(PyTypeObject *type, PyObject *args, PyObject *kwds) { - int sizehint = -1; - static char *kwlist[] = {"sizehint", NULL}; + int sizehint = -1; + static char *kwlist[] = {"sizehint", NULL}; - if (!PyArg_ParseTupleAndKeywords(args, kwds, "|i:epoll", kwlist, - &sizehint)) - return NULL; + if (!PyArg_ParseTupleAndKeywords(args, kwds, "|i:epoll", kwlist, + &sizehint)) + return NULL; - return newPyEpoll_Object(type, sizehint, -1); + return newPyEpoll_Object(type, sizehint, -1); } static void pyepoll_dealloc(pyEpoll_Object *self) { - (void)pyepoll_internal_close(self); - Py_TYPE(self)->tp_free(self); + (void)pyepoll_internal_close(self); + Py_TYPE(self)->tp_free(self); } static PyObject* pyepoll_close(pyEpoll_Object *self) { - errno = pyepoll_internal_close(self); - if (errno < 0) { - PyErr_SetFromErrno(PyExc_IOError); - return NULL; - } - Py_RETURN_NONE; + errno = pyepoll_internal_close(self); + if (errno < 0) { + PyErr_SetFromErrno(PyExc_IOError); + return NULL; + } + Py_RETURN_NONE; } PyDoc_STRVAR(pyepoll_close_doc, @@ -815,18 +815,18 @@ static PyObject* pyepoll_get_closed(pyEpoll_Object *self) { - if (self->epfd < 0) - Py_RETURN_TRUE; - else - Py_RETURN_FALSE; + if (self->epfd < 0) + Py_RETURN_TRUE; + else + Py_RETURN_FALSE; } static PyObject* pyepoll_fileno(pyEpoll_Object *self) { - if (self->epfd < 0) - return pyepoll_err_closed(); - return PyLong_FromLong(self->epfd); + if (self->epfd < 0) + return pyepoll_err_closed(); + return PyLong_FromLong(self->epfd); } PyDoc_STRVAR(pyepoll_fileno_doc, @@ -837,12 +837,12 @@ static PyObject* pyepoll_fromfd(PyObject *cls, PyObject *args) { - SOCKET fd; + SOCKET fd; - if (!PyArg_ParseTuple(args, "i:fromfd", &fd)) - return NULL; + if (!PyArg_ParseTuple(args, "i:fromfd", &fd)) + return NULL; - return newPyEpoll_Object((PyTypeObject*)cls, -1, fd); + return newPyEpoll_Object((PyTypeObject*)cls, -1, fd); } PyDoc_STRVAR(pyepoll_fromfd_doc, @@ -853,65 +853,65 @@ static PyObject * pyepoll_internal_ctl(int epfd, int op, PyObject *pfd, unsigned int events) { - struct epoll_event ev; - int result; - int fd; - - if (epfd < 0) - return pyepoll_err_closed(); - - fd = PyObject_AsFileDescriptor(pfd); - if (fd == -1) { - return NULL; - } - - switch(op) { - case EPOLL_CTL_ADD: - case EPOLL_CTL_MOD: - ev.events = events; - ev.data.fd = fd; - Py_BEGIN_ALLOW_THREADS - result = epoll_ctl(epfd, op, fd, &ev); - Py_END_ALLOW_THREADS - break; - case EPOLL_CTL_DEL: - /* In kernel versions before 2.6.9, the EPOLL_CTL_DEL - * operation required a non-NULL pointer in event, even - * though this argument is ignored. */ - Py_BEGIN_ALLOW_THREADS - result = epoll_ctl(epfd, op, fd, &ev); - if (errno == EBADF) { - /* fd already closed */ - result = 0; - errno = 0; - } - Py_END_ALLOW_THREADS - break; - default: - result = -1; - errno = EINVAL; - } - - if (result < 0) { - PyErr_SetFromErrno(PyExc_IOError); - return NULL; - } - Py_RETURN_NONE; + struct epoll_event ev; + int result; + int fd; + + if (epfd < 0) + return pyepoll_err_closed(); + + fd = PyObject_AsFileDescriptor(pfd); + if (fd == -1) { + return NULL; + } + + switch(op) { + case EPOLL_CTL_ADD: + case EPOLL_CTL_MOD: + ev.events = events; + ev.data.fd = fd; + Py_BEGIN_ALLOW_THREADS + result = epoll_ctl(epfd, op, fd, &ev); + Py_END_ALLOW_THREADS + break; + case EPOLL_CTL_DEL: + /* In kernel versions before 2.6.9, the EPOLL_CTL_DEL + * operation required a non-NULL pointer in event, even + * though this argument is ignored. */ + Py_BEGIN_ALLOW_THREADS + result = epoll_ctl(epfd, op, fd, &ev); + if (errno == EBADF) { + /* fd already closed */ + result = 0; + errno = 0; + } + Py_END_ALLOW_THREADS + break; + default: + result = -1; + errno = EINVAL; + } + + if (result < 0) { + PyErr_SetFromErrno(PyExc_IOError); + return NULL; + } + Py_RETURN_NONE; } static PyObject * pyepoll_register(pyEpoll_Object *self, PyObject *args, PyObject *kwds) { - PyObject *pfd; - unsigned int events = EPOLLIN | EPOLLOUT | EPOLLPRI; - static char *kwlist[] = {"fd", "eventmask", NULL}; - - if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|I:register", kwlist, - &pfd, &events)) { - return NULL; - } + PyObject *pfd; + unsigned int events = EPOLLIN | EPOLLOUT | EPOLLPRI; + static char *kwlist[] = {"fd", "eventmask", NULL}; + + if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|I:register", kwlist, + &pfd, &events)) { + return NULL; + } - return pyepoll_internal_ctl(self->epfd, EPOLL_CTL_ADD, pfd, events); + return pyepoll_internal_ctl(self->epfd, EPOLL_CTL_ADD, pfd, events); } PyDoc_STRVAR(pyepoll_register_doc, @@ -928,16 +928,16 @@ static PyObject * pyepoll_modify(pyEpoll_Object *self, PyObject *args, PyObject *kwds) { - PyObject *pfd; - unsigned int events; - static char *kwlist[] = {"fd", "eventmask", NULL}; - - if (!PyArg_ParseTupleAndKeywords(args, kwds, "OI:modify", kwlist, - &pfd, &events)) { - return NULL; - } + PyObject *pfd; + unsigned int events; + static char *kwlist[] = {"fd", "eventmask", NULL}; + + if (!PyArg_ParseTupleAndKeywords(args, kwds, "OI:modify", kwlist, + &pfd, &events)) { + return NULL; + } - return pyepoll_internal_ctl(self->epfd, EPOLL_CTL_MOD, pfd, events); + return pyepoll_internal_ctl(self->epfd, EPOLL_CTL_MOD, pfd, events); } PyDoc_STRVAR(pyepoll_modify_doc, @@ -949,15 +949,15 @@ static PyObject * pyepoll_unregister(pyEpoll_Object *self, PyObject *args, PyObject *kwds) { - PyObject *pfd; - static char *kwlist[] = {"fd", NULL}; + PyObject *pfd; + static char *kwlist[] = {"fd", NULL}; - if (!PyArg_ParseTupleAndKeywords(args, kwds, "O:unregister", kwlist, - &pfd)) { - return NULL; - } + if (!PyArg_ParseTupleAndKeywords(args, kwds, "O:unregister", kwlist, + &pfd)) { + return NULL; + } - return pyepoll_internal_ctl(self->epfd, EPOLL_CTL_DEL, pfd, 0); + return pyepoll_internal_ctl(self->epfd, EPOLL_CTL_DEL, pfd, 0); } PyDoc_STRVAR(pyepoll_unregister_doc, @@ -968,76 +968,76 @@ static PyObject * pyepoll_poll(pyEpoll_Object *self, PyObject *args, PyObject *kwds) { - double dtimeout = -1.; - int timeout; - int maxevents = -1; - int nfds, i; - PyObject *elist = NULL, *etuple = NULL; - struct epoll_event *evs = NULL; - static char *kwlist[] = {"timeout", "maxevents", NULL}; - - if (self->epfd < 0) - return pyepoll_err_closed(); - - if (!PyArg_ParseTupleAndKeywords(args, kwds, "|di:poll", kwlist, - &dtimeout, &maxevents)) { - return NULL; - } - - if (dtimeout < 0) { - timeout = -1; - } - else if (dtimeout * 1000.0 > INT_MAX) { - PyErr_SetString(PyExc_OverflowError, - "timeout is too large"); - return NULL; - } - else { - timeout = (int)(dtimeout * 1000.0); - } - - if (maxevents == -1) { - maxevents = FD_SETSIZE-1; - } - else if (maxevents < 1) { - PyErr_Format(PyExc_ValueError, - "maxevents must be greater than 0, got %d", - maxevents); - return NULL; - } - - evs = PyMem_New(struct epoll_event, maxevents); - if (evs == NULL) { - Py_DECREF(self); - PyErr_NoMemory(); - return NULL; - } - - Py_BEGIN_ALLOW_THREADS - nfds = epoll_wait(self->epfd, evs, maxevents, timeout); - Py_END_ALLOW_THREADS - if (nfds < 0) { - PyErr_SetFromErrno(PyExc_IOError); - goto error; - } - - elist = PyList_New(nfds); - if (elist == NULL) { - goto error; - } - - for (i = 0; i < nfds; i++) { - etuple = Py_BuildValue("iI", evs[i].data.fd, evs[i].events); - if (etuple == NULL) { - Py_CLEAR(elist); - goto error; - } - PyList_SET_ITEM(elist, i, etuple); - } + double dtimeout = -1.; + int timeout; + int maxevents = -1; + int nfds, i; + PyObject *elist = NULL, *etuple = NULL; + struct epoll_event *evs = NULL; + static char *kwlist[] = {"timeout", "maxevents", NULL}; + + if (self->epfd < 0) + return pyepoll_err_closed(); + + if (!PyArg_ParseTupleAndKeywords(args, kwds, "|di:poll", kwlist, + &dtimeout, &maxevents)) { + return NULL; + } + + if (dtimeout < 0) { + timeout = -1; + } + else if (dtimeout * 1000.0 > INT_MAX) { + PyErr_SetString(PyExc_OverflowError, + "timeout is too large"); + return NULL; + } + else { + timeout = (int)(dtimeout * 1000.0); + } + + if (maxevents == -1) { + maxevents = FD_SETSIZE-1; + } + else if (maxevents < 1) { + PyErr_Format(PyExc_ValueError, + "maxevents must be greater than 0, got %d", + maxevents); + return NULL; + } + + evs = PyMem_New(struct epoll_event, maxevents); + if (evs == NULL) { + Py_DECREF(self); + PyErr_NoMemory(); + return NULL; + } + + Py_BEGIN_ALLOW_THREADS + nfds = epoll_wait(self->epfd, evs, maxevents, timeout); + Py_END_ALLOW_THREADS + if (nfds < 0) { + PyErr_SetFromErrno(PyExc_IOError); + goto error; + } + + elist = PyList_New(nfds); + if (elist == NULL) { + goto error; + } + + for (i = 0; i < nfds; i++) { + etuple = Py_BuildValue("iI", evs[i].data.fd, evs[i].events); + if (etuple == NULL) { + Py_CLEAR(elist); + goto error; + } + PyList_SET_ITEM(elist, i, etuple); + } error: - PyMem_Free(evs); - return elist; + PyMem_Free(evs); + return elist; } PyDoc_STRVAR(pyepoll_poll_doc, @@ -1048,27 +1048,27 @@ Up to maxevents are returned to the caller."); static PyMethodDef pyepoll_methods[] = { - {"fromfd", (PyCFunction)pyepoll_fromfd, - METH_VARARGS | METH_CLASS, pyepoll_fromfd_doc}, - {"close", (PyCFunction)pyepoll_close, METH_NOARGS, - pyepoll_close_doc}, - {"fileno", (PyCFunction)pyepoll_fileno, METH_NOARGS, - pyepoll_fileno_doc}, - {"modify", (PyCFunction)pyepoll_modify, - METH_VARARGS | METH_KEYWORDS, pyepoll_modify_doc}, - {"register", (PyCFunction)pyepoll_register, - METH_VARARGS | METH_KEYWORDS, pyepoll_register_doc}, - {"unregister", (PyCFunction)pyepoll_unregister, - METH_VARARGS | METH_KEYWORDS, pyepoll_unregister_doc}, - {"poll", (PyCFunction)pyepoll_poll, - METH_VARARGS | METH_KEYWORDS, pyepoll_poll_doc}, - {NULL, NULL}, + {"fromfd", (PyCFunction)pyepoll_fromfd, + METH_VARARGS | METH_CLASS, pyepoll_fromfd_doc}, + {"close", (PyCFunction)pyepoll_close, METH_NOARGS, + pyepoll_close_doc}, + {"fileno", (PyCFunction)pyepoll_fileno, METH_NOARGS, + pyepoll_fileno_doc}, + {"modify", (PyCFunction)pyepoll_modify, + METH_VARARGS | METH_KEYWORDS, pyepoll_modify_doc}, + {"register", (PyCFunction)pyepoll_register, + METH_VARARGS | METH_KEYWORDS, pyepoll_register_doc}, + {"unregister", (PyCFunction)pyepoll_unregister, + METH_VARARGS | METH_KEYWORDS, pyepoll_unregister_doc}, + {"poll", (PyCFunction)pyepoll_poll, + METH_VARARGS | METH_KEYWORDS, pyepoll_poll_doc}, + {NULL, NULL}, }; static PyGetSetDef pyepoll_getsetlist[] = { - {"closed", (getter)pyepoll_get_closed, NULL, - "True if the epoll handler is closed"}, - {0}, + {"closed", (getter)pyepoll_get_closed, NULL, + "True if the epoll handler is closed"}, + {0}, }; PyDoc_STRVAR(pyepoll_doc, @@ -1081,45 +1081,45 @@ the maximum number of monitored events."); static PyTypeObject pyEpoll_Type = { - PyVarObject_HEAD_INIT(NULL, 0) - "select.epoll", /* tp_name */ - sizeof(pyEpoll_Object), /* tp_basicsize */ - 0, /* tp_itemsize */ - (destructor)pyepoll_dealloc, /* tp_dealloc */ - 0, /* tp_print */ - 0, /* tp_getattr */ - 0, /* tp_setattr */ - 0, /* tp_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, /* tp_flags */ - pyepoll_doc, /* tp_doc */ - 0, /* tp_traverse */ - 0, /* tp_clear */ - 0, /* tp_richcompare */ - 0, /* tp_weaklistoffset */ - 0, /* tp_iter */ - 0, /* tp_iternext */ - pyepoll_methods, /* tp_methods */ - 0, /* tp_members */ - pyepoll_getsetlist, /* tp_getset */ - 0, /* tp_base */ - 0, /* tp_dict */ - 0, /* tp_descr_get */ - 0, /* tp_descr_set */ - 0, /* tp_dictoffset */ - 0, /* tp_init */ - 0, /* tp_alloc */ - pyepoll_new, /* tp_new */ - 0, /* tp_free */ + PyVarObject_HEAD_INIT(NULL, 0) + "select.epoll", /* tp_name */ + sizeof(pyEpoll_Object), /* tp_basicsize */ + 0, /* tp_itemsize */ + (destructor)pyepoll_dealloc, /* tp_dealloc */ + 0, /* tp_print */ + 0, /* tp_getattr */ + 0, /* tp_setattr */ + 0, /* tp_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, /* tp_flags */ + pyepoll_doc, /* tp_doc */ + 0, /* tp_traverse */ + 0, /* tp_clear */ + 0, /* tp_richcompare */ + 0, /* tp_weaklistoffset */ + 0, /* tp_iter */ + 0, /* tp_iternext */ + pyepoll_methods, /* tp_methods */ + 0, /* tp_members */ + pyepoll_getsetlist, /* tp_getset */ + 0, /* tp_base */ + 0, /* tp_dict */ + 0, /* tp_descr_get */ + 0, /* tp_descr_set */ + 0, /* tp_dictoffset */ + 0, /* tp_init */ + 0, /* tp_alloc */ + pyepoll_new, /* tp_new */ + 0, /* tp_free */ }; #endif /* HAVE_EPOLL */ @@ -1174,8 +1174,8 @@ udata->object mapping."); typedef struct { - PyObject_HEAD - struct kevent e; + PyObject_HEAD + struct kevent e; } kqueue_event_Object; static PyTypeObject kqueue_event_Type; @@ -1183,8 +1183,8 @@ #define kqueue_event_Check(op) (PyObject_TypeCheck((op), &kqueue_event_Type)) typedef struct { - PyObject_HEAD - SOCKET kqfd; /* kqueue control fd */ + PyObject_HEAD + SOCKET kqfd; /* kqueue control fd */ } kqueue_queue_Object; static PyTypeObject kqueue_queue_Type; @@ -1222,13 +1222,13 @@ #define KQ_OFF(x) offsetof(kqueue_event_Object, x) static struct PyMemberDef kqueue_event_members[] = { - {"ident", T_UINTPTRT, KQ_OFF(e.ident)}, - {"filter", T_SHORT, KQ_OFF(e.filter)}, - {"flags", T_USHORT, KQ_OFF(e.flags)}, - {"fflags", T_UINT, KQ_OFF(e.fflags)}, - {"data", T_INTPTRT, KQ_OFF(e.data)}, - {"udata", T_UINTPTRT, KQ_OFF(e.udata)}, - {NULL} /* Sentinel */ + {"ident", T_UINTPTRT, KQ_OFF(e.ident)}, + {"filter", T_SHORT, KQ_OFF(e.filter)}, + {"flags", T_USHORT, KQ_OFF(e.flags)}, + {"fflags", T_UINT, KQ_OFF(e.fflags)}, + {"data", T_INTPTRT, KQ_OFF(e.data)}, + {"udata", T_UINTPTRT, KQ_OFF(e.udata)}, + {NULL} /* Sentinel */ }; #undef KQ_OFF @@ -1236,214 +1236,214 @@ kqueue_event_repr(kqueue_event_Object *s) { - char buf[1024]; - PyOS_snprintf( - buf, sizeof(buf), - "", - (size_t)(s->e.ident), s->e.filter, s->e.flags, - s->e.fflags, (Py_ssize_t)(s->e.data), s->e.udata); - return PyUnicode_FromString(buf); + char buf[1024]; + PyOS_snprintf( + buf, sizeof(buf), + "", + (size_t)(s->e.ident), s->e.filter, s->e.flags, + s->e.fflags, (Py_ssize_t)(s->e.data), s->e.udata); + return PyUnicode_FromString(buf); } static int kqueue_event_init(kqueue_event_Object *self, PyObject *args, PyObject *kwds) { - PyObject *pfd; - static char *kwlist[] = {"ident", "filter", "flags", "fflags", - "data", "udata", NULL}; - static char *fmt = "O|hhi" INTPTRT_FMT_UNIT UINTPTRT_FMT_UNIT ":kevent"; - - EV_SET(&(self->e), 0, EVFILT_READ, EV_ADD, 0, 0, 0); /* defaults */ - - if (!PyArg_ParseTupleAndKeywords(args, kwds, fmt, kwlist, - &pfd, &(self->e.filter), &(self->e.flags), - &(self->e.fflags), &(self->e.data), &(self->e.udata))) { - return -1; - } - - if (PyLong_Check(pfd)) { - self->e.ident = PyLong_AsUintptr_t(pfd); - } - else { - self->e.ident = PyObject_AsFileDescriptor(pfd); - } - if (PyErr_Occurred()) { - return -1; - } - return 0; + PyObject *pfd; + static char *kwlist[] = {"ident", "filter", "flags", "fflags", + "data", "udata", NULL}; + static char *fmt = "O|hhi" INTPTRT_FMT_UNIT UINTPTRT_FMT_UNIT ":kevent"; + + EV_SET(&(self->e), 0, EVFILT_READ, EV_ADD, 0, 0, 0); /* defaults */ + + if (!PyArg_ParseTupleAndKeywords(args, kwds, fmt, kwlist, + &pfd, &(self->e.filter), &(self->e.flags), + &(self->e.fflags), &(self->e.data), &(self->e.udata))) { + return -1; + } + + if (PyLong_Check(pfd)) { + self->e.ident = PyLong_AsUintptr_t(pfd); + } + else { + self->e.ident = PyObject_AsFileDescriptor(pfd); + } + if (PyErr_Occurred()) { + return -1; + } + return 0; } static PyObject * kqueue_event_richcompare(kqueue_event_Object *s, kqueue_event_Object *o, - int op) + int op) { - Py_intptr_t result = 0; + Py_intptr_t result = 0; - if (!kqueue_event_Check(o)) { - if (op == Py_EQ || op == Py_NE) { - PyObject *res = op == Py_EQ ? Py_False : Py_True; - Py_INCREF(res); - return res; - } - PyErr_Format(PyExc_TypeError, - "can't compare %.200s to %.200s", - Py_TYPE(s)->tp_name, Py_TYPE(o)->tp_name); - return NULL; - } - if (((result = s->e.ident - o->e.ident) == 0) && - ((result = s->e.filter - o->e.filter) == 0) && - ((result = s->e.flags - o->e.flags) == 0) && - ((result = s->e.fflags - o->e.fflags) == 0) && - ((result = s->e.data - o->e.data) == 0) && - ((result = s->e.udata - o->e.udata) == 0) - ) { - result = 0; - } - - switch (op) { - case Py_EQ: - result = (result == 0); - break; - case Py_NE: - result = (result != 0); - break; - case Py_LE: - result = (result <= 0); - break; - case Py_GE: - result = (result >= 0); - break; - case Py_LT: - result = (result < 0); - break; - case Py_GT: - result = (result > 0); - break; - } - return PyBool_FromLong((long)result); + if (!kqueue_event_Check(o)) { + if (op == Py_EQ || op == Py_NE) { + PyObject *res = op == Py_EQ ? Py_False : Py_True; + Py_INCREF(res); + return res; + } + PyErr_Format(PyExc_TypeError, + "can't compare %.200s to %.200s", + Py_TYPE(s)->tp_name, Py_TYPE(o)->tp_name); + return NULL; + } + if (((result = s->e.ident - o->e.ident) == 0) && + ((result = s->e.filter - o->e.filter) == 0) && + ((result = s->e.flags - o->e.flags) == 0) && + ((result = s->e.fflags - o->e.fflags) == 0) && + ((result = s->e.data - o->e.data) == 0) && + ((result = s->e.udata - o->e.udata) == 0) + ) { + result = 0; + } + + switch (op) { + case Py_EQ: + result = (result == 0); + break; + case Py_NE: + result = (result != 0); + break; + case Py_LE: + result = (result <= 0); + break; + case Py_GE: + result = (result >= 0); + break; + case Py_LT: + result = (result < 0); + break; + case Py_GT: + result = (result > 0); + break; + } + return PyBool_FromLong((long)result); } static PyTypeObject kqueue_event_Type = { - PyVarObject_HEAD_INIT(NULL, 0) - "select.kevent", /* tp_name */ - sizeof(kqueue_event_Object), /* tp_basicsize */ - 0, /* tp_itemsize */ - 0, /* tp_dealloc */ - 0, /* tp_print */ - 0, /* tp_getattr */ - 0, /* tp_setattr */ - 0, /* tp_reserved */ - (reprfunc)kqueue_event_repr, /* tp_repr */ - 0, /* tp_as_number */ - 0, /* tp_as_sequence */ - 0, /* tp_as_mapping */ - 0, /* tp_hash */ - 0, /* tp_call */ - 0, /* tp_str */ - 0, /* tp_getattro */ - 0, /* tp_setattro */ - 0, /* tp_as_buffer */ - Py_TPFLAGS_DEFAULT, /* tp_flags */ - kqueue_event_doc, /* tp_doc */ - 0, /* tp_traverse */ - 0, /* tp_clear */ - (richcmpfunc)kqueue_event_richcompare, /* tp_richcompare */ - 0, /* tp_weaklistoffset */ - 0, /* tp_iter */ - 0, /* tp_iternext */ - 0, /* tp_methods */ - kqueue_event_members, /* tp_members */ - 0, /* tp_getset */ - 0, /* tp_base */ - 0, /* tp_dict */ - 0, /* tp_descr_get */ - 0, /* tp_descr_set */ - 0, /* tp_dictoffset */ - (initproc)kqueue_event_init, /* tp_init */ - 0, /* tp_alloc */ - 0, /* tp_new */ - 0, /* tp_free */ + PyVarObject_HEAD_INIT(NULL, 0) + "select.kevent", /* tp_name */ + sizeof(kqueue_event_Object), /* tp_basicsize */ + 0, /* tp_itemsize */ + 0, /* tp_dealloc */ + 0, /* tp_print */ + 0, /* tp_getattr */ + 0, /* tp_setattr */ + 0, /* tp_reserved */ + (reprfunc)kqueue_event_repr, /* tp_repr */ + 0, /* tp_as_number */ + 0, /* tp_as_sequence */ + 0, /* tp_as_mapping */ + 0, /* tp_hash */ + 0, /* tp_call */ + 0, /* tp_str */ + 0, /* tp_getattro */ + 0, /* tp_setattro */ + 0, /* tp_as_buffer */ + Py_TPFLAGS_DEFAULT, /* tp_flags */ + kqueue_event_doc, /* tp_doc */ + 0, /* tp_traverse */ + 0, /* tp_clear */ + (richcmpfunc)kqueue_event_richcompare, /* tp_richcompare */ + 0, /* tp_weaklistoffset */ + 0, /* tp_iter */ + 0, /* tp_iternext */ + 0, /* tp_methods */ + kqueue_event_members, /* tp_members */ + 0, /* tp_getset */ + 0, /* tp_base */ + 0, /* tp_dict */ + 0, /* tp_descr_get */ + 0, /* tp_descr_set */ + 0, /* tp_dictoffset */ + (initproc)kqueue_event_init, /* tp_init */ + 0, /* tp_alloc */ + 0, /* tp_new */ + 0, /* tp_free */ }; static PyObject * kqueue_queue_err_closed(void) { - PyErr_SetString(PyExc_ValueError, "I/O operation on closed kqueue fd"); - return NULL; + PyErr_SetString(PyExc_ValueError, "I/O operation on closed kqueue fd"); + return NULL; } static int kqueue_queue_internal_close(kqueue_queue_Object *self) { - int save_errno = 0; - if (self->kqfd >= 0) { - int kqfd = self->kqfd; - self->kqfd = -1; - Py_BEGIN_ALLOW_THREADS - if (close(kqfd) < 0) - save_errno = errno; - Py_END_ALLOW_THREADS - } - return save_errno; + int save_errno = 0; + if (self->kqfd >= 0) { + int kqfd = self->kqfd; + self->kqfd = -1; + Py_BEGIN_ALLOW_THREADS + if (close(kqfd) < 0) + save_errno = errno; + Py_END_ALLOW_THREADS + } + return save_errno; } static PyObject * newKqueue_Object(PyTypeObject *type, SOCKET fd) { - kqueue_queue_Object *self; - assert(type != NULL && type->tp_alloc != NULL); - self = (kqueue_queue_Object *) type->tp_alloc(type, 0); - if (self == NULL) { - return NULL; - } - - if (fd == -1) { - Py_BEGIN_ALLOW_THREADS - self->kqfd = kqueue(); - Py_END_ALLOW_THREADS - } - else { - self->kqfd = fd; - } - if (self->kqfd < 0) { - Py_DECREF(self); - PyErr_SetFromErrno(PyExc_IOError); - return NULL; - } - return (PyObject *)self; + kqueue_queue_Object *self; + assert(type != NULL && type->tp_alloc != NULL); + self = (kqueue_queue_Object *) type->tp_alloc(type, 0); + if (self == NULL) { + return NULL; + } + + if (fd == -1) { + Py_BEGIN_ALLOW_THREADS + self->kqfd = kqueue(); + Py_END_ALLOW_THREADS + } + else { + self->kqfd = fd; + } + if (self->kqfd < 0) { + Py_DECREF(self); + PyErr_SetFromErrno(PyExc_IOError); + return NULL; + } + return (PyObject *)self; } static PyObject * kqueue_queue_new(PyTypeObject *type, PyObject *args, PyObject *kwds) { - if ((args != NULL && PyObject_Size(args)) || - (kwds != NULL && PyObject_Size(kwds))) { - PyErr_SetString(PyExc_ValueError, - "select.kqueue doesn't accept arguments"); - return NULL; - } + if ((args != NULL && PyObject_Size(args)) || + (kwds != NULL && PyObject_Size(kwds))) { + PyErr_SetString(PyExc_ValueError, + "select.kqueue doesn't accept arguments"); + return NULL; + } - return newKqueue_Object(type, -1); + return newKqueue_Object(type, -1); } static void kqueue_queue_dealloc(kqueue_queue_Object *self) { - kqueue_queue_internal_close(self); - Py_TYPE(self)->tp_free(self); + kqueue_queue_internal_close(self); + Py_TYPE(self)->tp_free(self); } static PyObject* kqueue_queue_close(kqueue_queue_Object *self) { - errno = kqueue_queue_internal_close(self); - if (errno < 0) { - PyErr_SetFromErrno(PyExc_IOError); - return NULL; - } - Py_RETURN_NONE; + errno = kqueue_queue_internal_close(self); + if (errno < 0) { + PyErr_SetFromErrno(PyExc_IOError); + return NULL; + } + Py_RETURN_NONE; } PyDoc_STRVAR(kqueue_queue_close_doc, @@ -1455,18 +1455,18 @@ static PyObject* kqueue_queue_get_closed(kqueue_queue_Object *self) { - if (self->kqfd < 0) - Py_RETURN_TRUE; - else - Py_RETURN_FALSE; + if (self->kqfd < 0) + Py_RETURN_TRUE; + else + Py_RETURN_FALSE; } static PyObject* kqueue_queue_fileno(kqueue_queue_Object *self) { - if (self->kqfd < 0) - return kqueue_queue_err_closed(); - return PyLong_FromLong(self->kqfd); + if (self->kqfd < 0) + return kqueue_queue_err_closed(); + return PyLong_FromLong(self->kqfd); } PyDoc_STRVAR(kqueue_queue_fileno_doc, @@ -1477,12 +1477,12 @@ static PyObject* kqueue_queue_fromfd(PyObject *cls, PyObject *args) { - SOCKET fd; + SOCKET fd; - if (!PyArg_ParseTuple(args, "i:fromfd", &fd)) - return NULL; + if (!PyArg_ParseTuple(args, "i:fromfd", &fd)) + return NULL; - return newKqueue_Object((PyTypeObject*)cls, fd); + return newKqueue_Object((PyTypeObject*)cls, fd); } PyDoc_STRVAR(kqueue_queue_fromfd_doc, @@ -1493,144 +1493,144 @@ static PyObject * kqueue_queue_control(kqueue_queue_Object *self, PyObject *args) { - int nevents = 0; - int gotevents = 0; - int nchanges = 0; - int i = 0; - PyObject *otimeout = NULL; - PyObject *ch = NULL; - PyObject *it = NULL, *ei = NULL; - PyObject *result = NULL; - struct kevent *evl = NULL; - struct kevent *chl = NULL; - struct timespec timeoutspec; - struct timespec *ptimeoutspec; - - if (self->kqfd < 0) - return kqueue_queue_err_closed(); - - if (!PyArg_ParseTuple(args, "Oi|O:control", &ch, &nevents, &otimeout)) - return NULL; - - if (nevents < 0) { - PyErr_Format(PyExc_ValueError, - "Length of eventlist must be 0 or positive, got %d", - nevents); - return NULL; - } - - if (otimeout == Py_None || otimeout == NULL) { - ptimeoutspec = NULL; - } - else if (PyNumber_Check(otimeout)) { - double timeout; - long seconds; - - timeout = PyFloat_AsDouble(otimeout); - if (timeout == -1 && PyErr_Occurred()) - return NULL; - if (timeout > (double)LONG_MAX) { - PyErr_SetString(PyExc_OverflowError, - "timeout period too long"); - return NULL; - } - if (timeout < 0) { - PyErr_SetString(PyExc_ValueError, - "timeout must be positive or None"); - return NULL; - } - - seconds = (long)timeout; - timeout = timeout - (double)seconds; - timeoutspec.tv_sec = seconds; - timeoutspec.tv_nsec = (long)(timeout * 1E9); - ptimeoutspec = &timeoutspec; - } - else { - PyErr_Format(PyExc_TypeError, - "timeout argument must be an number " - "or None, got %.200s", - Py_TYPE(otimeout)->tp_name); - return NULL; - } - - if (ch != NULL && ch != Py_None) { - it = PyObject_GetIter(ch); - if (it == NULL) { - PyErr_SetString(PyExc_TypeError, - "changelist is not iterable"); - return NULL; - } - nchanges = PyObject_Size(ch); - if (nchanges < 0) { - goto error; - } - - chl = PyMem_New(struct kevent, nchanges); - if (chl == NULL) { - PyErr_NoMemory(); - goto error; - } - i = 0; - while ((ei = PyIter_Next(it)) != NULL) { - if (!kqueue_event_Check(ei)) { - Py_DECREF(ei); - PyErr_SetString(PyExc_TypeError, - "changelist must be an iterable of " - "select.kevent objects"); - goto error; - } else { - chl[i++] = ((kqueue_event_Object *)ei)->e; - } - Py_DECREF(ei); - } - } - Py_CLEAR(it); - - /* event list */ - if (nevents) { - evl = PyMem_New(struct kevent, nevents); - if (evl == NULL) { - PyErr_NoMemory(); - goto error; - } - } - - Py_BEGIN_ALLOW_THREADS - gotevents = kevent(self->kqfd, chl, nchanges, - evl, nevents, ptimeoutspec); - Py_END_ALLOW_THREADS - - if (gotevents == -1) { - PyErr_SetFromErrno(PyExc_OSError); - goto error; - } - - result = PyList_New(gotevents); - if (result == NULL) { - goto error; - } - - for (i = 0; i < gotevents; i++) { - kqueue_event_Object *ch; - - ch = PyObject_New(kqueue_event_Object, &kqueue_event_Type); - if (ch == NULL) { - goto error; - } - ch->e = evl[i]; - PyList_SET_ITEM(result, i, (PyObject *)ch); - } - PyMem_Free(chl); - PyMem_Free(evl); - return result; + int nevents = 0; + int gotevents = 0; + int nchanges = 0; + int i = 0; + PyObject *otimeout = NULL; + PyObject *ch = NULL; + PyObject *it = NULL, *ei = NULL; + PyObject *result = NULL; + struct kevent *evl = NULL; + struct kevent *chl = NULL; + struct timespec timeoutspec; + struct timespec *ptimeoutspec; + + if (self->kqfd < 0) + return kqueue_queue_err_closed(); + + if (!PyArg_ParseTuple(args, "Oi|O:control", &ch, &nevents, &otimeout)) + return NULL; + + if (nevents < 0) { + PyErr_Format(PyExc_ValueError, + "Length of eventlist must be 0 or positive, got %d", + nevents); + return NULL; + } + + if (otimeout == Py_None || otimeout == NULL) { + ptimeoutspec = NULL; + } + else if (PyNumber_Check(otimeout)) { + double timeout; + long seconds; + + timeout = PyFloat_AsDouble(otimeout); + if (timeout == -1 && PyErr_Occurred()) + return NULL; + if (timeout > (double)LONG_MAX) { + PyErr_SetString(PyExc_OverflowError, + "timeout period too long"); + return NULL; + } + if (timeout < 0) { + PyErr_SetString(PyExc_ValueError, + "timeout must be positive or None"); + return NULL; + } + + seconds = (long)timeout; + timeout = timeout - (double)seconds; + timeoutspec.tv_sec = seconds; + timeoutspec.tv_nsec = (long)(timeout * 1E9); + ptimeoutspec = &timeoutspec; + } + else { + PyErr_Format(PyExc_TypeError, + "timeout argument must be an number " + "or None, got %.200s", + Py_TYPE(otimeout)->tp_name); + return NULL; + } + + if (ch != NULL && ch != Py_None) { + it = PyObject_GetIter(ch); + if (it == NULL) { + PyErr_SetString(PyExc_TypeError, + "changelist is not iterable"); + return NULL; + } + nchanges = PyObject_Size(ch); + if (nchanges < 0) { + goto error; + } + + chl = PyMem_New(struct kevent, nchanges); + if (chl == NULL) { + PyErr_NoMemory(); + goto error; + } + i = 0; + while ((ei = PyIter_Next(it)) != NULL) { + if (!kqueue_event_Check(ei)) { + Py_DECREF(ei); + PyErr_SetString(PyExc_TypeError, + "changelist must be an iterable of " + "select.kevent objects"); + goto error; + } else { + chl[i++] = ((kqueue_event_Object *)ei)->e; + } + Py_DECREF(ei); + } + } + Py_CLEAR(it); + + /* event list */ + if (nevents) { + evl = PyMem_New(struct kevent, nevents); + if (evl == NULL) { + PyErr_NoMemory(); + goto error; + } + } + + Py_BEGIN_ALLOW_THREADS + gotevents = kevent(self->kqfd, chl, nchanges, + evl, nevents, ptimeoutspec); + Py_END_ALLOW_THREADS + + if (gotevents == -1) { + PyErr_SetFromErrno(PyExc_OSError); + goto error; + } + + result = PyList_New(gotevents); + if (result == NULL) { + goto error; + } + + for (i = 0; i < gotevents; i++) { + kqueue_event_Object *ch; + + ch = PyObject_New(kqueue_event_Object, &kqueue_event_Type); + if (ch == NULL) { + goto error; + } + ch->e = evl[i]; + PyList_SET_ITEM(result, i, (PyObject *)ch); + } + PyMem_Free(chl); + PyMem_Free(evl); + return result; error: - PyMem_Free(chl); - PyMem_Free(evl); - Py_XDECREF(result); - Py_XDECREF(it); - return NULL; + PyMem_Free(chl); + PyMem_Free(evl); + Py_XDECREF(result); + Py_XDECREF(it); + return NULL; } PyDoc_STRVAR(kqueue_queue_control_doc, @@ -1646,21 +1646,21 @@ static PyMethodDef kqueue_queue_methods[] = { - {"fromfd", (PyCFunction)kqueue_queue_fromfd, - METH_VARARGS | METH_CLASS, kqueue_queue_fromfd_doc}, - {"close", (PyCFunction)kqueue_queue_close, METH_NOARGS, - kqueue_queue_close_doc}, - {"fileno", (PyCFunction)kqueue_queue_fileno, METH_NOARGS, - kqueue_queue_fileno_doc}, - {"control", (PyCFunction)kqueue_queue_control, - METH_VARARGS , kqueue_queue_control_doc}, - {NULL, NULL}, + {"fromfd", (PyCFunction)kqueue_queue_fromfd, + METH_VARARGS | METH_CLASS, kqueue_queue_fromfd_doc}, + {"close", (PyCFunction)kqueue_queue_close, METH_NOARGS, + kqueue_queue_close_doc}, + {"fileno", (PyCFunction)kqueue_queue_fileno, METH_NOARGS, + kqueue_queue_fileno_doc}, + {"control", (PyCFunction)kqueue_queue_control, + METH_VARARGS , kqueue_queue_control_doc}, + {NULL, NULL}, }; static PyGetSetDef kqueue_queue_getsetlist[] = { - {"closed", (getter)kqueue_queue_get_closed, NULL, - "True if the kqueue handler is closed"}, - {0}, + {"closed", (getter)kqueue_queue_get_closed, NULL, + "True if the kqueue handler is closed"}, + {0}, }; PyDoc_STRVAR(kqueue_queue_doc, @@ -1679,45 +1679,45 @@ >>> kq.control([kevent(sock, KQ_FILTER_WRITE, KQ_EV_DELETE)], 0)"); static PyTypeObject kqueue_queue_Type = { - PyVarObject_HEAD_INIT(NULL, 0) - "select.kqueue", /* tp_name */ - sizeof(kqueue_queue_Object), /* tp_basicsize */ - 0, /* tp_itemsize */ - (destructor)kqueue_queue_dealloc, /* tp_dealloc */ - 0, /* tp_print */ - 0, /* tp_getattr */ - 0, /* tp_setattr */ - 0, /* tp_reserved */ - 0, /* tp_repr */ - 0, /* tp_as_number */ - 0, /* tp_as_sequence */ - 0, /* tp_as_mapping */ - 0, /* tp_hash */ - 0, /* tp_call */ - 0, /* tp_str */ - 0, /* tp_getattro */ - 0, /* tp_setattro */ - 0, /* tp_as_buffer */ - Py_TPFLAGS_DEFAULT, /* tp_flags */ - kqueue_queue_doc, /* tp_doc */ - 0, /* tp_traverse */ - 0, /* tp_clear */ - 0, /* tp_richcompare */ - 0, /* tp_weaklistoffset */ - 0, /* tp_iter */ - 0, /* tp_iternext */ - kqueue_queue_methods, /* tp_methods */ - 0, /* tp_members */ - kqueue_queue_getsetlist, /* tp_getset */ - 0, /* tp_base */ - 0, /* tp_dict */ - 0, /* tp_descr_get */ - 0, /* tp_descr_set */ - 0, /* tp_dictoffset */ - 0, /* tp_init */ - 0, /* tp_alloc */ - kqueue_queue_new, /* tp_new */ - 0, /* tp_free */ + PyVarObject_HEAD_INIT(NULL, 0) + "select.kqueue", /* tp_name */ + sizeof(kqueue_queue_Object), /* tp_basicsize */ + 0, /* tp_itemsize */ + (destructor)kqueue_queue_dealloc, /* tp_dealloc */ + 0, /* tp_print */ + 0, /* tp_getattr */ + 0, /* tp_setattr */ + 0, /* tp_reserved */ + 0, /* tp_repr */ + 0, /* tp_as_number */ + 0, /* tp_as_sequence */ + 0, /* tp_as_mapping */ + 0, /* tp_hash */ + 0, /* tp_call */ + 0, /* tp_str */ + 0, /* tp_getattro */ + 0, /* tp_setattro */ + 0, /* tp_as_buffer */ + Py_TPFLAGS_DEFAULT, /* tp_flags */ + kqueue_queue_doc, /* tp_doc */ + 0, /* tp_traverse */ + 0, /* tp_clear */ + 0, /* tp_richcompare */ + 0, /* tp_weaklistoffset */ + 0, /* tp_iter */ + 0, /* tp_iternext */ + kqueue_queue_methods, /* tp_methods */ + 0, /* tp_members */ + kqueue_queue_getsetlist, /* tp_getset */ + 0, /* tp_base */ + 0, /* tp_dict */ + 0, /* tp_descr_get */ + 0, /* tp_descr_set */ + 0, /* tp_dictoffset */ + 0, /* tp_init */ + 0, /* tp_alloc */ + kqueue_queue_new, /* tp_new */ + 0, /* tp_free */ }; #endif /* HAVE_KQUEUE */ @@ -1748,11 +1748,11 @@ descriptors can be used."); static PyMethodDef select_methods[] = { - {"select", select_select, METH_VARARGS, select_doc}, + {"select", select_select, METH_VARARGS, select_doc}, #ifdef HAVE_POLL - {"poll", select_poll, METH_NOARGS, poll_doc}, + {"poll", select_poll, METH_NOARGS, poll_doc}, #endif /* HAVE_POLL */ - {0, 0}, /* sentinel */ + {0, 0}, /* sentinel */ }; PyDoc_STRVAR(module_doc, @@ -1763,167 +1763,167 @@ static struct PyModuleDef selectmodule = { - PyModuleDef_HEAD_INIT, - "select", - module_doc, - -1, - select_methods, - NULL, - NULL, - NULL, - NULL + PyModuleDef_HEAD_INIT, + "select", + module_doc, + -1, + select_methods, + NULL, + NULL, + NULL, + NULL }; PyMODINIT_FUNC PyInit_select(void) { - PyObject *m; - m = PyModule_Create(&selectmodule); - if (m == NULL) - return NULL; - - SelectError = PyErr_NewException("select.error", NULL, NULL); - Py_INCREF(SelectError); - PyModule_AddObject(m, "error", SelectError); + PyObject *m; + m = PyModule_Create(&selectmodule); + if (m == NULL) + return NULL; + + SelectError = PyErr_NewException("select.error", NULL, NULL); + Py_INCREF(SelectError); + PyModule_AddObject(m, "error", SelectError); #ifdef PIPE_BUF - PyModule_AddIntConstant(m, "PIPE_BUF", PIPE_BUF); + PyModule_AddIntConstant(m, "PIPE_BUF", PIPE_BUF); #endif #if defined(HAVE_POLL) #ifdef __APPLE__ - if (select_have_broken_poll()) { - if (PyObject_DelAttrString(m, "poll") == -1) { - PyErr_Clear(); - } - } else { + if (select_have_broken_poll()) { + if (PyObject_DelAttrString(m, "poll") == -1) { + PyErr_Clear(); + } + } else { #else - { + { #endif - if (PyType_Ready(&poll_Type) < 0) - return NULL; - PyModule_AddIntConstant(m, "POLLIN", POLLIN); - PyModule_AddIntConstant(m, "POLLPRI", POLLPRI); - PyModule_AddIntConstant(m, "POLLOUT", POLLOUT); - PyModule_AddIntConstant(m, "POLLERR", POLLERR); - PyModule_AddIntConstant(m, "POLLHUP", POLLHUP); - PyModule_AddIntConstant(m, "POLLNVAL", POLLNVAL); + if (PyType_Ready(&poll_Type) < 0) + return NULL; + PyModule_AddIntConstant(m, "POLLIN", POLLIN); + PyModule_AddIntConstant(m, "POLLPRI", POLLPRI); + PyModule_AddIntConstant(m, "POLLOUT", POLLOUT); + PyModule_AddIntConstant(m, "POLLERR", POLLERR); + PyModule_AddIntConstant(m, "POLLHUP", POLLHUP); + PyModule_AddIntConstant(m, "POLLNVAL", POLLNVAL); #ifdef POLLRDNORM - PyModule_AddIntConstant(m, "POLLRDNORM", POLLRDNORM); + PyModule_AddIntConstant(m, "POLLRDNORM", POLLRDNORM); #endif #ifdef POLLRDBAND - PyModule_AddIntConstant(m, "POLLRDBAND", POLLRDBAND); + PyModule_AddIntConstant(m, "POLLRDBAND", POLLRDBAND); #endif #ifdef POLLWRNORM - PyModule_AddIntConstant(m, "POLLWRNORM", POLLWRNORM); + PyModule_AddIntConstant(m, "POLLWRNORM", POLLWRNORM); #endif #ifdef POLLWRBAND - PyModule_AddIntConstant(m, "POLLWRBAND", POLLWRBAND); + PyModule_AddIntConstant(m, "POLLWRBAND", POLLWRBAND); #endif #ifdef POLLMSG - PyModule_AddIntConstant(m, "POLLMSG", POLLMSG); + PyModule_AddIntConstant(m, "POLLMSG", POLLMSG); #endif - } + } #endif /* HAVE_POLL */ #ifdef HAVE_EPOLL - Py_TYPE(&pyEpoll_Type) = &PyType_Type; - if (PyType_Ready(&pyEpoll_Type) < 0) - return NULL; - - Py_INCREF(&pyEpoll_Type); - PyModule_AddObject(m, "epoll", (PyObject *) &pyEpoll_Type); - - PyModule_AddIntConstant(m, "EPOLLIN", EPOLLIN); - PyModule_AddIntConstant(m, "EPOLLOUT", EPOLLOUT); - PyModule_AddIntConstant(m, "EPOLLPRI", EPOLLPRI); - PyModule_AddIntConstant(m, "EPOLLERR", EPOLLERR); - PyModule_AddIntConstant(m, "EPOLLHUP", EPOLLHUP); - PyModule_AddIntConstant(m, "EPOLLET", EPOLLET); + Py_TYPE(&pyEpoll_Type) = &PyType_Type; + if (PyType_Ready(&pyEpoll_Type) < 0) + return NULL; + + Py_INCREF(&pyEpoll_Type); + PyModule_AddObject(m, "epoll", (PyObject *) &pyEpoll_Type); + + PyModule_AddIntConstant(m, "EPOLLIN", EPOLLIN); + PyModule_AddIntConstant(m, "EPOLLOUT", EPOLLOUT); + PyModule_AddIntConstant(m, "EPOLLPRI", EPOLLPRI); + PyModule_AddIntConstant(m, "EPOLLERR", EPOLLERR); + PyModule_AddIntConstant(m, "EPOLLHUP", EPOLLHUP); + PyModule_AddIntConstant(m, "EPOLLET", EPOLLET); #ifdef EPOLLONESHOT - /* Kernel 2.6.2+ */ - PyModule_AddIntConstant(m, "EPOLLONESHOT", EPOLLONESHOT); + /* Kernel 2.6.2+ */ + PyModule_AddIntConstant(m, "EPOLLONESHOT", EPOLLONESHOT); #endif - /* PyModule_AddIntConstant(m, "EPOLL_RDHUP", EPOLLRDHUP); */ - PyModule_AddIntConstant(m, "EPOLLRDNORM", EPOLLRDNORM); - PyModule_AddIntConstant(m, "EPOLLRDBAND", EPOLLRDBAND); - PyModule_AddIntConstant(m, "EPOLLWRNORM", EPOLLWRNORM); - PyModule_AddIntConstant(m, "EPOLLWRBAND", EPOLLWRBAND); - PyModule_AddIntConstant(m, "EPOLLMSG", EPOLLMSG); + /* PyModule_AddIntConstant(m, "EPOLL_RDHUP", EPOLLRDHUP); */ + PyModule_AddIntConstant(m, "EPOLLRDNORM", EPOLLRDNORM); + PyModule_AddIntConstant(m, "EPOLLRDBAND", EPOLLRDBAND); + PyModule_AddIntConstant(m, "EPOLLWRNORM", EPOLLWRNORM); + PyModule_AddIntConstant(m, "EPOLLWRBAND", EPOLLWRBAND); + PyModule_AddIntConstant(m, "EPOLLMSG", EPOLLMSG); #endif /* HAVE_EPOLL */ #ifdef HAVE_KQUEUE - kqueue_event_Type.tp_new = PyType_GenericNew; - Py_TYPE(&kqueue_event_Type) = &PyType_Type; - if(PyType_Ready(&kqueue_event_Type) < 0) - return NULL; - - Py_INCREF(&kqueue_event_Type); - PyModule_AddObject(m, "kevent", (PyObject *)&kqueue_event_Type); - - Py_TYPE(&kqueue_queue_Type) = &PyType_Type; - if(PyType_Ready(&kqueue_queue_Type) < 0) - return NULL; - Py_INCREF(&kqueue_queue_Type); - PyModule_AddObject(m, "kqueue", (PyObject *)&kqueue_queue_Type); - - /* event filters */ - PyModule_AddIntConstant(m, "KQ_FILTER_READ", EVFILT_READ); - PyModule_AddIntConstant(m, "KQ_FILTER_WRITE", EVFILT_WRITE); - PyModule_AddIntConstant(m, "KQ_FILTER_AIO", EVFILT_AIO); - PyModule_AddIntConstant(m, "KQ_FILTER_VNODE", EVFILT_VNODE); - PyModule_AddIntConstant(m, "KQ_FILTER_PROC", EVFILT_PROC); + kqueue_event_Type.tp_new = PyType_GenericNew; + Py_TYPE(&kqueue_event_Type) = &PyType_Type; + if(PyType_Ready(&kqueue_event_Type) < 0) + return NULL; + + Py_INCREF(&kqueue_event_Type); + PyModule_AddObject(m, "kevent", (PyObject *)&kqueue_event_Type); + + Py_TYPE(&kqueue_queue_Type) = &PyType_Type; + if(PyType_Ready(&kqueue_queue_Type) < 0) + return NULL; + Py_INCREF(&kqueue_queue_Type); + PyModule_AddObject(m, "kqueue", (PyObject *)&kqueue_queue_Type); + + /* event filters */ + PyModule_AddIntConstant(m, "KQ_FILTER_READ", EVFILT_READ); + PyModule_AddIntConstant(m, "KQ_FILTER_WRITE", EVFILT_WRITE); + PyModule_AddIntConstant(m, "KQ_FILTER_AIO", EVFILT_AIO); + PyModule_AddIntConstant(m, "KQ_FILTER_VNODE", EVFILT_VNODE); + PyModule_AddIntConstant(m, "KQ_FILTER_PROC", EVFILT_PROC); #ifdef EVFILT_NETDEV - PyModule_AddIntConstant(m, "KQ_FILTER_NETDEV", EVFILT_NETDEV); + PyModule_AddIntConstant(m, "KQ_FILTER_NETDEV", EVFILT_NETDEV); #endif - PyModule_AddIntConstant(m, "KQ_FILTER_SIGNAL", EVFILT_SIGNAL); - PyModule_AddIntConstant(m, "KQ_FILTER_TIMER", EVFILT_TIMER); + PyModule_AddIntConstant(m, "KQ_FILTER_SIGNAL", EVFILT_SIGNAL); + PyModule_AddIntConstant(m, "KQ_FILTER_TIMER", EVFILT_TIMER); - /* event flags */ - PyModule_AddIntConstant(m, "KQ_EV_ADD", EV_ADD); - PyModule_AddIntConstant(m, "KQ_EV_DELETE", EV_DELETE); - PyModule_AddIntConstant(m, "KQ_EV_ENABLE", EV_ENABLE); - PyModule_AddIntConstant(m, "KQ_EV_DISABLE", EV_DISABLE); - PyModule_AddIntConstant(m, "KQ_EV_ONESHOT", EV_ONESHOT); - PyModule_AddIntConstant(m, "KQ_EV_CLEAR", EV_CLEAR); - - PyModule_AddIntConstant(m, "KQ_EV_SYSFLAGS", EV_SYSFLAGS); - PyModule_AddIntConstant(m, "KQ_EV_FLAG1", EV_FLAG1); - - PyModule_AddIntConstant(m, "KQ_EV_EOF", EV_EOF); - PyModule_AddIntConstant(m, "KQ_EV_ERROR", EV_ERROR); - - /* READ WRITE filter flag */ - PyModule_AddIntConstant(m, "KQ_NOTE_LOWAT", NOTE_LOWAT); - - /* VNODE filter flags */ - PyModule_AddIntConstant(m, "KQ_NOTE_DELETE", NOTE_DELETE); - PyModule_AddIntConstant(m, "KQ_NOTE_WRITE", NOTE_WRITE); - PyModule_AddIntConstant(m, "KQ_NOTE_EXTEND", NOTE_EXTEND); - PyModule_AddIntConstant(m, "KQ_NOTE_ATTRIB", NOTE_ATTRIB); - PyModule_AddIntConstant(m, "KQ_NOTE_LINK", NOTE_LINK); - PyModule_AddIntConstant(m, "KQ_NOTE_RENAME", NOTE_RENAME); - PyModule_AddIntConstant(m, "KQ_NOTE_REVOKE", NOTE_REVOKE); - - /* PROC filter flags */ - PyModule_AddIntConstant(m, "KQ_NOTE_EXIT", NOTE_EXIT); - PyModule_AddIntConstant(m, "KQ_NOTE_FORK", NOTE_FORK); - PyModule_AddIntConstant(m, "KQ_NOTE_EXEC", NOTE_EXEC); - PyModule_AddIntConstant(m, "KQ_NOTE_PCTRLMASK", NOTE_PCTRLMASK); - PyModule_AddIntConstant(m, "KQ_NOTE_PDATAMASK", NOTE_PDATAMASK); - - PyModule_AddIntConstant(m, "KQ_NOTE_TRACK", NOTE_TRACK); - PyModule_AddIntConstant(m, "KQ_NOTE_CHILD", NOTE_CHILD); - PyModule_AddIntConstant(m, "KQ_NOTE_TRACKERR", NOTE_TRACKERR); + /* event flags */ + PyModule_AddIntConstant(m, "KQ_EV_ADD", EV_ADD); + PyModule_AddIntConstant(m, "KQ_EV_DELETE", EV_DELETE); + PyModule_AddIntConstant(m, "KQ_EV_ENABLE", EV_ENABLE); + PyModule_AddIntConstant(m, "KQ_EV_DISABLE", EV_DISABLE); + PyModule_AddIntConstant(m, "KQ_EV_ONESHOT", EV_ONESHOT); + PyModule_AddIntConstant(m, "KQ_EV_CLEAR", EV_CLEAR); + + PyModule_AddIntConstant(m, "KQ_EV_SYSFLAGS", EV_SYSFLAGS); + PyModule_AddIntConstant(m, "KQ_EV_FLAG1", EV_FLAG1); + + PyModule_AddIntConstant(m, "KQ_EV_EOF", EV_EOF); + PyModule_AddIntConstant(m, "KQ_EV_ERROR", EV_ERROR); + + /* READ WRITE filter flag */ + PyModule_AddIntConstant(m, "KQ_NOTE_LOWAT", NOTE_LOWAT); + + /* VNODE filter flags */ + PyModule_AddIntConstant(m, "KQ_NOTE_DELETE", NOTE_DELETE); + PyModule_AddIntConstant(m, "KQ_NOTE_WRITE", NOTE_WRITE); + PyModule_AddIntConstant(m, "KQ_NOTE_EXTEND", NOTE_EXTEND); + PyModule_AddIntConstant(m, "KQ_NOTE_ATTRIB", NOTE_ATTRIB); + PyModule_AddIntConstant(m, "KQ_NOTE_LINK", NOTE_LINK); + PyModule_AddIntConstant(m, "KQ_NOTE_RENAME", NOTE_RENAME); + PyModule_AddIntConstant(m, "KQ_NOTE_REVOKE", NOTE_REVOKE); + + /* PROC filter flags */ + PyModule_AddIntConstant(m, "KQ_NOTE_EXIT", NOTE_EXIT); + PyModule_AddIntConstant(m, "KQ_NOTE_FORK", NOTE_FORK); + PyModule_AddIntConstant(m, "KQ_NOTE_EXEC", NOTE_EXEC); + PyModule_AddIntConstant(m, "KQ_NOTE_PCTRLMASK", NOTE_PCTRLMASK); + PyModule_AddIntConstant(m, "KQ_NOTE_PDATAMASK", NOTE_PDATAMASK); + + PyModule_AddIntConstant(m, "KQ_NOTE_TRACK", NOTE_TRACK); + PyModule_AddIntConstant(m, "KQ_NOTE_CHILD", NOTE_CHILD); + PyModule_AddIntConstant(m, "KQ_NOTE_TRACKERR", NOTE_TRACKERR); - /* NETDEV filter flags */ + /* NETDEV filter flags */ #ifdef EVFILT_NETDEV - PyModule_AddIntConstant(m, "KQ_NOTE_LINKUP", NOTE_LINKUP); - PyModule_AddIntConstant(m, "KQ_NOTE_LINKDOWN", NOTE_LINKDOWN); - PyModule_AddIntConstant(m, "KQ_NOTE_LINKINV", NOTE_LINKINV); + PyModule_AddIntConstant(m, "KQ_NOTE_LINKUP", NOTE_LINKUP); + PyModule_AddIntConstant(m, "KQ_NOTE_LINKDOWN", NOTE_LINKDOWN); + PyModule_AddIntConstant(m, "KQ_NOTE_LINKINV", NOTE_LINKINV); #endif #endif /* HAVE_KQUEUE */ - return m; + return m; } Modified: python/branches/py3k/Modules/sha1module.c ============================================================================== --- python/branches/py3k/Modules/sha1module.c (original) +++ python/branches/py3k/Modules/sha1module.c Sun May 9 17:52:27 2010 @@ -23,8 +23,8 @@ /* Some useful types */ #if SIZEOF_INT == 4 -typedef unsigned int SHA1_INT32; /* 32-bit integer */ -typedef PY_LONG_LONG SHA1_INT64; /* 64-bit integer */ +typedef unsigned int SHA1_INT32; /* 32-bit integer */ +typedef PY_LONG_LONG SHA1_INT64; /* 64-bit integer */ #else /* not defined. compilation will die. */ #endif @@ -122,7 +122,7 @@ /* expand it */ for (i = 16; i < 80; i++) { - W[i] = ROL(W[i-3] ^ W[i-8] ^ W[i-14] ^ W[i-16], 1); + W[i] = ROL(W[i-3] ^ W[i-8] ^ W[i-14] ^ W[i-16], 1); } /* compress */ @@ -131,7 +131,7 @@ #define FF1(a,b,c,d,e,i) e = (ROLc(a, 5) + F1(b,c,d) + e + W[i] + 0x6ed9eba1UL); b = ROLc(b, 30); #define FF2(a,b,c,d,e,i) e = (ROLc(a, 5) + F2(b,c,d) + e + W[i] + 0x8f1bbcdcUL); b = ROLc(b, 30); #define FF3(a,b,c,d,e,i) e = (ROLc(a, 5) + F3(b,c,d) + e + W[i] + 0xca62c1d6UL); b = ROLc(b, 30); - + for (i = 0; i < 20; ) { FF0(a,b,c,d,e,i++); FF0(e,a,b,c,d,i++); @@ -141,7 +141,7 @@ } /* round two */ - for (; i < 40; ) { + for (; i < 40; ) { FF1(a,b,c,d,e,i++); FF1(e,a,b,c,d,i++); FF1(d,e,a,b,c,i++); @@ -150,7 +150,7 @@ } /* round three */ - for (; i < 60; ) { + for (; i < 60; ) { FF2(a,b,c,d,e,i++); FF2(e,a,b,c,d,i++); FF2(d,e,a,b,c,i++); @@ -159,7 +159,7 @@ } /* round four */ - for (; i < 80; ) { + for (; i < 80; ) { FF3(a,b,c,d,e,i++); FF3(e,a,b,c,d,i++); FF3(d,e,a,b,c,i++); @@ -362,21 +362,21 @@ /* Create a new string */ retval = PyUnicode_FromStringAndSize(NULL, SHA1_DIGESTSIZE * 2); if (!retval) - return NULL; + return NULL; hex_digest = PyUnicode_AS_UNICODE(retval); if (!hex_digest) { - Py_DECREF(retval); - return NULL; + Py_DECREF(retval); + return NULL; } /* Make hex version of the digest */ for(i=j=0; i> 4) & 0xf; - c = (c>9) ? c+'a'-10 : c + '0'; + c = (c>9) ? c+'a'-10 : c + '0'; hex_digest[j++] = c; c = (digest[i] & 0xf); - c = (c>9) ? c+'a'-10 : c + '0'; + c = (c>9) ? c+'a'-10 : c + '0'; hex_digest[j++] = c; } return retval; @@ -404,11 +404,11 @@ } static PyMethodDef SHA1_methods[] = { - {"copy", (PyCFunction)SHA1_copy, METH_NOARGS, SHA1_copy__doc__}, - {"digest", (PyCFunction)SHA1_digest, METH_NOARGS, SHA1_digest__doc__}, + {"copy", (PyCFunction)SHA1_copy, METH_NOARGS, SHA1_copy__doc__}, + {"digest", (PyCFunction)SHA1_digest, METH_NOARGS, SHA1_digest__doc__}, {"hexdigest", (PyCFunction)SHA1_hexdigest, METH_NOARGS, SHA1_hexdigest__doc__}, - {"update", (PyCFunction)SHA1_update, METH_VARARGS, SHA1_update__doc__}, - {NULL, NULL} /* sentinel */ + {"update", (PyCFunction)SHA1_update, METH_VARARGS, SHA1_update__doc__}, + {NULL, NULL} /* sentinel */ }; static PyObject * @@ -448,13 +448,13 @@ static PyTypeObject SHA1type = { PyVarObject_HEAD_INIT(NULL, 0) - "_sha1.sha1", /*tp_name*/ - sizeof(SHA1object), /*tp_size*/ - 0, /*tp_itemsize*/ + "_sha1.sha1", /*tp_name*/ + sizeof(SHA1object), /*tp_size*/ + 0, /*tp_itemsize*/ /* methods */ - SHA1_dealloc, /*tp_dealloc*/ - 0, /*tp_print*/ - 0, /*tp_getattr*/ + SHA1_dealloc, /*tp_dealloc*/ + 0, /*tp_print*/ + 0, /*tp_getattr*/ 0, /*tp_setattr*/ 0, /*tp_reserved*/ 0, /*tp_repr*/ @@ -470,13 +470,13 @@ Py_TPFLAGS_DEFAULT, /*tp_flags*/ 0, /*tp_doc*/ 0, /*tp_traverse*/ - 0, /*tp_clear*/ - 0, /*tp_richcompare*/ - 0, /*tp_weaklistoffset*/ - 0, /*tp_iter*/ - 0, /*tp_iternext*/ - SHA1_methods, /* tp_methods */ - NULL, /* tp_members */ + 0, /*tp_clear*/ + 0, /*tp_richcompare*/ + 0, /*tp_weaklistoffset*/ + 0, /*tp_iter*/ + 0, /*tp_iternext*/ + SHA1_methods, /* tp_methods */ + NULL, /* tp_members */ SHA1_getseters, /* tp_getset */ }; @@ -529,7 +529,7 @@ static struct PyMethodDef SHA1_functions[] = { {"sha1",(PyCFunction)SHA1_new, METH_VARARGS|METH_KEYWORDS,SHA1_new__doc__}, - {NULL, NULL} /* Sentinel */ + {NULL, NULL} /* Sentinel */ }; @@ -539,15 +539,15 @@ static struct PyModuleDef _sha1module = { - PyModuleDef_HEAD_INIT, - "_sha1", - NULL, - -1, - SHA1_functions, - NULL, - NULL, - NULL, - NULL + PyModuleDef_HEAD_INIT, + "_sha1", + NULL, + -1, + SHA1_functions, + NULL, + NULL, + NULL, + NULL }; PyMODINIT_FUNC Modified: python/branches/py3k/Modules/sha256module.c ============================================================================== --- python/branches/py3k/Modules/sha256module.c (original) +++ python/branches/py3k/Modules/sha256module.c Sun May 9 17:52:27 2010 @@ -23,7 +23,7 @@ /* Endianness testing and definitions */ #define TestEndianness(variable) {int i=1; variable=PCT_BIG_ENDIAN;\ - if (*((char*)&i)==1) variable=PCT_LITTLE_ENDIAN;} + if (*((char*)&i)==1) variable=PCT_LITTLE_ENDIAN;} #define PCT_LITTLE_ENDIAN 1 #define PCT_BIG_ENDIAN 0 @@ -33,7 +33,7 @@ typedef unsigned char SHA_BYTE; #if SIZEOF_INT == 4 -typedef unsigned int SHA_INT32; /* 32-bit integer */ +typedef unsigned int SHA_INT32; /* 32-bit integer */ #else /* not defined. compilation will die. */ #endif @@ -47,11 +47,11 @@ typedef struct { PyObject_HEAD - SHA_INT32 digest[8]; /* Message digest */ - SHA_INT32 count_lo, count_hi; /* 64-bit bit count */ - SHA_BYTE data[SHA_BLOCKSIZE]; /* SHA data buffer */ + SHA_INT32 digest[8]; /* Message digest */ + SHA_INT32 count_lo, count_hi; /* 64-bit bit count */ + SHA_BYTE data[SHA_BLOCKSIZE]; /* SHA data buffer */ int Endianness; - int local; /* unprocessed amount in data */ + int local; /* unprocessed amount in data */ int digestsize; } SHAobject; @@ -63,7 +63,7 @@ SHA_INT32 value; if ( Endianness == PCT_BIG_ENDIAN ) - return; + return; byteCount /= sizeof(*buffer); while (byteCount--) { @@ -115,7 +115,7 @@ ( ((((unsigned long)(x)&0xFFFFFFFFUL)>>(unsigned long)((y)&31)) | \ ((unsigned long)(x)<<(unsigned long)(32-((y)&31)))) & 0xFFFFFFFFUL) #define Ch(x,y,z) (z ^ (x & (y ^ z))) -#define Maj(x,y,z) (((x | y) & z) | (x & y)) +#define Maj(x,y,z) (((x | y) & z) | (x & y)) #define S(x, n) ROR((x),(n)) #define R(x, n) (((x)&0xFFFFFFFFUL)>>(n)) #define Sigma0(x) (S(x, 2) ^ S(x, 13) ^ S(x, 22)) @@ -128,13 +128,13 @@ sha_transform(SHAobject *sha_info) { int i; - SHA_INT32 S[8], W[64], t0, t1; + SHA_INT32 S[8], W[64], t0, t1; memcpy(W, sha_info->data, sizeof(sha_info->data)); longReverse(W, (int)sizeof(sha_info->data), sha_info->Endianness); for (i = 16; i < 64; ++i) { - W[i] = Gamma1(W[i - 2]) + W[i - 7] + Gamma0(W[i - 15]) + W[i - 16]; + W[i] = Gamma1(W[i - 2]) + W[i - 7] + Gamma0(W[i - 15]) + W[i - 16]; } for (i = 0; i < 8; ++i) { S[i] = sha_info->digest[i]; @@ -212,8 +212,8 @@ RND(S[2],S[3],S[4],S[5],S[6],S[7],S[0],S[1],62,0xbef9a3f7); RND(S[1],S[2],S[3],S[4],S[5],S[6],S[7],S[0],63,0xc67178f2); -#undef RND - +#undef RND + /* feedback */ for (i = 0; i < 8; i++) { sha_info->digest[i] = sha_info->digest[i] + S[i]; @@ -315,14 +315,14 @@ count = (int) ((lo_bit_count >> 3) & 0x3f); ((SHA_BYTE *) sha_info->data)[count++] = 0x80; if (count > SHA_BLOCKSIZE - 8) { - memset(((SHA_BYTE *) sha_info->data) + count, 0, - SHA_BLOCKSIZE - count); - sha_transform(sha_info); - memset((SHA_BYTE *) sha_info->data, 0, SHA_BLOCKSIZE - 8); + memset(((SHA_BYTE *) sha_info->data) + count, 0, + SHA_BLOCKSIZE - count); + sha_transform(sha_info); + memset((SHA_BYTE *) sha_info->data, 0, SHA_BLOCKSIZE - 8); } else { - memset(((SHA_BYTE *) sha_info->data) + count, 0, - SHA_BLOCKSIZE - 8 - count); + memset(((SHA_BYTE *) sha_info->data) + count, 0, + SHA_BLOCKSIZE - 8 - count); } /* GJS: note that we add the hi/lo in big-endian. sha_transform will @@ -455,21 +455,21 @@ /* Create a new string */ retval = PyUnicode_FromStringAndSize(NULL, self->digestsize * 2); if (!retval) - return NULL; + return NULL; hex_digest = PyUnicode_AS_UNICODE(retval); if (!hex_digest) { - Py_DECREF(retval); - return NULL; + Py_DECREF(retval); + return NULL; } /* Make hex version of the digest */ for(i=j=0; idigestsize; i++) { char c; c = (digest[i] >> 4) & 0xf; - c = (c>9) ? c+'a'-10 : c + '0'; + c = (c>9) ? c+'a'-10 : c + '0'; hex_digest[j++] = c; c = (digest[i] & 0xf); - c = (c>9) ? c+'a'-10 : c + '0'; + c = (c>9) ? c+'a'-10 : c + '0'; hex_digest[j++] = c; } return retval; @@ -497,11 +497,11 @@ } static PyMethodDef SHA_methods[] = { - {"copy", (PyCFunction)SHA256_copy, METH_NOARGS, SHA256_copy__doc__}, - {"digest", (PyCFunction)SHA256_digest, METH_NOARGS, SHA256_digest__doc__}, + {"copy", (PyCFunction)SHA256_copy, METH_NOARGS, SHA256_copy__doc__}, + {"digest", (PyCFunction)SHA256_digest, METH_NOARGS, SHA256_digest__doc__}, {"hexdigest", (PyCFunction)SHA256_hexdigest, METH_NOARGS, SHA256_hexdigest__doc__}, - {"update", (PyCFunction)SHA256_update, METH_VARARGS, SHA256_update__doc__}, - {NULL, NULL} /* sentinel */ + {"update", (PyCFunction)SHA256_update, METH_VARARGS, SHA256_update__doc__}, + {NULL, NULL} /* sentinel */ }; static PyObject * @@ -538,13 +538,13 @@ static PyTypeObject SHA224type = { PyVarObject_HEAD_INIT(NULL, 0) - "_sha256.sha224", /*tp_name*/ - sizeof(SHAobject), /*tp_size*/ - 0, /*tp_itemsize*/ + "_sha256.sha224", /*tp_name*/ + sizeof(SHAobject), /*tp_size*/ + 0, /*tp_itemsize*/ /* methods */ - SHA_dealloc, /*tp_dealloc*/ - 0, /*tp_print*/ - 0, /*tp_getattr*/ + SHA_dealloc, /*tp_dealloc*/ + 0, /*tp_print*/ + 0, /*tp_getattr*/ 0, /*tp_setattr*/ 0, /*tp_reserved*/ 0, /*tp_repr*/ @@ -560,25 +560,25 @@ Py_TPFLAGS_DEFAULT, /*tp_flags*/ 0, /*tp_doc*/ 0, /*tp_traverse*/ - 0, /*tp_clear*/ - 0, /*tp_richcompare*/ - 0, /*tp_weaklistoffset*/ - 0, /*tp_iter*/ - 0, /*tp_iternext*/ - SHA_methods, /* tp_methods */ - SHA_members, /* tp_members */ + 0, /*tp_clear*/ + 0, /*tp_richcompare*/ + 0, /*tp_weaklistoffset*/ + 0, /*tp_iter*/ + 0, /*tp_iternext*/ + SHA_methods, /* tp_methods */ + SHA_members, /* tp_members */ SHA_getseters, /* tp_getset */ }; static PyTypeObject SHA256type = { PyVarObject_HEAD_INIT(NULL, 0) - "_sha256.sha256", /*tp_name*/ - sizeof(SHAobject), /*tp_size*/ - 0, /*tp_itemsize*/ + "_sha256.sha256", /*tp_name*/ + sizeof(SHAobject), /*tp_size*/ + 0, /*tp_itemsize*/ /* methods */ - SHA_dealloc, /*tp_dealloc*/ - 0, /*tp_print*/ - 0, /*tp_getattr*/ + SHA_dealloc, /*tp_dealloc*/ + 0, /*tp_print*/ + 0, /*tp_getattr*/ 0, /*tp_setattr*/ 0, /*tp_reserved*/ 0, /*tp_repr*/ @@ -594,13 +594,13 @@ Py_TPFLAGS_DEFAULT, /*tp_flags*/ 0, /*tp_doc*/ 0, /*tp_traverse*/ - 0, /*tp_clear*/ - 0, /*tp_richcompare*/ - 0, /*tp_weaklistoffset*/ - 0, /*tp_iter*/ - 0, /*tp_iternext*/ - SHA_methods, /* tp_methods */ - SHA_members, /* tp_members */ + 0, /*tp_clear*/ + 0, /*tp_richcompare*/ + 0, /*tp_weaklistoffset*/ + 0, /*tp_iter*/ + 0, /*tp_iternext*/ + SHA_methods, /* tp_methods */ + SHA_members, /* tp_members */ SHA_getseters, /* tp_getset */ }; @@ -695,7 +695,7 @@ static struct PyMethodDef SHA_functions[] = { {"sha256", (PyCFunction)SHA256_new, METH_VARARGS|METH_KEYWORDS, SHA256_new__doc__}, {"sha224", (PyCFunction)SHA224_new, METH_VARARGS|METH_KEYWORDS, SHA224_new__doc__}, - {NULL, NULL} /* Sentinel */ + {NULL, NULL} /* Sentinel */ }; @@ -705,15 +705,15 @@ static struct PyModuleDef _sha256module = { - PyModuleDef_HEAD_INIT, - "_sha256", - NULL, - -1, - SHA_functions, - NULL, - NULL, - NULL, - NULL + PyModuleDef_HEAD_INIT, + "_sha256", + NULL, + -1, + SHA_functions, + NULL, + NULL, + NULL, + NULL }; PyMODINIT_FUNC Modified: python/branches/py3k/Modules/sha512module.c ============================================================================== --- python/branches/py3k/Modules/sha512module.c (original) +++ python/branches/py3k/Modules/sha512module.c Sun May 9 17:52:27 2010 @@ -24,7 +24,7 @@ /* Endianness testing and definitions */ #define TestEndianness(variable) {int i=1; variable=PCT_BIG_ENDIAN;\ - if (*((char*)&i)==1) variable=PCT_LITTLE_ENDIAN;} + if (*((char*)&i)==1) variable=PCT_LITTLE_ENDIAN;} #define PCT_LITTLE_ENDIAN 1 #define PCT_BIG_ENDIAN 0 @@ -34,8 +34,8 @@ typedef unsigned char SHA_BYTE; #if SIZEOF_INT == 4 -typedef unsigned int SHA_INT32; /* 32-bit integer */ -typedef unsigned PY_LONG_LONG SHA_INT64; /* 64-bit integer */ +typedef unsigned int SHA_INT32; /* 32-bit integer */ +typedef unsigned PY_LONG_LONG SHA_INT64; /* 64-bit integer */ #else /* not defined. compilation will die. */ #endif @@ -49,11 +49,11 @@ typedef struct { PyObject_HEAD - SHA_INT64 digest[8]; /* Message digest */ - SHA_INT32 count_lo, count_hi; /* 64-bit bit count */ - SHA_BYTE data[SHA_BLOCKSIZE]; /* SHA data buffer */ + SHA_INT64 digest[8]; /* Message digest */ + SHA_INT32 count_lo, count_hi; /* 64-bit bit count */ + SHA_BYTE data[SHA_BLOCKSIZE]; /* SHA data buffer */ int Endianness; - int local; /* unprocessed amount in data */ + int local; /* unprocessed amount in data */ int digestsize; } SHAobject; @@ -65,22 +65,22 @@ SHA_INT64 value; if ( Endianness == PCT_BIG_ENDIAN ) - return; + return; byteCount /= sizeof(*buffer); while (byteCount--) { value = *buffer; - ((unsigned char*)buffer)[0] = (unsigned char)(value >> 56) & 0xff; - ((unsigned char*)buffer)[1] = (unsigned char)(value >> 48) & 0xff; - ((unsigned char*)buffer)[2] = (unsigned char)(value >> 40) & 0xff; - ((unsigned char*)buffer)[3] = (unsigned char)(value >> 32) & 0xff; - ((unsigned char*)buffer)[4] = (unsigned char)(value >> 24) & 0xff; - ((unsigned char*)buffer)[5] = (unsigned char)(value >> 16) & 0xff; - ((unsigned char*)buffer)[6] = (unsigned char)(value >> 8) & 0xff; - ((unsigned char*)buffer)[7] = (unsigned char)(value ) & 0xff; - - buffer++; + ((unsigned char*)buffer)[0] = (unsigned char)(value >> 56) & 0xff; + ((unsigned char*)buffer)[1] = (unsigned char)(value >> 48) & 0xff; + ((unsigned char*)buffer)[2] = (unsigned char)(value >> 40) & 0xff; + ((unsigned char*)buffer)[3] = (unsigned char)(value >> 32) & 0xff; + ((unsigned char*)buffer)[4] = (unsigned char)(value >> 24) & 0xff; + ((unsigned char*)buffer)[5] = (unsigned char)(value >> 16) & 0xff; + ((unsigned char*)buffer)[6] = (unsigned char)(value >> 8) & 0xff; + ((unsigned char*)buffer)[7] = (unsigned char)(value ) & 0xff; + + buffer++; } } @@ -125,7 +125,7 @@ ( ((((x) & Py_ULL(0xFFFFFFFFFFFFFFFF))>>((unsigned PY_LONG_LONG)(y) & 63)) | \ ((x)<<((unsigned PY_LONG_LONG)(64-((y) & 63))))) & Py_ULL(0xFFFFFFFFFFFFFFFF)) #define Ch(x,y,z) (z ^ (x & (y ^ z))) -#define Maj(x,y,z) (((x | y) & z) | (x & y)) +#define Maj(x,y,z) (((x | y) & z) | (x & y)) #define S(x, n) ROR64((x),(n)) #define R(x, n) (((x) & Py_ULL(0xFFFFFFFFFFFFFFFF)) >> ((unsigned PY_LONG_LONG)n)) #define Sigma0(x) (S(x, 28) ^ S(x, 34) ^ S(x, 39)) @@ -144,7 +144,7 @@ longReverse(W, (int)sizeof(sha_info->data), sha_info->Endianness); for (i = 16; i < 80; ++i) { - W[i] = Gamma1(W[i - 2]) + W[i - 7] + Gamma0(W[i - 15]) + W[i - 16]; + W[i] = Gamma1(W[i - 2]) + W[i - 7] + Gamma0(W[i - 15]) + W[i - 16]; } for (i = 0; i < 8; ++i) { S[i] = sha_info->digest[i]; @@ -238,8 +238,8 @@ RND(S[2],S[3],S[4],S[5],S[6],S[7],S[0],S[1],78,Py_ULL(0x5fcb6fab3ad6faec)); RND(S[1],S[2],S[3],S[4],S[5],S[6],S[7],S[0],79,Py_ULL(0x6c44198c4a475817)); -#undef RND - +#undef RND + /* feedback */ for (i = 0; i < 8; i++) { sha_info->digest[i] = sha_info->digest[i] + S[i]; @@ -341,14 +341,14 @@ count = (int) ((lo_bit_count >> 3) & 0x7f); ((SHA_BYTE *) sha_info->data)[count++] = 0x80; if (count > SHA_BLOCKSIZE - 16) { - memset(((SHA_BYTE *) sha_info->data) + count, 0, - SHA_BLOCKSIZE - count); - sha512_transform(sha_info); - memset((SHA_BYTE *) sha_info->data, 0, SHA_BLOCKSIZE - 16); + memset(((SHA_BYTE *) sha_info->data) + count, 0, + SHA_BLOCKSIZE - count); + sha512_transform(sha_info); + memset((SHA_BYTE *) sha_info->data, 0, SHA_BLOCKSIZE - 16); } else { - memset(((SHA_BYTE *) sha_info->data) + count, 0, - SHA_BLOCKSIZE - 16 - count); + memset(((SHA_BYTE *) sha_info->data) + count, 0, + SHA_BLOCKSIZE - 16 - count); } /* GJS: note that we add the hi/lo in big-endian. sha512_transform will @@ -521,21 +521,21 @@ /* Create a new string */ retval = PyUnicode_FromStringAndSize(NULL, self->digestsize * 2); if (!retval) - return NULL; + return NULL; hex_digest = PyUnicode_AS_UNICODE(retval); if (!hex_digest) { - Py_DECREF(retval); - return NULL; + Py_DECREF(retval); + return NULL; } /* Make hex version of the digest */ for (i=j=0; idigestsize; i++) { char c; c = (digest[i] >> 4) & 0xf; - c = (c>9) ? c+'a'-10 : c + '0'; + c = (c>9) ? c+'a'-10 : c + '0'; hex_digest[j++] = c; c = (digest[i] & 0xf); - c = (c>9) ? c+'a'-10 : c + '0'; + c = (c>9) ? c+'a'-10 : c + '0'; hex_digest[j++] = c; } return retval; @@ -563,11 +563,11 @@ } static PyMethodDef SHA_methods[] = { - {"copy", (PyCFunction)SHA512_copy, METH_NOARGS, SHA512_copy__doc__}, - {"digest", (PyCFunction)SHA512_digest, METH_NOARGS, SHA512_digest__doc__}, + {"copy", (PyCFunction)SHA512_copy, METH_NOARGS, SHA512_copy__doc__}, + {"digest", (PyCFunction)SHA512_digest, METH_NOARGS, SHA512_digest__doc__}, {"hexdigest", (PyCFunction)SHA512_hexdigest, METH_NOARGS, SHA512_hexdigest__doc__}, - {"update", (PyCFunction)SHA512_update, METH_VARARGS, SHA512_update__doc__}, - {NULL, NULL} /* sentinel */ + {"update", (PyCFunction)SHA512_update, METH_VARARGS, SHA512_update__doc__}, + {NULL, NULL} /* sentinel */ }; static PyObject * @@ -604,13 +604,13 @@ static PyTypeObject SHA384type = { PyVarObject_HEAD_INIT(NULL, 0) - "_sha512.sha384", /*tp_name*/ - sizeof(SHAobject), /*tp_size*/ - 0, /*tp_itemsize*/ + "_sha512.sha384", /*tp_name*/ + sizeof(SHAobject), /*tp_size*/ + 0, /*tp_itemsize*/ /* methods */ - SHA512_dealloc, /*tp_dealloc*/ - 0, /*tp_print*/ - 0, /*tp_getattr*/ + SHA512_dealloc, /*tp_dealloc*/ + 0, /*tp_print*/ + 0, /*tp_getattr*/ 0, /*tp_setattr*/ 0, /*tp_reserved*/ 0, /*tp_repr*/ @@ -626,25 +626,25 @@ Py_TPFLAGS_DEFAULT, /*tp_flags*/ 0, /*tp_doc*/ 0, /*tp_traverse*/ - 0, /*tp_clear*/ - 0, /*tp_richcompare*/ - 0, /*tp_weaklistoffset*/ - 0, /*tp_iter*/ - 0, /*tp_iternext*/ - SHA_methods, /* tp_methods */ - SHA_members, /* tp_members */ + 0, /*tp_clear*/ + 0, /*tp_richcompare*/ + 0, /*tp_weaklistoffset*/ + 0, /*tp_iter*/ + 0, /*tp_iternext*/ + SHA_methods, /* tp_methods */ + SHA_members, /* tp_members */ SHA_getseters, /* tp_getset */ }; static PyTypeObject SHA512type = { PyVarObject_HEAD_INIT(NULL, 0) - "_sha512.sha512", /*tp_name*/ - sizeof(SHAobject), /*tp_size*/ - 0, /*tp_itemsize*/ + "_sha512.sha512", /*tp_name*/ + sizeof(SHAobject), /*tp_size*/ + 0, /*tp_itemsize*/ /* methods */ - SHA512_dealloc, /*tp_dealloc*/ - 0, /*tp_print*/ - 0, /*tp_getattr*/ + SHA512_dealloc, /*tp_dealloc*/ + 0, /*tp_print*/ + 0, /*tp_getattr*/ 0, /*tp_setattr*/ 0, /*tp_reserved*/ 0, /*tp_repr*/ @@ -660,13 +660,13 @@ Py_TPFLAGS_DEFAULT, /*tp_flags*/ 0, /*tp_doc*/ 0, /*tp_traverse*/ - 0, /*tp_clear*/ - 0, /*tp_richcompare*/ - 0, /*tp_weaklistoffset*/ - 0, /*tp_iter*/ - 0, /*tp_iternext*/ - SHA_methods, /* tp_methods */ - SHA_members, /* tp_members */ + 0, /*tp_clear*/ + 0, /*tp_richcompare*/ + 0, /*tp_weaklistoffset*/ + 0, /*tp_iter*/ + 0, /*tp_iternext*/ + SHA_methods, /* tp_methods */ + SHA_members, /* tp_members */ SHA_getseters, /* tp_getset */ }; @@ -761,7 +761,7 @@ static struct PyMethodDef SHA_functions[] = { {"sha512", (PyCFunction)SHA512_new, METH_VARARGS|METH_KEYWORDS, SHA512_new__doc__}, {"sha384", (PyCFunction)SHA384_new, METH_VARARGS|METH_KEYWORDS, SHA384_new__doc__}, - {NULL, NULL} /* Sentinel */ + {NULL, NULL} /* Sentinel */ }; @@ -771,15 +771,15 @@ static struct PyModuleDef _sha512module = { - PyModuleDef_HEAD_INIT, - "_sha512", - NULL, - -1, - SHA_functions, - NULL, - NULL, - NULL, - NULL + PyModuleDef_HEAD_INIT, + "_sha512", + NULL, + -1, + SHA_functions, + NULL, + NULL, + NULL, + NULL }; PyMODINIT_FUNC Modified: python/branches/py3k/Modules/signalmodule.c ============================================================================== --- python/branches/py3k/Modules/signalmodule.c (original) +++ python/branches/py3k/Modules/signalmodule.c Sun May 9 17:52:27 2010 @@ -34,13 +34,13 @@ #ifndef NSIG # if defined(_NSIG) -# define NSIG _NSIG /* For BSD/SysV */ +# define NSIG _NSIG /* For BSD/SysV */ # elif defined(_SIGMAX) -# define NSIG (_SIGMAX + 1) /* For QNX */ +# define NSIG (_SIGMAX + 1) /* For QNX */ # elif defined(SIGMAX) -# define NSIG (SIGMAX + 1) /* For djgpp */ +# define NSIG (SIGMAX + 1) /* For djgpp */ # else -# define NSIG 64 /* Use a reasonable default value */ +# define NSIG 64 /* Use a reasonable default value */ # endif #endif @@ -82,8 +82,8 @@ #endif static struct { - int tripped; - PyObject *func; + int tripped; + PyObject *func; } Handlers[NSIG]; static sig_atomic_t wakeup_fd = -1; @@ -126,18 +126,18 @@ r = PyTuple_New(2); if (r == NULL) - return NULL; + return NULL; if(!(v = PyFloat_FromDouble(double_from_timeval(&iv->it_value)))) { - Py_DECREF(r); - return NULL; + Py_DECREF(r); + return NULL; } PyTuple_SET_ITEM(r, 0, v); if(!(v = PyFloat_FromDouble(double_from_timeval(&iv->it_interval)))) { - Py_DECREF(r); - return NULL; + Py_DECREF(r); + return NULL; } PyTuple_SET_ITEM(r, 1, v); @@ -149,8 +149,8 @@ static PyObject * signal_default_int_handler(PyObject *self, PyObject *args) { - PyErr_SetNone(PyExc_KeyboardInterrupt); - return NULL; + PyErr_SetNone(PyExc_KeyboardInterrupt); + return NULL; } PyDoc_STRVAR(default_int_handler_doc, @@ -163,7 +163,7 @@ static int checksignals_witharg(void * unused) { - return PyErr_CheckSignals(); + return PyErr_CheckSignals(); } static void @@ -171,38 +171,38 @@ { #ifdef WITH_THREAD #ifdef WITH_PTH - if (PyThread_get_thread_ident() != main_thread) { - pth_raise(*(pth_t *) main_thread, sig_num); - return; - } -#endif - /* See NOTES section above */ - if (getpid() == main_pid) { -#endif - Handlers[sig_num].tripped = 1; - /* Set is_tripped after setting .tripped, as it gets - cleared in PyErr_CheckSignals() before .tripped. */ - is_tripped = 1; - Py_AddPendingCall(checksignals_witharg, NULL); - if (wakeup_fd != -1) - write(wakeup_fd, "\0", 1); + if (PyThread_get_thread_ident() != main_thread) { + pth_raise(*(pth_t *) main_thread, sig_num); + return; + } +#endif + /* See NOTES section above */ + if (getpid() == main_pid) { +#endif + Handlers[sig_num].tripped = 1; + /* Set is_tripped after setting .tripped, as it gets + cleared in PyErr_CheckSignals() before .tripped. */ + is_tripped = 1; + Py_AddPendingCall(checksignals_witharg, NULL); + if (wakeup_fd != -1) + write(wakeup_fd, "\0", 1); #ifdef WITH_THREAD - } + } #endif #ifdef SIGCHLD - if (sig_num == SIGCHLD) { - /* To avoid infinite recursion, this signal remains - reset until explicit re-instated. - Don't clear the 'func' field as it is our pointer - to the Python handler... */ - return; - } + if (sig_num == SIGCHLD) { + /* To avoid infinite recursion, this signal remains + reset until explicit re-instated. + Don't clear the 'func' field as it is our pointer + to the Python handler... */ + return; + } #endif #ifndef HAVE_SIGACTION - /* If the handler was not set up with sigaction, reinstall it. See - * Python/pythonrun.c for the implementation of PyOS_setsig which - * makes this true. See also issue8354. */ - PyOS_setsig(sig_num, signal_handler); + /* If the handler was not set up with sigaction, reinstall it. See + * Python/pythonrun.c for the implementation of PyOS_setsig which + * makes this true. See also issue8354. */ + PyOS_setsig(sig_num, signal_handler); #endif } @@ -211,11 +211,11 @@ static PyObject * signal_alarm(PyObject *self, PyObject *args) { - int t; - if (!PyArg_ParseTuple(args, "i:alarm", &t)) - return NULL; - /* alarm() returns the number of seconds remaining */ - return PyLong_FromLong((long)alarm(t)); + int t; + if (!PyArg_ParseTuple(args, "i:alarm", &t)) + return NULL; + /* alarm() returns the number of seconds remaining */ + return PyLong_FromLong((long)alarm(t)); } PyDoc_STRVAR(alarm_doc, @@ -228,17 +228,17 @@ static PyObject * signal_pause(PyObject *self) { - Py_BEGIN_ALLOW_THREADS - (void)pause(); - Py_END_ALLOW_THREADS - /* make sure that any exceptions that got raised are propagated - * back into Python - */ - if (PyErr_CheckSignals()) - return NULL; + Py_BEGIN_ALLOW_THREADS + (void)pause(); + Py_END_ALLOW_THREADS + /* make sure that any exceptions that got raised are propagated + * back into Python + */ + if (PyErr_CheckSignals()) + return NULL; - Py_INCREF(Py_None); - return Py_None; + Py_INCREF(Py_None); + return Py_None; } PyDoc_STRVAR(pause_doc, "pause()\n\ @@ -251,44 +251,44 @@ static PyObject * signal_signal(PyObject *self, PyObject *args) { - PyObject *obj; - int sig_num; - PyObject *old_handler; - void (*func)(int); - if (!PyArg_ParseTuple(args, "iO:signal", &sig_num, &obj)) - return NULL; + PyObject *obj; + int sig_num; + PyObject *old_handler; + void (*func)(int); + if (!PyArg_ParseTuple(args, "iO:signal", &sig_num, &obj)) + return NULL; #ifdef WITH_THREAD - if (PyThread_get_thread_ident() != main_thread) { - PyErr_SetString(PyExc_ValueError, - "signal only works in main thread"); - return NULL; - } -#endif - if (sig_num < 1 || sig_num >= NSIG) { - PyErr_SetString(PyExc_ValueError, - "signal number out of range"); - return NULL; - } - if (obj == IgnoreHandler) - func = SIG_IGN; - else if (obj == DefaultHandler) - func = SIG_DFL; - else if (!PyCallable_Check(obj)) { - PyErr_SetString(PyExc_TypeError, + if (PyThread_get_thread_ident() != main_thread) { + PyErr_SetString(PyExc_ValueError, + "signal only works in main thread"); + return NULL; + } +#endif + if (sig_num < 1 || sig_num >= NSIG) { + PyErr_SetString(PyExc_ValueError, + "signal number out of range"); + return NULL; + } + if (obj == IgnoreHandler) + func = SIG_IGN; + else if (obj == DefaultHandler) + func = SIG_DFL; + else if (!PyCallable_Check(obj)) { + PyErr_SetString(PyExc_TypeError, "signal handler must be signal.SIG_IGN, signal.SIG_DFL, or a callable object"); - return NULL; - } - else - func = signal_handler; - if (PyOS_setsig(sig_num, func) == SIG_ERR) { - PyErr_SetFromErrno(PyExc_RuntimeError); - return NULL; - } - old_handler = Handlers[sig_num].func; - Handlers[sig_num].tripped = 0; - Py_INCREF(obj); - Handlers[sig_num].func = obj; - return old_handler; + return NULL; + } + else + func = signal_handler; + if (PyOS_setsig(sig_num, func) == SIG_ERR) { + PyErr_SetFromErrno(PyExc_RuntimeError); + return NULL; + } + old_handler = Handlers[sig_num].func; + Handlers[sig_num].tripped = 0; + Py_INCREF(obj); + Handlers[sig_num].func = obj; + return old_handler; } PyDoc_STRVAR(signal_doc, @@ -306,18 +306,18 @@ static PyObject * signal_getsignal(PyObject *self, PyObject *args) { - int sig_num; - PyObject *old_handler; - if (!PyArg_ParseTuple(args, "i:getsignal", &sig_num)) - return NULL; - if (sig_num < 1 || sig_num >= NSIG) { - PyErr_SetString(PyExc_ValueError, - "signal number out of range"); - return NULL; - } - old_handler = Handlers[sig_num].func; - Py_INCREF(old_handler); - return old_handler; + int sig_num; + PyObject *old_handler; + if (!PyArg_ParseTuple(args, "i:getsignal", &sig_num)) + return NULL; + if (sig_num < 1 || sig_num >= NSIG) { + PyErr_SetString(PyExc_ValueError, + "signal number out of range"); + return NULL; + } + old_handler = Handlers[sig_num].func; + Py_INCREF(old_handler); + return old_handler; } PyDoc_STRVAR(getsignal_doc, @@ -339,23 +339,23 @@ static PyObject * signal_siginterrupt(PyObject *self, PyObject *args) { - int sig_num; - int flag; + int sig_num; + int flag; - if (!PyArg_ParseTuple(args, "ii:siginterrupt", &sig_num, &flag)) - return NULL; - if (sig_num < 1 || sig_num >= NSIG) { - PyErr_SetString(PyExc_ValueError, - "signal number out of range"); - return NULL; - } - if (siginterrupt(sig_num, flag)<0) { - PyErr_SetFromErrno(PyExc_RuntimeError); - return NULL; - } + if (!PyArg_ParseTuple(args, "ii:siginterrupt", &sig_num, &flag)) + return NULL; + if (sig_num < 1 || sig_num >= NSIG) { + PyErr_SetString(PyExc_ValueError, + "signal number out of range"); + return NULL; + } + if (siginterrupt(sig_num, flag)<0) { + PyErr_SetFromErrno(PyExc_RuntimeError); + return NULL; + } - Py_INCREF(Py_None); - return Py_None; + Py_INCREF(Py_None); + return Py_None; } #endif @@ -363,24 +363,24 @@ static PyObject * signal_set_wakeup_fd(PyObject *self, PyObject *args) { - struct stat buf; - int fd, old_fd; - if (!PyArg_ParseTuple(args, "i:set_wakeup_fd", &fd)) - return NULL; + struct stat buf; + int fd, old_fd; + if (!PyArg_ParseTuple(args, "i:set_wakeup_fd", &fd)) + return NULL; #ifdef WITH_THREAD - if (PyThread_get_thread_ident() != main_thread) { - PyErr_SetString(PyExc_ValueError, - "set_wakeup_fd only works in main thread"); - return NULL; - } -#endif - if (fd != -1 && fstat(fd, &buf) != 0) { - PyErr_SetString(PyExc_ValueError, "invalid fd"); - return NULL; - } - old_fd = wakeup_fd; - wakeup_fd = fd; - return PyLong_FromLong(old_fd); + if (PyThread_get_thread_ident() != main_thread) { + PyErr_SetString(PyExc_ValueError, + "set_wakeup_fd only works in main thread"); + return NULL; + } +#endif + if (fd != -1 && fstat(fd, &buf) != 0) { + PyErr_SetString(PyExc_ValueError, "invalid fd"); + return NULL; + } + old_fd = wakeup_fd; + wakeup_fd = fd; + return PyLong_FromLong(old_fd); } PyDoc_STRVAR(set_wakeup_fd_doc, @@ -396,11 +396,11 @@ int PySignal_SetWakeupFd(int fd) { - int old_fd = wakeup_fd; - if (fd < 0) - fd = -1; - wakeup_fd = fd; - return old_fd; + int old_fd = wakeup_fd; + if (fd < 0) + fd = -1; + wakeup_fd = fd; + return old_fd; } @@ -414,14 +414,14 @@ struct itimerval new, old; if(!PyArg_ParseTuple(args, "id|d:setitimer", &which, &first, &interval)) - return NULL; + return NULL; timeval_from_double(first, &new.it_value); timeval_from_double(interval, &new.it_interval); /* Let OS check "which" value */ if (setitimer(which, &new, &old) != 0) { - PyErr_SetFromErrno(ItimerError); - return NULL; + PyErr_SetFromErrno(ItimerError); + return NULL; } return itimer_retval(&old); @@ -447,11 +447,11 @@ struct itimerval old; if (!PyArg_ParseTuple(args, "i:getitimer", &which)) - return NULL; + return NULL; if (getitimer(which, &old) != 0) { - PyErr_SetFromErrno(ItimerError); - return NULL; + PyErr_SetFromErrno(ItimerError); + return NULL; } return itimer_retval(&old); @@ -467,27 +467,27 @@ /* List of functions defined in the module */ static PyMethodDef signal_methods[] = { #ifdef HAVE_ALARM - {"alarm", signal_alarm, METH_VARARGS, alarm_doc}, + {"alarm", signal_alarm, METH_VARARGS, alarm_doc}, #endif #ifdef HAVE_SETITIMER {"setitimer", signal_setitimer, METH_VARARGS, setitimer_doc}, #endif #ifdef HAVE_GETITIMER - {"getitimer", signal_getitimer, METH_VARARGS, getitimer_doc}, + {"getitimer", signal_getitimer, METH_VARARGS, getitimer_doc}, #endif - {"signal", signal_signal, METH_VARARGS, signal_doc}, - {"getsignal", signal_getsignal, METH_VARARGS, getsignal_doc}, - {"set_wakeup_fd", signal_set_wakeup_fd, METH_VARARGS, set_wakeup_fd_doc}, + {"signal", signal_signal, METH_VARARGS, signal_doc}, + {"getsignal", signal_getsignal, METH_VARARGS, getsignal_doc}, + {"set_wakeup_fd", signal_set_wakeup_fd, METH_VARARGS, set_wakeup_fd_doc}, #ifdef HAVE_SIGINTERRUPT - {"siginterrupt", signal_siginterrupt, METH_VARARGS, siginterrupt_doc}, + {"siginterrupt", signal_siginterrupt, METH_VARARGS, siginterrupt_doc}, #endif #ifdef HAVE_PAUSE - {"pause", (PyCFunction)signal_pause, - METH_NOARGS,pause_doc}, + {"pause", (PyCFunction)signal_pause, + METH_NOARGS,pause_doc}, #endif - {"default_int_handler", signal_default_int_handler, - METH_VARARGS, default_int_handler_doc}, - {NULL, NULL} /* sentinel */ + {"default_int_handler", signal_default_int_handler, + METH_VARARGS, default_int_handler_doc}, + {NULL, NULL} /* sentinel */ }; @@ -528,264 +528,264 @@ the first is the signal number, the second is the interrupted stack frame."); static struct PyModuleDef signalmodule = { - PyModuleDef_HEAD_INIT, - "signal", - module_doc, - -1, - signal_methods, - NULL, - NULL, - NULL, - NULL + PyModuleDef_HEAD_INIT, + "signal", + module_doc, + -1, + signal_methods, + NULL, + NULL, + NULL, + NULL }; PyMODINIT_FUNC PyInit_signal(void) { - PyObject *m, *d, *x; - int i; + PyObject *m, *d, *x; + int i; #ifdef WITH_THREAD - main_thread = PyThread_get_thread_ident(); - main_pid = getpid(); + main_thread = PyThread_get_thread_ident(); + main_pid = getpid(); #endif - /* Create the module and add the functions */ - m = PyModule_Create(&signalmodule); - if (m == NULL) - return NULL; - - /* Add some symbolic constants to the module */ - d = PyModule_GetDict(m); - - x = DefaultHandler = PyLong_FromVoidPtr((void *)SIG_DFL); - if (!x || PyDict_SetItemString(d, "SIG_DFL", x) < 0) - goto finally; - - x = IgnoreHandler = PyLong_FromVoidPtr((void *)SIG_IGN); - if (!x || PyDict_SetItemString(d, "SIG_IGN", x) < 0) - goto finally; - - x = PyLong_FromLong((long)NSIG); - if (!x || PyDict_SetItemString(d, "NSIG", x) < 0) - goto finally; - Py_DECREF(x); - - x = IntHandler = PyDict_GetItemString(d, "default_int_handler"); - if (!x) - goto finally; - Py_INCREF(IntHandler); - - Handlers[0].tripped = 0; - for (i = 1; i < NSIG; i++) { - void (*t)(int); - t = PyOS_getsig(i); - Handlers[i].tripped = 0; - if (t == SIG_DFL) - Handlers[i].func = DefaultHandler; - else if (t == SIG_IGN) - Handlers[i].func = IgnoreHandler; - else - Handlers[i].func = Py_None; /* None of our business */ - Py_INCREF(Handlers[i].func); - } - if (Handlers[SIGINT].func == DefaultHandler) { - /* Install default int handler */ - Py_INCREF(IntHandler); - Py_DECREF(Handlers[SIGINT].func); - Handlers[SIGINT].func = IntHandler; - old_siginthandler = PyOS_setsig(SIGINT, signal_handler); - } + /* Create the module and add the functions */ + m = PyModule_Create(&signalmodule); + if (m == NULL) + return NULL; + + /* Add some symbolic constants to the module */ + d = PyModule_GetDict(m); + + x = DefaultHandler = PyLong_FromVoidPtr((void *)SIG_DFL); + if (!x || PyDict_SetItemString(d, "SIG_DFL", x) < 0) + goto finally; + + x = IgnoreHandler = PyLong_FromVoidPtr((void *)SIG_IGN); + if (!x || PyDict_SetItemString(d, "SIG_IGN", x) < 0) + goto finally; + + x = PyLong_FromLong((long)NSIG); + if (!x || PyDict_SetItemString(d, "NSIG", x) < 0) + goto finally; + Py_DECREF(x); + + x = IntHandler = PyDict_GetItemString(d, "default_int_handler"); + if (!x) + goto finally; + Py_INCREF(IntHandler); + + Handlers[0].tripped = 0; + for (i = 1; i < NSIG; i++) { + void (*t)(int); + t = PyOS_getsig(i); + Handlers[i].tripped = 0; + if (t == SIG_DFL) + Handlers[i].func = DefaultHandler; + else if (t == SIG_IGN) + Handlers[i].func = IgnoreHandler; + else + Handlers[i].func = Py_None; /* None of our business */ + Py_INCREF(Handlers[i].func); + } + if (Handlers[SIGINT].func == DefaultHandler) { + /* Install default int handler */ + Py_INCREF(IntHandler); + Py_DECREF(Handlers[SIGINT].func); + Handlers[SIGINT].func = IntHandler; + old_siginthandler = PyOS_setsig(SIGINT, signal_handler); + } #ifdef SIGHUP - x = PyLong_FromLong(SIGHUP); - PyDict_SetItemString(d, "SIGHUP", x); - Py_XDECREF(x); + x = PyLong_FromLong(SIGHUP); + PyDict_SetItemString(d, "SIGHUP", x); + Py_XDECREF(x); #endif #ifdef SIGINT - x = PyLong_FromLong(SIGINT); - PyDict_SetItemString(d, "SIGINT", x); - Py_XDECREF(x); + x = PyLong_FromLong(SIGINT); + PyDict_SetItemString(d, "SIGINT", x); + Py_XDECREF(x); #endif #ifdef SIGBREAK - x = PyLong_FromLong(SIGBREAK); - PyDict_SetItemString(d, "SIGBREAK", x); - Py_XDECREF(x); + x = PyLong_FromLong(SIGBREAK); + PyDict_SetItemString(d, "SIGBREAK", x); + Py_XDECREF(x); #endif #ifdef SIGQUIT - x = PyLong_FromLong(SIGQUIT); - PyDict_SetItemString(d, "SIGQUIT", x); - Py_XDECREF(x); + x = PyLong_FromLong(SIGQUIT); + PyDict_SetItemString(d, "SIGQUIT", x); + Py_XDECREF(x); #endif #ifdef SIGILL - x = PyLong_FromLong(SIGILL); - PyDict_SetItemString(d, "SIGILL", x); - Py_XDECREF(x); + x = PyLong_FromLong(SIGILL); + PyDict_SetItemString(d, "SIGILL", x); + Py_XDECREF(x); #endif #ifdef SIGTRAP - x = PyLong_FromLong(SIGTRAP); - PyDict_SetItemString(d, "SIGTRAP", x); - Py_XDECREF(x); + x = PyLong_FromLong(SIGTRAP); + PyDict_SetItemString(d, "SIGTRAP", x); + Py_XDECREF(x); #endif #ifdef SIGIOT - x = PyLong_FromLong(SIGIOT); - PyDict_SetItemString(d, "SIGIOT", x); - Py_XDECREF(x); + x = PyLong_FromLong(SIGIOT); + PyDict_SetItemString(d, "SIGIOT", x); + Py_XDECREF(x); #endif #ifdef SIGABRT - x = PyLong_FromLong(SIGABRT); - PyDict_SetItemString(d, "SIGABRT", x); - Py_XDECREF(x); + x = PyLong_FromLong(SIGABRT); + PyDict_SetItemString(d, "SIGABRT", x); + Py_XDECREF(x); #endif #ifdef SIGEMT - x = PyLong_FromLong(SIGEMT); - PyDict_SetItemString(d, "SIGEMT", x); - Py_XDECREF(x); + x = PyLong_FromLong(SIGEMT); + PyDict_SetItemString(d, "SIGEMT", x); + Py_XDECREF(x); #endif #ifdef SIGFPE - x = PyLong_FromLong(SIGFPE); - PyDict_SetItemString(d, "SIGFPE", x); - Py_XDECREF(x); + x = PyLong_FromLong(SIGFPE); + PyDict_SetItemString(d, "SIGFPE", x); + Py_XDECREF(x); #endif #ifdef SIGKILL - x = PyLong_FromLong(SIGKILL); - PyDict_SetItemString(d, "SIGKILL", x); - Py_XDECREF(x); + x = PyLong_FromLong(SIGKILL); + PyDict_SetItemString(d, "SIGKILL", x); + Py_XDECREF(x); #endif #ifdef SIGBUS - x = PyLong_FromLong(SIGBUS); - PyDict_SetItemString(d, "SIGBUS", x); - Py_XDECREF(x); + x = PyLong_FromLong(SIGBUS); + PyDict_SetItemString(d, "SIGBUS", x); + Py_XDECREF(x); #endif #ifdef SIGSEGV - x = PyLong_FromLong(SIGSEGV); - PyDict_SetItemString(d, "SIGSEGV", x); - Py_XDECREF(x); + x = PyLong_FromLong(SIGSEGV); + PyDict_SetItemString(d, "SIGSEGV", x); + Py_XDECREF(x); #endif #ifdef SIGSYS - x = PyLong_FromLong(SIGSYS); - PyDict_SetItemString(d, "SIGSYS", x); - Py_XDECREF(x); + x = PyLong_FromLong(SIGSYS); + PyDict_SetItemString(d, "SIGSYS", x); + Py_XDECREF(x); #endif #ifdef SIGPIPE - x = PyLong_FromLong(SIGPIPE); - PyDict_SetItemString(d, "SIGPIPE", x); - Py_XDECREF(x); + x = PyLong_FromLong(SIGPIPE); + PyDict_SetItemString(d, "SIGPIPE", x); + Py_XDECREF(x); #endif #ifdef SIGALRM - x = PyLong_FromLong(SIGALRM); - PyDict_SetItemString(d, "SIGALRM", x); - Py_XDECREF(x); + x = PyLong_FromLong(SIGALRM); + PyDict_SetItemString(d, "SIGALRM", x); + Py_XDECREF(x); #endif #ifdef SIGTERM - x = PyLong_FromLong(SIGTERM); - PyDict_SetItemString(d, "SIGTERM", x); - Py_XDECREF(x); + x = PyLong_FromLong(SIGTERM); + PyDict_SetItemString(d, "SIGTERM", x); + Py_XDECREF(x); #endif #ifdef SIGUSR1 - x = PyLong_FromLong(SIGUSR1); - PyDict_SetItemString(d, "SIGUSR1", x); - Py_XDECREF(x); + x = PyLong_FromLong(SIGUSR1); + PyDict_SetItemString(d, "SIGUSR1", x); + Py_XDECREF(x); #endif #ifdef SIGUSR2 - x = PyLong_FromLong(SIGUSR2); - PyDict_SetItemString(d, "SIGUSR2", x); - Py_XDECREF(x); + x = PyLong_FromLong(SIGUSR2); + PyDict_SetItemString(d, "SIGUSR2", x); + Py_XDECREF(x); #endif #ifdef SIGCLD - x = PyLong_FromLong(SIGCLD); - PyDict_SetItemString(d, "SIGCLD", x); - Py_XDECREF(x); + x = PyLong_FromLong(SIGCLD); + PyDict_SetItemString(d, "SIGCLD", x); + Py_XDECREF(x); #endif #ifdef SIGCHLD - x = PyLong_FromLong(SIGCHLD); - PyDict_SetItemString(d, "SIGCHLD", x); - Py_XDECREF(x); + x = PyLong_FromLong(SIGCHLD); + PyDict_SetItemString(d, "SIGCHLD", x); + Py_XDECREF(x); #endif #ifdef SIGPWR - x = PyLong_FromLong(SIGPWR); - PyDict_SetItemString(d, "SIGPWR", x); - Py_XDECREF(x); + x = PyLong_FromLong(SIGPWR); + PyDict_SetItemString(d, "SIGPWR", x); + Py_XDECREF(x); #endif #ifdef SIGIO - x = PyLong_FromLong(SIGIO); - PyDict_SetItemString(d, "SIGIO", x); - Py_XDECREF(x); + x = PyLong_FromLong(SIGIO); + PyDict_SetItemString(d, "SIGIO", x); + Py_XDECREF(x); #endif #ifdef SIGURG - x = PyLong_FromLong(SIGURG); - PyDict_SetItemString(d, "SIGURG", x); - Py_XDECREF(x); + x = PyLong_FromLong(SIGURG); + PyDict_SetItemString(d, "SIGURG", x); + Py_XDECREF(x); #endif #ifdef SIGWINCH - x = PyLong_FromLong(SIGWINCH); - PyDict_SetItemString(d, "SIGWINCH", x); - Py_XDECREF(x); + x = PyLong_FromLong(SIGWINCH); + PyDict_SetItemString(d, "SIGWINCH", x); + Py_XDECREF(x); #endif #ifdef SIGPOLL - x = PyLong_FromLong(SIGPOLL); - PyDict_SetItemString(d, "SIGPOLL", x); - Py_XDECREF(x); + x = PyLong_FromLong(SIGPOLL); + PyDict_SetItemString(d, "SIGPOLL", x); + Py_XDECREF(x); #endif #ifdef SIGSTOP - x = PyLong_FromLong(SIGSTOP); - PyDict_SetItemString(d, "SIGSTOP", x); - Py_XDECREF(x); + x = PyLong_FromLong(SIGSTOP); + PyDict_SetItemString(d, "SIGSTOP", x); + Py_XDECREF(x); #endif #ifdef SIGTSTP - x = PyLong_FromLong(SIGTSTP); - PyDict_SetItemString(d, "SIGTSTP", x); - Py_XDECREF(x); + x = PyLong_FromLong(SIGTSTP); + PyDict_SetItemString(d, "SIGTSTP", x); + Py_XDECREF(x); #endif #ifdef SIGCONT - x = PyLong_FromLong(SIGCONT); - PyDict_SetItemString(d, "SIGCONT", x); - Py_XDECREF(x); + x = PyLong_FromLong(SIGCONT); + PyDict_SetItemString(d, "SIGCONT", x); + Py_XDECREF(x); #endif #ifdef SIGTTIN - x = PyLong_FromLong(SIGTTIN); - PyDict_SetItemString(d, "SIGTTIN", x); - Py_XDECREF(x); + x = PyLong_FromLong(SIGTTIN); + PyDict_SetItemString(d, "SIGTTIN", x); + Py_XDECREF(x); #endif #ifdef SIGTTOU - x = PyLong_FromLong(SIGTTOU); - PyDict_SetItemString(d, "SIGTTOU", x); - Py_XDECREF(x); + x = PyLong_FromLong(SIGTTOU); + PyDict_SetItemString(d, "SIGTTOU", x); + Py_XDECREF(x); #endif #ifdef SIGVTALRM - x = PyLong_FromLong(SIGVTALRM); - PyDict_SetItemString(d, "SIGVTALRM", x); - Py_XDECREF(x); + x = PyLong_FromLong(SIGVTALRM); + PyDict_SetItemString(d, "SIGVTALRM", x); + Py_XDECREF(x); #endif #ifdef SIGPROF - x = PyLong_FromLong(SIGPROF); - PyDict_SetItemString(d, "SIGPROF", x); - Py_XDECREF(x); + x = PyLong_FromLong(SIGPROF); + PyDict_SetItemString(d, "SIGPROF", x); + Py_XDECREF(x); #endif #ifdef SIGXCPU - x = PyLong_FromLong(SIGXCPU); - PyDict_SetItemString(d, "SIGXCPU", x); - Py_XDECREF(x); + x = PyLong_FromLong(SIGXCPU); + PyDict_SetItemString(d, "SIGXCPU", x); + Py_XDECREF(x); #endif #ifdef SIGXFSZ - x = PyLong_FromLong(SIGXFSZ); - PyDict_SetItemString(d, "SIGXFSZ", x); - Py_XDECREF(x); + x = PyLong_FromLong(SIGXFSZ); + PyDict_SetItemString(d, "SIGXFSZ", x); + Py_XDECREF(x); #endif #ifdef SIGRTMIN - x = PyLong_FromLong(SIGRTMIN); - PyDict_SetItemString(d, "SIGRTMIN", x); - Py_XDECREF(x); + x = PyLong_FromLong(SIGRTMIN); + PyDict_SetItemString(d, "SIGRTMIN", x); + Py_XDECREF(x); #endif #ifdef SIGRTMAX - x = PyLong_FromLong(SIGRTMAX); - PyDict_SetItemString(d, "SIGRTMAX", x); - Py_XDECREF(x); + x = PyLong_FromLong(SIGRTMAX); + PyDict_SetItemString(d, "SIGRTMAX", x); + Py_XDECREF(x); #endif #ifdef SIGINFO - x = PyLong_FromLong(SIGINFO); - PyDict_SetItemString(d, "SIGINFO", x); - Py_XDECREF(x); + x = PyLong_FromLong(SIGINFO); + PyDict_SetItemString(d, "SIGINFO", x); + Py_XDECREF(x); #endif #ifdef ITIMER_REAL @@ -805,10 +805,10 @@ #endif #if defined (HAVE_SETITIMER) || defined (HAVE_GETITIMER) - ItimerError = PyErr_NewException("signal.ItimerError", - PyExc_IOError, NULL); + ItimerError = PyErr_NewException("signal.ItimerError", + PyExc_IOError, NULL); if (ItimerError != NULL) - PyDict_SetItemString(d, "ItimerError", ItimerError); + PyDict_SetItemString(d, "ItimerError", ItimerError); #endif #ifdef CTRL_C_EVENT @@ -824,8 +824,8 @@ #endif if (PyErr_Occurred()) { - Py_DECREF(m); - m = NULL; + Py_DECREF(m); + m = NULL; } finally: @@ -835,28 +835,28 @@ static void finisignal(void) { - int i; - PyObject *func; + int i; + PyObject *func; - PyOS_setsig(SIGINT, old_siginthandler); - old_siginthandler = SIG_DFL; + 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 && - func != DefaultHandler && func != IgnoreHandler) - PyOS_setsig(i, SIG_DFL); - Py_XDECREF(func); - } - - Py_XDECREF(IntHandler); - IntHandler = NULL; - Py_XDECREF(DefaultHandler); - DefaultHandler = NULL; - Py_XDECREF(IgnoreHandler); - IgnoreHandler = NULL; + 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 && + func != DefaultHandler && func != IgnoreHandler) + PyOS_setsig(i, SIG_DFL); + Py_XDECREF(func); + } + + Py_XDECREF(IntHandler); + IntHandler = NULL; + Py_XDECREF(DefaultHandler); + DefaultHandler = NULL; + Py_XDECREF(IgnoreHandler); + IgnoreHandler = NULL; } @@ -864,55 +864,55 @@ int PyErr_CheckSignals(void) { - int i; - PyObject *f; + int i; + PyObject *f; - if (!is_tripped) - return 0; + if (!is_tripped) + return 0; #ifdef WITH_THREAD - if (PyThread_get_thread_ident() != main_thread) - return 0; + if (PyThread_get_thread_ident() != main_thread) + return 0; #endif - /* - * The is_tripped variable is meant to speed up the calls to - * PyErr_CheckSignals (both directly or via pending calls) when no - * signal has arrived. This variable is set to 1 when a signal arrives - * and it is set to 0 here, when we know some signals arrived. This way - * we can run the registered handlers with no signals blocked. - * - * NOTE: with this approach we can have a situation where is_tripped is - * 1 but we have no more signals to handle (Handlers[i].tripped - * is 0 for every signal i). This won't do us any harm (except - * we're gonna spent some cycles for nothing). This happens when - * we receive a signal i after we zero is_tripped and before we - * check Handlers[i].tripped. - */ - is_tripped = 0; - - if (!(f = (PyObject *)PyEval_GetFrame())) - f = Py_None; - - for (i = 1; i < NSIG; i++) { - if (Handlers[i].tripped) { - PyObject *result = NULL; - PyObject *arglist = Py_BuildValue("(iO)", i, f); - Handlers[i].tripped = 0; - - if (arglist) { - result = PyEval_CallObject(Handlers[i].func, - arglist); - Py_DECREF(arglist); - } - if (!result) - return -1; - - Py_DECREF(result); - } - } + /* + * The is_tripped variable is meant to speed up the calls to + * PyErr_CheckSignals (both directly or via pending calls) when no + * signal has arrived. This variable is set to 1 when a signal arrives + * and it is set to 0 here, when we know some signals arrived. This way + * we can run the registered handlers with no signals blocked. + * + * NOTE: with this approach we can have a situation where is_tripped is + * 1 but we have no more signals to handle (Handlers[i].tripped + * is 0 for every signal i). This won't do us any harm (except + * we're gonna spent some cycles for nothing). This happens when + * we receive a signal i after we zero is_tripped and before we + * check Handlers[i].tripped. + */ + is_tripped = 0; + + if (!(f = (PyObject *)PyEval_GetFrame())) + f = Py_None; + + for (i = 1; i < NSIG; i++) { + if (Handlers[i].tripped) { + PyObject *result = NULL; + PyObject *arglist = Py_BuildValue("(iO)", i, f); + Handlers[i].tripped = 0; + + if (arglist) { + result = PyEval_CallObject(Handlers[i].func, + arglist); + Py_DECREF(arglist); + } + if (!result) + return -1; + + Py_DECREF(result); + } + } - return 0; + return 0; } @@ -922,49 +922,49 @@ void PyErr_SetInterrupt(void) { - is_tripped = 1; - Handlers[SIGINT].tripped = 1; - Py_AddPendingCall((int (*)(void *))PyErr_CheckSignals, NULL); + is_tripped = 1; + Handlers[SIGINT].tripped = 1; + Py_AddPendingCall((int (*)(void *))PyErr_CheckSignals, NULL); } void PyOS_InitInterrupts(void) { - PyObject *m = PyInit_signal(); - if (m) { - _PyImport_FixupExtension(m, "signal", "signal"); - Py_DECREF(m); - } + PyObject *m = PyInit_signal(); + if (m) { + _PyImport_FixupExtension(m, "signal", "signal"); + Py_DECREF(m); + } } void PyOS_FiniInterrupts(void) { - finisignal(); + finisignal(); } int PyOS_InterruptOccurred(void) { - if (Handlers[SIGINT].tripped) { + if (Handlers[SIGINT].tripped) { #ifdef WITH_THREAD - if (PyThread_get_thread_ident() != main_thread) - return 0; + if (PyThread_get_thread_ident() != main_thread) + return 0; #endif - Handlers[SIGINT].tripped = 0; - return 1; - } - return 0; + Handlers[SIGINT].tripped = 0; + return 1; + } + return 0; } void PyOS_AfterFork(void) { #ifdef WITH_THREAD - PyEval_ReInitThreads(); - main_thread = PyThread_get_thread_ident(); - main_pid = getpid(); - _PyImport_ReInitLock(); - PyThread_ReInitTLS(); + PyEval_ReInitThreads(); + main_thread = PyThread_get_thread_ident(); + main_pid = getpid(); + _PyImport_ReInitLock(); + PyThread_ReInitTLS(); #endif } Modified: python/branches/py3k/Modules/socketmodule.c ============================================================================== --- python/branches/py3k/Modules/socketmodule.c (original) +++ python/branches/py3k/Modules/socketmodule.c Sun May 9 17:52:27 2010 @@ -17,9 +17,9 @@ - socket.error: exception raised for socket specific errors - socket.gaierror: exception raised for getaddrinfo/getnameinfo errors, - a subclass of socket.error + a subclass of socket.error - socket.herror: exception raised for gethostby* errors, - a subclass of socket.error + a subclass of socket.error - socket.gethostbyname(hostname) --> host IP address (string: 'dd.dd.dd.dd') - socket.gethostbyaddr(IP address) --> (hostname, [alias, ...], [IP addr, ...]) - socket.gethostname() --> host name (string: 'spam' or 'spam.domain.com') @@ -27,14 +27,14 @@ - socket.getservbyname(servicename[, protocolname]) --> port number - socket.getservbyport(portnumber[, protocolname]) --> service name - socket.socket([family[, type [, proto, fileno]]]) --> new socket object - (fileno specifies a pre-existing socket file descriptor) + (fileno specifies a pre-existing socket file descriptor) - socket.socketpair([family[, type [, proto]]]) --> (socket, socket) - socket.ntohs(16 bit value) --> new int object - socket.ntohl(32 bit value) --> new int object - socket.htons(16 bit value) --> new int object - socket.htonl(32 bit value) --> new int object - socket.getaddrinfo(host, port [, family, socktype, proto, flags]) - --> List of (family, socktype, proto, canonname, sockaddr) + --> List of (family, socktype, proto, canonname, sockaddr) - socket.getnameinfo(sockaddr, flags) --> (host, port) - socket.AF_INET, socket.SOCK_STREAM, etc.: constants from - socket.has_ipv6: boolean value indicating if IPv6 is supported @@ -54,22 +54,22 @@ specify packet-type and ha-type/addr. - an AF_TIPC socket address is expressed as (addr_type, v1, v2, v3 [, scope]); where addr_type can be one of: - TIPC_ADDR_NAMESEQ, TIPC_ADDR_NAME, and TIPC_ADDR_ID; + TIPC_ADDR_NAMESEQ, TIPC_ADDR_NAME, and TIPC_ADDR_ID; and scope can be one of: - TIPC_ZONE_SCOPE, TIPC_CLUSTER_SCOPE, and TIPC_NODE_SCOPE. + TIPC_ZONE_SCOPE, TIPC_CLUSTER_SCOPE, and TIPC_NODE_SCOPE. The meaning of v1, v2 and v3 depends on the value of addr_type: - if addr_type is TIPC_ADDR_NAME: - v1 is the server type - v2 is the port identifier - v3 is ignored - if addr_type is TIPC_ADDR_NAMESEQ: - v1 is the server type - v2 is the lower port number - v3 is the upper port number - if addr_type is TIPC_ADDR_ID: - v1 is the node - v2 is the ref - v3 is ignored + if addr_type is TIPC_ADDR_NAME: + v1 is the server type + v2 is the port identifier + v3 is ignored + if addr_type is TIPC_ADDR_NAMESEQ: + v1 is the server type + v2 is the lower port number + v3 is the upper port number + if addr_type is TIPC_ADDR_ID: + v1 is the node + v2 is the ref + v3 is ignored Local naming conventions: @@ -283,7 +283,7 @@ #include #ifndef offsetof -# define offsetof(type, member) ((size_t)(&((type *)0)->member)) +# define offsetof(type, member) ((size_t)(&((type *)0)->member)) #endif #ifndef O_NONBLOCK @@ -351,16 +351,16 @@ static SOCKET dup_socket(SOCKET handle) { - HANDLE newhandle; + HANDLE newhandle; - if (!DuplicateHandle(GetCurrentProcess(), (HANDLE)handle, - GetCurrentProcess(), &newhandle, - 0, FALSE, DUPLICATE_SAME_ACCESS)) - { - WSASetLastError(GetLastError()); - return INVALID_SOCKET; - } - return (SOCKET)newhandle; + if (!DuplicateHandle(GetCurrentProcess(), (HANDLE)handle, + GetCurrentProcess(), &newhandle, + 0, FALSE, DUPLICATE_SAME_ACCESS)) + { + WSASetLastError(GetLastError()); + return INVALID_SOCKET; + } + return (SOCKET)newhandle; } #define SOCKETCLOSE closesocket #else @@ -418,7 +418,7 @@ #define SEGMENT_SIZE (32 * 1024 -1) #endif -#define SAS2SA(x) ((struct sockaddr *)(x)) +#define SAS2SA(x) ((struct sockaddr *)(x)) /* * Constants for getnameinfo() @@ -473,8 +473,8 @@ static PyObject* select_error(void) { - PyErr_SetString(socket_error, "unable to select on socket"); - return NULL; + PyErr_SetString(socket_error, "unable to select on socket"); + return NULL; } /* Convenience function to raise an error according to errno @@ -484,95 +484,95 @@ set_error(void) { #ifdef MS_WINDOWS - int err_no = WSAGetLastError(); - /* PyErr_SetExcFromWindowsErr() invokes FormatMessage() which - recognizes the error codes used by both GetLastError() and - WSAGetLastError */ - if (err_no) - return PyErr_SetExcFromWindowsErr(socket_error, err_no); + int err_no = WSAGetLastError(); + /* PyErr_SetExcFromWindowsErr() invokes FormatMessage() which + recognizes the error codes used by both GetLastError() and + WSAGetLastError */ + if (err_no) + return PyErr_SetExcFromWindowsErr(socket_error, err_no); #endif #if defined(PYOS_OS2) && !defined(PYCC_GCC) - if (sock_errno() != NO_ERROR) { - APIRET rc; - ULONG msglen; - char outbuf[100]; - int myerrorcode = sock_errno(); - - /* Retrieve socket-related error message from MPTN.MSG file */ - rc = DosGetMessage(NULL, 0, outbuf, sizeof(outbuf), - myerrorcode - SOCBASEERR + 26, - "mptn.msg", - &msglen); - if (rc == NO_ERROR) { - PyObject *v; - - /* OS/2 doesn't guarantee a terminator */ - outbuf[msglen] = '\0'; - if (strlen(outbuf) > 0) { - /* If non-empty msg, trim CRLF */ - char *lastc = &outbuf[ strlen(outbuf)-1 ]; - while (lastc > outbuf && - isspace(Py_CHARMASK(*lastc))) { - /* Trim trailing whitespace (CRLF) */ - *lastc-- = '\0'; - } - } - v = Py_BuildValue("(is)", myerrorcode, outbuf); - if (v != NULL) { - PyErr_SetObject(socket_error, v); - Py_DECREF(v); - } - return NULL; - } - } + if (sock_errno() != NO_ERROR) { + APIRET rc; + ULONG msglen; + char outbuf[100]; + int myerrorcode = sock_errno(); + + /* Retrieve socket-related error message from MPTN.MSG file */ + rc = DosGetMessage(NULL, 0, outbuf, sizeof(outbuf), + myerrorcode - SOCBASEERR + 26, + "mptn.msg", + &msglen); + if (rc == NO_ERROR) { + PyObject *v; + + /* OS/2 doesn't guarantee a terminator */ + outbuf[msglen] = '\0'; + if (strlen(outbuf) > 0) { + /* If non-empty msg, trim CRLF */ + char *lastc = &outbuf[ strlen(outbuf)-1 ]; + while (lastc > outbuf && + isspace(Py_CHARMASK(*lastc))) { + /* Trim trailing whitespace (CRLF) */ + *lastc-- = '\0'; + } + } + v = Py_BuildValue("(is)", myerrorcode, outbuf); + if (v != NULL) { + PyErr_SetObject(socket_error, v); + Py_DECREF(v); + } + return NULL; + } + } #endif - return PyErr_SetFromErrno(socket_error); + return PyErr_SetFromErrno(socket_error); } static PyObject * set_herror(int h_error) { - PyObject *v; + PyObject *v; #ifdef HAVE_HSTRERROR - v = Py_BuildValue("(is)", h_error, (char *)hstrerror(h_error)); + v = Py_BuildValue("(is)", h_error, (char *)hstrerror(h_error)); #else - v = Py_BuildValue("(is)", h_error, "host not found"); + v = Py_BuildValue("(is)", h_error, "host not found"); #endif - if (v != NULL) { - PyErr_SetObject(socket_herror, v); - Py_DECREF(v); - } + if (v != NULL) { + PyErr_SetObject(socket_herror, v); + Py_DECREF(v); + } - return NULL; + return NULL; } static PyObject * set_gaierror(int error) { - PyObject *v; + PyObject *v; #ifdef EAI_SYSTEM - /* EAI_SYSTEM is not available on Windows XP. */ - if (error == EAI_SYSTEM) - return set_error(); + /* EAI_SYSTEM is not available on Windows XP. */ + if (error == EAI_SYSTEM) + return set_error(); #endif #ifdef HAVE_GAI_STRERROR - v = Py_BuildValue("(is)", error, gai_strerror(error)); + v = Py_BuildValue("(is)", error, gai_strerror(error)); #else - v = Py_BuildValue("(is)", error, "getaddrinfo failed"); + v = Py_BuildValue("(is)", error, "getaddrinfo failed"); #endif - if (v != NULL) { - PyErr_SetObject(socket_gaierror, v); - Py_DECREF(v); - } + if (v != NULL) { + PyErr_SetObject(socket_gaierror, v); + Py_DECREF(v); + } - return NULL; + return NULL; } #ifdef __VMS @@ -580,22 +580,22 @@ static int sendsegmented(int sock_fd, char *buf, int len, int flags) { - int n = 0; - int remaining = len; + int n = 0; + int remaining = len; - while (remaining > 0) { - unsigned int segment; + while (remaining > 0) { + unsigned int segment; - segment = (remaining >= SEGMENT_SIZE ? SEGMENT_SIZE : remaining); - n = send(sock_fd, buf, segment, flags); - if (n < 0) { - return n; - } - remaining -= segment; - buf += segment; - } /* end while */ + segment = (remaining >= SEGMENT_SIZE ? SEGMENT_SIZE : remaining); + n = send(sock_fd, buf, segment, flags); + if (n < 0) { + return n; + } + remaining -= segment; + buf += segment; + } /* end while */ - return len; + return len; } #endif @@ -605,33 +605,33 @@ internal_setblocking(PySocketSockObject *s, int block) { #ifndef MS_WINDOWS - int delay_flag; + int delay_flag; #endif - Py_BEGIN_ALLOW_THREADS + Py_BEGIN_ALLOW_THREADS #ifndef MS_WINDOWS #if defined(PYOS_OS2) && !defined(PYCC_GCC) - block = !block; - ioctl(s->sock_fd, FIONBIO, (caddr_t)&block, sizeof(block)); + block = !block; + ioctl(s->sock_fd, FIONBIO, (caddr_t)&block, sizeof(block)); #elif defined(__VMS) - block = !block; - ioctl(s->sock_fd, FIONBIO, (unsigned int *)&block); + block = !block; + ioctl(s->sock_fd, FIONBIO, (unsigned int *)&block); #else /* !PYOS_OS2 && !__VMS */ - delay_flag = fcntl(s->sock_fd, F_GETFL, 0); - if (block) - delay_flag &= (~O_NONBLOCK); - else - delay_flag |= O_NONBLOCK; - fcntl(s->sock_fd, F_SETFL, delay_flag); + delay_flag = fcntl(s->sock_fd, F_GETFL, 0); + if (block) + delay_flag &= (~O_NONBLOCK); + else + delay_flag |= O_NONBLOCK; + fcntl(s->sock_fd, F_SETFL, delay_flag); #endif /* !PYOS_OS2 */ #else /* MS_WINDOWS */ - block = !block; - ioctlsocket(s->sock_fd, FIONBIO, (u_long*)&block); + block = !block; + ioctlsocket(s->sock_fd, FIONBIO, (u_long*)&block); #endif /* MS_WINDOWS */ - Py_END_ALLOW_THREADS + Py_END_ALLOW_THREADS - /* Since these don't return anything */ - return 1; + /* Since these don't return anything */ + return 1; } /* Do a select()/poll() on the socket, if necessary (sock_timeout > 0). @@ -642,53 +642,53 @@ static int internal_select(PySocketSockObject *s, int writing) { - int n; + int n; - /* Nothing to do unless we're in timeout mode (not non-blocking) */ - if (s->sock_timeout <= 0.0) - return 0; - - /* Guard against closed socket */ - if (s->sock_fd < 0) - return 0; + /* Nothing to do unless we're in timeout mode (not non-blocking) */ + if (s->sock_timeout <= 0.0) + return 0; + + /* Guard against closed socket */ + if (s->sock_fd < 0) + return 0; - /* Prefer poll, if available, since you can poll() any fd - * which can't be done with select(). */ + /* Prefer poll, if available, since you can poll() any fd + * which can't be done with select(). */ #ifdef HAVE_POLL - { - struct pollfd pollfd; - int timeout; - - pollfd.fd = s->sock_fd; - pollfd.events = writing ? POLLOUT : POLLIN; - - /* s->sock_timeout is in seconds, timeout in ms */ - timeout = (int)(s->sock_timeout * 1000 + 0.5); - n = poll(&pollfd, 1, timeout); - } -#else - { - /* Construct the arguments to select */ - fd_set fds; - struct timeval tv; - tv.tv_sec = (int)s->sock_timeout; - tv.tv_usec = (int)((s->sock_timeout - tv.tv_sec) * 1e6); - FD_ZERO(&fds); - FD_SET(s->sock_fd, &fds); - - /* See if the socket is ready */ - if (writing) - n = select(s->sock_fd+1, NULL, &fds, NULL, &tv); - else - n = select(s->sock_fd+1, &fds, NULL, NULL, &tv); - } -#endif - - if (n < 0) - return -1; - if (n == 0) - return 1; - return 0; + { + struct pollfd pollfd; + int timeout; + + pollfd.fd = s->sock_fd; + pollfd.events = writing ? POLLOUT : POLLIN; + + /* s->sock_timeout is in seconds, timeout in ms */ + timeout = (int)(s->sock_timeout * 1000 + 0.5); + n = poll(&pollfd, 1, timeout); + } +#else + { + /* Construct the arguments to select */ + fd_set fds; + struct timeval tv; + tv.tv_sec = (int)s->sock_timeout; + tv.tv_usec = (int)((s->sock_timeout - tv.tv_sec) * 1e6); + FD_ZERO(&fds); + FD_SET(s->sock_fd, &fds); + + /* See if the socket is ready */ + if (writing) + n = select(s->sock_fd+1, NULL, &fds, NULL, &tv); + else + n = select(s->sock_fd+1, &fds, NULL, NULL, &tv); + } +#endif + + if (n < 0) + return -1; + if (n == 0) + return 1; + return 0; } /* Initialize a new socket object. */ @@ -697,18 +697,18 @@ static void init_sockobject(PySocketSockObject *s, - SOCKET_T fd, int family, int type, int proto) + SOCKET_T fd, int family, int type, int proto) { - s->sock_fd = fd; - s->sock_family = family; - s->sock_type = type; - s->sock_proto = proto; - s->sock_timeout = defaulttimeout; + s->sock_fd = fd; + s->sock_family = family; + s->sock_type = type; + s->sock_proto = proto; + s->sock_timeout = defaulttimeout; - s->errorhandler = &set_error; + s->errorhandler = &set_error; - if (defaulttimeout >= 0.0) - internal_setblocking(s, 0); + if (defaulttimeout >= 0.0) + internal_setblocking(s, 0); } @@ -721,12 +721,12 @@ static PySocketSockObject * new_sockobject(SOCKET_T fd, int family, int type, int proto) { - PySocketSockObject *s; - s = (PySocketSockObject *) - PyType_GenericNew(&sock_type, NULL, NULL); - if (s != NULL) - init_sockobject(s, fd, family, type, proto); - return s; + PySocketSockObject *s; + s = (PySocketSockObject *) + PyType_GenericNew(&sock_type, NULL, NULL); + if (s != NULL) + init_sockobject(s, fd, family, type, proto); + return s; } @@ -746,122 +746,122 @@ static int setipaddr(char *name, struct sockaddr *addr_ret, size_t addr_ret_size, int af) { - struct addrinfo hints, *res; - int error; - int d1, d2, d3, d4; - char ch; - - memset((void *) addr_ret, '\0', sizeof(*addr_ret)); - if (name[0] == '\0') { - int siz; - memset(&hints, 0, sizeof(hints)); - hints.ai_family = af; - hints.ai_socktype = SOCK_DGRAM; /*dummy*/ - hints.ai_flags = AI_PASSIVE; - Py_BEGIN_ALLOW_THREADS - ACQUIRE_GETADDRINFO_LOCK - error = getaddrinfo(NULL, "0", &hints, &res); - Py_END_ALLOW_THREADS - /* We assume that those thread-unsafe getaddrinfo() versions - *are* safe regarding their return value, ie. that a - subsequent call to getaddrinfo() does not destroy the - outcome of the first call. */ - RELEASE_GETADDRINFO_LOCK - if (error) { - set_gaierror(error); - return -1; - } - switch (res->ai_family) { - case AF_INET: - siz = 4; - break; + struct addrinfo hints, *res; + int error; + int d1, d2, d3, d4; + char ch; + + memset((void *) addr_ret, '\0', sizeof(*addr_ret)); + if (name[0] == '\0') { + int siz; + memset(&hints, 0, sizeof(hints)); + hints.ai_family = af; + hints.ai_socktype = SOCK_DGRAM; /*dummy*/ + hints.ai_flags = AI_PASSIVE; + Py_BEGIN_ALLOW_THREADS + ACQUIRE_GETADDRINFO_LOCK + error = getaddrinfo(NULL, "0", &hints, &res); + Py_END_ALLOW_THREADS + /* We assume that those thread-unsafe getaddrinfo() versions + *are* safe regarding their return value, ie. that a + subsequent call to getaddrinfo() does not destroy the + outcome of the first call. */ + RELEASE_GETADDRINFO_LOCK + if (error) { + set_gaierror(error); + return -1; + } + switch (res->ai_family) { + case AF_INET: + siz = 4; + break; #ifdef ENABLE_IPV6 - case AF_INET6: - siz = 16; - break; -#endif - default: - freeaddrinfo(res); - PyErr_SetString(socket_error, - "unsupported address family"); - return -1; - } - if (res->ai_next) { - freeaddrinfo(res); - PyErr_SetString(socket_error, - "wildcard resolved to multiple address"); - return -1; - } - if (res->ai_addrlen < addr_ret_size) - addr_ret_size = res->ai_addrlen; - memcpy(addr_ret, res->ai_addr, addr_ret_size); - freeaddrinfo(res); - return siz; - } - if (name[0] == '<' && strcmp(name, "") == 0) { - struct sockaddr_in *sin; - if (af != AF_INET && af != AF_UNSPEC) { - PyErr_SetString(socket_error, - "address family mismatched"); - return -1; - } - sin = (struct sockaddr_in *)addr_ret; - memset((void *) sin, '\0', sizeof(*sin)); - sin->sin_family = AF_INET; + case AF_INET6: + siz = 16; + break; +#endif + default: + freeaddrinfo(res); + PyErr_SetString(socket_error, + "unsupported address family"); + return -1; + } + if (res->ai_next) { + freeaddrinfo(res); + PyErr_SetString(socket_error, + "wildcard resolved to multiple address"); + return -1; + } + if (res->ai_addrlen < addr_ret_size) + addr_ret_size = res->ai_addrlen; + memcpy(addr_ret, res->ai_addr, addr_ret_size); + freeaddrinfo(res); + return siz; + } + if (name[0] == '<' && strcmp(name, "") == 0) { + struct sockaddr_in *sin; + if (af != AF_INET && af != AF_UNSPEC) { + PyErr_SetString(socket_error, + "address family mismatched"); + return -1; + } + sin = (struct sockaddr_in *)addr_ret; + memset((void *) sin, '\0', sizeof(*sin)); + sin->sin_family = AF_INET; #ifdef HAVE_SOCKADDR_SA_LEN - sin->sin_len = sizeof(*sin); + sin->sin_len = sizeof(*sin); #endif - sin->sin_addr.s_addr = INADDR_BROADCAST; - return sizeof(sin->sin_addr); - } - if (sscanf(name, "%d.%d.%d.%d%c", &d1, &d2, &d3, &d4, &ch) == 4 && - 0 <= d1 && d1 <= 255 && 0 <= d2 && d2 <= 255 && - 0 <= d3 && d3 <= 255 && 0 <= d4 && d4 <= 255) { - struct sockaddr_in *sin; - sin = (struct sockaddr_in *)addr_ret; - sin->sin_addr.s_addr = htonl( - ((long) d1 << 24) | ((long) d2 << 16) | - ((long) d3 << 8) | ((long) d4 << 0)); - sin->sin_family = AF_INET; + sin->sin_addr.s_addr = INADDR_BROADCAST; + return sizeof(sin->sin_addr); + } + if (sscanf(name, "%d.%d.%d.%d%c", &d1, &d2, &d3, &d4, &ch) == 4 && + 0 <= d1 && d1 <= 255 && 0 <= d2 && d2 <= 255 && + 0 <= d3 && d3 <= 255 && 0 <= d4 && d4 <= 255) { + struct sockaddr_in *sin; + sin = (struct sockaddr_in *)addr_ret; + sin->sin_addr.s_addr = htonl( + ((long) d1 << 24) | ((long) d2 << 16) | + ((long) d3 << 8) | ((long) d4 << 0)); + sin->sin_family = AF_INET; #ifdef HAVE_SOCKADDR_SA_LEN - sin->sin_len = sizeof(*sin); + sin->sin_len = sizeof(*sin); #endif - return 4; - } - memset(&hints, 0, sizeof(hints)); - hints.ai_family = af; - Py_BEGIN_ALLOW_THREADS - ACQUIRE_GETADDRINFO_LOCK - error = getaddrinfo(name, NULL, &hints, &res); + return 4; + } + memset(&hints, 0, sizeof(hints)); + hints.ai_family = af; + Py_BEGIN_ALLOW_THREADS + ACQUIRE_GETADDRINFO_LOCK + error = getaddrinfo(name, NULL, &hints, &res); #if defined(__digital__) && defined(__unix__) - if (error == EAI_NONAME && af == AF_UNSPEC) { - /* On Tru64 V5.1, numeric-to-addr conversion fails - if no address family is given. Assume IPv4 for now.*/ - hints.ai_family = AF_INET; - error = getaddrinfo(name, NULL, &hints, &res); - } -#endif - Py_END_ALLOW_THREADS - RELEASE_GETADDRINFO_LOCK /* see comment in setipaddr() */ - if (error) { - set_gaierror(error); - return -1; - } - if (res->ai_addrlen < addr_ret_size) - addr_ret_size = res->ai_addrlen; - memcpy((char *) addr_ret, res->ai_addr, addr_ret_size); - freeaddrinfo(res); - switch (addr_ret->sa_family) { - case AF_INET: - return 4; + if (error == EAI_NONAME && af == AF_UNSPEC) { + /* On Tru64 V5.1, numeric-to-addr conversion fails + if no address family is given. Assume IPv4 for now.*/ + hints.ai_family = AF_INET; + error = getaddrinfo(name, NULL, &hints, &res); + } +#endif + Py_END_ALLOW_THREADS + RELEASE_GETADDRINFO_LOCK /* see comment in setipaddr() */ + if (error) { + set_gaierror(error); + return -1; + } + if (res->ai_addrlen < addr_ret_size) + addr_ret_size = res->ai_addrlen; + memcpy((char *) addr_ret, res->ai_addr, addr_ret_size); + freeaddrinfo(res); + switch (addr_ret->sa_family) { + case AF_INET: + return 4; #ifdef ENABLE_IPV6 - case AF_INET6: - return 16; + case AF_INET6: + return 16; #endif - default: - PyErr_SetString(socket_error, "unknown address family"); - return -1; - } + default: + PyErr_SetString(socket_error, "unknown address family"); + return -1; + } } @@ -872,16 +872,16 @@ static PyObject * makeipaddr(struct sockaddr *addr, int addrlen) { - char buf[NI_MAXHOST]; - int error; + char buf[NI_MAXHOST]; + int error; - error = getnameinfo(addr, addrlen, buf, sizeof(buf), NULL, 0, - NI_NUMERICHOST); - if (error) { - set_gaierror(error); - return NULL; - } - return PyUnicode_FromString(buf); + error = getnameinfo(addr, addrlen, buf, sizeof(buf), NULL, 0, + NI_NUMERICHOST); + if (error) { + set_gaierror(error); + return NULL; + } + return PyUnicode_FromString(buf); } @@ -893,24 +893,24 @@ static int setbdaddr(char *name, bdaddr_t *bdaddr) { - unsigned int b0, b1, b2, b3, b4, b5; - char ch; - int n; - - n = sscanf(name, "%X:%X:%X:%X:%X:%X%c", - &b5, &b4, &b3, &b2, &b1, &b0, &ch); - if (n == 6 && (b0 | b1 | b2 | b3 | b4 | b5) < 256) { - bdaddr->b[0] = b0; - bdaddr->b[1] = b1; - bdaddr->b[2] = b2; - bdaddr->b[3] = b3; - bdaddr->b[4] = b4; - bdaddr->b[5] = b5; - return 6; - } else { - PyErr_SetString(socket_error, "bad bluetooth address"); - return -1; - } + unsigned int b0, b1, b2, b3, b4, b5; + char ch; + int n; + + n = sscanf(name, "%X:%X:%X:%X:%X:%X%c", + &b5, &b4, &b3, &b2, &b1, &b0, &ch); + if (n == 6 && (b0 | b1 | b2 | b3 | b4 | b5) < 256) { + bdaddr->b[0] = b0; + bdaddr->b[1] = b1; + bdaddr->b[2] = b2; + bdaddr->b[3] = b3; + bdaddr->b[4] = b4; + bdaddr->b[5] = b5; + return 6; + } else { + PyErr_SetString(socket_error, "bad bluetooth address"); + return -1; + } } /* Create a string representation of the Bluetooth address. This is always a @@ -920,12 +920,12 @@ static PyObject * makebdaddr(bdaddr_t *bdaddr) { - char buf[(6 * 2) + 5 + 1]; + char buf[(6 * 2) + 5 + 1]; - sprintf(buf, "%02X:%02X:%02X:%02X:%02X:%02X", - bdaddr->b[5], bdaddr->b[4], bdaddr->b[3], - bdaddr->b[2], bdaddr->b[1], bdaddr->b[0]); - return PyUnicode_FromString(buf); + sprintf(buf, "%02X:%02X:%02X:%02X:%02X:%02X", + bdaddr->b[5], bdaddr->b[4], bdaddr->b[3], + bdaddr->b[2], bdaddr->b[1], bdaddr->b[0]); + return PyUnicode_FromString(buf); } #endif @@ -939,193 +939,193 @@ static PyObject * makesockaddr(int sockfd, struct sockaddr *addr, int addrlen, int proto) { - if (addrlen == 0) { - /* No address -- may be recvfrom() from known socket */ - Py_INCREF(Py_None); - return Py_None; - } - - switch (addr->sa_family) { - - case AF_INET: - { - struct sockaddr_in *a; - PyObject *addrobj = makeipaddr(addr, sizeof(*a)); - PyObject *ret = NULL; - if (addrobj) { - a = (struct sockaddr_in *)addr; - ret = Py_BuildValue("Oi", addrobj, ntohs(a->sin_port)); - Py_DECREF(addrobj); - } - return ret; - } + if (addrlen == 0) { + /* No address -- may be recvfrom() from known socket */ + Py_INCREF(Py_None); + return Py_None; + } + + switch (addr->sa_family) { + + case AF_INET: + { + struct sockaddr_in *a; + PyObject *addrobj = makeipaddr(addr, sizeof(*a)); + PyObject *ret = NULL; + if (addrobj) { + a = (struct sockaddr_in *)addr; + ret = Py_BuildValue("Oi", addrobj, ntohs(a->sin_port)); + Py_DECREF(addrobj); + } + return ret; + } #if defined(AF_UNIX) - case AF_UNIX: - { - struct sockaddr_un *a = (struct sockaddr_un *) addr; + case AF_UNIX: + { + struct sockaddr_un *a = (struct sockaddr_un *) addr; #ifdef linux - if (a->sun_path[0] == 0) { /* Linux abstract namespace */ - addrlen -= offsetof(struct sockaddr_un, sun_path); - return PyBytes_FromStringAndSize(a->sun_path, addrlen); - } - else + if (a->sun_path[0] == 0) { /* Linux abstract namespace */ + addrlen -= offsetof(struct sockaddr_un, sun_path); + return PyBytes_FromStringAndSize(a->sun_path, addrlen); + } + else #endif /* linux */ - { - /* regular NULL-terminated string */ - return PyUnicode_FromString(a->sun_path); - } - } + { + /* regular NULL-terminated string */ + return PyUnicode_FromString(a->sun_path); + } + } #endif /* AF_UNIX */ #if defined(AF_NETLINK) case AF_NETLINK: { - struct sockaddr_nl *a = (struct sockaddr_nl *) addr; - return Py_BuildValue("II", a->nl_pid, a->nl_groups); + struct sockaddr_nl *a = (struct sockaddr_nl *) addr; + return Py_BuildValue("II", a->nl_pid, a->nl_groups); } #endif /* AF_NETLINK */ #ifdef ENABLE_IPV6 - case AF_INET6: - { - struct sockaddr_in6 *a; - PyObject *addrobj = makeipaddr(addr, sizeof(*a)); - PyObject *ret = NULL; - if (addrobj) { - a = (struct sockaddr_in6 *)addr; - ret = Py_BuildValue("Oiii", - addrobj, - ntohs(a->sin6_port), - a->sin6_flowinfo, - a->sin6_scope_id); - Py_DECREF(addrobj); - } - return ret; - } + case AF_INET6: + { + struct sockaddr_in6 *a; + PyObject *addrobj = makeipaddr(addr, sizeof(*a)); + PyObject *ret = NULL; + if (addrobj) { + a = (struct sockaddr_in6 *)addr; + ret = Py_BuildValue("Oiii", + addrobj, + ntohs(a->sin6_port), + a->sin6_flowinfo, + a->sin6_scope_id); + Py_DECREF(addrobj); + } + return ret; + } #endif #ifdef USE_BLUETOOTH - case AF_BLUETOOTH: - switch (proto) { + case AF_BLUETOOTH: + switch (proto) { - case BTPROTO_L2CAP: - { - struct sockaddr_l2 *a = (struct sockaddr_l2 *) addr; - PyObject *addrobj = makebdaddr(&_BT_L2_MEMB(a, bdaddr)); - PyObject *ret = NULL; - if (addrobj) { - ret = Py_BuildValue("Oi", - addrobj, - _BT_L2_MEMB(a, psm)); - Py_DECREF(addrobj); - } - return ret; - } - - case BTPROTO_RFCOMM: - { - struct sockaddr_rc *a = (struct sockaddr_rc *) addr; - PyObject *addrobj = makebdaddr(&_BT_RC_MEMB(a, bdaddr)); - PyObject *ret = NULL; - if (addrobj) { - ret = Py_BuildValue("Oi", - addrobj, - _BT_RC_MEMB(a, channel)); - Py_DECREF(addrobj); - } - return ret; - } - - case BTPROTO_HCI: - { - struct sockaddr_hci *a = (struct sockaddr_hci *) addr; - PyObject *ret = NULL; - ret = Py_BuildValue("i", _BT_HCI_MEMB(a, dev)); - return ret; - } + case BTPROTO_L2CAP: + { + struct sockaddr_l2 *a = (struct sockaddr_l2 *) addr; + PyObject *addrobj = makebdaddr(&_BT_L2_MEMB(a, bdaddr)); + PyObject *ret = NULL; + if (addrobj) { + ret = Py_BuildValue("Oi", + addrobj, + _BT_L2_MEMB(a, psm)); + Py_DECREF(addrobj); + } + return ret; + } + + case BTPROTO_RFCOMM: + { + struct sockaddr_rc *a = (struct sockaddr_rc *) addr; + PyObject *addrobj = makebdaddr(&_BT_RC_MEMB(a, bdaddr)); + PyObject *ret = NULL; + if (addrobj) { + ret = Py_BuildValue("Oi", + addrobj, + _BT_RC_MEMB(a, channel)); + Py_DECREF(addrobj); + } + return ret; + } + + case BTPROTO_HCI: + { + struct sockaddr_hci *a = (struct sockaddr_hci *) addr; + PyObject *ret = NULL; + ret = Py_BuildValue("i", _BT_HCI_MEMB(a, dev)); + return ret; + } #if !defined(__FreeBSD__) - case BTPROTO_SCO: - { - struct sockaddr_sco *a = (struct sockaddr_sco *) addr; - return makebdaddr(&_BT_SCO_MEMB(a, bdaddr)); - } + case BTPROTO_SCO: + { + struct sockaddr_sco *a = (struct sockaddr_sco *) addr; + return makebdaddr(&_BT_SCO_MEMB(a, bdaddr)); + } #endif - default: - PyErr_SetString(PyExc_ValueError, - "Unknown Bluetooth protocol"); - return NULL; - } + default: + PyErr_SetString(PyExc_ValueError, + "Unknown Bluetooth protocol"); + return NULL; + } #endif #ifdef HAVE_NETPACKET_PACKET_H - case AF_PACKET: - { - struct sockaddr_ll *a = (struct sockaddr_ll *)addr; - char *ifname = ""; - struct ifreq ifr; - /* need to look up interface name give index */ - if (a->sll_ifindex) { - ifr.ifr_ifindex = a->sll_ifindex; - if (ioctl(sockfd, SIOCGIFNAME, &ifr) == 0) - ifname = ifr.ifr_name; - } - return Py_BuildValue("shbhy#", - ifname, - ntohs(a->sll_protocol), - a->sll_pkttype, - a->sll_hatype, - a->sll_addr, - a->sll_halen); - } + case AF_PACKET: + { + struct sockaddr_ll *a = (struct sockaddr_ll *)addr; + char *ifname = ""; + struct ifreq ifr; + /* need to look up interface name give index */ + if (a->sll_ifindex) { + ifr.ifr_ifindex = a->sll_ifindex; + if (ioctl(sockfd, SIOCGIFNAME, &ifr) == 0) + ifname = ifr.ifr_name; + } + return Py_BuildValue("shbhy#", + ifname, + ntohs(a->sll_protocol), + a->sll_pkttype, + a->sll_hatype, + a->sll_addr, + a->sll_halen); + } #endif #ifdef HAVE_LINUX_TIPC_H - case AF_TIPC: - { - struct sockaddr_tipc *a = (struct sockaddr_tipc *) addr; - if (a->addrtype == TIPC_ADDR_NAMESEQ) { - return Py_BuildValue("IIIII", - a->addrtype, - a->addr.nameseq.type, - a->addr.nameseq.lower, - a->addr.nameseq.upper, - a->scope); - } else if (a->addrtype == TIPC_ADDR_NAME) { - return Py_BuildValue("IIIII", - a->addrtype, - a->addr.name.name.type, - a->addr.name.name.instance, - a->addr.name.name.instance, - a->scope); - } else if (a->addrtype == TIPC_ADDR_ID) { - return Py_BuildValue("IIIII", - a->addrtype, - a->addr.id.node, - a->addr.id.ref, - 0, - a->scope); - } else { - PyErr_SetString(PyExc_ValueError, - "Invalid address type"); - return NULL; - } - } -#endif - - /* More cases here... */ - - default: - /* If we don't know the address family, don't raise an - exception -- return it as an (int, bytes) tuple. */ - return Py_BuildValue("iy#", - addr->sa_family, - addr->sa_data, - sizeof(addr->sa_data)); + case AF_TIPC: + { + struct sockaddr_tipc *a = (struct sockaddr_tipc *) addr; + if (a->addrtype == TIPC_ADDR_NAMESEQ) { + return Py_BuildValue("IIIII", + a->addrtype, + a->addr.nameseq.type, + a->addr.nameseq.lower, + a->addr.nameseq.upper, + a->scope); + } else if (a->addrtype == TIPC_ADDR_NAME) { + return Py_BuildValue("IIIII", + a->addrtype, + a->addr.name.name.type, + a->addr.name.name.instance, + a->addr.name.name.instance, + a->scope); + } else if (a->addrtype == TIPC_ADDR_ID) { + return Py_BuildValue("IIIII", + a->addrtype, + a->addr.id.node, + a->addr.id.ref, + 0, + a->scope); + } else { + PyErr_SetString(PyExc_ValueError, + "Invalid address type"); + return NULL; + } + } +#endif + + /* More cases here... */ + + default: + /* If we don't know the address family, don't raise an + exception -- return it as an (int, bytes) tuple. */ + return Py_BuildValue("iy#", + addr->sa_family, + addr->sa_data, + sizeof(addr->sa_data)); - } + } } @@ -1136,346 +1136,346 @@ static int getsockaddrarg(PySocketSockObject *s, PyObject *args, - struct sockaddr *addr_ret, int *len_ret) + struct sockaddr *addr_ret, int *len_ret) { - switch (s->sock_family) { + switch (s->sock_family) { #if defined(AF_UNIX) - case AF_UNIX: - { - struct sockaddr_un* addr; - char *path; - int len; - if (!PyArg_Parse(args, "s#", &path, &len)) - return 0; + case AF_UNIX: + { + struct sockaddr_un* addr; + char *path; + int len; + if (!PyArg_Parse(args, "s#", &path, &len)) + return 0; - addr = (struct sockaddr_un*)addr_ret; + addr = (struct sockaddr_un*)addr_ret; #ifdef linux - if (len > 0 && path[0] == 0) { - /* Linux abstract namespace extension */ - if (len > sizeof addr->sun_path) { - PyErr_SetString(socket_error, - "AF_UNIX path too long"); - return 0; - } - } - else + if (len > 0 && path[0] == 0) { + /* Linux abstract namespace extension */ + if (len > sizeof addr->sun_path) { + PyErr_SetString(socket_error, + "AF_UNIX path too long"); + return 0; + } + } + else #endif /* linux */ - { - /* regular NULL-terminated string */ - if (len >= sizeof addr->sun_path) { - PyErr_SetString(socket_error, - "AF_UNIX path too long"); - return 0; - } - addr->sun_path[len] = 0; - } - addr->sun_family = s->sock_family; - memcpy(addr->sun_path, path, len); + { + /* regular NULL-terminated string */ + if (len >= sizeof addr->sun_path) { + PyErr_SetString(socket_error, + "AF_UNIX path too long"); + return 0; + } + addr->sun_path[len] = 0; + } + addr->sun_family = s->sock_family; + memcpy(addr->sun_path, path, len); #if defined(PYOS_OS2) - *len_ret = sizeof(*addr); + *len_ret = sizeof(*addr); #else - *len_ret = len + offsetof(struct sockaddr_un, sun_path); + *len_ret = len + offsetof(struct sockaddr_un, sun_path); #endif - return 1; - } + return 1; + } #endif /* AF_UNIX */ #if defined(AF_NETLINK) - case AF_NETLINK: - { - struct sockaddr_nl* addr; - int pid, groups; - addr = (struct sockaddr_nl *)addr_ret; - if (!PyTuple_Check(args)) { - PyErr_Format( - PyExc_TypeError, - "getsockaddrarg: " - "AF_NETLINK address must be tuple, not %.500s", - Py_TYPE(args)->tp_name); - return 0; - } - if (!PyArg_ParseTuple(args, "II:getsockaddrarg", &pid, &groups)) - return 0; - addr->nl_family = AF_NETLINK; - addr->nl_pid = pid; - addr->nl_groups = groups; - *len_ret = sizeof(*addr); - return 1; - } -#endif - - case AF_INET: - { - struct sockaddr_in* addr; - char *host; - int port, result; - if (!PyTuple_Check(args)) { - PyErr_Format( - PyExc_TypeError, - "getsockaddrarg: " - "AF_INET address must be tuple, not %.500s", - Py_TYPE(args)->tp_name); - return 0; - } - if (!PyArg_ParseTuple(args, "eti:getsockaddrarg", - "idna", &host, &port)) - return 0; - addr=(struct sockaddr_in*)addr_ret; - result = setipaddr(host, (struct sockaddr *)addr, - sizeof(*addr), AF_INET); - PyMem_Free(host); - if (result < 0) - return 0; - if (port < 0 || port > 0xffff) { - PyErr_SetString( - PyExc_OverflowError, - "getsockaddrarg: port must be 0-65535."); - return 0; - } - addr->sin_family = AF_INET; - addr->sin_port = htons((short)port); - *len_ret = sizeof *addr; - return 1; - } + case AF_NETLINK: + { + struct sockaddr_nl* addr; + int pid, groups; + addr = (struct sockaddr_nl *)addr_ret; + if (!PyTuple_Check(args)) { + PyErr_Format( + PyExc_TypeError, + "getsockaddrarg: " + "AF_NETLINK address must be tuple, not %.500s", + Py_TYPE(args)->tp_name); + return 0; + } + if (!PyArg_ParseTuple(args, "II:getsockaddrarg", &pid, &groups)) + return 0; + addr->nl_family = AF_NETLINK; + addr->nl_pid = pid; + addr->nl_groups = groups; + *len_ret = sizeof(*addr); + return 1; + } +#endif + + case AF_INET: + { + struct sockaddr_in* addr; + char *host; + int port, result; + if (!PyTuple_Check(args)) { + PyErr_Format( + PyExc_TypeError, + "getsockaddrarg: " + "AF_INET address must be tuple, not %.500s", + Py_TYPE(args)->tp_name); + return 0; + } + if (!PyArg_ParseTuple(args, "eti:getsockaddrarg", + "idna", &host, &port)) + return 0; + addr=(struct sockaddr_in*)addr_ret; + result = setipaddr(host, (struct sockaddr *)addr, + sizeof(*addr), AF_INET); + PyMem_Free(host); + if (result < 0) + return 0; + if (port < 0 || port > 0xffff) { + PyErr_SetString( + PyExc_OverflowError, + "getsockaddrarg: port must be 0-65535."); + return 0; + } + addr->sin_family = AF_INET; + addr->sin_port = htons((short)port); + *len_ret = sizeof *addr; + return 1; + } #ifdef ENABLE_IPV6 - case AF_INET6: - { - struct sockaddr_in6* addr; - char *host; - int port, flowinfo, scope_id, result; - flowinfo = scope_id = 0; - if (!PyTuple_Check(args)) { - PyErr_Format( - PyExc_TypeError, - "getsockaddrarg: " - "AF_INET6 address must be tuple, not %.500s", - Py_TYPE(args)->tp_name); - return 0; - } - if (!PyArg_ParseTuple(args, "eti|ii", - "idna", &host, &port, &flowinfo, - &scope_id)) { - return 0; - } - addr = (struct sockaddr_in6*)addr_ret; - result = setipaddr(host, (struct sockaddr *)addr, - sizeof(*addr), AF_INET6); - PyMem_Free(host); - if (result < 0) - return 0; - if (port < 0 || port > 0xffff) { - PyErr_SetString( - PyExc_OverflowError, - "getsockaddrarg: port must be 0-65535."); - return 0; - } - addr->sin6_family = s->sock_family; - addr->sin6_port = htons((short)port); - addr->sin6_flowinfo = flowinfo; - addr->sin6_scope_id = scope_id; - *len_ret = sizeof *addr; - return 1; - } + case AF_INET6: + { + struct sockaddr_in6* addr; + char *host; + int port, flowinfo, scope_id, result; + flowinfo = scope_id = 0; + if (!PyTuple_Check(args)) { + PyErr_Format( + PyExc_TypeError, + "getsockaddrarg: " + "AF_INET6 address must be tuple, not %.500s", + Py_TYPE(args)->tp_name); + return 0; + } + if (!PyArg_ParseTuple(args, "eti|ii", + "idna", &host, &port, &flowinfo, + &scope_id)) { + return 0; + } + addr = (struct sockaddr_in6*)addr_ret; + result = setipaddr(host, (struct sockaddr *)addr, + sizeof(*addr), AF_INET6); + PyMem_Free(host); + if (result < 0) + return 0; + if (port < 0 || port > 0xffff) { + PyErr_SetString( + PyExc_OverflowError, + "getsockaddrarg: port must be 0-65535."); + return 0; + } + addr->sin6_family = s->sock_family; + addr->sin6_port = htons((short)port); + addr->sin6_flowinfo = flowinfo; + addr->sin6_scope_id = scope_id; + *len_ret = sizeof *addr; + return 1; + } #endif #ifdef USE_BLUETOOTH - case AF_BLUETOOTH: - { - switch (s->sock_proto) { - case BTPROTO_L2CAP: - { - struct sockaddr_l2 *addr; - char *straddr; - - addr = (struct sockaddr_l2 *)addr_ret; - memset(addr, 0, sizeof(struct sockaddr_l2)); - _BT_L2_MEMB(addr, family) = AF_BLUETOOTH; - if (!PyArg_ParseTuple(args, "si", &straddr, - &_BT_L2_MEMB(addr, psm))) { - PyErr_SetString(socket_error, "getsockaddrarg: " - "wrong format"); - return 0; - } - if (setbdaddr(straddr, &_BT_L2_MEMB(addr, bdaddr)) < 0) - return 0; - - *len_ret = sizeof *addr; - return 1; - } - case BTPROTO_RFCOMM: - { - struct sockaddr_rc *addr; - char *straddr; - - addr = (struct sockaddr_rc *)addr_ret; - _BT_RC_MEMB(addr, family) = AF_BLUETOOTH; - if (!PyArg_ParseTuple(args, "si", &straddr, - &_BT_RC_MEMB(addr, channel))) { - PyErr_SetString(socket_error, "getsockaddrarg: " - "wrong format"); - return 0; - } - if (setbdaddr(straddr, &_BT_RC_MEMB(addr, bdaddr)) < 0) - return 0; - - *len_ret = sizeof *addr; - return 1; - } - case BTPROTO_HCI: - { - struct sockaddr_hci *addr = (struct sockaddr_hci *)addr_ret; - _BT_HCI_MEMB(addr, family) = AF_BLUETOOTH; - if (!PyArg_ParseTuple(args, "i", &_BT_HCI_MEMB(addr, dev))) { - PyErr_SetString(socket_error, "getsockaddrarg: " - "wrong format"); - return 0; - } - *len_ret = sizeof *addr; - return 1; - } + case AF_BLUETOOTH: + { + switch (s->sock_proto) { + case BTPROTO_L2CAP: + { + struct sockaddr_l2 *addr; + char *straddr; + + addr = (struct sockaddr_l2 *)addr_ret; + memset(addr, 0, sizeof(struct sockaddr_l2)); + _BT_L2_MEMB(addr, family) = AF_BLUETOOTH; + if (!PyArg_ParseTuple(args, "si", &straddr, + &_BT_L2_MEMB(addr, psm))) { + PyErr_SetString(socket_error, "getsockaddrarg: " + "wrong format"); + return 0; + } + if (setbdaddr(straddr, &_BT_L2_MEMB(addr, bdaddr)) < 0) + return 0; + + *len_ret = sizeof *addr; + return 1; + } + case BTPROTO_RFCOMM: + { + struct sockaddr_rc *addr; + char *straddr; + + addr = (struct sockaddr_rc *)addr_ret; + _BT_RC_MEMB(addr, family) = AF_BLUETOOTH; + if (!PyArg_ParseTuple(args, "si", &straddr, + &_BT_RC_MEMB(addr, channel))) { + PyErr_SetString(socket_error, "getsockaddrarg: " + "wrong format"); + return 0; + } + if (setbdaddr(straddr, &_BT_RC_MEMB(addr, bdaddr)) < 0) + return 0; + + *len_ret = sizeof *addr; + return 1; + } + case BTPROTO_HCI: + { + struct sockaddr_hci *addr = (struct sockaddr_hci *)addr_ret; + _BT_HCI_MEMB(addr, family) = AF_BLUETOOTH; + if (!PyArg_ParseTuple(args, "i", &_BT_HCI_MEMB(addr, dev))) { + PyErr_SetString(socket_error, "getsockaddrarg: " + "wrong format"); + return 0; + } + *len_ret = sizeof *addr; + return 1; + } #if !defined(__FreeBSD__) - case BTPROTO_SCO: - { - struct sockaddr_sco *addr; - char *straddr; - - addr = (struct sockaddr_sco *)addr_ret; - _BT_SCO_MEMB(addr, family) = AF_BLUETOOTH; - if (!PyBytes_Check(args)) { - PyErr_SetString(socket_error, "getsockaddrarg: " - "wrong format"); - return 0; - } - straddr = PyBytes_AS_STRING(args); - if (setbdaddr(straddr, &_BT_SCO_MEMB(addr, bdaddr)) < 0) - return 0; - - *len_ret = sizeof *addr; - return 1; - } -#endif - default: - PyErr_SetString(socket_error, "getsockaddrarg: unknown Bluetooth protocol"); - return 0; - } - } + case BTPROTO_SCO: + { + struct sockaddr_sco *addr; + char *straddr; + + addr = (struct sockaddr_sco *)addr_ret; + _BT_SCO_MEMB(addr, family) = AF_BLUETOOTH; + if (!PyBytes_Check(args)) { + PyErr_SetString(socket_error, "getsockaddrarg: " + "wrong format"); + return 0; + } + straddr = PyBytes_AS_STRING(args); + if (setbdaddr(straddr, &_BT_SCO_MEMB(addr, bdaddr)) < 0) + return 0; + + *len_ret = sizeof *addr; + return 1; + } +#endif + default: + PyErr_SetString(socket_error, "getsockaddrarg: unknown Bluetooth protocol"); + return 0; + } + } #endif #ifdef HAVE_NETPACKET_PACKET_H - case AF_PACKET: - { - struct sockaddr_ll* addr; - struct ifreq ifr; - char *interfaceName; - int protoNumber; - int hatype = 0; - int pkttype = 0; - char *haddr = NULL; - unsigned int halen = 0; - - if (!PyTuple_Check(args)) { - PyErr_Format( - PyExc_TypeError, - "getsockaddrarg: " - "AF_PACKET address must be tuple, not %.500s", - Py_TYPE(args)->tp_name); - return 0; - } - if (!PyArg_ParseTuple(args, "si|iiy#", &interfaceName, - &protoNumber, &pkttype, &hatype, - &haddr, &halen)) - return 0; - strncpy(ifr.ifr_name, interfaceName, sizeof(ifr.ifr_name)); - ifr.ifr_name[(sizeof(ifr.ifr_name))-1] = '\0'; - if (ioctl(s->sock_fd, SIOCGIFINDEX, &ifr) < 0) { - s->errorhandler(); - return 0; - } - if (halen > 8) { - PyErr_SetString(PyExc_ValueError, - "Hardware address must be 8 bytes or less"); - return 0; - } - if (protoNumber < 0 || protoNumber > 0xffff) { - PyErr_SetString( - PyExc_OverflowError, - "getsockaddrarg: protoNumber must be 0-65535."); - return 0; - } - addr = (struct sockaddr_ll*)addr_ret; - addr->sll_family = AF_PACKET; - addr->sll_protocol = htons((short)protoNumber); - addr->sll_ifindex = ifr.ifr_ifindex; - addr->sll_pkttype = pkttype; - addr->sll_hatype = hatype; - if (halen != 0) { - memcpy(&addr->sll_addr, haddr, halen); - } - addr->sll_halen = halen; - *len_ret = sizeof *addr; - return 1; - } + case AF_PACKET: + { + struct sockaddr_ll* addr; + struct ifreq ifr; + char *interfaceName; + int protoNumber; + int hatype = 0; + int pkttype = 0; + char *haddr = NULL; + unsigned int halen = 0; + + if (!PyTuple_Check(args)) { + PyErr_Format( + PyExc_TypeError, + "getsockaddrarg: " + "AF_PACKET address must be tuple, not %.500s", + Py_TYPE(args)->tp_name); + return 0; + } + if (!PyArg_ParseTuple(args, "si|iiy#", &interfaceName, + &protoNumber, &pkttype, &hatype, + &haddr, &halen)) + return 0; + strncpy(ifr.ifr_name, interfaceName, sizeof(ifr.ifr_name)); + ifr.ifr_name[(sizeof(ifr.ifr_name))-1] = '\0'; + if (ioctl(s->sock_fd, SIOCGIFINDEX, &ifr) < 0) { + s->errorhandler(); + return 0; + } + if (halen > 8) { + PyErr_SetString(PyExc_ValueError, + "Hardware address must be 8 bytes or less"); + return 0; + } + if (protoNumber < 0 || protoNumber > 0xffff) { + PyErr_SetString( + PyExc_OverflowError, + "getsockaddrarg: protoNumber must be 0-65535."); + return 0; + } + addr = (struct sockaddr_ll*)addr_ret; + addr->sll_family = AF_PACKET; + addr->sll_protocol = htons((short)protoNumber); + addr->sll_ifindex = ifr.ifr_ifindex; + addr->sll_pkttype = pkttype; + addr->sll_hatype = hatype; + if (halen != 0) { + memcpy(&addr->sll_addr, haddr, halen); + } + addr->sll_halen = halen; + *len_ret = sizeof *addr; + return 1; + } #endif #ifdef HAVE_LINUX_TIPC_H - case AF_TIPC: - { - unsigned int atype, v1, v2, v3; - unsigned int scope = TIPC_CLUSTER_SCOPE; - struct sockaddr_tipc *addr; - - if (!PyTuple_Check(args)) { - PyErr_Format( - PyExc_TypeError, - "getsockaddrarg: " - "AF_TIPC address must be tuple, not %.500s", - Py_TYPE(args)->tp_name); - return 0; - } - - if (!PyArg_ParseTuple(args, - "IIII|I;Invalid TIPC address format", - &atype, &v1, &v2, &v3, &scope)) - return 0; - - addr = (struct sockaddr_tipc *) addr_ret; - memset(addr, 0, sizeof(struct sockaddr_tipc)); - - addr->family = AF_TIPC; - addr->scope = scope; - addr->addrtype = atype; - - if (atype == TIPC_ADDR_NAMESEQ) { - addr->addr.nameseq.type = v1; - addr->addr.nameseq.lower = v2; - addr->addr.nameseq.upper = v3; - } else if (atype == TIPC_ADDR_NAME) { - addr->addr.name.name.type = v1; - addr->addr.name.name.instance = v2; - } else if (atype == TIPC_ADDR_ID) { - addr->addr.id.node = v1; - addr->addr.id.ref = v2; - } else { - /* Shouldn't happen */ - PyErr_SetString(PyExc_TypeError, "Invalid address type"); - return 0; - } - - *len_ret = sizeof(*addr); - - return 1; - } -#endif - - /* More cases here... */ - - default: - PyErr_SetString(socket_error, "getsockaddrarg: bad family"); - return 0; + case AF_TIPC: + { + unsigned int atype, v1, v2, v3; + unsigned int scope = TIPC_CLUSTER_SCOPE; + struct sockaddr_tipc *addr; + + if (!PyTuple_Check(args)) { + PyErr_Format( + PyExc_TypeError, + "getsockaddrarg: " + "AF_TIPC address must be tuple, not %.500s", + Py_TYPE(args)->tp_name); + return 0; + } + + if (!PyArg_ParseTuple(args, + "IIII|I;Invalid TIPC address format", + &atype, &v1, &v2, &v3, &scope)) + return 0; + + addr = (struct sockaddr_tipc *) addr_ret; + memset(addr, 0, sizeof(struct sockaddr_tipc)); + + addr->family = AF_TIPC; + addr->scope = scope; + addr->addrtype = atype; + + if (atype == TIPC_ADDR_NAMESEQ) { + addr->addr.nameseq.type = v1; + addr->addr.nameseq.lower = v2; + addr->addr.nameseq.upper = v3; + } else if (atype == TIPC_ADDR_NAME) { + addr->addr.name.name.type = v1; + addr->addr.name.name.instance = v2; + } else if (atype == TIPC_ADDR_ID) { + addr->addr.id.node = v1; + addr->addr.id.ref = v2; + } else { + /* Shouldn't happen */ + PyErr_SetString(PyExc_TypeError, "Invalid address type"); + return 0; + } + + *len_ret = sizeof(*addr); + + return 1; + } +#endif + + /* More cases here... */ + + default: + PyErr_SetString(socket_error, "getsockaddrarg: bad family"); + return 0; - } + } } @@ -1486,89 +1486,89 @@ static int getsockaddrlen(PySocketSockObject *s, socklen_t *len_ret) { - switch (s->sock_family) { + switch (s->sock_family) { #if defined(AF_UNIX) - case AF_UNIX: - { - *len_ret = sizeof (struct sockaddr_un); - return 1; - } + case AF_UNIX: + { + *len_ret = sizeof (struct sockaddr_un); + return 1; + } #endif /* AF_UNIX */ #if defined(AF_NETLINK) case AF_NETLINK: { - *len_ret = sizeof (struct sockaddr_nl); - return 1; + *len_ret = sizeof (struct sockaddr_nl); + return 1; } #endif - case AF_INET: - { - *len_ret = sizeof (struct sockaddr_in); - return 1; - } + case AF_INET: + { + *len_ret = sizeof (struct sockaddr_in); + return 1; + } #ifdef ENABLE_IPV6 - case AF_INET6: - { - *len_ret = sizeof (struct sockaddr_in6); - return 1; - } + case AF_INET6: + { + *len_ret = sizeof (struct sockaddr_in6); + return 1; + } #endif #ifdef USE_BLUETOOTH - case AF_BLUETOOTH: - { - switch(s->sock_proto) - { - - case BTPROTO_L2CAP: - *len_ret = sizeof (struct sockaddr_l2); - return 1; - case BTPROTO_RFCOMM: - *len_ret = sizeof (struct sockaddr_rc); - return 1; - case BTPROTO_HCI: - *len_ret = sizeof (struct sockaddr_hci); - return 1; + case AF_BLUETOOTH: + { + switch(s->sock_proto) + { + + case BTPROTO_L2CAP: + *len_ret = sizeof (struct sockaddr_l2); + return 1; + case BTPROTO_RFCOMM: + *len_ret = sizeof (struct sockaddr_rc); + return 1; + case BTPROTO_HCI: + *len_ret = sizeof (struct sockaddr_hci); + return 1; #if !defined(__FreeBSD__) - case BTPROTO_SCO: - *len_ret = sizeof (struct sockaddr_sco); - return 1; -#endif - default: - PyErr_SetString(socket_error, "getsockaddrlen: " - "unknown BT protocol"); - return 0; + case BTPROTO_SCO: + *len_ret = sizeof (struct sockaddr_sco); + return 1; +#endif + default: + PyErr_SetString(socket_error, "getsockaddrlen: " + "unknown BT protocol"); + return 0; - } - } + } + } #endif #ifdef HAVE_NETPACKET_PACKET_H - case AF_PACKET: - { - *len_ret = sizeof (struct sockaddr_ll); - return 1; - } + case AF_PACKET: + { + *len_ret = sizeof (struct sockaddr_ll); + return 1; + } #endif #ifdef HAVE_LINUX_TIPC_H - case AF_TIPC: - { - *len_ret = sizeof (struct sockaddr_tipc); - return 1; - } + case AF_TIPC: + { + *len_ret = sizeof (struct sockaddr_tipc); + return 1; + } #endif - /* More cases here... */ + /* More cases here... */ - default: - PyErr_SetString(socket_error, "getsockaddrlen: bad family"); - return 0; + default: + PyErr_SetString(socket_error, "getsockaddrlen: bad family"); + return 0; - } + } } @@ -1577,52 +1577,52 @@ static PyObject * sock_accept(PySocketSockObject *s) { - sock_addr_t addrbuf; - SOCKET_T newfd = INVALID_SOCKET; - socklen_t addrlen; - PyObject *sock = NULL; - PyObject *addr = NULL; - PyObject *res = NULL; - int timeout; - - if (!getsockaddrlen(s, &addrlen)) - return NULL; - memset(&addrbuf, 0, addrlen); - - if (!IS_SELECTABLE(s)) - return select_error(); - - Py_BEGIN_ALLOW_THREADS - timeout = internal_select(s, 0); - if (!timeout) - newfd = accept(s->sock_fd, SAS2SA(&addrbuf), &addrlen); - Py_END_ALLOW_THREADS - - if (timeout == 1) { - PyErr_SetString(socket_timeout, "timed out"); - return NULL; - } - - if (newfd == INVALID_SOCKET) - return s->errorhandler(); - - sock = PyLong_FromSocket_t(newfd); - if (sock == NULL) { - SOCKETCLOSE(newfd); - goto finally; - } - - addr = makesockaddr(s->sock_fd, SAS2SA(&addrbuf), - addrlen, s->sock_proto); - if (addr == NULL) - goto finally; + sock_addr_t addrbuf; + SOCKET_T newfd = INVALID_SOCKET; + socklen_t addrlen; + PyObject *sock = NULL; + PyObject *addr = NULL; + PyObject *res = NULL; + int timeout; + + if (!getsockaddrlen(s, &addrlen)) + return NULL; + memset(&addrbuf, 0, addrlen); + + if (!IS_SELECTABLE(s)) + return select_error(); + + Py_BEGIN_ALLOW_THREADS + timeout = internal_select(s, 0); + if (!timeout) + newfd = accept(s->sock_fd, SAS2SA(&addrbuf), &addrlen); + Py_END_ALLOW_THREADS + + if (timeout == 1) { + PyErr_SetString(socket_timeout, "timed out"); + return NULL; + } + + if (newfd == INVALID_SOCKET) + return s->errorhandler(); + + sock = PyLong_FromSocket_t(newfd); + if (sock == NULL) { + SOCKETCLOSE(newfd); + goto finally; + } + + addr = makesockaddr(s->sock_fd, SAS2SA(&addrbuf), + addrlen, s->sock_proto); + if (addr == NULL) + goto finally; - res = PyTuple_Pack(2, sock, addr); + res = PyTuple_Pack(2, sock, addr); finally: - Py_XDECREF(sock); - Py_XDECREF(addr); - return res; + Py_XDECREF(sock); + Py_XDECREF(addr); + return res; } PyDoc_STRVAR(accept_doc, @@ -1640,17 +1640,17 @@ static PyObject * sock_setblocking(PySocketSockObject *s, PyObject *arg) { - int block; + int block; - block = PyLong_AsLong(arg); - if (block == -1 && PyErr_Occurred()) - return NULL; + block = PyLong_AsLong(arg); + if (block == -1 && PyErr_Occurred()) + return NULL; - s->sock_timeout = block ? -1.0 : 0.0; - internal_setblocking(s, block); + s->sock_timeout = block ? -1.0 : 0.0; + internal_setblocking(s, block); - Py_INCREF(Py_None); - return Py_None; + Py_INCREF(Py_None); + return Py_None; } PyDoc_STRVAR(setblocking_doc, @@ -1669,25 +1669,25 @@ static PyObject * sock_settimeout(PySocketSockObject *s, PyObject *arg) { - double timeout; + double timeout; - if (arg == Py_None) - timeout = -1.0; - else { - timeout = PyFloat_AsDouble(arg); - if (timeout < 0.0) { - if (!PyErr_Occurred()) - PyErr_SetString(PyExc_ValueError, - "Timeout value out of range"); - return NULL; - } - } + if (arg == Py_None) + timeout = -1.0; + else { + timeout = PyFloat_AsDouble(arg); + if (timeout < 0.0) { + if (!PyErr_Occurred()) + PyErr_SetString(PyExc_ValueError, + "Timeout value out of range"); + return NULL; + } + } - s->sock_timeout = timeout; - internal_setblocking(s, timeout < 0.0); + s->sock_timeout = timeout; + internal_setblocking(s, timeout < 0.0); - Py_INCREF(Py_None); - return Py_None; + Py_INCREF(Py_None); + return Py_None; } PyDoc_STRVAR(settimeout_doc, @@ -1703,12 +1703,12 @@ static PyObject * sock_gettimeout(PySocketSockObject *s) { - if (s->sock_timeout < 0.0) { - Py_INCREF(Py_None); - return Py_None; - } - else - return PyFloat_FromDouble(s->sock_timeout); + if (s->sock_timeout < 0.0) { + Py_INCREF(Py_None); + return Py_None; + } + else + return PyFloat_FromDouble(s->sock_timeout); } PyDoc_STRVAR(gettimeout_doc, @@ -1726,29 +1726,29 @@ static PyObject * sock_setsockopt(PySocketSockObject *s, PyObject *args) { - int level; - int optname; - int res; - char *buf; - int buflen; - int flag; - - if (PyArg_ParseTuple(args, "iii:setsockopt", - &level, &optname, &flag)) { - buf = (char *) &flag; - buflen = sizeof flag; - } - else { - PyErr_Clear(); - if (!PyArg_ParseTuple(args, "iiy#:setsockopt", - &level, &optname, &buf, &buflen)) - return NULL; - } - res = setsockopt(s->sock_fd, level, optname, (void *)buf, buflen); - if (res < 0) - return s->errorhandler(); - Py_INCREF(Py_None); - return Py_None; + int level; + int optname; + int res; + char *buf; + int buflen; + int flag; + + if (PyArg_ParseTuple(args, "iii:setsockopt", + &level, &optname, &flag)) { + buf = (char *) &flag; + buflen = sizeof flag; + } + else { + PyErr_Clear(); + if (!PyArg_ParseTuple(args, "iiy#:setsockopt", + &level, &optname, &buf, &buflen)) + return NULL; + } + res = setsockopt(s->sock_fd, level, optname, (void *)buf, buflen); + if (res < 0) + return s->errorhandler(); + Py_INCREF(Py_None); + return Py_None; } PyDoc_STRVAR(setsockopt_doc, @@ -1766,47 +1766,47 @@ static PyObject * sock_getsockopt(PySocketSockObject *s, PyObject *args) { - int level; - int optname; - int res; - PyObject *buf; - socklen_t buflen = 0; - - if (!PyArg_ParseTuple(args, "ii|i:getsockopt", - &level, &optname, &buflen)) - return NULL; - - if (buflen == 0) { - int flag = 0; - socklen_t flagsize = sizeof flag; - res = getsockopt(s->sock_fd, level, optname, - (void *)&flag, &flagsize); - if (res < 0) - return s->errorhandler(); - return PyLong_FromLong(flag); - } + int level; + int optname; + int res; + PyObject *buf; + socklen_t buflen = 0; + + if (!PyArg_ParseTuple(args, "ii|i:getsockopt", + &level, &optname, &buflen)) + return NULL; + + if (buflen == 0) { + int flag = 0; + socklen_t flagsize = sizeof flag; + res = getsockopt(s->sock_fd, level, optname, + (void *)&flag, &flagsize); + if (res < 0) + return s->errorhandler(); + return PyLong_FromLong(flag); + } #ifdef __VMS - /* socklen_t is unsigned so no negative test is needed, - test buflen == 0 is previously done */ - if (buflen > 1024) { -#else - if (buflen <= 0 || buflen > 1024) { -#endif - PyErr_SetString(socket_error, - "getsockopt buflen out of range"); - return NULL; - } - buf = PyBytes_FromStringAndSize((char *)NULL, buflen); - if (buf == NULL) - return NULL; - res = getsockopt(s->sock_fd, level, optname, - (void *)PyBytes_AS_STRING(buf), &buflen); - if (res < 0) { - Py_DECREF(buf); - return s->errorhandler(); - } - _PyBytes_Resize(&buf, buflen); - return buf; + /* socklen_t is unsigned so no negative test is needed, + test buflen == 0 is previously done */ + if (buflen > 1024) { +#else + if (buflen <= 0 || buflen > 1024) { +#endif + PyErr_SetString(socket_error, + "getsockopt buflen out of range"); + return NULL; + } + buf = PyBytes_FromStringAndSize((char *)NULL, buflen); + if (buf == NULL) + return NULL; + res = getsockopt(s->sock_fd, level, optname, + (void *)PyBytes_AS_STRING(buf), &buflen); + if (res < 0) { + Py_DECREF(buf); + return s->errorhandler(); + } + _PyBytes_Resize(&buf, buflen); + return buf; } PyDoc_STRVAR(getsockopt_doc, @@ -1822,19 +1822,19 @@ static PyObject * sock_bind(PySocketSockObject *s, PyObject *addro) { - sock_addr_t addrbuf; - int addrlen; - int res; - - if (!getsockaddrarg(s, addro, SAS2SA(&addrbuf), &addrlen)) - return NULL; - Py_BEGIN_ALLOW_THREADS - res = bind(s->sock_fd, SAS2SA(&addrbuf), addrlen); - Py_END_ALLOW_THREADS - if (res < 0) - return s->errorhandler(); - Py_INCREF(Py_None); - return Py_None; + sock_addr_t addrbuf; + int addrlen; + int res; + + if (!getsockaddrarg(s, addro, SAS2SA(&addrbuf), &addrlen)) + return NULL; + Py_BEGIN_ALLOW_THREADS + res = bind(s->sock_fd, SAS2SA(&addrbuf), addrlen); + Py_END_ALLOW_THREADS + if (res < 0) + return s->errorhandler(); + Py_INCREF(Py_None); + return Py_None; } PyDoc_STRVAR(bind_doc, @@ -1852,16 +1852,16 @@ static PyObject * sock_close(PySocketSockObject *s) { - SOCKET_T fd; + SOCKET_T fd; - if ((fd = s->sock_fd) != -1) { - s->sock_fd = -1; - Py_BEGIN_ALLOW_THREADS - (void) SOCKETCLOSE(fd); - Py_END_ALLOW_THREADS - } - Py_INCREF(Py_None); - return Py_None; + if ((fd = s->sock_fd) != -1) { + s->sock_fd = -1; + Py_BEGIN_ALLOW_THREADS + (void) SOCKETCLOSE(fd); + Py_END_ALLOW_THREADS + } + Py_INCREF(Py_None); + return Py_None; } PyDoc_STRVAR(close_doc, @@ -1871,90 +1871,90 @@ static int internal_connect(PySocketSockObject *s, struct sockaddr *addr, int addrlen, - int *timeoutp) + int *timeoutp) { - int res, timeout; + int res, timeout; - timeout = 0; - res = connect(s->sock_fd, addr, addrlen); + timeout = 0; + res = connect(s->sock_fd, addr, addrlen); #ifdef MS_WINDOWS - if (s->sock_timeout > 0.0) { - if (res < 0 && WSAGetLastError() == WSAEWOULDBLOCK && - IS_SELECTABLE(s)) { - /* This is a mess. Best solution: trust select */ - fd_set fds; - fd_set fds_exc; - struct timeval tv; - tv.tv_sec = (int)s->sock_timeout; - tv.tv_usec = (int)((s->sock_timeout - tv.tv_sec) * 1e6); - FD_ZERO(&fds); - FD_SET(s->sock_fd, &fds); - FD_ZERO(&fds_exc); - FD_SET(s->sock_fd, &fds_exc); - res = select(s->sock_fd+1, NULL, &fds, &fds_exc, &tv); - if (res == 0) { - res = WSAEWOULDBLOCK; - timeout = 1; - } else if (res > 0) { - if (FD_ISSET(s->sock_fd, &fds)) - /* The socket is in the writable set - this - means connected */ - res = 0; - else { - /* As per MS docs, we need to call getsockopt() - to get the underlying error */ - int res_size = sizeof res; - /* It must be in the exception set */ - assert(FD_ISSET(s->sock_fd, &fds_exc)); - if (0 == getsockopt(s->sock_fd, SOL_SOCKET, SO_ERROR, - (char *)&res, &res_size)) - /* getsockopt also clears WSAGetLastError, - so reset it back. */ - WSASetLastError(res); - else - res = WSAGetLastError(); - } - } - /* else if (res < 0) an error occurred */ - } - } - - if (res < 0) - res = WSAGetLastError(); - -#else - - if (s->sock_timeout > 0.0) { - if (res < 0 && errno == EINPROGRESS && IS_SELECTABLE(s)) { - timeout = internal_select(s, 1); - if (timeout == 0) { - /* Bug #1019808: in case of an EINPROGRESS, - use getsockopt(SO_ERROR) to get the real - error. */ - socklen_t res_size = sizeof res; - (void)getsockopt(s->sock_fd, SOL_SOCKET, - SO_ERROR, &res, &res_size); - if (res == EISCONN) - res = 0; - errno = res; - } - else if (timeout == -1) { - res = errno; /* had error */ - } - else - res = EWOULDBLOCK; /* timed out */ - } - } + if (s->sock_timeout > 0.0) { + if (res < 0 && WSAGetLastError() == WSAEWOULDBLOCK && + IS_SELECTABLE(s)) { + /* This is a mess. Best solution: trust select */ + fd_set fds; + fd_set fds_exc; + struct timeval tv; + tv.tv_sec = (int)s->sock_timeout; + tv.tv_usec = (int)((s->sock_timeout - tv.tv_sec) * 1e6); + FD_ZERO(&fds); + FD_SET(s->sock_fd, &fds); + FD_ZERO(&fds_exc); + FD_SET(s->sock_fd, &fds_exc); + res = select(s->sock_fd+1, NULL, &fds, &fds_exc, &tv); + if (res == 0) { + res = WSAEWOULDBLOCK; + timeout = 1; + } else if (res > 0) { + if (FD_ISSET(s->sock_fd, &fds)) + /* The socket is in the writable set - this + means connected */ + res = 0; + else { + /* As per MS docs, we need to call getsockopt() + to get the underlying error */ + int res_size = sizeof res; + /* It must be in the exception set */ + assert(FD_ISSET(s->sock_fd, &fds_exc)); + if (0 == getsockopt(s->sock_fd, SOL_SOCKET, SO_ERROR, + (char *)&res, &res_size)) + /* getsockopt also clears WSAGetLastError, + so reset it back. */ + WSASetLastError(res); + else + res = WSAGetLastError(); + } + } + /* else if (res < 0) an error occurred */ + } + } + + if (res < 0) + res = WSAGetLastError(); + +#else + + if (s->sock_timeout > 0.0) { + if (res < 0 && errno == EINPROGRESS && IS_SELECTABLE(s)) { + timeout = internal_select(s, 1); + if (timeout == 0) { + /* Bug #1019808: in case of an EINPROGRESS, + use getsockopt(SO_ERROR) to get the real + error. */ + socklen_t res_size = sizeof res; + (void)getsockopt(s->sock_fd, SOL_SOCKET, + SO_ERROR, &res, &res_size); + if (res == EISCONN) + res = 0; + errno = res; + } + else if (timeout == -1) { + res = errno; /* had error */ + } + else + res = EWOULDBLOCK; /* timed out */ + } + } - if (res < 0) - res = errno; + if (res < 0) + res = errno; #endif - *timeoutp = timeout; + *timeoutp = timeout; - return res; + return res; } /* s.connect(sockaddr) method */ @@ -1962,26 +1962,26 @@ static PyObject * sock_connect(PySocketSockObject *s, PyObject *addro) { - sock_addr_t addrbuf; - int addrlen; - int res; - int timeout; - - if (!getsockaddrarg(s, addro, SAS2SA(&addrbuf), &addrlen)) - return NULL; - - Py_BEGIN_ALLOW_THREADS - res = internal_connect(s, SAS2SA(&addrbuf), addrlen, &timeout); - Py_END_ALLOW_THREADS - - if (timeout == 1) { - PyErr_SetString(socket_timeout, "timed out"); - return NULL; - } - if (res != 0) - return s->errorhandler(); - Py_INCREF(Py_None); - return Py_None; + sock_addr_t addrbuf; + int addrlen; + int res; + int timeout; + + if (!getsockaddrarg(s, addro, SAS2SA(&addrbuf), &addrlen)) + return NULL; + + Py_BEGIN_ALLOW_THREADS + res = internal_connect(s, SAS2SA(&addrbuf), addrlen, &timeout); + Py_END_ALLOW_THREADS + + if (timeout == 1) { + PyErr_SetString(socket_timeout, "timed out"); + return NULL; + } + if (res != 0) + return s->errorhandler(); + Py_INCREF(Py_None); + return Py_None; } PyDoc_STRVAR(connect_doc, @@ -1996,26 +1996,26 @@ static PyObject * sock_connect_ex(PySocketSockObject *s, PyObject *addro) { - sock_addr_t addrbuf; - int addrlen; - int res; - int timeout; - - if (!getsockaddrarg(s, addro, SAS2SA(&addrbuf), &addrlen)) - return NULL; - - Py_BEGIN_ALLOW_THREADS - res = internal_connect(s, SAS2SA(&addrbuf), addrlen, &timeout); - Py_END_ALLOW_THREADS + sock_addr_t addrbuf; + int addrlen; + int res; + int timeout; + + if (!getsockaddrarg(s, addro, SAS2SA(&addrbuf), &addrlen)) + return NULL; + + Py_BEGIN_ALLOW_THREADS + res = internal_connect(s, SAS2SA(&addrbuf), addrlen, &timeout); + Py_END_ALLOW_THREADS - /* Signals are not errors (though they may raise exceptions). Adapted - from PyErr_SetFromErrnoWithFilenameObject(). */ + /* Signals are not errors (though they may raise exceptions). Adapted + from PyErr_SetFromErrnoWithFilenameObject(). */ #ifdef EINTR - if (res == EINTR && PyErr_CheckSignals()) - return NULL; + if (res == EINTR && PyErr_CheckSignals()) + return NULL; #endif - return PyLong_FromLong((long) res); + return PyLong_FromLong((long) res); } PyDoc_STRVAR(connect_ex_doc, @@ -2030,7 +2030,7 @@ static PyObject * sock_fileno(PySocketSockObject *s) { - return PyLong_FromSocket_t(s->sock_fd); + return PyLong_FromSocket_t(s->sock_fd); } PyDoc_STRVAR(fileno_doc, @@ -2044,20 +2044,20 @@ static PyObject * sock_getsockname(PySocketSockObject *s) { - sock_addr_t addrbuf; - int res; - socklen_t addrlen; - - if (!getsockaddrlen(s, &addrlen)) - return NULL; - memset(&addrbuf, 0, addrlen); - Py_BEGIN_ALLOW_THREADS - res = getsockname(s->sock_fd, SAS2SA(&addrbuf), &addrlen); - Py_END_ALLOW_THREADS - if (res < 0) - return s->errorhandler(); - return makesockaddr(s->sock_fd, SAS2SA(&addrbuf), addrlen, - s->sock_proto); + sock_addr_t addrbuf; + int res; + socklen_t addrlen; + + if (!getsockaddrlen(s, &addrlen)) + return NULL; + memset(&addrbuf, 0, addrlen); + Py_BEGIN_ALLOW_THREADS + res = getsockname(s->sock_fd, SAS2SA(&addrbuf), &addrlen); + Py_END_ALLOW_THREADS + if (res < 0) + return s->errorhandler(); + return makesockaddr(s->sock_fd, SAS2SA(&addrbuf), addrlen, + s->sock_proto); } PyDoc_STRVAR(getsockname_doc, @@ -2067,26 +2067,26 @@ info is a pair (hostaddr, port)."); -#ifdef HAVE_GETPEERNAME /* Cray APP doesn't have this :-( */ +#ifdef HAVE_GETPEERNAME /* Cray APP doesn't have this :-( */ /* s.getpeername() method */ static PyObject * sock_getpeername(PySocketSockObject *s) { - sock_addr_t addrbuf; - int res; - socklen_t addrlen; - - if (!getsockaddrlen(s, &addrlen)) - return NULL; - memset(&addrbuf, 0, addrlen); - Py_BEGIN_ALLOW_THREADS - res = getpeername(s->sock_fd, SAS2SA(&addrbuf), &addrlen); - Py_END_ALLOW_THREADS - if (res < 0) - return s->errorhandler(); - return makesockaddr(s->sock_fd, SAS2SA(&addrbuf), addrlen, - s->sock_proto); + sock_addr_t addrbuf; + int res; + socklen_t addrlen; + + if (!getsockaddrlen(s, &addrlen)) + return NULL; + memset(&addrbuf, 0, addrlen); + Py_BEGIN_ALLOW_THREADS + res = getpeername(s->sock_fd, SAS2SA(&addrbuf), &addrlen); + Py_END_ALLOW_THREADS + if (res < 0) + return s->errorhandler(); + return makesockaddr(s->sock_fd, SAS2SA(&addrbuf), addrlen, + s->sock_proto); } PyDoc_STRVAR(getpeername_doc, @@ -2103,21 +2103,21 @@ static PyObject * sock_listen(PySocketSockObject *s, PyObject *arg) { - int backlog; - int res; + int backlog; + int res; - backlog = PyLong_AsLong(arg); - if (backlog == -1 && PyErr_Occurred()) - return NULL; - Py_BEGIN_ALLOW_THREADS - if (backlog < 1) - backlog = 1; - res = listen(s->sock_fd, backlog); - Py_END_ALLOW_THREADS - if (res < 0) - return s->errorhandler(); - Py_INCREF(Py_None); - return Py_None; + backlog = PyLong_AsLong(arg); + if (backlog == -1 && PyErr_Occurred()) + return NULL; + Py_BEGIN_ALLOW_THREADS + if (backlog < 1) + backlog = 1; + res = listen(s->sock_fd, backlog); + Py_END_ALLOW_THREADS + if (res < 0) + return s->errorhandler(); + Py_INCREF(Py_None); + return Py_None; } PyDoc_STRVAR(listen_doc, @@ -2139,80 +2139,80 @@ static ssize_t sock_recv_guts(PySocketSockObject *s, char* cbuf, int len, int flags) { - ssize_t outlen = -1; - int timeout; + ssize_t outlen = -1; + int timeout; #ifdef __VMS - int remaining; - char *read_buf; + int remaining; + char *read_buf; #endif - if (!IS_SELECTABLE(s)) { - select_error(); - return -1; - } - if (len == 0) { - /* If 0 bytes were requested, do nothing. */ - return 0; - } + if (!IS_SELECTABLE(s)) { + select_error(); + return -1; + } + if (len == 0) { + /* If 0 bytes were requested, do nothing. */ + return 0; + } #ifndef __VMS - Py_BEGIN_ALLOW_THREADS - timeout = internal_select(s, 0); - if (!timeout) - outlen = recv(s->sock_fd, cbuf, len, flags); - Py_END_ALLOW_THREADS - - if (timeout == 1) { - PyErr_SetString(socket_timeout, "timed out"); - return -1; - } - if (outlen < 0) { - /* Note: the call to errorhandler() ALWAYS indirectly returned - NULL, so ignore its return value */ - s->errorhandler(); - return -1; - } -#else - read_buf = cbuf; - remaining = len; - while (remaining != 0) { - unsigned int segment; - int nread = -1; - - segment = remaining /SEGMENT_SIZE; - if (segment != 0) { - segment = SEGMENT_SIZE; - } - else { - segment = remaining; - } - - Py_BEGIN_ALLOW_THREADS - timeout = internal_select(s, 0); - if (!timeout) - nread = recv(s->sock_fd, read_buf, segment, flags); - Py_END_ALLOW_THREADS - - if (timeout == 1) { - PyErr_SetString(socket_timeout, "timed out"); - return -1; - } - if (nread < 0) { - s->errorhandler(); - return -1; - } - if (nread != remaining) { - read_buf += nread; - break; - } - - remaining -= segment; - read_buf += segment; - } - outlen = read_buf - cbuf; + Py_BEGIN_ALLOW_THREADS + timeout = internal_select(s, 0); + if (!timeout) + outlen = recv(s->sock_fd, cbuf, len, flags); + Py_END_ALLOW_THREADS + + if (timeout == 1) { + PyErr_SetString(socket_timeout, "timed out"); + return -1; + } + if (outlen < 0) { + /* Note: the call to errorhandler() ALWAYS indirectly returned + NULL, so ignore its return value */ + s->errorhandler(); + return -1; + } +#else + read_buf = cbuf; + remaining = len; + while (remaining != 0) { + unsigned int segment; + int nread = -1; + + segment = remaining /SEGMENT_SIZE; + if (segment != 0) { + segment = SEGMENT_SIZE; + } + else { + segment = remaining; + } + + Py_BEGIN_ALLOW_THREADS + timeout = internal_select(s, 0); + if (!timeout) + nread = recv(s->sock_fd, read_buf, segment, flags); + Py_END_ALLOW_THREADS + + if (timeout == 1) { + PyErr_SetString(socket_timeout, "timed out"); + return -1; + } + if (nread < 0) { + s->errorhandler(); + return -1; + } + if (nread != remaining) { + read_buf += nread; + break; + } + + remaining -= segment; + read_buf += segment; + } + outlen = read_buf - cbuf; #endif /* !__VMS */ - return outlen; + return outlen; } @@ -2221,39 +2221,39 @@ static PyObject * sock_recv(PySocketSockObject *s, PyObject *args) { - int recvlen, flags = 0; - ssize_t outlen; - PyObject *buf; - - if (!PyArg_ParseTuple(args, "i|i:recv", &recvlen, &flags)) - return NULL; - - if (recvlen < 0) { - PyErr_SetString(PyExc_ValueError, - "negative buffersize in recv"); - return NULL; - } - - /* Allocate a new string. */ - buf = PyBytes_FromStringAndSize((char *) 0, recvlen); - if (buf == NULL) - return NULL; - - /* Call the guts */ - outlen = sock_recv_guts(s, PyBytes_AS_STRING(buf), recvlen, flags); - if (outlen < 0) { - /* An error occurred, release the string and return an - error. */ - Py_DECREF(buf); - return NULL; - } - if (outlen != recvlen) { - /* We did not read as many bytes as we anticipated, resize the - string if possible and be successful. */ - _PyBytes_Resize(&buf, outlen); - } + int recvlen, flags = 0; + ssize_t outlen; + PyObject *buf; + + if (!PyArg_ParseTuple(args, "i|i:recv", &recvlen, &flags)) + return NULL; + + if (recvlen < 0) { + PyErr_SetString(PyExc_ValueError, + "negative buffersize in recv"); + return NULL; + } + + /* Allocate a new string. */ + buf = PyBytes_FromStringAndSize((char *) 0, recvlen); + if (buf == NULL) + return NULL; + + /* Call the guts */ + outlen = sock_recv_guts(s, PyBytes_AS_STRING(buf), recvlen, flags); + if (outlen < 0) { + /* An error occurred, release the string and return an + error. */ + Py_DECREF(buf); + return NULL; + } + if (outlen != recvlen) { + /* We did not read as many bytes as we anticipated, resize the + string if possible and be successful. */ + _PyBytes_Resize(&buf, outlen); + } - return buf; + return buf; } PyDoc_STRVAR(recv_doc, @@ -2270,52 +2270,52 @@ static PyObject* sock_recv_into(PySocketSockObject *s, PyObject *args, PyObject *kwds) { - static char *kwlist[] = {"buffer", "nbytes", "flags", 0}; + static char *kwlist[] = {"buffer", "nbytes", "flags", 0}; - int recvlen = 0, flags = 0; - ssize_t readlen; - Py_buffer pbuf; - char *buf; - int buflen; - - /* Get the buffer's memory */ - if (!PyArg_ParseTupleAndKeywords(args, kwds, "w*|ii:recv_into", kwlist, - &pbuf, &recvlen, &flags)) - return NULL; - buf = pbuf.buf; - buflen = pbuf.len; - - if (recvlen < 0) { - PyBuffer_Release(&pbuf); - PyErr_SetString(PyExc_ValueError, - "negative buffersize in recv_into"); - return NULL; - } - if (recvlen == 0) { - /* If nbytes was not specified, use the buffer's length */ - recvlen = buflen; - } - - /* Check if the buffer is large enough */ - if (buflen < recvlen) { - PyBuffer_Release(&pbuf); - PyErr_SetString(PyExc_ValueError, - "buffer too small for requested bytes"); - return NULL; - } - - /* Call the guts */ - readlen = sock_recv_guts(s, buf, recvlen, flags); - if (readlen < 0) { - /* Return an error. */ - PyBuffer_Release(&pbuf); - return NULL; - } - - PyBuffer_Release(&pbuf); - /* Return the number of bytes read. Note that we do not do anything - special here in the case that readlen < recvlen. */ - return PyLong_FromSsize_t(readlen); + int recvlen = 0, flags = 0; + ssize_t readlen; + Py_buffer pbuf; + char *buf; + int buflen; + + /* Get the buffer's memory */ + if (!PyArg_ParseTupleAndKeywords(args, kwds, "w*|ii:recv_into", kwlist, + &pbuf, &recvlen, &flags)) + return NULL; + buf = pbuf.buf; + buflen = pbuf.len; + + if (recvlen < 0) { + PyBuffer_Release(&pbuf); + PyErr_SetString(PyExc_ValueError, + "negative buffersize in recv_into"); + return NULL; + } + if (recvlen == 0) { + /* If nbytes was not specified, use the buffer's length */ + recvlen = buflen; + } + + /* Check if the buffer is large enough */ + if (buflen < recvlen) { + PyBuffer_Release(&pbuf); + PyErr_SetString(PyExc_ValueError, + "buffer too small for requested bytes"); + return NULL; + } + + /* Call the guts */ + readlen = sock_recv_guts(s, buf, recvlen, flags); + if (readlen < 0) { + /* Return an error. */ + PyBuffer_Release(&pbuf); + return NULL; + } + + PyBuffer_Release(&pbuf); + /* Return the number of bytes read. Note that we do not do anything + special here in the case that readlen < recvlen. */ + return PyLong_FromSsize_t(readlen); } PyDoc_STRVAR(recv_into_doc, @@ -2341,56 +2341,56 @@ */ static ssize_t sock_recvfrom_guts(PySocketSockObject *s, char* cbuf, int len, int flags, - PyObject** addr) + PyObject** addr) { - sock_addr_t addrbuf; - int timeout; - ssize_t n = -1; - socklen_t addrlen; - - *addr = NULL; - - if (!getsockaddrlen(s, &addrlen)) - return -1; - - if (!IS_SELECTABLE(s)) { - select_error(); - return -1; - } - - Py_BEGIN_ALLOW_THREADS - memset(&addrbuf, 0, addrlen); - timeout = internal_select(s, 0); - if (!timeout) { + sock_addr_t addrbuf; + int timeout; + ssize_t n = -1; + socklen_t addrlen; + + *addr = NULL; + + if (!getsockaddrlen(s, &addrlen)) + return -1; + + if (!IS_SELECTABLE(s)) { + select_error(); + return -1; + } + + Py_BEGIN_ALLOW_THREADS + memset(&addrbuf, 0, addrlen); + timeout = internal_select(s, 0); + if (!timeout) { #ifndef MS_WINDOWS #if defined(PYOS_OS2) && !defined(PYCC_GCC) - n = recvfrom(s->sock_fd, cbuf, len, flags, - SAS2SA(&addrbuf), &addrlen); + n = recvfrom(s->sock_fd, cbuf, len, flags, + SAS2SA(&addrbuf), &addrlen); #else - n = recvfrom(s->sock_fd, cbuf, len, flags, - (void *) &addrbuf, &addrlen); + n = recvfrom(s->sock_fd, cbuf, len, flags, + (void *) &addrbuf, &addrlen); #endif #else - n = recvfrom(s->sock_fd, cbuf, len, flags, - SAS2SA(&addrbuf), &addrlen); + n = recvfrom(s->sock_fd, cbuf, len, flags, + SAS2SA(&addrbuf), &addrlen); #endif - } - Py_END_ALLOW_THREADS + } + Py_END_ALLOW_THREADS - if (timeout == 1) { - PyErr_SetString(socket_timeout, "timed out"); - return -1; - } - if (n < 0) { - s->errorhandler(); - return -1; - } + if (timeout == 1) { + PyErr_SetString(socket_timeout, "timed out"); + return -1; + } + if (n < 0) { + s->errorhandler(); + return -1; + } - if (!(*addr = makesockaddr(s->sock_fd, SAS2SA(&addrbuf), - addrlen, s->sock_proto))) - return -1; + if (!(*addr = makesockaddr(s->sock_fd, SAS2SA(&addrbuf), + addrlen, s->sock_proto))) + return -1; - return n; + return n; } /* s.recvfrom(nbytes [,flags]) method */ @@ -2398,45 +2398,45 @@ static PyObject * sock_recvfrom(PySocketSockObject *s, PyObject *args) { - PyObject *buf = NULL; - PyObject *addr = NULL; - PyObject *ret = NULL; - int recvlen, flags = 0; - ssize_t outlen; - - if (!PyArg_ParseTuple(args, "i|i:recvfrom", &recvlen, &flags)) - return NULL; - - if (recvlen < 0) { - PyErr_SetString(PyExc_ValueError, - "negative buffersize in recvfrom"); - return NULL; - } - - buf = PyBytes_FromStringAndSize((char *) 0, recvlen); - if (buf == NULL) - return NULL; - - outlen = sock_recvfrom_guts(s, PyBytes_AS_STRING(buf), - recvlen, flags, &addr); - if (outlen < 0) { - goto finally; - } - - if (outlen != recvlen) { - /* We did not read as many bytes as we anticipated, resize the - string if possible and be succesful. */ - if (_PyBytes_Resize(&buf, outlen) < 0) - /* Oopsy, not so succesful after all. */ - goto finally; - } + PyObject *buf = NULL; + PyObject *addr = NULL; + PyObject *ret = NULL; + int recvlen, flags = 0; + ssize_t outlen; + + if (!PyArg_ParseTuple(args, "i|i:recvfrom", &recvlen, &flags)) + return NULL; + + if (recvlen < 0) { + PyErr_SetString(PyExc_ValueError, + "negative buffersize in recvfrom"); + return NULL; + } + + buf = PyBytes_FromStringAndSize((char *) 0, recvlen); + if (buf == NULL) + return NULL; + + outlen = sock_recvfrom_guts(s, PyBytes_AS_STRING(buf), + recvlen, flags, &addr); + if (outlen < 0) { + goto finally; + } + + if (outlen != recvlen) { + /* We did not read as many bytes as we anticipated, resize the + string if possible and be succesful. */ + if (_PyBytes_Resize(&buf, outlen) < 0) + /* Oopsy, not so succesful after all. */ + goto finally; + } - ret = PyTuple_Pack(2, buf, addr); + ret = PyTuple_Pack(2, buf, addr); finally: - Py_XDECREF(buf); - Py_XDECREF(addr); - return ret; + Py_XDECREF(buf); + Py_XDECREF(addr); + return ret; } PyDoc_STRVAR(recvfrom_doc, @@ -2450,47 +2450,47 @@ static PyObject * sock_recvfrom_into(PySocketSockObject *s, PyObject *args, PyObject* kwds) { - static char *kwlist[] = {"buffer", "nbytes", "flags", 0}; + static char *kwlist[] = {"buffer", "nbytes", "flags", 0}; - int recvlen = 0, flags = 0; - ssize_t readlen; - Py_buffer pbuf; - char *buf; - int buflen; - - PyObject *addr = NULL; - - if (!PyArg_ParseTupleAndKeywords(args, kwds, "w*|ii:recvfrom_into", - kwlist, &pbuf, - &recvlen, &flags)) - return NULL; - buf = pbuf.buf; - buflen = pbuf.len; - assert(buf != 0 && buflen > 0); - - if (recvlen < 0) { - PyBuffer_Release(&pbuf); - PyErr_SetString(PyExc_ValueError, - "negative buffersize in recvfrom_into"); - return NULL; - } - if (recvlen == 0) { - /* If nbytes was not specified, use the buffer's length */ - recvlen = buflen; - } - - readlen = sock_recvfrom_guts(s, buf, recvlen, flags, &addr); - if (readlen < 0) { - PyBuffer_Release(&pbuf); - /* Return an error */ - Py_XDECREF(addr); - return NULL; - } - - PyBuffer_Release(&pbuf); - /* Return the number of bytes read and the address. Note that we do - not do anything special here in the case that readlen < recvlen. */ - return Py_BuildValue("lN", readlen, addr); + int recvlen = 0, flags = 0; + ssize_t readlen; + Py_buffer pbuf; + char *buf; + int buflen; + + PyObject *addr = NULL; + + if (!PyArg_ParseTupleAndKeywords(args, kwds, "w*|ii:recvfrom_into", + kwlist, &pbuf, + &recvlen, &flags)) + return NULL; + buf = pbuf.buf; + buflen = pbuf.len; + assert(buf != 0 && buflen > 0); + + if (recvlen < 0) { + PyBuffer_Release(&pbuf); + PyErr_SetString(PyExc_ValueError, + "negative buffersize in recvfrom_into"); + return NULL; + } + if (recvlen == 0) { + /* If nbytes was not specified, use the buffer's length */ + recvlen = buflen; + } + + readlen = sock_recvfrom_guts(s, buf, recvlen, flags, &addr); + if (readlen < 0) { + PyBuffer_Release(&pbuf); + /* Return an error */ + Py_XDECREF(addr); + return NULL; + } + + PyBuffer_Release(&pbuf); + /* Return the number of bytes read and the address. Note that we do + not do anything special here in the case that readlen < recvlen. */ + return Py_BuildValue("lN", readlen, addr); } PyDoc_STRVAR(recvfrom_into_doc, @@ -2504,39 +2504,39 @@ static PyObject * sock_send(PySocketSockObject *s, PyObject *args) { - char *buf; - int len, n = -1, flags = 0, timeout; - Py_buffer pbuf; - - if (!PyArg_ParseTuple(args, "y*|i:send", &pbuf, &flags)) - return NULL; - - if (!IS_SELECTABLE(s)) { - PyBuffer_Release(&pbuf); - return select_error(); - } - buf = pbuf.buf; - len = pbuf.len; - - Py_BEGIN_ALLOW_THREADS - timeout = internal_select(s, 1); - if (!timeout) + char *buf; + int len, n = -1, flags = 0, timeout; + Py_buffer pbuf; + + if (!PyArg_ParseTuple(args, "y*|i:send", &pbuf, &flags)) + return NULL; + + if (!IS_SELECTABLE(s)) { + PyBuffer_Release(&pbuf); + return select_error(); + } + buf = pbuf.buf; + len = pbuf.len; + + Py_BEGIN_ALLOW_THREADS + timeout = internal_select(s, 1); + if (!timeout) #ifdef __VMS - n = sendsegmented(s->sock_fd, buf, len, flags); + n = sendsegmented(s->sock_fd, buf, len, flags); #else - n = send(s->sock_fd, buf, len, flags); + n = send(s->sock_fd, buf, len, flags); #endif - Py_END_ALLOW_THREADS + Py_END_ALLOW_THREADS - PyBuffer_Release(&pbuf); + PyBuffer_Release(&pbuf); - if (timeout == 1) { - PyErr_SetString(socket_timeout, "timed out"); - return NULL; - } - if (n < 0) - return s->errorhandler(); - return PyLong_FromLong((long)n); + if (timeout == 1) { + PyErr_SetString(socket_timeout, "timed out"); + return NULL; + } + if (n < 0) + return s->errorhandler(); + return PyLong_FromLong((long)n); } PyDoc_STRVAR(send_doc, @@ -2552,61 +2552,61 @@ static PyObject * sock_sendall(PySocketSockObject *s, PyObject *args) { - char *buf; - int len, n = -1, flags = 0, timeout; - Py_buffer pbuf; - - if (!PyArg_ParseTuple(args, "y*|i:sendall", &pbuf, &flags)) - return NULL; - buf = pbuf.buf; - len = pbuf.len; - - if (!IS_SELECTABLE(s)) { - PyBuffer_Release(&pbuf); - return select_error(); - } - - Py_BEGIN_ALLOW_THREADS - do { - timeout = internal_select(s, 1); - n = -1; - if (timeout) - break; + char *buf; + int len, n = -1, flags = 0, timeout; + Py_buffer pbuf; + + if (!PyArg_ParseTuple(args, "y*|i:sendall", &pbuf, &flags)) + return NULL; + buf = pbuf.buf; + len = pbuf.len; + + if (!IS_SELECTABLE(s)) { + PyBuffer_Release(&pbuf); + return select_error(); + } + + Py_BEGIN_ALLOW_THREADS + do { + timeout = internal_select(s, 1); + n = -1; + if (timeout) + break; #ifdef __VMS - n = sendsegmented(s->sock_fd, buf, len, flags); + n = sendsegmented(s->sock_fd, buf, len, flags); #else - n = send(s->sock_fd, buf, len, flags); + n = send(s->sock_fd, buf, len, flags); #endif - if (n < 0) { + if (n < 0) { #ifdef EINTR - /* We must handle EINTR here as there is no way for - * the caller to know how much was sent otherwise. */ - if (errno == EINTR) { - /* Run signal handlers. If an exception was - * raised, abort and leave this socket in - * an unknown state. */ - if (PyErr_CheckSignals()) - return NULL; - continue; - } -#endif - break; - } - buf += n; - len -= n; - } while (len > 0); - Py_END_ALLOW_THREADS - PyBuffer_Release(&pbuf); - - if (timeout == 1) { - PyErr_SetString(socket_timeout, "timed out"); - return NULL; - } - if (n < 0) - return s->errorhandler(); + /* We must handle EINTR here as there is no way for + * the caller to know how much was sent otherwise. */ + if (errno == EINTR) { + /* Run signal handlers. If an exception was + * raised, abort and leave this socket in + * an unknown state. */ + if (PyErr_CheckSignals()) + return NULL; + continue; + } +#endif + break; + } + buf += n; + len -= n; + } while (len > 0); + Py_END_ALLOW_THREADS + PyBuffer_Release(&pbuf); + + if (timeout == 1) { + PyErr_SetString(socket_timeout, "timed out"); + return NULL; + } + if (n < 0) + return s->errorhandler(); - Py_INCREF(Py_None); - return Py_None; + Py_INCREF(Py_None); + return Py_None; } PyDoc_STRVAR(sendall_doc, @@ -2623,47 +2623,47 @@ static PyObject * sock_sendto(PySocketSockObject *s, PyObject *args) { - Py_buffer pbuf; - PyObject *addro; - char *buf; - Py_ssize_t len; - sock_addr_t addrbuf; - int addrlen, n = -1, flags, timeout; - - flags = 0; - if (!PyArg_ParseTuple(args, "y*O:sendto", &pbuf, &addro)) { - PyErr_Clear(); - if (!PyArg_ParseTuple(args, "y*iO:sendto", - &pbuf, &flags, &addro)) - return NULL; - } - buf = pbuf.buf; - len = pbuf.len; - - if (!IS_SELECTABLE(s)) { - PyBuffer_Release(&pbuf); - return select_error(); - } - - if (!getsockaddrarg(s, addro, SAS2SA(&addrbuf), &addrlen)) { - PyBuffer_Release(&pbuf); - return NULL; - } - - Py_BEGIN_ALLOW_THREADS - timeout = internal_select(s, 1); - if (!timeout) - n = sendto(s->sock_fd, buf, len, flags, SAS2SA(&addrbuf), addrlen); - Py_END_ALLOW_THREADS - - PyBuffer_Release(&pbuf); - if (timeout == 1) { - PyErr_SetString(socket_timeout, "timed out"); - return NULL; - } - if (n < 0) - return s->errorhandler(); - return PyLong_FromLong((long)n); + Py_buffer pbuf; + PyObject *addro; + char *buf; + Py_ssize_t len; + sock_addr_t addrbuf; + int addrlen, n = -1, flags, timeout; + + flags = 0; + if (!PyArg_ParseTuple(args, "y*O:sendto", &pbuf, &addro)) { + PyErr_Clear(); + if (!PyArg_ParseTuple(args, "y*iO:sendto", + &pbuf, &flags, &addro)) + return NULL; + } + buf = pbuf.buf; + len = pbuf.len; + + if (!IS_SELECTABLE(s)) { + PyBuffer_Release(&pbuf); + return select_error(); + } + + if (!getsockaddrarg(s, addro, SAS2SA(&addrbuf), &addrlen)) { + PyBuffer_Release(&pbuf); + return NULL; + } + + Py_BEGIN_ALLOW_THREADS + timeout = internal_select(s, 1); + if (!timeout) + n = sendto(s->sock_fd, buf, len, flags, SAS2SA(&addrbuf), addrlen); + Py_END_ALLOW_THREADS + + PyBuffer_Release(&pbuf); + if (timeout == 1) { + PyErr_SetString(socket_timeout, "timed out"); + return NULL; + } + if (n < 0) + return s->errorhandler(); + return PyLong_FromLong((long)n); } PyDoc_STRVAR(sendto_doc, @@ -2678,19 +2678,19 @@ static PyObject * sock_shutdown(PySocketSockObject *s, PyObject *arg) { - int how; - int res; + int how; + int res; - how = PyLong_AsLong(arg); - if (how == -1 && PyErr_Occurred()) - return NULL; - Py_BEGIN_ALLOW_THREADS - res = shutdown(s->sock_fd, how); - Py_END_ALLOW_THREADS - if (res < 0) - return s->errorhandler(); - Py_INCREF(Py_None); - return Py_None; + how = PyLong_AsLong(arg); + if (how == -1 && PyErr_Occurred()) + return NULL; + Py_BEGIN_ALLOW_THREADS + res = shutdown(s->sock_fd, how); + Py_END_ALLOW_THREADS + if (res < 0) + return s->errorhandler(); + Py_INCREF(Py_None); + return Py_None; } PyDoc_STRVAR(shutdown_doc, @@ -2703,37 +2703,37 @@ static PyObject* sock_ioctl(PySocketSockObject *s, PyObject *arg) { - unsigned long cmd = SIO_RCVALL; - PyObject *argO; - DWORD recv; - - if (!PyArg_ParseTuple(arg, "kO:ioctl", &cmd, &argO)) - return NULL; - - switch (cmd) { - case SIO_RCVALL: { - unsigned int option = RCVALL_ON; - if (!PyArg_ParseTuple(arg, "kI:ioctl", &cmd, &option)) - return NULL; - if (WSAIoctl(s->sock_fd, cmd, &option, sizeof(option), - NULL, 0, &recv, NULL, NULL) == SOCKET_ERROR) { - return set_error(); - } - return PyLong_FromUnsignedLong(recv); } - case SIO_KEEPALIVE_VALS: { - struct tcp_keepalive ka; - if (!PyArg_ParseTuple(arg, "k(kkk):ioctl", &cmd, - &ka.onoff, &ka.keepalivetime, &ka.keepaliveinterval)) - return NULL; - if (WSAIoctl(s->sock_fd, cmd, &ka, sizeof(ka), - NULL, 0, &recv, NULL, NULL) == SOCKET_ERROR) { - return set_error(); - } - return PyLong_FromUnsignedLong(recv); } - default: - PyErr_Format(PyExc_ValueError, "invalid ioctl command %d", cmd); - return NULL; - } + unsigned long cmd = SIO_RCVALL; + PyObject *argO; + DWORD recv; + + if (!PyArg_ParseTuple(arg, "kO:ioctl", &cmd, &argO)) + return NULL; + + switch (cmd) { + case SIO_RCVALL: { + unsigned int option = RCVALL_ON; + if (!PyArg_ParseTuple(arg, "kI:ioctl", &cmd, &option)) + return NULL; + if (WSAIoctl(s->sock_fd, cmd, &option, sizeof(option), + NULL, 0, &recv, NULL, NULL) == SOCKET_ERROR) { + return set_error(); + } + return PyLong_FromUnsignedLong(recv); } + case SIO_KEEPALIVE_VALS: { + struct tcp_keepalive ka; + if (!PyArg_ParseTuple(arg, "k(kkk):ioctl", &cmd, + &ka.onoff, &ka.keepalivetime, &ka.keepaliveinterval)) + return NULL; + if (WSAIoctl(s->sock_fd, cmd, &ka, sizeof(ka), + NULL, 0, &recv, NULL, NULL) == SOCKET_ERROR) { + return set_error(); + } + return PyLong_FromUnsignedLong(recv); } + default: + PyErr_Format(PyExc_ValueError, "invalid ioctl command %d", cmd); + return NULL; + } } PyDoc_STRVAR(sock_ioctl_doc, "ioctl(cmd, option) -> long\n\ @@ -2747,57 +2747,57 @@ /* List of methods for socket objects */ static PyMethodDef sock_methods[] = { - {"_accept", (PyCFunction)sock_accept, METH_NOARGS, - accept_doc}, - {"bind", (PyCFunction)sock_bind, METH_O, - bind_doc}, - {"close", (PyCFunction)sock_close, METH_NOARGS, - close_doc}, - {"connect", (PyCFunction)sock_connect, METH_O, - connect_doc}, - {"connect_ex", (PyCFunction)sock_connect_ex, METH_O, - connect_ex_doc}, - {"fileno", (PyCFunction)sock_fileno, METH_NOARGS, - fileno_doc}, + {"_accept", (PyCFunction)sock_accept, METH_NOARGS, + accept_doc}, + {"bind", (PyCFunction)sock_bind, METH_O, + bind_doc}, + {"close", (PyCFunction)sock_close, METH_NOARGS, + close_doc}, + {"connect", (PyCFunction)sock_connect, METH_O, + connect_doc}, + {"connect_ex", (PyCFunction)sock_connect_ex, METH_O, + connect_ex_doc}, + {"fileno", (PyCFunction)sock_fileno, METH_NOARGS, + fileno_doc}, #ifdef HAVE_GETPEERNAME - {"getpeername", (PyCFunction)sock_getpeername, - METH_NOARGS, getpeername_doc}, + {"getpeername", (PyCFunction)sock_getpeername, + METH_NOARGS, getpeername_doc}, #endif - {"getsockname", (PyCFunction)sock_getsockname, - METH_NOARGS, getsockname_doc}, - {"getsockopt", (PyCFunction)sock_getsockopt, METH_VARARGS, - getsockopt_doc}, + {"getsockname", (PyCFunction)sock_getsockname, + METH_NOARGS, getsockname_doc}, + {"getsockopt", (PyCFunction)sock_getsockopt, METH_VARARGS, + getsockopt_doc}, #if defined(MS_WINDOWS) && defined(SIO_RCVALL) - {"ioctl", (PyCFunction)sock_ioctl, METH_VARARGS, - sock_ioctl_doc}, + {"ioctl", (PyCFunction)sock_ioctl, METH_VARARGS, + sock_ioctl_doc}, #endif - {"listen", (PyCFunction)sock_listen, METH_O, - listen_doc}, - {"recv", (PyCFunction)sock_recv, METH_VARARGS, - recv_doc}, - {"recv_into", (PyCFunction)sock_recv_into, METH_VARARGS | METH_KEYWORDS, - recv_into_doc}, - {"recvfrom", (PyCFunction)sock_recvfrom, METH_VARARGS, - recvfrom_doc}, - {"recvfrom_into", (PyCFunction)sock_recvfrom_into, METH_VARARGS | METH_KEYWORDS, - recvfrom_into_doc}, - {"send", (PyCFunction)sock_send, METH_VARARGS, - send_doc}, - {"sendall", (PyCFunction)sock_sendall, METH_VARARGS, - sendall_doc}, - {"sendto", (PyCFunction)sock_sendto, METH_VARARGS, - sendto_doc}, - {"setblocking", (PyCFunction)sock_setblocking, METH_O, - setblocking_doc}, - {"settimeout", (PyCFunction)sock_settimeout, METH_O, - settimeout_doc}, - {"gettimeout", (PyCFunction)sock_gettimeout, METH_NOARGS, - gettimeout_doc}, - {"setsockopt", (PyCFunction)sock_setsockopt, METH_VARARGS, - setsockopt_doc}, - {"shutdown", (PyCFunction)sock_shutdown, METH_O, - shutdown_doc}, - {NULL, NULL} /* sentinel */ + {"listen", (PyCFunction)sock_listen, METH_O, + listen_doc}, + {"recv", (PyCFunction)sock_recv, METH_VARARGS, + recv_doc}, + {"recv_into", (PyCFunction)sock_recv_into, METH_VARARGS | METH_KEYWORDS, + recv_into_doc}, + {"recvfrom", (PyCFunction)sock_recvfrom, METH_VARARGS, + recvfrom_doc}, + {"recvfrom_into", (PyCFunction)sock_recvfrom_into, METH_VARARGS | METH_KEYWORDS, + recvfrom_into_doc}, + {"send", (PyCFunction)sock_send, METH_VARARGS, + send_doc}, + {"sendall", (PyCFunction)sock_sendall, METH_VARARGS, + sendall_doc}, + {"sendto", (PyCFunction)sock_sendto, METH_VARARGS, + sendto_doc}, + {"setblocking", (PyCFunction)sock_setblocking, METH_O, + setblocking_doc}, + {"settimeout", (PyCFunction)sock_settimeout, METH_O, + settimeout_doc}, + {"gettimeout", (PyCFunction)sock_gettimeout, METH_NOARGS, + gettimeout_doc}, + {"setsockopt", (PyCFunction)sock_setsockopt, METH_VARARGS, + setsockopt_doc}, + {"shutdown", (PyCFunction)sock_shutdown, METH_O, + shutdown_doc}, + {NULL, NULL} /* sentinel */ }; /* SockObject members */ @@ -2815,9 +2815,9 @@ static void sock_dealloc(PySocketSockObject *s) { - if (s->sock_fd != -1) - (void) SOCKETCLOSE(s->sock_fd); - Py_TYPE(s)->tp_free((PyObject *)s); + if (s->sock_fd != -1) + (void) SOCKETCLOSE(s->sock_fd); + Py_TYPE(s)->tp_free((PyObject *)s); } @@ -2825,21 +2825,21 @@ sock_repr(PySocketSockObject *s) { #if SIZEOF_SOCKET_T > SIZEOF_LONG - if (s->sock_fd > LONG_MAX) { - /* this can occur on Win64, and actually there is a special - ugly printf formatter for decimal pointer length integer - printing, only bother if necessary*/ - PyErr_SetString(PyExc_OverflowError, - "no printf formatter to display " - "the socket descriptor in decimal"); - return NULL; - } -#endif - return PyUnicode_FromFormat( - "", - (long)s->sock_fd, s->sock_family, - s->sock_type, - s->sock_proto); + if (s->sock_fd > LONG_MAX) { + /* this can occur on Win64, and actually there is a special + ugly printf formatter for decimal pointer length integer + printing, only bother if necessary*/ + PyErr_SetString(PyExc_OverflowError, + "no printf formatter to display " + "the socket descriptor in decimal"); + return NULL; + } +#endif + return PyUnicode_FromFormat( + "", + (long)s->sock_fd, s->sock_family, + s->sock_type, + s->sock_proto); } @@ -2848,15 +2848,15 @@ static PyObject * sock_new(PyTypeObject *type, PyObject *args, PyObject *kwds) { - PyObject *new; + PyObject *new; - new = type->tp_alloc(type, 0); - if (new != NULL) { - ((PySocketSockObject *)new)->sock_fd = -1; - ((PySocketSockObject *)new)->sock_timeout = -1.0; - ((PySocketSockObject *)new)->errorhandler = &set_error; - } - return new; + new = type->tp_alloc(type, 0); + if (new != NULL) { + ((PySocketSockObject *)new)->sock_fd = -1; + ((PySocketSockObject *)new)->sock_timeout = -1.0; + ((PySocketSockObject *)new)->errorhandler = &set_error; + } + return new; } @@ -2866,40 +2866,40 @@ static int sock_initobj(PyObject *self, PyObject *args, PyObject *kwds) { - PySocketSockObject *s = (PySocketSockObject *)self; - PyObject *fdobj = NULL; - SOCKET_T fd = INVALID_SOCKET; - int family = AF_INET, type = SOCK_STREAM, proto = 0; - static char *keywords[] = {"family", "type", "proto", "fileno", 0}; - - if (!PyArg_ParseTupleAndKeywords(args, kwds, - "|iiiO:socket", keywords, - &family, &type, &proto, &fdobj)) - return -1; - - if (fdobj != NULL && fdobj != Py_None) { - fd = PyLong_AsSocket_t(fdobj); - if (fd == (SOCKET_T)(-1) && PyErr_Occurred()) - return -1; - if (fd == INVALID_SOCKET) { - PyErr_SetString(PyExc_ValueError, - "can't use invalid socket value"); - return -1; - } - } - else { - Py_BEGIN_ALLOW_THREADS - fd = socket(family, type, proto); - Py_END_ALLOW_THREADS - - if (fd == INVALID_SOCKET) { - set_error(); - return -1; - } - } - init_sockobject(s, fd, family, type, proto); + PySocketSockObject *s = (PySocketSockObject *)self; + PyObject *fdobj = NULL; + SOCKET_T fd = INVALID_SOCKET; + int family = AF_INET, type = SOCK_STREAM, proto = 0; + static char *keywords[] = {"family", "type", "proto", "fileno", 0}; + + if (!PyArg_ParseTupleAndKeywords(args, kwds, + "|iiiO:socket", keywords, + &family, &type, &proto, &fdobj)) + return -1; + + if (fdobj != NULL && fdobj != Py_None) { + fd = PyLong_AsSocket_t(fdobj); + if (fd == (SOCKET_T)(-1) && PyErr_Occurred()) + return -1; + if (fd == INVALID_SOCKET) { + PyErr_SetString(PyExc_ValueError, + "can't use invalid socket value"); + return -1; + } + } + else { + Py_BEGIN_ALLOW_THREADS + fd = socket(family, type, proto); + Py_END_ALLOW_THREADS + + if (fd == INVALID_SOCKET) { + set_error(); + return -1; + } + } + init_sockobject(s, fd, family, type, proto); - return 0; + return 0; } @@ -2907,45 +2907,45 @@ /* Type object for socket objects. */ static PyTypeObject sock_type = { - PyVarObject_HEAD_INIT(0, 0) /* Must fill in type value later */ - "_socket.socket", /* tp_name */ - sizeof(PySocketSockObject), /* tp_basicsize */ - 0, /* tp_itemsize */ - (destructor)sock_dealloc, /* tp_dealloc */ - 0, /* tp_print */ - 0, /* tp_getattr */ - 0, /* tp_setattr */ - 0, /* tp_reserved */ - (reprfunc)sock_repr, /* 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_BASETYPE, /* tp_flags */ - sock_doc, /* tp_doc */ - 0, /* tp_traverse */ - 0, /* tp_clear */ - 0, /* tp_richcompare */ - 0, /* tp_weaklistoffset */ - 0, /* tp_iter */ - 0, /* tp_iternext */ - sock_methods, /* tp_methods */ - sock_memberlist, /* tp_members */ - 0, /* tp_getset */ - 0, /* tp_base */ - 0, /* tp_dict */ - 0, /* tp_descr_get */ - 0, /* tp_descr_set */ - 0, /* tp_dictoffset */ - sock_initobj, /* tp_init */ - PyType_GenericAlloc, /* tp_alloc */ - sock_new, /* tp_new */ - PyObject_Del, /* tp_free */ + PyVarObject_HEAD_INIT(0, 0) /* Must fill in type value later */ + "_socket.socket", /* tp_name */ + sizeof(PySocketSockObject), /* tp_basicsize */ + 0, /* tp_itemsize */ + (destructor)sock_dealloc, /* tp_dealloc */ + 0, /* tp_print */ + 0, /* tp_getattr */ + 0, /* tp_setattr */ + 0, /* tp_reserved */ + (reprfunc)sock_repr, /* 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_BASETYPE, /* tp_flags */ + sock_doc, /* tp_doc */ + 0, /* tp_traverse */ + 0, /* tp_clear */ + 0, /* tp_richcompare */ + 0, /* tp_weaklistoffset */ + 0, /* tp_iter */ + 0, /* tp_iternext */ + sock_methods, /* tp_methods */ + sock_memberlist, /* tp_members */ + 0, /* tp_getset */ + 0, /* tp_base */ + 0, /* tp_dict */ + 0, /* tp_descr_get */ + 0, /* tp_descr_set */ + 0, /* tp_dictoffset */ + sock_initobj, /* tp_init */ + PyType_GenericAlloc, /* tp_alloc */ + sock_new, /* tp_new */ + PyObject_Del, /* tp_free */ }; @@ -2955,15 +2955,15 @@ static PyObject * socket_gethostname(PyObject *self, PyObject *unused) { - char buf[1024]; - int res; - Py_BEGIN_ALLOW_THREADS - res = gethostname(buf, (int) sizeof buf - 1); - Py_END_ALLOW_THREADS - if (res < 0) - return set_error(); - buf[sizeof buf - 1] = '\0'; - return PyUnicode_FromString(buf); + char buf[1024]; + int res; + Py_BEGIN_ALLOW_THREADS + res = gethostname(buf, (int) sizeof buf - 1); + Py_END_ALLOW_THREADS + if (res < 0) + return set_error(); + buf[sizeof buf - 1] = '\0'; + return PyUnicode_FromString(buf); } PyDoc_STRVAR(gethostname_doc, @@ -2978,14 +2978,14 @@ static PyObject * socket_gethostbyname(PyObject *self, PyObject *args) { - char *name; - sock_addr_t addrbuf; + char *name; + sock_addr_t addrbuf; - if (!PyArg_ParseTuple(args, "s:gethostbyname", &name)) - return NULL; - if (setipaddr(name, SAS2SA(&addrbuf), sizeof(addrbuf), AF_INET) < 0) - return NULL; - return makeipaddr(SAS2SA(&addrbuf), sizeof(struct sockaddr_in)); + if (!PyArg_ParseTuple(args, "s:gethostbyname", &name)) + return NULL; + if (setipaddr(name, SAS2SA(&addrbuf), sizeof(addrbuf), AF_INET) < 0) + return NULL; + return makeipaddr(SAS2SA(&addrbuf), sizeof(struct sockaddr_in)); } PyDoc_STRVAR(gethostbyname_doc, @@ -2999,126 +2999,126 @@ static PyObject * gethost_common(struct hostent *h, struct sockaddr *addr, int alen, int af) { - char **pch; - PyObject *rtn_tuple = (PyObject *)NULL; - PyObject *name_list = (PyObject *)NULL; - PyObject *addr_list = (PyObject *)NULL; - PyObject *tmp; - - if (h == NULL) { - /* Let's get real error message to return */ - set_herror(h_errno); - return NULL; - } - - if (h->h_addrtype != af) { - /* Let's get real error message to return */ - PyErr_SetString(socket_error, - (char *)strerror(EAFNOSUPPORT)); - - return NULL; - } - - switch (af) { - - case AF_INET: - if (alen < sizeof(struct sockaddr_in)) - return NULL; - break; + char **pch; + PyObject *rtn_tuple = (PyObject *)NULL; + PyObject *name_list = (PyObject *)NULL; + PyObject *addr_list = (PyObject *)NULL; + PyObject *tmp; + + if (h == NULL) { + /* Let's get real error message to return */ + set_herror(h_errno); + return NULL; + } + + if (h->h_addrtype != af) { + /* Let's get real error message to return */ + PyErr_SetString(socket_error, + (char *)strerror(EAFNOSUPPORT)); + + return NULL; + } + + switch (af) { + + case AF_INET: + if (alen < sizeof(struct sockaddr_in)) + return NULL; + break; #ifdef ENABLE_IPV6 - case AF_INET6: - if (alen < sizeof(struct sockaddr_in6)) - return NULL; - break; -#endif - - } - - if ((name_list = PyList_New(0)) == NULL) - goto err; - - if ((addr_list = PyList_New(0)) == NULL) - goto err; - - /* SF #1511317: h_aliases can be NULL */ - if (h->h_aliases) { - for (pch = h->h_aliases; *pch != NULL; pch++) { - int status; - tmp = PyUnicode_FromString(*pch); - if (tmp == NULL) - goto err; - - status = PyList_Append(name_list, tmp); - Py_DECREF(tmp); - - if (status) - goto err; - } - } - - for (pch = h->h_addr_list; *pch != NULL; pch++) { - int status; - - switch (af) { - - case AF_INET: - { - struct sockaddr_in sin; - memset(&sin, 0, sizeof(sin)); - sin.sin_family = af; + case AF_INET6: + if (alen < sizeof(struct sockaddr_in6)) + return NULL; + break; +#endif + + } + + if ((name_list = PyList_New(0)) == NULL) + goto err; + + if ((addr_list = PyList_New(0)) == NULL) + goto err; + + /* SF #1511317: h_aliases can be NULL */ + if (h->h_aliases) { + for (pch = h->h_aliases; *pch != NULL; pch++) { + int status; + tmp = PyUnicode_FromString(*pch); + if (tmp == NULL) + goto err; + + status = PyList_Append(name_list, tmp); + Py_DECREF(tmp); + + if (status) + goto err; + } + } + + for (pch = h->h_addr_list; *pch != NULL; pch++) { + int status; + + switch (af) { + + case AF_INET: + { + struct sockaddr_in sin; + memset(&sin, 0, sizeof(sin)); + sin.sin_family = af; #ifdef HAVE_SOCKADDR_SA_LEN - sin.sin_len = sizeof(sin); + sin.sin_len = sizeof(sin); #endif - memcpy(&sin.sin_addr, *pch, sizeof(sin.sin_addr)); - tmp = makeipaddr((struct sockaddr *)&sin, sizeof(sin)); + memcpy(&sin.sin_addr, *pch, sizeof(sin.sin_addr)); + tmp = makeipaddr((struct sockaddr *)&sin, sizeof(sin)); - if (pch == h->h_addr_list && alen >= sizeof(sin)) - memcpy((char *) addr, &sin, sizeof(sin)); - break; - } + if (pch == h->h_addr_list && alen >= sizeof(sin)) + memcpy((char *) addr, &sin, sizeof(sin)); + break; + } #ifdef ENABLE_IPV6 - case AF_INET6: - { - struct sockaddr_in6 sin6; - memset(&sin6, 0, sizeof(sin6)); - sin6.sin6_family = af; + case AF_INET6: + { + struct sockaddr_in6 sin6; + memset(&sin6, 0, sizeof(sin6)); + sin6.sin6_family = af; #ifdef HAVE_SOCKADDR_SA_LEN - sin6.sin6_len = sizeof(sin6); + sin6.sin6_len = sizeof(sin6); #endif - memcpy(&sin6.sin6_addr, *pch, sizeof(sin6.sin6_addr)); - tmp = makeipaddr((struct sockaddr *)&sin6, - sizeof(sin6)); + memcpy(&sin6.sin6_addr, *pch, sizeof(sin6.sin6_addr)); + tmp = makeipaddr((struct sockaddr *)&sin6, + sizeof(sin6)); - if (pch == h->h_addr_list && alen >= sizeof(sin6)) - memcpy((char *) addr, &sin6, sizeof(sin6)); - break; - } + if (pch == h->h_addr_list && alen >= sizeof(sin6)) + memcpy((char *) addr, &sin6, sizeof(sin6)); + break; + } #endif - default: /* can't happen */ - PyErr_SetString(socket_error, - "unsupported address family"); - return NULL; - } + default: /* can't happen */ + PyErr_SetString(socket_error, + "unsupported address family"); + return NULL; + } - if (tmp == NULL) - goto err; + if (tmp == NULL) + goto err; - status = PyList_Append(addr_list, tmp); - Py_DECREF(tmp); + status = PyList_Append(addr_list, tmp); + Py_DECREF(tmp); - if (status) - goto err; - } + if (status) + goto err; + } - rtn_tuple = Py_BuildValue("sOO", h->h_name, name_list, addr_list); + rtn_tuple = Py_BuildValue("sOO", h->h_name, name_list, addr_list); err: - Py_XDECREF(name_list); - Py_XDECREF(addr_list); - return rtn_tuple; + Py_XDECREF(name_list); + Py_XDECREF(addr_list); + return rtn_tuple; } @@ -3128,63 +3128,63 @@ static PyObject * socket_gethostbyname_ex(PyObject *self, PyObject *args) { - char *name; - struct hostent *h; + char *name; + struct hostent *h; #ifdef ENABLE_IPV6 - struct sockaddr_storage addr; + struct sockaddr_storage addr; #else - struct sockaddr_in addr; + struct sockaddr_in addr; #endif - struct sockaddr *sa; - PyObject *ret; + struct sockaddr *sa; + PyObject *ret; #ifdef HAVE_GETHOSTBYNAME_R - struct hostent hp_allocated; + struct hostent hp_allocated; #ifdef HAVE_GETHOSTBYNAME_R_3_ARG - struct hostent_data data; + struct hostent_data data; #else - char buf[16384]; - int buf_len = (sizeof buf) - 1; - int errnop; + char buf[16384]; + int buf_len = (sizeof buf) - 1; + int errnop; #endif #if defined(HAVE_GETHOSTBYNAME_R_3_ARG) || defined(HAVE_GETHOSTBYNAME_R_6_ARG) - int result; + int result; #endif #endif /* HAVE_GETHOSTBYNAME_R */ - if (!PyArg_ParseTuple(args, "s:gethostbyname_ex", &name)) - return NULL; - if (setipaddr(name, (struct sockaddr *)&addr, sizeof(addr), AF_INET) < 0) - return NULL; - Py_BEGIN_ALLOW_THREADS + if (!PyArg_ParseTuple(args, "s:gethostbyname_ex", &name)) + return NULL; + if (setipaddr(name, (struct sockaddr *)&addr, sizeof(addr), AF_INET) < 0) + return NULL; + Py_BEGIN_ALLOW_THREADS #ifdef HAVE_GETHOSTBYNAME_R #if defined(HAVE_GETHOSTBYNAME_R_6_ARG) - result = gethostbyname_r(name, &hp_allocated, buf, buf_len, - &h, &errnop); + result = gethostbyname_r(name, &hp_allocated, buf, buf_len, + &h, &errnop); #elif defined(HAVE_GETHOSTBYNAME_R_5_ARG) - h = gethostbyname_r(name, &hp_allocated, buf, buf_len, &errnop); + h = gethostbyname_r(name, &hp_allocated, buf, buf_len, &errnop); #else /* HAVE_GETHOSTBYNAME_R_3_ARG */ - memset((void *) &data, '\0', sizeof(data)); - result = gethostbyname_r(name, &hp_allocated, &data); - h = (result != 0) ? NULL : &hp_allocated; + memset((void *) &data, '\0', sizeof(data)); + result = gethostbyname_r(name, &hp_allocated, &data); + h = (result != 0) ? NULL : &hp_allocated; #endif #else /* not HAVE_GETHOSTBYNAME_R */ #ifdef USE_GETHOSTBYNAME_LOCK - PyThread_acquire_lock(netdb_lock, 1); + PyThread_acquire_lock(netdb_lock, 1); #endif - h = gethostbyname(name); + h = gethostbyname(name); #endif /* HAVE_GETHOSTBYNAME_R */ - Py_END_ALLOW_THREADS - /* Some C libraries would require addr.__ss_family instead of - addr.ss_family. - Therefore, we cast the sockaddr_storage into sockaddr to - access sa_family. */ - sa = (struct sockaddr*)&addr; - ret = gethost_common(h, (struct sockaddr *)&addr, sizeof(addr), - sa->sa_family); + Py_END_ALLOW_THREADS + /* Some C libraries would require addr.__ss_family instead of + addr.ss_family. + Therefore, we cast the sockaddr_storage into sockaddr to + access sa_family. */ + sa = (struct sockaddr*)&addr; + ret = gethost_common(h, (struct sockaddr *)&addr, sizeof(addr), + sa->sa_family); #ifdef USE_GETHOSTBYNAME_LOCK - PyThread_release_lock(netdb_lock); + PyThread_release_lock(netdb_lock); #endif - return ret; + return ret; } PyDoc_STRVAR(ghbn_ex_doc, @@ -3201,84 +3201,84 @@ socket_gethostbyaddr(PyObject *self, PyObject *args) { #ifdef ENABLE_IPV6 - struct sockaddr_storage addr; + struct sockaddr_storage addr; #else - struct sockaddr_in addr; + struct sockaddr_in addr; #endif - struct sockaddr *sa = (struct sockaddr *)&addr; - char *ip_num; - struct hostent *h; - PyObject *ret; + struct sockaddr *sa = (struct sockaddr *)&addr; + char *ip_num; + struct hostent *h; + PyObject *ret; #ifdef HAVE_GETHOSTBYNAME_R - struct hostent hp_allocated; + struct hostent hp_allocated; #ifdef HAVE_GETHOSTBYNAME_R_3_ARG - struct hostent_data data; + struct hostent_data data; #else - /* glibcs up to 2.10 assume that the buf argument to - gethostbyaddr_r is 8-byte aligned, which at least llvm-gcc - does not ensure. The attribute below instructs the compiler - to maintain this alignment. */ - char buf[16384] Py_ALIGNED(8); - int buf_len = (sizeof buf) - 1; - int errnop; + /* glibcs up to 2.10 assume that the buf argument to + gethostbyaddr_r is 8-byte aligned, which at least llvm-gcc + does not ensure. The attribute below instructs the compiler + to maintain this alignment. */ + char buf[16384] Py_ALIGNED(8); + int buf_len = (sizeof buf) - 1; + int errnop; #endif #if defined(HAVE_GETHOSTBYNAME_R_3_ARG) || defined(HAVE_GETHOSTBYNAME_R_6_ARG) - int result; + int result; #endif #endif /* HAVE_GETHOSTBYNAME_R */ - char *ap; - int al; - int af; - - if (!PyArg_ParseTuple(args, "s:gethostbyaddr", &ip_num)) - return NULL; - af = AF_UNSPEC; - if (setipaddr(ip_num, sa, sizeof(addr), af) < 0) - return NULL; - af = sa->sa_family; - ap = NULL; - al = 0; - switch (af) { - case AF_INET: - ap = (char *)&((struct sockaddr_in *)sa)->sin_addr; - al = sizeof(((struct sockaddr_in *)sa)->sin_addr); - break; + char *ap; + int al; + int af; + + if (!PyArg_ParseTuple(args, "s:gethostbyaddr", &ip_num)) + return NULL; + af = AF_UNSPEC; + if (setipaddr(ip_num, sa, sizeof(addr), af) < 0) + return NULL; + af = sa->sa_family; + ap = NULL; + al = 0; + switch (af) { + case AF_INET: + ap = (char *)&((struct sockaddr_in *)sa)->sin_addr; + al = sizeof(((struct sockaddr_in *)sa)->sin_addr); + break; #ifdef ENABLE_IPV6 - case AF_INET6: - ap = (char *)&((struct sockaddr_in6 *)sa)->sin6_addr; - al = sizeof(((struct sockaddr_in6 *)sa)->sin6_addr); - break; -#endif - default: - PyErr_SetString(socket_error, "unsupported address family"); - return NULL; - } - Py_BEGIN_ALLOW_THREADS + case AF_INET6: + ap = (char *)&((struct sockaddr_in6 *)sa)->sin6_addr; + al = sizeof(((struct sockaddr_in6 *)sa)->sin6_addr); + break; +#endif + default: + PyErr_SetString(socket_error, "unsupported address family"); + return NULL; + } + Py_BEGIN_ALLOW_THREADS #ifdef HAVE_GETHOSTBYNAME_R #if defined(HAVE_GETHOSTBYNAME_R_6_ARG) - result = gethostbyaddr_r(ap, al, af, - &hp_allocated, buf, buf_len, - &h, &errnop); + result = gethostbyaddr_r(ap, al, af, + &hp_allocated, buf, buf_len, + &h, &errnop); #elif defined(HAVE_GETHOSTBYNAME_R_5_ARG) - h = gethostbyaddr_r(ap, al, af, - &hp_allocated, buf, buf_len, &errnop); + h = gethostbyaddr_r(ap, al, af, + &hp_allocated, buf, buf_len, &errnop); #else /* HAVE_GETHOSTBYNAME_R_3_ARG */ - memset((void *) &data, '\0', sizeof(data)); - result = gethostbyaddr_r(ap, al, af, &hp_allocated, &data); - h = (result != 0) ? NULL : &hp_allocated; + memset((void *) &data, '\0', sizeof(data)); + result = gethostbyaddr_r(ap, al, af, &hp_allocated, &data); + h = (result != 0) ? NULL : &hp_allocated; #endif #else /* not HAVE_GETHOSTBYNAME_R */ #ifdef USE_GETHOSTBYNAME_LOCK - PyThread_acquire_lock(netdb_lock, 1); + PyThread_acquire_lock(netdb_lock, 1); #endif - h = gethostbyaddr(ap, al, af); + h = gethostbyaddr(ap, al, af); #endif /* HAVE_GETHOSTBYNAME_R */ - Py_END_ALLOW_THREADS - ret = gethost_common(h, (struct sockaddr *)&addr, sizeof(addr), af); + Py_END_ALLOW_THREADS + ret = gethost_common(h, (struct sockaddr *)&addr, sizeof(addr), af); #ifdef USE_GETHOSTBYNAME_LOCK - PyThread_release_lock(netdb_lock); + PyThread_release_lock(netdb_lock); #endif - return ret; + return ret; } PyDoc_STRVAR(gethostbyaddr_doc, @@ -3296,18 +3296,18 @@ static PyObject * socket_getservbyname(PyObject *self, PyObject *args) { - char *name, *proto=NULL; - struct servent *sp; - if (!PyArg_ParseTuple(args, "s|s:getservbyname", &name, &proto)) - return NULL; - Py_BEGIN_ALLOW_THREADS - sp = getservbyname(name, proto); - Py_END_ALLOW_THREADS - if (sp == NULL) { - PyErr_SetString(socket_error, "service/proto not found"); - return NULL; - } - return PyLong_FromLong((long) ntohs(sp->s_port)); + char *name, *proto=NULL; + struct servent *sp; + if (!PyArg_ParseTuple(args, "s|s:getservbyname", &name, &proto)) + return NULL; + Py_BEGIN_ALLOW_THREADS + sp = getservbyname(name, proto); + Py_END_ALLOW_THREADS + if (sp == NULL) { + PyErr_SetString(socket_error, "service/proto not found"); + return NULL; + } + return PyLong_FromLong((long) ntohs(sp->s_port)); } PyDoc_STRVAR(getservbyname_doc, @@ -3326,25 +3326,25 @@ static PyObject * socket_getservbyport(PyObject *self, PyObject *args) { - int port; - char *proto=NULL; - struct servent *sp; - if (!PyArg_ParseTuple(args, "i|s:getservbyport", &port, &proto)) - return NULL; - if (port < 0 || port > 0xffff) { - PyErr_SetString( - PyExc_OverflowError, - "getservbyport: port must be 0-65535."); - return NULL; - } - Py_BEGIN_ALLOW_THREADS - sp = getservbyport(htons((short)port), proto); - Py_END_ALLOW_THREADS - if (sp == NULL) { - PyErr_SetString(socket_error, "port/proto not found"); - return NULL; - } - return PyUnicode_FromString(sp->s_name); + int port; + char *proto=NULL; + struct servent *sp; + if (!PyArg_ParseTuple(args, "i|s:getservbyport", &port, &proto)) + return NULL; + if (port < 0 || port > 0xffff) { + PyErr_SetString( + PyExc_OverflowError, + "getservbyport: port must be 0-65535."); + return NULL; + } + Py_BEGIN_ALLOW_THREADS + sp = getservbyport(htons((short)port), proto); + Py_END_ALLOW_THREADS + if (sp == NULL) { + PyErr_SetString(socket_error, "port/proto not found"); + return NULL; + } + return PyUnicode_FromString(sp->s_name); } PyDoc_STRVAR(getservbyport_doc, @@ -3362,18 +3362,18 @@ static PyObject * socket_getprotobyname(PyObject *self, PyObject *args) { - char *name; - struct protoent *sp; - if (!PyArg_ParseTuple(args, "s:getprotobyname", &name)) - return NULL; - Py_BEGIN_ALLOW_THREADS - sp = getprotobyname(name); - Py_END_ALLOW_THREADS - if (sp == NULL) { - PyErr_SetString(socket_error, "protocol not found"); - return NULL; - } - return PyLong_FromLong((long) sp->p_proto); + char *name; + struct protoent *sp; + if (!PyArg_ParseTuple(args, "s:getprotobyname", &name)) + return NULL; + Py_BEGIN_ALLOW_THREADS + sp = getprotobyname(name); + Py_END_ALLOW_THREADS + if (sp == NULL) { + PyErr_SetString(socket_error, "protocol not found"); + return NULL; + } + return PyLong_FromLong((long) sp->p_proto); } PyDoc_STRVAR(getprotobyname_doc, @@ -3388,22 +3388,22 @@ static PyObject * socket_dup(PyObject *self, PyObject *fdobj) { - SOCKET_T fd, newfd; - PyObject *newfdobj; + SOCKET_T fd, newfd; + PyObject *newfdobj; - fd = PyLong_AsSocket_t(fdobj); - if (fd == (SOCKET_T)(-1) && PyErr_Occurred()) - return NULL; - - newfd = dup_socket(fd); - if (newfd == INVALID_SOCKET) - return set_error(); - - newfdobj = PyLong_FromSocket_t(newfd); - if (newfdobj == NULL) - SOCKETCLOSE(newfd); - return newfdobj; + fd = PyLong_AsSocket_t(fdobj); + if (fd == (SOCKET_T)(-1) && PyErr_Occurred()) + return NULL; + + newfd = dup_socket(fd); + if (newfd == INVALID_SOCKET) + return set_error(); + + newfdobj = PyLong_FromSocket_t(newfd); + if (newfdobj == NULL) + SOCKETCLOSE(newfd); + return newfdobj; } PyDoc_STRVAR(dup_doc, @@ -3423,40 +3423,40 @@ static PyObject * socket_socketpair(PyObject *self, PyObject *args) { - PySocketSockObject *s0 = NULL, *s1 = NULL; - SOCKET_T sv[2]; - int family, type = SOCK_STREAM, proto = 0; - PyObject *res = NULL; + PySocketSockObject *s0 = NULL, *s1 = NULL; + SOCKET_T sv[2]; + int family, type = SOCK_STREAM, proto = 0; + PyObject *res = NULL; #if defined(AF_UNIX) - family = AF_UNIX; + family = AF_UNIX; #else - family = AF_INET; + family = AF_INET; #endif - if (!PyArg_ParseTuple(args, "|iii:socketpair", - &family, &type, &proto)) - return NULL; - /* Create a pair of socket fds */ - if (socketpair(family, type, proto, sv) < 0) - return set_error(); - s0 = new_sockobject(sv[0], family, type, proto); - if (s0 == NULL) - goto finally; - s1 = new_sockobject(sv[1], family, type, proto); - if (s1 == NULL) - goto finally; - res = PyTuple_Pack(2, s0, s1); + if (!PyArg_ParseTuple(args, "|iii:socketpair", + &family, &type, &proto)) + return NULL; + /* Create a pair of socket fds */ + if (socketpair(family, type, proto, sv) < 0) + return set_error(); + s0 = new_sockobject(sv[0], family, type, proto); + if (s0 == NULL) + goto finally; + s1 = new_sockobject(sv[1], family, type, proto); + if (s1 == NULL) + goto finally; + res = PyTuple_Pack(2, s0, s1); finally: - if (res == NULL) { - if (s0 == NULL) - SOCKETCLOSE(sv[0]); - if (s1 == NULL) - SOCKETCLOSE(sv[1]); - } - Py_XDECREF(s0); - Py_XDECREF(s1); - return res; + if (res == NULL) { + if (s0 == NULL) + SOCKETCLOSE(sv[0]); + if (s1 == NULL) + SOCKETCLOSE(sv[1]); + } + Py_XDECREF(s0); + Py_XDECREF(s1); + return res; } PyDoc_STRVAR(socketpair_doc, @@ -3473,18 +3473,18 @@ static PyObject * socket_ntohs(PyObject *self, PyObject *args) { - int x1, x2; + int x1, x2; - if (!PyArg_ParseTuple(args, "i:ntohs", &x1)) { - return NULL; - } - if (x1 < 0) { - PyErr_SetString(PyExc_OverflowError, - "can't convert negative number to unsigned long"); - return NULL; - } - x2 = (unsigned int)ntohs((unsigned short)x1); - return PyLong_FromLong(x2); + if (!PyArg_ParseTuple(args, "i:ntohs", &x1)) { + return NULL; + } + if (x1 < 0) { + PyErr_SetString(PyExc_OverflowError, + "can't convert negative number to unsigned long"); + return NULL; + } + x2 = (unsigned int)ntohs((unsigned short)x1); + return PyLong_FromLong(x2); } PyDoc_STRVAR(ntohs_doc, @@ -3496,31 +3496,31 @@ static PyObject * socket_ntohl(PyObject *self, PyObject *arg) { - unsigned long x; + unsigned long x; - if (PyLong_Check(arg)) { - x = PyLong_AsUnsignedLong(arg); - if (x == (unsigned long) -1 && PyErr_Occurred()) - return NULL; + if (PyLong_Check(arg)) { + x = PyLong_AsUnsignedLong(arg); + if (x == (unsigned long) -1 && PyErr_Occurred()) + return NULL; #if SIZEOF_LONG > 4 - { - unsigned long y; - /* only want the trailing 32 bits */ - y = x & 0xFFFFFFFFUL; - if (y ^ x) - return PyErr_Format(PyExc_OverflowError, - "long int larger than 32 bits"); - x = y; - } -#endif - } - else - return PyErr_Format(PyExc_TypeError, - "expected int/long, %s found", - Py_TYPE(arg)->tp_name); - if (x == (unsigned long) -1 && PyErr_Occurred()) - return NULL; - return PyLong_FromUnsignedLong(ntohl(x)); + { + unsigned long y; + /* only want the trailing 32 bits */ + y = x & 0xFFFFFFFFUL; + if (y ^ x) + return PyErr_Format(PyExc_OverflowError, + "long int larger than 32 bits"); + x = y; + } +#endif + } + else + return PyErr_Format(PyExc_TypeError, + "expected int/long, %s found", + Py_TYPE(arg)->tp_name); + if (x == (unsigned long) -1 && PyErr_Occurred()) + return NULL; + return PyLong_FromUnsignedLong(ntohl(x)); } PyDoc_STRVAR(ntohl_doc, @@ -3532,18 +3532,18 @@ static PyObject * socket_htons(PyObject *self, PyObject *args) { - int x1, x2; + int x1, x2; - if (!PyArg_ParseTuple(args, "i:htons", &x1)) { - return NULL; - } - if (x1 < 0) { - PyErr_SetString(PyExc_OverflowError, - "can't convert negative number to unsigned long"); - return NULL; - } - x2 = (unsigned int)htons((unsigned short)x1); - return PyLong_FromLong(x2); + if (!PyArg_ParseTuple(args, "i:htons", &x1)) { + return NULL; + } + if (x1 < 0) { + PyErr_SetString(PyExc_OverflowError, + "can't convert negative number to unsigned long"); + return NULL; + } + x2 = (unsigned int)htons((unsigned short)x1); + return PyLong_FromLong(x2); } PyDoc_STRVAR(htons_doc, @@ -3555,29 +3555,29 @@ static PyObject * socket_htonl(PyObject *self, PyObject *arg) { - unsigned long x; + unsigned long x; - if (PyLong_Check(arg)) { - x = PyLong_AsUnsignedLong(arg); - if (x == (unsigned long) -1 && PyErr_Occurred()) - return NULL; + if (PyLong_Check(arg)) { + x = PyLong_AsUnsignedLong(arg); + if (x == (unsigned long) -1 && PyErr_Occurred()) + return NULL; #if SIZEOF_LONG > 4 - { - unsigned long y; - /* only want the trailing 32 bits */ - y = x & 0xFFFFFFFFUL; - if (y ^ x) - return PyErr_Format(PyExc_OverflowError, - "long int larger than 32 bits"); - x = y; - } -#endif - } - else - return PyErr_Format(PyExc_TypeError, - "expected int/long, %s found", - Py_TYPE(arg)->tp_name); - return PyLong_FromUnsignedLong(htonl((unsigned long)x)); + { + unsigned long y; + /* only want the trailing 32 bits */ + y = x & 0xFFFFFFFFUL; + if (y ^ x) + return PyErr_Format(PyExc_OverflowError, + "long int larger than 32 bits"); + x = y; + } +#endif + } + else + return PyErr_Format(PyExc_TypeError, + "expected int/long, %s found", + Py_TYPE(arg)->tp_name); + return PyLong_FromUnsignedLong(htonl((unsigned long)x)); } PyDoc_STRVAR(htonl_doc, @@ -3600,20 +3600,20 @@ #define INADDR_NONE (-1) #endif #ifdef HAVE_INET_ATON - struct in_addr buf; + struct in_addr buf; #endif #if !defined(HAVE_INET_ATON) || defined(USE_INET_ATON_WEAKLINK) #if (SIZEOF_INT != 4) #error "Not sure if in_addr_t exists and int is not 32-bits." #endif - /* Have to use inet_addr() instead */ - unsigned int packed_addr; + /* Have to use inet_addr() instead */ + unsigned int packed_addr; #endif - char *ip_addr; + char *ip_addr; - if (!PyArg_ParseTuple(args, "s:inet_aton", &ip_addr)) - return NULL; + if (!PyArg_ParseTuple(args, "s:inet_aton", &ip_addr)) + return NULL; #ifdef HAVE_INET_ATON @@ -3621,13 +3621,13 @@ #ifdef USE_INET_ATON_WEAKLINK if (inet_aton != NULL) { #endif - if (inet_aton(ip_addr, &buf)) - return PyBytes_FromStringAndSize((char *)(&buf), - sizeof(buf)); - - PyErr_SetString(socket_error, - "illegal IP address string passed to inet_aton"); - return NULL; + if (inet_aton(ip_addr, &buf)) + return PyBytes_FromStringAndSize((char *)(&buf), + sizeof(buf)); + + PyErr_SetString(socket_error, + "illegal IP address string passed to inet_aton"); + return NULL; #ifdef USE_INET_ATON_WEAKLINK } else { @@ -3637,22 +3637,22 @@ #if !defined(HAVE_INET_ATON) || defined(USE_INET_ATON_WEAKLINK) - /* special-case this address as inet_addr might return INADDR_NONE - * for this */ - if (strcmp(ip_addr, "255.255.255.255") == 0) { - packed_addr = 0xFFFFFFFF; - } else { - - packed_addr = inet_addr(ip_addr); - - if (packed_addr == INADDR_NONE) { /* invalid address */ - PyErr_SetString(socket_error, - "illegal IP address string passed to inet_aton"); - return NULL; - } - } - return PyBytes_FromStringAndSize((char *) &packed_addr, - sizeof(packed_addr)); + /* special-case this address as inet_addr might return INADDR_NONE + * for this */ + if (strcmp(ip_addr, "255.255.255.255") == 0) { + packed_addr = 0xFFFFFFFF; + } else { + + packed_addr = inet_addr(ip_addr); + + if (packed_addr == INADDR_NONE) { /* invalid address */ + PyErr_SetString(socket_error, + "illegal IP address string passed to inet_aton"); + return NULL; + } + } + return PyBytes_FromStringAndSize((char *) &packed_addr, + sizeof(packed_addr)); #ifdef USE_INET_ATON_WEAKLINK } @@ -3669,23 +3669,23 @@ static PyObject* socket_inet_ntoa(PyObject *self, PyObject *args) { - char *packed_str; - int addr_len; - struct in_addr packed_addr; - - if (!PyArg_ParseTuple(args, "y#:inet_ntoa", &packed_str, &addr_len)) { - return NULL; - } - - if (addr_len != sizeof(packed_addr)) { - PyErr_SetString(socket_error, - "packed IP wrong length for inet_ntoa"); - return NULL; - } + char *packed_str; + int addr_len; + struct in_addr packed_addr; + + if (!PyArg_ParseTuple(args, "y#:inet_ntoa", &packed_str, &addr_len)) { + return NULL; + } + + if (addr_len != sizeof(packed_addr)) { + PyErr_SetString(socket_error, + "packed IP wrong length for inet_ntoa"); + return NULL; + } - memcpy(&packed_addr, packed_str, addr_len); + memcpy(&packed_addr, packed_str, addr_len); - return PyUnicode_FromString(inet_ntoa(packed_addr)); + return PyUnicode_FromString(inet_ntoa(packed_addr)); } #ifdef HAVE_INET_PTON @@ -3699,46 +3699,46 @@ static PyObject * socket_inet_pton(PyObject *self, PyObject *args) { - int af; - char* ip; - int retval; + int af; + char* ip; + int retval; #ifdef ENABLE_IPV6 - char packed[MAX(sizeof(struct in_addr), sizeof(struct in6_addr))]; + char packed[MAX(sizeof(struct in_addr), sizeof(struct in6_addr))]; #else - char packed[sizeof(struct in_addr)]; + char packed[sizeof(struct in_addr)]; #endif - if (!PyArg_ParseTuple(args, "is:inet_pton", &af, &ip)) { - return NULL; - } + if (!PyArg_ParseTuple(args, "is:inet_pton", &af, &ip)) { + return NULL; + } #if !defined(ENABLE_IPV6) && defined(AF_INET6) - if(af == AF_INET6) { - PyErr_SetString(socket_error, - "can't use AF_INET6, IPv6 is disabled"); - return NULL; - } -#endif - - retval = inet_pton(af, ip, packed); - if (retval < 0) { - PyErr_SetFromErrno(socket_error); - return NULL; - } else if (retval == 0) { - PyErr_SetString(socket_error, - "illegal IP address string passed to inet_pton"); - return NULL; - } else if (af == AF_INET) { - return PyBytes_FromStringAndSize(packed, - sizeof(struct in_addr)); + if(af == AF_INET6) { + PyErr_SetString(socket_error, + "can't use AF_INET6, IPv6 is disabled"); + return NULL; + } +#endif + + retval = inet_pton(af, ip, packed); + if (retval < 0) { + PyErr_SetFromErrno(socket_error); + return NULL; + } else if (retval == 0) { + PyErr_SetString(socket_error, + "illegal IP address string passed to inet_pton"); + return NULL; + } else if (af == AF_INET) { + return PyBytes_FromStringAndSize(packed, + sizeof(struct in_addr)); #ifdef ENABLE_IPV6 - } else if (af == AF_INET6) { - return PyBytes_FromStringAndSize(packed, - sizeof(struct in6_addr)); -#endif - } else { - PyErr_SetString(socket_error, "unknown address family"); - return NULL; - } + } else if (af == AF_INET6) { + return PyBytes_FromStringAndSize(packed, + sizeof(struct in6_addr)); +#endif + } else { + PyErr_SetString(socket_error, "unknown address family"); + return NULL; + } } PyDoc_STRVAR(inet_ntop_doc, @@ -3749,54 +3749,54 @@ static PyObject * socket_inet_ntop(PyObject *self, PyObject *args) { - int af; - char* packed; - int len; - const char* retval; + int af; + char* packed; + int len; + const char* retval; #ifdef ENABLE_IPV6 - char ip[MAX(INET_ADDRSTRLEN, INET6_ADDRSTRLEN) + 1]; + char ip[MAX(INET_ADDRSTRLEN, INET6_ADDRSTRLEN) + 1]; #else - char ip[INET_ADDRSTRLEN + 1]; + char ip[INET_ADDRSTRLEN + 1]; #endif - /* Guarantee NUL-termination for PyUnicode_FromString() below */ - memset((void *) &ip[0], '\0', sizeof(ip)); + /* Guarantee NUL-termination for PyUnicode_FromString() below */ + memset((void *) &ip[0], '\0', sizeof(ip)); - if (!PyArg_ParseTuple(args, "iy#:inet_ntop", &af, &packed, &len)) { - return NULL; - } + if (!PyArg_ParseTuple(args, "iy#:inet_ntop", &af, &packed, &len)) { + return NULL; + } - if (af == AF_INET) { - if (len != sizeof(struct in_addr)) { - PyErr_SetString(PyExc_ValueError, - "invalid length of packed IP address string"); - return NULL; - } + if (af == AF_INET) { + if (len != sizeof(struct in_addr)) { + PyErr_SetString(PyExc_ValueError, + "invalid length of packed IP address string"); + return NULL; + } #ifdef ENABLE_IPV6 - } else if (af == AF_INET6) { - if (len != sizeof(struct in6_addr)) { - PyErr_SetString(PyExc_ValueError, - "invalid length of packed IP address string"); - return NULL; - } -#endif - } else { - PyErr_Format(PyExc_ValueError, - "unknown address family %d", af); - return NULL; - } - - retval = inet_ntop(af, packed, ip, sizeof(ip)); - if (!retval) { - PyErr_SetFromErrno(socket_error); - return NULL; - } else { - return PyUnicode_FromString(retval); - } - - /* NOTREACHED */ - PyErr_SetString(PyExc_RuntimeError, "invalid handling of inet_ntop"); - return NULL; + } else if (af == AF_INET6) { + if (len != sizeof(struct in6_addr)) { + PyErr_SetString(PyExc_ValueError, + "invalid length of packed IP address string"); + return NULL; + } +#endif + } else { + PyErr_Format(PyExc_ValueError, + "unknown address family %d", af); + return NULL; + } + + retval = inet_ntop(af, packed, ip, sizeof(ip)); + if (!retval) { + PyErr_SetFromErrno(socket_error); + return NULL; + } else { + return PyUnicode_FromString(retval); + } + + /* NOTREACHED */ + PyErr_SetString(PyExc_RuntimeError, "invalid handling of inet_ntop"); + return NULL; } #endif /* HAVE_INET_PTON */ @@ -3807,100 +3807,100 @@ static PyObject * socket_getaddrinfo(PyObject *self, PyObject *args) { - struct addrinfo hints, *res; - struct addrinfo *res0 = NULL; - PyObject *hobj = NULL; - PyObject *pobj = (PyObject *)NULL; - char pbuf[30]; - char *hptr, *pptr; - int family, socktype, protocol, flags; - int error; - PyObject *all = (PyObject *)NULL; - PyObject *idna = NULL; - - family = socktype = protocol = flags = 0; - family = AF_UNSPEC; - if (!PyArg_ParseTuple(args, "OO|iiii:getaddrinfo", - &hobj, &pobj, &family, &socktype, - &protocol, &flags)) { - return NULL; - } - if (hobj == Py_None) { - hptr = NULL; - } else if (PyUnicode_Check(hobj)) { - idna = PyObject_CallMethod(hobj, "encode", "s", "idna"); - if (!idna) - return NULL; - assert(PyBytes_Check(idna)); - hptr = PyBytes_AS_STRING(idna); - } else if (PyBytes_Check(hobj)) { - hptr = PyBytes_AsString(hobj); - } else { - PyErr_SetString(PyExc_TypeError, - "getaddrinfo() argument 1 must be string or None"); - return NULL; - } - if (PyLong_CheckExact(pobj)) { - long value = PyLong_AsLong(pobj); - if (value == -1 && PyErr_Occurred()) - goto err; - PyOS_snprintf(pbuf, sizeof(pbuf), "%ld", value); - pptr = pbuf; - } else if (PyUnicode_Check(pobj)) { - pptr = _PyUnicode_AsString(pobj); - } else if (PyBytes_Check(pobj)) { - pptr = PyBytes_AsString(pobj); - } else if (pobj == Py_None) { - pptr = (char *)NULL; - } else { - PyErr_SetString(socket_error, "Int or String expected"); - goto err; - } - memset(&hints, 0, sizeof(hints)); - hints.ai_family = family; - hints.ai_socktype = socktype; - hints.ai_protocol = protocol; - hints.ai_flags = flags; - Py_BEGIN_ALLOW_THREADS - ACQUIRE_GETADDRINFO_LOCK - error = getaddrinfo(hptr, pptr, &hints, &res0); - Py_END_ALLOW_THREADS - RELEASE_GETADDRINFO_LOCK /* see comment in setipaddr() */ - if (error) { - set_gaierror(error); - goto err; - } - - if ((all = PyList_New(0)) == NULL) - goto err; - for (res = res0; res; res = res->ai_next) { - PyObject *single; - PyObject *addr = - makesockaddr(-1, res->ai_addr, res->ai_addrlen, protocol); - if (addr == NULL) - goto err; - single = Py_BuildValue("iiisO", res->ai_family, - res->ai_socktype, res->ai_protocol, - res->ai_canonname ? res->ai_canonname : "", - addr); - Py_DECREF(addr); - if (single == NULL) - goto err; - - if (PyList_Append(all, single)) - goto err; - Py_XDECREF(single); - } - Py_XDECREF(idna); - if (res0) - freeaddrinfo(res0); - return all; + struct addrinfo hints, *res; + struct addrinfo *res0 = NULL; + PyObject *hobj = NULL; + PyObject *pobj = (PyObject *)NULL; + char pbuf[30]; + char *hptr, *pptr; + int family, socktype, protocol, flags; + int error; + PyObject *all = (PyObject *)NULL; + PyObject *idna = NULL; + + family = socktype = protocol = flags = 0; + family = AF_UNSPEC; + if (!PyArg_ParseTuple(args, "OO|iiii:getaddrinfo", + &hobj, &pobj, &family, &socktype, + &protocol, &flags)) { + return NULL; + } + if (hobj == Py_None) { + hptr = NULL; + } else if (PyUnicode_Check(hobj)) { + idna = PyObject_CallMethod(hobj, "encode", "s", "idna"); + if (!idna) + return NULL; + assert(PyBytes_Check(idna)); + hptr = PyBytes_AS_STRING(idna); + } else if (PyBytes_Check(hobj)) { + hptr = PyBytes_AsString(hobj); + } else { + PyErr_SetString(PyExc_TypeError, + "getaddrinfo() argument 1 must be string or None"); + return NULL; + } + if (PyLong_CheckExact(pobj)) { + long value = PyLong_AsLong(pobj); + if (value == -1 && PyErr_Occurred()) + goto err; + PyOS_snprintf(pbuf, sizeof(pbuf), "%ld", value); + pptr = pbuf; + } else if (PyUnicode_Check(pobj)) { + pptr = _PyUnicode_AsString(pobj); + } else if (PyBytes_Check(pobj)) { + pptr = PyBytes_AsString(pobj); + } else if (pobj == Py_None) { + pptr = (char *)NULL; + } else { + PyErr_SetString(socket_error, "Int or String expected"); + goto err; + } + memset(&hints, 0, sizeof(hints)); + hints.ai_family = family; + hints.ai_socktype = socktype; + hints.ai_protocol = protocol; + hints.ai_flags = flags; + Py_BEGIN_ALLOW_THREADS + ACQUIRE_GETADDRINFO_LOCK + error = getaddrinfo(hptr, pptr, &hints, &res0); + Py_END_ALLOW_THREADS + RELEASE_GETADDRINFO_LOCK /* see comment in setipaddr() */ + if (error) { + set_gaierror(error); + goto err; + } + + if ((all = PyList_New(0)) == NULL) + goto err; + for (res = res0; res; res = res->ai_next) { + PyObject *single; + PyObject *addr = + makesockaddr(-1, res->ai_addr, res->ai_addrlen, protocol); + if (addr == NULL) + goto err; + single = Py_BuildValue("iiisO", res->ai_family, + res->ai_socktype, res->ai_protocol, + res->ai_canonname ? res->ai_canonname : "", + addr); + Py_DECREF(addr); + if (single == NULL) + goto err; + + if (PyList_Append(all, single)) + goto err; + Py_XDECREF(single); + } + Py_XDECREF(idna); + if (res0) + freeaddrinfo(res0); + return all; err: - Py_XDECREF(all); - Py_XDECREF(idna); - if (res0) - freeaddrinfo(res0); - return (PyObject *)NULL; + Py_XDECREF(all); + Py_XDECREF(idna); + if (res0) + freeaddrinfo(res0); + return (PyObject *)NULL; } PyDoc_STRVAR(getaddrinfo_doc, @@ -3915,77 +3915,77 @@ static PyObject * socket_getnameinfo(PyObject *self, PyObject *args) { - PyObject *sa = (PyObject *)NULL; - int flags; - char *hostp; - int port, flowinfo, scope_id; - char hbuf[NI_MAXHOST], pbuf[NI_MAXSERV]; - struct addrinfo hints, *res = NULL; - int error; - PyObject *ret = (PyObject *)NULL; - - flags = flowinfo = scope_id = 0; - if (!PyArg_ParseTuple(args, "Oi:getnameinfo", &sa, &flags)) - return NULL; - if (!PyTuple_Check(sa)) { - PyErr_SetString(PyExc_TypeError, - "getnameinfo() argument 1 must be a tuple"); - return NULL; - } - if (!PyArg_ParseTuple(sa, "si|ii", - &hostp, &port, &flowinfo, &scope_id)) - return NULL; - PyOS_snprintf(pbuf, sizeof(pbuf), "%d", port); - memset(&hints, 0, sizeof(hints)); - hints.ai_family = AF_UNSPEC; - hints.ai_socktype = SOCK_DGRAM; /* make numeric port happy */ - Py_BEGIN_ALLOW_THREADS - ACQUIRE_GETADDRINFO_LOCK - error = getaddrinfo(hostp, pbuf, &hints, &res); - Py_END_ALLOW_THREADS - RELEASE_GETADDRINFO_LOCK /* see comment in setipaddr() */ - if (error) { - set_gaierror(error); - goto fail; - } - if (res->ai_next) { - PyErr_SetString(socket_error, - "sockaddr resolved to multiple addresses"); - goto fail; - } - switch (res->ai_family) { - case AF_INET: - { - if (PyTuple_GET_SIZE(sa) != 2) { - PyErr_SetString(socket_error, - "IPv4 sockaddr must be 2 tuple"); - goto fail; - } - break; - } + PyObject *sa = (PyObject *)NULL; + int flags; + char *hostp; + int port, flowinfo, scope_id; + char hbuf[NI_MAXHOST], pbuf[NI_MAXSERV]; + struct addrinfo hints, *res = NULL; + int error; + PyObject *ret = (PyObject *)NULL; + + flags = flowinfo = scope_id = 0; + if (!PyArg_ParseTuple(args, "Oi:getnameinfo", &sa, &flags)) + return NULL; + if (!PyTuple_Check(sa)) { + PyErr_SetString(PyExc_TypeError, + "getnameinfo() argument 1 must be a tuple"); + return NULL; + } + if (!PyArg_ParseTuple(sa, "si|ii", + &hostp, &port, &flowinfo, &scope_id)) + return NULL; + PyOS_snprintf(pbuf, sizeof(pbuf), "%d", port); + memset(&hints, 0, sizeof(hints)); + hints.ai_family = AF_UNSPEC; + hints.ai_socktype = SOCK_DGRAM; /* make numeric port happy */ + Py_BEGIN_ALLOW_THREADS + ACQUIRE_GETADDRINFO_LOCK + error = getaddrinfo(hostp, pbuf, &hints, &res); + Py_END_ALLOW_THREADS + RELEASE_GETADDRINFO_LOCK /* see comment in setipaddr() */ + if (error) { + set_gaierror(error); + goto fail; + } + if (res->ai_next) { + PyErr_SetString(socket_error, + "sockaddr resolved to multiple addresses"); + goto fail; + } + switch (res->ai_family) { + case AF_INET: + { + if (PyTuple_GET_SIZE(sa) != 2) { + PyErr_SetString(socket_error, + "IPv4 sockaddr must be 2 tuple"); + goto fail; + } + break; + } #ifdef ENABLE_IPV6 - case AF_INET6: - { - struct sockaddr_in6 *sin6; - sin6 = (struct sockaddr_in6 *)res->ai_addr; - sin6->sin6_flowinfo = flowinfo; - sin6->sin6_scope_id = scope_id; - break; - } -#endif - } - error = getnameinfo(res->ai_addr, res->ai_addrlen, - hbuf, sizeof(hbuf), pbuf, sizeof(pbuf), flags); - if (error) { - set_gaierror(error); - goto fail; - } - ret = Py_BuildValue("ss", hbuf, pbuf); + case AF_INET6: + { + struct sockaddr_in6 *sin6; + sin6 = (struct sockaddr_in6 *)res->ai_addr; + sin6->sin6_flowinfo = flowinfo; + sin6->sin6_scope_id = scope_id; + break; + } +#endif + } + error = getnameinfo(res->ai_addr, res->ai_addrlen, + hbuf, sizeof(hbuf), pbuf, sizeof(pbuf), flags); + if (error) { + set_gaierror(error); + goto fail; + } + ret = Py_BuildValue("ss", hbuf, pbuf); fail: - if (res) - freeaddrinfo(res); - return ret; + if (res) + freeaddrinfo(res); + return ret; } PyDoc_STRVAR(getnameinfo_doc, @@ -3999,12 +3999,12 @@ static PyObject * socket_getdefaulttimeout(PyObject *self) { - if (defaulttimeout < 0.0) { - Py_INCREF(Py_None); - return Py_None; - } - else - return PyFloat_FromDouble(defaulttimeout); + if (defaulttimeout < 0.0) { + Py_INCREF(Py_None); + return Py_None; + } + else + return PyFloat_FromDouble(defaulttimeout); } PyDoc_STRVAR(getdefaulttimeout_doc, @@ -4017,24 +4017,24 @@ static PyObject * socket_setdefaulttimeout(PyObject *self, PyObject *arg) { - double timeout; + double timeout; - if (arg == Py_None) - timeout = -1.0; - else { - timeout = PyFloat_AsDouble(arg); - if (timeout < 0.0) { - if (!PyErr_Occurred()) - PyErr_SetString(PyExc_ValueError, - "Timeout value out of range"); - return NULL; - } - } + if (arg == Py_None) + timeout = -1.0; + else { + timeout = PyFloat_AsDouble(arg); + if (timeout < 0.0) { + if (!PyErr_Occurred()) + PyErr_SetString(PyExc_ValueError, + "Timeout value out of range"); + return NULL; + } + } - defaulttimeout = timeout; + defaulttimeout = timeout; - Py_INCREF(Py_None); - return Py_None; + Py_INCREF(Py_None); + return Py_None; } PyDoc_STRVAR(setdefaulttimeout_doc, @@ -4048,55 +4048,55 @@ /* List of functions exported by this module. */ static PyMethodDef socket_methods[] = { - {"gethostbyname", socket_gethostbyname, - METH_VARARGS, gethostbyname_doc}, - {"gethostbyname_ex", socket_gethostbyname_ex, - METH_VARARGS, ghbn_ex_doc}, - {"gethostbyaddr", socket_gethostbyaddr, - METH_VARARGS, gethostbyaddr_doc}, - {"gethostname", socket_gethostname, - METH_NOARGS, gethostname_doc}, - {"getservbyname", socket_getservbyname, - METH_VARARGS, getservbyname_doc}, - {"getservbyport", socket_getservbyport, - METH_VARARGS, getservbyport_doc}, - {"getprotobyname", socket_getprotobyname, - METH_VARARGS, getprotobyname_doc}, + {"gethostbyname", socket_gethostbyname, + METH_VARARGS, gethostbyname_doc}, + {"gethostbyname_ex", socket_gethostbyname_ex, + METH_VARARGS, ghbn_ex_doc}, + {"gethostbyaddr", socket_gethostbyaddr, + METH_VARARGS, gethostbyaddr_doc}, + {"gethostname", socket_gethostname, + METH_NOARGS, gethostname_doc}, + {"getservbyname", socket_getservbyname, + METH_VARARGS, getservbyname_doc}, + {"getservbyport", socket_getservbyport, + METH_VARARGS, getservbyport_doc}, + {"getprotobyname", socket_getprotobyname, + METH_VARARGS, getprotobyname_doc}, #ifndef NO_DUP - {"dup", socket_dup, - METH_O, dup_doc}, + {"dup", socket_dup, + METH_O, dup_doc}, #endif #ifdef HAVE_SOCKETPAIR - {"socketpair", socket_socketpair, - METH_VARARGS, socketpair_doc}, + {"socketpair", socket_socketpair, + METH_VARARGS, socketpair_doc}, #endif - {"ntohs", socket_ntohs, - METH_VARARGS, ntohs_doc}, - {"ntohl", socket_ntohl, - METH_O, ntohl_doc}, - {"htons", socket_htons, - METH_VARARGS, htons_doc}, - {"htonl", socket_htonl, - METH_O, htonl_doc}, - {"inet_aton", socket_inet_aton, - METH_VARARGS, inet_aton_doc}, - {"inet_ntoa", socket_inet_ntoa, - METH_VARARGS, inet_ntoa_doc}, + {"ntohs", socket_ntohs, + METH_VARARGS, ntohs_doc}, + {"ntohl", socket_ntohl, + METH_O, ntohl_doc}, + {"htons", socket_htons, + METH_VARARGS, htons_doc}, + {"htonl", socket_htonl, + METH_O, htonl_doc}, + {"inet_aton", socket_inet_aton, + METH_VARARGS, inet_aton_doc}, + {"inet_ntoa", socket_inet_ntoa, + METH_VARARGS, inet_ntoa_doc}, #ifdef HAVE_INET_PTON - {"inet_pton", socket_inet_pton, - METH_VARARGS, inet_pton_doc}, - {"inet_ntop", socket_inet_ntop, - METH_VARARGS, inet_ntop_doc}, -#endif - {"getaddrinfo", socket_getaddrinfo, - METH_VARARGS, getaddrinfo_doc}, - {"getnameinfo", socket_getnameinfo, - METH_VARARGS, getnameinfo_doc}, - {"getdefaulttimeout", (PyCFunction)socket_getdefaulttimeout, - METH_NOARGS, getdefaulttimeout_doc}, - {"setdefaulttimeout", socket_setdefaulttimeout, - METH_O, setdefaulttimeout_doc}, - {NULL, NULL} /* Sentinel */ + {"inet_pton", socket_inet_pton, + METH_VARARGS, inet_pton_doc}, + {"inet_ntop", socket_inet_ntop, + METH_VARARGS, inet_ntop_doc}, +#endif + {"getaddrinfo", socket_getaddrinfo, + METH_VARARGS, getaddrinfo_doc}, + {"getnameinfo", socket_getnameinfo, + METH_VARARGS, getnameinfo_doc}, + {"getdefaulttimeout", (PyCFunction)socket_getdefaulttimeout, + METH_NOARGS, getdefaulttimeout_doc}, + {"setdefaulttimeout", socket_setdefaulttimeout, + METH_O, setdefaulttimeout_doc}, + {NULL, NULL} /* Sentinel */ }; @@ -4108,34 +4108,34 @@ static void os_cleanup(void) { - WSACleanup(); + WSACleanup(); } static int os_init(void) { - WSADATA WSAData; - int ret; - ret = WSAStartup(0x0101, &WSAData); - switch (ret) { - case 0: /* No error */ - Py_AtExit(os_cleanup); - return 1; /* Success */ - case WSASYSNOTREADY: - PyErr_SetString(PyExc_ImportError, - "WSAStartup failed: network not ready"); - break; - case WSAVERNOTSUPPORTED: - case WSAEINVAL: - PyErr_SetString( - PyExc_ImportError, - "WSAStartup failed: requested version not supported"); - break; - default: - PyErr_Format(PyExc_ImportError, "WSAStartup failed: error code %d", ret); - break; - } - return 0; /* Failure */ + WSADATA WSAData; + int ret; + ret = WSAStartup(0x0101, &WSAData); + switch (ret) { + case 0: /* No error */ + Py_AtExit(os_cleanup); + return 1; /* Success */ + case WSASYSNOTREADY: + PyErr_SetString(PyExc_ImportError, + "WSAStartup failed: network not ready"); + break; + case WSAVERNOTSUPPORTED: + case WSAEINVAL: + PyErr_SetString( + PyExc_ImportError, + "WSAStartup failed: requested version not supported"); + break; + default: + PyErr_Format(PyExc_ImportError, "WSAStartup failed: error code %d", ret); + break; + } + return 0; /* Failure */ } #endif /* MS_WINDOWS */ @@ -4150,18 +4150,18 @@ os_init(void) { #ifndef PYCC_GCC - int rc = sock_init(); + int rc = sock_init(); - if (rc == 0) { - return 1; /* Success */ - } + if (rc == 0) { + return 1; /* Success */ + } - PyErr_Format(PyExc_ImportError, "OS/2 TCP/IP Error# %d", sock_errno()); + PyErr_Format(PyExc_ImportError, "OS/2 TCP/IP Error# %d", sock_errno()); - return 0; /* Failure */ + return 0; /* Failure */ #else - /* No need to initialise sockets with GCC/EMX */ - return 1; /* Success */ + /* No need to initialise sockets with GCC/EMX */ + return 1; /* Success */ #endif } @@ -4172,7 +4172,7 @@ static int os_init(void) { - return 1; /* Success */ + return 1; /* Success */ } #endif @@ -4182,8 +4182,8 @@ static PySocketModule_APIObject PySocketModuleAPI = { - &sock_type, - NULL + &sock_type, + NULL }; @@ -4203,931 +4203,931 @@ See the socket module for documentation."); static struct PyModuleDef socketmodule = { - PyModuleDef_HEAD_INIT, - PySocket_MODULE_NAME, - socket_doc, - -1, - socket_methods, - NULL, - NULL, - NULL, - NULL + PyModuleDef_HEAD_INIT, + PySocket_MODULE_NAME, + socket_doc, + -1, + socket_methods, + NULL, + NULL, + NULL, + NULL }; PyMODINIT_FUNC PyInit__socket(void) { - PyObject *m, *has_ipv6; + PyObject *m, *has_ipv6; - if (!os_init()) - return NULL; + if (!os_init()) + return NULL; - Py_TYPE(&sock_type) = &PyType_Type; - m = PyModule_Create(&socketmodule); - if (m == NULL) - return NULL; - - socket_error = PyErr_NewException("socket.error", - PyExc_IOError, NULL); - if (socket_error == NULL) - return NULL; - PySocketModuleAPI.error = socket_error; - Py_INCREF(socket_error); - PyModule_AddObject(m, "error", socket_error); - socket_herror = PyErr_NewException("socket.herror", - socket_error, NULL); - if (socket_herror == NULL) - return NULL; - Py_INCREF(socket_herror); - PyModule_AddObject(m, "herror", socket_herror); - socket_gaierror = PyErr_NewException("socket.gaierror", socket_error, - NULL); - if (socket_gaierror == NULL) - return NULL; - Py_INCREF(socket_gaierror); - PyModule_AddObject(m, "gaierror", socket_gaierror); - socket_timeout = PyErr_NewException("socket.timeout", - socket_error, NULL); - if (socket_timeout == NULL) - return NULL; - Py_INCREF(socket_timeout); - PyModule_AddObject(m, "timeout", socket_timeout); - Py_INCREF((PyObject *)&sock_type); - if (PyModule_AddObject(m, "SocketType", - (PyObject *)&sock_type) != 0) - return NULL; - Py_INCREF((PyObject *)&sock_type); - if (PyModule_AddObject(m, "socket", - (PyObject *)&sock_type) != 0) - return NULL; + Py_TYPE(&sock_type) = &PyType_Type; + m = PyModule_Create(&socketmodule); + if (m == NULL) + return NULL; + + socket_error = PyErr_NewException("socket.error", + PyExc_IOError, NULL); + if (socket_error == NULL) + return NULL; + PySocketModuleAPI.error = socket_error; + Py_INCREF(socket_error); + PyModule_AddObject(m, "error", socket_error); + socket_herror = PyErr_NewException("socket.herror", + socket_error, NULL); + if (socket_herror == NULL) + return NULL; + Py_INCREF(socket_herror); + PyModule_AddObject(m, "herror", socket_herror); + socket_gaierror = PyErr_NewException("socket.gaierror", socket_error, + NULL); + if (socket_gaierror == NULL) + return NULL; + Py_INCREF(socket_gaierror); + PyModule_AddObject(m, "gaierror", socket_gaierror); + socket_timeout = PyErr_NewException("socket.timeout", + socket_error, NULL); + if (socket_timeout == NULL) + return NULL; + Py_INCREF(socket_timeout); + PyModule_AddObject(m, "timeout", socket_timeout); + Py_INCREF((PyObject *)&sock_type); + if (PyModule_AddObject(m, "SocketType", + (PyObject *)&sock_type) != 0) + return NULL; + Py_INCREF((PyObject *)&sock_type); + if (PyModule_AddObject(m, "socket", + (PyObject *)&sock_type) != 0) + return NULL; #ifdef ENABLE_IPV6 - has_ipv6 = Py_True; + has_ipv6 = Py_True; #else - has_ipv6 = Py_False; + has_ipv6 = Py_False; #endif - Py_INCREF(has_ipv6); - PyModule_AddObject(m, "has_ipv6", has_ipv6); + Py_INCREF(has_ipv6); + PyModule_AddObject(m, "has_ipv6", has_ipv6); - /* Export C API */ - if (PyModule_AddObject(m, PySocket_CAPI_NAME, - PyCapsule_New(&PySocketModuleAPI, PySocket_CAPSULE_NAME, NULL) - ) != 0) - return NULL; + /* Export C API */ + if (PyModule_AddObject(m, PySocket_CAPI_NAME, + PyCapsule_New(&PySocketModuleAPI, PySocket_CAPSULE_NAME, NULL) + ) != 0) + return NULL; - /* Address families (we only support AF_INET and AF_UNIX) */ + /* Address families (we only support AF_INET and AF_UNIX) */ #ifdef AF_UNSPEC - PyModule_AddIntConstant(m, "AF_UNSPEC", AF_UNSPEC); + PyModule_AddIntConstant(m, "AF_UNSPEC", AF_UNSPEC); #endif - PyModule_AddIntConstant(m, "AF_INET", AF_INET); + PyModule_AddIntConstant(m, "AF_INET", AF_INET); #ifdef AF_INET6 - PyModule_AddIntConstant(m, "AF_INET6", AF_INET6); + PyModule_AddIntConstant(m, "AF_INET6", AF_INET6); #endif /* AF_INET6 */ #if defined(AF_UNIX) - PyModule_AddIntConstant(m, "AF_UNIX", AF_UNIX); + PyModule_AddIntConstant(m, "AF_UNIX", AF_UNIX); #endif /* AF_UNIX */ #ifdef AF_AX25 - /* Amateur Radio AX.25 */ - PyModule_AddIntConstant(m, "AF_AX25", AF_AX25); + /* Amateur Radio AX.25 */ + PyModule_AddIntConstant(m, "AF_AX25", AF_AX25); #endif #ifdef AF_IPX - PyModule_AddIntConstant(m, "AF_IPX", AF_IPX); /* Novell IPX */ + PyModule_AddIntConstant(m, "AF_IPX", AF_IPX); /* Novell IPX */ #endif #ifdef AF_APPLETALK - /* Appletalk DDP */ - PyModule_AddIntConstant(m, "AF_APPLETALK", AF_APPLETALK); + /* Appletalk DDP */ + PyModule_AddIntConstant(m, "AF_APPLETALK", AF_APPLETALK); #endif #ifdef AF_NETROM - /* Amateur radio NetROM */ - PyModule_AddIntConstant(m, "AF_NETROM", AF_NETROM); + /* Amateur radio NetROM */ + PyModule_AddIntConstant(m, "AF_NETROM", AF_NETROM); #endif #ifdef AF_BRIDGE - /* Multiprotocol bridge */ - PyModule_AddIntConstant(m, "AF_BRIDGE", AF_BRIDGE); + /* Multiprotocol bridge */ + PyModule_AddIntConstant(m, "AF_BRIDGE", AF_BRIDGE); #endif #ifdef AF_ATMPVC - /* ATM PVCs */ - PyModule_AddIntConstant(m, "AF_ATMPVC", AF_ATMPVC); + /* ATM PVCs */ + PyModule_AddIntConstant(m, "AF_ATMPVC", AF_ATMPVC); #endif #ifdef AF_AAL5 - /* Reserved for Werner's ATM */ - PyModule_AddIntConstant(m, "AF_AAL5", AF_AAL5); + /* Reserved for Werner's ATM */ + PyModule_AddIntConstant(m, "AF_AAL5", AF_AAL5); #endif #ifdef AF_X25 - /* Reserved for X.25 project */ - PyModule_AddIntConstant(m, "AF_X25", AF_X25); + /* Reserved for X.25 project */ + PyModule_AddIntConstant(m, "AF_X25", AF_X25); #endif #ifdef AF_INET6 - PyModule_AddIntConstant(m, "AF_INET6", AF_INET6); /* IP version 6 */ + PyModule_AddIntConstant(m, "AF_INET6", AF_INET6); /* IP version 6 */ #endif #ifdef AF_ROSE - /* Amateur Radio X.25 PLP */ - PyModule_AddIntConstant(m, "AF_ROSE", AF_ROSE); + /* Amateur Radio X.25 PLP */ + PyModule_AddIntConstant(m, "AF_ROSE", AF_ROSE); #endif #ifdef AF_DECnet - /* Reserved for DECnet project */ - PyModule_AddIntConstant(m, "AF_DECnet", AF_DECnet); + /* Reserved for DECnet project */ + PyModule_AddIntConstant(m, "AF_DECnet", AF_DECnet); #endif #ifdef AF_NETBEUI - /* Reserved for 802.2LLC project */ - PyModule_AddIntConstant(m, "AF_NETBEUI", AF_NETBEUI); + /* Reserved for 802.2LLC project */ + PyModule_AddIntConstant(m, "AF_NETBEUI", AF_NETBEUI); #endif #ifdef AF_SECURITY - /* Security callback pseudo AF */ - PyModule_AddIntConstant(m, "AF_SECURITY", AF_SECURITY); + /* Security callback pseudo AF */ + PyModule_AddIntConstant(m, "AF_SECURITY", AF_SECURITY); #endif #ifdef AF_KEY - /* PF_KEY key management API */ - PyModule_AddIntConstant(m, "AF_KEY", AF_KEY); + /* PF_KEY key management API */ + PyModule_AddIntConstant(m, "AF_KEY", AF_KEY); #endif #ifdef AF_NETLINK - /* */ - PyModule_AddIntConstant(m, "AF_NETLINK", AF_NETLINK); - PyModule_AddIntConstant(m, "NETLINK_ROUTE", NETLINK_ROUTE); + /* */ + PyModule_AddIntConstant(m, "AF_NETLINK", AF_NETLINK); + PyModule_AddIntConstant(m, "NETLINK_ROUTE", NETLINK_ROUTE); #ifdef NETLINK_SKIP - PyModule_AddIntConstant(m, "NETLINK_SKIP", NETLINK_SKIP); + PyModule_AddIntConstant(m, "NETLINK_SKIP", NETLINK_SKIP); #endif #ifdef NETLINK_W1 - PyModule_AddIntConstant(m, "NETLINK_W1", NETLINK_W1); + PyModule_AddIntConstant(m, "NETLINK_W1", NETLINK_W1); #endif - PyModule_AddIntConstant(m, "NETLINK_USERSOCK", NETLINK_USERSOCK); - PyModule_AddIntConstant(m, "NETLINK_FIREWALL", NETLINK_FIREWALL); + PyModule_AddIntConstant(m, "NETLINK_USERSOCK", NETLINK_USERSOCK); + PyModule_AddIntConstant(m, "NETLINK_FIREWALL", NETLINK_FIREWALL); #ifdef NETLINK_TCPDIAG - PyModule_AddIntConstant(m, "NETLINK_TCPDIAG", NETLINK_TCPDIAG); + PyModule_AddIntConstant(m, "NETLINK_TCPDIAG", NETLINK_TCPDIAG); #endif #ifdef NETLINK_NFLOG - PyModule_AddIntConstant(m, "NETLINK_NFLOG", NETLINK_NFLOG); + PyModule_AddIntConstant(m, "NETLINK_NFLOG", NETLINK_NFLOG); #endif #ifdef NETLINK_XFRM - PyModule_AddIntConstant(m, "NETLINK_XFRM", NETLINK_XFRM); + PyModule_AddIntConstant(m, "NETLINK_XFRM", NETLINK_XFRM); #endif #ifdef NETLINK_ARPD - PyModule_AddIntConstant(m, "NETLINK_ARPD", NETLINK_ARPD); + PyModule_AddIntConstant(m, "NETLINK_ARPD", NETLINK_ARPD); #endif #ifdef NETLINK_ROUTE6 - PyModule_AddIntConstant(m, "NETLINK_ROUTE6", NETLINK_ROUTE6); + PyModule_AddIntConstant(m, "NETLINK_ROUTE6", NETLINK_ROUTE6); #endif - PyModule_AddIntConstant(m, "NETLINK_IP6_FW", NETLINK_IP6_FW); + PyModule_AddIntConstant(m, "NETLINK_IP6_FW", NETLINK_IP6_FW); #ifdef NETLINK_DNRTMSG - PyModule_AddIntConstant(m, "NETLINK_DNRTMSG", NETLINK_DNRTMSG); + PyModule_AddIntConstant(m, "NETLINK_DNRTMSG", NETLINK_DNRTMSG); #endif #ifdef NETLINK_TAPBASE - PyModule_AddIntConstant(m, "NETLINK_TAPBASE", NETLINK_TAPBASE); + PyModule_AddIntConstant(m, "NETLINK_TAPBASE", NETLINK_TAPBASE); #endif #endif /* AF_NETLINK */ #ifdef AF_ROUTE - /* Alias to emulate 4.4BSD */ - PyModule_AddIntConstant(m, "AF_ROUTE", AF_ROUTE); + /* Alias to emulate 4.4BSD */ + PyModule_AddIntConstant(m, "AF_ROUTE", AF_ROUTE); #endif #ifdef AF_ASH - /* Ash */ - PyModule_AddIntConstant(m, "AF_ASH", AF_ASH); + /* Ash */ + PyModule_AddIntConstant(m, "AF_ASH", AF_ASH); #endif #ifdef AF_ECONET - /* Acorn Econet */ - PyModule_AddIntConstant(m, "AF_ECONET", AF_ECONET); + /* Acorn Econet */ + PyModule_AddIntConstant(m, "AF_ECONET", AF_ECONET); #endif #ifdef AF_ATMSVC - /* ATM SVCs */ - PyModule_AddIntConstant(m, "AF_ATMSVC", AF_ATMSVC); + /* ATM SVCs */ + PyModule_AddIntConstant(m, "AF_ATMSVC", AF_ATMSVC); #endif #ifdef AF_SNA - /* Linux SNA Project (nutters!) */ - PyModule_AddIntConstant(m, "AF_SNA", AF_SNA); + /* Linux SNA Project (nutters!) */ + PyModule_AddIntConstant(m, "AF_SNA", AF_SNA); #endif #ifdef AF_IRDA - /* IRDA sockets */ - PyModule_AddIntConstant(m, "AF_IRDA", AF_IRDA); + /* IRDA sockets */ + PyModule_AddIntConstant(m, "AF_IRDA", AF_IRDA); #endif #ifdef AF_PPPOX - /* PPPoX sockets */ - PyModule_AddIntConstant(m, "AF_PPPOX", AF_PPPOX); + /* PPPoX sockets */ + PyModule_AddIntConstant(m, "AF_PPPOX", AF_PPPOX); #endif #ifdef AF_WANPIPE - /* Wanpipe API Sockets */ - PyModule_AddIntConstant(m, "AF_WANPIPE", AF_WANPIPE); + /* Wanpipe API Sockets */ + PyModule_AddIntConstant(m, "AF_WANPIPE", AF_WANPIPE); #endif #ifdef AF_LLC - /* Linux LLC */ - PyModule_AddIntConstant(m, "AF_LLC", AF_LLC); + /* Linux LLC */ + PyModule_AddIntConstant(m, "AF_LLC", AF_LLC); #endif #ifdef USE_BLUETOOTH - PyModule_AddIntConstant(m, "AF_BLUETOOTH", AF_BLUETOOTH); - PyModule_AddIntConstant(m, "BTPROTO_L2CAP", BTPROTO_L2CAP); - PyModule_AddIntConstant(m, "BTPROTO_HCI", BTPROTO_HCI); - PyModule_AddIntConstant(m, "SOL_HCI", SOL_HCI); - PyModule_AddIntConstant(m, "HCI_FILTER", HCI_FILTER); + PyModule_AddIntConstant(m, "AF_BLUETOOTH", AF_BLUETOOTH); + PyModule_AddIntConstant(m, "BTPROTO_L2CAP", BTPROTO_L2CAP); + PyModule_AddIntConstant(m, "BTPROTO_HCI", BTPROTO_HCI); + PyModule_AddIntConstant(m, "SOL_HCI", SOL_HCI); + PyModule_AddIntConstant(m, "HCI_FILTER", HCI_FILTER); #if !defined(__FreeBSD__) - PyModule_AddIntConstant(m, "HCI_TIME_STAMP", HCI_TIME_STAMP); - PyModule_AddIntConstant(m, "HCI_DATA_DIR", HCI_DATA_DIR); - PyModule_AddIntConstant(m, "BTPROTO_SCO", BTPROTO_SCO); -#endif - PyModule_AddIntConstant(m, "BTPROTO_RFCOMM", BTPROTO_RFCOMM); - PyModule_AddStringConstant(m, "BDADDR_ANY", "00:00:00:00:00:00"); - PyModule_AddStringConstant(m, "BDADDR_LOCAL", "00:00:00:FF:FF:FF"); + PyModule_AddIntConstant(m, "HCI_TIME_STAMP", HCI_TIME_STAMP); + PyModule_AddIntConstant(m, "HCI_DATA_DIR", HCI_DATA_DIR); + PyModule_AddIntConstant(m, "BTPROTO_SCO", BTPROTO_SCO); +#endif + PyModule_AddIntConstant(m, "BTPROTO_RFCOMM", BTPROTO_RFCOMM); + PyModule_AddStringConstant(m, "BDADDR_ANY", "00:00:00:00:00:00"); + PyModule_AddStringConstant(m, "BDADDR_LOCAL", "00:00:00:FF:FF:FF"); #endif #ifdef HAVE_NETPACKET_PACKET_H - PyModule_AddIntConstant(m, "AF_PACKET", AF_PACKET); - PyModule_AddIntConstant(m, "PF_PACKET", PF_PACKET); - PyModule_AddIntConstant(m, "PACKET_HOST", PACKET_HOST); - PyModule_AddIntConstant(m, "PACKET_BROADCAST", PACKET_BROADCAST); - PyModule_AddIntConstant(m, "PACKET_MULTICAST", PACKET_MULTICAST); - PyModule_AddIntConstant(m, "PACKET_OTHERHOST", PACKET_OTHERHOST); - PyModule_AddIntConstant(m, "PACKET_OUTGOING", PACKET_OUTGOING); - PyModule_AddIntConstant(m, "PACKET_LOOPBACK", PACKET_LOOPBACK); - PyModule_AddIntConstant(m, "PACKET_FASTROUTE", PACKET_FASTROUTE); + PyModule_AddIntConstant(m, "AF_PACKET", AF_PACKET); + PyModule_AddIntConstant(m, "PF_PACKET", PF_PACKET); + PyModule_AddIntConstant(m, "PACKET_HOST", PACKET_HOST); + PyModule_AddIntConstant(m, "PACKET_BROADCAST", PACKET_BROADCAST); + PyModule_AddIntConstant(m, "PACKET_MULTICAST", PACKET_MULTICAST); + PyModule_AddIntConstant(m, "PACKET_OTHERHOST", PACKET_OTHERHOST); + PyModule_AddIntConstant(m, "PACKET_OUTGOING", PACKET_OUTGOING); + PyModule_AddIntConstant(m, "PACKET_LOOPBACK", PACKET_LOOPBACK); + PyModule_AddIntConstant(m, "PACKET_FASTROUTE", PACKET_FASTROUTE); #endif #ifdef HAVE_LINUX_TIPC_H - PyModule_AddIntConstant(m, "AF_TIPC", AF_TIPC); + PyModule_AddIntConstant(m, "AF_TIPC", AF_TIPC); - /* for addresses */ - PyModule_AddIntConstant(m, "TIPC_ADDR_NAMESEQ", TIPC_ADDR_NAMESEQ); - PyModule_AddIntConstant(m, "TIPC_ADDR_NAME", TIPC_ADDR_NAME); - PyModule_AddIntConstant(m, "TIPC_ADDR_ID", TIPC_ADDR_ID); - - PyModule_AddIntConstant(m, "TIPC_ZONE_SCOPE", TIPC_ZONE_SCOPE); - PyModule_AddIntConstant(m, "TIPC_CLUSTER_SCOPE", TIPC_CLUSTER_SCOPE); - PyModule_AddIntConstant(m, "TIPC_NODE_SCOPE", TIPC_NODE_SCOPE); - - /* for setsockopt() */ - PyModule_AddIntConstant(m, "SOL_TIPC", SOL_TIPC); - PyModule_AddIntConstant(m, "TIPC_IMPORTANCE", TIPC_IMPORTANCE); - PyModule_AddIntConstant(m, "TIPC_SRC_DROPPABLE", TIPC_SRC_DROPPABLE); - PyModule_AddIntConstant(m, "TIPC_DEST_DROPPABLE", - TIPC_DEST_DROPPABLE); - PyModule_AddIntConstant(m, "TIPC_CONN_TIMEOUT", TIPC_CONN_TIMEOUT); - - PyModule_AddIntConstant(m, "TIPC_LOW_IMPORTANCE", - TIPC_LOW_IMPORTANCE); - PyModule_AddIntConstant(m, "TIPC_MEDIUM_IMPORTANCE", - TIPC_MEDIUM_IMPORTANCE); - PyModule_AddIntConstant(m, "TIPC_HIGH_IMPORTANCE", - TIPC_HIGH_IMPORTANCE); - PyModule_AddIntConstant(m, "TIPC_CRITICAL_IMPORTANCE", - TIPC_CRITICAL_IMPORTANCE); - - /* for subscriptions */ - PyModule_AddIntConstant(m, "TIPC_SUB_PORTS", TIPC_SUB_PORTS); - PyModule_AddIntConstant(m, "TIPC_SUB_SERVICE", TIPC_SUB_SERVICE); + /* for addresses */ + PyModule_AddIntConstant(m, "TIPC_ADDR_NAMESEQ", TIPC_ADDR_NAMESEQ); + PyModule_AddIntConstant(m, "TIPC_ADDR_NAME", TIPC_ADDR_NAME); + PyModule_AddIntConstant(m, "TIPC_ADDR_ID", TIPC_ADDR_ID); + + PyModule_AddIntConstant(m, "TIPC_ZONE_SCOPE", TIPC_ZONE_SCOPE); + PyModule_AddIntConstant(m, "TIPC_CLUSTER_SCOPE", TIPC_CLUSTER_SCOPE); + PyModule_AddIntConstant(m, "TIPC_NODE_SCOPE", TIPC_NODE_SCOPE); + + /* for setsockopt() */ + PyModule_AddIntConstant(m, "SOL_TIPC", SOL_TIPC); + PyModule_AddIntConstant(m, "TIPC_IMPORTANCE", TIPC_IMPORTANCE); + PyModule_AddIntConstant(m, "TIPC_SRC_DROPPABLE", TIPC_SRC_DROPPABLE); + PyModule_AddIntConstant(m, "TIPC_DEST_DROPPABLE", + TIPC_DEST_DROPPABLE); + PyModule_AddIntConstant(m, "TIPC_CONN_TIMEOUT", TIPC_CONN_TIMEOUT); + + PyModule_AddIntConstant(m, "TIPC_LOW_IMPORTANCE", + TIPC_LOW_IMPORTANCE); + PyModule_AddIntConstant(m, "TIPC_MEDIUM_IMPORTANCE", + TIPC_MEDIUM_IMPORTANCE); + PyModule_AddIntConstant(m, "TIPC_HIGH_IMPORTANCE", + TIPC_HIGH_IMPORTANCE); + PyModule_AddIntConstant(m, "TIPC_CRITICAL_IMPORTANCE", + TIPC_CRITICAL_IMPORTANCE); + + /* for subscriptions */ + PyModule_AddIntConstant(m, "TIPC_SUB_PORTS", TIPC_SUB_PORTS); + PyModule_AddIntConstant(m, "TIPC_SUB_SERVICE", TIPC_SUB_SERVICE); #ifdef TIPC_SUB_CANCEL - /* doesn't seem to be available everywhere */ - PyModule_AddIntConstant(m, "TIPC_SUB_CANCEL", TIPC_SUB_CANCEL); + /* doesn't seem to be available everywhere */ + PyModule_AddIntConstant(m, "TIPC_SUB_CANCEL", TIPC_SUB_CANCEL); #endif - PyModule_AddIntConstant(m, "TIPC_WAIT_FOREVER", TIPC_WAIT_FOREVER); - PyModule_AddIntConstant(m, "TIPC_PUBLISHED", TIPC_PUBLISHED); - PyModule_AddIntConstant(m, "TIPC_WITHDRAWN", TIPC_WITHDRAWN); - PyModule_AddIntConstant(m, "TIPC_SUBSCR_TIMEOUT", TIPC_SUBSCR_TIMEOUT); - PyModule_AddIntConstant(m, "TIPC_CFG_SRV", TIPC_CFG_SRV); - PyModule_AddIntConstant(m, "TIPC_TOP_SRV", TIPC_TOP_SRV); + PyModule_AddIntConstant(m, "TIPC_WAIT_FOREVER", TIPC_WAIT_FOREVER); + PyModule_AddIntConstant(m, "TIPC_PUBLISHED", TIPC_PUBLISHED); + PyModule_AddIntConstant(m, "TIPC_WITHDRAWN", TIPC_WITHDRAWN); + PyModule_AddIntConstant(m, "TIPC_SUBSCR_TIMEOUT", TIPC_SUBSCR_TIMEOUT); + PyModule_AddIntConstant(m, "TIPC_CFG_SRV", TIPC_CFG_SRV); + PyModule_AddIntConstant(m, "TIPC_TOP_SRV", TIPC_TOP_SRV); #endif - /* Socket types */ - PyModule_AddIntConstant(m, "SOCK_STREAM", SOCK_STREAM); - PyModule_AddIntConstant(m, "SOCK_DGRAM", SOCK_DGRAM); + /* Socket types */ + PyModule_AddIntConstant(m, "SOCK_STREAM", SOCK_STREAM); + PyModule_AddIntConstant(m, "SOCK_DGRAM", SOCK_DGRAM); /* We have incomplete socket support. */ - PyModule_AddIntConstant(m, "SOCK_RAW", SOCK_RAW); - PyModule_AddIntConstant(m, "SOCK_SEQPACKET", SOCK_SEQPACKET); + PyModule_AddIntConstant(m, "SOCK_RAW", SOCK_RAW); + PyModule_AddIntConstant(m, "SOCK_SEQPACKET", SOCK_SEQPACKET); #if defined(SOCK_RDM) - PyModule_AddIntConstant(m, "SOCK_RDM", SOCK_RDM); + PyModule_AddIntConstant(m, "SOCK_RDM", SOCK_RDM); #endif -#ifdef SO_DEBUG - PyModule_AddIntConstant(m, "SO_DEBUG", SO_DEBUG); +#ifdef SO_DEBUG + PyModule_AddIntConstant(m, "SO_DEBUG", SO_DEBUG); #endif -#ifdef SO_ACCEPTCONN - PyModule_AddIntConstant(m, "SO_ACCEPTCONN", SO_ACCEPTCONN); +#ifdef SO_ACCEPTCONN + PyModule_AddIntConstant(m, "SO_ACCEPTCONN", SO_ACCEPTCONN); #endif -#ifdef SO_REUSEADDR - PyModule_AddIntConstant(m, "SO_REUSEADDR", SO_REUSEADDR); +#ifdef SO_REUSEADDR + PyModule_AddIntConstant(m, "SO_REUSEADDR", SO_REUSEADDR); #endif #ifdef SO_EXCLUSIVEADDRUSE - PyModule_AddIntConstant(m, "SO_EXCLUSIVEADDRUSE", SO_EXCLUSIVEADDRUSE); + PyModule_AddIntConstant(m, "SO_EXCLUSIVEADDRUSE", SO_EXCLUSIVEADDRUSE); #endif -#ifdef SO_KEEPALIVE - PyModule_AddIntConstant(m, "SO_KEEPALIVE", SO_KEEPALIVE); +#ifdef SO_KEEPALIVE + PyModule_AddIntConstant(m, "SO_KEEPALIVE", SO_KEEPALIVE); #endif -#ifdef SO_DONTROUTE - PyModule_AddIntConstant(m, "SO_DONTROUTE", SO_DONTROUTE); +#ifdef SO_DONTROUTE + PyModule_AddIntConstant(m, "SO_DONTROUTE", SO_DONTROUTE); #endif -#ifdef SO_BROADCAST - PyModule_AddIntConstant(m, "SO_BROADCAST", SO_BROADCAST); +#ifdef SO_BROADCAST + PyModule_AddIntConstant(m, "SO_BROADCAST", SO_BROADCAST); #endif -#ifdef SO_USELOOPBACK - PyModule_AddIntConstant(m, "SO_USELOOPBACK", SO_USELOOPBACK); +#ifdef SO_USELOOPBACK + PyModule_AddIntConstant(m, "SO_USELOOPBACK", SO_USELOOPBACK); #endif -#ifdef SO_LINGER - PyModule_AddIntConstant(m, "SO_LINGER", SO_LINGER); +#ifdef SO_LINGER + PyModule_AddIntConstant(m, "SO_LINGER", SO_LINGER); #endif -#ifdef SO_OOBINLINE - PyModule_AddIntConstant(m, "SO_OOBINLINE", SO_OOBINLINE); +#ifdef SO_OOBINLINE + PyModule_AddIntConstant(m, "SO_OOBINLINE", SO_OOBINLINE); #endif -#ifdef SO_REUSEPORT - PyModule_AddIntConstant(m, "SO_REUSEPORT", SO_REUSEPORT); +#ifdef SO_REUSEPORT + PyModule_AddIntConstant(m, "SO_REUSEPORT", SO_REUSEPORT); #endif -#ifdef SO_SNDBUF - PyModule_AddIntConstant(m, "SO_SNDBUF", SO_SNDBUF); +#ifdef SO_SNDBUF + PyModule_AddIntConstant(m, "SO_SNDBUF", SO_SNDBUF); #endif -#ifdef SO_RCVBUF - PyModule_AddIntConstant(m, "SO_RCVBUF", SO_RCVBUF); +#ifdef SO_RCVBUF + PyModule_AddIntConstant(m, "SO_RCVBUF", SO_RCVBUF); #endif -#ifdef SO_SNDLOWAT - PyModule_AddIntConstant(m, "SO_SNDLOWAT", SO_SNDLOWAT); +#ifdef SO_SNDLOWAT + PyModule_AddIntConstant(m, "SO_SNDLOWAT", SO_SNDLOWAT); #endif -#ifdef SO_RCVLOWAT - PyModule_AddIntConstant(m, "SO_RCVLOWAT", SO_RCVLOWAT); +#ifdef SO_RCVLOWAT + PyModule_AddIntConstant(m, "SO_RCVLOWAT", SO_RCVLOWAT); #endif -#ifdef SO_SNDTIMEO - PyModule_AddIntConstant(m, "SO_SNDTIMEO", SO_SNDTIMEO); +#ifdef SO_SNDTIMEO + PyModule_AddIntConstant(m, "SO_SNDTIMEO", SO_SNDTIMEO); #endif -#ifdef SO_RCVTIMEO - PyModule_AddIntConstant(m, "SO_RCVTIMEO", SO_RCVTIMEO); +#ifdef SO_RCVTIMEO + PyModule_AddIntConstant(m, "SO_RCVTIMEO", SO_RCVTIMEO); #endif -#ifdef SO_ERROR - PyModule_AddIntConstant(m, "SO_ERROR", SO_ERROR); +#ifdef SO_ERROR + PyModule_AddIntConstant(m, "SO_ERROR", SO_ERROR); #endif -#ifdef SO_TYPE - PyModule_AddIntConstant(m, "SO_TYPE", SO_TYPE); +#ifdef SO_TYPE + PyModule_AddIntConstant(m, "SO_TYPE", SO_TYPE); #endif -#ifdef SO_SETFIB - PyModule_AddIntConstant(m, "SO_SETFIB", SO_SETFIB); +#ifdef SO_SETFIB + PyModule_AddIntConstant(m, "SO_SETFIB", SO_SETFIB); #endif - /* Maximum number of connections for "listen" */ -#ifdef SOMAXCONN - PyModule_AddIntConstant(m, "SOMAXCONN", SOMAXCONN); + /* Maximum number of connections for "listen" */ +#ifdef SOMAXCONN + PyModule_AddIntConstant(m, "SOMAXCONN", SOMAXCONN); #else - PyModule_AddIntConstant(m, "SOMAXCONN", 5); /* Common value */ + PyModule_AddIntConstant(m, "SOMAXCONN", 5); /* Common value */ #endif - /* Flags for send, recv */ -#ifdef MSG_OOB - PyModule_AddIntConstant(m, "MSG_OOB", MSG_OOB); + /* Flags for send, recv */ +#ifdef MSG_OOB + PyModule_AddIntConstant(m, "MSG_OOB", MSG_OOB); #endif -#ifdef MSG_PEEK - PyModule_AddIntConstant(m, "MSG_PEEK", MSG_PEEK); +#ifdef MSG_PEEK + PyModule_AddIntConstant(m, "MSG_PEEK", MSG_PEEK); #endif -#ifdef MSG_DONTROUTE - PyModule_AddIntConstant(m, "MSG_DONTROUTE", MSG_DONTROUTE); +#ifdef MSG_DONTROUTE + PyModule_AddIntConstant(m, "MSG_DONTROUTE", MSG_DONTROUTE); #endif -#ifdef MSG_DONTWAIT - PyModule_AddIntConstant(m, "MSG_DONTWAIT", MSG_DONTWAIT); +#ifdef MSG_DONTWAIT + PyModule_AddIntConstant(m, "MSG_DONTWAIT", MSG_DONTWAIT); #endif -#ifdef MSG_EOR - PyModule_AddIntConstant(m, "MSG_EOR", MSG_EOR); +#ifdef MSG_EOR + PyModule_AddIntConstant(m, "MSG_EOR", MSG_EOR); #endif -#ifdef MSG_TRUNC - PyModule_AddIntConstant(m, "MSG_TRUNC", MSG_TRUNC); +#ifdef MSG_TRUNC + PyModule_AddIntConstant(m, "MSG_TRUNC", MSG_TRUNC); #endif -#ifdef MSG_CTRUNC - PyModule_AddIntConstant(m, "MSG_CTRUNC", MSG_CTRUNC); +#ifdef MSG_CTRUNC + PyModule_AddIntConstant(m, "MSG_CTRUNC", MSG_CTRUNC); #endif -#ifdef MSG_WAITALL - PyModule_AddIntConstant(m, "MSG_WAITALL", MSG_WAITALL); +#ifdef MSG_WAITALL + PyModule_AddIntConstant(m, "MSG_WAITALL", MSG_WAITALL); #endif -#ifdef MSG_BTAG - PyModule_AddIntConstant(m, "MSG_BTAG", MSG_BTAG); +#ifdef MSG_BTAG + PyModule_AddIntConstant(m, "MSG_BTAG", MSG_BTAG); #endif -#ifdef MSG_ETAG - PyModule_AddIntConstant(m, "MSG_ETAG", MSG_ETAG); +#ifdef MSG_ETAG + PyModule_AddIntConstant(m, "MSG_ETAG", MSG_ETAG); #endif - /* Protocol level and numbers, usable for [gs]etsockopt */ -#ifdef SOL_SOCKET - PyModule_AddIntConstant(m, "SOL_SOCKET", SOL_SOCKET); + /* Protocol level and numbers, usable for [gs]etsockopt */ +#ifdef SOL_SOCKET + PyModule_AddIntConstant(m, "SOL_SOCKET", SOL_SOCKET); #endif -#ifdef SOL_IP - PyModule_AddIntConstant(m, "SOL_IP", SOL_IP); +#ifdef SOL_IP + PyModule_AddIntConstant(m, "SOL_IP", SOL_IP); #else - PyModule_AddIntConstant(m, "SOL_IP", 0); + PyModule_AddIntConstant(m, "SOL_IP", 0); #endif -#ifdef SOL_IPX - PyModule_AddIntConstant(m, "SOL_IPX", SOL_IPX); +#ifdef SOL_IPX + PyModule_AddIntConstant(m, "SOL_IPX", SOL_IPX); #endif -#ifdef SOL_AX25 - PyModule_AddIntConstant(m, "SOL_AX25", SOL_AX25); +#ifdef SOL_AX25 + PyModule_AddIntConstant(m, "SOL_AX25", SOL_AX25); #endif -#ifdef SOL_ATALK - PyModule_AddIntConstant(m, "SOL_ATALK", SOL_ATALK); +#ifdef SOL_ATALK + PyModule_AddIntConstant(m, "SOL_ATALK", SOL_ATALK); #endif -#ifdef SOL_NETROM - PyModule_AddIntConstant(m, "SOL_NETROM", SOL_NETROM); +#ifdef SOL_NETROM + PyModule_AddIntConstant(m, "SOL_NETROM", SOL_NETROM); #endif -#ifdef SOL_ROSE - PyModule_AddIntConstant(m, "SOL_ROSE", SOL_ROSE); +#ifdef SOL_ROSE + PyModule_AddIntConstant(m, "SOL_ROSE", SOL_ROSE); #endif -#ifdef SOL_TCP - PyModule_AddIntConstant(m, "SOL_TCP", SOL_TCP); +#ifdef SOL_TCP + PyModule_AddIntConstant(m, "SOL_TCP", SOL_TCP); #else - PyModule_AddIntConstant(m, "SOL_TCP", 6); + PyModule_AddIntConstant(m, "SOL_TCP", 6); #endif -#ifdef SOL_UDP - PyModule_AddIntConstant(m, "SOL_UDP", SOL_UDP); +#ifdef SOL_UDP + PyModule_AddIntConstant(m, "SOL_UDP", SOL_UDP); #else - PyModule_AddIntConstant(m, "SOL_UDP", 17); + PyModule_AddIntConstant(m, "SOL_UDP", 17); #endif -#ifdef IPPROTO_IP - PyModule_AddIntConstant(m, "IPPROTO_IP", IPPROTO_IP); +#ifdef IPPROTO_IP + PyModule_AddIntConstant(m, "IPPROTO_IP", IPPROTO_IP); #else - PyModule_AddIntConstant(m, "IPPROTO_IP", 0); + PyModule_AddIntConstant(m, "IPPROTO_IP", 0); #endif -#ifdef IPPROTO_HOPOPTS - PyModule_AddIntConstant(m, "IPPROTO_HOPOPTS", IPPROTO_HOPOPTS); +#ifdef IPPROTO_HOPOPTS + PyModule_AddIntConstant(m, "IPPROTO_HOPOPTS", IPPROTO_HOPOPTS); #endif -#ifdef IPPROTO_ICMP - PyModule_AddIntConstant(m, "IPPROTO_ICMP", IPPROTO_ICMP); +#ifdef IPPROTO_ICMP + PyModule_AddIntConstant(m, "IPPROTO_ICMP", IPPROTO_ICMP); #else - PyModule_AddIntConstant(m, "IPPROTO_ICMP", 1); + PyModule_AddIntConstant(m, "IPPROTO_ICMP", 1); #endif -#ifdef IPPROTO_IGMP - PyModule_AddIntConstant(m, "IPPROTO_IGMP", IPPROTO_IGMP); +#ifdef IPPROTO_IGMP + PyModule_AddIntConstant(m, "IPPROTO_IGMP", IPPROTO_IGMP); #endif -#ifdef IPPROTO_GGP - PyModule_AddIntConstant(m, "IPPROTO_GGP", IPPROTO_GGP); +#ifdef IPPROTO_GGP + PyModule_AddIntConstant(m, "IPPROTO_GGP", IPPROTO_GGP); #endif -#ifdef IPPROTO_IPV4 - PyModule_AddIntConstant(m, "IPPROTO_IPV4", IPPROTO_IPV4); +#ifdef IPPROTO_IPV4 + PyModule_AddIntConstant(m, "IPPROTO_IPV4", IPPROTO_IPV4); #endif -#ifdef IPPROTO_IPV6 - PyModule_AddIntConstant(m, "IPPROTO_IPV6", IPPROTO_IPV6); +#ifdef IPPROTO_IPV6 + PyModule_AddIntConstant(m, "IPPROTO_IPV6", IPPROTO_IPV6); #endif -#ifdef IPPROTO_IPIP - PyModule_AddIntConstant(m, "IPPROTO_IPIP", IPPROTO_IPIP); +#ifdef IPPROTO_IPIP + PyModule_AddIntConstant(m, "IPPROTO_IPIP", IPPROTO_IPIP); #endif -#ifdef IPPROTO_TCP - PyModule_AddIntConstant(m, "IPPROTO_TCP", IPPROTO_TCP); +#ifdef IPPROTO_TCP + PyModule_AddIntConstant(m, "IPPROTO_TCP", IPPROTO_TCP); #else - PyModule_AddIntConstant(m, "IPPROTO_TCP", 6); + PyModule_AddIntConstant(m, "IPPROTO_TCP", 6); #endif -#ifdef IPPROTO_EGP - PyModule_AddIntConstant(m, "IPPROTO_EGP", IPPROTO_EGP); +#ifdef IPPROTO_EGP + PyModule_AddIntConstant(m, "IPPROTO_EGP", IPPROTO_EGP); #endif -#ifdef IPPROTO_PUP - PyModule_AddIntConstant(m, "IPPROTO_PUP", IPPROTO_PUP); +#ifdef IPPROTO_PUP + PyModule_AddIntConstant(m, "IPPROTO_PUP", IPPROTO_PUP); #endif -#ifdef IPPROTO_UDP - PyModule_AddIntConstant(m, "IPPROTO_UDP", IPPROTO_UDP); +#ifdef IPPROTO_UDP + PyModule_AddIntConstant(m, "IPPROTO_UDP", IPPROTO_UDP); #else - PyModule_AddIntConstant(m, "IPPROTO_UDP", 17); + PyModule_AddIntConstant(m, "IPPROTO_UDP", 17); #endif -#ifdef IPPROTO_IDP - PyModule_AddIntConstant(m, "IPPROTO_IDP", IPPROTO_IDP); +#ifdef IPPROTO_IDP + PyModule_AddIntConstant(m, "IPPROTO_IDP", IPPROTO_IDP); #endif -#ifdef IPPROTO_HELLO - PyModule_AddIntConstant(m, "IPPROTO_HELLO", IPPROTO_HELLO); +#ifdef IPPROTO_HELLO + PyModule_AddIntConstant(m, "IPPROTO_HELLO", IPPROTO_HELLO); #endif -#ifdef IPPROTO_ND - PyModule_AddIntConstant(m, "IPPROTO_ND", IPPROTO_ND); +#ifdef IPPROTO_ND + PyModule_AddIntConstant(m, "IPPROTO_ND", IPPROTO_ND); #endif -#ifdef IPPROTO_TP - PyModule_AddIntConstant(m, "IPPROTO_TP", IPPROTO_TP); +#ifdef IPPROTO_TP + PyModule_AddIntConstant(m, "IPPROTO_TP", IPPROTO_TP); #endif -#ifdef IPPROTO_IPV6 - PyModule_AddIntConstant(m, "IPPROTO_IPV6", IPPROTO_IPV6); +#ifdef IPPROTO_IPV6 + PyModule_AddIntConstant(m, "IPPROTO_IPV6", IPPROTO_IPV6); #endif -#ifdef IPPROTO_ROUTING - PyModule_AddIntConstant(m, "IPPROTO_ROUTING", IPPROTO_ROUTING); +#ifdef IPPROTO_ROUTING + PyModule_AddIntConstant(m, "IPPROTO_ROUTING", IPPROTO_ROUTING); #endif -#ifdef IPPROTO_FRAGMENT - PyModule_AddIntConstant(m, "IPPROTO_FRAGMENT", IPPROTO_FRAGMENT); +#ifdef IPPROTO_FRAGMENT + PyModule_AddIntConstant(m, "IPPROTO_FRAGMENT", IPPROTO_FRAGMENT); #endif -#ifdef IPPROTO_RSVP - PyModule_AddIntConstant(m, "IPPROTO_RSVP", IPPROTO_RSVP); +#ifdef IPPROTO_RSVP + PyModule_AddIntConstant(m, "IPPROTO_RSVP", IPPROTO_RSVP); #endif -#ifdef IPPROTO_GRE - PyModule_AddIntConstant(m, "IPPROTO_GRE", IPPROTO_GRE); +#ifdef IPPROTO_GRE + PyModule_AddIntConstant(m, "IPPROTO_GRE", IPPROTO_GRE); #endif -#ifdef IPPROTO_ESP - PyModule_AddIntConstant(m, "IPPROTO_ESP", IPPROTO_ESP); +#ifdef IPPROTO_ESP + PyModule_AddIntConstant(m, "IPPROTO_ESP", IPPROTO_ESP); #endif -#ifdef IPPROTO_AH - PyModule_AddIntConstant(m, "IPPROTO_AH", IPPROTO_AH); +#ifdef IPPROTO_AH + PyModule_AddIntConstant(m, "IPPROTO_AH", IPPROTO_AH); #endif -#ifdef IPPROTO_MOBILE - PyModule_AddIntConstant(m, "IPPROTO_MOBILE", IPPROTO_MOBILE); +#ifdef IPPROTO_MOBILE + PyModule_AddIntConstant(m, "IPPROTO_MOBILE", IPPROTO_MOBILE); #endif -#ifdef IPPROTO_ICMPV6 - PyModule_AddIntConstant(m, "IPPROTO_ICMPV6", IPPROTO_ICMPV6); +#ifdef IPPROTO_ICMPV6 + PyModule_AddIntConstant(m, "IPPROTO_ICMPV6", IPPROTO_ICMPV6); #endif -#ifdef IPPROTO_NONE - PyModule_AddIntConstant(m, "IPPROTO_NONE", IPPROTO_NONE); +#ifdef IPPROTO_NONE + PyModule_AddIntConstant(m, "IPPROTO_NONE", IPPROTO_NONE); #endif -#ifdef IPPROTO_DSTOPTS - PyModule_AddIntConstant(m, "IPPROTO_DSTOPTS", IPPROTO_DSTOPTS); +#ifdef IPPROTO_DSTOPTS + PyModule_AddIntConstant(m, "IPPROTO_DSTOPTS", IPPROTO_DSTOPTS); #endif -#ifdef IPPROTO_XTP - PyModule_AddIntConstant(m, "IPPROTO_XTP", IPPROTO_XTP); +#ifdef IPPROTO_XTP + PyModule_AddIntConstant(m, "IPPROTO_XTP", IPPROTO_XTP); #endif -#ifdef IPPROTO_EON - PyModule_AddIntConstant(m, "IPPROTO_EON", IPPROTO_EON); +#ifdef IPPROTO_EON + PyModule_AddIntConstant(m, "IPPROTO_EON", IPPROTO_EON); #endif -#ifdef IPPROTO_PIM - PyModule_AddIntConstant(m, "IPPROTO_PIM", IPPROTO_PIM); +#ifdef IPPROTO_PIM + PyModule_AddIntConstant(m, "IPPROTO_PIM", IPPROTO_PIM); #endif -#ifdef IPPROTO_IPCOMP - PyModule_AddIntConstant(m, "IPPROTO_IPCOMP", IPPROTO_IPCOMP); +#ifdef IPPROTO_IPCOMP + PyModule_AddIntConstant(m, "IPPROTO_IPCOMP", IPPROTO_IPCOMP); #endif -#ifdef IPPROTO_VRRP - PyModule_AddIntConstant(m, "IPPROTO_VRRP", IPPROTO_VRRP); +#ifdef IPPROTO_VRRP + PyModule_AddIntConstant(m, "IPPROTO_VRRP", IPPROTO_VRRP); #endif -#ifdef IPPROTO_BIP - PyModule_AddIntConstant(m, "IPPROTO_BIP", IPPROTO_BIP); +#ifdef IPPROTO_BIP + PyModule_AddIntConstant(m, "IPPROTO_BIP", IPPROTO_BIP); #endif /**/ -#ifdef IPPROTO_RAW - PyModule_AddIntConstant(m, "IPPROTO_RAW", IPPROTO_RAW); +#ifdef IPPROTO_RAW + PyModule_AddIntConstant(m, "IPPROTO_RAW", IPPROTO_RAW); #else - PyModule_AddIntConstant(m, "IPPROTO_RAW", 255); + PyModule_AddIntConstant(m, "IPPROTO_RAW", 255); #endif -#ifdef IPPROTO_MAX - PyModule_AddIntConstant(m, "IPPROTO_MAX", IPPROTO_MAX); +#ifdef IPPROTO_MAX + PyModule_AddIntConstant(m, "IPPROTO_MAX", IPPROTO_MAX); #endif - /* Some port configuration */ -#ifdef IPPORT_RESERVED - PyModule_AddIntConstant(m, "IPPORT_RESERVED", IPPORT_RESERVED); + /* Some port configuration */ +#ifdef IPPORT_RESERVED + PyModule_AddIntConstant(m, "IPPORT_RESERVED", IPPORT_RESERVED); #else - PyModule_AddIntConstant(m, "IPPORT_RESERVED", 1024); + PyModule_AddIntConstant(m, "IPPORT_RESERVED", 1024); #endif -#ifdef IPPORT_USERRESERVED - PyModule_AddIntConstant(m, "IPPORT_USERRESERVED", IPPORT_USERRESERVED); +#ifdef IPPORT_USERRESERVED + PyModule_AddIntConstant(m, "IPPORT_USERRESERVED", IPPORT_USERRESERVED); #else - PyModule_AddIntConstant(m, "IPPORT_USERRESERVED", 5000); + PyModule_AddIntConstant(m, "IPPORT_USERRESERVED", 5000); #endif - /* Some reserved IP v.4 addresses */ -#ifdef INADDR_ANY - PyModule_AddIntConstant(m, "INADDR_ANY", INADDR_ANY); + /* Some reserved IP v.4 addresses */ +#ifdef INADDR_ANY + PyModule_AddIntConstant(m, "INADDR_ANY", INADDR_ANY); #else - PyModule_AddIntConstant(m, "INADDR_ANY", 0x00000000); + PyModule_AddIntConstant(m, "INADDR_ANY", 0x00000000); #endif -#ifdef INADDR_BROADCAST - PyModule_AddIntConstant(m, "INADDR_BROADCAST", INADDR_BROADCAST); +#ifdef INADDR_BROADCAST + PyModule_AddIntConstant(m, "INADDR_BROADCAST", INADDR_BROADCAST); #else - PyModule_AddIntConstant(m, "INADDR_BROADCAST", 0xffffffff); + PyModule_AddIntConstant(m, "INADDR_BROADCAST", 0xffffffff); #endif -#ifdef INADDR_LOOPBACK - PyModule_AddIntConstant(m, "INADDR_LOOPBACK", INADDR_LOOPBACK); +#ifdef INADDR_LOOPBACK + PyModule_AddIntConstant(m, "INADDR_LOOPBACK", INADDR_LOOPBACK); #else - PyModule_AddIntConstant(m, "INADDR_LOOPBACK", 0x7F000001); + PyModule_AddIntConstant(m, "INADDR_LOOPBACK", 0x7F000001); #endif -#ifdef INADDR_UNSPEC_GROUP - PyModule_AddIntConstant(m, "INADDR_UNSPEC_GROUP", INADDR_UNSPEC_GROUP); +#ifdef INADDR_UNSPEC_GROUP + PyModule_AddIntConstant(m, "INADDR_UNSPEC_GROUP", INADDR_UNSPEC_GROUP); #else - PyModule_AddIntConstant(m, "INADDR_UNSPEC_GROUP", 0xe0000000); + PyModule_AddIntConstant(m, "INADDR_UNSPEC_GROUP", 0xe0000000); #endif -#ifdef INADDR_ALLHOSTS_GROUP - PyModule_AddIntConstant(m, "INADDR_ALLHOSTS_GROUP", - INADDR_ALLHOSTS_GROUP); +#ifdef INADDR_ALLHOSTS_GROUP + PyModule_AddIntConstant(m, "INADDR_ALLHOSTS_GROUP", + INADDR_ALLHOSTS_GROUP); #else - PyModule_AddIntConstant(m, "INADDR_ALLHOSTS_GROUP", 0xe0000001); + PyModule_AddIntConstant(m, "INADDR_ALLHOSTS_GROUP", 0xe0000001); #endif -#ifdef INADDR_MAX_LOCAL_GROUP - PyModule_AddIntConstant(m, "INADDR_MAX_LOCAL_GROUP", - INADDR_MAX_LOCAL_GROUP); +#ifdef INADDR_MAX_LOCAL_GROUP + PyModule_AddIntConstant(m, "INADDR_MAX_LOCAL_GROUP", + INADDR_MAX_LOCAL_GROUP); #else - PyModule_AddIntConstant(m, "INADDR_MAX_LOCAL_GROUP", 0xe00000ff); + PyModule_AddIntConstant(m, "INADDR_MAX_LOCAL_GROUP", 0xe00000ff); #endif -#ifdef INADDR_NONE - PyModule_AddIntConstant(m, "INADDR_NONE", INADDR_NONE); +#ifdef INADDR_NONE + PyModule_AddIntConstant(m, "INADDR_NONE", INADDR_NONE); #else - PyModule_AddIntConstant(m, "INADDR_NONE", 0xffffffff); + PyModule_AddIntConstant(m, "INADDR_NONE", 0xffffffff); #endif - /* IPv4 [gs]etsockopt options */ -#ifdef IP_OPTIONS - PyModule_AddIntConstant(m, "IP_OPTIONS", IP_OPTIONS); + /* IPv4 [gs]etsockopt options */ +#ifdef IP_OPTIONS + PyModule_AddIntConstant(m, "IP_OPTIONS", IP_OPTIONS); #endif -#ifdef IP_HDRINCL - PyModule_AddIntConstant(m, "IP_HDRINCL", IP_HDRINCL); +#ifdef IP_HDRINCL + PyModule_AddIntConstant(m, "IP_HDRINCL", IP_HDRINCL); #endif -#ifdef IP_TOS - PyModule_AddIntConstant(m, "IP_TOS", IP_TOS); +#ifdef IP_TOS + PyModule_AddIntConstant(m, "IP_TOS", IP_TOS); #endif -#ifdef IP_TTL - PyModule_AddIntConstant(m, "IP_TTL", IP_TTL); +#ifdef IP_TTL + PyModule_AddIntConstant(m, "IP_TTL", IP_TTL); #endif -#ifdef IP_RECVOPTS - PyModule_AddIntConstant(m, "IP_RECVOPTS", IP_RECVOPTS); +#ifdef IP_RECVOPTS + PyModule_AddIntConstant(m, "IP_RECVOPTS", IP_RECVOPTS); #endif -#ifdef IP_RECVRETOPTS - PyModule_AddIntConstant(m, "IP_RECVRETOPTS", IP_RECVRETOPTS); +#ifdef IP_RECVRETOPTS + PyModule_AddIntConstant(m, "IP_RECVRETOPTS", IP_RECVRETOPTS); #endif -#ifdef IP_RECVDSTADDR - PyModule_AddIntConstant(m, "IP_RECVDSTADDR", IP_RECVDSTADDR); +#ifdef IP_RECVDSTADDR + PyModule_AddIntConstant(m, "IP_RECVDSTADDR", IP_RECVDSTADDR); #endif -#ifdef IP_RETOPTS - PyModule_AddIntConstant(m, "IP_RETOPTS", IP_RETOPTS); +#ifdef IP_RETOPTS + PyModule_AddIntConstant(m, "IP_RETOPTS", IP_RETOPTS); #endif -#ifdef IP_MULTICAST_IF - PyModule_AddIntConstant(m, "IP_MULTICAST_IF", IP_MULTICAST_IF); +#ifdef IP_MULTICAST_IF + PyModule_AddIntConstant(m, "IP_MULTICAST_IF", IP_MULTICAST_IF); #endif -#ifdef IP_MULTICAST_TTL - PyModule_AddIntConstant(m, "IP_MULTICAST_TTL", IP_MULTICAST_TTL); +#ifdef IP_MULTICAST_TTL + PyModule_AddIntConstant(m, "IP_MULTICAST_TTL", IP_MULTICAST_TTL); #endif -#ifdef IP_MULTICAST_LOOP - PyModule_AddIntConstant(m, "IP_MULTICAST_LOOP", IP_MULTICAST_LOOP); +#ifdef IP_MULTICAST_LOOP + PyModule_AddIntConstant(m, "IP_MULTICAST_LOOP", IP_MULTICAST_LOOP); #endif -#ifdef IP_ADD_MEMBERSHIP - PyModule_AddIntConstant(m, "IP_ADD_MEMBERSHIP", IP_ADD_MEMBERSHIP); +#ifdef IP_ADD_MEMBERSHIP + PyModule_AddIntConstant(m, "IP_ADD_MEMBERSHIP", IP_ADD_MEMBERSHIP); #endif -#ifdef IP_DROP_MEMBERSHIP - PyModule_AddIntConstant(m, "IP_DROP_MEMBERSHIP", IP_DROP_MEMBERSHIP); +#ifdef IP_DROP_MEMBERSHIP + PyModule_AddIntConstant(m, "IP_DROP_MEMBERSHIP", IP_DROP_MEMBERSHIP); #endif -#ifdef IP_DEFAULT_MULTICAST_TTL - PyModule_AddIntConstant(m, "IP_DEFAULT_MULTICAST_TTL", - IP_DEFAULT_MULTICAST_TTL); +#ifdef IP_DEFAULT_MULTICAST_TTL + PyModule_AddIntConstant(m, "IP_DEFAULT_MULTICAST_TTL", + IP_DEFAULT_MULTICAST_TTL); #endif -#ifdef IP_DEFAULT_MULTICAST_LOOP - PyModule_AddIntConstant(m, "IP_DEFAULT_MULTICAST_LOOP", - IP_DEFAULT_MULTICAST_LOOP); +#ifdef IP_DEFAULT_MULTICAST_LOOP + PyModule_AddIntConstant(m, "IP_DEFAULT_MULTICAST_LOOP", + IP_DEFAULT_MULTICAST_LOOP); #endif -#ifdef IP_MAX_MEMBERSHIPS - PyModule_AddIntConstant(m, "IP_MAX_MEMBERSHIPS", IP_MAX_MEMBERSHIPS); +#ifdef IP_MAX_MEMBERSHIPS + PyModule_AddIntConstant(m, "IP_MAX_MEMBERSHIPS", IP_MAX_MEMBERSHIPS); #endif - /* IPv6 [gs]etsockopt options, defined in RFC2553 */ -#ifdef IPV6_JOIN_GROUP - PyModule_AddIntConstant(m, "IPV6_JOIN_GROUP", IPV6_JOIN_GROUP); + /* IPv6 [gs]etsockopt options, defined in RFC2553 */ +#ifdef IPV6_JOIN_GROUP + PyModule_AddIntConstant(m, "IPV6_JOIN_GROUP", IPV6_JOIN_GROUP); #endif -#ifdef IPV6_LEAVE_GROUP - PyModule_AddIntConstant(m, "IPV6_LEAVE_GROUP", IPV6_LEAVE_GROUP); +#ifdef IPV6_LEAVE_GROUP + PyModule_AddIntConstant(m, "IPV6_LEAVE_GROUP", IPV6_LEAVE_GROUP); #endif -#ifdef IPV6_MULTICAST_HOPS - PyModule_AddIntConstant(m, "IPV6_MULTICAST_HOPS", IPV6_MULTICAST_HOPS); +#ifdef IPV6_MULTICAST_HOPS + PyModule_AddIntConstant(m, "IPV6_MULTICAST_HOPS", IPV6_MULTICAST_HOPS); #endif -#ifdef IPV6_MULTICAST_IF - PyModule_AddIntConstant(m, "IPV6_MULTICAST_IF", IPV6_MULTICAST_IF); +#ifdef IPV6_MULTICAST_IF + PyModule_AddIntConstant(m, "IPV6_MULTICAST_IF", IPV6_MULTICAST_IF); #endif -#ifdef IPV6_MULTICAST_LOOP - PyModule_AddIntConstant(m, "IPV6_MULTICAST_LOOP", IPV6_MULTICAST_LOOP); +#ifdef IPV6_MULTICAST_LOOP + PyModule_AddIntConstant(m, "IPV6_MULTICAST_LOOP", IPV6_MULTICAST_LOOP); #endif -#ifdef IPV6_UNICAST_HOPS - PyModule_AddIntConstant(m, "IPV6_UNICAST_HOPS", IPV6_UNICAST_HOPS); +#ifdef IPV6_UNICAST_HOPS + PyModule_AddIntConstant(m, "IPV6_UNICAST_HOPS", IPV6_UNICAST_HOPS); #endif - /* Additional IPV6 socket options, defined in RFC 3493 */ + /* Additional IPV6 socket options, defined in RFC 3493 */ #ifdef IPV6_V6ONLY - PyModule_AddIntConstant(m, "IPV6_V6ONLY", IPV6_V6ONLY); + PyModule_AddIntConstant(m, "IPV6_V6ONLY", IPV6_V6ONLY); #endif - /* Advanced IPV6 socket options, from RFC 3542 */ + /* Advanced IPV6 socket options, from RFC 3542 */ #ifdef IPV6_CHECKSUM - PyModule_AddIntConstant(m, "IPV6_CHECKSUM", IPV6_CHECKSUM); + PyModule_AddIntConstant(m, "IPV6_CHECKSUM", IPV6_CHECKSUM); #endif #ifdef IPV6_DONTFRAG - PyModule_AddIntConstant(m, "IPV6_DONTFRAG", IPV6_DONTFRAG); + PyModule_AddIntConstant(m, "IPV6_DONTFRAG", IPV6_DONTFRAG); #endif #ifdef IPV6_DSTOPTS - PyModule_AddIntConstant(m, "IPV6_DSTOPTS", IPV6_DSTOPTS); + PyModule_AddIntConstant(m, "IPV6_DSTOPTS", IPV6_DSTOPTS); #endif #ifdef IPV6_HOPLIMIT - PyModule_AddIntConstant(m, "IPV6_HOPLIMIT", IPV6_HOPLIMIT); + PyModule_AddIntConstant(m, "IPV6_HOPLIMIT", IPV6_HOPLIMIT); #endif #ifdef IPV6_HOPOPTS - PyModule_AddIntConstant(m, "IPV6_HOPOPTS", IPV6_HOPOPTS); + PyModule_AddIntConstant(m, "IPV6_HOPOPTS", IPV6_HOPOPTS); #endif #ifdef IPV6_NEXTHOP - PyModule_AddIntConstant(m, "IPV6_NEXTHOP", IPV6_NEXTHOP); + PyModule_AddIntConstant(m, "IPV6_NEXTHOP", IPV6_NEXTHOP); #endif #ifdef IPV6_PATHMTU - PyModule_AddIntConstant(m, "IPV6_PATHMTU", IPV6_PATHMTU); + PyModule_AddIntConstant(m, "IPV6_PATHMTU", IPV6_PATHMTU); #endif #ifdef IPV6_PKTINFO - PyModule_AddIntConstant(m, "IPV6_PKTINFO", IPV6_PKTINFO); + PyModule_AddIntConstant(m, "IPV6_PKTINFO", IPV6_PKTINFO); #endif #ifdef IPV6_RECVDSTOPTS - PyModule_AddIntConstant(m, "IPV6_RECVDSTOPTS", IPV6_RECVDSTOPTS); + PyModule_AddIntConstant(m, "IPV6_RECVDSTOPTS", IPV6_RECVDSTOPTS); #endif #ifdef IPV6_RECVHOPLIMIT - PyModule_AddIntConstant(m, "IPV6_RECVHOPLIMIT", IPV6_RECVHOPLIMIT); + PyModule_AddIntConstant(m, "IPV6_RECVHOPLIMIT", IPV6_RECVHOPLIMIT); #endif #ifdef IPV6_RECVHOPOPTS - PyModule_AddIntConstant(m, "IPV6_RECVHOPOPTS", IPV6_RECVHOPOPTS); + PyModule_AddIntConstant(m, "IPV6_RECVHOPOPTS", IPV6_RECVHOPOPTS); #endif #ifdef IPV6_RECVPKTINFO - PyModule_AddIntConstant(m, "IPV6_RECVPKTINFO", IPV6_RECVPKTINFO); + PyModule_AddIntConstant(m, "IPV6_RECVPKTINFO", IPV6_RECVPKTINFO); #endif #ifdef IPV6_RECVRTHDR - PyModule_AddIntConstant(m, "IPV6_RECVRTHDR", IPV6_RECVRTHDR); + PyModule_AddIntConstant(m, "IPV6_RECVRTHDR", IPV6_RECVRTHDR); #endif #ifdef IPV6_RECVTCLASS - PyModule_AddIntConstant(m, "IPV6_RECVTCLASS", IPV6_RECVTCLASS); + PyModule_AddIntConstant(m, "IPV6_RECVTCLASS", IPV6_RECVTCLASS); #endif #ifdef IPV6_RTHDR - PyModule_AddIntConstant(m, "IPV6_RTHDR", IPV6_RTHDR); + PyModule_AddIntConstant(m, "IPV6_RTHDR", IPV6_RTHDR); #endif #ifdef IPV6_RTHDRDSTOPTS - PyModule_AddIntConstant(m, "IPV6_RTHDRDSTOPTS", IPV6_RTHDRDSTOPTS); + PyModule_AddIntConstant(m, "IPV6_RTHDRDSTOPTS", IPV6_RTHDRDSTOPTS); #endif #ifdef IPV6_RTHDR_TYPE_0 - PyModule_AddIntConstant(m, "IPV6_RTHDR_TYPE_0", IPV6_RTHDR_TYPE_0); + PyModule_AddIntConstant(m, "IPV6_RTHDR_TYPE_0", IPV6_RTHDR_TYPE_0); #endif #ifdef IPV6_RECVPATHMTU - PyModule_AddIntConstant(m, "IPV6_RECVPATHMTU", IPV6_RECVPATHMTU); + PyModule_AddIntConstant(m, "IPV6_RECVPATHMTU", IPV6_RECVPATHMTU); #endif #ifdef IPV6_TCLASS - PyModule_AddIntConstant(m, "IPV6_TCLASS", IPV6_TCLASS); + PyModule_AddIntConstant(m, "IPV6_TCLASS", IPV6_TCLASS); #endif #ifdef IPV6_USE_MIN_MTU - PyModule_AddIntConstant(m, "IPV6_USE_MIN_MTU", IPV6_USE_MIN_MTU); + PyModule_AddIntConstant(m, "IPV6_USE_MIN_MTU", IPV6_USE_MIN_MTU); #endif - /* TCP options */ -#ifdef TCP_NODELAY - PyModule_AddIntConstant(m, "TCP_NODELAY", TCP_NODELAY); + /* TCP options */ +#ifdef TCP_NODELAY + PyModule_AddIntConstant(m, "TCP_NODELAY", TCP_NODELAY); #endif -#ifdef TCP_MAXSEG - PyModule_AddIntConstant(m, "TCP_MAXSEG", TCP_MAXSEG); +#ifdef TCP_MAXSEG + PyModule_AddIntConstant(m, "TCP_MAXSEG", TCP_MAXSEG); #endif -#ifdef TCP_CORK - PyModule_AddIntConstant(m, "TCP_CORK", TCP_CORK); +#ifdef TCP_CORK + PyModule_AddIntConstant(m, "TCP_CORK", TCP_CORK); #endif -#ifdef TCP_KEEPIDLE - PyModule_AddIntConstant(m, "TCP_KEEPIDLE", TCP_KEEPIDLE); +#ifdef TCP_KEEPIDLE + PyModule_AddIntConstant(m, "TCP_KEEPIDLE", TCP_KEEPIDLE); #endif -#ifdef TCP_KEEPINTVL - PyModule_AddIntConstant(m, "TCP_KEEPINTVL", TCP_KEEPINTVL); +#ifdef TCP_KEEPINTVL + PyModule_AddIntConstant(m, "TCP_KEEPINTVL", TCP_KEEPINTVL); #endif -#ifdef TCP_KEEPCNT - PyModule_AddIntConstant(m, "TCP_KEEPCNT", TCP_KEEPCNT); +#ifdef TCP_KEEPCNT + PyModule_AddIntConstant(m, "TCP_KEEPCNT", TCP_KEEPCNT); #endif -#ifdef TCP_SYNCNT - PyModule_AddIntConstant(m, "TCP_SYNCNT", TCP_SYNCNT); +#ifdef TCP_SYNCNT + PyModule_AddIntConstant(m, "TCP_SYNCNT", TCP_SYNCNT); #endif -#ifdef TCP_LINGER2 - PyModule_AddIntConstant(m, "TCP_LINGER2", TCP_LINGER2); +#ifdef TCP_LINGER2 + PyModule_AddIntConstant(m, "TCP_LINGER2", TCP_LINGER2); #endif -#ifdef TCP_DEFER_ACCEPT - PyModule_AddIntConstant(m, "TCP_DEFER_ACCEPT", TCP_DEFER_ACCEPT); +#ifdef TCP_DEFER_ACCEPT + PyModule_AddIntConstant(m, "TCP_DEFER_ACCEPT", TCP_DEFER_ACCEPT); #endif -#ifdef TCP_WINDOW_CLAMP - PyModule_AddIntConstant(m, "TCP_WINDOW_CLAMP", TCP_WINDOW_CLAMP); +#ifdef TCP_WINDOW_CLAMP + PyModule_AddIntConstant(m, "TCP_WINDOW_CLAMP", TCP_WINDOW_CLAMP); #endif -#ifdef TCP_INFO - PyModule_AddIntConstant(m, "TCP_INFO", TCP_INFO); +#ifdef TCP_INFO + PyModule_AddIntConstant(m, "TCP_INFO", TCP_INFO); #endif -#ifdef TCP_QUICKACK - PyModule_AddIntConstant(m, "TCP_QUICKACK", TCP_QUICKACK); +#ifdef TCP_QUICKACK + PyModule_AddIntConstant(m, "TCP_QUICKACK", TCP_QUICKACK); #endif - /* IPX options */ -#ifdef IPX_TYPE - PyModule_AddIntConstant(m, "IPX_TYPE", IPX_TYPE); + /* IPX options */ +#ifdef IPX_TYPE + PyModule_AddIntConstant(m, "IPX_TYPE", IPX_TYPE); #endif - /* get{addr,name}info parameters */ + /* get{addr,name}info parameters */ #ifdef EAI_ADDRFAMILY - PyModule_AddIntConstant(m, "EAI_ADDRFAMILY", EAI_ADDRFAMILY); + PyModule_AddIntConstant(m, "EAI_ADDRFAMILY", EAI_ADDRFAMILY); #endif #ifdef EAI_AGAIN - PyModule_AddIntConstant(m, "EAI_AGAIN", EAI_AGAIN); + PyModule_AddIntConstant(m, "EAI_AGAIN", EAI_AGAIN); #endif #ifdef EAI_BADFLAGS - PyModule_AddIntConstant(m, "EAI_BADFLAGS", EAI_BADFLAGS); + PyModule_AddIntConstant(m, "EAI_BADFLAGS", EAI_BADFLAGS); #endif #ifdef EAI_FAIL - PyModule_AddIntConstant(m, "EAI_FAIL", EAI_FAIL); + PyModule_AddIntConstant(m, "EAI_FAIL", EAI_FAIL); #endif #ifdef EAI_FAMILY - PyModule_AddIntConstant(m, "EAI_FAMILY", EAI_FAMILY); + PyModule_AddIntConstant(m, "EAI_FAMILY", EAI_FAMILY); #endif #ifdef EAI_MEMORY - PyModule_AddIntConstant(m, "EAI_MEMORY", EAI_MEMORY); + PyModule_AddIntConstant(m, "EAI_MEMORY", EAI_MEMORY); #endif #ifdef EAI_NODATA - PyModule_AddIntConstant(m, "EAI_NODATA", EAI_NODATA); + PyModule_AddIntConstant(m, "EAI_NODATA", EAI_NODATA); #endif #ifdef EAI_NONAME - PyModule_AddIntConstant(m, "EAI_NONAME", EAI_NONAME); + PyModule_AddIntConstant(m, "EAI_NONAME", EAI_NONAME); #endif #ifdef EAI_OVERFLOW - PyModule_AddIntConstant(m, "EAI_OVERFLOW", EAI_OVERFLOW); + PyModule_AddIntConstant(m, "EAI_OVERFLOW", EAI_OVERFLOW); #endif #ifdef EAI_SERVICE - PyModule_AddIntConstant(m, "EAI_SERVICE", EAI_SERVICE); + PyModule_AddIntConstant(m, "EAI_SERVICE", EAI_SERVICE); #endif #ifdef EAI_SOCKTYPE - PyModule_AddIntConstant(m, "EAI_SOCKTYPE", EAI_SOCKTYPE); + PyModule_AddIntConstant(m, "EAI_SOCKTYPE", EAI_SOCKTYPE); #endif #ifdef EAI_SYSTEM - PyModule_AddIntConstant(m, "EAI_SYSTEM", EAI_SYSTEM); + PyModule_AddIntConstant(m, "EAI_SYSTEM", EAI_SYSTEM); #endif #ifdef EAI_BADHINTS - PyModule_AddIntConstant(m, "EAI_BADHINTS", EAI_BADHINTS); + PyModule_AddIntConstant(m, "EAI_BADHINTS", EAI_BADHINTS); #endif #ifdef EAI_PROTOCOL - PyModule_AddIntConstant(m, "EAI_PROTOCOL", EAI_PROTOCOL); + PyModule_AddIntConstant(m, "EAI_PROTOCOL", EAI_PROTOCOL); #endif #ifdef EAI_MAX - PyModule_AddIntConstant(m, "EAI_MAX", EAI_MAX); + PyModule_AddIntConstant(m, "EAI_MAX", EAI_MAX); #endif #ifdef AI_PASSIVE - PyModule_AddIntConstant(m, "AI_PASSIVE", AI_PASSIVE); + PyModule_AddIntConstant(m, "AI_PASSIVE", AI_PASSIVE); #endif #ifdef AI_CANONNAME - PyModule_AddIntConstant(m, "AI_CANONNAME", AI_CANONNAME); + PyModule_AddIntConstant(m, "AI_CANONNAME", AI_CANONNAME); #endif #ifdef AI_NUMERICHOST - PyModule_AddIntConstant(m, "AI_NUMERICHOST", AI_NUMERICHOST); + PyModule_AddIntConstant(m, "AI_NUMERICHOST", AI_NUMERICHOST); #endif #ifdef AI_NUMERICSERV - PyModule_AddIntConstant(m, "AI_NUMERICSERV", AI_NUMERICSERV); + PyModule_AddIntConstant(m, "AI_NUMERICSERV", AI_NUMERICSERV); #endif #ifdef AI_MASK - PyModule_AddIntConstant(m, "AI_MASK", AI_MASK); + PyModule_AddIntConstant(m, "AI_MASK", AI_MASK); #endif #ifdef AI_ALL - PyModule_AddIntConstant(m, "AI_ALL", AI_ALL); + PyModule_AddIntConstant(m, "AI_ALL", AI_ALL); #endif #ifdef AI_V4MAPPED_CFG - PyModule_AddIntConstant(m, "AI_V4MAPPED_CFG", AI_V4MAPPED_CFG); + PyModule_AddIntConstant(m, "AI_V4MAPPED_CFG", AI_V4MAPPED_CFG); #endif #ifdef AI_ADDRCONFIG - PyModule_AddIntConstant(m, "AI_ADDRCONFIG", AI_ADDRCONFIG); + PyModule_AddIntConstant(m, "AI_ADDRCONFIG", AI_ADDRCONFIG); #endif #ifdef AI_V4MAPPED - PyModule_AddIntConstant(m, "AI_V4MAPPED", AI_V4MAPPED); + PyModule_AddIntConstant(m, "AI_V4MAPPED", AI_V4MAPPED); #endif #ifdef AI_DEFAULT - PyModule_AddIntConstant(m, "AI_DEFAULT", AI_DEFAULT); + PyModule_AddIntConstant(m, "AI_DEFAULT", AI_DEFAULT); #endif #ifdef NI_MAXHOST - PyModule_AddIntConstant(m, "NI_MAXHOST", NI_MAXHOST); + PyModule_AddIntConstant(m, "NI_MAXHOST", NI_MAXHOST); #endif #ifdef NI_MAXSERV - PyModule_AddIntConstant(m, "NI_MAXSERV", NI_MAXSERV); + PyModule_AddIntConstant(m, "NI_MAXSERV", NI_MAXSERV); #endif #ifdef NI_NOFQDN - PyModule_AddIntConstant(m, "NI_NOFQDN", NI_NOFQDN); + PyModule_AddIntConstant(m, "NI_NOFQDN", NI_NOFQDN); #endif #ifdef NI_NUMERICHOST - PyModule_AddIntConstant(m, "NI_NUMERICHOST", NI_NUMERICHOST); + PyModule_AddIntConstant(m, "NI_NUMERICHOST", NI_NUMERICHOST); #endif #ifdef NI_NAMEREQD - PyModule_AddIntConstant(m, "NI_NAMEREQD", NI_NAMEREQD); + PyModule_AddIntConstant(m, "NI_NAMEREQD", NI_NAMEREQD); #endif #ifdef NI_NUMERICSERV - PyModule_AddIntConstant(m, "NI_NUMERICSERV", NI_NUMERICSERV); + PyModule_AddIntConstant(m, "NI_NUMERICSERV", NI_NUMERICSERV); #endif #ifdef NI_DGRAM - PyModule_AddIntConstant(m, "NI_DGRAM", NI_DGRAM); + PyModule_AddIntConstant(m, "NI_DGRAM", NI_DGRAM); #endif - /* shutdown() parameters */ + /* shutdown() parameters */ #ifdef SHUT_RD - PyModule_AddIntConstant(m, "SHUT_RD", SHUT_RD); + PyModule_AddIntConstant(m, "SHUT_RD", SHUT_RD); #elif defined(SD_RECEIVE) - PyModule_AddIntConstant(m, "SHUT_RD", SD_RECEIVE); + PyModule_AddIntConstant(m, "SHUT_RD", SD_RECEIVE); #else - PyModule_AddIntConstant(m, "SHUT_RD", 0); + PyModule_AddIntConstant(m, "SHUT_RD", 0); #endif #ifdef SHUT_WR - PyModule_AddIntConstant(m, "SHUT_WR", SHUT_WR); + PyModule_AddIntConstant(m, "SHUT_WR", SHUT_WR); #elif defined(SD_SEND) - PyModule_AddIntConstant(m, "SHUT_WR", SD_SEND); + PyModule_AddIntConstant(m, "SHUT_WR", SD_SEND); #else - PyModule_AddIntConstant(m, "SHUT_WR", 1); + PyModule_AddIntConstant(m, "SHUT_WR", 1); #endif #ifdef SHUT_RDWR - PyModule_AddIntConstant(m, "SHUT_RDWR", SHUT_RDWR); + PyModule_AddIntConstant(m, "SHUT_RDWR", SHUT_RDWR); #elif defined(SD_BOTH) - PyModule_AddIntConstant(m, "SHUT_RDWR", SD_BOTH); + PyModule_AddIntConstant(m, "SHUT_RDWR", SD_BOTH); #else - PyModule_AddIntConstant(m, "SHUT_RDWR", 2); + PyModule_AddIntConstant(m, "SHUT_RDWR", 2); #endif #ifdef SIO_RCVALL - { - DWORD codes[] = {SIO_RCVALL, SIO_KEEPALIVE_VALS}; - const char *names[] = {"SIO_RCVALL", "SIO_KEEPALIVE_VALS"}; - int i; - for(i = 0; i /* VC6 is shipped with old platform headers, and does not have MSTcpIP.h * Separate SDKs have all the functions we want, but older ones don't have - * any version information. + * any version information. * I use SIO_GET_MULTICAST_FILTER to detect a decent SDK. */ # ifdef SIO_GET_MULTICAST_FILTER @@ -76,44 +76,44 @@ #endif /* Python module and C API name */ -#define PySocket_MODULE_NAME "_socket" -#define PySocket_CAPI_NAME "CAPI" -#define PySocket_CAPSULE_NAME PySocket_MODULE_NAME "." PySocket_CAPI_NAME +#define PySocket_MODULE_NAME "_socket" +#define PySocket_CAPI_NAME "CAPI" +#define PySocket_CAPSULE_NAME PySocket_MODULE_NAME "." PySocket_CAPI_NAME /* Abstract the socket file descriptor type */ #ifdef MS_WINDOWS typedef SOCKET SOCKET_T; -# ifdef MS_WIN64 -# define SIZEOF_SOCKET_T 8 -# else -# define SIZEOF_SOCKET_T 4 -# endif +# ifdef MS_WIN64 +# define SIZEOF_SOCKET_T 8 +# else +# define SIZEOF_SOCKET_T 4 +# endif #else typedef int SOCKET_T; -# define SIZEOF_SOCKET_T SIZEOF_INT +# define SIZEOF_SOCKET_T SIZEOF_INT #endif /* Socket address */ typedef union sock_addr { - struct sockaddr_in in; + struct sockaddr_in in; #ifdef AF_UNIX - struct sockaddr_un un; + struct sockaddr_un un; #endif #ifdef AF_NETLINK - struct sockaddr_nl nl; + struct sockaddr_nl nl; #endif #ifdef ENABLE_IPV6 - struct sockaddr_in6 in6; - struct sockaddr_storage storage; + struct sockaddr_in6 in6; + struct sockaddr_storage storage; #endif #ifdef HAVE_BLUETOOTH_BLUETOOTH_H - struct sockaddr_l2 bt_l2; - struct sockaddr_rc bt_rc; - struct sockaddr_sco bt_sco; - struct sockaddr_hci bt_hci; + struct sockaddr_l2 bt_l2; + struct sockaddr_rc bt_rc; + struct sockaddr_sco bt_sco; + struct sockaddr_hci bt_hci; #endif #ifdef HAVE_NETPACKET_PACKET_H - struct sockaddr_ll ll; + struct sockaddr_ll ll; #endif } sock_addr_t; @@ -122,16 +122,16 @@ arguments properly. */ typedef struct { - PyObject_HEAD - SOCKET_T sock_fd; /* Socket file descriptor */ - int sock_family; /* Address family, e.g., AF_INET */ - int sock_type; /* Socket type, e.g., SOCK_STREAM */ - int sock_proto; /* Protocol type, usually 0 */ - PyObject *(*errorhandler)(void); /* Error handler; checks - errno, returns NULL and - sets a Python exception */ - double sock_timeout; /* Operation timeout in seconds; - 0.0 means non-blocking */ + PyObject_HEAD + SOCKET_T sock_fd; /* Socket file descriptor */ + int sock_family; /* Address family, e.g., AF_INET */ + int sock_type; /* Socket type, e.g., SOCK_STREAM */ + int sock_proto; /* Protocol type, usually 0 */ + PyObject *(*errorhandler)(void); /* Error handler; checks + errno, returns NULL and + sets a Python exception */ + double sock_timeout; /* Operation timeout in seconds; + 0.0 means non-blocking */ } PySocketSockObject; /* --- C API ----------------------------------------------------*/ @@ -139,7 +139,7 @@ /* Short explanation of what this C API export mechanism does and how it works: - The _ssl module needs access to the type object defined in + The _ssl module needs access to the type object defined in the _socket module. Since cross-DLL linking introduces a lot of problems on many platforms, the "trick" is to wrap the C API of a module in a struct which then gets exported to @@ -161,24 +161,24 @@ Load _socket module and its C API; this sets up the global PySocketModule: - - if (PySocketModule_ImportModuleAndAPI()) - return; + + if (PySocketModule_ImportModuleAndAPI()) + return; Now use the C API as if it were defined in the using module: - if (!PyArg_ParseTuple(args, "O!|zz:ssl", + if (!PyArg_ParseTuple(args, "O!|zz:ssl", - PySocketModule.Sock_Type, + PySocketModule.Sock_Type, - (PyObject*)&Sock, - &key_file, &cert_file)) - return NULL; + (PyObject*)&Sock, + &key_file, &cert_file)) + return NULL; Support could easily be extended to export more C APIs/symbols - this way. Currently, only the type object is exported, + this way. Currently, only the type object is exported, other candidates would be socket constructors and socket access functions. @@ -186,8 +186,8 @@ /* C API for usage by other Python modules */ typedef struct { - PyTypeObject *Sock_Type; - PyObject *error; + PyTypeObject *Sock_Type; + PyObject *error; } PySocketModule_APIObject; #define PySocketModule_ImportModuleAndAPI() PyCapsule_Import(PySocket_CAPSULE_NAME, 1) Modified: python/branches/py3k/Modules/spwdmodule.c ============================================================================== --- python/branches/py3k/Modules/spwdmodule.c (original) +++ python/branches/py3k/Modules/spwdmodule.c Sun May 9 17:52:27 2010 @@ -27,16 +27,16 @@ #if defined(HAVE_GETSPNAM) || defined(HAVE_GETSPENT) static PyStructSequence_Field struct_spwd_type_fields[] = { - {"sp_nam", "login name"}, - {"sp_pwd", "encrypted password"}, - {"sp_lstchg", "date of last change"}, - {"sp_min", "min #days between changes"}, - {"sp_max", "max #days between changes"}, - {"sp_warn", "#days before pw expires to warn user about it"}, - {"sp_inact", "#days after pw expires until account is blocked"}, - {"sp_expire", "#days since 1970-01-01 until account is disabled"}, - {"sp_flag", "reserved"}, - {0} + {"sp_nam", "login name"}, + {"sp_pwd", "encrypted password"}, + {"sp_lstchg", "date of last change"}, + {"sp_min", "min #days between changes"}, + {"sp_max", "max #days between changes"}, + {"sp_warn", "#days before pw expires to warn user about it"}, + {"sp_inact", "#days after pw expires until account is blocked"}, + {"sp_expire", "#days since 1970-01-01 until account is disabled"}, + {"sp_flag", "reserved"}, + {0} }; PyDoc_STRVAR(struct_spwd__doc__, @@ -46,10 +46,10 @@ or via the object attributes as named in the above tuple."); static PyStructSequence_Desc struct_spwd_type_desc = { - "spwd.struct_spwd", - struct_spwd__doc__, - struct_spwd_type_fields, - 9, + "spwd.struct_spwd", + struct_spwd__doc__, + struct_spwd_type_fields, + 9, }; static int initialized; @@ -60,43 +60,43 @@ sets(PyObject *v, int i, const char* val) { if (val) { - PyObject *o = PyUnicode_DecodeFSDefault(val); - PyStructSequence_SET_ITEM(v, i, o); + PyObject *o = PyUnicode_DecodeFSDefault(val); + PyStructSequence_SET_ITEM(v, i, o); } else { - PyStructSequence_SET_ITEM(v, i, Py_None); - Py_INCREF(Py_None); + PyStructSequence_SET_ITEM(v, i, Py_None); + Py_INCREF(Py_None); } } static PyObject *mkspent(struct spwd *p) { - int setIndex = 0; - PyObject *v = PyStructSequence_New(&StructSpwdType); - if (v == NULL) - return NULL; + int setIndex = 0; + PyObject *v = PyStructSequence_New(&StructSpwdType); + if (v == NULL) + return NULL; #define SETI(i,val) PyStructSequence_SET_ITEM(v, i, PyLong_FromLong((long) val)) #define SETS(i,val) sets(v, i, val) - SETS(setIndex++, p->sp_namp); - SETS(setIndex++, p->sp_pwdp); - SETI(setIndex++, p->sp_lstchg); - SETI(setIndex++, p->sp_min); - SETI(setIndex++, p->sp_max); - SETI(setIndex++, p->sp_warn); - SETI(setIndex++, p->sp_inact); - SETI(setIndex++, p->sp_expire); - SETI(setIndex++, p->sp_flag); + SETS(setIndex++, p->sp_namp); + SETS(setIndex++, p->sp_pwdp); + SETI(setIndex++, p->sp_lstchg); + SETI(setIndex++, p->sp_min); + SETI(setIndex++, p->sp_max); + SETI(setIndex++, p->sp_warn); + SETI(setIndex++, p->sp_inact); + SETI(setIndex++, p->sp_expire); + SETI(setIndex++, p->sp_flag); #undef SETS #undef SETI - if (PyErr_Occurred()) { - Py_DECREF(v); - return NULL; - } + if (PyErr_Occurred()) { + Py_DECREF(v); + return NULL; + } - return v; + return v; } #endif /* HAVE_GETSPNAM || HAVE_GETSPENT */ @@ -112,26 +112,26 @@ static PyObject* spwd_getspnam(PyObject *self, PyObject *args) { - char *name; - struct spwd *p; - PyObject *arg, *bytes, *retval = NULL; - - if (!PyArg_ParseTuple(args, "U:getspnam", &arg)) - return NULL; - if ((bytes = PyUnicode_AsEncodedString(arg, - Py_FileSystemDefaultEncoding, - "surrogateescape")) == NULL) - return NULL; - if (PyBytes_AsStringAndSize(bytes, &name, NULL) == -1) - goto out; - if ((p = getspnam(name)) == NULL) { - PyErr_SetString(PyExc_KeyError, "getspnam(): name not found"); - goto out; - } - retval = mkspent(p); + char *name; + struct spwd *p; + PyObject *arg, *bytes, *retval = NULL; + + if (!PyArg_ParseTuple(args, "U:getspnam", &arg)) + return NULL; + if ((bytes = PyUnicode_AsEncodedString(arg, + Py_FileSystemDefaultEncoding, + "surrogateescape")) == NULL) + return NULL; + if (PyBytes_AsStringAndSize(bytes, &name, NULL) == -1) + goto out; + if ((p = getspnam(name)) == NULL) { + PyErr_SetString(PyExc_KeyError, "getspnam(): name not found"); + goto out; + } + retval = mkspent(p); out: - Py_DECREF(bytes); - return retval; + Py_DECREF(bytes); + return retval; } #endif /* HAVE_GETSPNAM */ @@ -147,63 +147,63 @@ static PyObject * spwd_getspall(PyObject *self, PyObject *args) { - PyObject *d; - struct spwd *p; - if ((d = PyList_New(0)) == NULL) - return NULL; - setspent(); - while ((p = getspent()) != NULL) { - PyObject *v = mkspent(p); - if (v == NULL || PyList_Append(d, v) != 0) { - Py_XDECREF(v); - Py_DECREF(d); - endspent(); - return NULL; - } - Py_DECREF(v); - } - endspent(); - return d; + PyObject *d; + struct spwd *p; + if ((d = PyList_New(0)) == NULL) + return NULL; + setspent(); + while ((p = getspent()) != NULL) { + PyObject *v = mkspent(p); + if (v == NULL || PyList_Append(d, v) != 0) { + Py_XDECREF(v); + Py_DECREF(d); + endspent(); + return NULL; + } + Py_DECREF(v); + } + endspent(); + return d; } #endif /* HAVE_GETSPENT */ static PyMethodDef spwd_methods[] = { -#ifdef HAVE_GETSPNAM - {"getspnam", spwd_getspnam, METH_VARARGS, spwd_getspnam__doc__}, +#ifdef HAVE_GETSPNAM + {"getspnam", spwd_getspnam, METH_VARARGS, spwd_getspnam__doc__}, #endif #ifdef HAVE_GETSPENT - {"getspall", spwd_getspall, METH_NOARGS, spwd_getspall__doc__}, + {"getspall", spwd_getspall, METH_NOARGS, spwd_getspall__doc__}, #endif - {NULL, NULL} /* sentinel */ + {NULL, NULL} /* sentinel */ }; static struct PyModuleDef spwdmodule = { - PyModuleDef_HEAD_INIT, - "spwd", - spwd__doc__, - -1, - spwd_methods, - NULL, - NULL, - NULL, - NULL + PyModuleDef_HEAD_INIT, + "spwd", + spwd__doc__, + -1, + spwd_methods, + NULL, + NULL, + NULL, + NULL }; PyMODINIT_FUNC PyInit_spwd(void) { - PyObject *m; - m=PyModule_Create(&spwdmodule); - if (m == NULL) - return NULL; - if (!initialized) - PyStructSequence_InitType(&StructSpwdType, - &struct_spwd_type_desc); - Py_INCREF((PyObject *) &StructSpwdType); - PyModule_AddObject(m, "struct_spwd", (PyObject *) &StructSpwdType); - initialized = 1; - return m; + PyObject *m; + m=PyModule_Create(&spwdmodule); + if (m == NULL) + return NULL; + if (!initialized) + PyStructSequence_InitType(&StructSpwdType, + &struct_spwd_type_desc); + Py_INCREF((PyObject *) &StructSpwdType); + PyModule_AddObject(m, "struct_spwd", (PyObject *) &StructSpwdType); + initialized = 1; + return m; } Modified: python/branches/py3k/Modules/symtablemodule.c ============================================================================== --- python/branches/py3k/Modules/symtablemodule.c (original) +++ python/branches/py3k/Modules/symtablemodule.c Sun May 9 17:52:27 2010 @@ -8,93 +8,93 @@ static PyObject * symtable_symtable(PyObject *self, PyObject *args) { - struct symtable *st; - PyObject *t; + struct symtable *st; + PyObject *t; - char *str; - char *filename; - char *startstr; - int start; - - if (!PyArg_ParseTuple(args, "sss:symtable", &str, &filename, - &startstr)) - return NULL; - if (strcmp(startstr, "exec") == 0) - start = Py_file_input; - else if (strcmp(startstr, "eval") == 0) - start = Py_eval_input; - else if (strcmp(startstr, "single") == 0) - start = Py_single_input; - else { - PyErr_SetString(PyExc_ValueError, - "symtable() arg 3 must be 'exec' or 'eval' or 'single'"); - return NULL; - } - st = Py_SymtableString(str, filename, start); - if (st == NULL) - return NULL; - t = st->st_blocks; - Py_INCREF(t); - PyMem_Free((void *)st->st_future); - PySymtable_Free(st); - return t; + char *str; + char *filename; + char *startstr; + int start; + + if (!PyArg_ParseTuple(args, "sss:symtable", &str, &filename, + &startstr)) + return NULL; + if (strcmp(startstr, "exec") == 0) + start = Py_file_input; + else if (strcmp(startstr, "eval") == 0) + start = Py_eval_input; + else if (strcmp(startstr, "single") == 0) + start = Py_single_input; + else { + PyErr_SetString(PyExc_ValueError, + "symtable() arg 3 must be 'exec' or 'eval' or 'single'"); + return NULL; + } + st = Py_SymtableString(str, filename, start); + if (st == NULL) + return NULL; + t = st->st_blocks; + Py_INCREF(t); + PyMem_Free((void *)st->st_future); + PySymtable_Free(st); + return t; } static PyMethodDef symtable_methods[] = { - {"symtable", symtable_symtable, METH_VARARGS, - PyDoc_STR("Return symbol and scope dictionaries" - " used internally by compiler.")}, - {NULL, NULL} /* sentinel */ + {"symtable", symtable_symtable, METH_VARARGS, + PyDoc_STR("Return symbol and scope dictionaries" + " used internally by compiler.")}, + {NULL, NULL} /* sentinel */ }; static struct PyModuleDef symtablemodule = { - PyModuleDef_HEAD_INIT, - "_symtable", - NULL, - -1, - symtable_methods, - NULL, - NULL, - NULL, - NULL + PyModuleDef_HEAD_INIT, + "_symtable", + NULL, + -1, + symtable_methods, + NULL, + NULL, + NULL, + NULL }; PyMODINIT_FUNC PyInit__symtable(void) { - PyObject *m; + PyObject *m; - m = PyModule_Create(&symtablemodule); - if (m == NULL) - return NULL; - PyModule_AddIntConstant(m, "USE", USE); - PyModule_AddIntConstant(m, "DEF_GLOBAL", DEF_GLOBAL); - PyModule_AddIntConstant(m, "DEF_LOCAL", DEF_LOCAL); - PyModule_AddIntConstant(m, "DEF_PARAM", DEF_PARAM); - PyModule_AddIntConstant(m, "DEF_FREE", DEF_FREE); - PyModule_AddIntConstant(m, "DEF_FREE_CLASS", DEF_FREE_CLASS); - PyModule_AddIntConstant(m, "DEF_IMPORT", DEF_IMPORT); - PyModule_AddIntConstant(m, "DEF_BOUND", DEF_BOUND); - - PyModule_AddIntConstant(m, "TYPE_FUNCTION", FunctionBlock); - PyModule_AddIntConstant(m, "TYPE_CLASS", ClassBlock); - PyModule_AddIntConstant(m, "TYPE_MODULE", ModuleBlock); - - PyModule_AddIntConstant(m, "OPT_IMPORT_STAR", OPT_IMPORT_STAR); - PyModule_AddIntConstant(m, "OPT_TOPLEVEL", OPT_TOPLEVEL); - - PyModule_AddIntConstant(m, "LOCAL", LOCAL); - PyModule_AddIntConstant(m, "GLOBAL_EXPLICIT", GLOBAL_EXPLICIT); - PyModule_AddIntConstant(m, "GLOBAL_IMPLICIT", GLOBAL_IMPLICIT); - PyModule_AddIntConstant(m, "FREE", FREE); - PyModule_AddIntConstant(m, "CELL", CELL); - - PyModule_AddIntConstant(m, "SCOPE_OFF", SCOPE_OFFSET); - PyModule_AddIntConstant(m, "SCOPE_MASK", SCOPE_MASK); - - if (PyErr_Occurred()) { - Py_DECREF(m); - m = 0; - } - return m; + m = PyModule_Create(&symtablemodule); + if (m == NULL) + return NULL; + PyModule_AddIntConstant(m, "USE", USE); + PyModule_AddIntConstant(m, "DEF_GLOBAL", DEF_GLOBAL); + PyModule_AddIntConstant(m, "DEF_LOCAL", DEF_LOCAL); + PyModule_AddIntConstant(m, "DEF_PARAM", DEF_PARAM); + PyModule_AddIntConstant(m, "DEF_FREE", DEF_FREE); + PyModule_AddIntConstant(m, "DEF_FREE_CLASS", DEF_FREE_CLASS); + PyModule_AddIntConstant(m, "DEF_IMPORT", DEF_IMPORT); + PyModule_AddIntConstant(m, "DEF_BOUND", DEF_BOUND); + + PyModule_AddIntConstant(m, "TYPE_FUNCTION", FunctionBlock); + PyModule_AddIntConstant(m, "TYPE_CLASS", ClassBlock); + PyModule_AddIntConstant(m, "TYPE_MODULE", ModuleBlock); + + PyModule_AddIntConstant(m, "OPT_IMPORT_STAR", OPT_IMPORT_STAR); + PyModule_AddIntConstant(m, "OPT_TOPLEVEL", OPT_TOPLEVEL); + + PyModule_AddIntConstant(m, "LOCAL", LOCAL); + PyModule_AddIntConstant(m, "GLOBAL_EXPLICIT", GLOBAL_EXPLICIT); + PyModule_AddIntConstant(m, "GLOBAL_IMPLICIT", GLOBAL_IMPLICIT); + PyModule_AddIntConstant(m, "FREE", FREE); + PyModule_AddIntConstant(m, "CELL", CELL); + + PyModule_AddIntConstant(m, "SCOPE_OFF", SCOPE_OFFSET); + PyModule_AddIntConstant(m, "SCOPE_MASK", SCOPE_MASK); + + if (PyErr_Occurred()) { + Py_DECREF(m); + m = 0; + } + return m; } Modified: python/branches/py3k/Modules/syslogmodule.c ============================================================================== --- python/branches/py3k/Modules/syslogmodule.c (original) +++ python/branches/py3k/Modules/syslogmodule.c Sun May 9 17:52:27 2010 @@ -4,20 +4,20 @@ All Rights Reserved -Permission to use, copy, modify, and distribute this software and its -documentation for any purpose and without fee is hereby granted, +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 +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 +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 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 +FITNESS, IN NO EVENT SHALL LANCE ELLINGHOUSE 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. ******************************************************************/ @@ -55,272 +55,272 @@ #include /* only one instance, only one syslog, so globals should be ok */ -static PyObject *S_ident_o = NULL; /* identifier, held by openlog() */ +static PyObject *S_ident_o = NULL; /* identifier, held by openlog() */ static char S_log_open = 0; static PyObject * syslog_get_argv(void) { - /* Figure out what to use for as the program "ident" for openlog(). - * This swallows exceptions and continues rather than failing out, - * because the syslog module can still be used because openlog(3) - * is optional. - */ - - Py_ssize_t argv_len; - PyObject *scriptobj; - char *atslash; - PyObject *argv = PySys_GetObject("argv"); - - if (argv == NULL) { - return(NULL); - } - - argv_len = PyList_Size(argv); - if (argv_len == -1) { - PyErr_Clear(); - return(NULL); - } - if (argv_len == 0) { - return(NULL); - } - - scriptobj = PyList_GetItem(argv, 0); - if (!PyUnicode_Check(scriptobj)) { - return(NULL); - } - if (PyUnicode_GET_SIZE(scriptobj) == 0) { - return(NULL); - } - - atslash = strrchr(_PyUnicode_AsString(scriptobj), SEP); - if (atslash) { - return(PyUnicode_FromString(atslash + 1)); - } else { - Py_INCREF(scriptobj); - return(scriptobj); - } + /* Figure out what to use for as the program "ident" for openlog(). + * This swallows exceptions and continues rather than failing out, + * because the syslog module can still be used because openlog(3) + * is optional. + */ + + Py_ssize_t argv_len; + PyObject *scriptobj; + char *atslash; + PyObject *argv = PySys_GetObject("argv"); + + if (argv == NULL) { + return(NULL); + } + + argv_len = PyList_Size(argv); + if (argv_len == -1) { + PyErr_Clear(); + return(NULL); + } + if (argv_len == 0) { + return(NULL); + } + + scriptobj = PyList_GetItem(argv, 0); + if (!PyUnicode_Check(scriptobj)) { + return(NULL); + } + if (PyUnicode_GET_SIZE(scriptobj) == 0) { + return(NULL); + } + + atslash = strrchr(_PyUnicode_AsString(scriptobj), SEP); + if (atslash) { + return(PyUnicode_FromString(atslash + 1)); + } else { + Py_INCREF(scriptobj); + return(scriptobj); + } - return(NULL); + return(NULL); } -static PyObject * +static PyObject * syslog_openlog(PyObject * self, PyObject * args, PyObject *kwds) { - long logopt = 0; - long facility = LOG_USER; - PyObject *new_S_ident_o = NULL; - static char *keywords[] = {"ident", "logoption", "facility", 0}; - - if (!PyArg_ParseTupleAndKeywords(args, kwds, - "|Ull:openlog", keywords, &new_S_ident_o, &logopt, &facility)) - return NULL; - - if (new_S_ident_o) { - Py_INCREF(new_S_ident_o); - } - - /* get sys.argv[0] or NULL if we can't for some reason */ - if (!new_S_ident_o) { - new_S_ident_o = syslog_get_argv(); - } - - Py_XDECREF(S_ident_o); - S_ident_o = new_S_ident_o; - - /* At this point, S_ident_o should be INCREF()ed. openlog(3) does not - * make a copy, and syslog(3) later uses it. We can't garbagecollect it - * If NULL, just let openlog figure it out (probably using C argv[0]). - */ - - openlog(S_ident_o ? _PyUnicode_AsString(S_ident_o) : NULL, logopt, facility); - S_log_open = 1; + long logopt = 0; + long facility = LOG_USER; + PyObject *new_S_ident_o = NULL; + static char *keywords[] = {"ident", "logoption", "facility", 0}; + + if (!PyArg_ParseTupleAndKeywords(args, kwds, + "|Ull:openlog", keywords, &new_S_ident_o, &logopt, &facility)) + return NULL; + + if (new_S_ident_o) { + Py_INCREF(new_S_ident_o); + } + + /* get sys.argv[0] or NULL if we can't for some reason */ + if (!new_S_ident_o) { + new_S_ident_o = syslog_get_argv(); + } + + Py_XDECREF(S_ident_o); + S_ident_o = new_S_ident_o; + + /* At this point, S_ident_o should be INCREF()ed. openlog(3) does not + * make a copy, and syslog(3) later uses it. We can't garbagecollect it + * If NULL, just let openlog figure it out (probably using C argv[0]). + */ + + openlog(S_ident_o ? _PyUnicode_AsString(S_ident_o) : NULL, logopt, facility); + S_log_open = 1; - Py_INCREF(Py_None); - return Py_None; + Py_INCREF(Py_None); + return Py_None; } -static PyObject * +static PyObject * syslog_syslog(PyObject * self, PyObject * args) { - PyObject *message_object; - const char *message; - int priority = LOG_INFO; - - if (!PyArg_ParseTuple(args, "iU;[priority,] message string", - &priority, &message_object)) { - PyErr_Clear(); - if (!PyArg_ParseTuple(args, "U;[priority,] message string", - &message_object)) - return NULL; - } - - message = _PyUnicode_AsString(message_object); - if (message == NULL) - return NULL; - - /* if log is not opened, open it now */ - if (!S_log_open) { - PyObject *openargs; - - /* Continue even if PyTuple_New fails, because openlog(3) is optional. - * So, we can still do loggin in the unlikely event things are so hosed - * that we can't do this tuple. - */ - if ((openargs = PyTuple_New(0))) { - PyObject *openlog_ret = syslog_openlog(self, openargs, NULL); - Py_XDECREF(openlog_ret); - Py_DECREF(openargs); - } - } - - Py_BEGIN_ALLOW_THREADS; - syslog(priority, "%s", message); - Py_END_ALLOW_THREADS; - Py_RETURN_NONE; + PyObject *message_object; + const char *message; + int priority = LOG_INFO; + + if (!PyArg_ParseTuple(args, "iU;[priority,] message string", + &priority, &message_object)) { + PyErr_Clear(); + if (!PyArg_ParseTuple(args, "U;[priority,] message string", + &message_object)) + return NULL; + } + + message = _PyUnicode_AsString(message_object); + if (message == NULL) + return NULL; + + /* if log is not opened, open it now */ + if (!S_log_open) { + PyObject *openargs; + + /* Continue even if PyTuple_New fails, because openlog(3) is optional. + * So, we can still do loggin in the unlikely event things are so hosed + * that we can't do this tuple. + */ + if ((openargs = PyTuple_New(0))) { + PyObject *openlog_ret = syslog_openlog(self, openargs, NULL); + Py_XDECREF(openlog_ret); + Py_DECREF(openargs); + } + } + + Py_BEGIN_ALLOW_THREADS; + syslog(priority, "%s", message); + Py_END_ALLOW_THREADS; + Py_RETURN_NONE; } -static PyObject * +static PyObject * syslog_closelog(PyObject *self, PyObject *unused) { - if (S_log_open) { - closelog(); - Py_XDECREF(S_ident_o); - S_ident_o = NULL; - S_log_open = 0; - } - Py_INCREF(Py_None); - return Py_None; + if (S_log_open) { + closelog(); + Py_XDECREF(S_ident_o); + S_ident_o = NULL; + S_log_open = 0; + } + Py_INCREF(Py_None); + return Py_None; } -static PyObject * +static PyObject * syslog_setlogmask(PyObject *self, PyObject *args) { - long maskpri, omaskpri; + long maskpri, omaskpri; - if (!PyArg_ParseTuple(args, "l;mask for priority", &maskpri)) - return NULL; - omaskpri = setlogmask(maskpri); - return PyLong_FromLong(omaskpri); + if (!PyArg_ParseTuple(args, "l;mask for priority", &maskpri)) + return NULL; + omaskpri = setlogmask(maskpri); + return PyLong_FromLong(omaskpri); } -static PyObject * +static PyObject * syslog_log_mask(PyObject *self, PyObject *args) { - long mask; - long pri; - if (!PyArg_ParseTuple(args, "l:LOG_MASK", &pri)) - return NULL; - mask = LOG_MASK(pri); - return PyLong_FromLong(mask); + long mask; + long pri; + if (!PyArg_ParseTuple(args, "l:LOG_MASK", &pri)) + return NULL; + mask = LOG_MASK(pri); + return PyLong_FromLong(mask); } -static PyObject * +static PyObject * syslog_log_upto(PyObject *self, PyObject *args) { - long mask; - long pri; - if (!PyArg_ParseTuple(args, "l:LOG_UPTO", &pri)) - return NULL; - mask = LOG_UPTO(pri); - return PyLong_FromLong(mask); + long mask; + long pri; + if (!PyArg_ParseTuple(args, "l:LOG_UPTO", &pri)) + return NULL; + mask = LOG_UPTO(pri); + return PyLong_FromLong(mask); } /* List of functions defined in the module */ static PyMethodDef syslog_methods[] = { - {"openlog", (PyCFunction) syslog_openlog, METH_VARARGS | METH_KEYWORDS}, - {"closelog", syslog_closelog, METH_NOARGS}, - {"syslog", syslog_syslog, METH_VARARGS}, - {"setlogmask", syslog_setlogmask, METH_VARARGS}, - {"LOG_MASK", syslog_log_mask, METH_VARARGS}, - {"LOG_UPTO", syslog_log_upto, METH_VARARGS}, - {NULL, NULL, 0} + {"openlog", (PyCFunction) syslog_openlog, METH_VARARGS | METH_KEYWORDS}, + {"closelog", syslog_closelog, METH_NOARGS}, + {"syslog", syslog_syslog, METH_VARARGS}, + {"setlogmask", syslog_setlogmask, METH_VARARGS}, + {"LOG_MASK", syslog_log_mask, METH_VARARGS}, + {"LOG_UPTO", syslog_log_upto, METH_VARARGS}, + {NULL, NULL, 0} }; /* Initialization function for the module */ static struct PyModuleDef syslogmodule = { - PyModuleDef_HEAD_INIT, - "syslog", - NULL, - -1, - syslog_methods, - NULL, - NULL, - NULL, - NULL + PyModuleDef_HEAD_INIT, + "syslog", + NULL, + -1, + syslog_methods, + NULL, + NULL, + NULL, + NULL }; PyMODINIT_FUNC PyInit_syslog(void) { - PyObject *m; + PyObject *m; - /* Create the module and add the functions */ - m = PyModule_Create(&syslogmodule); - if (m == NULL) - return NULL; - - /* Add some symbolic constants to the module */ - - /* Priorities */ - PyModule_AddIntConstant(m, "LOG_EMERG", LOG_EMERG); - PyModule_AddIntConstant(m, "LOG_ALERT", LOG_ALERT); - PyModule_AddIntConstant(m, "LOG_CRIT", LOG_CRIT); - PyModule_AddIntConstant(m, "LOG_ERR", LOG_ERR); - PyModule_AddIntConstant(m, "LOG_WARNING", LOG_WARNING); - PyModule_AddIntConstant(m, "LOG_NOTICE", LOG_NOTICE); - PyModule_AddIntConstant(m, "LOG_INFO", LOG_INFO); - PyModule_AddIntConstant(m, "LOG_DEBUG", LOG_DEBUG); - - /* openlog() option flags */ - PyModule_AddIntConstant(m, "LOG_PID", LOG_PID); - PyModule_AddIntConstant(m, "LOG_CONS", LOG_CONS); - PyModule_AddIntConstant(m, "LOG_NDELAY", LOG_NDELAY); + /* Create the module and add the functions */ + m = PyModule_Create(&syslogmodule); + if (m == NULL) + return NULL; + + /* Add some symbolic constants to the module */ + + /* Priorities */ + PyModule_AddIntConstant(m, "LOG_EMERG", LOG_EMERG); + PyModule_AddIntConstant(m, "LOG_ALERT", LOG_ALERT); + PyModule_AddIntConstant(m, "LOG_CRIT", LOG_CRIT); + PyModule_AddIntConstant(m, "LOG_ERR", LOG_ERR); + PyModule_AddIntConstant(m, "LOG_WARNING", LOG_WARNING); + PyModule_AddIntConstant(m, "LOG_NOTICE", LOG_NOTICE); + PyModule_AddIntConstant(m, "LOG_INFO", LOG_INFO); + PyModule_AddIntConstant(m, "LOG_DEBUG", LOG_DEBUG); + + /* openlog() option flags */ + PyModule_AddIntConstant(m, "LOG_PID", LOG_PID); + PyModule_AddIntConstant(m, "LOG_CONS", LOG_CONS); + PyModule_AddIntConstant(m, "LOG_NDELAY", LOG_NDELAY); #ifdef LOG_NOWAIT - PyModule_AddIntConstant(m, "LOG_NOWAIT", LOG_NOWAIT); + PyModule_AddIntConstant(m, "LOG_NOWAIT", LOG_NOWAIT); #endif #ifdef LOG_PERROR - PyModule_AddIntConstant(m, "LOG_PERROR", LOG_PERROR); + PyModule_AddIntConstant(m, "LOG_PERROR", LOG_PERROR); #endif - /* Facilities */ - PyModule_AddIntConstant(m, "LOG_KERN", LOG_KERN); - PyModule_AddIntConstant(m, "LOG_USER", LOG_USER); - PyModule_AddIntConstant(m, "LOG_MAIL", LOG_MAIL); - PyModule_AddIntConstant(m, "LOG_DAEMON", LOG_DAEMON); - PyModule_AddIntConstant(m, "LOG_AUTH", LOG_AUTH); - PyModule_AddIntConstant(m, "LOG_LPR", LOG_LPR); - PyModule_AddIntConstant(m, "LOG_LOCAL0", LOG_LOCAL0); - PyModule_AddIntConstant(m, "LOG_LOCAL1", LOG_LOCAL1); - PyModule_AddIntConstant(m, "LOG_LOCAL2", LOG_LOCAL2); - PyModule_AddIntConstant(m, "LOG_LOCAL3", LOG_LOCAL3); - PyModule_AddIntConstant(m, "LOG_LOCAL4", LOG_LOCAL4); - PyModule_AddIntConstant(m, "LOG_LOCAL5", LOG_LOCAL5); - PyModule_AddIntConstant(m, "LOG_LOCAL6", LOG_LOCAL6); - PyModule_AddIntConstant(m, "LOG_LOCAL7", LOG_LOCAL7); + /* Facilities */ + PyModule_AddIntConstant(m, "LOG_KERN", LOG_KERN); + PyModule_AddIntConstant(m, "LOG_USER", LOG_USER); + PyModule_AddIntConstant(m, "LOG_MAIL", LOG_MAIL); + PyModule_AddIntConstant(m, "LOG_DAEMON", LOG_DAEMON); + PyModule_AddIntConstant(m, "LOG_AUTH", LOG_AUTH); + PyModule_AddIntConstant(m, "LOG_LPR", LOG_LPR); + PyModule_AddIntConstant(m, "LOG_LOCAL0", LOG_LOCAL0); + PyModule_AddIntConstant(m, "LOG_LOCAL1", LOG_LOCAL1); + PyModule_AddIntConstant(m, "LOG_LOCAL2", LOG_LOCAL2); + PyModule_AddIntConstant(m, "LOG_LOCAL3", LOG_LOCAL3); + PyModule_AddIntConstant(m, "LOG_LOCAL4", LOG_LOCAL4); + PyModule_AddIntConstant(m, "LOG_LOCAL5", LOG_LOCAL5); + PyModule_AddIntConstant(m, "LOG_LOCAL6", LOG_LOCAL6); + PyModule_AddIntConstant(m, "LOG_LOCAL7", LOG_LOCAL7); #ifndef LOG_SYSLOG -#define LOG_SYSLOG LOG_DAEMON +#define LOG_SYSLOG LOG_DAEMON #endif #ifndef LOG_NEWS -#define LOG_NEWS LOG_MAIL +#define LOG_NEWS LOG_MAIL #endif #ifndef LOG_UUCP -#define LOG_UUCP LOG_MAIL +#define LOG_UUCP LOG_MAIL #endif #ifndef LOG_CRON -#define LOG_CRON LOG_DAEMON +#define LOG_CRON LOG_DAEMON #endif - PyModule_AddIntConstant(m, "LOG_SYSLOG", LOG_SYSLOG); - PyModule_AddIntConstant(m, "LOG_CRON", LOG_CRON); - PyModule_AddIntConstant(m, "LOG_UUCP", LOG_UUCP); - PyModule_AddIntConstant(m, "LOG_NEWS", LOG_NEWS); - return m; + PyModule_AddIntConstant(m, "LOG_SYSLOG", LOG_SYSLOG); + PyModule_AddIntConstant(m, "LOG_CRON", LOG_CRON); + PyModule_AddIntConstant(m, "LOG_UUCP", LOG_UUCP); + PyModule_AddIntConstant(m, "LOG_NEWS", LOG_NEWS); + return m; } Modified: python/branches/py3k/Modules/termios.c ============================================================================== --- python/branches/py3k/Modules/termios.c (original) +++ python/branches/py3k/Modules/termios.c Sun May 9 17:52:27 2010 @@ -42,14 +42,14 @@ static int fdconv(PyObject* obj, void* p) { - int fd; + int fd; - fd = PyObject_AsFileDescriptor(obj); - if (fd >= 0) { - *(int*)p = fd; - return 1; - } - return 0; + fd = PyObject_AsFileDescriptor(obj); + if (fd >= 0) { + *(int*)p = fd; + return 1; + } + return 0; } PyDoc_STRVAR(termios_tcgetattr__doc__, @@ -66,67 +66,67 @@ static PyObject * termios_tcgetattr(PyObject *self, PyObject *args) { - int fd; - struct termios mode; - PyObject *cc; - speed_t ispeed, ospeed; - PyObject *v; - int i; - char ch; - - if (!PyArg_ParseTuple(args, "O&:tcgetattr", - fdconv, (void*)&fd)) - return NULL; - - if (tcgetattr(fd, &mode) == -1) - return PyErr_SetFromErrno(TermiosError); - - ispeed = cfgetispeed(&mode); - ospeed = cfgetospeed(&mode); - - cc = PyList_New(NCCS); - if (cc == NULL) - return NULL; - for (i = 0; i < NCCS; i++) { - ch = (char)mode.c_cc[i]; - v = PyBytes_FromStringAndSize(&ch, 1); - if (v == NULL) - goto err; - PyList_SetItem(cc, i, v); - } - - /* Convert the MIN and TIME slots to integer. On some systems, the - MIN and TIME slots are the same as the EOF and EOL slots. So we - only do this in noncanonical input mode. */ - if ((mode.c_lflag & ICANON) == 0) { - v = PyLong_FromLong((long)mode.c_cc[VMIN]); - if (v == NULL) - goto err; - PyList_SetItem(cc, VMIN, v); - v = PyLong_FromLong((long)mode.c_cc[VTIME]); - if (v == NULL) - goto err; - PyList_SetItem(cc, VTIME, v); - } - - if (!(v = PyList_New(7))) - goto err; - - PyList_SetItem(v, 0, PyLong_FromLong((long)mode.c_iflag)); - PyList_SetItem(v, 1, PyLong_FromLong((long)mode.c_oflag)); - PyList_SetItem(v, 2, PyLong_FromLong((long)mode.c_cflag)); - PyList_SetItem(v, 3, PyLong_FromLong((long)mode.c_lflag)); - PyList_SetItem(v, 4, PyLong_FromLong((long)ispeed)); - PyList_SetItem(v, 5, PyLong_FromLong((long)ospeed)); - PyList_SetItem(v, 6, cc); - if (PyErr_Occurred()){ - Py_DECREF(v); - goto err; - } - return v; + int fd; + struct termios mode; + PyObject *cc; + speed_t ispeed, ospeed; + PyObject *v; + int i; + char ch; + + if (!PyArg_ParseTuple(args, "O&:tcgetattr", + fdconv, (void*)&fd)) + return NULL; + + if (tcgetattr(fd, &mode) == -1) + return PyErr_SetFromErrno(TermiosError); + + ispeed = cfgetispeed(&mode); + ospeed = cfgetospeed(&mode); + + cc = PyList_New(NCCS); + if (cc == NULL) + return NULL; + for (i = 0; i < NCCS; i++) { + ch = (char)mode.c_cc[i]; + v = PyBytes_FromStringAndSize(&ch, 1); + if (v == NULL) + goto err; + PyList_SetItem(cc, i, v); + } + + /* Convert the MIN and TIME slots to integer. On some systems, the + MIN and TIME slots are the same as the EOF and EOL slots. So we + only do this in noncanonical input mode. */ + if ((mode.c_lflag & ICANON) == 0) { + v = PyLong_FromLong((long)mode.c_cc[VMIN]); + if (v == NULL) + goto err; + PyList_SetItem(cc, VMIN, v); + v = PyLong_FromLong((long)mode.c_cc[VTIME]); + if (v == NULL) + goto err; + PyList_SetItem(cc, VTIME, v); + } + + if (!(v = PyList_New(7))) + goto err; + + PyList_SetItem(v, 0, PyLong_FromLong((long)mode.c_iflag)); + PyList_SetItem(v, 1, PyLong_FromLong((long)mode.c_oflag)); + PyList_SetItem(v, 2, PyLong_FromLong((long)mode.c_cflag)); + PyList_SetItem(v, 3, PyLong_FromLong((long)mode.c_lflag)); + PyList_SetItem(v, 4, PyLong_FromLong((long)ispeed)); + PyList_SetItem(v, 5, PyLong_FromLong((long)ospeed)); + PyList_SetItem(v, 6, cc); + if (PyErr_Occurred()){ + Py_DECREF(v); + goto err; + } + return v; err: - Py_DECREF(cc); - return NULL; + Py_DECREF(cc); + return NULL; } PyDoc_STRVAR(termios_tcsetattr__doc__, @@ -143,64 +143,64 @@ static PyObject * termios_tcsetattr(PyObject *self, PyObject *args) { - int fd, when; - struct termios mode; - speed_t ispeed, ospeed; - PyObject *term, *cc, *v; - int i; - - if (!PyArg_ParseTuple(args, "O&iO:tcsetattr", - fdconv, &fd, &when, &term)) - return NULL; - if (!PyList_Check(term) || PyList_Size(term) != 7) { - PyErr_SetString(PyExc_TypeError, - "tcsetattr, arg 3: must be 7 element list"); - return NULL; - } - - /* Get the old mode, in case there are any hidden fields... */ - if (tcgetattr(fd, &mode) == -1) - return PyErr_SetFromErrno(TermiosError); - mode.c_iflag = (tcflag_t) PyLong_AsLong(PyList_GetItem(term, 0)); - mode.c_oflag = (tcflag_t) PyLong_AsLong(PyList_GetItem(term, 1)); - mode.c_cflag = (tcflag_t) PyLong_AsLong(PyList_GetItem(term, 2)); - mode.c_lflag = (tcflag_t) PyLong_AsLong(PyList_GetItem(term, 3)); - ispeed = (speed_t) PyLong_AsLong(PyList_GetItem(term, 4)); - ospeed = (speed_t) PyLong_AsLong(PyList_GetItem(term, 5)); - cc = PyList_GetItem(term, 6); - if (PyErr_Occurred()) - return NULL; - - if (!PyList_Check(cc) || PyList_Size(cc) != NCCS) { - PyErr_Format(PyExc_TypeError, - "tcsetattr: attributes[6] must be %d element list", - NCCS); - return NULL; - } - - for (i = 0; i < NCCS; i++) { - v = PyList_GetItem(cc, i); - - if (PyBytes_Check(v) && PyBytes_Size(v) == 1) - mode.c_cc[i] = (cc_t) * PyBytes_AsString(v); - else if (PyLong_Check(v)) - mode.c_cc[i] = (cc_t) PyLong_AsLong(v); - else { - PyErr_SetString(PyExc_TypeError, + int fd, when; + struct termios mode; + speed_t ispeed, ospeed; + PyObject *term, *cc, *v; + int i; + + if (!PyArg_ParseTuple(args, "O&iO:tcsetattr", + fdconv, &fd, &when, &term)) + return NULL; + if (!PyList_Check(term) || PyList_Size(term) != 7) { + PyErr_SetString(PyExc_TypeError, + "tcsetattr, arg 3: must be 7 element list"); + return NULL; + } + + /* Get the old mode, in case there are any hidden fields... */ + if (tcgetattr(fd, &mode) == -1) + return PyErr_SetFromErrno(TermiosError); + mode.c_iflag = (tcflag_t) PyLong_AsLong(PyList_GetItem(term, 0)); + mode.c_oflag = (tcflag_t) PyLong_AsLong(PyList_GetItem(term, 1)); + mode.c_cflag = (tcflag_t) PyLong_AsLong(PyList_GetItem(term, 2)); + mode.c_lflag = (tcflag_t) PyLong_AsLong(PyList_GetItem(term, 3)); + ispeed = (speed_t) PyLong_AsLong(PyList_GetItem(term, 4)); + ospeed = (speed_t) PyLong_AsLong(PyList_GetItem(term, 5)); + cc = PyList_GetItem(term, 6); + if (PyErr_Occurred()) + return NULL; + + if (!PyList_Check(cc) || PyList_Size(cc) != NCCS) { + PyErr_Format(PyExc_TypeError, + "tcsetattr: attributes[6] must be %d element list", + NCCS); + return NULL; + } + + for (i = 0; i < NCCS; i++) { + v = PyList_GetItem(cc, i); + + if (PyBytes_Check(v) && PyBytes_Size(v) == 1) + mode.c_cc[i] = (cc_t) * PyBytes_AsString(v); + else if (PyLong_Check(v)) + mode.c_cc[i] = (cc_t) PyLong_AsLong(v); + else { + PyErr_SetString(PyExc_TypeError, "tcsetattr: elements of attributes must be characters or integers"); - return NULL; - } - } - - if (cfsetispeed(&mode, (speed_t) ispeed) == -1) - return PyErr_SetFromErrno(TermiosError); - if (cfsetospeed(&mode, (speed_t) ospeed) == -1) - return PyErr_SetFromErrno(TermiosError); - if (tcsetattr(fd, when, &mode) == -1) - return PyErr_SetFromErrno(TermiosError); + return NULL; + } + } + + if (cfsetispeed(&mode, (speed_t) ispeed) == -1) + return PyErr_SetFromErrno(TermiosError); + if (cfsetospeed(&mode, (speed_t) ospeed) == -1) + return PyErr_SetFromErrno(TermiosError); + if (tcsetattr(fd, when, &mode) == -1) + return PyErr_SetFromErrno(TermiosError); - Py_INCREF(Py_None); - return Py_None; + Py_INCREF(Py_None); + return Py_None; } PyDoc_STRVAR(termios_tcsendbreak__doc__, @@ -213,16 +213,16 @@ static PyObject * termios_tcsendbreak(PyObject *self, PyObject *args) { - int fd, duration; + int fd, duration; - if (!PyArg_ParseTuple(args, "O&i:tcsendbreak", - fdconv, &fd, &duration)) - return NULL; - if (tcsendbreak(fd, duration) == -1) - return PyErr_SetFromErrno(TermiosError); + if (!PyArg_ParseTuple(args, "O&i:tcsendbreak", + fdconv, &fd, &duration)) + return NULL; + if (tcsendbreak(fd, duration) == -1) + return PyErr_SetFromErrno(TermiosError); - Py_INCREF(Py_None); - return Py_None; + Py_INCREF(Py_None); + return Py_None; } PyDoc_STRVAR(termios_tcdrain__doc__, @@ -233,16 +233,16 @@ static PyObject * termios_tcdrain(PyObject *self, PyObject *args) { - int fd; + int fd; - if (!PyArg_ParseTuple(args, "O&:tcdrain", - fdconv, &fd)) - return NULL; - if (tcdrain(fd) == -1) - return PyErr_SetFromErrno(TermiosError); + if (!PyArg_ParseTuple(args, "O&:tcdrain", + fdconv, &fd)) + return NULL; + if (tcdrain(fd) == -1) + return PyErr_SetFromErrno(TermiosError); - Py_INCREF(Py_None); - return Py_None; + Py_INCREF(Py_None); + return Py_None; } PyDoc_STRVAR(termios_tcflush__doc__, @@ -256,16 +256,16 @@ static PyObject * termios_tcflush(PyObject *self, PyObject *args) { - int fd, queue; + int fd, queue; - if (!PyArg_ParseTuple(args, "O&i:tcflush", - fdconv, &fd, &queue)) - return NULL; - if (tcflush(fd, queue) == -1) - return PyErr_SetFromErrno(TermiosError); + if (!PyArg_ParseTuple(args, "O&i:tcflush", + fdconv, &fd, &queue)) + return NULL; + if (tcflush(fd, queue) == -1) + return PyErr_SetFromErrno(TermiosError); - Py_INCREF(Py_None); - return Py_None; + Py_INCREF(Py_None); + return Py_None; } PyDoc_STRVAR(termios_tcflow__doc__, @@ -279,33 +279,33 @@ static PyObject * termios_tcflow(PyObject *self, PyObject *args) { - int fd, action; + int fd, action; - if (!PyArg_ParseTuple(args, "O&i:tcflow", - fdconv, &fd, &action)) - return NULL; - if (tcflow(fd, action) == -1) - return PyErr_SetFromErrno(TermiosError); + if (!PyArg_ParseTuple(args, "O&i:tcflow", + fdconv, &fd, &action)) + return NULL; + if (tcflow(fd, action) == -1) + return PyErr_SetFromErrno(TermiosError); - Py_INCREF(Py_None); - return Py_None; + Py_INCREF(Py_None); + return Py_None; } static PyMethodDef termios_methods[] = { - {"tcgetattr", termios_tcgetattr, - METH_VARARGS, termios_tcgetattr__doc__}, - {"tcsetattr", termios_tcsetattr, - METH_VARARGS, termios_tcsetattr__doc__}, - {"tcsendbreak", termios_tcsendbreak, - METH_VARARGS, termios_tcsendbreak__doc__}, - {"tcdrain", termios_tcdrain, - METH_VARARGS, termios_tcdrain__doc__}, - {"tcflush", termios_tcflush, - METH_VARARGS, termios_tcflush__doc__}, - {"tcflow", termios_tcflow, - METH_VARARGS, termios_tcflow__doc__}, - {NULL, NULL} + {"tcgetattr", termios_tcgetattr, + METH_VARARGS, termios_tcgetattr__doc__}, + {"tcsetattr", termios_tcsetattr, + METH_VARARGS, termios_tcsetattr__doc__}, + {"tcsendbreak", termios_tcsendbreak, + METH_VARARGS, termios_tcsendbreak__doc__}, + {"tcdrain", termios_tcdrain, + METH_VARARGS, termios_tcdrain__doc__}, + {"tcflush", termios_tcflush, + METH_VARARGS, termios_tcflush__doc__}, + {"tcflow", termios_tcflow, + METH_VARARGS, termios_tcflow__doc__}, + {NULL, NULL} }; @@ -318,622 +318,622 @@ #endif static struct constant { - char *name; - long value; + char *name; + long value; } termios_constants[] = { - /* cfgetospeed(), cfsetospeed() constants */ - {"B0", B0}, - {"B50", B50}, - {"B75", B75}, - {"B110", B110}, - {"B134", B134}, - {"B150", B150}, - {"B200", B200}, - {"B300", B300}, - {"B600", B600}, - {"B1200", B1200}, - {"B1800", B1800}, - {"B2400", B2400}, - {"B4800", B4800}, - {"B9600", B9600}, - {"B19200", B19200}, - {"B38400", B38400}, + /* cfgetospeed(), cfsetospeed() constants */ + {"B0", B0}, + {"B50", B50}, + {"B75", B75}, + {"B110", B110}, + {"B134", B134}, + {"B150", B150}, + {"B200", B200}, + {"B300", B300}, + {"B600", B600}, + {"B1200", B1200}, + {"B1800", B1800}, + {"B2400", B2400}, + {"B4800", B4800}, + {"B9600", B9600}, + {"B19200", B19200}, + {"B38400", B38400}, #ifdef B57600 - {"B57600", B57600}, + {"B57600", B57600}, #endif #ifdef B115200 - {"B115200", B115200}, + {"B115200", B115200}, #endif #ifdef B230400 - {"B230400", B230400}, + {"B230400", B230400}, #endif #ifdef CBAUDEX - {"CBAUDEX", CBAUDEX}, + {"CBAUDEX", CBAUDEX}, #endif - /* tcsetattr() constants */ - {"TCSANOW", TCSANOW}, - {"TCSADRAIN", TCSADRAIN}, - {"TCSAFLUSH", TCSAFLUSH}, + /* tcsetattr() constants */ + {"TCSANOW", TCSANOW}, + {"TCSADRAIN", TCSADRAIN}, + {"TCSAFLUSH", TCSAFLUSH}, #ifdef TCSASOFT - {"TCSASOFT", TCSASOFT}, + {"TCSASOFT", TCSASOFT}, #endif - /* tcflush() constants */ - {"TCIFLUSH", TCIFLUSH}, - {"TCOFLUSH", TCOFLUSH}, - {"TCIOFLUSH", TCIOFLUSH}, - - /* tcflow() constants */ - {"TCOOFF", TCOOFF}, - {"TCOON", TCOON}, - {"TCIOFF", TCIOFF}, - {"TCION", TCION}, - - /* struct termios.c_iflag constants */ - {"IGNBRK", IGNBRK}, - {"BRKINT", BRKINT}, - {"IGNPAR", IGNPAR}, - {"PARMRK", PARMRK}, - {"INPCK", INPCK}, - {"ISTRIP", ISTRIP}, - {"INLCR", INLCR}, - {"IGNCR", IGNCR}, - {"ICRNL", ICRNL}, + /* tcflush() constants */ + {"TCIFLUSH", TCIFLUSH}, + {"TCOFLUSH", TCOFLUSH}, + {"TCIOFLUSH", TCIOFLUSH}, + + /* tcflow() constants */ + {"TCOOFF", TCOOFF}, + {"TCOON", TCOON}, + {"TCIOFF", TCIOFF}, + {"TCION", TCION}, + + /* struct termios.c_iflag constants */ + {"IGNBRK", IGNBRK}, + {"BRKINT", BRKINT}, + {"IGNPAR", IGNPAR}, + {"PARMRK", PARMRK}, + {"INPCK", INPCK}, + {"ISTRIP", ISTRIP}, + {"INLCR", INLCR}, + {"IGNCR", IGNCR}, + {"ICRNL", ICRNL}, #ifdef IUCLC - {"IUCLC", IUCLC}, + {"IUCLC", IUCLC}, #endif - {"IXON", IXON}, - {"IXANY", IXANY}, - {"IXOFF", IXOFF}, + {"IXON", IXON}, + {"IXANY", IXANY}, + {"IXOFF", IXOFF}, #ifdef IMAXBEL - {"IMAXBEL", IMAXBEL}, + {"IMAXBEL", IMAXBEL}, #endif - /* struct termios.c_oflag constants */ - {"OPOST", OPOST}, + /* struct termios.c_oflag constants */ + {"OPOST", OPOST}, #ifdef OLCUC - {"OLCUC", OLCUC}, + {"OLCUC", OLCUC}, #endif #ifdef ONLCR - {"ONLCR", ONLCR}, + {"ONLCR", ONLCR}, #endif #ifdef OCRNL - {"OCRNL", OCRNL}, + {"OCRNL", OCRNL}, #endif #ifdef ONOCR - {"ONOCR", ONOCR}, + {"ONOCR", ONOCR}, #endif #ifdef ONLRET - {"ONLRET", ONLRET}, + {"ONLRET", ONLRET}, #endif #ifdef OFILL - {"OFILL", OFILL}, + {"OFILL", OFILL}, #endif #ifdef OFDEL - {"OFDEL", OFDEL}, + {"OFDEL", OFDEL}, #endif #ifdef NLDLY - {"NLDLY", NLDLY}, + {"NLDLY", NLDLY}, #endif #ifdef CRDLY - {"CRDLY", CRDLY}, + {"CRDLY", CRDLY}, #endif #ifdef TABDLY - {"TABDLY", TABDLY}, + {"TABDLY", TABDLY}, #endif #ifdef BSDLY - {"BSDLY", BSDLY}, + {"BSDLY", BSDLY}, #endif #ifdef VTDLY - {"VTDLY", VTDLY}, + {"VTDLY", VTDLY}, #endif #ifdef FFDLY - {"FFDLY", FFDLY}, + {"FFDLY", FFDLY}, #endif - /* struct termios.c_oflag-related values (delay mask) */ + /* struct termios.c_oflag-related values (delay mask) */ #ifdef NL0 - {"NL0", NL0}, + {"NL0", NL0}, #endif #ifdef NL1 - {"NL1", NL1}, + {"NL1", NL1}, #endif #ifdef CR0 - {"CR0", CR0}, + {"CR0", CR0}, #endif #ifdef CR1 - {"CR1", CR1}, + {"CR1", CR1}, #endif #ifdef CR2 - {"CR2", CR2}, + {"CR2", CR2}, #endif #ifdef CR3 - {"CR3", CR3}, + {"CR3", CR3}, #endif #ifdef TAB0 - {"TAB0", TAB0}, + {"TAB0", TAB0}, #endif #ifdef TAB1 - {"TAB1", TAB1}, + {"TAB1", TAB1}, #endif #ifdef TAB2 - {"TAB2", TAB2}, + {"TAB2", TAB2}, #endif #ifdef TAB3 - {"TAB3", TAB3}, + {"TAB3", TAB3}, #endif #ifdef XTABS - {"XTABS", XTABS}, + {"XTABS", XTABS}, #endif #ifdef BS0 - {"BS0", BS0}, + {"BS0", BS0}, #endif #ifdef BS1 - {"BS1", BS1}, + {"BS1", BS1}, #endif #ifdef VT0 - {"VT0", VT0}, + {"VT0", VT0}, #endif #ifdef VT1 - {"VT1", VT1}, + {"VT1", VT1}, #endif #ifdef FF0 - {"FF0", FF0}, + {"FF0", FF0}, #endif #ifdef FF1 - {"FF1", FF1}, + {"FF1", FF1}, #endif - /* struct termios.c_cflag constants */ - {"CSIZE", CSIZE}, - {"CSTOPB", CSTOPB}, - {"CREAD", CREAD}, - {"PARENB", PARENB}, - {"PARODD", PARODD}, - {"HUPCL", HUPCL}, - {"CLOCAL", CLOCAL}, + /* struct termios.c_cflag constants */ + {"CSIZE", CSIZE}, + {"CSTOPB", CSTOPB}, + {"CREAD", CREAD}, + {"PARENB", PARENB}, + {"PARODD", PARODD}, + {"HUPCL", HUPCL}, + {"CLOCAL", CLOCAL}, #ifdef CIBAUD - {"CIBAUD", CIBAUD}, + {"CIBAUD", CIBAUD}, #endif #ifdef CRTSCTS - {"CRTSCTS", (long)CRTSCTS}, + {"CRTSCTS", (long)CRTSCTS}, #endif - /* struct termios.c_cflag-related values (character size) */ - {"CS5", CS5}, - {"CS6", CS6}, - {"CS7", CS7}, - {"CS8", CS8}, - - /* struct termios.c_lflag constants */ - {"ISIG", ISIG}, - {"ICANON", ICANON}, + /* struct termios.c_cflag-related values (character size) */ + {"CS5", CS5}, + {"CS6", CS6}, + {"CS7", CS7}, + {"CS8", CS8}, + + /* struct termios.c_lflag constants */ + {"ISIG", ISIG}, + {"ICANON", ICANON}, #ifdef XCASE - {"XCASE", XCASE}, + {"XCASE", XCASE}, #endif - {"ECHO", ECHO}, - {"ECHOE", ECHOE}, - {"ECHOK", ECHOK}, - {"ECHONL", ECHONL}, + {"ECHO", ECHO}, + {"ECHOE", ECHOE}, + {"ECHOK", ECHOK}, + {"ECHONL", ECHONL}, #ifdef ECHOCTL - {"ECHOCTL", ECHOCTL}, + {"ECHOCTL", ECHOCTL}, #endif #ifdef ECHOPRT - {"ECHOPRT", ECHOPRT}, + {"ECHOPRT", ECHOPRT}, #endif #ifdef ECHOKE - {"ECHOKE", ECHOKE}, + {"ECHOKE", ECHOKE}, #endif #ifdef FLUSHO - {"FLUSHO", FLUSHO}, + {"FLUSHO", FLUSHO}, #endif - {"NOFLSH", NOFLSH}, - {"TOSTOP", TOSTOP}, + {"NOFLSH", NOFLSH}, + {"TOSTOP", TOSTOP}, #ifdef PENDIN - {"PENDIN", PENDIN}, + {"PENDIN", PENDIN}, #endif - {"IEXTEN", IEXTEN}, + {"IEXTEN", IEXTEN}, - /* indexes into the control chars array returned by tcgetattr() */ - {"VINTR", VINTR}, - {"VQUIT", VQUIT}, - {"VERASE", VERASE}, - {"VKILL", VKILL}, - {"VEOF", VEOF}, - {"VTIME", VTIME}, - {"VMIN", VMIN}, + /* indexes into the control chars array returned by tcgetattr() */ + {"VINTR", VINTR}, + {"VQUIT", VQUIT}, + {"VERASE", VERASE}, + {"VKILL", VKILL}, + {"VEOF", VEOF}, + {"VTIME", VTIME}, + {"VMIN", VMIN}, #ifdef VSWTC - /* The #defines above ensure that if either is defined, both are, - * but both may be omitted by the system headers. ;-( */ - {"VSWTC", VSWTC}, - {"VSWTCH", VSWTCH}, -#endif - {"VSTART", VSTART}, - {"VSTOP", VSTOP}, - {"VSUSP", VSUSP}, - {"VEOL", VEOL}, + /* The #defines above ensure that if either is defined, both are, + * but both may be omitted by the system headers. ;-( */ + {"VSWTC", VSWTC}, + {"VSWTCH", VSWTCH}, +#endif + {"VSTART", VSTART}, + {"VSTOP", VSTOP}, + {"VSUSP", VSUSP}, + {"VEOL", VEOL}, #ifdef VREPRINT - {"VREPRINT", VREPRINT}, + {"VREPRINT", VREPRINT}, #endif #ifdef VDISCARD - {"VDISCARD", VDISCARD}, + {"VDISCARD", VDISCARD}, #endif #ifdef VWERASE - {"VWERASE", VWERASE}, + {"VWERASE", VWERASE}, #endif #ifdef VLNEXT - {"VLNEXT", VLNEXT}, + {"VLNEXT", VLNEXT}, #endif #ifdef VEOL2 - {"VEOL2", VEOL2}, + {"VEOL2", VEOL2}, #endif #ifdef B460800 - {"B460800", B460800}, + {"B460800", B460800}, #endif #ifdef CBAUD - {"CBAUD", CBAUD}, + {"CBAUD", CBAUD}, #endif #ifdef CDEL - {"CDEL", CDEL}, + {"CDEL", CDEL}, #endif #ifdef CDSUSP - {"CDSUSP", CDSUSP}, + {"CDSUSP", CDSUSP}, #endif #ifdef CEOF - {"CEOF", CEOF}, + {"CEOF", CEOF}, #endif #ifdef CEOL - {"CEOL", CEOL}, + {"CEOL", CEOL}, #endif #ifdef CEOL2 - {"CEOL2", CEOL2}, + {"CEOL2", CEOL2}, #endif #ifdef CEOT - {"CEOT", CEOT}, + {"CEOT", CEOT}, #endif #ifdef CERASE - {"CERASE", CERASE}, + {"CERASE", CERASE}, #endif #ifdef CESC - {"CESC", CESC}, + {"CESC", CESC}, #endif #ifdef CFLUSH - {"CFLUSH", CFLUSH}, + {"CFLUSH", CFLUSH}, #endif #ifdef CINTR - {"CINTR", CINTR}, + {"CINTR", CINTR}, #endif #ifdef CKILL - {"CKILL", CKILL}, + {"CKILL", CKILL}, #endif #ifdef CLNEXT - {"CLNEXT", CLNEXT}, + {"CLNEXT", CLNEXT}, #endif #ifdef CNUL - {"CNUL", CNUL}, + {"CNUL", CNUL}, #endif #ifdef COMMON - {"COMMON", COMMON}, + {"COMMON", COMMON}, #endif #ifdef CQUIT - {"CQUIT", CQUIT}, + {"CQUIT", CQUIT}, #endif #ifdef CRPRNT - {"CRPRNT", CRPRNT}, + {"CRPRNT", CRPRNT}, #endif #ifdef CSTART - {"CSTART", CSTART}, + {"CSTART", CSTART}, #endif #ifdef CSTOP - {"CSTOP", CSTOP}, + {"CSTOP", CSTOP}, #endif #ifdef CSUSP - {"CSUSP", CSUSP}, + {"CSUSP", CSUSP}, #endif #ifdef CSWTCH - {"CSWTCH", CSWTCH}, + {"CSWTCH", CSWTCH}, #endif #ifdef CWERASE - {"CWERASE", CWERASE}, + {"CWERASE", CWERASE}, #endif #ifdef EXTA - {"EXTA", EXTA}, + {"EXTA", EXTA}, #endif #ifdef EXTB - {"EXTB", EXTB}, + {"EXTB", EXTB}, #endif #ifdef FIOASYNC - {"FIOASYNC", FIOASYNC}, + {"FIOASYNC", FIOASYNC}, #endif #ifdef FIOCLEX - {"FIOCLEX", FIOCLEX}, + {"FIOCLEX", FIOCLEX}, #endif #ifdef FIONBIO - {"FIONBIO", FIONBIO}, + {"FIONBIO", FIONBIO}, #endif #ifdef FIONCLEX - {"FIONCLEX", FIONCLEX}, + {"FIONCLEX", FIONCLEX}, #endif #ifdef FIONREAD - {"FIONREAD", FIONREAD}, + {"FIONREAD", FIONREAD}, #endif #ifdef IBSHIFT - {"IBSHIFT", IBSHIFT}, + {"IBSHIFT", IBSHIFT}, #endif #ifdef INIT_C_CC - {"INIT_C_CC", INIT_C_CC}, + {"INIT_C_CC", INIT_C_CC}, #endif #ifdef IOCSIZE_MASK - {"IOCSIZE_MASK", IOCSIZE_MASK}, + {"IOCSIZE_MASK", IOCSIZE_MASK}, #endif #ifdef IOCSIZE_SHIFT - {"IOCSIZE_SHIFT", IOCSIZE_SHIFT}, + {"IOCSIZE_SHIFT", IOCSIZE_SHIFT}, #endif #ifdef NCC - {"NCC", NCC}, + {"NCC", NCC}, #endif #ifdef NCCS - {"NCCS", NCCS}, + {"NCCS", NCCS}, #endif #ifdef NSWTCH - {"NSWTCH", NSWTCH}, + {"NSWTCH", NSWTCH}, #endif #ifdef N_MOUSE - {"N_MOUSE", N_MOUSE}, + {"N_MOUSE", N_MOUSE}, #endif #ifdef N_PPP - {"N_PPP", N_PPP}, + {"N_PPP", N_PPP}, #endif #ifdef N_SLIP - {"N_SLIP", N_SLIP}, + {"N_SLIP", N_SLIP}, #endif #ifdef N_STRIP - {"N_STRIP", N_STRIP}, + {"N_STRIP", N_STRIP}, #endif #ifdef N_TTY - {"N_TTY", N_TTY}, + {"N_TTY", N_TTY}, #endif #ifdef TCFLSH - {"TCFLSH", TCFLSH}, + {"TCFLSH", TCFLSH}, #endif #ifdef TCGETA - {"TCGETA", TCGETA}, + {"TCGETA", TCGETA}, #endif #ifdef TCGETS - {"TCGETS", TCGETS}, + {"TCGETS", TCGETS}, #endif #ifdef TCSBRK - {"TCSBRK", TCSBRK}, + {"TCSBRK", TCSBRK}, #endif #ifdef TCSBRKP - {"TCSBRKP", TCSBRKP}, + {"TCSBRKP", TCSBRKP}, #endif #ifdef TCSETA - {"TCSETA", TCSETA}, + {"TCSETA", TCSETA}, #endif #ifdef TCSETAF - {"TCSETAF", TCSETAF}, + {"TCSETAF", TCSETAF}, #endif #ifdef TCSETAW - {"TCSETAW", TCSETAW}, + {"TCSETAW", TCSETAW}, #endif #ifdef TCSETS - {"TCSETS", TCSETS}, + {"TCSETS", TCSETS}, #endif #ifdef TCSETSF - {"TCSETSF", TCSETSF}, + {"TCSETSF", TCSETSF}, #endif #ifdef TCSETSW - {"TCSETSW", TCSETSW}, + {"TCSETSW", TCSETSW}, #endif #ifdef TCXONC - {"TCXONC", TCXONC}, + {"TCXONC", TCXONC}, #endif #ifdef TIOCCONS - {"TIOCCONS", TIOCCONS}, + {"TIOCCONS", TIOCCONS}, #endif #ifdef TIOCEXCL - {"TIOCEXCL", TIOCEXCL}, + {"TIOCEXCL", TIOCEXCL}, #endif #ifdef TIOCGETD - {"TIOCGETD", TIOCGETD}, + {"TIOCGETD", TIOCGETD}, #endif #ifdef TIOCGICOUNT - {"TIOCGICOUNT", TIOCGICOUNT}, + {"TIOCGICOUNT", TIOCGICOUNT}, #endif #ifdef TIOCGLCKTRMIOS - {"TIOCGLCKTRMIOS", TIOCGLCKTRMIOS}, + {"TIOCGLCKTRMIOS", TIOCGLCKTRMIOS}, #endif #ifdef TIOCGPGRP - {"TIOCGPGRP", TIOCGPGRP}, + {"TIOCGPGRP", TIOCGPGRP}, #endif #ifdef TIOCGSERIAL - {"TIOCGSERIAL", TIOCGSERIAL}, + {"TIOCGSERIAL", TIOCGSERIAL}, #endif #ifdef TIOCGSOFTCAR - {"TIOCGSOFTCAR", TIOCGSOFTCAR}, + {"TIOCGSOFTCAR", TIOCGSOFTCAR}, #endif #ifdef TIOCGWINSZ - {"TIOCGWINSZ", TIOCGWINSZ}, + {"TIOCGWINSZ", TIOCGWINSZ}, #endif #ifdef TIOCINQ - {"TIOCINQ", TIOCINQ}, + {"TIOCINQ", TIOCINQ}, #endif #ifdef TIOCLINUX - {"TIOCLINUX", TIOCLINUX}, + {"TIOCLINUX", TIOCLINUX}, #endif #ifdef TIOCMBIC - {"TIOCMBIC", TIOCMBIC}, + {"TIOCMBIC", TIOCMBIC}, #endif #ifdef TIOCMBIS - {"TIOCMBIS", TIOCMBIS}, + {"TIOCMBIS", TIOCMBIS}, #endif #ifdef TIOCMGET - {"TIOCMGET", TIOCMGET}, + {"TIOCMGET", TIOCMGET}, #endif #ifdef TIOCMIWAIT - {"TIOCMIWAIT", TIOCMIWAIT}, + {"TIOCMIWAIT", TIOCMIWAIT}, #endif #ifdef TIOCMSET - {"TIOCMSET", TIOCMSET}, + {"TIOCMSET", TIOCMSET}, #endif #ifdef TIOCM_CAR - {"TIOCM_CAR", TIOCM_CAR}, + {"TIOCM_CAR", TIOCM_CAR}, #endif #ifdef TIOCM_CD - {"TIOCM_CD", TIOCM_CD}, + {"TIOCM_CD", TIOCM_CD}, #endif #ifdef TIOCM_CTS - {"TIOCM_CTS", TIOCM_CTS}, + {"TIOCM_CTS", TIOCM_CTS}, #endif #ifdef TIOCM_DSR - {"TIOCM_DSR", TIOCM_DSR}, + {"TIOCM_DSR", TIOCM_DSR}, #endif #ifdef TIOCM_DTR - {"TIOCM_DTR", TIOCM_DTR}, + {"TIOCM_DTR", TIOCM_DTR}, #endif #ifdef TIOCM_LE - {"TIOCM_LE", TIOCM_LE}, + {"TIOCM_LE", TIOCM_LE}, #endif #ifdef TIOCM_RI - {"TIOCM_RI", TIOCM_RI}, + {"TIOCM_RI", TIOCM_RI}, #endif #ifdef TIOCM_RNG - {"TIOCM_RNG", TIOCM_RNG}, + {"TIOCM_RNG", TIOCM_RNG}, #endif #ifdef TIOCM_RTS - {"TIOCM_RTS", TIOCM_RTS}, + {"TIOCM_RTS", TIOCM_RTS}, #endif #ifdef TIOCM_SR - {"TIOCM_SR", TIOCM_SR}, + {"TIOCM_SR", TIOCM_SR}, #endif #ifdef TIOCM_ST - {"TIOCM_ST", TIOCM_ST}, + {"TIOCM_ST", TIOCM_ST}, #endif #ifdef TIOCNOTTY - {"TIOCNOTTY", TIOCNOTTY}, + {"TIOCNOTTY", TIOCNOTTY}, #endif #ifdef TIOCNXCL - {"TIOCNXCL", TIOCNXCL}, + {"TIOCNXCL", TIOCNXCL}, #endif #ifdef TIOCOUTQ - {"TIOCOUTQ", TIOCOUTQ}, + {"TIOCOUTQ", TIOCOUTQ}, #endif #ifdef TIOCPKT - {"TIOCPKT", TIOCPKT}, + {"TIOCPKT", TIOCPKT}, #endif #ifdef TIOCPKT_DATA - {"TIOCPKT_DATA", TIOCPKT_DATA}, + {"TIOCPKT_DATA", TIOCPKT_DATA}, #endif #ifdef TIOCPKT_DOSTOP - {"TIOCPKT_DOSTOP", TIOCPKT_DOSTOP}, + {"TIOCPKT_DOSTOP", TIOCPKT_DOSTOP}, #endif #ifdef TIOCPKT_FLUSHREAD - {"TIOCPKT_FLUSHREAD", TIOCPKT_FLUSHREAD}, + {"TIOCPKT_FLUSHREAD", TIOCPKT_FLUSHREAD}, #endif #ifdef TIOCPKT_FLUSHWRITE - {"TIOCPKT_FLUSHWRITE", TIOCPKT_FLUSHWRITE}, + {"TIOCPKT_FLUSHWRITE", TIOCPKT_FLUSHWRITE}, #endif #ifdef TIOCPKT_NOSTOP - {"TIOCPKT_NOSTOP", TIOCPKT_NOSTOP}, + {"TIOCPKT_NOSTOP", TIOCPKT_NOSTOP}, #endif #ifdef TIOCPKT_START - {"TIOCPKT_START", TIOCPKT_START}, + {"TIOCPKT_START", TIOCPKT_START}, #endif #ifdef TIOCPKT_STOP - {"TIOCPKT_STOP", TIOCPKT_STOP}, + {"TIOCPKT_STOP", TIOCPKT_STOP}, #endif #ifdef TIOCSCTTY - {"TIOCSCTTY", TIOCSCTTY}, + {"TIOCSCTTY", TIOCSCTTY}, #endif #ifdef TIOCSERCONFIG - {"TIOCSERCONFIG", TIOCSERCONFIG}, + {"TIOCSERCONFIG", TIOCSERCONFIG}, #endif #ifdef TIOCSERGETLSR - {"TIOCSERGETLSR", TIOCSERGETLSR}, + {"TIOCSERGETLSR", TIOCSERGETLSR}, #endif #ifdef TIOCSERGETMULTI - {"TIOCSERGETMULTI", TIOCSERGETMULTI}, + {"TIOCSERGETMULTI", TIOCSERGETMULTI}, #endif #ifdef TIOCSERGSTRUCT - {"TIOCSERGSTRUCT", TIOCSERGSTRUCT}, + {"TIOCSERGSTRUCT", TIOCSERGSTRUCT}, #endif #ifdef TIOCSERGWILD - {"TIOCSERGWILD", TIOCSERGWILD}, + {"TIOCSERGWILD", TIOCSERGWILD}, #endif #ifdef TIOCSERSETMULTI - {"TIOCSERSETMULTI", TIOCSERSETMULTI}, + {"TIOCSERSETMULTI", TIOCSERSETMULTI}, #endif #ifdef TIOCSERSWILD - {"TIOCSERSWILD", TIOCSERSWILD}, + {"TIOCSERSWILD", TIOCSERSWILD}, #endif #ifdef TIOCSER_TEMT - {"TIOCSER_TEMT", TIOCSER_TEMT}, + {"TIOCSER_TEMT", TIOCSER_TEMT}, #endif #ifdef TIOCSETD - {"TIOCSETD", TIOCSETD}, + {"TIOCSETD", TIOCSETD}, #endif #ifdef TIOCSLCKTRMIOS - {"TIOCSLCKTRMIOS", TIOCSLCKTRMIOS}, + {"TIOCSLCKTRMIOS", TIOCSLCKTRMIOS}, #endif #ifdef TIOCSPGRP - {"TIOCSPGRP", TIOCSPGRP}, + {"TIOCSPGRP", TIOCSPGRP}, #endif #ifdef TIOCSSERIAL - {"TIOCSSERIAL", TIOCSSERIAL}, + {"TIOCSSERIAL", TIOCSSERIAL}, #endif #ifdef TIOCSSOFTCAR - {"TIOCSSOFTCAR", TIOCSSOFTCAR}, + {"TIOCSSOFTCAR", TIOCSSOFTCAR}, #endif #ifdef TIOCSTI - {"TIOCSTI", TIOCSTI}, + {"TIOCSTI", TIOCSTI}, #endif #ifdef TIOCSWINSZ - {"TIOCSWINSZ", TIOCSWINSZ}, + {"TIOCSWINSZ", TIOCSWINSZ}, #endif #ifdef TIOCTTYGSTRUCT - {"TIOCTTYGSTRUCT", TIOCTTYGSTRUCT}, + {"TIOCTTYGSTRUCT", TIOCTTYGSTRUCT}, #endif - /* sentinel */ - {NULL, 0} + /* sentinel */ + {NULL, 0} }; static struct PyModuleDef termiosmodule = { - PyModuleDef_HEAD_INIT, - "termios", - termios__doc__, - -1, - termios_methods, - NULL, - NULL, - NULL, - NULL + PyModuleDef_HEAD_INIT, + "termios", + termios__doc__, + -1, + termios_methods, + NULL, + NULL, + NULL, + NULL }; PyMODINIT_FUNC PyInit_termios(void) { - PyObject *m; - struct constant *constant = termios_constants; + PyObject *m; + struct constant *constant = termios_constants; - m = PyModule_Create(&termiosmodule); - if (m == NULL) - return NULL; - - if (TermiosError == NULL) { - TermiosError = PyErr_NewException("termios.error", NULL, NULL); - } - Py_INCREF(TermiosError); - PyModule_AddObject(m, "error", TermiosError); - - while (constant->name != NULL) { - PyModule_AddIntConstant(m, constant->name, constant->value); - ++constant; - } - return m; + m = PyModule_Create(&termiosmodule); + if (m == NULL) + return NULL; + + if (TermiosError == NULL) { + TermiosError = PyErr_NewException("termios.error", NULL, NULL); + } + Py_INCREF(TermiosError); + PyModule_AddObject(m, "error", TermiosError); + + while (constant->name != NULL) { + PyModule_AddIntConstant(m, constant->name, constant->value); + ++constant; + } + return m; } Modified: python/branches/py3k/Modules/testcapi_long.h ============================================================================== --- python/branches/py3k/Modules/testcapi_long.h (original) +++ python/branches/py3k/Modules/testcapi_long.h Sun May 9 17:52:27 2010 @@ -1,182 +1,182 @@ /* Poor-man's template. Macros used: - TESTNAME name of the test (like test_long_api_inner) - TYPENAME the signed type (like long) - F_S_TO_PY convert signed to pylong; TYPENAME -> PyObject* - F_PY_TO_S convert pylong to signed; PyObject* -> TYPENAME - F_U_TO_PY convert unsigned to pylong; unsigned TYPENAME -> PyObject* + TESTNAME name of the test (like test_long_api_inner) + TYPENAME the signed type (like long) + F_S_TO_PY convert signed to pylong; TYPENAME -> PyObject* + F_PY_TO_S convert pylong to signed; PyObject* -> TYPENAME + F_U_TO_PY convert unsigned to pylong; unsigned TYPENAME -> PyObject* F_PY_TO_U convert pylong to unsigned; PyObject* -> unsigned TYPENAME */ static PyObject * TESTNAME(PyObject *error(const char*)) { - const int NBITS = sizeof(TYPENAME) * 8; - unsigned TYPENAME base; - PyObject *pyresult; - int i; - - /* Note: This test lets PyObjects leak if an error is raised. Since - an error should never be raised, leaks are impossible . */ - - /* Test native -> PyLong -> native roundtrip identity. - * Generate all powers of 2, and test them and their negations, - * plus the numbers +-1 off from them. - */ - base = 1; - for (i = 0; - i < NBITS + 1; /* on last, base overflows to 0 */ - ++i, base <<= 1) - { - int j; - for (j = 0; j < 6; ++j) { - TYPENAME in, out; - unsigned TYPENAME uin, uout; - - /* For 0, 1, 2 use base; for 3, 4, 5 use -base */ - uin = j < 3 ? base - : (unsigned TYPENAME)(-(TYPENAME)base); - - /* For 0 & 3, subtract 1. - * For 1 & 4, leave alone. - * For 2 & 5, add 1. - */ - uin += (unsigned TYPENAME)(TYPENAME)(j % 3 - 1); - - pyresult = F_U_TO_PY(uin); - if (pyresult == NULL) - return error( - "unsigned unexpected null result"); - - uout = F_PY_TO_U(pyresult); - if (uout == (unsigned TYPENAME)-1 && PyErr_Occurred()) - return error( - "unsigned unexpected -1 result"); - if (uout != uin) - return error( - "unsigned output != input"); - UNBIND(pyresult); - - in = (TYPENAME)uin; - pyresult = F_S_TO_PY(in); - if (pyresult == NULL) - return error( - "signed unexpected null result"); - - out = F_PY_TO_S(pyresult); - if (out == (TYPENAME)-1 && PyErr_Occurred()) - return error( - "signed unexpected -1 result"); - if (out != in) - return error( - "signed output != input"); - UNBIND(pyresult); - } - } - - /* Overflow tests. The loop above ensured that all limit cases that - * should not overflow don't overflow, so all we need to do here is - * provoke one-over-the-limit cases (not exhaustive, but sharp). - */ - { - PyObject *one, *x, *y; - TYPENAME out; - unsigned TYPENAME uout; - - one = PyLong_FromLong(1); - if (one == NULL) - return error( - "unexpected NULL from PyLong_FromLong"); - - /* Unsigned complains about -1? */ - x = PyNumber_Negative(one); - if (x == NULL) - return error( - "unexpected NULL from PyNumber_Negative"); - - uout = F_PY_TO_U(x); - if (uout != (unsigned TYPENAME)-1 || !PyErr_Occurred()) - return error( - "PyLong_AsUnsignedXXX(-1) didn't complain"); - if (!PyErr_ExceptionMatches(PyExc_OverflowError)) - return error( - "PyLong_AsUnsignedXXX(-1) raised " - "something other than OverflowError"); - PyErr_Clear(); - UNBIND(x); - - /* Unsigned complains about 2**NBITS? */ - y = PyLong_FromLong((long)NBITS); - if (y == NULL) - return error( - "unexpected NULL from PyLong_FromLong"); - - x = PyNumber_Lshift(one, y); /* 1L << NBITS, == 2**NBITS */ - UNBIND(y); - if (x == NULL) - return error( - "unexpected NULL from PyNumber_Lshift"); - - uout = F_PY_TO_U(x); - if (uout != (unsigned TYPENAME)-1 || !PyErr_Occurred()) - return error( - "PyLong_AsUnsignedXXX(2**NBITS) didn't " - "complain"); - if (!PyErr_ExceptionMatches(PyExc_OverflowError)) - return error( - "PyLong_AsUnsignedXXX(2**NBITS) raised " - "something other than OverflowError"); - PyErr_Clear(); - - /* Signed complains about 2**(NBITS-1)? - x still has 2**NBITS. */ - y = PyNumber_Rshift(x, one); /* 2**(NBITS-1) */ - UNBIND(x); - if (y == NULL) - return error( - "unexpected NULL from PyNumber_Rshift"); - - out = F_PY_TO_S(y); - if (out != (TYPENAME)-1 || !PyErr_Occurred()) - return error( - "PyLong_AsXXX(2**(NBITS-1)) didn't " - "complain"); - if (!PyErr_ExceptionMatches(PyExc_OverflowError)) - return error( - "PyLong_AsXXX(2**(NBITS-1)) raised " - "something other than OverflowError"); - PyErr_Clear(); - - /* Signed complains about -2**(NBITS-1)-1?; - y still has 2**(NBITS-1). */ - x = PyNumber_Negative(y); /* -(2**(NBITS-1)) */ - UNBIND(y); - if (x == NULL) - return error( - "unexpected NULL from PyNumber_Negative"); - - y = PyNumber_Subtract(x, one); /* -(2**(NBITS-1))-1 */ - UNBIND(x); - if (y == NULL) - return error( - "unexpected NULL from PyNumber_Subtract"); - - out = F_PY_TO_S(y); - if (out != (TYPENAME)-1 || !PyErr_Occurred()) - return error( - "PyLong_AsXXX(-2**(NBITS-1)-1) didn't " - "complain"); - if (!PyErr_ExceptionMatches(PyExc_OverflowError)) - return error( - "PyLong_AsXXX(-2**(NBITS-1)-1) raised " - "something other than OverflowError"); - PyErr_Clear(); - UNBIND(y); - - Py_XDECREF(x); - Py_XDECREF(y); - Py_DECREF(one); - } + const int NBITS = sizeof(TYPENAME) * 8; + unsigned TYPENAME base; + PyObject *pyresult; + int i; + + /* Note: This test lets PyObjects leak if an error is raised. Since + an error should never be raised, leaks are impossible . */ + + /* Test native -> PyLong -> native roundtrip identity. + * Generate all powers of 2, and test them and their negations, + * plus the numbers +-1 off from them. + */ + base = 1; + for (i = 0; + i < NBITS + 1; /* on last, base overflows to 0 */ + ++i, base <<= 1) + { + int j; + for (j = 0; j < 6; ++j) { + TYPENAME in, out; + unsigned TYPENAME uin, uout; + + /* For 0, 1, 2 use base; for 3, 4, 5 use -base */ + uin = j < 3 ? base + : (unsigned TYPENAME)(-(TYPENAME)base); + + /* For 0 & 3, subtract 1. + * For 1 & 4, leave alone. + * For 2 & 5, add 1. + */ + uin += (unsigned TYPENAME)(TYPENAME)(j % 3 - 1); + + pyresult = F_U_TO_PY(uin); + if (pyresult == NULL) + return error( + "unsigned unexpected null result"); + + uout = F_PY_TO_U(pyresult); + if (uout == (unsigned TYPENAME)-1 && PyErr_Occurred()) + return error( + "unsigned unexpected -1 result"); + if (uout != uin) + return error( + "unsigned output != input"); + UNBIND(pyresult); + + in = (TYPENAME)uin; + pyresult = F_S_TO_PY(in); + if (pyresult == NULL) + return error( + "signed unexpected null result"); + + out = F_PY_TO_S(pyresult); + if (out == (TYPENAME)-1 && PyErr_Occurred()) + return error( + "signed unexpected -1 result"); + if (out != in) + return error( + "signed output != input"); + UNBIND(pyresult); + } + } + + /* Overflow tests. The loop above ensured that all limit cases that + * should not overflow don't overflow, so all we need to do here is + * provoke one-over-the-limit cases (not exhaustive, but sharp). + */ + { + PyObject *one, *x, *y; + TYPENAME out; + unsigned TYPENAME uout; + + one = PyLong_FromLong(1); + if (one == NULL) + return error( + "unexpected NULL from PyLong_FromLong"); + + /* Unsigned complains about -1? */ + x = PyNumber_Negative(one); + if (x == NULL) + return error( + "unexpected NULL from PyNumber_Negative"); + + uout = F_PY_TO_U(x); + if (uout != (unsigned TYPENAME)-1 || !PyErr_Occurred()) + return error( + "PyLong_AsUnsignedXXX(-1) didn't complain"); + if (!PyErr_ExceptionMatches(PyExc_OverflowError)) + return error( + "PyLong_AsUnsignedXXX(-1) raised " + "something other than OverflowError"); + PyErr_Clear(); + UNBIND(x); + + /* Unsigned complains about 2**NBITS? */ + y = PyLong_FromLong((long)NBITS); + if (y == NULL) + return error( + "unexpected NULL from PyLong_FromLong"); + + x = PyNumber_Lshift(one, y); /* 1L << NBITS, == 2**NBITS */ + UNBIND(y); + if (x == NULL) + return error( + "unexpected NULL from PyNumber_Lshift"); + + uout = F_PY_TO_U(x); + if (uout != (unsigned TYPENAME)-1 || !PyErr_Occurred()) + return error( + "PyLong_AsUnsignedXXX(2**NBITS) didn't " + "complain"); + if (!PyErr_ExceptionMatches(PyExc_OverflowError)) + return error( + "PyLong_AsUnsignedXXX(2**NBITS) raised " + "something other than OverflowError"); + PyErr_Clear(); + + /* Signed complains about 2**(NBITS-1)? + x still has 2**NBITS. */ + y = PyNumber_Rshift(x, one); /* 2**(NBITS-1) */ + UNBIND(x); + if (y == NULL) + return error( + "unexpected NULL from PyNumber_Rshift"); + + out = F_PY_TO_S(y); + if (out != (TYPENAME)-1 || !PyErr_Occurred()) + return error( + "PyLong_AsXXX(2**(NBITS-1)) didn't " + "complain"); + if (!PyErr_ExceptionMatches(PyExc_OverflowError)) + return error( + "PyLong_AsXXX(2**(NBITS-1)) raised " + "something other than OverflowError"); + PyErr_Clear(); + + /* Signed complains about -2**(NBITS-1)-1?; + y still has 2**(NBITS-1). */ + x = PyNumber_Negative(y); /* -(2**(NBITS-1)) */ + UNBIND(y); + if (x == NULL) + return error( + "unexpected NULL from PyNumber_Negative"); + + y = PyNumber_Subtract(x, one); /* -(2**(NBITS-1))-1 */ + UNBIND(x); + if (y == NULL) + return error( + "unexpected NULL from PyNumber_Subtract"); + + out = F_PY_TO_S(y); + if (out != (TYPENAME)-1 || !PyErr_Occurred()) + return error( + "PyLong_AsXXX(-2**(NBITS-1)-1) didn't " + "complain"); + if (!PyErr_ExceptionMatches(PyExc_OverflowError)) + return error( + "PyLong_AsXXX(-2**(NBITS-1)-1) raised " + "something other than OverflowError"); + PyErr_Clear(); + UNBIND(y); + + Py_XDECREF(x); + Py_XDECREF(y); + Py_DECREF(one); + } - Py_INCREF(Py_None); - return Py_None; + Py_INCREF(Py_None); + return Py_None; } Modified: python/branches/py3k/Modules/timemodule.c ============================================================================== --- python/branches/py3k/Modules/timemodule.c (original) +++ python/branches/py3k/Modules/timemodule.c Sun May 9 17:52:27 2010 @@ -48,12 +48,12 @@ static HANDLE hInterruptEvent = NULL; static BOOL WINAPI PyCtrlHandler(DWORD dwCtrlType) { - SetEvent(hInterruptEvent); - /* allow other default handlers to be called. - Default Python handler will setup the - KeyboardInterrupt exception. - */ - return FALSE; + SetEvent(hInterruptEvent); + /* allow other default handlers to be called. + Default Python handler will setup the + KeyboardInterrupt exception. + */ + return FALSE; } static long main_thread; @@ -94,38 +94,38 @@ time_t _PyTime_DoubleToTimet(double x) { - time_t result; - double diff; + time_t result; + double diff; - result = (time_t)x; - /* How much info did we lose? time_t may be an integral or - * floating type, and we don't know which. If it's integral, - * we don't know whether C truncates, rounds, returns the floor, - * etc. If we lost a second or more, the C rounding is - * unreasonable, or the input just doesn't fit in a time_t; - * call it an error regardless. Note that the original cast to - * time_t can cause a C error too, but nothing we can do to - * worm around that. - */ - diff = x - (double)result; - if (diff <= -1.0 || diff >= 1.0) { - PyErr_SetString(PyExc_ValueError, - "timestamp out of range for platform time_t"); - result = (time_t)-1; - } - return result; + result = (time_t)x; + /* How much info did we lose? time_t may be an integral or + * floating type, and we don't know which. If it's integral, + * we don't know whether C truncates, rounds, returns the floor, + * etc. If we lost a second or more, the C rounding is + * unreasonable, or the input just doesn't fit in a time_t; + * call it an error regardless. Note that the original cast to + * time_t can cause a C error too, but nothing we can do to + * worm around that. + */ + diff = x - (double)result; + if (diff <= -1.0 || diff >= 1.0) { + PyErr_SetString(PyExc_ValueError, + "timestamp out of range for platform time_t"); + result = (time_t)-1; + } + return result; } static PyObject * time_time(PyObject *self, PyObject *unused) { - double secs; - secs = floattime(); - if (secs == 0.0) { - PyErr_SetFromErrno(PyExc_IOError); - return NULL; - } - return PyFloat_FromDouble(secs); + double secs; + secs = floattime(); + if (secs == 0.0) { + PyErr_SetFromErrno(PyExc_IOError); + return NULL; + } + return PyFloat_FromDouble(secs); } PyDoc_STRVAR(time_doc, @@ -147,7 +147,7 @@ static PyObject * time_clock(PyObject *self, PyObject *unused) { - return PyFloat_FromDouble(((double)clock()) / CLOCKS_PER_SEC); + return PyFloat_FromDouble(((double)clock()) / CLOCKS_PER_SEC); } #endif /* HAVE_CLOCK */ @@ -156,25 +156,25 @@ static PyObject * time_clock(PyObject *self, PyObject *unused) { - static LARGE_INTEGER ctrStart; - static double divisor = 0.0; - LARGE_INTEGER now; - double diff; - - if (divisor == 0.0) { - LARGE_INTEGER freq; - QueryPerformanceCounter(&ctrStart); - if (!QueryPerformanceFrequency(&freq) || freq.QuadPart == 0) { - /* Unlikely to happen - this works on all intel - machines at least! Revert to clock() */ - return PyFloat_FromDouble(((double)clock()) / - CLOCKS_PER_SEC); - } - divisor = (double)freq.QuadPart; - } - QueryPerformanceCounter(&now); - diff = (double)(now.QuadPart - ctrStart.QuadPart); - return PyFloat_FromDouble(diff / divisor); + static LARGE_INTEGER ctrStart; + static double divisor = 0.0; + LARGE_INTEGER now; + double diff; + + if (divisor == 0.0) { + LARGE_INTEGER freq; + QueryPerformanceCounter(&ctrStart); + if (!QueryPerformanceFrequency(&freq) || freq.QuadPart == 0) { + /* Unlikely to happen - this works on all intel + machines at least! Revert to clock() */ + return PyFloat_FromDouble(((double)clock()) / + CLOCKS_PER_SEC); + } + divisor = (double)freq.QuadPart; + } + QueryPerformanceCounter(&now); + diff = (double)(now.QuadPart - ctrStart.QuadPart); + return PyFloat_FromDouble(diff / divisor); } #define HAVE_CLOCK /* So it gets included in the methods */ @@ -192,13 +192,13 @@ static PyObject * time_sleep(PyObject *self, PyObject *args) { - double secs; - if (!PyArg_ParseTuple(args, "d:sleep", &secs)) - return NULL; - if (floatsleep(secs) != 0) - return NULL; - Py_INCREF(Py_None); - return Py_None; + double secs; + if (!PyArg_ParseTuple(args, "d:sleep", &secs)) + return NULL; + if (floatsleep(secs) != 0) + return NULL; + Py_INCREF(Py_None); + return Py_None; } PyDoc_STRVAR(sleep_doc, @@ -208,23 +208,23 @@ a floating point number for subsecond precision."); static PyStructSequence_Field struct_time_type_fields[] = { - {"tm_year", NULL}, - {"tm_mon", NULL}, - {"tm_mday", NULL}, - {"tm_hour", NULL}, - {"tm_min", NULL}, - {"tm_sec", NULL}, - {"tm_wday", NULL}, - {"tm_yday", NULL}, - {"tm_isdst", NULL}, - {0} + {"tm_year", NULL}, + {"tm_mon", NULL}, + {"tm_mday", NULL}, + {"tm_hour", NULL}, + {"tm_min", NULL}, + {"tm_sec", NULL}, + {"tm_wday", NULL}, + {"tm_yday", NULL}, + {"tm_isdst", NULL}, + {0} }; static PyStructSequence_Desc struct_time_type_desc = { - "time.struct_time", - NULL, - struct_time_type_fields, - 9, + "time.struct_time", + NULL, + struct_time_type_fields, + 9, }; static int initialized; @@ -233,71 +233,71 @@ static PyObject * tmtotuple(struct tm *p) { - PyObject *v = PyStructSequence_New(&StructTimeType); - if (v == NULL) - return NULL; + PyObject *v = PyStructSequence_New(&StructTimeType); + if (v == NULL) + return NULL; #define SET(i,val) PyStructSequence_SET_ITEM(v, i, PyLong_FromLong((long) val)) - SET(0, p->tm_year + 1900); - SET(1, p->tm_mon + 1); /* Want January == 1 */ - SET(2, p->tm_mday); - SET(3, p->tm_hour); - SET(4, p->tm_min); - SET(5, p->tm_sec); - SET(6, (p->tm_wday + 6) % 7); /* Want Monday == 0 */ - SET(7, p->tm_yday + 1); /* Want January, 1 == 1 */ - SET(8, p->tm_isdst); + SET(0, p->tm_year + 1900); + SET(1, p->tm_mon + 1); /* Want January == 1 */ + SET(2, p->tm_mday); + SET(3, p->tm_hour); + SET(4, p->tm_min); + SET(5, p->tm_sec); + SET(6, (p->tm_wday + 6) % 7); /* Want Monday == 0 */ + SET(7, p->tm_yday + 1); /* Want January, 1 == 1 */ + SET(8, p->tm_isdst); #undef SET - if (PyErr_Occurred()) { - Py_XDECREF(v); - return NULL; - } + if (PyErr_Occurred()) { + Py_XDECREF(v); + return NULL; + } - return v; + return v; } static PyObject * structtime_totuple(PyObject *t) { - PyObject *x = NULL; - unsigned int i; - PyObject *v = PyTuple_New(9); - if (v == NULL) - return NULL; - - for (i=0; i<9; i++) { - x = PyStructSequence_GET_ITEM(t, i); - Py_INCREF(x); - PyTuple_SET_ITEM(v, i, x); - } - - if (PyErr_Occurred()) { - Py_XDECREF(v); - return NULL; - } + PyObject *x = NULL; + unsigned int i; + PyObject *v = PyTuple_New(9); + if (v == NULL) + return NULL; + + for (i=0; i<9; i++) { + x = PyStructSequence_GET_ITEM(t, i); + Py_INCREF(x); + PyTuple_SET_ITEM(v, i, x); + } + + if (PyErr_Occurred()) { + Py_XDECREF(v); + return NULL; + } - return v; + return v; } static PyObject * time_convert(double when, struct tm * (*function)(const time_t *)) { - struct tm *p; - time_t whent = _PyTime_DoubleToTimet(when); + struct tm *p; + time_t whent = _PyTime_DoubleToTimet(when); - if (whent == (time_t)-1 && PyErr_Occurred()) - return NULL; - errno = 0; - p = function(&whent); - if (p == NULL) { + if (whent == (time_t)-1 && PyErr_Occurred()) + return NULL; + errno = 0; + p = function(&whent); + if (p == NULL) { #ifdef EINVAL - if (errno == 0) - errno = EINVAL; + if (errno == 0) + errno = EINVAL; #endif - return PyErr_SetFromErrno(PyExc_ValueError); - } - return tmtotuple(p); + return PyErr_SetFromErrno(PyExc_ValueError); + } + return tmtotuple(p); } /* Parse arg tuple that can contain an optional float-or-None value; @@ -307,28 +307,28 @@ static int parse_time_double_args(PyObject *args, char *format, double *pwhen) { - PyObject *ot = NULL; + PyObject *ot = NULL; - if (!PyArg_ParseTuple(args, format, &ot)) - return 0; - if (ot == NULL || ot == Py_None) - *pwhen = floattime(); - else { - double when = PyFloat_AsDouble(ot); - if (PyErr_Occurred()) - return 0; - *pwhen = when; - } - return 1; + if (!PyArg_ParseTuple(args, format, &ot)) + return 0; + if (ot == NULL || ot == Py_None) + *pwhen = floattime(); + else { + double when = PyFloat_AsDouble(ot); + if (PyErr_Occurred()) + return 0; + *pwhen = when; + } + return 1; } static PyObject * time_gmtime(PyObject *self, PyObject *args) { - double when; - if (!parse_time_double_args(args, "|O:gmtime", &when)) - return NULL; - return time_convert(when, gmtime); + double when; + if (!parse_time_double_args(args, "|O:gmtime", &when)) + return NULL; + return time_convert(when, gmtime); } PyDoc_STRVAR(gmtime_doc, @@ -341,15 +341,15 @@ static PyObject * time_localtime(PyObject *self, PyObject *args) { - double when; - if (!parse_time_double_args(args, "|O:localtime", &when)) - return NULL; - return time_convert(when, localtime); + double when; + if (!parse_time_double_args(args, "|O:localtime", &when)) + return NULL; + return time_convert(when, localtime); } PyDoc_STRVAR(localtime_doc, "localtime([seconds]) -> (tm_year,tm_mon,tm_mday,tm_hour,tm_min,\n\ - tm_sec,tm_wday,tm_yday,tm_isdst)\n\ + tm_sec,tm_wday,tm_yday,tm_isdst)\n\ \n\ Convert seconds since the Epoch to a time tuple expressing local time.\n\ When 'seconds' is not passed in, convert the current time instead."); @@ -357,63 +357,63 @@ static int gettmarg(PyObject *args, struct tm *p) { - int y; - PyObject *t = NULL; + int y; + PyObject *t = NULL; - memset((void *) p, '\0', sizeof(struct tm)); + memset((void *) p, '\0', sizeof(struct tm)); - if (PyTuple_Check(args)) { - t = args; - Py_INCREF(t); - } - else if (Py_TYPE(args) == &StructTimeType) { - t = structtime_totuple(args); - } - else { - PyErr_SetString(PyExc_TypeError, - "Tuple or struct_time argument required"); - return 0; - } - - if (t == NULL || !PyArg_ParseTuple(t, "iiiiiiiii", - &y, - &p->tm_mon, - &p->tm_mday, - &p->tm_hour, - &p->tm_min, - &p->tm_sec, - &p->tm_wday, - &p->tm_yday, - &p->tm_isdst)) { - Py_XDECREF(t); - return 0; - } - Py_DECREF(t); - - if (y < 1900) { - PyObject *accept = PyDict_GetItemString(moddict, - "accept2dyear"); - if (accept == NULL || !PyLong_CheckExact(accept) || - !PyObject_IsTrue(accept)) { - PyErr_SetString(PyExc_ValueError, - "year >= 1900 required"); - return 0; - } - if (69 <= y && y <= 99) - y += 1900; - else if (0 <= y && y <= 68) - y += 2000; - else { - PyErr_SetString(PyExc_ValueError, - "year out of range"); - return 0; - } - } - p->tm_year = y - 1900; - p->tm_mon--; - p->tm_wday = (p->tm_wday + 1) % 7; - p->tm_yday--; - return 1; + if (PyTuple_Check(args)) { + t = args; + Py_INCREF(t); + } + else if (Py_TYPE(args) == &StructTimeType) { + t = structtime_totuple(args); + } + else { + PyErr_SetString(PyExc_TypeError, + "Tuple or struct_time argument required"); + return 0; + } + + if (t == NULL || !PyArg_ParseTuple(t, "iiiiiiiii", + &y, + &p->tm_mon, + &p->tm_mday, + &p->tm_hour, + &p->tm_min, + &p->tm_sec, + &p->tm_wday, + &p->tm_yday, + &p->tm_isdst)) { + Py_XDECREF(t); + return 0; + } + Py_DECREF(t); + + if (y < 1900) { + PyObject *accept = PyDict_GetItemString(moddict, + "accept2dyear"); + if (accept == NULL || !PyLong_CheckExact(accept) || + !PyObject_IsTrue(accept)) { + PyErr_SetString(PyExc_ValueError, + "year >= 1900 required"); + return 0; + } + if (69 <= y && y <= 99) + y += 1900; + else if (0 <= y && y <= 68) + y += 2000; + else { + PyErr_SetString(PyExc_ValueError, + "year out of range"); + return 0; + } + } + p->tm_year = y - 1900; + p->tm_mon--; + p->tm_wday = (p->tm_wday + 1) % 7; + p->tm_yday--; + return 1; } #ifdef HAVE_STRFTIME @@ -430,174 +430,174 @@ static PyObject * time_strftime(PyObject *self, PyObject *args) { - PyObject *tup = NULL; - struct tm buf; - const time_char *fmt; - PyObject *format, *tmpfmt; - size_t fmtlen, buflen; - time_char *outbuf = 0; - size_t i; - - memset((void *) &buf, '\0', sizeof(buf)); - - /* Will always expect a unicode string to be passed as format. - Given that there's no str type anymore in py3k this seems safe. - */ - if (!PyArg_ParseTuple(args, "U|O:strftime", &format, &tup)) - return NULL; - - if (tup == NULL) { - time_t tt = time(NULL); - buf = *localtime(&tt); - } else if (!gettmarg(tup, &buf)) - return NULL; - - /* Checks added to make sure strftime() does not crash Python by - indexing blindly into some array for a textual representation - by some bad index (fixes bug #897625). - - Also support values of zero from Python code for arguments in which - that is out of range by forcing that value to the lowest value that - is valid (fixed bug #1520914). - - Valid ranges based on what is allowed in struct tm: - - - tm_year: [0, max(int)] (1) - - tm_mon: [0, 11] (2) - - tm_mday: [1, 31] - - tm_hour: [0, 23] - - tm_min: [0, 59] - - tm_sec: [0, 60] - - tm_wday: [0, 6] (1) - - tm_yday: [0, 365] (2) - - tm_isdst: [-max(int), max(int)] - - (1) gettmarg() handles bounds-checking. - (2) Python's acceptable range is one greater than the range in C, - thus need to check against automatic decrement by gettmarg(). - */ - if (buf.tm_mon == -1) - buf.tm_mon = 0; - else if (buf.tm_mon < 0 || buf.tm_mon > 11) { - PyErr_SetString(PyExc_ValueError, "month out of range"); - return NULL; - } - if (buf.tm_mday == 0) - buf.tm_mday = 1; - else if (buf.tm_mday < 0 || buf.tm_mday > 31) { - PyErr_SetString(PyExc_ValueError, "day of month out of range"); - return NULL; - } - if (buf.tm_hour < 0 || buf.tm_hour > 23) { - PyErr_SetString(PyExc_ValueError, "hour out of range"); - return NULL; - } - if (buf.tm_min < 0 || buf.tm_min > 59) { - PyErr_SetString(PyExc_ValueError, "minute out of range"); - return NULL; - } - if (buf.tm_sec < 0 || buf.tm_sec > 61) { - PyErr_SetString(PyExc_ValueError, "seconds out of range"); - return NULL; - } - /* tm_wday does not need checking of its upper-bound since taking - ``% 7`` in gettmarg() automatically restricts the range. */ - if (buf.tm_wday < 0) { - PyErr_SetString(PyExc_ValueError, "day of week out of range"); - return NULL; - } - if (buf.tm_yday == -1) - buf.tm_yday = 0; - else if (buf.tm_yday < 0 || buf.tm_yday > 365) { - PyErr_SetString(PyExc_ValueError, "day of year out of range"); - return NULL; - } - /* Normalize tm_isdst just in case someone foolishly implements %Z - based on the assumption that tm_isdst falls within the range of - [-1, 1] */ - if (buf.tm_isdst < -1) - buf.tm_isdst = -1; - else if (buf.tm_isdst > 1) - buf.tm_isdst = 1; + PyObject *tup = NULL; + struct tm buf; + const time_char *fmt; + PyObject *format, *tmpfmt; + size_t fmtlen, buflen; + time_char *outbuf = 0; + size_t i; + + memset((void *) &buf, '\0', sizeof(buf)); + + /* Will always expect a unicode string to be passed as format. + Given that there's no str type anymore in py3k this seems safe. + */ + if (!PyArg_ParseTuple(args, "U|O:strftime", &format, &tup)) + return NULL; + + if (tup == NULL) { + time_t tt = time(NULL); + buf = *localtime(&tt); + } else if (!gettmarg(tup, &buf)) + return NULL; + + /* Checks added to make sure strftime() does not crash Python by + indexing blindly into some array for a textual representation + by some bad index (fixes bug #897625). + + Also support values of zero from Python code for arguments in which + that is out of range by forcing that value to the lowest value that + is valid (fixed bug #1520914). + + Valid ranges based on what is allowed in struct tm: + + - tm_year: [0, max(int)] (1) + - tm_mon: [0, 11] (2) + - tm_mday: [1, 31] + - tm_hour: [0, 23] + - tm_min: [0, 59] + - tm_sec: [0, 60] + - tm_wday: [0, 6] (1) + - tm_yday: [0, 365] (2) + - tm_isdst: [-max(int), max(int)] + + (1) gettmarg() handles bounds-checking. + (2) Python's acceptable range is one greater than the range in C, + thus need to check against automatic decrement by gettmarg(). + */ + if (buf.tm_mon == -1) + buf.tm_mon = 0; + else if (buf.tm_mon < 0 || buf.tm_mon > 11) { + PyErr_SetString(PyExc_ValueError, "month out of range"); + return NULL; + } + if (buf.tm_mday == 0) + buf.tm_mday = 1; + else if (buf.tm_mday < 0 || buf.tm_mday > 31) { + PyErr_SetString(PyExc_ValueError, "day of month out of range"); + return NULL; + } + if (buf.tm_hour < 0 || buf.tm_hour > 23) { + PyErr_SetString(PyExc_ValueError, "hour out of range"); + return NULL; + } + if (buf.tm_min < 0 || buf.tm_min > 59) { + PyErr_SetString(PyExc_ValueError, "minute out of range"); + return NULL; + } + if (buf.tm_sec < 0 || buf.tm_sec > 61) { + PyErr_SetString(PyExc_ValueError, "seconds out of range"); + return NULL; + } + /* tm_wday does not need checking of its upper-bound since taking + ``% 7`` in gettmarg() automatically restricts the range. */ + if (buf.tm_wday < 0) { + PyErr_SetString(PyExc_ValueError, "day of week out of range"); + return NULL; + } + if (buf.tm_yday == -1) + buf.tm_yday = 0; + else if (buf.tm_yday < 0 || buf.tm_yday > 365) { + PyErr_SetString(PyExc_ValueError, "day of year out of range"); + return NULL; + } + /* Normalize tm_isdst just in case someone foolishly implements %Z + based on the assumption that tm_isdst falls within the range of + [-1, 1] */ + if (buf.tm_isdst < -1) + buf.tm_isdst = -1; + else if (buf.tm_isdst > 1) + buf.tm_isdst = 1; #ifdef HAVE_WCSFTIME - tmpfmt = PyBytes_FromStringAndSize(NULL, - sizeof(wchar_t) * (PyUnicode_GetSize(format)+1)); - if (!tmpfmt) - return NULL; - /* This assumes that PyUnicode_AsWideChar doesn't do any UTF-16 - expansion. */ - if (PyUnicode_AsWideChar((PyUnicodeObject*)format, - (wchar_t*)PyBytes_AS_STRING(tmpfmt), - PyUnicode_GetSize(format)+1) == (size_t)-1) - /* This shouldn't fail. */ - Py_FatalError("PyUnicode_AsWideChar failed"); - format = tmpfmt; - fmt = (wchar_t*)PyBytes_AS_STRING(format); + tmpfmt = PyBytes_FromStringAndSize(NULL, + sizeof(wchar_t) * (PyUnicode_GetSize(format)+1)); + if (!tmpfmt) + return NULL; + /* This assumes that PyUnicode_AsWideChar doesn't do any UTF-16 + expansion. */ + if (PyUnicode_AsWideChar((PyUnicodeObject*)format, + (wchar_t*)PyBytes_AS_STRING(tmpfmt), + PyUnicode_GetSize(format)+1) == (size_t)-1) + /* This shouldn't fail. */ + Py_FatalError("PyUnicode_AsWideChar failed"); + format = tmpfmt; + fmt = (wchar_t*)PyBytes_AS_STRING(format); #else - /* Convert the unicode string to an ascii one */ - format = PyUnicode_AsEncodedString(format, TZNAME_ENCODING, NULL); - if (format == NULL) - return NULL; - fmt = PyBytes_AS_STRING(format); + /* Convert the unicode string to an ascii one */ + format = PyUnicode_AsEncodedString(format, TZNAME_ENCODING, NULL); + if (format == NULL) + return NULL; + fmt = PyBytes_AS_STRING(format); #endif #if defined(MS_WINDOWS) && defined(HAVE_WCSFTIME) - /* check that the format string contains only valid directives */ - for(outbuf = wcschr(fmt, L'%'); - outbuf != NULL; - outbuf = wcschr(outbuf+2, L'%')) - { - if (outbuf[1]=='#') - ++outbuf; /* not documented by python, */ - if (outbuf[1]=='\0' || - !wcschr(L"aAbBcdfHIjmMpSUwWxXyYzZ%", outbuf[1])) - { - PyErr_SetString(PyExc_ValueError, "Invalid format string"); - return 0; - } - } + /* check that the format string contains only valid directives */ + for(outbuf = wcschr(fmt, L'%'); + outbuf != NULL; + outbuf = wcschr(outbuf+2, L'%')) + { + if (outbuf[1]=='#') + ++outbuf; /* not documented by python, */ + if (outbuf[1]=='\0' || + !wcschr(L"aAbBcdfHIjmMpSUwWxXyYzZ%", outbuf[1])) + { + PyErr_SetString(PyExc_ValueError, "Invalid format string"); + return 0; + } + } #endif - fmtlen = time_strlen(fmt); + fmtlen = time_strlen(fmt); - /* I hate these functions that presume you know how big the output - * will be ahead of time... - */ - for (i = 1024; ; i += i) { - outbuf = (time_char *)PyMem_Malloc(i*sizeof(time_char)); - if (outbuf == NULL) { - Py_DECREF(format); - return PyErr_NoMemory(); - } - buflen = format_time(outbuf, i, fmt, &buf); - if (buflen > 0 || i >= 256 * fmtlen) { - /* If the buffer is 256 times as long as the format, - it's probably not failing for lack of room! - More likely, the format yields an empty result, - e.g. an empty format, or %Z when the timezone - is unknown. */ - PyObject *ret; + /* I hate these functions that presume you know how big the output + * will be ahead of time... + */ + for (i = 1024; ; i += i) { + outbuf = (time_char *)PyMem_Malloc(i*sizeof(time_char)); + if (outbuf == NULL) { + Py_DECREF(format); + return PyErr_NoMemory(); + } + buflen = format_time(outbuf, i, fmt, &buf); + if (buflen > 0 || i >= 256 * fmtlen) { + /* If the buffer is 256 times as long as the format, + it's probably not failing for lack of room! + More likely, the format yields an empty result, + e.g. an empty format, or %Z when the timezone + is unknown. */ + PyObject *ret; #ifdef HAVE_WCSFTIME - ret = PyUnicode_FromWideChar(outbuf, buflen); + ret = PyUnicode_FromWideChar(outbuf, buflen); #else - ret = PyUnicode_Decode(outbuf, buflen, - TZNAME_ENCODING, NULL); + ret = PyUnicode_Decode(outbuf, buflen, + TZNAME_ENCODING, NULL); #endif - PyMem_Free(outbuf); - Py_DECREF(format); - return ret; - } - PyMem_Free(outbuf); + PyMem_Free(outbuf); + Py_DECREF(format); + return ret; + } + PyMem_Free(outbuf); #if defined _MSC_VER && _MSC_VER >= 1400 && defined(__STDC_SECURE_LIB__) - /* VisualStudio .NET 2005 does this properly */ - if (buflen == 0 && errno == EINVAL) { - PyErr_SetString(PyExc_ValueError, "Invalid format string"); - Py_DECREF(format); - return 0; - } + /* VisualStudio .NET 2005 does this properly */ + if (buflen == 0 && errno == EINVAL) { + PyErr_SetString(PyExc_ValueError, "Invalid format string"); + Py_DECREF(format); + return 0; + } #endif - } + } } #undef time_char @@ -614,15 +614,15 @@ static PyObject * time_strptime(PyObject *self, PyObject *args) { - PyObject *strptime_module = PyImport_ImportModuleNoBlock("_strptime"); - PyObject *strptime_result; + PyObject *strptime_module = PyImport_ImportModuleNoBlock("_strptime"); + PyObject *strptime_result; - if (!strptime_module) - return NULL; - strptime_result = PyObject_CallMethod(strptime_module, - "_strptime_time", "O", args); - Py_DECREF(strptime_module); - return strptime_result; + if (!strptime_module) + return NULL; + strptime_result = PyObject_CallMethod(strptime_module, + "_strptime_time", "O", args); + Py_DECREF(strptime_module); + return strptime_result; } PyDoc_STRVAR(strptime_doc, @@ -635,20 +635,20 @@ static PyObject * time_asctime(PyObject *self, PyObject *args) { - PyObject *tup = NULL; - struct tm buf; - char *p; - if (!PyArg_UnpackTuple(args, "asctime", 0, 1, &tup)) - return NULL; - if (tup == NULL) { - time_t tt = time(NULL); - buf = *localtime(&tt); - } else if (!gettmarg(tup, &buf)) - return NULL; - p = asctime(&buf); - if (p[24] == '\n') - p[24] = '\0'; - return PyUnicode_FromString(p); + PyObject *tup = NULL; + struct tm buf; + char *p; + if (!PyArg_UnpackTuple(args, "asctime", 0, 1, &tup)) + return NULL; + if (tup == NULL) { + time_t tt = time(NULL); + buf = *localtime(&tt); + } else if (!gettmarg(tup, &buf)) + return NULL; + p = asctime(&buf); + if (p[24] == '\n') + p[24] = '\0'; + return PyUnicode_FromString(p); } PyDoc_STRVAR(asctime_doc, @@ -661,30 +661,30 @@ static PyObject * time_ctime(PyObject *self, PyObject *args) { - PyObject *ot = NULL; - time_t tt; - char *p; - - if (!PyArg_UnpackTuple(args, "ctime", 0, 1, &ot)) - return NULL; - if (ot == NULL || ot == Py_None) - tt = time(NULL); - else { - double dt = PyFloat_AsDouble(ot); - if (PyErr_Occurred()) - return NULL; - tt = _PyTime_DoubleToTimet(dt); - if (tt == (time_t)-1 && PyErr_Occurred()) - return NULL; - } - p = ctime(&tt); - if (p == NULL) { - PyErr_SetString(PyExc_ValueError, "unconvertible time"); - return NULL; - } - if (p[24] == '\n') - p[24] = '\0'; - return PyUnicode_FromString(p); + PyObject *ot = NULL; + time_t tt; + char *p; + + if (!PyArg_UnpackTuple(args, "ctime", 0, 1, &ot)) + return NULL; + if (ot == NULL || ot == Py_None) + tt = time(NULL); + else { + double dt = PyFloat_AsDouble(ot); + if (PyErr_Occurred()) + return NULL; + tt = _PyTime_DoubleToTimet(dt); + if (tt == (time_t)-1 && PyErr_Occurred()) + return NULL; + } + p = ctime(&tt); + if (p == NULL) { + PyErr_SetString(PyExc_ValueError, "unconvertible time"); + return NULL; + } + if (p[24] == '\n') + p[24] = '\0'; + return PyUnicode_FromString(p); } PyDoc_STRVAR(ctime_doc, @@ -698,17 +698,17 @@ static PyObject * time_mktime(PyObject *self, PyObject *tup) { - struct tm buf; - time_t tt; - if (!gettmarg(tup, &buf)) - return NULL; - tt = mktime(&buf); - if (tt == (time_t)(-1)) { - PyErr_SetString(PyExc_OverflowError, - "mktime argument out of range"); - return NULL; - } - return PyFloat_FromDouble((double)tt); + struct tm buf; + time_t tt; + if (!gettmarg(tup, &buf)) + return NULL; + tt = mktime(&buf); + if (tt == (time_t)(-1)) { + PyErr_SetString(PyExc_OverflowError, + "mktime argument out of range"); + return NULL; + } + return PyFloat_FromDouble((double)tt); } PyDoc_STRVAR(mktime_doc, @@ -723,21 +723,21 @@ static PyObject * time_tzset(PyObject *self, PyObject *unused) { - PyObject* m; + PyObject* m; - m = PyImport_ImportModuleNoBlock("time"); - if (m == NULL) { - return NULL; - } + m = PyImport_ImportModuleNoBlock("time"); + if (m == NULL) { + return NULL; + } - tzset(); + tzset(); - /* Reset timezone, altzone, daylight and tzname */ - PyInit_timezone(m); - Py_DECREF(m); + /* Reset timezone, altzone, daylight and tzname */ + PyInit_timezone(m); + Py_DECREF(m); - Py_INCREF(Py_None); - return Py_None; + Py_INCREF(Py_None); + return Py_None; } PyDoc_STRVAR(tzset_doc, @@ -757,115 +757,115 @@ static void PyInit_timezone(PyObject *m) { /* This code moved from PyInit_time wholesale to allow calling it from - time_tzset. In the future, some parts of it can be moved back - (for platforms that don't HAVE_WORKING_TZSET, when we know what they - are), and the extraneous calls to tzset(3) should be removed. - I haven't done this yet, as I don't want to change this code as - little as possible when introducing the time.tzset and time.tzsetwall - methods. This should simply be a method of doing the following once, - at the top of this function and removing the call to tzset() from - time_tzset(): - - #ifdef HAVE_TZSET - tzset() - #endif + time_tzset. In the future, some parts of it can be moved back + (for platforms that don't HAVE_WORKING_TZSET, when we know what they + are), and the extraneous calls to tzset(3) should be removed. + I haven't done this yet, as I don't want to change this code as + little as possible when introducing the time.tzset and time.tzsetwall + methods. This should simply be a method of doing the following once, + at the top of this function and removing the call to tzset() from + time_tzset(): + + #ifdef HAVE_TZSET + tzset() + #endif - And I'm lazy and hate C so nyer. + And I'm lazy and hate C so nyer. */ #if defined(HAVE_TZNAME) && !defined(__GLIBC__) && !defined(__CYGWIN__) - PyObject *otz0, *otz1; - tzset(); + PyObject *otz0, *otz1; + tzset(); #ifdef PYOS_OS2 - PyModule_AddIntConstant(m, "timezone", _timezone); + PyModule_AddIntConstant(m, "timezone", _timezone); #else /* !PYOS_OS2 */ - PyModule_AddIntConstant(m, "timezone", timezone); + PyModule_AddIntConstant(m, "timezone", timezone); #endif /* PYOS_OS2 */ #ifdef HAVE_ALTZONE - PyModule_AddIntConstant(m, "altzone", altzone); + PyModule_AddIntConstant(m, "altzone", altzone); #else #ifdef PYOS_OS2 - PyModule_AddIntConstant(m, "altzone", _timezone-3600); + PyModule_AddIntConstant(m, "altzone", _timezone-3600); #else /* !PYOS_OS2 */ - PyModule_AddIntConstant(m, "altzone", timezone-3600); + PyModule_AddIntConstant(m, "altzone", timezone-3600); #endif /* PYOS_OS2 */ #endif - PyModule_AddIntConstant(m, "daylight", daylight); - otz0 = PyUnicode_Decode(tzname[0], strlen(tzname[0]), TZNAME_ENCODING, NULL); - otz1 = PyUnicode_Decode(tzname[1], strlen(tzname[1]), TZNAME_ENCODING, NULL); - PyModule_AddObject(m, "tzname", Py_BuildValue("(NN)", otz0, otz1)); + PyModule_AddIntConstant(m, "daylight", daylight); + otz0 = PyUnicode_Decode(tzname[0], strlen(tzname[0]), TZNAME_ENCODING, NULL); + otz1 = PyUnicode_Decode(tzname[1], strlen(tzname[1]), TZNAME_ENCODING, NULL); + PyModule_AddObject(m, "tzname", Py_BuildValue("(NN)", otz0, otz1)); #else /* !HAVE_TZNAME || __GLIBC__ || __CYGWIN__*/ #ifdef HAVE_STRUCT_TM_TM_ZONE - { + { #define YEAR ((time_t)((365 * 24 + 6) * 3600)) - time_t t; - struct tm *p; - long janzone, julyzone; - char janname[10], julyname[10]; - t = (time((time_t *)0) / YEAR) * YEAR; - p = localtime(&t); - janzone = -p->tm_gmtoff; - strncpy(janname, p->tm_zone ? p->tm_zone : " ", 9); - janname[9] = '\0'; - t += YEAR/2; - p = localtime(&t); - julyzone = -p->tm_gmtoff; - strncpy(julyname, p->tm_zone ? p->tm_zone : " ", 9); - julyname[9] = '\0'; - - if( janzone < julyzone ) { - /* DST is reversed in the southern hemisphere */ - PyModule_AddIntConstant(m, "timezone", julyzone); - PyModule_AddIntConstant(m, "altzone", janzone); - PyModule_AddIntConstant(m, "daylight", - janzone != julyzone); - PyModule_AddObject(m, "tzname", - Py_BuildValue("(zz)", - julyname, janname)); - } else { - PyModule_AddIntConstant(m, "timezone", janzone); - PyModule_AddIntConstant(m, "altzone", julyzone); - PyModule_AddIntConstant(m, "daylight", - janzone != julyzone); - PyModule_AddObject(m, "tzname", - Py_BuildValue("(zz)", - janname, julyname)); - } - } + time_t t; + struct tm *p; + long janzone, julyzone; + char janname[10], julyname[10]; + t = (time((time_t *)0) / YEAR) * YEAR; + p = localtime(&t); + janzone = -p->tm_gmtoff; + strncpy(janname, p->tm_zone ? p->tm_zone : " ", 9); + janname[9] = '\0'; + t += YEAR/2; + p = localtime(&t); + julyzone = -p->tm_gmtoff; + strncpy(julyname, p->tm_zone ? p->tm_zone : " ", 9); + julyname[9] = '\0'; + + if( janzone < julyzone ) { + /* DST is reversed in the southern hemisphere */ + PyModule_AddIntConstant(m, "timezone", julyzone); + PyModule_AddIntConstant(m, "altzone", janzone); + PyModule_AddIntConstant(m, "daylight", + janzone != julyzone); + PyModule_AddObject(m, "tzname", + Py_BuildValue("(zz)", + julyname, janname)); + } else { + PyModule_AddIntConstant(m, "timezone", janzone); + PyModule_AddIntConstant(m, "altzone", julyzone); + PyModule_AddIntConstant(m, "daylight", + janzone != julyzone); + PyModule_AddObject(m, "tzname", + Py_BuildValue("(zz)", + janname, julyname)); + } + } #else #endif /* HAVE_STRUCT_TM_TM_ZONE */ #ifdef __CYGWIN__ - tzset(); - PyModule_AddIntConstant(m, "timezone", _timezone); - PyModule_AddIntConstant(m, "altzone", _timezone-3600); - PyModule_AddIntConstant(m, "daylight", _daylight); - PyModule_AddObject(m, "tzname", - Py_BuildValue("(zz)", _tzname[0], _tzname[1])); + tzset(); + PyModule_AddIntConstant(m, "timezone", _timezone); + PyModule_AddIntConstant(m, "altzone", _timezone-3600); + PyModule_AddIntConstant(m, "daylight", _daylight); + PyModule_AddObject(m, "tzname", + Py_BuildValue("(zz)", _tzname[0], _tzname[1])); #endif /* __CYGWIN__ */ #endif /* !HAVE_TZNAME || __GLIBC__ || __CYGWIN__*/ } static PyMethodDef time_methods[] = { - {"time", time_time, METH_NOARGS, time_doc}, + {"time", time_time, METH_NOARGS, time_doc}, #ifdef HAVE_CLOCK - {"clock", time_clock, METH_NOARGS, clock_doc}, + {"clock", time_clock, METH_NOARGS, clock_doc}, #endif - {"sleep", time_sleep, METH_VARARGS, sleep_doc}, - {"gmtime", time_gmtime, METH_VARARGS, gmtime_doc}, - {"localtime", time_localtime, METH_VARARGS, localtime_doc}, - {"asctime", time_asctime, METH_VARARGS, asctime_doc}, - {"ctime", time_ctime, METH_VARARGS, ctime_doc}, + {"sleep", time_sleep, METH_VARARGS, sleep_doc}, + {"gmtime", time_gmtime, METH_VARARGS, gmtime_doc}, + {"localtime", time_localtime, METH_VARARGS, localtime_doc}, + {"asctime", time_asctime, METH_VARARGS, asctime_doc}, + {"ctime", time_ctime, METH_VARARGS, ctime_doc}, #ifdef HAVE_MKTIME - {"mktime", time_mktime, METH_O, mktime_doc}, + {"mktime", time_mktime, METH_O, mktime_doc}, #endif #ifdef HAVE_STRFTIME - {"strftime", time_strftime, METH_VARARGS, strftime_doc}, + {"strftime", time_strftime, METH_VARARGS, strftime_doc}, #endif - {"strptime", time_strptime, METH_VARARGS, strptime_doc}, + {"strptime", time_strptime, METH_VARARGS, strptime_doc}, #ifdef HAVE_WORKING_TZSET - {"tzset", time_tzset, METH_NOARGS, tzset_doc}, + {"tzset", time_tzset, METH_NOARGS, tzset_doc}, #endif - {NULL, NULL} /* sentinel */ + {NULL, NULL} /* sentinel */ }; @@ -917,53 +917,53 @@ static struct PyModuleDef timemodule = { - PyModuleDef_HEAD_INIT, - "time", - module_doc, - -1, - time_methods, - NULL, - NULL, - NULL, - NULL + PyModuleDef_HEAD_INIT, + "time", + module_doc, + -1, + time_methods, + NULL, + NULL, + NULL, + NULL }; PyMODINIT_FUNC PyInit_time(void) { - PyObject *m; - char *p; - m = PyModule_Create(&timemodule); - if (m == NULL) - return NULL; - - /* Accept 2-digit dates unless PYTHONY2K is set and non-empty */ - p = Py_GETENV("PYTHONY2K"); - PyModule_AddIntConstant(m, "accept2dyear", (long) (!p || !*p)); - /* Squirrel away the module's dictionary for the y2k check */ - moddict = PyModule_GetDict(m); - Py_INCREF(moddict); + PyObject *m; + char *p; + m = PyModule_Create(&timemodule); + if (m == NULL) + return NULL; + + /* Accept 2-digit dates unless PYTHONY2K is set and non-empty */ + p = Py_GETENV("PYTHONY2K"); + PyModule_AddIntConstant(m, "accept2dyear", (long) (!p || !*p)); + /* Squirrel away the module's dictionary for the y2k check */ + moddict = PyModule_GetDict(m); + Py_INCREF(moddict); - /* Set, or reset, module variables like time.timezone */ - PyInit_timezone(m); + /* Set, or reset, module variables like time.timezone */ + PyInit_timezone(m); #ifdef MS_WINDOWS - /* Helper to allow interrupts for Windows. - If Ctrl+C event delivered while not sleeping - it will be ignored. - */ - main_thread = PyThread_get_thread_ident(); - hInterruptEvent = CreateEvent(NULL, TRUE, FALSE, NULL); - SetConsoleCtrlHandler( PyCtrlHandler, TRUE); + /* Helper to allow interrupts for Windows. + If Ctrl+C event delivered while not sleeping + it will be ignored. + */ + main_thread = PyThread_get_thread_ident(); + hInterruptEvent = CreateEvent(NULL, TRUE, FALSE, NULL); + SetConsoleCtrlHandler( PyCtrlHandler, TRUE); #endif /* MS_WINDOWS */ - if (!initialized) { - PyStructSequence_InitType(&StructTimeType, - &struct_time_type_desc); - } - Py_INCREF(&StructTimeType); - PyModule_AddObject(m, "struct_time", (PyObject*) &StructTimeType); - initialized = 1; - return m; + if (!initialized) { + PyStructSequence_InitType(&StructTimeType, + &struct_time_type_desc); + } + Py_INCREF(&StructTimeType); + PyModule_AddObject(m, "struct_time", (PyObject*) &StructTimeType); + initialized = 1; + return m; } @@ -972,38 +972,38 @@ static double floattime(void) { - /* There are three ways to get the time: - (1) gettimeofday() -- resolution in microseconds - (2) ftime() -- resolution in milliseconds - (3) time() -- resolution in seconds - In all cases the return value is a float in seconds. - Since on some systems (e.g. SCO ODT 3.0) gettimeofday() may - fail, so we fall back on ftime() or time(). - Note: clock resolution does not imply clock accuracy! */ + /* There are three ways to get the time: + (1) gettimeofday() -- resolution in microseconds + (2) ftime() -- resolution in milliseconds + (3) time() -- resolution in seconds + In all cases the return value is a float in seconds. + Since on some systems (e.g. SCO ODT 3.0) gettimeofday() may + fail, so we fall back on ftime() or time(). + Note: clock resolution does not imply clock accuracy! */ #ifdef HAVE_GETTIMEOFDAY - { - struct timeval t; + { + struct timeval t; #ifdef GETTIMEOFDAY_NO_TZ - if (gettimeofday(&t) == 0) - return (double)t.tv_sec + t.tv_usec*0.000001; + if (gettimeofday(&t) == 0) + return (double)t.tv_sec + t.tv_usec*0.000001; #else /* !GETTIMEOFDAY_NO_TZ */ - if (gettimeofday(&t, (struct timezone *)NULL) == 0) - return (double)t.tv_sec + t.tv_usec*0.000001; + if (gettimeofday(&t, (struct timezone *)NULL) == 0) + return (double)t.tv_sec + t.tv_usec*0.000001; #endif /* !GETTIMEOFDAY_NO_TZ */ - } + } #endif /* !HAVE_GETTIMEOFDAY */ - { + { #if defined(HAVE_FTIME) - struct timeb t; - ftime(&t); - return (double)t.time + (double)t.millitm * (double)0.001; + struct timeb t; + ftime(&t); + return (double)t.time + (double)t.millitm * (double)0.001; #else /* !HAVE_FTIME */ - time_t secs; - time(&secs); - return (double)secs; + time_t secs; + time(&secs); + return (double)secs; #endif /* !HAVE_FTIME */ - } + } } @@ -1016,80 +1016,80 @@ { /* XXX Should test for MS_WINDOWS first! */ #if defined(HAVE_SELECT) && !defined(__EMX__) - struct timeval t; - double frac; - frac = fmod(secs, 1.0); - secs = floor(secs); - t.tv_sec = (long)secs; - t.tv_usec = (long)(frac*1000000.0); - Py_BEGIN_ALLOW_THREADS - if (select(0, (fd_set *)0, (fd_set *)0, (fd_set *)0, &t) != 0) { + struct timeval t; + double frac; + frac = fmod(secs, 1.0); + secs = floor(secs); + t.tv_sec = (long)secs; + t.tv_usec = (long)(frac*1000000.0); + Py_BEGIN_ALLOW_THREADS + if (select(0, (fd_set *)0, (fd_set *)0, (fd_set *)0, &t) != 0) { #ifdef EINTR - if (errno != EINTR) { + if (errno != EINTR) { #else - if (1) { + if (1) { #endif - Py_BLOCK_THREADS - PyErr_SetFromErrno(PyExc_IOError); - return -1; - } - } - Py_END_ALLOW_THREADS + Py_BLOCK_THREADS + PyErr_SetFromErrno(PyExc_IOError); + return -1; + } + } + Py_END_ALLOW_THREADS #elif defined(__WATCOMC__) && !defined(__QNX__) - /* XXX Can't interrupt this sleep */ - Py_BEGIN_ALLOW_THREADS - delay((int)(secs * 1000 + 0.5)); /* delay() uses milliseconds */ - Py_END_ALLOW_THREADS + /* XXX Can't interrupt this sleep */ + Py_BEGIN_ALLOW_THREADS + delay((int)(secs * 1000 + 0.5)); /* delay() uses milliseconds */ + Py_END_ALLOW_THREADS #elif defined(MS_WINDOWS) - { - double millisecs = secs * 1000.0; - unsigned long ul_millis; - - if (millisecs > (double)ULONG_MAX) { - PyErr_SetString(PyExc_OverflowError, - "sleep length is too large"); - return -1; - } - Py_BEGIN_ALLOW_THREADS - /* Allow sleep(0) to maintain win32 semantics, and as decreed - * by Guido, only the main thread can be interrupted. - */ - ul_millis = (unsigned long)millisecs; - if (ul_millis == 0 || - main_thread != PyThread_get_thread_ident()) - Sleep(ul_millis); - else { - DWORD rc; - ResetEvent(hInterruptEvent); - rc = WaitForSingleObject(hInterruptEvent, ul_millis); - if (rc == WAIT_OBJECT_0) { - /* Yield to make sure real Python signal - * handler called. - */ - Sleep(1); - Py_BLOCK_THREADS - errno = EINTR; - PyErr_SetFromErrno(PyExc_IOError); - return -1; - } - } - Py_END_ALLOW_THREADS - } + { + double millisecs = secs * 1000.0; + unsigned long ul_millis; + + if (millisecs > (double)ULONG_MAX) { + PyErr_SetString(PyExc_OverflowError, + "sleep length is too large"); + return -1; + } + Py_BEGIN_ALLOW_THREADS + /* Allow sleep(0) to maintain win32 semantics, and as decreed + * by Guido, only the main thread can be interrupted. + */ + ul_millis = (unsigned long)millisecs; + if (ul_millis == 0 || + main_thread != PyThread_get_thread_ident()) + Sleep(ul_millis); + else { + DWORD rc; + ResetEvent(hInterruptEvent); + rc = WaitForSingleObject(hInterruptEvent, ul_millis); + if (rc == WAIT_OBJECT_0) { + /* Yield to make sure real Python signal + * handler called. + */ + Sleep(1); + Py_BLOCK_THREADS + errno = EINTR; + PyErr_SetFromErrno(PyExc_IOError); + return -1; + } + } + Py_END_ALLOW_THREADS + } #elif defined(PYOS_OS2) - /* This Sleep *IS* Interruptable by Exceptions */ - Py_BEGIN_ALLOW_THREADS - if (DosSleep(secs * 1000) != NO_ERROR) { - Py_BLOCK_THREADS - PyErr_SetFromErrno(PyExc_IOError); - return -1; - } - Py_END_ALLOW_THREADS + /* This Sleep *IS* Interruptable by Exceptions */ + Py_BEGIN_ALLOW_THREADS + if (DosSleep(secs * 1000) != NO_ERROR) { + Py_BLOCK_THREADS + PyErr_SetFromErrno(PyExc_IOError); + return -1; + } + Py_END_ALLOW_THREADS #else - /* XXX Can't interrupt this sleep */ - Py_BEGIN_ALLOW_THREADS - sleep((int)secs); - Py_END_ALLOW_THREADS + /* XXX Can't interrupt this sleep */ + Py_BEGIN_ALLOW_THREADS + sleep((int)secs); + Py_END_ALLOW_THREADS #endif - return 0; + return 0; } Modified: python/branches/py3k/Modules/tkappinit.c ============================================================================== --- python/branches/py3k/Modules/tkappinit.c (original) +++ python/branches/py3k/Modules/tkappinit.c Sun May 9 17:52:27 2010 @@ -26,154 +26,154 @@ int Tcl_AppInit(Tcl_Interp *interp) { - Tk_Window main_window; - const char *_tkinter_skip_tk_init; + Tk_Window main_window; + const char *_tkinter_skip_tk_init; #ifdef TKINTER_PROTECT_LOADTK - const char *_tkinter_tk_failed; + const char *_tkinter_tk_failed; #endif #ifdef TK_AQUA #ifndef MAX_PATH_LEN #define MAX_PATH_LEN 1024 #endif - char tclLibPath[MAX_PATH_LEN], tkLibPath[MAX_PATH_LEN]; - Tcl_Obj* pathPtr; + char tclLibPath[MAX_PATH_LEN], tkLibPath[MAX_PATH_LEN]; + Tcl_Obj* pathPtr; - /* pre- Tcl_Init code copied from tkMacOSXAppInit.c */ - Tk_MacOSXOpenBundleResources (interp, "com.tcltk.tcllibrary", - tclLibPath, MAX_PATH_LEN, 0); - - if (tclLibPath[0] != '\0') { - Tcl_SetVar(interp, "tcl_library", tclLibPath, TCL_GLOBAL_ONLY); - Tcl_SetVar(interp, "tclDefaultLibrary", tclLibPath, TCL_GLOBAL_ONLY); - Tcl_SetVar(interp, "tcl_pkgPath", tclLibPath, TCL_GLOBAL_ONLY); - } - - if (tclLibPath[0] != '\0') { - Tcl_SetVar(interp, "tcl_library", tclLibPath, TCL_GLOBAL_ONLY); - Tcl_SetVar(interp, "tclDefaultLibrary", tclLibPath, TCL_GLOBAL_ONLY); - Tcl_SetVar(interp, "tcl_pkgPath", tclLibPath, TCL_GLOBAL_ONLY); - } + /* pre- Tcl_Init code copied from tkMacOSXAppInit.c */ + Tk_MacOSXOpenBundleResources (interp, "com.tcltk.tcllibrary", + tclLibPath, MAX_PATH_LEN, 0); + + if (tclLibPath[0] != '\0') { + Tcl_SetVar(interp, "tcl_library", tclLibPath, TCL_GLOBAL_ONLY); + Tcl_SetVar(interp, "tclDefaultLibrary", tclLibPath, TCL_GLOBAL_ONLY); + Tcl_SetVar(interp, "tcl_pkgPath", tclLibPath, TCL_GLOBAL_ONLY); + } + + if (tclLibPath[0] != '\0') { + Tcl_SetVar(interp, "tcl_library", tclLibPath, TCL_GLOBAL_ONLY); + Tcl_SetVar(interp, "tclDefaultLibrary", tclLibPath, TCL_GLOBAL_ONLY); + Tcl_SetVar(interp, "tcl_pkgPath", tclLibPath, TCL_GLOBAL_ONLY); + } #endif - if (Tcl_Init (interp) == TCL_ERROR) - return TCL_ERROR; + if (Tcl_Init (interp) == TCL_ERROR) + return TCL_ERROR; #ifdef TK_AQUA - /* pre- Tk_Init code copied from tkMacOSXAppInit.c */ - Tk_MacOSXOpenBundleResources (interp, "com.tcltk.tklibrary", - tkLibPath, MAX_PATH_LEN, 1); - - if (tclLibPath[0] != '\0') { - pathPtr = Tcl_NewStringObj(tclLibPath, -1); - } else { - Tcl_Obj *pathPtr = TclGetLibraryPath(); - } - - if (tkLibPath[0] != '\0') { - Tcl_Obj *objPtr; - - Tcl_SetVar(interp, "tk_library", tkLibPath, TCL_GLOBAL_ONLY); - objPtr = Tcl_NewStringObj(tkLibPath, -1); - Tcl_ListObjAppendElement(NULL, pathPtr, objPtr); - } + /* pre- Tk_Init code copied from tkMacOSXAppInit.c */ + Tk_MacOSXOpenBundleResources (interp, "com.tcltk.tklibrary", + tkLibPath, MAX_PATH_LEN, 1); + + if (tclLibPath[0] != '\0') { + pathPtr = Tcl_NewStringObj(tclLibPath, -1); + } else { + Tcl_Obj *pathPtr = TclGetLibraryPath(); + } + + if (tkLibPath[0] != '\0') { + Tcl_Obj *objPtr; + + Tcl_SetVar(interp, "tk_library", tkLibPath, TCL_GLOBAL_ONLY); + objPtr = Tcl_NewStringObj(tkLibPath, -1); + Tcl_ListObjAppendElement(NULL, pathPtr, objPtr); + } - TclSetLibraryPath(pathPtr); + TclSetLibraryPath(pathPtr); #endif #ifdef WITH_XXX - /* Initialize modules that don't require Tk */ + /* Initialize modules that don't require Tk */ #endif - _tkinter_skip_tk_init = Tcl_GetVar(interp, - "_tkinter_skip_tk_init", TCL_GLOBAL_ONLY); - if (_tkinter_skip_tk_init != NULL && - strcmp(_tkinter_skip_tk_init, "1") == 0) { - return TCL_OK; - } + _tkinter_skip_tk_init = Tcl_GetVar(interp, + "_tkinter_skip_tk_init", TCL_GLOBAL_ONLY); + if (_tkinter_skip_tk_init != NULL && + strcmp(_tkinter_skip_tk_init, "1") == 0) { + return TCL_OK; + } #ifdef TKINTER_PROTECT_LOADTK - _tkinter_tk_failed = Tcl_GetVar(interp, - "_tkinter_tk_failed", TCL_GLOBAL_ONLY); + _tkinter_tk_failed = Tcl_GetVar(interp, + "_tkinter_tk_failed", TCL_GLOBAL_ONLY); - if (tk_load_failed || ( - _tkinter_tk_failed != NULL && - strcmp(_tkinter_tk_failed, "1") == 0)) { - Tcl_SetResult(interp, TKINTER_LOADTK_ERRMSG, TCL_STATIC); - return TCL_ERROR; - } + if (tk_load_failed || ( + _tkinter_tk_failed != NULL && + strcmp(_tkinter_tk_failed, "1") == 0)) { + Tcl_SetResult(interp, TKINTER_LOADTK_ERRMSG, TCL_STATIC); + return TCL_ERROR; + } #endif - if (Tk_Init(interp) == TCL_ERROR) { + if (Tk_Init(interp) == TCL_ERROR) { #ifdef TKINTER_PROTECT_LOADTK - tk_load_failed = 1; - Tcl_SetVar(interp, "_tkinter_tk_failed", "1", TCL_GLOBAL_ONLY); + tk_load_failed = 1; + Tcl_SetVar(interp, "_tkinter_tk_failed", "1", TCL_GLOBAL_ONLY); #endif - return TCL_ERROR; - } + return TCL_ERROR; + } - main_window = Tk_MainWindow(interp); + main_window = Tk_MainWindow(interp); #ifdef TK_AQUA - TkMacOSXInitAppleEvents(interp); - TkMacOSXInitMenus(interp); + TkMacOSXInitAppleEvents(interp); + TkMacOSXInitMenus(interp); #endif - + #ifdef WITH_MOREBUTTONS - { - extern Tcl_CmdProc studButtonCmd; - extern Tcl_CmdProc triButtonCmd; - - Tcl_CreateCommand(interp, "studbutton", studButtonCmd, - (ClientData) main_window, NULL); - Tcl_CreateCommand(interp, "tributton", triButtonCmd, - (ClientData) main_window, NULL); - } + { + extern Tcl_CmdProc studButtonCmd; + extern Tcl_CmdProc triButtonCmd; + + Tcl_CreateCommand(interp, "studbutton", studButtonCmd, + (ClientData) main_window, NULL); + Tcl_CreateCommand(interp, "tributton", triButtonCmd, + (ClientData) main_window, NULL); + } #endif #ifdef WITH_PIL /* 0.2b5 and later -- not yet released as of May 14 */ - { - extern void TkImaging_Init(Tcl_Interp *); - TkImaging_Init(interp); - /* XXX TkImaging_Init() doesn't have the right return type */ - /*Tcl_StaticPackage(interp, "Imaging", TkImaging_Init, NULL);*/ - } + { + extern void TkImaging_Init(Tcl_Interp *); + TkImaging_Init(interp); + /* XXX TkImaging_Init() doesn't have the right return type */ + /*Tcl_StaticPackage(interp, "Imaging", TkImaging_Init, NULL);*/ + } #endif #ifdef WITH_PIL_OLD /* 0.2b4 and earlier */ - { - extern void TkImaging_Init(void); - /* XXX TkImaging_Init() doesn't have the right prototype */ - /*Tcl_StaticPackage(interp, "Imaging", TkImaging_Init, NULL);*/ - } + { + extern void TkImaging_Init(void); + /* XXX TkImaging_Init() doesn't have the right prototype */ + /*Tcl_StaticPackage(interp, "Imaging", TkImaging_Init, NULL);*/ + } #endif #ifdef WITH_TIX - { - extern int Tix_Init(Tcl_Interp *interp); - extern int Tix_SafeInit(Tcl_Interp *interp); - Tcl_StaticPackage(NULL, "Tix", Tix_Init, Tix_SafeInit); - } + { + extern int Tix_Init(Tcl_Interp *interp); + extern int Tix_SafeInit(Tcl_Interp *interp); + Tcl_StaticPackage(NULL, "Tix", Tix_Init, Tix_SafeInit); + } #endif #ifdef WITH_BLT - { - extern int Blt_Init(Tcl_Interp *); - extern int Blt_SafeInit(Tcl_Interp *); - Tcl_StaticPackage(NULL, "Blt", Blt_Init, Blt_SafeInit); - } + { + extern int Blt_Init(Tcl_Interp *); + extern int Blt_SafeInit(Tcl_Interp *); + Tcl_StaticPackage(NULL, "Blt", Blt_Init, Blt_SafeInit); + } #endif #ifdef WITH_TOGL - { - /* XXX I've heard rumors that this doesn't work */ - extern int Togl_Init(Tcl_Interp *); - /* XXX Is there no Togl_SafeInit? */ - Tcl_StaticPackage(NULL, "Togl", Togl_Init, NULL); - } + { + /* XXX I've heard rumors that this doesn't work */ + extern int Togl_Init(Tcl_Interp *); + /* XXX Is there no Togl_SafeInit? */ + Tcl_StaticPackage(NULL, "Togl", Togl_Init, NULL); + } #endif #ifdef WITH_XXX #endif - return TCL_OK; + return TCL_OK; } Modified: python/branches/py3k/Modules/unicodedata.c ============================================================================== --- python/branches/py3k/Modules/unicodedata.c (original) +++ python/branches/py3k/Modules/unicodedata.c Sun May 9 17:52:27 2010 @@ -19,14 +19,14 @@ /* character properties */ typedef struct { - const unsigned char category; /* index into - _PyUnicode_CategoryNames */ - const unsigned char combining; /* combining class value 0 - 255 */ - const unsigned char bidirectional; /* index into - _PyUnicode_BidirectionalNames */ - const unsigned char mirrored; /* true if mirrored in bidir mode */ - const unsigned char east_asian_width; /* index into - _PyUnicode_EastAsianWidth */ + const unsigned char category; /* index into + _PyUnicode_CategoryNames */ + const unsigned char combining; /* combining class value 0 - 255 */ + const unsigned char bidirectional; /* index into + _PyUnicode_BidirectionalNames */ + const unsigned char mirrored; /* true if mirrored in bidir mode */ + const unsigned char east_asian_width; /* index into + _PyUnicode_EastAsianWidth */ const unsigned char normalization_quick_check; /* see is_normalized() */ } _PyUnicode_DatabaseRecord; @@ -67,7 +67,7 @@ #define get_old_record(self, v) ((((PreviousDBVersion*)self)->getrecord)(v)) static PyMemberDef DB_members[] = { - {"unidata_version", T_STRING, offsetof(PreviousDBVersion, name), READONLY}, + {"unidata_version", T_STRING, offsetof(PreviousDBVersion, name), READONLY}, {NULL} }; @@ -79,14 +79,14 @@ new_previous_version(const char*name, const change_record* (*getrecord)(Py_UCS4), Py_UCS4 (*normalization)(Py_UCS4)) { - PreviousDBVersion *self; - self = PyObject_New(PreviousDBVersion, &UCD_Type); - if (self == NULL) - return NULL; - self->name = name; - self->getrecord = getrecord; + PreviousDBVersion *self; + self = PyObject_New(PreviousDBVersion, &UCD_Type); + if (self == NULL) + return NULL; + self->name = name; + self->getrecord = getrecord; self->normalization = normalization; - return (PyObject*)self; + return (PyObject*)self; } @@ -95,12 +95,12 @@ Py_UNICODE *v = PyUnicode_AS_UNICODE(obj); if (PyUnicode_GET_SIZE(obj) == 1) - return *v; + return *v; #ifndef Py_UNICODE_WIDE else if ((PyUnicode_GET_SIZE(obj) == 2) && (0xD800 <= v[0] && v[0] <= 0xDBFF) && (0xDC00 <= v[1] && v[1] <= 0xDFFF)) - return (((v[0] & 0x3FF)<<10) | (v[1] & 0x3FF)) + 0x10000; + return (((v[0] & 0x3FF)<<10) | (v[1] & 0x3FF)) + 0x10000; #endif PyErr_SetString(PyExc_TypeError, "need a single Unicode character as parameter"); @@ -137,7 +137,7 @@ /* unassigned */ have_old = 1; rc = -1; - } + } else if (old->decimal_changed != 0xFF) { have_old = 1; rc = old->decimal_changed; @@ -147,15 +147,15 @@ if (!have_old) rc = Py_UNICODE_TODECIMAL(c); if (rc < 0) { - if (defobj == NULL) { - PyErr_SetString(PyExc_ValueError, - "not a decimal"); + if (defobj == NULL) { + PyErr_SetString(PyExc_ValueError, + "not a decimal"); return NULL; - } - else { - Py_INCREF(defobj); - return defobj; - } + } + else { + Py_INCREF(defobj); + return defobj; + } } return PyLong_FromLong(rc); } @@ -182,14 +182,14 @@ return NULL; rc = Py_UNICODE_TODIGIT(c); if (rc < 0) { - if (defobj == NULL) { - PyErr_SetString(PyExc_ValueError, "not a digit"); + if (defobj == NULL) { + PyErr_SetString(PyExc_ValueError, "not a digit"); return NULL; - } - else { - Py_INCREF(defobj); - return defobj; - } + } + else { + Py_INCREF(defobj); + return defobj; + } } return PyLong_FromLong(rc); } @@ -222,7 +222,7 @@ /* unassigned */ have_old = 1; rc = -1.0; - } + } else if (old->decimal_changed != 0xFF) { have_old = 1; rc = old->decimal_changed; @@ -232,14 +232,14 @@ if (!have_old) rc = Py_UNICODE_TONUMERIC(c); if (rc == -1.0) { - if (defobj == NULL) { - PyErr_SetString(PyExc_ValueError, "not a numeric character"); - return NULL; - } - else { - Py_INCREF(defobj); - return defobj; - } + if (defobj == NULL) { + PyErr_SetString(PyExc_ValueError, "not a numeric character"); + return NULL; + } + else { + Py_INCREF(defobj); + return defobj; + } } return PyFloat_FromDouble(rc); } @@ -258,8 +258,8 @@ Py_UCS4 c; if (!PyArg_ParseTuple(args, "O!:category", - &PyUnicode_Type, &v)) - return NULL; + &PyUnicode_Type, &v)) + return NULL; c = getuchar(v); if (c == (Py_UCS4)-1) return NULL; @@ -287,8 +287,8 @@ Py_UCS4 c; if (!PyArg_ParseTuple(args, "O!:bidirectional", - &PyUnicode_Type, &v)) - return NULL; + &PyUnicode_Type, &v)) + return NULL; c = getuchar(v); if (c == (Py_UCS4)-1) return NULL; @@ -318,8 +318,8 @@ Py_UCS4 c; if (!PyArg_ParseTuple(args, "O!:combining", - &PyUnicode_Type, &v)) - return NULL; + &PyUnicode_Type, &v)) + return NULL; c = getuchar(v); if (c == (Py_UCS4)-1) return NULL; @@ -347,8 +347,8 @@ Py_UCS4 c; if (!PyArg_ParseTuple(args, "O!:mirrored", - &PyUnicode_Type, &v)) - return NULL; + &PyUnicode_Type, &v)) + return NULL; c = getuchar(v); if (c == (Py_UCS4)-1) return NULL; @@ -377,8 +377,8 @@ Py_UCS4 c; if (!PyArg_ParseTuple(args, "O!:east_asian_width", - &PyUnicode_Type, &v)) - return NULL; + &PyUnicode_Type, &v)) + return NULL; c = getuchar(v); if (c == (Py_UCS4)-1) return NULL; @@ -408,8 +408,8 @@ Py_UCS4 c; if (!PyArg_ParseTuple(args, "O!:decomposition", - &PyUnicode_Type, &v)) - return NULL; + &PyUnicode_Type, &v)) + return NULL; c = getuchar(v); if (c == (Py_UCS4)-1) return NULL; @@ -455,7 +455,7 @@ decomp_data[++index]); i += strlen(decomp + i); } - + decomp[i] = '\0'; return PyUnicode_FromString(decomp); @@ -466,7 +466,7 @@ { if (code >= 0x110000) { *index = 0; - } else if (self && UCD_Check(self) && + } else if (self && UCD_Check(self) && get_old_record(self, code)->category_changed==0) { /* unassigned in old version */ *index = 0; @@ -476,7 +476,7 @@ *index = decomp_index2[(*index<> 8; @@ -501,11 +501,11 @@ PyObject *result; Py_UNICODE *i, *end, *o; /* Longest decomposition in Unicode 3.2: U+FDFA */ - Py_UNICODE stack[20]; + Py_UNICODE stack[20]; Py_ssize_t space, isize; int index, prefix, count, stackptr; unsigned char prev, cur; - + stackptr = 0; isize = PyUnicode_GET_SIZE(input); /* Overallocate atmost 10 characters. */ @@ -642,12 +642,12 @@ i = PyUnicode_AS_UNICODE(result); end = i + PyUnicode_GET_SIZE(result); o = PyUnicode_AS_UNICODE(result); - + again: while (i < end) { for (index = 0; index < cskipped; index++) { if (skipped[index] == i) { - /* *i character is skipped. + /* *i character is skipped. Remove from list. */ skipped[index] = skipped[cskipped-1]; cskipped--; @@ -658,7 +658,7 @@ /* Hangul Composition. We don't need to check for pairs, since we always have decomposed data. */ if (LBase <= *i && *i < (LBase+LCount) && - i + 1 < end && + i + 1 < end && VBase <= i[1] && i[1] <= (VBase+VCount)) { int LIndex, VIndex; LIndex = i[0] - LBase; @@ -707,7 +707,7 @@ (index&((1<category_changed == 0) { /* unassigned */ return 0; - } + } } if (SBase <= code && code < SBase+SCount) { - /* Hangul syllable. */ - int SIndex = code - SBase; - int L = SIndex / NCount; - int V = (SIndex % NCount) / TCount; - int T = SIndex % TCount; - - if (buflen < 27) - /* Worst case: HANGUL SYLLABLE <10chars>. */ - return 0; - strcpy(buffer, "HANGUL SYLLABLE "); - buffer += 16; - strcpy(buffer, hangul_syllables[L][0]); - buffer += strlen(hangul_syllables[L][0]); - strcpy(buffer, hangul_syllables[V][1]); - buffer += strlen(hangul_syllables[V][1]); - strcpy(buffer, hangul_syllables[T][2]); - buffer += strlen(hangul_syllables[T][2]); - *buffer = '\0'; - return 1; + /* Hangul syllable. */ + int SIndex = code - SBase; + int L = SIndex / NCount; + int V = (SIndex % NCount) / TCount; + int T = SIndex % TCount; + + if (buflen < 27) + /* Worst case: HANGUL SYLLABLE <10chars>. */ + return 0; + strcpy(buffer, "HANGUL SYLLABLE "); + buffer += 16; + strcpy(buffer, hangul_syllables[L][0]); + buffer += strlen(hangul_syllables[L][0]); + strcpy(buffer, hangul_syllables[V][1]); + buffer += strlen(hangul_syllables[V][1]); + strcpy(buffer, hangul_syllables[T][2]); + buffer += strlen(hangul_syllables[T][2]); + *buffer = '\0'; + return 1; } if (is_unified_ideograph(code)) { @@ -980,23 +980,23 @@ return buffer[namelen] == '\0'; } -static void +static void find_syllable(const char *str, int *len, int *pos, int count, int column) { int i, len1; *len = -1; for (i = 0; i < count; i++) { - char *s = hangul_syllables[i][column]; - len1 = strlen(s); - if (len1 <= *len) - continue; - if (strncmp(str, s, len1) == 0) { - *len = len1; - *pos = i; - } + char *s = hangul_syllables[i][column]; + len1 = strlen(s); + if (len1 <= *len) + continue; + if (strncmp(str, s, len1) == 0) { + *len = len1; + *pos = i; + } } if (*len == -1) { - *len = 0; + *len = 0; } } @@ -1009,18 +1009,18 @@ /* Check for hangul syllables. */ if (strncmp(name, "HANGUL SYLLABLE ", 16) == 0) { - int len, L = -1, V = -1, T = -1; - const char *pos = name + 16; - find_syllable(pos, &len, &L, LCount, 0); - pos += len; - find_syllable(pos, &len, &V, VCount, 1); - pos += len; - find_syllable(pos, &len, &T, TCount, 2); - pos += len; - if (L != -1 && V != -1 && T != -1 && pos-name == namelen) { - *code = SBase + (L*VCount+V)*TCount + T; - return 1; - } + int len, L = -1, V = -1, T = -1; + const char *pos = name + 16; + find_syllable(pos, &len, &L, LCount, 0); + pos += len; + find_syllable(pos, &len, &V, VCount, 1); + pos += len; + find_syllable(pos, &len, &T, TCount, 2); + pos += len; + if (L != -1 && V != -1 && T != -1 && pos-name == namelen) { + *code = SBase + (L*VCount+V)*TCount + T; + return 1; + } /* Otherwise, it's an illegal syllable name. */ return 0; } @@ -1080,7 +1080,7 @@ } } -static const _PyUnicode_Name_CAPI hashAPI = +static const _PyUnicode_Name_CAPI hashAPI = { sizeof(_PyUnicode_Name_CAPI), _getucname, @@ -1112,14 +1112,14 @@ return NULL; if (!_getucname(self, c, name, sizeof(name))) { - if (defobj == NULL) { - PyErr_SetString(PyExc_ValueError, "no such name"); + if (defobj == NULL) { + PyErr_SetString(PyExc_ValueError, "no such name"); return NULL; - } - else { - Py_INCREF(defobj); - return defobj; - } + } + else { + Py_INCREF(defobj); + return defobj; + } } return PyUnicode_FromString(name); @@ -1157,7 +1157,7 @@ } #endif str[0] = (Py_UNICODE) code; - return PyUnicode_FromUnicode(str, 1); + return PyUnicode_FromUnicode(str, 1); } /* XXX Add doc strings. */ @@ -1182,27 +1182,27 @@ {"lookup", unicodedata_lookup, METH_VARARGS, unicodedata_lookup__doc__}, {"normalize", unicodedata_normalize, METH_VARARGS, unicodedata_normalize__doc__}, - {NULL, NULL} /* sentinel */ + {NULL, NULL} /* sentinel */ }; static PyTypeObject UCD_Type = { - /* The ob_type field must be initialized in the module init function - * to be portable to Windows without using C++. */ - PyVarObject_HEAD_INIT(NULL, 0) - "unicodedata.UCD", /*tp_name*/ - sizeof(PreviousDBVersion), /*tp_basicsize*/ - 0, /*tp_itemsize*/ - /* methods */ - (destructor)PyObject_Del, /*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*/ + /* The ob_type field must be initialized in the module init function + * to be portable to Windows without using C++. */ + PyVarObject_HEAD_INIT(NULL, 0) + "unicodedata.UCD", /*tp_name*/ + sizeof(PreviousDBVersion), /*tp_basicsize*/ + 0, /*tp_itemsize*/ + /* methods */ + (destructor)PyObject_Del, /*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*/ @@ -1243,15 +1243,15 @@ static struct PyModuleDef unicodedatamodule = { - PyModuleDef_HEAD_INIT, - "unicodedata", - unicodedata_docstring, - -1, - unicodedata_functions, - NULL, - NULL, - NULL, - NULL + PyModuleDef_HEAD_INIT, + "unicodedata", + unicodedata_docstring, + -1, + unicodedata_functions, + NULL, + NULL, + NULL, + NULL }; PyMODINIT_FUNC @@ -1281,7 +1281,7 @@ return m; } -/* +/* Local variables: c-basic-offset: 4 indent-tabs-mode: nil Modified: python/branches/py3k/Modules/xxmodule.c ============================================================================== --- python/branches/py3k/Modules/xxmodule.c (original) +++ python/branches/py3k/Modules/xxmodule.c Sun May 9 17:52:27 2010 @@ -19,23 +19,23 @@ static PyObject *ErrorObject; typedef struct { - PyObject_HEAD - PyObject *x_attr; /* Attributes dictionary */ + PyObject_HEAD + PyObject *x_attr; /* Attributes dictionary */ } XxoObject; static PyTypeObject Xxo_Type; -#define XxoObject_Check(v) (Py_TYPE(v) == &Xxo_Type) +#define XxoObject_Check(v) (Py_TYPE(v) == &Xxo_Type) static XxoObject * newXxoObject(PyObject *arg) { - XxoObject *self; - self = PyObject_New(XxoObject, &Xxo_Type); - if (self == NULL) - return NULL; - self->x_attr = NULL; - return self; + XxoObject *self; + self = PyObject_New(XxoObject, &Xxo_Type); + if (self == NULL) + return NULL; + self->x_attr = NULL; + return self; } /* Xxo methods */ @@ -43,101 +43,101 @@ static void Xxo_dealloc(XxoObject *self) { - Py_XDECREF(self->x_attr); - PyObject_Del(self); + Py_XDECREF(self->x_attr); + PyObject_Del(self); } static PyObject * Xxo_demo(XxoObject *self, PyObject *args) { - if (!PyArg_ParseTuple(args, ":demo")) - return NULL; - Py_INCREF(Py_None); - return Py_None; + if (!PyArg_ParseTuple(args, ":demo")) + return NULL; + Py_INCREF(Py_None); + return Py_None; } static PyMethodDef Xxo_methods[] = { - {"demo", (PyCFunction)Xxo_demo, METH_VARARGS, - PyDoc_STR("demo() -> None")}, - {NULL, NULL} /* sentinel */ + {"demo", (PyCFunction)Xxo_demo, METH_VARARGS, + PyDoc_STR("demo() -> None")}, + {NULL, NULL} /* sentinel */ }; static PyObject * Xxo_getattro(XxoObject *self, PyObject *name) { - if (self->x_attr != NULL) { - PyObject *v = PyDict_GetItem(self->x_attr, name); - if (v != NULL) { - Py_INCREF(v); - return v; - } - } - return PyObject_GenericGetAttr((PyObject *)self, name); + if (self->x_attr != NULL) { + PyObject *v = PyDict_GetItem(self->x_attr, name); + if (v != NULL) { + Py_INCREF(v); + return v; + } + } + return PyObject_GenericGetAttr((PyObject *)self, name); } static int Xxo_setattr(XxoObject *self, char *name, PyObject *v) { - if (self->x_attr == NULL) { - self->x_attr = PyDict_New(); - if (self->x_attr == NULL) - return -1; - } - if (v == NULL) { - int rv = PyDict_DelItemString(self->x_attr, name); - if (rv < 0) - PyErr_SetString(PyExc_AttributeError, - "delete non-existing Xxo attribute"); - return rv; - } - else - return PyDict_SetItemString(self->x_attr, name, v); + if (self->x_attr == NULL) { + self->x_attr = PyDict_New(); + if (self->x_attr == NULL) + return -1; + } + if (v == NULL) { + int rv = PyDict_DelItemString(self->x_attr, name); + if (rv < 0) + PyErr_SetString(PyExc_AttributeError, + "delete non-existing Xxo attribute"); + return rv; + } + else + return PyDict_SetItemString(self->x_attr, name, v); } static PyTypeObject Xxo_Type = { - /* The ob_type field must be initialized in the module init function - * to be portable to Windows without using C++. */ - PyVarObject_HEAD_INIT(NULL, 0) - "xxmodule.Xxo", /*tp_name*/ - sizeof(XxoObject), /*tp_basicsize*/ - 0, /*tp_itemsize*/ - /* methods */ - (destructor)Xxo_dealloc, /*tp_dealloc*/ - 0, /*tp_print*/ - (getattrfunc)0, /*tp_getattr*/ - (setattrfunc)Xxo_setattr, /*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*/ - (getattrofunc)Xxo_getattro, /*tp_getattro*/ - 0, /*tp_setattro*/ - 0, /*tp_as_buffer*/ - Py_TPFLAGS_DEFAULT, /*tp_flags*/ - 0, /*tp_doc*/ - 0, /*tp_traverse*/ - 0, /*tp_clear*/ - 0, /*tp_richcompare*/ - 0, /*tp_weaklistoffset*/ - 0, /*tp_iter*/ - 0, /*tp_iternext*/ - Xxo_methods, /*tp_methods*/ - 0, /*tp_members*/ - 0, /*tp_getset*/ - 0, /*tp_base*/ - 0, /*tp_dict*/ - 0, /*tp_descr_get*/ - 0, /*tp_descr_set*/ - 0, /*tp_dictoffset*/ - 0, /*tp_init*/ - 0, /*tp_alloc*/ - 0, /*tp_new*/ - 0, /*tp_free*/ - 0, /*tp_is_gc*/ + /* The ob_type field must be initialized in the module init function + * to be portable to Windows without using C++. */ + PyVarObject_HEAD_INIT(NULL, 0) + "xxmodule.Xxo", /*tp_name*/ + sizeof(XxoObject), /*tp_basicsize*/ + 0, /*tp_itemsize*/ + /* methods */ + (destructor)Xxo_dealloc, /*tp_dealloc*/ + 0, /*tp_print*/ + (getattrfunc)0, /*tp_getattr*/ + (setattrfunc)Xxo_setattr, /*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*/ + (getattrofunc)Xxo_getattro, /*tp_getattro*/ + 0, /*tp_setattro*/ + 0, /*tp_as_buffer*/ + Py_TPFLAGS_DEFAULT, /*tp_flags*/ + 0, /*tp_doc*/ + 0, /*tp_traverse*/ + 0, /*tp_clear*/ + 0, /*tp_richcompare*/ + 0, /*tp_weaklistoffset*/ + 0, /*tp_iter*/ + 0, /*tp_iternext*/ + Xxo_methods, /*tp_methods*/ + 0, /*tp_members*/ + 0, /*tp_getset*/ + 0, /*tp_base*/ + 0, /*tp_dict*/ + 0, /*tp_descr_get*/ + 0, /*tp_descr_set*/ + 0, /*tp_dictoffset*/ + 0, /*tp_init*/ + 0, /*tp_alloc*/ + 0, /*tp_new*/ + 0, /*tp_free*/ + 0, /*tp_is_gc*/ }; /* --------------------------------------------------------------------- */ @@ -151,12 +151,12 @@ static PyObject * xx_foo(PyObject *self, PyObject *args) { - long i, j; - long res; - if (!PyArg_ParseTuple(args, "ll:foo", &i, &j)) - return NULL; - res = i+j; /* XXX Do something here */ - return PyLong_FromLong(res); + long i, j; + long res; + if (!PyArg_ParseTuple(args, "ll:foo", &i, &j)) + return NULL; + res = i+j; /* XXX Do something here */ + return PyLong_FromLong(res); } @@ -165,14 +165,14 @@ static PyObject * xx_new(PyObject *self, PyObject *args) { - XxoObject *rv; + XxoObject *rv; - if (!PyArg_ParseTuple(args, ":new")) - return NULL; - rv = newXxoObject(args); - if (rv == NULL) - return NULL; - return (PyObject *)rv; + if (!PyArg_ParseTuple(args, ":new")) + return NULL; + rv = newXxoObject(args); + if (rv == NULL) + return NULL; + return (PyObject *)rv; } /* Example with subtle bug from extensions manual ("Thin Ice"). */ @@ -180,20 +180,20 @@ static PyObject * xx_bug(PyObject *self, PyObject *args) { - PyObject *list, *item; + PyObject *list, *item; - if (!PyArg_ParseTuple(args, "O:bug", &list)) - return NULL; + if (!PyArg_ParseTuple(args, "O:bug", &list)) + return NULL; - item = PyList_GetItem(list, 0); - /* Py_INCREF(item); */ - PyList_SetItem(list, 1, PyLong_FromLong(0L)); - PyObject_Print(item, stdout, 0); - printf("\n"); - /* Py_DECREF(item); */ + item = PyList_GetItem(list, 0); + /* Py_INCREF(item); */ + PyList_SetItem(list, 1, PyLong_FromLong(0L)); + PyObject_Print(item, stdout, 0); + printf("\n"); + /* Py_DECREF(item); */ - Py_INCREF(Py_None); - return Py_None; + Py_INCREF(Py_None); + return Py_None; } /* Test bad format character */ @@ -201,61 +201,61 @@ static PyObject * xx_roj(PyObject *self, PyObject *args) { - PyObject *a; - long b; - if (!PyArg_ParseTuple(args, "O#:roj", &a, &b)) - return NULL; - Py_INCREF(Py_None); - return Py_None; + PyObject *a; + long b; + if (!PyArg_ParseTuple(args, "O#:roj", &a, &b)) + return NULL; + Py_INCREF(Py_None); + return Py_None; } /* ---------- */ static PyTypeObject Str_Type = { - /* The ob_type field must be initialized in the module init function - * to be portable to Windows without using C++. */ - PyVarObject_HEAD_INIT(NULL, 0) - "xxmodule.Str", /*tp_name*/ - 0, /*tp_basicsize*/ - 0, /*tp_itemsize*/ - /* methods */ - 0, /*tp_dealloc*/ - 0, /*tp_print*/ - 0, /*tp_getattr*/ - 0, /*tp_setattr*/ - 0, /*tp_reserved*/ - 0, /*tp_repr*/ - 0, /*tp_as_number*/ - 0, /*tp_as_sequence*/ - 0, /*tp_as_mapping*/ - 0, /*tp_hash*/ - 0, /*tp_call*/ - 0, /*tp_str*/ - 0, /*tp_getattro*/ - 0, /*tp_setattro*/ - 0, /*tp_as_buffer*/ - Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /*tp_flags*/ - 0, /*tp_doc*/ - 0, /*tp_traverse*/ - 0, /*tp_clear*/ - 0, /*tp_richcompare*/ - 0, /*tp_weaklistoffset*/ - 0, /*tp_iter*/ - 0, /*tp_iternext*/ - 0, /*tp_methods*/ - 0, /*tp_members*/ - 0, /*tp_getset*/ - 0, /* see PyInit_xx */ /*tp_base*/ - 0, /*tp_dict*/ - 0, /*tp_descr_get*/ - 0, /*tp_descr_set*/ - 0, /*tp_dictoffset*/ - 0, /*tp_init*/ - 0, /*tp_alloc*/ - 0, /*tp_new*/ - 0, /*tp_free*/ - 0, /*tp_is_gc*/ + /* The ob_type field must be initialized in the module init function + * to be portable to Windows without using C++. */ + PyVarObject_HEAD_INIT(NULL, 0) + "xxmodule.Str", /*tp_name*/ + 0, /*tp_basicsize*/ + 0, /*tp_itemsize*/ + /* methods */ + 0, /*tp_dealloc*/ + 0, /*tp_print*/ + 0, /*tp_getattr*/ + 0, /*tp_setattr*/ + 0, /*tp_reserved*/ + 0, /*tp_repr*/ + 0, /*tp_as_number*/ + 0, /*tp_as_sequence*/ + 0, /*tp_as_mapping*/ + 0, /*tp_hash*/ + 0, /*tp_call*/ + 0, /*tp_str*/ + 0, /*tp_getattro*/ + 0, /*tp_setattro*/ + 0, /*tp_as_buffer*/ + Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /*tp_flags*/ + 0, /*tp_doc*/ + 0, /*tp_traverse*/ + 0, /*tp_clear*/ + 0, /*tp_richcompare*/ + 0, /*tp_weaklistoffset*/ + 0, /*tp_iter*/ + 0, /*tp_iternext*/ + 0, /*tp_methods*/ + 0, /*tp_members*/ + 0, /*tp_getset*/ + 0, /* see PyInit_xx */ /*tp_base*/ + 0, /*tp_dict*/ + 0, /*tp_descr_get*/ + 0, /*tp_descr_set*/ + 0, /*tp_dictoffset*/ + 0, /*tp_init*/ + 0, /*tp_alloc*/ + 0, /*tp_new*/ + 0, /*tp_free*/ + 0, /*tp_is_gc*/ }; /* ---------- */ @@ -263,54 +263,54 @@ static PyObject * null_richcompare(PyObject *self, PyObject *other, int op) { - Py_INCREF(Py_NotImplemented); - return Py_NotImplemented; + Py_INCREF(Py_NotImplemented); + return Py_NotImplemented; } static PyTypeObject Null_Type = { - /* The ob_type field must be initialized in the module init function - * to be portable to Windows without using C++. */ - PyVarObject_HEAD_INIT(NULL, 0) - "xxmodule.Null", /*tp_name*/ - 0, /*tp_basicsize*/ - 0, /*tp_itemsize*/ - /* methods */ - 0, /*tp_dealloc*/ - 0, /*tp_print*/ - 0, /*tp_getattr*/ - 0, /*tp_setattr*/ - 0, /*tp_reserved*/ - 0, /*tp_repr*/ - 0, /*tp_as_number*/ - 0, /*tp_as_sequence*/ - 0, /*tp_as_mapping*/ - 0, /*tp_hash*/ - 0, /*tp_call*/ - 0, /*tp_str*/ - 0, /*tp_getattro*/ - 0, /*tp_setattro*/ - 0, /*tp_as_buffer*/ - Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /*tp_flags*/ - 0, /*tp_doc*/ - 0, /*tp_traverse*/ - 0, /*tp_clear*/ - null_richcompare, /*tp_richcompare*/ - 0, /*tp_weaklistoffset*/ - 0, /*tp_iter*/ - 0, /*tp_iternext*/ - 0, /*tp_methods*/ - 0, /*tp_members*/ - 0, /*tp_getset*/ - 0, /* see PyInit_xx */ /*tp_base*/ - 0, /*tp_dict*/ - 0, /*tp_descr_get*/ - 0, /*tp_descr_set*/ - 0, /*tp_dictoffset*/ - 0, /*tp_init*/ - 0, /*tp_alloc*/ - 0, /* see PyInit_xx */ /*tp_new*/ - 0, /*tp_free*/ - 0, /*tp_is_gc*/ + /* The ob_type field must be initialized in the module init function + * to be portable to Windows without using C++. */ + PyVarObject_HEAD_INIT(NULL, 0) + "xxmodule.Null", /*tp_name*/ + 0, /*tp_basicsize*/ + 0, /*tp_itemsize*/ + /* methods */ + 0, /*tp_dealloc*/ + 0, /*tp_print*/ + 0, /*tp_getattr*/ + 0, /*tp_setattr*/ + 0, /*tp_reserved*/ + 0, /*tp_repr*/ + 0, /*tp_as_number*/ + 0, /*tp_as_sequence*/ + 0, /*tp_as_mapping*/ + 0, /*tp_hash*/ + 0, /*tp_call*/ + 0, /*tp_str*/ + 0, /*tp_getattro*/ + 0, /*tp_setattro*/ + 0, /*tp_as_buffer*/ + Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /*tp_flags*/ + 0, /*tp_doc*/ + 0, /*tp_traverse*/ + 0, /*tp_clear*/ + null_richcompare, /*tp_richcompare*/ + 0, /*tp_weaklistoffset*/ + 0, /*tp_iter*/ + 0, /*tp_iternext*/ + 0, /*tp_methods*/ + 0, /*tp_members*/ + 0, /*tp_getset*/ + 0, /* see PyInit_xx */ /*tp_base*/ + 0, /*tp_dict*/ + 0, /*tp_descr_get*/ + 0, /*tp_descr_set*/ + 0, /*tp_dictoffset*/ + 0, /*tp_init*/ + 0, /*tp_alloc*/ + 0, /* see PyInit_xx */ /*tp_new*/ + 0, /*tp_free*/ + 0, /*tp_is_gc*/ }; @@ -320,15 +320,15 @@ /* List of functions defined in the module */ static PyMethodDef xx_methods[] = { - {"roj", xx_roj, METH_VARARGS, - PyDoc_STR("roj(a,b) -> None")}, - {"foo", xx_foo, METH_VARARGS, - xx_foo_doc}, - {"new", xx_new, METH_VARARGS, - PyDoc_STR("new() -> new Xx object")}, - {"bug", xx_bug, METH_VARARGS, - PyDoc_STR("bug(o) -> None")}, - {NULL, NULL} /* sentinel */ + {"roj", xx_roj, METH_VARARGS, + PyDoc_STR("roj(a,b) -> None")}, + {"foo", xx_foo, METH_VARARGS, + xx_foo_doc}, + {"new", xx_new, METH_VARARGS, + PyDoc_STR("new() -> new Xx object")}, + {"bug", xx_bug, METH_VARARGS, + PyDoc_STR("bug(o) -> None")}, + {NULL, NULL} /* sentinel */ }; PyDoc_STRVAR(module_doc, @@ -338,59 +338,59 @@ static struct PyModuleDef xxmodule = { - PyModuleDef_HEAD_INIT, - "xx", - module_doc, - -1, - xx_methods, - NULL, - NULL, - NULL, - NULL + PyModuleDef_HEAD_INIT, + "xx", + module_doc, + -1, + xx_methods, + NULL, + NULL, + NULL, + NULL }; PyMODINIT_FUNC PyInit_xx(void) { - PyObject *m = NULL; + PyObject *m = NULL; - /* Due to cross platform compiler issues the slots must be filled - * here. It's required for portability to Windows without requiring - * C++. */ - Null_Type.tp_base = &PyBaseObject_Type; - Null_Type.tp_new = PyType_GenericNew; - Str_Type.tp_base = &PyUnicode_Type; - - /* Finalize the type object including setting type of the new type - * object; doing it here is required for portability, too. */ - if (PyType_Ready(&Xxo_Type) < 0) - goto fail; - - /* Create the module and add the functions */ - m = PyModule_Create(&xxmodule); - if (m == NULL) - goto fail; - - /* Add some symbolic constants to the module */ - if (ErrorObject == NULL) { - ErrorObject = PyErr_NewException("xx.error", NULL, NULL); - if (ErrorObject == NULL) - goto fail; - } - Py_INCREF(ErrorObject); - PyModule_AddObject(m, "error", ErrorObject); - - /* Add Str */ - if (PyType_Ready(&Str_Type) < 0) - goto fail; - PyModule_AddObject(m, "Str", (PyObject *)&Str_Type); - - /* Add Null */ - if (PyType_Ready(&Null_Type) < 0) - goto fail; - PyModule_AddObject(m, "Null", (PyObject *)&Null_Type); - return m; + /* Due to cross platform compiler issues the slots must be filled + * here. It's required for portability to Windows without requiring + * C++. */ + Null_Type.tp_base = &PyBaseObject_Type; + Null_Type.tp_new = PyType_GenericNew; + Str_Type.tp_base = &PyUnicode_Type; + + /* Finalize the type object including setting type of the new type + * object; doing it here is required for portability, too. */ + if (PyType_Ready(&Xxo_Type) < 0) + goto fail; + + /* Create the module and add the functions */ + m = PyModule_Create(&xxmodule); + if (m == NULL) + goto fail; + + /* Add some symbolic constants to the module */ + if (ErrorObject == NULL) { + ErrorObject = PyErr_NewException("xx.error", NULL, NULL); + if (ErrorObject == NULL) + goto fail; + } + Py_INCREF(ErrorObject); + PyModule_AddObject(m, "error", ErrorObject); + + /* Add Str */ + if (PyType_Ready(&Str_Type) < 0) + goto fail; + PyModule_AddObject(m, "Str", (PyObject *)&Str_Type); + + /* Add Null */ + if (PyType_Ready(&Null_Type) < 0) + goto fail; + PyModule_AddObject(m, "Null", (PyObject *)&Null_Type); + return m; fail: - Py_XDECREF(m); - return NULL; + Py_XDECREF(m); + return NULL; } Modified: python/branches/py3k/Modules/xxsubtype.c ============================================================================== --- python/branches/py3k/Modules/xxsubtype.c (original) +++ python/branches/py3k/Modules/xxsubtype.c Sun May 9 17:52:27 2010 @@ -19,291 +19,291 @@ /* spamlist -- a list subtype */ typedef struct { - PyListObject list; - int state; + PyListObject list; + int state; } spamlistobject; static PyObject * spamlist_getstate(spamlistobject *self, PyObject *args) { - if (!PyArg_ParseTuple(args, ":getstate")) - return NULL; - return PyLong_FromLong(self->state); + if (!PyArg_ParseTuple(args, ":getstate")) + return NULL; + return PyLong_FromLong(self->state); } static PyObject * spamlist_setstate(spamlistobject *self, PyObject *args) { - int state; + int state; - if (!PyArg_ParseTuple(args, "i:setstate", &state)) - return NULL; - self->state = state; - Py_INCREF(Py_None); - return Py_None; + if (!PyArg_ParseTuple(args, "i:setstate", &state)) + return NULL; + self->state = state; + Py_INCREF(Py_None); + return Py_None; } static PyObject * spamlist_specialmeth(PyObject *self, PyObject *args, PyObject *kw) { - PyObject *result = PyTuple_New(3); + PyObject *result = PyTuple_New(3); - if (result != NULL) { - if (self == NULL) - self = Py_None; - if (kw == NULL) - kw = Py_None; - Py_INCREF(self); - PyTuple_SET_ITEM(result, 0, self); - Py_INCREF(args); - PyTuple_SET_ITEM(result, 1, args); - Py_INCREF(kw); - PyTuple_SET_ITEM(result, 2, kw); - } - return result; + if (result != NULL) { + if (self == NULL) + self = Py_None; + if (kw == NULL) + kw = Py_None; + Py_INCREF(self); + PyTuple_SET_ITEM(result, 0, self); + Py_INCREF(args); + PyTuple_SET_ITEM(result, 1, args); + Py_INCREF(kw); + PyTuple_SET_ITEM(result, 2, kw); + } + return result; } static PyMethodDef spamlist_methods[] = { - {"getstate", (PyCFunction)spamlist_getstate, METH_VARARGS, - PyDoc_STR("getstate() -> state")}, - {"setstate", (PyCFunction)spamlist_setstate, METH_VARARGS, - PyDoc_STR("setstate(state)")}, - /* These entries differ only in the flags; they are used by the tests - in test.test_descr. */ - {"classmeth", (PyCFunction)spamlist_specialmeth, - METH_VARARGS | METH_KEYWORDS | METH_CLASS, - PyDoc_STR("classmeth(*args, **kw)")}, - {"staticmeth", (PyCFunction)spamlist_specialmeth, - METH_VARARGS | METH_KEYWORDS | METH_STATIC, - PyDoc_STR("staticmeth(*args, **kw)")}, - {NULL, NULL}, + {"getstate", (PyCFunction)spamlist_getstate, METH_VARARGS, + PyDoc_STR("getstate() -> state")}, + {"setstate", (PyCFunction)spamlist_setstate, METH_VARARGS, + PyDoc_STR("setstate(state)")}, + /* These entries differ only in the flags; they are used by the tests + in test.test_descr. */ + {"classmeth", (PyCFunction)spamlist_specialmeth, + METH_VARARGS | METH_KEYWORDS | METH_CLASS, + PyDoc_STR("classmeth(*args, **kw)")}, + {"staticmeth", (PyCFunction)spamlist_specialmeth, + METH_VARARGS | METH_KEYWORDS | METH_STATIC, + PyDoc_STR("staticmeth(*args, **kw)")}, + {NULL, NULL}, }; static int spamlist_init(spamlistobject *self, PyObject *args, PyObject *kwds) { - if (PyList_Type.tp_init((PyObject *)self, args, kwds) < 0) - return -1; - self->state = 0; - return 0; + if (PyList_Type.tp_init((PyObject *)self, args, kwds) < 0) + return -1; + self->state = 0; + return 0; } static PyObject * spamlist_state_get(spamlistobject *self) { - return PyLong_FromLong(self->state); + return PyLong_FromLong(self->state); } static PyGetSetDef spamlist_getsets[] = { - {"state", (getter)spamlist_state_get, NULL, - PyDoc_STR("an int variable for demonstration purposes")}, - {0} + {"state", (getter)spamlist_state_get, NULL, + PyDoc_STR("an int variable for demonstration purposes")}, + {0} }; static PyTypeObject spamlist_type = { - PyVarObject_HEAD_INIT(DEFERRED_ADDRESS(&PyType_Type), 0) - "xxsubtype.spamlist", - sizeof(spamlistobject), - 0, - 0, /* tp_dealloc */ - 0, /* tp_print */ - 0, /* tp_getattr */ - 0, /* tp_setattr */ - 0, /* tp_reserved */ - 0, /* tp_repr */ - 0, /* tp_as_number */ - 0, /* tp_as_sequence */ - 0, /* tp_as_mapping */ - 0, /* tp_hash */ - 0, /* tp_call */ - 0, /* tp_str */ - 0, /* tp_getattro */ - 0, /* tp_setattro */ - 0, /* tp_as_buffer */ - Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */ - 0, /* tp_doc */ - 0, /* tp_traverse */ - 0, /* tp_clear */ - 0, /* tp_richcompare */ - 0, /* tp_weaklistoffset */ - 0, /* tp_iter */ - 0, /* tp_iternext */ - spamlist_methods, /* tp_methods */ - 0, /* tp_members */ - spamlist_getsets, /* tp_getset */ - DEFERRED_ADDRESS(&PyList_Type), /* tp_base */ - 0, /* tp_dict */ - 0, /* tp_descr_get */ - 0, /* tp_descr_set */ - 0, /* tp_dictoffset */ - (initproc)spamlist_init, /* tp_init */ - 0, /* tp_alloc */ - 0, /* tp_new */ + PyVarObject_HEAD_INIT(DEFERRED_ADDRESS(&PyType_Type), 0) + "xxsubtype.spamlist", + sizeof(spamlistobject), + 0, + 0, /* tp_dealloc */ + 0, /* tp_print */ + 0, /* tp_getattr */ + 0, /* tp_setattr */ + 0, /* tp_reserved */ + 0, /* tp_repr */ + 0, /* tp_as_number */ + 0, /* tp_as_sequence */ + 0, /* tp_as_mapping */ + 0, /* tp_hash */ + 0, /* tp_call */ + 0, /* tp_str */ + 0, /* tp_getattro */ + 0, /* tp_setattro */ + 0, /* tp_as_buffer */ + Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */ + 0, /* tp_doc */ + 0, /* tp_traverse */ + 0, /* tp_clear */ + 0, /* tp_richcompare */ + 0, /* tp_weaklistoffset */ + 0, /* tp_iter */ + 0, /* tp_iternext */ + spamlist_methods, /* tp_methods */ + 0, /* tp_members */ + spamlist_getsets, /* tp_getset */ + DEFERRED_ADDRESS(&PyList_Type), /* tp_base */ + 0, /* tp_dict */ + 0, /* tp_descr_get */ + 0, /* tp_descr_set */ + 0, /* tp_dictoffset */ + (initproc)spamlist_init, /* tp_init */ + 0, /* tp_alloc */ + 0, /* tp_new */ }; /* spamdict -- a dict subtype */ typedef struct { - PyDictObject dict; - int state; + PyDictObject dict; + int state; } spamdictobject; static PyObject * spamdict_getstate(spamdictobject *self, PyObject *args) { - if (!PyArg_ParseTuple(args, ":getstate")) - return NULL; - return PyLong_FromLong(self->state); + if (!PyArg_ParseTuple(args, ":getstate")) + return NULL; + return PyLong_FromLong(self->state); } static PyObject * spamdict_setstate(spamdictobject *self, PyObject *args) { - int state; + int state; - if (!PyArg_ParseTuple(args, "i:setstate", &state)) - return NULL; - self->state = state; - Py_INCREF(Py_None); - return Py_None; + if (!PyArg_ParseTuple(args, "i:setstate", &state)) + return NULL; + self->state = state; + Py_INCREF(Py_None); + return Py_None; } static PyMethodDef spamdict_methods[] = { - {"getstate", (PyCFunction)spamdict_getstate, METH_VARARGS, - PyDoc_STR("getstate() -> state")}, - {"setstate", (PyCFunction)spamdict_setstate, METH_VARARGS, - PyDoc_STR("setstate(state)")}, - {NULL, NULL}, + {"getstate", (PyCFunction)spamdict_getstate, METH_VARARGS, + PyDoc_STR("getstate() -> state")}, + {"setstate", (PyCFunction)spamdict_setstate, METH_VARARGS, + PyDoc_STR("setstate(state)")}, + {NULL, NULL}, }; static int spamdict_init(spamdictobject *self, PyObject *args, PyObject *kwds) { - if (PyDict_Type.tp_init((PyObject *)self, args, kwds) < 0) - return -1; - self->state = 0; - return 0; + if (PyDict_Type.tp_init((PyObject *)self, args, kwds) < 0) + return -1; + self->state = 0; + return 0; } static PyMemberDef spamdict_members[] = { - {"state", T_INT, offsetof(spamdictobject, state), READONLY, - PyDoc_STR("an int variable for demonstration purposes")}, - {0} + {"state", T_INT, offsetof(spamdictobject, state), READONLY, + PyDoc_STR("an int variable for demonstration purposes")}, + {0} }; static PyTypeObject spamdict_type = { - PyVarObject_HEAD_INIT(DEFERRED_ADDRESS(&PyType_Type), 0) - "xxsubtype.spamdict", - sizeof(spamdictobject), - 0, - 0, /* tp_dealloc */ - 0, /* tp_print */ - 0, /* tp_getattr */ - 0, /* tp_setattr */ - 0, /* tp_reserved */ - 0, /* tp_repr */ - 0, /* tp_as_number */ - 0, /* tp_as_sequence */ - 0, /* tp_as_mapping */ - 0, /* tp_hash */ - 0, /* tp_call */ - 0, /* tp_str */ - 0, /* tp_getattro */ - 0, /* tp_setattro */ - 0, /* tp_as_buffer */ - Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */ - 0, /* tp_doc */ - 0, /* tp_traverse */ - 0, /* tp_clear */ - 0, /* tp_richcompare */ - 0, /* tp_weaklistoffset */ - 0, /* tp_iter */ - 0, /* tp_iternext */ - spamdict_methods, /* tp_methods */ - spamdict_members, /* tp_members */ - 0, /* tp_getset */ - DEFERRED_ADDRESS(&PyDict_Type), /* tp_base */ - 0, /* tp_dict */ - 0, /* tp_descr_get */ - 0, /* tp_descr_set */ - 0, /* tp_dictoffset */ - (initproc)spamdict_init, /* tp_init */ - 0, /* tp_alloc */ - 0, /* tp_new */ + PyVarObject_HEAD_INIT(DEFERRED_ADDRESS(&PyType_Type), 0) + "xxsubtype.spamdict", + sizeof(spamdictobject), + 0, + 0, /* tp_dealloc */ + 0, /* tp_print */ + 0, /* tp_getattr */ + 0, /* tp_setattr */ + 0, /* tp_reserved */ + 0, /* tp_repr */ + 0, /* tp_as_number */ + 0, /* tp_as_sequence */ + 0, /* tp_as_mapping */ + 0, /* tp_hash */ + 0, /* tp_call */ + 0, /* tp_str */ + 0, /* tp_getattro */ + 0, /* tp_setattro */ + 0, /* tp_as_buffer */ + Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */ + 0, /* tp_doc */ + 0, /* tp_traverse */ + 0, /* tp_clear */ + 0, /* tp_richcompare */ + 0, /* tp_weaklistoffset */ + 0, /* tp_iter */ + 0, /* tp_iternext */ + spamdict_methods, /* tp_methods */ + spamdict_members, /* tp_members */ + 0, /* tp_getset */ + DEFERRED_ADDRESS(&PyDict_Type), /* tp_base */ + 0, /* tp_dict */ + 0, /* tp_descr_get */ + 0, /* tp_descr_set */ + 0, /* tp_dictoffset */ + (initproc)spamdict_init, /* tp_init */ + 0, /* tp_alloc */ + 0, /* tp_new */ }; static PyObject * spam_bench(PyObject *self, PyObject *args) { - PyObject *obj, *name, *res; - int n = 1000; - time_t t0, t1; - - if (!PyArg_ParseTuple(args, "OS|i", &obj, &name, &n)) - return NULL; - t0 = clock(); - while (--n >= 0) { - res = PyObject_GetAttr(obj, name); - if (res == NULL) - return NULL; - Py_DECREF(res); - } - t1 = clock(); - return PyFloat_FromDouble((double)(t1-t0) / CLOCKS_PER_SEC); + PyObject *obj, *name, *res; + int n = 1000; + time_t t0, t1; + + if (!PyArg_ParseTuple(args, "OS|i", &obj, &name, &n)) + return NULL; + t0 = clock(); + while (--n >= 0) { + res = PyObject_GetAttr(obj, name); + if (res == NULL) + return NULL; + Py_DECREF(res); + } + t1 = clock(); + return PyFloat_FromDouble((double)(t1-t0) / CLOCKS_PER_SEC); } static PyMethodDef xxsubtype_functions[] = { - {"bench", spam_bench, METH_VARARGS}, - {NULL, NULL} /* sentinel */ + {"bench", spam_bench, METH_VARARGS}, + {NULL, NULL} /* sentinel */ }; static struct PyModuleDef xxsubtypemodule = { - PyModuleDef_HEAD_INIT, - "xxsubtype", - xxsubtype__doc__, - -1, - xxsubtype_functions, - NULL, - NULL, - NULL, - NULL + PyModuleDef_HEAD_INIT, + "xxsubtype", + xxsubtype__doc__, + -1, + xxsubtype_functions, + NULL, + NULL, + NULL, + NULL }; PyMODINIT_FUNC PyInit_xxsubtype(void) { - PyObject *m; + PyObject *m; - /* Fill in deferred data addresses. This must be done before - PyType_Ready() is called. Note that PyType_Ready() automatically - initializes the ob.ob_type field to &PyType_Type if it's NULL, - so it's not necessary to fill in ob_type first. */ - spamdict_type.tp_base = &PyDict_Type; - if (PyType_Ready(&spamdict_type) < 0) - return NULL; - - spamlist_type.tp_base = &PyList_Type; - if (PyType_Ready(&spamlist_type) < 0) - return NULL; - - m = PyModule_Create(&xxsubtypemodule); - if (m == NULL) - return NULL; - - if (PyType_Ready(&spamlist_type) < 0) - return NULL; - if (PyType_Ready(&spamdict_type) < 0) - return NULL; - - Py_INCREF(&spamlist_type); - if (PyModule_AddObject(m, "spamlist", - (PyObject *) &spamlist_type) < 0) - return NULL; - - Py_INCREF(&spamdict_type); - if (PyModule_AddObject(m, "spamdict", - (PyObject *) &spamdict_type) < 0) - return NULL; - return m; + /* Fill in deferred data addresses. This must be done before + PyType_Ready() is called. Note that PyType_Ready() automatically + initializes the ob.ob_type field to &PyType_Type if it's NULL, + so it's not necessary to fill in ob_type first. */ + spamdict_type.tp_base = &PyDict_Type; + if (PyType_Ready(&spamdict_type) < 0) + return NULL; + + spamlist_type.tp_base = &PyList_Type; + if (PyType_Ready(&spamlist_type) < 0) + return NULL; + + m = PyModule_Create(&xxsubtypemodule); + if (m == NULL) + return NULL; + + if (PyType_Ready(&spamlist_type) < 0) + return NULL; + if (PyType_Ready(&spamdict_type) < 0) + return NULL; + + Py_INCREF(&spamlist_type); + if (PyModule_AddObject(m, "spamlist", + (PyObject *) &spamlist_type) < 0) + return NULL; + + Py_INCREF(&spamdict_type); + if (PyModule_AddObject(m, "spamdict", + (PyObject *) &spamdict_type) < 0) + return NULL; + return m; } Modified: python/branches/py3k/Modules/zipimport.c ============================================================================== --- python/branches/py3k/Modules/zipimport.c (original) +++ python/branches/py3k/Modules/zipimport.c Sun May 9 17:52:27 2010 @@ -10,8 +10,8 @@ #define IS_PACKAGE 0x2 struct st_zip_searchorder { - char suffix[14]; - int type; + char suffix[14]; + int type; }; /* zip_searchorder defines how we search for a module in the Zip @@ -20,13 +20,13 @@ are swapped by initzipimport() if we run in optimized mode. Also, '/' is replaced by SEP there. */ static struct st_zip_searchorder zip_searchorder[] = { - {"/__init__.pyc", IS_PACKAGE | IS_BYTECODE}, - {"/__init__.pyo", IS_PACKAGE | IS_BYTECODE}, - {"/__init__.py", IS_PACKAGE | IS_SOURCE}, - {".pyc", IS_BYTECODE}, - {".pyo", IS_BYTECODE}, - {".py", IS_SOURCE}, - {"", 0} + {"/__init__.pyc", IS_PACKAGE | IS_BYTECODE}, + {"/__init__.pyo", IS_PACKAGE | IS_BYTECODE}, + {"/__init__.py", IS_PACKAGE | IS_SOURCE}, + {".pyc", IS_BYTECODE}, + {".pyo", IS_BYTECODE}, + {".py", IS_SOURCE}, + {"", 0} }; /* zipimporter object definition and support */ @@ -34,10 +34,10 @@ typedef struct _zipimporter ZipImporter; struct _zipimporter { - PyObject_HEAD - PyObject *archive; /* pathname of the Zip archive */ - PyObject *prefix; /* file prefix: "a/sub/directory/" */ - PyObject *files; /* dict with file info {path: toc_entry} */ + PyObject_HEAD + PyObject *archive; /* pathname of the Zip archive */ + PyObject *prefix; /* file prefix: "a/sub/directory/" */ + PyObject *files; /* dict with file info {path: toc_entry} */ }; static PyObject *ZipImportError; @@ -47,7 +47,7 @@ static PyObject *read_directory(char *archive); static PyObject *get_data(char *archive, PyObject *toc_entry); static PyObject *get_module_code(ZipImporter *self, char *fullname, - int *p_ispackage, char **p_modpath); + int *p_ispackage, char **p_modpath); #define ZipImporter_Check(op) PyObject_TypeCheck(op, &ZipImporter_Type) @@ -60,147 +60,147 @@ static int zipimporter_init(ZipImporter *self, PyObject *args, PyObject *kwds) { - char *path, *p, *prefix, buf[MAXPATHLEN+2]; - size_t len; + char *path, *p, *prefix, buf[MAXPATHLEN+2]; + size_t len; - if (!_PyArg_NoKeywords("zipimporter()", kwds)) - return -1; + if (!_PyArg_NoKeywords("zipimporter()", kwds)) + return -1; - if (!PyArg_ParseTuple(args, "s:zipimporter", &path)) - return -1; + if (!PyArg_ParseTuple(args, "s:zipimporter", &path)) + return -1; - len = strlen(path); - if (len == 0) { - PyErr_SetString(ZipImportError, "archive path is empty"); - return -1; - } - if (len >= MAXPATHLEN) { - PyErr_SetString(ZipImportError, - "archive path too long"); - return -1; - } - strcpy(buf, path); + len = strlen(path); + if (len == 0) { + PyErr_SetString(ZipImportError, "archive path is empty"); + return -1; + } + if (len >= MAXPATHLEN) { + PyErr_SetString(ZipImportError, + "archive path too long"); + return -1; + } + strcpy(buf, path); #ifdef ALTSEP - for (p = buf; *p; p++) { - if (*p == ALTSEP) - *p = SEP; - } + for (p = buf; *p; p++) { + if (*p == ALTSEP) + *p = SEP; + } #endif - path = NULL; - prefix = NULL; - for (;;) { - struct stat statbuf; - int rv; - - rv = stat(buf, &statbuf); - if (rv == 0) { - /* it exists */ - if (S_ISREG(statbuf.st_mode)) - /* it's a file */ - path = buf; - break; - } - /* back up one path element */ - p = strrchr(buf, SEP); - if (prefix != NULL) - *prefix = SEP; - if (p == NULL) - break; - *p = '\0'; - prefix = p; - } - if (path != NULL) { - PyObject *files; - files = PyDict_GetItemString(zip_directory_cache, path); - if (files == NULL) { - files = read_directory(buf); - if (files == NULL) - return -1; - if (PyDict_SetItemString(zip_directory_cache, path, - files) != 0) - return -1; - } - else - Py_INCREF(files); - self->files = files; - } - else { - PyErr_SetString(ZipImportError, "not a Zip file"); - return -1; - } - - if (prefix == NULL) - prefix = ""; - else { - prefix++; - len = strlen(prefix); - if (prefix[len-1] != SEP) { - /* add trailing SEP */ - prefix[len] = SEP; - prefix[len + 1] = '\0'; - } - } - - self->archive = PyUnicode_FromString(buf); - if (self->archive == NULL) - return -1; - - self->prefix = PyUnicode_FromString(prefix); - if (self->prefix == NULL) - return -1; + path = NULL; + prefix = NULL; + for (;;) { + struct stat statbuf; + int rv; + + rv = stat(buf, &statbuf); + if (rv == 0) { + /* it exists */ + if (S_ISREG(statbuf.st_mode)) + /* it's a file */ + path = buf; + break; + } + /* back up one path element */ + p = strrchr(buf, SEP); + if (prefix != NULL) + *prefix = SEP; + if (p == NULL) + break; + *p = '\0'; + prefix = p; + } + if (path != NULL) { + PyObject *files; + files = PyDict_GetItemString(zip_directory_cache, path); + if (files == NULL) { + files = read_directory(buf); + if (files == NULL) + return -1; + if (PyDict_SetItemString(zip_directory_cache, path, + files) != 0) + return -1; + } + else + Py_INCREF(files); + self->files = files; + } + else { + PyErr_SetString(ZipImportError, "not a Zip file"); + return -1; + } + + if (prefix == NULL) + prefix = ""; + else { + prefix++; + len = strlen(prefix); + if (prefix[len-1] != SEP) { + /* add trailing SEP */ + prefix[len] = SEP; + prefix[len + 1] = '\0'; + } + } + + self->archive = PyUnicode_FromString(buf); + if (self->archive == NULL) + return -1; + + self->prefix = PyUnicode_FromString(prefix); + if (self->prefix == NULL) + return -1; - return 0; + return 0; } /* GC support. */ static int zipimporter_traverse(PyObject *obj, visitproc visit, void *arg) { - ZipImporter *self = (ZipImporter *)obj; - Py_VISIT(self->files); - return 0; + ZipImporter *self = (ZipImporter *)obj; + Py_VISIT(self->files); + return 0; } static void zipimporter_dealloc(ZipImporter *self) { - PyObject_GC_UnTrack(self); - Py_XDECREF(self->archive); - Py_XDECREF(self->prefix); - Py_XDECREF(self->files); - Py_TYPE(self)->tp_free((PyObject *)self); + PyObject_GC_UnTrack(self); + Py_XDECREF(self->archive); + Py_XDECREF(self->prefix); + Py_XDECREF(self->files); + Py_TYPE(self)->tp_free((PyObject *)self); } static PyObject * zipimporter_repr(ZipImporter *self) { - char *archive = "???"; - char *prefix = ""; + char *archive = "???"; + char *prefix = ""; - if (self->archive != NULL && PyUnicode_Check(self->archive)) - archive = _PyUnicode_AsString(self->archive); - if (self->prefix != NULL && PyUnicode_Check(self->prefix)) - prefix = _PyUnicode_AsString(self->prefix); - if (prefix != NULL && *prefix) - return PyUnicode_FromFormat("", - archive, SEP, prefix); - else - return PyUnicode_FromFormat("", - archive); + if (self->archive != NULL && PyUnicode_Check(self->archive)) + archive = _PyUnicode_AsString(self->archive); + if (self->prefix != NULL && PyUnicode_Check(self->prefix)) + prefix = _PyUnicode_AsString(self->prefix); + if (prefix != NULL && *prefix) + return PyUnicode_FromFormat("", + archive, SEP, prefix); + else + return PyUnicode_FromFormat("", + archive); } /* return fullname.split(".")[-1] */ static char * get_subname(char *fullname) { - char *subname = strrchr(fullname, '.'); - if (subname == NULL) - subname = fullname; - else - subname++; - return subname; + char *subname = strrchr(fullname, '.'); + if (subname == NULL) + subname = fullname; + else + subname++; + return subname; } /* Given a (sub)modulename, write the potential file path in the @@ -209,59 +209,59 @@ static int make_filename(char *prefix, char *name, char *path) { - size_t len; - char *p; + size_t len; + char *p; - len = strlen(prefix); + len = strlen(prefix); - /* self.prefix + name [+ SEP + "__init__"] + ".py[co]" */ - if (len + strlen(name) + 13 >= MAXPATHLEN) { - PyErr_SetString(ZipImportError, "path too long"); - return -1; - } - - strcpy(path, prefix); - strcpy(path + len, name); - for (p = path + len; *p; p++) { - if (*p == '.') - *p = SEP; - } - len += strlen(name); - assert(len < INT_MAX); - return (int)len; + /* self.prefix + name [+ SEP + "__init__"] + ".py[co]" */ + if (len + strlen(name) + 13 >= MAXPATHLEN) { + PyErr_SetString(ZipImportError, "path too long"); + return -1; + } + + strcpy(path, prefix); + strcpy(path + len, name); + for (p = path + len; *p; p++) { + if (*p == '.') + *p = SEP; + } + len += strlen(name); + assert(len < INT_MAX); + return (int)len; } enum zi_module_info { - MI_ERROR, - MI_NOT_FOUND, - MI_MODULE, - MI_PACKAGE + MI_ERROR, + MI_NOT_FOUND, + MI_MODULE, + MI_PACKAGE }; /* Return some information about a module. */ static enum zi_module_info get_module_info(ZipImporter *self, char *fullname) { - char *subname, path[MAXPATHLEN + 1]; - int len; - struct st_zip_searchorder *zso; - - subname = get_subname(fullname); - - len = make_filename(_PyUnicode_AsString(self->prefix), subname, path); - if (len < 0) - return MI_ERROR; - - for (zso = zip_searchorder; *zso->suffix; zso++) { - strcpy(path + len, zso->suffix); - if (PyDict_GetItemString(self->files, path) != NULL) { - if (zso->type & IS_PACKAGE) - return MI_PACKAGE; - else - return MI_MODULE; - } - } - return MI_NOT_FOUND; + char *subname, path[MAXPATHLEN + 1]; + int len; + struct st_zip_searchorder *zso; + + subname = get_subname(fullname); + + len = make_filename(_PyUnicode_AsString(self->prefix), subname, path); + if (len < 0) + return MI_ERROR; + + for (zso = zip_searchorder; *zso->suffix; zso++) { + strcpy(path + len, zso->suffix); + if (PyDict_GetItemString(self->files, path) != NULL) { + if (zso->type & IS_PACKAGE) + return MI_PACKAGE; + else + return MI_MODULE; + } + } + return MI_NOT_FOUND; } /* Check whether we can satisfy the import of the module named by @@ -269,86 +269,86 @@ static PyObject * zipimporter_find_module(PyObject *obj, PyObject *args) { - ZipImporter *self = (ZipImporter *)obj; - PyObject *path = NULL; - char *fullname; - enum zi_module_info mi; - - if (!PyArg_ParseTuple(args, "s|O:zipimporter.find_module", - &fullname, &path)) - return NULL; - - mi = get_module_info(self, fullname); - if (mi == MI_ERROR) - return NULL; - if (mi == MI_NOT_FOUND) { - Py_INCREF(Py_None); - return Py_None; - } - Py_INCREF(self); - return (PyObject *)self; + ZipImporter *self = (ZipImporter *)obj; + PyObject *path = NULL; + char *fullname; + enum zi_module_info mi; + + if (!PyArg_ParseTuple(args, "s|O:zipimporter.find_module", + &fullname, &path)) + return NULL; + + mi = get_module_info(self, fullname); + if (mi == MI_ERROR) + return NULL; + if (mi == MI_NOT_FOUND) { + Py_INCREF(Py_None); + return Py_None; + } + Py_INCREF(self); + return (PyObject *)self; } /* Load and return the module named by 'fullname'. */ static PyObject * zipimporter_load_module(PyObject *obj, PyObject *args) { - ZipImporter *self = (ZipImporter *)obj; - PyObject *code, *mod, *dict; - char *fullname, *modpath; - int ispackage; - - if (!PyArg_ParseTuple(args, "s:zipimporter.load_module", - &fullname)) - return NULL; - - code = get_module_code(self, fullname, &ispackage, &modpath); - if (code == NULL) - return NULL; - - mod = PyImport_AddModule(fullname); - if (mod == NULL) { - Py_DECREF(code); - return NULL; - } - dict = PyModule_GetDict(mod); - - /* mod.__loader__ = self */ - if (PyDict_SetItemString(dict, "__loader__", (PyObject *)self) != 0) - goto error; - - if (ispackage) { - /* add __path__ to the module *before* the code gets - executed */ - PyObject *pkgpath, *fullpath; - char *subname = get_subname(fullname); - int err; - - fullpath = PyUnicode_FromFormat("%U%c%U%s", - self->archive, SEP, - self->prefix, subname); - if (fullpath == NULL) - goto error; - - pkgpath = Py_BuildValue("[O]", fullpath); - Py_DECREF(fullpath); - if (pkgpath == NULL) - goto error; - err = PyDict_SetItemString(dict, "__path__", pkgpath); - Py_DECREF(pkgpath); - if (err != 0) - goto error; - } - mod = PyImport_ExecCodeModuleEx(fullname, code, modpath); - Py_DECREF(code); - if (Py_VerboseFlag) - PySys_WriteStderr("import %s # loaded from Zip %s\n", - fullname, modpath); - return mod; + ZipImporter *self = (ZipImporter *)obj; + PyObject *code, *mod, *dict; + char *fullname, *modpath; + int ispackage; + + if (!PyArg_ParseTuple(args, "s:zipimporter.load_module", + &fullname)) + return NULL; + + code = get_module_code(self, fullname, &ispackage, &modpath); + if (code == NULL) + return NULL; + + mod = PyImport_AddModule(fullname); + if (mod == NULL) { + Py_DECREF(code); + return NULL; + } + dict = PyModule_GetDict(mod); + + /* mod.__loader__ = self */ + if (PyDict_SetItemString(dict, "__loader__", (PyObject *)self) != 0) + goto error; + + if (ispackage) { + /* add __path__ to the module *before* the code gets + executed */ + PyObject *pkgpath, *fullpath; + char *subname = get_subname(fullname); + int err; + + fullpath = PyUnicode_FromFormat("%U%c%U%s", + self->archive, SEP, + self->prefix, subname); + if (fullpath == NULL) + goto error; + + pkgpath = Py_BuildValue("[O]", fullpath); + Py_DECREF(fullpath); + if (pkgpath == NULL) + goto error; + err = PyDict_SetItemString(dict, "__path__", pkgpath); + Py_DECREF(pkgpath); + if (err != 0) + goto error; + } + mod = PyImport_ExecCodeModuleEx(fullname, code, modpath); + Py_DECREF(code); + if (Py_VerboseFlag) + PySys_WriteStderr("import %s # loaded from Zip %s\n", + fullname, modpath); + return mod; error: - Py_DECREF(code); - Py_DECREF(mod); - return NULL; + Py_DECREF(code); + Py_DECREF(mod); + return NULL; } /* Return a string matching __file__ for the named module */ @@ -362,13 +362,13 @@ if (!PyArg_ParseTuple(args, "s:zipimporter.get_filename", &fullname)) - return NULL; + return NULL; /* Deciding the filename requires working out where the code would come from if the module was actually loaded */ code = get_module_code(self, fullname, &ispackage, &modpath); if (code == NULL) - return NULL; + return NULL; Py_DECREF(code); /* Only need the path info */ return PyUnicode_FromString(modpath); @@ -378,123 +378,123 @@ static PyObject * zipimporter_is_package(PyObject *obj, PyObject *args) { - ZipImporter *self = (ZipImporter *)obj; - char *fullname; - enum zi_module_info mi; - - if (!PyArg_ParseTuple(args, "s:zipimporter.is_package", - &fullname)) - return NULL; - - mi = get_module_info(self, fullname); - if (mi == MI_ERROR) - return NULL; - if (mi == MI_NOT_FOUND) { - PyErr_Format(ZipImportError, "can't find module '%.200s'", - fullname); - return NULL; - } - return PyBool_FromLong(mi == MI_PACKAGE); + ZipImporter *self = (ZipImporter *)obj; + char *fullname; + enum zi_module_info mi; + + if (!PyArg_ParseTuple(args, "s:zipimporter.is_package", + &fullname)) + return NULL; + + mi = get_module_info(self, fullname); + if (mi == MI_ERROR) + return NULL; + if (mi == MI_NOT_FOUND) { + PyErr_Format(ZipImportError, "can't find module '%.200s'", + fullname); + return NULL; + } + return PyBool_FromLong(mi == MI_PACKAGE); } static PyObject * zipimporter_get_data(PyObject *obj, PyObject *args) { - ZipImporter *self = (ZipImporter *)obj; - char *path; + ZipImporter *self = (ZipImporter *)obj; + char *path; #ifdef ALTSEP - char *p, buf[MAXPATHLEN + 1]; + char *p, buf[MAXPATHLEN + 1]; #endif - PyObject *toc_entry; - Py_ssize_t len; - char *archive_str; + PyObject *toc_entry; + Py_ssize_t len; + char *archive_str; - if (!PyArg_ParseTuple(args, "s:zipimporter.get_data", &path)) - return NULL; + if (!PyArg_ParseTuple(args, "s:zipimporter.get_data", &path)) + return NULL; #ifdef ALTSEP - if (strlen(path) >= MAXPATHLEN) { - PyErr_SetString(ZipImportError, "path too long"); - return NULL; - } - strcpy(buf, path); - for (p = buf; *p; p++) { - if (*p == ALTSEP) - *p = SEP; - } - path = buf; + if (strlen(path) >= MAXPATHLEN) { + PyErr_SetString(ZipImportError, "path too long"); + return NULL; + } + strcpy(buf, path); + for (p = buf; *p; p++) { + if (*p == ALTSEP) + *p = SEP; + } + path = buf; #endif - archive_str = _PyUnicode_AsStringAndSize(self->archive, &len); - if ((size_t)len < strlen(path) && - strncmp(path, archive_str, len) == 0 && - path[len] == SEP) { - path = path + len + 1; - } - - toc_entry = PyDict_GetItemString(self->files, path); - if (toc_entry == NULL) { - PyErr_SetFromErrnoWithFilename(PyExc_IOError, path); - return NULL; - } - return get_data(archive_str, toc_entry); + archive_str = _PyUnicode_AsStringAndSize(self->archive, &len); + if ((size_t)len < strlen(path) && + strncmp(path, archive_str, len) == 0 && + path[len] == SEP) { + path = path + len + 1; + } + + toc_entry = PyDict_GetItemString(self->files, path); + if (toc_entry == NULL) { + PyErr_SetFromErrnoWithFilename(PyExc_IOError, path); + return NULL; + } + return get_data(archive_str, toc_entry); } static PyObject * zipimporter_get_code(PyObject *obj, PyObject *args) { - ZipImporter *self = (ZipImporter *)obj; - char *fullname; + ZipImporter *self = (ZipImporter *)obj; + char *fullname; - if (!PyArg_ParseTuple(args, "s:zipimporter.get_code", &fullname)) - return NULL; + if (!PyArg_ParseTuple(args, "s:zipimporter.get_code", &fullname)) + return NULL; - return get_module_code(self, fullname, NULL, NULL); + return get_module_code(self, fullname, NULL, NULL); } static PyObject * zipimporter_get_source(PyObject *obj, PyObject *args) { - ZipImporter *self = (ZipImporter *)obj; - PyObject *toc_entry; - char *fullname, *subname, path[MAXPATHLEN+1]; - int len; - enum zi_module_info mi; - - if (!PyArg_ParseTuple(args, "s:zipimporter.get_source", &fullname)) - return NULL; - - mi = get_module_info(self, fullname); - if (mi == MI_ERROR) - return NULL; - if (mi == MI_NOT_FOUND) { - PyErr_Format(ZipImportError, "can't find module '%.200s'", - fullname); - return NULL; - } - subname = get_subname(fullname); - - len = make_filename(_PyUnicode_AsString(self->prefix), subname, path); - if (len < 0) - return NULL; - - if (mi == MI_PACKAGE) { - path[len] = SEP; - strcpy(path + len + 1, "__init__.py"); - } - else - strcpy(path + len, ".py"); - - toc_entry = PyDict_GetItemString(self->files, path); - if (toc_entry != NULL) { - PyObject *bytes = get_data(_PyUnicode_AsString(self->archive), toc_entry); - PyObject *res = PyUnicode_FromString(PyBytes_AsString(bytes)); - Py_XDECREF(bytes); - return res; - } - - /* we have the module, but no source */ - Py_INCREF(Py_None); - return Py_None; + ZipImporter *self = (ZipImporter *)obj; + PyObject *toc_entry; + char *fullname, *subname, path[MAXPATHLEN+1]; + int len; + enum zi_module_info mi; + + if (!PyArg_ParseTuple(args, "s:zipimporter.get_source", &fullname)) + return NULL; + + mi = get_module_info(self, fullname); + if (mi == MI_ERROR) + return NULL; + if (mi == MI_NOT_FOUND) { + PyErr_Format(ZipImportError, "can't find module '%.200s'", + fullname); + return NULL; + } + subname = get_subname(fullname); + + len = make_filename(_PyUnicode_AsString(self->prefix), subname, path); + if (len < 0) + return NULL; + + if (mi == MI_PACKAGE) { + path[len] = SEP; + strcpy(path + len + 1, "__init__.py"); + } + else + strcpy(path + len, ".py"); + + toc_entry = PyDict_GetItemString(self->files, path); + if (toc_entry != NULL) { + PyObject *bytes = get_data(_PyUnicode_AsString(self->archive), toc_entry); + PyObject *res = PyUnicode_FromString(PyBytes_AsString(bytes)); + Py_XDECREF(bytes); + return res; + } + + /* we have the module, but no source */ + Py_INCREF(Py_None); + return Py_None; } PyDoc_STRVAR(doc_find_module, @@ -545,28 +545,28 @@ Return the filename for the specified module."); static PyMethodDef zipimporter_methods[] = { - {"find_module", zipimporter_find_module, METH_VARARGS, - doc_find_module}, - {"load_module", zipimporter_load_module, METH_VARARGS, - doc_load_module}, - {"get_data", zipimporter_get_data, METH_VARARGS, - doc_get_data}, - {"get_code", zipimporter_get_code, METH_VARARGS, - doc_get_code}, - {"get_source", zipimporter_get_source, METH_VARARGS, - doc_get_source}, - {"get_filename", zipimporter_get_filename, METH_VARARGS, - doc_get_filename}, - {"is_package", zipimporter_is_package, METH_VARARGS, - doc_is_package}, - {NULL, NULL} /* sentinel */ + {"find_module", zipimporter_find_module, METH_VARARGS, + doc_find_module}, + {"load_module", zipimporter_load_module, METH_VARARGS, + doc_load_module}, + {"get_data", zipimporter_get_data, METH_VARARGS, + doc_get_data}, + {"get_code", zipimporter_get_code, METH_VARARGS, + doc_get_code}, + {"get_source", zipimporter_get_source, METH_VARARGS, + doc_get_source}, + {"get_filename", zipimporter_get_filename, METH_VARARGS, + doc_get_filename}, + {"is_package", zipimporter_is_package, METH_VARARGS, + doc_is_package}, + {NULL, NULL} /* sentinel */ }; static PyMemberDef zipimporter_members[] = { - {"archive", T_OBJECT, offsetof(ZipImporter, archive), READONLY}, - {"prefix", T_OBJECT, offsetof(ZipImporter, prefix), READONLY}, - {"_files", T_OBJECT, offsetof(ZipImporter, files), READONLY}, - {NULL} + {"archive", T_OBJECT, offsetof(ZipImporter, archive), READONLY}, + {"prefix", T_OBJECT, offsetof(ZipImporter, prefix), READONLY}, + {"_files", T_OBJECT, offsetof(ZipImporter, files), READONLY}, + {NULL} }; PyDoc_STRVAR(zipimporter_doc, @@ -586,46 +586,46 @@ #define DEFERRED_ADDRESS(ADDR) 0 static PyTypeObject ZipImporter_Type = { - PyVarObject_HEAD_INIT(DEFERRED_ADDRESS(&PyType_Type), 0) - "zipimport.zipimporter", - sizeof(ZipImporter), - 0, /* tp_itemsize */ - (destructor)zipimporter_dealloc, /* tp_dealloc */ - 0, /* tp_print */ - 0, /* tp_getattr */ - 0, /* tp_setattr */ - 0, /* tp_reserved */ - (reprfunc)zipimporter_repr, /* 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_BASETYPE | - Py_TPFLAGS_HAVE_GC, /* tp_flags */ - zipimporter_doc, /* tp_doc */ - zipimporter_traverse, /* tp_traverse */ - 0, /* tp_clear */ - 0, /* tp_richcompare */ - 0, /* tp_weaklistoffset */ - 0, /* tp_iter */ - 0, /* tp_iternext */ - zipimporter_methods, /* tp_methods */ - zipimporter_members, /* tp_members */ - 0, /* tp_getset */ - 0, /* tp_base */ - 0, /* tp_dict */ - 0, /* tp_descr_get */ - 0, /* tp_descr_set */ - 0, /* tp_dictoffset */ - (initproc)zipimporter_init, /* tp_init */ - PyType_GenericAlloc, /* tp_alloc */ - PyType_GenericNew, /* tp_new */ - PyObject_GC_Del, /* tp_free */ + PyVarObject_HEAD_INIT(DEFERRED_ADDRESS(&PyType_Type), 0) + "zipimport.zipimporter", + sizeof(ZipImporter), + 0, /* tp_itemsize */ + (destructor)zipimporter_dealloc, /* tp_dealloc */ + 0, /* tp_print */ + 0, /* tp_getattr */ + 0, /* tp_setattr */ + 0, /* tp_reserved */ + (reprfunc)zipimporter_repr, /* 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_BASETYPE | + Py_TPFLAGS_HAVE_GC, /* tp_flags */ + zipimporter_doc, /* tp_doc */ + zipimporter_traverse, /* tp_traverse */ + 0, /* tp_clear */ + 0, /* tp_richcompare */ + 0, /* tp_weaklistoffset */ + 0, /* tp_iter */ + 0, /* tp_iternext */ + zipimporter_methods, /* tp_methods */ + zipimporter_members, /* tp_members */ + 0, /* tp_getset */ + 0, /* tp_base */ + 0, /* tp_dict */ + 0, /* tp_descr_get */ + 0, /* tp_descr_set */ + 0, /* tp_dictoffset */ + (initproc)zipimporter_init, /* tp_init */ + PyType_GenericAlloc, /* tp_alloc */ + PyType_GenericNew, /* tp_new */ + PyObject_GC_Del, /* tp_free */ }; @@ -636,16 +636,16 @@ marshal.c:r_long() */ static long get_long(unsigned char *buf) { - long x; - x = buf[0]; - x |= (long)buf[1] << 8; - x |= (long)buf[2] << 16; - x |= (long)buf[3] << 24; + long x; + x = buf[0]; + x |= (long)buf[1] << 8; + x |= (long)buf[2] << 16; + x |= (long)buf[3] << 24; #if SIZEOF_LONG > 4 - /* Sign extension for 64-bit machines */ - x |= -(x & 0x80000000L); + /* Sign extension for 64-bit machines */ + x |= -(x & 0x80000000L); #endif - return x; + return x; } /* @@ -657,13 +657,13 @@ A toc_entry is a tuple: (__file__, # value to use for __file__, available for all files - compress, # compression kind; 0 for uncompressed - data_size, # size of compressed data on disk - file_size, # size of decompressed data - file_offset, # offset of file header from start of archive - time, # mod time of file (in dos format) - date, # mod data of file (in dos format) - crc, # crc checksum of the data + compress, # compression kind; 0 for uncompressed + data_size, # size of compressed data on disk + file_size, # size of decompressed data + file_offset, # offset of file header from start of archive + time, # mod time of file (in dos format) + date, # mod data of file (in dos format) + crc, # crc checksum of the data ) Directories can be recognized by the trailing SEP in the name, @@ -672,115 +672,115 @@ static PyObject * read_directory(char *archive) { - PyObject *files = NULL; - FILE *fp; - long compress, crc, data_size, file_size, file_offset, date, time; - long header_offset, name_size, header_size, header_position; - long i, l, count; - size_t length; - char path[MAXPATHLEN + 5]; - char name[MAXPATHLEN + 5]; - char *p, endof_central_dir[22]; - long arc_offset; /* offset from beginning of file to start of zip-archive */ - - if (strlen(archive) > MAXPATHLEN) { - PyErr_SetString(PyExc_OverflowError, - "Zip path name is too long"); - return NULL; - } - strcpy(path, archive); - - fp = fopen(archive, "rb"); - if (fp == NULL) { - PyErr_Format(ZipImportError, "can't open Zip file: " - "'%.200s'", archive); - return NULL; - } - fseek(fp, -22, SEEK_END); - header_position = ftell(fp); - if (fread(endof_central_dir, 1, 22, fp) != 22) { - fclose(fp); - PyErr_Format(ZipImportError, "can't read Zip file: " - "'%.200s'", archive); - return NULL; - } - if (get_long((unsigned char *)endof_central_dir) != 0x06054B50) { - /* Bad: End of Central Dir signature */ - fclose(fp); - PyErr_Format(ZipImportError, "not a Zip file: " - "'%.200s'", archive); - return NULL; - } - - header_size = get_long((unsigned char *)endof_central_dir + 12); - header_offset = get_long((unsigned char *)endof_central_dir + 16); - arc_offset = header_position - header_offset - header_size; - header_offset += arc_offset; - - files = PyDict_New(); - if (files == NULL) - goto error; - - length = (long)strlen(path); - path[length] = SEP; - - /* Start of Central Directory */ - count = 0; - for (;;) { - PyObject *t; - int err; - - fseek(fp, header_offset, 0); /* Start of file header */ - l = PyMarshal_ReadLongFromFile(fp); - if (l != 0x02014B50) - break; /* Bad: Central Dir File Header */ - fseek(fp, header_offset + 10, 0); - compress = PyMarshal_ReadShortFromFile(fp); - time = PyMarshal_ReadShortFromFile(fp); - date = PyMarshal_ReadShortFromFile(fp); - crc = PyMarshal_ReadLongFromFile(fp); - data_size = PyMarshal_ReadLongFromFile(fp); - file_size = PyMarshal_ReadLongFromFile(fp); - name_size = PyMarshal_ReadShortFromFile(fp); - header_size = 46 + name_size + - PyMarshal_ReadShortFromFile(fp) + - PyMarshal_ReadShortFromFile(fp); - fseek(fp, header_offset + 42, 0); - file_offset = PyMarshal_ReadLongFromFile(fp) + arc_offset; - if (name_size > MAXPATHLEN) - name_size = MAXPATHLEN; - - p = name; - for (i = 0; i < name_size; i++) { - *p = (char)getc(fp); - if (*p == '/') - *p = SEP; - p++; - } - *p = 0; /* Add terminating null byte */ - header_offset += header_size; - - strncpy(path + length + 1, name, MAXPATHLEN - length - 1); - - t = Py_BuildValue("siiiiiii", path, compress, data_size, - file_size, file_offset, time, date, crc); - if (t == NULL) - goto error; - err = PyDict_SetItemString(files, name, t); - Py_DECREF(t); - if (err != 0) - goto error; - count++; - } - fclose(fp); - if (Py_VerboseFlag) - PySys_WriteStderr("# zipimport: found %ld names in %s\n", - count, archive); - return files; + PyObject *files = NULL; + FILE *fp; + long compress, crc, data_size, file_size, file_offset, date, time; + long header_offset, name_size, header_size, header_position; + long i, l, count; + size_t length; + char path[MAXPATHLEN + 5]; + char name[MAXPATHLEN + 5]; + char *p, endof_central_dir[22]; + long arc_offset; /* offset from beginning of file to start of zip-archive */ + + if (strlen(archive) > MAXPATHLEN) { + PyErr_SetString(PyExc_OverflowError, + "Zip path name is too long"); + return NULL; + } + strcpy(path, archive); + + fp = fopen(archive, "rb"); + if (fp == NULL) { + PyErr_Format(ZipImportError, "can't open Zip file: " + "'%.200s'", archive); + return NULL; + } + fseek(fp, -22, SEEK_END); + header_position = ftell(fp); + if (fread(endof_central_dir, 1, 22, fp) != 22) { + fclose(fp); + PyErr_Format(ZipImportError, "can't read Zip file: " + "'%.200s'", archive); + return NULL; + } + if (get_long((unsigned char *)endof_central_dir) != 0x06054B50) { + /* Bad: End of Central Dir signature */ + fclose(fp); + PyErr_Format(ZipImportError, "not a Zip file: " + "'%.200s'", archive); + return NULL; + } + + header_size = get_long((unsigned char *)endof_central_dir + 12); + header_offset = get_long((unsigned char *)endof_central_dir + 16); + arc_offset = header_position - header_offset - header_size; + header_offset += arc_offset; + + files = PyDict_New(); + if (files == NULL) + goto error; + + length = (long)strlen(path); + path[length] = SEP; + + /* Start of Central Directory */ + count = 0; + for (;;) { + PyObject *t; + int err; + + fseek(fp, header_offset, 0); /* Start of file header */ + l = PyMarshal_ReadLongFromFile(fp); + if (l != 0x02014B50) + break; /* Bad: Central Dir File Header */ + fseek(fp, header_offset + 10, 0); + compress = PyMarshal_ReadShortFromFile(fp); + time = PyMarshal_ReadShortFromFile(fp); + date = PyMarshal_ReadShortFromFile(fp); + crc = PyMarshal_ReadLongFromFile(fp); + data_size = PyMarshal_ReadLongFromFile(fp); + file_size = PyMarshal_ReadLongFromFile(fp); + name_size = PyMarshal_ReadShortFromFile(fp); + header_size = 46 + name_size + + PyMarshal_ReadShortFromFile(fp) + + PyMarshal_ReadShortFromFile(fp); + fseek(fp, header_offset + 42, 0); + file_offset = PyMarshal_ReadLongFromFile(fp) + arc_offset; + if (name_size > MAXPATHLEN) + name_size = MAXPATHLEN; + + p = name; + for (i = 0; i < name_size; i++) { + *p = (char)getc(fp); + if (*p == '/') + *p = SEP; + p++; + } + *p = 0; /* Add terminating null byte */ + header_offset += header_size; + + strncpy(path + length + 1, name, MAXPATHLEN - length - 1); + + t = Py_BuildValue("siiiiiii", path, compress, data_size, + file_size, file_offset, time, date, crc); + if (t == NULL) + goto error; + err = PyDict_SetItemString(files, name, t); + Py_DECREF(t); + if (err != 0) + goto error; + count++; + } + fclose(fp); + if (Py_VerboseFlag) + PySys_WriteStderr("# zipimport: found %ld names in %s\n", + count, archive); + return files; error: - fclose(fp); - Py_XDECREF(files); - return NULL; + fclose(fp); + Py_XDECREF(files); + return NULL; } /* Return the zlib.decompress function object, or NULL if zlib couldn't @@ -790,31 +790,31 @@ static PyObject * get_decompress_func(void) { - static PyObject *decompress = NULL; + static PyObject *decompress = NULL; - if (decompress == NULL) { - PyObject *zlib; - static int importing_zlib = 0; - - if (importing_zlib != 0) - /* Someone has a zlib.py[co] in their Zip file; - let's avoid a stack overflow. */ - return NULL; - importing_zlib = 1; - zlib = PyImport_ImportModuleNoBlock("zlib"); - importing_zlib = 0; - if (zlib != NULL) { - decompress = PyObject_GetAttrString(zlib, - "decompress"); - Py_DECREF(zlib); - } - else - PyErr_Clear(); - if (Py_VerboseFlag) - PySys_WriteStderr("# zipimport: zlib %s\n", - zlib != NULL ? "available": "UNAVAILABLE"); - } - return decompress; + if (decompress == NULL) { + PyObject *zlib; + static int importing_zlib = 0; + + if (importing_zlib != 0) + /* Someone has a zlib.py[co] in their Zip file; + let's avoid a stack overflow. */ + return NULL; + importing_zlib = 1; + zlib = PyImport_ImportModuleNoBlock("zlib"); + importing_zlib = 0; + if (zlib != NULL) { + decompress = PyObject_GetAttrString(zlib, + "decompress"); + Py_DECREF(zlib); + } + else + PyErr_Clear(); + if (Py_VerboseFlag) + PySys_WriteStderr("# zipimport: zlib %s\n", + zlib != NULL ? "available": "UNAVAILABLE"); + } + return decompress; } /* Given a path to a Zip file and a toc_entry, return the (uncompressed) @@ -822,91 +822,91 @@ static PyObject * get_data(char *archive, PyObject *toc_entry) { - PyObject *raw_data, *data = NULL, *decompress; - char *buf; - FILE *fp; - int err; - Py_ssize_t bytes_read = 0; - long l; - char *datapath; - long compress, data_size, file_size, file_offset, bytes_size; - long time, date, crc; - - if (!PyArg_ParseTuple(toc_entry, "slllllll", &datapath, &compress, - &data_size, &file_size, &file_offset, &time, - &date, &crc)) { - return NULL; - } - - fp = fopen(archive, "rb"); - if (!fp) { - PyErr_Format(PyExc_IOError, - "zipimport: can not open file %s", archive); - return NULL; - } - - /* Check to make sure the local file header is correct */ - fseek(fp, file_offset, 0); - l = PyMarshal_ReadLongFromFile(fp); - if (l != 0x04034B50) { - /* Bad: Local File Header */ - PyErr_Format(ZipImportError, - "bad local file header in %s", - archive); - fclose(fp); - return NULL; - } - fseek(fp, file_offset + 26, 0); - l = 30 + PyMarshal_ReadShortFromFile(fp) + - PyMarshal_ReadShortFromFile(fp); /* local header size */ - file_offset += l; /* Start of file data */ - - bytes_size = compress == 0 ? data_size : data_size + 1; - if (bytes_size == 0) - bytes_size++; - raw_data = PyBytes_FromStringAndSize((char *)NULL, bytes_size); - - if (raw_data == NULL) { - fclose(fp); - return NULL; - } - buf = PyBytes_AsString(raw_data); - - err = fseek(fp, file_offset, 0); - if (err == 0) - bytes_read = fread(buf, 1, data_size, fp); - fclose(fp); - if (err || bytes_read != data_size) { - PyErr_SetString(PyExc_IOError, - "zipimport: can't read data"); - Py_DECREF(raw_data); - return NULL; - } - - if (compress != 0) { - buf[data_size] = 'Z'; /* saw this in zipfile.py */ - data_size++; - } - buf[data_size] = '\0'; - - if (compress == 0) { /* data is not compressed */ - data = PyBytes_FromStringAndSize(buf, data_size); - Py_DECREF(raw_data); - return data; - } - - /* Decompress with zlib */ - decompress = get_decompress_func(); - if (decompress == NULL) { - PyErr_SetString(ZipImportError, - "can't decompress data; " - "zlib not available"); - goto error; - } - data = PyObject_CallFunction(decompress, "Oi", raw_data, -15); + PyObject *raw_data, *data = NULL, *decompress; + char *buf; + FILE *fp; + int err; + Py_ssize_t bytes_read = 0; + long l; + char *datapath; + long compress, data_size, file_size, file_offset, bytes_size; + long time, date, crc; + + if (!PyArg_ParseTuple(toc_entry, "slllllll", &datapath, &compress, + &data_size, &file_size, &file_offset, &time, + &date, &crc)) { + return NULL; + } + + fp = fopen(archive, "rb"); + if (!fp) { + PyErr_Format(PyExc_IOError, + "zipimport: can not open file %s", archive); + return NULL; + } + + /* Check to make sure the local file header is correct */ + fseek(fp, file_offset, 0); + l = PyMarshal_ReadLongFromFile(fp); + if (l != 0x04034B50) { + /* Bad: Local File Header */ + PyErr_Format(ZipImportError, + "bad local file header in %s", + archive); + fclose(fp); + return NULL; + } + fseek(fp, file_offset + 26, 0); + l = 30 + PyMarshal_ReadShortFromFile(fp) + + PyMarshal_ReadShortFromFile(fp); /* local header size */ + file_offset += l; /* Start of file data */ + + bytes_size = compress == 0 ? data_size : data_size + 1; + if (bytes_size == 0) + bytes_size++; + raw_data = PyBytes_FromStringAndSize((char *)NULL, bytes_size); + + if (raw_data == NULL) { + fclose(fp); + return NULL; + } + buf = PyBytes_AsString(raw_data); + + err = fseek(fp, file_offset, 0); + if (err == 0) + bytes_read = fread(buf, 1, data_size, fp); + fclose(fp); + if (err || bytes_read != data_size) { + PyErr_SetString(PyExc_IOError, + "zipimport: can't read data"); + Py_DECREF(raw_data); + return NULL; + } + + if (compress != 0) { + buf[data_size] = 'Z'; /* saw this in zipfile.py */ + data_size++; + } + buf[data_size] = '\0'; + + if (compress == 0) { /* data is not compressed */ + data = PyBytes_FromStringAndSize(buf, data_size); + Py_DECREF(raw_data); + return data; + } + + /* Decompress with zlib */ + decompress = get_decompress_func(); + if (decompress == NULL) { + PyErr_SetString(ZipImportError, + "can't decompress data; " + "zlib not available"); + goto error; + } + data = PyObject_CallFunction(decompress, "Oi", raw_data, -15); error: - Py_DECREF(raw_data); - return data; + Py_DECREF(raw_data); + return data; } /* Lenient date/time comparison function. The precision of the mtime @@ -915,11 +915,11 @@ static int eq_mtime(time_t t1, time_t t2) { - time_t d = t1 - t2; - if (d < 0) - d = -d; - /* dostime only stores even seconds, so be lenient */ - return d <= 1; + time_t d = t1 - t2; + if (d < 0) + d = -d; + /* dostime only stores even seconds, so be lenient */ + return d <= 1; } /* Given the contents of a .py[co] file in a buffer, unmarshal the data @@ -930,44 +930,44 @@ static PyObject * unmarshal_code(char *pathname, PyObject *data, time_t mtime) { - PyObject *code; - char *buf = PyBytes_AsString(data); - Py_ssize_t size = PyBytes_Size(data); - - if (size <= 9) { - PyErr_SetString(ZipImportError, - "bad pyc data"); - return NULL; - } - - if (get_long((unsigned char *)buf) != PyImport_GetMagicNumber()) { - if (Py_VerboseFlag) - PySys_WriteStderr("# %s has bad magic\n", - pathname); - Py_INCREF(Py_None); - return Py_None; /* signal caller to try alternative */ - } - - if (mtime != 0 && !eq_mtime(get_long((unsigned char *)buf + 4), - mtime)) { - if (Py_VerboseFlag) - PySys_WriteStderr("# %s has bad mtime\n", - pathname); - Py_INCREF(Py_None); - return Py_None; /* signal caller to try alternative */ - } - - code = PyMarshal_ReadObjectFromString(buf + 8, size - 8); - if (code == NULL) - return NULL; - if (!PyCode_Check(code)) { - Py_DECREF(code); - PyErr_Format(PyExc_TypeError, - "compiled module %.200s is not a code object", - pathname); - return NULL; - } - return code; + PyObject *code; + char *buf = PyBytes_AsString(data); + Py_ssize_t size = PyBytes_Size(data); + + if (size <= 9) { + PyErr_SetString(ZipImportError, + "bad pyc data"); + return NULL; + } + + if (get_long((unsigned char *)buf) != PyImport_GetMagicNumber()) { + if (Py_VerboseFlag) + PySys_WriteStderr("# %s has bad magic\n", + pathname); + Py_INCREF(Py_None); + return Py_None; /* signal caller to try alternative */ + } + + if (mtime != 0 && !eq_mtime(get_long((unsigned char *)buf + 4), + mtime)) { + if (Py_VerboseFlag) + PySys_WriteStderr("# %s has bad mtime\n", + pathname); + Py_INCREF(Py_None); + return Py_None; /* signal caller to try alternative */ + } + + code = PyMarshal_ReadObjectFromString(buf + 8, size - 8); + if (code == NULL) + return NULL; + if (!PyCode_Check(code)) { + Py_DECREF(code); + PyErr_Format(PyExc_TypeError, + "compiled module %.200s is not a code object", + pathname); + return NULL; + } + return code; } /* Replace any occurances of "\r\n?" in the input string with "\n". @@ -977,38 +977,38 @@ static PyObject * normalize_line_endings(PyObject *source) { - char *buf, *q, *p = PyBytes_AsString(source); - PyObject *fixed_source; - int len = 0; - - if (!p) { - return PyBytes_FromStringAndSize("\n\0", 2); - } - - /* one char extra for trailing \n and one for terminating \0 */ - buf = (char *)PyMem_Malloc(PyBytes_Size(source) + 2); - if (buf == NULL) { - PyErr_SetString(PyExc_MemoryError, - "zipimport: no memory to allocate " - "source buffer"); - return NULL; - } - /* replace "\r\n?" by "\n" */ - for (q = buf; *p != '\0'; p++) { - if (*p == '\r') { - *q++ = '\n'; - if (*(p + 1) == '\n') - p++; - } - else - *q++ = *p; - len++; - } - *q++ = '\n'; /* add trailing \n */ - *q = '\0'; - fixed_source = PyBytes_FromStringAndSize(buf, len + 2); - PyMem_Free(buf); - return fixed_source; + char *buf, *q, *p = PyBytes_AsString(source); + PyObject *fixed_source; + int len = 0; + + if (!p) { + return PyBytes_FromStringAndSize("\n\0", 2); + } + + /* one char extra for trailing \n and one for terminating \0 */ + buf = (char *)PyMem_Malloc(PyBytes_Size(source) + 2); + if (buf == NULL) { + PyErr_SetString(PyExc_MemoryError, + "zipimport: no memory to allocate " + "source buffer"); + return NULL; + } + /* replace "\r\n?" by "\n" */ + for (q = buf; *p != '\0'; p++) { + if (*p == '\r') { + *q++ = '\n'; + if (*(p + 1) == '\n') + p++; + } + else + *q++ = *p; + len++; + } + *q++ = '\n'; /* add trailing \n */ + *q = '\0'; + fixed_source = PyBytes_FromStringAndSize(buf, len + 2); + PyMem_Free(buf); + return fixed_source; } /* Given a string buffer containing Python source code, compile it @@ -1016,16 +1016,16 @@ static PyObject * compile_source(char *pathname, PyObject *source) { - PyObject *code, *fixed_source; + PyObject *code, *fixed_source; - fixed_source = normalize_line_endings(source); - if (fixed_source == NULL) - return NULL; - - code = Py_CompileString(PyBytes_AsString(fixed_source), pathname, - Py_file_input); - Py_DECREF(fixed_source); - return code; + fixed_source = normalize_line_endings(source); + if (fixed_source == NULL) + return NULL; + + code = Py_CompileString(PyBytes_AsString(fixed_source), pathname, + Py_file_input); + Py_DECREF(fixed_source); + return code; } /* Convert the date/time values found in the Zip archive to a value @@ -1033,19 +1033,19 @@ static time_t parse_dostime(int dostime, int dosdate) { - struct tm stm; + struct tm stm; - memset((void *) &stm, '\0', sizeof(stm)); + memset((void *) &stm, '\0', sizeof(stm)); - stm.tm_sec = (dostime & 0x1f) * 2; - stm.tm_min = (dostime >> 5) & 0x3f; - stm.tm_hour = (dostime >> 11) & 0x1f; - stm.tm_mday = dosdate & 0x1f; - stm.tm_mon = ((dosdate >> 5) & 0x0f) - 1; - stm.tm_year = ((dosdate >> 9) & 0x7f) + 80; - stm.tm_isdst = -1; /* wday/yday is ignored */ + stm.tm_sec = (dostime & 0x1f) * 2; + stm.tm_min = (dostime >> 5) & 0x3f; + stm.tm_hour = (dostime >> 11) & 0x1f; + stm.tm_mday = dosdate & 0x1f; + stm.tm_mon = ((dosdate >> 5) & 0x0f) - 1; + stm.tm_year = ((dosdate >> 9) & 0x7f) + 80; + stm.tm_isdst = -1; /* wday/yday is ignored */ - return mktime(&stm); + return mktime(&stm); } /* Given a path to a .pyc or .pyo file in the archive, return the @@ -1054,106 +1054,106 @@ static time_t get_mtime_of_source(ZipImporter *self, char *path) { - PyObject *toc_entry; - time_t mtime = 0; - Py_ssize_t lastchar = strlen(path) - 1; - char savechar = path[lastchar]; - path[lastchar] = '\0'; /* strip 'c' or 'o' from *.py[co] */ - toc_entry = PyDict_GetItemString(self->files, path); - if (toc_entry != NULL && PyTuple_Check(toc_entry) && - PyTuple_Size(toc_entry) == 8) { - /* fetch the time stamp of the .py file for comparison - with an embedded pyc time stamp */ - int time, date; - time = PyLong_AsLong(PyTuple_GetItem(toc_entry, 5)); - date = PyLong_AsLong(PyTuple_GetItem(toc_entry, 6)); - mtime = parse_dostime(time, date); - } - path[lastchar] = savechar; - return mtime; + PyObject *toc_entry; + time_t mtime = 0; + Py_ssize_t lastchar = strlen(path) - 1; + char savechar = path[lastchar]; + path[lastchar] = '\0'; /* strip 'c' or 'o' from *.py[co] */ + toc_entry = PyDict_GetItemString(self->files, path); + if (toc_entry != NULL && PyTuple_Check(toc_entry) && + PyTuple_Size(toc_entry) == 8) { + /* fetch the time stamp of the .py file for comparison + with an embedded pyc time stamp */ + int time, date; + time = PyLong_AsLong(PyTuple_GetItem(toc_entry, 5)); + date = PyLong_AsLong(PyTuple_GetItem(toc_entry, 6)); + mtime = parse_dostime(time, date); + } + path[lastchar] = savechar; + return mtime; } /* Return the code object for the module named by 'fullname' from the Zip archive as a new reference. */ static PyObject * get_code_from_data(ZipImporter *self, int ispackage, int isbytecode, - time_t mtime, PyObject *toc_entry) + time_t mtime, PyObject *toc_entry) { - PyObject *data, *code; - char *modpath; - char *archive = _PyUnicode_AsString(self->archive); - - if (archive == NULL) - return NULL; - - data = get_data(archive, toc_entry); - if (data == NULL) - return NULL; - - modpath = _PyUnicode_AsString(PyTuple_GetItem(toc_entry, 0)); - - if (isbytecode) { - code = unmarshal_code(modpath, data, mtime); - } - else { - code = compile_source(modpath, data); - } - Py_DECREF(data); - return code; + PyObject *data, *code; + char *modpath; + char *archive = _PyUnicode_AsString(self->archive); + + if (archive == NULL) + return NULL; + + data = get_data(archive, toc_entry); + if (data == NULL) + return NULL; + + modpath = _PyUnicode_AsString(PyTuple_GetItem(toc_entry, 0)); + + if (isbytecode) { + code = unmarshal_code(modpath, data, mtime); + } + else { + code = compile_source(modpath, data); + } + Py_DECREF(data); + return code; } /* Get the code object assoiciated with the module specified by 'fullname'. */ static PyObject * get_module_code(ZipImporter *self, char *fullname, - int *p_ispackage, char **p_modpath) + int *p_ispackage, char **p_modpath) { - PyObject *toc_entry; - char *subname, path[MAXPATHLEN + 1]; - int len; - struct st_zip_searchorder *zso; - - subname = get_subname(fullname); - - len = make_filename(_PyUnicode_AsString(self->prefix), subname, path); - if (len < 0) - return NULL; - - for (zso = zip_searchorder; *zso->suffix; zso++) { - PyObject *code = NULL; - - strcpy(path + len, zso->suffix); - if (Py_VerboseFlag > 1) - PySys_WriteStderr("# trying %s%c%s\n", - _PyUnicode_AsString(self->archive), - (int)SEP, path); - toc_entry = PyDict_GetItemString(self->files, path); - if (toc_entry != NULL) { - time_t mtime = 0; - int ispackage = zso->type & IS_PACKAGE; - int isbytecode = zso->type & IS_BYTECODE; - - if (isbytecode) - mtime = get_mtime_of_source(self, path); - if (p_ispackage != NULL) - *p_ispackage = ispackage; - code = get_code_from_data(self, ispackage, - isbytecode, mtime, - toc_entry); - if (code == Py_None) { - /* bad magic number or non-matching mtime - in byte code, try next */ - Py_DECREF(code); - continue; - } - if (code != NULL && p_modpath != NULL) - *p_modpath = _PyUnicode_AsString( - PyTuple_GetItem(toc_entry, 0)); - return code; - } - } - PyErr_Format(ZipImportError, "can't find module '%.200s'", fullname); - return NULL; + PyObject *toc_entry; + char *subname, path[MAXPATHLEN + 1]; + int len; + struct st_zip_searchorder *zso; + + subname = get_subname(fullname); + + len = make_filename(_PyUnicode_AsString(self->prefix), subname, path); + if (len < 0) + return NULL; + + for (zso = zip_searchorder; *zso->suffix; zso++) { + PyObject *code = NULL; + + strcpy(path + len, zso->suffix); + if (Py_VerboseFlag > 1) + PySys_WriteStderr("# trying %s%c%s\n", + _PyUnicode_AsString(self->archive), + (int)SEP, path); + toc_entry = PyDict_GetItemString(self->files, path); + if (toc_entry != NULL) { + time_t mtime = 0; + int ispackage = zso->type & IS_PACKAGE; + int isbytecode = zso->type & IS_BYTECODE; + + if (isbytecode) + mtime = get_mtime_of_source(self, path); + if (p_ispackage != NULL) + *p_ispackage = ispackage; + code = get_code_from_data(self, ispackage, + isbytecode, mtime, + toc_entry); + if (code == Py_None) { + /* bad magic number or non-matching mtime + in byte code, try next */ + Py_DECREF(code); + continue; + } + if (code != NULL && p_modpath != NULL) + *p_modpath = _PyUnicode_AsString( + PyTuple_GetItem(toc_entry, 0)); + return code; + } + } + PyErr_Format(ZipImportError, "can't find module '%.200s'", fullname); + return NULL; } @@ -1174,65 +1174,65 @@ to Zip archives."); static struct PyModuleDef zipimportmodule = { - PyModuleDef_HEAD_INIT, - "zipimport", - zipimport_doc, - -1, - NULL, - NULL, - NULL, - NULL, - NULL + PyModuleDef_HEAD_INIT, + "zipimport", + zipimport_doc, + -1, + NULL, + NULL, + NULL, + NULL, + NULL }; PyMODINIT_FUNC PyInit_zipimport(void) { - PyObject *mod; + PyObject *mod; + + if (PyType_Ready(&ZipImporter_Type) < 0) + return NULL; + + /* Correct directory separator */ + zip_searchorder[0].suffix[0] = SEP; + zip_searchorder[1].suffix[0] = SEP; + zip_searchorder[2].suffix[0] = SEP; + if (Py_OptimizeFlag) { + /* Reverse *.pyc and *.pyo */ + struct st_zip_searchorder tmp; + tmp = zip_searchorder[0]; + zip_searchorder[0] = zip_searchorder[1]; + zip_searchorder[1] = tmp; + tmp = zip_searchorder[3]; + zip_searchorder[3] = zip_searchorder[4]; + zip_searchorder[4] = tmp; + } + + mod = PyModule_Create(&zipimportmodule); + if (mod == NULL) + return NULL; - if (PyType_Ready(&ZipImporter_Type) < 0) - return NULL; + ZipImportError = PyErr_NewException("zipimport.ZipImportError", + PyExc_ImportError, NULL); + if (ZipImportError == NULL) + return NULL; - /* Correct directory separator */ - zip_searchorder[0].suffix[0] = SEP; - zip_searchorder[1].suffix[0] = SEP; - zip_searchorder[2].suffix[0] = SEP; - if (Py_OptimizeFlag) { - /* Reverse *.pyc and *.pyo */ - struct st_zip_searchorder tmp; - tmp = zip_searchorder[0]; - zip_searchorder[0] = zip_searchorder[1]; - zip_searchorder[1] = tmp; - tmp = zip_searchorder[3]; - zip_searchorder[3] = zip_searchorder[4]; - zip_searchorder[4] = tmp; - } - - mod = PyModule_Create(&zipimportmodule); - if (mod == NULL) - return NULL; - - ZipImportError = PyErr_NewException("zipimport.ZipImportError", - PyExc_ImportError, NULL); - if (ZipImportError == NULL) - return NULL; - - Py_INCREF(ZipImportError); - if (PyModule_AddObject(mod, "ZipImportError", - ZipImportError) < 0) - return NULL; - - Py_INCREF(&ZipImporter_Type); - if (PyModule_AddObject(mod, "zipimporter", - (PyObject *)&ZipImporter_Type) < 0) - return NULL; - - zip_directory_cache = PyDict_New(); - if (zip_directory_cache == NULL) - return NULL; - Py_INCREF(zip_directory_cache); - if (PyModule_AddObject(mod, "_zip_directory_cache", - zip_directory_cache) < 0) - return NULL; - return mod; + Py_INCREF(ZipImportError); + if (PyModule_AddObject(mod, "ZipImportError", + ZipImportError) < 0) + return NULL; + + Py_INCREF(&ZipImporter_Type); + if (PyModule_AddObject(mod, "zipimporter", + (PyObject *)&ZipImporter_Type) < 0) + return NULL; + + zip_directory_cache = PyDict_New(); + if (zip_directory_cache == NULL) + return NULL; + Py_INCREF(zip_directory_cache); + if (PyModule_AddObject(mod, "_zip_directory_cache", + zip_directory_cache) < 0) + return NULL; + return mod; } Modified: python/branches/py3k/Modules/zlibmodule.c ============================================================================== --- python/branches/py3k/Modules/zlibmodule.c (original) +++ python/branches/py3k/Modules/zlibmodule.c Sun May 9 17:52:27 2010 @@ -53,9 +53,9 @@ zlib_error(z_stream zst, int err, char *msg) { if (zst.msg == Z_NULL) - PyErr_Format(ZlibError, "Error %d %s", err, msg); + PyErr_Format(ZlibError, "Error %d %s", err, msg); else - PyErr_Format(ZlibError, "Error %d %s: %.200s", err, msg, zst.msg); + PyErr_Format(ZlibError, "Error %d %s: %.200s", err, msg, zst.msg); } PyDoc_STRVAR(compressobj__doc__, @@ -74,17 +74,17 @@ compobject *self; self = PyObject_New(compobject, type); if (self == NULL) - return NULL; + return NULL; self->is_initialised = 0; self->unused_data = PyBytes_FromStringAndSize("", 0); if (self->unused_data == NULL) { - Py_DECREF(self); - return NULL; + Py_DECREF(self); + return NULL; } self->unconsumed_tail = PyBytes_FromStringAndSize("", 0); if (self->unconsumed_tail == NULL) { - Py_DECREF(self); - return NULL; + Py_DECREF(self); + return NULL; } #ifdef WITH_THREAD self->lock = PyThread_allocate_lock(); @@ -108,7 +108,7 @@ /* require Python string object, optional 'level' arg */ if (!PyArg_ParseTuple(args, "y*|i:compress", &pinput, &level)) - return NULL; + return NULL; input = pinput.buf; length = pinput.len; @@ -116,10 +116,10 @@ output = (Byte*)malloc(zst.avail_out); if (output == NULL) { - PyBuffer_Release(&pinput); - PyErr_SetString(PyExc_MemoryError, - "Can't allocate memory to compress data"); - return NULL; + PyBuffer_Release(&pinput); + PyErr_SetString(PyExc_MemoryError, + "Can't allocate memory to compress data"); + return NULL; } /* Past the point of no return. From here on out, we need to make sure @@ -134,19 +134,19 @@ switch(err) { case(Z_OK): - break; + break; case(Z_MEM_ERROR): - PyErr_SetString(PyExc_MemoryError, - "Out of memory while compressing data"); - goto error; + PyErr_SetString(PyExc_MemoryError, + "Out of memory while compressing data"); + goto error; case(Z_STREAM_ERROR): - PyErr_SetString(ZlibError, - "Bad compression level"); - goto error; + PyErr_SetString(ZlibError, + "Bad compression level"); + goto error; default: deflateEnd(&zst); - zlib_error(zst, err, "while compressing data"); - goto error; + zlib_error(zst, err, "while compressing data"); + goto error; } Py_BEGIN_ALLOW_THREADS; @@ -154,17 +154,17 @@ Py_END_ALLOW_THREADS; if (err != Z_STREAM_END) { - zlib_error(zst, err, "while compressing data"); - deflateEnd(&zst); - goto error; + zlib_error(zst, err, "while compressing data"); + deflateEnd(&zst); + goto error; } err=deflateEnd(&zst); if (err == Z_OK) - ReturnVal = PyBytes_FromStringAndSize((char *)output, + ReturnVal = PyBytes_FromStringAndSize((char *)output, zst.total_out); else - zlib_error(zst, err, "while finishing compression"); + zlib_error(zst, err, "while finishing compression"); error: PyBuffer_Release(&pinput); @@ -191,20 +191,20 @@ z_stream zst; if (!PyArg_ParseTuple(args, "y*|in:decompress", - &pinput, &wsize, &r_strlen)) - return NULL; + &pinput, &wsize, &r_strlen)) + return NULL; input = pinput.buf; length = pinput.len; if (r_strlen <= 0) - r_strlen = 1; + r_strlen = 1; zst.avail_in = length; zst.avail_out = r_strlen; if (!(result_str = PyBytes_FromStringAndSize(NULL, r_strlen))) { - PyBuffer_Release(&pinput); - return NULL; + PyBuffer_Release(&pinput); + return NULL; } zst.zalloc = (alloc_func)NULL; @@ -215,60 +215,60 @@ switch(err) { case(Z_OK): - break; + break; case(Z_MEM_ERROR): - PyErr_SetString(PyExc_MemoryError, - "Out of memory while decompressing data"); - goto error; + PyErr_SetString(PyExc_MemoryError, + "Out of memory while decompressing data"); + goto error; default: inflateEnd(&zst); - zlib_error(zst, err, "while preparing to decompress data"); - goto error; + zlib_error(zst, err, "while preparing to decompress data"); + goto error; } do { - Py_BEGIN_ALLOW_THREADS - err=inflate(&zst, Z_FINISH); - Py_END_ALLOW_THREADS - - switch(err) { - case(Z_STREAM_END): - break; - case(Z_BUF_ERROR): - /* - * If there is at least 1 byte of room according to zst.avail_out - * and we get this error, assume that it means zlib cannot - * process the inflate call() due to an error in the data. - */ - if (zst.avail_out > 0) { - PyErr_Format(ZlibError, "Error %i while decompressing data", - err); - inflateEnd(&zst); - goto error; - } - /* fall through */ - case(Z_OK): - /* need more memory */ - if (_PyBytes_Resize(&result_str, r_strlen << 1) < 0) { - inflateEnd(&zst); - goto error; - } - zst.next_out = + Py_BEGIN_ALLOW_THREADS + err=inflate(&zst, Z_FINISH); + Py_END_ALLOW_THREADS + + switch(err) { + case(Z_STREAM_END): + break; + case(Z_BUF_ERROR): + /* + * If there is at least 1 byte of room according to zst.avail_out + * and we get this error, assume that it means zlib cannot + * process the inflate call() due to an error in the data. + */ + if (zst.avail_out > 0) { + PyErr_Format(ZlibError, "Error %i while decompressing data", + err); + inflateEnd(&zst); + goto error; + } + /* fall through */ + case(Z_OK): + /* need more memory */ + if (_PyBytes_Resize(&result_str, r_strlen << 1) < 0) { + inflateEnd(&zst); + goto error; + } + zst.next_out = (unsigned char *)PyBytes_AS_STRING(result_str) + r_strlen; - zst.avail_out = r_strlen; - r_strlen = r_strlen << 1; - break; - default: - inflateEnd(&zst); - zlib_error(zst, err, "while decompressing data"); - goto error; - } + zst.avail_out = r_strlen; + r_strlen = r_strlen << 1; + break; + default: + inflateEnd(&zst); + zlib_error(zst, err, "while decompressing data"); + goto error; + } } while (err != Z_STREAM_END); err = inflateEnd(&zst); if (err != Z_OK) { - zlib_error(zst, err, "while finishing data decompression"); - goto error; + zlib_error(zst, err, "while finishing data decompression"); + goto error; } if (_PyBytes_Resize(&result_str, zst.total_out) < 0) @@ -291,12 +291,12 @@ int wbits=MAX_WBITS, memLevel=DEF_MEM_LEVEL, strategy=0, err; if (!PyArg_ParseTuple(args, "|iiiii:compressobj", &level, &method, &wbits, - &memLevel, &strategy)) - return NULL; + &memLevel, &strategy)) + return NULL; self = newcompobject(&Comptype); if (self==NULL) - return(NULL); + return(NULL); self->zst.zalloc = (alloc_func)NULL; self->zst.zfree = (free_func)Z_NULL; self->zst.next_in = NULL; @@ -304,21 +304,21 @@ err = deflateInit2(&self->zst, level, method, wbits, memLevel, strategy); switch(err) { case (Z_OK): - self->is_initialised = 1; - return (PyObject*)self; + self->is_initialised = 1; + return (PyObject*)self; case (Z_MEM_ERROR): - Py_DECREF(self); - PyErr_SetString(PyExc_MemoryError, - "Can't allocate memory for compression object"); - return NULL; + Py_DECREF(self); + PyErr_SetString(PyExc_MemoryError, + "Can't allocate memory for compression object"); + return NULL; case(Z_STREAM_ERROR): - Py_DECREF(self); - PyErr_SetString(PyExc_ValueError, "Invalid initialization option"); - return NULL; + Py_DECREF(self); + PyErr_SetString(PyExc_ValueError, "Invalid initialization option"); + return NULL; default: - zlib_error(self->zst, err, "while creating compression object"); + zlib_error(self->zst, err, "while creating compression object"); Py_DECREF(self); - return NULL; + return NULL; } } @@ -328,11 +328,11 @@ int wbits=DEF_WBITS, err; compobject *self; if (!PyArg_ParseTuple(args, "|i:decompressobj", &wbits)) - return NULL; + return NULL; self = newcompobject(&Decomptype); if (self == NULL) - return(NULL); + return(NULL); self->zst.zalloc = (alloc_func)NULL; self->zst.zfree = (free_func)Z_NULL; self->zst.next_in = NULL; @@ -340,21 +340,21 @@ err = inflateInit2(&self->zst, wbits); switch(err) { case (Z_OK): - self->is_initialised = 1; - return (PyObject*)self; + self->is_initialised = 1; + return (PyObject*)self; case(Z_STREAM_ERROR): - Py_DECREF(self); - PyErr_SetString(PyExc_ValueError, "Invalid initialization option"); - return NULL; + Py_DECREF(self); + PyErr_SetString(PyExc_ValueError, "Invalid initialization option"); + return NULL; case (Z_MEM_ERROR): - Py_DECREF(self); - PyErr_SetString(PyExc_MemoryError, - "Can't allocate memory for decompression object"); - return NULL; + Py_DECREF(self); + PyErr_SetString(PyExc_MemoryError, + "Can't allocate memory for decompression object"); + return NULL; default: - zlib_error(self->zst, err, "while creating decompression object"); + zlib_error(self->zst, err, "while creating decompression object"); Py_DECREF(self); - return NULL; + return NULL; } } @@ -404,13 +404,13 @@ unsigned long start_total_out; if (!PyArg_ParseTuple(args, "y*:compress", &pinput)) - return NULL; + return NULL; input = pinput.buf; inplen = pinput.len; if (!(RetVal = PyBytes_FromStringAndSize(NULL, length))) { - PyBuffer_Release(&pinput); - return NULL; + PyBuffer_Release(&pinput); + return NULL; } ENTER_ZLIB(self); @@ -428,19 +428,19 @@ /* while Z_OK and the output buffer is full, there might be more output, so extend the output buffer and try again */ while (err == Z_OK && self->zst.avail_out == 0) { - if (_PyBytes_Resize(&RetVal, length << 1) < 0) { + if (_PyBytes_Resize(&RetVal, length << 1) < 0) { Py_DECREF(RetVal); RetVal = NULL; - goto error; + goto error; } - self->zst.next_out = + self->zst.next_out = (unsigned char *)PyBytes_AS_STRING(RetVal) + length; - self->zst.avail_out = length; - length = length << 1; + self->zst.avail_out = length; + length = length << 1; - Py_BEGIN_ALLOW_THREADS - err = deflate(&(self->zst), Z_NO_FLUSH); - Py_END_ALLOW_THREADS + Py_BEGIN_ALLOW_THREADS + err = deflate(&(self->zst), Z_NO_FLUSH); + Py_END_ALLOW_THREADS } /* We will only get Z_BUF_ERROR if the output buffer was full but there wasn't more output when we tried again, so it is not an error @@ -448,10 +448,10 @@ */ if (err != Z_OK && err != Z_BUF_ERROR) { - zlib_error(self->zst, err, "while compressing"); - Py_DECREF(RetVal); - RetVal = NULL; - goto error; + zlib_error(self->zst, err, "while compressing"); + Py_DECREF(RetVal); + RetVal = NULL; + goto error; } if (_PyBytes_Resize(&RetVal, self->zst.total_out - start_total_out) < 0) { Py_DECREF(RetVal); @@ -486,23 +486,23 @@ unsigned long start_total_out; if (!PyArg_ParseTuple(args, "y*|i:decompress", &pinput, - &max_length)) - return NULL; + &max_length)) + return NULL; input = pinput.buf; inplen = pinput.len; if (max_length < 0) { - PyBuffer_Release(&pinput); - PyErr_SetString(PyExc_ValueError, - "max_length must be greater than zero"); - return NULL; + PyBuffer_Release(&pinput); + PyErr_SetString(PyExc_ValueError, + "max_length must be greater than zero"); + return NULL; } /* limit amount of data allocated to max_length */ if (max_length && length > max_length) - length = max_length; + length = max_length; if (!(RetVal = PyBytes_FromStringAndSize(NULL, length))) { - PyBuffer_Release(&pinput); - return NULL; + PyBuffer_Release(&pinput); + return NULL; } ENTER_ZLIB(self); @@ -521,43 +521,43 @@ So extend the output buffer and try again. */ while (err == Z_OK && self->zst.avail_out == 0) { - /* If max_length set, don't continue decompressing if we've already - reached the limit. - */ - if (max_length && length >= max_length) - break; - - /* otherwise, ... */ - old_length = length; - length = length << 1; - if (max_length && length > max_length) - length = max_length; + /* If max_length set, don't continue decompressing if we've already + reached the limit. + */ + if (max_length && length >= max_length) + break; + + /* otherwise, ... */ + old_length = length; + length = length << 1; + if (max_length && length > max_length) + length = max_length; - if (_PyBytes_Resize(&RetVal, length) < 0) { + if (_PyBytes_Resize(&RetVal, length) < 0) { Py_DECREF(RetVal); RetVal = NULL; - goto error; + goto error; } - self->zst.next_out = + self->zst.next_out = (unsigned char *)PyBytes_AS_STRING(RetVal) + old_length; - self->zst.avail_out = length - old_length; + self->zst.avail_out = length - old_length; - Py_BEGIN_ALLOW_THREADS - err = inflate(&(self->zst), Z_SYNC_FLUSH); - Py_END_ALLOW_THREADS + Py_BEGIN_ALLOW_THREADS + err = inflate(&(self->zst), Z_SYNC_FLUSH); + Py_END_ALLOW_THREADS } /* Not all of the compressed data could be accommodated in the output buffer of specified size. Return the unconsumed tail in an attribute.*/ if(max_length) { - Py_DECREF(self->unconsumed_tail); - self->unconsumed_tail = PyBytes_FromStringAndSize((char *)self->zst.next_in, - self->zst.avail_in); - if(!self->unconsumed_tail) { - Py_DECREF(RetVal); - RetVal = NULL; - goto error; - } + Py_DECREF(self->unconsumed_tail); + self->unconsumed_tail = PyBytes_FromStringAndSize((char *)self->zst.next_in, + self->zst.avail_in); + if(!self->unconsumed_tail) { + Py_DECREF(RetVal); + RetVal = NULL; + goto error; + } } /* The end of the compressed data has been reached, so set the @@ -567,22 +567,22 @@ preserved. */ if (err == Z_STREAM_END) { - Py_XDECREF(self->unused_data); /* Free original empty string */ - self->unused_data = PyBytes_FromStringAndSize( - (char *)self->zst.next_in, self->zst.avail_in); - if (self->unused_data == NULL) { - Py_DECREF(RetVal); - goto error; - } - /* We will only get Z_BUF_ERROR if the output buffer was full - but there wasn't more output when we tried again, so it is - not an error condition. - */ + Py_XDECREF(self->unused_data); /* Free original empty string */ + self->unused_data = PyBytes_FromStringAndSize( + (char *)self->zst.next_in, self->zst.avail_in); + if (self->unused_data == NULL) { + Py_DECREF(RetVal); + goto error; + } + /* We will only get Z_BUF_ERROR if the output buffer was full + but there wasn't more output when we tried again, so it is + not an error condition. + */ } else if (err != Z_OK && err != Z_BUF_ERROR) { - zlib_error(self->zst, err, "while decompressing"); - Py_DECREF(RetVal); - RetVal = NULL; - goto error; + zlib_error(self->zst, err, "while decompressing"); + Py_DECREF(RetVal); + RetVal = NULL; + goto error; } if (_PyBytes_Resize(&RetVal, self->zst.total_out - start_total_out) < 0) { @@ -613,16 +613,16 @@ unsigned long start_total_out; if (!PyArg_ParseTuple(args, "|i:flush", &flushmode)) - return NULL; + return NULL; /* Flushing with Z_NO_FLUSH is a no-op, so there's no point in doing any work at all; just return an empty string. */ if (flushmode == Z_NO_FLUSH) { - return PyBytes_FromStringAndSize(NULL, 0); + return PyBytes_FromStringAndSize(NULL, 0); } if (!(RetVal = PyBytes_FromStringAndSize(NULL, length))) - return NULL; + return NULL; ENTER_ZLIB(self); @@ -638,44 +638,44 @@ /* while Z_OK and the output buffer is full, there might be more output, so extend the output buffer and try again */ while (err == Z_OK && self->zst.avail_out == 0) { - if (_PyBytes_Resize(&RetVal, length << 1) < 0) { + if (_PyBytes_Resize(&RetVal, length << 1) < 0) { Py_DECREF(RetVal); RetVal = NULL; - goto error; + goto error; } - self->zst.next_out = + self->zst.next_out = (unsigned char *)PyBytes_AS_STRING(RetVal) + length; - self->zst.avail_out = length; - length = length << 1; + self->zst.avail_out = length; + length = length << 1; - Py_BEGIN_ALLOW_THREADS - err = deflate(&(self->zst), flushmode); - Py_END_ALLOW_THREADS + Py_BEGIN_ALLOW_THREADS + err = deflate(&(self->zst), flushmode); + Py_END_ALLOW_THREADS } /* If flushmode is Z_FINISH, we also have to call deflateEnd() to free various data structures. Note we should only get Z_STREAM_END when flushmode is Z_FINISH, but checking both for safety*/ if (err == Z_STREAM_END && flushmode == Z_FINISH) { - err = deflateEnd(&(self->zst)); - if (err != Z_OK) { - zlib_error(self->zst, err, "from deflateEnd()"); - Py_DECREF(RetVal); - RetVal = NULL; - goto error; - } - else - self->is_initialised = 0; - - /* We will only get Z_BUF_ERROR if the output buffer was full - but there wasn't more output when we tried again, so it is - not an error condition. - */ + err = deflateEnd(&(self->zst)); + if (err != Z_OK) { + zlib_error(self->zst, err, "from deflateEnd()"); + Py_DECREF(RetVal); + RetVal = NULL; + goto error; + } + else + self->is_initialised = 0; + + /* We will only get Z_BUF_ERROR if the output buffer was full + but there wasn't more output when we tried again, so it is + not an error condition. + */ } else if (err!=Z_OK && err!=Z_BUF_ERROR) { - zlib_error(self->zst, err, "while flushing"); - Py_DECREF(RetVal); - RetVal = NULL; - goto error; + zlib_error(self->zst, err, "while flushing"); + Py_DECREF(RetVal); + RetVal = NULL; + goto error; } if (_PyBytes_Resize(&RetVal, self->zst.total_out - start_total_out) < 0) { @@ -807,13 +807,13 @@ unsigned long start_total_out; if (!PyArg_ParseTuple(args, "|i:flush", &length)) - return NULL; + return NULL; if (length <= 0) { - PyErr_SetString(PyExc_ValueError, "length must be greater than zero"); - return NULL; + PyErr_SetString(PyExc_ValueError, "length must be greater than zero"); + return NULL; } if (!(retval = PyBytes_FromStringAndSize(NULL, length))) - return NULL; + return NULL; ENTER_ZLIB(self); @@ -829,32 +829,32 @@ /* while Z_OK and the output buffer is full, there might be more output, so extend the output buffer and try again */ while ((err == Z_OK || err == Z_BUF_ERROR) && self->zst.avail_out == 0) { - if (_PyBytes_Resize(&retval, length << 1) < 0) { + if (_PyBytes_Resize(&retval, length << 1) < 0) { Py_DECREF(retval); retval = NULL; - goto error; + goto error; } - self->zst.next_out = (Byte *)PyBytes_AS_STRING(retval) + length; - self->zst.avail_out = length; - length = length << 1; - - Py_BEGIN_ALLOW_THREADS - err = inflate(&(self->zst), Z_FINISH); - Py_END_ALLOW_THREADS + self->zst.next_out = (Byte *)PyBytes_AS_STRING(retval) + length; + self->zst.avail_out = length; + length = length << 1; + + Py_BEGIN_ALLOW_THREADS + err = inflate(&(self->zst), Z_FINISH); + Py_END_ALLOW_THREADS } /* If flushmode is Z_FINISH, we also have to call deflateEnd() to free various data structures. Note we should only get Z_STREAM_END when flushmode is Z_FINISH */ if (err == Z_STREAM_END) { - err = inflateEnd(&(self->zst)); + err = inflateEnd(&(self->zst)); self->is_initialised = 0; - if (err != Z_OK) { - zlib_error(self->zst, err, "from inflateEnd()"); - Py_DECREF(retval); - retval = NULL; - goto error; - } + if (err != Z_OK) { + zlib_error(self->zst, err, "from inflateEnd()"); + Py_DECREF(retval); + retval = NULL; + goto error; + } } if (_PyBytes_Resize(&retval, self->zst.total_out - start_total_out) < 0) { Py_DECREF(retval); @@ -942,7 +942,7 @@ int signed_val; if (!PyArg_ParseTuple(args, "y*|I:crc32", &pbuf, &crc32val)) - return NULL; + return NULL; /* Releasing the GIL for very small buffers is inefficient and may lower performance */ if (pbuf.len > 1024*5) { @@ -950,7 +950,7 @@ signed_val = crc32(crc32val, pbuf.buf, pbuf.len); Py_END_ALLOW_THREADS } else { - signed_val = crc32(crc32val, pbuf.buf, pbuf.len); + signed_val = crc32(crc32val, pbuf.buf, pbuf.len); } PyBuffer_Release(&pbuf); return PyLong_FromUnsignedLong(signed_val & 0xffffffffU); @@ -1053,15 +1053,15 @@ "objects support decompress() and flush()."); static struct PyModuleDef zlibmodule = { - PyModuleDef_HEAD_INIT, - "zlib", - zlib_module_documentation, - -1, - zlib_methods, - NULL, - NULL, - NULL, - NULL + PyModuleDef_HEAD_INIT, + "zlib", + zlib_module_documentation, + -1, + zlib_methods, + NULL, + NULL, + NULL, + NULL }; PyMODINIT_FUNC @@ -1069,17 +1069,17 @@ { PyObject *m, *ver; if (PyType_Ready(&Comptype) < 0) - return NULL; + return NULL; if (PyType_Ready(&Decomptype) < 0) - return NULL; + return NULL; m = PyModule_Create(&zlibmodule); if (m == NULL) - return NULL; + return NULL; ZlibError = PyErr_NewException("zlib.error", NULL, NULL); if (ZlibError != NULL) { Py_INCREF(ZlibError); - PyModule_AddObject(m, "error", ZlibError); + PyModule_AddObject(m, "error", ZlibError); } PyModule_AddIntConstant(m, "MAX_WBITS", MAX_WBITS); PyModule_AddIntConstant(m, "DEFLATED", DEFLATED); @@ -1098,7 +1098,7 @@ ver = PyUnicode_FromString(ZLIB_VERSION); if (ver != NULL) - PyModule_AddObject(m, "ZLIB_VERSION", ver); + PyModule_AddObject(m, "ZLIB_VERSION", ver); PyModule_AddStringConstant(m, "__version__", "1.0"); Modified: python/branches/py3k/Objects/abstract.c ============================================================================== --- python/branches/py3k/Objects/abstract.c (original) +++ python/branches/py3k/Objects/abstract.c Sun May 9 17:52:27 2010 @@ -12,17 +12,17 @@ static PyObject * type_error(const char *msg, PyObject *obj) { - PyErr_Format(PyExc_TypeError, msg, obj->ob_type->tp_name); - return NULL; + PyErr_Format(PyExc_TypeError, msg, obj->ob_type->tp_name); + return NULL; } static PyObject * null_error(void) { - if (!PyErr_Occurred()) - PyErr_SetString(PyExc_SystemError, - "null argument to internal routine"); - return NULL; + if (!PyErr_Occurred()) + PyErr_SetString(PyExc_SystemError, + "null argument to internal routine"); + return NULL; } /* Operations on any object */ @@ -30,37 +30,37 @@ PyObject * PyObject_Type(PyObject *o) { - PyObject *v; + PyObject *v; - if (o == NULL) - return null_error(); - v = (PyObject *)o->ob_type; - Py_INCREF(v); - return v; + if (o == NULL) + return null_error(); + v = (PyObject *)o->ob_type; + Py_INCREF(v); + return v; } Py_ssize_t PyObject_Size(PyObject *o) { - PySequenceMethods *m; + PySequenceMethods *m; - if (o == NULL) { - null_error(); - return -1; - } - - m = o->ob_type->tp_as_sequence; - if (m && m->sq_length) - return m->sq_length(o); + if (o == NULL) { + null_error(); + return -1; + } + + m = o->ob_type->tp_as_sequence; + if (m && m->sq_length) + return m->sq_length(o); - return PyMapping_Size(o); + return PyMapping_Size(o); } #undef PyObject_Length Py_ssize_t PyObject_Length(PyObject *o) { - return PyObject_Size(o); + return PyObject_Size(o); } #define PyObject_Length PyObject_Size @@ -74,149 +74,149 @@ Py_ssize_t _PyObject_LengthHint(PyObject *o, Py_ssize_t defaultvalue) { - static PyObject *hintstrobj = NULL; - PyObject *ro, *hintmeth; - Py_ssize_t rv; - - /* try o.__len__() */ - rv = PyObject_Size(o); - if (rv >= 0) - return rv; - if (PyErr_Occurred()) { - if (!PyErr_ExceptionMatches(PyExc_TypeError)) - return -1; - PyErr_Clear(); - } - - /* try o.__length_hint__() */ - hintmeth = _PyObject_LookupSpecial(o, "__length_hint__", &hintstrobj); - if (hintmeth == NULL) { - if (PyErr_Occurred()) - return -1; - else - return defaultvalue; - } - ro = PyObject_CallFunctionObjArgs(hintmeth, NULL); - Py_DECREF(hintmeth); - if (ro == NULL) { - if (!PyErr_ExceptionMatches(PyExc_TypeError)) - return -1; - PyErr_Clear(); - return defaultvalue; - } - rv = PyLong_Check(ro) ? PyLong_AsSsize_t(ro) : defaultvalue; - Py_DECREF(ro); - return rv; + static PyObject *hintstrobj = NULL; + PyObject *ro, *hintmeth; + Py_ssize_t rv; + + /* try o.__len__() */ + rv = PyObject_Size(o); + if (rv >= 0) + return rv; + if (PyErr_Occurred()) { + if (!PyErr_ExceptionMatches(PyExc_TypeError)) + return -1; + PyErr_Clear(); + } + + /* try o.__length_hint__() */ + hintmeth = _PyObject_LookupSpecial(o, "__length_hint__", &hintstrobj); + if (hintmeth == NULL) { + if (PyErr_Occurred()) + return -1; + else + return defaultvalue; + } + ro = PyObject_CallFunctionObjArgs(hintmeth, NULL); + Py_DECREF(hintmeth); + if (ro == NULL) { + if (!PyErr_ExceptionMatches(PyExc_TypeError)) + return -1; + PyErr_Clear(); + return defaultvalue; + } + rv = PyLong_Check(ro) ? PyLong_AsSsize_t(ro) : defaultvalue; + Py_DECREF(ro); + return rv; } PyObject * PyObject_GetItem(PyObject *o, PyObject *key) { - PyMappingMethods *m; + PyMappingMethods *m; - if (o == NULL || key == NULL) - return null_error(); + if (o == NULL || key == NULL) + return null_error(); - m = o->ob_type->tp_as_mapping; - if (m && m->mp_subscript) - return m->mp_subscript(o, key); - - if (o->ob_type->tp_as_sequence) { - if (PyIndex_Check(key)) { - Py_ssize_t key_value; - key_value = PyNumber_AsSsize_t(key, PyExc_IndexError); - if (key_value == -1 && PyErr_Occurred()) - return NULL; - return PySequence_GetItem(o, key_value); - } - else if (o->ob_type->tp_as_sequence->sq_item) - return type_error("sequence index must " - "be integer, not '%.200s'", key); - } + m = o->ob_type->tp_as_mapping; + if (m && m->mp_subscript) + return m->mp_subscript(o, key); + + if (o->ob_type->tp_as_sequence) { + if (PyIndex_Check(key)) { + Py_ssize_t key_value; + key_value = PyNumber_AsSsize_t(key, PyExc_IndexError); + if (key_value == -1 && PyErr_Occurred()) + return NULL; + return PySequence_GetItem(o, key_value); + } + else if (o->ob_type->tp_as_sequence->sq_item) + return type_error("sequence index must " + "be integer, not '%.200s'", key); + } - return type_error("'%.200s' object is not subscriptable", o); + return type_error("'%.200s' object is not subscriptable", o); } int PyObject_SetItem(PyObject *o, PyObject *key, PyObject *value) { - PyMappingMethods *m; + PyMappingMethods *m; - if (o == NULL || key == NULL || value == NULL) { - null_error(); - return -1; - } - m = o->ob_type->tp_as_mapping; - if (m && m->mp_ass_subscript) - return m->mp_ass_subscript(o, key, value); - - if (o->ob_type->tp_as_sequence) { - if (PyIndex_Check(key)) { - Py_ssize_t key_value; - key_value = PyNumber_AsSsize_t(key, PyExc_IndexError); - if (key_value == -1 && PyErr_Occurred()) - return -1; - return PySequence_SetItem(o, key_value, value); - } - else if (o->ob_type->tp_as_sequence->sq_ass_item) { - type_error("sequence index must be " - "integer, not '%.200s'", key); - return -1; - } - } + if (o == NULL || key == NULL || value == NULL) { + null_error(); + return -1; + } + m = o->ob_type->tp_as_mapping; + if (m && m->mp_ass_subscript) + return m->mp_ass_subscript(o, key, value); + + if (o->ob_type->tp_as_sequence) { + if (PyIndex_Check(key)) { + Py_ssize_t key_value; + key_value = PyNumber_AsSsize_t(key, PyExc_IndexError); + if (key_value == -1 && PyErr_Occurred()) + return -1; + return PySequence_SetItem(o, key_value, value); + } + else if (o->ob_type->tp_as_sequence->sq_ass_item) { + type_error("sequence index must be " + "integer, not '%.200s'", key); + return -1; + } + } - type_error("'%.200s' object does not support item assignment", o); - return -1; + type_error("'%.200s' object does not support item assignment", o); + return -1; } int PyObject_DelItem(PyObject *o, PyObject *key) { - PyMappingMethods *m; + PyMappingMethods *m; - if (o == NULL || key == NULL) { - null_error(); - return -1; - } - m = o->ob_type->tp_as_mapping; - if (m && m->mp_ass_subscript) - return m->mp_ass_subscript(o, key, (PyObject*)NULL); - - if (o->ob_type->tp_as_sequence) { - if (PyIndex_Check(key)) { - Py_ssize_t key_value; - key_value = PyNumber_AsSsize_t(key, PyExc_IndexError); - if (key_value == -1 && PyErr_Occurred()) - return -1; - return PySequence_DelItem(o, key_value); - } - else if (o->ob_type->tp_as_sequence->sq_ass_item) { - type_error("sequence index must be " - "integer, not '%.200s'", key); - return -1; - } - } + if (o == NULL || key == NULL) { + null_error(); + return -1; + } + m = o->ob_type->tp_as_mapping; + if (m && m->mp_ass_subscript) + return m->mp_ass_subscript(o, key, (PyObject*)NULL); + + if (o->ob_type->tp_as_sequence) { + if (PyIndex_Check(key)) { + Py_ssize_t key_value; + key_value = PyNumber_AsSsize_t(key, PyExc_IndexError); + if (key_value == -1 && PyErr_Occurred()) + return -1; + return PySequence_DelItem(o, key_value); + } + else if (o->ob_type->tp_as_sequence->sq_ass_item) { + type_error("sequence index must be " + "integer, not '%.200s'", key); + return -1; + } + } - type_error("'%.200s' object does not support item deletion", o); - return -1; + type_error("'%.200s' object does not support item deletion", o); + return -1; } int PyObject_DelItemString(PyObject *o, char *key) { - PyObject *okey; - int ret; + PyObject *okey; + int ret; - if (o == NULL || key == NULL) { - null_error(); - return -1; - } - okey = PyUnicode_FromString(key); - if (okey == NULL) - return -1; - ret = PyObject_DelItem(o, okey); - Py_DECREF(okey); - return ret; + if (o == NULL || key == NULL) { + null_error(); + return -1; + } + okey = PyUnicode_FromString(key); + if (okey == NULL) + return -1; + ret = PyObject_DelItem(o, okey); + Py_DECREF(okey); + return ret; } /* We release the buffer right after use of this function which could @@ -224,104 +224,104 @@ */ int PyObject_AsCharBuffer(PyObject *obj, - const char **buffer, - Py_ssize_t *buffer_len) + const char **buffer, + Py_ssize_t *buffer_len) { - PyBufferProcs *pb; - Py_buffer view; + PyBufferProcs *pb; + Py_buffer view; - if (obj == NULL || buffer == NULL || buffer_len == NULL) { - null_error(); - return -1; - } - pb = obj->ob_type->tp_as_buffer; - if (pb == NULL || pb->bf_getbuffer == NULL) { - PyErr_SetString(PyExc_TypeError, - "expected an object with the buffer interface"); - return -1; - } - if ((*pb->bf_getbuffer)(obj, &view, PyBUF_SIMPLE)) return -1; - - *buffer = view.buf; - *buffer_len = view.len; - if (pb->bf_releasebuffer != NULL) - (*pb->bf_releasebuffer)(obj, &view); - Py_XDECREF(view.obj); - return 0; + if (obj == NULL || buffer == NULL || buffer_len == NULL) { + null_error(); + return -1; + } + pb = obj->ob_type->tp_as_buffer; + if (pb == NULL || pb->bf_getbuffer == NULL) { + PyErr_SetString(PyExc_TypeError, + "expected an object with the buffer interface"); + return -1; + } + if ((*pb->bf_getbuffer)(obj, &view, PyBUF_SIMPLE)) return -1; + + *buffer = view.buf; + *buffer_len = view.len; + if (pb->bf_releasebuffer != NULL) + (*pb->bf_releasebuffer)(obj, &view); + Py_XDECREF(view.obj); + return 0; } int PyObject_CheckReadBuffer(PyObject *obj) { - PyBufferProcs *pb = obj->ob_type->tp_as_buffer; - Py_buffer view; + PyBufferProcs *pb = obj->ob_type->tp_as_buffer; + Py_buffer view; - if (pb == NULL || - pb->bf_getbuffer == NULL) - return 0; - if ((*pb->bf_getbuffer)(obj, &view, PyBUF_SIMPLE) == -1) { - PyErr_Clear(); - return 0; - } - PyBuffer_Release(&view); - return 1; + if (pb == NULL || + pb->bf_getbuffer == NULL) + return 0; + if ((*pb->bf_getbuffer)(obj, &view, PyBUF_SIMPLE) == -1) { + PyErr_Clear(); + return 0; + } + PyBuffer_Release(&view); + return 1; } int PyObject_AsReadBuffer(PyObject *obj, - const void **buffer, - Py_ssize_t *buffer_len) + const void **buffer, + Py_ssize_t *buffer_len) { - PyBufferProcs *pb; - Py_buffer view; + PyBufferProcs *pb; + Py_buffer view; + + if (obj == NULL || buffer == NULL || buffer_len == NULL) { + null_error(); + return -1; + } + pb = obj->ob_type->tp_as_buffer; + if (pb == NULL || + pb->bf_getbuffer == NULL) { + PyErr_SetString(PyExc_TypeError, + "expected an object with a buffer interface"); + return -1; + } + + if ((*pb->bf_getbuffer)(obj, &view, PyBUF_SIMPLE)) return -1; - if (obj == NULL || buffer == NULL || buffer_len == NULL) { - null_error(); - return -1; - } - pb = obj->ob_type->tp_as_buffer; - if (pb == NULL || - pb->bf_getbuffer == NULL) { - PyErr_SetString(PyExc_TypeError, - "expected an object with a buffer interface"); - return -1; - } - - if ((*pb->bf_getbuffer)(obj, &view, PyBUF_SIMPLE)) return -1; - - *buffer = view.buf; - *buffer_len = view.len; - if (pb->bf_releasebuffer != NULL) - (*pb->bf_releasebuffer)(obj, &view); - Py_XDECREF(view.obj); - return 0; + *buffer = view.buf; + *buffer_len = view.len; + if (pb->bf_releasebuffer != NULL) + (*pb->bf_releasebuffer)(obj, &view); + Py_XDECREF(view.obj); + return 0; } int PyObject_AsWriteBuffer(PyObject *obj, - void **buffer, - Py_ssize_t *buffer_len) + void **buffer, + Py_ssize_t *buffer_len) { - PyBufferProcs *pb; - Py_buffer view; + PyBufferProcs *pb; + Py_buffer view; - if (obj == NULL || buffer == NULL || buffer_len == NULL) { - null_error(); - return -1; - } - pb = obj->ob_type->tp_as_buffer; - if (pb == NULL || - pb->bf_getbuffer == NULL || - ((*pb->bf_getbuffer)(obj, &view, PyBUF_WRITABLE) != 0)) { - PyErr_SetString(PyExc_TypeError, - "expected an object with a writable buffer interface"); - return -1; - } - - *buffer = view.buf; - *buffer_len = view.len; - if (pb->bf_releasebuffer != NULL) - (*pb->bf_releasebuffer)(obj, &view); - Py_XDECREF(view.obj); - return 0; + if (obj == NULL || buffer == NULL || buffer_len == NULL) { + null_error(); + return -1; + } + pb = obj->ob_type->tp_as_buffer; + if (pb == NULL || + pb->bf_getbuffer == NULL || + ((*pb->bf_getbuffer)(obj, &view, PyBUF_WRITABLE) != 0)) { + PyErr_SetString(PyExc_TypeError, + "expected an object with a writable buffer interface"); + return -1; + } + + *buffer = view.buf; + *buffer_len = view.len; + if (pb->bf_releasebuffer != NULL) + (*pb->bf_releasebuffer)(obj, &view); + Py_XDECREF(view.obj); + return 0; } /* Buffer C-API for Python 3.0 */ @@ -329,119 +329,119 @@ int PyObject_GetBuffer(PyObject *obj, Py_buffer *view, int flags) { - if (!PyObject_CheckBuffer(obj)) { - PyErr_Format(PyExc_TypeError, - "'%100s' does not support the buffer interface", - Py_TYPE(obj)->tp_name); - return -1; - } - return (*(obj->ob_type->tp_as_buffer->bf_getbuffer))(obj, view, flags); + if (!PyObject_CheckBuffer(obj)) { + PyErr_Format(PyExc_TypeError, + "'%100s' does not support the buffer interface", + Py_TYPE(obj)->tp_name); + return -1; + } + return (*(obj->ob_type->tp_as_buffer->bf_getbuffer))(obj, view, flags); } static int _IsFortranContiguous(Py_buffer *view) { - Py_ssize_t sd, dim; - int i; + Py_ssize_t sd, dim; + int i; - if (view->ndim == 0) return 1; - if (view->strides == NULL) return (view->ndim == 1); + if (view->ndim == 0) return 1; + if (view->strides == NULL) return (view->ndim == 1); - sd = view->itemsize; - if (view->ndim == 1) return (view->shape[0] == 1 || - sd == view->strides[0]); - for (i=0; indim; i++) { - dim = view->shape[i]; - if (dim == 0) return 1; - if (view->strides[i] != sd) return 0; - sd *= dim; - } - return 1; + sd = view->itemsize; + if (view->ndim == 1) return (view->shape[0] == 1 || + sd == view->strides[0]); + for (i=0; indim; i++) { + dim = view->shape[i]; + if (dim == 0) return 1; + if (view->strides[i] != sd) return 0; + sd *= dim; + } + return 1; } static int _IsCContiguous(Py_buffer *view) { - Py_ssize_t sd, dim; - int i; + Py_ssize_t sd, dim; + int i; - if (view->ndim == 0) return 1; - if (view->strides == NULL) return 1; + if (view->ndim == 0) return 1; + if (view->strides == NULL) return 1; - sd = view->itemsize; - if (view->ndim == 1) return (view->shape[0] == 1 || - sd == view->strides[0]); - for (i=view->ndim-1; i>=0; i--) { - dim = view->shape[i]; - if (dim == 0) return 1; - if (view->strides[i] != sd) return 0; - sd *= dim; - } - return 1; + sd = view->itemsize; + if (view->ndim == 1) return (view->shape[0] == 1 || + sd == view->strides[0]); + for (i=view->ndim-1; i>=0; i--) { + dim = view->shape[i]; + if (dim == 0) return 1; + if (view->strides[i] != sd) return 0; + sd *= dim; + } + return 1; } int PyBuffer_IsContiguous(Py_buffer *view, char fort) { - if (view->suboffsets != NULL) return 0; + if (view->suboffsets != NULL) return 0; - if (fort == 'C') - return _IsCContiguous(view); - else if (fort == 'F') - return _IsFortranContiguous(view); - else if (fort == 'A') - return (_IsCContiguous(view) || _IsFortranContiguous(view)); - return 0; + if (fort == 'C') + return _IsCContiguous(view); + else if (fort == 'F') + return _IsFortranContiguous(view); + else if (fort == 'A') + return (_IsCContiguous(view) || _IsFortranContiguous(view)); + return 0; } void* PyBuffer_GetPointer(Py_buffer *view, Py_ssize_t *indices) { - char* pointer; - int i; - pointer = (char *)view->buf; - for (i = 0; i < view->ndim; i++) { - pointer += view->strides[i]*indices[i]; - if ((view->suboffsets != NULL) && (view->suboffsets[i] >= 0)) { - pointer = *((char**)pointer) + view->suboffsets[i]; - } - } - return (void*)pointer; + char* pointer; + int i; + pointer = (char *)view->buf; + for (i = 0; i < view->ndim; i++) { + pointer += view->strides[i]*indices[i]; + if ((view->suboffsets != NULL) && (view->suboffsets[i] >= 0)) { + pointer = *((char**)pointer) + view->suboffsets[i]; + } + } + return (void*)pointer; } void _add_one_to_index_F(int nd, Py_ssize_t *index, Py_ssize_t *shape) { - int k; + int k; - for (k=0; k=0; k--) { - if (index[k] < shape[k]-1) { - index[k]++; - break; - } - else { - index[k] = 0; - } - } + for (k=nd-1; k>=0; k--) { + if (index[k] < shape[k]-1) { + index[k]++; + break; + } + else { + index[k] = 0; + } + } } /* view is not checked for consistency in either of these. It is @@ -452,242 +452,242 @@ int PyBuffer_ToContiguous(void *buf, Py_buffer *view, Py_ssize_t len, char fort) { - int k; - void (*addone)(int, Py_ssize_t *, Py_ssize_t *); - Py_ssize_t *indices, elements; - char *dest, *ptr; - - if (len > view->len) { - len = view->len; - } - - if (PyBuffer_IsContiguous(view, fort)) { - /* simplest copy is all that is needed */ - memcpy(buf, view->buf, len); - return 0; - } - - /* Otherwise a more elaborate scheme is needed */ - - /* XXX(nnorwitz): need to check for overflow! */ - indices = (Py_ssize_t *)PyMem_Malloc(sizeof(Py_ssize_t)*(view->ndim)); - if (indices == NULL) { - PyErr_NoMemory(); - return -1; - } - for (k=0; kndim;k++) { - indices[k] = 0; - } - - if (fort == 'F') { - addone = _add_one_to_index_F; - } - else { - addone = _add_one_to_index_C; - } - dest = buf; - /* XXX : This is not going to be the fastest code in the world - several optimizations are possible. - */ - elements = len / view->itemsize; - while (elements--) { - addone(view->ndim, indices, view->shape); - ptr = PyBuffer_GetPointer(view, indices); - memcpy(dest, ptr, view->itemsize); - dest += view->itemsize; - } - PyMem_Free(indices); - return 0; + int k; + void (*addone)(int, Py_ssize_t *, Py_ssize_t *); + Py_ssize_t *indices, elements; + char *dest, *ptr; + + if (len > view->len) { + len = view->len; + } + + if (PyBuffer_IsContiguous(view, fort)) { + /* simplest copy is all that is needed */ + memcpy(buf, view->buf, len); + return 0; + } + + /* Otherwise a more elaborate scheme is needed */ + + /* XXX(nnorwitz): need to check for overflow! */ + indices = (Py_ssize_t *)PyMem_Malloc(sizeof(Py_ssize_t)*(view->ndim)); + if (indices == NULL) { + PyErr_NoMemory(); + return -1; + } + for (k=0; kndim;k++) { + indices[k] = 0; + } + + if (fort == 'F') { + addone = _add_one_to_index_F; + } + else { + addone = _add_one_to_index_C; + } + dest = buf; + /* XXX : This is not going to be the fastest code in the world + several optimizations are possible. + */ + elements = len / view->itemsize; + while (elements--) { + addone(view->ndim, indices, view->shape); + ptr = PyBuffer_GetPointer(view, indices); + memcpy(dest, ptr, view->itemsize); + dest += view->itemsize; + } + PyMem_Free(indices); + return 0; } int PyBuffer_FromContiguous(Py_buffer *view, void *buf, Py_ssize_t len, char fort) { - int k; - void (*addone)(int, Py_ssize_t *, Py_ssize_t *); - Py_ssize_t *indices, elements; - char *src, *ptr; - - if (len > view->len) { - len = view->len; - } - - if (PyBuffer_IsContiguous(view, fort)) { - /* simplest copy is all that is needed */ - memcpy(view->buf, buf, len); - return 0; - } - - /* Otherwise a more elaborate scheme is needed */ - - /* XXX(nnorwitz): need to check for overflow! */ - indices = (Py_ssize_t *)PyMem_Malloc(sizeof(Py_ssize_t)*(view->ndim)); - if (indices == NULL) { - PyErr_NoMemory(); - return -1; - } - for (k=0; kndim;k++) { - indices[k] = 0; - } - - if (fort == 'F') { - addone = _add_one_to_index_F; - } - else { - addone = _add_one_to_index_C; - } - src = buf; - /* XXX : This is not going to be the fastest code in the world - several optimizations are possible. - */ - elements = len / view->itemsize; - while (elements--) { - addone(view->ndim, indices, view->shape); - ptr = PyBuffer_GetPointer(view, indices); - memcpy(ptr, src, view->itemsize); - src += view->itemsize; - } + int k; + void (*addone)(int, Py_ssize_t *, Py_ssize_t *); + Py_ssize_t *indices, elements; + char *src, *ptr; + + if (len > view->len) { + len = view->len; + } + + if (PyBuffer_IsContiguous(view, fort)) { + /* simplest copy is all that is needed */ + memcpy(view->buf, buf, len); + return 0; + } + + /* Otherwise a more elaborate scheme is needed */ + + /* XXX(nnorwitz): need to check for overflow! */ + indices = (Py_ssize_t *)PyMem_Malloc(sizeof(Py_ssize_t)*(view->ndim)); + if (indices == NULL) { + PyErr_NoMemory(); + return -1; + } + for (k=0; kndim;k++) { + indices[k] = 0; + } - PyMem_Free(indices); - return 0; + if (fort == 'F') { + addone = _add_one_to_index_F; + } + else { + addone = _add_one_to_index_C; + } + src = buf; + /* XXX : This is not going to be the fastest code in the world + several optimizations are possible. + */ + elements = len / view->itemsize; + while (elements--) { + addone(view->ndim, indices, view->shape); + ptr = PyBuffer_GetPointer(view, indices); + memcpy(ptr, src, view->itemsize); + src += view->itemsize; + } + + PyMem_Free(indices); + return 0; } int PyObject_CopyData(PyObject *dest, PyObject *src) { - Py_buffer view_dest, view_src; - int k; - Py_ssize_t *indices, elements; - char *dptr, *sptr; - - if (!PyObject_CheckBuffer(dest) || - !PyObject_CheckBuffer(src)) { - PyErr_SetString(PyExc_TypeError, - "both destination and source must have the "\ - "buffer interface"); - return -1; - } - - if (PyObject_GetBuffer(dest, &view_dest, PyBUF_FULL) != 0) return -1; - if (PyObject_GetBuffer(src, &view_src, PyBUF_FULL_RO) != 0) { - PyBuffer_Release(&view_dest); - return -1; - } - - if (view_dest.len < view_src.len) { - PyErr_SetString(PyExc_BufferError, - "destination is too small to receive data from source"); - PyBuffer_Release(&view_dest); - PyBuffer_Release(&view_src); - return -1; - } - - if ((PyBuffer_IsContiguous(&view_dest, 'C') && - PyBuffer_IsContiguous(&view_src, 'C')) || - (PyBuffer_IsContiguous(&view_dest, 'F') && - PyBuffer_IsContiguous(&view_src, 'F'))) { - /* simplest copy is all that is needed */ - memcpy(view_dest.buf, view_src.buf, view_src.len); - PyBuffer_Release(&view_dest); - PyBuffer_Release(&view_src); - return 0; - } - - /* Otherwise a more elaborate copy scheme is needed */ - - /* XXX(nnorwitz): need to check for overflow! */ - indices = (Py_ssize_t *)PyMem_Malloc(sizeof(Py_ssize_t)*view_src.ndim); - if (indices == NULL) { - PyErr_NoMemory(); - PyBuffer_Release(&view_dest); - PyBuffer_Release(&view_src); - return -1; - } - for (k=0; k=0; k--) { - strides[k] = sd; - sd *= shape[k]; - } - } - return; + sd = itemsize; + if (fort == 'F') { + for (k=0; k=0; k--) { + strides[k] = sd; + sd *= shape[k]; + } + } + return; } int PyBuffer_FillInfo(Py_buffer *view, PyObject *obj, void *buf, Py_ssize_t len, - int readonly, int flags) + int readonly, int flags) { - if (view == NULL) return 0; - if (((flags & PyBUF_WRITABLE) == PyBUF_WRITABLE) && - (readonly == 1)) { - PyErr_SetString(PyExc_BufferError, - "Object is not writable."); - return -1; - } - - view->obj = obj; - if (obj) - Py_INCREF(obj); - view->buf = buf; - view->len = len; - view->readonly = readonly; - view->itemsize = 1; - view->format = NULL; - if ((flags & PyBUF_FORMAT) == PyBUF_FORMAT) - view->format = "B"; - view->ndim = 1; - view->shape = NULL; - if ((flags & PyBUF_ND) == PyBUF_ND) - view->shape = &(view->len); - view->strides = NULL; - if ((flags & PyBUF_STRIDES) == PyBUF_STRIDES) - view->strides = &(view->itemsize); - view->suboffsets = NULL; - view->internal = NULL; - return 0; + if (view == NULL) return 0; + if (((flags & PyBUF_WRITABLE) == PyBUF_WRITABLE) && + (readonly == 1)) { + PyErr_SetString(PyExc_BufferError, + "Object is not writable."); + return -1; + } + + view->obj = obj; + if (obj) + Py_INCREF(obj); + view->buf = buf; + view->len = len; + view->readonly = readonly; + view->itemsize = 1; + view->format = NULL; + if ((flags & PyBUF_FORMAT) == PyBUF_FORMAT) + view->format = "B"; + view->ndim = 1; + view->shape = NULL; + if ((flags & PyBUF_ND) == PyBUF_ND) + view->shape = &(view->len); + view->strides = NULL; + if ((flags & PyBUF_STRIDES) == PyBUF_STRIDES) + view->strides = &(view->itemsize); + view->suboffsets = NULL; + view->internal = NULL; + return 0; } void PyBuffer_Release(Py_buffer *view) { - PyObject *obj = view->obj; - if (obj && Py_TYPE(obj)->tp_as_buffer && Py_TYPE(obj)->tp_as_buffer->bf_releasebuffer) - Py_TYPE(obj)->tp_as_buffer->bf_releasebuffer(obj, view); - Py_XDECREF(obj); - view->obj = NULL; + PyObject *obj = view->obj; + if (obj && Py_TYPE(obj)->tp_as_buffer && Py_TYPE(obj)->tp_as_buffer->bf_releasebuffer) + Py_TYPE(obj)->tp_as_buffer->bf_releasebuffer(obj, view); + Py_XDECREF(obj); + view->obj = NULL; } PyObject * @@ -700,41 +700,41 @@ /* Initialize cached value */ if (str__format__ == NULL) { - /* Initialize static variable needed by _PyType_Lookup */ - str__format__ = PyUnicode_FromString("__format__"); - if (str__format__ == NULL) - goto done; + /* Initialize static variable needed by _PyType_Lookup */ + str__format__ = PyUnicode_FromString("__format__"); + if (str__format__ == NULL) + goto done; } /* If no format_spec is provided, use an empty string */ if (format_spec == NULL) { - empty = PyUnicode_FromUnicode(NULL, 0); - format_spec = empty; + empty = PyUnicode_FromUnicode(NULL, 0); + format_spec = empty; } /* Make sure the type is initialized. float gets initialized late */ if (Py_TYPE(obj)->tp_dict == NULL) - if (PyType_Ready(Py_TYPE(obj)) < 0) - goto done; + if (PyType_Ready(Py_TYPE(obj)) < 0) + goto done; /* Find the (unbound!) __format__ method (a borrowed reference) */ meth = _PyType_Lookup(Py_TYPE(obj), str__format__); if (meth == NULL) { - PyErr_Format(PyExc_TypeError, - "Type %.100s doesn't define __format__", - Py_TYPE(obj)->tp_name); - goto done; + PyErr_Format(PyExc_TypeError, + "Type %.100s doesn't define __format__", + Py_TYPE(obj)->tp_name); + goto done; } /* And call it, binding it to the value */ result = PyObject_CallFunctionObjArgs(meth, obj, format_spec, NULL); if (result && !PyUnicode_Check(result)) { - PyErr_SetString(PyExc_TypeError, - "__format__ method did not return string"); - Py_DECREF(result); - result = NULL; - goto done; + PyErr_SetString(PyExc_TypeError, + "__format__ method did not return string"); + Py_DECREF(result); + result = NULL; + goto done; } done: @@ -746,24 +746,24 @@ int PyNumber_Check(PyObject *o) { - return o && o->ob_type->tp_as_number && - (o->ob_type->tp_as_number->nb_int || - o->ob_type->tp_as_number->nb_float); + return o && o->ob_type->tp_as_number && + (o->ob_type->tp_as_number->nb_int || + o->ob_type->tp_as_number->nb_float); } /* Binary operators */ #define NB_SLOT(x) offsetof(PyNumberMethods, x) #define NB_BINOP(nb_methods, slot) \ - (*(binaryfunc*)(& ((char*)nb_methods)[slot])) + (*(binaryfunc*)(& ((char*)nb_methods)[slot])) #define NB_TERNOP(nb_methods, slot) \ - (*(ternaryfunc*)(& ((char*)nb_methods)[slot])) + (*(ternaryfunc*)(& ((char*)nb_methods)[slot])) /* Calling scheme used for binary operations: Order operations are tried until either a valid result or error: - w.op(v,w)[*], v.op(v,w), w.op(v,w) + w.op(v,w)[*], v.op(v,w), w.op(v,w) [*] only when v->ob_type != w->ob_type && w->ob_type is a subclass of v->ob_type @@ -772,62 +772,62 @@ static PyObject * binary_op1(PyObject *v, PyObject *w, const int op_slot) { - PyObject *x; - binaryfunc slotv = NULL; - binaryfunc slotw = NULL; - - if (v->ob_type->tp_as_number != NULL) - slotv = NB_BINOP(v->ob_type->tp_as_number, op_slot); - if (w->ob_type != v->ob_type && - w->ob_type->tp_as_number != NULL) { - slotw = NB_BINOP(w->ob_type->tp_as_number, op_slot); - if (slotw == slotv) - slotw = NULL; - } - if (slotv) { - if (slotw && PyType_IsSubtype(w->ob_type, v->ob_type)) { - x = slotw(v, w); - if (x != Py_NotImplemented) - return x; - Py_DECREF(x); /* can't do it */ - slotw = NULL; - } - x = slotv(v, w); - if (x != Py_NotImplemented) - return x; - Py_DECREF(x); /* can't do it */ - } - if (slotw) { - x = slotw(v, w); - if (x != Py_NotImplemented) - return x; - Py_DECREF(x); /* can't do it */ - } - Py_INCREF(Py_NotImplemented); - return Py_NotImplemented; + PyObject *x; + binaryfunc slotv = NULL; + binaryfunc slotw = NULL; + + if (v->ob_type->tp_as_number != NULL) + slotv = NB_BINOP(v->ob_type->tp_as_number, op_slot); + if (w->ob_type != v->ob_type && + w->ob_type->tp_as_number != NULL) { + slotw = NB_BINOP(w->ob_type->tp_as_number, op_slot); + if (slotw == slotv) + slotw = NULL; + } + if (slotv) { + if (slotw && PyType_IsSubtype(w->ob_type, v->ob_type)) { + x = slotw(v, w); + if (x != Py_NotImplemented) + return x; + Py_DECREF(x); /* can't do it */ + slotw = NULL; + } + x = slotv(v, w); + if (x != Py_NotImplemented) + return x; + Py_DECREF(x); /* can't do it */ + } + if (slotw) { + x = slotw(v, w); + if (x != Py_NotImplemented) + return x; + Py_DECREF(x); /* can't do it */ + } + Py_INCREF(Py_NotImplemented); + return Py_NotImplemented; } static PyObject * binop_type_error(PyObject *v, PyObject *w, const char *op_name) { - PyErr_Format(PyExc_TypeError, - "unsupported operand type(s) for %.100s: " - "'%.100s' and '%.100s'", - op_name, - v->ob_type->tp_name, - w->ob_type->tp_name); - return NULL; + PyErr_Format(PyExc_TypeError, + "unsupported operand type(s) for %.100s: " + "'%.100s' and '%.100s'", + op_name, + v->ob_type->tp_name, + w->ob_type->tp_name); + return NULL; } static PyObject * binary_op(PyObject *v, PyObject *w, const int op_slot, const char *op_name) { - PyObject *result = binary_op1(v, w, op_slot); - if (result == Py_NotImplemented) { - Py_DECREF(result); - return binop_type_error(v, w, op_name); - } - return result; + PyObject *result = binary_op1(v, w, op_slot); + if (result == Py_NotImplemented) { + Py_DECREF(result); + return binop_type_error(v, w, op_name); + } + return result; } @@ -835,86 +835,86 @@ Calling scheme used for ternary operations: Order operations are tried until either a valid result or error: - v.op(v,w,z), w.op(v,w,z), z.op(v,w,z) + v.op(v,w,z), w.op(v,w,z), z.op(v,w,z) */ static PyObject * ternary_op(PyObject *v, - PyObject *w, - PyObject *z, - const int op_slot, - const char *op_name) -{ - PyNumberMethods *mv, *mw, *mz; - PyObject *x = NULL; - ternaryfunc slotv = NULL; - ternaryfunc slotw = NULL; - ternaryfunc slotz = NULL; - - mv = v->ob_type->tp_as_number; - mw = w->ob_type->tp_as_number; - if (mv != NULL) - slotv = NB_TERNOP(mv, op_slot); - if (w->ob_type != v->ob_type && - mw != NULL) { - slotw = NB_TERNOP(mw, op_slot); - if (slotw == slotv) - slotw = NULL; - } - if (slotv) { - if (slotw && PyType_IsSubtype(w->ob_type, v->ob_type)) { - x = slotw(v, w, z); - if (x != Py_NotImplemented) - return x; - Py_DECREF(x); /* can't do it */ - slotw = NULL; - } - x = slotv(v, w, z); - if (x != Py_NotImplemented) - return x; - Py_DECREF(x); /* can't do it */ - } - if (slotw) { - x = slotw(v, w, z); - if (x != Py_NotImplemented) - return x; - Py_DECREF(x); /* can't do it */ - } - mz = z->ob_type->tp_as_number; - if (mz != NULL) { - slotz = NB_TERNOP(mz, op_slot); - if (slotz == slotv || slotz == slotw) - slotz = NULL; - if (slotz) { - x = slotz(v, w, z); - if (x != Py_NotImplemented) - return x; - Py_DECREF(x); /* can't do it */ - } - } - - if (z == Py_None) - PyErr_Format( - PyExc_TypeError, - "unsupported operand type(s) for ** or pow(): " - "'%.100s' and '%.100s'", - v->ob_type->tp_name, - w->ob_type->tp_name); - else - PyErr_Format( - PyExc_TypeError, - "unsupported operand type(s) for pow(): " - "'%.100s', '%.100s', '%.100s'", - v->ob_type->tp_name, - w->ob_type->tp_name, - z->ob_type->tp_name); - return NULL; + PyObject *w, + PyObject *z, + const int op_slot, + const char *op_name) +{ + PyNumberMethods *mv, *mw, *mz; + PyObject *x = NULL; + ternaryfunc slotv = NULL; + ternaryfunc slotw = NULL; + ternaryfunc slotz = NULL; + + mv = v->ob_type->tp_as_number; + mw = w->ob_type->tp_as_number; + if (mv != NULL) + slotv = NB_TERNOP(mv, op_slot); + if (w->ob_type != v->ob_type && + mw != NULL) { + slotw = NB_TERNOP(mw, op_slot); + if (slotw == slotv) + slotw = NULL; + } + if (slotv) { + if (slotw && PyType_IsSubtype(w->ob_type, v->ob_type)) { + x = slotw(v, w, z); + if (x != Py_NotImplemented) + return x; + Py_DECREF(x); /* can't do it */ + slotw = NULL; + } + x = slotv(v, w, z); + if (x != Py_NotImplemented) + return x; + Py_DECREF(x); /* can't do it */ + } + if (slotw) { + x = slotw(v, w, z); + if (x != Py_NotImplemented) + return x; + Py_DECREF(x); /* can't do it */ + } + mz = z->ob_type->tp_as_number; + if (mz != NULL) { + slotz = NB_TERNOP(mz, op_slot); + if (slotz == slotv || slotz == slotw) + slotz = NULL; + if (slotz) { + x = slotz(v, w, z); + if (x != Py_NotImplemented) + return x; + Py_DECREF(x); /* can't do it */ + } + } + + if (z == Py_None) + PyErr_Format( + PyExc_TypeError, + "unsupported operand type(s) for ** or pow(): " + "'%.100s' and '%.100s'", + v->ob_type->tp_name, + w->ob_type->tp_name); + else + PyErr_Format( + PyExc_TypeError, + "unsupported operand type(s) for pow(): " + "'%.100s', '%.100s', '%.100s'", + v->ob_type->tp_name, + w->ob_type->tp_name, + z->ob_type->tp_name); + return NULL; } #define BINARY_FUNC(func, op, op_name) \ PyObject * \ func(PyObject *v, PyObject *w) { \ - return binary_op(v, w, NB_SLOT(op), op_name); \ + return binary_op(v, w, NB_SLOT(op), op_name); \ } BINARY_FUNC(PyNumber_Or, nb_or, "|") @@ -928,75 +928,75 @@ PyObject * PyNumber_Add(PyObject *v, PyObject *w) { - PyObject *result = binary_op1(v, w, NB_SLOT(nb_add)); - if (result == Py_NotImplemented) { - PySequenceMethods *m = v->ob_type->tp_as_sequence; - Py_DECREF(result); - if (m && m->sq_concat) { - return (*m->sq_concat)(v, w); - } - result = binop_type_error(v, w, "+"); - } - return result; + PyObject *result = binary_op1(v, w, NB_SLOT(nb_add)); + if (result == Py_NotImplemented) { + PySequenceMethods *m = v->ob_type->tp_as_sequence; + Py_DECREF(result); + if (m && m->sq_concat) { + return (*m->sq_concat)(v, w); + } + result = binop_type_error(v, w, "+"); + } + return result; } static PyObject * sequence_repeat(ssizeargfunc repeatfunc, PyObject *seq, PyObject *n) { - Py_ssize_t count; - if (PyIndex_Check(n)) { - count = PyNumber_AsSsize_t(n, PyExc_OverflowError); - if (count == -1 && PyErr_Occurred()) - return NULL; - } - else { - return type_error("can't multiply sequence by " - "non-int of type '%.200s'", n); - } - return (*repeatfunc)(seq, count); + Py_ssize_t count; + if (PyIndex_Check(n)) { + count = PyNumber_AsSsize_t(n, PyExc_OverflowError); + if (count == -1 && PyErr_Occurred()) + return NULL; + } + else { + return type_error("can't multiply sequence by " + "non-int of type '%.200s'", n); + } + return (*repeatfunc)(seq, count); } PyObject * PyNumber_Multiply(PyObject *v, PyObject *w) { - PyObject *result = binary_op1(v, w, NB_SLOT(nb_multiply)); - if (result == Py_NotImplemented) { - PySequenceMethods *mv = v->ob_type->tp_as_sequence; - PySequenceMethods *mw = w->ob_type->tp_as_sequence; - Py_DECREF(result); - if (mv && mv->sq_repeat) { - return sequence_repeat(mv->sq_repeat, v, w); - } - else if (mw && mw->sq_repeat) { - return sequence_repeat(mw->sq_repeat, w, v); - } - result = binop_type_error(v, w, "*"); - } - return result; + PyObject *result = binary_op1(v, w, NB_SLOT(nb_multiply)); + if (result == Py_NotImplemented) { + PySequenceMethods *mv = v->ob_type->tp_as_sequence; + PySequenceMethods *mw = w->ob_type->tp_as_sequence; + Py_DECREF(result); + if (mv && mv->sq_repeat) { + return sequence_repeat(mv->sq_repeat, v, w); + } + else if (mw && mw->sq_repeat) { + return sequence_repeat(mw->sq_repeat, w, v); + } + result = binop_type_error(v, w, "*"); + } + return result; } PyObject * PyNumber_FloorDivide(PyObject *v, PyObject *w) { - return binary_op(v, w, NB_SLOT(nb_floor_divide), "//"); + return binary_op(v, w, NB_SLOT(nb_floor_divide), "//"); } PyObject * PyNumber_TrueDivide(PyObject *v, PyObject *w) { - return binary_op(v, w, NB_SLOT(nb_true_divide), "/"); + return binary_op(v, w, NB_SLOT(nb_true_divide), "/"); } PyObject * PyNumber_Remainder(PyObject *v, PyObject *w) { - return binary_op(v, w, NB_SLOT(nb_remainder), "%"); + return binary_op(v, w, NB_SLOT(nb_remainder), "%"); } PyObject * PyNumber_Power(PyObject *v, PyObject *w, PyObject *z) { - return ternary_op(v, w, z, NB_SLOT(nb_power), "** or pow()"); + return ternary_op(v, w, z, NB_SLOT(nb_power), "** or pow()"); } /* Binary in-place operators */ @@ -1018,37 +1018,37 @@ static PyObject * binary_iop1(PyObject *v, PyObject *w, const int iop_slot, const int op_slot) { - PyNumberMethods *mv = v->ob_type->tp_as_number; - if (mv != NULL) { - binaryfunc slot = NB_BINOP(mv, iop_slot); - if (slot) { - PyObject *x = (slot)(v, w); - if (x != Py_NotImplemented) { - return x; - } - Py_DECREF(x); - } - } - return binary_op1(v, w, op_slot); + PyNumberMethods *mv = v->ob_type->tp_as_number; + if (mv != NULL) { + binaryfunc slot = NB_BINOP(mv, iop_slot); + if (slot) { + PyObject *x = (slot)(v, w); + if (x != Py_NotImplemented) { + return x; + } + Py_DECREF(x); + } + } + return binary_op1(v, w, op_slot); } static PyObject * binary_iop(PyObject *v, PyObject *w, const int iop_slot, const int op_slot, - const char *op_name) + const char *op_name) { - PyObject *result = binary_iop1(v, w, iop_slot, op_slot); - if (result == Py_NotImplemented) { - Py_DECREF(result); - return binop_type_error(v, w, op_name); - } - return result; + PyObject *result = binary_iop1(v, w, iop_slot, op_slot); + if (result == Py_NotImplemented) { + Py_DECREF(result); + return binop_type_error(v, w, op_name); + } + return result; } #define INPLACE_BINOP(func, iop, op, op_name) \ - PyObject * \ - func(PyObject *v, PyObject *w) { \ - return binary_iop(v, w, NB_SLOT(iop), NB_SLOT(op), op_name); \ - } + PyObject * \ + func(PyObject *v, PyObject *w) { \ + return binary_iop(v, w, NB_SLOT(iop), NB_SLOT(op), op_name); \ + } INPLACE_BINOP(PyNumber_InPlaceOr, nb_inplace_or, nb_or, "|=") INPLACE_BINOP(PyNumber_InPlaceXor, nb_inplace_xor, nb_xor, "^=") @@ -1060,84 +1060,84 @@ PyObject * PyNumber_InPlaceFloorDivide(PyObject *v, PyObject *w) { - return binary_iop(v, w, NB_SLOT(nb_inplace_floor_divide), - NB_SLOT(nb_floor_divide), "//="); + return binary_iop(v, w, NB_SLOT(nb_inplace_floor_divide), + NB_SLOT(nb_floor_divide), "//="); } PyObject * PyNumber_InPlaceTrueDivide(PyObject *v, PyObject *w) { - return binary_iop(v, w, NB_SLOT(nb_inplace_true_divide), - NB_SLOT(nb_true_divide), "/="); + return binary_iop(v, w, NB_SLOT(nb_inplace_true_divide), + NB_SLOT(nb_true_divide), "/="); } PyObject * PyNumber_InPlaceAdd(PyObject *v, PyObject *w) { - PyObject *result = binary_iop1(v, w, NB_SLOT(nb_inplace_add), - NB_SLOT(nb_add)); - if (result == Py_NotImplemented) { - PySequenceMethods *m = v->ob_type->tp_as_sequence; - Py_DECREF(result); - if (m != NULL) { - binaryfunc f = NULL; - f = m->sq_inplace_concat; - if (f == NULL) - f = m->sq_concat; - if (f != NULL) - return (*f)(v, w); - } - result = binop_type_error(v, w, "+="); - } - return result; + PyObject *result = binary_iop1(v, w, NB_SLOT(nb_inplace_add), + NB_SLOT(nb_add)); + if (result == Py_NotImplemented) { + PySequenceMethods *m = v->ob_type->tp_as_sequence; + Py_DECREF(result); + if (m != NULL) { + binaryfunc f = NULL; + f = m->sq_inplace_concat; + if (f == NULL) + f = m->sq_concat; + if (f != NULL) + return (*f)(v, w); + } + result = binop_type_error(v, w, "+="); + } + return result; } PyObject * PyNumber_InPlaceMultiply(PyObject *v, PyObject *w) { - PyObject *result = binary_iop1(v, w, NB_SLOT(nb_inplace_multiply), - NB_SLOT(nb_multiply)); - if (result == Py_NotImplemented) { - ssizeargfunc f = NULL; - PySequenceMethods *mv = v->ob_type->tp_as_sequence; - PySequenceMethods *mw = w->ob_type->tp_as_sequence; - Py_DECREF(result); - if (mv != NULL) { - f = mv->sq_inplace_repeat; - if (f == NULL) - f = mv->sq_repeat; - if (f != NULL) - return sequence_repeat(f, v, w); - } - else if (mw != NULL) { - /* Note that the right hand operand should not be - * mutated in this case so sq_inplace_repeat is not - * used. */ - if (mw->sq_repeat) - return sequence_repeat(mw->sq_repeat, w, v); - } - result = binop_type_error(v, w, "*="); - } - return result; + PyObject *result = binary_iop1(v, w, NB_SLOT(nb_inplace_multiply), + NB_SLOT(nb_multiply)); + if (result == Py_NotImplemented) { + ssizeargfunc f = NULL; + PySequenceMethods *mv = v->ob_type->tp_as_sequence; + PySequenceMethods *mw = w->ob_type->tp_as_sequence; + Py_DECREF(result); + if (mv != NULL) { + f = mv->sq_inplace_repeat; + if (f == NULL) + f = mv->sq_repeat; + if (f != NULL) + return sequence_repeat(f, v, w); + } + else if (mw != NULL) { + /* Note that the right hand operand should not be + * mutated in this case so sq_inplace_repeat is not + * used. */ + if (mw->sq_repeat) + return sequence_repeat(mw->sq_repeat, w, v); + } + result = binop_type_error(v, w, "*="); + } + return result; } PyObject * PyNumber_InPlaceRemainder(PyObject *v, PyObject *w) { - return binary_iop(v, w, NB_SLOT(nb_inplace_remainder), - NB_SLOT(nb_remainder), "%="); + return binary_iop(v, w, NB_SLOT(nb_inplace_remainder), + NB_SLOT(nb_remainder), "%="); } PyObject * PyNumber_InPlacePower(PyObject *v, PyObject *w, PyObject *z) { - if (v->ob_type->tp_as_number && - v->ob_type->tp_as_number->nb_inplace_power != NULL) { - return ternary_op(v, w, z, NB_SLOT(nb_inplace_power), "**="); - } - else { - return ternary_op(v, w, z, NB_SLOT(nb_power), "**="); - } + if (v->ob_type->tp_as_number && + v->ob_type->tp_as_number->nb_inplace_power != NULL) { + return ternary_op(v, w, z, NB_SLOT(nb_inplace_power), "**="); + } + else { + return ternary_op(v, w, z, NB_SLOT(nb_power), "**="); + } } @@ -1146,57 +1146,57 @@ PyObject * PyNumber_Negative(PyObject *o) { - PyNumberMethods *m; + PyNumberMethods *m; - if (o == NULL) - return null_error(); - m = o->ob_type->tp_as_number; - if (m && m->nb_negative) - return (*m->nb_negative)(o); + if (o == NULL) + return null_error(); + m = o->ob_type->tp_as_number; + if (m && m->nb_negative) + return (*m->nb_negative)(o); - return type_error("bad operand type for unary -: '%.200s'", o); + return type_error("bad operand type for unary -: '%.200s'", o); } PyObject * PyNumber_Positive(PyObject *o) { - PyNumberMethods *m; + PyNumberMethods *m; - if (o == NULL) - return null_error(); - m = o->ob_type->tp_as_number; - if (m && m->nb_positive) - return (*m->nb_positive)(o); + if (o == NULL) + return null_error(); + m = o->ob_type->tp_as_number; + if (m && m->nb_positive) + return (*m->nb_positive)(o); - return type_error("bad operand type for unary +: '%.200s'", o); + return type_error("bad operand type for unary +: '%.200s'", o); } PyObject * PyNumber_Invert(PyObject *o) { - PyNumberMethods *m; + PyNumberMethods *m; - if (o == NULL) - return null_error(); - m = o->ob_type->tp_as_number; - if (m && m->nb_invert) - return (*m->nb_invert)(o); + if (o == NULL) + return null_error(); + m = o->ob_type->tp_as_number; + if (m && m->nb_invert) + return (*m->nb_invert)(o); - return type_error("bad operand type for unary ~: '%.200s'", o); + return type_error("bad operand type for unary ~: '%.200s'", o); } PyObject * PyNumber_Absolute(PyObject *o) { - PyNumberMethods *m; + PyNumberMethods *m; - if (o == NULL) - return null_error(); - m = o->ob_type->tp_as_number; - if (m && m->nb_absolute) - return m->nb_absolute(o); + if (o == NULL) + return null_error(); + m = o->ob_type->tp_as_number; + if (m && m->nb_absolute) + return m->nb_absolute(o); - return type_error("bad operand type for abs(): '%.200s'", o); + return type_error("bad operand type for abs(): '%.200s'", o); } /* Return a Python Int or Long from the object item @@ -1206,30 +1206,30 @@ PyObject * PyNumber_Index(PyObject *item) { - PyObject *result = NULL; - if (item == NULL) - return null_error(); - if (PyLong_Check(item)) { - Py_INCREF(item); - return item; - } - if (PyIndex_Check(item)) { - result = item->ob_type->tp_as_number->nb_index(item); - if (result && !PyLong_Check(result)) { - PyErr_Format(PyExc_TypeError, - "__index__ returned non-int " - "(type %.200s)", - result->ob_type->tp_name); - Py_DECREF(result); - return NULL; - } - } - else { - PyErr_Format(PyExc_TypeError, - "'%.200s' object cannot be interpreted " - "as an integer", item->ob_type->tp_name); - } - return result; + PyObject *result = NULL; + if (item == NULL) + return null_error(); + if (PyLong_Check(item)) { + Py_INCREF(item); + return item; + } + if (PyIndex_Check(item)) { + result = item->ob_type->tp_as_number->nb_index(item); + if (result && !PyLong_Check(result)) { + PyErr_Format(PyExc_TypeError, + "__index__ returned non-int " + "(type %.200s)", + result->ob_type->tp_name); + Py_DECREF(result); + return NULL; + } + } + else { + PyErr_Format(PyExc_TypeError, + "'%.200s' object cannot be interpreted " + "as an integer", item->ob_type->tp_name); + } + return result; } /* Return an error on Overflow only if err is not NULL*/ @@ -1237,79 +1237,79 @@ Py_ssize_t PyNumber_AsSsize_t(PyObject *item, PyObject *err) { - Py_ssize_t result; - PyObject *runerr; - PyObject *value = PyNumber_Index(item); - if (value == NULL) - return -1; - - /* We're done if PyLong_AsSsize_t() returns without error. */ - result = PyLong_AsSsize_t(value); - if (result != -1 || !(runerr = PyErr_Occurred())) - goto finish; - - /* Error handling code -- only manage OverflowError differently */ - if (!PyErr_GivenExceptionMatches(runerr, PyExc_OverflowError)) - goto finish; - - PyErr_Clear(); - /* If no error-handling desired then the default clipping - is sufficient. - */ - if (!err) { - assert(PyLong_Check(value)); - /* Whether or not it is less than or equal to - zero is determined by the sign of ob_size - */ - if (_PyLong_Sign(value) < 0) - result = PY_SSIZE_T_MIN; - else - result = PY_SSIZE_T_MAX; - } - else { - /* Otherwise replace the error with caller's error object. */ - PyErr_Format(err, - "cannot fit '%.200s' into an index-sized integer", - item->ob_type->tp_name); - } + Py_ssize_t result; + PyObject *runerr; + PyObject *value = PyNumber_Index(item); + if (value == NULL) + return -1; + + /* We're done if PyLong_AsSsize_t() returns without error. */ + result = PyLong_AsSsize_t(value); + if (result != -1 || !(runerr = PyErr_Occurred())) + goto finish; + + /* Error handling code -- only manage OverflowError differently */ + if (!PyErr_GivenExceptionMatches(runerr, PyExc_OverflowError)) + goto finish; + + PyErr_Clear(); + /* If no error-handling desired then the default clipping + is sufficient. + */ + if (!err) { + assert(PyLong_Check(value)); + /* Whether or not it is less than or equal to + zero is determined by the sign of ob_size + */ + if (_PyLong_Sign(value) < 0) + result = PY_SSIZE_T_MIN; + else + result = PY_SSIZE_T_MAX; + } + else { + /* Otherwise replace the error with caller's error object. */ + PyErr_Format(err, + "cannot fit '%.200s' into an index-sized integer", + item->ob_type->tp_name); + } finish: - Py_DECREF(value); - return result; + Py_DECREF(value); + return result; } PyObject * _PyNumber_ConvertIntegralToInt(PyObject *integral, const char* error_format) { - static PyObject *int_name = NULL; - if (int_name == NULL) { - int_name = PyUnicode_InternFromString("__int__"); - if (int_name == NULL) - return NULL; - } - - if (integral && !PyLong_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); - if (int_func == NULL) { - PyErr_Clear(); /* Raise a different error. */ - goto non_integral_error; - } - Py_DECREF(integral); - integral = PyEval_CallObject(int_func, NULL); - Py_DECREF(int_func); - if (integral && !PyLong_Check(integral)) { - goto non_integral_error; - } - } - return integral; + static PyObject *int_name = NULL; + if (int_name == NULL) { + int_name = PyUnicode_InternFromString("__int__"); + if (int_name == NULL) + return NULL; + } + + if (integral && !PyLong_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); + if (int_func == NULL) { + PyErr_Clear(); /* Raise a different error. */ + goto non_integral_error; + } + Py_DECREF(integral); + integral = PyEval_CallObject(int_func, NULL); + Py_DECREF(int_func); + if (integral && !PyLong_Check(integral)) { + goto non_integral_error; + } + } + return integral; non_integral_error: - PyErr_Format(PyExc_TypeError, error_format, Py_TYPE(integral)->tp_name); - Py_DECREF(integral); - return NULL; + PyErr_Format(PyExc_TypeError, error_format, Py_TYPE(integral)->tp_name); + Py_DECREF(integral); + return NULL; } @@ -1317,134 +1317,134 @@ static PyObject * long_from_string(const char *s, Py_ssize_t len) { - char *end; - PyObject *x; + char *end; + PyObject *x; - x = PyLong_FromString((char*)s, &end, 10); - if (x == NULL) - return NULL; - if (end != s + len) { - PyErr_SetString(PyExc_ValueError, - "null byte in argument for int()"); - Py_DECREF(x); - return NULL; - } - return x; + x = PyLong_FromString((char*)s, &end, 10); + if (x == NULL) + return NULL; + if (end != s + len) { + PyErr_SetString(PyExc_ValueError, + "null byte in argument for int()"); + Py_DECREF(x); + return NULL; + } + return x; } PyObject * PyNumber_Long(PyObject *o) { - PyNumberMethods *m; - static PyObject *trunc_name = NULL; - PyObject *trunc_func; - const char *buffer; - Py_ssize_t buffer_len; - - if (trunc_name == NULL) { - trunc_name = PyUnicode_InternFromString("__trunc__"); - if (trunc_name == NULL) - return NULL; - } - - if (o == NULL) - return null_error(); - if (PyLong_CheckExact(o)) { - Py_INCREF(o); - return o; - } - m = o->ob_type->tp_as_number; - if (m && m->nb_int) { /* This should include subclasses of int */ - PyObject *res = m->nb_int(o); - if (res && !PyLong_Check(res)) { - PyErr_Format(PyExc_TypeError, - "__int__ returned non-int (type %.200s)", - res->ob_type->tp_name); - Py_DECREF(res); - return NULL; - } - return res; - } - if (PyLong_Check(o)) /* An int subclass without nb_int */ - return _PyLong_Copy((PyLongObject *)o); - trunc_func = PyObject_GetAttr(o, trunc_name); - if (trunc_func) { - PyObject *truncated = PyEval_CallObject(trunc_func, NULL); - PyObject *int_instance; - Py_DECREF(trunc_func); - /* __trunc__ is specified to return an Integral type, - but long() needs to return a long. */ - int_instance = _PyNumber_ConvertIntegralToInt( - truncated, - "__trunc__ returned non-Integral (type %.200s)"); - return int_instance; - } - PyErr_Clear(); /* It's not an error if o.__trunc__ doesn't exist. */ - - if (PyBytes_Check(o)) - /* need to do extra error checking that PyLong_FromString() - * doesn't do. In particular long('9.5') must raise an - * exception, not truncate the float. - */ - return long_from_string(PyBytes_AS_STRING(o), - PyBytes_GET_SIZE(o)); - if (PyUnicode_Check(o)) - /* The above check is done in PyLong_FromUnicode(). */ - return PyLong_FromUnicode(PyUnicode_AS_UNICODE(o), - PyUnicode_GET_SIZE(o), - 10); - if (!PyObject_AsCharBuffer(o, &buffer, &buffer_len)) - return long_from_string(buffer, buffer_len); + PyNumberMethods *m; + static PyObject *trunc_name = NULL; + PyObject *trunc_func; + const char *buffer; + Py_ssize_t buffer_len; + + if (trunc_name == NULL) { + trunc_name = PyUnicode_InternFromString("__trunc__"); + if (trunc_name == NULL) + return NULL; + } - return type_error("int() argument must be a string or a " - "number, not '%.200s'", o); + if (o == NULL) + return null_error(); + if (PyLong_CheckExact(o)) { + Py_INCREF(o); + return o; + } + m = o->ob_type->tp_as_number; + if (m && m->nb_int) { /* This should include subclasses of int */ + PyObject *res = m->nb_int(o); + if (res && !PyLong_Check(res)) { + PyErr_Format(PyExc_TypeError, + "__int__ returned non-int (type %.200s)", + res->ob_type->tp_name); + Py_DECREF(res); + return NULL; + } + return res; + } + if (PyLong_Check(o)) /* An int subclass without nb_int */ + return _PyLong_Copy((PyLongObject *)o); + trunc_func = PyObject_GetAttr(o, trunc_name); + if (trunc_func) { + PyObject *truncated = PyEval_CallObject(trunc_func, NULL); + PyObject *int_instance; + Py_DECREF(trunc_func); + /* __trunc__ is specified to return an Integral type, + but long() needs to return a long. */ + int_instance = _PyNumber_ConvertIntegralToInt( + truncated, + "__trunc__ returned non-Integral (type %.200s)"); + return int_instance; + } + PyErr_Clear(); /* It's not an error if o.__trunc__ doesn't exist. */ + + if (PyBytes_Check(o)) + /* need to do extra error checking that PyLong_FromString() + * doesn't do. In particular long('9.5') must raise an + * exception, not truncate the float. + */ + return long_from_string(PyBytes_AS_STRING(o), + PyBytes_GET_SIZE(o)); + if (PyUnicode_Check(o)) + /* The above check is done in PyLong_FromUnicode(). */ + return PyLong_FromUnicode(PyUnicode_AS_UNICODE(o), + PyUnicode_GET_SIZE(o), + 10); + if (!PyObject_AsCharBuffer(o, &buffer, &buffer_len)) + return long_from_string(buffer, buffer_len); + + return type_error("int() argument must be a string or a " + "number, not '%.200s'", o); } PyObject * PyNumber_Float(PyObject *o) { - PyNumberMethods *m; + PyNumberMethods *m; - if (o == NULL) - return null_error(); - m = o->ob_type->tp_as_number; - if (m && m->nb_float) { /* This should include subclasses of float */ - PyObject *res = m->nb_float(o); - if (res && !PyFloat_Check(res)) { - PyErr_Format(PyExc_TypeError, - "__float__ returned non-float (type %.200s)", - res->ob_type->tp_name); - Py_DECREF(res); - return NULL; - } - return res; - } - if (PyFloat_Check(o)) { /* A float subclass with nb_float == NULL */ - PyFloatObject *po = (PyFloatObject *)o; - return PyFloat_FromDouble(po->ob_fval); - } - return PyFloat_FromString(o); + if (o == NULL) + return null_error(); + m = o->ob_type->tp_as_number; + if (m && m->nb_float) { /* This should include subclasses of float */ + PyObject *res = m->nb_float(o); + if (res && !PyFloat_Check(res)) { + PyErr_Format(PyExc_TypeError, + "__float__ returned non-float (type %.200s)", + res->ob_type->tp_name); + Py_DECREF(res); + return NULL; + } + return res; + } + if (PyFloat_Check(o)) { /* A float subclass with nb_float == NULL */ + PyFloatObject *po = (PyFloatObject *)o; + return PyFloat_FromDouble(po->ob_fval); + } + return PyFloat_FromString(o); } PyObject * PyNumber_ToBase(PyObject *n, int base) { - PyObject *res = NULL; - PyObject *index = PyNumber_Index(n); + PyObject *res = NULL; + PyObject *index = PyNumber_Index(n); - if (!index) - return NULL; - if (PyLong_Check(index)) - res = _PyLong_Format(index, base); - else - /* It should not be possible to get here, as - PyNumber_Index already has a check for the same - condition */ - PyErr_SetString(PyExc_ValueError, "PyNumber_ToBase: index not " - "int or long"); - Py_DECREF(index); - return res; + if (!index) + return NULL; + if (PyLong_Check(index)) + res = _PyLong_Format(index, base); + else + /* It should not be possible to get here, as + PyNumber_Index already has a check for the same + condition */ + PyErr_SetString(PyExc_ValueError, "PyNumber_ToBase: index not " + "int or long"); + Py_DECREF(index); + return res; } @@ -1453,507 +1453,507 @@ int PySequence_Check(PyObject *s) { - if (PyDict_Check(s)) - return 0; - return s != NULL && s->ob_type->tp_as_sequence && - s->ob_type->tp_as_sequence->sq_item != NULL; + if (PyDict_Check(s)) + return 0; + return s != NULL && s->ob_type->tp_as_sequence && + s->ob_type->tp_as_sequence->sq_item != NULL; } Py_ssize_t PySequence_Size(PyObject *s) { - PySequenceMethods *m; + PySequenceMethods *m; + + if (s == NULL) { + null_error(); + return -1; + } - if (s == NULL) { - null_error(); - return -1; - } - - m = s->ob_type->tp_as_sequence; - if (m && m->sq_length) - return m->sq_length(s); + m = s->ob_type->tp_as_sequence; + if (m && m->sq_length) + return m->sq_length(s); - type_error("object of type '%.200s' has no len()", s); - return -1; + type_error("object of type '%.200s' has no len()", s); + return -1; } #undef PySequence_Length Py_ssize_t PySequence_Length(PyObject *s) { - return PySequence_Size(s); + return PySequence_Size(s); } #define PySequence_Length PySequence_Size PyObject * PySequence_Concat(PyObject *s, PyObject *o) { - PySequenceMethods *m; + PySequenceMethods *m; - if (s == NULL || o == NULL) - return null_error(); + if (s == NULL || o == NULL) + return null_error(); - m = s->ob_type->tp_as_sequence; - if (m && m->sq_concat) - return m->sq_concat(s, o); - - /* Instances of user classes defining an __add__() method only - have an nb_add slot, not an sq_concat slot. So we fall back - to nb_add if both arguments appear to be sequences. */ - if (PySequence_Check(s) && PySequence_Check(o)) { - PyObject *result = binary_op1(s, o, NB_SLOT(nb_add)); - if (result != Py_NotImplemented) - return result; - Py_DECREF(result); - } - return type_error("'%.200s' object can't be concatenated", s); + m = s->ob_type->tp_as_sequence; + if (m && m->sq_concat) + return m->sq_concat(s, o); + + /* Instances of user classes defining an __add__() method only + have an nb_add slot, not an sq_concat slot. So we fall back + to nb_add if both arguments appear to be sequences. */ + if (PySequence_Check(s) && PySequence_Check(o)) { + PyObject *result = binary_op1(s, o, NB_SLOT(nb_add)); + if (result != Py_NotImplemented) + return result; + Py_DECREF(result); + } + return type_error("'%.200s' object can't be concatenated", s); } PyObject * PySequence_Repeat(PyObject *o, Py_ssize_t count) { - PySequenceMethods *m; + PySequenceMethods *m; - if (o == NULL) - return null_error(); + if (o == NULL) + return null_error(); - m = o->ob_type->tp_as_sequence; - if (m && m->sq_repeat) - return m->sq_repeat(o, count); - - /* Instances of user classes defining a __mul__() method only - have an nb_multiply slot, not an sq_repeat slot. so we fall back - to nb_multiply if o appears to be a sequence. */ - if (PySequence_Check(o)) { - PyObject *n, *result; - n = PyLong_FromSsize_t(count); - if (n == NULL) - return NULL; - result = binary_op1(o, n, NB_SLOT(nb_multiply)); - Py_DECREF(n); - if (result != Py_NotImplemented) - return result; - Py_DECREF(result); - } - return type_error("'%.200s' object can't be repeated", o); + m = o->ob_type->tp_as_sequence; + if (m && m->sq_repeat) + return m->sq_repeat(o, count); + + /* Instances of user classes defining a __mul__() method only + have an nb_multiply slot, not an sq_repeat slot. so we fall back + to nb_multiply if o appears to be a sequence. */ + if (PySequence_Check(o)) { + PyObject *n, *result; + n = PyLong_FromSsize_t(count); + if (n == NULL) + return NULL; + result = binary_op1(o, n, NB_SLOT(nb_multiply)); + Py_DECREF(n); + if (result != Py_NotImplemented) + return result; + Py_DECREF(result); + } + return type_error("'%.200s' object can't be repeated", o); } PyObject * PySequence_InPlaceConcat(PyObject *s, PyObject *o) { - PySequenceMethods *m; + PySequenceMethods *m; - if (s == NULL || o == NULL) - return null_error(); + if (s == NULL || o == NULL) + return null_error(); - m = s->ob_type->tp_as_sequence; - if (m && m->sq_inplace_concat) - return m->sq_inplace_concat(s, o); - if (m && m->sq_concat) - return m->sq_concat(s, o); - - if (PySequence_Check(s) && PySequence_Check(o)) { - PyObject *result = binary_iop1(s, o, NB_SLOT(nb_inplace_add), - NB_SLOT(nb_add)); - if (result != Py_NotImplemented) - return result; - Py_DECREF(result); - } - return type_error("'%.200s' object can't be concatenated", s); + m = s->ob_type->tp_as_sequence; + if (m && m->sq_inplace_concat) + return m->sq_inplace_concat(s, o); + if (m && m->sq_concat) + return m->sq_concat(s, o); + + if (PySequence_Check(s) && PySequence_Check(o)) { + PyObject *result = binary_iop1(s, o, NB_SLOT(nb_inplace_add), + NB_SLOT(nb_add)); + if (result != Py_NotImplemented) + return result; + Py_DECREF(result); + } + return type_error("'%.200s' object can't be concatenated", s); } PyObject * PySequence_InPlaceRepeat(PyObject *o, Py_ssize_t count) { - PySequenceMethods *m; + PySequenceMethods *m; - if (o == NULL) - return null_error(); + if (o == NULL) + return null_error(); - m = o->ob_type->tp_as_sequence; - if (m && m->sq_inplace_repeat) - return m->sq_inplace_repeat(o, count); - if (m && m->sq_repeat) - return m->sq_repeat(o, count); - - if (PySequence_Check(o)) { - PyObject *n, *result; - n = PyLong_FromSsize_t(count); - if (n == NULL) - return NULL; - result = binary_iop1(o, n, NB_SLOT(nb_inplace_multiply), - NB_SLOT(nb_multiply)); - Py_DECREF(n); - if (result != Py_NotImplemented) - return result; - Py_DECREF(result); - } - return type_error("'%.200s' object can't be repeated", o); + m = o->ob_type->tp_as_sequence; + if (m && m->sq_inplace_repeat) + return m->sq_inplace_repeat(o, count); + if (m && m->sq_repeat) + return m->sq_repeat(o, count); + + if (PySequence_Check(o)) { + PyObject *n, *result; + n = PyLong_FromSsize_t(count); + if (n == NULL) + return NULL; + result = binary_iop1(o, n, NB_SLOT(nb_inplace_multiply), + NB_SLOT(nb_multiply)); + Py_DECREF(n); + if (result != Py_NotImplemented) + return result; + Py_DECREF(result); + } + return type_error("'%.200s' object can't be repeated", o); } PyObject * PySequence_GetItem(PyObject *s, Py_ssize_t i) { - PySequenceMethods *m; + PySequenceMethods *m; - if (s == NULL) - return null_error(); + if (s == NULL) + return null_error(); - m = s->ob_type->tp_as_sequence; - if (m && m->sq_item) { - if (i < 0) { - if (m->sq_length) { - Py_ssize_t l = (*m->sq_length)(s); - if (l < 0) - return NULL; - i += l; - } - } - return m->sq_item(s, i); - } + m = s->ob_type->tp_as_sequence; + if (m && m->sq_item) { + if (i < 0) { + if (m->sq_length) { + Py_ssize_t l = (*m->sq_length)(s); + if (l < 0) + return NULL; + i += l; + } + } + return m->sq_item(s, i); + } - return type_error("'%.200s' object does not support indexing", s); + return type_error("'%.200s' object does not support indexing", s); } PyObject * PySequence_GetSlice(PyObject *s, Py_ssize_t i1, Py_ssize_t i2) { - PyMappingMethods *mp; + PyMappingMethods *mp; - if (!s) return null_error(); + if (!s) return null_error(); - mp = s->ob_type->tp_as_mapping; - if (mp->mp_subscript) { - PyObject *res; - PyObject *slice = _PySlice_FromIndices(i1, i2); - if (!slice) - return NULL; - res = mp->mp_subscript(s, slice); - Py_DECREF(slice); - return res; - } + mp = s->ob_type->tp_as_mapping; + if (mp->mp_subscript) { + PyObject *res; + PyObject *slice = _PySlice_FromIndices(i1, i2); + if (!slice) + return NULL; + res = mp->mp_subscript(s, slice); + Py_DECREF(slice); + return res; + } - return type_error("'%.200s' object is unsliceable", s); + return type_error("'%.200s' object is unsliceable", s); } int PySequence_SetItem(PyObject *s, Py_ssize_t i, PyObject *o) { - PySequenceMethods *m; + PySequenceMethods *m; + + if (s == NULL) { + null_error(); + return -1; + } - if (s == NULL) { - null_error(); - return -1; - } - - m = s->ob_type->tp_as_sequence; - if (m && m->sq_ass_item) { - if (i < 0) { - if (m->sq_length) { - Py_ssize_t l = (*m->sq_length)(s); - if (l < 0) - return -1; - i += l; - } - } - return m->sq_ass_item(s, i, o); - } + m = s->ob_type->tp_as_sequence; + if (m && m->sq_ass_item) { + if (i < 0) { + if (m->sq_length) { + Py_ssize_t l = (*m->sq_length)(s); + if (l < 0) + return -1; + i += l; + } + } + return m->sq_ass_item(s, i, o); + } - type_error("'%.200s' object does not support item assignment", s); - return -1; + type_error("'%.200s' object does not support item assignment", s); + return -1; } int PySequence_DelItem(PyObject *s, Py_ssize_t i) { - PySequenceMethods *m; + PySequenceMethods *m; - if (s == NULL) { - null_error(); - return -1; - } - - m = s->ob_type->tp_as_sequence; - if (m && m->sq_ass_item) { - if (i < 0) { - if (m->sq_length) { - Py_ssize_t l = (*m->sq_length)(s); - if (l < 0) - return -1; - i += l; - } - } - return m->sq_ass_item(s, i, (PyObject *)NULL); - } + if (s == NULL) { + null_error(); + return -1; + } - type_error("'%.200s' object doesn't support item deletion", s); - return -1; + m = s->ob_type->tp_as_sequence; + if (m && m->sq_ass_item) { + if (i < 0) { + if (m->sq_length) { + Py_ssize_t l = (*m->sq_length)(s); + if (l < 0) + return -1; + i += l; + } + } + return m->sq_ass_item(s, i, (PyObject *)NULL); + } + + type_error("'%.200s' object doesn't support item deletion", s); + return -1; } int PySequence_SetSlice(PyObject *s, Py_ssize_t i1, Py_ssize_t i2, PyObject *o) { - PyMappingMethods *mp; + PyMappingMethods *mp; + + if (s == NULL) { + null_error(); + return -1; + } - if (s == NULL) { - null_error(); - return -1; - } - - mp = s->ob_type->tp_as_mapping; - if (mp->mp_ass_subscript) { - int res; - PyObject *slice = _PySlice_FromIndices(i1, i2); - if (!slice) - return -1; - res = mp->mp_ass_subscript(s, slice, o); - Py_DECREF(slice); - return res; - } + mp = s->ob_type->tp_as_mapping; + if (mp->mp_ass_subscript) { + int res; + PyObject *slice = _PySlice_FromIndices(i1, i2); + if (!slice) + return -1; + res = mp->mp_ass_subscript(s, slice, o); + Py_DECREF(slice); + return res; + } - type_error("'%.200s' object doesn't support slice assignment", s); - return -1; + type_error("'%.200s' object doesn't support slice assignment", s); + return -1; } int PySequence_DelSlice(PyObject *s, Py_ssize_t i1, Py_ssize_t i2) { - PyMappingMethods *mp; + PyMappingMethods *mp; + + if (s == NULL) { + null_error(); + return -1; + } - if (s == NULL) { - null_error(); - return -1; - } - - mp = s->ob_type->tp_as_mapping; - if (mp->mp_ass_subscript) { - int res; - PyObject *slice = _PySlice_FromIndices(i1, i2); - if (!slice) - return -1; - res = mp->mp_ass_subscript(s, slice, NULL); - Py_DECREF(slice); - return res; - } - type_error("'%.200s' object doesn't support slice deletion", s); - return -1; + mp = s->ob_type->tp_as_mapping; + if (mp->mp_ass_subscript) { + int res; + PyObject *slice = _PySlice_FromIndices(i1, i2); + if (!slice) + return -1; + res = mp->mp_ass_subscript(s, slice, NULL); + Py_DECREF(slice); + return res; + } + type_error("'%.200s' object doesn't support slice deletion", s); + return -1; } PyObject * PySequence_Tuple(PyObject *v) { - PyObject *it; /* iter(v) */ - Py_ssize_t n; /* guess for result tuple size */ - PyObject *result = NULL; - Py_ssize_t j; - - if (v == NULL) - return null_error(); - - /* Special-case the common tuple and list cases, for efficiency. */ - if (PyTuple_CheckExact(v)) { - /* Note that we can't know whether it's safe to return - a tuple *subclass* instance as-is, hence the restriction - to exact tuples here. In contrast, lists always make - a copy, so there's no need for exactness below. */ - Py_INCREF(v); - return v; - } - if (PyList_Check(v)) - return PyList_AsTuple(v); - - /* Get iterator. */ - it = PyObject_GetIter(v); - if (it == NULL) - return NULL; - - /* Guess result size and allocate space. */ - n = _PyObject_LengthHint(v, 10); - if (n == -1) - goto Fail; - result = PyTuple_New(n); - if (result == NULL) - goto Fail; - - /* Fill the tuple. */ - for (j = 0; ; ++j) { - PyObject *item = PyIter_Next(it); - if (item == NULL) { - if (PyErr_Occurred()) - goto Fail; - break; - } - if (j >= n) { - Py_ssize_t oldn = n; - /* The over-allocation strategy can grow a bit faster - than for lists because unlike lists the - over-allocation isn't permanent -- we reclaim - the excess before the end of this routine. - So, grow by ten and then add 25%. - */ - n += 10; - n += n >> 2; - if (n < oldn) { - /* Check for overflow */ - PyErr_NoMemory(); - Py_DECREF(item); - goto Fail; - } - if (_PyTuple_Resize(&result, n) != 0) { - Py_DECREF(item); - goto Fail; - } - } - PyTuple_SET_ITEM(result, j, item); - } - - /* Cut tuple back if guess was too large. */ - if (j < n && - _PyTuple_Resize(&result, j) != 0) - goto Fail; + PyObject *it; /* iter(v) */ + Py_ssize_t n; /* guess for result tuple size */ + PyObject *result = NULL; + Py_ssize_t j; + + if (v == NULL) + return null_error(); + + /* Special-case the common tuple and list cases, for efficiency. */ + if (PyTuple_CheckExact(v)) { + /* Note that we can't know whether it's safe to return + a tuple *subclass* instance as-is, hence the restriction + to exact tuples here. In contrast, lists always make + a copy, so there's no need for exactness below. */ + Py_INCREF(v); + return v; + } + if (PyList_Check(v)) + return PyList_AsTuple(v); + + /* Get iterator. */ + it = PyObject_GetIter(v); + if (it == NULL) + return NULL; + + /* Guess result size and allocate space. */ + n = _PyObject_LengthHint(v, 10); + if (n == -1) + goto Fail; + result = PyTuple_New(n); + if (result == NULL) + goto Fail; + + /* Fill the tuple. */ + for (j = 0; ; ++j) { + PyObject *item = PyIter_Next(it); + if (item == NULL) { + if (PyErr_Occurred()) + goto Fail; + break; + } + if (j >= n) { + Py_ssize_t oldn = n; + /* The over-allocation strategy can grow a bit faster + than for lists because unlike lists the + over-allocation isn't permanent -- we reclaim + the excess before the end of this routine. + So, grow by ten and then add 25%. + */ + n += 10; + n += n >> 2; + if (n < oldn) { + /* Check for overflow */ + PyErr_NoMemory(); + Py_DECREF(item); + goto Fail; + } + if (_PyTuple_Resize(&result, n) != 0) { + Py_DECREF(item); + goto Fail; + } + } + PyTuple_SET_ITEM(result, j, item); + } - Py_DECREF(it); - return result; + /* Cut tuple back if guess was too large. */ + if (j < n && + _PyTuple_Resize(&result, j) != 0) + goto Fail; + + Py_DECREF(it); + return result; Fail: - Py_XDECREF(result); - Py_DECREF(it); - return NULL; + Py_XDECREF(result); + Py_DECREF(it); + return NULL; } PyObject * PySequence_List(PyObject *v) { - PyObject *result; /* result list */ - PyObject *rv; /* return value from PyList_Extend */ + PyObject *result; /* result list */ + PyObject *rv; /* return value from PyList_Extend */ + + if (v == NULL) + return null_error(); - if (v == NULL) - return null_error(); + result = PyList_New(0); + if (result == NULL) + return NULL; - result = PyList_New(0); - if (result == NULL) - return NULL; - - rv = _PyList_Extend((PyListObject *)result, v); - if (rv == NULL) { - Py_DECREF(result); - return NULL; - } - Py_DECREF(rv); - return result; + rv = _PyList_Extend((PyListObject *)result, v); + if (rv == NULL) { + Py_DECREF(result); + return NULL; + } + Py_DECREF(rv); + return result; } PyObject * PySequence_Fast(PyObject *v, const char *m) { - PyObject *it; + PyObject *it; - if (v == NULL) - return null_error(); + if (v == NULL) + return null_error(); + + if (PyList_CheckExact(v) || PyTuple_CheckExact(v)) { + Py_INCREF(v); + return v; + } - if (PyList_CheckExact(v) || PyTuple_CheckExact(v)) { - Py_INCREF(v); - return v; - } - - it = PyObject_GetIter(v); - if (it == NULL) { - if (PyErr_ExceptionMatches(PyExc_TypeError)) - PyErr_SetString(PyExc_TypeError, m); - return NULL; - } + it = PyObject_GetIter(v); + if (it == NULL) { + if (PyErr_ExceptionMatches(PyExc_TypeError)) + PyErr_SetString(PyExc_TypeError, m); + return NULL; + } - v = PySequence_List(it); - Py_DECREF(it); + v = PySequence_List(it); + Py_DECREF(it); - return v; + return v; } /* Iterate over seq. Result depends on the operation: - PY_ITERSEARCH_COUNT: -1 if error, else # of times obj appears in seq. - PY_ITERSEARCH_INDEX: 0-based index of first occurrence of obj in seq; - set ValueError and return -1 if none found; also return -1 on error. + PY_ITERSEARCH_COUNT: -1 if error, else # of times obj appears in seq. + PY_ITERSEARCH_INDEX: 0-based index of first occurrence of obj in seq; + set ValueError and return -1 if none found; also return -1 on error. Py_ITERSEARCH_CONTAINS: return 1 if obj in seq, else 0; -1 on error. */ Py_ssize_t _PySequence_IterSearch(PyObject *seq, PyObject *obj, int operation) { - Py_ssize_t n; - int wrapped; /* for PY_ITERSEARCH_INDEX, true iff n wrapped around */ - PyObject *it; /* iter(seq) */ - - if (seq == NULL || obj == NULL) { - null_error(); - return -1; - } - - it = PyObject_GetIter(seq); - if (it == NULL) { - type_error("argument of type '%.200s' is not iterable", seq); - return -1; - } - - n = wrapped = 0; - for (;;) { - int cmp; - PyObject *item = PyIter_Next(it); - if (item == NULL) { - if (PyErr_Occurred()) - goto Fail; - break; - } - - cmp = PyObject_RichCompareBool(obj, item, Py_EQ); - Py_DECREF(item); - if (cmp < 0) - goto Fail; - if (cmp > 0) { - switch (operation) { - case PY_ITERSEARCH_COUNT: - if (n == PY_SSIZE_T_MAX) { - PyErr_SetString(PyExc_OverflowError, - "count exceeds C integer size"); - goto Fail; - } - ++n; - break; - - case PY_ITERSEARCH_INDEX: - if (wrapped) { - PyErr_SetString(PyExc_OverflowError, - "index exceeds C integer size"); - goto Fail; - } - goto Done; - - case PY_ITERSEARCH_CONTAINS: - n = 1; - goto Done; - - default: - assert(!"unknown operation"); - } - } - - if (operation == PY_ITERSEARCH_INDEX) { - if (n == PY_SSIZE_T_MAX) - wrapped = 1; - ++n; - } - } - - if (operation != PY_ITERSEARCH_INDEX) - goto Done; - - PyErr_SetString(PyExc_ValueError, - "sequence.index(x): x not in sequence"); - /* fall into failure code */ + Py_ssize_t n; + int wrapped; /* for PY_ITERSEARCH_INDEX, true iff n wrapped around */ + PyObject *it; /* iter(seq) */ + + if (seq == NULL || obj == NULL) { + null_error(); + return -1; + } + + it = PyObject_GetIter(seq); + if (it == NULL) { + type_error("argument of type '%.200s' is not iterable", seq); + return -1; + } + + n = wrapped = 0; + for (;;) { + int cmp; + PyObject *item = PyIter_Next(it); + if (item == NULL) { + if (PyErr_Occurred()) + goto Fail; + break; + } + + cmp = PyObject_RichCompareBool(obj, item, Py_EQ); + Py_DECREF(item); + if (cmp < 0) + goto Fail; + if (cmp > 0) { + switch (operation) { + case PY_ITERSEARCH_COUNT: + if (n == PY_SSIZE_T_MAX) { + PyErr_SetString(PyExc_OverflowError, + "count exceeds C integer size"); + goto Fail; + } + ++n; + break; + + case PY_ITERSEARCH_INDEX: + if (wrapped) { + PyErr_SetString(PyExc_OverflowError, + "index exceeds C integer size"); + goto Fail; + } + goto Done; + + case PY_ITERSEARCH_CONTAINS: + n = 1; + goto Done; + + default: + assert(!"unknown operation"); + } + } + + if (operation == PY_ITERSEARCH_INDEX) { + if (n == PY_SSIZE_T_MAX) + wrapped = 1; + ++n; + } + } + + if (operation != PY_ITERSEARCH_INDEX) + goto Done; + + PyErr_SetString(PyExc_ValueError, + "sequence.index(x): x not in sequence"); + /* fall into failure code */ Fail: - n = -1; - /* fall through */ + n = -1; + /* fall through */ Done: - Py_DECREF(it); - return n; + Py_DECREF(it); + return n; } @@ -1961,7 +1961,7 @@ Py_ssize_t PySequence_Count(PyObject *s, PyObject *o) { - return _PySequence_IterSearch(s, o, PY_ITERSEARCH_COUNT); + return _PySequence_IterSearch(s, o, PY_ITERSEARCH_COUNT); } /* Return -1 if error; 1 if ob in seq; 0 if ob not in seq. @@ -1970,12 +1970,12 @@ int PySequence_Contains(PyObject *seq, PyObject *ob) { - Py_ssize_t result; - PySequenceMethods *sqm = seq->ob_type->tp_as_sequence; - if (sqm != NULL && sqm->sq_contains != NULL) - return (*sqm->sq_contains)(seq, ob); - result = _PySequence_IterSearch(seq, ob, PY_ITERSEARCH_CONTAINS); - return Py_SAFE_DOWNCAST(result, Py_ssize_t, int); + Py_ssize_t result; + PySequenceMethods *sqm = seq->ob_type->tp_as_sequence; + if (sqm != NULL && sqm->sq_contains != NULL) + return (*sqm->sq_contains)(seq, ob); + result = _PySequence_IterSearch(seq, ob, PY_ITERSEARCH_CONTAINS); + return Py_SAFE_DOWNCAST(result, Py_ssize_t, int); } /* Backwards compatibility */ @@ -1983,13 +1983,13 @@ int PySequence_In(PyObject *w, PyObject *v) { - return PySequence_Contains(w, v); + return PySequence_Contains(w, v); } Py_ssize_t PySequence_Index(PyObject *s, PyObject *o) { - return _PySequence_IterSearch(s, o, PY_ITERSEARCH_INDEX); + return _PySequence_IterSearch(s, o, PY_ITERSEARCH_INDEX); } /* Operations on mappings */ @@ -1997,145 +1997,145 @@ int PyMapping_Check(PyObject *o) { - return o && o->ob_type->tp_as_mapping && - o->ob_type->tp_as_mapping->mp_subscript; + return o && o->ob_type->tp_as_mapping && + o->ob_type->tp_as_mapping->mp_subscript; } Py_ssize_t PyMapping_Size(PyObject *o) { - PyMappingMethods *m; + PyMappingMethods *m; - if (o == NULL) { - null_error(); - return -1; - } - - m = o->ob_type->tp_as_mapping; - if (m && m->mp_length) - return m->mp_length(o); + if (o == NULL) { + null_error(); + return -1; + } + + m = o->ob_type->tp_as_mapping; + if (m && m->mp_length) + return m->mp_length(o); - type_error("object of type '%.200s' has no len()", o); - return -1; + type_error("object of type '%.200s' has no len()", o); + return -1; } #undef PyMapping_Length Py_ssize_t PyMapping_Length(PyObject *o) { - return PyMapping_Size(o); + return PyMapping_Size(o); } #define PyMapping_Length PyMapping_Size PyObject * PyMapping_GetItemString(PyObject *o, char *key) { - PyObject *okey, *r; + PyObject *okey, *r; - if (key == NULL) - return null_error(); + if (key == NULL) + return null_error(); - okey = PyUnicode_FromString(key); - if (okey == NULL) - return NULL; - r = PyObject_GetItem(o, okey); - Py_DECREF(okey); - return r; + okey = PyUnicode_FromString(key); + if (okey == NULL) + return NULL; + r = PyObject_GetItem(o, okey); + Py_DECREF(okey); + return r; } int PyMapping_SetItemString(PyObject *o, char *key, PyObject *value) { - PyObject *okey; - int r; + PyObject *okey; + int r; - if (key == NULL) { - null_error(); - return -1; - } - - okey = PyUnicode_FromString(key); - if (okey == NULL) - return -1; - r = PyObject_SetItem(o, okey, value); - Py_DECREF(okey); - return r; + if (key == NULL) { + null_error(); + return -1; + } + + okey = PyUnicode_FromString(key); + if (okey == NULL) + return -1; + r = PyObject_SetItem(o, okey, value); + Py_DECREF(okey); + return r; } int PyMapping_HasKeyString(PyObject *o, char *key) { - PyObject *v; + PyObject *v; - v = PyMapping_GetItemString(o, key); - if (v) { - Py_DECREF(v); - return 1; - } - PyErr_Clear(); - return 0; + v = PyMapping_GetItemString(o, key); + if (v) { + Py_DECREF(v); + return 1; + } + PyErr_Clear(); + return 0; } int PyMapping_HasKey(PyObject *o, PyObject *key) { - PyObject *v; + PyObject *v; - v = PyObject_GetItem(o, key); - if (v) { - Py_DECREF(v); - return 1; - } - PyErr_Clear(); - return 0; + v = PyObject_GetItem(o, key); + if (v) { + Py_DECREF(v); + return 1; + } + PyErr_Clear(); + return 0; } PyObject * PyMapping_Keys(PyObject *o) { - PyObject *keys; - PyObject *fast; + PyObject *keys; + PyObject *fast; - if (PyDict_CheckExact(o)) - return PyDict_Keys(o); - keys = PyObject_CallMethod(o, "keys", NULL); - if (keys == NULL) - return NULL; - fast = PySequence_Fast(keys, "o.keys() are not iterable"); - Py_DECREF(keys); - return fast; + if (PyDict_CheckExact(o)) + return PyDict_Keys(o); + keys = PyObject_CallMethod(o, "keys", NULL); + if (keys == NULL) + return NULL; + fast = PySequence_Fast(keys, "o.keys() are not iterable"); + Py_DECREF(keys); + return fast; } PyObject * PyMapping_Items(PyObject *o) { - PyObject *items; - PyObject *fast; + PyObject *items; + PyObject *fast; - if (PyDict_CheckExact(o)) - return PyDict_Items(o); - items = PyObject_CallMethod(o, "items", NULL); - if (items == NULL) - return NULL; - fast = PySequence_Fast(items, "o.items() are not iterable"); - Py_DECREF(items); - return fast; + if (PyDict_CheckExact(o)) + return PyDict_Items(o); + items = PyObject_CallMethod(o, "items", NULL); + if (items == NULL) + return NULL; + fast = PySequence_Fast(items, "o.items() are not iterable"); + Py_DECREF(items); + return fast; } PyObject * PyMapping_Values(PyObject *o) { - PyObject *values; - PyObject *fast; + PyObject *values; + PyObject *fast; - if (PyDict_CheckExact(o)) - return PyDict_Values(o); - values = PyObject_CallMethod(o, "values", NULL); - if (values == NULL) - return NULL; - fast = PySequence_Fast(values, "o.values() are not iterable"); - Py_DECREF(values); - return fast; + if (PyDict_CheckExact(o)) + return PyDict_Values(o); + values = PyObject_CallMethod(o, "values", NULL); + if (values == NULL) + return NULL; + fast = PySequence_Fast(values, "o.values() are not iterable"); + Py_DECREF(values); + return fast; } /* Operations on callable objects */ @@ -2145,253 +2145,253 @@ PyObject * PyObject_CallObject(PyObject *o, PyObject *a) { - return PyEval_CallObjectWithKeywords(o, a, NULL); + return PyEval_CallObjectWithKeywords(o, a, NULL); } PyObject * PyObject_Call(PyObject *func, PyObject *arg, PyObject *kw) { - ternaryfunc call; + ternaryfunc call; - if ((call = func->ob_type->tp_call) != NULL) { - PyObject *result; - if (Py_EnterRecursiveCall(" while calling a Python object")) - return NULL; - result = (*call)(func, arg, kw); - Py_LeaveRecursiveCall(); - if (result == NULL && !PyErr_Occurred()) - PyErr_SetString( - PyExc_SystemError, - "NULL result without error in PyObject_Call"); - return result; - } - PyErr_Format(PyExc_TypeError, "'%.200s' object is not callable", - func->ob_type->tp_name); - return NULL; + if ((call = func->ob_type->tp_call) != NULL) { + PyObject *result; + if (Py_EnterRecursiveCall(" while calling a Python object")) + return NULL; + result = (*call)(func, arg, kw); + Py_LeaveRecursiveCall(); + if (result == NULL && !PyErr_Occurred()) + PyErr_SetString( + PyExc_SystemError, + "NULL result without error in PyObject_Call"); + return result; + } + PyErr_Format(PyExc_TypeError, "'%.200s' object is not callable", + func->ob_type->tp_name); + return NULL; } static PyObject* call_function_tail(PyObject *callable, PyObject *args) { - PyObject *retval; + PyObject *retval; - if (args == NULL) - return NULL; + if (args == NULL) + return NULL; - if (!PyTuple_Check(args)) { - PyObject *a; + if (!PyTuple_Check(args)) { + PyObject *a; - a = PyTuple_New(1); - if (a == NULL) { - Py_DECREF(args); - return NULL; - } - PyTuple_SET_ITEM(a, 0, args); - args = a; - } - retval = PyObject_Call(callable, args, NULL); + a = PyTuple_New(1); + if (a == NULL) { + Py_DECREF(args); + return NULL; + } + PyTuple_SET_ITEM(a, 0, args); + args = a; + } + retval = PyObject_Call(callable, args, NULL); - Py_DECREF(args); + Py_DECREF(args); - return retval; + return retval; } PyObject * PyObject_CallFunction(PyObject *callable, char *format, ...) { - va_list va; - PyObject *args; + va_list va; + PyObject *args; - if (callable == NULL) - return null_error(); + if (callable == NULL) + return null_error(); - if (format && *format) { - va_start(va, format); - args = Py_VaBuildValue(format, va); - va_end(va); - } - else - args = PyTuple_New(0); + if (format && *format) { + va_start(va, format); + args = Py_VaBuildValue(format, va); + va_end(va); + } + else + args = PyTuple_New(0); - return call_function_tail(callable, args); + return call_function_tail(callable, args); } PyObject * _PyObject_CallFunction_SizeT(PyObject *callable, char *format, ...) { - va_list va; - PyObject *args; + va_list va; + PyObject *args; - if (callable == NULL) - return null_error(); + if (callable == NULL) + return null_error(); - if (format && *format) { - va_start(va, format); - args = _Py_VaBuildValue_SizeT(format, va); - va_end(va); - } - else - args = PyTuple_New(0); + if (format && *format) { + va_start(va, format); + args = _Py_VaBuildValue_SizeT(format, va); + va_end(va); + } + else + args = PyTuple_New(0); - return call_function_tail(callable, args); + return call_function_tail(callable, args); } PyObject * PyObject_CallMethod(PyObject *o, char *name, char *format, ...) { - va_list va; - PyObject *args; - PyObject *func = NULL; - PyObject *retval = NULL; - - if (o == NULL || name == NULL) - return null_error(); - - func = PyObject_GetAttrString(o, name); - if (func == NULL) { - PyErr_SetString(PyExc_AttributeError, name); - return 0; - } - - if (!PyCallable_Check(func)) { - type_error("attribute of type '%.200s' is not callable", func); - goto exit; - } - - if (format && *format) { - va_start(va, format); - args = Py_VaBuildValue(format, va); - va_end(va); - } - else - args = PyTuple_New(0); + va_list va; + PyObject *args; + PyObject *func = NULL; + PyObject *retval = NULL; + + if (o == NULL || name == NULL) + return null_error(); + + func = PyObject_GetAttrString(o, name); + if (func == NULL) { + PyErr_SetString(PyExc_AttributeError, name); + return 0; + } + + if (!PyCallable_Check(func)) { + type_error("attribute of type '%.200s' is not callable", func); + goto exit; + } - retval = call_function_tail(func, args); + if (format && *format) { + va_start(va, format); + args = Py_VaBuildValue(format, va); + va_end(va); + } + else + args = PyTuple_New(0); + + retval = call_function_tail(func, args); exit: - /* args gets consumed in call_function_tail */ - Py_XDECREF(func); + /* args gets consumed in call_function_tail */ + Py_XDECREF(func); - return retval; + return retval; } PyObject * _PyObject_CallMethod_SizeT(PyObject *o, char *name, char *format, ...) { - va_list va; - PyObject *args; - PyObject *func = NULL; - PyObject *retval = NULL; - - if (o == NULL || name == NULL) - return null_error(); - - func = PyObject_GetAttrString(o, name); - if (func == NULL) { - PyErr_SetString(PyExc_AttributeError, name); - return 0; - } - - if (!PyCallable_Check(func)) { - type_error("attribute of type '%.200s' is not callable", func); - goto exit; - } - - if (format && *format) { - va_start(va, format); - args = _Py_VaBuildValue_SizeT(format, va); - va_end(va); - } - else - args = PyTuple_New(0); + va_list va; + PyObject *args; + PyObject *func = NULL; + PyObject *retval = NULL; + + if (o == NULL || name == NULL) + return null_error(); + + func = PyObject_GetAttrString(o, name); + if (func == NULL) { + PyErr_SetString(PyExc_AttributeError, name); + return 0; + } - retval = call_function_tail(func, args); + if (!PyCallable_Check(func)) { + type_error("attribute of type '%.200s' is not callable", func); + goto exit; + } + + if (format && *format) { + va_start(va, format); + args = _Py_VaBuildValue_SizeT(format, va); + va_end(va); + } + else + args = PyTuple_New(0); + + retval = call_function_tail(func, args); exit: - /* args gets consumed in call_function_tail */ - Py_XDECREF(func); + /* args gets consumed in call_function_tail */ + Py_XDECREF(func); - return retval; + return retval; } static PyObject * objargs_mktuple(va_list va) { - int i, n = 0; - va_list countva; - PyObject *result, *tmp; + int i, n = 0; + va_list countva; + PyObject *result, *tmp; #ifdef VA_LIST_IS_ARRAY - memcpy(countva, va, sizeof(va_list)); + memcpy(countva, va, sizeof(va_list)); #else #ifdef __va_copy - __va_copy(countva, va); + __va_copy(countva, va); #else - countva = va; + countva = va; #endif #endif - while (((PyObject *)va_arg(countva, PyObject *)) != NULL) - ++n; - result = PyTuple_New(n); - if (result != NULL && n > 0) { - for (i = 0; i < n; ++i) { - tmp = (PyObject *)va_arg(va, PyObject *); - PyTuple_SET_ITEM(result, i, tmp); - Py_INCREF(tmp); - } - } - return result; + while (((PyObject *)va_arg(countva, PyObject *)) != NULL) + ++n; + result = PyTuple_New(n); + if (result != NULL && n > 0) { + for (i = 0; i < n; ++i) { + tmp = (PyObject *)va_arg(va, PyObject *); + PyTuple_SET_ITEM(result, i, tmp); + Py_INCREF(tmp); + } + } + return result; } PyObject * PyObject_CallMethodObjArgs(PyObject *callable, PyObject *name, ...) { - PyObject *args, *tmp; - va_list vargs; + PyObject *args, *tmp; + va_list vargs; - if (callable == NULL || name == NULL) - return null_error(); + if (callable == NULL || name == NULL) + return null_error(); - callable = PyObject_GetAttr(callable, name); - if (callable == NULL) - return NULL; - - /* count the args */ - va_start(vargs, name); - args = objargs_mktuple(vargs); - va_end(vargs); - if (args == NULL) { - Py_DECREF(callable); - return NULL; - } - tmp = PyObject_Call(callable, args, NULL); - Py_DECREF(args); - Py_DECREF(callable); + callable = PyObject_GetAttr(callable, name); + if (callable == NULL) + return NULL; + + /* count the args */ + va_start(vargs, name); + args = objargs_mktuple(vargs); + va_end(vargs); + if (args == NULL) { + Py_DECREF(callable); + return NULL; + } + tmp = PyObject_Call(callable, args, NULL); + Py_DECREF(args); + Py_DECREF(callable); - return tmp; + return tmp; } PyObject * PyObject_CallFunctionObjArgs(PyObject *callable, ...) { - PyObject *args, *tmp; - va_list vargs; + PyObject *args, *tmp; + va_list vargs; - if (callable == NULL) - return null_error(); + if (callable == NULL) + return null_error(); - /* count the args */ - va_start(vargs, callable); - args = objargs_mktuple(vargs); - va_end(vargs); - if (args == NULL) - return NULL; - tmp = PyObject_Call(callable, args, NULL); - Py_DECREF(args); + /* count the args */ + va_start(vargs, callable); + args = objargs_mktuple(vargs); + va_end(vargs); + if (args == NULL) + return NULL; + tmp = PyObject_Call(callable, args, NULL); + Py_DECREF(args); - return tmp; + return tmp; } @@ -2415,7 +2415,7 @@ * produce exactly the same results: NULL is returned and no error is set. * * If some exception other than AttributeError is raised, then NULL is also - * returned, but the exception is not cleared. That's because we want the + * returned, but the exception is not cleared. That's because we want the * exception to be propagated along. * * Callers are expected to test for PyErr_Occurred() when the return value @@ -2426,282 +2426,282 @@ static PyObject * abstract_get_bases(PyObject *cls) { - static PyObject *__bases__ = NULL; - PyObject *bases; + static PyObject *__bases__ = NULL; + PyObject *bases; - if (__bases__ == NULL) { - __bases__ = PyUnicode_InternFromString("__bases__"); - if (__bases__ == NULL) - return NULL; - } - Py_ALLOW_RECURSION - bases = PyObject_GetAttr(cls, __bases__); - Py_END_ALLOW_RECURSION - if (bases == NULL) { - if (PyErr_ExceptionMatches(PyExc_AttributeError)) - PyErr_Clear(); - return NULL; - } - if (!PyTuple_Check(bases)) { - Py_DECREF(bases); - return NULL; - } - return bases; + if (__bases__ == NULL) { + __bases__ = PyUnicode_InternFromString("__bases__"); + if (__bases__ == NULL) + return NULL; + } + Py_ALLOW_RECURSION + bases = PyObject_GetAttr(cls, __bases__); + Py_END_ALLOW_RECURSION + if (bases == NULL) { + if (PyErr_ExceptionMatches(PyExc_AttributeError)) + PyErr_Clear(); + return NULL; + } + if (!PyTuple_Check(bases)) { + Py_DECREF(bases); + return NULL; + } + return bases; } static int abstract_issubclass(PyObject *derived, PyObject *cls) { - PyObject *bases = NULL; - Py_ssize_t i, n; - int r = 0; - - while (1) { - if (derived == cls) - return 1; - bases = abstract_get_bases(derived); - if (bases == NULL) { - if (PyErr_Occurred()) - return -1; - return 0; - } - n = PyTuple_GET_SIZE(bases); - if (n == 0) { - Py_DECREF(bases); - return 0; - } - /* Avoid recursivity in the single inheritance case */ - if (n == 1) { - derived = PyTuple_GET_ITEM(bases, 0); - Py_DECREF(bases); - continue; - } - for (i = 0; i < n; i++) { - r = abstract_issubclass(PyTuple_GET_ITEM(bases, i), cls); - if (r != 0) - break; - } - Py_DECREF(bases); - return r; - } + PyObject *bases = NULL; + Py_ssize_t i, n; + int r = 0; + + while (1) { + if (derived == cls) + return 1; + bases = abstract_get_bases(derived); + if (bases == NULL) { + if (PyErr_Occurred()) + return -1; + return 0; + } + n = PyTuple_GET_SIZE(bases); + if (n == 0) { + Py_DECREF(bases); + return 0; + } + /* Avoid recursivity in the single inheritance case */ + if (n == 1) { + derived = PyTuple_GET_ITEM(bases, 0); + Py_DECREF(bases); + continue; + } + for (i = 0; i < n; i++) { + r = abstract_issubclass(PyTuple_GET_ITEM(bases, i), cls); + if (r != 0) + break; + } + Py_DECREF(bases); + return r; + } } static int check_class(PyObject *cls, const char *error) { - PyObject *bases = abstract_get_bases(cls); - if (bases == NULL) { - /* Do not mask errors. */ - if (!PyErr_Occurred()) - PyErr_SetString(PyExc_TypeError, error); - return 0; - } - Py_DECREF(bases); - return -1; + PyObject *bases = abstract_get_bases(cls); + if (bases == NULL) { + /* Do not mask errors. */ + if (!PyErr_Occurred()) + PyErr_SetString(PyExc_TypeError, error); + return 0; + } + Py_DECREF(bases); + return -1; } static int recursive_isinstance(PyObject *inst, PyObject *cls) { - PyObject *icls; - static PyObject *__class__ = NULL; - int retval = 0; - - if (__class__ == NULL) { - __class__ = PyUnicode_InternFromString("__class__"); - if (__class__ == NULL) - return -1; - } - - if (PyType_Check(cls)) { - retval = PyObject_TypeCheck(inst, (PyTypeObject *)cls); - if (retval == 0) { - PyObject *c = PyObject_GetAttr(inst, __class__); - if (c == NULL) { - PyErr_Clear(); - } - else { - if (c != (PyObject *)(inst->ob_type) && - PyType_Check(c)) - retval = PyType_IsSubtype( - (PyTypeObject *)c, - (PyTypeObject *)cls); - Py_DECREF(c); - } - } - } - else { - if (!check_class(cls, - "isinstance() arg 2 must be a class, type," - " or tuple of classes and types")) - return -1; - icls = PyObject_GetAttr(inst, __class__); - if (icls == NULL) { - PyErr_Clear(); - retval = 0; - } - else { - retval = abstract_issubclass(icls, cls); - Py_DECREF(icls); - } - } + PyObject *icls; + static PyObject *__class__ = NULL; + int retval = 0; + + if (__class__ == NULL) { + __class__ = PyUnicode_InternFromString("__class__"); + if (__class__ == NULL) + return -1; + } + + if (PyType_Check(cls)) { + retval = PyObject_TypeCheck(inst, (PyTypeObject *)cls); + if (retval == 0) { + PyObject *c = PyObject_GetAttr(inst, __class__); + if (c == NULL) { + PyErr_Clear(); + } + else { + if (c != (PyObject *)(inst->ob_type) && + PyType_Check(c)) + retval = PyType_IsSubtype( + (PyTypeObject *)c, + (PyTypeObject *)cls); + Py_DECREF(c); + } + } + } + else { + if (!check_class(cls, + "isinstance() arg 2 must be a class, type," + " or tuple of classes and types")) + return -1; + icls = PyObject_GetAttr(inst, __class__); + if (icls == NULL) { + PyErr_Clear(); + retval = 0; + } + else { + retval = abstract_issubclass(icls, cls); + Py_DECREF(icls); + } + } - return retval; + return retval; } int PyObject_IsInstance(PyObject *inst, PyObject *cls) { - static PyObject *name = NULL; - PyObject *checker; + static PyObject *name = NULL; + PyObject *checker; + + /* Quick test for an exact match */ + if (Py_TYPE(inst) == (PyTypeObject *)cls) + return 1; + + if (PyTuple_Check(cls)) { + Py_ssize_t i; + Py_ssize_t n; + int r = 0; + + if (Py_EnterRecursiveCall(" in __instancecheck__")) + return -1; + n = PyTuple_GET_SIZE(cls); + for (i = 0; i < n; ++i) { + PyObject *item = PyTuple_GET_ITEM(cls, i); + r = PyObject_IsInstance(inst, item); + if (r != 0) + /* either found it, or got an error */ + break; + } + Py_LeaveRecursiveCall(); + return r; + } - /* Quick test for an exact match */ - if (Py_TYPE(inst) == (PyTypeObject *)cls) - return 1; - - if (PyTuple_Check(cls)) { - Py_ssize_t i; - Py_ssize_t n; - int r = 0; - - if (Py_EnterRecursiveCall(" in __instancecheck__")) - return -1; - n = PyTuple_GET_SIZE(cls); - for (i = 0; i < n; ++i) { - PyObject *item = PyTuple_GET_ITEM(cls, i); - r = PyObject_IsInstance(inst, item); - if (r != 0) - /* either found it, or got an error */ - break; - } - Py_LeaveRecursiveCall(); - return r; - } - - checker = _PyObject_LookupSpecial(cls, "__instancecheck__", &name); - if (checker != NULL) { - PyObject *res; - int ok = -1; - if (Py_EnterRecursiveCall(" in __instancecheck__")) { - Py_DECREF(checker); - return ok; - } - res = PyObject_CallFunctionObjArgs(checker, inst, NULL); - Py_LeaveRecursiveCall(); - Py_DECREF(checker); - if (res != NULL) { - ok = PyObject_IsTrue(res); - Py_DECREF(res); - } - return ok; - } - else if (PyErr_Occurred()) - return -1; - return recursive_isinstance(inst, cls); + checker = _PyObject_LookupSpecial(cls, "__instancecheck__", &name); + if (checker != NULL) { + PyObject *res; + int ok = -1; + if (Py_EnterRecursiveCall(" in __instancecheck__")) { + Py_DECREF(checker); + return ok; + } + res = PyObject_CallFunctionObjArgs(checker, inst, NULL); + Py_LeaveRecursiveCall(); + Py_DECREF(checker); + if (res != NULL) { + ok = PyObject_IsTrue(res); + Py_DECREF(res); + } + return ok; + } + else if (PyErr_Occurred()) + return -1; + return recursive_isinstance(inst, cls); } -static int +static int recursive_issubclass(PyObject *derived, PyObject *cls) { - if (PyType_Check(cls) && PyType_Check(derived)) { - /* Fast path (non-recursive) */ - return PyType_IsSubtype((PyTypeObject *)derived, (PyTypeObject *)cls); - } - if (!check_class(derived, - "issubclass() arg 1 must be a class")) - return -1; - if (!check_class(cls, - "issubclass() arg 2 must be a class" - " or tuple of classes")) - return -1; + if (PyType_Check(cls) && PyType_Check(derived)) { + /* Fast path (non-recursive) */ + return PyType_IsSubtype((PyTypeObject *)derived, (PyTypeObject *)cls); + } + if (!check_class(derived, + "issubclass() arg 1 must be a class")) + return -1; + if (!check_class(cls, + "issubclass() arg 2 must be a class" + " or tuple of classes")) + return -1; - return abstract_issubclass(derived, cls); + return abstract_issubclass(derived, cls); } int PyObject_IsSubclass(PyObject *derived, PyObject *cls) { - static PyObject *name = NULL; - PyObject *checker; + static PyObject *name = NULL; + PyObject *checker; + + if (PyTuple_Check(cls)) { + Py_ssize_t i; + Py_ssize_t n; + int r = 0; + + if (Py_EnterRecursiveCall(" in __subclasscheck__")) + return -1; + n = PyTuple_GET_SIZE(cls); + for (i = 0; i < n; ++i) { + PyObject *item = PyTuple_GET_ITEM(cls, i); + r = PyObject_IsSubclass(derived, item); + if (r != 0) + /* either found it, or got an error */ + break; + } + Py_LeaveRecursiveCall(); + return r; + } - if (PyTuple_Check(cls)) { - Py_ssize_t i; - Py_ssize_t n; - int r = 0; - - if (Py_EnterRecursiveCall(" in __subclasscheck__")) - return -1; - n = PyTuple_GET_SIZE(cls); - for (i = 0; i < n; ++i) { - PyObject *item = PyTuple_GET_ITEM(cls, i); - r = PyObject_IsSubclass(derived, item); - if (r != 0) - /* either found it, or got an error */ - break; - } - Py_LeaveRecursiveCall(); - return r; - } - - checker = _PyObject_LookupSpecial(cls, "__subclasscheck__", &name); - if (checker != NULL) { - PyObject *res; - int ok = -1; - if (Py_EnterRecursiveCall(" in __subclasscheck__")) { - Py_DECREF(checker); - return ok; - } - res = PyObject_CallFunctionObjArgs(checker, derived, NULL); - Py_LeaveRecursiveCall(); - Py_DECREF(checker); - if (res != NULL) { - ok = PyObject_IsTrue(res); - Py_DECREF(res); - } - return ok; - } - else if (PyErr_Occurred()) - return -1; - return recursive_issubclass(derived, cls); + checker = _PyObject_LookupSpecial(cls, "__subclasscheck__", &name); + if (checker != NULL) { + PyObject *res; + int ok = -1; + if (Py_EnterRecursiveCall(" in __subclasscheck__")) { + Py_DECREF(checker); + return ok; + } + res = PyObject_CallFunctionObjArgs(checker, derived, NULL); + Py_LeaveRecursiveCall(); + Py_DECREF(checker); + if (res != NULL) { + ok = PyObject_IsTrue(res); + Py_DECREF(res); + } + return ok; + } + else if (PyErr_Occurred()) + return -1; + return recursive_issubclass(derived, cls); } int _PyObject_RealIsInstance(PyObject *inst, PyObject *cls) { - return recursive_isinstance(inst, cls); + return recursive_isinstance(inst, cls); } int _PyObject_RealIsSubclass(PyObject *derived, PyObject *cls) { - return recursive_issubclass(derived, cls); + return recursive_issubclass(derived, cls); } PyObject * PyObject_GetIter(PyObject *o) { - PyTypeObject *t = o->ob_type; - getiterfunc f = NULL; - f = t->tp_iter; - if (f == NULL) { - if (PySequence_Check(o)) - return PySeqIter_New(o); - return type_error("'%.200s' object is not iterable", o); - } - else { - PyObject *res = (*f)(o); - if (res != NULL && !PyIter_Check(res)) { - PyErr_Format(PyExc_TypeError, - "iter() returned non-iterator " - "of type '%.100s'", - res->ob_type->tp_name); - Py_DECREF(res); - res = NULL; - } - return res; - } + PyTypeObject *t = o->ob_type; + getiterfunc f = NULL; + f = t->tp_iter; + if (f == NULL) { + if (PySequence_Check(o)) + return PySeqIter_New(o); + return type_error("'%.200s' object is not iterable", o); + } + else { + PyObject *res = (*f)(o); + if (res != NULL && !PyIter_Check(res)) { + PyErr_Format(PyExc_TypeError, + "iter() returned non-iterator " + "of type '%.100s'", + res->ob_type->tp_name); + Py_DECREF(res); + res = NULL; + } + return res; + } } /* Return next item. @@ -2709,18 +2709,18 @@ * If the iteration terminates normally, return NULL and clear the * PyExc_StopIteration exception (if it was set). PyErr_Occurred() * will be false. - * Else return the next object. PyErr_Occurred() will be false. + * Else return the next object. PyErr_Occurred() will be false. */ PyObject * PyIter_Next(PyObject *iter) { - PyObject *result; - result = (*iter->ob_type->tp_iternext)(iter); - if (result == NULL && - PyErr_Occurred() && - PyErr_ExceptionMatches(PyExc_StopIteration)) - PyErr_Clear(); - return result; + PyObject *result; + result = (*iter->ob_type->tp_iternext)(iter); + if (result == NULL && + PyErr_Occurred() && + PyErr_ExceptionMatches(PyExc_StopIteration)) + PyErr_Clear(); + return result; } @@ -2735,43 +2735,43 @@ char *const * _PySequence_BytesToCharpArray(PyObject* self) { - char **array; - Py_ssize_t i, argc; - PyObject *item = NULL; - - argc = PySequence_Size(self); - if (argc == -1) - return NULL; - - array = malloc((argc + 1) * sizeof(char *)); - if (array == NULL) { - PyErr_NoMemory(); - return NULL; - } - for (i = 0; i < argc; ++i) { - char *data; - item = PySequence_GetItem(self, i); - data = PyBytes_AsString(item); - if (data == NULL) { - /* NULL terminate before freeing. */ - array[i] = NULL; - goto fail; - } - array[i] = strdup(data); - if (!array[i]) { - PyErr_NoMemory(); - goto fail; - } - Py_DECREF(item); - } - array[argc] = NULL; + char **array; + Py_ssize_t i, argc; + PyObject *item = NULL; + + argc = PySequence_Size(self); + if (argc == -1) + return NULL; + + array = malloc((argc + 1) * sizeof(char *)); + if (array == NULL) { + PyErr_NoMemory(); + return NULL; + } + for (i = 0; i < argc; ++i) { + char *data; + item = PySequence_GetItem(self, i); + data = PyBytes_AsString(item); + if (data == NULL) { + /* NULL terminate before freeing. */ + array[i] = NULL; + goto fail; + } + array[i] = strdup(data); + if (!array[i]) { + PyErr_NoMemory(); + goto fail; + } + Py_DECREF(item); + } + array[argc] = NULL; - return array; + return array; fail: - Py_XDECREF(item); - _Py_FreeCharPArray(array); - return NULL; + Py_XDECREF(item); + _Py_FreeCharPArray(array); + return NULL; } @@ -2779,9 +2779,9 @@ void _Py_FreeCharPArray(char *const array[]) { - Py_ssize_t i; - for (i = 0; array[i] != NULL; ++i) { - free(array[i]); - } - free((void*)array); + Py_ssize_t i; + for (i = 0; array[i] != NULL; ++i) { + free(array[i]); + } + free((void*)array); } Modified: python/branches/py3k/Objects/boolobject.c ============================================================================== --- python/branches/py3k/Objects/boolobject.c (original) +++ python/branches/py3k/Objects/boolobject.c Sun May 9 17:52:27 2010 @@ -11,30 +11,30 @@ static PyObject * bool_repr(PyObject *self) { - PyObject *s; + PyObject *s; - if (self == Py_True) - s = true_str ? true_str : - (true_str = PyUnicode_InternFromString("True")); - else - s = false_str ? false_str : - (false_str = PyUnicode_InternFromString("False")); - Py_XINCREF(s); - return s; + if (self == Py_True) + s = true_str ? true_str : + (true_str = PyUnicode_InternFromString("True")); + else + s = false_str ? false_str : + (false_str = PyUnicode_InternFromString("False")); + Py_XINCREF(s); + return s; } /* Function to return a bool from a C long */ PyObject *PyBool_FromLong(long ok) { - PyObject *result; + PyObject *result; - if (ok) - result = Py_True; - else - result = Py_False; - Py_INCREF(result); - return result; + if (ok) + result = Py_True; + else + result = Py_False; + Py_INCREF(result); + return result; } /* We define bool_new to always return either Py_True or Py_False */ @@ -42,16 +42,16 @@ static PyObject * bool_new(PyTypeObject *type, PyObject *args, PyObject *kwds) { - static char *kwlist[] = {"x", 0}; - PyObject *x = Py_False; - long ok; - - if (!PyArg_ParseTupleAndKeywords(args, kwds, "|O:bool", kwlist, &x)) - return NULL; - ok = PyObject_IsTrue(x); - if (ok < 0) - return NULL; - return PyBool_FromLong(ok); + static char *kwlist[] = {"x", 0}; + PyObject *x = Py_False; + long ok; + + if (!PyArg_ParseTupleAndKeywords(args, kwds, "|O:bool", kwlist, &x)) + return NULL; + ok = PyObject_IsTrue(x); + if (ok < 0) + return NULL; + return PyBool_FromLong(ok); } /* Arithmetic operations redefined to return bool if both args are bool. */ @@ -59,25 +59,25 @@ static PyObject * bool_and(PyObject *a, PyObject *b) { - if (!PyBool_Check(a) || !PyBool_Check(b)) - return PyLong_Type.tp_as_number->nb_and(a, b); - return PyBool_FromLong((a == Py_True) & (b == Py_True)); + if (!PyBool_Check(a) || !PyBool_Check(b)) + return PyLong_Type.tp_as_number->nb_and(a, b); + return PyBool_FromLong((a == Py_True) & (b == Py_True)); } static PyObject * bool_or(PyObject *a, PyObject *b) { - if (!PyBool_Check(a) || !PyBool_Check(b)) - return PyLong_Type.tp_as_number->nb_or(a, b); - return PyBool_FromLong((a == Py_True) | (b == Py_True)); + if (!PyBool_Check(a) || !PyBool_Check(b)) + return PyLong_Type.tp_as_number->nb_or(a, b); + return PyBool_FromLong((a == Py_True) | (b == Py_True)); } static PyObject * bool_xor(PyObject *a, PyObject *b) { - if (!PyBool_Check(a) || !PyBool_Check(b)) - return PyLong_Type.tp_as_number->nb_xor(a, b); - return PyBool_FromLong((a == Py_True) ^ (b == Py_True)); + if (!PyBool_Check(a) || !PyBool_Check(b)) + return PyLong_Type.tp_as_number->nb_xor(a, b); + return PyBool_FromLong((a == Py_True) ^ (b == Py_True)); } /* Doc string */ @@ -92,93 +92,93 @@ /* Arithmetic methods -- only so we can override &, |, ^. */ static PyNumberMethods bool_as_number = { - 0, /* nb_add */ - 0, /* nb_subtract */ - 0, /* nb_multiply */ - 0, /* nb_remainder */ - 0, /* nb_divmod */ - 0, /* nb_power */ - 0, /* nb_negative */ - 0, /* nb_positive */ - 0, /* nb_absolute */ - 0, /* nb_bool */ - 0, /* nb_invert */ - 0, /* nb_lshift */ - 0, /* nb_rshift */ - bool_and, /* nb_and */ - bool_xor, /* nb_xor */ - bool_or, /* nb_or */ - 0, /* nb_int */ - 0, /* nb_reserved */ - 0, /* nb_float */ - 0, /* nb_inplace_add */ - 0, /* nb_inplace_subtract */ - 0, /* nb_inplace_multiply */ - 0, /* nb_inplace_remainder */ - 0, /* nb_inplace_power */ - 0, /* nb_inplace_lshift */ - 0, /* nb_inplace_rshift */ - 0, /* nb_inplace_and */ - 0, /* nb_inplace_xor */ - 0, /* nb_inplace_or */ - 0, /* nb_floor_divide */ - 0, /* nb_true_divide */ - 0, /* nb_inplace_floor_divide */ - 0, /* nb_inplace_true_divide */ - 0, /* nb_index */ + 0, /* nb_add */ + 0, /* nb_subtract */ + 0, /* nb_multiply */ + 0, /* nb_remainder */ + 0, /* nb_divmod */ + 0, /* nb_power */ + 0, /* nb_negative */ + 0, /* nb_positive */ + 0, /* nb_absolute */ + 0, /* nb_bool */ + 0, /* nb_invert */ + 0, /* nb_lshift */ + 0, /* nb_rshift */ + bool_and, /* nb_and */ + bool_xor, /* nb_xor */ + bool_or, /* nb_or */ + 0, /* nb_int */ + 0, /* nb_reserved */ + 0, /* nb_float */ + 0, /* nb_inplace_add */ + 0, /* nb_inplace_subtract */ + 0, /* nb_inplace_multiply */ + 0, /* nb_inplace_remainder */ + 0, /* nb_inplace_power */ + 0, /* nb_inplace_lshift */ + 0, /* nb_inplace_rshift */ + 0, /* nb_inplace_and */ + 0, /* nb_inplace_xor */ + 0, /* nb_inplace_or */ + 0, /* nb_floor_divide */ + 0, /* nb_true_divide */ + 0, /* nb_inplace_floor_divide */ + 0, /* nb_inplace_true_divide */ + 0, /* nb_index */ }; /* The type object for bool. Note that this cannot be subclassed! */ PyTypeObject PyBool_Type = { - PyVarObject_HEAD_INIT(&PyType_Type, 0) - "bool", - sizeof(struct _longobject), - 0, - 0, /* tp_dealloc */ - 0, /* tp_print */ - 0, /* tp_getattr */ - 0, /* tp_setattr */ - 0, /* tp_reserved */ - bool_repr, /* tp_repr */ - &bool_as_number, /* tp_as_number */ - 0, /* tp_as_sequence */ - 0, /* tp_as_mapping */ - 0, /* tp_hash */ - 0, /* tp_call */ - bool_repr, /* tp_str */ - 0, /* tp_getattro */ - 0, /* tp_setattro */ - 0, /* tp_as_buffer */ - Py_TPFLAGS_DEFAULT, /* tp_flags */ - bool_doc, /* tp_doc */ - 0, /* tp_traverse */ - 0, /* tp_clear */ - 0, /* tp_richcompare */ - 0, /* tp_weaklistoffset */ - 0, /* tp_iter */ - 0, /* tp_iternext */ - 0, /* tp_methods */ - 0, /* tp_members */ - 0, /* tp_getset */ - &PyLong_Type, /* tp_base */ - 0, /* tp_dict */ - 0, /* tp_descr_get */ - 0, /* tp_descr_set */ - 0, /* tp_dictoffset */ - 0, /* tp_init */ - 0, /* tp_alloc */ - bool_new, /* tp_new */ + PyVarObject_HEAD_INIT(&PyType_Type, 0) + "bool", + sizeof(struct _longobject), + 0, + 0, /* tp_dealloc */ + 0, /* tp_print */ + 0, /* tp_getattr */ + 0, /* tp_setattr */ + 0, /* tp_reserved */ + bool_repr, /* tp_repr */ + &bool_as_number, /* tp_as_number */ + 0, /* tp_as_sequence */ + 0, /* tp_as_mapping */ + 0, /* tp_hash */ + 0, /* tp_call */ + bool_repr, /* tp_str */ + 0, /* tp_getattro */ + 0, /* tp_setattro */ + 0, /* tp_as_buffer */ + Py_TPFLAGS_DEFAULT, /* tp_flags */ + bool_doc, /* tp_doc */ + 0, /* tp_traverse */ + 0, /* tp_clear */ + 0, /* tp_richcompare */ + 0, /* tp_weaklistoffset */ + 0, /* tp_iter */ + 0, /* tp_iternext */ + 0, /* tp_methods */ + 0, /* tp_members */ + 0, /* tp_getset */ + &PyLong_Type, /* tp_base */ + 0, /* tp_dict */ + 0, /* tp_descr_get */ + 0, /* tp_descr_set */ + 0, /* tp_dictoffset */ + 0, /* tp_init */ + 0, /* tp_alloc */ + bool_new, /* tp_new */ }; /* The objects representing bool values False and True */ struct _longobject _Py_FalseStruct = { - PyVarObject_HEAD_INIT(&PyBool_Type, 0) - { 0 } + PyVarObject_HEAD_INIT(&PyBool_Type, 0) + { 0 } }; struct _longobject _Py_TrueStruct = { - PyVarObject_HEAD_INIT(&PyBool_Type, 1) - { 1 } + PyVarObject_HEAD_INIT(&PyBool_Type, 1) + { 1 } }; Modified: python/branches/py3k/Objects/bytes_methods.c ============================================================================== --- python/branches/py3k/Objects/bytes_methods.c (original) +++ python/branches/py3k/Objects/bytes_methods.c Sun May 9 17:52:27 2010 @@ -24,7 +24,7 @@ e = p + len; for (; p < e; p++) { - if (!Py_ISSPACE(*p)) + if (!Py_ISSPACE(*p)) Py_RETURN_FALSE; } Py_RETURN_TRUE; @@ -46,16 +46,16 @@ /* Shortcut for single character strings */ if (len == 1 && Py_ISALPHA(*p)) - Py_RETURN_TRUE; + Py_RETURN_TRUE; /* Special case for empty strings */ if (len == 0) - Py_RETURN_FALSE; + Py_RETURN_FALSE; e = p + len; for (; p < e; p++) { - if (!Py_ISALPHA(*p)) - Py_RETURN_FALSE; + if (!Py_ISALPHA(*p)) + Py_RETURN_FALSE; } Py_RETURN_TRUE; } @@ -76,16 +76,16 @@ /* Shortcut for single character strings */ if (len == 1 && Py_ISALNUM(*p)) - Py_RETURN_TRUE; + Py_RETURN_TRUE; /* Special case for empty strings */ if (len == 0) - Py_RETURN_FALSE; + Py_RETURN_FALSE; e = p + len; for (; p < e; p++) { - if (!Py_ISALNUM(*p)) - Py_RETURN_FALSE; + if (!Py_ISALNUM(*p)) + Py_RETURN_FALSE; } Py_RETURN_TRUE; } @@ -106,16 +106,16 @@ /* Shortcut for single character strings */ if (len == 1 && Py_ISDIGIT(*p)) - Py_RETURN_TRUE; + Py_RETURN_TRUE; /* Special case for empty strings */ if (len == 0) - Py_RETURN_FALSE; + Py_RETURN_FALSE; e = p + len; for (; p < e; p++) { - if (!Py_ISDIGIT(*p)) - Py_RETURN_FALSE; + if (!Py_ISDIGIT(*p)) + Py_RETURN_FALSE; } Py_RETURN_TRUE; } @@ -137,19 +137,19 @@ /* Shortcut for single character strings */ if (len == 1) - return PyBool_FromLong(Py_ISLOWER(*p)); + return PyBool_FromLong(Py_ISLOWER(*p)); /* Special case for empty strings */ if (len == 0) - Py_RETURN_FALSE; + Py_RETURN_FALSE; e = p + len; cased = 0; for (; p < e; p++) { - if (Py_ISUPPER(*p)) - Py_RETURN_FALSE; - else if (!cased && Py_ISLOWER(*p)) - cased = 1; + if (Py_ISUPPER(*p)) + Py_RETURN_FALSE; + else if (!cased && Py_ISLOWER(*p)) + cased = 1; } return PyBool_FromLong(cased); } @@ -171,19 +171,19 @@ /* Shortcut for single character strings */ if (len == 1) - return PyBool_FromLong(Py_ISUPPER(*p)); + return PyBool_FromLong(Py_ISUPPER(*p)); /* Special case for empty strings */ if (len == 0) - Py_RETURN_FALSE; + Py_RETURN_FALSE; e = p + len; cased = 0; for (; p < e; p++) { - if (Py_ISLOWER(*p)) - Py_RETURN_FALSE; - else if (!cased && Py_ISUPPER(*p)) - cased = 1; + if (Py_ISLOWER(*p)) + Py_RETURN_FALSE; + else if (!cased && Py_ISUPPER(*p)) + cased = 1; } return PyBool_FromLong(cased); } @@ -207,32 +207,32 @@ /* Shortcut for single character strings */ if (len == 1) - return PyBool_FromLong(Py_ISUPPER(*p)); + return PyBool_FromLong(Py_ISUPPER(*p)); /* Special case for empty strings */ if (len == 0) - Py_RETURN_FALSE; + Py_RETURN_FALSE; e = p + len; cased = 0; previous_is_cased = 0; for (; p < e; p++) { - register const unsigned char ch = *p; + register const unsigned char ch = *p; - if (Py_ISUPPER(ch)) { - if (previous_is_cased) - Py_RETURN_FALSE; - previous_is_cased = 1; - cased = 1; - } - else if (Py_ISLOWER(ch)) { - if (!previous_is_cased) - Py_RETURN_FALSE; - previous_is_cased = 1; - cased = 1; - } - else - previous_is_cased = 0; + if (Py_ISUPPER(ch)) { + if (previous_is_cased) + Py_RETURN_FALSE; + previous_is_cased = 1; + cased = 1; + } + else if (Py_ISLOWER(ch)) { + if (!previous_is_cased) + Py_RETURN_FALSE; + previous_is_cased = 1; + cased = 1; + } + else + previous_is_cased = 0; } return PyBool_FromLong(cased); } @@ -246,23 +246,23 @@ void _Py_bytes_lower(char *result, const char *cptr, Py_ssize_t len) { - Py_ssize_t i; + Py_ssize_t i; /* - newobj = PyBytes_FromStringAndSize(NULL, len); - if (!newobj) - return NULL; + newobj = PyBytes_FromStringAndSize(NULL, len); + if (!newobj) + return NULL; - s = PyBytes_AS_STRING(newobj); + s = PyBytes_AS_STRING(newobj); */ - Py_MEMCPY(result, cptr, len); + Py_MEMCPY(result, cptr, len); - for (i = 0; i < len; i++) { - int c = Py_CHARMASK(result[i]); - if (Py_ISUPPER(c)) - result[i] = Py_TOLOWER(c); - } + for (i = 0; i < len; i++) { + int c = Py_CHARMASK(result[i]); + if (Py_ISUPPER(c)) + result[i] = Py_TOLOWER(c); + } } @@ -274,23 +274,23 @@ void _Py_bytes_upper(char *result, const char *cptr, Py_ssize_t len) { - Py_ssize_t i; + Py_ssize_t i; /* - newobj = PyBytes_FromStringAndSize(NULL, len); - if (!newobj) - return NULL; + newobj = PyBytes_FromStringAndSize(NULL, len); + if (!newobj) + return NULL; - s = PyBytes_AS_STRING(newobj); + s = PyBytes_AS_STRING(newobj); */ - Py_MEMCPY(result, cptr, len); + Py_MEMCPY(result, cptr, len); - for (i = 0; i < len; i++) { - int c = Py_CHARMASK(result[i]); - if (Py_ISLOWER(c)) - result[i] = Py_TOUPPER(c); - } + for (i = 0; i < len; i++) { + int c = Py_CHARMASK(result[i]); + if (Py_ISLOWER(c)) + result[i] = Py_TOUPPER(c); + } } @@ -303,29 +303,29 @@ void _Py_bytes_title(char *result, char *s, Py_ssize_t len) { - Py_ssize_t i; - int previous_is_cased = 0; + Py_ssize_t i; + int previous_is_cased = 0; /* - newobj = PyBytes_FromStringAndSize(NULL, len); - if (newobj == NULL) - return NULL; - s_new = PyBytes_AsString(newobj); + newobj = PyBytes_FromStringAndSize(NULL, len); + if (newobj == NULL) + return NULL; + s_new = PyBytes_AsString(newobj); */ - for (i = 0; i < len; i++) { - int c = Py_CHARMASK(*s++); - if (Py_ISLOWER(c)) { - if (!previous_is_cased) - c = Py_TOUPPER(c); - previous_is_cased = 1; - } else if (Py_ISUPPER(c)) { - if (previous_is_cased) - c = Py_TOLOWER(c); - previous_is_cased = 1; - } else - previous_is_cased = 0; - *result++ = c; - } + for (i = 0; i < len; i++) { + int c = Py_CHARMASK(*s++); + if (Py_ISLOWER(c)) { + if (!previous_is_cased) + c = Py_TOUPPER(c); + previous_is_cased = 1; + } else if (Py_ISUPPER(c)) { + if (previous_is_cased) + c = Py_TOLOWER(c); + previous_is_cased = 1; + } else + previous_is_cased = 0; + *result++ = c; + } } @@ -337,30 +337,30 @@ void _Py_bytes_capitalize(char *result, char *s, Py_ssize_t len) { - Py_ssize_t i; + Py_ssize_t i; /* - newobj = PyBytes_FromStringAndSize(NULL, len); - if (newobj == NULL) - return NULL; - s_new = PyBytes_AsString(newobj); + newobj = PyBytes_FromStringAndSize(NULL, len); + if (newobj == NULL) + return NULL; + s_new = PyBytes_AsString(newobj); */ - if (0 < len) { - int c = Py_CHARMASK(*s++); - if (Py_ISLOWER(c)) - *result = Py_TOUPPER(c); - else - *result = c; - result++; - } - for (i = 1; i < len; i++) { - int c = Py_CHARMASK(*s++); - if (Py_ISUPPER(c)) - *result = Py_TOLOWER(c); - else - *result = c; - result++; - } + if (0 < len) { + int c = Py_CHARMASK(*s++); + if (Py_ISLOWER(c)) + *result = Py_TOUPPER(c); + else + *result = c; + result++; + } + for (i = 1; i < len; i++) { + int c = Py_CHARMASK(*s++); + if (Py_ISUPPER(c)) + *result = Py_TOLOWER(c); + else + *result = c; + result++; + } } @@ -373,26 +373,26 @@ void _Py_bytes_swapcase(char *result, char *s, Py_ssize_t len) { - Py_ssize_t i; + Py_ssize_t i; /* - newobj = PyBytes_FromStringAndSize(NULL, len); - if (newobj == NULL) - return NULL; - s_new = PyBytes_AsString(newobj); + newobj = PyBytes_FromStringAndSize(NULL, len); + if (newobj == NULL) + return NULL; + s_new = PyBytes_AsString(newobj); */ - for (i = 0; i < len; i++) { - int c = Py_CHARMASK(*s++); - if (Py_ISLOWER(c)) { - *result = Py_TOUPPER(c); - } - else if (Py_ISUPPER(c)) { - *result = Py_TOLOWER(c); - } - else - *result = c; - result++; - } + for (i = 0; i < len; i++) { + int c = Py_CHARMASK(*s++); + if (Py_ISLOWER(c)) { + *result = Py_TOUPPER(c); + } + else if (Py_ISUPPER(c)) { + *result = Py_TOLOWER(c); + } + else + *result = c; + result++; + } } @@ -425,40 +425,40 @@ PyObject * _Py_bytes_maketrans(PyObject *args) { - PyObject *frm, *to, *res = NULL; - Py_buffer bfrm, bto; - Py_ssize_t i; - char *p; - - bfrm.len = -1; - bto.len = -1; - - if (!PyArg_ParseTuple(args, "OO:maketrans", &frm, &to)) - return NULL; - if (_getbuffer(frm, &bfrm) < 0) - return NULL; - if (_getbuffer(to, &bto) < 0) - goto done; - if (bfrm.len != bto.len) { - PyErr_Format(PyExc_ValueError, - "maketrans arguments must have same length"); - goto done; - } - res = PyBytes_FromStringAndSize(NULL, 256); - if (!res) { - goto done; - } - p = PyBytes_AS_STRING(res); - for (i = 0; i < 256; i++) - p[i] = i; - for (i = 0; i < bfrm.len; i++) { - p[((unsigned char *)bfrm.buf)[i]] = ((char *)bto.buf)[i]; - } + PyObject *frm, *to, *res = NULL; + Py_buffer bfrm, bto; + Py_ssize_t i; + char *p; + + bfrm.len = -1; + bto.len = -1; + + if (!PyArg_ParseTuple(args, "OO:maketrans", &frm, &to)) + return NULL; + if (_getbuffer(frm, &bfrm) < 0) + return NULL; + if (_getbuffer(to, &bto) < 0) + goto done; + if (bfrm.len != bto.len) { + PyErr_Format(PyExc_ValueError, + "maketrans arguments must have same length"); + goto done; + } + res = PyBytes_FromStringAndSize(NULL, 256); + if (!res) { + goto done; + } + p = PyBytes_AS_STRING(res); + for (i = 0; i < 256; i++) + p[i] = i; + for (i = 0; i < bfrm.len; i++) { + p[((unsigned char *)bfrm.buf)[i]] = ((char *)bto.buf)[i]; + } done: - if (bfrm.len != -1) - PyBuffer_Release(&bfrm); - if (bto.len != -1) - PyBuffer_Release(&bto); - return res; + if (bfrm.len != -1) + PyBuffer_Release(&bfrm); + if (bto.len != -1) + PyBuffer_Release(&bto); + return res; } Modified: python/branches/py3k/Objects/bytesobject.c ============================================================================== --- python/branches/py3k/Objects/bytesobject.c (original) +++ python/branches/py3k/Objects/bytesobject.c Sun May 9 17:52:27 2010 @@ -14,14 +14,14 @@ if (buffer == NULL || buffer->bf_getbuffer == NULL) { - PyErr_Format(PyExc_TypeError, - "Type %.100s doesn't support the buffer API", - Py_TYPE(obj)->tp_name); - return -1; + PyErr_Format(PyExc_TypeError, + "Type %.100s doesn't support the buffer API", + Py_TYPE(obj)->tp_name); + return -1; } if (buffer->bf_getbuffer(obj, view, PyBUF_SIMPLE) < 0) - return -1; + return -1; return view->len; } @@ -69,305 +69,305 @@ PyObject * PyBytes_FromStringAndSize(const char *str, Py_ssize_t size) { - register PyBytesObject *op; - if (size < 0) { - PyErr_SetString(PyExc_SystemError, - "Negative size passed to PyBytes_FromStringAndSize"); - return NULL; - } - if (size == 0 && (op = nullstring) != NULL) { + register PyBytesObject *op; + if (size < 0) { + PyErr_SetString(PyExc_SystemError, + "Negative size passed to PyBytes_FromStringAndSize"); + return NULL; + } + if (size == 0 && (op = nullstring) != NULL) { #ifdef COUNT_ALLOCS - null_strings++; + null_strings++; #endif - Py_INCREF(op); - return (PyObject *)op; - } - if (size == 1 && str != NULL && - (op = characters[*str & UCHAR_MAX]) != NULL) - { + Py_INCREF(op); + return (PyObject *)op; + } + if (size == 1 && str != NULL && + (op = characters[*str & UCHAR_MAX]) != NULL) + { #ifdef COUNT_ALLOCS - one_strings++; + one_strings++; #endif - Py_INCREF(op); - return (PyObject *)op; - } - - if (size > PY_SSIZE_T_MAX - PyBytesObject_SIZE) { - PyErr_SetString(PyExc_OverflowError, - "byte string is too large"); - return NULL; - } - - /* Inline PyObject_NewVar */ - op = (PyBytesObject *)PyObject_MALLOC(PyBytesObject_SIZE + size); - if (op == NULL) - return PyErr_NoMemory(); - PyObject_INIT_VAR(op, &PyBytes_Type, size); - op->ob_shash = -1; - if (str != NULL) - Py_MEMCPY(op->ob_sval, str, size); - op->ob_sval[size] = '\0'; - /* share short strings */ - if (size == 0) { - nullstring = op; - Py_INCREF(op); - } else if (size == 1 && str != NULL) { - characters[*str & UCHAR_MAX] = op; - Py_INCREF(op); - } - return (PyObject *) op; + Py_INCREF(op); + return (PyObject *)op; + } + + if (size > PY_SSIZE_T_MAX - PyBytesObject_SIZE) { + PyErr_SetString(PyExc_OverflowError, + "byte string is too large"); + return NULL; + } + + /* Inline PyObject_NewVar */ + op = (PyBytesObject *)PyObject_MALLOC(PyBytesObject_SIZE + size); + if (op == NULL) + return PyErr_NoMemory(); + PyObject_INIT_VAR(op, &PyBytes_Type, size); + op->ob_shash = -1; + if (str != NULL) + Py_MEMCPY(op->ob_sval, str, size); + op->ob_sval[size] = '\0'; + /* share short strings */ + if (size == 0) { + nullstring = op; + Py_INCREF(op); + } else if (size == 1 && str != NULL) { + characters[*str & UCHAR_MAX] = op; + Py_INCREF(op); + } + return (PyObject *) op; } PyObject * PyBytes_FromString(const char *str) { - register size_t size; - register PyBytesObject *op; + register size_t size; + register 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) { + 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++; + null_strings++; #endif - Py_INCREF(op); - return (PyObject *)op; - } - if (size == 1 && (op = characters[*str & UCHAR_MAX]) != NULL) { + Py_INCREF(op); + return (PyObject *)op; + } + if (size == 1 && (op = characters[*str & UCHAR_MAX]) != NULL) { #ifdef COUNT_ALLOCS - one_strings++; + 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(); - PyObject_INIT_VAR(op, &PyBytes_Type, size); - op->ob_shash = -1; - Py_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; + Py_INCREF(op); + return (PyObject *)op; + } + + /* Inline PyObject_NewVar */ + op = (PyBytesObject *)PyObject_MALLOC(PyBytesObject_SIZE + size); + if (op == NULL) + return PyErr_NoMemory(); + PyObject_INIT_VAR(op, &PyBytes_Type, size); + op->ob_shash = -1; + Py_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) { - va_list count; - Py_ssize_t n = 0; - const char* f; - char *s; - PyObject* string; + va_list count; + Py_ssize_t n = 0; + const char* f; + char *s; + PyObject* string; #ifdef VA_LIST_IS_ARRAY - Py_MEMCPY(count, vargs, sizeof(va_list)); + Py_MEMCPY(count, vargs, sizeof(va_list)); #else #ifdef __va_copy - __va_copy(count, vargs); + __va_copy(count, vargs); #else - count = vargs; + count = vargs; #endif #endif - /* step 1: figure out how large a buffer we need */ - for (f = format; *f; f++) { - if (*f == '%') { - const char* p = f; - while (*++f && *f != '%' && !ISALPHA(*f)) - ; - - /* skip the 'l' or 'z' in {%ld, %zd, %lu, %zu} since - * they don't affect the amount of space we reserve. - */ - if ((*f == 'l' || *f == 'z') && - (f[1] == 'd' || f[1] == 'u')) - ++f; - - switch (*f) { - case 'c': - (void)va_arg(count, int); - /* fall through... */ - case '%': - n++; - break; - case 'd': case 'u': case 'i': case 'x': - (void) va_arg(count, int); - /* 20 bytes is enough to hold a 64-bit - integer. Decimal takes the most space. - This isn't enough for octal. */ - n += 20; - break; - case 's': - s = va_arg(count, char*); - n += strlen(s); - break; - case 'p': - (void) va_arg(count, int); - /* maximum 64-bit pointer representation: - * 0xffffffffffffffff - * so 19 characters is enough. - * XXX I count 18 -- what's the extra for? - */ - n += 19; - break; - default: - /* if we stumble upon an unknown - formatting code, copy the rest of - the format string to the output - string. (we cannot just skip the - code, since there's no way to know - what's in the argument list) */ - n += strlen(p); - goto expand; - } - } else - n++; - } + /* step 1: figure out how large a buffer we need */ + for (f = format; *f; f++) { + if (*f == '%') { + const char* p = f; + while (*++f && *f != '%' && !ISALPHA(*f)) + ; + + /* skip the 'l' or 'z' in {%ld, %zd, %lu, %zu} since + * they don't affect the amount of space we reserve. + */ + if ((*f == 'l' || *f == 'z') && + (f[1] == 'd' || f[1] == 'u')) + ++f; + + switch (*f) { + case 'c': + (void)va_arg(count, int); + /* fall through... */ + case '%': + n++; + break; + case 'd': case 'u': case 'i': case 'x': + (void) va_arg(count, int); + /* 20 bytes is enough to hold a 64-bit + integer. Decimal takes the most space. + This isn't enough for octal. */ + n += 20; + break; + case 's': + s = va_arg(count, char*); + n += strlen(s); + break; + case 'p': + (void) va_arg(count, int); + /* maximum 64-bit pointer representation: + * 0xffffffffffffffff + * so 19 characters is enough. + * XXX I count 18 -- what's the extra for? + */ + n += 19; + break; + default: + /* if we stumble upon an unknown + formatting code, copy the rest of + the format string to the output + string. (we cannot just skip the + code, since there's no way to know + what's in the argument list) */ + n += strlen(p); + goto expand; + } + } else + n++; + } expand: - /* step 2: fill the buffer */ - /* Since we've analyzed how much space we need for the worst case, - use sprintf directly instead of the slower PyOS_snprintf. */ - string = PyBytes_FromStringAndSize(NULL, n); - if (!string) - return NULL; - - s = PyBytes_AsString(string); - - for (f = format; *f; f++) { - if (*f == '%') { - const char* p = f++; - Py_ssize_t i; - int longflag = 0; - int size_tflag = 0; - /* parse the width.precision part (we're only - interested in the precision value, if any) */ - n = 0; - while (ISDIGIT(*f)) - n = (n*10) + *f++ - '0'; - if (*f == '.') { - f++; - n = 0; - while (ISDIGIT(*f)) - n = (n*10) + *f++ - '0'; - } - while (*f && *f != '%' && !ISALPHA(*f)) - f++; - /* handle the long flag, but only for %ld and %lu. - others can be added when necessary. */ - if (*f == 'l' && (f[1] == 'd' || f[1] == 'u')) { - longflag = 1; - ++f; - } - /* handle the size_t flag. */ - if (*f == 'z' && (f[1] == 'd' || f[1] == 'u')) { - size_tflag = 1; - ++f; - } - - switch (*f) { - case 'c': - *s++ = va_arg(vargs, int); - break; - case 'd': - if (longflag) - sprintf(s, "%ld", va_arg(vargs, long)); - else if (size_tflag) - sprintf(s, "%" PY_FORMAT_SIZE_T "d", - va_arg(vargs, Py_ssize_t)); - else - sprintf(s, "%d", va_arg(vargs, int)); - s += strlen(s); - break; - case 'u': - if (longflag) - sprintf(s, "%lu", - va_arg(vargs, unsigned long)); - else if (size_tflag) - sprintf(s, "%" PY_FORMAT_SIZE_T "u", - va_arg(vargs, size_t)); - else - sprintf(s, "%u", - va_arg(vargs, unsigned int)); - s += strlen(s); - break; - case 'i': - sprintf(s, "%i", va_arg(vargs, int)); - s += strlen(s); - break; - case 'x': - sprintf(s, "%x", va_arg(vargs, int)); - s += strlen(s); - break; - case 's': - p = va_arg(vargs, char*); - i = strlen(p); - if (n > 0 && i > n) - i = n; - Py_MEMCPY(s, p, i); - s += i; - break; - case 'p': - sprintf(s, "%p", va_arg(vargs, void*)); - /* %p is ill-defined: ensure leading 0x. */ - if (s[1] == 'X') - s[1] = 'x'; - else if (s[1] != 'x') { - memmove(s+2, s, strlen(s)+1); - s[0] = '0'; - s[1] = 'x'; - } - s += strlen(s); - break; - case '%': - *s++ = '%'; - break; - default: - strcpy(s, p); - s += strlen(s); - goto end; - } - } else - *s++ = *f; - } + /* step 2: fill the buffer */ + /* Since we've analyzed how much space we need for the worst case, + use sprintf directly instead of the slower PyOS_snprintf. */ + string = PyBytes_FromStringAndSize(NULL, n); + if (!string) + return NULL; + + s = PyBytes_AsString(string); + + for (f = format; *f; f++) { + if (*f == '%') { + const char* p = f++; + Py_ssize_t i; + int longflag = 0; + int size_tflag = 0; + /* parse the width.precision part (we're only + interested in the precision value, if any) */ + n = 0; + while (ISDIGIT(*f)) + n = (n*10) + *f++ - '0'; + if (*f == '.') { + f++; + n = 0; + while (ISDIGIT(*f)) + n = (n*10) + *f++ - '0'; + } + while (*f && *f != '%' && !ISALPHA(*f)) + f++; + /* handle the long flag, but only for %ld and %lu. + others can be added when necessary. */ + if (*f == 'l' && (f[1] == 'd' || f[1] == 'u')) { + longflag = 1; + ++f; + } + /* handle the size_t flag. */ + if (*f == 'z' && (f[1] == 'd' || f[1] == 'u')) { + size_tflag = 1; + ++f; + } + + switch (*f) { + case 'c': + *s++ = va_arg(vargs, int); + break; + case 'd': + if (longflag) + sprintf(s, "%ld", va_arg(vargs, long)); + else if (size_tflag) + sprintf(s, "%" PY_FORMAT_SIZE_T "d", + va_arg(vargs, Py_ssize_t)); + else + sprintf(s, "%d", va_arg(vargs, int)); + s += strlen(s); + break; + case 'u': + if (longflag) + sprintf(s, "%lu", + va_arg(vargs, unsigned long)); + else if (size_tflag) + sprintf(s, "%" PY_FORMAT_SIZE_T "u", + va_arg(vargs, size_t)); + else + sprintf(s, "%u", + va_arg(vargs, unsigned int)); + s += strlen(s); + break; + case 'i': + sprintf(s, "%i", va_arg(vargs, int)); + s += strlen(s); + break; + case 'x': + sprintf(s, "%x", va_arg(vargs, int)); + s += strlen(s); + break; + case 's': + p = va_arg(vargs, char*); + i = strlen(p); + if (n > 0 && i > n) + i = n; + Py_MEMCPY(s, p, i); + s += i; + break; + case 'p': + sprintf(s, "%p", va_arg(vargs, void*)); + /* %p is ill-defined: ensure leading 0x. */ + if (s[1] == 'X') + s[1] = 'x'; + else if (s[1] != 'x') { + memmove(s+2, s, strlen(s)+1); + s[0] = '0'; + s[1] = 'x'; + } + s += strlen(s); + break; + case '%': + *s++ = '%'; + break; + default: + strcpy(s, p); + s += strlen(s); + goto end; + } + } else + *s++ = *f; + } end: - _PyBytes_Resize(&string, s - PyBytes_AS_STRING(string)); - return string; + _PyBytes_Resize(&string, s - PyBytes_AS_STRING(string)); + return string; } PyObject * PyBytes_FromFormat(const char *format, ...) { - PyObject* ret; - va_list vargs; + PyObject* ret; + va_list vargs; #ifdef HAVE_STDARG_PROTOTYPES - va_start(vargs, format); + va_start(vargs, format); #else - va_start(vargs); + va_start(vargs); #endif - ret = PyBytes_FromFormatV(format, vargs); - va_end(vargs); - return ret; + ret = PyBytes_FromFormatV(format, vargs); + va_end(vargs); + return ret; } static void bytes_dealloc(PyObject *op) { - Py_TYPE(op)->tp_free(op); + Py_TYPE(op)->tp_free(op); } /* Unescape a backslash-escaped string. If unicode is non-zero, @@ -376,135 +376,135 @@ specified encoding. */ PyObject *PyBytes_DecodeEscape(const char *s, - Py_ssize_t len, - const char *errors, - Py_ssize_t unicode, - const char *recode_encoding) -{ - int c; - char *p, *buf; - const char *end; - PyObject *v; - Py_ssize_t newlen = recode_encoding ? 4*len:len; - v = PyBytes_FromStringAndSize((char *)NULL, newlen); - if (v == NULL) - return NULL; - p = buf = PyBytes_AsString(v); - end = s + len; - while (s < end) { - if (*s != '\\') { - non_esc: - if (recode_encoding && (*s & 0x80)) { - PyObject *u, *w; - char *r; - const char* t; - Py_ssize_t rn; - t = s; - /* Decode non-ASCII bytes as UTF-8. */ - while (t < end && (*t & 0x80)) t++; - u = PyUnicode_DecodeUTF8(s, t - s, errors); - if(!u) goto failed; - - /* Recode them in target encoding. */ - w = PyUnicode_AsEncodedString( - u, recode_encoding, errors); - Py_DECREF(u); - if (!w) goto failed; - - /* Append bytes to output buffer. */ - assert(PyBytes_Check(w)); - r = PyBytes_AS_STRING(w); - rn = PyBytes_GET_SIZE(w); - Py_MEMCPY(p, r, rn); - p += rn; - Py_DECREF(w); - s = t; - } else { - *p++ = *s++; - } - 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 && ISXDIGIT(s[0]) && ISXDIGIT(s[1])) { - unsigned int x = 0; - c = Py_CHARMASK(*s); - s++; - if (ISDIGIT(c)) - x = c - '0'; - else if (ISLOWER(c)) - x = 10 + c - 'a'; - else - x = 10 + c - 'A'; - x = x << 4; - c = Py_CHARMASK(*s); - s++; - if (ISDIGIT(c)) - x += c - '0'; - else if (ISLOWER(c)) - x += 10 + c - 'a'; - else - x += 10 + c - 'A'; - *p++ = x; - break; - } - if (!errors || strcmp(errors, "strict") == 0) { - PyErr_SetString(PyExc_ValueError, - "invalid \\x escape"); - 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; - } - default: - *p++ = '\\'; - s--; - goto non_esc; /* an arbitry number of unescaped - UTF-8 bytes may follow. */ - } - } - if (p-buf < newlen) - _PyBytes_Resize(&v, p - buf); - return v; + Py_ssize_t len, + const char *errors, + Py_ssize_t unicode, + const char *recode_encoding) +{ + int c; + char *p, *buf; + const char *end; + PyObject *v; + Py_ssize_t newlen = recode_encoding ? 4*len:len; + v = PyBytes_FromStringAndSize((char *)NULL, newlen); + if (v == NULL) + return NULL; + p = buf = PyBytes_AsString(v); + end = s + len; + while (s < end) { + if (*s != '\\') { + non_esc: + if (recode_encoding && (*s & 0x80)) { + PyObject *u, *w; + char *r; + const char* t; + Py_ssize_t rn; + t = s; + /* Decode non-ASCII bytes as UTF-8. */ + while (t < end && (*t & 0x80)) t++; + u = PyUnicode_DecodeUTF8(s, t - s, errors); + if(!u) goto failed; + + /* Recode them in target encoding. */ + w = PyUnicode_AsEncodedString( + u, recode_encoding, errors); + Py_DECREF(u); + if (!w) goto failed; + + /* Append bytes to output buffer. */ + assert(PyBytes_Check(w)); + r = PyBytes_AS_STRING(w); + rn = PyBytes_GET_SIZE(w); + Py_MEMCPY(p, r, rn); + p += rn; + Py_DECREF(w); + s = t; + } else { + *p++ = *s++; + } + 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 && ISXDIGIT(s[0]) && ISXDIGIT(s[1])) { + unsigned int x = 0; + c = Py_CHARMASK(*s); + s++; + if (ISDIGIT(c)) + x = c - '0'; + else if (ISLOWER(c)) + x = 10 + c - 'a'; + else + x = 10 + c - 'A'; + x = x << 4; + c = Py_CHARMASK(*s); + s++; + if (ISDIGIT(c)) + x += c - '0'; + else if (ISLOWER(c)) + x += 10 + c - 'a'; + else + x += 10 + c - 'A'; + *p++ = x; + break; + } + if (!errors || strcmp(errors, "strict") == 0) { + PyErr_SetString(PyExc_ValueError, + "invalid \\x escape"); + 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; + } + default: + *p++ = '\\'; + s--; + goto non_esc; /* an arbitry number of unescaped + UTF-8 bytes may follow. */ + } + } + if (p-buf < newlen) + _PyBytes_Resize(&v, p - buf); + return v; failed: - Py_DECREF(v); - return NULL; + Py_DECREF(v); + return NULL; } /* -------------------------------------------------------------------- */ @@ -513,50 +513,50 @@ Py_ssize_t PyBytes_Size(register 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); + 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(register 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; + 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(register PyObject *obj, - register char **s, - register Py_ssize_t *len) + register char **s, + register 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_TypeError, - "expected bytes with no null"); - return -1; - } - return 0; + 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_TypeError, + "expected bytes with no null"); + return -1; + } + return 0; } /* -------------------------------------------------------------------- */ @@ -576,199 +576,199 @@ PyObject * PyBytes_Repr(PyObject *obj, int smartquotes) { - static const char *hexdigits = "0123456789abcdef"; - register PyBytesObject* op = (PyBytesObject*) obj; - Py_ssize_t length = Py_SIZE(op); - size_t newsize = 3 + 4 * length; - PyObject *v; - if (newsize > PY_SSIZE_T_MAX || (newsize-3) / 4 != length) { - PyErr_SetString(PyExc_OverflowError, - "bytes object is too large to make repr"); - return NULL; - } - v = PyUnicode_FromUnicode(NULL, newsize); - if (v == NULL) { - return NULL; - } - else { - register Py_ssize_t i; - register Py_UNICODE c; - register Py_UNICODE *p = PyUnicode_AS_UNICODE(v); - int quote; - - /* Figure out which quote to use; single is preferred */ - quote = '\''; - if (smartquotes) { - char *test, *start; - start = PyBytes_AS_STRING(op); - for (test = start; test < start+length; ++test) { - if (*test == '"') { - quote = '\''; /* back to single */ - goto decided; - } - else if (*test == '\'') - quote = '"'; - } - decided: - ; - } - - *p++ = 'b', *p++ = quote; - for (i = 0; i < length; i++) { - /* There's at least enough room for a hex escape - and a closing quote. */ - assert(newsize - (p - PyUnicode_AS_UNICODE(v)) >= 5); - 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++ = hexdigits[(c & 0xf0) >> 4]; - *p++ = hexdigits[c & 0xf]; - } - else - *p++ = c; - } - assert(newsize - (p - PyUnicode_AS_UNICODE(v)) >= 1); - *p++ = quote; - *p = '\0'; - if (PyUnicode_Resize(&v, (p - PyUnicode_AS_UNICODE(v)))) { - Py_DECREF(v); - return NULL; - } - return v; - } + static const char *hexdigits = "0123456789abcdef"; + register PyBytesObject* op = (PyBytesObject*) obj; + Py_ssize_t length = Py_SIZE(op); + size_t newsize = 3 + 4 * length; + PyObject *v; + if (newsize > PY_SSIZE_T_MAX || (newsize-3) / 4 != length) { + PyErr_SetString(PyExc_OverflowError, + "bytes object is too large to make repr"); + return NULL; + } + v = PyUnicode_FromUnicode(NULL, newsize); + if (v == NULL) { + return NULL; + } + else { + register Py_ssize_t i; + register Py_UNICODE c; + register Py_UNICODE *p = PyUnicode_AS_UNICODE(v); + int quote; + + /* Figure out which quote to use; single is preferred */ + quote = '\''; + if (smartquotes) { + char *test, *start; + start = PyBytes_AS_STRING(op); + for (test = start; test < start+length; ++test) { + if (*test == '"') { + quote = '\''; /* back to single */ + goto decided; + } + else if (*test == '\'') + quote = '"'; + } + decided: + ; + } + + *p++ = 'b', *p++ = quote; + for (i = 0; i < length; i++) { + /* There's at least enough room for a hex escape + and a closing quote. */ + assert(newsize - (p - PyUnicode_AS_UNICODE(v)) >= 5); + 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++ = hexdigits[(c & 0xf0) >> 4]; + *p++ = hexdigits[c & 0xf]; + } + else + *p++ = c; + } + assert(newsize - (p - PyUnicode_AS_UNICODE(v)) >= 1); + *p++ = quote; + *p = '\0'; + if (PyUnicode_Resize(&v, (p - PyUnicode_AS_UNICODE(v)))) { + Py_DECREF(v); + return NULL; + } + return v; + } } static PyObject * bytes_repr(PyObject *op) { - return PyBytes_Repr(op, 1); + 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); + 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); + return Py_SIZE(a); } /* This is also used by PyBytes_Concat() */ static PyObject * bytes_concat(PyObject *a, PyObject *b) { - Py_ssize_t size; - Py_buffer va, vb; - PyObject *result = NULL; - - va.len = -1; - vb.len = -1; - if (_getbuffer(a, &va) < 0 || - _getbuffer(b, &vb) < 0) { - PyErr_Format(PyExc_TypeError, "can't concat %.100s to %.100s", - Py_TYPE(a)->tp_name, Py_TYPE(b)->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; - } - - size = va.len + vb.len; - if (size < 0) { - PyErr_NoMemory(); - goto done; - } - - result = PyBytes_FromStringAndSize(NULL, size); - if (result != NULL) { - memcpy(PyBytes_AS_STRING(result), va.buf, va.len); - memcpy(PyBytes_AS_STRING(result) + va.len, vb.buf, vb.len); - } + Py_ssize_t size; + Py_buffer va, vb; + PyObject *result = NULL; + + va.len = -1; + vb.len = -1; + if (_getbuffer(a, &va) < 0 || + _getbuffer(b, &vb) < 0) { + PyErr_Format(PyExc_TypeError, "can't concat %.100s to %.100s", + Py_TYPE(a)->tp_name, Py_TYPE(b)->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; + } + + size = va.len + vb.len; + if (size < 0) { + PyErr_NoMemory(); + goto done; + } + + result = PyBytes_FromStringAndSize(NULL, size); + 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; + if (va.len != -1) + PyBuffer_Release(&va); + if (vb.len != -1) + PyBuffer_Release(&vb); + return result; } static PyObject * bytes_repeat(register PyBytesObject *a, register Py_ssize_t n) { - register Py_ssize_t i; - register Py_ssize_t j; - register Py_ssize_t size; - register 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 - */ - size = Py_SIZE(a) * n; - if (n && size / n != Py_SIZE(a)) { - PyErr_SetString(PyExc_OverflowError, - "repeated bytes are too long"); - return NULL; - } - 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(); - 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) { - Py_MEMCPY(op->ob_sval, a->ob_sval, Py_SIZE(a)); - i = Py_SIZE(a); - } - while (i < size) { - j = (i <= size-i) ? i : size-i; - Py_MEMCPY(op->ob_sval+i, op->ob_sval, j); - i += j; - } - return (PyObject *) op; + register Py_ssize_t i; + register Py_ssize_t j; + register Py_ssize_t size; + register 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 + */ + size = Py_SIZE(a) * n; + if (n && size / n != Py_SIZE(a)) { + PyErr_SetString(PyExc_OverflowError, + "repeated bytes are too long"); + return NULL; + } + 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(); + 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) { + Py_MEMCPY(op->ob_sval, a->ob_sval, Py_SIZE(a)); + i = Py_SIZE(a); + } + while (i < size) { + j = (i <= size-i) ? i : size-i; + Py_MEMCPY(op->ob_sval+i, op->ob_sval, j); + i += j; + } + return (PyObject *) op; } static int @@ -776,19 +776,19 @@ { Py_ssize_t ival = PyNumber_AsSsize_t(arg, PyExc_ValueError); if (ival == -1 && PyErr_Occurred()) { - Py_buffer varg; - int pos; - PyErr_Clear(); - if (_getbuffer(arg, &varg) < 0) - return -1; - pos = stringlib_find(PyBytes_AS_STRING(self), Py_SIZE(self), - varg.buf, varg.len, 0); - PyBuffer_Release(&varg); - return pos >= 0; + Py_buffer varg; + int pos; + PyErr_Clear(); + if (_getbuffer(arg, &varg) < 0) + return -1; + pos = stringlib_find(PyBytes_AS_STRING(self), Py_SIZE(self), + varg.buf, varg.len, 0); + PyBuffer_Release(&varg); + return pos >= 0; } if (ival < 0 || ival >= 256) { - PyErr_SetString(PyExc_ValueError, "byte must be in range(0, 256)"); - return -1; + PyErr_SetString(PyExc_ValueError, "byte must be in range(0, 256)"); + return -1; } return memchr(PyBytes_AS_STRING(self), ival, Py_SIZE(self)) != NULL; @@ -797,197 +797,197 @@ static PyObject * bytes_item(PyBytesObject *a, register 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]); + 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 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; - - /* Make sure both arguments are strings. */ - if (!(PyBytes_Check(a) && PyBytes_Check(b))) { - if (Py_BytesWarningFlag && (op == Py_EQ || op == Py_NE) && - (PyObject_IsInstance((PyObject*)a, - (PyObject*)&PyUnicode_Type) || - PyObject_IsInstance((PyObject*)b, - (PyObject*)&PyUnicode_Type))) { - if (PyErr_WarnEx(PyExc_BytesWarning, - "Comparison between bytes and string", 1)) - return NULL; - } - result = Py_NotImplemented; - goto out; - } - if (a == b) { - switch (op) { - case Py_EQ:case Py_LE:case Py_GE: - result = Py_True; - goto out; - case Py_NE:case Py_LT:case Py_GT: - result = Py_False; - goto out; - } - } - if (op == Py_EQ) { - /* Supporting Py_NE here as well does not save - much time, since Py_NE is rarely used. */ - if (Py_SIZE(a) == Py_SIZE(b) - && (a->ob_sval[0] == b->ob_sval[0] - && memcmp(a->ob_sval, b->ob_sval, Py_SIZE(a)) == 0)) { - result = Py_True; - } else { - result = Py_False; - } - goto out; - } - len_a = Py_SIZE(a); len_b = Py_SIZE(b); - min_len = (len_a < len_b) ? 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_EQ: assert(0); break; /* unreachable */ - case Py_NE: c = c != 0; break; - case Py_GT: c = c > 0; break; - case Py_GE: c = c >= 0; break; - default: - result = Py_NotImplemented; - goto out; - } - result = c ? Py_True : Py_False; + int c; + Py_ssize_t len_a, len_b; + Py_ssize_t min_len; + PyObject *result; + + /* Make sure both arguments are strings. */ + if (!(PyBytes_Check(a) && PyBytes_Check(b))) { + if (Py_BytesWarningFlag && (op == Py_EQ || op == Py_NE) && + (PyObject_IsInstance((PyObject*)a, + (PyObject*)&PyUnicode_Type) || + PyObject_IsInstance((PyObject*)b, + (PyObject*)&PyUnicode_Type))) { + if (PyErr_WarnEx(PyExc_BytesWarning, + "Comparison between bytes and string", 1)) + return NULL; + } + result = Py_NotImplemented; + goto out; + } + if (a == b) { + switch (op) { + case Py_EQ:case Py_LE:case Py_GE: + result = Py_True; + goto out; + case Py_NE:case Py_LT:case Py_GT: + result = Py_False; + goto out; + } + } + if (op == Py_EQ) { + /* Supporting Py_NE here as well does not save + much time, since Py_NE is rarely used. */ + if (Py_SIZE(a) == Py_SIZE(b) + && (a->ob_sval[0] == b->ob_sval[0] + && memcmp(a->ob_sval, b->ob_sval, Py_SIZE(a)) == 0)) { + result = Py_True; + } else { + result = Py_False; + } + goto out; + } + len_a = Py_SIZE(a); len_b = Py_SIZE(b); + min_len = (len_a < len_b) ? 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_EQ: assert(0); break; /* unreachable */ + case Py_NE: c = c != 0; break; + case Py_GT: c = c > 0; break; + case Py_GE: c = c >= 0; break; + default: + result = Py_NotImplemented; + goto out; + } + result = c ? Py_True : Py_False; out: - Py_INCREF(result); - return result; + Py_INCREF(result); + return result; } static long bytes_hash(PyBytesObject *a) { - register Py_ssize_t len; - register unsigned char *p; - register long x; - - if (a->ob_shash != -1) - return a->ob_shash; - len = Py_SIZE(a); - p = (unsigned char *) a->ob_sval; - x = *p << 7; - while (--len >= 0) - x = (1000003*x) ^ *p++; - x ^= Py_SIZE(a); - if (x == -1) - x = -2; - a->ob_shash = x; - return x; + register Py_ssize_t len; + register unsigned char *p; + register long x; + + if (a->ob_shash != -1) + return a->ob_shash; + len = Py_SIZE(a); + p = (unsigned char *) a->ob_sval; + x = *p << 7; + while (--len >= 0) + x = (1000003*x) ^ *p++; + x ^= Py_SIZE(a); + if (x == -1) + x = -2; + a->ob_shash = x; + return x; } 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_GetIndicesEx((PySliceObject*)item, - PyBytes_GET_SIZE(self), - &start, &stop, &step, &slicelength) < 0) { - return NULL; - } - - 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, not %.200s", - Py_TYPE(item)->tp_name); - return NULL; - } + 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_GetIndicesEx((PySliceObject*)item, + PyBytes_GET_SIZE(self), + &start, &stop, &step, &slicelength) < 0) { + return NULL; + } + + 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, 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); + 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*/ + (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, + (lenfunc)bytes_length, + (binaryfunc)bytes_subscript, + 0, }; static PyBufferProcs bytes_as_buffer = { - (getbufferproc)bytes_buffer_getbuffer, - NULL, + (getbufferproc)bytes_buffer_getbuffer, + NULL, }; @@ -1011,26 +1011,26 @@ static PyObject * bytes_split(PyBytesObject *self, PyObject *args) { - Py_ssize_t len = PyBytes_GET_SIZE(self), n; - Py_ssize_t maxsplit = -1; - const char *s = PyBytes_AS_STRING(self), *sub; - Py_buffer vsub; - PyObject *list, *subobj = Py_None; - - if (!PyArg_ParseTuple(args, "|On:split", &subobj, &maxsplit)) - return NULL; - if (maxsplit < 0) - maxsplit = PY_SSIZE_T_MAX; - if (subobj == Py_None) - return stringlib_split_whitespace((PyObject*) self, s, len, maxsplit); - if (_getbuffer(subobj, &vsub) < 0) - return NULL; - sub = vsub.buf; - n = vsub.len; - - list = stringlib_split((PyObject*) self, s, len, sub, n, maxsplit); - PyBuffer_Release(&vsub); - return list; + Py_ssize_t len = PyBytes_GET_SIZE(self), n; + Py_ssize_t maxsplit = -1; + const char *s = PyBytes_AS_STRING(self), *sub; + Py_buffer vsub; + PyObject *list, *subobj = Py_None; + + if (!PyArg_ParseTuple(args, "|On:split", &subobj, &maxsplit)) + return NULL; + if (maxsplit < 0) + maxsplit = PY_SSIZE_T_MAX; + if (subobj == Py_None) + return stringlib_split_whitespace((PyObject*) self, s, len, maxsplit); + if (_getbuffer(subobj, &vsub) < 0) + return NULL; + sub = vsub.buf; + n = vsub.len; + + list = stringlib_split((PyObject*) self, s, len, sub, n, maxsplit); + PyBuffer_Release(&vsub); + return list; } PyDoc_STRVAR(partition__doc__, @@ -1043,21 +1043,21 @@ static PyObject * bytes_partition(PyBytesObject *self, PyObject *sep_obj) { - const char *sep; - Py_ssize_t sep_len; + const char *sep; + Py_ssize_t sep_len; + + if (PyBytes_Check(sep_obj)) { + sep = PyBytes_AS_STRING(sep_obj); + sep_len = PyBytes_GET_SIZE(sep_obj); + } + else if (PyObject_AsCharBuffer(sep_obj, &sep, &sep_len)) + return NULL; - if (PyBytes_Check(sep_obj)) { - sep = PyBytes_AS_STRING(sep_obj); - sep_len = PyBytes_GET_SIZE(sep_obj); - } - else if (PyObject_AsCharBuffer(sep_obj, &sep, &sep_len)) - return NULL; - - return stringlib_partition( - (PyObject*) self, - PyBytes_AS_STRING(self), PyBytes_GET_SIZE(self), - sep_obj, sep, sep_len - ); + return stringlib_partition( + (PyObject*) self, + PyBytes_AS_STRING(self), PyBytes_GET_SIZE(self), + sep_obj, sep, sep_len + ); } PyDoc_STRVAR(rpartition__doc__, @@ -1071,21 +1071,21 @@ static PyObject * bytes_rpartition(PyBytesObject *self, PyObject *sep_obj) { - const char *sep; - Py_ssize_t sep_len; + const char *sep; + Py_ssize_t sep_len; - if (PyBytes_Check(sep_obj)) { - sep = PyBytes_AS_STRING(sep_obj); - sep_len = PyBytes_GET_SIZE(sep_obj); - } - else if (PyObject_AsCharBuffer(sep_obj, &sep, &sep_len)) - return NULL; - - return stringlib_rpartition( - (PyObject*) self, - PyBytes_AS_STRING(self), PyBytes_GET_SIZE(self), - sep_obj, sep, sep_len - ); + if (PyBytes_Check(sep_obj)) { + sep = PyBytes_AS_STRING(sep_obj); + sep_len = PyBytes_GET_SIZE(sep_obj); + } + else if (PyObject_AsCharBuffer(sep_obj, &sep, &sep_len)) + return NULL; + + return stringlib_rpartition( + (PyObject*) self, + PyBytes_AS_STRING(self), PyBytes_GET_SIZE(self), + sep_obj, sep, sep_len + ); } PyDoc_STRVAR(rsplit__doc__, @@ -1101,26 +1101,26 @@ static PyObject * bytes_rsplit(PyBytesObject *self, PyObject *args) { - Py_ssize_t len = PyBytes_GET_SIZE(self), n; - Py_ssize_t maxsplit = -1; - const char *s = PyBytes_AS_STRING(self), *sub; - Py_buffer vsub; - PyObject *list, *subobj = Py_None; - - if (!PyArg_ParseTuple(args, "|On:rsplit", &subobj, &maxsplit)) - return NULL; - if (maxsplit < 0) - maxsplit = PY_SSIZE_T_MAX; - if (subobj == Py_None) - return stringlib_rsplit_whitespace((PyObject*) self, s, len, maxsplit); - if (_getbuffer(subobj, &vsub) < 0) - return NULL; - sub = vsub.buf; - n = vsub.len; - - list = stringlib_rsplit((PyObject*) self, s, len, sub, n, maxsplit); - PyBuffer_Release(&vsub); - return list; + Py_ssize_t len = PyBytes_GET_SIZE(self), n; + Py_ssize_t maxsplit = -1; + const char *s = PyBytes_AS_STRING(self), *sub; + Py_buffer vsub; + PyObject *list, *subobj = Py_None; + + if (!PyArg_ParseTuple(args, "|On:rsplit", &subobj, &maxsplit)) + return NULL; + if (maxsplit < 0) + maxsplit = PY_SSIZE_T_MAX; + if (subobj == Py_None) + return stringlib_rsplit_whitespace((PyObject*) self, s, len, maxsplit); + if (_getbuffer(subobj, &vsub) < 0) + return NULL; + sub = vsub.buf; + n = vsub.len; + + list = stringlib_rsplit((PyObject*) self, s, len, sub, n, maxsplit); + PyBuffer_Release(&vsub); + return list; } @@ -1133,156 +1133,156 @@ static PyObject * bytes_join(PyObject *self, PyObject *orig) { - char *sep = PyBytes_AS_STRING(self); - const Py_ssize_t seplen = PyBytes_GET_SIZE(self); - PyObject *res = NULL; - char *p; - Py_ssize_t seqlen = 0; - size_t sz = 0; - Py_ssize_t i; - PyObject *seq, *item; - - seq = PySequence_Fast(orig, ""); - if (seq == NULL) { - return NULL; - } - - seqlen = PySequence_Size(seq); - if (seqlen == 0) { - Py_DECREF(seq); - return PyBytes_FromString(""); - } - if (seqlen == 1) { - item = PySequence_Fast_GET_ITEM(seq, 0); - if (PyBytes_CheckExact(item)) { - Py_INCREF(item); - Py_DECREF(seq); - return item; - } - } - - /* There are at least two things to join, or else we have a subclass - * of the builtin types in the sequence. - * Do a pre-pass to figure out the total amount of space we'll - * need (sz), and see whether all argument are bytes. - */ - /* XXX Shouldn't we use _getbuffer() on these items instead? */ - for (i = 0; i < seqlen; i++) { - const size_t old_sz = sz; - item = PySequence_Fast_GET_ITEM(seq, i); - if (!PyBytes_Check(item) && !PyByteArray_Check(item)) { - PyErr_Format(PyExc_TypeError, - "sequence item %zd: expected bytes," - " %.80s found", - i, Py_TYPE(item)->tp_name); - Py_DECREF(seq); - return NULL; - } - sz += Py_SIZE(item); - if (i != 0) - sz += seplen; - if (sz < old_sz || sz > PY_SSIZE_T_MAX) { - PyErr_SetString(PyExc_OverflowError, - "join() result is too long for bytes"); - Py_DECREF(seq); - return NULL; - } - } - - /* Allocate result space. */ - res = PyBytes_FromStringAndSize((char*)NULL, sz); - if (res == NULL) { - Py_DECREF(seq); - return NULL; - } - - /* Catenate everything. */ - /* I'm not worried about a PyByteArray item growing because there's - nowhere in this function where we release the GIL. */ - p = PyBytes_AS_STRING(res); - for (i = 0; i < seqlen; ++i) { - size_t n; - char *q; - if (i) { - Py_MEMCPY(p, sep, seplen); - p += seplen; - } - item = PySequence_Fast_GET_ITEM(seq, i); - n = Py_SIZE(item); - if (PyBytes_Check(item)) - q = PyBytes_AS_STRING(item); - else - q = PyByteArray_AS_STRING(item); - Py_MEMCPY(p, q, n); - p += n; - } + char *sep = PyBytes_AS_STRING(self); + const Py_ssize_t seplen = PyBytes_GET_SIZE(self); + PyObject *res = NULL; + char *p; + Py_ssize_t seqlen = 0; + size_t sz = 0; + Py_ssize_t i; + PyObject *seq, *item; + + seq = PySequence_Fast(orig, ""); + if (seq == NULL) { + return NULL; + } - Py_DECREF(seq); - return res; + seqlen = PySequence_Size(seq); + if (seqlen == 0) { + Py_DECREF(seq); + return PyBytes_FromString(""); + } + if (seqlen == 1) { + item = PySequence_Fast_GET_ITEM(seq, 0); + if (PyBytes_CheckExact(item)) { + Py_INCREF(item); + Py_DECREF(seq); + return item; + } + } + + /* There are at least two things to join, or else we have a subclass + * of the builtin types in the sequence. + * Do a pre-pass to figure out the total amount of space we'll + * need (sz), and see whether all argument are bytes. + */ + /* XXX Shouldn't we use _getbuffer() on these items instead? */ + for (i = 0; i < seqlen; i++) { + const size_t old_sz = sz; + item = PySequence_Fast_GET_ITEM(seq, i); + if (!PyBytes_Check(item) && !PyByteArray_Check(item)) { + PyErr_Format(PyExc_TypeError, + "sequence item %zd: expected bytes," + " %.80s found", + i, Py_TYPE(item)->tp_name); + Py_DECREF(seq); + return NULL; + } + sz += Py_SIZE(item); + if (i != 0) + sz += seplen; + if (sz < old_sz || sz > PY_SSIZE_T_MAX) { + PyErr_SetString(PyExc_OverflowError, + "join() result is too long for bytes"); + Py_DECREF(seq); + return NULL; + } + } + + /* Allocate result space. */ + res = PyBytes_FromStringAndSize((char*)NULL, sz); + if (res == NULL) { + Py_DECREF(seq); + return NULL; + } + + /* Catenate everything. */ + /* I'm not worried about a PyByteArray item growing because there's + nowhere in this function where we release the GIL. */ + p = PyBytes_AS_STRING(res); + for (i = 0; i < seqlen; ++i) { + size_t n; + char *q; + if (i) { + Py_MEMCPY(p, sep, seplen); + p += seplen; + } + item = PySequence_Fast_GET_ITEM(seq, i); + n = Py_SIZE(item); + if (PyBytes_Check(item)) + q = PyBytes_AS_STRING(item); + else + q = PyByteArray_AS_STRING(item); + Py_MEMCPY(p, q, n); + p += n; + } + + Py_DECREF(seq); + return res; } PyObject * _PyBytes_Join(PyObject *sep, PyObject *x) { - assert(sep != NULL && PyBytes_Check(sep)); - assert(x != NULL); - return bytes_join(sep, x); + assert(sep != NULL && PyBytes_Check(sep)); + assert(x != NULL); + return bytes_join(sep, x); } /* helper macro to fixup start/end slice values */ #define ADJUST_INDICES(start, end, len) \ - if (end > len) \ - end = len; \ - else if (end < 0) { \ - end += len; \ - if (end < 0) \ - end = 0; \ - } \ - if (start < 0) { \ - start += len; \ - if (start < 0) \ - start = 0; \ - } + if (end > len) \ + end = len; \ + else if (end < 0) { \ + end += len; \ + if (end < 0) \ + end = 0; \ + } \ + if (start < 0) { \ + start += len; \ + if (start < 0) \ + start = 0; \ + } Py_LOCAL_INLINE(Py_ssize_t) bytes_find_internal(PyBytesObject *self, PyObject *args, int dir) { - PyObject *subobj; - const char *sub; - Py_ssize_t sub_len; - Py_ssize_t start=0, end=PY_SSIZE_T_MAX; - PyObject *obj_start=Py_None, *obj_end=Py_None; - - if (!PyArg_ParseTuple(args, "O|OO:find/rfind/index/rindex", &subobj, - &obj_start, &obj_end)) - return -2; - /* To support None in "start" and "end" arguments, meaning - the same as if they were not passed. - */ - if (obj_start != Py_None) - if (!_PyEval_SliceIndex(obj_start, &start)) - return -2; - if (obj_end != Py_None) - if (!_PyEval_SliceIndex(obj_end, &end)) - return -2; - - if (PyBytes_Check(subobj)) { - sub = PyBytes_AS_STRING(subobj); - sub_len = PyBytes_GET_SIZE(subobj); - } - else if (PyObject_AsCharBuffer(subobj, &sub, &sub_len)) - /* XXX - the "expected a character buffer object" is pretty - confusing for a non-expert. remap to something else ? */ - return -2; - - if (dir > 0) - return stringlib_find_slice( - PyBytes_AS_STRING(self), PyBytes_GET_SIZE(self), - sub, sub_len, start, end); - else - return stringlib_rfind_slice( - PyBytes_AS_STRING(self), PyBytes_GET_SIZE(self), - sub, sub_len, start, end); + PyObject *subobj; + const char *sub; + Py_ssize_t sub_len; + Py_ssize_t start=0, end=PY_SSIZE_T_MAX; + PyObject *obj_start=Py_None, *obj_end=Py_None; + + if (!PyArg_ParseTuple(args, "O|OO:find/rfind/index/rindex", &subobj, + &obj_start, &obj_end)) + return -2; + /* To support None in "start" and "end" arguments, meaning + the same as if they were not passed. + */ + if (obj_start != Py_None) + if (!_PyEval_SliceIndex(obj_start, &start)) + return -2; + if (obj_end != Py_None) + if (!_PyEval_SliceIndex(obj_end, &end)) + return -2; + + if (PyBytes_Check(subobj)) { + sub = PyBytes_AS_STRING(subobj); + sub_len = PyBytes_GET_SIZE(subobj); + } + else if (PyObject_AsCharBuffer(subobj, &sub, &sub_len)) + /* XXX - the "expected a character buffer object" is pretty + confusing for a non-expert. remap to something else ? */ + return -2; + + if (dir > 0) + return stringlib_find_slice( + PyBytes_AS_STRING(self), PyBytes_GET_SIZE(self), + sub, sub_len, start, end); + else + return stringlib_rfind_slice( + PyBytes_AS_STRING(self), PyBytes_GET_SIZE(self), + sub, sub_len, start, end); } @@ -1298,10 +1298,10 @@ static PyObject * bytes_find(PyBytesObject *self, PyObject *args) { - Py_ssize_t result = bytes_find_internal(self, args, +1); - if (result == -2) - return NULL; - return PyLong_FromSsize_t(result); + Py_ssize_t result = bytes_find_internal(self, args, +1); + if (result == -2) + return NULL; + return PyLong_FromSsize_t(result); } @@ -1313,15 +1313,15 @@ static PyObject * bytes_index(PyBytesObject *self, PyObject *args) { - Py_ssize_t result = bytes_find_internal(self, args, +1); - if (result == -2) - return NULL; - if (result == -1) { - PyErr_SetString(PyExc_ValueError, - "substring not found"); - return NULL; - } - return PyLong_FromSsize_t(result); + Py_ssize_t result = bytes_find_internal(self, args, +1); + if (result == -2) + return NULL; + if (result == -1) { + PyErr_SetString(PyExc_ValueError, + "substring not found"); + return NULL; + } + return PyLong_FromSsize_t(result); } @@ -1337,10 +1337,10 @@ static PyObject * bytes_rfind(PyBytesObject *self, PyObject *args) { - Py_ssize_t result = bytes_find_internal(self, args, -1); - if (result == -2) - return NULL; - return PyLong_FromSsize_t(result); + Py_ssize_t result = bytes_find_internal(self, args, -1); + if (result == -2) + return NULL; + return PyLong_FromSsize_t(result); } @@ -1352,101 +1352,101 @@ static PyObject * bytes_rindex(PyBytesObject *self, PyObject *args) { - Py_ssize_t result = bytes_find_internal(self, args, -1); - if (result == -2) - return NULL; - if (result == -1) { - PyErr_SetString(PyExc_ValueError, - "substring not found"); - return NULL; - } - return PyLong_FromSsize_t(result); + Py_ssize_t result = bytes_find_internal(self, args, -1); + if (result == -2) + return NULL; + if (result == -1) { + PyErr_SetString(PyExc_ValueError, + "substring not found"); + return NULL; + } + return PyLong_FromSsize_t(result); } 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 (_getbuffer(sepobj, &vsep) < 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_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 (_getbuffer(sepobj, &vsep) < 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; + char *s = PyBytes_AS_STRING(self); + Py_ssize_t len = PyBytes_GET_SIZE(self), i, j; + + i = 0; + if (striptype != RIGHTSTRIP) { + while (i < len && ISSPACE(s[i])) { + i++; + } + } + + j = len; + if (striptype != LEFTSTRIP) { + do { + j--; + } while (j >= i && ISSPACE(s[j])); + j++; + } - i = 0; - if (striptype != RIGHTSTRIP) { - while (i < len && ISSPACE(s[i])) { - i++; - } - } - - j = len; - if (striptype != LEFTSTRIP) { - do { - j--; - } while (j >= i && 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); + 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 *args) { - PyObject *sep = NULL; + PyObject *sep = NULL; - if (!PyArg_ParseTuple(args, (char *)stripformat[striptype], &sep)) - return NULL; + if (!PyArg_ParseTuple(args, (char *)stripformat[striptype], &sep)) + return NULL; - if (sep != NULL && sep != Py_None) { - return do_xstrip(self, striptype, sep); - } - return do_strip(self, striptype); + if (sep != NULL && sep != Py_None) { + return do_xstrip(self, striptype, sep); + } + return do_strip(self, striptype); } @@ -1458,10 +1458,10 @@ static PyObject * bytes_strip(PyBytesObject *self, PyObject *args) { - if (PyTuple_GET_SIZE(args) == 0) - return do_strip(self, BOTHSTRIP); /* Common case */ - else - return do_argstrip(self, BOTHSTRIP, args); + if (PyTuple_GET_SIZE(args) == 0) + return do_strip(self, BOTHSTRIP); /* Common case */ + else + return do_argstrip(self, BOTHSTRIP, args); } @@ -1473,10 +1473,10 @@ static PyObject * bytes_lstrip(PyBytesObject *self, PyObject *args) { - if (PyTuple_GET_SIZE(args) == 0) - return do_strip(self, LEFTSTRIP); /* Common case */ - else - return do_argstrip(self, LEFTSTRIP, args); + if (PyTuple_GET_SIZE(args) == 0) + return do_strip(self, LEFTSTRIP); /* Common case */ + else + return do_argstrip(self, LEFTSTRIP, args); } @@ -1488,10 +1488,10 @@ static PyObject * bytes_rstrip(PyBytesObject *self, PyObject *args) { - if (PyTuple_GET_SIZE(args) == 0) - return do_strip(self, RIGHTSTRIP); /* Common case */ - else - return do_argstrip(self, RIGHTSTRIP, args); + if (PyTuple_GET_SIZE(args) == 0) + return do_strip(self, RIGHTSTRIP); /* Common case */ + else + return do_argstrip(self, RIGHTSTRIP, args); } @@ -1505,27 +1505,27 @@ static PyObject * bytes_count(PyBytesObject *self, PyObject *args) { - PyObject *sub_obj; - const char *str = PyBytes_AS_STRING(self), *sub; - Py_ssize_t sub_len; - Py_ssize_t start = 0, end = PY_SSIZE_T_MAX; - - if (!PyArg_ParseTuple(args, "O|O&O&:count", &sub_obj, - _PyEval_SliceIndex, &start, _PyEval_SliceIndex, &end)) - return NULL; - - if (PyBytes_Check(sub_obj)) { - sub = PyBytes_AS_STRING(sub_obj); - sub_len = PyBytes_GET_SIZE(sub_obj); - } - else if (PyObject_AsCharBuffer(sub_obj, &sub, &sub_len)) - return NULL; - - ADJUST_INDICES(start, end, PyBytes_GET_SIZE(self)); - - return PyLong_FromSsize_t( - stringlib_count(str + start, end - start, sub, sub_len, PY_SSIZE_T_MAX) - ); + PyObject *sub_obj; + const char *str = PyBytes_AS_STRING(self), *sub; + Py_ssize_t sub_len; + Py_ssize_t start = 0, end = PY_SSIZE_T_MAX; + + if (!PyArg_ParseTuple(args, "O|O&O&:count", &sub_obj, + _PyEval_SliceIndex, &start, _PyEval_SliceIndex, &end)) + return NULL; + + if (PyBytes_Check(sub_obj)) { + sub = PyBytes_AS_STRING(sub_obj); + sub_len = PyBytes_GET_SIZE(sub_obj); + } + else if (PyObject_AsCharBuffer(sub_obj, &sub, &sub_len)) + return NULL; + + ADJUST_INDICES(start, end, PyBytes_GET_SIZE(self)); + + return PyLong_FromSsize_t( + stringlib_count(str + start, end - start, sub, sub_len, PY_SSIZE_T_MAX) + ); } @@ -1540,110 +1540,110 @@ static PyObject * bytes_translate(PyBytesObject *self, PyObject *args) { - register char *input, *output; - const char *table; - register Py_ssize_t i, c, changed = 0; - PyObject *input_obj = (PyObject*)self; - const char *output_start, *del_table=NULL; - Py_ssize_t inlen, tablen, dellen = 0; - PyObject *result; - int trans_table[256]; - PyObject *tableobj, *delobj = NULL; - - if (!PyArg_UnpackTuple(args, "translate", 1, 2, - &tableobj, &delobj)) - return NULL; - - if (PyBytes_Check(tableobj)) { - table = PyBytes_AS_STRING(tableobj); - tablen = PyBytes_GET_SIZE(tableobj); - } - else if (tableobj == Py_None) { - table = NULL; - tablen = 256; - } - else if (PyObject_AsCharBuffer(tableobj, &table, &tablen)) - return NULL; - - if (tablen != 256) { - PyErr_SetString(PyExc_ValueError, - "translation table must be 256 characters long"); - return NULL; - } - - if (delobj != NULL) { - if (PyBytes_Check(delobj)) { - del_table = PyBytes_AS_STRING(delobj); - dellen = PyBytes_GET_SIZE(delobj); - } - else if (PyObject_AsCharBuffer(delobj, &del_table, &dellen)) - return NULL; - } - else { - del_table = NULL; - dellen = 0; - } - - inlen = PyBytes_GET_SIZE(input_obj); - result = PyBytes_FromStringAndSize((char *)NULL, inlen); - if (result == NULL) - return NULL; - output_start = output = PyBytes_AsString(result); - input = PyBytes_AS_STRING(input_obj); - - if (dellen == 0 && table != NULL) { - /* If no deletions are required, use faster code */ - for (i = inlen; --i >= 0; ) { - c = Py_CHARMASK(*input++); - if (Py_CHARMASK((*output++ = table[c])) != c) - changed = 1; - } - if (changed || !PyBytes_CheckExact(input_obj)) - return result; - Py_DECREF(result); - Py_INCREF(input_obj); - return input_obj; - } - - if (table == 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[i]); - } - - for (i = 0; i < dellen; i++) - trans_table[(int) Py_CHARMASK(del_table[i])] = -1; - - 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; + register char *input, *output; + const char *table; + register Py_ssize_t i, c, changed = 0; + PyObject *input_obj = (PyObject*)self; + const char *output_start, *del_table=NULL; + Py_ssize_t inlen, tablen, dellen = 0; + PyObject *result; + int trans_table[256]; + PyObject *tableobj, *delobj = NULL; + + if (!PyArg_UnpackTuple(args, "translate", 1, 2, + &tableobj, &delobj)) + return NULL; + + if (PyBytes_Check(tableobj)) { + table = PyBytes_AS_STRING(tableobj); + tablen = PyBytes_GET_SIZE(tableobj); + } + else if (tableobj == Py_None) { + table = NULL; + tablen = 256; + } + else if (PyObject_AsCharBuffer(tableobj, &table, &tablen)) + return NULL; + + if (tablen != 256) { + PyErr_SetString(PyExc_ValueError, + "translation table must be 256 characters long"); + return NULL; + } + + if (delobj != NULL) { + if (PyBytes_Check(delobj)) { + del_table = PyBytes_AS_STRING(delobj); + dellen = PyBytes_GET_SIZE(delobj); + } + else if (PyObject_AsCharBuffer(delobj, &del_table, &dellen)) + return NULL; + } + else { + del_table = NULL; + dellen = 0; + } + + inlen = PyBytes_GET_SIZE(input_obj); + result = PyBytes_FromStringAndSize((char *)NULL, inlen); + if (result == NULL) + return NULL; + output_start = output = PyBytes_AsString(result); + input = PyBytes_AS_STRING(input_obj); + + if (dellen == 0 && table != NULL) { + /* If no deletions are required, use faster code */ + for (i = inlen; --i >= 0; ) { + c = Py_CHARMASK(*input++); + if (Py_CHARMASK((*output++ = table[c])) != c) + changed = 1; + } + if (changed || !PyBytes_CheckExact(input_obj)) + return result; + Py_DECREF(result); + Py_INCREF(input_obj); + return input_obj; + } + + if (table == 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[i]); + } + + for (i = 0; i < dellen; i++) + trans_table[(int) Py_CHARMASK(del_table[i])] = -1; + + 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; } static PyObject * bytes_maketrans(PyObject *null, PyObject *args) { - return _Py_bytes_maketrans(args); + return _Py_bytes_maketrans(args); } /* find and count characters and substrings */ -#define findchar(target, target_len, c) \ +#define findchar(target, target_len, c) \ ((char *)memchr((const void *)(target), c, target_len)) /* String ops must return a string. */ @@ -1651,29 +1651,29 @@ Py_LOCAL(PyBytesObject *) return_self(PyBytesObject *self) { - if (PyBytes_CheckExact(self)) { - Py_INCREF(self); - return self; - } - return (PyBytesObject *)PyBytes_FromStringAndSize( - PyBytes_AS_STRING(self), - PyBytes_GET_SIZE(self)); + if (PyBytes_CheckExact(self)) { + Py_INCREF(self); + return self; + } + return (PyBytesObject *)PyBytes_FromStringAndSize( + PyBytes_AS_STRING(self), + PyBytes_GET_SIZE(self)); } Py_LOCAL_INLINE(Py_ssize_t) countchar(const char *target, int target_len, char c, Py_ssize_t maxcount) { - Py_ssize_t count=0; - const char *start=target; - const char *end=target+target_len; - - while ( (start=findchar(start, end-start, c)) != NULL ) { - count++; - if (count >= maxcount) - break; - start += 1; - } - return count; + Py_ssize_t count=0; + const char *start=target; + const char *end=target+target_len; + + while ( (start=findchar(start, end-start, c)) != NULL ) { + count++; + if (count >= maxcount) + break; + start += 1; + } + return count; } @@ -1682,467 +1682,467 @@ /* len(self)>=1, from="", len(to)>=1, maxcount>=1 */ Py_LOCAL(PyBytesObject *) replace_interleave(PyBytesObject *self, - const char *to_s, Py_ssize_t to_len, - Py_ssize_t maxcount) + const char *to_s, Py_ssize_t to_len, + Py_ssize_t maxcount) { - char *self_s, *result_s; - Py_ssize_t self_len, result_len; - Py_ssize_t count, i, product; - PyBytesObject *result; - - self_len = PyBytes_GET_SIZE(self); - - /* 1 at the end plus 1 after every character */ - count = self_len+1; - if (maxcount < count) - count = maxcount; - - /* Check for overflow */ - /* result_len = count * to_len + self_len; */ - product = count * to_len; - if (product / to_len != count) { - PyErr_SetString(PyExc_OverflowError, - "replacement bytes are too long"); - return NULL; - } - result_len = product + self_len; - if (result_len < 0) { - PyErr_SetString(PyExc_OverflowError, - "replacement bytes are too long"); - return NULL; - } - - if (! (result = (PyBytesObject *) - PyBytes_FromStringAndSize(NULL, result_len)) ) - return NULL; - - self_s = PyBytes_AS_STRING(self); - result_s = PyBytes_AS_STRING(result); - - /* TODO: special case single character, which doesn't need memcpy */ - - /* Lay the first one down (guaranteed this will occur) */ - Py_MEMCPY(result_s, to_s, to_len); - result_s += to_len; - count -= 1; - - for (i=0; i=1, len(from)==1, to="", maxcount>=1 */ Py_LOCAL(PyBytesObject *) replace_delete_single_character(PyBytesObject *self, - char from_c, Py_ssize_t maxcount) + char from_c, Py_ssize_t maxcount) { - char *self_s, *result_s; - char *start, *next, *end; - Py_ssize_t self_len, result_len; - Py_ssize_t count; - PyBytesObject *result; - - self_len = PyBytes_GET_SIZE(self); - self_s = PyBytes_AS_STRING(self); - - count = countchar(self_s, self_len, from_c, maxcount); - if (count == 0) { - return return_self(self); - } - - result_len = self_len - count; /* from_len == 1 */ - assert(result_len>=0); - - if ( (result = (PyBytesObject *) - PyBytes_FromStringAndSize(NULL, result_len)) == NULL) - return NULL; - result_s = PyBytes_AS_STRING(result); - - start = self_s; - end = self_s + self_len; - while (count-- > 0) { - next = findchar(start, end-start, from_c); - if (next == NULL) - break; - Py_MEMCPY(result_s, start, next-start); - result_s += (next-start); - start = next+1; - } - Py_MEMCPY(result_s, start, end-start); + char *self_s, *result_s; + char *start, *next, *end; + Py_ssize_t self_len, result_len; + Py_ssize_t count; + PyBytesObject *result; + + self_len = PyBytes_GET_SIZE(self); + self_s = PyBytes_AS_STRING(self); + + count = countchar(self_s, self_len, from_c, maxcount); + if (count == 0) { + return return_self(self); + } + + result_len = self_len - count; /* from_len == 1 */ + assert(result_len>=0); - return result; + if ( (result = (PyBytesObject *) + PyBytes_FromStringAndSize(NULL, result_len)) == NULL) + return NULL; + result_s = PyBytes_AS_STRING(result); + + start = self_s; + end = self_s + self_len; + while (count-- > 0) { + next = findchar(start, end-start, from_c); + if (next == NULL) + break; + Py_MEMCPY(result_s, start, next-start); + result_s += (next-start); + start = next+1; + } + Py_MEMCPY(result_s, start, end-start); + + return result; } /* len(self)>=1, len(from)>=2, to="", maxcount>=1 */ Py_LOCAL(PyBytesObject *) replace_delete_substring(PyBytesObject *self, - const char *from_s, Py_ssize_t from_len, - Py_ssize_t maxcount) { - char *self_s, *result_s; - char *start, *next, *end; - Py_ssize_t self_len, result_len; - Py_ssize_t count, offset; - PyBytesObject *result; - - self_len = PyBytes_GET_SIZE(self); - self_s = PyBytes_AS_STRING(self); - - count = stringlib_count(self_s, self_len, - from_s, from_len, - maxcount); - - if (count == 0) { - /* no matches */ - return return_self(self); - } - - result_len = self_len - (count * from_len); - assert (result_len>=0); - - if ( (result = (PyBytesObject *) - PyBytes_FromStringAndSize(NULL, result_len)) == NULL ) - return NULL; - - result_s = PyBytes_AS_STRING(result); - - start = self_s; - end = self_s + self_len; - while (count-- > 0) { - offset = stringlib_find(start, end-start, - from_s, from_len, - 0); - if (offset == -1) - break; - next = start + offset; - - Py_MEMCPY(result_s, start, next-start); - - result_s += (next-start); - start = next+from_len; - } - Py_MEMCPY(result_s, start, end-start); - return result; + const char *from_s, Py_ssize_t from_len, + Py_ssize_t maxcount) { + char *self_s, *result_s; + char *start, *next, *end; + Py_ssize_t self_len, result_len; + Py_ssize_t count, offset; + PyBytesObject *result; + + self_len = PyBytes_GET_SIZE(self); + self_s = PyBytes_AS_STRING(self); + + count = stringlib_count(self_s, self_len, + from_s, from_len, + maxcount); + + if (count == 0) { + /* no matches */ + return return_self(self); + } + + result_len = self_len - (count * from_len); + assert (result_len>=0); + + if ( (result = (PyBytesObject *) + PyBytes_FromStringAndSize(NULL, result_len)) == NULL ) + return NULL; + + result_s = PyBytes_AS_STRING(result); + + start = self_s; + end = self_s + self_len; + while (count-- > 0) { + offset = stringlib_find(start, end-start, + from_s, from_len, + 0); + if (offset == -1) + break; + next = start + offset; + + Py_MEMCPY(result_s, start, next-start); + + result_s += (next-start); + start = next+from_len; + } + Py_MEMCPY(result_s, start, end-start); + return result; } /* len(self)>=1, len(from)==len(to)==1, maxcount>=1 */ Py_LOCAL(PyBytesObject *) replace_single_character_in_place(PyBytesObject *self, - char from_c, char to_c, - Py_ssize_t maxcount) + char from_c, char to_c, + Py_ssize_t maxcount) { - char *self_s, *result_s, *start, *end, *next; - Py_ssize_t self_len; - PyBytesObject *result; - - /* The result string will be the same size */ - self_s = PyBytes_AS_STRING(self); - self_len = PyBytes_GET_SIZE(self); - - next = findchar(self_s, self_len, from_c); - - if (next == NULL) { - /* No matches; return the original string */ - return return_self(self); - } - - /* Need to make a new string */ - result = (PyBytesObject *) PyBytes_FromStringAndSize(NULL, self_len); - if (result == NULL) - return NULL; - result_s = PyBytes_AS_STRING(result); - Py_MEMCPY(result_s, self_s, self_len); - - /* change everything in-place, starting with this one */ - start = result_s + (next-self_s); - *start = to_c; - start++; - end = result_s + self_len; - - while (--maxcount > 0) { - next = findchar(start, end-start, from_c); - if (next == NULL) - break; - *next = to_c; - start = next+1; - } + char *self_s, *result_s, *start, *end, *next; + Py_ssize_t self_len; + PyBytesObject *result; + + /* The result string will be the same size */ + self_s = PyBytes_AS_STRING(self); + self_len = PyBytes_GET_SIZE(self); + + next = findchar(self_s, self_len, from_c); + + if (next == NULL) { + /* No matches; return the original string */ + return return_self(self); + } - return result; + /* Need to make a new string */ + result = (PyBytesObject *) PyBytes_FromStringAndSize(NULL, self_len); + if (result == NULL) + return NULL; + result_s = PyBytes_AS_STRING(result); + Py_MEMCPY(result_s, self_s, self_len); + + /* change everything in-place, starting with this one */ + start = result_s + (next-self_s); + *start = to_c; + start++; + end = result_s + self_len; + + while (--maxcount > 0) { + next = findchar(start, end-start, from_c); + if (next == NULL) + break; + *next = to_c; + start = next+1; + } + + return result; } /* len(self)>=1, len(from)==len(to)>=2, maxcount>=1 */ Py_LOCAL(PyBytesObject *) replace_substring_in_place(PyBytesObject *self, - const char *from_s, Py_ssize_t from_len, - const char *to_s, Py_ssize_t to_len, - Py_ssize_t maxcount) -{ - char *result_s, *start, *end; - char *self_s; - Py_ssize_t self_len, offset; - PyBytesObject *result; - - /* The result string will be the same size */ - - self_s = PyBytes_AS_STRING(self); - self_len = PyBytes_GET_SIZE(self); - - offset = stringlib_find(self_s, self_len, - from_s, from_len, - 0); - if (offset == -1) { - /* No matches; return the original string */ - return return_self(self); - } - - /* Need to make a new string */ - result = (PyBytesObject *) PyBytes_FromStringAndSize(NULL, self_len); - if (result == NULL) - return NULL; - result_s = PyBytes_AS_STRING(result); - Py_MEMCPY(result_s, self_s, self_len); - - /* change everything in-place, starting with this one */ - start = result_s + offset; - Py_MEMCPY(start, to_s, from_len); - start += from_len; - end = result_s + self_len; - - while ( --maxcount > 0) { - offset = stringlib_find(start, end-start, - from_s, from_len, - 0); - if (offset==-1) - break; - Py_MEMCPY(start+offset, to_s, from_len); - start += offset+from_len; - } + const char *from_s, Py_ssize_t from_len, + const char *to_s, Py_ssize_t to_len, + Py_ssize_t maxcount) +{ + char *result_s, *start, *end; + char *self_s; + Py_ssize_t self_len, offset; + PyBytesObject *result; + + /* The result string will be the same size */ + + self_s = PyBytes_AS_STRING(self); + self_len = PyBytes_GET_SIZE(self); + + offset = stringlib_find(self_s, self_len, + from_s, from_len, + 0); + if (offset == -1) { + /* No matches; return the original string */ + return return_self(self); + } - return result; + /* Need to make a new string */ + result = (PyBytesObject *) PyBytes_FromStringAndSize(NULL, self_len); + if (result == NULL) + return NULL; + result_s = PyBytes_AS_STRING(result); + Py_MEMCPY(result_s, self_s, self_len); + + /* change everything in-place, starting with this one */ + start = result_s + offset; + Py_MEMCPY(start, to_s, from_len); + start += from_len; + end = result_s + self_len; + + while ( --maxcount > 0) { + offset = stringlib_find(start, end-start, + from_s, from_len, + 0); + if (offset==-1) + break; + Py_MEMCPY(start+offset, to_s, from_len); + start += offset+from_len; + } + + return result; } /* len(self)>=1, len(from)==1, len(to)>=2, maxcount>=1 */ Py_LOCAL(PyBytesObject *) replace_single_character(PyBytesObject *self, - char from_c, - const char *to_s, Py_ssize_t to_len, - Py_ssize_t maxcount) -{ - char *self_s, *result_s; - char *start, *next, *end; - Py_ssize_t self_len, result_len; - Py_ssize_t count, product; - PyBytesObject *result; - - self_s = PyBytes_AS_STRING(self); - self_len = PyBytes_GET_SIZE(self); - - count = countchar(self_s, self_len, from_c, maxcount); - if (count == 0) { - /* no matches, return unchanged */ - return return_self(self); - } - - /* use the difference between current and new, hence the "-1" */ - /* result_len = self_len + count * (to_len-1) */ - product = count * (to_len-1); - if (product / (to_len-1) != count) { - PyErr_SetString(PyExc_OverflowError, - "replacement bytes are too long"); - return NULL; - } - result_len = self_len + product; - if (result_len < 0) { - PyErr_SetString(PyExc_OverflowError, - "replacment bytes are too long"); - return NULL; - } - - if ( (result = (PyBytesObject *) - PyBytes_FromStringAndSize(NULL, result_len)) == NULL) - return NULL; - result_s = PyBytes_AS_STRING(result); - - start = self_s; - end = self_s + self_len; - while (count-- > 0) { - next = findchar(start, end-start, from_c); - if (next == NULL) - break; - - if (next == start) { - /* replace with the 'to' */ - Py_MEMCPY(result_s, to_s, to_len); - result_s += to_len; - start += 1; - } else { - /* copy the unchanged old then the 'to' */ - Py_MEMCPY(result_s, start, next-start); - result_s += (next-start); - Py_MEMCPY(result_s, to_s, to_len); - result_s += to_len; - start = next+1; - } - } - /* Copy the remainder of the remaining string */ - Py_MEMCPY(result_s, start, end-start); + char from_c, + const char *to_s, Py_ssize_t to_len, + Py_ssize_t maxcount) +{ + char *self_s, *result_s; + char *start, *next, *end; + Py_ssize_t self_len, result_len; + Py_ssize_t count, product; + PyBytesObject *result; + + self_s = PyBytes_AS_STRING(self); + self_len = PyBytes_GET_SIZE(self); + + count = countchar(self_s, self_len, from_c, maxcount); + if (count == 0) { + /* no matches, return unchanged */ + return return_self(self); + } + + /* use the difference between current and new, hence the "-1" */ + /* result_len = self_len + count * (to_len-1) */ + product = count * (to_len-1); + if (product / (to_len-1) != count) { + PyErr_SetString(PyExc_OverflowError, + "replacement bytes are too long"); + return NULL; + } + result_len = self_len + product; + if (result_len < 0) { + PyErr_SetString(PyExc_OverflowError, + "replacment bytes are too long"); + return NULL; + } - return result; + if ( (result = (PyBytesObject *) + PyBytes_FromStringAndSize(NULL, result_len)) == NULL) + return NULL; + result_s = PyBytes_AS_STRING(result); + + start = self_s; + end = self_s + self_len; + while (count-- > 0) { + next = findchar(start, end-start, from_c); + if (next == NULL) + break; + + if (next == start) { + /* replace with the 'to' */ + Py_MEMCPY(result_s, to_s, to_len); + result_s += to_len; + start += 1; + } else { + /* copy the unchanged old then the 'to' */ + Py_MEMCPY(result_s, start, next-start); + result_s += (next-start); + Py_MEMCPY(result_s, to_s, to_len); + result_s += to_len; + start = next+1; + } + } + /* Copy the remainder of the remaining string */ + Py_MEMCPY(result_s, start, end-start); + + return result; } /* len(self)>=1, len(from)>=2, len(to)>=2, maxcount>=1 */ Py_LOCAL(PyBytesObject *) replace_substring(PyBytesObject *self, - const char *from_s, Py_ssize_t from_len, - const char *to_s, Py_ssize_t to_len, - Py_ssize_t maxcount) { - char *self_s, *result_s; - char *start, *next, *end; - Py_ssize_t self_len, result_len; - Py_ssize_t count, offset, product; - PyBytesObject *result; - - self_s = PyBytes_AS_STRING(self); - self_len = PyBytes_GET_SIZE(self); - - count = stringlib_count(self_s, self_len, - from_s, from_len, - maxcount); - - if (count == 0) { - /* no matches, return unchanged */ - return return_self(self); - } - - /* Check for overflow */ - /* result_len = self_len + count * (to_len-from_len) */ - product = count * (to_len-from_len); - if (product / (to_len-from_len) != count) { - PyErr_SetString(PyExc_OverflowError, - "replacement bytes are too long"); - return NULL; - } - result_len = self_len + product; - if (result_len < 0) { - PyErr_SetString(PyExc_OverflowError, - "replacement bytes are too long"); - return NULL; - } - - if ( (result = (PyBytesObject *) - PyBytes_FromStringAndSize(NULL, result_len)) == NULL) - return NULL; - result_s = PyBytes_AS_STRING(result); - - start = self_s; - end = self_s + self_len; - while (count-- > 0) { - offset = stringlib_find(start, end-start, - from_s, from_len, - 0); - if (offset == -1) - break; - next = start+offset; - if (next == start) { - /* replace with the 'to' */ - Py_MEMCPY(result_s, to_s, to_len); - result_s += to_len; - start += from_len; - } else { - /* copy the unchanged old then the 'to' */ - Py_MEMCPY(result_s, start, next-start); - result_s += (next-start); - Py_MEMCPY(result_s, to_s, to_len); - result_s += to_len; - start = next+from_len; - } - } - /* Copy the remainder of the remaining string */ - Py_MEMCPY(result_s, start, end-start); + const char *from_s, Py_ssize_t from_len, + const char *to_s, Py_ssize_t to_len, + Py_ssize_t maxcount) { + char *self_s, *result_s; + char *start, *next, *end; + Py_ssize_t self_len, result_len; + Py_ssize_t count, offset, product; + PyBytesObject *result; + + self_s = PyBytes_AS_STRING(self); + self_len = PyBytes_GET_SIZE(self); + + count = stringlib_count(self_s, self_len, + from_s, from_len, + maxcount); + + if (count == 0) { + /* no matches, return unchanged */ + return return_self(self); + } + + /* Check for overflow */ + /* result_len = self_len + count * (to_len-from_len) */ + product = count * (to_len-from_len); + if (product / (to_len-from_len) != count) { + PyErr_SetString(PyExc_OverflowError, + "replacement bytes are too long"); + return NULL; + } + result_len = self_len + product; + if (result_len < 0) { + PyErr_SetString(PyExc_OverflowError, + "replacement bytes are too long"); + return NULL; + } + + if ( (result = (PyBytesObject *) + PyBytes_FromStringAndSize(NULL, result_len)) == NULL) + return NULL; + result_s = PyBytes_AS_STRING(result); + + start = self_s; + end = self_s + self_len; + while (count-- > 0) { + offset = stringlib_find(start, end-start, + from_s, from_len, + 0); + if (offset == -1) + break; + next = start+offset; + if (next == start) { + /* replace with the 'to' */ + Py_MEMCPY(result_s, to_s, to_len); + result_s += to_len; + start += from_len; + } else { + /* copy the unchanged old then the 'to' */ + Py_MEMCPY(result_s, start, next-start); + result_s += (next-start); + Py_MEMCPY(result_s, to_s, to_len); + result_s += to_len; + start = next+from_len; + } + } + /* Copy the remainder of the remaining string */ + Py_MEMCPY(result_s, start, end-start); - return result; + return result; } Py_LOCAL(PyBytesObject *) replace(PyBytesObject *self, - const char *from_s, Py_ssize_t from_len, - const char *to_s, Py_ssize_t to_len, - Py_ssize_t maxcount) -{ - if (maxcount < 0) { - maxcount = PY_SSIZE_T_MAX; - } else if (maxcount == 0 || PyBytes_GET_SIZE(self) == 0) { - /* nothing to do; return the original string */ - return return_self(self); - } - - if (maxcount == 0 || - (from_len == 0 && to_len == 0)) { - /* nothing to do; return the original string */ - return return_self(self); - } - - /* Handle zero-length special cases */ - - if (from_len == 0) { - /* insert the 'to' string everywhere. */ - /* >>> "Python".replace("", ".") */ - /* '.P.y.t.h.o.n.' */ - return replace_interleave(self, to_s, to_len, maxcount); - } - - /* Except for "".replace("", "A") == "A" there is no way beyond this */ - /* point for an empty self string to generate a non-empty string */ - /* Special case so the remaining code always gets a non-empty string */ - if (PyBytes_GET_SIZE(self) == 0) { - return return_self(self); - } - - if (to_len == 0) { - /* delete all occurrences of 'from' string */ - if (from_len == 1) { - return replace_delete_single_character( - self, from_s[0], maxcount); - } else { - return replace_delete_substring(self, from_s, - from_len, maxcount); - } - } - - /* Handle special case where both strings have the same length */ - - if (from_len == to_len) { - if (from_len == 1) { - return replace_single_character_in_place( - self, - from_s[0], - to_s[0], - maxcount); - } else { - return replace_substring_in_place( - self, from_s, from_len, to_s, to_len, - maxcount); - } - } - - /* Otherwise use the more generic algorithms */ - if (from_len == 1) { - return replace_single_character(self, from_s[0], - to_s, to_len, maxcount); - } else { - /* len('from')>=2, len('to')>=1 */ - return replace_substring(self, from_s, from_len, to_s, to_len, - maxcount); - } + const char *from_s, Py_ssize_t from_len, + const char *to_s, Py_ssize_t to_len, + Py_ssize_t maxcount) +{ + if (maxcount < 0) { + maxcount = PY_SSIZE_T_MAX; + } else if (maxcount == 0 || PyBytes_GET_SIZE(self) == 0) { + /* nothing to do; return the original string */ + return return_self(self); + } + + if (maxcount == 0 || + (from_len == 0 && to_len == 0)) { + /* nothing to do; return the original string */ + return return_self(self); + } + + /* Handle zero-length special cases */ + + if (from_len == 0) { + /* insert the 'to' string everywhere. */ + /* >>> "Python".replace("", ".") */ + /* '.P.y.t.h.o.n.' */ + return replace_interleave(self, to_s, to_len, maxcount); + } + + /* Except for "".replace("", "A") == "A" there is no way beyond this */ + /* point for an empty self string to generate a non-empty string */ + /* Special case so the remaining code always gets a non-empty string */ + if (PyBytes_GET_SIZE(self) == 0) { + return return_self(self); + } + + if (to_len == 0) { + /* delete all occurrences of 'from' string */ + if (from_len == 1) { + return replace_delete_single_character( + self, from_s[0], maxcount); + } else { + return replace_delete_substring(self, from_s, + from_len, maxcount); + } + } + + /* Handle special case where both strings have the same length */ + + if (from_len == to_len) { + if (from_len == 1) { + return replace_single_character_in_place( + self, + from_s[0], + to_s[0], + maxcount); + } else { + return replace_substring_in_place( + self, from_s, from_len, to_s, to_len, + maxcount); + } + } + + /* Otherwise use the more generic algorithms */ + if (from_len == 1) { + return replace_single_character(self, from_s[0], + to_s, to_len, maxcount); + } else { + /* len('from')>=2, len('to')>=1 */ + return replace_substring(self, from_s, from_len, to_s, to_len, + maxcount); + } } PyDoc_STRVAR(replace__doc__, @@ -2155,31 +2155,31 @@ static PyObject * bytes_replace(PyBytesObject *self, PyObject *args) { - Py_ssize_t count = -1; - PyObject *from, *to; - const char *from_s, *to_s; - Py_ssize_t from_len, to_len; - - if (!PyArg_ParseTuple(args, "OO|n:replace", &from, &to, &count)) - return NULL; - - if (PyBytes_Check(from)) { - from_s = PyBytes_AS_STRING(from); - from_len = PyBytes_GET_SIZE(from); - } - else if (PyObject_AsCharBuffer(from, &from_s, &from_len)) - return NULL; - - if (PyBytes_Check(to)) { - to_s = PyBytes_AS_STRING(to); - to_len = PyBytes_GET_SIZE(to); - } - else if (PyObject_AsCharBuffer(to, &to_s, &to_len)) - return NULL; - - return (PyObject *)replace((PyBytesObject *) self, - from_s, from_len, - to_s, to_len, count); + Py_ssize_t count = -1; + PyObject *from, *to; + const char *from_s, *to_s; + Py_ssize_t from_len, to_len; + + if (!PyArg_ParseTuple(args, "OO|n:replace", &from, &to, &count)) + return NULL; + + if (PyBytes_Check(from)) { + from_s = PyBytes_AS_STRING(from); + from_len = PyBytes_GET_SIZE(from); + } + else if (PyObject_AsCharBuffer(from, &from_s, &from_len)) + return NULL; + + if (PyBytes_Check(to)) { + to_s = PyBytes_AS_STRING(to); + to_len = PyBytes_GET_SIZE(to); + } + else if (PyObject_AsCharBuffer(to, &to_s, &to_len)) + return NULL; + + return (PyObject *)replace((PyBytesObject *) self, + from_s, from_len, + to_s, to_len, count); } /** End DALKE **/ @@ -2190,38 +2190,38 @@ */ Py_LOCAL(int) _bytes_tailmatch(PyBytesObject *self, PyObject *substr, Py_ssize_t start, - Py_ssize_t end, int direction) + Py_ssize_t end, int direction) { - Py_ssize_t len = PyBytes_GET_SIZE(self); - Py_ssize_t slen; - const char* sub; - const char* str; - - if (PyBytes_Check(substr)) { - sub = PyBytes_AS_STRING(substr); - slen = PyBytes_GET_SIZE(substr); - } - else if (PyObject_AsCharBuffer(substr, &sub, &slen)) - return -1; - str = PyBytes_AS_STRING(self); - - ADJUST_INDICES(start, end, len); - - if (direction < 0) { - /* startswith */ - if (start+slen > len) - return 0; - } else { - /* endswith */ - if (end-start < slen || start > len) - return 0; - - if (end-slen > start) - start = end - slen; - } - if (end-start >= slen) - return ! memcmp(str+start, sub, slen); - return 0; + Py_ssize_t len = PyBytes_GET_SIZE(self); + Py_ssize_t slen; + const char* sub; + const char* str; + + if (PyBytes_Check(substr)) { + sub = PyBytes_AS_STRING(substr); + slen = PyBytes_GET_SIZE(substr); + } + else if (PyObject_AsCharBuffer(substr, &sub, &slen)) + return -1; + str = PyBytes_AS_STRING(self); + + ADJUST_INDICES(start, end, len); + + if (direction < 0) { + /* startswith */ + if (start+slen > len) + return 0; + } else { + /* endswith */ + if (end-start < slen || start > len) + return 0; + + if (end-slen > start) + start = end - slen; + } + if (end-start >= slen) + return ! memcmp(str+start, sub, slen); + return 0; } @@ -2236,33 +2236,33 @@ static PyObject * bytes_startswith(PyBytesObject *self, PyObject *args) { - Py_ssize_t start = 0; - Py_ssize_t end = PY_SSIZE_T_MAX; - PyObject *subobj; - int result; - - if (!PyArg_ParseTuple(args, "O|O&O&:startswith", &subobj, - _PyEval_SliceIndex, &start, _PyEval_SliceIndex, &end)) - return NULL; - if (PyTuple_Check(subobj)) { - Py_ssize_t i; - for (i = 0; i < PyTuple_GET_SIZE(subobj); i++) { - result = _bytes_tailmatch(self, - PyTuple_GET_ITEM(subobj, i), - start, end, -1); - if (result == -1) - return NULL; - else if (result) { - Py_RETURN_TRUE; - } - } - Py_RETURN_FALSE; - } - result = _bytes_tailmatch(self, subobj, start, end, -1); - if (result == -1) - return NULL; - else - return PyBool_FromLong(result); + Py_ssize_t start = 0; + Py_ssize_t end = PY_SSIZE_T_MAX; + PyObject *subobj; + int result; + + if (!PyArg_ParseTuple(args, "O|O&O&:startswith", &subobj, + _PyEval_SliceIndex, &start, _PyEval_SliceIndex, &end)) + return NULL; + if (PyTuple_Check(subobj)) { + Py_ssize_t i; + for (i = 0; i < PyTuple_GET_SIZE(subobj); i++) { + result = _bytes_tailmatch(self, + PyTuple_GET_ITEM(subobj, i), + start, end, -1); + if (result == -1) + return NULL; + else if (result) { + Py_RETURN_TRUE; + } + } + Py_RETURN_FALSE; + } + result = _bytes_tailmatch(self, subobj, start, end, -1); + if (result == -1) + return NULL; + else + return PyBool_FromLong(result); } @@ -2277,33 +2277,33 @@ static PyObject * bytes_endswith(PyBytesObject *self, PyObject *args) { - Py_ssize_t start = 0; - Py_ssize_t end = PY_SSIZE_T_MAX; - PyObject *subobj; - int result; - - if (!PyArg_ParseTuple(args, "O|O&O&:endswith", &subobj, - _PyEval_SliceIndex, &start, _PyEval_SliceIndex, &end)) - return NULL; - if (PyTuple_Check(subobj)) { - Py_ssize_t i; - for (i = 0; i < PyTuple_GET_SIZE(subobj); i++) { - result = _bytes_tailmatch(self, - PyTuple_GET_ITEM(subobj, i), - start, end, +1); - if (result == -1) - return NULL; - else if (result) { - Py_RETURN_TRUE; - } - } - Py_RETURN_FALSE; - } - result = _bytes_tailmatch(self, subobj, start, end, +1); - if (result == -1) - return NULL; - else - return PyBool_FromLong(result); + Py_ssize_t start = 0; + Py_ssize_t end = PY_SSIZE_T_MAX; + PyObject *subobj; + int result; + + if (!PyArg_ParseTuple(args, "O|O&O&:endswith", &subobj, + _PyEval_SliceIndex, &start, _PyEval_SliceIndex, &end)) + return NULL; + if (PyTuple_Check(subobj)) { + Py_ssize_t i; + for (i = 0; i < PyTuple_GET_SIZE(subobj); i++) { + result = _bytes_tailmatch(self, + PyTuple_GET_ITEM(subobj, i), + start, end, +1); + if (result == -1) + return NULL; + else if (result) { + Py_RETURN_TRUE; + } + } + Py_RETURN_FALSE; + } + result = _bytes_tailmatch(self, subobj, start, end, +1); + if (result == -1) + return NULL; + else + return PyBool_FromLong(result); } @@ -2320,15 +2320,15 @@ static PyObject * bytes_decode(PyObject *self, PyObject *args, PyObject *kwargs) { - const char *encoding = NULL; - const char *errors = NULL; - static char *kwlist[] = {"encoding", "errors", 0}; - - if (!PyArg_ParseTupleAndKeywords(args, kwargs, "|ss:decode", kwlist, &encoding, &errors)) - return NULL; - if (encoding == NULL) - encoding = PyUnicode_GetDefaultEncoding(); - return PyUnicode_FromEncodedObject(self, encoding, errors); + const char *encoding = NULL; + const char *errors = NULL; + static char *kwlist[] = {"encoding", "errors", 0}; + + if (!PyArg_ParseTupleAndKeywords(args, kwargs, "|ss:decode", kwlist, &encoding, &errors)) + return NULL; + if (encoding == NULL) + encoding = PyUnicode_GetDefaultEncoding(); + return PyUnicode_FromEncodedObject(self, encoding, errors); } @@ -2345,12 +2345,12 @@ int keepends = 0; if (!PyArg_ParseTuple(args, "|i:splitlines", &keepends)) - return NULL; + return NULL; return stringlib_splitlines( - (PyObject*) self, PyBytes_AS_STRING(self), - PyBytes_GET_SIZE(self), keepends - ); + (PyObject*) self, PyBytes_AS_STRING(self), + PyBytes_GET_SIZE(self), keepends + ); } @@ -2364,61 +2364,61 @@ static int hex_digit_to_int(Py_UNICODE c) { - if (c >= 128) - return -1; - if (ISDIGIT(c)) - return c - '0'; - else { - if (ISUPPER(c)) - c = TOLOWER(c); - if (c >= 'a' && c <= 'f') - return c - 'a' + 10; - } - return -1; + if (c >= 128) + return -1; + if (ISDIGIT(c)) + return c - '0'; + else { + if (ISUPPER(c)) + c = TOLOWER(c); + if (c >= 'a' && c <= 'f') + return c - 'a' + 10; + } + return -1; } static PyObject * bytes_fromhex(PyObject *cls, PyObject *args) { - PyObject *newstring, *hexobj; - char *buf; - Py_UNICODE *hex; - Py_ssize_t hexlen, byteslen, i, j; - int top, bot; - - if (!PyArg_ParseTuple(args, "U:fromhex", &hexobj)) - return NULL; - assert(PyUnicode_Check(hexobj)); - hexlen = PyUnicode_GET_SIZE(hexobj); - hex = PyUnicode_AS_UNICODE(hexobj); - byteslen = hexlen/2; /* This overestimates if there are spaces */ - newstring = PyBytes_FromStringAndSize(NULL, byteslen); - if (!newstring) - return NULL; - buf = PyBytes_AS_STRING(newstring); - for (i = j = 0; i < hexlen; i += 2) { - /* skip over spaces in the input */ - while (hex[i] == ' ') - i++; - if (i >= hexlen) - break; - top = hex_digit_to_int(hex[i]); - bot = hex_digit_to_int(hex[i+1]); - if (top == -1 || bot == -1) { - PyErr_Format(PyExc_ValueError, - "non-hexadecimal number found in " - "fromhex() arg at position %zd", i); - goto error; - } - buf[j++] = (top << 4) + bot; - } - if (j != byteslen && _PyBytes_Resize(&newstring, j) < 0) - goto error; - return newstring; + PyObject *newstring, *hexobj; + char *buf; + Py_UNICODE *hex; + Py_ssize_t hexlen, byteslen, i, j; + int top, bot; + + if (!PyArg_ParseTuple(args, "U:fromhex", &hexobj)) + return NULL; + assert(PyUnicode_Check(hexobj)); + hexlen = PyUnicode_GET_SIZE(hexobj); + hex = PyUnicode_AS_UNICODE(hexobj); + byteslen = hexlen/2; /* This overestimates if there are spaces */ + newstring = PyBytes_FromStringAndSize(NULL, byteslen); + if (!newstring) + return NULL; + buf = PyBytes_AS_STRING(newstring); + for (i = j = 0; i < hexlen; i += 2) { + /* skip over spaces in the input */ + while (hex[i] == ' ') + i++; + if (i >= hexlen) + break; + top = hex_digit_to_int(hex[i]); + bot = hex_digit_to_int(hex[i+1]); + if (top == -1 || bot == -1) { + PyErr_Format(PyExc_ValueError, + "non-hexadecimal number found in " + "fromhex() arg at position %zd", i); + goto error; + } + buf[j++] = (top << 4) + bot; + } + if (j != byteslen && _PyBytes_Resize(&newstring, j) < 0) + goto error; + return newstring; error: - Py_XDECREF(newstring); - return NULL; + Py_XDECREF(newstring); + return NULL; } PyDoc_STRVAR(sizeof__doc__, @@ -2427,80 +2427,80 @@ static PyObject * bytes_sizeof(PyBytesObject *v) { - Py_ssize_t res; - res = PyBytesObject_SIZE + Py_SIZE(v) * Py_TYPE(v)->tp_itemsize; - return PyLong_FromSsize_t(res); + Py_ssize_t res; + res = PyBytesObject_SIZE + Py_SIZE(v) * Py_TYPE(v)->tp_itemsize; + return PyLong_FromSsize_t(res); } static PyObject * bytes_getnewargs(PyBytesObject *v) { - return Py_BuildValue("(y#)", v->ob_sval, Py_SIZE(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, center__doc__}, - {"count", (PyCFunction)bytes_count, METH_VARARGS, count__doc__}, - {"decode", (PyCFunction)bytes_decode, METH_VARARGS | METH_KEYWORDS, decode__doc__}, - {"endswith", (PyCFunction)bytes_endswith, METH_VARARGS, - endswith__doc__}, - {"expandtabs", (PyCFunction)stringlib_expandtabs, METH_VARARGS, - expandtabs__doc__}, - {"find", (PyCFunction)bytes_find, METH_VARARGS, find__doc__}, - {"fromhex", (PyCFunction)bytes_fromhex, METH_VARARGS|METH_CLASS, - fromhex_doc}, - {"index", (PyCFunction)bytes_index, METH_VARARGS, 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__}, - {"join", (PyCFunction)bytes_join, METH_O, join__doc__}, - {"ljust", (PyCFunction)stringlib_ljust, METH_VARARGS, ljust__doc__}, - {"lower", (PyCFunction)stringlib_lower, METH_NOARGS, _Py_lower__doc__}, - {"lstrip", (PyCFunction)bytes_lstrip, METH_VARARGS, lstrip__doc__}, - {"maketrans", (PyCFunction)bytes_maketrans, METH_VARARGS|METH_STATIC, - _Py_maketrans__doc__}, - {"partition", (PyCFunction)bytes_partition, METH_O, partition__doc__}, - {"replace", (PyCFunction)bytes_replace, METH_VARARGS, replace__doc__}, - {"rfind", (PyCFunction)bytes_rfind, METH_VARARGS, rfind__doc__}, - {"rindex", (PyCFunction)bytes_rindex, METH_VARARGS, rindex__doc__}, - {"rjust", (PyCFunction)stringlib_rjust, METH_VARARGS, rjust__doc__}, - {"rpartition", (PyCFunction)bytes_rpartition, METH_O, - rpartition__doc__}, - {"rsplit", (PyCFunction)bytes_rsplit, METH_VARARGS, rsplit__doc__}, - {"rstrip", (PyCFunction)bytes_rstrip, METH_VARARGS, rstrip__doc__}, - {"split", (PyCFunction)bytes_split, METH_VARARGS, split__doc__}, - {"splitlines", (PyCFunction)bytes_splitlines, METH_VARARGS, - splitlines__doc__}, - {"startswith", (PyCFunction)bytes_startswith, METH_VARARGS, - startswith__doc__}, - {"strip", (PyCFunction)bytes_strip, METH_VARARGS, strip__doc__}, - {"swapcase", (PyCFunction)stringlib_swapcase, METH_NOARGS, - _Py_swapcase__doc__}, - {"title", (PyCFunction)stringlib_title, METH_NOARGS, _Py_title__doc__}, - {"translate", (PyCFunction)bytes_translate, METH_VARARGS, - translate__doc__}, - {"upper", (PyCFunction)stringlib_upper, METH_NOARGS, _Py_upper__doc__}, - {"zfill", (PyCFunction)stringlib_zfill, METH_VARARGS, zfill__doc__}, - {"__sizeof__", (PyCFunction)bytes_sizeof, METH_NOARGS, - sizeof__doc__}, - {NULL, NULL} /* sentinel */ + {"__getnewargs__", (PyCFunction)bytes_getnewargs, METH_NOARGS}, + {"capitalize", (PyCFunction)stringlib_capitalize, METH_NOARGS, + _Py_capitalize__doc__}, + {"center", (PyCFunction)stringlib_center, METH_VARARGS, center__doc__}, + {"count", (PyCFunction)bytes_count, METH_VARARGS, count__doc__}, + {"decode", (PyCFunction)bytes_decode, METH_VARARGS | METH_KEYWORDS, decode__doc__}, + {"endswith", (PyCFunction)bytes_endswith, METH_VARARGS, + endswith__doc__}, + {"expandtabs", (PyCFunction)stringlib_expandtabs, METH_VARARGS, + expandtabs__doc__}, + {"find", (PyCFunction)bytes_find, METH_VARARGS, find__doc__}, + {"fromhex", (PyCFunction)bytes_fromhex, METH_VARARGS|METH_CLASS, + fromhex_doc}, + {"index", (PyCFunction)bytes_index, METH_VARARGS, 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__}, + {"join", (PyCFunction)bytes_join, METH_O, join__doc__}, + {"ljust", (PyCFunction)stringlib_ljust, METH_VARARGS, ljust__doc__}, + {"lower", (PyCFunction)stringlib_lower, METH_NOARGS, _Py_lower__doc__}, + {"lstrip", (PyCFunction)bytes_lstrip, METH_VARARGS, lstrip__doc__}, + {"maketrans", (PyCFunction)bytes_maketrans, METH_VARARGS|METH_STATIC, + _Py_maketrans__doc__}, + {"partition", (PyCFunction)bytes_partition, METH_O, partition__doc__}, + {"replace", (PyCFunction)bytes_replace, METH_VARARGS, replace__doc__}, + {"rfind", (PyCFunction)bytes_rfind, METH_VARARGS, rfind__doc__}, + {"rindex", (PyCFunction)bytes_rindex, METH_VARARGS, rindex__doc__}, + {"rjust", (PyCFunction)stringlib_rjust, METH_VARARGS, rjust__doc__}, + {"rpartition", (PyCFunction)bytes_rpartition, METH_O, + rpartition__doc__}, + {"rsplit", (PyCFunction)bytes_rsplit, METH_VARARGS, rsplit__doc__}, + {"rstrip", (PyCFunction)bytes_rstrip, METH_VARARGS, rstrip__doc__}, + {"split", (PyCFunction)bytes_split, METH_VARARGS, split__doc__}, + {"splitlines", (PyCFunction)bytes_splitlines, METH_VARARGS, + splitlines__doc__}, + {"startswith", (PyCFunction)bytes_startswith, METH_VARARGS, + startswith__doc__}, + {"strip", (PyCFunction)bytes_strip, METH_VARARGS, strip__doc__}, + {"swapcase", (PyCFunction)stringlib_swapcase, METH_NOARGS, + _Py_swapcase__doc__}, + {"title", (PyCFunction)stringlib_title, METH_NOARGS, _Py_title__doc__}, + {"translate", (PyCFunction)bytes_translate, METH_VARARGS, + translate__doc__}, + {"upper", (PyCFunction)stringlib_upper, METH_NOARGS, _Py_upper__doc__}, + {"zfill", (PyCFunction)stringlib_zfill, METH_VARARGS, zfill__doc__}, + {"__sizeof__", (PyCFunction)bytes_sizeof, METH_NOARGS, + sizeof__doc__}, + {NULL, NULL} /* sentinel */ }; static PyObject * @@ -2509,236 +2509,236 @@ static PyObject * bytes_new(PyTypeObject *type, PyObject *args, PyObject *kwds) { - PyObject *x = NULL; - const char *encoding = NULL; - const char *errors = NULL; - PyObject *new = NULL; - Py_ssize_t size; - static char *kwlist[] = {"source", "encoding", "errors", 0}; - - if (type != &PyBytes_Type) - return str_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_FromString(""); - } - - if (PyUnicode_Check(x)) { - /* Encode via the codec registry */ - if (encoding == NULL) { - PyErr_SetString(PyExc_TypeError, - "string argument without an encoding"); - return NULL; - } - new = PyUnicode_AsEncodedString(x, encoding, errors); - if (new == NULL) - return NULL; - assert(PyBytes_Check(new)); - return new; - } - /* Is it an integer? */ - size = PyNumber_AsSsize_t(x, PyExc_OverflowError); - if (size == -1 && PyErr_Occurred()) { - if (PyErr_ExceptionMatches(PyExc_OverflowError)) - return NULL; - PyErr_Clear(); - } - else if (size < 0) { - PyErr_SetString(PyExc_ValueError, "negative count"); - return NULL; - } - else { - new = PyBytes_FromStringAndSize(NULL, size); - if (new == NULL) { - return NULL; - } - if (size > 0) { - memset(((PyBytesObject*)new)->ob_sval, 0, size); - } - return new; - } - - /* If it's not unicode, there can't be encoding or errors */ - if (encoding != NULL || errors != NULL) { - PyErr_SetString(PyExc_TypeError, - "encoding or errors without a string argument"); - return NULL; - } - return PyObject_Bytes(x); + PyObject *x = NULL; + const char *encoding = NULL; + const char *errors = NULL; + PyObject *new = NULL; + Py_ssize_t size; + static char *kwlist[] = {"source", "encoding", "errors", 0}; + + if (type != &PyBytes_Type) + return str_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_FromString(""); + } + + if (PyUnicode_Check(x)) { + /* Encode via the codec registry */ + if (encoding == NULL) { + PyErr_SetString(PyExc_TypeError, + "string argument without an encoding"); + return NULL; + } + new = PyUnicode_AsEncodedString(x, encoding, errors); + if (new == NULL) + return NULL; + assert(PyBytes_Check(new)); + return new; + } + /* Is it an integer? */ + size = PyNumber_AsSsize_t(x, PyExc_OverflowError); + if (size == -1 && PyErr_Occurred()) { + if (PyErr_ExceptionMatches(PyExc_OverflowError)) + return NULL; + PyErr_Clear(); + } + else if (size < 0) { + PyErr_SetString(PyExc_ValueError, "negative count"); + return NULL; + } + else { + new = PyBytes_FromStringAndSize(NULL, size); + if (new == NULL) { + return NULL; + } + if (size > 0) { + memset(((PyBytesObject*)new)->ob_sval, 0, size); + } + return new; + } + + /* If it's not unicode, there can't be encoding or errors */ + if (encoding != NULL || errors != NULL) { + PyErr_SetString(PyExc_TypeError, + "encoding or errors without a string argument"); + return NULL; + } + return PyObject_Bytes(x); } PyObject * PyBytes_FromObject(PyObject *x) { - PyObject *new, *it; - Py_ssize_t i, size; + PyObject *new, *it; + Py_ssize_t i, size; + + if (x == NULL) { + PyErr_BadInternalCall(); + return NULL; + } + /* Use the modern buffer interface */ + if (PyObject_CheckBuffer(x)) { + Py_buffer view; + if (PyObject_GetBuffer(x, &view, PyBUF_FULL_RO) < 0) + return NULL; + new = PyBytes_FromStringAndSize(NULL, view.len); + if (!new) + goto fail; + /* XXX(brett.cannon): Better way to get to internal buffer? */ + 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; + } + if (PyUnicode_Check(x)) { + PyErr_SetString(PyExc_TypeError, + "cannot convert unicode object to bytes"); + return NULL; + } + + if (PyList_CheckExact(x)) { + new = PyBytes_FromStringAndSize(NULL, Py_SIZE(x)); + if (new == NULL) + return NULL; + for (i = 0; i < Py_SIZE(x); i++) { + Py_ssize_t value = PyNumber_AsSsize_t( + PyList_GET_ITEM(x, i), PyExc_ValueError); + if (value == -1 && PyErr_Occurred()) { + Py_DECREF(new); + return NULL; + } + if (value < 0 || value >= 256) { + PyErr_SetString(PyExc_ValueError, + "bytes must be in range(0, 256)"); + Py_DECREF(new); + return NULL; + } + ((PyBytesObject *)new)->ob_sval[i] = value; + } + return new; + } + if (PyTuple_CheckExact(x)) { + new = PyBytes_FromStringAndSize(NULL, Py_SIZE(x)); + if (new == NULL) + return NULL; + for (i = 0; i < Py_SIZE(x); i++) { + Py_ssize_t value = PyNumber_AsSsize_t( + PyTuple_GET_ITEM(x, i), PyExc_ValueError); + if (value == -1 && PyErr_Occurred()) { + Py_DECREF(new); + return NULL; + } + if (value < 0 || value >= 256) { + PyErr_SetString(PyExc_ValueError, + "bytes must be in range(0, 256)"); + Py_DECREF(new); + return NULL; + } + ((PyBytesObject *)new)->ob_sval[i] = value; + } + return new; + } - if (x == NULL) { - PyErr_BadInternalCall(); - return NULL; - } - /* Use the modern buffer interface */ - if (PyObject_CheckBuffer(x)) { - Py_buffer view; - if (PyObject_GetBuffer(x, &view, PyBUF_FULL_RO) < 0) - return NULL; - new = PyBytes_FromStringAndSize(NULL, view.len); - if (!new) - goto fail; - /* XXX(brett.cannon): Better way to get to internal buffer? */ - 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; - } - if (PyUnicode_Check(x)) { - PyErr_SetString(PyExc_TypeError, - "cannot convert unicode object to bytes"); - return NULL; - } - - if (PyList_CheckExact(x)) { - new = PyBytes_FromStringAndSize(NULL, Py_SIZE(x)); - if (new == NULL) - return NULL; - for (i = 0; i < Py_SIZE(x); i++) { - Py_ssize_t value = PyNumber_AsSsize_t( - PyList_GET_ITEM(x, i), PyExc_ValueError); - if (value == -1 && PyErr_Occurred()) { - Py_DECREF(new); - return NULL; - } - if (value < 0 || value >= 256) { - PyErr_SetString(PyExc_ValueError, - "bytes must be in range(0, 256)"); - Py_DECREF(new); - return NULL; - } - ((PyBytesObject *)new)->ob_sval[i] = value; - } - return new; - } - if (PyTuple_CheckExact(x)) { - new = PyBytes_FromStringAndSize(NULL, Py_SIZE(x)); - if (new == NULL) - return NULL; - for (i = 0; i < Py_SIZE(x); i++) { - Py_ssize_t value = PyNumber_AsSsize_t( - PyTuple_GET_ITEM(x, i), PyExc_ValueError); - if (value == -1 && PyErr_Occurred()) { - Py_DECREF(new); - return NULL; - } - if (value < 0 || value >= 256) { - PyErr_SetString(PyExc_ValueError, - "bytes must be in range(0, 256)"); - Py_DECREF(new); - return NULL; - } - ((PyBytesObject *)new)->ob_sval[i] = value; - } - return new; - } - - /* For iterator version, create a string object and resize as needed */ - size = _PyObject_LengthHint(x, 64); - if (size == -1 && PyErr_Occurred()) - return NULL; - /* Allocate an extra byte to prevent PyBytes_FromStringAndSize() from - returning a shared empty bytes string. This required because we - want to call _PyBytes_Resize() the returned object, which we can - only do on bytes objects with refcount == 1. */ - size += 1; - new = PyBytes_FromStringAndSize(NULL, size); - if (new == NULL) - return NULL; - - /* Get the iterator */ - it = PyObject_GetIter(x); - if (it == NULL) - goto error; - - /* 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, PyExc_ValueError); - 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) { - size = 2 * size + 1; - if (_PyBytes_Resize(&new, size) < 0) - goto error; - } - ((PyBytesObject *)new)->ob_sval[i] = value; - } - _PyBytes_Resize(&new, i); - - /* Clean up and return success */ - Py_DECREF(it); - return new; + /* For iterator version, create a string object and resize as needed */ + size = _PyObject_LengthHint(x, 64); + if (size == -1 && PyErr_Occurred()) + return NULL; + /* Allocate an extra byte to prevent PyBytes_FromStringAndSize() from + returning a shared empty bytes string. This required because we + want to call _PyBytes_Resize() the returned object, which we can + only do on bytes objects with refcount == 1. */ + size += 1; + new = PyBytes_FromStringAndSize(NULL, size); + if (new == NULL) + return NULL; + + /* Get the iterator */ + it = PyObject_GetIter(x); + if (it == NULL) + goto error; + + /* 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, PyExc_ValueError); + 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) { + size = 2 * size + 1; + if (_PyBytes_Resize(&new, size) < 0) + goto error; + } + ((PyBytesObject *)new)->ob_sval[i] = value; + } + _PyBytes_Resize(&new, i); + + /* Clean up and return success */ + Py_DECREF(it); + return new; error: - /* Error handling when new != NULL */ - Py_XDECREF(it); - Py_DECREF(new); - return NULL; + /* Error handling when new != NULL */ + Py_XDECREF(it); + Py_DECREF(new); + return NULL; } static PyObject * str_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds) { - PyObject *tmp, *pnew; - Py_ssize_t n; + 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_CheckExact(tmp)); - n = PyBytes_GET_SIZE(tmp); - pnew = type->tp_alloc(type, n); - if (pnew != NULL) { - Py_MEMCPY(PyBytes_AS_STRING(pnew), - PyBytes_AS_STRING(tmp), n+1); - ((PyBytesObject *)pnew)->ob_shash = - ((PyBytesObject *)tmp)->ob_shash; - } - Py_DECREF(tmp); - return pnew; + assert(PyType_IsSubtype(type, &PyBytes_Type)); + tmp = bytes_new(&PyBytes_Type, args, kwds); + if (tmp == NULL) + return NULL; + assert(PyBytes_CheckExact(tmp)); + n = PyBytes_GET_SIZE(tmp); + pnew = type->tp_alloc(type, n); + if (pnew != NULL) { + Py_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, @@ -2756,70 +2756,70 @@ 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 */ - 0, /* 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 */ + 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 */ + 0, /* 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(register PyObject **pv, register PyObject *w) { - register PyObject *v; - assert(pv != NULL); - if (*pv == NULL) - return; - if (w == NULL) { - Py_DECREF(*pv); - *pv = NULL; - return; - } - v = bytes_concat(*pv, w); - Py_DECREF(*pv); - *pv = v; + register PyObject *v; + assert(pv != NULL); + if (*pv == NULL) + return; + if (w == NULL) { + Py_DECREF(*pv); + *pv = NULL; + return; + } + v = bytes_concat(*pv, w); + Py_DECREF(*pv); + *pv = v; } void PyBytes_ConcatAndDel(register PyObject **pv, register PyObject *w) { - PyBytes_Concat(pv, w); - Py_XDECREF(w); + PyBytes_Concat(pv, w); + Py_XDECREF(w); } @@ -2840,31 +2840,31 @@ int _PyBytes_Resize(PyObject **pv, Py_ssize_t newsize) { - register PyObject *v; - register PyBytesObject *sv; - v = *pv; - if (!PyBytes_Check(v) || Py_REFCNT(v) != 1 || newsize < 0) { - *pv = 0; - Py_DECREF(v); - PyErr_BadInternalCall(); - return -1; - } - /* XXX UNREF/NEWREF interface should be more symmetrical */ - _Py_DEC_REFTOTAL; - _Py_ForgetReference(v); - *pv = (PyObject *) - PyObject_REALLOC((char *)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; + register PyObject *v; + register PyBytesObject *sv; + v = *pv; + if (!PyBytes_Check(v) || Py_REFCNT(v) != 1 || newsize < 0) { + *pv = 0; + Py_DECREF(v); + PyErr_BadInternalCall(); + return -1; + } + /* XXX UNREF/NEWREF interface should be more symmetrical */ + _Py_DEC_REFTOTAL; + _Py_ForgetReference(v); + *pv = (PyObject *) + PyObject_REALLOC((char *)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; } /* _PyBytes_FormatLong emulates the format codes d, u, o, x and X, and @@ -2880,262 +2880,262 @@ * set in flags. The case of hex digits will be correct, * There will be at least prec digits, zero-filled on the left if * necessary to get that many. - * val object to be converted - * flags bitmask of format flags; only F_ALT is looked at - * prec minimum number of digits; 0-fill on left if needed - * type a character in [duoxX]; u acts the same as d + * val object to be converted + * flags bitmask of format flags; only F_ALT is looked at + * prec minimum number of digits; 0-fill on left if needed + * type a character in [duoxX]; u acts the same as d * * CAUTION: o, x and X conversions on regular ints can never * produce a '-' sign, but can for Python's unbounded ints. */ PyObject* _PyBytes_FormatLong(PyObject *val, int flags, int prec, int type, - char **pbuf, int *plen) + char **pbuf, int *plen) { - PyObject *result = NULL; - char *buf; - Py_ssize_t i; - int sign; /* 1 if '-', else 0 */ - int len; /* number of characters */ - Py_ssize_t llen; - int numdigits; /* len == numnondigits + numdigits */ - int numnondigits = 0; - - /* Avoid exceeding SSIZE_T_MAX */ - if (prec > INT_MAX-3) { - PyErr_SetString(PyExc_OverflowError, - "precision too large"); - return NULL; - } - - switch (type) { - case 'd': - case 'u': - /* Special-case boolean: we want 0/1 */ - if (PyBool_Check(val)) - result = PyNumber_ToBase(val, 10); - else - result = Py_TYPE(val)->tp_str(val); - break; - case 'o': - numnondigits = 2; - result = PyNumber_ToBase(val, 8); - break; - case 'x': - case 'X': - numnondigits = 2; - result = PyNumber_ToBase(val, 16); - break; - default: - assert(!"'type' not in [duoxX]"); - } - if (!result) - return NULL; - - buf = _PyUnicode_AsString(result); - if (!buf) { - Py_DECREF(result); - return NULL; - } - - /* To modify the string in-place, there can only be one reference. */ - if (Py_REFCNT(result) != 1) { - PyErr_BadInternalCall(); - return NULL; - } - llen = PyUnicode_GetSize(result); - if (llen > INT_MAX) { - PyErr_SetString(PyExc_ValueError, - "string too large in _PyBytes_FormatLong"); - return NULL; - } - len = (int)llen; - if (buf[len-1] == 'L') { - --len; - buf[len] = '\0'; - } - sign = buf[0] == '-'; - numnondigits += sign; - numdigits = len - numnondigits; - assert(numdigits > 0); - - /* Get rid of base marker unless F_ALT */ - if (((flags & F_ALT) == 0 && - (type == 'o' || type == 'x' || type == 'X'))) { - assert(buf[sign] == '0'); - assert(buf[sign+1] == 'x' || buf[sign+1] == 'X' || - buf[sign+1] == 'o'); - numnondigits -= 2; - buf += 2; - len -= 2; - if (sign) - buf[0] = '-'; - assert(len == numnondigits + numdigits); - assert(numdigits > 0); - } - - /* Fill with leading zeroes to meet minimum width. */ - if (prec > numdigits) { - PyObject *r1 = PyBytes_FromStringAndSize(NULL, - numnondigits + prec); - char *b1; - if (!r1) { - Py_DECREF(result); - return NULL; - } - b1 = PyBytes_AS_STRING(r1); - for (i = 0; i < numnondigits; ++i) - *b1++ = *buf++; - for (i = 0; i < prec - numdigits; i++) - *b1++ = '0'; - for (i = 0; i < numdigits; i++) - *b1++ = *buf++; - *b1 = '\0'; - Py_DECREF(result); - result = r1; - buf = PyBytes_AS_STRING(result); - len = numnondigits + prec; - } - - /* Fix up case for hex conversions. */ - if (type == 'X') { - /* Need to convert all lower case letters to upper case. - and need to convert 0x to 0X (and -0x to -0X). */ - for (i = 0; i < len; i++) - if (buf[i] >= 'a' && buf[i] <= 'x') - buf[i] -= 'a'-'A'; - } - *pbuf = buf; - *plen = len; - return result; + PyObject *result = NULL; + char *buf; + Py_ssize_t i; + int sign; /* 1 if '-', else 0 */ + int len; /* number of characters */ + Py_ssize_t llen; + int numdigits; /* len == numnondigits + numdigits */ + int numnondigits = 0; + + /* Avoid exceeding SSIZE_T_MAX */ + if (prec > INT_MAX-3) { + PyErr_SetString(PyExc_OverflowError, + "precision too large"); + return NULL; + } + + switch (type) { + case 'd': + case 'u': + /* Special-case boolean: we want 0/1 */ + if (PyBool_Check(val)) + result = PyNumber_ToBase(val, 10); + else + result = Py_TYPE(val)->tp_str(val); + break; + case 'o': + numnondigits = 2; + result = PyNumber_ToBase(val, 8); + break; + case 'x': + case 'X': + numnondigits = 2; + result = PyNumber_ToBase(val, 16); + break; + default: + assert(!"'type' not in [duoxX]"); + } + if (!result) + return NULL; + + buf = _PyUnicode_AsString(result); + if (!buf) { + Py_DECREF(result); + return NULL; + } + + /* To modify the string in-place, there can only be one reference. */ + if (Py_REFCNT(result) != 1) { + PyErr_BadInternalCall(); + return NULL; + } + llen = PyUnicode_GetSize(result); + if (llen > INT_MAX) { + PyErr_SetString(PyExc_ValueError, + "string too large in _PyBytes_FormatLong"); + return NULL; + } + len = (int)llen; + if (buf[len-1] == 'L') { + --len; + buf[len] = '\0'; + } + sign = buf[0] == '-'; + numnondigits += sign; + numdigits = len - numnondigits; + assert(numdigits > 0); + + /* Get rid of base marker unless F_ALT */ + if (((flags & F_ALT) == 0 && + (type == 'o' || type == 'x' || type == 'X'))) { + assert(buf[sign] == '0'); + assert(buf[sign+1] == 'x' || buf[sign+1] == 'X' || + buf[sign+1] == 'o'); + numnondigits -= 2; + buf += 2; + len -= 2; + if (sign) + buf[0] = '-'; + assert(len == numnondigits + numdigits); + assert(numdigits > 0); + } + + /* Fill with leading zeroes to meet minimum width. */ + if (prec > numdigits) { + PyObject *r1 = PyBytes_FromStringAndSize(NULL, + numnondigits + prec); + char *b1; + if (!r1) { + Py_DECREF(result); + return NULL; + } + b1 = PyBytes_AS_STRING(r1); + for (i = 0; i < numnondigits; ++i) + *b1++ = *buf++; + for (i = 0; i < prec - numdigits; i++) + *b1++ = '0'; + for (i = 0; i < numdigits; i++) + *b1++ = *buf++; + *b1 = '\0'; + Py_DECREF(result); + result = r1; + buf = PyBytes_AS_STRING(result); + len = numnondigits + prec; + } + + /* Fix up case for hex conversions. */ + if (type == 'X') { + /* Need to convert all lower case letters to upper case. + and need to convert 0x to 0X (and -0x to -0X). */ + for (i = 0; i < len; i++) + if (buf[i] >= 'a' && buf[i] <= 'x') + buf[i] -= 'a'-'A'; + } + *pbuf = buf; + *plen = len; + return result; } void PyBytes_Fini(void) { - int i; - for (i = 0; i < UCHAR_MAX + 1; i++) { - Py_XDECREF(characters[i]); - characters[i] = NULL; - } - Py_XDECREF(nullstring); - nullstring = NULL; + int i; + for (i = 0; i < UCHAR_MAX + 1; i++) { + Py_XDECREF(characters[i]); + characters[i] = NULL; + } + Py_XDECREF(nullstring); + nullstring = NULL; } /*********************** Bytes Iterator ****************************/ typedef struct { - PyObject_HEAD - Py_ssize_t it_index; - PyBytesObject *it_seq; /* Set to NULL when iterator is exhausted */ + 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); + _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; + Py_VISIT(it->it_seq); + return 0; } static PyObject * striter_next(striterobject *it) { - PyBytesObject *seq; - PyObject *item; + PyBytesObject *seq; + PyObject *item; + + assert(it != NULL); + seq = it->it_seq; + if (seq == NULL) + return NULL; + assert(PyBytes_Check(seq)); - 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; - } - - Py_DECREF(seq); - it->it_seq = NULL; - return NULL; + 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; + } + + Py_DECREF(seq); + it->it_seq = NULL; + 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); + 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))."); + "Private method returning an estimate of len(list(it))."); static PyMethodDef striter_methods[] = { - {"__length_hint__", (PyCFunction)striter_len, METH_NOARGS, - length_hint_doc}, - {NULL, NULL} /* sentinel */ + {"__length_hint__", (PyCFunction)striter_len, METH_NOARGS, + length_hint_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, + 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; + 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; + 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; } Modified: python/branches/py3k/Objects/cellobject.c ============================================================================== --- python/branches/py3k/Objects/cellobject.c (original) +++ python/branches/py3k/Objects/cellobject.c Sun May 9 17:52:27 2010 @@ -5,50 +5,50 @@ PyObject * PyCell_New(PyObject *obj) { - PyCellObject *op; + PyCellObject *op; - op = (PyCellObject *)PyObject_GC_New(PyCellObject, &PyCell_Type); - if (op == NULL) - return NULL; - op->ob_ref = obj; - Py_XINCREF(obj); + op = (PyCellObject *)PyObject_GC_New(PyCellObject, &PyCell_Type); + if (op == NULL) + return NULL; + op->ob_ref = obj; + Py_XINCREF(obj); - _PyObject_GC_TRACK(op); - return (PyObject *)op; + _PyObject_GC_TRACK(op); + return (PyObject *)op; } PyObject * PyCell_Get(PyObject *op) { - if (!PyCell_Check(op)) { - PyErr_BadInternalCall(); - return NULL; - } - Py_XINCREF(((PyCellObject*)op)->ob_ref); - return PyCell_GET(op); + if (!PyCell_Check(op)) { + PyErr_BadInternalCall(); + return NULL; + } + Py_XINCREF(((PyCellObject*)op)->ob_ref); + return PyCell_GET(op); } int PyCell_Set(PyObject *op, PyObject *obj) { - PyObject* oldobj; - if (!PyCell_Check(op)) { - PyErr_BadInternalCall(); - return -1; - } - oldobj = PyCell_GET(op); - Py_XINCREF(obj); - PyCell_SET(op, obj); - Py_XDECREF(oldobj); - return 0; + PyObject* oldobj; + if (!PyCell_Check(op)) { + PyErr_BadInternalCall(); + return -1; + } + oldobj = PyCell_GET(op); + Py_XINCREF(obj); + PyCell_SET(op, obj); + Py_XDECREF(oldobj); + return 0; } static void cell_dealloc(PyCellObject *op) { - _PyObject_GC_UNTRACK(op); - Py_XDECREF(op->ob_ref); - PyObject_GC_Del(op); + _PyObject_GC_UNTRACK(op); + Py_XDECREF(op->ob_ref); + PyObject_GC_Del(op); } #define TEST_COND(cond) ((cond) ? Py_True : Py_False) @@ -56,124 +56,124 @@ static PyObject * cell_richcompare(PyObject *a, PyObject *b, int op) { - int result; - PyObject *v; + int result; + PyObject *v; - /* neither argument should be NULL, unless something's gone wrong */ - assert(a != NULL && b != NULL); + /* neither argument should be NULL, unless something's gone wrong */ + assert(a != NULL && b != NULL); - /* both arguments should be instances of PyCellObject */ - if (!PyCell_Check(a) || !PyCell_Check(b)) { - v = Py_NotImplemented; - Py_INCREF(v); - return v; - } - - /* compare cells by contents; empty cells come before anything else */ - a = ((PyCellObject *)a)->ob_ref; - b = ((PyCellObject *)b)->ob_ref; - if (a != NULL && b != NULL) - return PyObject_RichCompare(a, b, op); - - result = (b == NULL) - (a == NULL); - switch (op) { - case Py_EQ: - v = TEST_COND(result == 0); - break; - case Py_NE: - v = TEST_COND(result != 0); - break; - case Py_LE: - v = TEST_COND(result <= 0); - break; - case Py_GE: - v = TEST_COND(result >= 0); - break; - case Py_LT: - v = TEST_COND(result < 0); - break; - case Py_GT: - v = TEST_COND(result > 0); - break; - default: - PyErr_BadArgument(); - return NULL; - } - Py_INCREF(v); - return v; + /* both arguments should be instances of PyCellObject */ + if (!PyCell_Check(a) || !PyCell_Check(b)) { + v = Py_NotImplemented; + Py_INCREF(v); + return v; + } + + /* compare cells by contents; empty cells come before anything else */ + a = ((PyCellObject *)a)->ob_ref; + b = ((PyCellObject *)b)->ob_ref; + if (a != NULL && b != NULL) + return PyObject_RichCompare(a, b, op); + + result = (b == NULL) - (a == NULL); + switch (op) { + case Py_EQ: + v = TEST_COND(result == 0); + break; + case Py_NE: + v = TEST_COND(result != 0); + break; + case Py_LE: + v = TEST_COND(result <= 0); + break; + case Py_GE: + v = TEST_COND(result >= 0); + break; + case Py_LT: + v = TEST_COND(result < 0); + break; + case Py_GT: + v = TEST_COND(result > 0); + break; + default: + PyErr_BadArgument(); + return NULL; + } + Py_INCREF(v); + return v; } static PyObject * cell_repr(PyCellObject *op) { - if (op->ob_ref == NULL) - return PyUnicode_FromFormat("", op); + if (op->ob_ref == NULL) + return PyUnicode_FromFormat("", op); - return PyUnicode_FromFormat("", - op, op->ob_ref->ob_type->tp_name, - op->ob_ref); + return PyUnicode_FromFormat("", + op, op->ob_ref->ob_type->tp_name, + op->ob_ref); } static int cell_traverse(PyCellObject *op, visitproc visit, void *arg) { - Py_VISIT(op->ob_ref); - return 0; + Py_VISIT(op->ob_ref); + return 0; } static int cell_clear(PyCellObject *op) { - Py_CLEAR(op->ob_ref); - return 0; + Py_CLEAR(op->ob_ref); + return 0; } static PyObject * cell_get_contents(PyCellObject *op, void *closure) { - if (op->ob_ref == NULL) - { - PyErr_SetString(PyExc_ValueError, "Cell is empty"); - return NULL; - } - Py_INCREF(op->ob_ref); - return op->ob_ref; + if (op->ob_ref == NULL) + { + PyErr_SetString(PyExc_ValueError, "Cell is empty"); + return NULL; + } + Py_INCREF(op->ob_ref); + return op->ob_ref; } static PyGetSetDef cell_getsetlist[] = { - {"cell_contents", (getter)cell_get_contents, NULL}, - {NULL} /* sentinel */ + {"cell_contents", (getter)cell_get_contents, NULL}, + {NULL} /* sentinel */ }; PyTypeObject PyCell_Type = { - PyVarObject_HEAD_INIT(&PyType_Type, 0) - "cell", - sizeof(PyCellObject), - 0, - (destructor)cell_dealloc, /* tp_dealloc */ - 0, /* tp_print */ - 0, /* tp_getattr */ - 0, /* tp_setattr */ - 0, /* tp_reserved */ - (reprfunc)cell_repr, /* 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)cell_traverse, /* tp_traverse */ - (inquiry)cell_clear, /* tp_clear */ - cell_richcompare, /* tp_richcompare */ - 0, /* tp_weaklistoffset */ - 0, /* tp_iter */ - 0, /* tp_iternext */ - 0, /* tp_methods */ - 0, /* tp_members */ - cell_getsetlist, /* tp_getset */ + PyVarObject_HEAD_INIT(&PyType_Type, 0) + "cell", + sizeof(PyCellObject), + 0, + (destructor)cell_dealloc, /* tp_dealloc */ + 0, /* tp_print */ + 0, /* tp_getattr */ + 0, /* tp_setattr */ + 0, /* tp_reserved */ + (reprfunc)cell_repr, /* 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)cell_traverse, /* tp_traverse */ + (inquiry)cell_clear, /* tp_clear */ + cell_richcompare, /* tp_richcompare */ + 0, /* tp_weaklistoffset */ + 0, /* tp_iter */ + 0, /* tp_iternext */ + 0, /* tp_methods */ + 0, /* tp_members */ + cell_getsetlist, /* tp_getset */ }; Modified: python/branches/py3k/Objects/classobject.c ============================================================================== --- python/branches/py3k/Objects/classobject.c (original) +++ python/branches/py3k/Objects/classobject.c Sun May 9 17:52:27 2010 @@ -17,21 +17,21 @@ PyObject * PyMethod_Function(PyObject *im) { - if (!PyMethod_Check(im)) { - PyErr_BadInternalCall(); - return NULL; - } - return ((PyMethodObject *)im)->im_func; + if (!PyMethod_Check(im)) { + PyErr_BadInternalCall(); + return NULL; + } + return ((PyMethodObject *)im)->im_func; } PyObject * PyMethod_Self(PyObject *im) { - if (!PyMethod_Check(im)) { - PyErr_BadInternalCall(); - return NULL; - } - return ((PyMethodObject *)im)->im_self; + if (!PyMethod_Check(im)) { + PyErr_BadInternalCall(); + return NULL; + } + return ((PyMethodObject *)im)->im_self; } /* Method objects are used for bound instance methods returned by @@ -42,29 +42,29 @@ PyObject * PyMethod_New(PyObject *func, PyObject *self) { - register PyMethodObject *im; - if (self == NULL) { - PyErr_BadInternalCall(); - return NULL; - } - im = free_list; - if (im != NULL) { - free_list = (PyMethodObject *)(im->im_self); - PyObject_INIT(im, &PyMethod_Type); - numfree--; - } - else { - im = PyObject_GC_New(PyMethodObject, &PyMethod_Type); - if (im == NULL) - return NULL; - } - im->im_weakreflist = NULL; - Py_INCREF(func); - im->im_func = func; - Py_XINCREF(self); - im->im_self = self; - _PyObject_GC_TRACK(im); - return (PyObject *)im; + register PyMethodObject *im; + if (self == NULL) { + PyErr_BadInternalCall(); + return NULL; + } + im = free_list; + if (im != NULL) { + free_list = (PyMethodObject *)(im->im_self); + PyObject_INIT(im, &PyMethod_Type); + numfree--; + } + else { + im = PyObject_GC_New(PyMethodObject, &PyMethod_Type); + if (im == NULL) + return NULL; + } + im->im_weakreflist = NULL; + Py_INCREF(func); + im->im_func = func; + Py_XINCREF(self); + im->im_self = self; + _PyObject_GC_TRACK(im); + return (PyObject *)im; } /* Descriptors for PyMethod attributes */ @@ -74,11 +74,11 @@ #define MO_OFF(x) offsetof(PyMethodObject, x) static PyMemberDef method_memberlist[] = { - {"__func__", T_OBJECT, MO_OFF(im_func), READONLY|RESTRICTED, - "the function (or other callable) implementing a method"}, - {"__self__", T_OBJECT, MO_OFF(im_self), READONLY|RESTRICTED, - "the instance to which a method is bound"}, - {NULL} /* Sentinel */ + {"__func__", T_OBJECT, MO_OFF(im_func), READONLY|RESTRICTED, + "the function (or other callable) implementing a method"}, + {"__self__", T_OBJECT, MO_OFF(im_self), READONLY|RESTRICTED, + "the instance to which a method is bound"}, + {NULL} /* Sentinel */ }; /* Christian Tismer argued convincingly that method attributes should @@ -89,46 +89,46 @@ static PyObject * method_get_doc(PyMethodObject *im, void *context) { - static PyObject *docstr; - if (docstr == NULL) { - docstr= PyUnicode_InternFromString("__doc__"); - if (docstr == NULL) - return NULL; - } - return PyObject_GetAttr(im->im_func, docstr); + static PyObject *docstr; + if (docstr == NULL) { + docstr= PyUnicode_InternFromString("__doc__"); + if (docstr == NULL) + return NULL; + } + return PyObject_GetAttr(im->im_func, docstr); } static PyGetSetDef method_getset[] = { - {"__doc__", (getter)method_get_doc, NULL, NULL}, - {0} + {"__doc__", (getter)method_get_doc, NULL, NULL}, + {0} }; static PyObject * method_getattro(PyObject *obj, PyObject *name) { - PyMethodObject *im = (PyMethodObject *)obj; - PyTypeObject *tp = obj->ob_type; - PyObject *descr = NULL; - - { - if (tp->tp_dict == NULL) { - if (PyType_Ready(tp) < 0) - return NULL; - } - descr = _PyType_Lookup(tp, name); - } - - if (descr != NULL) { - descrgetfunc f = TP_DESCR_GET(descr->ob_type); - if (f != NULL) - return f(descr, obj, (PyObject *)obj->ob_type); - else { - Py_INCREF(descr); - return descr; - } - } + PyMethodObject *im = (PyMethodObject *)obj; + PyTypeObject *tp = obj->ob_type; + PyObject *descr = NULL; + + { + if (tp->tp_dict == NULL) { + if (PyType_Ready(tp) < 0) + return NULL; + } + descr = _PyType_Lookup(tp, name); + } + + if (descr != NULL) { + descrgetfunc f = TP_DESCR_GET(descr->ob_type); + if (f != NULL) + return f(descr, obj, (PyObject *)obj->ob_type); + else { + Py_INCREF(descr); + return descr; + } + } - return PyObject_GetAttr(im->im_func, name); + return PyObject_GetAttr(im->im_func, name); } PyDoc_STRVAR(method_doc, @@ -139,241 +139,241 @@ static PyObject * method_new(PyTypeObject* type, PyObject* args, PyObject *kw) { - PyObject *func; - PyObject *self; + PyObject *func; + PyObject *self; - if (!_PyArg_NoKeywords("method", kw)) - return NULL; - if (!PyArg_UnpackTuple(args, "method", 2, 2, - &func, &self)) - return NULL; - if (!PyCallable_Check(func)) { - PyErr_SetString(PyExc_TypeError, - "first argument must be callable"); - return NULL; - } - if (self == NULL || self == Py_None) { - PyErr_SetString(PyExc_TypeError, - "self must not be None"); - return NULL; - } + if (!_PyArg_NoKeywords("method", kw)) + return NULL; + if (!PyArg_UnpackTuple(args, "method", 2, 2, + &func, &self)) + return NULL; + if (!PyCallable_Check(func)) { + PyErr_SetString(PyExc_TypeError, + "first argument must be callable"); + return NULL; + } + if (self == NULL || self == Py_None) { + PyErr_SetString(PyExc_TypeError, + "self must not be None"); + return NULL; + } - return PyMethod_New(func, self); + return PyMethod_New(func, self); } static void method_dealloc(register PyMethodObject *im) { - _PyObject_GC_UNTRACK(im); - if (im->im_weakreflist != NULL) - PyObject_ClearWeakRefs((PyObject *)im); - Py_DECREF(im->im_func); - Py_XDECREF(im->im_self); - if (numfree < PyMethod_MAXFREELIST) { - im->im_self = (PyObject *)free_list; - free_list = im; - numfree++; - } - else { - PyObject_GC_Del(im); - } + _PyObject_GC_UNTRACK(im); + if (im->im_weakreflist != NULL) + PyObject_ClearWeakRefs((PyObject *)im); + Py_DECREF(im->im_func); + Py_XDECREF(im->im_self); + if (numfree < PyMethod_MAXFREELIST) { + im->im_self = (PyObject *)free_list; + free_list = im; + numfree++; + } + else { + PyObject_GC_Del(im); + } } static PyObject * method_richcompare(PyObject *self, PyObject *other, int op) { - PyMethodObject *a, *b; - PyObject *res; - int eq; - - if ((op != Py_EQ && op != Py_NE) || - !PyMethod_Check(self) || - !PyMethod_Check(other)) - { - Py_INCREF(Py_NotImplemented); - return Py_NotImplemented; - } - a = (PyMethodObject *)self; - b = (PyMethodObject *)other; - eq = PyObject_RichCompareBool(a->im_func, b->im_func, Py_EQ); - if (eq == 1) { - if (a->im_self == NULL || b->im_self == NULL) - eq = a->im_self == b->im_self; - else - eq = PyObject_RichCompareBool(a->im_self, b->im_self, - Py_EQ); - } - if (eq < 0) - return NULL; - if (op == Py_EQ) - res = eq ? Py_True : Py_False; - else - res = eq ? Py_False : Py_True; - Py_INCREF(res); - return res; + PyMethodObject *a, *b; + PyObject *res; + int eq; + + if ((op != Py_EQ && op != Py_NE) || + !PyMethod_Check(self) || + !PyMethod_Check(other)) + { + Py_INCREF(Py_NotImplemented); + return Py_NotImplemented; + } + a = (PyMethodObject *)self; + b = (PyMethodObject *)other; + eq = PyObject_RichCompareBool(a->im_func, b->im_func, Py_EQ); + if (eq == 1) { + if (a->im_self == NULL || b->im_self == NULL) + eq = a->im_self == b->im_self; + else + eq = PyObject_RichCompareBool(a->im_self, b->im_self, + Py_EQ); + } + if (eq < 0) + return NULL; + if (op == Py_EQ) + res = eq ? Py_True : Py_False; + else + res = eq ? Py_False : Py_True; + Py_INCREF(res); + return res; } static PyObject * method_repr(PyMethodObject *a) { - PyObject *self = a->im_self; - PyObject *func = a->im_func; - PyObject *klass = (PyObject*)Py_TYPE(self); - PyObject *funcname = NULL ,*klassname = NULL, *result = NULL; - char *defname = "?"; - - if (self == NULL) { - PyErr_BadInternalCall(); - return NULL; - } - - funcname = PyObject_GetAttrString(func, "__name__"); - if (funcname == NULL) { - if (!PyErr_ExceptionMatches(PyExc_AttributeError)) - return NULL; - PyErr_Clear(); - } - else if (!PyUnicode_Check(funcname)) { - Py_DECREF(funcname); - funcname = NULL; - } - - if (klass == NULL) - klassname = NULL; - else { - klassname = PyObject_GetAttrString(klass, "__name__"); - if (klassname == NULL) { - if (!PyErr_ExceptionMatches(PyExc_AttributeError)) - return NULL; - PyErr_Clear(); - } - else if (!PyUnicode_Check(klassname)) { - Py_DECREF(klassname); - klassname = NULL; - } - } - - /* XXX Shouldn't use repr()/%R here! */ - result = PyUnicode_FromFormat("", - klassname, defname, - funcname, defname, self); - - Py_XDECREF(funcname); - Py_XDECREF(klassname); - return result; + PyObject *self = a->im_self; + PyObject *func = a->im_func; + PyObject *klass = (PyObject*)Py_TYPE(self); + PyObject *funcname = NULL ,*klassname = NULL, *result = NULL; + char *defname = "?"; + + if (self == NULL) { + PyErr_BadInternalCall(); + return NULL; + } + + funcname = PyObject_GetAttrString(func, "__name__"); + if (funcname == NULL) { + if (!PyErr_ExceptionMatches(PyExc_AttributeError)) + return NULL; + PyErr_Clear(); + } + else if (!PyUnicode_Check(funcname)) { + Py_DECREF(funcname); + funcname = NULL; + } + + if (klass == NULL) + klassname = NULL; + else { + klassname = PyObject_GetAttrString(klass, "__name__"); + if (klassname == NULL) { + if (!PyErr_ExceptionMatches(PyExc_AttributeError)) + return NULL; + PyErr_Clear(); + } + else if (!PyUnicode_Check(klassname)) { + Py_DECREF(klassname); + klassname = NULL; + } + } + + /* XXX Shouldn't use repr()/%R here! */ + result = PyUnicode_FromFormat("", + klassname, defname, + funcname, defname, self); + + Py_XDECREF(funcname); + Py_XDECREF(klassname); + return result; } static long method_hash(PyMethodObject *a) { - long x, y; - if (a->im_self == NULL) - x = PyObject_Hash(Py_None); - else - x = PyObject_Hash(a->im_self); - if (x == -1) - return -1; - y = PyObject_Hash(a->im_func); - if (y == -1) - return -1; - x = x ^ y; - if (x == -1) - x = -2; - return x; + long x, y; + if (a->im_self == NULL) + x = PyObject_Hash(Py_None); + else + x = PyObject_Hash(a->im_self); + if (x == -1) + return -1; + y = PyObject_Hash(a->im_func); + if (y == -1) + return -1; + x = x ^ y; + if (x == -1) + x = -2; + return x; } static int method_traverse(PyMethodObject *im, visitproc visit, void *arg) { - Py_VISIT(im->im_func); - Py_VISIT(im->im_self); - return 0; + Py_VISIT(im->im_func); + Py_VISIT(im->im_self); + return 0; } static PyObject * method_call(PyObject *func, PyObject *arg, PyObject *kw) { - PyObject *self = PyMethod_GET_SELF(func); - PyObject *result; + PyObject *self = PyMethod_GET_SELF(func); + PyObject *result; - func = PyMethod_GET_FUNCTION(func); - if (self == NULL) { - PyErr_BadInternalCall(); - return NULL; - } - else { - Py_ssize_t argcount = PyTuple_Size(arg); - PyObject *newarg = PyTuple_New(argcount + 1); - int i; - if (newarg == NULL) - return NULL; - Py_INCREF(self); - PyTuple_SET_ITEM(newarg, 0, self); - for (i = 0; i < argcount; i++) { - PyObject *v = PyTuple_GET_ITEM(arg, i); - Py_XINCREF(v); - PyTuple_SET_ITEM(newarg, i+1, v); - } - arg = newarg; - } - result = PyObject_Call((PyObject *)func, arg, kw); - Py_DECREF(arg); - return result; + func = PyMethod_GET_FUNCTION(func); + if (self == NULL) { + PyErr_BadInternalCall(); + return NULL; + } + else { + Py_ssize_t argcount = PyTuple_Size(arg); + PyObject *newarg = PyTuple_New(argcount + 1); + int i; + if (newarg == NULL) + return NULL; + Py_INCREF(self); + PyTuple_SET_ITEM(newarg, 0, self); + for (i = 0; i < argcount; i++) { + PyObject *v = PyTuple_GET_ITEM(arg, i); + Py_XINCREF(v); + PyTuple_SET_ITEM(newarg, i+1, v); + } + arg = newarg; + } + result = PyObject_Call((PyObject *)func, arg, kw); + Py_DECREF(arg); + return result; } static PyObject * method_descr_get(PyObject *meth, PyObject *obj, PyObject *cls) { - /* Don't rebind an already bound method of a class that's not a base - class of cls. */ - if (PyMethod_GET_SELF(meth) != NULL) { - /* Already bound */ - Py_INCREF(meth); - return meth; - } - /* Bind it to obj */ - return PyMethod_New(PyMethod_GET_FUNCTION(meth), obj); + /* Don't rebind an already bound method of a class that's not a base + class of cls. */ + if (PyMethod_GET_SELF(meth) != NULL) { + /* Already bound */ + Py_INCREF(meth); + return meth; + } + /* Bind it to obj */ + return PyMethod_New(PyMethod_GET_FUNCTION(meth), obj); } PyTypeObject PyMethod_Type = { - PyVarObject_HEAD_INIT(&PyType_Type, 0) - "method", - sizeof(PyMethodObject), - 0, - (destructor)method_dealloc, /* tp_dealloc */ - 0, /* tp_print */ - 0, /* tp_getattr */ - 0, /* tp_setattr */ - 0, /* tp_reserved */ - (reprfunc)method_repr, /* tp_repr */ - 0, /* tp_as_number */ - 0, /* tp_as_sequence */ - 0, /* tp_as_mapping */ - (hashfunc)method_hash, /* tp_hash */ - method_call, /* tp_call */ - 0, /* tp_str */ - method_getattro, /* tp_getattro */ - PyObject_GenericSetAttr, /* tp_setattro */ - 0, /* tp_as_buffer */ - Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC, /* tp_flags */ - method_doc, /* tp_doc */ - (traverseproc)method_traverse, /* tp_traverse */ - 0, /* tp_clear */ - method_richcompare, /* tp_richcompare */ - offsetof(PyMethodObject, im_weakreflist), /* tp_weaklistoffset */ - 0, /* tp_iter */ - 0, /* tp_iternext */ - 0, /* tp_methods */ - method_memberlist, /* tp_members */ - method_getset, /* tp_getset */ - 0, /* tp_base */ - 0, /* tp_dict */ - method_descr_get, /* tp_descr_get */ - 0, /* tp_descr_set */ - 0, /* tp_dictoffset */ - 0, /* tp_init */ - 0, /* tp_alloc */ - method_new, /* tp_new */ + PyVarObject_HEAD_INIT(&PyType_Type, 0) + "method", + sizeof(PyMethodObject), + 0, + (destructor)method_dealloc, /* tp_dealloc */ + 0, /* tp_print */ + 0, /* tp_getattr */ + 0, /* tp_setattr */ + 0, /* tp_reserved */ + (reprfunc)method_repr, /* tp_repr */ + 0, /* tp_as_number */ + 0, /* tp_as_sequence */ + 0, /* tp_as_mapping */ + (hashfunc)method_hash, /* tp_hash */ + method_call, /* tp_call */ + 0, /* tp_str */ + method_getattro, /* tp_getattro */ + PyObject_GenericSetAttr, /* tp_setattro */ + 0, /* tp_as_buffer */ + Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC, /* tp_flags */ + method_doc, /* tp_doc */ + (traverseproc)method_traverse, /* tp_traverse */ + 0, /* tp_clear */ + method_richcompare, /* tp_richcompare */ + offsetof(PyMethodObject, im_weakreflist), /* tp_weaklistoffset */ + 0, /* tp_iter */ + 0, /* tp_iternext */ + 0, /* tp_methods */ + method_memberlist, /* tp_members */ + method_getset, /* tp_getset */ + 0, /* tp_base */ + 0, /* tp_dict */ + method_descr_get, /* tp_descr_get */ + 0, /* tp_descr_set */ + 0, /* tp_dictoffset */ + 0, /* tp_init */ + 0, /* tp_alloc */ + method_new, /* tp_new */ }; /* Clear out the free list */ @@ -381,22 +381,22 @@ int PyMethod_ClearFreeList(void) { - int freelist_size = numfree; - - while (free_list) { - PyMethodObject *im = free_list; - free_list = (PyMethodObject *)(im->im_self); - PyObject_GC_Del(im); - numfree--; - } - assert(numfree == 0); - return freelist_size; + int freelist_size = numfree; + + while (free_list) { + PyMethodObject *im = free_list; + free_list = (PyMethodObject *)(im->im_self); + PyObject_GC_Del(im); + numfree--; + } + assert(numfree == 0); + return freelist_size; } void PyMethod_Fini(void) { - (void)PyMethod_ClearFreeList(); + (void)PyMethod_ClearFreeList(); } /* ------------------------------------------------------------------------ @@ -405,176 +405,176 @@ PyObject * PyInstanceMethod_New(PyObject *func) { - PyInstanceMethodObject *method; - method = PyObject_GC_New(PyInstanceMethodObject, - &PyInstanceMethod_Type); - if (method == NULL) return NULL; - Py_INCREF(func); - method->func = func; - _PyObject_GC_TRACK(method); - return (PyObject *)method; + PyInstanceMethodObject *method; + method = PyObject_GC_New(PyInstanceMethodObject, + &PyInstanceMethod_Type); + if (method == NULL) return NULL; + Py_INCREF(func); + method->func = func; + _PyObject_GC_TRACK(method); + return (PyObject *)method; } PyObject * PyInstanceMethod_Function(PyObject *im) { - if (!PyInstanceMethod_Check(im)) { - PyErr_BadInternalCall(); - return NULL; - } - return PyInstanceMethod_GET_FUNCTION(im); + if (!PyInstanceMethod_Check(im)) { + PyErr_BadInternalCall(); + return NULL; + } + return PyInstanceMethod_GET_FUNCTION(im); } #define IMO_OFF(x) offsetof(PyInstanceMethodObject, x) static PyMemberDef instancemethod_memberlist[] = { - {"__func__", T_OBJECT, IMO_OFF(func), READONLY|RESTRICTED, - "the function (or other callable) implementing a method"}, - {NULL} /* Sentinel */ + {"__func__", T_OBJECT, IMO_OFF(func), READONLY|RESTRICTED, + "the function (or other callable) implementing a method"}, + {NULL} /* Sentinel */ }; static PyObject * instancemethod_get_doc(PyObject *self, void *context) { - static PyObject *docstr; - if (docstr == NULL) { - docstr = PyUnicode_InternFromString("__doc__"); - if (docstr == NULL) - return NULL; - } - return PyObject_GetAttr(PyInstanceMethod_GET_FUNCTION(self), docstr); + static PyObject *docstr; + if (docstr == NULL) { + docstr = PyUnicode_InternFromString("__doc__"); + if (docstr == NULL) + return NULL; + } + return PyObject_GetAttr(PyInstanceMethod_GET_FUNCTION(self), docstr); } static PyGetSetDef instancemethod_getset[] = { - {"__doc__", (getter)instancemethod_get_doc, NULL, NULL}, - {0} + {"__doc__", (getter)instancemethod_get_doc, NULL, NULL}, + {0} }; static PyObject * instancemethod_getattro(PyObject *self, PyObject *name) { - PyTypeObject *tp = self->ob_type; - PyObject *descr = NULL; + PyTypeObject *tp = self->ob_type; + PyObject *descr = NULL; - if (tp->tp_dict == NULL) { - if (PyType_Ready(tp) < 0) - return NULL; - } - descr = _PyType_Lookup(tp, name); - - if (descr != NULL) { - descrgetfunc f = TP_DESCR_GET(descr->ob_type); - if (f != NULL) - return f(descr, self, (PyObject *)self->ob_type); - else { - Py_INCREF(descr); - return descr; - } - } + if (tp->tp_dict == NULL) { + if (PyType_Ready(tp) < 0) + return NULL; + } + descr = _PyType_Lookup(tp, name); + + if (descr != NULL) { + descrgetfunc f = TP_DESCR_GET(descr->ob_type); + if (f != NULL) + return f(descr, self, (PyObject *)self->ob_type); + else { + Py_INCREF(descr); + return descr; + } + } - return PyObject_GetAttr(PyInstanceMethod_GET_FUNCTION(self), name); + return PyObject_GetAttr(PyInstanceMethod_GET_FUNCTION(self), name); } static void instancemethod_dealloc(PyObject *self) { - _PyObject_GC_UNTRACK(self); - Py_DECREF(PyInstanceMethod_GET_FUNCTION(self)); - PyObject_GC_Del(self); + _PyObject_GC_UNTRACK(self); + Py_DECREF(PyInstanceMethod_GET_FUNCTION(self)); + PyObject_GC_Del(self); } static int instancemethod_traverse(PyObject *self, visitproc visit, void *arg) { - Py_VISIT(PyInstanceMethod_GET_FUNCTION(self)); - return 0; + Py_VISIT(PyInstanceMethod_GET_FUNCTION(self)); + return 0; } static PyObject * instancemethod_call(PyObject *self, PyObject *arg, PyObject *kw) { - return PyObject_Call(PyMethod_GET_FUNCTION(self), arg, kw); + return PyObject_Call(PyMethod_GET_FUNCTION(self), arg, kw); } static PyObject * instancemethod_descr_get(PyObject *descr, PyObject *obj, PyObject *type) { - register PyObject *func = PyInstanceMethod_GET_FUNCTION(descr); - if (obj == NULL) { - Py_INCREF(func); - return func; - } - else - return PyMethod_New(func, obj); + register PyObject *func = PyInstanceMethod_GET_FUNCTION(descr); + if (obj == NULL) { + Py_INCREF(func); + return func; + } + else + return PyMethod_New(func, obj); } static PyObject * instancemethod_richcompare(PyObject *self, PyObject *other, int op) { - PyInstanceMethodObject *a, *b; - PyObject *res; - int eq; - - if ((op != Py_EQ && op != Py_NE) || - !PyInstanceMethod_Check(self) || - !PyInstanceMethod_Check(other)) - { - Py_INCREF(Py_NotImplemented); - return Py_NotImplemented; - } - a = (PyInstanceMethodObject *)self; - b = (PyInstanceMethodObject *)other; - eq = PyObject_RichCompareBool(a->func, b->func, Py_EQ); - if (eq < 0) - return NULL; - if (op == Py_EQ) - res = eq ? Py_True : Py_False; - else - res = eq ? Py_False : Py_True; - Py_INCREF(res); - return res; + PyInstanceMethodObject *a, *b; + PyObject *res; + int eq; + + if ((op != Py_EQ && op != Py_NE) || + !PyInstanceMethod_Check(self) || + !PyInstanceMethod_Check(other)) + { + Py_INCREF(Py_NotImplemented); + return Py_NotImplemented; + } + a = (PyInstanceMethodObject *)self; + b = (PyInstanceMethodObject *)other; + eq = PyObject_RichCompareBool(a->func, b->func, Py_EQ); + if (eq < 0) + return NULL; + if (op == Py_EQ) + res = eq ? Py_True : Py_False; + else + res = eq ? Py_False : Py_True; + Py_INCREF(res); + return res; } static PyObject * instancemethod_repr(PyObject *self) { - PyObject *func = PyInstanceMethod_Function(self); - PyObject *funcname = NULL , *result = NULL; - char *defname = "?"; - - if (func == NULL) { - PyErr_BadInternalCall(); - return NULL; - } - - funcname = PyObject_GetAttrString(func, "__name__"); - if (funcname == NULL) { - if (!PyErr_ExceptionMatches(PyExc_AttributeError)) - return NULL; - PyErr_Clear(); - } - else if (!PyUnicode_Check(funcname)) { - Py_DECREF(funcname); - funcname = NULL; - } + PyObject *func = PyInstanceMethod_Function(self); + PyObject *funcname = NULL , *result = NULL; + char *defname = "?"; + + if (func == NULL) { + PyErr_BadInternalCall(); + return NULL; + } + + funcname = PyObject_GetAttrString(func, "__name__"); + if (funcname == NULL) { + if (!PyErr_ExceptionMatches(PyExc_AttributeError)) + return NULL; + PyErr_Clear(); + } + else if (!PyUnicode_Check(funcname)) { + Py_DECREF(funcname); + funcname = NULL; + } - result = PyUnicode_FromFormat("", - funcname, defname, self); + result = PyUnicode_FromFormat("", + funcname, defname, self); - Py_XDECREF(funcname); - return result; + Py_XDECREF(funcname); + return result; } /* static long instancemethod_hash(PyObject *self) { - long x, y; - x = (long)self; - y = PyObject_Hash(PyInstanceMethod_GET_FUNCTION(self)); - if (y == -1) - return -1; - x = x ^ y; - if (x == -1) - x = -2; - return x; + long x, y; + x = (long)self; + y = PyObject_Hash(PyInstanceMethod_GET_FUNCTION(self)); + if (y == -1) + return -1; + x = x ^ y; + if (x == -1) + x = -2; + return x; } */ @@ -586,59 +586,59 @@ static PyObject * instancemethod_new(PyTypeObject* type, PyObject* args, PyObject *kw) { - PyObject *func; + PyObject *func; - if (!_PyArg_NoKeywords("instancemethod", kw)) - return NULL; - if (!PyArg_UnpackTuple(args, "instancemethod", 1, 1, &func)) - return NULL; - if (!PyCallable_Check(func)) { - PyErr_SetString(PyExc_TypeError, - "first argument must be callable"); - return NULL; - } + if (!_PyArg_NoKeywords("instancemethod", kw)) + return NULL; + if (!PyArg_UnpackTuple(args, "instancemethod", 1, 1, &func)) + return NULL; + if (!PyCallable_Check(func)) { + PyErr_SetString(PyExc_TypeError, + "first argument must be callable"); + return NULL; + } - return PyInstanceMethod_New(func); + return PyInstanceMethod_New(func); } PyTypeObject PyInstanceMethod_Type = { - PyVarObject_HEAD_INIT(&PyType_Type, 0) - "instancemethod", /* tp_name */ - sizeof(PyInstanceMethodObject), /* tp_basicsize */ - 0, /* tp_itemsize */ - instancemethod_dealloc, /* tp_dealloc */ - 0, /* tp_print */ - 0, /* tp_getattr */ - 0, /* tp_setattr */ - 0, /* tp_reserved */ - (reprfunc)instancemethod_repr, /* tp_repr */ - 0, /* tp_as_number */ - 0, /* tp_as_sequence */ - 0, /* tp_as_mapping */ - 0, /*(hashfunc)instancemethod_hash, tp_hash */ - instancemethod_call, /* tp_call */ - 0, /* tp_str */ - instancemethod_getattro, /* tp_getattro */ - PyObject_GenericSetAttr, /* tp_setattro */ - 0, /* tp_as_buffer */ - Py_TPFLAGS_DEFAULT - | Py_TPFLAGS_HAVE_GC, /* tp_flags */ - instancemethod_doc, /* tp_doc */ - instancemethod_traverse, /* tp_traverse */ - 0, /* tp_clear */ - instancemethod_richcompare, /* tp_richcompare */ - 0, /* tp_weaklistoffset */ - 0, /* tp_iter */ - 0, /* tp_iternext */ - 0, /* tp_methods */ - instancemethod_memberlist, /* tp_members */ - instancemethod_getset, /* tp_getset */ - 0, /* tp_base */ - 0, /* tp_dict */ - instancemethod_descr_get, /* tp_descr_get */ - 0, /* tp_descr_set */ - 0, /* tp_dictoffset */ - 0, /* tp_init */ - 0, /* tp_alloc */ - instancemethod_new, /* tp_new */ + PyVarObject_HEAD_INIT(&PyType_Type, 0) + "instancemethod", /* tp_name */ + sizeof(PyInstanceMethodObject), /* tp_basicsize */ + 0, /* tp_itemsize */ + instancemethod_dealloc, /* tp_dealloc */ + 0, /* tp_print */ + 0, /* tp_getattr */ + 0, /* tp_setattr */ + 0, /* tp_reserved */ + (reprfunc)instancemethod_repr, /* tp_repr */ + 0, /* tp_as_number */ + 0, /* tp_as_sequence */ + 0, /* tp_as_mapping */ + 0, /*(hashfunc)instancemethod_hash, tp_hash */ + instancemethod_call, /* tp_call */ + 0, /* tp_str */ + instancemethod_getattro, /* tp_getattro */ + PyObject_GenericSetAttr, /* tp_setattro */ + 0, /* tp_as_buffer */ + Py_TPFLAGS_DEFAULT + | Py_TPFLAGS_HAVE_GC, /* tp_flags */ + instancemethod_doc, /* tp_doc */ + instancemethod_traverse, /* tp_traverse */ + 0, /* tp_clear */ + instancemethod_richcompare, /* tp_richcompare */ + 0, /* tp_weaklistoffset */ + 0, /* tp_iter */ + 0, /* tp_iternext */ + 0, /* tp_methods */ + instancemethod_memberlist, /* tp_members */ + instancemethod_getset, /* tp_getset */ + 0, /* tp_base */ + 0, /* tp_dict */ + instancemethod_descr_get, /* tp_descr_get */ + 0, /* tp_descr_set */ + 0, /* tp_dictoffset */ + 0, /* tp_init */ + 0, /* tp_alloc */ + instancemethod_new, /* tp_new */ }; Modified: python/branches/py3k/Objects/codeobject.c ============================================================================== --- python/branches/py3k/Objects/codeobject.c (original) +++ python/branches/py3k/Objects/codeobject.c Sun May 9 17:52:27 2010 @@ -3,183 +3,183 @@ #include "structmember.h" #define NAME_CHARS \ - "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ_abcdefghijklmnopqrstuvwxyz" + "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ_abcdefghijklmnopqrstuvwxyz" /* all_name_chars(s): true iff all chars in s are valid NAME_CHARS */ static int all_name_chars(Py_UNICODE *s) { - static char ok_name_char[256]; - static unsigned char *name_chars = (unsigned char *)NAME_CHARS; + static char ok_name_char[256]; + static unsigned char *name_chars = (unsigned char *)NAME_CHARS; - if (ok_name_char[*name_chars] == 0) { - unsigned char *p; - for (p = name_chars; *p; p++) - ok_name_char[*p] = 1; - } - while (*s) { - if (*s >= 128) - return 0; - if (ok_name_char[*s++] == 0) - return 0; - } - return 1; + if (ok_name_char[*name_chars] == 0) { + unsigned char *p; + for (p = name_chars; *p; p++) + ok_name_char[*p] = 1; + } + while (*s) { + if (*s >= 128) + return 0; + if (ok_name_char[*s++] == 0) + return 0; + } + return 1; } static void intern_strings(PyObject *tuple) { - Py_ssize_t i; + Py_ssize_t i; - for (i = PyTuple_GET_SIZE(tuple); --i >= 0; ) { - PyObject *v = PyTuple_GET_ITEM(tuple, i); - if (v == NULL || !PyUnicode_CheckExact(v)) { - Py_FatalError("non-string found in code slot"); - } - PyUnicode_InternInPlace(&PyTuple_GET_ITEM(tuple, i)); - } + for (i = PyTuple_GET_SIZE(tuple); --i >= 0; ) { + PyObject *v = PyTuple_GET_ITEM(tuple, i); + if (v == NULL || !PyUnicode_CheckExact(v)) { + Py_FatalError("non-string found in code slot"); + } + PyUnicode_InternInPlace(&PyTuple_GET_ITEM(tuple, i)); + } } PyCodeObject * PyCode_New(int argcount, int kwonlyargcount, - int nlocals, int stacksize, int flags, - PyObject *code, PyObject *consts, PyObject *names, - PyObject *varnames, PyObject *freevars, PyObject *cellvars, - PyObject *filename, PyObject *name, int firstlineno, - PyObject *lnotab) -{ - PyCodeObject *co; - Py_ssize_t i; - - /* Check argument types */ - if (argcount < 0 || kwonlyargcount < 0 || nlocals < 0 || - code == NULL || - consts == NULL || !PyTuple_Check(consts) || - names == NULL || !PyTuple_Check(names) || - varnames == NULL || !PyTuple_Check(varnames) || - freevars == NULL || !PyTuple_Check(freevars) || - cellvars == NULL || !PyTuple_Check(cellvars) || - name == NULL || !PyUnicode_Check(name) || - filename == NULL || !PyUnicode_Check(filename) || - lnotab == NULL || !PyBytes_Check(lnotab) || - !PyObject_CheckReadBuffer(code)) { - PyErr_BadInternalCall(); - return NULL; - } - intern_strings(names); - intern_strings(varnames); - intern_strings(freevars); - intern_strings(cellvars); - /* Intern selected string constants */ - for (i = PyTuple_Size(consts); --i >= 0; ) { - PyObject *v = PyTuple_GetItem(consts, i); - if (!PyUnicode_Check(v)) - continue; - if (!all_name_chars(PyUnicode_AS_UNICODE(v))) - continue; - PyUnicode_InternInPlace(&PyTuple_GET_ITEM(consts, i)); - } - co = PyObject_NEW(PyCodeObject, &PyCode_Type); - if (co != NULL) { - co->co_argcount = argcount; - co->co_kwonlyargcount = kwonlyargcount; - co->co_nlocals = nlocals; - co->co_stacksize = stacksize; - co->co_flags = flags; - Py_INCREF(code); - co->co_code = code; - Py_INCREF(consts); - co->co_consts = consts; - Py_INCREF(names); - co->co_names = names; - Py_INCREF(varnames); - co->co_varnames = varnames; - Py_INCREF(freevars); - co->co_freevars = freevars; - Py_INCREF(cellvars); - co->co_cellvars = cellvars; - Py_INCREF(filename); - co->co_filename = filename; - Py_INCREF(name); - co->co_name = name; - co->co_firstlineno = firstlineno; - Py_INCREF(lnotab); - co->co_lnotab = lnotab; - co->co_zombieframe = NULL; - co->co_weakreflist = NULL; - } - return co; + int nlocals, int stacksize, int flags, + PyObject *code, PyObject *consts, PyObject *names, + PyObject *varnames, PyObject *freevars, PyObject *cellvars, + PyObject *filename, PyObject *name, int firstlineno, + PyObject *lnotab) +{ + PyCodeObject *co; + Py_ssize_t i; + + /* Check argument types */ + if (argcount < 0 || kwonlyargcount < 0 || nlocals < 0 || + code == NULL || + consts == NULL || !PyTuple_Check(consts) || + names == NULL || !PyTuple_Check(names) || + varnames == NULL || !PyTuple_Check(varnames) || + freevars == NULL || !PyTuple_Check(freevars) || + cellvars == NULL || !PyTuple_Check(cellvars) || + name == NULL || !PyUnicode_Check(name) || + filename == NULL || !PyUnicode_Check(filename) || + lnotab == NULL || !PyBytes_Check(lnotab) || + !PyObject_CheckReadBuffer(code)) { + PyErr_BadInternalCall(); + return NULL; + } + intern_strings(names); + intern_strings(varnames); + intern_strings(freevars); + intern_strings(cellvars); + /* Intern selected string constants */ + for (i = PyTuple_Size(consts); --i >= 0; ) { + PyObject *v = PyTuple_GetItem(consts, i); + if (!PyUnicode_Check(v)) + continue; + if (!all_name_chars(PyUnicode_AS_UNICODE(v))) + continue; + PyUnicode_InternInPlace(&PyTuple_GET_ITEM(consts, i)); + } + co = PyObject_NEW(PyCodeObject, &PyCode_Type); + if (co != NULL) { + co->co_argcount = argcount; + co->co_kwonlyargcount = kwonlyargcount; + co->co_nlocals = nlocals; + co->co_stacksize = stacksize; + co->co_flags = flags; + Py_INCREF(code); + co->co_code = code; + Py_INCREF(consts); + co->co_consts = consts; + Py_INCREF(names); + co->co_names = names; + Py_INCREF(varnames); + co->co_varnames = varnames; + Py_INCREF(freevars); + co->co_freevars = freevars; + Py_INCREF(cellvars); + co->co_cellvars = cellvars; + Py_INCREF(filename); + co->co_filename = filename; + Py_INCREF(name); + co->co_name = name; + co->co_firstlineno = firstlineno; + Py_INCREF(lnotab); + co->co_lnotab = lnotab; + co->co_zombieframe = NULL; + co->co_weakreflist = NULL; + } + return co; } PyCodeObject * PyCode_NewEmpty(const char *filename, const char *funcname, int firstlineno) { - static PyObject *emptystring = NULL; - static PyObject *nulltuple = NULL; - PyObject *filename_ob = NULL; - PyObject *funcname_ob = NULL; - PyCodeObject *result = NULL; - if (emptystring == NULL) { - emptystring = PyBytes_FromString(""); - if (emptystring == NULL) - goto failed; - } - if (nulltuple == NULL) { - nulltuple = PyTuple_New(0); - if (nulltuple == NULL) - goto failed; - } - funcname_ob = PyUnicode_FromString(funcname); - if (funcname_ob == NULL) - goto failed; - filename_ob = PyUnicode_DecodeFSDefault(filename); - if (filename_ob == NULL) - goto failed; - - result = PyCode_New(0, /* argcount */ - 0, /* kwonlyargcount */ - 0, /* nlocals */ - 0, /* stacksize */ - 0, /* flags */ - emptystring, /* code */ - nulltuple, /* consts */ - nulltuple, /* names */ - nulltuple, /* varnames */ - nulltuple, /* freevars */ - nulltuple, /* cellvars */ - filename_ob, /* filename */ - funcname_ob, /* name */ - firstlineno, /* firstlineno */ - emptystring /* lnotab */ - ); + static PyObject *emptystring = NULL; + static PyObject *nulltuple = NULL; + PyObject *filename_ob = NULL; + PyObject *funcname_ob = NULL; + PyCodeObject *result = NULL; + if (emptystring == NULL) { + emptystring = PyBytes_FromString(""); + if (emptystring == NULL) + goto failed; + } + if (nulltuple == NULL) { + nulltuple = PyTuple_New(0); + if (nulltuple == NULL) + goto failed; + } + funcname_ob = PyUnicode_FromString(funcname); + if (funcname_ob == NULL) + goto failed; + filename_ob = PyUnicode_DecodeFSDefault(filename); + if (filename_ob == NULL) + goto failed; + + result = PyCode_New(0, /* argcount */ + 0, /* kwonlyargcount */ + 0, /* nlocals */ + 0, /* stacksize */ + 0, /* flags */ + emptystring, /* code */ + nulltuple, /* consts */ + nulltuple, /* names */ + nulltuple, /* varnames */ + nulltuple, /* freevars */ + nulltuple, /* cellvars */ + filename_ob, /* filename */ + funcname_ob, /* name */ + firstlineno, /* firstlineno */ + emptystring /* lnotab */ + ); failed: - Py_XDECREF(funcname_ob); - Py_XDECREF(filename_ob); - return result; + Py_XDECREF(funcname_ob); + Py_XDECREF(filename_ob); + return result; } #define OFF(x) offsetof(PyCodeObject, x) static PyMemberDef code_memberlist[] = { - {"co_argcount", T_INT, OFF(co_argcount), READONLY}, - {"co_kwonlyargcount", T_INT, OFF(co_kwonlyargcount), READONLY}, - {"co_nlocals", T_INT, OFF(co_nlocals), READONLY}, - {"co_stacksize",T_INT, OFF(co_stacksize), READONLY}, - {"co_flags", T_INT, OFF(co_flags), READONLY}, - {"co_code", T_OBJECT, OFF(co_code), READONLY}, - {"co_consts", T_OBJECT, OFF(co_consts), READONLY}, - {"co_names", T_OBJECT, OFF(co_names), READONLY}, - {"co_varnames", T_OBJECT, OFF(co_varnames), READONLY}, - {"co_freevars", T_OBJECT, OFF(co_freevars), READONLY}, - {"co_cellvars", T_OBJECT, OFF(co_cellvars), READONLY}, - {"co_filename", T_OBJECT, OFF(co_filename), READONLY}, - {"co_name", T_OBJECT, OFF(co_name), READONLY}, - {"co_firstlineno", T_INT, OFF(co_firstlineno), READONLY}, - {"co_lnotab", T_OBJECT, OFF(co_lnotab), READONLY}, - {NULL} /* Sentinel */ + {"co_argcount", T_INT, OFF(co_argcount), READONLY}, + {"co_kwonlyargcount", T_INT, OFF(co_kwonlyargcount), READONLY}, + {"co_nlocals", T_INT, OFF(co_nlocals), READONLY}, + {"co_stacksize",T_INT, OFF(co_stacksize), READONLY}, + {"co_flags", T_INT, OFF(co_flags), READONLY}, + {"co_code", T_OBJECT, OFF(co_code), READONLY}, + {"co_consts", T_OBJECT, OFF(co_consts), READONLY}, + {"co_names", T_OBJECT, OFF(co_names), READONLY}, + {"co_varnames", T_OBJECT, OFF(co_varnames), READONLY}, + {"co_freevars", T_OBJECT, OFF(co_freevars), READONLY}, + {"co_cellvars", T_OBJECT, OFF(co_cellvars), READONLY}, + {"co_filename", T_OBJECT, OFF(co_filename), READONLY}, + {"co_name", T_OBJECT, OFF(co_name), READONLY}, + {"co_firstlineno", T_INT, OFF(co_firstlineno), READONLY}, + {"co_lnotab", T_OBJECT, OFF(co_lnotab), READONLY}, + {NULL} /* Sentinel */ }; /* Helper for code_new: return a shallow copy of a tuple that is @@ -188,42 +188,42 @@ static PyObject* validate_and_copy_tuple(PyObject *tup) { - PyObject *newtuple; - PyObject *item; - Py_ssize_t i, len; - - len = PyTuple_GET_SIZE(tup); - newtuple = PyTuple_New(len); - if (newtuple == NULL) - return NULL; - - for (i = 0; i < len; i++) { - item = PyTuple_GET_ITEM(tup, i); - if (PyUnicode_CheckExact(item)) { - Py_INCREF(item); - } - else if (!PyUnicode_Check(item)) { - PyErr_Format( - PyExc_TypeError, - "name tuples must contain only " - "strings, not '%.500s'", - item->ob_type->tp_name); - Py_DECREF(newtuple); - return NULL; - } - else { - item = PyUnicode_FromUnicode( - PyUnicode_AS_UNICODE(item), - PyUnicode_GET_SIZE(item)); - if (item == NULL) { - Py_DECREF(newtuple); - return NULL; - } - } - PyTuple_SET_ITEM(newtuple, i, item); - } + PyObject *newtuple; + PyObject *item; + Py_ssize_t i, len; + + len = PyTuple_GET_SIZE(tup); + newtuple = PyTuple_New(len); + if (newtuple == NULL) + return NULL; + + for (i = 0; i < len; i++) { + item = PyTuple_GET_ITEM(tup, i); + if (PyUnicode_CheckExact(item)) { + Py_INCREF(item); + } + else if (!PyUnicode_Check(item)) { + PyErr_Format( + PyExc_TypeError, + "name tuples must contain only " + "strings, not '%.500s'", + item->ob_type->tp_name); + Py_DECREF(newtuple); + return NULL; + } + else { + item = PyUnicode_FromUnicode( + PyUnicode_AS_UNICODE(item), + PyUnicode_GET_SIZE(item)); + if (item == NULL) { + Py_DECREF(newtuple); + return NULL; + } + } + PyTuple_SET_ITEM(newtuple, i, item); + } - return newtuple; + return newtuple; } PyDoc_STRVAR(code_doc, @@ -236,253 +236,253 @@ static PyObject * code_new(PyTypeObject *type, PyObject *args, PyObject *kw) { - int argcount; - int kwonlyargcount; - int nlocals; - int stacksize; - int flags; - PyObject *co = NULL; - PyObject *code; - PyObject *consts; - PyObject *names, *ournames = NULL; - PyObject *varnames, *ourvarnames = NULL; - PyObject *freevars = NULL, *ourfreevars = NULL; - PyObject *cellvars = NULL, *ourcellvars = NULL; - PyObject *filename; - PyObject *name; - int firstlineno; - PyObject *lnotab; - - if (!PyArg_ParseTuple(args, "iiiiiSO!O!O!UUiS|O!O!:code", - &argcount, &kwonlyargcount, - &nlocals, &stacksize, &flags, - &code, - &PyTuple_Type, &consts, - &PyTuple_Type, &names, - &PyTuple_Type, &varnames, - &filename, &name, - &firstlineno, &lnotab, - &PyTuple_Type, &freevars, - &PyTuple_Type, &cellvars)) - return NULL; - - if (argcount < 0) { - PyErr_SetString( - PyExc_ValueError, - "code: argcount must not be negative"); - goto cleanup; - } - - if (kwonlyargcount < 0) { - PyErr_SetString( - PyExc_ValueError, - "code: kwonlyargcount must not be negative"); - goto cleanup; - } - if (nlocals < 0) { - PyErr_SetString( - PyExc_ValueError, - "code: nlocals must not be negative"); - goto cleanup; - } - - ournames = validate_and_copy_tuple(names); - if (ournames == NULL) - goto cleanup; - ourvarnames = validate_and_copy_tuple(varnames); - if (ourvarnames == NULL) - goto cleanup; - if (freevars) - ourfreevars = validate_and_copy_tuple(freevars); - else - ourfreevars = PyTuple_New(0); - if (ourfreevars == NULL) - goto cleanup; - if (cellvars) - ourcellvars = validate_and_copy_tuple(cellvars); - else - ourcellvars = PyTuple_New(0); - if (ourcellvars == NULL) - goto cleanup; - - co = (PyObject *)PyCode_New(argcount, kwonlyargcount, - nlocals, stacksize, flags, - code, consts, ournames, ourvarnames, - ourfreevars, ourcellvars, filename, - name, firstlineno, lnotab); + int argcount; + int kwonlyargcount; + int nlocals; + int stacksize; + int flags; + PyObject *co = NULL; + PyObject *code; + PyObject *consts; + PyObject *names, *ournames = NULL; + PyObject *varnames, *ourvarnames = NULL; + PyObject *freevars = NULL, *ourfreevars = NULL; + PyObject *cellvars = NULL, *ourcellvars = NULL; + PyObject *filename; + PyObject *name; + int firstlineno; + PyObject *lnotab; + + if (!PyArg_ParseTuple(args, "iiiiiSO!O!O!UUiS|O!O!:code", + &argcount, &kwonlyargcount, + &nlocals, &stacksize, &flags, + &code, + &PyTuple_Type, &consts, + &PyTuple_Type, &names, + &PyTuple_Type, &varnames, + &filename, &name, + &firstlineno, &lnotab, + &PyTuple_Type, &freevars, + &PyTuple_Type, &cellvars)) + return NULL; + + if (argcount < 0) { + PyErr_SetString( + PyExc_ValueError, + "code: argcount must not be negative"); + goto cleanup; + } + + if (kwonlyargcount < 0) { + PyErr_SetString( + PyExc_ValueError, + "code: kwonlyargcount must not be negative"); + goto cleanup; + } + if (nlocals < 0) { + PyErr_SetString( + PyExc_ValueError, + "code: nlocals must not be negative"); + goto cleanup; + } + + ournames = validate_and_copy_tuple(names); + if (ournames == NULL) + goto cleanup; + ourvarnames = validate_and_copy_tuple(varnames); + if (ourvarnames == NULL) + goto cleanup; + if (freevars) + ourfreevars = validate_and_copy_tuple(freevars); + else + ourfreevars = PyTuple_New(0); + if (ourfreevars == NULL) + goto cleanup; + if (cellvars) + ourcellvars = validate_and_copy_tuple(cellvars); + else + ourcellvars = PyTuple_New(0); + if (ourcellvars == NULL) + goto cleanup; + + co = (PyObject *)PyCode_New(argcount, kwonlyargcount, + nlocals, stacksize, flags, + code, consts, ournames, ourvarnames, + ourfreevars, ourcellvars, filename, + name, firstlineno, lnotab); cleanup: - Py_XDECREF(ournames); - Py_XDECREF(ourvarnames); - Py_XDECREF(ourfreevars); - Py_XDECREF(ourcellvars); - return co; + Py_XDECREF(ournames); + Py_XDECREF(ourvarnames); + Py_XDECREF(ourfreevars); + Py_XDECREF(ourcellvars); + return co; } static void code_dealloc(PyCodeObject *co) { - Py_XDECREF(co->co_code); - Py_XDECREF(co->co_consts); - Py_XDECREF(co->co_names); - Py_XDECREF(co->co_varnames); - Py_XDECREF(co->co_freevars); - Py_XDECREF(co->co_cellvars); - Py_XDECREF(co->co_filename); - Py_XDECREF(co->co_name); - Py_XDECREF(co->co_lnotab); - if (co->co_zombieframe != NULL) - PyObject_GC_Del(co->co_zombieframe); - if (co->co_weakreflist != NULL) - PyObject_ClearWeakRefs((PyObject*)co); - PyObject_DEL(co); + Py_XDECREF(co->co_code); + Py_XDECREF(co->co_consts); + Py_XDECREF(co->co_names); + Py_XDECREF(co->co_varnames); + Py_XDECREF(co->co_freevars); + Py_XDECREF(co->co_cellvars); + Py_XDECREF(co->co_filename); + Py_XDECREF(co->co_name); + Py_XDECREF(co->co_lnotab); + if (co->co_zombieframe != NULL) + PyObject_GC_Del(co->co_zombieframe); + if (co->co_weakreflist != NULL) + PyObject_ClearWeakRefs((PyObject*)co); + PyObject_DEL(co); } static PyObject * code_repr(PyCodeObject *co) { - int lineno; - if (co->co_firstlineno != 0) - lineno = co->co_firstlineno; - else - lineno = -1; - if (co->co_filename && PyUnicode_Check(co->co_filename)) { - return PyUnicode_FromFormat( - "", - co->co_name, co, co->co_filename, lineno); - } else { - return PyUnicode_FromFormat( - "", - co->co_name, co, lineno); - } + int lineno; + if (co->co_firstlineno != 0) + lineno = co->co_firstlineno; + else + lineno = -1; + if (co->co_filename && PyUnicode_Check(co->co_filename)) { + return PyUnicode_FromFormat( + "", + co->co_name, co, co->co_filename, lineno); + } else { + return PyUnicode_FromFormat( + "", + co->co_name, co, lineno); + } } static PyObject * code_richcompare(PyObject *self, PyObject *other, int op) { - PyCodeObject *co, *cp; - int eq; - PyObject *res; - - if ((op != Py_EQ && op != Py_NE) || - !PyCode_Check(self) || - !PyCode_Check(other)) { - Py_INCREF(Py_NotImplemented); - return Py_NotImplemented; - } - - co = (PyCodeObject *)self; - cp = (PyCodeObject *)other; - - eq = PyObject_RichCompareBool(co->co_name, cp->co_name, Py_EQ); - if (eq <= 0) goto unequal; - eq = co->co_argcount == cp->co_argcount; - if (!eq) goto unequal; - eq = co->co_kwonlyargcount == cp->co_kwonlyargcount; - if (!eq) goto unequal; - eq = co->co_nlocals == cp->co_nlocals; - if (!eq) goto unequal; - eq = co->co_flags == cp->co_flags; - if (!eq) goto unequal; - eq = co->co_firstlineno == cp->co_firstlineno; - if (!eq) goto unequal; - eq = PyObject_RichCompareBool(co->co_code, cp->co_code, Py_EQ); - if (eq <= 0) goto unequal; - eq = PyObject_RichCompareBool(co->co_consts, cp->co_consts, Py_EQ); - if (eq <= 0) goto unequal; - eq = PyObject_RichCompareBool(co->co_names, cp->co_names, Py_EQ); - if (eq <= 0) goto unequal; - eq = PyObject_RichCompareBool(co->co_varnames, cp->co_varnames, Py_EQ); - if (eq <= 0) goto unequal; - eq = PyObject_RichCompareBool(co->co_freevars, cp->co_freevars, Py_EQ); - if (eq <= 0) goto unequal; - eq = PyObject_RichCompareBool(co->co_cellvars, cp->co_cellvars, Py_EQ); - if (eq <= 0) goto unequal; - - if (op == Py_EQ) - res = Py_True; - else - res = Py_False; - goto done; + PyCodeObject *co, *cp; + int eq; + PyObject *res; + + if ((op != Py_EQ && op != Py_NE) || + !PyCode_Check(self) || + !PyCode_Check(other)) { + Py_INCREF(Py_NotImplemented); + return Py_NotImplemented; + } + + co = (PyCodeObject *)self; + cp = (PyCodeObject *)other; + + eq = PyObject_RichCompareBool(co->co_name, cp->co_name, Py_EQ); + if (eq <= 0) goto unequal; + eq = co->co_argcount == cp->co_argcount; + if (!eq) goto unequal; + eq = co->co_kwonlyargcount == cp->co_kwonlyargcount; + if (!eq) goto unequal; + eq = co->co_nlocals == cp->co_nlocals; + if (!eq) goto unequal; + eq = co->co_flags == cp->co_flags; + if (!eq) goto unequal; + eq = co->co_firstlineno == cp->co_firstlineno; + if (!eq) goto unequal; + eq = PyObject_RichCompareBool(co->co_code, cp->co_code, Py_EQ); + if (eq <= 0) goto unequal; + eq = PyObject_RichCompareBool(co->co_consts, cp->co_consts, Py_EQ); + if (eq <= 0) goto unequal; + eq = PyObject_RichCompareBool(co->co_names, cp->co_names, Py_EQ); + if (eq <= 0) goto unequal; + eq = PyObject_RichCompareBool(co->co_varnames, cp->co_varnames, Py_EQ); + if (eq <= 0) goto unequal; + eq = PyObject_RichCompareBool(co->co_freevars, cp->co_freevars, Py_EQ); + if (eq <= 0) goto unequal; + eq = PyObject_RichCompareBool(co->co_cellvars, cp->co_cellvars, Py_EQ); + if (eq <= 0) goto unequal; + + if (op == Py_EQ) + res = Py_True; + else + res = Py_False; + goto done; unequal: - if (eq < 0) - return NULL; - if (op == Py_NE) - res = Py_True; - else - res = Py_False; + if (eq < 0) + return NULL; + if (op == Py_NE) + res = Py_True; + else + res = Py_False; done: - Py_INCREF(res); - return res; + Py_INCREF(res); + return res; } static long code_hash(PyCodeObject *co) { - long h, h0, h1, h2, h3, h4, h5, h6; - h0 = PyObject_Hash(co->co_name); - if (h0 == -1) return -1; - h1 = PyObject_Hash(co->co_code); - if (h1 == -1) return -1; - h2 = PyObject_Hash(co->co_consts); - if (h2 == -1) return -1; - h3 = PyObject_Hash(co->co_names); - if (h3 == -1) return -1; - h4 = PyObject_Hash(co->co_varnames); - if (h4 == -1) return -1; - h5 = PyObject_Hash(co->co_freevars); - if (h5 == -1) return -1; - h6 = PyObject_Hash(co->co_cellvars); - if (h6 == -1) return -1; - h = h0 ^ h1 ^ h2 ^ h3 ^ h4 ^ h5 ^ h6 ^ - co->co_argcount ^ co->co_kwonlyargcount ^ - co->co_nlocals ^ co->co_flags; - if (h == -1) h = -2; - return h; + long h, h0, h1, h2, h3, h4, h5, h6; + h0 = PyObject_Hash(co->co_name); + if (h0 == -1) return -1; + h1 = PyObject_Hash(co->co_code); + if (h1 == -1) return -1; + h2 = PyObject_Hash(co->co_consts); + if (h2 == -1) return -1; + h3 = PyObject_Hash(co->co_names); + if (h3 == -1) return -1; + h4 = PyObject_Hash(co->co_varnames); + if (h4 == -1) return -1; + h5 = PyObject_Hash(co->co_freevars); + if (h5 == -1) return -1; + h6 = PyObject_Hash(co->co_cellvars); + if (h6 == -1) return -1; + h = h0 ^ h1 ^ h2 ^ h3 ^ h4 ^ h5 ^ h6 ^ + co->co_argcount ^ co->co_kwonlyargcount ^ + co->co_nlocals ^ co->co_flags; + if (h == -1) h = -2; + return h; } /* XXX code objects need to participate in GC? */ PyTypeObject PyCode_Type = { - PyVarObject_HEAD_INIT(&PyType_Type, 0) - "code", - sizeof(PyCodeObject), - 0, - (destructor)code_dealloc, /* tp_dealloc */ - 0, /* tp_print */ - 0, /* tp_getattr */ - 0, /* tp_setattr */ - 0, /* tp_reserved */ - (reprfunc)code_repr, /* tp_repr */ - 0, /* tp_as_number */ - 0, /* tp_as_sequence */ - 0, /* tp_as_mapping */ - (hashfunc)code_hash, /* tp_hash */ - 0, /* tp_call */ - 0, /* tp_str */ - PyObject_GenericGetAttr, /* tp_getattro */ - 0, /* tp_setattro */ - 0, /* tp_as_buffer */ - Py_TPFLAGS_DEFAULT, /* tp_flags */ - code_doc, /* tp_doc */ - 0, /* tp_traverse */ - 0, /* tp_clear */ - code_richcompare, /* tp_richcompare */ - offsetof(PyCodeObject, co_weakreflist), /* tp_weaklistoffset */ - 0, /* tp_iter */ - 0, /* tp_iternext */ - 0, /* tp_methods */ - code_memberlist, /* tp_members */ - 0, /* tp_getset */ - 0, /* tp_base */ - 0, /* tp_dict */ - 0, /* tp_descr_get */ - 0, /* tp_descr_set */ - 0, /* tp_dictoffset */ - 0, /* tp_init */ - 0, /* tp_alloc */ - code_new, /* tp_new */ + PyVarObject_HEAD_INIT(&PyType_Type, 0) + "code", + sizeof(PyCodeObject), + 0, + (destructor)code_dealloc, /* tp_dealloc */ + 0, /* tp_print */ + 0, /* tp_getattr */ + 0, /* tp_setattr */ + 0, /* tp_reserved */ + (reprfunc)code_repr, /* tp_repr */ + 0, /* tp_as_number */ + 0, /* tp_as_sequence */ + 0, /* tp_as_mapping */ + (hashfunc)code_hash, /* tp_hash */ + 0, /* tp_call */ + 0, /* tp_str */ + PyObject_GenericGetAttr, /* tp_getattro */ + 0, /* tp_setattro */ + 0, /* tp_as_buffer */ + Py_TPFLAGS_DEFAULT, /* tp_flags */ + code_doc, /* tp_doc */ + 0, /* tp_traverse */ + 0, /* tp_clear */ + code_richcompare, /* tp_richcompare */ + offsetof(PyCodeObject, co_weakreflist), /* tp_weaklistoffset */ + 0, /* tp_iter */ + 0, /* tp_iternext */ + 0, /* tp_methods */ + code_memberlist, /* tp_members */ + 0, /* tp_getset */ + 0, /* tp_base */ + 0, /* tp_dict */ + 0, /* tp_descr_get */ + 0, /* tp_descr_set */ + 0, /* tp_dictoffset */ + 0, /* tp_init */ + 0, /* tp_alloc */ + code_new, /* tp_new */ }; /* Use co_lnotab to compute the line number from a bytecode index, addrq. See @@ -492,17 +492,17 @@ int PyCode_Addr2Line(PyCodeObject *co, int addrq) { - int size = PyBytes_Size(co->co_lnotab) / 2; - unsigned char *p = (unsigned char*)PyBytes_AsString(co->co_lnotab); - int line = co->co_firstlineno; - int addr = 0; - while (--size >= 0) { - addr += *p++; - if (addr > addrq) - break; - line += *p++; - } - return line; + int size = PyBytes_Size(co->co_lnotab) / 2; + unsigned char *p = (unsigned char*)PyBytes_AsString(co->co_lnotab); + int line = co->co_firstlineno; + int addr = 0; + while (--size >= 0) { + addr += *p++; + if (addr > addrq) + break; + line += *p++; + } + return line; } /* Update *bounds to describe the first and one-past-the-last instructions in @@ -510,47 +510,47 @@ int _PyCode_CheckLineNumber(PyCodeObject* co, int lasti, PyAddrPair *bounds) { - int size, addr, line; - unsigned char* p; + int size, addr, line; + unsigned char* p; - p = (unsigned char*)PyBytes_AS_STRING(co->co_lnotab); - size = PyBytes_GET_SIZE(co->co_lnotab) / 2; + p = (unsigned char*)PyBytes_AS_STRING(co->co_lnotab); + size = PyBytes_GET_SIZE(co->co_lnotab) / 2; - addr = 0; - line = co->co_firstlineno; - assert(line > 0); - - /* possible optimization: if f->f_lasti == instr_ub - (likely to be a common case) then we already know - instr_lb -- if we stored the matching value of p - somwhere we could skip the first while loop. */ - - /* See lnotab_notes.txt for the description of - co_lnotab. A point to remember: increments to p - come in (addr, line) pairs. */ - - bounds->ap_lower = 0; - while (size > 0) { - if (addr + *p > lasti) - break; - addr += *p++; - if (*p) - bounds->ap_lower = addr; - line += *p++; - --size; - } - - if (size > 0) { - while (--size >= 0) { - addr += *p++; - if (*p++) - break; - } - bounds->ap_upper = addr; - } - else { - bounds->ap_upper = INT_MAX; + addr = 0; + line = co->co_firstlineno; + assert(line > 0); + + /* possible optimization: if f->f_lasti == instr_ub + (likely to be a common case) then we already know + instr_lb -- if we stored the matching value of p + somwhere we could skip the first while loop. */ + + /* See lnotab_notes.txt for the description of + co_lnotab. A point to remember: increments to p + come in (addr, line) pairs. */ + + bounds->ap_lower = 0; + while (size > 0) { + if (addr + *p > lasti) + break; + addr += *p++; + if (*p) + bounds->ap_lower = addr; + line += *p++; + --size; + } + + if (size > 0) { + while (--size >= 0) { + addr += *p++; + if (*p++) + break; } + bounds->ap_upper = addr; + } + else { + bounds->ap_upper = INT_MAX; + } - return line; + return line; } Modified: python/branches/py3k/Objects/complexobject.c ============================================================================== --- python/branches/py3k/Objects/complexobject.c (original) +++ python/branches/py3k/Objects/complexobject.c Sun May 9 17:52:27 2010 @@ -15,377 +15,377 @@ Py_complex c_sum(Py_complex a, Py_complex b) { - Py_complex r; - r.real = a.real + b.real; - r.imag = a.imag + b.imag; - return r; + Py_complex r; + r.real = a.real + b.real; + r.imag = a.imag + b.imag; + return r; } Py_complex c_diff(Py_complex a, Py_complex b) { - Py_complex r; - r.real = a.real - b.real; - r.imag = a.imag - b.imag; - return r; + Py_complex r; + r.real = a.real - b.real; + r.imag = a.imag - b.imag; + return r; } Py_complex c_neg(Py_complex a) { - Py_complex r; - r.real = -a.real; - r.imag = -a.imag; - return r; + Py_complex r; + r.real = -a.real; + r.imag = -a.imag; + return r; } Py_complex c_prod(Py_complex a, Py_complex b) { - Py_complex r; - r.real = a.real*b.real - a.imag*b.imag; - r.imag = a.real*b.imag + a.imag*b.real; - return r; + Py_complex r; + r.real = a.real*b.real - a.imag*b.imag; + r.imag = a.real*b.imag + a.imag*b.real; + return r; } Py_complex c_quot(Py_complex a, Py_complex b) { - /****************************************************************** - This was the original algorithm. It's grossly prone to spurious - overflow and underflow errors. It also merrily divides by 0 despite - checking for that(!). The code still serves a doc purpose here, as - the algorithm following is a simple by-cases transformation of this - one: - - Py_complex r; - double d = b.real*b.real + b.imag*b.imag; - if (d == 0.) - errno = EDOM; - r.real = (a.real*b.real + a.imag*b.imag)/d; - r.imag = (a.imag*b.real - a.real*b.imag)/d; - return r; - ******************************************************************/ - - /* This algorithm is better, and is pretty obvious: first divide the - * numerators and denominator by whichever of {b.real, b.imag} has - * larger magnitude. The earliest reference I found was to CACM - * Algorithm 116 (Complex Division, Robert L. Smith, Stanford - * University). As usual, though, we're still ignoring all IEEE - * endcases. - */ - Py_complex r; /* the result */ - const double abs_breal = b.real < 0 ? -b.real : b.real; - const double abs_bimag = b.imag < 0 ? -b.imag : b.imag; - - if (abs_breal >= abs_bimag) { - /* divide tops and bottom by b.real */ - if (abs_breal == 0.0) { - errno = EDOM; - r.real = r.imag = 0.0; - } - else { - const double ratio = b.imag / b.real; - const double denom = b.real + b.imag * ratio; - r.real = (a.real + a.imag * ratio) / denom; - r.imag = (a.imag - a.real * ratio) / denom; - } - } - else { - /* divide tops and bottom by b.imag */ - const double ratio = b.real / b.imag; - const double denom = b.real * ratio + b.imag; - assert(b.imag != 0.0); - r.real = (a.real * ratio + a.imag) / denom; - r.imag = (a.imag * ratio - a.real) / denom; - } - return r; + /****************************************************************** + This was the original algorithm. It's grossly prone to spurious + overflow and underflow errors. It also merrily divides by 0 despite + checking for that(!). The code still serves a doc purpose here, as + the algorithm following is a simple by-cases transformation of this + one: + + Py_complex r; + double d = b.real*b.real + b.imag*b.imag; + if (d == 0.) + errno = EDOM; + r.real = (a.real*b.real + a.imag*b.imag)/d; + r.imag = (a.imag*b.real - a.real*b.imag)/d; + return r; + ******************************************************************/ + + /* This algorithm is better, and is pretty obvious: first divide the + * numerators and denominator by whichever of {b.real, b.imag} has + * larger magnitude. The earliest reference I found was to CACM + * Algorithm 116 (Complex Division, Robert L. Smith, Stanford + * University). As usual, though, we're still ignoring all IEEE + * endcases. + */ + Py_complex r; /* the result */ + const double abs_breal = b.real < 0 ? -b.real : b.real; + const double abs_bimag = b.imag < 0 ? -b.imag : b.imag; + + if (abs_breal >= abs_bimag) { + /* divide tops and bottom by b.real */ + if (abs_breal == 0.0) { + errno = EDOM; + r.real = r.imag = 0.0; + } + else { + const double ratio = b.imag / b.real; + const double denom = b.real + b.imag * ratio; + r.real = (a.real + a.imag * ratio) / denom; + r.imag = (a.imag - a.real * ratio) / denom; + } + } + else { + /* divide tops and bottom by b.imag */ + const double ratio = b.real / b.imag; + const double denom = b.real * ratio + b.imag; + assert(b.imag != 0.0); + r.real = (a.real * ratio + a.imag) / denom; + r.imag = (a.imag * ratio - a.real) / denom; + } + return r; } Py_complex c_pow(Py_complex a, Py_complex b) { - Py_complex r; - double vabs,len,at,phase; - if (b.real == 0. && b.imag == 0.) { - r.real = 1.; - r.imag = 0.; - } - else if (a.real == 0. && a.imag == 0.) { - if (b.imag != 0. || b.real < 0.) - errno = EDOM; - r.real = 0.; - r.imag = 0.; - } - else { - vabs = hypot(a.real,a.imag); - len = pow(vabs,b.real); - at = atan2(a.imag, a.real); - phase = at*b.real; - if (b.imag != 0.0) { - len /= exp(at*b.imag); - phase += b.imag*log(vabs); - } - r.real = len*cos(phase); - r.imag = len*sin(phase); - } - return r; + Py_complex r; + double vabs,len,at,phase; + if (b.real == 0. && b.imag == 0.) { + r.real = 1.; + r.imag = 0.; + } + else if (a.real == 0. && a.imag == 0.) { + if (b.imag != 0. || b.real < 0.) + errno = EDOM; + r.real = 0.; + r.imag = 0.; + } + else { + vabs = hypot(a.real,a.imag); + len = pow(vabs,b.real); + at = atan2(a.imag, a.real); + phase = at*b.real; + if (b.imag != 0.0) { + len /= exp(at*b.imag); + phase += b.imag*log(vabs); + } + r.real = len*cos(phase); + r.imag = len*sin(phase); + } + return r; } static Py_complex c_powu(Py_complex x, long n) { - Py_complex r, p; - long mask = 1; - r = c_1; - p = x; - while (mask > 0 && n >= mask) { - if (n & mask) - r = c_prod(r,p); - mask <<= 1; - p = c_prod(p,p); - } - return r; + Py_complex r, p; + long mask = 1; + r = c_1; + p = x; + while (mask > 0 && n >= mask) { + if (n & mask) + r = c_prod(r,p); + mask <<= 1; + p = c_prod(p,p); + } + return r; } static Py_complex c_powi(Py_complex x, long n) { - Py_complex cn; + Py_complex cn; - if (n > 100 || n < -100) { - cn.real = (double) n; - cn.imag = 0.; - return c_pow(x,cn); - } - else if (n > 0) - return c_powu(x,n); - else - return c_quot(c_1,c_powu(x,-n)); + if (n > 100 || n < -100) { + cn.real = (double) n; + cn.imag = 0.; + return c_pow(x,cn); + } + else if (n > 0) + return c_powu(x,n); + else + return c_quot(c_1,c_powu(x,-n)); } double c_abs(Py_complex z) { - /* sets errno = ERANGE on overflow; otherwise errno = 0 */ - double result; + /* sets errno = ERANGE on overflow; otherwise errno = 0 */ + double result; - if (!Py_IS_FINITE(z.real) || !Py_IS_FINITE(z.imag)) { - /* C99 rules: if either the real or the imaginary part is an - infinity, return infinity, even if the other part is a - NaN. */ - if (Py_IS_INFINITY(z.real)) { - result = fabs(z.real); - errno = 0; - return result; - } - if (Py_IS_INFINITY(z.imag)) { - result = fabs(z.imag); - errno = 0; - return result; - } - /* either the real or imaginary part is a NaN, - and neither is infinite. Result should be NaN. */ - return Py_NAN; - } - result = hypot(z.real, z.imag); - if (!Py_IS_FINITE(result)) - errno = ERANGE; - else - errno = 0; - return result; + if (!Py_IS_FINITE(z.real) || !Py_IS_FINITE(z.imag)) { + /* C99 rules: if either the real or the imaginary part is an + infinity, return infinity, even if the other part is a + NaN. */ + if (Py_IS_INFINITY(z.real)) { + result = fabs(z.real); + errno = 0; + return result; + } + if (Py_IS_INFINITY(z.imag)) { + result = fabs(z.imag); + errno = 0; + return result; + } + /* either the real or imaginary part is a NaN, + and neither is infinite. Result should be NaN. */ + return Py_NAN; + } + result = hypot(z.real, z.imag); + if (!Py_IS_FINITE(result)) + errno = ERANGE; + else + errno = 0; + return result; } static PyObject * complex_subtype_from_c_complex(PyTypeObject *type, Py_complex cval) { - PyObject *op; + PyObject *op; - op = type->tp_alloc(type, 0); - if (op != NULL) - ((PyComplexObject *)op)->cval = cval; - return op; + op = type->tp_alloc(type, 0); + if (op != NULL) + ((PyComplexObject *)op)->cval = cval; + return op; } PyObject * PyComplex_FromCComplex(Py_complex cval) { - register PyComplexObject *op; + register PyComplexObject *op; - /* Inline PyObject_New */ - op = (PyComplexObject *) PyObject_MALLOC(sizeof(PyComplexObject)); - if (op == NULL) - return PyErr_NoMemory(); - PyObject_INIT(op, &PyComplex_Type); - op->cval = cval; - return (PyObject *) op; + /* Inline PyObject_New */ + op = (PyComplexObject *) PyObject_MALLOC(sizeof(PyComplexObject)); + if (op == NULL) + return PyErr_NoMemory(); + PyObject_INIT(op, &PyComplex_Type); + op->cval = cval; + return (PyObject *) op; } static PyObject * complex_subtype_from_doubles(PyTypeObject *type, double real, double imag) { - Py_complex c; - c.real = real; - c.imag = imag; - return complex_subtype_from_c_complex(type, c); + Py_complex c; + c.real = real; + c.imag = imag; + return complex_subtype_from_c_complex(type, c); } PyObject * PyComplex_FromDoubles(double real, double imag) { - Py_complex c; - c.real = real; - c.imag = imag; - return PyComplex_FromCComplex(c); + Py_complex c; + c.real = real; + c.imag = imag; + return PyComplex_FromCComplex(c); } double PyComplex_RealAsDouble(PyObject *op) { - if (PyComplex_Check(op)) { - return ((PyComplexObject *)op)->cval.real; - } - else { - return PyFloat_AsDouble(op); - } + if (PyComplex_Check(op)) { + return ((PyComplexObject *)op)->cval.real; + } + else { + return PyFloat_AsDouble(op); + } } double PyComplex_ImagAsDouble(PyObject *op) { - if (PyComplex_Check(op)) { - return ((PyComplexObject *)op)->cval.imag; - } - else { - return 0.0; - } + if (PyComplex_Check(op)) { + return ((PyComplexObject *)op)->cval.imag; + } + else { + return 0.0; + } } static PyObject * try_complex_special_method(PyObject *op) { - PyObject *f; - static PyObject *complexstr; + PyObject *f; + static PyObject *complexstr; - f = _PyObject_LookupSpecial(op, "__complex__", &complexstr); - if (f) { - PyObject *res = PyObject_CallFunctionObjArgs(f, NULL); - Py_DECREF(f); - return res; - } - return NULL; + f = _PyObject_LookupSpecial(op, "__complex__", &complexstr); + if (f) { + PyObject *res = PyObject_CallFunctionObjArgs(f, NULL); + Py_DECREF(f); + return res; + } + return NULL; } Py_complex PyComplex_AsCComplex(PyObject *op) { - Py_complex cv; - PyObject *newop = NULL; + Py_complex cv; + PyObject *newop = NULL; - assert(op); - /* If op is already of type PyComplex_Type, return its value */ - if (PyComplex_Check(op)) { - return ((PyComplexObject *)op)->cval; - } - /* If not, use op's __complex__ method, if it exists */ - - /* return -1 on failure */ - cv.real = -1.; - cv.imag = 0.; - - newop = try_complex_special_method(op); - - if (newop) { - if (!PyComplex_Check(newop)) { - PyErr_SetString(PyExc_TypeError, - "__complex__ should return a complex object"); - Py_DECREF(newop); - return cv; - } - cv = ((PyComplexObject *)newop)->cval; - Py_DECREF(newop); - return cv; - } - else if (PyErr_Occurred()) { - return cv; - } - /* If neither of the above works, interpret op as a float giving the - real part of the result, and fill in the imaginary part as 0. */ - else { - /* PyFloat_AsDouble will return -1 on failure */ - cv.real = PyFloat_AsDouble(op); - return cv; - } + assert(op); + /* If op is already of type PyComplex_Type, return its value */ + if (PyComplex_Check(op)) { + return ((PyComplexObject *)op)->cval; + } + /* If not, use op's __complex__ method, if it exists */ + + /* return -1 on failure */ + cv.real = -1.; + cv.imag = 0.; + + newop = try_complex_special_method(op); + + if (newop) { + if (!PyComplex_Check(newop)) { + PyErr_SetString(PyExc_TypeError, + "__complex__ should return a complex object"); + Py_DECREF(newop); + return cv; + } + cv = ((PyComplexObject *)newop)->cval; + Py_DECREF(newop); + return cv; + } + else if (PyErr_Occurred()) { + return cv; + } + /* If neither of the above works, interpret op as a float giving the + real part of the result, and fill in the imaginary part as 0. */ + else { + /* PyFloat_AsDouble will return -1 on failure */ + cv.real = PyFloat_AsDouble(op); + return cv; + } } static void complex_dealloc(PyObject *op) { - op->ob_type->tp_free(op); + op->ob_type->tp_free(op); } static PyObject * complex_format(PyComplexObject *v, int precision, char format_code) { - PyObject *result = NULL; - Py_ssize_t len; + PyObject *result = NULL; + Py_ssize_t len; - /* If these are non-NULL, they'll need to be freed. */ - char *pre = NULL; - char *im = NULL; - char *buf = NULL; - - /* These do not need to be freed. re is either an alias - for pre or a pointer to a constant. lead and tail - are pointers to constants. */ - char *re = NULL; - char *lead = ""; - char *tail = ""; - - if (v->cval.real == 0. && copysign(1.0, v->cval.real)==1.0) { - re = ""; - im = PyOS_double_to_string(v->cval.imag, format_code, - precision, 0, NULL); - if (!im) { - PyErr_NoMemory(); - goto done; - } - } else { - /* Format imaginary part with sign, real part without */ - pre = PyOS_double_to_string(v->cval.real, format_code, - precision, 0, NULL); - if (!pre) { - PyErr_NoMemory(); - goto done; - } - re = pre; - - im = PyOS_double_to_string(v->cval.imag, format_code, - precision, Py_DTSF_SIGN, NULL); - if (!im) { - PyErr_NoMemory(); - goto done; - } - lead = "("; - tail = ")"; - } - /* Alloc the final buffer. Add one for the "j" in the format string, - and one for the trailing zero. */ - len = strlen(lead) + strlen(re) + strlen(im) + strlen(tail) + 2; - buf = PyMem_Malloc(len); - if (!buf) { - PyErr_NoMemory(); - goto done; - } - PyOS_snprintf(buf, len, "%s%s%sj%s", lead, re, im, tail); - result = PyUnicode_FromString(buf); + /* If these are non-NULL, they'll need to be freed. */ + char *pre = NULL; + char *im = NULL; + char *buf = NULL; + + /* These do not need to be freed. re is either an alias + for pre or a pointer to a constant. lead and tail + are pointers to constants. */ + char *re = NULL; + char *lead = ""; + char *tail = ""; + + if (v->cval.real == 0. && copysign(1.0, v->cval.real)==1.0) { + re = ""; + im = PyOS_double_to_string(v->cval.imag, format_code, + precision, 0, NULL); + if (!im) { + PyErr_NoMemory(); + goto done; + } + } else { + /* Format imaginary part with sign, real part without */ + pre = PyOS_double_to_string(v->cval.real, format_code, + precision, 0, NULL); + if (!pre) { + PyErr_NoMemory(); + goto done; + } + re = pre; + + im = PyOS_double_to_string(v->cval.imag, format_code, + precision, Py_DTSF_SIGN, NULL); + if (!im) { + PyErr_NoMemory(); + goto done; + } + lead = "("; + tail = ")"; + } + /* Alloc the final buffer. Add one for the "j" in the format string, + and one for the trailing zero. */ + len = strlen(lead) + strlen(re) + strlen(im) + strlen(tail) + 2; + buf = PyMem_Malloc(len); + if (!buf) { + PyErr_NoMemory(); + goto done; + } + PyOS_snprintf(buf, len, "%s%s%sj%s", lead, re, im, tail); + result = PyUnicode_FromString(buf); done: - PyMem_Free(im); - PyMem_Free(pre); - PyMem_Free(buf); + PyMem_Free(im); + PyMem_Free(pre); + PyMem_Free(buf); - return result; + return result; } static PyObject * @@ -403,264 +403,264 @@ static long complex_hash(PyComplexObject *v) { - long hashreal, hashimag, combined; - hashreal = _Py_HashDouble(v->cval.real); - if (hashreal == -1) - return -1; - hashimag = _Py_HashDouble(v->cval.imag); - if (hashimag == -1) - return -1; - /* Note: if the imaginary part is 0, hashimag is 0 now, - * so the following returns hashreal unchanged. This is - * important because numbers of different types that - * compare equal must have the same hash value, so that - * hash(x + 0*j) must equal hash(x). - */ - combined = hashreal + 1000003 * hashimag; - if (combined == -1) - combined = -2; - return combined; + long hashreal, hashimag, combined; + hashreal = _Py_HashDouble(v->cval.real); + if (hashreal == -1) + return -1; + hashimag = _Py_HashDouble(v->cval.imag); + if (hashimag == -1) + return -1; + /* Note: if the imaginary part is 0, hashimag is 0 now, + * so the following returns hashreal unchanged. This is + * important because numbers of different types that + * compare equal must have the same hash value, so that + * hash(x + 0*j) must equal hash(x). + */ + combined = hashreal + 1000003 * hashimag; + if (combined == -1) + combined = -2; + return combined; } /* This macro may return! */ #define TO_COMPLEX(obj, c) \ - if (PyComplex_Check(obj)) \ - c = ((PyComplexObject *)(obj))->cval; \ - else if (to_complex(&(obj), &(c)) < 0) \ - return (obj) + if (PyComplex_Check(obj)) \ + c = ((PyComplexObject *)(obj))->cval; \ + else if (to_complex(&(obj), &(c)) < 0) \ + return (obj) static int to_complex(PyObject **pobj, Py_complex *pc) { - PyObject *obj = *pobj; + PyObject *obj = *pobj; - pc->real = pc->imag = 0.0; - if (PyLong_Check(obj)) { - pc->real = PyLong_AsDouble(obj); - if (pc->real == -1.0 && PyErr_Occurred()) { - *pobj = NULL; - return -1; - } - return 0; - } - if (PyFloat_Check(obj)) { - pc->real = PyFloat_AsDouble(obj); - return 0; - } - Py_INCREF(Py_NotImplemented); - *pobj = Py_NotImplemented; - return -1; + pc->real = pc->imag = 0.0; + if (PyLong_Check(obj)) { + pc->real = PyLong_AsDouble(obj); + if (pc->real == -1.0 && PyErr_Occurred()) { + *pobj = NULL; + return -1; + } + return 0; + } + if (PyFloat_Check(obj)) { + pc->real = PyFloat_AsDouble(obj); + return 0; + } + Py_INCREF(Py_NotImplemented); + *pobj = Py_NotImplemented; + return -1; } - + static PyObject * complex_add(PyObject *v, PyObject *w) { - Py_complex result; - Py_complex a, b; - TO_COMPLEX(v, a); - TO_COMPLEX(w, b); - PyFPE_START_PROTECT("complex_add", return 0) - result = c_sum(a, b); - PyFPE_END_PROTECT(result) - return PyComplex_FromCComplex(result); + Py_complex result; + Py_complex a, b; + TO_COMPLEX(v, a); + TO_COMPLEX(w, b); + PyFPE_START_PROTECT("complex_add", return 0) + result = c_sum(a, b); + PyFPE_END_PROTECT(result) + return PyComplex_FromCComplex(result); } static PyObject * complex_sub(PyObject *v, PyObject *w) { - Py_complex result; - Py_complex a, b; - TO_COMPLEX(v, a); - TO_COMPLEX(w, b); - PyFPE_START_PROTECT("complex_sub", return 0) - result = c_diff(a, b); - PyFPE_END_PROTECT(result) - return PyComplex_FromCComplex(result); + Py_complex result; + Py_complex a, b; + TO_COMPLEX(v, a); + TO_COMPLEX(w, b); + PyFPE_START_PROTECT("complex_sub", return 0) + result = c_diff(a, b); + PyFPE_END_PROTECT(result) + return PyComplex_FromCComplex(result); } static PyObject * complex_mul(PyObject *v, PyObject *w) { - Py_complex result; - Py_complex a, b; - TO_COMPLEX(v, a); - TO_COMPLEX(w, b); - PyFPE_START_PROTECT("complex_mul", return 0) - result = c_prod(a, b); - PyFPE_END_PROTECT(result) - return PyComplex_FromCComplex(result); + Py_complex result; + Py_complex a, b; + TO_COMPLEX(v, a); + TO_COMPLEX(w, b); + PyFPE_START_PROTECT("complex_mul", return 0) + result = c_prod(a, b); + PyFPE_END_PROTECT(result) + return PyComplex_FromCComplex(result); } static PyObject * complex_div(PyObject *v, PyObject *w) { - Py_complex quot; - Py_complex a, b; - TO_COMPLEX(v, a); - TO_COMPLEX(w, b); - PyFPE_START_PROTECT("complex_div", return 0) - errno = 0; - quot = c_quot(a, b); - PyFPE_END_PROTECT(quot) - if (errno == EDOM) { - PyErr_SetString(PyExc_ZeroDivisionError, "complex division by zero"); - return NULL; - } - return PyComplex_FromCComplex(quot); + Py_complex quot; + Py_complex a, b; + TO_COMPLEX(v, a); + TO_COMPLEX(w, b); + PyFPE_START_PROTECT("complex_div", return 0) + errno = 0; + quot = c_quot(a, b); + PyFPE_END_PROTECT(quot) + if (errno == EDOM) { + PyErr_SetString(PyExc_ZeroDivisionError, "complex division by zero"); + return NULL; + } + return PyComplex_FromCComplex(quot); } static PyObject * complex_remainder(PyObject *v, PyObject *w) { - PyErr_SetString(PyExc_TypeError, - "can't mod complex numbers."); - return NULL; + PyErr_SetString(PyExc_TypeError, + "can't mod complex numbers."); + return NULL; } static PyObject * complex_divmod(PyObject *v, PyObject *w) { - PyErr_SetString(PyExc_TypeError, - "can't take floor or mod of complex number."); - return NULL; + PyErr_SetString(PyExc_TypeError, + "can't take floor or mod of complex number."); + return NULL; } static PyObject * complex_pow(PyObject *v, PyObject *w, PyObject *z) { - Py_complex p; - Py_complex exponent; - long int_exponent; - Py_complex a, b; - TO_COMPLEX(v, a); - TO_COMPLEX(w, b); - - if (z != Py_None) { - PyErr_SetString(PyExc_ValueError, "complex modulo"); - return NULL; - } - PyFPE_START_PROTECT("complex_pow", return 0) - errno = 0; - exponent = b; - int_exponent = (long)exponent.real; - if (exponent.imag == 0. && exponent.real == int_exponent) - p = c_powi(a, int_exponent); - else - p = c_pow(a, exponent); - - PyFPE_END_PROTECT(p) - Py_ADJUST_ERANGE2(p.real, p.imag); - if (errno == EDOM) { - PyErr_SetString(PyExc_ZeroDivisionError, - "0.0 to a negative or complex power"); - return NULL; - } - else if (errno == ERANGE) { - PyErr_SetString(PyExc_OverflowError, - "complex exponentiation"); - return NULL; - } - return PyComplex_FromCComplex(p); + Py_complex p; + Py_complex exponent; + long int_exponent; + Py_complex a, b; + TO_COMPLEX(v, a); + TO_COMPLEX(w, b); + + if (z != Py_None) { + PyErr_SetString(PyExc_ValueError, "complex modulo"); + return NULL; + } + PyFPE_START_PROTECT("complex_pow", return 0) + errno = 0; + exponent = b; + int_exponent = (long)exponent.real; + if (exponent.imag == 0. && exponent.real == int_exponent) + p = c_powi(a, int_exponent); + else + p = c_pow(a, exponent); + + PyFPE_END_PROTECT(p) + Py_ADJUST_ERANGE2(p.real, p.imag); + if (errno == EDOM) { + PyErr_SetString(PyExc_ZeroDivisionError, + "0.0 to a negative or complex power"); + return NULL; + } + else if (errno == ERANGE) { + PyErr_SetString(PyExc_OverflowError, + "complex exponentiation"); + return NULL; + } + return PyComplex_FromCComplex(p); } static PyObject * complex_int_div(PyObject *v, PyObject *w) { - PyErr_SetString(PyExc_TypeError, - "can't take floor of complex number."); - return NULL; + PyErr_SetString(PyExc_TypeError, + "can't take floor of complex number."); + return NULL; } static PyObject * complex_neg(PyComplexObject *v) { - Py_complex neg; - neg.real = -v->cval.real; - neg.imag = -v->cval.imag; - return PyComplex_FromCComplex(neg); + Py_complex neg; + neg.real = -v->cval.real; + neg.imag = -v->cval.imag; + return PyComplex_FromCComplex(neg); } static PyObject * complex_pos(PyComplexObject *v) { - if (PyComplex_CheckExact(v)) { - Py_INCREF(v); - return (PyObject *)v; - } - else - return PyComplex_FromCComplex(v->cval); + if (PyComplex_CheckExact(v)) { + Py_INCREF(v); + return (PyObject *)v; + } + else + return PyComplex_FromCComplex(v->cval); } static PyObject * complex_abs(PyComplexObject *v) { - double result; + double result; - PyFPE_START_PROTECT("complex_abs", return 0) - result = c_abs(v->cval); - PyFPE_END_PROTECT(result) - - if (errno == ERANGE) { - PyErr_SetString(PyExc_OverflowError, - "absolute value too large"); - return NULL; - } - return PyFloat_FromDouble(result); + PyFPE_START_PROTECT("complex_abs", return 0) + result = c_abs(v->cval); + PyFPE_END_PROTECT(result) + + if (errno == ERANGE) { + PyErr_SetString(PyExc_OverflowError, + "absolute value too large"); + return NULL; + } + return PyFloat_FromDouble(result); } static int complex_bool(PyComplexObject *v) { - return v->cval.real != 0.0 || v->cval.imag != 0.0; + return v->cval.real != 0.0 || v->cval.imag != 0.0; } static PyObject * complex_richcompare(PyObject *v, PyObject *w, int op) { - PyObject *res; - Py_complex i, j; - TO_COMPLEX(v, i); - TO_COMPLEX(w, j); - - if (op != Py_EQ && op != Py_NE) { - Py_INCREF(Py_NotImplemented); - return Py_NotImplemented; - } - - if ((i.real == j.real && i.imag == j.imag) == (op == Py_EQ)) - res = Py_True; - else - res = Py_False; + PyObject *res; + Py_complex i, j; + TO_COMPLEX(v, i); + TO_COMPLEX(w, j); + + if (op != Py_EQ && op != Py_NE) { + Py_INCREF(Py_NotImplemented); + return Py_NotImplemented; + } + + if ((i.real == j.real && i.imag == j.imag) == (op == Py_EQ)) + res = Py_True; + else + res = Py_False; - Py_INCREF(res); - return res; + Py_INCREF(res); + return res; } static PyObject * complex_int(PyObject *v) { - PyErr_SetString(PyExc_TypeError, - "can't convert complex to int"); - return NULL; + PyErr_SetString(PyExc_TypeError, + "can't convert complex to int"); + return NULL; } static PyObject * complex_float(PyObject *v) { - PyErr_SetString(PyExc_TypeError, - "can't convert complex to float"); - return NULL; + PyErr_SetString(PyExc_TypeError, + "can't convert complex to float"); + return NULL; } static PyObject * complex_conjugate(PyObject *self) { - Py_complex c; - c = ((PyComplexObject *)self)->cval; - c.imag = -c.imag; - return PyComplex_FromCComplex(c); + Py_complex c; + c = ((PyComplexObject *)self)->cval; + c.imag = -c.imag; + return PyComplex_FromCComplex(c); } PyDoc_STRVAR(complex_conjugate_doc, @@ -671,8 +671,8 @@ static PyObject * complex_getnewargs(PyComplexObject *v) { - Py_complex c = v->cval; - return Py_BuildValue("(dd)", c.real, c.imag); + Py_complex c = v->cval; + return Py_BuildValue("(dd)", c.real, c.imag); } PyDoc_STRVAR(complex__format__doc, @@ -686,7 +686,7 @@ PyObject *format_spec; if (!PyArg_ParseTuple(args, "U:__format__", &format_spec)) - return NULL; + return NULL; return _PyComplex_FormatAdvanced(self, PyUnicode_AS_UNICODE(format_spec), PyUnicode_GET_SIZE(format_spec)); @@ -696,10 +696,10 @@ static PyObject * complex_is_finite(PyObject *self) { - Py_complex c; - c = ((PyComplexObject *)self)->cval; - return PyBool_FromLong((long)(Py_IS_FINITE(c.real) && - Py_IS_FINITE(c.imag))); + Py_complex c; + c = ((PyComplexObject *)self)->cval; + return PyBool_FromLong((long)(Py_IS_FINITE(c.real) && + Py_IS_FINITE(c.imag))); } PyDoc_STRVAR(complex_is_finite_doc, @@ -709,305 +709,305 @@ #endif static PyMethodDef complex_methods[] = { - {"conjugate", (PyCFunction)complex_conjugate, METH_NOARGS, - complex_conjugate_doc}, + {"conjugate", (PyCFunction)complex_conjugate, METH_NOARGS, + complex_conjugate_doc}, #if 0 - {"is_finite", (PyCFunction)complex_is_finite, METH_NOARGS, - complex_is_finite_doc}, + {"is_finite", (PyCFunction)complex_is_finite, METH_NOARGS, + complex_is_finite_doc}, #endif - {"__getnewargs__", (PyCFunction)complex_getnewargs, METH_NOARGS}, - {"__format__", (PyCFunction)complex__format__, - METH_VARARGS, complex__format__doc}, - {NULL, NULL} /* sentinel */ + {"__getnewargs__", (PyCFunction)complex_getnewargs, METH_NOARGS}, + {"__format__", (PyCFunction)complex__format__, + METH_VARARGS, complex__format__doc}, + {NULL, NULL} /* sentinel */ }; static PyMemberDef complex_members[] = { - {"real", T_DOUBLE, offsetof(PyComplexObject, cval.real), READONLY, - "the real part of a complex number"}, - {"imag", T_DOUBLE, offsetof(PyComplexObject, cval.imag), READONLY, - "the imaginary part of a complex number"}, - {0}, + {"real", T_DOUBLE, offsetof(PyComplexObject, cval.real), READONLY, + "the real part of a complex number"}, + {"imag", T_DOUBLE, offsetof(PyComplexObject, cval.imag), READONLY, + "the imaginary part of a complex number"}, + {0}, }; static PyObject * complex_subtype_from_string(PyTypeObject *type, PyObject *v) { - const char *s, *start; - char *end; - double x=0.0, y=0.0, z; - int got_bracket=0; - char *s_buffer = NULL; - Py_ssize_t len; - - if (PyUnicode_Check(v)) { - s_buffer = (char *)PyMem_MALLOC(PyUnicode_GET_SIZE(v) + 1); - if (s_buffer == NULL) - return PyErr_NoMemory(); - if (PyUnicode_EncodeDecimal(PyUnicode_AS_UNICODE(v), - PyUnicode_GET_SIZE(v), - s_buffer, - NULL)) - goto error; - s = s_buffer; - len = strlen(s); - } - else if (PyObject_AsCharBuffer(v, &s, &len)) { - PyErr_SetString(PyExc_TypeError, - "complex() arg is not a string"); - return NULL; - } - - /* position on first nonblank */ - start = s; - while (Py_ISSPACE(*s)) - s++; - if (*s == '(') { - /* Skip over possible bracket from repr(). */ - got_bracket = 1; - s++; - while (Py_ISSPACE(*s)) - s++; - } - - /* a valid complex string usually takes one of the three forms: - - - real part only - j - imaginary part only - j - real and imaginary parts - - where represents any numeric string that's accepted by the - float constructor (including 'nan', 'inf', 'infinity', etc.), and - is any string of the form whose first - character is '+' or '-'. - - For backwards compatibility, the extra forms - - j - j - j - - are also accepted, though support for these forms may be removed from - a future version of Python. - */ - - /* first look for forms starting with */ - z = PyOS_string_to_double(s, &end, NULL); - if (z == -1.0 && PyErr_Occurred()) { - if (PyErr_ExceptionMatches(PyExc_ValueError)) - PyErr_Clear(); - else - goto error; - } - if (end != s) { - /* all 4 forms starting with land here */ - s = end; - if (*s == '+' || *s == '-') { - /* j | j */ - x = z; - y = PyOS_string_to_double(s, &end, NULL); - if (y == -1.0 && PyErr_Occurred()) { - if (PyErr_ExceptionMatches(PyExc_ValueError)) - PyErr_Clear(); - else - goto error; - } - if (end != s) - /* j */ - s = end; - else { - /* j */ - y = *s == '+' ? 1.0 : -1.0; - s++; - } - if (!(*s == 'j' || *s == 'J')) - goto parse_error; - s++; - } - else if (*s == 'j' || *s == 'J') { - /* j */ - s++; - y = z; - } - else - /* */ - x = z; - } - else { - /* not starting with ; must be j or j */ - if (*s == '+' || *s == '-') { - /* j */ - y = *s == '+' ? 1.0 : -1.0; - s++; - } - else - /* j */ - y = 1.0; - if (!(*s == 'j' || *s == 'J')) - goto parse_error; - s++; - } - - /* trailing whitespace and closing bracket */ - while (Py_ISSPACE(*s)) - s++; - if (got_bracket) { - /* if there was an opening parenthesis, then the corresponding - closing parenthesis should be right here */ - if (*s != ')') - goto parse_error; - s++; - while (Py_ISSPACE(*s)) - s++; - } - - /* we should now be at the end of the string */ - if (s-start != len) - goto parse_error; - - if (s_buffer) - PyMem_FREE(s_buffer); - return complex_subtype_from_doubles(type, x, y); + const char *s, *start; + char *end; + double x=0.0, y=0.0, z; + int got_bracket=0; + char *s_buffer = NULL; + Py_ssize_t len; + + if (PyUnicode_Check(v)) { + s_buffer = (char *)PyMem_MALLOC(PyUnicode_GET_SIZE(v) + 1); + if (s_buffer == NULL) + return PyErr_NoMemory(); + if (PyUnicode_EncodeDecimal(PyUnicode_AS_UNICODE(v), + PyUnicode_GET_SIZE(v), + s_buffer, + NULL)) + goto error; + s = s_buffer; + len = strlen(s); + } + else if (PyObject_AsCharBuffer(v, &s, &len)) { + PyErr_SetString(PyExc_TypeError, + "complex() arg is not a string"); + return NULL; + } + + /* position on first nonblank */ + start = s; + while (Py_ISSPACE(*s)) + s++; + if (*s == '(') { + /* Skip over possible bracket from repr(). */ + got_bracket = 1; + s++; + while (Py_ISSPACE(*s)) + s++; + } + + /* a valid complex string usually takes one of the three forms: + + - real part only + j - imaginary part only + j - real and imaginary parts + + where represents any numeric string that's accepted by the + float constructor (including 'nan', 'inf', 'infinity', etc.), and + is any string of the form whose first + character is '+' or '-'. + + For backwards compatibility, the extra forms + + j + j + j + + are also accepted, though support for these forms may be removed from + a future version of Python. + */ + + /* first look for forms starting with */ + z = PyOS_string_to_double(s, &end, NULL); + if (z == -1.0 && PyErr_Occurred()) { + if (PyErr_ExceptionMatches(PyExc_ValueError)) + PyErr_Clear(); + else + goto error; + } + if (end != s) { + /* all 4 forms starting with land here */ + s = end; + if (*s == '+' || *s == '-') { + /* j | j */ + x = z; + y = PyOS_string_to_double(s, &end, NULL); + if (y == -1.0 && PyErr_Occurred()) { + if (PyErr_ExceptionMatches(PyExc_ValueError)) + PyErr_Clear(); + else + goto error; + } + if (end != s) + /* j */ + s = end; + else { + /* j */ + y = *s == '+' ? 1.0 : -1.0; + s++; + } + if (!(*s == 'j' || *s == 'J')) + goto parse_error; + s++; + } + else if (*s == 'j' || *s == 'J') { + /* j */ + s++; + y = z; + } + else + /* */ + x = z; + } + else { + /* not starting with ; must be j or j */ + if (*s == '+' || *s == '-') { + /* j */ + y = *s == '+' ? 1.0 : -1.0; + s++; + } + else + /* j */ + y = 1.0; + if (!(*s == 'j' || *s == 'J')) + goto parse_error; + s++; + } + + /* trailing whitespace and closing bracket */ + while (Py_ISSPACE(*s)) + s++; + if (got_bracket) { + /* if there was an opening parenthesis, then the corresponding + closing parenthesis should be right here */ + if (*s != ')') + goto parse_error; + s++; + while (Py_ISSPACE(*s)) + s++; + } + + /* we should now be at the end of the string */ + if (s-start != len) + goto parse_error; + + if (s_buffer) + PyMem_FREE(s_buffer); + return complex_subtype_from_doubles(type, x, y); parse_error: - PyErr_SetString(PyExc_ValueError, - "complex() arg is a malformed string"); + PyErr_SetString(PyExc_ValueError, + "complex() arg is a malformed string"); error: - if (s_buffer) - PyMem_FREE(s_buffer); - return NULL; + if (s_buffer) + PyMem_FREE(s_buffer); + return NULL; } static PyObject * complex_new(PyTypeObject *type, PyObject *args, PyObject *kwds) { - PyObject *r, *i, *tmp; - PyNumberMethods *nbr, *nbi = NULL; - Py_complex cr, ci; - int own_r = 0; - int cr_is_complex = 0; - int ci_is_complex = 0; - static char *kwlist[] = {"real", "imag", 0}; - - r = Py_False; - i = NULL; - if (!PyArg_ParseTupleAndKeywords(args, kwds, "|OO:complex", kwlist, - &r, &i)) - return NULL; - - /* Special-case for a single argument when type(arg) is complex. */ - if (PyComplex_CheckExact(r) && i == NULL && - type == &PyComplex_Type) { - /* Note that we can't know whether it's safe to return - a complex *subclass* instance as-is, hence the restriction - to exact complexes here. If either the input or the - output is a complex subclass, it will be handled below - as a non-orthogonal vector. */ - Py_INCREF(r); - return r; - } - if (PyUnicode_Check(r)) { - if (i != NULL) { - PyErr_SetString(PyExc_TypeError, - "complex() can't take second arg" - " if first is a string"); - return NULL; - } - return complex_subtype_from_string(type, r); - } - if (i != NULL && PyUnicode_Check(i)) { - PyErr_SetString(PyExc_TypeError, - "complex() second arg can't be a string"); - return NULL; - } - - tmp = try_complex_special_method(r); - if (tmp) { - r = tmp; - own_r = 1; - } - else if (PyErr_Occurred()) { - return NULL; - } - - nbr = r->ob_type->tp_as_number; - if (i != NULL) - nbi = i->ob_type->tp_as_number; - if (nbr == NULL || nbr->nb_float == NULL || - ((i != NULL) && (nbi == NULL || nbi->nb_float == NULL))) { - PyErr_SetString(PyExc_TypeError, - "complex() argument must be a string or a number"); - if (own_r) { - Py_DECREF(r); - } - return NULL; - } - - /* If we get this far, then the "real" and "imag" parts should - both be treated as numbers, and the constructor should return a - complex number equal to (real + imag*1j). - - Note that we do NOT assume the input to already be in canonical - form; the "real" and "imag" parts might themselves be complex - numbers, which slightly complicates the code below. */ - if (PyComplex_Check(r)) { - /* Note that if r is of a complex subtype, we're only - retaining its real & imag parts here, and the return - value is (properly) of the builtin complex type. */ - cr = ((PyComplexObject*)r)->cval; - cr_is_complex = 1; - if (own_r) { - Py_DECREF(r); - } - } - else { - /* The "real" part really is entirely real, and contributes - nothing in the imaginary direction. - Just treat it as a double. */ - tmp = PyNumber_Float(r); - if (own_r) { - /* r was a newly created complex number, rather - than the original "real" argument. */ - Py_DECREF(r); - } - if (tmp == NULL) - return NULL; - if (!PyFloat_Check(tmp)) { - PyErr_SetString(PyExc_TypeError, - "float(r) didn't return a float"); - Py_DECREF(tmp); - return NULL; - } - cr.real = PyFloat_AsDouble(tmp); - cr.imag = 0.0; /* Shut up compiler warning */ - Py_DECREF(tmp); - } - if (i == NULL) { - ci.real = 0.0; - } - else if (PyComplex_Check(i)) { - ci = ((PyComplexObject*)i)->cval; - ci_is_complex = 1; - } else { - /* The "imag" part really is entirely imaginary, and - contributes nothing in the real direction. - Just treat it as a double. */ - tmp = (*nbi->nb_float)(i); - if (tmp == NULL) - return NULL; - ci.real = PyFloat_AsDouble(tmp); - Py_DECREF(tmp); - } - /* If the input was in canonical form, then the "real" and "imag" - parts are real numbers, so that ci.imag and cr.imag are zero. - We need this correction in case they were not real numbers. */ - - if (ci_is_complex) { - cr.real -= ci.imag; - } - if (cr_is_complex) { - ci.real += cr.imag; - } - return complex_subtype_from_doubles(type, cr.real, ci.real); + PyObject *r, *i, *tmp; + PyNumberMethods *nbr, *nbi = NULL; + Py_complex cr, ci; + int own_r = 0; + int cr_is_complex = 0; + int ci_is_complex = 0; + static char *kwlist[] = {"real", "imag", 0}; + + r = Py_False; + i = NULL; + if (!PyArg_ParseTupleAndKeywords(args, kwds, "|OO:complex", kwlist, + &r, &i)) + return NULL; + + /* Special-case for a single argument when type(arg) is complex. */ + if (PyComplex_CheckExact(r) && i == NULL && + type == &PyComplex_Type) { + /* Note that we can't know whether it's safe to return + a complex *subclass* instance as-is, hence the restriction + to exact complexes here. If either the input or the + output is a complex subclass, it will be handled below + as a non-orthogonal vector. */ + Py_INCREF(r); + return r; + } + if (PyUnicode_Check(r)) { + if (i != NULL) { + PyErr_SetString(PyExc_TypeError, + "complex() can't take second arg" + " if first is a string"); + return NULL; + } + return complex_subtype_from_string(type, r); + } + if (i != NULL && PyUnicode_Check(i)) { + PyErr_SetString(PyExc_TypeError, + "complex() second arg can't be a string"); + return NULL; + } + + tmp = try_complex_special_method(r); + if (tmp) { + r = tmp; + own_r = 1; + } + else if (PyErr_Occurred()) { + return NULL; + } + + nbr = r->ob_type->tp_as_number; + if (i != NULL) + nbi = i->ob_type->tp_as_number; + if (nbr == NULL || nbr->nb_float == NULL || + ((i != NULL) && (nbi == NULL || nbi->nb_float == NULL))) { + PyErr_SetString(PyExc_TypeError, + "complex() argument must be a string or a number"); + if (own_r) { + Py_DECREF(r); + } + return NULL; + } + + /* If we get this far, then the "real" and "imag" parts should + both be treated as numbers, and the constructor should return a + complex number equal to (real + imag*1j). + + Note that we do NOT assume the input to already be in canonical + form; the "real" and "imag" parts might themselves be complex + numbers, which slightly complicates the code below. */ + if (PyComplex_Check(r)) { + /* Note that if r is of a complex subtype, we're only + retaining its real & imag parts here, and the return + value is (properly) of the builtin complex type. */ + cr = ((PyComplexObject*)r)->cval; + cr_is_complex = 1; + if (own_r) { + Py_DECREF(r); + } + } + else { + /* The "real" part really is entirely real, and contributes + nothing in the imaginary direction. + Just treat it as a double. */ + tmp = PyNumber_Float(r); + if (own_r) { + /* r was a newly created complex number, rather + than the original "real" argument. */ + Py_DECREF(r); + } + if (tmp == NULL) + return NULL; + if (!PyFloat_Check(tmp)) { + PyErr_SetString(PyExc_TypeError, + "float(r) didn't return a float"); + Py_DECREF(tmp); + return NULL; + } + cr.real = PyFloat_AsDouble(tmp); + cr.imag = 0.0; /* Shut up compiler warning */ + Py_DECREF(tmp); + } + if (i == NULL) { + ci.real = 0.0; + } + else if (PyComplex_Check(i)) { + ci = ((PyComplexObject*)i)->cval; + ci_is_complex = 1; + } else { + /* The "imag" part really is entirely imaginary, and + contributes nothing in the real direction. + Just treat it as a double. */ + tmp = (*nbi->nb_float)(i); + if (tmp == NULL) + return NULL; + ci.real = PyFloat_AsDouble(tmp); + Py_DECREF(tmp); + } + /* If the input was in canonical form, then the "real" and "imag" + parts are real numbers, so that ci.imag and cr.imag are zero. + We need this correction in case they were not real numbers. */ + + if (ci_is_complex) { + cr.real -= ci.imag; + } + if (cr_is_complex) { + ci.real += cr.imag; + } + return complex_subtype_from_doubles(type, cr.real, ci.real); } PyDoc_STRVAR(complex_doc, @@ -1017,79 +1017,79 @@ "This is equivalent to (real + imag*1j) where imag defaults to 0."); static PyNumberMethods complex_as_number = { - (binaryfunc)complex_add, /* nb_add */ - (binaryfunc)complex_sub, /* nb_subtract */ - (binaryfunc)complex_mul, /* nb_multiply */ - (binaryfunc)complex_remainder, /* nb_remainder */ - (binaryfunc)complex_divmod, /* nb_divmod */ - (ternaryfunc)complex_pow, /* nb_power */ - (unaryfunc)complex_neg, /* nb_negative */ - (unaryfunc)complex_pos, /* nb_positive */ - (unaryfunc)complex_abs, /* nb_absolute */ - (inquiry)complex_bool, /* nb_bool */ - 0, /* nb_invert */ - 0, /* nb_lshift */ - 0, /* nb_rshift */ - 0, /* nb_and */ - 0, /* nb_xor */ - 0, /* nb_or */ - complex_int, /* nb_int */ - 0, /* nb_reserved */ - complex_float, /* nb_float */ - 0, /* nb_inplace_add */ - 0, /* nb_inplace_subtract */ - 0, /* nb_inplace_multiply*/ - 0, /* nb_inplace_remainder */ - 0, /* nb_inplace_power */ - 0, /* nb_inplace_lshift */ - 0, /* nb_inplace_rshift */ - 0, /* nb_inplace_and */ - 0, /* nb_inplace_xor */ - 0, /* nb_inplace_or */ - (binaryfunc)complex_int_div, /* nb_floor_divide */ - (binaryfunc)complex_div, /* nb_true_divide */ - 0, /* nb_inplace_floor_divide */ - 0, /* nb_inplace_true_divide */ + (binaryfunc)complex_add, /* nb_add */ + (binaryfunc)complex_sub, /* nb_subtract */ + (binaryfunc)complex_mul, /* nb_multiply */ + (binaryfunc)complex_remainder, /* nb_remainder */ + (binaryfunc)complex_divmod, /* nb_divmod */ + (ternaryfunc)complex_pow, /* nb_power */ + (unaryfunc)complex_neg, /* nb_negative */ + (unaryfunc)complex_pos, /* nb_positive */ + (unaryfunc)complex_abs, /* nb_absolute */ + (inquiry)complex_bool, /* nb_bool */ + 0, /* nb_invert */ + 0, /* nb_lshift */ + 0, /* nb_rshift */ + 0, /* nb_and */ + 0, /* nb_xor */ + 0, /* nb_or */ + complex_int, /* nb_int */ + 0, /* nb_reserved */ + complex_float, /* nb_float */ + 0, /* nb_inplace_add */ + 0, /* nb_inplace_subtract */ + 0, /* nb_inplace_multiply*/ + 0, /* nb_inplace_remainder */ + 0, /* nb_inplace_power */ + 0, /* nb_inplace_lshift */ + 0, /* nb_inplace_rshift */ + 0, /* nb_inplace_and */ + 0, /* nb_inplace_xor */ + 0, /* nb_inplace_or */ + (binaryfunc)complex_int_div, /* nb_floor_divide */ + (binaryfunc)complex_div, /* nb_true_divide */ + 0, /* nb_inplace_floor_divide */ + 0, /* nb_inplace_true_divide */ }; PyTypeObject PyComplex_Type = { - PyVarObject_HEAD_INIT(&PyType_Type, 0) - "complex", - sizeof(PyComplexObject), - 0, - complex_dealloc, /* tp_dealloc */ - 0, /* tp_print */ - 0, /* tp_getattr */ - 0, /* tp_setattr */ - 0, /* tp_reserved */ - (reprfunc)complex_repr, /* tp_repr */ - &complex_as_number, /* tp_as_number */ - 0, /* tp_as_sequence */ - 0, /* tp_as_mapping */ - (hashfunc)complex_hash, /* tp_hash */ - 0, /* tp_call */ - (reprfunc)complex_str, /* tp_str */ - PyObject_GenericGetAttr, /* tp_getattro */ - 0, /* tp_setattro */ - 0, /* tp_as_buffer */ - Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */ - complex_doc, /* tp_doc */ - 0, /* tp_traverse */ - 0, /* tp_clear */ - complex_richcompare, /* tp_richcompare */ - 0, /* tp_weaklistoffset */ - 0, /* tp_iter */ - 0, /* tp_iternext */ - complex_methods, /* tp_methods */ - complex_members, /* tp_members */ - 0, /* tp_getset */ - 0, /* tp_base */ - 0, /* tp_dict */ - 0, /* tp_descr_get */ - 0, /* tp_descr_set */ - 0, /* tp_dictoffset */ - 0, /* tp_init */ - PyType_GenericAlloc, /* tp_alloc */ - complex_new, /* tp_new */ - PyObject_Del, /* tp_free */ + PyVarObject_HEAD_INIT(&PyType_Type, 0) + "complex", + sizeof(PyComplexObject), + 0, + complex_dealloc, /* tp_dealloc */ + 0, /* tp_print */ + 0, /* tp_getattr */ + 0, /* tp_setattr */ + 0, /* tp_reserved */ + (reprfunc)complex_repr, /* tp_repr */ + &complex_as_number, /* tp_as_number */ + 0, /* tp_as_sequence */ + 0, /* tp_as_mapping */ + (hashfunc)complex_hash, /* tp_hash */ + 0, /* tp_call */ + (reprfunc)complex_str, /* tp_str */ + PyObject_GenericGetAttr, /* tp_getattro */ + 0, /* tp_setattro */ + 0, /* tp_as_buffer */ + Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */ + complex_doc, /* tp_doc */ + 0, /* tp_traverse */ + 0, /* tp_clear */ + complex_richcompare, /* tp_richcompare */ + 0, /* tp_weaklistoffset */ + 0, /* tp_iter */ + 0, /* tp_iternext */ + complex_methods, /* tp_methods */ + complex_members, /* tp_members */ + 0, /* tp_getset */ + 0, /* tp_base */ + 0, /* tp_dict */ + 0, /* tp_descr_get */ + 0, /* tp_descr_set */ + 0, /* tp_dictoffset */ + 0, /* tp_init */ + PyType_GenericAlloc, /* tp_alloc */ + complex_new, /* tp_new */ + PyObject_Del, /* tp_free */ }; Modified: python/branches/py3k/Objects/descrobject.c ============================================================================== --- python/branches/py3k/Objects/descrobject.c (original) +++ python/branches/py3k/Objects/descrobject.c Sun May 9 17:52:27 2010 @@ -6,647 +6,647 @@ static void descr_dealloc(PyDescrObject *descr) { - _PyObject_GC_UNTRACK(descr); - Py_XDECREF(descr->d_type); - Py_XDECREF(descr->d_name); - PyObject_GC_Del(descr); + _PyObject_GC_UNTRACK(descr); + Py_XDECREF(descr->d_type); + Py_XDECREF(descr->d_name); + PyObject_GC_Del(descr); } static PyObject * descr_name(PyDescrObject *descr) { - if (descr->d_name != NULL && PyUnicode_Check(descr->d_name)) - return descr->d_name; - return NULL; + if (descr->d_name != NULL && PyUnicode_Check(descr->d_name)) + return descr->d_name; + return NULL; } static PyObject * descr_repr(PyDescrObject *descr, char *format) { - PyObject *name = NULL; - if (descr->d_name != NULL && PyUnicode_Check(descr->d_name)) - name = descr->d_name; + PyObject *name = NULL; + if (descr->d_name != NULL && PyUnicode_Check(descr->d_name)) + name = descr->d_name; - return PyUnicode_FromFormat(format, name, "?", descr->d_type->tp_name); + return PyUnicode_FromFormat(format, name, "?", descr->d_type->tp_name); } static PyObject * method_repr(PyMethodDescrObject *descr) { - return descr_repr((PyDescrObject *)descr, - ""); + return descr_repr((PyDescrObject *)descr, + ""); } static PyObject * member_repr(PyMemberDescrObject *descr) { - return descr_repr((PyDescrObject *)descr, - ""); + return descr_repr((PyDescrObject *)descr, + ""); } static PyObject * getset_repr(PyGetSetDescrObject *descr) { - return descr_repr((PyDescrObject *)descr, - ""); + return descr_repr((PyDescrObject *)descr, + ""); } static PyObject * wrapperdescr_repr(PyWrapperDescrObject *descr) { - return descr_repr((PyDescrObject *)descr, - ""); + return descr_repr((PyDescrObject *)descr, + ""); } static int descr_check(PyDescrObject *descr, PyObject *obj, PyObject **pres) { - if (obj == NULL) { - Py_INCREF(descr); - *pres = (PyObject *)descr; - return 1; - } - if (!PyObject_TypeCheck(obj, descr->d_type)) { - PyErr_Format(PyExc_TypeError, - "descriptor '%V' for '%s' objects " - "doesn't apply to '%s' object", - descr_name((PyDescrObject *)descr), "?", - descr->d_type->tp_name, - obj->ob_type->tp_name); - *pres = NULL; - return 1; - } - return 0; + if (obj == NULL) { + Py_INCREF(descr); + *pres = (PyObject *)descr; + return 1; + } + if (!PyObject_TypeCheck(obj, descr->d_type)) { + PyErr_Format(PyExc_TypeError, + "descriptor '%V' for '%s' objects " + "doesn't apply to '%s' object", + descr_name((PyDescrObject *)descr), "?", + descr->d_type->tp_name, + obj->ob_type->tp_name); + *pres = NULL; + return 1; + } + return 0; } static PyObject * classmethod_get(PyMethodDescrObject *descr, PyObject *obj, PyObject *type) { - /* Ensure a valid type. Class methods ignore obj. */ - if (type == NULL) { - if (obj != NULL) - type = (PyObject *)obj->ob_type; - else { - /* Wot - no type?! */ - PyErr_Format(PyExc_TypeError, - "descriptor '%V' for type '%s' " - "needs either an object or a type", - descr_name((PyDescrObject *)descr), "?", - PyDescr_TYPE(descr)->tp_name); - return NULL; - } - } - if (!PyType_Check(type)) { - PyErr_Format(PyExc_TypeError, - "descriptor '%V' for type '%s' " - "needs a type, not a '%s' as arg 2", - descr_name((PyDescrObject *)descr), "?", - PyDescr_TYPE(descr)->tp_name, - type->ob_type->tp_name); - return NULL; - } - if (!PyType_IsSubtype((PyTypeObject *)type, PyDescr_TYPE(descr))) { - PyErr_Format(PyExc_TypeError, - "descriptor '%V' for type '%s' " - "doesn't apply to type '%s'", - descr_name((PyDescrObject *)descr), "?", - PyDescr_TYPE(descr)->tp_name, - ((PyTypeObject *)type)->tp_name); - return NULL; - } - return PyCFunction_New(descr->d_method, type); + /* Ensure a valid type. Class methods ignore obj. */ + if (type == NULL) { + if (obj != NULL) + type = (PyObject *)obj->ob_type; + else { + /* Wot - no type?! */ + PyErr_Format(PyExc_TypeError, + "descriptor '%V' for type '%s' " + "needs either an object or a type", + descr_name((PyDescrObject *)descr), "?", + PyDescr_TYPE(descr)->tp_name); + return NULL; + } + } + if (!PyType_Check(type)) { + PyErr_Format(PyExc_TypeError, + "descriptor '%V' for type '%s' " + "needs a type, not a '%s' as arg 2", + descr_name((PyDescrObject *)descr), "?", + PyDescr_TYPE(descr)->tp_name, + type->ob_type->tp_name); + return NULL; + } + if (!PyType_IsSubtype((PyTypeObject *)type, PyDescr_TYPE(descr))) { + PyErr_Format(PyExc_TypeError, + "descriptor '%V' for type '%s' " + "doesn't apply to type '%s'", + descr_name((PyDescrObject *)descr), "?", + PyDescr_TYPE(descr)->tp_name, + ((PyTypeObject *)type)->tp_name); + return NULL; + } + return PyCFunction_New(descr->d_method, type); } static PyObject * method_get(PyMethodDescrObject *descr, PyObject *obj, PyObject *type) { - PyObject *res; + PyObject *res; - if (descr_check((PyDescrObject *)descr, obj, &res)) - return res; - return PyCFunction_New(descr->d_method, obj); + if (descr_check((PyDescrObject *)descr, obj, &res)) + return res; + return PyCFunction_New(descr->d_method, obj); } static PyObject * member_get(PyMemberDescrObject *descr, PyObject *obj, PyObject *type) { - PyObject *res; + PyObject *res; - if (descr_check((PyDescrObject *)descr, obj, &res)) - return res; - return PyMember_GetOne((char *)obj, descr->d_member); + if (descr_check((PyDescrObject *)descr, obj, &res)) + return res; + return PyMember_GetOne((char *)obj, descr->d_member); } static PyObject * getset_get(PyGetSetDescrObject *descr, PyObject *obj, PyObject *type) { - PyObject *res; + PyObject *res; - if (descr_check((PyDescrObject *)descr, obj, &res)) - return res; - if (descr->d_getset->get != NULL) - return descr->d_getset->get(obj, descr->d_getset->closure); - PyErr_Format(PyExc_AttributeError, - "attribute '%V' of '%.100s' objects is not readable", - descr_name((PyDescrObject *)descr), "?", - PyDescr_TYPE(descr)->tp_name); - return NULL; + if (descr_check((PyDescrObject *)descr, obj, &res)) + return res; + if (descr->d_getset->get != NULL) + return descr->d_getset->get(obj, descr->d_getset->closure); + PyErr_Format(PyExc_AttributeError, + "attribute '%V' of '%.100s' objects is not readable", + descr_name((PyDescrObject *)descr), "?", + PyDescr_TYPE(descr)->tp_name); + return NULL; } static PyObject * wrapperdescr_get(PyWrapperDescrObject *descr, PyObject *obj, PyObject *type) { - PyObject *res; + PyObject *res; - if (descr_check((PyDescrObject *)descr, obj, &res)) - return res; - return PyWrapper_New((PyObject *)descr, obj); + if (descr_check((PyDescrObject *)descr, obj, &res)) + return res; + return PyWrapper_New((PyObject *)descr, obj); } static int descr_setcheck(PyDescrObject *descr, PyObject *obj, PyObject *value, - int *pres) + int *pres) { - assert(obj != NULL); - if (!PyObject_TypeCheck(obj, descr->d_type)) { - PyErr_Format(PyExc_TypeError, - "descriptor '%V' for '%.100s' objects " - "doesn't apply to '%.100s' object", - descr_name(descr), "?", - descr->d_type->tp_name, - obj->ob_type->tp_name); - *pres = -1; - return 1; - } - return 0; + assert(obj != NULL); + if (!PyObject_TypeCheck(obj, descr->d_type)) { + PyErr_Format(PyExc_TypeError, + "descriptor '%V' for '%.100s' objects " + "doesn't apply to '%.100s' object", + descr_name(descr), "?", + descr->d_type->tp_name, + obj->ob_type->tp_name); + *pres = -1; + return 1; + } + return 0; } static int member_set(PyMemberDescrObject *descr, PyObject *obj, PyObject *value) { - int res; + int res; - if (descr_setcheck((PyDescrObject *)descr, obj, value, &res)) - return res; - return PyMember_SetOne((char *)obj, descr->d_member, value); + if (descr_setcheck((PyDescrObject *)descr, obj, value, &res)) + return res; + return PyMember_SetOne((char *)obj, descr->d_member, value); } static int getset_set(PyGetSetDescrObject *descr, PyObject *obj, PyObject *value) { - int res; + int res; - if (descr_setcheck((PyDescrObject *)descr, obj, value, &res)) - return res; - if (descr->d_getset->set != NULL) - return descr->d_getset->set(obj, value, - descr->d_getset->closure); - PyErr_Format(PyExc_AttributeError, - "attribute '%V' of '%.100s' objects is not writable", - descr_name((PyDescrObject *)descr), "?", - PyDescr_TYPE(descr)->tp_name); - return -1; + if (descr_setcheck((PyDescrObject *)descr, obj, value, &res)) + return res; + if (descr->d_getset->set != NULL) + return descr->d_getset->set(obj, value, + descr->d_getset->closure); + PyErr_Format(PyExc_AttributeError, + "attribute '%V' of '%.100s' objects is not writable", + descr_name((PyDescrObject *)descr), "?", + PyDescr_TYPE(descr)->tp_name); + return -1; } static PyObject * methoddescr_call(PyMethodDescrObject *descr, PyObject *args, PyObject *kwds) { - Py_ssize_t argc; - PyObject *self, *func, *result; + Py_ssize_t argc; + PyObject *self, *func, *result; - /* Make sure that the first argument is acceptable as 'self' */ - assert(PyTuple_Check(args)); - argc = PyTuple_GET_SIZE(args); - if (argc < 1) { - PyErr_Format(PyExc_TypeError, - "descriptor '%V' of '%.100s' " - "object needs an argument", - descr_name((PyDescrObject *)descr), "?", - PyDescr_TYPE(descr)->tp_name); - return NULL; - } - self = PyTuple_GET_ITEM(args, 0); - if (!PyObject_IsInstance(self, (PyObject *)PyDescr_TYPE(descr))) { - PyErr_Format(PyExc_TypeError, - "descriptor '%V' " - "requires a '%.100s' object " - "but received a '%.100s'", - descr_name((PyDescrObject *)descr), "?", - PyDescr_TYPE(descr)->tp_name, - self->ob_type->tp_name); - return NULL; - } - - func = PyCFunction_New(descr->d_method, self); - if (func == NULL) - return NULL; - args = PyTuple_GetSlice(args, 1, argc); - if (args == NULL) { - Py_DECREF(func); - return NULL; - } - result = PyEval_CallObjectWithKeywords(func, args, kwds); - Py_DECREF(args); - Py_DECREF(func); - return result; + /* Make sure that the first argument is acceptable as 'self' */ + assert(PyTuple_Check(args)); + argc = PyTuple_GET_SIZE(args); + if (argc < 1) { + PyErr_Format(PyExc_TypeError, + "descriptor '%V' of '%.100s' " + "object needs an argument", + descr_name((PyDescrObject *)descr), "?", + PyDescr_TYPE(descr)->tp_name); + return NULL; + } + self = PyTuple_GET_ITEM(args, 0); + if (!PyObject_IsInstance(self, (PyObject *)PyDescr_TYPE(descr))) { + PyErr_Format(PyExc_TypeError, + "descriptor '%V' " + "requires a '%.100s' object " + "but received a '%.100s'", + descr_name((PyDescrObject *)descr), "?", + PyDescr_TYPE(descr)->tp_name, + self->ob_type->tp_name); + return NULL; + } + + func = PyCFunction_New(descr->d_method, self); + if (func == NULL) + return NULL; + args = PyTuple_GetSlice(args, 1, argc); + if (args == NULL) { + Py_DECREF(func); + return NULL; + } + result = PyEval_CallObjectWithKeywords(func, args, kwds); + Py_DECREF(args); + Py_DECREF(func); + return result; } static PyObject * classmethoddescr_call(PyMethodDescrObject *descr, PyObject *args, - PyObject *kwds) + PyObject *kwds) { - PyObject *func, *result; + PyObject *func, *result; - func = PyCFunction_New(descr->d_method, (PyObject *)PyDescr_TYPE(descr)); - if (func == NULL) - return NULL; + func = PyCFunction_New(descr->d_method, (PyObject *)PyDescr_TYPE(descr)); + if (func == NULL) + return NULL; - result = PyEval_CallObjectWithKeywords(func, args, kwds); - Py_DECREF(func); - return result; + result = PyEval_CallObjectWithKeywords(func, args, kwds); + Py_DECREF(func); + return result; } static PyObject * wrapperdescr_call(PyWrapperDescrObject *descr, PyObject *args, PyObject *kwds) { - Py_ssize_t argc; - PyObject *self, *func, *result; + Py_ssize_t argc; + PyObject *self, *func, *result; - /* Make sure that the first argument is acceptable as 'self' */ - assert(PyTuple_Check(args)); - argc = PyTuple_GET_SIZE(args); - if (argc < 1) { - PyErr_Format(PyExc_TypeError, - "descriptor '%V' of '%.100s' " - "object needs an argument", - descr_name((PyDescrObject *)descr), "?", - PyDescr_TYPE(descr)->tp_name); - return NULL; - } - self = PyTuple_GET_ITEM(args, 0); - if (!PyObject_IsInstance(self, (PyObject *)PyDescr_TYPE(descr))) { - PyErr_Format(PyExc_TypeError, - "descriptor '%V' " - "requires a '%.100s' object " - "but received a '%.100s'", - descr_name((PyDescrObject *)descr), "?", - PyDescr_TYPE(descr)->tp_name, - self->ob_type->tp_name); - return NULL; - } - - func = PyWrapper_New((PyObject *)descr, self); - if (func == NULL) - return NULL; - args = PyTuple_GetSlice(args, 1, argc); - if (args == NULL) { - Py_DECREF(func); - return NULL; - } - result = PyEval_CallObjectWithKeywords(func, args, kwds); - Py_DECREF(args); - Py_DECREF(func); - return result; + /* Make sure that the first argument is acceptable as 'self' */ + assert(PyTuple_Check(args)); + argc = PyTuple_GET_SIZE(args); + if (argc < 1) { + PyErr_Format(PyExc_TypeError, + "descriptor '%V' of '%.100s' " + "object needs an argument", + descr_name((PyDescrObject *)descr), "?", + PyDescr_TYPE(descr)->tp_name); + return NULL; + } + self = PyTuple_GET_ITEM(args, 0); + if (!PyObject_IsInstance(self, (PyObject *)PyDescr_TYPE(descr))) { + PyErr_Format(PyExc_TypeError, + "descriptor '%V' " + "requires a '%.100s' object " + "but received a '%.100s'", + descr_name((PyDescrObject *)descr), "?", + PyDescr_TYPE(descr)->tp_name, + self->ob_type->tp_name); + return NULL; + } + + func = PyWrapper_New((PyObject *)descr, self); + if (func == NULL) + return NULL; + args = PyTuple_GetSlice(args, 1, argc); + if (args == NULL) { + Py_DECREF(func); + return NULL; + } + result = PyEval_CallObjectWithKeywords(func, args, kwds); + Py_DECREF(args); + Py_DECREF(func); + return result; } static PyObject * method_get_doc(PyMethodDescrObject *descr, void *closure) { - if (descr->d_method->ml_doc == NULL) { - Py_INCREF(Py_None); - return Py_None; - } - return PyUnicode_FromString(descr->d_method->ml_doc); + if (descr->d_method->ml_doc == NULL) { + Py_INCREF(Py_None); + return Py_None; + } + return PyUnicode_FromString(descr->d_method->ml_doc); } static PyMemberDef descr_members[] = { - {"__objclass__", T_OBJECT, offsetof(PyDescrObject, d_type), READONLY}, - {"__name__", T_OBJECT, offsetof(PyDescrObject, d_name), READONLY}, - {0} + {"__objclass__", T_OBJECT, offsetof(PyDescrObject, d_type), READONLY}, + {"__name__", T_OBJECT, offsetof(PyDescrObject, d_name), READONLY}, + {0} }; static PyGetSetDef method_getset[] = { - {"__doc__", (getter)method_get_doc}, - {0} + {"__doc__", (getter)method_get_doc}, + {0} }; static PyObject * member_get_doc(PyMemberDescrObject *descr, void *closure) { - if (descr->d_member->doc == NULL) { - Py_INCREF(Py_None); - return Py_None; - } - return PyUnicode_FromString(descr->d_member->doc); + if (descr->d_member->doc == NULL) { + Py_INCREF(Py_None); + return Py_None; + } + return PyUnicode_FromString(descr->d_member->doc); } static PyGetSetDef member_getset[] = { - {"__doc__", (getter)member_get_doc}, - {0} + {"__doc__", (getter)member_get_doc}, + {0} }; static PyObject * getset_get_doc(PyGetSetDescrObject *descr, void *closure) { - if (descr->d_getset->doc == NULL) { - Py_INCREF(Py_None); - return Py_None; - } - return PyUnicode_FromString(descr->d_getset->doc); + if (descr->d_getset->doc == NULL) { + Py_INCREF(Py_None); + return Py_None; + } + return PyUnicode_FromString(descr->d_getset->doc); } static PyGetSetDef getset_getset[] = { - {"__doc__", (getter)getset_get_doc}, - {0} + {"__doc__", (getter)getset_get_doc}, + {0} }; static PyObject * wrapperdescr_get_doc(PyWrapperDescrObject *descr, void *closure) { - if (descr->d_base->doc == NULL) { - Py_INCREF(Py_None); - return Py_None; - } - return PyUnicode_FromString(descr->d_base->doc); + if (descr->d_base->doc == NULL) { + Py_INCREF(Py_None); + return Py_None; + } + return PyUnicode_FromString(descr->d_base->doc); } static PyGetSetDef wrapperdescr_getset[] = { - {"__doc__", (getter)wrapperdescr_get_doc}, - {0} + {"__doc__", (getter)wrapperdescr_get_doc}, + {0} }; static int descr_traverse(PyObject *self, visitproc visit, void *arg) { - PyDescrObject *descr = (PyDescrObject *)self; - Py_VISIT(descr->d_type); - return 0; + PyDescrObject *descr = (PyDescrObject *)self; + Py_VISIT(descr->d_type); + return 0; } PyTypeObject PyMethodDescr_Type = { - PyVarObject_HEAD_INIT(&PyType_Type, 0) - "method_descriptor", - sizeof(PyMethodDescrObject), - 0, - (destructor)descr_dealloc, /* tp_dealloc */ - 0, /* tp_print */ - 0, /* tp_getattr */ - 0, /* tp_setattr */ - 0, /* tp_reserved */ - (reprfunc)method_repr, /* tp_repr */ - 0, /* tp_as_number */ - 0, /* tp_as_sequence */ - 0, /* tp_as_mapping */ - 0, /* tp_hash */ - (ternaryfunc)methoddescr_call, /* 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 */ - descr_traverse, /* tp_traverse */ - 0, /* tp_clear */ - 0, /* tp_richcompare */ - 0, /* tp_weaklistoffset */ - 0, /* tp_iter */ - 0, /* tp_iternext */ - 0, /* tp_methods */ - descr_members, /* tp_members */ - method_getset, /* tp_getset */ - 0, /* tp_base */ - 0, /* tp_dict */ - (descrgetfunc)method_get, /* tp_descr_get */ - 0, /* tp_descr_set */ + PyVarObject_HEAD_INIT(&PyType_Type, 0) + "method_descriptor", + sizeof(PyMethodDescrObject), + 0, + (destructor)descr_dealloc, /* tp_dealloc */ + 0, /* tp_print */ + 0, /* tp_getattr */ + 0, /* tp_setattr */ + 0, /* tp_reserved */ + (reprfunc)method_repr, /* tp_repr */ + 0, /* tp_as_number */ + 0, /* tp_as_sequence */ + 0, /* tp_as_mapping */ + 0, /* tp_hash */ + (ternaryfunc)methoddescr_call, /* 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 */ + descr_traverse, /* tp_traverse */ + 0, /* tp_clear */ + 0, /* tp_richcompare */ + 0, /* tp_weaklistoffset */ + 0, /* tp_iter */ + 0, /* tp_iternext */ + 0, /* tp_methods */ + descr_members, /* tp_members */ + method_getset, /* tp_getset */ + 0, /* tp_base */ + 0, /* tp_dict */ + (descrgetfunc)method_get, /* tp_descr_get */ + 0, /* tp_descr_set */ }; /* This is for METH_CLASS in C, not for "f = classmethod(f)" in Python! */ PyTypeObject PyClassMethodDescr_Type = { - PyVarObject_HEAD_INIT(&PyType_Type, 0) - "classmethod_descriptor", - sizeof(PyMethodDescrObject), - 0, - (destructor)descr_dealloc, /* tp_dealloc */ - 0, /* tp_print */ - 0, /* tp_getattr */ - 0, /* tp_setattr */ - 0, /* tp_reserved */ - (reprfunc)method_repr, /* tp_repr */ - 0, /* tp_as_number */ - 0, /* tp_as_sequence */ - 0, /* tp_as_mapping */ - 0, /* tp_hash */ - (ternaryfunc)classmethoddescr_call, /* 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 */ - descr_traverse, /* tp_traverse */ - 0, /* tp_clear */ - 0, /* tp_richcompare */ - 0, /* tp_weaklistoffset */ - 0, /* tp_iter */ - 0, /* tp_iternext */ - 0, /* tp_methods */ - descr_members, /* tp_members */ - method_getset, /* tp_getset */ - 0, /* tp_base */ - 0, /* tp_dict */ - (descrgetfunc)classmethod_get, /* tp_descr_get */ - 0, /* tp_descr_set */ + PyVarObject_HEAD_INIT(&PyType_Type, 0) + "classmethod_descriptor", + sizeof(PyMethodDescrObject), + 0, + (destructor)descr_dealloc, /* tp_dealloc */ + 0, /* tp_print */ + 0, /* tp_getattr */ + 0, /* tp_setattr */ + 0, /* tp_reserved */ + (reprfunc)method_repr, /* tp_repr */ + 0, /* tp_as_number */ + 0, /* tp_as_sequence */ + 0, /* tp_as_mapping */ + 0, /* tp_hash */ + (ternaryfunc)classmethoddescr_call, /* 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 */ + descr_traverse, /* tp_traverse */ + 0, /* tp_clear */ + 0, /* tp_richcompare */ + 0, /* tp_weaklistoffset */ + 0, /* tp_iter */ + 0, /* tp_iternext */ + 0, /* tp_methods */ + descr_members, /* tp_members */ + method_getset, /* tp_getset */ + 0, /* tp_base */ + 0, /* tp_dict */ + (descrgetfunc)classmethod_get, /* tp_descr_get */ + 0, /* tp_descr_set */ }; PyTypeObject PyMemberDescr_Type = { - PyVarObject_HEAD_INIT(&PyType_Type, 0) - "member_descriptor", - sizeof(PyMemberDescrObject), - 0, - (destructor)descr_dealloc, /* tp_dealloc */ - 0, /* tp_print */ - 0, /* tp_getattr */ - 0, /* tp_setattr */ - 0, /* tp_reserved */ - (reprfunc)member_repr, /* 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 */ - descr_traverse, /* tp_traverse */ - 0, /* tp_clear */ - 0, /* tp_richcompare */ - 0, /* tp_weaklistoffset */ - 0, /* tp_iter */ - 0, /* tp_iternext */ - 0, /* tp_methods */ - descr_members, /* tp_members */ - member_getset, /* tp_getset */ - 0, /* tp_base */ - 0, /* tp_dict */ - (descrgetfunc)member_get, /* tp_descr_get */ - (descrsetfunc)member_set, /* tp_descr_set */ + PyVarObject_HEAD_INIT(&PyType_Type, 0) + "member_descriptor", + sizeof(PyMemberDescrObject), + 0, + (destructor)descr_dealloc, /* tp_dealloc */ + 0, /* tp_print */ + 0, /* tp_getattr */ + 0, /* tp_setattr */ + 0, /* tp_reserved */ + (reprfunc)member_repr, /* 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 */ + descr_traverse, /* tp_traverse */ + 0, /* tp_clear */ + 0, /* tp_richcompare */ + 0, /* tp_weaklistoffset */ + 0, /* tp_iter */ + 0, /* tp_iternext */ + 0, /* tp_methods */ + descr_members, /* tp_members */ + member_getset, /* tp_getset */ + 0, /* tp_base */ + 0, /* tp_dict */ + (descrgetfunc)member_get, /* tp_descr_get */ + (descrsetfunc)member_set, /* tp_descr_set */ }; PyTypeObject PyGetSetDescr_Type = { - PyVarObject_HEAD_INIT(&PyType_Type, 0) - "getset_descriptor", - sizeof(PyGetSetDescrObject), - 0, - (destructor)descr_dealloc, /* tp_dealloc */ - 0, /* tp_print */ - 0, /* tp_getattr */ - 0, /* tp_setattr */ - 0, /* tp_reserved */ - (reprfunc)getset_repr, /* 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 */ - descr_traverse, /* tp_traverse */ - 0, /* tp_clear */ - 0, /* tp_richcompare */ - 0, /* tp_weaklistoffset */ - 0, /* tp_iter */ - 0, /* tp_iternext */ - 0, /* tp_methods */ - descr_members, /* tp_members */ - getset_getset, /* tp_getset */ - 0, /* tp_base */ - 0, /* tp_dict */ - (descrgetfunc)getset_get, /* tp_descr_get */ - (descrsetfunc)getset_set, /* tp_descr_set */ + PyVarObject_HEAD_INIT(&PyType_Type, 0) + "getset_descriptor", + sizeof(PyGetSetDescrObject), + 0, + (destructor)descr_dealloc, /* tp_dealloc */ + 0, /* tp_print */ + 0, /* tp_getattr */ + 0, /* tp_setattr */ + 0, /* tp_reserved */ + (reprfunc)getset_repr, /* 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 */ + descr_traverse, /* tp_traverse */ + 0, /* tp_clear */ + 0, /* tp_richcompare */ + 0, /* tp_weaklistoffset */ + 0, /* tp_iter */ + 0, /* tp_iternext */ + 0, /* tp_methods */ + descr_members, /* tp_members */ + getset_getset, /* tp_getset */ + 0, /* tp_base */ + 0, /* tp_dict */ + (descrgetfunc)getset_get, /* tp_descr_get */ + (descrsetfunc)getset_set, /* tp_descr_set */ }; PyTypeObject PyWrapperDescr_Type = { - PyVarObject_HEAD_INIT(&PyType_Type, 0) - "wrapper_descriptor", - sizeof(PyWrapperDescrObject), - 0, - (destructor)descr_dealloc, /* tp_dealloc */ - 0, /* tp_print */ - 0, /* tp_getattr */ - 0, /* tp_setattr */ - 0, /* tp_reserved */ - (reprfunc)wrapperdescr_repr, /* tp_repr */ - 0, /* tp_as_number */ - 0, /* tp_as_sequence */ - 0, /* tp_as_mapping */ - 0, /* tp_hash */ - (ternaryfunc)wrapperdescr_call, /* 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 */ - descr_traverse, /* tp_traverse */ - 0, /* tp_clear */ - 0, /* tp_richcompare */ - 0, /* tp_weaklistoffset */ - 0, /* tp_iter */ - 0, /* tp_iternext */ - 0, /* tp_methods */ - descr_members, /* tp_members */ - wrapperdescr_getset, /* tp_getset */ - 0, /* tp_base */ - 0, /* tp_dict */ - (descrgetfunc)wrapperdescr_get, /* tp_descr_get */ - 0, /* tp_descr_set */ + PyVarObject_HEAD_INIT(&PyType_Type, 0) + "wrapper_descriptor", + sizeof(PyWrapperDescrObject), + 0, + (destructor)descr_dealloc, /* tp_dealloc */ + 0, /* tp_print */ + 0, /* tp_getattr */ + 0, /* tp_setattr */ + 0, /* tp_reserved */ + (reprfunc)wrapperdescr_repr, /* tp_repr */ + 0, /* tp_as_number */ + 0, /* tp_as_sequence */ + 0, /* tp_as_mapping */ + 0, /* tp_hash */ + (ternaryfunc)wrapperdescr_call, /* 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 */ + descr_traverse, /* tp_traverse */ + 0, /* tp_clear */ + 0, /* tp_richcompare */ + 0, /* tp_weaklistoffset */ + 0, /* tp_iter */ + 0, /* tp_iternext */ + 0, /* tp_methods */ + descr_members, /* tp_members */ + wrapperdescr_getset, /* tp_getset */ + 0, /* tp_base */ + 0, /* tp_dict */ + (descrgetfunc)wrapperdescr_get, /* tp_descr_get */ + 0, /* tp_descr_set */ }; static PyDescrObject * descr_new(PyTypeObject *descrtype, PyTypeObject *type, const char *name) { - PyDescrObject *descr; + PyDescrObject *descr; - descr = (PyDescrObject *)PyType_GenericAlloc(descrtype, 0); - if (descr != NULL) { - Py_XINCREF(type); - descr->d_type = type; - descr->d_name = PyUnicode_InternFromString(name); - if (descr->d_name == NULL) { - Py_DECREF(descr); - descr = NULL; - } - } - return descr; + descr = (PyDescrObject *)PyType_GenericAlloc(descrtype, 0); + if (descr != NULL) { + Py_XINCREF(type); + descr->d_type = type; + descr->d_name = PyUnicode_InternFromString(name); + if (descr->d_name == NULL) { + Py_DECREF(descr); + descr = NULL; + } + } + return descr; } PyObject * PyDescr_NewMethod(PyTypeObject *type, PyMethodDef *method) { - PyMethodDescrObject *descr; + PyMethodDescrObject *descr; - descr = (PyMethodDescrObject *)descr_new(&PyMethodDescr_Type, - type, method->ml_name); - if (descr != NULL) - descr->d_method = method; - return (PyObject *)descr; + descr = (PyMethodDescrObject *)descr_new(&PyMethodDescr_Type, + type, method->ml_name); + if (descr != NULL) + descr->d_method = method; + return (PyObject *)descr; } PyObject * PyDescr_NewClassMethod(PyTypeObject *type, PyMethodDef *method) { - PyMethodDescrObject *descr; + PyMethodDescrObject *descr; - descr = (PyMethodDescrObject *)descr_new(&PyClassMethodDescr_Type, - type, method->ml_name); - if (descr != NULL) - descr->d_method = method; - return (PyObject *)descr; + descr = (PyMethodDescrObject *)descr_new(&PyClassMethodDescr_Type, + type, method->ml_name); + if (descr != NULL) + descr->d_method = method; + return (PyObject *)descr; } PyObject * PyDescr_NewMember(PyTypeObject *type, PyMemberDef *member) { - PyMemberDescrObject *descr; + PyMemberDescrObject *descr; - descr = (PyMemberDescrObject *)descr_new(&PyMemberDescr_Type, - type, member->name); - if (descr != NULL) - descr->d_member = member; - return (PyObject *)descr; + descr = (PyMemberDescrObject *)descr_new(&PyMemberDescr_Type, + type, member->name); + if (descr != NULL) + descr->d_member = member; + return (PyObject *)descr; } PyObject * PyDescr_NewGetSet(PyTypeObject *type, PyGetSetDef *getset) { - PyGetSetDescrObject *descr; + PyGetSetDescrObject *descr; - descr = (PyGetSetDescrObject *)descr_new(&PyGetSetDescr_Type, - type, getset->name); - if (descr != NULL) - descr->d_getset = getset; - return (PyObject *)descr; + descr = (PyGetSetDescrObject *)descr_new(&PyGetSetDescr_Type, + type, getset->name); + if (descr != NULL) + descr->d_getset = getset; + return (PyObject *)descr; } PyObject * PyDescr_NewWrapper(PyTypeObject *type, struct wrapperbase *base, void *wrapped) { - PyWrapperDescrObject *descr; + PyWrapperDescrObject *descr; - descr = (PyWrapperDescrObject *)descr_new(&PyWrapperDescr_Type, - type, base->name); - if (descr != NULL) { - descr->d_base = base; - descr->d_wrapped = wrapped; - } - return (PyObject *)descr; + descr = (PyWrapperDescrObject *)descr_new(&PyWrapperDescr_Type, + type, base->name); + if (descr != NULL) { + descr->d_base = base; + descr->d_wrapped = wrapped; + } + return (PyObject *)descr; } @@ -656,180 +656,180 @@ bit of a pain */ typedef struct { - PyObject_HEAD - PyObject *dict; + PyObject_HEAD + PyObject *dict; } proxyobject; static Py_ssize_t proxy_len(proxyobject *pp) { - return PyObject_Size(pp->dict); + return PyObject_Size(pp->dict); } static PyObject * proxy_getitem(proxyobject *pp, PyObject *key) { - return PyObject_GetItem(pp->dict, key); + return PyObject_GetItem(pp->dict, key); } static PyMappingMethods proxy_as_mapping = { - (lenfunc)proxy_len, /* mp_length */ - (binaryfunc)proxy_getitem, /* mp_subscript */ - 0, /* mp_ass_subscript */ + (lenfunc)proxy_len, /* mp_length */ + (binaryfunc)proxy_getitem, /* mp_subscript */ + 0, /* mp_ass_subscript */ }; static int proxy_contains(proxyobject *pp, PyObject *key) { - return PyDict_Contains(pp->dict, key); + return PyDict_Contains(pp->dict, key); } static PySequenceMethods proxy_as_sequence = { - 0, /* sq_length */ - 0, /* sq_concat */ - 0, /* sq_repeat */ - 0, /* sq_item */ - 0, /* sq_slice */ - 0, /* sq_ass_item */ - 0, /* sq_ass_slice */ - (objobjproc)proxy_contains, /* sq_contains */ - 0, /* sq_inplace_concat */ - 0, /* sq_inplace_repeat */ + 0, /* sq_length */ + 0, /* sq_concat */ + 0, /* sq_repeat */ + 0, /* sq_item */ + 0, /* sq_slice */ + 0, /* sq_ass_item */ + 0, /* sq_ass_slice */ + (objobjproc)proxy_contains, /* sq_contains */ + 0, /* sq_inplace_concat */ + 0, /* sq_inplace_repeat */ }; static PyObject * proxy_get(proxyobject *pp, PyObject *args) { - PyObject *key, *def = Py_None; + PyObject *key, *def = Py_None; - if (!PyArg_UnpackTuple(args, "get", 1, 2, &key, &def)) - return NULL; - return PyObject_CallMethod(pp->dict, "get", "(OO)", key, def); + if (!PyArg_UnpackTuple(args, "get", 1, 2, &key, &def)) + return NULL; + return PyObject_CallMethod(pp->dict, "get", "(OO)", key, def); } static PyObject * proxy_keys(proxyobject *pp) { - return PyMapping_Keys(pp->dict); + return PyMapping_Keys(pp->dict); } static PyObject * proxy_values(proxyobject *pp) { - return PyMapping_Values(pp->dict); + return PyMapping_Values(pp->dict); } static PyObject * proxy_items(proxyobject *pp) { - return PyMapping_Items(pp->dict); + return PyMapping_Items(pp->dict); } static PyObject * proxy_copy(proxyobject *pp) { - return PyObject_CallMethod(pp->dict, "copy", NULL); + return PyObject_CallMethod(pp->dict, "copy", NULL); } static PyMethodDef proxy_methods[] = { - {"get", (PyCFunction)proxy_get, METH_VARARGS, - PyDoc_STR("D.get(k[,d]) -> D[k] if k in D, else d." - " d defaults to None.")}, - {"keys", (PyCFunction)proxy_keys, METH_NOARGS, - PyDoc_STR("D.keys() -> list of D's keys")}, - {"values", (PyCFunction)proxy_values, METH_NOARGS, - PyDoc_STR("D.values() -> list of D's values")}, - {"items", (PyCFunction)proxy_items, METH_NOARGS, - PyDoc_STR("D.items() -> list of D's (key, value) pairs, as 2-tuples")}, - {"copy", (PyCFunction)proxy_copy, METH_NOARGS, - PyDoc_STR("D.copy() -> a shallow copy of D")}, - {0} + {"get", (PyCFunction)proxy_get, METH_VARARGS, + PyDoc_STR("D.get(k[,d]) -> D[k] if k in D, else d." + " d defaults to None.")}, + {"keys", (PyCFunction)proxy_keys, METH_NOARGS, + PyDoc_STR("D.keys() -> list of D's keys")}, + {"values", (PyCFunction)proxy_values, METH_NOARGS, + PyDoc_STR("D.values() -> list of D's values")}, + {"items", (PyCFunction)proxy_items, METH_NOARGS, + PyDoc_STR("D.items() -> list of D's (key, value) pairs, as 2-tuples")}, + {"copy", (PyCFunction)proxy_copy, METH_NOARGS, + PyDoc_STR("D.copy() -> a shallow copy of D")}, + {0} }; static void proxy_dealloc(proxyobject *pp) { - _PyObject_GC_UNTRACK(pp); - Py_DECREF(pp->dict); - PyObject_GC_Del(pp); + _PyObject_GC_UNTRACK(pp); + Py_DECREF(pp->dict); + PyObject_GC_Del(pp); } static PyObject * proxy_getiter(proxyobject *pp) { - return PyObject_GetIter(pp->dict); + return PyObject_GetIter(pp->dict); } static PyObject * proxy_str(proxyobject *pp) { - return PyObject_Str(pp->dict); + return PyObject_Str(pp->dict); } static int proxy_traverse(PyObject *self, visitproc visit, void *arg) { - proxyobject *pp = (proxyobject *)self; - Py_VISIT(pp->dict); - return 0; + proxyobject *pp = (proxyobject *)self; + Py_VISIT(pp->dict); + return 0; } static PyObject * proxy_richcompare(proxyobject *v, PyObject *w, int op) { - return PyObject_RichCompare(v->dict, w, op); + return PyObject_RichCompare(v->dict, w, op); } PyTypeObject PyDictProxy_Type = { - PyVarObject_HEAD_INIT(&PyType_Type, 0) - "dict_proxy", /* tp_name */ - sizeof(proxyobject), /* tp_basicsize */ - 0, /* tp_itemsize */ - /* methods */ - (destructor)proxy_dealloc, /* tp_dealloc */ - 0, /* tp_print */ - 0, /* tp_getattr */ - 0, /* tp_setattr */ - 0, /* tp_reserved */ - 0, /* tp_repr */ - 0, /* tp_as_number */ - &proxy_as_sequence, /* tp_as_sequence */ - &proxy_as_mapping, /* tp_as_mapping */ - 0, /* tp_hash */ - 0, /* tp_call */ - (reprfunc)proxy_str, /* 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 */ - proxy_traverse, /* tp_traverse */ - 0, /* tp_clear */ - (richcmpfunc)proxy_richcompare, /* tp_richcompare */ - 0, /* tp_weaklistoffset */ - (getiterfunc)proxy_getiter, /* tp_iter */ - 0, /* tp_iternext */ - proxy_methods, /* tp_methods */ - 0, /* tp_members */ - 0, /* tp_getset */ - 0, /* tp_base */ - 0, /* tp_dict */ - 0, /* tp_descr_get */ - 0, /* tp_descr_set */ + PyVarObject_HEAD_INIT(&PyType_Type, 0) + "dict_proxy", /* tp_name */ + sizeof(proxyobject), /* tp_basicsize */ + 0, /* tp_itemsize */ + /* methods */ + (destructor)proxy_dealloc, /* tp_dealloc */ + 0, /* tp_print */ + 0, /* tp_getattr */ + 0, /* tp_setattr */ + 0, /* tp_reserved */ + 0, /* tp_repr */ + 0, /* tp_as_number */ + &proxy_as_sequence, /* tp_as_sequence */ + &proxy_as_mapping, /* tp_as_mapping */ + 0, /* tp_hash */ + 0, /* tp_call */ + (reprfunc)proxy_str, /* 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 */ + proxy_traverse, /* tp_traverse */ + 0, /* tp_clear */ + (richcmpfunc)proxy_richcompare, /* tp_richcompare */ + 0, /* tp_weaklistoffset */ + (getiterfunc)proxy_getiter, /* tp_iter */ + 0, /* tp_iternext */ + proxy_methods, /* tp_methods */ + 0, /* tp_members */ + 0, /* tp_getset */ + 0, /* tp_base */ + 0, /* tp_dict */ + 0, /* tp_descr_get */ + 0, /* tp_descr_set */ }; PyObject * PyDictProxy_New(PyObject *dict) { - proxyobject *pp; + proxyobject *pp; - pp = PyObject_GC_New(proxyobject, &PyDictProxy_Type); - if (pp != NULL) { - Py_INCREF(dict); - pp->dict = dict; - _PyObject_GC_TRACK(pp); - } - return (PyObject *)pp; + pp = PyObject_GC_New(proxyobject, &PyDictProxy_Type); + if (pp != NULL) { + Py_INCREF(dict); + pp->dict = dict; + _PyObject_GC_TRACK(pp); + } + return (PyObject *)pp; } @@ -842,9 +842,9 @@ static PyTypeObject wrappertype; typedef struct { - PyObject_HEAD - PyWrapperDescrObject *descr; - PyObject *self; + PyObject_HEAD + PyWrapperDescrObject *descr; + PyObject *self; } wrapperobject; #define Wrapper_Check(v) (Py_TYPE(v) == &wrappertype) @@ -852,12 +852,12 @@ static void wrapper_dealloc(wrapperobject *wp) { - PyObject_GC_UnTrack(wp); - Py_TRASHCAN_SAFE_BEGIN(wp) - Py_XDECREF(wp->descr); - Py_XDECREF(wp->self); - PyObject_GC_Del(wp); - Py_TRASHCAN_SAFE_END(wp) + PyObject_GC_UnTrack(wp); + Py_TRASHCAN_SAFE_BEGIN(wp) + Py_XDECREF(wp->descr); + Py_XDECREF(wp->self); + PyObject_GC_Del(wp); + Py_TRASHCAN_SAFE_END(wp) } #define TEST_COND(cond) ((cond) ? Py_True : Py_False) @@ -865,211 +865,211 @@ static PyObject * wrapper_richcompare(PyObject *a, PyObject *b, int op) { - int result; - PyObject *v; - PyWrapperDescrObject *a_descr, *b_descr; - - assert(a != NULL && b != NULL); - - /* both arguments should be wrapperobjects */ - if (!Wrapper_Check(a) || !Wrapper_Check(b)) { - v = Py_NotImplemented; - Py_INCREF(v); - return v; - } - - /* compare by descriptor address; if the descriptors are the same, - compare by the objects they're bound to */ - a_descr = ((wrapperobject *)a)->descr; - b_descr = ((wrapperobject *)b)->descr; - if (a_descr == b_descr) { - a = ((wrapperobject *)a)->self; - b = ((wrapperobject *)b)->self; - return PyObject_RichCompare(a, b, op); - } - - result = a_descr - b_descr; - switch (op) { - case Py_EQ: - v = TEST_COND(result == 0); - break; - case Py_NE: - v = TEST_COND(result != 0); - break; - case Py_LE: - v = TEST_COND(result <= 0); - break; - case Py_GE: - v = TEST_COND(result >= 0); - break; - case Py_LT: - v = TEST_COND(result < 0); - break; - case Py_GT: - v = TEST_COND(result > 0); - break; - default: - PyErr_BadArgument(); - return NULL; - } - Py_INCREF(v); - return v; + int result; + PyObject *v; + PyWrapperDescrObject *a_descr, *b_descr; + + assert(a != NULL && b != NULL); + + /* both arguments should be wrapperobjects */ + if (!Wrapper_Check(a) || !Wrapper_Check(b)) { + v = Py_NotImplemented; + Py_INCREF(v); + return v; + } + + /* compare by descriptor address; if the descriptors are the same, + compare by the objects they're bound to */ + a_descr = ((wrapperobject *)a)->descr; + b_descr = ((wrapperobject *)b)->descr; + if (a_descr == b_descr) { + a = ((wrapperobject *)a)->self; + b = ((wrapperobject *)b)->self; + return PyObject_RichCompare(a, b, op); + } + + result = a_descr - b_descr; + switch (op) { + case Py_EQ: + v = TEST_COND(result == 0); + break; + case Py_NE: + v = TEST_COND(result != 0); + break; + case Py_LE: + v = TEST_COND(result <= 0); + break; + case Py_GE: + v = TEST_COND(result >= 0); + break; + case Py_LT: + v = TEST_COND(result < 0); + break; + case Py_GT: + v = TEST_COND(result > 0); + break; + default: + PyErr_BadArgument(); + return NULL; + } + Py_INCREF(v); + return v; } static long wrapper_hash(wrapperobject *wp) { - int x, y; - x = _Py_HashPointer(wp->descr); - if (x == -1) - return -1; - y = PyObject_Hash(wp->self); - if (y == -1) - return -1; - x = x ^ y; - if (x == -1) - x = -2; - return x; + int x, y; + x = _Py_HashPointer(wp->descr); + if (x == -1) + return -1; + y = PyObject_Hash(wp->self); + if (y == -1) + return -1; + x = x ^ y; + if (x == -1) + x = -2; + return x; } static PyObject * wrapper_repr(wrapperobject *wp) { - return PyUnicode_FromFormat("", - wp->descr->d_base->name, - wp->self->ob_type->tp_name, - wp->self); + return PyUnicode_FromFormat("", + wp->descr->d_base->name, + wp->self->ob_type->tp_name, + wp->self); } static PyMemberDef wrapper_members[] = { - {"__self__", T_OBJECT, offsetof(wrapperobject, self), READONLY}, - {0} + {"__self__", T_OBJECT, offsetof(wrapperobject, self), READONLY}, + {0} }; static PyObject * wrapper_objclass(wrapperobject *wp) { - PyObject *c = (PyObject *)PyDescr_TYPE(wp->descr); + PyObject *c = (PyObject *)PyDescr_TYPE(wp->descr); - Py_INCREF(c); - return c; + Py_INCREF(c); + return c; } static PyObject * wrapper_name(wrapperobject *wp) { - const char *s = wp->descr->d_base->name; + const char *s = wp->descr->d_base->name; - return PyUnicode_FromString(s); + return PyUnicode_FromString(s); } static PyObject * wrapper_doc(wrapperobject *wp) { - const char *s = wp->descr->d_base->doc; + const char *s = wp->descr->d_base->doc; - if (s == NULL) { - Py_INCREF(Py_None); - return Py_None; - } - else { - return PyUnicode_FromString(s); - } + if (s == NULL) { + Py_INCREF(Py_None); + return Py_None; + } + else { + return PyUnicode_FromString(s); + } } static PyGetSetDef wrapper_getsets[] = { - {"__objclass__", (getter)wrapper_objclass}, - {"__name__", (getter)wrapper_name}, - {"__doc__", (getter)wrapper_doc}, - {0} + {"__objclass__", (getter)wrapper_objclass}, + {"__name__", (getter)wrapper_name}, + {"__doc__", (getter)wrapper_doc}, + {0} }; static PyObject * wrapper_call(wrapperobject *wp, PyObject *args, PyObject *kwds) { - wrapperfunc wrapper = wp->descr->d_base->wrapper; - PyObject *self = wp->self; + wrapperfunc wrapper = wp->descr->d_base->wrapper; + PyObject *self = wp->self; - if (wp->descr->d_base->flags & PyWrapperFlag_KEYWORDS) { - wrapperfunc_kwds wk = (wrapperfunc_kwds)wrapper; - return (*wk)(self, args, wp->descr->d_wrapped, kwds); - } - - if (kwds != NULL && (!PyDict_Check(kwds) || PyDict_Size(kwds) != 0)) { - PyErr_Format(PyExc_TypeError, - "wrapper %s doesn't take keyword arguments", - wp->descr->d_base->name); - return NULL; - } - return (*wrapper)(self, args, wp->descr->d_wrapped); + if (wp->descr->d_base->flags & PyWrapperFlag_KEYWORDS) { + wrapperfunc_kwds wk = (wrapperfunc_kwds)wrapper; + return (*wk)(self, args, wp->descr->d_wrapped, kwds); + } + + if (kwds != NULL && (!PyDict_Check(kwds) || PyDict_Size(kwds) != 0)) { + PyErr_Format(PyExc_TypeError, + "wrapper %s doesn't take keyword arguments", + wp->descr->d_base->name); + return NULL; + } + return (*wrapper)(self, args, wp->descr->d_wrapped); } static int wrapper_traverse(PyObject *self, visitproc visit, void *arg) { - wrapperobject *wp = (wrapperobject *)self; - Py_VISIT(wp->descr); - Py_VISIT(wp->self); - return 0; + wrapperobject *wp = (wrapperobject *)self; + Py_VISIT(wp->descr); + Py_VISIT(wp->self); + return 0; } static PyTypeObject wrappertype = { - PyVarObject_HEAD_INIT(&PyType_Type, 0) - "method-wrapper", /* tp_name */ - sizeof(wrapperobject), /* tp_basicsize */ - 0, /* tp_itemsize */ - /* methods */ - (destructor)wrapper_dealloc, /* tp_dealloc */ - 0, /* tp_print */ - 0, /* tp_getattr */ - 0, /* tp_setattr */ - 0, /* tp_reserved */ - (reprfunc)wrapper_repr, /* tp_repr */ - 0, /* tp_as_number */ - 0, /* tp_as_sequence */ - 0, /* tp_as_mapping */ - (hashfunc)wrapper_hash, /* tp_hash */ - (ternaryfunc)wrapper_call, /* 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 */ - wrapper_traverse, /* tp_traverse */ - 0, /* tp_clear */ - wrapper_richcompare, /* tp_richcompare */ - 0, /* tp_weaklistoffset */ - 0, /* tp_iter */ - 0, /* tp_iternext */ - 0, /* tp_methods */ - wrapper_members, /* tp_members */ - wrapper_getsets, /* tp_getset */ - 0, /* tp_base */ - 0, /* tp_dict */ - 0, /* tp_descr_get */ - 0, /* tp_descr_set */ + PyVarObject_HEAD_INIT(&PyType_Type, 0) + "method-wrapper", /* tp_name */ + sizeof(wrapperobject), /* tp_basicsize */ + 0, /* tp_itemsize */ + /* methods */ + (destructor)wrapper_dealloc, /* tp_dealloc */ + 0, /* tp_print */ + 0, /* tp_getattr */ + 0, /* tp_setattr */ + 0, /* tp_reserved */ + (reprfunc)wrapper_repr, /* tp_repr */ + 0, /* tp_as_number */ + 0, /* tp_as_sequence */ + 0, /* tp_as_mapping */ + (hashfunc)wrapper_hash, /* tp_hash */ + (ternaryfunc)wrapper_call, /* 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 */ + wrapper_traverse, /* tp_traverse */ + 0, /* tp_clear */ + wrapper_richcompare, /* tp_richcompare */ + 0, /* tp_weaklistoffset */ + 0, /* tp_iter */ + 0, /* tp_iternext */ + 0, /* tp_methods */ + wrapper_members, /* tp_members */ + wrapper_getsets, /* tp_getset */ + 0, /* tp_base */ + 0, /* tp_dict */ + 0, /* tp_descr_get */ + 0, /* tp_descr_set */ }; PyObject * PyWrapper_New(PyObject *d, PyObject *self) { - wrapperobject *wp; - PyWrapperDescrObject *descr; + wrapperobject *wp; + PyWrapperDescrObject *descr; - assert(PyObject_TypeCheck(d, &PyWrapperDescr_Type)); - descr = (PyWrapperDescrObject *)d; - assert(PyObject_IsInstance(self, (PyObject *)PyDescr_TYPE(descr))); - - wp = PyObject_GC_New(wrapperobject, &wrappertype); - if (wp != NULL) { - Py_INCREF(descr); - wp->descr = descr; - Py_INCREF(self); - wp->self = self; - _PyObject_GC_TRACK(wp); - } - return (PyObject *)wp; + assert(PyObject_TypeCheck(d, &PyWrapperDescr_Type)); + descr = (PyWrapperDescrObject *)d; + assert(PyObject_IsInstance(self, (PyObject *)PyDescr_TYPE(descr))); + + wp = PyObject_GC_New(wrapperobject, &wrappertype); + if (wp != NULL) { + Py_INCREF(descr); + wp->descr = descr; + Py_INCREF(self); + wp->self = self; + _PyObject_GC_TRACK(wp); + } + return (PyObject *)wp; } @@ -1078,247 +1078,247 @@ /* class property(object): - def __init__(self, fget=None, fset=None, fdel=None, doc=None): - if doc is None and fget is not None and hasattr(fget, "__doc__"): - doc = fget.__doc__ - self.__get = fget - self.__set = fset - self.__del = fdel - self.__doc__ = doc - - def __get__(self, inst, type=None): - if inst is None: - return self - if self.__get is None: - raise AttributeError, "unreadable attribute" - return self.__get(inst) - - def __set__(self, inst, value): - if self.__set is None: - raise AttributeError, "can't set attribute" - return self.__set(inst, value) - - def __delete__(self, inst): - if self.__del is None: - raise AttributeError, "can't delete attribute" - return self.__del(inst) + def __init__(self, fget=None, fset=None, fdel=None, doc=None): + if doc is None and fget is not None and hasattr(fget, "__doc__"): + doc = fget.__doc__ + self.__get = fget + self.__set = fset + self.__del = fdel + self.__doc__ = doc + + def __get__(self, inst, type=None): + if inst is None: + return self + if self.__get is None: + raise AttributeError, "unreadable attribute" + return self.__get(inst) + + def __set__(self, inst, value): + if self.__set is None: + raise AttributeError, "can't set attribute" + return self.__set(inst, value) + + def __delete__(self, inst): + if self.__del is None: + raise AttributeError, "can't delete attribute" + return self.__del(inst) */ typedef struct { - PyObject_HEAD - PyObject *prop_get; - PyObject *prop_set; - PyObject *prop_del; - PyObject *prop_doc; - int getter_doc; + PyObject_HEAD + PyObject *prop_get; + PyObject *prop_set; + PyObject *prop_del; + PyObject *prop_doc; + int getter_doc; } propertyobject; static PyObject * property_copy(PyObject *, PyObject *, PyObject *, - PyObject *, PyObject *); + PyObject *, PyObject *); static PyMemberDef property_members[] = { - {"fget", T_OBJECT, offsetof(propertyobject, prop_get), READONLY}, - {"fset", T_OBJECT, offsetof(propertyobject, prop_set), READONLY}, - {"fdel", T_OBJECT, offsetof(propertyobject, prop_del), READONLY}, - {"__doc__", T_OBJECT, offsetof(propertyobject, prop_doc), READONLY}, - {0} + {"fget", T_OBJECT, offsetof(propertyobject, prop_get), READONLY}, + {"fset", T_OBJECT, offsetof(propertyobject, prop_set), READONLY}, + {"fdel", T_OBJECT, offsetof(propertyobject, prop_del), READONLY}, + {"__doc__", T_OBJECT, offsetof(propertyobject, prop_doc), READONLY}, + {0} }; PyDoc_STRVAR(getter_doc, - "Descriptor to change the getter on a property."); + "Descriptor to change the getter on a property."); static PyObject * property_getter(PyObject *self, PyObject *getter) { - return property_copy(self, getter, NULL, NULL, NULL); + return property_copy(self, getter, NULL, NULL, NULL); } PyDoc_STRVAR(setter_doc, - "Descriptor to change the setter on a property."); + "Descriptor to change the setter on a property."); static PyObject * property_setter(PyObject *self, PyObject *setter) { - return property_copy(self, NULL, setter, NULL, NULL); + return property_copy(self, NULL, setter, NULL, NULL); } PyDoc_STRVAR(deleter_doc, - "Descriptor to change the deleter on a property."); + "Descriptor to change the deleter on a property."); static PyObject * property_deleter(PyObject *self, PyObject *deleter) { - return property_copy(self, NULL, NULL, deleter, NULL); + return property_copy(self, NULL, NULL, deleter, NULL); } static PyMethodDef property_methods[] = { - {"getter", property_getter, METH_O, getter_doc}, - {"setter", property_setter, METH_O, setter_doc}, - {"deleter", property_deleter, METH_O, deleter_doc}, - {0} + {"getter", property_getter, METH_O, getter_doc}, + {"setter", property_setter, METH_O, setter_doc}, + {"deleter", property_deleter, METH_O, deleter_doc}, + {0} }; static void property_dealloc(PyObject *self) { - propertyobject *gs = (propertyobject *)self; + propertyobject *gs = (propertyobject *)self; - _PyObject_GC_UNTRACK(self); - Py_XDECREF(gs->prop_get); - Py_XDECREF(gs->prop_set); - Py_XDECREF(gs->prop_del); - Py_XDECREF(gs->prop_doc); - self->ob_type->tp_free(self); + _PyObject_GC_UNTRACK(self); + Py_XDECREF(gs->prop_get); + Py_XDECREF(gs->prop_set); + Py_XDECREF(gs->prop_del); + Py_XDECREF(gs->prop_doc); + self->ob_type->tp_free(self); } static PyObject * property_descr_get(PyObject *self, PyObject *obj, PyObject *type) { - propertyobject *gs = (propertyobject *)self; + propertyobject *gs = (propertyobject *)self; - if (obj == NULL || obj == Py_None) { - Py_INCREF(self); - return self; - } - if (gs->prop_get == NULL) { - PyErr_SetString(PyExc_AttributeError, "unreadable attribute"); - return NULL; - } - return PyObject_CallFunction(gs->prop_get, "(O)", obj); + if (obj == NULL || obj == Py_None) { + Py_INCREF(self); + return self; + } + if (gs->prop_get == NULL) { + PyErr_SetString(PyExc_AttributeError, "unreadable attribute"); + return NULL; + } + return PyObject_CallFunction(gs->prop_get, "(O)", obj); } static int property_descr_set(PyObject *self, PyObject *obj, PyObject *value) { - propertyobject *gs = (propertyobject *)self; - PyObject *func, *res; + propertyobject *gs = (propertyobject *)self; + PyObject *func, *res; - if (value == NULL) - func = gs->prop_del; - else - func = gs->prop_set; - if (func == NULL) { - PyErr_SetString(PyExc_AttributeError, - value == NULL ? - "can't delete attribute" : - "can't set attribute"); - return -1; - } - if (value == NULL) - res = PyObject_CallFunction(func, "(O)", obj); - else - res = PyObject_CallFunction(func, "(OO)", obj, value); - if (res == NULL) - return -1; - Py_DECREF(res); - return 0; + if (value == NULL) + func = gs->prop_del; + else + func = gs->prop_set; + if (func == NULL) { + PyErr_SetString(PyExc_AttributeError, + value == NULL ? + "can't delete attribute" : + "can't set attribute"); + return -1; + } + if (value == NULL) + res = PyObject_CallFunction(func, "(O)", obj); + else + res = PyObject_CallFunction(func, "(OO)", obj, value); + if (res == NULL) + return -1; + Py_DECREF(res); + return 0; } static PyObject * property_copy(PyObject *old, PyObject *get, PyObject *set, PyObject *del, - PyObject *doc) + PyObject *doc) { - propertyobject *pold = (propertyobject *)old; - PyObject *new, *type; + propertyobject *pold = (propertyobject *)old; + PyObject *new, *type; - type = PyObject_Type(old); - if (type == NULL) - return NULL; - - if (get == NULL || get == Py_None) { - Py_XDECREF(get); - get = pold->prop_get ? pold->prop_get : Py_None; - } - if (set == NULL || set == Py_None) { - Py_XDECREF(set); - set = pold->prop_set ? pold->prop_set : Py_None; - } - if (del == NULL || del == Py_None) { - Py_XDECREF(del); - del = pold->prop_del ? pold->prop_del : Py_None; - } - if (doc == NULL || doc == Py_None) { - Py_XDECREF(doc); - if (pold->getter_doc && get != Py_None) { - /* make _init use __doc__ from getter */ - doc = Py_None; - } - else { - doc = pold->prop_doc ? pold->prop_doc : Py_None; - } - } - - new = PyObject_CallFunction(type, "OOOO", get, set, del, doc); - Py_DECREF(type); - if (new == NULL) - return NULL; - return new; + type = PyObject_Type(old); + if (type == NULL) + return NULL; + + if (get == NULL || get == Py_None) { + Py_XDECREF(get); + get = pold->prop_get ? pold->prop_get : Py_None; + } + if (set == NULL || set == Py_None) { + Py_XDECREF(set); + set = pold->prop_set ? pold->prop_set : Py_None; + } + if (del == NULL || del == Py_None) { + Py_XDECREF(del); + del = pold->prop_del ? pold->prop_del : Py_None; + } + if (doc == NULL || doc == Py_None) { + Py_XDECREF(doc); + if (pold->getter_doc && get != Py_None) { + /* make _init use __doc__ from getter */ + doc = Py_None; + } + else { + doc = pold->prop_doc ? pold->prop_doc : Py_None; + } + } + + new = PyObject_CallFunction(type, "OOOO", get, set, del, doc); + Py_DECREF(type); + if (new == NULL) + return NULL; + return new; } static int property_init(PyObject *self, PyObject *args, PyObject *kwds) { - PyObject *get = NULL, *set = NULL, *del = NULL, *doc = NULL; - static char *kwlist[] = {"fget", "fset", "fdel", "doc", 0}; - propertyobject *prop = (propertyobject *)self; - - if (!PyArg_ParseTupleAndKeywords(args, kwds, "|OOOO:property", - kwlist, &get, &set, &del, &doc)) - return -1; - - if (get == Py_None) - get = NULL; - if (set == Py_None) - set = NULL; - if (del == Py_None) - del = NULL; - - Py_XINCREF(get); - Py_XINCREF(set); - Py_XINCREF(del); - Py_XINCREF(doc); - - prop->prop_get = get; - prop->prop_set = set; - prop->prop_del = del; - prop->prop_doc = doc; - prop->getter_doc = 0; - - /* if no docstring given and the getter has one, use that one */ - if ((doc == NULL || doc == Py_None) && get != NULL) { - PyObject *get_doc = PyObject_GetAttrString(get, "__doc__"); - if (get_doc) { - if (Py_TYPE(self) == &PyProperty_Type) { - Py_XDECREF(prop->prop_doc); - prop->prop_doc = get_doc; - } - else { - /* If this is a property subclass, put __doc__ - in dict of the subclass instance instead, - otherwise it gets shadowed by __doc__ in the - class's dict. */ - int err = PyObject_SetAttrString(self, "__doc__", get_doc); - Py_DECREF(get_doc); - if (err < 0) - return -1; - } - prop->getter_doc = 1; - } - else if (PyErr_ExceptionMatches(PyExc_Exception)) { - PyErr_Clear(); - } - else { - return -1; - } - } + PyObject *get = NULL, *set = NULL, *del = NULL, *doc = NULL; + static char *kwlist[] = {"fget", "fset", "fdel", "doc", 0}; + propertyobject *prop = (propertyobject *)self; + + if (!PyArg_ParseTupleAndKeywords(args, kwds, "|OOOO:property", + kwlist, &get, &set, &del, &doc)) + return -1; + + if (get == Py_None) + get = NULL; + if (set == Py_None) + set = NULL; + if (del == Py_None) + del = NULL; + + Py_XINCREF(get); + Py_XINCREF(set); + Py_XINCREF(del); + Py_XINCREF(doc); + + prop->prop_get = get; + prop->prop_set = set; + prop->prop_del = del; + prop->prop_doc = doc; + prop->getter_doc = 0; + + /* if no docstring given and the getter has one, use that one */ + if ((doc == NULL || doc == Py_None) && get != NULL) { + PyObject *get_doc = PyObject_GetAttrString(get, "__doc__"); + if (get_doc) { + if (Py_TYPE(self) == &PyProperty_Type) { + Py_XDECREF(prop->prop_doc); + prop->prop_doc = get_doc; + } + else { + /* If this is a property subclass, put __doc__ + in dict of the subclass instance instead, + otherwise it gets shadowed by __doc__ in the + class's dict. */ + int err = PyObject_SetAttrString(self, "__doc__", get_doc); + Py_DECREF(get_doc); + if (err < 0) + return -1; + } + prop->getter_doc = 1; + } + else if (PyErr_ExceptionMatches(PyExc_Exception)) { + PyErr_Clear(); + } + else { + return -1; + } + } - return 0; + return 0; } PyDoc_STRVAR(property_doc, @@ -1346,54 +1346,54 @@ static int property_traverse(PyObject *self, visitproc visit, void *arg) { - propertyobject *pp = (propertyobject *)self; - Py_VISIT(pp->prop_get); - Py_VISIT(pp->prop_set); - Py_VISIT(pp->prop_del); - Py_VISIT(pp->prop_doc); - return 0; + propertyobject *pp = (propertyobject *)self; + Py_VISIT(pp->prop_get); + Py_VISIT(pp->prop_set); + Py_VISIT(pp->prop_del); + Py_VISIT(pp->prop_doc); + return 0; } PyTypeObject PyProperty_Type = { - PyVarObject_HEAD_INIT(&PyType_Type, 0) - "property", /* tp_name */ - sizeof(propertyobject), /* tp_basicsize */ - 0, /* tp_itemsize */ - /* methods */ - property_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 | - Py_TPFLAGS_BASETYPE, /* tp_flags */ - property_doc, /* tp_doc */ - property_traverse, /* tp_traverse */ - 0, /* tp_clear */ - 0, /* tp_richcompare */ - 0, /* tp_weaklistoffset */ - 0, /* tp_iter */ - 0, /* tp_iternext */ - property_methods, /* tp_methods */ - property_members, /* tp_members */ - 0, /* tp_getset */ - 0, /* tp_base */ - 0, /* tp_dict */ - property_descr_get, /* tp_descr_get */ - property_descr_set, /* tp_descr_set */ - 0, /* tp_dictoffset */ - property_init, /* tp_init */ - PyType_GenericAlloc, /* tp_alloc */ - PyType_GenericNew, /* tp_new */ - PyObject_GC_Del, /* tp_free */ + PyVarObject_HEAD_INIT(&PyType_Type, 0) + "property", /* tp_name */ + sizeof(propertyobject), /* tp_basicsize */ + 0, /* tp_itemsize */ + /* methods */ + property_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 | + Py_TPFLAGS_BASETYPE, /* tp_flags */ + property_doc, /* tp_doc */ + property_traverse, /* tp_traverse */ + 0, /* tp_clear */ + 0, /* tp_richcompare */ + 0, /* tp_weaklistoffset */ + 0, /* tp_iter */ + 0, /* tp_iternext */ + property_methods, /* tp_methods */ + property_members, /* tp_members */ + 0, /* tp_getset */ + 0, /* tp_base */ + 0, /* tp_dict */ + property_descr_get, /* tp_descr_get */ + property_descr_set, /* tp_descr_set */ + 0, /* tp_dictoffset */ + property_init, /* tp_init */ + PyType_GenericAlloc, /* tp_alloc */ + PyType_GenericNew, /* tp_new */ + PyObject_GC_Del, /* tp_free */ }; Modified: python/branches/py3k/Objects/dictobject.c ============================================================================== --- python/branches/py3k/Objects/dictobject.c (original) +++ python/branches/py3k/Objects/dictobject.c Sun May 9 17:52:27 2010 @@ -17,12 +17,12 @@ static void set_key_error(PyObject *arg) { - PyObject *tup; - tup = PyTuple_Pack(1, arg); - if (!tup) - return; /* caller will expect error to be set anyway */ - PyErr_SetObject(PyExc_KeyError, tup); - Py_DECREF(tup); + PyObject *tup; + tup = PyTuple_Pack(1, arg); + if (!tup) + return; /* caller will expect error to be set anyway */ + PyErr_SetObject(PyExc_KeyError, tup); + Py_DECREF(tup); } /* Define this out if you don't want conversion statistics on exit. */ @@ -52,7 +52,7 @@ OTOH, when collisions occur, the tendency to fill contiguous slices of the hash table makes a good collision resolution strategy crucial. Taking only the last i bits of the hash code is also vulnerable: for example, consider -the list [i << 16 for i in range(20000)] as a set of keys. Since ints are +the list [i << 16 for i in range(20000)] as a set of keys. Since ints are their own hash codes, and this fits in a dict of size 2**15, the last 15 bits of every hash code are all 0: they *all* map to the same table index. @@ -142,7 +142,7 @@ PyObject * _PyDict_Dummy(void) { - return dummy; + return dummy; } #endif @@ -157,9 +157,9 @@ static void show_counts(void) { - fprintf(stderr, "created %ld string dicts\n", created); - fprintf(stderr, "converted %ld to normal dicts\n", converted); - fprintf(stderr, "%.2f%% conversion rate\n", (100.0*converted)/created); + fprintf(stderr, "created %ld string dicts\n", created); + fprintf(stderr, "converted %ld to normal dicts\n", converted); + fprintf(stderr, "%.2f%% conversion rate\n", (100.0*converted)/created); } #endif @@ -172,12 +172,12 @@ static void show_alloc(void) { - fprintf(stderr, "Dict allocations: %" PY_FORMAT_SIZE_T "d\n", - count_alloc); - fprintf(stderr, "Dict reuse through freelist: %" PY_FORMAT_SIZE_T - "d\n", count_reuse); - fprintf(stderr, "%.2f%% reuse rate\n\n", - (100.0*count_reuse/(count_alloc+count_reuse))); + fprintf(stderr, "Dict allocations: %" PY_FORMAT_SIZE_T "d\n", + count_alloc); + fprintf(stderr, "Dict reuse through freelist: %" PY_FORMAT_SIZE_T + "d\n", count_reuse); + fprintf(stderr, "%.2f%% reuse rate\n\n", + (100.0*count_reuse/(count_alloc+count_reuse))); } #endif @@ -189,12 +189,12 @@ static void show_track(void) { - fprintf(stderr, "Dicts created: %" PY_FORMAT_SIZE_T "d\n", - count_tracked + count_untracked); - fprintf(stderr, "Dicts tracked by the GC: %" PY_FORMAT_SIZE_T - "d\n", count_tracked); - fprintf(stderr, "%.2f%% dict tracking rate\n\n", - (100.0*count_tracked/(count_untracked+count_tracked))); + fprintf(stderr, "Dicts created: %" PY_FORMAT_SIZE_T "d\n", + count_tracked + count_untracked); + fprintf(stderr, "Dicts tracked by the GC: %" PY_FORMAT_SIZE_T + "d\n", count_tracked); + fprintf(stderr, "%.2f%% dict tracking rate\n\n", + (100.0*count_tracked/(count_untracked+count_tracked))); } #endif @@ -208,15 +208,15 @@ an excellent reason not to). */ -#define INIT_NONZERO_DICT_SLOTS(mp) do { \ - (mp)->ma_table = (mp)->ma_smalltable; \ - (mp)->ma_mask = PyDict_MINSIZE - 1; \ +#define INIT_NONZERO_DICT_SLOTS(mp) do { \ + (mp)->ma_table = (mp)->ma_smalltable; \ + (mp)->ma_mask = PyDict_MINSIZE - 1; \ } while(0) -#define EMPTY_TO_MINSIZE(mp) do { \ - memset((mp)->ma_smalltable, 0, sizeof((mp)->ma_smalltable)); \ - (mp)->ma_used = (mp)->ma_fill = 0; \ - INIT_NONZERO_DICT_SLOTS(mp); \ +#define EMPTY_TO_MINSIZE(mp) do { \ + memset((mp)->ma_smalltable, 0, sizeof((mp)->ma_smalltable)); \ + (mp)->ma_used = (mp)->ma_fill = 0; \ + INIT_NONZERO_DICT_SLOTS(mp); \ } while(0) /* Dictionary reuse scheme to save calls to malloc, free, and memset */ @@ -229,68 +229,68 @@ void PyDict_Fini(void) { - PyDictObject *op; + PyDictObject *op; - while (numfree) { - op = free_list[--numfree]; - assert(PyDict_CheckExact(op)); - PyObject_GC_Del(op); - } + while (numfree) { + op = free_list[--numfree]; + assert(PyDict_CheckExact(op)); + PyObject_GC_Del(op); + } } PyObject * PyDict_New(void) { - register PyDictObject *mp; - if (dummy == NULL) { /* Auto-initialize dummy */ - dummy = PyUnicode_FromString(""); - if (dummy == NULL) - return NULL; + register PyDictObject *mp; + if (dummy == NULL) { /* Auto-initialize dummy */ + dummy = PyUnicode_FromString(""); + if (dummy == NULL) + return NULL; #ifdef SHOW_CONVERSION_COUNTS - Py_AtExit(show_counts); + Py_AtExit(show_counts); #endif #ifdef SHOW_ALLOC_COUNT - Py_AtExit(show_alloc); + Py_AtExit(show_alloc); #endif #ifdef SHOW_TRACK_COUNT - Py_AtExit(show_track); + Py_AtExit(show_track); #endif - } - if (numfree) { - mp = free_list[--numfree]; - assert (mp != NULL); - assert (Py_TYPE(mp) == &PyDict_Type); - _Py_NewReference((PyObject *)mp); - if (mp->ma_fill) { - EMPTY_TO_MINSIZE(mp); - } else { - /* At least set ma_table and ma_mask; these are wrong - if an empty but presized dict is added to freelist */ - INIT_NONZERO_DICT_SLOTS(mp); - } - assert (mp->ma_used == 0); - assert (mp->ma_table == mp->ma_smalltable); - assert (mp->ma_mask == PyDict_MINSIZE - 1); + } + if (numfree) { + mp = free_list[--numfree]; + assert (mp != NULL); + assert (Py_TYPE(mp) == &PyDict_Type); + _Py_NewReference((PyObject *)mp); + if (mp->ma_fill) { + EMPTY_TO_MINSIZE(mp); + } else { + /* At least set ma_table and ma_mask; these are wrong + if an empty but presized dict is added to freelist */ + INIT_NONZERO_DICT_SLOTS(mp); + } + assert (mp->ma_used == 0); + assert (mp->ma_table == mp->ma_smalltable); + assert (mp->ma_mask == PyDict_MINSIZE - 1); #ifdef SHOW_ALLOC_COUNT - count_reuse++; + count_reuse++; #endif - } else { - mp = PyObject_GC_New(PyDictObject, &PyDict_Type); - if (mp == NULL) - return NULL; - EMPTY_TO_MINSIZE(mp); + } else { + mp = PyObject_GC_New(PyDictObject, &PyDict_Type); + if (mp == NULL) + return NULL; + EMPTY_TO_MINSIZE(mp); #ifdef SHOW_ALLOC_COUNT - count_alloc++; + count_alloc++; #endif - } - mp->ma_lookup = lookdict_unicode; + } + mp->ma_lookup = lookdict_unicode; #ifdef SHOW_TRACK_COUNT - count_untracked++; + count_untracked++; #endif #ifdef SHOW_CONVERSION_COUNTS - ++created; + ++created; #endif - return (PyObject *)mp; + return (PyObject *)mp; } /* @@ -320,80 +320,80 @@ static PyDictEntry * lookdict(PyDictObject *mp, PyObject *key, register long hash) { - register size_t i; - register size_t perturb; - register PyDictEntry *freeslot; - register size_t mask = (size_t)mp->ma_mask; - PyDictEntry *ep0 = mp->ma_table; - register PyDictEntry *ep; - register int cmp; - PyObject *startkey; - - i = (size_t)hash & mask; - ep = &ep0[i]; - if (ep->me_key == NULL || ep->me_key == key) - return ep; - - if (ep->me_key == dummy) - freeslot = ep; - else { - if (ep->me_hash == hash) { - startkey = ep->me_key; - Py_INCREF(startkey); - cmp = PyObject_RichCompareBool(startkey, key, Py_EQ); - Py_DECREF(startkey); - if (cmp < 0) - return NULL; - if (ep0 == mp->ma_table && ep->me_key == startkey) { - if (cmp > 0) - return ep; - } - else { - /* The compare did major nasty stuff to the - * dict: start over. - * XXX A clever adversary could prevent this - * XXX from terminating. - */ - return lookdict(mp, key, hash); - } - } - freeslot = NULL; - } - - /* In the loop, me_key == dummy is by far (factor of 100s) the - least likely outcome, so test for that last. */ - for (perturb = hash; ; perturb >>= PERTURB_SHIFT) { - i = (i << 2) + i + perturb + 1; - ep = &ep0[i & mask]; - if (ep->me_key == NULL) - return freeslot == NULL ? ep : freeslot; - if (ep->me_key == key) - return ep; - if (ep->me_hash == hash && ep->me_key != dummy) { - startkey = ep->me_key; - Py_INCREF(startkey); - cmp = PyObject_RichCompareBool(startkey, key, Py_EQ); - Py_DECREF(startkey); - if (cmp < 0) - return NULL; - if (ep0 == mp->ma_table && ep->me_key == startkey) { - if (cmp > 0) - return ep; - } - else { - /* The compare did major nasty stuff to the - * dict: start over. - * XXX A clever adversary could prevent this - * XXX from terminating. - */ - return lookdict(mp, key, hash); - } - } - else if (ep->me_key == dummy && freeslot == NULL) - freeslot = ep; - } - assert(0); /* NOT REACHED */ - return 0; + register size_t i; + register size_t perturb; + register PyDictEntry *freeslot; + register size_t mask = (size_t)mp->ma_mask; + PyDictEntry *ep0 = mp->ma_table; + register PyDictEntry *ep; + register int cmp; + PyObject *startkey; + + i = (size_t)hash & mask; + ep = &ep0[i]; + if (ep->me_key == NULL || ep->me_key == key) + return ep; + + if (ep->me_key == dummy) + freeslot = ep; + else { + if (ep->me_hash == hash) { + startkey = ep->me_key; + Py_INCREF(startkey); + cmp = PyObject_RichCompareBool(startkey, key, Py_EQ); + Py_DECREF(startkey); + if (cmp < 0) + return NULL; + if (ep0 == mp->ma_table && ep->me_key == startkey) { + if (cmp > 0) + return ep; + } + else { + /* The compare did major nasty stuff to the + * dict: start over. + * XXX A clever adversary could prevent this + * XXX from terminating. + */ + return lookdict(mp, key, hash); + } + } + freeslot = NULL; + } + + /* In the loop, me_key == dummy is by far (factor of 100s) the + least likely outcome, so test for that last. */ + for (perturb = hash; ; perturb >>= PERTURB_SHIFT) { + i = (i << 2) + i + perturb + 1; + ep = &ep0[i & mask]; + if (ep->me_key == NULL) + return freeslot == NULL ? ep : freeslot; + if (ep->me_key == key) + return ep; + if (ep->me_hash == hash && ep->me_key != dummy) { + startkey = ep->me_key; + Py_INCREF(startkey); + cmp = PyObject_RichCompareBool(startkey, key, Py_EQ); + Py_DECREF(startkey); + if (cmp < 0) + return NULL; + if (ep0 == mp->ma_table && ep->me_key == startkey) { + if (cmp > 0) + return ep; + } + else { + /* The compare did major nasty stuff to the + * dict: start over. + * XXX A clever adversary could prevent this + * XXX from terminating. + */ + return lookdict(mp, key, hash); + } + } + else if (ep->me_key == dummy && freeslot == NULL) + freeslot = ep; + } + assert(0); /* NOT REACHED */ + return 0; } /* @@ -409,114 +409,114 @@ static PyDictEntry * lookdict_unicode(PyDictObject *mp, PyObject *key, register long hash) { - register size_t i; - register size_t perturb; - register PyDictEntry *freeslot; - register size_t mask = (size_t)mp->ma_mask; - PyDictEntry *ep0 = mp->ma_table; - register PyDictEntry *ep; - - /* Make sure this function doesn't have to handle non-unicode keys, - including subclasses of str; e.g., one reason to subclass - unicodes is to override __eq__, and for speed we don't cater to - that here. */ - if (!PyUnicode_CheckExact(key)) { + register size_t i; + register size_t perturb; + register PyDictEntry *freeslot; + register size_t mask = (size_t)mp->ma_mask; + PyDictEntry *ep0 = mp->ma_table; + register PyDictEntry *ep; + + /* Make sure this function doesn't have to handle non-unicode keys, + including subclasses of str; e.g., one reason to subclass + unicodes is to override __eq__, and for speed we don't cater to + that here. */ + if (!PyUnicode_CheckExact(key)) { #ifdef SHOW_CONVERSION_COUNTS - ++converted; + ++converted; #endif - mp->ma_lookup = lookdict; - return lookdict(mp, key, hash); - } - i = hash & mask; - ep = &ep0[i]; - if (ep->me_key == NULL || ep->me_key == key) - return ep; - if (ep->me_key == dummy) - freeslot = ep; - else { - if (ep->me_hash == hash && unicode_eq(ep->me_key, key)) - return ep; - freeslot = NULL; - } - - /* In the loop, me_key == dummy is by far (factor of 100s) the - least likely outcome, so test for that last. */ - for (perturb = hash; ; perturb >>= PERTURB_SHIFT) { - i = (i << 2) + i + perturb + 1; - ep = &ep0[i & mask]; - if (ep->me_key == NULL) - return freeslot == NULL ? ep : freeslot; - if (ep->me_key == key - || (ep->me_hash == hash - && ep->me_key != dummy - && unicode_eq(ep->me_key, key))) - return ep; - if (ep->me_key == dummy && freeslot == NULL) - freeslot = ep; - } - assert(0); /* NOT REACHED */ - return 0; + mp->ma_lookup = lookdict; + return lookdict(mp, key, hash); + } + i = hash & mask; + ep = &ep0[i]; + if (ep->me_key == NULL || ep->me_key == key) + return ep; + if (ep->me_key == dummy) + freeslot = ep; + else { + if (ep->me_hash == hash && unicode_eq(ep->me_key, key)) + return ep; + freeslot = NULL; + } + + /* In the loop, me_key == dummy is by far (factor of 100s) the + least likely outcome, so test for that last. */ + for (perturb = hash; ; perturb >>= PERTURB_SHIFT) { + i = (i << 2) + i + perturb + 1; + ep = &ep0[i & mask]; + if (ep->me_key == NULL) + return freeslot == NULL ? ep : freeslot; + if (ep->me_key == key + || (ep->me_hash == hash + && ep->me_key != dummy + && unicode_eq(ep->me_key, key))) + return ep; + if (ep->me_key == dummy && freeslot == NULL) + freeslot = ep; + } + assert(0); /* NOT REACHED */ + return 0; } int _PyDict_HasOnlyStringKeys(PyObject *dict) { - Py_ssize_t pos = 0; - PyObject *key, *value; - assert(PyDict_CheckExact(dict)); - /* Shortcut */ - if (((PyDictObject *)dict)->ma_lookup == lookdict_unicode) - return 1; - while (PyDict_Next(dict, &pos, &key, &value)) - if (!PyUnicode_Check(key)) - return 0; - return 1; + Py_ssize_t pos = 0; + PyObject *key, *value; + assert(PyDict_CheckExact(dict)); + /* Shortcut */ + if (((PyDictObject *)dict)->ma_lookup == lookdict_unicode) + return 1; + while (PyDict_Next(dict, &pos, &key, &value)) + if (!PyUnicode_Check(key)) + return 0; + return 1; } #ifdef SHOW_TRACK_COUNT #define INCREASE_TRACK_COUNT \ - (count_tracked++, count_untracked--); + (count_tracked++, count_untracked--); #define DECREASE_TRACK_COUNT \ - (count_tracked--, count_untracked++); + (count_tracked--, count_untracked++); #else #define INCREASE_TRACK_COUNT #define DECREASE_TRACK_COUNT #endif #define MAINTAIN_TRACKING(mp, key, value) \ - do { \ - if (!_PyObject_GC_IS_TRACKED(mp)) { \ - if (_PyObject_GC_MAY_BE_TRACKED(key) || \ - _PyObject_GC_MAY_BE_TRACKED(value)) { \ - _PyObject_GC_TRACK(mp); \ - INCREASE_TRACK_COUNT \ - } \ - } \ - } while(0) + do { \ + if (!_PyObject_GC_IS_TRACKED(mp)) { \ + if (_PyObject_GC_MAY_BE_TRACKED(key) || \ + _PyObject_GC_MAY_BE_TRACKED(value)) { \ + _PyObject_GC_TRACK(mp); \ + INCREASE_TRACK_COUNT \ + } \ + } \ + } while(0) void _PyDict_MaybeUntrack(PyObject *op) { - PyDictObject *mp; - PyObject *value; - Py_ssize_t mask, i; - PyDictEntry *ep; - - if (!PyDict_CheckExact(op) || !_PyObject_GC_IS_TRACKED(op)) - return; - - mp = (PyDictObject *) op; - ep = mp->ma_table; - mask = mp->ma_mask; - for (i = 0; i <= mask; i++) { - if ((value = ep[i].me_value) == NULL) - continue; - if (_PyObject_GC_MAY_BE_TRACKED(value) || - _PyObject_GC_MAY_BE_TRACKED(ep[i].me_key)) - return; - } - DECREASE_TRACK_COUNT - _PyObject_GC_UNTRACK(op); + PyDictObject *mp; + PyObject *value; + Py_ssize_t mask, i; + PyDictEntry *ep; + + if (!PyDict_CheckExact(op) || !_PyObject_GC_IS_TRACKED(op)) + return; + + mp = (PyDictObject *) op; + ep = mp->ma_table; + mask = mp->ma_mask; + for (i = 0; i <= mask; i++) { + if ((value = ep[i].me_value) == NULL) + continue; + if (_PyObject_GC_MAY_BE_TRACKED(value) || + _PyObject_GC_MAY_BE_TRACKED(ep[i].me_key)) + return; + } + DECREASE_TRACK_COUNT + _PyObject_GC_UNTRACK(op); } @@ -529,37 +529,37 @@ static int insertdict(register PyDictObject *mp, PyObject *key, long hash, PyObject *value) { - PyObject *old_value; - register PyDictEntry *ep; - typedef PyDictEntry *(*lookupfunc)(PyDictObject *, PyObject *, long); - - assert(mp->ma_lookup != NULL); - ep = mp->ma_lookup(mp, key, hash); - if (ep == NULL) { - Py_DECREF(key); - Py_DECREF(value); - return -1; - } - MAINTAIN_TRACKING(mp, key, value); - if (ep->me_value != NULL) { - old_value = ep->me_value; - ep->me_value = value; - Py_DECREF(old_value); /* which **CAN** re-enter */ - Py_DECREF(key); - } - else { - if (ep->me_key == NULL) - mp->ma_fill++; - else { - assert(ep->me_key == dummy); - Py_DECREF(dummy); - } - ep->me_key = key; - ep->me_hash = (Py_ssize_t)hash; - ep->me_value = value; - mp->ma_used++; - } - return 0; + PyObject *old_value; + register PyDictEntry *ep; + typedef PyDictEntry *(*lookupfunc)(PyDictObject *, PyObject *, long); + + assert(mp->ma_lookup != NULL); + ep = mp->ma_lookup(mp, key, hash); + if (ep == NULL) { + Py_DECREF(key); + Py_DECREF(value); + return -1; + } + MAINTAIN_TRACKING(mp, key, value); + if (ep->me_value != NULL) { + old_value = ep->me_value; + ep->me_value = value; + Py_DECREF(old_value); /* which **CAN** re-enter */ + Py_DECREF(key); + } + else { + if (ep->me_key == NULL) + mp->ma_fill++; + else { + assert(ep->me_key == dummy); + Py_DECREF(dummy); + } + ep->me_key = key; + ep->me_hash = (Py_ssize_t)hash; + ep->me_value = value; + mp->ma_used++; + } + return 0; } /* @@ -572,27 +572,27 @@ */ static void insertdict_clean(register PyDictObject *mp, PyObject *key, long hash, - PyObject *value) + PyObject *value) { - register size_t i; - register size_t perturb; - register size_t mask = (size_t)mp->ma_mask; - PyDictEntry *ep0 = mp->ma_table; - register PyDictEntry *ep; - - MAINTAIN_TRACKING(mp, key, value); - i = hash & mask; - ep = &ep0[i]; - for (perturb = hash; ep->me_key != NULL; perturb >>= PERTURB_SHIFT) { - i = (i << 2) + i + perturb + 1; - ep = &ep0[i & mask]; - } - assert(ep->me_value == NULL); - mp->ma_fill++; - ep->me_key = key; - ep->me_hash = (Py_ssize_t)hash; - ep->me_value = value; - mp->ma_used++; + register size_t i; + register size_t perturb; + register size_t mask = (size_t)mp->ma_mask; + PyDictEntry *ep0 = mp->ma_table; + register PyDictEntry *ep; + + MAINTAIN_TRACKING(mp, key, value); + i = hash & mask; + ep = &ep0[i]; + for (perturb = hash; ep->me_key != NULL; perturb >>= PERTURB_SHIFT) { + i = (i << 2) + i + perturb + 1; + ep = &ep0[i & mask]; + } + assert(ep->me_value == NULL); + mp->ma_fill++; + ep->me_key = key; + ep->me_hash = (Py_ssize_t)hash; + ep->me_value = value; + mp->ma_used++; } /* @@ -603,84 +603,84 @@ static int dictresize(PyDictObject *mp, Py_ssize_t minused) { - Py_ssize_t newsize; - PyDictEntry *oldtable, *newtable, *ep; - Py_ssize_t i; - int is_oldtable_malloced; - PyDictEntry small_copy[PyDict_MINSIZE]; - - assert(minused >= 0); - - /* Find the smallest table size > minused. */ - for (newsize = PyDict_MINSIZE; - newsize <= minused && newsize > 0; - newsize <<= 1) - ; - if (newsize <= 0) { - PyErr_NoMemory(); - return -1; - } - - /* Get space for a new table. */ - oldtable = mp->ma_table; - assert(oldtable != NULL); - is_oldtable_malloced = oldtable != mp->ma_smalltable; - - if (newsize == PyDict_MINSIZE) { - /* A large table is shrinking, or we can't get any smaller. */ - newtable = mp->ma_smalltable; - if (newtable == oldtable) { - if (mp->ma_fill == mp->ma_used) { - /* No dummies, so no point doing anything. */ - return 0; - } - /* We're not going to resize it, but rebuild the - table anyway to purge old dummy entries. - Subtle: This is *necessary* if fill==size, - as lookdict needs at least one virgin slot to - terminate failing searches. If fill < size, it's - merely desirable, as dummies slow searches. */ - assert(mp->ma_fill > mp->ma_used); - memcpy(small_copy, oldtable, sizeof(small_copy)); - oldtable = small_copy; - } - } - else { - newtable = PyMem_NEW(PyDictEntry, newsize); - if (newtable == NULL) { - PyErr_NoMemory(); - return -1; - } - } - - /* Make the dict empty, using the new table. */ - assert(newtable != oldtable); - mp->ma_table = newtable; - mp->ma_mask = newsize - 1; - memset(newtable, 0, sizeof(PyDictEntry) * newsize); - mp->ma_used = 0; - i = mp->ma_fill; - mp->ma_fill = 0; - - /* Copy the data over; this is refcount-neutral for active entries; - dummy entries aren't copied over, of course */ - for (ep = oldtable; i > 0; ep++) { - if (ep->me_value != NULL) { /* active entry */ - --i; - insertdict_clean(mp, ep->me_key, (long)ep->me_hash, - ep->me_value); - } - else if (ep->me_key != NULL) { /* dummy entry */ - --i; - assert(ep->me_key == dummy); - Py_DECREF(ep->me_key); - } - /* else key == value == NULL: nothing to do */ - } - - if (is_oldtable_malloced) - PyMem_DEL(oldtable); - return 0; + Py_ssize_t newsize; + PyDictEntry *oldtable, *newtable, *ep; + Py_ssize_t i; + int is_oldtable_malloced; + PyDictEntry small_copy[PyDict_MINSIZE]; + + assert(minused >= 0); + + /* Find the smallest table size > minused. */ + for (newsize = PyDict_MINSIZE; + newsize <= minused && newsize > 0; + newsize <<= 1) + ; + if (newsize <= 0) { + PyErr_NoMemory(); + return -1; + } + + /* Get space for a new table. */ + oldtable = mp->ma_table; + assert(oldtable != NULL); + is_oldtable_malloced = oldtable != mp->ma_smalltable; + + if (newsize == PyDict_MINSIZE) { + /* A large table is shrinking, or we can't get any smaller. */ + newtable = mp->ma_smalltable; + if (newtable == oldtable) { + if (mp->ma_fill == mp->ma_used) { + /* No dummies, so no point doing anything. */ + return 0; + } + /* We're not going to resize it, but rebuild the + table anyway to purge old dummy entries. + Subtle: This is *necessary* if fill==size, + as lookdict needs at least one virgin slot to + terminate failing searches. If fill < size, it's + merely desirable, as dummies slow searches. */ + assert(mp->ma_fill > mp->ma_used); + memcpy(small_copy, oldtable, sizeof(small_copy)); + oldtable = small_copy; + } + } + else { + newtable = PyMem_NEW(PyDictEntry, newsize); + if (newtable == NULL) { + PyErr_NoMemory(); + return -1; + } + } + + /* Make the dict empty, using the new table. */ + assert(newtable != oldtable); + mp->ma_table = newtable; + mp->ma_mask = newsize - 1; + memset(newtable, 0, sizeof(PyDictEntry) * newsize); + mp->ma_used = 0; + i = mp->ma_fill; + mp->ma_fill = 0; + + /* Copy the data over; this is refcount-neutral for active entries; + dummy entries aren't copied over, of course */ + for (ep = oldtable; i > 0; ep++) { + if (ep->me_value != NULL) { /* active entry */ + --i; + insertdict_clean(mp, ep->me_key, (long)ep->me_hash, + ep->me_value); + } + else if (ep->me_key != NULL) { /* dummy entry */ + --i; + assert(ep->me_key == dummy); + Py_DECREF(ep->me_key); + } + /* else key == value == NULL: nothing to do */ + } + + if (is_oldtable_malloced) + PyMem_DEL(oldtable); + return 0; } /* Create a new dictionary pre-sized to hold an estimated number of elements. @@ -691,13 +691,13 @@ PyObject * _PyDict_NewPresized(Py_ssize_t minused) { - PyObject *op = PyDict_New(); + PyObject *op = PyDict_New(); - if (minused>5 && op != NULL && dictresize((PyDictObject *)op, minused) == -1) { - Py_DECREF(op); - return NULL; - } - return op; + if (minused>5 && op != NULL && dictresize((PyDictObject *)op, minused) == -1) { + Py_DECREF(op); + return NULL; + } + return op; } /* Note that, for historical reasons, PyDict_GetItem() suppresses all errors @@ -713,47 +713,47 @@ PyObject * PyDict_GetItem(PyObject *op, PyObject *key) { - long hash; - PyDictObject *mp = (PyDictObject *)op; - PyDictEntry *ep; - PyThreadState *tstate; - if (!PyDict_Check(op)) - return NULL; - if (!PyUnicode_CheckExact(key) || - (hash = ((PyUnicodeObject *) key)->hash) == -1) - { - hash = PyObject_Hash(key); - if (hash == -1) { - PyErr_Clear(); - return NULL; - } - } - - /* We can arrive here with a NULL tstate during initialization: try - running "python -Wi" for an example related to string interning. - Let's just hope that no exception occurs then... This must be - _PyThreadState_Current and not PyThreadState_GET() because in debug - mode, the latter complains if tstate is NULL. */ - tstate = (PyThreadState*)_Py_atomic_load_relaxed( - &_PyThreadState_Current); - if (tstate != NULL && tstate->curexc_type != NULL) { - /* preserve the existing exception */ - PyObject *err_type, *err_value, *err_tb; - PyErr_Fetch(&err_type, &err_value, &err_tb); - ep = (mp->ma_lookup)(mp, key, hash); - /* ignore errors */ - PyErr_Restore(err_type, err_value, err_tb); - if (ep == NULL) - return NULL; - } - else { - ep = (mp->ma_lookup)(mp, key, hash); - if (ep == NULL) { - PyErr_Clear(); - return NULL; - } - } - return ep->me_value; + long hash; + PyDictObject *mp = (PyDictObject *)op; + PyDictEntry *ep; + PyThreadState *tstate; + if (!PyDict_Check(op)) + return NULL; + if (!PyUnicode_CheckExact(key) || + (hash = ((PyUnicodeObject *) key)->hash) == -1) + { + hash = PyObject_Hash(key); + if (hash == -1) { + PyErr_Clear(); + return NULL; + } + } + + /* We can arrive here with a NULL tstate during initialization: try + running "python -Wi" for an example related to string interning. + Let's just hope that no exception occurs then... This must be + _PyThreadState_Current and not PyThreadState_GET() because in debug + mode, the latter complains if tstate is NULL. */ + tstate = (PyThreadState*)_Py_atomic_load_relaxed( + &_PyThreadState_Current); + if (tstate != NULL && tstate->curexc_type != NULL) { + /* preserve the existing exception */ + PyObject *err_type, *err_value, *err_tb; + PyErr_Fetch(&err_type, &err_value, &err_tb); + ep = (mp->ma_lookup)(mp, key, hash); + /* ignore errors */ + PyErr_Restore(err_type, err_value, err_tb); + if (ep == NULL) + return NULL; + } + else { + ep = (mp->ma_lookup)(mp, key, hash); + if (ep == NULL) { + PyErr_Clear(); + return NULL; + } + } + return ep->me_value; } /* Variant of PyDict_GetItem() that doesn't suppress exceptions. @@ -763,27 +763,27 @@ PyObject * PyDict_GetItemWithError(PyObject *op, PyObject *key) { - long hash; - PyDictObject*mp = (PyDictObject *)op; - PyDictEntry *ep; - - if (!PyDict_Check(op)) { - PyErr_BadInternalCall(); - return NULL; - } - if (!PyUnicode_CheckExact(key) || - (hash = ((PyUnicodeObject *) key)->hash) == -1) - { - hash = PyObject_Hash(key); - if (hash == -1) { - return NULL; - } - } - - ep = (mp->ma_lookup)(mp, key, hash); - if (ep == NULL) - return NULL; - return ep->me_value; + long hash; + PyDictObject*mp = (PyDictObject *)op; + PyDictEntry *ep; + + if (!PyDict_Check(op)) { + PyErr_BadInternalCall(); + return NULL; + } + if (!PyUnicode_CheckExact(key) || + (hash = ((PyUnicodeObject *) key)->hash) == -1) + { + hash = PyObject_Hash(key); + if (hash == -1) { + return NULL; + } + } + + ep = (mp->ma_lookup)(mp, key, hash); + if (ep == NULL) + return NULL; + return ep->me_value; } /* CAUTION: PyDict_SetItem() must guarantee that it won't resize the @@ -795,154 +795,154 @@ int PyDict_SetItem(register PyObject *op, PyObject *key, PyObject *value) { - register PyDictObject *mp; - register long hash; - register Py_ssize_t n_used; - - if (!PyDict_Check(op)) { - PyErr_BadInternalCall(); - return -1; - } - assert(key); - assert(value); - mp = (PyDictObject *)op; - if (!PyUnicode_CheckExact(key) || - (hash = ((PyUnicodeObject *) key)->hash) == -1) - { - hash = PyObject_Hash(key); - if (hash == -1) - return -1; - } - assert(mp->ma_fill <= mp->ma_mask); /* at least one empty slot */ - n_used = mp->ma_used; - Py_INCREF(value); - Py_INCREF(key); - if (insertdict(mp, key, hash, value) != 0) - return -1; - /* If we added a key, we can safely resize. Otherwise just return! - * If fill >= 2/3 size, adjust size. Normally, this doubles or - * quaduples the size, but it's also possible for the dict to shrink - * (if ma_fill is much larger than ma_used, meaning a lot of dict - * keys have been * deleted). - * - * Quadrupling the size improves average dictionary sparseness - * (reducing collisions) at the cost of some memory and iteration - * speed (which loops over every possible entry). It also halves - * the number of expensive resize operations in a growing dictionary. - * - * Very large dictionaries (over 50K items) use doubling instead. - * This may help applications with severe memory constraints. - */ - if (!(mp->ma_used > n_used && mp->ma_fill*3 >= (mp->ma_mask+1)*2)) - return 0; - return dictresize(mp, (mp->ma_used > 50000 ? 2 : 4) * mp->ma_used); + register PyDictObject *mp; + register long hash; + register Py_ssize_t n_used; + + if (!PyDict_Check(op)) { + PyErr_BadInternalCall(); + return -1; + } + assert(key); + assert(value); + mp = (PyDictObject *)op; + if (!PyUnicode_CheckExact(key) || + (hash = ((PyUnicodeObject *) key)->hash) == -1) + { + hash = PyObject_Hash(key); + if (hash == -1) + return -1; + } + assert(mp->ma_fill <= mp->ma_mask); /* at least one empty slot */ + n_used = mp->ma_used; + Py_INCREF(value); + Py_INCREF(key); + if (insertdict(mp, key, hash, value) != 0) + return -1; + /* If we added a key, we can safely resize. Otherwise just return! + * If fill >= 2/3 size, adjust size. Normally, this doubles or + * quaduples the size, but it's also possible for the dict to shrink + * (if ma_fill is much larger than ma_used, meaning a lot of dict + * keys have been * deleted). + * + * Quadrupling the size improves average dictionary sparseness + * (reducing collisions) at the cost of some memory and iteration + * speed (which loops over every possible entry). It also halves + * the number of expensive resize operations in a growing dictionary. + * + * Very large dictionaries (over 50K items) use doubling instead. + * This may help applications with severe memory constraints. + */ + if (!(mp->ma_used > n_used && mp->ma_fill*3 >= (mp->ma_mask+1)*2)) + return 0; + return dictresize(mp, (mp->ma_used > 50000 ? 2 : 4) * mp->ma_used); } int PyDict_DelItem(PyObject *op, PyObject *key) { - register PyDictObject *mp; - register long hash; - register PyDictEntry *ep; - PyObject *old_value, *old_key; - - if (!PyDict_Check(op)) { - PyErr_BadInternalCall(); - return -1; - } - assert(key); - if (!PyUnicode_CheckExact(key) || - (hash = ((PyUnicodeObject *) key)->hash) == -1) { - hash = PyObject_Hash(key); - if (hash == -1) - return -1; - } - mp = (PyDictObject *)op; - ep = (mp->ma_lookup)(mp, key, hash); - if (ep == NULL) - return -1; - if (ep->me_value == NULL) { - set_key_error(key); - return -1; - } - old_key = ep->me_key; - Py_INCREF(dummy); - ep->me_key = dummy; - old_value = ep->me_value; - ep->me_value = NULL; - mp->ma_used--; - Py_DECREF(old_value); - Py_DECREF(old_key); - return 0; + register PyDictObject *mp; + register long hash; + register PyDictEntry *ep; + PyObject *old_value, *old_key; + + if (!PyDict_Check(op)) { + PyErr_BadInternalCall(); + return -1; + } + assert(key); + if (!PyUnicode_CheckExact(key) || + (hash = ((PyUnicodeObject *) key)->hash) == -1) { + hash = PyObject_Hash(key); + if (hash == -1) + return -1; + } + mp = (PyDictObject *)op; + ep = (mp->ma_lookup)(mp, key, hash); + if (ep == NULL) + return -1; + if (ep->me_value == NULL) { + set_key_error(key); + return -1; + } + old_key = ep->me_key; + Py_INCREF(dummy); + ep->me_key = dummy; + old_value = ep->me_value; + ep->me_value = NULL; + mp->ma_used--; + Py_DECREF(old_value); + Py_DECREF(old_key); + return 0; } void PyDict_Clear(PyObject *op) { - PyDictObject *mp; - PyDictEntry *ep, *table; - int table_is_malloced; - Py_ssize_t fill; - PyDictEntry small_copy[PyDict_MINSIZE]; + PyDictObject *mp; + PyDictEntry *ep, *table; + int table_is_malloced; + Py_ssize_t fill; + PyDictEntry small_copy[PyDict_MINSIZE]; #ifdef Py_DEBUG - Py_ssize_t i, n; + Py_ssize_t i, n; #endif - if (!PyDict_Check(op)) - return; - mp = (PyDictObject *)op; + if (!PyDict_Check(op)) + return; + mp = (PyDictObject *)op; #ifdef Py_DEBUG - n = mp->ma_mask + 1; - i = 0; + n = mp->ma_mask + 1; + i = 0; #endif - table = mp->ma_table; - assert(table != NULL); - table_is_malloced = table != mp->ma_smalltable; - - /* This is delicate. During the process of clearing the dict, - * decrefs can cause the dict to mutate. To avoid fatal confusion - * (voice of experience), we have to make the dict empty before - * clearing the slots, and never refer to anything via mp->xxx while - * clearing. - */ - fill = mp->ma_fill; - if (table_is_malloced) - EMPTY_TO_MINSIZE(mp); - - else if (fill > 0) { - /* It's a small table with something that needs to be cleared. - * Afraid the only safe way is to copy the dict entries into - * another small table first. - */ - memcpy(small_copy, table, sizeof(small_copy)); - table = small_copy; - EMPTY_TO_MINSIZE(mp); - } - /* else it's a small table that's already empty */ - - /* Now we can finally clear things. If C had refcounts, we could - * assert that the refcount on table is 1 now, i.e. that this function - * has unique access to it, so decref side-effects can't alter it. - */ - for (ep = table; fill > 0; ++ep) { + table = mp->ma_table; + assert(table != NULL); + table_is_malloced = table != mp->ma_smalltable; + + /* This is delicate. During the process of clearing the dict, + * decrefs can cause the dict to mutate. To avoid fatal confusion + * (voice of experience), we have to make the dict empty before + * clearing the slots, and never refer to anything via mp->xxx while + * clearing. + */ + fill = mp->ma_fill; + if (table_is_malloced) + EMPTY_TO_MINSIZE(mp); + + else if (fill > 0) { + /* It's a small table with something that needs to be cleared. + * Afraid the only safe way is to copy the dict entries into + * another small table first. + */ + memcpy(small_copy, table, sizeof(small_copy)); + table = small_copy; + EMPTY_TO_MINSIZE(mp); + } + /* else it's a small table that's already empty */ + + /* Now we can finally clear things. If C had refcounts, we could + * assert that the refcount on table is 1 now, i.e. that this function + * has unique access to it, so decref side-effects can't alter it. + */ + for (ep = table; fill > 0; ++ep) { #ifdef Py_DEBUG - assert(i < n); - ++i; + assert(i < n); + ++i; #endif - if (ep->me_key) { - --fill; - Py_DECREF(ep->me_key); - Py_XDECREF(ep->me_value); - } + if (ep->me_key) { + --fill; + Py_DECREF(ep->me_key); + Py_XDECREF(ep->me_value); + } #ifdef Py_DEBUG - else - assert(ep->me_value == NULL); + else + assert(ep->me_value == NULL); #endif - } + } - if (table_is_malloced) - PyMem_DEL(table); + if (table_is_malloced) + PyMem_DEL(table); } /* @@ -963,55 +963,55 @@ int PyDict_Next(PyObject *op, Py_ssize_t *ppos, PyObject **pkey, PyObject **pvalue) { - register Py_ssize_t i; - register Py_ssize_t mask; - register PyDictEntry *ep; - - if (!PyDict_Check(op)) - return 0; - i = *ppos; - if (i < 0) - return 0; - ep = ((PyDictObject *)op)->ma_table; - mask = ((PyDictObject *)op)->ma_mask; - while (i <= mask && ep[i].me_value == NULL) - i++; - *ppos = i+1; - if (i > mask) - return 0; - if (pkey) - *pkey = ep[i].me_key; - if (pvalue) - *pvalue = ep[i].me_value; - return 1; + register Py_ssize_t i; + register Py_ssize_t mask; + register PyDictEntry *ep; + + if (!PyDict_Check(op)) + return 0; + i = *ppos; + if (i < 0) + return 0; + ep = ((PyDictObject *)op)->ma_table; + mask = ((PyDictObject *)op)->ma_mask; + while (i <= mask && ep[i].me_value == NULL) + i++; + *ppos = i+1; + if (i > mask) + return 0; + if (pkey) + *pkey = ep[i].me_key; + if (pvalue) + *pvalue = ep[i].me_value; + return 1; } /* Internal version of PyDict_Next that returns a hash value in addition to the key and value.*/ int _PyDict_Next(PyObject *op, Py_ssize_t *ppos, PyObject **pkey, PyObject **pvalue, long *phash) { - register Py_ssize_t i; - register Py_ssize_t mask; - register PyDictEntry *ep; - - if (!PyDict_Check(op)) - return 0; - i = *ppos; - if (i < 0) - return 0; - ep = ((PyDictObject *)op)->ma_table; - mask = ((PyDictObject *)op)->ma_mask; - while (i <= mask && ep[i].me_value == NULL) - i++; - *ppos = i+1; - if (i > mask) - return 0; - *phash = (long)(ep[i].me_hash); - if (pkey) - *pkey = ep[i].me_key; - if (pvalue) - *pvalue = ep[i].me_value; - return 1; + register Py_ssize_t i; + register Py_ssize_t mask; + register PyDictEntry *ep; + + if (!PyDict_Check(op)) + return 0; + i = *ppos; + if (i < 0) + return 0; + ep = ((PyDictObject *)op)->ma_table; + mask = ((PyDictObject *)op)->ma_mask; + while (i <= mask && ep[i].me_value == NULL) + i++; + *ppos = i+1; + if (i > mask) + return 0; + *phash = (long)(ep[i].me_hash); + if (pkey) + *pkey = ep[i].me_key; + if (pvalue) + *pvalue = ep[i].me_value; + return 1; } /* Methods */ @@ -1019,404 +1019,404 @@ static void dict_dealloc(register PyDictObject *mp) { - register PyDictEntry *ep; - Py_ssize_t fill = mp->ma_fill; - PyObject_GC_UnTrack(mp); - Py_TRASHCAN_SAFE_BEGIN(mp) - for (ep = mp->ma_table; fill > 0; ep++) { - if (ep->me_key) { - --fill; - Py_DECREF(ep->me_key); - Py_XDECREF(ep->me_value); - } - } - if (mp->ma_table != mp->ma_smalltable) - PyMem_DEL(mp->ma_table); - if (numfree < PyDict_MAXFREELIST && Py_TYPE(mp) == &PyDict_Type) - free_list[numfree++] = mp; - else - Py_TYPE(mp)->tp_free((PyObject *)mp); - Py_TRASHCAN_SAFE_END(mp) + register PyDictEntry *ep; + Py_ssize_t fill = mp->ma_fill; + PyObject_GC_UnTrack(mp); + Py_TRASHCAN_SAFE_BEGIN(mp) + for (ep = mp->ma_table; fill > 0; ep++) { + if (ep->me_key) { + --fill; + Py_DECREF(ep->me_key); + Py_XDECREF(ep->me_value); + } + } + if (mp->ma_table != mp->ma_smalltable) + PyMem_DEL(mp->ma_table); + if (numfree < PyDict_MAXFREELIST && Py_TYPE(mp) == &PyDict_Type) + free_list[numfree++] = mp; + else + Py_TYPE(mp)->tp_free((PyObject *)mp); + Py_TRASHCAN_SAFE_END(mp) } static PyObject * dict_repr(PyDictObject *mp) { - Py_ssize_t i; - PyObject *s, *temp, *colon = NULL; - PyObject *pieces = NULL, *result = NULL; - PyObject *key, *value; - - i = Py_ReprEnter((PyObject *)mp); - if (i != 0) { - return i > 0 ? PyUnicode_FromString("{...}") : NULL; - } - - if (mp->ma_used == 0) { - result = PyUnicode_FromString("{}"); - goto Done; - } - - pieces = PyList_New(0); - if (pieces == NULL) - goto Done; - - colon = PyUnicode_FromString(": "); - if (colon == NULL) - goto Done; - - /* Do repr() on each key+value pair, and insert ": " between them. - Note that repr may mutate the dict. */ - i = 0; - while (PyDict_Next((PyObject *)mp, &i, &key, &value)) { - int status; - /* Prevent repr from deleting value during key format. */ - Py_INCREF(value); - s = PyObject_Repr(key); - PyUnicode_Append(&s, colon); - PyUnicode_AppendAndDel(&s, PyObject_Repr(value)); - Py_DECREF(value); - if (s == NULL) - goto Done; - status = PyList_Append(pieces, s); - Py_DECREF(s); /* append created a new ref */ - if (status < 0) - goto Done; - } - - /* Add "{}" decorations to the first and last items. */ - assert(PyList_GET_SIZE(pieces) > 0); - s = PyUnicode_FromString("{"); - if (s == NULL) - goto Done; - temp = PyList_GET_ITEM(pieces, 0); - PyUnicode_AppendAndDel(&s, temp); - PyList_SET_ITEM(pieces, 0, s); - if (s == NULL) - goto Done; - - s = PyUnicode_FromString("}"); - if (s == NULL) - goto Done; - temp = PyList_GET_ITEM(pieces, PyList_GET_SIZE(pieces) - 1); - PyUnicode_AppendAndDel(&temp, s); - PyList_SET_ITEM(pieces, PyList_GET_SIZE(pieces) - 1, temp); - if (temp == NULL) - goto Done; - - /* Paste them all together with ", " between. */ - s = PyUnicode_FromString(", "); - if (s == NULL) - goto Done; - result = PyUnicode_Join(s, pieces); - Py_DECREF(s); + Py_ssize_t i; + PyObject *s, *temp, *colon = NULL; + PyObject *pieces = NULL, *result = NULL; + PyObject *key, *value; + + i = Py_ReprEnter((PyObject *)mp); + if (i != 0) { + return i > 0 ? PyUnicode_FromString("{...}") : NULL; + } + + if (mp->ma_used == 0) { + result = PyUnicode_FromString("{}"); + goto Done; + } + + pieces = PyList_New(0); + if (pieces == NULL) + goto Done; + + colon = PyUnicode_FromString(": "); + if (colon == NULL) + goto Done; + + /* Do repr() on each key+value pair, and insert ": " between them. + Note that repr may mutate the dict. */ + i = 0; + while (PyDict_Next((PyObject *)mp, &i, &key, &value)) { + int status; + /* Prevent repr from deleting value during key format. */ + Py_INCREF(value); + s = PyObject_Repr(key); + PyUnicode_Append(&s, colon); + PyUnicode_AppendAndDel(&s, PyObject_Repr(value)); + Py_DECREF(value); + if (s == NULL) + goto Done; + status = PyList_Append(pieces, s); + Py_DECREF(s); /* append created a new ref */ + if (status < 0) + goto Done; + } + + /* Add "{}" decorations to the first and last items. */ + assert(PyList_GET_SIZE(pieces) > 0); + s = PyUnicode_FromString("{"); + if (s == NULL) + goto Done; + temp = PyList_GET_ITEM(pieces, 0); + PyUnicode_AppendAndDel(&s, temp); + PyList_SET_ITEM(pieces, 0, s); + if (s == NULL) + goto Done; + + s = PyUnicode_FromString("}"); + if (s == NULL) + goto Done; + temp = PyList_GET_ITEM(pieces, PyList_GET_SIZE(pieces) - 1); + PyUnicode_AppendAndDel(&temp, s); + PyList_SET_ITEM(pieces, PyList_GET_SIZE(pieces) - 1, temp); + if (temp == NULL) + goto Done; + + /* Paste them all together with ", " between. */ + s = PyUnicode_FromString(", "); + if (s == NULL) + goto Done; + result = PyUnicode_Join(s, pieces); + Py_DECREF(s); Done: - Py_XDECREF(pieces); - Py_XDECREF(colon); - Py_ReprLeave((PyObject *)mp); - return result; + Py_XDECREF(pieces); + Py_XDECREF(colon); + Py_ReprLeave((PyObject *)mp); + return result; } static Py_ssize_t dict_length(PyDictObject *mp) { - return mp->ma_used; + return mp->ma_used; } static PyObject * dict_subscript(PyDictObject *mp, register PyObject *key) { - PyObject *v; - long hash; - PyDictEntry *ep; - assert(mp->ma_table != NULL); - if (!PyUnicode_CheckExact(key) || - (hash = ((PyUnicodeObject *) key)->hash) == -1) { - hash = PyObject_Hash(key); - if (hash == -1) - return NULL; - } - ep = (mp->ma_lookup)(mp, key, hash); - if (ep == NULL) - return NULL; - v = ep->me_value; - if (v == NULL) { - if (!PyDict_CheckExact(mp)) { - /* Look up __missing__ method if we're a subclass. */ - PyObject *missing, *res; - static PyObject *missing_str = NULL; - missing = _PyObject_LookupSpecial((PyObject *)mp, - "__missing__", - &missing_str); - if (missing != NULL) { - res = PyObject_CallFunctionObjArgs(missing, - key, NULL); - Py_DECREF(missing); - return res; - } - else if (PyErr_Occurred()) - return NULL; - } - set_key_error(key); - return NULL; - } - else - Py_INCREF(v); - return v; + PyObject *v; + long hash; + PyDictEntry *ep; + assert(mp->ma_table != NULL); + if (!PyUnicode_CheckExact(key) || + (hash = ((PyUnicodeObject *) key)->hash) == -1) { + hash = PyObject_Hash(key); + if (hash == -1) + return NULL; + } + ep = (mp->ma_lookup)(mp, key, hash); + if (ep == NULL) + return NULL; + v = ep->me_value; + if (v == NULL) { + if (!PyDict_CheckExact(mp)) { + /* Look up __missing__ method if we're a subclass. */ + PyObject *missing, *res; + static PyObject *missing_str = NULL; + missing = _PyObject_LookupSpecial((PyObject *)mp, + "__missing__", + &missing_str); + if (missing != NULL) { + res = PyObject_CallFunctionObjArgs(missing, + key, NULL); + Py_DECREF(missing); + return res; + } + else if (PyErr_Occurred()) + return NULL; + } + set_key_error(key); + return NULL; + } + else + Py_INCREF(v); + return v; } static int dict_ass_sub(PyDictObject *mp, PyObject *v, PyObject *w) { - if (w == NULL) - return PyDict_DelItem((PyObject *)mp, v); - else - return PyDict_SetItem((PyObject *)mp, v, w); + if (w == NULL) + return PyDict_DelItem((PyObject *)mp, v); + else + return PyDict_SetItem((PyObject *)mp, v, w); } static PyMappingMethods dict_as_mapping = { - (lenfunc)dict_length, /*mp_length*/ - (binaryfunc)dict_subscript, /*mp_subscript*/ - (objobjargproc)dict_ass_sub, /*mp_ass_subscript*/ + (lenfunc)dict_length, /*mp_length*/ + (binaryfunc)dict_subscript, /*mp_subscript*/ + (objobjargproc)dict_ass_sub, /*mp_ass_subscript*/ }; static PyObject * dict_keys(register PyDictObject *mp) { - register PyObject *v; - register Py_ssize_t i, j; - PyDictEntry *ep; - Py_ssize_t mask, n; + register PyObject *v; + register Py_ssize_t i, j; + PyDictEntry *ep; + Py_ssize_t mask, n; again: - n = mp->ma_used; - v = PyList_New(n); - if (v == NULL) - return NULL; - if (n != mp->ma_used) { - /* Durnit. The allocations caused the dict to resize. - * Just start over, this shouldn't normally happen. - */ - Py_DECREF(v); - goto again; - } - ep = mp->ma_table; - mask = mp->ma_mask; - for (i = 0, j = 0; i <= mask; i++) { - if (ep[i].me_value != NULL) { - PyObject *key = ep[i].me_key; - Py_INCREF(key); - PyList_SET_ITEM(v, j, key); - j++; - } - } - assert(j == n); - return v; + n = mp->ma_used; + v = PyList_New(n); + if (v == NULL) + return NULL; + if (n != mp->ma_used) { + /* Durnit. The allocations caused the dict to resize. + * Just start over, this shouldn't normally happen. + */ + Py_DECREF(v); + goto again; + } + ep = mp->ma_table; + mask = mp->ma_mask; + for (i = 0, j = 0; i <= mask; i++) { + if (ep[i].me_value != NULL) { + PyObject *key = ep[i].me_key; + Py_INCREF(key); + PyList_SET_ITEM(v, j, key); + j++; + } + } + assert(j == n); + return v; } static PyObject * dict_values(register PyDictObject *mp) { - register PyObject *v; - register Py_ssize_t i, j; - PyDictEntry *ep; - Py_ssize_t mask, n; + register PyObject *v; + register Py_ssize_t i, j; + PyDictEntry *ep; + Py_ssize_t mask, n; again: - n = mp->ma_used; - v = PyList_New(n); - if (v == NULL) - return NULL; - if (n != mp->ma_used) { - /* Durnit. The allocations caused the dict to resize. - * Just start over, this shouldn't normally happen. - */ - Py_DECREF(v); - goto again; - } - ep = mp->ma_table; - mask = mp->ma_mask; - for (i = 0, j = 0; i <= mask; i++) { - if (ep[i].me_value != NULL) { - PyObject *value = ep[i].me_value; - Py_INCREF(value); - PyList_SET_ITEM(v, j, value); - j++; - } - } - assert(j == n); - return v; + n = mp->ma_used; + v = PyList_New(n); + if (v == NULL) + return NULL; + if (n != mp->ma_used) { + /* Durnit. The allocations caused the dict to resize. + * Just start over, this shouldn't normally happen. + */ + Py_DECREF(v); + goto again; + } + ep = mp->ma_table; + mask = mp->ma_mask; + for (i = 0, j = 0; i <= mask; i++) { + if (ep[i].me_value != NULL) { + PyObject *value = ep[i].me_value; + Py_INCREF(value); + PyList_SET_ITEM(v, j, value); + j++; + } + } + assert(j == n); + return v; } static PyObject * dict_items(register PyDictObject *mp) { - register PyObject *v; - register Py_ssize_t i, j, n; - Py_ssize_t mask; - PyObject *item, *key, *value; - PyDictEntry *ep; - - /* Preallocate the list of tuples, to avoid allocations during - * the loop over the items, which could trigger GC, which - * could resize the dict. :-( - */ + register PyObject *v; + register Py_ssize_t i, j, n; + Py_ssize_t mask; + PyObject *item, *key, *value; + PyDictEntry *ep; + + /* Preallocate the list of tuples, to avoid allocations during + * the loop over the items, which could trigger GC, which + * could resize the dict. :-( + */ again: - n = mp->ma_used; - v = PyList_New(n); - if (v == NULL) - return NULL; - for (i = 0; i < n; i++) { - item = PyTuple_New(2); - if (item == NULL) { - Py_DECREF(v); - return NULL; - } - PyList_SET_ITEM(v, i, item); - } - if (n != mp->ma_used) { - /* Durnit. The allocations caused the dict to resize. - * Just start over, this shouldn't normally happen. - */ - Py_DECREF(v); - goto again; - } - /* Nothing we do below makes any function calls. */ - ep = mp->ma_table; - mask = mp->ma_mask; - for (i = 0, j = 0; i <= mask; i++) { - if ((value=ep[i].me_value) != NULL) { - key = ep[i].me_key; - item = PyList_GET_ITEM(v, j); - Py_INCREF(key); - PyTuple_SET_ITEM(item, 0, key); - Py_INCREF(value); - PyTuple_SET_ITEM(item, 1, value); - j++; - } - } - assert(j == n); - return v; + n = mp->ma_used; + v = PyList_New(n); + if (v == NULL) + return NULL; + for (i = 0; i < n; i++) { + item = PyTuple_New(2); + if (item == NULL) { + Py_DECREF(v); + return NULL; + } + PyList_SET_ITEM(v, i, item); + } + if (n != mp->ma_used) { + /* Durnit. The allocations caused the dict to resize. + * Just start over, this shouldn't normally happen. + */ + Py_DECREF(v); + goto again; + } + /* Nothing we do below makes any function calls. */ + ep = mp->ma_table; + mask = mp->ma_mask; + for (i = 0, j = 0; i <= mask; i++) { + if ((value=ep[i].me_value) != NULL) { + key = ep[i].me_key; + item = PyList_GET_ITEM(v, j); + Py_INCREF(key); + PyTuple_SET_ITEM(item, 0, key); + Py_INCREF(value); + PyTuple_SET_ITEM(item, 1, value); + j++; + } + } + assert(j == n); + return v; } static PyObject * dict_fromkeys(PyObject *cls, PyObject *args) { - PyObject *seq; - PyObject *value = Py_None; - PyObject *it; /* iter(seq) */ - PyObject *key; - PyObject *d; - int status; - - if (!PyArg_UnpackTuple(args, "fromkeys", 1, 2, &seq, &value)) - return NULL; - - d = PyObject_CallObject(cls, NULL); - if (d == NULL) - return NULL; - - if (PyDict_CheckExact(d) && PyDict_CheckExact(seq)) { - PyDictObject *mp = (PyDictObject *)d; - PyObject *oldvalue; - Py_ssize_t pos = 0; - PyObject *key; - long hash; - - if (dictresize(mp, Py_SIZE(seq))) - return NULL; - - while (_PyDict_Next(seq, &pos, &key, &oldvalue, &hash)) { - Py_INCREF(key); - Py_INCREF(value); - if (insertdict(mp, key, hash, value)) - return NULL; - } - return d; - } - - if (PyDict_CheckExact(d) && PyAnySet_CheckExact(seq)) { - PyDictObject *mp = (PyDictObject *)d; - Py_ssize_t pos = 0; - PyObject *key; - long hash; - - if (dictresize(mp, PySet_GET_SIZE(seq))) - return NULL; - - while (_PySet_NextEntry(seq, &pos, &key, &hash)) { - Py_INCREF(key); - Py_INCREF(value); - if (insertdict(mp, key, hash, value)) - return NULL; - } - return d; - } - - it = PyObject_GetIter(seq); - if (it == NULL){ - Py_DECREF(d); - return NULL; - } - - if (PyDict_CheckExact(d)) { - while ((key = PyIter_Next(it)) != NULL) { - status = PyDict_SetItem(d, key, value); - Py_DECREF(key); - if (status < 0) - goto Fail; - } - } else { - while ((key = PyIter_Next(it)) != NULL) { - status = PyObject_SetItem(d, key, value); - Py_DECREF(key); - if (status < 0) - goto Fail; - } - } - - if (PyErr_Occurred()) - goto Fail; - Py_DECREF(it); - return d; + PyObject *seq; + PyObject *value = Py_None; + PyObject *it; /* iter(seq) */ + PyObject *key; + PyObject *d; + int status; + + if (!PyArg_UnpackTuple(args, "fromkeys", 1, 2, &seq, &value)) + return NULL; + + d = PyObject_CallObject(cls, NULL); + if (d == NULL) + return NULL; + + if (PyDict_CheckExact(d) && PyDict_CheckExact(seq)) { + PyDictObject *mp = (PyDictObject *)d; + PyObject *oldvalue; + Py_ssize_t pos = 0; + PyObject *key; + long hash; + + if (dictresize(mp, Py_SIZE(seq))) + return NULL; + + while (_PyDict_Next(seq, &pos, &key, &oldvalue, &hash)) { + Py_INCREF(key); + Py_INCREF(value); + if (insertdict(mp, key, hash, value)) + return NULL; + } + return d; + } + + if (PyDict_CheckExact(d) && PyAnySet_CheckExact(seq)) { + PyDictObject *mp = (PyDictObject *)d; + Py_ssize_t pos = 0; + PyObject *key; + long hash; + + if (dictresize(mp, PySet_GET_SIZE(seq))) + return NULL; + + while (_PySet_NextEntry(seq, &pos, &key, &hash)) { + Py_INCREF(key); + Py_INCREF(value); + if (insertdict(mp, key, hash, value)) + return NULL; + } + return d; + } + + it = PyObject_GetIter(seq); + if (it == NULL){ + Py_DECREF(d); + return NULL; + } + + if (PyDict_CheckExact(d)) { + while ((key = PyIter_Next(it)) != NULL) { + status = PyDict_SetItem(d, key, value); + Py_DECREF(key); + if (status < 0) + goto Fail; + } + } else { + while ((key = PyIter_Next(it)) != NULL) { + status = PyObject_SetItem(d, key, value); + Py_DECREF(key); + if (status < 0) + goto Fail; + } + } + + if (PyErr_Occurred()) + goto Fail; + Py_DECREF(it); + return d; Fail: - Py_DECREF(it); - Py_DECREF(d); - return NULL; + Py_DECREF(it); + Py_DECREF(d); + return NULL; } static int dict_update_common(PyObject *self, PyObject *args, PyObject *kwds, char *methname) { - PyObject *arg = NULL; - int result = 0; + PyObject *arg = NULL; + int result = 0; - if (!PyArg_UnpackTuple(args, methname, 0, 1, &arg)) - result = -1; + if (!PyArg_UnpackTuple(args, methname, 0, 1, &arg)) + result = -1; - else if (arg != NULL) { - if (PyObject_HasAttrString(arg, "keys")) - result = PyDict_Merge(self, arg, 1); - else - result = PyDict_MergeFromSeq2(self, arg, 1); - } - if (result == 0 && kwds != NULL) { - if (PyArg_ValidateKeywordArguments(kwds)) - result = PyDict_Merge(self, kwds, 1); - else - result = -1; - } - return result; + else if (arg != NULL) { + if (PyObject_HasAttrString(arg, "keys")) + result = PyDict_Merge(self, arg, 1); + else + result = PyDict_MergeFromSeq2(self, arg, 1); + } + if (result == 0 && kwds != NULL) { + if (PyArg_ValidateKeywordArguments(kwds)) + result = PyDict_Merge(self, kwds, 1); + else + result = -1; + } + return result; } static PyObject * dict_update(PyObject *self, PyObject *args, PyObject *kwds) { - if (dict_update_common(self, args, kwds, "update") != -1) - Py_RETURN_NONE; - return NULL; + if (dict_update_common(self, args, kwds, "update") != -1) + Py_RETURN_NONE; + return NULL; } /* Update unconditionally replaces existing items. @@ -1432,238 +1432,238 @@ int PyDict_MergeFromSeq2(PyObject *d, PyObject *seq2, int override) { - PyObject *it; /* iter(seq2) */ - Py_ssize_t i; /* index into seq2 of current element */ - PyObject *item; /* seq2[i] */ - PyObject *fast; /* item as a 2-tuple or 2-list */ - - assert(d != NULL); - assert(PyDict_Check(d)); - assert(seq2 != NULL); - - it = PyObject_GetIter(seq2); - if (it == NULL) - return -1; - - for (i = 0; ; ++i) { - PyObject *key, *value; - Py_ssize_t n; - - fast = NULL; - item = PyIter_Next(it); - if (item == NULL) { - if (PyErr_Occurred()) - goto Fail; - break; - } - - /* Convert item to sequence, and verify length 2. */ - fast = PySequence_Fast(item, ""); - if (fast == NULL) { - if (PyErr_ExceptionMatches(PyExc_TypeError)) - PyErr_Format(PyExc_TypeError, - "cannot convert dictionary update " - "sequence element #%zd to a sequence", - i); - goto Fail; - } - n = PySequence_Fast_GET_SIZE(fast); - if (n != 2) { - PyErr_Format(PyExc_ValueError, - "dictionary update sequence element #%zd " - "has length %zd; 2 is required", - i, n); - goto Fail; - } - - /* Update/merge with this (key, value) pair. */ - key = PySequence_Fast_GET_ITEM(fast, 0); - value = PySequence_Fast_GET_ITEM(fast, 1); - if (override || PyDict_GetItem(d, key) == NULL) { - int status = PyDict_SetItem(d, key, value); - if (status < 0) - goto Fail; - } - Py_DECREF(fast); - Py_DECREF(item); - } + PyObject *it; /* iter(seq2) */ + Py_ssize_t i; /* index into seq2 of current element */ + PyObject *item; /* seq2[i] */ + PyObject *fast; /* item as a 2-tuple or 2-list */ + + assert(d != NULL); + assert(PyDict_Check(d)); + assert(seq2 != NULL); + + it = PyObject_GetIter(seq2); + if (it == NULL) + return -1; + + for (i = 0; ; ++i) { + PyObject *key, *value; + Py_ssize_t n; + + fast = NULL; + item = PyIter_Next(it); + if (item == NULL) { + if (PyErr_Occurred()) + goto Fail; + break; + } + + /* Convert item to sequence, and verify length 2. */ + fast = PySequence_Fast(item, ""); + if (fast == NULL) { + if (PyErr_ExceptionMatches(PyExc_TypeError)) + PyErr_Format(PyExc_TypeError, + "cannot convert dictionary update " + "sequence element #%zd to a sequence", + i); + goto Fail; + } + n = PySequence_Fast_GET_SIZE(fast); + if (n != 2) { + PyErr_Format(PyExc_ValueError, + "dictionary update sequence element #%zd " + "has length %zd; 2 is required", + i, n); + goto Fail; + } + + /* Update/merge with this (key, value) pair. */ + key = PySequence_Fast_GET_ITEM(fast, 0); + value = PySequence_Fast_GET_ITEM(fast, 1); + if (override || PyDict_GetItem(d, key) == NULL) { + int status = PyDict_SetItem(d, key, value); + if (status < 0) + goto Fail; + } + Py_DECREF(fast); + Py_DECREF(item); + } - i = 0; - goto Return; + i = 0; + goto Return; Fail: - Py_XDECREF(item); - Py_XDECREF(fast); - i = -1; + Py_XDECREF(item); + Py_XDECREF(fast); + i = -1; Return: - Py_DECREF(it); - return Py_SAFE_DOWNCAST(i, Py_ssize_t, int); + Py_DECREF(it); + return Py_SAFE_DOWNCAST(i, Py_ssize_t, int); } int PyDict_Update(PyObject *a, PyObject *b) { - return PyDict_Merge(a, b, 1); + return PyDict_Merge(a, b, 1); } int PyDict_Merge(PyObject *a, PyObject *b, int override) { - register PyDictObject *mp, *other; - register Py_ssize_t i; - PyDictEntry *entry; - - /* We accept for the argument either a concrete dictionary object, - * or an abstract "mapping" object. For the former, we can do - * things quite efficiently. For the latter, we only require that - * PyMapping_Keys() and PyObject_GetItem() be supported. - */ - if (a == NULL || !PyDict_Check(a) || b == NULL) { - PyErr_BadInternalCall(); - return -1; - } - mp = (PyDictObject*)a; - if (PyDict_Check(b)) { - other = (PyDictObject*)b; - if (other == mp || other->ma_used == 0) - /* a.update(a) or a.update({}); nothing to do */ - return 0; - if (mp->ma_used == 0) - /* Since the target dict is empty, PyDict_GetItem() - * always returns NULL. Setting override to 1 - * skips the unnecessary test. - */ - override = 1; - /* Do one big resize at the start, rather than - * incrementally resizing as we insert new items. Expect - * that there will be no (or few) overlapping keys. - */ - if ((mp->ma_fill + other->ma_used)*3 >= (mp->ma_mask+1)*2) { - if (dictresize(mp, (mp->ma_used + other->ma_used)*2) != 0) - return -1; - } - for (i = 0; i <= other->ma_mask; i++) { - entry = &other->ma_table[i]; - if (entry->me_value != NULL && - (override || - PyDict_GetItem(a, entry->me_key) == NULL)) { - Py_INCREF(entry->me_key); - Py_INCREF(entry->me_value); - if (insertdict(mp, entry->me_key, - (long)entry->me_hash, - entry->me_value) != 0) - return -1; - } - } - } - else { - /* Do it the generic, slower way */ - PyObject *keys = PyMapping_Keys(b); - PyObject *iter; - PyObject *key, *value; - int status; - - if (keys == NULL) - /* Docstring says this is equivalent to E.keys() so - * if E doesn't have a .keys() method we want - * AttributeError to percolate up. Might as well - * do the same for any other error. - */ - return -1; - - iter = PyObject_GetIter(keys); - Py_DECREF(keys); - if (iter == NULL) - return -1; - - for (key = PyIter_Next(iter); key; key = PyIter_Next(iter)) { - if (!override && PyDict_GetItem(a, key) != NULL) { - Py_DECREF(key); - continue; - } - value = PyObject_GetItem(b, key); - if (value == NULL) { - Py_DECREF(iter); - Py_DECREF(key); - return -1; - } - status = PyDict_SetItem(a, key, value); - Py_DECREF(key); - Py_DECREF(value); - if (status < 0) { - Py_DECREF(iter); - return -1; - } - } - Py_DECREF(iter); - if (PyErr_Occurred()) - /* Iterator completed, via error */ - return -1; - } - return 0; + register PyDictObject *mp, *other; + register Py_ssize_t i; + PyDictEntry *entry; + + /* We accept for the argument either a concrete dictionary object, + * or an abstract "mapping" object. For the former, we can do + * things quite efficiently. For the latter, we only require that + * PyMapping_Keys() and PyObject_GetItem() be supported. + */ + if (a == NULL || !PyDict_Check(a) || b == NULL) { + PyErr_BadInternalCall(); + return -1; + } + mp = (PyDictObject*)a; + if (PyDict_Check(b)) { + other = (PyDictObject*)b; + if (other == mp || other->ma_used == 0) + /* a.update(a) or a.update({}); nothing to do */ + return 0; + if (mp->ma_used == 0) + /* Since the target dict is empty, PyDict_GetItem() + * always returns NULL. Setting override to 1 + * skips the unnecessary test. + */ + override = 1; + /* Do one big resize at the start, rather than + * incrementally resizing as we insert new items. Expect + * that there will be no (or few) overlapping keys. + */ + if ((mp->ma_fill + other->ma_used)*3 >= (mp->ma_mask+1)*2) { + if (dictresize(mp, (mp->ma_used + other->ma_used)*2) != 0) + return -1; + } + for (i = 0; i <= other->ma_mask; i++) { + entry = &other->ma_table[i]; + if (entry->me_value != NULL && + (override || + PyDict_GetItem(a, entry->me_key) == NULL)) { + Py_INCREF(entry->me_key); + Py_INCREF(entry->me_value); + if (insertdict(mp, entry->me_key, + (long)entry->me_hash, + entry->me_value) != 0) + return -1; + } + } + } + else { + /* Do it the generic, slower way */ + PyObject *keys = PyMapping_Keys(b); + PyObject *iter; + PyObject *key, *value; + int status; + + if (keys == NULL) + /* Docstring says this is equivalent to E.keys() so + * if E doesn't have a .keys() method we want + * AttributeError to percolate up. Might as well + * do the same for any other error. + */ + return -1; + + iter = PyObject_GetIter(keys); + Py_DECREF(keys); + if (iter == NULL) + return -1; + + for (key = PyIter_Next(iter); key; key = PyIter_Next(iter)) { + if (!override && PyDict_GetItem(a, key) != NULL) { + Py_DECREF(key); + continue; + } + value = PyObject_GetItem(b, key); + if (value == NULL) { + Py_DECREF(iter); + Py_DECREF(key); + return -1; + } + status = PyDict_SetItem(a, key, value); + Py_DECREF(key); + Py_DECREF(value); + if (status < 0) { + Py_DECREF(iter); + return -1; + } + } + Py_DECREF(iter); + if (PyErr_Occurred()) + /* Iterator completed, via error */ + return -1; + } + return 0; } static PyObject * dict_copy(register PyDictObject *mp) { - return PyDict_Copy((PyObject*)mp); + return PyDict_Copy((PyObject*)mp); } PyObject * PyDict_Copy(PyObject *o) { - PyObject *copy; + PyObject *copy; - if (o == NULL || !PyDict_Check(o)) { - PyErr_BadInternalCall(); - return NULL; - } - copy = PyDict_New(); - if (copy == NULL) - return NULL; - if (PyDict_Merge(copy, o, 1) == 0) - return copy; - Py_DECREF(copy); - return NULL; + if (o == NULL || !PyDict_Check(o)) { + PyErr_BadInternalCall(); + return NULL; + } + copy = PyDict_New(); + if (copy == NULL) + return NULL; + if (PyDict_Merge(copy, o, 1) == 0) + return copy; + Py_DECREF(copy); + return NULL; } Py_ssize_t PyDict_Size(PyObject *mp) { - if (mp == NULL || !PyDict_Check(mp)) { - PyErr_BadInternalCall(); - return -1; - } - return ((PyDictObject *)mp)->ma_used; + if (mp == NULL || !PyDict_Check(mp)) { + PyErr_BadInternalCall(); + return -1; + } + return ((PyDictObject *)mp)->ma_used; } PyObject * PyDict_Keys(PyObject *mp) { - if (mp == NULL || !PyDict_Check(mp)) { - PyErr_BadInternalCall(); - return NULL; - } - return dict_keys((PyDictObject *)mp); + if (mp == NULL || !PyDict_Check(mp)) { + PyErr_BadInternalCall(); + return NULL; + } + return dict_keys((PyDictObject *)mp); } PyObject * PyDict_Values(PyObject *mp) { - if (mp == NULL || !PyDict_Check(mp)) { - PyErr_BadInternalCall(); - return NULL; - } - return dict_values((PyDictObject *)mp); + if (mp == NULL || !PyDict_Check(mp)) { + PyErr_BadInternalCall(); + return NULL; + } + return dict_values((PyDictObject *)mp); } PyObject * PyDict_Items(PyObject *mp) { - if (mp == NULL || !PyDict_Check(mp)) { - PyErr_BadInternalCall(); - return NULL; - } - return dict_items((PyDictObject *)mp); + if (mp == NULL || !PyDict_Check(mp)) { + PyErr_BadInternalCall(); + return NULL; + } + return dict_items((PyDictObject *)mp); } /* Return 1 if dicts equal, 0 if not, -1 if error. @@ -1673,271 +1673,271 @@ static int dict_equal(PyDictObject *a, PyDictObject *b) { - Py_ssize_t i; + Py_ssize_t i; - if (a->ma_used != b->ma_used) - /* can't be equal if # of entries differ */ - return 0; - - /* Same # of entries -- check all of 'em. Exit early on any diff. */ - for (i = 0; i <= a->ma_mask; i++) { - PyObject *aval = a->ma_table[i].me_value; - if (aval != NULL) { - int cmp; - PyObject *bval; - PyObject *key = a->ma_table[i].me_key; - /* temporarily bump aval's refcount to ensure it stays - alive until we're done with it */ - Py_INCREF(aval); - /* ditto for key */ - Py_INCREF(key); - bval = PyDict_GetItemWithError((PyObject *)b, key); - Py_DECREF(key); - if (bval == NULL) { - Py_DECREF(aval); - if (PyErr_Occurred()) - return -1; - return 0; - } - cmp = PyObject_RichCompareBool(aval, bval, Py_EQ); - Py_DECREF(aval); - if (cmp <= 0) /* error or not equal */ - return cmp; - } - } - return 1; + if (a->ma_used != b->ma_used) + /* can't be equal if # of entries differ */ + return 0; + + /* Same # of entries -- check all of 'em. Exit early on any diff. */ + for (i = 0; i <= a->ma_mask; i++) { + PyObject *aval = a->ma_table[i].me_value; + if (aval != NULL) { + int cmp; + PyObject *bval; + PyObject *key = a->ma_table[i].me_key; + /* temporarily bump aval's refcount to ensure it stays + alive until we're done with it */ + Py_INCREF(aval); + /* ditto for key */ + Py_INCREF(key); + bval = PyDict_GetItemWithError((PyObject *)b, key); + Py_DECREF(key); + if (bval == NULL) { + Py_DECREF(aval); + if (PyErr_Occurred()) + return -1; + return 0; + } + cmp = PyObject_RichCompareBool(aval, bval, Py_EQ); + Py_DECREF(aval); + if (cmp <= 0) /* error or not equal */ + return cmp; + } + } + return 1; } static PyObject * dict_richcompare(PyObject *v, PyObject *w, int op) { - int cmp; - PyObject *res; + int cmp; + PyObject *res; - if (!PyDict_Check(v) || !PyDict_Check(w)) { - res = Py_NotImplemented; - } - else if (op == Py_EQ || op == Py_NE) { - cmp = dict_equal((PyDictObject *)v, (PyDictObject *)w); - if (cmp < 0) - return NULL; - res = (cmp == (op == Py_EQ)) ? Py_True : Py_False; - } - else - res = Py_NotImplemented; - Py_INCREF(res); - return res; + if (!PyDict_Check(v) || !PyDict_Check(w)) { + res = Py_NotImplemented; + } + else if (op == Py_EQ || op == Py_NE) { + cmp = dict_equal((PyDictObject *)v, (PyDictObject *)w); + if (cmp < 0) + return NULL; + res = (cmp == (op == Py_EQ)) ? Py_True : Py_False; + } + else + res = Py_NotImplemented; + Py_INCREF(res); + return res; } static PyObject * dict_contains(register PyDictObject *mp, PyObject *key) { - long hash; - PyDictEntry *ep; + long hash; + PyDictEntry *ep; - if (!PyUnicode_CheckExact(key) || - (hash = ((PyUnicodeObject *) key)->hash) == -1) { - hash = PyObject_Hash(key); - if (hash == -1) - return NULL; - } - ep = (mp->ma_lookup)(mp, key, hash); - if (ep == NULL) - return NULL; - return PyBool_FromLong(ep->me_value != NULL); + if (!PyUnicode_CheckExact(key) || + (hash = ((PyUnicodeObject *) key)->hash) == -1) { + hash = PyObject_Hash(key); + if (hash == -1) + return NULL; + } + ep = (mp->ma_lookup)(mp, key, hash); + if (ep == NULL) + return NULL; + return PyBool_FromLong(ep->me_value != NULL); } static PyObject * dict_get(register PyDictObject *mp, PyObject *args) { - PyObject *key; - PyObject *failobj = Py_None; - PyObject *val = NULL; - long hash; - PyDictEntry *ep; - - if (!PyArg_UnpackTuple(args, "get", 1, 2, &key, &failobj)) - return NULL; - - if (!PyUnicode_CheckExact(key) || - (hash = ((PyUnicodeObject *) key)->hash) == -1) { - hash = PyObject_Hash(key); - if (hash == -1) - return NULL; - } - ep = (mp->ma_lookup)(mp, key, hash); - if (ep == NULL) - return NULL; - val = ep->me_value; - if (val == NULL) - val = failobj; - Py_INCREF(val); - return val; + PyObject *key; + PyObject *failobj = Py_None; + PyObject *val = NULL; + long hash; + PyDictEntry *ep; + + if (!PyArg_UnpackTuple(args, "get", 1, 2, &key, &failobj)) + return NULL; + + if (!PyUnicode_CheckExact(key) || + (hash = ((PyUnicodeObject *) key)->hash) == -1) { + hash = PyObject_Hash(key); + if (hash == -1) + return NULL; + } + ep = (mp->ma_lookup)(mp, key, hash); + if (ep == NULL) + return NULL; + val = ep->me_value; + if (val == NULL) + val = failobj; + Py_INCREF(val); + return val; } static PyObject * dict_setdefault(register PyDictObject *mp, PyObject *args) { - PyObject *key; - PyObject *failobj = Py_None; - PyObject *val = NULL; - long hash; - PyDictEntry *ep; - - if (!PyArg_UnpackTuple(args, "setdefault", 1, 2, &key, &failobj)) - return NULL; - - if (!PyUnicode_CheckExact(key) || - (hash = ((PyUnicodeObject *) key)->hash) == -1) { - hash = PyObject_Hash(key); - if (hash == -1) - return NULL; - } - ep = (mp->ma_lookup)(mp, key, hash); - if (ep == NULL) - return NULL; - val = ep->me_value; - if (val == NULL) { - val = failobj; - if (PyDict_SetItem((PyObject*)mp, key, failobj)) - val = NULL; - } - Py_XINCREF(val); - return val; + PyObject *key; + PyObject *failobj = Py_None; + PyObject *val = NULL; + long hash; + PyDictEntry *ep; + + if (!PyArg_UnpackTuple(args, "setdefault", 1, 2, &key, &failobj)) + return NULL; + + if (!PyUnicode_CheckExact(key) || + (hash = ((PyUnicodeObject *) key)->hash) == -1) { + hash = PyObject_Hash(key); + if (hash == -1) + return NULL; + } + ep = (mp->ma_lookup)(mp, key, hash); + if (ep == NULL) + return NULL; + val = ep->me_value; + if (val == NULL) { + val = failobj; + if (PyDict_SetItem((PyObject*)mp, key, failobj)) + val = NULL; + } + Py_XINCREF(val); + return val; } static PyObject * dict_clear(register PyDictObject *mp) { - PyDict_Clear((PyObject *)mp); - Py_RETURN_NONE; + PyDict_Clear((PyObject *)mp); + Py_RETURN_NONE; } static PyObject * dict_pop(PyDictObject *mp, PyObject *args) { - long hash; - PyDictEntry *ep; - PyObject *old_value, *old_key; - PyObject *key, *deflt = NULL; - - if(!PyArg_UnpackTuple(args, "pop", 1, 2, &key, &deflt)) - return NULL; - if (mp->ma_used == 0) { - if (deflt) { - Py_INCREF(deflt); - return deflt; - } - PyErr_SetString(PyExc_KeyError, - "pop(): dictionary is empty"); - return NULL; - } - if (!PyUnicode_CheckExact(key) || - (hash = ((PyUnicodeObject *) key)->hash) == -1) { - hash = PyObject_Hash(key); - if (hash == -1) - return NULL; - } - ep = (mp->ma_lookup)(mp, key, hash); - if (ep == NULL) - return NULL; - if (ep->me_value == NULL) { - if (deflt) { - Py_INCREF(deflt); - return deflt; - } - set_key_error(key); - return NULL; - } - old_key = ep->me_key; - Py_INCREF(dummy); - ep->me_key = dummy; - old_value = ep->me_value; - ep->me_value = NULL; - mp->ma_used--; - Py_DECREF(old_key); - return old_value; + long hash; + PyDictEntry *ep; + PyObject *old_value, *old_key; + PyObject *key, *deflt = NULL; + + if(!PyArg_UnpackTuple(args, "pop", 1, 2, &key, &deflt)) + return NULL; + if (mp->ma_used == 0) { + if (deflt) { + Py_INCREF(deflt); + return deflt; + } + PyErr_SetString(PyExc_KeyError, + "pop(): dictionary is empty"); + return NULL; + } + if (!PyUnicode_CheckExact(key) || + (hash = ((PyUnicodeObject *) key)->hash) == -1) { + hash = PyObject_Hash(key); + if (hash == -1) + return NULL; + } + ep = (mp->ma_lookup)(mp, key, hash); + if (ep == NULL) + return NULL; + if (ep->me_value == NULL) { + if (deflt) { + Py_INCREF(deflt); + return deflt; + } + set_key_error(key); + return NULL; + } + old_key = ep->me_key; + Py_INCREF(dummy); + ep->me_key = dummy; + old_value = ep->me_value; + ep->me_value = NULL; + mp->ma_used--; + Py_DECREF(old_key); + return old_value; } static PyObject * dict_popitem(PyDictObject *mp) { - Py_ssize_t i = 0; - PyDictEntry *ep; - PyObject *res; - - /* Allocate the result tuple before checking the size. Believe it - * or not, this allocation could trigger a garbage collection which - * could empty the dict, so if we checked the size first and that - * happened, the result would be an infinite loop (searching for an - * entry that no longer exists). Note that the usual popitem() - * idiom is "while d: k, v = d.popitem()". so needing to throw the - * tuple away if the dict *is* empty isn't a significant - * inefficiency -- possible, but unlikely in practice. - */ - res = PyTuple_New(2); - if (res == NULL) - return NULL; - if (mp->ma_used == 0) { - Py_DECREF(res); - PyErr_SetString(PyExc_KeyError, - "popitem(): dictionary is empty"); - return NULL; - } - /* Set ep to "the first" dict entry with a value. We abuse the hash - * field of slot 0 to hold a search finger: - * If slot 0 has a value, use slot 0. - * Else slot 0 is being used to hold a search finger, - * and we use its hash value as the first index to look. - */ - ep = &mp->ma_table[0]; - if (ep->me_value == NULL) { - i = ep->me_hash; - /* The hash field may be a real hash value, or it may be a - * legit search finger, or it may be a once-legit search - * finger that's out of bounds now because it wrapped around - * or the table shrunk -- simply make sure it's in bounds now. - */ - if (i > mp->ma_mask || i < 1) - i = 1; /* skip slot 0 */ - while ((ep = &mp->ma_table[i])->me_value == NULL) { - i++; - if (i > mp->ma_mask) - i = 1; - } - } - PyTuple_SET_ITEM(res, 0, ep->me_key); - PyTuple_SET_ITEM(res, 1, ep->me_value); - Py_INCREF(dummy); - ep->me_key = dummy; - ep->me_value = NULL; - mp->ma_used--; - assert(mp->ma_table[0].me_value == NULL); - mp->ma_table[0].me_hash = i + 1; /* next place to start */ - return res; + Py_ssize_t i = 0; + PyDictEntry *ep; + PyObject *res; + + /* Allocate the result tuple before checking the size. Believe it + * or not, this allocation could trigger a garbage collection which + * could empty the dict, so if we checked the size first and that + * happened, the result would be an infinite loop (searching for an + * entry that no longer exists). Note that the usual popitem() + * idiom is "while d: k, v = d.popitem()". so needing to throw the + * tuple away if the dict *is* empty isn't a significant + * inefficiency -- possible, but unlikely in practice. + */ + res = PyTuple_New(2); + if (res == NULL) + return NULL; + if (mp->ma_used == 0) { + Py_DECREF(res); + PyErr_SetString(PyExc_KeyError, + "popitem(): dictionary is empty"); + return NULL; + } + /* Set ep to "the first" dict entry with a value. We abuse the hash + * field of slot 0 to hold a search finger: + * If slot 0 has a value, use slot 0. + * Else slot 0 is being used to hold a search finger, + * and we use its hash value as the first index to look. + */ + ep = &mp->ma_table[0]; + if (ep->me_value == NULL) { + i = ep->me_hash; + /* The hash field may be a real hash value, or it may be a + * legit search finger, or it may be a once-legit search + * finger that's out of bounds now because it wrapped around + * or the table shrunk -- simply make sure it's in bounds now. + */ + if (i > mp->ma_mask || i < 1) + i = 1; /* skip slot 0 */ + while ((ep = &mp->ma_table[i])->me_value == NULL) { + i++; + if (i > mp->ma_mask) + i = 1; + } + } + PyTuple_SET_ITEM(res, 0, ep->me_key); + PyTuple_SET_ITEM(res, 1, ep->me_value); + Py_INCREF(dummy); + ep->me_key = dummy; + ep->me_value = NULL; + mp->ma_used--; + assert(mp->ma_table[0].me_value == NULL); + mp->ma_table[0].me_hash = i + 1; /* next place to start */ + return res; } static int dict_traverse(PyObject *op, visitproc visit, void *arg) { - Py_ssize_t i = 0; - PyObject *pk; - PyObject *pv; - - while (PyDict_Next(op, &i, &pk, &pv)) { - Py_VISIT(pk); - Py_VISIT(pv); - } - return 0; + Py_ssize_t i = 0; + PyObject *pk; + PyObject *pv; + + while (PyDict_Next(op, &i, &pk, &pv)) { + Py_VISIT(pk); + Py_VISIT(pv); + } + return 0; } static int dict_tp_clear(PyObject *op) { - PyDict_Clear(op); - return 0; + PyDict_Clear(op); + return 0; } static PyObject *dictiter_new(PyDictObject *, PyTypeObject *); @@ -1945,12 +1945,12 @@ static PyObject * dict_sizeof(PyDictObject *mp) { - Py_ssize_t res; + Py_ssize_t res; - res = sizeof(PyDictObject); - if (mp->ma_table != mp->ma_smalltable) - res = res + (mp->ma_mask + 1) * sizeof(PyDictEntry); - return PyLong_FromSsize_t(res); + res = sizeof(PyDictObject); + if (mp->ma_table != mp->ma_smalltable) + res = res + (mp->ma_mask + 1) * sizeof(PyDictEntry); + return PyLong_FromSsize_t(res); } PyDoc_STRVAR(contains__doc__, @@ -1997,126 +1997,126 @@ static PyObject *dictvalues_new(PyObject *); PyDoc_STRVAR(keys__doc__, - "D.keys() -> a set-like object providing a view on D's keys"); + "D.keys() -> a set-like object providing a view on D's keys"); PyDoc_STRVAR(items__doc__, - "D.items() -> a set-like object providing a view on D's items"); + "D.items() -> a set-like object providing a view on D's items"); PyDoc_STRVAR(values__doc__, - "D.values() -> an object providing a view on D's values"); + "D.values() -> an object providing a view on D's values"); static PyMethodDef mapp_methods[] = { - {"__contains__",(PyCFunction)dict_contains, METH_O | METH_COEXIST, - contains__doc__}, - {"__getitem__", (PyCFunction)dict_subscript, METH_O | METH_COEXIST, - getitem__doc__}, - {"__sizeof__", (PyCFunction)dict_sizeof, METH_NOARGS, - sizeof__doc__}, - {"get", (PyCFunction)dict_get, METH_VARARGS, - get__doc__}, - {"setdefault", (PyCFunction)dict_setdefault, METH_VARARGS, - setdefault_doc__}, - {"pop", (PyCFunction)dict_pop, METH_VARARGS, - pop__doc__}, - {"popitem", (PyCFunction)dict_popitem, METH_NOARGS, - popitem__doc__}, - {"keys", (PyCFunction)dictkeys_new, METH_NOARGS, - keys__doc__}, - {"items", (PyCFunction)dictitems_new, METH_NOARGS, - items__doc__}, - {"values", (PyCFunction)dictvalues_new, METH_NOARGS, - values__doc__}, - {"update", (PyCFunction)dict_update, METH_VARARGS | METH_KEYWORDS, - update__doc__}, - {"fromkeys", (PyCFunction)dict_fromkeys, METH_VARARGS | METH_CLASS, - fromkeys__doc__}, - {"clear", (PyCFunction)dict_clear, METH_NOARGS, - clear__doc__}, - {"copy", (PyCFunction)dict_copy, METH_NOARGS, - copy__doc__}, - {NULL, NULL} /* sentinel */ + {"__contains__",(PyCFunction)dict_contains, METH_O | METH_COEXIST, + contains__doc__}, + {"__getitem__", (PyCFunction)dict_subscript, METH_O | METH_COEXIST, + getitem__doc__}, + {"__sizeof__", (PyCFunction)dict_sizeof, METH_NOARGS, + sizeof__doc__}, + {"get", (PyCFunction)dict_get, METH_VARARGS, + get__doc__}, + {"setdefault", (PyCFunction)dict_setdefault, METH_VARARGS, + setdefault_doc__}, + {"pop", (PyCFunction)dict_pop, METH_VARARGS, + pop__doc__}, + {"popitem", (PyCFunction)dict_popitem, METH_NOARGS, + popitem__doc__}, + {"keys", (PyCFunction)dictkeys_new, METH_NOARGS, + keys__doc__}, + {"items", (PyCFunction)dictitems_new, METH_NOARGS, + items__doc__}, + {"values", (PyCFunction)dictvalues_new, METH_NOARGS, + values__doc__}, + {"update", (PyCFunction)dict_update, METH_VARARGS | METH_KEYWORDS, + update__doc__}, + {"fromkeys", (PyCFunction)dict_fromkeys, METH_VARARGS | METH_CLASS, + fromkeys__doc__}, + {"clear", (PyCFunction)dict_clear, METH_NOARGS, + clear__doc__}, + {"copy", (PyCFunction)dict_copy, METH_NOARGS, + copy__doc__}, + {NULL, NULL} /* sentinel */ }; /* Return 1 if `key` is in dict `op`, 0 if not, and -1 on error. */ int PyDict_Contains(PyObject *op, PyObject *key) { - long hash; - PyDictObject *mp = (PyDictObject *)op; - PyDictEntry *ep; - - if (!PyUnicode_CheckExact(key) || - (hash = ((PyUnicodeObject *) key)->hash) == -1) { - hash = PyObject_Hash(key); - if (hash == -1) - return -1; - } - ep = (mp->ma_lookup)(mp, key, hash); - return ep == NULL ? -1 : (ep->me_value != NULL); + long hash; + PyDictObject *mp = (PyDictObject *)op; + PyDictEntry *ep; + + if (!PyUnicode_CheckExact(key) || + (hash = ((PyUnicodeObject *) key)->hash) == -1) { + hash = PyObject_Hash(key); + if (hash == -1) + return -1; + } + ep = (mp->ma_lookup)(mp, key, hash); + return ep == NULL ? -1 : (ep->me_value != NULL); } /* Internal version of PyDict_Contains used when the hash value is already known */ int _PyDict_Contains(PyObject *op, PyObject *key, long hash) { - PyDictObject *mp = (PyDictObject *)op; - PyDictEntry *ep; + PyDictObject *mp = (PyDictObject *)op; + PyDictEntry *ep; - ep = (mp->ma_lookup)(mp, key, hash); - return ep == NULL ? -1 : (ep->me_value != NULL); + ep = (mp->ma_lookup)(mp, key, hash); + return ep == NULL ? -1 : (ep->me_value != NULL); } /* Hack to implement "key in dict" */ static PySequenceMethods dict_as_sequence = { - 0, /* sq_length */ - 0, /* sq_concat */ - 0, /* sq_repeat */ - 0, /* sq_item */ - 0, /* sq_slice */ - 0, /* sq_ass_item */ - 0, /* sq_ass_slice */ - PyDict_Contains, /* sq_contains */ - 0, /* sq_inplace_concat */ - 0, /* sq_inplace_repeat */ + 0, /* sq_length */ + 0, /* sq_concat */ + 0, /* sq_repeat */ + 0, /* sq_item */ + 0, /* sq_slice */ + 0, /* sq_ass_item */ + 0, /* sq_ass_slice */ + PyDict_Contains, /* sq_contains */ + 0, /* sq_inplace_concat */ + 0, /* sq_inplace_repeat */ }; static PyObject * dict_new(PyTypeObject *type, PyObject *args, PyObject *kwds) { - PyObject *self; + PyObject *self; - assert(type != NULL && type->tp_alloc != NULL); - self = type->tp_alloc(type, 0); - if (self != NULL) { - PyDictObject *d = (PyDictObject *)self; - /* It's guaranteed that tp->alloc zeroed out the struct. */ - assert(d->ma_table == NULL && d->ma_fill == 0 && d->ma_used == 0); - INIT_NONZERO_DICT_SLOTS(d); - d->ma_lookup = lookdict_unicode; - /* The object has been implicitely tracked by tp_alloc */ - if (type == &PyDict_Type) - _PyObject_GC_UNTRACK(d); + assert(type != NULL && type->tp_alloc != NULL); + self = type->tp_alloc(type, 0); + if (self != NULL) { + PyDictObject *d = (PyDictObject *)self; + /* It's guaranteed that tp->alloc zeroed out the struct. */ + assert(d->ma_table == NULL && d->ma_fill == 0 && d->ma_used == 0); + INIT_NONZERO_DICT_SLOTS(d); + d->ma_lookup = lookdict_unicode; + /* The object has been implicitely tracked by tp_alloc */ + if (type == &PyDict_Type) + _PyObject_GC_UNTRACK(d); #ifdef SHOW_CONVERSION_COUNTS - ++created; + ++created; #endif #ifdef SHOW_TRACK_COUNT - if (_PyObject_GC_IS_TRACKED(d)) - count_tracked++; - else - count_untracked++; + if (_PyObject_GC_IS_TRACKED(d)) + count_tracked++; + else + count_untracked++; #endif - } - return self; + } + return self; } static int dict_init(PyObject *self, PyObject *args, PyObject *kwds) { - return dict_update_common(self, args, kwds, "dict"); + return dict_update_common(self, args, kwds, "dict"); } static PyObject * dict_iter(PyDictObject *dict) { - return dictiter_new(dict, &PyDictIterKey_Type); + return dictiter_new(dict, &PyDictIterKey_Type); } PyDoc_STRVAR(dictionary_doc, @@ -2131,46 +2131,46 @@ " in the keyword argument list. For example: dict(one=1, two=2)"); PyTypeObject PyDict_Type = { - PyVarObject_HEAD_INIT(&PyType_Type, 0) - "dict", - sizeof(PyDictObject), - 0, - (destructor)dict_dealloc, /* tp_dealloc */ - 0, /* tp_print */ - 0, /* tp_getattr */ - 0, /* tp_setattr */ - 0, /* tp_reserved */ - (reprfunc)dict_repr, /* tp_repr */ - 0, /* tp_as_number */ - &dict_as_sequence, /* tp_as_sequence */ - &dict_as_mapping, /* tp_as_mapping */ - (hashfunc)PyObject_HashNotImplemented, /* 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 | - Py_TPFLAGS_BASETYPE | Py_TPFLAGS_DICT_SUBCLASS, /* tp_flags */ - dictionary_doc, /* tp_doc */ - dict_traverse, /* tp_traverse */ - dict_tp_clear, /* tp_clear */ - dict_richcompare, /* tp_richcompare */ - 0, /* tp_weaklistoffset */ - (getiterfunc)dict_iter, /* tp_iter */ - 0, /* tp_iternext */ - mapp_methods, /* tp_methods */ - 0, /* tp_members */ - 0, /* tp_getset */ - 0, /* tp_base */ - 0, /* tp_dict */ - 0, /* tp_descr_get */ - 0, /* tp_descr_set */ - 0, /* tp_dictoffset */ - dict_init, /* tp_init */ - PyType_GenericAlloc, /* tp_alloc */ - dict_new, /* tp_new */ - PyObject_GC_Del, /* tp_free */ + PyVarObject_HEAD_INIT(&PyType_Type, 0) + "dict", + sizeof(PyDictObject), + 0, + (destructor)dict_dealloc, /* tp_dealloc */ + 0, /* tp_print */ + 0, /* tp_getattr */ + 0, /* tp_setattr */ + 0, /* tp_reserved */ + (reprfunc)dict_repr, /* tp_repr */ + 0, /* tp_as_number */ + &dict_as_sequence, /* tp_as_sequence */ + &dict_as_mapping, /* tp_as_mapping */ + (hashfunc)PyObject_HashNotImplemented, /* 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 | + Py_TPFLAGS_BASETYPE | Py_TPFLAGS_DICT_SUBCLASS, /* tp_flags */ + dictionary_doc, /* tp_doc */ + dict_traverse, /* tp_traverse */ + dict_tp_clear, /* tp_clear */ + dict_richcompare, /* tp_richcompare */ + 0, /* tp_weaklistoffset */ + (getiterfunc)dict_iter, /* tp_iter */ + 0, /* tp_iternext */ + mapp_methods, /* tp_methods */ + 0, /* tp_members */ + 0, /* tp_getset */ + 0, /* tp_base */ + 0, /* tp_dict */ + 0, /* tp_descr_get */ + 0, /* tp_descr_set */ + 0, /* tp_dictoffset */ + dict_init, /* tp_init */ + PyType_GenericAlloc, /* tp_alloc */ + dict_new, /* tp_new */ + PyObject_GC_Del, /* tp_free */ }; /* For backward compatibility with old dictionary interface */ @@ -2178,340 +2178,340 @@ PyObject * PyDict_GetItemString(PyObject *v, const char *key) { - PyObject *kv, *rv; - kv = PyUnicode_FromString(key); - if (kv == NULL) - return NULL; - rv = PyDict_GetItem(v, kv); - Py_DECREF(kv); - return rv; + PyObject *kv, *rv; + kv = PyUnicode_FromString(key); + if (kv == NULL) + return NULL; + rv = PyDict_GetItem(v, kv); + Py_DECREF(kv); + return rv; } int PyDict_SetItemString(PyObject *v, const char *key, PyObject *item) { - PyObject *kv; - int err; - kv = PyUnicode_FromString(key); - if (kv == NULL) - return -1; - PyUnicode_InternInPlace(&kv); /* XXX Should we really? */ - err = PyDict_SetItem(v, kv, item); - Py_DECREF(kv); - return err; + PyObject *kv; + int err; + kv = PyUnicode_FromString(key); + if (kv == NULL) + return -1; + PyUnicode_InternInPlace(&kv); /* XXX Should we really? */ + err = PyDict_SetItem(v, kv, item); + Py_DECREF(kv); + return err; } int PyDict_DelItemString(PyObject *v, const char *key) { - PyObject *kv; - int err; - kv = PyUnicode_FromString(key); - if (kv == NULL) - return -1; - err = PyDict_DelItem(v, kv); - Py_DECREF(kv); - return err; + PyObject *kv; + int err; + kv = PyUnicode_FromString(key); + if (kv == NULL) + return -1; + err = PyDict_DelItem(v, kv); + Py_DECREF(kv); + return err; } /* Dictionary iterator types */ typedef struct { - PyObject_HEAD - PyDictObject *di_dict; /* Set to NULL when iterator is exhausted */ - Py_ssize_t di_used; - Py_ssize_t di_pos; - PyObject* di_result; /* reusable result tuple for iteritems */ - Py_ssize_t len; + PyObject_HEAD + PyDictObject *di_dict; /* Set to NULL when iterator is exhausted */ + Py_ssize_t di_used; + Py_ssize_t di_pos; + PyObject* di_result; /* reusable result tuple for iteritems */ + Py_ssize_t len; } dictiterobject; static PyObject * dictiter_new(PyDictObject *dict, PyTypeObject *itertype) { - dictiterobject *di; - di = PyObject_GC_New(dictiterobject, itertype); - if (di == NULL) - return NULL; - Py_INCREF(dict); - di->di_dict = dict; - di->di_used = dict->ma_used; - di->di_pos = 0; - di->len = dict->ma_used; - if (itertype == &PyDictIterItem_Type) { - di->di_result = PyTuple_Pack(2, Py_None, Py_None); - if (di->di_result == NULL) { - Py_DECREF(di); - return NULL; - } - } - else - di->di_result = NULL; - _PyObject_GC_TRACK(di); - return (PyObject *)di; + dictiterobject *di; + di = PyObject_GC_New(dictiterobject, itertype); + if (di == NULL) + return NULL; + Py_INCREF(dict); + di->di_dict = dict; + di->di_used = dict->ma_used; + di->di_pos = 0; + di->len = dict->ma_used; + if (itertype == &PyDictIterItem_Type) { + di->di_result = PyTuple_Pack(2, Py_None, Py_None); + if (di->di_result == NULL) { + Py_DECREF(di); + return NULL; + } + } + else + di->di_result = NULL; + _PyObject_GC_TRACK(di); + return (PyObject *)di; } static void dictiter_dealloc(dictiterobject *di) { - Py_XDECREF(di->di_dict); - Py_XDECREF(di->di_result); - PyObject_GC_Del(di); + Py_XDECREF(di->di_dict); + Py_XDECREF(di->di_result); + PyObject_GC_Del(di); } static int dictiter_traverse(dictiterobject *di, visitproc visit, void *arg) { - Py_VISIT(di->di_dict); - Py_VISIT(di->di_result); - return 0; + Py_VISIT(di->di_dict); + Py_VISIT(di->di_result); + return 0; } static PyObject * dictiter_len(dictiterobject *di) { - Py_ssize_t len = 0; - if (di->di_dict != NULL && di->di_used == di->di_dict->ma_used) - len = di->len; - return PyLong_FromSize_t(len); + Py_ssize_t len = 0; + if (di->di_dict != NULL && di->di_used == di->di_dict->ma_used) + len = di->len; + return PyLong_FromSize_t(len); } PyDoc_STRVAR(length_hint_doc, "Private method returning an estimate of len(list(it))."); static PyMethodDef dictiter_methods[] = { - {"__length_hint__", (PyCFunction)dictiter_len, METH_NOARGS, - length_hint_doc}, - {NULL, NULL} /* sentinel */ + {"__length_hint__", (PyCFunction)dictiter_len, METH_NOARGS, + length_hint_doc}, + {NULL, NULL} /* sentinel */ }; static PyObject *dictiter_iternextkey(dictiterobject *di) { - PyObject *key; - register Py_ssize_t i, mask; - register PyDictEntry *ep; - PyDictObject *d = di->di_dict; - - if (d == NULL) - return NULL; - assert (PyDict_Check(d)); - - if (di->di_used != d->ma_used) { - PyErr_SetString(PyExc_RuntimeError, - "dictionary changed size during iteration"); - di->di_used = -1; /* Make this state sticky */ - return NULL; - } - - i = di->di_pos; - if (i < 0) - goto fail; - ep = d->ma_table; - mask = d->ma_mask; - while (i <= mask && ep[i].me_value == NULL) - i++; - di->di_pos = i+1; - if (i > mask) - goto fail; - di->len--; - key = ep[i].me_key; - Py_INCREF(key); - return key; + PyObject *key; + register Py_ssize_t i, mask; + register PyDictEntry *ep; + PyDictObject *d = di->di_dict; + + if (d == NULL) + return NULL; + assert (PyDict_Check(d)); + + if (di->di_used != d->ma_used) { + PyErr_SetString(PyExc_RuntimeError, + "dictionary changed size during iteration"); + di->di_used = -1; /* Make this state sticky */ + return NULL; + } + + i = di->di_pos; + if (i < 0) + goto fail; + ep = d->ma_table; + mask = d->ma_mask; + while (i <= mask && ep[i].me_value == NULL) + i++; + di->di_pos = i+1; + if (i > mask) + goto fail; + di->len--; + key = ep[i].me_key; + Py_INCREF(key); + return key; fail: - Py_DECREF(d); - di->di_dict = NULL; - return NULL; + Py_DECREF(d); + di->di_dict = NULL; + return NULL; } PyTypeObject PyDictIterKey_Type = { - PyVarObject_HEAD_INIT(&PyType_Type, 0) - "dict_keyiterator", /* tp_name */ - sizeof(dictiterobject), /* tp_basicsize */ - 0, /* tp_itemsize */ - /* methods */ - (destructor)dictiter_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)dictiter_traverse, /* tp_traverse */ - 0, /* tp_clear */ - 0, /* tp_richcompare */ - 0, /* tp_weaklistoffset */ - PyObject_SelfIter, /* tp_iter */ - (iternextfunc)dictiter_iternextkey, /* tp_iternext */ - dictiter_methods, /* tp_methods */ - 0, + PyVarObject_HEAD_INIT(&PyType_Type, 0) + "dict_keyiterator", /* tp_name */ + sizeof(dictiterobject), /* tp_basicsize */ + 0, /* tp_itemsize */ + /* methods */ + (destructor)dictiter_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)dictiter_traverse, /* tp_traverse */ + 0, /* tp_clear */ + 0, /* tp_richcompare */ + 0, /* tp_weaklistoffset */ + PyObject_SelfIter, /* tp_iter */ + (iternextfunc)dictiter_iternextkey, /* tp_iternext */ + dictiter_methods, /* tp_methods */ + 0, }; static PyObject *dictiter_iternextvalue(dictiterobject *di) { - PyObject *value; - register Py_ssize_t i, mask; - register PyDictEntry *ep; - PyDictObject *d = di->di_dict; - - if (d == NULL) - return NULL; - assert (PyDict_Check(d)); - - if (di->di_used != d->ma_used) { - PyErr_SetString(PyExc_RuntimeError, - "dictionary changed size during iteration"); - di->di_used = -1; /* Make this state sticky */ - return NULL; - } - - i = di->di_pos; - mask = d->ma_mask; - if (i < 0 || i > mask) - goto fail; - ep = d->ma_table; - while ((value=ep[i].me_value) == NULL) { - i++; - if (i > mask) - goto fail; - } - di->di_pos = i+1; - di->len--; - Py_INCREF(value); - return value; + PyObject *value; + register Py_ssize_t i, mask; + register PyDictEntry *ep; + PyDictObject *d = di->di_dict; + + if (d == NULL) + return NULL; + assert (PyDict_Check(d)); + + if (di->di_used != d->ma_used) { + PyErr_SetString(PyExc_RuntimeError, + "dictionary changed size during iteration"); + di->di_used = -1; /* Make this state sticky */ + return NULL; + } + + i = di->di_pos; + mask = d->ma_mask; + if (i < 0 || i > mask) + goto fail; + ep = d->ma_table; + while ((value=ep[i].me_value) == NULL) { + i++; + if (i > mask) + goto fail; + } + di->di_pos = i+1; + di->len--; + Py_INCREF(value); + return value; fail: - Py_DECREF(d); - di->di_dict = NULL; - return NULL; + Py_DECREF(d); + di->di_dict = NULL; + return NULL; } PyTypeObject PyDictIterValue_Type = { - PyVarObject_HEAD_INIT(&PyType_Type, 0) - "dict_valueiterator", /* tp_name */ - sizeof(dictiterobject), /* tp_basicsize */ - 0, /* tp_itemsize */ - /* methods */ - (destructor)dictiter_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)dictiter_traverse, /* tp_traverse */ - 0, /* tp_clear */ - 0, /* tp_richcompare */ - 0, /* tp_weaklistoffset */ - PyObject_SelfIter, /* tp_iter */ - (iternextfunc)dictiter_iternextvalue, /* tp_iternext */ - dictiter_methods, /* tp_methods */ - 0, + PyVarObject_HEAD_INIT(&PyType_Type, 0) + "dict_valueiterator", /* tp_name */ + sizeof(dictiterobject), /* tp_basicsize */ + 0, /* tp_itemsize */ + /* methods */ + (destructor)dictiter_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)dictiter_traverse, /* tp_traverse */ + 0, /* tp_clear */ + 0, /* tp_richcompare */ + 0, /* tp_weaklistoffset */ + PyObject_SelfIter, /* tp_iter */ + (iternextfunc)dictiter_iternextvalue, /* tp_iternext */ + dictiter_methods, /* tp_methods */ + 0, }; static PyObject *dictiter_iternextitem(dictiterobject *di) { - PyObject *key, *value, *result = di->di_result; - register Py_ssize_t i, mask; - register PyDictEntry *ep; - PyDictObject *d = di->di_dict; - - if (d == NULL) - return NULL; - assert (PyDict_Check(d)); - - if (di->di_used != d->ma_used) { - PyErr_SetString(PyExc_RuntimeError, - "dictionary changed size during iteration"); - di->di_used = -1; /* Make this state sticky */ - return NULL; - } - - i = di->di_pos; - if (i < 0) - goto fail; - ep = d->ma_table; - mask = d->ma_mask; - while (i <= mask && ep[i].me_value == NULL) - i++; - di->di_pos = i+1; - if (i > mask) - goto fail; - - if (result->ob_refcnt == 1) { - Py_INCREF(result); - Py_DECREF(PyTuple_GET_ITEM(result, 0)); - Py_DECREF(PyTuple_GET_ITEM(result, 1)); - } else { - result = PyTuple_New(2); - if (result == NULL) - return NULL; - } - di->len--; - key = ep[i].me_key; - value = ep[i].me_value; - Py_INCREF(key); - Py_INCREF(value); - PyTuple_SET_ITEM(result, 0, key); - PyTuple_SET_ITEM(result, 1, value); - return result; + PyObject *key, *value, *result = di->di_result; + register Py_ssize_t i, mask; + register PyDictEntry *ep; + PyDictObject *d = di->di_dict; + + if (d == NULL) + return NULL; + assert (PyDict_Check(d)); + + if (di->di_used != d->ma_used) { + PyErr_SetString(PyExc_RuntimeError, + "dictionary changed size during iteration"); + di->di_used = -1; /* Make this state sticky */ + return NULL; + } + + i = di->di_pos; + if (i < 0) + goto fail; + ep = d->ma_table; + mask = d->ma_mask; + while (i <= mask && ep[i].me_value == NULL) + i++; + di->di_pos = i+1; + if (i > mask) + goto fail; + + if (result->ob_refcnt == 1) { + Py_INCREF(result); + Py_DECREF(PyTuple_GET_ITEM(result, 0)); + Py_DECREF(PyTuple_GET_ITEM(result, 1)); + } else { + result = PyTuple_New(2); + if (result == NULL) + return NULL; + } + di->len--; + key = ep[i].me_key; + value = ep[i].me_value; + Py_INCREF(key); + Py_INCREF(value); + PyTuple_SET_ITEM(result, 0, key); + PyTuple_SET_ITEM(result, 1, value); + return result; fail: - Py_DECREF(d); - di->di_dict = NULL; - return NULL; + Py_DECREF(d); + di->di_dict = NULL; + return NULL; } PyTypeObject PyDictIterItem_Type = { - PyVarObject_HEAD_INIT(&PyType_Type, 0) - "dict_itemiterator", /* tp_name */ - sizeof(dictiterobject), /* tp_basicsize */ - 0, /* tp_itemsize */ - /* methods */ - (destructor)dictiter_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)dictiter_traverse, /* tp_traverse */ - 0, /* tp_clear */ - 0, /* tp_richcompare */ - 0, /* tp_weaklistoffset */ - PyObject_SelfIter, /* tp_iter */ - (iternextfunc)dictiter_iternextitem, /* tp_iternext */ - dictiter_methods, /* tp_methods */ - 0, + PyVarObject_HEAD_INIT(&PyType_Type, 0) + "dict_itemiterator", /* tp_name */ + sizeof(dictiterobject), /* tp_basicsize */ + 0, /* tp_itemsize */ + /* methods */ + (destructor)dictiter_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)dictiter_traverse, /* tp_traverse */ + 0, /* tp_clear */ + 0, /* tp_richcompare */ + 0, /* tp_weaklistoffset */ + PyObject_SelfIter, /* tp_iter */ + (iternextfunc)dictiter_iternextitem, /* tp_iternext */ + dictiter_methods, /* tp_methods */ + 0, }; @@ -2522,56 +2522,56 @@ /* The instance lay-out is the same for all three; but the type differs. */ typedef struct { - PyObject_HEAD - PyDictObject *dv_dict; + PyObject_HEAD + PyDictObject *dv_dict; } dictviewobject; static void dictview_dealloc(dictviewobject *dv) { - Py_XDECREF(dv->dv_dict); - PyObject_GC_Del(dv); + Py_XDECREF(dv->dv_dict); + PyObject_GC_Del(dv); } static int dictview_traverse(dictviewobject *dv, visitproc visit, void *arg) { - Py_VISIT(dv->dv_dict); - return 0; + Py_VISIT(dv->dv_dict); + return 0; } static Py_ssize_t dictview_len(dictviewobject *dv) { - Py_ssize_t len = 0; - if (dv->dv_dict != NULL) - len = dv->dv_dict->ma_used; - return len; + Py_ssize_t len = 0; + if (dv->dv_dict != NULL) + len = dv->dv_dict->ma_used; + return len; } static PyObject * dictview_new(PyObject *dict, PyTypeObject *type) { - dictviewobject *dv; - if (dict == NULL) { - PyErr_BadInternalCall(); - return NULL; - } - if (!PyDict_Check(dict)) { - /* XXX Get rid of this restriction later */ - PyErr_Format(PyExc_TypeError, - "%s() requires a dict argument, not '%s'", - type->tp_name, dict->ob_type->tp_name); - return NULL; - } - dv = PyObject_GC_New(dictviewobject, type); - if (dv == NULL) - return NULL; - Py_INCREF(dict); - dv->dv_dict = (PyDictObject *)dict; - _PyObject_GC_TRACK(dv); - return (PyObject *)dv; + dictviewobject *dv; + if (dict == NULL) { + PyErr_BadInternalCall(); + return NULL; + } + if (!PyDict_Check(dict)) { + /* XXX Get rid of this restriction later */ + PyErr_Format(PyExc_TypeError, + "%s() requires a dict argument, not '%s'", + type->tp_name, dict->ob_type->tp_name); + return NULL; + } + dv = PyObject_GC_New(dictviewobject, type); + if (dv == NULL) + return NULL; + Py_INCREF(dict); + dv->dv_dict = (PyDictObject *)dict; + _PyObject_GC_TRACK(dv); + return (PyObject *)dv; } /* TODO(guido): The views objects are not complete: @@ -2587,102 +2587,102 @@ static int all_contained_in(PyObject *self, PyObject *other) { - PyObject *iter = PyObject_GetIter(self); - int ok = 1; + PyObject *iter = PyObject_GetIter(self); + int ok = 1; - if (iter == NULL) - return -1; - for (;;) { - PyObject *next = PyIter_Next(iter); - if (next == NULL) { - if (PyErr_Occurred()) - ok = -1; - break; - } - ok = PySequence_Contains(other, next); - Py_DECREF(next); - if (ok <= 0) - break; - } - Py_DECREF(iter); - return ok; + if (iter == NULL) + return -1; + for (;;) { + PyObject *next = PyIter_Next(iter); + if (next == NULL) { + if (PyErr_Occurred()) + ok = -1; + break; + } + ok = PySequence_Contains(other, next); + Py_DECREF(next); + if (ok <= 0) + break; + } + Py_DECREF(iter); + return ok; } static PyObject * dictview_richcompare(PyObject *self, PyObject *other, int op) { - Py_ssize_t len_self, len_other; - int ok; - PyObject *result; - - assert(self != NULL); - assert(PyDictViewSet_Check(self)); - assert(other != NULL); - - if (!PyAnySet_Check(other) && !PyDictViewSet_Check(other)) { - Py_INCREF(Py_NotImplemented); - return Py_NotImplemented; - } - - len_self = PyObject_Size(self); - if (len_self < 0) - return NULL; - len_other = PyObject_Size(other); - if (len_other < 0) - return NULL; - - ok = 0; - switch(op) { - - case Py_NE: - case Py_EQ: - if (len_self == len_other) - ok = all_contained_in(self, other); - if (op == Py_NE && ok >= 0) - ok = !ok; - break; - - case Py_LT: - if (len_self < len_other) - ok = all_contained_in(self, other); - break; - - case Py_LE: - if (len_self <= len_other) - ok = all_contained_in(self, other); - break; - - case Py_GT: - if (len_self > len_other) - ok = all_contained_in(other, self); - break; - - case Py_GE: - if (len_self >= len_other) - ok = all_contained_in(other, self); - break; - - } - if (ok < 0) - return NULL; - result = ok ? Py_True : Py_False; - Py_INCREF(result); - return result; + Py_ssize_t len_self, len_other; + int ok; + PyObject *result; + + assert(self != NULL); + assert(PyDictViewSet_Check(self)); + assert(other != NULL); + + if (!PyAnySet_Check(other) && !PyDictViewSet_Check(other)) { + Py_INCREF(Py_NotImplemented); + return Py_NotImplemented; + } + + len_self = PyObject_Size(self); + if (len_self < 0) + return NULL; + len_other = PyObject_Size(other); + if (len_other < 0) + return NULL; + + ok = 0; + switch(op) { + + case Py_NE: + case Py_EQ: + if (len_self == len_other) + ok = all_contained_in(self, other); + if (op == Py_NE && ok >= 0) + ok = !ok; + break; + + case Py_LT: + if (len_self < len_other) + ok = all_contained_in(self, other); + break; + + case Py_LE: + if (len_self <= len_other) + ok = all_contained_in(self, other); + break; + + case Py_GT: + if (len_self > len_other) + ok = all_contained_in(other, self); + break; + + case Py_GE: + if (len_self >= len_other) + ok = all_contained_in(other, self); + break; + + } + if (ok < 0) + return NULL; + result = ok ? Py_True : Py_False; + Py_INCREF(result); + return result; } static PyObject * dictview_repr(dictviewobject *dv) { - PyObject *seq; - PyObject *result; - - seq = PySequence_List((PyObject *)dv); - if (seq == NULL) - return NULL; - - result = PyUnicode_FromFormat("%s(%R)", Py_TYPE(dv)->tp_name, seq); - Py_DECREF(seq); - return result; + PyObject *seq; + PyObject *result; + + seq = PySequence_List((PyObject *)dv); + if (seq == NULL) + return NULL; + + result = PyUnicode_FromFormat("%s(%R)", Py_TYPE(dv)->tp_name, seq); + Py_DECREF(seq); + return result; } /*** dict_keys ***/ @@ -2690,164 +2690,164 @@ static PyObject * dictkeys_iter(dictviewobject *dv) { - if (dv->dv_dict == NULL) { - Py_RETURN_NONE; - } - return dictiter_new(dv->dv_dict, &PyDictIterKey_Type); + if (dv->dv_dict == NULL) { + Py_RETURN_NONE; + } + return dictiter_new(dv->dv_dict, &PyDictIterKey_Type); } static int dictkeys_contains(dictviewobject *dv, PyObject *obj) { - if (dv->dv_dict == NULL) - return 0; - return PyDict_Contains((PyObject *)dv->dv_dict, obj); + if (dv->dv_dict == NULL) + return 0; + return PyDict_Contains((PyObject *)dv->dv_dict, obj); } static PySequenceMethods dictkeys_as_sequence = { - (lenfunc)dictview_len, /* sq_length */ - 0, /* sq_concat */ - 0, /* sq_repeat */ - 0, /* sq_item */ - 0, /* sq_slice */ - 0, /* sq_ass_item */ - 0, /* sq_ass_slice */ - (objobjproc)dictkeys_contains, /* sq_contains */ + (lenfunc)dictview_len, /* sq_length */ + 0, /* sq_concat */ + 0, /* sq_repeat */ + 0, /* sq_item */ + 0, /* sq_slice */ + 0, /* sq_ass_item */ + 0, /* sq_ass_slice */ + (objobjproc)dictkeys_contains, /* sq_contains */ }; static PyObject* dictviews_sub(PyObject* self, PyObject *other) { - PyObject *result = PySet_New(self); - PyObject *tmp; - if (result == NULL) - return NULL; - - tmp = PyObject_CallMethod(result, "difference_update", "O", other); - if (tmp == NULL) { - Py_DECREF(result); - return NULL; - } + PyObject *result = PySet_New(self); + PyObject *tmp; + if (result == NULL) + return NULL; + + tmp = PyObject_CallMethod(result, "difference_update", "O", other); + if (tmp == NULL) { + Py_DECREF(result); + return NULL; + } - Py_DECREF(tmp); - return result; + Py_DECREF(tmp); + return result; } static PyObject* dictviews_and(PyObject* self, PyObject *other) { - PyObject *result = PySet_New(self); - PyObject *tmp; - if (result == NULL) - return NULL; - - tmp = PyObject_CallMethod(result, "intersection_update", "O", other); - if (tmp == NULL) { - Py_DECREF(result); - return NULL; - } + PyObject *result = PySet_New(self); + PyObject *tmp; + if (result == NULL) + return NULL; + + tmp = PyObject_CallMethod(result, "intersection_update", "O", other); + if (tmp == NULL) { + Py_DECREF(result); + return NULL; + } - Py_DECREF(tmp); - return result; + Py_DECREF(tmp); + return result; } static PyObject* dictviews_or(PyObject* self, PyObject *other) { - PyObject *result = PySet_New(self); - PyObject *tmp; - if (result == NULL) - return NULL; - - tmp = PyObject_CallMethod(result, "update", "O", other); - if (tmp == NULL) { - Py_DECREF(result); - return NULL; - } + PyObject *result = PySet_New(self); + PyObject *tmp; + if (result == NULL) + return NULL; + + tmp = PyObject_CallMethod(result, "update", "O", other); + if (tmp == NULL) { + Py_DECREF(result); + return NULL; + } - Py_DECREF(tmp); - return result; + Py_DECREF(tmp); + return result; } static PyObject* dictviews_xor(PyObject* self, PyObject *other) { - PyObject *result = PySet_New(self); - PyObject *tmp; - if (result == NULL) - return NULL; - - tmp = PyObject_CallMethod(result, "symmetric_difference_update", "O", - other); - if (tmp == NULL) { - Py_DECREF(result); - return NULL; - } + PyObject *result = PySet_New(self); + PyObject *tmp; + if (result == NULL) + return NULL; + + tmp = PyObject_CallMethod(result, "symmetric_difference_update", "O", + other); + if (tmp == NULL) { + Py_DECREF(result); + return NULL; + } - Py_DECREF(tmp); - return result; + Py_DECREF(tmp); + return result; } static PyNumberMethods dictviews_as_number = { - 0, /*nb_add*/ - (binaryfunc)dictviews_sub, /*nb_subtract*/ - 0, /*nb_multiply*/ - 0, /*nb_remainder*/ - 0, /*nb_divmod*/ - 0, /*nb_power*/ - 0, /*nb_negative*/ - 0, /*nb_positive*/ - 0, /*nb_absolute*/ - 0, /*nb_bool*/ - 0, /*nb_invert*/ - 0, /*nb_lshift*/ - 0, /*nb_rshift*/ - (binaryfunc)dictviews_and, /*nb_and*/ - (binaryfunc)dictviews_xor, /*nb_xor*/ - (binaryfunc)dictviews_or, /*nb_or*/ + 0, /*nb_add*/ + (binaryfunc)dictviews_sub, /*nb_subtract*/ + 0, /*nb_multiply*/ + 0, /*nb_remainder*/ + 0, /*nb_divmod*/ + 0, /*nb_power*/ + 0, /*nb_negative*/ + 0, /*nb_positive*/ + 0, /*nb_absolute*/ + 0, /*nb_bool*/ + 0, /*nb_invert*/ + 0, /*nb_lshift*/ + 0, /*nb_rshift*/ + (binaryfunc)dictviews_and, /*nb_and*/ + (binaryfunc)dictviews_xor, /*nb_xor*/ + (binaryfunc)dictviews_or, /*nb_or*/ }; static PyMethodDef dictkeys_methods[] = { - {NULL, NULL} /* sentinel */ + {NULL, NULL} /* sentinel */ }; PyTypeObject PyDictKeys_Type = { - PyVarObject_HEAD_INIT(&PyType_Type, 0) - "dict_keys", /* tp_name */ - sizeof(dictviewobject), /* tp_basicsize */ - 0, /* tp_itemsize */ - /* methods */ - (destructor)dictview_dealloc, /* tp_dealloc */ - 0, /* tp_print */ - 0, /* tp_getattr */ - 0, /* tp_setattr */ - 0, /* tp_reserved */ - (reprfunc)dictview_repr, /* tp_repr */ - &dictviews_as_number, /* tp_as_number */ - &dictkeys_as_sequence, /* 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)dictview_traverse, /* tp_traverse */ - 0, /* tp_clear */ - dictview_richcompare, /* tp_richcompare */ - 0, /* tp_weaklistoffset */ - (getiterfunc)dictkeys_iter, /* tp_iter */ - 0, /* tp_iternext */ - dictkeys_methods, /* tp_methods */ - 0, + PyVarObject_HEAD_INIT(&PyType_Type, 0) + "dict_keys", /* tp_name */ + sizeof(dictviewobject), /* tp_basicsize */ + 0, /* tp_itemsize */ + /* methods */ + (destructor)dictview_dealloc, /* tp_dealloc */ + 0, /* tp_print */ + 0, /* tp_getattr */ + 0, /* tp_setattr */ + 0, /* tp_reserved */ + (reprfunc)dictview_repr, /* tp_repr */ + &dictviews_as_number, /* tp_as_number */ + &dictkeys_as_sequence, /* 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)dictview_traverse, /* tp_traverse */ + 0, /* tp_clear */ + dictview_richcompare, /* tp_richcompare */ + 0, /* tp_weaklistoffset */ + (getiterfunc)dictkeys_iter, /* tp_iter */ + 0, /* tp_iternext */ + dictkeys_methods, /* tp_methods */ + 0, }; static PyObject * dictkeys_new(PyObject *dict) { - return dictview_new(dict, &PyDictKeys_Type); + return dictview_new(dict, &PyDictKeys_Type); } /*** dict_items ***/ @@ -2855,83 +2855,83 @@ static PyObject * dictitems_iter(dictviewobject *dv) { - if (dv->dv_dict == NULL) { - Py_RETURN_NONE; - } - return dictiter_new(dv->dv_dict, &PyDictIterItem_Type); + if (dv->dv_dict == NULL) { + Py_RETURN_NONE; + } + return dictiter_new(dv->dv_dict, &PyDictIterItem_Type); } static int dictitems_contains(dictviewobject *dv, PyObject *obj) { - PyObject *key, *value, *found; - if (dv->dv_dict == NULL) - return 0; - if (!PyTuple_Check(obj) || PyTuple_GET_SIZE(obj) != 2) - return 0; - key = PyTuple_GET_ITEM(obj, 0); - value = PyTuple_GET_ITEM(obj, 1); - found = PyDict_GetItem((PyObject *)dv->dv_dict, key); - if (found == NULL) { - if (PyErr_Occurred()) - return -1; - return 0; - } - return PyObject_RichCompareBool(value, found, Py_EQ); + PyObject *key, *value, *found; + if (dv->dv_dict == NULL) + return 0; + if (!PyTuple_Check(obj) || PyTuple_GET_SIZE(obj) != 2) + return 0; + key = PyTuple_GET_ITEM(obj, 0); + value = PyTuple_GET_ITEM(obj, 1); + found = PyDict_GetItem((PyObject *)dv->dv_dict, key); + if (found == NULL) { + if (PyErr_Occurred()) + return -1; + return 0; + } + return PyObject_RichCompareBool(value, found, Py_EQ); } static PySequenceMethods dictitems_as_sequence = { - (lenfunc)dictview_len, /* sq_length */ - 0, /* sq_concat */ - 0, /* sq_repeat */ - 0, /* sq_item */ - 0, /* sq_slice */ - 0, /* sq_ass_item */ - 0, /* sq_ass_slice */ - (objobjproc)dictitems_contains, /* sq_contains */ + (lenfunc)dictview_len, /* sq_length */ + 0, /* sq_concat */ + 0, /* sq_repeat */ + 0, /* sq_item */ + 0, /* sq_slice */ + 0, /* sq_ass_item */ + 0, /* sq_ass_slice */ + (objobjproc)dictitems_contains, /* sq_contains */ }; static PyMethodDef dictitems_methods[] = { - {NULL, NULL} /* sentinel */ + {NULL, NULL} /* sentinel */ }; PyTypeObject PyDictItems_Type = { - PyVarObject_HEAD_INIT(&PyType_Type, 0) - "dict_items", /* tp_name */ - sizeof(dictviewobject), /* tp_basicsize */ - 0, /* tp_itemsize */ - /* methods */ - (destructor)dictview_dealloc, /* tp_dealloc */ - 0, /* tp_print */ - 0, /* tp_getattr */ - 0, /* tp_setattr */ - 0, /* tp_reserved */ - (reprfunc)dictview_repr, /* tp_repr */ - &dictviews_as_number, /* tp_as_number */ - &dictitems_as_sequence, /* 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)dictview_traverse, /* tp_traverse */ - 0, /* tp_clear */ - dictview_richcompare, /* tp_richcompare */ - 0, /* tp_weaklistoffset */ - (getiterfunc)dictitems_iter, /* tp_iter */ - 0, /* tp_iternext */ - dictitems_methods, /* tp_methods */ - 0, + PyVarObject_HEAD_INIT(&PyType_Type, 0) + "dict_items", /* tp_name */ + sizeof(dictviewobject), /* tp_basicsize */ + 0, /* tp_itemsize */ + /* methods */ + (destructor)dictview_dealloc, /* tp_dealloc */ + 0, /* tp_print */ + 0, /* tp_getattr */ + 0, /* tp_setattr */ + 0, /* tp_reserved */ + (reprfunc)dictview_repr, /* tp_repr */ + &dictviews_as_number, /* tp_as_number */ + &dictitems_as_sequence, /* 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)dictview_traverse, /* tp_traverse */ + 0, /* tp_clear */ + dictview_richcompare, /* tp_richcompare */ + 0, /* tp_weaklistoffset */ + (getiterfunc)dictitems_iter, /* tp_iter */ + 0, /* tp_iternext */ + dictitems_methods, /* tp_methods */ + 0, }; static PyObject * dictitems_new(PyObject *dict) { - return dictview_new(dict, &PyDictItems_Type); + return dictview_new(dict, &PyDictItems_Type); } /*** dict_values ***/ @@ -2939,62 +2939,62 @@ static PyObject * dictvalues_iter(dictviewobject *dv) { - if (dv->dv_dict == NULL) { - Py_RETURN_NONE; - } - return dictiter_new(dv->dv_dict, &PyDictIterValue_Type); + if (dv->dv_dict == NULL) { + Py_RETURN_NONE; + } + return dictiter_new(dv->dv_dict, &PyDictIterValue_Type); } static PySequenceMethods dictvalues_as_sequence = { - (lenfunc)dictview_len, /* sq_length */ - 0, /* sq_concat */ - 0, /* sq_repeat */ - 0, /* sq_item */ - 0, /* sq_slice */ - 0, /* sq_ass_item */ - 0, /* sq_ass_slice */ - (objobjproc)0, /* sq_contains */ + (lenfunc)dictview_len, /* sq_length */ + 0, /* sq_concat */ + 0, /* sq_repeat */ + 0, /* sq_item */ + 0, /* sq_slice */ + 0, /* sq_ass_item */ + 0, /* sq_ass_slice */ + (objobjproc)0, /* sq_contains */ }; static PyMethodDef dictvalues_methods[] = { - {NULL, NULL} /* sentinel */ + {NULL, NULL} /* sentinel */ }; PyTypeObject PyDictValues_Type = { - PyVarObject_HEAD_INIT(&PyType_Type, 0) - "dict_values", /* tp_name */ - sizeof(dictviewobject), /* tp_basicsize */ - 0, /* tp_itemsize */ - /* methods */ - (destructor)dictview_dealloc, /* tp_dealloc */ - 0, /* tp_print */ - 0, /* tp_getattr */ - 0, /* tp_setattr */ - 0, /* tp_reserved */ - (reprfunc)dictview_repr, /* tp_repr */ - 0, /* tp_as_number */ - &dictvalues_as_sequence, /* 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)dictview_traverse, /* tp_traverse */ - 0, /* tp_clear */ - 0, /* tp_richcompare */ - 0, /* tp_weaklistoffset */ - (getiterfunc)dictvalues_iter, /* tp_iter */ - 0, /* tp_iternext */ - dictvalues_methods, /* tp_methods */ - 0, + PyVarObject_HEAD_INIT(&PyType_Type, 0) + "dict_values", /* tp_name */ + sizeof(dictviewobject), /* tp_basicsize */ + 0, /* tp_itemsize */ + /* methods */ + (destructor)dictview_dealloc, /* tp_dealloc */ + 0, /* tp_print */ + 0, /* tp_getattr */ + 0, /* tp_setattr */ + 0, /* tp_reserved */ + (reprfunc)dictview_repr, /* tp_repr */ + 0, /* tp_as_number */ + &dictvalues_as_sequence, /* 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)dictview_traverse, /* tp_traverse */ + 0, /* tp_clear */ + 0, /* tp_richcompare */ + 0, /* tp_weaklistoffset */ + (getiterfunc)dictvalues_iter, /* tp_iter */ + 0, /* tp_iternext */ + dictvalues_methods, /* tp_methods */ + 0, }; static PyObject * dictvalues_new(PyObject *dict) { - return dictview_new(dict, &PyDictValues_Type); + return dictview_new(dict, &PyDictValues_Type); } Modified: python/branches/py3k/Objects/enumobject.c ============================================================================== --- python/branches/py3k/Objects/enumobject.c (original) +++ python/branches/py3k/Objects/enumobject.c Sun May 9 17:52:27 2010 @@ -3,159 +3,159 @@ #include "Python.h" typedef struct { - PyObject_HEAD - Py_ssize_t en_index; /* current index of enumeration */ - PyObject* en_sit; /* secondary iterator of enumeration */ - PyObject* en_result; /* result tuple */ - PyObject* en_longindex; /* index for sequences >= PY_SSIZE_T_MAX */ + PyObject_HEAD + Py_ssize_t en_index; /* current index of enumeration */ + PyObject* en_sit; /* secondary iterator of enumeration */ + PyObject* en_result; /* result tuple */ + PyObject* en_longindex; /* index for sequences >= PY_SSIZE_T_MAX */ } enumobject; static PyObject * enum_new(PyTypeObject *type, PyObject *args, PyObject *kwds) { - enumobject *en; - PyObject *seq = NULL; - PyObject *start = NULL; - static char *kwlist[] = {"iterable", "start", 0}; - - if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|O:enumerate", kwlist, - &seq, &start)) - return NULL; - - en = (enumobject *)type->tp_alloc(type, 0); - if (en == NULL) - return NULL; - if (start != NULL) { - start = PyNumber_Index(start); - if (start == NULL) { - Py_DECREF(en); - return NULL; - } - assert(PyLong_Check(start)); - en->en_index = PyLong_AsSsize_t(start); - if (en->en_index == -1 && PyErr_Occurred()) { - PyErr_Clear(); - en->en_index = PY_SSIZE_T_MAX; - en->en_longindex = start; - } else { - en->en_longindex = NULL; - Py_DECREF(start); - } - } else { - en->en_index = 0; - en->en_longindex = NULL; - } - en->en_sit = PyObject_GetIter(seq); - if (en->en_sit == NULL) { - Py_DECREF(en); - return NULL; - } - en->en_result = PyTuple_Pack(2, Py_None, Py_None); - if (en->en_result == NULL) { - Py_DECREF(en); - return NULL; - } - return (PyObject *)en; + enumobject *en; + PyObject *seq = NULL; + PyObject *start = NULL; + static char *kwlist[] = {"iterable", "start", 0}; + + if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|O:enumerate", kwlist, + &seq, &start)) + return NULL; + + en = (enumobject *)type->tp_alloc(type, 0); + if (en == NULL) + return NULL; + if (start != NULL) { + start = PyNumber_Index(start); + if (start == NULL) { + Py_DECREF(en); + return NULL; + } + assert(PyLong_Check(start)); + en->en_index = PyLong_AsSsize_t(start); + if (en->en_index == -1 && PyErr_Occurred()) { + PyErr_Clear(); + en->en_index = PY_SSIZE_T_MAX; + en->en_longindex = start; + } else { + en->en_longindex = NULL; + Py_DECREF(start); + } + } else { + en->en_index = 0; + en->en_longindex = NULL; + } + en->en_sit = PyObject_GetIter(seq); + if (en->en_sit == NULL) { + Py_DECREF(en); + return NULL; + } + en->en_result = PyTuple_Pack(2, Py_None, Py_None); + if (en->en_result == NULL) { + Py_DECREF(en); + return NULL; + } + return (PyObject *)en; } static void enum_dealloc(enumobject *en) { - PyObject_GC_UnTrack(en); - Py_XDECREF(en->en_sit); - Py_XDECREF(en->en_result); - Py_XDECREF(en->en_longindex); - Py_TYPE(en)->tp_free(en); + PyObject_GC_UnTrack(en); + Py_XDECREF(en->en_sit); + Py_XDECREF(en->en_result); + Py_XDECREF(en->en_longindex); + Py_TYPE(en)->tp_free(en); } static int enum_traverse(enumobject *en, visitproc visit, void *arg) { - Py_VISIT(en->en_sit); - Py_VISIT(en->en_result); - Py_VISIT(en->en_longindex); - return 0; + Py_VISIT(en->en_sit); + Py_VISIT(en->en_result); + Py_VISIT(en->en_longindex); + return 0; } static PyObject * enum_next_long(enumobject *en, PyObject* next_item) { - static PyObject *one = NULL; - PyObject *result = en->en_result; - PyObject *next_index; - PyObject *stepped_up; - - if (en->en_longindex == NULL) { - en->en_longindex = PyLong_FromSsize_t(PY_SSIZE_T_MAX); - if (en->en_longindex == NULL) - return NULL; - } - if (one == NULL) { - one = PyLong_FromLong(1); - if (one == NULL) - return NULL; - } - next_index = en->en_longindex; - assert(next_index != NULL); - stepped_up = PyNumber_Add(next_index, one); - if (stepped_up == NULL) - return NULL; - en->en_longindex = stepped_up; - - if (result->ob_refcnt == 1) { - Py_INCREF(result); - Py_DECREF(PyTuple_GET_ITEM(result, 0)); - Py_DECREF(PyTuple_GET_ITEM(result, 1)); - } else { - result = PyTuple_New(2); - if (result == NULL) { - Py_DECREF(next_index); - Py_DECREF(next_item); - return NULL; - } - } - PyTuple_SET_ITEM(result, 0, next_index); - PyTuple_SET_ITEM(result, 1, next_item); - return result; + static PyObject *one = NULL; + PyObject *result = en->en_result; + PyObject *next_index; + PyObject *stepped_up; + + if (en->en_longindex == NULL) { + en->en_longindex = PyLong_FromSsize_t(PY_SSIZE_T_MAX); + if (en->en_longindex == NULL) + return NULL; + } + if (one == NULL) { + one = PyLong_FromLong(1); + if (one == NULL) + return NULL; + } + next_index = en->en_longindex; + assert(next_index != NULL); + stepped_up = PyNumber_Add(next_index, one); + if (stepped_up == NULL) + return NULL; + en->en_longindex = stepped_up; + + if (result->ob_refcnt == 1) { + Py_INCREF(result); + Py_DECREF(PyTuple_GET_ITEM(result, 0)); + Py_DECREF(PyTuple_GET_ITEM(result, 1)); + } else { + result = PyTuple_New(2); + if (result == NULL) { + Py_DECREF(next_index); + Py_DECREF(next_item); + return NULL; + } + } + PyTuple_SET_ITEM(result, 0, next_index); + PyTuple_SET_ITEM(result, 1, next_item); + return result; } static PyObject * enum_next(enumobject *en) { - PyObject *next_index; - PyObject *next_item; - PyObject *result = en->en_result; - PyObject *it = en->en_sit; - - next_item = (*Py_TYPE(it)->tp_iternext)(it); - if (next_item == NULL) - return NULL; - - if (en->en_index == PY_SSIZE_T_MAX) - return enum_next_long(en, next_item); - - next_index = PyLong_FromSsize_t(en->en_index); - if (next_index == NULL) { - Py_DECREF(next_item); - return NULL; - } - en->en_index++; - - if (result->ob_refcnt == 1) { - Py_INCREF(result); - Py_DECREF(PyTuple_GET_ITEM(result, 0)); - Py_DECREF(PyTuple_GET_ITEM(result, 1)); - } else { - result = PyTuple_New(2); - if (result == NULL) { - Py_DECREF(next_index); - Py_DECREF(next_item); - return NULL; - } - } - PyTuple_SET_ITEM(result, 0, next_index); - PyTuple_SET_ITEM(result, 1, next_item); - return result; + PyObject *next_index; + PyObject *next_item; + PyObject *result = en->en_result; + PyObject *it = en->en_sit; + + next_item = (*Py_TYPE(it)->tp_iternext)(it); + if (next_item == NULL) + return NULL; + + if (en->en_index == PY_SSIZE_T_MAX) + return enum_next_long(en, next_item); + + next_index = PyLong_FromSsize_t(en->en_index); + if (next_index == NULL) { + Py_DECREF(next_item); + return NULL; + } + en->en_index++; + + if (result->ob_refcnt == 1) { + Py_INCREF(result); + Py_DECREF(PyTuple_GET_ITEM(result, 0)); + Py_DECREF(PyTuple_GET_ITEM(result, 1)); + } else { + result = PyTuple_New(2); + if (result == NULL) { + Py_DECREF(next_index); + Py_DECREF(next_item); + return NULL; + } + } + PyTuple_SET_ITEM(result, 0, next_index); + PyTuple_SET_ITEM(result, 1, next_item); + return result; } PyDoc_STRVAR(enum_doc, @@ -167,134 +167,134 @@ "for obtaining an indexed list: (0, seq[0]), (1, seq[1]), (2, seq[2]), ..."); PyTypeObject PyEnum_Type = { - PyVarObject_HEAD_INIT(&PyType_Type, 0) - "enumerate", /* tp_name */ - sizeof(enumobject), /* tp_basicsize */ - 0, /* tp_itemsize */ - /* methods */ - (destructor)enum_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 | - Py_TPFLAGS_BASETYPE, /* tp_flags */ - enum_doc, /* tp_doc */ - (traverseproc)enum_traverse, /* tp_traverse */ - 0, /* tp_clear */ - 0, /* tp_richcompare */ - 0, /* tp_weaklistoffset */ - PyObject_SelfIter, /* tp_iter */ - (iternextfunc)enum_next, /* tp_iternext */ - 0, /* tp_methods */ - 0, /* tp_members */ - 0, /* tp_getset */ - 0, /* tp_base */ - 0, /* tp_dict */ - 0, /* tp_descr_get */ - 0, /* tp_descr_set */ - 0, /* tp_dictoffset */ - 0, /* tp_init */ - PyType_GenericAlloc, /* tp_alloc */ - enum_new, /* tp_new */ - PyObject_GC_Del, /* tp_free */ + PyVarObject_HEAD_INIT(&PyType_Type, 0) + "enumerate", /* tp_name */ + sizeof(enumobject), /* tp_basicsize */ + 0, /* tp_itemsize */ + /* methods */ + (destructor)enum_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 | + Py_TPFLAGS_BASETYPE, /* tp_flags */ + enum_doc, /* tp_doc */ + (traverseproc)enum_traverse, /* tp_traverse */ + 0, /* tp_clear */ + 0, /* tp_richcompare */ + 0, /* tp_weaklistoffset */ + PyObject_SelfIter, /* tp_iter */ + (iternextfunc)enum_next, /* tp_iternext */ + 0, /* tp_methods */ + 0, /* tp_members */ + 0, /* tp_getset */ + 0, /* tp_base */ + 0, /* tp_dict */ + 0, /* tp_descr_get */ + 0, /* tp_descr_set */ + 0, /* tp_dictoffset */ + 0, /* tp_init */ + PyType_GenericAlloc, /* tp_alloc */ + enum_new, /* tp_new */ + PyObject_GC_Del, /* tp_free */ }; /* Reversed Object ***************************************************************/ typedef struct { - PyObject_HEAD - Py_ssize_t index; - PyObject* seq; + PyObject_HEAD + Py_ssize_t index; + PyObject* seq; } reversedobject; static PyObject * reversed_new(PyTypeObject *type, PyObject *args, PyObject *kwds) { - Py_ssize_t n; - PyObject *seq, *reversed_meth; - static PyObject *reversed_cache = NULL; - reversedobject *ro; - - if (type == &PyReversed_Type && !_PyArg_NoKeywords("reversed()", kwds)) - return NULL; - - if (!PyArg_UnpackTuple(args, "reversed", 1, 1, &seq) ) - return NULL; - - reversed_meth = _PyObject_LookupSpecial(seq, "__reversed__", &reversed_cache); - if (reversed_meth != NULL) { - PyObject *res = PyObject_CallFunctionObjArgs(reversed_meth, NULL); - Py_DECREF(reversed_meth); - return res; - } - else if (PyErr_Occurred()) - return NULL; - - if (!PySequence_Check(seq)) { - PyErr_SetString(PyExc_TypeError, - "argument to reversed() must be a sequence"); - return NULL; - } - - n = PySequence_Size(seq); - if (n == -1) - return NULL; - - ro = (reversedobject *)type->tp_alloc(type, 0); - if (ro == NULL) - return NULL; - - ro->index = n-1; - Py_INCREF(seq); - ro->seq = seq; - return (PyObject *)ro; + Py_ssize_t n; + PyObject *seq, *reversed_meth; + static PyObject *reversed_cache = NULL; + reversedobject *ro; + + if (type == &PyReversed_Type && !_PyArg_NoKeywords("reversed()", kwds)) + return NULL; + + if (!PyArg_UnpackTuple(args, "reversed", 1, 1, &seq) ) + return NULL; + + reversed_meth = _PyObject_LookupSpecial(seq, "__reversed__", &reversed_cache); + if (reversed_meth != NULL) { + PyObject *res = PyObject_CallFunctionObjArgs(reversed_meth, NULL); + Py_DECREF(reversed_meth); + return res; + } + else if (PyErr_Occurred()) + return NULL; + + if (!PySequence_Check(seq)) { + PyErr_SetString(PyExc_TypeError, + "argument to reversed() must be a sequence"); + return NULL; + } + + n = PySequence_Size(seq); + if (n == -1) + return NULL; + + ro = (reversedobject *)type->tp_alloc(type, 0); + if (ro == NULL) + return NULL; + + ro->index = n-1; + Py_INCREF(seq); + ro->seq = seq; + return (PyObject *)ro; } static void reversed_dealloc(reversedobject *ro) { - PyObject_GC_UnTrack(ro); - Py_XDECREF(ro->seq); - Py_TYPE(ro)->tp_free(ro); + PyObject_GC_UnTrack(ro); + Py_XDECREF(ro->seq); + Py_TYPE(ro)->tp_free(ro); } static int reversed_traverse(reversedobject *ro, visitproc visit, void *arg) { - Py_VISIT(ro->seq); - return 0; + Py_VISIT(ro->seq); + return 0; } static PyObject * reversed_next(reversedobject *ro) { - PyObject *item; - Py_ssize_t index = ro->index; + PyObject *item; + Py_ssize_t index = ro->index; - if (index >= 0) { - item = PySequence_GetItem(ro->seq, index); - if (item != NULL) { - ro->index--; - return item; - } - if (PyErr_ExceptionMatches(PyExc_IndexError) || - PyErr_ExceptionMatches(PyExc_StopIteration)) - PyErr_Clear(); - } - ro->index = -1; - Py_CLEAR(ro->seq); - return NULL; + if (index >= 0) { + item = PySequence_GetItem(ro->seq, index); + if (item != NULL) { + ro->index--; + return item; + } + if (PyErr_ExceptionMatches(PyExc_IndexError) || + PyErr_ExceptionMatches(PyExc_StopIteration)) + PyErr_Clear(); + } + ro->index = -1; + Py_CLEAR(ro->seq); + return NULL; } PyDoc_STRVAR(reversed_doc, @@ -305,64 +305,64 @@ static PyObject * reversed_len(reversedobject *ro) { - Py_ssize_t position, seqsize; + Py_ssize_t position, seqsize; - if (ro->seq == NULL) - return PyLong_FromLong(0); - seqsize = PySequence_Size(ro->seq); - if (seqsize == -1) - return NULL; - position = ro->index + 1; - return PyLong_FromSsize_t((seqsize < position) ? 0 : position); + if (ro->seq == NULL) + return PyLong_FromLong(0); + seqsize = PySequence_Size(ro->seq); + if (seqsize == -1) + return NULL; + position = ro->index + 1; + return PyLong_FromSsize_t((seqsize < position) ? 0 : position); } PyDoc_STRVAR(length_hint_doc, "Private method returning an estimate of len(list(it))."); static PyMethodDef reversediter_methods[] = { - {"__length_hint__", (PyCFunction)reversed_len, METH_NOARGS, length_hint_doc}, - {NULL, NULL} /* sentinel */ + {"__length_hint__", (PyCFunction)reversed_len, METH_NOARGS, length_hint_doc}, + {NULL, NULL} /* sentinel */ }; PyTypeObject PyReversed_Type = { - PyVarObject_HEAD_INIT(&PyType_Type, 0) - "reversed", /* tp_name */ - sizeof(reversedobject), /* tp_basicsize */ - 0, /* tp_itemsize */ - /* methods */ - (destructor)reversed_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 | - Py_TPFLAGS_BASETYPE, /* tp_flags */ - reversed_doc, /* tp_doc */ - (traverseproc)reversed_traverse,/* tp_traverse */ - 0, /* tp_clear */ - 0, /* tp_richcompare */ - 0, /* tp_weaklistoffset */ - PyObject_SelfIter, /* tp_iter */ - (iternextfunc)reversed_next, /* tp_iternext */ - reversediter_methods, /* tp_methods */ - 0, /* tp_members */ - 0, /* tp_getset */ - 0, /* tp_base */ - 0, /* tp_dict */ - 0, /* tp_descr_get */ - 0, /* tp_descr_set */ - 0, /* tp_dictoffset */ - 0, /* tp_init */ - PyType_GenericAlloc, /* tp_alloc */ - reversed_new, /* tp_new */ - PyObject_GC_Del, /* tp_free */ + PyVarObject_HEAD_INIT(&PyType_Type, 0) + "reversed", /* tp_name */ + sizeof(reversedobject), /* tp_basicsize */ + 0, /* tp_itemsize */ + /* methods */ + (destructor)reversed_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 | + Py_TPFLAGS_BASETYPE, /* tp_flags */ + reversed_doc, /* tp_doc */ + (traverseproc)reversed_traverse,/* tp_traverse */ + 0, /* tp_clear */ + 0, /* tp_richcompare */ + 0, /* tp_weaklistoffset */ + PyObject_SelfIter, /* tp_iter */ + (iternextfunc)reversed_next, /* tp_iternext */ + reversediter_methods, /* tp_methods */ + 0, /* tp_members */ + 0, /* tp_getset */ + 0, /* tp_base */ + 0, /* tp_dict */ + 0, /* tp_descr_get */ + 0, /* tp_descr_set */ + 0, /* tp_dictoffset */ + 0, /* tp_init */ + PyType_GenericAlloc, /* tp_alloc */ + reversed_new, /* tp_new */ + PyObject_GC_Del, /* tp_free */ }; Modified: python/branches/py3k/Objects/exceptions.c ============================================================================== --- python/branches/py3k/Objects/exceptions.c (original) +++ python/branches/py3k/Objects/exceptions.c Sun May 9 17:52:27 2010 @@ -270,7 +270,7 @@ } else { /* PyException_SetContext steals this reference */ Py_INCREF(arg); - } + } PyException_SetContext(self, arg); return 0; } @@ -296,7 +296,7 @@ } else { /* PyException_SetCause steals this reference */ Py_INCREF(arg); - } + } PyException_SetCause(self, arg); return 0; } @@ -379,7 +379,7 @@ PyObject_GenericSetAttr, /*tp_setattro*/ 0, /*tp_as_buffer*/ Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC | - Py_TPFLAGS_BASE_EXC_SUBCLASS, /*tp_flags*/ + Py_TPFLAGS_BASE_EXC_SUBCLASS, /*tp_flags*/ PyDoc_STR("Common base class for all exceptions"), /* tp_doc */ (traverseproc)BaseException_traverse, /* tp_traverse */ (inquiry)BaseException_clear, /* tp_clear */ @@ -1013,7 +1013,7 @@ result = PyUnicode_FromFormat("%S (%U, line %ld)", self->msg ? self->msg : Py_None, filename, - PyLong_AsLongAndOverflow(self->lineno, &overflow)); + PyLong_AsLongAndOverflow(self->lineno, &overflow)); else if (filename) result = PyUnicode_FromFormat("%S (%U)", self->msg ? self->msg : Py_None, @@ -2011,25 +2011,25 @@ PyExc_RecursionErrorInst = BaseException_new(&_PyExc_RuntimeError, NULL, NULL); if (!PyExc_RecursionErrorInst) - Py_FatalError("Cannot pre-allocate RuntimeError instance for " - "recursion errors"); + Py_FatalError("Cannot pre-allocate RuntimeError instance for " + "recursion errors"); else { - PyBaseExceptionObject *err_inst = - (PyBaseExceptionObject *)PyExc_RecursionErrorInst; - PyObject *args_tuple; - PyObject *exc_message; - exc_message = PyUnicode_FromString("maximum recursion depth exceeded"); - if (!exc_message) - Py_FatalError("cannot allocate argument for RuntimeError " - "pre-allocation"); - args_tuple = PyTuple_Pack(1, exc_message); - if (!args_tuple) - Py_FatalError("cannot allocate tuple for RuntimeError " - "pre-allocation"); - Py_DECREF(exc_message); - if (BaseException_init(err_inst, args_tuple, NULL)) - Py_FatalError("init of pre-allocated RuntimeError failed"); - Py_DECREF(args_tuple); + PyBaseExceptionObject *err_inst = + (PyBaseExceptionObject *)PyExc_RecursionErrorInst; + PyObject *args_tuple; + PyObject *exc_message; + exc_message = PyUnicode_FromString("maximum recursion depth exceeded"); + if (!exc_message) + Py_FatalError("cannot allocate argument for RuntimeError " + "pre-allocation"); + args_tuple = PyTuple_Pack(1, exc_message); + if (!args_tuple) + Py_FatalError("cannot allocate tuple for RuntimeError " + "pre-allocation"); + Py_DECREF(exc_message); + if (BaseException_init(err_inst, args_tuple, NULL)) + Py_FatalError("init of pre-allocated RuntimeError failed"); + Py_DECREF(args_tuple); } Py_DECREF(bltinmod); Modified: python/branches/py3k/Objects/fileobject.c ============================================================================== --- python/branches/py3k/Objects/fileobject.c (original) +++ python/branches/py3k/Objects/fileobject.c Sun May 9 17:52:27 2010 @@ -14,10 +14,10 @@ #endif /* Newline flags */ -#define NEWLINE_UNKNOWN 0 /* No newline seen, yet */ -#define NEWLINE_CR 1 /* \r newline seen */ -#define NEWLINE_LF 2 /* \n newline seen */ -#define NEWLINE_CRLF 4 /* \r\n newline seen */ +#define NEWLINE_UNKNOWN 0 /* No newline seen, yet */ +#define NEWLINE_CR 1 /* \r newline seen */ +#define NEWLINE_LF 2 /* \n newline seen */ +#define NEWLINE_CRLF 4 /* \r\n newline seen */ #ifdef __cplusplus extern "C" { @@ -27,110 +27,110 @@ PyObject * PyFile_FromFd(int fd, char *name, char *mode, int buffering, char *encoding, - char *errors, char *newline, int closefd) + char *errors, char *newline, int closefd) { - PyObject *io, *stream, *nameobj = NULL; + PyObject *io, *stream, *nameobj = NULL; - io = PyImport_ImportModule("io"); - if (io == NULL) - return NULL; - stream = PyObject_CallMethod(io, "open", "isisssi", fd, mode, - buffering, encoding, errors, - newline, closefd); - Py_DECREF(io); - if (stream == NULL) - return NULL; - if (name != NULL) { - nameobj = PyUnicode_DecodeFSDefault(name); - if (nameobj == NULL) - PyErr_Clear(); - else { - if (PyObject_SetAttrString(stream, "name", nameobj) < 0) - PyErr_Clear(); - Py_DECREF(nameobj); - } - } - return stream; + io = PyImport_ImportModule("io"); + if (io == NULL) + return NULL; + stream = PyObject_CallMethod(io, "open", "isisssi", fd, mode, + buffering, encoding, errors, + newline, closefd); + Py_DECREF(io); + if (stream == NULL) + return NULL; + if (name != NULL) { + nameobj = PyUnicode_DecodeFSDefault(name); + if (nameobj == NULL) + PyErr_Clear(); + else { + if (PyObject_SetAttrString(stream, "name", nameobj) < 0) + PyErr_Clear(); + Py_DECREF(nameobj); + } + } + return stream; } PyObject * PyFile_GetLine(PyObject *f, int n) { - PyObject *result; + PyObject *result; - if (f == NULL) { - PyErr_BadInternalCall(); - return NULL; - } - - { - PyObject *reader; - PyObject *args; - - reader = PyObject_GetAttrString(f, "readline"); - if (reader == NULL) - return NULL; - if (n <= 0) - args = PyTuple_New(0); - else - args = Py_BuildValue("(i)", n); - if (args == NULL) { - Py_DECREF(reader); - return NULL; - } - result = PyEval_CallObject(reader, args); - Py_DECREF(reader); - Py_DECREF(args); - if (result != NULL && !PyBytes_Check(result) && - !PyUnicode_Check(result)) { - Py_DECREF(result); - result = NULL; - PyErr_SetString(PyExc_TypeError, - "object.readline() returned non-string"); - } - } - - if (n < 0 && result != NULL && PyBytes_Check(result)) { - char *s = PyBytes_AS_STRING(result); - Py_ssize_t len = PyBytes_GET_SIZE(result); - if (len == 0) { - Py_DECREF(result); - result = NULL; - PyErr_SetString(PyExc_EOFError, - "EOF when reading a line"); - } - else if (s[len-1] == '\n') { - if (result->ob_refcnt == 1) - _PyBytes_Resize(&result, len-1); - else { - PyObject *v; - v = PyBytes_FromStringAndSize(s, len-1); - Py_DECREF(result); - result = v; - } - } - } - if (n < 0 && result != NULL && PyUnicode_Check(result)) { - Py_UNICODE *s = PyUnicode_AS_UNICODE(result); - Py_ssize_t len = PyUnicode_GET_SIZE(result); - if (len == 0) { - Py_DECREF(result); - result = NULL; - PyErr_SetString(PyExc_EOFError, - "EOF when reading a line"); - } - else if (s[len-1] == '\n') { - if (result->ob_refcnt == 1) - PyUnicode_Resize(&result, len-1); - else { - PyObject *v; - v = PyUnicode_FromUnicode(s, len-1); - Py_DECREF(result); - result = v; - } - } - } - return result; + if (f == NULL) { + PyErr_BadInternalCall(); + return NULL; + } + + { + PyObject *reader; + PyObject *args; + + reader = PyObject_GetAttrString(f, "readline"); + if (reader == NULL) + return NULL; + if (n <= 0) + args = PyTuple_New(0); + else + args = Py_BuildValue("(i)", n); + if (args == NULL) { + Py_DECREF(reader); + return NULL; + } + result = PyEval_CallObject(reader, args); + Py_DECREF(reader); + Py_DECREF(args); + if (result != NULL && !PyBytes_Check(result) && + !PyUnicode_Check(result)) { + Py_DECREF(result); + result = NULL; + PyErr_SetString(PyExc_TypeError, + "object.readline() returned non-string"); + } + } + + if (n < 0 && result != NULL && PyBytes_Check(result)) { + char *s = PyBytes_AS_STRING(result); + Py_ssize_t len = PyBytes_GET_SIZE(result); + if (len == 0) { + Py_DECREF(result); + result = NULL; + PyErr_SetString(PyExc_EOFError, + "EOF when reading a line"); + } + else if (s[len-1] == '\n') { + if (result->ob_refcnt == 1) + _PyBytes_Resize(&result, len-1); + else { + PyObject *v; + v = PyBytes_FromStringAndSize(s, len-1); + Py_DECREF(result); + result = v; + } + } + } + if (n < 0 && result != NULL && PyUnicode_Check(result)) { + Py_UNICODE *s = PyUnicode_AS_UNICODE(result); + Py_ssize_t len = PyUnicode_GET_SIZE(result); + if (len == 0) { + Py_DECREF(result); + result = NULL; + PyErr_SetString(PyExc_EOFError, + "EOF when reading a line"); + } + else if (s[len-1] == '\n') { + if (result->ob_refcnt == 1) + PyUnicode_Resize(&result, len-1); + else { + PyObject *v; + v = PyUnicode_FromUnicode(s, len-1); + Py_DECREF(result); + result = v; + } + } + } + return result; } /* Interfaces to write objects/strings to file-like objects */ @@ -138,60 +138,60 @@ int PyFile_WriteObject(PyObject *v, PyObject *f, int flags) { - PyObject *writer, *value, *args, *result; - if (f == NULL) { - PyErr_SetString(PyExc_TypeError, "writeobject with NULL file"); - return -1; - } - writer = PyObject_GetAttrString(f, "write"); - if (writer == NULL) - return -1; - if (flags & Py_PRINT_RAW) { - value = PyObject_Str(v); - } - else - value = PyObject_Repr(v); - if (value == NULL) { - Py_DECREF(writer); - return -1; - } - args = PyTuple_Pack(1, value); - if (args == NULL) { - Py_DECREF(value); - Py_DECREF(writer); - return -1; - } - result = PyEval_CallObject(writer, args); - Py_DECREF(args); - Py_DECREF(value); - Py_DECREF(writer); - if (result == NULL) - return -1; - Py_DECREF(result); - return 0; + PyObject *writer, *value, *args, *result; + if (f == NULL) { + PyErr_SetString(PyExc_TypeError, "writeobject with NULL file"); + return -1; + } + writer = PyObject_GetAttrString(f, "write"); + if (writer == NULL) + return -1; + if (flags & Py_PRINT_RAW) { + value = PyObject_Str(v); + } + else + value = PyObject_Repr(v); + if (value == NULL) { + Py_DECREF(writer); + return -1; + } + args = PyTuple_Pack(1, value); + if (args == NULL) { + Py_DECREF(value); + Py_DECREF(writer); + return -1; + } + result = PyEval_CallObject(writer, args); + Py_DECREF(args); + Py_DECREF(value); + Py_DECREF(writer); + if (result == NULL) + return -1; + Py_DECREF(result); + return 0; } int PyFile_WriteString(const char *s, PyObject *f) { - if (f == NULL) { - /* Should be caused by a pre-existing error */ - if (!PyErr_Occurred()) - PyErr_SetString(PyExc_SystemError, - "null file for PyFile_WriteString"); - return -1; - } - else if (!PyErr_Occurred()) { - PyObject *v = PyUnicode_FromString(s); - int err; - if (v == NULL) - return -1; - err = PyFile_WriteObject(v, f, Py_PRINT_RAW); - Py_DECREF(v); - return err; - } - else - return -1; + if (f == NULL) { + /* Should be caused by a pre-existing error */ + if (!PyErr_Occurred()) + PyErr_SetString(PyExc_SystemError, + "null file for PyFile_WriteString"); + return -1; + } + else if (!PyErr_Occurred()) { + PyObject *v = PyUnicode_FromString(s); + int err; + if (v == NULL) + return -1; + err = PyFile_WriteObject(v, f, Py_PRINT_RAW); + Py_DECREF(v); + return err; + } + else + return -1; } /* Try to get a file-descriptor from a Python object. If the object @@ -204,45 +204,45 @@ int PyObject_AsFileDescriptor(PyObject *o) { - int fd; - PyObject *meth; + int fd; + PyObject *meth; - if (PyLong_Check(o)) { - fd = PyLong_AsLong(o); - } - else if ((meth = PyObject_GetAttrString(o, "fileno")) != NULL) - { - PyObject *fno = PyEval_CallObject(meth, NULL); - Py_DECREF(meth); - if (fno == NULL) - return -1; - - if (PyLong_Check(fno)) { - fd = PyLong_AsLong(fno); - Py_DECREF(fno); - } - else { - PyErr_SetString(PyExc_TypeError, - "fileno() returned a non-integer"); - Py_DECREF(fno); - return -1; - } - } - else { - PyErr_SetString(PyExc_TypeError, - "argument must be an int, or have a fileno() method."); - return -1; - } - - if (fd == -1 && PyErr_Occurred()) - return -1; - if (fd < 0) { - PyErr_Format(PyExc_ValueError, - "file descriptor cannot be a negative integer (%i)", - fd); - return -1; - } - return fd; + if (PyLong_Check(o)) { + fd = PyLong_AsLong(o); + } + else if ((meth = PyObject_GetAttrString(o, "fileno")) != NULL) + { + PyObject *fno = PyEval_CallObject(meth, NULL); + Py_DECREF(meth); + if (fno == NULL) + return -1; + + if (PyLong_Check(fno)) { + fd = PyLong_AsLong(fno); + Py_DECREF(fno); + } + else { + PyErr_SetString(PyExc_TypeError, + "fileno() returned a non-integer"); + Py_DECREF(fno); + return -1; + } + } + else { + PyErr_SetString(PyExc_TypeError, + "argument must be an int, or have a fileno() method."); + return -1; + } + + if (fd == -1 && PyErr_Occurred()) + return -1; + if (fd < 0) { + PyErr_Format(PyExc_ValueError, + "file descriptor cannot be a negative integer (%i)", + fd); + return -1; + } + return fd; } /* @@ -262,68 +262,68 @@ char * Py_UniversalNewlineFgets(char *buf, int n, FILE *stream, PyObject *fobj) { - char *p = buf; - int c; - int newlinetypes = 0; - int skipnextlf = 0; - - if (fobj) { - errno = ENXIO; /* What can you do... */ - return NULL; - } - FLOCKFILE(stream); - c = 'x'; /* Shut up gcc warning */ - while (--n > 0 && (c = GETC(stream)) != EOF ) { - if (skipnextlf ) { - skipnextlf = 0; - if (c == '\n') { - /* Seeing a \n here with skipnextlf true - ** means we saw a \r before. - */ - newlinetypes |= NEWLINE_CRLF; - c = GETC(stream); - if (c == EOF) break; - } else { - /* - ** Note that c == EOF also brings us here, - ** so we're okay if the last char in the file - ** is a CR. - */ - newlinetypes |= NEWLINE_CR; - } - } - if (c == '\r') { - /* A \r is translated into a \n, and we skip - ** an adjacent \n, if any. We don't set the - ** newlinetypes flag until we've seen the next char. - */ - skipnextlf = 1; - c = '\n'; - } else if ( c == '\n') { - newlinetypes |= NEWLINE_LF; - } - *p++ = c; - if (c == '\n') break; - } - if ( c == EOF && skipnextlf ) - newlinetypes |= NEWLINE_CR; - FUNLOCKFILE(stream); - *p = '\0'; - if ( skipnextlf ) { - /* If we have no file object we cannot save the - ** skipnextlf flag. We have to readahead, which - ** will cause a pause if we're reading from an - ** interactive stream, but that is very unlikely - ** unless we're doing something silly like - ** exec(open("/dev/tty").read()). - */ - c = GETC(stream); - if ( c != '\n' ) - ungetc(c, stream); - } - if (p == buf) - return NULL; - return buf; + char *p = buf; + int c; + int newlinetypes = 0; + int skipnextlf = 0; + + if (fobj) { + errno = ENXIO; /* What can you do... */ + return NULL; + } + FLOCKFILE(stream); + c = 'x'; /* Shut up gcc warning */ + while (--n > 0 && (c = GETC(stream)) != EOF ) { + if (skipnextlf ) { + skipnextlf = 0; + if (c == '\n') { + /* Seeing a \n here with skipnextlf true + ** means we saw a \r before. + */ + newlinetypes |= NEWLINE_CRLF; + c = GETC(stream); + if (c == EOF) break; + } else { + /* + ** Note that c == EOF also brings us here, + ** so we're okay if the last char in the file + ** is a CR. + */ + newlinetypes |= NEWLINE_CR; + } + } + if (c == '\r') { + /* A \r is translated into a \n, and we skip + ** an adjacent \n, if any. We don't set the + ** newlinetypes flag until we've seen the next char. + */ + skipnextlf = 1; + c = '\n'; + } else if ( c == '\n') { + newlinetypes |= NEWLINE_LF; + } + *p++ = c; + if (c == '\n') break; + } + if ( c == EOF && skipnextlf ) + newlinetypes |= NEWLINE_CR; + FUNLOCKFILE(stream); + *p = '\0'; + if ( skipnextlf ) { + /* If we have no file object we cannot save the + ** skipnextlf flag. We have to readahead, which + ** will cause a pause if we're reading from an + ** interactive stream, but that is very unlikely + ** unless we're doing something silly like + ** exec(open("/dev/tty").read()). + */ + c = GETC(stream); + if ( c != '\n' ) + ungetc(c, stream); + } + if (p == buf) + return NULL; + return buf; } /* **************************** std printer **************************** @@ -332,195 +332,195 @@ */ typedef struct { - PyObject_HEAD - int fd; + PyObject_HEAD + int fd; } PyStdPrinter_Object; static PyObject * stdprinter_new(PyTypeObject *type, PyObject *args, PyObject *kews) { - PyStdPrinter_Object *self; + PyStdPrinter_Object *self; - assert(type != NULL && type->tp_alloc != NULL); + assert(type != NULL && type->tp_alloc != NULL); - self = (PyStdPrinter_Object *) type->tp_alloc(type, 0); - if (self != NULL) { - self->fd = -1; - } + self = (PyStdPrinter_Object *) type->tp_alloc(type, 0); + if (self != NULL) { + self->fd = -1; + } - return (PyObject *) self; + return (PyObject *) self; } static int fileio_init(PyObject *self, PyObject *args, PyObject *kwds) { - PyErr_SetString(PyExc_TypeError, - "cannot create 'stderrprinter' instances"); - return -1; + PyErr_SetString(PyExc_TypeError, + "cannot create 'stderrprinter' instances"); + return -1; } PyObject * PyFile_NewStdPrinter(int fd) { - PyStdPrinter_Object *self; + PyStdPrinter_Object *self; - if (fd != fileno(stdout) && fd != fileno(stderr)) { - /* not enough infrastructure for PyErr_BadInternalCall() */ - return NULL; - } - - self = PyObject_New(PyStdPrinter_Object, - &PyStdPrinter_Type); - if (self != NULL) { - self->fd = fd; - } - return (PyObject*)self; + if (fd != fileno(stdout) && fd != fileno(stderr)) { + /* not enough infrastructure for PyErr_BadInternalCall() */ + return NULL; + } + + self = PyObject_New(PyStdPrinter_Object, + &PyStdPrinter_Type); + if (self != NULL) { + self->fd = fd; + } + return (PyObject*)self; } static PyObject * stdprinter_write(PyStdPrinter_Object *self, PyObject *args) { - char *c; - Py_ssize_t n; + char *c; + Py_ssize_t n; - if (self->fd < 0) { - /* fd might be invalid on Windows - * I can't raise an exception here. It may lead to an - * unlimited recursion in the case stderr is invalid. - */ - Py_RETURN_NONE; - } - - if (!PyArg_ParseTuple(args, "s", &c)) { - return NULL; - } - n = strlen(c); - - Py_BEGIN_ALLOW_THREADS - errno = 0; - n = write(self->fd, c, n); - Py_END_ALLOW_THREADS - - if (n < 0) { - if (errno == EAGAIN) - Py_RETURN_NONE; - PyErr_SetFromErrno(PyExc_IOError); - return NULL; - } + if (self->fd < 0) { + /* fd might be invalid on Windows + * I can't raise an exception here. It may lead to an + * unlimited recursion in the case stderr is invalid. + */ + Py_RETURN_NONE; + } + + if (!PyArg_ParseTuple(args, "s", &c)) { + return NULL; + } + n = strlen(c); + + Py_BEGIN_ALLOW_THREADS + errno = 0; + n = write(self->fd, c, n); + Py_END_ALLOW_THREADS + + if (n < 0) { + if (errno == EAGAIN) + Py_RETURN_NONE; + PyErr_SetFromErrno(PyExc_IOError); + return NULL; + } - return PyLong_FromSsize_t(n); + return PyLong_FromSsize_t(n); } static PyObject * stdprinter_fileno(PyStdPrinter_Object *self) { - return PyLong_FromLong((long) self->fd); + return PyLong_FromLong((long) self->fd); } static PyObject * stdprinter_repr(PyStdPrinter_Object *self) { - return PyUnicode_FromFormat("", - self->fd, self); + return PyUnicode_FromFormat("", + self->fd, self); } static PyObject * stdprinter_noop(PyStdPrinter_Object *self) { - Py_RETURN_NONE; + Py_RETURN_NONE; } static PyObject * stdprinter_isatty(PyStdPrinter_Object *self) { - long res; - if (self->fd < 0) { - Py_RETURN_FALSE; - } - - Py_BEGIN_ALLOW_THREADS - res = isatty(self->fd); - Py_END_ALLOW_THREADS + long res; + if (self->fd < 0) { + Py_RETURN_FALSE; + } + + Py_BEGIN_ALLOW_THREADS + res = isatty(self->fd); + Py_END_ALLOW_THREADS - return PyBool_FromLong(res); + return PyBool_FromLong(res); } static PyMethodDef stdprinter_methods[] = { - {"close", (PyCFunction)stdprinter_noop, METH_NOARGS, ""}, - {"flush", (PyCFunction)stdprinter_noop, METH_NOARGS, ""}, - {"fileno", (PyCFunction)stdprinter_fileno, METH_NOARGS, ""}, - {"isatty", (PyCFunction)stdprinter_isatty, METH_NOARGS, ""}, - {"write", (PyCFunction)stdprinter_write, METH_VARARGS, ""}, - {NULL, NULL} /*sentinel */ + {"close", (PyCFunction)stdprinter_noop, METH_NOARGS, ""}, + {"flush", (PyCFunction)stdprinter_noop, METH_NOARGS, ""}, + {"fileno", (PyCFunction)stdprinter_fileno, METH_NOARGS, ""}, + {"isatty", (PyCFunction)stdprinter_isatty, METH_NOARGS, ""}, + {"write", (PyCFunction)stdprinter_write, METH_VARARGS, ""}, + {NULL, NULL} /*sentinel */ }; static PyObject * get_closed(PyStdPrinter_Object *self, void *closure) { - Py_INCREF(Py_False); - return Py_False; + Py_INCREF(Py_False); + return Py_False; } static PyObject * get_mode(PyStdPrinter_Object *self, void *closure) { - return PyUnicode_FromString("w"); + return PyUnicode_FromString("w"); } static PyObject * get_encoding(PyStdPrinter_Object *self, void *closure) { - Py_RETURN_NONE; + Py_RETURN_NONE; } static PyGetSetDef stdprinter_getsetlist[] = { - {"closed", (getter)get_closed, NULL, "True if the file is closed"}, - {"encoding", (getter)get_encoding, NULL, "Encoding of the file"}, - {"mode", (getter)get_mode, NULL, "String giving the file mode"}, - {0}, + {"closed", (getter)get_closed, NULL, "True if the file is closed"}, + {"encoding", (getter)get_encoding, NULL, "Encoding of the file"}, + {"mode", (getter)get_mode, NULL, "String giving the file mode"}, + {0}, }; PyTypeObject PyStdPrinter_Type = { - PyVarObject_HEAD_INIT(&PyType_Type, 0) - "stderrprinter", /* tp_name */ - sizeof(PyStdPrinter_Object), /* tp_basicsize */ - 0, /* tp_itemsize */ - /* methods */ - 0, /* tp_dealloc */ - 0, /* tp_print */ - 0, /* tp_getattr */ - 0, /* tp_setattr */ - 0, /* tp_reserved */ - (reprfunc)stdprinter_repr, /* tp_repr */ - 0, /* tp_as_number */ - 0, /* tp_as_sequence */ - 0, /* tp_as_mapping */ - 0, /* tp_hash */ - 0, /* tp_call */ - 0, /* tp_str */ - PyObject_GenericGetAttr, /* tp_getattro */ - 0, /* tp_setattro */ - 0, /* tp_as_buffer */ - Py_TPFLAGS_DEFAULT, /* tp_flags */ - 0, /* tp_doc */ - 0, /* tp_traverse */ - 0, /* tp_clear */ - 0, /* tp_richcompare */ - 0, /* tp_weaklistoffset */ - 0, /* tp_iter */ - 0, /* tp_iternext */ - stdprinter_methods, /* tp_methods */ - 0, /* tp_members */ - stdprinter_getsetlist, /* tp_getset */ - 0, /* tp_base */ - 0, /* tp_dict */ - 0, /* tp_descr_get */ - 0, /* tp_descr_set */ - 0, /* tp_dictoffset */ - fileio_init, /* tp_init */ - PyType_GenericAlloc, /* tp_alloc */ - stdprinter_new, /* tp_new */ - PyObject_Del, /* tp_free */ + PyVarObject_HEAD_INIT(&PyType_Type, 0) + "stderrprinter", /* tp_name */ + sizeof(PyStdPrinter_Object), /* tp_basicsize */ + 0, /* tp_itemsize */ + /* methods */ + 0, /* tp_dealloc */ + 0, /* tp_print */ + 0, /* tp_getattr */ + 0, /* tp_setattr */ + 0, /* tp_reserved */ + (reprfunc)stdprinter_repr, /* tp_repr */ + 0, /* tp_as_number */ + 0, /* tp_as_sequence */ + 0, /* tp_as_mapping */ + 0, /* tp_hash */ + 0, /* tp_call */ + 0, /* tp_str */ + PyObject_GenericGetAttr, /* tp_getattro */ + 0, /* tp_setattro */ + 0, /* tp_as_buffer */ + Py_TPFLAGS_DEFAULT, /* tp_flags */ + 0, /* tp_doc */ + 0, /* tp_traverse */ + 0, /* tp_clear */ + 0, /* tp_richcompare */ + 0, /* tp_weaklistoffset */ + 0, /* tp_iter */ + 0, /* tp_iternext */ + stdprinter_methods, /* tp_methods */ + 0, /* tp_members */ + stdprinter_getsetlist, /* tp_getset */ + 0, /* tp_base */ + 0, /* tp_dict */ + 0, /* tp_descr_get */ + 0, /* tp_descr_set */ + 0, /* tp_dictoffset */ + fileio_init, /* tp_init */ + PyType_GenericAlloc, /* tp_alloc */ + stdprinter_new, /* tp_new */ + PyObject_Del, /* tp_free */ }; Modified: python/branches/py3k/Objects/floatobject.c ============================================================================== --- python/branches/py3k/Objects/floatobject.c (original) +++ python/branches/py3k/Objects/floatobject.c Sun May 9 17:52:27 2010 @@ -22,13 +22,13 @@ #endif /* Special free list -- see comments for same code in intobject.c. */ -#define BLOCK_SIZE 1000 /* 1K less typical malloc overhead */ -#define BHEAD_SIZE 8 /* Enough for a 64-bit pointer */ -#define N_FLOATOBJECTS ((BLOCK_SIZE - BHEAD_SIZE) / sizeof(PyFloatObject)) +#define BLOCK_SIZE 1000 /* 1K less typical malloc overhead */ +#define BHEAD_SIZE 8 /* Enough for a 64-bit pointer */ +#define N_FLOATOBJECTS ((BLOCK_SIZE - BHEAD_SIZE) / sizeof(PyFloatObject)) struct _floatblock { - struct _floatblock *next; - PyFloatObject objects[N_FLOATOBJECTS]; + struct _floatblock *next; + PyFloatObject objects[N_FLOATOBJECTS]; }; typedef struct _floatblock PyFloatBlock; @@ -39,31 +39,31 @@ static PyFloatObject * fill_free_list(void) { - PyFloatObject *p, *q; - /* XXX Float blocks escape the object heap. Use PyObject_MALLOC ??? */ - p = (PyFloatObject *) PyMem_MALLOC(sizeof(PyFloatBlock)); - if (p == NULL) - return (PyFloatObject *) PyErr_NoMemory(); - ((PyFloatBlock *)p)->next = block_list; - block_list = (PyFloatBlock *)p; - p = &((PyFloatBlock *)p)->objects[0]; - q = p + N_FLOATOBJECTS; - while (--q > p) - Py_TYPE(q) = (struct _typeobject *)(q-1); - Py_TYPE(q) = NULL; - return p + N_FLOATOBJECTS - 1; + PyFloatObject *p, *q; + /* XXX Float blocks escape the object heap. Use PyObject_MALLOC ??? */ + p = (PyFloatObject *) PyMem_MALLOC(sizeof(PyFloatBlock)); + if (p == NULL) + return (PyFloatObject *) PyErr_NoMemory(); + ((PyFloatBlock *)p)->next = block_list; + block_list = (PyFloatBlock *)p; + p = &((PyFloatBlock *)p)->objects[0]; + q = p + N_FLOATOBJECTS; + while (--q > p) + Py_TYPE(q) = (struct _typeobject *)(q-1); + Py_TYPE(q) = NULL; + return p + N_FLOATOBJECTS - 1; } double PyFloat_GetMax(void) { - return DBL_MAX; + return DBL_MAX; } double PyFloat_GetMin(void) { - return DBL_MIN; + return DBL_MIN; } static PyTypeObject FloatInfoType; @@ -76,183 +76,183 @@ your system's :file:`float.h` for more information."); static PyStructSequence_Field floatinfo_fields[] = { - {"max", "DBL_MAX -- maximum representable finite float"}, - {"max_exp", "DBL_MAX_EXP -- maximum int e such that radix**(e-1) " - "is representable"}, - {"max_10_exp", "DBL_MAX_10_EXP -- maximum int e such that 10**e " - "is representable"}, - {"min", "DBL_MIN -- Minimum positive normalizer float"}, - {"min_exp", "DBL_MIN_EXP -- minimum int e such that radix**(e-1) " - "is a normalized float"}, - {"min_10_exp", "DBL_MIN_10_EXP -- minimum int e such that 10**e is " - "a normalized"}, - {"dig", "DBL_DIG -- digits"}, - {"mant_dig", "DBL_MANT_DIG -- mantissa digits"}, - {"epsilon", "DBL_EPSILON -- Difference between 1 and the next " - "representable float"}, - {"radix", "FLT_RADIX -- radix of exponent"}, - {"rounds", "FLT_ROUNDS -- addition rounds"}, - {0} + {"max", "DBL_MAX -- maximum representable finite float"}, + {"max_exp", "DBL_MAX_EXP -- maximum int e such that radix**(e-1) " + "is representable"}, + {"max_10_exp", "DBL_MAX_10_EXP -- maximum int e such that 10**e " + "is representable"}, + {"min", "DBL_MIN -- Minimum positive normalizer float"}, + {"min_exp", "DBL_MIN_EXP -- minimum int e such that radix**(e-1) " + "is a normalized float"}, + {"min_10_exp", "DBL_MIN_10_EXP -- minimum int e such that 10**e is " + "a normalized"}, + {"dig", "DBL_DIG -- digits"}, + {"mant_dig", "DBL_MANT_DIG -- mantissa digits"}, + {"epsilon", "DBL_EPSILON -- Difference between 1 and the next " + "representable float"}, + {"radix", "FLT_RADIX -- radix of exponent"}, + {"rounds", "FLT_ROUNDS -- addition rounds"}, + {0} }; static PyStructSequence_Desc floatinfo_desc = { - "sys.float_info", /* name */ - floatinfo__doc__, /* doc */ - floatinfo_fields, /* fields */ - 11 + "sys.float_info", /* name */ + floatinfo__doc__, /* doc */ + floatinfo_fields, /* fields */ + 11 }; PyObject * PyFloat_GetInfo(void) { - PyObject* floatinfo; - int pos = 0; + PyObject* floatinfo; + int pos = 0; - floatinfo = PyStructSequence_New(&FloatInfoType); - if (floatinfo == NULL) { - return NULL; - } + floatinfo = PyStructSequence_New(&FloatInfoType); + if (floatinfo == NULL) { + return NULL; + } #define SetIntFlag(flag) \ - PyStructSequence_SET_ITEM(floatinfo, pos++, PyLong_FromLong(flag)) + PyStructSequence_SET_ITEM(floatinfo, pos++, PyLong_FromLong(flag)) #define SetDblFlag(flag) \ - PyStructSequence_SET_ITEM(floatinfo, pos++, PyFloat_FromDouble(flag)) + PyStructSequence_SET_ITEM(floatinfo, pos++, PyFloat_FromDouble(flag)) - SetDblFlag(DBL_MAX); - SetIntFlag(DBL_MAX_EXP); - SetIntFlag(DBL_MAX_10_EXP); - SetDblFlag(DBL_MIN); - SetIntFlag(DBL_MIN_EXP); - SetIntFlag(DBL_MIN_10_EXP); - SetIntFlag(DBL_DIG); - SetIntFlag(DBL_MANT_DIG); - SetDblFlag(DBL_EPSILON); - SetIntFlag(FLT_RADIX); - SetIntFlag(FLT_ROUNDS); + SetDblFlag(DBL_MAX); + SetIntFlag(DBL_MAX_EXP); + SetIntFlag(DBL_MAX_10_EXP); + SetDblFlag(DBL_MIN); + SetIntFlag(DBL_MIN_EXP); + SetIntFlag(DBL_MIN_10_EXP); + SetIntFlag(DBL_DIG); + SetIntFlag(DBL_MANT_DIG); + SetDblFlag(DBL_EPSILON); + SetIntFlag(FLT_RADIX); + SetIntFlag(FLT_ROUNDS); #undef SetIntFlag #undef SetDblFlag - - if (PyErr_Occurred()) { - Py_CLEAR(floatinfo); - return NULL; - } - return floatinfo; + + if (PyErr_Occurred()) { + Py_CLEAR(floatinfo); + return NULL; + } + return floatinfo; } PyObject * PyFloat_FromDouble(double fval) { - register PyFloatObject *op; - if (free_list == NULL) { - if ((free_list = fill_free_list()) == NULL) - return NULL; - } - /* Inline PyObject_New */ - op = free_list; - free_list = (PyFloatObject *)Py_TYPE(op); - PyObject_INIT(op, &PyFloat_Type); - op->ob_fval = fval; - return (PyObject *) op; + register PyFloatObject *op; + if (free_list == NULL) { + if ((free_list = fill_free_list()) == NULL) + return NULL; + } + /* Inline PyObject_New */ + op = free_list; + free_list = (PyFloatObject *)Py_TYPE(op); + PyObject_INIT(op, &PyFloat_Type); + op->ob_fval = fval; + return (PyObject *) op; } PyObject * PyFloat_FromString(PyObject *v) { - const char *s, *last, *end; - double x; - char buffer[256]; /* for errors */ - char *s_buffer = NULL; - Py_ssize_t len; - PyObject *result = NULL; - - if (PyUnicode_Check(v)) { - s_buffer = (char *)PyMem_MALLOC(PyUnicode_GET_SIZE(v)+1); - if (s_buffer == NULL) - return PyErr_NoMemory(); - if (PyUnicode_EncodeDecimal(PyUnicode_AS_UNICODE(v), - PyUnicode_GET_SIZE(v), - s_buffer, - NULL)) - goto error; - s = s_buffer; - len = strlen(s); - } - else if (PyObject_AsCharBuffer(v, &s, &len)) { - PyErr_SetString(PyExc_TypeError, - "float() argument must be a string or a number"); - return NULL; - } - last = s + len; - - while (Py_ISSPACE(*s)) - s++; - /* We don't care about overflow or underflow. If the platform - * supports them, infinities and signed zeroes (on underflow) are - * fine. */ - x = PyOS_string_to_double(s, (char **)&end, NULL); - if (x == -1.0 && PyErr_Occurred()) - goto error; - while (Py_ISSPACE(*end)) - end++; - if (end == last) - result = PyFloat_FromDouble(x); - else { - PyOS_snprintf(buffer, sizeof(buffer), - "invalid literal for float(): %.200s", s); - PyErr_SetString(PyExc_ValueError, buffer); - result = NULL; - } + const char *s, *last, *end; + double x; + char buffer[256]; /* for errors */ + char *s_buffer = NULL; + Py_ssize_t len; + PyObject *result = NULL; + + if (PyUnicode_Check(v)) { + s_buffer = (char *)PyMem_MALLOC(PyUnicode_GET_SIZE(v)+1); + if (s_buffer == NULL) + return PyErr_NoMemory(); + if (PyUnicode_EncodeDecimal(PyUnicode_AS_UNICODE(v), + PyUnicode_GET_SIZE(v), + s_buffer, + NULL)) + goto error; + s = s_buffer; + len = strlen(s); + } + else if (PyObject_AsCharBuffer(v, &s, &len)) { + PyErr_SetString(PyExc_TypeError, + "float() argument must be a string or a number"); + return NULL; + } + last = s + len; + + while (Py_ISSPACE(*s)) + s++; + /* We don't care about overflow or underflow. If the platform + * supports them, infinities and signed zeroes (on underflow) are + * fine. */ + x = PyOS_string_to_double(s, (char **)&end, NULL); + if (x == -1.0 && PyErr_Occurred()) + goto error; + while (Py_ISSPACE(*end)) + end++; + if (end == last) + result = PyFloat_FromDouble(x); + else { + PyOS_snprintf(buffer, sizeof(buffer), + "invalid literal for float(): %.200s", s); + PyErr_SetString(PyExc_ValueError, buffer); + result = NULL; + } error: - if (s_buffer) - PyMem_FREE(s_buffer); - return result; + if (s_buffer) + PyMem_FREE(s_buffer); + return result; } static void float_dealloc(PyFloatObject *op) { - if (PyFloat_CheckExact(op)) { - Py_TYPE(op) = (struct _typeobject *)free_list; - free_list = op; - } - else - Py_TYPE(op)->tp_free((PyObject *)op); + if (PyFloat_CheckExact(op)) { + Py_TYPE(op) = (struct _typeobject *)free_list; + free_list = op; + } + else + Py_TYPE(op)->tp_free((PyObject *)op); } double PyFloat_AsDouble(PyObject *op) { - PyNumberMethods *nb; - PyFloatObject *fo; - double val; - - if (op && PyFloat_Check(op)) - return PyFloat_AS_DOUBLE((PyFloatObject*) op); - - if (op == NULL) { - PyErr_BadArgument(); - return -1; - } - - if ((nb = Py_TYPE(op)->tp_as_number) == NULL || nb->nb_float == NULL) { - PyErr_SetString(PyExc_TypeError, "a float is required"); - return -1; - } - - fo = (PyFloatObject*) (*nb->nb_float) (op); - if (fo == NULL) - return -1; - if (!PyFloat_Check(fo)) { - PyErr_SetString(PyExc_TypeError, - "nb_float should return float object"); - return -1; - } + PyNumberMethods *nb; + PyFloatObject *fo; + double val; + + if (op && PyFloat_Check(op)) + return PyFloat_AS_DOUBLE((PyFloatObject*) op); + + if (op == NULL) { + PyErr_BadArgument(); + return -1; + } + + if ((nb = Py_TYPE(op)->tp_as_number) == NULL || nb->nb_float == NULL) { + PyErr_SetString(PyExc_TypeError, "a float is required"); + return -1; + } + + fo = (PyFloatObject*) (*nb->nb_float) (op); + if (fo == NULL) + return -1; + if (!PyFloat_Check(fo)) { + PyErr_SetString(PyExc_TypeError, + "nb_float should return float object"); + return -1; + } - val = PyFloat_AS_DOUBLE(fo); - Py_DECREF(fo); + val = PyFloat_AS_DOUBLE(fo); + Py_DECREF(fo); - return val; + return val; } /* Macro and helper that convert PyObject obj to a C double and store @@ -261,32 +261,32 @@ obj is not of float, int or long type, Py_NotImplemented is incref'ed, stored in obj, and returned from the function invoking this macro. */ -#define CONVERT_TO_DOUBLE(obj, dbl) \ - if (PyFloat_Check(obj)) \ - dbl = PyFloat_AS_DOUBLE(obj); \ - else if (convert_to_double(&(obj), &(dbl)) < 0) \ - return obj; +#define CONVERT_TO_DOUBLE(obj, dbl) \ + if (PyFloat_Check(obj)) \ + dbl = PyFloat_AS_DOUBLE(obj); \ + else if (convert_to_double(&(obj), &(dbl)) < 0) \ + return obj; /* Methods */ static int convert_to_double(PyObject **v, double *dbl) { - register PyObject *obj = *v; + register PyObject *obj = *v; - if (PyLong_Check(obj)) { - *dbl = PyLong_AsDouble(obj); - if (*dbl == -1.0 && PyErr_Occurred()) { - *v = NULL; - return -1; - } - } - else { - Py_INCREF(Py_NotImplemented); - *v = Py_NotImplemented; - return -1; - } - return 0; + if (PyLong_Check(obj)) { + *dbl = PyLong_AsDouble(obj); + if (*dbl == -1.0 && PyErr_Occurred()) { + *v = NULL; + return -1; + } + } + else { + Py_INCREF(Py_NotImplemented); + *v = Py_NotImplemented; + return -1; + } + return 0; } static PyObject * @@ -298,7 +298,7 @@ Py_DTSF_ADD_DOT_0, NULL); if (!buf) - return PyErr_NoMemory(); + return PyErr_NoMemory(); result = PyUnicode_FromString(buf); PyMem_Free(buf); return result; @@ -334,341 +334,341 @@ static PyObject* float_richcompare(PyObject *v, PyObject *w, int op) { - double i, j; - int r = 0; + double i, j; + int r = 0; - assert(PyFloat_Check(v)); - i = PyFloat_AS_DOUBLE(v); + assert(PyFloat_Check(v)); + i = PyFloat_AS_DOUBLE(v); - /* Switch on the type of w. Set i and j to doubles to be compared, - * and op to the richcomp to use. - */ - if (PyFloat_Check(w)) - j = PyFloat_AS_DOUBLE(w); - - else if (!Py_IS_FINITE(i)) { - if (PyLong_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. - */ - j = 0.0; - else - goto Unimplemented; - } - - else if (PyLong_Check(w)) { - int vsign = i == 0.0 ? 0 : i < 0.0 ? -1 : 1; - int wsign = _PyLong_Sign(w); - size_t nbits; - int exponent; - - if (vsign != wsign) { - /* Magnitudes are irrelevant -- the signs alone - * determine the outcome. - */ - i = (double)vsign; - j = (double)wsign; - goto Compare; - } - /* The signs are the same. */ - /* Convert w to a double if it fits. In particular, 0 fits. */ - nbits = _PyLong_NumBits(w); - if (nbits == (size_t)-1 && PyErr_Occurred()) { - /* This long is so large that size_t isn't big enough - * to hold the # of bits. Replace with little doubles - * that give the same outcome -- w is so large that - * its magnitude must exceed the magnitude of any - * finite float. - */ - PyErr_Clear(); - i = (double)vsign; - assert(wsign != 0); - j = wsign * 2.0; - goto Compare; - } - if (nbits <= 48) { - j = PyLong_AsDouble(w); - /* It's impossible that <= 48 bits overflowed. */ - assert(j != -1.0 || ! PyErr_Occurred()); - goto Compare; - } - assert(wsign != 0); /* else nbits was 0 */ - assert(vsign != 0); /* if vsign were 0, then since wsign is - * not 0, we would have taken the - * vsign != wsign branch at the start */ - /* We want to work with non-negative numbers. */ - if (vsign < 0) { - /* "Multiply both sides" by -1; this also swaps the - * comparator. - */ - i = -i; - op = _Py_SwappedOp[op]; - } - assert(i > 0.0); - (void) frexp(i, &exponent); - /* exponent is the # of bits in v before the radix point; - * we know that nbits (the # of bits in w) > 48 at this point - */ - if (exponent < 0 || (size_t)exponent < nbits) { - i = 1.0; - j = 2.0; - goto Compare; - } - if ((size_t)exponent > nbits) { - i = 2.0; - j = 1.0; - goto Compare; - } - /* v and w have the same number of bits before the radix - * point. Construct two longs that have the same comparison - * outcome. - */ - { - double fracpart; - double intpart; - PyObject *result = NULL; - PyObject *one = NULL; - PyObject *vv = NULL; - PyObject *ww = w; - - if (wsign < 0) { - ww = PyNumber_Negative(w); - if (ww == NULL) - goto Error; - } - else - Py_INCREF(ww); - - fracpart = modf(i, &intpart); - vv = PyLong_FromDouble(intpart); - if (vv == NULL) - goto Error; - - if (fracpart != 0.0) { - /* Shift left, and or a 1 bit into vv - * to represent the lost fraction. - */ - PyObject *temp; - - one = PyLong_FromLong(1); - if (one == NULL) - goto Error; - - temp = PyNumber_Lshift(ww, one); - if (temp == NULL) - goto Error; - Py_DECREF(ww); - ww = temp; - - temp = PyNumber_Lshift(vv, one); - if (temp == NULL) - goto Error; - Py_DECREF(vv); - vv = temp; - - temp = PyNumber_Or(vv, one); - if (temp == NULL) - goto Error; - Py_DECREF(vv); - vv = temp; - } - - r = PyObject_RichCompareBool(vv, ww, op); - if (r < 0) - goto Error; - result = PyBool_FromLong(r); - Error: - Py_XDECREF(vv); - Py_XDECREF(ww); - Py_XDECREF(one); - return result; - } - } /* else if (PyLong_Check(w)) */ + /* Switch on the type of w. Set i and j to doubles to be compared, + * and op to the richcomp to use. + */ + if (PyFloat_Check(w)) + j = PyFloat_AS_DOUBLE(w); + + else if (!Py_IS_FINITE(i)) { + if (PyLong_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. + */ + j = 0.0; + else + goto Unimplemented; + } + + else if (PyLong_Check(w)) { + int vsign = i == 0.0 ? 0 : i < 0.0 ? -1 : 1; + int wsign = _PyLong_Sign(w); + size_t nbits; + int exponent; + + if (vsign != wsign) { + /* Magnitudes are irrelevant -- the signs alone + * determine the outcome. + */ + i = (double)vsign; + j = (double)wsign; + goto Compare; + } + /* The signs are the same. */ + /* Convert w to a double if it fits. In particular, 0 fits. */ + nbits = _PyLong_NumBits(w); + if (nbits == (size_t)-1 && PyErr_Occurred()) { + /* This long is so large that size_t isn't big enough + * to hold the # of bits. Replace with little doubles + * that give the same outcome -- w is so large that + * its magnitude must exceed the magnitude of any + * finite float. + */ + PyErr_Clear(); + i = (double)vsign; + assert(wsign != 0); + j = wsign * 2.0; + goto Compare; + } + if (nbits <= 48) { + j = PyLong_AsDouble(w); + /* It's impossible that <= 48 bits overflowed. */ + assert(j != -1.0 || ! PyErr_Occurred()); + goto Compare; + } + assert(wsign != 0); /* else nbits was 0 */ + assert(vsign != 0); /* if vsign were 0, then since wsign is + * not 0, we would have taken the + * vsign != wsign branch at the start */ + /* We want to work with non-negative numbers. */ + if (vsign < 0) { + /* "Multiply both sides" by -1; this also swaps the + * comparator. + */ + i = -i; + op = _Py_SwappedOp[op]; + } + assert(i > 0.0); + (void) frexp(i, &exponent); + /* exponent is the # of bits in v before the radix point; + * we know that nbits (the # of bits in w) > 48 at this point + */ + if (exponent < 0 || (size_t)exponent < nbits) { + i = 1.0; + j = 2.0; + goto Compare; + } + if ((size_t)exponent > nbits) { + i = 2.0; + j = 1.0; + goto Compare; + } + /* v and w have the same number of bits before the radix + * point. Construct two longs that have the same comparison + * outcome. + */ + { + double fracpart; + double intpart; + PyObject *result = NULL; + PyObject *one = NULL; + PyObject *vv = NULL; + PyObject *ww = w; + + if (wsign < 0) { + ww = PyNumber_Negative(w); + if (ww == NULL) + goto Error; + } + else + Py_INCREF(ww); + + fracpart = modf(i, &intpart); + vv = PyLong_FromDouble(intpart); + if (vv == NULL) + goto Error; + + if (fracpart != 0.0) { + /* Shift left, and or a 1 bit into vv + * to represent the lost fraction. + */ + PyObject *temp; + + one = PyLong_FromLong(1); + if (one == NULL) + goto Error; + + temp = PyNumber_Lshift(ww, one); + if (temp == NULL) + goto Error; + Py_DECREF(ww); + ww = temp; + + temp = PyNumber_Lshift(vv, one); + if (temp == NULL) + goto Error; + Py_DECREF(vv); + vv = temp; + + temp = PyNumber_Or(vv, one); + if (temp == NULL) + goto Error; + Py_DECREF(vv); + vv = temp; + } + + r = PyObject_RichCompareBool(vv, ww, op); + if (r < 0) + goto Error; + result = PyBool_FromLong(r); + Error: + Py_XDECREF(vv); + Py_XDECREF(ww); + Py_XDECREF(one); + return result; + } + } /* else if (PyLong_Check(w)) */ - else /* w isn't float, int, or long */ - goto Unimplemented; + else /* w isn't float, int, or long */ + goto Unimplemented; Compare: - PyFPE_START_PROTECT("richcompare", return NULL) - switch (op) { - case Py_EQ: - r = i == j; - break; - case Py_NE: - r = i != j; - break; - case Py_LE: - r = i <= j; - break; - case Py_GE: - r = i >= j; - break; - case Py_LT: - r = i < j; - break; - case Py_GT: - r = i > j; - break; - } - PyFPE_END_PROTECT(r) - return PyBool_FromLong(r); + PyFPE_START_PROTECT("richcompare", return NULL) + switch (op) { + case Py_EQ: + r = i == j; + break; + case Py_NE: + r = i != j; + break; + case Py_LE: + r = i <= j; + break; + case Py_GE: + r = i >= j; + break; + case Py_LT: + r = i < j; + break; + case Py_GT: + r = i > j; + break; + } + PyFPE_END_PROTECT(r) + return PyBool_FromLong(r); Unimplemented: - Py_INCREF(Py_NotImplemented); - return Py_NotImplemented; + Py_INCREF(Py_NotImplemented); + return Py_NotImplemented; } static long float_hash(PyFloatObject *v) { - return _Py_HashDouble(v->ob_fval); + return _Py_HashDouble(v->ob_fval); } static PyObject * float_add(PyObject *v, PyObject *w) { - double a,b; - CONVERT_TO_DOUBLE(v, a); - CONVERT_TO_DOUBLE(w, b); - PyFPE_START_PROTECT("add", return 0) - a = a + b; - PyFPE_END_PROTECT(a) - return PyFloat_FromDouble(a); + double a,b; + CONVERT_TO_DOUBLE(v, a); + CONVERT_TO_DOUBLE(w, b); + PyFPE_START_PROTECT("add", return 0) + a = a + b; + PyFPE_END_PROTECT(a) + return PyFloat_FromDouble(a); } static PyObject * float_sub(PyObject *v, PyObject *w) { - double a,b; - CONVERT_TO_DOUBLE(v, a); - CONVERT_TO_DOUBLE(w, b); - PyFPE_START_PROTECT("subtract", return 0) - a = a - b; - PyFPE_END_PROTECT(a) - return PyFloat_FromDouble(a); + double a,b; + CONVERT_TO_DOUBLE(v, a); + CONVERT_TO_DOUBLE(w, b); + PyFPE_START_PROTECT("subtract", return 0) + a = a - b; + PyFPE_END_PROTECT(a) + return PyFloat_FromDouble(a); } static PyObject * float_mul(PyObject *v, PyObject *w) { - double a,b; - CONVERT_TO_DOUBLE(v, a); - CONVERT_TO_DOUBLE(w, b); - PyFPE_START_PROTECT("multiply", return 0) - a = a * b; - PyFPE_END_PROTECT(a) - return PyFloat_FromDouble(a); + double a,b; + CONVERT_TO_DOUBLE(v, a); + CONVERT_TO_DOUBLE(w, b); + PyFPE_START_PROTECT("multiply", return 0) + a = a * b; + PyFPE_END_PROTECT(a) + return PyFloat_FromDouble(a); } static PyObject * float_div(PyObject *v, PyObject *w) { - double a,b; - CONVERT_TO_DOUBLE(v, a); - CONVERT_TO_DOUBLE(w, b); + double a,b; + CONVERT_TO_DOUBLE(v, a); + CONVERT_TO_DOUBLE(w, b); #ifdef Py_NAN - if (b == 0.0) { - PyErr_SetString(PyExc_ZeroDivisionError, - "float division by zero"); - return NULL; - } + if (b == 0.0) { + PyErr_SetString(PyExc_ZeroDivisionError, + "float division by zero"); + return NULL; + } #endif - PyFPE_START_PROTECT("divide", return 0) - a = a / b; - PyFPE_END_PROTECT(a) - return PyFloat_FromDouble(a); + PyFPE_START_PROTECT("divide", return 0) + a = a / b; + PyFPE_END_PROTECT(a) + return PyFloat_FromDouble(a); } static PyObject * float_rem(PyObject *v, PyObject *w) { - double vx, wx; - double mod; - CONVERT_TO_DOUBLE(v, vx); - CONVERT_TO_DOUBLE(w, wx); + double vx, wx; + double mod; + CONVERT_TO_DOUBLE(v, vx); + CONVERT_TO_DOUBLE(w, wx); #ifdef Py_NAN - if (wx == 0.0) { - PyErr_SetString(PyExc_ZeroDivisionError, - "float modulo"); - return NULL; - } + if (wx == 0.0) { + PyErr_SetString(PyExc_ZeroDivisionError, + "float modulo"); + return NULL; + } #endif - PyFPE_START_PROTECT("modulo", return 0) - mod = fmod(vx, wx); - /* note: checking mod*wx < 0 is incorrect -- underflows to - 0 if wx < sqrt(smallest nonzero double) */ - if (mod && ((wx < 0) != (mod < 0))) { - mod += wx; - } - PyFPE_END_PROTECT(mod) - return PyFloat_FromDouble(mod); + PyFPE_START_PROTECT("modulo", return 0) + mod = fmod(vx, wx); + /* note: checking mod*wx < 0 is incorrect -- underflows to + 0 if wx < sqrt(smallest nonzero double) */ + if (mod && ((wx < 0) != (mod < 0))) { + mod += wx; + } + PyFPE_END_PROTECT(mod) + return PyFloat_FromDouble(mod); } static PyObject * float_divmod(PyObject *v, PyObject *w) { - double vx, wx; - double div, mod, floordiv; - CONVERT_TO_DOUBLE(v, vx); - CONVERT_TO_DOUBLE(w, wx); - if (wx == 0.0) { - PyErr_SetString(PyExc_ZeroDivisionError, "float divmod()"); - return NULL; - } - PyFPE_START_PROTECT("divmod", return 0) - mod = fmod(vx, wx); - /* fmod is typically exact, so vx-mod is *mathematically* an - exact multiple of wx. But this is fp arithmetic, and fp - vx - mod is an approximation; the result is that div may - not be an exact integral value after the division, although - it will always be very close to one. - */ - div = (vx - mod) / wx; - if (mod) { - /* ensure the remainder has the same sign as the denominator */ - if ((wx < 0) != (mod < 0)) { - mod += wx; - div -= 1.0; - } - } - else { - /* the remainder is zero, and in the presence of signed zeroes - fmod returns different results across platforms; ensure - it has the same sign as the denominator; we'd like to do - "mod = wx * 0.0", but that may get optimized away */ - mod *= mod; /* hide "mod = +0" from optimizer */ - if (wx < 0.0) - mod = -mod; - } - /* snap quotient to nearest integral value */ - if (div) { - floordiv = floor(div); - if (div - floordiv > 0.5) - floordiv += 1.0; - } - else { - /* div is zero - get the same sign as the true quotient */ - div *= div; /* hide "div = +0" from optimizers */ - floordiv = div * vx / wx; /* zero w/ sign of vx/wx */ - } - PyFPE_END_PROTECT(floordiv) - return Py_BuildValue("(dd)", floordiv, mod); + double vx, wx; + double div, mod, floordiv; + CONVERT_TO_DOUBLE(v, vx); + CONVERT_TO_DOUBLE(w, wx); + if (wx == 0.0) { + PyErr_SetString(PyExc_ZeroDivisionError, "float divmod()"); + return NULL; + } + PyFPE_START_PROTECT("divmod", return 0) + mod = fmod(vx, wx); + /* fmod is typically exact, so vx-mod is *mathematically* an + exact multiple of wx. But this is fp arithmetic, and fp + vx - mod is an approximation; the result is that div may + not be an exact integral value after the division, although + it will always be very close to one. + */ + div = (vx - mod) / wx; + if (mod) { + /* ensure the remainder has the same sign as the denominator */ + if ((wx < 0) != (mod < 0)) { + mod += wx; + div -= 1.0; + } + } + else { + /* the remainder is zero, and in the presence of signed zeroes + fmod returns different results across platforms; ensure + it has the same sign as the denominator; we'd like to do + "mod = wx * 0.0", but that may get optimized away */ + mod *= mod; /* hide "mod = +0" from optimizer */ + if (wx < 0.0) + mod = -mod; + } + /* snap quotient to nearest integral value */ + if (div) { + floordiv = floor(div); + if (div - floordiv > 0.5) + floordiv += 1.0; + } + else { + /* div is zero - get the same sign as the true quotient */ + div *= div; /* hide "div = +0" from optimizers */ + floordiv = div * vx / wx; /* zero w/ sign of vx/wx */ + } + PyFPE_END_PROTECT(floordiv) + return Py_BuildValue("(dd)", floordiv, mod); } static PyObject * float_floor_div(PyObject *v, PyObject *w) { - PyObject *t, *r; + PyObject *t, *r; - t = float_divmod(v, w); - if (t == NULL || t == Py_NotImplemented) - return t; - assert(PyTuple_CheckExact(t)); - r = PyTuple_GET_ITEM(t, 0); - Py_INCREF(r); - Py_DECREF(t); - return r; + t = float_divmod(v, w); + if (t == NULL || t == Py_NotImplemented) + return t; + assert(PyTuple_CheckExact(t)); + r = PyTuple_GET_ITEM(t, 0); + Py_INCREF(r); + Py_DECREF(t); + return r; } /* determine whether x is an odd integer or not; assumes that @@ -678,123 +678,123 @@ static PyObject * float_pow(PyObject *v, PyObject *w, PyObject *z) { - double iv, iw, ix; - int negate_result = 0; + double iv, iw, ix; + int negate_result = 0; - if ((PyObject *)z != Py_None) { - PyErr_SetString(PyExc_TypeError, "pow() 3rd argument not " - "allowed unless all arguments are integers"); - return NULL; - } - - CONVERT_TO_DOUBLE(v, iv); - CONVERT_TO_DOUBLE(w, iw); - - /* Sort out special cases here instead of relying on pow() */ - if (iw == 0) { /* v**0 is 1, even 0**0 */ - return PyFloat_FromDouble(1.0); - } - if (Py_IS_NAN(iv)) { /* nan**w = nan, unless w == 0 */ - return PyFloat_FromDouble(iv); - } - if (Py_IS_NAN(iw)) { /* v**nan = nan, unless v == 1; 1**nan = 1 */ - return PyFloat_FromDouble(iv == 1.0 ? 1.0 : iw); - } - if (Py_IS_INFINITY(iw)) { - /* v**inf is: 0.0 if abs(v) < 1; 1.0 if abs(v) == 1; inf if - * abs(v) > 1 (including case where v infinite) - * - * v**-inf is: inf if abs(v) < 1; 1.0 if abs(v) == 1; 0.0 if - * abs(v) > 1 (including case where v infinite) - */ - iv = fabs(iv); - if (iv == 1.0) - return PyFloat_FromDouble(1.0); - else if ((iw > 0.0) == (iv > 1.0)) - return PyFloat_FromDouble(fabs(iw)); /* return inf */ - else - return PyFloat_FromDouble(0.0); - } - if (Py_IS_INFINITY(iv)) { - /* (+-inf)**w is: inf for w positive, 0 for w negative; in - * both cases, we need to add the appropriate sign if w is - * an odd integer. - */ - int iw_is_odd = DOUBLE_IS_ODD_INTEGER(iw); - if (iw > 0.0) - return PyFloat_FromDouble(iw_is_odd ? iv : fabs(iv)); - else - return PyFloat_FromDouble(iw_is_odd ? - copysign(0.0, iv) : 0.0); - } - if (iv == 0.0) { /* 0**w is: 0 for w positive, 1 for w zero - (already dealt with above), and an error - if w is negative. */ - int iw_is_odd = DOUBLE_IS_ODD_INTEGER(iw); - if (iw < 0.0) { - PyErr_SetString(PyExc_ZeroDivisionError, - "0.0 cannot be raised to a " - "negative power"); - return NULL; - } - /* use correct sign if iw is odd */ - return PyFloat_FromDouble(iw_is_odd ? iv : 0.0); - } - - if (iv < 0.0) { - /* Whether this is an error is a mess, and bumps into libm - * bugs so we have to figure it out ourselves. - */ - if (iw != floor(iw)) { - /* Negative numbers raised to fractional powers - * become complex. - */ - return PyComplex_Type.tp_as_number->nb_power(v, w, z); - } - /* iw is an exact integer, albeit perhaps a very large - * one. Replace iv by its absolute value and remember - * to negate the pow result if iw is odd. - */ - iv = -iv; - negate_result = DOUBLE_IS_ODD_INTEGER(iw); - } - - if (iv == 1.0) { /* 1**w is 1, even 1**inf and 1**nan */ - /* (-1) ** large_integer also ends up here. Here's an - * extract from the comments for the previous - * implementation explaining why this special case is - * necessary: - * - * -1 raised to an exact integer should never be exceptional. - * Alas, some libms (chiefly glibc as of early 2003) return - * NaN and set EDOM on pow(-1, large_int) if the int doesn't - * happen to be representable in a *C* integer. That's a - * bug. - */ - return PyFloat_FromDouble(negate_result ? -1.0 : 1.0); - } - - /* Now iv and iw are finite, iw is nonzero, and iv is - * positive and not equal to 1.0. We finally allow - * the platform pow to step in and do the rest. - */ - errno = 0; - PyFPE_START_PROTECT("pow", return NULL) - ix = pow(iv, iw); - PyFPE_END_PROTECT(ix) - Py_ADJUST_ERANGE1(ix); - if (negate_result) - ix = -ix; - - if (errno != 0) { - /* We don't expect any errno value other than ERANGE, but - * the range of libm bugs appears unbounded. - */ - PyErr_SetFromErrno(errno == ERANGE ? PyExc_OverflowError : - PyExc_ValueError); - return NULL; - } - return PyFloat_FromDouble(ix); + if ((PyObject *)z != Py_None) { + PyErr_SetString(PyExc_TypeError, "pow() 3rd argument not " + "allowed unless all arguments are integers"); + return NULL; + } + + CONVERT_TO_DOUBLE(v, iv); + CONVERT_TO_DOUBLE(w, iw); + + /* Sort out special cases here instead of relying on pow() */ + if (iw == 0) { /* v**0 is 1, even 0**0 */ + return PyFloat_FromDouble(1.0); + } + if (Py_IS_NAN(iv)) { /* nan**w = nan, unless w == 0 */ + return PyFloat_FromDouble(iv); + } + if (Py_IS_NAN(iw)) { /* v**nan = nan, unless v == 1; 1**nan = 1 */ + return PyFloat_FromDouble(iv == 1.0 ? 1.0 : iw); + } + if (Py_IS_INFINITY(iw)) { + /* v**inf is: 0.0 if abs(v) < 1; 1.0 if abs(v) == 1; inf if + * abs(v) > 1 (including case where v infinite) + * + * v**-inf is: inf if abs(v) < 1; 1.0 if abs(v) == 1; 0.0 if + * abs(v) > 1 (including case where v infinite) + */ + iv = fabs(iv); + if (iv == 1.0) + return PyFloat_FromDouble(1.0); + else if ((iw > 0.0) == (iv > 1.0)) + return PyFloat_FromDouble(fabs(iw)); /* return inf */ + else + return PyFloat_FromDouble(0.0); + } + if (Py_IS_INFINITY(iv)) { + /* (+-inf)**w is: inf for w positive, 0 for w negative; in + * both cases, we need to add the appropriate sign if w is + * an odd integer. + */ + int iw_is_odd = DOUBLE_IS_ODD_INTEGER(iw); + if (iw > 0.0) + return PyFloat_FromDouble(iw_is_odd ? iv : fabs(iv)); + else + return PyFloat_FromDouble(iw_is_odd ? + copysign(0.0, iv) : 0.0); + } + if (iv == 0.0) { /* 0**w is: 0 for w positive, 1 for w zero + (already dealt with above), and an error + if w is negative. */ + int iw_is_odd = DOUBLE_IS_ODD_INTEGER(iw); + if (iw < 0.0) { + PyErr_SetString(PyExc_ZeroDivisionError, + "0.0 cannot be raised to a " + "negative power"); + return NULL; + } + /* use correct sign if iw is odd */ + return PyFloat_FromDouble(iw_is_odd ? iv : 0.0); + } + + if (iv < 0.0) { + /* Whether this is an error is a mess, and bumps into libm + * bugs so we have to figure it out ourselves. + */ + if (iw != floor(iw)) { + /* Negative numbers raised to fractional powers + * become complex. + */ + return PyComplex_Type.tp_as_number->nb_power(v, w, z); + } + /* iw is an exact integer, albeit perhaps a very large + * one. Replace iv by its absolute value and remember + * to negate the pow result if iw is odd. + */ + iv = -iv; + negate_result = DOUBLE_IS_ODD_INTEGER(iw); + } + + if (iv == 1.0) { /* 1**w is 1, even 1**inf and 1**nan */ + /* (-1) ** large_integer also ends up here. Here's an + * extract from the comments for the previous + * implementation explaining why this special case is + * necessary: + * + * -1 raised to an exact integer should never be exceptional. + * Alas, some libms (chiefly glibc as of early 2003) return + * NaN and set EDOM on pow(-1, large_int) if the int doesn't + * happen to be representable in a *C* integer. That's a + * bug. + */ + return PyFloat_FromDouble(negate_result ? -1.0 : 1.0); + } + + /* Now iv and iw are finite, iw is nonzero, and iv is + * positive and not equal to 1.0. We finally allow + * the platform pow to step in and do the rest. + */ + errno = 0; + PyFPE_START_PROTECT("pow", return NULL) + ix = pow(iv, iw); + PyFPE_END_PROTECT(ix) + Py_ADJUST_ERANGE1(ix); + if (negate_result) + ix = -ix; + + if (errno != 0) { + /* We don't expect any errno value other than ERANGE, but + * the range of libm bugs appears unbounded. + */ + PyErr_SetFromErrno(errno == ERANGE ? PyExc_OverflowError : + PyExc_ValueError); + return NULL; + } + return PyFloat_FromDouble(ix); } #undef DOUBLE_IS_ODD_INTEGER @@ -802,97 +802,97 @@ static PyObject * float_neg(PyFloatObject *v) { - return PyFloat_FromDouble(-v->ob_fval); + return PyFloat_FromDouble(-v->ob_fval); } static PyObject * float_abs(PyFloatObject *v) { - return PyFloat_FromDouble(fabs(v->ob_fval)); + return PyFloat_FromDouble(fabs(v->ob_fval)); } static int float_bool(PyFloatObject *v) { - return v->ob_fval != 0.0; + return v->ob_fval != 0.0; } static PyObject * float_is_integer(PyObject *v) { - double x = PyFloat_AsDouble(v); - PyObject *o; - - if (x == -1.0 && PyErr_Occurred()) - return NULL; - if (!Py_IS_FINITE(x)) - Py_RETURN_FALSE; - errno = 0; - PyFPE_START_PROTECT("is_integer", return NULL) - o = (floor(x) == x) ? Py_True : Py_False; - PyFPE_END_PROTECT(x) - if (errno != 0) { - PyErr_SetFromErrno(errno == ERANGE ? PyExc_OverflowError : - PyExc_ValueError); - return NULL; - } - Py_INCREF(o); - return o; + double x = PyFloat_AsDouble(v); + PyObject *o; + + if (x == -1.0 && PyErr_Occurred()) + return NULL; + if (!Py_IS_FINITE(x)) + Py_RETURN_FALSE; + errno = 0; + PyFPE_START_PROTECT("is_integer", return NULL) + o = (floor(x) == x) ? Py_True : Py_False; + PyFPE_END_PROTECT(x) + if (errno != 0) { + PyErr_SetFromErrno(errno == ERANGE ? PyExc_OverflowError : + PyExc_ValueError); + return NULL; + } + Py_INCREF(o); + return o; } #if 0 static PyObject * float_is_inf(PyObject *v) { - double x = PyFloat_AsDouble(v); - if (x == -1.0 && PyErr_Occurred()) - return NULL; - return PyBool_FromLong((long)Py_IS_INFINITY(x)); + double x = PyFloat_AsDouble(v); + if (x == -1.0 && PyErr_Occurred()) + return NULL; + return PyBool_FromLong((long)Py_IS_INFINITY(x)); } static PyObject * float_is_nan(PyObject *v) { - double x = PyFloat_AsDouble(v); - if (x == -1.0 && PyErr_Occurred()) - return NULL; - return PyBool_FromLong((long)Py_IS_NAN(x)); + double x = PyFloat_AsDouble(v); + if (x == -1.0 && PyErr_Occurred()) + return NULL; + return PyBool_FromLong((long)Py_IS_NAN(x)); } static PyObject * float_is_finite(PyObject *v) { - double x = PyFloat_AsDouble(v); - if (x == -1.0 && PyErr_Occurred()) - return NULL; - return PyBool_FromLong((long)Py_IS_FINITE(x)); + double x = PyFloat_AsDouble(v); + if (x == -1.0 && PyErr_Occurred()) + return NULL; + return PyBool_FromLong((long)Py_IS_FINITE(x)); } #endif static PyObject * float_trunc(PyObject *v) { - double x = PyFloat_AsDouble(v); - double wholepart; /* integral portion of x, rounded toward 0 */ + double x = PyFloat_AsDouble(v); + double wholepart; /* integral portion of x, rounded toward 0 */ - (void)modf(x, &wholepart); - /* Try to get out cheap if this fits in a Python int. The attempt - * to cast to long must be protected, as C doesn't define what - * happens if the double is too big to fit in a long. Some rare - * systems raise an exception then (RISCOS was mentioned as one, - * and someone using a non-default option on Sun also bumped into - * that). Note that checking for >= and <= LONG_{MIN,MAX} would - * still be vulnerable: if a long has more bits of precision than - * a double, casting MIN/MAX to double may yield an approximation, - * and if that's rounded up, then, e.g., wholepart=LONG_MAX+1 would - * yield true from the C expression wholepart<=LONG_MAX, despite - * that wholepart is actually greater than LONG_MAX. - */ - if (LONG_MIN < wholepart && wholepart < LONG_MAX) { - const long aslong = (long)wholepart; - return PyLong_FromLong(aslong); - } - return PyLong_FromDouble(wholepart); + (void)modf(x, &wholepart); + /* Try to get out cheap if this fits in a Python int. The attempt + * to cast to long must be protected, as C doesn't define what + * happens if the double is too big to fit in a long. Some rare + * systems raise an exception then (RISCOS was mentioned as one, + * and someone using a non-default option on Sun also bumped into + * that). Note that checking for >= and <= LONG_{MIN,MAX} would + * still be vulnerable: if a long has more bits of precision than + * a double, casting MIN/MAX to double may yield an approximation, + * and if that's rounded up, then, e.g., wholepart=LONG_MAX+1 would + * yield true from the C expression wholepart<=LONG_MAX, despite + * that wholepart is actually greater than LONG_MAX. + */ + if (LONG_MIN < wholepart && wholepart < LONG_MAX) { + const long aslong = (long)wholepart; + return PyLong_FromLong(aslong); + } + return PyLong_FromDouble(wholepart); } /* double_round: rounds a finite double to the closest multiple of @@ -907,49 +907,49 @@ static PyObject * double_round(double x, int ndigits) { - double rounded; - Py_ssize_t buflen, mybuflen=100; - char *buf, *buf_end, shortbuf[100], *mybuf=shortbuf; - int decpt, sign; - PyObject *result = NULL; - - /* round to a decimal string */ - buf = _Py_dg_dtoa(x, 3, ndigits, &decpt, &sign, &buf_end); - if (buf == NULL) { - PyErr_NoMemory(); - return NULL; - } - - /* Get new buffer if shortbuf is too small. Space needed <= buf_end - - buf + 8: (1 extra for '0', 1 for sign, 5 for exp, 1 for '\0'). */ - buflen = buf_end - buf; - if (buflen + 8 > mybuflen) { - mybuflen = buflen+8; - mybuf = (char *)PyMem_Malloc(mybuflen); - if (mybuf == NULL) { - PyErr_NoMemory(); - goto exit; - } - } - /* copy buf to mybuf, adding exponent, sign and leading 0 */ - PyOS_snprintf(mybuf, mybuflen, "%s0%se%d", (sign ? "-" : ""), - buf, decpt - (int)buflen); - - /* and convert the resulting string back to a double */ - errno = 0; - rounded = _Py_dg_strtod(mybuf, NULL); - if (errno == ERANGE && fabs(rounded) >= 1.) - PyErr_SetString(PyExc_OverflowError, - "rounded value too large to represent"); - else - result = PyFloat_FromDouble(rounded); - - /* done computing value; now clean up */ - if (mybuf != shortbuf) - PyMem_Free(mybuf); + double rounded; + Py_ssize_t buflen, mybuflen=100; + char *buf, *buf_end, shortbuf[100], *mybuf=shortbuf; + int decpt, sign; + PyObject *result = NULL; + + /* round to a decimal string */ + buf = _Py_dg_dtoa(x, 3, ndigits, &decpt, &sign, &buf_end); + if (buf == NULL) { + PyErr_NoMemory(); + return NULL; + } + + /* Get new buffer if shortbuf is too small. Space needed <= buf_end - + buf + 8: (1 extra for '0', 1 for sign, 5 for exp, 1 for '\0'). */ + buflen = buf_end - buf; + if (buflen + 8 > mybuflen) { + mybuflen = buflen+8; + mybuf = (char *)PyMem_Malloc(mybuflen); + if (mybuf == NULL) { + PyErr_NoMemory(); + goto exit; + } + } + /* copy buf to mybuf, adding exponent, sign and leading 0 */ + PyOS_snprintf(mybuf, mybuflen, "%s0%se%d", (sign ? "-" : ""), + buf, decpt - (int)buflen); + + /* and convert the resulting string back to a double */ + errno = 0; + rounded = _Py_dg_strtod(mybuf, NULL); + if (errno == ERANGE && fabs(rounded) >= 1.) + PyErr_SetString(PyExc_OverflowError, + "rounded value too large to represent"); + else + result = PyFloat_FromDouble(rounded); + + /* done computing value; now clean up */ + if (mybuf != shortbuf) + PyMem_Free(mybuf); exit: - _Py_dg_freedtoa(buf); - return result; + _Py_dg_freedtoa(buf); + return result; } #else /* PY_NO_SHORT_FLOAT_REPR */ @@ -959,47 +959,47 @@ static PyObject * double_round(double x, int ndigits) { - double pow1, pow2, y, z; - if (ndigits >= 0) { - if (ndigits > 22) { - /* pow1 and pow2 are each safe from overflow, but - pow1*pow2 ~= pow(10.0, ndigits) might overflow */ - pow1 = pow(10.0, (double)(ndigits-22)); - pow2 = 1e22; - } - else { - pow1 = pow(10.0, (double)ndigits); - pow2 = 1.0; - } - y = (x*pow1)*pow2; - /* if y overflows, then rounded value is exactly x */ - if (!Py_IS_FINITE(y)) - return PyFloat_FromDouble(x); - } - else { - pow1 = pow(10.0, (double)-ndigits); - pow2 = 1.0; /* unused; silences a gcc compiler warning */ - y = x / pow1; - } - - z = round(y); - if (fabs(y-z) == 0.5) - /* halfway between two integers; use round-half-even */ - z = 2.0*round(y/2.0); - - if (ndigits >= 0) - z = (z / pow2) / pow1; - else - z *= pow1; - - /* if computation resulted in overflow, raise OverflowError */ - if (!Py_IS_FINITE(z)) { - PyErr_SetString(PyExc_OverflowError, - "overflow occurred during round"); - return NULL; - } + double pow1, pow2, y, z; + if (ndigits >= 0) { + if (ndigits > 22) { + /* pow1 and pow2 are each safe from overflow, but + pow1*pow2 ~= pow(10.0, ndigits) might overflow */ + pow1 = pow(10.0, (double)(ndigits-22)); + pow2 = 1e22; + } + else { + pow1 = pow(10.0, (double)ndigits); + pow2 = 1.0; + } + y = (x*pow1)*pow2; + /* if y overflows, then rounded value is exactly x */ + if (!Py_IS_FINITE(y)) + return PyFloat_FromDouble(x); + } + else { + pow1 = pow(10.0, (double)-ndigits); + pow2 = 1.0; /* unused; silences a gcc compiler warning */ + y = x / pow1; + } + + z = round(y); + if (fabs(y-z) == 0.5) + /* halfway between two integers; use round-half-even */ + z = 2.0*round(y/2.0); + + if (ndigits >= 0) + z = (z / pow2) / pow1; + else + z *= pow1; + + /* if computation resulted in overflow, raise OverflowError */ + if (!Py_IS_FINITE(z)) { + PyErr_SetString(PyExc_OverflowError, + "overflow occurred during round"); + return NULL; + } - return PyFloat_FromDouble(z); + return PyFloat_FromDouble(z); } #endif /* PY_NO_SHORT_FLOAT_REPR */ @@ -1009,45 +1009,45 @@ static PyObject * float_round(PyObject *v, PyObject *args) { - double x, rounded; - PyObject *o_ndigits = NULL; - Py_ssize_t ndigits; - - x = PyFloat_AsDouble(v); - if (!PyArg_ParseTuple(args, "|O", &o_ndigits)) - return NULL; - if (o_ndigits == NULL) { - /* single-argument round: round to nearest integer */ - rounded = round(x); - if (fabs(x-rounded) == 0.5) - /* halfway case: round to even */ - rounded = 2.0*round(x/2.0); - return PyLong_FromDouble(rounded); - } - - /* interpret second argument as a Py_ssize_t; clips on overflow */ - ndigits = PyNumber_AsSsize_t(o_ndigits, NULL); - if (ndigits == -1 && PyErr_Occurred()) - return NULL; - - /* nans and infinities round to themselves */ - if (!Py_IS_FINITE(x)) - return PyFloat_FromDouble(x); - - /* Deal with extreme values for ndigits. For ndigits > NDIGITS_MAX, x - always rounds to itself. For ndigits < NDIGITS_MIN, x always - rounds to +-0.0. Here 0.30103 is an upper bound for log10(2). */ + double x, rounded; + PyObject *o_ndigits = NULL; + Py_ssize_t ndigits; + + x = PyFloat_AsDouble(v); + if (!PyArg_ParseTuple(args, "|O", &o_ndigits)) + return NULL; + if (o_ndigits == NULL) { + /* single-argument round: round to nearest integer */ + rounded = round(x); + if (fabs(x-rounded) == 0.5) + /* halfway case: round to even */ + rounded = 2.0*round(x/2.0); + return PyLong_FromDouble(rounded); + } + + /* interpret second argument as a Py_ssize_t; clips on overflow */ + ndigits = PyNumber_AsSsize_t(o_ndigits, NULL); + if (ndigits == -1 && PyErr_Occurred()) + return NULL; + + /* nans and infinities round to themselves */ + if (!Py_IS_FINITE(x)) + return PyFloat_FromDouble(x); + + /* Deal with extreme values for ndigits. For ndigits > NDIGITS_MAX, x + always rounds to itself. For ndigits < NDIGITS_MIN, x always + rounds to +-0.0. Here 0.30103 is an upper bound for log10(2). */ #define NDIGITS_MAX ((int)((DBL_MANT_DIG-DBL_MIN_EXP) * 0.30103)) #define NDIGITS_MIN (-(int)((DBL_MAX_EXP + 1) * 0.30103)) - if (ndigits > NDIGITS_MAX) - /* return x */ - return PyFloat_FromDouble(x); - else if (ndigits < NDIGITS_MIN) - /* return 0.0, but with sign of x */ - return PyFloat_FromDouble(0.0*x); - else - /* finite x, and ndigits is not unreasonably large */ - return double_round(x, (int)ndigits); + if (ndigits > NDIGITS_MAX) + /* return x */ + return PyFloat_FromDouble(x); + else if (ndigits < NDIGITS_MIN) + /* return 0.0, but with sign of x */ + return PyFloat_FromDouble(0.0*x); + else + /* finite x, and ndigits is not unreasonably large */ + return double_round(x, (int)ndigits); #undef NDIGITS_MAX #undef NDIGITS_MIN } @@ -1055,11 +1055,11 @@ static PyObject * float_float(PyObject *v) { - if (PyFloat_CheckExact(v)) - Py_INCREF(v); - else - v = PyFloat_FromDouble(((PyFloatObject *)v)->ob_fval); - return v; + if (PyFloat_CheckExact(v)) + Py_INCREF(v); + else + v = PyFloat_FromDouble(((PyFloatObject *)v)->ob_fval); + return v; } /* turn ASCII hex characters into integer values and vice versa */ @@ -1067,73 +1067,73 @@ static char char_from_hex(int x) { - assert(0 <= x && x < 16); - return "0123456789abcdef"[x]; + assert(0 <= x && x < 16); + return "0123456789abcdef"[x]; } static int hex_from_char(char c) { - int x; - switch(c) { - case '0': - x = 0; - break; - case '1': - x = 1; - break; - case '2': - x = 2; - break; - case '3': - x = 3; - break; - case '4': - x = 4; - break; - case '5': - x = 5; - break; - case '6': - x = 6; - break; - case '7': - x = 7; - break; - case '8': - x = 8; - break; - case '9': - x = 9; - break; - case 'a': - case 'A': - x = 10; - break; - case 'b': - case 'B': - x = 11; - break; - case 'c': - case 'C': - x = 12; - break; - case 'd': - case 'D': - x = 13; - break; - case 'e': - case 'E': - x = 14; - break; - case 'f': - case 'F': - x = 15; - break; - default: - x = -1; - break; - } - return x; + int x; + switch(c) { + case '0': + x = 0; + break; + case '1': + x = 1; + break; + case '2': + x = 2; + break; + case '3': + x = 3; + break; + case '4': + x = 4; + break; + case '5': + x = 5; + break; + case '6': + x = 6; + break; + case '7': + x = 7; + break; + case '8': + x = 8; + break; + case '9': + x = 9; + break; + case 'a': + case 'A': + x = 10; + break; + case 'b': + case 'B': + x = 11; + break; + case 'c': + case 'C': + x = 12; + break; + case 'd': + case 'D': + x = 13; + break; + case 'e': + case 'E': + x = 14; + break; + case 'f': + case 'F': + x = 15; + break; + default: + x = -1; + break; + } + return x; } /* convert a float to a hexadecimal string */ @@ -1145,54 +1145,54 @@ static PyObject * float_hex(PyObject *v) { - double x, m; - int e, shift, i, si, esign; - /* Space for 1+(TOHEX_NBITS-1)/4 digits, a decimal point, and the - trailing NUL byte. */ - char s[(TOHEX_NBITS-1)/4+3]; - - CONVERT_TO_DOUBLE(v, x); - - if (Py_IS_NAN(x) || Py_IS_INFINITY(x)) - return float_str((PyFloatObject *)v); - - if (x == 0.0) { - if(copysign(1.0, x) == -1.0) - return PyUnicode_FromString("-0x0.0p+0"); - else - return PyUnicode_FromString("0x0.0p+0"); - } - - m = frexp(fabs(x), &e); - shift = 1 - MAX(DBL_MIN_EXP - e, 0); - m = ldexp(m, shift); - e -= shift; - - si = 0; - s[si] = char_from_hex((int)m); - si++; - m -= (int)m; - s[si] = '.'; - si++; - for (i=0; i < (TOHEX_NBITS-1)/4; i++) { - m *= 16.0; - s[si] = char_from_hex((int)m); - si++; - m -= (int)m; - } - s[si] = '\0'; - - if (e < 0) { - esign = (int)'-'; - e = -e; - } - else - esign = (int)'+'; - - if (x < 0.0) - return PyUnicode_FromFormat("-0x%sp%c%d", s, esign, e); - else - return PyUnicode_FromFormat("0x%sp%c%d", s, esign, e); + double x, m; + int e, shift, i, si, esign; + /* Space for 1+(TOHEX_NBITS-1)/4 digits, a decimal point, and the + trailing NUL byte. */ + char s[(TOHEX_NBITS-1)/4+3]; + + CONVERT_TO_DOUBLE(v, x); + + if (Py_IS_NAN(x) || Py_IS_INFINITY(x)) + return float_str((PyFloatObject *)v); + + if (x == 0.0) { + if(copysign(1.0, x) == -1.0) + return PyUnicode_FromString("-0x0.0p+0"); + else + return PyUnicode_FromString("0x0.0p+0"); + } + + m = frexp(fabs(x), &e); + shift = 1 - MAX(DBL_MIN_EXP - e, 0); + m = ldexp(m, shift); + e -= shift; + + si = 0; + s[si] = char_from_hex((int)m); + si++; + m -= (int)m; + s[si] = '.'; + si++; + for (i=0; i < (TOHEX_NBITS-1)/4; i++) { + m *= 16.0; + s[si] = char_from_hex((int)m); + si++; + m -= (int)m; + } + s[si] = '\0'; + + if (e < 0) { + esign = (int)'-'; + e = -e; + } + else + esign = (int)'+'; + + if (x < 0.0) + return PyUnicode_FromFormat("-0x%sp%c%d", s, esign, e); + else + return PyUnicode_FromFormat("0x%sp%c%d", s, esign, e); } PyDoc_STRVAR(float_hex_doc, @@ -1209,242 +1209,242 @@ static PyObject * float_fromhex(PyObject *cls, PyObject *arg) { - PyObject *result_as_float, *result; - double x; - long exp, top_exp, lsb, key_digit; - char *s, *coeff_start, *s_store, *coeff_end, *exp_start, *s_end; - int half_eps, digit, round_up, negate=0; - Py_ssize_t length, ndigits, fdigits, i; - - /* - * For the sake of simplicity and correctness, we impose an artificial - * limit on ndigits, the total number of hex digits in the coefficient - * The limit is chosen to ensure that, writing exp for the exponent, - * - * (1) if exp > LONG_MAX/2 then the value of the hex string is - * guaranteed to overflow (provided it's nonzero) - * - * (2) if exp < LONG_MIN/2 then the value of the hex string is - * guaranteed to underflow to 0. - * - * (3) if LONG_MIN/2 <= exp <= LONG_MAX/2 then there's no danger of - * overflow in the calculation of exp and top_exp below. - * - * More specifically, ndigits is assumed to satisfy the following - * inequalities: - * - * 4*ndigits <= DBL_MIN_EXP - DBL_MANT_DIG - LONG_MIN/2 - * 4*ndigits <= LONG_MAX/2 + 1 - DBL_MAX_EXP - * - * If either of these inequalities is not satisfied, a ValueError is - * raised. Otherwise, write x for the value of the hex string, and - * assume x is nonzero. Then - * - * 2**(exp-4*ndigits) <= |x| < 2**(exp+4*ndigits). - * - * Now if exp > LONG_MAX/2 then: - * - * exp - 4*ndigits >= LONG_MAX/2 + 1 - (LONG_MAX/2 + 1 - DBL_MAX_EXP) - * = DBL_MAX_EXP - * - * so |x| >= 2**DBL_MAX_EXP, which is too large to be stored in C - * double, so overflows. If exp < LONG_MIN/2, then - * - * exp + 4*ndigits <= LONG_MIN/2 - 1 + ( - * DBL_MIN_EXP - DBL_MANT_DIG - LONG_MIN/2) - * = DBL_MIN_EXP - DBL_MANT_DIG - 1 - * - * and so |x| < 2**(DBL_MIN_EXP-DBL_MANT_DIG-1), hence underflows to 0 - * when converted to a C double. - * - * It's easy to show that if LONG_MIN/2 <= exp <= LONG_MAX/2 then both - * exp+4*ndigits and exp-4*ndigits are within the range of a long. - */ - - s = _PyUnicode_AsStringAndSize(arg, &length); - if (s == NULL) - return NULL; - s_end = s + length; - - /******************** - * Parse the string * - ********************/ - - /* leading whitespace */ - while (Py_ISSPACE(*s)) - s++; - - /* infinities and nans */ - x = _Py_parse_inf_or_nan(s, &coeff_end); - if (coeff_end != s) { - s = coeff_end; - goto finished; - } - - /* optional sign */ - if (*s == '-') { - s++; - negate = 1; - } - else if (*s == '+') - s++; - - /* [0x] */ - s_store = s; - if (*s == '0') { - s++; - if (*s == 'x' || *s == 'X') - s++; - else - s = s_store; - } - - /* coefficient: [. ] */ - coeff_start = s; - while (hex_from_char(*s) >= 0) - s++; - s_store = s; - if (*s == '.') { - s++; - while (hex_from_char(*s) >= 0) - s++; - coeff_end = s-1; - } - else - coeff_end = s; - - /* ndigits = total # of hex digits; fdigits = # after point */ - ndigits = coeff_end - coeff_start; - fdigits = coeff_end - s_store; - if (ndigits == 0) - goto parse_error; - if (ndigits > MIN(DBL_MIN_EXP - DBL_MANT_DIG - LONG_MIN/2, - LONG_MAX/2 + 1 - DBL_MAX_EXP)/4) - goto insane_length_error; - - /* [p ] */ - if (*s == 'p' || *s == 'P') { - s++; - exp_start = s; - if (*s == '-' || *s == '+') - s++; - if (!('0' <= *s && *s <= '9')) - goto parse_error; - s++; - while ('0' <= *s && *s <= '9') - s++; - exp = strtol(exp_start, NULL, 10); - } - else - exp = 0; + PyObject *result_as_float, *result; + double x; + long exp, top_exp, lsb, key_digit; + char *s, *coeff_start, *s_store, *coeff_end, *exp_start, *s_end; + int half_eps, digit, round_up, negate=0; + Py_ssize_t length, ndigits, fdigits, i; + + /* + * For the sake of simplicity and correctness, we impose an artificial + * limit on ndigits, the total number of hex digits in the coefficient + * The limit is chosen to ensure that, writing exp for the exponent, + * + * (1) if exp > LONG_MAX/2 then the value of the hex string is + * guaranteed to overflow (provided it's nonzero) + * + * (2) if exp < LONG_MIN/2 then the value of the hex string is + * guaranteed to underflow to 0. + * + * (3) if LONG_MIN/2 <= exp <= LONG_MAX/2 then there's no danger of + * overflow in the calculation of exp and top_exp below. + * + * More specifically, ndigits is assumed to satisfy the following + * inequalities: + * + * 4*ndigits <= DBL_MIN_EXP - DBL_MANT_DIG - LONG_MIN/2 + * 4*ndigits <= LONG_MAX/2 + 1 - DBL_MAX_EXP + * + * If either of these inequalities is not satisfied, a ValueError is + * raised. Otherwise, write x for the value of the hex string, and + * assume x is nonzero. Then + * + * 2**(exp-4*ndigits) <= |x| < 2**(exp+4*ndigits). + * + * Now if exp > LONG_MAX/2 then: + * + * exp - 4*ndigits >= LONG_MAX/2 + 1 - (LONG_MAX/2 + 1 - DBL_MAX_EXP) + * = DBL_MAX_EXP + * + * so |x| >= 2**DBL_MAX_EXP, which is too large to be stored in C + * double, so overflows. If exp < LONG_MIN/2, then + * + * exp + 4*ndigits <= LONG_MIN/2 - 1 + ( + * DBL_MIN_EXP - DBL_MANT_DIG - LONG_MIN/2) + * = DBL_MIN_EXP - DBL_MANT_DIG - 1 + * + * and so |x| < 2**(DBL_MIN_EXP-DBL_MANT_DIG-1), hence underflows to 0 + * when converted to a C double. + * + * It's easy to show that if LONG_MIN/2 <= exp <= LONG_MAX/2 then both + * exp+4*ndigits and exp-4*ndigits are within the range of a long. + */ + + s = _PyUnicode_AsStringAndSize(arg, &length); + if (s == NULL) + return NULL; + s_end = s + length; + + /******************** + * Parse the string * + ********************/ + + /* leading whitespace */ + while (Py_ISSPACE(*s)) + s++; + + /* infinities and nans */ + x = _Py_parse_inf_or_nan(s, &coeff_end); + if (coeff_end != s) { + s = coeff_end; + goto finished; + } + + /* optional sign */ + if (*s == '-') { + s++; + negate = 1; + } + else if (*s == '+') + s++; + + /* [0x] */ + s_store = s; + if (*s == '0') { + s++; + if (*s == 'x' || *s == 'X') + s++; + else + s = s_store; + } + + /* coefficient: [. ] */ + coeff_start = s; + while (hex_from_char(*s) >= 0) + s++; + s_store = s; + if (*s == '.') { + s++; + while (hex_from_char(*s) >= 0) + s++; + coeff_end = s-1; + } + else + coeff_end = s; + + /* ndigits = total # of hex digits; fdigits = # after point */ + ndigits = coeff_end - coeff_start; + fdigits = coeff_end - s_store; + if (ndigits == 0) + goto parse_error; + if (ndigits > MIN(DBL_MIN_EXP - DBL_MANT_DIG - LONG_MIN/2, + LONG_MAX/2 + 1 - DBL_MAX_EXP)/4) + goto insane_length_error; + + /* [p ] */ + if (*s == 'p' || *s == 'P') { + s++; + exp_start = s; + if (*s == '-' || *s == '+') + s++; + if (!('0' <= *s && *s <= '9')) + goto parse_error; + s++; + while ('0' <= *s && *s <= '9') + s++; + exp = strtol(exp_start, NULL, 10); + } + else + exp = 0; /* for 0 <= j < ndigits, HEX_DIGIT(j) gives the jth most significant digit */ -#define HEX_DIGIT(j) hex_from_char(*((j) < fdigits ? \ - coeff_end-(j) : \ - coeff_end-1-(j))) - - /******************************************* - * Compute rounded value of the hex string * - *******************************************/ - - /* Discard leading zeros, and catch extreme overflow and underflow */ - while (ndigits > 0 && HEX_DIGIT(ndigits-1) == 0) - ndigits--; - if (ndigits == 0 || exp < LONG_MIN/2) { - x = 0.0; - goto finished; - } - if (exp > LONG_MAX/2) - goto overflow_error; - - /* Adjust exponent for fractional part. */ - exp = exp - 4*((long)fdigits); - - /* top_exp = 1 more than exponent of most sig. bit of coefficient */ - top_exp = exp + 4*((long)ndigits - 1); - for (digit = HEX_DIGIT(ndigits-1); digit != 0; digit /= 2) - top_exp++; - - /* catch almost all nonextreme cases of overflow and underflow here */ - if (top_exp < DBL_MIN_EXP - DBL_MANT_DIG) { - x = 0.0; - goto finished; - } - if (top_exp > DBL_MAX_EXP) - goto overflow_error; - - /* lsb = exponent of least significant bit of the *rounded* value. - This is top_exp - DBL_MANT_DIG unless result is subnormal. */ - lsb = MAX(top_exp, (long)DBL_MIN_EXP) - DBL_MANT_DIG; - - x = 0.0; - if (exp >= lsb) { - /* no rounding required */ - for (i = ndigits-1; i >= 0; i--) - x = 16.0*x + HEX_DIGIT(i); - x = ldexp(x, (int)(exp)); - goto finished; - } - /* rounding required. key_digit is the index of the hex digit - containing the first bit to be rounded away. */ - half_eps = 1 << (int)((lsb - exp - 1) % 4); - key_digit = (lsb - exp - 1) / 4; - for (i = ndigits-1; i > key_digit; i--) - x = 16.0*x + HEX_DIGIT(i); - digit = HEX_DIGIT(key_digit); - x = 16.0*x + (double)(digit & (16-2*half_eps)); - - /* round-half-even: round up if bit lsb-1 is 1 and at least one of - bits lsb, lsb-2, lsb-3, lsb-4, ... is 1. */ - if ((digit & half_eps) != 0) { - round_up = 0; - if ((digit & (3*half_eps-1)) != 0 || - (half_eps == 8 && (HEX_DIGIT(key_digit+1) & 1) != 0)) - round_up = 1; - else - for (i = key_digit-1; i >= 0; i--) - if (HEX_DIGIT(i) != 0) { - round_up = 1; - break; - } - if (round_up == 1) { - x += 2*half_eps; - if (top_exp == DBL_MAX_EXP && - x == ldexp((double)(2*half_eps), DBL_MANT_DIG)) - /* overflow corner case: pre-rounded value < - 2**DBL_MAX_EXP; rounded=2**DBL_MAX_EXP. */ - goto overflow_error; - } - } - x = ldexp(x, (int)(exp+4*key_digit)); +#define HEX_DIGIT(j) hex_from_char(*((j) < fdigits ? \ + coeff_end-(j) : \ + coeff_end-1-(j))) + + /******************************************* + * Compute rounded value of the hex string * + *******************************************/ + + /* Discard leading zeros, and catch extreme overflow and underflow */ + while (ndigits > 0 && HEX_DIGIT(ndigits-1) == 0) + ndigits--; + if (ndigits == 0 || exp < LONG_MIN/2) { + x = 0.0; + goto finished; + } + if (exp > LONG_MAX/2) + goto overflow_error; + + /* Adjust exponent for fractional part. */ + exp = exp - 4*((long)fdigits); + + /* top_exp = 1 more than exponent of most sig. bit of coefficient */ + top_exp = exp + 4*((long)ndigits - 1); + for (digit = HEX_DIGIT(ndigits-1); digit != 0; digit /= 2) + top_exp++; + + /* catch almost all nonextreme cases of overflow and underflow here */ + if (top_exp < DBL_MIN_EXP - DBL_MANT_DIG) { + x = 0.0; + goto finished; + } + if (top_exp > DBL_MAX_EXP) + goto overflow_error; + + /* lsb = exponent of least significant bit of the *rounded* value. + This is top_exp - DBL_MANT_DIG unless result is subnormal. */ + lsb = MAX(top_exp, (long)DBL_MIN_EXP) - DBL_MANT_DIG; + + x = 0.0; + if (exp >= lsb) { + /* no rounding required */ + for (i = ndigits-1; i >= 0; i--) + x = 16.0*x + HEX_DIGIT(i); + x = ldexp(x, (int)(exp)); + goto finished; + } + /* rounding required. key_digit is the index of the hex digit + containing the first bit to be rounded away. */ + half_eps = 1 << (int)((lsb - exp - 1) % 4); + key_digit = (lsb - exp - 1) / 4; + for (i = ndigits-1; i > key_digit; i--) + x = 16.0*x + HEX_DIGIT(i); + digit = HEX_DIGIT(key_digit); + x = 16.0*x + (double)(digit & (16-2*half_eps)); + + /* round-half-even: round up if bit lsb-1 is 1 and at least one of + bits lsb, lsb-2, lsb-3, lsb-4, ... is 1. */ + if ((digit & half_eps) != 0) { + round_up = 0; + if ((digit & (3*half_eps-1)) != 0 || + (half_eps == 8 && (HEX_DIGIT(key_digit+1) & 1) != 0)) + round_up = 1; + else + for (i = key_digit-1; i >= 0; i--) + if (HEX_DIGIT(i) != 0) { + round_up = 1; + break; + } + if (round_up == 1) { + x += 2*half_eps; + if (top_exp == DBL_MAX_EXP && + x == ldexp((double)(2*half_eps), DBL_MANT_DIG)) + /* overflow corner case: pre-rounded value < + 2**DBL_MAX_EXP; rounded=2**DBL_MAX_EXP. */ + goto overflow_error; + } + } + x = ldexp(x, (int)(exp+4*key_digit)); finished: - /* optional trailing whitespace leading to the end of the string */ - while (Py_ISSPACE(*s)) - s++; - if (s != s_end) - goto parse_error; - result_as_float = Py_BuildValue("(d)", negate ? -x : x); - if (result_as_float == NULL) - return NULL; - result = PyObject_CallObject(cls, result_as_float); - Py_DECREF(result_as_float); - return result; + /* optional trailing whitespace leading to the end of the string */ + while (Py_ISSPACE(*s)) + s++; + if (s != s_end) + goto parse_error; + result_as_float = Py_BuildValue("(d)", negate ? -x : x); + if (result_as_float == NULL) + return NULL; + result = PyObject_CallObject(cls, result_as_float); + Py_DECREF(result_as_float); + return result; overflow_error: - PyErr_SetString(PyExc_OverflowError, - "hexadecimal value too large to represent as a float"); - return NULL; + PyErr_SetString(PyExc_OverflowError, + "hexadecimal value too large to represent as a float"); + return NULL; parse_error: - PyErr_SetString(PyExc_ValueError, - "invalid hexadecimal floating-point string"); - return NULL; + PyErr_SetString(PyExc_ValueError, + "invalid hexadecimal floating-point string"); + return NULL; insane_length_error: - PyErr_SetString(PyExc_ValueError, - "hexadecimal string too long to convert"); - return NULL; + PyErr_SetString(PyExc_ValueError, + "hexadecimal string too long to convert"); + return NULL; } PyDoc_STRVAR(float_fromhex_doc, @@ -1460,79 +1460,79 @@ static PyObject * float_as_integer_ratio(PyObject *v, PyObject *unused) { - double self; - double float_part; - int exponent; - int i; - - PyObject *prev; - PyObject *py_exponent = NULL; - PyObject *numerator = NULL; - PyObject *denominator = NULL; - PyObject *result_pair = NULL; - PyNumberMethods *long_methods = PyLong_Type.tp_as_number; + double self; + double float_part; + int exponent; + int i; + + PyObject *prev; + PyObject *py_exponent = NULL; + PyObject *numerator = NULL; + PyObject *denominator = NULL; + PyObject *result_pair = NULL; + PyNumberMethods *long_methods = PyLong_Type.tp_as_number; #define INPLACE_UPDATE(obj, call) \ - prev = obj; \ - obj = call; \ - Py_DECREF(prev); \ - - CONVERT_TO_DOUBLE(v, self); - - if (Py_IS_INFINITY(self)) { - PyErr_SetString(PyExc_OverflowError, - "Cannot pass infinity to float.as_integer_ratio."); - return NULL; - } + prev = obj; \ + obj = call; \ + Py_DECREF(prev); \ + + CONVERT_TO_DOUBLE(v, self); + + if (Py_IS_INFINITY(self)) { + PyErr_SetString(PyExc_OverflowError, + "Cannot pass infinity to float.as_integer_ratio."); + return NULL; + } #ifdef Py_NAN - if (Py_IS_NAN(self)) { - PyErr_SetString(PyExc_ValueError, - "Cannot pass NaN to float.as_integer_ratio."); - return NULL; - } + if (Py_IS_NAN(self)) { + PyErr_SetString(PyExc_ValueError, + "Cannot pass NaN to float.as_integer_ratio."); + return NULL; + } #endif - PyFPE_START_PROTECT("as_integer_ratio", goto error); - float_part = frexp(self, &exponent); /* self == float_part * 2**exponent exactly */ - PyFPE_END_PROTECT(float_part); - - for (i=0; i<300 && float_part != floor(float_part) ; i++) { - float_part *= 2.0; - exponent--; - } - /* self == float_part * 2**exponent exactly and float_part is integral. - If FLT_RADIX != 2, the 300 steps may leave a tiny fractional part - to be truncated by PyLong_FromDouble(). */ - - numerator = PyLong_FromDouble(float_part); - if (numerator == NULL) goto error; - - /* fold in 2**exponent */ - denominator = PyLong_FromLong(1); - py_exponent = PyLong_FromLong(labs((long)exponent)); - if (py_exponent == NULL) goto error; - INPLACE_UPDATE(py_exponent, - long_methods->nb_lshift(denominator, py_exponent)); - if (py_exponent == NULL) goto error; - if (exponent > 0) { - INPLACE_UPDATE(numerator, - long_methods->nb_multiply(numerator, py_exponent)); - if (numerator == NULL) goto error; - } - else { - Py_DECREF(denominator); - denominator = py_exponent; - py_exponent = NULL; - } + PyFPE_START_PROTECT("as_integer_ratio", goto error); + float_part = frexp(self, &exponent); /* self == float_part * 2**exponent exactly */ + PyFPE_END_PROTECT(float_part); + + for (i=0; i<300 && float_part != floor(float_part) ; i++) { + float_part *= 2.0; + exponent--; + } + /* self == float_part * 2**exponent exactly and float_part is integral. + If FLT_RADIX != 2, the 300 steps may leave a tiny fractional part + to be truncated by PyLong_FromDouble(). */ + + numerator = PyLong_FromDouble(float_part); + if (numerator == NULL) goto error; + + /* fold in 2**exponent */ + denominator = PyLong_FromLong(1); + py_exponent = PyLong_FromLong(labs((long)exponent)); + if (py_exponent == NULL) goto error; + INPLACE_UPDATE(py_exponent, + long_methods->nb_lshift(denominator, py_exponent)); + if (py_exponent == NULL) goto error; + if (exponent > 0) { + INPLACE_UPDATE(numerator, + long_methods->nb_multiply(numerator, py_exponent)); + if (numerator == NULL) goto error; + } + else { + Py_DECREF(denominator); + denominator = py_exponent; + py_exponent = NULL; + } - result_pair = PyTuple_Pack(2, numerator, denominator); + result_pair = PyTuple_Pack(2, numerator, denominator); #undef INPLACE_UPDATE error: - Py_XDECREF(py_exponent); - Py_XDECREF(denominator); - Py_XDECREF(numerator); - return result_pair; + Py_XDECREF(py_exponent); + Py_XDECREF(denominator); + Py_XDECREF(numerator); + return result_pair; } PyDoc_STRVAR(float_as_integer_ratio_doc, @@ -1556,18 +1556,18 @@ static PyObject * float_new(PyTypeObject *type, PyObject *args, PyObject *kwds) { - PyObject *x = Py_False; /* Integer zero */ - static char *kwlist[] = {"x", 0}; + PyObject *x = Py_False; /* Integer zero */ + static char *kwlist[] = {"x", 0}; - if (type != &PyFloat_Type) - return float_subtype_new(type, args, kwds); /* Wimp out */ - if (!PyArg_ParseTupleAndKeywords(args, kwds, "|O:float", kwlist, &x)) - return NULL; - /* If it's a string, but not a string subclass, use - PyFloat_FromString. */ - if (PyUnicode_CheckExact(x)) - return PyFloat_FromString(x); - return PyNumber_Float(x); + if (type != &PyFloat_Type) + return float_subtype_new(type, args, kwds); /* Wimp out */ + if (!PyArg_ParseTupleAndKeywords(args, kwds, "|O:float", kwlist, &x)) + return NULL; + /* If it's a string, but not a string subclass, use + PyFloat_FromString. */ + if (PyUnicode_CheckExact(x)) + return PyFloat_FromString(x); + return PyNumber_Float(x); } /* Wimpy, slow approach to tp_new calls for subtypes of float: @@ -1578,33 +1578,33 @@ static PyObject * float_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds) { - PyObject *tmp, *newobj; + PyObject *tmp, *newobj; - assert(PyType_IsSubtype(type, &PyFloat_Type)); - tmp = float_new(&PyFloat_Type, args, kwds); - if (tmp == NULL) - return NULL; - assert(PyFloat_CheckExact(tmp)); - newobj = type->tp_alloc(type, 0); - if (newobj == NULL) { - Py_DECREF(tmp); - return NULL; - } - ((PyFloatObject *)newobj)->ob_fval = ((PyFloatObject *)tmp)->ob_fval; - Py_DECREF(tmp); - return newobj; + assert(PyType_IsSubtype(type, &PyFloat_Type)); + tmp = float_new(&PyFloat_Type, args, kwds); + if (tmp == NULL) + return NULL; + assert(PyFloat_CheckExact(tmp)); + newobj = type->tp_alloc(type, 0); + if (newobj == NULL) { + Py_DECREF(tmp); + return NULL; + } + ((PyFloatObject *)newobj)->ob_fval = ((PyFloatObject *)tmp)->ob_fval; + Py_DECREF(tmp); + return newobj; } static PyObject * float_getnewargs(PyFloatObject *v) { - return Py_BuildValue("(d)", v->ob_fval); + return Py_BuildValue("(d)", v->ob_fval); } /* this is for the benefit of the pack/unpack routines below */ typedef enum { - unknown_format, ieee_big_endian_format, ieee_little_endian_format + unknown_format, ieee_big_endian_format, ieee_little_endian_format } float_format_type; static float_format_type double_format, float_format; @@ -1613,42 +1613,42 @@ static PyObject * float_getformat(PyTypeObject *v, PyObject* arg) { - char* s; - float_format_type r; + char* s; + float_format_type r; - if (!PyUnicode_Check(arg)) { - PyErr_Format(PyExc_TypeError, - "__getformat__() argument must be string, not %.500s", - Py_TYPE(arg)->tp_name); - return NULL; - } - s = _PyUnicode_AsString(arg); - if (s == NULL) - return NULL; - if (strcmp(s, "double") == 0) { - r = double_format; - } - else if (strcmp(s, "float") == 0) { - r = float_format; - } - else { - PyErr_SetString(PyExc_ValueError, - "__getformat__() argument 1 must be " - "'double' or 'float'"); - return NULL; - } - - switch (r) { - case unknown_format: - return PyUnicode_FromString("unknown"); - case ieee_little_endian_format: - return PyUnicode_FromString("IEEE, little-endian"); - case ieee_big_endian_format: - return PyUnicode_FromString("IEEE, big-endian"); - default: - Py_FatalError("insane float_format or double_format"); - return NULL; - } + if (!PyUnicode_Check(arg)) { + PyErr_Format(PyExc_TypeError, + "__getformat__() argument must be string, not %.500s", + Py_TYPE(arg)->tp_name); + return NULL; + } + s = _PyUnicode_AsString(arg); + if (s == NULL) + return NULL; + if (strcmp(s, "double") == 0) { + r = double_format; + } + else if (strcmp(s, "float") == 0) { + r = float_format; + } + else { + PyErr_SetString(PyExc_ValueError, + "__getformat__() argument 1 must be " + "'double' or 'float'"); + return NULL; + } + + switch (r) { + case unknown_format: + return PyUnicode_FromString("unknown"); + case ieee_little_endian_format: + return PyUnicode_FromString("IEEE, little-endian"); + case ieee_big_endian_format: + return PyUnicode_FromString("IEEE, big-endian"); + default: + Py_FatalError("insane float_format or double_format"); + return NULL; + } } PyDoc_STRVAR(float_getformat_doc, @@ -1664,57 +1664,57 @@ static PyObject * float_setformat(PyTypeObject *v, PyObject* args) { - char* typestr; - char* format; - float_format_type f; - float_format_type detected; - float_format_type *p; - - if (!PyArg_ParseTuple(args, "ss:__setformat__", &typestr, &format)) - return NULL; - - if (strcmp(typestr, "double") == 0) { - p = &double_format; - detected = detected_double_format; - } - else if (strcmp(typestr, "float") == 0) { - p = &float_format; - detected = detected_float_format; - } - else { - PyErr_SetString(PyExc_ValueError, - "__setformat__() argument 1 must " - "be 'double' or 'float'"); - return NULL; - } - - if (strcmp(format, "unknown") == 0) { - f = unknown_format; - } - else if (strcmp(format, "IEEE, little-endian") == 0) { - f = ieee_little_endian_format; - } - else if (strcmp(format, "IEEE, big-endian") == 0) { - f = ieee_big_endian_format; - } - else { - PyErr_SetString(PyExc_ValueError, - "__setformat__() argument 2 must be " - "'unknown', 'IEEE, little-endian' or " - "'IEEE, big-endian'"); - return NULL; - - } - - if (f != unknown_format && f != detected) { - PyErr_Format(PyExc_ValueError, - "can only set %s format to 'unknown' or the " - "detected platform value", typestr); - return NULL; - } + char* typestr; + char* format; + float_format_type f; + float_format_type detected; + float_format_type *p; + + if (!PyArg_ParseTuple(args, "ss:__setformat__", &typestr, &format)) + return NULL; + + if (strcmp(typestr, "double") == 0) { + p = &double_format; + detected = detected_double_format; + } + else if (strcmp(typestr, "float") == 0) { + p = &float_format; + detected = detected_float_format; + } + else { + PyErr_SetString(PyExc_ValueError, + "__setformat__() argument 1 must " + "be 'double' or 'float'"); + return NULL; + } + + if (strcmp(format, "unknown") == 0) { + f = unknown_format; + } + else if (strcmp(format, "IEEE, little-endian") == 0) { + f = ieee_little_endian_format; + } + else if (strcmp(format, "IEEE, big-endian") == 0) { + f = ieee_big_endian_format; + } + else { + PyErr_SetString(PyExc_ValueError, + "__setformat__() argument 2 must be " + "'unknown', 'IEEE, little-endian' or " + "'IEEE, big-endian'"); + return NULL; + + } + + if (f != unknown_format && f != detected) { + PyErr_Format(PyExc_ValueError, + "can only set %s format to 'unknown' or the " + "detected platform value", typestr); + return NULL; + } - *p = f; - Py_RETURN_NONE; + *p = f; + Py_RETURN_NONE; } PyDoc_STRVAR(float_setformat_doc, @@ -1733,19 +1733,19 @@ static PyObject * float_getzero(PyObject *v, void *closure) { - return PyFloat_FromDouble(0.0); + return PyFloat_FromDouble(0.0); } static PyObject * float__format__(PyObject *self, PyObject *args) { - PyObject *format_spec; + PyObject *format_spec; - if (!PyArg_ParseTuple(args, "U:__format__", &format_spec)) - return NULL; - return _PyFloat_FormatAdvanced(self, - PyUnicode_AS_UNICODE(format_spec), - PyUnicode_GET_SIZE(format_spec)); + if (!PyArg_ParseTuple(args, "U:__format__", &format_spec)) + return NULL; + return _PyFloat_FormatAdvanced(self, + PyUnicode_AS_UNICODE(format_spec), + PyUnicode_GET_SIZE(format_spec)); } PyDoc_STRVAR(float__format__doc, @@ -1755,45 +1755,45 @@ static PyMethodDef float_methods[] = { - {"conjugate", (PyCFunction)float_float, METH_NOARGS, - "Returns self, the complex conjugate of any float."}, - {"__trunc__", (PyCFunction)float_trunc, METH_NOARGS, - "Returns the Integral closest to x between 0 and x."}, - {"__round__", (PyCFunction)float_round, METH_VARARGS, - "Returns the Integral closest to x, rounding half toward even.\n" - "When an argument is passed, works like built-in round(x, ndigits)."}, - {"as_integer_ratio", (PyCFunction)float_as_integer_ratio, METH_NOARGS, - float_as_integer_ratio_doc}, - {"fromhex", (PyCFunction)float_fromhex, - METH_O|METH_CLASS, float_fromhex_doc}, - {"hex", (PyCFunction)float_hex, - METH_NOARGS, float_hex_doc}, - {"is_integer", (PyCFunction)float_is_integer, METH_NOARGS, - "Returns True if the float is an integer."}, + {"conjugate", (PyCFunction)float_float, METH_NOARGS, + "Returns self, the complex conjugate of any float."}, + {"__trunc__", (PyCFunction)float_trunc, METH_NOARGS, + "Returns the Integral closest to x between 0 and x."}, + {"__round__", (PyCFunction)float_round, METH_VARARGS, + "Returns the Integral closest to x, rounding half toward even.\n" + "When an argument is passed, works like built-in round(x, ndigits)."}, + {"as_integer_ratio", (PyCFunction)float_as_integer_ratio, METH_NOARGS, + float_as_integer_ratio_doc}, + {"fromhex", (PyCFunction)float_fromhex, + METH_O|METH_CLASS, float_fromhex_doc}, + {"hex", (PyCFunction)float_hex, + METH_NOARGS, float_hex_doc}, + {"is_integer", (PyCFunction)float_is_integer, METH_NOARGS, + "Returns True if the float is an integer."}, #if 0 - {"is_inf", (PyCFunction)float_is_inf, METH_NOARGS, - "Returns True if the float is positive or negative infinite."}, - {"is_finite", (PyCFunction)float_is_finite, METH_NOARGS, - "Returns True if the float is finite, neither infinite nor NaN."}, - {"is_nan", (PyCFunction)float_is_nan, METH_NOARGS, - "Returns True if the float is not a number (NaN)."}, + {"is_inf", (PyCFunction)float_is_inf, METH_NOARGS, + "Returns True if the float is positive or negative infinite."}, + {"is_finite", (PyCFunction)float_is_finite, METH_NOARGS, + "Returns True if the float is finite, neither infinite nor NaN."}, + {"is_nan", (PyCFunction)float_is_nan, METH_NOARGS, + "Returns True if the float is not a number (NaN)."}, #endif - {"__getnewargs__", (PyCFunction)float_getnewargs, METH_NOARGS}, - {"__getformat__", (PyCFunction)float_getformat, - METH_O|METH_CLASS, float_getformat_doc}, - {"__setformat__", (PyCFunction)float_setformat, - METH_VARARGS|METH_CLASS, float_setformat_doc}, - {"__format__", (PyCFunction)float__format__, - METH_VARARGS, float__format__doc}, - {NULL, NULL} /* sentinel */ + {"__getnewargs__", (PyCFunction)float_getnewargs, METH_NOARGS}, + {"__getformat__", (PyCFunction)float_getformat, + METH_O|METH_CLASS, float_getformat_doc}, + {"__setformat__", (PyCFunction)float_setformat, + METH_VARARGS|METH_CLASS, float_setformat_doc}, + {"__format__", (PyCFunction)float__format__, + METH_VARARGS, float__format__doc}, + {NULL, NULL} /* sentinel */ }; static PyGetSetDef float_getset[] = { - {"real", + {"real", (getter)float_float, (setter)NULL, "the real part of a complex number", NULL}, - {"imag", + {"imag", (getter)float_getzero, (setter)NULL, "the imaginary part of a complex number", NULL}, @@ -1807,229 +1807,229 @@ static PyNumberMethods float_as_number = { - float_add, /*nb_add*/ - float_sub, /*nb_subtract*/ - float_mul, /*nb_multiply*/ - float_rem, /*nb_remainder*/ - float_divmod, /*nb_divmod*/ - float_pow, /*nb_power*/ - (unaryfunc)float_neg, /*nb_negative*/ - (unaryfunc)float_float, /*nb_positive*/ - (unaryfunc)float_abs, /*nb_absolute*/ - (inquiry)float_bool, /*nb_bool*/ - 0, /*nb_invert*/ - 0, /*nb_lshift*/ - 0, /*nb_rshift*/ - 0, /*nb_and*/ - 0, /*nb_xor*/ - 0, /*nb_or*/ - float_trunc, /*nb_int*/ - 0, /*nb_reserved*/ - float_float, /*nb_float*/ - 0, /* nb_inplace_add */ - 0, /* nb_inplace_subtract */ - 0, /* nb_inplace_multiply */ - 0, /* nb_inplace_remainder */ - 0, /* nb_inplace_power */ - 0, /* nb_inplace_lshift */ - 0, /* nb_inplace_rshift */ - 0, /* nb_inplace_and */ - 0, /* nb_inplace_xor */ - 0, /* nb_inplace_or */ - float_floor_div, /* nb_floor_divide */ - float_div, /* nb_true_divide */ - 0, /* nb_inplace_floor_divide */ - 0, /* nb_inplace_true_divide */ + float_add, /*nb_add*/ + float_sub, /*nb_subtract*/ + float_mul, /*nb_multiply*/ + float_rem, /*nb_remainder*/ + float_divmod, /*nb_divmod*/ + float_pow, /*nb_power*/ + (unaryfunc)float_neg, /*nb_negative*/ + (unaryfunc)float_float, /*nb_positive*/ + (unaryfunc)float_abs, /*nb_absolute*/ + (inquiry)float_bool, /*nb_bool*/ + 0, /*nb_invert*/ + 0, /*nb_lshift*/ + 0, /*nb_rshift*/ + 0, /*nb_and*/ + 0, /*nb_xor*/ + 0, /*nb_or*/ + float_trunc, /*nb_int*/ + 0, /*nb_reserved*/ + float_float, /*nb_float*/ + 0, /* nb_inplace_add */ + 0, /* nb_inplace_subtract */ + 0, /* nb_inplace_multiply */ + 0, /* nb_inplace_remainder */ + 0, /* nb_inplace_power */ + 0, /* nb_inplace_lshift */ + 0, /* nb_inplace_rshift */ + 0, /* nb_inplace_and */ + 0, /* nb_inplace_xor */ + 0, /* nb_inplace_or */ + float_floor_div, /* nb_floor_divide */ + float_div, /* nb_true_divide */ + 0, /* nb_inplace_floor_divide */ + 0, /* nb_inplace_true_divide */ }; PyTypeObject PyFloat_Type = { - PyVarObject_HEAD_INIT(&PyType_Type, 0) - "float", - sizeof(PyFloatObject), - 0, - (destructor)float_dealloc, /* tp_dealloc */ - 0, /* tp_print */ - 0, /* tp_getattr */ - 0, /* tp_setattr */ - 0, /* tp_reserved */ - (reprfunc)float_repr, /* tp_repr */ - &float_as_number, /* tp_as_number */ - 0, /* tp_as_sequence */ - 0, /* tp_as_mapping */ - (hashfunc)float_hash, /* tp_hash */ - 0, /* tp_call */ - (reprfunc)float_str, /* tp_str */ - PyObject_GenericGetAttr, /* tp_getattro */ - 0, /* tp_setattro */ - 0, /* tp_as_buffer */ - Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */ - float_doc, /* tp_doc */ - 0, /* tp_traverse */ - 0, /* tp_clear */ - float_richcompare, /* tp_richcompare */ - 0, /* tp_weaklistoffset */ - 0, /* tp_iter */ - 0, /* tp_iternext */ - float_methods, /* tp_methods */ - 0, /* tp_members */ - float_getset, /* tp_getset */ - 0, /* tp_base */ - 0, /* tp_dict */ - 0, /* tp_descr_get */ - 0, /* tp_descr_set */ - 0, /* tp_dictoffset */ - 0, /* tp_init */ - 0, /* tp_alloc */ - float_new, /* tp_new */ + PyVarObject_HEAD_INIT(&PyType_Type, 0) + "float", + sizeof(PyFloatObject), + 0, + (destructor)float_dealloc, /* tp_dealloc */ + 0, /* tp_print */ + 0, /* tp_getattr */ + 0, /* tp_setattr */ + 0, /* tp_reserved */ + (reprfunc)float_repr, /* tp_repr */ + &float_as_number, /* tp_as_number */ + 0, /* tp_as_sequence */ + 0, /* tp_as_mapping */ + (hashfunc)float_hash, /* tp_hash */ + 0, /* tp_call */ + (reprfunc)float_str, /* tp_str */ + PyObject_GenericGetAttr, /* tp_getattro */ + 0, /* tp_setattro */ + 0, /* tp_as_buffer */ + Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */ + float_doc, /* tp_doc */ + 0, /* tp_traverse */ + 0, /* tp_clear */ + float_richcompare, /* tp_richcompare */ + 0, /* tp_weaklistoffset */ + 0, /* tp_iter */ + 0, /* tp_iternext */ + float_methods, /* tp_methods */ + 0, /* tp_members */ + float_getset, /* tp_getset */ + 0, /* tp_base */ + 0, /* tp_dict */ + 0, /* tp_descr_get */ + 0, /* tp_descr_set */ + 0, /* tp_dictoffset */ + 0, /* tp_init */ + 0, /* tp_alloc */ + float_new, /* tp_new */ }; void _PyFloat_Init(void) { - /* We attempt to determine if this machine is using IEEE - floating point formats by peering at the bits of some - carefully chosen values. If it looks like we are on an - IEEE platform, the float packing/unpacking routines can - just copy bits, if not they resort to arithmetic & shifts - and masks. The shifts & masks approach works on all finite - values, but what happens to infinities, NaNs and signed - zeroes on packing is an accident, and attempting to unpack - a NaN or an infinity will raise an exception. - - Note that if we're on some whacked-out platform which uses - IEEE formats but isn't strictly little-endian or big- - endian, we will fall back to the portable shifts & masks - method. */ + /* We attempt to determine if this machine is using IEEE + floating point formats by peering at the bits of some + carefully chosen values. If it looks like we are on an + IEEE platform, the float packing/unpacking routines can + just copy bits, if not they resort to arithmetic & shifts + and masks. The shifts & masks approach works on all finite + values, but what happens to infinities, NaNs and signed + zeroes on packing is an accident, and attempting to unpack + a NaN or an infinity will raise an exception. + + Note that if we're on some whacked-out platform which uses + IEEE formats but isn't strictly little-endian or big- + endian, we will fall back to the portable shifts & masks + method. */ #if SIZEOF_DOUBLE == 8 - { - double x = 9006104071832581.0; - if (memcmp(&x, "\x43\x3f\xff\x01\x02\x03\x04\x05", 8) == 0) - detected_double_format = ieee_big_endian_format; - else if (memcmp(&x, "\x05\x04\x03\x02\x01\xff\x3f\x43", 8) == 0) - detected_double_format = ieee_little_endian_format; - else - detected_double_format = unknown_format; - } + { + double x = 9006104071832581.0; + if (memcmp(&x, "\x43\x3f\xff\x01\x02\x03\x04\x05", 8) == 0) + detected_double_format = ieee_big_endian_format; + else if (memcmp(&x, "\x05\x04\x03\x02\x01\xff\x3f\x43", 8) == 0) + detected_double_format = ieee_little_endian_format; + else + detected_double_format = unknown_format; + } #else - detected_double_format = unknown_format; + detected_double_format = unknown_format; #endif #if SIZEOF_FLOAT == 4 - { - float y = 16711938.0; - if (memcmp(&y, "\x4b\x7f\x01\x02", 4) == 0) - detected_float_format = ieee_big_endian_format; - else if (memcmp(&y, "\x02\x01\x7f\x4b", 4) == 0) - detected_float_format = ieee_little_endian_format; - else - detected_float_format = unknown_format; - } + { + float y = 16711938.0; + if (memcmp(&y, "\x4b\x7f\x01\x02", 4) == 0) + detected_float_format = ieee_big_endian_format; + else if (memcmp(&y, "\x02\x01\x7f\x4b", 4) == 0) + detected_float_format = ieee_little_endian_format; + else + detected_float_format = unknown_format; + } #else - detected_float_format = unknown_format; + detected_float_format = unknown_format; #endif - double_format = detected_double_format; - float_format = detected_float_format; + double_format = detected_double_format; + float_format = detected_float_format; - /* Init float info */ - if (FloatInfoType.tp_name == 0) - PyStructSequence_InitType(&FloatInfoType, &floatinfo_desc); + /* Init float info */ + if (FloatInfoType.tp_name == 0) + PyStructSequence_InitType(&FloatInfoType, &floatinfo_desc); } int PyFloat_ClearFreeList(void) { - PyFloatObject *p; - PyFloatBlock *list, *next; - int i; - int u; /* remaining unfreed floats per block */ - int freelist_size = 0; - - list = block_list; - block_list = NULL; - free_list = NULL; - while (list != NULL) { - u = 0; - for (i = 0, p = &list->objects[0]; - i < N_FLOATOBJECTS; - i++, p++) { - if (PyFloat_CheckExact(p) && Py_REFCNT(p) != 0) - u++; - } - next = list->next; - if (u) { - list->next = block_list; - block_list = list; - for (i = 0, p = &list->objects[0]; - i < N_FLOATOBJECTS; - i++, p++) { - if (!PyFloat_CheckExact(p) || - Py_REFCNT(p) == 0) { - Py_TYPE(p) = (struct _typeobject *) - free_list; - free_list = p; - } - } - } - else { - PyMem_FREE(list); - } - freelist_size += u; - list = next; - } - return freelist_size; + PyFloatObject *p; + PyFloatBlock *list, *next; + int i; + int u; /* remaining unfreed floats per block */ + int freelist_size = 0; + + list = block_list; + block_list = NULL; + free_list = NULL; + while (list != NULL) { + u = 0; + for (i = 0, p = &list->objects[0]; + i < N_FLOATOBJECTS; + i++, p++) { + if (PyFloat_CheckExact(p) && Py_REFCNT(p) != 0) + u++; + } + next = list->next; + if (u) { + list->next = block_list; + block_list = list; + for (i = 0, p = &list->objects[0]; + i < N_FLOATOBJECTS; + i++, p++) { + if (!PyFloat_CheckExact(p) || + Py_REFCNT(p) == 0) { + Py_TYPE(p) = (struct _typeobject *) + free_list; + free_list = p; + } + } + } + else { + PyMem_FREE(list); + } + freelist_size += u; + list = next; + } + return freelist_size; } void PyFloat_Fini(void) { - PyFloatObject *p; - PyFloatBlock *list; - int i; - int u; /* total unfreed floats per block */ - - u = PyFloat_ClearFreeList(); - - if (!Py_VerboseFlag) - return; - fprintf(stderr, "# cleanup floats"); - if (!u) { - fprintf(stderr, "\n"); - } - else { - fprintf(stderr, - ": %d unfreed float%s\n", - u, u == 1 ? "" : "s"); - } - if (Py_VerboseFlag > 1) { - list = block_list; - while (list != NULL) { - for (i = 0, p = &list->objects[0]; - i < N_FLOATOBJECTS; - i++, p++) { - if (PyFloat_CheckExact(p) && - Py_REFCNT(p) != 0) { - char *buf = PyOS_double_to_string( - PyFloat_AS_DOUBLE(p), 'r', - 0, 0, NULL); - if (buf) { - /* XXX(twouters) cast - refcount to long - until %zd is - universally - available - */ - fprintf(stderr, - "# \n", - p, (long)Py_REFCNT(p), buf); - PyMem_Free(buf); - } - } - } - list = list->next; - } - } + PyFloatObject *p; + PyFloatBlock *list; + int i; + int u; /* total unfreed floats per block */ + + u = PyFloat_ClearFreeList(); + + if (!Py_VerboseFlag) + return; + fprintf(stderr, "# cleanup floats"); + if (!u) { + fprintf(stderr, "\n"); + } + else { + fprintf(stderr, + ": %d unfreed float%s\n", + u, u == 1 ? "" : "s"); + } + if (Py_VerboseFlag > 1) { + list = block_list; + while (list != NULL) { + for (i = 0, p = &list->objects[0]; + i < N_FLOATOBJECTS; + i++, p++) { + if (PyFloat_CheckExact(p) && + Py_REFCNT(p) != 0) { + char *buf = PyOS_double_to_string( + PyFloat_AS_DOUBLE(p), 'r', + 0, 0, NULL); + if (buf) { + /* XXX(twouters) cast + refcount to long + until %zd is + universally + available + */ + fprintf(stderr, + "# \n", + p, (long)Py_REFCNT(p), buf); + PyMem_Free(buf); + } + } + } + list = list->next; + } + } } /*---------------------------------------------------------------------------- @@ -2038,406 +2038,406 @@ int _PyFloat_Pack4(double x, unsigned char *p, int le) { - if (float_format == unknown_format) { - unsigned char sign; - int e; - double f; - unsigned int fbits; - int incr = 1; - - if (le) { - p += 3; - incr = -1; - } - - if (x < 0) { - sign = 1; - x = -x; - } - else - sign = 0; - - f = frexp(x, &e); - - /* Normalize f to be in the range [1.0, 2.0) */ - if (0.5 <= f && f < 1.0) { - f *= 2.0; - e--; - } - else if (f == 0.0) - e = 0; - else { - PyErr_SetString(PyExc_SystemError, - "frexp() result out of range"); - return -1; - } - - if (e >= 128) - goto Overflow; - else if (e < -126) { - /* Gradual underflow */ - f = ldexp(f, 126 + e); - e = 0; - } - else if (!(e == 0 && f == 0.0)) { - e += 127; - f -= 1.0; /* Get rid of leading 1 */ - } - - f *= 8388608.0; /* 2**23 */ - fbits = (unsigned int)(f + 0.5); /* Round */ - assert(fbits <= 8388608); - if (fbits >> 23) { - /* The carry propagated out of a string of 23 1 bits. */ - fbits = 0; - ++e; - if (e >= 255) - goto Overflow; - } - - /* First byte */ - *p = (sign << 7) | (e >> 1); - p += incr; - - /* Second byte */ - *p = (char) (((e & 1) << 7) | (fbits >> 16)); - p += incr; - - /* Third byte */ - *p = (fbits >> 8) & 0xFF; - p += incr; - - /* Fourth byte */ - *p = fbits & 0xFF; - - /* Done */ - return 0; - - } - else { - float y = (float)x; - const char *s = (char*)&y; - int i, incr = 1; - - if (Py_IS_INFINITY(y) && !Py_IS_INFINITY(x)) - goto Overflow; - - if ((float_format == ieee_little_endian_format && !le) - || (float_format == ieee_big_endian_format && le)) { - p += 3; - incr = -1; - } - - for (i = 0; i < 4; i++) { - *p = *s++; - p += incr; - } - return 0; - } + if (float_format == unknown_format) { + unsigned char sign; + int e; + double f; + unsigned int fbits; + int incr = 1; + + if (le) { + p += 3; + incr = -1; + } + + if (x < 0) { + sign = 1; + x = -x; + } + else + sign = 0; + + f = frexp(x, &e); + + /* Normalize f to be in the range [1.0, 2.0) */ + if (0.5 <= f && f < 1.0) { + f *= 2.0; + e--; + } + else if (f == 0.0) + e = 0; + else { + PyErr_SetString(PyExc_SystemError, + "frexp() result out of range"); + return -1; + } + + if (e >= 128) + goto Overflow; + else if (e < -126) { + /* Gradual underflow */ + f = ldexp(f, 126 + e); + e = 0; + } + else if (!(e == 0 && f == 0.0)) { + e += 127; + f -= 1.0; /* Get rid of leading 1 */ + } + + f *= 8388608.0; /* 2**23 */ + fbits = (unsigned int)(f + 0.5); /* Round */ + assert(fbits <= 8388608); + if (fbits >> 23) { + /* The carry propagated out of a string of 23 1 bits. */ + fbits = 0; + ++e; + if (e >= 255) + goto Overflow; + } + + /* First byte */ + *p = (sign << 7) | (e >> 1); + p += incr; + + /* Second byte */ + *p = (char) (((e & 1) << 7) | (fbits >> 16)); + p += incr; + + /* Third byte */ + *p = (fbits >> 8) & 0xFF; + p += incr; + + /* Fourth byte */ + *p = fbits & 0xFF; + + /* Done */ + return 0; + + } + else { + float y = (float)x; + const char *s = (char*)&y; + int i, incr = 1; + + if (Py_IS_INFINITY(y) && !Py_IS_INFINITY(x)) + goto Overflow; + + if ((float_format == ieee_little_endian_format && !le) + || (float_format == ieee_big_endian_format && le)) { + p += 3; + incr = -1; + } + + for (i = 0; i < 4; i++) { + *p = *s++; + p += incr; + } + return 0; + } Overflow: - PyErr_SetString(PyExc_OverflowError, - "float too large to pack with f format"); - return -1; + PyErr_SetString(PyExc_OverflowError, + "float too large to pack with f format"); + return -1; } int _PyFloat_Pack8(double x, unsigned char *p, int le) { - if (double_format == unknown_format) { - unsigned char sign; - int e; - double f; - unsigned int fhi, flo; - int incr = 1; - - if (le) { - p += 7; - incr = -1; - } - - if (x < 0) { - sign = 1; - x = -x; - } - else - sign = 0; - - f = frexp(x, &e); - - /* Normalize f to be in the range [1.0, 2.0) */ - if (0.5 <= f && f < 1.0) { - f *= 2.0; - e--; - } - else if (f == 0.0) - e = 0; - else { - PyErr_SetString(PyExc_SystemError, - "frexp() result out of range"); - return -1; - } - - if (e >= 1024) - goto Overflow; - else if (e < -1022) { - /* Gradual underflow */ - f = ldexp(f, 1022 + e); - e = 0; - } - else if (!(e == 0 && f == 0.0)) { - e += 1023; - f -= 1.0; /* Get rid of leading 1 */ - } - - /* fhi receives the high 28 bits; flo the low 24 bits (== 52 bits) */ - f *= 268435456.0; /* 2**28 */ - fhi = (unsigned int)f; /* Truncate */ - assert(fhi < 268435456); - - f -= (double)fhi; - f *= 16777216.0; /* 2**24 */ - flo = (unsigned int)(f + 0.5); /* Round */ - assert(flo <= 16777216); - if (flo >> 24) { - /* The carry propagated out of a string of 24 1 bits. */ - flo = 0; - ++fhi; - if (fhi >> 28) { - /* And it also progagated out of the next 28 bits. */ - fhi = 0; - ++e; - if (e >= 2047) - goto Overflow; - } - } - - /* First byte */ - *p = (sign << 7) | (e >> 4); - p += incr; - - /* Second byte */ - *p = (unsigned char) (((e & 0xF) << 4) | (fhi >> 24)); - p += incr; - - /* Third byte */ - *p = (fhi >> 16) & 0xFF; - p += incr; - - /* Fourth byte */ - *p = (fhi >> 8) & 0xFF; - p += incr; - - /* Fifth byte */ - *p = fhi & 0xFF; - p += incr; - - /* Sixth byte */ - *p = (flo >> 16) & 0xFF; - p += incr; - - /* Seventh byte */ - *p = (flo >> 8) & 0xFF; - p += incr; - - /* Eighth byte */ - *p = flo & 0xFF; - p += incr; - - /* Done */ - return 0; - - Overflow: - PyErr_SetString(PyExc_OverflowError, - "float too large to pack with d format"); - return -1; - } - else { - const char *s = (char*)&x; - int i, incr = 1; - - if ((double_format == ieee_little_endian_format && !le) - || (double_format == ieee_big_endian_format && le)) { - p += 7; - incr = -1; - } - - for (i = 0; i < 8; i++) { - *p = *s++; - p += incr; - } - return 0; - } + if (double_format == unknown_format) { + unsigned char sign; + int e; + double f; + unsigned int fhi, flo; + int incr = 1; + + if (le) { + p += 7; + incr = -1; + } + + if (x < 0) { + sign = 1; + x = -x; + } + else + sign = 0; + + f = frexp(x, &e); + + /* Normalize f to be in the range [1.0, 2.0) */ + if (0.5 <= f && f < 1.0) { + f *= 2.0; + e--; + } + else if (f == 0.0) + e = 0; + else { + PyErr_SetString(PyExc_SystemError, + "frexp() result out of range"); + return -1; + } + + if (e >= 1024) + goto Overflow; + else if (e < -1022) { + /* Gradual underflow */ + f = ldexp(f, 1022 + e); + e = 0; + } + else if (!(e == 0 && f == 0.0)) { + e += 1023; + f -= 1.0; /* Get rid of leading 1 */ + } + + /* fhi receives the high 28 bits; flo the low 24 bits (== 52 bits) */ + f *= 268435456.0; /* 2**28 */ + fhi = (unsigned int)f; /* Truncate */ + assert(fhi < 268435456); + + f -= (double)fhi; + f *= 16777216.0; /* 2**24 */ + flo = (unsigned int)(f + 0.5); /* Round */ + assert(flo <= 16777216); + if (flo >> 24) { + /* The carry propagated out of a string of 24 1 bits. */ + flo = 0; + ++fhi; + if (fhi >> 28) { + /* And it also progagated out of the next 28 bits. */ + fhi = 0; + ++e; + if (e >= 2047) + goto Overflow; + } + } + + /* First byte */ + *p = (sign << 7) | (e >> 4); + p += incr; + + /* Second byte */ + *p = (unsigned char) (((e & 0xF) << 4) | (fhi >> 24)); + p += incr; + + /* Third byte */ + *p = (fhi >> 16) & 0xFF; + p += incr; + + /* Fourth byte */ + *p = (fhi >> 8) & 0xFF; + p += incr; + + /* Fifth byte */ + *p = fhi & 0xFF; + p += incr; + + /* Sixth byte */ + *p = (flo >> 16) & 0xFF; + p += incr; + + /* Seventh byte */ + *p = (flo >> 8) & 0xFF; + p += incr; + + /* Eighth byte */ + *p = flo & 0xFF; + p += incr; + + /* Done */ + return 0; + + Overflow: + PyErr_SetString(PyExc_OverflowError, + "float too large to pack with d format"); + return -1; + } + else { + const char *s = (char*)&x; + int i, incr = 1; + + if ((double_format == ieee_little_endian_format && !le) + || (double_format == ieee_big_endian_format && le)) { + p += 7; + incr = -1; + } + + for (i = 0; i < 8; i++) { + *p = *s++; + p += incr; + } + return 0; + } } double _PyFloat_Unpack4(const unsigned char *p, int le) { - if (float_format == unknown_format) { - unsigned char sign; - int e; - unsigned int f; - double x; - int incr = 1; - - if (le) { - p += 3; - incr = -1; - } - - /* First byte */ - sign = (*p >> 7) & 1; - e = (*p & 0x7F) << 1; - p += incr; - - /* Second byte */ - e |= (*p >> 7) & 1; - f = (*p & 0x7F) << 16; - p += incr; - - if (e == 255) { - PyErr_SetString( - PyExc_ValueError, - "can't unpack IEEE 754 special value " - "on non-IEEE platform"); - return -1; - } - - /* Third byte */ - f |= *p << 8; - p += incr; - - /* Fourth byte */ - f |= *p; - - x = (double)f / 8388608.0; - - /* XXX This sadly ignores Inf/NaN issues */ - if (e == 0) - e = -126; - else { - x += 1.0; - e -= 127; - } - x = ldexp(x, e); - - if (sign) - x = -x; - - return x; - } - else { - float x; - - if ((float_format == ieee_little_endian_format && !le) - || (float_format == ieee_big_endian_format && le)) { - char buf[4]; - char *d = &buf[3]; - int i; - - for (i = 0; i < 4; i++) { - *d-- = *p++; - } - memcpy(&x, buf, 4); - } - else { - memcpy(&x, p, 4); - } + if (float_format == unknown_format) { + unsigned char sign; + int e; + unsigned int f; + double x; + int incr = 1; + + if (le) { + p += 3; + incr = -1; + } + + /* First byte */ + sign = (*p >> 7) & 1; + e = (*p & 0x7F) << 1; + p += incr; + + /* Second byte */ + e |= (*p >> 7) & 1; + f = (*p & 0x7F) << 16; + p += incr; + + if (e == 255) { + PyErr_SetString( + PyExc_ValueError, + "can't unpack IEEE 754 special value " + "on non-IEEE platform"); + return -1; + } + + /* Third byte */ + f |= *p << 8; + p += incr; + + /* Fourth byte */ + f |= *p; + + x = (double)f / 8388608.0; + + /* XXX This sadly ignores Inf/NaN issues */ + if (e == 0) + e = -126; + else { + x += 1.0; + e -= 127; + } + x = ldexp(x, e); + + if (sign) + x = -x; + + return x; + } + else { + float x; + + if ((float_format == ieee_little_endian_format && !le) + || (float_format == ieee_big_endian_format && le)) { + char buf[4]; + char *d = &buf[3]; + int i; + + for (i = 0; i < 4; i++) { + *d-- = *p++; + } + memcpy(&x, buf, 4); + } + else { + memcpy(&x, p, 4); + } - return x; - } + return x; + } } double _PyFloat_Unpack8(const unsigned char *p, int le) { - if (double_format == unknown_format) { - unsigned char sign; - int e; - unsigned int fhi, flo; - double x; - int incr = 1; - - if (le) { - p += 7; - incr = -1; - } - - /* First byte */ - sign = (*p >> 7) & 1; - e = (*p & 0x7F) << 4; - - p += incr; - - /* Second byte */ - e |= (*p >> 4) & 0xF; - fhi = (*p & 0xF) << 24; - p += incr; - - if (e == 2047) { - PyErr_SetString( - PyExc_ValueError, - "can't unpack IEEE 754 special value " - "on non-IEEE platform"); - return -1.0; - } - - /* Third byte */ - fhi |= *p << 16; - p += incr; - - /* Fourth byte */ - fhi |= *p << 8; - p += incr; - - /* Fifth byte */ - fhi |= *p; - p += incr; - - /* Sixth byte */ - flo = *p << 16; - p += incr; - - /* Seventh byte */ - flo |= *p << 8; - p += incr; - - /* Eighth byte */ - flo |= *p; - - x = (double)fhi + (double)flo / 16777216.0; /* 2**24 */ - x /= 268435456.0; /* 2**28 */ - - if (e == 0) - e = -1022; - else { - x += 1.0; - e -= 1023; - } - x = ldexp(x, e); - - if (sign) - x = -x; - - return x; - } - else { - double x; - - if ((double_format == ieee_little_endian_format && !le) - || (double_format == ieee_big_endian_format && le)) { - char buf[8]; - char *d = &buf[7]; - int i; - - for (i = 0; i < 8; i++) { - *d-- = *p++; - } - memcpy(&x, buf, 8); - } - else { - memcpy(&x, p, 8); - } + if (double_format == unknown_format) { + unsigned char sign; + int e; + unsigned int fhi, flo; + double x; + int incr = 1; + + if (le) { + p += 7; + incr = -1; + } + + /* First byte */ + sign = (*p >> 7) & 1; + e = (*p & 0x7F) << 4; + + p += incr; + + /* Second byte */ + e |= (*p >> 4) & 0xF; + fhi = (*p & 0xF) << 24; + p += incr; + + if (e == 2047) { + PyErr_SetString( + PyExc_ValueError, + "can't unpack IEEE 754 special value " + "on non-IEEE platform"); + return -1.0; + } + + /* Third byte */ + fhi |= *p << 16; + p += incr; + + /* Fourth byte */ + fhi |= *p << 8; + p += incr; + + /* Fifth byte */ + fhi |= *p; + p += incr; + + /* Sixth byte */ + flo = *p << 16; + p += incr; + + /* Seventh byte */ + flo |= *p << 8; + p += incr; + + /* Eighth byte */ + flo |= *p; + + x = (double)fhi + (double)flo / 16777216.0; /* 2**24 */ + x /= 268435456.0; /* 2**28 */ + + if (e == 0) + e = -1022; + else { + x += 1.0; + e -= 1023; + } + x = ldexp(x, e); + + if (sign) + x = -x; + + return x; + } + else { + double x; + + if ((double_format == ieee_little_endian_format && !le) + || (double_format == ieee_big_endian_format && le)) { + char buf[8]; + char *d = &buf[7]; + int i; + + for (i = 0; i < 8; i++) { + *d-- = *p++; + } + memcpy(&x, buf, 8); + } + else { + memcpy(&x, p, 8); + } - return x; - } + return x; + } } Modified: python/branches/py3k/Objects/frameobject.c ============================================================================== --- python/branches/py3k/Objects/frameobject.c (original) +++ python/branches/py3k/Objects/frameobject.c Sun May 9 17:52:27 2010 @@ -15,39 +15,39 @@ #define OFF(x) offsetof(PyFrameObject, x) static PyMemberDef frame_memberlist[] = { - {"f_back", T_OBJECT, OFF(f_back), READONLY}, - {"f_code", T_OBJECT, OFF(f_code), READONLY}, - {"f_builtins", T_OBJECT, OFF(f_builtins),READONLY}, - {"f_globals", T_OBJECT, OFF(f_globals), READONLY}, - {"f_lasti", T_INT, OFF(f_lasti), READONLY}, - {NULL} /* Sentinel */ + {"f_back", T_OBJECT, OFF(f_back), READONLY}, + {"f_code", T_OBJECT, OFF(f_code), READONLY}, + {"f_builtins", T_OBJECT, OFF(f_builtins),READONLY}, + {"f_globals", T_OBJECT, OFF(f_globals), READONLY}, + {"f_lasti", T_INT, OFF(f_lasti), READONLY}, + {NULL} /* Sentinel */ }; static PyObject * frame_getlocals(PyFrameObject *f, void *closure) { - PyFrame_FastToLocals(f); - Py_INCREF(f->f_locals); - return f->f_locals; + PyFrame_FastToLocals(f); + Py_INCREF(f->f_locals); + return f->f_locals; } int PyFrame_GetLineNumber(PyFrameObject *f) { - if (f->f_trace) - return f->f_lineno; - else - return PyCode_Addr2Line(f->f_code, f->f_lasti); + if (f->f_trace) + return f->f_lineno; + else + return PyCode_Addr2Line(f->f_code, f->f_lasti); } static PyObject * frame_getlineno(PyFrameObject *f, void *closure) { - return PyLong_FromLong(PyFrame_GetLineNumber(f)); + return PyLong_FromLong(PyFrame_GetLineNumber(f)); } /* Setter for f_lineno - you can set f_lineno from within a trace function in - * order to jump to a given line of code, subject to some restrictions. Most + * order to jump to a given line of code, subject to some restrictions. Most * lines are OK to jump to because they don't make any assumptions about the * state of the stack (obvious because you could remove the line and the code * would still work without any stack errors), but there are some constructs @@ -64,309 +64,309 @@ static int frame_setlineno(PyFrameObject *f, PyObject* p_new_lineno) { - int new_lineno = 0; /* The new value of f_lineno */ - long l_new_lineno; - int overflow; - int new_lasti = 0; /* The new value of f_lasti */ - int new_iblock = 0; /* The new value of f_iblock */ - unsigned char *code = NULL; /* The bytecode for the frame... */ - Py_ssize_t code_len = 0; /* ...and its length */ - unsigned char *lnotab = NULL; /* Iterating over co_lnotab */ - Py_ssize_t lnotab_len = 0; /* (ditto) */ - int offset = 0; /* (ditto) */ - int line = 0; /* (ditto) */ - int addr = 0; /* (ditto) */ - int min_addr = 0; /* Scanning the SETUPs and POPs */ - int max_addr = 0; /* (ditto) */ - int delta_iblock = 0; /* (ditto) */ - int min_delta_iblock = 0; /* (ditto) */ - int min_iblock = 0; /* (ditto) */ - int f_lasti_setup_addr = 0; /* Policing no-jump-into-finally */ - int new_lasti_setup_addr = 0; /* (ditto) */ - int blockstack[CO_MAXBLOCKS]; /* Walking the 'finally' blocks */ - int in_finally[CO_MAXBLOCKS]; /* (ditto) */ - int blockstack_top = 0; /* (ditto) */ - unsigned char setup_op = 0; /* (ditto) */ - - /* f_lineno must be an integer. */ - if (!PyLong_CheckExact(p_new_lineno)) { - PyErr_SetString(PyExc_ValueError, - "lineno must be an integer"); - return -1; - } - - /* You can only do this from within a trace function, not via - * _getframe or similar hackery. */ - if (!f->f_trace) - { - PyErr_Format(PyExc_ValueError, - "f_lineno can only be set by a" - " line trace function"); - return -1; - } - - /* Fail if the line comes before the start of the code block. */ - l_new_lineno = PyLong_AsLongAndOverflow(p_new_lineno, &overflow); - if (overflow + int new_lineno = 0; /* The new value of f_lineno */ + long l_new_lineno; + int overflow; + int new_lasti = 0; /* The new value of f_lasti */ + int new_iblock = 0; /* The new value of f_iblock */ + unsigned char *code = NULL; /* The bytecode for the frame... */ + Py_ssize_t code_len = 0; /* ...and its length */ + unsigned char *lnotab = NULL; /* Iterating over co_lnotab */ + Py_ssize_t lnotab_len = 0; /* (ditto) */ + int offset = 0; /* (ditto) */ + int line = 0; /* (ditto) */ + int addr = 0; /* (ditto) */ + int min_addr = 0; /* Scanning the SETUPs and POPs */ + int max_addr = 0; /* (ditto) */ + int delta_iblock = 0; /* (ditto) */ + int min_delta_iblock = 0; /* (ditto) */ + int min_iblock = 0; /* (ditto) */ + int f_lasti_setup_addr = 0; /* Policing no-jump-into-finally */ + int new_lasti_setup_addr = 0; /* (ditto) */ + int blockstack[CO_MAXBLOCKS]; /* Walking the 'finally' blocks */ + int in_finally[CO_MAXBLOCKS]; /* (ditto) */ + int blockstack_top = 0; /* (ditto) */ + unsigned char setup_op = 0; /* (ditto) */ + + /* f_lineno must be an integer. */ + if (!PyLong_CheckExact(p_new_lineno)) { + PyErr_SetString(PyExc_ValueError, + "lineno must be an integer"); + return -1; + } + + /* You can only do this from within a trace function, not via + * _getframe or similar hackery. */ + if (!f->f_trace) + { + PyErr_Format(PyExc_ValueError, + "f_lineno can only be set by a" + " line trace function"); + return -1; + } + + /* Fail if the line comes before the start of the code block. */ + l_new_lineno = PyLong_AsLongAndOverflow(p_new_lineno, &overflow); + if (overflow #if SIZEOF_LONG > SIZEOF_INT - || l_new_lineno > INT_MAX - || l_new_lineno < INT_MIN + || l_new_lineno > INT_MAX + || l_new_lineno < INT_MIN #endif - ) { - PyErr_SetString(PyExc_ValueError, - "lineno out of range"); - return -1; - } - new_lineno = (int)l_new_lineno; - - if (new_lineno < f->f_code->co_firstlineno) { - PyErr_Format(PyExc_ValueError, - "line %d comes before the current code block", - new_lineno); - return -1; - } - else if (new_lineno == f->f_code->co_firstlineno) { - new_lasti = 0; - new_lineno = f->f_code->co_firstlineno; - } - else { - /* Find the bytecode offset for the start of the given - * line, or the first code-owning line after it. */ - char *tmp; - PyBytes_AsStringAndSize(f->f_code->co_lnotab, - &tmp, &lnotab_len); - lnotab = (unsigned char *) tmp; - addr = 0; - line = f->f_code->co_firstlineno; - new_lasti = -1; - for (offset = 0; offset < lnotab_len; offset += 2) { - addr += lnotab[offset]; - line += lnotab[offset+1]; - if (line >= new_lineno) { - new_lasti = addr; - new_lineno = line; - break; - } - } - } - - /* If we didn't reach the requested line, return an error. */ - if (new_lasti == -1) { - PyErr_Format(PyExc_ValueError, - "line %d comes after the current code block", - new_lineno); - return -1; - } - - /* We're now ready to look at the bytecode. */ - PyBytes_AsStringAndSize(f->f_code->co_code, (char **)&code, &code_len); - min_addr = MIN(new_lasti, f->f_lasti); - max_addr = MAX(new_lasti, f->f_lasti); - - /* You can't jump onto a line with an 'except' statement on it - - * they expect to have an exception on the top of the stack, which - * won't be true if you jump to them. They always start with code - * that either pops the exception using POP_TOP (plain 'except:' - * lines do this) or duplicates the exception on the stack using - * DUP_TOP (if there's an exception type specified). See compile.c, - * 'com_try_except' for the full details. There aren't any other - * cases (AFAIK) where a line's code can start with DUP_TOP or - * POP_TOP, but if any ever appear, they'll be subject to the same - * restriction (but with a different error message). */ - if (code[new_lasti] == DUP_TOP || code[new_lasti] == POP_TOP) { - PyErr_SetString(PyExc_ValueError, - "can't jump to 'except' line as there's no exception"); - return -1; - } - - /* You can't jump into or out of a 'finally' block because the 'try' - * block leaves something on the stack for the END_FINALLY to clean - * up. So we walk the bytecode, maintaining a simulated blockstack. - * When we reach the old or new address and it's in a 'finally' block - * we note the address of the corresponding SETUP_FINALLY. The jump - * is only legal if neither address is in a 'finally' block or - * they're both in the same one. 'blockstack' is a stack of the - * bytecode addresses of the SETUP_X opcodes, and 'in_finally' tracks - * whether we're in a 'finally' block at each blockstack level. */ - f_lasti_setup_addr = -1; - new_lasti_setup_addr = -1; - memset(blockstack, '\0', sizeof(blockstack)); - memset(in_finally, '\0', sizeof(in_finally)); - blockstack_top = 0; - for (addr = 0; addr < code_len; addr++) { - unsigned char op = code[addr]; - switch (op) { - case SETUP_LOOP: - case SETUP_EXCEPT: - case SETUP_FINALLY: - blockstack[blockstack_top++] = addr; - in_finally[blockstack_top-1] = 0; - break; - - case POP_BLOCK: - assert(blockstack_top > 0); - setup_op = code[blockstack[blockstack_top-1]]; - if (setup_op == SETUP_FINALLY) { - in_finally[blockstack_top-1] = 1; - } - else { - blockstack_top--; - } - break; - - case END_FINALLY: - /* Ignore END_FINALLYs for SETUP_EXCEPTs - they exist - * in the bytecode but don't correspond to an actual - * 'finally' block. (If blockstack_top is 0, we must - * be seeing such an END_FINALLY.) */ - if (blockstack_top > 0) { - setup_op = code[blockstack[blockstack_top-1]]; - if (setup_op == SETUP_FINALLY) { - blockstack_top--; - } - } - break; - } - - /* For the addresses we're interested in, see whether they're - * within a 'finally' block and if so, remember the address - * of the SETUP_FINALLY. */ - if (addr == new_lasti || addr == f->f_lasti) { - int i = 0; - int setup_addr = -1; - for (i = blockstack_top-1; i >= 0; i--) { - if (in_finally[i]) { - setup_addr = blockstack[i]; - break; - } - } - - if (setup_addr != -1) { - if (addr == new_lasti) { - new_lasti_setup_addr = setup_addr; - } - - if (addr == f->f_lasti) { - f_lasti_setup_addr = setup_addr; - } - } - } - - if (op >= HAVE_ARGUMENT) { - addr += 2; - } - } - - /* Verify that the blockstack tracking code didn't get lost. */ - assert(blockstack_top == 0); - - /* After all that, are we jumping into / out of a 'finally' block? */ - if (new_lasti_setup_addr != f_lasti_setup_addr) { - PyErr_SetString(PyExc_ValueError, - "can't jump into or out of a 'finally' block"); - return -1; - } - - - /* Police block-jumping (you can't jump into the middle of a block) - * and ensure that the blockstack finishes up in a sensible state (by - * popping any blocks we're jumping out of). We look at all the - * blockstack operations between the current position and the new - * one, and keep track of how many blocks we drop out of on the way. - * By also keeping track of the lowest blockstack position we see, we - * can tell whether the jump goes into any blocks without coming out - * again - in that case we raise an exception below. */ - delta_iblock = 0; - for (addr = min_addr; addr < max_addr; addr++) { - unsigned char op = code[addr]; - switch (op) { - case SETUP_LOOP: - case SETUP_EXCEPT: - case SETUP_FINALLY: - delta_iblock++; - break; - - case POP_BLOCK: - delta_iblock--; - break; - } - - min_delta_iblock = MIN(min_delta_iblock, delta_iblock); - - if (op >= HAVE_ARGUMENT) { - addr += 2; - } - } - - /* Derive the absolute iblock values from the deltas. */ - min_iblock = f->f_iblock + min_delta_iblock; - if (new_lasti > f->f_lasti) { - /* Forwards jump. */ - new_iblock = f->f_iblock + delta_iblock; - } - else { - /* Backwards jump. */ - new_iblock = f->f_iblock - delta_iblock; - } - - /* Are we jumping into a block? */ - if (new_iblock > min_iblock) { - PyErr_SetString(PyExc_ValueError, - "can't jump into the middle of a block"); - return -1; - } - - /* Pop any blocks that we're jumping out of. */ - while (f->f_iblock > new_iblock) { - PyTryBlock *b = &f->f_blockstack[--f->f_iblock]; - while ((f->f_stacktop - f->f_valuestack) > b->b_level) { - PyObject *v = (*--f->f_stacktop); - Py_DECREF(v); - } - } - - /* Finally set the new f_lineno and f_lasti and return OK. */ - f->f_lineno = new_lineno; - f->f_lasti = new_lasti; - return 0; + ) { + PyErr_SetString(PyExc_ValueError, + "lineno out of range"); + return -1; + } + new_lineno = (int)l_new_lineno; + + if (new_lineno < f->f_code->co_firstlineno) { + PyErr_Format(PyExc_ValueError, + "line %d comes before the current code block", + new_lineno); + return -1; + } + else if (new_lineno == f->f_code->co_firstlineno) { + new_lasti = 0; + new_lineno = f->f_code->co_firstlineno; + } + else { + /* Find the bytecode offset for the start of the given + * line, or the first code-owning line after it. */ + char *tmp; + PyBytes_AsStringAndSize(f->f_code->co_lnotab, + &tmp, &lnotab_len); + lnotab = (unsigned char *) tmp; + addr = 0; + line = f->f_code->co_firstlineno; + new_lasti = -1; + for (offset = 0; offset < lnotab_len; offset += 2) { + addr += lnotab[offset]; + line += lnotab[offset+1]; + if (line >= new_lineno) { + new_lasti = addr; + new_lineno = line; + break; + } + } + } + + /* If we didn't reach the requested line, return an error. */ + if (new_lasti == -1) { + PyErr_Format(PyExc_ValueError, + "line %d comes after the current code block", + new_lineno); + return -1; + } + + /* We're now ready to look at the bytecode. */ + PyBytes_AsStringAndSize(f->f_code->co_code, (char **)&code, &code_len); + min_addr = MIN(new_lasti, f->f_lasti); + max_addr = MAX(new_lasti, f->f_lasti); + + /* You can't jump onto a line with an 'except' statement on it - + * they expect to have an exception on the top of the stack, which + * won't be true if you jump to them. They always start with code + * that either pops the exception using POP_TOP (plain 'except:' + * lines do this) or duplicates the exception on the stack using + * DUP_TOP (if there's an exception type specified). See compile.c, + * 'com_try_except' for the full details. There aren't any other + * cases (AFAIK) where a line's code can start with DUP_TOP or + * POP_TOP, but if any ever appear, they'll be subject to the same + * restriction (but with a different error message). */ + if (code[new_lasti] == DUP_TOP || code[new_lasti] == POP_TOP) { + PyErr_SetString(PyExc_ValueError, + "can't jump to 'except' line as there's no exception"); + return -1; + } + + /* You can't jump into or out of a 'finally' block because the 'try' + * block leaves something on the stack for the END_FINALLY to clean + * up. So we walk the bytecode, maintaining a simulated blockstack. + * When we reach the old or new address and it's in a 'finally' block + * we note the address of the corresponding SETUP_FINALLY. The jump + * is only legal if neither address is in a 'finally' block or + * they're both in the same one. 'blockstack' is a stack of the + * bytecode addresses of the SETUP_X opcodes, and 'in_finally' tracks + * whether we're in a 'finally' block at each blockstack level. */ + f_lasti_setup_addr = -1; + new_lasti_setup_addr = -1; + memset(blockstack, '\0', sizeof(blockstack)); + memset(in_finally, '\0', sizeof(in_finally)); + blockstack_top = 0; + for (addr = 0; addr < code_len; addr++) { + unsigned char op = code[addr]; + switch (op) { + case SETUP_LOOP: + case SETUP_EXCEPT: + case SETUP_FINALLY: + blockstack[blockstack_top++] = addr; + in_finally[blockstack_top-1] = 0; + break; + + case POP_BLOCK: + assert(blockstack_top > 0); + setup_op = code[blockstack[blockstack_top-1]]; + if (setup_op == SETUP_FINALLY) { + in_finally[blockstack_top-1] = 1; + } + else { + blockstack_top--; + } + break; + + case END_FINALLY: + /* Ignore END_FINALLYs for SETUP_EXCEPTs - they exist + * in the bytecode but don't correspond to an actual + * 'finally' block. (If blockstack_top is 0, we must + * be seeing such an END_FINALLY.) */ + if (blockstack_top > 0) { + setup_op = code[blockstack[blockstack_top-1]]; + if (setup_op == SETUP_FINALLY) { + blockstack_top--; + } + } + break; + } + + /* For the addresses we're interested in, see whether they're + * within a 'finally' block and if so, remember the address + * of the SETUP_FINALLY. */ + if (addr == new_lasti || addr == f->f_lasti) { + int i = 0; + int setup_addr = -1; + for (i = blockstack_top-1; i >= 0; i--) { + if (in_finally[i]) { + setup_addr = blockstack[i]; + break; + } + } + + if (setup_addr != -1) { + if (addr == new_lasti) { + new_lasti_setup_addr = setup_addr; + } + + if (addr == f->f_lasti) { + f_lasti_setup_addr = setup_addr; + } + } + } + + if (op >= HAVE_ARGUMENT) { + addr += 2; + } + } + + /* Verify that the blockstack tracking code didn't get lost. */ + assert(blockstack_top == 0); + + /* After all that, are we jumping into / out of a 'finally' block? */ + if (new_lasti_setup_addr != f_lasti_setup_addr) { + PyErr_SetString(PyExc_ValueError, + "can't jump into or out of a 'finally' block"); + return -1; + } + + + /* Police block-jumping (you can't jump into the middle of a block) + * and ensure that the blockstack finishes up in a sensible state (by + * popping any blocks we're jumping out of). We look at all the + * blockstack operations between the current position and the new + * one, and keep track of how many blocks we drop out of on the way. + * By also keeping track of the lowest blockstack position we see, we + * can tell whether the jump goes into any blocks without coming out + * again - in that case we raise an exception below. */ + delta_iblock = 0; + for (addr = min_addr; addr < max_addr; addr++) { + unsigned char op = code[addr]; + switch (op) { + case SETUP_LOOP: + case SETUP_EXCEPT: + case SETUP_FINALLY: + delta_iblock++; + break; + + case POP_BLOCK: + delta_iblock--; + break; + } + + min_delta_iblock = MIN(min_delta_iblock, delta_iblock); + + if (op >= HAVE_ARGUMENT) { + addr += 2; + } + } + + /* Derive the absolute iblock values from the deltas. */ + min_iblock = f->f_iblock + min_delta_iblock; + if (new_lasti > f->f_lasti) { + /* Forwards jump. */ + new_iblock = f->f_iblock + delta_iblock; + } + else { + /* Backwards jump. */ + new_iblock = f->f_iblock - delta_iblock; + } + + /* Are we jumping into a block? */ + if (new_iblock > min_iblock) { + PyErr_SetString(PyExc_ValueError, + "can't jump into the middle of a block"); + return -1; + } + + /* Pop any blocks that we're jumping out of. */ + while (f->f_iblock > new_iblock) { + PyTryBlock *b = &f->f_blockstack[--f->f_iblock]; + while ((f->f_stacktop - f->f_valuestack) > b->b_level) { + PyObject *v = (*--f->f_stacktop); + Py_DECREF(v); + } + } + + /* Finally set the new f_lineno and f_lasti and return OK. */ + f->f_lineno = new_lineno; + f->f_lasti = new_lasti; + return 0; } static PyObject * frame_gettrace(PyFrameObject *f, void *closure) { - PyObject* trace = f->f_trace; + PyObject* trace = f->f_trace; - if (trace == NULL) - trace = Py_None; + if (trace == NULL) + trace = Py_None; - Py_INCREF(trace); + Py_INCREF(trace); - return trace; + return trace; } static int frame_settrace(PyFrameObject *f, PyObject* v, void *closure) { - PyObject* old_value; + PyObject* old_value; - /* We rely on f_lineno being accurate when f_trace is set. */ - f->f_lineno = PyFrame_GetLineNumber(f); + /* We rely on f_lineno being accurate when f_trace is set. */ + f->f_lineno = PyFrame_GetLineNumber(f); - old_value = f->f_trace; - Py_XINCREF(v); - f->f_trace = v; - Py_XDECREF(old_value); + old_value = f->f_trace; + Py_XINCREF(v); + f->f_trace = v; + Py_XDECREF(old_value); - return 0; + return 0; } static PyGetSetDef frame_getsetlist[] = { - {"f_locals", (getter)frame_getlocals, NULL, NULL}, - {"f_lineno", (getter)frame_getlineno, - (setter)frame_setlineno, NULL}, - {"f_trace", (getter)frame_gettrace, (setter)frame_settrace, NULL}, - {0} + {"f_locals", (getter)frame_getlocals, NULL, NULL}, + {"f_lineno", (getter)frame_getlineno, + (setter)frame_setlineno, NULL}, + {"f_trace", (getter)frame_gettrace, (setter)frame_settrace, NULL}, + {0} }; /* Stack frames are allocated and deallocated at a considerable rate. @@ -383,7 +383,7 @@ the following fields are still valid: * ob_type, ob_size, f_code, f_valuestack; - + * f_locals, f_trace, f_exc_type, f_exc_value, f_exc_traceback are NULL; @@ -394,10 +394,10 @@ integers are allocated in a special way -- see intobject.c). When a stack frame is on the free list, only the following members have a meaning: - ob_type == &Frametype - f_back next item on free list, or NULL - f_stacksize size of value stack - ob_size size of localsplus + ob_type == &Frametype + f_back next item on free list, or NULL + f_stacksize size of value stack + ob_size size of localsplus Note that the value and block stacks are preserved -- this can save another malloc() call or two (and two free() calls as well!). Also note that, unlike for integers, each frame object is a @@ -413,307 +413,307 @@ */ static PyFrameObject *free_list = NULL; -static int numfree = 0; /* number of frames currently in free_list */ +static int numfree = 0; /* number of frames currently in free_list */ /* max value for numfree */ -#define PyFrame_MAXFREELIST 200 +#define PyFrame_MAXFREELIST 200 static void frame_dealloc(PyFrameObject *f) { - PyObject **p, **valuestack; - PyCodeObject *co; + PyObject **p, **valuestack; + PyCodeObject *co; - PyObject_GC_UnTrack(f); - Py_TRASHCAN_SAFE_BEGIN(f) - /* Kill all local variables */ - valuestack = f->f_valuestack; - for (p = f->f_localsplus; p < valuestack; p++) - Py_CLEAR(*p); - - /* Free stack */ - if (f->f_stacktop != NULL) { - for (p = valuestack; p < f->f_stacktop; p++) - Py_XDECREF(*p); - } - - Py_XDECREF(f->f_back); - Py_DECREF(f->f_builtins); - Py_DECREF(f->f_globals); - Py_CLEAR(f->f_locals); - Py_CLEAR(f->f_trace); - Py_CLEAR(f->f_exc_type); - Py_CLEAR(f->f_exc_value); - Py_CLEAR(f->f_exc_traceback); - - co = f->f_code; - if (co->co_zombieframe == NULL) - co->co_zombieframe = f; - else if (numfree < PyFrame_MAXFREELIST) { - ++numfree; - f->f_back = free_list; - free_list = f; - } - else - PyObject_GC_Del(f); + PyObject_GC_UnTrack(f); + Py_TRASHCAN_SAFE_BEGIN(f) + /* Kill all local variables */ + valuestack = f->f_valuestack; + for (p = f->f_localsplus; p < valuestack; p++) + Py_CLEAR(*p); + + /* Free stack */ + if (f->f_stacktop != NULL) { + for (p = valuestack; p < f->f_stacktop; p++) + Py_XDECREF(*p); + } + + Py_XDECREF(f->f_back); + Py_DECREF(f->f_builtins); + Py_DECREF(f->f_globals); + Py_CLEAR(f->f_locals); + Py_CLEAR(f->f_trace); + Py_CLEAR(f->f_exc_type); + Py_CLEAR(f->f_exc_value); + Py_CLEAR(f->f_exc_traceback); + + co = f->f_code; + if (co->co_zombieframe == NULL) + co->co_zombieframe = f; + else if (numfree < PyFrame_MAXFREELIST) { + ++numfree; + f->f_back = free_list; + free_list = f; + } + else + PyObject_GC_Del(f); - Py_DECREF(co); - Py_TRASHCAN_SAFE_END(f) + Py_DECREF(co); + Py_TRASHCAN_SAFE_END(f) } static int frame_traverse(PyFrameObject *f, visitproc visit, void *arg) { - PyObject **fastlocals, **p; - int i, slots; + PyObject **fastlocals, **p; + int i, slots; - Py_VISIT(f->f_back); - Py_VISIT(f->f_code); - Py_VISIT(f->f_builtins); - Py_VISIT(f->f_globals); - Py_VISIT(f->f_locals); - Py_VISIT(f->f_trace); - Py_VISIT(f->f_exc_type); - Py_VISIT(f->f_exc_value); - Py_VISIT(f->f_exc_traceback); - - /* locals */ - slots = f->f_code->co_nlocals + PyTuple_GET_SIZE(f->f_code->co_cellvars) + PyTuple_GET_SIZE(f->f_code->co_freevars); - fastlocals = f->f_localsplus; - for (i = slots; --i >= 0; ++fastlocals) - Py_VISIT(*fastlocals); - - /* stack */ - if (f->f_stacktop != NULL) { - for (p = f->f_valuestack; p < f->f_stacktop; p++) - Py_VISIT(*p); - } - return 0; + Py_VISIT(f->f_back); + Py_VISIT(f->f_code); + Py_VISIT(f->f_builtins); + Py_VISIT(f->f_globals); + Py_VISIT(f->f_locals); + Py_VISIT(f->f_trace); + Py_VISIT(f->f_exc_type); + Py_VISIT(f->f_exc_value); + Py_VISIT(f->f_exc_traceback); + + /* locals */ + slots = f->f_code->co_nlocals + PyTuple_GET_SIZE(f->f_code->co_cellvars) + PyTuple_GET_SIZE(f->f_code->co_freevars); + fastlocals = f->f_localsplus; + for (i = slots; --i >= 0; ++fastlocals) + Py_VISIT(*fastlocals); + + /* stack */ + if (f->f_stacktop != NULL) { + for (p = f->f_valuestack; p < f->f_stacktop; p++) + Py_VISIT(*p); + } + return 0; } static void frame_clear(PyFrameObject *f) { - PyObject **fastlocals, **p, **oldtop; - int i, slots; + PyObject **fastlocals, **p, **oldtop; + int i, slots; - /* Before anything else, make sure that this frame is clearly marked - * as being defunct! Else, e.g., a generator reachable from this - * frame may also point to this frame, believe itself to still be - * active, and try cleaning up this frame again. - */ - oldtop = f->f_stacktop; - f->f_stacktop = NULL; - - Py_CLEAR(f->f_exc_type); - Py_CLEAR(f->f_exc_value); - Py_CLEAR(f->f_exc_traceback); - Py_CLEAR(f->f_trace); - - /* locals */ - slots = f->f_code->co_nlocals + PyTuple_GET_SIZE(f->f_code->co_cellvars) + PyTuple_GET_SIZE(f->f_code->co_freevars); - fastlocals = f->f_localsplus; - for (i = slots; --i >= 0; ++fastlocals) - Py_CLEAR(*fastlocals); - - /* stack */ - if (oldtop != NULL) { - for (p = f->f_valuestack; p < oldtop; p++) - Py_CLEAR(*p); - } + /* Before anything else, make sure that this frame is clearly marked + * as being defunct! Else, e.g., a generator reachable from this + * frame may also point to this frame, believe itself to still be + * active, and try cleaning up this frame again. + */ + oldtop = f->f_stacktop; + f->f_stacktop = NULL; + + Py_CLEAR(f->f_exc_type); + Py_CLEAR(f->f_exc_value); + Py_CLEAR(f->f_exc_traceback); + Py_CLEAR(f->f_trace); + + /* locals */ + slots = f->f_code->co_nlocals + PyTuple_GET_SIZE(f->f_code->co_cellvars) + PyTuple_GET_SIZE(f->f_code->co_freevars); + fastlocals = f->f_localsplus; + for (i = slots; --i >= 0; ++fastlocals) + Py_CLEAR(*fastlocals); + + /* stack */ + if (oldtop != NULL) { + for (p = f->f_valuestack; p < oldtop; p++) + Py_CLEAR(*p); + } } static PyObject * frame_sizeof(PyFrameObject *f) { - Py_ssize_t res, extras, ncells, nfrees; + Py_ssize_t res, extras, ncells, nfrees; - ncells = PyTuple_GET_SIZE(f->f_code->co_cellvars); - nfrees = PyTuple_GET_SIZE(f->f_code->co_freevars); - extras = f->f_code->co_stacksize + f->f_code->co_nlocals + - ncells + nfrees; - /* subtract one as it is already included in PyFrameObject */ - res = sizeof(PyFrameObject) + (extras-1) * sizeof(PyObject *); + ncells = PyTuple_GET_SIZE(f->f_code->co_cellvars); + nfrees = PyTuple_GET_SIZE(f->f_code->co_freevars); + extras = f->f_code->co_stacksize + f->f_code->co_nlocals + + ncells + nfrees; + /* subtract one as it is already included in PyFrameObject */ + res = sizeof(PyFrameObject) + (extras-1) * sizeof(PyObject *); - return PyLong_FromSsize_t(res); + return PyLong_FromSsize_t(res); } PyDoc_STRVAR(sizeof__doc__, "F.__sizeof__() -> size of F in memory, in bytes"); static PyMethodDef frame_methods[] = { - {"__sizeof__", (PyCFunction)frame_sizeof, METH_NOARGS, - sizeof__doc__}, - {NULL, NULL} /* sentinel */ + {"__sizeof__", (PyCFunction)frame_sizeof, METH_NOARGS, + sizeof__doc__}, + {NULL, NULL} /* sentinel */ }; PyTypeObject PyFrame_Type = { - PyVarObject_HEAD_INIT(&PyType_Type, 0) - "frame", - sizeof(PyFrameObject), - sizeof(PyObject *), - (destructor)frame_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 */ - PyObject_GenericSetAttr, /* tp_setattro */ - 0, /* tp_as_buffer */ - Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */ - 0, /* tp_doc */ - (traverseproc)frame_traverse, /* tp_traverse */ - (inquiry)frame_clear, /* tp_clear */ - 0, /* tp_richcompare */ - 0, /* tp_weaklistoffset */ - 0, /* tp_iter */ - 0, /* tp_iternext */ - frame_methods, /* tp_methods */ - frame_memberlist, /* tp_members */ - frame_getsetlist, /* tp_getset */ - 0, /* tp_base */ - 0, /* tp_dict */ + PyVarObject_HEAD_INIT(&PyType_Type, 0) + "frame", + sizeof(PyFrameObject), + sizeof(PyObject *), + (destructor)frame_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 */ + PyObject_GenericSetAttr, /* tp_setattro */ + 0, /* tp_as_buffer */ + Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */ + 0, /* tp_doc */ + (traverseproc)frame_traverse, /* tp_traverse */ + (inquiry)frame_clear, /* tp_clear */ + 0, /* tp_richcompare */ + 0, /* tp_weaklistoffset */ + 0, /* tp_iter */ + 0, /* tp_iternext */ + frame_methods, /* tp_methods */ + frame_memberlist, /* tp_members */ + frame_getsetlist, /* tp_getset */ + 0, /* tp_base */ + 0, /* tp_dict */ }; static PyObject *builtin_object; int _PyFrame_Init() { - builtin_object = PyUnicode_InternFromString("__builtins__"); - if (builtin_object == NULL) - return 0; - return 1; + builtin_object = PyUnicode_InternFromString("__builtins__"); + if (builtin_object == NULL) + return 0; + return 1; } PyFrameObject * PyFrame_New(PyThreadState *tstate, PyCodeObject *code, PyObject *globals, - PyObject *locals) + PyObject *locals) { - PyFrameObject *back = tstate->frame; - PyFrameObject *f; - PyObject *builtins; - Py_ssize_t i; + PyFrameObject *back = tstate->frame; + PyFrameObject *f; + PyObject *builtins; + Py_ssize_t i; #ifdef Py_DEBUG - if (code == NULL || globals == NULL || !PyDict_Check(globals) || - (locals != NULL && !PyMapping_Check(locals))) { - PyErr_BadInternalCall(); - return NULL; - } + if (code == NULL || globals == NULL || !PyDict_Check(globals) || + (locals != NULL && !PyMapping_Check(locals))) { + PyErr_BadInternalCall(); + return NULL; + } #endif - if (back == NULL || back->f_globals != globals) { - builtins = PyDict_GetItem(globals, builtin_object); - if (builtins) { - if (PyModule_Check(builtins)) { - builtins = PyModule_GetDict(builtins); - assert(!builtins || PyDict_Check(builtins)); - } - else if (!PyDict_Check(builtins)) - builtins = NULL; - } - if (builtins == NULL) { - /* No builtins! Make up a minimal one - Give them 'None', at least. */ - builtins = PyDict_New(); - if (builtins == NULL || - PyDict_SetItemString( - builtins, "None", Py_None) < 0) - return NULL; - } - else - Py_INCREF(builtins); - - } - else { - /* If we share the globals, we share the builtins. - Save a lookup and a call. */ - builtins = back->f_builtins; - assert(builtins != NULL && PyDict_Check(builtins)); - Py_INCREF(builtins); - } - if (code->co_zombieframe != NULL) { - f = code->co_zombieframe; - code->co_zombieframe = NULL; - _Py_NewReference((PyObject *)f); - assert(f->f_code == code); - } - else { - Py_ssize_t extras, ncells, nfrees; - ncells = PyTuple_GET_SIZE(code->co_cellvars); - nfrees = PyTuple_GET_SIZE(code->co_freevars); - extras = code->co_stacksize + code->co_nlocals + ncells + - nfrees; - if (free_list == NULL) { - f = PyObject_GC_NewVar(PyFrameObject, &PyFrame_Type, - extras); - if (f == NULL) { - Py_DECREF(builtins); - return NULL; - } - } - else { - assert(numfree > 0); - --numfree; - f = free_list; - free_list = free_list->f_back; - if (Py_SIZE(f) < extras) { - f = PyObject_GC_Resize(PyFrameObject, f, extras); - if (f == NULL) { - Py_DECREF(builtins); - return NULL; - } - } - _Py_NewReference((PyObject *)f); - } - - f->f_code = code; - extras = code->co_nlocals + ncells + nfrees; - f->f_valuestack = f->f_localsplus + extras; - for (i=0; if_localsplus[i] = NULL; - f->f_locals = NULL; - f->f_trace = NULL; - f->f_exc_type = f->f_exc_value = f->f_exc_traceback = NULL; - } - f->f_stacktop = f->f_valuestack; - f->f_builtins = builtins; - Py_XINCREF(back); - f->f_back = back; - Py_INCREF(code); - Py_INCREF(globals); - f->f_globals = globals; - /* Most functions have CO_NEWLOCALS and CO_OPTIMIZED set. */ - if ((code->co_flags & (CO_NEWLOCALS | CO_OPTIMIZED)) == - (CO_NEWLOCALS | CO_OPTIMIZED)) - ; /* f_locals = NULL; will be set by PyFrame_FastToLocals() */ - else if (code->co_flags & CO_NEWLOCALS) { - locals = PyDict_New(); - if (locals == NULL) { - Py_DECREF(f); - return NULL; - } - f->f_locals = locals; - } - else { - if (locals == NULL) - locals = globals; - Py_INCREF(locals); - f->f_locals = locals; - } - f->f_tstate = tstate; - - f->f_lasti = -1; - f->f_lineno = code->co_firstlineno; - f->f_iblock = 0; + if (back == NULL || back->f_globals != globals) { + builtins = PyDict_GetItem(globals, builtin_object); + if (builtins) { + if (PyModule_Check(builtins)) { + builtins = PyModule_GetDict(builtins); + assert(!builtins || PyDict_Check(builtins)); + } + else if (!PyDict_Check(builtins)) + builtins = NULL; + } + if (builtins == NULL) { + /* No builtins! Make up a minimal one + Give them 'None', at least. */ + builtins = PyDict_New(); + if (builtins == NULL || + PyDict_SetItemString( + builtins, "None", Py_None) < 0) + return NULL; + } + else + Py_INCREF(builtins); + + } + else { + /* If we share the globals, we share the builtins. + Save a lookup and a call. */ + builtins = back->f_builtins; + assert(builtins != NULL && PyDict_Check(builtins)); + Py_INCREF(builtins); + } + if (code->co_zombieframe != NULL) { + f = code->co_zombieframe; + code->co_zombieframe = NULL; + _Py_NewReference((PyObject *)f); + assert(f->f_code == code); + } + else { + Py_ssize_t extras, ncells, nfrees; + ncells = PyTuple_GET_SIZE(code->co_cellvars); + nfrees = PyTuple_GET_SIZE(code->co_freevars); + extras = code->co_stacksize + code->co_nlocals + ncells + + nfrees; + if (free_list == NULL) { + f = PyObject_GC_NewVar(PyFrameObject, &PyFrame_Type, + extras); + if (f == NULL) { + Py_DECREF(builtins); + return NULL; + } + } + else { + assert(numfree > 0); + --numfree; + f = free_list; + free_list = free_list->f_back; + if (Py_SIZE(f) < extras) { + f = PyObject_GC_Resize(PyFrameObject, f, extras); + if (f == NULL) { + Py_DECREF(builtins); + return NULL; + } + } + _Py_NewReference((PyObject *)f); + } + + f->f_code = code; + extras = code->co_nlocals + ncells + nfrees; + f->f_valuestack = f->f_localsplus + extras; + for (i=0; if_localsplus[i] = NULL; + f->f_locals = NULL; + f->f_trace = NULL; + f->f_exc_type = f->f_exc_value = f->f_exc_traceback = NULL; + } + f->f_stacktop = f->f_valuestack; + f->f_builtins = builtins; + Py_XINCREF(back); + f->f_back = back; + Py_INCREF(code); + Py_INCREF(globals); + f->f_globals = globals; + /* Most functions have CO_NEWLOCALS and CO_OPTIMIZED set. */ + if ((code->co_flags & (CO_NEWLOCALS | CO_OPTIMIZED)) == + (CO_NEWLOCALS | CO_OPTIMIZED)) + ; /* f_locals = NULL; will be set by PyFrame_FastToLocals() */ + else if (code->co_flags & CO_NEWLOCALS) { + locals = PyDict_New(); + if (locals == NULL) { + Py_DECREF(f); + return NULL; + } + f->f_locals = locals; + } + else { + if (locals == NULL) + locals = globals; + Py_INCREF(locals); + f->f_locals = locals; + } + f->f_tstate = tstate; + + f->f_lasti = -1; + f->f_lineno = code->co_firstlineno; + f->f_iblock = 0; - _PyObject_GC_TRACK(f); - return f; + _PyObject_GC_TRACK(f); + return f; } /* Block management */ @@ -721,28 +721,28 @@ void PyFrame_BlockSetup(PyFrameObject *f, int type, int handler, int level) { - PyTryBlock *b; - if (f->f_iblock >= CO_MAXBLOCKS) - Py_FatalError("XXX block stack overflow"); - b = &f->f_blockstack[f->f_iblock++]; - b->b_type = type; - b->b_level = level; - b->b_handler = handler; + PyTryBlock *b; + if (f->f_iblock >= CO_MAXBLOCKS) + Py_FatalError("XXX block stack overflow"); + b = &f->f_blockstack[f->f_iblock++]; + b->b_type = type; + b->b_level = level; + b->b_handler = handler; } PyTryBlock * PyFrame_BlockPop(PyFrameObject *f) { - PyTryBlock *b; - if (f->f_iblock <= 0) - Py_FatalError("XXX block stack underflow"); - b = &f->f_blockstack[--f->f_iblock]; - return b; + PyTryBlock *b; + if (f->f_iblock <= 0) + Py_FatalError("XXX block stack underflow"); + b = &f->f_blockstack[--f->f_iblock]; + return b; } /* Convert between "fast" version of locals and dictionary version. - - map and values are input arguments. map is a tuple of strings. + + map and values are input arguments. map is a tuple of strings. values is an array of PyObject*. At index i, map[i] is the name of the variable with value values[i]. The function copies the first nmap variable from map/values into dict. If values[i] is NULL, @@ -758,29 +758,29 @@ static void map_to_dict(PyObject *map, Py_ssize_t nmap, PyObject *dict, PyObject **values, - int deref) + int deref) { - Py_ssize_t j; - assert(PyTuple_Check(map)); - assert(PyDict_Check(dict)); - assert(PyTuple_Size(map) >= nmap); - for (j = nmap; --j >= 0; ) { - PyObject *key = PyTuple_GET_ITEM(map, j); - PyObject *value = values[j]; - assert(PyUnicode_Check(key)); - if (deref) { - assert(PyCell_Check(value)); - value = PyCell_GET(value); - } - if (value == NULL) { - if (PyObject_DelItem(dict, key) != 0) - PyErr_Clear(); - } - else { - if (PyObject_SetItem(dict, key, value) != 0) - PyErr_Clear(); - } - } + Py_ssize_t j; + assert(PyTuple_Check(map)); + assert(PyDict_Check(dict)); + assert(PyTuple_Size(map) >= nmap); + for (j = nmap; --j >= 0; ) { + PyObject *key = PyTuple_GET_ITEM(map, j); + PyObject *value = values[j]; + assert(PyUnicode_Check(key)); + if (deref) { + assert(PyCell_Check(value)); + value = PyCell_GET(value); + } + if (value == NULL) { + if (PyObject_DelItem(dict, key) != 0) + PyErr_Clear(); + } + else { + if (PyObject_SetItem(dict, key, value) != 0) + PyErr_Clear(); + } + } } /* Copy values from the "locals" dict into the fast locals. @@ -788,7 +788,7 @@ dict is an input argument containing string keys representing variables names and arbitrary PyObject* as values. - map and values are input arguments. map is a tuple of strings. + map and values are input arguments. map is a tuple of strings. values is an array of PyObject*. At index i, map[i] is the name of the variable with value values[i]. The function copies the first nmap variable from map/values into dict. If values[i] is NULL, @@ -806,150 +806,150 @@ static void dict_to_map(PyObject *map, Py_ssize_t nmap, PyObject *dict, PyObject **values, - int deref, int clear) + int deref, int clear) { - Py_ssize_t j; - assert(PyTuple_Check(map)); - assert(PyDict_Check(dict)); - assert(PyTuple_Size(map) >= nmap); - for (j = nmap; --j >= 0; ) { - PyObject *key = PyTuple_GET_ITEM(map, j); - PyObject *value = PyObject_GetItem(dict, key); - assert(PyUnicode_Check(key)); - /* We only care about NULLs if clear is true. */ - if (value == NULL) { - PyErr_Clear(); - if (!clear) - continue; - } - if (deref) { - assert(PyCell_Check(values[j])); - if (PyCell_GET(values[j]) != value) { - if (PyCell_Set(values[j], value) < 0) - PyErr_Clear(); - } - } else if (values[j] != value) { - Py_XINCREF(value); - Py_XDECREF(values[j]); - values[j] = value; - } - Py_XDECREF(value); - } + Py_ssize_t j; + assert(PyTuple_Check(map)); + assert(PyDict_Check(dict)); + assert(PyTuple_Size(map) >= nmap); + for (j = nmap; --j >= 0; ) { + PyObject *key = PyTuple_GET_ITEM(map, j); + PyObject *value = PyObject_GetItem(dict, key); + assert(PyUnicode_Check(key)); + /* We only care about NULLs if clear is true. */ + if (value == NULL) { + PyErr_Clear(); + if (!clear) + continue; + } + if (deref) { + assert(PyCell_Check(values[j])); + if (PyCell_GET(values[j]) != value) { + if (PyCell_Set(values[j], value) < 0) + PyErr_Clear(); + } + } else if (values[j] != value) { + Py_XINCREF(value); + Py_XDECREF(values[j]); + values[j] = value; + } + Py_XDECREF(value); + } } void PyFrame_FastToLocals(PyFrameObject *f) { - /* Merge fast locals into f->f_locals */ - PyObject *locals, *map; - PyObject **fast; - PyObject *error_type, *error_value, *error_traceback; - PyCodeObject *co; - Py_ssize_t j; - int ncells, nfreevars; - if (f == NULL) - return; - locals = f->f_locals; - if (locals == NULL) { - locals = f->f_locals = PyDict_New(); - if (locals == NULL) { - PyErr_Clear(); /* Can't report it :-( */ - return; - } - } - co = f->f_code; - map = co->co_varnames; - if (!PyTuple_Check(map)) - return; - PyErr_Fetch(&error_type, &error_value, &error_traceback); - fast = f->f_localsplus; - j = PyTuple_GET_SIZE(map); - if (j > co->co_nlocals) - j = co->co_nlocals; - if (co->co_nlocals) - map_to_dict(map, j, locals, fast, 0); - ncells = PyTuple_GET_SIZE(co->co_cellvars); - nfreevars = PyTuple_GET_SIZE(co->co_freevars); - if (ncells || nfreevars) { - map_to_dict(co->co_cellvars, ncells, - locals, fast + co->co_nlocals, 1); - /* If the namespace is unoptimized, then one of the - following cases applies: - 1. It does not contain free variables, because it - uses import * or is a top-level namespace. - 2. It is a class namespace. - We don't want to accidentally copy free variables - into the locals dict used by the class. - */ - if (co->co_flags & CO_OPTIMIZED) { - map_to_dict(co->co_freevars, nfreevars, - locals, fast + co->co_nlocals + ncells, 1); - } - } - PyErr_Restore(error_type, error_value, error_traceback); + /* Merge fast locals into f->f_locals */ + PyObject *locals, *map; + PyObject **fast; + PyObject *error_type, *error_value, *error_traceback; + PyCodeObject *co; + Py_ssize_t j; + int ncells, nfreevars; + if (f == NULL) + return; + locals = f->f_locals; + if (locals == NULL) { + locals = f->f_locals = PyDict_New(); + if (locals == NULL) { + PyErr_Clear(); /* Can't report it :-( */ + return; + } + } + co = f->f_code; + map = co->co_varnames; + if (!PyTuple_Check(map)) + return; + PyErr_Fetch(&error_type, &error_value, &error_traceback); + fast = f->f_localsplus; + j = PyTuple_GET_SIZE(map); + if (j > co->co_nlocals) + j = co->co_nlocals; + if (co->co_nlocals) + map_to_dict(map, j, locals, fast, 0); + ncells = PyTuple_GET_SIZE(co->co_cellvars); + nfreevars = PyTuple_GET_SIZE(co->co_freevars); + if (ncells || nfreevars) { + map_to_dict(co->co_cellvars, ncells, + locals, fast + co->co_nlocals, 1); + /* If the namespace is unoptimized, then one of the + following cases applies: + 1. It does not contain free variables, because it + uses import * or is a top-level namespace. + 2. It is a class namespace. + We don't want to accidentally copy free variables + into the locals dict used by the class. + */ + if (co->co_flags & CO_OPTIMIZED) { + map_to_dict(co->co_freevars, nfreevars, + locals, fast + co->co_nlocals + ncells, 1); + } + } + PyErr_Restore(error_type, error_value, error_traceback); } void PyFrame_LocalsToFast(PyFrameObject *f, int clear) { - /* Merge f->f_locals into fast locals */ - PyObject *locals, *map; - PyObject **fast; - PyObject *error_type, *error_value, *error_traceback; - PyCodeObject *co; - Py_ssize_t j; - int ncells, nfreevars; - if (f == NULL) - return; - locals = f->f_locals; - co = f->f_code; - map = co->co_varnames; - if (locals == NULL) - return; - if (!PyTuple_Check(map)) - return; - PyErr_Fetch(&error_type, &error_value, &error_traceback); - fast = f->f_localsplus; - j = PyTuple_GET_SIZE(map); - if (j > co->co_nlocals) - j = co->co_nlocals; - if (co->co_nlocals) - dict_to_map(co->co_varnames, j, locals, fast, 0, clear); - ncells = PyTuple_GET_SIZE(co->co_cellvars); - nfreevars = PyTuple_GET_SIZE(co->co_freevars); - if (ncells || nfreevars) { - dict_to_map(co->co_cellvars, ncells, - locals, fast + co->co_nlocals, 1, clear); - /* Same test as in PyFrame_FastToLocals() above. */ - if (co->co_flags & CO_OPTIMIZED) { - dict_to_map(co->co_freevars, nfreevars, - locals, fast + co->co_nlocals + ncells, 1, - clear); - } - } - PyErr_Restore(error_type, error_value, error_traceback); + /* Merge f->f_locals into fast locals */ + PyObject *locals, *map; + PyObject **fast; + PyObject *error_type, *error_value, *error_traceback; + PyCodeObject *co; + Py_ssize_t j; + int ncells, nfreevars; + if (f == NULL) + return; + locals = f->f_locals; + co = f->f_code; + map = co->co_varnames; + if (locals == NULL) + return; + if (!PyTuple_Check(map)) + return; + PyErr_Fetch(&error_type, &error_value, &error_traceback); + fast = f->f_localsplus; + j = PyTuple_GET_SIZE(map); + if (j > co->co_nlocals) + j = co->co_nlocals; + if (co->co_nlocals) + dict_to_map(co->co_varnames, j, locals, fast, 0, clear); + ncells = PyTuple_GET_SIZE(co->co_cellvars); + nfreevars = PyTuple_GET_SIZE(co->co_freevars); + if (ncells || nfreevars) { + dict_to_map(co->co_cellvars, ncells, + locals, fast + co->co_nlocals, 1, clear); + /* Same test as in PyFrame_FastToLocals() above. */ + if (co->co_flags & CO_OPTIMIZED) { + dict_to_map(co->co_freevars, nfreevars, + locals, fast + co->co_nlocals + ncells, 1, + clear); + } + } + PyErr_Restore(error_type, error_value, error_traceback); } /* Clear out the free list */ int PyFrame_ClearFreeList(void) { - int freelist_size = numfree; - - while (free_list != NULL) { - PyFrameObject *f = free_list; - free_list = free_list->f_back; - PyObject_GC_Del(f); - --numfree; - } - assert(numfree == 0); - return freelist_size; + int freelist_size = numfree; + + while (free_list != NULL) { + PyFrameObject *f = free_list; + free_list = free_list->f_back; + PyObject_GC_Del(f); + --numfree; + } + assert(numfree == 0); + return freelist_size; } void PyFrame_Fini(void) { - (void)PyFrame_ClearFreeList(); - Py_XDECREF(builtin_object); - builtin_object = NULL; + (void)PyFrame_ClearFreeList(); + Py_XDECREF(builtin_object); + builtin_object = NULL; } Modified: python/branches/py3k/Objects/funcobject.c ============================================================================== --- python/branches/py3k/Objects/funcobject.c (original) +++ python/branches/py3k/Objects/funcobject.c Sun May 9 17:52:27 2010 @@ -9,215 +9,215 @@ PyObject * PyFunction_New(PyObject *code, PyObject *globals) { - PyFunctionObject *op = PyObject_GC_New(PyFunctionObject, - &PyFunction_Type); - static PyObject *__name__ = 0; - if (op != NULL) { - PyObject *doc; - PyObject *consts; - PyObject *module; - op->func_weakreflist = NULL; - Py_INCREF(code); - op->func_code = code; - Py_INCREF(globals); - op->func_globals = globals; - op->func_name = ((PyCodeObject *)code)->co_name; - Py_INCREF(op->func_name); - op->func_defaults = NULL; /* No default arguments */ - op->func_kwdefaults = NULL; /* No keyword only defaults */ - op->func_closure = NULL; - consts = ((PyCodeObject *)code)->co_consts; - if (PyTuple_Size(consts) >= 1) { - doc = PyTuple_GetItem(consts, 0); - if (!PyUnicode_Check(doc)) - doc = Py_None; - } - else - doc = Py_None; - Py_INCREF(doc); - op->func_doc = doc; - op->func_dict = NULL; - op->func_module = NULL; - op->func_annotations = NULL; - - /* __module__: If module name is in globals, use it. - Otherwise, use None. - */ - if (!__name__) { - __name__ = PyUnicode_InternFromString("__name__"); - if (!__name__) { - Py_DECREF(op); - return NULL; - } - } - module = PyDict_GetItem(globals, __name__); - if (module) { - Py_INCREF(module); - op->func_module = module; - } - } - else - return NULL; - _PyObject_GC_TRACK(op); - return (PyObject *)op; + PyFunctionObject *op = PyObject_GC_New(PyFunctionObject, + &PyFunction_Type); + static PyObject *__name__ = 0; + if (op != NULL) { + PyObject *doc; + PyObject *consts; + PyObject *module; + op->func_weakreflist = NULL; + Py_INCREF(code); + op->func_code = code; + Py_INCREF(globals); + op->func_globals = globals; + op->func_name = ((PyCodeObject *)code)->co_name; + Py_INCREF(op->func_name); + op->func_defaults = NULL; /* No default arguments */ + op->func_kwdefaults = NULL; /* No keyword only defaults */ + op->func_closure = NULL; + consts = ((PyCodeObject *)code)->co_consts; + if (PyTuple_Size(consts) >= 1) { + doc = PyTuple_GetItem(consts, 0); + if (!PyUnicode_Check(doc)) + doc = Py_None; + } + else + doc = Py_None; + Py_INCREF(doc); + op->func_doc = doc; + op->func_dict = NULL; + op->func_module = NULL; + op->func_annotations = NULL; + + /* __module__: If module name is in globals, use it. + Otherwise, use None. + */ + if (!__name__) { + __name__ = PyUnicode_InternFromString("__name__"); + if (!__name__) { + Py_DECREF(op); + return NULL; + } + } + module = PyDict_GetItem(globals, __name__); + if (module) { + Py_INCREF(module); + op->func_module = module; + } + } + else + return NULL; + _PyObject_GC_TRACK(op); + return (PyObject *)op; } PyObject * PyFunction_GetCode(PyObject *op) { - if (!PyFunction_Check(op)) { - PyErr_BadInternalCall(); - return NULL; - } - return ((PyFunctionObject *) op) -> func_code; + if (!PyFunction_Check(op)) { + PyErr_BadInternalCall(); + return NULL; + } + return ((PyFunctionObject *) op) -> func_code; } PyObject * PyFunction_GetGlobals(PyObject *op) { - if (!PyFunction_Check(op)) { - PyErr_BadInternalCall(); - return NULL; - } - return ((PyFunctionObject *) op) -> func_globals; + if (!PyFunction_Check(op)) { + PyErr_BadInternalCall(); + return NULL; + } + return ((PyFunctionObject *) op) -> func_globals; } PyObject * PyFunction_GetModule(PyObject *op) { - if (!PyFunction_Check(op)) { - PyErr_BadInternalCall(); - return NULL; - } - return ((PyFunctionObject *) op) -> func_module; + if (!PyFunction_Check(op)) { + PyErr_BadInternalCall(); + return NULL; + } + return ((PyFunctionObject *) op) -> func_module; } PyObject * PyFunction_GetDefaults(PyObject *op) { - if (!PyFunction_Check(op)) { - PyErr_BadInternalCall(); - return NULL; - } - return ((PyFunctionObject *) op) -> func_defaults; + if (!PyFunction_Check(op)) { + PyErr_BadInternalCall(); + return NULL; + } + return ((PyFunctionObject *) op) -> func_defaults; } int PyFunction_SetDefaults(PyObject *op, PyObject *defaults) { - if (!PyFunction_Check(op)) { - PyErr_BadInternalCall(); - return -1; - } - if (defaults == Py_None) - defaults = NULL; - else if (defaults && PyTuple_Check(defaults)) { - Py_INCREF(defaults); - } - else { - PyErr_SetString(PyExc_SystemError, "non-tuple default args"); - return -1; - } - Py_XDECREF(((PyFunctionObject *) op) -> func_defaults); - ((PyFunctionObject *) op) -> func_defaults = defaults; - return 0; + if (!PyFunction_Check(op)) { + PyErr_BadInternalCall(); + return -1; + } + if (defaults == Py_None) + defaults = NULL; + else if (defaults && PyTuple_Check(defaults)) { + Py_INCREF(defaults); + } + else { + PyErr_SetString(PyExc_SystemError, "non-tuple default args"); + return -1; + } + Py_XDECREF(((PyFunctionObject *) op) -> func_defaults); + ((PyFunctionObject *) op) -> func_defaults = defaults; + return 0; } PyObject * PyFunction_GetKwDefaults(PyObject *op) { - if (!PyFunction_Check(op)) { - PyErr_BadInternalCall(); - return NULL; - } - return ((PyFunctionObject *) op) -> func_kwdefaults; + if (!PyFunction_Check(op)) { + PyErr_BadInternalCall(); + return NULL; + } + return ((PyFunctionObject *) op) -> func_kwdefaults; } int PyFunction_SetKwDefaults(PyObject *op, PyObject *defaults) { - if (!PyFunction_Check(op)) { - PyErr_BadInternalCall(); - return -1; - } - if (defaults == Py_None) - defaults = NULL; - else if (defaults && PyDict_Check(defaults)) { - Py_INCREF(defaults); - } - else { - PyErr_SetString(PyExc_SystemError, - "non-dict keyword only default args"); - return -1; - } - Py_XDECREF(((PyFunctionObject *)op) -> func_kwdefaults); - ((PyFunctionObject *) op) -> func_kwdefaults = defaults; - return 0; + if (!PyFunction_Check(op)) { + PyErr_BadInternalCall(); + return -1; + } + if (defaults == Py_None) + defaults = NULL; + else if (defaults && PyDict_Check(defaults)) { + Py_INCREF(defaults); + } + else { + PyErr_SetString(PyExc_SystemError, + "non-dict keyword only default args"); + return -1; + } + Py_XDECREF(((PyFunctionObject *)op) -> func_kwdefaults); + ((PyFunctionObject *) op) -> func_kwdefaults = defaults; + return 0; } PyObject * PyFunction_GetClosure(PyObject *op) { - if (!PyFunction_Check(op)) { - PyErr_BadInternalCall(); - return NULL; - } - return ((PyFunctionObject *) op) -> func_closure; + if (!PyFunction_Check(op)) { + PyErr_BadInternalCall(); + return NULL; + } + return ((PyFunctionObject *) op) -> func_closure; } int PyFunction_SetClosure(PyObject *op, PyObject *closure) { - if (!PyFunction_Check(op)) { - PyErr_BadInternalCall(); - return -1; - } - if (closure == Py_None) - closure = NULL; - else if (PyTuple_Check(closure)) { - Py_INCREF(closure); - } - else { - PyErr_Format(PyExc_SystemError, - "expected tuple for closure, got '%.100s'", - closure->ob_type->tp_name); - return -1; - } - Py_XDECREF(((PyFunctionObject *) op) -> func_closure); - ((PyFunctionObject *) op) -> func_closure = closure; - return 0; + if (!PyFunction_Check(op)) { + PyErr_BadInternalCall(); + return -1; + } + if (closure == Py_None) + closure = NULL; + else if (PyTuple_Check(closure)) { + Py_INCREF(closure); + } + else { + PyErr_Format(PyExc_SystemError, + "expected tuple for closure, got '%.100s'", + closure->ob_type->tp_name); + return -1; + } + Py_XDECREF(((PyFunctionObject *) op) -> func_closure); + ((PyFunctionObject *) op) -> func_closure = closure; + return 0; } PyObject * PyFunction_GetAnnotations(PyObject *op) { - if (!PyFunction_Check(op)) { - PyErr_BadInternalCall(); - return NULL; - } - return ((PyFunctionObject *) op) -> func_annotations; + if (!PyFunction_Check(op)) { + PyErr_BadInternalCall(); + return NULL; + } + return ((PyFunctionObject *) op) -> func_annotations; } int PyFunction_SetAnnotations(PyObject *op, PyObject *annotations) { - if (!PyFunction_Check(op)) { - PyErr_BadInternalCall(); - return -1; - } - if (annotations == Py_None) - annotations = NULL; - else if (annotations && PyDict_Check(annotations)) { - Py_INCREF(annotations); - } - else { - PyErr_SetString(PyExc_SystemError, - "non-dict annotations"); - return -1; - } - Py_XDECREF(((PyFunctionObject *)op) -> func_annotations); - ((PyFunctionObject *) op) -> func_annotations = annotations; - return 0; + if (!PyFunction_Check(op)) { + PyErr_BadInternalCall(); + return -1; + } + if (annotations == Py_None) + annotations = NULL; + else if (annotations && PyDict_Check(annotations)) { + Py_INCREF(annotations); + } + else { + PyErr_SetString(PyExc_SystemError, + "non-dict annotations"); + return -1; + } + Py_XDECREF(((PyFunctionObject *)op) -> func_annotations); + ((PyFunctionObject *) op) -> func_annotations = annotations; + return 0; } /* Methods */ @@ -225,224 +225,224 @@ #define OFF(x) offsetof(PyFunctionObject, x) static PyMemberDef func_memberlist[] = { - {"__closure__", T_OBJECT, OFF(func_closure), - RESTRICTED|READONLY}, - {"__doc__", T_OBJECT, OFF(func_doc), PY_WRITE_RESTRICTED}, - {"__globals__", T_OBJECT, OFF(func_globals), - RESTRICTED|READONLY}, - {"__module__", T_OBJECT, OFF(func_module), PY_WRITE_RESTRICTED}, - {NULL} /* Sentinel */ + {"__closure__", T_OBJECT, OFF(func_closure), + RESTRICTED|READONLY}, + {"__doc__", T_OBJECT, OFF(func_doc), PY_WRITE_RESTRICTED}, + {"__globals__", T_OBJECT, OFF(func_globals), + RESTRICTED|READONLY}, + {"__module__", T_OBJECT, OFF(func_module), PY_WRITE_RESTRICTED}, + {NULL} /* Sentinel */ }; static PyObject * func_get_dict(PyFunctionObject *op) { - if (op->func_dict == NULL) { - op->func_dict = PyDict_New(); - if (op->func_dict == NULL) - return NULL; - } - Py_INCREF(op->func_dict); - return op->func_dict; + if (op->func_dict == NULL) { + op->func_dict = PyDict_New(); + if (op->func_dict == NULL) + return NULL; + } + Py_INCREF(op->func_dict); + return op->func_dict; } static int func_set_dict(PyFunctionObject *op, PyObject *value) { - PyObject *tmp; + PyObject *tmp; - /* It is illegal to del f.func_dict */ - if (value == NULL) { - PyErr_SetString(PyExc_TypeError, - "function's dictionary may not be deleted"); - return -1; - } - /* Can only set func_dict to a dictionary */ - if (!PyDict_Check(value)) { - PyErr_SetString(PyExc_TypeError, - "setting function's dictionary to a non-dict"); - return -1; - } - tmp = op->func_dict; - Py_INCREF(value); - op->func_dict = value; - Py_XDECREF(tmp); - return 0; + /* It is illegal to del f.func_dict */ + if (value == NULL) { + PyErr_SetString(PyExc_TypeError, + "function's dictionary may not be deleted"); + return -1; + } + /* Can only set func_dict to a dictionary */ + if (!PyDict_Check(value)) { + PyErr_SetString(PyExc_TypeError, + "setting function's dictionary to a non-dict"); + return -1; + } + tmp = op->func_dict; + Py_INCREF(value); + op->func_dict = value; + Py_XDECREF(tmp); + return 0; } static PyObject * func_get_code(PyFunctionObject *op) { - Py_INCREF(op->func_code); - return op->func_code; + Py_INCREF(op->func_code); + return op->func_code; } static int func_set_code(PyFunctionObject *op, PyObject *value) { - PyObject *tmp; - Py_ssize_t nfree, nclosure; + PyObject *tmp; + Py_ssize_t nfree, nclosure; - /* Not legal to del f.func_code or to set it to anything - * other than a code object. */ - if (value == NULL || !PyCode_Check(value)) { - PyErr_SetString(PyExc_TypeError, - "__code__ must be set to a code object"); - return -1; - } - nfree = PyCode_GetNumFree((PyCodeObject *)value); - nclosure = (op->func_closure == NULL ? 0 : - PyTuple_GET_SIZE(op->func_closure)); - if (nclosure != nfree) { - PyErr_Format(PyExc_ValueError, - "%U() requires a code object with %zd free vars," - " not %zd", - op->func_name, - nclosure, nfree); - return -1; - } - tmp = op->func_code; - Py_INCREF(value); - op->func_code = value; - Py_DECREF(tmp); - return 0; + /* Not legal to del f.func_code or to set it to anything + * other than a code object. */ + if (value == NULL || !PyCode_Check(value)) { + PyErr_SetString(PyExc_TypeError, + "__code__ must be set to a code object"); + return -1; + } + nfree = PyCode_GetNumFree((PyCodeObject *)value); + nclosure = (op->func_closure == NULL ? 0 : + PyTuple_GET_SIZE(op->func_closure)); + if (nclosure != nfree) { + PyErr_Format(PyExc_ValueError, + "%U() requires a code object with %zd free vars," + " not %zd", + op->func_name, + nclosure, nfree); + return -1; + } + tmp = op->func_code; + Py_INCREF(value); + op->func_code = value; + Py_DECREF(tmp); + return 0; } static PyObject * func_get_name(PyFunctionObject *op) { - Py_INCREF(op->func_name); - return op->func_name; + Py_INCREF(op->func_name); + return op->func_name; } static int func_set_name(PyFunctionObject *op, PyObject *value) { - PyObject *tmp; + PyObject *tmp; - /* Not legal to del f.func_name or to set it to anything - * other than a string object. */ - if (value == NULL || !PyUnicode_Check(value)) { - PyErr_SetString(PyExc_TypeError, - "__name__ must be set to a string object"); - return -1; - } - tmp = op->func_name; - Py_INCREF(value); - op->func_name = value; - Py_DECREF(tmp); - return 0; + /* Not legal to del f.func_name or to set it to anything + * other than a string object. */ + if (value == NULL || !PyUnicode_Check(value)) { + PyErr_SetString(PyExc_TypeError, + "__name__ must be set to a string object"); + return -1; + } + tmp = op->func_name; + Py_INCREF(value); + op->func_name = value; + Py_DECREF(tmp); + return 0; } static PyObject * func_get_defaults(PyFunctionObject *op) { - if (op->func_defaults == NULL) { - Py_INCREF(Py_None); - return Py_None; - } - Py_INCREF(op->func_defaults); - return op->func_defaults; + if (op->func_defaults == NULL) { + Py_INCREF(Py_None); + return Py_None; + } + Py_INCREF(op->func_defaults); + return op->func_defaults; } static int func_set_defaults(PyFunctionObject *op, PyObject *value) { - PyObject *tmp; + PyObject *tmp; - /* Legal to del f.func_defaults. - * Can only set func_defaults to NULL or a tuple. */ - if (value == Py_None) - value = NULL; - if (value != NULL && !PyTuple_Check(value)) { - PyErr_SetString(PyExc_TypeError, - "__defaults__ must be set to a tuple object"); - return -1; - } - tmp = op->func_defaults; - Py_XINCREF(value); - op->func_defaults = value; - Py_XDECREF(tmp); - return 0; + /* Legal to del f.func_defaults. + * Can only set func_defaults to NULL or a tuple. */ + if (value == Py_None) + value = NULL; + if (value != NULL && !PyTuple_Check(value)) { + PyErr_SetString(PyExc_TypeError, + "__defaults__ must be set to a tuple object"); + return -1; + } + tmp = op->func_defaults; + Py_XINCREF(value); + op->func_defaults = value; + Py_XDECREF(tmp); + return 0; } static PyObject * func_get_kwdefaults(PyFunctionObject *op) { - if (op->func_kwdefaults == NULL) { - Py_INCREF(Py_None); - return Py_None; - } - Py_INCREF(op->func_kwdefaults); - return op->func_kwdefaults; + if (op->func_kwdefaults == NULL) { + Py_INCREF(Py_None); + return Py_None; + } + Py_INCREF(op->func_kwdefaults); + return op->func_kwdefaults; } static int func_set_kwdefaults(PyFunctionObject *op, PyObject *value) { - PyObject *tmp; + PyObject *tmp; - if (value == Py_None) - value = NULL; - /* Legal to del f.func_kwdefaults. - * Can only set func_kwdefaults to NULL or a dict. */ - if (value != NULL && !PyDict_Check(value)) { - PyErr_SetString(PyExc_TypeError, - "__kwdefaults__ must be set to a dict object"); - return -1; - } - tmp = op->func_kwdefaults; - Py_XINCREF(value); - op->func_kwdefaults = value; - Py_XDECREF(tmp); - return 0; + if (value == Py_None) + value = NULL; + /* Legal to del f.func_kwdefaults. + * Can only set func_kwdefaults to NULL or a dict. */ + if (value != NULL && !PyDict_Check(value)) { + PyErr_SetString(PyExc_TypeError, + "__kwdefaults__ must be set to a dict object"); + return -1; + } + tmp = op->func_kwdefaults; + Py_XINCREF(value); + op->func_kwdefaults = value; + Py_XDECREF(tmp); + return 0; } static PyObject * func_get_annotations(PyFunctionObject *op) { - if (op->func_annotations == NULL) { - op->func_annotations = PyDict_New(); - if (op->func_annotations == NULL) - return NULL; - } - Py_INCREF(op->func_annotations); - return op->func_annotations; + if (op->func_annotations == NULL) { + op->func_annotations = PyDict_New(); + if (op->func_annotations == NULL) + return NULL; + } + Py_INCREF(op->func_annotations); + return op->func_annotations; } static int func_set_annotations(PyFunctionObject *op, PyObject *value) { - PyObject *tmp; + PyObject *tmp; - if (value == Py_None) - value = NULL; - /* Legal to del f.func_annotations. - * Can only set func_annotations to NULL (through C api) - * or a dict. */ - if (value != NULL && !PyDict_Check(value)) { - PyErr_SetString(PyExc_TypeError, - "__annotations__ must be set to a dict object"); - return -1; - } - tmp = op->func_annotations; - Py_XINCREF(value); - op->func_annotations = value; - Py_XDECREF(tmp); - return 0; + if (value == Py_None) + value = NULL; + /* Legal to del f.func_annotations. + * Can only set func_annotations to NULL (through C api) + * or a dict. */ + if (value != NULL && !PyDict_Check(value)) { + PyErr_SetString(PyExc_TypeError, + "__annotations__ must be set to a dict object"); + return -1; + } + tmp = op->func_annotations; + Py_XINCREF(value); + op->func_annotations = value; + Py_XDECREF(tmp); + return 0; } static PyGetSetDef func_getsetlist[] = { - {"__code__", (getter)func_get_code, (setter)func_set_code}, - {"__defaults__", (getter)func_get_defaults, - (setter)func_set_defaults}, - {"__kwdefaults__", (getter)func_get_kwdefaults, - (setter)func_set_kwdefaults}, - {"__annotations__", (getter)func_get_annotations, - (setter)func_set_annotations}, - {"__dict__", (getter)func_get_dict, (setter)func_set_dict}, - {"__name__", (getter)func_get_name, (setter)func_set_name}, - {NULL} /* Sentinel */ + {"__code__", (getter)func_get_code, (setter)func_set_code}, + {"__defaults__", (getter)func_get_defaults, + (setter)func_set_defaults}, + {"__kwdefaults__", (getter)func_get_kwdefaults, + (setter)func_set_kwdefaults}, + {"__annotations__", (getter)func_get_annotations, + (setter)func_set_annotations}, + {"__dict__", (getter)func_get_dict, (setter)func_set_dict}, + {"__name__", (getter)func_get_name, (setter)func_set_name}, + {NULL} /* Sentinel */ }; PyDoc_STRVAR(func_doc, @@ -455,241 +455,241 @@ /* func_new() maintains the following invariants for closures. The closure must correspond to the free variables of the code object. - - if len(code.co_freevars) == 0: - closure = NULL + + if len(code.co_freevars) == 0: + closure = NULL else: - len(closure) == len(code.co_freevars) + len(closure) == len(code.co_freevars) for every elt in closure, type(elt) == cell */ static PyObject * func_new(PyTypeObject* type, PyObject* args, PyObject* kw) { - PyCodeObject *code; - PyObject *globals; - PyObject *name = Py_None; - PyObject *defaults = Py_None; - PyObject *closure = Py_None; - PyFunctionObject *newfunc; - Py_ssize_t nfree, nclosure; - static char *kwlist[] = {"code", "globals", "name", - "argdefs", "closure", 0}; - - if (!PyArg_ParseTupleAndKeywords(args, kw, "O!O!|OOO:function", - kwlist, - &PyCode_Type, &code, - &PyDict_Type, &globals, - &name, &defaults, &closure)) - return NULL; - if (name != Py_None && !PyUnicode_Check(name)) { - PyErr_SetString(PyExc_TypeError, - "arg 3 (name) must be None or string"); - return NULL; - } - if (defaults != Py_None && !PyTuple_Check(defaults)) { - PyErr_SetString(PyExc_TypeError, - "arg 4 (defaults) must be None or tuple"); - return NULL; - } - nfree = PyTuple_GET_SIZE(code->co_freevars); - if (!PyTuple_Check(closure)) { - if (nfree && closure == Py_None) { - PyErr_SetString(PyExc_TypeError, - "arg 5 (closure) must be tuple"); - return NULL; - } - else if (closure != Py_None) { - PyErr_SetString(PyExc_TypeError, - "arg 5 (closure) must be None or tuple"); - return NULL; - } - } - - /* check that the closure is well-formed */ - nclosure = closure == Py_None ? 0 : PyTuple_GET_SIZE(closure); - if (nfree != nclosure) - return PyErr_Format(PyExc_ValueError, - "%U requires closure of length %zd, not %zd", - code->co_name, nfree, nclosure); - if (nclosure) { - Py_ssize_t i; - for (i = 0; i < nclosure; i++) { - PyObject *o = PyTuple_GET_ITEM(closure, i); - if (!PyCell_Check(o)) { - return PyErr_Format(PyExc_TypeError, - "arg 5 (closure) expected cell, found %s", - o->ob_type->tp_name); - } - } - } - - newfunc = (PyFunctionObject *)PyFunction_New((PyObject *)code, - globals); - if (newfunc == NULL) - return NULL; - - if (name != Py_None) { - Py_INCREF(name); - Py_DECREF(newfunc->func_name); - newfunc->func_name = name; - } - if (defaults != Py_None) { - Py_INCREF(defaults); - newfunc->func_defaults = defaults; - } - if (closure != Py_None) { - Py_INCREF(closure); - newfunc->func_closure = closure; - } + PyCodeObject *code; + PyObject *globals; + PyObject *name = Py_None; + PyObject *defaults = Py_None; + PyObject *closure = Py_None; + PyFunctionObject *newfunc; + Py_ssize_t nfree, nclosure; + static char *kwlist[] = {"code", "globals", "name", + "argdefs", "closure", 0}; + + if (!PyArg_ParseTupleAndKeywords(args, kw, "O!O!|OOO:function", + kwlist, + &PyCode_Type, &code, + &PyDict_Type, &globals, + &name, &defaults, &closure)) + return NULL; + if (name != Py_None && !PyUnicode_Check(name)) { + PyErr_SetString(PyExc_TypeError, + "arg 3 (name) must be None or string"); + return NULL; + } + if (defaults != Py_None && !PyTuple_Check(defaults)) { + PyErr_SetString(PyExc_TypeError, + "arg 4 (defaults) must be None or tuple"); + return NULL; + } + nfree = PyTuple_GET_SIZE(code->co_freevars); + if (!PyTuple_Check(closure)) { + if (nfree && closure == Py_None) { + PyErr_SetString(PyExc_TypeError, + "arg 5 (closure) must be tuple"); + return NULL; + } + else if (closure != Py_None) { + PyErr_SetString(PyExc_TypeError, + "arg 5 (closure) must be None or tuple"); + return NULL; + } + } + + /* check that the closure is well-formed */ + nclosure = closure == Py_None ? 0 : PyTuple_GET_SIZE(closure); + if (nfree != nclosure) + return PyErr_Format(PyExc_ValueError, + "%U requires closure of length %zd, not %zd", + code->co_name, nfree, nclosure); + if (nclosure) { + Py_ssize_t i; + for (i = 0; i < nclosure; i++) { + PyObject *o = PyTuple_GET_ITEM(closure, i); + if (!PyCell_Check(o)) { + return PyErr_Format(PyExc_TypeError, + "arg 5 (closure) expected cell, found %s", + o->ob_type->tp_name); + } + } + } + + newfunc = (PyFunctionObject *)PyFunction_New((PyObject *)code, + globals); + if (newfunc == NULL) + return NULL; + + if (name != Py_None) { + Py_INCREF(name); + Py_DECREF(newfunc->func_name); + newfunc->func_name = name; + } + if (defaults != Py_None) { + Py_INCREF(defaults); + newfunc->func_defaults = defaults; + } + if (closure != Py_None) { + Py_INCREF(closure); + newfunc->func_closure = closure; + } - return (PyObject *)newfunc; + return (PyObject *)newfunc; } static void func_dealloc(PyFunctionObject *op) { - _PyObject_GC_UNTRACK(op); - if (op->func_weakreflist != NULL) - PyObject_ClearWeakRefs((PyObject *) op); - Py_DECREF(op->func_code); - Py_DECREF(op->func_globals); - Py_XDECREF(op->func_module); - Py_DECREF(op->func_name); - Py_XDECREF(op->func_defaults); - Py_XDECREF(op->func_kwdefaults); - Py_XDECREF(op->func_doc); - Py_XDECREF(op->func_dict); - Py_XDECREF(op->func_closure); - Py_XDECREF(op->func_annotations); - PyObject_GC_Del(op); + _PyObject_GC_UNTRACK(op); + if (op->func_weakreflist != NULL) + PyObject_ClearWeakRefs((PyObject *) op); + Py_DECREF(op->func_code); + Py_DECREF(op->func_globals); + Py_XDECREF(op->func_module); + Py_DECREF(op->func_name); + Py_XDECREF(op->func_defaults); + Py_XDECREF(op->func_kwdefaults); + Py_XDECREF(op->func_doc); + Py_XDECREF(op->func_dict); + Py_XDECREF(op->func_closure); + Py_XDECREF(op->func_annotations); + PyObject_GC_Del(op); } static PyObject* func_repr(PyFunctionObject *op) { - return PyUnicode_FromFormat("", - op->func_name, op); + return PyUnicode_FromFormat("", + op->func_name, op); } static int func_traverse(PyFunctionObject *f, visitproc visit, void *arg) { - Py_VISIT(f->func_code); - Py_VISIT(f->func_globals); - Py_VISIT(f->func_module); - Py_VISIT(f->func_defaults); - Py_VISIT(f->func_kwdefaults); - Py_VISIT(f->func_doc); - Py_VISIT(f->func_name); - Py_VISIT(f->func_dict); - Py_VISIT(f->func_closure); - Py_VISIT(f->func_annotations); - return 0; + Py_VISIT(f->func_code); + Py_VISIT(f->func_globals); + Py_VISIT(f->func_module); + Py_VISIT(f->func_defaults); + Py_VISIT(f->func_kwdefaults); + Py_VISIT(f->func_doc); + Py_VISIT(f->func_name); + Py_VISIT(f->func_dict); + Py_VISIT(f->func_closure); + Py_VISIT(f->func_annotations); + return 0; } static PyObject * function_call(PyObject *func, PyObject *arg, PyObject *kw) { - PyObject *result; - PyObject *argdefs; - PyObject *kwtuple = NULL; - PyObject **d, **k; - Py_ssize_t nk, nd; - - argdefs = PyFunction_GET_DEFAULTS(func); - if (argdefs != NULL && PyTuple_Check(argdefs)) { - d = &PyTuple_GET_ITEM((PyTupleObject *)argdefs, 0); - nd = PyTuple_GET_SIZE(argdefs); - } - else { - d = NULL; - nd = 0; - } - - if (kw != NULL && PyDict_Check(kw)) { - Py_ssize_t pos, i; - nk = PyDict_Size(kw); - kwtuple = PyTuple_New(2*nk); - if (kwtuple == NULL) - return NULL; - k = &PyTuple_GET_ITEM(kwtuple, 0); - pos = i = 0; - while (PyDict_Next(kw, &pos, &k[i], &k[i+1])) { - Py_INCREF(k[i]); - Py_INCREF(k[i+1]); - i += 2; - } - nk = i/2; - } - else { - k = NULL; - nk = 0; - } - - result = PyEval_EvalCodeEx( - (PyCodeObject *)PyFunction_GET_CODE(func), - PyFunction_GET_GLOBALS(func), (PyObject *)NULL, - &PyTuple_GET_ITEM(arg, 0), PyTuple_GET_SIZE(arg), - k, nk, d, nd, - PyFunction_GET_KW_DEFAULTS(func), - PyFunction_GET_CLOSURE(func)); + PyObject *result; + PyObject *argdefs; + PyObject *kwtuple = NULL; + PyObject **d, **k; + Py_ssize_t nk, nd; + + argdefs = PyFunction_GET_DEFAULTS(func); + if (argdefs != NULL && PyTuple_Check(argdefs)) { + d = &PyTuple_GET_ITEM((PyTupleObject *)argdefs, 0); + nd = PyTuple_GET_SIZE(argdefs); + } + else { + d = NULL; + nd = 0; + } + + if (kw != NULL && PyDict_Check(kw)) { + Py_ssize_t pos, i; + nk = PyDict_Size(kw); + kwtuple = PyTuple_New(2*nk); + if (kwtuple == NULL) + return NULL; + k = &PyTuple_GET_ITEM(kwtuple, 0); + pos = i = 0; + while (PyDict_Next(kw, &pos, &k[i], &k[i+1])) { + Py_INCREF(k[i]); + Py_INCREF(k[i+1]); + i += 2; + } + nk = i/2; + } + else { + k = NULL; + nk = 0; + } + + result = PyEval_EvalCodeEx( + (PyCodeObject *)PyFunction_GET_CODE(func), + PyFunction_GET_GLOBALS(func), (PyObject *)NULL, + &PyTuple_GET_ITEM(arg, 0), PyTuple_GET_SIZE(arg), + k, nk, d, nd, + PyFunction_GET_KW_DEFAULTS(func), + PyFunction_GET_CLOSURE(func)); - Py_XDECREF(kwtuple); + Py_XDECREF(kwtuple); - return result; + return result; } /* Bind a function to an object */ static PyObject * func_descr_get(PyObject *func, PyObject *obj, PyObject *type) { - if (obj == Py_None || obj == NULL) { - Py_INCREF(func); - return func; - } - return PyMethod_New(func, obj); + if (obj == Py_None || obj == NULL) { + Py_INCREF(func); + return func; + } + return PyMethod_New(func, obj); } PyTypeObject PyFunction_Type = { - PyVarObject_HEAD_INIT(&PyType_Type, 0) - "function", - sizeof(PyFunctionObject), - 0, - (destructor)func_dealloc, /* tp_dealloc */ - 0, /* tp_print */ - 0, /* tp_getattr */ - 0, /* tp_setattr */ - 0, /* tp_reserved */ - (reprfunc)func_repr, /* tp_repr */ - 0, /* tp_as_number */ - 0, /* tp_as_sequence */ - 0, /* tp_as_mapping */ - 0, /* tp_hash */ - function_call, /* tp_call */ - 0, /* tp_str */ - PyObject_GenericGetAttr, /* tp_getattro */ - PyObject_GenericSetAttr, /* tp_setattro */ - 0, /* tp_as_buffer */ - Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */ - func_doc, /* tp_doc */ - (traverseproc)func_traverse, /* tp_traverse */ - 0, /* tp_clear */ - 0, /* tp_richcompare */ - offsetof(PyFunctionObject, func_weakreflist), /* tp_weaklistoffset */ - 0, /* tp_iter */ - 0, /* tp_iternext */ - 0, /* tp_methods */ - func_memberlist, /* tp_members */ - func_getsetlist, /* tp_getset */ - 0, /* tp_base */ - 0, /* tp_dict */ - func_descr_get, /* tp_descr_get */ - 0, /* tp_descr_set */ - offsetof(PyFunctionObject, func_dict), /* tp_dictoffset */ - 0, /* tp_init */ - 0, /* tp_alloc */ - func_new, /* tp_new */ + PyVarObject_HEAD_INIT(&PyType_Type, 0) + "function", + sizeof(PyFunctionObject), + 0, + (destructor)func_dealloc, /* tp_dealloc */ + 0, /* tp_print */ + 0, /* tp_getattr */ + 0, /* tp_setattr */ + 0, /* tp_reserved */ + (reprfunc)func_repr, /* tp_repr */ + 0, /* tp_as_number */ + 0, /* tp_as_sequence */ + 0, /* tp_as_mapping */ + 0, /* tp_hash */ + function_call, /* tp_call */ + 0, /* tp_str */ + PyObject_GenericGetAttr, /* tp_getattro */ + PyObject_GenericSetAttr, /* tp_setattro */ + 0, /* tp_as_buffer */ + Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */ + func_doc, /* tp_doc */ + (traverseproc)func_traverse, /* tp_traverse */ + 0, /* tp_clear */ + 0, /* tp_richcompare */ + offsetof(PyFunctionObject, func_weakreflist), /* tp_weaklistoffset */ + 0, /* tp_iter */ + 0, /* tp_iternext */ + 0, /* tp_methods */ + func_memberlist, /* tp_members */ + func_getsetlist, /* tp_getset */ + 0, /* tp_base */ + 0, /* tp_dict */ + func_descr_get, /* tp_descr_get */ + 0, /* tp_descr_set */ + offsetof(PyFunctionObject, func_dict), /* tp_dictoffset */ + 0, /* tp_init */ + 0, /* tp_alloc */ + func_new, /* tp_new */ }; @@ -700,9 +700,9 @@ To declare a class method, use this idiom: class C: - def f(cls, arg1, arg2, ...): ... - f = classmethod(f) - + def f(cls, arg1, arg2, ...): ... + f = classmethod(f) + It can be called either on the class (e.g. C.f()) or on an instance (e.g. C().f()); the instance is ignored except for its class. If a class method is called for a derived class, the derived class @@ -713,66 +713,66 @@ */ typedef struct { - PyObject_HEAD - PyObject *cm_callable; + PyObject_HEAD + PyObject *cm_callable; } classmethod; static void cm_dealloc(classmethod *cm) { - _PyObject_GC_UNTRACK((PyObject *)cm); - Py_XDECREF(cm->cm_callable); - Py_TYPE(cm)->tp_free((PyObject *)cm); + _PyObject_GC_UNTRACK((PyObject *)cm); + Py_XDECREF(cm->cm_callable); + Py_TYPE(cm)->tp_free((PyObject *)cm); } static int cm_traverse(classmethod *cm, visitproc visit, void *arg) { - Py_VISIT(cm->cm_callable); - return 0; + Py_VISIT(cm->cm_callable); + return 0; } static int cm_clear(classmethod *cm) { - Py_CLEAR(cm->cm_callable); - return 0; + Py_CLEAR(cm->cm_callable); + return 0; } static PyObject * cm_descr_get(PyObject *self, PyObject *obj, PyObject *type) { - classmethod *cm = (classmethod *)self; + classmethod *cm = (classmethod *)self; - if (cm->cm_callable == NULL) { - PyErr_SetString(PyExc_RuntimeError, - "uninitialized classmethod object"); - return NULL; - } - if (type == NULL) - type = (PyObject *)(Py_TYPE(obj)); - return PyMethod_New(cm->cm_callable, type); + if (cm->cm_callable == NULL) { + PyErr_SetString(PyExc_RuntimeError, + "uninitialized classmethod object"); + return NULL; + } + if (type == NULL) + type = (PyObject *)(Py_TYPE(obj)); + return PyMethod_New(cm->cm_callable, type); } static int cm_init(PyObject *self, PyObject *args, PyObject *kwds) { - classmethod *cm = (classmethod *)self; - PyObject *callable; + classmethod *cm = (classmethod *)self; + PyObject *callable; - if (!PyArg_UnpackTuple(args, "classmethod", 1, 1, &callable)) - return -1; - if (!_PyArg_NoKeywords("classmethod", kwds)) - return -1; - Py_INCREF(callable); - cm->cm_callable = callable; - return 0; + if (!PyArg_UnpackTuple(args, "classmethod", 1, 1, &callable)) + return -1; + if (!_PyArg_NoKeywords("classmethod", kwds)) + return -1; + Py_INCREF(callable); + cm->cm_callable = callable; + return 0; } static PyMemberDef cm_memberlist[] = { - {"__func__", T_OBJECT, offsetof(classmethod, cm_callable), READONLY}, - {NULL} /* Sentinel */ + {"__func__", T_OBJECT, offsetof(classmethod, cm_callable), READONLY}, + {NULL} /* Sentinel */ }; PyDoc_STRVAR(classmethod_doc, @@ -797,57 +797,57 @@ If you want those, see the staticmethod builtin."); PyTypeObject PyClassMethod_Type = { - PyVarObject_HEAD_INIT(&PyType_Type, 0) - "classmethod", - sizeof(classmethod), - 0, - (destructor)cm_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_BASETYPE | Py_TPFLAGS_HAVE_GC, - classmethod_doc, /* tp_doc */ - (traverseproc)cm_traverse, /* tp_traverse */ - (inquiry)cm_clear, /* tp_clear */ - 0, /* tp_richcompare */ - 0, /* tp_weaklistoffset */ - 0, /* tp_iter */ - 0, /* tp_iternext */ - 0, /* tp_methods */ - cm_memberlist, /* tp_members */ - 0, /* tp_getset */ - 0, /* tp_base */ - 0, /* tp_dict */ - cm_descr_get, /* tp_descr_get */ - 0, /* tp_descr_set */ - 0, /* tp_dictoffset */ - cm_init, /* tp_init */ - PyType_GenericAlloc, /* tp_alloc */ - PyType_GenericNew, /* tp_new */ - PyObject_GC_Del, /* tp_free */ + PyVarObject_HEAD_INIT(&PyType_Type, 0) + "classmethod", + sizeof(classmethod), + 0, + (destructor)cm_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_BASETYPE | Py_TPFLAGS_HAVE_GC, + classmethod_doc, /* tp_doc */ + (traverseproc)cm_traverse, /* tp_traverse */ + (inquiry)cm_clear, /* tp_clear */ + 0, /* tp_richcompare */ + 0, /* tp_weaklistoffset */ + 0, /* tp_iter */ + 0, /* tp_iternext */ + 0, /* tp_methods */ + cm_memberlist, /* tp_members */ + 0, /* tp_getset */ + 0, /* tp_base */ + 0, /* tp_dict */ + cm_descr_get, /* tp_descr_get */ + 0, /* tp_descr_set */ + 0, /* tp_dictoffset */ + cm_init, /* tp_init */ + PyType_GenericAlloc, /* tp_alloc */ + PyType_GenericNew, /* tp_new */ + PyObject_GC_Del, /* tp_free */ }; PyObject * PyClassMethod_New(PyObject *callable) { - classmethod *cm = (classmethod *) - PyType_GenericAlloc(&PyClassMethod_Type, 0); - if (cm != NULL) { - Py_INCREF(callable); - cm->cm_callable = callable; - } - return (PyObject *)cm; + classmethod *cm = (classmethod *) + PyType_GenericAlloc(&PyClassMethod_Type, 0); + if (cm != NULL) { + Py_INCREF(callable); + cm->cm_callable = callable; + } + return (PyObject *)cm; } @@ -857,8 +857,8 @@ To declare a static method, use this idiom: class C: - def f(arg1, arg2, ...): ... - f = staticmethod(f) + def f(arg1, arg2, ...): ... + f = staticmethod(f) It can be called either on the class (e.g. C.f()) or on an instance (e.g. C().f()); the instance is ignored except for its class. @@ -868,66 +868,66 @@ */ typedef struct { - PyObject_HEAD - PyObject *sm_callable; + PyObject_HEAD + PyObject *sm_callable; } staticmethod; static void sm_dealloc(staticmethod *sm) { - _PyObject_GC_UNTRACK((PyObject *)sm); - Py_XDECREF(sm->sm_callable); - Py_TYPE(sm)->tp_free((PyObject *)sm); + _PyObject_GC_UNTRACK((PyObject *)sm); + Py_XDECREF(sm->sm_callable); + Py_TYPE(sm)->tp_free((PyObject *)sm); } static int sm_traverse(staticmethod *sm, visitproc visit, void *arg) { - Py_VISIT(sm->sm_callable); - return 0; + Py_VISIT(sm->sm_callable); + return 0; } static int sm_clear(staticmethod *sm) { - Py_XDECREF(sm->sm_callable); - sm->sm_callable = NULL; + Py_XDECREF(sm->sm_callable); + sm->sm_callable = NULL; - return 0; + return 0; } static PyObject * sm_descr_get(PyObject *self, PyObject *obj, PyObject *type) { - staticmethod *sm = (staticmethod *)self; + staticmethod *sm = (staticmethod *)self; - if (sm->sm_callable == NULL) { - PyErr_SetString(PyExc_RuntimeError, - "uninitialized staticmethod object"); - return NULL; - } - Py_INCREF(sm->sm_callable); - return sm->sm_callable; + if (sm->sm_callable == NULL) { + PyErr_SetString(PyExc_RuntimeError, + "uninitialized staticmethod object"); + return NULL; + } + Py_INCREF(sm->sm_callable); + return sm->sm_callable; } static int sm_init(PyObject *self, PyObject *args, PyObject *kwds) { - staticmethod *sm = (staticmethod *)self; - PyObject *callable; + staticmethod *sm = (staticmethod *)self; + PyObject *callable; - if (!PyArg_UnpackTuple(args, "staticmethod", 1, 1, &callable)) - return -1; - if (!_PyArg_NoKeywords("staticmethod", kwds)) - return -1; - Py_INCREF(callable); - sm->sm_callable = callable; - return 0; + if (!PyArg_UnpackTuple(args, "staticmethod", 1, 1, &callable)) + return -1; + if (!_PyArg_NoKeywords("staticmethod", kwds)) + return -1; + Py_INCREF(callable); + sm->sm_callable = callable; + return 0; } static PyMemberDef sm_memberlist[] = { - {"__func__", T_OBJECT, offsetof(staticmethod, sm_callable), READONLY}, - {NULL} /* Sentinel */ + {"__func__", T_OBJECT, offsetof(staticmethod, sm_callable), READONLY}, + {NULL} /* Sentinel */ }; PyDoc_STRVAR(staticmethod_doc, @@ -939,8 +939,8 @@ To declare a static method, use this idiom:\n\ \n\ class C:\n\ - def f(arg1, arg2, ...): ...\n\ - f = staticmethod(f)\n\ + def f(arg1, arg2, ...): ...\n\ + f = staticmethod(f)\n\ \n\ It can be called either on the class (e.g. C.f()) or on an instance\n\ (e.g. C().f()). The instance is ignored except for its class.\n\ @@ -949,55 +949,55 @@ For a more advanced concept, see the classmethod builtin."); PyTypeObject PyStaticMethod_Type = { - PyVarObject_HEAD_INIT(&PyType_Type, 0) - "staticmethod", - sizeof(staticmethod), - 0, - (destructor)sm_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_BASETYPE | Py_TPFLAGS_HAVE_GC, - staticmethod_doc, /* tp_doc */ - (traverseproc)sm_traverse, /* tp_traverse */ - (inquiry)sm_clear, /* tp_clear */ - 0, /* tp_richcompare */ - 0, /* tp_weaklistoffset */ - 0, /* tp_iter */ - 0, /* tp_iternext */ - 0, /* tp_methods */ - sm_memberlist, /* tp_members */ - 0, /* tp_getset */ - 0, /* tp_base */ - 0, /* tp_dict */ - sm_descr_get, /* tp_descr_get */ - 0, /* tp_descr_set */ - 0, /* tp_dictoffset */ - sm_init, /* tp_init */ - PyType_GenericAlloc, /* tp_alloc */ - PyType_GenericNew, /* tp_new */ - PyObject_GC_Del, /* tp_free */ + PyVarObject_HEAD_INIT(&PyType_Type, 0) + "staticmethod", + sizeof(staticmethod), + 0, + (destructor)sm_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_BASETYPE | Py_TPFLAGS_HAVE_GC, + staticmethod_doc, /* tp_doc */ + (traverseproc)sm_traverse, /* tp_traverse */ + (inquiry)sm_clear, /* tp_clear */ + 0, /* tp_richcompare */ + 0, /* tp_weaklistoffset */ + 0, /* tp_iter */ + 0, /* tp_iternext */ + 0, /* tp_methods */ + sm_memberlist, /* tp_members */ + 0, /* tp_getset */ + 0, /* tp_base */ + 0, /* tp_dict */ + sm_descr_get, /* tp_descr_get */ + 0, /* tp_descr_set */ + 0, /* tp_dictoffset */ + sm_init, /* tp_init */ + PyType_GenericAlloc, /* tp_alloc */ + PyType_GenericNew, /* tp_new */ + PyObject_GC_Del, /* tp_free */ }; PyObject * PyStaticMethod_New(PyObject *callable) { - staticmethod *sm = (staticmethod *) - PyType_GenericAlloc(&PyStaticMethod_Type, 0); - if (sm != NULL) { - Py_INCREF(callable); - sm->sm_callable = callable; - } - return (PyObject *)sm; + staticmethod *sm = (staticmethod *) + PyType_GenericAlloc(&PyStaticMethod_Type, 0); + if (sm != NULL) { + Py_INCREF(callable); + sm->sm_callable = callable; + } + return (PyObject *)sm; } Modified: python/branches/py3k/Objects/genobject.c ============================================================================== --- python/branches/py3k/Objects/genobject.c (original) +++ python/branches/py3k/Objects/genobject.c Sun May 9 17:52:27 2010 @@ -10,103 +10,103 @@ static int gen_traverse(PyGenObject *gen, visitproc visit, void *arg) { - Py_VISIT((PyObject *)gen->gi_frame); - Py_VISIT(gen->gi_code); - return 0; + Py_VISIT((PyObject *)gen->gi_frame); + Py_VISIT(gen->gi_code); + return 0; } static void gen_dealloc(PyGenObject *gen) { - PyObject *self = (PyObject *) gen; + PyObject *self = (PyObject *) gen; - _PyObject_GC_UNTRACK(gen); + _PyObject_GC_UNTRACK(gen); - if (gen->gi_weakreflist != NULL) - PyObject_ClearWeakRefs(self); + if (gen->gi_weakreflist != NULL) + PyObject_ClearWeakRefs(self); - _PyObject_GC_TRACK(self); + _PyObject_GC_TRACK(self); - if (gen->gi_frame != NULL && gen->gi_frame->f_stacktop != NULL) { - /* Generator is paused, so we need to close */ - Py_TYPE(gen)->tp_del(self); - if (self->ob_refcnt > 0) - return; /* resurrected. :( */ - } - - _PyObject_GC_UNTRACK(self); - Py_CLEAR(gen->gi_frame); - Py_CLEAR(gen->gi_code); - PyObject_GC_Del(gen); + if (gen->gi_frame != NULL && gen->gi_frame->f_stacktop != NULL) { + /* Generator is paused, so we need to close */ + Py_TYPE(gen)->tp_del(self); + if (self->ob_refcnt > 0) + return; /* resurrected. :( */ + } + + _PyObject_GC_UNTRACK(self); + Py_CLEAR(gen->gi_frame); + Py_CLEAR(gen->gi_code); + PyObject_GC_Del(gen); } static PyObject * gen_send_ex(PyGenObject *gen, PyObject *arg, int exc) { - PyThreadState *tstate = PyThreadState_GET(); - PyFrameObject *f = gen->gi_frame; - PyObject *result; - - if (gen->gi_running) { - PyErr_SetString(PyExc_ValueError, - "generator already executing"); - return NULL; - } - if (f==NULL || f->f_stacktop == NULL) { - /* Only set exception if called from send() */ - if (arg && !exc) - PyErr_SetNone(PyExc_StopIteration); - return NULL; - } - - if (f->f_lasti == -1) { - if (arg && arg != Py_None) { - PyErr_SetString(PyExc_TypeError, - "can't send non-None value to a " - "just-started generator"); - return NULL; - } - } else { - /* Push arg onto the frame's value stack */ - result = arg ? arg : Py_None; - Py_INCREF(result); - *(f->f_stacktop++) = result; - } - - /* Generators always return to their most recent caller, not - * necessarily their creator. */ - Py_XINCREF(tstate->frame); - assert(f->f_back == NULL); - f->f_back = tstate->frame; - - gen->gi_running = 1; - result = PyEval_EvalFrameEx(f, exc); - gen->gi_running = 0; - - /* Don't keep the reference to f_back any longer than necessary. It - * may keep a chain of frames alive or it could create a reference - * cycle. */ - assert(f->f_back == tstate->frame); - Py_CLEAR(f->f_back); - - /* If the generator just returned (as opposed to yielding), signal - * that the generator is exhausted. */ - if (result == Py_None && f->f_stacktop == NULL) { - Py_DECREF(result); - result = NULL; - /* Set exception if not called by gen_iternext() */ - if (arg) - PyErr_SetNone(PyExc_StopIteration); - } - - if (!result || f->f_stacktop == NULL) { - /* generator can't be rerun, so release the frame */ - Py_DECREF(f); - gen->gi_frame = NULL; - } + PyThreadState *tstate = PyThreadState_GET(); + PyFrameObject *f = gen->gi_frame; + PyObject *result; + + if (gen->gi_running) { + PyErr_SetString(PyExc_ValueError, + "generator already executing"); + return NULL; + } + if (f==NULL || f->f_stacktop == NULL) { + /* Only set exception if called from send() */ + if (arg && !exc) + PyErr_SetNone(PyExc_StopIteration); + return NULL; + } + + if (f->f_lasti == -1) { + if (arg && arg != Py_None) { + PyErr_SetString(PyExc_TypeError, + "can't send non-None value to a " + "just-started generator"); + return NULL; + } + } else { + /* Push arg onto the frame's value stack */ + result = arg ? arg : Py_None; + Py_INCREF(result); + *(f->f_stacktop++) = result; + } + + /* Generators always return to their most recent caller, not + * necessarily their creator. */ + Py_XINCREF(tstate->frame); + assert(f->f_back == NULL); + f->f_back = tstate->frame; + + gen->gi_running = 1; + result = PyEval_EvalFrameEx(f, exc); + gen->gi_running = 0; + + /* Don't keep the reference to f_back any longer than necessary. It + * may keep a chain of frames alive or it could create a reference + * cycle. */ + assert(f->f_back == tstate->frame); + Py_CLEAR(f->f_back); + + /* If the generator just returned (as opposed to yielding), signal + * that the generator is exhausted. */ + if (result == Py_None && f->f_stacktop == NULL) { + Py_DECREF(result); + result = NULL; + /* Set exception if not called by gen_iternext() */ + if (arg) + PyErr_SetNone(PyExc_StopIteration); + } + + if (!result || f->f_stacktop == NULL) { + /* generator can't be rerun, so release the frame */ + Py_DECREF(f); + gen->gi_frame = NULL; + } - return result; + return result; } PyDoc_STRVAR(send_doc, @@ -116,7 +116,7 @@ static PyObject * gen_send(PyGenObject *gen, PyObject *arg) { - return gen_send_ex(gen, arg, 0); + return gen_send_ex(gen, arg, 0); } PyDoc_STRVAR(close_doc, @@ -125,83 +125,83 @@ static PyObject * gen_close(PyGenObject *gen, PyObject *args) { - PyObject *retval; - PyErr_SetNone(PyExc_GeneratorExit); - retval = gen_send_ex(gen, Py_None, 1); - if (retval) { - Py_DECREF(retval); - PyErr_SetString(PyExc_RuntimeError, - "generator ignored GeneratorExit"); - return NULL; - } - if (PyErr_ExceptionMatches(PyExc_StopIteration) - || PyErr_ExceptionMatches(PyExc_GeneratorExit)) - { - PyErr_Clear(); /* ignore these errors */ - Py_INCREF(Py_None); - return Py_None; - } - return NULL; + PyObject *retval; + PyErr_SetNone(PyExc_GeneratorExit); + retval = gen_send_ex(gen, Py_None, 1); + if (retval) { + Py_DECREF(retval); + PyErr_SetString(PyExc_RuntimeError, + "generator ignored GeneratorExit"); + return NULL; + } + if (PyErr_ExceptionMatches(PyExc_StopIteration) + || PyErr_ExceptionMatches(PyExc_GeneratorExit)) + { + PyErr_Clear(); /* ignore these errors */ + Py_INCREF(Py_None); + return Py_None; + } + return NULL; } static void gen_del(PyObject *self) { - PyObject *res; - PyObject *error_type, *error_value, *error_traceback; - PyGenObject *gen = (PyGenObject *)self; - - if (gen->gi_frame == NULL || gen->gi_frame->f_stacktop == NULL) - /* Generator isn't paused, so no need to close */ - return; - - /* Temporarily resurrect the object. */ - assert(self->ob_refcnt == 0); - self->ob_refcnt = 1; - - /* Save the current exception, if any. */ - PyErr_Fetch(&error_type, &error_value, &error_traceback); - - res = gen_close(gen, NULL); - - if (res == NULL) - PyErr_WriteUnraisable(self); - else - Py_DECREF(res); - - /* Restore the saved exception. */ - PyErr_Restore(error_type, error_value, error_traceback); - - /* Undo the temporary resurrection; can't use DECREF here, it would - * cause a recursive call. - */ - assert(self->ob_refcnt > 0); - if (--self->ob_refcnt == 0) - return; /* this is the normal path out */ - - /* close() resurrected it! Make it look like the original Py_DECREF - * never happened. - */ - { - Py_ssize_t refcnt = self->ob_refcnt; - _Py_NewReference(self); - self->ob_refcnt = refcnt; - } - assert(PyType_IS_GC(self->ob_type) && - _Py_AS_GC(self)->gc.gc_refs != _PyGC_REFS_UNTRACKED); - - /* If Py_REF_DEBUG, _Py_NewReference bumped _Py_RefTotal, so - * we need to undo that. */ - _Py_DEC_REFTOTAL; - /* If Py_TRACE_REFS, _Py_NewReference re-added self to the object - * chain, so no more to do there. - * If COUNT_ALLOCS, the original decref bumped tp_frees, and - * _Py_NewReference bumped tp_allocs: both of those need to be - * undone. - */ + PyObject *res; + PyObject *error_type, *error_value, *error_traceback; + PyGenObject *gen = (PyGenObject *)self; + + if (gen->gi_frame == NULL || gen->gi_frame->f_stacktop == NULL) + /* Generator isn't paused, so no need to close */ + return; + + /* Temporarily resurrect the object. */ + assert(self->ob_refcnt == 0); + self->ob_refcnt = 1; + + /* Save the current exception, if any. */ + PyErr_Fetch(&error_type, &error_value, &error_traceback); + + res = gen_close(gen, NULL); + + if (res == NULL) + PyErr_WriteUnraisable(self); + else + Py_DECREF(res); + + /* Restore the saved exception. */ + PyErr_Restore(error_type, error_value, error_traceback); + + /* Undo the temporary resurrection; can't use DECREF here, it would + * cause a recursive call. + */ + assert(self->ob_refcnt > 0); + if (--self->ob_refcnt == 0) + return; /* this is the normal path out */ + + /* close() resurrected it! Make it look like the original Py_DECREF + * never happened. + */ + { + Py_ssize_t refcnt = self->ob_refcnt; + _Py_NewReference(self); + self->ob_refcnt = refcnt; + } + assert(PyType_IS_GC(self->ob_type) && + _Py_AS_GC(self)->gc.gc_refs != _PyGC_REFS_UNTRACKED); + + /* If Py_REF_DEBUG, _Py_NewReference bumped _Py_RefTotal, so + * we need to undo that. */ + _Py_DEC_REFTOTAL; + /* If Py_TRACE_REFS, _Py_NewReference re-added self to the object + * chain, so no more to do there. + * If COUNT_ALLOCS, the original decref bumped tp_frees, and + * _Py_NewReference bumped tp_allocs: both of those need to be + * undone. + */ #ifdef COUNT_ALLOCS - --self->ob_type->tp_frees; - --self->ob_type->tp_allocs; + --self->ob_type->tp_frees; + --self->ob_type->tp_allocs; #endif } @@ -214,89 +214,89 @@ static PyObject * gen_throw(PyGenObject *gen, PyObject *args) { - PyObject *typ; - PyObject *tb = NULL; - PyObject *val = NULL; - - if (!PyArg_UnpackTuple(args, "throw", 1, 3, &typ, &val, &tb)) - return NULL; - - /* First, check the traceback argument, replacing None with - NULL. */ - if (tb == Py_None) - tb = NULL; - else if (tb != NULL && !PyTraceBack_Check(tb)) { - PyErr_SetString(PyExc_TypeError, - "throw() third argument must be a traceback object"); - return NULL; - } - - Py_INCREF(typ); - Py_XINCREF(val); - Py_XINCREF(tb); - - if (PyExceptionClass_Check(typ)) { - PyErr_NormalizeException(&typ, &val, &tb); - } - - else if (PyExceptionInstance_Check(typ)) { - /* Raising an instance. The value should be a dummy. */ - if (val && val != Py_None) { - PyErr_SetString(PyExc_TypeError, - "instance exception may not have a separate value"); - goto failed_throw; - } - else { - /* Normalize to raise , */ - Py_XDECREF(val); - val = typ; - typ = PyExceptionInstance_Class(typ); - Py_INCREF(typ); - } - } - else { - /* Not something you can raise. throw() fails. */ - PyErr_Format(PyExc_TypeError, - "exceptions must be classes or instances " - "deriving from BaseException, not %s", - typ->ob_type->tp_name); - goto failed_throw; - } + PyObject *typ; + PyObject *tb = NULL; + PyObject *val = NULL; + + if (!PyArg_UnpackTuple(args, "throw", 1, 3, &typ, &val, &tb)) + return NULL; + + /* First, check the traceback argument, replacing None with + NULL. */ + if (tb == Py_None) + tb = NULL; + else if (tb != NULL && !PyTraceBack_Check(tb)) { + PyErr_SetString(PyExc_TypeError, + "throw() third argument must be a traceback object"); + return NULL; + } + + Py_INCREF(typ); + Py_XINCREF(val); + Py_XINCREF(tb); + + if (PyExceptionClass_Check(typ)) { + PyErr_NormalizeException(&typ, &val, &tb); + } + + else if (PyExceptionInstance_Check(typ)) { + /* Raising an instance. The value should be a dummy. */ + if (val && val != Py_None) { + PyErr_SetString(PyExc_TypeError, + "instance exception may not have a separate value"); + goto failed_throw; + } + else { + /* Normalize to raise , */ + Py_XDECREF(val); + val = typ; + typ = PyExceptionInstance_Class(typ); + Py_INCREF(typ); + } + } + else { + /* Not something you can raise. throw() fails. */ + PyErr_Format(PyExc_TypeError, + "exceptions must be classes or instances " + "deriving from BaseException, not %s", + typ->ob_type->tp_name); + goto failed_throw; + } - PyErr_Restore(typ, val, tb); - return gen_send_ex(gen, Py_None, 1); + PyErr_Restore(typ, val, tb); + return gen_send_ex(gen, Py_None, 1); failed_throw: - /* Didn't use our arguments, so restore their original refcounts */ - Py_DECREF(typ); - Py_XDECREF(val); - Py_XDECREF(tb); - return NULL; + /* Didn't use our arguments, so restore their original refcounts */ + Py_DECREF(typ); + Py_XDECREF(val); + Py_XDECREF(tb); + return NULL; } static PyObject * gen_iternext(PyGenObject *gen) { - return gen_send_ex(gen, NULL, 0); + return gen_send_ex(gen, NULL, 0); } static PyObject * gen_repr(PyGenObject *gen) { - return PyUnicode_FromFormat("", - ((PyCodeObject *)gen->gi_code)->co_name, - gen); + return PyUnicode_FromFormat("", + ((PyCodeObject *)gen->gi_code)->co_name, + gen); } static PyObject * gen_get_name(PyGenObject *gen) { - PyObject *name = ((PyCodeObject *)gen->gi_code)->co_name; - Py_INCREF(name); - return name; + PyObject *name = ((PyCodeObject *)gen->gi_code)->co_name; + Py_INCREF(name); + return name; } @@ -304,109 +304,109 @@ "Return the name of the generator's associated code object."); static PyGetSetDef gen_getsetlist[] = { - {"__name__", (getter)gen_get_name, NULL, gen__name__doc__}, - {NULL} + {"__name__", (getter)gen_get_name, NULL, gen__name__doc__}, + {NULL} }; static PyMemberDef gen_memberlist[] = { - {"gi_frame", T_OBJECT, offsetof(PyGenObject, gi_frame), READONLY}, - {"gi_running", T_INT, offsetof(PyGenObject, gi_running), READONLY}, - {"gi_code", T_OBJECT, offsetof(PyGenObject, gi_code), READONLY}, - {NULL} /* Sentinel */ + {"gi_frame", T_OBJECT, offsetof(PyGenObject, gi_frame), READONLY}, + {"gi_running", T_INT, offsetof(PyGenObject, gi_running), READONLY}, + {"gi_code", T_OBJECT, offsetof(PyGenObject, gi_code), READONLY}, + {NULL} /* Sentinel */ }; static PyMethodDef gen_methods[] = { - {"send",(PyCFunction)gen_send, METH_O, send_doc}, - {"throw",(PyCFunction)gen_throw, METH_VARARGS, throw_doc}, - {"close",(PyCFunction)gen_close, METH_NOARGS, close_doc}, - {NULL, NULL} /* Sentinel */ + {"send",(PyCFunction)gen_send, METH_O, send_doc}, + {"throw",(PyCFunction)gen_throw, METH_VARARGS, throw_doc}, + {"close",(PyCFunction)gen_close, METH_NOARGS, close_doc}, + {NULL, NULL} /* Sentinel */ }; PyTypeObject PyGen_Type = { - PyVarObject_HEAD_INIT(&PyType_Type, 0) - "generator", /* tp_name */ - sizeof(PyGenObject), /* tp_basicsize */ - 0, /* tp_itemsize */ - /* methods */ - (destructor)gen_dealloc, /* tp_dealloc */ - 0, /* tp_print */ - 0, /* tp_getattr */ - 0, /* tp_setattr */ - 0, /* tp_reserved */ - (reprfunc)gen_repr, /* 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)gen_traverse, /* tp_traverse */ - 0, /* tp_clear */ - 0, /* tp_richcompare */ - offsetof(PyGenObject, gi_weakreflist), /* tp_weaklistoffset */ - PyObject_SelfIter, /* tp_iter */ - (iternextfunc)gen_iternext, /* tp_iternext */ - gen_methods, /* tp_methods */ - gen_memberlist, /* tp_members */ - gen_getsetlist, /* tp_getset */ - 0, /* tp_base */ - 0, /* tp_dict */ - - 0, /* tp_descr_get */ - 0, /* tp_descr_set */ - 0, /* tp_dictoffset */ - 0, /* tp_init */ - 0, /* tp_alloc */ - 0, /* tp_new */ - 0, /* tp_free */ - 0, /* tp_is_gc */ - 0, /* tp_bases */ - 0, /* tp_mro */ - 0, /* tp_cache */ - 0, /* tp_subclasses */ - 0, /* tp_weaklist */ - gen_del, /* tp_del */ + PyVarObject_HEAD_INIT(&PyType_Type, 0) + "generator", /* tp_name */ + sizeof(PyGenObject), /* tp_basicsize */ + 0, /* tp_itemsize */ + /* methods */ + (destructor)gen_dealloc, /* tp_dealloc */ + 0, /* tp_print */ + 0, /* tp_getattr */ + 0, /* tp_setattr */ + 0, /* tp_reserved */ + (reprfunc)gen_repr, /* 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)gen_traverse, /* tp_traverse */ + 0, /* tp_clear */ + 0, /* tp_richcompare */ + offsetof(PyGenObject, gi_weakreflist), /* tp_weaklistoffset */ + PyObject_SelfIter, /* tp_iter */ + (iternextfunc)gen_iternext, /* tp_iternext */ + gen_methods, /* tp_methods */ + gen_memberlist, /* tp_members */ + gen_getsetlist, /* tp_getset */ + 0, /* tp_base */ + 0, /* tp_dict */ + + 0, /* tp_descr_get */ + 0, /* tp_descr_set */ + 0, /* tp_dictoffset */ + 0, /* tp_init */ + 0, /* tp_alloc */ + 0, /* tp_new */ + 0, /* tp_free */ + 0, /* tp_is_gc */ + 0, /* tp_bases */ + 0, /* tp_mro */ + 0, /* tp_cache */ + 0, /* tp_subclasses */ + 0, /* tp_weaklist */ + gen_del, /* tp_del */ }; PyObject * PyGen_New(PyFrameObject *f) { - PyGenObject *gen = PyObject_GC_New(PyGenObject, &PyGen_Type); - if (gen == NULL) { - Py_DECREF(f); - return NULL; - } - gen->gi_frame = f; - Py_INCREF(f->f_code); - gen->gi_code = (PyObject *)(f->f_code); - gen->gi_running = 0; - gen->gi_weakreflist = NULL; - _PyObject_GC_TRACK(gen); - return (PyObject *)gen; + PyGenObject *gen = PyObject_GC_New(PyGenObject, &PyGen_Type); + if (gen == NULL) { + Py_DECREF(f); + return NULL; + } + gen->gi_frame = f; + Py_INCREF(f->f_code); + gen->gi_code = (PyObject *)(f->f_code); + gen->gi_running = 0; + gen->gi_weakreflist = NULL; + _PyObject_GC_TRACK(gen); + return (PyObject *)gen; } int PyGen_NeedsFinalizing(PyGenObject *gen) { - int i; - PyFrameObject *f = gen->gi_frame; + int i; + PyFrameObject *f = gen->gi_frame; - if (f == NULL || f->f_stacktop == NULL || f->f_iblock <= 0) - return 0; /* no frame or empty blockstack == no finalization */ + if (f == NULL || f->f_stacktop == NULL || f->f_iblock <= 0) + return 0; /* no frame or empty blockstack == no finalization */ - /* Any block type besides a loop requires cleanup. */ - i = f->f_iblock; - while (--i >= 0) { - if (f->f_blockstack[i].b_type != SETUP_LOOP) - return 1; - } + /* Any block type besides a loop requires cleanup. */ + i = f->f_iblock; + while (--i >= 0) { + if (f->f_blockstack[i].b_type != SETUP_LOOP) + return 1; + } - /* No blocks except loops, it's safe to skip finalization. */ - return 0; + /* No blocks except loops, it's safe to skip finalization. */ + return 0; } Modified: python/branches/py3k/Objects/iterobject.c ============================================================================== --- python/branches/py3k/Objects/iterobject.c (original) +++ python/branches/py3k/Objects/iterobject.c Sun May 9 17:52:27 2010 @@ -3,230 +3,230 @@ #include "Python.h" typedef struct { - PyObject_HEAD - long it_index; - PyObject *it_seq; /* Set to NULL when iterator is exhausted */ + PyObject_HEAD + long it_index; + PyObject *it_seq; /* Set to NULL when iterator is exhausted */ } seqiterobject; PyObject * PySeqIter_New(PyObject *seq) { - seqiterobject *it; + seqiterobject *it; - if (!PySequence_Check(seq)) { - PyErr_BadInternalCall(); - return NULL; - } - it = PyObject_GC_New(seqiterobject, &PySeqIter_Type); - if (it == NULL) - return NULL; - it->it_index = 0; - Py_INCREF(seq); - it->it_seq = seq; - _PyObject_GC_TRACK(it); - return (PyObject *)it; + if (!PySequence_Check(seq)) { + PyErr_BadInternalCall(); + return NULL; + } + it = PyObject_GC_New(seqiterobject, &PySeqIter_Type); + if (it == NULL) + return NULL; + it->it_index = 0; + Py_INCREF(seq); + it->it_seq = seq; + _PyObject_GC_TRACK(it); + return (PyObject *)it; } static void iter_dealloc(seqiterobject *it) { - _PyObject_GC_UNTRACK(it); - Py_XDECREF(it->it_seq); - PyObject_GC_Del(it); + _PyObject_GC_UNTRACK(it); + Py_XDECREF(it->it_seq); + PyObject_GC_Del(it); } static int iter_traverse(seqiterobject *it, visitproc visit, void *arg) { - Py_VISIT(it->it_seq); - return 0; + Py_VISIT(it->it_seq); + return 0; } static PyObject * iter_iternext(PyObject *iterator) { - seqiterobject *it; - PyObject *seq; - PyObject *result; - - assert(PySeqIter_Check(iterator)); - it = (seqiterobject *)iterator; - seq = it->it_seq; - if (seq == NULL) - return NULL; - - result = PySequence_GetItem(seq, it->it_index); - if (result != NULL) { - it->it_index++; - return result; - } - if (PyErr_ExceptionMatches(PyExc_IndexError) || - PyErr_ExceptionMatches(PyExc_StopIteration)) - { - PyErr_Clear(); - Py_DECREF(seq); - it->it_seq = NULL; - } - return NULL; + seqiterobject *it; + PyObject *seq; + PyObject *result; + + assert(PySeqIter_Check(iterator)); + it = (seqiterobject *)iterator; + seq = it->it_seq; + if (seq == NULL) + return NULL; + + result = PySequence_GetItem(seq, it->it_index); + if (result != NULL) { + it->it_index++; + return result; + } + if (PyErr_ExceptionMatches(PyExc_IndexError) || + PyErr_ExceptionMatches(PyExc_StopIteration)) + { + PyErr_Clear(); + Py_DECREF(seq); + it->it_seq = NULL; + } + return NULL; } static PyObject * iter_len(seqiterobject *it) { - Py_ssize_t seqsize, len; + Py_ssize_t seqsize, len; - if (it->it_seq) { - seqsize = PySequence_Size(it->it_seq); - if (seqsize == -1) - return NULL; - len = seqsize - it->it_index; - if (len >= 0) - return PyLong_FromSsize_t(len); - } - return PyLong_FromLong(0); + if (it->it_seq) { + seqsize = PySequence_Size(it->it_seq); + if (seqsize == -1) + return NULL; + len = seqsize - it->it_index; + if (len >= 0) + return PyLong_FromSsize_t(len); + } + return PyLong_FromLong(0); } PyDoc_STRVAR(length_hint_doc, "Private method returning an estimate of len(list(it))."); static PyMethodDef seqiter_methods[] = { - {"__length_hint__", (PyCFunction)iter_len, METH_NOARGS, length_hint_doc}, - {NULL, NULL} /* sentinel */ + {"__length_hint__", (PyCFunction)iter_len, METH_NOARGS, length_hint_doc}, + {NULL, NULL} /* sentinel */ }; PyTypeObject PySeqIter_Type = { - PyVarObject_HEAD_INIT(&PyType_Type, 0) - "iterator", /* tp_name */ - sizeof(seqiterobject), /* tp_basicsize */ - 0, /* tp_itemsize */ - /* methods */ - (destructor)iter_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)iter_traverse, /* tp_traverse */ - 0, /* tp_clear */ - 0, /* tp_richcompare */ - 0, /* tp_weaklistoffset */ - PyObject_SelfIter, /* tp_iter */ - iter_iternext, /* tp_iternext */ - seqiter_methods, /* tp_methods */ - 0, /* tp_members */ + PyVarObject_HEAD_INIT(&PyType_Type, 0) + "iterator", /* tp_name */ + sizeof(seqiterobject), /* tp_basicsize */ + 0, /* tp_itemsize */ + /* methods */ + (destructor)iter_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)iter_traverse, /* tp_traverse */ + 0, /* tp_clear */ + 0, /* tp_richcompare */ + 0, /* tp_weaklistoffset */ + PyObject_SelfIter, /* tp_iter */ + iter_iternext, /* tp_iternext */ + seqiter_methods, /* tp_methods */ + 0, /* tp_members */ }; /* -------------------------------------- */ typedef struct { - PyObject_HEAD - PyObject *it_callable; /* Set to NULL when iterator is exhausted */ - PyObject *it_sentinel; /* Set to NULL when iterator is exhausted */ + PyObject_HEAD + PyObject *it_callable; /* Set to NULL when iterator is exhausted */ + PyObject *it_sentinel; /* Set to NULL when iterator is exhausted */ } calliterobject; PyObject * PyCallIter_New(PyObject *callable, PyObject *sentinel) { - calliterobject *it; - it = PyObject_GC_New(calliterobject, &PyCallIter_Type); - if (it == NULL) - return NULL; - Py_INCREF(callable); - it->it_callable = callable; - Py_INCREF(sentinel); - it->it_sentinel = sentinel; - _PyObject_GC_TRACK(it); - return (PyObject *)it; + calliterobject *it; + it = PyObject_GC_New(calliterobject, &PyCallIter_Type); + if (it == NULL) + return NULL; + Py_INCREF(callable); + it->it_callable = callable; + Py_INCREF(sentinel); + it->it_sentinel = sentinel; + _PyObject_GC_TRACK(it); + return (PyObject *)it; } static void calliter_dealloc(calliterobject *it) { - _PyObject_GC_UNTRACK(it); - Py_XDECREF(it->it_callable); - Py_XDECREF(it->it_sentinel); - PyObject_GC_Del(it); + _PyObject_GC_UNTRACK(it); + Py_XDECREF(it->it_callable); + Py_XDECREF(it->it_sentinel); + PyObject_GC_Del(it); } static int calliter_traverse(calliterobject *it, visitproc visit, void *arg) { - Py_VISIT(it->it_callable); - Py_VISIT(it->it_sentinel); - return 0; + Py_VISIT(it->it_callable); + Py_VISIT(it->it_sentinel); + return 0; } static PyObject * calliter_iternext(calliterobject *it) { - if (it->it_callable != NULL) { - PyObject *args = PyTuple_New(0); - PyObject *result; - if (args == NULL) - return NULL; - result = PyObject_Call(it->it_callable, args, NULL); - Py_DECREF(args); - if (result != NULL) { - int ok; - ok = PyObject_RichCompareBool(result, - it->it_sentinel, - Py_EQ); - if (ok == 0) - return result; /* Common case, fast path */ - Py_DECREF(result); - if (ok > 0) { - Py_CLEAR(it->it_callable); - Py_CLEAR(it->it_sentinel); - } - } - else if (PyErr_ExceptionMatches(PyExc_StopIteration)) { - PyErr_Clear(); - Py_CLEAR(it->it_callable); - Py_CLEAR(it->it_sentinel); - } - } - return NULL; + if (it->it_callable != NULL) { + PyObject *args = PyTuple_New(0); + PyObject *result; + if (args == NULL) + return NULL; + result = PyObject_Call(it->it_callable, args, NULL); + Py_DECREF(args); + if (result != NULL) { + int ok; + ok = PyObject_RichCompareBool(result, + it->it_sentinel, + Py_EQ); + if (ok == 0) + return result; /* Common case, fast path */ + Py_DECREF(result); + if (ok > 0) { + Py_CLEAR(it->it_callable); + Py_CLEAR(it->it_sentinel); + } + } + else if (PyErr_ExceptionMatches(PyExc_StopIteration)) { + PyErr_Clear(); + Py_CLEAR(it->it_callable); + Py_CLEAR(it->it_sentinel); + } + } + return NULL; } PyTypeObject PyCallIter_Type = { - PyVarObject_HEAD_INIT(&PyType_Type, 0) - "callable_iterator", /* tp_name */ - sizeof(calliterobject), /* tp_basicsize */ - 0, /* tp_itemsize */ - /* methods */ - (destructor)calliter_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)calliter_traverse, /* tp_traverse */ - 0, /* tp_clear */ - 0, /* tp_richcompare */ - 0, /* tp_weaklistoffset */ - PyObject_SelfIter, /* tp_iter */ - (iternextfunc)calliter_iternext, /* tp_iternext */ - 0, /* tp_methods */ + PyVarObject_HEAD_INIT(&PyType_Type, 0) + "callable_iterator", /* tp_name */ + sizeof(calliterobject), /* tp_basicsize */ + 0, /* tp_itemsize */ + /* methods */ + (destructor)calliter_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)calliter_traverse, /* tp_traverse */ + 0, /* tp_clear */ + 0, /* tp_richcompare */ + 0, /* tp_weaklistoffset */ + PyObject_SelfIter, /* tp_iter */ + (iternextfunc)calliter_iternext, /* tp_iternext */ + 0, /* tp_methods */ }; Modified: python/branches/py3k/Objects/listobject.c ============================================================================== --- python/branches/py3k/Objects/listobject.c (original) +++ python/branches/py3k/Objects/listobject.c Sun May 9 17:52:27 2010 @@ -5,7 +5,7 @@ #ifdef STDC_HEADERS #include #else -#include /* For size_t */ +#include /* For size_t */ #endif /* Ensure ob_item has room for at least newsize elements, and set @@ -24,52 +24,52 @@ static int list_resize(PyListObject *self, Py_ssize_t newsize) { - PyObject **items; - size_t new_allocated; - Py_ssize_t allocated = self->allocated; - - /* Bypass realloc() when a previous overallocation is large enough - to accommodate the newsize. If the newsize falls lower than half - the allocated size, then proceed with the realloc() to shrink the list. - */ - if (allocated >= newsize && newsize >= (allocated >> 1)) { - assert(self->ob_item != NULL || newsize == 0); - Py_SIZE(self) = newsize; - return 0; - } - - /* This over-allocates proportional to the list size, making room - * for additional growth. The over-allocation is mild, but is - * enough to give linear-time amortized behavior over a long - * sequence of appends() in the presence of a poorly-performing - * system realloc(). - * The growth pattern is: 0, 4, 8, 16, 25, 35, 46, 58, 72, 88, ... - */ - new_allocated = (newsize >> 3) + (newsize < 9 ? 3 : 6); - - /* check for integer overflow */ - if (new_allocated > PY_SIZE_MAX - newsize) { - PyErr_NoMemory(); - return -1; - } else { - new_allocated += newsize; - } - - if (newsize == 0) - new_allocated = 0; - items = self->ob_item; - if (new_allocated <= ((~(size_t)0) / sizeof(PyObject *))) - PyMem_RESIZE(items, PyObject *, new_allocated); - else - items = NULL; - if (items == NULL) { - PyErr_NoMemory(); - return -1; - } - self->ob_item = items; - Py_SIZE(self) = newsize; - self->allocated = new_allocated; - return 0; + PyObject **items; + size_t new_allocated; + Py_ssize_t allocated = self->allocated; + + /* Bypass realloc() when a previous overallocation is large enough + to accommodate the newsize. If the newsize falls lower than half + the allocated size, then proceed with the realloc() to shrink the list. + */ + if (allocated >= newsize && newsize >= (allocated >> 1)) { + assert(self->ob_item != NULL || newsize == 0); + Py_SIZE(self) = newsize; + return 0; + } + + /* This over-allocates proportional to the list size, making room + * for additional growth. The over-allocation is mild, but is + * enough to give linear-time amortized behavior over a long + * sequence of appends() in the presence of a poorly-performing + * system realloc(). + * The growth pattern is: 0, 4, 8, 16, 25, 35, 46, 58, 72, 88, ... + */ + new_allocated = (newsize >> 3) + (newsize < 9 ? 3 : 6); + + /* check for integer overflow */ + if (new_allocated > PY_SIZE_MAX - newsize) { + PyErr_NoMemory(); + return -1; + } else { + new_allocated += newsize; + } + + if (newsize == 0) + new_allocated = 0; + items = self->ob_item; + if (new_allocated <= ((~(size_t)0) / sizeof(PyObject *))) + PyMem_RESIZE(items, PyObject *, new_allocated); + else + items = NULL; + if (items == NULL) { + PyErr_NoMemory(); + return -1; + } + self->ob_item = items; + Py_SIZE(self) = newsize; + self->allocated = new_allocated; + return 0; } /* Debug statistic to compare allocations with reuse through the free list */ @@ -81,12 +81,12 @@ static void show_alloc(void) { - fprintf(stderr, "List allocations: %" PY_FORMAT_SIZE_T "d\n", - count_alloc); - fprintf(stderr, "List reuse through freelist: %" PY_FORMAT_SIZE_T - "d\n", count_reuse); - fprintf(stderr, "%.2f%% reuse rate\n\n", - (100.0*count_reuse/(count_alloc+count_reuse))); + fprintf(stderr, "List allocations: %" PY_FORMAT_SIZE_T "d\n", + count_alloc); + fprintf(stderr, "List reuse through freelist: %" PY_FORMAT_SIZE_T + "d\n", count_reuse); + fprintf(stderr, "%.2f%% reuse rate\n\n", + (100.0*count_reuse/(count_alloc+count_reuse))); } #endif @@ -100,77 +100,77 @@ void PyList_Fini(void) { - PyListObject *op; + PyListObject *op; - while (numfree) { - op = free_list[--numfree]; - assert(PyList_CheckExact(op)); - PyObject_GC_Del(op); - } + while (numfree) { + op = free_list[--numfree]; + assert(PyList_CheckExact(op)); + PyObject_GC_Del(op); + } } PyObject * PyList_New(Py_ssize_t size) { - PyListObject *op; - size_t nbytes; + PyListObject *op; + size_t nbytes; #ifdef SHOW_ALLOC_COUNT - static int initialized = 0; - if (!initialized) { - Py_AtExit(show_alloc); - initialized = 1; - } + static int initialized = 0; + if (!initialized) { + Py_AtExit(show_alloc); + initialized = 1; + } #endif - if (size < 0) { - PyErr_BadInternalCall(); - return NULL; - } - /* Check for overflow without an actual overflow, - * which can cause compiler to optimise out */ - if ((size_t)size > PY_SIZE_MAX / sizeof(PyObject *)) - return PyErr_NoMemory(); - nbytes = size * sizeof(PyObject *); - if (numfree) { - numfree--; - op = free_list[numfree]; - _Py_NewReference((PyObject *)op); + if (size < 0) { + PyErr_BadInternalCall(); + return NULL; + } + /* Check for overflow without an actual overflow, + * which can cause compiler to optimise out */ + if ((size_t)size > PY_SIZE_MAX / sizeof(PyObject *)) + return PyErr_NoMemory(); + nbytes = size * sizeof(PyObject *); + if (numfree) { + numfree--; + op = free_list[numfree]; + _Py_NewReference((PyObject *)op); #ifdef SHOW_ALLOC_COUNT - count_reuse++; + count_reuse++; #endif - } else { - op = PyObject_GC_New(PyListObject, &PyList_Type); - if (op == NULL) - return NULL; + } else { + op = PyObject_GC_New(PyListObject, &PyList_Type); + if (op == NULL) + return NULL; #ifdef SHOW_ALLOC_COUNT - count_alloc++; + count_alloc++; #endif - } - if (size <= 0) - op->ob_item = NULL; - else { - op->ob_item = (PyObject **) PyMem_MALLOC(nbytes); - if (op->ob_item == NULL) { - Py_DECREF(op); - return PyErr_NoMemory(); - } - memset(op->ob_item, 0, nbytes); - } - Py_SIZE(op) = size; - op->allocated = size; - _PyObject_GC_TRACK(op); - return (PyObject *) op; + } + if (size <= 0) + op->ob_item = NULL; + else { + op->ob_item = (PyObject **) PyMem_MALLOC(nbytes); + if (op->ob_item == NULL) { + Py_DECREF(op); + return PyErr_NoMemory(); + } + memset(op->ob_item, 0, nbytes); + } + Py_SIZE(op) = size; + op->allocated = size; + _PyObject_GC_TRACK(op); + return (PyObject *) op; } Py_ssize_t PyList_Size(PyObject *op) { - if (!PyList_Check(op)) { - PyErr_BadInternalCall(); - return -1; - } - else - return Py_SIZE(op); + if (!PyList_Check(op)) { + PyErr_BadInternalCall(); + return -1; + } + else + return Py_SIZE(op); } static PyObject *indexerr = NULL; @@ -178,117 +178,117 @@ PyObject * PyList_GetItem(PyObject *op, Py_ssize_t i) { - if (!PyList_Check(op)) { - PyErr_BadInternalCall(); - return NULL; - } - if (i < 0 || i >= Py_SIZE(op)) { - if (indexerr == NULL) { - indexerr = PyUnicode_FromString( - "list index out of range"); - if (indexerr == NULL) - return NULL; - } - PyErr_SetObject(PyExc_IndexError, indexerr); - return NULL; - } - return ((PyListObject *)op) -> ob_item[i]; + if (!PyList_Check(op)) { + PyErr_BadInternalCall(); + return NULL; + } + if (i < 0 || i >= Py_SIZE(op)) { + if (indexerr == NULL) { + indexerr = PyUnicode_FromString( + "list index out of range"); + if (indexerr == NULL) + return NULL; + } + PyErr_SetObject(PyExc_IndexError, indexerr); + return NULL; + } + return ((PyListObject *)op) -> ob_item[i]; } int PyList_SetItem(register PyObject *op, register Py_ssize_t i, register PyObject *newitem) { - register PyObject *olditem; - register PyObject **p; - if (!PyList_Check(op)) { - Py_XDECREF(newitem); - PyErr_BadInternalCall(); - return -1; - } - if (i < 0 || i >= Py_SIZE(op)) { - Py_XDECREF(newitem); - PyErr_SetString(PyExc_IndexError, - "list assignment index out of range"); - return -1; - } - p = ((PyListObject *)op) -> ob_item + i; - olditem = *p; - *p = newitem; - Py_XDECREF(olditem); - return 0; + register PyObject *olditem; + register PyObject **p; + if (!PyList_Check(op)) { + Py_XDECREF(newitem); + PyErr_BadInternalCall(); + return -1; + } + if (i < 0 || i >= Py_SIZE(op)) { + Py_XDECREF(newitem); + PyErr_SetString(PyExc_IndexError, + "list assignment index out of range"); + return -1; + } + p = ((PyListObject *)op) -> ob_item + i; + olditem = *p; + *p = newitem; + Py_XDECREF(olditem); + return 0; } static int ins1(PyListObject *self, Py_ssize_t where, PyObject *v) { - Py_ssize_t i, n = Py_SIZE(self); - PyObject **items; - if (v == NULL) { - PyErr_BadInternalCall(); - return -1; - } - if (n == PY_SSIZE_T_MAX) { - PyErr_SetString(PyExc_OverflowError, - "cannot add more objects to list"); - return -1; - } - - if (list_resize(self, n+1) == -1) - return -1; - - if (where < 0) { - where += n; - if (where < 0) - where = 0; - } - if (where > n) - where = n; - items = self->ob_item; - for (i = n; --i >= where; ) - items[i+1] = items[i]; - Py_INCREF(v); - items[where] = v; - return 0; + Py_ssize_t i, n = Py_SIZE(self); + PyObject **items; + if (v == NULL) { + PyErr_BadInternalCall(); + return -1; + } + if (n == PY_SSIZE_T_MAX) { + PyErr_SetString(PyExc_OverflowError, + "cannot add more objects to list"); + return -1; + } + + if (list_resize(self, n+1) == -1) + return -1; + + if (where < 0) { + where += n; + if (where < 0) + where = 0; + } + if (where > n) + where = n; + items = self->ob_item; + for (i = n; --i >= where; ) + items[i+1] = items[i]; + Py_INCREF(v); + items[where] = v; + return 0; } int PyList_Insert(PyObject *op, Py_ssize_t where, PyObject *newitem) { - if (!PyList_Check(op)) { - PyErr_BadInternalCall(); - return -1; - } - return ins1((PyListObject *)op, where, newitem); + if (!PyList_Check(op)) { + PyErr_BadInternalCall(); + return -1; + } + return ins1((PyListObject *)op, where, newitem); } static int app1(PyListObject *self, PyObject *v) { - Py_ssize_t n = PyList_GET_SIZE(self); + Py_ssize_t n = PyList_GET_SIZE(self); - assert (v != NULL); - if (n == PY_SSIZE_T_MAX) { - PyErr_SetString(PyExc_OverflowError, - "cannot add more objects to list"); - return -1; - } - - if (list_resize(self, n+1) == -1) - return -1; - - Py_INCREF(v); - PyList_SET_ITEM(self, n, v); - return 0; + assert (v != NULL); + if (n == PY_SSIZE_T_MAX) { + PyErr_SetString(PyExc_OverflowError, + "cannot add more objects to list"); + return -1; + } + + if (list_resize(self, n+1) == -1) + return -1; + + Py_INCREF(v); + PyList_SET_ITEM(self, n, v); + return 0; } int PyList_Append(PyObject *op, PyObject *newitem) { - if (PyList_Check(op) && (newitem != NULL)) - return app1((PyListObject *)op, newitem); - PyErr_BadInternalCall(); - return -1; + if (PyList_Check(op) && (newitem != NULL)) + return app1((PyListObject *)op, newitem); + PyErr_BadInternalCall(); + return -1; } /* Methods */ @@ -296,271 +296,271 @@ static void list_dealloc(PyListObject *op) { - Py_ssize_t i; - PyObject_GC_UnTrack(op); - Py_TRASHCAN_SAFE_BEGIN(op) - if (op->ob_item != NULL) { - /* Do it backwards, for Christian Tismer. - There's a simple test case where somehow this reduces - thrashing when a *very* large list is created and - immediately deleted. */ - i = Py_SIZE(op); - while (--i >= 0) { - Py_XDECREF(op->ob_item[i]); - } - PyMem_FREE(op->ob_item); - } - if (numfree < PyList_MAXFREELIST && PyList_CheckExact(op)) - free_list[numfree++] = op; - else - Py_TYPE(op)->tp_free((PyObject *)op); - Py_TRASHCAN_SAFE_END(op) + Py_ssize_t i; + PyObject_GC_UnTrack(op); + Py_TRASHCAN_SAFE_BEGIN(op) + if (op->ob_item != NULL) { + /* Do it backwards, for Christian Tismer. + There's a simple test case where somehow this reduces + thrashing when a *very* large list is created and + immediately deleted. */ + i = Py_SIZE(op); + while (--i >= 0) { + Py_XDECREF(op->ob_item[i]); + } + PyMem_FREE(op->ob_item); + } + if (numfree < PyList_MAXFREELIST && PyList_CheckExact(op)) + free_list[numfree++] = op; + else + Py_TYPE(op)->tp_free((PyObject *)op); + Py_TRASHCAN_SAFE_END(op) } static PyObject * list_repr(PyListObject *v) { - Py_ssize_t i; - PyObject *s, *temp; - PyObject *pieces = NULL, *result = NULL; - - i = Py_ReprEnter((PyObject*)v); - if (i != 0) { - return i > 0 ? PyUnicode_FromString("[...]") : NULL; - } - - if (Py_SIZE(v) == 0) { - result = PyUnicode_FromString("[]"); - goto Done; - } - - pieces = PyList_New(0); - if (pieces == NULL) - goto Done; - - /* Do repr() on each element. Note that this may mutate the list, - so must refetch the list size on each iteration. */ - for (i = 0; i < Py_SIZE(v); ++i) { - int status; - if (Py_EnterRecursiveCall(" while getting the repr of a list")) - goto Done; - s = PyObject_Repr(v->ob_item[i]); - Py_LeaveRecursiveCall(); - if (s == NULL) - goto Done; - status = PyList_Append(pieces, s); - Py_DECREF(s); /* append created a new ref */ - if (status < 0) - goto Done; - } - - /* Add "[]" decorations to the first and last items. */ - assert(PyList_GET_SIZE(pieces) > 0); - s = PyUnicode_FromString("["); - if (s == NULL) - goto Done; - temp = PyList_GET_ITEM(pieces, 0); - PyUnicode_AppendAndDel(&s, temp); - PyList_SET_ITEM(pieces, 0, s); - if (s == NULL) - goto Done; - - s = PyUnicode_FromString("]"); - if (s == NULL) - goto Done; - temp = PyList_GET_ITEM(pieces, PyList_GET_SIZE(pieces) - 1); - PyUnicode_AppendAndDel(&temp, s); - PyList_SET_ITEM(pieces, PyList_GET_SIZE(pieces) - 1, temp); - if (temp == NULL) - goto Done; - - /* Paste them all together with ", " between. */ - s = PyUnicode_FromString(", "); - if (s == NULL) - goto Done; - result = PyUnicode_Join(s, pieces); - Py_DECREF(s); + Py_ssize_t i; + PyObject *s, *temp; + PyObject *pieces = NULL, *result = NULL; + + i = Py_ReprEnter((PyObject*)v); + if (i != 0) { + return i > 0 ? PyUnicode_FromString("[...]") : NULL; + } + + if (Py_SIZE(v) == 0) { + result = PyUnicode_FromString("[]"); + goto Done; + } + + pieces = PyList_New(0); + if (pieces == NULL) + goto Done; + + /* Do repr() on each element. Note that this may mutate the list, + so must refetch the list size on each iteration. */ + for (i = 0; i < Py_SIZE(v); ++i) { + int status; + if (Py_EnterRecursiveCall(" while getting the repr of a list")) + goto Done; + s = PyObject_Repr(v->ob_item[i]); + Py_LeaveRecursiveCall(); + if (s == NULL) + goto Done; + status = PyList_Append(pieces, s); + Py_DECREF(s); /* append created a new ref */ + if (status < 0) + goto Done; + } + + /* Add "[]" decorations to the first and last items. */ + assert(PyList_GET_SIZE(pieces) > 0); + s = PyUnicode_FromString("["); + if (s == NULL) + goto Done; + temp = PyList_GET_ITEM(pieces, 0); + PyUnicode_AppendAndDel(&s, temp); + PyList_SET_ITEM(pieces, 0, s); + if (s == NULL) + goto Done; + + s = PyUnicode_FromString("]"); + if (s == NULL) + goto Done; + temp = PyList_GET_ITEM(pieces, PyList_GET_SIZE(pieces) - 1); + PyUnicode_AppendAndDel(&temp, s); + PyList_SET_ITEM(pieces, PyList_GET_SIZE(pieces) - 1, temp); + if (temp == NULL) + goto Done; + + /* Paste them all together with ", " between. */ + s = PyUnicode_FromString(", "); + if (s == NULL) + goto Done; + result = PyUnicode_Join(s, pieces); + Py_DECREF(s); Done: - Py_XDECREF(pieces); - Py_ReprLeave((PyObject *)v); - return result; + Py_XDECREF(pieces); + Py_ReprLeave((PyObject *)v); + return result; } static Py_ssize_t list_length(PyListObject *a) { - return Py_SIZE(a); + return Py_SIZE(a); } static int list_contains(PyListObject *a, PyObject *el) { - Py_ssize_t i; - int cmp; + Py_ssize_t i; + int cmp; - for (i = 0, cmp = 0 ; cmp == 0 && i < Py_SIZE(a); ++i) - cmp = PyObject_RichCompareBool(el, PyList_GET_ITEM(a, i), - Py_EQ); - return cmp; + for (i = 0, cmp = 0 ; cmp == 0 && i < Py_SIZE(a); ++i) + cmp = PyObject_RichCompareBool(el, PyList_GET_ITEM(a, i), + Py_EQ); + return cmp; } static PyObject * list_item(PyListObject *a, Py_ssize_t i) { - if (i < 0 || i >= Py_SIZE(a)) { - if (indexerr == NULL) { - indexerr = PyUnicode_FromString( - "list index out of range"); - if (indexerr == NULL) - return NULL; - } - PyErr_SetObject(PyExc_IndexError, indexerr); - return NULL; - } - Py_INCREF(a->ob_item[i]); - return a->ob_item[i]; + if (i < 0 || i >= Py_SIZE(a)) { + if (indexerr == NULL) { + indexerr = PyUnicode_FromString( + "list index out of range"); + if (indexerr == NULL) + return NULL; + } + PyErr_SetObject(PyExc_IndexError, indexerr); + return NULL; + } + Py_INCREF(a->ob_item[i]); + return a->ob_item[i]; } static PyObject * list_slice(PyListObject *a, Py_ssize_t ilow, Py_ssize_t ihigh) { - PyListObject *np; - PyObject **src, **dest; - Py_ssize_t i, len; - if (ilow < 0) - ilow = 0; - else if (ilow > Py_SIZE(a)) - ilow = Py_SIZE(a); - if (ihigh < ilow) - ihigh = ilow; - else if (ihigh > Py_SIZE(a)) - ihigh = Py_SIZE(a); - len = ihigh - ilow; - np = (PyListObject *) PyList_New(len); - if (np == NULL) - return NULL; - - src = a->ob_item + ilow; - dest = np->ob_item; - for (i = 0; i < len; i++) { - PyObject *v = src[i]; - Py_INCREF(v); - dest[i] = v; - } - return (PyObject *)np; + PyListObject *np; + PyObject **src, **dest; + Py_ssize_t i, len; + if (ilow < 0) + ilow = 0; + else if (ilow > Py_SIZE(a)) + ilow = Py_SIZE(a); + if (ihigh < ilow) + ihigh = ilow; + else if (ihigh > Py_SIZE(a)) + ihigh = Py_SIZE(a); + len = ihigh - ilow; + np = (PyListObject *) PyList_New(len); + if (np == NULL) + return NULL; + + src = a->ob_item + ilow; + dest = np->ob_item; + for (i = 0; i < len; i++) { + PyObject *v = src[i]; + Py_INCREF(v); + dest[i] = v; + } + return (PyObject *)np; } PyObject * PyList_GetSlice(PyObject *a, Py_ssize_t ilow, Py_ssize_t ihigh) { - if (!PyList_Check(a)) { - PyErr_BadInternalCall(); - return NULL; - } - return list_slice((PyListObject *)a, ilow, ihigh); + if (!PyList_Check(a)) { + PyErr_BadInternalCall(); + return NULL; + } + return list_slice((PyListObject *)a, ilow, ihigh); } static PyObject * list_concat(PyListObject *a, PyObject *bb) { - Py_ssize_t size; - Py_ssize_t i; - PyObject **src, **dest; - PyListObject *np; - if (!PyList_Check(bb)) { - PyErr_Format(PyExc_TypeError, - "can only concatenate list (not \"%.200s\") to list", - bb->ob_type->tp_name); - return NULL; - } + Py_ssize_t size; + Py_ssize_t i; + PyObject **src, **dest; + PyListObject *np; + if (!PyList_Check(bb)) { + PyErr_Format(PyExc_TypeError, + "can only concatenate list (not \"%.200s\") to list", + bb->ob_type->tp_name); + return NULL; + } #define b ((PyListObject *)bb) - size = Py_SIZE(a) + Py_SIZE(b); - if (size < 0) - return PyErr_NoMemory(); - np = (PyListObject *) PyList_New(size); - if (np == NULL) { - return NULL; - } - src = a->ob_item; - dest = np->ob_item; - for (i = 0; i < Py_SIZE(a); i++) { - PyObject *v = src[i]; - Py_INCREF(v); - dest[i] = v; - } - src = b->ob_item; - dest = np->ob_item + Py_SIZE(a); - for (i = 0; i < Py_SIZE(b); i++) { - PyObject *v = src[i]; - Py_INCREF(v); - dest[i] = v; - } - return (PyObject *)np; + size = Py_SIZE(a) + Py_SIZE(b); + if (size < 0) + return PyErr_NoMemory(); + np = (PyListObject *) PyList_New(size); + if (np == NULL) { + return NULL; + } + src = a->ob_item; + dest = np->ob_item; + for (i = 0; i < Py_SIZE(a); i++) { + PyObject *v = src[i]; + Py_INCREF(v); + dest[i] = v; + } + src = b->ob_item; + dest = np->ob_item + Py_SIZE(a); + for (i = 0; i < Py_SIZE(b); i++) { + PyObject *v = src[i]; + Py_INCREF(v); + dest[i] = v; + } + return (PyObject *)np; #undef b } static PyObject * list_repeat(PyListObject *a, Py_ssize_t n) { - Py_ssize_t i, j; - Py_ssize_t size; - PyListObject *np; - PyObject **p, **items; - PyObject *elem; - if (n < 0) - n = 0; - size = Py_SIZE(a) * n; - if (n && size/n != Py_SIZE(a)) - return PyErr_NoMemory(); - if (size == 0) - return PyList_New(0); - np = (PyListObject *) PyList_New(size); - if (np == NULL) - return NULL; - - items = np->ob_item; - if (Py_SIZE(a) == 1) { - elem = a->ob_item[0]; - for (i = 0; i < n; i++) { - items[i] = elem; - Py_INCREF(elem); - } - return (PyObject *) np; - } - p = np->ob_item; - items = a->ob_item; - for (i = 0; i < n; i++) { - for (j = 0; j < Py_SIZE(a); j++) { - *p = items[j]; - Py_INCREF(*p); - p++; - } - } - return (PyObject *) np; + Py_ssize_t i, j; + Py_ssize_t size; + PyListObject *np; + PyObject **p, **items; + PyObject *elem; + if (n < 0) + n = 0; + size = Py_SIZE(a) * n; + if (n && size/n != Py_SIZE(a)) + return PyErr_NoMemory(); + if (size == 0) + return PyList_New(0); + np = (PyListObject *) PyList_New(size); + if (np == NULL) + return NULL; + + items = np->ob_item; + if (Py_SIZE(a) == 1) { + elem = a->ob_item[0]; + for (i = 0; i < n; i++) { + items[i] = elem; + Py_INCREF(elem); + } + return (PyObject *) np; + } + p = np->ob_item; + items = a->ob_item; + for (i = 0; i < n; i++) { + for (j = 0; j < Py_SIZE(a); j++) { + *p = items[j]; + Py_INCREF(*p); + p++; + } + } + return (PyObject *) np; } static int list_clear(PyListObject *a) { - Py_ssize_t i; - PyObject **item = a->ob_item; - if (item != NULL) { - /* Because XDECREF can recursively invoke operations on - this list, we make it empty first. */ - i = Py_SIZE(a); - Py_SIZE(a) = 0; - a->ob_item = NULL; - a->allocated = 0; - while (--i >= 0) { - Py_XDECREF(item[i]); - } - PyMem_FREE(item); - } - /* Never fails; the return value can be ignored. - Note that there is no guarantee that the list is actually empty - at this point, because XDECREF may have populated it again! */ - return 0; + Py_ssize_t i; + PyObject **item = a->ob_item; + if (item != NULL) { + /* Because XDECREF can recursively invoke operations on + this list, we make it empty first. */ + i = Py_SIZE(a); + Py_SIZE(a) = 0; + a->ob_item = NULL; + a->allocated = 0; + while (--i >= 0) { + Py_XDECREF(item[i]); + } + PyMem_FREE(item); + } + /* Never fails; the return value can be ignored. + Note that there is no guarantee that the list is actually empty + at this point, because XDECREF may have populated it again! */ + return 0; } /* a[ilow:ihigh] = v if v != NULL. @@ -572,368 +572,368 @@ static int list_ass_slice(PyListObject *a, Py_ssize_t ilow, Py_ssize_t ihigh, PyObject *v) { - /* Because [X]DECREF can recursively invoke list operations on - this list, we must postpone all [X]DECREF activity until - after the list is back in its canonical shape. Therefore - we must allocate an additional array, 'recycle', into which - we temporarily copy the items that are deleted from the - list. :-( */ - PyObject *recycle_on_stack[8]; - PyObject **recycle = recycle_on_stack; /* will allocate more if needed */ - PyObject **item; - PyObject **vitem = NULL; - PyObject *v_as_SF = NULL; /* PySequence_Fast(v) */ - Py_ssize_t n; /* # of elements in replacement list */ - Py_ssize_t norig; /* # of elements in list getting replaced */ - Py_ssize_t d; /* Change in size */ - Py_ssize_t k; - size_t s; - int result = -1; /* guilty until proved innocent */ + /* Because [X]DECREF can recursively invoke list operations on + this list, we must postpone all [X]DECREF activity until + after the list is back in its canonical shape. Therefore + we must allocate an additional array, 'recycle', into which + we temporarily copy the items that are deleted from the + list. :-( */ + PyObject *recycle_on_stack[8]; + PyObject **recycle = recycle_on_stack; /* will allocate more if needed */ + PyObject **item; + PyObject **vitem = NULL; + PyObject *v_as_SF = NULL; /* PySequence_Fast(v) */ + Py_ssize_t n; /* # of elements in replacement list */ + Py_ssize_t norig; /* # of elements in list getting replaced */ + Py_ssize_t d; /* Change in size */ + Py_ssize_t k; + size_t s; + int result = -1; /* guilty until proved innocent */ #define b ((PyListObject *)v) - if (v == NULL) - n = 0; - else { - if (a == b) { - /* Special case "a[i:j] = a" -- copy b first */ - v = list_slice(b, 0, Py_SIZE(b)); - if (v == NULL) - return result; - result = list_ass_slice(a, ilow, ihigh, v); - Py_DECREF(v); - return result; - } - v_as_SF = PySequence_Fast(v, "can only assign an iterable"); - if(v_as_SF == NULL) - goto Error; - n = PySequence_Fast_GET_SIZE(v_as_SF); - vitem = PySequence_Fast_ITEMS(v_as_SF); - } - if (ilow < 0) - ilow = 0; - else if (ilow > Py_SIZE(a)) - ilow = Py_SIZE(a); - - if (ihigh < ilow) - ihigh = ilow; - else if (ihigh > Py_SIZE(a)) - ihigh = Py_SIZE(a); - - norig = ihigh - ilow; - assert(norig >= 0); - d = n - norig; - if (Py_SIZE(a) + d == 0) { - Py_XDECREF(v_as_SF); - return list_clear(a); - } - item = a->ob_item; - /* recycle the items that we are about to remove */ - s = norig * sizeof(PyObject *); - if (s > sizeof(recycle_on_stack)) { - recycle = (PyObject **)PyMem_MALLOC(s); - if (recycle == NULL) { - PyErr_NoMemory(); - goto Error; - } - } - memcpy(recycle, &item[ilow], s); - - if (d < 0) { /* Delete -d items */ - memmove(&item[ihigh+d], &item[ihigh], - (Py_SIZE(a) - ihigh)*sizeof(PyObject *)); - list_resize(a, Py_SIZE(a) + d); - item = a->ob_item; - } - else if (d > 0) { /* Insert d items */ - k = Py_SIZE(a); - if (list_resize(a, k+d) < 0) - goto Error; - item = a->ob_item; - memmove(&item[ihigh+d], &item[ihigh], - (k - ihigh)*sizeof(PyObject *)); - } - for (k = 0; k < n; k++, ilow++) { - PyObject *w = vitem[k]; - Py_XINCREF(w); - item[ilow] = w; - } - for (k = norig - 1; k >= 0; --k) - Py_XDECREF(recycle[k]); - result = 0; + if (v == NULL) + n = 0; + else { + if (a == b) { + /* Special case "a[i:j] = a" -- copy b first */ + v = list_slice(b, 0, Py_SIZE(b)); + if (v == NULL) + return result; + result = list_ass_slice(a, ilow, ihigh, v); + Py_DECREF(v); + return result; + } + v_as_SF = PySequence_Fast(v, "can only assign an iterable"); + if(v_as_SF == NULL) + goto Error; + n = PySequence_Fast_GET_SIZE(v_as_SF); + vitem = PySequence_Fast_ITEMS(v_as_SF); + } + if (ilow < 0) + ilow = 0; + else if (ilow > Py_SIZE(a)) + ilow = Py_SIZE(a); + + if (ihigh < ilow) + ihigh = ilow; + else if (ihigh > Py_SIZE(a)) + ihigh = Py_SIZE(a); + + norig = ihigh - ilow; + assert(norig >= 0); + d = n - norig; + if (Py_SIZE(a) + d == 0) { + Py_XDECREF(v_as_SF); + return list_clear(a); + } + item = a->ob_item; + /* recycle the items that we are about to remove */ + s = norig * sizeof(PyObject *); + if (s > sizeof(recycle_on_stack)) { + recycle = (PyObject **)PyMem_MALLOC(s); + if (recycle == NULL) { + PyErr_NoMemory(); + goto Error; + } + } + memcpy(recycle, &item[ilow], s); + + if (d < 0) { /* Delete -d items */ + memmove(&item[ihigh+d], &item[ihigh], + (Py_SIZE(a) - ihigh)*sizeof(PyObject *)); + list_resize(a, Py_SIZE(a) + d); + item = a->ob_item; + } + else if (d > 0) { /* Insert d items */ + k = Py_SIZE(a); + if (list_resize(a, k+d) < 0) + goto Error; + item = a->ob_item; + memmove(&item[ihigh+d], &item[ihigh], + (k - ihigh)*sizeof(PyObject *)); + } + for (k = 0; k < n; k++, ilow++) { + PyObject *w = vitem[k]; + Py_XINCREF(w); + item[ilow] = w; + } + for (k = norig - 1; k >= 0; --k) + Py_XDECREF(recycle[k]); + result = 0; Error: - if (recycle != recycle_on_stack) - PyMem_FREE(recycle); - Py_XDECREF(v_as_SF); - return result; + if (recycle != recycle_on_stack) + PyMem_FREE(recycle); + Py_XDECREF(v_as_SF); + return result; #undef b } int PyList_SetSlice(PyObject *a, Py_ssize_t ilow, Py_ssize_t ihigh, PyObject *v) { - if (!PyList_Check(a)) { - PyErr_BadInternalCall(); - return -1; - } - return list_ass_slice((PyListObject *)a, ilow, ihigh, v); + if (!PyList_Check(a)) { + PyErr_BadInternalCall(); + return -1; + } + return list_ass_slice((PyListObject *)a, ilow, ihigh, v); } static PyObject * list_inplace_repeat(PyListObject *self, Py_ssize_t n) { - PyObject **items; - Py_ssize_t size, i, j, p; + PyObject **items; + Py_ssize_t size, i, j, p; - size = PyList_GET_SIZE(self); - if (size == 0 || n == 1) { - Py_INCREF(self); - return (PyObject *)self; - } - - if (n < 1) { - (void)list_clear(self); - Py_INCREF(self); - return (PyObject *)self; - } - - if (size > PY_SSIZE_T_MAX / n) { - return PyErr_NoMemory(); - } - - if (list_resize(self, size*n) == -1) - return NULL; - - p = size; - items = self->ob_item; - for (i = 1; i < n; i++) { /* Start counting at 1, not 0 */ - for (j = 0; j < size; j++) { - PyObject *o = items[j]; - Py_INCREF(o); - items[p++] = o; - } - } - Py_INCREF(self); - return (PyObject *)self; + size = PyList_GET_SIZE(self); + if (size == 0 || n == 1) { + Py_INCREF(self); + return (PyObject *)self; + } + + if (n < 1) { + (void)list_clear(self); + Py_INCREF(self); + return (PyObject *)self; + } + + if (size > PY_SSIZE_T_MAX / n) { + return PyErr_NoMemory(); + } + + if (list_resize(self, size*n) == -1) + return NULL; + + p = size; + items = self->ob_item; + for (i = 1; i < n; i++) { /* Start counting at 1, not 0 */ + for (j = 0; j < size; j++) { + PyObject *o = items[j]; + Py_INCREF(o); + items[p++] = o; + } + } + Py_INCREF(self); + return (PyObject *)self; } static int list_ass_item(PyListObject *a, Py_ssize_t i, PyObject *v) { - PyObject *old_value; - if (i < 0 || i >= Py_SIZE(a)) { - PyErr_SetString(PyExc_IndexError, - "list assignment index out of range"); - return -1; - } - if (v == NULL) - return list_ass_slice(a, i, i+1, v); - Py_INCREF(v); - old_value = a->ob_item[i]; - a->ob_item[i] = v; - Py_DECREF(old_value); - return 0; + PyObject *old_value; + if (i < 0 || i >= Py_SIZE(a)) { + PyErr_SetString(PyExc_IndexError, + "list assignment index out of range"); + return -1; + } + if (v == NULL) + return list_ass_slice(a, i, i+1, v); + Py_INCREF(v); + old_value = a->ob_item[i]; + a->ob_item[i] = v; + Py_DECREF(old_value); + return 0; } static PyObject * listinsert(PyListObject *self, PyObject *args) { - Py_ssize_t i; - PyObject *v; - if (!PyArg_ParseTuple(args, "nO:insert", &i, &v)) - return NULL; - if (ins1(self, i, v) == 0) - Py_RETURN_NONE; - return NULL; + Py_ssize_t i; + PyObject *v; + if (!PyArg_ParseTuple(args, "nO:insert", &i, &v)) + return NULL; + if (ins1(self, i, v) == 0) + Py_RETURN_NONE; + return NULL; } static PyObject * listappend(PyListObject *self, PyObject *v) { - if (app1(self, v) == 0) - Py_RETURN_NONE; - return NULL; + if (app1(self, v) == 0) + Py_RETURN_NONE; + return NULL; } static PyObject * listextend(PyListObject *self, PyObject *b) { - PyObject *it; /* iter(v) */ - Py_ssize_t m; /* size of self */ - Py_ssize_t n; /* guess for size of b */ - Py_ssize_t mn; /* m + n */ - Py_ssize_t i; - PyObject *(*iternext)(PyObject *); - - /* Special cases: - 1) lists and tuples which can use PySequence_Fast ops - 2) extending self to self requires making a copy first - */ - if (PyList_CheckExact(b) || PyTuple_CheckExact(b) || (PyObject *)self == b) { - PyObject **src, **dest; - b = PySequence_Fast(b, "argument must be iterable"); - if (!b) - return NULL; - n = PySequence_Fast_GET_SIZE(b); - if (n == 0) { - /* short circuit when b is empty */ - Py_DECREF(b); - Py_RETURN_NONE; - } - m = Py_SIZE(self); - if (list_resize(self, m + n) == -1) { - Py_DECREF(b); - return NULL; - } - /* note that we may still have self == b here for the - * situation a.extend(a), but the following code works - * in that case too. Just make sure to resize self - * before calling PySequence_Fast_ITEMS. - */ - /* populate the end of self with b's items */ - src = PySequence_Fast_ITEMS(b); - dest = self->ob_item + m; - for (i = 0; i < n; i++) { - PyObject *o = src[i]; - Py_INCREF(o); - dest[i] = o; - } - Py_DECREF(b); - Py_RETURN_NONE; - } - - it = PyObject_GetIter(b); - if (it == NULL) - return NULL; - iternext = *it->ob_type->tp_iternext; - - /* Guess a result list size. */ - n = _PyObject_LengthHint(b, 8); - if (n == -1) { - Py_DECREF(it); - return NULL; - } - m = Py_SIZE(self); - mn = m + n; - if (mn >= m) { - /* Make room. */ - if (list_resize(self, mn) == -1) - goto error; - /* Make the list sane again. */ - Py_SIZE(self) = m; - } - /* Else m + n overflowed; on the chance that n lied, and there really - * is enough room, ignore it. If n was telling the truth, we'll - * eventually run out of memory during the loop. - */ - - /* Run iterator to exhaustion. */ - for (;;) { - PyObject *item = iternext(it); - if (item == NULL) { - if (PyErr_Occurred()) { - if (PyErr_ExceptionMatches(PyExc_StopIteration)) - PyErr_Clear(); - else - goto error; - } - break; - } - if (Py_SIZE(self) < self->allocated) { - /* steals ref */ - PyList_SET_ITEM(self, Py_SIZE(self), item); - ++Py_SIZE(self); - } - else { - int status = app1(self, item); - Py_DECREF(item); /* append creates a new ref */ - if (status < 0) - goto error; - } - } - - /* Cut back result list if initial guess was too large. */ - if (Py_SIZE(self) < self->allocated) - list_resize(self, Py_SIZE(self)); /* shrinking can't fail */ + PyObject *it; /* iter(v) */ + Py_ssize_t m; /* size of self */ + Py_ssize_t n; /* guess for size of b */ + Py_ssize_t mn; /* m + n */ + Py_ssize_t i; + PyObject *(*iternext)(PyObject *); + + /* Special cases: + 1) lists and tuples which can use PySequence_Fast ops + 2) extending self to self requires making a copy first + */ + if (PyList_CheckExact(b) || PyTuple_CheckExact(b) || (PyObject *)self == b) { + PyObject **src, **dest; + b = PySequence_Fast(b, "argument must be iterable"); + if (!b) + return NULL; + n = PySequence_Fast_GET_SIZE(b); + if (n == 0) { + /* short circuit when b is empty */ + Py_DECREF(b); + Py_RETURN_NONE; + } + m = Py_SIZE(self); + if (list_resize(self, m + n) == -1) { + Py_DECREF(b); + return NULL; + } + /* note that we may still have self == b here for the + * situation a.extend(a), but the following code works + * in that case too. Just make sure to resize self + * before calling PySequence_Fast_ITEMS. + */ + /* populate the end of self with b's items */ + src = PySequence_Fast_ITEMS(b); + dest = self->ob_item + m; + for (i = 0; i < n; i++) { + PyObject *o = src[i]; + Py_INCREF(o); + dest[i] = o; + } + Py_DECREF(b); + Py_RETURN_NONE; + } + + it = PyObject_GetIter(b); + if (it == NULL) + return NULL; + iternext = *it->ob_type->tp_iternext; + + /* Guess a result list size. */ + n = _PyObject_LengthHint(b, 8); + if (n == -1) { + Py_DECREF(it); + return NULL; + } + m = Py_SIZE(self); + mn = m + n; + if (mn >= m) { + /* Make room. */ + if (list_resize(self, mn) == -1) + goto error; + /* Make the list sane again. */ + Py_SIZE(self) = m; + } + /* Else m + n overflowed; on the chance that n lied, and there really + * is enough room, ignore it. If n was telling the truth, we'll + * eventually run out of memory during the loop. + */ + + /* Run iterator to exhaustion. */ + for (;;) { + PyObject *item = iternext(it); + if (item == NULL) { + if (PyErr_Occurred()) { + if (PyErr_ExceptionMatches(PyExc_StopIteration)) + PyErr_Clear(); + else + goto error; + } + break; + } + if (Py_SIZE(self) < self->allocated) { + /* steals ref */ + PyList_SET_ITEM(self, Py_SIZE(self), item); + ++Py_SIZE(self); + } + else { + int status = app1(self, item); + Py_DECREF(item); /* append creates a new ref */ + if (status < 0) + goto error; + } + } + + /* Cut back result list if initial guess was too large. */ + if (Py_SIZE(self) < self->allocated) + list_resize(self, Py_SIZE(self)); /* shrinking can't fail */ - Py_DECREF(it); - Py_RETURN_NONE; + Py_DECREF(it); + Py_RETURN_NONE; error: - Py_DECREF(it); - return NULL; + Py_DECREF(it); + return NULL; } PyObject * _PyList_Extend(PyListObject *self, PyObject *b) { - return listextend(self, b); + return listextend(self, b); } static PyObject * list_inplace_concat(PyListObject *self, PyObject *other) { - PyObject *result; + PyObject *result; - result = listextend(self, other); - if (result == NULL) - return result; - Py_DECREF(result); - Py_INCREF(self); - return (PyObject *)self; + result = listextend(self, other); + if (result == NULL) + return result; + Py_DECREF(result); + Py_INCREF(self); + return (PyObject *)self; } static PyObject * listpop(PyListObject *self, PyObject *args) { - Py_ssize_t i = -1; - PyObject *v; - int status; - - if (!PyArg_ParseTuple(args, "|n:pop", &i)) - return NULL; - - if (Py_SIZE(self) == 0) { - /* Special-case most common failure cause */ - PyErr_SetString(PyExc_IndexError, "pop from empty list"); - return NULL; - } - if (i < 0) - i += Py_SIZE(self); - if (i < 0 || i >= Py_SIZE(self)) { - PyErr_SetString(PyExc_IndexError, "pop index out of range"); - return NULL; - } - v = self->ob_item[i]; - if (i == Py_SIZE(self) - 1) { - status = list_resize(self, Py_SIZE(self) - 1); - assert(status >= 0); - return v; /* and v now owns the reference the list had */ - } - Py_INCREF(v); - status = list_ass_slice(self, i, i+1, (PyObject *)NULL); - assert(status >= 0); - /* Use status, so that in a release build compilers don't - * complain about the unused name. - */ - (void) status; + Py_ssize_t i = -1; + PyObject *v; + int status; + + if (!PyArg_ParseTuple(args, "|n:pop", &i)) + return NULL; + + if (Py_SIZE(self) == 0) { + /* Special-case most common failure cause */ + PyErr_SetString(PyExc_IndexError, "pop from empty list"); + return NULL; + } + if (i < 0) + i += Py_SIZE(self); + if (i < 0 || i >= Py_SIZE(self)) { + PyErr_SetString(PyExc_IndexError, "pop index out of range"); + return NULL; + } + v = self->ob_item[i]; + if (i == Py_SIZE(self) - 1) { + status = list_resize(self, Py_SIZE(self) - 1); + assert(status >= 0); + return v; /* and v now owns the reference the list had */ + } + Py_INCREF(v); + status = list_ass_slice(self, i, i+1, (PyObject *)NULL); + assert(status >= 0); + /* Use status, so that in a release build compilers don't + * complain about the unused name. + */ + (void) status; - return v; + return v; } /* Reverse a slice of a list in place, from lo up to (exclusive) hi. */ static void reverse_slice(PyObject **lo, PyObject **hi) { - assert(lo && hi); + assert(lo && hi); - --hi; - while (lo < hi) { - PyObject *t = *lo; - *lo = *hi; - *hi = t; - ++lo; - --hi; - } + --hi; + while (lo < hi) { + PyObject *t = *lo; + *lo = *hi; + *hi = t; + ++lo; + --hi; + } } /* Lots of code for an adaptive, stable, natural mergesort. There are many @@ -951,7 +951,7 @@ started. It makes more sense in context . X and Y are PyObject*s. */ #define IFLT(X, Y) if ((k = ISLT(X, Y)) < 0) goto fail; \ - if (k) + if (k) /* binarysort is the best method for sorting small arrays: it does few compares, but can do data movement quadratic in the number of @@ -967,48 +967,48 @@ static int binarysort(PyObject **lo, PyObject **hi, PyObject **start) { - register Py_ssize_t k; - register PyObject **l, **p, **r; - register PyObject *pivot; - - assert(lo <= start && start <= hi); - /* assert [lo, start) is sorted */ - if (lo == start) - ++start; - for (; start < hi; ++start) { - /* set l to where *start belongs */ - l = lo; - r = start; - pivot = *r; - /* Invariants: - * pivot >= all in [lo, l). - * pivot < all in [r, start). - * The second is vacuously true at the start. - */ - assert(l < r); - do { - p = l + ((r - l) >> 1); - IFLT(pivot, *p) - r = p; - else - l = p+1; - } while (l < r); - assert(l == r); - /* The invariants still hold, so pivot >= all in [lo, l) and - pivot < all in [l, start), so pivot belongs at l. Note - that if there are elements equal to pivot, l points to the - first slot after them -- that's why this sort is stable. - Slide over to make room. - Caution: using memmove is much slower under MSVC 5; - we're not usually moving many slots. */ - for (p = start; p > l; --p) - *p = *(p-1); - *l = pivot; - } - return 0; + register Py_ssize_t k; + register PyObject **l, **p, **r; + register PyObject *pivot; + + assert(lo <= start && start <= hi); + /* assert [lo, start) is sorted */ + if (lo == start) + ++start; + for (; start < hi; ++start) { + /* set l to where *start belongs */ + l = lo; + r = start; + pivot = *r; + /* Invariants: + * pivot >= all in [lo, l). + * pivot < all in [r, start). + * The second is vacuously true at the start. + */ + assert(l < r); + do { + p = l + ((r - l) >> 1); + IFLT(pivot, *p) + r = p; + else + l = p+1; + } while (l < r); + assert(l == r); + /* The invariants still hold, so pivot >= all in [lo, l) and + pivot < all in [l, start), so pivot belongs at l. Note + that if there are elements equal to pivot, l points to the + first slot after them -- that's why this sort is stable. + Slide over to make room. + Caution: using memmove is much slower under MSVC 5; + we're not usually moving many slots. */ + for (p = start; p > l; --p) + *p = *(p-1); + *l = pivot; + } + return 0; fail: - return -1; + return -1; } /* @@ -1032,35 +1032,35 @@ static Py_ssize_t count_run(PyObject **lo, PyObject **hi, int *descending) { - Py_ssize_t k; - Py_ssize_t n; + Py_ssize_t k; + Py_ssize_t n; - assert(lo < hi); - *descending = 0; - ++lo; - if (lo == hi) - return 1; - - n = 2; - IFLT(*lo, *(lo-1)) { - *descending = 1; - for (lo = lo+1; lo < hi; ++lo, ++n) { - IFLT(*lo, *(lo-1)) - ; - else - break; - } - } - else { - for (lo = lo+1; lo < hi; ++lo, ++n) { - IFLT(*lo, *(lo-1)) - break; - } - } + assert(lo < hi); + *descending = 0; + ++lo; + if (lo == hi) + return 1; + + n = 2; + IFLT(*lo, *(lo-1)) { + *descending = 1; + for (lo = lo+1; lo < hi; ++lo, ++n) { + IFLT(*lo, *(lo-1)) + ; + else + break; + } + } + else { + for (lo = lo+1; lo < hi; ++lo, ++n) { + IFLT(*lo, *(lo-1)) + break; + } + } - return n; + return n; fail: - return -1; + return -1; } /* @@ -1087,78 +1087,78 @@ static Py_ssize_t gallop_left(PyObject *key, PyObject **a, Py_ssize_t n, Py_ssize_t hint) { - Py_ssize_t ofs; - Py_ssize_t lastofs; - Py_ssize_t k; - - assert(key && a && n > 0 && hint >= 0 && hint < n); - - a += hint; - lastofs = 0; - ofs = 1; - IFLT(*a, key) { - /* a[hint] < key -- gallop right, until - * a[hint + lastofs] < key <= a[hint + ofs] - */ - const Py_ssize_t maxofs = n - hint; /* &a[n-1] is highest */ - while (ofs < maxofs) { - IFLT(a[ofs], key) { - lastofs = ofs; - ofs = (ofs << 1) + 1; - if (ofs <= 0) /* int overflow */ - ofs = maxofs; - } - else /* key <= a[hint + ofs] */ - break; - } - if (ofs > maxofs) - ofs = maxofs; - /* Translate back to offsets relative to &a[0]. */ - lastofs += hint; - ofs += hint; - } - else { - /* key <= a[hint] -- gallop left, until - * a[hint - ofs] < key <= a[hint - lastofs] - */ - const Py_ssize_t maxofs = hint + 1; /* &a[0] is lowest */ - while (ofs < maxofs) { - IFLT(*(a-ofs), key) - break; - /* key <= a[hint - ofs] */ - lastofs = ofs; - ofs = (ofs << 1) + 1; - if (ofs <= 0) /* int overflow */ - ofs = maxofs; - } - if (ofs > maxofs) - ofs = maxofs; - /* Translate back to positive offsets relative to &a[0]. */ - k = lastofs; - lastofs = hint - ofs; - ofs = hint - k; - } - a -= hint; - - assert(-1 <= lastofs && lastofs < ofs && ofs <= n); - /* Now a[lastofs] < key <= a[ofs], so key belongs somewhere to the - * right of lastofs but no farther right than ofs. Do a binary - * search, with invariant a[lastofs-1] < key <= a[ofs]. - */ - ++lastofs; - while (lastofs < ofs) { - Py_ssize_t m = lastofs + ((ofs - lastofs) >> 1); - - IFLT(a[m], key) - lastofs = m+1; /* a[m] < key */ - else - ofs = m; /* key <= a[m] */ - } - assert(lastofs == ofs); /* so a[ofs-1] < key <= a[ofs] */ - return ofs; + Py_ssize_t ofs; + Py_ssize_t lastofs; + Py_ssize_t k; + + assert(key && a && n > 0 && hint >= 0 && hint < n); + + a += hint; + lastofs = 0; + ofs = 1; + IFLT(*a, key) { + /* a[hint] < key -- gallop right, until + * a[hint + lastofs] < key <= a[hint + ofs] + */ + const Py_ssize_t maxofs = n - hint; /* &a[n-1] is highest */ + while (ofs < maxofs) { + IFLT(a[ofs], key) { + lastofs = ofs; + ofs = (ofs << 1) + 1; + if (ofs <= 0) /* int overflow */ + ofs = maxofs; + } + else /* key <= a[hint + ofs] */ + break; + } + if (ofs > maxofs) + ofs = maxofs; + /* Translate back to offsets relative to &a[0]. */ + lastofs += hint; + ofs += hint; + } + else { + /* key <= a[hint] -- gallop left, until + * a[hint - ofs] < key <= a[hint - lastofs] + */ + const Py_ssize_t maxofs = hint + 1; /* &a[0] is lowest */ + while (ofs < maxofs) { + IFLT(*(a-ofs), key) + break; + /* key <= a[hint - ofs] */ + lastofs = ofs; + ofs = (ofs << 1) + 1; + if (ofs <= 0) /* int overflow */ + ofs = maxofs; + } + if (ofs > maxofs) + ofs = maxofs; + /* Translate back to positive offsets relative to &a[0]. */ + k = lastofs; + lastofs = hint - ofs; + ofs = hint - k; + } + a -= hint; + + assert(-1 <= lastofs && lastofs < ofs && ofs <= n); + /* Now a[lastofs] < key <= a[ofs], so key belongs somewhere to the + * right of lastofs but no farther right than ofs. Do a binary + * search, with invariant a[lastofs-1] < key <= a[ofs]. + */ + ++lastofs; + while (lastofs < ofs) { + Py_ssize_t m = lastofs + ((ofs - lastofs) >> 1); + + IFLT(a[m], key) + lastofs = m+1; /* a[m] < key */ + else + ofs = m; /* key <= a[m] */ + } + assert(lastofs == ofs); /* so a[ofs-1] < key <= a[ofs] */ + return ofs; fail: - return -1; + return -1; } /* @@ -1178,78 +1178,78 @@ static Py_ssize_t gallop_right(PyObject *key, PyObject **a, Py_ssize_t n, Py_ssize_t hint) { - Py_ssize_t ofs; - Py_ssize_t lastofs; - Py_ssize_t k; - - assert(key && a && n > 0 && hint >= 0 && hint < n); - - a += hint; - lastofs = 0; - ofs = 1; - IFLT(key, *a) { - /* key < a[hint] -- gallop left, until - * a[hint - ofs] <= key < a[hint - lastofs] - */ - const Py_ssize_t maxofs = hint + 1; /* &a[0] is lowest */ - while (ofs < maxofs) { - IFLT(key, *(a-ofs)) { - lastofs = ofs; - ofs = (ofs << 1) + 1; - if (ofs <= 0) /* int overflow */ - ofs = maxofs; - } - else /* a[hint - ofs] <= key */ - break; - } - if (ofs > maxofs) - ofs = maxofs; - /* Translate back to positive offsets relative to &a[0]. */ - k = lastofs; - lastofs = hint - ofs; - ofs = hint - k; - } - else { - /* a[hint] <= key -- gallop right, until - * a[hint + lastofs] <= key < a[hint + ofs] - */ - const Py_ssize_t maxofs = n - hint; /* &a[n-1] is highest */ - while (ofs < maxofs) { - IFLT(key, a[ofs]) - break; - /* a[hint + ofs] <= key */ - lastofs = ofs; - ofs = (ofs << 1) + 1; - if (ofs <= 0) /* int overflow */ - ofs = maxofs; - } - if (ofs > maxofs) - ofs = maxofs; - /* Translate back to offsets relative to &a[0]. */ - lastofs += hint; - ofs += hint; - } - a -= hint; - - assert(-1 <= lastofs && lastofs < ofs && ofs <= n); - /* Now a[lastofs] <= key < a[ofs], so key belongs somewhere to the - * right of lastofs but no farther right than ofs. Do a binary - * search, with invariant a[lastofs-1] <= key < a[ofs]. - */ - ++lastofs; - while (lastofs < ofs) { - Py_ssize_t m = lastofs + ((ofs - lastofs) >> 1); - - IFLT(key, a[m]) - ofs = m; /* key < a[m] */ - else - lastofs = m+1; /* a[m] <= key */ - } - assert(lastofs == ofs); /* so a[ofs-1] <= key < a[ofs] */ - return ofs; + Py_ssize_t ofs; + Py_ssize_t lastofs; + Py_ssize_t k; + + assert(key && a && n > 0 && hint >= 0 && hint < n); + + a += hint; + lastofs = 0; + ofs = 1; + IFLT(key, *a) { + /* key < a[hint] -- gallop left, until + * a[hint - ofs] <= key < a[hint - lastofs] + */ + const Py_ssize_t maxofs = hint + 1; /* &a[0] is lowest */ + while (ofs < maxofs) { + IFLT(key, *(a-ofs)) { + lastofs = ofs; + ofs = (ofs << 1) + 1; + if (ofs <= 0) /* int overflow */ + ofs = maxofs; + } + else /* a[hint - ofs] <= key */ + break; + } + if (ofs > maxofs) + ofs = maxofs; + /* Translate back to positive offsets relative to &a[0]. */ + k = lastofs; + lastofs = hint - ofs; + ofs = hint - k; + } + else { + /* a[hint] <= key -- gallop right, until + * a[hint + lastofs] <= key < a[hint + ofs] + */ + const Py_ssize_t maxofs = n - hint; /* &a[n-1] is highest */ + while (ofs < maxofs) { + IFLT(key, a[ofs]) + break; + /* a[hint + ofs] <= key */ + lastofs = ofs; + ofs = (ofs << 1) + 1; + if (ofs <= 0) /* int overflow */ + ofs = maxofs; + } + if (ofs > maxofs) + ofs = maxofs; + /* Translate back to offsets relative to &a[0]. */ + lastofs += hint; + ofs += hint; + } + a -= hint; + + assert(-1 <= lastofs && lastofs < ofs && ofs <= n); + /* Now a[lastofs] <= key < a[ofs], so key belongs somewhere to the + * right of lastofs but no farther right than ofs. Do a binary + * search, with invariant a[lastofs-1] <= key < a[ofs]. + */ + ++lastofs; + while (lastofs < ofs) { + Py_ssize_t m = lastofs + ((ofs - lastofs) >> 1); + + IFLT(key, a[m]) + ofs = m; /* key < a[m] */ + else + lastofs = m+1; /* a[m] <= key */ + } + assert(lastofs == ofs); /* so a[ofs-1] <= key < a[ofs] */ + return ofs; fail: - return -1; + return -1; } /* The maximum number of entries in a MergeState's pending-runs stack. @@ -1272,48 +1272,48 @@ * a convenient way to pass state around among the helper functions. */ struct s_slice { - PyObject **base; - Py_ssize_t len; + PyObject **base; + Py_ssize_t len; }; typedef struct s_MergeState { - /* This controls when we get *into* galloping mode. It's initialized - * to MIN_GALLOP. merge_lo and merge_hi tend to nudge it higher for - * random data, and lower for highly structured data. - */ - Py_ssize_t min_gallop; - - /* 'a' is temp storage to help with merges. It contains room for - * alloced entries. - */ - PyObject **a; /* may point to temparray below */ - Py_ssize_t alloced; - - /* A stack of n pending runs yet to be merged. Run #i starts at - * address base[i] and extends for len[i] elements. It's always - * true (so long as the indices are in bounds) that - * - * pending[i].base + pending[i].len == pending[i+1].base - * - * so we could cut the storage for this, but it's a minor amount, - * and keeping all the info explicit simplifies the code. - */ - int n; - struct s_slice pending[MAX_MERGE_PENDING]; + /* This controls when we get *into* galloping mode. It's initialized + * to MIN_GALLOP. merge_lo and merge_hi tend to nudge it higher for + * random data, and lower for highly structured data. + */ + Py_ssize_t min_gallop; + + /* 'a' is temp storage to help with merges. It contains room for + * alloced entries. + */ + PyObject **a; /* may point to temparray below */ + Py_ssize_t alloced; + + /* A stack of n pending runs yet to be merged. Run #i starts at + * address base[i] and extends for len[i] elements. It's always + * true (so long as the indices are in bounds) that + * + * pending[i].base + pending[i].len == pending[i+1].base + * + * so we could cut the storage for this, but it's a minor amount, + * and keeping all the info explicit simplifies the code. + */ + int n; + struct s_slice pending[MAX_MERGE_PENDING]; - /* 'a' points to this when possible, rather than muck with malloc. */ - PyObject *temparray[MERGESTATE_TEMP_SIZE]; + /* 'a' points to this when possible, rather than muck with malloc. */ + PyObject *temparray[MERGESTATE_TEMP_SIZE]; } MergeState; /* Conceptually a MergeState's constructor. */ static void merge_init(MergeState *ms) { - assert(ms != NULL); - ms->a = ms->temparray; - ms->alloced = MERGESTATE_TEMP_SIZE; - ms->n = 0; - ms->min_gallop = MIN_GALLOP; + assert(ms != NULL); + ms->a = ms->temparray; + ms->alloced = MERGESTATE_TEMP_SIZE; + ms->n = 0; + ms->min_gallop = MIN_GALLOP; } /* Free all the temp memory owned by the MergeState. This must be called @@ -1323,11 +1323,11 @@ static void merge_freemem(MergeState *ms) { - assert(ms != NULL); - if (ms->a != ms->temparray) - PyMem_Free(ms->a); - ms->a = ms->temparray; - ms->alloced = MERGESTATE_TEMP_SIZE; + assert(ms != NULL); + if (ms->a != ms->temparray) + PyMem_Free(ms->a); + ms->a = ms->temparray; + ms->alloced = MERGESTATE_TEMP_SIZE; } /* Ensure enough temp memory for 'need' array slots is available. @@ -1336,28 +1336,28 @@ static int merge_getmem(MergeState *ms, Py_ssize_t need) { - assert(ms != NULL); - if (need <= ms->alloced) - return 0; - /* Don't realloc! That can cost cycles to copy the old data, but - * we don't care what's in the block. - */ - merge_freemem(ms); - if ((size_t)need > PY_SSIZE_T_MAX / sizeof(PyObject*)) { - PyErr_NoMemory(); - return -1; - } - ms->a = (PyObject **)PyMem_Malloc(need * sizeof(PyObject*)); - if (ms->a) { - ms->alloced = need; - return 0; - } - PyErr_NoMemory(); - merge_freemem(ms); /* reset to sane state */ - return -1; + assert(ms != NULL); + if (need <= ms->alloced) + return 0; + /* Don't realloc! That can cost cycles to copy the old data, but + * we don't care what's in the block. + */ + merge_freemem(ms); + if ((size_t)need > PY_SSIZE_T_MAX / sizeof(PyObject*)) { + PyErr_NoMemory(); + return -1; + } + ms->a = (PyObject **)PyMem_Malloc(need * sizeof(PyObject*)); + if (ms->a) { + ms->alloced = need; + return 0; + } + PyErr_NoMemory(); + merge_freemem(ms); /* reset to sane state */ + return -1; } -#define MERGE_GETMEM(MS, NEED) ((NEED) <= (MS)->alloced ? 0 : \ - merge_getmem(MS, NEED)) +#define MERGE_GETMEM(MS, NEED) ((NEED) <= (MS)->alloced ? 0 : \ + merge_getmem(MS, NEED)) /* Merge the na elements starting at pa with the nb elements starting at pb * in a stable way, in-place. na and nb must be > 0, and pa + na == pb. @@ -1369,125 +1369,125 @@ merge_lo(MergeState *ms, PyObject **pa, Py_ssize_t na, PyObject **pb, Py_ssize_t nb) { - Py_ssize_t k; - PyObject **dest; - int result = -1; /* guilty until proved innocent */ - Py_ssize_t min_gallop; - - assert(ms && pa && pb && na > 0 && nb > 0 && pa + na == pb); - if (MERGE_GETMEM(ms, na) < 0) - return -1; - memcpy(ms->a, pa, na * sizeof(PyObject*)); - dest = pa; - pa = ms->a; - - *dest++ = *pb++; - --nb; - if (nb == 0) - goto Succeed; - if (na == 1) - goto CopyB; - - min_gallop = ms->min_gallop; - for (;;) { - Py_ssize_t acount = 0; /* # of times A won in a row */ - Py_ssize_t bcount = 0; /* # of times B won in a row */ - - /* Do the straightforward thing until (if ever) one run - * appears to win consistently. - */ - for (;;) { - assert(na > 1 && nb > 0); - k = ISLT(*pb, *pa); - if (k) { - if (k < 0) - goto Fail; - *dest++ = *pb++; - ++bcount; - acount = 0; - --nb; - if (nb == 0) - goto Succeed; - if (bcount >= min_gallop) - break; - } - else { - *dest++ = *pa++; - ++acount; - bcount = 0; - --na; - if (na == 1) - goto CopyB; - if (acount >= min_gallop) - break; - } - } - - /* One run is winning so consistently that galloping may - * be a huge win. So try that, and continue galloping until - * (if ever) neither run appears to be winning consistently - * anymore. - */ - ++min_gallop; - do { - assert(na > 1 && nb > 0); - min_gallop -= min_gallop > 1; - ms->min_gallop = min_gallop; - k = gallop_right(*pb, pa, na, 0); - acount = k; - if (k) { - if (k < 0) - goto Fail; - memcpy(dest, pa, k * sizeof(PyObject *)); - dest += k; - pa += k; - na -= k; - if (na == 1) - goto CopyB; - /* na==0 is impossible now if the comparison - * function is consistent, but we can't assume - * that it is. - */ - if (na == 0) - goto Succeed; - } - *dest++ = *pb++; - --nb; - if (nb == 0) - goto Succeed; - - k = gallop_left(*pa, pb, nb, 0); - bcount = k; - if (k) { - if (k < 0) - goto Fail; - memmove(dest, pb, k * sizeof(PyObject *)); - dest += k; - pb += k; - nb -= k; - if (nb == 0) - goto Succeed; - } - *dest++ = *pa++; - --na; - if (na == 1) - goto CopyB; - } while (acount >= MIN_GALLOP || bcount >= MIN_GALLOP); - ++min_gallop; /* penalize it for leaving galloping mode */ - ms->min_gallop = min_gallop; - } + Py_ssize_t k; + PyObject **dest; + int result = -1; /* guilty until proved innocent */ + Py_ssize_t min_gallop; + + assert(ms && pa && pb && na > 0 && nb > 0 && pa + na == pb); + if (MERGE_GETMEM(ms, na) < 0) + return -1; + memcpy(ms->a, pa, na * sizeof(PyObject*)); + dest = pa; + pa = ms->a; + + *dest++ = *pb++; + --nb; + if (nb == 0) + goto Succeed; + if (na == 1) + goto CopyB; + + min_gallop = ms->min_gallop; + for (;;) { + Py_ssize_t acount = 0; /* # of times A won in a row */ + Py_ssize_t bcount = 0; /* # of times B won in a row */ + + /* Do the straightforward thing until (if ever) one run + * appears to win consistently. + */ + for (;;) { + assert(na > 1 && nb > 0); + k = ISLT(*pb, *pa); + if (k) { + if (k < 0) + goto Fail; + *dest++ = *pb++; + ++bcount; + acount = 0; + --nb; + if (nb == 0) + goto Succeed; + if (bcount >= min_gallop) + break; + } + else { + *dest++ = *pa++; + ++acount; + bcount = 0; + --na; + if (na == 1) + goto CopyB; + if (acount >= min_gallop) + break; + } + } + + /* One run is winning so consistently that galloping may + * be a huge win. So try that, and continue galloping until + * (if ever) neither run appears to be winning consistently + * anymore. + */ + ++min_gallop; + do { + assert(na > 1 && nb > 0); + min_gallop -= min_gallop > 1; + ms->min_gallop = min_gallop; + k = gallop_right(*pb, pa, na, 0); + acount = k; + if (k) { + if (k < 0) + goto Fail; + memcpy(dest, pa, k * sizeof(PyObject *)); + dest += k; + pa += k; + na -= k; + if (na == 1) + goto CopyB; + /* na==0 is impossible now if the comparison + * function is consistent, but we can't assume + * that it is. + */ + if (na == 0) + goto Succeed; + } + *dest++ = *pb++; + --nb; + if (nb == 0) + goto Succeed; + + k = gallop_left(*pa, pb, nb, 0); + bcount = k; + if (k) { + if (k < 0) + goto Fail; + memmove(dest, pb, k * sizeof(PyObject *)); + dest += k; + pb += k; + nb -= k; + if (nb == 0) + goto Succeed; + } + *dest++ = *pa++; + --na; + if (na == 1) + goto CopyB; + } while (acount >= MIN_GALLOP || bcount >= MIN_GALLOP); + ++min_gallop; /* penalize it for leaving galloping mode */ + ms->min_gallop = min_gallop; + } Succeed: - result = 0; + result = 0; Fail: - if (na) - memcpy(dest, pa, na * sizeof(PyObject*)); - return result; + if (na) + memcpy(dest, pa, na * sizeof(PyObject*)); + return result; CopyB: - assert(na == 1 && nb > 0); - /* The last element of pa belongs at the end of the merge. */ - memmove(dest, pb, nb * sizeof(PyObject *)); - dest[nb] = *pa; - return 0; + assert(na == 1 && nb > 0); + /* The last element of pa belongs at the end of the merge. */ + memmove(dest, pb, nb * sizeof(PyObject *)); + dest[nb] = *pa; + return 0; } /* Merge the na elements starting at pa with the nb elements starting at pb @@ -1499,134 +1499,134 @@ static Py_ssize_t merge_hi(MergeState *ms, PyObject **pa, Py_ssize_t na, PyObject **pb, Py_ssize_t nb) { - Py_ssize_t k; - PyObject **dest; - int result = -1; /* guilty until proved innocent */ - PyObject **basea; - PyObject **baseb; - Py_ssize_t min_gallop; - - assert(ms && pa && pb && na > 0 && nb > 0 && pa + na == pb); - if (MERGE_GETMEM(ms, nb) < 0) - return -1; - dest = pb + nb - 1; - memcpy(ms->a, pb, nb * sizeof(PyObject*)); - basea = pa; - baseb = ms->a; - pb = ms->a + nb - 1; - pa += na - 1; - - *dest-- = *pa--; - --na; - if (na == 0) - goto Succeed; - if (nb == 1) - goto CopyA; - - min_gallop = ms->min_gallop; - for (;;) { - Py_ssize_t acount = 0; /* # of times A won in a row */ - Py_ssize_t bcount = 0; /* # of times B won in a row */ - - /* Do the straightforward thing until (if ever) one run - * appears to win consistently. - */ - for (;;) { - assert(na > 0 && nb > 1); - k = ISLT(*pb, *pa); - if (k) { - if (k < 0) - goto Fail; - *dest-- = *pa--; - ++acount; - bcount = 0; - --na; - if (na == 0) - goto Succeed; - if (acount >= min_gallop) - break; - } - else { - *dest-- = *pb--; - ++bcount; - acount = 0; - --nb; - if (nb == 1) - goto CopyA; - if (bcount >= min_gallop) - break; - } - } - - /* One run is winning so consistently that galloping may - * be a huge win. So try that, and continue galloping until - * (if ever) neither run appears to be winning consistently - * anymore. - */ - ++min_gallop; - do { - assert(na > 0 && nb > 1); - min_gallop -= min_gallop > 1; - ms->min_gallop = min_gallop; - k = gallop_right(*pb, basea, na, na-1); - if (k < 0) - goto Fail; - k = na - k; - acount = k; - if (k) { - dest -= k; - pa -= k; - memmove(dest+1, pa+1, k * sizeof(PyObject *)); - na -= k; - if (na == 0) - goto Succeed; - } - *dest-- = *pb--; - --nb; - if (nb == 1) - goto CopyA; - - k = gallop_left(*pa, baseb, nb, nb-1); - if (k < 0) - goto Fail; - k = nb - k; - bcount = k; - if (k) { - dest -= k; - pb -= k; - memcpy(dest+1, pb+1, k * sizeof(PyObject *)); - nb -= k; - if (nb == 1) - goto CopyA; - /* nb==0 is impossible now if the comparison - * function is consistent, but we can't assume - * that it is. - */ - if (nb == 0) - goto Succeed; - } - *dest-- = *pa--; - --na; - if (na == 0) - goto Succeed; - } while (acount >= MIN_GALLOP || bcount >= MIN_GALLOP); - ++min_gallop; /* penalize it for leaving galloping mode */ - ms->min_gallop = min_gallop; - } + Py_ssize_t k; + PyObject **dest; + int result = -1; /* guilty until proved innocent */ + PyObject **basea; + PyObject **baseb; + Py_ssize_t min_gallop; + + assert(ms && pa && pb && na > 0 && nb > 0 && pa + na == pb); + if (MERGE_GETMEM(ms, nb) < 0) + return -1; + dest = pb + nb - 1; + memcpy(ms->a, pb, nb * sizeof(PyObject*)); + basea = pa; + baseb = ms->a; + pb = ms->a + nb - 1; + pa += na - 1; + + *dest-- = *pa--; + --na; + if (na == 0) + goto Succeed; + if (nb == 1) + goto CopyA; + + min_gallop = ms->min_gallop; + for (;;) { + Py_ssize_t acount = 0; /* # of times A won in a row */ + Py_ssize_t bcount = 0; /* # of times B won in a row */ + + /* Do the straightforward thing until (if ever) one run + * appears to win consistently. + */ + for (;;) { + assert(na > 0 && nb > 1); + k = ISLT(*pb, *pa); + if (k) { + if (k < 0) + goto Fail; + *dest-- = *pa--; + ++acount; + bcount = 0; + --na; + if (na == 0) + goto Succeed; + if (acount >= min_gallop) + break; + } + else { + *dest-- = *pb--; + ++bcount; + acount = 0; + --nb; + if (nb == 1) + goto CopyA; + if (bcount >= min_gallop) + break; + } + } + + /* One run is winning so consistently that galloping may + * be a huge win. So try that, and continue galloping until + * (if ever) neither run appears to be winning consistently + * anymore. + */ + ++min_gallop; + do { + assert(na > 0 && nb > 1); + min_gallop -= min_gallop > 1; + ms->min_gallop = min_gallop; + k = gallop_right(*pb, basea, na, na-1); + if (k < 0) + goto Fail; + k = na - k; + acount = k; + if (k) { + dest -= k; + pa -= k; + memmove(dest+1, pa+1, k * sizeof(PyObject *)); + na -= k; + if (na == 0) + goto Succeed; + } + *dest-- = *pb--; + --nb; + if (nb == 1) + goto CopyA; + + k = gallop_left(*pa, baseb, nb, nb-1); + if (k < 0) + goto Fail; + k = nb - k; + bcount = k; + if (k) { + dest -= k; + pb -= k; + memcpy(dest+1, pb+1, k * sizeof(PyObject *)); + nb -= k; + if (nb == 1) + goto CopyA; + /* nb==0 is impossible now if the comparison + * function is consistent, but we can't assume + * that it is. + */ + if (nb == 0) + goto Succeed; + } + *dest-- = *pa--; + --na; + if (na == 0) + goto Succeed; + } while (acount >= MIN_GALLOP || bcount >= MIN_GALLOP); + ++min_gallop; /* penalize it for leaving galloping mode */ + ms->min_gallop = min_gallop; + } Succeed: - result = 0; + result = 0; Fail: - if (nb) - memcpy(dest-(nb-1), baseb, nb * sizeof(PyObject*)); - return result; + if (nb) + memcpy(dest-(nb-1), baseb, nb * sizeof(PyObject*)); + return result; CopyA: - assert(nb == 1 && na > 0); - /* The first element of pb belongs at the front of the merge. */ - dest -= na; - pa -= na; - memmove(dest+1, pa+1, na * sizeof(PyObject *)); - *dest = *pb; - return 0; + assert(nb == 1 && na > 0); + /* The first element of pb belongs at the front of the merge. */ + dest -= na; + pa -= na; + memmove(dest+1, pa+1, na * sizeof(PyObject *)); + *dest = *pb; + return 0; } /* Merge the two runs at stack indices i and i+1. @@ -1635,56 +1635,56 @@ static Py_ssize_t merge_at(MergeState *ms, Py_ssize_t i) { - PyObject **pa, **pb; - Py_ssize_t na, nb; - Py_ssize_t k; - - assert(ms != NULL); - assert(ms->n >= 2); - assert(i >= 0); - assert(i == ms->n - 2 || i == ms->n - 3); - - pa = ms->pending[i].base; - na = ms->pending[i].len; - pb = ms->pending[i+1].base; - nb = ms->pending[i+1].len; - assert(na > 0 && nb > 0); - assert(pa + na == pb); - - /* Record the length of the combined runs; if i is the 3rd-last - * run now, also slide over the last run (which isn't involved - * in this merge). The current run i+1 goes away in any case. - */ - ms->pending[i].len = na + nb; - if (i == ms->n - 3) - ms->pending[i+1] = ms->pending[i+2]; - --ms->n; - - /* Where does b start in a? Elements in a before that can be - * ignored (already in place). - */ - k = gallop_right(*pb, pa, na, 0); - if (k < 0) - return -1; - pa += k; - na -= k; - if (na == 0) - return 0; - - /* Where does a end in b? Elements in b after that can be - * ignored (already in place). - */ - nb = gallop_left(pa[na-1], pb, nb, nb-1); - if (nb <= 0) - return nb; - - /* Merge what remains of the runs, using a temp array with - * min(na, nb) elements. - */ - if (na <= nb) - return merge_lo(ms, pa, na, pb, nb); - else - return merge_hi(ms, pa, na, pb, nb); + PyObject **pa, **pb; + Py_ssize_t na, nb; + Py_ssize_t k; + + assert(ms != NULL); + assert(ms->n >= 2); + assert(i >= 0); + assert(i == ms->n - 2 || i == ms->n - 3); + + pa = ms->pending[i].base; + na = ms->pending[i].len; + pb = ms->pending[i+1].base; + nb = ms->pending[i+1].len; + assert(na > 0 && nb > 0); + assert(pa + na == pb); + + /* Record the length of the combined runs; if i is the 3rd-last + * run now, also slide over the last run (which isn't involved + * in this merge). The current run i+1 goes away in any case. + */ + ms->pending[i].len = na + nb; + if (i == ms->n - 3) + ms->pending[i+1] = ms->pending[i+2]; + --ms->n; + + /* Where does b start in a? Elements in a before that can be + * ignored (already in place). + */ + k = gallop_right(*pb, pa, na, 0); + if (k < 0) + return -1; + pa += k; + na -= k; + if (na == 0) + return 0; + + /* Where does a end in b? Elements in b after that can be + * ignored (already in place). + */ + nb = gallop_left(pa[na-1], pb, nb, nb-1); + if (nb <= 0) + return nb; + + /* Merge what remains of the runs, using a temp array with + * min(na, nb) elements. + */ + if (na <= nb) + return merge_lo(ms, pa, na, pb, nb); + else + return merge_hi(ms, pa, na, pb, nb); } /* Examine the stack of runs waiting to be merged, merging adjacent runs @@ -1700,25 +1700,25 @@ static int merge_collapse(MergeState *ms) { - struct s_slice *p = ms->pending; + struct s_slice *p = ms->pending; - assert(ms); - while (ms->n > 1) { - Py_ssize_t n = ms->n - 2; - if (n > 0 && p[n-1].len <= p[n].len + p[n+1].len) { - if (p[n-1].len < p[n+1].len) - --n; - if (merge_at(ms, n) < 0) - return -1; - } - else if (p[n].len <= p[n+1].len) { - if (merge_at(ms, n) < 0) - return -1; - } - else - break; - } - return 0; + assert(ms); + while (ms->n > 1) { + Py_ssize_t n = ms->n - 2; + if (n > 0 && p[n-1].len <= p[n].len + p[n+1].len) { + if (p[n-1].len < p[n+1].len) + --n; + if (merge_at(ms, n) < 0) + return -1; + } + else if (p[n].len <= p[n+1].len) { + if (merge_at(ms, n) < 0) + return -1; + } + else + break; + } + return 0; } /* Regardless of invariants, merge all runs on the stack until only one @@ -1729,17 +1729,17 @@ static int merge_force_collapse(MergeState *ms) { - struct s_slice *p = ms->pending; + struct s_slice *p = ms->pending; - assert(ms); - while (ms->n > 1) { - Py_ssize_t n = ms->n - 2; - if (n > 0 && p[n-1].len < p[n+1].len) - --n; - if (merge_at(ms, n) < 0) - return -1; - } - return 0; + assert(ms); + while (ms->n > 1) { + Py_ssize_t n = ms->n - 2; + if (n > 0 && p[n-1].len < p[n+1].len) + --n; + if (merge_at(ms, n) < 0) + return -1; + } + return 0; } /* Compute a good value for the minimum run length; natural runs shorter @@ -1755,14 +1755,14 @@ static Py_ssize_t merge_compute_minrun(Py_ssize_t n) { - Py_ssize_t r = 0; /* becomes 1 if any 1 bits are shifted off */ + Py_ssize_t r = 0; /* becomes 1 if any 1 bits are shifted off */ - assert(n >= 0); - while (n >= 64) { - r |= n & 1; - n >>= 1; - } - return n + r; + assert(n >= 0); + while (n >= 64) { + r |= n & 1; + n >>= 1; + } + return n + r; } /* Special wrapper to support stable sorting using the decorate-sort-undecorate @@ -1773,9 +1773,9 @@ a full record. */ typedef struct { - PyObject_HEAD - PyObject *key; - PyObject *value; + PyObject_HEAD + PyObject *key; + PyObject *value; } sortwrapperobject; PyDoc_STRVAR(sortwrapper_doc, "Object wrapper with a custom sort key."); @@ -1785,51 +1785,51 @@ sortwrapper_dealloc(sortwrapperobject *); PyTypeObject PySortWrapper_Type = { - PyVarObject_HEAD_INIT(&PyType_Type, 0) - "sortwrapper", /* tp_name */ - sizeof(sortwrapperobject), /* tp_basicsize */ - 0, /* tp_itemsize */ - /* methods */ - (destructor)sortwrapper_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, /* tp_flags */ - sortwrapper_doc, /* tp_doc */ - 0, /* tp_traverse */ - 0, /* tp_clear */ - (richcmpfunc)sortwrapper_richcompare, /* tp_richcompare */ + PyVarObject_HEAD_INIT(&PyType_Type, 0) + "sortwrapper", /* tp_name */ + sizeof(sortwrapperobject), /* tp_basicsize */ + 0, /* tp_itemsize */ + /* methods */ + (destructor)sortwrapper_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, /* tp_flags */ + sortwrapper_doc, /* tp_doc */ + 0, /* tp_traverse */ + 0, /* tp_clear */ + (richcmpfunc)sortwrapper_richcompare, /* tp_richcompare */ }; static PyObject * sortwrapper_richcompare(sortwrapperobject *a, sortwrapperobject *b, int op) { - if (!PyObject_TypeCheck(b, &PySortWrapper_Type)) { - PyErr_SetString(PyExc_TypeError, - "expected a sortwrapperobject"); - return NULL; - } - return PyObject_RichCompare(a->key, b->key, op); + if (!PyObject_TypeCheck(b, &PySortWrapper_Type)) { + PyErr_SetString(PyExc_TypeError, + "expected a sortwrapperobject"); + return NULL; + } + return PyObject_RichCompare(a->key, b->key, op); } static void sortwrapper_dealloc(sortwrapperobject *so) { - Py_XDECREF(so->key); - Py_XDECREF(so->value); - PyObject_Del(so); + Py_XDECREF(so->key); + Py_XDECREF(so->value); + PyObject_Del(so); } /* Returns a new reference to a sortwrapper. @@ -1838,30 +1838,30 @@ static PyObject * build_sortwrapper(PyObject *key, PyObject *value) { - sortwrapperobject *so; + sortwrapperobject *so; - so = PyObject_New(sortwrapperobject, &PySortWrapper_Type); - if (so == NULL) - return NULL; - so->key = key; - so->value = value; - return (PyObject *)so; + so = PyObject_New(sortwrapperobject, &PySortWrapper_Type); + if (so == NULL) + return NULL; + so->key = key; + so->value = value; + return (PyObject *)so; } /* Returns a new reference to the value underlying the wrapper. */ static PyObject * sortwrapper_getvalue(PyObject *so) { - PyObject *value; + PyObject *value; - if (!PyObject_TypeCheck(so, &PySortWrapper_Type)) { - PyErr_SetString(PyExc_TypeError, - "expected a sortwrapperobject"); - return NULL; - } - value = ((sortwrapperobject *)so)->value; - Py_INCREF(value); - return value; + if (!PyObject_TypeCheck(so, &PySortWrapper_Type)) { + PyErr_SetString(PyExc_TypeError, + "expected a sortwrapperobject"); + return NULL; + } + value = ((sortwrapperobject *)so)->value; + Py_INCREF(value); + return value; } /* An adaptive, stable, natural mergesort. See listsort.txt. @@ -1872,163 +1872,163 @@ static PyObject * listsort(PyListObject *self, PyObject *args, PyObject *kwds) { - MergeState ms; - PyObject **lo, **hi; - Py_ssize_t nremaining; - Py_ssize_t minrun; - Py_ssize_t saved_ob_size, saved_allocated; - PyObject **saved_ob_item; - PyObject **final_ob_item; - PyObject *result = NULL; /* guilty until proved innocent */ - int reverse = 0; - PyObject *keyfunc = NULL; - Py_ssize_t i; - PyObject *key, *value, *kvpair; - static char *kwlist[] = {"key", "reverse", 0}; - - assert(self != NULL); - assert (PyList_Check(self)); - if (args != NULL) { - if (!PyArg_ParseTupleAndKeywords(args, kwds, "|Oi:sort", - kwlist, &keyfunc, &reverse)) - return NULL; - if (Py_SIZE(args) > 0) { - PyErr_SetString(PyExc_TypeError, - "must use keyword argument for key function"); - return NULL; - } - } - if (keyfunc == Py_None) - keyfunc = NULL; - - /* The list is temporarily made empty, so that mutations performed - * by comparison functions can't affect the slice of memory we're - * sorting (allowing mutations during sorting is a core-dump - * factory, since ob_item may change). - */ - saved_ob_size = Py_SIZE(self); - saved_ob_item = self->ob_item; - saved_allocated = self->allocated; - Py_SIZE(self) = 0; - self->ob_item = NULL; - self->allocated = -1; /* any operation will reset it to >= 0 */ - - if (keyfunc != NULL) { - for (i=0 ; i < saved_ob_size ; i++) { - value = saved_ob_item[i]; - key = PyObject_CallFunctionObjArgs(keyfunc, value, - NULL); - if (key == NULL) { - for (i=i-1 ; i>=0 ; i--) { - kvpair = saved_ob_item[i]; - value = sortwrapper_getvalue(kvpair); - saved_ob_item[i] = value; - Py_DECREF(kvpair); - } - goto dsu_fail; - } - kvpair = build_sortwrapper(key, value); - if (kvpair == NULL) - goto dsu_fail; - saved_ob_item[i] = kvpair; - } - } - - /* Reverse sort stability achieved by initially reversing the list, - applying a stable forward sort, then reversing the final result. */ - if (reverse && saved_ob_size > 1) - reverse_slice(saved_ob_item, saved_ob_item + saved_ob_size); - - merge_init(&ms); - - nremaining = saved_ob_size; - if (nremaining < 2) - goto succeed; - - /* March over the array once, left to right, finding natural runs, - * and extending short natural runs to minrun elements. - */ - lo = saved_ob_item; - hi = lo + nremaining; - minrun = merge_compute_minrun(nremaining); - do { - int descending; - Py_ssize_t n; - - /* Identify next run. */ - n = count_run(lo, hi, &descending); - if (n < 0) - goto fail; - if (descending) - reverse_slice(lo, lo + n); - /* If short, extend to min(minrun, nremaining). */ - if (n < minrun) { - const Py_ssize_t force = nremaining <= minrun ? - nremaining : minrun; - if (binarysort(lo, lo + force, lo + n) < 0) - goto fail; - n = force; - } - /* Push run onto pending-runs stack, and maybe merge. */ - assert(ms.n < MAX_MERGE_PENDING); - ms.pending[ms.n].base = lo; - ms.pending[ms.n].len = n; - ++ms.n; - if (merge_collapse(&ms) < 0) - goto fail; - /* Advance to find next run. */ - lo += n; - nremaining -= n; - } while (nremaining); - assert(lo == hi); - - if (merge_force_collapse(&ms) < 0) - goto fail; - assert(ms.n == 1); - assert(ms.pending[0].base == saved_ob_item); - assert(ms.pending[0].len == saved_ob_size); + MergeState ms; + PyObject **lo, **hi; + Py_ssize_t nremaining; + Py_ssize_t minrun; + Py_ssize_t saved_ob_size, saved_allocated; + PyObject **saved_ob_item; + PyObject **final_ob_item; + PyObject *result = NULL; /* guilty until proved innocent */ + int reverse = 0; + PyObject *keyfunc = NULL; + Py_ssize_t i; + PyObject *key, *value, *kvpair; + static char *kwlist[] = {"key", "reverse", 0}; + + assert(self != NULL); + assert (PyList_Check(self)); + if (args != NULL) { + if (!PyArg_ParseTupleAndKeywords(args, kwds, "|Oi:sort", + kwlist, &keyfunc, &reverse)) + return NULL; + if (Py_SIZE(args) > 0) { + PyErr_SetString(PyExc_TypeError, + "must use keyword argument for key function"); + return NULL; + } + } + if (keyfunc == Py_None) + keyfunc = NULL; + + /* The list is temporarily made empty, so that mutations performed + * by comparison functions can't affect the slice of memory we're + * sorting (allowing mutations during sorting is a core-dump + * factory, since ob_item may change). + */ + saved_ob_size = Py_SIZE(self); + saved_ob_item = self->ob_item; + saved_allocated = self->allocated; + Py_SIZE(self) = 0; + self->ob_item = NULL; + self->allocated = -1; /* any operation will reset it to >= 0 */ + + if (keyfunc != NULL) { + for (i=0 ; i < saved_ob_size ; i++) { + value = saved_ob_item[i]; + key = PyObject_CallFunctionObjArgs(keyfunc, value, + NULL); + if (key == NULL) { + for (i=i-1 ; i>=0 ; i--) { + kvpair = saved_ob_item[i]; + value = sortwrapper_getvalue(kvpair); + saved_ob_item[i] = value; + Py_DECREF(kvpair); + } + goto dsu_fail; + } + kvpair = build_sortwrapper(key, value); + if (kvpair == NULL) + goto dsu_fail; + saved_ob_item[i] = kvpair; + } + } + + /* Reverse sort stability achieved by initially reversing the list, + applying a stable forward sort, then reversing the final result. */ + if (reverse && saved_ob_size > 1) + reverse_slice(saved_ob_item, saved_ob_item + saved_ob_size); + + merge_init(&ms); + + nremaining = saved_ob_size; + if (nremaining < 2) + goto succeed; + + /* March over the array once, left to right, finding natural runs, + * and extending short natural runs to minrun elements. + */ + lo = saved_ob_item; + hi = lo + nremaining; + minrun = merge_compute_minrun(nremaining); + do { + int descending; + Py_ssize_t n; + + /* Identify next run. */ + n = count_run(lo, hi, &descending); + if (n < 0) + goto fail; + if (descending) + reverse_slice(lo, lo + n); + /* If short, extend to min(minrun, nremaining). */ + if (n < minrun) { + const Py_ssize_t force = nremaining <= minrun ? + nremaining : minrun; + if (binarysort(lo, lo + force, lo + n) < 0) + goto fail; + n = force; + } + /* Push run onto pending-runs stack, and maybe merge. */ + assert(ms.n < MAX_MERGE_PENDING); + ms.pending[ms.n].base = lo; + ms.pending[ms.n].len = n; + ++ms.n; + if (merge_collapse(&ms) < 0) + goto fail; + /* Advance to find next run. */ + lo += n; + nremaining -= n; + } while (nremaining); + assert(lo == hi); + + if (merge_force_collapse(&ms) < 0) + goto fail; + assert(ms.n == 1); + assert(ms.pending[0].base == saved_ob_item); + assert(ms.pending[0].len == saved_ob_size); succeed: - result = Py_None; + result = Py_None; fail: - if (keyfunc != NULL) { - for (i=0 ; i < saved_ob_size ; i++) { - kvpair = saved_ob_item[i]; - value = sortwrapper_getvalue(kvpair); - saved_ob_item[i] = value; - Py_DECREF(kvpair); - } - } - - if (self->allocated != -1 && result != NULL) { - /* The user mucked with the list during the sort, - * and we don't already have another error to report. - */ - PyErr_SetString(PyExc_ValueError, "list modified during sort"); - result = NULL; - } + if (keyfunc != NULL) { + for (i=0 ; i < saved_ob_size ; i++) { + kvpair = saved_ob_item[i]; + value = sortwrapper_getvalue(kvpair); + saved_ob_item[i] = value; + Py_DECREF(kvpair); + } + } + + if (self->allocated != -1 && result != NULL) { + /* The user mucked with the list during the sort, + * and we don't already have another error to report. + */ + PyErr_SetString(PyExc_ValueError, "list modified during sort"); + result = NULL; + } - if (reverse && saved_ob_size > 1) - reverse_slice(saved_ob_item, saved_ob_item + saved_ob_size); + if (reverse && saved_ob_size > 1) + reverse_slice(saved_ob_item, saved_ob_item + saved_ob_size); - merge_freemem(&ms); + merge_freemem(&ms); dsu_fail: - final_ob_item = self->ob_item; - i = Py_SIZE(self); - Py_SIZE(self) = saved_ob_size; - self->ob_item = saved_ob_item; - self->allocated = saved_allocated; - if (final_ob_item != NULL) { - /* we cannot use list_clear() for this because it does not - guarantee that the list is really empty when it returns */ - while (--i >= 0) { - Py_XDECREF(final_ob_item[i]); - } - PyMem_FREE(final_ob_item); - } - Py_XINCREF(result); - return result; + final_ob_item = self->ob_item; + i = Py_SIZE(self); + Py_SIZE(self) = saved_ob_size; + self->ob_item = saved_ob_item; + self->allocated = saved_allocated; + if (final_ob_item != NULL) { + /* we cannot use list_clear() for this because it does not + guarantee that the list is really empty when it returns */ + while (--i >= 0) { + Py_XDECREF(final_ob_item[i]); + } + PyMem_FREE(final_ob_item); + } + Py_XINCREF(result); + return result; } #undef IFLT #undef ISLT @@ -2036,262 +2036,262 @@ int PyList_Sort(PyObject *v) { - if (v == NULL || !PyList_Check(v)) { - PyErr_BadInternalCall(); - return -1; - } - v = listsort((PyListObject *)v, (PyObject *)NULL, (PyObject *)NULL); - if (v == NULL) - return -1; - Py_DECREF(v); - return 0; + if (v == NULL || !PyList_Check(v)) { + PyErr_BadInternalCall(); + return -1; + } + v = listsort((PyListObject *)v, (PyObject *)NULL, (PyObject *)NULL); + if (v == NULL) + return -1; + Py_DECREF(v); + return 0; } static PyObject * listreverse(PyListObject *self) { - if (Py_SIZE(self) > 1) - reverse_slice(self->ob_item, self->ob_item + Py_SIZE(self)); - Py_RETURN_NONE; + if (Py_SIZE(self) > 1) + reverse_slice(self->ob_item, self->ob_item + Py_SIZE(self)); + Py_RETURN_NONE; } int PyList_Reverse(PyObject *v) { - PyListObject *self = (PyListObject *)v; + PyListObject *self = (PyListObject *)v; - if (v == NULL || !PyList_Check(v)) { - PyErr_BadInternalCall(); - return -1; - } - if (Py_SIZE(self) > 1) - reverse_slice(self->ob_item, self->ob_item + Py_SIZE(self)); - return 0; + if (v == NULL || !PyList_Check(v)) { + PyErr_BadInternalCall(); + return -1; + } + if (Py_SIZE(self) > 1) + reverse_slice(self->ob_item, self->ob_item + Py_SIZE(self)); + return 0; } PyObject * PyList_AsTuple(PyObject *v) { - PyObject *w; - PyObject **p, **q; - Py_ssize_t n; - if (v == NULL || !PyList_Check(v)) { - PyErr_BadInternalCall(); - return NULL; - } - n = Py_SIZE(v); - w = PyTuple_New(n); - if (w == NULL) - return NULL; - p = ((PyTupleObject *)w)->ob_item; - q = ((PyListObject *)v)->ob_item; - while (--n >= 0) { - Py_INCREF(*q); - *p = *q; - p++; - q++; - } - return w; + PyObject *w; + PyObject **p, **q; + Py_ssize_t n; + if (v == NULL || !PyList_Check(v)) { + PyErr_BadInternalCall(); + return NULL; + } + n = Py_SIZE(v); + w = PyTuple_New(n); + if (w == NULL) + return NULL; + p = ((PyTupleObject *)w)->ob_item; + q = ((PyListObject *)v)->ob_item; + while (--n >= 0) { + Py_INCREF(*q); + *p = *q; + p++; + q++; + } + return w; } static PyObject * listindex(PyListObject *self, PyObject *args) { - Py_ssize_t i, start=0, stop=Py_SIZE(self); - PyObject *v, *format_tuple, *err_string; - static PyObject *err_format = NULL; - - if (!PyArg_ParseTuple(args, "O|O&O&:index", &v, - _PyEval_SliceIndex, &start, - _PyEval_SliceIndex, &stop)) - return NULL; - if (start < 0) { - start += Py_SIZE(self); - if (start < 0) - start = 0; - } - if (stop < 0) { - stop += Py_SIZE(self); - if (stop < 0) - stop = 0; - } - for (i = start; i < stop && i < Py_SIZE(self); i++) { - int cmp = PyObject_RichCompareBool(self->ob_item[i], v, Py_EQ); - if (cmp > 0) - return PyLong_FromSsize_t(i); - else if (cmp < 0) - return NULL; - } - if (err_format == NULL) { - err_format = PyUnicode_FromString("%r is not in list"); - if (err_format == NULL) - return NULL; - } - format_tuple = PyTuple_Pack(1, v); - if (format_tuple == NULL) - return NULL; - err_string = PyUnicode_Format(err_format, format_tuple); - Py_DECREF(format_tuple); - if (err_string == NULL) - return NULL; - PyErr_SetObject(PyExc_ValueError, err_string); - Py_DECREF(err_string); - return NULL; + Py_ssize_t i, start=0, stop=Py_SIZE(self); + PyObject *v, *format_tuple, *err_string; + static PyObject *err_format = NULL; + + if (!PyArg_ParseTuple(args, "O|O&O&:index", &v, + _PyEval_SliceIndex, &start, + _PyEval_SliceIndex, &stop)) + return NULL; + if (start < 0) { + start += Py_SIZE(self); + if (start < 0) + start = 0; + } + if (stop < 0) { + stop += Py_SIZE(self); + if (stop < 0) + stop = 0; + } + for (i = start; i < stop && i < Py_SIZE(self); i++) { + int cmp = PyObject_RichCompareBool(self->ob_item[i], v, Py_EQ); + if (cmp > 0) + return PyLong_FromSsize_t(i); + else if (cmp < 0) + return NULL; + } + if (err_format == NULL) { + err_format = PyUnicode_FromString("%r is not in list"); + if (err_format == NULL) + return NULL; + } + format_tuple = PyTuple_Pack(1, v); + if (format_tuple == NULL) + return NULL; + err_string = PyUnicode_Format(err_format, format_tuple); + Py_DECREF(format_tuple); + if (err_string == NULL) + return NULL; + PyErr_SetObject(PyExc_ValueError, err_string); + Py_DECREF(err_string); + return NULL; } static PyObject * listcount(PyListObject *self, PyObject *v) { - Py_ssize_t count = 0; - Py_ssize_t i; + Py_ssize_t count = 0; + Py_ssize_t i; - for (i = 0; i < Py_SIZE(self); i++) { - int cmp = PyObject_RichCompareBool(self->ob_item[i], v, Py_EQ); - if (cmp > 0) - count++; - else if (cmp < 0) - return NULL; - } - return PyLong_FromSsize_t(count); + for (i = 0; i < Py_SIZE(self); i++) { + int cmp = PyObject_RichCompareBool(self->ob_item[i], v, Py_EQ); + if (cmp > 0) + count++; + else if (cmp < 0) + return NULL; + } + return PyLong_FromSsize_t(count); } static PyObject * listremove(PyListObject *self, PyObject *v) { - Py_ssize_t i; + Py_ssize_t i; - for (i = 0; i < Py_SIZE(self); i++) { - int cmp = PyObject_RichCompareBool(self->ob_item[i], v, Py_EQ); - if (cmp > 0) { - if (list_ass_slice(self, i, i+1, - (PyObject *)NULL) == 0) - Py_RETURN_NONE; - return NULL; - } - else if (cmp < 0) - return NULL; - } - PyErr_SetString(PyExc_ValueError, "list.remove(x): x not in list"); - return NULL; + for (i = 0; i < Py_SIZE(self); i++) { + int cmp = PyObject_RichCompareBool(self->ob_item[i], v, Py_EQ); + if (cmp > 0) { + if (list_ass_slice(self, i, i+1, + (PyObject *)NULL) == 0) + Py_RETURN_NONE; + return NULL; + } + else if (cmp < 0) + return NULL; + } + PyErr_SetString(PyExc_ValueError, "list.remove(x): x not in list"); + return NULL; } static int list_traverse(PyListObject *o, visitproc visit, void *arg) { - Py_ssize_t i; + Py_ssize_t i; - for (i = Py_SIZE(o); --i >= 0; ) - Py_VISIT(o->ob_item[i]); - return 0; + for (i = Py_SIZE(o); --i >= 0; ) + Py_VISIT(o->ob_item[i]); + return 0; } static PyObject * list_richcompare(PyObject *v, PyObject *w, int op) { - PyListObject *vl, *wl; - Py_ssize_t i; + PyListObject *vl, *wl; + Py_ssize_t i; - if (!PyList_Check(v) || !PyList_Check(w)) { - Py_INCREF(Py_NotImplemented); - return Py_NotImplemented; - } - - vl = (PyListObject *)v; - wl = (PyListObject *)w; - - if (Py_SIZE(vl) != Py_SIZE(wl) && (op == Py_EQ || op == Py_NE)) { - /* Shortcut: if the lengths differ, the lists differ */ - PyObject *res; - if (op == Py_EQ) - res = Py_False; - else - res = Py_True; - Py_INCREF(res); - return res; - } - - /* Search for the first index where items are different */ - for (i = 0; i < Py_SIZE(vl) && i < Py_SIZE(wl); i++) { - int k = PyObject_RichCompareBool(vl->ob_item[i], - wl->ob_item[i], Py_EQ); - if (k < 0) - return NULL; - if (!k) - break; - } - - if (i >= Py_SIZE(vl) || i >= Py_SIZE(wl)) { - /* No more items to compare -- compare sizes */ - Py_ssize_t vs = Py_SIZE(vl); - Py_ssize_t ws = Py_SIZE(wl); - int cmp; - PyObject *res; - switch (op) { - case Py_LT: cmp = vs < ws; break; - case Py_LE: cmp = vs <= ws; break; - case Py_EQ: cmp = vs == ws; break; - case Py_NE: cmp = vs != ws; break; - case Py_GT: cmp = vs > ws; break; - case Py_GE: cmp = vs >= ws; break; - default: return NULL; /* cannot happen */ - } - if (cmp) - res = Py_True; - else - res = Py_False; - Py_INCREF(res); - return res; - } - - /* We have an item that differs -- shortcuts for EQ/NE */ - if (op == Py_EQ) { - Py_INCREF(Py_False); - return Py_False; - } - if (op == Py_NE) { - Py_INCREF(Py_True); - return Py_True; - } + if (!PyList_Check(v) || !PyList_Check(w)) { + Py_INCREF(Py_NotImplemented); + return Py_NotImplemented; + } + + vl = (PyListObject *)v; + wl = (PyListObject *)w; + + if (Py_SIZE(vl) != Py_SIZE(wl) && (op == Py_EQ || op == Py_NE)) { + /* Shortcut: if the lengths differ, the lists differ */ + PyObject *res; + if (op == Py_EQ) + res = Py_False; + else + res = Py_True; + Py_INCREF(res); + return res; + } + + /* Search for the first index where items are different */ + for (i = 0; i < Py_SIZE(vl) && i < Py_SIZE(wl); i++) { + int k = PyObject_RichCompareBool(vl->ob_item[i], + wl->ob_item[i], Py_EQ); + if (k < 0) + return NULL; + if (!k) + break; + } + + if (i >= Py_SIZE(vl) || i >= Py_SIZE(wl)) { + /* No more items to compare -- compare sizes */ + Py_ssize_t vs = Py_SIZE(vl); + Py_ssize_t ws = Py_SIZE(wl); + int cmp; + PyObject *res; + switch (op) { + case Py_LT: cmp = vs < ws; break; + case Py_LE: cmp = vs <= ws; break; + case Py_EQ: cmp = vs == ws; break; + case Py_NE: cmp = vs != ws; break; + case Py_GT: cmp = vs > ws; break; + case Py_GE: cmp = vs >= ws; break; + default: return NULL; /* cannot happen */ + } + if (cmp) + res = Py_True; + else + res = Py_False; + Py_INCREF(res); + return res; + } + + /* We have an item that differs -- shortcuts for EQ/NE */ + if (op == Py_EQ) { + Py_INCREF(Py_False); + return Py_False; + } + if (op == Py_NE) { + Py_INCREF(Py_True); + return Py_True; + } - /* Compare the final item again using the proper operator */ - return PyObject_RichCompare(vl->ob_item[i], wl->ob_item[i], op); + /* Compare the final item again using the proper operator */ + return PyObject_RichCompare(vl->ob_item[i], wl->ob_item[i], op); } static int list_init(PyListObject *self, PyObject *args, PyObject *kw) { - PyObject *arg = NULL; - static char *kwlist[] = {"sequence", 0}; + PyObject *arg = NULL; + static char *kwlist[] = {"sequence", 0}; - if (!PyArg_ParseTupleAndKeywords(args, kw, "|O:list", kwlist, &arg)) - return -1; + if (!PyArg_ParseTupleAndKeywords(args, kw, "|O:list", kwlist, &arg)) + return -1; - /* Verify list invariants established by PyType_GenericAlloc() */ - assert(0 <= Py_SIZE(self)); - assert(Py_SIZE(self) <= self->allocated || self->allocated == -1); - assert(self->ob_item != NULL || - self->allocated == 0 || self->allocated == -1); - - /* Empty previous contents */ - if (self->ob_item != NULL) { - (void)list_clear(self); - } - if (arg != NULL) { - PyObject *rv = listextend(self, arg); - if (rv == NULL) - return -1; - Py_DECREF(rv); - } - return 0; + /* Verify list invariants established by PyType_GenericAlloc() */ + assert(0 <= Py_SIZE(self)); + assert(Py_SIZE(self) <= self->allocated || self->allocated == -1); + assert(self->ob_item != NULL || + self->allocated == 0 || self->allocated == -1); + + /* Empty previous contents */ + if (self->ob_item != NULL) { + (void)list_clear(self); + } + if (arg != NULL) { + PyObject *rv = listextend(self, arg); + if (rv == NULL) + return -1; + Py_DECREF(rv); + } + return 0; } static PyObject * list_sizeof(PyListObject *self) { - Py_ssize_t res; + Py_ssize_t res; - res = sizeof(PyListObject) + self->allocated * sizeof(void*); - return PyLong_FromSsize_t(res); + res = sizeof(PyListObject) + self->allocated * sizeof(void*); + return PyLong_FromSsize_t(res); } static PyObject *list_iter(PyObject *seq); @@ -2328,32 +2328,32 @@ static PyObject *list_subscript(PyListObject*, PyObject*); static PyMethodDef list_methods[] = { - {"__getitem__", (PyCFunction)list_subscript, METH_O|METH_COEXIST, getitem_doc}, - {"__reversed__",(PyCFunction)list_reversed, METH_NOARGS, reversed_doc}, - {"__sizeof__", (PyCFunction)list_sizeof, METH_NOARGS, sizeof_doc}, - {"append", (PyCFunction)listappend, METH_O, append_doc}, - {"insert", (PyCFunction)listinsert, METH_VARARGS, insert_doc}, - {"extend", (PyCFunction)listextend, METH_O, extend_doc}, - {"pop", (PyCFunction)listpop, METH_VARARGS, pop_doc}, - {"remove", (PyCFunction)listremove, METH_O, remove_doc}, - {"index", (PyCFunction)listindex, METH_VARARGS, index_doc}, - {"count", (PyCFunction)listcount, METH_O, count_doc}, - {"reverse", (PyCFunction)listreverse, METH_NOARGS, reverse_doc}, - {"sort", (PyCFunction)listsort, METH_VARARGS | METH_KEYWORDS, sort_doc}, - {NULL, NULL} /* sentinel */ + {"__getitem__", (PyCFunction)list_subscript, METH_O|METH_COEXIST, getitem_doc}, + {"__reversed__",(PyCFunction)list_reversed, METH_NOARGS, reversed_doc}, + {"__sizeof__", (PyCFunction)list_sizeof, METH_NOARGS, sizeof_doc}, + {"append", (PyCFunction)listappend, METH_O, append_doc}, + {"insert", (PyCFunction)listinsert, METH_VARARGS, insert_doc}, + {"extend", (PyCFunction)listextend, METH_O, extend_doc}, + {"pop", (PyCFunction)listpop, METH_VARARGS, pop_doc}, + {"remove", (PyCFunction)listremove, METH_O, remove_doc}, + {"index", (PyCFunction)listindex, METH_VARARGS, index_doc}, + {"count", (PyCFunction)listcount, METH_O, count_doc}, + {"reverse", (PyCFunction)listreverse, METH_NOARGS, reverse_doc}, + {"sort", (PyCFunction)listsort, METH_VARARGS | METH_KEYWORDS, sort_doc}, + {NULL, NULL} /* sentinel */ }; static PySequenceMethods list_as_sequence = { - (lenfunc)list_length, /* sq_length */ - (binaryfunc)list_concat, /* sq_concat */ - (ssizeargfunc)list_repeat, /* sq_repeat */ - (ssizeargfunc)list_item, /* sq_item */ - 0, /* sq_slice */ - (ssizeobjargproc)list_ass_item, /* sq_ass_item */ - 0, /* sq_ass_slice */ - (objobjproc)list_contains, /* sq_contains */ - (binaryfunc)list_inplace_concat, /* sq_inplace_concat */ - (ssizeargfunc)list_inplace_repeat, /* sq_inplace_repeat */ + (lenfunc)list_length, /* sq_length */ + (binaryfunc)list_concat, /* sq_concat */ + (ssizeargfunc)list_repeat, /* sq_repeat */ + (ssizeargfunc)list_item, /* sq_item */ + 0, /* sq_slice */ + (ssizeobjargproc)list_ass_item, /* sq_ass_item */ + 0, /* sq_ass_slice */ + (objobjproc)list_contains, /* sq_contains */ + (binaryfunc)list_inplace_concat, /* sq_inplace_concat */ + (ssizeargfunc)list_inplace_repeat, /* sq_inplace_repeat */ }; PyDoc_STRVAR(list_doc, @@ -2363,275 +2363,275 @@ static PyObject * list_subscript(PyListObject* self, PyObject* item) { - if (PyIndex_Check(item)) { - Py_ssize_t i; - i = PyNumber_AsSsize_t(item, PyExc_IndexError); - if (i == -1 && PyErr_Occurred()) - return NULL; - if (i < 0) - i += PyList_GET_SIZE(self); - return list_item(self, i); - } - else if (PySlice_Check(item)) { - Py_ssize_t start, stop, step, slicelength, cur, i; - PyObject* result; - PyObject* it; - PyObject **src, **dest; - - if (PySlice_GetIndicesEx((PySliceObject*)item, Py_SIZE(self), - &start, &stop, &step, &slicelength) < 0) { - return NULL; - } - - if (slicelength <= 0) { - return PyList_New(0); - } - else if (step == 1) { - return list_slice(self, start, stop); - } - else { - result = PyList_New(slicelength); - if (!result) return NULL; - - src = self->ob_item; - dest = ((PyListObject *)result)->ob_item; - for (cur = start, i = 0; i < slicelength; - cur += step, i++) { - it = src[cur]; - Py_INCREF(it); - dest[i] = it; - } - - return result; - } - } - else { - PyErr_Format(PyExc_TypeError, - "list indices must be integers, not %.200s", - item->ob_type->tp_name); - return NULL; - } + if (PyIndex_Check(item)) { + Py_ssize_t i; + i = PyNumber_AsSsize_t(item, PyExc_IndexError); + if (i == -1 && PyErr_Occurred()) + return NULL; + if (i < 0) + i += PyList_GET_SIZE(self); + return list_item(self, i); + } + else if (PySlice_Check(item)) { + Py_ssize_t start, stop, step, slicelength, cur, i; + PyObject* result; + PyObject* it; + PyObject **src, **dest; + + if (PySlice_GetIndicesEx((PySliceObject*)item, Py_SIZE(self), + &start, &stop, &step, &slicelength) < 0) { + return NULL; + } + + if (slicelength <= 0) { + return PyList_New(0); + } + else if (step == 1) { + return list_slice(self, start, stop); + } + else { + result = PyList_New(slicelength); + if (!result) return NULL; + + src = self->ob_item; + dest = ((PyListObject *)result)->ob_item; + for (cur = start, i = 0; i < slicelength; + cur += step, i++) { + it = src[cur]; + Py_INCREF(it); + dest[i] = it; + } + + return result; + } + } + else { + PyErr_Format(PyExc_TypeError, + "list indices must be integers, not %.200s", + item->ob_type->tp_name); + return NULL; + } } static int list_ass_subscript(PyListObject* self, PyObject* item, PyObject* value) { - if (PyIndex_Check(item)) { - Py_ssize_t i = PyNumber_AsSsize_t(item, PyExc_IndexError); - if (i == -1 && PyErr_Occurred()) - return -1; - if (i < 0) - i += PyList_GET_SIZE(self); - return list_ass_item(self, i, value); - } - else if (PySlice_Check(item)) { - Py_ssize_t start, stop, step, slicelength; - - if (PySlice_GetIndicesEx((PySliceObject*)item, Py_SIZE(self), - &start, &stop, &step, &slicelength) < 0) { - return -1; - } - - if (step == 1) - return list_ass_slice(self, start, stop, value); - - /* Make sure s[5:2] = [..] inserts at the right place: - before 5, not before 2. */ - if ((step < 0 && start < stop) || - (step > 0 && start > stop)) - stop = start; - - if (value == NULL) { - /* delete slice */ - PyObject **garbage; - size_t cur; - Py_ssize_t i; - - if (slicelength <= 0) - return 0; - - if (step < 0) { - stop = start + 1; - start = stop + step*(slicelength - 1) - 1; - step = -step; - } - - assert((size_t)slicelength <= - PY_SIZE_MAX / sizeof(PyObject*)); - - garbage = (PyObject**) - PyMem_MALLOC(slicelength*sizeof(PyObject*)); - if (!garbage) { - PyErr_NoMemory(); - return -1; - } - - /* drawing pictures might help understand these for - loops. Basically, we memmove the parts of the - list that are *not* part of the slice: step-1 - items for each item that is part of the slice, - and then tail end of the list that was not - covered by the slice */ - for (cur = start, i = 0; - cur < (size_t)stop; - cur += step, i++) { - Py_ssize_t lim = step - 1; - - garbage[i] = PyList_GET_ITEM(self, cur); - - if (cur + step >= (size_t)Py_SIZE(self)) { - lim = Py_SIZE(self) - cur - 1; - } - - memmove(self->ob_item + cur - i, - self->ob_item + cur + 1, - lim * sizeof(PyObject *)); - } - cur = start + slicelength*step; - if (cur < (size_t)Py_SIZE(self)) { - memmove(self->ob_item + cur - slicelength, - self->ob_item + cur, - (Py_SIZE(self) - cur) * - sizeof(PyObject *)); - } - - Py_SIZE(self) -= slicelength; - list_resize(self, Py_SIZE(self)); - - for (i = 0; i < slicelength; i++) { - Py_DECREF(garbage[i]); - } - PyMem_FREE(garbage); - - return 0; - } - else { - /* assign slice */ - PyObject *ins, *seq; - PyObject **garbage, **seqitems, **selfitems; - Py_ssize_t cur, i; - - /* protect against a[::-1] = a */ - if (self == (PyListObject*)value) { - seq = list_slice((PyListObject*)value, 0, - PyList_GET_SIZE(value)); - } - else { - seq = PySequence_Fast(value, - "must assign iterable " - "to extended slice"); - } - if (!seq) - return -1; - - if (PySequence_Fast_GET_SIZE(seq) != slicelength) { - PyErr_Format(PyExc_ValueError, - "attempt to assign sequence of " - "size %zd to extended slice of " - "size %zd", - PySequence_Fast_GET_SIZE(seq), - slicelength); - Py_DECREF(seq); - return -1; - } - - if (!slicelength) { - Py_DECREF(seq); - return 0; - } - - garbage = (PyObject**) - PyMem_MALLOC(slicelength*sizeof(PyObject*)); - if (!garbage) { - Py_DECREF(seq); - PyErr_NoMemory(); - return -1; - } - - selfitems = self->ob_item; - seqitems = PySequence_Fast_ITEMS(seq); - for (cur = start, i = 0; i < slicelength; - cur += step, i++) { - garbage[i] = selfitems[cur]; - ins = seqitems[i]; - Py_INCREF(ins); - selfitems[cur] = ins; - } - - for (i = 0; i < slicelength; i++) { - Py_DECREF(garbage[i]); - } - - PyMem_FREE(garbage); - Py_DECREF(seq); - - return 0; - } - } - else { - PyErr_Format(PyExc_TypeError, - "list indices must be integers, not %.200s", - item->ob_type->tp_name); - return -1; - } + if (PyIndex_Check(item)) { + Py_ssize_t i = PyNumber_AsSsize_t(item, PyExc_IndexError); + if (i == -1 && PyErr_Occurred()) + return -1; + if (i < 0) + i += PyList_GET_SIZE(self); + return list_ass_item(self, i, value); + } + else if (PySlice_Check(item)) { + Py_ssize_t start, stop, step, slicelength; + + if (PySlice_GetIndicesEx((PySliceObject*)item, Py_SIZE(self), + &start, &stop, &step, &slicelength) < 0) { + return -1; + } + + if (step == 1) + return list_ass_slice(self, start, stop, value); + + /* Make sure s[5:2] = [..] inserts at the right place: + before 5, not before 2. */ + if ((step < 0 && start < stop) || + (step > 0 && start > stop)) + stop = start; + + if (value == NULL) { + /* delete slice */ + PyObject **garbage; + size_t cur; + Py_ssize_t i; + + if (slicelength <= 0) + return 0; + + if (step < 0) { + stop = start + 1; + start = stop + step*(slicelength - 1) - 1; + step = -step; + } + + assert((size_t)slicelength <= + PY_SIZE_MAX / sizeof(PyObject*)); + + garbage = (PyObject**) + PyMem_MALLOC(slicelength*sizeof(PyObject*)); + if (!garbage) { + PyErr_NoMemory(); + return -1; + } + + /* drawing pictures might help understand these for + loops. Basically, we memmove the parts of the + list that are *not* part of the slice: step-1 + items for each item that is part of the slice, + and then tail end of the list that was not + covered by the slice */ + for (cur = start, i = 0; + cur < (size_t)stop; + cur += step, i++) { + Py_ssize_t lim = step - 1; + + garbage[i] = PyList_GET_ITEM(self, cur); + + if (cur + step >= (size_t)Py_SIZE(self)) { + lim = Py_SIZE(self) - cur - 1; + } + + memmove(self->ob_item + cur - i, + self->ob_item + cur + 1, + lim * sizeof(PyObject *)); + } + cur = start + slicelength*step; + if (cur < (size_t)Py_SIZE(self)) { + memmove(self->ob_item + cur - slicelength, + self->ob_item + cur, + (Py_SIZE(self) - cur) * + sizeof(PyObject *)); + } + + Py_SIZE(self) -= slicelength; + list_resize(self, Py_SIZE(self)); + + for (i = 0; i < slicelength; i++) { + Py_DECREF(garbage[i]); + } + PyMem_FREE(garbage); + + return 0; + } + else { + /* assign slice */ + PyObject *ins, *seq; + PyObject **garbage, **seqitems, **selfitems; + Py_ssize_t cur, i; + + /* protect against a[::-1] = a */ + if (self == (PyListObject*)value) { + seq = list_slice((PyListObject*)value, 0, + PyList_GET_SIZE(value)); + } + else { + seq = PySequence_Fast(value, + "must assign iterable " + "to extended slice"); + } + if (!seq) + return -1; + + if (PySequence_Fast_GET_SIZE(seq) != slicelength) { + PyErr_Format(PyExc_ValueError, + "attempt to assign sequence of " + "size %zd to extended slice of " + "size %zd", + PySequence_Fast_GET_SIZE(seq), + slicelength); + Py_DECREF(seq); + return -1; + } + + if (!slicelength) { + Py_DECREF(seq); + return 0; + } + + garbage = (PyObject**) + PyMem_MALLOC(slicelength*sizeof(PyObject*)); + if (!garbage) { + Py_DECREF(seq); + PyErr_NoMemory(); + return -1; + } + + selfitems = self->ob_item; + seqitems = PySequence_Fast_ITEMS(seq); + for (cur = start, i = 0; i < slicelength; + cur += step, i++) { + garbage[i] = selfitems[cur]; + ins = seqitems[i]; + Py_INCREF(ins); + selfitems[cur] = ins; + } + + for (i = 0; i < slicelength; i++) { + Py_DECREF(garbage[i]); + } + + PyMem_FREE(garbage); + Py_DECREF(seq); + + return 0; + } + } + else { + PyErr_Format(PyExc_TypeError, + "list indices must be integers, not %.200s", + item->ob_type->tp_name); + return -1; + } } static PyMappingMethods list_as_mapping = { - (lenfunc)list_length, - (binaryfunc)list_subscript, - (objobjargproc)list_ass_subscript + (lenfunc)list_length, + (binaryfunc)list_subscript, + (objobjargproc)list_ass_subscript }; PyTypeObject PyList_Type = { - PyVarObject_HEAD_INIT(&PyType_Type, 0) - "list", - sizeof(PyListObject), - 0, - (destructor)list_dealloc, /* tp_dealloc */ - 0, /* tp_print */ - 0, /* tp_getattr */ - 0, /* tp_setattr */ - 0, /* tp_reserved */ - (reprfunc)list_repr, /* tp_repr */ - 0, /* tp_as_number */ - &list_as_sequence, /* tp_as_sequence */ - &list_as_mapping, /* tp_as_mapping */ - (hashfunc)PyObject_HashNotImplemented, /* 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 | - Py_TPFLAGS_BASETYPE | Py_TPFLAGS_LIST_SUBCLASS, /* tp_flags */ - list_doc, /* tp_doc */ - (traverseproc)list_traverse, /* tp_traverse */ - (inquiry)list_clear, /* tp_clear */ - list_richcompare, /* tp_richcompare */ - 0, /* tp_weaklistoffset */ - list_iter, /* tp_iter */ - 0, /* tp_iternext */ - list_methods, /* tp_methods */ - 0, /* tp_members */ - 0, /* tp_getset */ - 0, /* tp_base */ - 0, /* tp_dict */ - 0, /* tp_descr_get */ - 0, /* tp_descr_set */ - 0, /* tp_dictoffset */ - (initproc)list_init, /* tp_init */ - PyType_GenericAlloc, /* tp_alloc */ - PyType_GenericNew, /* tp_new */ - PyObject_GC_Del, /* tp_free */ + PyVarObject_HEAD_INIT(&PyType_Type, 0) + "list", + sizeof(PyListObject), + 0, + (destructor)list_dealloc, /* tp_dealloc */ + 0, /* tp_print */ + 0, /* tp_getattr */ + 0, /* tp_setattr */ + 0, /* tp_reserved */ + (reprfunc)list_repr, /* tp_repr */ + 0, /* tp_as_number */ + &list_as_sequence, /* tp_as_sequence */ + &list_as_mapping, /* tp_as_mapping */ + (hashfunc)PyObject_HashNotImplemented, /* 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 | + Py_TPFLAGS_BASETYPE | Py_TPFLAGS_LIST_SUBCLASS, /* tp_flags */ + list_doc, /* tp_doc */ + (traverseproc)list_traverse, /* tp_traverse */ + (inquiry)list_clear, /* tp_clear */ + list_richcompare, /* tp_richcompare */ + 0, /* tp_weaklistoffset */ + list_iter, /* tp_iter */ + 0, /* tp_iternext */ + list_methods, /* tp_methods */ + 0, /* tp_members */ + 0, /* tp_getset */ + 0, /* tp_base */ + 0, /* tp_dict */ + 0, /* tp_descr_get */ + 0, /* tp_descr_set */ + 0, /* tp_dictoffset */ + (initproc)list_init, /* tp_init */ + PyType_GenericAlloc, /* tp_alloc */ + PyType_GenericNew, /* tp_new */ + PyObject_GC_Del, /* tp_free */ }; /*********************** List Iterator **************************/ typedef struct { - PyObject_HEAD - long it_index; - PyListObject *it_seq; /* Set to NULL when iterator is exhausted */ + PyObject_HEAD + long it_index; + PyListObject *it_seq; /* Set to NULL when iterator is exhausted */ } listiterobject; static PyObject *list_iter(PyObject *); @@ -2643,119 +2643,119 @@ PyDoc_STRVAR(length_hint_doc, "Private method returning an estimate of len(list(it))."); static PyMethodDef listiter_methods[] = { - {"__length_hint__", (PyCFunction)listiter_len, METH_NOARGS, length_hint_doc}, - {NULL, NULL} /* sentinel */ + {"__length_hint__", (PyCFunction)listiter_len, METH_NOARGS, length_hint_doc}, + {NULL, NULL} /* sentinel */ }; PyTypeObject PyListIter_Type = { - PyVarObject_HEAD_INIT(&PyType_Type, 0) - "list_iterator", /* tp_name */ - sizeof(listiterobject), /* tp_basicsize */ - 0, /* tp_itemsize */ - /* methods */ - (destructor)listiter_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)listiter_traverse, /* tp_traverse */ - 0, /* tp_clear */ - 0, /* tp_richcompare */ - 0, /* tp_weaklistoffset */ - PyObject_SelfIter, /* tp_iter */ - (iternextfunc)listiter_next, /* tp_iternext */ - listiter_methods, /* tp_methods */ - 0, /* tp_members */ + PyVarObject_HEAD_INIT(&PyType_Type, 0) + "list_iterator", /* tp_name */ + sizeof(listiterobject), /* tp_basicsize */ + 0, /* tp_itemsize */ + /* methods */ + (destructor)listiter_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)listiter_traverse, /* tp_traverse */ + 0, /* tp_clear */ + 0, /* tp_richcompare */ + 0, /* tp_weaklistoffset */ + PyObject_SelfIter, /* tp_iter */ + (iternextfunc)listiter_next, /* tp_iternext */ + listiter_methods, /* tp_methods */ + 0, /* tp_members */ }; static PyObject * list_iter(PyObject *seq) { - listiterobject *it; + listiterobject *it; - if (!PyList_Check(seq)) { - PyErr_BadInternalCall(); - return NULL; - } - it = PyObject_GC_New(listiterobject, &PyListIter_Type); - if (it == NULL) - return NULL; - it->it_index = 0; - Py_INCREF(seq); - it->it_seq = (PyListObject *)seq; - _PyObject_GC_TRACK(it); - return (PyObject *)it; + if (!PyList_Check(seq)) { + PyErr_BadInternalCall(); + return NULL; + } + it = PyObject_GC_New(listiterobject, &PyListIter_Type); + if (it == NULL) + return NULL; + it->it_index = 0; + Py_INCREF(seq); + it->it_seq = (PyListObject *)seq; + _PyObject_GC_TRACK(it); + return (PyObject *)it; } static void listiter_dealloc(listiterobject *it) { - _PyObject_GC_UNTRACK(it); - Py_XDECREF(it->it_seq); - PyObject_GC_Del(it); + _PyObject_GC_UNTRACK(it); + Py_XDECREF(it->it_seq); + PyObject_GC_Del(it); } static int listiter_traverse(listiterobject *it, visitproc visit, void *arg) { - Py_VISIT(it->it_seq); - return 0; + Py_VISIT(it->it_seq); + return 0; } static PyObject * listiter_next(listiterobject *it) { - PyListObject *seq; - PyObject *item; + PyListObject *seq; + PyObject *item; - assert(it != NULL); - seq = it->it_seq; - if (seq == NULL) - return NULL; - assert(PyList_Check(seq)); - - if (it->it_index < PyList_GET_SIZE(seq)) { - item = PyList_GET_ITEM(seq, it->it_index); - ++it->it_index; - Py_INCREF(item); - return item; - } - - Py_DECREF(seq); - it->it_seq = NULL; - return NULL; + assert(it != NULL); + seq = it->it_seq; + if (seq == NULL) + return NULL; + assert(PyList_Check(seq)); + + if (it->it_index < PyList_GET_SIZE(seq)) { + item = PyList_GET_ITEM(seq, it->it_index); + ++it->it_index; + Py_INCREF(item); + return item; + } + + Py_DECREF(seq); + it->it_seq = NULL; + return NULL; } static PyObject * listiter_len(listiterobject *it) { - Py_ssize_t len; - if (it->it_seq) { - len = PyList_GET_SIZE(it->it_seq) - it->it_index; - if (len >= 0) - return PyLong_FromSsize_t(len); - } - return PyLong_FromLong(0); + Py_ssize_t len; + if (it->it_seq) { + len = PyList_GET_SIZE(it->it_seq) - it->it_index; + if (len >= 0) + return PyLong_FromSsize_t(len); + } + return PyLong_FromLong(0); } /*********************** List Reverse Iterator **************************/ typedef struct { - PyObject_HEAD - Py_ssize_t it_index; - PyListObject *it_seq; /* Set to NULL when iterator is exhausted */ + PyObject_HEAD + Py_ssize_t it_index; + PyListObject *it_seq; /* Set to NULL when iterator is exhausted */ } listreviterobject; static PyObject *list_reversed(PyListObject *, PyObject *); @@ -2765,101 +2765,101 @@ static PyObject *listreviter_len(listreviterobject *); static PyMethodDef listreviter_methods[] = { - {"__length_hint__", (PyCFunction)listreviter_len, METH_NOARGS, length_hint_doc}, - {NULL, NULL} /* sentinel */ + {"__length_hint__", (PyCFunction)listreviter_len, METH_NOARGS, length_hint_doc}, + {NULL, NULL} /* sentinel */ }; PyTypeObject PyListRevIter_Type = { - PyVarObject_HEAD_INIT(&PyType_Type, 0) - "list_reverseiterator", /* tp_name */ - sizeof(listreviterobject), /* tp_basicsize */ - 0, /* tp_itemsize */ - /* methods */ - (destructor)listreviter_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)listreviter_traverse, /* tp_traverse */ - 0, /* tp_clear */ - 0, /* tp_richcompare */ - 0, /* tp_weaklistoffset */ - PyObject_SelfIter, /* tp_iter */ - (iternextfunc)listreviter_next, /* tp_iternext */ - listreviter_methods, /* tp_methods */ - 0, + PyVarObject_HEAD_INIT(&PyType_Type, 0) + "list_reverseiterator", /* tp_name */ + sizeof(listreviterobject), /* tp_basicsize */ + 0, /* tp_itemsize */ + /* methods */ + (destructor)listreviter_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)listreviter_traverse, /* tp_traverse */ + 0, /* tp_clear */ + 0, /* tp_richcompare */ + 0, /* tp_weaklistoffset */ + PyObject_SelfIter, /* tp_iter */ + (iternextfunc)listreviter_next, /* tp_iternext */ + listreviter_methods, /* tp_methods */ + 0, }; static PyObject * list_reversed(PyListObject *seq, PyObject *unused) { - listreviterobject *it; + listreviterobject *it; - it = PyObject_GC_New(listreviterobject, &PyListRevIter_Type); - if (it == NULL) - return NULL; - assert(PyList_Check(seq)); - it->it_index = PyList_GET_SIZE(seq) - 1; - Py_INCREF(seq); - it->it_seq = seq; - PyObject_GC_Track(it); - return (PyObject *)it; + it = PyObject_GC_New(listreviterobject, &PyListRevIter_Type); + if (it == NULL) + return NULL; + assert(PyList_Check(seq)); + it->it_index = PyList_GET_SIZE(seq) - 1; + Py_INCREF(seq); + it->it_seq = seq; + PyObject_GC_Track(it); + return (PyObject *)it; } static void listreviter_dealloc(listreviterobject *it) { - PyObject_GC_UnTrack(it); - Py_XDECREF(it->it_seq); - PyObject_GC_Del(it); + PyObject_GC_UnTrack(it); + Py_XDECREF(it->it_seq); + PyObject_GC_Del(it); } static int listreviter_traverse(listreviterobject *it, visitproc visit, void *arg) { - Py_VISIT(it->it_seq); - return 0; + Py_VISIT(it->it_seq); + return 0; } static PyObject * listreviter_next(listreviterobject *it) { - PyObject *item; - Py_ssize_t index = it->it_index; - PyListObject *seq = it->it_seq; - - if (index>=0 && index < PyList_GET_SIZE(seq)) { - item = PyList_GET_ITEM(seq, index); - it->it_index--; - Py_INCREF(item); - return item; - } - it->it_index = -1; - if (seq != NULL) { - it->it_seq = NULL; - Py_DECREF(seq); - } - return NULL; + PyObject *item; + Py_ssize_t index = it->it_index; + PyListObject *seq = it->it_seq; + + if (index>=0 && index < PyList_GET_SIZE(seq)) { + item = PyList_GET_ITEM(seq, index); + it->it_index--; + Py_INCREF(item); + return item; + } + it->it_index = -1; + if (seq != NULL) { + it->it_seq = NULL; + Py_DECREF(seq); + } + return NULL; } static PyObject * listreviter_len(listreviterobject *it) { - Py_ssize_t len = it->it_index + 1; - if (it->it_seq == NULL || PyList_GET_SIZE(it->it_seq) < len) - len = 0; - return PyLong_FromSsize_t(len); + Py_ssize_t len = it->it_index + 1; + if (it->it_seq == NULL || PyList_GET_SIZE(it->it_seq) < len) + len = 0; + return PyLong_FromSsize_t(len); } Modified: python/branches/py3k/Objects/longobject.c ============================================================================== --- python/branches/py3k/Objects/longobject.c (original) +++ python/branches/py3k/Objects/longobject.c Sun May 9 17:52:27 2010 @@ -11,16 +11,16 @@ #include #ifndef NSMALLPOSINTS -#define NSMALLPOSINTS 257 +#define NSMALLPOSINTS 257 #endif #ifndef NSMALLNEGINTS -#define NSMALLNEGINTS 5 +#define NSMALLNEGINTS 5 #endif /* convert a PyLong of size 1, 0 or -1 to an sdigit */ -#define MEDIUM_VALUE(x) (Py_SIZE(x) < 0 ? -(sdigit)(x)->ob_digit[0] : \ - (Py_SIZE(x) == 0 ? (sdigit)0 : \ - (sdigit)(x)->ob_digit[0])) +#define MEDIUM_VALUE(x) (Py_SIZE(x) < 0 ? -(sdigit)(x)->ob_digit[0] : \ + (Py_SIZE(x) == 0 ? (sdigit)0 : \ + (sdigit)(x)->ob_digit[0])) #define ABS(x) ((x) < 0 ? -(x) : (x)) #if NSMALLNEGINTS + NSMALLPOSINTS > 0 @@ -37,32 +37,32 @@ static PyObject * get_small_int(sdigit ival) { - PyObject *v = (PyObject*)(small_ints + ival + NSMALLNEGINTS); - Py_INCREF(v); + PyObject *v = (PyObject*)(small_ints + ival + NSMALLNEGINTS); + Py_INCREF(v); #ifdef COUNT_ALLOCS - if (ival >= 0) - quick_int_allocs++; - else - quick_neg_int_allocs++; + if (ival >= 0) + quick_int_allocs++; + else + quick_neg_int_allocs++; #endif - return v; + return v; } #define CHECK_SMALL_INT(ival) \ - do if (-NSMALLNEGINTS <= ival && ival < NSMALLPOSINTS) { \ - return get_small_int((sdigit)ival); \ - } while(0) + do if (-NSMALLNEGINTS <= ival && ival < NSMALLPOSINTS) { \ + return get_small_int((sdigit)ival); \ + } while(0) -static PyLongObject * +static PyLongObject * maybe_small_long(PyLongObject *v) { - if (v && ABS(Py_SIZE(v)) <= 1) { - sdigit ival = MEDIUM_VALUE(v); - if (-NSMALLNEGINTS <= ival && ival < NSMALLPOSINTS) { - Py_DECREF(v); - return (PyLongObject *)get_small_int(ival); - } - } - return v; + if (v && ABS(Py_SIZE(v)) <= 1) { + sdigit ival = MEDIUM_VALUE(v); + if (-NSMALLNEGINTS <= ival && ival < NSMALLPOSINTS) { + Py_DECREF(v); + return (PyLongObject *)get_small_int(ival); + } + } + return v; } #else #define CHECK_SMALL_INT(ival) @@ -72,10 +72,10 @@ /* If a freshly-allocated long is already shared, it must be a small integer, so negating it must go to PyLong_FromLong */ #define NEGATE(x) \ - do if (Py_REFCNT(x) == 1) Py_SIZE(x) = -Py_SIZE(x); \ - else { PyObject* tmp=PyLong_FromLong(-MEDIUM_VALUE(x)); \ - Py_DECREF(x); (x) = (PyLongObject*)tmp; } \ - while(0) + do if (Py_REFCNT(x) == 1) Py_SIZE(x) = -Py_SIZE(x); \ + else { PyObject* tmp=PyLong_FromLong(-MEDIUM_VALUE(x)); \ + Py_DECREF(x); (x) = (PyLongObject*)tmp; } \ + while(0) /* For long multiplication, use the O(N**2) school algorithm unless * both operands contain more than KARATSUBA_CUTOFF digits (this * being an internal Python long digit, in base BASE). @@ -96,7 +96,7 @@ #define MIN(x, y) ((x) > (y) ? (y) : (x)) #define SIGCHECK(PyTryBlock) \ - if (PyErr_CheckSignals()) PyTryBlock \ + if (PyErr_CheckSignals()) PyTryBlock \ /* Normalize (remove leading zeros from) a long int object. Doesn't attempt to free the storage--in most cases, due to the nature @@ -105,68 +105,68 @@ static PyLongObject * long_normalize(register PyLongObject *v) { - Py_ssize_t j = ABS(Py_SIZE(v)); - Py_ssize_t i = j; + Py_ssize_t j = ABS(Py_SIZE(v)); + Py_ssize_t i = j; - while (i > 0 && v->ob_digit[i-1] == 0) - --i; - if (i != j) - Py_SIZE(v) = (Py_SIZE(v) < 0) ? -(i) : i; - return v; + while (i > 0 && v->ob_digit[i-1] == 0) + --i; + if (i != j) + Py_SIZE(v) = (Py_SIZE(v) < 0) ? -(i) : i; + return v; } /* Allocate a new long int object with size digits. Return NULL and set exception if we run out of memory. */ #define MAX_LONG_DIGITS \ - ((PY_SSIZE_T_MAX - offsetof(PyLongObject, ob_digit))/sizeof(digit)) + ((PY_SSIZE_T_MAX - offsetof(PyLongObject, ob_digit))/sizeof(digit)) PyLongObject * _PyLong_New(Py_ssize_t size) { - PyLongObject *result; - /* Number of bytes needed is: offsetof(PyLongObject, ob_digit) + - sizeof(digit)*size. Previous incarnations of this code used - sizeof(PyVarObject) instead of the offsetof, but this risks being - incorrect in the presence of padding between the PyVarObject header - and the digits. */ - if (size > (Py_ssize_t)MAX_LONG_DIGITS) { - PyErr_SetString(PyExc_OverflowError, - "too many digits in integer"); - return NULL; - } - result = PyObject_MALLOC(offsetof(PyLongObject, ob_digit) + - size*sizeof(digit)); - if (!result) { - PyErr_NoMemory(); - return NULL; - } - return (PyLongObject*)PyObject_INIT_VAR(result, &PyLong_Type, size); + PyLongObject *result; + /* Number of bytes needed is: offsetof(PyLongObject, ob_digit) + + sizeof(digit)*size. Previous incarnations of this code used + sizeof(PyVarObject) instead of the offsetof, but this risks being + incorrect in the presence of padding between the PyVarObject header + and the digits. */ + if (size > (Py_ssize_t)MAX_LONG_DIGITS) { + PyErr_SetString(PyExc_OverflowError, + "too many digits in integer"); + return NULL; + } + result = PyObject_MALLOC(offsetof(PyLongObject, ob_digit) + + size*sizeof(digit)); + if (!result) { + PyErr_NoMemory(); + return NULL; + } + return (PyLongObject*)PyObject_INIT_VAR(result, &PyLong_Type, size); } PyObject * _PyLong_Copy(PyLongObject *src) { - PyLongObject *result; - Py_ssize_t i; + PyLongObject *result; + Py_ssize_t i; - assert(src != NULL); - i = Py_SIZE(src); - if (i < 0) - i = -(i); - if (i < 2) { - sdigit ival = src->ob_digit[0]; - if (Py_SIZE(src) < 0) - ival = -ival; - CHECK_SMALL_INT(ival); - } - result = _PyLong_New(i); - if (result != NULL) { - Py_SIZE(result) = Py_SIZE(src); - while (--i >= 0) - result->ob_digit[i] = src->ob_digit[i]; - } - return (PyObject *)result; + assert(src != NULL); + i = Py_SIZE(src); + if (i < 0) + i = -(i); + if (i < 2) { + sdigit ival = src->ob_digit[0]; + if (Py_SIZE(src) < 0) + ival = -ival; + CHECK_SMALL_INT(ival); + } + result = _PyLong_New(i); + if (result != NULL) { + Py_SIZE(result) = Py_SIZE(src); + while (--i >= 0) + result->ob_digit[i] = src->ob_digit[i]; + } + return (PyObject *)result; } /* Create a new long int object from a C long int */ @@ -174,68 +174,68 @@ PyObject * PyLong_FromLong(long ival) { - PyLongObject *v; - unsigned long abs_ival; - unsigned long t; /* unsigned so >> doesn't propagate sign bit */ - int ndigits = 0; - int sign = 1; - - CHECK_SMALL_INT(ival); - - if (ival < 0) { - /* negate: can't write this as abs_ival = -ival since that - invokes undefined behaviour when ival is LONG_MIN */ - abs_ival = 0U-(unsigned long)ival; - sign = -1; - } - else { - abs_ival = (unsigned long)ival; - } - - /* Fast path for single-digit ints */ - if (!(abs_ival >> PyLong_SHIFT)) { - v = _PyLong_New(1); - if (v) { - Py_SIZE(v) = sign; - v->ob_digit[0] = Py_SAFE_DOWNCAST( - abs_ival, unsigned long, digit); - } - return (PyObject*)v; - } + PyLongObject *v; + unsigned long abs_ival; + unsigned long t; /* unsigned so >> doesn't propagate sign bit */ + int ndigits = 0; + int sign = 1; + + CHECK_SMALL_INT(ival); + + if (ival < 0) { + /* negate: can't write this as abs_ival = -ival since that + invokes undefined behaviour when ival is LONG_MIN */ + abs_ival = 0U-(unsigned long)ival; + sign = -1; + } + else { + abs_ival = (unsigned long)ival; + } + + /* Fast path for single-digit ints */ + if (!(abs_ival >> PyLong_SHIFT)) { + v = _PyLong_New(1); + if (v) { + Py_SIZE(v) = sign; + v->ob_digit[0] = Py_SAFE_DOWNCAST( + abs_ival, unsigned long, digit); + } + return (PyObject*)v; + } #if PyLong_SHIFT==15 - /* 2 digits */ - if (!(abs_ival >> 2*PyLong_SHIFT)) { - v = _PyLong_New(2); - if (v) { - Py_SIZE(v) = 2*sign; - v->ob_digit[0] = Py_SAFE_DOWNCAST( - abs_ival & PyLong_MASK, unsigned long, digit); - v->ob_digit[1] = Py_SAFE_DOWNCAST( - abs_ival >> PyLong_SHIFT, unsigned long, digit); - } - return (PyObject*)v; - } + /* 2 digits */ + if (!(abs_ival >> 2*PyLong_SHIFT)) { + v = _PyLong_New(2); + if (v) { + Py_SIZE(v) = 2*sign; + v->ob_digit[0] = Py_SAFE_DOWNCAST( + abs_ival & PyLong_MASK, unsigned long, digit); + v->ob_digit[1] = Py_SAFE_DOWNCAST( + abs_ival >> PyLong_SHIFT, unsigned long, digit); + } + return (PyObject*)v; + } #endif - /* Larger numbers: loop to determine number of digits */ - t = abs_ival; - while (t) { - ++ndigits; - t >>= PyLong_SHIFT; - } - v = _PyLong_New(ndigits); - if (v != NULL) { - digit *p = v->ob_digit; - Py_SIZE(v) = ndigits*sign; - t = abs_ival; - while (t) { - *p++ = Py_SAFE_DOWNCAST( - t & PyLong_MASK, unsigned long, digit); - t >>= PyLong_SHIFT; - } - } - return (PyObject *)v; + /* Larger numbers: loop to determine number of digits */ + t = abs_ival; + while (t) { + ++ndigits; + t >>= PyLong_SHIFT; + } + v = _PyLong_New(ndigits); + if (v != NULL) { + digit *p = v->ob_digit; + Py_SIZE(v) = ndigits*sign; + t = abs_ival; + while (t) { + *p++ = Py_SAFE_DOWNCAST( + t & PyLong_MASK, unsigned long, digit); + t >>= PyLong_SHIFT; + } + } + return (PyObject *)v; } /* Create a new long int object from a C unsigned long int */ @@ -243,28 +243,28 @@ PyObject * PyLong_FromUnsignedLong(unsigned long ival) { - PyLongObject *v; - unsigned long t; - int ndigits = 0; - - if (ival < PyLong_BASE) - return PyLong_FromLong(ival); - /* Count the number of Python digits. */ - t = (unsigned long)ival; - while (t) { - ++ndigits; - t >>= PyLong_SHIFT; - } - v = _PyLong_New(ndigits); - if (v != NULL) { - digit *p = v->ob_digit; - Py_SIZE(v) = ndigits; - while (ival) { - *p++ = (digit)(ival & PyLong_MASK); - ival >>= PyLong_SHIFT; - } - } - return (PyObject *)v; + PyLongObject *v; + unsigned long t; + int ndigits = 0; + + if (ival < PyLong_BASE) + return PyLong_FromLong(ival); + /* Count the number of Python digits. */ + t = (unsigned long)ival; + while (t) { + ++ndigits; + t >>= PyLong_SHIFT; + } + v = _PyLong_New(ndigits); + if (v != NULL) { + digit *p = v->ob_digit; + Py_SIZE(v) = ndigits; + while (ival) { + *p++ = (digit)(ival & PyLong_MASK); + ival >>= PyLong_SHIFT; + } + } + return (PyObject *)v; } /* Create a new long int object from a C double */ @@ -272,41 +272,41 @@ PyObject * PyLong_FromDouble(double dval) { - PyLongObject *v; - double frac; - int i, ndig, expo, neg; - neg = 0; - if (Py_IS_INFINITY(dval)) { - PyErr_SetString(PyExc_OverflowError, - "cannot convert float infinity to integer"); - return NULL; - } - if (Py_IS_NAN(dval)) { - PyErr_SetString(PyExc_ValueError, - "cannot convert float NaN to integer"); - return NULL; - } - if (dval < 0.0) { - neg = 1; - dval = -dval; - } - frac = frexp(dval, &expo); /* dval = frac*2**expo; 0.0 <= frac < 1.0 */ - if (expo <= 0) - return PyLong_FromLong(0L); - ndig = (expo-1) / PyLong_SHIFT + 1; /* Number of 'digits' in result */ - v = _PyLong_New(ndig); - if (v == NULL) - return NULL; - frac = ldexp(frac, (expo-1) % PyLong_SHIFT + 1); - for (i = ndig; --i >= 0; ) { - digit bits = (digit)frac; - v->ob_digit[i] = bits; - frac = frac - (double)bits; - frac = ldexp(frac, PyLong_SHIFT); - } - if (neg) - Py_SIZE(v) = -(Py_SIZE(v)); - return (PyObject *)v; + PyLongObject *v; + double frac; + int i, ndig, expo, neg; + neg = 0; + if (Py_IS_INFINITY(dval)) { + PyErr_SetString(PyExc_OverflowError, + "cannot convert float infinity to integer"); + return NULL; + } + if (Py_IS_NAN(dval)) { + PyErr_SetString(PyExc_ValueError, + "cannot convert float NaN to integer"); + return NULL; + } + if (dval < 0.0) { + neg = 1; + dval = -dval; + } + frac = frexp(dval, &expo); /* dval = frac*2**expo; 0.0 <= frac < 1.0 */ + if (expo <= 0) + return PyLong_FromLong(0L); + ndig = (expo-1) / PyLong_SHIFT + 1; /* Number of 'digits' in result */ + v = _PyLong_New(ndig); + if (v == NULL) + return NULL; + frac = ldexp(frac, (expo-1) % PyLong_SHIFT + 1); + for (i = ndig; --i >= 0; ) { + digit bits = (digit)frac; + v->ob_digit[i] = bits; + frac = frac - (double)bits; + frac = ldexp(frac, PyLong_SHIFT); + } + if (neg) + Py_SIZE(v) = -(Py_SIZE(v)); + return (PyObject *)v; } /* Checking for overflow in PyLong_AsLong is a PITA since C doesn't define @@ -318,8 +318,8 @@ * However, some other compilers warn about applying unary minus to an * unsigned operand. Hence the weird "0-". */ -#define PY_ABS_LONG_MIN (0-(unsigned long)LONG_MIN) -#define PY_ABS_SSIZE_T_MIN (0-(size_t)PY_SSIZE_T_MIN) +#define PY_ABS_LONG_MIN (0-(unsigned long)LONG_MIN) +#define PY_ABS_SSIZE_T_MIN (0-(size_t)PY_SSIZE_T_MIN) /* Get a C long int from a long int object. Returns -1 and sets an error condition if overflow occurs. */ @@ -327,102 +327,102 @@ long PyLong_AsLongAndOverflow(PyObject *vv, int *overflow) { - /* This version by Tim Peters */ - register PyLongObject *v; - unsigned long x, prev; - long res; - Py_ssize_t i; - int sign; - int do_decref = 0; /* if nb_int was called */ - - *overflow = 0; - if (vv == NULL) { - PyErr_BadInternalCall(); - return -1; - } - - if (!PyLong_Check(vv)) { - PyNumberMethods *nb; - nb = vv->ob_type->tp_as_number; - if (nb == NULL || nb->nb_int == NULL) { - PyErr_SetString(PyExc_TypeError, - "an integer is required"); - return -1; - } - vv = (*nb->nb_int) (vv); - if (vv == NULL) - return -1; - do_decref = 1; - if (!PyLong_Check(vv)) { - Py_DECREF(vv); - PyErr_SetString(PyExc_TypeError, - "nb_int should return int object"); - return -1; - } - } - - res = -1; - v = (PyLongObject *)vv; - i = Py_SIZE(v); - - switch (i) { - case -1: - res = -(sdigit)v->ob_digit[0]; - break; - case 0: - res = 0; - break; - case 1: - res = v->ob_digit[0]; - break; - default: - sign = 1; - x = 0; - if (i < 0) { - sign = -1; - i = -(i); - } - while (--i >= 0) { - prev = x; - x = (x << PyLong_SHIFT) | v->ob_digit[i]; - if ((x >> PyLong_SHIFT) != prev) { - *overflow = sign; - goto exit; - } - } - /* Haven't lost any bits, but casting to long requires extra - * care (see comment above). - */ - if (x <= (unsigned long)LONG_MAX) { - res = (long)x * sign; - } - else if (sign < 0 && x == PY_ABS_LONG_MIN) { - res = LONG_MIN; - } - else { - *overflow = sign; - /* res is already set to -1 */ - } - } + /* This version by Tim Peters */ + register PyLongObject *v; + unsigned long x, prev; + long res; + Py_ssize_t i; + int sign; + int do_decref = 0; /* if nb_int was called */ + + *overflow = 0; + if (vv == NULL) { + PyErr_BadInternalCall(); + return -1; + } + + if (!PyLong_Check(vv)) { + PyNumberMethods *nb; + nb = vv->ob_type->tp_as_number; + if (nb == NULL || nb->nb_int == NULL) { + PyErr_SetString(PyExc_TypeError, + "an integer is required"); + return -1; + } + vv = (*nb->nb_int) (vv); + if (vv == NULL) + return -1; + do_decref = 1; + if (!PyLong_Check(vv)) { + Py_DECREF(vv); + PyErr_SetString(PyExc_TypeError, + "nb_int should return int object"); + return -1; + } + } + + res = -1; + v = (PyLongObject *)vv; + i = Py_SIZE(v); + + switch (i) { + case -1: + res = -(sdigit)v->ob_digit[0]; + break; + case 0: + res = 0; + break; + case 1: + res = v->ob_digit[0]; + break; + default: + sign = 1; + x = 0; + if (i < 0) { + sign = -1; + i = -(i); + } + while (--i >= 0) { + prev = x; + x = (x << PyLong_SHIFT) | v->ob_digit[i]; + if ((x >> PyLong_SHIFT) != prev) { + *overflow = sign; + goto exit; + } + } + /* Haven't lost any bits, but casting to long requires extra + * care (see comment above). + */ + if (x <= (unsigned long)LONG_MAX) { + res = (long)x * sign; + } + else if (sign < 0 && x == PY_ABS_LONG_MIN) { + res = LONG_MIN; + } + else { + *overflow = sign; + /* res is already set to -1 */ + } + } exit: - if (do_decref) { - Py_DECREF(vv); - } - return res; + if (do_decref) { + Py_DECREF(vv); + } + return res; } -long +long PyLong_AsLong(PyObject *obj) { - int overflow; - long result = PyLong_AsLongAndOverflow(obj, &overflow); - if (overflow) { - /* XXX: could be cute and give a different - message for overflow == -1 */ - PyErr_SetString(PyExc_OverflowError, - "Python int too large to convert to C long"); - } - return result; + int overflow; + long result = PyLong_AsLongAndOverflow(obj, &overflow); + if (overflow) { + /* XXX: could be cute and give a different + message for overflow == -1 */ + PyErr_SetString(PyExc_OverflowError, + "Python int too large to convert to C long"); + } + return result; } /* Get a Py_ssize_t from a long int object. @@ -430,54 +430,54 @@ Py_ssize_t PyLong_AsSsize_t(PyObject *vv) { - register PyLongObject *v; - size_t x, prev; - Py_ssize_t i; - int sign; - - if (vv == NULL) { - PyErr_BadInternalCall(); - return -1; - } - if (!PyLong_Check(vv)) { - PyErr_SetString(PyExc_TypeError, "an integer is required"); - return -1; - } - - v = (PyLongObject *)vv; - i = Py_SIZE(v); - switch (i) { - case -1: return -(sdigit)v->ob_digit[0]; - case 0: return 0; - case 1: return v->ob_digit[0]; - } - sign = 1; - x = 0; - if (i < 0) { - sign = -1; - i = -(i); - } - while (--i >= 0) { - prev = x; - x = (x << PyLong_SHIFT) | v->ob_digit[i]; - if ((x >> PyLong_SHIFT) != prev) - goto overflow; - } - /* Haven't lost any bits, but casting to a signed type requires - * extra care (see comment above). - */ - if (x <= (size_t)PY_SSIZE_T_MAX) { - return (Py_ssize_t)x * sign; - } - else if (sign < 0 && x == PY_ABS_SSIZE_T_MIN) { - return PY_SSIZE_T_MIN; - } - /* else overflow */ + register PyLongObject *v; + size_t x, prev; + Py_ssize_t i; + int sign; + + if (vv == NULL) { + PyErr_BadInternalCall(); + return -1; + } + if (!PyLong_Check(vv)) { + PyErr_SetString(PyExc_TypeError, "an integer is required"); + return -1; + } + + v = (PyLongObject *)vv; + i = Py_SIZE(v); + switch (i) { + case -1: return -(sdigit)v->ob_digit[0]; + case 0: return 0; + case 1: return v->ob_digit[0]; + } + sign = 1; + x = 0; + if (i < 0) { + sign = -1; + i = -(i); + } + while (--i >= 0) { + prev = x; + x = (x << PyLong_SHIFT) | v->ob_digit[i]; + if ((x >> PyLong_SHIFT) != prev) + goto overflow; + } + /* Haven't lost any bits, but casting to a signed type requires + * extra care (see comment above). + */ + if (x <= (size_t)PY_SSIZE_T_MAX) { + return (Py_ssize_t)x * sign; + } + else if (sign < 0 && x == PY_ABS_SSIZE_T_MIN) { + return PY_SSIZE_T_MIN; + } + /* else overflow */ overflow: - PyErr_SetString(PyExc_OverflowError, - "Python int too large to convert to C ssize_t"); - return -1; + PyErr_SetString(PyExc_OverflowError, + "Python int too large to convert to C ssize_t"); + return -1; } /* Get a C unsigned long int from a long int object. @@ -486,41 +486,41 @@ unsigned long PyLong_AsUnsignedLong(PyObject *vv) { - register PyLongObject *v; - unsigned long x, prev; - Py_ssize_t i; - - if (vv == NULL) { - PyErr_BadInternalCall(); - return (unsigned long)-1; - } - if (!PyLong_Check(vv)) { - PyErr_SetString(PyExc_TypeError, "an integer is required"); - return (unsigned long)-1; - } - - v = (PyLongObject *)vv; - i = Py_SIZE(v); - x = 0; - if (i < 0) { - PyErr_SetString(PyExc_OverflowError, - "can't convert negative value to unsigned int"); - return (unsigned long) -1; - } - switch (i) { - case 0: return 0; - case 1: return v->ob_digit[0]; - } - while (--i >= 0) { - prev = x; - x = (x << PyLong_SHIFT) | v->ob_digit[i]; - if ((x >> PyLong_SHIFT) != prev) { - PyErr_SetString(PyExc_OverflowError, - "python int too large to convert to C unsigned long"); - return (unsigned long) -1; - } - } - return x; + register PyLongObject *v; + unsigned long x, prev; + Py_ssize_t i; + + if (vv == NULL) { + PyErr_BadInternalCall(); + return (unsigned long)-1; + } + if (!PyLong_Check(vv)) { + PyErr_SetString(PyExc_TypeError, "an integer is required"); + return (unsigned long)-1; + } + + v = (PyLongObject *)vv; + i = Py_SIZE(v); + x = 0; + if (i < 0) { + PyErr_SetString(PyExc_OverflowError, + "can't convert negative value to unsigned int"); + return (unsigned long) -1; + } + switch (i) { + case 0: return 0; + case 1: return v->ob_digit[0]; + } + while (--i >= 0) { + prev = x; + x = (x << PyLong_SHIFT) | v->ob_digit[i]; + if ((x >> PyLong_SHIFT) != prev) { + PyErr_SetString(PyExc_OverflowError, + "python int too large to convert to C unsigned long"); + return (unsigned long) -1; + } + } + return x; } /* Get a C unsigned long int from a long int object. @@ -529,41 +529,41 @@ size_t PyLong_AsSize_t(PyObject *vv) { - register PyLongObject *v; - size_t x, prev; - Py_ssize_t i; - - if (vv == NULL) { - PyErr_BadInternalCall(); - return (size_t) -1; - } - if (!PyLong_Check(vv)) { - PyErr_SetString(PyExc_TypeError, "an integer is required"); - return (size_t)-1; - } - - v = (PyLongObject *)vv; - i = Py_SIZE(v); - x = 0; - if (i < 0) { - PyErr_SetString(PyExc_OverflowError, - "can't convert negative value to size_t"); - return (size_t) -1; - } - switch (i) { - case 0: return 0; - case 1: return v->ob_digit[0]; - } - while (--i >= 0) { - prev = x; - x = (x << PyLong_SHIFT) | v->ob_digit[i]; - if ((x >> PyLong_SHIFT) != prev) { - PyErr_SetString(PyExc_OverflowError, - "Python int too large to convert to C size_t"); - return (unsigned long) -1; - } - } - return x; + register PyLongObject *v; + size_t x, prev; + Py_ssize_t i; + + if (vv == NULL) { + PyErr_BadInternalCall(); + return (size_t) -1; + } + if (!PyLong_Check(vv)) { + PyErr_SetString(PyExc_TypeError, "an integer is required"); + return (size_t)-1; + } + + v = (PyLongObject *)vv; + i = Py_SIZE(v); + x = 0; + if (i < 0) { + PyErr_SetString(PyExc_OverflowError, + "can't convert negative value to size_t"); + return (size_t) -1; + } + switch (i) { + case 0: return 0; + case 1: return v->ob_digit[0]; + } + while (--i >= 0) { + prev = x; + x = (x << PyLong_SHIFT) | v->ob_digit[i]; + if ((x >> PyLong_SHIFT) != prev) { + PyErr_SetString(PyExc_OverflowError, + "Python int too large to convert to C size_t"); + return (unsigned long) -1; + } + } + return x; } /* Get a C unsigned long int from a long int object, ignoring the high bits. @@ -572,354 +572,354 @@ static unsigned long _PyLong_AsUnsignedLongMask(PyObject *vv) { - register PyLongObject *v; - unsigned long x; - Py_ssize_t i; - int sign; - - if (vv == NULL || !PyLong_Check(vv)) { - PyErr_BadInternalCall(); - return (unsigned long) -1; - } - v = (PyLongObject *)vv; - i = Py_SIZE(v); - switch (i) { - case 0: return 0; - case 1: return v->ob_digit[0]; - } - sign = 1; - x = 0; - if (i < 0) { - sign = -1; - i = -i; - } - while (--i >= 0) { - x = (x << PyLong_SHIFT) | v->ob_digit[i]; - } - return x * sign; + register PyLongObject *v; + unsigned long x; + Py_ssize_t i; + int sign; + + if (vv == NULL || !PyLong_Check(vv)) { + PyErr_BadInternalCall(); + return (unsigned long) -1; + } + v = (PyLongObject *)vv; + i = Py_SIZE(v); + switch (i) { + case 0: return 0; + case 1: return v->ob_digit[0]; + } + sign = 1; + x = 0; + if (i < 0) { + sign = -1; + i = -i; + } + while (--i >= 0) { + x = (x << PyLong_SHIFT) | v->ob_digit[i]; + } + return x * sign; } unsigned long PyLong_AsUnsignedLongMask(register PyObject *op) { - PyNumberMethods *nb; - PyLongObject *lo; - unsigned long val; - - if (op && PyLong_Check(op)) - return _PyLong_AsUnsignedLongMask(op); - - if (op == NULL || (nb = op->ob_type->tp_as_number) == NULL || - nb->nb_int == NULL) { - PyErr_SetString(PyExc_TypeError, "an integer is required"); - return (unsigned long)-1; - } - - lo = (PyLongObject*) (*nb->nb_int) (op); - if (lo == NULL) - return (unsigned long)-1; - if (PyLong_Check(lo)) { - val = _PyLong_AsUnsignedLongMask((PyObject *)lo); - Py_DECREF(lo); - if (PyErr_Occurred()) - return (unsigned long)-1; - return val; - } - else - { - Py_DECREF(lo); - PyErr_SetString(PyExc_TypeError, - "nb_int should return int object"); - return (unsigned long)-1; - } + PyNumberMethods *nb; + PyLongObject *lo; + unsigned long val; + + if (op && PyLong_Check(op)) + return _PyLong_AsUnsignedLongMask(op); + + if (op == NULL || (nb = op->ob_type->tp_as_number) == NULL || + nb->nb_int == NULL) { + PyErr_SetString(PyExc_TypeError, "an integer is required"); + return (unsigned long)-1; + } + + lo = (PyLongObject*) (*nb->nb_int) (op); + if (lo == NULL) + return (unsigned long)-1; + if (PyLong_Check(lo)) { + val = _PyLong_AsUnsignedLongMask((PyObject *)lo); + Py_DECREF(lo); + if (PyErr_Occurred()) + return (unsigned long)-1; + return val; + } + else + { + Py_DECREF(lo); + PyErr_SetString(PyExc_TypeError, + "nb_int should return int object"); + return (unsigned long)-1; + } } int _PyLong_Sign(PyObject *vv) { - PyLongObject *v = (PyLongObject *)vv; + PyLongObject *v = (PyLongObject *)vv; - assert(v != NULL); - assert(PyLong_Check(v)); + assert(v != NULL); + assert(PyLong_Check(v)); - return Py_SIZE(v) == 0 ? 0 : (Py_SIZE(v) < 0 ? -1 : 1); + return Py_SIZE(v) == 0 ? 0 : (Py_SIZE(v) < 0 ? -1 : 1); } size_t _PyLong_NumBits(PyObject *vv) { - PyLongObject *v = (PyLongObject *)vv; - size_t result = 0; - Py_ssize_t ndigits; - - assert(v != NULL); - assert(PyLong_Check(v)); - ndigits = ABS(Py_SIZE(v)); - assert(ndigits == 0 || v->ob_digit[ndigits - 1] != 0); - if (ndigits > 0) { - digit msd = v->ob_digit[ndigits - 1]; - - result = (ndigits - 1) * PyLong_SHIFT; - if (result / PyLong_SHIFT != (size_t)(ndigits - 1)) - goto Overflow; - do { - ++result; - if (result == 0) - goto Overflow; - msd >>= 1; - } while (msd); - } - return result; + PyLongObject *v = (PyLongObject *)vv; + size_t result = 0; + Py_ssize_t ndigits; + + assert(v != NULL); + assert(PyLong_Check(v)); + ndigits = ABS(Py_SIZE(v)); + assert(ndigits == 0 || v->ob_digit[ndigits - 1] != 0); + if (ndigits > 0) { + digit msd = v->ob_digit[ndigits - 1]; + + result = (ndigits - 1) * PyLong_SHIFT; + if (result / PyLong_SHIFT != (size_t)(ndigits - 1)) + goto Overflow; + do { + ++result; + if (result == 0) + goto Overflow; + msd >>= 1; + } while (msd); + } + return result; Overflow: - PyErr_SetString(PyExc_OverflowError, "int has too many bits " - "to express in a platform size_t"); - return (size_t)-1; + PyErr_SetString(PyExc_OverflowError, "int has too many bits " + "to express in a platform size_t"); + return (size_t)-1; } PyObject * _PyLong_FromByteArray(const unsigned char* bytes, size_t n, - int little_endian, int is_signed) + int little_endian, int is_signed) { - const unsigned char* pstartbyte;/* LSB of bytes */ - int incr; /* direction to move pstartbyte */ - const unsigned char* pendbyte; /* MSB of bytes */ - size_t numsignificantbytes; /* number of bytes that matter */ - Py_ssize_t ndigits; /* number of Python long digits */ - PyLongObject* v; /* result */ - Py_ssize_t idigit = 0; /* next free index in v->ob_digit */ - - if (n == 0) - return PyLong_FromLong(0L); - - if (little_endian) { - pstartbyte = bytes; - pendbyte = bytes + n - 1; - incr = 1; - } - else { - pstartbyte = bytes + n - 1; - pendbyte = bytes; - incr = -1; - } - - if (is_signed) - is_signed = *pendbyte >= 0x80; - - /* Compute numsignificantbytes. This consists of finding the most - significant byte. Leading 0 bytes are insignficant if the number - is positive, and leading 0xff bytes if negative. */ - { - size_t i; - const unsigned char* p = pendbyte; - const int pincr = -incr; /* search MSB to LSB */ - const unsigned char insignficant = is_signed ? 0xff : 0x00; - - for (i = 0; i < n; ++i, p += pincr) { - if (*p != insignficant) - break; - } - numsignificantbytes = n - i; - /* 2's-comp is a bit tricky here, e.g. 0xff00 == -0x0100, so - actually has 2 significant bytes. OTOH, 0xff0001 == - -0x00ffff, so we wouldn't *need* to bump it there; but we - do for 0xffff = -0x0001. To be safe without bothering to - check every case, bump it regardless. */ - if (is_signed && numsignificantbytes < n) - ++numsignificantbytes; - } - - /* How many Python long digits do we need? We have - 8*numsignificantbytes bits, and each Python long digit has - PyLong_SHIFT bits, so it's the ceiling of the quotient. */ - /* catch overflow before it happens */ - if (numsignificantbytes > (PY_SSIZE_T_MAX - PyLong_SHIFT) / 8) { - PyErr_SetString(PyExc_OverflowError, - "byte array too long to convert to int"); - return NULL; - } - ndigits = (numsignificantbytes * 8 + PyLong_SHIFT - 1) / PyLong_SHIFT; - v = _PyLong_New(ndigits); - if (v == NULL) - return NULL; - - /* Copy the bits over. The tricky parts are computing 2's-comp on - the fly for signed numbers, and dealing with the mismatch between - 8-bit bytes and (probably) 15-bit Python digits.*/ - { - size_t i; - twodigits carry = 1; /* for 2's-comp calculation */ - twodigits accum = 0; /* sliding register */ - unsigned int accumbits = 0; /* number of bits in accum */ - const unsigned char* p = pstartbyte; - - for (i = 0; i < numsignificantbytes; ++i, p += incr) { - twodigits thisbyte = *p; - /* Compute correction for 2's comp, if needed. */ - if (is_signed) { - thisbyte = (0xff ^ thisbyte) + carry; - carry = thisbyte >> 8; - thisbyte &= 0xff; - } - /* Because we're going LSB to MSB, thisbyte is - more significant than what's already in accum, - so needs to be prepended to accum. */ - accum |= (twodigits)thisbyte << accumbits; - accumbits += 8; - if (accumbits >= PyLong_SHIFT) { - /* There's enough to fill a Python digit. */ - assert(idigit < ndigits); - v->ob_digit[idigit] = (digit)(accum & - PyLong_MASK); - ++idigit; - accum >>= PyLong_SHIFT; - accumbits -= PyLong_SHIFT; - assert(accumbits < PyLong_SHIFT); - } - } - assert(accumbits < PyLong_SHIFT); - if (accumbits) { - assert(idigit < ndigits); - v->ob_digit[idigit] = (digit)accum; - ++idigit; - } - } + const unsigned char* pstartbyte;/* LSB of bytes */ + int incr; /* direction to move pstartbyte */ + const unsigned char* pendbyte; /* MSB of bytes */ + size_t numsignificantbytes; /* number of bytes that matter */ + Py_ssize_t ndigits; /* number of Python long digits */ + PyLongObject* v; /* result */ + Py_ssize_t idigit = 0; /* next free index in v->ob_digit */ + + if (n == 0) + return PyLong_FromLong(0L); + + if (little_endian) { + pstartbyte = bytes; + pendbyte = bytes + n - 1; + incr = 1; + } + else { + pstartbyte = bytes + n - 1; + pendbyte = bytes; + incr = -1; + } + + if (is_signed) + is_signed = *pendbyte >= 0x80; + + /* Compute numsignificantbytes. This consists of finding the most + significant byte. Leading 0 bytes are insignficant if the number + is positive, and leading 0xff bytes if negative. */ + { + size_t i; + const unsigned char* p = pendbyte; + const int pincr = -incr; /* search MSB to LSB */ + const unsigned char insignficant = is_signed ? 0xff : 0x00; + + for (i = 0; i < n; ++i, p += pincr) { + if (*p != insignficant) + break; + } + numsignificantbytes = n - i; + /* 2's-comp is a bit tricky here, e.g. 0xff00 == -0x0100, so + actually has 2 significant bytes. OTOH, 0xff0001 == + -0x00ffff, so we wouldn't *need* to bump it there; but we + do for 0xffff = -0x0001. To be safe without bothering to + check every case, bump it regardless. */ + if (is_signed && numsignificantbytes < n) + ++numsignificantbytes; + } + + /* How many Python long digits do we need? We have + 8*numsignificantbytes bits, and each Python long digit has + PyLong_SHIFT bits, so it's the ceiling of the quotient. */ + /* catch overflow before it happens */ + if (numsignificantbytes > (PY_SSIZE_T_MAX - PyLong_SHIFT) / 8) { + PyErr_SetString(PyExc_OverflowError, + "byte array too long to convert to int"); + return NULL; + } + ndigits = (numsignificantbytes * 8 + PyLong_SHIFT - 1) / PyLong_SHIFT; + v = _PyLong_New(ndigits); + if (v == NULL) + return NULL; + + /* Copy the bits over. The tricky parts are computing 2's-comp on + the fly for signed numbers, and dealing with the mismatch between + 8-bit bytes and (probably) 15-bit Python digits.*/ + { + size_t i; + twodigits carry = 1; /* for 2's-comp calculation */ + twodigits accum = 0; /* sliding register */ + unsigned int accumbits = 0; /* number of bits in accum */ + const unsigned char* p = pstartbyte; + + for (i = 0; i < numsignificantbytes; ++i, p += incr) { + twodigits thisbyte = *p; + /* Compute correction for 2's comp, if needed. */ + if (is_signed) { + thisbyte = (0xff ^ thisbyte) + carry; + carry = thisbyte >> 8; + thisbyte &= 0xff; + } + /* Because we're going LSB to MSB, thisbyte is + more significant than what's already in accum, + so needs to be prepended to accum. */ + accum |= (twodigits)thisbyte << accumbits; + accumbits += 8; + if (accumbits >= PyLong_SHIFT) { + /* There's enough to fill a Python digit. */ + assert(idigit < ndigits); + v->ob_digit[idigit] = (digit)(accum & + PyLong_MASK); + ++idigit; + accum >>= PyLong_SHIFT; + accumbits -= PyLong_SHIFT; + assert(accumbits < PyLong_SHIFT); + } + } + assert(accumbits < PyLong_SHIFT); + if (accumbits) { + assert(idigit < ndigits); + v->ob_digit[idigit] = (digit)accum; + ++idigit; + } + } - Py_SIZE(v) = is_signed ? -idigit : idigit; - return (PyObject *)long_normalize(v); + Py_SIZE(v) = is_signed ? -idigit : idigit; + return (PyObject *)long_normalize(v); } int _PyLong_AsByteArray(PyLongObject* v, - unsigned char* bytes, size_t n, - int little_endian, int is_signed) + unsigned char* bytes, size_t n, + int little_endian, int is_signed) { - Py_ssize_t i; /* index into v->ob_digit */ - Py_ssize_t ndigits; /* |v->ob_size| */ - twodigits accum; /* sliding register */ - unsigned int accumbits; /* # bits in accum */ - int do_twos_comp; /* store 2's-comp? is_signed and v < 0 */ - digit carry; /* for computing 2's-comp */ - size_t j; /* # bytes filled */ - unsigned char* p; /* pointer to next byte in bytes */ - int pincr; /* direction to move p */ - - assert(v != NULL && PyLong_Check(v)); - - if (Py_SIZE(v) < 0) { - ndigits = -(Py_SIZE(v)); - if (!is_signed) { - PyErr_SetString(PyExc_OverflowError, - "can't convert negative int to unsigned"); - return -1; - } - do_twos_comp = 1; - } - else { - ndigits = Py_SIZE(v); - do_twos_comp = 0; - } - - if (little_endian) { - p = bytes; - pincr = 1; - } - else { - p = bytes + n - 1; - pincr = -1; - } - - /* Copy over all the Python digits. - It's crucial that every Python digit except for the MSD contribute - exactly PyLong_SHIFT bits to the total, so first assert that the long is - normalized. */ - assert(ndigits == 0 || v->ob_digit[ndigits - 1] != 0); - j = 0; - accum = 0; - accumbits = 0; - carry = do_twos_comp ? 1 : 0; - for (i = 0; i < ndigits; ++i) { - digit thisdigit = v->ob_digit[i]; - if (do_twos_comp) { - thisdigit = (thisdigit ^ PyLong_MASK) + carry; - carry = thisdigit >> PyLong_SHIFT; - thisdigit &= PyLong_MASK; - } - /* Because we're going LSB to MSB, thisdigit is more - significant than what's already in accum, so needs to be - prepended to accum. */ - accum |= (twodigits)thisdigit << accumbits; - - /* The most-significant digit may be (probably is) at least - partly empty. */ - if (i == ndigits - 1) { - /* Count # of sign bits -- they needn't be stored, - * although for signed conversion we need later to - * make sure at least one sign bit gets stored. */ - digit s = do_twos_comp ? thisdigit ^ PyLong_MASK : - thisdigit; - while (s != 0) { - s >>= 1; - accumbits++; - } - } - else - accumbits += PyLong_SHIFT; - - /* Store as many bytes as possible. */ - while (accumbits >= 8) { - if (j >= n) - goto Overflow; - ++j; - *p = (unsigned char)(accum & 0xff); - p += pincr; - accumbits -= 8; - accum >>= 8; - } - } - - /* Store the straggler (if any). */ - assert(accumbits < 8); - assert(carry == 0); /* else do_twos_comp and *every* digit was 0 */ - if (accumbits > 0) { - if (j >= n) - goto Overflow; - ++j; - if (do_twos_comp) { - /* Fill leading bits of the byte with sign bits - (appropriately pretending that the long had an - infinite supply of sign bits). */ - accum |= (~(twodigits)0) << accumbits; - } - *p = (unsigned char)(accum & 0xff); - p += pincr; - } - else if (j == n && n > 0 && is_signed) { - /* The main loop filled the byte array exactly, so the code - just above didn't get to ensure there's a sign bit, and the - loop below wouldn't add one either. Make sure a sign bit - exists. */ - unsigned char msb = *(p - pincr); - int sign_bit_set = msb >= 0x80; - assert(accumbits == 0); - if (sign_bit_set == do_twos_comp) - return 0; - else - goto Overflow; - } - - /* Fill remaining bytes with copies of the sign bit. */ - { - unsigned char signbyte = do_twos_comp ? 0xffU : 0U; - for ( ; j < n; ++j, p += pincr) - *p = signbyte; - } + Py_ssize_t i; /* index into v->ob_digit */ + Py_ssize_t ndigits; /* |v->ob_size| */ + twodigits accum; /* sliding register */ + unsigned int accumbits; /* # bits in accum */ + int do_twos_comp; /* store 2's-comp? is_signed and v < 0 */ + digit carry; /* for computing 2's-comp */ + size_t j; /* # bytes filled */ + unsigned char* p; /* pointer to next byte in bytes */ + int pincr; /* direction to move p */ + + assert(v != NULL && PyLong_Check(v)); + + if (Py_SIZE(v) < 0) { + ndigits = -(Py_SIZE(v)); + if (!is_signed) { + PyErr_SetString(PyExc_OverflowError, + "can't convert negative int to unsigned"); + return -1; + } + do_twos_comp = 1; + } + else { + ndigits = Py_SIZE(v); + do_twos_comp = 0; + } + + if (little_endian) { + p = bytes; + pincr = 1; + } + else { + p = bytes + n - 1; + pincr = -1; + } + + /* Copy over all the Python digits. + It's crucial that every Python digit except for the MSD contribute + exactly PyLong_SHIFT bits to the total, so first assert that the long is + normalized. */ + assert(ndigits == 0 || v->ob_digit[ndigits - 1] != 0); + j = 0; + accum = 0; + accumbits = 0; + carry = do_twos_comp ? 1 : 0; + for (i = 0; i < ndigits; ++i) { + digit thisdigit = v->ob_digit[i]; + if (do_twos_comp) { + thisdigit = (thisdigit ^ PyLong_MASK) + carry; + carry = thisdigit >> PyLong_SHIFT; + thisdigit &= PyLong_MASK; + } + /* Because we're going LSB to MSB, thisdigit is more + significant than what's already in accum, so needs to be + prepended to accum. */ + accum |= (twodigits)thisdigit << accumbits; + + /* The most-significant digit may be (probably is) at least + partly empty. */ + if (i == ndigits - 1) { + /* Count # of sign bits -- they needn't be stored, + * although for signed conversion we need later to + * make sure at least one sign bit gets stored. */ + digit s = do_twos_comp ? thisdigit ^ PyLong_MASK : + thisdigit; + while (s != 0) { + s >>= 1; + accumbits++; + } + } + else + accumbits += PyLong_SHIFT; + + /* Store as many bytes as possible. */ + while (accumbits >= 8) { + if (j >= n) + goto Overflow; + ++j; + *p = (unsigned char)(accum & 0xff); + p += pincr; + accumbits -= 8; + accum >>= 8; + } + } + + /* Store the straggler (if any). */ + assert(accumbits < 8); + assert(carry == 0); /* else do_twos_comp and *every* digit was 0 */ + if (accumbits > 0) { + if (j >= n) + goto Overflow; + ++j; + if (do_twos_comp) { + /* Fill leading bits of the byte with sign bits + (appropriately pretending that the long had an + infinite supply of sign bits). */ + accum |= (~(twodigits)0) << accumbits; + } + *p = (unsigned char)(accum & 0xff); + p += pincr; + } + else if (j == n && n > 0 && is_signed) { + /* The main loop filled the byte array exactly, so the code + just above didn't get to ensure there's a sign bit, and the + loop below wouldn't add one either. Make sure a sign bit + exists. */ + unsigned char msb = *(p - pincr); + int sign_bit_set = msb >= 0x80; + assert(accumbits == 0); + if (sign_bit_set == do_twos_comp) + return 0; + else + goto Overflow; + } + + /* Fill remaining bytes with copies of the sign bit. */ + { + unsigned char signbyte = do_twos_comp ? 0xffU : 0U; + for ( ; j < n; ++j, p += pincr) + *p = signbyte; + } - return 0; + return 0; Overflow: - PyErr_SetString(PyExc_OverflowError, "int too big to convert"); - return -1; + PyErr_SetString(PyExc_OverflowError, "int too big to convert"); + return -1; } @@ -934,10 +934,10 @@ #if SIZEOF_LONG_LONG < SIZEOF_VOID_P # error "PyLong_FromVoidPtr: sizeof(PY_LONG_LONG) < sizeof(void*)" #endif - /* special-case null pointer */ - if (!p) - return PyLong_FromLong(0); - return PyLong_FromUnsignedLongLong((unsigned PY_LONG_LONG)(Py_uintptr_t)p); + /* special-case null pointer */ + if (!p) + return PyLong_FromLong(0); + return PyLong_FromUnsignedLongLong((unsigned PY_LONG_LONG)(Py_uintptr_t)p); } @@ -946,17 +946,17 @@ void * PyLong_AsVoidPtr(PyObject *vv) { - /* This function will allow int or long objects. If vv is neither, - then the PyLong_AsLong*() functions will raise the exception: - PyExc_SystemError, "bad argument to internal function" - */ + /* This function will allow int or long objects. If vv is neither, + then the PyLong_AsLong*() functions will raise the exception: + PyExc_SystemError, "bad argument to internal function" + */ #if SIZEOF_VOID_P <= SIZEOF_LONG - long x; + long x; - if (PyLong_Check(vv) && _PyLong_Sign(vv) < 0) - x = PyLong_AsLong(vv); - else - x = PyLong_AsUnsignedLong(vv); + if (PyLong_Check(vv) && _PyLong_Sign(vv) < 0) + x = PyLong_AsLong(vv); + else + x = PyLong_AsUnsignedLong(vv); #else #ifndef HAVE_LONG_LONG @@ -965,18 +965,18 @@ #if SIZEOF_LONG_LONG < SIZEOF_VOID_P # error "PyLong_AsVoidPtr: sizeof(PY_LONG_LONG) < sizeof(void*)" #endif - PY_LONG_LONG x; + PY_LONG_LONG x; - if (PyLong_Check(vv) && _PyLong_Sign(vv) < 0) - x = PyLong_AsLongLong(vv); - else - x = PyLong_AsUnsignedLongLong(vv); + if (PyLong_Check(vv) && _PyLong_Sign(vv) < 0) + x = PyLong_AsLongLong(vv); + else + x = PyLong_AsUnsignedLongLong(vv); #endif /* SIZEOF_VOID_P <= SIZEOF_LONG */ - if (x == -1 && PyErr_Occurred()) - return NULL; - return (void *)x; + if (x == -1 && PyErr_Occurred()) + return NULL; + return (void *)x; } #ifdef HAVE_LONG_LONG @@ -986,50 +986,50 @@ */ #define IS_LITTLE_ENDIAN (int)*(unsigned char*)&one -#define PY_ABS_LLONG_MIN (0-(unsigned PY_LONG_LONG)PY_LLONG_MIN) +#define PY_ABS_LLONG_MIN (0-(unsigned PY_LONG_LONG)PY_LLONG_MIN) /* Create a new long int object from a C PY_LONG_LONG int. */ PyObject * PyLong_FromLongLong(PY_LONG_LONG ival) { - PyLongObject *v; - unsigned PY_LONG_LONG abs_ival; - unsigned PY_LONG_LONG t; /* unsigned so >> doesn't propagate sign bit */ - int ndigits = 0; - int negative = 0; - - CHECK_SMALL_INT(ival); - if (ival < 0) { - /* avoid signed overflow on negation; see comments - in PyLong_FromLong above. */ - abs_ival = (unsigned PY_LONG_LONG)(-1-ival) + 1; - negative = 1; - } - else { - abs_ival = (unsigned PY_LONG_LONG)ival; - } - - /* Count the number of Python digits. - We used to pick 5 ("big enough for anything"), but that's a - waste of time and space given that 5*15 = 75 bits are rarely - needed. */ - t = abs_ival; - while (t) { - ++ndigits; - t >>= PyLong_SHIFT; - } - v = _PyLong_New(ndigits); - if (v != NULL) { - digit *p = v->ob_digit; - Py_SIZE(v) = negative ? -ndigits : ndigits; - t = abs_ival; - while (t) { - *p++ = (digit)(t & PyLong_MASK); - t >>= PyLong_SHIFT; - } - } - return (PyObject *)v; + PyLongObject *v; + unsigned PY_LONG_LONG abs_ival; + unsigned PY_LONG_LONG t; /* unsigned so >> doesn't propagate sign bit */ + int ndigits = 0; + int negative = 0; + + CHECK_SMALL_INT(ival); + if (ival < 0) { + /* avoid signed overflow on negation; see comments + in PyLong_FromLong above. */ + abs_ival = (unsigned PY_LONG_LONG)(-1-ival) + 1; + negative = 1; + } + else { + abs_ival = (unsigned PY_LONG_LONG)ival; + } + + /* Count the number of Python digits. + We used to pick 5 ("big enough for anything"), but that's a + waste of time and space given that 5*15 = 75 bits are rarely + needed. */ + t = abs_ival; + while (t) { + ++ndigits; + t >>= PyLong_SHIFT; + } + v = _PyLong_New(ndigits); + if (v != NULL) { + digit *p = v->ob_digit; + Py_SIZE(v) = negative ? -ndigits : ndigits; + t = abs_ival; + while (t) { + *p++ = (digit)(t & PyLong_MASK); + t >>= PyLong_SHIFT; + } + } + return (PyObject *)v; } /* Create a new long int object from a C unsigned PY_LONG_LONG int. */ @@ -1037,28 +1037,28 @@ PyObject * PyLong_FromUnsignedLongLong(unsigned PY_LONG_LONG ival) { - PyLongObject *v; - unsigned PY_LONG_LONG t; - int ndigits = 0; - - if (ival < PyLong_BASE) - return PyLong_FromLong((long)ival); - /* Count the number of Python digits. */ - t = (unsigned PY_LONG_LONG)ival; - while (t) { - ++ndigits; - t >>= PyLong_SHIFT; - } - v = _PyLong_New(ndigits); - if (v != NULL) { - digit *p = v->ob_digit; - Py_SIZE(v) = ndigits; - while (ival) { - *p++ = (digit)(ival & PyLong_MASK); - ival >>= PyLong_SHIFT; - } - } - return (PyObject *)v; + PyLongObject *v; + unsigned PY_LONG_LONG t; + int ndigits = 0; + + if (ival < PyLong_BASE) + return PyLong_FromLong((long)ival); + /* Count the number of Python digits. */ + t = (unsigned PY_LONG_LONG)ival; + while (t) { + ++ndigits; + t >>= PyLong_SHIFT; + } + v = _PyLong_New(ndigits); + if (v != NULL) { + digit *p = v->ob_digit; + Py_SIZE(v) = ndigits; + while (ival) { + *p++ = (digit)(ival & PyLong_MASK); + ival >>= PyLong_SHIFT; + } + } + return (PyObject *)v; } /* Create a new long int object from a C Py_ssize_t. */ @@ -1066,39 +1066,39 @@ PyObject * PyLong_FromSsize_t(Py_ssize_t ival) { - PyLongObject *v; - size_t abs_ival; - size_t t; /* unsigned so >> doesn't propagate sign bit */ - int ndigits = 0; - int negative = 0; - - CHECK_SMALL_INT(ival); - if (ival < 0) { - /* avoid signed overflow when ival = SIZE_T_MIN */ - abs_ival = (size_t)(-1-ival)+1; - negative = 1; - } - else { - abs_ival = (size_t)ival; - } - - /* Count the number of Python digits. */ - t = abs_ival; - while (t) { - ++ndigits; - t >>= PyLong_SHIFT; - } - v = _PyLong_New(ndigits); - if (v != NULL) { - digit *p = v->ob_digit; - Py_SIZE(v) = negative ? -ndigits : ndigits; - t = abs_ival; - while (t) { - *p++ = (digit)(t & PyLong_MASK); - t >>= PyLong_SHIFT; - } - } - return (PyObject *)v; + PyLongObject *v; + size_t abs_ival; + size_t t; /* unsigned so >> doesn't propagate sign bit */ + int ndigits = 0; + int negative = 0; + + CHECK_SMALL_INT(ival); + if (ival < 0) { + /* avoid signed overflow when ival = SIZE_T_MIN */ + abs_ival = (size_t)(-1-ival)+1; + negative = 1; + } + else { + abs_ival = (size_t)ival; + } + + /* Count the number of Python digits. */ + t = abs_ival; + while (t) { + ++ndigits; + t >>= PyLong_SHIFT; + } + v = _PyLong_New(ndigits); + if (v != NULL) { + digit *p = v->ob_digit; + Py_SIZE(v) = negative ? -ndigits : ndigits; + t = abs_ival; + while (t) { + *p++ = (digit)(t & PyLong_MASK); + t >>= PyLong_SHIFT; + } + } + return (PyObject *)v; } /* Create a new long int object from a C size_t. */ @@ -1106,28 +1106,28 @@ PyObject * PyLong_FromSize_t(size_t ival) { - PyLongObject *v; - size_t t; - int ndigits = 0; - - if (ival < PyLong_BASE) - return PyLong_FromLong((long)ival); - /* Count the number of Python digits. */ - t = ival; - while (t) { - ++ndigits; - t >>= PyLong_SHIFT; - } - v = _PyLong_New(ndigits); - if (v != NULL) { - digit *p = v->ob_digit; - Py_SIZE(v) = ndigits; - while (ival) { - *p++ = (digit)(ival & PyLong_MASK); - ival >>= PyLong_SHIFT; - } - } - return (PyObject *)v; + PyLongObject *v; + size_t t; + int ndigits = 0; + + if (ival < PyLong_BASE) + return PyLong_FromLong((long)ival); + /* Count the number of Python digits. */ + t = ival; + while (t) { + ++ndigits; + t >>= PyLong_SHIFT; + } + v = _PyLong_New(ndigits); + if (v != NULL) { + digit *p = v->ob_digit; + Py_SIZE(v) = ndigits; + while (ival) { + *p++ = (digit)(ival & PyLong_MASK); + ival >>= PyLong_SHIFT; + } + } + return (PyObject *)v; } /* Get a C PY_LONG_LONG int from a long int object. @@ -1136,51 +1136,51 @@ PY_LONG_LONG PyLong_AsLongLong(PyObject *vv) { - PyLongObject *v; - PY_LONG_LONG bytes; - int one = 1; - int res; - - if (vv == NULL) { - PyErr_BadInternalCall(); - return -1; - } - if (!PyLong_Check(vv)) { - PyNumberMethods *nb; - PyObject *io; - if ((nb = vv->ob_type->tp_as_number) == NULL || - nb->nb_int == NULL) { - PyErr_SetString(PyExc_TypeError, "an integer is required"); - return -1; - } - io = (*nb->nb_int) (vv); - if (io == NULL) - return -1; - if (PyLong_Check(io)) { - bytes = PyLong_AsLongLong(io); - Py_DECREF(io); - return bytes; - } - Py_DECREF(io); - PyErr_SetString(PyExc_TypeError, "integer conversion failed"); - return -1; - } - - v = (PyLongObject*)vv; - switch(Py_SIZE(v)) { - case -1: return -(sdigit)v->ob_digit[0]; - case 0: return 0; - case 1: return v->ob_digit[0]; - } - res = _PyLong_AsByteArray( - (PyLongObject *)vv, (unsigned char *)&bytes, - SIZEOF_LONG_LONG, IS_LITTLE_ENDIAN, 1); - - /* Plan 9 can't handle PY_LONG_LONG in ? : expressions */ - if (res < 0) - return (PY_LONG_LONG)-1; - else - return bytes; + PyLongObject *v; + PY_LONG_LONG bytes; + int one = 1; + int res; + + if (vv == NULL) { + PyErr_BadInternalCall(); + return -1; + } + if (!PyLong_Check(vv)) { + PyNumberMethods *nb; + PyObject *io; + if ((nb = vv->ob_type->tp_as_number) == NULL || + nb->nb_int == NULL) { + PyErr_SetString(PyExc_TypeError, "an integer is required"); + return -1; + } + io = (*nb->nb_int) (vv); + if (io == NULL) + return -1; + if (PyLong_Check(io)) { + bytes = PyLong_AsLongLong(io); + Py_DECREF(io); + return bytes; + } + Py_DECREF(io); + PyErr_SetString(PyExc_TypeError, "integer conversion failed"); + return -1; + } + + v = (PyLongObject*)vv; + switch(Py_SIZE(v)) { + case -1: return -(sdigit)v->ob_digit[0]; + case 0: return 0; + case 1: return v->ob_digit[0]; + } + res = _PyLong_AsByteArray( + (PyLongObject *)vv, (unsigned char *)&bytes, + SIZEOF_LONG_LONG, IS_LITTLE_ENDIAN, 1); + + /* Plan 9 can't handle PY_LONG_LONG in ? : expressions */ + if (res < 0) + return (PY_LONG_LONG)-1; + else + return bytes; } /* Get a C unsigned PY_LONG_LONG int from a long int object. @@ -1189,31 +1189,31 @@ unsigned PY_LONG_LONG PyLong_AsUnsignedLongLong(PyObject *vv) { - PyLongObject *v; - unsigned PY_LONG_LONG bytes; - int one = 1; - int res; - - if (vv == NULL || !PyLong_Check(vv)) { - PyErr_BadInternalCall(); - return (unsigned PY_LONG_LONG)-1; - } - - v = (PyLongObject*)vv; - switch(Py_SIZE(v)) { - case 0: return 0; - case 1: return v->ob_digit[0]; - } - - res = _PyLong_AsByteArray( - (PyLongObject *)vv, (unsigned char *)&bytes, - SIZEOF_LONG_LONG, IS_LITTLE_ENDIAN, 0); - - /* Plan 9 can't handle PY_LONG_LONG in ? : expressions */ - if (res < 0) - return (unsigned PY_LONG_LONG)res; - else - return bytes; + PyLongObject *v; + unsigned PY_LONG_LONG bytes; + int one = 1; + int res; + + if (vv == NULL || !PyLong_Check(vv)) { + PyErr_BadInternalCall(); + return (unsigned PY_LONG_LONG)-1; + } + + v = (PyLongObject*)vv; + switch(Py_SIZE(v)) { + case 0: return 0; + case 1: return v->ob_digit[0]; + } + + res = _PyLong_AsByteArray( + (PyLongObject *)vv, (unsigned char *)&bytes, + SIZEOF_LONG_LONG, IS_LITTLE_ENDIAN, 0); + + /* Plan 9 can't handle PY_LONG_LONG in ? : expressions */ + if (res < 0) + return (unsigned PY_LONG_LONG)res; + else + return bytes; } /* Get a C unsigned long int from a long int object, ignoring the high bits. @@ -1222,66 +1222,66 @@ static unsigned PY_LONG_LONG _PyLong_AsUnsignedLongLongMask(PyObject *vv) { - register PyLongObject *v; - unsigned PY_LONG_LONG x; - Py_ssize_t i; - int sign; - - if (vv == NULL || !PyLong_Check(vv)) { - PyErr_BadInternalCall(); - return (unsigned long) -1; - } - v = (PyLongObject *)vv; - switch(Py_SIZE(v)) { - case 0: return 0; - case 1: return v->ob_digit[0]; - } - i = Py_SIZE(v); - sign = 1; - x = 0; - if (i < 0) { - sign = -1; - i = -i; - } - while (--i >= 0) { - x = (x << PyLong_SHIFT) | v->ob_digit[i]; - } - return x * sign; + register PyLongObject *v; + unsigned PY_LONG_LONG x; + Py_ssize_t i; + int sign; + + if (vv == NULL || !PyLong_Check(vv)) { + PyErr_BadInternalCall(); + return (unsigned long) -1; + } + v = (PyLongObject *)vv; + switch(Py_SIZE(v)) { + case 0: return 0; + case 1: return v->ob_digit[0]; + } + i = Py_SIZE(v); + sign = 1; + x = 0; + if (i < 0) { + sign = -1; + i = -i; + } + while (--i >= 0) { + x = (x << PyLong_SHIFT) | v->ob_digit[i]; + } + return x * sign; } unsigned PY_LONG_LONG PyLong_AsUnsignedLongLongMask(register PyObject *op) { - PyNumberMethods *nb; - PyLongObject *lo; - unsigned PY_LONG_LONG val; - - if (op && PyLong_Check(op)) - return _PyLong_AsUnsignedLongLongMask(op); - - if (op == NULL || (nb = op->ob_type->tp_as_number) == NULL || - nb->nb_int == NULL) { - PyErr_SetString(PyExc_TypeError, "an integer is required"); - return (unsigned PY_LONG_LONG)-1; - } - - lo = (PyLongObject*) (*nb->nb_int) (op); - if (lo == NULL) - return (unsigned PY_LONG_LONG)-1; - if (PyLong_Check(lo)) { - val = _PyLong_AsUnsignedLongLongMask((PyObject *)lo); - Py_DECREF(lo); - if (PyErr_Occurred()) - return (unsigned PY_LONG_LONG)-1; - return val; - } - else - { - Py_DECREF(lo); - PyErr_SetString(PyExc_TypeError, - "nb_int should return int object"); - return (unsigned PY_LONG_LONG)-1; - } + PyNumberMethods *nb; + PyLongObject *lo; + unsigned PY_LONG_LONG val; + + if (op && PyLong_Check(op)) + return _PyLong_AsUnsignedLongLongMask(op); + + if (op == NULL || (nb = op->ob_type->tp_as_number) == NULL || + nb->nb_int == NULL) { + PyErr_SetString(PyExc_TypeError, "an integer is required"); + return (unsigned PY_LONG_LONG)-1; + } + + lo = (PyLongObject*) (*nb->nb_int) (op); + if (lo == NULL) + return (unsigned PY_LONG_LONG)-1; + if (PyLong_Check(lo)) { + val = _PyLong_AsUnsignedLongLongMask((PyObject *)lo); + Py_DECREF(lo); + if (PyErr_Occurred()) + return (unsigned PY_LONG_LONG)-1; + return val; + } + else + { + Py_DECREF(lo); + PyErr_SetString(PyExc_TypeError, + "nb_int should return int object"); + return (unsigned PY_LONG_LONG)-1; + } } #undef IS_LITTLE_ENDIAN @@ -1296,116 +1296,116 @@ PY_LONG_LONG PyLong_AsLongLongAndOverflow(PyObject *vv, int *overflow) { - /* This version by Tim Peters */ - register PyLongObject *v; - unsigned PY_LONG_LONG x, prev; - PY_LONG_LONG res; - Py_ssize_t i; - int sign; - int do_decref = 0; /* if nb_int was called */ - - *overflow = 0; - if (vv == NULL) { - PyErr_BadInternalCall(); - return -1; - } - - if (!PyLong_Check(vv)) { - PyNumberMethods *nb; - nb = vv->ob_type->tp_as_number; - if (nb == NULL || nb->nb_int == NULL) { - PyErr_SetString(PyExc_TypeError, - "an integer is required"); - return -1; - } - vv = (*nb->nb_int) (vv); - if (vv == NULL) - return -1; - do_decref = 1; - if (!PyLong_Check(vv)) { - Py_DECREF(vv); - PyErr_SetString(PyExc_TypeError, - "nb_int should return int object"); - return -1; - } - } - - res = -1; - v = (PyLongObject *)vv; - i = Py_SIZE(v); - - switch (i) { - case -1: - res = -(sdigit)v->ob_digit[0]; - break; - case 0: - res = 0; - break; - case 1: - res = v->ob_digit[0]; - break; - default: - sign = 1; - x = 0; - if (i < 0) { - sign = -1; - i = -(i); - } - while (--i >= 0) { - prev = x; - x = (x << PyLong_SHIFT) + v->ob_digit[i]; - if ((x >> PyLong_SHIFT) != prev) { - *overflow = sign; - goto exit; - } - } - /* Haven't lost any bits, but casting to long requires extra - * care (see comment above). - */ - if (x <= (unsigned PY_LONG_LONG)PY_LLONG_MAX) { - res = (PY_LONG_LONG)x * sign; - } - else if (sign < 0 && x == PY_ABS_LLONG_MIN) { - res = PY_LLONG_MIN; - } - else { - *overflow = sign; - /* res is already set to -1 */ - } - } + /* This version by Tim Peters */ + register PyLongObject *v; + unsigned PY_LONG_LONG x, prev; + PY_LONG_LONG res; + Py_ssize_t i; + int sign; + int do_decref = 0; /* if nb_int was called */ + + *overflow = 0; + if (vv == NULL) { + PyErr_BadInternalCall(); + return -1; + } + + if (!PyLong_Check(vv)) { + PyNumberMethods *nb; + nb = vv->ob_type->tp_as_number; + if (nb == NULL || nb->nb_int == NULL) { + PyErr_SetString(PyExc_TypeError, + "an integer is required"); + return -1; + } + vv = (*nb->nb_int) (vv); + if (vv == NULL) + return -1; + do_decref = 1; + if (!PyLong_Check(vv)) { + Py_DECREF(vv); + PyErr_SetString(PyExc_TypeError, + "nb_int should return int object"); + return -1; + } + } + + res = -1; + v = (PyLongObject *)vv; + i = Py_SIZE(v); + + switch (i) { + case -1: + res = -(sdigit)v->ob_digit[0]; + break; + case 0: + res = 0; + break; + case 1: + res = v->ob_digit[0]; + break; + default: + sign = 1; + x = 0; + if (i < 0) { + sign = -1; + i = -(i); + } + while (--i >= 0) { + prev = x; + x = (x << PyLong_SHIFT) + v->ob_digit[i]; + if ((x >> PyLong_SHIFT) != prev) { + *overflow = sign; + goto exit; + } + } + /* Haven't lost any bits, but casting to long requires extra + * care (see comment above). + */ + if (x <= (unsigned PY_LONG_LONG)PY_LLONG_MAX) { + res = (PY_LONG_LONG)x * sign; + } + else if (sign < 0 && x == PY_ABS_LLONG_MIN) { + res = PY_LLONG_MIN; + } + else { + *overflow = sign; + /* res is already set to -1 */ + } + } exit: - if (do_decref) { - Py_DECREF(vv); - } - return res; + if (do_decref) { + Py_DECREF(vv); + } + return res; } #endif /* HAVE_LONG_LONG */ #define CHECK_BINOP(v,w) \ - if (!PyLong_Check(v) || !PyLong_Check(w)) { \ - Py_INCREF(Py_NotImplemented); \ - return Py_NotImplemented; \ - } + if (!PyLong_Check(v) || !PyLong_Check(w)) { \ + Py_INCREF(Py_NotImplemented); \ + return Py_NotImplemented; \ + } /* bits_in_digit(d) returns the unique integer k such that 2**(k-1) <= d < 2**k if d is nonzero, else 0. */ static const unsigned char BitLengthTable[32] = { - 0, 1, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 4, 4, 4, 4, - 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5 + 0, 1, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 4, 4, 4, 4, + 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5 }; static int bits_in_digit(digit d) { - int d_bits = 0; - while (d >= 32) { - d_bits += 6; - d >>= 6; - } - d_bits += (int)BitLengthTable[d]; - return d_bits; + int d_bits = 0; + while (d >= 32) { + d_bits += 6; + d >>= 6; + } + d_bits += (int)BitLengthTable[d]; + return d_bits; } /* x[0:m] and y[0:n] are digit vectors, LSD first, m >= n required. x[0:n] @@ -1415,23 +1415,23 @@ static digit v_iadd(digit *x, Py_ssize_t m, digit *y, Py_ssize_t n) { - Py_ssize_t i; - digit carry = 0; + Py_ssize_t i; + digit carry = 0; - assert(m >= n); - for (i = 0; i < n; ++i) { - carry += x[i] + y[i]; - x[i] = carry & PyLong_MASK; - carry >>= PyLong_SHIFT; - assert((carry & 1) == carry); - } - for (; carry && i < m; ++i) { - carry += x[i]; - x[i] = carry & PyLong_MASK; - carry >>= PyLong_SHIFT; - assert((carry & 1) == carry); - } - return carry; + assert(m >= n); + for (i = 0; i < n; ++i) { + carry += x[i] + y[i]; + x[i] = carry & PyLong_MASK; + carry >>= PyLong_SHIFT; + assert((carry & 1) == carry); + } + for (; carry && i < m; ++i) { + carry += x[i]; + x[i] = carry & PyLong_MASK; + carry >>= PyLong_SHIFT; + assert((carry & 1) == carry); + } + return carry; } /* x[0:m] and y[0:n] are digit vectors, LSD first, m >= n required. x[0:n] @@ -1441,23 +1441,23 @@ static digit v_isub(digit *x, Py_ssize_t m, digit *y, Py_ssize_t n) { - Py_ssize_t i; - digit borrow = 0; + Py_ssize_t i; + digit borrow = 0; - assert(m >= n); - for (i = 0; i < n; ++i) { - borrow = x[i] - y[i] - borrow; - x[i] = borrow & PyLong_MASK; - borrow >>= PyLong_SHIFT; - borrow &= 1; /* keep only 1 sign bit */ - } - for (; borrow && i < m; ++i) { - borrow = x[i] - borrow; - x[i] = borrow & PyLong_MASK; - borrow >>= PyLong_SHIFT; - borrow &= 1; - } - return borrow; + assert(m >= n); + for (i = 0; i < n; ++i) { + borrow = x[i] - y[i] - borrow; + x[i] = borrow & PyLong_MASK; + borrow >>= PyLong_SHIFT; + borrow &= 1; /* keep only 1 sign bit */ + } + for (; borrow && i < m; ++i) { + borrow = x[i] - borrow; + x[i] = borrow & PyLong_MASK; + borrow >>= PyLong_SHIFT; + borrow &= 1; + } + return borrow; } /* Shift digit vector a[0:m] d bits left, with 0 <= d < PyLong_SHIFT. Put @@ -1466,16 +1466,16 @@ static digit v_lshift(digit *z, digit *a, Py_ssize_t m, int d) { - Py_ssize_t i; - digit carry = 0; + Py_ssize_t i; + digit carry = 0; - assert(0 <= d && d < PyLong_SHIFT); - for (i=0; i < m; i++) { - twodigits acc = (twodigits)a[i] << d | carry; - z[i] = (digit)acc & PyLong_MASK; - carry = (digit)(acc >> PyLong_SHIFT); - } - return carry; + assert(0 <= d && d < PyLong_SHIFT); + for (i=0; i < m; i++) { + twodigits acc = (twodigits)a[i] << d | carry; + z[i] = (digit)acc & PyLong_MASK; + carry = (digit)(acc >> PyLong_SHIFT); + } + return carry; } /* Shift digit vector a[0:m] d bits right, with 0 <= d < PyLong_SHIFT. Put @@ -1484,17 +1484,17 @@ static digit v_rshift(digit *z, digit *a, Py_ssize_t m, int d) { - Py_ssize_t i; - digit carry = 0; - digit mask = ((digit)1 << d) - 1U; - - assert(0 <= d && d < PyLong_SHIFT); - for (i=m; i-- > 0;) { - twodigits acc = (twodigits)carry << PyLong_SHIFT | a[i]; - carry = (digit)acc & mask; - z[i] = (digit)(acc >> d); - } - return carry; + Py_ssize_t i; + digit carry = 0; + digit mask = ((digit)1 << d) - 1U; + + assert(0 <= d && d < PyLong_SHIFT); + for (i=m; i-- > 0;) { + twodigits acc = (twodigits)carry << PyLong_SHIFT | a[i]; + carry = (digit)acc & mask; + z[i] = (digit)(acc >> d); + } + return carry; } /* Divide long pin, w/ size digits, by non-zero digit n, storing quotient @@ -1506,18 +1506,18 @@ static digit inplace_divrem1(digit *pout, digit *pin, Py_ssize_t size, digit n) { - twodigits rem = 0; + twodigits rem = 0; - assert(n > 0 && n <= PyLong_MASK); - pin += size; - pout += size; - while (--size >= 0) { - digit hi; - rem = (rem << PyLong_SHIFT) | *--pin; - *--pout = hi = (digit)(rem / n); - rem -= (twodigits)hi * n; - } - return (digit)rem; + assert(n > 0 && n <= PyLong_MASK); + pin += size; + pout += size; + while (--size >= 0) { + digit hi; + rem = (rem << PyLong_SHIFT) | *--pin; + *--pout = hi = (digit)(rem / n); + rem -= (twodigits)hi * n; + } + return (digit)rem; } /* Divide a long integer by a digit, returning both the quotient @@ -1527,15 +1527,15 @@ static PyLongObject * divrem1(PyLongObject *a, digit n, digit *prem) { - const Py_ssize_t size = ABS(Py_SIZE(a)); - PyLongObject *z; + const Py_ssize_t size = ABS(Py_SIZE(a)); + PyLongObject *z; - assert(n > 0 && n <= PyLong_MASK); - z = _PyLong_New(size); - if (z == NULL) - return NULL; - *prem = inplace_divrem1(z->ob_digit, a->ob_digit, size, n); - return long_normalize(z); + assert(n > 0 && n <= PyLong_MASK); + z = _PyLong_New(size); + if (z == NULL) + return NULL; + *prem = inplace_divrem1(z->ob_digit, a->ob_digit, size, n); + return long_normalize(z); } /* Convert a long integer to a base 10 string. Returns a new non-shared @@ -1545,111 +1545,111 @@ static PyObject * long_to_decimal_string(PyObject *aa) { - PyLongObject *scratch, *a; - PyObject *str; - Py_ssize_t size, strlen, size_a, i, j; - digit *pout, *pin, rem, tenpow; - Py_UNICODE *p; - int negative; - - a = (PyLongObject *)aa; - if (a == NULL || !PyLong_Check(a)) { - PyErr_BadInternalCall(); - return NULL; - } - size_a = ABS(Py_SIZE(a)); - negative = Py_SIZE(a) < 0; - - /* quick and dirty upper bound for the number of digits - required to express a in base _PyLong_DECIMAL_BASE: - - #digits = 1 + floor(log2(a) / log2(_PyLong_DECIMAL_BASE)) - - But log2(a) < size_a * PyLong_SHIFT, and - log2(_PyLong_DECIMAL_BASE) = log2(10) * _PyLong_DECIMAL_SHIFT - > 3 * _PyLong_DECIMAL_SHIFT - */ - if (size_a > PY_SSIZE_T_MAX / PyLong_SHIFT) { - PyErr_SetString(PyExc_OverflowError, - "long is too large to format"); - return NULL; - } - /* the expression size_a * PyLong_SHIFT is now safe from overflow */ - size = 1 + size_a * PyLong_SHIFT / (3 * _PyLong_DECIMAL_SHIFT); - scratch = _PyLong_New(size); - if (scratch == NULL) - return NULL; - - /* convert array of base _PyLong_BASE digits in pin to an array of - base _PyLong_DECIMAL_BASE digits in pout, following Knuth (TAOCP, - Volume 2 (3rd edn), section 4.4, Method 1b). */ - pin = a->ob_digit; - pout = scratch->ob_digit; - size = 0; - for (i = size_a; --i >= 0; ) { - digit hi = pin[i]; - for (j = 0; j < size; j++) { - twodigits z = (twodigits)pout[j] << PyLong_SHIFT | hi; - hi = (digit)(z / _PyLong_DECIMAL_BASE); - pout[j] = (digit)(z - (twodigits)hi * - _PyLong_DECIMAL_BASE); - } - while (hi) { - pout[size++] = hi % _PyLong_DECIMAL_BASE; - hi /= _PyLong_DECIMAL_BASE; - } - /* check for keyboard interrupt */ - SIGCHECK({ - Py_DECREF(scratch); - return NULL; - }) - } - /* pout should have at least one digit, so that the case when a = 0 - works correctly */ - if (size == 0) - pout[size++] = 0; - - /* calculate exact length of output string, and allocate */ - strlen = negative + 1 + (size - 1) * _PyLong_DECIMAL_SHIFT; - tenpow = 10; - rem = pout[size-1]; - while (rem >= tenpow) { - tenpow *= 10; - strlen++; - } - str = PyUnicode_FromUnicode(NULL, strlen); - if (str == NULL) { - Py_DECREF(scratch); - return NULL; - } - - /* fill the string right-to-left */ - p = PyUnicode_AS_UNICODE(str) + strlen; - *p = '\0'; - /* pout[0] through pout[size-2] contribute exactly - _PyLong_DECIMAL_SHIFT digits each */ - for (i=0; i < size - 1; i++) { - rem = pout[i]; - for (j = 0; j < _PyLong_DECIMAL_SHIFT; j++) { - *--p = '0' + rem % 10; - rem /= 10; - } - } - /* pout[size-1]: always produce at least one decimal digit */ - rem = pout[i]; - do { - *--p = '0' + rem % 10; - rem /= 10; - } while (rem != 0); - - /* and sign */ - if (negative) - *--p = '-'; - - /* check we've counted correctly */ - assert(p == PyUnicode_AS_UNICODE(str)); - Py_DECREF(scratch); - return (PyObject *)str; + PyLongObject *scratch, *a; + PyObject *str; + Py_ssize_t size, strlen, size_a, i, j; + digit *pout, *pin, rem, tenpow; + Py_UNICODE *p; + int negative; + + a = (PyLongObject *)aa; + if (a == NULL || !PyLong_Check(a)) { + PyErr_BadInternalCall(); + return NULL; + } + size_a = ABS(Py_SIZE(a)); + negative = Py_SIZE(a) < 0; + + /* quick and dirty upper bound for the number of digits + required to express a in base _PyLong_DECIMAL_BASE: + + #digits = 1 + floor(log2(a) / log2(_PyLong_DECIMAL_BASE)) + + But log2(a) < size_a * PyLong_SHIFT, and + log2(_PyLong_DECIMAL_BASE) = log2(10) * _PyLong_DECIMAL_SHIFT + > 3 * _PyLong_DECIMAL_SHIFT + */ + if (size_a > PY_SSIZE_T_MAX / PyLong_SHIFT) { + PyErr_SetString(PyExc_OverflowError, + "long is too large to format"); + return NULL; + } + /* the expression size_a * PyLong_SHIFT is now safe from overflow */ + size = 1 + size_a * PyLong_SHIFT / (3 * _PyLong_DECIMAL_SHIFT); + scratch = _PyLong_New(size); + if (scratch == NULL) + return NULL; + + /* convert array of base _PyLong_BASE digits in pin to an array of + base _PyLong_DECIMAL_BASE digits in pout, following Knuth (TAOCP, + Volume 2 (3rd edn), section 4.4, Method 1b). */ + pin = a->ob_digit; + pout = scratch->ob_digit; + size = 0; + for (i = size_a; --i >= 0; ) { + digit hi = pin[i]; + for (j = 0; j < size; j++) { + twodigits z = (twodigits)pout[j] << PyLong_SHIFT | hi; + hi = (digit)(z / _PyLong_DECIMAL_BASE); + pout[j] = (digit)(z - (twodigits)hi * + _PyLong_DECIMAL_BASE); + } + while (hi) { + pout[size++] = hi % _PyLong_DECIMAL_BASE; + hi /= _PyLong_DECIMAL_BASE; + } + /* check for keyboard interrupt */ + SIGCHECK({ + Py_DECREF(scratch); + return NULL; + }) + } + /* pout should have at least one digit, so that the case when a = 0 + works correctly */ + if (size == 0) + pout[size++] = 0; + + /* calculate exact length of output string, and allocate */ + strlen = negative + 1 + (size - 1) * _PyLong_DECIMAL_SHIFT; + tenpow = 10; + rem = pout[size-1]; + while (rem >= tenpow) { + tenpow *= 10; + strlen++; + } + str = PyUnicode_FromUnicode(NULL, strlen); + if (str == NULL) { + Py_DECREF(scratch); + return NULL; + } + + /* fill the string right-to-left */ + p = PyUnicode_AS_UNICODE(str) + strlen; + *p = '\0'; + /* pout[0] through pout[size-2] contribute exactly + _PyLong_DECIMAL_SHIFT digits each */ + for (i=0; i < size - 1; i++) { + rem = pout[i]; + for (j = 0; j < _PyLong_DECIMAL_SHIFT; j++) { + *--p = '0' + rem % 10; + rem /= 10; + } + } + /* pout[size-1]: always produce at least one decimal digit */ + rem = pout[i]; + do { + *--p = '0' + rem % 10; + rem /= 10; + } while (rem != 0); + + /* and sign */ + if (negative) + *--p = '-'; + + /* check we've counted correctly */ + assert(p == PyUnicode_AS_UNICODE(str)); + Py_DECREF(scratch); + return (PyObject *)str; } /* Convert a long int object to a string, using a given conversion base, @@ -1659,102 +1659,102 @@ PyObject * _PyLong_Format(PyObject *aa, int base) { - register PyLongObject *a = (PyLongObject *)aa; - PyObject *str; - Py_ssize_t i, sz; - Py_ssize_t size_a; - Py_UNICODE *p, sign = '\0'; - int bits; - - assert(base == 2 || base == 8 || base == 10 || base == 16); - if (base == 10) - return long_to_decimal_string((PyObject *)a); - - if (a == NULL || !PyLong_Check(a)) { - PyErr_BadInternalCall(); - return NULL; - } - size_a = ABS(Py_SIZE(a)); - - /* Compute a rough upper bound for the length of the string */ - switch (base) { - case 16: - bits = 4; - break; - case 8: - bits = 3; - break; - case 2: - bits = 1; - break; - default: - assert(0); /* shouldn't ever get here */ - bits = 0; /* to silence gcc warning */ - } - /* compute length of output string: allow 2 characters for prefix and - 1 for possible '-' sign. */ - if (size_a > (PY_SSIZE_T_MAX - 3) / PyLong_SHIFT) { - PyErr_SetString(PyExc_OverflowError, - "int is too large to format"); - return NULL; - } - /* now size_a * PyLong_SHIFT + 3 <= PY_SSIZE_T_MAX, so the RHS below - is safe from overflow */ - sz = 3 + (size_a * PyLong_SHIFT + (bits - 1)) / bits; - assert(sz >= 0); - str = PyUnicode_FromUnicode(NULL, sz); - if (str == NULL) - return NULL; - p = PyUnicode_AS_UNICODE(str) + sz; - *p = '\0'; - if (Py_SIZE(a) < 0) - sign = '-'; - - if (Py_SIZE(a) == 0) { - *--p = '0'; - } - else { - /* JRH: special case for power-of-2 bases */ - twodigits accum = 0; - int accumbits = 0; /* # of bits in accum */ - for (i = 0; i < size_a; ++i) { - accum |= (twodigits)a->ob_digit[i] << accumbits; - accumbits += PyLong_SHIFT; - assert(accumbits >= bits); - do { - Py_UNICODE cdigit; - cdigit = (Py_UNICODE)(accum & (base - 1)); - cdigit += (cdigit < 10) ? '0' : 'a'-10; - assert(p > PyUnicode_AS_UNICODE(str)); - *--p = cdigit; - accumbits -= bits; - accum >>= bits; - } while (i < size_a-1 ? accumbits >= bits : accum > 0); - } - } - - if (base == 16) - *--p = 'x'; - else if (base == 8) - *--p = 'o'; - else /* (base == 2) */ - *--p = 'b'; - *--p = '0'; - if (sign) - *--p = sign; - if (p != PyUnicode_AS_UNICODE(str)) { - Py_UNICODE *q = PyUnicode_AS_UNICODE(str); - assert(p > q); - do { - } while ((*q++ = *p++) != '\0'); - q--; - if (PyUnicode_Resize(&str,(Py_ssize_t) (q - - PyUnicode_AS_UNICODE(str)))) { - Py_DECREF(str); - return NULL; - } - } - return (PyObject *)str; + register PyLongObject *a = (PyLongObject *)aa; + PyObject *str; + Py_ssize_t i, sz; + Py_ssize_t size_a; + Py_UNICODE *p, sign = '\0'; + int bits; + + assert(base == 2 || base == 8 || base == 10 || base == 16); + if (base == 10) + return long_to_decimal_string((PyObject *)a); + + if (a == NULL || !PyLong_Check(a)) { + PyErr_BadInternalCall(); + return NULL; + } + size_a = ABS(Py_SIZE(a)); + + /* Compute a rough upper bound for the length of the string */ + switch (base) { + case 16: + bits = 4; + break; + case 8: + bits = 3; + break; + case 2: + bits = 1; + break; + default: + assert(0); /* shouldn't ever get here */ + bits = 0; /* to silence gcc warning */ + } + /* compute length of output string: allow 2 characters for prefix and + 1 for possible '-' sign. */ + if (size_a > (PY_SSIZE_T_MAX - 3) / PyLong_SHIFT) { + PyErr_SetString(PyExc_OverflowError, + "int is too large to format"); + return NULL; + } + /* now size_a * PyLong_SHIFT + 3 <= PY_SSIZE_T_MAX, so the RHS below + is safe from overflow */ + sz = 3 + (size_a * PyLong_SHIFT + (bits - 1)) / bits; + assert(sz >= 0); + str = PyUnicode_FromUnicode(NULL, sz); + if (str == NULL) + return NULL; + p = PyUnicode_AS_UNICODE(str) + sz; + *p = '\0'; + if (Py_SIZE(a) < 0) + sign = '-'; + + if (Py_SIZE(a) == 0) { + *--p = '0'; + } + else { + /* JRH: special case for power-of-2 bases */ + twodigits accum = 0; + int accumbits = 0; /* # of bits in accum */ + for (i = 0; i < size_a; ++i) { + accum |= (twodigits)a->ob_digit[i] << accumbits; + accumbits += PyLong_SHIFT; + assert(accumbits >= bits); + do { + Py_UNICODE cdigit; + cdigit = (Py_UNICODE)(accum & (base - 1)); + cdigit += (cdigit < 10) ? '0' : 'a'-10; + assert(p > PyUnicode_AS_UNICODE(str)); + *--p = cdigit; + accumbits -= bits; + accum >>= bits; + } while (i < size_a-1 ? accumbits >= bits : accum > 0); + } + } + + if (base == 16) + *--p = 'x'; + else if (base == 8) + *--p = 'o'; + else /* (base == 2) */ + *--p = 'b'; + *--p = '0'; + if (sign) + *--p = sign; + if (p != PyUnicode_AS_UNICODE(str)) { + Py_UNICODE *q = PyUnicode_AS_UNICODE(str); + assert(p > q); + do { + } while ((*q++ = *p++) != '\0'); + q--; + if (PyUnicode_Resize(&str,(Py_ssize_t) (q - + PyUnicode_AS_UNICODE(str)))) { + Py_DECREF(str); + return NULL; + } + } + return (PyObject *)str; } /* Table of digit values for 8-bit string -> integer conversion. @@ -1765,22 +1765,22 @@ * base B digit iff _PyLong_DigitValue[Py_CHARPyLong_MASK(c)] < B. */ unsigned char _PyLong_DigitValue[256] = { - 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, - 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, - 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, - 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 37, 37, 37, 37, 37, 37, - 37, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, - 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 37, 37, 37, 37, 37, - 37, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, - 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 37, 37, 37, 37, 37, - 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, - 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, - 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, - 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, - 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, - 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, - 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, - 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, + 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, + 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, + 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, + 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 37, 37, 37, 37, 37, 37, + 37, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, + 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 37, 37, 37, 37, 37, + 37, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, + 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 37, 37, 37, 37, 37, + 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, + 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, + 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, + 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, + 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, + 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, + 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, + 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, }; /* *str points to the first digit in a string of base `base` digits. base @@ -1792,111 +1792,111 @@ static PyLongObject * long_from_binary_base(char **str, int base) { - char *p = *str; - char *start = p; - int bits_per_char; - Py_ssize_t n; - PyLongObject *z; - twodigits accum; - int bits_in_accum; - digit *pdigit; - - assert(base >= 2 && base <= 32 && (base & (base - 1)) == 0); - n = base; - for (bits_per_char = -1; n; ++bits_per_char) - n >>= 1; - /* n <- total # of bits needed, while setting p to end-of-string */ - while (_PyLong_DigitValue[Py_CHARMASK(*p)] < base) - ++p; - *str = p; - /* n <- # of Python digits needed, = ceiling(n/PyLong_SHIFT). */ - n = (p - start) * bits_per_char + PyLong_SHIFT - 1; - if (n / bits_per_char < p - start) { - PyErr_SetString(PyExc_ValueError, - "int string too large to convert"); - return NULL; - } - n = n / PyLong_SHIFT; - z = _PyLong_New(n); - if (z == NULL) - return NULL; - /* Read string from right, and fill in long from left; i.e., - * from least to most significant in both. - */ - accum = 0; - bits_in_accum = 0; - pdigit = z->ob_digit; - while (--p >= start) { - int k = (int)_PyLong_DigitValue[Py_CHARMASK(*p)]; - assert(k >= 0 && k < base); - accum |= (twodigits)k << bits_in_accum; - bits_in_accum += bits_per_char; - if (bits_in_accum >= PyLong_SHIFT) { - *pdigit++ = (digit)(accum & PyLong_MASK); - assert(pdigit - z->ob_digit <= n); - accum >>= PyLong_SHIFT; - bits_in_accum -= PyLong_SHIFT; - assert(bits_in_accum < PyLong_SHIFT); - } - } - if (bits_in_accum) { - assert(bits_in_accum <= PyLong_SHIFT); - *pdigit++ = (digit)accum; - assert(pdigit - z->ob_digit <= n); - } - while (pdigit - z->ob_digit < n) - *pdigit++ = 0; - return long_normalize(z); + char *p = *str; + char *start = p; + int bits_per_char; + Py_ssize_t n; + PyLongObject *z; + twodigits accum; + int bits_in_accum; + digit *pdigit; + + assert(base >= 2 && base <= 32 && (base & (base - 1)) == 0); + n = base; + for (bits_per_char = -1; n; ++bits_per_char) + n >>= 1; + /* n <- total # of bits needed, while setting p to end-of-string */ + while (_PyLong_DigitValue[Py_CHARMASK(*p)] < base) + ++p; + *str = p; + /* n <- # of Python digits needed, = ceiling(n/PyLong_SHIFT). */ + n = (p - start) * bits_per_char + PyLong_SHIFT - 1; + if (n / bits_per_char < p - start) { + PyErr_SetString(PyExc_ValueError, + "int string too large to convert"); + return NULL; + } + n = n / PyLong_SHIFT; + z = _PyLong_New(n); + if (z == NULL) + return NULL; + /* Read string from right, and fill in long from left; i.e., + * from least to most significant in both. + */ + accum = 0; + bits_in_accum = 0; + pdigit = z->ob_digit; + while (--p >= start) { + int k = (int)_PyLong_DigitValue[Py_CHARMASK(*p)]; + assert(k >= 0 && k < base); + accum |= (twodigits)k << bits_in_accum; + bits_in_accum += bits_per_char; + if (bits_in_accum >= PyLong_SHIFT) { + *pdigit++ = (digit)(accum & PyLong_MASK); + assert(pdigit - z->ob_digit <= n); + accum >>= PyLong_SHIFT; + bits_in_accum -= PyLong_SHIFT; + assert(bits_in_accum < PyLong_SHIFT); + } + } + if (bits_in_accum) { + assert(bits_in_accum <= PyLong_SHIFT); + *pdigit++ = (digit)accum; + assert(pdigit - z->ob_digit <= n); + } + while (pdigit - z->ob_digit < n) + *pdigit++ = 0; + return long_normalize(z); } PyObject * PyLong_FromString(char *str, char **pend, int base) { - int sign = 1, error_if_nonzero = 0; - char *start, *orig_str = str; - PyLongObject *z = NULL; - PyObject *strobj; - Py_ssize_t slen; - - if ((base != 0 && base < 2) || base > 36) { - PyErr_SetString(PyExc_ValueError, - "int() arg 2 must be >= 2 and <= 36"); - return NULL; - } - while (*str != '\0' && isspace(Py_CHARMASK(*str))) - str++; - if (*str == '+') - ++str; - else if (*str == '-') { - ++str; - sign = -1; - } - if (base == 0) { - if (str[0] != '0') - base = 10; - else if (str[1] == 'x' || str[1] == 'X') - base = 16; - else if (str[1] == 'o' || str[1] == 'O') - base = 8; - else if (str[1] == 'b' || str[1] == 'B') - base = 2; - else { - /* "old" (C-style) octal literal, now invalid. - it might still be zero though */ - error_if_nonzero = 1; - base = 10; - } - } - if (str[0] == '0' && - ((base == 16 && (str[1] == 'x' || str[1] == 'X')) || - (base == 8 && (str[1] == 'o' || str[1] == 'O')) || - (base == 2 && (str[1] == 'b' || str[1] == 'B')))) - str += 2; - - start = str; - if ((base & (base - 1)) == 0) - z = long_from_binary_base(&str, base); - else { + int sign = 1, error_if_nonzero = 0; + char *start, *orig_str = str; + PyLongObject *z = NULL; + PyObject *strobj; + Py_ssize_t slen; + + if ((base != 0 && base < 2) || base > 36) { + PyErr_SetString(PyExc_ValueError, + "int() arg 2 must be >= 2 and <= 36"); + return NULL; + } + while (*str != '\0' && isspace(Py_CHARMASK(*str))) + str++; + if (*str == '+') + ++str; + else if (*str == '-') { + ++str; + sign = -1; + } + if (base == 0) { + if (str[0] != '0') + base = 10; + else if (str[1] == 'x' || str[1] == 'X') + base = 16; + else if (str[1] == 'o' || str[1] == 'O') + base = 8; + else if (str[1] == 'b' || str[1] == 'B') + base = 2; + else { + /* "old" (C-style) octal literal, now invalid. + it might still be zero though */ + error_if_nonzero = 1; + base = 10; + } + } + if (str[0] == '0' && + ((base == 16 && (str[1] == 'x' || str[1] == 'X')) || + (base == 8 && (str[1] == 'o' || str[1] == 'O')) || + (base == 2 && (str[1] == 'b' || str[1] == 'B')))) + str += 2; + + start = str; + if ((base & (base - 1)) == 0) + z = long_from_binary_base(&str, base); + else { /*** Binary bases can be converted in time linear in the number of digits, because Python's representation base is binary. Other bases (including decimal!) use @@ -1982,227 +1982,227 @@ just 1 digit at the start, so that the copying code was exercised for every digit beyond the first. ***/ - register twodigits c; /* current input character */ - Py_ssize_t size_z; - int i; - int convwidth; - twodigits convmultmax, convmult; - digit *pz, *pzstop; - char* scan; - - static double log_base_BASE[37] = {0.0e0,}; - static int convwidth_base[37] = {0,}; - static twodigits convmultmax_base[37] = {0,}; - - if (log_base_BASE[base] == 0.0) { - twodigits convmax = base; - int i = 1; - - log_base_BASE[base] = log((double)base) / - log((double)PyLong_BASE); - for (;;) { - twodigits next = convmax * base; - if (next > PyLong_BASE) - break; - convmax = next; - ++i; - } - convmultmax_base[base] = convmax; - assert(i > 0); - convwidth_base[base] = i; - } - - /* Find length of the string of numeric characters. */ - scan = str; - while (_PyLong_DigitValue[Py_CHARMASK(*scan)] < base) - ++scan; - - /* Create a long object that can contain the largest possible - * integer with this base and length. Note that there's no - * need to initialize z->ob_digit -- no slot is read up before - * being stored into. - */ - size_z = (Py_ssize_t)((scan - str) * log_base_BASE[base]) + 1; - /* Uncomment next line to test exceedingly rare copy code */ - /* size_z = 1; */ - assert(size_z > 0); - z = _PyLong_New(size_z); - if (z == NULL) - return NULL; - Py_SIZE(z) = 0; - - /* `convwidth` consecutive input digits are treated as a single - * digit in base `convmultmax`. - */ - convwidth = convwidth_base[base]; - convmultmax = convmultmax_base[base]; - - /* Work ;-) */ - while (str < scan) { - /* grab up to convwidth digits from the input string */ - c = (digit)_PyLong_DigitValue[Py_CHARMASK(*str++)]; - for (i = 1; i < convwidth && str != scan; ++i, ++str) { - c = (twodigits)(c * base + - (int)_PyLong_DigitValue[Py_CHARMASK(*str)]); - assert(c < PyLong_BASE); - } - - convmult = convmultmax; - /* Calculate the shift only if we couldn't get - * convwidth digits. - */ - if (i != convwidth) { - convmult = base; - for ( ; i > 1; --i) - convmult *= base; - } - - /* Multiply z by convmult, and add c. */ - pz = z->ob_digit; - pzstop = pz + Py_SIZE(z); - for (; pz < pzstop; ++pz) { - c += (twodigits)*pz * convmult; - *pz = (digit)(c & PyLong_MASK); - c >>= PyLong_SHIFT; - } - /* carry off the current end? */ - if (c) { - assert(c < PyLong_BASE); - if (Py_SIZE(z) < size_z) { - *pz = (digit)c; - ++Py_SIZE(z); - } - else { - PyLongObject *tmp; - /* Extremely rare. Get more space. */ - assert(Py_SIZE(z) == size_z); - tmp = _PyLong_New(size_z + 1); - if (tmp == NULL) { - Py_DECREF(z); - return NULL; - } - memcpy(tmp->ob_digit, - z->ob_digit, - sizeof(digit) * size_z); - Py_DECREF(z); - z = tmp; - z->ob_digit[size_z] = (digit)c; - ++size_z; - } - } - } - } - if (z == NULL) - return NULL; - if (error_if_nonzero) { - /* reset the base to 0, else the exception message - doesn't make too much sense */ - base = 0; - if (Py_SIZE(z) != 0) - goto onError; - /* there might still be other problems, therefore base - remains zero here for the same reason */ - } - if (str == start) - goto onError; - if (sign < 0) - Py_SIZE(z) = -(Py_SIZE(z)); - while (*str && isspace(Py_CHARMASK(*str))) - str++; - if (*str != '\0') - goto onError; - if (pend) - *pend = str; - long_normalize(z); - return (PyObject *) maybe_small_long(z); + register twodigits c; /* current input character */ + Py_ssize_t size_z; + int i; + int convwidth; + twodigits convmultmax, convmult; + digit *pz, *pzstop; + char* scan; + + static double log_base_BASE[37] = {0.0e0,}; + static int convwidth_base[37] = {0,}; + static twodigits convmultmax_base[37] = {0,}; + + if (log_base_BASE[base] == 0.0) { + twodigits convmax = base; + int i = 1; + + log_base_BASE[base] = log((double)base) / + log((double)PyLong_BASE); + for (;;) { + twodigits next = convmax * base; + if (next > PyLong_BASE) + break; + convmax = next; + ++i; + } + convmultmax_base[base] = convmax; + assert(i > 0); + convwidth_base[base] = i; + } + + /* Find length of the string of numeric characters. */ + scan = str; + while (_PyLong_DigitValue[Py_CHARMASK(*scan)] < base) + ++scan; + + /* Create a long object that can contain the largest possible + * integer with this base and length. Note that there's no + * need to initialize z->ob_digit -- no slot is read up before + * being stored into. + */ + size_z = (Py_ssize_t)((scan - str) * log_base_BASE[base]) + 1; + /* Uncomment next line to test exceedingly rare copy code */ + /* size_z = 1; */ + assert(size_z > 0); + z = _PyLong_New(size_z); + if (z == NULL) + return NULL; + Py_SIZE(z) = 0; + + /* `convwidth` consecutive input digits are treated as a single + * digit in base `convmultmax`. + */ + convwidth = convwidth_base[base]; + convmultmax = convmultmax_base[base]; + + /* Work ;-) */ + while (str < scan) { + /* grab up to convwidth digits from the input string */ + c = (digit)_PyLong_DigitValue[Py_CHARMASK(*str++)]; + for (i = 1; i < convwidth && str != scan; ++i, ++str) { + c = (twodigits)(c * base + + (int)_PyLong_DigitValue[Py_CHARMASK(*str)]); + assert(c < PyLong_BASE); + } + + convmult = convmultmax; + /* Calculate the shift only if we couldn't get + * convwidth digits. + */ + if (i != convwidth) { + convmult = base; + for ( ; i > 1; --i) + convmult *= base; + } + + /* Multiply z by convmult, and add c. */ + pz = z->ob_digit; + pzstop = pz + Py_SIZE(z); + for (; pz < pzstop; ++pz) { + c += (twodigits)*pz * convmult; + *pz = (digit)(c & PyLong_MASK); + c >>= PyLong_SHIFT; + } + /* carry off the current end? */ + if (c) { + assert(c < PyLong_BASE); + if (Py_SIZE(z) < size_z) { + *pz = (digit)c; + ++Py_SIZE(z); + } + else { + PyLongObject *tmp; + /* Extremely rare. Get more space. */ + assert(Py_SIZE(z) == size_z); + tmp = _PyLong_New(size_z + 1); + if (tmp == NULL) { + Py_DECREF(z); + return NULL; + } + memcpy(tmp->ob_digit, + z->ob_digit, + sizeof(digit) * size_z); + Py_DECREF(z); + z = tmp; + z->ob_digit[size_z] = (digit)c; + ++size_z; + } + } + } + } + if (z == NULL) + return NULL; + if (error_if_nonzero) { + /* reset the base to 0, else the exception message + doesn't make too much sense */ + base = 0; + if (Py_SIZE(z) != 0) + goto onError; + /* there might still be other problems, therefore base + remains zero here for the same reason */ + } + if (str == start) + goto onError; + if (sign < 0) + Py_SIZE(z) = -(Py_SIZE(z)); + while (*str && isspace(Py_CHARMASK(*str))) + str++; + if (*str != '\0') + goto onError; + if (pend) + *pend = str; + long_normalize(z); + return (PyObject *) maybe_small_long(z); onError: - Py_XDECREF(z); - slen = strlen(orig_str) < 200 ? strlen(orig_str) : 200; - strobj = PyUnicode_FromStringAndSize(orig_str, slen); - if (strobj == NULL) - return NULL; - PyErr_Format(PyExc_ValueError, - "invalid literal for int() with base %d: %R", - base, strobj); - Py_DECREF(strobj); - return NULL; + Py_XDECREF(z); + slen = strlen(orig_str) < 200 ? strlen(orig_str) : 200; + strobj = PyUnicode_FromStringAndSize(orig_str, slen); + if (strobj == NULL) + return NULL; + PyErr_Format(PyExc_ValueError, + "invalid literal for int() with base %d: %R", + base, strobj); + Py_DECREF(strobj); + return NULL; } PyObject * PyLong_FromUnicode(Py_UNICODE *u, Py_ssize_t length, int base) { - PyObject *result; - char *buffer = (char *)PyMem_MALLOC(length+1); + PyObject *result; + char *buffer = (char *)PyMem_MALLOC(length+1); - if (buffer == NULL) - return NULL; + if (buffer == NULL) + return NULL; - if (PyUnicode_EncodeDecimal(u, length, buffer, NULL)) { - PyMem_FREE(buffer); - return NULL; - } - result = PyLong_FromString(buffer, NULL, base); - PyMem_FREE(buffer); - return result; + if (PyUnicode_EncodeDecimal(u, length, buffer, NULL)) { + PyMem_FREE(buffer); + return NULL; + } + result = PyLong_FromString(buffer, NULL, base); + PyMem_FREE(buffer); + return result; } /* forward */ static PyLongObject *x_divrem - (PyLongObject *, PyLongObject *, PyLongObject **); + (PyLongObject *, PyLongObject *, PyLongObject **); static PyObject *long_long(PyObject *v); /* Long division with remainder, top-level routine */ static int long_divrem(PyLongObject *a, PyLongObject *b, - PyLongObject **pdiv, PyLongObject **prem) + PyLongObject **pdiv, PyLongObject **prem) { - Py_ssize_t size_a = ABS(Py_SIZE(a)), size_b = ABS(Py_SIZE(b)); - PyLongObject *z; + Py_ssize_t size_a = ABS(Py_SIZE(a)), size_b = ABS(Py_SIZE(b)); + PyLongObject *z; - if (size_b == 0) { - PyErr_SetString(PyExc_ZeroDivisionError, - "integer division or modulo by zero"); - return -1; - } - if (size_a < size_b || - (size_a == size_b && - a->ob_digit[size_a-1] < b->ob_digit[size_b-1])) { - /* |a| < |b|. */ - *pdiv = (PyLongObject*)PyLong_FromLong(0); - if (*pdiv == NULL) - return -1; - Py_INCREF(a); - *prem = (PyLongObject *) a; - return 0; - } - if (size_b == 1) { - digit rem = 0; - z = divrem1(a, b->ob_digit[0], &rem); - if (z == NULL) - return -1; - *prem = (PyLongObject *) PyLong_FromLong((long)rem); - if (*prem == NULL) { - Py_DECREF(z); - return -1; - } - } - else { - z = x_divrem(a, b, prem); - if (z == NULL) - return -1; - } - /* Set the signs. - The quotient z has the sign of a*b; - the remainder r has the sign of a, - so a = b*z + r. */ - if ((Py_SIZE(a) < 0) != (Py_SIZE(b) < 0)) - NEGATE(z); - if (Py_SIZE(a) < 0 && Py_SIZE(*prem) != 0) - NEGATE(*prem); - *pdiv = maybe_small_long(z); - return 0; + if (size_b == 0) { + PyErr_SetString(PyExc_ZeroDivisionError, + "integer division or modulo by zero"); + return -1; + } + if (size_a < size_b || + (size_a == size_b && + a->ob_digit[size_a-1] < b->ob_digit[size_b-1])) { + /* |a| < |b|. */ + *pdiv = (PyLongObject*)PyLong_FromLong(0); + if (*pdiv == NULL) + return -1; + Py_INCREF(a); + *prem = (PyLongObject *) a; + return 0; + } + if (size_b == 1) { + digit rem = 0; + z = divrem1(a, b->ob_digit[0], &rem); + if (z == NULL) + return -1; + *prem = (PyLongObject *) PyLong_FromLong((long)rem); + if (*prem == NULL) { + Py_DECREF(z); + return -1; + } + } + else { + z = x_divrem(a, b, prem); + if (z == NULL) + return -1; + } + /* Set the signs. + The quotient z has the sign of a*b; + the remainder r has the sign of a, + so a = b*z + r. */ + if ((Py_SIZE(a) < 0) != (Py_SIZE(b) < 0)) + NEGATE(z); + if (Py_SIZE(a) < 0 && Py_SIZE(*prem) != 0) + NEGATE(*prem); + *pdiv = maybe_small_long(z); + return 0; } /* Unsigned long division with remainder -- the algorithm. The arguments v1 @@ -2211,125 +2211,125 @@ static PyLongObject * x_divrem(PyLongObject *v1, PyLongObject *w1, PyLongObject **prem) { - PyLongObject *v, *w, *a; - Py_ssize_t i, k, size_v, size_w; - int d; - digit wm1, wm2, carry, q, r, vtop, *v0, *vk, *w0, *ak; - twodigits vv; - sdigit zhi; - stwodigits z; - - /* We follow Knuth [The Art of Computer Programming, Vol. 2 (3rd - edn.), section 4.3.1, Algorithm D], except that we don't explicitly - handle the special case when the initial estimate q for a quotient - digit is >= PyLong_BASE: the max value for q is PyLong_BASE+1, and - that won't overflow a digit. */ - - /* allocate space; w will also be used to hold the final remainder */ - size_v = ABS(Py_SIZE(v1)); - size_w = ABS(Py_SIZE(w1)); - assert(size_v >= size_w && size_w >= 2); /* Assert checks by div() */ - v = _PyLong_New(size_v+1); - if (v == NULL) { - *prem = NULL; - return NULL; - } - w = _PyLong_New(size_w); - if (w == NULL) { - Py_DECREF(v); - *prem = NULL; - return NULL; - } - - /* normalize: shift w1 left so that its top digit is >= PyLong_BASE/2. - shift v1 left by the same amount. Results go into w and v. */ - d = PyLong_SHIFT - bits_in_digit(w1->ob_digit[size_w-1]); - carry = v_lshift(w->ob_digit, w1->ob_digit, size_w, d); - assert(carry == 0); - carry = v_lshift(v->ob_digit, v1->ob_digit, size_v, d); - if (carry != 0 || v->ob_digit[size_v-1] >= w->ob_digit[size_w-1]) { - v->ob_digit[size_v] = carry; - size_v++; - } - - /* Now v->ob_digit[size_v-1] < w->ob_digit[size_w-1], so quotient has - at most (and usually exactly) k = size_v - size_w digits. */ - k = size_v - size_w; - assert(k >= 0); - a = _PyLong_New(k); - if (a == NULL) { - Py_DECREF(w); - Py_DECREF(v); - *prem = NULL; - return NULL; - } - v0 = v->ob_digit; - w0 = w->ob_digit; - wm1 = w0[size_w-1]; - wm2 = w0[size_w-2]; - for (vk = v0+k, ak = a->ob_digit + k; vk-- > v0;) { - /* inner loop: divide vk[0:size_w+1] by w0[0:size_w], giving - single-digit quotient q, remainder in vk[0:size_w]. */ - - SIGCHECK({ - Py_DECREF(a); - Py_DECREF(w); - Py_DECREF(v); - *prem = NULL; - return NULL; - }) - - /* estimate quotient digit q; may overestimate by 1 (rare) */ - vtop = vk[size_w]; - assert(vtop <= wm1); - vv = ((twodigits)vtop << PyLong_SHIFT) | vk[size_w-1]; - q = (digit)(vv / wm1); - r = (digit)(vv - (twodigits)wm1 * q); /* r = vv % wm1 */ - while ((twodigits)wm2 * q > (((twodigits)r << PyLong_SHIFT) - | vk[size_w-2])) { - --q; - r += wm1; - if (r >= PyLong_BASE) - break; - } - assert(q <= PyLong_BASE); - - /* subtract q*w0[0:size_w] from vk[0:size_w+1] */ - zhi = 0; - for (i = 0; i < size_w; ++i) { - /* invariants: -PyLong_BASE <= -q <= zhi <= 0; - -PyLong_BASE * q <= z < PyLong_BASE */ - z = (sdigit)vk[i] + zhi - - (stwodigits)q * (stwodigits)w0[i]; - vk[i] = (digit)z & PyLong_MASK; - zhi = (sdigit)Py_ARITHMETIC_RIGHT_SHIFT(stwodigits, - z, PyLong_SHIFT); - } - - /* add w back if q was too large (this branch taken rarely) */ - assert((sdigit)vtop + zhi == -1 || (sdigit)vtop + zhi == 0); - if ((sdigit)vtop + zhi < 0) { - carry = 0; - for (i = 0; i < size_w; ++i) { - carry += vk[i] + w0[i]; - vk[i] = carry & PyLong_MASK; - carry >>= PyLong_SHIFT; - } - --q; - } - - /* store quotient digit */ - assert(q < PyLong_BASE); - *--ak = q; - } - - /* unshift remainder; we reuse w to store the result */ - carry = v_rshift(w0, v0, size_w, d); - assert(carry==0); - Py_DECREF(v); + PyLongObject *v, *w, *a; + Py_ssize_t i, k, size_v, size_w; + int d; + digit wm1, wm2, carry, q, r, vtop, *v0, *vk, *w0, *ak; + twodigits vv; + sdigit zhi; + stwodigits z; + + /* We follow Knuth [The Art of Computer Programming, Vol. 2 (3rd + edn.), section 4.3.1, Algorithm D], except that we don't explicitly + handle the special case when the initial estimate q for a quotient + digit is >= PyLong_BASE: the max value for q is PyLong_BASE+1, and + that won't overflow a digit. */ + + /* allocate space; w will also be used to hold the final remainder */ + size_v = ABS(Py_SIZE(v1)); + size_w = ABS(Py_SIZE(w1)); + assert(size_v >= size_w && size_w >= 2); /* Assert checks by div() */ + v = _PyLong_New(size_v+1); + if (v == NULL) { + *prem = NULL; + return NULL; + } + w = _PyLong_New(size_w); + if (w == NULL) { + Py_DECREF(v); + *prem = NULL; + return NULL; + } + + /* normalize: shift w1 left so that its top digit is >= PyLong_BASE/2. + shift v1 left by the same amount. Results go into w and v. */ + d = PyLong_SHIFT - bits_in_digit(w1->ob_digit[size_w-1]); + carry = v_lshift(w->ob_digit, w1->ob_digit, size_w, d); + assert(carry == 0); + carry = v_lshift(v->ob_digit, v1->ob_digit, size_v, d); + if (carry != 0 || v->ob_digit[size_v-1] >= w->ob_digit[size_w-1]) { + v->ob_digit[size_v] = carry; + size_v++; + } + + /* Now v->ob_digit[size_v-1] < w->ob_digit[size_w-1], so quotient has + at most (and usually exactly) k = size_v - size_w digits. */ + k = size_v - size_w; + assert(k >= 0); + a = _PyLong_New(k); + if (a == NULL) { + Py_DECREF(w); + Py_DECREF(v); + *prem = NULL; + return NULL; + } + v0 = v->ob_digit; + w0 = w->ob_digit; + wm1 = w0[size_w-1]; + wm2 = w0[size_w-2]; + for (vk = v0+k, ak = a->ob_digit + k; vk-- > v0;) { + /* inner loop: divide vk[0:size_w+1] by w0[0:size_w], giving + single-digit quotient q, remainder in vk[0:size_w]. */ + + SIGCHECK({ + Py_DECREF(a); + Py_DECREF(w); + Py_DECREF(v); + *prem = NULL; + return NULL; + }) + + /* estimate quotient digit q; may overestimate by 1 (rare) */ + vtop = vk[size_w]; + assert(vtop <= wm1); + vv = ((twodigits)vtop << PyLong_SHIFT) | vk[size_w-1]; + q = (digit)(vv / wm1); + r = (digit)(vv - (twodigits)wm1 * q); /* r = vv % wm1 */ + while ((twodigits)wm2 * q > (((twodigits)r << PyLong_SHIFT) + | vk[size_w-2])) { + --q; + r += wm1; + if (r >= PyLong_BASE) + break; + } + assert(q <= PyLong_BASE); + + /* subtract q*w0[0:size_w] from vk[0:size_w+1] */ + zhi = 0; + for (i = 0; i < size_w; ++i) { + /* invariants: -PyLong_BASE <= -q <= zhi <= 0; + -PyLong_BASE * q <= z < PyLong_BASE */ + z = (sdigit)vk[i] + zhi - + (stwodigits)q * (stwodigits)w0[i]; + vk[i] = (digit)z & PyLong_MASK; + zhi = (sdigit)Py_ARITHMETIC_RIGHT_SHIFT(stwodigits, + z, PyLong_SHIFT); + } + + /* add w back if q was too large (this branch taken rarely) */ + assert((sdigit)vtop + zhi == -1 || (sdigit)vtop + zhi == 0); + if ((sdigit)vtop + zhi < 0) { + carry = 0; + for (i = 0; i < size_w; ++i) { + carry += vk[i] + w0[i]; + vk[i] = carry & PyLong_MASK; + carry >>= PyLong_SHIFT; + } + --q; + } + + /* store quotient digit */ + assert(q < PyLong_BASE); + *--ak = q; + } + + /* unshift remainder; we reuse w to store the result */ + carry = v_rshift(w0, v0, size_w, d); + assert(carry==0); + Py_DECREF(v); - *prem = long_normalize(w); - return long_normalize(a); + *prem = long_normalize(w); + return long_normalize(a); } /* For a nonzero PyLong a, express a in the form x * 2**e, with 0.5 <= @@ -2349,111 +2349,111 @@ double _PyLong_Frexp(PyLongObject *a, Py_ssize_t *e) { - Py_ssize_t a_size, a_bits, shift_digits, shift_bits, x_size; - /* See below for why x_digits is always large enough. */ - digit rem, x_digits[2 + (DBL_MANT_DIG + 1) / PyLong_SHIFT]; - double dx; - /* Correction term for round-half-to-even rounding. For a digit x, - "x + half_even_correction[x & 7]" gives x rounded to the nearest - multiple of 4, rounding ties to a multiple of 8. */ - static const int half_even_correction[8] = {0, -1, -2, 1, 0, -1, 2, 1}; - - a_size = ABS(Py_SIZE(a)); - if (a_size == 0) { - /* Special case for 0: significand 0.0, exponent 0. */ - *e = 0; - return 0.0; - } - a_bits = bits_in_digit(a->ob_digit[a_size-1]); - /* The following is an overflow-free version of the check - "if ((a_size - 1) * PyLong_SHIFT + a_bits > PY_SSIZE_T_MAX) ..." */ - if (a_size >= (PY_SSIZE_T_MAX - 1) / PyLong_SHIFT + 1 && - (a_size > (PY_SSIZE_T_MAX - 1) / PyLong_SHIFT + 1 || - a_bits > (PY_SSIZE_T_MAX - 1) % PyLong_SHIFT + 1)) - goto overflow; - a_bits = (a_size - 1) * PyLong_SHIFT + a_bits; - - /* Shift the first DBL_MANT_DIG + 2 bits of a into x_digits[0:x_size] - (shifting left if a_bits <= DBL_MANT_DIG + 2). - - Number of digits needed for result: write // for floor division. - Then if shifting left, we end up using - - 1 + a_size + (DBL_MANT_DIG + 2 - a_bits) // PyLong_SHIFT - - digits. If shifting right, we use - - a_size - (a_bits - DBL_MANT_DIG - 2) // PyLong_SHIFT - - digits. Using a_size = 1 + (a_bits - 1) // PyLong_SHIFT along with - the inequalities - - m // PyLong_SHIFT + n // PyLong_SHIFT <= (m + n) // PyLong_SHIFT - m // PyLong_SHIFT - n // PyLong_SHIFT <= - 1 + (m - n - 1) // PyLong_SHIFT, - - valid for any integers m and n, we find that x_size satisfies - - x_size <= 2 + (DBL_MANT_DIG + 1) // PyLong_SHIFT - - in both cases. - */ - if (a_bits <= DBL_MANT_DIG + 2) { - shift_digits = (DBL_MANT_DIG + 2 - a_bits) / PyLong_SHIFT; - shift_bits = (DBL_MANT_DIG + 2 - a_bits) % PyLong_SHIFT; - x_size = 0; - while (x_size < shift_digits) - x_digits[x_size++] = 0; - rem = v_lshift(x_digits + x_size, a->ob_digit, a_size, - (int)shift_bits); - x_size += a_size; - x_digits[x_size++] = rem; - } - else { - shift_digits = (a_bits - DBL_MANT_DIG - 2) / PyLong_SHIFT; - shift_bits = (a_bits - DBL_MANT_DIG - 2) % PyLong_SHIFT; - rem = v_rshift(x_digits, a->ob_digit + shift_digits, - a_size - shift_digits, (int)shift_bits); - x_size = a_size - shift_digits; - /* For correct rounding below, we need the least significant - bit of x to be 'sticky' for this shift: if any of the bits - shifted out was nonzero, we set the least significant bit - of x. */ - if (rem) - x_digits[0] |= 1; - else - while (shift_digits > 0) - if (a->ob_digit[--shift_digits]) { - x_digits[0] |= 1; - break; - } - } - assert(1 <= x_size && x_size <= (Py_ssize_t)(sizeof(x_digits)/sizeof(digit))); - - /* Round, and convert to double. */ - x_digits[0] += half_even_correction[x_digits[0] & 7]; - dx = x_digits[--x_size]; - while (x_size > 0) - dx = dx * PyLong_BASE + x_digits[--x_size]; - - /* Rescale; make correction if result is 1.0. */ - dx /= 4.0 * EXP2_DBL_MANT_DIG; - if (dx == 1.0) { - if (a_bits == PY_SSIZE_T_MAX) - goto overflow; - dx = 0.5; - a_bits += 1; - } + Py_ssize_t a_size, a_bits, shift_digits, shift_bits, x_size; + /* See below for why x_digits is always large enough. */ + digit rem, x_digits[2 + (DBL_MANT_DIG + 1) / PyLong_SHIFT]; + double dx; + /* Correction term for round-half-to-even rounding. For a digit x, + "x + half_even_correction[x & 7]" gives x rounded to the nearest + multiple of 4, rounding ties to a multiple of 8. */ + static const int half_even_correction[8] = {0, -1, -2, 1, 0, -1, 2, 1}; + + a_size = ABS(Py_SIZE(a)); + if (a_size == 0) { + /* Special case for 0: significand 0.0, exponent 0. */ + *e = 0; + return 0.0; + } + a_bits = bits_in_digit(a->ob_digit[a_size-1]); + /* The following is an overflow-free version of the check + "if ((a_size - 1) * PyLong_SHIFT + a_bits > PY_SSIZE_T_MAX) ..." */ + if (a_size >= (PY_SSIZE_T_MAX - 1) / PyLong_SHIFT + 1 && + (a_size > (PY_SSIZE_T_MAX - 1) / PyLong_SHIFT + 1 || + a_bits > (PY_SSIZE_T_MAX - 1) % PyLong_SHIFT + 1)) + goto overflow; + a_bits = (a_size - 1) * PyLong_SHIFT + a_bits; + + /* Shift the first DBL_MANT_DIG + 2 bits of a into x_digits[0:x_size] + (shifting left if a_bits <= DBL_MANT_DIG + 2). + + Number of digits needed for result: write // for floor division. + Then if shifting left, we end up using + + 1 + a_size + (DBL_MANT_DIG + 2 - a_bits) // PyLong_SHIFT + + digits. If shifting right, we use + + a_size - (a_bits - DBL_MANT_DIG - 2) // PyLong_SHIFT + + digits. Using a_size = 1 + (a_bits - 1) // PyLong_SHIFT along with + the inequalities + + m // PyLong_SHIFT + n // PyLong_SHIFT <= (m + n) // PyLong_SHIFT + m // PyLong_SHIFT - n // PyLong_SHIFT <= + 1 + (m - n - 1) // PyLong_SHIFT, + + valid for any integers m and n, we find that x_size satisfies + + x_size <= 2 + (DBL_MANT_DIG + 1) // PyLong_SHIFT + + in both cases. + */ + if (a_bits <= DBL_MANT_DIG + 2) { + shift_digits = (DBL_MANT_DIG + 2 - a_bits) / PyLong_SHIFT; + shift_bits = (DBL_MANT_DIG + 2 - a_bits) % PyLong_SHIFT; + x_size = 0; + while (x_size < shift_digits) + x_digits[x_size++] = 0; + rem = v_lshift(x_digits + x_size, a->ob_digit, a_size, + (int)shift_bits); + x_size += a_size; + x_digits[x_size++] = rem; + } + else { + shift_digits = (a_bits - DBL_MANT_DIG - 2) / PyLong_SHIFT; + shift_bits = (a_bits - DBL_MANT_DIG - 2) % PyLong_SHIFT; + rem = v_rshift(x_digits, a->ob_digit + shift_digits, + a_size - shift_digits, (int)shift_bits); + x_size = a_size - shift_digits; + /* For correct rounding below, we need the least significant + bit of x to be 'sticky' for this shift: if any of the bits + shifted out was nonzero, we set the least significant bit + of x. */ + if (rem) + x_digits[0] |= 1; + else + while (shift_digits > 0) + if (a->ob_digit[--shift_digits]) { + x_digits[0] |= 1; + break; + } + } + assert(1 <= x_size && x_size <= (Py_ssize_t)(sizeof(x_digits)/sizeof(digit))); + + /* Round, and convert to double. */ + x_digits[0] += half_even_correction[x_digits[0] & 7]; + dx = x_digits[--x_size]; + while (x_size > 0) + dx = dx * PyLong_BASE + x_digits[--x_size]; + + /* Rescale; make correction if result is 1.0. */ + dx /= 4.0 * EXP2_DBL_MANT_DIG; + if (dx == 1.0) { + if (a_bits == PY_SSIZE_T_MAX) + goto overflow; + dx = 0.5; + a_bits += 1; + } - *e = a_bits; - return Py_SIZE(a) < 0 ? -dx : dx; + *e = a_bits; + return Py_SIZE(a) < 0 ? -dx : dx; overflow: - /* exponent > PY_SSIZE_T_MAX */ - PyErr_SetString(PyExc_OverflowError, - "huge integer: number of bits overflows a Py_ssize_t"); - *e = 0; - return -1.0; + /* exponent > PY_SSIZE_T_MAX */ + PyErr_SetString(PyExc_OverflowError, + "huge integer: number of bits overflows a Py_ssize_t"); + *e = 0; + return -1.0; } /* Get a C double from a long int object. Rounds to the nearest double, @@ -2462,20 +2462,20 @@ double PyLong_AsDouble(PyObject *v) { - Py_ssize_t exponent; - double x; + Py_ssize_t exponent; + double x; - if (v == NULL || !PyLong_Check(v)) { - PyErr_BadInternalCall(); - return -1.0; - } - x = _PyLong_Frexp((PyLongObject *)v, &exponent); - if ((x == -1.0 && PyErr_Occurred()) || exponent > DBL_MAX_EXP) { - PyErr_SetString(PyExc_OverflowError, - "long int too large to convert to float"); - return -1.0; - } - return ldexp(x, (int)exponent); + if (v == NULL || !PyLong_Check(v)) { + PyErr_BadInternalCall(); + return -1.0; + } + x = _PyLong_Frexp((PyLongObject *)v, &exponent); + if ((x == -1.0 && PyErr_Occurred()) || exponent > DBL_MAX_EXP) { + PyErr_SetString(PyExc_OverflowError, + "long int too large to convert to float"); + return -1.0; + } + return ldexp(x, (int)exponent); } /* Methods */ @@ -2483,109 +2483,109 @@ static void long_dealloc(PyObject *v) { - Py_TYPE(v)->tp_free(v); + Py_TYPE(v)->tp_free(v); } static int long_compare(PyLongObject *a, PyLongObject *b) { - Py_ssize_t sign; + Py_ssize_t sign; - if (Py_SIZE(a) != Py_SIZE(b)) { - sign = Py_SIZE(a) - Py_SIZE(b); - } - else { - Py_ssize_t i = ABS(Py_SIZE(a)); - while (--i >= 0 && a->ob_digit[i] == b->ob_digit[i]) - ; - if (i < 0) - sign = 0; - else { - sign = (sdigit)a->ob_digit[i] - (sdigit)b->ob_digit[i]; - if (Py_SIZE(a) < 0) - sign = -sign; - } - } - return sign < 0 ? -1 : sign > 0 ? 1 : 0; + if (Py_SIZE(a) != Py_SIZE(b)) { + sign = Py_SIZE(a) - Py_SIZE(b); + } + else { + Py_ssize_t i = ABS(Py_SIZE(a)); + while (--i >= 0 && a->ob_digit[i] == b->ob_digit[i]) + ; + if (i < 0) + sign = 0; + else { + sign = (sdigit)a->ob_digit[i] - (sdigit)b->ob_digit[i]; + if (Py_SIZE(a) < 0) + sign = -sign; + } + } + return sign < 0 ? -1 : sign > 0 ? 1 : 0; } #define TEST_COND(cond) \ - ((cond) ? Py_True : Py_False) + ((cond) ? Py_True : Py_False) static PyObject * long_richcompare(PyObject *self, PyObject *other, int op) { - int result; - PyObject *v; - CHECK_BINOP(self, other); - if (self == other) - result = 0; - else - result = long_compare((PyLongObject*)self, (PyLongObject*)other); - /* Convert the return value to a Boolean */ - switch (op) { - case Py_EQ: - v = TEST_COND(result == 0); - break; - case Py_NE: - v = TEST_COND(result != 0); - break; - case Py_LE: - v = TEST_COND(result <= 0); - break; - case Py_GE: - v = TEST_COND(result >= 0); - break; - case Py_LT: - v = TEST_COND(result == -1); - break; - case Py_GT: - v = TEST_COND(result == 1); - break; - default: - PyErr_BadArgument(); - return NULL; - } - Py_INCREF(v); - return v; + int result; + PyObject *v; + CHECK_BINOP(self, other); + if (self == other) + result = 0; + else + result = long_compare((PyLongObject*)self, (PyLongObject*)other); + /* Convert the return value to a Boolean */ + switch (op) { + case Py_EQ: + v = TEST_COND(result == 0); + break; + case Py_NE: + v = TEST_COND(result != 0); + break; + case Py_LE: + v = TEST_COND(result <= 0); + break; + case Py_GE: + v = TEST_COND(result >= 0); + break; + case Py_LT: + v = TEST_COND(result == -1); + break; + case Py_GT: + v = TEST_COND(result == 1); + break; + default: + PyErr_BadArgument(); + return NULL; + } + Py_INCREF(v); + return v; } static long long_hash(PyLongObject *v) { - unsigned long x; - Py_ssize_t i; - int sign; - - i = Py_SIZE(v); - switch(i) { - case -1: return v->ob_digit[0]==1 ? -2 : -(sdigit)v->ob_digit[0]; - case 0: return 0; - case 1: return v->ob_digit[0]; - } - sign = 1; - x = 0; - if (i < 0) { - sign = -1; - i = -(i); - } - /* The following loop produces a C unsigned long x such that x is - congruent to the absolute value of v modulo ULONG_MAX. The - resulting x is nonzero if and only if v is. */ - while (--i >= 0) { - /* Force a native long #-bits (32 or 64) circular shift */ - x = (x >> (8*SIZEOF_LONG-PyLong_SHIFT)) | (x << PyLong_SHIFT); - x += v->ob_digit[i]; - /* If the addition above overflowed we compensate by - incrementing. This preserves the value modulo - ULONG_MAX. */ - if (x < v->ob_digit[i]) - x++; - } - x = x * sign; - if (x == (unsigned long)-1) - x = (unsigned long)-2; - return (long)x; + unsigned long x; + Py_ssize_t i; + int sign; + + i = Py_SIZE(v); + switch(i) { + case -1: return v->ob_digit[0]==1 ? -2 : -(sdigit)v->ob_digit[0]; + case 0: return 0; + case 1: return v->ob_digit[0]; + } + sign = 1; + x = 0; + if (i < 0) { + sign = -1; + i = -(i); + } + /* The following loop produces a C unsigned long x such that x is + congruent to the absolute value of v modulo ULONG_MAX. The + resulting x is nonzero if and only if v is. */ + while (--i >= 0) { + /* Force a native long #-bits (32 or 64) circular shift */ + x = (x >> (8*SIZEOF_LONG-PyLong_SHIFT)) | (x << PyLong_SHIFT); + x += v->ob_digit[i]; + /* If the addition above overflowed we compensate by + incrementing. This preserves the value modulo + ULONG_MAX. */ + if (x < v->ob_digit[i]) + x++; + } + x = x * sign; + if (x == (unsigned long)-1) + x = (unsigned long)-2; + return (long)x; } @@ -2594,33 +2594,33 @@ static PyLongObject * x_add(PyLongObject *a, PyLongObject *b) { - Py_ssize_t size_a = ABS(Py_SIZE(a)), size_b = ABS(Py_SIZE(b)); - PyLongObject *z; - Py_ssize_t i; - digit carry = 0; - - /* Ensure a is the larger of the two: */ - if (size_a < size_b) { - { PyLongObject *temp = a; a = b; b = temp; } - { Py_ssize_t size_temp = size_a; - size_a = size_b; - size_b = size_temp; } - } - z = _PyLong_New(size_a+1); - if (z == NULL) - return NULL; - for (i = 0; i < size_b; ++i) { - carry += a->ob_digit[i] + b->ob_digit[i]; - z->ob_digit[i] = carry & PyLong_MASK; - carry >>= PyLong_SHIFT; - } - for (; i < size_a; ++i) { - carry += a->ob_digit[i]; - z->ob_digit[i] = carry & PyLong_MASK; - carry >>= PyLong_SHIFT; - } - z->ob_digit[i] = carry; - return long_normalize(z); + Py_ssize_t size_a = ABS(Py_SIZE(a)), size_b = ABS(Py_SIZE(b)); + PyLongObject *z; + Py_ssize_t i; + digit carry = 0; + + /* Ensure a is the larger of the two: */ + if (size_a < size_b) { + { PyLongObject *temp = a; a = b; b = temp; } + { Py_ssize_t size_temp = size_a; + size_a = size_b; + size_b = size_temp; } + } + z = _PyLong_New(size_a+1); + if (z == NULL) + return NULL; + for (i = 0; i < size_b; ++i) { + carry += a->ob_digit[i] + b->ob_digit[i]; + z->ob_digit[i] = carry & PyLong_MASK; + carry >>= PyLong_SHIFT; + } + for (; i < size_a; ++i) { + carry += a->ob_digit[i]; + z->ob_digit[i] = carry & PyLong_MASK; + carry >>= PyLong_SHIFT; + } + z->ob_digit[i] = carry; + return long_normalize(z); } /* Subtract the absolute values of two integers. */ @@ -2628,113 +2628,113 @@ static PyLongObject * x_sub(PyLongObject *a, PyLongObject *b) { - Py_ssize_t size_a = ABS(Py_SIZE(a)), size_b = ABS(Py_SIZE(b)); - PyLongObject *z; - Py_ssize_t i; - int sign = 1; - digit borrow = 0; - - /* Ensure a is the larger of the two: */ - if (size_a < size_b) { - sign = -1; - { PyLongObject *temp = a; a = b; b = temp; } - { Py_ssize_t size_temp = size_a; - size_a = size_b; - size_b = size_temp; } - } - else if (size_a == size_b) { - /* Find highest digit where a and b differ: */ - i = size_a; - while (--i >= 0 && a->ob_digit[i] == b->ob_digit[i]) - ; - if (i < 0) - return (PyLongObject *)PyLong_FromLong(0); - if (a->ob_digit[i] < b->ob_digit[i]) { - sign = -1; - { PyLongObject *temp = a; a = b; b = temp; } - } - size_a = size_b = i+1; - } - z = _PyLong_New(size_a); - if (z == NULL) - return NULL; - for (i = 0; i < size_b; ++i) { - /* The following assumes unsigned arithmetic - works module 2**N for some N>PyLong_SHIFT. */ - borrow = a->ob_digit[i] - b->ob_digit[i] - borrow; - z->ob_digit[i] = borrow & PyLong_MASK; - borrow >>= PyLong_SHIFT; - borrow &= 1; /* Keep only one sign bit */ - } - for (; i < size_a; ++i) { - borrow = a->ob_digit[i] - borrow; - z->ob_digit[i] = borrow & PyLong_MASK; - borrow >>= PyLong_SHIFT; - borrow &= 1; /* Keep only one sign bit */ - } - assert(borrow == 0); - if (sign < 0) - NEGATE(z); - return long_normalize(z); + Py_ssize_t size_a = ABS(Py_SIZE(a)), size_b = ABS(Py_SIZE(b)); + PyLongObject *z; + Py_ssize_t i; + int sign = 1; + digit borrow = 0; + + /* Ensure a is the larger of the two: */ + if (size_a < size_b) { + sign = -1; + { PyLongObject *temp = a; a = b; b = temp; } + { Py_ssize_t size_temp = size_a; + size_a = size_b; + size_b = size_temp; } + } + else if (size_a == size_b) { + /* Find highest digit where a and b differ: */ + i = size_a; + while (--i >= 0 && a->ob_digit[i] == b->ob_digit[i]) + ; + if (i < 0) + return (PyLongObject *)PyLong_FromLong(0); + if (a->ob_digit[i] < b->ob_digit[i]) { + sign = -1; + { PyLongObject *temp = a; a = b; b = temp; } + } + size_a = size_b = i+1; + } + z = _PyLong_New(size_a); + if (z == NULL) + return NULL; + for (i = 0; i < size_b; ++i) { + /* The following assumes unsigned arithmetic + works module 2**N for some N>PyLong_SHIFT. */ + borrow = a->ob_digit[i] - b->ob_digit[i] - borrow; + z->ob_digit[i] = borrow & PyLong_MASK; + borrow >>= PyLong_SHIFT; + borrow &= 1; /* Keep only one sign bit */ + } + for (; i < size_a; ++i) { + borrow = a->ob_digit[i] - borrow; + z->ob_digit[i] = borrow & PyLong_MASK; + borrow >>= PyLong_SHIFT; + borrow &= 1; /* Keep only one sign bit */ + } + assert(borrow == 0); + if (sign < 0) + NEGATE(z); + return long_normalize(z); } static PyObject * long_add(PyLongObject *a, PyLongObject *b) { - PyLongObject *z; + PyLongObject *z; - CHECK_BINOP(a, b); + CHECK_BINOP(a, b); - if (ABS(Py_SIZE(a)) <= 1 && ABS(Py_SIZE(b)) <= 1) { - PyObject *result = PyLong_FromLong(MEDIUM_VALUE(a) + - MEDIUM_VALUE(b)); - return result; - } - if (Py_SIZE(a) < 0) { - if (Py_SIZE(b) < 0) { - z = x_add(a, b); - if (z != NULL && Py_SIZE(z) != 0) - Py_SIZE(z) = -(Py_SIZE(z)); - } - else - z = x_sub(b, a); - } - else { - if (Py_SIZE(b) < 0) - z = x_sub(a, b); - else - z = x_add(a, b); - } - return (PyObject *)z; + if (ABS(Py_SIZE(a)) <= 1 && ABS(Py_SIZE(b)) <= 1) { + PyObject *result = PyLong_FromLong(MEDIUM_VALUE(a) + + MEDIUM_VALUE(b)); + return result; + } + if (Py_SIZE(a) < 0) { + if (Py_SIZE(b) < 0) { + z = x_add(a, b); + if (z != NULL && Py_SIZE(z) != 0) + Py_SIZE(z) = -(Py_SIZE(z)); + } + else + z = x_sub(b, a); + } + else { + if (Py_SIZE(b) < 0) + z = x_sub(a, b); + else + z = x_add(a, b); + } + return (PyObject *)z; } static PyObject * long_sub(PyLongObject *a, PyLongObject *b) { - PyLongObject *z; + PyLongObject *z; - CHECK_BINOP(a, b); + CHECK_BINOP(a, b); - if (ABS(Py_SIZE(a)) <= 1 && ABS(Py_SIZE(b)) <= 1) { - PyObject* r; - r = PyLong_FromLong(MEDIUM_VALUE(a)-MEDIUM_VALUE(b)); - return r; - } - if (Py_SIZE(a) < 0) { - if (Py_SIZE(b) < 0) - z = x_sub(a, b); - else - z = x_add(a, b); - if (z != NULL && Py_SIZE(z) != 0) - Py_SIZE(z) = -(Py_SIZE(z)); - } - else { - if (Py_SIZE(b) < 0) - z = x_add(a, b); - else - z = x_sub(a, b); - } - return (PyObject *)z; + if (ABS(Py_SIZE(a)) <= 1 && ABS(Py_SIZE(b)) <= 1) { + PyObject* r; + r = PyLong_FromLong(MEDIUM_VALUE(a)-MEDIUM_VALUE(b)); + return r; + } + if (Py_SIZE(a) < 0) { + if (Py_SIZE(b) < 0) + z = x_sub(a, b); + else + z = x_add(a, b); + if (z != NULL && Py_SIZE(z) != 0) + Py_SIZE(z) = -(Py_SIZE(z)); + } + else { + if (Py_SIZE(b) < 0) + z = x_add(a, b); + else + z = x_sub(a, b); + } + return (PyObject *)z; } /* Grade school multiplication, ignoring the signs. @@ -2743,85 +2743,85 @@ static PyLongObject * x_mul(PyLongObject *a, PyLongObject *b) { - PyLongObject *z; - Py_ssize_t size_a = ABS(Py_SIZE(a)); - Py_ssize_t size_b = ABS(Py_SIZE(b)); - Py_ssize_t i; - - z = _PyLong_New(size_a + size_b); - if (z == NULL) - return NULL; - - memset(z->ob_digit, 0, Py_SIZE(z) * sizeof(digit)); - if (a == b) { - /* Efficient squaring per HAC, Algorithm 14.16: - * http://www.cacr.math.uwaterloo.ca/hac/about/chap14.pdf - * Gives slightly less than a 2x speedup when a == b, - * via exploiting that each entry in the multiplication - * pyramid appears twice (except for the size_a squares). - */ - for (i = 0; i < size_a; ++i) { - twodigits carry; - twodigits f = a->ob_digit[i]; - digit *pz = z->ob_digit + (i << 1); - digit *pa = a->ob_digit + i + 1; - digit *paend = a->ob_digit + size_a; - - SIGCHECK({ - Py_DECREF(z); - return NULL; - }) - - carry = *pz + f * f; - *pz++ = (digit)(carry & PyLong_MASK); - carry >>= PyLong_SHIFT; - assert(carry <= PyLong_MASK); - - /* Now f is added in twice in each column of the - * pyramid it appears. Same as adding f<<1 once. - */ - f <<= 1; - while (pa < paend) { - carry += *pz + *pa++ * f; - *pz++ = (digit)(carry & PyLong_MASK); - carry >>= PyLong_SHIFT; - assert(carry <= (PyLong_MASK << 1)); - } - if (carry) { - carry += *pz; - *pz++ = (digit)(carry & PyLong_MASK); - carry >>= PyLong_SHIFT; - } - if (carry) - *pz += (digit)(carry & PyLong_MASK); - assert((carry >> PyLong_SHIFT) == 0); - } - } - else { /* a is not the same as b -- gradeschool long mult */ - for (i = 0; i < size_a; ++i) { - twodigits carry = 0; - twodigits f = a->ob_digit[i]; - digit *pz = z->ob_digit + i; - digit *pb = b->ob_digit; - digit *pbend = b->ob_digit + size_b; - - SIGCHECK({ - Py_DECREF(z); - return NULL; - }) - - while (pb < pbend) { - carry += *pz + *pb++ * f; - *pz++ = (digit)(carry & PyLong_MASK); - carry >>= PyLong_SHIFT; - assert(carry <= PyLong_MASK); - } - if (carry) - *pz += (digit)(carry & PyLong_MASK); - assert((carry >> PyLong_SHIFT) == 0); - } - } - return long_normalize(z); + PyLongObject *z; + Py_ssize_t size_a = ABS(Py_SIZE(a)); + Py_ssize_t size_b = ABS(Py_SIZE(b)); + Py_ssize_t i; + + z = _PyLong_New(size_a + size_b); + if (z == NULL) + return NULL; + + memset(z->ob_digit, 0, Py_SIZE(z) * sizeof(digit)); + if (a == b) { + /* Efficient squaring per HAC, Algorithm 14.16: + * http://www.cacr.math.uwaterloo.ca/hac/about/chap14.pdf + * Gives slightly less than a 2x speedup when a == b, + * via exploiting that each entry in the multiplication + * pyramid appears twice (except for the size_a squares). + */ + for (i = 0; i < size_a; ++i) { + twodigits carry; + twodigits f = a->ob_digit[i]; + digit *pz = z->ob_digit + (i << 1); + digit *pa = a->ob_digit + i + 1; + digit *paend = a->ob_digit + size_a; + + SIGCHECK({ + Py_DECREF(z); + return NULL; + }) + + carry = *pz + f * f; + *pz++ = (digit)(carry & PyLong_MASK); + carry >>= PyLong_SHIFT; + assert(carry <= PyLong_MASK); + + /* Now f is added in twice in each column of the + * pyramid it appears. Same as adding f<<1 once. + */ + f <<= 1; + while (pa < paend) { + carry += *pz + *pa++ * f; + *pz++ = (digit)(carry & PyLong_MASK); + carry >>= PyLong_SHIFT; + assert(carry <= (PyLong_MASK << 1)); + } + if (carry) { + carry += *pz; + *pz++ = (digit)(carry & PyLong_MASK); + carry >>= PyLong_SHIFT; + } + if (carry) + *pz += (digit)(carry & PyLong_MASK); + assert((carry >> PyLong_SHIFT) == 0); + } + } + else { /* a is not the same as b -- gradeschool long mult */ + for (i = 0; i < size_a; ++i) { + twodigits carry = 0; + twodigits f = a->ob_digit[i]; + digit *pz = z->ob_digit + i; + digit *pb = b->ob_digit; + digit *pbend = b->ob_digit + size_b; + + SIGCHECK({ + Py_DECREF(z); + return NULL; + }) + + while (pb < pbend) { + carry += *pz + *pb++ * f; + *pz++ = (digit)(carry & PyLong_MASK); + carry >>= PyLong_SHIFT; + assert(carry <= PyLong_MASK); + } + if (carry) + *pz += (digit)(carry & PyLong_MASK); + assert((carry >> PyLong_SHIFT) == 0); + } + } + return long_normalize(z); } /* A helper for Karatsuba multiplication (k_mul). @@ -2834,26 +2834,26 @@ static int kmul_split(PyLongObject *n, Py_ssize_t size, PyLongObject **high, PyLongObject **low) { - PyLongObject *hi, *lo; - Py_ssize_t size_lo, size_hi; - const Py_ssize_t size_n = ABS(Py_SIZE(n)); - - size_lo = MIN(size_n, size); - size_hi = size_n - size_lo; - - if ((hi = _PyLong_New(size_hi)) == NULL) - return -1; - if ((lo = _PyLong_New(size_lo)) == NULL) { - Py_DECREF(hi); - return -1; - } - - memcpy(lo->ob_digit, n->ob_digit, size_lo * sizeof(digit)); - memcpy(hi->ob_digit, n->ob_digit + size_lo, size_hi * sizeof(digit)); - - *high = long_normalize(hi); - *low = long_normalize(lo); - return 0; + PyLongObject *hi, *lo; + Py_ssize_t size_lo, size_hi; + const Py_ssize_t size_n = ABS(Py_SIZE(n)); + + size_lo = MIN(size_n, size); + size_hi = size_n - size_lo; + + if ((hi = _PyLong_New(size_hi)) == NULL) + return -1; + if ((lo = _PyLong_New(size_lo)) == NULL) { + Py_DECREF(hi); + return -1; + } + + memcpy(lo->ob_digit, n->ob_digit, size_lo * sizeof(digit)); + memcpy(hi->ob_digit, n->ob_digit + size_lo, size_hi * sizeof(digit)); + + *high = long_normalize(hi); + *low = long_normalize(lo); + return 0; } static PyLongObject *k_lopsided_mul(PyLongObject *a, PyLongObject *b); @@ -2865,169 +2865,169 @@ static PyLongObject * k_mul(PyLongObject *a, PyLongObject *b) { - Py_ssize_t asize = ABS(Py_SIZE(a)); - Py_ssize_t bsize = ABS(Py_SIZE(b)); - PyLongObject *ah = NULL; - PyLongObject *al = NULL; - PyLongObject *bh = NULL; - PyLongObject *bl = NULL; - PyLongObject *ret = NULL; - PyLongObject *t1, *t2, *t3; - Py_ssize_t shift; /* the number of digits we split off */ - Py_ssize_t i; - - /* (ah*X+al)(bh*X+bl) = ah*bh*X*X + (ah*bl + al*bh)*X + al*bl - * Let k = (ah+al)*(bh+bl) = ah*bl + al*bh + ah*bh + al*bl - * Then the original product is - * ah*bh*X*X + (k - ah*bh - al*bl)*X + al*bl - * By picking X to be a power of 2, "*X" is just shifting, and it's - * been reduced to 3 multiplies on numbers half the size. - */ - - /* We want to split based on the larger number; fiddle so that b - * is largest. - */ - if (asize > bsize) { - t1 = a; - a = b; - b = t1; - - i = asize; - asize = bsize; - bsize = i; - } - - /* Use gradeschool math when either number is too small. */ - i = a == b ? KARATSUBA_SQUARE_CUTOFF : KARATSUBA_CUTOFF; - if (asize <= i) { - if (asize == 0) - return (PyLongObject *)PyLong_FromLong(0); - else - return x_mul(a, b); - } - - /* If a is small compared to b, splitting on b gives a degenerate - * case with ah==0, and Karatsuba may be (even much) less efficient - * than "grade school" then. However, we can still win, by viewing - * b as a string of "big digits", each of width a->ob_size. That - * leads to a sequence of balanced calls to k_mul. - */ - if (2 * asize <= bsize) - return k_lopsided_mul(a, b); - - /* Split a & b into hi & lo pieces. */ - shift = bsize >> 1; - if (kmul_split(a, shift, &ah, &al) < 0) goto fail; - assert(Py_SIZE(ah) > 0); /* the split isn't degenerate */ - - if (a == b) { - bh = ah; - bl = al; - Py_INCREF(bh); - Py_INCREF(bl); - } - else if (kmul_split(b, shift, &bh, &bl) < 0) goto fail; - - /* The plan: - * 1. Allocate result space (asize + bsize digits: that's always - * enough). - * 2. Compute ah*bh, and copy into result at 2*shift. - * 3. Compute al*bl, and copy into result at 0. Note that this - * can't overlap with #2. - * 4. Subtract al*bl from the result, starting at shift. This may - * underflow (borrow out of the high digit), but we don't care: - * we're effectively doing unsigned arithmetic mod - * BASE**(sizea + sizeb), and so long as the *final* result fits, - * borrows and carries out of the high digit can be ignored. - * 5. Subtract ah*bh from the result, starting at shift. - * 6. Compute (ah+al)*(bh+bl), and add it into the result starting - * at shift. - */ - - /* 1. Allocate result space. */ - ret = _PyLong_New(asize + bsize); - if (ret == NULL) goto fail; + Py_ssize_t asize = ABS(Py_SIZE(a)); + Py_ssize_t bsize = ABS(Py_SIZE(b)); + PyLongObject *ah = NULL; + PyLongObject *al = NULL; + PyLongObject *bh = NULL; + PyLongObject *bl = NULL; + PyLongObject *ret = NULL; + PyLongObject *t1, *t2, *t3; + Py_ssize_t shift; /* the number of digits we split off */ + Py_ssize_t i; + + /* (ah*X+al)(bh*X+bl) = ah*bh*X*X + (ah*bl + al*bh)*X + al*bl + * Let k = (ah+al)*(bh+bl) = ah*bl + al*bh + ah*bh + al*bl + * Then the original product is + * ah*bh*X*X + (k - ah*bh - al*bl)*X + al*bl + * By picking X to be a power of 2, "*X" is just shifting, and it's + * been reduced to 3 multiplies on numbers half the size. + */ + + /* We want to split based on the larger number; fiddle so that b + * is largest. + */ + if (asize > bsize) { + t1 = a; + a = b; + b = t1; + + i = asize; + asize = bsize; + bsize = i; + } + + /* Use gradeschool math when either number is too small. */ + i = a == b ? KARATSUBA_SQUARE_CUTOFF : KARATSUBA_CUTOFF; + if (asize <= i) { + if (asize == 0) + return (PyLongObject *)PyLong_FromLong(0); + else + return x_mul(a, b); + } + + /* If a is small compared to b, splitting on b gives a degenerate + * case with ah==0, and Karatsuba may be (even much) less efficient + * than "grade school" then. However, we can still win, by viewing + * b as a string of "big digits", each of width a->ob_size. That + * leads to a sequence of balanced calls to k_mul. + */ + if (2 * asize <= bsize) + return k_lopsided_mul(a, b); + + /* Split a & b into hi & lo pieces. */ + shift = bsize >> 1; + if (kmul_split(a, shift, &ah, &al) < 0) goto fail; + assert(Py_SIZE(ah) > 0); /* the split isn't degenerate */ + + if (a == b) { + bh = ah; + bl = al; + Py_INCREF(bh); + Py_INCREF(bl); + } + else if (kmul_split(b, shift, &bh, &bl) < 0) goto fail; + + /* The plan: + * 1. Allocate result space (asize + bsize digits: that's always + * enough). + * 2. Compute ah*bh, and copy into result at 2*shift. + * 3. Compute al*bl, and copy into result at 0. Note that this + * can't overlap with #2. + * 4. Subtract al*bl from the result, starting at shift. This may + * underflow (borrow out of the high digit), but we don't care: + * we're effectively doing unsigned arithmetic mod + * BASE**(sizea + sizeb), and so long as the *final* result fits, + * borrows and carries out of the high digit can be ignored. + * 5. Subtract ah*bh from the result, starting at shift. + * 6. Compute (ah+al)*(bh+bl), and add it into the result starting + * at shift. + */ + + /* 1. Allocate result space. */ + ret = _PyLong_New(asize + bsize); + if (ret == NULL) goto fail; #ifdef Py_DEBUG - /* Fill with trash, to catch reference to uninitialized digits. */ - memset(ret->ob_digit, 0xDF, Py_SIZE(ret) * sizeof(digit)); + /* Fill with trash, to catch reference to uninitialized digits. */ + memset(ret->ob_digit, 0xDF, Py_SIZE(ret) * sizeof(digit)); #endif - /* 2. t1 <- ah*bh, and copy into high digits of result. */ - if ((t1 = k_mul(ah, bh)) == NULL) goto fail; - assert(Py_SIZE(t1) >= 0); - assert(2*shift + Py_SIZE(t1) <= Py_SIZE(ret)); - memcpy(ret->ob_digit + 2*shift, t1->ob_digit, - Py_SIZE(t1) * sizeof(digit)); - - /* Zero-out the digits higher than the ah*bh copy. */ - i = Py_SIZE(ret) - 2*shift - Py_SIZE(t1); - if (i) - memset(ret->ob_digit + 2*shift + Py_SIZE(t1), 0, - i * sizeof(digit)); - - /* 3. t2 <- al*bl, and copy into the low digits. */ - if ((t2 = k_mul(al, bl)) == NULL) { - Py_DECREF(t1); - goto fail; - } - assert(Py_SIZE(t2) >= 0); - assert(Py_SIZE(t2) <= 2*shift); /* no overlap with high digits */ - memcpy(ret->ob_digit, t2->ob_digit, Py_SIZE(t2) * sizeof(digit)); - - /* Zero out remaining digits. */ - i = 2*shift - Py_SIZE(t2); /* number of uninitialized digits */ - if (i) - memset(ret->ob_digit + Py_SIZE(t2), 0, i * sizeof(digit)); - - /* 4 & 5. Subtract ah*bh (t1) and al*bl (t2). We do al*bl first - * because it's fresher in cache. - */ - i = Py_SIZE(ret) - shift; /* # digits after shift */ - (void)v_isub(ret->ob_digit + shift, i, t2->ob_digit, Py_SIZE(t2)); - Py_DECREF(t2); - - (void)v_isub(ret->ob_digit + shift, i, t1->ob_digit, Py_SIZE(t1)); - Py_DECREF(t1); - - /* 6. t3 <- (ah+al)(bh+bl), and add into result. */ - if ((t1 = x_add(ah, al)) == NULL) goto fail; - Py_DECREF(ah); - Py_DECREF(al); - ah = al = NULL; - - if (a == b) { - t2 = t1; - Py_INCREF(t2); - } - else if ((t2 = x_add(bh, bl)) == NULL) { - Py_DECREF(t1); - goto fail; - } - Py_DECREF(bh); - Py_DECREF(bl); - bh = bl = NULL; - - t3 = k_mul(t1, t2); - Py_DECREF(t1); - Py_DECREF(t2); - if (t3 == NULL) goto fail; - assert(Py_SIZE(t3) >= 0); - - /* Add t3. It's not obvious why we can't run out of room here. - * See the (*) comment after this function. - */ - (void)v_iadd(ret->ob_digit + shift, i, t3->ob_digit, Py_SIZE(t3)); - Py_DECREF(t3); + /* 2. t1 <- ah*bh, and copy into high digits of result. */ + if ((t1 = k_mul(ah, bh)) == NULL) goto fail; + assert(Py_SIZE(t1) >= 0); + assert(2*shift + Py_SIZE(t1) <= Py_SIZE(ret)); + memcpy(ret->ob_digit + 2*shift, t1->ob_digit, + Py_SIZE(t1) * sizeof(digit)); + + /* Zero-out the digits higher than the ah*bh copy. */ + i = Py_SIZE(ret) - 2*shift - Py_SIZE(t1); + if (i) + memset(ret->ob_digit + 2*shift + Py_SIZE(t1), 0, + i * sizeof(digit)); + + /* 3. t2 <- al*bl, and copy into the low digits. */ + if ((t2 = k_mul(al, bl)) == NULL) { + Py_DECREF(t1); + goto fail; + } + assert(Py_SIZE(t2) >= 0); + assert(Py_SIZE(t2) <= 2*shift); /* no overlap with high digits */ + memcpy(ret->ob_digit, t2->ob_digit, Py_SIZE(t2) * sizeof(digit)); + + /* Zero out remaining digits. */ + i = 2*shift - Py_SIZE(t2); /* number of uninitialized digits */ + if (i) + memset(ret->ob_digit + Py_SIZE(t2), 0, i * sizeof(digit)); + + /* 4 & 5. Subtract ah*bh (t1) and al*bl (t2). We do al*bl first + * because it's fresher in cache. + */ + i = Py_SIZE(ret) - shift; /* # digits after shift */ + (void)v_isub(ret->ob_digit + shift, i, t2->ob_digit, Py_SIZE(t2)); + Py_DECREF(t2); + + (void)v_isub(ret->ob_digit + shift, i, t1->ob_digit, Py_SIZE(t1)); + Py_DECREF(t1); + + /* 6. t3 <- (ah+al)(bh+bl), and add into result. */ + if ((t1 = x_add(ah, al)) == NULL) goto fail; + Py_DECREF(ah); + Py_DECREF(al); + ah = al = NULL; + + if (a == b) { + t2 = t1; + Py_INCREF(t2); + } + else if ((t2 = x_add(bh, bl)) == NULL) { + Py_DECREF(t1); + goto fail; + } + Py_DECREF(bh); + Py_DECREF(bl); + bh = bl = NULL; + + t3 = k_mul(t1, t2); + Py_DECREF(t1); + Py_DECREF(t2); + if (t3 == NULL) goto fail; + assert(Py_SIZE(t3) >= 0); + + /* Add t3. It's not obvious why we can't run out of room here. + * See the (*) comment after this function. + */ + (void)v_iadd(ret->ob_digit + shift, i, t3->ob_digit, Py_SIZE(t3)); + Py_DECREF(t3); - return long_normalize(ret); + return long_normalize(ret); fail: - Py_XDECREF(ret); - Py_XDECREF(ah); - Py_XDECREF(al); - Py_XDECREF(bh); - Py_XDECREF(bl); - return NULL; + Py_XDECREF(ret); + Py_XDECREF(ah); + Py_XDECREF(al); + Py_XDECREF(bh); + Py_XDECREF(bl); + return NULL; } /* (*) Why adding t3 can't "run out of room" above. @@ -3086,85 +3086,85 @@ static PyLongObject * k_lopsided_mul(PyLongObject *a, PyLongObject *b) { - const Py_ssize_t asize = ABS(Py_SIZE(a)); - Py_ssize_t bsize = ABS(Py_SIZE(b)); - Py_ssize_t nbdone; /* # of b digits already multiplied */ - PyLongObject *ret; - PyLongObject *bslice = NULL; - - assert(asize > KARATSUBA_CUTOFF); - assert(2 * asize <= bsize); - - /* Allocate result space, and zero it out. */ - ret = _PyLong_New(asize + bsize); - if (ret == NULL) - return NULL; - memset(ret->ob_digit, 0, Py_SIZE(ret) * sizeof(digit)); - - /* Successive slices of b are copied into bslice. */ - bslice = _PyLong_New(asize); - if (bslice == NULL) - goto fail; - - nbdone = 0; - while (bsize > 0) { - PyLongObject *product; - const Py_ssize_t nbtouse = MIN(bsize, asize); - - /* Multiply the next slice of b by a. */ - memcpy(bslice->ob_digit, b->ob_digit + nbdone, - nbtouse * sizeof(digit)); - Py_SIZE(bslice) = nbtouse; - product = k_mul(a, bslice); - if (product == NULL) - goto fail; - - /* Add into result. */ - (void)v_iadd(ret->ob_digit + nbdone, Py_SIZE(ret) - nbdone, - product->ob_digit, Py_SIZE(product)); - Py_DECREF(product); - - bsize -= nbtouse; - nbdone += nbtouse; - } + const Py_ssize_t asize = ABS(Py_SIZE(a)); + Py_ssize_t bsize = ABS(Py_SIZE(b)); + Py_ssize_t nbdone; /* # of b digits already multiplied */ + PyLongObject *ret; + PyLongObject *bslice = NULL; + + assert(asize > KARATSUBA_CUTOFF); + assert(2 * asize <= bsize); + + /* Allocate result space, and zero it out. */ + ret = _PyLong_New(asize + bsize); + if (ret == NULL) + return NULL; + memset(ret->ob_digit, 0, Py_SIZE(ret) * sizeof(digit)); + + /* Successive slices of b are copied into bslice. */ + bslice = _PyLong_New(asize); + if (bslice == NULL) + goto fail; + + nbdone = 0; + while (bsize > 0) { + PyLongObject *product; + const Py_ssize_t nbtouse = MIN(bsize, asize); + + /* Multiply the next slice of b by a. */ + memcpy(bslice->ob_digit, b->ob_digit + nbdone, + nbtouse * sizeof(digit)); + Py_SIZE(bslice) = nbtouse; + product = k_mul(a, bslice); + if (product == NULL) + goto fail; + + /* Add into result. */ + (void)v_iadd(ret->ob_digit + nbdone, Py_SIZE(ret) - nbdone, + product->ob_digit, Py_SIZE(product)); + Py_DECREF(product); + + bsize -= nbtouse; + nbdone += nbtouse; + } - Py_DECREF(bslice); - return long_normalize(ret); + Py_DECREF(bslice); + return long_normalize(ret); fail: - Py_DECREF(ret); - Py_XDECREF(bslice); - return NULL; + Py_DECREF(ret); + Py_XDECREF(bslice); + return NULL; } static PyObject * long_mul(PyLongObject *a, PyLongObject *b) { - PyLongObject *z; + PyLongObject *z; - CHECK_BINOP(a, b); + CHECK_BINOP(a, b); - /* fast path for single-digit multiplication */ - if (ABS(Py_SIZE(a)) <= 1 && ABS(Py_SIZE(b)) <= 1) { - stwodigits v = (stwodigits)(MEDIUM_VALUE(a)) * MEDIUM_VALUE(b); + /* fast path for single-digit multiplication */ + if (ABS(Py_SIZE(a)) <= 1 && ABS(Py_SIZE(b)) <= 1) { + stwodigits v = (stwodigits)(MEDIUM_VALUE(a)) * MEDIUM_VALUE(b); #ifdef HAVE_LONG_LONG - return PyLong_FromLongLong((PY_LONG_LONG)v); + return PyLong_FromLongLong((PY_LONG_LONG)v); #else - /* if we don't have long long then we're almost certainly - using 15-bit digits, so v will fit in a long. In the - unlikely event that we're using 30-bit digits on a platform - without long long, a large v will just cause us to fall - through to the general multiplication code below. */ - if (v >= LONG_MIN && v <= LONG_MAX) - return PyLong_FromLong((long)v); + /* if we don't have long long then we're almost certainly + using 15-bit digits, so v will fit in a long. In the + unlikely event that we're using 30-bit digits on a platform + without long long, a large v will just cause us to fall + through to the general multiplication code below. */ + if (v >= LONG_MIN && v <= LONG_MAX) + return PyLong_FromLong((long)v); #endif - } + } - z = k_mul(a, b); - /* Negate if exactly one of the inputs is negative. */ - if (((Py_SIZE(a) ^ Py_SIZE(b)) < 0) && z) - NEGATE(z); - return (PyObject *)z; + z = k_mul(a, b); + /* Negate if exactly one of the inputs is negative. */ + if (((Py_SIZE(a) ^ Py_SIZE(b)) < 0) && z) + NEGATE(z); + return (PyObject *)z; } /* The / and % operators are now defined in terms of divmod(). @@ -3173,11 +3173,11 @@ |a| by |b|, with the sign of a. This is also expressed as a - b*trunc(a/b), if trunc truncates towards zero. Some examples: - a b a rem b a mod b - 13 10 3 3 - -13 10 -3 7 - 13 -10 3 -7 - -13 -10 -3 -3 + a b a rem b a mod b + 13 10 3 3 + -13 10 -3 7 + 13 -10 3 -7 + -13 -10 -3 -3 So, to get from rem to mod, we have to add b if a and b have different signs. We then subtract one from the 'div' part of the outcome to keep the invariant intact. */ @@ -3190,57 +3190,57 @@ */ static int l_divmod(PyLongObject *v, PyLongObject *w, - PyLongObject **pdiv, PyLongObject **pmod) + PyLongObject **pdiv, PyLongObject **pmod) { - PyLongObject *div, *mod; + PyLongObject *div, *mod; - if (long_divrem(v, w, &div, &mod) < 0) - return -1; - if ((Py_SIZE(mod) < 0 && Py_SIZE(w) > 0) || - (Py_SIZE(mod) > 0 && Py_SIZE(w) < 0)) { - PyLongObject *temp; - PyLongObject *one; - temp = (PyLongObject *) long_add(mod, w); - Py_DECREF(mod); - mod = temp; - if (mod == NULL) { - Py_DECREF(div); - return -1; - } - one = (PyLongObject *) PyLong_FromLong(1L); - if (one == NULL || - (temp = (PyLongObject *) long_sub(div, one)) == NULL) { - Py_DECREF(mod); - Py_DECREF(div); - Py_XDECREF(one); - return -1; - } - Py_DECREF(one); - Py_DECREF(div); - div = temp; - } - if (pdiv != NULL) - *pdiv = div; - else - Py_DECREF(div); - - if (pmod != NULL) - *pmod = mod; - else - Py_DECREF(mod); + if (long_divrem(v, w, &div, &mod) < 0) + return -1; + if ((Py_SIZE(mod) < 0 && Py_SIZE(w) > 0) || + (Py_SIZE(mod) > 0 && Py_SIZE(w) < 0)) { + PyLongObject *temp; + PyLongObject *one; + temp = (PyLongObject *) long_add(mod, w); + Py_DECREF(mod); + mod = temp; + if (mod == NULL) { + Py_DECREF(div); + return -1; + } + one = (PyLongObject *) PyLong_FromLong(1L); + if (one == NULL || + (temp = (PyLongObject *) long_sub(div, one)) == NULL) { + Py_DECREF(mod); + Py_DECREF(div); + Py_XDECREF(one); + return -1; + } + Py_DECREF(one); + Py_DECREF(div); + div = temp; + } + if (pdiv != NULL) + *pdiv = div; + else + Py_DECREF(div); + + if (pmod != NULL) + *pmod = mod; + else + Py_DECREF(mod); - return 0; + return 0; } static PyObject * long_div(PyObject *a, PyObject *b) { - PyLongObject *div; + PyLongObject *div; - CHECK_BINOP(a, b); - if (l_divmod((PyLongObject*)a, (PyLongObject*)b, &div, NULL) < 0) - div = NULL; - return (PyObject *)div; + CHECK_BINOP(a, b); + if (l_divmod((PyLongObject*)a, (PyLongObject*)b, &div, NULL) < 0) + div = NULL; + return (PyObject *)div; } /* PyLong/PyLong -> float, with correctly rounded result. */ @@ -3251,631 +3251,631 @@ static PyObject * long_true_divide(PyObject *v, PyObject *w) { - PyLongObject *a, *b, *x; - Py_ssize_t a_size, b_size, shift, extra_bits, diff, x_size, x_bits; - digit mask, low; - int inexact, negate, a_is_small, b_is_small; - double dx, result; - - CHECK_BINOP(v, w); - a = (PyLongObject *)v; - b = (PyLongObject *)w; - - /* - Method in a nutshell: - - 0. reduce to case a, b > 0; filter out obvious underflow/overflow - 1. choose a suitable integer 'shift' - 2. use integer arithmetic to compute x = floor(2**-shift*a/b) - 3. adjust x for correct rounding - 4. convert x to a double dx with the same value - 5. return ldexp(dx, shift). - - In more detail: - - 0. For any a, a/0 raises ZeroDivisionError; for nonzero b, 0/b - returns either 0.0 or -0.0, depending on the sign of b. For a and - b both nonzero, ignore signs of a and b, and add the sign back in - at the end. Now write a_bits and b_bits for the bit lengths of a - and b respectively (that is, a_bits = 1 + floor(log_2(a)); likewise - for b). Then - - 2**(a_bits - b_bits - 1) < a/b < 2**(a_bits - b_bits + 1). - - So if a_bits - b_bits > DBL_MAX_EXP then a/b > 2**DBL_MAX_EXP and - so overflows. Similarly, if a_bits - b_bits < DBL_MIN_EXP - - DBL_MANT_DIG - 1 then a/b underflows to 0. With these cases out of - the way, we can assume that - - DBL_MIN_EXP - DBL_MANT_DIG - 1 <= a_bits - b_bits <= DBL_MAX_EXP. - - 1. The integer 'shift' is chosen so that x has the right number of - bits for a double, plus two or three extra bits that will be used - in the rounding decisions. Writing a_bits and b_bits for the - number of significant bits in a and b respectively, a - straightforward formula for shift is: - - shift = a_bits - b_bits - DBL_MANT_DIG - 2 - - This is fine in the usual case, but if a/b is smaller than the - smallest normal float then it can lead to double rounding on an - IEEE 754 platform, giving incorrectly rounded results. So we - adjust the formula slightly. The actual formula used is: - - shift = MAX(a_bits - b_bits, DBL_MIN_EXP) - DBL_MANT_DIG - 2 - - 2. The quantity x is computed by first shifting a (left -shift bits - if shift <= 0, right shift bits if shift > 0) and then dividing by - b. For both the shift and the division, we keep track of whether - the result is inexact, in a flag 'inexact'; this information is - needed at the rounding stage. - - With the choice of shift above, together with our assumption that - a_bits - b_bits >= DBL_MIN_EXP - DBL_MANT_DIG - 1, it follows - that x >= 1. - - 3. Now x * 2**shift <= a/b < (x+1) * 2**shift. We want to replace - this with an exactly representable float of the form - - round(x/2**extra_bits) * 2**(extra_bits+shift). - - For float representability, we need x/2**extra_bits < - 2**DBL_MANT_DIG and extra_bits + shift >= DBL_MIN_EXP - - DBL_MANT_DIG. This translates to the condition: - - extra_bits >= MAX(x_bits, DBL_MIN_EXP - shift) - DBL_MANT_DIG - - To round, we just modify the bottom digit of x in-place; this can - end up giving a digit with value > PyLONG_MASK, but that's not a - problem since digits can hold values up to 2*PyLONG_MASK+1. - - With the original choices for shift above, extra_bits will always - be 2 or 3. Then rounding under the round-half-to-even rule, we - round up iff the most significant of the extra bits is 1, and - either: (a) the computation of x in step 2 had an inexact result, - or (b) at least one other of the extra bits is 1, or (c) the least - significant bit of x (above those to be rounded) is 1. - - 4. Conversion to a double is straightforward; all floating-point - operations involved in the conversion are exact, so there's no - danger of rounding errors. - - 5. Use ldexp(x, shift) to compute x*2**shift, the final result. - The result will always be exactly representable as a double, except - in the case that it overflows. To avoid dependence on the exact - behaviour of ldexp on overflow, we check for overflow before - applying ldexp. The result of ldexp is adjusted for sign before - returning. - */ - - /* Reduce to case where a and b are both positive. */ - a_size = ABS(Py_SIZE(a)); - b_size = ABS(Py_SIZE(b)); - negate = (Py_SIZE(a) < 0) ^ (Py_SIZE(b) < 0); - if (b_size == 0) { - PyErr_SetString(PyExc_ZeroDivisionError, - "division by zero"); - goto error; - } - if (a_size == 0) - goto underflow_or_zero; - - /* Fast path for a and b small (exactly representable in a double). - Relies on floating-point division being correctly rounded; results - may be subject to double rounding on x86 machines that operate with - the x87 FPU set to 64-bit precision. */ - a_is_small = a_size <= MANT_DIG_DIGITS || - (a_size == MANT_DIG_DIGITS+1 && - a->ob_digit[MANT_DIG_DIGITS] >> MANT_DIG_BITS == 0); - b_is_small = b_size <= MANT_DIG_DIGITS || - (b_size == MANT_DIG_DIGITS+1 && - b->ob_digit[MANT_DIG_DIGITS] >> MANT_DIG_BITS == 0); - if (a_is_small && b_is_small) { - double da, db; - da = a->ob_digit[--a_size]; - while (a_size > 0) - da = da * PyLong_BASE + a->ob_digit[--a_size]; - db = b->ob_digit[--b_size]; - while (b_size > 0) - db = db * PyLong_BASE + b->ob_digit[--b_size]; - result = da / db; - goto success; - } - - /* Catch obvious cases of underflow and overflow */ - diff = a_size - b_size; - if (diff > PY_SSIZE_T_MAX/PyLong_SHIFT - 1) - /* Extreme overflow */ - goto overflow; - else if (diff < 1 - PY_SSIZE_T_MAX/PyLong_SHIFT) - /* Extreme underflow */ - goto underflow_or_zero; - /* Next line is now safe from overflowing a Py_ssize_t */ - diff = diff * PyLong_SHIFT + bits_in_digit(a->ob_digit[a_size - 1]) - - bits_in_digit(b->ob_digit[b_size - 1]); - /* Now diff = a_bits - b_bits. */ - if (diff > DBL_MAX_EXP) - goto overflow; - else if (diff < DBL_MIN_EXP - DBL_MANT_DIG - 1) - goto underflow_or_zero; - - /* Choose value for shift; see comments for step 1 above. */ - shift = MAX(diff, DBL_MIN_EXP) - DBL_MANT_DIG - 2; - - inexact = 0; - - /* x = abs(a * 2**-shift) */ - if (shift <= 0) { - Py_ssize_t i, shift_digits = -shift / PyLong_SHIFT; - digit rem; - /* x = a << -shift */ - if (a_size >= PY_SSIZE_T_MAX - 1 - shift_digits) { - /* In practice, it's probably impossible to end up - here. Both a and b would have to be enormous, - using close to SIZE_T_MAX bytes of memory each. */ - PyErr_SetString(PyExc_OverflowError, - "intermediate overflow during division"); - goto error; - } - x = _PyLong_New(a_size + shift_digits + 1); - if (x == NULL) - goto error; - for (i = 0; i < shift_digits; i++) - x->ob_digit[i] = 0; - rem = v_lshift(x->ob_digit + shift_digits, a->ob_digit, - a_size, -shift % PyLong_SHIFT); - x->ob_digit[a_size + shift_digits] = rem; - } - else { - Py_ssize_t shift_digits = shift / PyLong_SHIFT; - digit rem; - /* x = a >> shift */ - assert(a_size >= shift_digits); - x = _PyLong_New(a_size - shift_digits); - if (x == NULL) - goto error; - rem = v_rshift(x->ob_digit, a->ob_digit + shift_digits, - a_size - shift_digits, shift % PyLong_SHIFT); - /* set inexact if any of the bits shifted out is nonzero */ - if (rem) - inexact = 1; - while (!inexact && shift_digits > 0) - if (a->ob_digit[--shift_digits]) - inexact = 1; - } - long_normalize(x); - x_size = Py_SIZE(x); - - /* x //= b. If the remainder is nonzero, set inexact. We own the only - reference to x, so it's safe to modify it in-place. */ - if (b_size == 1) { - digit rem = inplace_divrem1(x->ob_digit, x->ob_digit, x_size, - b->ob_digit[0]); - long_normalize(x); - if (rem) - inexact = 1; - } - else { - PyLongObject *div, *rem; - div = x_divrem(x, b, &rem); - Py_DECREF(x); - x = div; - if (x == NULL) - goto error; - if (Py_SIZE(rem)) - inexact = 1; - Py_DECREF(rem); - } - x_size = ABS(Py_SIZE(x)); - assert(x_size > 0); /* result of division is never zero */ - x_bits = (x_size-1)*PyLong_SHIFT+bits_in_digit(x->ob_digit[x_size-1]); - - /* The number of extra bits that have to be rounded away. */ - extra_bits = MAX(x_bits, DBL_MIN_EXP - shift) - DBL_MANT_DIG; - assert(extra_bits == 2 || extra_bits == 3); - - /* Round by directly modifying the low digit of x. */ - mask = (digit)1 << (extra_bits - 1); - low = x->ob_digit[0] | inexact; - if (low & mask && low & (3*mask-1)) - low += mask; - x->ob_digit[0] = low & ~(mask-1U); - - /* Convert x to a double dx; the conversion is exact. */ - dx = x->ob_digit[--x_size]; - while (x_size > 0) - dx = dx * PyLong_BASE + x->ob_digit[--x_size]; - Py_DECREF(x); - - /* Check whether ldexp result will overflow a double. */ - if (shift + x_bits >= DBL_MAX_EXP && - (shift + x_bits > DBL_MAX_EXP || dx == ldexp(1.0, (int)x_bits))) - goto overflow; - result = ldexp(dx, (int)shift); + PyLongObject *a, *b, *x; + Py_ssize_t a_size, b_size, shift, extra_bits, diff, x_size, x_bits; + digit mask, low; + int inexact, negate, a_is_small, b_is_small; + double dx, result; + + CHECK_BINOP(v, w); + a = (PyLongObject *)v; + b = (PyLongObject *)w; + + /* + Method in a nutshell: + + 0. reduce to case a, b > 0; filter out obvious underflow/overflow + 1. choose a suitable integer 'shift' + 2. use integer arithmetic to compute x = floor(2**-shift*a/b) + 3. adjust x for correct rounding + 4. convert x to a double dx with the same value + 5. return ldexp(dx, shift). + + In more detail: + + 0. For any a, a/0 raises ZeroDivisionError; for nonzero b, 0/b + returns either 0.0 or -0.0, depending on the sign of b. For a and + b both nonzero, ignore signs of a and b, and add the sign back in + at the end. Now write a_bits and b_bits for the bit lengths of a + and b respectively (that is, a_bits = 1 + floor(log_2(a)); likewise + for b). Then + + 2**(a_bits - b_bits - 1) < a/b < 2**(a_bits - b_bits + 1). + + So if a_bits - b_bits > DBL_MAX_EXP then a/b > 2**DBL_MAX_EXP and + so overflows. Similarly, if a_bits - b_bits < DBL_MIN_EXP - + DBL_MANT_DIG - 1 then a/b underflows to 0. With these cases out of + the way, we can assume that + + DBL_MIN_EXP - DBL_MANT_DIG - 1 <= a_bits - b_bits <= DBL_MAX_EXP. + + 1. The integer 'shift' is chosen so that x has the right number of + bits for a double, plus two or three extra bits that will be used + in the rounding decisions. Writing a_bits and b_bits for the + number of significant bits in a and b respectively, a + straightforward formula for shift is: + + shift = a_bits - b_bits - DBL_MANT_DIG - 2 + + This is fine in the usual case, but if a/b is smaller than the + smallest normal float then it can lead to double rounding on an + IEEE 754 platform, giving incorrectly rounded results. So we + adjust the formula slightly. The actual formula used is: + + shift = MAX(a_bits - b_bits, DBL_MIN_EXP) - DBL_MANT_DIG - 2 + + 2. The quantity x is computed by first shifting a (left -shift bits + if shift <= 0, right shift bits if shift > 0) and then dividing by + b. For both the shift and the division, we keep track of whether + the result is inexact, in a flag 'inexact'; this information is + needed at the rounding stage. + + With the choice of shift above, together with our assumption that + a_bits - b_bits >= DBL_MIN_EXP - DBL_MANT_DIG - 1, it follows + that x >= 1. + + 3. Now x * 2**shift <= a/b < (x+1) * 2**shift. We want to replace + this with an exactly representable float of the form + + round(x/2**extra_bits) * 2**(extra_bits+shift). + + For float representability, we need x/2**extra_bits < + 2**DBL_MANT_DIG and extra_bits + shift >= DBL_MIN_EXP - + DBL_MANT_DIG. This translates to the condition: + + extra_bits >= MAX(x_bits, DBL_MIN_EXP - shift) - DBL_MANT_DIG + + To round, we just modify the bottom digit of x in-place; this can + end up giving a digit with value > PyLONG_MASK, but that's not a + problem since digits can hold values up to 2*PyLONG_MASK+1. + + With the original choices for shift above, extra_bits will always + be 2 or 3. Then rounding under the round-half-to-even rule, we + round up iff the most significant of the extra bits is 1, and + either: (a) the computation of x in step 2 had an inexact result, + or (b) at least one other of the extra bits is 1, or (c) the least + significant bit of x (above those to be rounded) is 1. + + 4. Conversion to a double is straightforward; all floating-point + operations involved in the conversion are exact, so there's no + danger of rounding errors. + + 5. Use ldexp(x, shift) to compute x*2**shift, the final result. + The result will always be exactly representable as a double, except + in the case that it overflows. To avoid dependence on the exact + behaviour of ldexp on overflow, we check for overflow before + applying ldexp. The result of ldexp is adjusted for sign before + returning. + */ + + /* Reduce to case where a and b are both positive. */ + a_size = ABS(Py_SIZE(a)); + b_size = ABS(Py_SIZE(b)); + negate = (Py_SIZE(a) < 0) ^ (Py_SIZE(b) < 0); + if (b_size == 0) { + PyErr_SetString(PyExc_ZeroDivisionError, + "division by zero"); + goto error; + } + if (a_size == 0) + goto underflow_or_zero; + + /* Fast path for a and b small (exactly representable in a double). + Relies on floating-point division being correctly rounded; results + may be subject to double rounding on x86 machines that operate with + the x87 FPU set to 64-bit precision. */ + a_is_small = a_size <= MANT_DIG_DIGITS || + (a_size == MANT_DIG_DIGITS+1 && + a->ob_digit[MANT_DIG_DIGITS] >> MANT_DIG_BITS == 0); + b_is_small = b_size <= MANT_DIG_DIGITS || + (b_size == MANT_DIG_DIGITS+1 && + b->ob_digit[MANT_DIG_DIGITS] >> MANT_DIG_BITS == 0); + if (a_is_small && b_is_small) { + double da, db; + da = a->ob_digit[--a_size]; + while (a_size > 0) + da = da * PyLong_BASE + a->ob_digit[--a_size]; + db = b->ob_digit[--b_size]; + while (b_size > 0) + db = db * PyLong_BASE + b->ob_digit[--b_size]; + result = da / db; + goto success; + } + + /* Catch obvious cases of underflow and overflow */ + diff = a_size - b_size; + if (diff > PY_SSIZE_T_MAX/PyLong_SHIFT - 1) + /* Extreme overflow */ + goto overflow; + else if (diff < 1 - PY_SSIZE_T_MAX/PyLong_SHIFT) + /* Extreme underflow */ + goto underflow_or_zero; + /* Next line is now safe from overflowing a Py_ssize_t */ + diff = diff * PyLong_SHIFT + bits_in_digit(a->ob_digit[a_size - 1]) - + bits_in_digit(b->ob_digit[b_size - 1]); + /* Now diff = a_bits - b_bits. */ + if (diff > DBL_MAX_EXP) + goto overflow; + else if (diff < DBL_MIN_EXP - DBL_MANT_DIG - 1) + goto underflow_or_zero; + + /* Choose value for shift; see comments for step 1 above. */ + shift = MAX(diff, DBL_MIN_EXP) - DBL_MANT_DIG - 2; + + inexact = 0; + + /* x = abs(a * 2**-shift) */ + if (shift <= 0) { + Py_ssize_t i, shift_digits = -shift / PyLong_SHIFT; + digit rem; + /* x = a << -shift */ + if (a_size >= PY_SSIZE_T_MAX - 1 - shift_digits) { + /* In practice, it's probably impossible to end up + here. Both a and b would have to be enormous, + using close to SIZE_T_MAX bytes of memory each. */ + PyErr_SetString(PyExc_OverflowError, + "intermediate overflow during division"); + goto error; + } + x = _PyLong_New(a_size + shift_digits + 1); + if (x == NULL) + goto error; + for (i = 0; i < shift_digits; i++) + x->ob_digit[i] = 0; + rem = v_lshift(x->ob_digit + shift_digits, a->ob_digit, + a_size, -shift % PyLong_SHIFT); + x->ob_digit[a_size + shift_digits] = rem; + } + else { + Py_ssize_t shift_digits = shift / PyLong_SHIFT; + digit rem; + /* x = a >> shift */ + assert(a_size >= shift_digits); + x = _PyLong_New(a_size - shift_digits); + if (x == NULL) + goto error; + rem = v_rshift(x->ob_digit, a->ob_digit + shift_digits, + a_size - shift_digits, shift % PyLong_SHIFT); + /* set inexact if any of the bits shifted out is nonzero */ + if (rem) + inexact = 1; + while (!inexact && shift_digits > 0) + if (a->ob_digit[--shift_digits]) + inexact = 1; + } + long_normalize(x); + x_size = Py_SIZE(x); + + /* x //= b. If the remainder is nonzero, set inexact. We own the only + reference to x, so it's safe to modify it in-place. */ + if (b_size == 1) { + digit rem = inplace_divrem1(x->ob_digit, x->ob_digit, x_size, + b->ob_digit[0]); + long_normalize(x); + if (rem) + inexact = 1; + } + else { + PyLongObject *div, *rem; + div = x_divrem(x, b, &rem); + Py_DECREF(x); + x = div; + if (x == NULL) + goto error; + if (Py_SIZE(rem)) + inexact = 1; + Py_DECREF(rem); + } + x_size = ABS(Py_SIZE(x)); + assert(x_size > 0); /* result of division is never zero */ + x_bits = (x_size-1)*PyLong_SHIFT+bits_in_digit(x->ob_digit[x_size-1]); + + /* The number of extra bits that have to be rounded away. */ + extra_bits = MAX(x_bits, DBL_MIN_EXP - shift) - DBL_MANT_DIG; + assert(extra_bits == 2 || extra_bits == 3); + + /* Round by directly modifying the low digit of x. */ + mask = (digit)1 << (extra_bits - 1); + low = x->ob_digit[0] | inexact; + if (low & mask && low & (3*mask-1)) + low += mask; + x->ob_digit[0] = low & ~(mask-1U); + + /* Convert x to a double dx; the conversion is exact. */ + dx = x->ob_digit[--x_size]; + while (x_size > 0) + dx = dx * PyLong_BASE + x->ob_digit[--x_size]; + Py_DECREF(x); + + /* Check whether ldexp result will overflow a double. */ + if (shift + x_bits >= DBL_MAX_EXP && + (shift + x_bits > DBL_MAX_EXP || dx == ldexp(1.0, (int)x_bits))) + goto overflow; + result = ldexp(dx, (int)shift); success: - return PyFloat_FromDouble(negate ? -result : result); + return PyFloat_FromDouble(negate ? -result : result); underflow_or_zero: - return PyFloat_FromDouble(negate ? -0.0 : 0.0); + return PyFloat_FromDouble(negate ? -0.0 : 0.0); overflow: - PyErr_SetString(PyExc_OverflowError, - "integer division result too large for a float"); + PyErr_SetString(PyExc_OverflowError, + "integer division result too large for a float"); error: - return NULL; + return NULL; } static PyObject * long_mod(PyObject *a, PyObject *b) { - PyLongObject *mod; - - CHECK_BINOP(a, b); - - if (l_divmod((PyLongObject*)a, (PyLongObject*)b, NULL, &mod) < 0) - mod = NULL; - return (PyObject *)mod; + PyLongObject *mod; + + CHECK_BINOP(a, b); + + if (l_divmod((PyLongObject*)a, (PyLongObject*)b, NULL, &mod) < 0) + mod = NULL; + return (PyObject *)mod; } static PyObject * long_divmod(PyObject *a, PyObject *b) { - PyLongObject *div, *mod; - PyObject *z; + PyLongObject *div, *mod; + PyObject *z; - CHECK_BINOP(a, b); + CHECK_BINOP(a, b); - if (l_divmod((PyLongObject*)a, (PyLongObject*)b, &div, &mod) < 0) { - return NULL; - } - z = PyTuple_New(2); - if (z != NULL) { - PyTuple_SetItem(z, 0, (PyObject *) div); - PyTuple_SetItem(z, 1, (PyObject *) mod); - } - else { - Py_DECREF(div); - Py_DECREF(mod); - } - return z; + if (l_divmod((PyLongObject*)a, (PyLongObject*)b, &div, &mod) < 0) { + return NULL; + } + z = PyTuple_New(2); + if (z != NULL) { + PyTuple_SetItem(z, 0, (PyObject *) div); + PyTuple_SetItem(z, 1, (PyObject *) mod); + } + else { + Py_DECREF(div); + Py_DECREF(mod); + } + return z; } /* pow(v, w, x) */ static PyObject * long_pow(PyObject *v, PyObject *w, PyObject *x) { - PyLongObject *a, *b, *c; /* a,b,c = v,w,x */ - int negativeOutput = 0; /* if x<0 return negative output */ + PyLongObject *a, *b, *c; /* a,b,c = v,w,x */ + int negativeOutput = 0; /* if x<0 return negative output */ - PyLongObject *z = NULL; /* accumulated result */ - Py_ssize_t i, j, k; /* counters */ - PyLongObject *temp = NULL; - - /* 5-ary values. If the exponent is large enough, table is - * precomputed so that table[i] == a**i % c for i in range(32). - */ - PyLongObject *table[32] = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, - 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0}; - - /* a, b, c = v, w, x */ - CHECK_BINOP(v, w); - a = (PyLongObject*)v; Py_INCREF(a); - b = (PyLongObject*)w; Py_INCREF(b); - if (PyLong_Check(x)) { - c = (PyLongObject *)x; - Py_INCREF(x); - } - else if (x == Py_None) - c = NULL; - else { - Py_DECREF(a); - Py_DECREF(b); - Py_INCREF(Py_NotImplemented); - return Py_NotImplemented; - } - - if (Py_SIZE(b) < 0) { /* if exponent is negative */ - if (c) { - PyErr_SetString(PyExc_TypeError, "pow() 2nd argument " - "cannot be negative when 3rd argument specified"); - goto Error; - } - else { - /* else return a float. This works because we know - that this calls float_pow() which converts its - arguments to double. */ - Py_DECREF(a); - Py_DECREF(b); - return PyFloat_Type.tp_as_number->nb_power(v, w, x); - } - } - - if (c) { - /* if modulus == 0: - raise ValueError() */ - if (Py_SIZE(c) == 0) { - PyErr_SetString(PyExc_ValueError, - "pow() 3rd argument cannot be 0"); - goto Error; - } - - /* if modulus < 0: - negativeOutput = True - modulus = -modulus */ - if (Py_SIZE(c) < 0) { - negativeOutput = 1; - temp = (PyLongObject *)_PyLong_Copy(c); - if (temp == NULL) - goto Error; - Py_DECREF(c); - c = temp; - temp = NULL; - NEGATE(c); - } - - /* if modulus == 1: - return 0 */ - if ((Py_SIZE(c) == 1) && (c->ob_digit[0] == 1)) { - z = (PyLongObject *)PyLong_FromLong(0L); - goto Done; - } - - /* if base < 0: - base = base % modulus - Having the base positive just makes things easier. */ - if (Py_SIZE(a) < 0) { - if (l_divmod(a, c, NULL, &temp) < 0) - goto Error; - Py_DECREF(a); - a = temp; - temp = NULL; - } - } - - /* At this point a, b, and c are guaranteed non-negative UNLESS - c is NULL, in which case a may be negative. */ - - z = (PyLongObject *)PyLong_FromLong(1L); - if (z == NULL) - goto Error; - - /* Perform a modular reduction, X = X % c, but leave X alone if c - * is NULL. - */ -#define REDUCE(X) \ - if (c != NULL) { \ - if (l_divmod(X, c, NULL, &temp) < 0) \ - goto Error; \ - Py_XDECREF(X); \ - X = temp; \ - temp = NULL; \ - } - - /* Multiply two values, then reduce the result: - result = X*Y % c. If c is NULL, skip the mod. */ -#define MULT(X, Y, result) \ -{ \ - temp = (PyLongObject *)long_mul(X, Y); \ - if (temp == NULL) \ - goto Error; \ - Py_XDECREF(result); \ - result = temp; \ - temp = NULL; \ - REDUCE(result) \ -} - - if (Py_SIZE(b) <= FIVEARY_CUTOFF) { - /* Left-to-right binary exponentiation (HAC Algorithm 14.79) */ - /* http://www.cacr.math.uwaterloo.ca/hac/about/chap14.pdf */ - for (i = Py_SIZE(b) - 1; i >= 0; --i) { - digit bi = b->ob_digit[i]; - - for (j = (digit)1 << (PyLong_SHIFT-1); j != 0; j >>= 1) { - MULT(z, z, z) - if (bi & j) - MULT(z, a, z) - } - } - } - else { - /* Left-to-right 5-ary exponentiation (HAC Algorithm 14.82) */ - Py_INCREF(z); /* still holds 1L */ - table[0] = z; - for (i = 1; i < 32; ++i) - MULT(table[i-1], a, table[i]) - - for (i = Py_SIZE(b) - 1; i >= 0; --i) { - const digit bi = b->ob_digit[i]; - - for (j = PyLong_SHIFT - 5; j >= 0; j -= 5) { - const int index = (bi >> j) & 0x1f; - for (k = 0; k < 5; ++k) - MULT(z, z, z) - if (index) - MULT(z, table[index], z) - } - } - } - - if (negativeOutput && (Py_SIZE(z) != 0)) { - temp = (PyLongObject *)long_sub(z, c); - if (temp == NULL) - goto Error; - Py_DECREF(z); - z = temp; - temp = NULL; - } - goto Done; + PyLongObject *z = NULL; /* accumulated result */ + Py_ssize_t i, j, k; /* counters */ + PyLongObject *temp = NULL; + + /* 5-ary values. If the exponent is large enough, table is + * precomputed so that table[i] == a**i % c for i in range(32). + */ + PyLongObject *table[32] = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, + 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0}; + + /* a, b, c = v, w, x */ + CHECK_BINOP(v, w); + a = (PyLongObject*)v; Py_INCREF(a); + b = (PyLongObject*)w; Py_INCREF(b); + if (PyLong_Check(x)) { + c = (PyLongObject *)x; + Py_INCREF(x); + } + else if (x == Py_None) + c = NULL; + else { + Py_DECREF(a); + Py_DECREF(b); + Py_INCREF(Py_NotImplemented); + return Py_NotImplemented; + } + + if (Py_SIZE(b) < 0) { /* if exponent is negative */ + if (c) { + PyErr_SetString(PyExc_TypeError, "pow() 2nd argument " + "cannot be negative when 3rd argument specified"); + goto Error; + } + else { + /* else return a float. This works because we know + that this calls float_pow() which converts its + arguments to double. */ + Py_DECREF(a); + Py_DECREF(b); + return PyFloat_Type.tp_as_number->nb_power(v, w, x); + } + } + + if (c) { + /* if modulus == 0: + raise ValueError() */ + if (Py_SIZE(c) == 0) { + PyErr_SetString(PyExc_ValueError, + "pow() 3rd argument cannot be 0"); + goto Error; + } + + /* if modulus < 0: + negativeOutput = True + modulus = -modulus */ + if (Py_SIZE(c) < 0) { + negativeOutput = 1; + temp = (PyLongObject *)_PyLong_Copy(c); + if (temp == NULL) + goto Error; + Py_DECREF(c); + c = temp; + temp = NULL; + NEGATE(c); + } + + /* if modulus == 1: + return 0 */ + if ((Py_SIZE(c) == 1) && (c->ob_digit[0] == 1)) { + z = (PyLongObject *)PyLong_FromLong(0L); + goto Done; + } + + /* if base < 0: + base = base % modulus + Having the base positive just makes things easier. */ + if (Py_SIZE(a) < 0) { + if (l_divmod(a, c, NULL, &temp) < 0) + goto Error; + Py_DECREF(a); + a = temp; + temp = NULL; + } + } + + /* At this point a, b, and c are guaranteed non-negative UNLESS + c is NULL, in which case a may be negative. */ + + z = (PyLongObject *)PyLong_FromLong(1L); + if (z == NULL) + goto Error; + + /* Perform a modular reduction, X = X % c, but leave X alone if c + * is NULL. + */ +#define REDUCE(X) \ + if (c != NULL) { \ + if (l_divmod(X, c, NULL, &temp) < 0) \ + goto Error; \ + Py_XDECREF(X); \ + X = temp; \ + temp = NULL; \ + } + + /* Multiply two values, then reduce the result: + result = X*Y % c. If c is NULL, skip the mod. */ +#define MULT(X, Y, result) \ +{ \ + temp = (PyLongObject *)long_mul(X, Y); \ + if (temp == NULL) \ + goto Error; \ + Py_XDECREF(result); \ + result = temp; \ + temp = NULL; \ + REDUCE(result) \ +} + + if (Py_SIZE(b) <= FIVEARY_CUTOFF) { + /* Left-to-right binary exponentiation (HAC Algorithm 14.79) */ + /* http://www.cacr.math.uwaterloo.ca/hac/about/chap14.pdf */ + for (i = Py_SIZE(b) - 1; i >= 0; --i) { + digit bi = b->ob_digit[i]; + + for (j = (digit)1 << (PyLong_SHIFT-1); j != 0; j >>= 1) { + MULT(z, z, z) + if (bi & j) + MULT(z, a, z) + } + } + } + else { + /* Left-to-right 5-ary exponentiation (HAC Algorithm 14.82) */ + Py_INCREF(z); /* still holds 1L */ + table[0] = z; + for (i = 1; i < 32; ++i) + MULT(table[i-1], a, table[i]) + + for (i = Py_SIZE(b) - 1; i >= 0; --i) { + const digit bi = b->ob_digit[i]; + + for (j = PyLong_SHIFT - 5; j >= 0; j -= 5) { + const int index = (bi >> j) & 0x1f; + for (k = 0; k < 5; ++k) + MULT(z, z, z) + if (index) + MULT(z, table[index], z) + } + } + } + + if (negativeOutput && (Py_SIZE(z) != 0)) { + temp = (PyLongObject *)long_sub(z, c); + if (temp == NULL) + goto Error; + Py_DECREF(z); + z = temp; + temp = NULL; + } + goto Done; Error: - if (z != NULL) { - Py_DECREF(z); - z = NULL; - } - /* fall through */ + if (z != NULL) { + Py_DECREF(z); + z = NULL; + } + /* fall through */ Done: - if (Py_SIZE(b) > FIVEARY_CUTOFF) { - for (i = 0; i < 32; ++i) - Py_XDECREF(table[i]); - } - Py_DECREF(a); - Py_DECREF(b); - Py_XDECREF(c); - Py_XDECREF(temp); - return (PyObject *)z; + if (Py_SIZE(b) > FIVEARY_CUTOFF) { + for (i = 0; i < 32; ++i) + Py_XDECREF(table[i]); + } + Py_DECREF(a); + Py_DECREF(b); + Py_XDECREF(c); + Py_XDECREF(temp); + return (PyObject *)z; } static PyObject * long_invert(PyLongObject *v) { - /* Implement ~x as -(x+1) */ - PyLongObject *x; - PyLongObject *w; - if (ABS(Py_SIZE(v)) <=1) - return PyLong_FromLong(-(MEDIUM_VALUE(v)+1)); - w = (PyLongObject *)PyLong_FromLong(1L); - if (w == NULL) - return NULL; - x = (PyLongObject *) long_add(v, w); - Py_DECREF(w); - if (x == NULL) - return NULL; - Py_SIZE(x) = -(Py_SIZE(x)); - return (PyObject *)maybe_small_long(x); + /* Implement ~x as -(x+1) */ + PyLongObject *x; + PyLongObject *w; + if (ABS(Py_SIZE(v)) <=1) + return PyLong_FromLong(-(MEDIUM_VALUE(v)+1)); + w = (PyLongObject *)PyLong_FromLong(1L); + if (w == NULL) + return NULL; + x = (PyLongObject *) long_add(v, w); + Py_DECREF(w); + if (x == NULL) + return NULL; + Py_SIZE(x) = -(Py_SIZE(x)); + return (PyObject *)maybe_small_long(x); } static PyObject * long_neg(PyLongObject *v) { - PyLongObject *z; - if (ABS(Py_SIZE(v)) <= 1) - return PyLong_FromLong(-MEDIUM_VALUE(v)); - z = (PyLongObject *)_PyLong_Copy(v); - if (z != NULL) - Py_SIZE(z) = -(Py_SIZE(v)); - return (PyObject *)z; + PyLongObject *z; + if (ABS(Py_SIZE(v)) <= 1) + return PyLong_FromLong(-MEDIUM_VALUE(v)); + z = (PyLongObject *)_PyLong_Copy(v); + if (z != NULL) + Py_SIZE(z) = -(Py_SIZE(v)); + return (PyObject *)z; } static PyObject * long_abs(PyLongObject *v) { - if (Py_SIZE(v) < 0) - return long_neg(v); - else - return long_long((PyObject *)v); + if (Py_SIZE(v) < 0) + return long_neg(v); + else + return long_long((PyObject *)v); } static int long_bool(PyLongObject *v) { - return Py_SIZE(v) != 0; + return Py_SIZE(v) != 0; } static PyObject * long_rshift(PyLongObject *a, PyLongObject *b) { - PyLongObject *z = NULL; - Py_ssize_t shiftby, newsize, wordshift, loshift, hishift, i, j; - digit lomask, himask; - - CHECK_BINOP(a, b); - - if (Py_SIZE(a) < 0) { - /* Right shifting negative numbers is harder */ - PyLongObject *a1, *a2; - a1 = (PyLongObject *) long_invert(a); - if (a1 == NULL) - goto rshift_error; - a2 = (PyLongObject *) long_rshift(a1, b); - Py_DECREF(a1); - if (a2 == NULL) - goto rshift_error; - z = (PyLongObject *) long_invert(a2); - Py_DECREF(a2); - } - else { - shiftby = PyLong_AsSsize_t((PyObject *)b); - if (shiftby == -1L && PyErr_Occurred()) - goto rshift_error; - if (shiftby < 0) { - PyErr_SetString(PyExc_ValueError, - "negative shift count"); - goto rshift_error; - } - wordshift = shiftby / PyLong_SHIFT; - newsize = ABS(Py_SIZE(a)) - wordshift; - if (newsize <= 0) - return PyLong_FromLong(0); - loshift = shiftby % PyLong_SHIFT; - hishift = PyLong_SHIFT - loshift; - lomask = ((digit)1 << hishift) - 1; - himask = PyLong_MASK ^ lomask; - z = _PyLong_New(newsize); - if (z == NULL) - goto rshift_error; - if (Py_SIZE(a) < 0) - Py_SIZE(z) = -(Py_SIZE(z)); - for (i = 0, j = wordshift; i < newsize; i++, j++) { - z->ob_digit[i] = (a->ob_digit[j] >> loshift) & lomask; - if (i+1 < newsize) - z->ob_digit[i] |= - (a->ob_digit[j+1] << hishift) & himask; - } - z = long_normalize(z); - } + PyLongObject *z = NULL; + Py_ssize_t shiftby, newsize, wordshift, loshift, hishift, i, j; + digit lomask, himask; + + CHECK_BINOP(a, b); + + if (Py_SIZE(a) < 0) { + /* Right shifting negative numbers is harder */ + PyLongObject *a1, *a2; + a1 = (PyLongObject *) long_invert(a); + if (a1 == NULL) + goto rshift_error; + a2 = (PyLongObject *) long_rshift(a1, b); + Py_DECREF(a1); + if (a2 == NULL) + goto rshift_error; + z = (PyLongObject *) long_invert(a2); + Py_DECREF(a2); + } + else { + shiftby = PyLong_AsSsize_t((PyObject *)b); + if (shiftby == -1L && PyErr_Occurred()) + goto rshift_error; + if (shiftby < 0) { + PyErr_SetString(PyExc_ValueError, + "negative shift count"); + goto rshift_error; + } + wordshift = shiftby / PyLong_SHIFT; + newsize = ABS(Py_SIZE(a)) - wordshift; + if (newsize <= 0) + return PyLong_FromLong(0); + loshift = shiftby % PyLong_SHIFT; + hishift = PyLong_SHIFT - loshift; + lomask = ((digit)1 << hishift) - 1; + himask = PyLong_MASK ^ lomask; + z = _PyLong_New(newsize); + if (z == NULL) + goto rshift_error; + if (Py_SIZE(a) < 0) + Py_SIZE(z) = -(Py_SIZE(z)); + for (i = 0, j = wordshift; i < newsize; i++, j++) { + z->ob_digit[i] = (a->ob_digit[j] >> loshift) & lomask; + if (i+1 < newsize) + z->ob_digit[i] |= + (a->ob_digit[j+1] << hishift) & himask; + } + z = long_normalize(z); + } rshift_error: - return (PyObject *) maybe_small_long(z); + return (PyObject *) maybe_small_long(z); } static PyObject * long_lshift(PyObject *v, PyObject *w) { - /* This version due to Tim Peters */ - PyLongObject *a = (PyLongObject*)v; - PyLongObject *b = (PyLongObject*)w; - PyLongObject *z = NULL; - Py_ssize_t shiftby, oldsize, newsize, wordshift, remshift, i, j; - twodigits accum; - - CHECK_BINOP(a, b); - - shiftby = PyLong_AsSsize_t((PyObject *)b); - if (shiftby == -1L && PyErr_Occurred()) - goto lshift_error; - if (shiftby < 0) { - PyErr_SetString(PyExc_ValueError, "negative shift count"); - goto lshift_error; - } - /* wordshift, remshift = divmod(shiftby, PyLong_SHIFT) */ - wordshift = shiftby / PyLong_SHIFT; - remshift = shiftby - wordshift * PyLong_SHIFT; - - oldsize = ABS(Py_SIZE(a)); - newsize = oldsize + wordshift; - if (remshift) - ++newsize; - z = _PyLong_New(newsize); - if (z == NULL) - goto lshift_error; - if (Py_SIZE(a) < 0) - NEGATE(z); - for (i = 0; i < wordshift; i++) - z->ob_digit[i] = 0; - accum = 0; - for (i = wordshift, j = 0; j < oldsize; i++, j++) { - accum |= (twodigits)a->ob_digit[j] << remshift; - z->ob_digit[i] = (digit)(accum & PyLong_MASK); - accum >>= PyLong_SHIFT; - } - if (remshift) - z->ob_digit[newsize-1] = (digit)accum; - else - assert(!accum); - z = long_normalize(z); + /* This version due to Tim Peters */ + PyLongObject *a = (PyLongObject*)v; + PyLongObject *b = (PyLongObject*)w; + PyLongObject *z = NULL; + Py_ssize_t shiftby, oldsize, newsize, wordshift, remshift, i, j; + twodigits accum; + + CHECK_BINOP(a, b); + + shiftby = PyLong_AsSsize_t((PyObject *)b); + if (shiftby == -1L && PyErr_Occurred()) + goto lshift_error; + if (shiftby < 0) { + PyErr_SetString(PyExc_ValueError, "negative shift count"); + goto lshift_error; + } + /* wordshift, remshift = divmod(shiftby, PyLong_SHIFT) */ + wordshift = shiftby / PyLong_SHIFT; + remshift = shiftby - wordshift * PyLong_SHIFT; + + oldsize = ABS(Py_SIZE(a)); + newsize = oldsize + wordshift; + if (remshift) + ++newsize; + z = _PyLong_New(newsize); + if (z == NULL) + goto lshift_error; + if (Py_SIZE(a) < 0) + NEGATE(z); + for (i = 0; i < wordshift; i++) + z->ob_digit[i] = 0; + accum = 0; + for (i = wordshift, j = 0; j < oldsize; i++, j++) { + accum |= (twodigits)a->ob_digit[j] << remshift; + z->ob_digit[i] = (digit)(accum & PyLong_MASK); + accum >>= PyLong_SHIFT; + } + if (remshift) + z->ob_digit[newsize-1] = (digit)accum; + else + assert(!accum); + z = long_normalize(z); lshift_error: - return (PyObject *) maybe_small_long(z); + return (PyObject *) maybe_small_long(z); } /* Compute two's complement of digit vector a[0:m], writing result to @@ -3885,186 +3885,186 @@ static void v_complement(digit *z, digit *a, Py_ssize_t m) { - Py_ssize_t i; - digit carry = 1; - for (i = 0; i < m; ++i) { - carry += a[i] ^ PyLong_MASK; - z[i] = carry & PyLong_MASK; - carry >>= PyLong_SHIFT; - } - assert(carry == 0); + Py_ssize_t i; + digit carry = 1; + for (i = 0; i < m; ++i) { + carry += a[i] ^ PyLong_MASK; + z[i] = carry & PyLong_MASK; + carry >>= PyLong_SHIFT; + } + assert(carry == 0); } /* Bitwise and/xor/or operations */ static PyObject * long_bitwise(PyLongObject *a, - int op, /* '&', '|', '^' */ - PyLongObject *b) + int op, /* '&', '|', '^' */ + PyLongObject *b) { - int nega, negb, negz; - Py_ssize_t size_a, size_b, size_z, i; - PyLongObject *z; - - /* Bitwise operations for negative numbers operate as though - on a two's complement representation. So convert arguments - from sign-magnitude to two's complement, and convert the - result back to sign-magnitude at the end. */ - - /* If a is negative, replace it by its two's complement. */ - size_a = ABS(Py_SIZE(a)); - nega = Py_SIZE(a) < 0; - if (nega) { - z = _PyLong_New(size_a); - if (z == NULL) - return NULL; - v_complement(z->ob_digit, a->ob_digit, size_a); - a = z; - } - else - /* Keep reference count consistent. */ - Py_INCREF(a); - - /* Same for b. */ - size_b = ABS(Py_SIZE(b)); - negb = Py_SIZE(b) < 0; - if (negb) { - z = _PyLong_New(size_b); - if (z == NULL) { - Py_DECREF(a); - return NULL; - } - v_complement(z->ob_digit, b->ob_digit, size_b); - b = z; - } - else - Py_INCREF(b); - - /* Swap a and b if necessary to ensure size_a >= size_b. */ - if (size_a < size_b) { - z = a; a = b; b = z; - size_z = size_a; size_a = size_b; size_b = size_z; - negz = nega; nega = negb; negb = negz; - } - - /* JRH: The original logic here was to allocate the result value (z) - as the longer of the two operands. However, there are some cases - where the result is guaranteed to be shorter than that: AND of two - positives, OR of two negatives: use the shorter number. AND with - mixed signs: use the positive number. OR with mixed signs: use the - negative number. - */ - switch (op) { - case '^': - negz = nega ^ negb; - size_z = size_a; - break; - case '&': - negz = nega & negb; - size_z = negb ? size_a : size_b; - break; - case '|': - negz = nega | negb; - size_z = negb ? size_b : size_a; - break; - default: - PyErr_BadArgument(); - return NULL; - } - - /* We allow an extra digit if z is negative, to make sure that - the final two's complement of z doesn't overflow. */ - z = _PyLong_New(size_z + negz); - if (z == NULL) { - Py_DECREF(a); - Py_DECREF(b); - return NULL; - } - - /* Compute digits for overlap of a and b. */ - switch(op) { - case '&': - for (i = 0; i < size_b; ++i) - z->ob_digit[i] = a->ob_digit[i] & b->ob_digit[i]; - break; - case '|': - for (i = 0; i < size_b; ++i) - z->ob_digit[i] = a->ob_digit[i] | b->ob_digit[i]; - break; - case '^': - for (i = 0; i < size_b; ++i) - z->ob_digit[i] = a->ob_digit[i] ^ b->ob_digit[i]; - break; - default: - PyErr_BadArgument(); - return NULL; - } - - /* Copy any remaining digits of a, inverting if necessary. */ - if (op == '^' && negb) - for (; i < size_z; ++i) - z->ob_digit[i] = a->ob_digit[i] ^ PyLong_MASK; - else if (i < size_z) - memcpy(&z->ob_digit[i], &a->ob_digit[i], - (size_z-i)*sizeof(digit)); - - /* Complement result if negative. */ - if (negz) { - Py_SIZE(z) = -(Py_SIZE(z)); - z->ob_digit[size_z] = PyLong_MASK; - v_complement(z->ob_digit, z->ob_digit, size_z+1); - } - - Py_DECREF(a); - Py_DECREF(b); - return (PyObject *)maybe_small_long(long_normalize(z)); + int nega, negb, negz; + Py_ssize_t size_a, size_b, size_z, i; + PyLongObject *z; + + /* Bitwise operations for negative numbers operate as though + on a two's complement representation. So convert arguments + from sign-magnitude to two's complement, and convert the + result back to sign-magnitude at the end. */ + + /* If a is negative, replace it by its two's complement. */ + size_a = ABS(Py_SIZE(a)); + nega = Py_SIZE(a) < 0; + if (nega) { + z = _PyLong_New(size_a); + if (z == NULL) + return NULL; + v_complement(z->ob_digit, a->ob_digit, size_a); + a = z; + } + else + /* Keep reference count consistent. */ + Py_INCREF(a); + + /* Same for b. */ + size_b = ABS(Py_SIZE(b)); + negb = Py_SIZE(b) < 0; + if (negb) { + z = _PyLong_New(size_b); + if (z == NULL) { + Py_DECREF(a); + return NULL; + } + v_complement(z->ob_digit, b->ob_digit, size_b); + b = z; + } + else + Py_INCREF(b); + + /* Swap a and b if necessary to ensure size_a >= size_b. */ + if (size_a < size_b) { + z = a; a = b; b = z; + size_z = size_a; size_a = size_b; size_b = size_z; + negz = nega; nega = negb; negb = negz; + } + + /* JRH: The original logic here was to allocate the result value (z) + as the longer of the two operands. However, there are some cases + where the result is guaranteed to be shorter than that: AND of two + positives, OR of two negatives: use the shorter number. AND with + mixed signs: use the positive number. OR with mixed signs: use the + negative number. + */ + switch (op) { + case '^': + negz = nega ^ negb; + size_z = size_a; + break; + case '&': + negz = nega & negb; + size_z = negb ? size_a : size_b; + break; + case '|': + negz = nega | negb; + size_z = negb ? size_b : size_a; + break; + default: + PyErr_BadArgument(); + return NULL; + } + + /* We allow an extra digit if z is negative, to make sure that + the final two's complement of z doesn't overflow. */ + z = _PyLong_New(size_z + negz); + if (z == NULL) { + Py_DECREF(a); + Py_DECREF(b); + return NULL; + } + + /* Compute digits for overlap of a and b. */ + switch(op) { + case '&': + for (i = 0; i < size_b; ++i) + z->ob_digit[i] = a->ob_digit[i] & b->ob_digit[i]; + break; + case '|': + for (i = 0; i < size_b; ++i) + z->ob_digit[i] = a->ob_digit[i] | b->ob_digit[i]; + break; + case '^': + for (i = 0; i < size_b; ++i) + z->ob_digit[i] = a->ob_digit[i] ^ b->ob_digit[i]; + break; + default: + PyErr_BadArgument(); + return NULL; + } + + /* Copy any remaining digits of a, inverting if necessary. */ + if (op == '^' && negb) + for (; i < size_z; ++i) + z->ob_digit[i] = a->ob_digit[i] ^ PyLong_MASK; + else if (i < size_z) + memcpy(&z->ob_digit[i], &a->ob_digit[i], + (size_z-i)*sizeof(digit)); + + /* Complement result if negative. */ + if (negz) { + Py_SIZE(z) = -(Py_SIZE(z)); + z->ob_digit[size_z] = PyLong_MASK; + v_complement(z->ob_digit, z->ob_digit, size_z+1); + } + + Py_DECREF(a); + Py_DECREF(b); + return (PyObject *)maybe_small_long(long_normalize(z)); } static PyObject * long_and(PyObject *a, PyObject *b) { - PyObject *c; - CHECK_BINOP(a, b); - c = long_bitwise((PyLongObject*)a, '&', (PyLongObject*)b); - return c; + PyObject *c; + CHECK_BINOP(a, b); + c = long_bitwise((PyLongObject*)a, '&', (PyLongObject*)b); + return c; } static PyObject * long_xor(PyObject *a, PyObject *b) { - PyObject *c; - CHECK_BINOP(a, b); - c = long_bitwise((PyLongObject*)a, '^', (PyLongObject*)b); - return c; + PyObject *c; + CHECK_BINOP(a, b); + c = long_bitwise((PyLongObject*)a, '^', (PyLongObject*)b); + return c; } static PyObject * long_or(PyObject *a, PyObject *b) { - PyObject *c; - CHECK_BINOP(a, b); - c = long_bitwise((PyLongObject*)a, '|', (PyLongObject*)b); - return c; + PyObject *c; + CHECK_BINOP(a, b); + c = long_bitwise((PyLongObject*)a, '|', (PyLongObject*)b); + return c; } static PyObject * long_long(PyObject *v) { - if (PyLong_CheckExact(v)) - Py_INCREF(v); - else - v = _PyLong_Copy((PyLongObject *)v); - return v; + if (PyLong_CheckExact(v)) + Py_INCREF(v); + else + v = _PyLong_Copy((PyLongObject *)v); + return v; } static PyObject * long_float(PyObject *v) { - double result; - result = PyLong_AsDouble(v); - if (result == -1.0 && PyErr_Occurred()) - return NULL; - return PyFloat_FromDouble(result); + double result; + result = PyLong_AsDouble(v); + if (result == -1.0 && PyErr_Occurred()) + return NULL; + return PyFloat_FromDouble(result); } static PyObject * @@ -4073,47 +4073,47 @@ static PyObject * long_new(PyTypeObject *type, PyObject *args, PyObject *kwds) { - PyObject *x = NULL; - int base = -909; /* unlikely! */ - static char *kwlist[] = {"x", "base", 0}; - - if (type != &PyLong_Type) - return long_subtype_new(type, args, kwds); /* Wimp out */ - if (!PyArg_ParseTupleAndKeywords(args, kwds, "|Oi:int", kwlist, - &x, &base)) - return NULL; - if (x == NULL) - return PyLong_FromLong(0L); - if (base == -909) - return PyNumber_Long(x); - else if (PyUnicode_Check(x)) - return PyLong_FromUnicode(PyUnicode_AS_UNICODE(x), - PyUnicode_GET_SIZE(x), - base); - else if (PyByteArray_Check(x) || PyBytes_Check(x)) { - /* Since PyLong_FromString doesn't have a length parameter, - * check here for possible NULs in the string. */ - char *string; - Py_ssize_t size = Py_SIZE(x); - if (PyByteArray_Check(x)) - string = PyByteArray_AS_STRING(x); - else - string = PyBytes_AS_STRING(x); - if (strlen(string) != (size_t)size) { - /* We only see this if there's a null byte in x, - x is a bytes or buffer, *and* a base is given. */ - PyErr_Format(PyExc_ValueError, - "invalid literal for int() with base %d: %R", - base, x); - return NULL; - } - return PyLong_FromString(string, NULL, base); - } - else { - PyErr_SetString(PyExc_TypeError, - "int() can't convert non-string with explicit base"); - return NULL; - } + PyObject *x = NULL; + int base = -909; /* unlikely! */ + static char *kwlist[] = {"x", "base", 0}; + + if (type != &PyLong_Type) + return long_subtype_new(type, args, kwds); /* Wimp out */ + if (!PyArg_ParseTupleAndKeywords(args, kwds, "|Oi:int", kwlist, + &x, &base)) + return NULL; + if (x == NULL) + return PyLong_FromLong(0L); + if (base == -909) + return PyNumber_Long(x); + else if (PyUnicode_Check(x)) + return PyLong_FromUnicode(PyUnicode_AS_UNICODE(x), + PyUnicode_GET_SIZE(x), + base); + else if (PyByteArray_Check(x) || PyBytes_Check(x)) { + /* Since PyLong_FromString doesn't have a length parameter, + * check here for possible NULs in the string. */ + char *string; + Py_ssize_t size = Py_SIZE(x); + if (PyByteArray_Check(x)) + string = PyByteArray_AS_STRING(x); + else + string = PyBytes_AS_STRING(x); + if (strlen(string) != (size_t)size) { + /* We only see this if there's a null byte in x, + x is a bytes or buffer, *and* a base is given. */ + PyErr_Format(PyExc_ValueError, + "invalid literal for int() with base %d: %R", + base, x); + return NULL; + } + return PyLong_FromString(string, NULL, base); + } + else { + PyErr_SetString(PyExc_TypeError, + "int() can't convert non-string with explicit base"); + return NULL; + } } /* Wimpy, slow approach to tp_new calls for subtypes of long: @@ -4124,256 +4124,256 @@ static PyObject * long_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds) { - PyLongObject *tmp, *newobj; - Py_ssize_t i, n; + PyLongObject *tmp, *newobj; + Py_ssize_t i, n; - assert(PyType_IsSubtype(type, &PyLong_Type)); - tmp = (PyLongObject *)long_new(&PyLong_Type, args, kwds); - if (tmp == NULL) - return NULL; - assert(PyLong_CheckExact(tmp)); - n = Py_SIZE(tmp); - if (n < 0) - n = -n; - newobj = (PyLongObject *)type->tp_alloc(type, n); - if (newobj == NULL) { - Py_DECREF(tmp); - return NULL; - } - assert(PyLong_Check(newobj)); - Py_SIZE(newobj) = Py_SIZE(tmp); - for (i = 0; i < n; i++) - newobj->ob_digit[i] = tmp->ob_digit[i]; - Py_DECREF(tmp); - return (PyObject *)newobj; + assert(PyType_IsSubtype(type, &PyLong_Type)); + tmp = (PyLongObject *)long_new(&PyLong_Type, args, kwds); + if (tmp == NULL) + return NULL; + assert(PyLong_CheckExact(tmp)); + n = Py_SIZE(tmp); + if (n < 0) + n = -n; + newobj = (PyLongObject *)type->tp_alloc(type, n); + if (newobj == NULL) { + Py_DECREF(tmp); + return NULL; + } + assert(PyLong_Check(newobj)); + Py_SIZE(newobj) = Py_SIZE(tmp); + for (i = 0; i < n; i++) + newobj->ob_digit[i] = tmp->ob_digit[i]; + Py_DECREF(tmp); + return (PyObject *)newobj; } static PyObject * long_getnewargs(PyLongObject *v) { - return Py_BuildValue("(N)", _PyLong_Copy(v)); + return Py_BuildValue("(N)", _PyLong_Copy(v)); } static PyObject * long_get0(PyLongObject *v, void *context) { - return PyLong_FromLong(0L); + return PyLong_FromLong(0L); } static PyObject * long_get1(PyLongObject *v, void *context) { - return PyLong_FromLong(1L); + return PyLong_FromLong(1L); } static PyObject * long__format__(PyObject *self, PyObject *args) { - PyObject *format_spec; + PyObject *format_spec; - if (!PyArg_ParseTuple(args, "U:__format__", &format_spec)) - return NULL; - return _PyLong_FormatAdvanced(self, - PyUnicode_AS_UNICODE(format_spec), - PyUnicode_GET_SIZE(format_spec)); + if (!PyArg_ParseTuple(args, "U:__format__", &format_spec)) + return NULL; + return _PyLong_FormatAdvanced(self, + PyUnicode_AS_UNICODE(format_spec), + PyUnicode_GET_SIZE(format_spec)); } static PyObject * long_round(PyObject *self, PyObject *args) { - PyObject *o_ndigits=NULL, *temp; - PyLongObject *pow=NULL, *q=NULL, *r=NULL, *ndigits=NULL, *one; - int errcode; - digit q_mod_4; - - /* Notes on the algorithm: to round to the nearest 10**n (n positive), - the straightforward method is: - - (1) divide by 10**n - (2) round to nearest integer (round to even in case of tie) - (3) multiply result by 10**n. - - But the rounding step involves examining the fractional part of the - quotient to see whether it's greater than 0.5 or not. Since we - want to do the whole calculation in integer arithmetic, it's - simpler to do: - - (1) divide by (10**n)/2 - (2) round to nearest multiple of 2 (multiple of 4 in case of tie) - (3) multiply result by (10**n)/2. - - Then all we need to know about the fractional part of the quotient - arising in step (2) is whether it's zero or not. - - Doing both a multiplication and division is wasteful, and is easily - avoided if we just figure out how much to adjust the original input - by to do the rounding. - - Here's the whole algorithm expressed in Python. - - def round(self, ndigits = None): - """round(int, int) -> int""" - if ndigits is None or ndigits >= 0: - return self - pow = 10**-ndigits >> 1 - q, r = divmod(self, pow) - self -= r - if (q & 1 != 0): - if (q & 2 == r == 0): - self -= pow - else: - self += pow - return self - - */ - if (!PyArg_ParseTuple(args, "|O", &o_ndigits)) - return NULL; - if (o_ndigits == NULL) - return long_long(self); - - ndigits = (PyLongObject *)PyNumber_Index(o_ndigits); - if (ndigits == NULL) - return NULL; - - if (Py_SIZE(ndigits) >= 0) { - Py_DECREF(ndigits); - return long_long(self); - } - - Py_INCREF(self); /* to keep refcounting simple */ - /* we now own references to self, ndigits */ - - /* pow = 10 ** -ndigits >> 1 */ - pow = (PyLongObject *)PyLong_FromLong(10L); - if (pow == NULL) - goto error; - temp = long_neg(ndigits); - Py_DECREF(ndigits); - ndigits = (PyLongObject *)temp; - if (ndigits == NULL) - goto error; - temp = long_pow((PyObject *)pow, (PyObject *)ndigits, Py_None); - Py_DECREF(pow); - pow = (PyLongObject *)temp; - if (pow == NULL) - goto error; - assert(PyLong_Check(pow)); /* check long_pow returned a long */ - one = (PyLongObject *)PyLong_FromLong(1L); - if (one == NULL) - goto error; - temp = long_rshift(pow, one); - Py_DECREF(one); - Py_DECREF(pow); - pow = (PyLongObject *)temp; - if (pow == NULL) - goto error; - - /* q, r = divmod(self, pow) */ - errcode = l_divmod((PyLongObject *)self, pow, &q, &r); - if (errcode == -1) - goto error; - - /* self -= r */ - temp = long_sub((PyLongObject *)self, r); - Py_DECREF(self); - self = temp; - if (self == NULL) - goto error; - - /* get value of quotient modulo 4 */ - if (Py_SIZE(q) == 0) - q_mod_4 = 0; - else if (Py_SIZE(q) > 0) - q_mod_4 = q->ob_digit[0] & 3; - else - q_mod_4 = (PyLong_BASE-q->ob_digit[0]) & 3; - - if ((q_mod_4 & 1) == 1) { - /* q is odd; round self up or down by adding or subtracting pow */ - if (q_mod_4 == 1 && Py_SIZE(r) == 0) - temp = (PyObject *)long_sub((PyLongObject *)self, pow); - else - temp = (PyObject *)long_add((PyLongObject *)self, pow); - Py_DECREF(self); - self = temp; - if (self == NULL) - goto error; - } - Py_DECREF(q); - Py_DECREF(r); - Py_DECREF(pow); - Py_DECREF(ndigits); - return self; + PyObject *o_ndigits=NULL, *temp; + PyLongObject *pow=NULL, *q=NULL, *r=NULL, *ndigits=NULL, *one; + int errcode; + digit q_mod_4; + + /* Notes on the algorithm: to round to the nearest 10**n (n positive), + the straightforward method is: + + (1) divide by 10**n + (2) round to nearest integer (round to even in case of tie) + (3) multiply result by 10**n. + + But the rounding step involves examining the fractional part of the + quotient to see whether it's greater than 0.5 or not. Since we + want to do the whole calculation in integer arithmetic, it's + simpler to do: + + (1) divide by (10**n)/2 + (2) round to nearest multiple of 2 (multiple of 4 in case of tie) + (3) multiply result by (10**n)/2. + + Then all we need to know about the fractional part of the quotient + arising in step (2) is whether it's zero or not. + + Doing both a multiplication and division is wasteful, and is easily + avoided if we just figure out how much to adjust the original input + by to do the rounding. + + Here's the whole algorithm expressed in Python. + + def round(self, ndigits = None): + """round(int, int) -> int""" + if ndigits is None or ndigits >= 0: + return self + pow = 10**-ndigits >> 1 + q, r = divmod(self, pow) + self -= r + if (q & 1 != 0): + if (q & 2 == r == 0): + self -= pow + else: + self += pow + return self + + */ + if (!PyArg_ParseTuple(args, "|O", &o_ndigits)) + return NULL; + if (o_ndigits == NULL) + return long_long(self); + + ndigits = (PyLongObject *)PyNumber_Index(o_ndigits); + if (ndigits == NULL) + return NULL; + + if (Py_SIZE(ndigits) >= 0) { + Py_DECREF(ndigits); + return long_long(self); + } + + Py_INCREF(self); /* to keep refcounting simple */ + /* we now own references to self, ndigits */ + + /* pow = 10 ** -ndigits >> 1 */ + pow = (PyLongObject *)PyLong_FromLong(10L); + if (pow == NULL) + goto error; + temp = long_neg(ndigits); + Py_DECREF(ndigits); + ndigits = (PyLongObject *)temp; + if (ndigits == NULL) + goto error; + temp = long_pow((PyObject *)pow, (PyObject *)ndigits, Py_None); + Py_DECREF(pow); + pow = (PyLongObject *)temp; + if (pow == NULL) + goto error; + assert(PyLong_Check(pow)); /* check long_pow returned a long */ + one = (PyLongObject *)PyLong_FromLong(1L); + if (one == NULL) + goto error; + temp = long_rshift(pow, one); + Py_DECREF(one); + Py_DECREF(pow); + pow = (PyLongObject *)temp; + if (pow == NULL) + goto error; + + /* q, r = divmod(self, pow) */ + errcode = l_divmod((PyLongObject *)self, pow, &q, &r); + if (errcode == -1) + goto error; + + /* self -= r */ + temp = long_sub((PyLongObject *)self, r); + Py_DECREF(self); + self = temp; + if (self == NULL) + goto error; + + /* get value of quotient modulo 4 */ + if (Py_SIZE(q) == 0) + q_mod_4 = 0; + else if (Py_SIZE(q) > 0) + q_mod_4 = q->ob_digit[0] & 3; + else + q_mod_4 = (PyLong_BASE-q->ob_digit[0]) & 3; + + if ((q_mod_4 & 1) == 1) { + /* q is odd; round self up or down by adding or subtracting pow */ + if (q_mod_4 == 1 && Py_SIZE(r) == 0) + temp = (PyObject *)long_sub((PyLongObject *)self, pow); + else + temp = (PyObject *)long_add((PyLongObject *)self, pow); + Py_DECREF(self); + self = temp; + if (self == NULL) + goto error; + } + Py_DECREF(q); + Py_DECREF(r); + Py_DECREF(pow); + Py_DECREF(ndigits); + return self; error: - Py_XDECREF(q); - Py_XDECREF(r); - Py_XDECREF(pow); - Py_XDECREF(self); - Py_XDECREF(ndigits); - return NULL; + Py_XDECREF(q); + Py_XDECREF(r); + Py_XDECREF(pow); + Py_XDECREF(self); + Py_XDECREF(ndigits); + return NULL; } static PyObject * long_sizeof(PyLongObject *v) { - Py_ssize_t res; + Py_ssize_t res; - res = offsetof(PyLongObject, ob_digit) + ABS(Py_SIZE(v))*sizeof(digit); - return PyLong_FromSsize_t(res); + res = offsetof(PyLongObject, ob_digit) + ABS(Py_SIZE(v))*sizeof(digit); + return PyLong_FromSsize_t(res); } static PyObject * long_bit_length(PyLongObject *v) { - PyLongObject *result, *x, *y; - Py_ssize_t ndigits, msd_bits = 0; - digit msd; - - assert(v != NULL); - assert(PyLong_Check(v)); - - ndigits = ABS(Py_SIZE(v)); - if (ndigits == 0) - return PyLong_FromLong(0); - - msd = v->ob_digit[ndigits-1]; - while (msd >= 32) { - msd_bits += 6; - msd >>= 6; - } - msd_bits += (long)(BitLengthTable[msd]); - - if (ndigits <= PY_SSIZE_T_MAX/PyLong_SHIFT) - return PyLong_FromSsize_t((ndigits-1)*PyLong_SHIFT + msd_bits); - - /* expression above may overflow; use Python integers instead */ - result = (PyLongObject *)PyLong_FromSsize_t(ndigits - 1); - if (result == NULL) - return NULL; - x = (PyLongObject *)PyLong_FromLong(PyLong_SHIFT); - if (x == NULL) - goto error; - y = (PyLongObject *)long_mul(result, x); - Py_DECREF(x); - if (y == NULL) - goto error; - Py_DECREF(result); - result = y; - - x = (PyLongObject *)PyLong_FromLong((long)msd_bits); - if (x == NULL) - goto error; - y = (PyLongObject *)long_add(result, x); - Py_DECREF(x); - if (y == NULL) - goto error; - Py_DECREF(result); - result = y; + PyLongObject *result, *x, *y; + Py_ssize_t ndigits, msd_bits = 0; + digit msd; + + assert(v != NULL); + assert(PyLong_Check(v)); + + ndigits = ABS(Py_SIZE(v)); + if (ndigits == 0) + return PyLong_FromLong(0); + + msd = v->ob_digit[ndigits-1]; + while (msd >= 32) { + msd_bits += 6; + msd >>= 6; + } + msd_bits += (long)(BitLengthTable[msd]); + + if (ndigits <= PY_SSIZE_T_MAX/PyLong_SHIFT) + return PyLong_FromSsize_t((ndigits-1)*PyLong_SHIFT + msd_bits); + + /* expression above may overflow; use Python integers instead */ + result = (PyLongObject *)PyLong_FromSsize_t(ndigits - 1); + if (result == NULL) + return NULL; + x = (PyLongObject *)PyLong_FromLong(PyLong_SHIFT); + if (x == NULL) + goto error; + y = (PyLongObject *)long_mul(result, x); + Py_DECREF(x); + if (y == NULL) + goto error; + Py_DECREF(result); + result = y; + + x = (PyLongObject *)PyLong_FromLong((long)msd_bits); + if (x == NULL) + goto error; + y = (PyLongObject *)long_add(result, x); + Py_DECREF(x); + if (y == NULL) + goto error; + Py_DECREF(result); + result = y; - return (PyObject *)result; + return (PyObject *)result; error: - Py_DECREF(result); - return NULL; + Py_DECREF(result); + return NULL; } PyDoc_STRVAR(long_bit_length_doc, @@ -4389,7 +4389,7 @@ static PyObject * long_is_finite(PyObject *v) { - Py_RETURN_TRUE; + Py_RETURN_TRUE; } #endif @@ -4397,64 +4397,64 @@ static PyObject * long_to_bytes(PyLongObject *v, PyObject *args, PyObject *kwds) { - PyObject *byteorder_str; - PyObject *is_signed_obj = NULL; - Py_ssize_t length; - int little_endian; - int is_signed; - PyObject *bytes; - static char *kwlist[] = {"length", "byteorder", "signed", NULL}; - - if (!PyArg_ParseTupleAndKeywords(args, kwds, "nU|O:to_bytes", kwlist, - &length, &byteorder_str, - &is_signed_obj)) - return NULL; - - if (args != NULL && Py_SIZE(args) > 2) { - PyErr_SetString(PyExc_TypeError, - "'signed' is a keyword-only argument"); - return NULL; - } - - if (!PyUnicode_CompareWithASCIIString(byteorder_str, "little")) - little_endian = 1; - else if (!PyUnicode_CompareWithASCIIString(byteorder_str, "big")) - little_endian = 0; - else { - PyErr_SetString(PyExc_ValueError, - "byteorder must be either 'little' or 'big'"); - return NULL; - } - - if (is_signed_obj != NULL) { - int cmp = PyObject_IsTrue(is_signed_obj); - if (cmp < 0) - return NULL; - is_signed = cmp ? 1 : 0; - } - else { - /* If the signed argument was omitted, use False as the - default. */ - is_signed = 0; - } - - if (length < 0) { - PyErr_SetString(PyExc_ValueError, - "length argument must be non-negative"); - return NULL; - } - - bytes = PyBytes_FromStringAndSize(NULL, length); - if (bytes == NULL) - return NULL; - - if (_PyLong_AsByteArray(v, (unsigned char *)PyBytes_AS_STRING(bytes), - length, little_endian, is_signed) < 0) { - Py_DECREF(bytes); - return NULL; - } + PyObject *byteorder_str; + PyObject *is_signed_obj = NULL; + Py_ssize_t length; + int little_endian; + int is_signed; + PyObject *bytes; + static char *kwlist[] = {"length", "byteorder", "signed", NULL}; + + if (!PyArg_ParseTupleAndKeywords(args, kwds, "nU|O:to_bytes", kwlist, + &length, &byteorder_str, + &is_signed_obj)) + return NULL; + + if (args != NULL && Py_SIZE(args) > 2) { + PyErr_SetString(PyExc_TypeError, + "'signed' is a keyword-only argument"); + return NULL; + } + + if (!PyUnicode_CompareWithASCIIString(byteorder_str, "little")) + little_endian = 1; + else if (!PyUnicode_CompareWithASCIIString(byteorder_str, "big")) + little_endian = 0; + else { + PyErr_SetString(PyExc_ValueError, + "byteorder must be either 'little' or 'big'"); + return NULL; + } + + if (is_signed_obj != NULL) { + int cmp = PyObject_IsTrue(is_signed_obj); + if (cmp < 0) + return NULL; + is_signed = cmp ? 1 : 0; + } + else { + /* If the signed argument was omitted, use False as the + default. */ + is_signed = 0; + } + + if (length < 0) { + PyErr_SetString(PyExc_ValueError, + "length argument must be non-negative"); + return NULL; + } + + bytes = PyBytes_FromStringAndSize(NULL, length); + if (bytes == NULL) + return NULL; + + if (_PyLong_AsByteArray(v, (unsigned char *)PyBytes_AS_STRING(bytes), + length, little_endian, is_signed) < 0) { + Py_DECREF(bytes); + return NULL; + } - return bytes; + return bytes; } PyDoc_STRVAR(long_to_bytes_doc, @@ -4462,7 +4462,7 @@ \n\ Return an array of bytes representing an integer.\n\ \n\ -The integer is represented using length bytes. An OverflowError is\n\ +The integer is represented using length bytes. An OverflowError is\n\ raised if the integer is not representable with the given number of\n\ bytes.\n\ \n\ @@ -4473,87 +4473,87 @@ byte order of the host system, use `sys.byteorder' as the byte order value.\n\ \n\ The signed keyword-only argument determines whether two's complement is\n\ -used to represent the integer. If signed is False and a negative integer\n\ +used to represent the integer. If signed is False and a negative integer\n\ is given, an OverflowError is raised."); static PyObject * long_from_bytes(PyTypeObject *type, PyObject *args, PyObject *kwds) { - PyObject *byteorder_str; - PyObject *is_signed_obj = NULL; - int little_endian; - int is_signed; - PyObject *obj; - PyObject *bytes; - PyObject *long_obj; - static char *kwlist[] = {"bytes", "byteorder", "signed", NULL}; - - if (!PyArg_ParseTupleAndKeywords(args, kwds, "OU|O:from_bytes", kwlist, - &obj, &byteorder_str, - &is_signed_obj)) - return NULL; - - if (args != NULL && Py_SIZE(args) > 2) { - PyErr_SetString(PyExc_TypeError, - "'signed' is a keyword-only argument"); - return NULL; - } - - if (!PyUnicode_CompareWithASCIIString(byteorder_str, "little")) - little_endian = 1; - else if (!PyUnicode_CompareWithASCIIString(byteorder_str, "big")) - little_endian = 0; - else { - PyErr_SetString(PyExc_ValueError, - "byteorder must be either 'little' or 'big'"); - return NULL; - } - - if (is_signed_obj != NULL) { - int cmp = PyObject_IsTrue(is_signed_obj); - if (cmp < 0) - return NULL; - is_signed = cmp ? 1 : 0; - } - else { - /* If the signed argument was omitted, use False as the - default. */ - is_signed = 0; - } - - bytes = PyObject_Bytes(obj); - if (bytes == NULL) - return NULL; - - long_obj = _PyLong_FromByteArray( - (unsigned char *)PyBytes_AS_STRING(bytes), Py_SIZE(bytes), - little_endian, is_signed); - Py_DECREF(bytes); - - /* If from_bytes() was used on subclass, allocate new subclass - * instance, initialize it with decoded long value and return it. - */ - if (type != &PyLong_Type && PyType_IsSubtype(type, &PyLong_Type)) { - PyLongObject *newobj; - int i; - Py_ssize_t n = ABS(Py_SIZE(long_obj)); - - newobj = (PyLongObject *)type->tp_alloc(type, n); - if (newobj == NULL) { - Py_DECREF(long_obj); - return NULL; - } - assert(PyLong_Check(newobj)); - Py_SIZE(newobj) = Py_SIZE(long_obj); - for (i = 0; i < n; i++) { - newobj->ob_digit[i] = - ((PyLongObject *)long_obj)->ob_digit[i]; - } - Py_DECREF(long_obj); - return (PyObject *)newobj; - } + PyObject *byteorder_str; + PyObject *is_signed_obj = NULL; + int little_endian; + int is_signed; + PyObject *obj; + PyObject *bytes; + PyObject *long_obj; + static char *kwlist[] = {"bytes", "byteorder", "signed", NULL}; + + if (!PyArg_ParseTupleAndKeywords(args, kwds, "OU|O:from_bytes", kwlist, + &obj, &byteorder_str, + &is_signed_obj)) + return NULL; + + if (args != NULL && Py_SIZE(args) > 2) { + PyErr_SetString(PyExc_TypeError, + "'signed' is a keyword-only argument"); + return NULL; + } + + if (!PyUnicode_CompareWithASCIIString(byteorder_str, "little")) + little_endian = 1; + else if (!PyUnicode_CompareWithASCIIString(byteorder_str, "big")) + little_endian = 0; + else { + PyErr_SetString(PyExc_ValueError, + "byteorder must be either 'little' or 'big'"); + return NULL; + } + + if (is_signed_obj != NULL) { + int cmp = PyObject_IsTrue(is_signed_obj); + if (cmp < 0) + return NULL; + is_signed = cmp ? 1 : 0; + } + else { + /* If the signed argument was omitted, use False as the + default. */ + is_signed = 0; + } + + bytes = PyObject_Bytes(obj); + if (bytes == NULL) + return NULL; + + long_obj = _PyLong_FromByteArray( + (unsigned char *)PyBytes_AS_STRING(bytes), Py_SIZE(bytes), + little_endian, is_signed); + Py_DECREF(bytes); + + /* If from_bytes() was used on subclass, allocate new subclass + * instance, initialize it with decoded long value and return it. + */ + if (type != &PyLong_Type && PyType_IsSubtype(type, &PyLong_Type)) { + PyLongObject *newobj; + int i; + Py_ssize_t n = ABS(Py_SIZE(long_obj)); + + newobj = (PyLongObject *)type->tp_alloc(type, n); + if (newobj == NULL) { + Py_DECREF(long_obj); + return NULL; + } + assert(PyLong_Check(newobj)); + Py_SIZE(newobj) = Py_SIZE(long_obj); + for (i = 0; i < n; i++) { + newobj->ob_digit[i] = + ((PyLongObject *)long_obj)->ob_digit[i]; + } + Py_DECREF(long_obj); + return (PyObject *)newobj; + } - return long_obj; + return long_obj; } PyDoc_STRVAR(long_from_bytes_doc, @@ -4575,32 +4575,32 @@ used to represent the integer."); static PyMethodDef long_methods[] = { - {"conjugate", (PyCFunction)long_long, METH_NOARGS, - "Returns self, the complex conjugate of any int."}, - {"bit_length", (PyCFunction)long_bit_length, METH_NOARGS, - long_bit_length_doc}, + {"conjugate", (PyCFunction)long_long, METH_NOARGS, + "Returns self, the complex conjugate of any int."}, + {"bit_length", (PyCFunction)long_bit_length, METH_NOARGS, + long_bit_length_doc}, #if 0 - {"is_finite", (PyCFunction)long_is_finite, METH_NOARGS, - "Returns always True."}, + {"is_finite", (PyCFunction)long_is_finite, METH_NOARGS, + "Returns always True."}, #endif - {"to_bytes", (PyCFunction)long_to_bytes, - METH_VARARGS|METH_KEYWORDS, long_to_bytes_doc}, - {"from_bytes", (PyCFunction)long_from_bytes, - METH_VARARGS|METH_KEYWORDS|METH_CLASS, long_from_bytes_doc}, - {"__trunc__", (PyCFunction)long_long, METH_NOARGS, - "Truncating an Integral returns itself."}, - {"__floor__", (PyCFunction)long_long, METH_NOARGS, - "Flooring an Integral returns itself."}, - {"__ceil__", (PyCFunction)long_long, METH_NOARGS, - "Ceiling of an Integral returns itself."}, - {"__round__", (PyCFunction)long_round, METH_VARARGS, - "Rounding an Integral returns itself.\n" - "Rounding with an ndigits argument also returns an integer."}, - {"__getnewargs__", (PyCFunction)long_getnewargs, METH_NOARGS}, - {"__format__", (PyCFunction)long__format__, METH_VARARGS}, - {"__sizeof__", (PyCFunction)long_sizeof, METH_NOARGS, - "Returns size in memory, in bytes"}, - {NULL, NULL} /* sentinel */ + {"to_bytes", (PyCFunction)long_to_bytes, + METH_VARARGS|METH_KEYWORDS, long_to_bytes_doc}, + {"from_bytes", (PyCFunction)long_from_bytes, + METH_VARARGS|METH_KEYWORDS|METH_CLASS, long_from_bytes_doc}, + {"__trunc__", (PyCFunction)long_long, METH_NOARGS, + "Truncating an Integral returns itself."}, + {"__floor__", (PyCFunction)long_long, METH_NOARGS, + "Flooring an Integral returns itself."}, + {"__ceil__", (PyCFunction)long_long, METH_NOARGS, + "Ceiling of an Integral returns itself."}, + {"__round__", (PyCFunction)long_round, METH_VARARGS, + "Rounding an Integral returns itself.\n" + "Rounding with an ndigits argument also returns an integer."}, + {"__getnewargs__", (PyCFunction)long_getnewargs, METH_NOARGS}, + {"__format__", (PyCFunction)long__format__, METH_VARARGS}, + {"__sizeof__", (PyCFunction)long_sizeof, METH_NOARGS, + "Returns size in memory, in bytes"}, + {NULL, NULL} /* sentinel */ }; static PyGetSetDef long_getset[] = { @@ -4633,83 +4633,83 @@ converting a non-string."); static PyNumberMethods long_as_number = { - (binaryfunc) long_add, /*nb_add*/ - (binaryfunc) long_sub, /*nb_subtract*/ - (binaryfunc) long_mul, /*nb_multiply*/ - long_mod, /*nb_remainder*/ - long_divmod, /*nb_divmod*/ - long_pow, /*nb_power*/ - (unaryfunc) long_neg, /*nb_negative*/ - (unaryfunc) long_long, /*tp_positive*/ - (unaryfunc) long_abs, /*tp_absolute*/ - (inquiry) long_bool, /*tp_bool*/ - (unaryfunc) long_invert, /*nb_invert*/ - long_lshift, /*nb_lshift*/ - (binaryfunc) long_rshift, /*nb_rshift*/ - long_and, /*nb_and*/ - long_xor, /*nb_xor*/ - long_or, /*nb_or*/ - long_long, /*nb_int*/ - 0, /*nb_reserved*/ - long_float, /*nb_float*/ - 0, /* nb_inplace_add */ - 0, /* nb_inplace_subtract */ - 0, /* nb_inplace_multiply */ - 0, /* nb_inplace_remainder */ - 0, /* nb_inplace_power */ - 0, /* nb_inplace_lshift */ - 0, /* nb_inplace_rshift */ - 0, /* nb_inplace_and */ - 0, /* nb_inplace_xor */ - 0, /* nb_inplace_or */ - long_div, /* nb_floor_divide */ - long_true_divide, /* nb_true_divide */ - 0, /* nb_inplace_floor_divide */ - 0, /* nb_inplace_true_divide */ - long_long, /* nb_index */ + (binaryfunc) long_add, /*nb_add*/ + (binaryfunc) long_sub, /*nb_subtract*/ + (binaryfunc) long_mul, /*nb_multiply*/ + long_mod, /*nb_remainder*/ + long_divmod, /*nb_divmod*/ + long_pow, /*nb_power*/ + (unaryfunc) long_neg, /*nb_negative*/ + (unaryfunc) long_long, /*tp_positive*/ + (unaryfunc) long_abs, /*tp_absolute*/ + (inquiry) long_bool, /*tp_bool*/ + (unaryfunc) long_invert, /*nb_invert*/ + long_lshift, /*nb_lshift*/ + (binaryfunc) long_rshift, /*nb_rshift*/ + long_and, /*nb_and*/ + long_xor, /*nb_xor*/ + long_or, /*nb_or*/ + long_long, /*nb_int*/ + 0, /*nb_reserved*/ + long_float, /*nb_float*/ + 0, /* nb_inplace_add */ + 0, /* nb_inplace_subtract */ + 0, /* nb_inplace_multiply */ + 0, /* nb_inplace_remainder */ + 0, /* nb_inplace_power */ + 0, /* nb_inplace_lshift */ + 0, /* nb_inplace_rshift */ + 0, /* nb_inplace_and */ + 0, /* nb_inplace_xor */ + 0, /* nb_inplace_or */ + long_div, /* nb_floor_divide */ + long_true_divide, /* nb_true_divide */ + 0, /* nb_inplace_floor_divide */ + 0, /* nb_inplace_true_divide */ + long_long, /* nb_index */ }; PyTypeObject PyLong_Type = { - PyVarObject_HEAD_INIT(&PyType_Type, 0) - "int", /* tp_name */ - offsetof(PyLongObject, ob_digit), /* tp_basicsize */ - sizeof(digit), /* tp_itemsize */ - long_dealloc, /* tp_dealloc */ - 0, /* tp_print */ - 0, /* tp_getattr */ - 0, /* tp_setattr */ - 0, /* tp_reserved */ - long_to_decimal_string, /* tp_repr */ - &long_as_number, /* tp_as_number */ - 0, /* tp_as_sequence */ - 0, /* tp_as_mapping */ - (hashfunc)long_hash, /* tp_hash */ - 0, /* tp_call */ - long_to_decimal_string, /* tp_str */ - PyObject_GenericGetAttr, /* tp_getattro */ - 0, /* tp_setattro */ - 0, /* tp_as_buffer */ - Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | - Py_TPFLAGS_LONG_SUBCLASS, /* tp_flags */ - long_doc, /* tp_doc */ - 0, /* tp_traverse */ - 0, /* tp_clear */ - long_richcompare, /* tp_richcompare */ - 0, /* tp_weaklistoffset */ - 0, /* tp_iter */ - 0, /* tp_iternext */ - long_methods, /* tp_methods */ - 0, /* tp_members */ - long_getset, /* tp_getset */ - 0, /* tp_base */ - 0, /* tp_dict */ - 0, /* tp_descr_get */ - 0, /* tp_descr_set */ - 0, /* tp_dictoffset */ - 0, /* tp_init */ - 0, /* tp_alloc */ - long_new, /* tp_new */ - PyObject_Del, /* tp_free */ + PyVarObject_HEAD_INIT(&PyType_Type, 0) + "int", /* tp_name */ + offsetof(PyLongObject, ob_digit), /* tp_basicsize */ + sizeof(digit), /* tp_itemsize */ + long_dealloc, /* tp_dealloc */ + 0, /* tp_print */ + 0, /* tp_getattr */ + 0, /* tp_setattr */ + 0, /* tp_reserved */ + long_to_decimal_string, /* tp_repr */ + &long_as_number, /* tp_as_number */ + 0, /* tp_as_sequence */ + 0, /* tp_as_mapping */ + (hashfunc)long_hash, /* tp_hash */ + 0, /* tp_call */ + long_to_decimal_string, /* tp_str */ + PyObject_GenericGetAttr, /* tp_getattro */ + 0, /* tp_setattro */ + 0, /* tp_as_buffer */ + Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | + Py_TPFLAGS_LONG_SUBCLASS, /* tp_flags */ + long_doc, /* tp_doc */ + 0, /* tp_traverse */ + 0, /* tp_clear */ + long_richcompare, /* tp_richcompare */ + 0, /* tp_weaklistoffset */ + 0, /* tp_iter */ + 0, /* tp_iternext */ + long_methods, /* tp_methods */ + 0, /* tp_members */ + long_getset, /* tp_getset */ + 0, /* tp_base */ + 0, /* tp_dict */ + 0, /* tp_descr_get */ + 0, /* tp_descr_set */ + 0, /* tp_dictoffset */ + 0, /* tp_init */ + 0, /* tp_alloc */ + long_new, /* tp_new */ + PyObject_Del, /* tp_free */ }; static PyTypeObject Int_InfoType; @@ -4721,89 +4721,89 @@ internal representation of integers. The attributes are read only."); static PyStructSequence_Field int_info_fields[] = { - {"bits_per_digit", "size of a digit in bits"}, - {"sizeof_digit", "size in bytes of the C type used to " - "represent a digit"}, - {NULL, NULL} + {"bits_per_digit", "size of a digit in bits"}, + {"sizeof_digit", "size in bytes of the C type used to " + "represent a digit"}, + {NULL, NULL} }; static PyStructSequence_Desc int_info_desc = { - "sys.int_info", /* name */ - int_info__doc__, /* doc */ - int_info_fields, /* fields */ - 2 /* number of fields */ + "sys.int_info", /* name */ + int_info__doc__, /* doc */ + int_info_fields, /* fields */ + 2 /* number of fields */ }; PyObject * PyLong_GetInfo(void) { - PyObject* int_info; - int field = 0; - int_info = PyStructSequence_New(&Int_InfoType); - if (int_info == NULL) - return NULL; - PyStructSequence_SET_ITEM(int_info, field++, - PyLong_FromLong(PyLong_SHIFT)); - PyStructSequence_SET_ITEM(int_info, field++, - PyLong_FromLong(sizeof(digit))); - if (PyErr_Occurred()) { - Py_CLEAR(int_info); - return NULL; - } - return int_info; + PyObject* int_info; + int field = 0; + int_info = PyStructSequence_New(&Int_InfoType); + if (int_info == NULL) + return NULL; + PyStructSequence_SET_ITEM(int_info, field++, + PyLong_FromLong(PyLong_SHIFT)); + PyStructSequence_SET_ITEM(int_info, field++, + PyLong_FromLong(sizeof(digit))); + if (PyErr_Occurred()) { + Py_CLEAR(int_info); + return NULL; + } + return int_info; } int _PyLong_Init(void) { #if NSMALLNEGINTS + NSMALLPOSINTS > 0 - int ival, size; - PyLongObject *v = small_ints; + int ival, size; + PyLongObject *v = small_ints; - for (ival = -NSMALLNEGINTS; ival < NSMALLPOSINTS; ival++, v++) { - size = (ival < 0) ? -1 : ((ival == 0) ? 0 : 1); - if (Py_TYPE(v) == &PyLong_Type) { - /* The element is already initialized, most likely - * the Python interpreter was initialized before. - */ - Py_ssize_t refcnt; - PyObject* op = (PyObject*)v; - - refcnt = Py_REFCNT(op) < 0 ? 0 : Py_REFCNT(op); - _Py_NewReference(op); - /* _Py_NewReference sets the ref count to 1 but - * the ref count might be larger. Set the refcnt - * to the original refcnt + 1 */ - Py_REFCNT(op) = refcnt + 1; - assert(Py_SIZE(op) == size); - assert(v->ob_digit[0] == abs(ival)); - } - else { - PyObject_INIT(v, &PyLong_Type); - } - Py_SIZE(v) = size; - v->ob_digit[0] = abs(ival); - } + for (ival = -NSMALLNEGINTS; ival < NSMALLPOSINTS; ival++, v++) { + size = (ival < 0) ? -1 : ((ival == 0) ? 0 : 1); + if (Py_TYPE(v) == &PyLong_Type) { + /* The element is already initialized, most likely + * the Python interpreter was initialized before. + */ + Py_ssize_t refcnt; + PyObject* op = (PyObject*)v; + + refcnt = Py_REFCNT(op) < 0 ? 0 : Py_REFCNT(op); + _Py_NewReference(op); + /* _Py_NewReference sets the ref count to 1 but + * the ref count might be larger. Set the refcnt + * to the original refcnt + 1 */ + Py_REFCNT(op) = refcnt + 1; + assert(Py_SIZE(op) == size); + assert(v->ob_digit[0] == abs(ival)); + } + else { + PyObject_INIT(v, &PyLong_Type); + } + Py_SIZE(v) = size; + v->ob_digit[0] = abs(ival); + } #endif - /* initialize int_info */ - if (Int_InfoType.tp_name == 0) - PyStructSequence_InitType(&Int_InfoType, &int_info_desc); + /* initialize int_info */ + if (Int_InfoType.tp_name == 0) + PyStructSequence_InitType(&Int_InfoType, &int_info_desc); - return 1; + return 1; } void PyLong_Fini(void) { - /* Integers are currently statically allocated. Py_DECREF is not - needed, but Python must forget about the reference or multiple - reinitializations will fail. */ + /* Integers are currently statically allocated. Py_DECREF is not + needed, but Python must forget about the reference or multiple + reinitializations will fail. */ #if NSMALLNEGINTS + NSMALLPOSINTS > 0 - int i; - PyLongObject *v = small_ints; - for (i = 0; i < NSMALLNEGINTS + NSMALLPOSINTS; i++, v++) { - _Py_DEC_REFTOTAL; - _Py_ForgetReference((PyObject*)v); - } + int i; + PyLongObject *v = small_ints; + for (i = 0; i < NSMALLNEGINTS + NSMALLPOSINTS; i++, v++) { + _Py_DEC_REFTOTAL; + _Py_ForgetReference((PyObject*)v); + } #endif } Modified: python/branches/py3k/Objects/methodobject.c ============================================================================== --- python/branches/py3k/Objects/methodobject.c (original) +++ python/branches/py3k/Objects/methodobject.c Sun May 9 17:52:27 2010 @@ -16,104 +16,104 @@ PyObject * PyCFunction_NewEx(PyMethodDef *ml, PyObject *self, PyObject *module) { - PyCFunctionObject *op; - op = free_list; - if (op != NULL) { - free_list = (PyCFunctionObject *)(op->m_self); - PyObject_INIT(op, &PyCFunction_Type); - numfree--; - } - else { - op = PyObject_GC_New(PyCFunctionObject, &PyCFunction_Type); - if (op == NULL) - return NULL; - } - op->m_ml = ml; - Py_XINCREF(self); - op->m_self = self; - Py_XINCREF(module); - op->m_module = module; - _PyObject_GC_TRACK(op); - return (PyObject *)op; + PyCFunctionObject *op; + op = free_list; + if (op != NULL) { + free_list = (PyCFunctionObject *)(op->m_self); + PyObject_INIT(op, &PyCFunction_Type); + numfree--; + } + else { + op = PyObject_GC_New(PyCFunctionObject, &PyCFunction_Type); + if (op == NULL) + return NULL; + } + op->m_ml = ml; + Py_XINCREF(self); + op->m_self = self; + Py_XINCREF(module); + op->m_module = module; + _PyObject_GC_TRACK(op); + return (PyObject *)op; } PyCFunction PyCFunction_GetFunction(PyObject *op) { - if (!PyCFunction_Check(op)) { - PyErr_BadInternalCall(); - return NULL; - } - return ((PyCFunctionObject *)op) -> m_ml -> ml_meth; + if (!PyCFunction_Check(op)) { + PyErr_BadInternalCall(); + return NULL; + } + return ((PyCFunctionObject *)op) -> m_ml -> ml_meth; } PyObject * PyCFunction_GetSelf(PyObject *op) { - if (!PyCFunction_Check(op)) { - PyErr_BadInternalCall(); - return NULL; - } - return ((PyCFunctionObject *)op) -> m_self; + if (!PyCFunction_Check(op)) { + PyErr_BadInternalCall(); + return NULL; + } + return ((PyCFunctionObject *)op) -> m_self; } int PyCFunction_GetFlags(PyObject *op) { - if (!PyCFunction_Check(op)) { - PyErr_BadInternalCall(); - return -1; - } - return ((PyCFunctionObject *)op) -> m_ml -> ml_flags; + if (!PyCFunction_Check(op)) { + PyErr_BadInternalCall(); + return -1; + } + return ((PyCFunctionObject *)op) -> m_ml -> ml_flags; } PyObject * PyCFunction_Call(PyObject *func, PyObject *arg, PyObject *kw) { - PyCFunctionObject* f = (PyCFunctionObject*)func; - PyCFunction meth = PyCFunction_GET_FUNCTION(func); - PyObject *self = PyCFunction_GET_SELF(func); - Py_ssize_t size; - - switch (PyCFunction_GET_FLAGS(func) & ~(METH_CLASS | METH_STATIC | METH_COEXIST)) { - case METH_VARARGS: - if (kw == NULL || PyDict_Size(kw) == 0) - return (*meth)(self, arg); - break; - case METH_VARARGS | METH_KEYWORDS: - return (*(PyCFunctionWithKeywords)meth)(self, arg, kw); - case METH_NOARGS: - if (kw == NULL || PyDict_Size(kw) == 0) { - size = PyTuple_GET_SIZE(arg); - if (size == 0) - return (*meth)(self, NULL); - PyErr_Format(PyExc_TypeError, - "%.200s() takes no arguments (%zd given)", - f->m_ml->ml_name, size); - return NULL; - } - break; - case METH_O: - if (kw == NULL || PyDict_Size(kw) == 0) { - size = PyTuple_GET_SIZE(arg); - if (size == 1) - return (*meth)(self, PyTuple_GET_ITEM(arg, 0)); - PyErr_Format(PyExc_TypeError, - "%.200s() takes exactly one argument (%zd given)", - f->m_ml->ml_name, size); - return NULL; - } - break; - default: - PyErr_SetString(PyExc_SystemError, "Bad call flags in " - "PyCFunction_Call. METH_OLDARGS is no " - "longer supported!"); - - return NULL; - } - PyErr_Format(PyExc_TypeError, "%.200s() takes no keyword arguments", - f->m_ml->ml_name); - return NULL; + PyCFunctionObject* f = (PyCFunctionObject*)func; + PyCFunction meth = PyCFunction_GET_FUNCTION(func); + PyObject *self = PyCFunction_GET_SELF(func); + Py_ssize_t size; + + switch (PyCFunction_GET_FLAGS(func) & ~(METH_CLASS | METH_STATIC | METH_COEXIST)) { + case METH_VARARGS: + if (kw == NULL || PyDict_Size(kw) == 0) + return (*meth)(self, arg); + break; + case METH_VARARGS | METH_KEYWORDS: + return (*(PyCFunctionWithKeywords)meth)(self, arg, kw); + case METH_NOARGS: + if (kw == NULL || PyDict_Size(kw) == 0) { + size = PyTuple_GET_SIZE(arg); + if (size == 0) + return (*meth)(self, NULL); + PyErr_Format(PyExc_TypeError, + "%.200s() takes no arguments (%zd given)", + f->m_ml->ml_name, size); + return NULL; + } + break; + case METH_O: + if (kw == NULL || PyDict_Size(kw) == 0) { + size = PyTuple_GET_SIZE(arg); + if (size == 1) + return (*meth)(self, PyTuple_GET_ITEM(arg, 0)); + PyErr_Format(PyExc_TypeError, + "%.200s() takes exactly one argument (%zd given)", + f->m_ml->ml_name, size); + return NULL; + } + break; + default: + PyErr_SetString(PyExc_SystemError, "Bad call flags in " + "PyCFunction_Call. METH_OLDARGS is no " + "longer supported!"); + + return NULL; + } + PyErr_Format(PyExc_TypeError, "%.200s() takes no keyword arguments", + f->m_ml->ml_name); + return NULL; } /* Methods (the standard built-in methods, that is) */ @@ -121,163 +121,163 @@ static void meth_dealloc(PyCFunctionObject *m) { - _PyObject_GC_UNTRACK(m); - Py_XDECREF(m->m_self); - Py_XDECREF(m->m_module); - if (numfree < PyCFunction_MAXFREELIST) { - m->m_self = (PyObject *)free_list; - free_list = m; - numfree++; - } - else { - PyObject_GC_Del(m); - } + _PyObject_GC_UNTRACK(m); + Py_XDECREF(m->m_self); + Py_XDECREF(m->m_module); + if (numfree < PyCFunction_MAXFREELIST) { + m->m_self = (PyObject *)free_list; + free_list = m; + numfree++; + } + else { + PyObject_GC_Del(m); + } } static PyObject * meth_get__doc__(PyCFunctionObject *m, void *closure) { - const char *doc = m->m_ml->ml_doc; + const char *doc = m->m_ml->ml_doc; - if (doc != NULL) - return PyUnicode_FromString(doc); - Py_INCREF(Py_None); - return Py_None; + if (doc != NULL) + return PyUnicode_FromString(doc); + Py_INCREF(Py_None); + return Py_None; } static PyObject * meth_get__name__(PyCFunctionObject *m, void *closure) { - return PyUnicode_FromString(m->m_ml->ml_name); + return PyUnicode_FromString(m->m_ml->ml_name); } static int meth_traverse(PyCFunctionObject *m, visitproc visit, void *arg) { - Py_VISIT(m->m_self); - Py_VISIT(m->m_module); - return 0; + Py_VISIT(m->m_self); + Py_VISIT(m->m_module); + return 0; } static PyObject * meth_get__self__(PyCFunctionObject *m, void *closure) { - PyObject *self; + PyObject *self; - self = m->m_self; - if (self == NULL) - self = Py_None; - Py_INCREF(self); - return self; + self = m->m_self; + if (self == NULL) + self = Py_None; + Py_INCREF(self); + return self; } static PyGetSetDef meth_getsets [] = { - {"__doc__", (getter)meth_get__doc__, NULL, NULL}, - {"__name__", (getter)meth_get__name__, NULL, NULL}, - {"__self__", (getter)meth_get__self__, NULL, NULL}, - {0} + {"__doc__", (getter)meth_get__doc__, NULL, NULL}, + {"__name__", (getter)meth_get__name__, NULL, NULL}, + {"__self__", (getter)meth_get__self__, NULL, NULL}, + {0} }; #define OFF(x) offsetof(PyCFunctionObject, x) static PyMemberDef meth_members[] = { - {"__module__", T_OBJECT, OFF(m_module), PY_WRITE_RESTRICTED}, - {NULL} + {"__module__", T_OBJECT, OFF(m_module), PY_WRITE_RESTRICTED}, + {NULL} }; static PyObject * meth_repr(PyCFunctionObject *m) { - if (m->m_self == NULL || PyModule_Check(m->m_self)) - return PyUnicode_FromFormat("", - m->m_ml->ml_name); - return PyUnicode_FromFormat("", - m->m_ml->ml_name, - m->m_self->ob_type->tp_name, - m->m_self); + if (m->m_self == NULL || PyModule_Check(m->m_self)) + return PyUnicode_FromFormat("", + m->m_ml->ml_name); + return PyUnicode_FromFormat("", + m->m_ml->ml_name, + m->m_self->ob_type->tp_name, + m->m_self); } static PyObject * meth_richcompare(PyObject *self, PyObject *other, int op) { - PyCFunctionObject *a, *b; - PyObject *res; - int eq; - - if ((op != Py_EQ && op != Py_NE) || - !PyCFunction_Check(self) || - !PyCFunction_Check(other)) - { - Py_INCREF(Py_NotImplemented); - return Py_NotImplemented; - } - a = (PyCFunctionObject *)self; - b = (PyCFunctionObject *)other; - eq = a->m_self == b->m_self; - if (eq) - eq = a->m_ml->ml_meth == b->m_ml->ml_meth; - if (op == Py_EQ) - res = eq ? Py_True : Py_False; - else - res = eq ? Py_False : Py_True; - Py_INCREF(res); - return res; + PyCFunctionObject *a, *b; + PyObject *res; + int eq; + + if ((op != Py_EQ && op != Py_NE) || + !PyCFunction_Check(self) || + !PyCFunction_Check(other)) + { + Py_INCREF(Py_NotImplemented); + return Py_NotImplemented; + } + a = (PyCFunctionObject *)self; + b = (PyCFunctionObject *)other; + eq = a->m_self == b->m_self; + if (eq) + eq = a->m_ml->ml_meth == b->m_ml->ml_meth; + if (op == Py_EQ) + res = eq ? Py_True : Py_False; + else + res = eq ? Py_False : Py_True; + Py_INCREF(res); + return res; } static long meth_hash(PyCFunctionObject *a) { - long x,y; - if (a->m_self == NULL) - x = 0; - else { - x = PyObject_Hash(a->m_self); - if (x == -1) - return -1; - } - y = _Py_HashPointer((void*)(a->m_ml->ml_meth)); - if (y == -1) - return -1; - x ^= y; - if (x == -1) - x = -2; - return x; + long x,y; + if (a->m_self == NULL) + x = 0; + else { + x = PyObject_Hash(a->m_self); + if (x == -1) + return -1; + } + y = _Py_HashPointer((void*)(a->m_ml->ml_meth)); + if (y == -1) + return -1; + x ^= y; + if (x == -1) + x = -2; + return x; } PyTypeObject PyCFunction_Type = { - PyVarObject_HEAD_INIT(&PyType_Type, 0) - "builtin_function_or_method", - sizeof(PyCFunctionObject), - 0, - (destructor)meth_dealloc, /* tp_dealloc */ - 0, /* tp_print */ - 0, /* tp_getattr */ - 0, /* tp_setattr */ - 0, /* tp_reserved */ - (reprfunc)meth_repr, /* tp_repr */ - 0, /* tp_as_number */ - 0, /* tp_as_sequence */ - 0, /* tp_as_mapping */ - (hashfunc)meth_hash, /* tp_hash */ - PyCFunction_Call, /* 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)meth_traverse, /* tp_traverse */ - 0, /* tp_clear */ - meth_richcompare, /* tp_richcompare */ - 0, /* tp_weaklistoffset */ - 0, /* tp_iter */ - 0, /* tp_iternext */ - 0, /* tp_methods */ - meth_members, /* tp_members */ - meth_getsets, /* tp_getset */ - 0, /* tp_base */ - 0, /* tp_dict */ + PyVarObject_HEAD_INIT(&PyType_Type, 0) + "builtin_function_or_method", + sizeof(PyCFunctionObject), + 0, + (destructor)meth_dealloc, /* tp_dealloc */ + 0, /* tp_print */ + 0, /* tp_getattr */ + 0, /* tp_setattr */ + 0, /* tp_reserved */ + (reprfunc)meth_repr, /* tp_repr */ + 0, /* tp_as_number */ + 0, /* tp_as_sequence */ + 0, /* tp_as_mapping */ + (hashfunc)meth_hash, /* tp_hash */ + PyCFunction_Call, /* 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)meth_traverse, /* tp_traverse */ + 0, /* tp_clear */ + meth_richcompare, /* tp_richcompare */ + 0, /* tp_weaklistoffset */ + 0, /* tp_iter */ + 0, /* tp_iternext */ + 0, /* tp_methods */ + meth_members, /* tp_members */ + meth_getsets, /* tp_getset */ + 0, /* tp_base */ + 0, /* tp_dict */ }; /* Clear out the free list */ @@ -285,22 +285,22 @@ int PyCFunction_ClearFreeList(void) { - int freelist_size = numfree; - - while (free_list) { - PyCFunctionObject *v = free_list; - free_list = (PyCFunctionObject *)(v->m_self); - PyObject_GC_Del(v); - numfree--; - } - assert(numfree == 0); - return freelist_size; + int freelist_size = numfree; + + while (free_list) { + PyCFunctionObject *v = free_list; + free_list = (PyCFunctionObject *)(v->m_self); + PyObject_GC_Del(v); + numfree--; + } + assert(numfree == 0); + return freelist_size; } void PyCFunction_Fini(void) { - (void)PyCFunction_ClearFreeList(); + (void)PyCFunction_ClearFreeList(); } /* PyCFunction_New() is now just a macro that calls PyCFunction_NewEx(), @@ -314,5 +314,5 @@ PyObject * PyCFunction_New(PyMethodDef *ml, PyObject *self) { - return PyCFunction_NewEx(ml, self, NULL); + return PyCFunction_NewEx(ml, self, NULL); } Modified: python/branches/py3k/Objects/moduleobject.c ============================================================================== --- python/branches/py3k/Objects/moduleobject.c (original) +++ python/branches/py3k/Objects/moduleobject.c Sun May 9 17:52:27 2010 @@ -7,53 +7,53 @@ static Py_ssize_t max_module_number; typedef struct { - PyObject_HEAD - PyObject *md_dict; - struct PyModuleDef *md_def; - void *md_state; + PyObject_HEAD + PyObject *md_dict; + struct PyModuleDef *md_def; + void *md_state; } PyModuleObject; static PyMemberDef module_members[] = { - {"__dict__", T_OBJECT, offsetof(PyModuleObject, md_dict), READONLY}, - {0} + {"__dict__", T_OBJECT, offsetof(PyModuleObject, md_dict), READONLY}, + {0} }; static PyTypeObject moduledef_type = { - PyVarObject_HEAD_INIT(&PyType_Type, 0) - "moduledef", /* tp_name */ - sizeof(struct PyModuleDef), /* tp_size */ - 0, /* tp_itemsize */ + PyVarObject_HEAD_INIT(&PyType_Type, 0) + "moduledef", /* tp_name */ + sizeof(struct PyModuleDef), /* tp_size */ + 0, /* tp_itemsize */ }; PyObject * PyModule_New(const char *name) { - PyModuleObject *m; - PyObject *nameobj; - m = PyObject_GC_New(PyModuleObject, &PyModule_Type); - if (m == NULL) - return NULL; - m->md_def = NULL; - m->md_state = NULL; - nameobj = PyUnicode_FromString(name); - m->md_dict = PyDict_New(); - if (m->md_dict == NULL || nameobj == NULL) - goto fail; - if (PyDict_SetItemString(m->md_dict, "__name__", nameobj) != 0) - goto fail; - if (PyDict_SetItemString(m->md_dict, "__doc__", Py_None) != 0) - goto fail; - if (PyDict_SetItemString(m->md_dict, "__package__", Py_None) != 0) - goto fail; - Py_DECREF(nameobj); - PyObject_GC_Track(m); - return (PyObject *)m; + PyModuleObject *m; + PyObject *nameobj; + m = PyObject_GC_New(PyModuleObject, &PyModule_Type); + if (m == NULL) + return NULL; + m->md_def = NULL; + m->md_state = NULL; + nameobj = PyUnicode_FromString(name); + m->md_dict = PyDict_New(); + if (m->md_dict == NULL || nameobj == NULL) + goto fail; + if (PyDict_SetItemString(m->md_dict, "__name__", nameobj) != 0) + goto fail; + if (PyDict_SetItemString(m->md_dict, "__doc__", Py_None) != 0) + goto fail; + if (PyDict_SetItemString(m->md_dict, "__package__", Py_None) != 0) + goto fail; + Py_DECREF(nameobj); + PyObject_GC_Track(m); + return (PyObject *)m; fail: - Py_XDECREF(nameobj); - Py_DECREF(m); - return NULL; + Py_XDECREF(nameobj); + Py_DECREF(m); + return NULL; } static char api_version_warning[] = @@ -63,231 +63,231 @@ PyObject * PyModule_Create2(struct PyModuleDef* module, int module_api_version) { - PyObject *d, *v, *n; - PyMethodDef *ml; - const char* name; - PyModuleObject *m; - if (!Py_IsInitialized()) - Py_FatalError("Interpreter not initialized (version mismatch?)"); - if (PyType_Ready(&moduledef_type) < 0) - return NULL; - if (module->m_base.m_index == 0) { - max_module_number++; - Py_REFCNT(module) = 1; - Py_TYPE(module) = &moduledef_type; - module->m_base.m_index = max_module_number; - } - name = module->m_name; - if (module_api_version != PYTHON_API_VERSION) { - char message[512]; - PyOS_snprintf(message, sizeof(message), - api_version_warning, name, - PYTHON_API_VERSION, name, - module_api_version); - if (PyErr_WarnEx(PyExc_RuntimeWarning, message, 1)) - return NULL; - } - /* Make sure name is fully qualified. - - This is a bit of a hack: when the shared library is loaded, - the module name is "package.module", but the module calls - PyModule_Create*() with just "module" for the name. The shared - library loader squirrels away the true name of the module in - _Py_PackageContext, and PyModule_Create*() will substitute this - (if the name actually matches). - */ - if (_Py_PackageContext != NULL) { - char *p = strrchr(_Py_PackageContext, '.'); - if (p != NULL && strcmp(module->m_name, p+1) == 0) { - name = _Py_PackageContext; - _Py_PackageContext = NULL; - } - } - if ((m = (PyModuleObject*)PyModule_New(name)) == NULL) - return NULL; - - if (module->m_size > 0) { - m->md_state = PyMem_MALLOC(module->m_size); - if (!m->md_state) { - PyErr_NoMemory(); - Py_DECREF(m); - return NULL; - } - memset(m->md_state, 0, module->m_size); - } - - d = PyModule_GetDict((PyObject*)m); - if (module->m_methods != NULL) { - n = PyUnicode_FromString(name); - if (n == NULL) - return NULL; - for (ml = module->m_methods; ml->ml_name != NULL; ml++) { - if ((ml->ml_flags & METH_CLASS) || - (ml->ml_flags & METH_STATIC)) { - PyErr_SetString(PyExc_ValueError, - "module functions cannot set" - " METH_CLASS or METH_STATIC"); - Py_DECREF(n); - return NULL; - } - v = PyCFunction_NewEx(ml, (PyObject*)m, n); - if (v == NULL) { - Py_DECREF(n); - return NULL; - } - if (PyDict_SetItemString(d, ml->ml_name, v) != 0) { - Py_DECREF(v); - Py_DECREF(n); - return NULL; - } - Py_DECREF(v); - } - Py_DECREF(n); - } - if (module->m_doc != NULL) { - v = PyUnicode_FromString(module->m_doc); - if (v == NULL || PyDict_SetItemString(d, "__doc__", v) != 0) { - Py_XDECREF(v); - return NULL; - } - Py_DECREF(v); - } - m->md_def = module; - return (PyObject*)m; + PyObject *d, *v, *n; + PyMethodDef *ml; + const char* name; + PyModuleObject *m; + if (!Py_IsInitialized()) + Py_FatalError("Interpreter not initialized (version mismatch?)"); + if (PyType_Ready(&moduledef_type) < 0) + return NULL; + if (module->m_base.m_index == 0) { + max_module_number++; + Py_REFCNT(module) = 1; + Py_TYPE(module) = &moduledef_type; + module->m_base.m_index = max_module_number; + } + name = module->m_name; + if (module_api_version != PYTHON_API_VERSION) { + char message[512]; + PyOS_snprintf(message, sizeof(message), + api_version_warning, name, + PYTHON_API_VERSION, name, + module_api_version); + if (PyErr_WarnEx(PyExc_RuntimeWarning, message, 1)) + return NULL; + } + /* Make sure name is fully qualified. + + This is a bit of a hack: when the shared library is loaded, + the module name is "package.module", but the module calls + PyModule_Create*() with just "module" for the name. The shared + library loader squirrels away the true name of the module in + _Py_PackageContext, and PyModule_Create*() will substitute this + (if the name actually matches). + */ + if (_Py_PackageContext != NULL) { + char *p = strrchr(_Py_PackageContext, '.'); + if (p != NULL && strcmp(module->m_name, p+1) == 0) { + name = _Py_PackageContext; + _Py_PackageContext = NULL; + } + } + if ((m = (PyModuleObject*)PyModule_New(name)) == NULL) + return NULL; + + if (module->m_size > 0) { + m->md_state = PyMem_MALLOC(module->m_size); + if (!m->md_state) { + PyErr_NoMemory(); + Py_DECREF(m); + return NULL; + } + memset(m->md_state, 0, module->m_size); + } + + d = PyModule_GetDict((PyObject*)m); + if (module->m_methods != NULL) { + n = PyUnicode_FromString(name); + if (n == NULL) + return NULL; + for (ml = module->m_methods; ml->ml_name != NULL; ml++) { + if ((ml->ml_flags & METH_CLASS) || + (ml->ml_flags & METH_STATIC)) { + PyErr_SetString(PyExc_ValueError, + "module functions cannot set" + " METH_CLASS or METH_STATIC"); + Py_DECREF(n); + return NULL; + } + v = PyCFunction_NewEx(ml, (PyObject*)m, n); + if (v == NULL) { + Py_DECREF(n); + return NULL; + } + if (PyDict_SetItemString(d, ml->ml_name, v) != 0) { + Py_DECREF(v); + Py_DECREF(n); + return NULL; + } + Py_DECREF(v); + } + Py_DECREF(n); + } + if (module->m_doc != NULL) { + v = PyUnicode_FromString(module->m_doc); + if (v == NULL || PyDict_SetItemString(d, "__doc__", v) != 0) { + Py_XDECREF(v); + return NULL; + } + Py_DECREF(v); + } + m->md_def = module; + return (PyObject*)m; } PyObject * PyModule_GetDict(PyObject *m) { - PyObject *d; - if (!PyModule_Check(m)) { - PyErr_BadInternalCall(); - return NULL; - } - d = ((PyModuleObject *)m) -> md_dict; - if (d == NULL) - ((PyModuleObject *)m) -> md_dict = d = PyDict_New(); - return d; + PyObject *d; + if (!PyModule_Check(m)) { + PyErr_BadInternalCall(); + return NULL; + } + d = ((PyModuleObject *)m) -> md_dict; + if (d == NULL) + ((PyModuleObject *)m) -> md_dict = d = PyDict_New(); + return d; } const char * PyModule_GetName(PyObject *m) { - PyObject *d; - PyObject *nameobj; - if (!PyModule_Check(m)) { - PyErr_BadArgument(); - return NULL; - } - d = ((PyModuleObject *)m)->md_dict; - if (d == NULL || - (nameobj = PyDict_GetItemString(d, "__name__")) == NULL || - !PyUnicode_Check(nameobj)) - { - PyErr_SetString(PyExc_SystemError, "nameless module"); - return NULL; - } - return _PyUnicode_AsString(nameobj); + PyObject *d; + PyObject *nameobj; + if (!PyModule_Check(m)) { + PyErr_BadArgument(); + return NULL; + } + d = ((PyModuleObject *)m)->md_dict; + if (d == NULL || + (nameobj = PyDict_GetItemString(d, "__name__")) == NULL || + !PyUnicode_Check(nameobj)) + { + PyErr_SetString(PyExc_SystemError, "nameless module"); + return NULL; + } + return _PyUnicode_AsString(nameobj); } static PyObject* module_getfilename(PyObject *m) { - PyObject *d; - PyObject *fileobj; - if (!PyModule_Check(m)) { - PyErr_BadArgument(); - return NULL; - } - d = ((PyModuleObject *)m)->md_dict; - if (d == NULL || - (fileobj = PyDict_GetItemString(d, "__file__")) == NULL || - !PyUnicode_Check(fileobj)) - { - PyErr_SetString(PyExc_SystemError, "module filename missing"); - return NULL; - } - return fileobj; + PyObject *d; + PyObject *fileobj; + if (!PyModule_Check(m)) { + PyErr_BadArgument(); + return NULL; + } + d = ((PyModuleObject *)m)->md_dict; + if (d == NULL || + (fileobj = PyDict_GetItemString(d, "__file__")) == NULL || + !PyUnicode_Check(fileobj)) + { + PyErr_SetString(PyExc_SystemError, "module filename missing"); + return NULL; + } + return fileobj; } const char * PyModule_GetFilename(PyObject *m) { - PyObject *fileobj; - fileobj = module_getfilename(m); - if (fileobj == NULL) - return NULL; - return _PyUnicode_AsString(fileobj); + PyObject *fileobj; + fileobj = module_getfilename(m); + if (fileobj == NULL) + return NULL; + return _PyUnicode_AsString(fileobj); } PyModuleDef* PyModule_GetDef(PyObject* m) { - if (!PyModule_Check(m)) { - PyErr_BadArgument(); - return NULL; - } - return ((PyModuleObject *)m)->md_def; + if (!PyModule_Check(m)) { + PyErr_BadArgument(); + return NULL; + } + return ((PyModuleObject *)m)->md_def; } void* PyModule_GetState(PyObject* m) { - if (!PyModule_Check(m)) { - PyErr_BadArgument(); - return NULL; - } - return ((PyModuleObject *)m)->md_state; + if (!PyModule_Check(m)) { + PyErr_BadArgument(); + return NULL; + } + return ((PyModuleObject *)m)->md_state; } void _PyModule_Clear(PyObject *m) { - /* To make the execution order of destructors for global - objects a bit more predictable, we first zap all objects - whose name starts with a single underscore, before we clear - the entire dictionary. We zap them by replacing them with - None, rather than deleting them from the dictionary, to - avoid rehashing the dictionary (to some extent). */ - - Py_ssize_t pos; - PyObject *key, *value; - PyObject *d; - - d = ((PyModuleObject *)m)->md_dict; - if (d == NULL) - return; - - /* First, clear only names starting with a single underscore */ - pos = 0; - while (PyDict_Next(d, &pos, &key, &value)) { - if (value != Py_None && PyUnicode_Check(key)) { - const char *s = _PyUnicode_AsString(key); - if (s[0] == '_' && s[1] != '_') { - if (Py_VerboseFlag > 1) - PySys_WriteStderr("# clear[1] %s\n", s); - PyDict_SetItem(d, key, Py_None); - } - } - } - - /* Next, clear all names except for __builtins__ */ - pos = 0; - while (PyDict_Next(d, &pos, &key, &value)) { - if (value != Py_None && PyUnicode_Check(key)) { - const char *s = _PyUnicode_AsString(key); - if (s[0] != '_' || strcmp(s, "__builtins__") != 0) { - if (Py_VerboseFlag > 1) - PySys_WriteStderr("# clear[2] %s\n", s); - PyDict_SetItem(d, key, Py_None); - } - } - } - - /* Note: we leave __builtins__ in place, so that destructors - of non-global objects defined in this module can still use - builtins, in particularly 'None'. */ + /* To make the execution order of destructors for global + objects a bit more predictable, we first zap all objects + whose name starts with a single underscore, before we clear + the entire dictionary. We zap them by replacing them with + None, rather than deleting them from the dictionary, to + avoid rehashing the dictionary (to some extent). */ + + Py_ssize_t pos; + PyObject *key, *value; + PyObject *d; + + d = ((PyModuleObject *)m)->md_dict; + if (d == NULL) + return; + + /* First, clear only names starting with a single underscore */ + pos = 0; + while (PyDict_Next(d, &pos, &key, &value)) { + if (value != Py_None && PyUnicode_Check(key)) { + const char *s = _PyUnicode_AsString(key); + if (s[0] == '_' && s[1] != '_') { + if (Py_VerboseFlag > 1) + PySys_WriteStderr("# clear[1] %s\n", s); + PyDict_SetItem(d, key, Py_None); + } + } + } + + /* Next, clear all names except for __builtins__ */ + pos = 0; + while (PyDict_Next(d, &pos, &key, &value)) { + if (value != Py_None && PyUnicode_Check(key)) { + const char *s = _PyUnicode_AsString(key); + if (s[0] != '_' || strcmp(s, "__builtins__") != 0) { + if (Py_VerboseFlag > 1) + PySys_WriteStderr("# clear[2] %s\n", s); + PyDict_SetItem(d, key, Py_None); + } + } + } + + /* Note: we leave __builtins__ in place, so that destructors + of non-global objects defined in this module can still use + builtins, in particularly 'None'. */ } @@ -296,86 +296,86 @@ static int module_init(PyModuleObject *m, PyObject *args, PyObject *kwds) { - static char *kwlist[] = {"name", "doc", NULL}; - PyObject *dict, *name = Py_None, *doc = Py_None; - if (!PyArg_ParseTupleAndKeywords(args, kwds, "U|O:module.__init__", - kwlist, &name, &doc)) - return -1; - dict = m->md_dict; - if (dict == NULL) { - dict = PyDict_New(); - if (dict == NULL) - return -1; - m->md_dict = dict; - } - if (PyDict_SetItemString(dict, "__name__", name) < 0) - return -1; - if (PyDict_SetItemString(dict, "__doc__", doc) < 0) - return -1; - return 0; + static char *kwlist[] = {"name", "doc", NULL}; + PyObject *dict, *name = Py_None, *doc = Py_None; + if (!PyArg_ParseTupleAndKeywords(args, kwds, "U|O:module.__init__", + kwlist, &name, &doc)) + return -1; + dict = m->md_dict; + if (dict == NULL) { + dict = PyDict_New(); + if (dict == NULL) + return -1; + m->md_dict = dict; + } + if (PyDict_SetItemString(dict, "__name__", name) < 0) + return -1; + if (PyDict_SetItemString(dict, "__doc__", doc) < 0) + return -1; + return 0; } static void module_dealloc(PyModuleObject *m) { - PyObject_GC_UnTrack(m); - if (m->md_def && m->md_def->m_free) - m->md_def->m_free(m); - if (m->md_dict != NULL) { - /* If we are the only ones holding a reference, we can clear - the dictionary. */ - if (Py_REFCNT(m->md_dict) == 1) - _PyModule_Clear((PyObject *)m); - Py_DECREF(m->md_dict); - } - if (m->md_state != NULL) - PyMem_FREE(m->md_state); - Py_TYPE(m)->tp_free((PyObject *)m); + PyObject_GC_UnTrack(m); + if (m->md_def && m->md_def->m_free) + m->md_def->m_free(m); + if (m->md_dict != NULL) { + /* If we are the only ones holding a reference, we can clear + the dictionary. */ + if (Py_REFCNT(m->md_dict) == 1) + _PyModule_Clear((PyObject *)m); + Py_DECREF(m->md_dict); + } + if (m->md_state != NULL) + PyMem_FREE(m->md_state); + Py_TYPE(m)->tp_free((PyObject *)m); } static PyObject * module_repr(PyModuleObject *m) { - const char *name; - PyObject *filename; + const char *name; + PyObject *filename; - name = PyModule_GetName((PyObject *)m); - if (name == NULL) { - PyErr_Clear(); - name = "?"; - } - filename = module_getfilename((PyObject *)m); - if (filename == NULL) { - PyErr_Clear(); - return PyUnicode_FromFormat("", name); - } - return PyUnicode_FromFormat("", name, filename); + name = PyModule_GetName((PyObject *)m); + if (name == NULL) { + PyErr_Clear(); + name = "?"; + } + filename = module_getfilename((PyObject *)m); + if (filename == NULL) { + PyErr_Clear(); + return PyUnicode_FromFormat("", name); + } + return PyUnicode_FromFormat("", name, filename); } static int module_traverse(PyModuleObject *m, visitproc visit, void *arg) { - if (m->md_def && m->md_def->m_traverse) { - int res = m->md_def->m_traverse((PyObject*)m, visit, arg); - if (res) - return res; - } - Py_VISIT(m->md_dict); - return 0; + if (m->md_def && m->md_def->m_traverse) { + int res = m->md_def->m_traverse((PyObject*)m, visit, arg); + if (res) + return res; + } + Py_VISIT(m->md_dict); + return 0; } static int module_clear(PyModuleObject *m) { - if (m->md_def && m->md_def->m_clear) { - int res = m->md_def->m_clear((PyObject*)m); - if (res) - return res; - } - Py_CLEAR(m->md_dict); - return 0; + if (m->md_def && m->md_def->m_clear) { + int res = m->md_def->m_clear((PyObject*)m); + if (res) + return res; + } + Py_CLEAR(m->md_dict); + return 0; } - + PyDoc_STRVAR(module_doc, "module(name[, doc])\n\ @@ -384,44 +384,44 @@ 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 */ - 0, /* tp_itemsize */ - (destructor)module_dealloc, /* tp_dealloc */ - 0, /* tp_print */ - 0, /* tp_getattr */ - 0, /* tp_setattr */ - 0, /* tp_reserved */ - (reprfunc)module_repr, /* 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 */ - PyObject_GenericSetAttr, /* tp_setattro */ - 0, /* tp_as_buffer */ - Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC | - Py_TPFLAGS_BASETYPE, /* tp_flags */ - module_doc, /* tp_doc */ - (traverseproc)module_traverse, /* tp_traverse */ - (inquiry)module_clear, /* tp_clear */ - 0, /* tp_richcompare */ - 0, /* tp_weaklistoffset */ - 0, /* tp_iter */ - 0, /* tp_iternext */ - 0, /* tp_methods */ - module_members, /* tp_members */ - 0, /* tp_getset */ - 0, /* tp_base */ - 0, /* tp_dict */ - 0, /* tp_descr_get */ - 0, /* tp_descr_set */ - offsetof(PyModuleObject, md_dict), /* tp_dictoffset */ - (initproc)module_init, /* tp_init */ - PyType_GenericAlloc, /* tp_alloc */ - PyType_GenericNew, /* tp_new */ - PyObject_GC_Del, /* tp_free */ + PyVarObject_HEAD_INIT(&PyType_Type, 0) + "module", /* tp_name */ + sizeof(PyModuleObject), /* tp_size */ + 0, /* tp_itemsize */ + (destructor)module_dealloc, /* tp_dealloc */ + 0, /* tp_print */ + 0, /* tp_getattr */ + 0, /* tp_setattr */ + 0, /* tp_reserved */ + (reprfunc)module_repr, /* 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 */ + PyObject_GenericSetAttr, /* tp_setattro */ + 0, /* tp_as_buffer */ + Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC | + Py_TPFLAGS_BASETYPE, /* tp_flags */ + module_doc, /* tp_doc */ + (traverseproc)module_traverse, /* tp_traverse */ + (inquiry)module_clear, /* tp_clear */ + 0, /* tp_richcompare */ + 0, /* tp_weaklistoffset */ + 0, /* tp_iter */ + 0, /* tp_iternext */ + 0, /* tp_methods */ + module_members, /* tp_members */ + 0, /* tp_getset */ + 0, /* tp_base */ + 0, /* tp_dict */ + 0, /* tp_descr_get */ + 0, /* tp_descr_set */ + offsetof(PyModuleObject, md_dict), /* tp_dictoffset */ + (initproc)module_init, /* tp_init */ + PyType_GenericAlloc, /* tp_alloc */ + PyType_GenericNew, /* tp_new */ + PyObject_GC_Del, /* tp_free */ }; Modified: python/branches/py3k/Objects/object.c ============================================================================== --- python/branches/py3k/Objects/object.c (original) +++ python/branches/py3k/Objects/object.c Sun May 9 17:52:27 2010 @@ -15,18 +15,18 @@ Py_ssize_t _Py_GetRefTotal(void) { - PyObject *o; - Py_ssize_t total = _Py_RefTotal; - /* ignore the references to the dummy object of the dicts and sets - because they are not reliable and not useful (now that the - hash table code is well-tested) */ - o = _PyDict_Dummy(); - if (o != NULL) - total -= o->ob_refcnt; - o = _PySet_Dummy(); - if (o != NULL) - total -= o->ob_refcnt; - return total; + PyObject *o; + Py_ssize_t total = _Py_RefTotal; + /* ignore the references to the dummy object of the dicts and sets + because they are not reliable and not useful (now that the + hash table code is well-tested) */ + o = _PyDict_Dummy(); + if (o != NULL) + total -= o->ob_refcnt; + o = _PySet_Dummy(); + if (o != NULL) + total -= o->ob_refcnt; + return total; } #endif /* Py_REF_DEBUG */ @@ -58,21 +58,21 @@ _Py_AddToAllObjects(PyObject *op, int force) { #ifdef Py_DEBUG - if (!force) { - /* If it's initialized memory, op must be in or out of - * the list unambiguously. - */ - assert((op->_ob_prev == NULL) == (op->_ob_next == NULL)); - } + if (!force) { + /* If it's initialized memory, op must be in or out of + * the list unambiguously. + */ + assert((op->_ob_prev == NULL) == (op->_ob_next == NULL)); + } #endif - if (force || op->_ob_prev == NULL) { - op->_ob_next = refchain._ob_next; - op->_ob_prev = &refchain; - refchain._ob_next->_ob_prev = op; - refchain._ob_next = op; - } + if (force || op->_ob_prev == NULL) { + op->_ob_next = refchain._ob_next; + op->_ob_prev = &refchain; + refchain._ob_next->_ob_prev = op; + refchain._ob_next = op; + } } -#endif /* Py_TRACE_REFS */ +#endif /* Py_TRACE_REFS */ #ifdef COUNT_ALLOCS static PyTypeObject *type_list; @@ -89,99 +89,99 @@ void dump_counts(FILE* f) { - PyTypeObject *tp; + PyTypeObject *tp; - for (tp = type_list; tp; tp = tp->tp_next) - fprintf(f, "%s alloc'd: %" PY_FORMAT_SIZE_T "d, " - "freed: %" PY_FORMAT_SIZE_T "d, " - "max in use: %" PY_FORMAT_SIZE_T "d\n", - tp->tp_name, tp->tp_allocs, tp->tp_frees, - tp->tp_maxalloc); - fprintf(f, "fast tuple allocs: %" PY_FORMAT_SIZE_T "d, " - "empty: %" PY_FORMAT_SIZE_T "d\n", - fast_tuple_allocs, tuple_zero_allocs); - fprintf(f, "fast int allocs: pos: %" PY_FORMAT_SIZE_T "d, " - "neg: %" PY_FORMAT_SIZE_T "d\n", - quick_int_allocs, quick_neg_int_allocs); - fprintf(f, "null strings: %" PY_FORMAT_SIZE_T "d, " - "1-strings: %" PY_FORMAT_SIZE_T "d\n", - null_strings, one_strings); + for (tp = type_list; tp; tp = tp->tp_next) + fprintf(f, "%s alloc'd: %" PY_FORMAT_SIZE_T "d, " + "freed: %" PY_FORMAT_SIZE_T "d, " + "max in use: %" PY_FORMAT_SIZE_T "d\n", + tp->tp_name, tp->tp_allocs, tp->tp_frees, + tp->tp_maxalloc); + fprintf(f, "fast tuple allocs: %" PY_FORMAT_SIZE_T "d, " + "empty: %" PY_FORMAT_SIZE_T "d\n", + fast_tuple_allocs, tuple_zero_allocs); + fprintf(f, "fast int allocs: pos: %" PY_FORMAT_SIZE_T "d, " + "neg: %" PY_FORMAT_SIZE_T "d\n", + quick_int_allocs, quick_neg_int_allocs); + fprintf(f, "null strings: %" PY_FORMAT_SIZE_T "d, " + "1-strings: %" PY_FORMAT_SIZE_T "d\n", + null_strings, one_strings); } PyObject * get_counts(void) { - PyTypeObject *tp; - PyObject *result; - PyObject *v; - - result = PyList_New(0); - if (result == NULL) - return NULL; - for (tp = type_list; tp; tp = tp->tp_next) { - v = Py_BuildValue("(snnn)", tp->tp_name, tp->tp_allocs, - tp->tp_frees, tp->tp_maxalloc); - if (v == NULL) { - Py_DECREF(result); - return NULL; - } - if (PyList_Append(result, v) < 0) { - Py_DECREF(v); - Py_DECREF(result); - return NULL; - } - Py_DECREF(v); - } - return result; + PyTypeObject *tp; + PyObject *result; + PyObject *v; + + result = PyList_New(0); + if (result == NULL) + return NULL; + for (tp = type_list; tp; tp = tp->tp_next) { + v = Py_BuildValue("(snnn)", tp->tp_name, tp->tp_allocs, + tp->tp_frees, tp->tp_maxalloc); + if (v == NULL) { + Py_DECREF(result); + return NULL; + } + if (PyList_Append(result, v) < 0) { + Py_DECREF(v); + Py_DECREF(result); + return NULL; + } + Py_DECREF(v); + } + return result; } void inc_count(PyTypeObject *tp) { - if (tp->tp_next == NULL && tp->tp_prev == NULL) { - /* first time; insert in linked list */ - if (tp->tp_next != NULL) /* sanity check */ - Py_FatalError("XXX inc_count sanity check"); - if (type_list) - type_list->tp_prev = tp; - tp->tp_next = type_list; - /* Note that as of Python 2.2, heap-allocated type objects - * can go away, but this code requires that they stay alive - * until program exit. That's why we're careful with - * refcounts here. type_list gets a new reference to tp, - * while ownership of the reference type_list used to hold - * (if any) was transferred to tp->tp_next in the line above. - * tp is thus effectively immortal after this. - */ - Py_INCREF(tp); - type_list = tp; + if (tp->tp_next == NULL && tp->tp_prev == NULL) { + /* first time; insert in linked list */ + if (tp->tp_next != NULL) /* sanity check */ + Py_FatalError("XXX inc_count sanity check"); + if (type_list) + type_list->tp_prev = tp; + tp->tp_next = type_list; + /* Note that as of Python 2.2, heap-allocated type objects + * can go away, but this code requires that they stay alive + * until program exit. That's why we're careful with + * refcounts here. type_list gets a new reference to tp, + * while ownership of the reference type_list used to hold + * (if any) was transferred to tp->tp_next in the line above. + * tp is thus effectively immortal after this. + */ + Py_INCREF(tp); + type_list = tp; #ifdef Py_TRACE_REFS - /* Also insert in the doubly-linked list of all objects, - * if not already there. - */ - _Py_AddToAllObjects((PyObject *)tp, 0); + /* Also insert in the doubly-linked list of all objects, + * if not already there. + */ + _Py_AddToAllObjects((PyObject *)tp, 0); #endif - } - tp->tp_allocs++; - if (tp->tp_allocs - tp->tp_frees > tp->tp_maxalloc) - tp->tp_maxalloc = tp->tp_allocs - tp->tp_frees; + } + tp->tp_allocs++; + if (tp->tp_allocs - tp->tp_frees > tp->tp_maxalloc) + tp->tp_maxalloc = tp->tp_allocs - tp->tp_frees; } void dec_count(PyTypeObject *tp) { - tp->tp_frees++; - if (unlist_types_without_objects && - tp->tp_allocs == tp->tp_frees) { - /* unlink the type from type_list */ - if (tp->tp_prev) - tp->tp_prev->tp_next = tp->tp_next; - else - type_list = tp->tp_next; - if (tp->tp_next) - tp->tp_next->tp_prev = tp->tp_prev; - tp->tp_next = tp->tp_prev = NULL; - Py_DECREF(tp); - } + tp->tp_frees++; + if (unlist_types_without_objects && + tp->tp_allocs == tp->tp_frees) { + /* unlink the type from type_list */ + if (tp->tp_prev) + tp->tp_prev->tp_next = tp->tp_next; + else + type_list = tp->tp_next; + if (tp->tp_next) + tp->tp_next->tp_prev = tp->tp_prev; + tp->tp_next = tp->tp_prev = NULL; + Py_DECREF(tp); + } } #endif @@ -191,13 +191,13 @@ void _Py_NegativeRefcount(const char *fname, int lineno, PyObject *op) { - char buf[300]; + char buf[300]; - PyOS_snprintf(buf, sizeof(buf), - "%s:%i object at %p has negative ref count " - "%" PY_FORMAT_SIZE_T "d", - fname, lineno, op, op->ob_refcnt); - Py_FatalError(buf); + PyOS_snprintf(buf, sizeof(buf), + "%s:%i object at %p has negative ref count " + "%" PY_FORMAT_SIZE_T "d", + fname, lineno, op, op->ob_refcnt); + Py_FatalError(buf); } #endif /* Py_REF_DEBUG */ @@ -217,123 +217,123 @@ PyObject * PyObject_Init(PyObject *op, PyTypeObject *tp) { - if (op == NULL) - return PyErr_NoMemory(); - /* Any changes should be reflected in PyObject_INIT (objimpl.h) */ - Py_TYPE(op) = tp; - _Py_NewReference(op); - return op; + if (op == NULL) + return PyErr_NoMemory(); + /* Any changes should be reflected in PyObject_INIT (objimpl.h) */ + Py_TYPE(op) = tp; + _Py_NewReference(op); + return op; } PyVarObject * PyObject_InitVar(PyVarObject *op, PyTypeObject *tp, Py_ssize_t size) { - if (op == NULL) - return (PyVarObject *) PyErr_NoMemory(); - /* Any changes should be reflected in PyObject_INIT_VAR */ - op->ob_size = size; - Py_TYPE(op) = tp; - _Py_NewReference((PyObject *)op); - return op; + if (op == NULL) + return (PyVarObject *) PyErr_NoMemory(); + /* Any changes should be reflected in PyObject_INIT_VAR */ + op->ob_size = size; + Py_TYPE(op) = tp; + _Py_NewReference((PyObject *)op); + return op; } PyObject * _PyObject_New(PyTypeObject *tp) { - PyObject *op; - op = (PyObject *) PyObject_MALLOC(_PyObject_SIZE(tp)); - if (op == NULL) - return PyErr_NoMemory(); - return PyObject_INIT(op, tp); + PyObject *op; + op = (PyObject *) PyObject_MALLOC(_PyObject_SIZE(tp)); + if (op == NULL) + return PyErr_NoMemory(); + return PyObject_INIT(op, tp); } PyVarObject * _PyObject_NewVar(PyTypeObject *tp, Py_ssize_t nitems) { - PyVarObject *op; - const size_t size = _PyObject_VAR_SIZE(tp, nitems); - op = (PyVarObject *) PyObject_MALLOC(size); - if (op == NULL) - return (PyVarObject *)PyErr_NoMemory(); - return PyObject_INIT_VAR(op, tp, nitems); + PyVarObject *op; + const size_t size = _PyObject_VAR_SIZE(tp, nitems); + op = (PyVarObject *) PyObject_MALLOC(size); + if (op == NULL) + return (PyVarObject *)PyErr_NoMemory(); + return PyObject_INIT_VAR(op, tp, nitems); } /* Implementation of PyObject_Print with recursion checking */ static int internal_print(PyObject *op, FILE *fp, int flags, int nesting) { - int ret = 0; - if (nesting > 10) { - PyErr_SetString(PyExc_RuntimeError, "print recursion"); - return -1; - } - if (PyErr_CheckSignals()) - return -1; + int ret = 0; + if (nesting > 10) { + PyErr_SetString(PyExc_RuntimeError, "print recursion"); + return -1; + } + if (PyErr_CheckSignals()) + return -1; #ifdef USE_STACKCHECK - if (PyOS_CheckStack()) { - PyErr_SetString(PyExc_MemoryError, "stack overflow"); - return -1; - } + if (PyOS_CheckStack()) { + PyErr_SetString(PyExc_MemoryError, "stack overflow"); + return -1; + } #endif - clearerr(fp); /* Clear any previous error condition */ - if (op == NULL) { - Py_BEGIN_ALLOW_THREADS - fprintf(fp, ""); - Py_END_ALLOW_THREADS - } - else { - if (op->ob_refcnt <= 0) - /* XXX(twouters) cast refcount to long until %zd is - universally available */ - Py_BEGIN_ALLOW_THREADS - fprintf(fp, "", - (long)op->ob_refcnt, op); - Py_END_ALLOW_THREADS - else { - PyObject *s; - if (flags & Py_PRINT_RAW) - s = PyObject_Str(op); - else - s = PyObject_Repr(op); - if (s == NULL) - ret = -1; - else if (PyBytes_Check(s)) { - fwrite(PyBytes_AS_STRING(s), 1, - PyBytes_GET_SIZE(s), fp); - } - else if (PyUnicode_Check(s)) { - PyObject *t; - t = _PyUnicode_AsDefaultEncodedString(s, NULL); - if (t == NULL) - ret = 0; - else { - fwrite(PyBytes_AS_STRING(t), 1, - PyBytes_GET_SIZE(t), fp); - } - } - else { - PyErr_Format(PyExc_TypeError, - "str() or repr() returned '%.100s'", - s->ob_type->tp_name); - ret = -1; - } - Py_XDECREF(s); - } - } - if (ret == 0) { - if (ferror(fp)) { - PyErr_SetFromErrno(PyExc_IOError); - clearerr(fp); - ret = -1; - } - } - return ret; + clearerr(fp); /* Clear any previous error condition */ + if (op == NULL) { + Py_BEGIN_ALLOW_THREADS + fprintf(fp, ""); + Py_END_ALLOW_THREADS + } + else { + if (op->ob_refcnt <= 0) + /* XXX(twouters) cast refcount to long until %zd is + universally available */ + Py_BEGIN_ALLOW_THREADS + fprintf(fp, "", + (long)op->ob_refcnt, op); + Py_END_ALLOW_THREADS + else { + PyObject *s; + if (flags & Py_PRINT_RAW) + s = PyObject_Str(op); + else + s = PyObject_Repr(op); + if (s == NULL) + ret = -1; + else if (PyBytes_Check(s)) { + fwrite(PyBytes_AS_STRING(s), 1, + PyBytes_GET_SIZE(s), fp); + } + else if (PyUnicode_Check(s)) { + PyObject *t; + t = _PyUnicode_AsDefaultEncodedString(s, NULL); + if (t == NULL) + ret = 0; + else { + fwrite(PyBytes_AS_STRING(t), 1, + PyBytes_GET_SIZE(t), fp); + } + } + else { + PyErr_Format(PyExc_TypeError, + "str() or repr() returned '%.100s'", + s->ob_type->tp_name); + ret = -1; + } + Py_XDECREF(s); + } + } + if (ret == 0) { + if (ferror(fp)) { + PyErr_SetFromErrno(PyExc_IOError); + clearerr(fp); + ret = -1; + } + } + return ret; } int PyObject_Print(PyObject *op, FILE *fp, int flags) { - return internal_print(op, fp, flags, 0); + return internal_print(op, fp, flags, 0); } /* For debugging convenience. Set a breakpoint here and call it from your DLL */ @@ -347,159 +347,159 @@ void _PyObject_Dump(PyObject* op) { - if (op == NULL) - fprintf(stderr, "NULL\n"); - else { + if (op == NULL) + fprintf(stderr, "NULL\n"); + else { #ifdef WITH_THREAD - PyGILState_STATE gil; + PyGILState_STATE gil; #endif - fprintf(stderr, "object : "); + fprintf(stderr, "object : "); #ifdef WITH_THREAD - gil = PyGILState_Ensure(); + gil = PyGILState_Ensure(); #endif - (void)PyObject_Print(op, stderr, 0); + (void)PyObject_Print(op, stderr, 0); #ifdef WITH_THREAD - PyGILState_Release(gil); + PyGILState_Release(gil); #endif - /* XXX(twouters) cast refcount to long until %zd is - universally available */ - fprintf(stderr, "\n" - "type : %s\n" - "refcount: %ld\n" - "address : %p\n", - Py_TYPE(op)==NULL ? "NULL" : Py_TYPE(op)->tp_name, - (long)op->ob_refcnt, - op); - } + /* XXX(twouters) cast refcount to long until %zd is + universally available */ + fprintf(stderr, "\n" + "type : %s\n" + "refcount: %ld\n" + "address : %p\n", + Py_TYPE(op)==NULL ? "NULL" : Py_TYPE(op)->tp_name, + (long)op->ob_refcnt, + op); + } } PyObject * PyObject_Repr(PyObject *v) { - PyObject *res; - if (PyErr_CheckSignals()) - return NULL; + PyObject *res; + if (PyErr_CheckSignals()) + return NULL; #ifdef USE_STACKCHECK - if (PyOS_CheckStack()) { - PyErr_SetString(PyExc_MemoryError, "stack overflow"); - return NULL; - } + if (PyOS_CheckStack()) { + PyErr_SetString(PyExc_MemoryError, "stack overflow"); + return NULL; + } #endif - if (v == NULL) - return PyUnicode_FromString(""); - if (Py_TYPE(v)->tp_repr == NULL) - return PyUnicode_FromFormat("<%s object at %p>", - v->ob_type->tp_name, v); - res = (*v->ob_type->tp_repr)(v); - if (res != NULL && !PyUnicode_Check(res)) { - PyErr_Format(PyExc_TypeError, - "__repr__ returned non-string (type %.200s)", - res->ob_type->tp_name); - Py_DECREF(res); - return NULL; - } - return res; + if (v == NULL) + return PyUnicode_FromString(""); + if (Py_TYPE(v)->tp_repr == NULL) + return PyUnicode_FromFormat("<%s object at %p>", + v->ob_type->tp_name, v); + res = (*v->ob_type->tp_repr)(v); + if (res != NULL && !PyUnicode_Check(res)) { + PyErr_Format(PyExc_TypeError, + "__repr__ returned non-string (type %.200s)", + res->ob_type->tp_name); + Py_DECREF(res); + return NULL; + } + return res; } PyObject * PyObject_Str(PyObject *v) { - PyObject *res; - if (PyErr_CheckSignals()) - return NULL; + PyObject *res; + if (PyErr_CheckSignals()) + return NULL; #ifdef USE_STACKCHECK - if (PyOS_CheckStack()) { - PyErr_SetString(PyExc_MemoryError, "stack overflow"); - return NULL; - } + if (PyOS_CheckStack()) { + PyErr_SetString(PyExc_MemoryError, "stack overflow"); + return NULL; + } #endif - if (v == NULL) - return PyUnicode_FromString(""); - if (PyUnicode_CheckExact(v)) { - Py_INCREF(v); - return v; - } - if (Py_TYPE(v)->tp_str == NULL) - return PyObject_Repr(v); - - /* It is possible for a type to have a tp_str representation that loops - infinitely. */ - if (Py_EnterRecursiveCall(" while getting the str of an object")) - return NULL; - res = (*Py_TYPE(v)->tp_str)(v); - Py_LeaveRecursiveCall(); - if (res == NULL) - return NULL; - if (!PyUnicode_Check(res)) { - PyErr_Format(PyExc_TypeError, - "__str__ returned non-string (type %.200s)", - Py_TYPE(res)->tp_name); - Py_DECREF(res); - return NULL; - } - return res; + if (v == NULL) + return PyUnicode_FromString(""); + if (PyUnicode_CheckExact(v)) { + Py_INCREF(v); + return v; + } + if (Py_TYPE(v)->tp_str == NULL) + return PyObject_Repr(v); + + /* It is possible for a type to have a tp_str representation that loops + infinitely. */ + if (Py_EnterRecursiveCall(" while getting the str of an object")) + return NULL; + res = (*Py_TYPE(v)->tp_str)(v); + Py_LeaveRecursiveCall(); + if (res == NULL) + return NULL; + if (!PyUnicode_Check(res)) { + PyErr_Format(PyExc_TypeError, + "__str__ returned non-string (type %.200s)", + Py_TYPE(res)->tp_name); + Py_DECREF(res); + return NULL; + } + return res; } PyObject * PyObject_ASCII(PyObject *v) { - PyObject *repr, *ascii, *res; - - repr = PyObject_Repr(v); - if (repr == NULL) - return NULL; - - /* repr is guaranteed to be a PyUnicode object by PyObject_Repr */ - ascii = PyUnicode_EncodeASCII( - PyUnicode_AS_UNICODE(repr), - PyUnicode_GET_SIZE(repr), - "backslashreplace"); - - Py_DECREF(repr); - if (ascii == NULL) - return NULL; - - res = PyUnicode_DecodeASCII( - PyBytes_AS_STRING(ascii), - PyBytes_GET_SIZE(ascii), - NULL); + PyObject *repr, *ascii, *res; - Py_DECREF(ascii); - return res; + repr = PyObject_Repr(v); + if (repr == NULL) + return NULL; + + /* repr is guaranteed to be a PyUnicode object by PyObject_Repr */ + ascii = PyUnicode_EncodeASCII( + PyUnicode_AS_UNICODE(repr), + PyUnicode_GET_SIZE(repr), + "backslashreplace"); + + Py_DECREF(repr); + if (ascii == NULL) + return NULL; + + res = PyUnicode_DecodeASCII( + PyBytes_AS_STRING(ascii), + PyBytes_GET_SIZE(ascii), + NULL); + + Py_DECREF(ascii); + return res; } PyObject * PyObject_Bytes(PyObject *v) { - PyObject *result, *func; - static PyObject *bytesstring = NULL; + PyObject *result, *func; + static PyObject *bytesstring = NULL; - if (v == NULL) - return PyBytes_FromString(""); + if (v == NULL) + return PyBytes_FromString(""); - if (PyBytes_CheckExact(v)) { - Py_INCREF(v); - return v; - } - - func = _PyObject_LookupSpecial(v, "__bytes__", &bytesstring); - if (func != NULL) { - result = PyObject_CallFunctionObjArgs(func, NULL); - 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; - } - return result; - } - else if (PyErr_Occurred()) - return NULL; - return PyBytes_FromObject(v); + if (PyBytes_CheckExact(v)) { + Py_INCREF(v); + return v; + } + + func = _PyObject_LookupSpecial(v, "__bytes__", &bytesstring); + if (func != NULL) { + result = PyObject_CallFunctionObjArgs(func, NULL); + 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; + } + return result; + } + else if (PyErr_Occurred()) + return NULL; + return PyBytes_FromObject(v); } /* For Python 3.0.1 and later, the old three-way comparison has been @@ -542,51 +542,51 @@ static PyObject * do_richcompare(PyObject *v, PyObject *w, int op) { - richcmpfunc f; - PyObject *res; - int checked_reverse_op = 0; - - if (v->ob_type != w->ob_type && - PyType_IsSubtype(w->ob_type, v->ob_type) && - (f = w->ob_type->tp_richcompare) != NULL) { - checked_reverse_op = 1; - res = (*f)(w, v, _Py_SwappedOp[op]); - if (res != Py_NotImplemented) - return res; - Py_DECREF(res); - } - if ((f = v->ob_type->tp_richcompare) != NULL) { - res = (*f)(v, w, op); - if (res != Py_NotImplemented) - return res; - Py_DECREF(res); - } - if (!checked_reverse_op && (f = w->ob_type->tp_richcompare) != NULL) { - res = (*f)(w, v, _Py_SwappedOp[op]); - if (res != Py_NotImplemented) - return res; - Py_DECREF(res); - } - /* If neither object implements it, provide a sensible default - for == and !=, but raise an exception for ordering. */ - switch (op) { - case Py_EQ: - res = (v == w) ? Py_True : Py_False; - break; - case Py_NE: - res = (v != w) ? Py_True : Py_False; - break; - default: - /* XXX Special-case None so it doesn't show as NoneType() */ - PyErr_Format(PyExc_TypeError, - "unorderable types: %.100s() %s %.100s()", - v->ob_type->tp_name, - opstrings[op], - w->ob_type->tp_name); - return NULL; - } - Py_INCREF(res); - return res; + richcmpfunc f; + PyObject *res; + int checked_reverse_op = 0; + + if (v->ob_type != w->ob_type && + PyType_IsSubtype(w->ob_type, v->ob_type) && + (f = w->ob_type->tp_richcompare) != NULL) { + checked_reverse_op = 1; + res = (*f)(w, v, _Py_SwappedOp[op]); + if (res != Py_NotImplemented) + return res; + Py_DECREF(res); + } + if ((f = v->ob_type->tp_richcompare) != NULL) { + res = (*f)(v, w, op); + if (res != Py_NotImplemented) + return res; + Py_DECREF(res); + } + if (!checked_reverse_op && (f = w->ob_type->tp_richcompare) != NULL) { + res = (*f)(w, v, _Py_SwappedOp[op]); + if (res != Py_NotImplemented) + return res; + Py_DECREF(res); + } + /* If neither object implements it, provide a sensible default + for == and !=, but raise an exception for ordering. */ + switch (op) { + case Py_EQ: + res = (v == w) ? Py_True : Py_False; + break; + case Py_NE: + res = (v != w) ? Py_True : Py_False; + break; + default: + /* XXX Special-case None so it doesn't show as NoneType() */ + PyErr_Format(PyExc_TypeError, + "unorderable types: %.100s() %s %.100s()", + v->ob_type->tp_name, + opstrings[op], + w->ob_type->tp_name); + return NULL; + } + Py_INCREF(res); + return res; } /* Perform a rich comparison with object result. This wraps do_richcompare() @@ -595,19 +595,19 @@ PyObject * PyObject_RichCompare(PyObject *v, PyObject *w, int op) { - PyObject *res; + PyObject *res; - assert(Py_LT <= op && op <= Py_GE); - if (v == NULL || w == NULL) { - if (!PyErr_Occurred()) - PyErr_BadInternalCall(); - return NULL; - } - if (Py_EnterRecursiveCall(" in comparison")) - return NULL; - res = do_richcompare(v, w, op); - Py_LeaveRecursiveCall(); - return res; + assert(Py_LT <= op && op <= Py_GE); + if (v == NULL || w == NULL) { + if (!PyErr_Occurred()) + PyErr_BadInternalCall(); + return NULL; + } + if (Py_EnterRecursiveCall(" in comparison")) + return NULL; + res = do_richcompare(v, w, op); + Py_LeaveRecursiveCall(); + return res; } /* Perform a rich comparison with integer result. This wraps @@ -615,31 +615,31 @@ int PyObject_RichCompareBool(PyObject *v, PyObject *w, int op) { - PyObject *res; - int ok; + PyObject *res; + int ok; - /* Quick result when objects are the same. - Guarantees that identity implies equality. */ - if (v == w) { - if (op == Py_EQ) - return 1; - else if (op == Py_NE) - return 0; - } - - res = PyObject_RichCompare(v, w, op); - if (res == NULL) - return -1; - if (PyBool_Check(res)) - ok = (res == Py_True); - else - ok = PyObject_IsTrue(res); - Py_DECREF(res); - return ok; + /* Quick result when objects are the same. + Guarantees that identity implies equality. */ + if (v == w) { + if (op == Py_EQ) + return 1; + else if (op == Py_NE) + return 0; + } + + res = PyObject_RichCompare(v, w, op); + if (res == NULL) + return -1; + if (PyBool_Check(res)) + ok = (res == Py_True); + else + ok = PyObject_IsTrue(res); + Py_DECREF(res); + return ok; } /* Set of hash utility functions to help maintaining the invariant that - if a==b then hash(a)==hash(b) + if a==b then hash(a)==hash(b) All the utility functions (_Py_Hash*()) return "-1" to signify an error. */ @@ -647,230 +647,230 @@ long _Py_HashDouble(double v) { - double intpart, fractpart; - int expo; - long hipart; - long x; /* the final hash value */ - /* This is designed so that Python numbers of different types - * that compare equal hash to the same value; otherwise comparisons - * of mapping keys will turn out weird. - */ - - if (!Py_IS_FINITE(v)) { - if (Py_IS_INFINITY(v)) - return v < 0 ? -271828 : 314159; - else - return 0; - } - fractpart = modf(v, &intpart); - if (fractpart == 0.0) { - /* This must return the same hash as an equal int or long. */ - if (intpart > LONG_MAX/2 || -intpart > LONG_MAX/2) { - /* Convert to long and use its hash. */ - PyObject *plong; /* converted to Python long */ - plong = PyLong_FromDouble(v); - if (plong == NULL) - return -1; - x = PyObject_Hash(plong); - Py_DECREF(plong); - return x; - } - /* Fits in a C long == a Python int, so is its own hash. */ - x = (long)intpart; - if (x == -1) - x = -2; - return x; - } - /* The fractional part is non-zero, so we don't have to worry about - * making this match the hash of some other type. - * Use frexp to get at the bits in the double. - * Since the VAX D double format has 56 mantissa bits, which is the - * most of any double format in use, each of these parts may have as - * many as (but no more than) 56 significant bits. - * So, assuming sizeof(long) >= 4, each part can be broken into two - * longs; frexp and multiplication are used to do that. - * Also, since the Cray double format has 15 exponent bits, which is - * the most of any double format in use, shifting the exponent field - * left by 15 won't overflow a long (again assuming sizeof(long) >= 4). - */ - v = frexp(v, &expo); - v *= 2147483648.0; /* 2**31 */ - hipart = (long)v; /* take the top 32 bits */ - v = (v - (double)hipart) * 2147483648.0; /* get the next 32 bits */ - x = hipart + (long)v + (expo << 15); - if (x == -1) - x = -2; - return x; + double intpart, fractpart; + int expo; + long hipart; + long x; /* the final hash value */ + /* This is designed so that Python numbers of different types + * that compare equal hash to the same value; otherwise comparisons + * of mapping keys will turn out weird. + */ + + if (!Py_IS_FINITE(v)) { + if (Py_IS_INFINITY(v)) + return v < 0 ? -271828 : 314159; + else + return 0; + } + fractpart = modf(v, &intpart); + if (fractpart == 0.0) { + /* This must return the same hash as an equal int or long. */ + if (intpart > LONG_MAX/2 || -intpart > LONG_MAX/2) { + /* Convert to long and use its hash. */ + PyObject *plong; /* converted to Python long */ + plong = PyLong_FromDouble(v); + if (plong == NULL) + return -1; + x = PyObject_Hash(plong); + Py_DECREF(plong); + return x; + } + /* Fits in a C long == a Python int, so is its own hash. */ + x = (long)intpart; + if (x == -1) + x = -2; + return x; + } + /* The fractional part is non-zero, so we don't have to worry about + * making this match the hash of some other type. + * Use frexp to get at the bits in the double. + * Since the VAX D double format has 56 mantissa bits, which is the + * most of any double format in use, each of these parts may have as + * many as (but no more than) 56 significant bits. + * So, assuming sizeof(long) >= 4, each part can be broken into two + * longs; frexp and multiplication are used to do that. + * Also, since the Cray double format has 15 exponent bits, which is + * the most of any double format in use, shifting the exponent field + * left by 15 won't overflow a long (again assuming sizeof(long) >= 4). + */ + v = frexp(v, &expo); + v *= 2147483648.0; /* 2**31 */ + hipart = (long)v; /* take the top 32 bits */ + v = (v - (double)hipart) * 2147483648.0; /* get the next 32 bits */ + x = hipart + (long)v + (expo << 15); + if (x == -1) + x = -2; + return x; } long _Py_HashPointer(void *p) { - long x; - size_t y = (size_t)p; - /* bottom 3 or 4 bits are likely to be 0; rotate y by 4 to avoid - excessive hash collisions for dicts and sets */ - y = (y >> 4) | (y << (8 * SIZEOF_VOID_P - 4)); - x = (long)y; - if (x == -1) - x = -2; - return x; + long x; + size_t y = (size_t)p; + /* bottom 3 or 4 bits are likely to be 0; rotate y by 4 to avoid + excessive hash collisions for dicts and sets */ + y = (y >> 4) | (y << (8 * SIZEOF_VOID_P - 4)); + x = (long)y; + if (x == -1) + x = -2; + return x; } long PyObject_HashNotImplemented(PyObject *v) { - PyErr_Format(PyExc_TypeError, "unhashable type: '%.200s'", - Py_TYPE(v)->tp_name); - return -1; + PyErr_Format(PyExc_TypeError, "unhashable type: '%.200s'", + Py_TYPE(v)->tp_name); + return -1; } long PyObject_Hash(PyObject *v) { - PyTypeObject *tp = Py_TYPE(v); - if (tp->tp_hash != NULL) - return (*tp->tp_hash)(v); - /* To keep to the general practice that inheriting - * solely from object in C code should work without - * an explicit call to PyType_Ready, we implicitly call - * PyType_Ready here and then check the tp_hash slot again - */ - if (tp->tp_dict == NULL) { - if (PyType_Ready(tp) < 0) - return -1; - if (tp->tp_hash != NULL) - return (*tp->tp_hash)(v); - } - /* Otherwise, the object can't be hashed */ - return PyObject_HashNotImplemented(v); + PyTypeObject *tp = Py_TYPE(v); + if (tp->tp_hash != NULL) + return (*tp->tp_hash)(v); + /* To keep to the general practice that inheriting + * solely from object in C code should work without + * an explicit call to PyType_Ready, we implicitly call + * PyType_Ready here and then check the tp_hash slot again + */ + if (tp->tp_dict == NULL) { + if (PyType_Ready(tp) < 0) + return -1; + if (tp->tp_hash != NULL) + return (*tp->tp_hash)(v); + } + /* Otherwise, the object can't be hashed */ + return PyObject_HashNotImplemented(v); } PyObject * PyObject_GetAttrString(PyObject *v, const char *name) { - PyObject *w, *res; + PyObject *w, *res; - if (Py_TYPE(v)->tp_getattr != NULL) - return (*Py_TYPE(v)->tp_getattr)(v, (char*)name); - w = PyUnicode_InternFromString(name); - if (w == NULL) - return NULL; - res = PyObject_GetAttr(v, w); - Py_XDECREF(w); - return res; + if (Py_TYPE(v)->tp_getattr != NULL) + return (*Py_TYPE(v)->tp_getattr)(v, (char*)name); + w = PyUnicode_InternFromString(name); + if (w == NULL) + return NULL; + res = PyObject_GetAttr(v, w); + Py_XDECREF(w); + return res; } int PyObject_HasAttrString(PyObject *v, const char *name) { - PyObject *res = PyObject_GetAttrString(v, name); - if (res != NULL) { - Py_DECREF(res); - return 1; - } - PyErr_Clear(); - return 0; + PyObject *res = PyObject_GetAttrString(v, name); + if (res != NULL) { + Py_DECREF(res); + return 1; + } + PyErr_Clear(); + return 0; } int PyObject_SetAttrString(PyObject *v, const char *name, PyObject *w) { - PyObject *s; - int res; + PyObject *s; + int res; - if (Py_TYPE(v)->tp_setattr != NULL) - return (*Py_TYPE(v)->tp_setattr)(v, (char*)name, w); - s = PyUnicode_InternFromString(name); - if (s == NULL) - return -1; - res = PyObject_SetAttr(v, s, w); - Py_XDECREF(s); - return res; + if (Py_TYPE(v)->tp_setattr != NULL) + return (*Py_TYPE(v)->tp_setattr)(v, (char*)name, w); + s = PyUnicode_InternFromString(name); + if (s == NULL) + return -1; + res = PyObject_SetAttr(v, s, w); + Py_XDECREF(s); + return res; } PyObject * PyObject_GetAttr(PyObject *v, PyObject *name) { - PyTypeObject *tp = Py_TYPE(v); + PyTypeObject *tp = Py_TYPE(v); - if (!PyUnicode_Check(name)) { - PyErr_Format(PyExc_TypeError, - "attribute name must be string, not '%.200s'", - name->ob_type->tp_name); - return NULL; - } - if (tp->tp_getattro != NULL) - return (*tp->tp_getattro)(v, name); - if (tp->tp_getattr != NULL) { - char *name_str = _PyUnicode_AsString(name); - if (name_str == NULL) - return NULL; - return (*tp->tp_getattr)(v, name_str); - } - PyErr_Format(PyExc_AttributeError, - "'%.50s' object has no attribute '%U'", - tp->tp_name, name); - return NULL; + if (!PyUnicode_Check(name)) { + PyErr_Format(PyExc_TypeError, + "attribute name must be string, not '%.200s'", + name->ob_type->tp_name); + return NULL; + } + if (tp->tp_getattro != NULL) + return (*tp->tp_getattro)(v, name); + if (tp->tp_getattr != NULL) { + char *name_str = _PyUnicode_AsString(name); + if (name_str == NULL) + return NULL; + return (*tp->tp_getattr)(v, name_str); + } + PyErr_Format(PyExc_AttributeError, + "'%.50s' object has no attribute '%U'", + tp->tp_name, name); + return NULL; } int PyObject_HasAttr(PyObject *v, PyObject *name) { - PyObject *res = PyObject_GetAttr(v, name); - if (res != NULL) { - Py_DECREF(res); - return 1; - } - PyErr_Clear(); - return 0; + PyObject *res = PyObject_GetAttr(v, name); + if (res != NULL) { + Py_DECREF(res); + return 1; + } + PyErr_Clear(); + return 0; } int PyObject_SetAttr(PyObject *v, PyObject *name, PyObject *value) { - PyTypeObject *tp = Py_TYPE(v); - int err; + PyTypeObject *tp = Py_TYPE(v); + int err; - if (!PyUnicode_Check(name)) { - PyErr_Format(PyExc_TypeError, - "attribute name must be string, not '%.200s'", - name->ob_type->tp_name); - return -1; - } - Py_INCREF(name); - - PyUnicode_InternInPlace(&name); - if (tp->tp_setattro != NULL) { - err = (*tp->tp_setattro)(v, name, value); - Py_DECREF(name); - return err; - } - if (tp->tp_setattr != NULL) { - char *name_str = _PyUnicode_AsString(name); - if (name_str == NULL) - return -1; - err = (*tp->tp_setattr)(v, name_str, value); - Py_DECREF(name); - return err; - } - Py_DECREF(name); - assert(name->ob_refcnt >= 1); - if (tp->tp_getattr == NULL && tp->tp_getattro == NULL) - PyErr_Format(PyExc_TypeError, - "'%.100s' object has no attributes " - "(%s .%U)", - tp->tp_name, - value==NULL ? "del" : "assign to", - name); - else - PyErr_Format(PyExc_TypeError, - "'%.100s' object has only read-only attributes " - "(%s .%U)", - tp->tp_name, - value==NULL ? "del" : "assign to", - name); - return -1; + if (!PyUnicode_Check(name)) { + PyErr_Format(PyExc_TypeError, + "attribute name must be string, not '%.200s'", + name->ob_type->tp_name); + return -1; + } + Py_INCREF(name); + + PyUnicode_InternInPlace(&name); + if (tp->tp_setattro != NULL) { + err = (*tp->tp_setattro)(v, name, value); + Py_DECREF(name); + return err; + } + if (tp->tp_setattr != NULL) { + char *name_str = _PyUnicode_AsString(name); + if (name_str == NULL) + return -1; + err = (*tp->tp_setattr)(v, name_str, value); + Py_DECREF(name); + return err; + } + Py_DECREF(name); + assert(name->ob_refcnt >= 1); + if (tp->tp_getattr == NULL && tp->tp_getattro == NULL) + PyErr_Format(PyExc_TypeError, + "'%.100s' object has no attributes " + "(%s .%U)", + tp->tp_name, + value==NULL ? "del" : "assign to", + name); + else + PyErr_Format(PyExc_TypeError, + "'%.100s' object has only read-only attributes " + "(%s .%U)", + tp->tp_name, + value==NULL ? "del" : "assign to", + name); + return -1; } /* Helper to get a pointer to an object's __dict__ slot, if any */ @@ -878,33 +878,33 @@ PyObject ** _PyObject_GetDictPtr(PyObject *obj) { - Py_ssize_t dictoffset; - PyTypeObject *tp = Py_TYPE(obj); + Py_ssize_t dictoffset; + PyTypeObject *tp = Py_TYPE(obj); - dictoffset = tp->tp_dictoffset; - if (dictoffset == 0) - return NULL; - if (dictoffset < 0) { - Py_ssize_t tsize; - size_t size; - - tsize = ((PyVarObject *)obj)->ob_size; - if (tsize < 0) - tsize = -tsize; - size = _PyObject_VAR_SIZE(tp, tsize); - - dictoffset += (long)size; - assert(dictoffset > 0); - assert(dictoffset % SIZEOF_VOID_P == 0); - } - return (PyObject **) ((char *)obj + dictoffset); + dictoffset = tp->tp_dictoffset; + if (dictoffset == 0) + return NULL; + if (dictoffset < 0) { + Py_ssize_t tsize; + size_t size; + + tsize = ((PyVarObject *)obj)->ob_size; + if (tsize < 0) + tsize = -tsize; + size = _PyObject_VAR_SIZE(tp, tsize); + + dictoffset += (long)size; + assert(dictoffset > 0); + assert(dictoffset % SIZEOF_VOID_P == 0); + } + return (PyObject **) ((char *)obj + dictoffset); } PyObject * PyObject_SelfIter(PyObject *obj) { - Py_INCREF(obj); - return obj; + Py_INCREF(obj); + return obj; } /* Helper used when the __next__ method is removed from a type: @@ -915,10 +915,10 @@ PyObject * _PyObject_NextNotImplemented(PyObject *self) { - PyErr_Format(PyExc_TypeError, - "'%.200s' object is not iterable", - Py_TYPE(self)->tp_name); - return NULL; + PyErr_Format(PyExc_TypeError, + "'%.200s' object is not iterable", + Py_TYPE(self)->tp_name); + return NULL; } /* Generic GetAttr functions - put these in your tp_[gs]etattro slot */ @@ -926,189 +926,189 @@ PyObject * PyObject_GenericGetAttr(PyObject *obj, PyObject *name) { - PyTypeObject *tp = Py_TYPE(obj); - PyObject *descr = NULL; - PyObject *res = NULL; - descrgetfunc f; - Py_ssize_t dictoffset; - PyObject **dictptr; - - if (!PyUnicode_Check(name)){ - PyErr_Format(PyExc_TypeError, - "attribute name must be string, not '%.200s'", - name->ob_type->tp_name); - return NULL; - } - else - Py_INCREF(name); - - if (tp->tp_dict == NULL) { - if (PyType_Ready(tp) < 0) - goto done; - } + PyTypeObject *tp = Py_TYPE(obj); + PyObject *descr = NULL; + PyObject *res = NULL; + descrgetfunc f; + Py_ssize_t dictoffset; + PyObject **dictptr; + + if (!PyUnicode_Check(name)){ + PyErr_Format(PyExc_TypeError, + "attribute name must be string, not '%.200s'", + name->ob_type->tp_name); + return NULL; + } + else + Py_INCREF(name); + + if (tp->tp_dict == NULL) { + if (PyType_Ready(tp) < 0) + goto done; + } #if 0 /* XXX this is not quite _PyType_Lookup anymore */ - /* Inline _PyType_Lookup */ - { - Py_ssize_t i, n; - PyObject *mro, *base, *dict; - - /* Look in tp_dict of types in MRO */ - mro = tp->tp_mro; - assert(mro != NULL); - assert(PyTuple_Check(mro)); - n = PyTuple_GET_SIZE(mro); - for (i = 0; i < n; i++) { - base = PyTuple_GET_ITEM(mro, i); - assert(PyType_Check(base)); - dict = ((PyTypeObject *)base)->tp_dict; - assert(dict && PyDict_Check(dict)); - descr = PyDict_GetItem(dict, name); - if (descr != NULL) - break; - } - } + /* Inline _PyType_Lookup */ + { + Py_ssize_t i, n; + PyObject *mro, *base, *dict; + + /* Look in tp_dict of types in MRO */ + mro = tp->tp_mro; + assert(mro != NULL); + assert(PyTuple_Check(mro)); + n = PyTuple_GET_SIZE(mro); + for (i = 0; i < n; i++) { + base = PyTuple_GET_ITEM(mro, i); + assert(PyType_Check(base)); + dict = ((PyTypeObject *)base)->tp_dict; + assert(dict && PyDict_Check(dict)); + descr = PyDict_GetItem(dict, name); + if (descr != NULL) + break; + } + } #else - descr = _PyType_Lookup(tp, name); + descr = _PyType_Lookup(tp, name); #endif - Py_XINCREF(descr); + Py_XINCREF(descr); + + f = NULL; + if (descr != NULL) { + f = descr->ob_type->tp_descr_get; + if (f != NULL && PyDescr_IsData(descr)) { + res = f(descr, obj, (PyObject *)obj->ob_type); + Py_DECREF(descr); + goto done; + } + } - f = NULL; - if (descr != NULL) { - f = descr->ob_type->tp_descr_get; - if (f != NULL && PyDescr_IsData(descr)) { - res = f(descr, obj, (PyObject *)obj->ob_type); - Py_DECREF(descr); - goto done; - } - } - - /* Inline _PyObject_GetDictPtr */ - dictoffset = tp->tp_dictoffset; - if (dictoffset != 0) { - PyObject *dict; - if (dictoffset < 0) { - Py_ssize_t tsize; - size_t size; - - tsize = ((PyVarObject *)obj)->ob_size; - if (tsize < 0) - tsize = -tsize; - size = _PyObject_VAR_SIZE(tp, tsize); - - dictoffset += (long)size; - assert(dictoffset > 0); - assert(dictoffset % SIZEOF_VOID_P == 0); - } - dictptr = (PyObject **) ((char *)obj + dictoffset); - dict = *dictptr; - if (dict != NULL) { - Py_INCREF(dict); - res = PyDict_GetItem(dict, name); - if (res != NULL) { - Py_INCREF(res); - Py_XDECREF(descr); - Py_DECREF(dict); - goto done; - } - Py_DECREF(dict); - } - } - - if (f != NULL) { - res = f(descr, obj, (PyObject *)Py_TYPE(obj)); - Py_DECREF(descr); - goto done; - } - - if (descr != NULL) { - res = descr; - /* descr was already increfed above */ - goto done; - } - - PyErr_Format(PyExc_AttributeError, - "'%.50s' object has no attribute '%U'", - tp->tp_name, name); + /* Inline _PyObject_GetDictPtr */ + dictoffset = tp->tp_dictoffset; + if (dictoffset != 0) { + PyObject *dict; + if (dictoffset < 0) { + Py_ssize_t tsize; + size_t size; + + tsize = ((PyVarObject *)obj)->ob_size; + if (tsize < 0) + tsize = -tsize; + size = _PyObject_VAR_SIZE(tp, tsize); + + dictoffset += (long)size; + assert(dictoffset > 0); + assert(dictoffset % SIZEOF_VOID_P == 0); + } + dictptr = (PyObject **) ((char *)obj + dictoffset); + dict = *dictptr; + if (dict != NULL) { + Py_INCREF(dict); + res = PyDict_GetItem(dict, name); + if (res != NULL) { + Py_INCREF(res); + Py_XDECREF(descr); + Py_DECREF(dict); + goto done; + } + Py_DECREF(dict); + } + } + + if (f != NULL) { + res = f(descr, obj, (PyObject *)Py_TYPE(obj)); + Py_DECREF(descr); + goto done; + } + + if (descr != NULL) { + res = descr; + /* descr was already increfed above */ + goto done; + } + + PyErr_Format(PyExc_AttributeError, + "'%.50s' object has no attribute '%U'", + tp->tp_name, name); done: - Py_DECREF(name); - return res; + Py_DECREF(name); + return res; } int PyObject_GenericSetAttr(PyObject *obj, PyObject *name, PyObject *value) { - PyTypeObject *tp = Py_TYPE(obj); - PyObject *descr; - descrsetfunc f; - PyObject **dictptr; - int res = -1; - - if (!PyUnicode_Check(name)){ - PyErr_Format(PyExc_TypeError, - "attribute name must be string, not '%.200s'", - name->ob_type->tp_name); - return -1; - } - else - Py_INCREF(name); - - if (tp->tp_dict == NULL) { - if (PyType_Ready(tp) < 0) - goto done; - } - - descr = _PyType_Lookup(tp, name); - f = NULL; - if (descr != NULL) { - f = descr->ob_type->tp_descr_set; - if (f != NULL && PyDescr_IsData(descr)) { - res = f(descr, obj, value); - goto done; - } - } - - dictptr = _PyObject_GetDictPtr(obj); - if (dictptr != NULL) { - PyObject *dict = *dictptr; - if (dict == NULL && value != NULL) { - dict = PyDict_New(); - if (dict == NULL) - goto done; - *dictptr = dict; - } - if (dict != NULL) { - Py_INCREF(dict); - if (value == NULL) - res = PyDict_DelItem(dict, name); - else - res = PyDict_SetItem(dict, name, value); - if (res < 0 && PyErr_ExceptionMatches(PyExc_KeyError)) - PyErr_SetObject(PyExc_AttributeError, name); - Py_DECREF(dict); - goto done; - } - } - - if (f != NULL) { - res = f(descr, obj, value); - goto done; - } - - if (descr == NULL) { - PyErr_Format(PyExc_AttributeError, - "'%.100s' object has no attribute '%U'", - tp->tp_name, name); - goto done; - } - - PyErr_Format(PyExc_AttributeError, - "'%.50s' object attribute '%U' is read-only", - tp->tp_name, name); + PyTypeObject *tp = Py_TYPE(obj); + PyObject *descr; + descrsetfunc f; + PyObject **dictptr; + int res = -1; + + if (!PyUnicode_Check(name)){ + PyErr_Format(PyExc_TypeError, + "attribute name must be string, not '%.200s'", + name->ob_type->tp_name); + return -1; + } + else + Py_INCREF(name); + + if (tp->tp_dict == NULL) { + if (PyType_Ready(tp) < 0) + goto done; + } + + descr = _PyType_Lookup(tp, name); + f = NULL; + if (descr != NULL) { + f = descr->ob_type->tp_descr_set; + if (f != NULL && PyDescr_IsData(descr)) { + res = f(descr, obj, value); + goto done; + } + } + + dictptr = _PyObject_GetDictPtr(obj); + if (dictptr != NULL) { + PyObject *dict = *dictptr; + if (dict == NULL && value != NULL) { + dict = PyDict_New(); + if (dict == NULL) + goto done; + *dictptr = dict; + } + if (dict != NULL) { + Py_INCREF(dict); + if (value == NULL) + res = PyDict_DelItem(dict, name); + else + res = PyDict_SetItem(dict, name, value); + if (res < 0 && PyErr_ExceptionMatches(PyExc_KeyError)) + PyErr_SetObject(PyExc_AttributeError, name); + Py_DECREF(dict); + goto done; + } + } + + if (f != NULL) { + res = f(descr, obj, value); + goto done; + } + + if (descr == NULL) { + PyErr_Format(PyExc_AttributeError, + "'%.100s' object has no attribute '%U'", + tp->tp_name, name); + goto done; + } + + PyErr_Format(PyExc_AttributeError, + "'%.50s' object attribute '%U' is read-only", + tp->tp_name, name); done: - Py_DECREF(name); - return res; + Py_DECREF(name); + return res; } /* Test a value used as condition, e.g., in a for or if statement. @@ -1117,26 +1117,26 @@ int PyObject_IsTrue(PyObject *v) { - Py_ssize_t res; - if (v == Py_True) - return 1; - if (v == Py_False) - return 0; - if (v == Py_None) - return 0; - else if (v->ob_type->tp_as_number != NULL && - v->ob_type->tp_as_number->nb_bool != NULL) - res = (*v->ob_type->tp_as_number->nb_bool)(v); - else if (v->ob_type->tp_as_mapping != NULL && - v->ob_type->tp_as_mapping->mp_length != NULL) - res = (*v->ob_type->tp_as_mapping->mp_length)(v); - else if (v->ob_type->tp_as_sequence != NULL && - v->ob_type->tp_as_sequence->sq_length != NULL) - res = (*v->ob_type->tp_as_sequence->sq_length)(v); - else - return 1; - /* if it is negative, it should be either -1 or -2 */ - return (res > 0) ? 1 : Py_SAFE_DOWNCAST(res, Py_ssize_t, int); + Py_ssize_t res; + if (v == Py_True) + return 1; + if (v == Py_False) + return 0; + if (v == Py_None) + return 0; + else if (v->ob_type->tp_as_number != NULL && + v->ob_type->tp_as_number->nb_bool != NULL) + res = (*v->ob_type->tp_as_number->nb_bool)(v); + else if (v->ob_type->tp_as_mapping != NULL && + v->ob_type->tp_as_mapping->mp_length != NULL) + res = (*v->ob_type->tp_as_mapping->mp_length)(v); + else if (v->ob_type->tp_as_sequence != NULL && + v->ob_type->tp_as_sequence->sq_length != NULL) + res = (*v->ob_type->tp_as_sequence->sq_length)(v); + else + return 1; + /* if it is negative, it should be either -1 or -2 */ + return (res > 0) ? 1 : Py_SAFE_DOWNCAST(res, Py_ssize_t, int); } /* equivalent of 'not v' @@ -1145,11 +1145,11 @@ int PyObject_Not(PyObject *v) { - int res; - res = PyObject_IsTrue(v); - if (res < 0) - return res; - return res == 0; + int res; + res = PyObject_IsTrue(v); + if (res < 0) + return res; + return res == 0; } /* Test whether an object can be called */ @@ -1157,9 +1157,9 @@ int PyCallable_Check(PyObject *x) { - if (x == NULL) - return 0; - return x->ob_type->tp_call != NULL; + if (x == NULL) + return 0; + return x->ob_type->tp_call != NULL; } /* ------------------------- PyObject_Dir() helpers ------------------------- */ @@ -1175,78 +1175,78 @@ static int merge_class_dict(PyObject* dict, PyObject* aclass) { - PyObject *classdict; - PyObject *bases; + PyObject *classdict; + PyObject *bases; - assert(PyDict_Check(dict)); - assert(aclass); + assert(PyDict_Check(dict)); + assert(aclass); - /* Merge in the type's dict (if any). */ - classdict = PyObject_GetAttrString(aclass, "__dict__"); - if (classdict == NULL) - PyErr_Clear(); - else { - int status = PyDict_Update(dict, classdict); - Py_DECREF(classdict); - if (status < 0) - return -1; - } - - /* Recursively merge in the base types' (if any) dicts. */ - bases = PyObject_GetAttrString(aclass, "__bases__"); - if (bases == NULL) - PyErr_Clear(); - else { - /* We have no guarantee that bases is a real tuple */ - Py_ssize_t i, n; - n = PySequence_Size(bases); /* This better be right */ - if (n < 0) - PyErr_Clear(); - else { - for (i = 0; i < n; i++) { - int status; - PyObject *base = PySequence_GetItem(bases, i); - if (base == NULL) { - Py_DECREF(bases); - return -1; - } - status = merge_class_dict(dict, base); - Py_DECREF(base); - if (status < 0) { - Py_DECREF(bases); - return -1; - } - } - } - Py_DECREF(bases); - } - return 0; + /* Merge in the type's dict (if any). */ + classdict = PyObject_GetAttrString(aclass, "__dict__"); + if (classdict == NULL) + PyErr_Clear(); + else { + int status = PyDict_Update(dict, classdict); + Py_DECREF(classdict); + if (status < 0) + return -1; + } + + /* Recursively merge in the base types' (if any) dicts. */ + bases = PyObject_GetAttrString(aclass, "__bases__"); + if (bases == NULL) + PyErr_Clear(); + else { + /* We have no guarantee that bases is a real tuple */ + Py_ssize_t i, n; + n = PySequence_Size(bases); /* This better be right */ + if (n < 0) + PyErr_Clear(); + else { + for (i = 0; i < n; i++) { + int status; + PyObject *base = PySequence_GetItem(bases, i); + if (base == NULL) { + Py_DECREF(bases); + return -1; + } + status = merge_class_dict(dict, base); + Py_DECREF(base); + if (status < 0) { + Py_DECREF(bases); + return -1; + } + } + } + Py_DECREF(bases); + } + return 0; } /* Helper for PyObject_Dir without arguments: returns the local scope. */ static PyObject * _dir_locals(void) { - PyObject *names; - PyObject *locals = PyEval_GetLocals(); + PyObject *names; + PyObject *locals = PyEval_GetLocals(); - if (locals == NULL) { - PyErr_SetString(PyExc_SystemError, "frame does not exist"); - return NULL; - } - - names = PyMapping_Keys(locals); - if (!names) - return NULL; - if (!PyList_Check(names)) { - PyErr_Format(PyExc_TypeError, - "dir(): expected keys() of locals to be a list, " - "not '%.200s'", Py_TYPE(names)->tp_name); - Py_DECREF(names); - return NULL; - } - /* the locals don't need to be DECREF'd */ - return names; + if (locals == NULL) { + PyErr_SetString(PyExc_SystemError, "frame does not exist"); + return NULL; + } + + names = PyMapping_Keys(locals); + if (!names) + return NULL; + if (!PyList_Check(names)) { + PyErr_Format(PyExc_TypeError, + "dir(): expected keys() of locals to be a list, " + "not '%.200s'", Py_TYPE(names)->tp_name); + Py_DECREF(names); + return NULL; + } + /* the locals don't need to be DECREF'd */ + return names; } /* Helper for PyObject_Dir of type objects: returns __dict__ and __bases__. @@ -1256,37 +1256,37 @@ static PyObject * _specialized_dir_type(PyObject *obj) { - PyObject *result = NULL; - PyObject *dict = PyDict_New(); + PyObject *result = NULL; + PyObject *dict = PyDict_New(); - if (dict != NULL && merge_class_dict(dict, obj) == 0) - result = PyDict_Keys(dict); + if (dict != NULL && merge_class_dict(dict, obj) == 0) + result = PyDict_Keys(dict); - Py_XDECREF(dict); - return result; + Py_XDECREF(dict); + return result; } /* Helper for PyObject_Dir of module objects: returns the module's __dict__. */ static PyObject * _specialized_dir_module(PyObject *obj) { - PyObject *result = NULL; - PyObject *dict = PyObject_GetAttrString(obj, "__dict__"); + PyObject *result = NULL; + PyObject *dict = PyObject_GetAttrString(obj, "__dict__"); - if (dict != NULL) { - if (PyDict_Check(dict)) - result = PyDict_Keys(dict); - else { - const char *name = PyModule_GetName(obj); - if (name) - PyErr_Format(PyExc_TypeError, - "%.200s.__dict__ is not a dictionary", - name); - } - } + if (dict != NULL) { + if (PyDict_Check(dict)) + result = PyDict_Keys(dict); + else { + const char *name = PyModule_GetName(obj); + if (name) + PyErr_Format(PyExc_TypeError, + "%.200s.__dict__ is not a dictionary", + name); + } + } - Py_XDECREF(dict); - return result; + Py_XDECREF(dict); + return result; } /* Helper for PyObject_Dir of generic objects: returns __dict__, __class__, @@ -1295,47 +1295,47 @@ static PyObject * _generic_dir(PyObject *obj) { - PyObject *result = NULL; - PyObject *dict = NULL; - PyObject *itsclass = NULL; - - /* Get __dict__ (which may or may not be a real dict...) */ - dict = PyObject_GetAttrString(obj, "__dict__"); - if (dict == NULL) { - PyErr_Clear(); - dict = PyDict_New(); - } - else if (!PyDict_Check(dict)) { - Py_DECREF(dict); - dict = PyDict_New(); - } - else { - /* Copy __dict__ to avoid mutating it. */ - PyObject *temp = PyDict_Copy(dict); - Py_DECREF(dict); - dict = temp; - } - - if (dict == NULL) - goto error; - - /* Merge in attrs reachable from its class. */ - itsclass = PyObject_GetAttrString(obj, "__class__"); - if (itsclass == NULL) - /* XXX(tomer): Perhaps fall back to obj->ob_type if no - __class__ exists? */ - PyErr_Clear(); - else { - if (merge_class_dict(dict, itsclass) != 0) - goto error; - } + PyObject *result = NULL; + PyObject *dict = NULL; + PyObject *itsclass = NULL; + + /* Get __dict__ (which may or may not be a real dict...) */ + dict = PyObject_GetAttrString(obj, "__dict__"); + if (dict == NULL) { + PyErr_Clear(); + dict = PyDict_New(); + } + else if (!PyDict_Check(dict)) { + Py_DECREF(dict); + dict = PyDict_New(); + } + else { + /* Copy __dict__ to avoid mutating it. */ + PyObject *temp = PyDict_Copy(dict); + Py_DECREF(dict); + dict = temp; + } + + if (dict == NULL) + goto error; + + /* Merge in attrs reachable from its class. */ + itsclass = PyObject_GetAttrString(obj, "__class__"); + if (itsclass == NULL) + /* XXX(tomer): Perhaps fall back to obj->ob_type if no + __class__ exists? */ + PyErr_Clear(); + else { + if (merge_class_dict(dict, itsclass) != 0) + goto error; + } - result = PyDict_Keys(dict); - /* fall through */ + result = PyDict_Keys(dict); + /* fall through */ error: - Py_XDECREF(itsclass); - Py_XDECREF(dict); - return result; + Py_XDECREF(itsclass); + Py_XDECREF(dict); + return result; } /* Helper for PyObject_Dir: object introspection. @@ -1344,40 +1344,40 @@ static PyObject * _dir_object(PyObject *obj) { - PyObject * result = NULL; - PyObject * dirfunc = PyObject_GetAttrString((PyObject*)obj->ob_type, - "__dir__"); - - assert(obj); - if (dirfunc == NULL) { - /* use default implementation */ - PyErr_Clear(); - if (PyModule_Check(obj)) - result = _specialized_dir_module(obj); - else if (PyType_Check(obj)) - result = _specialized_dir_type(obj); - else - result = _generic_dir(obj); - } - else { - /* use __dir__ */ - result = PyObject_CallFunctionObjArgs(dirfunc, obj, NULL); - Py_DECREF(dirfunc); - if (result == NULL) - return NULL; - - /* result must be a list */ - /* XXX(gbrandl): could also check if all items are strings */ - if (!PyList_Check(result)) { - PyErr_Format(PyExc_TypeError, - "__dir__() must return a list, not %.200s", - Py_TYPE(result)->tp_name); - Py_DECREF(result); - result = NULL; - } - } + PyObject * result = NULL; + PyObject * dirfunc = PyObject_GetAttrString((PyObject*)obj->ob_type, + "__dir__"); + + assert(obj); + if (dirfunc == NULL) { + /* use default implementation */ + PyErr_Clear(); + if (PyModule_Check(obj)) + result = _specialized_dir_module(obj); + else if (PyType_Check(obj)) + result = _specialized_dir_type(obj); + else + result = _generic_dir(obj); + } + else { + /* use __dir__ */ + result = PyObject_CallFunctionObjArgs(dirfunc, obj, NULL); + Py_DECREF(dirfunc); + if (result == NULL) + return NULL; + + /* result must be a list */ + /* XXX(gbrandl): could also check if all items are strings */ + if (!PyList_Check(result)) { + PyErr_Format(PyExc_TypeError, + "__dir__() must return a list, not %.200s", + Py_TYPE(result)->tp_name); + Py_DECREF(result); + result = NULL; + } + } - return result; + return result; } /* Implementation of dir() -- if obj is NULL, returns the names in the current @@ -1387,24 +1387,24 @@ PyObject * PyObject_Dir(PyObject *obj) { - PyObject * result; + PyObject * result; - if (obj == NULL) - /* no object -- introspect the locals */ - result = _dir_locals(); - else - /* object -- introspect the object */ - result = _dir_object(obj); - - assert(result == NULL || PyList_Check(result)); - - if (result != NULL && PyList_Sort(result) != 0) { - /* sorting the list failed */ - Py_DECREF(result); - result = NULL; - } + if (obj == NULL) + /* no object -- introspect the locals */ + result = _dir_locals(); + else + /* object -- introspect the object */ + result = _dir_object(obj); + + assert(result == NULL || PyList_Check(result)); + + if (result != NULL && PyList_Sort(result) != 0) { + /* sorting the list failed */ + Py_DECREF(result); + result = NULL; + } - return result; + return result; } /* @@ -1418,35 +1418,35 @@ static PyObject * none_repr(PyObject *op) { - return PyUnicode_FromString("None"); + return PyUnicode_FromString("None"); } /* ARGUSED */ static void none_dealloc(PyObject* ignore) { - /* This should never get called, but we also don't want to SEGV if - * we accidentally decref None out of existence. - */ - Py_FatalError("deallocating None"); + /* This should never get called, but we also don't want to SEGV if + * we accidentally decref None out of existence. + */ + Py_FatalError("deallocating None"); } static PyTypeObject PyNone_Type = { - PyVarObject_HEAD_INIT(&PyType_Type, 0) - "NoneType", - 0, - 0, - none_dealloc, /*tp_dealloc*/ /*never called*/ - 0, /*tp_print*/ - 0, /*tp_getattr*/ - 0, /*tp_setattr*/ - 0, /*tp_reserved*/ - none_repr, /*tp_repr*/ - 0, /*tp_as_number*/ - 0, /*tp_as_sequence*/ - 0, /*tp_as_mapping*/ - 0, /*tp_hash */ + PyVarObject_HEAD_INIT(&PyType_Type, 0) + "NoneType", + 0, + 0, + none_dealloc, /*tp_dealloc*/ /*never called*/ + 0, /*tp_print*/ + 0, /*tp_getattr*/ + 0, /*tp_setattr*/ + 0, /*tp_reserved*/ + none_repr, /*tp_repr*/ + 0, /*tp_as_number*/ + 0, /*tp_as_sequence*/ + 0, /*tp_as_mapping*/ + 0, /*tp_hash */ }; PyObject _Py_NoneStruct = { @@ -1460,165 +1460,165 @@ static PyObject * NotImplemented_repr(PyObject *op) { - return PyUnicode_FromString("NotImplemented"); + return PyUnicode_FromString("NotImplemented"); } static PyTypeObject PyNotImplemented_Type = { - PyVarObject_HEAD_INIT(&PyType_Type, 0) - "NotImplementedType", - 0, - 0, - none_dealloc, /*tp_dealloc*/ /*never called*/ - 0, /*tp_print*/ - 0, /*tp_getattr*/ - 0, /*tp_setattr*/ - 0, /*tp_reserved*/ - NotImplemented_repr, /*tp_repr*/ - 0, /*tp_as_number*/ - 0, /*tp_as_sequence*/ - 0, /*tp_as_mapping*/ - 0, /*tp_hash */ + PyVarObject_HEAD_INIT(&PyType_Type, 0) + "NotImplementedType", + 0, + 0, + none_dealloc, /*tp_dealloc*/ /*never called*/ + 0, /*tp_print*/ + 0, /*tp_getattr*/ + 0, /*tp_setattr*/ + 0, /*tp_reserved*/ + NotImplemented_repr, /*tp_repr*/ + 0, /*tp_as_number*/ + 0, /*tp_as_sequence*/ + 0, /*tp_as_mapping*/ + 0, /*tp_hash */ }; PyObject _Py_NotImplementedStruct = { - _PyObject_EXTRA_INIT - 1, &PyNotImplemented_Type + _PyObject_EXTRA_INIT + 1, &PyNotImplemented_Type }; void _Py_ReadyTypes(void) { - if (PyType_Ready(&PyType_Type) < 0) - Py_FatalError("Can't initialize type type"); + if (PyType_Ready(&PyType_Type) < 0) + Py_FatalError("Can't initialize type type"); - if (PyType_Ready(&_PyWeakref_RefType) < 0) - Py_FatalError("Can't initialize weakref type"); + if (PyType_Ready(&_PyWeakref_RefType) < 0) + Py_FatalError("Can't initialize weakref type"); - if (PyType_Ready(&_PyWeakref_CallableProxyType) < 0) - Py_FatalError("Can't initialize callable weakref proxy type"); + if (PyType_Ready(&_PyWeakref_CallableProxyType) < 0) + Py_FatalError("Can't initialize callable weakref proxy type"); - if (PyType_Ready(&_PyWeakref_ProxyType) < 0) - Py_FatalError("Can't initialize weakref proxy type"); + if (PyType_Ready(&_PyWeakref_ProxyType) < 0) + Py_FatalError("Can't initialize weakref proxy type"); - if (PyType_Ready(&PyBool_Type) < 0) - Py_FatalError("Can't initialize bool type"); + if (PyType_Ready(&PyBool_Type) < 0) + Py_FatalError("Can't initialize bool type"); - if (PyType_Ready(&PyByteArray_Type) < 0) - Py_FatalError("Can't initialize bytearray type"); + if (PyType_Ready(&PyByteArray_Type) < 0) + Py_FatalError("Can't initialize bytearray type"); - if (PyType_Ready(&PyBytes_Type) < 0) - Py_FatalError("Can't initialize 'str'"); + if (PyType_Ready(&PyBytes_Type) < 0) + Py_FatalError("Can't initialize 'str'"); - if (PyType_Ready(&PyList_Type) < 0) - Py_FatalError("Can't initialize list type"); + if (PyType_Ready(&PyList_Type) < 0) + Py_FatalError("Can't initialize list type"); - if (PyType_Ready(&PyNone_Type) < 0) - Py_FatalError("Can't initialize None type"); + if (PyType_Ready(&PyNone_Type) < 0) + Py_FatalError("Can't initialize None type"); - if (PyType_Ready(Py_Ellipsis->ob_type) < 0) - Py_FatalError("Can't initialize type(Ellipsis)"); + if (PyType_Ready(Py_Ellipsis->ob_type) < 0) + Py_FatalError("Can't initialize type(Ellipsis)"); - if (PyType_Ready(&PyNotImplemented_Type) < 0) - Py_FatalError("Can't initialize NotImplemented type"); + if (PyType_Ready(&PyNotImplemented_Type) < 0) + Py_FatalError("Can't initialize NotImplemented type"); - if (PyType_Ready(&PyTraceBack_Type) < 0) - Py_FatalError("Can't initialize traceback type"); + if (PyType_Ready(&PyTraceBack_Type) < 0) + Py_FatalError("Can't initialize traceback type"); - if (PyType_Ready(&PySuper_Type) < 0) - Py_FatalError("Can't initialize super type"); + if (PyType_Ready(&PySuper_Type) < 0) + Py_FatalError("Can't initialize super type"); - if (PyType_Ready(&PyBaseObject_Type) < 0) - Py_FatalError("Can't initialize object type"); + if (PyType_Ready(&PyBaseObject_Type) < 0) + Py_FatalError("Can't initialize object type"); - if (PyType_Ready(&PyRange_Type) < 0) - Py_FatalError("Can't initialize range type"); + if (PyType_Ready(&PyRange_Type) < 0) + Py_FatalError("Can't initialize range type"); - if (PyType_Ready(&PyDict_Type) < 0) - Py_FatalError("Can't initialize dict type"); + if (PyType_Ready(&PyDict_Type) < 0) + Py_FatalError("Can't initialize dict type"); - if (PyType_Ready(&PySet_Type) < 0) - Py_FatalError("Can't initialize set type"); + if (PyType_Ready(&PySet_Type) < 0) + Py_FatalError("Can't initialize set type"); - if (PyType_Ready(&PyUnicode_Type) < 0) - Py_FatalError("Can't initialize str type"); + if (PyType_Ready(&PyUnicode_Type) < 0) + Py_FatalError("Can't initialize str type"); - if (PyType_Ready(&PySlice_Type) < 0) - Py_FatalError("Can't initialize slice type"); + if (PyType_Ready(&PySlice_Type) < 0) + Py_FatalError("Can't initialize slice type"); - if (PyType_Ready(&PyStaticMethod_Type) < 0) - Py_FatalError("Can't initialize static method type"); + if (PyType_Ready(&PyStaticMethod_Type) < 0) + Py_FatalError("Can't initialize static method type"); - if (PyType_Ready(&PyComplex_Type) < 0) - Py_FatalError("Can't initialize complex type"); + if (PyType_Ready(&PyComplex_Type) < 0) + Py_FatalError("Can't initialize complex type"); - if (PyType_Ready(&PyFloat_Type) < 0) - Py_FatalError("Can't initialize float type"); + if (PyType_Ready(&PyFloat_Type) < 0) + Py_FatalError("Can't initialize float type"); - if (PyType_Ready(&PyLong_Type) < 0) - Py_FatalError("Can't initialize int type"); + if (PyType_Ready(&PyLong_Type) < 0) + Py_FatalError("Can't initialize int type"); - if (PyType_Ready(&PyFrozenSet_Type) < 0) - Py_FatalError("Can't initialize frozenset type"); + if (PyType_Ready(&PyFrozenSet_Type) < 0) + Py_FatalError("Can't initialize frozenset type"); - if (PyType_Ready(&PyProperty_Type) < 0) - Py_FatalError("Can't initialize property type"); + if (PyType_Ready(&PyProperty_Type) < 0) + Py_FatalError("Can't initialize property type"); - if (PyType_Ready(&PyMemoryView_Type) < 0) - Py_FatalError("Can't initialize memoryview type"); + if (PyType_Ready(&PyMemoryView_Type) < 0) + Py_FatalError("Can't initialize memoryview type"); - if (PyType_Ready(&PyTuple_Type) < 0) - Py_FatalError("Can't initialize tuple type"); + if (PyType_Ready(&PyTuple_Type) < 0) + Py_FatalError("Can't initialize tuple type"); - if (PyType_Ready(&PyEnum_Type) < 0) - Py_FatalError("Can't initialize enumerate type"); + if (PyType_Ready(&PyEnum_Type) < 0) + Py_FatalError("Can't initialize enumerate type"); - if (PyType_Ready(&PyReversed_Type) < 0) - Py_FatalError("Can't initialize reversed type"); + if (PyType_Ready(&PyReversed_Type) < 0) + Py_FatalError("Can't initialize reversed type"); - if (PyType_Ready(&PyStdPrinter_Type) < 0) - Py_FatalError("Can't initialize StdPrinter"); + if (PyType_Ready(&PyStdPrinter_Type) < 0) + Py_FatalError("Can't initialize StdPrinter"); - if (PyType_Ready(&PyCode_Type) < 0) - Py_FatalError("Can't initialize code type"); + if (PyType_Ready(&PyCode_Type) < 0) + Py_FatalError("Can't initialize code type"); - if (PyType_Ready(&PyFrame_Type) < 0) - Py_FatalError("Can't initialize frame type"); + if (PyType_Ready(&PyFrame_Type) < 0) + Py_FatalError("Can't initialize frame type"); - if (PyType_Ready(&PyCFunction_Type) < 0) - Py_FatalError("Can't initialize builtin function type"); + if (PyType_Ready(&PyCFunction_Type) < 0) + Py_FatalError("Can't initialize builtin function type"); - if (PyType_Ready(&PyMethod_Type) < 0) - Py_FatalError("Can't initialize method type"); + if (PyType_Ready(&PyMethod_Type) < 0) + Py_FatalError("Can't initialize method type"); - if (PyType_Ready(&PyFunction_Type) < 0) - Py_FatalError("Can't initialize function type"); + if (PyType_Ready(&PyFunction_Type) < 0) + Py_FatalError("Can't initialize function type"); - if (PyType_Ready(&PyDictProxy_Type) < 0) - Py_FatalError("Can't initialize dict proxy type"); + if (PyType_Ready(&PyDictProxy_Type) < 0) + Py_FatalError("Can't initialize dict proxy type"); - if (PyType_Ready(&PyGen_Type) < 0) - Py_FatalError("Can't initialize generator type"); + if (PyType_Ready(&PyGen_Type) < 0) + Py_FatalError("Can't initialize generator type"); - if (PyType_Ready(&PyGetSetDescr_Type) < 0) - Py_FatalError("Can't initialize get-set descriptor type"); + if (PyType_Ready(&PyGetSetDescr_Type) < 0) + Py_FatalError("Can't initialize get-set descriptor type"); - if (PyType_Ready(&PyWrapperDescr_Type) < 0) - Py_FatalError("Can't initialize wrapper type"); + if (PyType_Ready(&PyWrapperDescr_Type) < 0) + Py_FatalError("Can't initialize wrapper type"); - if (PyType_Ready(&PyEllipsis_Type) < 0) - Py_FatalError("Can't initialize ellipsis type"); + if (PyType_Ready(&PyEllipsis_Type) < 0) + Py_FatalError("Can't initialize ellipsis type"); - if (PyType_Ready(&PyMemberDescr_Type) < 0) - Py_FatalError("Can't initialize member descriptor type"); + if (PyType_Ready(&PyMemberDescr_Type) < 0) + Py_FatalError("Can't initialize member descriptor type"); - if (PyType_Ready(&PyFilter_Type) < 0) - Py_FatalError("Can't initialize filter type"); + if (PyType_Ready(&PyFilter_Type) < 0) + Py_FatalError("Can't initialize filter type"); - if (PyType_Ready(&PyMap_Type) < 0) - Py_FatalError("Can't initialize map type"); + if (PyType_Ready(&PyMap_Type) < 0) + Py_FatalError("Can't initialize map type"); - if (PyType_Ready(&PyZip_Type) < 0) - Py_FatalError("Can't initialize zip type"); + if (PyType_Ready(&PyZip_Type) < 0) + Py_FatalError("Can't initialize zip type"); } @@ -1627,50 +1627,50 @@ void _Py_NewReference(PyObject *op) { - _Py_INC_REFTOTAL; - op->ob_refcnt = 1; - _Py_AddToAllObjects(op, 1); - _Py_INC_TPALLOCS(op); + _Py_INC_REFTOTAL; + op->ob_refcnt = 1; + _Py_AddToAllObjects(op, 1); + _Py_INC_TPALLOCS(op); } void _Py_ForgetReference(register PyObject *op) { #ifdef SLOW_UNREF_CHECK - register PyObject *p; + register PyObject *p; #endif - if (op->ob_refcnt < 0) - Py_FatalError("UNREF negative refcnt"); - if (op == &refchain || - op->_ob_prev->_ob_next != op || op->_ob_next->_ob_prev != op) { - fprintf(stderr, "* ob\n"); - _PyObject_Dump(op); - fprintf(stderr, "* op->_ob_prev->_ob_next\n"); - _PyObject_Dump(op->_ob_prev->_ob_next); - fprintf(stderr, "* op->_ob_next->_ob_prev\n"); - _PyObject_Dump(op->_ob_next->_ob_prev); - Py_FatalError("UNREF invalid object"); - } + if (op->ob_refcnt < 0) + Py_FatalError("UNREF negative refcnt"); + if (op == &refchain || + op->_ob_prev->_ob_next != op || op->_ob_next->_ob_prev != op) { + fprintf(stderr, "* ob\n"); + _PyObject_Dump(op); + fprintf(stderr, "* op->_ob_prev->_ob_next\n"); + _PyObject_Dump(op->_ob_prev->_ob_next); + fprintf(stderr, "* op->_ob_next->_ob_prev\n"); + _PyObject_Dump(op->_ob_next->_ob_prev); + Py_FatalError("UNREF invalid object"); + } #ifdef SLOW_UNREF_CHECK - for (p = refchain._ob_next; p != &refchain; p = p->_ob_next) { - if (p == op) - break; - } - if (p == &refchain) /* Not found */ - Py_FatalError("UNREF unknown object"); + for (p = refchain._ob_next; p != &refchain; p = p->_ob_next) { + if (p == op) + break; + } + if (p == &refchain) /* Not found */ + Py_FatalError("UNREF unknown object"); #endif - op->_ob_next->_ob_prev = op->_ob_prev; - op->_ob_prev->_ob_next = op->_ob_next; - op->_ob_next = op->_ob_prev = NULL; - _Py_INC_TPFREES(op); + op->_ob_next->_ob_prev = op->_ob_prev; + op->_ob_prev->_ob_next = op->_ob_next; + op->_ob_next = op->_ob_prev = NULL; + _Py_INC_TPFREES(op); } void _Py_Dealloc(PyObject *op) { - destructor dealloc = Py_TYPE(op)->tp_dealloc; - _Py_ForgetReference(op); - (*dealloc)(op); + destructor dealloc = Py_TYPE(op)->tp_dealloc; + _Py_ForgetReference(op); + (*dealloc)(op); } /* Print all live objects. Because PyObject_Print is called, the @@ -1679,14 +1679,14 @@ void _Py_PrintReferences(FILE *fp) { - PyObject *op; - fprintf(fp, "Remaining objects:\n"); - for (op = refchain._ob_next; op != &refchain; op = op->_ob_next) { - fprintf(fp, "%p [%" PY_FORMAT_SIZE_T "d] ", op, op->ob_refcnt); - if (PyObject_Print(op, fp, 0) != 0) - PyErr_Clear(); - putc('\n', fp); - } + PyObject *op; + fprintf(fp, "Remaining objects:\n"); + for (op = refchain._ob_next; op != &refchain; op = op->_ob_next) { + fprintf(fp, "%p [%" PY_FORMAT_SIZE_T "d] ", op, op->ob_refcnt); + if (PyObject_Print(op, fp, 0) != 0) + PyErr_Clear(); + putc('\n', fp); + } } /* Print the addresses of all live objects. Unlike _Py_PrintReferences, this @@ -1695,40 +1695,40 @@ void _Py_PrintReferenceAddresses(FILE *fp) { - PyObject *op; - fprintf(fp, "Remaining object addresses:\n"); - for (op = refchain._ob_next; op != &refchain; op = op->_ob_next) - fprintf(fp, "%p [%" PY_FORMAT_SIZE_T "d] %s\n", op, - op->ob_refcnt, Py_TYPE(op)->tp_name); + PyObject *op; + fprintf(fp, "Remaining object addresses:\n"); + for (op = refchain._ob_next; op != &refchain; op = op->_ob_next) + fprintf(fp, "%p [%" PY_FORMAT_SIZE_T "d] %s\n", op, + op->ob_refcnt, Py_TYPE(op)->tp_name); } PyObject * _Py_GetObjects(PyObject *self, PyObject *args) { - int i, n; - PyObject *t = NULL; - PyObject *res, *op; - - if (!PyArg_ParseTuple(args, "i|O", &n, &t)) - return NULL; - op = refchain._ob_next; - res = PyList_New(0); - if (res == NULL) - return NULL; - for (i = 0; (n == 0 || i < n) && op != &refchain; i++) { - while (op == self || op == args || op == res || op == t || - (t != NULL && Py_TYPE(op) != (PyTypeObject *) t)) { - op = op->_ob_next; - if (op == &refchain) - return res; - } - if (PyList_Append(res, op) < 0) { - Py_DECREF(res); - return NULL; - } - op = op->_ob_next; - } - return res; + int i, n; + PyObject *t = NULL; + PyObject *res, *op; + + if (!PyArg_ParseTuple(args, "i|O", &n, &t)) + return NULL; + op = refchain._ob_next; + res = PyList_New(0); + if (res == NULL) + return NULL; + for (i = 0; (n == 0 || i < n) && op != &refchain; i++) { + while (op == self || op == args || op == res || op == t || + (t != NULL && Py_TYPE(op) != (PyTypeObject *) t)) { + op = op->_ob_next; + if (op == &refchain) + return res; + } + if (PyList_Append(res, op) < 0) { + Py_DECREF(res); + return NULL; + } + op = op->_ob_next; + } + return res; } #endif @@ -1747,19 +1747,19 @@ void * PyMem_Malloc(size_t nbytes) { - return PyMem_MALLOC(nbytes); + return PyMem_MALLOC(nbytes); } void * PyMem_Realloc(void *p, size_t nbytes) { - return PyMem_REALLOC(p, nbytes); + return PyMem_REALLOC(p, nbytes); } void PyMem_Free(void *p) { - PyMem_FREE(p); + PyMem_FREE(p); } @@ -1780,52 +1780,52 @@ int Py_ReprEnter(PyObject *obj) { - PyObject *dict; - PyObject *list; - Py_ssize_t i; - - dict = PyThreadState_GetDict(); - if (dict == NULL) - return 0; - list = PyDict_GetItemString(dict, KEY); - if (list == NULL) { - list = PyList_New(0); - if (list == NULL) - return -1; - if (PyDict_SetItemString(dict, KEY, list) < 0) - return -1; - Py_DECREF(list); - } - i = PyList_GET_SIZE(list); - while (--i >= 0) { - if (PyList_GET_ITEM(list, i) == obj) - return 1; - } - PyList_Append(list, obj); - return 0; + PyObject *dict; + PyObject *list; + Py_ssize_t i; + + dict = PyThreadState_GetDict(); + if (dict == NULL) + return 0; + list = PyDict_GetItemString(dict, KEY); + if (list == NULL) { + list = PyList_New(0); + if (list == NULL) + return -1; + if (PyDict_SetItemString(dict, KEY, list) < 0) + return -1; + Py_DECREF(list); + } + i = PyList_GET_SIZE(list); + while (--i >= 0) { + if (PyList_GET_ITEM(list, i) == obj) + return 1; + } + PyList_Append(list, obj); + return 0; } void Py_ReprLeave(PyObject *obj) { - PyObject *dict; - PyObject *list; - Py_ssize_t i; - - dict = PyThreadState_GetDict(); - if (dict == NULL) - return; - list = PyDict_GetItemString(dict, KEY); - if (list == NULL || !PyList_Check(list)) - return; - i = PyList_GET_SIZE(list); - /* Count backwards because we always expect obj to be list[-1] */ - while (--i >= 0) { - if (PyList_GET_ITEM(list, i) == obj) { - PyList_SetSlice(list, i, i + 1, NULL); - break; - } - } + PyObject *dict; + PyObject *list; + Py_ssize_t i; + + dict = PyThreadState_GetDict(); + if (dict == NULL) + return; + list = PyDict_GetItemString(dict, KEY); + if (list == NULL || !PyList_Check(list)) + return; + i = PyList_GET_SIZE(list); + /* Count backwards because we always expect obj to be list[-1] */ + while (--i >= 0) { + if (PyList_GET_ITEM(list, i) == obj) { + PyList_SetSlice(list, i, i + 1, NULL); + break; + } + } } /* Trashcan support. */ @@ -1845,11 +1845,11 @@ void _PyTrash_deposit_object(PyObject *op) { - assert(PyObject_IS_GC(op)); - assert(_Py_AS_GC(op)->gc.gc_refs == _PyGC_REFS_UNTRACKED); - assert(op->ob_refcnt == 0); - _Py_AS_GC(op)->gc.gc_prev = (PyGC_Head *)_PyTrash_delete_later; - _PyTrash_delete_later = op; + assert(PyObject_IS_GC(op)); + assert(_Py_AS_GC(op)->gc.gc_refs == _PyGC_REFS_UNTRACKED); + assert(op->ob_refcnt == 0); + _Py_AS_GC(op)->gc.gc_prev = (PyGC_Head *)_PyTrash_delete_later; + _PyTrash_delete_later = op; } /* Dealloccate all the objects in the _PyTrash_delete_later list. Called when @@ -1858,24 +1858,24 @@ void _PyTrash_destroy_chain(void) { - while (_PyTrash_delete_later) { - PyObject *op = _PyTrash_delete_later; - destructor dealloc = Py_TYPE(op)->tp_dealloc; - - _PyTrash_delete_later = - (PyObject*) _Py_AS_GC(op)->gc.gc_prev; - - /* Call the deallocator directly. This used to try to - * fool Py_DECREF into calling it indirectly, but - * Py_DECREF was already called on this object, and in - * assorted non-release builds calling Py_DECREF again ends - * up distorting allocation statistics. - */ - assert(op->ob_refcnt == 0); - ++_PyTrash_delete_nesting; - (*dealloc)(op); - --_PyTrash_delete_nesting; - } + while (_PyTrash_delete_later) { + PyObject *op = _PyTrash_delete_later; + destructor dealloc = Py_TYPE(op)->tp_dealloc; + + _PyTrash_delete_later = + (PyObject*) _Py_AS_GC(op)->gc.gc_prev; + + /* Call the deallocator directly. This used to try to + * fool Py_DECREF into calling it indirectly, but + * Py_DECREF was already called on this object, and in + * assorted non-release builds calling Py_DECREF again ends + * up distorting allocation statistics. + */ + assert(op->ob_refcnt == 0); + ++_PyTrash_delete_nesting; + (*dealloc)(op); + --_PyTrash_delete_nesting; + } } #ifdef __cplusplus Modified: python/branches/py3k/Objects/obmalloc.c ============================================================================== --- python/branches/py3k/Objects/obmalloc.c (original) +++ python/branches/py3k/Objects/obmalloc.c Sun May 9 17:52:27 2010 @@ -27,7 +27,7 @@ the cyclic garbage collector operates selectively on container objects. - Object-specific allocators + Object-specific allocators _____ ______ ______ ________ [ int ] [ dict ] [ list ] ... [ string ] Python core | +3 | <----- Object-specific memory -----> | <-- Non-object memory --> | @@ -67,7 +67,7 @@ * in Proc. 1995 Int'l. Workshop on Memory Management, September 1995. */ -/* #undef WITH_MEMORY_LIMITS */ /* disable mem limit checks */ +/* #undef WITH_MEMORY_LIMITS */ /* disable mem limit checks */ /*==========================================================================*/ @@ -95,22 +95,22 @@ * * For small requests we have the following table: * - * Request in bytes Size of allocated block Size class idx + * Request in bytes Size of allocated block Size class idx * ---------------------------------------------------------------- * 1-8 8 0 - * 9-16 16 1 - * 17-24 24 2 - * 25-32 32 3 - * 33-40 40 4 - * 41-48 48 5 - * 49-56 56 6 - * 57-64 64 7 - * 65-72 72 8 - * ... ... ... - * 241-248 248 30 - * 249-256 256 31 + * 9-16 16 1 + * 17-24 24 2 + * 25-32 32 3 + * 33-40 40 4 + * 41-48 48 5 + * 49-56 56 6 + * 57-64 64 7 + * 65-72 72 8 + * ... ... ... + * 241-248 248 30 + * 249-256 256 31 * - * 0, 257 and up: routed to the underlying allocator. + * 0, 257 and up: routed to the underlying allocator. */ /*==========================================================================*/ @@ -127,9 +127,9 @@ * * You shouldn't change this unless you know what you are doing. */ -#define ALIGNMENT 8 /* must be 2^N */ -#define ALIGNMENT_SHIFT 3 -#define ALIGNMENT_MASK (ALIGNMENT - 1) +#define ALIGNMENT 8 /* must be 2^N */ +#define ALIGNMENT_SHIFT 3 +#define ALIGNMENT_MASK (ALIGNMENT - 1) /* Return the number of bytes in size class I, as a uint. */ #define INDEX2SIZE(I) (((uint)(I) + 1) << ALIGNMENT_SHIFT) @@ -140,14 +140,14 @@ * this value according to your application behaviour and memory needs. * * The following invariants must hold: - * 1) ALIGNMENT <= SMALL_REQUEST_THRESHOLD <= 256 - * 2) SMALL_REQUEST_THRESHOLD is evenly divisible by ALIGNMENT + * 1) ALIGNMENT <= SMALL_REQUEST_THRESHOLD <= 256 + * 2) SMALL_REQUEST_THRESHOLD is evenly divisible by ALIGNMENT * * Although not required, for better performance and space efficiency, * it is recommended that SMALL_REQUEST_THRESHOLD is set to a power of 2. */ -#define SMALL_REQUEST_THRESHOLD 256 -#define NB_SMALL_SIZE_CLASSES (SMALL_REQUEST_THRESHOLD / ALIGNMENT) +#define SMALL_REQUEST_THRESHOLD 256 +#define NB_SMALL_SIZE_CLASSES (SMALL_REQUEST_THRESHOLD / ALIGNMENT) /* * The system's VMM page size can be obtained on most unices with a @@ -159,15 +159,15 @@ * violation fault. 4K is apparently OK for all the platforms that python * currently targets. */ -#define SYSTEM_PAGE_SIZE (4 * 1024) -#define SYSTEM_PAGE_SIZE_MASK (SYSTEM_PAGE_SIZE - 1) +#define SYSTEM_PAGE_SIZE (4 * 1024) +#define SYSTEM_PAGE_SIZE_MASK (SYSTEM_PAGE_SIZE - 1) /* * Maximum amount of memory managed by the allocator for small requests. */ #ifdef WITH_MEMORY_LIMITS #ifndef SMALL_MEMORY_LIMIT -#define SMALL_MEMORY_LIMIT (64 * 1024 * 1024) /* 64 MB -- more? */ +#define SMALL_MEMORY_LIMIT (64 * 1024 * 1024) /* 64 MB -- more? */ #endif #endif @@ -184,18 +184,18 @@ * some address space wastage, but this is the most portable way to request * memory from the system across various platforms. */ -#define ARENA_SIZE (256 << 10) /* 256KB */ +#define ARENA_SIZE (256 << 10) /* 256KB */ #ifdef WITH_MEMORY_LIMITS -#define MAX_ARENAS (SMALL_MEMORY_LIMIT / ARENA_SIZE) +#define MAX_ARENAS (SMALL_MEMORY_LIMIT / ARENA_SIZE) #endif /* * Size of the pools used for small blocks. Should be a power of 2, * between 1K and SYSTEM_PAGE_SIZE, that is: 1k, 2k, 4k. */ -#define POOL_SIZE SYSTEM_PAGE_SIZE /* must be 2^N */ -#define POOL_SIZE_MASK SYSTEM_PAGE_SIZE_MASK +#define POOL_SIZE SYSTEM_PAGE_SIZE /* must be 2^N */ +#define POOL_SIZE_MASK SYSTEM_PAGE_SIZE_MASK /* * -- End of tunable settings section -- @@ -221,92 +221,92 @@ /* * Python's threads are serialized, so object malloc locking is disabled. */ -#define SIMPLELOCK_DECL(lock) /* simple lock declaration */ -#define SIMPLELOCK_INIT(lock) /* allocate (if needed) and initialize */ -#define SIMPLELOCK_FINI(lock) /* free/destroy an existing lock */ -#define SIMPLELOCK_LOCK(lock) /* acquire released lock */ -#define SIMPLELOCK_UNLOCK(lock) /* release acquired lock */ +#define SIMPLELOCK_DECL(lock) /* simple lock declaration */ +#define SIMPLELOCK_INIT(lock) /* allocate (if needed) and initialize */ +#define SIMPLELOCK_FINI(lock) /* free/destroy an existing lock */ +#define SIMPLELOCK_LOCK(lock) /* acquire released lock */ +#define SIMPLELOCK_UNLOCK(lock) /* release acquired lock */ /* * Basic types * I don't care if these are defined in or elsewhere. Axiom. */ #undef uchar -#define uchar unsigned char /* assuming == 8 bits */ +#define uchar unsigned char /* assuming == 8 bits */ #undef uint -#define uint unsigned int /* assuming >= 16 bits */ +#define uint unsigned int /* assuming >= 16 bits */ #undef ulong -#define ulong unsigned long /* assuming >= 32 bits */ +#define ulong unsigned long /* assuming >= 32 bits */ #undef uptr -#define uptr Py_uintptr_t +#define uptr Py_uintptr_t /* When you say memory, my mind reasons in terms of (pointers to) blocks */ typedef uchar block; /* Pool for small blocks. */ struct pool_header { - union { block *_padding; - uint count; } ref; /* number of allocated blocks */ - block *freeblock; /* pool's free list head */ - struct pool_header *nextpool; /* next pool of this size class */ - struct pool_header *prevpool; /* previous pool "" */ - uint arenaindex; /* index into arenas of base adr */ - uint szidx; /* block size class index */ - uint nextoffset; /* bytes to virgin block */ - uint maxnextoffset; /* largest valid nextoffset */ + union { block *_padding; + uint count; } ref; /* number of allocated blocks */ + block *freeblock; /* pool's free list head */ + struct pool_header *nextpool; /* next pool of this size class */ + struct pool_header *prevpool; /* previous pool "" */ + uint arenaindex; /* index into arenas of base adr */ + uint szidx; /* block size class index */ + uint nextoffset; /* bytes to virgin block */ + uint maxnextoffset; /* largest valid nextoffset */ }; typedef struct pool_header *poolp; /* Record keeping for arenas. */ struct arena_object { - /* The address of the arena, as returned by malloc. Note that 0 - * will never be returned by a successful malloc, and is used - * here to mark an arena_object that doesn't correspond to an - * allocated arena. - */ - uptr address; - - /* Pool-aligned pointer to the next pool to be carved off. */ - block* pool_address; - - /* The number of available pools in the arena: free pools + never- - * allocated pools. - */ - uint nfreepools; - - /* The total number of pools in the arena, whether or not available. */ - uint ntotalpools; - - /* Singly-linked list of available pools. */ - struct pool_header* freepools; - - /* Whenever this arena_object is not associated with an allocated - * arena, the nextarena member is used to link all unassociated - * arena_objects in the singly-linked `unused_arena_objects` list. - * The prevarena member is unused in this case. - * - * When this arena_object is associated with an allocated arena - * with at least one available pool, both members are used in the - * doubly-linked `usable_arenas` list, which is maintained in - * increasing order of `nfreepools` values. - * - * Else this arena_object is associated with an allocated arena - * all of whose pools are in use. `nextarena` and `prevarena` - * are both meaningless in this case. - */ - struct arena_object* nextarena; - struct arena_object* prevarena; + /* The address of the arena, as returned by malloc. Note that 0 + * will never be returned by a successful malloc, and is used + * here to mark an arena_object that doesn't correspond to an + * allocated arena. + */ + uptr address; + + /* Pool-aligned pointer to the next pool to be carved off. */ + block* pool_address; + + /* The number of available pools in the arena: free pools + never- + * allocated pools. + */ + uint nfreepools; + + /* The total number of pools in the arena, whether or not available. */ + uint ntotalpools; + + /* Singly-linked list of available pools. */ + struct pool_header* freepools; + + /* Whenever this arena_object is not associated with an allocated + * arena, the nextarena member is used to link all unassociated + * arena_objects in the singly-linked `unused_arena_objects` list. + * The prevarena member is unused in this case. + * + * When this arena_object is associated with an allocated arena + * with at least one available pool, both members are used in the + * doubly-linked `usable_arenas` list, which is maintained in + * increasing order of `nfreepools` values. + * + * Else this arena_object is associated with an allocated arena + * all of whose pools are in use. `nextarena` and `prevarena` + * are both meaningless in this case. + */ + struct arena_object* nextarena; + struct arena_object* prevarena; }; #undef ROUNDUP -#define ROUNDUP(x) (((x) + ALIGNMENT_MASK) & ~ALIGNMENT_MASK) -#define POOL_OVERHEAD ROUNDUP(sizeof(struct pool_header)) +#define ROUNDUP(x) (((x) + ALIGNMENT_MASK) & ~ALIGNMENT_MASK) +#define POOL_OVERHEAD ROUNDUP(sizeof(struct pool_header)) -#define DUMMY_SIZE_IDX 0xffff /* size class of newly cached pools */ +#define DUMMY_SIZE_IDX 0xffff /* size class of newly cached pools */ /* Round pointer P down to the closest pool-aligned address <= P, as a poolp */ #define POOL_ADDR(P) ((poolp)((uptr)(P) & ~(uptr)POOL_SIZE_MASK)) @@ -320,10 +320,10 @@ * This malloc lock */ SIMPLELOCK_DECL(_malloc_lock) -#define LOCK() SIMPLELOCK_LOCK(_malloc_lock) -#define UNLOCK() SIMPLELOCK_UNLOCK(_malloc_lock) -#define LOCK_INIT() SIMPLELOCK_INIT(_malloc_lock) -#define LOCK_FINI() SIMPLELOCK_FINI(_malloc_lock) +#define LOCK() SIMPLELOCK_LOCK(_malloc_lock) +#define UNLOCK() SIMPLELOCK_UNLOCK(_malloc_lock) +#define LOCK_INIT() SIMPLELOCK_INIT(_malloc_lock) +#define LOCK_FINI() SIMPLELOCK_FINI(_malloc_lock) /* * Pool table -- headed, circular, doubly-linked lists of partially used pools. @@ -403,9 +403,9 @@ compensating for that a pool_header's nextpool and prevpool members immediately follow a pool_header's first two members: - union { block *_padding; - uint count; } ref; - block *freeblock; + union { block *_padding; + uint count; } ref; + block *freeblock; each of which consume sizeof(block *) bytes. So what usedpools[i+i] really contains is a fudged-up pointer p such that *if* C believes it's a poolp @@ -421,25 +421,25 @@ the prevpool member. **************************************************************************** */ -#define PTA(x) ((poolp )((uchar *)&(usedpools[2*(x)]) - 2*sizeof(block *))) -#define PT(x) PTA(x), PTA(x) +#define PTA(x) ((poolp )((uchar *)&(usedpools[2*(x)]) - 2*sizeof(block *))) +#define PT(x) PTA(x), PTA(x) static poolp usedpools[2 * ((NB_SMALL_SIZE_CLASSES + 7) / 8) * 8] = { - PT(0), PT(1), PT(2), PT(3), PT(4), PT(5), PT(6), PT(7) + PT(0), PT(1), PT(2), PT(3), PT(4), PT(5), PT(6), PT(7) #if NB_SMALL_SIZE_CLASSES > 8 - , PT(8), PT(9), PT(10), PT(11), PT(12), PT(13), PT(14), PT(15) + , PT(8), PT(9), PT(10), PT(11), PT(12), PT(13), PT(14), PT(15) #if NB_SMALL_SIZE_CLASSES > 16 - , PT(16), PT(17), PT(18), PT(19), PT(20), PT(21), PT(22), PT(23) + , PT(16), PT(17), PT(18), PT(19), PT(20), PT(21), PT(22), PT(23) #if NB_SMALL_SIZE_CLASSES > 24 - , PT(24), PT(25), PT(26), PT(27), PT(28), PT(29), PT(30), PT(31) + , PT(24), PT(25), PT(26), PT(27), PT(28), PT(29), PT(30), PT(31) #if NB_SMALL_SIZE_CLASSES > 32 - , PT(32), PT(33), PT(34), PT(35), PT(36), PT(37), PT(38), PT(39) + , PT(32), PT(33), PT(34), PT(35), PT(36), PT(37), PT(38), PT(39) #if NB_SMALL_SIZE_CLASSES > 40 - , PT(40), PT(41), PT(42), PT(43), PT(44), PT(45), PT(46), PT(47) + , PT(40), PT(41), PT(42), PT(43), PT(44), PT(45), PT(46), PT(47) #if NB_SMALL_SIZE_CLASSES > 48 - , PT(48), PT(49), PT(50), PT(51), PT(52), PT(53), PT(54), PT(55) + , PT(48), PT(49), PT(50), PT(51), PT(52), PT(53), PT(54), PT(55) #if NB_SMALL_SIZE_CLASSES > 56 - , PT(56), PT(57), PT(58), PT(59), PT(60), PT(61), PT(62), PT(63) + , PT(56), PT(57), PT(58), PT(59), PT(60), PT(61), PT(62), PT(63) #endif /* NB_SMALL_SIZE_CLASSES > 56 */ #endif /* NB_SMALL_SIZE_CLASSES > 48 */ #endif /* NB_SMALL_SIZE_CLASSES > 40 */ @@ -523,90 +523,90 @@ static struct arena_object* new_arena(void) { - struct arena_object* arenaobj; - uint excess; /* number of bytes above pool alignment */ + struct arena_object* arenaobj; + uint excess; /* number of bytes above pool alignment */ #ifdef PYMALLOC_DEBUG - if (Py_GETENV("PYTHONMALLOCSTATS")) - _PyObject_DebugMallocStats(); + if (Py_GETENV("PYTHONMALLOCSTATS")) + _PyObject_DebugMallocStats(); #endif - if (unused_arena_objects == NULL) { - uint i; - uint numarenas; - size_t nbytes; - - /* Double the number of arena objects on each allocation. - * Note that it's possible for `numarenas` to overflow. - */ - numarenas = maxarenas ? maxarenas << 1 : INITIAL_ARENA_OBJECTS; - if (numarenas <= maxarenas) - return NULL; /* overflow */ + if (unused_arena_objects == NULL) { + uint i; + uint numarenas; + size_t nbytes; + + /* Double the number of arena objects on each allocation. + * Note that it's possible for `numarenas` to overflow. + */ + numarenas = maxarenas ? maxarenas << 1 : INITIAL_ARENA_OBJECTS; + if (numarenas <= maxarenas) + return NULL; /* overflow */ #if SIZEOF_SIZE_T <= SIZEOF_INT - if (numarenas > PY_SIZE_MAX / sizeof(*arenas)) - return NULL; /* overflow */ + if (numarenas > PY_SIZE_MAX / sizeof(*arenas)) + return NULL; /* overflow */ #endif - nbytes = numarenas * sizeof(*arenas); - arenaobj = (struct arena_object *)realloc(arenas, nbytes); - if (arenaobj == NULL) - return NULL; - arenas = arenaobj; - - /* We might need to fix pointers that were copied. However, - * new_arena only gets called when all the pages in the - * previous arenas are full. Thus, there are *no* pointers - * into the old array. Thus, we don't have to worry about - * invalid pointers. Just to be sure, some asserts: - */ - assert(usable_arenas == NULL); - assert(unused_arena_objects == NULL); - - /* Put the new arenas on the unused_arena_objects list. */ - for (i = maxarenas; i < numarenas; ++i) { - arenas[i].address = 0; /* mark as unassociated */ - arenas[i].nextarena = i < numarenas - 1 ? - &arenas[i+1] : NULL; - } - - /* Update globals. */ - unused_arena_objects = &arenas[maxarenas]; - maxarenas = numarenas; - } - - /* Take the next available arena object off the head of the list. */ - assert(unused_arena_objects != NULL); - arenaobj = unused_arena_objects; - unused_arena_objects = arenaobj->nextarena; - assert(arenaobj->address == 0); - arenaobj->address = (uptr)malloc(ARENA_SIZE); - if (arenaobj->address == 0) { - /* The allocation failed: return NULL after putting the - * arenaobj back. - */ - arenaobj->nextarena = unused_arena_objects; - unused_arena_objects = arenaobj; - return NULL; - } + nbytes = numarenas * sizeof(*arenas); + arenaobj = (struct arena_object *)realloc(arenas, nbytes); + if (arenaobj == NULL) + return NULL; + arenas = arenaobj; + + /* We might need to fix pointers that were copied. However, + * new_arena only gets called when all the pages in the + * previous arenas are full. Thus, there are *no* pointers + * into the old array. Thus, we don't have to worry about + * invalid pointers. Just to be sure, some asserts: + */ + assert(usable_arenas == NULL); + assert(unused_arena_objects == NULL); - ++narenas_currently_allocated; + /* Put the new arenas on the unused_arena_objects list. */ + for (i = maxarenas; i < numarenas; ++i) { + arenas[i].address = 0; /* mark as unassociated */ + arenas[i].nextarena = i < numarenas - 1 ? + &arenas[i+1] : NULL; + } + + /* Update globals. */ + unused_arena_objects = &arenas[maxarenas]; + maxarenas = numarenas; + } + + /* Take the next available arena object off the head of the list. */ + assert(unused_arena_objects != NULL); + arenaobj = unused_arena_objects; + unused_arena_objects = arenaobj->nextarena; + assert(arenaobj->address == 0); + arenaobj->address = (uptr)malloc(ARENA_SIZE); + if (arenaobj->address == 0) { + /* The allocation failed: return NULL after putting the + * arenaobj back. + */ + arenaobj->nextarena = unused_arena_objects; + unused_arena_objects = arenaobj; + return NULL; + } + + ++narenas_currently_allocated; #ifdef PYMALLOC_DEBUG - ++ntimes_arena_allocated; - if (narenas_currently_allocated > narenas_highwater) - narenas_highwater = narenas_currently_allocated; + ++ntimes_arena_allocated; + if (narenas_currently_allocated > narenas_highwater) + narenas_highwater = narenas_currently_allocated; #endif - arenaobj->freepools = NULL; - /* pool_address <- first pool-aligned address in the arena - nfreepools <- number of whole pools that fit after alignment */ - arenaobj->pool_address = (block*)arenaobj->address; - arenaobj->nfreepools = ARENA_SIZE / POOL_SIZE; - assert(POOL_SIZE * arenaobj->nfreepools == ARENA_SIZE); - excess = (uint)(arenaobj->address & POOL_SIZE_MASK); - if (excess != 0) { - --arenaobj->nfreepools; - arenaobj->pool_address += POOL_SIZE - excess; - } - arenaobj->ntotalpools = arenaobj->nfreepools; + arenaobj->freepools = NULL; + /* pool_address <- first pool-aligned address in the arena + nfreepools <- number of whole pools that fit after alignment */ + arenaobj->pool_address = (block*)arenaobj->address; + arenaobj->nfreepools = ARENA_SIZE / POOL_SIZE; + assert(POOL_SIZE * arenaobj->nfreepools == ARENA_SIZE); + excess = (uint)(arenaobj->address & POOL_SIZE_MASK); + if (excess != 0) { + --arenaobj->nfreepools; + arenaobj->pool_address += POOL_SIZE - excess; + } + arenaobj->ntotalpools = arenaobj->nfreepools; - return arenaobj; + return arenaobj; } /* @@ -622,11 +622,11 @@ Tricky: Let B be the arena base address associated with the pool, B = arenas[(POOL)->arenaindex].address. Then P belongs to the arena if and only if - B <= P < B + ARENA_SIZE + B <= P < B + ARENA_SIZE Subtracting B throughout, this is true iff - 0 <= P-B < ARENA_SIZE + 0 <= P-B < ARENA_SIZE By using unsigned arithmetic, the "0 <=" half of the test can be skipped. @@ -660,7 +660,7 @@ arena_object (one not currently associated with an allocated arena), AO.address is 0, and the second test in the macro reduces to: - P < ARENA_SIZE + P < ARENA_SIZE If P >= ARENA_SIZE (extremely likely), the macro again correctly concludes that P is not controlled by obmalloc. However, if P < ARENA_SIZE, this part @@ -683,10 +683,10 @@ obmalloc controls. Since this test is needed at every entry point, it's extremely desirable that it be this fast. */ -#define Py_ADDRESS_IN_RANGE(P, POOL) \ - ((POOL)->arenaindex < maxarenas && \ - (uptr)(P) - arenas[(POOL)->arenaindex].address < (uptr)ARENA_SIZE && \ - arenas[(POOL)->arenaindex].address != 0) +#define Py_ADDRESS_IN_RANGE(P, POOL) \ + ((POOL)->arenaindex < maxarenas && \ + (uptr)(P) - arenas[(POOL)->arenaindex].address < (uptr)ARENA_SIZE && \ + arenas[(POOL)->arenaindex].address != 0) /* This is only useful when running memory debuggers such as @@ -709,7 +709,7 @@ #undef Py_ADDRESS_IN_RANGE #if defined(__GNUC__) && ((__GNUC__ == 3) && (__GNUC_MINOR__ >= 1) || \ - (__GNUC__ >= 4)) + (__GNUC__ >= 4)) #define Py_NO_INLINE __attribute__((__noinline__)) #else #define Py_NO_INLINE @@ -738,201 +738,201 @@ void * PyObject_Malloc(size_t nbytes) { - block *bp; - poolp pool; - poolp next; - uint size; + block *bp; + poolp pool; + poolp next; + uint size; #ifdef WITH_VALGRIND - if (UNLIKELY(running_on_valgrind == -1)) - running_on_valgrind = RUNNING_ON_VALGRIND; - if (UNLIKELY(running_on_valgrind)) - goto redirect; + if (UNLIKELY(running_on_valgrind == -1)) + running_on_valgrind = RUNNING_ON_VALGRIND; + if (UNLIKELY(running_on_valgrind)) + goto redirect; #endif - /* - * Limit ourselves to PY_SSIZE_T_MAX bytes to prevent security holes. - * Most python internals blindly use a signed Py_ssize_t to track - * things without checking for overflows or negatives. - * As size_t is unsigned, checking for nbytes < 0 is not required. - */ - if (nbytes > PY_SSIZE_T_MAX) - return NULL; - - /* - * This implicitly redirects malloc(0). - */ - if ((nbytes - 1) < SMALL_REQUEST_THRESHOLD) { - LOCK(); - /* - * Most frequent paths first - */ - size = (uint)(nbytes - 1) >> ALIGNMENT_SHIFT; - pool = usedpools[size + size]; - if (pool != pool->nextpool) { - /* - * There is a used pool for this size class. - * Pick up the head block of its free list. - */ - ++pool->ref.count; - bp = pool->freeblock; - assert(bp != NULL); - if ((pool->freeblock = *(block **)bp) != NULL) { - UNLOCK(); - return (void *)bp; - } - /* - * Reached the end of the free list, try to extend it. - */ - if (pool->nextoffset <= pool->maxnextoffset) { - /* There is room for another block. */ - pool->freeblock = (block*)pool + - pool->nextoffset; - pool->nextoffset += INDEX2SIZE(size); - *(block **)(pool->freeblock) = NULL; - UNLOCK(); - return (void *)bp; - } - /* Pool is full, unlink from used pools. */ - next = pool->nextpool; - pool = pool->prevpool; - next->prevpool = pool; - pool->nextpool = next; - UNLOCK(); - return (void *)bp; - } - - /* There isn't a pool of the right size class immediately - * available: use a free pool. - */ - if (usable_arenas == NULL) { - /* No arena has a free pool: allocate a new arena. */ + /* + * Limit ourselves to PY_SSIZE_T_MAX bytes to prevent security holes. + * Most python internals blindly use a signed Py_ssize_t to track + * things without checking for overflows or negatives. + * As size_t is unsigned, checking for nbytes < 0 is not required. + */ + if (nbytes > PY_SSIZE_T_MAX) + return NULL; + + /* + * This implicitly redirects malloc(0). + */ + if ((nbytes - 1) < SMALL_REQUEST_THRESHOLD) { + LOCK(); + /* + * Most frequent paths first + */ + size = (uint)(nbytes - 1) >> ALIGNMENT_SHIFT; + pool = usedpools[size + size]; + if (pool != pool->nextpool) { + /* + * There is a used pool for this size class. + * Pick up the head block of its free list. + */ + ++pool->ref.count; + bp = pool->freeblock; + assert(bp != NULL); + if ((pool->freeblock = *(block **)bp) != NULL) { + UNLOCK(); + return (void *)bp; + } + /* + * Reached the end of the free list, try to extend it. + */ + if (pool->nextoffset <= pool->maxnextoffset) { + /* There is room for another block. */ + pool->freeblock = (block*)pool + + pool->nextoffset; + pool->nextoffset += INDEX2SIZE(size); + *(block **)(pool->freeblock) = NULL; + UNLOCK(); + return (void *)bp; + } + /* Pool is full, unlink from used pools. */ + next = pool->nextpool; + pool = pool->prevpool; + next->prevpool = pool; + pool->nextpool = next; + UNLOCK(); + return (void *)bp; + } + + /* There isn't a pool of the right size class immediately + * available: use a free pool. + */ + if (usable_arenas == NULL) { + /* No arena has a free pool: allocate a new arena. */ #ifdef WITH_MEMORY_LIMITS - if (narenas_currently_allocated >= MAX_ARENAS) { - UNLOCK(); - goto redirect; - } + if (narenas_currently_allocated >= MAX_ARENAS) { + UNLOCK(); + goto redirect; + } #endif - usable_arenas = new_arena(); - if (usable_arenas == NULL) { - UNLOCK(); - goto redirect; - } - usable_arenas->nextarena = - usable_arenas->prevarena = NULL; - } - assert(usable_arenas->address != 0); - - /* Try to get a cached free pool. */ - pool = usable_arenas->freepools; - if (pool != NULL) { - /* Unlink from cached pools. */ - usable_arenas->freepools = pool->nextpool; - - /* This arena already had the smallest nfreepools - * value, so decreasing nfreepools doesn't change - * that, and we don't need to rearrange the - * usable_arenas list. However, if the arena has - * become wholly allocated, we need to remove its - * arena_object from usable_arenas. - */ - --usable_arenas->nfreepools; - if (usable_arenas->nfreepools == 0) { - /* Wholly allocated: remove. */ - assert(usable_arenas->freepools == NULL); - assert(usable_arenas->nextarena == NULL || - usable_arenas->nextarena->prevarena == - usable_arenas); - - usable_arenas = usable_arenas->nextarena; - if (usable_arenas != NULL) { - usable_arenas->prevarena = NULL; - assert(usable_arenas->address != 0); - } - } - else { - /* nfreepools > 0: it must be that freepools - * isn't NULL, or that we haven't yet carved - * off all the arena's pools for the first - * time. - */ - assert(usable_arenas->freepools != NULL || - usable_arenas->pool_address <= - (block*)usable_arenas->address + - ARENA_SIZE - POOL_SIZE); - } - init_pool: - /* Frontlink to used pools. */ - next = usedpools[size + size]; /* == prev */ - pool->nextpool = next; - pool->prevpool = next; - next->nextpool = pool; - next->prevpool = pool; - pool->ref.count = 1; - if (pool->szidx == size) { - /* Luckily, this pool last contained blocks - * of the same size class, so its header - * and free list are already initialized. - */ - bp = pool->freeblock; - pool->freeblock = *(block **)bp; - UNLOCK(); - return (void *)bp; - } - /* - * Initialize the pool header, set up the free list to - * contain just the second block, and return the first - * block. - */ - pool->szidx = size; - size = INDEX2SIZE(size); - bp = (block *)pool + POOL_OVERHEAD; - pool->nextoffset = POOL_OVERHEAD + (size << 1); - pool->maxnextoffset = POOL_SIZE - size; - pool->freeblock = bp + size; - *(block **)(pool->freeblock) = NULL; - UNLOCK(); - return (void *)bp; - } - - /* Carve off a new pool. */ - assert(usable_arenas->nfreepools > 0); - assert(usable_arenas->freepools == NULL); - pool = (poolp)usable_arenas->pool_address; - assert((block*)pool <= (block*)usable_arenas->address + - ARENA_SIZE - POOL_SIZE); - pool->arenaindex = usable_arenas - arenas; - assert(&arenas[pool->arenaindex] == usable_arenas); - pool->szidx = DUMMY_SIZE_IDX; - usable_arenas->pool_address += POOL_SIZE; - --usable_arenas->nfreepools; - - if (usable_arenas->nfreepools == 0) { - assert(usable_arenas->nextarena == NULL || - usable_arenas->nextarena->prevarena == - usable_arenas); - /* Unlink the arena: it is completely allocated. */ - usable_arenas = usable_arenas->nextarena; - if (usable_arenas != NULL) { - usable_arenas->prevarena = NULL; - assert(usable_arenas->address != 0); - } - } + usable_arenas = new_arena(); + if (usable_arenas == NULL) { + UNLOCK(); + goto redirect; + } + usable_arenas->nextarena = + usable_arenas->prevarena = NULL; + } + assert(usable_arenas->address != 0); + + /* Try to get a cached free pool. */ + pool = usable_arenas->freepools; + if (pool != NULL) { + /* Unlink from cached pools. */ + usable_arenas->freepools = pool->nextpool; + + /* This arena already had the smallest nfreepools + * value, so decreasing nfreepools doesn't change + * that, and we don't need to rearrange the + * usable_arenas list. However, if the arena has + * become wholly allocated, we need to remove its + * arena_object from usable_arenas. + */ + --usable_arenas->nfreepools; + if (usable_arenas->nfreepools == 0) { + /* Wholly allocated: remove. */ + assert(usable_arenas->freepools == NULL); + assert(usable_arenas->nextarena == NULL || + usable_arenas->nextarena->prevarena == + usable_arenas); + + usable_arenas = usable_arenas->nextarena; + if (usable_arenas != NULL) { + usable_arenas->prevarena = NULL; + assert(usable_arenas->address != 0); + } + } + else { + /* nfreepools > 0: it must be that freepools + * isn't NULL, or that we haven't yet carved + * off all the arena's pools for the first + * time. + */ + assert(usable_arenas->freepools != NULL || + usable_arenas->pool_address <= + (block*)usable_arenas->address + + ARENA_SIZE - POOL_SIZE); + } + init_pool: + /* Frontlink to used pools. */ + next = usedpools[size + size]; /* == prev */ + pool->nextpool = next; + pool->prevpool = next; + next->nextpool = pool; + next->prevpool = pool; + pool->ref.count = 1; + if (pool->szidx == size) { + /* Luckily, this pool last contained blocks + * of the same size class, so its header + * and free list are already initialized. + */ + bp = pool->freeblock; + pool->freeblock = *(block **)bp; + UNLOCK(); + return (void *)bp; + } + /* + * Initialize the pool header, set up the free list to + * contain just the second block, and return the first + * block. + */ + pool->szidx = size; + size = INDEX2SIZE(size); + bp = (block *)pool + POOL_OVERHEAD; + pool->nextoffset = POOL_OVERHEAD + (size << 1); + pool->maxnextoffset = POOL_SIZE - size; + pool->freeblock = bp + size; + *(block **)(pool->freeblock) = NULL; + UNLOCK(); + return (void *)bp; + } + + /* Carve off a new pool. */ + assert(usable_arenas->nfreepools > 0); + assert(usable_arenas->freepools == NULL); + pool = (poolp)usable_arenas->pool_address; + assert((block*)pool <= (block*)usable_arenas->address + + ARENA_SIZE - POOL_SIZE); + pool->arenaindex = usable_arenas - arenas; + assert(&arenas[pool->arenaindex] == usable_arenas); + pool->szidx = DUMMY_SIZE_IDX; + usable_arenas->pool_address += POOL_SIZE; + --usable_arenas->nfreepools; + + if (usable_arenas->nfreepools == 0) { + assert(usable_arenas->nextarena == NULL || + usable_arenas->nextarena->prevarena == + usable_arenas); + /* Unlink the arena: it is completely allocated. */ + usable_arenas = usable_arenas->nextarena; + if (usable_arenas != NULL) { + usable_arenas->prevarena = NULL; + assert(usable_arenas->address != 0); + } + } - goto init_pool; - } + goto init_pool; + } - /* The small block allocator ends here. */ + /* The small block allocator ends here. */ redirect: - /* Redirect the original request to the underlying (libc) allocator. - * We jump here on bigger requests, on error in the code above (as a - * last chance to serve the request) or when the max memory limit - * has been reached. - */ - if (nbytes == 0) - nbytes = 1; - return (void *)malloc(nbytes); + /* Redirect the original request to the underlying (libc) allocator. + * We jump here on bigger requests, on error in the code above (as a + * last chance to serve the request) or when the max memory limit + * has been reached. + */ + if (nbytes == 0) + nbytes = 1; + return (void *)malloc(nbytes); } /* free */ @@ -941,218 +941,218 @@ void PyObject_Free(void *p) { - poolp pool; - block *lastfree; - poolp next, prev; - uint size; + poolp pool; + block *lastfree; + poolp next, prev; + uint size; - if (p == NULL) /* free(NULL) has no effect */ - return; + if (p == NULL) /* free(NULL) has no effect */ + return; #ifdef WITH_VALGRIND - if (UNLIKELY(running_on_valgrind > 0)) - goto redirect; + if (UNLIKELY(running_on_valgrind > 0)) + goto redirect; #endif - pool = POOL_ADDR(p); - if (Py_ADDRESS_IN_RANGE(p, pool)) { - /* We allocated this address. */ - LOCK(); - /* Link p to the start of the pool's freeblock list. Since - * the pool had at least the p block outstanding, the pool - * wasn't empty (so it's already in a usedpools[] list, or - * was full and is in no list -- it's not in the freeblocks - * list in any case). - */ - assert(pool->ref.count > 0); /* else it was empty */ - *(block **)p = lastfree = pool->freeblock; - pool->freeblock = (block *)p; - if (lastfree) { - struct arena_object* ao; - uint nf; /* ao->nfreepools */ - - /* freeblock wasn't NULL, so the pool wasn't full, - * and the pool is in a usedpools[] list. - */ - if (--pool->ref.count != 0) { - /* pool isn't empty: leave it in usedpools */ - UNLOCK(); - return; - } - /* Pool is now empty: unlink from usedpools, and - * link to the front of freepools. This ensures that - * previously freed pools will be allocated later - * (being not referenced, they are perhaps paged out). - */ - next = pool->nextpool; - prev = pool->prevpool; - next->prevpool = prev; - prev->nextpool = next; - - /* Link the pool to freepools. This is a singly-linked - * list, and pool->prevpool isn't used there. - */ - ao = &arenas[pool->arenaindex]; - pool->nextpool = ao->freepools; - ao->freepools = pool; - nf = ++ao->nfreepools; - - /* All the rest is arena management. We just freed - * a pool, and there are 4 cases for arena mgmt: - * 1. If all the pools are free, return the arena to - * the system free(). - * 2. If this is the only free pool in the arena, - * add the arena back to the `usable_arenas` list. - * 3. If the "next" arena has a smaller count of free - * pools, we have to "slide this arena right" to - * restore that usable_arenas is sorted in order of - * nfreepools. - * 4. Else there's nothing more to do. - */ - if (nf == ao->ntotalpools) { - /* Case 1. First unlink ao from usable_arenas. - */ - assert(ao->prevarena == NULL || - ao->prevarena->address != 0); - assert(ao ->nextarena == NULL || - ao->nextarena->address != 0); - - /* Fix the pointer in the prevarena, or the - * usable_arenas pointer. - */ - if (ao->prevarena == NULL) { - usable_arenas = ao->nextarena; - assert(usable_arenas == NULL || - usable_arenas->address != 0); - } - else { - assert(ao->prevarena->nextarena == ao); - ao->prevarena->nextarena = - ao->nextarena; - } - /* Fix the pointer in the nextarena. */ - if (ao->nextarena != NULL) { - assert(ao->nextarena->prevarena == ao); - ao->nextarena->prevarena = - ao->prevarena; - } - /* Record that this arena_object slot is - * available to be reused. - */ - ao->nextarena = unused_arena_objects; - unused_arena_objects = ao; - - /* Free the entire arena. */ - free((void *)ao->address); - ao->address = 0; /* mark unassociated */ - --narenas_currently_allocated; - - UNLOCK(); - return; - } - if (nf == 1) { - /* Case 2. Put ao at the head of - * usable_arenas. Note that because - * ao->nfreepools was 0 before, ao isn't - * currently on the usable_arenas list. - */ - ao->nextarena = usable_arenas; - ao->prevarena = NULL; - if (usable_arenas) - usable_arenas->prevarena = ao; - usable_arenas = ao; - assert(usable_arenas->address != 0); - - UNLOCK(); - return; - } - /* If this arena is now out of order, we need to keep - * the list sorted. The list is kept sorted so that - * the "most full" arenas are used first, which allows - * the nearly empty arenas to be completely freed. In - * a few un-scientific tests, it seems like this - * approach allowed a lot more memory to be freed. - */ - if (ao->nextarena == NULL || - nf <= ao->nextarena->nfreepools) { - /* Case 4. Nothing to do. */ - UNLOCK(); - return; - } - /* Case 3: We have to move the arena towards the end - * of the list, because it has more free pools than - * the arena to its right. - * First unlink ao from usable_arenas. - */ - if (ao->prevarena != NULL) { - /* ao isn't at the head of the list */ - assert(ao->prevarena->nextarena == ao); - ao->prevarena->nextarena = ao->nextarena; - } - else { - /* ao is at the head of the list */ - assert(usable_arenas == ao); - usable_arenas = ao->nextarena; - } - ao->nextarena->prevarena = ao->prevarena; - - /* Locate the new insertion point by iterating over - * the list, using our nextarena pointer. - */ - while (ao->nextarena != NULL && - nf > ao->nextarena->nfreepools) { - ao->prevarena = ao->nextarena; - ao->nextarena = ao->nextarena->nextarena; - } - - /* Insert ao at this point. */ - assert(ao->nextarena == NULL || - ao->prevarena == ao->nextarena->prevarena); - assert(ao->prevarena->nextarena == ao->nextarena); - - ao->prevarena->nextarena = ao; - if (ao->nextarena != NULL) - ao->nextarena->prevarena = ao; - - /* Verify that the swaps worked. */ - assert(ao->nextarena == NULL || - nf <= ao->nextarena->nfreepools); - assert(ao->prevarena == NULL || - nf > ao->prevarena->nfreepools); - assert(ao->nextarena == NULL || - ao->nextarena->prevarena == ao); - assert((usable_arenas == ao && - ao->prevarena == NULL) || - ao->prevarena->nextarena == ao); - - UNLOCK(); - return; - } - /* Pool was full, so doesn't currently live in any list: - * link it to the front of the appropriate usedpools[] list. - * This mimics LRU pool usage for new allocations and - * targets optimal filling when several pools contain - * blocks of the same size class. - */ - --pool->ref.count; - assert(pool->ref.count > 0); /* else the pool is empty */ - size = pool->szidx; - next = usedpools[size + size]; - prev = next->prevpool; - /* insert pool before next: prev <-> pool <-> next */ - pool->nextpool = next; - pool->prevpool = prev; - next->prevpool = pool; - prev->nextpool = pool; - UNLOCK(); - return; - } + pool = POOL_ADDR(p); + if (Py_ADDRESS_IN_RANGE(p, pool)) { + /* We allocated this address. */ + LOCK(); + /* Link p to the start of the pool's freeblock list. Since + * the pool had at least the p block outstanding, the pool + * wasn't empty (so it's already in a usedpools[] list, or + * was full and is in no list -- it's not in the freeblocks + * list in any case). + */ + assert(pool->ref.count > 0); /* else it was empty */ + *(block **)p = lastfree = pool->freeblock; + pool->freeblock = (block *)p; + if (lastfree) { + struct arena_object* ao; + uint nf; /* ao->nfreepools */ + + /* freeblock wasn't NULL, so the pool wasn't full, + * and the pool is in a usedpools[] list. + */ + if (--pool->ref.count != 0) { + /* pool isn't empty: leave it in usedpools */ + UNLOCK(); + return; + } + /* Pool is now empty: unlink from usedpools, and + * link to the front of freepools. This ensures that + * previously freed pools will be allocated later + * (being not referenced, they are perhaps paged out). + */ + next = pool->nextpool; + prev = pool->prevpool; + next->prevpool = prev; + prev->nextpool = next; + + /* Link the pool to freepools. This is a singly-linked + * list, and pool->prevpool isn't used there. + */ + ao = &arenas[pool->arenaindex]; + pool->nextpool = ao->freepools; + ao->freepools = pool; + nf = ++ao->nfreepools; + + /* All the rest is arena management. We just freed + * a pool, and there are 4 cases for arena mgmt: + * 1. If all the pools are free, return the arena to + * the system free(). + * 2. If this is the only free pool in the arena, + * add the arena back to the `usable_arenas` list. + * 3. If the "next" arena has a smaller count of free + * pools, we have to "slide this arena right" to + * restore that usable_arenas is sorted in order of + * nfreepools. + * 4. Else there's nothing more to do. + */ + if (nf == ao->ntotalpools) { + /* Case 1. First unlink ao from usable_arenas. + */ + assert(ao->prevarena == NULL || + ao->prevarena->address != 0); + assert(ao ->nextarena == NULL || + ao->nextarena->address != 0); + + /* Fix the pointer in the prevarena, or the + * usable_arenas pointer. + */ + if (ao->prevarena == NULL) { + usable_arenas = ao->nextarena; + assert(usable_arenas == NULL || + usable_arenas->address != 0); + } + else { + assert(ao->prevarena->nextarena == ao); + ao->prevarena->nextarena = + ao->nextarena; + } + /* Fix the pointer in the nextarena. */ + if (ao->nextarena != NULL) { + assert(ao->nextarena->prevarena == ao); + ao->nextarena->prevarena = + ao->prevarena; + } + /* Record that this arena_object slot is + * available to be reused. + */ + ao->nextarena = unused_arena_objects; + unused_arena_objects = ao; + + /* Free the entire arena. */ + free((void *)ao->address); + ao->address = 0; /* mark unassociated */ + --narenas_currently_allocated; + + UNLOCK(); + return; + } + if (nf == 1) { + /* Case 2. Put ao at the head of + * usable_arenas. Note that because + * ao->nfreepools was 0 before, ao isn't + * currently on the usable_arenas list. + */ + ao->nextarena = usable_arenas; + ao->prevarena = NULL; + if (usable_arenas) + usable_arenas->prevarena = ao; + usable_arenas = ao; + assert(usable_arenas->address != 0); + + UNLOCK(); + return; + } + /* If this arena is now out of order, we need to keep + * the list sorted. The list is kept sorted so that + * the "most full" arenas are used first, which allows + * the nearly empty arenas to be completely freed. In + * a few un-scientific tests, it seems like this + * approach allowed a lot more memory to be freed. + */ + if (ao->nextarena == NULL || + nf <= ao->nextarena->nfreepools) { + /* Case 4. Nothing to do. */ + UNLOCK(); + return; + } + /* Case 3: We have to move the arena towards the end + * of the list, because it has more free pools than + * the arena to its right. + * First unlink ao from usable_arenas. + */ + if (ao->prevarena != NULL) { + /* ao isn't at the head of the list */ + assert(ao->prevarena->nextarena == ao); + ao->prevarena->nextarena = ao->nextarena; + } + else { + /* ao is at the head of the list */ + assert(usable_arenas == ao); + usable_arenas = ao->nextarena; + } + ao->nextarena->prevarena = ao->prevarena; + + /* Locate the new insertion point by iterating over + * the list, using our nextarena pointer. + */ + while (ao->nextarena != NULL && + nf > ao->nextarena->nfreepools) { + ao->prevarena = ao->nextarena; + ao->nextarena = ao->nextarena->nextarena; + } + + /* Insert ao at this point. */ + assert(ao->nextarena == NULL || + ao->prevarena == ao->nextarena->prevarena); + assert(ao->prevarena->nextarena == ao->nextarena); + + ao->prevarena->nextarena = ao; + if (ao->nextarena != NULL) + ao->nextarena->prevarena = ao; + + /* Verify that the swaps worked. */ + assert(ao->nextarena == NULL || + nf <= ao->nextarena->nfreepools); + assert(ao->prevarena == NULL || + nf > ao->prevarena->nfreepools); + assert(ao->nextarena == NULL || + ao->nextarena->prevarena == ao); + assert((usable_arenas == ao && + ao->prevarena == NULL) || + ao->prevarena->nextarena == ao); + + UNLOCK(); + return; + } + /* Pool was full, so doesn't currently live in any list: + * link it to the front of the appropriate usedpools[] list. + * This mimics LRU pool usage for new allocations and + * targets optimal filling when several pools contain + * blocks of the same size class. + */ + --pool->ref.count; + assert(pool->ref.count > 0); /* else the pool is empty */ + size = pool->szidx; + next = usedpools[size + size]; + prev = next->prevpool; + /* insert pool before next: prev <-> pool <-> next */ + pool->nextpool = next; + pool->prevpool = prev; + next->prevpool = pool; + prev->nextpool = pool; + UNLOCK(); + return; + } #ifdef WITH_VALGRIND redirect: #endif - /* We didn't allocate this address. */ - free(p); + /* We didn't allocate this address. */ + free(p); } /* realloc. If p is NULL, this acts like malloc(nbytes). Else if nbytes==0, @@ -1164,81 +1164,81 @@ void * PyObject_Realloc(void *p, size_t nbytes) { - void *bp; - poolp pool; - size_t size; - - if (p == NULL) - return PyObject_Malloc(nbytes); - - /* - * Limit ourselves to PY_SSIZE_T_MAX bytes to prevent security holes. - * Most python internals blindly use a signed Py_ssize_t to track - * things without checking for overflows or negatives. - * As size_t is unsigned, checking for nbytes < 0 is not required. - */ - if (nbytes > PY_SSIZE_T_MAX) - return NULL; + void *bp; + poolp pool; + size_t size; + + if (p == NULL) + return PyObject_Malloc(nbytes); + + /* + * Limit ourselves to PY_SSIZE_T_MAX bytes to prevent security holes. + * Most python internals blindly use a signed Py_ssize_t to track + * things without checking for overflows or negatives. + * As size_t is unsigned, checking for nbytes < 0 is not required. + */ + if (nbytes > PY_SSIZE_T_MAX) + return NULL; #ifdef WITH_VALGRIND - /* Treat running_on_valgrind == -1 the same as 0 */ - if (UNLIKELY(running_on_valgrind > 0)) - goto redirect; + /* Treat running_on_valgrind == -1 the same as 0 */ + if (UNLIKELY(running_on_valgrind > 0)) + goto redirect; #endif - pool = POOL_ADDR(p); - if (Py_ADDRESS_IN_RANGE(p, pool)) { - /* We're in charge of this block */ - size = INDEX2SIZE(pool->szidx); - if (nbytes <= size) { - /* The block is staying the same or shrinking. If - * it's shrinking, there's a tradeoff: it costs - * cycles to copy the block to a smaller size class, - * but it wastes memory not to copy it. The - * compromise here is to copy on shrink only if at - * least 25% of size can be shaved off. - */ - if (4 * nbytes > 3 * size) { - /* It's the same, - * or shrinking and new/old > 3/4. - */ - return p; - } - size = nbytes; - } - bp = PyObject_Malloc(nbytes); - if (bp != NULL) { - memcpy(bp, p, size); - PyObject_Free(p); - } - return bp; - } + pool = POOL_ADDR(p); + if (Py_ADDRESS_IN_RANGE(p, pool)) { + /* We're in charge of this block */ + size = INDEX2SIZE(pool->szidx); + if (nbytes <= size) { + /* The block is staying the same or shrinking. If + * it's shrinking, there's a tradeoff: it costs + * cycles to copy the block to a smaller size class, + * but it wastes memory not to copy it. The + * compromise here is to copy on shrink only if at + * least 25% of size can be shaved off. + */ + if (4 * nbytes > 3 * size) { + /* It's the same, + * or shrinking and new/old > 3/4. + */ + return p; + } + size = nbytes; + } + bp = PyObject_Malloc(nbytes); + if (bp != NULL) { + memcpy(bp, p, size); + PyObject_Free(p); + } + return bp; + } #ifdef WITH_VALGRIND redirect: #endif - /* We're not managing this block. If nbytes <= - * SMALL_REQUEST_THRESHOLD, it's tempting to try to take over this - * block. However, if we do, we need to copy the valid data from - * the C-managed block to one of our blocks, and there's no portable - * way to know how much of the memory space starting at p is valid. - * As bug 1185883 pointed out the hard way, it's possible that the - * C-managed block is "at the end" of allocated VM space, so that - * a memory fault can occur if we try to copy nbytes bytes starting - * at p. Instead we punt: let C continue to manage this block. - */ - if (nbytes) - return realloc(p, nbytes); - /* C doesn't define the result of realloc(p, 0) (it may or may not - * return NULL then), but Python's docs promise that nbytes==0 never - * returns NULL. We don't pass 0 to realloc(), to avoid that endcase - * to begin with. Even then, we can't be sure that realloc() won't - * return NULL. - */ - bp = realloc(p, 1); - return bp ? bp : p; + /* We're not managing this block. If nbytes <= + * SMALL_REQUEST_THRESHOLD, it's tempting to try to take over this + * block. However, if we do, we need to copy the valid data from + * the C-managed block to one of our blocks, and there's no portable + * way to know how much of the memory space starting at p is valid. + * As bug 1185883 pointed out the hard way, it's possible that the + * C-managed block is "at the end" of allocated VM space, so that + * a memory fault can occur if we try to copy nbytes bytes starting + * at p. Instead we punt: let C continue to manage this block. + */ + if (nbytes) + return realloc(p, nbytes); + /* C doesn't define the result of realloc(p, 0) (it may or may not + * return NULL then), but Python's docs promise that nbytes==0 never + * returns NULL. We don't pass 0 to realloc(), to avoid that endcase + * to begin with. Even then, we can't be sure that realloc() won't + * return NULL. + */ + bp = realloc(p, 1); + return bp ? bp : p; } -#else /* ! WITH_PYMALLOC */ +#else /* ! WITH_PYMALLOC */ /*==========================================================================*/ /* pymalloc not enabled: Redirect the entry points to malloc. These will @@ -1247,19 +1247,19 @@ void * PyObject_Malloc(size_t n) { - return PyMem_MALLOC(n); + return PyMem_MALLOC(n); } void * PyObject_Realloc(void *p, size_t n) { - return PyMem_REALLOC(p, n); + return PyMem_REALLOC(p, n); } void PyObject_Free(void *p) { - PyMem_FREE(p); + PyMem_FREE(p); } #endif /* WITH_PYMALLOC */ @@ -1284,7 +1284,7 @@ #define _PYMALLOC_MEM_ID 'm' /* the PyMem_Malloc() API */ #define _PYMALLOC_OBJ_ID 'o' /* The PyObject_Malloc() API */ -static size_t serialno = 0; /* incremented on each debug {m,re}alloc */ +static size_t serialno = 0; /* incremented on each debug {m,re}alloc */ /* serialno is always incremented via calling this routine. The point is * to supply a single place to set a breakpoint. @@ -1292,7 +1292,7 @@ static void bumpserialno(void) { - ++serialno; + ++serialno; } #define SST SIZEOF_SIZE_T @@ -1301,13 +1301,13 @@ static size_t read_size_t(const void *p) { - const uchar *q = (const uchar *)p; - size_t result = *q++; - int i; - - for (i = SST; --i > 0; ++q) - result = (result << 8) | *q; - return result; + const uchar *q = (const uchar *)p; + size_t result = *q++; + int i; + + for (i = SST; --i > 0; ++q) + result = (result << 8) | *q; + return result; } /* Write n as a big-endian size_t, MSB at address p, LSB at @@ -1316,13 +1316,13 @@ static void write_size_t(void *p, size_t n) { - uchar *q = (uchar *)p + SST - 1; - int i; + uchar *q = (uchar *)p + SST - 1; + int i; - for (i = SST; --i >= 0; --q) { - *q = (uchar)(n & 0xff); - n >>= 8; - } + for (i = SST; --i >= 0; --q) { + *q = (uchar)(n & 0xff); + n >>= 8; + } } #ifdef Py_DEBUG @@ -1333,22 +1333,22 @@ static int pool_is_in_list(const poolp target, poolp list) { - poolp origlist = list; - assert(target != NULL); - if (list == NULL) - return 0; - do { - if (target == list) - return 1; - list = list->nextpool; - } while (list != NULL && list != origlist); - return 0; + poolp origlist = list; + assert(target != NULL); + if (list == NULL) + return 0; + do { + if (target == list) + return 1; + list = list->nextpool; + } while (list != NULL && list != origlist); + return 0; } #else #define pool_is_in_list(X, Y) 1 -#endif /* Py_DEBUG */ +#endif /* Py_DEBUG */ /* Let S = sizeof(size_t). The debug malloc asks for 4*S extra bytes and fills them with useful stuff, here calling the underlying malloc's result p: @@ -1378,39 +1378,39 @@ void * _PyMem_DebugMalloc(size_t nbytes) { - return _PyObject_DebugMallocApi(_PYMALLOC_MEM_ID, nbytes); + return _PyObject_DebugMallocApi(_PYMALLOC_MEM_ID, nbytes); } void * _PyMem_DebugRealloc(void *p, size_t nbytes) { - return _PyObject_DebugReallocApi(_PYMALLOC_MEM_ID, p, nbytes); + return _PyObject_DebugReallocApi(_PYMALLOC_MEM_ID, p, nbytes); } void _PyMem_DebugFree(void *p) { - _PyObject_DebugFreeApi(_PYMALLOC_MEM_ID, p); + _PyObject_DebugFreeApi(_PYMALLOC_MEM_ID, p); } /* debug replacements for the PyObject_* memory API */ void * _PyObject_DebugMalloc(size_t nbytes) { - return _PyObject_DebugMallocApi(_PYMALLOC_OBJ_ID, nbytes); + return _PyObject_DebugMallocApi(_PYMALLOC_OBJ_ID, nbytes); } void * _PyObject_DebugRealloc(void *p, size_t nbytes) { - return _PyObject_DebugReallocApi(_PYMALLOC_OBJ_ID, p, nbytes); + return _PyObject_DebugReallocApi(_PYMALLOC_OBJ_ID, p, nbytes); } void _PyObject_DebugFree(void *p) { - _PyObject_DebugFreeApi(_PYMALLOC_OBJ_ID, p); + _PyObject_DebugFreeApi(_PYMALLOC_OBJ_ID, p); } void _PyObject_DebugCheckAddress(const void *p) { - _PyObject_DebugCheckAddressApi(_PYMALLOC_OBJ_ID, p); + _PyObject_DebugCheckAddressApi(_PYMALLOC_OBJ_ID, p); } @@ -1418,34 +1418,34 @@ void * _PyObject_DebugMallocApi(char id, size_t nbytes) { - uchar *p; /* base address of malloc'ed block */ - uchar *tail; /* p + 2*SST + nbytes == pointer to tail pad bytes */ - size_t total; /* nbytes + 4*SST */ - - bumpserialno(); - total = nbytes + 4*SST; - if (total < nbytes) - /* overflow: can't represent total as a size_t */ - return NULL; - - p = (uchar *)PyObject_Malloc(total); - if (p == NULL) - return NULL; - - /* at p, write size (SST bytes), id (1 byte), pad (SST-1 bytes) */ - write_size_t(p, nbytes); - p[SST] = (uchar)id; - memset(p + SST + 1 , FORBIDDENBYTE, SST-1); - - if (nbytes > 0) - memset(p + 2*SST, CLEANBYTE, nbytes); - - /* at tail, write pad (SST bytes) and serialno (SST bytes) */ - tail = p + 2*SST + nbytes; - memset(tail, FORBIDDENBYTE, SST); - write_size_t(tail + SST, serialno); + uchar *p; /* base address of malloc'ed block */ + uchar *tail; /* p + 2*SST + nbytes == pointer to tail pad bytes */ + size_t total; /* nbytes + 4*SST */ + + bumpserialno(); + total = nbytes + 4*SST; + if (total < nbytes) + /* overflow: can't represent total as a size_t */ + return NULL; + + p = (uchar *)PyObject_Malloc(total); + if (p == NULL) + return NULL; + + /* at p, write size (SST bytes), id (1 byte), pad (SST-1 bytes) */ + write_size_t(p, nbytes); + p[SST] = (uchar)id; + memset(p + SST + 1 , FORBIDDENBYTE, SST-1); + + if (nbytes > 0) + memset(p + 2*SST, CLEANBYTE, nbytes); + + /* at tail, write pad (SST bytes) and serialno (SST bytes) */ + tail = p + 2*SST + nbytes; + memset(tail, FORBIDDENBYTE, SST); + write_size_t(tail + SST, serialno); - return p + 2*SST; + return p + 2*SST; } /* The debug free first checks the 2*SST bytes on each end for sanity (in @@ -1456,68 +1456,68 @@ void _PyObject_DebugFreeApi(char api, void *p) { - uchar *q = (uchar *)p - 2*SST; /* address returned from malloc */ - size_t nbytes; + uchar *q = (uchar *)p - 2*SST; /* address returned from malloc */ + size_t nbytes; - if (p == NULL) - return; - _PyObject_DebugCheckAddressApi(api, p); - nbytes = read_size_t(q); - nbytes += 4*SST; - if (nbytes > 0) - memset(q, DEADBYTE, nbytes); - PyObject_Free(q); + if (p == NULL) + return; + _PyObject_DebugCheckAddressApi(api, p); + nbytes = read_size_t(q); + nbytes += 4*SST; + if (nbytes > 0) + memset(q, DEADBYTE, nbytes); + PyObject_Free(q); } void * _PyObject_DebugReallocApi(char api, void *p, size_t nbytes) { - uchar *q = (uchar *)p; - uchar *tail; - size_t total; /* nbytes + 4*SST */ - size_t original_nbytes; - int i; - - if (p == NULL) - return _PyObject_DebugMallocApi(api, nbytes); - - _PyObject_DebugCheckAddressApi(api, p); - bumpserialno(); - original_nbytes = read_size_t(q - 2*SST); - total = nbytes + 4*SST; - if (total < nbytes) - /* overflow: can't represent total as a size_t */ - return NULL; - - if (nbytes < original_nbytes) { - /* shrinking: mark old extra memory dead */ - memset(q + nbytes, DEADBYTE, original_nbytes - nbytes + 2*SST); - } - - /* Resize and add decorations. We may get a new pointer here, in which - * case we didn't get the chance to mark the old memory with DEADBYTE, - * but we live with that. - */ - q = (uchar *)PyObject_Realloc(q - 2*SST, total); - if (q == NULL) - return NULL; - - write_size_t(q, nbytes); - assert(q[SST] == (uchar)api); - for (i = 1; i < SST; ++i) - assert(q[SST + i] == FORBIDDENBYTE); - q += 2*SST; - tail = q + nbytes; - memset(tail, FORBIDDENBYTE, SST); - write_size_t(tail + SST, serialno); - - if (nbytes > original_nbytes) { - /* growing: mark new extra memory clean */ - memset(q + original_nbytes, CLEANBYTE, - nbytes - original_nbytes); - } + uchar *q = (uchar *)p; + uchar *tail; + size_t total; /* nbytes + 4*SST */ + size_t original_nbytes; + int i; + + if (p == NULL) + return _PyObject_DebugMallocApi(api, nbytes); + + _PyObject_DebugCheckAddressApi(api, p); + bumpserialno(); + original_nbytes = read_size_t(q - 2*SST); + total = nbytes + 4*SST; + if (total < nbytes) + /* overflow: can't represent total as a size_t */ + return NULL; + + if (nbytes < original_nbytes) { + /* shrinking: mark old extra memory dead */ + memset(q + nbytes, DEADBYTE, original_nbytes - nbytes + 2*SST); + } + + /* Resize and add decorations. We may get a new pointer here, in which + * case we didn't get the chance to mark the old memory with DEADBYTE, + * but we live with that. + */ + q = (uchar *)PyObject_Realloc(q - 2*SST, total); + if (q == NULL) + return NULL; + + write_size_t(q, nbytes); + assert(q[SST] == (uchar)api); + for (i = 1; i < SST; ++i) + assert(q[SST + i] == FORBIDDENBYTE); + q += 2*SST; + tail = q + nbytes; + memset(tail, FORBIDDENBYTE, SST); + write_size_t(tail + SST, serialno); + + if (nbytes > original_nbytes) { + /* growing: mark new extra memory clean */ + memset(q + original_nbytes, CLEANBYTE, + nbytes - original_nbytes); + } - return q; + return q; } /* Check the forbidden bytes on both ends of the memory allocated for p. @@ -1528,192 +1528,192 @@ void _PyObject_DebugCheckAddressApi(char api, const void *p) { - const uchar *q = (const uchar *)p; - char msgbuf[64]; - char *msg; - size_t nbytes; - const uchar *tail; - int i; - char id; - - if (p == NULL) { - msg = "didn't expect a NULL pointer"; - goto error; - } - - /* Check the API id */ - id = (char)q[-SST]; - if (id != api) { - msg = msgbuf; - snprintf(msg, sizeof(msgbuf), "bad ID: Allocated using API '%c', verified using API '%c'", id, api); - msgbuf[sizeof(msgbuf)-1] = 0; - goto error; - } - - /* Check the stuff at the start of p first: if there's underwrite - * corruption, the number-of-bytes field may be nuts, and checking - * the tail could lead to a segfault then. - */ - for (i = SST-1; i >= 1; --i) { - if (*(q-i) != FORBIDDENBYTE) { - msg = "bad leading pad byte"; - goto error; - } - } - - nbytes = read_size_t(q - 2*SST); - tail = q + nbytes; - for (i = 0; i < SST; ++i) { - if (tail[i] != FORBIDDENBYTE) { - msg = "bad trailing pad byte"; - goto error; - } - } + const uchar *q = (const uchar *)p; + char msgbuf[64]; + char *msg; + size_t nbytes; + const uchar *tail; + int i; + char id; + + if (p == NULL) { + msg = "didn't expect a NULL pointer"; + goto error; + } + + /* Check the API id */ + id = (char)q[-SST]; + if (id != api) { + msg = msgbuf; + snprintf(msg, sizeof(msgbuf), "bad ID: Allocated using API '%c', verified using API '%c'", id, api); + msgbuf[sizeof(msgbuf)-1] = 0; + goto error; + } + + /* Check the stuff at the start of p first: if there's underwrite + * corruption, the number-of-bytes field may be nuts, and checking + * the tail could lead to a segfault then. + */ + for (i = SST-1; i >= 1; --i) { + if (*(q-i) != FORBIDDENBYTE) { + msg = "bad leading pad byte"; + goto error; + } + } + + nbytes = read_size_t(q - 2*SST); + tail = q + nbytes; + for (i = 0; i < SST; ++i) { + if (tail[i] != FORBIDDENBYTE) { + msg = "bad trailing pad byte"; + goto error; + } + } - return; + return; error: - _PyObject_DebugDumpAddress(p); - Py_FatalError(msg); + _PyObject_DebugDumpAddress(p); + Py_FatalError(msg); } /* Display info to stderr about the memory block at p. */ void _PyObject_DebugDumpAddress(const void *p) { - const uchar *q = (const uchar *)p; - const uchar *tail; - size_t nbytes, serial; - int i; - int ok; - char id; - - fprintf(stderr, "Debug memory block at address p=%p:", p); - if (p == NULL) { - fprintf(stderr, "\n"); - return; - } - id = (char)q[-SST]; - fprintf(stderr, " API '%c'\n", id); - - nbytes = read_size_t(q - 2*SST); - fprintf(stderr, " %" PY_FORMAT_SIZE_T "u bytes originally " - "requested\n", nbytes); - - /* In case this is nuts, check the leading pad bytes first. */ - fprintf(stderr, " The %d pad bytes at p-%d are ", SST-1, SST-1); - ok = 1; - for (i = 1; i <= SST-1; ++i) { - if (*(q-i) != FORBIDDENBYTE) { - ok = 0; - break; - } - } - if (ok) - fputs("FORBIDDENBYTE, as expected.\n", stderr); - else { - fprintf(stderr, "not all FORBIDDENBYTE (0x%02x):\n", - FORBIDDENBYTE); - for (i = SST-1; i >= 1; --i) { - const uchar byte = *(q-i); - fprintf(stderr, " at p-%d: 0x%02x", i, byte); - if (byte != FORBIDDENBYTE) - fputs(" *** OUCH", stderr); - fputc('\n', stderr); - } - - fputs(" Because memory is corrupted at the start, the " - "count of bytes requested\n" - " may be bogus, and checking the trailing pad " - "bytes may segfault.\n", stderr); - } - - tail = q + nbytes; - fprintf(stderr, " The %d pad bytes at tail=%p are ", SST, tail); - ok = 1; - for (i = 0; i < SST; ++i) { - if (tail[i] != FORBIDDENBYTE) { - ok = 0; - break; - } - } - if (ok) - fputs("FORBIDDENBYTE, as expected.\n", stderr); - else { - fprintf(stderr, "not all FORBIDDENBYTE (0x%02x):\n", - FORBIDDENBYTE); - for (i = 0; i < SST; ++i) { - const uchar byte = tail[i]; - fprintf(stderr, " at tail+%d: 0x%02x", - i, byte); - if (byte != FORBIDDENBYTE) - fputs(" *** OUCH", stderr); - fputc('\n', stderr); - } - } - - serial = read_size_t(tail + SST); - fprintf(stderr, " The block was made by call #%" PY_FORMAT_SIZE_T - "u to debug malloc/realloc.\n", serial); - - if (nbytes > 0) { - i = 0; - fputs(" Data at p:", stderr); - /* print up to 8 bytes at the start */ - while (q < tail && i < 8) { - fprintf(stderr, " %02x", *q); - ++i; - ++q; - } - /* and up to 8 at the end */ - if (q < tail) { - if (tail - q > 8) { - fputs(" ...", stderr); - q = tail - 8; - } - while (q < tail) { - fprintf(stderr, " %02x", *q); - ++q; - } - } - fputc('\n', stderr); - } + const uchar *q = (const uchar *)p; + const uchar *tail; + size_t nbytes, serial; + int i; + int ok; + char id; + + fprintf(stderr, "Debug memory block at address p=%p:", p); + if (p == NULL) { + fprintf(stderr, "\n"); + return; + } + id = (char)q[-SST]; + fprintf(stderr, " API '%c'\n", id); + + nbytes = read_size_t(q - 2*SST); + fprintf(stderr, " %" PY_FORMAT_SIZE_T "u bytes originally " + "requested\n", nbytes); + + /* In case this is nuts, check the leading pad bytes first. */ + fprintf(stderr, " The %d pad bytes at p-%d are ", SST-1, SST-1); + ok = 1; + for (i = 1; i <= SST-1; ++i) { + if (*(q-i) != FORBIDDENBYTE) { + ok = 0; + break; + } + } + if (ok) + fputs("FORBIDDENBYTE, as expected.\n", stderr); + else { + fprintf(stderr, "not all FORBIDDENBYTE (0x%02x):\n", + FORBIDDENBYTE); + for (i = SST-1; i >= 1; --i) { + const uchar byte = *(q-i); + fprintf(stderr, " at p-%d: 0x%02x", i, byte); + if (byte != FORBIDDENBYTE) + fputs(" *** OUCH", stderr); + fputc('\n', stderr); + } + + fputs(" Because memory is corrupted at the start, the " + "count of bytes requested\n" + " may be bogus, and checking the trailing pad " + "bytes may segfault.\n", stderr); + } + + tail = q + nbytes; + fprintf(stderr, " The %d pad bytes at tail=%p are ", SST, tail); + ok = 1; + for (i = 0; i < SST; ++i) { + if (tail[i] != FORBIDDENBYTE) { + ok = 0; + break; + } + } + if (ok) + fputs("FORBIDDENBYTE, as expected.\n", stderr); + else { + fprintf(stderr, "not all FORBIDDENBYTE (0x%02x):\n", + FORBIDDENBYTE); + for (i = 0; i < SST; ++i) { + const uchar byte = tail[i]; + fprintf(stderr, " at tail+%d: 0x%02x", + i, byte); + if (byte != FORBIDDENBYTE) + fputs(" *** OUCH", stderr); + fputc('\n', stderr); + } + } + + serial = read_size_t(tail + SST); + fprintf(stderr, " The block was made by call #%" PY_FORMAT_SIZE_T + "u to debug malloc/realloc.\n", serial); + + if (nbytes > 0) { + i = 0; + fputs(" Data at p:", stderr); + /* print up to 8 bytes at the start */ + while (q < tail && i < 8) { + fprintf(stderr, " %02x", *q); + ++i; + ++q; + } + /* and up to 8 at the end */ + if (q < tail) { + if (tail - q > 8) { + fputs(" ...", stderr); + q = tail - 8; + } + while (q < tail) { + fprintf(stderr, " %02x", *q); + ++q; + } + } + fputc('\n', stderr); + } } static size_t printone(const char* msg, size_t value) { - int i, k; - char buf[100]; - size_t origvalue = value; - - fputs(msg, stderr); - for (i = (int)strlen(msg); i < 35; ++i) - fputc(' ', stderr); - fputc('=', stderr); - - /* Write the value with commas. */ - i = 22; - buf[i--] = '\0'; - buf[i--] = '\n'; - k = 3; - do { - size_t nextvalue = value / 10; - uint digit = (uint)(value - nextvalue * 10); - value = nextvalue; - buf[i--] = (char)(digit + '0'); - --k; - if (k == 0 && value && i >= 0) { - k = 3; - buf[i--] = ','; - } - } while (value && i >= 0); - - while (i >= 0) - buf[i--] = ' '; - fputs(buf, stderr); + int i, k; + char buf[100]; + size_t origvalue = value; + + fputs(msg, stderr); + for (i = (int)strlen(msg); i < 35; ++i) + fputc(' ', stderr); + fputc('=', stderr); + + /* Write the value with commas. */ + i = 22; + buf[i--] = '\0'; + buf[i--] = '\n'; + k = 3; + do { + size_t nextvalue = value / 10; + uint digit = (uint)(value - nextvalue * 10); + value = nextvalue; + buf[i--] = (char)(digit + '0'); + --k; + if (k == 0 && value && i >= 0) { + k = 3; + buf[i--] = ','; + } + } while (value && i >= 0); + + while (i >= 0) + buf[i--] = ' '; + fputs(buf, stderr); - return origvalue; + return origvalue; } /* Print summary info to stderr about the state of pymalloc's structures. @@ -1723,142 +1723,142 @@ void _PyObject_DebugMallocStats(void) { - uint i; - const uint numclasses = SMALL_REQUEST_THRESHOLD >> ALIGNMENT_SHIFT; - /* # of pools, allocated blocks, and free blocks per class index */ - size_t numpools[SMALL_REQUEST_THRESHOLD >> ALIGNMENT_SHIFT]; - size_t numblocks[SMALL_REQUEST_THRESHOLD >> ALIGNMENT_SHIFT]; - size_t numfreeblocks[SMALL_REQUEST_THRESHOLD >> ALIGNMENT_SHIFT]; - /* total # of allocated bytes in used and full pools */ - size_t allocated_bytes = 0; - /* total # of available bytes in used pools */ - size_t available_bytes = 0; - /* # of free pools + pools not yet carved out of current arena */ - uint numfreepools = 0; - /* # of bytes for arena alignment padding */ - size_t arena_alignment = 0; - /* # of bytes in used and full pools used for pool_headers */ - size_t pool_header_bytes = 0; - /* # of bytes in used and full pools wasted due to quantization, - * i.e. the necessarily leftover space at the ends of used and - * full pools. - */ - size_t quantization = 0; - /* # of arenas actually allocated. */ - size_t narenas = 0; - /* running total -- should equal narenas * ARENA_SIZE */ - size_t total; - char buf[128]; - - fprintf(stderr, "Small block threshold = %d, in %u size classes.\n", - SMALL_REQUEST_THRESHOLD, numclasses); - - for (i = 0; i < numclasses; ++i) - numpools[i] = numblocks[i] = numfreeblocks[i] = 0; - - /* Because full pools aren't linked to from anything, it's easiest - * to march over all the arenas. If we're lucky, most of the memory - * will be living in full pools -- would be a shame to miss them. - */ - for (i = 0; i < maxarenas; ++i) { - uint poolsinarena; - uint j; - uptr base = arenas[i].address; - - /* Skip arenas which are not allocated. */ - if (arenas[i].address == (uptr)NULL) - continue; - narenas += 1; - - poolsinarena = arenas[i].ntotalpools; - numfreepools += arenas[i].nfreepools; - - /* round up to pool alignment */ - if (base & (uptr)POOL_SIZE_MASK) { - arena_alignment += POOL_SIZE; - base &= ~(uptr)POOL_SIZE_MASK; - base += POOL_SIZE; - } - - /* visit every pool in the arena */ - assert(base <= (uptr) arenas[i].pool_address); - for (j = 0; - base < (uptr) arenas[i].pool_address; - ++j, base += POOL_SIZE) { - poolp p = (poolp)base; - const uint sz = p->szidx; - uint freeblocks; - - if (p->ref.count == 0) { - /* currently unused */ - assert(pool_is_in_list(p, arenas[i].freepools)); - continue; - } - ++numpools[sz]; - numblocks[sz] += p->ref.count; - freeblocks = NUMBLOCKS(sz) - p->ref.count; - numfreeblocks[sz] += freeblocks; + uint i; + const uint numclasses = SMALL_REQUEST_THRESHOLD >> ALIGNMENT_SHIFT; + /* # of pools, allocated blocks, and free blocks per class index */ + size_t numpools[SMALL_REQUEST_THRESHOLD >> ALIGNMENT_SHIFT]; + size_t numblocks[SMALL_REQUEST_THRESHOLD >> ALIGNMENT_SHIFT]; + size_t numfreeblocks[SMALL_REQUEST_THRESHOLD >> ALIGNMENT_SHIFT]; + /* total # of allocated bytes in used and full pools */ + size_t allocated_bytes = 0; + /* total # of available bytes in used pools */ + size_t available_bytes = 0; + /* # of free pools + pools not yet carved out of current arena */ + uint numfreepools = 0; + /* # of bytes for arena alignment padding */ + size_t arena_alignment = 0; + /* # of bytes in used and full pools used for pool_headers */ + size_t pool_header_bytes = 0; + /* # of bytes in used and full pools wasted due to quantization, + * i.e. the necessarily leftover space at the ends of used and + * full pools. + */ + size_t quantization = 0; + /* # of arenas actually allocated. */ + size_t narenas = 0; + /* running total -- should equal narenas * ARENA_SIZE */ + size_t total; + char buf[128]; + + fprintf(stderr, "Small block threshold = %d, in %u size classes.\n", + SMALL_REQUEST_THRESHOLD, numclasses); + + for (i = 0; i < numclasses; ++i) + numpools[i] = numblocks[i] = numfreeblocks[i] = 0; + + /* Because full pools aren't linked to from anything, it's easiest + * to march over all the arenas. If we're lucky, most of the memory + * will be living in full pools -- would be a shame to miss them. + */ + for (i = 0; i < maxarenas; ++i) { + uint poolsinarena; + uint j; + uptr base = arenas[i].address; + + /* Skip arenas which are not allocated. */ + if (arenas[i].address == (uptr)NULL) + continue; + narenas += 1; + + poolsinarena = arenas[i].ntotalpools; + numfreepools += arenas[i].nfreepools; + + /* round up to pool alignment */ + if (base & (uptr)POOL_SIZE_MASK) { + arena_alignment += POOL_SIZE; + base &= ~(uptr)POOL_SIZE_MASK; + base += POOL_SIZE; + } + + /* visit every pool in the arena */ + assert(base <= (uptr) arenas[i].pool_address); + for (j = 0; + base < (uptr) arenas[i].pool_address; + ++j, base += POOL_SIZE) { + poolp p = (poolp)base; + const uint sz = p->szidx; + uint freeblocks; + + if (p->ref.count == 0) { + /* currently unused */ + assert(pool_is_in_list(p, arenas[i].freepools)); + continue; + } + ++numpools[sz]; + numblocks[sz] += p->ref.count; + freeblocks = NUMBLOCKS(sz) - p->ref.count; + numfreeblocks[sz] += freeblocks; #ifdef Py_DEBUG - if (freeblocks > 0) - assert(pool_is_in_list(p, usedpools[sz + sz])); + if (freeblocks > 0) + assert(pool_is_in_list(p, usedpools[sz + sz])); #endif - } - } - assert(narenas == narenas_currently_allocated); - - fputc('\n', stderr); - fputs("class size num pools blocks in use avail blocks\n" - "----- ---- --------- ------------- ------------\n", - stderr); - - for (i = 0; i < numclasses; ++i) { - size_t p = numpools[i]; - size_t b = numblocks[i]; - size_t f = numfreeblocks[i]; - uint size = INDEX2SIZE(i); - if (p == 0) { - assert(b == 0 && f == 0); - continue; - } - fprintf(stderr, "%5u %6u " - "%11" PY_FORMAT_SIZE_T "u " - "%15" PY_FORMAT_SIZE_T "u " - "%13" PY_FORMAT_SIZE_T "u\n", - i, size, p, b, f); - allocated_bytes += b * size; - available_bytes += f * size; - pool_header_bytes += p * POOL_OVERHEAD; - quantization += p * ((POOL_SIZE - POOL_OVERHEAD) % size); - } - fputc('\n', stderr); - (void)printone("# times object malloc called", serialno); - - (void)printone("# arenas allocated total", ntimes_arena_allocated); - (void)printone("# arenas reclaimed", ntimes_arena_allocated - narenas); - (void)printone("# arenas highwater mark", narenas_highwater); - (void)printone("# arenas allocated current", narenas); - - PyOS_snprintf(buf, sizeof(buf), - "%" PY_FORMAT_SIZE_T "u arenas * %d bytes/arena", - narenas, ARENA_SIZE); - (void)printone(buf, narenas * ARENA_SIZE); - - fputc('\n', stderr); - - total = printone("# bytes in allocated blocks", allocated_bytes); - total += printone("# bytes in available blocks", available_bytes); - - PyOS_snprintf(buf, sizeof(buf), - "%u unused pools * %d bytes", numfreepools, POOL_SIZE); - total += printone(buf, (size_t)numfreepools * POOL_SIZE); - - total += printone("# bytes lost to pool headers", pool_header_bytes); - total += printone("# bytes lost to quantization", quantization); - total += printone("# bytes lost to arena alignment", arena_alignment); - (void)printone("Total", total); + } + } + assert(narenas == narenas_currently_allocated); + + fputc('\n', stderr); + fputs("class size num pools blocks in use avail blocks\n" + "----- ---- --------- ------------- ------------\n", + stderr); + + for (i = 0; i < numclasses; ++i) { + size_t p = numpools[i]; + size_t b = numblocks[i]; + size_t f = numfreeblocks[i]; + uint size = INDEX2SIZE(i); + if (p == 0) { + assert(b == 0 && f == 0); + continue; + } + fprintf(stderr, "%5u %6u " + "%11" PY_FORMAT_SIZE_T "u " + "%15" PY_FORMAT_SIZE_T "u " + "%13" PY_FORMAT_SIZE_T "u\n", + i, size, p, b, f); + allocated_bytes += b * size; + available_bytes += f * size; + pool_header_bytes += p * POOL_OVERHEAD; + quantization += p * ((POOL_SIZE - POOL_OVERHEAD) % size); + } + fputc('\n', stderr); + (void)printone("# times object malloc called", serialno); + + (void)printone("# arenas allocated total", ntimes_arena_allocated); + (void)printone("# arenas reclaimed", ntimes_arena_allocated - narenas); + (void)printone("# arenas highwater mark", narenas_highwater); + (void)printone("# arenas allocated current", narenas); + + PyOS_snprintf(buf, sizeof(buf), + "%" PY_FORMAT_SIZE_T "u arenas * %d bytes/arena", + narenas, ARENA_SIZE); + (void)printone(buf, narenas * ARENA_SIZE); + + fputc('\n', stderr); + + total = printone("# bytes in allocated blocks", allocated_bytes); + total += printone("# bytes in available blocks", available_bytes); + + PyOS_snprintf(buf, sizeof(buf), + "%u unused pools * %d bytes", numfreepools, POOL_SIZE); + total += printone(buf, (size_t)numfreepools * POOL_SIZE); + + total += printone("# bytes lost to pool headers", pool_header_bytes); + total += printone("# bytes lost to quantization", quantization); + total += printone("# bytes lost to arena alignment", arena_alignment); + (void)printone("Total", total); } -#endif /* PYMALLOC_DEBUG */ +#endif /* PYMALLOC_DEBUG */ #ifdef Py_USING_MEMORY_DEBUGGER /* Make this function last so gcc won't inline it since the definition is @@ -1867,8 +1867,8 @@ int Py_ADDRESS_IN_RANGE(void *P, poolp pool) { - return pool->arenaindex < maxarenas && - (uptr)P - arenas[pool->arenaindex].address < (uptr)ARENA_SIZE && - arenas[pool->arenaindex].address != 0; + return pool->arenaindex < maxarenas && + (uptr)P - arenas[pool->arenaindex].address < (uptr)ARENA_SIZE && + arenas[pool->arenaindex].address != 0; } #endif Modified: python/branches/py3k/Objects/rangeobject.c ============================================================================== --- python/branches/py3k/Objects/rangeobject.c (original) +++ python/branches/py3k/Objects/rangeobject.c Sun May 9 17:52:27 2010 @@ -17,7 +17,7 @@ } rangeobject; /* Helper function for validating step. Always returns a new reference or - NULL on error. + NULL on error. */ static PyObject * validate_step(PyObject *step) @@ -269,7 +269,7 @@ static PyObject * range_reduce(rangeobject *r, PyObject *args) { - return Py_BuildValue("(O(OOO))", Py_TYPE(r), + return Py_BuildValue("(O(OOO))", Py_TYPE(r), r->start, r->stop, r->step); } @@ -328,11 +328,11 @@ } static PySequenceMethods range_as_sequence = { - (lenfunc)range_length, /* sq_length */ - 0, /* sq_concat */ - 0, /* sq_repeat */ + (lenfunc)range_length, /* sq_length */ + 0, /* sq_concat */ + 0, /* sq_repeat */ (ssizeargfunc)range_item, /* sq_item */ - 0, /* sq_slice */ + 0, /* sq_slice */ 0, /* sq_ass_item */ 0, /* sq_ass_slice */ (objobjproc)range_contains, /* sq_contains */ @@ -345,51 +345,51 @@ "Returns a reverse iterator."); static PyMethodDef range_methods[] = { - {"__reversed__", (PyCFunction)range_reverse, METH_NOARGS, - reverse_doc}, - {"__reduce__", (PyCFunction)range_reduce, METH_VARARGS}, - {NULL, NULL} /* sentinel */ + {"__reversed__", (PyCFunction)range_reverse, METH_NOARGS, + reverse_doc}, + {"__reduce__", (PyCFunction)range_reduce, METH_VARARGS}, + {NULL, NULL} /* sentinel */ }; PyTypeObject PyRange_Type = { - PyVarObject_HEAD_INIT(&PyType_Type, 0) - "range", /* Name of this type */ - sizeof(rangeobject), /* Basic object size */ - 0, /* Item size for varobject */ - (destructor)range_dealloc, /* tp_dealloc */ - 0, /* tp_print */ - 0, /* tp_getattr */ - 0, /* tp_setattr */ - 0, /* tp_reserved */ - (reprfunc)range_repr, /* tp_repr */ - 0, /* tp_as_number */ - &range_as_sequence, /* tp_as_sequence */ - 0, /* tp_as_mapping */ - 0, /* tp_hash */ - 0, /* tp_call */ - 0, /* tp_str */ - PyObject_GenericGetAttr, /* tp_getattro */ - 0, /* tp_setattro */ - 0, /* tp_as_buffer */ - Py_TPFLAGS_DEFAULT, /* tp_flags */ - range_doc, /* tp_doc */ - 0, /* tp_traverse */ - 0, /* tp_clear */ - 0, /* tp_richcompare */ - 0, /* tp_weaklistoffset */ - range_iter, /* tp_iter */ - 0, /* tp_iternext */ - range_methods, /* tp_methods */ - 0, /* tp_members */ - 0, /* tp_getset */ - 0, /* tp_base */ - 0, /* tp_dict */ - 0, /* tp_descr_get */ - 0, /* tp_descr_set */ - 0, /* tp_dictoffset */ - 0, /* tp_init */ - 0, /* tp_alloc */ - range_new, /* tp_new */ + PyVarObject_HEAD_INIT(&PyType_Type, 0) + "range", /* Name of this type */ + sizeof(rangeobject), /* Basic object size */ + 0, /* Item size for varobject */ + (destructor)range_dealloc, /* tp_dealloc */ + 0, /* tp_print */ + 0, /* tp_getattr */ + 0, /* tp_setattr */ + 0, /* tp_reserved */ + (reprfunc)range_repr, /* tp_repr */ + 0, /* tp_as_number */ + &range_as_sequence, /* tp_as_sequence */ + 0, /* tp_as_mapping */ + 0, /* tp_hash */ + 0, /* tp_call */ + 0, /* tp_str */ + PyObject_GenericGetAttr, /* tp_getattro */ + 0, /* tp_setattro */ + 0, /* tp_as_buffer */ + Py_TPFLAGS_DEFAULT, /* tp_flags */ + range_doc, /* tp_doc */ + 0, /* tp_traverse */ + 0, /* tp_clear */ + 0, /* tp_richcompare */ + 0, /* tp_weaklistoffset */ + range_iter, /* tp_iter */ + 0, /* tp_iternext */ + range_methods, /* tp_methods */ + 0, /* tp_members */ + 0, /* tp_getset */ + 0, /* tp_base */ + 0, /* tp_dict */ + 0, /* tp_descr_get */ + 0, /* tp_descr_set */ + 0, /* tp_dictoffset */ + 0, /* tp_init */ + 0, /* tp_alloc */ + range_new, /* tp_new */ }; /*********************** range Iterator **************************/ @@ -400,18 +400,18 @@ */ typedef struct { - PyObject_HEAD - long index; - long start; - long step; - long len; + PyObject_HEAD + long index; + long start; + long step; + long len; } rangeiterobject; static PyObject * rangeiter_next(rangeiterobject *r) { if (r->index < r->len) - /* cast to unsigned to avoid possible signed overflow + /* cast to unsigned to avoid possible signed overflow in intermediate calculations. */ return PyLong_FromLong((long)(r->start + (unsigned long)(r->index++) * r->step)); @@ -445,50 +445,50 @@ static PyMethodDef rangeiter_methods[] = { {"__length_hint__", (PyCFunction)rangeiter_len, METH_NOARGS, - length_hint_doc}, - {NULL, NULL} /* sentinel */ + length_hint_doc}, + {NULL, NULL} /* sentinel */ }; PyTypeObject PyRangeIter_Type = { - PyVarObject_HEAD_INIT(&PyType_Type, 0) - "range_iterator", /* tp_name */ - sizeof(rangeiterobject), /* tp_basicsize */ - 0, /* tp_itemsize */ - /* methods */ - (destructor)PyObject_Del, /* 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, /* tp_flags */ - 0, /* tp_doc */ - 0, /* tp_traverse */ - 0, /* tp_clear */ - 0, /* tp_richcompare */ - 0, /* tp_weaklistoffset */ - PyObject_SelfIter, /* tp_iter */ - (iternextfunc)rangeiter_next, /* tp_iternext */ - rangeiter_methods, /* tp_methods */ - 0, /* tp_members */ - 0, /* tp_getset */ - 0, /* tp_base */ - 0, /* tp_dict */ - 0, /* tp_descr_get */ - 0, /* tp_descr_set */ - 0, /* tp_dictoffset */ - 0, /* tp_init */ - 0, /* tp_alloc */ - rangeiter_new, /* tp_new */ + PyVarObject_HEAD_INIT(&PyType_Type, 0) + "range_iterator", /* tp_name */ + sizeof(rangeiterobject), /* tp_basicsize */ + 0, /* tp_itemsize */ + /* methods */ + (destructor)PyObject_Del, /* 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, /* tp_flags */ + 0, /* tp_doc */ + 0, /* tp_traverse */ + 0, /* tp_clear */ + 0, /* tp_richcompare */ + 0, /* tp_weaklistoffset */ + PyObject_SelfIter, /* tp_iter */ + (iternextfunc)rangeiter_next, /* tp_iternext */ + rangeiter_methods, /* tp_methods */ + 0, /* tp_members */ + 0, /* tp_getset */ + 0, /* tp_base */ + 0, /* tp_dict */ + 0, /* tp_descr_get */ + 0, /* tp_descr_set */ + 0, /* tp_dictoffset */ + 0, /* tp_init */ + 0, /* tp_alloc */ + rangeiter_new, /* tp_new */ }; /* Return number of items in range (lo, hi, step). step != 0 @@ -560,8 +560,8 @@ static PyMethodDef longrangeiter_methods[] = { {"__length_hint__", (PyCFunction)longrangeiter_len, METH_NOARGS, - length_hint_doc}, - {NULL, NULL} /* sentinel */ + length_hint_doc}, + {NULL, NULL} /* sentinel */ }; static void @@ -610,36 +610,36 @@ } PyTypeObject PyLongRangeIter_Type = { - PyVarObject_HEAD_INIT(&PyType_Type, 0) - "longrange_iterator", /* tp_name */ - sizeof(longrangeiterobject), /* tp_basicsize */ - 0, /* tp_itemsize */ - /* methods */ - (destructor)longrangeiter_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, /* tp_flags */ - 0, /* tp_doc */ - 0, /* tp_traverse */ - 0, /* tp_clear */ - 0, /* tp_richcompare */ - 0, /* tp_weaklistoffset */ - PyObject_SelfIter, /* tp_iter */ - (iternextfunc)longrangeiter_next, /* tp_iternext */ - longrangeiter_methods, /* tp_methods */ - 0, + PyVarObject_HEAD_INIT(&PyType_Type, 0) + "longrange_iterator", /* tp_name */ + sizeof(longrangeiterobject), /* tp_basicsize */ + 0, /* tp_itemsize */ + /* methods */ + (destructor)longrangeiter_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, /* tp_flags */ + 0, /* tp_doc */ + 0, /* tp_traverse */ + 0, /* tp_clear */ + 0, /* tp_richcompare */ + 0, /* tp_weaklistoffset */ + PyObject_SelfIter, /* tp_iter */ + (iternextfunc)longrangeiter_next, /* tp_iternext */ + longrangeiter_methods, /* tp_methods */ + 0, }; static PyObject * Modified: python/branches/py3k/Objects/setobject.c ============================================================================== --- python/branches/py3k/Objects/setobject.c (original) +++ python/branches/py3k/Objects/setobject.c Sun May 9 17:52:27 2010 @@ -1,5 +1,5 @@ -/* set object implementation +/* set object implementation Written and maintained by Raymond D. Hettinger Derived from Lib/sets.py and Objects/dictobject.c. @@ -17,12 +17,12 @@ static void set_key_error(PyObject *arg) { - PyObject *tup; - tup = PyTuple_Pack(1, arg); - if (!tup) - return; /* caller will expect error to be set anyway */ - PyErr_SetObject(PyExc_KeyError, tup); - Py_DECREF(tup); + PyObject *tup; + tup = PyTuple_Pack(1, arg); + if (!tup) + return; /* caller will expect error to be set anyway */ + PyErr_SetObject(PyExc_KeyError, tup); + Py_DECREF(tup); } /* This must be >= 1. */ @@ -35,20 +35,20 @@ PyObject * _PySet_Dummy(void) { - return dummy; + return dummy; } #endif -#define INIT_NONZERO_SET_SLOTS(so) do { \ - (so)->table = (so)->smalltable; \ - (so)->mask = PySet_MINSIZE - 1; \ - (so)->hash = -1; \ +#define INIT_NONZERO_SET_SLOTS(so) do { \ + (so)->table = (so)->smalltable; \ + (so)->mask = PySet_MINSIZE - 1; \ + (so)->hash = -1; \ } while(0) -#define EMPTY_TO_MINSIZE(so) do { \ - memset((so)->smalltable, 0, sizeof((so)->smalltable)); \ - (so)->used = (so)->fill = 0; \ - INIT_NONZERO_SET_SLOTS(so); \ +#define EMPTY_TO_MINSIZE(so) do { \ + memset((so)->smalltable, 0, sizeof((so)->smalltable)); \ + (so)->used = (so)->fill = 0; \ + INIT_NONZERO_SET_SLOTS(so); \ } while(0) /* Reuse scheme to save calls to malloc, free, and memset */ @@ -77,78 +77,78 @@ static setentry * set_lookkey(PySetObject *so, PyObject *key, register long hash) { - register Py_ssize_t i; - register size_t perturb; - register setentry *freeslot; - register size_t mask = so->mask; - setentry *table = so->table; - register setentry *entry; - register int cmp; - PyObject *startkey; - - i = hash & mask; - entry = &table[i]; - if (entry->key == NULL || entry->key == key) - return entry; - - if (entry->key == dummy) - freeslot = entry; - else { - if (entry->hash == hash) { - startkey = entry->key; - Py_INCREF(startkey); - cmp = PyObject_RichCompareBool(startkey, key, Py_EQ); - Py_DECREF(startkey); - if (cmp < 0) - return NULL; - if (table == so->table && entry->key == startkey) { - if (cmp > 0) - return entry; - } - else { - /* The compare did major nasty stuff to the - * set: start over. - */ - return set_lookkey(so, key, hash); - } - } - freeslot = NULL; - } - - /* In the loop, key == dummy is by far (factor of 100s) the - least likely outcome, so test for that last. */ - for (perturb = hash; ; perturb >>= PERTURB_SHIFT) { - i = (i << 2) + i + perturb + 1; - entry = &table[i & mask]; - if (entry->key == NULL) { - if (freeslot != NULL) - entry = freeslot; - break; - } - if (entry->key == key) - break; - if (entry->hash == hash && entry->key != dummy) { - startkey = entry->key; - Py_INCREF(startkey); - cmp = PyObject_RichCompareBool(startkey, key, Py_EQ); - Py_DECREF(startkey); - if (cmp < 0) - return NULL; - if (table == so->table && entry->key == startkey) { - if (cmp > 0) - break; - } - else { - /* The compare did major nasty stuff to the - * set: start over. - */ - return set_lookkey(so, key, hash); - } - } - else if (entry->key == dummy && freeslot == NULL) - freeslot = entry; - } - return entry; + register Py_ssize_t i; + register size_t perturb; + register setentry *freeslot; + register size_t mask = so->mask; + setentry *table = so->table; + register setentry *entry; + register int cmp; + PyObject *startkey; + + i = hash & mask; + entry = &table[i]; + if (entry->key == NULL || entry->key == key) + return entry; + + if (entry->key == dummy) + freeslot = entry; + else { + if (entry->hash == hash) { + startkey = entry->key; + Py_INCREF(startkey); + cmp = PyObject_RichCompareBool(startkey, key, Py_EQ); + Py_DECREF(startkey); + if (cmp < 0) + return NULL; + if (table == so->table && entry->key == startkey) { + if (cmp > 0) + return entry; + } + else { + /* The compare did major nasty stuff to the + * set: start over. + */ + return set_lookkey(so, key, hash); + } + } + freeslot = NULL; + } + + /* In the loop, key == dummy is by far (factor of 100s) the + least likely outcome, so test for that last. */ + for (perturb = hash; ; perturb >>= PERTURB_SHIFT) { + i = (i << 2) + i + perturb + 1; + entry = &table[i & mask]; + if (entry->key == NULL) { + if (freeslot != NULL) + entry = freeslot; + break; + } + if (entry->key == key) + break; + if (entry->hash == hash && entry->key != dummy) { + startkey = entry->key; + Py_INCREF(startkey); + cmp = PyObject_RichCompareBool(startkey, key, Py_EQ); + Py_DECREF(startkey); + if (cmp < 0) + return NULL; + if (table == so->table && entry->key == startkey) { + if (cmp > 0) + break; + } + else { + /* The compare did major nasty stuff to the + * set: start over. + */ + return set_lookkey(so, key, hash); + } + } + else if (entry->key == dummy && freeslot == NULL) + freeslot = entry; + } + return entry; } /* @@ -159,50 +159,50 @@ static setentry * set_lookkey_unicode(PySetObject *so, PyObject *key, register long hash) { - register Py_ssize_t i; - register size_t perturb; - register setentry *freeslot; - register size_t mask = so->mask; - setentry *table = so->table; - register setentry *entry; - - /* Make sure this function doesn't have to handle non-unicode keys, - including subclasses of str; e.g., one reason to subclass - strings is to override __eq__, and for speed we don't cater to - that here. */ - if (!PyUnicode_CheckExact(key)) { - so->lookup = set_lookkey; - return set_lookkey(so, key, hash); - } - i = hash & mask; - entry = &table[i]; - if (entry->key == NULL || entry->key == key) - return entry; - if (entry->key == dummy) - freeslot = entry; - else { - if (entry->hash == hash && unicode_eq(entry->key, key)) - return entry; - freeslot = NULL; - } - - /* In the loop, key == dummy is by far (factor of 100s) the - least likely outcome, so test for that last. */ - for (perturb = hash; ; perturb >>= PERTURB_SHIFT) { - i = (i << 2) + i + perturb + 1; - entry = &table[i & mask]; - if (entry->key == NULL) - return freeslot == NULL ? entry : freeslot; - if (entry->key == key - || (entry->hash == hash - && entry->key != dummy - && unicode_eq(entry->key, key))) - return entry; - if (entry->key == dummy && freeslot == NULL) - freeslot = entry; - } - assert(0); /* NOT REACHED */ - return 0; + register Py_ssize_t i; + register size_t perturb; + register setentry *freeslot; + register size_t mask = so->mask; + setentry *table = so->table; + register setentry *entry; + + /* Make sure this function doesn't have to handle non-unicode keys, + including subclasses of str; e.g., one reason to subclass + strings is to override __eq__, and for speed we don't cater to + that here. */ + if (!PyUnicode_CheckExact(key)) { + so->lookup = set_lookkey; + return set_lookkey(so, key, hash); + } + i = hash & mask; + entry = &table[i]; + if (entry->key == NULL || entry->key == key) + return entry; + if (entry->key == dummy) + freeslot = entry; + else { + if (entry->hash == hash && unicode_eq(entry->key, key)) + return entry; + freeslot = NULL; + } + + /* In the loop, key == dummy is by far (factor of 100s) the + least likely outcome, so test for that last. */ + for (perturb = hash; ; perturb >>= PERTURB_SHIFT) { + i = (i << 2) + i + perturb + 1; + entry = &table[i & mask]; + if (entry->key == NULL) + return freeslot == NULL ? entry : freeslot; + if (entry->key == key + || (entry->hash == hash + && entry->key != dummy + && unicode_eq(entry->key, key))) + return entry; + if (entry->key == dummy && freeslot == NULL) + freeslot = entry; + } + assert(0); /* NOT REACHED */ + return 0; } /* @@ -213,30 +213,30 @@ static int set_insert_key(register PySetObject *so, PyObject *key, long hash) { - register setentry *entry; - typedef setentry *(*lookupfunc)(PySetObject *, PyObject *, long); + register setentry *entry; + typedef setentry *(*lookupfunc)(PySetObject *, PyObject *, long); - assert(so->lookup != NULL); - entry = so->lookup(so, key, hash); - if (entry == NULL) - return -1; - if (entry->key == NULL) { - /* UNUSED */ - so->fill++; - entry->key = key; - entry->hash = hash; - so->used++; - } else if (entry->key == dummy) { - /* DUMMY */ - entry->key = key; - entry->hash = hash; - so->used++; - Py_DECREF(dummy); - } else { - /* ACTIVE */ - Py_DECREF(key); - } - return 0; + assert(so->lookup != NULL); + entry = so->lookup(so, key, hash); + if (entry == NULL) + return -1; + if (entry->key == NULL) { + /* UNUSED */ + so->fill++; + entry->key = key; + entry->hash = hash; + so->used++; + } else if (entry->key == dummy) { + /* DUMMY */ + entry->key = key; + entry->hash = hash; + so->used++; + Py_DECREF(dummy); + } else { + /* ACTIVE */ + Py_DECREF(key); + } + return 0; } /* @@ -250,22 +250,22 @@ static void set_insert_clean(register PySetObject *so, PyObject *key, long hash) { - register size_t i; - register size_t perturb; - register size_t mask = (size_t)so->mask; - setentry *table = so->table; - register setentry *entry; - - i = hash & mask; - entry = &table[i]; - for (perturb = hash; entry->key != NULL; perturb >>= PERTURB_SHIFT) { - i = (i << 2) + i + perturb + 1; - entry = &table[i & mask]; - } - so->fill++; - entry->key = key; - entry->hash = hash; - so->used++; + register size_t i; + register size_t perturb; + register size_t mask = (size_t)so->mask; + setentry *table = so->table; + register setentry *entry; + + i = hash & mask; + entry = &table[i]; + for (perturb = hash; entry->key != NULL; perturb >>= PERTURB_SHIFT) { + i = (i << 2) + i + perturb + 1; + entry = &table[i & mask]; + } + so->fill++; + entry->key = key; + entry->hash = hash; + so->used++; } /* @@ -276,86 +276,86 @@ static int set_table_resize(PySetObject *so, Py_ssize_t minused) { - Py_ssize_t newsize; - setentry *oldtable, *newtable, *entry; - Py_ssize_t i; - int is_oldtable_malloced; - setentry small_copy[PySet_MINSIZE]; - - assert(minused >= 0); - - /* Find the smallest table size > minused. */ - for (newsize = PySet_MINSIZE; - newsize <= minused && newsize > 0; - newsize <<= 1) - ; - if (newsize <= 0) { - PyErr_NoMemory(); - return -1; - } - - /* Get space for a new table. */ - oldtable = so->table; - assert(oldtable != NULL); - is_oldtable_malloced = oldtable != so->smalltable; - - if (newsize == PySet_MINSIZE) { - /* A large table is shrinking, or we can't get any smaller. */ - newtable = so->smalltable; - if (newtable == oldtable) { - if (so->fill == so->used) { - /* No dummies, so no point doing anything. */ - return 0; - } - /* We're not going to resize it, but rebuild the - table anyway to purge old dummy entries. - Subtle: This is *necessary* if fill==size, - as set_lookkey needs at least one virgin slot to - terminate failing searches. If fill < size, it's - merely desirable, as dummies slow searches. */ - assert(so->fill > so->used); - memcpy(small_copy, oldtable, sizeof(small_copy)); - oldtable = small_copy; - } - } - else { - newtable = PyMem_NEW(setentry, newsize); - if (newtable == NULL) { - PyErr_NoMemory(); - return -1; - } - } - - /* Make the set empty, using the new table. */ - assert(newtable != oldtable); - so->table = newtable; - so->mask = newsize - 1; - memset(newtable, 0, sizeof(setentry) * newsize); - so->used = 0; - i = so->fill; - so->fill = 0; - - /* Copy the data over; this is refcount-neutral for active entries; - dummy entries aren't copied over, of course */ - for (entry = oldtable; i > 0; entry++) { - if (entry->key == NULL) { - /* UNUSED */ - ; - } else if (entry->key == dummy) { - /* DUMMY */ - --i; - assert(entry->key == dummy); - Py_DECREF(entry->key); - } else { - /* ACTIVE */ - --i; - set_insert_clean(so, entry->key, entry->hash); - } - } - - if (is_oldtable_malloced) - PyMem_DEL(oldtable); - return 0; + Py_ssize_t newsize; + setentry *oldtable, *newtable, *entry; + Py_ssize_t i; + int is_oldtable_malloced; + setentry small_copy[PySet_MINSIZE]; + + assert(minused >= 0); + + /* Find the smallest table size > minused. */ + for (newsize = PySet_MINSIZE; + newsize <= minused && newsize > 0; + newsize <<= 1) + ; + if (newsize <= 0) { + PyErr_NoMemory(); + return -1; + } + + /* Get space for a new table. */ + oldtable = so->table; + assert(oldtable != NULL); + is_oldtable_malloced = oldtable != so->smalltable; + + if (newsize == PySet_MINSIZE) { + /* A large table is shrinking, or we can't get any smaller. */ + newtable = so->smalltable; + if (newtable == oldtable) { + if (so->fill == so->used) { + /* No dummies, so no point doing anything. */ + return 0; + } + /* We're not going to resize it, but rebuild the + table anyway to purge old dummy entries. + Subtle: This is *necessary* if fill==size, + as set_lookkey needs at least one virgin slot to + terminate failing searches. If fill < size, it's + merely desirable, as dummies slow searches. */ + assert(so->fill > so->used); + memcpy(small_copy, oldtable, sizeof(small_copy)); + oldtable = small_copy; + } + } + else { + newtable = PyMem_NEW(setentry, newsize); + if (newtable == NULL) { + PyErr_NoMemory(); + return -1; + } + } + + /* Make the set empty, using the new table. */ + assert(newtable != oldtable); + so->table = newtable; + so->mask = newsize - 1; + memset(newtable, 0, sizeof(setentry) * newsize); + so->used = 0; + i = so->fill; + so->fill = 0; + + /* Copy the data over; this is refcount-neutral for active entries; + dummy entries aren't copied over, of course */ + for (entry = oldtable; i > 0; entry++) { + if (entry->key == NULL) { + /* UNUSED */ + ; + } else if (entry->key == dummy) { + /* DUMMY */ + --i; + assert(entry->key == dummy); + Py_DECREF(entry->key); + } else { + /* ACTIVE */ + --i; + set_insert_clean(so, entry->key, entry->hash); + } + } + + if (is_oldtable_malloced) + PyMem_DEL(oldtable); + return 0; } /* CAUTION: set_add_key/entry() must guarantee it won't resize the table */ @@ -363,42 +363,42 @@ static int set_add_entry(register PySetObject *so, setentry *entry) { - register Py_ssize_t n_used; + register Py_ssize_t n_used; - assert(so->fill <= so->mask); /* at least one empty slot */ - n_used = so->used; - Py_INCREF(entry->key); - if (set_insert_key(so, entry->key, entry->hash) == -1) { - Py_DECREF(entry->key); - return -1; - } - if (!(so->used > n_used && so->fill*3 >= (so->mask+1)*2)) - return 0; - return set_table_resize(so, so->used>50000 ? so->used*2 : so->used*4); + assert(so->fill <= so->mask); /* at least one empty slot */ + n_used = so->used; + Py_INCREF(entry->key); + if (set_insert_key(so, entry->key, entry->hash) == -1) { + Py_DECREF(entry->key); + return -1; + } + if (!(so->used > n_used && so->fill*3 >= (so->mask+1)*2)) + return 0; + return set_table_resize(so, so->used>50000 ? so->used*2 : so->used*4); } static int set_add_key(register PySetObject *so, PyObject *key) { - register long hash; - register Py_ssize_t n_used; + register long hash; + register Py_ssize_t n_used; - if (!PyUnicode_CheckExact(key) || - (hash = ((PyUnicodeObject *) key)->hash) == -1) { - hash = PyObject_Hash(key); - if (hash == -1) - return -1; - } - assert(so->fill <= so->mask); /* at least one empty slot */ - n_used = so->used; - Py_INCREF(key); - if (set_insert_key(so, key, hash) == -1) { - Py_DECREF(key); - return -1; - } - if (!(so->used > n_used && so->fill*3 >= (so->mask+1)*2)) - return 0; - return set_table_resize(so, so->used>50000 ? so->used*2 : so->used*4); + if (!PyUnicode_CheckExact(key) || + (hash = ((PyUnicodeObject *) key)->hash) == -1) { + hash = PyObject_Hash(key); + if (hash == -1) + return -1; + } + assert(so->fill <= so->mask); /* at least one empty slot */ + n_used = so->used; + Py_INCREF(key); + if (set_insert_key(so, key, hash) == -1) { + Py_DECREF(key); + return -1; + } + if (!(so->used > n_used && so->fill*3 >= (so->mask+1)*2)) + return 0; + return set_table_resize(so, so->used>50000 ? so->used*2 : so->used*4); } #define DISCARD_NOTFOUND 0 @@ -406,112 +406,112 @@ static int set_discard_entry(PySetObject *so, setentry *oldentry) -{ register setentry *entry; - PyObject *old_key; +{ register setentry *entry; + PyObject *old_key; - entry = (so->lookup)(so, oldentry->key, oldentry->hash); - if (entry == NULL) - return -1; - if (entry->key == NULL || entry->key == dummy) - return DISCARD_NOTFOUND; - old_key = entry->key; - Py_INCREF(dummy); - entry->key = dummy; - so->used--; - Py_DECREF(old_key); - return DISCARD_FOUND; + entry = (so->lookup)(so, oldentry->key, oldentry->hash); + if (entry == NULL) + return -1; + if (entry->key == NULL || entry->key == dummy) + return DISCARD_NOTFOUND; + old_key = entry->key; + Py_INCREF(dummy); + entry->key = dummy; + so->used--; + Py_DECREF(old_key); + return DISCARD_FOUND; } static int set_discard_key(PySetObject *so, PyObject *key) { - register long hash; - register setentry *entry; - PyObject *old_key; - - assert (PyAnySet_Check(so)); - - if (!PyUnicode_CheckExact(key) || - (hash = ((PyUnicodeObject *) key)->hash) == -1) { - hash = PyObject_Hash(key); - if (hash == -1) - return -1; - } - entry = (so->lookup)(so, key, hash); - if (entry == NULL) - return -1; - if (entry->key == NULL || entry->key == dummy) - return DISCARD_NOTFOUND; - old_key = entry->key; - Py_INCREF(dummy); - entry->key = dummy; - so->used--; - Py_DECREF(old_key); - return DISCARD_FOUND; + register long hash; + register setentry *entry; + PyObject *old_key; + + assert (PyAnySet_Check(so)); + + if (!PyUnicode_CheckExact(key) || + (hash = ((PyUnicodeObject *) key)->hash) == -1) { + hash = PyObject_Hash(key); + if (hash == -1) + return -1; + } + entry = (so->lookup)(so, key, hash); + if (entry == NULL) + return -1; + if (entry->key == NULL || entry->key == dummy) + return DISCARD_NOTFOUND; + old_key = entry->key; + Py_INCREF(dummy); + entry->key = dummy; + so->used--; + Py_DECREF(old_key); + return DISCARD_FOUND; } static int set_clear_internal(PySetObject *so) { - setentry *entry, *table; - int table_is_malloced; - Py_ssize_t fill; - setentry small_copy[PySet_MINSIZE]; + setentry *entry, *table; + int table_is_malloced; + Py_ssize_t fill; + setentry small_copy[PySet_MINSIZE]; #ifdef Py_DEBUG - Py_ssize_t i, n; - assert (PyAnySet_Check(so)); + Py_ssize_t i, n; + assert (PyAnySet_Check(so)); - n = so->mask + 1; - i = 0; + n = so->mask + 1; + i = 0; #endif - table = so->table; - assert(table != NULL); - table_is_malloced = table != so->smalltable; - - /* This is delicate. During the process of clearing the set, - * decrefs can cause the set to mutate. To avoid fatal confusion - * (voice of experience), we have to make the set empty before - * clearing the slots, and never refer to anything via so->ref while - * clearing. - */ - fill = so->fill; - if (table_is_malloced) - EMPTY_TO_MINSIZE(so); - - else if (fill > 0) { - /* It's a small table with something that needs to be cleared. - * Afraid the only safe way is to copy the set entries into - * another small table first. - */ - memcpy(small_copy, table, sizeof(small_copy)); - table = small_copy; - EMPTY_TO_MINSIZE(so); - } - /* else it's a small table that's already empty */ - - /* Now we can finally clear things. If C had refcounts, we could - * assert that the refcount on table is 1 now, i.e. that this function - * has unique access to it, so decref side-effects can't alter it. - */ - for (entry = table; fill > 0; ++entry) { + table = so->table; + assert(table != NULL); + table_is_malloced = table != so->smalltable; + + /* This is delicate. During the process of clearing the set, + * decrefs can cause the set to mutate. To avoid fatal confusion + * (voice of experience), we have to make the set empty before + * clearing the slots, and never refer to anything via so->ref while + * clearing. + */ + fill = so->fill; + if (table_is_malloced) + EMPTY_TO_MINSIZE(so); + + else if (fill > 0) { + /* It's a small table with something that needs to be cleared. + * Afraid the only safe way is to copy the set entries into + * another small table first. + */ + memcpy(small_copy, table, sizeof(small_copy)); + table = small_copy; + EMPTY_TO_MINSIZE(so); + } + /* else it's a small table that's already empty */ + + /* Now we can finally clear things. If C had refcounts, we could + * assert that the refcount on table is 1 now, i.e. that this function + * has unique access to it, so decref side-effects can't alter it. + */ + for (entry = table; fill > 0; ++entry) { #ifdef Py_DEBUG - assert(i < n); - ++i; + assert(i < n); + ++i; #endif - if (entry->key) { - --fill; - Py_DECREF(entry->key); - } + if (entry->key) { + --fill; + Py_DECREF(entry->key); + } #ifdef Py_DEBUG - else - assert(entry->key == NULL); + else + assert(entry->key == NULL); #endif - } + } - if (table_is_malloced) - PyMem_DEL(table); - return 0; + if (table_is_malloced) + PyMem_DEL(table); + return 0; } /* @@ -525,223 +525,223 @@ * } * * CAUTION: In general, it isn't safe to use set_next in a loop that - * mutates the table. + * mutates the table. */ static int set_next(PySetObject *so, Py_ssize_t *pos_ptr, setentry **entry_ptr) { - Py_ssize_t i; - Py_ssize_t mask; - register setentry *table; - - assert (PyAnySet_Check(so)); - i = *pos_ptr; - assert(i >= 0); - table = so->table; - mask = so->mask; - while (i <= mask && (table[i].key == NULL || table[i].key == dummy)) - i++; - *pos_ptr = i+1; - if (i > mask) - return 0; - assert(table[i].key != NULL); - *entry_ptr = &table[i]; - return 1; + Py_ssize_t i; + Py_ssize_t mask; + register setentry *table; + + assert (PyAnySet_Check(so)); + i = *pos_ptr; + assert(i >= 0); + table = so->table; + mask = so->mask; + while (i <= mask && (table[i].key == NULL || table[i].key == dummy)) + i++; + *pos_ptr = i+1; + if (i > mask) + return 0; + assert(table[i].key != NULL); + *entry_ptr = &table[i]; + return 1; } static void set_dealloc(PySetObject *so) { - register setentry *entry; - Py_ssize_t fill = so->fill; - PyObject_GC_UnTrack(so); - Py_TRASHCAN_SAFE_BEGIN(so) - if (so->weakreflist != NULL) - PyObject_ClearWeakRefs((PyObject *) so); - - for (entry = so->table; fill > 0; entry++) { - if (entry->key) { - --fill; - Py_DECREF(entry->key); - } - } - if (so->table != so->smalltable) - PyMem_DEL(so->table); - if (numfree < PySet_MAXFREELIST && PyAnySet_CheckExact(so)) - free_list[numfree++] = so; - else - Py_TYPE(so)->tp_free(so); - Py_TRASHCAN_SAFE_END(so) + register setentry *entry; + Py_ssize_t fill = so->fill; + PyObject_GC_UnTrack(so); + Py_TRASHCAN_SAFE_BEGIN(so) + if (so->weakreflist != NULL) + PyObject_ClearWeakRefs((PyObject *) so); + + for (entry = so->table; fill > 0; entry++) { + if (entry->key) { + --fill; + Py_DECREF(entry->key); + } + } + if (so->table != so->smalltable) + PyMem_DEL(so->table); + if (numfree < PySet_MAXFREELIST && PyAnySet_CheckExact(so)) + free_list[numfree++] = so; + else + Py_TYPE(so)->tp_free(so); + Py_TRASHCAN_SAFE_END(so) } static PyObject * set_repr(PySetObject *so) { - PyObject *keys, *result=NULL; - Py_UNICODE *u; - int status = Py_ReprEnter((PyObject*)so); - PyObject *listrepr; - Py_ssize_t newsize; - - if (status != 0) { - if (status < 0) - return NULL; - return PyUnicode_FromFormat("%s(...)", Py_TYPE(so)->tp_name); - } - - /* shortcut for the empty set */ - if (!so->used) { - Py_ReprLeave((PyObject*)so); - return PyUnicode_FromFormat("%s()", Py_TYPE(so)->tp_name); - } - - keys = PySequence_List((PyObject *)so); - if (keys == NULL) - goto done; - - listrepr = PyObject_Repr(keys); - Py_DECREF(keys); - if (listrepr == NULL) - goto done; - newsize = PyUnicode_GET_SIZE(listrepr); - result = PyUnicode_FromUnicode(NULL, newsize); - if (result) { - u = PyUnicode_AS_UNICODE(result); - *u++ = '{'; - /* Omit the brackets from the listrepr */ - Py_UNICODE_COPY(u, PyUnicode_AS_UNICODE(listrepr)+1, - PyUnicode_GET_SIZE(listrepr)-2); - u += newsize-2; - *u++ = '}'; - } - Py_DECREF(listrepr); - if (Py_TYPE(so) != &PySet_Type) { - PyObject *tmp = PyUnicode_FromFormat("%s(%U)", - Py_TYPE(so)->tp_name, - result); - Py_DECREF(result); - result = tmp; - } + PyObject *keys, *result=NULL; + Py_UNICODE *u; + int status = Py_ReprEnter((PyObject*)so); + PyObject *listrepr; + Py_ssize_t newsize; + + if (status != 0) { + if (status < 0) + return NULL; + return PyUnicode_FromFormat("%s(...)", Py_TYPE(so)->tp_name); + } + + /* shortcut for the empty set */ + if (!so->used) { + Py_ReprLeave((PyObject*)so); + return PyUnicode_FromFormat("%s()", Py_TYPE(so)->tp_name); + } + + keys = PySequence_List((PyObject *)so); + if (keys == NULL) + goto done; + + listrepr = PyObject_Repr(keys); + Py_DECREF(keys); + if (listrepr == NULL) + goto done; + newsize = PyUnicode_GET_SIZE(listrepr); + result = PyUnicode_FromUnicode(NULL, newsize); + if (result) { + u = PyUnicode_AS_UNICODE(result); + *u++ = '{'; + /* Omit the brackets from the listrepr */ + Py_UNICODE_COPY(u, PyUnicode_AS_UNICODE(listrepr)+1, + PyUnicode_GET_SIZE(listrepr)-2); + u += newsize-2; + *u++ = '}'; + } + Py_DECREF(listrepr); + if (Py_TYPE(so) != &PySet_Type) { + PyObject *tmp = PyUnicode_FromFormat("%s(%U)", + Py_TYPE(so)->tp_name, + result); + Py_DECREF(result); + result = tmp; + } done: - Py_ReprLeave((PyObject*)so); - return result; + Py_ReprLeave((PyObject*)so); + return result; } static Py_ssize_t set_len(PyObject *so) { - return ((PySetObject *)so)->used; + return ((PySetObject *)so)->used; } static int set_merge(PySetObject *so, PyObject *otherset) { - PySetObject *other; - register Py_ssize_t i; - register setentry *entry; - - assert (PyAnySet_Check(so)); - assert (PyAnySet_Check(otherset)); - - other = (PySetObject*)otherset; - if (other == so || other->used == 0) - /* a.update(a) or a.update({}); nothing to do */ - return 0; - /* Do one big resize at the start, rather than - * incrementally resizing as we insert new keys. Expect - * that there will be no (or few) overlapping keys. - */ - if ((so->fill + other->used)*3 >= (so->mask+1)*2) { - if (set_table_resize(so, (so->used + other->used)*2) != 0) - return -1; - } - for (i = 0; i <= other->mask; i++) { - entry = &other->table[i]; - if (entry->key != NULL && - entry->key != dummy) { - Py_INCREF(entry->key); - if (set_insert_key(so, entry->key, entry->hash) == -1) { - Py_DECREF(entry->key); - return -1; - } - } - } - return 0; + PySetObject *other; + register Py_ssize_t i; + register setentry *entry; + + assert (PyAnySet_Check(so)); + assert (PyAnySet_Check(otherset)); + + other = (PySetObject*)otherset; + if (other == so || other->used == 0) + /* a.update(a) or a.update({}); nothing to do */ + return 0; + /* Do one big resize at the start, rather than + * incrementally resizing as we insert new keys. Expect + * that there will be no (or few) overlapping keys. + */ + if ((so->fill + other->used)*3 >= (so->mask+1)*2) { + if (set_table_resize(so, (so->used + other->used)*2) != 0) + return -1; + } + for (i = 0; i <= other->mask; i++) { + entry = &other->table[i]; + if (entry->key != NULL && + entry->key != dummy) { + Py_INCREF(entry->key); + if (set_insert_key(so, entry->key, entry->hash) == -1) { + Py_DECREF(entry->key); + return -1; + } + } + } + return 0; } static int set_contains_key(PySetObject *so, PyObject *key) { - long hash; - setentry *entry; + long hash; + setentry *entry; - if (!PyUnicode_CheckExact(key) || - (hash = ((PyUnicodeObject *) key)->hash) == -1) { - hash = PyObject_Hash(key); - if (hash == -1) - return -1; - } - entry = (so->lookup)(so, key, hash); - if (entry == NULL) - return -1; - key = entry->key; - return key != NULL && key != dummy; + if (!PyUnicode_CheckExact(key) || + (hash = ((PyUnicodeObject *) key)->hash) == -1) { + hash = PyObject_Hash(key); + if (hash == -1) + return -1; + } + entry = (so->lookup)(so, key, hash); + if (entry == NULL) + return -1; + key = entry->key; + return key != NULL && key != dummy; } static int set_contains_entry(PySetObject *so, setentry *entry) { - PyObject *key; - setentry *lu_entry; + PyObject *key; + setentry *lu_entry; - lu_entry = (so->lookup)(so, entry->key, entry->hash); - if (lu_entry == NULL) - return -1; - key = lu_entry->key; - return key != NULL && key != dummy; + lu_entry = (so->lookup)(so, entry->key, entry->hash); + if (lu_entry == NULL) + return -1; + key = lu_entry->key; + return key != NULL && key != dummy; } static PyObject * set_pop(PySetObject *so) { - register Py_ssize_t i = 0; - register setentry *entry; - PyObject *key; - - assert (PyAnySet_Check(so)); - if (so->used == 0) { - PyErr_SetString(PyExc_KeyError, "pop from an empty set"); - return NULL; - } - - /* Set entry to "the first" unused or dummy set entry. We abuse - * the hash field of slot 0 to hold a search finger: - * If slot 0 has a value, use slot 0. - * Else slot 0 is being used to hold a search finger, - * and we use its hash value as the first index to look. - */ - entry = &so->table[0]; - if (entry->key == NULL || entry->key == dummy) { - i = entry->hash; - /* The hash field may be a real hash value, or it may be a - * legit search finger, or it may be a once-legit search - * finger that's out of bounds now because it wrapped around - * or the table shrunk -- simply make sure it's in bounds now. - */ - if (i > so->mask || i < 1) - i = 1; /* skip slot 0 */ - while ((entry = &so->table[i])->key == NULL || entry->key==dummy) { - i++; - if (i > so->mask) - i = 1; - } - } - key = entry->key; - Py_INCREF(dummy); - entry->key = dummy; - so->used--; - so->table[0].hash = i + 1; /* next place to start */ - return key; + register Py_ssize_t i = 0; + register setentry *entry; + PyObject *key; + + assert (PyAnySet_Check(so)); + if (so->used == 0) { + PyErr_SetString(PyExc_KeyError, "pop from an empty set"); + return NULL; + } + + /* Set entry to "the first" unused or dummy set entry. We abuse + * the hash field of slot 0 to hold a search finger: + * If slot 0 has a value, use slot 0. + * Else slot 0 is being used to hold a search finger, + * and we use its hash value as the first index to look. + */ + entry = &so->table[0]; + if (entry->key == NULL || entry->key == dummy) { + i = entry->hash; + /* The hash field may be a real hash value, or it may be a + * legit search finger, or it may be a once-legit search + * finger that's out of bounds now because it wrapped around + * or the table shrunk -- simply make sure it's in bounds now. + */ + if (i > so->mask || i < 1) + i = 1; /* skip slot 0 */ + while ((entry = &so->table[i])->key == NULL || entry->key==dummy) { + i++; + if (i > so->mask) + i = 1; + } + } + key = entry->key; + Py_INCREF(dummy); + entry->key = dummy; + so->used--; + so->table[0].hash = i + 1; /* next place to start */ + return key; } PyDoc_STRVAR(pop_doc, "Remove and return an arbitrary set element.\n\ @@ -750,289 +750,289 @@ static int set_traverse(PySetObject *so, visitproc visit, void *arg) { - Py_ssize_t pos = 0; - setentry *entry; + Py_ssize_t pos = 0; + setentry *entry; - while (set_next(so, &pos, &entry)) - Py_VISIT(entry->key); - return 0; + while (set_next(so, &pos, &entry)) + Py_VISIT(entry->key); + return 0; } static long frozenset_hash(PyObject *self) { - PySetObject *so = (PySetObject *)self; - long h, hash = 1927868237L; - setentry *entry; - Py_ssize_t pos = 0; - - if (so->hash != -1) - return so->hash; - - hash *= PySet_GET_SIZE(self) + 1; - while (set_next(so, &pos, &entry)) { - /* Work to increase the bit dispersion for closely spaced hash - values. The is important because some use cases have many - combinations of a small number of elements with nearby - hashes so that many distinct combinations collapse to only - a handful of distinct hash values. */ - h = entry->hash; - hash ^= (h ^ (h << 16) ^ 89869747L) * 3644798167u; - } - hash = hash * 69069L + 907133923L; - if (hash == -1) - hash = 590923713L; - so->hash = hash; - return hash; + PySetObject *so = (PySetObject *)self; + long h, hash = 1927868237L; + setentry *entry; + Py_ssize_t pos = 0; + + if (so->hash != -1) + return so->hash; + + hash *= PySet_GET_SIZE(self) + 1; + while (set_next(so, &pos, &entry)) { + /* Work to increase the bit dispersion for closely spaced hash + values. The is important because some use cases have many + combinations of a small number of elements with nearby + hashes so that many distinct combinations collapse to only + a handful of distinct hash values. */ + h = entry->hash; + hash ^= (h ^ (h << 16) ^ 89869747L) * 3644798167u; + } + hash = hash * 69069L + 907133923L; + if (hash == -1) + hash = 590923713L; + so->hash = hash; + return hash; } /***** Set iterator type ***********************************************/ typedef struct { - PyObject_HEAD - PySetObject *si_set; /* Set to NULL when iterator is exhausted */ - Py_ssize_t si_used; - Py_ssize_t si_pos; - Py_ssize_t len; + PyObject_HEAD + PySetObject *si_set; /* Set to NULL when iterator is exhausted */ + Py_ssize_t si_used; + Py_ssize_t si_pos; + Py_ssize_t len; } setiterobject; static void setiter_dealloc(setiterobject *si) { - Py_XDECREF(si->si_set); - PyObject_GC_Del(si); + Py_XDECREF(si->si_set); + PyObject_GC_Del(si); } static int setiter_traverse(setiterobject *si, visitproc visit, void *arg) { - Py_VISIT(si->si_set); - return 0; + Py_VISIT(si->si_set); + return 0; } static PyObject * setiter_len(setiterobject *si) { - Py_ssize_t len = 0; - if (si->si_set != NULL && si->si_used == si->si_set->used) - len = si->len; - return PyLong_FromLong(len); + Py_ssize_t len = 0; + if (si->si_set != NULL && si->si_used == si->si_set->used) + len = si->len; + return PyLong_FromLong(len); } PyDoc_STRVAR(length_hint_doc, "Private method returning an estimate of len(list(it))."); static PyMethodDef setiter_methods[] = { - {"__length_hint__", (PyCFunction)setiter_len, METH_NOARGS, length_hint_doc}, - {NULL, NULL} /* sentinel */ + {"__length_hint__", (PyCFunction)setiter_len, METH_NOARGS, length_hint_doc}, + {NULL, NULL} /* sentinel */ }; static PyObject *setiter_iternext(setiterobject *si) { - PyObject *key; - register Py_ssize_t i, mask; - register setentry *entry; - PySetObject *so = si->si_set; - - if (so == NULL) - return NULL; - assert (PyAnySet_Check(so)); - - if (si->si_used != so->used) { - PyErr_SetString(PyExc_RuntimeError, - "Set changed size during iteration"); - si->si_used = -1; /* Make this state sticky */ - return NULL; - } - - i = si->si_pos; - assert(i>=0); - entry = so->table; - mask = so->mask; - while (i <= mask && (entry[i].key == NULL || entry[i].key == dummy)) - i++; - si->si_pos = i+1; - if (i > mask) - goto fail; - si->len--; - key = entry[i].key; - Py_INCREF(key); - return key; + PyObject *key; + register Py_ssize_t i, mask; + register setentry *entry; + PySetObject *so = si->si_set; + + if (so == NULL) + return NULL; + assert (PyAnySet_Check(so)); + + if (si->si_used != so->used) { + PyErr_SetString(PyExc_RuntimeError, + "Set changed size during iteration"); + si->si_used = -1; /* Make this state sticky */ + return NULL; + } + + i = si->si_pos; + assert(i>=0); + entry = so->table; + mask = so->mask; + while (i <= mask && (entry[i].key == NULL || entry[i].key == dummy)) + i++; + si->si_pos = i+1; + if (i > mask) + goto fail; + si->len--; + key = entry[i].key; + Py_INCREF(key); + return key; fail: - Py_DECREF(so); - si->si_set = NULL; - return NULL; + Py_DECREF(so); + si->si_set = NULL; + return NULL; } PyTypeObject PySetIter_Type = { - PyVarObject_HEAD_INIT(&PyType_Type, 0) - "set_iterator", /* tp_name */ - sizeof(setiterobject), /* tp_basicsize */ - 0, /* tp_itemsize */ - /* methods */ - (destructor)setiter_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)setiter_traverse, /* tp_traverse */ - 0, /* tp_clear */ - 0, /* tp_richcompare */ - 0, /* tp_weaklistoffset */ - PyObject_SelfIter, /* tp_iter */ - (iternextfunc)setiter_iternext, /* tp_iternext */ - setiter_methods, /* tp_methods */ - 0, + PyVarObject_HEAD_INIT(&PyType_Type, 0) + "set_iterator", /* tp_name */ + sizeof(setiterobject), /* tp_basicsize */ + 0, /* tp_itemsize */ + /* methods */ + (destructor)setiter_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)setiter_traverse, /* tp_traverse */ + 0, /* tp_clear */ + 0, /* tp_richcompare */ + 0, /* tp_weaklistoffset */ + PyObject_SelfIter, /* tp_iter */ + (iternextfunc)setiter_iternext, /* tp_iternext */ + setiter_methods, /* tp_methods */ + 0, }; static PyObject * set_iter(PySetObject *so) { - setiterobject *si = PyObject_GC_New(setiterobject, &PySetIter_Type); - if (si == NULL) - return NULL; - Py_INCREF(so); - si->si_set = so; - si->si_used = so->used; - si->si_pos = 0; - si->len = so->used; - _PyObject_GC_TRACK(si); - return (PyObject *)si; + setiterobject *si = PyObject_GC_New(setiterobject, &PySetIter_Type); + if (si == NULL) + return NULL; + Py_INCREF(so); + si->si_set = so; + si->si_used = so->used; + si->si_pos = 0; + si->len = so->used; + _PyObject_GC_TRACK(si); + return (PyObject *)si; } static int set_update_internal(PySetObject *so, PyObject *other) { - PyObject *key, *it; + PyObject *key, *it; - if (PyAnySet_Check(other)) - return set_merge(so, other); + if (PyAnySet_Check(other)) + return set_merge(so, other); - if (PyDict_CheckExact(other)) { - PyObject *value; - Py_ssize_t pos = 0; - long hash; - Py_ssize_t dictsize = PyDict_Size(other); - - /* Do one big resize at the start, rather than - * incrementally resizing as we insert new keys. Expect - * that there will be no (or few) overlapping keys. - */ - if (dictsize == -1) - return -1; - if ((so->fill + dictsize)*3 >= (so->mask+1)*2) { - if (set_table_resize(so, (so->used + dictsize)*2) != 0) - return -1; - } - while (_PyDict_Next(other, &pos, &key, &value, &hash)) { - setentry an_entry; - - an_entry.hash = hash; - an_entry.key = key; - if (set_add_entry(so, &an_entry) == -1) - return -1; - } - return 0; - } - - it = PyObject_GetIter(other); - if (it == NULL) - return -1; - - while ((key = PyIter_Next(it)) != NULL) { - if (set_add_key(so, key) == -1) { - Py_DECREF(it); - Py_DECREF(key); - return -1; - } - Py_DECREF(key); - } - Py_DECREF(it); - if (PyErr_Occurred()) - return -1; - return 0; + if (PyDict_CheckExact(other)) { + PyObject *value; + Py_ssize_t pos = 0; + long hash; + Py_ssize_t dictsize = PyDict_Size(other); + + /* Do one big resize at the start, rather than + * incrementally resizing as we insert new keys. Expect + * that there will be no (or few) overlapping keys. + */ + if (dictsize == -1) + return -1; + if ((so->fill + dictsize)*3 >= (so->mask+1)*2) { + if (set_table_resize(so, (so->used + dictsize)*2) != 0) + return -1; + } + while (_PyDict_Next(other, &pos, &key, &value, &hash)) { + setentry an_entry; + + an_entry.hash = hash; + an_entry.key = key; + if (set_add_entry(so, &an_entry) == -1) + return -1; + } + return 0; + } + + it = PyObject_GetIter(other); + if (it == NULL) + return -1; + + while ((key = PyIter_Next(it)) != NULL) { + if (set_add_key(so, key) == -1) { + Py_DECREF(it); + Py_DECREF(key); + return -1; + } + Py_DECREF(key); + } + Py_DECREF(it); + if (PyErr_Occurred()) + return -1; + return 0; } static PyObject * set_update(PySetObject *so, PyObject *args) { - Py_ssize_t i; + Py_ssize_t i; - for (i=0 ; i"); - if (dummy == NULL) - return NULL; - } - - /* create PySetObject structure */ - if (numfree && - (type == &PySet_Type || type == &PyFrozenSet_Type)) { - so = free_list[--numfree]; - assert (so != NULL && PyAnySet_CheckExact(so)); - Py_TYPE(so) = type; - _Py_NewReference((PyObject *)so); - EMPTY_TO_MINSIZE(so); - PyObject_GC_Track(so); - } else { - so = (PySetObject *)type->tp_alloc(type, 0); - if (so == NULL) - return NULL; - /* tp_alloc has already zeroed the structure */ - assert(so->table == NULL && so->fill == 0 && so->used == 0); - INIT_NONZERO_SET_SLOTS(so); - } - - so->lookup = set_lookkey_unicode; - so->weakreflist = NULL; - - if (iterable != NULL) { - if (set_update_internal(so, iterable) == -1) { - Py_DECREF(so); - return NULL; - } - } + if (dummy == NULL) { /* Auto-initialize dummy */ + dummy = PyUnicode_FromString(""); + if (dummy == NULL) + return NULL; + } + + /* create PySetObject structure */ + if (numfree && + (type == &PySet_Type || type == &PyFrozenSet_Type)) { + so = free_list[--numfree]; + assert (so != NULL && PyAnySet_CheckExact(so)); + Py_TYPE(so) = type; + _Py_NewReference((PyObject *)so); + EMPTY_TO_MINSIZE(so); + PyObject_GC_Track(so); + } else { + so = (PySetObject *)type->tp_alloc(type, 0); + if (so == NULL) + return NULL; + /* tp_alloc has already zeroed the structure */ + assert(so->table == NULL && so->fill == 0 && so->used == 0); + INIT_NONZERO_SET_SLOTS(so); + } + + so->lookup = set_lookkey_unicode; + so->weakreflist = NULL; + + if (iterable != NULL) { + if (set_update_internal(so, iterable) == -1) { + Py_DECREF(so); + return NULL; + } + } - return (PyObject *)so; + return (PyObject *)so; } static PyObject * make_new_set_basetype(PyTypeObject *type, PyObject *iterable) { - if (type != &PySet_Type && type != &PyFrozenSet_Type) { - if (PyType_IsSubtype(type, &PySet_Type)) - type = &PySet_Type; - else - type = &PyFrozenSet_Type; - } - return make_new_set(type, iterable); + if (type != &PySet_Type && type != &PyFrozenSet_Type) { + if (PyType_IsSubtype(type, &PySet_Type)) + type = &PySet_Type; + else + type = &PyFrozenSet_Type; + } + return make_new_set(type, iterable); } /* The empty frozenset is a singleton */ @@ -1041,56 +1041,56 @@ static PyObject * frozenset_new(PyTypeObject *type, PyObject *args, PyObject *kwds) { - PyObject *iterable = NULL, *result; + PyObject *iterable = NULL, *result; - if (type == &PyFrozenSet_Type && !_PyArg_NoKeywords("frozenset()", kwds)) - return NULL; + if (type == &PyFrozenSet_Type && !_PyArg_NoKeywords("frozenset()", kwds)) + return NULL; - if (!PyArg_UnpackTuple(args, type->tp_name, 0, 1, &iterable)) - return NULL; + if (!PyArg_UnpackTuple(args, type->tp_name, 0, 1, &iterable)) + return NULL; - if (type != &PyFrozenSet_Type) - return make_new_set(type, iterable); - - if (iterable != NULL) { - /* frozenset(f) is idempotent */ - if (PyFrozenSet_CheckExact(iterable)) { - Py_INCREF(iterable); - return iterable; - } - result = make_new_set(type, iterable); - if (result == NULL || PySet_GET_SIZE(result)) - return result; - Py_DECREF(result); - } - /* The empty frozenset is a singleton */ - if (emptyfrozenset == NULL) - emptyfrozenset = make_new_set(type, NULL); - Py_XINCREF(emptyfrozenset); - return emptyfrozenset; + if (type != &PyFrozenSet_Type) + return make_new_set(type, iterable); + + if (iterable != NULL) { + /* frozenset(f) is idempotent */ + if (PyFrozenSet_CheckExact(iterable)) { + Py_INCREF(iterable); + return iterable; + } + result = make_new_set(type, iterable); + if (result == NULL || PySet_GET_SIZE(result)) + return result; + Py_DECREF(result); + } + /* The empty frozenset is a singleton */ + if (emptyfrozenset == NULL) + emptyfrozenset = make_new_set(type, NULL); + Py_XINCREF(emptyfrozenset); + return emptyfrozenset; } void PySet_Fini(void) { - PySetObject *so; + PySetObject *so; - while (numfree) { - numfree--; - so = free_list[numfree]; - PyObject_GC_Del(so); - } - Py_CLEAR(dummy); - Py_CLEAR(emptyfrozenset); + while (numfree) { + numfree--; + so = free_list[numfree]; + PyObject_GC_Del(so); + } + Py_CLEAR(dummy); + Py_CLEAR(emptyfrozenset); } static PyObject * set_new(PyTypeObject *type, PyObject *args, PyObject *kwds) { - if (type == &PySet_Type && !_PyArg_NoKeywords("set()", kwds)) - return NULL; - - return make_new_set(type, NULL); + if (type == &PySet_Type && !_PyArg_NoKeywords("set()", kwds)) + return NULL; + + return make_new_set(type, NULL); } /* set_swap_bodies() switches the contents of any two sets by moving their @@ -1100,64 +1100,64 @@ t=set(a); a.clear(); a.update(b); b.clear(); b.update(t); del t The function always succeeds and it leaves both objects in a stable state. - Useful for creating temporary frozensets from sets for membership testing + Useful for creating temporary frozensets from sets for membership testing in __contains__(), discard(), and remove(). Also useful for operations - that update in-place (by allowing an intermediate result to be swapped + that update in-place (by allowing an intermediate result to be swapped into one of the original inputs). */ static void set_swap_bodies(PySetObject *a, PySetObject *b) { - Py_ssize_t t; - setentry *u; - setentry *(*f)(PySetObject *so, PyObject *key, long hash); - setentry tab[PySet_MINSIZE]; - long h; - - t = a->fill; a->fill = b->fill; b->fill = t; - t = a->used; a->used = b->used; b->used = t; - t = a->mask; a->mask = b->mask; b->mask = t; - - u = a->table; - if (a->table == a->smalltable) - u = b->smalltable; - a->table = b->table; - if (b->table == b->smalltable) - a->table = a->smalltable; - b->table = u; - - f = a->lookup; a->lookup = b->lookup; b->lookup = f; - - if (a->table == a->smalltable || b->table == b->smalltable) { - memcpy(tab, a->smalltable, sizeof(tab)); - memcpy(a->smalltable, b->smalltable, sizeof(tab)); - memcpy(b->smalltable, tab, sizeof(tab)); - } - - if (PyType_IsSubtype(Py_TYPE(a), &PyFrozenSet_Type) && - PyType_IsSubtype(Py_TYPE(b), &PyFrozenSet_Type)) { - h = a->hash; a->hash = b->hash; b->hash = h; - } else { - a->hash = -1; - b->hash = -1; - } + Py_ssize_t t; + setentry *u; + setentry *(*f)(PySetObject *so, PyObject *key, long hash); + setentry tab[PySet_MINSIZE]; + long h; + + t = a->fill; a->fill = b->fill; b->fill = t; + t = a->used; a->used = b->used; b->used = t; + t = a->mask; a->mask = b->mask; b->mask = t; + + u = a->table; + if (a->table == a->smalltable) + u = b->smalltable; + a->table = b->table; + if (b->table == b->smalltable) + a->table = a->smalltable; + b->table = u; + + f = a->lookup; a->lookup = b->lookup; b->lookup = f; + + if (a->table == a->smalltable || b->table == b->smalltable) { + memcpy(tab, a->smalltable, sizeof(tab)); + memcpy(a->smalltable, b->smalltable, sizeof(tab)); + memcpy(b->smalltable, tab, sizeof(tab)); + } + + if (PyType_IsSubtype(Py_TYPE(a), &PyFrozenSet_Type) && + PyType_IsSubtype(Py_TYPE(b), &PyFrozenSet_Type)) { + h = a->hash; a->hash = b->hash; b->hash = h; + } else { + a->hash = -1; + b->hash = -1; + } } static PyObject * set_copy(PySetObject *so) { - return make_new_set_basetype(Py_TYPE(so), (PyObject *)so); + return make_new_set_basetype(Py_TYPE(so), (PyObject *)so); } static PyObject * frozenset_copy(PySetObject *so) { - if (PyFrozenSet_CheckExact(so)) { - Py_INCREF(so); - return (PyObject *)so; - } - return set_copy(so); + if (PyFrozenSet_CheckExact(so)) { + Py_INCREF(so); + return (PyObject *)so; + } + return set_copy(so); } PyDoc_STRVAR(copy_doc, "Return a shallow copy of a set."); @@ -1165,8 +1165,8 @@ static PyObject * set_clear(PySetObject *so) { - set_clear_internal(so); - Py_RETURN_NONE; + set_clear_internal(so); + Py_RETURN_NONE; } PyDoc_STRVAR(clear_doc, "Remove all elements from this set."); @@ -1174,24 +1174,24 @@ static PyObject * set_union(PySetObject *so, PyObject *args) { - PySetObject *result; - PyObject *other; - Py_ssize_t i; - - result = (PySetObject *)set_copy(so); - if (result == NULL) - return NULL; - - for (i=0 ; i PySet_GET_SIZE(so)) { - tmp = (PyObject *)so; - so = (PySetObject *)other; - other = tmp; - } - - while (set_next((PySetObject *)other, &pos, &entry)) { - int rv = set_contains_entry(so, entry); - if (rv == -1) { - Py_DECREF(result); - return NULL; - } - if (rv) { - if (set_add_entry(result, entry) == -1) { - Py_DECREF(result); - return NULL; - } - } - } - return (PyObject *)result; - } - - it = PyObject_GetIter(other); - if (it == NULL) { - Py_DECREF(result); - return NULL; - } - - while ((key = PyIter_Next(it)) != NULL) { - int rv; - setentry entry; - long hash = PyObject_Hash(key); - - if (hash == -1) { - Py_DECREF(it); - Py_DECREF(result); - Py_DECREF(key); - return NULL; - } - entry.hash = hash; - entry.key = key; - rv = set_contains_entry(so, &entry); - if (rv == -1) { - Py_DECREF(it); - Py_DECREF(result); - Py_DECREF(key); - return NULL; - } - if (rv) { - if (set_add_entry(result, &entry) == -1) { - Py_DECREF(it); - Py_DECREF(result); - Py_DECREF(key); - return NULL; - } - } - Py_DECREF(key); - } - Py_DECREF(it); - if (PyErr_Occurred()) { - Py_DECREF(result); - return NULL; - } - return (PyObject *)result; + result = (PySetObject *)make_new_set_basetype(Py_TYPE(so), NULL); + if (result == NULL) + return NULL; + + if (PyAnySet_Check(other)) { + Py_ssize_t pos = 0; + setentry *entry; + + if (PySet_GET_SIZE(other) > PySet_GET_SIZE(so)) { + tmp = (PyObject *)so; + so = (PySetObject *)other; + other = tmp; + } + + while (set_next((PySetObject *)other, &pos, &entry)) { + int rv = set_contains_entry(so, entry); + if (rv == -1) { + Py_DECREF(result); + return NULL; + } + if (rv) { + if (set_add_entry(result, entry) == -1) { + Py_DECREF(result); + return NULL; + } + } + } + return (PyObject *)result; + } + + it = PyObject_GetIter(other); + if (it == NULL) { + Py_DECREF(result); + return NULL; + } + + while ((key = PyIter_Next(it)) != NULL) { + int rv; + setentry entry; + long hash = PyObject_Hash(key); + + if (hash == -1) { + Py_DECREF(it); + Py_DECREF(result); + Py_DECREF(key); + return NULL; + } + entry.hash = hash; + entry.key = key; + rv = set_contains_entry(so, &entry); + if (rv == -1) { + Py_DECREF(it); + Py_DECREF(result); + Py_DECREF(key); + return NULL; + } + if (rv) { + if (set_add_entry(result, &entry) == -1) { + Py_DECREF(it); + Py_DECREF(result); + Py_DECREF(key); + return NULL; + } + } + Py_DECREF(key); + } + Py_DECREF(it); + if (PyErr_Occurred()) { + Py_DECREF(result); + return NULL; + } + return (PyObject *)result; } static PyObject * set_intersection_multi(PySetObject *so, PyObject *args) { - Py_ssize_t i; - PyObject *result = (PyObject *)so; + Py_ssize_t i; + PyObject *result = (PyObject *)so; - if (PyTuple_GET_SIZE(args) == 0) - return set_copy(so); + if (PyTuple_GET_SIZE(args) == 0) + return set_copy(so); - Py_INCREF(so); - for (i=0 ; i PySet_GET_SIZE(so)) { - tmp = (PyObject *)so; - so = (PySetObject *)other; - other = tmp; - } - while (set_next((PySetObject *)other, &pos, &entry)) { - int rv = set_contains_entry(so, entry); - if (rv == -1) - return NULL; - if (rv) - Py_RETURN_FALSE; - } - Py_RETURN_TRUE; - } - - it = PyObject_GetIter(other); - if (it == NULL) - return NULL; - - while ((key = PyIter_Next(it)) != NULL) { - int rv; - setentry entry; - long hash = PyObject_Hash(key);; - - if (hash == -1) { - Py_DECREF(key); - Py_DECREF(it); - return NULL; - } - entry.hash = hash; - entry.key = key; - rv = set_contains_entry(so, &entry); - Py_DECREF(key); - if (rv == -1) { - Py_DECREF(it); - return NULL; - } - if (rv) { - Py_DECREF(it); - Py_RETURN_FALSE; - } - } - Py_DECREF(it); - if (PyErr_Occurred()) - return NULL; - Py_RETURN_TRUE; + if ((PyObject *)so == other) { + if (PySet_GET_SIZE(so) == 0) + Py_RETURN_TRUE; + else + Py_RETURN_FALSE; + } + + if (PyAnySet_CheckExact(other)) { + Py_ssize_t pos = 0; + setentry *entry; + + if (PySet_GET_SIZE(other) > PySet_GET_SIZE(so)) { + tmp = (PyObject *)so; + so = (PySetObject *)other; + other = tmp; + } + while (set_next((PySetObject *)other, &pos, &entry)) { + int rv = set_contains_entry(so, entry); + if (rv == -1) + return NULL; + if (rv) + Py_RETURN_FALSE; + } + Py_RETURN_TRUE; + } + + it = PyObject_GetIter(other); + if (it == NULL) + return NULL; + + while ((key = PyIter_Next(it)) != NULL) { + int rv; + setentry entry; + long hash = PyObject_Hash(key);; + + if (hash == -1) { + Py_DECREF(key); + Py_DECREF(it); + return NULL; + } + entry.hash = hash; + entry.key = key; + rv = set_contains_entry(so, &entry); + Py_DECREF(key); + if (rv == -1) { + Py_DECREF(it); + return NULL; + } + if (rv) { + Py_DECREF(it); + Py_RETURN_FALSE; + } + } + Py_DECREF(it); + if (PyErr_Occurred()) + return NULL; + Py_RETURN_TRUE; } PyDoc_STRVAR(isdisjoint_doc, @@ -1471,51 +1471,51 @@ static int set_difference_update_internal(PySetObject *so, PyObject *other) { - if ((PyObject *)so == other) - return set_clear_internal(so); - - if (PyAnySet_Check(other)) { - setentry *entry; - Py_ssize_t pos = 0; - - while (set_next((PySetObject *)other, &pos, &entry)) - if (set_discard_entry(so, entry) == -1) - return -1; - } else { - PyObject *key, *it; - it = PyObject_GetIter(other); - if (it == NULL) - return -1; - - while ((key = PyIter_Next(it)) != NULL) { - if (set_discard_key(so, key) == -1) { - Py_DECREF(it); - Py_DECREF(key); - return -1; - } - Py_DECREF(key); - } - Py_DECREF(it); - if (PyErr_Occurred()) - return -1; - } - /* If more than 1/5 are dummies, then resize them away. */ - if ((so->fill - so->used) * 5 < so->mask) - return 0; - return set_table_resize(so, so->used>50000 ? so->used*2 : so->used*4); + if ((PyObject *)so == other) + return set_clear_internal(so); + + if (PyAnySet_Check(other)) { + setentry *entry; + Py_ssize_t pos = 0; + + while (set_next((PySetObject *)other, &pos, &entry)) + if (set_discard_entry(so, entry) == -1) + return -1; + } else { + PyObject *key, *it; + it = PyObject_GetIter(other); + if (it == NULL) + return -1; + + while ((key = PyIter_Next(it)) != NULL) { + if (set_discard_key(so, key) == -1) { + Py_DECREF(it); + Py_DECREF(key); + return -1; + } + Py_DECREF(key); + } + Py_DECREF(it); + if (PyErr_Occurred()) + return -1; + } + /* If more than 1/5 are dummies, then resize them away. */ + if ((so->fill - so->used) * 5 < so->mask) + return 0; + return set_table_resize(so, so->used>50000 ? so->used*2 : so->used*4); } static PyObject * set_difference_update(PySetObject *so, PyObject *args) { - Py_ssize_t i; + Py_ssize_t i; - for (i=0 ; ihash; - entrycopy.key = entry->key; - if (!_PyDict_Contains(other, entry->key, entry->hash)) { - if (set_add_entry((PySetObject *)result, &entrycopy) == -1) { - Py_DECREF(result); - return NULL; - } - } - } - return result; - } - - while (set_next(so, &pos, &entry)) { - int rv = set_contains_entry((PySetObject *)other, entry); - if (rv == -1) { - Py_DECREF(result); - return NULL; - } - if (!rv) { - if (set_add_entry((PySetObject *)result, entry) == -1) { - Py_DECREF(result); - return NULL; - } - } - } - return result; + PyObject *result; + setentry *entry; + Py_ssize_t pos = 0; + + if (!PyAnySet_Check(other) && !PyDict_CheckExact(other)) { + result = set_copy(so); + if (result == NULL) + return NULL; + if (set_difference_update_internal((PySetObject *)result, other) != -1) + return result; + Py_DECREF(result); + return NULL; + } + + result = make_new_set_basetype(Py_TYPE(so), NULL); + if (result == NULL) + return NULL; + + if (PyDict_CheckExact(other)) { + while (set_next(so, &pos, &entry)) { + setentry entrycopy; + entrycopy.hash = entry->hash; + entrycopy.key = entry->key; + if (!_PyDict_Contains(other, entry->key, entry->hash)) { + if (set_add_entry((PySetObject *)result, &entrycopy) == -1) { + Py_DECREF(result); + return NULL; + } + } + } + return result; + } + + while (set_next(so, &pos, &entry)) { + int rv = set_contains_entry((PySetObject *)other, entry); + if (rv == -1) { + Py_DECREF(result); + return NULL; + } + if (!rv) { + if (set_add_entry((PySetObject *)result, entry) == -1) { + Py_DECREF(result); + return NULL; + } + } + } + return result; } static PyObject * set_difference_multi(PySetObject *so, PyObject *args) { - Py_ssize_t i; - PyObject *result, *other; + Py_ssize_t i; + PyObject *result, *other; - if (PyTuple_GET_SIZE(args) == 0) - return set_copy(so); + if (PyTuple_GET_SIZE(args) == 0) + return set_copy(so); - other = PyTuple_GET_ITEM(args, 0); - result = set_difference(so, other); - if (result == NULL) - return NULL; - - for (i=1 ; i PySet_GET_SIZE(other)) - Py_RETURN_FALSE; - - while (set_next(so, &pos, &entry)) { - int rv = set_contains_entry((PySetObject *)other, entry); - if (rv == -1) - return NULL; - if (!rv) - Py_RETURN_FALSE; - } - Py_RETURN_TRUE; + if (!PyAnySet_Check(other)) { + PyObject *tmp, *result; + tmp = make_new_set(&PySet_Type, other); + if (tmp == NULL) + return NULL; + result = set_issubset(so, tmp); + Py_DECREF(tmp); + return result; + } + if (PySet_GET_SIZE(so) > PySet_GET_SIZE(other)) + Py_RETURN_FALSE; + + while (set_next(so, &pos, &entry)) { + int rv = set_contains_entry((PySetObject *)other, entry); + if (rv == -1) + return NULL; + if (!rv) + Py_RETURN_FALSE; + } + Py_RETURN_TRUE; } PyDoc_STRVAR(issubset_doc, "Report whether another set contains this set."); @@ -1765,17 +1765,17 @@ static PyObject * set_issuperset(PySetObject *so, PyObject *other) { - PyObject *tmp, *result; + PyObject *tmp, *result; - if (!PyAnySet_Check(other)) { - tmp = make_new_set(&PySet_Type, other); - if (tmp == NULL) - return NULL; - result = set_issuperset(so, tmp); - Py_DECREF(tmp); - return result; - } - return set_issubset((PySetObject *)other, (PyObject *)so); + if (!PyAnySet_Check(other)) { + tmp = make_new_set(&PySet_Type, other); + if (tmp == NULL) + return NULL; + result = set_issuperset(so, tmp); + Py_DECREF(tmp); + return result; + } + return set_issubset((PySetObject *)other, (PyObject *)so); } PyDoc_STRVAR(issuperset_doc, "Report whether this set contains another set."); @@ -1783,54 +1783,54 @@ static PyObject * set_richcompare(PySetObject *v, PyObject *w, int op) { - PyObject *r1, *r2; + PyObject *r1, *r2; - if(!PyAnySet_Check(w)) { - Py_INCREF(Py_NotImplemented); - return Py_NotImplemented; - } - switch (op) { - case Py_EQ: - if (PySet_GET_SIZE(v) != PySet_GET_SIZE(w)) - Py_RETURN_FALSE; - if (v->hash != -1 && - ((PySetObject *)w)->hash != -1 && - v->hash != ((PySetObject *)w)->hash) - Py_RETURN_FALSE; - return set_issubset(v, w); - case Py_NE: - r1 = set_richcompare(v, w, Py_EQ); - if (r1 == NULL) - return NULL; - r2 = PyBool_FromLong(PyObject_Not(r1)); - Py_DECREF(r1); - return r2; - case Py_LE: - return set_issubset(v, w); - case Py_GE: - return set_issuperset(v, w); - case Py_LT: - if (PySet_GET_SIZE(v) >= PySet_GET_SIZE(w)) - Py_RETURN_FALSE; - return set_issubset(v, w); - case Py_GT: - if (PySet_GET_SIZE(v) <= PySet_GET_SIZE(w)) - Py_RETURN_FALSE; - return set_issuperset(v, w); - } - Py_INCREF(Py_NotImplemented); - return Py_NotImplemented; + if(!PyAnySet_Check(w)) { + Py_INCREF(Py_NotImplemented); + return Py_NotImplemented; + } + switch (op) { + case Py_EQ: + if (PySet_GET_SIZE(v) != PySet_GET_SIZE(w)) + Py_RETURN_FALSE; + if (v->hash != -1 && + ((PySetObject *)w)->hash != -1 && + v->hash != ((PySetObject *)w)->hash) + Py_RETURN_FALSE; + return set_issubset(v, w); + case Py_NE: + r1 = set_richcompare(v, w, Py_EQ); + if (r1 == NULL) + return NULL; + r2 = PyBool_FromLong(PyObject_Not(r1)); + Py_DECREF(r1); + return r2; + case Py_LE: + return set_issubset(v, w); + case Py_GE: + return set_issuperset(v, w); + case Py_LT: + if (PySet_GET_SIZE(v) >= PySet_GET_SIZE(w)) + Py_RETURN_FALSE; + return set_issubset(v, w); + case Py_GT: + if (PySet_GET_SIZE(v) <= PySet_GET_SIZE(w)) + Py_RETURN_FALSE; + return set_issuperset(v, w); + } + Py_INCREF(Py_NotImplemented); + return Py_NotImplemented; } static PyObject * set_add(PySetObject *so, PyObject *key) { - if (set_add_key(so, key) == -1) - return NULL; - Py_RETURN_NONE; + if (set_add_key(so, key) == -1) + return NULL; + Py_RETURN_NONE; } -PyDoc_STRVAR(add_doc, +PyDoc_STRVAR(add_doc, "Add an element to a set.\n\ \n\ This has no effect if the element is already present."); @@ -1838,34 +1838,34 @@ static int set_contains(PySetObject *so, PyObject *key) { - PyObject *tmpkey; - int rv; + PyObject *tmpkey; + int rv; - rv = set_contains_key(so, key); - if (rv == -1) { - if (!PySet_Check(key) || !PyErr_ExceptionMatches(PyExc_TypeError)) - return -1; - PyErr_Clear(); - tmpkey = make_new_set(&PyFrozenSet_Type, NULL); - if (tmpkey == NULL) - return -1; - set_swap_bodies((PySetObject *)tmpkey, (PySetObject *)key); - rv = set_contains(so, tmpkey); - set_swap_bodies((PySetObject *)tmpkey, (PySetObject *)key); - Py_DECREF(tmpkey); - } - return rv; + rv = set_contains_key(so, key); + if (rv == -1) { + if (!PySet_Check(key) || !PyErr_ExceptionMatches(PyExc_TypeError)) + return -1; + PyErr_Clear(); + tmpkey = make_new_set(&PyFrozenSet_Type, NULL); + if (tmpkey == NULL) + return -1; + set_swap_bodies((PySetObject *)tmpkey, (PySetObject *)key); + rv = set_contains(so, tmpkey); + set_swap_bodies((PySetObject *)tmpkey, (PySetObject *)key); + Py_DECREF(tmpkey); + } + return rv; } static PyObject * set_direct_contains(PySetObject *so, PyObject *key) { - long result; + long result; - result = set_contains(so, key); - if (result == -1) - return NULL; - return PyBool_FromLong(result); + result = set_contains(so, key); + if (result == -1) + return NULL; + return PyBool_FromLong(result); } PyDoc_STRVAR(contains_doc, "x.__contains__(y) <==> y in x."); @@ -1873,30 +1873,30 @@ static PyObject * set_remove(PySetObject *so, PyObject *key) { - PyObject *tmpkey; - int rv; + PyObject *tmpkey; + int rv; - rv = set_discard_key(so, key); - if (rv == -1) { - if (!PySet_Check(key) || !PyErr_ExceptionMatches(PyExc_TypeError)) - return NULL; - PyErr_Clear(); - tmpkey = make_new_set(&PyFrozenSet_Type, NULL); - if (tmpkey == NULL) - return NULL; - set_swap_bodies((PySetObject *)tmpkey, (PySetObject *)key); - rv = set_discard_key(so, tmpkey); - set_swap_bodies((PySetObject *)tmpkey, (PySetObject *)key); - Py_DECREF(tmpkey); - if (rv == -1) - return NULL; - } - - if (rv == DISCARD_NOTFOUND) { - set_key_error(key); - return NULL; - } - Py_RETURN_NONE; + rv = set_discard_key(so, key); + if (rv == -1) { + if (!PySet_Check(key) || !PyErr_ExceptionMatches(PyExc_TypeError)) + return NULL; + PyErr_Clear(); + tmpkey = make_new_set(&PyFrozenSet_Type, NULL); + if (tmpkey == NULL) + return NULL; + set_swap_bodies((PySetObject *)tmpkey, (PySetObject *)key); + rv = set_discard_key(so, tmpkey); + set_swap_bodies((PySetObject *)tmpkey, (PySetObject *)key); + Py_DECREF(tmpkey); + if (rv == -1) + return NULL; + } + + if (rv == DISCARD_NOTFOUND) { + set_key_error(key); + return NULL; + } + Py_RETURN_NONE; } PyDoc_STRVAR(remove_doc, @@ -1907,54 +1907,54 @@ static PyObject * set_discard(PySetObject *so, PyObject *key) { - PyObject *tmpkey, *result; - int rv; + PyObject *tmpkey, *result; + int rv; - rv = set_discard_key(so, key); - if (rv == -1) { - if (!PySet_Check(key) || !PyErr_ExceptionMatches(PyExc_TypeError)) - return NULL; - PyErr_Clear(); - tmpkey = make_new_set(&PyFrozenSet_Type, NULL); - if (tmpkey == NULL) - return NULL; - set_swap_bodies((PySetObject *)tmpkey, (PySetObject *)key); - result = set_discard(so, tmpkey); - set_swap_bodies((PySetObject *)tmpkey, (PySetObject *)key); - Py_DECREF(tmpkey); - return result; - } - Py_RETURN_NONE; + rv = set_discard_key(so, key); + if (rv == -1) { + if (!PySet_Check(key) || !PyErr_ExceptionMatches(PyExc_TypeError)) + return NULL; + PyErr_Clear(); + tmpkey = make_new_set(&PyFrozenSet_Type, NULL); + if (tmpkey == NULL) + return NULL; + set_swap_bodies((PySetObject *)tmpkey, (PySetObject *)key); + result = set_discard(so, tmpkey); + set_swap_bodies((PySetObject *)tmpkey, (PySetObject *)key); + Py_DECREF(tmpkey); + return result; + } + Py_RETURN_NONE; } PyDoc_STRVAR(discard_doc, "Remove an element from a set if it is a member.\n\ \n\ -If the element is not a member, do nothing."); +If the element is not a member, do nothing."); static PyObject * set_reduce(PySetObject *so) { - PyObject *keys=NULL, *args=NULL, *result=NULL, *dict=NULL; + PyObject *keys=NULL, *args=NULL, *result=NULL, *dict=NULL; - keys = PySequence_List((PyObject *)so); - if (keys == NULL) - goto done; - args = PyTuple_Pack(1, keys); - if (args == NULL) - goto done; - dict = PyObject_GetAttrString((PyObject *)so, "__dict__"); - if (dict == NULL) { - PyErr_Clear(); - dict = Py_None; - Py_INCREF(dict); - } - result = PyTuple_Pack(3, Py_TYPE(so), args, dict); + keys = PySequence_List((PyObject *)so); + if (keys == NULL) + goto done; + args = PyTuple_Pack(1, keys); + if (args == NULL) + goto done; + dict = PyObject_GetAttrString((PyObject *)so, "__dict__"); + if (dict == NULL) { + PyErr_Clear(); + dict = Py_None; + Py_INCREF(dict); + } + result = PyTuple_Pack(3, Py_TYPE(so), args, dict); done: - Py_XDECREF(args); - Py_XDECREF(keys); - Py_XDECREF(dict); - return result; + Py_XDECREF(args); + Py_XDECREF(keys); + Py_XDECREF(dict); + return result; } PyDoc_STRVAR(reduce_doc, "Return state information for pickling."); @@ -1962,42 +1962,42 @@ static PyObject * set_sizeof(PySetObject *so) { - Py_ssize_t res; + Py_ssize_t res; - res = sizeof(PySetObject); - if (so->table != so->smalltable) - res = res + (so->mask + 1) * sizeof(setentry); - return PyLong_FromSsize_t(res); + res = sizeof(PySetObject); + if (so->table != so->smalltable) + res = res + (so->mask + 1) * sizeof(setentry); + return PyLong_FromSsize_t(res); } PyDoc_STRVAR(sizeof_doc, "S.__sizeof__() -> size of S in memory, in bytes"); static int set_init(PySetObject *self, PyObject *args, PyObject *kwds) { - PyObject *iterable = NULL; + PyObject *iterable = NULL; - if (!PyAnySet_Check(self)) - return -1; - if (PySet_Check(self) && !_PyArg_NoKeywords("set()", kwds)) - return -1; - if (!PyArg_UnpackTuple(args, Py_TYPE(self)->tp_name, 0, 1, &iterable)) - return -1; - set_clear_internal(self); - self->hash = -1; - if (iterable == NULL) - return 0; - return set_update_internal(self, iterable); + if (!PyAnySet_Check(self)) + return -1; + if (PySet_Check(self) && !_PyArg_NoKeywords("set()", kwds)) + return -1; + if (!PyArg_UnpackTuple(args, Py_TYPE(self)->tp_name, 0, 1, &iterable)) + return -1; + set_clear_internal(self); + self->hash = -1; + if (iterable == NULL) + return 0; + return set_update_internal(self, iterable); } static PySequenceMethods set_as_sequence = { - set_len, /* sq_length */ - 0, /* sq_concat */ - 0, /* sq_repeat */ - 0, /* sq_item */ - 0, /* sq_slice */ - 0, /* sq_ass_item */ - 0, /* sq_ass_slice */ - (objobjproc)set_contains, /* sq_contains */ + set_len, /* sq_length */ + 0, /* sq_concat */ + 0, /* sq_repeat */ + 0, /* sq_item */ + 0, /* sq_slice */ + 0, /* sq_ass_item */ + 0, /* sq_ass_slice */ + (objobjproc)set_contains, /* sq_contains */ }; /* set object ********************************************************/ @@ -2010,83 +2010,83 @@ #endif static PyMethodDef set_methods[] = { - {"add", (PyCFunction)set_add, METH_O, - add_doc}, - {"clear", (PyCFunction)set_clear, METH_NOARGS, - clear_doc}, - {"__contains__",(PyCFunction)set_direct_contains, METH_O | METH_COEXIST, - contains_doc}, - {"copy", (PyCFunction)set_copy, METH_NOARGS, - copy_doc}, - {"discard", (PyCFunction)set_discard, METH_O, - discard_doc}, - {"difference", (PyCFunction)set_difference_multi, METH_VARARGS, - difference_doc}, - {"difference_update", (PyCFunction)set_difference_update, METH_VARARGS, - difference_update_doc}, - {"intersection",(PyCFunction)set_intersection_multi, METH_VARARGS, - intersection_doc}, - {"intersection_update",(PyCFunction)set_intersection_update_multi, METH_VARARGS, - intersection_update_doc}, - {"isdisjoint", (PyCFunction)set_isdisjoint, METH_O, - isdisjoint_doc}, - {"issubset", (PyCFunction)set_issubset, METH_O, - issubset_doc}, - {"issuperset", (PyCFunction)set_issuperset, METH_O, - issuperset_doc}, - {"pop", (PyCFunction)set_pop, METH_NOARGS, - pop_doc}, - {"__reduce__", (PyCFunction)set_reduce, METH_NOARGS, - reduce_doc}, - {"remove", (PyCFunction)set_remove, METH_O, - remove_doc}, - {"__sizeof__", (PyCFunction)set_sizeof, METH_NOARGS, - sizeof_doc}, - {"symmetric_difference",(PyCFunction)set_symmetric_difference, METH_O, - symmetric_difference_doc}, - {"symmetric_difference_update",(PyCFunction)set_symmetric_difference_update, METH_O, - symmetric_difference_update_doc}, + {"add", (PyCFunction)set_add, METH_O, + add_doc}, + {"clear", (PyCFunction)set_clear, METH_NOARGS, + clear_doc}, + {"__contains__",(PyCFunction)set_direct_contains, METH_O | METH_COEXIST, + contains_doc}, + {"copy", (PyCFunction)set_copy, METH_NOARGS, + copy_doc}, + {"discard", (PyCFunction)set_discard, METH_O, + discard_doc}, + {"difference", (PyCFunction)set_difference_multi, METH_VARARGS, + difference_doc}, + {"difference_update", (PyCFunction)set_difference_update, METH_VARARGS, + difference_update_doc}, + {"intersection",(PyCFunction)set_intersection_multi, METH_VARARGS, + intersection_doc}, + {"intersection_update",(PyCFunction)set_intersection_update_multi, METH_VARARGS, + intersection_update_doc}, + {"isdisjoint", (PyCFunction)set_isdisjoint, METH_O, + isdisjoint_doc}, + {"issubset", (PyCFunction)set_issubset, METH_O, + issubset_doc}, + {"issuperset", (PyCFunction)set_issuperset, METH_O, + issuperset_doc}, + {"pop", (PyCFunction)set_pop, METH_NOARGS, + pop_doc}, + {"__reduce__", (PyCFunction)set_reduce, METH_NOARGS, + reduce_doc}, + {"remove", (PyCFunction)set_remove, METH_O, + remove_doc}, + {"__sizeof__", (PyCFunction)set_sizeof, METH_NOARGS, + sizeof_doc}, + {"symmetric_difference",(PyCFunction)set_symmetric_difference, METH_O, + symmetric_difference_doc}, + {"symmetric_difference_update",(PyCFunction)set_symmetric_difference_update, METH_O, + symmetric_difference_update_doc}, #ifdef Py_DEBUG - {"test_c_api", (PyCFunction)test_c_api, METH_NOARGS, - test_c_api_doc}, + {"test_c_api", (PyCFunction)test_c_api, METH_NOARGS, + test_c_api_doc}, #endif - {"union", (PyCFunction)set_union, METH_VARARGS, - union_doc}, - {"update", (PyCFunction)set_update, METH_VARARGS, - update_doc}, - {NULL, NULL} /* sentinel */ + {"union", (PyCFunction)set_union, METH_VARARGS, + union_doc}, + {"update", (PyCFunction)set_update, METH_VARARGS, + update_doc}, + {NULL, NULL} /* sentinel */ }; static PyNumberMethods set_as_number = { - 0, /*nb_add*/ - (binaryfunc)set_sub, /*nb_subtract*/ - 0, /*nb_multiply*/ - 0, /*nb_remainder*/ - 0, /*nb_divmod*/ - 0, /*nb_power*/ - 0, /*nb_negative*/ - 0, /*nb_positive*/ - 0, /*nb_absolute*/ - 0, /*nb_bool*/ - 0, /*nb_invert*/ - 0, /*nb_lshift*/ - 0, /*nb_rshift*/ - (binaryfunc)set_and, /*nb_and*/ - (binaryfunc)set_xor, /*nb_xor*/ - (binaryfunc)set_or, /*nb_or*/ - 0, /*nb_int*/ - 0, /*nb_reserved*/ - 0, /*nb_float*/ - 0, /*nb_inplace_add*/ - (binaryfunc)set_isub, /*nb_inplace_subtract*/ - 0, /*nb_inplace_multiply*/ - 0, /*nb_inplace_remainder*/ - 0, /*nb_inplace_power*/ - 0, /*nb_inplace_lshift*/ - 0, /*nb_inplace_rshift*/ - (binaryfunc)set_iand, /*nb_inplace_and*/ - (binaryfunc)set_ixor, /*nb_inplace_xor*/ - (binaryfunc)set_ior, /*nb_inplace_or*/ + 0, /*nb_add*/ + (binaryfunc)set_sub, /*nb_subtract*/ + 0, /*nb_multiply*/ + 0, /*nb_remainder*/ + 0, /*nb_divmod*/ + 0, /*nb_power*/ + 0, /*nb_negative*/ + 0, /*nb_positive*/ + 0, /*nb_absolute*/ + 0, /*nb_bool*/ + 0, /*nb_invert*/ + 0, /*nb_lshift*/ + 0, /*nb_rshift*/ + (binaryfunc)set_and, /*nb_and*/ + (binaryfunc)set_xor, /*nb_xor*/ + (binaryfunc)set_or, /*nb_or*/ + 0, /*nb_int*/ + 0, /*nb_reserved*/ + 0, /*nb_float*/ + 0, /*nb_inplace_add*/ + (binaryfunc)set_isub, /*nb_inplace_subtract*/ + 0, /*nb_inplace_multiply*/ + 0, /*nb_inplace_remainder*/ + 0, /*nb_inplace_power*/ + 0, /*nb_inplace_lshift*/ + 0, /*nb_inplace_rshift*/ + (binaryfunc)set_iand, /*nb_inplace_and*/ + (binaryfunc)set_ixor, /*nb_inplace_xor*/ + (binaryfunc)set_ior, /*nb_inplace_or*/ }; PyDoc_STRVAR(set_doc, @@ -2096,95 +2096,95 @@ Build an unordered collection of unique elements."); PyTypeObject PySet_Type = { - PyVarObject_HEAD_INIT(&PyType_Type, 0) - "set", /* tp_name */ - sizeof(PySetObject), /* tp_basicsize */ - 0, /* tp_itemsize */ - /* methods */ - (destructor)set_dealloc, /* tp_dealloc */ - 0, /* tp_print */ - 0, /* tp_getattr */ - 0, /* tp_setattr */ - 0, /* tp_reserved */ - (reprfunc)set_repr, /* tp_repr */ - &set_as_number, /* tp_as_number */ - &set_as_sequence, /* tp_as_sequence */ - 0, /* tp_as_mapping */ - (hashfunc)PyObject_HashNotImplemented, /* 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 | - Py_TPFLAGS_BASETYPE, /* tp_flags */ - set_doc, /* tp_doc */ - (traverseproc)set_traverse, /* tp_traverse */ - (inquiry)set_clear_internal, /* tp_clear */ - (richcmpfunc)set_richcompare, /* tp_richcompare */ - offsetof(PySetObject, weakreflist), /* tp_weaklistoffset */ - (getiterfunc)set_iter, /* tp_iter */ - 0, /* tp_iternext */ - set_methods, /* tp_methods */ - 0, /* tp_members */ - 0, /* tp_getset */ - 0, /* tp_base */ - 0, /* tp_dict */ - 0, /* tp_descr_get */ - 0, /* tp_descr_set */ - 0, /* tp_dictoffset */ - (initproc)set_init, /* tp_init */ - PyType_GenericAlloc, /* tp_alloc */ - set_new, /* tp_new */ - PyObject_GC_Del, /* tp_free */ + PyVarObject_HEAD_INIT(&PyType_Type, 0) + "set", /* tp_name */ + sizeof(PySetObject), /* tp_basicsize */ + 0, /* tp_itemsize */ + /* methods */ + (destructor)set_dealloc, /* tp_dealloc */ + 0, /* tp_print */ + 0, /* tp_getattr */ + 0, /* tp_setattr */ + 0, /* tp_reserved */ + (reprfunc)set_repr, /* tp_repr */ + &set_as_number, /* tp_as_number */ + &set_as_sequence, /* tp_as_sequence */ + 0, /* tp_as_mapping */ + (hashfunc)PyObject_HashNotImplemented, /* 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 | + Py_TPFLAGS_BASETYPE, /* tp_flags */ + set_doc, /* tp_doc */ + (traverseproc)set_traverse, /* tp_traverse */ + (inquiry)set_clear_internal, /* tp_clear */ + (richcmpfunc)set_richcompare, /* tp_richcompare */ + offsetof(PySetObject, weakreflist), /* tp_weaklistoffset */ + (getiterfunc)set_iter, /* tp_iter */ + 0, /* tp_iternext */ + set_methods, /* tp_methods */ + 0, /* tp_members */ + 0, /* tp_getset */ + 0, /* tp_base */ + 0, /* tp_dict */ + 0, /* tp_descr_get */ + 0, /* tp_descr_set */ + 0, /* tp_dictoffset */ + (initproc)set_init, /* tp_init */ + PyType_GenericAlloc, /* tp_alloc */ + set_new, /* tp_new */ + PyObject_GC_Del, /* tp_free */ }; /* frozenset object ********************************************************/ static PyMethodDef frozenset_methods[] = { - {"__contains__",(PyCFunction)set_direct_contains, METH_O | METH_COEXIST, - contains_doc}, - {"copy", (PyCFunction)frozenset_copy, METH_NOARGS, - copy_doc}, - {"difference", (PyCFunction)set_difference_multi, METH_VARARGS, - difference_doc}, - {"intersection",(PyCFunction)set_intersection_multi, METH_VARARGS, - intersection_doc}, - {"isdisjoint", (PyCFunction)set_isdisjoint, METH_O, - isdisjoint_doc}, - {"issubset", (PyCFunction)set_issubset, METH_O, - issubset_doc}, - {"issuperset", (PyCFunction)set_issuperset, METH_O, - issuperset_doc}, - {"__reduce__", (PyCFunction)set_reduce, METH_NOARGS, - reduce_doc}, - {"__sizeof__", (PyCFunction)set_sizeof, METH_NOARGS, - sizeof_doc}, - {"symmetric_difference",(PyCFunction)set_symmetric_difference, METH_O, - symmetric_difference_doc}, - {"union", (PyCFunction)set_union, METH_VARARGS, - union_doc}, - {NULL, NULL} /* sentinel */ + {"__contains__",(PyCFunction)set_direct_contains, METH_O | METH_COEXIST, + contains_doc}, + {"copy", (PyCFunction)frozenset_copy, METH_NOARGS, + copy_doc}, + {"difference", (PyCFunction)set_difference_multi, METH_VARARGS, + difference_doc}, + {"intersection",(PyCFunction)set_intersection_multi, METH_VARARGS, + intersection_doc}, + {"isdisjoint", (PyCFunction)set_isdisjoint, METH_O, + isdisjoint_doc}, + {"issubset", (PyCFunction)set_issubset, METH_O, + issubset_doc}, + {"issuperset", (PyCFunction)set_issuperset, METH_O, + issuperset_doc}, + {"__reduce__", (PyCFunction)set_reduce, METH_NOARGS, + reduce_doc}, + {"__sizeof__", (PyCFunction)set_sizeof, METH_NOARGS, + sizeof_doc}, + {"symmetric_difference",(PyCFunction)set_symmetric_difference, METH_O, + symmetric_difference_doc}, + {"union", (PyCFunction)set_union, METH_VARARGS, + union_doc}, + {NULL, NULL} /* sentinel */ }; static PyNumberMethods frozenset_as_number = { - 0, /*nb_add*/ - (binaryfunc)set_sub, /*nb_subtract*/ - 0, /*nb_multiply*/ - 0, /*nb_remainder*/ - 0, /*nb_divmod*/ - 0, /*nb_power*/ - 0, /*nb_negative*/ - 0, /*nb_positive*/ - 0, /*nb_absolute*/ - 0, /*nb_bool*/ - 0, /*nb_invert*/ - 0, /*nb_lshift*/ - 0, /*nb_rshift*/ - (binaryfunc)set_and, /*nb_and*/ - (binaryfunc)set_xor, /*nb_xor*/ - (binaryfunc)set_or, /*nb_or*/ + 0, /*nb_add*/ + (binaryfunc)set_sub, /*nb_subtract*/ + 0, /*nb_multiply*/ + 0, /*nb_remainder*/ + 0, /*nb_divmod*/ + 0, /*nb_power*/ + 0, /*nb_negative*/ + 0, /*nb_positive*/ + 0, /*nb_absolute*/ + 0, /*nb_bool*/ + 0, /*nb_invert*/ + 0, /*nb_lshift*/ + 0, /*nb_rshift*/ + (binaryfunc)set_and, /*nb_and*/ + (binaryfunc)set_xor, /*nb_xor*/ + (binaryfunc)set_or, /*nb_or*/ }; PyDoc_STRVAR(frozenset_doc, @@ -2194,47 +2194,47 @@ Build an immutable unordered collection of unique elements."); PyTypeObject PyFrozenSet_Type = { - PyVarObject_HEAD_INIT(&PyType_Type, 0) - "frozenset", /* tp_name */ - sizeof(PySetObject), /* tp_basicsize */ - 0, /* tp_itemsize */ - /* methods */ - (destructor)set_dealloc, /* tp_dealloc */ - 0, /* tp_print */ - 0, /* tp_getattr */ - 0, /* tp_setattr */ - 0, /* tp_reserved */ - (reprfunc)set_repr, /* tp_repr */ - &frozenset_as_number, /* tp_as_number */ - &set_as_sequence, /* tp_as_sequence */ - 0, /* tp_as_mapping */ - frozenset_hash, /* 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 | - Py_TPFLAGS_BASETYPE, /* tp_flags */ - frozenset_doc, /* tp_doc */ - (traverseproc)set_traverse, /* tp_traverse */ - (inquiry)set_clear_internal, /* tp_clear */ - (richcmpfunc)set_richcompare, /* tp_richcompare */ - offsetof(PySetObject, weakreflist), /* tp_weaklistoffset */ - (getiterfunc)set_iter, /* tp_iter */ - 0, /* tp_iternext */ - frozenset_methods, /* tp_methods */ - 0, /* tp_members */ - 0, /* tp_getset */ - 0, /* tp_base */ - 0, /* tp_dict */ - 0, /* tp_descr_get */ - 0, /* tp_descr_set */ - 0, /* tp_dictoffset */ - 0, /* tp_init */ - PyType_GenericAlloc, /* tp_alloc */ - frozenset_new, /* tp_new */ - PyObject_GC_Del, /* tp_free */ + PyVarObject_HEAD_INIT(&PyType_Type, 0) + "frozenset", /* tp_name */ + sizeof(PySetObject), /* tp_basicsize */ + 0, /* tp_itemsize */ + /* methods */ + (destructor)set_dealloc, /* tp_dealloc */ + 0, /* tp_print */ + 0, /* tp_getattr */ + 0, /* tp_setattr */ + 0, /* tp_reserved */ + (reprfunc)set_repr, /* tp_repr */ + &frozenset_as_number, /* tp_as_number */ + &set_as_sequence, /* tp_as_sequence */ + 0, /* tp_as_mapping */ + frozenset_hash, /* 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 | + Py_TPFLAGS_BASETYPE, /* tp_flags */ + frozenset_doc, /* tp_doc */ + (traverseproc)set_traverse, /* tp_traverse */ + (inquiry)set_clear_internal, /* tp_clear */ + (richcmpfunc)set_richcompare, /* tp_richcompare */ + offsetof(PySetObject, weakreflist), /* tp_weaklistoffset */ + (getiterfunc)set_iter, /* tp_iter */ + 0, /* tp_iternext */ + frozenset_methods, /* tp_methods */ + 0, /* tp_members */ + 0, /* tp_getset */ + 0, /* tp_base */ + 0, /* tp_dict */ + 0, /* tp_descr_get */ + 0, /* tp_descr_set */ + 0, /* tp_dictoffset */ + 0, /* tp_init */ + PyType_GenericAlloc, /* tp_alloc */ + frozenset_new, /* tp_new */ + PyObject_GC_Del, /* tp_free */ }; @@ -2243,238 +2243,238 @@ PyObject * PySet_New(PyObject *iterable) { - return make_new_set(&PySet_Type, iterable); + return make_new_set(&PySet_Type, iterable); } PyObject * PyFrozenSet_New(PyObject *iterable) { - return make_new_set(&PyFrozenSet_Type, iterable); + return make_new_set(&PyFrozenSet_Type, iterable); } Py_ssize_t PySet_Size(PyObject *anyset) { - if (!PyAnySet_Check(anyset)) { - PyErr_BadInternalCall(); - return -1; - } - return PySet_GET_SIZE(anyset); + if (!PyAnySet_Check(anyset)) { + PyErr_BadInternalCall(); + return -1; + } + return PySet_GET_SIZE(anyset); } int PySet_Clear(PyObject *set) { - if (!PySet_Check(set)) { - PyErr_BadInternalCall(); - return -1; - } - return set_clear_internal((PySetObject *)set); + if (!PySet_Check(set)) { + PyErr_BadInternalCall(); + return -1; + } + return set_clear_internal((PySetObject *)set); } int PySet_Contains(PyObject *anyset, PyObject *key) { - if (!PyAnySet_Check(anyset)) { - PyErr_BadInternalCall(); - return -1; - } - return set_contains_key((PySetObject *)anyset, key); + if (!PyAnySet_Check(anyset)) { + PyErr_BadInternalCall(); + return -1; + } + return set_contains_key((PySetObject *)anyset, key); } int PySet_Discard(PyObject *set, PyObject *key) { - if (!PySet_Check(set)) { - PyErr_BadInternalCall(); - return -1; - } - return set_discard_key((PySetObject *)set, key); + if (!PySet_Check(set)) { + PyErr_BadInternalCall(); + return -1; + } + return set_discard_key((PySetObject *)set, key); } int PySet_Add(PyObject *anyset, PyObject *key) { - if (!PySet_Check(anyset) && - (!PyFrozenSet_Check(anyset) || Py_REFCNT(anyset) != 1)) { - PyErr_BadInternalCall(); - return -1; - } - return set_add_key((PySetObject *)anyset, key); + if (!PySet_Check(anyset) && + (!PyFrozenSet_Check(anyset) || Py_REFCNT(anyset) != 1)) { + PyErr_BadInternalCall(); + return -1; + } + return set_add_key((PySetObject *)anyset, key); } int _PySet_NextEntry(PyObject *set, Py_ssize_t *pos, PyObject **key, long *hash) { - setentry *entry; + setentry *entry; - if (!PyAnySet_Check(set)) { - PyErr_BadInternalCall(); - return -1; - } - if (set_next((PySetObject *)set, pos, &entry) == 0) - return 0; - *key = entry->key; - *hash = entry->hash; - return 1; + if (!PyAnySet_Check(set)) { + PyErr_BadInternalCall(); + return -1; + } + if (set_next((PySetObject *)set, pos, &entry) == 0) + return 0; + *key = entry->key; + *hash = entry->hash; + return 1; } PyObject * PySet_Pop(PyObject *set) { - if (!PySet_Check(set)) { - PyErr_BadInternalCall(); - return NULL; - } - return set_pop((PySetObject *)set); + if (!PySet_Check(set)) { + PyErr_BadInternalCall(); + return NULL; + } + return set_pop((PySetObject *)set); } int _PySet_Update(PyObject *set, PyObject *iterable) { - if (!PySet_Check(set)) { - PyErr_BadInternalCall(); - return -1; - } - return set_update_internal((PySetObject *)set, iterable); + if (!PySet_Check(set)) { + PyErr_BadInternalCall(); + return -1; + } + return set_update_internal((PySetObject *)set, iterable); } #ifdef Py_DEBUG -/* Test code to be called with any three element set. +/* Test code to be called with any three element set. Returns True and original set is restored. */ -#define assertRaises(call_return_value, exception) \ - do { \ - assert(call_return_value); \ - assert(PyErr_ExceptionMatches(exception)); \ - PyErr_Clear(); \ - } while(0) +#define assertRaises(call_return_value, exception) \ + do { \ + assert(call_return_value); \ + assert(PyErr_ExceptionMatches(exception)); \ + PyErr_Clear(); \ + } while(0) static PyObject * test_c_api(PySetObject *so) { - Py_ssize_t count; - char *s; - Py_ssize_t i; - PyObject *elem=NULL, *dup=NULL, *t, *f, *dup2, *x; - PyObject *ob = (PyObject *)so; - long hash; - PyObject *str; - - /* Verify preconditions */ - assert(PyAnySet_Check(ob)); - assert(PyAnySet_CheckExact(ob)); - assert(!PyFrozenSet_CheckExact(ob)); - - /* so.clear(); so |= set("abc"); */ - str = PyUnicode_FromString("abc"); - if (str == NULL) - return NULL; - set_clear_internal(so); - if (set_update_internal(so, str) == -1) { - Py_DECREF(str); - return NULL; - } - Py_DECREF(str); - - /* Exercise type/size checks */ - assert(PySet_Size(ob) == 3); - assert(PySet_GET_SIZE(ob) == 3); - - /* Raise TypeError for non-iterable constructor arguments */ - assertRaises(PySet_New(Py_None) == NULL, PyExc_TypeError); - assertRaises(PyFrozenSet_New(Py_None) == NULL, PyExc_TypeError); - - /* Raise TypeError for unhashable key */ - dup = PySet_New(ob); - assertRaises(PySet_Discard(ob, dup) == -1, PyExc_TypeError); - assertRaises(PySet_Contains(ob, dup) == -1, PyExc_TypeError); - assertRaises(PySet_Add(ob, dup) == -1, PyExc_TypeError); - - /* Exercise successful pop, contains, add, and discard */ - elem = PySet_Pop(ob); - assert(PySet_Contains(ob, elem) == 0); - assert(PySet_GET_SIZE(ob) == 2); - assert(PySet_Add(ob, elem) == 0); - assert(PySet_Contains(ob, elem) == 1); - assert(PySet_GET_SIZE(ob) == 3); - assert(PySet_Discard(ob, elem) == 1); - assert(PySet_GET_SIZE(ob) == 2); - assert(PySet_Discard(ob, elem) == 0); - assert(PySet_GET_SIZE(ob) == 2); - - /* Exercise clear */ - dup2 = PySet_New(dup); - assert(PySet_Clear(dup2) == 0); - assert(PySet_Size(dup2) == 0); - Py_DECREF(dup2); - - /* Raise SystemError on clear or update of frozen set */ - f = PyFrozenSet_New(dup); - assertRaises(PySet_Clear(f) == -1, PyExc_SystemError); - assertRaises(_PySet_Update(f, dup) == -1, PyExc_SystemError); - assert(PySet_Add(f, elem) == 0); - Py_INCREF(f); - assertRaises(PySet_Add(f, elem) == -1, PyExc_SystemError); - Py_DECREF(f); - Py_DECREF(f); - - /* Exercise direct iteration */ - i = 0, count = 0; - while (_PySet_NextEntry((PyObject *)dup, &i, &x, &hash)) { - s = _PyUnicode_AsString(x); - assert(s && (s[0] == 'a' || s[0] == 'b' || s[0] == 'c')); - count++; - } - assert(count == 3); - - /* Exercise updates */ - dup2 = PySet_New(NULL); - assert(_PySet_Update(dup2, dup) == 0); - assert(PySet_Size(dup2) == 3); - assert(_PySet_Update(dup2, dup) == 0); - assert(PySet_Size(dup2) == 3); - Py_DECREF(dup2); - - /* Raise SystemError when self argument is not a set or frozenset. */ - t = PyTuple_New(0); - assertRaises(PySet_Size(t) == -1, PyExc_SystemError); - assertRaises(PySet_Contains(t, elem) == -1, PyExc_SystemError); - Py_DECREF(t); - - /* Raise SystemError when self argument is not a set. */ - f = PyFrozenSet_New(dup); - assert(PySet_Size(f) == 3); - assert(PyFrozenSet_CheckExact(f)); - assertRaises(PySet_Discard(f, elem) == -1, PyExc_SystemError); - assertRaises(PySet_Pop(f) == NULL, PyExc_SystemError); - Py_DECREF(f); - - /* Raise KeyError when popping from an empty set */ - assert(PyNumber_InPlaceSubtract(ob, ob) == ob); - Py_DECREF(ob); - assert(PySet_GET_SIZE(ob) == 0); - assertRaises(PySet_Pop(ob) == NULL, PyExc_KeyError); - - /* Restore the set from the copy using the PyNumber API */ - assert(PyNumber_InPlaceOr(ob, dup) == ob); - Py_DECREF(ob); - - /* Verify constructors accept NULL arguments */ - f = PySet_New(NULL); - assert(f != NULL); - assert(PySet_GET_SIZE(f) == 0); - Py_DECREF(f); - f = PyFrozenSet_New(NULL); - assert(f != NULL); - assert(PyFrozenSet_CheckExact(f)); - assert(PySet_GET_SIZE(f) == 0); - Py_DECREF(f); - - Py_DECREF(elem); - Py_DECREF(dup); - Py_RETURN_TRUE; + Py_ssize_t count; + char *s; + Py_ssize_t i; + PyObject *elem=NULL, *dup=NULL, *t, *f, *dup2, *x; + PyObject *ob = (PyObject *)so; + long hash; + PyObject *str; + + /* Verify preconditions */ + assert(PyAnySet_Check(ob)); + assert(PyAnySet_CheckExact(ob)); + assert(!PyFrozenSet_CheckExact(ob)); + + /* so.clear(); so |= set("abc"); */ + str = PyUnicode_FromString("abc"); + if (str == NULL) + return NULL; + set_clear_internal(so); + if (set_update_internal(so, str) == -1) { + Py_DECREF(str); + return NULL; + } + Py_DECREF(str); + + /* Exercise type/size checks */ + assert(PySet_Size(ob) == 3); + assert(PySet_GET_SIZE(ob) == 3); + + /* Raise TypeError for non-iterable constructor arguments */ + assertRaises(PySet_New(Py_None) == NULL, PyExc_TypeError); + assertRaises(PyFrozenSet_New(Py_None) == NULL, PyExc_TypeError); + + /* Raise TypeError for unhashable key */ + dup = PySet_New(ob); + assertRaises(PySet_Discard(ob, dup) == -1, PyExc_TypeError); + assertRaises(PySet_Contains(ob, dup) == -1, PyExc_TypeError); + assertRaises(PySet_Add(ob, dup) == -1, PyExc_TypeError); + + /* Exercise successful pop, contains, add, and discard */ + elem = PySet_Pop(ob); + assert(PySet_Contains(ob, elem) == 0); + assert(PySet_GET_SIZE(ob) == 2); + assert(PySet_Add(ob, elem) == 0); + assert(PySet_Contains(ob, elem) == 1); + assert(PySet_GET_SIZE(ob) == 3); + assert(PySet_Discard(ob, elem) == 1); + assert(PySet_GET_SIZE(ob) == 2); + assert(PySet_Discard(ob, elem) == 0); + assert(PySet_GET_SIZE(ob) == 2); + + /* Exercise clear */ + dup2 = PySet_New(dup); + assert(PySet_Clear(dup2) == 0); + assert(PySet_Size(dup2) == 0); + Py_DECREF(dup2); + + /* Raise SystemError on clear or update of frozen set */ + f = PyFrozenSet_New(dup); + assertRaises(PySet_Clear(f) == -1, PyExc_SystemError); + assertRaises(_PySet_Update(f, dup) == -1, PyExc_SystemError); + assert(PySet_Add(f, elem) == 0); + Py_INCREF(f); + assertRaises(PySet_Add(f, elem) == -1, PyExc_SystemError); + Py_DECREF(f); + Py_DECREF(f); + + /* Exercise direct iteration */ + i = 0, count = 0; + while (_PySet_NextEntry((PyObject *)dup, &i, &x, &hash)) { + s = _PyUnicode_AsString(x); + assert(s && (s[0] == 'a' || s[0] == 'b' || s[0] == 'c')); + count++; + } + assert(count == 3); + + /* Exercise updates */ + dup2 = PySet_New(NULL); + assert(_PySet_Update(dup2, dup) == 0); + assert(PySet_Size(dup2) == 3); + assert(_PySet_Update(dup2, dup) == 0); + assert(PySet_Size(dup2) == 3); + Py_DECREF(dup2); + + /* Raise SystemError when self argument is not a set or frozenset. */ + t = PyTuple_New(0); + assertRaises(PySet_Size(t) == -1, PyExc_SystemError); + assertRaises(PySet_Contains(t, elem) == -1, PyExc_SystemError); + Py_DECREF(t); + + /* Raise SystemError when self argument is not a set. */ + f = PyFrozenSet_New(dup); + assert(PySet_Size(f) == 3); + assert(PyFrozenSet_CheckExact(f)); + assertRaises(PySet_Discard(f, elem) == -1, PyExc_SystemError); + assertRaises(PySet_Pop(f) == NULL, PyExc_SystemError); + Py_DECREF(f); + + /* Raise KeyError when popping from an empty set */ + assert(PyNumber_InPlaceSubtract(ob, ob) == ob); + Py_DECREF(ob); + assert(PySet_GET_SIZE(ob) == 0); + assertRaises(PySet_Pop(ob) == NULL, PyExc_KeyError); + + /* Restore the set from the copy using the PyNumber API */ + assert(PyNumber_InPlaceOr(ob, dup) == ob); + Py_DECREF(ob); + + /* Verify constructors accept NULL arguments */ + f = PySet_New(NULL); + assert(f != NULL); + assert(PySet_GET_SIZE(f) == 0); + Py_DECREF(f); + f = PyFrozenSet_New(NULL); + assert(f != NULL); + assert(PyFrozenSet_CheckExact(f)); + assert(PySet_GET_SIZE(f) == 0); + Py_DECREF(f); + + Py_DECREF(elem); + Py_DECREF(dup); + Py_RETURN_TRUE; } #undef assertRaises Modified: python/branches/py3k/Objects/sliceobject.c ============================================================================== --- python/branches/py3k/Objects/sliceobject.c (original) +++ python/branches/py3k/Objects/sliceobject.c Sun May 9 17:52:27 2010 @@ -7,7 +7,7 @@ for this file. */ -/* +/* Py_Ellipsis encodes the '...' rubber index token. It is similar to the Py_NoneStruct in that there is no way to create other objects of this type and there is exactly one in existence. @@ -19,35 +19,35 @@ static PyObject * ellipsis_repr(PyObject *op) { - return PyUnicode_FromString("Ellipsis"); + return PyUnicode_FromString("Ellipsis"); } PyTypeObject PyEllipsis_Type = { - PyVarObject_HEAD_INIT(&PyType_Type, 0) - "ellipsis", /* tp_name */ - 0, /* tp_basicsize */ - 0, /* tp_itemsize */ - 0, /*never called*/ /* tp_dealloc */ - 0, /* tp_print */ - 0, /* tp_getattr */ - 0, /* tp_setattr */ - 0, /* tp_reserved */ - ellipsis_repr, /* tp_repr */ - 0, /* tp_as_number */ - 0, /* tp_as_sequence */ - 0, /* tp_as_mapping */ - 0, /* tp_hash */ - 0, /* tp_call */ - 0, /* tp_str */ - PyObject_GenericGetAttr, /* tp_getattro */ - 0, /* tp_setattro */ - 0, /* tp_as_buffer */ - Py_TPFLAGS_DEFAULT, /* tp_flags */ + PyVarObject_HEAD_INIT(&PyType_Type, 0) + "ellipsis", /* tp_name */ + 0, /* tp_basicsize */ + 0, /* tp_itemsize */ + 0, /*never called*/ /* tp_dealloc */ + 0, /* tp_print */ + 0, /* tp_getattr */ + 0, /* tp_setattr */ + 0, /* tp_reserved */ + ellipsis_repr, /* tp_repr */ + 0, /* tp_as_number */ + 0, /* tp_as_sequence */ + 0, /* tp_as_mapping */ + 0, /* tp_hash */ + 0, /* tp_call */ + 0, /* tp_str */ + PyObject_GenericGetAttr, /* tp_getattro */ + 0, /* tp_setattro */ + 0, /* tp_as_buffer */ + Py_TPFLAGS_DEFAULT, /* tp_flags */ }; PyObject _Py_EllipsisObject = { - _PyObject_EXTRA_INIT - 1, &PyEllipsis_Type + _PyObject_EXTRA_INIT + 1, &PyEllipsis_Type }; @@ -60,154 +60,154 @@ PyObject * PySlice_New(PyObject *start, PyObject *stop, PyObject *step) { - PySliceObject *obj = PyObject_New(PySliceObject, &PySlice_Type); + PySliceObject *obj = PyObject_New(PySliceObject, &PySlice_Type); - if (obj == NULL) - return NULL; + if (obj == NULL) + return NULL; - if (step == NULL) step = Py_None; - Py_INCREF(step); - if (start == NULL) start = Py_None; - Py_INCREF(start); - if (stop == NULL) stop = Py_None; - Py_INCREF(stop); - - obj->step = step; - obj->start = start; - obj->stop = stop; + if (step == NULL) step = Py_None; + Py_INCREF(step); + if (start == NULL) start = Py_None; + Py_INCREF(start); + if (stop == NULL) stop = Py_None; + Py_INCREF(stop); + + obj->step = step; + obj->start = start; + obj->stop = stop; - return (PyObject *) obj; + return (PyObject *) obj; } PyObject * _PySlice_FromIndices(Py_ssize_t istart, Py_ssize_t istop) { - PyObject *start, *end, *slice; - start = PyLong_FromSsize_t(istart); - if (!start) - return NULL; - end = PyLong_FromSsize_t(istop); - if (!end) { - Py_DECREF(start); - return NULL; - } - - slice = PySlice_New(start, end, NULL); - Py_DECREF(start); - Py_DECREF(end); - return slice; + PyObject *start, *end, *slice; + start = PyLong_FromSsize_t(istart); + if (!start) + return NULL; + end = PyLong_FromSsize_t(istop); + if (!end) { + Py_DECREF(start); + return NULL; + } + + slice = PySlice_New(start, end, NULL); + Py_DECREF(start); + Py_DECREF(end); + return slice; } int PySlice_GetIndices(PySliceObject *r, Py_ssize_t length, Py_ssize_t *start, Py_ssize_t *stop, Py_ssize_t *step) { - /* XXX support long ints */ - if (r->step == Py_None) { - *step = 1; - } else { - if (!PyLong_Check(r->step)) return -1; - *step = PyLong_AsSsize_t(r->step); - } - if (r->start == Py_None) { - *start = *step < 0 ? length-1 : 0; - } else { - if (!PyLong_Check(r->start)) return -1; - *start = PyLong_AsSsize_t(r->start); - if (*start < 0) *start += length; - } - if (r->stop == Py_None) { - *stop = *step < 0 ? -1 : length; - } else { - if (!PyLong_Check(r->stop)) return -1; - *stop = PyLong_AsSsize_t(r->stop); - if (*stop < 0) *stop += length; - } - if (*stop > length) return -1; - if (*start >= length) return -1; - if (*step == 0) return -1; - return 0; + /* XXX support long ints */ + if (r->step == Py_None) { + *step = 1; + } else { + if (!PyLong_Check(r->step)) return -1; + *step = PyLong_AsSsize_t(r->step); + } + if (r->start == Py_None) { + *start = *step < 0 ? length-1 : 0; + } else { + if (!PyLong_Check(r->start)) return -1; + *start = PyLong_AsSsize_t(r->start); + if (*start < 0) *start += length; + } + if (r->stop == Py_None) { + *stop = *step < 0 ? -1 : length; + } else { + if (!PyLong_Check(r->stop)) return -1; + *stop = PyLong_AsSsize_t(r->stop); + if (*stop < 0) *stop += length; + } + if (*stop > length) return -1; + if (*start >= length) return -1; + if (*step == 0) return -1; + return 0; } int PySlice_GetIndicesEx(PySliceObject *r, Py_ssize_t length, - Py_ssize_t *start, Py_ssize_t *stop, Py_ssize_t *step, Py_ssize_t *slicelength) + Py_ssize_t *start, Py_ssize_t *stop, Py_ssize_t *step, Py_ssize_t *slicelength) { - /* this is harder to get right than you might think */ + /* this is harder to get right than you might think */ - Py_ssize_t defstart, defstop; + Py_ssize_t defstart, defstop; - if (r->step == Py_None) { - *step = 1; - } - else { - if (!_PyEval_SliceIndex(r->step, step)) return -1; - if (*step == 0) { - PyErr_SetString(PyExc_ValueError, - "slice step cannot be zero"); - return -1; - } - } - - defstart = *step < 0 ? length-1 : 0; - defstop = *step < 0 ? -1 : length; - - if (r->start == Py_None) { - *start = defstart; - } - else { - if (!_PyEval_SliceIndex(r->start, start)) return -1; - if (*start < 0) *start += length; - if (*start < 0) *start = (*step < 0) ? -1 : 0; - if (*start >= length) - *start = (*step < 0) ? length - 1 : length; - } - - if (r->stop == Py_None) { - *stop = defstop; - } - else { - if (!_PyEval_SliceIndex(r->stop, stop)) return -1; - if (*stop < 0) *stop += length; - if (*stop < 0) *stop = (*step < 0) ? -1 : 0; - if (*stop >= length) - *stop = (*step < 0) ? length - 1 : length; - } - - if ((*step < 0 && *stop >= *start) - || (*step > 0 && *start >= *stop)) { - *slicelength = 0; - } - else if (*step < 0) { - *slicelength = (*stop-*start+1)/(*step)+1; - } - else { - *slicelength = (*stop-*start-1)/(*step)+1; - } + if (r->step == Py_None) { + *step = 1; + } + else { + if (!_PyEval_SliceIndex(r->step, step)) return -1; + if (*step == 0) { + PyErr_SetString(PyExc_ValueError, + "slice step cannot be zero"); + return -1; + } + } + + defstart = *step < 0 ? length-1 : 0; + defstop = *step < 0 ? -1 : length; + + if (r->start == Py_None) { + *start = defstart; + } + else { + if (!_PyEval_SliceIndex(r->start, start)) return -1; + if (*start < 0) *start += length; + if (*start < 0) *start = (*step < 0) ? -1 : 0; + if (*start >= length) + *start = (*step < 0) ? length - 1 : length; + } + + if (r->stop == Py_None) { + *stop = defstop; + } + else { + if (!_PyEval_SliceIndex(r->stop, stop)) return -1; + if (*stop < 0) *stop += length; + if (*stop < 0) *stop = (*step < 0) ? -1 : 0; + if (*stop >= length) + *stop = (*step < 0) ? length - 1 : length; + } + + if ((*step < 0 && *stop >= *start) + || (*step > 0 && *start >= *stop)) { + *slicelength = 0; + } + else if (*step < 0) { + *slicelength = (*stop-*start+1)/(*step)+1; + } + else { + *slicelength = (*stop-*start-1)/(*step)+1; + } - return 0; + return 0; } static PyObject * slice_new(PyTypeObject *type, PyObject *args, PyObject *kw) { - PyObject *start, *stop, *step; + PyObject *start, *stop, *step; - start = stop = step = NULL; + start = stop = step = NULL; - if (!_PyArg_NoKeywords("slice()", kw)) - return NULL; + if (!_PyArg_NoKeywords("slice()", kw)) + return NULL; - if (!PyArg_UnpackTuple(args, "slice", 1, 3, &start, &stop, &step)) - return NULL; - - /* This swapping of stop and start is to maintain similarity with - range(). */ - if (stop == NULL) { - stop = start; - start = NULL; - } - return PySlice_New(start, stop, step); + if (!PyArg_UnpackTuple(args, "slice", 1, 3, &start, &stop, &step)) + return NULL; + + /* This swapping of stop and start is to maintain similarity with + range(). */ + if (stop == NULL) { + stop = start; + start = NULL; + } + return PySlice_New(start, stop, step); } PyDoc_STRVAR(slice_doc, @@ -218,42 +218,42 @@ static void slice_dealloc(PySliceObject *r) { - Py_DECREF(r->step); - Py_DECREF(r->start); - Py_DECREF(r->stop); - PyObject_Del(r); + Py_DECREF(r->step); + Py_DECREF(r->start); + Py_DECREF(r->stop); + PyObject_Del(r); } static PyObject * slice_repr(PySliceObject *r) { - return PyUnicode_FromFormat("slice(%R, %R, %R)", r->start, r->stop, r->step); + return PyUnicode_FromFormat("slice(%R, %R, %R)", r->start, r->stop, r->step); } static PyMemberDef slice_members[] = { - {"start", T_OBJECT, offsetof(PySliceObject, start), READONLY}, - {"stop", T_OBJECT, offsetof(PySliceObject, stop), READONLY}, - {"step", T_OBJECT, offsetof(PySliceObject, step), READONLY}, - {0} + {"start", T_OBJECT, offsetof(PySliceObject, start), READONLY}, + {"stop", T_OBJECT, offsetof(PySliceObject, stop), READONLY}, + {"step", T_OBJECT, offsetof(PySliceObject, step), READONLY}, + {0} }; static PyObject* slice_indices(PySliceObject* self, PyObject* len) { - Py_ssize_t ilen, start, stop, step, slicelength; + Py_ssize_t ilen, start, stop, step, slicelength; - ilen = PyNumber_AsSsize_t(len, PyExc_OverflowError); + ilen = PyNumber_AsSsize_t(len, PyExc_OverflowError); - if (ilen == -1 && PyErr_Occurred()) { - return NULL; - } + if (ilen == -1 && PyErr_Occurred()) { + return NULL; + } - if (PySlice_GetIndicesEx(self, ilen, &start, &stop, - &step, &slicelength) < 0) { - return NULL; - } + if (PySlice_GetIndicesEx(self, ilen, &start, &stop, + &step, &slicelength) < 0) { + return NULL; + } - return Py_BuildValue("(nnn)", start, stop, step); + return Py_BuildValue("(nnn)", start, stop, step); } PyDoc_STRVAR(slice_indices_doc, @@ -267,119 +267,119 @@ static PyObject * slice_reduce(PySliceObject* self) { - return Py_BuildValue("O(OOO)", Py_TYPE(self), self->start, self->stop, self->step); + return Py_BuildValue("O(OOO)", Py_TYPE(self), self->start, self->stop, self->step); } PyDoc_STRVAR(reduce_doc, "Return state information for pickling."); static PyMethodDef slice_methods[] = { - {"indices", (PyCFunction)slice_indices, - METH_O, slice_indices_doc}, - {"__reduce__", (PyCFunction)slice_reduce, - METH_NOARGS, reduce_doc}, - {NULL, NULL} + {"indices", (PyCFunction)slice_indices, + METH_O, slice_indices_doc}, + {"__reduce__", (PyCFunction)slice_reduce, + METH_NOARGS, reduce_doc}, + {NULL, NULL} }; static PyObject * slice_richcompare(PyObject *v, PyObject *w, int op) { - PyObject *t1; - PyObject *t2; - PyObject *res; - - if (!PySlice_Check(v) || !PySlice_Check(w)) { - Py_INCREF(Py_NotImplemented); - return Py_NotImplemented; - } - - if (v == w) { - /* XXX Do we really need this shortcut? - There's a unit test for it, but is that fair? */ - switch (op) { - case Py_EQ: - case Py_LE: - case Py_GE: - res = Py_True; - break; - default: - res = Py_False; - break; - } - Py_INCREF(res); - return res; - } - - t1 = PyTuple_New(3); - t2 = PyTuple_New(3); - if (t1 == NULL || t2 == NULL) - return NULL; - - PyTuple_SET_ITEM(t1, 0, ((PySliceObject *)v)->start); - PyTuple_SET_ITEM(t1, 1, ((PySliceObject *)v)->stop); - PyTuple_SET_ITEM(t1, 2, ((PySliceObject *)v)->step); - PyTuple_SET_ITEM(t2, 0, ((PySliceObject *)w)->start); - PyTuple_SET_ITEM(t2, 1, ((PySliceObject *)w)->stop); - PyTuple_SET_ITEM(t2, 2, ((PySliceObject *)w)->step); - - res = PyObject_RichCompare(t1, t2, op); - - PyTuple_SET_ITEM(t1, 0, NULL); - PyTuple_SET_ITEM(t1, 1, NULL); - PyTuple_SET_ITEM(t1, 2, NULL); - PyTuple_SET_ITEM(t2, 0, NULL); - PyTuple_SET_ITEM(t2, 1, NULL); - PyTuple_SET_ITEM(t2, 2, NULL); + PyObject *t1; + PyObject *t2; + PyObject *res; + + if (!PySlice_Check(v) || !PySlice_Check(w)) { + Py_INCREF(Py_NotImplemented); + return Py_NotImplemented; + } + + if (v == w) { + /* XXX Do we really need this shortcut? + There's a unit test for it, but is that fair? */ + switch (op) { + case Py_EQ: + case Py_LE: + case Py_GE: + res = Py_True; + break; + default: + res = Py_False; + break; + } + Py_INCREF(res); + return res; + } + + t1 = PyTuple_New(3); + t2 = PyTuple_New(3); + if (t1 == NULL || t2 == NULL) + return NULL; + + PyTuple_SET_ITEM(t1, 0, ((PySliceObject *)v)->start); + PyTuple_SET_ITEM(t1, 1, ((PySliceObject *)v)->stop); + PyTuple_SET_ITEM(t1, 2, ((PySliceObject *)v)->step); + PyTuple_SET_ITEM(t2, 0, ((PySliceObject *)w)->start); + PyTuple_SET_ITEM(t2, 1, ((PySliceObject *)w)->stop); + PyTuple_SET_ITEM(t2, 2, ((PySliceObject *)w)->step); + + res = PyObject_RichCompare(t1, t2, op); + + PyTuple_SET_ITEM(t1, 0, NULL); + PyTuple_SET_ITEM(t1, 1, NULL); + PyTuple_SET_ITEM(t1, 2, NULL); + PyTuple_SET_ITEM(t2, 0, NULL); + PyTuple_SET_ITEM(t2, 1, NULL); + PyTuple_SET_ITEM(t2, 2, NULL); - Py_DECREF(t1); - Py_DECREF(t2); + Py_DECREF(t1); + Py_DECREF(t2); - return res; + return res; } static long slice_hash(PySliceObject *v) { - PyErr_SetString(PyExc_TypeError, "unhashable type"); - return -1L; + PyErr_SetString(PyExc_TypeError, "unhashable type"); + return -1L; } PyTypeObject PySlice_Type = { - PyVarObject_HEAD_INIT(&PyType_Type, 0) - "slice", /* Name of this type */ - sizeof(PySliceObject), /* Basic object size */ - 0, /* Item size for varobject */ - (destructor)slice_dealloc, /* tp_dealloc */ - 0, /* tp_print */ - 0, /* tp_getattr */ - 0, /* tp_setattr */ - 0, /* tp_reserved */ - (reprfunc)slice_repr, /* tp_repr */ - 0, /* tp_as_number */ - 0, /* tp_as_sequence */ - 0, /* tp_as_mapping */ - (hashfunc)slice_hash, /* tp_hash */ - 0, /* tp_call */ - 0, /* tp_str */ - PyObject_GenericGetAttr, /* tp_getattro */ - 0, /* tp_setattro */ - 0, /* tp_as_buffer */ - Py_TPFLAGS_DEFAULT, /* tp_flags */ - slice_doc, /* tp_doc */ - 0, /* tp_traverse */ - 0, /* tp_clear */ - slice_richcompare, /* tp_richcompare */ - 0, /* tp_weaklistoffset */ - 0, /* tp_iter */ - 0, /* tp_iternext */ - slice_methods, /* tp_methods */ - slice_members, /* tp_members */ - 0, /* tp_getset */ - 0, /* tp_base */ - 0, /* tp_dict */ - 0, /* tp_descr_get */ - 0, /* tp_descr_set */ - 0, /* tp_dictoffset */ - 0, /* tp_init */ - 0, /* tp_alloc */ - slice_new, /* tp_new */ + PyVarObject_HEAD_INIT(&PyType_Type, 0) + "slice", /* Name of this type */ + sizeof(PySliceObject), /* Basic object size */ + 0, /* Item size for varobject */ + (destructor)slice_dealloc, /* tp_dealloc */ + 0, /* tp_print */ + 0, /* tp_getattr */ + 0, /* tp_setattr */ + 0, /* tp_reserved */ + (reprfunc)slice_repr, /* tp_repr */ + 0, /* tp_as_number */ + 0, /* tp_as_sequence */ + 0, /* tp_as_mapping */ + (hashfunc)slice_hash, /* tp_hash */ + 0, /* tp_call */ + 0, /* tp_str */ + PyObject_GenericGetAttr, /* tp_getattro */ + 0, /* tp_setattro */ + 0, /* tp_as_buffer */ + Py_TPFLAGS_DEFAULT, /* tp_flags */ + slice_doc, /* tp_doc */ + 0, /* tp_traverse */ + 0, /* tp_clear */ + slice_richcompare, /* tp_richcompare */ + 0, /* tp_weaklistoffset */ + 0, /* tp_iter */ + 0, /* tp_iternext */ + slice_methods, /* tp_methods */ + slice_members, /* tp_members */ + 0, /* tp_getset */ + 0, /* tp_base */ + 0, /* tp_dict */ + 0, /* tp_descr_get */ + 0, /* tp_descr_set */ + 0, /* tp_dictoffset */ + 0, /* tp_init */ + 0, /* tp_alloc */ + slice_new, /* tp_new */ }; Modified: python/branches/py3k/Objects/stringlib/eq.h ============================================================================== --- python/branches/py3k/Objects/stringlib/eq.h (original) +++ python/branches/py3k/Objects/stringlib/eq.h Sun May 9 17:52:27 2010 @@ -6,16 +6,16 @@ Py_LOCAL_INLINE(int) unicode_eq(PyObject *aa, PyObject *bb) { - register PyUnicodeObject *a = (PyUnicodeObject *)aa; - register PyUnicodeObject *b = (PyUnicodeObject *)bb; + register PyUnicodeObject *a = (PyUnicodeObject *)aa; + register PyUnicodeObject *b = (PyUnicodeObject *)bb; - if (a->length != b->length) - return 0; - if (a->length == 0) - return 1; - if (a->str[0] != b->str[0]) - return 0; - if (a->length == 1) - return 1; - return memcmp(a->str, b->str, a->length * sizeof(Py_UNICODE)) == 0; + if (a->length != b->length) + return 0; + if (a->length == 0) + return 1; + if (a->str[0] != b->str[0]) + return 0; + if (a->length == 1) + return 1; + return memcmp(a->str, b->str, a->length * sizeof(Py_UNICODE)) == 0; } Modified: python/branches/py3k/Objects/stringlib/string_format.h ============================================================================== --- python/branches/py3k/Objects/stringlib/string_format.h (original) +++ python/branches/py3k/Objects/stringlib/string_format.h Sun May 9 17:52:27 2010 @@ -563,36 +563,36 @@ PyObject *format_spec_object = NULL; PyObject *(*formatter)(PyObject *, STRINGLIB_CHAR *, Py_ssize_t) = NULL; STRINGLIB_CHAR* format_spec_start = format_spec->ptr ? - format_spec->ptr : NULL; + format_spec->ptr : NULL; Py_ssize_t format_spec_len = format_spec->ptr ? - format_spec->end - format_spec->ptr : 0; + format_spec->end - format_spec->ptr : 0; /* If we know the type exactly, skip the lookup of __format__ and just call the formatter directly. */ if (PyUnicode_CheckExact(fieldobj)) - formatter = _PyUnicode_FormatAdvanced; + formatter = _PyUnicode_FormatAdvanced; else if (PyLong_CheckExact(fieldobj)) - formatter =_PyLong_FormatAdvanced; + formatter =_PyLong_FormatAdvanced; else if (PyFloat_CheckExact(fieldobj)) - formatter = _PyFloat_FormatAdvanced; + formatter = _PyFloat_FormatAdvanced; /* XXX: for 2.6, convert format_spec to the appropriate type (unicode, str) */ if (formatter) { - /* we know exactly which formatter will be called when __format__ is - looked up, so call it directly, instead. */ - result = formatter(fieldobj, format_spec_start, format_spec_len); + /* we know exactly which formatter will be called when __format__ is + looked up, so call it directly, instead. */ + result = formatter(fieldobj, format_spec_start, format_spec_len); } else { - /* We need to create an object out of the pointers we have, because - __format__ takes a string/unicode object for format_spec. */ - format_spec_object = STRINGLIB_NEW(format_spec_start, - format_spec_len); - if (format_spec_object == NULL) - goto done; + /* We need to create an object out of the pointers we have, because + __format__ takes a string/unicode object for format_spec. */ + format_spec_object = STRINGLIB_NEW(format_spec_start, + format_spec_len); + if (format_spec_object == NULL) + goto done; - result = PyObject_Format(fieldobj, format_spec_object); + result = PyObject_Format(fieldobj, format_spec_object); } if (result == NULL) goto done; @@ -605,11 +605,11 @@ /* Convert result to our type. We could be str, and result could be unicode */ { - PyObject *tmp = STRINGLIB_TOSTR(result); - if (tmp == NULL) - goto done; - Py_DECREF(result); - result = tmp; + PyObject *tmp = STRINGLIB_TOSTR(result); + if (tmp == NULL) + goto done; + Py_DECREF(result); + result = tmp; } #endif @@ -844,17 +844,17 @@ return STRINGLIB_TOASCII(obj); #endif default: - if (conversion > 32 && conversion < 127) { - /* It's the ASCII subrange; casting to char is safe - (assuming the execution character set is an ASCII - superset). */ - PyErr_Format(PyExc_ValueError, + if (conversion > 32 && conversion < 127) { + /* It's the ASCII subrange; casting to char is safe + (assuming the execution character set is an ASCII + superset). */ + PyErr_Format(PyExc_ValueError, "Unknown conversion specifier %c", (char)conversion); - } else - PyErr_Format(PyExc_ValueError, - "Unknown conversion specifier \\x%x", - (unsigned int)conversion); + } else + PyErr_Format(PyExc_ValueError, + "Unknown conversion specifier \\x%x", + (unsigned int)conversion); return NULL; } } @@ -1119,7 +1119,7 @@ Py_INCREF(conversion_str); } else - conversion_str = STRINGLIB_NEW(&conversion, 1); + conversion_str = STRINGLIB_NEW(&conversion, 1); if (conversion_str == NULL) goto done; @@ -1135,39 +1135,39 @@ } static PyMethodDef formatteriter_methods[] = { - {NULL, NULL} /* sentinel */ + {NULL, NULL} /* sentinel */ }; static PyTypeObject PyFormatterIter_Type = { PyVarObject_HEAD_INIT(&PyType_Type, 0) - "formatteriterator", /* tp_name */ - sizeof(formatteriterobject), /* tp_basicsize */ - 0, /* tp_itemsize */ + "formatteriterator", /* tp_name */ + sizeof(formatteriterobject), /* tp_basicsize */ + 0, /* tp_itemsize */ /* methods */ - (destructor)formatteriter_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, /* tp_flags */ - 0, /* tp_doc */ - 0, /* tp_traverse */ - 0, /* tp_clear */ - 0, /* tp_richcompare */ - 0, /* tp_weaklistoffset */ - PyObject_SelfIter, /* tp_iter */ - (iternextfunc)formatteriter_next, /* tp_iternext */ - formatteriter_methods, /* tp_methods */ + (destructor)formatteriter_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, /* tp_flags */ + 0, /* tp_doc */ + 0, /* tp_traverse */ + 0, /* tp_clear */ + 0, /* tp_richcompare */ + 0, /* tp_weaklistoffset */ + PyObject_SelfIter, /* tp_iter */ + (iternextfunc)formatteriter_next, /* tp_iternext */ + formatteriter_methods, /* tp_methods */ 0, }; @@ -1268,39 +1268,39 @@ } static PyMethodDef fieldnameiter_methods[] = { - {NULL, NULL} /* sentinel */ + {NULL, NULL} /* sentinel */ }; static PyTypeObject PyFieldNameIter_Type = { PyVarObject_HEAD_INIT(&PyType_Type, 0) - "fieldnameiterator", /* tp_name */ - sizeof(fieldnameiterobject), /* tp_basicsize */ - 0, /* tp_itemsize */ + "fieldnameiterator", /* tp_name */ + sizeof(fieldnameiterobject), /* tp_basicsize */ + 0, /* tp_itemsize */ /* methods */ - (destructor)fieldnameiter_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, /* tp_flags */ - 0, /* tp_doc */ - 0, /* tp_traverse */ - 0, /* tp_clear */ - 0, /* tp_richcompare */ - 0, /* tp_weaklistoffset */ - PyObject_SelfIter, /* tp_iter */ - (iternextfunc)fieldnameiter_next, /* tp_iternext */ - fieldnameiter_methods, /* tp_methods */ + (destructor)fieldnameiter_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, /* tp_flags */ + 0, /* tp_doc */ + 0, /* tp_traverse */ + 0, /* tp_clear */ + 0, /* tp_richcompare */ + 0, /* tp_weaklistoffset */ + PyObject_SelfIter, /* tp_iter */ + (iternextfunc)fieldnameiter_next, /* tp_iternext */ + fieldnameiter_methods, /* tp_methods */ 0}; /* unicode_formatter_field_name_split is used to implement Modified: python/branches/py3k/Objects/structseq.c ============================================================================== --- python/branches/py3k/Objects/structseq.c (original) +++ python/branches/py3k/Objects/structseq.c Sun May 9 17:52:27 2010 @@ -9,7 +9,7 @@ static char real_length_key[] = "n_fields"; static char unnamed_fields_key[] = "n_unnamed_fields"; -/* Fields with this name have only a field index, not a field name. +/* Fields with this name have only a field index, not a field name. They are only allowed for indices < n_visible_fields. */ char *PyStructSequence_UnnamedField = "unnamed field"; @@ -29,511 +29,511 @@ PyObject * PyStructSequence_New(PyTypeObject *type) { - PyStructSequence *obj; + PyStructSequence *obj; - obj = PyObject_New(PyStructSequence, type); - if (obj == NULL) - return NULL; - Py_SIZE(obj) = VISIBLE_SIZE_TP(type); + obj = PyObject_New(PyStructSequence, type); + if (obj == NULL) + return NULL; + Py_SIZE(obj) = VISIBLE_SIZE_TP(type); - return (PyObject*) obj; + return (PyObject*) obj; } static void structseq_dealloc(PyStructSequence *obj) { - Py_ssize_t i, size; + Py_ssize_t i, size; - size = REAL_SIZE(obj); - for (i = 0; i < size; ++i) { - Py_XDECREF(obj->ob_item[i]); - } - PyObject_Del(obj); + size = REAL_SIZE(obj); + for (i = 0; i < size; ++i) { + Py_XDECREF(obj->ob_item[i]); + } + PyObject_Del(obj); } static Py_ssize_t structseq_length(PyStructSequence *obj) { - return VISIBLE_SIZE(obj); + return VISIBLE_SIZE(obj); } static PyObject* structseq_item(PyStructSequence *obj, Py_ssize_t i) { - if (i < 0 || i >= VISIBLE_SIZE(obj)) { - PyErr_SetString(PyExc_IndexError, "tuple index out of range"); - return NULL; - } - Py_INCREF(obj->ob_item[i]); - return obj->ob_item[i]; + if (i < 0 || i >= VISIBLE_SIZE(obj)) { + PyErr_SetString(PyExc_IndexError, "tuple index out of range"); + return NULL; + } + Py_INCREF(obj->ob_item[i]); + return obj->ob_item[i]; } static PyObject* structseq_slice(PyStructSequence *obj, Py_ssize_t low, Py_ssize_t high) { - PyTupleObject *np; - Py_ssize_t i; + PyTupleObject *np; + Py_ssize_t i; - if (low < 0) - low = 0; - if (high > VISIBLE_SIZE(obj)) - high = VISIBLE_SIZE(obj); - if (high < low) - high = low; - np = (PyTupleObject *)PyTuple_New(high-low); - if (np == NULL) - return NULL; - for(i = low; i < high; ++i) { - PyObject *v = obj->ob_item[i]; - Py_INCREF(v); - PyTuple_SET_ITEM(np, i-low, v); - } - return (PyObject *) np; + if (low < 0) + low = 0; + if (high > VISIBLE_SIZE(obj)) + high = VISIBLE_SIZE(obj); + if (high < low) + high = low; + np = (PyTupleObject *)PyTuple_New(high-low); + if (np == NULL) + return NULL; + for(i = low; i < high; ++i) { + PyObject *v = obj->ob_item[i]; + Py_INCREF(v); + PyTuple_SET_ITEM(np, i-low, v); + } + return (PyObject *) np; } static PyObject * structseq_subscript(PyStructSequence *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 += VISIBLE_SIZE(self); - - if (i < 0 || i >= VISIBLE_SIZE(self)) { - PyErr_SetString(PyExc_IndexError, - "tuple index out of range"); - return NULL; - } - Py_INCREF(self->ob_item[i]); - return self->ob_item[i]; - } - else if (PySlice_Check(item)) { - Py_ssize_t start, stop, step, slicelen, cur, i; - PyObject *result; - - if (PySlice_GetIndicesEx((PySliceObject *)item, - VISIBLE_SIZE(self), &start, &stop, - &step, &slicelen) < 0) { - return NULL; - } - if (slicelen <= 0) - return PyTuple_New(0); - result = PyTuple_New(slicelen); - if (result == NULL) - return NULL; - for (cur = start, i = 0; i < slicelen; - cur += step, i++) { - PyObject *v = self->ob_item[cur]; - Py_INCREF(v); - PyTuple_SET_ITEM(result, i, v); - } - return result; - } - else { - PyErr_SetString(PyExc_TypeError, - "structseq index must be integer"); - return NULL; - } + 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 += VISIBLE_SIZE(self); + + if (i < 0 || i >= VISIBLE_SIZE(self)) { + PyErr_SetString(PyExc_IndexError, + "tuple index out of range"); + return NULL; + } + Py_INCREF(self->ob_item[i]); + return self->ob_item[i]; + } + else if (PySlice_Check(item)) { + Py_ssize_t start, stop, step, slicelen, cur, i; + PyObject *result; + + if (PySlice_GetIndicesEx((PySliceObject *)item, + VISIBLE_SIZE(self), &start, &stop, + &step, &slicelen) < 0) { + return NULL; + } + if (slicelen <= 0) + return PyTuple_New(0); + result = PyTuple_New(slicelen); + if (result == NULL) + return NULL; + for (cur = start, i = 0; i < slicelen; + cur += step, i++) { + PyObject *v = self->ob_item[cur]; + Py_INCREF(v); + PyTuple_SET_ITEM(result, i, v); + } + return result; + } + else { + PyErr_SetString(PyExc_TypeError, + "structseq index must be integer"); + return NULL; + } } static PyObject * structseq_new(PyTypeObject *type, PyObject *args, PyObject *kwds) { - PyObject *arg = NULL; - PyObject *dict = NULL; - PyObject *ob; - PyStructSequence *res = NULL; - Py_ssize_t len, min_len, max_len, i, n_unnamed_fields; - static char *kwlist[] = {"sequence", "dict", 0}; - - if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|O:structseq", - kwlist, &arg, &dict)) - return NULL; - - arg = PySequence_Fast(arg, "constructor requires a sequence"); - - if (!arg) { - return NULL; - } - - if (dict && !PyDict_Check(dict)) { - PyErr_Format(PyExc_TypeError, - "%.500s() takes a dict as second arg, if any", - type->tp_name); - Py_DECREF(arg); - return NULL; - } - - len = PySequence_Fast_GET_SIZE(arg); - min_len = VISIBLE_SIZE_TP(type); - max_len = REAL_SIZE_TP(type); - n_unnamed_fields = UNNAMED_FIELDS_TP(type); - - if (min_len != max_len) { - if (len < min_len) { - PyErr_Format(PyExc_TypeError, - "%.500s() takes an at least %zd-sequence (%zd-sequence given)", - type->tp_name, min_len, len); - Py_DECREF(arg); - return NULL; - } - - if (len > max_len) { - PyErr_Format(PyExc_TypeError, - "%.500s() takes an at most %zd-sequence (%zd-sequence given)", - type->tp_name, max_len, len); - Py_DECREF(arg); - return NULL; - } - } - else { - if (len != min_len) { - PyErr_Format(PyExc_TypeError, - "%.500s() takes a %zd-sequence (%zd-sequence given)", - type->tp_name, min_len, len); - Py_DECREF(arg); - return NULL; - } - } - - res = (PyStructSequence*) PyStructSequence_New(type); - if (res == NULL) { - return NULL; - } - for (i = 0; i < len; ++i) { - PyObject *v = PySequence_Fast_GET_ITEM(arg, i); - Py_INCREF(v); - res->ob_item[i] = v; - } - for (; i < max_len; ++i) { - if (dict && (ob = PyDict_GetItemString( - dict, type->tp_members[i-n_unnamed_fields].name))) { - } - else { - ob = Py_None; - } - Py_INCREF(ob); - res->ob_item[i] = ob; - } - - Py_DECREF(arg); - return (PyObject*) res; + PyObject *arg = NULL; + PyObject *dict = NULL; + PyObject *ob; + PyStructSequence *res = NULL; + Py_ssize_t len, min_len, max_len, i, n_unnamed_fields; + static char *kwlist[] = {"sequence", "dict", 0}; + + if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|O:structseq", + kwlist, &arg, &dict)) + return NULL; + + arg = PySequence_Fast(arg, "constructor requires a sequence"); + + if (!arg) { + return NULL; + } + + if (dict && !PyDict_Check(dict)) { + PyErr_Format(PyExc_TypeError, + "%.500s() takes a dict as second arg, if any", + type->tp_name); + Py_DECREF(arg); + return NULL; + } + + len = PySequence_Fast_GET_SIZE(arg); + min_len = VISIBLE_SIZE_TP(type); + max_len = REAL_SIZE_TP(type); + n_unnamed_fields = UNNAMED_FIELDS_TP(type); + + if (min_len != max_len) { + if (len < min_len) { + PyErr_Format(PyExc_TypeError, + "%.500s() takes an at least %zd-sequence (%zd-sequence given)", + type->tp_name, min_len, len); + Py_DECREF(arg); + return NULL; + } + + if (len > max_len) { + PyErr_Format(PyExc_TypeError, + "%.500s() takes an at most %zd-sequence (%zd-sequence given)", + type->tp_name, max_len, len); + Py_DECREF(arg); + return NULL; + } + } + else { + if (len != min_len) { + PyErr_Format(PyExc_TypeError, + "%.500s() takes a %zd-sequence (%zd-sequence given)", + type->tp_name, min_len, len); + Py_DECREF(arg); + return NULL; + } + } + + res = (PyStructSequence*) PyStructSequence_New(type); + if (res == NULL) { + return NULL; + } + for (i = 0; i < len; ++i) { + PyObject *v = PySequence_Fast_GET_ITEM(arg, i); + Py_INCREF(v); + res->ob_item[i] = v; + } + for (; i < max_len; ++i) { + if (dict && (ob = PyDict_GetItemString( + dict, type->tp_members[i-n_unnamed_fields].name))) { + } + else { + ob = Py_None; + } + Py_INCREF(ob); + res->ob_item[i] = ob; + } + + Py_DECREF(arg); + return (PyObject*) res; } static PyObject * make_tuple(PyStructSequence *obj) { - return structseq_slice(obj, 0, VISIBLE_SIZE(obj)); + return structseq_slice(obj, 0, VISIBLE_SIZE(obj)); } static PyObject * structseq_repr(PyStructSequence *obj) { - /* buffer and type size were chosen well considered. */ + /* buffer and type size were chosen well considered. */ #define REPR_BUFFER_SIZE 512 #define TYPE_MAXSIZE 100 - PyObject *tup; - PyTypeObject *typ = Py_TYPE(obj); - int i, removelast = 0; - Py_ssize_t len; - char buf[REPR_BUFFER_SIZE]; - char *endofbuf, *pbuf = buf; - - /* pointer to end of writeable buffer; safes space for "...)\0" */ - endofbuf= &buf[REPR_BUFFER_SIZE-5]; - - if ((tup = make_tuple(obj)) == NULL) { - return NULL; - } - - /* "typename(", limited to TYPE_MAXSIZE */ - len = strlen(typ->tp_name) > TYPE_MAXSIZE ? TYPE_MAXSIZE : - strlen(typ->tp_name); - strncpy(pbuf, typ->tp_name, len); - pbuf += len; - *pbuf++ = '('; - - for (i=0; i < VISIBLE_SIZE(obj); i++) { - PyObject *val, *repr; - char *cname, *crepr; - - cname = typ->tp_members[i].name; - - val = PyTuple_GetItem(tup, i); - if (cname == NULL || val == NULL) { - return NULL; - } - repr = PyObject_Repr(val); - if (repr == NULL) { - Py_DECREF(tup); - return NULL; - } - crepr = _PyUnicode_AsString(repr); - if (crepr == NULL) { - Py_DECREF(tup); - Py_DECREF(repr); - return NULL; - } - - /* + 3: keep space for "=" and ", " */ - len = strlen(cname) + strlen(crepr) + 3; - if ((pbuf+len) <= endofbuf) { - strcpy(pbuf, cname); - pbuf += strlen(cname); - *pbuf++ = '='; - strcpy(pbuf, crepr); - pbuf += strlen(crepr); - *pbuf++ = ','; - *pbuf++ = ' '; - removelast = 1; - Py_DECREF(repr); - } - else { - strcpy(pbuf, "..."); - pbuf += 3; - removelast = 0; - Py_DECREF(repr); - break; - } - } - Py_DECREF(tup); - if (removelast) { - /* overwrite last ", " */ - pbuf-=2; - } - *pbuf++ = ')'; - *pbuf = '\0'; + PyObject *tup; + PyTypeObject *typ = Py_TYPE(obj); + int i, removelast = 0; + Py_ssize_t len; + char buf[REPR_BUFFER_SIZE]; + char *endofbuf, *pbuf = buf; + + /* pointer to end of writeable buffer; safes space for "...)\0" */ + endofbuf= &buf[REPR_BUFFER_SIZE-5]; + + if ((tup = make_tuple(obj)) == NULL) { + return NULL; + } + + /* "typename(", limited to TYPE_MAXSIZE */ + len = strlen(typ->tp_name) > TYPE_MAXSIZE ? TYPE_MAXSIZE : + strlen(typ->tp_name); + strncpy(pbuf, typ->tp_name, len); + pbuf += len; + *pbuf++ = '('; + + for (i=0; i < VISIBLE_SIZE(obj); i++) { + PyObject *val, *repr; + char *cname, *crepr; + + cname = typ->tp_members[i].name; + + val = PyTuple_GetItem(tup, i); + if (cname == NULL || val == NULL) { + return NULL; + } + repr = PyObject_Repr(val); + if (repr == NULL) { + Py_DECREF(tup); + return NULL; + } + crepr = _PyUnicode_AsString(repr); + if (crepr == NULL) { + Py_DECREF(tup); + Py_DECREF(repr); + return NULL; + } + + /* + 3: keep space for "=" and ", " */ + len = strlen(cname) + strlen(crepr) + 3; + if ((pbuf+len) <= endofbuf) { + strcpy(pbuf, cname); + pbuf += strlen(cname); + *pbuf++ = '='; + strcpy(pbuf, crepr); + pbuf += strlen(crepr); + *pbuf++ = ','; + *pbuf++ = ' '; + removelast = 1; + Py_DECREF(repr); + } + else { + strcpy(pbuf, "..."); + pbuf += 3; + removelast = 0; + Py_DECREF(repr); + break; + } + } + Py_DECREF(tup); + if (removelast) { + /* overwrite last ", " */ + pbuf-=2; + } + *pbuf++ = ')'; + *pbuf = '\0'; - return PyUnicode_FromString(buf); + return PyUnicode_FromString(buf); } static PyObject * structseq_concat(PyStructSequence *obj, PyObject *b) { - PyObject *tup, *result; - tup = make_tuple(obj); - result = PySequence_Concat(tup, b); - Py_DECREF(tup); - return result; + PyObject *tup, *result; + tup = make_tuple(obj); + result = PySequence_Concat(tup, b); + Py_DECREF(tup); + return result; } static PyObject * structseq_repeat(PyStructSequence *obj, Py_ssize_t n) { - PyObject *tup, *result; - tup = make_tuple(obj); - result = PySequence_Repeat(tup, n); - Py_DECREF(tup); - return result; + PyObject *tup, *result; + tup = make_tuple(obj); + result = PySequence_Repeat(tup, n); + Py_DECREF(tup); + return result; } static int structseq_contains(PyStructSequence *obj, PyObject *o) { - PyObject *tup; - int result; - tup = make_tuple(obj); - if (!tup) - return -1; - result = PySequence_Contains(tup, o); - Py_DECREF(tup); - return result; + PyObject *tup; + int result; + tup = make_tuple(obj); + if (!tup) + return -1; + result = PySequence_Contains(tup, o); + Py_DECREF(tup); + return result; } static long structseq_hash(PyObject *obj) { - PyObject *tup; - long result; - tup = make_tuple((PyStructSequence*) obj); - if (!tup) - return -1; - result = PyObject_Hash(tup); - Py_DECREF(tup); - return result; + PyObject *tup; + long result; + tup = make_tuple((PyStructSequence*) obj); + if (!tup) + return -1; + result = PyObject_Hash(tup); + Py_DECREF(tup); + return result; } static PyObject * structseq_richcompare(PyObject *obj, PyObject *o2, int op) { - PyObject *tup, *result; - tup = make_tuple((PyStructSequence*) obj); - result = PyObject_RichCompare(tup, o2, op); - Py_DECREF(tup); - return result; + PyObject *tup, *result; + tup = make_tuple((PyStructSequence*) obj); + result = PyObject_RichCompare(tup, o2, op); + Py_DECREF(tup); + return result; } static PyObject * structseq_reduce(PyStructSequence* self) { - PyObject* tup; - PyObject* dict; - PyObject* result; - Py_ssize_t n_fields, n_visible_fields, n_unnamed_fields; - int i; - - n_fields = REAL_SIZE(self); - n_visible_fields = VISIBLE_SIZE(self); - n_unnamed_fields = UNNAMED_FIELDS(self); - tup = PyTuple_New(n_visible_fields); - if (!tup) { - return NULL; - } - - dict = PyDict_New(); - if (!dict) { - Py_DECREF(tup); - return NULL; - } - - for (i = 0; i < n_visible_fields; i++) { - Py_INCREF(self->ob_item[i]); - PyTuple_SET_ITEM(tup, i, self->ob_item[i]); - } - - for (; i < n_fields; i++) { - char *n = Py_TYPE(self)->tp_members[i-n_unnamed_fields].name; - PyDict_SetItemString(dict, n, - self->ob_item[i]); - } + PyObject* tup; + PyObject* dict; + PyObject* result; + Py_ssize_t n_fields, n_visible_fields, n_unnamed_fields; + int i; + + n_fields = REAL_SIZE(self); + n_visible_fields = VISIBLE_SIZE(self); + n_unnamed_fields = UNNAMED_FIELDS(self); + tup = PyTuple_New(n_visible_fields); + if (!tup) { + return NULL; + } + + dict = PyDict_New(); + if (!dict) { + Py_DECREF(tup); + return NULL; + } + + for (i = 0; i < n_visible_fields; i++) { + Py_INCREF(self->ob_item[i]); + PyTuple_SET_ITEM(tup, i, self->ob_item[i]); + } + + for (; i < n_fields; i++) { + char *n = Py_TYPE(self)->tp_members[i-n_unnamed_fields].name; + PyDict_SetItemString(dict, n, + self->ob_item[i]); + } - result = Py_BuildValue("(O(OO))", Py_TYPE(self), tup, dict); + result = Py_BuildValue("(O(OO))", Py_TYPE(self), tup, dict); - Py_DECREF(tup); - Py_DECREF(dict); + Py_DECREF(tup); + Py_DECREF(dict); - return result; + return result; } static PySequenceMethods structseq_as_sequence = { - (lenfunc)structseq_length, - (binaryfunc)structseq_concat, /* sq_concat */ - (ssizeargfunc)structseq_repeat, /* sq_repeat */ - (ssizeargfunc)structseq_item, /* sq_item */ - 0, /* sq_slice */ - 0, /* sq_ass_item */ - 0, /* sq_ass_slice */ - (objobjproc)structseq_contains, /* sq_contains */ + (lenfunc)structseq_length, + (binaryfunc)structseq_concat, /* sq_concat */ + (ssizeargfunc)structseq_repeat, /* sq_repeat */ + (ssizeargfunc)structseq_item, /* sq_item */ + 0, /* sq_slice */ + 0, /* sq_ass_item */ + 0, /* sq_ass_slice */ + (objobjproc)structseq_contains, /* sq_contains */ }; static PyMappingMethods structseq_as_mapping = { - (lenfunc)structseq_length, - (binaryfunc)structseq_subscript, + (lenfunc)structseq_length, + (binaryfunc)structseq_subscript, }; static PyMethodDef structseq_methods[] = { - {"__reduce__", (PyCFunction)structseq_reduce, - METH_NOARGS, NULL}, - {NULL, NULL} + {"__reduce__", (PyCFunction)structseq_reduce, + METH_NOARGS, NULL}, + {NULL, NULL} }; static PyTypeObject _struct_sequence_template = { - PyVarObject_HEAD_INIT(&PyType_Type, 0) - NULL, /* tp_name */ - 0, /* tp_basicsize */ - 0, /* tp_itemsize */ - (destructor)structseq_dealloc, /* tp_dealloc */ - 0, /* tp_print */ - 0, /* tp_getattr */ - 0, /* tp_setattr */ - 0, /* tp_reserved */ - (reprfunc)structseq_repr, /* tp_repr */ - 0, /* tp_as_number */ - &structseq_as_sequence, /* tp_as_sequence */ - &structseq_as_mapping, /* tp_as_mapping */ - structseq_hash, /* tp_hash */ - 0, /* tp_call */ - 0, /* tp_str */ - 0, /* tp_getattro */ - 0, /* tp_setattro */ - 0, /* tp_as_buffer */ - Py_TPFLAGS_DEFAULT, /* tp_flags */ - NULL, /* tp_doc */ - 0, /* tp_traverse */ - 0, /* tp_clear */ - structseq_richcompare, /* tp_richcompare */ - 0, /* tp_weaklistoffset */ - 0, /* tp_iter */ - 0, /* tp_iternext */ - structseq_methods, /* tp_methods */ - NULL, /* tp_members */ - 0, /* tp_getset */ - 0, /* tp_base */ - 0, /* tp_dict */ - 0, /* tp_descr_get */ - 0, /* tp_descr_set */ - 0, /* tp_dictoffset */ - 0, /* tp_init */ - 0, /* tp_alloc */ - structseq_new, /* tp_new */ + PyVarObject_HEAD_INIT(&PyType_Type, 0) + NULL, /* tp_name */ + 0, /* tp_basicsize */ + 0, /* tp_itemsize */ + (destructor)structseq_dealloc, /* tp_dealloc */ + 0, /* tp_print */ + 0, /* tp_getattr */ + 0, /* tp_setattr */ + 0, /* tp_reserved */ + (reprfunc)structseq_repr, /* tp_repr */ + 0, /* tp_as_number */ + &structseq_as_sequence, /* tp_as_sequence */ + &structseq_as_mapping, /* tp_as_mapping */ + structseq_hash, /* tp_hash */ + 0, /* tp_call */ + 0, /* tp_str */ + 0, /* tp_getattro */ + 0, /* tp_setattro */ + 0, /* tp_as_buffer */ + Py_TPFLAGS_DEFAULT, /* tp_flags */ + NULL, /* tp_doc */ + 0, /* tp_traverse */ + 0, /* tp_clear */ + structseq_richcompare, /* tp_richcompare */ + 0, /* tp_weaklistoffset */ + 0, /* tp_iter */ + 0, /* tp_iternext */ + structseq_methods, /* tp_methods */ + NULL, /* tp_members */ + 0, /* tp_getset */ + 0, /* tp_base */ + 0, /* tp_dict */ + 0, /* tp_descr_get */ + 0, /* tp_descr_set */ + 0, /* tp_dictoffset */ + 0, /* tp_init */ + 0, /* tp_alloc */ + structseq_new, /* tp_new */ }; void PyStructSequence_InitType(PyTypeObject *type, PyStructSequence_Desc *desc) { - PyObject *dict; - PyMemberDef* members; - int n_members, n_unnamed_members, i, k; + PyObject *dict; + PyMemberDef* members; + int n_members, n_unnamed_members, i, k; #ifdef Py_TRACE_REFS - /* if the type object was chained, unchain it first - before overwriting its storage */ - if (type->ob_base.ob_base._ob_next) { - _Py_ForgetReference((PyObject*)type); - } + /* if the type object was chained, unchain it first + before overwriting its storage */ + if (type->ob_base.ob_base._ob_next) { + _Py_ForgetReference((PyObject*)type); + } #endif - n_unnamed_members = 0; - for (i = 0; desc->fields[i].name != NULL; ++i) - if (desc->fields[i].name == PyStructSequence_UnnamedField) - n_unnamed_members++; - n_members = i; - - memcpy(type, &_struct_sequence_template, sizeof(PyTypeObject)); - type->tp_name = desc->name; - type->tp_doc = desc->doc; - type->tp_basicsize = sizeof(PyStructSequence)+ - sizeof(PyObject*)*(n_members-1); - type->tp_itemsize = 0; - - members = PyMem_NEW(PyMemberDef, n_members-n_unnamed_members+1); - if (members == NULL) - return; - - for (i = k = 0; i < n_members; ++i) { - if (desc->fields[i].name == PyStructSequence_UnnamedField) - continue; - members[k].name = desc->fields[i].name; - members[k].type = T_OBJECT; - members[k].offset = offsetof(PyStructSequence, ob_item) - + i * sizeof(PyObject*); - members[k].flags = READONLY; - members[k].doc = desc->fields[i].doc; - k++; - } - members[k].name = NULL; - - type->tp_members = members; - - if (PyType_Ready(type) < 0) - return; - Py_INCREF(type); - - dict = type->tp_dict; -#define SET_DICT_FROM_INT(key, value) \ - do { \ - PyObject *v = PyLong_FromLong((long) value); \ - if (v != NULL) { \ - PyDict_SetItemString(dict, key, v); \ - Py_DECREF(v); \ - } \ - } while (0) - - SET_DICT_FROM_INT(visible_length_key, desc->n_in_sequence); - SET_DICT_FROM_INT(real_length_key, n_members); - SET_DICT_FROM_INT(unnamed_fields_key, n_unnamed_members); + n_unnamed_members = 0; + for (i = 0; desc->fields[i].name != NULL; ++i) + if (desc->fields[i].name == PyStructSequence_UnnamedField) + n_unnamed_members++; + n_members = i; + + memcpy(type, &_struct_sequence_template, sizeof(PyTypeObject)); + type->tp_name = desc->name; + type->tp_doc = desc->doc; + type->tp_basicsize = sizeof(PyStructSequence)+ + sizeof(PyObject*)*(n_members-1); + type->tp_itemsize = 0; + + members = PyMem_NEW(PyMemberDef, n_members-n_unnamed_members+1); + if (members == NULL) + return; + + for (i = k = 0; i < n_members; ++i) { + if (desc->fields[i].name == PyStructSequence_UnnamedField) + continue; + members[k].name = desc->fields[i].name; + members[k].type = T_OBJECT; + members[k].offset = offsetof(PyStructSequence, ob_item) + + i * sizeof(PyObject*); + members[k].flags = READONLY; + members[k].doc = desc->fields[i].doc; + k++; + } + members[k].name = NULL; + + type->tp_members = members; + + if (PyType_Ready(type) < 0) + return; + Py_INCREF(type); + + dict = type->tp_dict; +#define SET_DICT_FROM_INT(key, value) \ + do { \ + PyObject *v = PyLong_FromLong((long) value); \ + if (v != NULL) { \ + PyDict_SetItemString(dict, key, v); \ + Py_DECREF(v); \ + } \ + } while (0) + + SET_DICT_FROM_INT(visible_length_key, desc->n_in_sequence); + SET_DICT_FROM_INT(real_length_key, n_members); + SET_DICT_FROM_INT(unnamed_fields_key, n_unnamed_members); } Modified: python/branches/py3k/Objects/tupleobject.c ============================================================================== --- python/branches/py3k/Objects/tupleobject.c (original) +++ python/branches/py3k/Objects/tupleobject.c Sun May 9 17:52:27 2010 @@ -5,9 +5,9 @@ /* Speed optimization to avoid frequent malloc/free of small tuples */ #ifndef PyTuple_MAXSAVESIZE -#define PyTuple_MAXSAVESIZE 20 /* Largest tuple to save on free list */ +#define PyTuple_MAXSAVESIZE 20 /* Largest tuple to save on free list */ #endif -#ifndef PyTuple_MAXFREELIST +#ifndef PyTuple_MAXFREELIST #define PyTuple_MAXFREELIST 2000 /* Maximum number of tuples of each size to save */ #endif @@ -35,12 +35,12 @@ static void show_track(void) { - fprintf(stderr, "Tuples created: %" PY_FORMAT_SIZE_T "d\n", - count_tracked + count_untracked); - fprintf(stderr, "Tuples tracked by the GC: %" PY_FORMAT_SIZE_T - "d\n", count_tracked); - fprintf(stderr, "%.2f%% tuple tracking rate\n\n", - (100.0*count_tracked/(count_untracked+count_tracked))); + fprintf(stderr, "Tuples created: %" PY_FORMAT_SIZE_T "d\n", + count_tracked + count_untracked); + fprintf(stderr, "Tuples tracked by the GC: %" PY_FORMAT_SIZE_T + "d\n", count_tracked); + fprintf(stderr, "%.2f%% tuple tracking rate\n\n", + (100.0*count_tracked/(count_untracked+count_tracked))); } #endif @@ -48,161 +48,161 @@ PyObject * PyTuple_New(register Py_ssize_t size) { - register PyTupleObject *op; - Py_ssize_t i; - if (size < 0) { - PyErr_BadInternalCall(); - return NULL; - } + register PyTupleObject *op; + Py_ssize_t i; + if (size < 0) { + PyErr_BadInternalCall(); + return NULL; + } #if PyTuple_MAXSAVESIZE > 0 - if (size == 0 && free_list[0]) { - op = free_list[0]; - Py_INCREF(op); + if (size == 0 && free_list[0]) { + op = free_list[0]; + Py_INCREF(op); #ifdef COUNT_ALLOCS - tuple_zero_allocs++; + tuple_zero_allocs++; #endif - return (PyObject *) op; - } - if (size < PyTuple_MAXSAVESIZE && (op = free_list[size]) != NULL) { - free_list[size] = (PyTupleObject *) op->ob_item[0]; - numfree[size]--; + return (PyObject *) op; + } + if (size < PyTuple_MAXSAVESIZE && (op = free_list[size]) != NULL) { + free_list[size] = (PyTupleObject *) op->ob_item[0]; + numfree[size]--; #ifdef COUNT_ALLOCS - fast_tuple_allocs++; + fast_tuple_allocs++; #endif - /* Inline PyObject_InitVar */ + /* Inline PyObject_InitVar */ #ifdef Py_TRACE_REFS - Py_SIZE(op) = size; - Py_TYPE(op) = &PyTuple_Type; + Py_SIZE(op) = size; + Py_TYPE(op) = &PyTuple_Type; #endif - _Py_NewReference((PyObject *)op); - } - else + _Py_NewReference((PyObject *)op); + } + else #endif - { - Py_ssize_t nbytes = size * sizeof(PyObject *); - /* Check for overflow */ - if (nbytes / sizeof(PyObject *) != (size_t)size || - (nbytes > PY_SSIZE_T_MAX - sizeof(PyTupleObject) - sizeof(PyObject *))) - { - return PyErr_NoMemory(); - } - nbytes += sizeof(PyTupleObject) - sizeof(PyObject *); - - op = PyObject_GC_NewVar(PyTupleObject, &PyTuple_Type, size); - if (op == NULL) - return NULL; - } - for (i=0; i < size; i++) - op->ob_item[i] = NULL; + { + Py_ssize_t nbytes = size * sizeof(PyObject *); + /* Check for overflow */ + if (nbytes / sizeof(PyObject *) != (size_t)size || + (nbytes > PY_SSIZE_T_MAX - sizeof(PyTupleObject) - sizeof(PyObject *))) + { + return PyErr_NoMemory(); + } + nbytes += sizeof(PyTupleObject) - sizeof(PyObject *); + + op = PyObject_GC_NewVar(PyTupleObject, &PyTuple_Type, size); + if (op == NULL) + return NULL; + } + for (i=0; i < size; i++) + op->ob_item[i] = NULL; #if PyTuple_MAXSAVESIZE > 0 - if (size == 0) { - free_list[0] = op; - ++numfree[0]; - Py_INCREF(op); /* extra INCREF so that this is never freed */ - } + if (size == 0) { + free_list[0] = op; + ++numfree[0]; + Py_INCREF(op); /* extra INCREF so that this is never freed */ + } #endif #ifdef SHOW_TRACK_COUNT - count_tracked++; + count_tracked++; #endif - _PyObject_GC_TRACK(op); - return (PyObject *) op; + _PyObject_GC_TRACK(op); + return (PyObject *) op; } Py_ssize_t PyTuple_Size(register PyObject *op) { - if (!PyTuple_Check(op)) { - PyErr_BadInternalCall(); - return -1; - } - else - return Py_SIZE(op); + if (!PyTuple_Check(op)) { + PyErr_BadInternalCall(); + return -1; + } + else + return Py_SIZE(op); } PyObject * PyTuple_GetItem(register PyObject *op, register Py_ssize_t i) { - if (!PyTuple_Check(op)) { - PyErr_BadInternalCall(); - return NULL; - } - if (i < 0 || i >= Py_SIZE(op)) { - PyErr_SetString(PyExc_IndexError, "tuple index out of range"); - return NULL; - } - return ((PyTupleObject *)op) -> ob_item[i]; + if (!PyTuple_Check(op)) { + PyErr_BadInternalCall(); + return NULL; + } + if (i < 0 || i >= Py_SIZE(op)) { + PyErr_SetString(PyExc_IndexError, "tuple index out of range"); + return NULL; + } + return ((PyTupleObject *)op) -> ob_item[i]; } int PyTuple_SetItem(register PyObject *op, register Py_ssize_t i, PyObject *newitem) { - register PyObject *olditem; - register PyObject **p; - if (!PyTuple_Check(op) || op->ob_refcnt != 1) { - Py_XDECREF(newitem); - PyErr_BadInternalCall(); - return -1; - } - if (i < 0 || i >= Py_SIZE(op)) { - Py_XDECREF(newitem); - PyErr_SetString(PyExc_IndexError, - "tuple assignment index out of range"); - return -1; - } - p = ((PyTupleObject *)op) -> ob_item + i; - olditem = *p; - *p = newitem; - Py_XDECREF(olditem); - return 0; + register PyObject *olditem; + register PyObject **p; + if (!PyTuple_Check(op) || op->ob_refcnt != 1) { + Py_XDECREF(newitem); + PyErr_BadInternalCall(); + return -1; + } + if (i < 0 || i >= Py_SIZE(op)) { + Py_XDECREF(newitem); + PyErr_SetString(PyExc_IndexError, + "tuple assignment index out of range"); + return -1; + } + p = ((PyTupleObject *)op) -> ob_item + i; + olditem = *p; + *p = newitem; + Py_XDECREF(olditem); + return 0; } void _PyTuple_MaybeUntrack(PyObject *op) { - PyTupleObject *t; - Py_ssize_t i, n; - - if (!PyTuple_CheckExact(op) || !_PyObject_GC_IS_TRACKED(op)) - return; - t = (PyTupleObject *) op; - n = Py_SIZE(t); - for (i = 0; i < n; i++) { - PyObject *elt = PyTuple_GET_ITEM(t, i); - /* Tuple with NULL elements aren't - fully constructed, don't untrack - them yet. */ - if (!elt || - _PyObject_GC_MAY_BE_TRACKED(elt)) - return; - } + PyTupleObject *t; + Py_ssize_t i, n; + + if (!PyTuple_CheckExact(op) || !_PyObject_GC_IS_TRACKED(op)) + return; + t = (PyTupleObject *) op; + n = Py_SIZE(t); + for (i = 0; i < n; i++) { + PyObject *elt = PyTuple_GET_ITEM(t, i); + /* Tuple with NULL elements aren't + fully constructed, don't untrack + them yet. */ + if (!elt || + _PyObject_GC_MAY_BE_TRACKED(elt)) + return; + } #ifdef SHOW_TRACK_COUNT - count_tracked--; - count_untracked++; + count_tracked--; + count_untracked++; #endif - _PyObject_GC_UNTRACK(op); + _PyObject_GC_UNTRACK(op); } PyObject * PyTuple_Pack(Py_ssize_t n, ...) { - Py_ssize_t i; - PyObject *o; - PyObject *result; - PyObject **items; - va_list vargs; - - va_start(vargs, n); - result = PyTuple_New(n); - if (result == NULL) - return NULL; - items = ((PyTupleObject *)result)->ob_item; - for (i = 0; i < n; i++) { - o = va_arg(vargs, PyObject *); - Py_INCREF(o); - items[i] = o; - } - va_end(vargs); - return result; + Py_ssize_t i; + PyObject *o; + PyObject *result; + PyObject **items; + va_list vargs; + + va_start(vargs, n); + result = PyTuple_New(n); + if (result == NULL) + return NULL; + items = ((PyTupleObject *)result)->ob_item; + for (i = 0; i < n; i++) { + o = va_arg(vargs, PyObject *); + Py_INCREF(o); + items[i] = o; + } + va_end(vargs); + return result; } @@ -211,405 +211,405 @@ static void tupledealloc(register PyTupleObject *op) { - register Py_ssize_t i; - register Py_ssize_t len = Py_SIZE(op); - PyObject_GC_UnTrack(op); - Py_TRASHCAN_SAFE_BEGIN(op) - if (len > 0) { - i = len; - while (--i >= 0) - Py_XDECREF(op->ob_item[i]); + register Py_ssize_t i; + register Py_ssize_t len = Py_SIZE(op); + PyObject_GC_UnTrack(op); + Py_TRASHCAN_SAFE_BEGIN(op) + if (len > 0) { + i = len; + while (--i >= 0) + Py_XDECREF(op->ob_item[i]); #if PyTuple_MAXSAVESIZE > 0 - if (len < PyTuple_MAXSAVESIZE && - numfree[len] < PyTuple_MAXFREELIST && - Py_TYPE(op) == &PyTuple_Type) - { - op->ob_item[0] = (PyObject *) free_list[len]; - numfree[len]++; - free_list[len] = op; - goto done; /* return */ - } + if (len < PyTuple_MAXSAVESIZE && + numfree[len] < PyTuple_MAXFREELIST && + Py_TYPE(op) == &PyTuple_Type) + { + op->ob_item[0] = (PyObject *) free_list[len]; + numfree[len]++; + free_list[len] = op; + goto done; /* return */ + } #endif - } - Py_TYPE(op)->tp_free((PyObject *)op); + } + Py_TYPE(op)->tp_free((PyObject *)op); done: - Py_TRASHCAN_SAFE_END(op) + Py_TRASHCAN_SAFE_END(op) } static PyObject * tuplerepr(PyTupleObject *v) { - Py_ssize_t i, n; - PyObject *s, *temp; - PyObject *pieces, *result = NULL; - - n = Py_SIZE(v); - if (n == 0) - return PyUnicode_FromString("()"); - - /* While not mutable, it is still possible to end up with a cycle in a - tuple through an object that stores itself within a tuple (and thus - infinitely asks for the repr of itself). This should only be - possible within a type. */ - i = Py_ReprEnter((PyObject *)v); - if (i != 0) { - return i > 0 ? PyUnicode_FromString("(...)") : NULL; - } - - pieces = PyTuple_New(n); - if (pieces == NULL) - return NULL; - - /* Do repr() on each element. */ - for (i = 0; i < n; ++i) { - if (Py_EnterRecursiveCall(" while getting the repr of a tuple")) - goto Done; - s = PyObject_Repr(v->ob_item[i]); - Py_LeaveRecursiveCall(); - if (s == NULL) - goto Done; - PyTuple_SET_ITEM(pieces, i, s); - } - - /* Add "()" decorations to the first and last items. */ - assert(n > 0); - s = PyUnicode_FromString("("); - if (s == NULL) - goto Done; - temp = PyTuple_GET_ITEM(pieces, 0); - PyUnicode_AppendAndDel(&s, temp); - PyTuple_SET_ITEM(pieces, 0, s); - if (s == NULL) - goto Done; - - s = PyUnicode_FromString(n == 1 ? ",)" : ")"); - if (s == NULL) - goto Done; - temp = PyTuple_GET_ITEM(pieces, n-1); - PyUnicode_AppendAndDel(&temp, s); - PyTuple_SET_ITEM(pieces, n-1, temp); - if (temp == NULL) - goto Done; - - /* Paste them all together with ", " between. */ - s = PyUnicode_FromString(", "); - if (s == NULL) - goto Done; - result = PyUnicode_Join(s, pieces); - Py_DECREF(s); + Py_ssize_t i, n; + PyObject *s, *temp; + PyObject *pieces, *result = NULL; + + n = Py_SIZE(v); + if (n == 0) + return PyUnicode_FromString("()"); + + /* While not mutable, it is still possible to end up with a cycle in a + tuple through an object that stores itself within a tuple (and thus + infinitely asks for the repr of itself). This should only be + possible within a type. */ + i = Py_ReprEnter((PyObject *)v); + if (i != 0) { + return i > 0 ? PyUnicode_FromString("(...)") : NULL; + } + + pieces = PyTuple_New(n); + if (pieces == NULL) + return NULL; + + /* Do repr() on each element. */ + for (i = 0; i < n; ++i) { + if (Py_EnterRecursiveCall(" while getting the repr of a tuple")) + goto Done; + s = PyObject_Repr(v->ob_item[i]); + Py_LeaveRecursiveCall(); + if (s == NULL) + goto Done; + PyTuple_SET_ITEM(pieces, i, s); + } + + /* Add "()" decorations to the first and last items. */ + assert(n > 0); + s = PyUnicode_FromString("("); + if (s == NULL) + goto Done; + temp = PyTuple_GET_ITEM(pieces, 0); + PyUnicode_AppendAndDel(&s, temp); + PyTuple_SET_ITEM(pieces, 0, s); + if (s == NULL) + goto Done; + + s = PyUnicode_FromString(n == 1 ? ",)" : ")"); + if (s == NULL) + goto Done; + temp = PyTuple_GET_ITEM(pieces, n-1); + PyUnicode_AppendAndDel(&temp, s); + PyTuple_SET_ITEM(pieces, n-1, temp); + if (temp == NULL) + goto Done; + + /* Paste them all together with ", " between. */ + s = PyUnicode_FromString(", "); + if (s == NULL) + goto Done; + result = PyUnicode_Join(s, pieces); + Py_DECREF(s); Done: - Py_DECREF(pieces); - Py_ReprLeave((PyObject *)v); - return result; + Py_DECREF(pieces); + Py_ReprLeave((PyObject *)v); + return result; } -/* The addend 82520, was selected from the range(0, 1000000) for - generating the greatest number of prime multipliers for tuples +/* The addend 82520, was selected from the range(0, 1000000) for + generating the greatest number of prime multipliers for tuples upto length eight: - 1082527, 1165049, 1082531, 1165057, 1247581, 1330103, 1082533, + 1082527, 1165049, 1082531, 1165057, 1247581, 1330103, 1082533, 1330111, 1412633, 1165069, 1247599, 1495177, 1577699 */ static long tuplehash(PyTupleObject *v) { - register long x, y; - register Py_ssize_t len = Py_SIZE(v); - register PyObject **p; - long mult = 1000003L; - x = 0x345678L; - p = v->ob_item; - while (--len >= 0) { - y = PyObject_Hash(*p++); - if (y == -1) - return -1; - x = (x ^ y) * mult; - /* the cast might truncate len; that doesn't change hash stability */ - mult += (long)(82520L + len + len); - } - x += 97531L; - if (x == -1) - x = -2; - return x; + register long x, y; + register Py_ssize_t len = Py_SIZE(v); + register PyObject **p; + long mult = 1000003L; + x = 0x345678L; + p = v->ob_item; + while (--len >= 0) { + y = PyObject_Hash(*p++); + if (y == -1) + return -1; + x = (x ^ y) * mult; + /* the cast might truncate len; that doesn't change hash stability */ + mult += (long)(82520L + len + len); + } + x += 97531L; + if (x == -1) + x = -2; + return x; } static Py_ssize_t tuplelength(PyTupleObject *a) { - return Py_SIZE(a); + return Py_SIZE(a); } static int tuplecontains(PyTupleObject *a, PyObject *el) { - Py_ssize_t i; - int cmp; + Py_ssize_t i; + int cmp; - for (i = 0, cmp = 0 ; cmp == 0 && i < Py_SIZE(a); ++i) - cmp = PyObject_RichCompareBool(el, PyTuple_GET_ITEM(a, i), - Py_EQ); - return cmp; + for (i = 0, cmp = 0 ; cmp == 0 && i < Py_SIZE(a); ++i) + cmp = PyObject_RichCompareBool(el, PyTuple_GET_ITEM(a, i), + Py_EQ); + return cmp; } static PyObject * tupleitem(register PyTupleObject *a, register Py_ssize_t i) { - if (i < 0 || i >= Py_SIZE(a)) { - PyErr_SetString(PyExc_IndexError, "tuple index out of range"); - return NULL; - } - Py_INCREF(a->ob_item[i]); - return a->ob_item[i]; + if (i < 0 || i >= Py_SIZE(a)) { + PyErr_SetString(PyExc_IndexError, "tuple index out of range"); + return NULL; + } + Py_INCREF(a->ob_item[i]); + return a->ob_item[i]; } static PyObject * -tupleslice(register PyTupleObject *a, register Py_ssize_t ilow, - register Py_ssize_t ihigh) +tupleslice(register PyTupleObject *a, register Py_ssize_t ilow, + register Py_ssize_t ihigh) { - register PyTupleObject *np; - PyObject **src, **dest; - register Py_ssize_t i; - Py_ssize_t len; - if (ilow < 0) - ilow = 0; - if (ihigh > Py_SIZE(a)) - ihigh = Py_SIZE(a); - if (ihigh < ilow) - ihigh = ilow; - if (ilow == 0 && ihigh == Py_SIZE(a) && PyTuple_CheckExact(a)) { - Py_INCREF(a); - return (PyObject *)a; - } - len = ihigh - ilow; - np = (PyTupleObject *)PyTuple_New(len); - if (np == NULL) - return NULL; - src = a->ob_item + ilow; - dest = np->ob_item; - for (i = 0; i < len; i++) { - PyObject *v = src[i]; - Py_INCREF(v); - dest[i] = v; - } - return (PyObject *)np; + register PyTupleObject *np; + PyObject **src, **dest; + register Py_ssize_t i; + Py_ssize_t len; + if (ilow < 0) + ilow = 0; + if (ihigh > Py_SIZE(a)) + ihigh = Py_SIZE(a); + if (ihigh < ilow) + ihigh = ilow; + if (ilow == 0 && ihigh == Py_SIZE(a) && PyTuple_CheckExact(a)) { + Py_INCREF(a); + return (PyObject *)a; + } + len = ihigh - ilow; + np = (PyTupleObject *)PyTuple_New(len); + if (np == NULL) + return NULL; + src = a->ob_item + ilow; + dest = np->ob_item; + for (i = 0; i < len; i++) { + PyObject *v = src[i]; + Py_INCREF(v); + dest[i] = v; + } + return (PyObject *)np; } PyObject * PyTuple_GetSlice(PyObject *op, Py_ssize_t i, Py_ssize_t j) { - if (op == NULL || !PyTuple_Check(op)) { - PyErr_BadInternalCall(); - return NULL; - } - return tupleslice((PyTupleObject *)op, i, j); + if (op == NULL || !PyTuple_Check(op)) { + PyErr_BadInternalCall(); + return NULL; + } + return tupleslice((PyTupleObject *)op, i, j); } static PyObject * tupleconcat(register PyTupleObject *a, register PyObject *bb) { - register Py_ssize_t size; - register Py_ssize_t i; - PyObject **src, **dest; - PyTupleObject *np; - if (!PyTuple_Check(bb)) { - PyErr_Format(PyExc_TypeError, - "can only concatenate tuple (not \"%.200s\") to tuple", - Py_TYPE(bb)->tp_name); - return NULL; - } + register Py_ssize_t size; + register Py_ssize_t i; + PyObject **src, **dest; + PyTupleObject *np; + if (!PyTuple_Check(bb)) { + PyErr_Format(PyExc_TypeError, + "can only concatenate tuple (not \"%.200s\") to tuple", + Py_TYPE(bb)->tp_name); + return NULL; + } #define b ((PyTupleObject *)bb) - size = Py_SIZE(a) + Py_SIZE(b); - if (size < 0) - return PyErr_NoMemory(); - np = (PyTupleObject *) PyTuple_New(size); - if (np == NULL) { - return NULL; - } - src = a->ob_item; - dest = np->ob_item; - for (i = 0; i < Py_SIZE(a); i++) { - PyObject *v = src[i]; - Py_INCREF(v); - dest[i] = v; - } - src = b->ob_item; - dest = np->ob_item + Py_SIZE(a); - for (i = 0; i < Py_SIZE(b); i++) { - PyObject *v = src[i]; - Py_INCREF(v); - dest[i] = v; - } - return (PyObject *)np; + size = Py_SIZE(a) + Py_SIZE(b); + if (size < 0) + return PyErr_NoMemory(); + np = (PyTupleObject *) PyTuple_New(size); + if (np == NULL) { + return NULL; + } + src = a->ob_item; + dest = np->ob_item; + for (i = 0; i < Py_SIZE(a); i++) { + PyObject *v = src[i]; + Py_INCREF(v); + dest[i] = v; + } + src = b->ob_item; + dest = np->ob_item + Py_SIZE(a); + for (i = 0; i < Py_SIZE(b); i++) { + PyObject *v = src[i]; + Py_INCREF(v); + dest[i] = v; + } + return (PyObject *)np; #undef b } static PyObject * tuplerepeat(PyTupleObject *a, Py_ssize_t n) { - Py_ssize_t i, j; - Py_ssize_t size; - PyTupleObject *np; - PyObject **p, **items; - if (n < 0) - n = 0; - if (Py_SIZE(a) == 0 || n == 1) { - if (PyTuple_CheckExact(a)) { - /* Since tuples are immutable, we can return a shared - copy in this case */ - Py_INCREF(a); - return (PyObject *)a; - } - if (Py_SIZE(a) == 0) - return PyTuple_New(0); - } - size = Py_SIZE(a) * n; - if (size/Py_SIZE(a) != n) - return PyErr_NoMemory(); - np = (PyTupleObject *) PyTuple_New(size); - if (np == NULL) - return NULL; - p = np->ob_item; - items = a->ob_item; - for (i = 0; i < n; i++) { - for (j = 0; j < Py_SIZE(a); j++) { - *p = items[j]; - Py_INCREF(*p); - p++; - } - } - return (PyObject *) np; + Py_ssize_t i, j; + Py_ssize_t size; + PyTupleObject *np; + PyObject **p, **items; + if (n < 0) + n = 0; + if (Py_SIZE(a) == 0 || n == 1) { + if (PyTuple_CheckExact(a)) { + /* Since tuples are immutable, we can return a shared + copy in this case */ + Py_INCREF(a); + return (PyObject *)a; + } + if (Py_SIZE(a) == 0) + return PyTuple_New(0); + } + size = Py_SIZE(a) * n; + if (size/Py_SIZE(a) != n) + return PyErr_NoMemory(); + np = (PyTupleObject *) PyTuple_New(size); + if (np == NULL) + return NULL; + p = np->ob_item; + items = a->ob_item; + for (i = 0; i < n; i++) { + for (j = 0; j < Py_SIZE(a); j++) { + *p = items[j]; + Py_INCREF(*p); + p++; + } + } + return (PyObject *) np; } static PyObject * tupleindex(PyTupleObject *self, PyObject *args) { - Py_ssize_t i, start=0, stop=Py_SIZE(self); - PyObject *v; + Py_ssize_t i, start=0, stop=Py_SIZE(self); + PyObject *v; - if (!PyArg_ParseTuple(args, "O|O&O&:index", &v, - _PyEval_SliceIndex, &start, - _PyEval_SliceIndex, &stop)) - return NULL; - if (start < 0) { - start += Py_SIZE(self); - if (start < 0) - start = 0; - } - if (stop < 0) { - stop += Py_SIZE(self); - if (stop < 0) - stop = 0; - } - for (i = start; i < stop && i < Py_SIZE(self); i++) { - int cmp = PyObject_RichCompareBool(self->ob_item[i], v, Py_EQ); - if (cmp > 0) - return PyLong_FromSsize_t(i); - else if (cmp < 0) - return NULL; - } - PyErr_SetString(PyExc_ValueError, "tuple.index(x): x not in tuple"); - return NULL; + if (!PyArg_ParseTuple(args, "O|O&O&:index", &v, + _PyEval_SliceIndex, &start, + _PyEval_SliceIndex, &stop)) + return NULL; + if (start < 0) { + start += Py_SIZE(self); + if (start < 0) + start = 0; + } + if (stop < 0) { + stop += Py_SIZE(self); + if (stop < 0) + stop = 0; + } + for (i = start; i < stop && i < Py_SIZE(self); i++) { + int cmp = PyObject_RichCompareBool(self->ob_item[i], v, Py_EQ); + if (cmp > 0) + return PyLong_FromSsize_t(i); + else if (cmp < 0) + return NULL; + } + PyErr_SetString(PyExc_ValueError, "tuple.index(x): x not in tuple"); + return NULL; } static PyObject * tuplecount(PyTupleObject *self, PyObject *v) { - Py_ssize_t count = 0; - Py_ssize_t i; + Py_ssize_t count = 0; + Py_ssize_t i; - for (i = 0; i < Py_SIZE(self); i++) { - int cmp = PyObject_RichCompareBool(self->ob_item[i], v, Py_EQ); - if (cmp > 0) - count++; - else if (cmp < 0) - return NULL; - } - return PyLong_FromSsize_t(count); + for (i = 0; i < Py_SIZE(self); i++) { + int cmp = PyObject_RichCompareBool(self->ob_item[i], v, Py_EQ); + if (cmp > 0) + count++; + else if (cmp < 0) + return NULL; + } + return PyLong_FromSsize_t(count); } static int tupletraverse(PyTupleObject *o, visitproc visit, void *arg) { - Py_ssize_t i; + Py_ssize_t i; - for (i = Py_SIZE(o); --i >= 0; ) - Py_VISIT(o->ob_item[i]); - return 0; + for (i = Py_SIZE(o); --i >= 0; ) + Py_VISIT(o->ob_item[i]); + return 0; } static PyObject * tuplerichcompare(PyObject *v, PyObject *w, int op) { - PyTupleObject *vt, *wt; - Py_ssize_t i; - Py_ssize_t vlen, wlen; - - if (!PyTuple_Check(v) || !PyTuple_Check(w)) { - Py_INCREF(Py_NotImplemented); - return Py_NotImplemented; - } - - vt = (PyTupleObject *)v; - wt = (PyTupleObject *)w; - - vlen = Py_SIZE(vt); - wlen = Py_SIZE(wt); - - /* Note: the corresponding code for lists has an "early out" test - * here when op is EQ or NE and the lengths differ. That pays there, - * but Tim was unable to find any real code where EQ/NE tuple - * compares don't have the same length, so testing for it here would - * have cost without benefit. - */ - - /* Search for the first index where items are different. - * Note that because tuples are immutable, it's safe to reuse - * vlen and wlen across the comparison calls. - */ - for (i = 0; i < vlen && i < wlen; i++) { - int k = PyObject_RichCompareBool(vt->ob_item[i], - wt->ob_item[i], Py_EQ); - if (k < 0) - return NULL; - if (!k) - break; - } - - if (i >= vlen || i >= wlen) { - /* No more items to compare -- compare sizes */ - int cmp; - PyObject *res; - switch (op) { - case Py_LT: cmp = vlen < wlen; break; - case Py_LE: cmp = vlen <= wlen; break; - case Py_EQ: cmp = vlen == wlen; break; - case Py_NE: cmp = vlen != wlen; break; - case Py_GT: cmp = vlen > wlen; break; - case Py_GE: cmp = vlen >= wlen; break; - default: return NULL; /* cannot happen */ - } - if (cmp) - res = Py_True; - else - res = Py_False; - Py_INCREF(res); - return res; - } - - /* We have an item that differs -- shortcuts for EQ/NE */ - if (op == Py_EQ) { - Py_INCREF(Py_False); - return Py_False; - } - if (op == Py_NE) { - Py_INCREF(Py_True); - return Py_True; - } + PyTupleObject *vt, *wt; + Py_ssize_t i; + Py_ssize_t vlen, wlen; + + if (!PyTuple_Check(v) || !PyTuple_Check(w)) { + Py_INCREF(Py_NotImplemented); + return Py_NotImplemented; + } + + vt = (PyTupleObject *)v; + wt = (PyTupleObject *)w; + + vlen = Py_SIZE(vt); + wlen = Py_SIZE(wt); + + /* Note: the corresponding code for lists has an "early out" test + * here when op is EQ or NE and the lengths differ. That pays there, + * but Tim was unable to find any real code where EQ/NE tuple + * compares don't have the same length, so testing for it here would + * have cost without benefit. + */ + + /* Search for the first index where items are different. + * Note that because tuples are immutable, it's safe to reuse + * vlen and wlen across the comparison calls. + */ + for (i = 0; i < vlen && i < wlen; i++) { + int k = PyObject_RichCompareBool(vt->ob_item[i], + wt->ob_item[i], Py_EQ); + if (k < 0) + return NULL; + if (!k) + break; + } + + if (i >= vlen || i >= wlen) { + /* No more items to compare -- compare sizes */ + int cmp; + PyObject *res; + switch (op) { + case Py_LT: cmp = vlen < wlen; break; + case Py_LE: cmp = vlen <= wlen; break; + case Py_EQ: cmp = vlen == wlen; break; + case Py_NE: cmp = vlen != wlen; break; + case Py_GT: cmp = vlen > wlen; break; + case Py_GE: cmp = vlen >= wlen; break; + default: return NULL; /* cannot happen */ + } + if (cmp) + res = Py_True; + else + res = Py_False; + Py_INCREF(res); + return res; + } + + /* We have an item that differs -- shortcuts for EQ/NE */ + if (op == Py_EQ) { + Py_INCREF(Py_False); + return Py_False; + } + if (op == Py_NE) { + Py_INCREF(Py_True); + return Py_True; + } - /* Compare the final item again using the proper operator */ - return PyObject_RichCompare(vt->ob_item[i], wt->ob_item[i], op); + /* Compare the final item again using the proper operator */ + return PyObject_RichCompare(vt->ob_item[i], wt->ob_item[i], op); } static PyObject * @@ -618,41 +618,41 @@ static PyObject * tuple_new(PyTypeObject *type, PyObject *args, PyObject *kwds) { - PyObject *arg = NULL; - static char *kwlist[] = {"sequence", 0}; + PyObject *arg = NULL; + static char *kwlist[] = {"sequence", 0}; - if (type != &PyTuple_Type) - return tuple_subtype_new(type, args, kwds); - if (!PyArg_ParseTupleAndKeywords(args, kwds, "|O:tuple", kwlist, &arg)) - return NULL; - - if (arg == NULL) - return PyTuple_New(0); - else - return PySequence_Tuple(arg); + if (type != &PyTuple_Type) + return tuple_subtype_new(type, args, kwds); + if (!PyArg_ParseTupleAndKeywords(args, kwds, "|O:tuple", kwlist, &arg)) + return NULL; + + if (arg == NULL) + return PyTuple_New(0); + else + return PySequence_Tuple(arg); } static PyObject * tuple_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds) { - PyObject *tmp, *newobj, *item; - Py_ssize_t i, n; + PyObject *tmp, *newobj, *item; + Py_ssize_t i, n; - assert(PyType_IsSubtype(type, &PyTuple_Type)); - tmp = tuple_new(&PyTuple_Type, args, kwds); - if (tmp == NULL) - return NULL; - assert(PyTuple_Check(tmp)); - newobj = type->tp_alloc(type, n = PyTuple_GET_SIZE(tmp)); - if (newobj == NULL) - return NULL; - for (i = 0; i < n; i++) { - item = PyTuple_GET_ITEM(tmp, i); - Py_INCREF(item); - PyTuple_SET_ITEM(newobj, i, item); - } - Py_DECREF(tmp); - return newobj; + assert(PyType_IsSubtype(type, &PyTuple_Type)); + tmp = tuple_new(&PyTuple_Type, args, kwds); + if (tmp == NULL) + return NULL; + assert(PyTuple_Check(tmp)); + newobj = type->tp_alloc(type, n = PyTuple_GET_SIZE(tmp)); + if (newobj == NULL) + return NULL; + for (i = 0; i < n; i++) { + item = PyTuple_GET_ITEM(tmp, i); + Py_INCREF(item); + PyTuple_SET_ITEM(newobj, i, item); + } + Py_DECREF(tmp); + return newobj; } PyDoc_STRVAR(tuple_doc, @@ -662,86 +662,86 @@ If the argument is a tuple, the return value is the same object."); static PySequenceMethods tuple_as_sequence = { - (lenfunc)tuplelength, /* sq_length */ - (binaryfunc)tupleconcat, /* sq_concat */ - (ssizeargfunc)tuplerepeat, /* sq_repeat */ - (ssizeargfunc)tupleitem, /* sq_item */ - 0, /* sq_slice */ - 0, /* sq_ass_item */ - 0, /* sq_ass_slice */ - (objobjproc)tuplecontains, /* sq_contains */ + (lenfunc)tuplelength, /* sq_length */ + (binaryfunc)tupleconcat, /* sq_concat */ + (ssizeargfunc)tuplerepeat, /* sq_repeat */ + (ssizeargfunc)tupleitem, /* sq_item */ + 0, /* sq_slice */ + 0, /* sq_ass_item */ + 0, /* sq_ass_slice */ + (objobjproc)tuplecontains, /* sq_contains */ }; static PyObject* tuplesubscript(PyTupleObject* 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 += PyTuple_GET_SIZE(self); - return tupleitem(self, i); - } - else if (PySlice_Check(item)) { - Py_ssize_t start, stop, step, slicelength, cur, i; - PyObject* result; - PyObject* it; - PyObject **src, **dest; - - if (PySlice_GetIndicesEx((PySliceObject*)item, - PyTuple_GET_SIZE(self), - &start, &stop, &step, &slicelength) < 0) { - return NULL; - } - - if (slicelength <= 0) { - return PyTuple_New(0); - } - else if (start == 0 && step == 1 && - slicelength == PyTuple_GET_SIZE(self) && - PyTuple_CheckExact(self)) { - Py_INCREF(self); - return (PyObject *)self; - } - else { - result = PyTuple_New(slicelength); - if (!result) return NULL; - - src = self->ob_item; - dest = ((PyTupleObject *)result)->ob_item; - for (cur = start, i = 0; i < slicelength; - cur += step, i++) { - it = src[cur]; - Py_INCREF(it); - dest[i] = it; - } - - return result; - } - } - else { - PyErr_Format(PyExc_TypeError, - "tuple indices must be integers, not %.200s", - Py_TYPE(item)->tp_name); - return NULL; - } + 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 += PyTuple_GET_SIZE(self); + return tupleitem(self, i); + } + else if (PySlice_Check(item)) { + Py_ssize_t start, stop, step, slicelength, cur, i; + PyObject* result; + PyObject* it; + PyObject **src, **dest; + + if (PySlice_GetIndicesEx((PySliceObject*)item, + PyTuple_GET_SIZE(self), + &start, &stop, &step, &slicelength) < 0) { + return NULL; + } + + if (slicelength <= 0) { + return PyTuple_New(0); + } + else if (start == 0 && step == 1 && + slicelength == PyTuple_GET_SIZE(self) && + PyTuple_CheckExact(self)) { + Py_INCREF(self); + return (PyObject *)self; + } + else { + result = PyTuple_New(slicelength); + if (!result) return NULL; + + src = self->ob_item; + dest = ((PyTupleObject *)result)->ob_item; + for (cur = start, i = 0; i < slicelength; + cur += step, i++) { + it = src[cur]; + Py_INCREF(it); + dest[i] = it; + } + + return result; + } + } + else { + PyErr_Format(PyExc_TypeError, + "tuple indices must be integers, not %.200s", + Py_TYPE(item)->tp_name); + return NULL; + } } static PyObject * tuple_getnewargs(PyTupleObject *v) { - return Py_BuildValue("(N)", tupleslice(v, 0, Py_SIZE(v))); - + return Py_BuildValue("(N)", tupleslice(v, 0, Py_SIZE(v))); + } static PyObject * tuple_sizeof(PyTupleObject *self) { - Py_ssize_t res; + Py_ssize_t res; - res = PyTuple_Type.tp_basicsize + Py_SIZE(self) * sizeof(PyObject *); - return PyLong_FromSsize_t(res); + res = PyTuple_Type.tp_basicsize + Py_SIZE(self) * sizeof(PyObject *); + return PyLong_FromSsize_t(res); } PyDoc_STRVAR(index_doc, @@ -754,62 +754,62 @@ "T.__sizeof__() -- size of T in memory, in bytes"); static PyMethodDef tuple_methods[] = { - {"__getnewargs__", (PyCFunction)tuple_getnewargs, METH_NOARGS}, - {"__sizeof__", (PyCFunction)tuple_sizeof, METH_NOARGS, sizeof_doc}, - {"index", (PyCFunction)tupleindex, METH_VARARGS, index_doc}, - {"count", (PyCFunction)tuplecount, METH_O, count_doc}, - {NULL, NULL} /* sentinel */ + {"__getnewargs__", (PyCFunction)tuple_getnewargs, METH_NOARGS}, + {"__sizeof__", (PyCFunction)tuple_sizeof, METH_NOARGS, sizeof_doc}, + {"index", (PyCFunction)tupleindex, METH_VARARGS, index_doc}, + {"count", (PyCFunction)tuplecount, METH_O, count_doc}, + {NULL, NULL} /* sentinel */ }; static PyMappingMethods tuple_as_mapping = { - (lenfunc)tuplelength, - (binaryfunc)tuplesubscript, - 0 + (lenfunc)tuplelength, + (binaryfunc)tuplesubscript, + 0 }; static PyObject *tuple_iter(PyObject *seq); PyTypeObject PyTuple_Type = { - PyVarObject_HEAD_INIT(&PyType_Type, 0) - "tuple", - sizeof(PyTupleObject) - sizeof(PyObject *), - sizeof(PyObject *), - (destructor)tupledealloc, /* tp_dealloc */ - 0, /* tp_print */ - 0, /* tp_getattr */ - 0, /* tp_setattr */ - 0, /* tp_reserved */ - (reprfunc)tuplerepr, /* tp_repr */ - 0, /* tp_as_number */ - &tuple_as_sequence, /* tp_as_sequence */ - &tuple_as_mapping, /* tp_as_mapping */ - (hashfunc)tuplehash, /* 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 | - Py_TPFLAGS_BASETYPE | Py_TPFLAGS_TUPLE_SUBCLASS, /* tp_flags */ - tuple_doc, /* tp_doc */ - (traverseproc)tupletraverse, /* tp_traverse */ - 0, /* tp_clear */ - tuplerichcompare, /* tp_richcompare */ - 0, /* tp_weaklistoffset */ - tuple_iter, /* tp_iter */ - 0, /* tp_iternext */ - tuple_methods, /* tp_methods */ - 0, /* tp_members */ - 0, /* tp_getset */ - 0, /* tp_base */ - 0, /* tp_dict */ - 0, /* tp_descr_get */ - 0, /* tp_descr_set */ - 0, /* tp_dictoffset */ - 0, /* tp_init */ - 0, /* tp_alloc */ - tuple_new, /* tp_new */ - PyObject_GC_Del, /* tp_free */ + PyVarObject_HEAD_INIT(&PyType_Type, 0) + "tuple", + sizeof(PyTupleObject) - sizeof(PyObject *), + sizeof(PyObject *), + (destructor)tupledealloc, /* tp_dealloc */ + 0, /* tp_print */ + 0, /* tp_getattr */ + 0, /* tp_setattr */ + 0, /* tp_reserved */ + (reprfunc)tuplerepr, /* tp_repr */ + 0, /* tp_as_number */ + &tuple_as_sequence, /* tp_as_sequence */ + &tuple_as_mapping, /* tp_as_mapping */ + (hashfunc)tuplehash, /* 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 | + Py_TPFLAGS_BASETYPE | Py_TPFLAGS_TUPLE_SUBCLASS, /* tp_flags */ + tuple_doc, /* tp_doc */ + (traverseproc)tupletraverse, /* tp_traverse */ + 0, /* tp_clear */ + tuplerichcompare, /* tp_richcompare */ + 0, /* tp_weaklistoffset */ + tuple_iter, /* tp_iter */ + 0, /* tp_iternext */ + tuple_methods, /* tp_methods */ + 0, /* tp_members */ + 0, /* tp_getset */ + 0, /* tp_base */ + 0, /* tp_dict */ + 0, /* tp_descr_get */ + 0, /* tp_descr_set */ + 0, /* tp_dictoffset */ + 0, /* tp_init */ + 0, /* tp_alloc */ + tuple_new, /* tp_new */ + PyObject_GC_Del, /* tp_free */ }; /* The following function breaks the notion that tuples are immutable: @@ -822,207 +822,207 @@ int _PyTuple_Resize(PyObject **pv, Py_ssize_t newsize) { - register PyTupleObject *v; - register PyTupleObject *sv; - Py_ssize_t i; - Py_ssize_t oldsize; - - v = (PyTupleObject *) *pv; - if (v == NULL || Py_TYPE(v) != &PyTuple_Type || - (Py_SIZE(v) != 0 && Py_REFCNT(v) != 1)) { - *pv = 0; - Py_XDECREF(v); - PyErr_BadInternalCall(); - return -1; - } - oldsize = Py_SIZE(v); - if (oldsize == newsize) - return 0; - - if (oldsize == 0) { - /* Empty tuples are often shared, so we should never - resize them in-place even if we do own the only - (current) reference */ - Py_DECREF(v); - *pv = PyTuple_New(newsize); - return *pv == NULL ? -1 : 0; - } - - /* XXX UNREF/NEWREF interface should be more symmetrical */ - _Py_DEC_REFTOTAL; - if (_PyObject_GC_IS_TRACKED(v)) - _PyObject_GC_UNTRACK(v); - _Py_ForgetReference((PyObject *) v); - /* DECREF items deleted by shrinkage */ - for (i = newsize; i < oldsize; i++) { - Py_XDECREF(v->ob_item[i]); - v->ob_item[i] = NULL; - } - sv = PyObject_GC_Resize(PyTupleObject, v, newsize); - if (sv == NULL) { - *pv = NULL; - PyObject_GC_Del(v); - return -1; - } - _Py_NewReference((PyObject *) sv); - /* Zero out items added by growing */ - if (newsize > oldsize) - memset(&sv->ob_item[oldsize], 0, - sizeof(*sv->ob_item) * (newsize - oldsize)); - *pv = (PyObject *) sv; - _PyObject_GC_TRACK(sv); - return 0; + register PyTupleObject *v; + register PyTupleObject *sv; + Py_ssize_t i; + Py_ssize_t oldsize; + + v = (PyTupleObject *) *pv; + if (v == NULL || Py_TYPE(v) != &PyTuple_Type || + (Py_SIZE(v) != 0 && Py_REFCNT(v) != 1)) { + *pv = 0; + Py_XDECREF(v); + PyErr_BadInternalCall(); + return -1; + } + oldsize = Py_SIZE(v); + if (oldsize == newsize) + return 0; + + if (oldsize == 0) { + /* Empty tuples are often shared, so we should never + resize them in-place even if we do own the only + (current) reference */ + Py_DECREF(v); + *pv = PyTuple_New(newsize); + return *pv == NULL ? -1 : 0; + } + + /* XXX UNREF/NEWREF interface should be more symmetrical */ + _Py_DEC_REFTOTAL; + if (_PyObject_GC_IS_TRACKED(v)) + _PyObject_GC_UNTRACK(v); + _Py_ForgetReference((PyObject *) v); + /* DECREF items deleted by shrinkage */ + for (i = newsize; i < oldsize; i++) { + Py_XDECREF(v->ob_item[i]); + v->ob_item[i] = NULL; + } + sv = PyObject_GC_Resize(PyTupleObject, v, newsize); + if (sv == NULL) { + *pv = NULL; + PyObject_GC_Del(v); + return -1; + } + _Py_NewReference((PyObject *) sv); + /* Zero out items added by growing */ + if (newsize > oldsize) + memset(&sv->ob_item[oldsize], 0, + sizeof(*sv->ob_item) * (newsize - oldsize)); + *pv = (PyObject *) sv; + _PyObject_GC_TRACK(sv); + return 0; } int PyTuple_ClearFreeList(void) { - int freelist_size = 0; + int freelist_size = 0; #if PyTuple_MAXSAVESIZE > 0 - int i; - for (i = 1; i < PyTuple_MAXSAVESIZE; i++) { - PyTupleObject *p, *q; - p = free_list[i]; - freelist_size += numfree[i]; - free_list[i] = NULL; - numfree[i] = 0; - while (p) { - q = p; - p = (PyTupleObject *)(p->ob_item[0]); - PyObject_GC_Del(q); - } - } + int i; + for (i = 1; i < PyTuple_MAXSAVESIZE; i++) { + PyTupleObject *p, *q; + p = free_list[i]; + freelist_size += numfree[i]; + free_list[i] = NULL; + numfree[i] = 0; + while (p) { + q = p; + p = (PyTupleObject *)(p->ob_item[0]); + PyObject_GC_Del(q); + } + } #endif - return freelist_size; + return freelist_size; } - + void PyTuple_Fini(void) { #if PyTuple_MAXSAVESIZE > 0 - /* empty tuples are used all over the place and applications may - * rely on the fact that an empty tuple is a singleton. */ - Py_XDECREF(free_list[0]); - free_list[0] = NULL; + /* empty tuples are used all over the place and applications may + * rely on the fact that an empty tuple is a singleton. */ + Py_XDECREF(free_list[0]); + free_list[0] = NULL; - (void)PyTuple_ClearFreeList(); + (void)PyTuple_ClearFreeList(); #endif #ifdef SHOW_TRACK_COUNT - show_track(); + show_track(); #endif } /*********************** Tuple Iterator **************************/ typedef struct { - PyObject_HEAD - long it_index; - PyTupleObject *it_seq; /* Set to NULL when iterator is exhausted */ + PyObject_HEAD + long it_index; + PyTupleObject *it_seq; /* Set to NULL when iterator is exhausted */ } tupleiterobject; static void tupleiter_dealloc(tupleiterobject *it) { - _PyObject_GC_UNTRACK(it); - Py_XDECREF(it->it_seq); - PyObject_GC_Del(it); + _PyObject_GC_UNTRACK(it); + Py_XDECREF(it->it_seq); + PyObject_GC_Del(it); } static int tupleiter_traverse(tupleiterobject *it, visitproc visit, void *arg) { - Py_VISIT(it->it_seq); - return 0; + Py_VISIT(it->it_seq); + return 0; } static PyObject * tupleiter_next(tupleiterobject *it) { - PyTupleObject *seq; - PyObject *item; + PyTupleObject *seq; + PyObject *item; - assert(it != NULL); - seq = it->it_seq; - if (seq == NULL) - return NULL; - assert(PyTuple_Check(seq)); - - if (it->it_index < PyTuple_GET_SIZE(seq)) { - item = PyTuple_GET_ITEM(seq, it->it_index); - ++it->it_index; - Py_INCREF(item); - return item; - } - - Py_DECREF(seq); - it->it_seq = NULL; - return NULL; + assert(it != NULL); + seq = it->it_seq; + if (seq == NULL) + return NULL; + assert(PyTuple_Check(seq)); + + if (it->it_index < PyTuple_GET_SIZE(seq)) { + item = PyTuple_GET_ITEM(seq, it->it_index); + ++it->it_index; + Py_INCREF(item); + return item; + } + + Py_DECREF(seq); + it->it_seq = NULL; + return NULL; } static PyObject * tupleiter_len(tupleiterobject *it) { - Py_ssize_t len = 0; - if (it->it_seq) - len = PyTuple_GET_SIZE(it->it_seq) - it->it_index; - return PyLong_FromSsize_t(len); + Py_ssize_t len = 0; + if (it->it_seq) + len = PyTuple_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 PyMethodDef tupleiter_methods[] = { - {"__length_hint__", (PyCFunction)tupleiter_len, METH_NOARGS, length_hint_doc}, - {NULL, NULL} /* sentinel */ + {"__length_hint__", (PyCFunction)tupleiter_len, METH_NOARGS, length_hint_doc}, + {NULL, NULL} /* sentinel */ }; PyTypeObject PyTupleIter_Type = { - PyVarObject_HEAD_INIT(&PyType_Type, 0) - "tuple_iterator", /* tp_name */ - sizeof(tupleiterobject), /* tp_basicsize */ - 0, /* tp_itemsize */ - /* methods */ - (destructor)tupleiter_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)tupleiter_traverse, /* tp_traverse */ - 0, /* tp_clear */ - 0, /* tp_richcompare */ - 0, /* tp_weaklistoffset */ - PyObject_SelfIter, /* tp_iter */ - (iternextfunc)tupleiter_next, /* tp_iternext */ - tupleiter_methods, /* tp_methods */ - 0, + PyVarObject_HEAD_INIT(&PyType_Type, 0) + "tuple_iterator", /* tp_name */ + sizeof(tupleiterobject), /* tp_basicsize */ + 0, /* tp_itemsize */ + /* methods */ + (destructor)tupleiter_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)tupleiter_traverse, /* tp_traverse */ + 0, /* tp_clear */ + 0, /* tp_richcompare */ + 0, /* tp_weaklistoffset */ + PyObject_SelfIter, /* tp_iter */ + (iternextfunc)tupleiter_next, /* tp_iternext */ + tupleiter_methods, /* tp_methods */ + 0, }; static PyObject * tuple_iter(PyObject *seq) { - tupleiterobject *it; + tupleiterobject *it; - if (!PyTuple_Check(seq)) { - PyErr_BadInternalCall(); - return NULL; - } - it = PyObject_GC_New(tupleiterobject, &PyTupleIter_Type); - if (it == NULL) - return NULL; - it->it_index = 0; - Py_INCREF(seq); - it->it_seq = (PyTupleObject *)seq; - _PyObject_GC_TRACK(it); - return (PyObject *)it; + if (!PyTuple_Check(seq)) { + PyErr_BadInternalCall(); + return NULL; + } + it = PyObject_GC_New(tupleiterobject, &PyTupleIter_Type); + if (it == NULL) + return NULL; + it->it_index = 0; + Py_INCREF(seq); + it->it_seq = (PyTupleObject *)seq; + _PyObject_GC_TRACK(it); + return (PyObject *)it; } Modified: python/branches/py3k/Objects/typeobject.c ============================================================================== --- python/branches/py3k/Objects/typeobject.c (original) +++ python/branches/py3k/Objects/typeobject.c Sun May 9 17:52:27 2010 @@ -13,22 +13,22 @@ they normally would. This is why the maximum size is limited to MCACHE_MAX_ATTR_SIZE, since it might be a problem if very large strings are used as attribute names. */ -#define MCACHE_MAX_ATTR_SIZE 100 -#define MCACHE_SIZE_EXP 10 -#define MCACHE_HASH(version, name_hash) \ - (((unsigned int)(version) * (unsigned int)(name_hash)) \ - >> (8*sizeof(unsigned int) - MCACHE_SIZE_EXP)) +#define MCACHE_MAX_ATTR_SIZE 100 +#define MCACHE_SIZE_EXP 10 +#define MCACHE_HASH(version, name_hash) \ + (((unsigned int)(version) * (unsigned int)(name_hash)) \ + >> (8*sizeof(unsigned int) - MCACHE_SIZE_EXP)) #define MCACHE_HASH_METHOD(type, name) \ - MCACHE_HASH((type)->tp_version_tag, \ - ((PyUnicodeObject *)(name))->hash) + MCACHE_HASH((type)->tp_version_tag, \ + ((PyUnicodeObject *)(name))->hash) #define MCACHE_CACHEABLE_NAME(name) \ - PyUnicode_CheckExact(name) && \ - PyUnicode_GET_SIZE(name) <= MCACHE_MAX_ATTR_SIZE + PyUnicode_CheckExact(name) && \ + PyUnicode_GET_SIZE(name) <= MCACHE_MAX_ATTR_SIZE struct method_cache_entry { - unsigned int version; - PyObject *name; /* reference to exactly a str or None */ - PyObject *value; /* borrowed */ + unsigned int version; + PyObject *name; /* reference to exactly a str or None */ + PyObject *value; /* borrowed */ }; static struct method_cache_entry method_cache[1 << MCACHE_SIZE_EXP]; @@ -37,325 +37,325 @@ unsigned int PyType_ClearCache(void) { - Py_ssize_t i; - unsigned int cur_version_tag = next_version_tag - 1; - - for (i = 0; i < (1 << MCACHE_SIZE_EXP); i++) { - method_cache[i].version = 0; - Py_CLEAR(method_cache[i].name); - method_cache[i].value = NULL; - } - next_version_tag = 0; - /* mark all version tags as invalid */ - PyType_Modified(&PyBaseObject_Type); - return cur_version_tag; + Py_ssize_t i; + unsigned int cur_version_tag = next_version_tag - 1; + + for (i = 0; i < (1 << MCACHE_SIZE_EXP); i++) { + method_cache[i].version = 0; + Py_CLEAR(method_cache[i].name); + method_cache[i].value = NULL; + } + next_version_tag = 0; + /* mark all version tags as invalid */ + PyType_Modified(&PyBaseObject_Type); + return cur_version_tag; } void PyType_Modified(PyTypeObject *type) { - /* Invalidate any cached data for the specified type and all - subclasses. This function is called after the base - classes, mro, or attributes of the type are altered. - - Invariants: - - - Py_TPFLAGS_VALID_VERSION_TAG is never set if - Py_TPFLAGS_HAVE_VERSION_TAG is not set (e.g. on type - objects coming from non-recompiled extension modules) - - - before Py_TPFLAGS_VALID_VERSION_TAG can be set on a type, - it must first be set on all super types. - - This function clears the Py_TPFLAGS_VALID_VERSION_TAG of a - type (so it must first clear it on all subclasses). The - tp_version_tag value is meaningless unless this flag is set. - We don't assign new version tags eagerly, but only as - needed. - */ - PyObject *raw, *ref; - Py_ssize_t i, n; - - if (!PyType_HasFeature(type, Py_TPFLAGS_VALID_VERSION_TAG)) - return; - - raw = type->tp_subclasses; - if (raw != NULL) { - n = PyList_GET_SIZE(raw); - for (i = 0; i < n; i++) { - ref = PyList_GET_ITEM(raw, i); - ref = PyWeakref_GET_OBJECT(ref); - if (ref != Py_None) { - PyType_Modified((PyTypeObject *)ref); - } - } - } - type->tp_flags &= ~Py_TPFLAGS_VALID_VERSION_TAG; + /* Invalidate any cached data for the specified type and all + subclasses. This function is called after the base + classes, mro, or attributes of the type are altered. + + Invariants: + + - Py_TPFLAGS_VALID_VERSION_TAG is never set if + Py_TPFLAGS_HAVE_VERSION_TAG is not set (e.g. on type + objects coming from non-recompiled extension modules) + + - before Py_TPFLAGS_VALID_VERSION_TAG can be set on a type, + it must first be set on all super types. + + This function clears the Py_TPFLAGS_VALID_VERSION_TAG of a + type (so it must first clear it on all subclasses). The + tp_version_tag value is meaningless unless this flag is set. + We don't assign new version tags eagerly, but only as + needed. + */ + PyObject *raw, *ref; + Py_ssize_t i, n; + + if (!PyType_HasFeature(type, Py_TPFLAGS_VALID_VERSION_TAG)) + return; + + raw = type->tp_subclasses; + if (raw != NULL) { + n = PyList_GET_SIZE(raw); + for (i = 0; i < n; i++) { + ref = PyList_GET_ITEM(raw, i); + ref = PyWeakref_GET_OBJECT(ref); + if (ref != Py_None) { + PyType_Modified((PyTypeObject *)ref); + } + } + } + type->tp_flags &= ~Py_TPFLAGS_VALID_VERSION_TAG; } static void type_mro_modified(PyTypeObject *type, PyObject *bases) { - /* - Check that all base classes or elements of the mro of type are - able to be cached. This function is called after the base - classes or mro of the type are altered. - - Unset HAVE_VERSION_TAG and VALID_VERSION_TAG if the type - inherits from an old-style class, either directly or if it - appears in the MRO of a new-style class. No support either for - custom MROs that include types that are not officially super - types. - - Called from mro_internal, which will subsequently be called on - each subclass when their mro is recursively updated. - */ - Py_ssize_t i, n; - int clear = 0; - - if (!PyType_HasFeature(type, Py_TPFLAGS_HAVE_VERSION_TAG)) - return; - - n = PyTuple_GET_SIZE(bases); - for (i = 0; i < n; i++) { - PyObject *b = PyTuple_GET_ITEM(bases, i); - PyTypeObject *cls; - - if (!PyType_Check(b) ) { - clear = 1; - break; - } - - cls = (PyTypeObject *)b; - - if (!PyType_HasFeature(cls, Py_TPFLAGS_HAVE_VERSION_TAG) || - !PyType_IsSubtype(type, cls)) { - clear = 1; - break; - } - } - - if (clear) - type->tp_flags &= ~(Py_TPFLAGS_HAVE_VERSION_TAG| - Py_TPFLAGS_VALID_VERSION_TAG); + /* + Check that all base classes or elements of the mro of type are + able to be cached. This function is called after the base + classes or mro of the type are altered. + + Unset HAVE_VERSION_TAG and VALID_VERSION_TAG if the type + inherits from an old-style class, either directly or if it + appears in the MRO of a new-style class. No support either for + custom MROs that include types that are not officially super + types. + + Called from mro_internal, which will subsequently be called on + each subclass when their mro is recursively updated. + */ + Py_ssize_t i, n; + int clear = 0; + + if (!PyType_HasFeature(type, Py_TPFLAGS_HAVE_VERSION_TAG)) + return; + + n = PyTuple_GET_SIZE(bases); + for (i = 0; i < n; i++) { + PyObject *b = PyTuple_GET_ITEM(bases, i); + PyTypeObject *cls; + + if (!PyType_Check(b) ) { + clear = 1; + break; + } + + cls = (PyTypeObject *)b; + + if (!PyType_HasFeature(cls, Py_TPFLAGS_HAVE_VERSION_TAG) || + !PyType_IsSubtype(type, cls)) { + clear = 1; + break; + } + } + + if (clear) + type->tp_flags &= ~(Py_TPFLAGS_HAVE_VERSION_TAG| + Py_TPFLAGS_VALID_VERSION_TAG); } static int assign_version_tag(PyTypeObject *type) { - /* Ensure that the tp_version_tag is valid and set - Py_TPFLAGS_VALID_VERSION_TAG. To respect the invariant, this - must first be done on all super classes. Return 0 if this - cannot be done, 1 if Py_TPFLAGS_VALID_VERSION_TAG. - */ - Py_ssize_t i, n; - PyObject *bases; - - if (PyType_HasFeature(type, Py_TPFLAGS_VALID_VERSION_TAG)) - return 1; - if (!PyType_HasFeature(type, Py_TPFLAGS_HAVE_VERSION_TAG)) - return 0; - if (!PyType_HasFeature(type, Py_TPFLAGS_READY)) - return 0; - - type->tp_version_tag = next_version_tag++; - /* for stress-testing: next_version_tag &= 0xFF; */ - - if (type->tp_version_tag == 0) { - /* wrap-around or just starting Python - clear the whole - cache by filling names with references to Py_None. - Values are also set to NULL for added protection, as they - are borrowed reference */ - for (i = 0; i < (1 << MCACHE_SIZE_EXP); i++) { - method_cache[i].value = NULL; - Py_XDECREF(method_cache[i].name); - method_cache[i].name = Py_None; - Py_INCREF(Py_None); - } - /* mark all version tags as invalid */ - PyType_Modified(&PyBaseObject_Type); - return 1; - } - bases = type->tp_bases; - n = PyTuple_GET_SIZE(bases); - for (i = 0; i < n; i++) { - PyObject *b = PyTuple_GET_ITEM(bases, i); - assert(PyType_Check(b)); - if (!assign_version_tag((PyTypeObject *)b)) - return 0; - } - type->tp_flags |= Py_TPFLAGS_VALID_VERSION_TAG; - return 1; + /* Ensure that the tp_version_tag is valid and set + Py_TPFLAGS_VALID_VERSION_TAG. To respect the invariant, this + must first be done on all super classes. Return 0 if this + cannot be done, 1 if Py_TPFLAGS_VALID_VERSION_TAG. + */ + Py_ssize_t i, n; + PyObject *bases; + + if (PyType_HasFeature(type, Py_TPFLAGS_VALID_VERSION_TAG)) + return 1; + if (!PyType_HasFeature(type, Py_TPFLAGS_HAVE_VERSION_TAG)) + return 0; + if (!PyType_HasFeature(type, Py_TPFLAGS_READY)) + return 0; + + type->tp_version_tag = next_version_tag++; + /* for stress-testing: next_version_tag &= 0xFF; */ + + if (type->tp_version_tag == 0) { + /* wrap-around or just starting Python - clear the whole + cache by filling names with references to Py_None. + Values are also set to NULL for added protection, as they + are borrowed reference */ + for (i = 0; i < (1 << MCACHE_SIZE_EXP); i++) { + method_cache[i].value = NULL; + Py_XDECREF(method_cache[i].name); + method_cache[i].name = Py_None; + Py_INCREF(Py_None); + } + /* mark all version tags as invalid */ + PyType_Modified(&PyBaseObject_Type); + return 1; + } + bases = type->tp_bases; + n = PyTuple_GET_SIZE(bases); + for (i = 0; i < n; i++) { + PyObject *b = PyTuple_GET_ITEM(bases, i); + assert(PyType_Check(b)); + if (!assign_version_tag((PyTypeObject *)b)) + return 0; + } + type->tp_flags |= Py_TPFLAGS_VALID_VERSION_TAG; + return 1; } static PyMemberDef type_members[] = { - {"__basicsize__", T_INT, offsetof(PyTypeObject,tp_basicsize),READONLY}, - {"__itemsize__", T_INT, offsetof(PyTypeObject, tp_itemsize), READONLY}, - {"__flags__", T_LONG, offsetof(PyTypeObject, tp_flags), READONLY}, - {"__weakrefoffset__", T_LONG, - offsetof(PyTypeObject, tp_weaklistoffset), READONLY}, - {"__base__", T_OBJECT, offsetof(PyTypeObject, tp_base), READONLY}, - {"__dictoffset__", T_LONG, - offsetof(PyTypeObject, tp_dictoffset), READONLY}, - {"__mro__", T_OBJECT, offsetof(PyTypeObject, tp_mro), READONLY}, - {0} + {"__basicsize__", T_INT, offsetof(PyTypeObject,tp_basicsize),READONLY}, + {"__itemsize__", T_INT, offsetof(PyTypeObject, tp_itemsize), READONLY}, + {"__flags__", T_LONG, offsetof(PyTypeObject, tp_flags), READONLY}, + {"__weakrefoffset__", T_LONG, + offsetof(PyTypeObject, tp_weaklistoffset), READONLY}, + {"__base__", T_OBJECT, offsetof(PyTypeObject, tp_base), READONLY}, + {"__dictoffset__", T_LONG, + offsetof(PyTypeObject, tp_dictoffset), READONLY}, + {"__mro__", T_OBJECT, offsetof(PyTypeObject, tp_mro), READONLY}, + {0} }; static PyObject * type_name(PyTypeObject *type, void *context) { - const char *s; + const char *s; - if (type->tp_flags & Py_TPFLAGS_HEAPTYPE) { - PyHeapTypeObject* et = (PyHeapTypeObject*)type; + if (type->tp_flags & Py_TPFLAGS_HEAPTYPE) { + PyHeapTypeObject* et = (PyHeapTypeObject*)type; - Py_INCREF(et->ht_name); - return et->ht_name; - } - else { - s = strrchr(type->tp_name, '.'); - if (s == NULL) - s = type->tp_name; - else - s++; - return PyUnicode_FromString(s); - } + Py_INCREF(et->ht_name); + return et->ht_name; + } + else { + s = strrchr(type->tp_name, '.'); + if (s == NULL) + s = type->tp_name; + else + s++; + return PyUnicode_FromString(s); + } } static int type_set_name(PyTypeObject *type, PyObject *value, void *context) { - PyHeapTypeObject* et; - char *tp_name; - PyObject *tmp; - - if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE)) { - PyErr_Format(PyExc_TypeError, - "can't set %s.__name__", type->tp_name); - return -1; - } - if (!value) { - PyErr_Format(PyExc_TypeError, - "can't delete %s.__name__", type->tp_name); - return -1; - } - if (!PyUnicode_Check(value)) { - PyErr_Format(PyExc_TypeError, - "can only assign string to %s.__name__, not '%s'", - type->tp_name, Py_TYPE(value)->tp_name); - return -1; - } - - /* Check absence of null characters */ - tmp = PyUnicode_FromStringAndSize("\0", 1); - if (tmp == NULL) - return -1; - if (PyUnicode_Contains(value, tmp) != 0) { - Py_DECREF(tmp); - PyErr_Format(PyExc_ValueError, - "__name__ must not contain null bytes"); - return -1; - } - Py_DECREF(tmp); - - tp_name = _PyUnicode_AsString(value); - if (tp_name == NULL) - return -1; - - et = (PyHeapTypeObject*)type; + PyHeapTypeObject* et; + char *tp_name; + PyObject *tmp; + + if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE)) { + PyErr_Format(PyExc_TypeError, + "can't set %s.__name__", type->tp_name); + return -1; + } + if (!value) { + PyErr_Format(PyExc_TypeError, + "can't delete %s.__name__", type->tp_name); + return -1; + } + if (!PyUnicode_Check(value)) { + PyErr_Format(PyExc_TypeError, + "can only assign string to %s.__name__, not '%s'", + type->tp_name, Py_TYPE(value)->tp_name); + return -1; + } + + /* Check absence of null characters */ + tmp = PyUnicode_FromStringAndSize("\0", 1); + if (tmp == NULL) + return -1; + if (PyUnicode_Contains(value, tmp) != 0) { + Py_DECREF(tmp); + PyErr_Format(PyExc_ValueError, + "__name__ must not contain null bytes"); + return -1; + } + Py_DECREF(tmp); + + tp_name = _PyUnicode_AsString(value); + if (tp_name == NULL) + return -1; + + et = (PyHeapTypeObject*)type; - Py_INCREF(value); + Py_INCREF(value); - Py_DECREF(et->ht_name); - et->ht_name = value; + Py_DECREF(et->ht_name); + et->ht_name = value; - type->tp_name = tp_name; + type->tp_name = tp_name; - return 0; + return 0; } static PyObject * type_module(PyTypeObject *type, void *context) { - PyObject *mod; - char *s; + PyObject *mod; + char *s; - if (type->tp_flags & Py_TPFLAGS_HEAPTYPE) { - mod = PyDict_GetItemString(type->tp_dict, "__module__"); - if (!mod) { - PyErr_Format(PyExc_AttributeError, "__module__"); - return 0; - } - Py_XINCREF(mod); - return mod; - } - else { - s = strrchr(type->tp_name, '.'); - if (s != NULL) - return PyUnicode_FromStringAndSize( - type->tp_name, (Py_ssize_t)(s - type->tp_name)); - return PyUnicode_FromString("builtins"); - } + if (type->tp_flags & Py_TPFLAGS_HEAPTYPE) { + mod = PyDict_GetItemString(type->tp_dict, "__module__"); + if (!mod) { + PyErr_Format(PyExc_AttributeError, "__module__"); + return 0; + } + Py_XINCREF(mod); + return mod; + } + else { + s = strrchr(type->tp_name, '.'); + if (s != NULL) + return PyUnicode_FromStringAndSize( + type->tp_name, (Py_ssize_t)(s - type->tp_name)); + return PyUnicode_FromString("builtins"); + } } static int type_set_module(PyTypeObject *type, PyObject *value, void *context) { - if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE)) { - PyErr_Format(PyExc_TypeError, - "can't set %s.__module__", type->tp_name); - return -1; - } - if (!value) { - PyErr_Format(PyExc_TypeError, - "can't delete %s.__module__", type->tp_name); - return -1; - } + if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE)) { + PyErr_Format(PyExc_TypeError, + "can't set %s.__module__", type->tp_name); + return -1; + } + if (!value) { + PyErr_Format(PyExc_TypeError, + "can't delete %s.__module__", type->tp_name); + return -1; + } - PyType_Modified(type); + PyType_Modified(type); - return PyDict_SetItemString(type->tp_dict, "__module__", value); + return PyDict_SetItemString(type->tp_dict, "__module__", value); } static PyObject * type_abstractmethods(PyTypeObject *type, void *context) { - PyObject *mod = PyDict_GetItemString(type->tp_dict, - "__abstractmethods__"); - if (!mod) { - PyErr_Format(PyExc_AttributeError, "__abstractmethods__"); - return NULL; - } - Py_XINCREF(mod); - return mod; + PyObject *mod = PyDict_GetItemString(type->tp_dict, + "__abstractmethods__"); + if (!mod) { + PyErr_Format(PyExc_AttributeError, "__abstractmethods__"); + return NULL; + } + Py_XINCREF(mod); + return mod; } static int type_set_abstractmethods(PyTypeObject *type, PyObject *value, void *context) { - /* __abstractmethods__ should only be set once on a type, in - abc.ABCMeta.__new__, so this function doesn't do anything - special to update subclasses. - */ - int res = PyDict_SetItemString(type->tp_dict, - "__abstractmethods__", value); - if (res == 0) { - PyType_Modified(type); - if (value && PyObject_IsTrue(value)) { - type->tp_flags |= Py_TPFLAGS_IS_ABSTRACT; - } - else { - type->tp_flags &= ~Py_TPFLAGS_IS_ABSTRACT; - } - } - return res; + /* __abstractmethods__ should only be set once on a type, in + abc.ABCMeta.__new__, so this function doesn't do anything + special to update subclasses. + */ + int res = PyDict_SetItemString(type->tp_dict, + "__abstractmethods__", value); + if (res == 0) { + PyType_Modified(type); + if (value && PyObject_IsTrue(value)) { + type->tp_flags |= Py_TPFLAGS_IS_ABSTRACT; + } + else { + type->tp_flags &= ~Py_TPFLAGS_IS_ABSTRACT; + } + } + return res; } static PyObject * type_get_bases(PyTypeObject *type, void *context) { - Py_INCREF(type->tp_bases); - return type->tp_bases; + Py_INCREF(type->tp_bases); + return type->tp_bases; } static PyTypeObject *best_base(PyObject *); @@ -367,357 +367,357 @@ typedef int (*update_callback)(PyTypeObject *, void *); static int update_subclasses(PyTypeObject *type, PyObject *name, - update_callback callback, void *data); + update_callback callback, void *data); static int recurse_down_subclasses(PyTypeObject *type, PyObject *name, - update_callback callback, void *data); + update_callback callback, void *data); static int mro_subclasses(PyTypeObject *type, PyObject* temp) { - PyTypeObject *subclass; - PyObject *ref, *subclasses, *old_mro; - Py_ssize_t i, n; - - subclasses = type->tp_subclasses; - if (subclasses == NULL) - return 0; - assert(PyList_Check(subclasses)); - n = PyList_GET_SIZE(subclasses); - for (i = 0; i < n; i++) { - ref = PyList_GET_ITEM(subclasses, i); - assert(PyWeakref_CheckRef(ref)); - subclass = (PyTypeObject *)PyWeakref_GET_OBJECT(ref); - assert(subclass != NULL); - if ((PyObject *)subclass == Py_None) - continue; - assert(PyType_Check(subclass)); - old_mro = subclass->tp_mro; - if (mro_internal(subclass) < 0) { - subclass->tp_mro = old_mro; - return -1; - } - else { - PyObject* tuple; - tuple = PyTuple_Pack(2, subclass, old_mro); - Py_DECREF(old_mro); - if (!tuple) - return -1; - if (PyList_Append(temp, tuple) < 0) - return -1; - Py_DECREF(tuple); - } - if (mro_subclasses(subclass, temp) < 0) - return -1; - } - return 0; + PyTypeObject *subclass; + PyObject *ref, *subclasses, *old_mro; + Py_ssize_t i, n; + + subclasses = type->tp_subclasses; + if (subclasses == NULL) + return 0; + assert(PyList_Check(subclasses)); + n = PyList_GET_SIZE(subclasses); + for (i = 0; i < n; i++) { + ref = PyList_GET_ITEM(subclasses, i); + assert(PyWeakref_CheckRef(ref)); + subclass = (PyTypeObject *)PyWeakref_GET_OBJECT(ref); + assert(subclass != NULL); + if ((PyObject *)subclass == Py_None) + continue; + assert(PyType_Check(subclass)); + old_mro = subclass->tp_mro; + if (mro_internal(subclass) < 0) { + subclass->tp_mro = old_mro; + return -1; + } + else { + PyObject* tuple; + tuple = PyTuple_Pack(2, subclass, old_mro); + Py_DECREF(old_mro); + if (!tuple) + return -1; + if (PyList_Append(temp, tuple) < 0) + return -1; + Py_DECREF(tuple); + } + if (mro_subclasses(subclass, temp) < 0) + return -1; + } + return 0; } static int type_set_bases(PyTypeObject *type, PyObject *value, void *context) { - Py_ssize_t i; - int r = 0; - PyObject *ob, *temp; - PyTypeObject *new_base, *old_base; - PyObject *old_bases, *old_mro; - - if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE)) { - PyErr_Format(PyExc_TypeError, - "can't set %s.__bases__", type->tp_name); - return -1; - } - if (!value) { - PyErr_Format(PyExc_TypeError, - "can't delete %s.__bases__", type->tp_name); - return -1; - } - if (!PyTuple_Check(value)) { - PyErr_Format(PyExc_TypeError, - "can only assign tuple to %s.__bases__, not %s", - type->tp_name, Py_TYPE(value)->tp_name); - return -1; - } - if (PyTuple_GET_SIZE(value) == 0) { - PyErr_Format(PyExc_TypeError, - "can only assign non-empty tuple to %s.__bases__, not ()", - type->tp_name); - return -1; - } - for (i = 0; i < PyTuple_GET_SIZE(value); i++) { - ob = PyTuple_GET_ITEM(value, i); - if (!PyType_Check(ob)) { - PyErr_Format( - PyExc_TypeError, - "%s.__bases__ must be tuple of old- or new-style classes, not '%s'", - type->tp_name, Py_TYPE(ob)->tp_name); - return -1; - } - if (PyType_Check(ob)) { - if (PyType_IsSubtype((PyTypeObject*)ob, type)) { - PyErr_SetString(PyExc_TypeError, - "a __bases__ item causes an inheritance cycle"); - return -1; - } - } - } - - new_base = best_base(value); - - if (!new_base) { - return -1; - } - - if (!compatible_for_assignment(type->tp_base, new_base, "__bases__")) - return -1; - - Py_INCREF(new_base); - Py_INCREF(value); - - old_bases = type->tp_bases; - old_base = type->tp_base; - old_mro = type->tp_mro; - - type->tp_bases = value; - type->tp_base = new_base; - - if (mro_internal(type) < 0) { - goto bail; - } - - temp = PyList_New(0); - if (!temp) - goto bail; - - r = mro_subclasses(type, temp); - - if (r < 0) { - for (i = 0; i < PyList_Size(temp); i++) { - PyTypeObject* cls; - PyObject* mro; - PyArg_UnpackTuple(PyList_GET_ITEM(temp, i), - "", 2, 2, &cls, &mro); - Py_INCREF(mro); - ob = cls->tp_mro; - cls->tp_mro = mro; - Py_DECREF(ob); - } - Py_DECREF(temp); - goto bail; - } - - Py_DECREF(temp); - - /* any base that was in __bases__ but now isn't, we - need to remove |type| from its tp_subclasses. - conversely, any class now in __bases__ that wasn't - needs to have |type| added to its subclasses. */ - - /* for now, sod that: just remove from all old_bases, - add to all new_bases */ - - for (i = PyTuple_GET_SIZE(old_bases) - 1; i >= 0; i--) { - ob = PyTuple_GET_ITEM(old_bases, i); - if (PyType_Check(ob)) { - remove_subclass( - (PyTypeObject*)ob, type); - } - } - - for (i = PyTuple_GET_SIZE(value) - 1; i >= 0; i--) { - ob = PyTuple_GET_ITEM(value, i); - if (PyType_Check(ob)) { - if (add_subclass((PyTypeObject*)ob, type) < 0) - r = -1; - } - } - - update_all_slots(type); - - Py_DECREF(old_bases); - Py_DECREF(old_base); - Py_DECREF(old_mro); + Py_ssize_t i; + int r = 0; + PyObject *ob, *temp; + PyTypeObject *new_base, *old_base; + PyObject *old_bases, *old_mro; + + if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE)) { + PyErr_Format(PyExc_TypeError, + "can't set %s.__bases__", type->tp_name); + return -1; + } + if (!value) { + PyErr_Format(PyExc_TypeError, + "can't delete %s.__bases__", type->tp_name); + return -1; + } + if (!PyTuple_Check(value)) { + PyErr_Format(PyExc_TypeError, + "can only assign tuple to %s.__bases__, not %s", + type->tp_name, Py_TYPE(value)->tp_name); + return -1; + } + if (PyTuple_GET_SIZE(value) == 0) { + PyErr_Format(PyExc_TypeError, + "can only assign non-empty tuple to %s.__bases__, not ()", + type->tp_name); + return -1; + } + for (i = 0; i < PyTuple_GET_SIZE(value); i++) { + ob = PyTuple_GET_ITEM(value, i); + if (!PyType_Check(ob)) { + PyErr_Format( + PyExc_TypeError, + "%s.__bases__ must be tuple of old- or new-style classes, not '%s'", + type->tp_name, Py_TYPE(ob)->tp_name); + return -1; + } + if (PyType_Check(ob)) { + if (PyType_IsSubtype((PyTypeObject*)ob, type)) { + PyErr_SetString(PyExc_TypeError, + "a __bases__ item causes an inheritance cycle"); + return -1; + } + } + } + + new_base = best_base(value); + + if (!new_base) { + return -1; + } + + if (!compatible_for_assignment(type->tp_base, new_base, "__bases__")) + return -1; + + Py_INCREF(new_base); + Py_INCREF(value); + + old_bases = type->tp_bases; + old_base = type->tp_base; + old_mro = type->tp_mro; + + type->tp_bases = value; + type->tp_base = new_base; + + if (mro_internal(type) < 0) { + goto bail; + } + + temp = PyList_New(0); + if (!temp) + goto bail; + + r = mro_subclasses(type, temp); + + if (r < 0) { + for (i = 0; i < PyList_Size(temp); i++) { + PyTypeObject* cls; + PyObject* mro; + PyArg_UnpackTuple(PyList_GET_ITEM(temp, i), + "", 2, 2, &cls, &mro); + Py_INCREF(mro); + ob = cls->tp_mro; + cls->tp_mro = mro; + Py_DECREF(ob); + } + Py_DECREF(temp); + goto bail; + } + + Py_DECREF(temp); + + /* any base that was in __bases__ but now isn't, we + need to remove |type| from its tp_subclasses. + conversely, any class now in __bases__ that wasn't + needs to have |type| added to its subclasses. */ + + /* for now, sod that: just remove from all old_bases, + add to all new_bases */ + + for (i = PyTuple_GET_SIZE(old_bases) - 1; i >= 0; i--) { + ob = PyTuple_GET_ITEM(old_bases, i); + if (PyType_Check(ob)) { + remove_subclass( + (PyTypeObject*)ob, type); + } + } + + for (i = PyTuple_GET_SIZE(value) - 1; i >= 0; i--) { + ob = PyTuple_GET_ITEM(value, i); + if (PyType_Check(ob)) { + if (add_subclass((PyTypeObject*)ob, type) < 0) + r = -1; + } + } + + update_all_slots(type); + + Py_DECREF(old_bases); + Py_DECREF(old_base); + Py_DECREF(old_mro); - return r; + return r; bail: - Py_DECREF(type->tp_bases); - Py_DECREF(type->tp_base); - if (type->tp_mro != old_mro) { - Py_DECREF(type->tp_mro); - } - - type->tp_bases = old_bases; - type->tp_base = old_base; - type->tp_mro = old_mro; + Py_DECREF(type->tp_bases); + Py_DECREF(type->tp_base); + if (type->tp_mro != old_mro) { + Py_DECREF(type->tp_mro); + } + + type->tp_bases = old_bases; + type->tp_base = old_base; + type->tp_mro = old_mro; - return -1; + return -1; } static PyObject * type_dict(PyTypeObject *type, void *context) { - if (type->tp_dict == NULL) { - Py_INCREF(Py_None); - return Py_None; - } - return PyDictProxy_New(type->tp_dict); + if (type->tp_dict == NULL) { + Py_INCREF(Py_None); + return Py_None; + } + return PyDictProxy_New(type->tp_dict); } static PyObject * type_get_doc(PyTypeObject *type, void *context) { - PyObject *result; - if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE) && type->tp_doc != NULL) - return PyUnicode_FromString(type->tp_doc); - result = PyDict_GetItemString(type->tp_dict, "__doc__"); - if (result == NULL) { - result = Py_None; - Py_INCREF(result); - } - else if (Py_TYPE(result)->tp_descr_get) { - result = Py_TYPE(result)->tp_descr_get(result, NULL, - (PyObject *)type); - } - else { - Py_INCREF(result); - } - return result; + PyObject *result; + if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE) && type->tp_doc != NULL) + return PyUnicode_FromString(type->tp_doc); + result = PyDict_GetItemString(type->tp_dict, "__doc__"); + if (result == NULL) { + result = Py_None; + Py_INCREF(result); + } + else if (Py_TYPE(result)->tp_descr_get) { + result = Py_TYPE(result)->tp_descr_get(result, NULL, + (PyObject *)type); + } + else { + Py_INCREF(result); + } + return result; } static PyObject * type___instancecheck__(PyObject *type, PyObject *inst) { - switch (_PyObject_RealIsInstance(inst, type)) { - case -1: - return NULL; - case 0: - Py_RETURN_FALSE; - default: - Py_RETURN_TRUE; - } + switch (_PyObject_RealIsInstance(inst, type)) { + case -1: + return NULL; + case 0: + Py_RETURN_FALSE; + default: + Py_RETURN_TRUE; + } } static PyObject * type___subclasscheck__(PyObject *type, PyObject *inst) { - switch (_PyObject_RealIsSubclass(inst, type)) { - case -1: - return NULL; - case 0: - Py_RETURN_FALSE; - default: - Py_RETURN_TRUE; - } + switch (_PyObject_RealIsSubclass(inst, type)) { + case -1: + return NULL; + case 0: + Py_RETURN_FALSE; + default: + Py_RETURN_TRUE; + } } static PyGetSetDef type_getsets[] = { - {"__name__", (getter)type_name, (setter)type_set_name, NULL}, - {"__bases__", (getter)type_get_bases, (setter)type_set_bases, NULL}, - {"__module__", (getter)type_module, (setter)type_set_module, NULL}, - {"__abstractmethods__", (getter)type_abstractmethods, - (setter)type_set_abstractmethods, NULL}, - {"__dict__", (getter)type_dict, NULL, NULL}, - {"__doc__", (getter)type_get_doc, NULL, NULL}, - {0} + {"__name__", (getter)type_name, (setter)type_set_name, NULL}, + {"__bases__", (getter)type_get_bases, (setter)type_set_bases, NULL}, + {"__module__", (getter)type_module, (setter)type_set_module, NULL}, + {"__abstractmethods__", (getter)type_abstractmethods, + (setter)type_set_abstractmethods, NULL}, + {"__dict__", (getter)type_dict, NULL, NULL}, + {"__doc__", (getter)type_get_doc, NULL, NULL}, + {0} }; static PyObject * type_repr(PyTypeObject *type) { - PyObject *mod, *name, *rtn; + PyObject *mod, *name, *rtn; - mod = type_module(type, NULL); - if (mod == NULL) - PyErr_Clear(); - else if (!PyUnicode_Check(mod)) { - Py_DECREF(mod); - mod = NULL; - } - name = type_name(type, NULL); - if (name == NULL) - return NULL; - - if (mod != NULL && PyUnicode_CompareWithASCIIString(mod, "builtins")) - rtn = PyUnicode_FromFormat("", mod, name); - else - rtn = PyUnicode_FromFormat("", type->tp_name); - - Py_XDECREF(mod); - Py_DECREF(name); - return rtn; + mod = type_module(type, NULL); + if (mod == NULL) + PyErr_Clear(); + else if (!PyUnicode_Check(mod)) { + Py_DECREF(mod); + mod = NULL; + } + name = type_name(type, NULL); + if (name == NULL) + return NULL; + + if (mod != NULL && PyUnicode_CompareWithASCIIString(mod, "builtins")) + rtn = PyUnicode_FromFormat("", mod, name); + else + rtn = PyUnicode_FromFormat("", type->tp_name); + + Py_XDECREF(mod); + Py_DECREF(name); + return rtn; } static PyObject * type_call(PyTypeObject *type, PyObject *args, PyObject *kwds) { - PyObject *obj; + PyObject *obj; - if (type->tp_new == NULL) { - PyErr_Format(PyExc_TypeError, - "cannot create '%.100s' instances", - type->tp_name); - return NULL; - } - - obj = type->tp_new(type, args, kwds); - if (obj != NULL) { - /* Ugly exception: when the call was type(something), - don't call tp_init on the result. */ - if (type == &PyType_Type && - PyTuple_Check(args) && PyTuple_GET_SIZE(args) == 1 && - (kwds == NULL || - (PyDict_Check(kwds) && PyDict_Size(kwds) == 0))) - return obj; - /* If the returned object is not an instance of type, - it won't be initialized. */ - if (!PyType_IsSubtype(Py_TYPE(obj), type)) - return obj; - type = Py_TYPE(obj); - if (type->tp_init != NULL && - type->tp_init(obj, args, kwds) < 0) { - Py_DECREF(obj); - obj = NULL; - } - } - return obj; + if (type->tp_new == NULL) { + PyErr_Format(PyExc_TypeError, + "cannot create '%.100s' instances", + type->tp_name); + return NULL; + } + + obj = type->tp_new(type, args, kwds); + if (obj != NULL) { + /* Ugly exception: when the call was type(something), + don't call tp_init on the result. */ + if (type == &PyType_Type && + PyTuple_Check(args) && PyTuple_GET_SIZE(args) == 1 && + (kwds == NULL || + (PyDict_Check(kwds) && PyDict_Size(kwds) == 0))) + return obj; + /* If the returned object is not an instance of type, + it won't be initialized. */ + if (!PyType_IsSubtype(Py_TYPE(obj), type)) + return obj; + type = Py_TYPE(obj); + if (type->tp_init != NULL && + type->tp_init(obj, args, kwds) < 0) { + Py_DECREF(obj); + obj = NULL; + } + } + return obj; } PyObject * PyType_GenericAlloc(PyTypeObject *type, Py_ssize_t nitems) { - PyObject *obj; - const size_t size = _PyObject_VAR_SIZE(type, nitems+1); - /* note that we need to add one, for the sentinel */ - - if (PyType_IS_GC(type)) - obj = _PyObject_GC_Malloc(size); - else - obj = (PyObject *)PyObject_MALLOC(size); - - if (obj == NULL) - return PyErr_NoMemory(); - - memset(obj, '\0', size); - - if (type->tp_flags & Py_TPFLAGS_HEAPTYPE) - Py_INCREF(type); - - if (type->tp_itemsize == 0) - PyObject_INIT(obj, type); - else - (void) PyObject_INIT_VAR((PyVarObject *)obj, type, nitems); - - if (PyType_IS_GC(type)) - _PyObject_GC_TRACK(obj); - return obj; + PyObject *obj; + const size_t size = _PyObject_VAR_SIZE(type, nitems+1); + /* note that we need to add one, for the sentinel */ + + if (PyType_IS_GC(type)) + obj = _PyObject_GC_Malloc(size); + else + obj = (PyObject *)PyObject_MALLOC(size); + + if (obj == NULL) + return PyErr_NoMemory(); + + memset(obj, '\0', size); + + if (type->tp_flags & Py_TPFLAGS_HEAPTYPE) + Py_INCREF(type); + + if (type->tp_itemsize == 0) + PyObject_INIT(obj, type); + else + (void) PyObject_INIT_VAR((PyVarObject *)obj, type, nitems); + + if (PyType_IS_GC(type)) + _PyObject_GC_TRACK(obj); + return obj; } PyObject * PyType_GenericNew(PyTypeObject *type, PyObject *args, PyObject *kwds) { - return type->tp_alloc(type, 0); + return type->tp_alloc(type, 0); } /* Helpers for subtyping */ @@ -725,341 +725,341 @@ static int traverse_slots(PyTypeObject *type, PyObject *self, visitproc visit, void *arg) { - Py_ssize_t i, n; - PyMemberDef *mp; + Py_ssize_t i, n; + PyMemberDef *mp; - n = Py_SIZE(type); - mp = PyHeapType_GET_MEMBERS((PyHeapTypeObject *)type); - for (i = 0; i < n; i++, mp++) { - if (mp->type == T_OBJECT_EX) { - char *addr = (char *)self + mp->offset; - PyObject *obj = *(PyObject **)addr; - if (obj != NULL) { - int err = visit(obj, arg); - if (err) - return err; - } - } - } - return 0; + n = Py_SIZE(type); + mp = PyHeapType_GET_MEMBERS((PyHeapTypeObject *)type); + for (i = 0; i < n; i++, mp++) { + if (mp->type == T_OBJECT_EX) { + char *addr = (char *)self + mp->offset; + PyObject *obj = *(PyObject **)addr; + if (obj != NULL) { + int err = visit(obj, arg); + if (err) + return err; + } + } + } + return 0; } static int subtype_traverse(PyObject *self, visitproc visit, void *arg) { - PyTypeObject *type, *base; - traverseproc basetraverse; + PyTypeObject *type, *base; + traverseproc basetraverse; - /* Find the nearest base with a different tp_traverse, - and traverse slots while we're at it */ - type = Py_TYPE(self); - base = type; - while ((basetraverse = base->tp_traverse) == subtype_traverse) { - if (Py_SIZE(base)) { - int err = traverse_slots(base, self, visit, arg); - if (err) - return err; - } - base = base->tp_base; - assert(base); - } - - if (type->tp_dictoffset != base->tp_dictoffset) { - PyObject **dictptr = _PyObject_GetDictPtr(self); - if (dictptr && *dictptr) - Py_VISIT(*dictptr); - } - - if (type->tp_flags & Py_TPFLAGS_HEAPTYPE) - /* For a heaptype, the instances count as references - to the type. Traverse the type so the collector - can find cycles involving this link. */ - Py_VISIT(type); - - if (basetraverse) - return basetraverse(self, visit, arg); - return 0; + /* Find the nearest base with a different tp_traverse, + and traverse slots while we're at it */ + type = Py_TYPE(self); + base = type; + while ((basetraverse = base->tp_traverse) == subtype_traverse) { + if (Py_SIZE(base)) { + int err = traverse_slots(base, self, visit, arg); + if (err) + return err; + } + base = base->tp_base; + assert(base); + } + + if (type->tp_dictoffset != base->tp_dictoffset) { + PyObject **dictptr = _PyObject_GetDictPtr(self); + if (dictptr && *dictptr) + Py_VISIT(*dictptr); + } + + if (type->tp_flags & Py_TPFLAGS_HEAPTYPE) + /* For a heaptype, the instances count as references + to the type. Traverse the type so the collector + can find cycles involving this link. */ + Py_VISIT(type); + + if (basetraverse) + return basetraverse(self, visit, arg); + return 0; } static void clear_slots(PyTypeObject *type, PyObject *self) { - Py_ssize_t i, n; - PyMemberDef *mp; + Py_ssize_t i, n; + PyMemberDef *mp; - n = Py_SIZE(type); - mp = PyHeapType_GET_MEMBERS((PyHeapTypeObject *)type); - for (i = 0; i < n; i++, mp++) { - if (mp->type == T_OBJECT_EX && !(mp->flags & READONLY)) { - char *addr = (char *)self + mp->offset; - PyObject *obj = *(PyObject **)addr; - if (obj != NULL) { - *(PyObject **)addr = NULL; - Py_DECREF(obj); - } - } - } + n = Py_SIZE(type); + mp = PyHeapType_GET_MEMBERS((PyHeapTypeObject *)type); + for (i = 0; i < n; i++, mp++) { + if (mp->type == T_OBJECT_EX && !(mp->flags & READONLY)) { + char *addr = (char *)self + mp->offset; + PyObject *obj = *(PyObject **)addr; + if (obj != NULL) { + *(PyObject **)addr = NULL; + Py_DECREF(obj); + } + } + } } static int subtype_clear(PyObject *self) { - PyTypeObject *type, *base; - inquiry baseclear; + PyTypeObject *type, *base; + inquiry baseclear; - /* Find the nearest base with a different tp_clear - and clear slots while we're at it */ - type = Py_TYPE(self); - base = type; - while ((baseclear = base->tp_clear) == subtype_clear) { - if (Py_SIZE(base)) - clear_slots(base, self); - base = base->tp_base; - assert(base); - } - - /* There's no need to clear the instance dict (if any); - the collector will call its tp_clear handler. */ - - if (baseclear) - return baseclear(self); - return 0; + /* Find the nearest base with a different tp_clear + and clear slots while we're at it */ + type = Py_TYPE(self); + base = type; + while ((baseclear = base->tp_clear) == subtype_clear) { + if (Py_SIZE(base)) + clear_slots(base, self); + base = base->tp_base; + assert(base); + } + + /* There's no need to clear the instance dict (if any); + the collector will call its tp_clear handler. */ + + if (baseclear) + return baseclear(self); + return 0; } static void subtype_dealloc(PyObject *self) { - PyTypeObject *type, *base; - destructor basedealloc; + PyTypeObject *type, *base; + destructor basedealloc; + + /* Extract the type; we expect it to be a heap type */ + type = Py_TYPE(self); + assert(type->tp_flags & Py_TPFLAGS_HEAPTYPE); + + /* Test whether the type has GC exactly once */ + + if (!PyType_IS_GC(type)) { + /* It's really rare to find a dynamic type that doesn't have + GC; it can only happen when deriving from 'object' and not + adding any slots or instance variables. This allows + certain simplifications: there's no need to call + clear_slots(), or DECREF the dict, or clear weakrefs. */ + + /* Maybe call finalizer; exit early if resurrected */ + if (type->tp_del) { + type->tp_del(self); + if (self->ob_refcnt > 0) + return; + } + + /* Find the nearest base with a different tp_dealloc */ + base = type; + while ((basedealloc = base->tp_dealloc) == subtype_dealloc) { + assert(Py_SIZE(base) == 0); + base = base->tp_base; + assert(base); + } + + /* Extract the type again; tp_del may have changed it */ + type = Py_TYPE(self); + + /* Call the base tp_dealloc() */ + assert(basedealloc); + basedealloc(self); + + /* Can't reference self beyond this point */ + Py_DECREF(type); + + /* Done */ + return; + } + + /* We get here only if the type has GC */ + + /* UnTrack and re-Track around the trashcan macro, alas */ + /* See explanation at end of function for full disclosure */ + PyObject_GC_UnTrack(self); + ++_PyTrash_delete_nesting; + Py_TRASHCAN_SAFE_BEGIN(self); + --_PyTrash_delete_nesting; + /* DO NOT restore GC tracking at this point. weakref callbacks + * (if any, and whether directly here or indirectly in something we + * call) may trigger GC, and if self is tracked at that point, it + * will look like trash to GC and GC will try to delete self again. + */ + + /* Find the nearest base with a different tp_dealloc */ + base = type; + while ((basedealloc = base->tp_dealloc) == subtype_dealloc) { + base = base->tp_base; + assert(base); + } + + /* If we added a weaklist, we clear it. Do this *before* calling + the finalizer (__del__), clearing slots, or clearing the instance + dict. */ + + if (type->tp_weaklistoffset && !base->tp_weaklistoffset) + PyObject_ClearWeakRefs(self); + + /* Maybe call finalizer; exit early if resurrected */ + if (type->tp_del) { + _PyObject_GC_TRACK(self); + type->tp_del(self); + if (self->ob_refcnt > 0) + goto endlabel; /* resurrected */ + else + _PyObject_GC_UNTRACK(self); + /* New weakrefs could be created during the finalizer call. + If this occurs, clear them out without calling their + finalizers since they might rely on part of the object + being finalized that has already been destroyed. */ + if (type->tp_weaklistoffset && !base->tp_weaklistoffset) { + /* Modeled after GET_WEAKREFS_LISTPTR() */ + PyWeakReference **list = (PyWeakReference **) \ + PyObject_GET_WEAKREFS_LISTPTR(self); + while (*list) + _PyWeakref_ClearRef(*list); + } + } - /* Extract the type; we expect it to be a heap type */ - type = Py_TYPE(self); - assert(type->tp_flags & Py_TPFLAGS_HEAPTYPE); - - /* Test whether the type has GC exactly once */ - - if (!PyType_IS_GC(type)) { - /* It's really rare to find a dynamic type that doesn't have - GC; it can only happen when deriving from 'object' and not - adding any slots or instance variables. This allows - certain simplifications: there's no need to call - clear_slots(), or DECREF the dict, or clear weakrefs. */ - - /* Maybe call finalizer; exit early if resurrected */ - if (type->tp_del) { - type->tp_del(self); - if (self->ob_refcnt > 0) - return; - } - - /* Find the nearest base with a different tp_dealloc */ - base = type; - while ((basedealloc = base->tp_dealloc) == subtype_dealloc) { - assert(Py_SIZE(base) == 0); - base = base->tp_base; - assert(base); - } - - /* Extract the type again; tp_del may have changed it */ - type = Py_TYPE(self); - - /* Call the base tp_dealloc() */ - assert(basedealloc); - basedealloc(self); - - /* Can't reference self beyond this point */ - Py_DECREF(type); - - /* Done */ - return; - } - - /* We get here only if the type has GC */ - - /* UnTrack and re-Track around the trashcan macro, alas */ - /* See explanation at end of function for full disclosure */ - PyObject_GC_UnTrack(self); - ++_PyTrash_delete_nesting; - Py_TRASHCAN_SAFE_BEGIN(self); - --_PyTrash_delete_nesting; - /* DO NOT restore GC tracking at this point. weakref callbacks - * (if any, and whether directly here or indirectly in something we - * call) may trigger GC, and if self is tracked at that point, it - * will look like trash to GC and GC will try to delete self again. - */ - - /* Find the nearest base with a different tp_dealloc */ - base = type; - while ((basedealloc = base->tp_dealloc) == subtype_dealloc) { - base = base->tp_base; - assert(base); - } - - /* If we added a weaklist, we clear it. Do this *before* calling - the finalizer (__del__), clearing slots, or clearing the instance - dict. */ - - if (type->tp_weaklistoffset && !base->tp_weaklistoffset) - PyObject_ClearWeakRefs(self); - - /* Maybe call finalizer; exit early if resurrected */ - if (type->tp_del) { - _PyObject_GC_TRACK(self); - type->tp_del(self); - if (self->ob_refcnt > 0) - goto endlabel; /* resurrected */ - else - _PyObject_GC_UNTRACK(self); - /* New weakrefs could be created during the finalizer call. - If this occurs, clear them out without calling their - finalizers since they might rely on part of the object - being finalized that has already been destroyed. */ - if (type->tp_weaklistoffset && !base->tp_weaklistoffset) { - /* Modeled after GET_WEAKREFS_LISTPTR() */ - PyWeakReference **list = (PyWeakReference **) \ - PyObject_GET_WEAKREFS_LISTPTR(self); - while (*list) - _PyWeakref_ClearRef(*list); - } - } - - /* Clear slots up to the nearest base with a different tp_dealloc */ - base = type; - while ((basedealloc = base->tp_dealloc) == subtype_dealloc) { - if (Py_SIZE(base)) - clear_slots(base, self); - base = base->tp_base; - assert(base); - } - - /* If we added a dict, DECREF it */ - if (type->tp_dictoffset && !base->tp_dictoffset) { - PyObject **dictptr = _PyObject_GetDictPtr(self); - if (dictptr != NULL) { - PyObject *dict = *dictptr; - if (dict != NULL) { - Py_DECREF(dict); - *dictptr = NULL; - } - } - } - - /* Extract the type again; tp_del may have changed it */ - type = Py_TYPE(self); - - /* Call the base tp_dealloc(); first retrack self if - * basedealloc knows about gc. - */ - if (PyType_IS_GC(base)) - _PyObject_GC_TRACK(self); - assert(basedealloc); - basedealloc(self); + /* Clear slots up to the nearest base with a different tp_dealloc */ + base = type; + while ((basedealloc = base->tp_dealloc) == subtype_dealloc) { + if (Py_SIZE(base)) + clear_slots(base, self); + base = base->tp_base; + assert(base); + } + + /* If we added a dict, DECREF it */ + if (type->tp_dictoffset && !base->tp_dictoffset) { + PyObject **dictptr = _PyObject_GetDictPtr(self); + if (dictptr != NULL) { + PyObject *dict = *dictptr; + if (dict != NULL) { + Py_DECREF(dict); + *dictptr = NULL; + } + } + } + + /* Extract the type again; tp_del may have changed it */ + type = Py_TYPE(self); + + /* Call the base tp_dealloc(); first retrack self if + * basedealloc knows about gc. + */ + if (PyType_IS_GC(base)) + _PyObject_GC_TRACK(self); + assert(basedealloc); + basedealloc(self); - /* Can't reference self beyond this point */ - Py_DECREF(type); + /* Can't reference self beyond this point */ + Py_DECREF(type); endlabel: - ++_PyTrash_delete_nesting; - Py_TRASHCAN_SAFE_END(self); - --_PyTrash_delete_nesting; + ++_PyTrash_delete_nesting; + Py_TRASHCAN_SAFE_END(self); + --_PyTrash_delete_nesting; - /* Explanation of the weirdness around the trashcan macros: + /* Explanation of the weirdness around the trashcan macros: - Q. What do the trashcan macros do? + Q. What do the trashcan macros do? - A. Read the comment titled "Trashcan mechanism" in object.h. - For one, this explains why there must be a call to GC-untrack - before the trashcan begin macro. Without understanding the - trashcan code, the answers to the following questions don't make - sense. + A. Read the comment titled "Trashcan mechanism" in object.h. + For one, this explains why there must be a call to GC-untrack + before the trashcan begin macro. Without understanding the + trashcan code, the answers to the following questions don't make + sense. - Q. Why do we GC-untrack before the trashcan and then immediately - GC-track again afterward? + Q. Why do we GC-untrack before the trashcan and then immediately + GC-track again afterward? - A. In the case that the base class is GC-aware, the base class - probably GC-untracks the object. If it does that using the - UNTRACK macro, this will crash when the object is already - untracked. Because we don't know what the base class does, the - only safe thing is to make sure the object is tracked when we - call the base class dealloc. But... The trashcan begin macro - requires that the object is *untracked* before it is called. So - the dance becomes: + A. In the case that the base class is GC-aware, the base class + probably GC-untracks the object. If it does that using the + UNTRACK macro, this will crash when the object is already + untracked. Because we don't know what the base class does, the + only safe thing is to make sure the object is tracked when we + call the base class dealloc. But... The trashcan begin macro + requires that the object is *untracked* before it is called. So + the dance becomes: - GC untrack - trashcan begin - GC track + GC untrack + trashcan begin + GC track - Q. Why did the last question say "immediately GC-track again"? - It's nowhere near immediately. + Q. Why did the last question say "immediately GC-track again"? + It's nowhere near immediately. - A. Because the code *used* to re-track immediately. Bad Idea. - self has a refcount of 0, and if gc ever gets its hands on it - (which can happen if any weakref callback gets invoked), it - looks like trash to gc too, and gc also tries to delete self - then. But we're already deleting self. Double dealloction is - a subtle disaster. + A. Because the code *used* to re-track immediately. Bad Idea. + self has a refcount of 0, and if gc ever gets its hands on it + (which can happen if any weakref callback gets invoked), it + looks like trash to gc too, and gc also tries to delete self + then. But we're already deleting self. Double dealloction is + a subtle disaster. - Q. Why the bizarre (net-zero) manipulation of - _PyTrash_delete_nesting around the trashcan macros? + Q. Why the bizarre (net-zero) manipulation of + _PyTrash_delete_nesting around the trashcan macros? - A. Some base classes (e.g. list) also use the trashcan mechanism. - The following scenario used to be possible: + A. Some base classes (e.g. list) also use the trashcan mechanism. + The following scenario used to be possible: - - suppose the trashcan level is one below the trashcan limit + - suppose the trashcan level is one below the trashcan limit - - subtype_dealloc() is called + - subtype_dealloc() is called - - the trashcan limit is not yet reached, so the trashcan level - is incremented and the code between trashcan begin and end is - executed + - the trashcan limit is not yet reached, so the trashcan level + is incremented and the code between trashcan begin and end is + executed - - this destroys much of the object's contents, including its - slots and __dict__ + - this destroys much of the object's contents, including its + slots and __dict__ - - basedealloc() is called; this is really list_dealloc(), or - some other type which also uses the trashcan macros + - basedealloc() is called; this is really list_dealloc(), or + some other type which also uses the trashcan macros - - the trashcan limit is now reached, so the object is put on the - trashcan's to-be-deleted-later list + - the trashcan limit is now reached, so the object is put on the + trashcan's to-be-deleted-later list - - basedealloc() returns + - basedealloc() returns - - subtype_dealloc() decrefs the object's type + - subtype_dealloc() decrefs the object's type - - subtype_dealloc() returns + - subtype_dealloc() returns - - later, the trashcan code starts deleting the objects from its - to-be-deleted-later list + - later, the trashcan code starts deleting the objects from its + to-be-deleted-later list - - subtype_dealloc() is called *AGAIN* for the same object + - subtype_dealloc() is called *AGAIN* for the same object - - at the very least (if the destroyed slots and __dict__ don't - cause problems) the object's type gets decref'ed a second - time, which is *BAD*!!! + - at the very least (if the destroyed slots and __dict__ don't + cause problems) the object's type gets decref'ed a second + time, which is *BAD*!!! - The remedy is to make sure that if the code between trashcan - begin and end in subtype_dealloc() is called, the code between - trashcan begin and end in basedealloc() will also be called. - This is done by decrementing the level after passing into the - trashcan block, and incrementing it just before leaving the - block. + The remedy is to make sure that if the code between trashcan + begin and end in subtype_dealloc() is called, the code between + trashcan begin and end in basedealloc() will also be called. + This is done by decrementing the level after passing into the + trashcan block, and incrementing it just before leaving the + block. - But now it's possible that a chain of objects consisting solely - of objects whose deallocator is subtype_dealloc() will defeat - the trashcan mechanism completely: the decremented level means - that the effective level never reaches the limit. Therefore, we - *increment* the level *before* entering the trashcan block, and - matchingly decrement it after leaving. This means the trashcan - code will trigger a little early, but that's no big deal. + But now it's possible that a chain of objects consisting solely + of objects whose deallocator is subtype_dealloc() will defeat + the trashcan mechanism completely: the decremented level means + that the effective level never reaches the limit. Therefore, we + *increment* the level *before* entering the trashcan block, and + matchingly decrement it after leaving. This means the trashcan + code will trigger a little early, but that's no big deal. - Q. Are there any live examples of code in need of all this - complexity? + Q. Are there any live examples of code in need of all this + complexity? - A. Yes. See SF bug 668433 for code that crashed (when Python was - compiled in debug mode) before the trashcan level manipulations - were added. For more discussion, see SF patches 581742, 575073 - and bug 574207. - */ + A. Yes. See SF bug 668433 for code that crashed (when Python was + compiled in debug mode) before the trashcan level manipulations + were added. For more discussion, see SF patches 581742, 575073 + and bug 574207. + */ } static PyTypeObject *solid_base(PyTypeObject *type); @@ -1069,36 +1069,36 @@ int PyType_IsSubtype(PyTypeObject *a, PyTypeObject *b) { - PyObject *mro; + PyObject *mro; - mro = a->tp_mro; - if (mro != NULL) { - /* Deal with multiple inheritance without recursion - by walking the MRO tuple */ - Py_ssize_t i, n; - assert(PyTuple_Check(mro)); - n = PyTuple_GET_SIZE(mro); - for (i = 0; i < n; i++) { - if (PyTuple_GET_ITEM(mro, i) == (PyObject *)b) - return 1; - } - return 0; - } - else { - /* a is not completely initilized yet; follow tp_base */ - do { - if (a == b) - return 1; - a = a->tp_base; - } while (a != NULL); - return b == &PyBaseObject_Type; - } + mro = a->tp_mro; + if (mro != NULL) { + /* Deal with multiple inheritance without recursion + by walking the MRO tuple */ + Py_ssize_t i, n; + assert(PyTuple_Check(mro)); + n = PyTuple_GET_SIZE(mro); + for (i = 0; i < n; i++) { + if (PyTuple_GET_ITEM(mro, i) == (PyObject *)b) + return 1; + } + return 0; + } + else { + /* a is not completely initilized yet; follow tp_base */ + do { + if (a == b) + return 1; + a = a->tp_base; + } while (a != NULL); + return b == &PyBaseObject_Type; + } } /* Internal routines to do a method lookup in the type without looking in the instance dictionary (so we can't use PyObject_GetAttr) but still binding - it to the instance. The arguments are the object, + it to the instance. The arguments are the object, the method name as a C string, and the address of a static variable used to cache the interned Python string. @@ -1115,75 +1115,75 @@ static PyObject * lookup_maybe(PyObject *self, char *attrstr, PyObject **attrobj) { - PyObject *res; + PyObject *res; - if (*attrobj == NULL) { - *attrobj = PyUnicode_InternFromString(attrstr); - if (*attrobj == NULL) - return NULL; - } - res = _PyType_Lookup(Py_TYPE(self), *attrobj); - if (res != NULL) { - descrgetfunc f; - if ((f = Py_TYPE(res)->tp_descr_get) == NULL) - Py_INCREF(res); - else - res = f(res, self, (PyObject *)(Py_TYPE(self))); - } - return res; + if (*attrobj == NULL) { + *attrobj = PyUnicode_InternFromString(attrstr); + if (*attrobj == NULL) + return NULL; + } + res = _PyType_Lookup(Py_TYPE(self), *attrobj); + if (res != NULL) { + descrgetfunc f; + if ((f = Py_TYPE(res)->tp_descr_get) == NULL) + Py_INCREF(res); + else + res = f(res, self, (PyObject *)(Py_TYPE(self))); + } + return res; } static PyObject * lookup_method(PyObject *self, char *attrstr, PyObject **attrobj) { - PyObject *res = lookup_maybe(self, attrstr, attrobj); - if (res == NULL && !PyErr_Occurred()) - PyErr_SetObject(PyExc_AttributeError, *attrobj); - return res; + PyObject *res = lookup_maybe(self, attrstr, attrobj); + if (res == NULL && !PyErr_Occurred()) + PyErr_SetObject(PyExc_AttributeError, *attrobj); + return res; } PyObject * _PyObject_LookupSpecial(PyObject *self, char *attrstr, PyObject **attrobj) { - return lookup_maybe(self, attrstr, attrobj); + return lookup_maybe(self, attrstr, attrobj); } /* A variation of PyObject_CallMethod that uses lookup_method() - instead of PyObject_GetAttrString(). This uses the same convention + instead of PyObject_GetAttrString(). This uses the same convention as lookup_method to cache the interned name string object. */ static PyObject * call_method(PyObject *o, char *name, PyObject **nameobj, char *format, ...) { - va_list va; - PyObject *args, *func = 0, *retval; - va_start(va, format); - - func = lookup_maybe(o, name, nameobj); - if (func == NULL) { - va_end(va); - if (!PyErr_Occurred()) - PyErr_SetObject(PyExc_AttributeError, *nameobj); - return NULL; - } - - if (format && *format) - args = Py_VaBuildValue(format, va); - else - args = PyTuple_New(0); - - va_end(va); - - if (args == NULL) - return NULL; + va_list va; + PyObject *args, *func = 0, *retval; + va_start(va, format); + + func = lookup_maybe(o, name, nameobj); + if (func == NULL) { + va_end(va); + if (!PyErr_Occurred()) + PyErr_SetObject(PyExc_AttributeError, *nameobj); + return NULL; + } + + if (format && *format) + args = Py_VaBuildValue(format, va); + else + args = PyTuple_New(0); + + va_end(va); + + if (args == NULL) + return NULL; - assert(PyTuple_Check(args)); - retval = PyObject_Call(func, args, NULL); + assert(PyTuple_Check(args)); + retval = PyObject_Call(func, args, NULL); - Py_DECREF(args); - Py_DECREF(func); + Py_DECREF(args); + Py_DECREF(func); - return retval; + return retval; } /* Clone of call_method() that returns NotImplemented when the lookup fails. */ @@ -1191,37 +1191,37 @@ static PyObject * call_maybe(PyObject *o, char *name, PyObject **nameobj, char *format, ...) { - va_list va; - PyObject *args, *func = 0, *retval; - va_start(va, format); - - func = lookup_maybe(o, name, nameobj); - if (func == NULL) { - va_end(va); - if (!PyErr_Occurred()) { - Py_INCREF(Py_NotImplemented); - return Py_NotImplemented; - } - return NULL; - } - - if (format && *format) - args = Py_VaBuildValue(format, va); - else - args = PyTuple_New(0); - - va_end(va); - - if (args == NULL) - return NULL; + va_list va; + PyObject *args, *func = 0, *retval; + va_start(va, format); + + func = lookup_maybe(o, name, nameobj); + if (func == NULL) { + va_end(va); + if (!PyErr_Occurred()) { + Py_INCREF(Py_NotImplemented); + return Py_NotImplemented; + } + return NULL; + } + + if (format && *format) + args = Py_VaBuildValue(format, va); + else + args = PyTuple_New(0); - assert(PyTuple_Check(args)); - retval = PyObject_Call(func, args, NULL); + va_end(va); - Py_DECREF(args); - Py_DECREF(func); + if (args == NULL) + return NULL; - return retval; + assert(PyTuple_Check(args)); + retval = PyObject_Call(func, args, NULL); + + Py_DECREF(args); + Py_DECREF(func); + + return retval; } /* @@ -1254,68 +1254,68 @@ static int tail_contains(PyObject *list, int whence, PyObject *o) { - Py_ssize_t j, size; - size = PyList_GET_SIZE(list); + Py_ssize_t j, size; + size = PyList_GET_SIZE(list); - for (j = whence+1; j < size; j++) { - if (PyList_GET_ITEM(list, j) == o) - return 1; - } - return 0; + for (j = whence+1; j < size; j++) { + if (PyList_GET_ITEM(list, j) == o) + return 1; + } + return 0; } static PyObject * class_name(PyObject *cls) { - PyObject *name = PyObject_GetAttrString(cls, "__name__"); - if (name == NULL) { - PyErr_Clear(); - Py_XDECREF(name); - name = PyObject_Repr(cls); - } - if (name == NULL) - return NULL; - if (!PyUnicode_Check(name)) { - Py_DECREF(name); - return NULL; - } - return name; + PyObject *name = PyObject_GetAttrString(cls, "__name__"); + if (name == NULL) { + PyErr_Clear(); + Py_XDECREF(name); + name = PyObject_Repr(cls); + } + if (name == NULL) + return NULL; + if (!PyUnicode_Check(name)) { + Py_DECREF(name); + return NULL; + } + return name; } static int check_duplicates(PyObject *list) { - Py_ssize_t i, j, n; - /* Let's use a quadratic time algorithm, - assuming that the bases lists is short. - */ - n = PyList_GET_SIZE(list); - for (i = 0; i < n; i++) { - PyObject *o = PyList_GET_ITEM(list, i); - for (j = i + 1; j < n; j++) { - if (PyList_GET_ITEM(list, j) == o) { - o = class_name(o); - if (o != NULL) { - PyErr_Format(PyExc_TypeError, - "duplicate base class %U", - o); - Py_DECREF(o); - } else { - PyErr_SetString(PyExc_TypeError, - "duplicate base class"); - } - return -1; - } - } - } - return 0; + Py_ssize_t i, j, n; + /* Let's use a quadratic time algorithm, + assuming that the bases lists is short. + */ + n = PyList_GET_SIZE(list); + for (i = 0; i < n; i++) { + PyObject *o = PyList_GET_ITEM(list, i); + for (j = i + 1; j < n; j++) { + if (PyList_GET_ITEM(list, j) == o) { + o = class_name(o); + if (o != NULL) { + PyErr_Format(PyExc_TypeError, + "duplicate base class %U", + o); + Py_DECREF(o); + } else { + PyErr_SetString(PyExc_TypeError, + "duplicate base class"); + } + return -1; + } + } + } + return 0; } /* Raise a TypeError for an MRO order disagreement. It's hard to produce a good error message. In the absence of better insight into error reporting, report the classes that were candidates - to be put next into the MRO. There is some conflict between the + to be put next into the MRO. There is some conflict between the order in which they should be put in the MRO, but it's hard to diagnose what constraint can't be satisfied. */ @@ -1323,252 +1323,252 @@ static void set_mro_error(PyObject *to_merge, int *remain) { - Py_ssize_t i, n, off, to_merge_size; - char buf[1000]; - PyObject *k, *v; - PyObject *set = PyDict_New(); - if (!set) return; - - to_merge_size = PyList_GET_SIZE(to_merge); - for (i = 0; i < to_merge_size; i++) { - PyObject *L = PyList_GET_ITEM(to_merge, i); - if (remain[i] < PyList_GET_SIZE(L)) { - PyObject *c = PyList_GET_ITEM(L, remain[i]); - if (PyDict_SetItem(set, c, Py_None) < 0) { - Py_DECREF(set); - return; - } - } - } - n = PyDict_Size(set); + Py_ssize_t i, n, off, to_merge_size; + char buf[1000]; + PyObject *k, *v; + PyObject *set = PyDict_New(); + if (!set) return; + + to_merge_size = PyList_GET_SIZE(to_merge); + for (i = 0; i < to_merge_size; i++) { + PyObject *L = PyList_GET_ITEM(to_merge, i); + if (remain[i] < PyList_GET_SIZE(L)) { + PyObject *c = PyList_GET_ITEM(L, remain[i]); + if (PyDict_SetItem(set, c, Py_None) < 0) { + Py_DECREF(set); + return; + } + } + } + n = PyDict_Size(set); - off = PyOS_snprintf(buf, sizeof(buf), "Cannot create a \ + off = PyOS_snprintf(buf, sizeof(buf), "Cannot create a \ consistent method resolution\norder (MRO) for bases"); - i = 0; - while (PyDict_Next(set, &i, &k, &v) && (size_t)off < sizeof(buf)) { - PyObject *name = class_name(k); - off += PyOS_snprintf(buf + off, sizeof(buf) - off, " %s", - name ? _PyUnicode_AsString(name) : "?"); - Py_XDECREF(name); - if (--n && (size_t)(off+1) < sizeof(buf)) { - buf[off++] = ','; - buf[off] = '\0'; - } - } - PyErr_SetString(PyExc_TypeError, buf); - Py_DECREF(set); + i = 0; + while (PyDict_Next(set, &i, &k, &v) && (size_t)off < sizeof(buf)) { + PyObject *name = class_name(k); + off += PyOS_snprintf(buf + off, sizeof(buf) - off, " %s", + name ? _PyUnicode_AsString(name) : "?"); + Py_XDECREF(name); + if (--n && (size_t)(off+1) < sizeof(buf)) { + buf[off++] = ','; + buf[off] = '\0'; + } + } + PyErr_SetString(PyExc_TypeError, buf); + Py_DECREF(set); } static int pmerge(PyObject *acc, PyObject* to_merge) { - Py_ssize_t i, j, to_merge_size, empty_cnt; - int *remain; - int ok; - - to_merge_size = PyList_GET_SIZE(to_merge); - - /* remain stores an index into each sublist of to_merge. - remain[i] is the index of the next base in to_merge[i] - that is not included in acc. - */ - remain = (int *)PyMem_MALLOC(SIZEOF_INT*to_merge_size); - if (remain == NULL) - return -1; - for (i = 0; i < to_merge_size; i++) - remain[i] = 0; + Py_ssize_t i, j, to_merge_size, empty_cnt; + int *remain; + int ok; + + to_merge_size = PyList_GET_SIZE(to_merge); + + /* remain stores an index into each sublist of to_merge. + remain[i] is the index of the next base in to_merge[i] + that is not included in acc. + */ + remain = (int *)PyMem_MALLOC(SIZEOF_INT*to_merge_size); + if (remain == NULL) + return -1; + for (i = 0; i < to_merge_size; i++) + remain[i] = 0; again: - empty_cnt = 0; - for (i = 0; i < to_merge_size; i++) { - PyObject *candidate; - - PyObject *cur_list = PyList_GET_ITEM(to_merge, i); - - if (remain[i] >= PyList_GET_SIZE(cur_list)) { - empty_cnt++; - continue; - } - - /* Choose next candidate for MRO. - - The input sequences alone can determine the choice. - If not, choose the class which appears in the MRO - of the earliest direct superclass of the new class. - */ - - candidate = PyList_GET_ITEM(cur_list, remain[i]); - for (j = 0; j < to_merge_size; j++) { - PyObject *j_lst = PyList_GET_ITEM(to_merge, j); - if (tail_contains(j_lst, remain[j], candidate)) { - goto skip; /* continue outer loop */ - } - } - ok = PyList_Append(acc, candidate); - if (ok < 0) { - PyMem_Free(remain); - return -1; - } - for (j = 0; j < to_merge_size; j++) { - PyObject *j_lst = PyList_GET_ITEM(to_merge, j); - if (remain[j] < PyList_GET_SIZE(j_lst) && - PyList_GET_ITEM(j_lst, remain[j]) == candidate) { - remain[j]++; - } - } - goto again; - skip: ; - } - - if (empty_cnt == to_merge_size) { - PyMem_FREE(remain); - return 0; - } - set_mro_error(to_merge, remain); - PyMem_FREE(remain); - return -1; + empty_cnt = 0; + for (i = 0; i < to_merge_size; i++) { + PyObject *candidate; + + PyObject *cur_list = PyList_GET_ITEM(to_merge, i); + + if (remain[i] >= PyList_GET_SIZE(cur_list)) { + empty_cnt++; + continue; + } + + /* Choose next candidate for MRO. + + The input sequences alone can determine the choice. + If not, choose the class which appears in the MRO + of the earliest direct superclass of the new class. + */ + + candidate = PyList_GET_ITEM(cur_list, remain[i]); + for (j = 0; j < to_merge_size; j++) { + PyObject *j_lst = PyList_GET_ITEM(to_merge, j); + if (tail_contains(j_lst, remain[j], candidate)) { + goto skip; /* continue outer loop */ + } + } + ok = PyList_Append(acc, candidate); + if (ok < 0) { + PyMem_Free(remain); + return -1; + } + for (j = 0; j < to_merge_size; j++) { + PyObject *j_lst = PyList_GET_ITEM(to_merge, j); + if (remain[j] < PyList_GET_SIZE(j_lst) && + PyList_GET_ITEM(j_lst, remain[j]) == candidate) { + remain[j]++; + } + } + goto again; + skip: ; + } + + if (empty_cnt == to_merge_size) { + PyMem_FREE(remain); + return 0; + } + set_mro_error(to_merge, remain); + PyMem_FREE(remain); + return -1; } static PyObject * mro_implementation(PyTypeObject *type) { - Py_ssize_t i, n; - int ok; - PyObject *bases, *result; - PyObject *to_merge, *bases_aslist; - - if (type->tp_dict == NULL) { - if (PyType_Ready(type) < 0) - return NULL; - } - - /* Find a superclass linearization that honors the constraints - of the explicit lists of bases and the constraints implied by - each base class. - - to_merge is a list of lists, where each list is a superclass - linearization implied by a base class. The last element of - to_merge is the declared list of bases. - */ - - bases = type->tp_bases; - n = PyTuple_GET_SIZE(bases); - - to_merge = PyList_New(n+1); - if (to_merge == NULL) - return NULL; - - for (i = 0; i < n; i++) { - PyObject *base = PyTuple_GET_ITEM(bases, i); - PyObject *parentMRO; - parentMRO = PySequence_List(((PyTypeObject*)base)->tp_mro); - if (parentMRO == NULL) { - Py_DECREF(to_merge); - return NULL; - } - - PyList_SET_ITEM(to_merge, i, parentMRO); - } - - bases_aslist = PySequence_List(bases); - if (bases_aslist == NULL) { - Py_DECREF(to_merge); - return NULL; - } - /* This is just a basic sanity check. */ - if (check_duplicates(bases_aslist) < 0) { - Py_DECREF(to_merge); - Py_DECREF(bases_aslist); - return NULL; - } - PyList_SET_ITEM(to_merge, n, bases_aslist); - - result = Py_BuildValue("[O]", (PyObject *)type); - if (result == NULL) { - Py_DECREF(to_merge); - return NULL; - } - - ok = pmerge(result, to_merge); - Py_DECREF(to_merge); - if (ok < 0) { - Py_DECREF(result); - return NULL; - } + Py_ssize_t i, n; + int ok; + PyObject *bases, *result; + PyObject *to_merge, *bases_aslist; + + if (type->tp_dict == NULL) { + if (PyType_Ready(type) < 0) + return NULL; + } + + /* Find a superclass linearization that honors the constraints + of the explicit lists of bases and the constraints implied by + each base class. + + to_merge is a list of lists, where each list is a superclass + linearization implied by a base class. The last element of + to_merge is the declared list of bases. + */ + + bases = type->tp_bases; + n = PyTuple_GET_SIZE(bases); + + to_merge = PyList_New(n+1); + if (to_merge == NULL) + return NULL; + + for (i = 0; i < n; i++) { + PyObject *base = PyTuple_GET_ITEM(bases, i); + PyObject *parentMRO; + parentMRO = PySequence_List(((PyTypeObject*)base)->tp_mro); + if (parentMRO == NULL) { + Py_DECREF(to_merge); + return NULL; + } + + PyList_SET_ITEM(to_merge, i, parentMRO); + } - return result; + bases_aslist = PySequence_List(bases); + if (bases_aslist == NULL) { + Py_DECREF(to_merge); + return NULL; + } + /* This is just a basic sanity check. */ + if (check_duplicates(bases_aslist) < 0) { + Py_DECREF(to_merge); + Py_DECREF(bases_aslist); + return NULL; + } + PyList_SET_ITEM(to_merge, n, bases_aslist); + + result = Py_BuildValue("[O]", (PyObject *)type); + if (result == NULL) { + Py_DECREF(to_merge); + return NULL; + } + + ok = pmerge(result, to_merge); + Py_DECREF(to_merge); + if (ok < 0) { + Py_DECREF(result); + return NULL; + } + + return result; } static PyObject * mro_external(PyObject *self) { - PyTypeObject *type = (PyTypeObject *)self; + PyTypeObject *type = (PyTypeObject *)self; - return mro_implementation(type); + return mro_implementation(type); } static int mro_internal(PyTypeObject *type) { - PyObject *mro, *result, *tuple; - int checkit = 0; + PyObject *mro, *result, *tuple; + int checkit = 0; + + if (Py_TYPE(type) == &PyType_Type) { + result = mro_implementation(type); + } + else { + static PyObject *mro_str; + checkit = 1; + mro = lookup_method((PyObject *)type, "mro", &mro_str); + if (mro == NULL) + return -1; + result = PyObject_CallObject(mro, NULL); + Py_DECREF(mro); + } + if (result == NULL) + return -1; + tuple = PySequence_Tuple(result); + Py_DECREF(result); + if (tuple == NULL) + return -1; + if (checkit) { + Py_ssize_t i, len; + PyObject *cls; + PyTypeObject *solid; + + solid = solid_base(type); + + len = PyTuple_GET_SIZE(tuple); + + for (i = 0; i < len; i++) { + PyTypeObject *t; + cls = PyTuple_GET_ITEM(tuple, i); + if (!PyType_Check(cls)) { + PyErr_Format(PyExc_TypeError, + "mro() returned a non-class ('%.500s')", + Py_TYPE(cls)->tp_name); + Py_DECREF(tuple); + return -1; + } + t = (PyTypeObject*)cls; + if (!PyType_IsSubtype(solid, solid_base(t))) { + PyErr_Format(PyExc_TypeError, + "mro() returned base with unsuitable layout ('%.500s')", + t->tp_name); + Py_DECREF(tuple); + return -1; + } + } + } + type->tp_mro = tuple; - if (Py_TYPE(type) == &PyType_Type) { - result = mro_implementation(type); - } - else { - static PyObject *mro_str; - checkit = 1; - mro = lookup_method((PyObject *)type, "mro", &mro_str); - if (mro == NULL) - return -1; - result = PyObject_CallObject(mro, NULL); - Py_DECREF(mro); - } - if (result == NULL) - return -1; - tuple = PySequence_Tuple(result); - Py_DECREF(result); - if (tuple == NULL) - return -1; - if (checkit) { - Py_ssize_t i, len; - PyObject *cls; - PyTypeObject *solid; - - solid = solid_base(type); - - len = PyTuple_GET_SIZE(tuple); - - for (i = 0; i < len; i++) { - PyTypeObject *t; - cls = PyTuple_GET_ITEM(tuple, i); - if (!PyType_Check(cls)) { - PyErr_Format(PyExc_TypeError, - "mro() returned a non-class ('%.500s')", - Py_TYPE(cls)->tp_name); - Py_DECREF(tuple); - return -1; - } - t = (PyTypeObject*)cls; - if (!PyType_IsSubtype(solid, solid_base(t))) { - PyErr_Format(PyExc_TypeError, - "mro() returned base with unsuitable layout ('%.500s')", - t->tp_name); - Py_DECREF(tuple); - return -1; - } - } - } - type->tp_mro = tuple; - - type_mro_modified(type, type->tp_mro); - /* corner case: the old-style super class might have been hidden - from the custom MRO */ - type_mro_modified(type, type->tp_bases); + type_mro_modified(type, type->tp_mro); + /* corner case: the old-style super class might have been hidden + from the custom MRO */ + type_mro_modified(type, type->tp_bases); - PyType_Modified(type); + PyType_Modified(type); - return 0; + return 0; } @@ -1578,90 +1578,90 @@ static PyTypeObject * best_base(PyObject *bases) { - Py_ssize_t i, n; - PyTypeObject *base, *winner, *candidate, *base_i; - PyObject *base_proto; - - assert(PyTuple_Check(bases)); - n = PyTuple_GET_SIZE(bases); - assert(n > 0); - base = NULL; - winner = NULL; - for (i = 0; i < n; i++) { - base_proto = PyTuple_GET_ITEM(bases, i); - if (!PyType_Check(base_proto)) { - PyErr_SetString( - PyExc_TypeError, - "bases must be types"); - return NULL; - } - base_i = (PyTypeObject *)base_proto; - if (base_i->tp_dict == NULL) { - if (PyType_Ready(base_i) < 0) - return NULL; - } - candidate = solid_base(base_i); - if (winner == NULL) { - winner = candidate; - base = base_i; - } - else if (PyType_IsSubtype(winner, candidate)) - ; - else if (PyType_IsSubtype(candidate, winner)) { - winner = candidate; - base = base_i; - } - else { - PyErr_SetString( - PyExc_TypeError, - "multiple bases have " - "instance lay-out conflict"); - return NULL; - } - } - if (base == NULL) - PyErr_SetString(PyExc_TypeError, - "a new-style class can't have only classic bases"); - return base; + Py_ssize_t i, n; + PyTypeObject *base, *winner, *candidate, *base_i; + PyObject *base_proto; + + assert(PyTuple_Check(bases)); + n = PyTuple_GET_SIZE(bases); + assert(n > 0); + base = NULL; + winner = NULL; + for (i = 0; i < n; i++) { + base_proto = PyTuple_GET_ITEM(bases, i); + if (!PyType_Check(base_proto)) { + PyErr_SetString( + PyExc_TypeError, + "bases must be types"); + return NULL; + } + base_i = (PyTypeObject *)base_proto; + if (base_i->tp_dict == NULL) { + if (PyType_Ready(base_i) < 0) + return NULL; + } + candidate = solid_base(base_i); + if (winner == NULL) { + winner = candidate; + base = base_i; + } + else if (PyType_IsSubtype(winner, candidate)) + ; + else if (PyType_IsSubtype(candidate, winner)) { + winner = candidate; + base = base_i; + } + else { + PyErr_SetString( + PyExc_TypeError, + "multiple bases have " + "instance lay-out conflict"); + return NULL; + } + } + if (base == NULL) + PyErr_SetString(PyExc_TypeError, + "a new-style class can't have only classic bases"); + return base; } static int extra_ivars(PyTypeObject *type, PyTypeObject *base) { - size_t t_size = type->tp_basicsize; - size_t b_size = base->tp_basicsize; + size_t t_size = type->tp_basicsize; + size_t b_size = base->tp_basicsize; - assert(t_size >= b_size); /* Else type smaller than base! */ - if (type->tp_itemsize || base->tp_itemsize) { - /* If itemsize is involved, stricter rules */ - return t_size != b_size || - type->tp_itemsize != base->tp_itemsize; - } - if (type->tp_weaklistoffset && base->tp_weaklistoffset == 0 && - type->tp_weaklistoffset + sizeof(PyObject *) == t_size && - type->tp_flags & Py_TPFLAGS_HEAPTYPE) - t_size -= sizeof(PyObject *); - if (type->tp_dictoffset && base->tp_dictoffset == 0 && - type->tp_dictoffset + sizeof(PyObject *) == t_size && - type->tp_flags & Py_TPFLAGS_HEAPTYPE) - t_size -= sizeof(PyObject *); + assert(t_size >= b_size); /* Else type smaller than base! */ + if (type->tp_itemsize || base->tp_itemsize) { + /* If itemsize is involved, stricter rules */ + return t_size != b_size || + type->tp_itemsize != base->tp_itemsize; + } + if (type->tp_weaklistoffset && base->tp_weaklistoffset == 0 && + type->tp_weaklistoffset + sizeof(PyObject *) == t_size && + type->tp_flags & Py_TPFLAGS_HEAPTYPE) + t_size -= sizeof(PyObject *); + if (type->tp_dictoffset && base->tp_dictoffset == 0 && + type->tp_dictoffset + sizeof(PyObject *) == t_size && + type->tp_flags & Py_TPFLAGS_HEAPTYPE) + t_size -= sizeof(PyObject *); - return t_size != b_size; + return t_size != b_size; } static PyTypeObject * solid_base(PyTypeObject *type) { - PyTypeObject *base; + PyTypeObject *base; - if (type->tp_base) - base = solid_base(type->tp_base); - else - base = &PyBaseObject_Type; - if (extra_ivars(type, base)) - return type; - else - return base; + if (type->tp_base) + base = solid_base(type->tp_base); + else + base = &PyBaseObject_Type; + if (extra_ivars(type, base)) + return type; + else + return base; } static void object_dealloc(PyObject *); @@ -1677,180 +1677,180 @@ static PyTypeObject * get_builtin_base_with_dict(PyTypeObject *type) { - while (type->tp_base != NULL) { - if (type->tp_dictoffset != 0 && - !(type->tp_flags & Py_TPFLAGS_HEAPTYPE)) - return type; - type = type->tp_base; - } - return NULL; + while (type->tp_base != NULL) { + if (type->tp_dictoffset != 0 && + !(type->tp_flags & Py_TPFLAGS_HEAPTYPE)) + return type; + type = type->tp_base; + } + return NULL; } static PyObject * get_dict_descriptor(PyTypeObject *type) { - static PyObject *dict_str; - PyObject *descr; + static PyObject *dict_str; + PyObject *descr; - if (dict_str == NULL) { - dict_str = PyUnicode_InternFromString("__dict__"); - if (dict_str == NULL) - return NULL; - } - descr = _PyType_Lookup(type, dict_str); - if (descr == NULL || !PyDescr_IsData(descr)) - return NULL; + if (dict_str == NULL) { + dict_str = PyUnicode_InternFromString("__dict__"); + if (dict_str == NULL) + return NULL; + } + descr = _PyType_Lookup(type, dict_str); + if (descr == NULL || !PyDescr_IsData(descr)) + return NULL; - return descr; + return descr; } static void raise_dict_descr_error(PyObject *obj) { - PyErr_Format(PyExc_TypeError, - "this __dict__ descriptor does not support " - "'%.200s' objects", Py_TYPE(obj)->tp_name); + PyErr_Format(PyExc_TypeError, + "this __dict__ descriptor does not support " + "'%.200s' objects", Py_TYPE(obj)->tp_name); } static PyObject * subtype_dict(PyObject *obj, void *context) { - PyObject **dictptr; - PyObject *dict; - PyTypeObject *base; - - base = get_builtin_base_with_dict(Py_TYPE(obj)); - if (base != NULL) { - descrgetfunc func; - PyObject *descr = get_dict_descriptor(base); - if (descr == NULL) { - raise_dict_descr_error(obj); - return NULL; - } - func = Py_TYPE(descr)->tp_descr_get; - if (func == NULL) { - raise_dict_descr_error(obj); - return NULL; - } - return func(descr, obj, (PyObject *)(Py_TYPE(obj))); - } - - dictptr = _PyObject_GetDictPtr(obj); - if (dictptr == NULL) { - PyErr_SetString(PyExc_AttributeError, - "This object has no __dict__"); - return NULL; - } - dict = *dictptr; - if (dict == NULL) - *dictptr = dict = PyDict_New(); - Py_XINCREF(dict); - return dict; + PyObject **dictptr; + PyObject *dict; + PyTypeObject *base; + + base = get_builtin_base_with_dict(Py_TYPE(obj)); + if (base != NULL) { + descrgetfunc func; + PyObject *descr = get_dict_descriptor(base); + if (descr == NULL) { + raise_dict_descr_error(obj); + return NULL; + } + func = Py_TYPE(descr)->tp_descr_get; + if (func == NULL) { + raise_dict_descr_error(obj); + return NULL; + } + return func(descr, obj, (PyObject *)(Py_TYPE(obj))); + } + + dictptr = _PyObject_GetDictPtr(obj); + if (dictptr == NULL) { + PyErr_SetString(PyExc_AttributeError, + "This object has no __dict__"); + return NULL; + } + dict = *dictptr; + if (dict == NULL) + *dictptr = dict = PyDict_New(); + Py_XINCREF(dict); + return dict; } static int subtype_setdict(PyObject *obj, PyObject *value, void *context) { - PyObject **dictptr; - PyObject *dict; - PyTypeObject *base; - - base = get_builtin_base_with_dict(Py_TYPE(obj)); - if (base != NULL) { - descrsetfunc func; - PyObject *descr = get_dict_descriptor(base); - if (descr == NULL) { - raise_dict_descr_error(obj); - return -1; - } - func = Py_TYPE(descr)->tp_descr_set; - if (func == NULL) { - raise_dict_descr_error(obj); - return -1; - } - return func(descr, obj, value); - } - - dictptr = _PyObject_GetDictPtr(obj); - if (dictptr == NULL) { - PyErr_SetString(PyExc_AttributeError, - "This object has no __dict__"); - return -1; - } - if (value != NULL && !PyDict_Check(value)) { - PyErr_Format(PyExc_TypeError, - "__dict__ must be set to a dictionary, " - "not a '%.200s'", Py_TYPE(value)->tp_name); - return -1; - } - dict = *dictptr; - Py_XINCREF(value); - *dictptr = value; - Py_XDECREF(dict); - return 0; + PyObject **dictptr; + PyObject *dict; + PyTypeObject *base; + + base = get_builtin_base_with_dict(Py_TYPE(obj)); + if (base != NULL) { + descrsetfunc func; + PyObject *descr = get_dict_descriptor(base); + if (descr == NULL) { + raise_dict_descr_error(obj); + return -1; + } + func = Py_TYPE(descr)->tp_descr_set; + if (func == NULL) { + raise_dict_descr_error(obj); + return -1; + } + return func(descr, obj, value); + } + + dictptr = _PyObject_GetDictPtr(obj); + if (dictptr == NULL) { + PyErr_SetString(PyExc_AttributeError, + "This object has no __dict__"); + return -1; + } + if (value != NULL && !PyDict_Check(value)) { + PyErr_Format(PyExc_TypeError, + "__dict__ must be set to a dictionary, " + "not a '%.200s'", Py_TYPE(value)->tp_name); + return -1; + } + dict = *dictptr; + Py_XINCREF(value); + *dictptr = value; + Py_XDECREF(dict); + return 0; } static PyObject * subtype_getweakref(PyObject *obj, void *context) { - PyObject **weaklistptr; - PyObject *result; + PyObject **weaklistptr; + PyObject *result; - if (Py_TYPE(obj)->tp_weaklistoffset == 0) { - PyErr_SetString(PyExc_AttributeError, - "This object has no __weakref__"); - return NULL; - } - assert(Py_TYPE(obj)->tp_weaklistoffset > 0); - assert(Py_TYPE(obj)->tp_weaklistoffset + sizeof(PyObject *) <= - (size_t)(Py_TYPE(obj)->tp_basicsize)); - weaklistptr = (PyObject **) - ((char *)obj + Py_TYPE(obj)->tp_weaklistoffset); - if (*weaklistptr == NULL) - result = Py_None; - else - result = *weaklistptr; - Py_INCREF(result); - return result; + if (Py_TYPE(obj)->tp_weaklistoffset == 0) { + PyErr_SetString(PyExc_AttributeError, + "This object has no __weakref__"); + return NULL; + } + assert(Py_TYPE(obj)->tp_weaklistoffset > 0); + assert(Py_TYPE(obj)->tp_weaklistoffset + sizeof(PyObject *) <= + (size_t)(Py_TYPE(obj)->tp_basicsize)); + weaklistptr = (PyObject **) + ((char *)obj + Py_TYPE(obj)->tp_weaklistoffset); + if (*weaklistptr == NULL) + result = Py_None; + else + result = *weaklistptr; + Py_INCREF(result); + return result; } /* Three variants on the subtype_getsets list. */ static PyGetSetDef subtype_getsets_full[] = { - {"__dict__", subtype_dict, subtype_setdict, - PyDoc_STR("dictionary for instance variables (if defined)")}, - {"__weakref__", subtype_getweakref, NULL, - PyDoc_STR("list of weak references to the object (if defined)")}, - {0} + {"__dict__", subtype_dict, subtype_setdict, + PyDoc_STR("dictionary for instance variables (if defined)")}, + {"__weakref__", subtype_getweakref, NULL, + PyDoc_STR("list of weak references to the object (if defined)")}, + {0} }; static PyGetSetDef subtype_getsets_dict_only[] = { - {"__dict__", subtype_dict, subtype_setdict, - PyDoc_STR("dictionary for instance variables (if defined)")}, - {0} + {"__dict__", subtype_dict, subtype_setdict, + PyDoc_STR("dictionary for instance variables (if defined)")}, + {0} }; static PyGetSetDef subtype_getsets_weakref_only[] = { - {"__weakref__", subtype_getweakref, NULL, - PyDoc_STR("list of weak references to the object (if defined)")}, - {0} + {"__weakref__", subtype_getweakref, NULL, + PyDoc_STR("list of weak references to the object (if defined)")}, + {0} }; static int valid_identifier(PyObject *s) { - if (!PyUnicode_Check(s)) { - PyErr_Format(PyExc_TypeError, - "__slots__ items must be strings, not '%.200s'", - Py_TYPE(s)->tp_name); - return 0; - } - if (!PyUnicode_IsIdentifier(s)) { - PyErr_SetString(PyExc_TypeError, - "__slots__ must be identifiers"); - return 0; - } - return 1; + if (!PyUnicode_Check(s)) { + PyErr_Format(PyExc_TypeError, + "__slots__ items must be strings, not '%.200s'", + Py_TYPE(s)->tp_name); + return 0; + } + if (!PyUnicode_IsIdentifier(s)) { + PyErr_SetString(PyExc_TypeError, + "__slots__ must be identifiers"); + return 0; + } + return 1; } /* Forward */ @@ -1860,435 +1860,435 @@ static int type_init(PyObject *cls, PyObject *args, PyObject *kwds) { - int res; + int res; - assert(args != NULL && PyTuple_Check(args)); - assert(kwds == NULL || PyDict_Check(kwds)); + assert(args != NULL && PyTuple_Check(args)); + assert(kwds == NULL || PyDict_Check(kwds)); - if (kwds != NULL && PyDict_Check(kwds) && PyDict_Size(kwds) != 0) { - PyErr_SetString(PyExc_TypeError, - "type.__init__() takes no keyword arguments"); - return -1; - } - - if (args != NULL && PyTuple_Check(args) && - (PyTuple_GET_SIZE(args) != 1 && PyTuple_GET_SIZE(args) != 3)) { - PyErr_SetString(PyExc_TypeError, - "type.__init__() takes 1 or 3 arguments"); - return -1; - } - - /* Call object.__init__(self) now. */ - /* XXX Could call super(type, cls).__init__() but what's the point? */ - args = PyTuple_GetSlice(args, 0, 0); - res = object_init(cls, args, NULL); - Py_DECREF(args); - return res; + if (kwds != NULL && PyDict_Check(kwds) && PyDict_Size(kwds) != 0) { + PyErr_SetString(PyExc_TypeError, + "type.__init__() takes no keyword arguments"); + return -1; + } + + if (args != NULL && PyTuple_Check(args) && + (PyTuple_GET_SIZE(args) != 1 && PyTuple_GET_SIZE(args) != 3)) { + PyErr_SetString(PyExc_TypeError, + "type.__init__() takes 1 or 3 arguments"); + return -1; + } + + /* Call object.__init__(self) now. */ + /* XXX Could call super(type, cls).__init__() but what's the point? */ + args = PyTuple_GetSlice(args, 0, 0); + res = object_init(cls, args, NULL); + Py_DECREF(args); + return res; } static PyObject * type_new(PyTypeObject *metatype, PyObject *args, PyObject *kwds) { - PyObject *name, *bases, *dict; - static char *kwlist[] = {"name", "bases", "dict", 0}; - PyObject *slots, *tmp, *newslots; - PyTypeObject *type, *base, *tmptype, *winner; - PyHeapTypeObject *et; - PyMemberDef *mp; - Py_ssize_t i, nbases, nslots, slotoffset, add_dict, add_weak; - int j, may_add_dict, may_add_weak; - - assert(args != NULL && PyTuple_Check(args)); - assert(kwds == NULL || PyDict_Check(kwds)); - - /* Special case: type(x) should return x->ob_type */ - { - const Py_ssize_t nargs = PyTuple_GET_SIZE(args); - const Py_ssize_t nkwds = kwds == NULL ? 0 : PyDict_Size(kwds); - - if (PyType_CheckExact(metatype) && nargs == 1 && nkwds == 0) { - PyObject *x = PyTuple_GET_ITEM(args, 0); - Py_INCREF(Py_TYPE(x)); - return (PyObject *) Py_TYPE(x); - } - - /* SF bug 475327 -- if that didn't trigger, we need 3 - arguments. but PyArg_ParseTupleAndKeywords below may give - a msg saying type() needs exactly 3. */ - if (nargs + nkwds != 3) { - PyErr_SetString(PyExc_TypeError, - "type() takes 1 or 3 arguments"); - return NULL; - } - } - - /* Check arguments: (name, bases, dict) */ - if (!PyArg_ParseTupleAndKeywords(args, kwds, "UO!O!:type", kwlist, - &name, - &PyTuple_Type, &bases, - &PyDict_Type, &dict)) - return NULL; - - /* Determine the proper metatype to deal with this, - and check for metatype conflicts while we're at it. - Note that if some other metatype wins to contract, - it's possible that its instances are not types. */ - nbases = PyTuple_GET_SIZE(bases); - winner = metatype; - for (i = 0; i < nbases; i++) { - tmp = PyTuple_GET_ITEM(bases, i); - tmptype = Py_TYPE(tmp); - if (PyType_IsSubtype(winner, tmptype)) - continue; - if (PyType_IsSubtype(tmptype, winner)) { - winner = tmptype; - continue; - } - PyErr_SetString(PyExc_TypeError, - "metaclass conflict: " - "the metaclass of a derived class " - "must be a (non-strict) subclass " - "of the metaclasses of all its bases"); - return NULL; - } - if (winner != metatype) { - if (winner->tp_new != type_new) /* Pass it to the winner */ - return winner->tp_new(winner, args, kwds); - metatype = winner; - } - - /* Adjust for empty tuple bases */ - if (nbases == 0) { - bases = PyTuple_Pack(1, &PyBaseObject_Type); - if (bases == NULL) - return NULL; - nbases = 1; - } - else - Py_INCREF(bases); - - /* XXX From here until type is allocated, "return NULL" leaks bases! */ - - /* Calculate best base, and check that all bases are type objects */ - base = best_base(bases); - if (base == NULL) { - Py_DECREF(bases); - return NULL; - } - if (!PyType_HasFeature(base, Py_TPFLAGS_BASETYPE)) { - PyErr_Format(PyExc_TypeError, - "type '%.100s' is not an acceptable base type", - base->tp_name); - Py_DECREF(bases); - return NULL; - } - - /* Check for a __slots__ sequence variable in dict, and count it */ - slots = PyDict_GetItemString(dict, "__slots__"); - nslots = 0; - add_dict = 0; - add_weak = 0; - may_add_dict = base->tp_dictoffset == 0; - may_add_weak = base->tp_weaklistoffset == 0 && base->tp_itemsize == 0; - if (slots == NULL) { - if (may_add_dict) { - add_dict++; - } - if (may_add_weak) { - add_weak++; - } - } - else { - /* Have slots */ - - /* Make it into a tuple */ - if (PyUnicode_Check(slots)) - slots = PyTuple_Pack(1, slots); - else - slots = PySequence_Tuple(slots); - if (slots == NULL) { - Py_DECREF(bases); - return NULL; - } - assert(PyTuple_Check(slots)); - - /* Are slots allowed? */ - nslots = PyTuple_GET_SIZE(slots); - if (nslots > 0 && base->tp_itemsize != 0) { - PyErr_Format(PyExc_TypeError, - "nonempty __slots__ " - "not supported for subtype of '%s'", - base->tp_name); - bad_slots: - Py_DECREF(bases); - Py_DECREF(slots); - return NULL; - } - - /* Check for valid slot names and two special cases */ - for (i = 0; i < nslots; i++) { - PyObject *tmp = PyTuple_GET_ITEM(slots, i); - if (!valid_identifier(tmp)) - goto bad_slots; - assert(PyUnicode_Check(tmp)); - if (PyUnicode_CompareWithASCIIString(tmp, "__dict__") == 0) { - if (!may_add_dict || add_dict) { - PyErr_SetString(PyExc_TypeError, - "__dict__ slot disallowed: " - "we already got one"); - goto bad_slots; - } - add_dict++; - } - if (PyUnicode_CompareWithASCIIString(tmp, "__weakref__") == 0) { - if (!may_add_weak || add_weak) { - PyErr_SetString(PyExc_TypeError, - "__weakref__ slot disallowed: " - "either we already got one, " - "or __itemsize__ != 0"); - goto bad_slots; - } - add_weak++; - } - } - - /* Copy slots into a list, mangle names and sort them. - Sorted names are needed for __class__ assignment. - Convert them back to tuple at the end. - */ - newslots = PyList_New(nslots - add_dict - add_weak); - if (newslots == NULL) - goto bad_slots; - for (i = j = 0; i < nslots; i++) { - tmp = PyTuple_GET_ITEM(slots, i); - if ((add_dict && - PyUnicode_CompareWithASCIIString(tmp, "__dict__") == 0) || - (add_weak && - PyUnicode_CompareWithASCIIString(tmp, "__weakref__") == 0)) - continue; - tmp =_Py_Mangle(name, tmp); - if (!tmp) - goto bad_slots; - PyList_SET_ITEM(newslots, j, tmp); - j++; - } - assert(j == nslots - add_dict - add_weak); - nslots = j; - Py_DECREF(slots); - if (PyList_Sort(newslots) == -1) { - Py_DECREF(bases); - Py_DECREF(newslots); - return NULL; - } - slots = PyList_AsTuple(newslots); - Py_DECREF(newslots); - if (slots == NULL) { - Py_DECREF(bases); - return NULL; - } - - /* Secondary bases may provide weakrefs or dict */ - if (nbases > 1 && - ((may_add_dict && !add_dict) || - (may_add_weak && !add_weak))) { - for (i = 0; i < nbases; i++) { - tmp = PyTuple_GET_ITEM(bases, i); - if (tmp == (PyObject *)base) - continue; /* Skip primary base */ - assert(PyType_Check(tmp)); - tmptype = (PyTypeObject *)tmp; - if (may_add_dict && !add_dict && - tmptype->tp_dictoffset != 0) - add_dict++; - if (may_add_weak && !add_weak && - tmptype->tp_weaklistoffset != 0) - add_weak++; - if (may_add_dict && !add_dict) - continue; - if (may_add_weak && !add_weak) - continue; - /* Nothing more to check */ - break; - } - } - } - - /* XXX From here until type is safely allocated, - "return NULL" may leak slots! */ - - /* Allocate the type object */ - type = (PyTypeObject *)metatype->tp_alloc(metatype, nslots); - if (type == NULL) { - Py_XDECREF(slots); - Py_DECREF(bases); - return NULL; - } - - /* Keep name and slots alive in the extended type object */ - et = (PyHeapTypeObject *)type; - Py_INCREF(name); - et->ht_name = name; - et->ht_slots = slots; - - /* Initialize tp_flags */ - type->tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HEAPTYPE | - Py_TPFLAGS_BASETYPE; - if (base->tp_flags & Py_TPFLAGS_HAVE_GC) - type->tp_flags |= Py_TPFLAGS_HAVE_GC; - - /* Initialize essential fields */ - type->tp_as_number = &et->as_number; - type->tp_as_sequence = &et->as_sequence; - type->tp_as_mapping = &et->as_mapping; - type->tp_as_buffer = &et->as_buffer; - type->tp_name = _PyUnicode_AsString(name); - if (!type->tp_name) { - Py_DECREF(type); - return NULL; - } - - /* Set tp_base and tp_bases */ - type->tp_bases = bases; - Py_INCREF(base); - type->tp_base = base; - - /* Initialize tp_dict from passed-in dict */ - type->tp_dict = dict = PyDict_Copy(dict); - if (dict == NULL) { - Py_DECREF(type); - return NULL; - } - - /* Set __module__ in the dict */ - if (PyDict_GetItemString(dict, "__module__") == NULL) { - tmp = PyEval_GetGlobals(); - if (tmp != NULL) { - tmp = PyDict_GetItemString(tmp, "__name__"); - if (tmp != NULL) { - if (PyDict_SetItemString(dict, "__module__", - tmp) < 0) - return NULL; - } - } - } - - /* Set tp_doc to a copy of dict['__doc__'], if the latter is there - and is a string. The __doc__ accessor will first look for tp_doc; - if that fails, it will still look into __dict__. - */ - { - PyObject *doc = PyDict_GetItemString(dict, "__doc__"); - if (doc != NULL && PyUnicode_Check(doc)) { - Py_ssize_t len; - char *doc_str; - char *tp_doc; - - doc_str = _PyUnicode_AsString(doc); - if (doc_str == NULL) { - Py_DECREF(type); - return NULL; - } - /* Silently truncate the docstring if it contains null bytes. */ - len = strlen(doc_str); - tp_doc = (char *)PyObject_MALLOC(len + 1); - if (tp_doc == NULL) { - Py_DECREF(type); - return NULL; - } - memcpy(tp_doc, doc_str, len + 1); - type->tp_doc = tp_doc; - } - } - - /* Special-case __new__: if it's a plain function, - make it a static function */ - tmp = PyDict_GetItemString(dict, "__new__"); - if (tmp != NULL && PyFunction_Check(tmp)) { - tmp = PyStaticMethod_New(tmp); - if (tmp == NULL) { - Py_DECREF(type); - return NULL; - } - PyDict_SetItemString(dict, "__new__", tmp); - Py_DECREF(tmp); - } - - /* Add descriptors for custom slots from __slots__, or for __dict__ */ - mp = PyHeapType_GET_MEMBERS(et); - slotoffset = base->tp_basicsize; - if (slots != NULL) { - for (i = 0; i < nslots; i++, mp++) { - mp->name = _PyUnicode_AsString( - PyTuple_GET_ITEM(slots, i)); - mp->type = T_OBJECT_EX; - mp->offset = slotoffset; - - /* __dict__ and __weakref__ are already filtered out */ - assert(strcmp(mp->name, "__dict__") != 0); - assert(strcmp(mp->name, "__weakref__") != 0); - - slotoffset += sizeof(PyObject *); - } - } - if (add_dict) { - if (base->tp_itemsize) - type->tp_dictoffset = -(long)sizeof(PyObject *); - else - type->tp_dictoffset = slotoffset; - slotoffset += sizeof(PyObject *); - } - if (add_weak) { - assert(!base->tp_itemsize); - type->tp_weaklistoffset = slotoffset; - slotoffset += sizeof(PyObject *); - } - type->tp_basicsize = slotoffset; - type->tp_itemsize = base->tp_itemsize; - type->tp_members = PyHeapType_GET_MEMBERS(et); - - if (type->tp_weaklistoffset && type->tp_dictoffset) - type->tp_getset = subtype_getsets_full; - else if (type->tp_weaklistoffset && !type->tp_dictoffset) - type->tp_getset = subtype_getsets_weakref_only; - else if (!type->tp_weaklistoffset && type->tp_dictoffset) - type->tp_getset = subtype_getsets_dict_only; - else - type->tp_getset = NULL; - - /* Special case some slots */ - if (type->tp_dictoffset != 0 || nslots > 0) { - if (base->tp_getattr == NULL && base->tp_getattro == NULL) - type->tp_getattro = PyObject_GenericGetAttr; - if (base->tp_setattr == NULL && base->tp_setattro == NULL) - type->tp_setattro = PyObject_GenericSetAttr; - } - type->tp_dealloc = subtype_dealloc; - - /* Enable GC unless there are really no instance variables possible */ - if (!(type->tp_basicsize == sizeof(PyObject) && - type->tp_itemsize == 0)) - type->tp_flags |= Py_TPFLAGS_HAVE_GC; - - /* Always override allocation strategy to use regular heap */ - type->tp_alloc = PyType_GenericAlloc; - if (type->tp_flags & Py_TPFLAGS_HAVE_GC) { - type->tp_free = PyObject_GC_Del; - type->tp_traverse = subtype_traverse; - type->tp_clear = subtype_clear; - } - else - type->tp_free = PyObject_Del; - - /* Initialize the rest */ - if (PyType_Ready(type) < 0) { - Py_DECREF(type); - return NULL; - } + PyObject *name, *bases, *dict; + static char *kwlist[] = {"name", "bases", "dict", 0}; + PyObject *slots, *tmp, *newslots; + PyTypeObject *type, *base, *tmptype, *winner; + PyHeapTypeObject *et; + PyMemberDef *mp; + Py_ssize_t i, nbases, nslots, slotoffset, add_dict, add_weak; + int j, may_add_dict, may_add_weak; + + assert(args != NULL && PyTuple_Check(args)); + assert(kwds == NULL || PyDict_Check(kwds)); + + /* Special case: type(x) should return x->ob_type */ + { + const Py_ssize_t nargs = PyTuple_GET_SIZE(args); + const Py_ssize_t nkwds = kwds == NULL ? 0 : PyDict_Size(kwds); + + if (PyType_CheckExact(metatype) && nargs == 1 && nkwds == 0) { + PyObject *x = PyTuple_GET_ITEM(args, 0); + Py_INCREF(Py_TYPE(x)); + return (PyObject *) Py_TYPE(x); + } + + /* SF bug 475327 -- if that didn't trigger, we need 3 + arguments. but PyArg_ParseTupleAndKeywords below may give + a msg saying type() needs exactly 3. */ + if (nargs + nkwds != 3) { + PyErr_SetString(PyExc_TypeError, + "type() takes 1 or 3 arguments"); + return NULL; + } + } + + /* Check arguments: (name, bases, dict) */ + if (!PyArg_ParseTupleAndKeywords(args, kwds, "UO!O!:type", kwlist, + &name, + &PyTuple_Type, &bases, + &PyDict_Type, &dict)) + return NULL; + + /* Determine the proper metatype to deal with this, + and check for metatype conflicts while we're at it. + Note that if some other metatype wins to contract, + it's possible that its instances are not types. */ + nbases = PyTuple_GET_SIZE(bases); + winner = metatype; + for (i = 0; i < nbases; i++) { + tmp = PyTuple_GET_ITEM(bases, i); + tmptype = Py_TYPE(tmp); + if (PyType_IsSubtype(winner, tmptype)) + continue; + if (PyType_IsSubtype(tmptype, winner)) { + winner = tmptype; + continue; + } + PyErr_SetString(PyExc_TypeError, + "metaclass conflict: " + "the metaclass of a derived class " + "must be a (non-strict) subclass " + "of the metaclasses of all its bases"); + return NULL; + } + if (winner != metatype) { + if (winner->tp_new != type_new) /* Pass it to the winner */ + return winner->tp_new(winner, args, kwds); + metatype = winner; + } + + /* Adjust for empty tuple bases */ + if (nbases == 0) { + bases = PyTuple_Pack(1, &PyBaseObject_Type); + if (bases == NULL) + return NULL; + nbases = 1; + } + else + Py_INCREF(bases); + + /* XXX From here until type is allocated, "return NULL" leaks bases! */ + + /* Calculate best base, and check that all bases are type objects */ + base = best_base(bases); + if (base == NULL) { + Py_DECREF(bases); + return NULL; + } + if (!PyType_HasFeature(base, Py_TPFLAGS_BASETYPE)) { + PyErr_Format(PyExc_TypeError, + "type '%.100s' is not an acceptable base type", + base->tp_name); + Py_DECREF(bases); + return NULL; + } + + /* Check for a __slots__ sequence variable in dict, and count it */ + slots = PyDict_GetItemString(dict, "__slots__"); + nslots = 0; + add_dict = 0; + add_weak = 0; + may_add_dict = base->tp_dictoffset == 0; + may_add_weak = base->tp_weaklistoffset == 0 && base->tp_itemsize == 0; + if (slots == NULL) { + if (may_add_dict) { + add_dict++; + } + if (may_add_weak) { + add_weak++; + } + } + else { + /* Have slots */ + + /* Make it into a tuple */ + if (PyUnicode_Check(slots)) + slots = PyTuple_Pack(1, slots); + else + slots = PySequence_Tuple(slots); + if (slots == NULL) { + Py_DECREF(bases); + return NULL; + } + assert(PyTuple_Check(slots)); + + /* Are slots allowed? */ + nslots = PyTuple_GET_SIZE(slots); + if (nslots > 0 && base->tp_itemsize != 0) { + PyErr_Format(PyExc_TypeError, + "nonempty __slots__ " + "not supported for subtype of '%s'", + base->tp_name); + bad_slots: + Py_DECREF(bases); + Py_DECREF(slots); + return NULL; + } + + /* Check for valid slot names and two special cases */ + for (i = 0; i < nslots; i++) { + PyObject *tmp = PyTuple_GET_ITEM(slots, i); + if (!valid_identifier(tmp)) + goto bad_slots; + assert(PyUnicode_Check(tmp)); + if (PyUnicode_CompareWithASCIIString(tmp, "__dict__") == 0) { + if (!may_add_dict || add_dict) { + PyErr_SetString(PyExc_TypeError, + "__dict__ slot disallowed: " + "we already got one"); + goto bad_slots; + } + add_dict++; + } + if (PyUnicode_CompareWithASCIIString(tmp, "__weakref__") == 0) { + if (!may_add_weak || add_weak) { + PyErr_SetString(PyExc_TypeError, + "__weakref__ slot disallowed: " + "either we already got one, " + "or __itemsize__ != 0"); + goto bad_slots; + } + add_weak++; + } + } + + /* Copy slots into a list, mangle names and sort them. + Sorted names are needed for __class__ assignment. + Convert them back to tuple at the end. + */ + newslots = PyList_New(nslots - add_dict - add_weak); + if (newslots == NULL) + goto bad_slots; + for (i = j = 0; i < nslots; i++) { + tmp = PyTuple_GET_ITEM(slots, i); + if ((add_dict && + PyUnicode_CompareWithASCIIString(tmp, "__dict__") == 0) || + (add_weak && + PyUnicode_CompareWithASCIIString(tmp, "__weakref__") == 0)) + continue; + tmp =_Py_Mangle(name, tmp); + if (!tmp) + goto bad_slots; + PyList_SET_ITEM(newslots, j, tmp); + j++; + } + assert(j == nslots - add_dict - add_weak); + nslots = j; + Py_DECREF(slots); + if (PyList_Sort(newslots) == -1) { + Py_DECREF(bases); + Py_DECREF(newslots); + return NULL; + } + slots = PyList_AsTuple(newslots); + Py_DECREF(newslots); + if (slots == NULL) { + Py_DECREF(bases); + return NULL; + } + + /* Secondary bases may provide weakrefs or dict */ + if (nbases > 1 && + ((may_add_dict && !add_dict) || + (may_add_weak && !add_weak))) { + for (i = 0; i < nbases; i++) { + tmp = PyTuple_GET_ITEM(bases, i); + if (tmp == (PyObject *)base) + continue; /* Skip primary base */ + assert(PyType_Check(tmp)); + tmptype = (PyTypeObject *)tmp; + if (may_add_dict && !add_dict && + tmptype->tp_dictoffset != 0) + add_dict++; + if (may_add_weak && !add_weak && + tmptype->tp_weaklistoffset != 0) + add_weak++; + if (may_add_dict && !add_dict) + continue; + if (may_add_weak && !add_weak) + continue; + /* Nothing more to check */ + break; + } + } + } - /* Put the proper slots in place */ - fixup_slot_dispatchers(type); + /* XXX From here until type is safely allocated, + "return NULL" may leak slots! */ - return (PyObject *)type; + /* Allocate the type object */ + type = (PyTypeObject *)metatype->tp_alloc(metatype, nslots); + if (type == NULL) { + Py_XDECREF(slots); + Py_DECREF(bases); + return NULL; + } + + /* Keep name and slots alive in the extended type object */ + et = (PyHeapTypeObject *)type; + Py_INCREF(name); + et->ht_name = name; + et->ht_slots = slots; + + /* Initialize tp_flags */ + type->tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HEAPTYPE | + Py_TPFLAGS_BASETYPE; + if (base->tp_flags & Py_TPFLAGS_HAVE_GC) + type->tp_flags |= Py_TPFLAGS_HAVE_GC; + + /* Initialize essential fields */ + type->tp_as_number = &et->as_number; + type->tp_as_sequence = &et->as_sequence; + type->tp_as_mapping = &et->as_mapping; + type->tp_as_buffer = &et->as_buffer; + type->tp_name = _PyUnicode_AsString(name); + if (!type->tp_name) { + Py_DECREF(type); + return NULL; + } + + /* Set tp_base and tp_bases */ + type->tp_bases = bases; + Py_INCREF(base); + type->tp_base = base; + + /* Initialize tp_dict from passed-in dict */ + type->tp_dict = dict = PyDict_Copy(dict); + if (dict == NULL) { + Py_DECREF(type); + return NULL; + } + + /* Set __module__ in the dict */ + if (PyDict_GetItemString(dict, "__module__") == NULL) { + tmp = PyEval_GetGlobals(); + if (tmp != NULL) { + tmp = PyDict_GetItemString(tmp, "__name__"); + if (tmp != NULL) { + if (PyDict_SetItemString(dict, "__module__", + tmp) < 0) + return NULL; + } + } + } + + /* Set tp_doc to a copy of dict['__doc__'], if the latter is there + and is a string. The __doc__ accessor will first look for tp_doc; + if that fails, it will still look into __dict__. + */ + { + PyObject *doc = PyDict_GetItemString(dict, "__doc__"); + if (doc != NULL && PyUnicode_Check(doc)) { + Py_ssize_t len; + char *doc_str; + char *tp_doc; + + doc_str = _PyUnicode_AsString(doc); + if (doc_str == NULL) { + Py_DECREF(type); + return NULL; + } + /* Silently truncate the docstring if it contains null bytes. */ + len = strlen(doc_str); + tp_doc = (char *)PyObject_MALLOC(len + 1); + if (tp_doc == NULL) { + Py_DECREF(type); + return NULL; + } + memcpy(tp_doc, doc_str, len + 1); + type->tp_doc = tp_doc; + } + } + + /* Special-case __new__: if it's a plain function, + make it a static function */ + tmp = PyDict_GetItemString(dict, "__new__"); + if (tmp != NULL && PyFunction_Check(tmp)) { + tmp = PyStaticMethod_New(tmp); + if (tmp == NULL) { + Py_DECREF(type); + return NULL; + } + PyDict_SetItemString(dict, "__new__", tmp); + Py_DECREF(tmp); + } + + /* Add descriptors for custom slots from __slots__, or for __dict__ */ + mp = PyHeapType_GET_MEMBERS(et); + slotoffset = base->tp_basicsize; + if (slots != NULL) { + for (i = 0; i < nslots; i++, mp++) { + mp->name = _PyUnicode_AsString( + PyTuple_GET_ITEM(slots, i)); + mp->type = T_OBJECT_EX; + mp->offset = slotoffset; + + /* __dict__ and __weakref__ are already filtered out */ + assert(strcmp(mp->name, "__dict__") != 0); + assert(strcmp(mp->name, "__weakref__") != 0); + + slotoffset += sizeof(PyObject *); + } + } + if (add_dict) { + if (base->tp_itemsize) + type->tp_dictoffset = -(long)sizeof(PyObject *); + else + type->tp_dictoffset = slotoffset; + slotoffset += sizeof(PyObject *); + } + if (add_weak) { + assert(!base->tp_itemsize); + type->tp_weaklistoffset = slotoffset; + slotoffset += sizeof(PyObject *); + } + type->tp_basicsize = slotoffset; + type->tp_itemsize = base->tp_itemsize; + type->tp_members = PyHeapType_GET_MEMBERS(et); + + if (type->tp_weaklistoffset && type->tp_dictoffset) + type->tp_getset = subtype_getsets_full; + else if (type->tp_weaklistoffset && !type->tp_dictoffset) + type->tp_getset = subtype_getsets_weakref_only; + else if (!type->tp_weaklistoffset && type->tp_dictoffset) + type->tp_getset = subtype_getsets_dict_only; + else + type->tp_getset = NULL; + + /* Special case some slots */ + if (type->tp_dictoffset != 0 || nslots > 0) { + if (base->tp_getattr == NULL && base->tp_getattro == NULL) + type->tp_getattro = PyObject_GenericGetAttr; + if (base->tp_setattr == NULL && base->tp_setattro == NULL) + type->tp_setattro = PyObject_GenericSetAttr; + } + type->tp_dealloc = subtype_dealloc; + + /* Enable GC unless there are really no instance variables possible */ + if (!(type->tp_basicsize == sizeof(PyObject) && + type->tp_itemsize == 0)) + type->tp_flags |= Py_TPFLAGS_HAVE_GC; + + /* Always override allocation strategy to use regular heap */ + type->tp_alloc = PyType_GenericAlloc; + if (type->tp_flags & Py_TPFLAGS_HAVE_GC) { + type->tp_free = PyObject_GC_Del; + type->tp_traverse = subtype_traverse; + type->tp_clear = subtype_clear; + } + else + type->tp_free = PyObject_Del; + + /* Initialize the rest */ + if (PyType_Ready(type) < 0) { + Py_DECREF(type); + return NULL; + } + + /* Put the proper slots in place */ + fixup_slot_dispatchers(type); + + return (PyObject *)type; } /* Internal API to look for a name through the MRO. @@ -2296,50 +2296,50 @@ PyObject * _PyType_Lookup(PyTypeObject *type, PyObject *name) { - Py_ssize_t i, n; - PyObject *mro, *res, *base, *dict; - unsigned int h; - - if (MCACHE_CACHEABLE_NAME(name) && - PyType_HasFeature(type, Py_TPFLAGS_VALID_VERSION_TAG)) { - /* fast path */ - h = MCACHE_HASH_METHOD(type, name); - if (method_cache[h].version == type->tp_version_tag && - method_cache[h].name == name) - return method_cache[h].value; - } - - /* Look in tp_dict of types in MRO */ - mro = type->tp_mro; - - /* If mro is NULL, the type is either not yet initialized - by PyType_Ready(), or already cleared by type_clear(). - Either way the safest thing to do is to return NULL. */ - if (mro == NULL) - return NULL; - - res = NULL; - assert(PyTuple_Check(mro)); - n = PyTuple_GET_SIZE(mro); - for (i = 0; i < n; i++) { - base = PyTuple_GET_ITEM(mro, i); - assert(PyType_Check(base)); - dict = ((PyTypeObject *)base)->tp_dict; - assert(dict && PyDict_Check(dict)); - res = PyDict_GetItem(dict, name); - if (res != NULL) - break; - } - - if (MCACHE_CACHEABLE_NAME(name) && assign_version_tag(type)) { - h = MCACHE_HASH_METHOD(type, name); - method_cache[h].version = type->tp_version_tag; - method_cache[h].value = res; /* borrowed */ - Py_INCREF(name); - Py_DECREF(method_cache[h].name); - method_cache[h].name = name; - } - return res; + Py_ssize_t i, n; + PyObject *mro, *res, *base, *dict; + unsigned int h; + + if (MCACHE_CACHEABLE_NAME(name) && + PyType_HasFeature(type, Py_TPFLAGS_VALID_VERSION_TAG)) { + /* fast path */ + h = MCACHE_HASH_METHOD(type, name); + if (method_cache[h].version == type->tp_version_tag && + method_cache[h].name == name) + return method_cache[h].value; + } + + /* Look in tp_dict of types in MRO */ + mro = type->tp_mro; + + /* If mro is NULL, the type is either not yet initialized + by PyType_Ready(), or already cleared by type_clear(). + Either way the safest thing to do is to return NULL. */ + if (mro == NULL) + return NULL; + + res = NULL; + assert(PyTuple_Check(mro)); + n = PyTuple_GET_SIZE(mro); + for (i = 0; i < n; i++) { + base = PyTuple_GET_ITEM(mro, i); + assert(PyType_Check(base)); + dict = ((PyTypeObject *)base)->tp_dict; + assert(dict && PyDict_Check(dict)); + res = PyDict_GetItem(dict, name); + if (res != NULL) + break; + } + + if (MCACHE_CACHEABLE_NAME(name) && assign_version_tag(type)) { + h = MCACHE_HASH_METHOD(type, name); + method_cache[h].version = type->tp_version_tag; + method_cache[h].value = res; /* borrowed */ + Py_INCREF(name); + Py_DECREF(method_cache[h].name); + method_cache[h].name = name; + } + return res; } /* This is similar to PyObject_GenericGetAttr(), @@ -2347,166 +2347,166 @@ static PyObject * type_getattro(PyTypeObject *type, PyObject *name) { - PyTypeObject *metatype = Py_TYPE(type); - PyObject *meta_attribute, *attribute; - descrgetfunc meta_get; - - /* Initialize this type (we'll assume the metatype is initialized) */ - if (type->tp_dict == NULL) { - if (PyType_Ready(type) < 0) - return NULL; - } - - /* No readable descriptor found yet */ - meta_get = NULL; - - /* Look for the attribute in the metatype */ - meta_attribute = _PyType_Lookup(metatype, name); - - if (meta_attribute != NULL) { - meta_get = Py_TYPE(meta_attribute)->tp_descr_get; - - if (meta_get != NULL && PyDescr_IsData(meta_attribute)) { - /* Data descriptors implement tp_descr_set to intercept - * 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); - } - Py_INCREF(meta_attribute); - } - - /* No data descriptor found on metatype. Look in tp_dict of this - * type and its bases */ - attribute = _PyType_Lookup(type, name); - if (attribute != NULL) { - /* Implement descriptor functionality, if any */ - descrgetfunc 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); - } - - Py_INCREF(attribute); - return attribute; - } - - /* No attribute found in local __dict__ (or bases): use the - * descriptor from the metatype, if any */ - if (meta_get != NULL) { - PyObject *res; - res = meta_get(meta_attribute, (PyObject *)type, - (PyObject *)metatype); - Py_DECREF(meta_attribute); - return res; - } - - /* If an ordinary attribute was found on the metatype, return it now */ - if (meta_attribute != NULL) { - return meta_attribute; - } - - /* Give up */ - PyErr_Format(PyExc_AttributeError, - "type object '%.50s' has no attribute '%U'", - type->tp_name, name); - return NULL; + PyTypeObject *metatype = Py_TYPE(type); + PyObject *meta_attribute, *attribute; + descrgetfunc meta_get; + + /* Initialize this type (we'll assume the metatype is initialized) */ + if (type->tp_dict == NULL) { + if (PyType_Ready(type) < 0) + return NULL; + } + + /* No readable descriptor found yet */ + meta_get = NULL; + + /* Look for the attribute in the metatype */ + meta_attribute = _PyType_Lookup(metatype, name); + + if (meta_attribute != NULL) { + meta_get = Py_TYPE(meta_attribute)->tp_descr_get; + + if (meta_get != NULL && PyDescr_IsData(meta_attribute)) { + /* Data descriptors implement tp_descr_set to intercept + * 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); + } + Py_INCREF(meta_attribute); + } + + /* No data descriptor found on metatype. Look in tp_dict of this + * type and its bases */ + attribute = _PyType_Lookup(type, name); + if (attribute != NULL) { + /* Implement descriptor functionality, if any */ + descrgetfunc 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); + } + + Py_INCREF(attribute); + return attribute; + } + + /* No attribute found in local __dict__ (or bases): use the + * descriptor from the metatype, if any */ + if (meta_get != NULL) { + PyObject *res; + res = meta_get(meta_attribute, (PyObject *)type, + (PyObject *)metatype); + Py_DECREF(meta_attribute); + return res; + } + + /* If an ordinary attribute was found on the metatype, return it now */ + if (meta_attribute != NULL) { + return meta_attribute; + } + + /* Give up */ + PyErr_Format(PyExc_AttributeError, + "type object '%.50s' has no attribute '%U'", + type->tp_name, name); + return NULL; } static int type_setattro(PyTypeObject *type, PyObject *name, PyObject *value) { - if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE)) { - PyErr_Format( - PyExc_TypeError, - "can't set attributes of built-in/extension type '%s'", - type->tp_name); - return -1; - } - if (PyObject_GenericSetAttr((PyObject *)type, name, value) < 0) - return -1; - return update_slot(type, name); + if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE)) { + PyErr_Format( + PyExc_TypeError, + "can't set attributes of built-in/extension type '%s'", + type->tp_name); + return -1; + } + if (PyObject_GenericSetAttr((PyObject *)type, name, value) < 0) + return -1; + return update_slot(type, name); } static void type_dealloc(PyTypeObject *type) { - PyHeapTypeObject *et; + PyHeapTypeObject *et; - /* Assert this is a heap-allocated type object */ - assert(type->tp_flags & Py_TPFLAGS_HEAPTYPE); - _PyObject_GC_UNTRACK(type); - PyObject_ClearWeakRefs((PyObject *)type); - et = (PyHeapTypeObject *)type; - Py_XDECREF(type->tp_base); - Py_XDECREF(type->tp_dict); - Py_XDECREF(type->tp_bases); - Py_XDECREF(type->tp_mro); - Py_XDECREF(type->tp_cache); - Py_XDECREF(type->tp_subclasses); - /* A type's tp_doc is heap allocated, unlike the tp_doc slots - * of most other objects. It's okay to cast it to char *. - */ - PyObject_Free((char *)type->tp_doc); - Py_XDECREF(et->ht_name); - Py_XDECREF(et->ht_slots); - Py_TYPE(type)->tp_free((PyObject *)type); + /* Assert this is a heap-allocated type object */ + assert(type->tp_flags & Py_TPFLAGS_HEAPTYPE); + _PyObject_GC_UNTRACK(type); + PyObject_ClearWeakRefs((PyObject *)type); + et = (PyHeapTypeObject *)type; + Py_XDECREF(type->tp_base); + Py_XDECREF(type->tp_dict); + Py_XDECREF(type->tp_bases); + Py_XDECREF(type->tp_mro); + Py_XDECREF(type->tp_cache); + Py_XDECREF(type->tp_subclasses); + /* A type's tp_doc is heap allocated, unlike the tp_doc slots + * of most other objects. It's okay to cast it to char *. + */ + PyObject_Free((char *)type->tp_doc); + Py_XDECREF(et->ht_name); + Py_XDECREF(et->ht_slots); + Py_TYPE(type)->tp_free((PyObject *)type); } static PyObject * type_subclasses(PyTypeObject *type, PyObject *args_ignored) { - PyObject *list, *raw, *ref; - Py_ssize_t i, n; + PyObject *list, *raw, *ref; + Py_ssize_t i, n; - list = PyList_New(0); - if (list == NULL) - return NULL; - raw = type->tp_subclasses; - if (raw == NULL) - return list; - assert(PyList_Check(raw)); - n = PyList_GET_SIZE(raw); - for (i = 0; i < n; i++) { - ref = PyList_GET_ITEM(raw, i); - assert(PyWeakref_CheckRef(ref)); - ref = PyWeakref_GET_OBJECT(ref); - if (ref != Py_None) { - if (PyList_Append(list, ref) < 0) { - Py_DECREF(list); - return NULL; - } - } - } - return list; + list = PyList_New(0); + if (list == NULL) + return NULL; + raw = type->tp_subclasses; + if (raw == NULL) + return list; + assert(PyList_Check(raw)); + n = PyList_GET_SIZE(raw); + for (i = 0; i < n; i++) { + ref = PyList_GET_ITEM(raw, i); + assert(PyWeakref_CheckRef(ref)); + ref = PyWeakref_GET_OBJECT(ref); + if (ref != Py_None) { + if (PyList_Append(list, ref) < 0) { + Py_DECREF(list); + return NULL; + } + } + } + return list; } static PyObject * type_prepare(PyObject *self, PyObject *args, PyObject *kwds) { - return PyDict_New(); + return PyDict_New(); } static PyMethodDef type_methods[] = { - {"mro", (PyCFunction)mro_external, METH_NOARGS, - PyDoc_STR("mro() -> list\nreturn a type's method resolution order")}, - {"__subclasses__", (PyCFunction)type_subclasses, METH_NOARGS, - PyDoc_STR("__subclasses__() -> list of immediate subclasses")}, - {"__prepare__", (PyCFunction)type_prepare, - METH_VARARGS | METH_KEYWORDS | METH_CLASS, - PyDoc_STR("__prepare__() -> dict\n" - "used to create the namespace for the class statement")}, - {"__instancecheck__", type___instancecheck__, METH_O, - PyDoc_STR("__instancecheck__() -> check if an object is an instance")}, - {"__subclasscheck__", type___subclasscheck__, METH_O, - PyDoc_STR("__subclasschck__ -> check if an class is a subclass")}, - {0} + {"mro", (PyCFunction)mro_external, METH_NOARGS, + PyDoc_STR("mro() -> list\nreturn a type's method resolution order")}, + {"__subclasses__", (PyCFunction)type_subclasses, METH_NOARGS, + PyDoc_STR("__subclasses__() -> list of immediate subclasses")}, + {"__prepare__", (PyCFunction)type_prepare, + METH_VARARGS | METH_KEYWORDS | METH_CLASS, + PyDoc_STR("__prepare__() -> dict\n" + "used to create the namespace for the class statement")}, + {"__instancecheck__", type___instancecheck__, METH_O, + PyDoc_STR("__instancecheck__() -> check if an object is an instance")}, + {"__subclasscheck__", type___subclasscheck__, METH_O, + PyDoc_STR("__subclasschck__ -> check if an class is a subclass")}, + {0} }; PyDoc_STRVAR(type_doc, @@ -2516,109 +2516,109 @@ static int type_traverse(PyTypeObject *type, visitproc visit, void *arg) { - /* Because of type_is_gc(), the collector only calls this - for heaptypes. */ - assert(type->tp_flags & Py_TPFLAGS_HEAPTYPE); - - Py_VISIT(type->tp_dict); - Py_VISIT(type->tp_cache); - Py_VISIT(type->tp_mro); - Py_VISIT(type->tp_bases); - Py_VISIT(type->tp_base); - - /* There's no need to visit type->tp_subclasses or - ((PyHeapTypeObject *)type)->ht_slots, because they can't be involved - in cycles; tp_subclasses is a list of weak references, - and slots is a tuple of strings. */ + /* Because of type_is_gc(), the collector only calls this + for heaptypes. */ + assert(type->tp_flags & Py_TPFLAGS_HEAPTYPE); + + Py_VISIT(type->tp_dict); + Py_VISIT(type->tp_cache); + Py_VISIT(type->tp_mro); + Py_VISIT(type->tp_bases); + Py_VISIT(type->tp_base); + + /* There's no need to visit type->tp_subclasses or + ((PyHeapTypeObject *)type)->ht_slots, because they can't be involved + in cycles; tp_subclasses is a list of weak references, + and slots is a tuple of strings. */ - return 0; + return 0; } static int type_clear(PyTypeObject *type) { - /* Because of type_is_gc(), the collector only calls this - for heaptypes. */ - assert(type->tp_flags & Py_TPFLAGS_HEAPTYPE); - - /* The only field we need to clear is tp_mro, which is part of a - hard cycle (its first element is the class itself) that won't - be broken otherwise (it's a tuple and tuples don't have a - tp_clear handler). None of the other fields need to be - cleared, and here's why: - - tp_dict: - It is a dict, so the collector will call its tp_clear. - - tp_cache: - Not used; if it were, it would be a dict. - - tp_bases, tp_base: - If these are involved in a cycle, there must be at least - one other, mutable object in the cycle, e.g. a base - class's dict; the cycle will be broken that way. - - tp_subclasses: - A list of weak references can't be part of a cycle; and - lists have their own tp_clear. - - slots (in PyHeapTypeObject): - A tuple of strings can't be part of a cycle. - */ + /* Because of type_is_gc(), the collector only calls this + for heaptypes. */ + assert(type->tp_flags & Py_TPFLAGS_HEAPTYPE); + + /* The only field we need to clear is tp_mro, which is part of a + hard cycle (its first element is the class itself) that won't + be broken otherwise (it's a tuple and tuples don't have a + tp_clear handler). None of the other fields need to be + cleared, and here's why: + + tp_dict: + It is a dict, so the collector will call its tp_clear. + + tp_cache: + Not used; if it were, it would be a dict. + + tp_bases, tp_base: + If these are involved in a cycle, there must be at least + one other, mutable object in the cycle, e.g. a base + class's dict; the cycle will be broken that way. + + tp_subclasses: + A list of weak references can't be part of a cycle; and + lists have their own tp_clear. + + slots (in PyHeapTypeObject): + A tuple of strings can't be part of a cycle. + */ - Py_CLEAR(type->tp_mro); + Py_CLEAR(type->tp_mro); - return 0; + return 0; } static int type_is_gc(PyTypeObject *type) { - return type->tp_flags & Py_TPFLAGS_HEAPTYPE; + return type->tp_flags & Py_TPFLAGS_HEAPTYPE; } PyTypeObject PyType_Type = { - PyVarObject_HEAD_INIT(&PyType_Type, 0) - "type", /* tp_name */ - sizeof(PyHeapTypeObject), /* tp_basicsize */ - sizeof(PyMemberDef), /* tp_itemsize */ - (destructor)type_dealloc, /* tp_dealloc */ - 0, /* tp_print */ - 0, /* tp_getattr */ - 0, /* tp_setattr */ - 0, /* tp_reserved */ - (reprfunc)type_repr, /* tp_repr */ - 0, /* tp_as_number */ - 0, /* tp_as_sequence */ - 0, /* tp_as_mapping */ - 0, /* tp_hash */ - (ternaryfunc)type_call, /* tp_call */ - 0, /* tp_str */ - (getattrofunc)type_getattro, /* tp_getattro */ - (setattrofunc)type_setattro, /* tp_setattro */ - 0, /* tp_as_buffer */ - Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC | - Py_TPFLAGS_BASETYPE | Py_TPFLAGS_TYPE_SUBCLASS, /* tp_flags */ - type_doc, /* tp_doc */ - (traverseproc)type_traverse, /* tp_traverse */ - (inquiry)type_clear, /* tp_clear */ - 0, /* tp_richcompare */ - offsetof(PyTypeObject, tp_weaklist), /* tp_weaklistoffset */ - 0, /* tp_iter */ - 0, /* tp_iternext */ - type_methods, /* tp_methods */ - type_members, /* tp_members */ - type_getsets, /* tp_getset */ - 0, /* tp_base */ - 0, /* tp_dict */ - 0, /* tp_descr_get */ - 0, /* tp_descr_set */ - offsetof(PyTypeObject, tp_dict), /* tp_dictoffset */ - type_init, /* tp_init */ - 0, /* tp_alloc */ - type_new, /* tp_new */ - PyObject_GC_Del, /* tp_free */ - (inquiry)type_is_gc, /* tp_is_gc */ + PyVarObject_HEAD_INIT(&PyType_Type, 0) + "type", /* tp_name */ + sizeof(PyHeapTypeObject), /* tp_basicsize */ + sizeof(PyMemberDef), /* tp_itemsize */ + (destructor)type_dealloc, /* tp_dealloc */ + 0, /* tp_print */ + 0, /* tp_getattr */ + 0, /* tp_setattr */ + 0, /* tp_reserved */ + (reprfunc)type_repr, /* tp_repr */ + 0, /* tp_as_number */ + 0, /* tp_as_sequence */ + 0, /* tp_as_mapping */ + 0, /* tp_hash */ + (ternaryfunc)type_call, /* tp_call */ + 0, /* tp_str */ + (getattrofunc)type_getattro, /* tp_getattro */ + (setattrofunc)type_setattro, /* tp_setattro */ + 0, /* tp_as_buffer */ + Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC | + Py_TPFLAGS_BASETYPE | Py_TPFLAGS_TYPE_SUBCLASS, /* tp_flags */ + type_doc, /* tp_doc */ + (traverseproc)type_traverse, /* tp_traverse */ + (inquiry)type_clear, /* tp_clear */ + 0, /* tp_richcompare */ + offsetof(PyTypeObject, tp_weaklist), /* tp_weaklistoffset */ + 0, /* tp_iter */ + 0, /* tp_iternext */ + type_methods, /* tp_methods */ + type_members, /* tp_members */ + type_getsets, /* tp_getset */ + 0, /* tp_base */ + 0, /* tp_dict */ + 0, /* tp_descr_get */ + 0, /* tp_descr_set */ + offsetof(PyTypeObject, tp_dict), /* tp_dictoffset */ + type_init, /* tp_init */ + 0, /* tp_alloc */ + type_new, /* tp_new */ + PyObject_GC_Del, /* tp_free */ + (inquiry)type_is_gc, /* tp_is_gc */ }; @@ -2671,318 +2671,318 @@ static int excess_args(PyObject *args, PyObject *kwds) { - return PyTuple_GET_SIZE(args) || - (kwds && PyDict_Check(kwds) && PyDict_Size(kwds)); + return PyTuple_GET_SIZE(args) || + (kwds && PyDict_Check(kwds) && PyDict_Size(kwds)); } static int object_init(PyObject *self, PyObject *args, PyObject *kwds) { - int err = 0; - if (excess_args(args, kwds)) { - PyTypeObject *type = Py_TYPE(self); - if (type->tp_init != object_init && - type->tp_new != object_new) - { - err = PyErr_WarnEx(PyExc_DeprecationWarning, - "object.__init__() takes no parameters", - 1); - } - else if (type->tp_init != object_init || - type->tp_new == object_new) - { - PyErr_SetString(PyExc_TypeError, - "object.__init__() takes no parameters"); - err = -1; - } - } - return err; + int err = 0; + if (excess_args(args, kwds)) { + PyTypeObject *type = Py_TYPE(self); + if (type->tp_init != object_init && + type->tp_new != object_new) + { + err = PyErr_WarnEx(PyExc_DeprecationWarning, + "object.__init__() takes no parameters", + 1); + } + else if (type->tp_init != object_init || + type->tp_new == object_new) + { + PyErr_SetString(PyExc_TypeError, + "object.__init__() takes no parameters"); + err = -1; + } + } + return err; } static PyObject * object_new(PyTypeObject *type, PyObject *args, PyObject *kwds) { - int err = 0; - if (excess_args(args, kwds)) { - if (type->tp_new != object_new && - type->tp_init != object_init) - { - err = PyErr_WarnEx(PyExc_DeprecationWarning, - "object.__new__() takes no parameters", - 1); - } - else if (type->tp_new != object_new || - type->tp_init == object_init) - { - PyErr_SetString(PyExc_TypeError, - "object.__new__() takes no parameters"); - err = -1; - } - } - if (err < 0) - return NULL; - - if (type->tp_flags & Py_TPFLAGS_IS_ABSTRACT) { - static PyObject *comma = NULL; - PyObject *abstract_methods = NULL; - PyObject *builtins; - PyObject *sorted; - PyObject *sorted_methods = NULL; - PyObject *joined = NULL; - - /* Compute ", ".join(sorted(type.__abstractmethods__)) - into joined. */ - abstract_methods = type_abstractmethods(type, NULL); - if (abstract_methods == NULL) - goto error; - builtins = PyEval_GetBuiltins(); - if (builtins == NULL) - goto error; - sorted = PyDict_GetItemString(builtins, "sorted"); - if (sorted == NULL) - goto error; - sorted_methods = PyObject_CallFunctionObjArgs(sorted, - abstract_methods, - NULL); - if (sorted_methods == NULL) - goto error; - if (comma == NULL) { - comma = PyUnicode_InternFromString(", "); - if (comma == NULL) - goto error; - } - joined = PyObject_CallMethod(comma, "join", - "O", sorted_methods); - if (joined == NULL) - goto error; - - PyErr_Format(PyExc_TypeError, - "Can't instantiate abstract class %s " - "with abstract methods %U", - type->tp_name, - joined); - error: - Py_XDECREF(joined); - Py_XDECREF(sorted_methods); - Py_XDECREF(abstract_methods); - return NULL; - } - return type->tp_alloc(type, 0); + int err = 0; + if (excess_args(args, kwds)) { + if (type->tp_new != object_new && + type->tp_init != object_init) + { + err = PyErr_WarnEx(PyExc_DeprecationWarning, + "object.__new__() takes no parameters", + 1); + } + else if (type->tp_new != object_new || + type->tp_init == object_init) + { + PyErr_SetString(PyExc_TypeError, + "object.__new__() takes no parameters"); + err = -1; + } + } + if (err < 0) + return NULL; + + if (type->tp_flags & Py_TPFLAGS_IS_ABSTRACT) { + static PyObject *comma = NULL; + PyObject *abstract_methods = NULL; + PyObject *builtins; + PyObject *sorted; + PyObject *sorted_methods = NULL; + PyObject *joined = NULL; + + /* Compute ", ".join(sorted(type.__abstractmethods__)) + into joined. */ + abstract_methods = type_abstractmethods(type, NULL); + if (abstract_methods == NULL) + goto error; + builtins = PyEval_GetBuiltins(); + if (builtins == NULL) + goto error; + sorted = PyDict_GetItemString(builtins, "sorted"); + if (sorted == NULL) + goto error; + sorted_methods = PyObject_CallFunctionObjArgs(sorted, + abstract_methods, + NULL); + if (sorted_methods == NULL) + goto error; + if (comma == NULL) { + comma = PyUnicode_InternFromString(", "); + if (comma == NULL) + goto error; + } + joined = PyObject_CallMethod(comma, "join", + "O", sorted_methods); + if (joined == NULL) + goto error; + + PyErr_Format(PyExc_TypeError, + "Can't instantiate abstract class %s " + "with abstract methods %U", + type->tp_name, + joined); + error: + Py_XDECREF(joined); + Py_XDECREF(sorted_methods); + Py_XDECREF(abstract_methods); + return NULL; + } + return type->tp_alloc(type, 0); } static void object_dealloc(PyObject *self) { - Py_TYPE(self)->tp_free(self); + Py_TYPE(self)->tp_free(self); } static PyObject * object_repr(PyObject *self) { - PyTypeObject *type; - PyObject *mod, *name, *rtn; + PyTypeObject *type; + PyObject *mod, *name, *rtn; - type = Py_TYPE(self); - mod = type_module(type, NULL); - if (mod == NULL) - PyErr_Clear(); - else if (!PyUnicode_Check(mod)) { - Py_DECREF(mod); - mod = NULL; - } - name = type_name(type, NULL); - if (name == NULL) - return NULL; - if (mod != NULL && PyUnicode_CompareWithASCIIString(mod, "builtins")) - rtn = PyUnicode_FromFormat("<%U.%U object at %p>", mod, name, self); - else - rtn = PyUnicode_FromFormat("<%s object at %p>", - type->tp_name, self); - Py_XDECREF(mod); - Py_DECREF(name); - return rtn; + type = Py_TYPE(self); + mod = type_module(type, NULL); + if (mod == NULL) + PyErr_Clear(); + else if (!PyUnicode_Check(mod)) { + Py_DECREF(mod); + mod = NULL; + } + name = type_name(type, NULL); + if (name == NULL) + return NULL; + if (mod != NULL && PyUnicode_CompareWithASCIIString(mod, "builtins")) + rtn = PyUnicode_FromFormat("<%U.%U object at %p>", mod, name, self); + else + rtn = PyUnicode_FromFormat("<%s object at %p>", + type->tp_name, self); + Py_XDECREF(mod); + Py_DECREF(name); + return rtn; } static PyObject * object_str(PyObject *self) { - unaryfunc f; + unaryfunc f; - f = Py_TYPE(self)->tp_repr; - if (f == NULL) - f = object_repr; - return f(self); + f = Py_TYPE(self)->tp_repr; + if (f == NULL) + f = object_repr; + return f(self); } static PyObject * object_richcompare(PyObject *self, PyObject *other, int op) { - PyObject *res; + PyObject *res; - switch (op) { + switch (op) { - case Py_EQ: - /* Return NotImplemented instead of False, so if two - objects are compared, both get a chance at the - comparison. See issue #1393. */ - res = (self == other) ? Py_True : Py_NotImplemented; - Py_INCREF(res); - break; - - case Py_NE: - /* By default, != returns the opposite of ==, - unless the latter returns NotImplemented. */ - res = PyObject_RichCompare(self, other, Py_EQ); - if (res != NULL && res != Py_NotImplemented) { - int ok = PyObject_IsTrue(res); - Py_DECREF(res); - if (ok < 0) - res = NULL; - else { - if (ok) - res = Py_False; - else - res = Py_True; - Py_INCREF(res); - } - } - break; - - default: - res = Py_NotImplemented; - Py_INCREF(res); - break; - } + case Py_EQ: + /* Return NotImplemented instead of False, so if two + objects are compared, both get a chance at the + comparison. See issue #1393. */ + res = (self == other) ? Py_True : Py_NotImplemented; + Py_INCREF(res); + break; + + case Py_NE: + /* By default, != returns the opposite of ==, + unless the latter returns NotImplemented. */ + res = PyObject_RichCompare(self, other, Py_EQ); + if (res != NULL && res != Py_NotImplemented) { + int ok = PyObject_IsTrue(res); + Py_DECREF(res); + if (ok < 0) + res = NULL; + else { + if (ok) + res = Py_False; + else + res = Py_True; + Py_INCREF(res); + } + } + break; - return res; + default: + res = Py_NotImplemented; + Py_INCREF(res); + break; + } + + return res; } static PyObject * object_get_class(PyObject *self, void *closure) { - Py_INCREF(Py_TYPE(self)); - return (PyObject *)(Py_TYPE(self)); + Py_INCREF(Py_TYPE(self)); + return (PyObject *)(Py_TYPE(self)); } static int equiv_structs(PyTypeObject *a, PyTypeObject *b) { - return a == b || - (a != NULL && - b != NULL && - a->tp_basicsize == b->tp_basicsize && - a->tp_itemsize == b->tp_itemsize && - a->tp_dictoffset == b->tp_dictoffset && - a->tp_weaklistoffset == b->tp_weaklistoffset && - ((a->tp_flags & Py_TPFLAGS_HAVE_GC) == - (b->tp_flags & Py_TPFLAGS_HAVE_GC))); + return a == b || + (a != NULL && + b != NULL && + a->tp_basicsize == b->tp_basicsize && + a->tp_itemsize == b->tp_itemsize && + a->tp_dictoffset == b->tp_dictoffset && + a->tp_weaklistoffset == b->tp_weaklistoffset && + ((a->tp_flags & Py_TPFLAGS_HAVE_GC) == + (b->tp_flags & Py_TPFLAGS_HAVE_GC))); } static int same_slots_added(PyTypeObject *a, PyTypeObject *b) { - PyTypeObject *base = a->tp_base; - Py_ssize_t size; - PyObject *slots_a, *slots_b; - - if (base != b->tp_base) - return 0; - if (equiv_structs(a, base) && equiv_structs(b, base)) - return 1; - size = base->tp_basicsize; - if (a->tp_dictoffset == size && b->tp_dictoffset == size) - size += sizeof(PyObject *); - if (a->tp_weaklistoffset == size && b->tp_weaklistoffset == size) - size += sizeof(PyObject *); - - /* Check slots compliance */ - slots_a = ((PyHeapTypeObject *)a)->ht_slots; - slots_b = ((PyHeapTypeObject *)b)->ht_slots; - if (slots_a && slots_b) { - if (PyObject_RichCompareBool(slots_a, slots_b, Py_EQ) != 1) - return 0; - size += sizeof(PyObject *) * PyTuple_GET_SIZE(slots_a); - } - return size == a->tp_basicsize && size == b->tp_basicsize; + PyTypeObject *base = a->tp_base; + Py_ssize_t size; + PyObject *slots_a, *slots_b; + + if (base != b->tp_base) + return 0; + if (equiv_structs(a, base) && equiv_structs(b, base)) + return 1; + size = base->tp_basicsize; + if (a->tp_dictoffset == size && b->tp_dictoffset == size) + size += sizeof(PyObject *); + if (a->tp_weaklistoffset == size && b->tp_weaklistoffset == size) + size += sizeof(PyObject *); + + /* Check slots compliance */ + slots_a = ((PyHeapTypeObject *)a)->ht_slots; + slots_b = ((PyHeapTypeObject *)b)->ht_slots; + if (slots_a && slots_b) { + if (PyObject_RichCompareBool(slots_a, slots_b, Py_EQ) != 1) + return 0; + size += sizeof(PyObject *) * PyTuple_GET_SIZE(slots_a); + } + return size == a->tp_basicsize && size == b->tp_basicsize; } static int compatible_for_assignment(PyTypeObject* oldto, PyTypeObject* newto, char* attr) { - PyTypeObject *newbase, *oldbase; + PyTypeObject *newbase, *oldbase; - if (newto->tp_dealloc != oldto->tp_dealloc || - newto->tp_free != oldto->tp_free) - { - PyErr_Format(PyExc_TypeError, - "%s assignment: " - "'%s' deallocator differs from '%s'", - attr, - newto->tp_name, - oldto->tp_name); - return 0; - } - newbase = newto; - oldbase = oldto; - while (equiv_structs(newbase, newbase->tp_base)) - newbase = newbase->tp_base; - while (equiv_structs(oldbase, oldbase->tp_base)) - oldbase = oldbase->tp_base; - if (newbase != oldbase && - (newbase->tp_base != oldbase->tp_base || - !same_slots_added(newbase, oldbase))) { - PyErr_Format(PyExc_TypeError, - "%s assignment: " - "'%s' object layout differs from '%s'", - attr, - newto->tp_name, - oldto->tp_name); - return 0; - } + if (newto->tp_dealloc != oldto->tp_dealloc || + newto->tp_free != oldto->tp_free) + { + PyErr_Format(PyExc_TypeError, + "%s assignment: " + "'%s' deallocator differs from '%s'", + attr, + newto->tp_name, + oldto->tp_name); + return 0; + } + newbase = newto; + oldbase = oldto; + while (equiv_structs(newbase, newbase->tp_base)) + newbase = newbase->tp_base; + while (equiv_structs(oldbase, oldbase->tp_base)) + oldbase = oldbase->tp_base; + if (newbase != oldbase && + (newbase->tp_base != oldbase->tp_base || + !same_slots_added(newbase, oldbase))) { + PyErr_Format(PyExc_TypeError, + "%s assignment: " + "'%s' object layout differs from '%s'", + attr, + newto->tp_name, + oldto->tp_name); + return 0; + } - return 1; + return 1; } static int object_set_class(PyObject *self, PyObject *value, void *closure) { - PyTypeObject *oldto = Py_TYPE(self); - PyTypeObject *newto; + PyTypeObject *oldto = Py_TYPE(self); + PyTypeObject *newto; - if (value == NULL) { - PyErr_SetString(PyExc_TypeError, - "can't delete __class__ attribute"); - return -1; - } - if (!PyType_Check(value)) { - PyErr_Format(PyExc_TypeError, - "__class__ must be set to new-style class, not '%s' object", - Py_TYPE(value)->tp_name); - return -1; - } - newto = (PyTypeObject *)value; - if (!(newto->tp_flags & Py_TPFLAGS_HEAPTYPE) || - !(oldto->tp_flags & Py_TPFLAGS_HEAPTYPE)) - { - PyErr_Format(PyExc_TypeError, - "__class__ assignment: only for heap types"); - return -1; - } - if (compatible_for_assignment(newto, oldto, "__class__")) { - Py_INCREF(newto); - Py_TYPE(self) = newto; - Py_DECREF(oldto); - return 0; - } - else { - return -1; - } + if (value == NULL) { + PyErr_SetString(PyExc_TypeError, + "can't delete __class__ attribute"); + return -1; + } + if (!PyType_Check(value)) { + PyErr_Format(PyExc_TypeError, + "__class__ must be set to new-style class, not '%s' object", + Py_TYPE(value)->tp_name); + return -1; + } + newto = (PyTypeObject *)value; + if (!(newto->tp_flags & Py_TPFLAGS_HEAPTYPE) || + !(oldto->tp_flags & Py_TPFLAGS_HEAPTYPE)) + { + PyErr_Format(PyExc_TypeError, + "__class__ assignment: only for heap types"); + return -1; + } + if (compatible_for_assignment(newto, oldto, "__class__")) { + Py_INCREF(newto); + Py_TYPE(self) = newto; + Py_DECREF(oldto); + return 0; + } + else { + return -1; + } } static PyGetSetDef object_getsets[] = { - {"__class__", object_get_class, object_set_class, - PyDoc_STR("the object's class")}, - {0} + {"__class__", object_get_class, object_set_class, + PyDoc_STR("the object's class")}, + {0} }; @@ -2996,194 +2996,194 @@ static PyObject * import_copyreg(void) { - static PyObject *copyreg_str; + static PyObject *copyreg_str; - if (!copyreg_str) { - copyreg_str = PyUnicode_InternFromString("copyreg"); - if (copyreg_str == NULL) - return NULL; - } + if (!copyreg_str) { + copyreg_str = PyUnicode_InternFromString("copyreg"); + if (copyreg_str == NULL) + return NULL; + } - return PyImport_Import(copyreg_str); + return PyImport_Import(copyreg_str); } static PyObject * slotnames(PyObject *cls) { - PyObject *clsdict; - PyObject *copyreg; - PyObject *slotnames; - - if (!PyType_Check(cls)) { - Py_INCREF(Py_None); - return Py_None; - } - - clsdict = ((PyTypeObject *)cls)->tp_dict; - slotnames = PyDict_GetItemString(clsdict, "__slotnames__"); - if (slotnames != NULL && PyList_Check(slotnames)) { - Py_INCREF(slotnames); - return slotnames; - } - - copyreg = import_copyreg(); - if (copyreg == NULL) - return NULL; - - slotnames = PyObject_CallMethod(copyreg, "_slotnames", "O", cls); - Py_DECREF(copyreg); - if (slotnames != NULL && - slotnames != Py_None && - !PyList_Check(slotnames)) - { - PyErr_SetString(PyExc_TypeError, - "copyreg._slotnames didn't return a list or None"); - Py_DECREF(slotnames); - slotnames = NULL; - } + PyObject *clsdict; + PyObject *copyreg; + PyObject *slotnames; + + if (!PyType_Check(cls)) { + Py_INCREF(Py_None); + return Py_None; + } + + clsdict = ((PyTypeObject *)cls)->tp_dict; + slotnames = PyDict_GetItemString(clsdict, "__slotnames__"); + if (slotnames != NULL && PyList_Check(slotnames)) { + Py_INCREF(slotnames); + return slotnames; + } + + copyreg = import_copyreg(); + if (copyreg == NULL) + return NULL; + + slotnames = PyObject_CallMethod(copyreg, "_slotnames", "O", cls); + Py_DECREF(copyreg); + if (slotnames != NULL && + slotnames != Py_None && + !PyList_Check(slotnames)) + { + PyErr_SetString(PyExc_TypeError, + "copyreg._slotnames didn't return a list or None"); + Py_DECREF(slotnames); + slotnames = NULL; + } - return slotnames; + return slotnames; } static PyObject * reduce_2(PyObject *obj) { - PyObject *cls, *getnewargs; - PyObject *args = NULL, *args2 = NULL; - PyObject *getstate = NULL, *state = NULL, *names = NULL; - PyObject *slots = NULL, *listitems = NULL, *dictitems = NULL; - PyObject *copyreg = NULL, *newobj = NULL, *res = NULL; - Py_ssize_t i, n; - - cls = PyObject_GetAttrString(obj, "__class__"); - if (cls == NULL) - return NULL; - - getnewargs = PyObject_GetAttrString(obj, "__getnewargs__"); - if (getnewargs != NULL) { - args = PyObject_CallObject(getnewargs, NULL); - Py_DECREF(getnewargs); - if (args != NULL && !PyTuple_Check(args)) { - PyErr_Format(PyExc_TypeError, - "__getnewargs__ should return a tuple, " - "not '%.200s'", Py_TYPE(args)->tp_name); - goto end; - } - } - else { - PyErr_Clear(); - args = PyTuple_New(0); - } - if (args == NULL) - goto end; - - getstate = PyObject_GetAttrString(obj, "__getstate__"); - if (getstate != NULL) { - state = PyObject_CallObject(getstate, NULL); - Py_DECREF(getstate); - if (state == NULL) - goto end; - } - else { - PyErr_Clear(); - state = PyObject_GetAttrString(obj, "__dict__"); - if (state == NULL) { - PyErr_Clear(); - state = Py_None; - Py_INCREF(state); - } - names = slotnames(cls); - if (names == NULL) - goto end; - if (names != Py_None) { - assert(PyList_Check(names)); - slots = PyDict_New(); - if (slots == NULL) - goto end; - n = 0; - /* Can't pre-compute the list size; the list - is stored on the class so accessible to other - threads, which may be run by DECREF */ - for (i = 0; i < PyList_GET_SIZE(names); i++) { - PyObject *name, *value; - name = PyList_GET_ITEM(names, i); - value = PyObject_GetAttr(obj, name); - if (value == NULL) - PyErr_Clear(); - else { - int err = PyDict_SetItem(slots, name, - value); - Py_DECREF(value); - if (err) - goto end; - n++; - } - } - if (n) { - state = Py_BuildValue("(NO)", state, slots); - if (state == NULL) - goto end; - } - } - } - - if (!PyList_Check(obj)) { - listitems = Py_None; - Py_INCREF(listitems); - } - else { - listitems = PyObject_GetIter(obj); - if (listitems == NULL) - goto end; - } - - if (!PyDict_Check(obj)) { - dictitems = Py_None; - Py_INCREF(dictitems); - } - else { - PyObject *items = PyObject_CallMethod(obj, "items", ""); - if (items == NULL) - goto end; - dictitems = PyObject_GetIter(items); - Py_DECREF(items); - if (dictitems == NULL) - goto end; - } - - copyreg = import_copyreg(); - if (copyreg == NULL) - goto end; - newobj = PyObject_GetAttrString(copyreg, "__newobj__"); - if (newobj == NULL) - goto end; - - n = PyTuple_GET_SIZE(args); - args2 = PyTuple_New(n+1); - if (args2 == NULL) - goto end; - PyTuple_SET_ITEM(args2, 0, cls); - cls = NULL; - for (i = 0; i < n; i++) { - PyObject *v = PyTuple_GET_ITEM(args, i); - Py_INCREF(v); - PyTuple_SET_ITEM(args2, i+1, v); - } + PyObject *cls, *getnewargs; + PyObject *args = NULL, *args2 = NULL; + PyObject *getstate = NULL, *state = NULL, *names = NULL; + PyObject *slots = NULL, *listitems = NULL, *dictitems = NULL; + PyObject *copyreg = NULL, *newobj = NULL, *res = NULL; + Py_ssize_t i, n; + + cls = PyObject_GetAttrString(obj, "__class__"); + if (cls == NULL) + return NULL; + + getnewargs = PyObject_GetAttrString(obj, "__getnewargs__"); + if (getnewargs != NULL) { + args = PyObject_CallObject(getnewargs, NULL); + Py_DECREF(getnewargs); + if (args != NULL && !PyTuple_Check(args)) { + PyErr_Format(PyExc_TypeError, + "__getnewargs__ should return a tuple, " + "not '%.200s'", Py_TYPE(args)->tp_name); + goto end; + } + } + else { + PyErr_Clear(); + args = PyTuple_New(0); + } + if (args == NULL) + goto end; + + getstate = PyObject_GetAttrString(obj, "__getstate__"); + if (getstate != NULL) { + state = PyObject_CallObject(getstate, NULL); + Py_DECREF(getstate); + if (state == NULL) + goto end; + } + else { + PyErr_Clear(); + state = PyObject_GetAttrString(obj, "__dict__"); + if (state == NULL) { + PyErr_Clear(); + state = Py_None; + Py_INCREF(state); + } + names = slotnames(cls); + if (names == NULL) + goto end; + if (names != Py_None) { + assert(PyList_Check(names)); + slots = PyDict_New(); + if (slots == NULL) + goto end; + n = 0; + /* Can't pre-compute the list size; the list + is stored on the class so accessible to other + threads, which may be run by DECREF */ + for (i = 0; i < PyList_GET_SIZE(names); i++) { + PyObject *name, *value; + name = PyList_GET_ITEM(names, i); + value = PyObject_GetAttr(obj, name); + if (value == NULL) + PyErr_Clear(); + else { + int err = PyDict_SetItem(slots, name, + value); + Py_DECREF(value); + if (err) + goto end; + n++; + } + } + if (n) { + state = Py_BuildValue("(NO)", state, slots); + if (state == NULL) + goto end; + } + } + } + + if (!PyList_Check(obj)) { + listitems = Py_None; + Py_INCREF(listitems); + } + else { + listitems = PyObject_GetIter(obj); + if (listitems == NULL) + goto end; + } + + if (!PyDict_Check(obj)) { + dictitems = Py_None; + Py_INCREF(dictitems); + } + else { + PyObject *items = PyObject_CallMethod(obj, "items", ""); + if (items == NULL) + goto end; + dictitems = PyObject_GetIter(items); + Py_DECREF(items); + if (dictitems == NULL) + goto end; + } + + copyreg = import_copyreg(); + if (copyreg == NULL) + goto end; + newobj = PyObject_GetAttrString(copyreg, "__newobj__"); + if (newobj == NULL) + goto end; + + n = PyTuple_GET_SIZE(args); + args2 = PyTuple_New(n+1); + if (args2 == NULL) + goto end; + PyTuple_SET_ITEM(args2, 0, cls); + cls = NULL; + for (i = 0; i < n; i++) { + PyObject *v = PyTuple_GET_ITEM(args, i); + Py_INCREF(v); + PyTuple_SET_ITEM(args2, i+1, v); + } - res = PyTuple_Pack(5, newobj, args2, state, listitems, dictitems); + res = PyTuple_Pack(5, newobj, args2, state, listitems, dictitems); end: - Py_XDECREF(cls); - Py_XDECREF(args); - Py_XDECREF(args2); - Py_XDECREF(slots); - Py_XDECREF(state); - Py_XDECREF(names); - Py_XDECREF(listitems); - Py_XDECREF(dictitems); - Py_XDECREF(copyreg); - Py_XDECREF(newobj); - return res; + Py_XDECREF(cls); + Py_XDECREF(args); + Py_XDECREF(args2); + Py_XDECREF(slots); + Py_XDECREF(state); + Py_XDECREF(names); + Py_XDECREF(listitems); + Py_XDECREF(dictitems); + Py_XDECREF(copyreg); + Py_XDECREF(newobj); + return res; } /* @@ -3204,79 +3204,79 @@ static PyObject * _common_reduce(PyObject *self, int proto) { - PyObject *copyreg, *res; + PyObject *copyreg, *res; - if (proto >= 2) - return reduce_2(self); + if (proto >= 2) + return reduce_2(self); - copyreg = import_copyreg(); - if (!copyreg) - return NULL; + copyreg = import_copyreg(); + if (!copyreg) + return NULL; - res = PyEval_CallMethod(copyreg, "_reduce_ex", "(Oi)", self, proto); - Py_DECREF(copyreg); + res = PyEval_CallMethod(copyreg, "_reduce_ex", "(Oi)", self, proto); + Py_DECREF(copyreg); - return res; + return res; } static PyObject * object_reduce(PyObject *self, PyObject *args) { - int proto = 0; + int proto = 0; - if (!PyArg_ParseTuple(args, "|i:__reduce__", &proto)) - return NULL; + if (!PyArg_ParseTuple(args, "|i:__reduce__", &proto)) + return NULL; - return _common_reduce(self, proto); + return _common_reduce(self, proto); } static PyObject * object_reduce_ex(PyObject *self, PyObject *args) { - PyObject *reduce, *res; - int proto = 0; + PyObject *reduce, *res; + int proto = 0; - if (!PyArg_ParseTuple(args, "|i:__reduce_ex__", &proto)) - return NULL; + if (!PyArg_ParseTuple(args, "|i:__reduce_ex__", &proto)) + return NULL; - reduce = PyObject_GetAttrString(self, "__reduce__"); - if (reduce == NULL) - PyErr_Clear(); - else { - PyObject *cls, *clsreduce, *objreduce; - int override; - cls = PyObject_GetAttrString(self, "__class__"); - if (cls == NULL) { - Py_DECREF(reduce); - return NULL; - } - clsreduce = PyObject_GetAttrString(cls, "__reduce__"); - Py_DECREF(cls); - if (clsreduce == NULL) { - Py_DECREF(reduce); - return NULL; - } - objreduce = PyDict_GetItemString(PyBaseObject_Type.tp_dict, - "__reduce__"); - override = (clsreduce != objreduce); - Py_DECREF(clsreduce); - if (override) { - res = PyObject_CallObject(reduce, NULL); - Py_DECREF(reduce); - return res; - } - else - Py_DECREF(reduce); - } + reduce = PyObject_GetAttrString(self, "__reduce__"); + if (reduce == NULL) + PyErr_Clear(); + else { + PyObject *cls, *clsreduce, *objreduce; + int override; + cls = PyObject_GetAttrString(self, "__class__"); + if (cls == NULL) { + Py_DECREF(reduce); + return NULL; + } + clsreduce = PyObject_GetAttrString(cls, "__reduce__"); + Py_DECREF(cls); + if (clsreduce == NULL) { + Py_DECREF(reduce); + return NULL; + } + objreduce = PyDict_GetItemString(PyBaseObject_Type.tp_dict, + "__reduce__"); + override = (clsreduce != objreduce); + Py_DECREF(clsreduce); + if (override) { + res = PyObject_CallObject(reduce, NULL); + Py_DECREF(reduce); + return res; + } + else + Py_DECREF(reduce); + } - return _common_reduce(self, proto); + return _common_reduce(self, proto); } static PyObject * object_subclasshook(PyObject *cls, PyObject *args) { - Py_INCREF(Py_NotImplemented); - return Py_NotImplemented; + Py_INCREF(Py_NotImplemented); + return Py_NotImplemented; } PyDoc_STRVAR(object_subclasshook_doc, @@ -3292,104 +3292,104 @@ class object: def __format__(self, format_spec): - return format(str(self), format_spec) + return format(str(self), format_spec) */ static PyObject * object_format(PyObject *self, PyObject *args) { - PyObject *format_spec; - PyObject *self_as_str = NULL; - PyObject *result = NULL; - PyObject *format_meth = NULL; - - if (!PyArg_ParseTuple(args, "U:__format__", &format_spec)) - return NULL; - - self_as_str = PyObject_Str(self); - if (self_as_str != NULL) { - /* find the format function */ - format_meth = PyObject_GetAttrString(self_as_str, "__format__"); - if (format_meth != NULL) { - /* and call it */ - result = PyObject_CallFunctionObjArgs(format_meth, format_spec, NULL); - } + PyObject *format_spec; + PyObject *self_as_str = NULL; + PyObject *result = NULL; + PyObject *format_meth = NULL; + + if (!PyArg_ParseTuple(args, "U:__format__", &format_spec)) + return NULL; + + self_as_str = PyObject_Str(self); + if (self_as_str != NULL) { + /* find the format function */ + format_meth = PyObject_GetAttrString(self_as_str, "__format__"); + if (format_meth != NULL) { + /* and call it */ + result = PyObject_CallFunctionObjArgs(format_meth, format_spec, NULL); } + } - Py_XDECREF(self_as_str); - Py_XDECREF(format_meth); + Py_XDECREF(self_as_str); + Py_XDECREF(format_meth); - return result; + return result; } static PyObject * object_sizeof(PyObject *self, PyObject *args) { - Py_ssize_t res, isize; + Py_ssize_t res, isize; - res = 0; - isize = self->ob_type->tp_itemsize; - if (isize > 0) - res = Py_SIZE(self->ob_type) * isize; - res += self->ob_type->tp_basicsize; + res = 0; + isize = self->ob_type->tp_itemsize; + if (isize > 0) + res = Py_SIZE(self->ob_type) * isize; + res += self->ob_type->tp_basicsize; - return PyLong_FromSsize_t(res); + return PyLong_FromSsize_t(res); } static PyMethodDef object_methods[] = { - {"__reduce_ex__", object_reduce_ex, METH_VARARGS, - PyDoc_STR("helper for pickle")}, - {"__reduce__", object_reduce, METH_VARARGS, - PyDoc_STR("helper for pickle")}, - {"__subclasshook__", object_subclasshook, METH_CLASS | METH_VARARGS, - object_subclasshook_doc}, - {"__format__", object_format, METH_VARARGS, - PyDoc_STR("default object formatter")}, - {"__sizeof__", object_sizeof, METH_NOARGS, - PyDoc_STR("__sizeof__() -> size of object in memory, in bytes")}, - {0} + {"__reduce_ex__", object_reduce_ex, METH_VARARGS, + PyDoc_STR("helper for pickle")}, + {"__reduce__", object_reduce, METH_VARARGS, + PyDoc_STR("helper for pickle")}, + {"__subclasshook__", object_subclasshook, METH_CLASS | METH_VARARGS, + object_subclasshook_doc}, + {"__format__", object_format, METH_VARARGS, + PyDoc_STR("default object formatter")}, + {"__sizeof__", object_sizeof, METH_NOARGS, + PyDoc_STR("__sizeof__() -> size of object in memory, in bytes")}, + {0} }; PyTypeObject PyBaseObject_Type = { - PyVarObject_HEAD_INIT(&PyType_Type, 0) - "object", /* tp_name */ - sizeof(PyObject), /* tp_basicsize */ - 0, /* tp_itemsize */ - object_dealloc, /* tp_dealloc */ - 0, /* tp_print */ - 0, /* tp_getattr */ - 0, /* tp_setattr */ - 0, /* tp_reserved */ - object_repr, /* tp_repr */ - 0, /* tp_as_number */ - 0, /* tp_as_sequence */ - 0, /* tp_as_mapping */ - (hashfunc)_Py_HashPointer, /* tp_hash */ - 0, /* tp_call */ - object_str, /* tp_str */ - PyObject_GenericGetAttr, /* tp_getattro */ - PyObject_GenericSetAttr, /* tp_setattro */ - 0, /* tp_as_buffer */ - Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */ - PyDoc_STR("The most base type"), /* tp_doc */ - 0, /* tp_traverse */ - 0, /* tp_clear */ - object_richcompare, /* tp_richcompare */ - 0, /* tp_weaklistoffset */ - 0, /* tp_iter */ - 0, /* tp_iternext */ - object_methods, /* tp_methods */ - 0, /* tp_members */ - object_getsets, /* tp_getset */ - 0, /* tp_base */ - 0, /* tp_dict */ - 0, /* tp_descr_get */ - 0, /* tp_descr_set */ - 0, /* tp_dictoffset */ - object_init, /* tp_init */ - PyType_GenericAlloc, /* tp_alloc */ - object_new, /* tp_new */ - PyObject_Del, /* tp_free */ + PyVarObject_HEAD_INIT(&PyType_Type, 0) + "object", /* tp_name */ + sizeof(PyObject), /* tp_basicsize */ + 0, /* tp_itemsize */ + object_dealloc, /* tp_dealloc */ + 0, /* tp_print */ + 0, /* tp_getattr */ + 0, /* tp_setattr */ + 0, /* tp_reserved */ + object_repr, /* tp_repr */ + 0, /* tp_as_number */ + 0, /* tp_as_sequence */ + 0, /* tp_as_mapping */ + (hashfunc)_Py_HashPointer, /* tp_hash */ + 0, /* tp_call */ + object_str, /* tp_str */ + PyObject_GenericGetAttr, /* tp_getattro */ + PyObject_GenericSetAttr, /* tp_setattro */ + 0, /* tp_as_buffer */ + Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */ + PyDoc_STR("The most base type"), /* tp_doc */ + 0, /* tp_traverse */ + 0, /* tp_clear */ + object_richcompare, /* tp_richcompare */ + 0, /* tp_weaklistoffset */ + 0, /* tp_iter */ + 0, /* tp_iternext */ + object_methods, /* tp_methods */ + 0, /* tp_members */ + object_getsets, /* tp_getset */ + 0, /* tp_base */ + 0, /* tp_dict */ + 0, /* tp_descr_get */ + 0, /* tp_descr_set */ + 0, /* tp_dictoffset */ + object_init, /* tp_init */ + PyType_GenericAlloc, /* tp_alloc */ + object_new, /* tp_new */ + PyObject_Del, /* tp_free */ }; @@ -3398,168 +3398,168 @@ static int add_methods(PyTypeObject *type, PyMethodDef *meth) { - PyObject *dict = type->tp_dict; + PyObject *dict = type->tp_dict; - for (; meth->ml_name != NULL; meth++) { - PyObject *descr; - if (PyDict_GetItemString(dict, meth->ml_name) && - !(meth->ml_flags & METH_COEXIST)) - continue; - if (meth->ml_flags & METH_CLASS) { - if (meth->ml_flags & METH_STATIC) { - PyErr_SetString(PyExc_ValueError, - "method cannot be both class and static"); - return -1; - } - descr = PyDescr_NewClassMethod(type, meth); - } - else if (meth->ml_flags & METH_STATIC) { - PyObject *cfunc = PyCFunction_New(meth, NULL); - if (cfunc == NULL) - return -1; - descr = PyStaticMethod_New(cfunc); - Py_DECREF(cfunc); - } - else { - descr = PyDescr_NewMethod(type, meth); - } - if (descr == NULL) - return -1; - if (PyDict_SetItemString(dict, meth->ml_name, descr) < 0) - return -1; - Py_DECREF(descr); - } - return 0; + for (; meth->ml_name != NULL; meth++) { + PyObject *descr; + if (PyDict_GetItemString(dict, meth->ml_name) && + !(meth->ml_flags & METH_COEXIST)) + continue; + if (meth->ml_flags & METH_CLASS) { + if (meth->ml_flags & METH_STATIC) { + PyErr_SetString(PyExc_ValueError, + "method cannot be both class and static"); + return -1; + } + descr = PyDescr_NewClassMethod(type, meth); + } + else if (meth->ml_flags & METH_STATIC) { + PyObject *cfunc = PyCFunction_New(meth, NULL); + if (cfunc == NULL) + return -1; + descr = PyStaticMethod_New(cfunc); + Py_DECREF(cfunc); + } + else { + descr = PyDescr_NewMethod(type, meth); + } + if (descr == NULL) + return -1; + if (PyDict_SetItemString(dict, meth->ml_name, descr) < 0) + return -1; + Py_DECREF(descr); + } + return 0; } static int add_members(PyTypeObject *type, PyMemberDef *memb) { - PyObject *dict = type->tp_dict; + PyObject *dict = type->tp_dict; - for (; memb->name != NULL; memb++) { - PyObject *descr; - if (PyDict_GetItemString(dict, memb->name)) - continue; - descr = PyDescr_NewMember(type, memb); - if (descr == NULL) - return -1; - if (PyDict_SetItemString(dict, memb->name, descr) < 0) - return -1; - Py_DECREF(descr); - } - return 0; + for (; memb->name != NULL; memb++) { + PyObject *descr; + if (PyDict_GetItemString(dict, memb->name)) + continue; + descr = PyDescr_NewMember(type, memb); + if (descr == NULL) + return -1; + if (PyDict_SetItemString(dict, memb->name, descr) < 0) + return -1; + Py_DECREF(descr); + } + return 0; } static int add_getset(PyTypeObject *type, PyGetSetDef *gsp) { - PyObject *dict = type->tp_dict; + PyObject *dict = type->tp_dict; - for (; gsp->name != NULL; gsp++) { - PyObject *descr; - if (PyDict_GetItemString(dict, gsp->name)) - continue; - descr = PyDescr_NewGetSet(type, gsp); - - if (descr == NULL) - return -1; - if (PyDict_SetItemString(dict, gsp->name, descr) < 0) - return -1; - Py_DECREF(descr); - } - return 0; + for (; gsp->name != NULL; gsp++) { + PyObject *descr; + if (PyDict_GetItemString(dict, gsp->name)) + continue; + descr = PyDescr_NewGetSet(type, gsp); + + if (descr == NULL) + return -1; + if (PyDict_SetItemString(dict, gsp->name, descr) < 0) + return -1; + Py_DECREF(descr); + } + return 0; } static void inherit_special(PyTypeObject *type, PyTypeObject *base) { - Py_ssize_t oldsize, newsize; + Py_ssize_t oldsize, newsize; - /* Copying basicsize is connected to the GC flags */ - oldsize = base->tp_basicsize; - newsize = type->tp_basicsize ? type->tp_basicsize : oldsize; - if (!(type->tp_flags & Py_TPFLAGS_HAVE_GC) && - (base->tp_flags & Py_TPFLAGS_HAVE_GC) && - (!type->tp_traverse && !type->tp_clear)) { - type->tp_flags |= Py_TPFLAGS_HAVE_GC; - if (type->tp_traverse == NULL) - type->tp_traverse = base->tp_traverse; - if (type->tp_clear == NULL) - type->tp_clear = base->tp_clear; - } - { - /* The condition below could use some explanation. - It appears that tp_new is not inherited for static types - whose base class is 'object'; this seems to be a precaution - so that old extension types don't suddenly become - callable (object.__new__ wouldn't insure the invariants - that the extension type's own factory function ensures). - Heap types, of course, are under our control, so they do - inherit tp_new; static extension types that specify some - other built-in type as the default are considered - new-style-aware so they also inherit object.__new__. */ - if (base != &PyBaseObject_Type || - (type->tp_flags & Py_TPFLAGS_HEAPTYPE)) { - if (type->tp_new == NULL) - type->tp_new = base->tp_new; - } - } - type->tp_basicsize = newsize; + /* Copying basicsize is connected to the GC flags */ + oldsize = base->tp_basicsize; + newsize = type->tp_basicsize ? type->tp_basicsize : oldsize; + if (!(type->tp_flags & Py_TPFLAGS_HAVE_GC) && + (base->tp_flags & Py_TPFLAGS_HAVE_GC) && + (!type->tp_traverse && !type->tp_clear)) { + type->tp_flags |= Py_TPFLAGS_HAVE_GC; + if (type->tp_traverse == NULL) + type->tp_traverse = base->tp_traverse; + if (type->tp_clear == NULL) + type->tp_clear = base->tp_clear; + } + { + /* The condition below could use some explanation. + It appears that tp_new is not inherited for static types + whose base class is 'object'; this seems to be a precaution + so that old extension types don't suddenly become + callable (object.__new__ wouldn't insure the invariants + that the extension type's own factory function ensures). + Heap types, of course, are under our control, so they do + inherit tp_new; static extension types that specify some + other built-in type as the default are considered + new-style-aware so they also inherit object.__new__. */ + if (base != &PyBaseObject_Type || + (type->tp_flags & Py_TPFLAGS_HEAPTYPE)) { + if (type->tp_new == NULL) + type->tp_new = base->tp_new; + } + } + type->tp_basicsize = newsize; - /* Copy other non-function slots */ + /* Copy other non-function slots */ #undef COPYVAL #define COPYVAL(SLOT) \ - if (type->SLOT == 0) type->SLOT = base->SLOT + if (type->SLOT == 0) type->SLOT = base->SLOT - COPYVAL(tp_itemsize); - COPYVAL(tp_weaklistoffset); - COPYVAL(tp_dictoffset); - - /* Setup fast subclass flags */ - if (PyType_IsSubtype(base, (PyTypeObject*)PyExc_BaseException)) - type->tp_flags |= Py_TPFLAGS_BASE_EXC_SUBCLASS; - else if (PyType_IsSubtype(base, &PyType_Type)) - type->tp_flags |= Py_TPFLAGS_TYPE_SUBCLASS; - else if (PyType_IsSubtype(base, &PyLong_Type)) - type->tp_flags |= Py_TPFLAGS_LONG_SUBCLASS; - else if (PyType_IsSubtype(base, &PyBytes_Type)) - type->tp_flags |= Py_TPFLAGS_BYTES_SUBCLASS; - else if (PyType_IsSubtype(base, &PyUnicode_Type)) - type->tp_flags |= Py_TPFLAGS_UNICODE_SUBCLASS; - else if (PyType_IsSubtype(base, &PyTuple_Type)) - type->tp_flags |= Py_TPFLAGS_TUPLE_SUBCLASS; - else if (PyType_IsSubtype(base, &PyList_Type)) - type->tp_flags |= Py_TPFLAGS_LIST_SUBCLASS; - else if (PyType_IsSubtype(base, &PyDict_Type)) - type->tp_flags |= Py_TPFLAGS_DICT_SUBCLASS; + COPYVAL(tp_itemsize); + COPYVAL(tp_weaklistoffset); + COPYVAL(tp_dictoffset); + + /* Setup fast subclass flags */ + if (PyType_IsSubtype(base, (PyTypeObject*)PyExc_BaseException)) + type->tp_flags |= Py_TPFLAGS_BASE_EXC_SUBCLASS; + else if (PyType_IsSubtype(base, &PyType_Type)) + type->tp_flags |= Py_TPFLAGS_TYPE_SUBCLASS; + else if (PyType_IsSubtype(base, &PyLong_Type)) + type->tp_flags |= Py_TPFLAGS_LONG_SUBCLASS; + else if (PyType_IsSubtype(base, &PyBytes_Type)) + type->tp_flags |= Py_TPFLAGS_BYTES_SUBCLASS; + else if (PyType_IsSubtype(base, &PyUnicode_Type)) + type->tp_flags |= Py_TPFLAGS_UNICODE_SUBCLASS; + else if (PyType_IsSubtype(base, &PyTuple_Type)) + type->tp_flags |= Py_TPFLAGS_TUPLE_SUBCLASS; + else if (PyType_IsSubtype(base, &PyList_Type)) + type->tp_flags |= Py_TPFLAGS_LIST_SUBCLASS; + else if (PyType_IsSubtype(base, &PyDict_Type)) + type->tp_flags |= Py_TPFLAGS_DICT_SUBCLASS; } static char *hash_name_op[] = { - "__eq__", - "__hash__", - NULL + "__eq__", + "__hash__", + NULL }; static int overrides_hash(PyTypeObject *type) { - char **p; - PyObject *dict = type->tp_dict; + char **p; + PyObject *dict = type->tp_dict; - assert(dict != NULL); - for (p = hash_name_op; *p; p++) { - if (PyDict_GetItemString(dict, *p) != NULL) - return 1; - } - return 0; + assert(dict != NULL); + for (p = hash_name_op; *p; p++) { + if (PyDict_GetItemString(dict, *p) != NULL) + return 1; + } + return 0; } static void inherit_slots(PyTypeObject *type, PyTypeObject *base) { - PyTypeObject *basebase; + PyTypeObject *basebase; #undef SLOTDEFINED #undef COPYSLOT @@ -3569,147 +3569,147 @@ #undef COPYBUF #define SLOTDEFINED(SLOT) \ - (base->SLOT != 0 && \ - (basebase == NULL || base->SLOT != basebase->SLOT)) + (base->SLOT != 0 && \ + (basebase == NULL || base->SLOT != basebase->SLOT)) #define COPYSLOT(SLOT) \ - if (!type->SLOT && SLOTDEFINED(SLOT)) type->SLOT = base->SLOT + if (!type->SLOT && SLOTDEFINED(SLOT)) type->SLOT = base->SLOT #define COPYNUM(SLOT) COPYSLOT(tp_as_number->SLOT) #define COPYSEQ(SLOT) COPYSLOT(tp_as_sequence->SLOT) #define COPYMAP(SLOT) COPYSLOT(tp_as_mapping->SLOT) #define COPYBUF(SLOT) COPYSLOT(tp_as_buffer->SLOT) - /* This won't inherit indirect slots (from tp_as_number etc.) - if type doesn't provide the space. */ + /* This won't inherit indirect slots (from tp_as_number etc.) + if type doesn't provide the space. */ - if (type->tp_as_number != NULL && base->tp_as_number != NULL) { - basebase = base->tp_base; - if (basebase->tp_as_number == NULL) - basebase = NULL; - COPYNUM(nb_add); - COPYNUM(nb_subtract); - COPYNUM(nb_multiply); - COPYNUM(nb_remainder); - COPYNUM(nb_divmod); - COPYNUM(nb_power); - COPYNUM(nb_negative); - COPYNUM(nb_positive); - COPYNUM(nb_absolute); - COPYNUM(nb_bool); - COPYNUM(nb_invert); - COPYNUM(nb_lshift); - COPYNUM(nb_rshift); - COPYNUM(nb_and); - COPYNUM(nb_xor); - COPYNUM(nb_or); - COPYNUM(nb_int); - COPYNUM(nb_float); - COPYNUM(nb_inplace_add); - COPYNUM(nb_inplace_subtract); - COPYNUM(nb_inplace_multiply); - COPYNUM(nb_inplace_remainder); - COPYNUM(nb_inplace_power); - COPYNUM(nb_inplace_lshift); - COPYNUM(nb_inplace_rshift); - COPYNUM(nb_inplace_and); - COPYNUM(nb_inplace_xor); - COPYNUM(nb_inplace_or); - COPYNUM(nb_true_divide); - COPYNUM(nb_floor_divide); - COPYNUM(nb_inplace_true_divide); - COPYNUM(nb_inplace_floor_divide); - COPYNUM(nb_index); - } - - if (type->tp_as_sequence != NULL && base->tp_as_sequence != NULL) { - basebase = base->tp_base; - if (basebase->tp_as_sequence == NULL) - basebase = NULL; - COPYSEQ(sq_length); - COPYSEQ(sq_concat); - COPYSEQ(sq_repeat); - COPYSEQ(sq_item); - COPYSEQ(sq_ass_item); - COPYSEQ(sq_contains); - COPYSEQ(sq_inplace_concat); - COPYSEQ(sq_inplace_repeat); - } - - if (type->tp_as_mapping != NULL && base->tp_as_mapping != NULL) { - basebase = base->tp_base; - if (basebase->tp_as_mapping == NULL) - basebase = NULL; - COPYMAP(mp_length); - COPYMAP(mp_subscript); - COPYMAP(mp_ass_subscript); - } - - if (type->tp_as_buffer != NULL && base->tp_as_buffer != NULL) { - basebase = base->tp_base; - if (basebase->tp_as_buffer == NULL) - basebase = NULL; - COPYBUF(bf_getbuffer); - COPYBUF(bf_releasebuffer); - } - - basebase = base->tp_base; - - COPYSLOT(tp_dealloc); - if (type->tp_getattr == NULL && type->tp_getattro == NULL) { - type->tp_getattr = base->tp_getattr; - type->tp_getattro = base->tp_getattro; - } - if (type->tp_setattr == NULL && type->tp_setattro == NULL) { - type->tp_setattr = base->tp_setattr; - type->tp_setattro = base->tp_setattro; - } - /* tp_reserved is ignored */ - COPYSLOT(tp_repr); - /* tp_hash see tp_richcompare */ - COPYSLOT(tp_call); - COPYSLOT(tp_str); - { - /* Copy comparison-related slots only when - not overriding them anywhere */ - if (type->tp_richcompare == NULL && - type->tp_hash == NULL && - !overrides_hash(type)) - { - type->tp_richcompare = base->tp_richcompare; - type->tp_hash = base->tp_hash; - } - } - { - COPYSLOT(tp_iter); - COPYSLOT(tp_iternext); - } - { - COPYSLOT(tp_descr_get); - COPYSLOT(tp_descr_set); - COPYSLOT(tp_dictoffset); - COPYSLOT(tp_init); - COPYSLOT(tp_alloc); - COPYSLOT(tp_is_gc); - if ((type->tp_flags & Py_TPFLAGS_HAVE_GC) == - (base->tp_flags & Py_TPFLAGS_HAVE_GC)) { - /* They agree about gc. */ - COPYSLOT(tp_free); - } - else if ((type->tp_flags & Py_TPFLAGS_HAVE_GC) && - type->tp_free == NULL && - base->tp_free == PyObject_Free) { - /* A bit of magic to plug in the correct default - * tp_free function when a derived class adds gc, - * didn't define tp_free, and the base uses the - * default non-gc tp_free. - */ - type->tp_free = PyObject_GC_Del; - } - /* else they didn't agree about gc, and there isn't something - * obvious to be done -- the type is on its own. - */ - } + if (type->tp_as_number != NULL && base->tp_as_number != NULL) { + basebase = base->tp_base; + if (basebase->tp_as_number == NULL) + basebase = NULL; + COPYNUM(nb_add); + COPYNUM(nb_subtract); + COPYNUM(nb_multiply); + COPYNUM(nb_remainder); + COPYNUM(nb_divmod); + COPYNUM(nb_power); + COPYNUM(nb_negative); + COPYNUM(nb_positive); + COPYNUM(nb_absolute); + COPYNUM(nb_bool); + COPYNUM(nb_invert); + COPYNUM(nb_lshift); + COPYNUM(nb_rshift); + COPYNUM(nb_and); + COPYNUM(nb_xor); + COPYNUM(nb_or); + COPYNUM(nb_int); + COPYNUM(nb_float); + COPYNUM(nb_inplace_add); + COPYNUM(nb_inplace_subtract); + COPYNUM(nb_inplace_multiply); + COPYNUM(nb_inplace_remainder); + COPYNUM(nb_inplace_power); + COPYNUM(nb_inplace_lshift); + COPYNUM(nb_inplace_rshift); + COPYNUM(nb_inplace_and); + COPYNUM(nb_inplace_xor); + COPYNUM(nb_inplace_or); + COPYNUM(nb_true_divide); + COPYNUM(nb_floor_divide); + COPYNUM(nb_inplace_true_divide); + COPYNUM(nb_inplace_floor_divide); + COPYNUM(nb_index); + } + + if (type->tp_as_sequence != NULL && base->tp_as_sequence != NULL) { + basebase = base->tp_base; + if (basebase->tp_as_sequence == NULL) + basebase = NULL; + COPYSEQ(sq_length); + COPYSEQ(sq_concat); + COPYSEQ(sq_repeat); + COPYSEQ(sq_item); + COPYSEQ(sq_ass_item); + COPYSEQ(sq_contains); + COPYSEQ(sq_inplace_concat); + COPYSEQ(sq_inplace_repeat); + } + + if (type->tp_as_mapping != NULL && base->tp_as_mapping != NULL) { + basebase = base->tp_base; + if (basebase->tp_as_mapping == NULL) + basebase = NULL; + COPYMAP(mp_length); + COPYMAP(mp_subscript); + COPYMAP(mp_ass_subscript); + } + + if (type->tp_as_buffer != NULL && base->tp_as_buffer != NULL) { + basebase = base->tp_base; + if (basebase->tp_as_buffer == NULL) + basebase = NULL; + COPYBUF(bf_getbuffer); + COPYBUF(bf_releasebuffer); + } + + basebase = base->tp_base; + + COPYSLOT(tp_dealloc); + if (type->tp_getattr == NULL && type->tp_getattro == NULL) { + type->tp_getattr = base->tp_getattr; + type->tp_getattro = base->tp_getattro; + } + if (type->tp_setattr == NULL && type->tp_setattro == NULL) { + type->tp_setattr = base->tp_setattr; + type->tp_setattro = base->tp_setattro; + } + /* tp_reserved is ignored */ + COPYSLOT(tp_repr); + /* tp_hash see tp_richcompare */ + COPYSLOT(tp_call); + COPYSLOT(tp_str); + { + /* Copy comparison-related slots only when + not overriding them anywhere */ + if (type->tp_richcompare == NULL && + type->tp_hash == NULL && + !overrides_hash(type)) + { + type->tp_richcompare = base->tp_richcompare; + type->tp_hash = base->tp_hash; + } + } + { + COPYSLOT(tp_iter); + COPYSLOT(tp_iternext); + } + { + COPYSLOT(tp_descr_get); + COPYSLOT(tp_descr_set); + COPYSLOT(tp_dictoffset); + COPYSLOT(tp_init); + COPYSLOT(tp_alloc); + COPYSLOT(tp_is_gc); + if ((type->tp_flags & Py_TPFLAGS_HAVE_GC) == + (base->tp_flags & Py_TPFLAGS_HAVE_GC)) { + /* They agree about gc. */ + COPYSLOT(tp_free); + } + else if ((type->tp_flags & Py_TPFLAGS_HAVE_GC) && + type->tp_free == NULL && + base->tp_free == PyObject_Free) { + /* A bit of magic to plug in the correct default + * tp_free function when a derived class adds gc, + * didn't define tp_free, and the base uses the + * default non-gc tp_free. + */ + type->tp_free = PyObject_GC_Del; + } + /* else they didn't agree about gc, and there isn't something + * obvious to be done -- the type is on its own. + */ + } } static int add_operators(PyTypeObject *); @@ -3717,273 +3717,273 @@ int PyType_Ready(PyTypeObject *type) { - PyObject *dict, *bases; - PyTypeObject *base; - Py_ssize_t i, n; - - if (type->tp_flags & Py_TPFLAGS_READY) { - assert(type->tp_dict != NULL); - return 0; - } - assert((type->tp_flags & Py_TPFLAGS_READYING) == 0); + PyObject *dict, *bases; + PyTypeObject *base; + Py_ssize_t i, n; + + if (type->tp_flags & Py_TPFLAGS_READY) { + assert(type->tp_dict != NULL); + return 0; + } + assert((type->tp_flags & Py_TPFLAGS_READYING) == 0); - type->tp_flags |= Py_TPFLAGS_READYING; + type->tp_flags |= Py_TPFLAGS_READYING; #ifdef Py_TRACE_REFS - /* PyType_Ready is the closest thing we have to a choke point - * for type objects, so is the best place I can think of to try - * to get type objects into the doubly-linked list of all objects. - * Still, not all type objects go thru PyType_Ready. - */ - _Py_AddToAllObjects((PyObject *)type, 0); + /* PyType_Ready is the closest thing we have to a choke point + * for type objects, so is the best place I can think of to try + * to get type objects into the doubly-linked list of all objects. + * Still, not all type objects go thru PyType_Ready. + */ + _Py_AddToAllObjects((PyObject *)type, 0); #endif - /* Initialize tp_base (defaults to BaseObject unless that's us) */ - base = type->tp_base; - if (base == NULL && type != &PyBaseObject_Type) { - base = type->tp_base = &PyBaseObject_Type; - Py_INCREF(base); - } - - /* Now the only way base can still be NULL is if type is - * &PyBaseObject_Type. - */ - - /* Initialize the base class */ - if (base != NULL && base->tp_dict == NULL) { - if (PyType_Ready(base) < 0) - goto error; - } - - /* Initialize ob_type if NULL. This means extensions that want to be - compilable separately on Windows can call PyType_Ready() instead of - initializing the ob_type field of their type objects. */ - /* The test for base != NULL is really unnecessary, since base is only - NULL when type is &PyBaseObject_Type, and we know its ob_type is - not NULL (it's initialized to &PyType_Type). But coverity doesn't - know that. */ - if (Py_TYPE(type) == NULL && base != NULL) - Py_TYPE(type) = Py_TYPE(base); - - /* Initialize tp_bases */ - bases = type->tp_bases; - if (bases == NULL) { - if (base == NULL) - bases = PyTuple_New(0); - else - bases = PyTuple_Pack(1, base); - if (bases == NULL) - goto error; - type->tp_bases = bases; - } - - /* Initialize tp_dict */ - dict = type->tp_dict; - if (dict == NULL) { - dict = PyDict_New(); - if (dict == NULL) - goto error; - type->tp_dict = dict; - } - - /* Add type-specific descriptors to tp_dict */ - if (add_operators(type) < 0) - goto error; - if (type->tp_methods != NULL) { - if (add_methods(type, type->tp_methods) < 0) - goto error; - } - if (type->tp_members != NULL) { - if (add_members(type, type->tp_members) < 0) - goto error; - } - if (type->tp_getset != NULL) { - if (add_getset(type, type->tp_getset) < 0) - goto error; - } - - /* Calculate method resolution order */ - if (mro_internal(type) < 0) { - goto error; - } - - /* Inherit special flags from dominant base */ - if (type->tp_base != NULL) - inherit_special(type, type->tp_base); - - /* Initialize tp_dict properly */ - bases = type->tp_mro; - assert(bases != NULL); - assert(PyTuple_Check(bases)); - n = PyTuple_GET_SIZE(bases); - for (i = 1; i < n; i++) { - PyObject *b = PyTuple_GET_ITEM(bases, i); - if (PyType_Check(b)) - inherit_slots(type, (PyTypeObject *)b); - } - - /* Sanity check for tp_free. */ - if (PyType_IS_GC(type) && (type->tp_flags & Py_TPFLAGS_BASETYPE) && - (type->tp_free == NULL || type->tp_free == PyObject_Del)) { - /* This base class needs to call tp_free, but doesn't have - * one, or its tp_free is for non-gc'ed objects. - */ - PyErr_Format(PyExc_TypeError, "type '%.100s' participates in " - "gc and is a base type but has inappropriate " - "tp_free slot", - type->tp_name); - goto error; - } - - /* if the type dictionary doesn't contain a __doc__, set it from - the tp_doc slot. - */ - if (PyDict_GetItemString(type->tp_dict, "__doc__") == NULL) { - if (type->tp_doc != NULL) { - PyObject *doc = PyUnicode_FromString(type->tp_doc); - if (doc == NULL) - goto error; - PyDict_SetItemString(type->tp_dict, "__doc__", doc); - Py_DECREF(doc); - } else { - PyDict_SetItemString(type->tp_dict, - "__doc__", Py_None); - } - } - - /* Hack for tp_hash and __hash__. - If after all that, tp_hash is still NULL, and __hash__ is not in - tp_dict, set tp_hash to PyObject_HashNotImplemented and - tp_dict['__hash__'] equal to None. - This signals that __hash__ is not inherited. - */ - if (type->tp_hash == NULL) { - if (PyDict_GetItemString(type->tp_dict, "__hash__") == NULL) { - if (PyDict_SetItemString(type->tp_dict, "__hash__", Py_None) < 0) - goto error; - type->tp_hash = PyObject_HashNotImplemented; - } - } - - /* Some more special stuff */ - base = type->tp_base; - if (base != NULL) { - if (type->tp_as_number == NULL) - type->tp_as_number = base->tp_as_number; - if (type->tp_as_sequence == NULL) - type->tp_as_sequence = base->tp_as_sequence; - if (type->tp_as_mapping == NULL) - type->tp_as_mapping = base->tp_as_mapping; - if (type->tp_as_buffer == NULL) - type->tp_as_buffer = base->tp_as_buffer; - } - - /* Link into each base class's list of subclasses */ - bases = type->tp_bases; - n = PyTuple_GET_SIZE(bases); - for (i = 0; i < n; i++) { - PyObject *b = PyTuple_GET_ITEM(bases, i); - if (PyType_Check(b) && - add_subclass((PyTypeObject *)b, type) < 0) - goto error; - } - - /* Warn for a type that implements tp_compare (now known as - tp_reserved) but not tp_richcompare. */ - if (type->tp_reserved && !type->tp_richcompare) { - int error; - char msg[240]; - PyOS_snprintf(msg, sizeof(msg), - "Type %.100s defines tp_reserved (formerly " - "tp_compare) but not tp_richcompare. " - "Comparisons may not behave as intended.", - type->tp_name); - error = PyErr_WarnEx(PyExc_DeprecationWarning, msg, 1); - if (error == -1) - goto error; - } - - /* All done -- set the ready flag */ - assert(type->tp_dict != NULL); - type->tp_flags = - (type->tp_flags & ~Py_TPFLAGS_READYING) | Py_TPFLAGS_READY; - return 0; + /* Initialize tp_base (defaults to BaseObject unless that's us) */ + base = type->tp_base; + if (base == NULL && type != &PyBaseObject_Type) { + base = type->tp_base = &PyBaseObject_Type; + Py_INCREF(base); + } + + /* Now the only way base can still be NULL is if type is + * &PyBaseObject_Type. + */ + + /* Initialize the base class */ + if (base != NULL && base->tp_dict == NULL) { + if (PyType_Ready(base) < 0) + goto error; + } + + /* Initialize ob_type if NULL. This means extensions that want to be + compilable separately on Windows can call PyType_Ready() instead of + initializing the ob_type field of their type objects. */ + /* The test for base != NULL is really unnecessary, since base is only + NULL when type is &PyBaseObject_Type, and we know its ob_type is + not NULL (it's initialized to &PyType_Type). But coverity doesn't + know that. */ + if (Py_TYPE(type) == NULL && base != NULL) + Py_TYPE(type) = Py_TYPE(base); + + /* Initialize tp_bases */ + bases = type->tp_bases; + if (bases == NULL) { + if (base == NULL) + bases = PyTuple_New(0); + else + bases = PyTuple_Pack(1, base); + if (bases == NULL) + goto error; + type->tp_bases = bases; + } + + /* Initialize tp_dict */ + dict = type->tp_dict; + if (dict == NULL) { + dict = PyDict_New(); + if (dict == NULL) + goto error; + type->tp_dict = dict; + } + + /* Add type-specific descriptors to tp_dict */ + if (add_operators(type) < 0) + goto error; + if (type->tp_methods != NULL) { + if (add_methods(type, type->tp_methods) < 0) + goto error; + } + if (type->tp_members != NULL) { + if (add_members(type, type->tp_members) < 0) + goto error; + } + if (type->tp_getset != NULL) { + if (add_getset(type, type->tp_getset) < 0) + goto error; + } + + /* Calculate method resolution order */ + if (mro_internal(type) < 0) { + goto error; + } + + /* Inherit special flags from dominant base */ + if (type->tp_base != NULL) + inherit_special(type, type->tp_base); + + /* Initialize tp_dict properly */ + bases = type->tp_mro; + assert(bases != NULL); + assert(PyTuple_Check(bases)); + n = PyTuple_GET_SIZE(bases); + for (i = 1; i < n; i++) { + PyObject *b = PyTuple_GET_ITEM(bases, i); + if (PyType_Check(b)) + inherit_slots(type, (PyTypeObject *)b); + } + + /* Sanity check for tp_free. */ + if (PyType_IS_GC(type) && (type->tp_flags & Py_TPFLAGS_BASETYPE) && + (type->tp_free == NULL || type->tp_free == PyObject_Del)) { + /* This base class needs to call tp_free, but doesn't have + * one, or its tp_free is for non-gc'ed objects. + */ + PyErr_Format(PyExc_TypeError, "type '%.100s' participates in " + "gc and is a base type but has inappropriate " + "tp_free slot", + type->tp_name); + goto error; + } + + /* if the type dictionary doesn't contain a __doc__, set it from + the tp_doc slot. + */ + if (PyDict_GetItemString(type->tp_dict, "__doc__") == NULL) { + if (type->tp_doc != NULL) { + PyObject *doc = PyUnicode_FromString(type->tp_doc); + if (doc == NULL) + goto error; + PyDict_SetItemString(type->tp_dict, "__doc__", doc); + Py_DECREF(doc); + } else { + PyDict_SetItemString(type->tp_dict, + "__doc__", Py_None); + } + } + + /* Hack for tp_hash and __hash__. + If after all that, tp_hash is still NULL, and __hash__ is not in + tp_dict, set tp_hash to PyObject_HashNotImplemented and + tp_dict['__hash__'] equal to None. + This signals that __hash__ is not inherited. + */ + if (type->tp_hash == NULL) { + if (PyDict_GetItemString(type->tp_dict, "__hash__") == NULL) { + if (PyDict_SetItemString(type->tp_dict, "__hash__", Py_None) < 0) + goto error; + type->tp_hash = PyObject_HashNotImplemented; + } + } + + /* Some more special stuff */ + base = type->tp_base; + if (base != NULL) { + if (type->tp_as_number == NULL) + type->tp_as_number = base->tp_as_number; + if (type->tp_as_sequence == NULL) + type->tp_as_sequence = base->tp_as_sequence; + if (type->tp_as_mapping == NULL) + type->tp_as_mapping = base->tp_as_mapping; + if (type->tp_as_buffer == NULL) + type->tp_as_buffer = base->tp_as_buffer; + } + + /* Link into each base class's list of subclasses */ + bases = type->tp_bases; + n = PyTuple_GET_SIZE(bases); + for (i = 0; i < n; i++) { + PyObject *b = PyTuple_GET_ITEM(bases, i); + if (PyType_Check(b) && + add_subclass((PyTypeObject *)b, type) < 0) + goto error; + } + + /* Warn for a type that implements tp_compare (now known as + tp_reserved) but not tp_richcompare. */ + if (type->tp_reserved && !type->tp_richcompare) { + int error; + char msg[240]; + PyOS_snprintf(msg, sizeof(msg), + "Type %.100s defines tp_reserved (formerly " + "tp_compare) but not tp_richcompare. " + "Comparisons may not behave as intended.", + type->tp_name); + error = PyErr_WarnEx(PyExc_DeprecationWarning, msg, 1); + if (error == -1) + goto error; + } + + /* All done -- set the ready flag */ + assert(type->tp_dict != NULL); + type->tp_flags = + (type->tp_flags & ~Py_TPFLAGS_READYING) | Py_TPFLAGS_READY; + return 0; error: - type->tp_flags &= ~Py_TPFLAGS_READYING; - return -1; + type->tp_flags &= ~Py_TPFLAGS_READYING; + return -1; } static int add_subclass(PyTypeObject *base, PyTypeObject *type) { - Py_ssize_t i; - int result; - PyObject *list, *ref, *newobj; - - list = base->tp_subclasses; - if (list == NULL) { - base->tp_subclasses = list = PyList_New(0); - if (list == NULL) - return -1; - } - assert(PyList_Check(list)); - newobj = PyWeakref_NewRef((PyObject *)type, NULL); - i = PyList_GET_SIZE(list); - while (--i >= 0) { - ref = PyList_GET_ITEM(list, i); - assert(PyWeakref_CheckRef(ref)); - if (PyWeakref_GET_OBJECT(ref) == Py_None) - return PyList_SetItem(list, i, newobj); - } - result = PyList_Append(list, newobj); - Py_DECREF(newobj); - return result; + Py_ssize_t i; + int result; + PyObject *list, *ref, *newobj; + + list = base->tp_subclasses; + if (list == NULL) { + base->tp_subclasses = list = PyList_New(0); + if (list == NULL) + return -1; + } + assert(PyList_Check(list)); + newobj = PyWeakref_NewRef((PyObject *)type, NULL); + i = PyList_GET_SIZE(list); + while (--i >= 0) { + ref = PyList_GET_ITEM(list, i); + assert(PyWeakref_CheckRef(ref)); + if (PyWeakref_GET_OBJECT(ref) == Py_None) + return PyList_SetItem(list, i, newobj); + } + result = PyList_Append(list, newobj); + Py_DECREF(newobj); + return result; } static void remove_subclass(PyTypeObject *base, PyTypeObject *type) { - Py_ssize_t i; - PyObject *list, *ref; + Py_ssize_t i; + PyObject *list, *ref; - list = base->tp_subclasses; - if (list == NULL) { - return; - } - assert(PyList_Check(list)); - i = PyList_GET_SIZE(list); - while (--i >= 0) { - ref = PyList_GET_ITEM(list, i); - assert(PyWeakref_CheckRef(ref)); - if (PyWeakref_GET_OBJECT(ref) == (PyObject*)type) { - /* this can't fail, right? */ - PySequence_DelItem(list, i); - return; - } - } + list = base->tp_subclasses; + if (list == NULL) { + return; + } + assert(PyList_Check(list)); + i = PyList_GET_SIZE(list); + while (--i >= 0) { + ref = PyList_GET_ITEM(list, i); + assert(PyWeakref_CheckRef(ref)); + if (PyWeakref_GET_OBJECT(ref) == (PyObject*)type) { + /* this can't fail, right? */ + PySequence_DelItem(list, i); + return; + } + } } static int check_num_args(PyObject *ob, int n) { - if (!PyTuple_CheckExact(ob)) { - PyErr_SetString(PyExc_SystemError, - "PyArg_UnpackTuple() argument list is not a tuple"); - return 0; - } - if (n == PyTuple_GET_SIZE(ob)) - return 1; - PyErr_Format( - PyExc_TypeError, - "expected %d arguments, got %zd", n, PyTuple_GET_SIZE(ob)); - return 0; + if (!PyTuple_CheckExact(ob)) { + PyErr_SetString(PyExc_SystemError, + "PyArg_UnpackTuple() argument list is not a tuple"); + return 0; + } + if (n == PyTuple_GET_SIZE(ob)) + return 1; + PyErr_Format( + PyExc_TypeError, + "expected %d arguments, got %zd", n, PyTuple_GET_SIZE(ob)); + return 0; } /* Generic wrappers for overloadable 'operators' such as __getitem__ */ /* There's a wrapper *function* for each distinct function typedef used - for type object slots (e.g. binaryfunc, ternaryfunc, etc.). There's a + for type object slots (e.g. binaryfunc, ternaryfunc, etc.). There's a wrapper *table* for each distinct operation (e.g. __len__, __add__). Most tables have only one entry; the tables for binary operators have two entries, one regular and one with reversed arguments. */ @@ -3991,253 +3991,253 @@ static PyObject * wrap_lenfunc(PyObject *self, PyObject *args, void *wrapped) { - lenfunc func = (lenfunc)wrapped; - Py_ssize_t res; + lenfunc func = (lenfunc)wrapped; + Py_ssize_t res; - if (!check_num_args(args, 0)) - return NULL; - res = (*func)(self); - if (res == -1 && PyErr_Occurred()) - return NULL; - return PyLong_FromLong((long)res); + if (!check_num_args(args, 0)) + return NULL; + res = (*func)(self); + if (res == -1 && PyErr_Occurred()) + return NULL; + return PyLong_FromLong((long)res); } static PyObject * wrap_inquirypred(PyObject *self, PyObject *args, void *wrapped) { - inquiry func = (inquiry)wrapped; - int res; + inquiry func = (inquiry)wrapped; + int res; - if (!check_num_args(args, 0)) - return NULL; - res = (*func)(self); - if (res == -1 && PyErr_Occurred()) - return NULL; - return PyBool_FromLong((long)res); + if (!check_num_args(args, 0)) + return NULL; + res = (*func)(self); + if (res == -1 && PyErr_Occurred()) + return NULL; + return PyBool_FromLong((long)res); } static PyObject * wrap_binaryfunc(PyObject *self, PyObject *args, void *wrapped) { - binaryfunc func = (binaryfunc)wrapped; - PyObject *other; + binaryfunc func = (binaryfunc)wrapped; + PyObject *other; - if (!check_num_args(args, 1)) - return NULL; - other = PyTuple_GET_ITEM(args, 0); - return (*func)(self, other); + if (!check_num_args(args, 1)) + return NULL; + other = PyTuple_GET_ITEM(args, 0); + return (*func)(self, other); } static PyObject * wrap_binaryfunc_l(PyObject *self, PyObject *args, void *wrapped) { - binaryfunc func = (binaryfunc)wrapped; - PyObject *other; + binaryfunc func = (binaryfunc)wrapped; + PyObject *other; - if (!check_num_args(args, 1)) - return NULL; - other = PyTuple_GET_ITEM(args, 0); - return (*func)(self, other); + if (!check_num_args(args, 1)) + return NULL; + other = PyTuple_GET_ITEM(args, 0); + return (*func)(self, other); } static PyObject * wrap_binaryfunc_r(PyObject *self, PyObject *args, void *wrapped) { - binaryfunc func = (binaryfunc)wrapped; - PyObject *other; + binaryfunc func = (binaryfunc)wrapped; + PyObject *other; - if (!check_num_args(args, 1)) - return NULL; - other = PyTuple_GET_ITEM(args, 0); - if (!PyType_IsSubtype(Py_TYPE(other), Py_TYPE(self))) { - Py_INCREF(Py_NotImplemented); - return Py_NotImplemented; - } - return (*func)(other, self); + if (!check_num_args(args, 1)) + return NULL; + other = PyTuple_GET_ITEM(args, 0); + if (!PyType_IsSubtype(Py_TYPE(other), Py_TYPE(self))) { + Py_INCREF(Py_NotImplemented); + return Py_NotImplemented; + } + return (*func)(other, self); } static PyObject * wrap_ternaryfunc(PyObject *self, PyObject *args, void *wrapped) { - ternaryfunc func = (ternaryfunc)wrapped; - PyObject *other; - PyObject *third = Py_None; - - /* Note: This wrapper only works for __pow__() */ - - if (!PyArg_UnpackTuple(args, "", 1, 2, &other, &third)) - return NULL; - return (*func)(self, other, third); + ternaryfunc func = (ternaryfunc)wrapped; + PyObject *other; + PyObject *third = Py_None; + + /* Note: This wrapper only works for __pow__() */ + + if (!PyArg_UnpackTuple(args, "", 1, 2, &other, &third)) + return NULL; + return (*func)(self, other, third); } static PyObject * wrap_ternaryfunc_r(PyObject *self, PyObject *args, void *wrapped) { - ternaryfunc func = (ternaryfunc)wrapped; - PyObject *other; - PyObject *third = Py_None; - - /* Note: This wrapper only works for __pow__() */ - - if (!PyArg_UnpackTuple(args, "", 1, 2, &other, &third)) - return NULL; - return (*func)(other, self, third); + ternaryfunc func = (ternaryfunc)wrapped; + PyObject *other; + PyObject *third = Py_None; + + /* Note: This wrapper only works for __pow__() */ + + if (!PyArg_UnpackTuple(args, "", 1, 2, &other, &third)) + return NULL; + return (*func)(other, self, third); } static PyObject * wrap_unaryfunc(PyObject *self, PyObject *args, void *wrapped) { - unaryfunc func = (unaryfunc)wrapped; + unaryfunc func = (unaryfunc)wrapped; - if (!check_num_args(args, 0)) - return NULL; - return (*func)(self); + if (!check_num_args(args, 0)) + return NULL; + return (*func)(self); } static PyObject * wrap_indexargfunc(PyObject *self, PyObject *args, void *wrapped) { - ssizeargfunc func = (ssizeargfunc)wrapped; - PyObject* o; - Py_ssize_t i; - - if (!PyArg_UnpackTuple(args, "", 1, 1, &o)) - return NULL; - i = PyNumber_AsSsize_t(o, PyExc_OverflowError); - if (i == -1 && PyErr_Occurred()) - return NULL; - return (*func)(self, i); + ssizeargfunc func = (ssizeargfunc)wrapped; + PyObject* o; + Py_ssize_t i; + + if (!PyArg_UnpackTuple(args, "", 1, 1, &o)) + return NULL; + i = PyNumber_AsSsize_t(o, PyExc_OverflowError); + if (i == -1 && PyErr_Occurred()) + return NULL; + return (*func)(self, i); } static Py_ssize_t getindex(PyObject *self, PyObject *arg) { - Py_ssize_t i; + Py_ssize_t i; - i = PyNumber_AsSsize_t(arg, PyExc_OverflowError); - if (i == -1 && PyErr_Occurred()) - return -1; - if (i < 0) { - PySequenceMethods *sq = Py_TYPE(self)->tp_as_sequence; - if (sq && sq->sq_length) { - Py_ssize_t n = (*sq->sq_length)(self); - if (n < 0) - return -1; - i += n; - } - } - return i; + i = PyNumber_AsSsize_t(arg, PyExc_OverflowError); + if (i == -1 && PyErr_Occurred()) + return -1; + if (i < 0) { + PySequenceMethods *sq = Py_TYPE(self)->tp_as_sequence; + if (sq && sq->sq_length) { + Py_ssize_t n = (*sq->sq_length)(self); + if (n < 0) + return -1; + i += n; + } + } + return i; } static PyObject * wrap_sq_item(PyObject *self, PyObject *args, void *wrapped) { - ssizeargfunc func = (ssizeargfunc)wrapped; - PyObject *arg; - Py_ssize_t i; - - if (PyTuple_GET_SIZE(args) == 1) { - arg = PyTuple_GET_ITEM(args, 0); - i = getindex(self, arg); - if (i == -1 && PyErr_Occurred()) - return NULL; - return (*func)(self, i); - } - check_num_args(args, 1); - assert(PyErr_Occurred()); - return NULL; + ssizeargfunc func = (ssizeargfunc)wrapped; + PyObject *arg; + Py_ssize_t i; + + if (PyTuple_GET_SIZE(args) == 1) { + arg = PyTuple_GET_ITEM(args, 0); + i = getindex(self, arg); + if (i == -1 && PyErr_Occurred()) + return NULL; + return (*func)(self, i); + } + check_num_args(args, 1); + assert(PyErr_Occurred()); + return NULL; } static PyObject * wrap_sq_setitem(PyObject *self, PyObject *args, void *wrapped) { - ssizeobjargproc func = (ssizeobjargproc)wrapped; - Py_ssize_t i; - int res; - PyObject *arg, *value; - - if (!PyArg_UnpackTuple(args, "", 2, 2, &arg, &value)) - return NULL; - i = getindex(self, arg); - if (i == -1 && PyErr_Occurred()) - return NULL; - res = (*func)(self, i, value); - if (res == -1 && PyErr_Occurred()) - return NULL; - Py_INCREF(Py_None); - return Py_None; + ssizeobjargproc func = (ssizeobjargproc)wrapped; + Py_ssize_t i; + int res; + PyObject *arg, *value; + + if (!PyArg_UnpackTuple(args, "", 2, 2, &arg, &value)) + return NULL; + i = getindex(self, arg); + if (i == -1 && PyErr_Occurred()) + return NULL; + res = (*func)(self, i, value); + if (res == -1 && PyErr_Occurred()) + return NULL; + Py_INCREF(Py_None); + return Py_None; } static PyObject * wrap_sq_delitem(PyObject *self, PyObject *args, void *wrapped) { - ssizeobjargproc func = (ssizeobjargproc)wrapped; - Py_ssize_t i; - int res; - PyObject *arg; - - if (!check_num_args(args, 1)) - return NULL; - arg = PyTuple_GET_ITEM(args, 0); - i = getindex(self, arg); - if (i == -1 && PyErr_Occurred()) - return NULL; - res = (*func)(self, i, NULL); - if (res == -1 && PyErr_Occurred()) - return NULL; - Py_INCREF(Py_None); - return Py_None; + ssizeobjargproc func = (ssizeobjargproc)wrapped; + Py_ssize_t i; + int res; + PyObject *arg; + + if (!check_num_args(args, 1)) + return NULL; + arg = PyTuple_GET_ITEM(args, 0); + i = getindex(self, arg); + if (i == -1 && PyErr_Occurred()) + return NULL; + res = (*func)(self, i, NULL); + if (res == -1 && PyErr_Occurred()) + return NULL; + Py_INCREF(Py_None); + return Py_None; } /* XXX objobjproc is a misnomer; should be objargpred */ static PyObject * wrap_objobjproc(PyObject *self, PyObject *args, void *wrapped) { - objobjproc func = (objobjproc)wrapped; - int res; - PyObject *value; - - if (!check_num_args(args, 1)) - return NULL; - value = PyTuple_GET_ITEM(args, 0); - res = (*func)(self, value); - if (res == -1 && PyErr_Occurred()) - return NULL; - else - return PyBool_FromLong(res); + objobjproc func = (objobjproc)wrapped; + int res; + PyObject *value; + + if (!check_num_args(args, 1)) + return NULL; + value = PyTuple_GET_ITEM(args, 0); + res = (*func)(self, value); + if (res == -1 && PyErr_Occurred()) + return NULL; + else + return PyBool_FromLong(res); } static PyObject * wrap_objobjargproc(PyObject *self, PyObject *args, void *wrapped) { - objobjargproc func = (objobjargproc)wrapped; - int res; - PyObject *key, *value; - - if (!PyArg_UnpackTuple(args, "", 2, 2, &key, &value)) - return NULL; - res = (*func)(self, key, value); - if (res == -1 && PyErr_Occurred()) - return NULL; - Py_INCREF(Py_None); - return Py_None; + objobjargproc func = (objobjargproc)wrapped; + int res; + PyObject *key, *value; + + if (!PyArg_UnpackTuple(args, "", 2, 2, &key, &value)) + return NULL; + res = (*func)(self, key, value); + if (res == -1 && PyErr_Occurred()) + return NULL; + Py_INCREF(Py_None); + return Py_None; } static PyObject * wrap_delitem(PyObject *self, PyObject *args, void *wrapped) { - objobjargproc func = (objobjargproc)wrapped; - int res; - PyObject *key; - - if (!check_num_args(args, 1)) - return NULL; - key = PyTuple_GET_ITEM(args, 0); - res = (*func)(self, key, NULL); - if (res == -1 && PyErr_Occurred()) - return NULL; - Py_INCREF(Py_None); - return Py_None; + objobjargproc func = (objobjargproc)wrapped; + int res; + PyObject *key; + + if (!check_num_args(args, 1)) + return NULL; + key = PyTuple_GET_ITEM(args, 0); + res = (*func)(self, key, NULL); + if (res == -1 && PyErr_Occurred()) + return NULL; + Py_INCREF(Py_None); + return Py_None; } /* Helper to check for object.__setattr__ or __delattr__ applied to a type. @@ -4245,90 +4245,90 @@ static int hackcheck(PyObject *self, setattrofunc func, char *what) { - PyTypeObject *type = Py_TYPE(self); - while (type && type->tp_flags & Py_TPFLAGS_HEAPTYPE) - type = type->tp_base; - /* If type is NULL now, this is a really weird type. - In the spirit of backwards compatibility (?), just shut up. */ - if (type && type->tp_setattro != func) { - PyErr_Format(PyExc_TypeError, - "can't apply this %s to %s object", - what, - type->tp_name); - return 0; - } - return 1; + PyTypeObject *type = Py_TYPE(self); + while (type && type->tp_flags & Py_TPFLAGS_HEAPTYPE) + type = type->tp_base; + /* If type is NULL now, this is a really weird type. + In the spirit of backwards compatibility (?), just shut up. */ + if (type && type->tp_setattro != func) { + PyErr_Format(PyExc_TypeError, + "can't apply this %s to %s object", + what, + type->tp_name); + return 0; + } + return 1; } static PyObject * wrap_setattr(PyObject *self, PyObject *args, void *wrapped) { - setattrofunc func = (setattrofunc)wrapped; - int res; - PyObject *name, *value; - - if (!PyArg_UnpackTuple(args, "", 2, 2, &name, &value)) - return NULL; - if (!hackcheck(self, func, "__setattr__")) - return NULL; - res = (*func)(self, name, value); - if (res < 0) - return NULL; - Py_INCREF(Py_None); - return Py_None; + setattrofunc func = (setattrofunc)wrapped; + int res; + PyObject *name, *value; + + if (!PyArg_UnpackTuple(args, "", 2, 2, &name, &value)) + return NULL; + if (!hackcheck(self, func, "__setattr__")) + return NULL; + res = (*func)(self, name, value); + if (res < 0) + return NULL; + Py_INCREF(Py_None); + return Py_None; } static PyObject * wrap_delattr(PyObject *self, PyObject *args, void *wrapped) { - setattrofunc func = (setattrofunc)wrapped; - int res; - PyObject *name; - - if (!check_num_args(args, 1)) - return NULL; - name = PyTuple_GET_ITEM(args, 0); - if (!hackcheck(self, func, "__delattr__")) - return NULL; - res = (*func)(self, name, NULL); - if (res < 0) - return NULL; - Py_INCREF(Py_None); - return Py_None; + setattrofunc func = (setattrofunc)wrapped; + int res; + PyObject *name; + + if (!check_num_args(args, 1)) + return NULL; + name = PyTuple_GET_ITEM(args, 0); + if (!hackcheck(self, func, "__delattr__")) + return NULL; + res = (*func)(self, name, NULL); + if (res < 0) + return NULL; + Py_INCREF(Py_None); + return Py_None; } static PyObject * wrap_hashfunc(PyObject *self, PyObject *args, void *wrapped) { - hashfunc func = (hashfunc)wrapped; - long res; + hashfunc func = (hashfunc)wrapped; + long res; - if (!check_num_args(args, 0)) - return NULL; - res = (*func)(self); - if (res == -1 && PyErr_Occurred()) - return NULL; - return PyLong_FromLong(res); + if (!check_num_args(args, 0)) + return NULL; + res = (*func)(self); + if (res == -1 && PyErr_Occurred()) + return NULL; + return PyLong_FromLong(res); } static PyObject * wrap_call(PyObject *self, PyObject *args, void *wrapped, PyObject *kwds) { - ternaryfunc func = (ternaryfunc)wrapped; + ternaryfunc func = (ternaryfunc)wrapped; - return (*func)(self, args, kwds); + return (*func)(self, args, kwds); } static PyObject * wrap_richcmpfunc(PyObject *self, PyObject *args, void *wrapped, int op) { - richcmpfunc func = (richcmpfunc)wrapped; - PyObject *other; + richcmpfunc func = (richcmpfunc)wrapped; + PyObject *other; - if (!check_num_args(args, 1)) - return NULL; - other = PyTuple_GET_ITEM(args, 0); - return (*func)(self, other, op); + if (!check_num_args(args, 1)) + return NULL; + other = PyTuple_GET_ITEM(args, 0); + return (*func)(self, other, op); } #undef RICHCMP_WRAPPER @@ -4336,7 +4336,7 @@ static PyObject * \ richcmp_##NAME(PyObject *self, PyObject *args, void *wrapped) \ { \ - return wrap_richcmpfunc(self, args, wrapped, OP); \ + return wrap_richcmpfunc(self, args, wrapped, OP); \ } RICHCMP_WRAPPER(lt, Py_LT) @@ -4349,164 +4349,164 @@ static PyObject * wrap_next(PyObject *self, PyObject *args, void *wrapped) { - unaryfunc func = (unaryfunc)wrapped; - PyObject *res; + unaryfunc func = (unaryfunc)wrapped; + PyObject *res; - if (!check_num_args(args, 0)) - return NULL; - res = (*func)(self); - if (res == NULL && !PyErr_Occurred()) - PyErr_SetNone(PyExc_StopIteration); - return res; + if (!check_num_args(args, 0)) + return NULL; + res = (*func)(self); + if (res == NULL && !PyErr_Occurred()) + PyErr_SetNone(PyExc_StopIteration); + return res; } static PyObject * wrap_descr_get(PyObject *self, PyObject *args, void *wrapped) { - descrgetfunc func = (descrgetfunc)wrapped; - PyObject *obj; - PyObject *type = NULL; - - if (!PyArg_UnpackTuple(args, "", 1, 2, &obj, &type)) - return NULL; - if (obj == Py_None) - obj = NULL; - if (type == Py_None) - type = NULL; - if (type == NULL &&obj == NULL) { - PyErr_SetString(PyExc_TypeError, - "__get__(None, None) is invalid"); - return NULL; - } - return (*func)(self, obj, type); + descrgetfunc func = (descrgetfunc)wrapped; + PyObject *obj; + PyObject *type = NULL; + + if (!PyArg_UnpackTuple(args, "", 1, 2, &obj, &type)) + return NULL; + if (obj == Py_None) + obj = NULL; + if (type == Py_None) + type = NULL; + if (type == NULL &&obj == NULL) { + PyErr_SetString(PyExc_TypeError, + "__get__(None, None) is invalid"); + return NULL; + } + return (*func)(self, obj, type); } static PyObject * wrap_descr_set(PyObject *self, PyObject *args, void *wrapped) { - descrsetfunc func = (descrsetfunc)wrapped; - PyObject *obj, *value; - int ret; - - if (!PyArg_UnpackTuple(args, "", 2, 2, &obj, &value)) - return NULL; - ret = (*func)(self, obj, value); - if (ret < 0) - return NULL; - Py_INCREF(Py_None); - return Py_None; + descrsetfunc func = (descrsetfunc)wrapped; + PyObject *obj, *value; + int ret; + + if (!PyArg_UnpackTuple(args, "", 2, 2, &obj, &value)) + return NULL; + ret = (*func)(self, obj, value); + if (ret < 0) + return NULL; + Py_INCREF(Py_None); + return Py_None; } static PyObject * wrap_descr_delete(PyObject *self, PyObject *args, void *wrapped) { - descrsetfunc func = (descrsetfunc)wrapped; - PyObject *obj; - int ret; - - if (!check_num_args(args, 1)) - return NULL; - obj = PyTuple_GET_ITEM(args, 0); - ret = (*func)(self, obj, NULL); - if (ret < 0) - return NULL; - Py_INCREF(Py_None); - return Py_None; + descrsetfunc func = (descrsetfunc)wrapped; + PyObject *obj; + int ret; + + if (!check_num_args(args, 1)) + return NULL; + obj = PyTuple_GET_ITEM(args, 0); + ret = (*func)(self, obj, NULL); + if (ret < 0) + return NULL; + Py_INCREF(Py_None); + return Py_None; } static PyObject * wrap_init(PyObject *self, PyObject *args, void *wrapped, PyObject *kwds) { - initproc func = (initproc)wrapped; + initproc func = (initproc)wrapped; - if (func(self, args, kwds) < 0) - return NULL; - Py_INCREF(Py_None); - return Py_None; + if (func(self, args, kwds) < 0) + return NULL; + Py_INCREF(Py_None); + return Py_None; } static PyObject * tp_new_wrapper(PyObject *self, PyObject *args, PyObject *kwds) { - PyTypeObject *type, *subtype, *staticbase; - PyObject *arg0, *res; + PyTypeObject *type, *subtype, *staticbase; + PyObject *arg0, *res; - if (self == NULL || !PyType_Check(self)) - Py_FatalError("__new__() called with non-type 'self'"); - type = (PyTypeObject *)self; - if (!PyTuple_Check(args) || PyTuple_GET_SIZE(args) < 1) { - PyErr_Format(PyExc_TypeError, - "%s.__new__(): not enough arguments", - type->tp_name); - return NULL; - } - arg0 = PyTuple_GET_ITEM(args, 0); - if (!PyType_Check(arg0)) { - PyErr_Format(PyExc_TypeError, - "%s.__new__(X): X is not a type object (%s)", - type->tp_name, - Py_TYPE(arg0)->tp_name); - return NULL; - } - subtype = (PyTypeObject *)arg0; - if (!PyType_IsSubtype(subtype, type)) { - PyErr_Format(PyExc_TypeError, - "%s.__new__(%s): %s is not a subtype of %s", - type->tp_name, - subtype->tp_name, - subtype->tp_name, - type->tp_name); - return NULL; - } - - /* Check that the use doesn't do something silly and unsafe like - object.__new__(dict). To do this, we check that the - most derived base that's not a heap type is this type. */ - staticbase = subtype; - while (staticbase && (staticbase->tp_flags & Py_TPFLAGS_HEAPTYPE)) - staticbase = staticbase->tp_base; - /* If staticbase is NULL now, it is a really weird type. - In the spirit of backwards compatibility (?), just shut up. */ - if (staticbase && staticbase->tp_new != type->tp_new) { - PyErr_Format(PyExc_TypeError, - "%s.__new__(%s) is not safe, use %s.__new__()", - type->tp_name, - subtype->tp_name, - staticbase == NULL ? "?" : staticbase->tp_name); - return NULL; - } - - args = PyTuple_GetSlice(args, 1, PyTuple_GET_SIZE(args)); - if (args == NULL) - return NULL; - res = type->tp_new(subtype, args, kwds); - Py_DECREF(args); - return res; + if (self == NULL || !PyType_Check(self)) + Py_FatalError("__new__() called with non-type 'self'"); + type = (PyTypeObject *)self; + if (!PyTuple_Check(args) || PyTuple_GET_SIZE(args) < 1) { + PyErr_Format(PyExc_TypeError, + "%s.__new__(): not enough arguments", + type->tp_name); + return NULL; + } + arg0 = PyTuple_GET_ITEM(args, 0); + if (!PyType_Check(arg0)) { + PyErr_Format(PyExc_TypeError, + "%s.__new__(X): X is not a type object (%s)", + type->tp_name, + Py_TYPE(arg0)->tp_name); + return NULL; + } + subtype = (PyTypeObject *)arg0; + if (!PyType_IsSubtype(subtype, type)) { + PyErr_Format(PyExc_TypeError, + "%s.__new__(%s): %s is not a subtype of %s", + type->tp_name, + subtype->tp_name, + subtype->tp_name, + type->tp_name); + return NULL; + } + + /* Check that the use doesn't do something silly and unsafe like + object.__new__(dict). To do this, we check that the + most derived base that's not a heap type is this type. */ + staticbase = subtype; + while (staticbase && (staticbase->tp_flags & Py_TPFLAGS_HEAPTYPE)) + staticbase = staticbase->tp_base; + /* If staticbase is NULL now, it is a really weird type. + In the spirit of backwards compatibility (?), just shut up. */ + if (staticbase && staticbase->tp_new != type->tp_new) { + PyErr_Format(PyExc_TypeError, + "%s.__new__(%s) is not safe, use %s.__new__()", + type->tp_name, + subtype->tp_name, + staticbase == NULL ? "?" : staticbase->tp_name); + return NULL; + } + + args = PyTuple_GetSlice(args, 1, PyTuple_GET_SIZE(args)); + if (args == NULL) + return NULL; + res = type->tp_new(subtype, args, kwds); + Py_DECREF(args); + return res; } static struct PyMethodDef tp_new_methoddef[] = { - {"__new__", (PyCFunction)tp_new_wrapper, METH_VARARGS|METH_KEYWORDS, - PyDoc_STR("T.__new__(S, ...) -> " - "a new object with type S, a subtype of T")}, - {0} + {"__new__", (PyCFunction)tp_new_wrapper, METH_VARARGS|METH_KEYWORDS, + PyDoc_STR("T.__new__(S, ...) -> " + "a new object with type S, a subtype of T")}, + {0} }; static int add_tp_new_wrapper(PyTypeObject *type) { - PyObject *func; + PyObject *func; - if (PyDict_GetItemString(type->tp_dict, "__new__") != NULL) - return 0; - func = PyCFunction_New(tp_new_methoddef, (PyObject *)type); - if (func == NULL) - return -1; - if (PyDict_SetItemString(type->tp_dict, "__new__", func)) { - Py_DECREF(func); - return -1; - } - Py_DECREF(func); - return 0; + if (PyDict_GetItemString(type->tp_dict, "__new__") != NULL) + return 0; + func = PyCFunction_New(tp_new_methoddef, (PyObject *)type); + if (func == NULL) + return -1; + if (PyDict_SetItemString(type->tp_dict, "__new__", func)) { + Py_DECREF(func); + return -1; + } + Py_DECREF(func); + return 0; } /* Slot wrappers that call the corresponding __foo__ slot. See comments @@ -4516,16 +4516,16 @@ static PyObject * \ FUNCNAME(PyObject *self) \ { \ - static PyObject *cache_str; \ - return call_method(self, OPSTR, &cache_str, "()"); \ + static PyObject *cache_str; \ + return call_method(self, OPSTR, &cache_str, "()"); \ } #define SLOT1(FUNCNAME, OPSTR, ARG1TYPE, ARGCODES) \ static PyObject * \ FUNCNAME(PyObject *self, ARG1TYPE arg1) \ { \ - static PyObject *cache_str; \ - return call_method(self, OPSTR, &cache_str, "(" ARGCODES ")", arg1); \ + static PyObject *cache_str; \ + return call_method(self, OPSTR, &cache_str, "(" ARGCODES ")", arg1); \ } /* Boolean helper for SLOT1BINFULL(). @@ -4533,33 +4533,33 @@ static int method_is_overloaded(PyObject *left, PyObject *right, char *name) { - PyObject *a, *b; - int ok; + PyObject *a, *b; + int ok; - b = PyObject_GetAttrString((PyObject *)(Py_TYPE(right)), name); - if (b == NULL) { - PyErr_Clear(); - /* If right doesn't have it, it's not overloaded */ - return 0; - } - - a = PyObject_GetAttrString((PyObject *)(Py_TYPE(left)), name); - if (a == NULL) { - PyErr_Clear(); - Py_DECREF(b); - /* If right has it but left doesn't, it's overloaded */ - return 1; - } - - ok = PyObject_RichCompareBool(a, b, Py_NE); - Py_DECREF(a); - Py_DECREF(b); - if (ok < 0) { - PyErr_Clear(); - return 0; - } + b = PyObject_GetAttrString((PyObject *)(Py_TYPE(right)), name); + if (b == NULL) { + PyErr_Clear(); + /* If right doesn't have it, it's not overloaded */ + return 0; + } + + a = PyObject_GetAttrString((PyObject *)(Py_TYPE(left)), name); + if (a == NULL) { + PyErr_Clear(); + Py_DECREF(b); + /* If right has it but left doesn't, it's overloaded */ + return 1; + } + + ok = PyObject_RichCompareBool(a, b, Py_NE); + Py_DECREF(a); + Py_DECREF(b); + if (ok < 0) { + PyErr_Clear(); + return 0; + } - return ok; + return ok; } @@ -4567,68 +4567,68 @@ static PyObject * \ FUNCNAME(PyObject *self, PyObject *other) \ { \ - static PyObject *cache_str, *rcache_str; \ - int do_other = Py_TYPE(self) != Py_TYPE(other) && \ - Py_TYPE(other)->tp_as_number != NULL && \ - Py_TYPE(other)->tp_as_number->SLOTNAME == TESTFUNC; \ - if (Py_TYPE(self)->tp_as_number != NULL && \ - Py_TYPE(self)->tp_as_number->SLOTNAME == TESTFUNC) { \ - PyObject *r; \ - if (do_other && \ - PyType_IsSubtype(Py_TYPE(other), Py_TYPE(self)) && \ - method_is_overloaded(self, other, ROPSTR)) { \ - r = call_maybe( \ - other, ROPSTR, &rcache_str, "(O)", self); \ - if (r != Py_NotImplemented) \ - return r; \ - Py_DECREF(r); \ - do_other = 0; \ - } \ - r = call_maybe( \ - self, OPSTR, &cache_str, "(O)", other); \ - if (r != Py_NotImplemented || \ - Py_TYPE(other) == Py_TYPE(self)) \ - return r; \ - Py_DECREF(r); \ - } \ - if (do_other) { \ - return call_maybe( \ - other, ROPSTR, &rcache_str, "(O)", self); \ - } \ - Py_INCREF(Py_NotImplemented); \ - return Py_NotImplemented; \ + static PyObject *cache_str, *rcache_str; \ + int do_other = Py_TYPE(self) != Py_TYPE(other) && \ + Py_TYPE(other)->tp_as_number != NULL && \ + Py_TYPE(other)->tp_as_number->SLOTNAME == TESTFUNC; \ + if (Py_TYPE(self)->tp_as_number != NULL && \ + Py_TYPE(self)->tp_as_number->SLOTNAME == TESTFUNC) { \ + PyObject *r; \ + if (do_other && \ + PyType_IsSubtype(Py_TYPE(other), Py_TYPE(self)) && \ + method_is_overloaded(self, other, ROPSTR)) { \ + r = call_maybe( \ + other, ROPSTR, &rcache_str, "(O)", self); \ + if (r != Py_NotImplemented) \ + return r; \ + Py_DECREF(r); \ + do_other = 0; \ + } \ + r = call_maybe( \ + self, OPSTR, &cache_str, "(O)", other); \ + if (r != Py_NotImplemented || \ + Py_TYPE(other) == Py_TYPE(self)) \ + return r; \ + Py_DECREF(r); \ + } \ + if (do_other) { \ + return call_maybe( \ + other, ROPSTR, &rcache_str, "(O)", self); \ + } \ + Py_INCREF(Py_NotImplemented); \ + return Py_NotImplemented; \ } #define SLOT1BIN(FUNCNAME, SLOTNAME, OPSTR, ROPSTR) \ - SLOT1BINFULL(FUNCNAME, FUNCNAME, SLOTNAME, OPSTR, ROPSTR) + SLOT1BINFULL(FUNCNAME, FUNCNAME, SLOTNAME, OPSTR, ROPSTR) #define SLOT2(FUNCNAME, OPSTR, ARG1TYPE, ARG2TYPE, ARGCODES) \ static PyObject * \ FUNCNAME(PyObject *self, ARG1TYPE arg1, ARG2TYPE arg2) \ { \ - static PyObject *cache_str; \ - return call_method(self, OPSTR, &cache_str, \ - "(" ARGCODES ")", arg1, arg2); \ + static PyObject *cache_str; \ + return call_method(self, OPSTR, &cache_str, \ + "(" ARGCODES ")", arg1, arg2); \ } static Py_ssize_t slot_sq_length(PyObject *self) { - static PyObject *len_str; - PyObject *res = call_method(self, "__len__", &len_str, "()"); - Py_ssize_t len; - - if (res == NULL) - return -1; - len = PyNumber_AsSsize_t(res, PyExc_OverflowError); - Py_DECREF(res); - if (len < 0) { - if (!PyErr_Occurred()) - PyErr_SetString(PyExc_ValueError, - "__len__() should return >= 0"); - return -1; - } - return len; + static PyObject *len_str; + PyObject *res = call_method(self, "__len__", &len_str, "()"); + Py_ssize_t len; + + if (res == NULL) + return -1; + len = PyNumber_AsSsize_t(res, PyExc_OverflowError); + Py_DECREF(res); + if (len < 0) { + if (!PyErr_Occurred()) + PyErr_SetString(PyExc_ValueError, + "__len__() should return >= 0"); + return -1; + } + return len; } /* Super-optimized version of slot_sq_item. @@ -4636,93 +4636,93 @@ static PyObject * slot_sq_item(PyObject *self, Py_ssize_t i) { - static PyObject *getitem_str; - PyObject *func, *args = NULL, *ival = NULL, *retval = NULL; - descrgetfunc f; - - if (getitem_str == NULL) { - getitem_str = PyUnicode_InternFromString("__getitem__"); - if (getitem_str == NULL) - return NULL; - } - func = _PyType_Lookup(Py_TYPE(self), getitem_str); - if (func != NULL) { - if ((f = Py_TYPE(func)->tp_descr_get) == NULL) - Py_INCREF(func); - else { - func = f(func, self, (PyObject *)(Py_TYPE(self))); - if (func == NULL) { - return NULL; - } - } - ival = PyLong_FromSsize_t(i); - if (ival != NULL) { - args = PyTuple_New(1); - if (args != NULL) { - PyTuple_SET_ITEM(args, 0, ival); - retval = PyObject_Call(func, args, NULL); - Py_XDECREF(args); - Py_XDECREF(func); - return retval; - } - } - } - else { - PyErr_SetObject(PyExc_AttributeError, getitem_str); - } - Py_XDECREF(args); - Py_XDECREF(ival); - Py_XDECREF(func); - return NULL; + static PyObject *getitem_str; + PyObject *func, *args = NULL, *ival = NULL, *retval = NULL; + descrgetfunc f; + + if (getitem_str == NULL) { + getitem_str = PyUnicode_InternFromString("__getitem__"); + if (getitem_str == NULL) + return NULL; + } + func = _PyType_Lookup(Py_TYPE(self), getitem_str); + if (func != NULL) { + if ((f = Py_TYPE(func)->tp_descr_get) == NULL) + Py_INCREF(func); + else { + func = f(func, self, (PyObject *)(Py_TYPE(self))); + if (func == NULL) { + return NULL; + } + } + ival = PyLong_FromSsize_t(i); + if (ival != NULL) { + args = PyTuple_New(1); + if (args != NULL) { + PyTuple_SET_ITEM(args, 0, ival); + retval = PyObject_Call(func, args, NULL); + Py_XDECREF(args); + Py_XDECREF(func); + return retval; + } + } + } + else { + PyErr_SetObject(PyExc_AttributeError, getitem_str); + } + Py_XDECREF(args); + Py_XDECREF(ival); + Py_XDECREF(func); + return NULL; } static int slot_sq_ass_item(PyObject *self, Py_ssize_t index, PyObject *value) { - PyObject *res; - static PyObject *delitem_str, *setitem_str; + PyObject *res; + static PyObject *delitem_str, *setitem_str; - if (value == NULL) - res = call_method(self, "__delitem__", &delitem_str, - "(n)", index); - else - res = call_method(self, "__setitem__", &setitem_str, - "(nO)", index, value); - if (res == NULL) - return -1; - Py_DECREF(res); - return 0; + if (value == NULL) + res = call_method(self, "__delitem__", &delitem_str, + "(n)", index); + else + res = call_method(self, "__setitem__", &setitem_str, + "(nO)", index, value); + if (res == NULL) + return -1; + Py_DECREF(res); + return 0; } static int slot_sq_contains(PyObject *self, PyObject *value) { - PyObject *func, *res, *args; - int result = -1; + PyObject *func, *res, *args; + int result = -1; - static PyObject *contains_str; + static PyObject *contains_str; - func = lookup_maybe(self, "__contains__", &contains_str); - if (func != NULL) { - args = PyTuple_Pack(1, value); - if (args == NULL) - res = NULL; - else { - res = PyObject_Call(func, args, NULL); - Py_DECREF(args); - } - Py_DECREF(func); - if (res != NULL) { - result = PyObject_IsTrue(res); - Py_DECREF(res); - } - } - else if (! PyErr_Occurred()) { - /* Possible results: -1 and 1 */ - result = (int)_PySequence_IterSearch(self, value, - PY_ITERSEARCH_CONTAINS); - } - return result; + func = lookup_maybe(self, "__contains__", &contains_str); + if (func != NULL) { + args = PyTuple_Pack(1, value); + if (args == NULL) + res = NULL; + else { + res = PyObject_Call(func, args, NULL); + Py_DECREF(args); + } + Py_DECREF(func); + if (res != NULL) { + result = PyObject_IsTrue(res); + Py_DECREF(res); + } + } + else if (! PyErr_Occurred()) { + /* Possible results: -1 and 1 */ + result = (int)_PySequence_IterSearch(self, value, + PY_ITERSEARCH_CONTAINS); + } + return result; } #define slot_mp_length slot_sq_length @@ -4732,19 +4732,19 @@ static int slot_mp_ass_subscript(PyObject *self, PyObject *key, PyObject *value) { - PyObject *res; - static PyObject *delitem_str, *setitem_str; + PyObject *res; + static PyObject *delitem_str, *setitem_str; - if (value == NULL) - res = call_method(self, "__delitem__", &delitem_str, - "(O)", key); - else - res = call_method(self, "__setitem__", &setitem_str, - "(OO)", key, value); - if (res == NULL) - return -1; - Py_DECREF(res); - return 0; + if (value == NULL) + res = call_method(self, "__delitem__", &delitem_str, + "(O)", key); + else + res = call_method(self, "__setitem__", &setitem_str, + "(OO)", key, value); + if (res == NULL) + return -1; + Py_DECREF(res); + return 0; } SLOT1BIN(slot_nb_add, nb_add, "__add__", "__radd__") @@ -4756,25 +4756,25 @@ static PyObject *slot_nb_power(PyObject *, PyObject *, PyObject *); SLOT1BINFULL(slot_nb_power_binary, slot_nb_power, - nb_power, "__pow__", "__rpow__") + nb_power, "__pow__", "__rpow__") static PyObject * slot_nb_power(PyObject *self, PyObject *other, PyObject *modulus) { - static PyObject *pow_str; + static PyObject *pow_str; - if (modulus == Py_None) - return slot_nb_power_binary(self, other); - /* Three-arg power doesn't use __rpow__. But ternary_op - can call this when the second argument's type uses - slot_nb_power, so check before calling self.__pow__. */ - if (Py_TYPE(self)->tp_as_number != NULL && - Py_TYPE(self)->tp_as_number->nb_power == slot_nb_power) { - return call_method(self, "__pow__", &pow_str, - "(OO)", other, modulus); - } - Py_INCREF(Py_NotImplemented); - return Py_NotImplemented; + if (modulus == Py_None) + return slot_nb_power_binary(self, other); + /* Three-arg power doesn't use __rpow__. But ternary_op + can call this when the second argument's type uses + slot_nb_power, so check before calling self.__pow__. */ + if (Py_TYPE(self)->tp_as_number != NULL && + Py_TYPE(self)->tp_as_number->nb_power == slot_nb_power) { + return call_method(self, "__pow__", &pow_str, + "(OO)", other, modulus); + } + Py_INCREF(Py_NotImplemented); + return Py_NotImplemented; } SLOT0(slot_nb_negative, "__neg__") @@ -4784,52 +4784,52 @@ static int slot_nb_bool(PyObject *self) { - PyObject *func, *args; - static PyObject *bool_str, *len_str; - int result = -1; - int using_len = 0; - - func = lookup_maybe(self, "__bool__", &bool_str); - if (func == NULL) { - if (PyErr_Occurred()) - return -1; - func = lookup_maybe(self, "__len__", &len_str); - if (func == NULL) - return PyErr_Occurred() ? -1 : 1; - using_len = 1; - } - args = PyTuple_New(0); - if (args != NULL) { - PyObject *temp = PyObject_Call(func, args, NULL); - Py_DECREF(args); - if (temp != NULL) { - if (using_len) { - /* enforced by slot_nb_len */ - result = PyObject_IsTrue(temp); - } - else if (PyBool_Check(temp)) { - result = PyObject_IsTrue(temp); - } - else { - PyErr_Format(PyExc_TypeError, - "__bool__ should return " - "bool, returned %s", - Py_TYPE(temp)->tp_name); - result = -1; - } - Py_DECREF(temp); - } - } - Py_DECREF(func); - return result; + PyObject *func, *args; + static PyObject *bool_str, *len_str; + int result = -1; + int using_len = 0; + + func = lookup_maybe(self, "__bool__", &bool_str); + if (func == NULL) { + if (PyErr_Occurred()) + return -1; + func = lookup_maybe(self, "__len__", &len_str); + if (func == NULL) + return PyErr_Occurred() ? -1 : 1; + using_len = 1; + } + args = PyTuple_New(0); + if (args != NULL) { + PyObject *temp = PyObject_Call(func, args, NULL); + Py_DECREF(args); + if (temp != NULL) { + if (using_len) { + /* enforced by slot_nb_len */ + result = PyObject_IsTrue(temp); + } + else if (PyBool_Check(temp)) { + result = PyObject_IsTrue(temp); + } + else { + PyErr_Format(PyExc_TypeError, + "__bool__ should return " + "bool, returned %s", + Py_TYPE(temp)->tp_name); + result = -1; + } + Py_DECREF(temp); + } + } + Py_DECREF(func); + return result; } static PyObject * slot_nb_index(PyObject *self) { - static PyObject *index_str; - return call_method(self, "__index__", &index_str, "()"); + static PyObject *index_str; + return call_method(self, "__index__", &index_str, "()"); } @@ -4847,11 +4847,11 @@ SLOT1(slot_nb_inplace_multiply, "__imul__", PyObject *, "O") SLOT1(slot_nb_inplace_remainder, "__imod__", PyObject *, "O") /* Can't use SLOT1 here, because nb_inplace_power is ternary */ -static PyObject * -slot_nb_inplace_power(PyObject *self, PyObject * arg1, PyObject *arg2) -{ - static PyObject *cache_str; - return call_method(self, "__ipow__", &cache_str, "(" "O" ")", arg1); +static PyObject * +slot_nb_inplace_power(PyObject *self, PyObject * arg1, PyObject *arg2) +{ + static PyObject *cache_str; + return call_method(self, "__ipow__", &cache_str, "(" "O" ")", arg1); } SLOT1(slot_nb_inplace_lshift, "__ilshift__", PyObject *, "O") SLOT1(slot_nb_inplace_rshift, "__irshift__", PyObject *, "O") @@ -4859,7 +4859,7 @@ SLOT1(slot_nb_inplace_xor, "__ixor__", PyObject *, "O") SLOT1(slot_nb_inplace_or, "__ior__", PyObject *, "O") SLOT1BIN(slot_nb_floor_divide, nb_floor_divide, - "__floordiv__", "__rfloordiv__") + "__floordiv__", "__rfloordiv__") SLOT1BIN(slot_nb_true_divide, nb_true_divide, "__truediv__", "__rtruediv__") SLOT1(slot_nb_inplace_floor_divide, "__ifloordiv__", PyObject *, "O") SLOT1(slot_nb_inplace_true_divide, "__itruediv__", PyObject *, "O") @@ -4867,90 +4867,90 @@ static PyObject * slot_tp_repr(PyObject *self) { - PyObject *func, *res; - static PyObject *repr_str; + PyObject *func, *res; + static PyObject *repr_str; - func = lookup_method(self, "__repr__", &repr_str); - if (func != NULL) { - res = PyEval_CallObject(func, NULL); - Py_DECREF(func); - return res; - } - PyErr_Clear(); - return PyUnicode_FromFormat("<%s object at %p>", - Py_TYPE(self)->tp_name, self); + func = lookup_method(self, "__repr__", &repr_str); + if (func != NULL) { + res = PyEval_CallObject(func, NULL); + Py_DECREF(func); + return res; + } + PyErr_Clear(); + return PyUnicode_FromFormat("<%s object at %p>", + Py_TYPE(self)->tp_name, self); } static PyObject * slot_tp_str(PyObject *self) { - PyObject *func, *res; - static PyObject *str_str; + PyObject *func, *res; + static PyObject *str_str; - func = lookup_method(self, "__str__", &str_str); - if (func != NULL) { - res = PyEval_CallObject(func, NULL); - Py_DECREF(func); - return res; - } - else { - PyObject *ress; - PyErr_Clear(); - res = slot_tp_repr(self); - if (!res) - return NULL; - ress = _PyUnicode_AsDefaultEncodedString(res, NULL); - Py_DECREF(res); - return ress; - } + func = lookup_method(self, "__str__", &str_str); + if (func != NULL) { + res = PyEval_CallObject(func, NULL); + Py_DECREF(func); + return res; + } + else { + PyObject *ress; + PyErr_Clear(); + res = slot_tp_repr(self); + if (!res) + return NULL; + ress = _PyUnicode_AsDefaultEncodedString(res, NULL); + Py_DECREF(res); + return ress; + } } static long slot_tp_hash(PyObject *self) { - PyObject *func, *res; - static PyObject *hash_str; - long h; - - func = lookup_method(self, "__hash__", &hash_str); - - if (func == Py_None) { - Py_DECREF(func); - func = NULL; - } - - if (func == NULL) { - return PyObject_HashNotImplemented(self); - } - - res = PyEval_CallObject(func, NULL); - Py_DECREF(func); - if (res == NULL) - return -1; - if (PyLong_Check(res)) - h = PyLong_Type.tp_hash(res); - else - h = PyLong_AsLong(res); - Py_DECREF(res); - if (h == -1 && !PyErr_Occurred()) - h = -2; - return h; + PyObject *func, *res; + static PyObject *hash_str; + long h; + + func = lookup_method(self, "__hash__", &hash_str); + + if (func == Py_None) { + Py_DECREF(func); + func = NULL; + } + + if (func == NULL) { + return PyObject_HashNotImplemented(self); + } + + res = PyEval_CallObject(func, NULL); + Py_DECREF(func); + if (res == NULL) + return -1; + if (PyLong_Check(res)) + h = PyLong_Type.tp_hash(res); + else + h = PyLong_AsLong(res); + Py_DECREF(res); + if (h == -1 && !PyErr_Occurred()) + h = -2; + return h; } static PyObject * slot_tp_call(PyObject *self, PyObject *args, PyObject *kwds) { - static PyObject *call_str; - PyObject *meth = lookup_method(self, "__call__", &call_str); - PyObject *res; + static PyObject *call_str; + PyObject *meth = lookup_method(self, "__call__", &call_str); + PyObject *res; - if (meth == NULL) - return NULL; + if (meth == NULL) + return NULL; - res = PyObject_Call(meth, args, kwds); + res = PyObject_Call(meth, args, kwds); - Py_DECREF(meth); - return res; + Py_DECREF(meth); + return res; } /* There are two slot dispatch functions for tp_getattro. @@ -4967,100 +4967,100 @@ static PyObject * slot_tp_getattro(PyObject *self, PyObject *name) { - static PyObject *getattribute_str = NULL; - return call_method(self, "__getattribute__", &getattribute_str, - "(O)", name); + static PyObject *getattribute_str = NULL; + return call_method(self, "__getattribute__", &getattribute_str, + "(O)", name); } static PyObject * call_attribute(PyObject *self, PyObject *attr, PyObject *name) { - PyObject *res, *descr = NULL; - descrgetfunc f = Py_TYPE(attr)->tp_descr_get; + PyObject *res, *descr = NULL; + descrgetfunc f = Py_TYPE(attr)->tp_descr_get; - if (f != NULL) { - descr = f(attr, self, (PyObject *)(Py_TYPE(self))); - if (descr == NULL) - return NULL; - else - attr = descr; - } - res = PyObject_CallFunctionObjArgs(attr, name, NULL); - Py_XDECREF(descr); - return res; + if (f != NULL) { + descr = f(attr, self, (PyObject *)(Py_TYPE(self))); + if (descr == NULL) + return NULL; + else + attr = descr; + } + res = PyObject_CallFunctionObjArgs(attr, name, NULL); + Py_XDECREF(descr); + return res; } static PyObject * slot_tp_getattr_hook(PyObject *self, PyObject *name) { - PyTypeObject *tp = Py_TYPE(self); - PyObject *getattr, *getattribute, *res; - static PyObject *getattribute_str = NULL; - static PyObject *getattr_str = NULL; - - if (getattr_str == NULL) { - getattr_str = PyUnicode_InternFromString("__getattr__"); - if (getattr_str == NULL) - return NULL; - } - if (getattribute_str == NULL) { - getattribute_str = - PyUnicode_InternFromString("__getattribute__"); - if (getattribute_str == NULL) - return NULL; - } - /* speed hack: we could use lookup_maybe, but that would resolve the - method fully for each attribute lookup for classes with - __getattr__, even when the attribute is present. So we use - _PyType_Lookup and create the method only when needed, with - call_attribute. */ - getattr = _PyType_Lookup(tp, getattr_str); - if (getattr == NULL) { - /* No __getattr__ hook: use a simpler dispatcher */ - tp->tp_getattro = slot_tp_getattro; - return slot_tp_getattro(self, name); - } - Py_INCREF(getattr); - /* speed hack: we could use lookup_maybe, but that would resolve the - method fully for each attribute lookup for classes with - __getattr__, even when self has the default __getattribute__ - method. So we use _PyType_Lookup and create the method only when - needed, with call_attribute. */ - getattribute = _PyType_Lookup(tp, getattribute_str); - if (getattribute == NULL || - (Py_TYPE(getattribute) == &PyWrapperDescr_Type && - ((PyWrapperDescrObject *)getattribute)->d_wrapped == - (void *)PyObject_GenericGetAttr)) - res = PyObject_GenericGetAttr(self, name); - else { - Py_INCREF(getattribute); - res = call_attribute(self, getattribute, name); - Py_DECREF(getattribute); - } - if (res == NULL && PyErr_ExceptionMatches(PyExc_AttributeError)) { - PyErr_Clear(); - res = call_attribute(self, getattr, name); - } - Py_DECREF(getattr); - return res; + PyTypeObject *tp = Py_TYPE(self); + PyObject *getattr, *getattribute, *res; + static PyObject *getattribute_str = NULL; + static PyObject *getattr_str = NULL; + + if (getattr_str == NULL) { + getattr_str = PyUnicode_InternFromString("__getattr__"); + if (getattr_str == NULL) + return NULL; + } + if (getattribute_str == NULL) { + getattribute_str = + PyUnicode_InternFromString("__getattribute__"); + if (getattribute_str == NULL) + return NULL; + } + /* speed hack: we could use lookup_maybe, but that would resolve the + method fully for each attribute lookup for classes with + __getattr__, even when the attribute is present. So we use + _PyType_Lookup and create the method only when needed, with + call_attribute. */ + getattr = _PyType_Lookup(tp, getattr_str); + if (getattr == NULL) { + /* No __getattr__ hook: use a simpler dispatcher */ + tp->tp_getattro = slot_tp_getattro; + return slot_tp_getattro(self, name); + } + Py_INCREF(getattr); + /* speed hack: we could use lookup_maybe, but that would resolve the + method fully for each attribute lookup for classes with + __getattr__, even when self has the default __getattribute__ + method. So we use _PyType_Lookup and create the method only when + needed, with call_attribute. */ + getattribute = _PyType_Lookup(tp, getattribute_str); + if (getattribute == NULL || + (Py_TYPE(getattribute) == &PyWrapperDescr_Type && + ((PyWrapperDescrObject *)getattribute)->d_wrapped == + (void *)PyObject_GenericGetAttr)) + res = PyObject_GenericGetAttr(self, name); + else { + Py_INCREF(getattribute); + res = call_attribute(self, getattribute, name); + Py_DECREF(getattribute); + } + if (res == NULL && PyErr_ExceptionMatches(PyExc_AttributeError)) { + PyErr_Clear(); + res = call_attribute(self, getattr, name); + } + Py_DECREF(getattr); + return res; } static int slot_tp_setattro(PyObject *self, PyObject *name, PyObject *value) { - PyObject *res; - static PyObject *delattr_str, *setattr_str; + PyObject *res; + static PyObject *delattr_str, *setattr_str; - if (value == NULL) - res = call_method(self, "__delattr__", &delattr_str, - "(O)", name); - else - res = call_method(self, "__setattr__", &setattr_str, - "(OO)", name, value); - if (res == NULL) - return -1; - Py_DECREF(res); - return 0; + if (value == NULL) + res = call_method(self, "__delattr__", &delattr_str, + "(O)", name); + else + res = call_method(self, "__setattr__", &setattr_str, + "(OO)", name, value); + if (res == NULL) + return -1; + Py_DECREF(res); + return 0; } static char *name_op[] = { @@ -5075,222 +5075,222 @@ static PyObject * slot_tp_richcompare(PyObject *self, PyObject *other, int op) { - PyObject *func, *args, *res; - static PyObject *op_str[6]; + PyObject *func, *args, *res; + static PyObject *op_str[6]; - func = lookup_method(self, name_op[op], &op_str[op]); - if (func == NULL) { - PyErr_Clear(); - Py_INCREF(Py_NotImplemented); - return Py_NotImplemented; - } - args = PyTuple_Pack(1, other); - if (args == NULL) - res = NULL; - else { - res = PyObject_Call(func, args, NULL); - Py_DECREF(args); - } - Py_DECREF(func); - return res; + func = lookup_method(self, name_op[op], &op_str[op]); + if (func == NULL) { + PyErr_Clear(); + Py_INCREF(Py_NotImplemented); + return Py_NotImplemented; + } + args = PyTuple_Pack(1, other); + if (args == NULL) + res = NULL; + else { + res = PyObject_Call(func, args, NULL); + Py_DECREF(args); + } + Py_DECREF(func); + return res; } static PyObject * slot_tp_iter(PyObject *self) { - PyObject *func, *res; - static PyObject *iter_str, *getitem_str; + PyObject *func, *res; + static PyObject *iter_str, *getitem_str; - func = lookup_method(self, "__iter__", &iter_str); - if (func != NULL) { - PyObject *args; - args = res = PyTuple_New(0); - if (args != NULL) { - res = PyObject_Call(func, args, NULL); - Py_DECREF(args); - } - Py_DECREF(func); - return res; - } - PyErr_Clear(); - func = lookup_method(self, "__getitem__", &getitem_str); - if (func == NULL) { - PyErr_Format(PyExc_TypeError, - "'%.200s' object is not iterable", - Py_TYPE(self)->tp_name); - return NULL; - } - Py_DECREF(func); - return PySeqIter_New(self); + func = lookup_method(self, "__iter__", &iter_str); + if (func != NULL) { + PyObject *args; + args = res = PyTuple_New(0); + if (args != NULL) { + res = PyObject_Call(func, args, NULL); + Py_DECREF(args); + } + Py_DECREF(func); + return res; + } + PyErr_Clear(); + func = lookup_method(self, "__getitem__", &getitem_str); + if (func == NULL) { + PyErr_Format(PyExc_TypeError, + "'%.200s' object is not iterable", + Py_TYPE(self)->tp_name); + return NULL; + } + Py_DECREF(func); + return PySeqIter_New(self); } static PyObject * slot_tp_iternext(PyObject *self) { - static PyObject *next_str; - return call_method(self, "__next__", &next_str, "()"); + static PyObject *next_str; + return call_method(self, "__next__", &next_str, "()"); } static PyObject * slot_tp_descr_get(PyObject *self, PyObject *obj, PyObject *type) { - PyTypeObject *tp = Py_TYPE(self); - PyObject *get; - static PyObject *get_str = NULL; - - if (get_str == NULL) { - get_str = PyUnicode_InternFromString("__get__"); - if (get_str == NULL) - return NULL; - } - get = _PyType_Lookup(tp, get_str); - if (get == NULL) { - /* Avoid further slowdowns */ - if (tp->tp_descr_get == slot_tp_descr_get) - tp->tp_descr_get = NULL; - Py_INCREF(self); - return self; - } - if (obj == NULL) - obj = Py_None; - if (type == NULL) - type = Py_None; - return PyObject_CallFunctionObjArgs(get, self, obj, type, NULL); + PyTypeObject *tp = Py_TYPE(self); + PyObject *get; + static PyObject *get_str = NULL; + + if (get_str == NULL) { + get_str = PyUnicode_InternFromString("__get__"); + if (get_str == NULL) + return NULL; + } + get = _PyType_Lookup(tp, get_str); + if (get == NULL) { + /* Avoid further slowdowns */ + if (tp->tp_descr_get == slot_tp_descr_get) + tp->tp_descr_get = NULL; + Py_INCREF(self); + return self; + } + if (obj == NULL) + obj = Py_None; + if (type == NULL) + type = Py_None; + return PyObject_CallFunctionObjArgs(get, self, obj, type, NULL); } static int slot_tp_descr_set(PyObject *self, PyObject *target, PyObject *value) { - PyObject *res; - static PyObject *del_str, *set_str; + PyObject *res; + static PyObject *del_str, *set_str; - if (value == NULL) - res = call_method(self, "__delete__", &del_str, - "(O)", target); - else - res = call_method(self, "__set__", &set_str, - "(OO)", target, value); - if (res == NULL) - return -1; - Py_DECREF(res); - return 0; + if (value == NULL) + res = call_method(self, "__delete__", &del_str, + "(O)", target); + else + res = call_method(self, "__set__", &set_str, + "(OO)", target, value); + if (res == NULL) + return -1; + Py_DECREF(res); + return 0; } static int slot_tp_init(PyObject *self, PyObject *args, PyObject *kwds) { - static PyObject *init_str; - PyObject *meth = lookup_method(self, "__init__", &init_str); - PyObject *res; - - if (meth == NULL) - return -1; - res = PyObject_Call(meth, args, kwds); - Py_DECREF(meth); - if (res == NULL) - return -1; - if (res != Py_None) { - PyErr_Format(PyExc_TypeError, - "__init__() should return None, not '%.200s'", - Py_TYPE(res)->tp_name); - Py_DECREF(res); - return -1; - } - Py_DECREF(res); - return 0; + static PyObject *init_str; + PyObject *meth = lookup_method(self, "__init__", &init_str); + PyObject *res; + + if (meth == NULL) + return -1; + res = PyObject_Call(meth, args, kwds); + Py_DECREF(meth); + if (res == NULL) + return -1; + if (res != Py_None) { + PyErr_Format(PyExc_TypeError, + "__init__() should return None, not '%.200s'", + Py_TYPE(res)->tp_name); + Py_DECREF(res); + return -1; + } + Py_DECREF(res); + return 0; } static PyObject * slot_tp_new(PyTypeObject *type, PyObject *args, PyObject *kwds) { - static PyObject *new_str; - PyObject *func; - PyObject *newargs, *x; - Py_ssize_t i, n; - - if (new_str == NULL) { - new_str = PyUnicode_InternFromString("__new__"); - if (new_str == NULL) - return NULL; - } - func = PyObject_GetAttr((PyObject *)type, new_str); - if (func == NULL) - return NULL; - assert(PyTuple_Check(args)); - n = PyTuple_GET_SIZE(args); - newargs = PyTuple_New(n+1); - if (newargs == NULL) - return NULL; - Py_INCREF(type); - PyTuple_SET_ITEM(newargs, 0, (PyObject *)type); - for (i = 0; i < n; i++) { - x = PyTuple_GET_ITEM(args, i); - Py_INCREF(x); - PyTuple_SET_ITEM(newargs, i+1, x); - } - x = PyObject_Call(func, newargs, kwds); - Py_DECREF(newargs); - Py_DECREF(func); - return x; + static PyObject *new_str; + PyObject *func; + PyObject *newargs, *x; + Py_ssize_t i, n; + + if (new_str == NULL) { + new_str = PyUnicode_InternFromString("__new__"); + if (new_str == NULL) + return NULL; + } + func = PyObject_GetAttr((PyObject *)type, new_str); + if (func == NULL) + return NULL; + assert(PyTuple_Check(args)); + n = PyTuple_GET_SIZE(args); + newargs = PyTuple_New(n+1); + if (newargs == NULL) + return NULL; + Py_INCREF(type); + PyTuple_SET_ITEM(newargs, 0, (PyObject *)type); + for (i = 0; i < n; i++) { + x = PyTuple_GET_ITEM(args, i); + Py_INCREF(x); + PyTuple_SET_ITEM(newargs, i+1, x); + } + x = PyObject_Call(func, newargs, kwds); + Py_DECREF(newargs); + Py_DECREF(func); + return x; } static void slot_tp_del(PyObject *self) { - static PyObject *del_str = NULL; - PyObject *del, *res; - PyObject *error_type, *error_value, *error_traceback; - - /* Temporarily resurrect the object. */ - assert(self->ob_refcnt == 0); - self->ob_refcnt = 1; - - /* Save the current exception, if any. */ - PyErr_Fetch(&error_type, &error_value, &error_traceback); - - /* Execute __del__ method, if any. */ - del = lookup_maybe(self, "__del__", &del_str); - if (del != NULL) { - res = PyEval_CallObject(del, NULL); - if (res == NULL) - PyErr_WriteUnraisable(del); - else - Py_DECREF(res); - Py_DECREF(del); - } - - /* Restore the saved exception. */ - PyErr_Restore(error_type, error_value, error_traceback); - - /* Undo the temporary resurrection; can't use DECREF here, it would - * cause a recursive call. - */ - assert(self->ob_refcnt > 0); - if (--self->ob_refcnt == 0) - return; /* this is the normal path out */ - - /* __del__ resurrected it! Make it look like the original Py_DECREF - * never happened. - */ - { - Py_ssize_t refcnt = self->ob_refcnt; - _Py_NewReference(self); - self->ob_refcnt = refcnt; - } - assert(!PyType_IS_GC(Py_TYPE(self)) || - _Py_AS_GC(self)->gc.gc_refs != _PyGC_REFS_UNTRACKED); - /* If Py_REF_DEBUG, _Py_NewReference bumped _Py_RefTotal, so - * we need to undo that. */ - _Py_DEC_REFTOTAL; - /* If Py_TRACE_REFS, _Py_NewReference re-added self to the object - * chain, so no more to do there. - * If COUNT_ALLOCS, the original decref bumped tp_frees, and - * _Py_NewReference bumped tp_allocs: both of those need to be - * undone. - */ + static PyObject *del_str = NULL; + PyObject *del, *res; + PyObject *error_type, *error_value, *error_traceback; + + /* Temporarily resurrect the object. */ + assert(self->ob_refcnt == 0); + self->ob_refcnt = 1; + + /* Save the current exception, if any. */ + PyErr_Fetch(&error_type, &error_value, &error_traceback); + + /* Execute __del__ method, if any. */ + del = lookup_maybe(self, "__del__", &del_str); + if (del != NULL) { + res = PyEval_CallObject(del, NULL); + if (res == NULL) + PyErr_WriteUnraisable(del); + else + Py_DECREF(res); + Py_DECREF(del); + } + + /* Restore the saved exception. */ + PyErr_Restore(error_type, error_value, error_traceback); + + /* Undo the temporary resurrection; can't use DECREF here, it would + * cause a recursive call. + */ + assert(self->ob_refcnt > 0); + if (--self->ob_refcnt == 0) + return; /* this is the normal path out */ + + /* __del__ resurrected it! Make it look like the original Py_DECREF + * never happened. + */ + { + Py_ssize_t refcnt = self->ob_refcnt; + _Py_NewReference(self); + self->ob_refcnt = refcnt; + } + assert(!PyType_IS_GC(Py_TYPE(self)) || + _Py_AS_GC(self)->gc.gc_refs != _PyGC_REFS_UNTRACKED); + /* If Py_REF_DEBUG, _Py_NewReference bumped _Py_RefTotal, so + * we need to undo that. */ + _Py_DEC_REFTOTAL; + /* If Py_TRACE_REFS, _Py_NewReference re-added self to the object + * chain, so no more to do there. + * If COUNT_ALLOCS, the original decref bumped tp_frees, and + * _Py_NewReference bumped tp_allocs: both of those need to be + * undone. + */ #ifdef COUNT_ALLOCS - --Py_TYPE(self)->tp_frees; - --Py_TYPE(self)->tp_allocs; + --Py_TYPE(self)->tp_frees; + --Py_TYPE(self)->tp_allocs; #endif } @@ -5319,236 +5319,236 @@ #undef RBINSLOT #define TPSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \ - {NAME, offsetof(PyTypeObject, SLOT), (void *)(FUNCTION), WRAPPER, \ - PyDoc_STR(DOC)} + {NAME, offsetof(PyTypeObject, SLOT), (void *)(FUNCTION), WRAPPER, \ + PyDoc_STR(DOC)} #define FLSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC, FLAGS) \ - {NAME, offsetof(PyTypeObject, SLOT), (void *)(FUNCTION), WRAPPER, \ - PyDoc_STR(DOC), FLAGS} + {NAME, offsetof(PyTypeObject, SLOT), (void *)(FUNCTION), WRAPPER, \ + PyDoc_STR(DOC), FLAGS} #define ETSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \ - {NAME, offsetof(PyHeapTypeObject, SLOT), (void *)(FUNCTION), WRAPPER, \ - PyDoc_STR(DOC)} + {NAME, offsetof(PyHeapTypeObject, SLOT), (void *)(FUNCTION), WRAPPER, \ + PyDoc_STR(DOC)} #define SQSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \ - ETSLOT(NAME, as_sequence.SLOT, FUNCTION, WRAPPER, DOC) + ETSLOT(NAME, as_sequence.SLOT, FUNCTION, WRAPPER, DOC) #define MPSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \ - ETSLOT(NAME, as_mapping.SLOT, FUNCTION, WRAPPER, DOC) + ETSLOT(NAME, as_mapping.SLOT, FUNCTION, WRAPPER, DOC) #define NBSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \ - ETSLOT(NAME, as_number.SLOT, FUNCTION, WRAPPER, DOC) + ETSLOT(NAME, as_number.SLOT, FUNCTION, WRAPPER, DOC) #define UNSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \ - ETSLOT(NAME, as_number.SLOT, FUNCTION, WRAPPER, \ - "x." NAME "() <==> " DOC) + ETSLOT(NAME, as_number.SLOT, FUNCTION, WRAPPER, \ + "x." NAME "() <==> " DOC) #define IBSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \ - ETSLOT(NAME, as_number.SLOT, FUNCTION, WRAPPER, \ - "x." NAME "(y) <==> x" DOC "y") + ETSLOT(NAME, as_number.SLOT, FUNCTION, WRAPPER, \ + "x." NAME "(y) <==> x" DOC "y") #define BINSLOT(NAME, SLOT, FUNCTION, DOC) \ - ETSLOT(NAME, as_number.SLOT, FUNCTION, wrap_binaryfunc_l, \ - "x." NAME "(y) <==> x" DOC "y") + ETSLOT(NAME, as_number.SLOT, FUNCTION, wrap_binaryfunc_l, \ + "x." NAME "(y) <==> x" DOC "y") #define RBINSLOT(NAME, SLOT, FUNCTION, DOC) \ - ETSLOT(NAME, as_number.SLOT, FUNCTION, wrap_binaryfunc_r, \ - "x." NAME "(y) <==> y" DOC "x") + ETSLOT(NAME, as_number.SLOT, FUNCTION, wrap_binaryfunc_r, \ + "x." NAME "(y) <==> y" DOC "x") #define BINSLOTNOTINFIX(NAME, SLOT, FUNCTION, DOC) \ - ETSLOT(NAME, as_number.SLOT, FUNCTION, wrap_binaryfunc_l, \ - "x." NAME "(y) <==> " DOC) + ETSLOT(NAME, as_number.SLOT, FUNCTION, wrap_binaryfunc_l, \ + "x." NAME "(y) <==> " DOC) #define RBINSLOTNOTINFIX(NAME, SLOT, FUNCTION, DOC) \ - ETSLOT(NAME, as_number.SLOT, FUNCTION, wrap_binaryfunc_r, \ - "x." NAME "(y) <==> " DOC) + ETSLOT(NAME, as_number.SLOT, FUNCTION, wrap_binaryfunc_r, \ + "x." NAME "(y) <==> " DOC) static slotdef slotdefs[] = { - SQSLOT("__len__", sq_length, slot_sq_length, wrap_lenfunc, - "x.__len__() <==> len(x)"), - /* Heap types defining __add__/__mul__ have sq_concat/sq_repeat == NULL. - The logic in abstract.c always falls back to nb_add/nb_multiply in - this case. Defining both the nb_* and the sq_* slots to call the - user-defined methods has unexpected side-effects, as shown by - test_descr.notimplemented() */ - SQSLOT("__add__", sq_concat, NULL, wrap_binaryfunc, - "x.__add__(y) <==> x+y"), - SQSLOT("__mul__", sq_repeat, NULL, wrap_indexargfunc, - "x.__mul__(n) <==> x*n"), - SQSLOT("__rmul__", sq_repeat, NULL, wrap_indexargfunc, - "x.__rmul__(n) <==> n*x"), - SQSLOT("__getitem__", sq_item, slot_sq_item, wrap_sq_item, - "x.__getitem__(y) <==> x[y]"), - SQSLOT("__setitem__", sq_ass_item, slot_sq_ass_item, wrap_sq_setitem, - "x.__setitem__(i, y) <==> x[i]=y"), - SQSLOT("__delitem__", sq_ass_item, slot_sq_ass_item, wrap_sq_delitem, - "x.__delitem__(y) <==> del x[y]"), - SQSLOT("__contains__", sq_contains, slot_sq_contains, wrap_objobjproc, - "x.__contains__(y) <==> y in x"), - SQSLOT("__iadd__", sq_inplace_concat, NULL, - wrap_binaryfunc, "x.__iadd__(y) <==> x+=y"), - SQSLOT("__imul__", sq_inplace_repeat, NULL, - wrap_indexargfunc, "x.__imul__(y) <==> x*=y"), - - MPSLOT("__len__", mp_length, slot_mp_length, wrap_lenfunc, - "x.__len__() <==> len(x)"), - MPSLOT("__getitem__", mp_subscript, slot_mp_subscript, - wrap_binaryfunc, - "x.__getitem__(y) <==> x[y]"), - MPSLOT("__setitem__", mp_ass_subscript, slot_mp_ass_subscript, - wrap_objobjargproc, - "x.__setitem__(i, y) <==> x[i]=y"), - MPSLOT("__delitem__", mp_ass_subscript, slot_mp_ass_subscript, - wrap_delitem, - "x.__delitem__(y) <==> del x[y]"), - - BINSLOT("__add__", nb_add, slot_nb_add, - "+"), - RBINSLOT("__radd__", nb_add, slot_nb_add, - "+"), - BINSLOT("__sub__", nb_subtract, slot_nb_subtract, - "-"), - RBINSLOT("__rsub__", nb_subtract, slot_nb_subtract, - "-"), - BINSLOT("__mul__", nb_multiply, slot_nb_multiply, - "*"), - RBINSLOT("__rmul__", nb_multiply, slot_nb_multiply, - "*"), - BINSLOT("__mod__", nb_remainder, slot_nb_remainder, - "%"), - RBINSLOT("__rmod__", nb_remainder, slot_nb_remainder, - "%"), - BINSLOTNOTINFIX("__divmod__", nb_divmod, slot_nb_divmod, - "divmod(x, y)"), - RBINSLOTNOTINFIX("__rdivmod__", nb_divmod, slot_nb_divmod, - "divmod(y, x)"), - NBSLOT("__pow__", nb_power, slot_nb_power, wrap_ternaryfunc, - "x.__pow__(y[, z]) <==> pow(x, y[, z])"), - NBSLOT("__rpow__", nb_power, slot_nb_power, wrap_ternaryfunc_r, - "y.__rpow__(x[, z]) <==> pow(x, y[, z])"), - UNSLOT("__neg__", nb_negative, slot_nb_negative, wrap_unaryfunc, "-x"), - UNSLOT("__pos__", nb_positive, slot_nb_positive, wrap_unaryfunc, "+x"), - UNSLOT("__abs__", nb_absolute, slot_nb_absolute, wrap_unaryfunc, - "abs(x)"), - UNSLOT("__bool__", nb_bool, slot_nb_bool, wrap_inquirypred, - "x != 0"), - UNSLOT("__invert__", nb_invert, slot_nb_invert, wrap_unaryfunc, "~x"), - BINSLOT("__lshift__", nb_lshift, slot_nb_lshift, "<<"), - RBINSLOT("__rlshift__", nb_lshift, slot_nb_lshift, "<<"), - BINSLOT("__rshift__", nb_rshift, slot_nb_rshift, ">>"), - RBINSLOT("__rrshift__", nb_rshift, slot_nb_rshift, ">>"), - BINSLOT("__and__", nb_and, slot_nb_and, "&"), - RBINSLOT("__rand__", nb_and, slot_nb_and, "&"), - BINSLOT("__xor__", nb_xor, slot_nb_xor, "^"), - RBINSLOT("__rxor__", nb_xor, slot_nb_xor, "^"), - BINSLOT("__or__", nb_or, slot_nb_or, "|"), - RBINSLOT("__ror__", nb_or, slot_nb_or, "|"), - UNSLOT("__int__", nb_int, slot_nb_int, wrap_unaryfunc, - "int(x)"), - UNSLOT("__float__", nb_float, slot_nb_float, wrap_unaryfunc, - "float(x)"), - NBSLOT("__index__", nb_index, slot_nb_index, wrap_unaryfunc, - "x[y:z] <==> x[y.__index__():z.__index__()]"), - IBSLOT("__iadd__", nb_inplace_add, slot_nb_inplace_add, - wrap_binaryfunc, "+"), - IBSLOT("__isub__", nb_inplace_subtract, slot_nb_inplace_subtract, - wrap_binaryfunc, "-"), - IBSLOT("__imul__", nb_inplace_multiply, slot_nb_inplace_multiply, - wrap_binaryfunc, "*"), - IBSLOT("__imod__", nb_inplace_remainder, slot_nb_inplace_remainder, - wrap_binaryfunc, "%"), - IBSLOT("__ipow__", nb_inplace_power, slot_nb_inplace_power, - wrap_binaryfunc, "**"), - IBSLOT("__ilshift__", nb_inplace_lshift, slot_nb_inplace_lshift, - wrap_binaryfunc, "<<"), - IBSLOT("__irshift__", nb_inplace_rshift, slot_nb_inplace_rshift, - wrap_binaryfunc, ">>"), - IBSLOT("__iand__", nb_inplace_and, slot_nb_inplace_and, - wrap_binaryfunc, "&"), - IBSLOT("__ixor__", nb_inplace_xor, slot_nb_inplace_xor, - wrap_binaryfunc, "^"), - IBSLOT("__ior__", nb_inplace_or, slot_nb_inplace_or, - wrap_binaryfunc, "|"), - BINSLOT("__floordiv__", nb_floor_divide, slot_nb_floor_divide, "//"), - RBINSLOT("__rfloordiv__", nb_floor_divide, slot_nb_floor_divide, "//"), - BINSLOT("__truediv__", nb_true_divide, slot_nb_true_divide, "/"), - RBINSLOT("__rtruediv__", nb_true_divide, slot_nb_true_divide, "/"), - IBSLOT("__ifloordiv__", nb_inplace_floor_divide, - slot_nb_inplace_floor_divide, wrap_binaryfunc, "//"), - IBSLOT("__itruediv__", nb_inplace_true_divide, - slot_nb_inplace_true_divide, wrap_binaryfunc, "/"), - - TPSLOT("__str__", tp_str, slot_tp_str, wrap_unaryfunc, - "x.__str__() <==> str(x)"), - TPSLOT("__repr__", tp_repr, slot_tp_repr, wrap_unaryfunc, - "x.__repr__() <==> repr(x)"), - TPSLOT("__hash__", tp_hash, slot_tp_hash, wrap_hashfunc, - "x.__hash__() <==> hash(x)"), - FLSLOT("__call__", tp_call, slot_tp_call, (wrapperfunc)wrap_call, - "x.__call__(...) <==> x(...)", PyWrapperFlag_KEYWORDS), - TPSLOT("__getattribute__", tp_getattro, slot_tp_getattr_hook, - wrap_binaryfunc, "x.__getattribute__('name') <==> x.name"), - TPSLOT("__getattribute__", tp_getattr, NULL, NULL, ""), - TPSLOT("__getattr__", tp_getattro, slot_tp_getattr_hook, NULL, ""), - TPSLOT("__getattr__", tp_getattr, NULL, NULL, ""), - TPSLOT("__setattr__", tp_setattro, slot_tp_setattro, wrap_setattr, - "x.__setattr__('name', value) <==> x.name = value"), - TPSLOT("__setattr__", tp_setattr, NULL, NULL, ""), - TPSLOT("__delattr__", tp_setattro, slot_tp_setattro, wrap_delattr, - "x.__delattr__('name') <==> del x.name"), - TPSLOT("__delattr__", tp_setattr, NULL, NULL, ""), - TPSLOT("__lt__", tp_richcompare, slot_tp_richcompare, richcmp_lt, - "x.__lt__(y) <==> x x<=y"), - TPSLOT("__eq__", tp_richcompare, slot_tp_richcompare, richcmp_eq, - "x.__eq__(y) <==> x==y"), - TPSLOT("__ne__", tp_richcompare, slot_tp_richcompare, richcmp_ne, - "x.__ne__(y) <==> x!=y"), - TPSLOT("__gt__", tp_richcompare, slot_tp_richcompare, richcmp_gt, - "x.__gt__(y) <==> x>y"), - TPSLOT("__ge__", tp_richcompare, slot_tp_richcompare, richcmp_ge, - "x.__ge__(y) <==> x>=y"), - TPSLOT("__iter__", tp_iter, slot_tp_iter, wrap_unaryfunc, - "x.__iter__() <==> iter(x)"), - TPSLOT("__next__", tp_iternext, slot_tp_iternext, wrap_next, - "x.__next__() <==> next(x)"), - TPSLOT("__get__", tp_descr_get, slot_tp_descr_get, wrap_descr_get, - "descr.__get__(obj[, type]) -> value"), - TPSLOT("__set__", tp_descr_set, slot_tp_descr_set, wrap_descr_set, - "descr.__set__(obj, value)"), - TPSLOT("__delete__", tp_descr_set, slot_tp_descr_set, - wrap_descr_delete, "descr.__delete__(obj)"), - FLSLOT("__init__", tp_init, slot_tp_init, (wrapperfunc)wrap_init, - "x.__init__(...) initializes x; " - "see x.__class__.__doc__ for signature", - PyWrapperFlag_KEYWORDS), - TPSLOT("__new__", tp_new, slot_tp_new, NULL, ""), - TPSLOT("__del__", tp_del, slot_tp_del, NULL, ""), - {NULL} + SQSLOT("__len__", sq_length, slot_sq_length, wrap_lenfunc, + "x.__len__() <==> len(x)"), + /* Heap types defining __add__/__mul__ have sq_concat/sq_repeat == NULL. + The logic in abstract.c always falls back to nb_add/nb_multiply in + this case. Defining both the nb_* and the sq_* slots to call the + user-defined methods has unexpected side-effects, as shown by + test_descr.notimplemented() */ + SQSLOT("__add__", sq_concat, NULL, wrap_binaryfunc, + "x.__add__(y) <==> x+y"), + SQSLOT("__mul__", sq_repeat, NULL, wrap_indexargfunc, + "x.__mul__(n) <==> x*n"), + SQSLOT("__rmul__", sq_repeat, NULL, wrap_indexargfunc, + "x.__rmul__(n) <==> n*x"), + SQSLOT("__getitem__", sq_item, slot_sq_item, wrap_sq_item, + "x.__getitem__(y) <==> x[y]"), + SQSLOT("__setitem__", sq_ass_item, slot_sq_ass_item, wrap_sq_setitem, + "x.__setitem__(i, y) <==> x[i]=y"), + SQSLOT("__delitem__", sq_ass_item, slot_sq_ass_item, wrap_sq_delitem, + "x.__delitem__(y) <==> del x[y]"), + SQSLOT("__contains__", sq_contains, slot_sq_contains, wrap_objobjproc, + "x.__contains__(y) <==> y in x"), + SQSLOT("__iadd__", sq_inplace_concat, NULL, + wrap_binaryfunc, "x.__iadd__(y) <==> x+=y"), + SQSLOT("__imul__", sq_inplace_repeat, NULL, + wrap_indexargfunc, "x.__imul__(y) <==> x*=y"), + + MPSLOT("__len__", mp_length, slot_mp_length, wrap_lenfunc, + "x.__len__() <==> len(x)"), + MPSLOT("__getitem__", mp_subscript, slot_mp_subscript, + wrap_binaryfunc, + "x.__getitem__(y) <==> x[y]"), + MPSLOT("__setitem__", mp_ass_subscript, slot_mp_ass_subscript, + wrap_objobjargproc, + "x.__setitem__(i, y) <==> x[i]=y"), + MPSLOT("__delitem__", mp_ass_subscript, slot_mp_ass_subscript, + wrap_delitem, + "x.__delitem__(y) <==> del x[y]"), + + BINSLOT("__add__", nb_add, slot_nb_add, + "+"), + RBINSLOT("__radd__", nb_add, slot_nb_add, + "+"), + BINSLOT("__sub__", nb_subtract, slot_nb_subtract, + "-"), + RBINSLOT("__rsub__", nb_subtract, slot_nb_subtract, + "-"), + BINSLOT("__mul__", nb_multiply, slot_nb_multiply, + "*"), + RBINSLOT("__rmul__", nb_multiply, slot_nb_multiply, + "*"), + BINSLOT("__mod__", nb_remainder, slot_nb_remainder, + "%"), + RBINSLOT("__rmod__", nb_remainder, slot_nb_remainder, + "%"), + BINSLOTNOTINFIX("__divmod__", nb_divmod, slot_nb_divmod, + "divmod(x, y)"), + RBINSLOTNOTINFIX("__rdivmod__", nb_divmod, slot_nb_divmod, + "divmod(y, x)"), + NBSLOT("__pow__", nb_power, slot_nb_power, wrap_ternaryfunc, + "x.__pow__(y[, z]) <==> pow(x, y[, z])"), + NBSLOT("__rpow__", nb_power, slot_nb_power, wrap_ternaryfunc_r, + "y.__rpow__(x[, z]) <==> pow(x, y[, z])"), + UNSLOT("__neg__", nb_negative, slot_nb_negative, wrap_unaryfunc, "-x"), + UNSLOT("__pos__", nb_positive, slot_nb_positive, wrap_unaryfunc, "+x"), + UNSLOT("__abs__", nb_absolute, slot_nb_absolute, wrap_unaryfunc, + "abs(x)"), + UNSLOT("__bool__", nb_bool, slot_nb_bool, wrap_inquirypred, + "x != 0"), + UNSLOT("__invert__", nb_invert, slot_nb_invert, wrap_unaryfunc, "~x"), + BINSLOT("__lshift__", nb_lshift, slot_nb_lshift, "<<"), + RBINSLOT("__rlshift__", nb_lshift, slot_nb_lshift, "<<"), + BINSLOT("__rshift__", nb_rshift, slot_nb_rshift, ">>"), + RBINSLOT("__rrshift__", nb_rshift, slot_nb_rshift, ">>"), + BINSLOT("__and__", nb_and, slot_nb_and, "&"), + RBINSLOT("__rand__", nb_and, slot_nb_and, "&"), + BINSLOT("__xor__", nb_xor, slot_nb_xor, "^"), + RBINSLOT("__rxor__", nb_xor, slot_nb_xor, "^"), + BINSLOT("__or__", nb_or, slot_nb_or, "|"), + RBINSLOT("__ror__", nb_or, slot_nb_or, "|"), + UNSLOT("__int__", nb_int, slot_nb_int, wrap_unaryfunc, + "int(x)"), + UNSLOT("__float__", nb_float, slot_nb_float, wrap_unaryfunc, + "float(x)"), + NBSLOT("__index__", nb_index, slot_nb_index, wrap_unaryfunc, + "x[y:z] <==> x[y.__index__():z.__index__()]"), + IBSLOT("__iadd__", nb_inplace_add, slot_nb_inplace_add, + wrap_binaryfunc, "+"), + IBSLOT("__isub__", nb_inplace_subtract, slot_nb_inplace_subtract, + wrap_binaryfunc, "-"), + IBSLOT("__imul__", nb_inplace_multiply, slot_nb_inplace_multiply, + wrap_binaryfunc, "*"), + IBSLOT("__imod__", nb_inplace_remainder, slot_nb_inplace_remainder, + wrap_binaryfunc, "%"), + IBSLOT("__ipow__", nb_inplace_power, slot_nb_inplace_power, + wrap_binaryfunc, "**"), + IBSLOT("__ilshift__", nb_inplace_lshift, slot_nb_inplace_lshift, + wrap_binaryfunc, "<<"), + IBSLOT("__irshift__", nb_inplace_rshift, slot_nb_inplace_rshift, + wrap_binaryfunc, ">>"), + IBSLOT("__iand__", nb_inplace_and, slot_nb_inplace_and, + wrap_binaryfunc, "&"), + IBSLOT("__ixor__", nb_inplace_xor, slot_nb_inplace_xor, + wrap_binaryfunc, "^"), + IBSLOT("__ior__", nb_inplace_or, slot_nb_inplace_or, + wrap_binaryfunc, "|"), + BINSLOT("__floordiv__", nb_floor_divide, slot_nb_floor_divide, "//"), + RBINSLOT("__rfloordiv__", nb_floor_divide, slot_nb_floor_divide, "//"), + BINSLOT("__truediv__", nb_true_divide, slot_nb_true_divide, "/"), + RBINSLOT("__rtruediv__", nb_true_divide, slot_nb_true_divide, "/"), + IBSLOT("__ifloordiv__", nb_inplace_floor_divide, + slot_nb_inplace_floor_divide, wrap_binaryfunc, "//"), + IBSLOT("__itruediv__", nb_inplace_true_divide, + slot_nb_inplace_true_divide, wrap_binaryfunc, "/"), + + TPSLOT("__str__", tp_str, slot_tp_str, wrap_unaryfunc, + "x.__str__() <==> str(x)"), + TPSLOT("__repr__", tp_repr, slot_tp_repr, wrap_unaryfunc, + "x.__repr__() <==> repr(x)"), + TPSLOT("__hash__", tp_hash, slot_tp_hash, wrap_hashfunc, + "x.__hash__() <==> hash(x)"), + FLSLOT("__call__", tp_call, slot_tp_call, (wrapperfunc)wrap_call, + "x.__call__(...) <==> x(...)", PyWrapperFlag_KEYWORDS), + TPSLOT("__getattribute__", tp_getattro, slot_tp_getattr_hook, + wrap_binaryfunc, "x.__getattribute__('name') <==> x.name"), + TPSLOT("__getattribute__", tp_getattr, NULL, NULL, ""), + TPSLOT("__getattr__", tp_getattro, slot_tp_getattr_hook, NULL, ""), + TPSLOT("__getattr__", tp_getattr, NULL, NULL, ""), + TPSLOT("__setattr__", tp_setattro, slot_tp_setattro, wrap_setattr, + "x.__setattr__('name', value) <==> x.name = value"), + TPSLOT("__setattr__", tp_setattr, NULL, NULL, ""), + TPSLOT("__delattr__", tp_setattro, slot_tp_setattro, wrap_delattr, + "x.__delattr__('name') <==> del x.name"), + TPSLOT("__delattr__", tp_setattr, NULL, NULL, ""), + TPSLOT("__lt__", tp_richcompare, slot_tp_richcompare, richcmp_lt, + "x.__lt__(y) <==> x x<=y"), + TPSLOT("__eq__", tp_richcompare, slot_tp_richcompare, richcmp_eq, + "x.__eq__(y) <==> x==y"), + TPSLOT("__ne__", tp_richcompare, slot_tp_richcompare, richcmp_ne, + "x.__ne__(y) <==> x!=y"), + TPSLOT("__gt__", tp_richcompare, slot_tp_richcompare, richcmp_gt, + "x.__gt__(y) <==> x>y"), + TPSLOT("__ge__", tp_richcompare, slot_tp_richcompare, richcmp_ge, + "x.__ge__(y) <==> x>=y"), + TPSLOT("__iter__", tp_iter, slot_tp_iter, wrap_unaryfunc, + "x.__iter__() <==> iter(x)"), + TPSLOT("__next__", tp_iternext, slot_tp_iternext, wrap_next, + "x.__next__() <==> next(x)"), + TPSLOT("__get__", tp_descr_get, slot_tp_descr_get, wrap_descr_get, + "descr.__get__(obj[, type]) -> value"), + TPSLOT("__set__", tp_descr_set, slot_tp_descr_set, wrap_descr_set, + "descr.__set__(obj, value)"), + TPSLOT("__delete__", tp_descr_set, slot_tp_descr_set, + wrap_descr_delete, "descr.__delete__(obj)"), + FLSLOT("__init__", tp_init, slot_tp_init, (wrapperfunc)wrap_init, + "x.__init__(...) initializes x; " + "see x.__class__.__doc__ for signature", + PyWrapperFlag_KEYWORDS), + TPSLOT("__new__", tp_new, slot_tp_new, NULL, ""), + TPSLOT("__del__", tp_del, slot_tp_del, NULL, ""), + {NULL} }; /* Given a type pointer and an offset gotten from a slotdef entry, return a - pointer to the actual slot. This is not quite the same as simply adding + pointer to the actual slot. This is not quite the same as simply adding the offset to the type pointer, since it takes care to indirect through the proper indirection pointer (as_buffer, etc.); it returns NULL if the indirection pointer is NULL. */ static void ** slotptr(PyTypeObject *type, int ioffset) { - char *ptr; - long offset = ioffset; + char *ptr; + long offset = ioffset; - /* Note: this depends on the order of the members of PyHeapTypeObject! */ - assert(offset >= 0); - assert((size_t)offset < offsetof(PyHeapTypeObject, as_buffer)); - if ((size_t)offset >= offsetof(PyHeapTypeObject, as_sequence)) { - ptr = (char *)type->tp_as_sequence; - offset -= offsetof(PyHeapTypeObject, as_sequence); - } - else if ((size_t)offset >= offsetof(PyHeapTypeObject, as_mapping)) { - ptr = (char *)type->tp_as_mapping; - offset -= offsetof(PyHeapTypeObject, as_mapping); - } - else if ((size_t)offset >= offsetof(PyHeapTypeObject, as_number)) { - ptr = (char *)type->tp_as_number; - offset -= offsetof(PyHeapTypeObject, as_number); - } - else { - ptr = (char *)type; - } - if (ptr != NULL) - ptr += offset; - return (void **)ptr; + /* Note: this depends on the order of the members of PyHeapTypeObject! */ + assert(offset >= 0); + assert((size_t)offset < offsetof(PyHeapTypeObject, as_buffer)); + if ((size_t)offset >= offsetof(PyHeapTypeObject, as_sequence)) { + ptr = (char *)type->tp_as_sequence; + offset -= offsetof(PyHeapTypeObject, as_sequence); + } + else if ((size_t)offset >= offsetof(PyHeapTypeObject, as_mapping)) { + ptr = (char *)type->tp_as_mapping; + offset -= offsetof(PyHeapTypeObject, as_mapping); + } + else if ((size_t)offset >= offsetof(PyHeapTypeObject, as_number)) { + ptr = (char *)type->tp_as_number; + offset -= offsetof(PyHeapTypeObject, as_number); + } + else { + ptr = (char *)type; + } + if (ptr != NULL) + ptr += offset; + return (void **)ptr; } /* Length of array of slotdef pointers used to store slots with the @@ -5562,37 +5562,37 @@ static void ** resolve_slotdups(PyTypeObject *type, PyObject *name) { - /* XXX Maybe this could be optimized more -- but is it worth it? */ + /* XXX Maybe this could be optimized more -- but is it worth it? */ - /* pname and ptrs act as a little cache */ - static PyObject *pname; - static slotdef *ptrs[MAX_EQUIV]; - slotdef *p, **pp; - void **res, **ptr; - - if (pname != name) { - /* Collect all slotdefs that match name into ptrs. */ - pname = name; - pp = ptrs; - for (p = slotdefs; p->name_strobj; p++) { - if (p->name_strobj == name) - *pp++ = p; - } - *pp = NULL; - } - - /* Look in all matching slots of the type; if exactly one of these has - a filled-in slot, return its value. Otherwise return NULL. */ - res = NULL; - for (pp = ptrs; *pp; pp++) { - ptr = slotptr(type, (*pp)->offset); - if (ptr == NULL || *ptr == NULL) - continue; - if (res != NULL) - return NULL; - res = ptr; - } - return res; + /* pname and ptrs act as a little cache */ + static PyObject *pname; + static slotdef *ptrs[MAX_EQUIV]; + slotdef *p, **pp; + void **res, **ptr; + + if (pname != name) { + /* Collect all slotdefs that match name into ptrs. */ + pname = name; + pp = ptrs; + for (p = slotdefs; p->name_strobj; p++) { + if (p->name_strobj == name) + *pp++ = p; + } + *pp = NULL; + } + + /* Look in all matching slots of the type; if exactly one of these has + a filled-in slot, return its value. Otherwise return NULL. */ + res = NULL; + for (pp = ptrs; *pp; pp++) { + ptr = slotptr(type, (*pp)->offset); + if (ptr == NULL || *ptr == NULL) + continue; + if (res != NULL) + return NULL; + res = ptr; + } + return res; } /* Common code for update_slots_callback() and fixup_slot_dispatchers(). This @@ -5604,81 +5604,81 @@ static slotdef * update_one_slot(PyTypeObject *type, slotdef *p) { - PyObject *descr; - PyWrapperDescrObject *d; - void *generic = NULL, *specific = NULL; - int use_generic = 0; - int offset = p->offset; - void **ptr = slotptr(type, offset); - - if (ptr == NULL) { - do { - ++p; - } while (p->offset == offset); - return p; - } - do { - descr = _PyType_Lookup(type, p->name_strobj); - if (descr == NULL) { - if (ptr == (void**)&type->tp_iternext) { - specific = _PyObject_NextNotImplemented; - } - continue; - } - if (Py_TYPE(descr) == &PyWrapperDescr_Type) { - void **tptr = resolve_slotdups(type, p->name_strobj); - if (tptr == NULL || tptr == ptr) - generic = p->function; - d = (PyWrapperDescrObject *)descr; - if (d->d_base->wrapper == p->wrapper && - PyType_IsSubtype(type, PyDescr_TYPE(d))) - { - if (specific == NULL || - specific == d->d_wrapped) - specific = d->d_wrapped; - else - use_generic = 1; - } - } - else if (Py_TYPE(descr) == &PyCFunction_Type && - PyCFunction_GET_FUNCTION(descr) == - (PyCFunction)tp_new_wrapper && - ptr == (void**)&type->tp_new) - { - /* The __new__ wrapper is not a wrapper descriptor, - so must be special-cased differently. - If we don't do this, creating an instance will - always use slot_tp_new which will look up - __new__ in the MRO which will call tp_new_wrapper - which will look through the base classes looking - for a static base and call its tp_new (usually - PyType_GenericNew), after performing various - sanity checks and constructing a new argument - list. Cut all that nonsense short -- this speeds - up instance creation tremendously. */ - specific = (void *)type->tp_new; - /* XXX I'm not 100% sure that there isn't a hole - in this reasoning that requires additional - sanity checks. I'll buy the first person to - point out a bug in this reasoning a beer. */ - } - else if (descr == Py_None && - ptr == (void**)&type->tp_hash) { - /* We specifically allow __hash__ to be set to None - to prevent inheritance of the default - implementation from object.__hash__ */ - specific = PyObject_HashNotImplemented; - } - else { - use_generic = 1; - generic = p->function; - } - } while ((++p)->offset == offset); - if (specific && !use_generic) - *ptr = specific; - else - *ptr = generic; - return p; + PyObject *descr; + PyWrapperDescrObject *d; + void *generic = NULL, *specific = NULL; + int use_generic = 0; + int offset = p->offset; + void **ptr = slotptr(type, offset); + + if (ptr == NULL) { + do { + ++p; + } while (p->offset == offset); + return p; + } + do { + descr = _PyType_Lookup(type, p->name_strobj); + if (descr == NULL) { + if (ptr == (void**)&type->tp_iternext) { + specific = _PyObject_NextNotImplemented; + } + continue; + } + if (Py_TYPE(descr) == &PyWrapperDescr_Type) { + void **tptr = resolve_slotdups(type, p->name_strobj); + if (tptr == NULL || tptr == ptr) + generic = p->function; + d = (PyWrapperDescrObject *)descr; + if (d->d_base->wrapper == p->wrapper && + PyType_IsSubtype(type, PyDescr_TYPE(d))) + { + if (specific == NULL || + specific == d->d_wrapped) + specific = d->d_wrapped; + else + use_generic = 1; + } + } + else if (Py_TYPE(descr) == &PyCFunction_Type && + PyCFunction_GET_FUNCTION(descr) == + (PyCFunction)tp_new_wrapper && + ptr == (void**)&type->tp_new) + { + /* The __new__ wrapper is not a wrapper descriptor, + so must be special-cased differently. + If we don't do this, creating an instance will + always use slot_tp_new which will look up + __new__ in the MRO which will call tp_new_wrapper + which will look through the base classes looking + for a static base and call its tp_new (usually + PyType_GenericNew), after performing various + sanity checks and constructing a new argument + list. Cut all that nonsense short -- this speeds + up instance creation tremendously. */ + specific = (void *)type->tp_new; + /* XXX I'm not 100% sure that there isn't a hole + in this reasoning that requires additional + sanity checks. I'll buy the first person to + point out a bug in this reasoning a beer. */ + } + else if (descr == Py_None && + ptr == (void**)&type->tp_hash) { + /* We specifically allow __hash__ to be set to None + to prevent inheritance of the default + implementation from object.__hash__ */ + specific = PyObject_HashNotImplemented; + } + else { + use_generic = 1; + generic = p->function; + } + } while ((++p)->offset == offset); + if (specific && !use_generic) + *ptr = specific; + else + *ptr = generic; + return p; } /* In the type, update the slots whose slotdefs are gathered in the pp array. @@ -5686,11 +5686,11 @@ static int update_slots_callback(PyTypeObject *type, void *data) { - slotdef **pp = (slotdef **)data; + slotdef **pp = (slotdef **)data; - for (; *pp; pp++) - update_one_slot(type, *pp); - return 0; + for (; *pp; pp++) + update_one_slot(type, *pp); + return 0; } /* Comparison function for qsort() to compare slotdefs by their offset, and @@ -5698,14 +5698,14 @@ static int slotdef_cmp(const void *aa, const void *bb) { - const slotdef *a = (const slotdef *)aa, *b = (const slotdef *)bb; - int c = a->offset - b->offset; - if (c != 0) - return c; - else - /* Cannot use a-b, as this gives off_t, - which may lose precision when converted to int. */ - return (a > b) ? 1 : (a < b) ? -1 : 0; + const slotdef *a = (const slotdef *)aa, *b = (const slotdef *)bb; + int c = a->offset - b->offset; + if (c != 0) + return c; + else + /* Cannot use a-b, as this gives off_t, + which may lose precision when converted to int. */ + return (a > b) ? 1 : (a < b) ? -1 : 0; } /* Initialize the slotdefs table by adding interned string objects for the @@ -5713,56 +5713,56 @@ static void init_slotdefs(void) { - slotdef *p; - static int initialized = 0; + slotdef *p; + static int initialized = 0; - if (initialized) - return; - for (p = slotdefs; p->name; p++) { - p->name_strobj = PyUnicode_InternFromString(p->name); - if (!p->name_strobj) - Py_FatalError("Out of memory interning slotdef names"); - } - qsort((void *)slotdefs, (size_t)(p-slotdefs), sizeof(slotdef), - slotdef_cmp); - initialized = 1; + if (initialized) + return; + for (p = slotdefs; p->name; p++) { + p->name_strobj = PyUnicode_InternFromString(p->name); + if (!p->name_strobj) + Py_FatalError("Out of memory interning slotdef names"); + } + qsort((void *)slotdefs, (size_t)(p-slotdefs), sizeof(slotdef), + slotdef_cmp); + initialized = 1; } /* Update the slots after assignment to a class (type) attribute. */ static int update_slot(PyTypeObject *type, PyObject *name) { - slotdef *ptrs[MAX_EQUIV]; - slotdef *p; - slotdef **pp; - int offset; - - /* Clear the VALID_VERSION flag of 'type' and all its - subclasses. This could possibly be unified with the - update_subclasses() recursion below, but carefully: - they each have their own conditions on which to stop - recursing into subclasses. */ - PyType_Modified(type); - - init_slotdefs(); - pp = ptrs; - for (p = slotdefs; p->name; p++) { - /* XXX assume name is interned! */ - if (p->name_strobj == name) - *pp++ = p; - } - *pp = NULL; - for (pp = ptrs; *pp; pp++) { - p = *pp; - offset = p->offset; - while (p > slotdefs && (p-1)->offset == offset) - --p; - *pp = p; - } - if (ptrs[0] == NULL) - return 0; /* Not an attribute that affects any slots */ - return update_subclasses(type, name, - update_slots_callback, (void *)ptrs); + slotdef *ptrs[MAX_EQUIV]; + slotdef *p; + slotdef **pp; + int offset; + + /* Clear the VALID_VERSION flag of 'type' and all its + subclasses. This could possibly be unified with the + update_subclasses() recursion below, but carefully: + they each have their own conditions on which to stop + recursing into subclasses. */ + PyType_Modified(type); + + init_slotdefs(); + pp = ptrs; + for (p = slotdefs; p->name; p++) { + /* XXX assume name is interned! */ + if (p->name_strobj == name) + *pp++ = p; + } + *pp = NULL; + for (pp = ptrs; *pp; pp++) { + p = *pp; + offset = p->offset; + while (p > slotdefs && (p-1)->offset == offset) + --p; + *pp = p; + } + if (ptrs[0] == NULL) + return 0; /* Not an attribute that affects any slots */ + return update_subclasses(type, name, + update_slots_callback, (void *)ptrs); } /* Store the proper functions in the slot dispatches at class (type) @@ -5771,23 +5771,23 @@ static void fixup_slot_dispatchers(PyTypeObject *type) { - slotdef *p; + slotdef *p; - init_slotdefs(); - for (p = slotdefs; p->name; ) - p = update_one_slot(type, p); + init_slotdefs(); + for (p = slotdefs; p->name; ) + p = update_one_slot(type, p); } static void update_all_slots(PyTypeObject* type) { - slotdef *p; + slotdef *p; - init_slotdefs(); - for (p = slotdefs; p->name; p++) { - /* update_slot returns int but can't actually fail */ - update_slot(type, p->name_strobj); - } + init_slotdefs(); + for (p = slotdefs; p->name; p++) { + /* update_slot returns int but can't actually fail */ + update_slot(type, p->name_strobj); + } } /* recurse_down_subclasses() and update_subclasses() are mutually @@ -5796,56 +5796,56 @@ static int update_subclasses(PyTypeObject *type, PyObject *name, - update_callback callback, void *data) + update_callback callback, void *data) { - if (callback(type, data) < 0) - return -1; - return recurse_down_subclasses(type, name, callback, data); + if (callback(type, data) < 0) + return -1; + return recurse_down_subclasses(type, name, callback, data); } static int recurse_down_subclasses(PyTypeObject *type, PyObject *name, - update_callback callback, void *data) + update_callback callback, void *data) { - PyTypeObject *subclass; - PyObject *ref, *subclasses, *dict; - Py_ssize_t i, n; - - subclasses = type->tp_subclasses; - if (subclasses == NULL) - return 0; - assert(PyList_Check(subclasses)); - n = PyList_GET_SIZE(subclasses); - for (i = 0; i < n; i++) { - ref = PyList_GET_ITEM(subclasses, i); - assert(PyWeakref_CheckRef(ref)); - subclass = (PyTypeObject *)PyWeakref_GET_OBJECT(ref); - assert(subclass != NULL); - if ((PyObject *)subclass == Py_None) - continue; - assert(PyType_Check(subclass)); - /* Avoid recursing down into unaffected classes */ - dict = subclass->tp_dict; - if (dict != NULL && PyDict_Check(dict) && - PyDict_GetItem(dict, name) != NULL) - continue; - if (update_subclasses(subclass, name, callback, data) < 0) - return -1; - } - return 0; + PyTypeObject *subclass; + PyObject *ref, *subclasses, *dict; + Py_ssize_t i, n; + + subclasses = type->tp_subclasses; + if (subclasses == NULL) + return 0; + assert(PyList_Check(subclasses)); + n = PyList_GET_SIZE(subclasses); + for (i = 0; i < n; i++) { + ref = PyList_GET_ITEM(subclasses, i); + assert(PyWeakref_CheckRef(ref)); + subclass = (PyTypeObject *)PyWeakref_GET_OBJECT(ref); + assert(subclass != NULL); + if ((PyObject *)subclass == Py_None) + continue; + assert(PyType_Check(subclass)); + /* Avoid recursing down into unaffected classes */ + dict = subclass->tp_dict; + if (dict != NULL && PyDict_Check(dict) && + PyDict_GetItem(dict, name) != NULL) + continue; + if (update_subclasses(subclass, name, callback, data) < 0) + return -1; + } + return 0; } /* This function is called by PyType_Ready() to populate the type's dictionary with method descriptors for function slots. For each function slot (like tp_repr) that's defined in the type, one or more corresponding descriptors are added in the type's tp_dict dictionary - under the appropriate name (like __repr__). Some function slots + under the appropriate name (like __repr__). Some function slots cause more than one descriptor to be added (for example, the nb_add slot adds both __add__ and __radd__ descriptors) and some function slots compete for the same descriptor (for example both sq_item and mp_subscript generate a __getitem__ descriptor). - In the latter case, the first slotdef entry encoutered wins. Since + In the latter case, the first slotdef entry encoutered wins. Since slotdef entries are sorted by the offset of the slot in the PyHeapTypeObject, this gives us some control over disambiguating between competing slots: the members of PyHeapTypeObject are listed @@ -5868,344 +5868,344 @@ static int add_operators(PyTypeObject *type) { - PyObject *dict = type->tp_dict; - slotdef *p; - PyObject *descr; - void **ptr; - - init_slotdefs(); - for (p = slotdefs; p->name; p++) { - if (p->wrapper == NULL) - continue; - ptr = slotptr(type, p->offset); - if (!ptr || !*ptr) - continue; - if (PyDict_GetItem(dict, p->name_strobj)) - continue; - if (*ptr == PyObject_HashNotImplemented) { - /* Classes may prevent the inheritance of the tp_hash - slot by storing PyObject_HashNotImplemented in it. Make it - visible as a None value for the __hash__ attribute. */ - if (PyDict_SetItem(dict, p->name_strobj, Py_None) < 0) - return -1; - } - else { - descr = PyDescr_NewWrapper(type, p, *ptr); - if (descr == NULL) - return -1; - if (PyDict_SetItem(dict, p->name_strobj, descr) < 0) - return -1; - Py_DECREF(descr); - } - } - if (type->tp_new != NULL) { - if (add_tp_new_wrapper(type) < 0) - return -1; - } - return 0; + PyObject *dict = type->tp_dict; + slotdef *p; + PyObject *descr; + void **ptr; + + init_slotdefs(); + for (p = slotdefs; p->name; p++) { + if (p->wrapper == NULL) + continue; + ptr = slotptr(type, p->offset); + if (!ptr || !*ptr) + continue; + if (PyDict_GetItem(dict, p->name_strobj)) + continue; + if (*ptr == PyObject_HashNotImplemented) { + /* Classes may prevent the inheritance of the tp_hash + slot by storing PyObject_HashNotImplemented in it. Make it + visible as a None value for the __hash__ attribute. */ + if (PyDict_SetItem(dict, p->name_strobj, Py_None) < 0) + return -1; + } + else { + descr = PyDescr_NewWrapper(type, p, *ptr); + if (descr == NULL) + return -1; + if (PyDict_SetItem(dict, p->name_strobj, descr) < 0) + return -1; + Py_DECREF(descr); + } + } + if (type->tp_new != NULL) { + if (add_tp_new_wrapper(type) < 0) + return -1; + } + return 0; } /* Cooperative 'super' */ typedef struct { - PyObject_HEAD - PyTypeObject *type; - PyObject *obj; - PyTypeObject *obj_type; + PyObject_HEAD + PyTypeObject *type; + PyObject *obj; + PyTypeObject *obj_type; } superobject; static PyMemberDef super_members[] = { - {"__thisclass__", T_OBJECT, offsetof(superobject, type), READONLY, - "the class invoking super()"}, - {"__self__", T_OBJECT, offsetof(superobject, obj), READONLY, - "the instance invoking super(); may be None"}, - {"__self_class__", T_OBJECT, offsetof(superobject, obj_type), READONLY, - "the type of the instance invoking super(); may be None"}, - {0} + {"__thisclass__", T_OBJECT, offsetof(superobject, type), READONLY, + "the class invoking super()"}, + {"__self__", T_OBJECT, offsetof(superobject, obj), READONLY, + "the instance invoking super(); may be None"}, + {"__self_class__", T_OBJECT, offsetof(superobject, obj_type), READONLY, + "the type of the instance invoking super(); may be None"}, + {0} }; static void super_dealloc(PyObject *self) { - superobject *su = (superobject *)self; + superobject *su = (superobject *)self; - _PyObject_GC_UNTRACK(self); - Py_XDECREF(su->obj); - Py_XDECREF(su->type); - Py_XDECREF(su->obj_type); - Py_TYPE(self)->tp_free(self); + _PyObject_GC_UNTRACK(self); + Py_XDECREF(su->obj); + Py_XDECREF(su->type); + Py_XDECREF(su->obj_type); + Py_TYPE(self)->tp_free(self); } static PyObject * super_repr(PyObject *self) { - superobject *su = (superobject *)self; + superobject *su = (superobject *)self; - if (su->obj_type) - return PyUnicode_FromFormat( - ", <%s object>>", - su->type ? su->type->tp_name : "NULL", - su->obj_type->tp_name); - else - return PyUnicode_FromFormat( - ", NULL>", - su->type ? su->type->tp_name : "NULL"); + if (su->obj_type) + return PyUnicode_FromFormat( + ", <%s object>>", + su->type ? su->type->tp_name : "NULL", + su->obj_type->tp_name); + else + return PyUnicode_FromFormat( + ", NULL>", + su->type ? su->type->tp_name : "NULL"); } static PyObject * super_getattro(PyObject *self, PyObject *name) { - superobject *su = (superobject *)self; - int skip = su->obj_type == NULL; + superobject *su = (superobject *)self; + int skip = su->obj_type == NULL; - if (!skip) { - /* We want __class__ to return the class of the super object - (i.e. super, or a subclass), not the class of su->obj. */ - skip = (PyUnicode_Check(name) && - PyUnicode_GET_SIZE(name) == 9 && - PyUnicode_CompareWithASCIIString(name, "__class__") == 0); - } - - if (!skip) { - PyObject *mro, *res, *tmp, *dict; - PyTypeObject *starttype; - descrgetfunc f; - Py_ssize_t i, n; - - starttype = su->obj_type; - mro = starttype->tp_mro; - - if (mro == NULL) - n = 0; - else { - assert(PyTuple_Check(mro)); - n = PyTuple_GET_SIZE(mro); - } - for (i = 0; i < n; i++) { - if ((PyObject *)(su->type) == PyTuple_GET_ITEM(mro, i)) - break; - } - i++; - res = NULL; - for (; i < n; i++) { - tmp = PyTuple_GET_ITEM(mro, i); - if (PyType_Check(tmp)) - dict = ((PyTypeObject *)tmp)->tp_dict; - else - continue; - res = PyDict_GetItem(dict, name); - if (res != NULL) { - Py_INCREF(res); - f = Py_TYPE(res)->tp_descr_get; - if (f != NULL) { - tmp = f(res, - /* Only pass 'obj' param if - this is instance-mode super - (See SF ID #743627) - */ - (su->obj == (PyObject *) - su->obj_type - ? (PyObject *)NULL - : su->obj), - (PyObject *)starttype); - Py_DECREF(res); - res = tmp; - } - return res; - } - } - } - return PyObject_GenericGetAttr(self, name); + if (!skip) { + /* We want __class__ to return the class of the super object + (i.e. super, or a subclass), not the class of su->obj. */ + skip = (PyUnicode_Check(name) && + PyUnicode_GET_SIZE(name) == 9 && + PyUnicode_CompareWithASCIIString(name, "__class__") == 0); + } + + if (!skip) { + PyObject *mro, *res, *tmp, *dict; + PyTypeObject *starttype; + descrgetfunc f; + Py_ssize_t i, n; + + starttype = su->obj_type; + mro = starttype->tp_mro; + + if (mro == NULL) + n = 0; + else { + assert(PyTuple_Check(mro)); + n = PyTuple_GET_SIZE(mro); + } + for (i = 0; i < n; i++) { + if ((PyObject *)(su->type) == PyTuple_GET_ITEM(mro, i)) + break; + } + i++; + res = NULL; + for (; i < n; i++) { + tmp = PyTuple_GET_ITEM(mro, i); + if (PyType_Check(tmp)) + dict = ((PyTypeObject *)tmp)->tp_dict; + else + continue; + res = PyDict_GetItem(dict, name); + if (res != NULL) { + Py_INCREF(res); + f = Py_TYPE(res)->tp_descr_get; + if (f != NULL) { + tmp = f(res, + /* Only pass 'obj' param if + this is instance-mode super + (See SF ID #743627) + */ + (su->obj == (PyObject *) + su->obj_type + ? (PyObject *)NULL + : su->obj), + (PyObject *)starttype); + Py_DECREF(res); + res = tmp; + } + return res; + } + } + } + return PyObject_GenericGetAttr(self, name); } static PyTypeObject * supercheck(PyTypeObject *type, PyObject *obj) { - /* Check that a super() call makes sense. Return a type object. + /* Check that a super() call makes sense. Return a type object. + + obj can be a new-style class, or an instance of one: - obj can be a new-style class, or an instance of one: + - If it is a class, it must be a subclass of 'type'. This case is + used for class methods; the return value is obj. - - If it is a class, it must be a subclass of 'type'. This case is - used for class methods; the return value is obj. + - If it is an instance, it must be an instance of 'type'. This is + the normal case; the return value is obj.__class__. + + But... when obj is an instance, we want to allow for the case where + Py_TYPE(obj) is not a subclass of type, but obj.__class__ is! + This will allow using super() with a proxy for obj. + */ + + /* Check for first bullet above (special case) */ + if (PyType_Check(obj) && PyType_IsSubtype((PyTypeObject *)obj, type)) { + Py_INCREF(obj); + return (PyTypeObject *)obj; + } + + /* Normal case */ + if (PyType_IsSubtype(Py_TYPE(obj), type)) { + Py_INCREF(Py_TYPE(obj)); + return Py_TYPE(obj); + } + else { + /* Try the slow way */ + static PyObject *class_str = NULL; + PyObject *class_attr; + + if (class_str == NULL) { + class_str = PyUnicode_FromString("__class__"); + if (class_str == NULL) + return NULL; + } + + class_attr = PyObject_GetAttr(obj, class_str); + + if (class_attr != NULL && + PyType_Check(class_attr) && + (PyTypeObject *)class_attr != Py_TYPE(obj)) + { + int ok = PyType_IsSubtype( + (PyTypeObject *)class_attr, type); + if (ok) + return (PyTypeObject *)class_attr; + } - - If it is an instance, it must be an instance of 'type'. This is - the normal case; the return value is obj.__class__. - - But... when obj is an instance, we want to allow for the case where - Py_TYPE(obj) is not a subclass of type, but obj.__class__ is! - This will allow using super() with a proxy for obj. - */ - - /* Check for first bullet above (special case) */ - if (PyType_Check(obj) && PyType_IsSubtype((PyTypeObject *)obj, type)) { - Py_INCREF(obj); - return (PyTypeObject *)obj; - } - - /* Normal case */ - if (PyType_IsSubtype(Py_TYPE(obj), type)) { - Py_INCREF(Py_TYPE(obj)); - return Py_TYPE(obj); - } - else { - /* Try the slow way */ - static PyObject *class_str = NULL; - PyObject *class_attr; - - if (class_str == NULL) { - class_str = PyUnicode_FromString("__class__"); - if (class_str == NULL) - return NULL; - } - - class_attr = PyObject_GetAttr(obj, class_str); - - if (class_attr != NULL && - PyType_Check(class_attr) && - (PyTypeObject *)class_attr != Py_TYPE(obj)) - { - int ok = PyType_IsSubtype( - (PyTypeObject *)class_attr, type); - if (ok) - return (PyTypeObject *)class_attr; - } - - if (class_attr == NULL) - PyErr_Clear(); - else - Py_DECREF(class_attr); - } - - PyErr_SetString(PyExc_TypeError, - "super(type, obj): " - "obj must be an instance or subtype of type"); - return NULL; + if (class_attr == NULL) + PyErr_Clear(); + else + Py_DECREF(class_attr); + } + + PyErr_SetString(PyExc_TypeError, + "super(type, obj): " + "obj must be an instance or subtype of type"); + return NULL; } static PyObject * super_descr_get(PyObject *self, PyObject *obj, PyObject *type) { - superobject *su = (superobject *)self; - superobject *newobj; + superobject *su = (superobject *)self; + superobject *newobj; - if (obj == NULL || obj == Py_None || su->obj != NULL) { - /* Not binding to an object, or already bound */ - Py_INCREF(self); - return self; - } - if (Py_TYPE(su) != &PySuper_Type) - /* If su is an instance of a (strict) subclass of super, - call its type */ - return PyObject_CallFunctionObjArgs((PyObject *)Py_TYPE(su), - su->type, obj, NULL); - else { - /* Inline the common case */ - PyTypeObject *obj_type = supercheck(su->type, obj); - if (obj_type == NULL) - return NULL; - newobj = (superobject *)PySuper_Type.tp_new(&PySuper_Type, - NULL, NULL); - if (newobj == NULL) - return NULL; - Py_INCREF(su->type); - Py_INCREF(obj); - newobj->type = su->type; - newobj->obj = obj; - newobj->obj_type = obj_type; - return (PyObject *)newobj; - } + if (obj == NULL || obj == Py_None || su->obj != NULL) { + /* Not binding to an object, or already bound */ + Py_INCREF(self); + return self; + } + if (Py_TYPE(su) != &PySuper_Type) + /* If su is an instance of a (strict) subclass of super, + call its type */ + return PyObject_CallFunctionObjArgs((PyObject *)Py_TYPE(su), + su->type, obj, NULL); + else { + /* Inline the common case */ + PyTypeObject *obj_type = supercheck(su->type, obj); + if (obj_type == NULL) + return NULL; + newobj = (superobject *)PySuper_Type.tp_new(&PySuper_Type, + NULL, NULL); + if (newobj == NULL) + return NULL; + Py_INCREF(su->type); + Py_INCREF(obj); + newobj->type = su->type; + newobj->obj = obj; + newobj->obj_type = obj_type; + return (PyObject *)newobj; + } } static int super_init(PyObject *self, PyObject *args, PyObject *kwds) { - superobject *su = (superobject *)self; - PyTypeObject *type = NULL; - PyObject *obj = NULL; - PyTypeObject *obj_type = NULL; - - if (!_PyArg_NoKeywords("super", kwds)) - return -1; - if (!PyArg_ParseTuple(args, "|O!O:super", &PyType_Type, &type, &obj)) - return -1; - + superobject *su = (superobject *)self; + PyTypeObject *type = NULL; + PyObject *obj = NULL; + PyTypeObject *obj_type = NULL; + + if (!_PyArg_NoKeywords("super", kwds)) + return -1; + if (!PyArg_ParseTuple(args, "|O!O:super", &PyType_Type, &type, &obj)) + return -1; + + if (type == NULL) { + /* Call super(), without args -- fill in from __class__ + and first local variable on the stack. */ + PyFrameObject *f = PyThreadState_GET()->frame; + PyCodeObject *co = f->f_code; + int i, n; + if (co == NULL) { + PyErr_SetString(PyExc_SystemError, + "super(): no code object"); + return -1; + } + if (co->co_argcount == 0) { + PyErr_SetString(PyExc_SystemError, + "super(): no arguments"); + return -1; + } + obj = f->f_localsplus[0]; + if (obj == NULL) { + PyErr_SetString(PyExc_SystemError, + "super(): arg[0] deleted"); + return -1; + } + if (co->co_freevars == NULL) + n = 0; + else { + assert(PyTuple_Check(co->co_freevars)); + n = PyTuple_GET_SIZE(co->co_freevars); + } + for (i = 0; i < n; i++) { + PyObject *name = PyTuple_GET_ITEM(co->co_freevars, i); + assert(PyUnicode_Check(name)); + if (!PyUnicode_CompareWithASCIIString(name, + "__class__")) { + Py_ssize_t index = co->co_nlocals + + PyTuple_GET_SIZE(co->co_cellvars) + i; + PyObject *cell = f->f_localsplus[index]; + if (cell == NULL || !PyCell_Check(cell)) { + PyErr_SetString(PyExc_SystemError, + "super(): bad __class__ cell"); + return -1; + } + type = (PyTypeObject *) PyCell_GET(cell); + if (type == NULL) { + PyErr_SetString(PyExc_SystemError, + "super(): empty __class__ cell"); + return -1; + } + if (!PyType_Check(type)) { + PyErr_Format(PyExc_SystemError, + "super(): __class__ is not a type (%s)", + Py_TYPE(type)->tp_name); + return -1; + } + break; + } + } if (type == NULL) { - /* Call super(), without args -- fill in from __class__ - and first local variable on the stack. */ - PyFrameObject *f = PyThreadState_GET()->frame; - PyCodeObject *co = f->f_code; - int i, n; - if (co == NULL) { - PyErr_SetString(PyExc_SystemError, - "super(): no code object"); - return -1; - } - if (co->co_argcount == 0) { - PyErr_SetString(PyExc_SystemError, - "super(): no arguments"); - return -1; - } - obj = f->f_localsplus[0]; - if (obj == NULL) { - PyErr_SetString(PyExc_SystemError, - "super(): arg[0] deleted"); - return -1; - } - if (co->co_freevars == NULL) - n = 0; - else { - assert(PyTuple_Check(co->co_freevars)); - n = PyTuple_GET_SIZE(co->co_freevars); - } - for (i = 0; i < n; i++) { - PyObject *name = PyTuple_GET_ITEM(co->co_freevars, i); - assert(PyUnicode_Check(name)); - if (!PyUnicode_CompareWithASCIIString(name, - "__class__")) { - Py_ssize_t index = co->co_nlocals + - PyTuple_GET_SIZE(co->co_cellvars) + i; - PyObject *cell = f->f_localsplus[index]; - if (cell == NULL || !PyCell_Check(cell)) { - PyErr_SetString(PyExc_SystemError, - "super(): bad __class__ cell"); - return -1; - } - type = (PyTypeObject *) PyCell_GET(cell); - if (type == NULL) { - PyErr_SetString(PyExc_SystemError, - "super(): empty __class__ cell"); - return -1; - } - if (!PyType_Check(type)) { - PyErr_Format(PyExc_SystemError, - "super(): __class__ is not a type (%s)", - Py_TYPE(type)->tp_name); - return -1; - } - break; - } - } - if (type == NULL) { - PyErr_SetString(PyExc_SystemError, - "super(): __class__ cell not found"); - return -1; - } - } - - if (obj == Py_None) - obj = NULL; - if (obj != NULL) { - obj_type = supercheck(type, obj); - if (obj_type == NULL) - return -1; - Py_INCREF(obj); - } - Py_INCREF(type); - su->type = type; - su->obj = obj; - su->obj_type = obj_type; - return 0; + PyErr_SetString(PyExc_SystemError, + "super(): __class__ cell not found"); + return -1; + } + } + + if (obj == Py_None) + obj = NULL; + if (obj != NULL) { + obj_type = supercheck(type, obj); + if (obj_type == NULL) + return -1; + Py_INCREF(obj); + } + Py_INCREF(type); + su->type = type; + su->obj = obj; + su->obj_type = obj_type; + return 0; } PyDoc_STRVAR(super_doc, @@ -6216,65 +6216,65 @@ "Typical use to call a cooperative superclass method:\n" "class C(B):\n" " def meth(self, arg):\n" -" super().meth(arg)\n" +" super().meth(arg)\n" "This works for class methods too:\n" "class C(B):\n" " @classmethod\n" " def cmeth(cls, arg):\n" -" super().cmeth(arg)\n"); +" super().cmeth(arg)\n"); static int super_traverse(PyObject *self, visitproc visit, void *arg) { - superobject *su = (superobject *)self; + superobject *su = (superobject *)self; - Py_VISIT(su->obj); - Py_VISIT(su->type); - Py_VISIT(su->obj_type); + Py_VISIT(su->obj); + Py_VISIT(su->type); + Py_VISIT(su->obj_type); - return 0; + return 0; } PyTypeObject PySuper_Type = { - PyVarObject_HEAD_INIT(&PyType_Type, 0) - "super", /* tp_name */ - sizeof(superobject), /* tp_basicsize */ - 0, /* tp_itemsize */ - /* methods */ - super_dealloc, /* tp_dealloc */ - 0, /* tp_print */ - 0, /* tp_getattr */ - 0, /* tp_setattr */ - 0, /* tp_reserved */ - super_repr, /* tp_repr */ - 0, /* tp_as_number */ - 0, /* tp_as_sequence */ - 0, /* tp_as_mapping */ - 0, /* tp_hash */ - 0, /* tp_call */ - 0, /* tp_str */ - super_getattro, /* tp_getattro */ - 0, /* tp_setattro */ - 0, /* tp_as_buffer */ - Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC | - Py_TPFLAGS_BASETYPE, /* tp_flags */ - super_doc, /* tp_doc */ - super_traverse, /* tp_traverse */ - 0, /* tp_clear */ - 0, /* tp_richcompare */ - 0, /* tp_weaklistoffset */ - 0, /* tp_iter */ - 0, /* tp_iternext */ - 0, /* tp_methods */ - super_members, /* tp_members */ - 0, /* tp_getset */ - 0, /* tp_base */ - 0, /* tp_dict */ - super_descr_get, /* tp_descr_get */ - 0, /* tp_descr_set */ - 0, /* tp_dictoffset */ - super_init, /* tp_init */ - PyType_GenericAlloc, /* tp_alloc */ - PyType_GenericNew, /* tp_new */ - PyObject_GC_Del, /* tp_free */ + PyVarObject_HEAD_INIT(&PyType_Type, 0) + "super", /* tp_name */ + sizeof(superobject), /* tp_basicsize */ + 0, /* tp_itemsize */ + /* methods */ + super_dealloc, /* tp_dealloc */ + 0, /* tp_print */ + 0, /* tp_getattr */ + 0, /* tp_setattr */ + 0, /* tp_reserved */ + super_repr, /* tp_repr */ + 0, /* tp_as_number */ + 0, /* tp_as_sequence */ + 0, /* tp_as_mapping */ + 0, /* tp_hash */ + 0, /* tp_call */ + 0, /* tp_str */ + super_getattro, /* tp_getattro */ + 0, /* tp_setattro */ + 0, /* tp_as_buffer */ + Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC | + Py_TPFLAGS_BASETYPE, /* tp_flags */ + super_doc, /* tp_doc */ + super_traverse, /* tp_traverse */ + 0, /* tp_clear */ + 0, /* tp_richcompare */ + 0, /* tp_weaklistoffset */ + 0, /* tp_iter */ + 0, /* tp_iternext */ + 0, /* tp_methods */ + super_members, /* tp_members */ + 0, /* tp_getset */ + 0, /* tp_base */ + 0, /* tp_dict */ + super_descr_get, /* tp_descr_get */ + 0, /* tp_descr_set */ + 0, /* tp_dictoffset */ + super_init, /* tp_init */ + PyType_GenericAlloc, /* tp_alloc */ + PyType_GenericNew, /* tp_new */ + PyObject_GC_Del, /* tp_free */ }; Modified: python/branches/py3k/Objects/weakrefobject.c ============================================================================== --- python/branches/py3k/Objects/weakrefobject.c (original) +++ python/branches/py3k/Objects/weakrefobject.c Sun May 9 17:52:27 2010 @@ -57,9 +57,9 @@ PyWeakref_GET_OBJECT(self)); if (*list == self) - /* If 'self' is the end of the list (and thus self->wr_next == NULL) - then the weakref list itself (and thus the value of *list) will - end up being set to NULL. */ + /* If 'self' is the end of the list (and thus self->wr_next == NULL) + then the weakref list itself (and thus the value of *list) will + end up being set to NULL. */ *list = self->wr_next; self->wr_object = Py_None; if (self->wr_prev != NULL) @@ -161,21 +161,21 @@ PyOS_snprintf(buffer, sizeof(buffer), "", self); } else { - char *name = NULL; - PyObject *nameobj = PyObject_GetAttrString(PyWeakref_GET_OBJECT(self), - "__name__"); - if (nameobj == NULL) - PyErr_Clear(); - else if (PyUnicode_Check(nameobj)) - name = _PyUnicode_AsString(nameobj); + char *name = NULL; + PyObject *nameobj = PyObject_GetAttrString(PyWeakref_GET_OBJECT(self), + "__name__"); + if (nameobj == NULL) + PyErr_Clear(); + else if (PyUnicode_Check(nameobj)) + name = _PyUnicode_AsString(nameobj); PyOS_snprintf(buffer, sizeof(buffer), - name ? "" - : "", - self, - Py_TYPE(PyWeakref_GET_OBJECT(self))->tp_name, - PyWeakref_GET_OBJECT(self), - name); - Py_XDECREF(nameobj); + name ? "" + : "", + self, + Py_TYPE(PyWeakref_GET_OBJECT(self))->tp_name, + PyWeakref_GET_OBJECT(self), + name); + Py_XDECREF(nameobj); } return PyUnicode_FromString(buffer); } @@ -188,8 +188,8 @@ weakref_richcompare(PyWeakReference* self, PyWeakReference* other, int op) { if ((op != Py_EQ && op != Py_NE) || - !PyWeakref_Check(self) || - !PyWeakref_Check(other)) { + !PyWeakref_Check(self) || + !PyWeakref_Check(other)) { Py_INCREF(Py_NotImplemented); return Py_NotImplemented; } @@ -339,10 +339,10 @@ sizeof(PyWeakReference), 0, weakref_dealloc, /*tp_dealloc*/ - 0, /*tp_print*/ + 0, /*tp_print*/ 0, /*tp_getattr*/ 0, /*tp_setattr*/ - 0, /*tp_reserved*/ + 0, /*tp_reserved*/ (reprfunc)weakref_repr, /*tp_repr*/ 0, /*tp_as_number*/ 0, /*tp_as_sequence*/ @@ -358,7 +358,7 @@ 0, /*tp_doc*/ (traverseproc)gc_traverse, /*tp_traverse*/ (inquiry)gc_clear, /*tp_clear*/ - (richcmpfunc)weakref_richcompare, /*tp_richcompare*/ + (richcmpfunc)weakref_richcompare, /*tp_richcompare*/ 0, /*tp_weaklistoffset*/ 0, /*tp_iter*/ 0, /*tp_iternext*/ @@ -438,9 +438,9 @@ #define WRAP_METHOD(method, special) \ static PyObject * \ method(PyObject *proxy) { \ - UNWRAP(proxy); \ - return PyObject_CallMethod(proxy, special, ""); \ - } + UNWRAP(proxy); \ + return PyObject_CallMethod(proxy, special, ""); \ + } /* direct slots */ @@ -454,9 +454,9 @@ { char buf[160]; PyOS_snprintf(buf, sizeof(buf), - "", proxy, - Py_TYPE(PyWeakref_GET_OBJECT(proxy))->tp_name, - PyWeakref_GET_OBJECT(proxy)); + "", proxy, + Py_TYPE(PyWeakref_GET_OBJECT(proxy))->tp_name, + PyWeakref_GET_OBJECT(proxy)); return PyUnicode_FromString(buf); } @@ -587,8 +587,8 @@ static PyMethodDef proxy_methods[] = { - {"__bytes__", (PyCFunction)proxy_bytes, METH_NOARGS}, - {NULL, NULL} + {"__bytes__", (PyCFunction)proxy_bytes, METH_NOARGS}, + {NULL, NULL} }; @@ -636,7 +636,7 @@ 0, /*sq_item*/ 0, /*sq_slice*/ 0, /*sq_ass_item*/ - 0, /*sq_ass_slice*/ + 0, /*sq_ass_slice*/ (objobjproc)proxy_contains, /* sq_contains */ }; @@ -655,20 +655,20 @@ 0, /* methods */ (destructor)proxy_dealloc, /* tp_dealloc */ - 0, /* tp_print */ - 0, /* tp_getattr */ - 0, /* tp_setattr */ - 0, /* tp_reserved */ - (reprfunc)proxy_repr, /* tp_repr */ - &proxy_as_number, /* tp_as_number */ - &proxy_as_sequence, /* tp_as_sequence */ - &proxy_as_mapping, /* tp_as_mapping */ - 0, /* tp_hash */ - 0, /* tp_call */ + 0, /* tp_print */ + 0, /* tp_getattr */ + 0, /* tp_setattr */ + 0, /* tp_reserved */ + (reprfunc)proxy_repr, /* tp_repr */ + &proxy_as_number, /* tp_as_number */ + &proxy_as_sequence, /* tp_as_sequence */ + &proxy_as_mapping, /* tp_as_mapping */ + 0, /* tp_hash */ + 0, /* tp_call */ proxy_str, /* tp_str */ proxy_getattr, /* tp_getattro */ (setattrofunc)proxy_setattr, /* tp_setattro */ - 0, /* tp_as_buffer */ + 0, /* tp_as_buffer */ Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC, /* tp_flags */ 0, /* tp_doc */ (traverseproc)gc_traverse, /* tp_traverse */ @@ -677,7 +677,7 @@ 0, /* tp_weaklistoffset */ (getiterfunc)proxy_iter, /* tp_iter */ (iternextfunc)proxy_iternext, /* tp_iternext */ - proxy_methods, /* tp_methods */ + proxy_methods, /* tp_methods */ }; @@ -689,20 +689,20 @@ 0, /* methods */ (destructor)proxy_dealloc, /* tp_dealloc */ - 0, /* tp_print */ - 0, /* tp_getattr */ - 0, /* tp_setattr */ - 0, /* tp_reserved */ - (unaryfunc)proxy_repr, /* tp_repr */ - &proxy_as_number, /* tp_as_number */ - &proxy_as_sequence, /* tp_as_sequence */ - &proxy_as_mapping, /* tp_as_mapping */ - 0, /* tp_hash */ - proxy_call, /* tp_call */ - proxy_str, /* tp_str */ + 0, /* tp_print */ + 0, /* tp_getattr */ + 0, /* tp_setattr */ + 0, /* tp_reserved */ + (unaryfunc)proxy_repr, /* tp_repr */ + &proxy_as_number, /* tp_as_number */ + &proxy_as_sequence, /* tp_as_sequence */ + &proxy_as_mapping, /* tp_as_mapping */ + 0, /* tp_hash */ + proxy_call, /* tp_call */ + proxy_str, /* tp_str */ proxy_getattr, /* tp_getattro */ (setattrofunc)proxy_setattr, /* tp_setattro */ - 0, /* tp_as_buffer */ + 0, /* tp_as_buffer */ Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC, /* tp_flags */ 0, /* tp_doc */ (traverseproc)gc_traverse, /* tp_traverse */ @@ -724,7 +724,7 @@ if (!PyType_SUPPORTS_WEAKREFS(Py_TYPE(ob))) { PyErr_Format(PyExc_TypeError, - "cannot create weak reference to '%s' object", + "cannot create weak reference to '%s' object", Py_TYPE(ob)->tp_name); return NULL; } @@ -783,7 +783,7 @@ if (!PyType_SUPPORTS_WEAKREFS(Py_TYPE(ob))) { PyErr_Format(PyExc_TypeError, - "cannot create weak reference to '%s' object", + "cannot create weak reference to '%s' object", Py_TYPE(ob)->tp_name); return NULL; } @@ -908,7 +908,7 @@ else { PyObject *tuple; Py_ssize_t i = 0; - + tuple = PyTuple_New(count * 2); if (tuple == NULL) { if (restore_error) Modified: python/branches/py3k/PC/VS7.1/make_buildinfo.c ============================================================================== --- python/branches/py3k/PC/VS7.1/make_buildinfo.c (original) +++ python/branches/py3k/PC/VS7.1/make_buildinfo.c Sun May 9 17:52:27 2010 @@ -21,72 +21,72 @@ int make_buildinfo2() { - struct _stat st; - HKEY hTortoise; - char command[500]; - DWORD type, size; - if (_stat(".svn", &st) < 0) - return 0; - /* Allow suppression of subwcrev.exe invocation if a no_subwcrev file is present. */ - if (_stat("no_subwcrev", &st) == 0) - return 0; - if (RegOpenKey(HKEY_LOCAL_MACHINE, "Software\\TortoiseSVN", &hTortoise) != ERROR_SUCCESS && - RegOpenKey(HKEY_CURRENT_USER, "Software\\TortoiseSVN", &hTortoise) != ERROR_SUCCESS) - /* Tortoise not installed */ - return 0; - command[0] = '"'; /* quote the path to the executable */ - size = sizeof(command) - 1; - if (RegQueryValueEx(hTortoise, "Directory", 0, &type, command+1, &size) != ERROR_SUCCESS || - type != REG_SZ) - /* Registry corrupted */ - return 0; - strcat(command, "bin\\subwcrev.exe"); - if (_stat(command+1, &st) < 0) - /* subwcrev.exe not part of the release */ - return 0; - strcat(command, "\" ..\\.. ..\\..\\Modules\\getbuildinfo.c getbuildinfo2.c"); - puts(command); fflush(stdout); - if (system(command) < 0) - return 0; - return 1; + struct _stat st; + HKEY hTortoise; + char command[500]; + DWORD type, size; + if (_stat(".svn", &st) < 0) + return 0; + /* Allow suppression of subwcrev.exe invocation if a no_subwcrev file is present. */ + if (_stat("no_subwcrev", &st) == 0) + return 0; + if (RegOpenKey(HKEY_LOCAL_MACHINE, "Software\\TortoiseSVN", &hTortoise) != ERROR_SUCCESS && + RegOpenKey(HKEY_CURRENT_USER, "Software\\TortoiseSVN", &hTortoise) != ERROR_SUCCESS) + /* Tortoise not installed */ + return 0; + command[0] = '"'; /* quote the path to the executable */ + size = sizeof(command) - 1; + if (RegQueryValueEx(hTortoise, "Directory", 0, &type, command+1, &size) != ERROR_SUCCESS || + type != REG_SZ) + /* Registry corrupted */ + return 0; + strcat(command, "bin\\subwcrev.exe"); + if (_stat(command+1, &st) < 0) + /* subwcrev.exe not part of the release */ + return 0; + strcat(command, "\" ..\\.. ..\\..\\Modules\\getbuildinfo.c getbuildinfo2.c"); + puts(command); fflush(stdout); + if (system(command) < 0) + return 0; + return 1; } int main(int argc, char*argv[]) { - char command[500] = "cl.exe -c -D_WIN32 -DUSE_DL_EXPORT -D_WINDOWS -DWIN32 -D_WINDLL "; - int do_unlink, result; - if (argc != 2) { - fprintf(stderr, "make_buildinfo $(ConfigurationName)\n"); - return EXIT_FAILURE; - } - if (strcmp(argv[1], "Release") == 0) { - strcat(command, "-MD "); - } - else if (strcmp(argv[1], "Debug") == 0) { - strcat(command, "-D_DEBUG -MDd "); - } - else if (strcmp(argv[1], "ReleaseItanium") == 0) { - strcat(command, "-MD /USECL:MS_ITANIUM "); - } - else if (strcmp(argv[1], "ReleaseAMD64") == 0) { - strcat(command, "-MD "); - strcat(command, "-MD /USECL:MS_OPTERON "); - } - else { - fprintf(stderr, "unsupported configuration %s\n", argv[1]); - return EXIT_FAILURE; - } + char command[500] = "cl.exe -c -D_WIN32 -DUSE_DL_EXPORT -D_WINDOWS -DWIN32 -D_WINDLL "; + int do_unlink, result; + if (argc != 2) { + fprintf(stderr, "make_buildinfo $(ConfigurationName)\n"); + return EXIT_FAILURE; + } + if (strcmp(argv[1], "Release") == 0) { + strcat(command, "-MD "); + } + else if (strcmp(argv[1], "Debug") == 0) { + strcat(command, "-D_DEBUG -MDd "); + } + else if (strcmp(argv[1], "ReleaseItanium") == 0) { + strcat(command, "-MD /USECL:MS_ITANIUM "); + } + else if (strcmp(argv[1], "ReleaseAMD64") == 0) { + strcat(command, "-MD "); + strcat(command, "-MD /USECL:MS_OPTERON "); + } + else { + fprintf(stderr, "unsupported configuration %s\n", argv[1]); + return EXIT_FAILURE; + } - if ((do_unlink = make_buildinfo2())) - strcat(command, "getbuildinfo2.c -DSUBWCREV "); - else - strcat(command, "..\\..\\Modules\\getbuildinfo.c"); - strcat(command, " -Fogetbuildinfo.o -I..\\..\\Include -I..\\..\\PC"); - puts(command); fflush(stdout); - result = system(command); - if (do_unlink) - unlink("getbuildinfo2.c"); - if (result < 0) - return EXIT_FAILURE; - return 0; + if ((do_unlink = make_buildinfo2())) + strcat(command, "getbuildinfo2.c -DSUBWCREV "); + else + strcat(command, "..\\..\\Modules\\getbuildinfo.c"); + strcat(command, " -Fogetbuildinfo.o -I..\\..\\Include -I..\\..\\PC"); + puts(command); fflush(stdout); + result = system(command); + if (do_unlink) + unlink("getbuildinfo2.c"); + if (result < 0) + return EXIT_FAILURE; + return 0; } Modified: python/branches/py3k/PC/VS8.0/make_buildinfo.c ============================================================================== --- python/branches/py3k/PC/VS8.0/make_buildinfo.c (original) +++ python/branches/py3k/PC/VS8.0/make_buildinfo.c Sun May 9 17:52:27 2010 @@ -23,72 +23,72 @@ int make_buildinfo2() { - struct _stat st; - HKEY hTortoise; - char command[CMD_SIZE+1]; - DWORD type, size; - if (_stat(".svn", &st) < 0) - return 0; - /* Allow suppression of subwcrev.exe invocation if a no_subwcrev file is present. */ - if (_stat("no_subwcrev", &st) == 0) - return 0; - if (RegOpenKey(HKEY_LOCAL_MACHINE, "Software\\TortoiseSVN", &hTortoise) != ERROR_SUCCESS && - RegOpenKey(HKEY_CURRENT_USER, "Software\\TortoiseSVN", &hTortoise) != ERROR_SUCCESS) - /* Tortoise not installed */ - return 0; - command[0] = '"'; /* quote the path to the executable */ - size = sizeof(command) - 1; - if (RegQueryValueEx(hTortoise, "Directory", 0, &type, command+1, &size) != ERROR_SUCCESS || - type != REG_SZ) - /* Registry corrupted */ - return 0; - strcat_s(command, CMD_SIZE, "bin\\subwcrev.exe"); - if (_stat(command+1, &st) < 0) - /* subwcrev.exe not part of the release */ - return 0; - strcat_s(command, CMD_SIZE, "\" ..\\.. ..\\..\\Modules\\getbuildinfo.c getbuildinfo2.c"); - puts(command); fflush(stdout); - if (system(command) < 0) - return 0; - return 1; + struct _stat st; + HKEY hTortoise; + char command[CMD_SIZE+1]; + DWORD type, size; + if (_stat(".svn", &st) < 0) + return 0; + /* Allow suppression of subwcrev.exe invocation if a no_subwcrev file is present. */ + if (_stat("no_subwcrev", &st) == 0) + return 0; + if (RegOpenKey(HKEY_LOCAL_MACHINE, "Software\\TortoiseSVN", &hTortoise) != ERROR_SUCCESS && + RegOpenKey(HKEY_CURRENT_USER, "Software\\TortoiseSVN", &hTortoise) != ERROR_SUCCESS) + /* Tortoise not installed */ + return 0; + command[0] = '"'; /* quote the path to the executable */ + size = sizeof(command) - 1; + if (RegQueryValueEx(hTortoise, "Directory", 0, &type, command+1, &size) != ERROR_SUCCESS || + type != REG_SZ) + /* Registry corrupted */ + return 0; + strcat_s(command, CMD_SIZE, "bin\\subwcrev.exe"); + if (_stat(command+1, &st) < 0) + /* subwcrev.exe not part of the release */ + return 0; + strcat_s(command, CMD_SIZE, "\" ..\\.. ..\\..\\Modules\\getbuildinfo.c getbuildinfo2.c"); + puts(command); fflush(stdout); + if (system(command) < 0) + return 0; + return 1; } int main(int argc, char*argv[]) { - char command[500] = "cl.exe -c -D_WIN32 -DUSE_DL_EXPORT -D_WINDOWS -DWIN32 -D_WINDLL "; - int do_unlink, result; - if (argc != 2) { - fprintf(stderr, "make_buildinfo $(ConfigurationName)\n"); - return EXIT_FAILURE; - } - if (strcmp(argv[1], "Release") == 0) { - strcat_s(command, CMD_SIZE, "-MD "); - } - else if (strcmp(argv[1], "Debug") == 0) { - strcat_s(command, CMD_SIZE, "-D_DEBUG -MDd "); - } - else if (strcmp(argv[1], "ReleaseItanium") == 0) { - strcat_s(command, CMD_SIZE, "-MD /USECL:MS_ITANIUM "); - } - else if (strcmp(argv[1], "ReleaseAMD64") == 0) { - strcat_s(command, CMD_SIZE, "-MD "); - strcat_s(command, CMD_SIZE, "-MD /USECL:MS_OPTERON "); - } - else { - fprintf(stderr, "unsupported configuration %s\n", argv[1]); - return EXIT_FAILURE; - } + char command[500] = "cl.exe -c -D_WIN32 -DUSE_DL_EXPORT -D_WINDOWS -DWIN32 -D_WINDLL "; + int do_unlink, result; + if (argc != 2) { + fprintf(stderr, "make_buildinfo $(ConfigurationName)\n"); + return EXIT_FAILURE; + } + if (strcmp(argv[1], "Release") == 0) { + strcat_s(command, CMD_SIZE, "-MD "); + } + else if (strcmp(argv[1], "Debug") == 0) { + strcat_s(command, CMD_SIZE, "-D_DEBUG -MDd "); + } + else if (strcmp(argv[1], "ReleaseItanium") == 0) { + strcat_s(command, CMD_SIZE, "-MD /USECL:MS_ITANIUM "); + } + else if (strcmp(argv[1], "ReleaseAMD64") == 0) { + strcat_s(command, CMD_SIZE, "-MD "); + strcat_s(command, CMD_SIZE, "-MD /USECL:MS_OPTERON "); + } + else { + fprintf(stderr, "unsupported configuration %s\n", argv[1]); + return EXIT_FAILURE; + } - if ((do_unlink = make_buildinfo2())) - strcat_s(command, CMD_SIZE, "getbuildinfo2.c -DSUBWCREV "); - else - strcat_s(command, CMD_SIZE, "..\\..\\Modules\\getbuildinfo.c"); - strcat_s(command, CMD_SIZE, " -Fogetbuildinfo.o -I..\\..\\Include -I..\\..\\PC"); - puts(command); fflush(stdout); - result = system(command); - if (do_unlink) - _unlink("getbuildinfo2.c"); - if (result < 0) - return EXIT_FAILURE; - return 0; -} \ No newline at end of file + if ((do_unlink = make_buildinfo2())) + strcat_s(command, CMD_SIZE, "getbuildinfo2.c -DSUBWCREV "); + else + strcat_s(command, CMD_SIZE, "..\\..\\Modules\\getbuildinfo.c"); + strcat_s(command, CMD_SIZE, " -Fogetbuildinfo.o -I..\\..\\Include -I..\\..\\PC"); + puts(command); fflush(stdout); + result = system(command); + if (do_unlink) + _unlink("getbuildinfo2.c"); + if (result < 0) + return EXIT_FAILURE; + return 0; +} Modified: python/branches/py3k/PC/_msi.c ============================================================================== --- python/branches/py3k/PC/_msi.c (original) +++ python/branches/py3k/PC/_msi.c Sun May 9 17:52:27 2010 @@ -20,19 +20,19 @@ UUID result; unsigned short *cresult; PyObject *oresult; - + /* May return ok, local only, and no address. For local only, the documentation says we still get a uuid. For RPC_S_UUID_NO_ADDRESS, it's not clear whether we can use the result. */ if (UuidCreate(&result) == RPC_S_UUID_NO_ADDRESS) { - PyErr_SetString(PyExc_NotImplementedError, "processing 'no address' result"); - return NULL; + PyErr_SetString(PyExc_NotImplementedError, "processing 'no address' result"); + return NULL; } if (UuidToStringW(&result, &cresult) == RPC_S_OUT_OF_MEMORY) { - PyErr_SetString(PyExc_MemoryError, "out of memory in uuidgen"); - return NULL; + PyErr_SetString(PyExc_MemoryError, "out of memory in uuidgen"); + return NULL; } oresult = PyUnicode_FromUnicode(cresult, wcslen(cresult)); @@ -57,7 +57,7 @@ { int result = _open(pszFile, oflag, pmode); if (result == -1) - *err = errno; + *err = errno; return result; } @@ -65,7 +65,7 @@ { UINT result = (UINT)_read(hf, memory, cb); if (result != cb) - *err = errno; + *err = errno; return result; } @@ -73,7 +73,7 @@ { UINT result = (UINT)_write(hf, memory, cb); if (result != cb) - *err = errno; + *err = errno; return result; } @@ -81,7 +81,7 @@ { int result = _close(hf); if (result != 0) - *err = errno; + *err = errno; return result; } @@ -89,7 +89,7 @@ { long result = (long)_lseek(hf, dist, seektype); if (result == -1) - *err = errno; + *err = errno; return result; } @@ -97,7 +97,7 @@ { int result = remove(pszFile); if (result != 0) - *err = errno; + *err = errno; return result; } @@ -110,9 +110,9 @@ { char *name = _tempnam("", "tmp"); if ((name != NULL) && ((int)strlen(name) < cbTempName)) { - strcpy(pszTempName, name); - free(name); - return TRUE; + strcpy(pszTempName, name); + free(name); + return TRUE; } if (name) free(name); @@ -122,10 +122,10 @@ static FNFCISTATUS(cb_status) { if (pv) { - PyObject *result = PyObject_CallMethod(pv, "status", "iii", typeStatus, cb1, cb2); - if (result == NULL) - return -1; - Py_DECREF(result); + PyObject *result = PyObject_CallMethod(pv, "status", "iii", typeStatus, cb1, cb2); + if (result == NULL) + return -1; + Py_DECREF(result); } return 0; } @@ -133,18 +133,18 @@ static FNFCIGETNEXTCABINET(cb_getnextcabinet) { if (pv) { - PyObject *result = PyObject_CallMethod(pv, "getnextcabinet", "i", pccab->iCab); - if (result == NULL) - return -1; - if (!PyBytes_Check(result)) { - PyErr_Format(PyExc_TypeError, - "Incorrect return type %s from getnextcabinet", - result->ob_type->tp_name); - Py_DECREF(result); - return FALSE; - } - strncpy(pccab->szCab, PyBytes_AsString(result), sizeof(pccab->szCab)); - return TRUE; + PyObject *result = PyObject_CallMethod(pv, "getnextcabinet", "i", pccab->iCab); + if (result == NULL) + return -1; + if (!PyBytes_Check(result)) { + PyErr_Format(PyExc_TypeError, + "Incorrect return type %s from getnextcabinet", + result->ob_type->tp_name); + Py_DECREF(result); + return FALSE; + } + strncpy(pccab->szCab, PyBytes_AsString(result), sizeof(pccab->szCab)); + return TRUE; } return FALSE; } @@ -157,21 +157,21 @@ /* Need Win32 handle to get time stamps */ handle = CreateFile(pszName, GENERIC_READ, FILE_SHARE_READ, NULL, - OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL); + OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL); if (handle == INVALID_HANDLE_VALUE) - return -1; + return -1; if (GetFileInformationByHandle(handle, &bhfi) == FALSE) { - CloseHandle(handle); - return -1; + CloseHandle(handle); + return -1; } FileTimeToLocalFileTime(&bhfi.ftLastWriteTime, &filetime); FileTimeToDosDateTime(&filetime, pdate, ptime); - *pattribs = (int)(bhfi.dwFileAttributes & - (_A_RDONLY | _A_SYSTEM | _A_HIDDEN | _A_ARCH)); + *pattribs = (int)(bhfi.dwFileAttributes & + (_A_RDONLY | _A_SYSTEM | _A_HIDDEN | _A_ARCH)); CloseHandle(handle); @@ -189,11 +189,11 @@ if (!PyArg_ParseTuple(args, "sO:FCICreate", &cabname, &files)) - return NULL; + return NULL; if (!PyList_Check(files)) { - PyErr_SetString(PyExc_TypeError, "FCICreate expects a list"); - return NULL; + PyErr_SetString(PyExc_TypeError, "FCICreate expects a list"); + return NULL; } ccab.cb = INT_MAX; /* no need to split CAB into multiple media */ @@ -209,49 +209,49 @@ ccab.szDisk[0] = '\0'; for (i = 0, p = cabname; *p; p = CharNext(p)) - if (*p == '\\' || *p == '/') - i = p - cabname + 1; + if (*p == '\\' || *p == '/') + i = p - cabname + 1; if (i >= sizeof(ccab.szCabPath) || - strlen(cabname+i) >= sizeof(ccab.szCab)) { - PyErr_SetString(PyExc_ValueError, "path name too long"); - return 0; + strlen(cabname+i) >= sizeof(ccab.szCab)) { + PyErr_SetString(PyExc_ValueError, "path name too long"); + return 0; } if (i > 0) { - memcpy(ccab.szCabPath, cabname, i); - ccab.szCabPath[i] = '\0'; - strcpy(ccab.szCab, cabname+i); + memcpy(ccab.szCabPath, cabname, i); + ccab.szCabPath[i] = '\0'; + strcpy(ccab.szCab, cabname+i); } else { - strcpy(ccab.szCabPath, ".\\"); - strcpy(ccab.szCab, cabname); + strcpy(ccab.szCabPath, ".\\"); + strcpy(ccab.szCab, cabname); } hfci = FCICreate(&erf, cb_fileplaced, cb_alloc, cb_free, - cb_open, cb_read, cb_write, cb_close, cb_seek, cb_delete, - cb_gettempfile, &ccab, NULL); + cb_open, cb_read, cb_write, cb_close, cb_seek, cb_delete, + cb_gettempfile, &ccab, NULL); if (hfci == NULL) { - PyErr_Format(PyExc_ValueError, "FCI error %d", erf.erfOper); - return NULL; + PyErr_Format(PyExc_ValueError, "FCI error %d", erf.erfOper); + return NULL; } for (i=0; i < PyList_GET_SIZE(files); i++) { - PyObject *item = PyList_GET_ITEM(files, i); - char *filename, *cabname; - if (!PyArg_ParseTuple(item, "ss", &filename, &cabname)) - goto err; - if (!FCIAddFile(hfci, filename, cabname, FALSE, - cb_getnextcabinet, cb_status, cb_getopeninfo, - tcompTYPE_MSZIP)) - goto err; + PyObject *item = PyList_GET_ITEM(files, i); + char *filename, *cabname; + if (!PyArg_ParseTuple(item, "ss", &filename, &cabname)) + goto err; + if (!FCIAddFile(hfci, filename, cabname, FALSE, + cb_getnextcabinet, cb_status, cb_getopeninfo, + tcompTYPE_MSZIP)) + goto err; } if (!FCIFlushCabinet(hfci, FALSE, cb_getnextcabinet, cb_status)) - goto err; + goto err; if (!FCIDestroy(hfci)) - goto err; + goto err; Py_INCREF(Py_None); return Py_None; @@ -266,7 +266,7 @@ MSIHANDLE h; }msiobj; -static void +static void msiobj_dealloc(msiobj* msidb) { MsiCloseHandle(msidb->h); @@ -292,41 +292,41 @@ MSIHANDLE err = MsiGetLastErrorRecord(); if (err == 0) { - switch(status) { - case ERROR_ACCESS_DENIED: - PyErr_SetString(MSIError, "access denied"); - return NULL; - case ERROR_FUNCTION_FAILED: - PyErr_SetString(MSIError, "function failed"); - return NULL; - case ERROR_INVALID_DATA: - PyErr_SetString(MSIError, "invalid data"); - return NULL; - case ERROR_INVALID_HANDLE: - PyErr_SetString(MSIError, "invalid handle"); - return NULL; - case ERROR_INVALID_STATE: - PyErr_SetString(MSIError, "invalid state"); - return NULL; - case ERROR_INVALID_PARAMETER: - PyErr_SetString(MSIError, "invalid parameter"); - return NULL; - default: - PyErr_Format(MSIError, "unknown error %x", status); - return NULL; - } + switch(status) { + case ERROR_ACCESS_DENIED: + PyErr_SetString(MSIError, "access denied"); + return NULL; + case ERROR_FUNCTION_FAILED: + PyErr_SetString(MSIError, "function failed"); + return NULL; + case ERROR_INVALID_DATA: + PyErr_SetString(MSIError, "invalid data"); + return NULL; + case ERROR_INVALID_HANDLE: + PyErr_SetString(MSIError, "invalid handle"); + return NULL; + case ERROR_INVALID_STATE: + PyErr_SetString(MSIError, "invalid state"); + return NULL; + case ERROR_INVALID_PARAMETER: + PyErr_SetString(MSIError, "invalid parameter"); + return NULL; + default: + PyErr_Format(MSIError, "unknown error %x", status); + return NULL; + } } code = MsiRecordGetInteger(err, 1); /* XXX code */ if (MsiFormatRecord(0, err, res, &size) == ERROR_MORE_DATA) { - res = malloc(size+1); - MsiFormatRecord(0, err, res, &size); - res[size]='\0'; + res = malloc(size+1); + MsiFormatRecord(0, err, res, &size); + res[size]='\0'; } MsiCloseHandle(err); PyErr_SetString(MSIError, res); if (res != buf) - free(res); + free(res); return NULL; } @@ -343,7 +343,7 @@ { unsigned int field; int status; - + if (!PyArg_ParseTuple(args, "I:GetInteger", &field)) return NULL; status = MsiRecordGetInteger(record->h, field); @@ -363,7 +363,7 @@ WCHAR *res = buf; DWORD size = sizeof(buf); PyObject* string; - + if (!PyArg_ParseTuple(args, "I:GetString", &field)) return NULL; status = MsiRecordGetStringW(record->h, field, res, &size); @@ -386,7 +386,7 @@ { int status = MsiRecordClearData(record->h); if (status != ERROR_SUCCESS) - return msierror(status); + return msierror(status); Py_INCREF(Py_None); return Py_None; @@ -400,10 +400,10 @@ Py_UNICODE *data; if (!PyArg_ParseTuple(args, "iu:SetString", &field, &data)) - return NULL; + return NULL; if ((status = MsiRecordSetStringW(record->h, field, data)) != ERROR_SUCCESS) - return msierror(status); + return msierror(status); Py_INCREF(Py_None); return Py_None; @@ -417,10 +417,10 @@ Py_UNICODE *data; if (!PyArg_ParseTuple(args, "iu:SetStream", &field, &data)) - return NULL; + return NULL; if ((status = MsiRecordSetStreamW(record->h, field, data)) != ERROR_SUCCESS) - return msierror(status); + return msierror(status); Py_INCREF(Py_None); return Py_None; @@ -434,10 +434,10 @@ int data; if (!PyArg_ParseTuple(args, "ii:SetInteger", &field, &data)) - return NULL; + return NULL; if ((status = MsiRecordSetInteger(record->h, field, data)) != ERROR_SUCCESS) - return msierror(status); + return msierror(status); Py_INCREF(Py_None); return Py_None; @@ -446,39 +446,39 @@ static PyMethodDef record_methods[] = { - { "GetFieldCount", (PyCFunction)record_getfieldcount, METH_NOARGS, - PyDoc_STR("GetFieldCount() -> int\nWraps MsiRecordGetFieldCount")}, + { "GetFieldCount", (PyCFunction)record_getfieldcount, METH_NOARGS, + PyDoc_STR("GetFieldCount() -> int\nWraps MsiRecordGetFieldCount")}, { "GetInteger", (PyCFunction)record_getinteger, METH_VARARGS, PyDoc_STR("GetInteger(field) -> int\nWraps MsiRecordGetInteger")}, { "GetString", (PyCFunction)record_getstring, METH_VARARGS, PyDoc_STR("GetString(field) -> string\nWraps MsiRecordGetString")}, - { "SetString", (PyCFunction)record_setstring, METH_VARARGS, - PyDoc_STR("SetString(field,str) -> None\nWraps MsiRecordSetString")}, - { "SetStream", (PyCFunction)record_setstream, METH_VARARGS, - PyDoc_STR("SetStream(field,filename) -> None\nWraps MsiRecordSetInteger")}, - { "SetInteger", (PyCFunction)record_setinteger, METH_VARARGS, - PyDoc_STR("SetInteger(field,int) -> None\nWraps MsiRecordSetInteger")}, - { "ClearData", (PyCFunction)record_cleardata, METH_NOARGS, - PyDoc_STR("ClearData() -> int\nWraps MsiRecordGClearData")}, + { "SetString", (PyCFunction)record_setstring, METH_VARARGS, + PyDoc_STR("SetString(field,str) -> None\nWraps MsiRecordSetString")}, + { "SetStream", (PyCFunction)record_setstream, METH_VARARGS, + PyDoc_STR("SetStream(field,filename) -> None\nWraps MsiRecordSetInteger")}, + { "SetInteger", (PyCFunction)record_setinteger, METH_VARARGS, + PyDoc_STR("SetInteger(field,int) -> None\nWraps MsiRecordSetInteger")}, + { "ClearData", (PyCFunction)record_cleardata, METH_NOARGS, + PyDoc_STR("ClearData() -> int\nWraps MsiRecordGClearData")}, { NULL, NULL } }; static PyTypeObject record_Type = { - PyVarObject_HEAD_INIT(NULL, 0) - "_msi.Record", /*tp_name*/ - sizeof(msiobj), /*tp_basicsize*/ - 0, /*tp_itemsize*/ - /* methods */ - (destructor)msiobj_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*/ + PyVarObject_HEAD_INIT(NULL, 0) + "_msi.Record", /*tp_name*/ + sizeof(msiobj), /*tp_basicsize*/ + 0, /*tp_itemsize*/ + /* methods */ + (destructor)msiobj_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*/ @@ -513,8 +513,8 @@ msiobj *result = PyObject_NEW(struct msiobj, &record_Type); if (!result) { - MsiCloseHandle(h); - return NULL; + MsiCloseHandle(h); + return NULL; } result->h = h; @@ -537,27 +537,27 @@ DWORD ssize = sizeof(sval); if (!PyArg_ParseTuple(args, "i:GetProperty", &field)) - return NULL; + return NULL; - status = MsiSummaryInfoGetProperty(si->h, field, &type, &ival, - &fval, sval, &ssize); + status = MsiSummaryInfoGetProperty(si->h, field, &type, &ival, + &fval, sval, &ssize); if (status == ERROR_MORE_DATA) { - sval = malloc(ssize); - status = MsiSummaryInfoGetProperty(si->h, field, &type, &ival, - &fval, sval, &ssize); + sval = malloc(ssize); + status = MsiSummaryInfoGetProperty(si->h, field, &type, &ival, + &fval, sval, &ssize); } switch(type) { - case VT_I2: case VT_I4: - return PyLong_FromLong(ival); - case VT_FILETIME: - PyErr_SetString(PyExc_NotImplementedError, "FILETIME result"); - return NULL; - case VT_LPSTR: - result = PyBytes_FromStringAndSize(sval, ssize); - if (sval != sbuf) - free(sval); - return result; + case VT_I2: case VT_I4: + return PyLong_FromLong(ival); + case VT_FILETIME: + PyErr_SetString(PyExc_NotImplementedError, "FILETIME result"); + return NULL; + case VT_LPSTR: + result = PyBytes_FromStringAndSize(sval, ssize); + if (sval != sbuf) + free(sval); + return result; } PyErr_Format(PyExc_NotImplementedError, "result of type %d", type); return NULL; @@ -571,7 +571,7 @@ status = MsiSummaryInfoGetPropertyCount(si->h, &result); if (status != ERROR_SUCCESS) - return msierror(status); + return msierror(status); return PyLong_FromLong(result); } @@ -584,25 +584,25 @@ PyObject* data; if (!PyArg_ParseTuple(args, "iO:SetProperty", &field, &data)) - return NULL; + return NULL; if (PyUnicode_Check(data)) { - status = MsiSummaryInfoSetPropertyW(si->h, field, VT_LPSTR, - 0, NULL, PyUnicode_AsUnicode(data)); + status = MsiSummaryInfoSetPropertyW(si->h, field, VT_LPSTR, + 0, NULL, PyUnicode_AsUnicode(data)); } else if (PyLong_CheckExact(data)) { - long value = PyLong_AsLong(data); - if (value == -1 && PyErr_Occurred()) { - return NULL; - } - status = MsiSummaryInfoSetProperty(si->h, field, VT_I4, - value, NULL, NULL); + long value = PyLong_AsLong(data); + if (value == -1 && PyErr_Occurred()) { + return NULL; + } + status = MsiSummaryInfoSetProperty(si->h, field, VT_I4, + value, NULL, NULL); } else { - PyErr_SetString(PyExc_TypeError, "unsupported type"); - return NULL; + PyErr_SetString(PyExc_TypeError, "unsupported type"); + return NULL; } - + if (status != ERROR_SUCCESS) - return msierror(status); + return msierror(status); Py_INCREF(Py_None); return Py_None; @@ -616,39 +616,39 @@ status = MsiSummaryInfoPersist(si->h); if (status != ERROR_SUCCESS) - return msierror(status); + return msierror(status); Py_INCREF(Py_None); return Py_None; } static PyMethodDef summary_methods[] = { - { "GetProperty", (PyCFunction)summary_getproperty, METH_VARARGS, - PyDoc_STR("GetProperty(propid) -> value\nWraps MsiSummaryInfoGetProperty")}, - { "GetPropertyCount", (PyCFunction)summary_getpropertycount, METH_NOARGS, - PyDoc_STR("GetProperty() -> int\nWraps MsiSummaryInfoGetPropertyCount")}, - { "SetProperty", (PyCFunction)summary_setproperty, METH_VARARGS, - PyDoc_STR("SetProperty(value) -> None\nWraps MsiSummaryInfoProperty")}, - { "Persist", (PyCFunction)summary_persist, METH_NOARGS, - PyDoc_STR("Persist() -> None\nWraps MsiSummaryInfoPersist")}, + { "GetProperty", (PyCFunction)summary_getproperty, METH_VARARGS, + PyDoc_STR("GetProperty(propid) -> value\nWraps MsiSummaryInfoGetProperty")}, + { "GetPropertyCount", (PyCFunction)summary_getpropertycount, METH_NOARGS, + PyDoc_STR("GetProperty() -> int\nWraps MsiSummaryInfoGetPropertyCount")}, + { "SetProperty", (PyCFunction)summary_setproperty, METH_VARARGS, + PyDoc_STR("SetProperty(value) -> None\nWraps MsiSummaryInfoProperty")}, + { "Persist", (PyCFunction)summary_persist, METH_NOARGS, + PyDoc_STR("Persist() -> None\nWraps MsiSummaryInfoPersist")}, { NULL, NULL } }; static PyTypeObject summary_Type = { - PyVarObject_HEAD_INIT(NULL, 0) - "_msi.SummaryInformation", /*tp_name*/ - sizeof(msiobj), /*tp_basicsize*/ - 0, /*tp_itemsize*/ - /* methods */ - (destructor)msiobj_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*/ + PyVarObject_HEAD_INIT(NULL, 0) + "_msi.SummaryInformation", /*tp_name*/ + sizeof(msiobj), /*tp_basicsize*/ + 0, /*tp_itemsize*/ + /* methods */ + (destructor)msiobj_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*/ @@ -687,7 +687,7 @@ PyObject *oparams = Py_None; if (!PyArg_ParseTuple(args, "O:Execute", &oparams)) - return NULL; + return NULL; if (oparams != Py_None) { if (oparams->ob_type != &record_Type) { @@ -699,7 +699,7 @@ status = MsiViewExecute(view->h, params); if (status != ERROR_SUCCESS) - return msierror(status); + return msierror(status); Py_INCREF(Py_None); return Py_None; @@ -712,7 +712,7 @@ MSIHANDLE result; if ((status = MsiViewFetch(view->h, &result)) != ERROR_SUCCESS) - return msierror(status); + return msierror(status); return record_new(result); } @@ -725,10 +725,10 @@ MSIHANDLE result; if (!PyArg_ParseTuple(args, "i:GetColumnInfo", &kind)) - return NULL; + return NULL; if ((status = MsiViewGetColumnInfo(view->h, kind, &result)) != ERROR_SUCCESS) - return msierror(status); + return msierror(status); return record_new(result); } @@ -741,15 +741,15 @@ int status; if (!PyArg_ParseTuple(args, "iO:Modify", &kind, &data)) - return NULL; + return NULL; if (data->ob_type != &record_Type) { - PyErr_SetString(PyExc_TypeError, "Modify expects a record object"); - return NULL; + PyErr_SetString(PyExc_TypeError, "Modify expects a record object"); + return NULL; } if ((status = MsiViewModify(view->h, kind, ((msiobj*)data)->h)) != ERROR_SUCCESS) - return msierror(status); + return msierror(status); Py_INCREF(Py_None); return Py_None; @@ -761,42 +761,42 @@ int status; if ((status = MsiViewClose(view->h)) != ERROR_SUCCESS) - return msierror(status); + return msierror(status); Py_INCREF(Py_None); return Py_None; } static PyMethodDef view_methods[] = { - { "Execute", (PyCFunction)view_execute, METH_VARARGS, - PyDoc_STR("Execute(params=None) -> None\nWraps MsiViewExecute")}, + { "Execute", (PyCFunction)view_execute, METH_VARARGS, + PyDoc_STR("Execute(params=None) -> None\nWraps MsiViewExecute")}, { "GetColumnInfo", (PyCFunction)view_getcolumninfo, METH_VARARGS, - PyDoc_STR("GetColumnInfo() -> result\nWraps MsiGetColumnInfo")}, + PyDoc_STR("GetColumnInfo() -> result\nWraps MsiGetColumnInfo")}, { "Fetch", (PyCFunction)view_fetch, METH_NOARGS, - PyDoc_STR("Fetch() -> result\nWraps MsiViewFetch")}, + PyDoc_STR("Fetch() -> result\nWraps MsiViewFetch")}, { "Modify", (PyCFunction)view_modify, METH_VARARGS, - PyDoc_STR("Modify(mode,record) -> None\nWraps MsiViewModify")}, + PyDoc_STR("Modify(mode,record) -> None\nWraps MsiViewModify")}, { "Close", (PyCFunction)view_close, METH_NOARGS, - PyDoc_STR("Close() -> result\nWraps MsiViewClose")}, + PyDoc_STR("Close() -> result\nWraps MsiViewClose")}, { NULL, NULL } }; static PyTypeObject msiview_Type = { - PyVarObject_HEAD_INIT(NULL, 0) - "_msi.View", /*tp_name*/ - sizeof(msiobj), /*tp_basicsize*/ - 0, /*tp_itemsize*/ - /* methods */ - (destructor)msiobj_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*/ + PyVarObject_HEAD_INIT(NULL, 0) + "_msi.View", /*tp_name*/ + sizeof(msiobj), /*tp_basicsize*/ + 0, /*tp_itemsize*/ + /* methods */ + (destructor)msiobj_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*/ @@ -836,15 +836,15 @@ msiobj *result; if (!PyArg_ParseTuple(args, "s:OpenView", &sql)) - return NULL; + return NULL; if ((status = MsiDatabaseOpenView(msidb->h, sql, &hView)) != ERROR_SUCCESS) - return msierror(status); + return msierror(status); result = PyObject_NEW(struct msiobj, &msiview_Type); if (!result) { - MsiCloseHandle(hView); - return NULL; + MsiCloseHandle(hView); + return NULL; } result->h = hView; @@ -857,7 +857,7 @@ int status; if ((status = MsiDatabaseCommit(msidb->h)) != ERROR_SUCCESS) - return msierror(status); + return msierror(status); Py_INCREF(Py_None); return Py_None; @@ -872,16 +872,16 @@ msiobj *oresult; if (!PyArg_ParseTuple(args, "i:GetSummaryInformation", &count)) - return NULL; + return NULL; status = MsiGetSummaryInformation(db->h, NULL, count, &result); if (status != ERROR_SUCCESS) - return msierror(status); + return msierror(status); oresult = PyObject_NEW(struct msiobj, &summary_Type); if (!result) { - MsiCloseHandle(result); - return NULL; + MsiCloseHandle(result); + return NULL; } oresult->h = result; @@ -889,31 +889,31 @@ } static PyMethodDef db_methods[] = { - { "OpenView", (PyCFunction)msidb_openview, METH_VARARGS, - PyDoc_STR("OpenView(sql) -> viewobj\nWraps MsiDatabaseOpenView")}, + { "OpenView", (PyCFunction)msidb_openview, METH_VARARGS, + PyDoc_STR("OpenView(sql) -> viewobj\nWraps MsiDatabaseOpenView")}, { "Commit", (PyCFunction)msidb_commit, METH_NOARGS, - PyDoc_STR("Commit() -> None\nWraps MsiDatabaseCommit")}, - { "GetSummaryInformation", (PyCFunction)msidb_getsummaryinformation, METH_VARARGS, - PyDoc_STR("GetSummaryInformation(updateCount) -> viewobj\nWraps MsiGetSummaryInformation")}, + PyDoc_STR("Commit() -> None\nWraps MsiDatabaseCommit")}, + { "GetSummaryInformation", (PyCFunction)msidb_getsummaryinformation, METH_VARARGS, + PyDoc_STR("GetSummaryInformation(updateCount) -> viewobj\nWraps MsiGetSummaryInformation")}, { NULL, NULL } }; static PyTypeObject msidb_Type = { - PyVarObject_HEAD_INIT(NULL, 0) - "_msi.Database", /*tp_name*/ - sizeof(msiobj), /*tp_basicsize*/ - 0, /*tp_itemsize*/ - /* methods */ - (destructor)msiobj_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*/ + PyVarObject_HEAD_INIT(NULL, 0) + "_msi.Database", /*tp_name*/ + sizeof(msiobj), /*tp_basicsize*/ + 0, /*tp_itemsize*/ + /* methods */ + (destructor)msiobj_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*/ @@ -949,18 +949,18 @@ int persist; MSIHANDLE h; msiobj *result; - + if (!PyArg_ParseTuple(args, "si:MSIOpenDatabase", &path, &persist)) - return NULL; + return NULL; - status = MsiOpenDatabase(path, (LPCSTR)persist, &h); + status = MsiOpenDatabase(path, (LPCSTR)persist, &h); if (status != ERROR_SUCCESS) - return msierror(status); + return msierror(status); result = PyObject_NEW(struct msiobj, &msidb_Type); if (!result) { - MsiCloseHandle(h); - return NULL; + MsiCloseHandle(h); + return NULL; } result->h = h; return (PyObject*)result; @@ -973,11 +973,11 @@ MSIHANDLE h; if (!PyArg_ParseTuple(args, "i:CreateRecord", &count)) - return NULL; - + return NULL; + h = MsiCreateRecord(count); if (h == 0) - return msierror(0); + return msierror(0); return record_new(h); } @@ -985,29 +985,29 @@ static PyMethodDef msi_methods[] = { {"UuidCreate", (PyCFunction)uuidcreate, METH_NOARGS, - PyDoc_STR("UuidCreate() -> string")}, - {"FCICreate", (PyCFunction)fcicreate, METH_VARARGS, - PyDoc_STR("fcicreate(cabname,files) -> None")}, - {"OpenDatabase", (PyCFunction)msiopendb, METH_VARARGS, - PyDoc_STR("OpenDatabase(name, flags) -> dbobj\nWraps MsiOpenDatabase")}, - {"CreateRecord", (PyCFunction)createrecord, METH_VARARGS, - PyDoc_STR("OpenDatabase(name, flags) -> dbobj\nWraps MsiCreateRecord")}, - {NULL, NULL} /* sentinel */ + PyDoc_STR("UuidCreate() -> string")}, + {"FCICreate", (PyCFunction)fcicreate, METH_VARARGS, + PyDoc_STR("fcicreate(cabname,files) -> None")}, + {"OpenDatabase", (PyCFunction)msiopendb, METH_VARARGS, + PyDoc_STR("OpenDatabase(name, flags) -> dbobj\nWraps MsiOpenDatabase")}, + {"CreateRecord", (PyCFunction)createrecord, METH_VARARGS, + PyDoc_STR("OpenDatabase(name, flags) -> dbobj\nWraps MsiCreateRecord")}, + {NULL, NULL} /* sentinel */ }; static char msi_doc[] = "Documentation"; static struct PyModuleDef _msimodule = { - PyModuleDef_HEAD_INIT, - "_msi", - msi_doc, - -1, - msi_methods, - NULL, - NULL, - NULL, - NULL + PyModuleDef_HEAD_INIT, + "_msi", + msi_doc, + -1, + msi_methods, + NULL, + NULL, + NULL, + NULL }; PyMODINIT_FUNC @@ -1017,7 +1017,7 @@ m = PyModule_Create(&_msimodule); if (m == NULL) - return NULL; + return NULL; PyModule_AddIntConstant(m, "MSIDBOPEN_CREATEDIRECT", (int)MSIDBOPEN_CREATEDIRECT); PyModule_AddIntConstant(m, "MSIDBOPEN_CREATE", (int)MSIDBOPEN_CREATE); @@ -1063,7 +1063,7 @@ MSIError = PyErr_NewException ("_msi.MSIError", NULL, NULL); if (!MSIError) - return NULL; + return NULL; PyModule_AddObject(m, "MSIError", MSIError); return m; } Modified: python/branches/py3k/PC/_subprocess.c ============================================================================== --- python/branches/py3k/PC/_subprocess.c (original) +++ python/branches/py3k/PC/_subprocess.c Sun May 9 17:52:27 2010 @@ -46,8 +46,8 @@ the wrapper is used to provide Detach and Close methods */ typedef struct { - PyObject_HEAD - HANDLE handle; + PyObject_HEAD + HANDLE handle; } sp_handle_object; static PyTypeObject sp_handle_type; @@ -55,104 +55,104 @@ static PyObject* sp_handle_new(HANDLE handle) { - sp_handle_object* self; + sp_handle_object* self; - self = PyObject_NEW(sp_handle_object, &sp_handle_type); - if (self == NULL) - return NULL; + self = PyObject_NEW(sp_handle_object, &sp_handle_type); + if (self == NULL) + return NULL; - self->handle = handle; + self->handle = handle; - return (PyObject*) self; + return (PyObject*) self; } #if defined(MS_WIN32) && !defined(MS_WIN64) -#define HANDLE_TO_PYNUM(handle) PyLong_FromLong((long) handle) -#define PY_HANDLE_PARAM "l" +#define HANDLE_TO_PYNUM(handle) PyLong_FromLong((long) handle) +#define PY_HANDLE_PARAM "l" #else -#define HANDLE_TO_PYNUM(handle) PyLong_FromLongLong((long long) handle) -#define PY_HANDLE_PARAM "L" +#define HANDLE_TO_PYNUM(handle) PyLong_FromLongLong((long long) handle) +#define PY_HANDLE_PARAM "L" #endif static PyObject* sp_handle_detach(sp_handle_object* self, PyObject* args) { - HANDLE handle; + HANDLE handle; - if (! PyArg_ParseTuple(args, ":Detach")) - return NULL; + if (! PyArg_ParseTuple(args, ":Detach")) + return NULL; - handle = self->handle; + handle = self->handle; - self->handle = INVALID_HANDLE_VALUE; + self->handle = INVALID_HANDLE_VALUE; - /* note: return the current handle, as an integer */ - return HANDLE_TO_PYNUM(handle); + /* note: return the current handle, as an integer */ + return HANDLE_TO_PYNUM(handle); } static PyObject* sp_handle_close(sp_handle_object* self, PyObject* args) { - if (! PyArg_ParseTuple(args, ":Close")) - return NULL; + if (! PyArg_ParseTuple(args, ":Close")) + return NULL; - if (self->handle != INVALID_HANDLE_VALUE) { - CloseHandle(self->handle); - self->handle = INVALID_HANDLE_VALUE; - } - Py_INCREF(Py_None); - return Py_None; + if (self->handle != INVALID_HANDLE_VALUE) { + CloseHandle(self->handle); + self->handle = INVALID_HANDLE_VALUE; + } + Py_INCREF(Py_None); + return Py_None; } static void sp_handle_dealloc(sp_handle_object* self) { - if (self->handle != INVALID_HANDLE_VALUE) - CloseHandle(self->handle); - PyObject_FREE(self); + if (self->handle != INVALID_HANDLE_VALUE) + CloseHandle(self->handle); + PyObject_FREE(self); } static PyMethodDef sp_handle_methods[] = { - {"Detach", (PyCFunction) sp_handle_detach, METH_VARARGS}, - {"Close", (PyCFunction) sp_handle_close, METH_VARARGS}, - {NULL, NULL} + {"Detach", (PyCFunction) sp_handle_detach, METH_VARARGS}, + {"Close", (PyCFunction) sp_handle_close, METH_VARARGS}, + {NULL, NULL} }; static PyObject* sp_handle_as_int(sp_handle_object* self) { - return HANDLE_TO_PYNUM(self->handle); + return HANDLE_TO_PYNUM(self->handle); } static PyNumberMethods sp_handle_as_number; static PyTypeObject sp_handle_type = { - PyVarObject_HEAD_INIT(NULL, 0) - "_subprocess_handle", sizeof(sp_handle_object), 0, - (destructor) sp_handle_dealloc, /*tp_dealloc*/ - 0, /*tp_print*/ - 0, /*tp_getattr*/ - 0, /*tp_setattr*/ - 0, /*tp_reserved*/ - 0, /*tp_repr*/ - &sp_handle_as_number, /*tp_as_number */ - 0, /*tp_as_sequence */ - 0, /*tp_as_mapping */ - 0, /*tp_hash*/ - 0, /*tp_call*/ - 0, /*tp_str*/ - 0, /*tp_getattro*/ - 0, /*tp_setattro*/ - 0, /*tp_as_buffer*/ - Py_TPFLAGS_DEFAULT, /*tp_flags*/ - 0, /*tp_doc*/ - 0, /*tp_traverse*/ - 0, /*tp_clear*/ - 0, /*tp_richcompare*/ - 0, /*tp_weaklistoffset*/ - 0, /*tp_iter*/ - 0, /*tp_iternext*/ - sp_handle_methods, /*tp_methods*/ + PyVarObject_HEAD_INIT(NULL, 0) + "_subprocess_handle", sizeof(sp_handle_object), 0, + (destructor) sp_handle_dealloc, /*tp_dealloc*/ + 0, /*tp_print*/ + 0, /*tp_getattr*/ + 0, /*tp_setattr*/ + 0, /*tp_reserved*/ + 0, /*tp_repr*/ + &sp_handle_as_number, /*tp_as_number */ + 0, /*tp_as_sequence */ + 0, /*tp_as_mapping */ + 0, /*tp_hash*/ + 0, /*tp_call*/ + 0, /*tp_str*/ + 0, /*tp_getattro*/ + 0, /*tp_setattro*/ + 0, /*tp_as_buffer*/ + Py_TPFLAGS_DEFAULT, /*tp_flags*/ + 0, /*tp_doc*/ + 0, /*tp_traverse*/ + 0, /*tp_clear*/ + 0, /*tp_richcompare*/ + 0, /*tp_weaklistoffset*/ + 0, /*tp_iter*/ + 0, /*tp_iternext*/ + sp_handle_methods, /*tp_methods*/ }; /* -------------------------------------------------------------------- */ @@ -168,26 +168,26 @@ static PyObject * sp_GetStdHandle(PyObject* self, PyObject* args) { - HANDLE handle; - int std_handle; + HANDLE handle; + int std_handle; - if (! PyArg_ParseTuple(args, "i:GetStdHandle", &std_handle)) - return NULL; + if (! PyArg_ParseTuple(args, "i:GetStdHandle", &std_handle)) + return NULL; - Py_BEGIN_ALLOW_THREADS - handle = GetStdHandle((DWORD) std_handle); - Py_END_ALLOW_THREADS - - if (handle == INVALID_HANDLE_VALUE) - return PyErr_SetFromWindowsErr(GetLastError()); - - if (! handle) { - Py_INCREF(Py_None); - return Py_None; - } + Py_BEGIN_ALLOW_THREADS + handle = GetStdHandle((DWORD) std_handle); + Py_END_ALLOW_THREADS + + if (handle == INVALID_HANDLE_VALUE) + return PyErr_SetFromWindowsErr(GetLastError()); + + if (! handle) { + Py_INCREF(Py_None); + return Py_None; + } - /* note: returns integer, not handle object */ - return HANDLE_TO_PYNUM(handle); + /* note: returns integer, not handle object */ + return HANDLE_TO_PYNUM(handle); } PyDoc_STRVAR(GetCurrentProcess_doc, @@ -198,10 +198,10 @@ static PyObject * sp_GetCurrentProcess(PyObject* self, PyObject* args) { - if (! PyArg_ParseTuple(args, ":GetCurrentProcess")) - return NULL; + if (! PyArg_ParseTuple(args, ":GetCurrentProcess")) + return NULL; - return sp_handle_new(GetCurrentProcess()); + return sp_handle_new(GetCurrentProcess()); } PyDoc_STRVAR(DuplicateHandle_doc, @@ -218,43 +218,43 @@ static PyObject * sp_DuplicateHandle(PyObject* self, PyObject* args) { - HANDLE target_handle; - BOOL result; + HANDLE target_handle; + BOOL result; - HANDLE source_process_handle; - HANDLE source_handle; - HANDLE target_process_handle; - int desired_access; - int inherit_handle; - int options = 0; - - if (! PyArg_ParseTuple(args, - PY_HANDLE_PARAM PY_HANDLE_PARAM PY_HANDLE_PARAM - "ii|i:DuplicateHandle", - &source_process_handle, - &source_handle, - &target_process_handle, - &desired_access, - &inherit_handle, - &options)) - return NULL; - - Py_BEGIN_ALLOW_THREADS - result = DuplicateHandle( - source_process_handle, - source_handle, - target_process_handle, - &target_handle, - desired_access, - inherit_handle, - options - ); - Py_END_ALLOW_THREADS + HANDLE source_process_handle; + HANDLE source_handle; + HANDLE target_process_handle; + int desired_access; + int inherit_handle; + int options = 0; + + if (! PyArg_ParseTuple(args, + PY_HANDLE_PARAM PY_HANDLE_PARAM PY_HANDLE_PARAM + "ii|i:DuplicateHandle", + &source_process_handle, + &source_handle, + &target_process_handle, + &desired_access, + &inherit_handle, + &options)) + return NULL; + + Py_BEGIN_ALLOW_THREADS + result = DuplicateHandle( + source_process_handle, + source_handle, + target_process_handle, + &target_handle, + desired_access, + inherit_handle, + options + ); + Py_END_ALLOW_THREADS - if (! result) - return PyErr_SetFromWindowsErr(GetLastError()); + if (! result) + return PyErr_SetFromWindowsErr(GetLastError()); - return sp_handle_new(target_handle); + return sp_handle_new(target_handle); } PyDoc_STRVAR(CreatePipe_doc, @@ -268,25 +268,25 @@ static PyObject * sp_CreatePipe(PyObject* self, PyObject* args) { - HANDLE read_pipe; - HANDLE write_pipe; - BOOL result; + HANDLE read_pipe; + HANDLE write_pipe; + BOOL result; - PyObject* pipe_attributes; /* ignored */ - int size; + PyObject* pipe_attributes; /* ignored */ + int size; - if (! PyArg_ParseTuple(args, "Oi:CreatePipe", &pipe_attributes, &size)) - return NULL; + if (! PyArg_ParseTuple(args, "Oi:CreatePipe", &pipe_attributes, &size)) + return NULL; - Py_BEGIN_ALLOW_THREADS - result = CreatePipe(&read_pipe, &write_pipe, NULL, size); - Py_END_ALLOW_THREADS + Py_BEGIN_ALLOW_THREADS + result = CreatePipe(&read_pipe, &write_pipe, NULL, size); + Py_END_ALLOW_THREADS - if (! result) - return PyErr_SetFromWindowsErr(GetLastError()); + if (! result) + return PyErr_SetFromWindowsErr(GetLastError()); - return Py_BuildValue( - "NN", sp_handle_new(read_pipe), sp_handle_new(write_pipe)); + return Py_BuildValue( + "NN", sp_handle_new(read_pipe), sp_handle_new(write_pipe)); } /* helpers for createprocess */ @@ -294,110 +294,110 @@ static int getint(PyObject* obj, char* name) { - PyObject* value; - int ret; + PyObject* value; + int ret; - value = PyObject_GetAttrString(obj, name); - if (! value) { - PyErr_Clear(); /* FIXME: propagate error? */ - return 0; - } - ret = (int) PyLong_AsLong(value); - Py_DECREF(value); - return ret; + value = PyObject_GetAttrString(obj, name); + if (! value) { + PyErr_Clear(); /* FIXME: propagate error? */ + return 0; + } + ret = (int) PyLong_AsLong(value); + Py_DECREF(value); + return ret; } static HANDLE gethandle(PyObject* obj, char* name) { - sp_handle_object* value; - HANDLE ret; + sp_handle_object* value; + HANDLE ret; - value = (sp_handle_object*) PyObject_GetAttrString(obj, name); - if (! value) { - PyErr_Clear(); /* FIXME: propagate error? */ - return NULL; - } - if (Py_TYPE(value) != &sp_handle_type) - ret = NULL; - else - ret = value->handle; - Py_DECREF(value); - return ret; + value = (sp_handle_object*) PyObject_GetAttrString(obj, name); + if (! value) { + PyErr_Clear(); /* FIXME: propagate error? */ + return NULL; + } + if (Py_TYPE(value) != &sp_handle_type) + ret = NULL; + else + ret = value->handle; + Py_DECREF(value); + return ret; } static PyObject* getenvironment(PyObject* environment) { - int i, envsize; - PyObject* out = NULL; - PyObject* keys; - PyObject* values; - Py_UNICODE* p; - - /* convert environment dictionary to windows enviroment string */ - if (! PyMapping_Check(environment)) { - PyErr_SetString( - PyExc_TypeError, "environment must be dictionary or None"); - return NULL; - } - - envsize = PyMapping_Length(environment); - - keys = PyMapping_Keys(environment); - values = PyMapping_Values(environment); - if (!keys || !values) - goto error; - - out = PyUnicode_FromUnicode(NULL, 2048); - if (! out) - goto error; - - p = PyUnicode_AS_UNICODE(out); - - for (i = 0; i < envsize; i++) { - int ksize, vsize, totalsize; - PyObject* key = PyList_GET_ITEM(keys, i); - PyObject* value = PyList_GET_ITEM(values, i); - - if (! PyUnicode_Check(key) || ! PyUnicode_Check(value)) { - PyErr_SetString(PyExc_TypeError, - "environment can only contain strings"); - goto error; - } - ksize = PyUnicode_GET_SIZE(key); - vsize = PyUnicode_GET_SIZE(value); - totalsize = (p - PyUnicode_AS_UNICODE(out)) + ksize + 1 + - vsize + 1 + 1; - if (totalsize > PyUnicode_GET_SIZE(out)) { - int offset = p - PyUnicode_AS_UNICODE(out); - PyUnicode_Resize(&out, totalsize + 1024); - p = PyUnicode_AS_UNICODE(out) + offset; - } - Py_UNICODE_COPY(p, PyUnicode_AS_UNICODE(key), ksize); - p += ksize; - *p++ = '='; - Py_UNICODE_COPY(p, PyUnicode_AS_UNICODE(value), vsize); - p += vsize; - *p++ = '\0'; - } - - /* add trailing null byte */ - *p++ = '\0'; - PyUnicode_Resize(&out, p - PyUnicode_AS_UNICODE(out)); + int i, envsize; + PyObject* out = NULL; + PyObject* keys; + PyObject* values; + Py_UNICODE* p; + + /* convert environment dictionary to windows enviroment string */ + if (! PyMapping_Check(environment)) { + PyErr_SetString( + PyExc_TypeError, "environment must be dictionary or None"); + return NULL; + } + + envsize = PyMapping_Length(environment); + + keys = PyMapping_Keys(environment); + values = PyMapping_Values(environment); + if (!keys || !values) + goto error; + + out = PyUnicode_FromUnicode(NULL, 2048); + if (! out) + goto error; + + p = PyUnicode_AS_UNICODE(out); + + for (i = 0; i < envsize; i++) { + int ksize, vsize, totalsize; + PyObject* key = PyList_GET_ITEM(keys, i); + PyObject* value = PyList_GET_ITEM(values, i); + + if (! PyUnicode_Check(key) || ! PyUnicode_Check(value)) { + PyErr_SetString(PyExc_TypeError, + "environment can only contain strings"); + goto error; + } + ksize = PyUnicode_GET_SIZE(key); + vsize = PyUnicode_GET_SIZE(value); + totalsize = (p - PyUnicode_AS_UNICODE(out)) + ksize + 1 + + vsize + 1 + 1; + if (totalsize > PyUnicode_GET_SIZE(out)) { + int offset = p - PyUnicode_AS_UNICODE(out); + PyUnicode_Resize(&out, totalsize + 1024); + p = PyUnicode_AS_UNICODE(out) + offset; + } + Py_UNICODE_COPY(p, PyUnicode_AS_UNICODE(key), ksize); + p += ksize; + *p++ = '='; + Py_UNICODE_COPY(p, PyUnicode_AS_UNICODE(value), vsize); + p += vsize; + *p++ = '\0'; + } + + /* add trailing null byte */ + *p++ = '\0'; + PyUnicode_Resize(&out, p - PyUnicode_AS_UNICODE(out)); - /* PyObject_Print(out, stdout, 0); */ + /* PyObject_Print(out, stdout, 0); */ - Py_XDECREF(keys); - Py_XDECREF(values); + Py_XDECREF(keys); + Py_XDECREF(values); - return out; + return out; error: - Py_XDECREF(out); - Py_XDECREF(keys); - Py_XDECREF(values); - return NULL; + Py_XDECREF(out); + Py_XDECREF(keys); + Py_XDECREF(values); + return NULL; } PyDoc_STRVAR(CreateProcess_doc, @@ -415,77 +415,77 @@ static PyObject * sp_CreateProcess(PyObject* self, PyObject* args) { - BOOL result; - PROCESS_INFORMATION pi; - STARTUPINFOW si; - PyObject* environment; - - Py_UNICODE* application_name; - Py_UNICODE* command_line; - PyObject* process_attributes; /* ignored */ - PyObject* thread_attributes; /* ignored */ - int inherit_handles; - int creation_flags; - PyObject* env_mapping; - Py_UNICODE* current_directory; - PyObject* startup_info; - - if (! PyArg_ParseTuple(args, "ZZOOiiOZO:CreateProcess", - &application_name, - &command_line, - &process_attributes, - &thread_attributes, - &inherit_handles, - &creation_flags, - &env_mapping, - ¤t_directory, - &startup_info)) - return NULL; - - ZeroMemory(&si, sizeof(si)); - si.cb = sizeof(si); - - /* note: we only support a small subset of all SI attributes */ - si.dwFlags = getint(startup_info, "dwFlags"); - si.wShowWindow = getint(startup_info, "wShowWindow"); - si.hStdInput = gethandle(startup_info, "hStdInput"); - si.hStdOutput = gethandle(startup_info, "hStdOutput"); - si.hStdError = gethandle(startup_info, "hStdError"); - - if (PyErr_Occurred()) - return NULL; - - if (env_mapping == Py_None) - environment = NULL; - else { - environment = getenvironment(env_mapping); - if (! environment) - return NULL; - } - - Py_BEGIN_ALLOW_THREADS - result = CreateProcessW(application_name, - command_line, - NULL, - NULL, - inherit_handles, - creation_flags | CREATE_UNICODE_ENVIRONMENT, - environment ? PyUnicode_AS_UNICODE(environment) : NULL, - current_directory, - &si, - &pi); - Py_END_ALLOW_THREADS - - Py_XDECREF(environment); - - if (! result) - return PyErr_SetFromWindowsErr(GetLastError()); - - return Py_BuildValue("NNii", - sp_handle_new(pi.hProcess), - sp_handle_new(pi.hThread), - pi.dwProcessId, - pi.dwThreadId); + BOOL result; + PROCESS_INFORMATION pi; + STARTUPINFOW si; + PyObject* environment; + + Py_UNICODE* application_name; + Py_UNICODE* command_line; + PyObject* process_attributes; /* ignored */ + PyObject* thread_attributes; /* ignored */ + int inherit_handles; + int creation_flags; + PyObject* env_mapping; + Py_UNICODE* current_directory; + PyObject* startup_info; + + if (! PyArg_ParseTuple(args, "ZZOOiiOZO:CreateProcess", + &application_name, + &command_line, + &process_attributes, + &thread_attributes, + &inherit_handles, + &creation_flags, + &env_mapping, + ¤t_directory, + &startup_info)) + return NULL; + + ZeroMemory(&si, sizeof(si)); + si.cb = sizeof(si); + + /* note: we only support a small subset of all SI attributes */ + si.dwFlags = getint(startup_info, "dwFlags"); + si.wShowWindow = getint(startup_info, "wShowWindow"); + si.hStdInput = gethandle(startup_info, "hStdInput"); + si.hStdOutput = gethandle(startup_info, "hStdOutput"); + si.hStdError = gethandle(startup_info, "hStdError"); + + if (PyErr_Occurred()) + return NULL; + + if (env_mapping == Py_None) + environment = NULL; + else { + environment = getenvironment(env_mapping); + if (! environment) + return NULL; + } + + Py_BEGIN_ALLOW_THREADS + result = CreateProcessW(application_name, + command_line, + NULL, + NULL, + inherit_handles, + creation_flags | CREATE_UNICODE_ENVIRONMENT, + environment ? PyUnicode_AS_UNICODE(environment) : NULL, + current_directory, + &si, + &pi); + Py_END_ALLOW_THREADS + + Py_XDECREF(environment); + + if (! result) + return PyErr_SetFromWindowsErr(GetLastError()); + + return Py_BuildValue("NNii", + sp_handle_new(pi.hProcess), + sp_handle_new(pi.hThread), + pi.dwProcessId, + pi.dwThreadId); } PyDoc_STRVAR(TerminateProcess_doc, @@ -496,21 +496,21 @@ static PyObject * sp_TerminateProcess(PyObject* self, PyObject* args) { - BOOL result; + BOOL result; - HANDLE process; - int exit_code; - if (! PyArg_ParseTuple(args, PY_HANDLE_PARAM "i:TerminateProcess", - &process, &exit_code)) - return NULL; + HANDLE process; + int exit_code; + if (! PyArg_ParseTuple(args, PY_HANDLE_PARAM "i:TerminateProcess", + &process, &exit_code)) + return NULL; - result = TerminateProcess(process, exit_code); + result = TerminateProcess(process, exit_code); - if (! result) - return PyErr_SetFromWindowsErr(GetLastError()); + if (! result) + return PyErr_SetFromWindowsErr(GetLastError()); - Py_INCREF(Py_None); - return Py_None; + Py_INCREF(Py_None); + return Py_None; } PyDoc_STRVAR(GetExitCodeProcess_doc, @@ -521,19 +521,19 @@ static PyObject * sp_GetExitCodeProcess(PyObject* self, PyObject* args) { - DWORD exit_code; - BOOL result; + DWORD exit_code; + BOOL result; - HANDLE process; - if (! PyArg_ParseTuple(args, PY_HANDLE_PARAM ":GetExitCodeProcess", &process)) - return NULL; + HANDLE process; + if (! PyArg_ParseTuple(args, PY_HANDLE_PARAM ":GetExitCodeProcess", &process)) + return NULL; - result = GetExitCodeProcess(process, &exit_code); + result = GetExitCodeProcess(process, &exit_code); - if (! result) - return PyErr_SetFromWindowsErr(GetLastError()); + if (! result) + return PyErr_SetFromWindowsErr(GetLastError()); - return PyLong_FromLong(exit_code); + return PyLong_FromLong(exit_code); } PyDoc_STRVAR(WaitForSingleObject_doc, @@ -546,23 +546,23 @@ static PyObject * sp_WaitForSingleObject(PyObject* self, PyObject* args) { - DWORD result; + DWORD result; - HANDLE handle; - int milliseconds; - if (! PyArg_ParseTuple(args, PY_HANDLE_PARAM "i:WaitForSingleObject", - &handle, - &milliseconds)) - return NULL; - - Py_BEGIN_ALLOW_THREADS - result = WaitForSingleObject(handle, (DWORD) milliseconds); - Py_END_ALLOW_THREADS + HANDLE handle; + int milliseconds; + if (! PyArg_ParseTuple(args, PY_HANDLE_PARAM "i:WaitForSingleObject", + &handle, + &milliseconds)) + return NULL; + + Py_BEGIN_ALLOW_THREADS + result = WaitForSingleObject(handle, (DWORD) milliseconds); + Py_END_ALLOW_THREADS - if (result == WAIT_FAILED) - return PyErr_SetFromWindowsErr(GetLastError()); + if (result == WAIT_FAILED) + return PyErr_SetFromWindowsErr(GetLastError()); - return PyLong_FromLong((int) result); + return PyLong_FromLong((int) result); } PyDoc_STRVAR(GetVersion_doc, @@ -573,10 +573,10 @@ static PyObject * sp_GetVersion(PyObject* self, PyObject* args) { - if (! PyArg_ParseTuple(args, ":GetVersion")) - return NULL; + if (! PyArg_ParseTuple(args, ":GetVersion")) + return NULL; - return PyLong_FromLong((int) GetVersion()); + return PyLong_FromLong((int) GetVersion()); } PyDoc_STRVAR(GetModuleFileName_doc, @@ -594,41 +594,41 @@ static PyObject * sp_GetModuleFileName(PyObject* self, PyObject* args) { - BOOL result; - HMODULE module; - WCHAR filename[MAX_PATH]; + BOOL result; + HMODULE module; + WCHAR filename[MAX_PATH]; - if (! PyArg_ParseTuple(args, PY_HANDLE_PARAM ":GetModuleFileName", - &module)) - return NULL; + if (! PyArg_ParseTuple(args, PY_HANDLE_PARAM ":GetModuleFileName", + &module)) + return NULL; - result = GetModuleFileNameW(module, filename, MAX_PATH); - filename[MAX_PATH-1] = '\0'; + result = GetModuleFileNameW(module, filename, MAX_PATH); + filename[MAX_PATH-1] = '\0'; - if (! result) - return PyErr_SetFromWindowsErr(GetLastError()); + if (! result) + return PyErr_SetFromWindowsErr(GetLastError()); - return PyUnicode_FromUnicode(filename, Py_UNICODE_strlen(filename)); + return PyUnicode_FromUnicode(filename, Py_UNICODE_strlen(filename)); } static PyMethodDef sp_functions[] = { - {"GetStdHandle", sp_GetStdHandle, METH_VARARGS, GetStdHandle_doc}, - {"GetCurrentProcess", sp_GetCurrentProcess, METH_VARARGS, - GetCurrentProcess_doc}, - {"DuplicateHandle", sp_DuplicateHandle, METH_VARARGS, - DuplicateHandle_doc}, - {"CreatePipe", sp_CreatePipe, METH_VARARGS, CreatePipe_doc}, - {"CreateProcess", sp_CreateProcess, METH_VARARGS, CreateProcess_doc}, - {"TerminateProcess", sp_TerminateProcess, METH_VARARGS, - TerminateProcess_doc}, - {"GetExitCodeProcess", sp_GetExitCodeProcess, METH_VARARGS, - GetExitCodeProcess_doc}, - {"WaitForSingleObject", sp_WaitForSingleObject, METH_VARARGS, - WaitForSingleObject_doc}, - {"GetVersion", sp_GetVersion, METH_VARARGS, GetVersion_doc}, - {"GetModuleFileName", sp_GetModuleFileName, METH_VARARGS, - GetModuleFileName_doc}, - {NULL, NULL} + {"GetStdHandle", sp_GetStdHandle, METH_VARARGS, GetStdHandle_doc}, + {"GetCurrentProcess", sp_GetCurrentProcess, METH_VARARGS, + GetCurrentProcess_doc}, + {"DuplicateHandle", sp_DuplicateHandle, METH_VARARGS, + DuplicateHandle_doc}, + {"CreatePipe", sp_CreatePipe, METH_VARARGS, CreatePipe_doc}, + {"CreateProcess", sp_CreateProcess, METH_VARARGS, CreateProcess_doc}, + {"TerminateProcess", sp_TerminateProcess, METH_VARARGS, + TerminateProcess_doc}, + {"GetExitCodeProcess", sp_GetExitCodeProcess, METH_VARARGS, + GetExitCodeProcess_doc}, + {"WaitForSingleObject", sp_WaitForSingleObject, METH_VARARGS, + WaitForSingleObject_doc}, + {"GetVersion", sp_GetVersion, METH_VARARGS, GetVersion_doc}, + {"GetModuleFileName", sp_GetModuleFileName, METH_VARARGS, + GetModuleFileName_doc}, + {NULL, NULL} }; /* -------------------------------------------------------------------- */ @@ -636,53 +636,53 @@ static void defint(PyObject* d, const char* name, int value) { - PyObject* v = PyLong_FromLong((long) value); - if (v) { - PyDict_SetItemString(d, (char*) name, v); - Py_DECREF(v); - } + PyObject* v = PyLong_FromLong((long) value); + if (v) { + PyDict_SetItemString(d, (char*) name, v); + Py_DECREF(v); + } } static struct PyModuleDef _subprocessmodule = { - PyModuleDef_HEAD_INIT, - "_subprocess", - NULL, - -1, - sp_functions, - NULL, - NULL, - NULL, - NULL + PyModuleDef_HEAD_INIT, + "_subprocess", + NULL, + -1, + sp_functions, + NULL, + NULL, + NULL, + NULL }; PyMODINIT_FUNC PyInit__subprocess() { - PyObject *d; - PyObject *m; + PyObject *d; + PyObject *m; - /* patch up object descriptors */ - sp_handle_as_number.nb_int = (unaryfunc) sp_handle_as_int; - if (PyType_Ready(&sp_handle_type) < 0) - return NULL; - - m = PyModule_Create(&_subprocessmodule); - if (m == NULL) - return NULL; - d = PyModule_GetDict(m); - - /* constants */ - defint(d, "STD_INPUT_HANDLE", STD_INPUT_HANDLE); - defint(d, "STD_OUTPUT_HANDLE", STD_OUTPUT_HANDLE); - defint(d, "STD_ERROR_HANDLE", STD_ERROR_HANDLE); - defint(d, "DUPLICATE_SAME_ACCESS", DUPLICATE_SAME_ACCESS); - defint(d, "STARTF_USESTDHANDLES", STARTF_USESTDHANDLES); - defint(d, "STARTF_USESHOWWINDOW", STARTF_USESHOWWINDOW); - defint(d, "SW_HIDE", SW_HIDE); - defint(d, "INFINITE", INFINITE); - defint(d, "WAIT_OBJECT_0", WAIT_OBJECT_0); - defint(d, "CREATE_NEW_CONSOLE", CREATE_NEW_CONSOLE); - defint(d, "CREATE_NEW_PROCESS_GROUP", CREATE_NEW_PROCESS_GROUP); + /* patch up object descriptors */ + sp_handle_as_number.nb_int = (unaryfunc) sp_handle_as_int; + if (PyType_Ready(&sp_handle_type) < 0) + return NULL; + + m = PyModule_Create(&_subprocessmodule); + if (m == NULL) + return NULL; + d = PyModule_GetDict(m); + + /* constants */ + defint(d, "STD_INPUT_HANDLE", STD_INPUT_HANDLE); + defint(d, "STD_OUTPUT_HANDLE", STD_OUTPUT_HANDLE); + defint(d, "STD_ERROR_HANDLE", STD_ERROR_HANDLE); + defint(d, "DUPLICATE_SAME_ACCESS", DUPLICATE_SAME_ACCESS); + defint(d, "STARTF_USESTDHANDLES", STARTF_USESTDHANDLES); + defint(d, "STARTF_USESHOWWINDOW", STARTF_USESHOWWINDOW); + defint(d, "SW_HIDE", SW_HIDE); + defint(d, "INFINITE", INFINITE); + defint(d, "WAIT_OBJECT_0", WAIT_OBJECT_0); + defint(d, "CREATE_NEW_CONSOLE", CREATE_NEW_CONSOLE); + defint(d, "CREATE_NEW_PROCESS_GROUP", CREATE_NEW_PROCESS_GROUP); - return m; + return m; } Modified: python/branches/py3k/PC/bdist_wininst/archive.h ============================================================================== --- python/branches/py3k/PC/bdist_wininst/archive.h (original) +++ python/branches/py3k/PC/bdist_wininst/archive.h Sun May 9 17:52:27 2010 @@ -14,55 +14,55 @@ */ struct eof_cdir { - long tag; /* must be 0x06054b50 */ - short disknum; - short firstdisk; - short nTotalCDirThis; - short nTotalCDir; - long nBytesCDir; - long ofsCDir; - short commentlen; + long tag; /* must be 0x06054b50 */ + short disknum; + short firstdisk; + short nTotalCDirThis; + short nTotalCDir; + long nBytesCDir; + long ofsCDir; + short commentlen; }; struct cdir { - long tag; /* must be 0x02014b50 */ - short version_made; - short version_extract; - short gp_bitflag; - short comp_method; - short last_mod_file_time; - short last_mod_file_date; - long crc32; - long comp_size; - long uncomp_size; - short fname_length; - short extra_length; - short comment_length; - short disknum_start; - short int_file_attr; - long ext_file_attr; - long ofs_local_header; + long tag; /* must be 0x02014b50 */ + short version_made; + short version_extract; + short gp_bitflag; + short comp_method; + short last_mod_file_time; + short last_mod_file_date; + long crc32; + long comp_size; + long uncomp_size; + short fname_length; + short extra_length; + short comment_length; + short disknum_start; + short int_file_attr; + long ext_file_attr; + long ofs_local_header; }; struct fhdr { - long tag; /* must be 0x04034b50 */ - short version_needed; - short flags; - short method; - short last_mod_file_time; - short last_mod_file_date; - long crc32; - long comp_size; - long uncomp_size; - short fname_length; - short extra_length; + long tag; /* must be 0x04034b50 */ + short version_needed; + short flags; + short method; + short last_mod_file_time; + short last_mod_file_date; + long crc32; + long comp_size; + long uncomp_size; + short fname_length; + short extra_length; }; struct meta_data_hdr { - int tag; - int uncomp_size; - int bitmap_size; + int tag; + int uncomp_size; + int bitmap_size; }; #pragma pack() @@ -70,29 +70,29 @@ /* installation scheme */ typedef struct tagSCHEME { - char *name; - char *prefix; + char *name; + char *prefix; } SCHEME; typedef int (*NOTIFYPROC)(int code, LPSTR text, ...); extern BOOL extract_file(char *dst, char *src, int method, int comp_size, - int uncomp_size, NOTIFYPROC notify); + int uncomp_size, NOTIFYPROC notify); extern BOOL unzip_archive(SCHEME *scheme, char *dirname, char *data, - DWORD size, NOTIFYPROC notify); + DWORD size, NOTIFYPROC notify); extern char * map_new_file(DWORD flags, char *filename, char - *pathname_part, int size, - WORD wFatDate, WORD wFatTime, - NOTIFYPROC callback); + *pathname_part, int size, + WORD wFatDate, WORD wFatTime, + NOTIFYPROC callback); extern BOOL ensure_directory (char *pathname, char *new_part, - NOTIFYPROC callback); + NOTIFYPROC callback); /* codes for NOITIFYPROC */ #define DIR_CREATED 1 Modified: python/branches/py3k/PC/bdist_wininst/extract.c ============================================================================== --- python/branches/py3k/PC/bdist_wininst/extract.c (original) +++ python/branches/py3k/PC/bdist_wininst/extract.c Sun May 9 17:52:27 2010 @@ -19,181 +19,181 @@ /* Convert unix-path to dos-path */ static void normpath(char *path) { - while (path && *path) { - if (*path == '/') - *path = '\\'; - ++path; - } + while (path && *path) { + if (*path == '/') + *path = '\\'; + ++path; + } } BOOL ensure_directory(char *pathname, char *new_part, NOTIFYPROC notify) { - while (new_part && *new_part && (new_part = strchr(new_part, '\\'))) { - DWORD attr; - *new_part = '\0'; - attr = GetFileAttributes(pathname); - if (attr == -1) { - /* nothing found */ - if (!CreateDirectory(pathname, NULL) && notify) - notify(SYSTEM_ERROR, - "CreateDirectory (%s)", pathname); - else - notify(DIR_CREATED, pathname); - } - if (attr & FILE_ATTRIBUTE_DIRECTORY) { - ; - } else { - SetLastError(183); - if (notify) - notify(SYSTEM_ERROR, - "CreateDirectory (%s)", pathname); - } - *new_part = '\\'; - ++new_part; - } - return TRUE; + while (new_part && *new_part && (new_part = strchr(new_part, '\\'))) { + DWORD attr; + *new_part = '\0'; + attr = GetFileAttributes(pathname); + if (attr == -1) { + /* nothing found */ + if (!CreateDirectory(pathname, NULL) && notify) + notify(SYSTEM_ERROR, + "CreateDirectory (%s)", pathname); + else + notify(DIR_CREATED, pathname); + } + if (attr & FILE_ATTRIBUTE_DIRECTORY) { + ; + } else { + SetLastError(183); + if (notify) + notify(SYSTEM_ERROR, + "CreateDirectory (%s)", pathname); + } + *new_part = '\\'; + ++new_part; + } + return TRUE; } /* XXX Should better explicitely specify * uncomp_size and file_times instead of pfhdr! */ char *map_new_file(DWORD flags, char *filename, - char *pathname_part, int size, - WORD wFatDate, WORD wFatTime, - NOTIFYPROC notify) + char *pathname_part, int size, + WORD wFatDate, WORD wFatTime, + NOTIFYPROC notify) { - HANDLE hFile, hFileMapping; - char *dst; - FILETIME ft; + HANDLE hFile, hFileMapping; + char *dst; + FILETIME ft; try_again: - if (!flags) - flags = CREATE_NEW; - hFile = CreateFile(filename, - GENERIC_WRITE | GENERIC_READ, - 0, NULL, - flags, - FILE_ATTRIBUTE_NORMAL, NULL); - if (hFile == INVALID_HANDLE_VALUE) { - DWORD x = GetLastError(); - switch (x) { - case ERROR_FILE_EXISTS: - if (notify && notify(CAN_OVERWRITE, filename)) - hFile = CreateFile(filename, - GENERIC_WRITE|GENERIC_READ, - 0, NULL, - CREATE_ALWAYS, - FILE_ATTRIBUTE_NORMAL, - NULL); - else { - if (notify) - notify(FILE_OVERWRITTEN, filename); - return NULL; - } - break; - case ERROR_PATH_NOT_FOUND: - if (ensure_directory(filename, pathname_part, notify)) - goto try_again; - else - return FALSE; - break; - default: - SetLastError(x); - break; - } - } - if (hFile == INVALID_HANDLE_VALUE) { - if (notify) - notify (SYSTEM_ERROR, "CreateFile (%s)", filename); - return NULL; - } - - if (notify) - notify(FILE_CREATED, filename); - - DosDateTimeToFileTime(wFatDate, wFatTime, &ft); - SetFileTime(hFile, &ft, &ft, &ft); - - - if (size == 0) { - /* We cannot map a zero-length file (Also it makes - no sense */ - CloseHandle(hFile); - return NULL; - } - - hFileMapping = CreateFileMapping(hFile, - NULL, PAGE_READWRITE, 0, size, NULL); - - CloseHandle(hFile); - - if (hFileMapping == INVALID_HANDLE_VALUE) { - if (notify) - notify(SYSTEM_ERROR, - "CreateFileMapping (%s)", filename); - return NULL; - } - - dst = MapViewOfFile(hFileMapping, - FILE_MAP_WRITE, 0, 0, 0); - - CloseHandle(hFileMapping); - - if (!dst) { - if (notify) - notify(SYSTEM_ERROR, "MapViewOfFile (%s)", filename); - return NULL; - } - return dst; + if (!flags) + flags = CREATE_NEW; + hFile = CreateFile(filename, + GENERIC_WRITE | GENERIC_READ, + 0, NULL, + flags, + FILE_ATTRIBUTE_NORMAL, NULL); + if (hFile == INVALID_HANDLE_VALUE) { + DWORD x = GetLastError(); + switch (x) { + case ERROR_FILE_EXISTS: + if (notify && notify(CAN_OVERWRITE, filename)) + hFile = CreateFile(filename, + GENERIC_WRITE|GENERIC_READ, + 0, NULL, + CREATE_ALWAYS, + FILE_ATTRIBUTE_NORMAL, + NULL); + else { + if (notify) + notify(FILE_OVERWRITTEN, filename); + return NULL; + } + break; + case ERROR_PATH_NOT_FOUND: + if (ensure_directory(filename, pathname_part, notify)) + goto try_again; + else + return FALSE; + break; + default: + SetLastError(x); + break; + } + } + if (hFile == INVALID_HANDLE_VALUE) { + if (notify) + notify (SYSTEM_ERROR, "CreateFile (%s)", filename); + return NULL; + } + + if (notify) + notify(FILE_CREATED, filename); + + DosDateTimeToFileTime(wFatDate, wFatTime, &ft); + SetFileTime(hFile, &ft, &ft, &ft); + + + if (size == 0) { + /* We cannot map a zero-length file (Also it makes + no sense */ + CloseHandle(hFile); + return NULL; + } + + hFileMapping = CreateFileMapping(hFile, + NULL, PAGE_READWRITE, 0, size, NULL); + + CloseHandle(hFile); + + if (hFileMapping == INVALID_HANDLE_VALUE) { + if (notify) + notify(SYSTEM_ERROR, + "CreateFileMapping (%s)", filename); + return NULL; + } + + dst = MapViewOfFile(hFileMapping, + FILE_MAP_WRITE, 0, 0, 0); + + CloseHandle(hFileMapping); + + if (!dst) { + if (notify) + notify(SYSTEM_ERROR, "MapViewOfFile (%s)", filename); + return NULL; + } + return dst; } BOOL extract_file(char *dst, char *src, int method, int comp_size, - int uncomp_size, NOTIFYPROC notify) + int uncomp_size, NOTIFYPROC notify) { - z_stream zstream; - int result; + z_stream zstream; + int result; - if (method == Z_DEFLATED) { - int x; - memset(&zstream, 0, sizeof(zstream)); - zstream.next_in = src; - zstream.avail_in = comp_size+1; - zstream.next_out = dst; - zstream.avail_out = uncomp_size; + if (method == Z_DEFLATED) { + int x; + memset(&zstream, 0, sizeof(zstream)); + zstream.next_in = src; + zstream.avail_in = comp_size+1; + zstream.next_out = dst; + zstream.avail_out = uncomp_size; /* Apparently an undocumented feature of zlib: Set windowsize to negative values to supress the gzip header and be compatible with zip! */ - result = TRUE; - if (Z_OK != (x = inflateInit2(&zstream, -15))) { - if (notify) - notify(ZLIB_ERROR, - "inflateInit2 returns %d", x); - result = FALSE; - goto cleanup; - } - if (Z_STREAM_END != (x = inflate(&zstream, Z_FINISH))) { - if (notify) - notify(ZLIB_ERROR, - "inflate returns %d", x); - result = FALSE; - } - cleanup: - if (Z_OK != (x = inflateEnd(&zstream))) { - if (notify) - notify (ZLIB_ERROR, - "inflateEnd returns %d", x); - result = FALSE; - } - } else if (method == 0) { - memcpy(dst, src, uncomp_size); - result = TRUE; - } else - result = FALSE; - UnmapViewOfFile(dst); - return result; + result = TRUE; + if (Z_OK != (x = inflateInit2(&zstream, -15))) { + if (notify) + notify(ZLIB_ERROR, + "inflateInit2 returns %d", x); + result = FALSE; + goto cleanup; + } + if (Z_STREAM_END != (x = inflate(&zstream, Z_FINISH))) { + if (notify) + notify(ZLIB_ERROR, + "inflate returns %d", x); + result = FALSE; + } + cleanup: + if (Z_OK != (x = inflateEnd(&zstream))) { + if (notify) + notify (ZLIB_ERROR, + "inflateEnd returns %d", x); + result = FALSE; + } + } else if (method == 0) { + memcpy(dst, src, uncomp_size); + result = TRUE; + } else + result = FALSE; + UnmapViewOfFile(dst); + return result; } /* Open a zip-compatible archive and extract all files @@ -201,121 +201,121 @@ */ BOOL unzip_archive(SCHEME *scheme, char *dirname, char *data, DWORD size, - NOTIFYPROC notify) + NOTIFYPROC notify) { - int n; - char pathname[MAX_PATH]; - char *new_part; - - /* read the end of central directory record */ - struct eof_cdir *pe = (struct eof_cdir *)&data[size - sizeof - (struct eof_cdir)]; - - int arc_start = size - sizeof (struct eof_cdir) - pe->nBytesCDir - - pe->ofsCDir; - - /* set position to start of central directory */ - int pos = arc_start + pe->ofsCDir; - - /* make sure this is a zip file */ - if (pe->tag != 0x06054b50) - return FALSE; - - /* Loop through the central directory, reading all entries */ - for (n = 0; n < pe->nTotalCDir; ++n) { - int i; - char *fname; - char *pcomp; - char *dst; - struct cdir *pcdir; - struct fhdr *pfhdr; - - pcdir = (struct cdir *)&data[pos]; - pfhdr = (struct fhdr *)&data[pcdir->ofs_local_header + - arc_start]; - - if (pcdir->tag != 0x02014b50) - return FALSE; - if (pfhdr->tag != 0x04034b50) - return FALSE; - pos += sizeof(struct cdir); - fname = (char *)&data[pos]; /* This is not null terminated! */ - pos += pcdir->fname_length + pcdir->extra_length + - pcdir->comment_length; - - pcomp = &data[pcdir->ofs_local_header - + sizeof(struct fhdr) - + arc_start - + pfhdr->fname_length - + pfhdr->extra_length]; - - /* dirname is the Python home directory (prefix) */ - strcpy(pathname, dirname); - if (pathname[strlen(pathname)-1] != '\\') - strcat(pathname, "\\"); - new_part = &pathname[lstrlen(pathname)]; - /* we must now match the first part of the pathname - * in the archive to a component in the installation - * scheme (PURELIB, PLATLIB, HEADERS, SCRIPTS, or DATA) - * and replace this part by the one in the scheme to use - */ - for (i = 0; scheme[i].name; ++i) { - if (0 == strnicmp(scheme[i].name, fname, - strlen(scheme[i].name))) { - char *rest; - int len; - - /* length of the replaced part */ - int namelen = strlen(scheme[i].name); - - strcat(pathname, scheme[i].prefix); - - rest = fname + namelen; - len = pfhdr->fname_length - namelen; - - if ((pathname[strlen(pathname)-1] != '\\') - && (pathname[strlen(pathname)-1] != '/')) - strcat(pathname, "\\"); - /* Now that pathname ends with a separator, - * we must make sure rest does not start with - * an additional one. - */ - if ((rest[0] == '\\') || (rest[0] == '/')) { - ++rest; - --len; - } - - strncat(pathname, rest, len); - goto Done; - } - } - /* no prefix to replace found, go unchanged */ - strncat(pathname, fname, pfhdr->fname_length); - Done: - normpath(pathname); - if (pathname[strlen(pathname)-1] != '\\') { - /* - * The local file header (pfhdr) does not always - * contain the compressed and uncompressed sizes of - * the data depending on bit 3 of the flags field. So - * it seems better to use the data from the central - * directory (pcdir). - */ - dst = map_new_file(0, pathname, new_part, - pcdir->uncomp_size, - pcdir->last_mod_file_date, - pcdir->last_mod_file_time, notify); - if (dst) { - if (!extract_file(dst, pcomp, pfhdr->method, - pcdir->comp_size, - pcdir->uncomp_size, - notify)) - return FALSE; - } /* else ??? */ - } - if (notify) - notify(NUM_FILES, new_part, (int)pe->nTotalCDir, - (int)n+1); - } - return TRUE; + int n; + char pathname[MAX_PATH]; + char *new_part; + + /* read the end of central directory record */ + struct eof_cdir *pe = (struct eof_cdir *)&data[size - sizeof + (struct eof_cdir)]; + + int arc_start = size - sizeof (struct eof_cdir) - pe->nBytesCDir - + pe->ofsCDir; + + /* set position to start of central directory */ + int pos = arc_start + pe->ofsCDir; + + /* make sure this is a zip file */ + if (pe->tag != 0x06054b50) + return FALSE; + + /* Loop through the central directory, reading all entries */ + for (n = 0; n < pe->nTotalCDir; ++n) { + int i; + char *fname; + char *pcomp; + char *dst; + struct cdir *pcdir; + struct fhdr *pfhdr; + + pcdir = (struct cdir *)&data[pos]; + pfhdr = (struct fhdr *)&data[pcdir->ofs_local_header + + arc_start]; + + if (pcdir->tag != 0x02014b50) + return FALSE; + if (pfhdr->tag != 0x04034b50) + return FALSE; + pos += sizeof(struct cdir); + fname = (char *)&data[pos]; /* This is not null terminated! */ + pos += pcdir->fname_length + pcdir->extra_length + + pcdir->comment_length; + + pcomp = &data[pcdir->ofs_local_header + + sizeof(struct fhdr) + + arc_start + + pfhdr->fname_length + + pfhdr->extra_length]; + + /* dirname is the Python home directory (prefix) */ + strcpy(pathname, dirname); + if (pathname[strlen(pathname)-1] != '\\') + strcat(pathname, "\\"); + new_part = &pathname[lstrlen(pathname)]; + /* we must now match the first part of the pathname + * in the archive to a component in the installation + * scheme (PURELIB, PLATLIB, HEADERS, SCRIPTS, or DATA) + * and replace this part by the one in the scheme to use + */ + for (i = 0; scheme[i].name; ++i) { + if (0 == strnicmp(scheme[i].name, fname, + strlen(scheme[i].name))) { + char *rest; + int len; + + /* length of the replaced part */ + int namelen = strlen(scheme[i].name); + + strcat(pathname, scheme[i].prefix); + + rest = fname + namelen; + len = pfhdr->fname_length - namelen; + + if ((pathname[strlen(pathname)-1] != '\\') + && (pathname[strlen(pathname)-1] != '/')) + strcat(pathname, "\\"); + /* Now that pathname ends with a separator, + * we must make sure rest does not start with + * an additional one. + */ + if ((rest[0] == '\\') || (rest[0] == '/')) { + ++rest; + --len; + } + + strncat(pathname, rest, len); + goto Done; + } + } + /* no prefix to replace found, go unchanged */ + strncat(pathname, fname, pfhdr->fname_length); + Done: + normpath(pathname); + if (pathname[strlen(pathname)-1] != '\\') { + /* + * The local file header (pfhdr) does not always + * contain the compressed and uncompressed sizes of + * the data depending on bit 3 of the flags field. So + * it seems better to use the data from the central + * directory (pcdir). + */ + dst = map_new_file(0, pathname, new_part, + pcdir->uncomp_size, + pcdir->last_mod_file_date, + pcdir->last_mod_file_time, notify); + if (dst) { + if (!extract_file(dst, pcomp, pfhdr->method, + pcdir->comp_size, + pcdir->uncomp_size, + notify)) + return FALSE; + } /* else ??? */ + } + if (notify) + notify(NUM_FILES, new_part, (int)pe->nTotalCDir, + (int)n+1); + } + return TRUE; } Modified: python/branches/py3k/PC/bdist_wininst/install.c ============================================================================== --- python/branches/py3k/PC/bdist_wininst/install.c (original) +++ python/branches/py3k/PC/bdist_wininst/install.c Sun May 9 17:52:27 2010 @@ -20,21 +20,21 @@ * * At runtime, the exefile has appended: * - compressed setup-data in ini-format, containing the following sections: - * [metadata] - * author=Greg Ward - * author_email=gward at python.net - * description=Python Distribution Utilities - * licence=Python - * name=Distutils - * url=http://www.python.org/sigs/distutils-sig/ - * version=0.9pre + * [metadata] + * author=Greg Ward + * author_email=gward at python.net + * description=Python Distribution Utilities + * licence=Python + * name=Distutils + * url=http://www.python.org/sigs/distutils-sig/ + * version=0.9pre * - * [Setup] - * info= text to be displayed in the edit-box - * title= to be displayed by this program - * target_version = if present, python version required - * pyc_compile = if 0, do not compile py to pyc - * pyo_compile = if 0, do not compile py to pyo + * [Setup] + * info= text to be displayed in the edit-box + * title= to be displayed by this program + * target_version = if present, python version required + * pyc_compile = if 0, do not compile py to pyc + * pyo_compile = if 0, do not compile py to pyo * * - a struct meta_data_hdr, describing the above * - a zip-file, containing the modules to be installed. @@ -119,28 +119,28 @@ HWND hwndMain; HWND hDialog; -char *ini_file; /* Full pathname of ini-file */ +char *ini_file; /* Full pathname of ini-file */ /* From ini-file */ -char info[4096]; /* [Setup] info= */ -char title[80]; /* [Setup] title=, contains package name - including version: "Distutils-1.0.1" */ -char target_version[10]; /* [Setup] target_version=, required python - version or empty string */ -char build_info[80]; /* [Setup] build_info=, distutils version - and build date */ +char info[4096]; /* [Setup] info= */ +char title[80]; /* [Setup] title=, contains package name + including version: "Distutils-1.0.1" */ +char target_version[10]; /* [Setup] target_version=, required python + version or empty string */ +char build_info[80]; /* [Setup] build_info=, distutils version + and build date */ -char meta_name[80]; /* package name without version like - 'Distutils' */ +char meta_name[80]; /* package name without version like + 'Distutils' */ char install_script[MAX_PATH]; char *pre_install_script; /* run before we install a single file */ char user_access_control[10]; // one of 'auto', 'force', otherwise none. -int py_major, py_minor; /* Python version selected for installation */ +int py_major, py_minor; /* Python version selected for installation */ -char *arc_data; /* memory mapped archive */ -DWORD arc_size; /* number of bytes in archive */ -int exe_size; /* number of bytes for exe-file portion */ +char *arc_data; /* memory mapped archive */ +DWORD arc_size; /* number of bytes in archive */ +int exe_size; /* number of bytes for exe-file portion */ char python_dir[MAX_PATH]; char pythondll[MAX_PATH]; BOOL pyc_compile, pyo_compile; @@ -148,7 +148,7 @@ the permissions of the current user. */ HKEY hkey_root = (HKEY)-1; -BOOL success; /* Installation successfull? */ +BOOL success; /* Installation successfull? */ char *failure_reason = NULL; HANDLE hBitmap; @@ -166,128 +166,128 @@ /* Note: If scheme.prefix is nonempty, it must end with a '\'! */ /* Note: purelib must be the FIRST entry! */ SCHEME old_scheme[] = { - { "PURELIB", "" }, - { "PLATLIB", "" }, - { "HEADERS", "" }, /* 'Include/dist_name' part already in archive */ - { "SCRIPTS", "Scripts\\" }, - { "DATA", "" }, - { NULL, NULL }, + { "PURELIB", "" }, + { "PLATLIB", "" }, + { "HEADERS", "" }, /* 'Include/dist_name' part already in archive */ + { "SCRIPTS", "Scripts\\" }, + { "DATA", "" }, + { NULL, NULL }, }; SCHEME new_scheme[] = { - { "PURELIB", "Lib\\site-packages\\" }, - { "PLATLIB", "Lib\\site-packages\\" }, - { "HEADERS", "" }, /* 'Include/dist_name' part already in archive */ - { "SCRIPTS", "Scripts\\" }, - { "DATA", "" }, - { NULL, NULL }, + { "PURELIB", "Lib\\site-packages\\" }, + { "PLATLIB", "Lib\\site-packages\\" }, + { "HEADERS", "" }, /* 'Include/dist_name' part already in archive */ + { "SCRIPTS", "Scripts\\" }, + { "DATA", "" }, + { NULL, NULL }, }; static void unescape(char *dst, char *src, unsigned size) { - char *eon; - char ch; + char *eon; + char ch; - while (src && *src && (size > 2)) { - if (*src == '\\') { - switch (*++src) { - case 'n': - ++src; - *dst++ = '\r'; - *dst++ = '\n'; - size -= 2; - break; - case 'r': - ++src; - *dst++ = '\r'; - --size; - break; - case '0': case '1': case '2': case '3': - ch = (char)strtol(src, &eon, 8); - if (ch == '\n') { - *dst++ = '\r'; - --size; - } - *dst++ = ch; - --size; - src = eon; - } - } else { - *dst++ = *src++; - --size; - } - } - *dst = '\0'; + while (src && *src && (size > 2)) { + if (*src == '\\') { + switch (*++src) { + case 'n': + ++src; + *dst++ = '\r'; + *dst++ = '\n'; + size -= 2; + break; + case 'r': + ++src; + *dst++ = '\r'; + --size; + break; + case '0': case '1': case '2': case '3': + ch = (char)strtol(src, &eon, 8); + if (ch == '\n') { + *dst++ = '\r'; + --size; + } + *dst++ = ch; + --size; + src = eon; + } + } else { + *dst++ = *src++; + --size; + } + } + *dst = '\0'; } static struct tagFile { - char *path; - struct tagFile *next; + char *path; + struct tagFile *next; } *file_list = NULL; static void set_failure_reason(char *reason) { if (failure_reason) - free(failure_reason); + free(failure_reason); failure_reason = strdup(reason); success = FALSE; } static char *get_failure_reason() { if (!failure_reason) - return "Installation failed."; + return "Installation failed."; return failure_reason; } static void add_to_filelist(char *path) { - struct tagFile *p; - p = (struct tagFile *)malloc(sizeof(struct tagFile)); - p->path = strdup(path); - p->next = file_list; - file_list = p; + struct tagFile *p; + p = (struct tagFile *)malloc(sizeof(struct tagFile)); + p->path = strdup(path); + p->next = file_list; + file_list = p; } static int do_compile_files(int (__cdecl * PyRun_SimpleString)(char *), - int optimize) + int optimize) { - struct tagFile *p; - int total, n; - char Buffer[MAX_PATH + 64]; - int errors = 0; - - total = 0; - p = file_list; - while (p) { - ++total; - p = p->next; - } - SendDlgItemMessage(hDialog, IDC_PROGRESS, PBM_SETRANGE, 0, - MAKELPARAM(0, total)); - SendDlgItemMessage(hDialog, IDC_PROGRESS, PBM_SETPOS, 0, 0); - - n = 0; - p = file_list; - while (p) { - ++n; - wsprintf(Buffer, - "import py_compile; py_compile.compile (r'%s')", - p->path); - if (PyRun_SimpleString(Buffer)) { - ++errors; - } - /* We send the notification even if the files could not - * be created so that the uninstaller will remove them - * in case they are created later. - */ - wsprintf(Buffer, "%s%c", p->path, optimize ? 'o' : 'c'); - notify(FILE_CREATED, Buffer); - - SendDlgItemMessage(hDialog, IDC_PROGRESS, PBM_SETPOS, n, 0); - SetDlgItemText(hDialog, IDC_INFO, p->path); - p = p->next; - } - return errors; + struct tagFile *p; + int total, n; + char Buffer[MAX_PATH + 64]; + int errors = 0; + + total = 0; + p = file_list; + while (p) { + ++total; + p = p->next; + } + SendDlgItemMessage(hDialog, IDC_PROGRESS, PBM_SETRANGE, 0, + MAKELPARAM(0, total)); + SendDlgItemMessage(hDialog, IDC_PROGRESS, PBM_SETPOS, 0, 0); + + n = 0; + p = file_list; + while (p) { + ++n; + wsprintf(Buffer, + "import py_compile; py_compile.compile (r'%s')", + p->path); + if (PyRun_SimpleString(Buffer)) { + ++errors; + } + /* We send the notification even if the files could not + * be created so that the uninstaller will remove them + * in case they are created later. + */ + wsprintf(Buffer, "%s%c", p->path, optimize ? 'o' : 'c'); + notify(FILE_CREATED, Buffer); + + SendDlgItemMessage(hDialog, IDC_PROGRESS, PBM_SETPOS, n, 0); + SetDlgItemText(hDialog, IDC_INFO, p->path); + p = p->next; + } + return errors; } #define DECLPROC(dll, result, name, args)\ @@ -304,22 +304,22 @@ // Result string must be free'd wchar_t *widen_string(char *src) { - wchar_t *result; - DWORD dest_cch; - int src_len = strlen(src) + 1; // include NULL term in all ops - /* use MultiByteToWideChar() to see how much we need. */ - /* NOTE: this will include the null-term in the length */ - dest_cch = MultiByteToWideChar(CP_ACP, 0, src, src_len, NULL, 0); - // alloc the buffer - result = (wchar_t *)malloc(dest_cch * sizeof(wchar_t)); - if (result==NULL) - return NULL; - /* do the conversion */ - if (0==MultiByteToWideChar(CP_ACP, 0, src, src_len, result, dest_cch)) { - free(result); - return NULL; - } - return result; + wchar_t *result; + DWORD dest_cch; + int src_len = strlen(src) + 1; // include NULL term in all ops + /* use MultiByteToWideChar() to see how much we need. */ + /* NOTE: this will include the null-term in the length */ + dest_cch = MultiByteToWideChar(CP_ACP, 0, src, src_len, NULL, 0); + // alloc the buffer + result = (wchar_t *)malloc(dest_cch * sizeof(wchar_t)); + if (result==NULL) + return NULL; + /* do the conversion */ + if (0==MultiByteToWideChar(CP_ACP, 0, src, src_len, result, dest_cch)) { + free(result); + return NULL; + } + return result; } /* @@ -328,47 +328,47 @@ */ static int compile_filelist(HINSTANCE hPython, BOOL optimize_flag) { - DECLPROC(hPython, void, Py_Initialize, (void)); - DECLPROC(hPython, void, Py_SetProgramName, (wchar_t *)); - DECLPROC(hPython, void, Py_Finalize, (void)); - DECLPROC(hPython, int, PyRun_SimpleString, (char *)); - DECLPROC(hPython, PyObject *, PySys_GetObject, (char *)); - DECLVAR(hPython, int, Py_OptimizeFlag); + DECLPROC(hPython, void, Py_Initialize, (void)); + DECLPROC(hPython, void, Py_SetProgramName, (wchar_t *)); + DECLPROC(hPython, void, Py_Finalize, (void)); + DECLPROC(hPython, int, PyRun_SimpleString, (char *)); + DECLPROC(hPython, PyObject *, PySys_GetObject, (char *)); + DECLVAR(hPython, int, Py_OptimizeFlag); - int errors = 0; - struct tagFile *p = file_list; + int errors = 0; + struct tagFile *p = file_list; - if (!p) - return 0; + if (!p) + return 0; - if (!Py_Initialize || !Py_SetProgramName || !Py_Finalize) - return -1; + if (!Py_Initialize || !Py_SetProgramName || !Py_Finalize) + return -1; - if (!PyRun_SimpleString || !PySys_GetObject || !Py_OptimizeFlag) - return -1; + if (!PyRun_SimpleString || !PySys_GetObject || !Py_OptimizeFlag) + return -1; - *Py_OptimizeFlag = optimize_flag ? 1 : 0; - Py_SetProgramName(wmodulename); - Py_Initialize(); + *Py_OptimizeFlag = optimize_flag ? 1 : 0; + Py_SetProgramName(wmodulename); + Py_Initialize(); - errors += do_compile_files(PyRun_SimpleString, optimize_flag); - Py_Finalize(); + errors += do_compile_files(PyRun_SimpleString, optimize_flag); + Py_Finalize(); - return errors; + return errors; } typedef PyObject *(*PyCFunction)(PyObject *, PyObject *); struct PyMethodDef { - char *ml_name; - PyCFunction ml_meth; - int ml_flags; - char *ml_doc; + char *ml_name; + PyCFunction ml_meth; + int ml_flags; + char *ml_doc; }; typedef struct PyMethodDef PyMethodDef; // XXX - all of these are potentially fragile! We load and unload -// the Python DLL multiple times - so storing functions pointers +// the Python DLL multiple times - so storing functions pointers // is dangerous (although things *look* OK at present) // Better might be to roll prepare_script_environment() into // LoadPythonDll(), and create a new UnloadPythonDLL() which also @@ -385,249 +385,249 @@ #define DEF_CSIDL(name) { name, #name } struct { - int nFolder; - char *name; + int nFolder; + char *name; } csidl_names[] = { - /* Startup menu for all users. - NT only */ - DEF_CSIDL(CSIDL_COMMON_STARTMENU), - /* Startup menu. */ - DEF_CSIDL(CSIDL_STARTMENU), + /* Startup menu for all users. + NT only */ + DEF_CSIDL(CSIDL_COMMON_STARTMENU), + /* Startup menu. */ + DEF_CSIDL(CSIDL_STARTMENU), /* DEF_CSIDL(CSIDL_COMMON_APPDATA), */ /* DEF_CSIDL(CSIDL_LOCAL_APPDATA), */ - /* Repository for application-specific data. - Needs Internet Explorer 4.0 */ - DEF_CSIDL(CSIDL_APPDATA), - - /* The desktop for all users. - NT only */ - DEF_CSIDL(CSIDL_COMMON_DESKTOPDIRECTORY), - /* The desktop. */ - DEF_CSIDL(CSIDL_DESKTOPDIRECTORY), - - /* Startup folder for all users. - NT only */ - DEF_CSIDL(CSIDL_COMMON_STARTUP), - /* Startup folder. */ - DEF_CSIDL(CSIDL_STARTUP), - - /* Programs item in the start menu for all users. - NT only */ - DEF_CSIDL(CSIDL_COMMON_PROGRAMS), - /* Program item in the user's start menu. */ - DEF_CSIDL(CSIDL_PROGRAMS), + /* Repository for application-specific data. + Needs Internet Explorer 4.0 */ + DEF_CSIDL(CSIDL_APPDATA), + + /* The desktop for all users. + NT only */ + DEF_CSIDL(CSIDL_COMMON_DESKTOPDIRECTORY), + /* The desktop. */ + DEF_CSIDL(CSIDL_DESKTOPDIRECTORY), + + /* Startup folder for all users. + NT only */ + DEF_CSIDL(CSIDL_COMMON_STARTUP), + /* Startup folder. */ + DEF_CSIDL(CSIDL_STARTUP), + + /* Programs item in the start menu for all users. + NT only */ + DEF_CSIDL(CSIDL_COMMON_PROGRAMS), + /* Program item in the user's start menu. */ + DEF_CSIDL(CSIDL_PROGRAMS), /* DEF_CSIDL(CSIDL_PROGRAM_FILES_COMMON), */ /* DEF_CSIDL(CSIDL_PROGRAM_FILES), */ - /* Virtual folder containing fonts. */ - DEF_CSIDL(CSIDL_FONTS), + /* Virtual folder containing fonts. */ + DEF_CSIDL(CSIDL_FONTS), }; #define DIM(a) (sizeof(a) / sizeof((a)[0])) static PyObject *FileCreated(PyObject *self, PyObject *args) { - char *path; - if (!g_PyArg_ParseTuple(args, "s", &path)) - return NULL; - notify(FILE_CREATED, path); - return g_Py_BuildValue(""); + char *path; + if (!g_PyArg_ParseTuple(args, "s", &path)) + return NULL; + notify(FILE_CREATED, path); + return g_Py_BuildValue(""); } static PyObject *DirectoryCreated(PyObject *self, PyObject *args) { - char *path; - if (!g_PyArg_ParseTuple(args, "s", &path)) - return NULL; - notify(DIR_CREATED, path); - return g_Py_BuildValue(""); + char *path; + if (!g_PyArg_ParseTuple(args, "s", &path)) + return NULL; + notify(DIR_CREATED, path); + return g_Py_BuildValue(""); } static PyObject *GetSpecialFolderPath(PyObject *self, PyObject *args) { - char *name; - char lpszPath[MAX_PATH]; - int i; - static HRESULT (WINAPI *My_SHGetSpecialFolderPath)(HWND hwnd, - LPTSTR lpszPath, - int nFolder, - BOOL fCreate); - - if (!My_SHGetSpecialFolderPath) { - HINSTANCE hLib = LoadLibrary("shell32.dll"); - if (!hLib) { - g_PyErr_Format(g_PyExc_OSError, - "function not available"); - return NULL; - } - My_SHGetSpecialFolderPath = (BOOL (WINAPI *)(HWND, LPTSTR, - int, BOOL)) - GetProcAddress(hLib, - "SHGetSpecialFolderPathA"); - } - - if (!g_PyArg_ParseTuple(args, "s", &name)) - return NULL; - - if (!My_SHGetSpecialFolderPath) { - g_PyErr_Format(g_PyExc_OSError, "function not available"); - return NULL; - } - - for (i = 0; i < DIM(csidl_names); ++i) { - if (0 == strcmpi(csidl_names[i].name, name)) { - int nFolder; - nFolder = csidl_names[i].nFolder; - if (My_SHGetSpecialFolderPath(NULL, lpszPath, - nFolder, 0)) - return g_Py_BuildValue("s", lpszPath); - else { - g_PyErr_Format(g_PyExc_OSError, - "no such folder (%s)", name); - return NULL; - } - - } - }; - g_PyErr_Format(g_PyExc_ValueError, "unknown CSIDL (%s)", name); - return NULL; + char *name; + char lpszPath[MAX_PATH]; + int i; + static HRESULT (WINAPI *My_SHGetSpecialFolderPath)(HWND hwnd, + LPTSTR lpszPath, + int nFolder, + BOOL fCreate); + + if (!My_SHGetSpecialFolderPath) { + HINSTANCE hLib = LoadLibrary("shell32.dll"); + if (!hLib) { + g_PyErr_Format(g_PyExc_OSError, + "function not available"); + return NULL; + } + My_SHGetSpecialFolderPath = (BOOL (WINAPI *)(HWND, LPTSTR, + int, BOOL)) + GetProcAddress(hLib, + "SHGetSpecialFolderPathA"); + } + + if (!g_PyArg_ParseTuple(args, "s", &name)) + return NULL; + + if (!My_SHGetSpecialFolderPath) { + g_PyErr_Format(g_PyExc_OSError, "function not available"); + return NULL; + } + + for (i = 0; i < DIM(csidl_names); ++i) { + if (0 == strcmpi(csidl_names[i].name, name)) { + int nFolder; + nFolder = csidl_names[i].nFolder; + if (My_SHGetSpecialFolderPath(NULL, lpszPath, + nFolder, 0)) + return g_Py_BuildValue("s", lpszPath); + else { + g_PyErr_Format(g_PyExc_OSError, + "no such folder (%s)", name); + return NULL; + } + + } + }; + g_PyErr_Format(g_PyExc_ValueError, "unknown CSIDL (%s)", name); + return NULL; } static PyObject *CreateShortcut(PyObject *self, PyObject *args) { - char *path; /* path and filename */ - char *description; - char *filename; - - char *arguments = NULL; - char *iconpath = NULL; - int iconindex = 0; - char *workdir = NULL; - - WCHAR wszFilename[MAX_PATH]; - - IShellLink *ps1 = NULL; - IPersistFile *pPf = NULL; - - HRESULT hr; - - hr = CoInitialize(NULL); - if (FAILED(hr)) { - g_PyErr_Format(g_PyExc_OSError, - "CoInitialize failed, error 0x%x", hr); - goto error; - } - - if (!g_PyArg_ParseTuple(args, "sss|sssi", - &path, &description, &filename, - &arguments, &workdir, &iconpath, &iconindex)) - return NULL; - - hr = CoCreateInstance(&CLSID_ShellLink, - NULL, - CLSCTX_INPROC_SERVER, - &IID_IShellLink, - &ps1); - if (FAILED(hr)) { - g_PyErr_Format(g_PyExc_OSError, - "CoCreateInstance failed, error 0x%x", hr); - goto error; - } - - hr = ps1->lpVtbl->QueryInterface(ps1, &IID_IPersistFile, - (void **)&pPf); - if (FAILED(hr)) { - g_PyErr_Format(g_PyExc_OSError, - "QueryInterface(IPersistFile) error 0x%x", hr); - goto error; - } - - - hr = ps1->lpVtbl->SetPath(ps1, path); - if (FAILED(hr)) { - g_PyErr_Format(g_PyExc_OSError, - "SetPath() failed, error 0x%x", hr); - goto error; - } - - hr = ps1->lpVtbl->SetDescription(ps1, description); - if (FAILED(hr)) { - g_PyErr_Format(g_PyExc_OSError, - "SetDescription() failed, error 0x%x", hr); - goto error; - } - - if (arguments) { - hr = ps1->lpVtbl->SetArguments(ps1, arguments); - if (FAILED(hr)) { - g_PyErr_Format(g_PyExc_OSError, - "SetArguments() error 0x%x", hr); - goto error; - } - } - - if (iconpath) { - hr = ps1->lpVtbl->SetIconLocation(ps1, iconpath, iconindex); - if (FAILED(hr)) { - g_PyErr_Format(g_PyExc_OSError, - "SetIconLocation() error 0x%x", hr); - goto error; - } - } - - if (workdir) { - hr = ps1->lpVtbl->SetWorkingDirectory(ps1, workdir); - if (FAILED(hr)) { - g_PyErr_Format(g_PyExc_OSError, - "SetWorkingDirectory() error 0x%x", hr); - goto error; - } - } - - MultiByteToWideChar(CP_ACP, 0, - filename, -1, - wszFilename, MAX_PATH); - - hr = pPf->lpVtbl->Save(pPf, wszFilename, TRUE); - if (FAILED(hr)) { - g_PyErr_Format(g_PyExc_OSError, - "Failed to create shortcut '%s' - error 0x%x", filename, hr); - goto error; - } - - pPf->lpVtbl->Release(pPf); - ps1->lpVtbl->Release(ps1); - CoUninitialize(); - return g_Py_BuildValue(""); - + char *path; /* path and filename */ + char *description; + char *filename; + + char *arguments = NULL; + char *iconpath = NULL; + int iconindex = 0; + char *workdir = NULL; + + WCHAR wszFilename[MAX_PATH]; + + IShellLink *ps1 = NULL; + IPersistFile *pPf = NULL; + + HRESULT hr; + + hr = CoInitialize(NULL); + if (FAILED(hr)) { + g_PyErr_Format(g_PyExc_OSError, + "CoInitialize failed, error 0x%x", hr); + goto error; + } + + if (!g_PyArg_ParseTuple(args, "sss|sssi", + &path, &description, &filename, + &arguments, &workdir, &iconpath, &iconindex)) + return NULL; + + hr = CoCreateInstance(&CLSID_ShellLink, + NULL, + CLSCTX_INPROC_SERVER, + &IID_IShellLink, + &ps1); + if (FAILED(hr)) { + g_PyErr_Format(g_PyExc_OSError, + "CoCreateInstance failed, error 0x%x", hr); + goto error; + } + + hr = ps1->lpVtbl->QueryInterface(ps1, &IID_IPersistFile, + (void **)&pPf); + if (FAILED(hr)) { + g_PyErr_Format(g_PyExc_OSError, + "QueryInterface(IPersistFile) error 0x%x", hr); + goto error; + } + + + hr = ps1->lpVtbl->SetPath(ps1, path); + if (FAILED(hr)) { + g_PyErr_Format(g_PyExc_OSError, + "SetPath() failed, error 0x%x", hr); + goto error; + } + + hr = ps1->lpVtbl->SetDescription(ps1, description); + if (FAILED(hr)) { + g_PyErr_Format(g_PyExc_OSError, + "SetDescription() failed, error 0x%x", hr); + goto error; + } + + if (arguments) { + hr = ps1->lpVtbl->SetArguments(ps1, arguments); + if (FAILED(hr)) { + g_PyErr_Format(g_PyExc_OSError, + "SetArguments() error 0x%x", hr); + goto error; + } + } + + if (iconpath) { + hr = ps1->lpVtbl->SetIconLocation(ps1, iconpath, iconindex); + if (FAILED(hr)) { + g_PyErr_Format(g_PyExc_OSError, + "SetIconLocation() error 0x%x", hr); + goto error; + } + } + + if (workdir) { + hr = ps1->lpVtbl->SetWorkingDirectory(ps1, workdir); + if (FAILED(hr)) { + g_PyErr_Format(g_PyExc_OSError, + "SetWorkingDirectory() error 0x%x", hr); + goto error; + } + } + + MultiByteToWideChar(CP_ACP, 0, + filename, -1, + wszFilename, MAX_PATH); + + hr = pPf->lpVtbl->Save(pPf, wszFilename, TRUE); + if (FAILED(hr)) { + g_PyErr_Format(g_PyExc_OSError, + "Failed to create shortcut '%s' - error 0x%x", filename, hr); + goto error; + } + + pPf->lpVtbl->Release(pPf); + ps1->lpVtbl->Release(ps1); + CoUninitialize(); + return g_Py_BuildValue(""); + error: - if (pPf) - pPf->lpVtbl->Release(pPf); + if (pPf) + pPf->lpVtbl->Release(pPf); - if (ps1) - ps1->lpVtbl->Release(ps1); + if (ps1) + ps1->lpVtbl->Release(ps1); - CoUninitialize(); + CoUninitialize(); - return NULL; + return NULL; } static PyObject *PyMessageBox(PyObject *self, PyObject *args) { - int rc; - char *text, *caption; - int flags; - if (!g_PyArg_ParseTuple(args, "ssi", &text, &caption, &flags)) - return NULL; - rc = MessageBox(GetFocus(), text, caption, flags); - return g_Py_BuildValue("i", rc); + int rc; + char *text, *caption; + int flags; + if (!g_PyArg_ParseTuple(args, "ssi", &text, &caption, &flags)) + return NULL; + rc = MessageBox(GetFocus(), text, caption, flags); + return g_Py_BuildValue("i", rc); } static PyObject *GetRootHKey(PyObject *self) { - return g_PyLong_FromVoidPtr(hkey_root); + return g_PyLong_FromVoidPtr(hkey_root); } #define METH_VARARGS 0x0001 @@ -635,74 +635,74 @@ typedef PyObject *(*PyCFunction)(PyObject *, PyObject *); PyMethodDef meth[] = { - {"create_shortcut", CreateShortcut, METH_VARARGS, NULL}, - {"get_special_folder_path", GetSpecialFolderPath, METH_VARARGS, NULL}, - {"get_root_hkey", (PyCFunction)GetRootHKey, METH_NOARGS, NULL}, - {"file_created", FileCreated, METH_VARARGS, NULL}, - {"directory_created", DirectoryCreated, METH_VARARGS, NULL}, - {"message_box", PyMessageBox, METH_VARARGS, NULL}, + {"create_shortcut", CreateShortcut, METH_VARARGS, NULL}, + {"get_special_folder_path", GetSpecialFolderPath, METH_VARARGS, NULL}, + {"get_root_hkey", (PyCFunction)GetRootHKey, METH_NOARGS, NULL}, + {"file_created", FileCreated, METH_VARARGS, NULL}, + {"directory_created", DirectoryCreated, METH_VARARGS, NULL}, + {"message_box", PyMessageBox, METH_VARARGS, NULL}, }; static HINSTANCE LoadPythonDll(char *fname) { - char fullpath[_MAX_PATH]; - LONG size = sizeof(fullpath); - char subkey_name[80]; - char buffer[260 + 12]; - HINSTANCE h; - - /* make sure PYTHONHOME is set, to that sys.path is initialized correctly */ - wsprintf(buffer, "PYTHONHOME=%s", python_dir); - _putenv(buffer); - h = LoadLibrary(fname); - if (h) - return h; - wsprintf(subkey_name, - "SOFTWARE\\Python\\PythonCore\\%d.%d\\InstallPath", - py_major, py_minor); - if (ERROR_SUCCESS != RegQueryValue(HKEY_CURRENT_USER, subkey_name, - fullpath, &size) && - ERROR_SUCCESS != RegQueryValue(HKEY_LOCAL_MACHINE, subkey_name, - fullpath, &size)) - return NULL; - strcat(fullpath, "\\"); - strcat(fullpath, fname); - return LoadLibrary(fullpath); + char fullpath[_MAX_PATH]; + LONG size = sizeof(fullpath); + char subkey_name[80]; + char buffer[260 + 12]; + HINSTANCE h; + + /* make sure PYTHONHOME is set, to that sys.path is initialized correctly */ + wsprintf(buffer, "PYTHONHOME=%s", python_dir); + _putenv(buffer); + h = LoadLibrary(fname); + if (h) + return h; + wsprintf(subkey_name, + "SOFTWARE\\Python\\PythonCore\\%d.%d\\InstallPath", + py_major, py_minor); + if (ERROR_SUCCESS != RegQueryValue(HKEY_CURRENT_USER, subkey_name, + fullpath, &size) && + ERROR_SUCCESS != RegQueryValue(HKEY_LOCAL_MACHINE, subkey_name, + fullpath, &size)) + return NULL; + strcat(fullpath, "\\"); + strcat(fullpath, fname); + return LoadLibrary(fullpath); } static int prepare_script_environment(HINSTANCE hPython) { - PyObject *mod; - DECLPROC(hPython, PyObject *, PyImport_ImportModule, (char *)); - DECLPROC(hPython, int, PyObject_SetAttrString, (PyObject *, char *, PyObject *)); - DECLPROC(hPython, PyObject *, PyObject_GetAttrString, (PyObject *, char *)); - DECLPROC(hPython, PyObject *, PyCFunction_New, (PyMethodDef *, PyObject *)); - DECLPROC(hPython, PyObject *, Py_BuildValue, (char *, ...)); - DECLPROC(hPython, int, PyArg_ParseTuple, (PyObject *, char *, ...)); - DECLPROC(hPython, PyObject *, PyErr_Format, (PyObject *, char *)); - DECLPROC(hPython, PyObject *, PyLong_FromVoidPtr, (void *)); - if (!PyImport_ImportModule || !PyObject_GetAttrString || - !PyObject_SetAttrString || !PyCFunction_New) - return 1; - if (!Py_BuildValue || !PyArg_ParseTuple || !PyErr_Format) - return 1; - - mod = PyImport_ImportModule("builtins"); - if (mod) { - int i; - g_PyExc_ValueError = PyObject_GetAttrString(mod, "ValueError"); - g_PyExc_OSError = PyObject_GetAttrString(mod, "OSError"); - for (i = 0; i < DIM(meth); ++i) { - PyObject_SetAttrString(mod, meth[i].ml_name, - PyCFunction_New(&meth[i], NULL)); - } - } - g_Py_BuildValue = Py_BuildValue; - g_PyArg_ParseTuple = PyArg_ParseTuple; - g_PyErr_Format = PyErr_Format; - g_PyLong_FromVoidPtr = PyLong_FromVoidPtr; + PyObject *mod; + DECLPROC(hPython, PyObject *, PyImport_ImportModule, (char *)); + DECLPROC(hPython, int, PyObject_SetAttrString, (PyObject *, char *, PyObject *)); + DECLPROC(hPython, PyObject *, PyObject_GetAttrString, (PyObject *, char *)); + DECLPROC(hPython, PyObject *, PyCFunction_New, (PyMethodDef *, PyObject *)); + DECLPROC(hPython, PyObject *, Py_BuildValue, (char *, ...)); + DECLPROC(hPython, int, PyArg_ParseTuple, (PyObject *, char *, ...)); + DECLPROC(hPython, PyObject *, PyErr_Format, (PyObject *, char *)); + DECLPROC(hPython, PyObject *, PyLong_FromVoidPtr, (void *)); + if (!PyImport_ImportModule || !PyObject_GetAttrString || + !PyObject_SetAttrString || !PyCFunction_New) + return 1; + if (!Py_BuildValue || !PyArg_ParseTuple || !PyErr_Format) + return 1; + + mod = PyImport_ImportModule("builtins"); + if (mod) { + int i; + g_PyExc_ValueError = PyObject_GetAttrString(mod, "ValueError"); + g_PyExc_OSError = PyObject_GetAttrString(mod, "OSError"); + for (i = 0; i < DIM(meth); ++i) { + PyObject_SetAttrString(mod, meth[i].ml_name, + PyCFunction_New(&meth[i], NULL)); + } + } + g_Py_BuildValue = Py_BuildValue; + g_PyArg_ParseTuple = PyArg_ParseTuple; + g_PyErr_Format = PyErr_Format; + g_PyLong_FromVoidPtr = PyLong_FromVoidPtr; - return 0; + return 0; } /* @@ -718,483 +718,483 @@ static int do_run_installscript(HINSTANCE hPython, char *pathname, int argc, char **argv) { - int fh, result, i; - static wchar_t *wargv[256]; - DECLPROC(hPython, void, Py_Initialize, (void)); - DECLPROC(hPython, int, PySys_SetArgv, (int, wchar_t **)); - DECLPROC(hPython, int, PyRun_SimpleString, (char *)); - DECLPROC(hPython, void, Py_Finalize, (void)); - DECLPROC(hPython, PyObject *, Py_BuildValue, (char *, ...)); - DECLPROC(hPython, PyObject *, PyCFunction_New, - (PyMethodDef *, PyObject *)); - DECLPROC(hPython, int, PyArg_ParseTuple, (PyObject *, char *, ...)); - DECLPROC(hPython, PyObject *, PyErr_Format, (PyObject *, char *)); - - if (!Py_Initialize || !PySys_SetArgv - || !PyRun_SimpleString || !Py_Finalize) - return 1; - - if (!Py_BuildValue || !PyArg_ParseTuple || !PyErr_Format) - return 1; - - if (!PyCFunction_New || !PyArg_ParseTuple || !PyErr_Format) - return 1; - - if (pathname == NULL || pathname[0] == '\0') - return 2; - - fh = open(pathname, _O_RDONLY); - if (-1 == fh) { - fprintf(stderr, "Could not open postinstall-script %s\n", - pathname); - return 3; - } - - SetDlgItemText(hDialog, IDC_INFO, "Running Script..."); - - Py_Initialize(); - - prepare_script_environment(hPython); - // widen the argv array for py3k. - memset(wargv, 0, sizeof(wargv)); - for (i=0;i 0) { - script[n] = '\n'; - script[n+1] = 0; - result = PyRun_SimpleString(script); - } - } - } - Py_Finalize(); + int fh, result, i; + static wchar_t *wargv[256]; + DECLPROC(hPython, void, Py_Initialize, (void)); + DECLPROC(hPython, int, PySys_SetArgv, (int, wchar_t **)); + DECLPROC(hPython, int, PyRun_SimpleString, (char *)); + DECLPROC(hPython, void, Py_Finalize, (void)); + DECLPROC(hPython, PyObject *, Py_BuildValue, (char *, ...)); + DECLPROC(hPython, PyObject *, PyCFunction_New, + (PyMethodDef *, PyObject *)); + DECLPROC(hPython, int, PyArg_ParseTuple, (PyObject *, char *, ...)); + DECLPROC(hPython, PyObject *, PyErr_Format, (PyObject *, char *)); + + if (!Py_Initialize || !PySys_SetArgv + || !PyRun_SimpleString || !Py_Finalize) + return 1; + + if (!Py_BuildValue || !PyArg_ParseTuple || !PyErr_Format) + return 1; + + if (!PyCFunction_New || !PyArg_ParseTuple || !PyErr_Format) + return 1; + + if (pathname == NULL || pathname[0] == '\0') + return 2; + + fh = open(pathname, _O_RDONLY); + if (-1 == fh) { + fprintf(stderr, "Could not open postinstall-script %s\n", + pathname); + return 3; + } + + SetDlgItemText(hDialog, IDC_INFO, "Running Script..."); + + Py_Initialize(); + + prepare_script_environment(hPython); + // widen the argv array for py3k. + memset(wargv, 0, sizeof(wargv)); + for (i=0;i 0) { + script[n] = '\n'; + script[n+1] = 0; + result = PyRun_SimpleString(script); + } + } + } + Py_Finalize(); - close(fh); - return result; + close(fh); + return result; } static int run_installscript(char *pathname, int argc, char **argv, char **pOutput) { - HINSTANCE hPython; - int result = 1; - int out_buf_size; - HANDLE redirected, old_stderr, old_stdout; - char *tempname; - - *pOutput = NULL; - - tempname = tempnam(NULL, NULL); - // We use a static CRT while the Python version we load uses - // the CRT from one of various possibile DLLs. As a result we - // need to redirect the standard handles using the API rather - // than the CRT. - redirected = CreateFile( - tempname, - GENERIC_WRITE | GENERIC_READ, - FILE_SHARE_READ, - NULL, - CREATE_ALWAYS, - FILE_ATTRIBUTE_NORMAL | FILE_FLAG_WRITE_THROUGH, - NULL); - old_stdout = GetStdHandle(STD_OUTPUT_HANDLE); - old_stderr = GetStdHandle(STD_ERROR_HANDLE); - SetStdHandle(STD_OUTPUT_HANDLE, redirected); - SetStdHandle(STD_ERROR_HANDLE, redirected); - - hPython = LoadPythonDll(pythondll); - if (hPython) { - result = do_run_installscript(hPython, pathname, argc, argv); - FreeLibrary(hPython); - } else { - fprintf(stderr, "*** Could not load Python ***"); - } - SetStdHandle(STD_OUTPUT_HANDLE, old_stdout); - SetStdHandle(STD_ERROR_HANDLE, old_stderr); - out_buf_size = min(GetFileSize(redirected, NULL), 4096); - *pOutput = malloc(out_buf_size+1); - if (*pOutput) { - DWORD nread = 0; - SetFilePointer(redirected, 0, 0, FILE_BEGIN); - ReadFile(redirected, *pOutput, out_buf_size, &nread, NULL); - (*pOutput)[nread] = '\0'; - } - CloseHandle(redirected); - DeleteFile(tempname); - return result; + HINSTANCE hPython; + int result = 1; + int out_buf_size; + HANDLE redirected, old_stderr, old_stdout; + char *tempname; + + *pOutput = NULL; + + tempname = tempnam(NULL, NULL); + // We use a static CRT while the Python version we load uses + // the CRT from one of various possibile DLLs. As a result we + // need to redirect the standard handles using the API rather + // than the CRT. + redirected = CreateFile( + tempname, + GENERIC_WRITE | GENERIC_READ, + FILE_SHARE_READ, + NULL, + CREATE_ALWAYS, + FILE_ATTRIBUTE_NORMAL | FILE_FLAG_WRITE_THROUGH, + NULL); + old_stdout = GetStdHandle(STD_OUTPUT_HANDLE); + old_stderr = GetStdHandle(STD_ERROR_HANDLE); + SetStdHandle(STD_OUTPUT_HANDLE, redirected); + SetStdHandle(STD_ERROR_HANDLE, redirected); + + hPython = LoadPythonDll(pythondll); + if (hPython) { + result = do_run_installscript(hPython, pathname, argc, argv); + FreeLibrary(hPython); + } else { + fprintf(stderr, "*** Could not load Python ***"); + } + SetStdHandle(STD_OUTPUT_HANDLE, old_stdout); + SetStdHandle(STD_ERROR_HANDLE, old_stderr); + out_buf_size = min(GetFileSize(redirected, NULL), 4096); + *pOutput = malloc(out_buf_size+1); + if (*pOutput) { + DWORD nread = 0; + SetFilePointer(redirected, 0, 0, FILE_BEGIN); + ReadFile(redirected, *pOutput, out_buf_size, &nread, NULL); + (*pOutput)[nread] = '\0'; + } + CloseHandle(redirected); + DeleteFile(tempname); + return result; } static int do_run_simple_script(HINSTANCE hPython, char *script) { - int rc; - DECLPROC(hPython, void, Py_Initialize, (void)); - DECLPROC(hPython, void, Py_SetProgramName, (wchar_t *)); - DECLPROC(hPython, void, Py_Finalize, (void)); - DECLPROC(hPython, int, PyRun_SimpleString, (char *)); - DECLPROC(hPython, void, PyErr_Print, (void)); - - if (!Py_Initialize || !Py_SetProgramName || !Py_Finalize || - !PyRun_SimpleString || !PyErr_Print) - return -1; - - Py_SetProgramName(wmodulename); - Py_Initialize(); - prepare_script_environment(hPython); - rc = PyRun_SimpleString(script); - if (rc) - PyErr_Print(); - Py_Finalize(); - return rc; + int rc; + DECLPROC(hPython, void, Py_Initialize, (void)); + DECLPROC(hPython, void, Py_SetProgramName, (wchar_t *)); + DECLPROC(hPython, void, Py_Finalize, (void)); + DECLPROC(hPython, int, PyRun_SimpleString, (char *)); + DECLPROC(hPython, void, PyErr_Print, (void)); + + if (!Py_Initialize || !Py_SetProgramName || !Py_Finalize || + !PyRun_SimpleString || !PyErr_Print) + return -1; + + Py_SetProgramName(wmodulename); + Py_Initialize(); + prepare_script_environment(hPython); + rc = PyRun_SimpleString(script); + if (rc) + PyErr_Print(); + Py_Finalize(); + return rc; } static int run_simple_script(char *script) { - int rc; - HINSTANCE hPython; - char *tempname = tempnam(NULL, NULL); - // Redirect output using win32 API - see comments above... - HANDLE redirected = CreateFile( - tempname, - GENERIC_WRITE | GENERIC_READ, - FILE_SHARE_READ, - NULL, - CREATE_ALWAYS, - FILE_ATTRIBUTE_NORMAL | FILE_FLAG_WRITE_THROUGH, - NULL); - HANDLE old_stdout = GetStdHandle(STD_OUTPUT_HANDLE); - HANDLE old_stderr = GetStdHandle(STD_ERROR_HANDLE); - SetStdHandle(STD_OUTPUT_HANDLE, redirected); - SetStdHandle(STD_ERROR_HANDLE, redirected); - - hPython = LoadPythonDll(pythondll); - if (!hPython) { - char reason[128]; - wsprintf(reason, "Can't load Python for pre-install script (%d)", GetLastError()); - set_failure_reason(reason); - return -1; - } - rc = do_run_simple_script(hPython, script); - FreeLibrary(hPython); - SetStdHandle(STD_OUTPUT_HANDLE, old_stdout); - SetStdHandle(STD_ERROR_HANDLE, old_stderr); - /* We only care about the output when we fail. If the script works - OK, then we discard it - */ - if (rc) { - int err_buf_size; - char *err_buf; - const char *prefix = "Running the pre-installation script failed\r\n"; - int prefix_len = strlen(prefix); - err_buf_size = GetFileSize(redirected, NULL); - if (err_buf_size==INVALID_FILE_SIZE) // an error - let's try anyway... - err_buf_size = 4096; - err_buf = malloc(prefix_len + err_buf_size + 1); - if (err_buf) { - DWORD n = 0; - strcpy(err_buf, prefix); - SetFilePointer(redirected, 0, 0, FILE_BEGIN); - ReadFile(redirected, err_buf+prefix_len, err_buf_size, &n, NULL); - err_buf[prefix_len+n] = '\0'; - set_failure_reason(err_buf); - free(err_buf); - } else { - set_failure_reason("Out of memory!"); - } - } - CloseHandle(redirected); - DeleteFile(tempname); - return rc; + int rc; + HINSTANCE hPython; + char *tempname = tempnam(NULL, NULL); + // Redirect output using win32 API - see comments above... + HANDLE redirected = CreateFile( + tempname, + GENERIC_WRITE | GENERIC_READ, + FILE_SHARE_READ, + NULL, + CREATE_ALWAYS, + FILE_ATTRIBUTE_NORMAL | FILE_FLAG_WRITE_THROUGH, + NULL); + HANDLE old_stdout = GetStdHandle(STD_OUTPUT_HANDLE); + HANDLE old_stderr = GetStdHandle(STD_ERROR_HANDLE); + SetStdHandle(STD_OUTPUT_HANDLE, redirected); + SetStdHandle(STD_ERROR_HANDLE, redirected); + + hPython = LoadPythonDll(pythondll); + if (!hPython) { + char reason[128]; + wsprintf(reason, "Can't load Python for pre-install script (%d)", GetLastError()); + set_failure_reason(reason); + return -1; + } + rc = do_run_simple_script(hPython, script); + FreeLibrary(hPython); + SetStdHandle(STD_OUTPUT_HANDLE, old_stdout); + SetStdHandle(STD_ERROR_HANDLE, old_stderr); + /* We only care about the output when we fail. If the script works + OK, then we discard it + */ + if (rc) { + int err_buf_size; + char *err_buf; + const char *prefix = "Running the pre-installation script failed\r\n"; + int prefix_len = strlen(prefix); + err_buf_size = GetFileSize(redirected, NULL); + if (err_buf_size==INVALID_FILE_SIZE) // an error - let's try anyway... + err_buf_size = 4096; + err_buf = malloc(prefix_len + err_buf_size + 1); + if (err_buf) { + DWORD n = 0; + strcpy(err_buf, prefix); + SetFilePointer(redirected, 0, 0, FILE_BEGIN); + ReadFile(redirected, err_buf+prefix_len, err_buf_size, &n, NULL); + err_buf[prefix_len+n] = '\0'; + set_failure_reason(err_buf); + free(err_buf); + } else { + set_failure_reason("Out of memory!"); + } + } + CloseHandle(redirected); + DeleteFile(tempname); + return rc; } static BOOL SystemError(int error, char *msg) { - char Buffer[1024]; - int n; + char Buffer[1024]; + int n; - if (error) { - LPVOID lpMsgBuf; - FormatMessage( - FORMAT_MESSAGE_ALLOCATE_BUFFER | - FORMAT_MESSAGE_FROM_SYSTEM, - NULL, - error, - MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), - (LPSTR)&lpMsgBuf, - 0, - NULL - ); - strncpy(Buffer, lpMsgBuf, sizeof(Buffer)); - LocalFree(lpMsgBuf); - } else - Buffer[0] = '\0'; - n = lstrlen(Buffer); - _snprintf(Buffer+n, sizeof(Buffer)-n, msg); - MessageBox(hwndMain, Buffer, "Runtime Error", MB_OK | MB_ICONSTOP); - return FALSE; + if (error) { + LPVOID lpMsgBuf; + FormatMessage( + FORMAT_MESSAGE_ALLOCATE_BUFFER | + FORMAT_MESSAGE_FROM_SYSTEM, + NULL, + error, + MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), + (LPSTR)&lpMsgBuf, + 0, + NULL + ); + strncpy(Buffer, lpMsgBuf, sizeof(Buffer)); + LocalFree(lpMsgBuf); + } else + Buffer[0] = '\0'; + n = lstrlen(Buffer); + _snprintf(Buffer+n, sizeof(Buffer)-n, msg); + MessageBox(hwndMain, Buffer, "Runtime Error", MB_OK | MB_ICONSTOP); + return FALSE; } static BOOL notify (int code, char *fmt, ...) { - char Buffer[1024]; - va_list marker; - BOOL result = TRUE; - int a, b; - char *cp; + char Buffer[1024]; + va_list marker; + BOOL result = TRUE; + int a, b; + char *cp; - va_start(marker, fmt); - _vsnprintf(Buffer, sizeof(Buffer), fmt, marker); + va_start(marker, fmt); + _vsnprintf(Buffer, sizeof(Buffer), fmt, marker); - switch (code) { + switch (code) { /* Questions */ - case CAN_OVERWRITE: - break; + case CAN_OVERWRITE: + break; /* Information notification */ - case DIR_CREATED: - if (logfile) - fprintf(logfile, "100 Made Dir: %s\n", fmt); - break; - - case FILE_CREATED: - if (logfile) - fprintf(logfile, "200 File Copy: %s\n", fmt); - goto add_to_filelist_label; - break; - - case FILE_OVERWRITTEN: - if (logfile) - fprintf(logfile, "200 File Overwrite: %s\n", fmt); - add_to_filelist_label: - if ((cp = strrchr(fmt, '.')) && (0 == strcmp (cp, ".py"))) - add_to_filelist(fmt); - break; + case DIR_CREATED: + if (logfile) + fprintf(logfile, "100 Made Dir: %s\n", fmt); + break; + + case FILE_CREATED: + if (logfile) + fprintf(logfile, "200 File Copy: %s\n", fmt); + goto add_to_filelist_label; + break; + + case FILE_OVERWRITTEN: + if (logfile) + fprintf(logfile, "200 File Overwrite: %s\n", fmt); + add_to_filelist_label: + if ((cp = strrchr(fmt, '.')) && (0 == strcmp (cp, ".py"))) + add_to_filelist(fmt); + break; /* Error Messages */ - case ZLIB_ERROR: - MessageBox(GetFocus(), Buffer, "Error", - MB_OK | MB_ICONWARNING); - break; - - case SYSTEM_ERROR: - SystemError(GetLastError(), Buffer); - break; - - case NUM_FILES: - a = va_arg(marker, int); - b = va_arg(marker, int); - SendMessage(hDialog, WM_NUMFILES, 0, MAKELPARAM(0, a)); - SendMessage(hDialog, WM_NEXTFILE, b,(LPARAM)fmt); - } - va_end(marker); - - return result; + case ZLIB_ERROR: + MessageBox(GetFocus(), Buffer, "Error", + MB_OK | MB_ICONWARNING); + break; + + case SYSTEM_ERROR: + SystemError(GetLastError(), Buffer); + break; + + case NUM_FILES: + a = va_arg(marker, int); + b = va_arg(marker, int); + SendMessage(hDialog, WM_NUMFILES, 0, MAKELPARAM(0, a)); + SendMessage(hDialog, WM_NEXTFILE, b,(LPARAM)fmt); + } + va_end(marker); + + return result; } static char *MapExistingFile(char *pathname, DWORD *psize) { - HANDLE hFile, hFileMapping; - DWORD nSizeLow, nSizeHigh; - char *data; - - hFile = CreateFile(pathname, - GENERIC_READ, FILE_SHARE_READ, NULL, - OPEN_EXISTING, - FILE_ATTRIBUTE_NORMAL, NULL); - if (hFile == INVALID_HANDLE_VALUE) - return NULL; - nSizeLow = GetFileSize(hFile, &nSizeHigh); - hFileMapping = CreateFileMapping(hFile, - NULL, PAGE_READONLY, 0, 0, NULL); - CloseHandle(hFile); - - if (hFileMapping == INVALID_HANDLE_VALUE) - return NULL; - - data = MapViewOfFile(hFileMapping, - FILE_MAP_READ, 0, 0, 0); - - CloseHandle(hFileMapping); - *psize = nSizeLow; - return data; + HANDLE hFile, hFileMapping; + DWORD nSizeLow, nSizeHigh; + char *data; + + hFile = CreateFile(pathname, + GENERIC_READ, FILE_SHARE_READ, NULL, + OPEN_EXISTING, + FILE_ATTRIBUTE_NORMAL, NULL); + if (hFile == INVALID_HANDLE_VALUE) + return NULL; + nSizeLow = GetFileSize(hFile, &nSizeHigh); + hFileMapping = CreateFileMapping(hFile, + NULL, PAGE_READONLY, 0, 0, NULL); + CloseHandle(hFile); + + if (hFileMapping == INVALID_HANDLE_VALUE) + return NULL; + + data = MapViewOfFile(hFileMapping, + FILE_MAP_READ, 0, 0, 0); + + CloseHandle(hFileMapping); + *psize = nSizeLow; + return data; } static void create_bitmap(HWND hwnd) { - BITMAPFILEHEADER *bfh; - BITMAPINFO *bi; - HDC hdc; - - if (!bitmap_bytes) - return; - - if (hBitmap) - return; - - hdc = GetDC(hwnd); - - bfh = (BITMAPFILEHEADER *)bitmap_bytes; - bi = (BITMAPINFO *)(bitmap_bytes + sizeof(BITMAPFILEHEADER)); - - hBitmap = CreateDIBitmap(hdc, - &bi->bmiHeader, - CBM_INIT, - bitmap_bytes + bfh->bfOffBits, - bi, - DIB_RGB_COLORS); - ReleaseDC(hwnd, hdc); + BITMAPFILEHEADER *bfh; + BITMAPINFO *bi; + HDC hdc; + + if (!bitmap_bytes) + return; + + if (hBitmap) + return; + + hdc = GetDC(hwnd); + + bfh = (BITMAPFILEHEADER *)bitmap_bytes; + bi = (BITMAPINFO *)(bitmap_bytes + sizeof(BITMAPFILEHEADER)); + + hBitmap = CreateDIBitmap(hdc, + &bi->bmiHeader, + CBM_INIT, + bitmap_bytes + bfh->bfOffBits, + bi, + DIB_RGB_COLORS); + ReleaseDC(hwnd, hdc); } /* Extract everything we need to begin the installation. Currently this is the INI filename with install data, and the raw pre-install script */ static BOOL ExtractInstallData(char *data, DWORD size, int *pexe_size, - char **out_ini_file, char **out_preinstall_script) + char **out_ini_file, char **out_preinstall_script) { - /* read the end of central directory record */ - struct eof_cdir *pe = (struct eof_cdir *)&data[size - sizeof - (struct eof_cdir)]; - - int arc_start = size - sizeof (struct eof_cdir) - pe->nBytesCDir - - pe->ofsCDir; - - int ofs = arc_start - sizeof (struct meta_data_hdr); - - /* read meta_data info */ - struct meta_data_hdr *pmd = (struct meta_data_hdr *)&data[ofs]; - char *src, *dst; - char *ini_file; - char tempdir[MAX_PATH]; - - /* ensure that if we fail, we don't have garbage out pointers */ - *out_ini_file = *out_preinstall_script = NULL; - - if (pe->tag != 0x06054b50) { - return FALSE; - } - - if (pmd->tag != 0x1234567B) { - return SystemError(0, - "Invalid cfgdata magic number (see bdist_wininst.py)"); - } - if (ofs < 0) { - return FALSE; - } - - if (pmd->bitmap_size) { - /* Store pointer to bitmap bytes */ - bitmap_bytes = (char *)pmd - pmd->uncomp_size - pmd->bitmap_size; - } - - *pexe_size = ofs - pmd->uncomp_size - pmd->bitmap_size; - - src = ((char *)pmd) - pmd->uncomp_size; - ini_file = malloc(MAX_PATH); /* will be returned, so do not free it */ - if (!ini_file) - return FALSE; - if (!GetTempPath(sizeof(tempdir), tempdir) - || !GetTempFileName(tempdir, "~du", 0, ini_file)) { - SystemError(GetLastError(), - "Could not create temporary file"); - return FALSE; - } - - dst = map_new_file(CREATE_ALWAYS, ini_file, NULL, pmd->uncomp_size, - 0, 0, NULL/*notify*/); - if (!dst) - return FALSE; - /* Up to the first \0 is the INI file data. */ - strncpy(dst, src, pmd->uncomp_size); - src += strlen(dst) + 1; - /* Up to next \0 is the pre-install script */ - *out_preinstall_script = strdup(src); - *out_ini_file = ini_file; - UnmapViewOfFile(dst); - return TRUE; + /* read the end of central directory record */ + struct eof_cdir *pe = (struct eof_cdir *)&data[size - sizeof + (struct eof_cdir)]; + + int arc_start = size - sizeof (struct eof_cdir) - pe->nBytesCDir - + pe->ofsCDir; + + int ofs = arc_start - sizeof (struct meta_data_hdr); + + /* read meta_data info */ + struct meta_data_hdr *pmd = (struct meta_data_hdr *)&data[ofs]; + char *src, *dst; + char *ini_file; + char tempdir[MAX_PATH]; + + /* ensure that if we fail, we don't have garbage out pointers */ + *out_ini_file = *out_preinstall_script = NULL; + + if (pe->tag != 0x06054b50) { + return FALSE; + } + + if (pmd->tag != 0x1234567B) { + return SystemError(0, + "Invalid cfgdata magic number (see bdist_wininst.py)"); + } + if (ofs < 0) { + return FALSE; + } + + if (pmd->bitmap_size) { + /* Store pointer to bitmap bytes */ + bitmap_bytes = (char *)pmd - pmd->uncomp_size - pmd->bitmap_size; + } + + *pexe_size = ofs - pmd->uncomp_size - pmd->bitmap_size; + + src = ((char *)pmd) - pmd->uncomp_size; + ini_file = malloc(MAX_PATH); /* will be returned, so do not free it */ + if (!ini_file) + return FALSE; + if (!GetTempPath(sizeof(tempdir), tempdir) + || !GetTempFileName(tempdir, "~du", 0, ini_file)) { + SystemError(GetLastError(), + "Could not create temporary file"); + return FALSE; + } + + dst = map_new_file(CREATE_ALWAYS, ini_file, NULL, pmd->uncomp_size, + 0, 0, NULL/*notify*/); + if (!dst) + return FALSE; + /* Up to the first \0 is the INI file data. */ + strncpy(dst, src, pmd->uncomp_size); + src += strlen(dst) + 1; + /* Up to next \0 is the pre-install script */ + *out_preinstall_script = strdup(src); + *out_ini_file = ini_file; + UnmapViewOfFile(dst); + return TRUE; } static void PumpMessages(void) { - MSG msg; - while (PeekMessage(&msg, NULL, 0, 0, PM_REMOVE)) { - TranslateMessage(&msg); - DispatchMessage(&msg); - } + MSG msg; + while (PeekMessage(&msg, NULL, 0, 0, PM_REMOVE)) { + TranslateMessage(&msg); + DispatchMessage(&msg); + } } LRESULT CALLBACK WindowProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam) { - HDC hdc; - HFONT hFont; - int h; - PAINTSTRUCT ps; - switch (msg) { - case WM_PAINT: - hdc = BeginPaint(hwnd, &ps); - h = GetSystemMetrics(SM_CYSCREEN) / 10; - hFont = CreateFont(h, 0, 0, 0, 700, TRUE, - 0, 0, 0, 0, 0, 0, 0, "Times Roman"); - hFont = SelectObject(hdc, hFont); - SetBkMode(hdc, TRANSPARENT); - TextOut(hdc, 15, 15, title, strlen(title)); - SetTextColor(hdc, RGB(255, 255, 255)); - TextOut(hdc, 10, 10, title, strlen(title)); - DeleteObject(SelectObject(hdc, hFont)); - EndPaint(hwnd, &ps); - return 0; - } - return DefWindowProc(hwnd, msg, wParam, lParam); + HDC hdc; + HFONT hFont; + int h; + PAINTSTRUCT ps; + switch (msg) { + case WM_PAINT: + hdc = BeginPaint(hwnd, &ps); + h = GetSystemMetrics(SM_CYSCREEN) / 10; + hFont = CreateFont(h, 0, 0, 0, 700, TRUE, + 0, 0, 0, 0, 0, 0, 0, "Times Roman"); + hFont = SelectObject(hdc, hFont); + SetBkMode(hdc, TRANSPARENT); + TextOut(hdc, 15, 15, title, strlen(title)); + SetTextColor(hdc, RGB(255, 255, 255)); + TextOut(hdc, 10, 10, title, strlen(title)); + DeleteObject(SelectObject(hdc, hFont)); + EndPaint(hwnd, &ps); + return 0; + } + return DefWindowProc(hwnd, msg, wParam, lParam); } static HWND CreateBackground(char *title) { - WNDCLASS wc; - HWND hwnd; - char buffer[4096]; - - wc.style = CS_VREDRAW | CS_HREDRAW; - wc.lpfnWndProc = WindowProc; - wc.cbWndExtra = 0; - wc.cbClsExtra = 0; - wc.hInstance = GetModuleHandle(NULL); - wc.hIcon = NULL; - wc.hCursor = LoadCursor(NULL, IDC_ARROW); - wc.hbrBackground = CreateSolidBrush(RGB(0, 0, 128)); - wc.lpszMenuName = NULL; - wc.lpszClassName = "SetupWindowClass"; - - if (!RegisterClass(&wc)) - MessageBox(hwndMain, - "Could not register window class", - "Setup.exe", MB_OK); - - wsprintf(buffer, "Setup %s", title); - hwnd = CreateWindow("SetupWindowClass", - buffer, - 0, - 0, 0, - GetSystemMetrics(SM_CXFULLSCREEN), - GetSystemMetrics(SM_CYFULLSCREEN), - NULL, - NULL, - GetModuleHandle(NULL), - NULL); - ShowWindow(hwnd, SW_SHOWMAXIMIZED); - UpdateWindow(hwnd); - return hwnd; + WNDCLASS wc; + HWND hwnd; + char buffer[4096]; + + wc.style = CS_VREDRAW | CS_HREDRAW; + wc.lpfnWndProc = WindowProc; + wc.cbWndExtra = 0; + wc.cbClsExtra = 0; + wc.hInstance = GetModuleHandle(NULL); + wc.hIcon = NULL; + wc.hCursor = LoadCursor(NULL, IDC_ARROW); + wc.hbrBackground = CreateSolidBrush(RGB(0, 0, 128)); + wc.lpszMenuName = NULL; + wc.lpszClassName = "SetupWindowClass"; + + if (!RegisterClass(&wc)) + MessageBox(hwndMain, + "Could not register window class", + "Setup.exe", MB_OK); + + wsprintf(buffer, "Setup %s", title); + hwnd = CreateWindow("SetupWindowClass", + buffer, + 0, + 0, 0, + GetSystemMetrics(SM_CXFULLSCREEN), + GetSystemMetrics(SM_CYFULLSCREEN), + NULL, + NULL, + GetModuleHandle(NULL), + NULL); + ShowWindow(hwnd, SW_SHOWMAXIMIZED); + UpdateWindow(hwnd); + return hwnd; } /* @@ -1202,16 +1202,16 @@ */ static void CenterWindow(HWND hwnd) { - RECT rc; - int w, h; + RECT rc; + int w, h; - GetWindowRect(hwnd, &rc); - w = GetSystemMetrics(SM_CXSCREEN); - h = GetSystemMetrics(SM_CYSCREEN); - MoveWindow(hwnd, - (w - (rc.right-rc.left))/2, - (h - (rc.bottom-rc.top))/2, - rc.right-rc.left, rc.bottom-rc.top, FALSE); + GetWindowRect(hwnd, &rc); + w = GetSystemMetrics(SM_CXSCREEN); + h = GetSystemMetrics(SM_CYSCREEN); + MoveWindow(hwnd, + (w - (rc.right-rc.left))/2, + (h - (rc.bottom-rc.top))/2, + rc.right-rc.left, rc.bottom-rc.top, FALSE); } #include @@ -1219,45 +1219,45 @@ BOOL CALLBACK IntroDlgProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam) { - LPNMHDR lpnm; - char Buffer[4096]; + LPNMHDR lpnm; + char Buffer[4096]; - switch (msg) { - case WM_INITDIALOG: - create_bitmap(hwnd); - if(hBitmap) - SendDlgItemMessage(hwnd, IDC_BITMAP, STM_SETIMAGE, - IMAGE_BITMAP, (LPARAM)hBitmap); - CenterWindow(GetParent(hwnd)); - wsprintf(Buffer, - "This Wizard will install %s on your computer. " - "Click Next to continue " - "or Cancel to exit the Setup Wizard.", - meta_name); - SetDlgItemText(hwnd, IDC_TITLE, Buffer); - SetDlgItemText(hwnd, IDC_INTRO_TEXT, info); - SetDlgItemText(hwnd, IDC_BUILD_INFO, build_info); - return FALSE; - - case WM_NOTIFY: - lpnm = (LPNMHDR) lParam; - - switch (lpnm->code) { - case PSN_SETACTIVE: - PropSheet_SetWizButtons(GetParent(hwnd), PSWIZB_NEXT); - break; - - case PSN_WIZNEXT: - break; - - case PSN_RESET: - break; - - default: - break; - } - } - return FALSE; + switch (msg) { + case WM_INITDIALOG: + create_bitmap(hwnd); + if(hBitmap) + SendDlgItemMessage(hwnd, IDC_BITMAP, STM_SETIMAGE, + IMAGE_BITMAP, (LPARAM)hBitmap); + CenterWindow(GetParent(hwnd)); + wsprintf(Buffer, + "This Wizard will install %s on your computer. " + "Click Next to continue " + "or Cancel to exit the Setup Wizard.", + meta_name); + SetDlgItemText(hwnd, IDC_TITLE, Buffer); + SetDlgItemText(hwnd, IDC_INTRO_TEXT, info); + SetDlgItemText(hwnd, IDC_BUILD_INFO, build_info); + return FALSE; + + case WM_NOTIFY: + lpnm = (LPNMHDR) lParam; + + switch (lpnm->code) { + case PSN_SETACTIVE: + PropSheet_SetWizButtons(GetParent(hwnd), PSWIZB_NEXT); + break; + + case PSN_WIZNEXT: + break; + + case PSN_RESET: + break; + + default: + break; + } + } + return FALSE; } #ifdef USE_OTHER_PYTHON_VERSIONS @@ -1269,133 +1269,133 @@ int bound_image_minor; static BOOL __stdcall StatusRoutine(IMAGEHLP_STATUS_REASON reason, - PSTR ImageName, - PSTR DllName, - ULONG Va, - ULONG Parameter) -{ - char fname[_MAX_PATH]; - int int_version; - - switch(reason) { - case BindOutOfMemory: - case BindRvaToVaFailed: - case BindNoRoomInImage: - case BindImportProcedureFailed: - break; - - case BindImportProcedure: - case BindForwarder: - case BindForwarderNOT: - case BindImageModified: - case BindExpandFileHeaders: - case BindImageComplete: - case BindSymbolsNotUpdated: - case BindMismatchedSymbols: - case BindImportModuleFailed: - break; - - case BindImportModule: - if (1 == sscanf(DllName, "python%d", &int_version)) { - SearchPath(NULL, DllName, NULL, sizeof(fname), - fname, NULL); - strcpy(bound_image_dll, fname); - bound_image_major = int_version / 10; - bound_image_minor = int_version % 10; - OutputDebugString("BOUND "); - OutputDebugString(fname); - OutputDebugString("\n"); - } - break; - } - return TRUE; + PSTR ImageName, + PSTR DllName, + ULONG Va, + ULONG Parameter) +{ + char fname[_MAX_PATH]; + int int_version; + + switch(reason) { + case BindOutOfMemory: + case BindRvaToVaFailed: + case BindNoRoomInImage: + case BindImportProcedureFailed: + break; + + case BindImportProcedure: + case BindForwarder: + case BindForwarderNOT: + case BindImageModified: + case BindExpandFileHeaders: + case BindImageComplete: + case BindSymbolsNotUpdated: + case BindMismatchedSymbols: + case BindImportModuleFailed: + break; + + case BindImportModule: + if (1 == sscanf(DllName, "python%d", &int_version)) { + SearchPath(NULL, DllName, NULL, sizeof(fname), + fname, NULL); + strcpy(bound_image_dll, fname); + bound_image_major = int_version / 10; + bound_image_minor = int_version % 10; + OutputDebugString("BOUND "); + OutputDebugString(fname); + OutputDebugString("\n"); + } + break; + } + return TRUE; } /* */ static LPSTR get_sys_prefix(LPSTR exe, LPSTR dll) { - void (__cdecl * Py_Initialize)(void); - void (__cdecl * Py_SetProgramName)(char *); - void (__cdecl * Py_Finalize)(void); - void* (__cdecl * PySys_GetObject)(char *); - void (__cdecl * PySys_SetArgv)(int, char **); - char* (__cdecl * Py_GetPrefix)(void); - char* (__cdecl * Py_GetPath)(void); - HINSTANCE hPython; - LPSTR prefix = NULL; - int (__cdecl * PyRun_SimpleString)(char *); - - { - char Buffer[256]; - wsprintf(Buffer, "PYTHONHOME=%s", exe); - *strrchr(Buffer, '\\') = '\0'; -// MessageBox(GetFocus(), Buffer, "PYTHONHOME", MB_OK); - _putenv(Buffer); - _putenv("PYTHONPATH="); - } - - hPython = LoadLibrary(dll); - if (!hPython) - return NULL; - Py_Initialize = (void (*)(void))GetProcAddress - (hPython,"Py_Initialize"); - - PySys_SetArgv = (void (*)(int, char **))GetProcAddress - (hPython,"PySys_SetArgv"); - - PyRun_SimpleString = (int (*)(char *))GetProcAddress - (hPython,"PyRun_SimpleString"); - - Py_SetProgramName = (void (*)(char *))GetProcAddress - (hPython,"Py_SetProgramName"); - - PySys_GetObject = (void* (*)(char *))GetProcAddress - (hPython,"PySys_GetObject"); - - Py_GetPrefix = (char * (*)(void))GetProcAddress - (hPython,"Py_GetPrefix"); - - Py_GetPath = (char * (*)(void))GetProcAddress - (hPython,"Py_GetPath"); - - Py_Finalize = (void (*)(void))GetProcAddress(hPython, - "Py_Finalize"); - Py_SetProgramName(exe); - Py_Initialize(); - PySys_SetArgv(1, &exe); + void (__cdecl * Py_Initialize)(void); + void (__cdecl * Py_SetProgramName)(char *); + void (__cdecl * Py_Finalize)(void); + void* (__cdecl * PySys_GetObject)(char *); + void (__cdecl * PySys_SetArgv)(int, char **); + char* (__cdecl * Py_GetPrefix)(void); + char* (__cdecl * Py_GetPath)(void); + HINSTANCE hPython; + LPSTR prefix = NULL; + int (__cdecl * PyRun_SimpleString)(char *); + + { + char Buffer[256]; + wsprintf(Buffer, "PYTHONHOME=%s", exe); + *strrchr(Buffer, '\\') = '\0'; +// MessageBox(GetFocus(), Buffer, "PYTHONHOME", MB_OK); + _putenv(Buffer); + _putenv("PYTHONPATH="); + } + + hPython = LoadLibrary(dll); + if (!hPython) + return NULL; + Py_Initialize = (void (*)(void))GetProcAddress + (hPython,"Py_Initialize"); + + PySys_SetArgv = (void (*)(int, char **))GetProcAddress + (hPython,"PySys_SetArgv"); + + PyRun_SimpleString = (int (*)(char *))GetProcAddress + (hPython,"PyRun_SimpleString"); + + Py_SetProgramName = (void (*)(char *))GetProcAddress + (hPython,"Py_SetProgramName"); + + PySys_GetObject = (void* (*)(char *))GetProcAddress + (hPython,"PySys_GetObject"); + + Py_GetPrefix = (char * (*)(void))GetProcAddress + (hPython,"Py_GetPrefix"); + + Py_GetPath = (char * (*)(void))GetProcAddress + (hPython,"Py_GetPath"); + + Py_Finalize = (void (*)(void))GetProcAddress(hPython, + "Py_Finalize"); + Py_SetProgramName(exe); + Py_Initialize(); + PySys_SetArgv(1, &exe); - MessageBox(GetFocus(), Py_GetPrefix(), "PREFIX", MB_OK); - MessageBox(GetFocus(), Py_GetPath(), "PATH", MB_OK); + MessageBox(GetFocus(), Py_GetPrefix(), "PREFIX", MB_OK); + MessageBox(GetFocus(), Py_GetPath(), "PATH", MB_OK); - Py_Finalize(); - FreeLibrary(hPython); + Py_Finalize(); + FreeLibrary(hPython); - return prefix; + return prefix; } static BOOL CheckPythonExe(LPSTR pathname, LPSTR version, int *pmajor, int *pminor) { - bound_image_dll[0] = '\0'; - if (!BindImageEx(BIND_NO_BOUND_IMPORTS | BIND_NO_UPDATE | BIND_ALL_IMAGES, - pathname, - NULL, - NULL, - StatusRoutine)) - return SystemError(0, "Could not bind image"); - if (bound_image_dll[0] == '\0') - return SystemError(0, "Does not seem to be a python executable"); - *pmajor = bound_image_major; - *pminor = bound_image_minor; - if (version && *version) { - char core_version[12]; - wsprintf(core_version, "%d.%d", bound_image_major, bound_image_minor); - if (strcmp(version, core_version)) - return SystemError(0, "Wrong Python version"); - } - get_sys_prefix(pathname, bound_image_dll); - return TRUE; + bound_image_dll[0] = '\0'; + if (!BindImageEx(BIND_NO_BOUND_IMPORTS | BIND_NO_UPDATE | BIND_ALL_IMAGES, + pathname, + NULL, + NULL, + StatusRoutine)) + return SystemError(0, "Could not bind image"); + if (bound_image_dll[0] == '\0') + return SystemError(0, "Does not seem to be a python executable"); + *pmajor = bound_image_major; + *pminor = bound_image_minor; + if (version && *version) { + char core_version[12]; + wsprintf(core_version, "%d.%d", bound_image_major, bound_image_minor); + if (strcmp(version, core_version)) + return SystemError(0, "Wrong Python version"); + } + get_sys_prefix(pathname, bound_image_dll); + return TRUE; } /* @@ -1404,48 +1404,48 @@ */ static BOOL GetOtherPythonVersion(HWND hwnd, LPSTR version) { - char vers_name[_MAX_PATH + 80]; - DWORD itemindex; - OPENFILENAME of; - char pathname[_MAX_PATH]; - DWORD result; - - strcpy(pathname, "python.exe"); - - memset(&of, 0, sizeof(of)); - of.lStructSize = sizeof(OPENFILENAME); - of.hwndOwner = GetParent(hwnd); - of.hInstance = NULL; - of.lpstrFilter = "python.exe\0python.exe\0"; - of.lpstrCustomFilter = NULL; - of.nMaxCustFilter = 0; - of.nFilterIndex = 1; - of.lpstrFile = pathname; - of.nMaxFile = sizeof(pathname); - of.lpstrFileTitle = NULL; - of.nMaxFileTitle = 0; - of.lpstrInitialDir = NULL; - of.lpstrTitle = "Python executable"; - of.Flags = OFN_FILEMUSTEXIST | OFN_PATHMUSTEXIST; - of.lpstrDefExt = "exe"; - - result = GetOpenFileName(&of); - if (result) { - int major, minor; - if (!CheckPythonExe(pathname, version, &major, &minor)) { - return FALSE; - } - *strrchr(pathname, '\\') = '\0'; - wsprintf(vers_name, "Python Version %d.%d in %s", - major, minor, pathname); - itemindex = SendMessage(hwnd, LB_INSERTSTRING, -1, - (LPARAM)(LPSTR)vers_name); - SendMessage(hwnd, LB_SETCURSEL, itemindex, 0); - SendMessage(hwnd, LB_SETITEMDATA, itemindex, - (LPARAM)(LPSTR)strdup(pathname)); - return TRUE; - } - return FALSE; + char vers_name[_MAX_PATH + 80]; + DWORD itemindex; + OPENFILENAME of; + char pathname[_MAX_PATH]; + DWORD result; + + strcpy(pathname, "python.exe"); + + memset(&of, 0, sizeof(of)); + of.lStructSize = sizeof(OPENFILENAME); + of.hwndOwner = GetParent(hwnd); + of.hInstance = NULL; + of.lpstrFilter = "python.exe\0python.exe\0"; + of.lpstrCustomFilter = NULL; + of.nMaxCustFilter = 0; + of.nFilterIndex = 1; + of.lpstrFile = pathname; + of.nMaxFile = sizeof(pathname); + of.lpstrFileTitle = NULL; + of.nMaxFileTitle = 0; + of.lpstrInitialDir = NULL; + of.lpstrTitle = "Python executable"; + of.Flags = OFN_FILEMUSTEXIST | OFN_PATHMUSTEXIST; + of.lpstrDefExt = "exe"; + + result = GetOpenFileName(&of); + if (result) { + int major, minor; + if (!CheckPythonExe(pathname, version, &major, &minor)) { + return FALSE; + } + *strrchr(pathname, '\\') = '\0'; + wsprintf(vers_name, "Python Version %d.%d in %s", + major, minor, pathname); + itemindex = SendMessage(hwnd, LB_INSERTSTRING, -1, + (LPARAM)(LPSTR)vers_name); + SendMessage(hwnd, LB_SETCURSEL, itemindex, 0); + SendMessage(hwnd, LB_SETITEMDATA, itemindex, + (LPARAM)(LPSTR)strdup(pathname)); + return TRUE; + } + return FALSE; } #endif /* USE_OTHER_PYTHON_VERSIONS */ @@ -1462,71 +1462,71 @@ */ static BOOL GetPythonVersions(HWND hwnd, HKEY hkRoot, LPSTR version) { - DWORD index = 0; - char core_version[80]; - HKEY hKey; - BOOL result = TRUE; - DWORD bufsize; - - if (ERROR_SUCCESS != RegOpenKeyEx(hkRoot, - "Software\\Python\\PythonCore", - 0, KEY_READ, &hKey)) - return FALSE; - bufsize = sizeof(core_version); - while (ERROR_SUCCESS == RegEnumKeyEx(hKey, index, - core_version, &bufsize, NULL, - NULL, NULL, NULL)) { - char subkey_name[80], vers_name[80]; - int itemindex; - DWORD value_size; - HKEY hk; - - bufsize = sizeof(core_version); - ++index; - if (version && *version && strcmp(version, core_version)) - continue; - - wsprintf(vers_name, "Python Version %s (found in registry)", - core_version); - wsprintf(subkey_name, - "Software\\Python\\PythonCore\\%s\\InstallPath", - core_version); - if (ERROR_SUCCESS == RegOpenKeyEx(hkRoot, subkey_name, 0, KEY_READ, &hk)) { - InstalledVersionInfo *ivi = - (InstalledVersionInfo *)malloc(sizeof(InstalledVersionInfo)); - value_size = sizeof(ivi->prefix); - if (ivi && - ERROR_SUCCESS == RegQueryValueEx(hk, NULL, NULL, NULL, - ivi->prefix, &value_size)) { - itemindex = SendMessage(hwnd, LB_ADDSTRING, 0, - (LPARAM)(LPSTR)vers_name); - ivi->hkey = hkRoot; - SendMessage(hwnd, LB_SETITEMDATA, itemindex, - (LPARAM)(LPSTR)ivi); - } - RegCloseKey(hk); - } - } - RegCloseKey(hKey); - return result; + DWORD index = 0; + char core_version[80]; + HKEY hKey; + BOOL result = TRUE; + DWORD bufsize; + + if (ERROR_SUCCESS != RegOpenKeyEx(hkRoot, + "Software\\Python\\PythonCore", + 0, KEY_READ, &hKey)) + return FALSE; + bufsize = sizeof(core_version); + while (ERROR_SUCCESS == RegEnumKeyEx(hKey, index, + core_version, &bufsize, NULL, + NULL, NULL, NULL)) { + char subkey_name[80], vers_name[80]; + int itemindex; + DWORD value_size; + HKEY hk; + + bufsize = sizeof(core_version); + ++index; + if (version && *version && strcmp(version, core_version)) + continue; + + wsprintf(vers_name, "Python Version %s (found in registry)", + core_version); + wsprintf(subkey_name, + "Software\\Python\\PythonCore\\%s\\InstallPath", + core_version); + if (ERROR_SUCCESS == RegOpenKeyEx(hkRoot, subkey_name, 0, KEY_READ, &hk)) { + InstalledVersionInfo *ivi = + (InstalledVersionInfo *)malloc(sizeof(InstalledVersionInfo)); + value_size = sizeof(ivi->prefix); + if (ivi && + ERROR_SUCCESS == RegQueryValueEx(hk, NULL, NULL, NULL, + ivi->prefix, &value_size)) { + itemindex = SendMessage(hwnd, LB_ADDSTRING, 0, + (LPARAM)(LPSTR)vers_name); + ivi->hkey = hkRoot; + SendMessage(hwnd, LB_SETITEMDATA, itemindex, + (LPARAM)(LPSTR)ivi); + } + RegCloseKey(hk); + } + } + RegCloseKey(hKey); + return result; } /* Determine if the current user can write to HKEY_LOCAL_MACHINE */ BOOL HasLocalMachinePrivs() { - HKEY hKey; - DWORD result; - static char KeyName[] = - "Software\\Microsoft\\Windows\\CurrentVersion\\Uninstall"; - - result = RegOpenKeyEx(HKEY_LOCAL_MACHINE, - KeyName, - 0, - KEY_CREATE_SUB_KEY, - &hKey); - if (result==0) - RegCloseKey(hKey); - return result==0; + HKEY hKey; + DWORD result; + static char KeyName[] = + "Software\\Microsoft\\Windows\\CurrentVersion\\Uninstall"; + + result = RegOpenKeyEx(HKEY_LOCAL_MACHINE, + KeyName, + 0, + KEY_CREATE_SUB_KEY, + &hKey); + if (result==0) + RegCloseKey(hKey); + return result==0; } // Check the root registry key to use - either HKLM or HKCU. @@ -1539,86 +1539,86 @@ // We assume hkey_root is already set to where Python itself is installed. void CheckRootKey(HWND hwnd) { - if (hkey_root==HKEY_CURRENT_USER) { - ; // as above, always install ourself in HKCU too. - } else if (hkey_root==HKEY_LOCAL_MACHINE) { - // Python in HKLM, but we may or may not have permissions there. - // Open the uninstall key with 'create' permissions - if this fails, - // we don't have permission. - if (!HasLocalMachinePrivs()) - hkey_root = HKEY_CURRENT_USER; - } else { - MessageBox(hwnd, "Don't know Python's installation type", - "Strange", MB_OK | MB_ICONSTOP); - /* Default to wherever they can, but preferring HKLM */ - hkey_root = HasLocalMachinePrivs() ? HKEY_LOCAL_MACHINE : HKEY_CURRENT_USER; - } + if (hkey_root==HKEY_CURRENT_USER) { + ; // as above, always install ourself in HKCU too. + } else if (hkey_root==HKEY_LOCAL_MACHINE) { + // Python in HKLM, but we may or may not have permissions there. + // Open the uninstall key with 'create' permissions - if this fails, + // we don't have permission. + if (!HasLocalMachinePrivs()) + hkey_root = HKEY_CURRENT_USER; + } else { + MessageBox(hwnd, "Don't know Python's installation type", + "Strange", MB_OK | MB_ICONSTOP); + /* Default to wherever they can, but preferring HKLM */ + hkey_root = HasLocalMachinePrivs() ? HKEY_LOCAL_MACHINE : HKEY_CURRENT_USER; + } } /* Return the installation scheme depending on Python version number */ SCHEME *GetScheme(int major, int minor) { - if (major > 2) - return new_scheme; - else if((major == 2) && (minor >= 2)) - return new_scheme; - return old_scheme; + if (major > 2) + return new_scheme; + else if((major == 2) && (minor >= 2)) + return new_scheme; + return old_scheme; } BOOL CALLBACK SelectPythonDlgProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam) { - LPNMHDR lpnm; + LPNMHDR lpnm; - switch (msg) { - case WM_INITDIALOG: - if (hBitmap) - SendDlgItemMessage(hwnd, IDC_BITMAP, STM_SETIMAGE, - IMAGE_BITMAP, (LPARAM)hBitmap); - GetPythonVersions(GetDlgItem(hwnd, IDC_VERSIONS_LIST), - HKEY_LOCAL_MACHINE, target_version); - GetPythonVersions(GetDlgItem(hwnd, IDC_VERSIONS_LIST), - HKEY_CURRENT_USER, target_version); - { /* select the last entry which is the highest python - version found */ - int count; - count = SendDlgItemMessage(hwnd, IDC_VERSIONS_LIST, - LB_GETCOUNT, 0, 0); - if (count && count != LB_ERR) - SendDlgItemMessage(hwnd, IDC_VERSIONS_LIST, LB_SETCURSEL, - count-1, 0); - - /* If a specific Python version is required, - * display a prominent notice showing this fact. - */ - if (target_version && target_version[0]) { - char buffer[4096]; - wsprintf(buffer, - "Python %s is required for this package. " - "Select installation to use:", - target_version); - SetDlgItemText(hwnd, IDC_TITLE, buffer); - } - - if (count == 0) { - char Buffer[4096]; - char *msg; - if (target_version && target_version[0]) { - wsprintf(Buffer, - "Python version %s required, which was not found" - " in the registry.", target_version); - msg = Buffer; - } else - msg = "No Python installation found in the registry."; - MessageBox(hwnd, msg, "Cannot install", - MB_OK | MB_ICONSTOP); - } - } - goto UpdateInstallDir; - break; + switch (msg) { + case WM_INITDIALOG: + if (hBitmap) + SendDlgItemMessage(hwnd, IDC_BITMAP, STM_SETIMAGE, + IMAGE_BITMAP, (LPARAM)hBitmap); + GetPythonVersions(GetDlgItem(hwnd, IDC_VERSIONS_LIST), + HKEY_LOCAL_MACHINE, target_version); + GetPythonVersions(GetDlgItem(hwnd, IDC_VERSIONS_LIST), + HKEY_CURRENT_USER, target_version); + { /* select the last entry which is the highest python + version found */ + int count; + count = SendDlgItemMessage(hwnd, IDC_VERSIONS_LIST, + LB_GETCOUNT, 0, 0); + if (count && count != LB_ERR) + SendDlgItemMessage(hwnd, IDC_VERSIONS_LIST, LB_SETCURSEL, + count-1, 0); + + /* If a specific Python version is required, + * display a prominent notice showing this fact. + */ + if (target_version && target_version[0]) { + char buffer[4096]; + wsprintf(buffer, + "Python %s is required for this package. " + "Select installation to use:", + target_version); + SetDlgItemText(hwnd, IDC_TITLE, buffer); + } + + if (count == 0) { + char Buffer[4096]; + char *msg; + if (target_version && target_version[0]) { + wsprintf(Buffer, + "Python version %s required, which was not found" + " in the registry.", target_version); + msg = Buffer; + } else + msg = "No Python installation found in the registry."; + MessageBox(hwnd, msg, "Cannot install", + MB_OK | MB_ICONSTOP); + } + } + goto UpdateInstallDir; + break; - case WM_COMMAND: - switch (LOWORD(wParam)) { + case WM_COMMAND: + switch (LOWORD(wParam)) { /* case IDC_OTHERPYTHON: if (GetOtherPythonVersion(GetDlgItem(hwnd, IDC_VERSIONS_LIST), @@ -1626,307 +1626,307 @@ goto UpdateInstallDir; break; */ - case IDC_VERSIONS_LIST: - switch (HIWORD(wParam)) { - int id; - case LBN_SELCHANGE: - UpdateInstallDir: - PropSheet_SetWizButtons(GetParent(hwnd), - PSWIZB_BACK | PSWIZB_NEXT); - id = SendDlgItemMessage(hwnd, IDC_VERSIONS_LIST, - LB_GETCURSEL, 0, 0); - if (id == LB_ERR) { - PropSheet_SetWizButtons(GetParent(hwnd), - PSWIZB_BACK); - SetDlgItemText(hwnd, IDC_PATH, ""); - SetDlgItemText(hwnd, IDC_INSTALL_PATH, ""); - strcpy(python_dir, ""); - strcpy(pythondll, ""); - } else { - char *pbuf; - int result; - InstalledVersionInfo *ivi; - PropSheet_SetWizButtons(GetParent(hwnd), - PSWIZB_BACK | PSWIZB_NEXT); - /* Get the python directory */ - ivi = (InstalledVersionInfo *) - SendDlgItemMessage(hwnd, - IDC_VERSIONS_LIST, - LB_GETITEMDATA, - id, - 0); - hkey_root = ivi->hkey; - strcpy(python_dir, ivi->prefix); - SetDlgItemText(hwnd, IDC_PATH, python_dir); - /* retrieve the python version and pythondll to use */ - result = SendDlgItemMessage(hwnd, IDC_VERSIONS_LIST, - LB_GETTEXTLEN, (WPARAM)id, 0); - pbuf = (char *)malloc(result + 1); - if (pbuf) { - /* guess the name of the python-dll */ - SendDlgItemMessage(hwnd, IDC_VERSIONS_LIST, - LB_GETTEXT, (WPARAM)id, - (LPARAM)pbuf); - result = sscanf(pbuf, "Python Version %d.%d", - &py_major, &py_minor); - if (result == 2) { + case IDC_VERSIONS_LIST: + switch (HIWORD(wParam)) { + int id; + case LBN_SELCHANGE: + UpdateInstallDir: + PropSheet_SetWizButtons(GetParent(hwnd), + PSWIZB_BACK | PSWIZB_NEXT); + id = SendDlgItemMessage(hwnd, IDC_VERSIONS_LIST, + LB_GETCURSEL, 0, 0); + if (id == LB_ERR) { + PropSheet_SetWizButtons(GetParent(hwnd), + PSWIZB_BACK); + SetDlgItemText(hwnd, IDC_PATH, ""); + SetDlgItemText(hwnd, IDC_INSTALL_PATH, ""); + strcpy(python_dir, ""); + strcpy(pythondll, ""); + } else { + char *pbuf; + int result; + InstalledVersionInfo *ivi; + PropSheet_SetWizButtons(GetParent(hwnd), + PSWIZB_BACK | PSWIZB_NEXT); + /* Get the python directory */ + ivi = (InstalledVersionInfo *) + SendDlgItemMessage(hwnd, + IDC_VERSIONS_LIST, + LB_GETITEMDATA, + id, + 0); + hkey_root = ivi->hkey; + strcpy(python_dir, ivi->prefix); + SetDlgItemText(hwnd, IDC_PATH, python_dir); + /* retrieve the python version and pythondll to use */ + result = SendDlgItemMessage(hwnd, IDC_VERSIONS_LIST, + LB_GETTEXTLEN, (WPARAM)id, 0); + pbuf = (char *)malloc(result + 1); + if (pbuf) { + /* guess the name of the python-dll */ + SendDlgItemMessage(hwnd, IDC_VERSIONS_LIST, + LB_GETTEXT, (WPARAM)id, + (LPARAM)pbuf); + result = sscanf(pbuf, "Python Version %d.%d", + &py_major, &py_minor); + if (result == 2) { #ifdef _DEBUG - wsprintf(pythondll, "python%d%d_d.dll", - py_major, py_minor); + wsprintf(pythondll, "python%d%d_d.dll", + py_major, py_minor); #else - wsprintf(pythondll, "python%d%d.dll", - py_major, py_minor); + wsprintf(pythondll, "python%d%d.dll", + py_major, py_minor); #endif - } - free(pbuf); - } else - strcpy(pythondll, ""); - /* retrieve the scheme for this version */ - { - char install_path[_MAX_PATH]; - SCHEME *scheme = GetScheme(py_major, py_minor); - strcpy(install_path, python_dir); - if (install_path[strlen(install_path)-1] != '\\') - strcat(install_path, "\\"); - strcat(install_path, scheme[0].prefix); - SetDlgItemText(hwnd, IDC_INSTALL_PATH, install_path); - } - } - } - break; - } - return 0; - - case WM_NOTIFY: - lpnm = (LPNMHDR) lParam; - - switch (lpnm->code) { - int id; - case PSN_SETACTIVE: - id = SendDlgItemMessage(hwnd, IDC_VERSIONS_LIST, - LB_GETCURSEL, 0, 0); - if (id == LB_ERR) - PropSheet_SetWizButtons(GetParent(hwnd), - PSWIZB_BACK); - else - PropSheet_SetWizButtons(GetParent(hwnd), - PSWIZB_BACK | PSWIZB_NEXT); - break; - - case PSN_WIZNEXT: - break; - - case PSN_WIZFINISH: - break; - - case PSN_RESET: - break; - - default: - break; - } - } - return 0; + } + free(pbuf); + } else + strcpy(pythondll, ""); + /* retrieve the scheme for this version */ + { + char install_path[_MAX_PATH]; + SCHEME *scheme = GetScheme(py_major, py_minor); + strcpy(install_path, python_dir); + if (install_path[strlen(install_path)-1] != '\\') + strcat(install_path, "\\"); + strcat(install_path, scheme[0].prefix); + SetDlgItemText(hwnd, IDC_INSTALL_PATH, install_path); + } + } + } + break; + } + return 0; + + case WM_NOTIFY: + lpnm = (LPNMHDR) lParam; + + switch (lpnm->code) { + int id; + case PSN_SETACTIVE: + id = SendDlgItemMessage(hwnd, IDC_VERSIONS_LIST, + LB_GETCURSEL, 0, 0); + if (id == LB_ERR) + PropSheet_SetWizButtons(GetParent(hwnd), + PSWIZB_BACK); + else + PropSheet_SetWizButtons(GetParent(hwnd), + PSWIZB_BACK | PSWIZB_NEXT); + break; + + case PSN_WIZNEXT: + break; + + case PSN_WIZFINISH: + break; + + case PSN_RESET: + break; + + default: + break; + } + } + return 0; } static BOOL OpenLogfile(char *dir) { - char buffer[_MAX_PATH+1]; - time_t ltime; - struct tm *now; - long result; - HKEY hKey, hSubkey; - char subkey_name[256]; - static char KeyName[] = - "Software\\Microsoft\\Windows\\CurrentVersion\\Uninstall"; - const char *root_name = (hkey_root==HKEY_LOCAL_MACHINE ? - "HKEY_LOCAL_MACHINE" : "HKEY_CURRENT_USER"); - DWORD disposition; - - /* Use Create, as the Uninstall subkey may not exist under HKCU. - Use CreateKeyEx, so we can specify a SAM specifying write access - */ - result = RegCreateKeyEx(hkey_root, - KeyName, - 0, /* reserved */ - NULL, /* class */ - 0, /* options */ - KEY_CREATE_SUB_KEY, /* sam */ - NULL, /* security */ - &hKey, /* result key */ - NULL); /* disposition */ - if (result != ERROR_SUCCESS) { - if (result == ERROR_ACCESS_DENIED) { - /* This should no longer be able to happen - we have already - checked if they have permissions in HKLM, and all users - should have write access to HKCU. - */ - MessageBox(GetFocus(), - "You do not seem to have sufficient access rights\n" - "on this machine to install this software", - NULL, - MB_OK | MB_ICONSTOP); - return FALSE; - } else { - MessageBox(GetFocus(), KeyName, "Could not open key", MB_OK); - } - } - - sprintf(buffer, "%s\\%s-wininst.log", dir, meta_name); - logfile = fopen(buffer, "a"); - time(<ime); - now = localtime(<ime); - strftime(buffer, sizeof(buffer), - "*** Installation started %Y/%m/%d %H:%M ***\n", - localtime(<ime)); - fprintf(logfile, buffer); - fprintf(logfile, "Source: %s\n", modulename); - - /* Root key must be first entry processed by uninstaller. */ - fprintf(logfile, "999 Root Key: %s\n", root_name); - - sprintf(subkey_name, "%s-py%d.%d", meta_name, py_major, py_minor); - - result = RegCreateKeyEx(hKey, subkey_name, - 0, NULL, 0, - KEY_WRITE, - NULL, - &hSubkey, - &disposition); - - if (result != ERROR_SUCCESS) - MessageBox(GetFocus(), subkey_name, "Could not create key", MB_OK); - - RegCloseKey(hKey); - - if (disposition == REG_CREATED_NEW_KEY) - fprintf(logfile, "020 Reg DB Key: [%s]%s\n", KeyName, subkey_name); - - sprintf(buffer, "Python %d.%d %s", py_major, py_minor, title); - - result = RegSetValueEx(hSubkey, "DisplayName", - 0, - REG_SZ, - buffer, - strlen(buffer)+1); - - if (result != ERROR_SUCCESS) - MessageBox(GetFocus(), buffer, "Could not set key value", MB_OK); - - fprintf(logfile, "040 Reg DB Value: [%s\\%s]%s=%s\n", - KeyName, subkey_name, "DisplayName", buffer); - - { - FILE *fp; - sprintf(buffer, "%s\\Remove%s.exe", dir, meta_name); - fp = fopen(buffer, "wb"); - fwrite(arc_data, exe_size, 1, fp); - fclose(fp); - - sprintf(buffer, "\"%s\\Remove%s.exe\" -u \"%s\\%s-wininst.log\"", - dir, meta_name, dir, meta_name); - - result = RegSetValueEx(hSubkey, "UninstallString", - 0, - REG_SZ, - buffer, - strlen(buffer)+1); - - if (result != ERROR_SUCCESS) - MessageBox(GetFocus(), buffer, "Could not set key value", MB_OK); - - fprintf(logfile, "040 Reg DB Value: [%s\\%s]%s=%s\n", - KeyName, subkey_name, "UninstallString", buffer); - } - return TRUE; + char buffer[_MAX_PATH+1]; + time_t ltime; + struct tm *now; + long result; + HKEY hKey, hSubkey; + char subkey_name[256]; + static char KeyName[] = + "Software\\Microsoft\\Windows\\CurrentVersion\\Uninstall"; + const char *root_name = (hkey_root==HKEY_LOCAL_MACHINE ? + "HKEY_LOCAL_MACHINE" : "HKEY_CURRENT_USER"); + DWORD disposition; + + /* Use Create, as the Uninstall subkey may not exist under HKCU. + Use CreateKeyEx, so we can specify a SAM specifying write access + */ + result = RegCreateKeyEx(hkey_root, + KeyName, + 0, /* reserved */ + NULL, /* class */ + 0, /* options */ + KEY_CREATE_SUB_KEY, /* sam */ + NULL, /* security */ + &hKey, /* result key */ + NULL); /* disposition */ + if (result != ERROR_SUCCESS) { + if (result == ERROR_ACCESS_DENIED) { + /* This should no longer be able to happen - we have already + checked if they have permissions in HKLM, and all users + should have write access to HKCU. + */ + MessageBox(GetFocus(), + "You do not seem to have sufficient access rights\n" + "on this machine to install this software", + NULL, + MB_OK | MB_ICONSTOP); + return FALSE; + } else { + MessageBox(GetFocus(), KeyName, "Could not open key", MB_OK); + } + } + + sprintf(buffer, "%s\\%s-wininst.log", dir, meta_name); + logfile = fopen(buffer, "a"); + time(<ime); + now = localtime(<ime); + strftime(buffer, sizeof(buffer), + "*** Installation started %Y/%m/%d %H:%M ***\n", + localtime(<ime)); + fprintf(logfile, buffer); + fprintf(logfile, "Source: %s\n", modulename); + + /* Root key must be first entry processed by uninstaller. */ + fprintf(logfile, "999 Root Key: %s\n", root_name); + + sprintf(subkey_name, "%s-py%d.%d", meta_name, py_major, py_minor); + + result = RegCreateKeyEx(hKey, subkey_name, + 0, NULL, 0, + KEY_WRITE, + NULL, + &hSubkey, + &disposition); + + if (result != ERROR_SUCCESS) + MessageBox(GetFocus(), subkey_name, "Could not create key", MB_OK); + + RegCloseKey(hKey); + + if (disposition == REG_CREATED_NEW_KEY) + fprintf(logfile, "020 Reg DB Key: [%s]%s\n", KeyName, subkey_name); + + sprintf(buffer, "Python %d.%d %s", py_major, py_minor, title); + + result = RegSetValueEx(hSubkey, "DisplayName", + 0, + REG_SZ, + buffer, + strlen(buffer)+1); + + if (result != ERROR_SUCCESS) + MessageBox(GetFocus(), buffer, "Could not set key value", MB_OK); + + fprintf(logfile, "040 Reg DB Value: [%s\\%s]%s=%s\n", + KeyName, subkey_name, "DisplayName", buffer); + + { + FILE *fp; + sprintf(buffer, "%s\\Remove%s.exe", dir, meta_name); + fp = fopen(buffer, "wb"); + fwrite(arc_data, exe_size, 1, fp); + fclose(fp); + + sprintf(buffer, "\"%s\\Remove%s.exe\" -u \"%s\\%s-wininst.log\"", + dir, meta_name, dir, meta_name); + + result = RegSetValueEx(hSubkey, "UninstallString", + 0, + REG_SZ, + buffer, + strlen(buffer)+1); + + if (result != ERROR_SUCCESS) + MessageBox(GetFocus(), buffer, "Could not set key value", MB_OK); + + fprintf(logfile, "040 Reg DB Value: [%s\\%s]%s=%s\n", + KeyName, subkey_name, "UninstallString", buffer); + } + return TRUE; } static void CloseLogfile(void) { - char buffer[_MAX_PATH+1]; - time_t ltime; - struct tm *now; - - time(<ime); - now = localtime(<ime); - strftime(buffer, sizeof(buffer), - "*** Installation finished %Y/%m/%d %H:%M ***\n", - localtime(<ime)); - fprintf(logfile, buffer); - if (logfile) - fclose(logfile); + char buffer[_MAX_PATH+1]; + time_t ltime; + struct tm *now; + + time(<ime); + now = localtime(<ime); + strftime(buffer, sizeof(buffer), + "*** Installation finished %Y/%m/%d %H:%M ***\n", + localtime(<ime)); + fprintf(logfile, buffer); + if (logfile) + fclose(logfile); } BOOL CALLBACK InstallFilesDlgProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam) { - LPNMHDR lpnm; - char Buffer[4096]; - SCHEME *scheme; - - switch (msg) { - case WM_INITDIALOG: - if (hBitmap) - SendDlgItemMessage(hwnd, IDC_BITMAP, STM_SETIMAGE, - IMAGE_BITMAP, (LPARAM)hBitmap); - wsprintf(Buffer, - "Click Next to begin the installation of %s. " - "If you want to review or change any of your " - " installation settings, click Back. " - "Click Cancel to exit the wizard.", - meta_name); - SetDlgItemText(hwnd, IDC_TITLE, Buffer); - SetDlgItemText(hwnd, IDC_INFO, "Ready to install"); - break; - - case WM_NUMFILES: - SendDlgItemMessage(hwnd, IDC_PROGRESS, PBM_SETRANGE, 0, lParam); - PumpMessages(); - return TRUE; - - case WM_NEXTFILE: - SendDlgItemMessage(hwnd, IDC_PROGRESS, PBM_SETPOS, wParam, - 0); - SetDlgItemText(hwnd, IDC_INFO, (LPSTR)lParam); - PumpMessages(); - return TRUE; - - case WM_NOTIFY: - lpnm = (LPNMHDR) lParam; - - switch (lpnm->code) { - case PSN_SETACTIVE: - PropSheet_SetWizButtons(GetParent(hwnd), - PSWIZB_BACK | PSWIZB_NEXT); - break; - - case PSN_WIZFINISH: - break; - - case PSN_WIZNEXT: - /* Handle a Next button click here */ - hDialog = hwnd; - success = TRUE; - - /* Disable the buttons while we work. Sending CANCELTOCLOSE has - the effect of disabling the cancel button, which is a) as we - do everything synchronously we can't cancel, and b) the next - step is 'finished', when it is too late to cancel anyway. - The next step being 'Finished' means we also don't need to - restore the button state back */ - PropSheet_SetWizButtons(GetParent(hwnd), 0); - SendMessage(GetParent(hwnd), PSM_CANCELTOCLOSE, 0, 0); - /* Make sure the installation directory name ends in a */ - /* backslash */ - if (python_dir[strlen(python_dir)-1] != '\\') - strcat(python_dir, "\\"); - /* Strip the trailing backslash again */ - python_dir[strlen(python_dir)-1] = '\0'; - - CheckRootKey(hwnd); - - if (!OpenLogfile(python_dir)) - break; + LPNMHDR lpnm; + char Buffer[4096]; + SCHEME *scheme; + + switch (msg) { + case WM_INITDIALOG: + if (hBitmap) + SendDlgItemMessage(hwnd, IDC_BITMAP, STM_SETIMAGE, + IMAGE_BITMAP, (LPARAM)hBitmap); + wsprintf(Buffer, + "Click Next to begin the installation of %s. " + "If you want to review or change any of your " + " installation settings, click Back. " + "Click Cancel to exit the wizard.", + meta_name); + SetDlgItemText(hwnd, IDC_TITLE, Buffer); + SetDlgItemText(hwnd, IDC_INFO, "Ready to install"); + break; + + case WM_NUMFILES: + SendDlgItemMessage(hwnd, IDC_PROGRESS, PBM_SETRANGE, 0, lParam); + PumpMessages(); + return TRUE; + + case WM_NEXTFILE: + SendDlgItemMessage(hwnd, IDC_PROGRESS, PBM_SETPOS, wParam, + 0); + SetDlgItemText(hwnd, IDC_INFO, (LPSTR)lParam); + PumpMessages(); + return TRUE; + + case WM_NOTIFY: + lpnm = (LPNMHDR) lParam; + + switch (lpnm->code) { + case PSN_SETACTIVE: + PropSheet_SetWizButtons(GetParent(hwnd), + PSWIZB_BACK | PSWIZB_NEXT); + break; + + case PSN_WIZFINISH: + break; + + case PSN_WIZNEXT: + /* Handle a Next button click here */ + hDialog = hwnd; + success = TRUE; + + /* Disable the buttons while we work. Sending CANCELTOCLOSE has + the effect of disabling the cancel button, which is a) as we + do everything synchronously we can't cancel, and b) the next + step is 'finished', when it is too late to cancel anyway. + The next step being 'Finished' means we also don't need to + restore the button state back */ + PropSheet_SetWizButtons(GetParent(hwnd), 0); + SendMessage(GetParent(hwnd), PSM_CANCELTOCLOSE, 0, 0); + /* Make sure the installation directory name ends in a */ + /* backslash */ + if (python_dir[strlen(python_dir)-1] != '\\') + strcat(python_dir, "\\"); + /* Strip the trailing backslash again */ + python_dir[strlen(python_dir)-1] = '\0'; + + CheckRootKey(hwnd); + + if (!OpenLogfile(python_dir)) + break; /* * The scheme we have to use depends on the Python version... @@ -1947,202 +1947,202 @@ 'data' : '$base', } */ - scheme = GetScheme(py_major, py_minor); - /* Run the pre-install script. */ - if (pre_install_script && *pre_install_script) { - SetDlgItemText (hwnd, IDC_TITLE, - "Running pre-installation script"); - run_simple_script(pre_install_script); - } - if (!success) { - break; - } - /* Extract all files from the archive */ - SetDlgItemText(hwnd, IDC_TITLE, "Installing files..."); - if (!unzip_archive (scheme, - python_dir, arc_data, - arc_size, notify)) - set_failure_reason("Failed to unzip installation files"); - /* Compile the py-files */ - if (success && pyc_compile) { - int errors; - HINSTANCE hPython; - SetDlgItemText(hwnd, IDC_TITLE, - "Compiling files to .pyc..."); - - SetDlgItemText(hDialog, IDC_INFO, "Loading python..."); - hPython = LoadPythonDll(pythondll); - if (hPython) { - errors = compile_filelist(hPython, FALSE); - FreeLibrary(hPython); - } - /* Compilation errors are intentionally ignored: - * Python2.0 contains a bug which will result - * in sys.path containing garbage under certain - * circumstances, and an error message will only - * confuse the user. - */ - } - if (success && pyo_compile) { - int errors; - HINSTANCE hPython; - SetDlgItemText(hwnd, IDC_TITLE, - "Compiling files to .pyo..."); - - SetDlgItemText(hDialog, IDC_INFO, "Loading python..."); - hPython = LoadPythonDll(pythondll); - if (hPython) { - errors = compile_filelist(hPython, TRUE); - FreeLibrary(hPython); - } - /* Errors ignored: see above */ - } - - - break; - - case PSN_RESET: - break; - - default: - break; - } - } - return 0; + scheme = GetScheme(py_major, py_minor); + /* Run the pre-install script. */ + if (pre_install_script && *pre_install_script) { + SetDlgItemText (hwnd, IDC_TITLE, + "Running pre-installation script"); + run_simple_script(pre_install_script); + } + if (!success) { + break; + } + /* Extract all files from the archive */ + SetDlgItemText(hwnd, IDC_TITLE, "Installing files..."); + if (!unzip_archive (scheme, + python_dir, arc_data, + arc_size, notify)) + set_failure_reason("Failed to unzip installation files"); + /* Compile the py-files */ + if (success && pyc_compile) { + int errors; + HINSTANCE hPython; + SetDlgItemText(hwnd, IDC_TITLE, + "Compiling files to .pyc..."); + + SetDlgItemText(hDialog, IDC_INFO, "Loading python..."); + hPython = LoadPythonDll(pythondll); + if (hPython) { + errors = compile_filelist(hPython, FALSE); + FreeLibrary(hPython); + } + /* Compilation errors are intentionally ignored: + * Python2.0 contains a bug which will result + * in sys.path containing garbage under certain + * circumstances, and an error message will only + * confuse the user. + */ + } + if (success && pyo_compile) { + int errors; + HINSTANCE hPython; + SetDlgItemText(hwnd, IDC_TITLE, + "Compiling files to .pyo..."); + + SetDlgItemText(hDialog, IDC_INFO, "Loading python..."); + hPython = LoadPythonDll(pythondll); + if (hPython) { + errors = compile_filelist(hPython, TRUE); + FreeLibrary(hPython); + } + /* Errors ignored: see above */ + } + + + break; + + case PSN_RESET: + break; + + default: + break; + } + } + return 0; } BOOL CALLBACK FinishedDlgProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam) { - LPNMHDR lpnm; + LPNMHDR lpnm; - switch (msg) { - case WM_INITDIALOG: - if (hBitmap) - SendDlgItemMessage(hwnd, IDC_BITMAP, STM_SETIMAGE, - IMAGE_BITMAP, (LPARAM)hBitmap); - if (!success) - SetDlgItemText(hwnd, IDC_INFO, get_failure_reason()); - - /* async delay: will show the dialog box completely before - the install_script is started */ - PostMessage(hwnd, WM_USER, 0, 0L); - return TRUE; - - case WM_USER: - - if (success && install_script && install_script[0]) { - char fname[MAX_PATH]; - char *buffer; - HCURSOR hCursor; - int result; - - char *argv[3] = {NULL, "-install", NULL}; - - SetDlgItemText(hwnd, IDC_TITLE, - "Please wait while running postinstall script..."); - strcpy(fname, python_dir); - strcat(fname, "\\Scripts\\"); - strcat(fname, install_script); - - if (logfile) - fprintf(logfile, "300 Run Script: [%s]%s\n", pythondll, fname); - - hCursor = SetCursor(LoadCursor(NULL, IDC_WAIT)); - - argv[0] = fname; - - result = run_installscript(fname, 2, argv, &buffer); - if (0 != result) { - fprintf(stderr, "*** run_installscript: internal error 0x%X ***\n", result); - } - if (buffer) - SetDlgItemText(hwnd, IDC_INFO, buffer); - SetDlgItemText(hwnd, IDC_TITLE, - "Postinstall script finished.\n" - "Click the Finish button to exit the Setup wizard."); - - free(buffer); - SetCursor(hCursor); - CloseLogfile(); - } - - return TRUE; - - case WM_NOTIFY: - lpnm = (LPNMHDR) lParam; - - switch (lpnm->code) { - case PSN_SETACTIVE: /* Enable the Finish button */ - PropSheet_SetWizButtons(GetParent(hwnd), PSWIZB_FINISH); - break; - - case PSN_WIZNEXT: - break; - - case PSN_WIZFINISH: - break; - - case PSN_RESET: - break; - - default: - break; - } - } - return 0; + switch (msg) { + case WM_INITDIALOG: + if (hBitmap) + SendDlgItemMessage(hwnd, IDC_BITMAP, STM_SETIMAGE, + IMAGE_BITMAP, (LPARAM)hBitmap); + if (!success) + SetDlgItemText(hwnd, IDC_INFO, get_failure_reason()); + + /* async delay: will show the dialog box completely before + the install_script is started */ + PostMessage(hwnd, WM_USER, 0, 0L); + return TRUE; + + case WM_USER: + + if (success && install_script && install_script[0]) { + char fname[MAX_PATH]; + char *buffer; + HCURSOR hCursor; + int result; + + char *argv[3] = {NULL, "-install", NULL}; + + SetDlgItemText(hwnd, IDC_TITLE, + "Please wait while running postinstall script..."); + strcpy(fname, python_dir); + strcat(fname, "\\Scripts\\"); + strcat(fname, install_script); + + if (logfile) + fprintf(logfile, "300 Run Script: [%s]%s\n", pythondll, fname); + + hCursor = SetCursor(LoadCursor(NULL, IDC_WAIT)); + + argv[0] = fname; + + result = run_installscript(fname, 2, argv, &buffer); + if (0 != result) { + fprintf(stderr, "*** run_installscript: internal error 0x%X ***\n", result); + } + if (buffer) + SetDlgItemText(hwnd, IDC_INFO, buffer); + SetDlgItemText(hwnd, IDC_TITLE, + "Postinstall script finished.\n" + "Click the Finish button to exit the Setup wizard."); + + free(buffer); + SetCursor(hCursor); + CloseLogfile(); + } + + return TRUE; + + case WM_NOTIFY: + lpnm = (LPNMHDR) lParam; + + switch (lpnm->code) { + case PSN_SETACTIVE: /* Enable the Finish button */ + PropSheet_SetWizButtons(GetParent(hwnd), PSWIZB_FINISH); + break; + + case PSN_WIZNEXT: + break; + + case PSN_WIZFINISH: + break; + + case PSN_RESET: + break; + + default: + break; + } + } + return 0; } void RunWizard(HWND hwnd) { - PROPSHEETPAGE psp = {0}; - HPROPSHEETPAGE ahpsp[4] = {0}; - PROPSHEETHEADER psh = {0}; - - /* Display module information */ - psp.dwSize = sizeof(psp); - psp.dwFlags = PSP_DEFAULT|PSP_HIDEHEADER; - psp.hInstance = GetModuleHandle (NULL); - psp.lParam = 0; - psp.pfnDlgProc = IntroDlgProc; - psp.pszTemplate = MAKEINTRESOURCE(IDD_INTRO); - - ahpsp[0] = CreatePropertySheetPage(&psp); - - /* Select python version to use */ - psp.dwFlags = PSP_DEFAULT|PSP_HIDEHEADER; - psp.pszTemplate = MAKEINTRESOURCE(IDD_SELECTPYTHON); - psp.pfnDlgProc = SelectPythonDlgProc; - - ahpsp[1] = CreatePropertySheetPage(&psp); - - /* Install the files */ - psp.dwFlags = PSP_DEFAULT|PSP_HIDEHEADER; - psp.pszTemplate = MAKEINTRESOURCE(IDD_INSTALLFILES); - psp.pfnDlgProc = InstallFilesDlgProc; - - ahpsp[2] = CreatePropertySheetPage(&psp); - - /* Show success or failure */ - psp.dwFlags = PSP_DEFAULT|PSP_HIDEHEADER; - psp.pszTemplate = MAKEINTRESOURCE(IDD_FINISHED); - psp.pfnDlgProc = FinishedDlgProc; - - ahpsp[3] = CreatePropertySheetPage(&psp); - - /* Create the property sheet */ - psh.dwSize = sizeof(psh); - psh.hInstance = GetModuleHandle(NULL); - psh.hwndParent = hwnd; - psh.phpage = ahpsp; - psh.dwFlags = PSH_WIZARD/*97*//*|PSH_WATERMARK|PSH_HEADER*/; - psh.pszbmWatermark = NULL; - psh.pszbmHeader = NULL; - psh.nStartPage = 0; - psh.nPages = 4; + PROPSHEETPAGE psp = {0}; + HPROPSHEETPAGE ahpsp[4] = {0}; + PROPSHEETHEADER psh = {0}; + + /* Display module information */ + psp.dwSize = sizeof(psp); + psp.dwFlags = PSP_DEFAULT|PSP_HIDEHEADER; + psp.hInstance = GetModuleHandle (NULL); + psp.lParam = 0; + psp.pfnDlgProc = IntroDlgProc; + psp.pszTemplate = MAKEINTRESOURCE(IDD_INTRO); + + ahpsp[0] = CreatePropertySheetPage(&psp); + + /* Select python version to use */ + psp.dwFlags = PSP_DEFAULT|PSP_HIDEHEADER; + psp.pszTemplate = MAKEINTRESOURCE(IDD_SELECTPYTHON); + psp.pfnDlgProc = SelectPythonDlgProc; + + ahpsp[1] = CreatePropertySheetPage(&psp); + + /* Install the files */ + psp.dwFlags = PSP_DEFAULT|PSP_HIDEHEADER; + psp.pszTemplate = MAKEINTRESOURCE(IDD_INSTALLFILES); + psp.pfnDlgProc = InstallFilesDlgProc; + + ahpsp[2] = CreatePropertySheetPage(&psp); + + /* Show success or failure */ + psp.dwFlags = PSP_DEFAULT|PSP_HIDEHEADER; + psp.pszTemplate = MAKEINTRESOURCE(IDD_FINISHED); + psp.pfnDlgProc = FinishedDlgProc; + + ahpsp[3] = CreatePropertySheetPage(&psp); + + /* Create the property sheet */ + psh.dwSize = sizeof(psh); + psh.hInstance = GetModuleHandle(NULL); + psh.hwndParent = hwnd; + psh.phpage = ahpsp; + psh.dwFlags = PSH_WIZARD/*97*//*|PSH_WATERMARK|PSH_HEADER*/; + psh.pszbmWatermark = NULL; + psh.pszbmHeader = NULL; + psh.nStartPage = 0; + psh.nPages = 4; - PropertySheet(&psh); + PropertySheet(&psh); } // subtly different from HasLocalMachinePrivs(), in that after executing @@ -2150,16 +2150,16 @@ // such implication for HasLocalMachinePrivs BOOL MyIsUserAnAdmin() { - typedef BOOL (WINAPI *PFNIsUserAnAdmin)(); - static PFNIsUserAnAdmin pfnIsUserAnAdmin = NULL; - HMODULE shell32; - // This function isn't guaranteed to be available (and it can't hurt - // to leave the library loaded) - if (0 == (shell32=LoadLibrary("shell32.dll"))) - return FALSE; - if (0 == (pfnIsUserAnAdmin=(PFNIsUserAnAdmin)GetProcAddress(shell32, "IsUserAnAdmin"))) - return FALSE; - return (*pfnIsUserAnAdmin)(); + typedef BOOL (WINAPI *PFNIsUserAnAdmin)(); + static PFNIsUserAnAdmin pfnIsUserAnAdmin = NULL; + HMODULE shell32; + // This function isn't guaranteed to be available (and it can't hurt + // to leave the library loaded) + if (0 == (shell32=LoadLibrary("shell32.dll"))) + return FALSE; + if (0 == (pfnIsUserAnAdmin=(PFNIsUserAnAdmin)GetProcAddress(shell32, "IsUserAnAdmin"))) + return FALSE; + return (*pfnIsUserAnAdmin)(); } // Some magic for Vista's UAC. If there is a target_version, and @@ -2171,38 +2171,38 @@ // Returns TRUE if we should spawn an elevated child BOOL NeedAutoUAC() { - HKEY hk; - char key_name[80]; - // no Python version info == we can't know yet. - if (target_version[0] == '\0') - return FALSE; - // see how python is current installed - wsprintf(key_name, - "Software\\Python\\PythonCore\\%s\\InstallPath", - target_version); - if (ERROR_SUCCESS != RegOpenKeyEx(HKEY_LOCAL_MACHINE, - key_name, 0, KEY_READ, &hk)) - return FALSE; - RegCloseKey(hk); - // Python is installed in HKLM - we must elevate. - return TRUE; + HKEY hk; + char key_name[80]; + // no Python version info == we can't know yet. + if (target_version[0] == '\0') + return FALSE; + // see how python is current installed + wsprintf(key_name, + "Software\\Python\\PythonCore\\%s\\InstallPath", + target_version); + if (ERROR_SUCCESS != RegOpenKeyEx(HKEY_LOCAL_MACHINE, + key_name, 0, KEY_READ, &hk)) + return FALSE; + RegCloseKey(hk); + // Python is installed in HKLM - we must elevate. + return TRUE; } // Returns TRUE if the platform supports UAC. BOOL PlatformSupportsUAC() { - // Note that win2k does seem to support ShellExecute with 'runas', - // but does *not* support IsUserAnAdmin - so we just pretend things - // only work on XP and later. - BOOL bIsWindowsXPorLater; - OSVERSIONINFO winverinfo; - winverinfo.dwOSVersionInfoSize = sizeof(winverinfo); - if (!GetVersionEx(&winverinfo)) - return FALSE; // something bad has gone wrong - bIsWindowsXPorLater = + // Note that win2k does seem to support ShellExecute with 'runas', + // but does *not* support IsUserAnAdmin - so we just pretend things + // only work on XP and later. + BOOL bIsWindowsXPorLater; + OSVERSIONINFO winverinfo; + winverinfo.dwOSVersionInfoSize = sizeof(winverinfo); + if (!GetVersionEx(&winverinfo)) + return FALSE; // something bad has gone wrong + bIsWindowsXPorLater = ( (winverinfo.dwMajorVersion > 5) || ( (winverinfo.dwMajorVersion == 5) && (winverinfo.dwMinorVersion >= 1) )); - return bIsWindowsXPorLater; + return bIsWindowsXPorLater; } // Spawn ourself as an elevated application. On failure, a message is @@ -2210,97 +2210,97 @@ // on error. void SpawnUAC() { - // interesting failure scenario that has been seen: initial executable - // runs from a network drive - but once elevated, that network share - // isn't seen, and ShellExecute fails with SE_ERR_ACCESSDENIED. - int ret = (int)ShellExecute(0, "runas", modulename, "", NULL, - SW_SHOWNORMAL); - if (ret <= 32) { - char msg[128]; - wsprintf(msg, "Failed to start elevated process (ShellExecute returned %d)", ret); - MessageBox(0, msg, "Setup", MB_OK | MB_ICONERROR); - } + // interesting failure scenario that has been seen: initial executable + // runs from a network drive - but once elevated, that network share + // isn't seen, and ShellExecute fails with SE_ERR_ACCESSDENIED. + int ret = (int)ShellExecute(0, "runas", modulename, "", NULL, + SW_SHOWNORMAL); + if (ret <= 32) { + char msg[128]; + wsprintf(msg, "Failed to start elevated process (ShellExecute returned %d)", ret); + MessageBox(0, msg, "Setup", MB_OK | MB_ICONERROR); + } } int DoInstall(void) { - char ini_buffer[4096]; + char ini_buffer[4096]; - /* Read installation information */ - GetPrivateProfileString("Setup", "title", "", ini_buffer, - sizeof(ini_buffer), ini_file); - unescape(title, ini_buffer, sizeof(title)); - - GetPrivateProfileString("Setup", "info", "", ini_buffer, - sizeof(ini_buffer), ini_file); - unescape(info, ini_buffer, sizeof(info)); - - GetPrivateProfileString("Setup", "build_info", "", build_info, - sizeof(build_info), ini_file); - - pyc_compile = GetPrivateProfileInt("Setup", "target_compile", 1, - ini_file); - pyo_compile = GetPrivateProfileInt("Setup", "target_optimize", 1, - ini_file); - - GetPrivateProfileString("Setup", "target_version", "", - target_version, sizeof(target_version), - ini_file); - - GetPrivateProfileString("metadata", "name", "", - meta_name, sizeof(meta_name), - ini_file); - - GetPrivateProfileString("Setup", "install_script", "", - install_script, sizeof(install_script), - ini_file); - - GetPrivateProfileString("Setup", "user_access_control", "", - user_access_control, sizeof(user_access_control), ini_file); - - // See if we need to do the Vista UAC magic. - if (strcmp(user_access_control, "force")==0) { - if (PlatformSupportsUAC() && !MyIsUserAnAdmin()) { - SpawnUAC(); - return 0; - } - // already admin - keep going - } else if (strcmp(user_access_control, "auto")==0) { - // Check if it looks like we need UAC control, based - // on how Python itself was installed. - if (PlatformSupportsUAC() && !MyIsUserAnAdmin() && NeedAutoUAC()) { - SpawnUAC(); - return 0; - } - } else { - // display a warning about unknown values - only the developer - // of the extension will see it (until they fix it!) - if (user_access_control[0] && strcmp(user_access_control, "none") != 0) { - MessageBox(GetFocus(), "Bad user_access_control value", "oops", MB_OK); - // nothing to do. - } - } - - hwndMain = CreateBackground(title); - - RunWizard(hwndMain); - - /* Clean up */ - UnmapViewOfFile(arc_data); - if (ini_file) - DeleteFile(ini_file); + /* Read installation information */ + GetPrivateProfileString("Setup", "title", "", ini_buffer, + sizeof(ini_buffer), ini_file); + unescape(title, ini_buffer, sizeof(title)); + + GetPrivateProfileString("Setup", "info", "", ini_buffer, + sizeof(ini_buffer), ini_file); + unescape(info, ini_buffer, sizeof(info)); + + GetPrivateProfileString("Setup", "build_info", "", build_info, + sizeof(build_info), ini_file); + + pyc_compile = GetPrivateProfileInt("Setup", "target_compile", 1, + ini_file); + pyo_compile = GetPrivateProfileInt("Setup", "target_optimize", 1, + ini_file); + + GetPrivateProfileString("Setup", "target_version", "", + target_version, sizeof(target_version), + ini_file); + + GetPrivateProfileString("metadata", "name", "", + meta_name, sizeof(meta_name), + ini_file); + + GetPrivateProfileString("Setup", "install_script", "", + install_script, sizeof(install_script), + ini_file); + + GetPrivateProfileString("Setup", "user_access_control", "", + user_access_control, sizeof(user_access_control), ini_file); + + // See if we need to do the Vista UAC magic. + if (strcmp(user_access_control, "force")==0) { + if (PlatformSupportsUAC() && !MyIsUserAnAdmin()) { + SpawnUAC(); + return 0; + } + // already admin - keep going + } else if (strcmp(user_access_control, "auto")==0) { + // Check if it looks like we need UAC control, based + // on how Python itself was installed. + if (PlatformSupportsUAC() && !MyIsUserAnAdmin() && NeedAutoUAC()) { + SpawnUAC(); + return 0; + } + } else { + // display a warning about unknown values - only the developer + // of the extension will see it (until they fix it!) + if (user_access_control[0] && strcmp(user_access_control, "none") != 0) { + MessageBox(GetFocus(), "Bad user_access_control value", "oops", MB_OK); + // nothing to do. + } + } + + hwndMain = CreateBackground(title); + + RunWizard(hwndMain); + + /* Clean up */ + UnmapViewOfFile(arc_data); + if (ini_file) + DeleteFile(ini_file); - if (hBitmap) - DeleteObject(hBitmap); + if (hBitmap) + DeleteObject(hBitmap); - return 0; + return 0; } /*********************** uninstall section ******************************/ static int compare(const void *p1, const void *p2) { - return strcmp(*(char **)p2, *(char **)p1); + return strcmp(*(char **)p2, *(char **)p1); } /* @@ -2314,380 +2314,380 @@ */ void remove_exe(void) { - char exename[_MAX_PATH]; - char batname[_MAX_PATH]; - FILE *fp; - STARTUPINFO si; - PROCESS_INFORMATION pi; - - GetModuleFileName(NULL, exename, sizeof(exename)); - sprintf(batname, "%s.bat", exename); - fp = fopen(batname, "w"); - fprintf(fp, ":Repeat\n"); - fprintf(fp, "del \"%s\"\n", exename); - fprintf(fp, "if exist \"%s\" goto Repeat\n", exename); - fprintf(fp, "del \"%s\"\n", batname); - fclose(fp); - - ZeroMemory(&si, sizeof(si)); - si.cb = sizeof(si); - si.dwFlags = STARTF_USESHOWWINDOW; - si.wShowWindow = SW_HIDE; - if (CreateProcess(NULL, - batname, - NULL, - NULL, - FALSE, - CREATE_SUSPENDED | IDLE_PRIORITY_CLASS, - NULL, - "\\", - &si, - &pi)) { - SetThreadPriority(pi.hThread, THREAD_PRIORITY_IDLE); - SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_TIME_CRITICAL); - SetPriorityClass(GetCurrentProcess(), HIGH_PRIORITY_CLASS); - CloseHandle(pi.hProcess); - ResumeThread(pi.hThread); - CloseHandle(pi.hThread); - } + char exename[_MAX_PATH]; + char batname[_MAX_PATH]; + FILE *fp; + STARTUPINFO si; + PROCESS_INFORMATION pi; + + GetModuleFileName(NULL, exename, sizeof(exename)); + sprintf(batname, "%s.bat", exename); + fp = fopen(batname, "w"); + fprintf(fp, ":Repeat\n"); + fprintf(fp, "del \"%s\"\n", exename); + fprintf(fp, "if exist \"%s\" goto Repeat\n", exename); + fprintf(fp, "del \"%s\"\n", batname); + fclose(fp); + + ZeroMemory(&si, sizeof(si)); + si.cb = sizeof(si); + si.dwFlags = STARTF_USESHOWWINDOW; + si.wShowWindow = SW_HIDE; + if (CreateProcess(NULL, + batname, + NULL, + NULL, + FALSE, + CREATE_SUSPENDED | IDLE_PRIORITY_CLASS, + NULL, + "\\", + &si, + &pi)) { + SetThreadPriority(pi.hThread, THREAD_PRIORITY_IDLE); + SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_TIME_CRITICAL); + SetPriorityClass(GetCurrentProcess(), HIGH_PRIORITY_CLASS); + CloseHandle(pi.hProcess); + ResumeThread(pi.hThread); + CloseHandle(pi.hThread); + } } void DeleteRegistryKey(char *string) { - char *keyname; - char *subkeyname; - char *delim; - HKEY hKey; - long result; - char *line; - - line = strdup(string); /* so we can change it */ - - keyname = strchr(line, '['); - if (!keyname) - return; - ++keyname; - - subkeyname = strchr(keyname, ']'); - if (!subkeyname) - return; - *subkeyname++='\0'; - delim = strchr(subkeyname, '\n'); - if (delim) - *delim = '\0'; - - result = RegOpenKeyEx(hkey_root, - keyname, - 0, - KEY_WRITE, - &hKey); - - if (result != ERROR_SUCCESS) - MessageBox(GetFocus(), string, "Could not open key", MB_OK); - else { - result = RegDeleteKey(hKey, subkeyname); - if (result != ERROR_SUCCESS && result != ERROR_FILE_NOT_FOUND) - MessageBox(GetFocus(), string, "Could not delete key", MB_OK); - RegCloseKey(hKey); - } - free(line); + char *keyname; + char *subkeyname; + char *delim; + HKEY hKey; + long result; + char *line; + + line = strdup(string); /* so we can change it */ + + keyname = strchr(line, '['); + if (!keyname) + return; + ++keyname; + + subkeyname = strchr(keyname, ']'); + if (!subkeyname) + return; + *subkeyname++='\0'; + delim = strchr(subkeyname, '\n'); + if (delim) + *delim = '\0'; + + result = RegOpenKeyEx(hkey_root, + keyname, + 0, + KEY_WRITE, + &hKey); + + if (result != ERROR_SUCCESS) + MessageBox(GetFocus(), string, "Could not open key", MB_OK); + else { + result = RegDeleteKey(hKey, subkeyname); + if (result != ERROR_SUCCESS && result != ERROR_FILE_NOT_FOUND) + MessageBox(GetFocus(), string, "Could not delete key", MB_OK); + RegCloseKey(hKey); + } + free(line); } void DeleteRegistryValue(char *string) { - char *keyname; - char *valuename; - char *value; - HKEY hKey; - long result; - char *line; + char *keyname; + char *valuename; + char *value; + HKEY hKey; + long result; + char *line; - line = strdup(string); /* so we can change it */ + line = strdup(string); /* so we can change it */ /* Format is 'Reg DB Value: [key]name=value' */ - keyname = strchr(line, '['); - if (!keyname) - return; - ++keyname; - valuename = strchr(keyname, ']'); - if (!valuename) - return; - *valuename++ = '\0'; - value = strchr(valuename, '='); - if (!value) - return; - - *value++ = '\0'; - - result = RegOpenKeyEx(hkey_root, - keyname, - 0, - KEY_WRITE, - &hKey); - if (result != ERROR_SUCCESS) - MessageBox(GetFocus(), string, "Could not open key", MB_OK); - else { - result = RegDeleteValue(hKey, valuename); - if (result != ERROR_SUCCESS && result != ERROR_FILE_NOT_FOUND) - MessageBox(GetFocus(), string, "Could not delete value", MB_OK); - RegCloseKey(hKey); - } - free(line); + keyname = strchr(line, '['); + if (!keyname) + return; + ++keyname; + valuename = strchr(keyname, ']'); + if (!valuename) + return; + *valuename++ = '\0'; + value = strchr(valuename, '='); + if (!value) + return; + + *value++ = '\0'; + + result = RegOpenKeyEx(hkey_root, + keyname, + 0, + KEY_WRITE, + &hKey); + if (result != ERROR_SUCCESS) + MessageBox(GetFocus(), string, "Could not open key", MB_OK); + else { + result = RegDeleteValue(hKey, valuename); + if (result != ERROR_SUCCESS && result != ERROR_FILE_NOT_FOUND) + MessageBox(GetFocus(), string, "Could not delete value", MB_OK); + RegCloseKey(hKey); + } + free(line); } BOOL MyDeleteFile(char *line) { - char *pathname = strchr(line, ':'); - if (!pathname) - return FALSE; - ++pathname; - while (isspace(*pathname)) - ++pathname; - return DeleteFile(pathname); + char *pathname = strchr(line, ':'); + if (!pathname) + return FALSE; + ++pathname; + while (isspace(*pathname)) + ++pathname; + return DeleteFile(pathname); } BOOL MyRemoveDirectory(char *line) { - char *pathname = strchr(line, ':'); - if (!pathname) - return FALSE; - ++pathname; - while (isspace(*pathname)) - ++pathname; - return RemoveDirectory(pathname); + char *pathname = strchr(line, ':'); + if (!pathname) + return FALSE; + ++pathname; + while (isspace(*pathname)) + ++pathname; + return RemoveDirectory(pathname); } BOOL Run_RemoveScript(char *line) { - char *dllname; - char *scriptname; - static char lastscript[MAX_PATH]; + char *dllname; + char *scriptname; + static char lastscript[MAX_PATH]; /* Format is 'Run Scripts: [pythondll]scriptname' */ /* XXX Currently, pythondll carries no path!!! */ - dllname = strchr(line, '['); - if (!dllname) - return FALSE; - ++dllname; - scriptname = strchr(dllname, ']'); - if (!scriptname) - return FALSE; - *scriptname++ = '\0'; - /* this function may be called more than one time with the same - script, only run it one time */ - if (strcmp(lastscript, scriptname)) { - char *argv[3] = {NULL, "-remove", NULL}; - char *buffer = NULL; - - argv[0] = scriptname; - - if (0 != run_installscript(scriptname, 2, argv, &buffer)) - fprintf(stderr, "*** Could not run installation script ***"); - - if (buffer && buffer[0]) - MessageBox(GetFocus(), buffer, "uninstall-script", MB_OK); - free(buffer); - - strcpy(lastscript, scriptname); - } - return TRUE; + dllname = strchr(line, '['); + if (!dllname) + return FALSE; + ++dllname; + scriptname = strchr(dllname, ']'); + if (!scriptname) + return FALSE; + *scriptname++ = '\0'; + /* this function may be called more than one time with the same + script, only run it one time */ + if (strcmp(lastscript, scriptname)) { + char *argv[3] = {NULL, "-remove", NULL}; + char *buffer = NULL; + + argv[0] = scriptname; + + if (0 != run_installscript(scriptname, 2, argv, &buffer)) + fprintf(stderr, "*** Could not run installation script ***"); + + if (buffer && buffer[0]) + MessageBox(GetFocus(), buffer, "uninstall-script", MB_OK); + free(buffer); + + strcpy(lastscript, scriptname); + } + return TRUE; } int DoUninstall(int argc, char **argv) { - FILE *logfile; - char buffer[4096]; - int nLines = 0; - int i; - char *cp; - int nFiles = 0; - int nDirs = 0; - int nErrors = 0; - char **lines; - int lines_buffer_size = 10; - - if (argc != 3) { - MessageBox(NULL, - "Wrong number of args", - NULL, - MB_OK); - return 1; /* Error */ - } - if (strcmp(argv[1], "-u")) { - MessageBox(NULL, - "2. arg is not -u", - NULL, - MB_OK); - return 1; /* Error */ - } - - logfile = fopen(argv[2], "r"); - if (!logfile) { - MessageBox(NULL, - "could not open logfile", - NULL, - MB_OK); - return 1; /* Error */ - } - - lines = (char **)malloc(sizeof(char *) * lines_buffer_size); - if (!lines) - return SystemError(0, "Out of memory"); - - /* Read the whole logfile, realloacting the buffer */ - while (fgets(buffer, sizeof(buffer), logfile)) { - int len = strlen(buffer); - /* remove trailing white space */ - while (isspace(buffer[len-1])) - len -= 1; - buffer[len] = '\0'; - lines[nLines++] = strdup(buffer); - if (nLines >= lines_buffer_size) { - lines_buffer_size += 10; - lines = (char **)realloc(lines, - sizeof(char *) * lines_buffer_size); - if (!lines) - return SystemError(0, "Out of memory"); - } - } - fclose(logfile); - - /* Sort all the lines, so that highest 3-digit codes are first */ - qsort(&lines[0], nLines, sizeof(char *), - compare); - - if (IDYES != MessageBox(NULL, - "Are you sure you want to remove\n" - "this package from your computer?", - "Please confirm", - MB_YESNO | MB_ICONQUESTION)) - return 0; - - hkey_root = HKEY_LOCAL_MACHINE; - cp = ""; - for (i = 0; i < nLines; ++i) { - /* Ignore duplicate lines */ - if (strcmp(cp, lines[i])) { - int ign; - cp = lines[i]; - /* Parse the lines */ - if (2 == sscanf(cp, "%d Root Key: %s", &ign, &buffer)) { - if (strcmp(buffer, "HKEY_CURRENT_USER")==0) - hkey_root = HKEY_CURRENT_USER; - else { - // HKLM - check they have permissions. - if (!HasLocalMachinePrivs()) { - MessageBox(GetFocus(), - "You do not seem to have sufficient access rights\n" - "on this machine to uninstall this software", - NULL, - MB_OK | MB_ICONSTOP); - return 1; /* Error */ - } - } - } else if (2 == sscanf(cp, "%d Made Dir: %s", &ign, &buffer)) { - if (MyRemoveDirectory(cp)) - ++nDirs; - else { - int code = GetLastError(); - if (code != 2 && code != 3) { /* file or path not found */ - ++nErrors; - } - } - } else if (2 == sscanf(cp, "%d File Copy: %s", &ign, &buffer)) { - if (MyDeleteFile(cp)) - ++nFiles; - else { - int code = GetLastError(); - if (code != 2 && code != 3) { /* file or path not found */ - ++nErrors; - } - } - } else if (2 == sscanf(cp, "%d File Overwrite: %s", &ign, &buffer)) { - if (MyDeleteFile(cp)) - ++nFiles; - else { - int code = GetLastError(); - if (code != 2 && code != 3) { /* file or path not found */ - ++nErrors; - } - } - } else if (2 == sscanf(cp, "%d Reg DB Key: %s", &ign, &buffer)) { - DeleteRegistryKey(cp); - } else if (2 == sscanf(cp, "%d Reg DB Value: %s", &ign, &buffer)) { - DeleteRegistryValue(cp); - } else if (2 == sscanf(cp, "%d Run Script: %s", &ign, &buffer)) { - Run_RemoveScript(cp); - } - } - } - - if (DeleteFile(argv[2])) { - ++nFiles; - } else { - ++nErrors; - SystemError(GetLastError(), argv[2]); - } - if (nErrors) - wsprintf(buffer, - "%d files and %d directories removed\n" - "%d files or directories could not be removed", - nFiles, nDirs, nErrors); - else - wsprintf(buffer, "%d files and %d directories removed", - nFiles, nDirs); - MessageBox(NULL, buffer, "Uninstall Finished!", - MB_OK | MB_ICONINFORMATION); - remove_exe(); - return 0; + FILE *logfile; + char buffer[4096]; + int nLines = 0; + int i; + char *cp; + int nFiles = 0; + int nDirs = 0; + int nErrors = 0; + char **lines; + int lines_buffer_size = 10; + + if (argc != 3) { + MessageBox(NULL, + "Wrong number of args", + NULL, + MB_OK); + return 1; /* Error */ + } + if (strcmp(argv[1], "-u")) { + MessageBox(NULL, + "2. arg is not -u", + NULL, + MB_OK); + return 1; /* Error */ + } + + logfile = fopen(argv[2], "r"); + if (!logfile) { + MessageBox(NULL, + "could not open logfile", + NULL, + MB_OK); + return 1; /* Error */ + } + + lines = (char **)malloc(sizeof(char *) * lines_buffer_size); + if (!lines) + return SystemError(0, "Out of memory"); + + /* Read the whole logfile, realloacting the buffer */ + while (fgets(buffer, sizeof(buffer), logfile)) { + int len = strlen(buffer); + /* remove trailing white space */ + while (isspace(buffer[len-1])) + len -= 1; + buffer[len] = '\0'; + lines[nLines++] = strdup(buffer); + if (nLines >= lines_buffer_size) { + lines_buffer_size += 10; + lines = (char **)realloc(lines, + sizeof(char *) * lines_buffer_size); + if (!lines) + return SystemError(0, "Out of memory"); + } + } + fclose(logfile); + + /* Sort all the lines, so that highest 3-digit codes are first */ + qsort(&lines[0], nLines, sizeof(char *), + compare); + + if (IDYES != MessageBox(NULL, + "Are you sure you want to remove\n" + "this package from your computer?", + "Please confirm", + MB_YESNO | MB_ICONQUESTION)) + return 0; + + hkey_root = HKEY_LOCAL_MACHINE; + cp = ""; + for (i = 0; i < nLines; ++i) { + /* Ignore duplicate lines */ + if (strcmp(cp, lines[i])) { + int ign; + cp = lines[i]; + /* Parse the lines */ + if (2 == sscanf(cp, "%d Root Key: %s", &ign, &buffer)) { + if (strcmp(buffer, "HKEY_CURRENT_USER")==0) + hkey_root = HKEY_CURRENT_USER; + else { + // HKLM - check they have permissions. + if (!HasLocalMachinePrivs()) { + MessageBox(GetFocus(), + "You do not seem to have sufficient access rights\n" + "on this machine to uninstall this software", + NULL, + MB_OK | MB_ICONSTOP); + return 1; /* Error */ + } + } + } else if (2 == sscanf(cp, "%d Made Dir: %s", &ign, &buffer)) { + if (MyRemoveDirectory(cp)) + ++nDirs; + else { + int code = GetLastError(); + if (code != 2 && code != 3) { /* file or path not found */ + ++nErrors; + } + } + } else if (2 == sscanf(cp, "%d File Copy: %s", &ign, &buffer)) { + if (MyDeleteFile(cp)) + ++nFiles; + else { + int code = GetLastError(); + if (code != 2 && code != 3) { /* file or path not found */ + ++nErrors; + } + } + } else if (2 == sscanf(cp, "%d File Overwrite: %s", &ign, &buffer)) { + if (MyDeleteFile(cp)) + ++nFiles; + else { + int code = GetLastError(); + if (code != 2 && code != 3) { /* file or path not found */ + ++nErrors; + } + } + } else if (2 == sscanf(cp, "%d Reg DB Key: %s", &ign, &buffer)) { + DeleteRegistryKey(cp); + } else if (2 == sscanf(cp, "%d Reg DB Value: %s", &ign, &buffer)) { + DeleteRegistryValue(cp); + } else if (2 == sscanf(cp, "%d Run Script: %s", &ign, &buffer)) { + Run_RemoveScript(cp); + } + } + } + + if (DeleteFile(argv[2])) { + ++nFiles; + } else { + ++nErrors; + SystemError(GetLastError(), argv[2]); + } + if (nErrors) + wsprintf(buffer, + "%d files and %d directories removed\n" + "%d files or directories could not be removed", + nFiles, nDirs, nErrors); + else + wsprintf(buffer, "%d files and %d directories removed", + nFiles, nDirs); + MessageBox(NULL, buffer, "Uninstall Finished!", + MB_OK | MB_ICONINFORMATION); + remove_exe(); + return 0; } int WINAPI WinMain(HINSTANCE hInst, HINSTANCE hPrevInst, - LPSTR lpszCmdLine, INT nCmdShow) + LPSTR lpszCmdLine, INT nCmdShow) { - extern int __argc; - extern char **__argv; - char *basename; - - GetModuleFileName(NULL, modulename, sizeof(modulename)); - GetModuleFileNameW(NULL, wmodulename, sizeof(wmodulename)/sizeof(wmodulename[0])); - - /* Map the executable file to memory */ - arc_data = MapExistingFile(modulename, &arc_size); - if (!arc_data) { - SystemError(GetLastError(), "Could not open archive"); - return 1; - } - - /* OK. So this program can act as installer (self-extracting - * zip-file, or as uninstaller when started with '-u logfile' - * command line flags. - * - * The installer is usually started without command line flags, - * and the uninstaller is usually started with the '-u logfile' - * flag. What to do if some innocent user double-clicks the - * exe-file? - * The following implements a defensive strategy... - */ - - /* Try to extract the configuration data into a temporary file */ - if (ExtractInstallData(arc_data, arc_size, &exe_size, - &ini_file, &pre_install_script)) - return DoInstall(); - - if (!ini_file && __argc > 1) { - return DoUninstall(__argc, __argv); - } - - - basename = strrchr(modulename, '\\'); - if (basename) - ++basename; - - /* Last guess about the purpose of this program */ - if (basename && (0 == strncmp(basename, "Remove", 6))) - SystemError(0, "This program is normally started by windows"); - else - SystemError(0, "Setup program invalid or damaged"); - return 1; + extern int __argc; + extern char **__argv; + char *basename; + + GetModuleFileName(NULL, modulename, sizeof(modulename)); + GetModuleFileNameW(NULL, wmodulename, sizeof(wmodulename)/sizeof(wmodulename[0])); + + /* Map the executable file to memory */ + arc_data = MapExistingFile(modulename, &arc_size); + if (!arc_data) { + SystemError(GetLastError(), "Could not open archive"); + return 1; + } + + /* OK. So this program can act as installer (self-extracting + * zip-file, or as uninstaller when started with '-u logfile' + * command line flags. + * + * The installer is usually started without command line flags, + * and the uninstaller is usually started with the '-u logfile' + * flag. What to do if some innocent user double-clicks the + * exe-file? + * The following implements a defensive strategy... + */ + + /* Try to extract the configuration data into a temporary file */ + if (ExtractInstallData(arc_data, arc_size, &exe_size, + &ini_file, &pre_install_script)) + return DoInstall(); + + if (!ini_file && __argc > 1) { + return DoUninstall(__argc, __argv); + } + + + basename = strrchr(modulename, '\\'); + if (basename) + ++basename; + + /* Last guess about the purpose of this program */ + if (basename && (0 == strncmp(basename, "Remove", 6))) + SystemError(0, "This program is normally started by windows"); + else + SystemError(0, "Setup program invalid or damaged"); + return 1; } Modified: python/branches/py3k/PC/config.c ============================================================================== --- python/branches/py3k/PC/config.c (original) +++ python/branches/py3k/PC/config.c Sun May 9 17:52:27 2010 @@ -71,87 +71,87 @@ struct _inittab _PyImport_Inittab[] = { - {"array", PyInit_array}, - {"_ast", PyInit__ast}, + {"array", PyInit_array}, + {"_ast", PyInit__ast}, #ifdef MS_WINDOWS #ifndef MS_WINI64 - {"audioop", PyInit_audioop}, + {"audioop", PyInit_audioop}, #endif #endif - {"binascii", PyInit_binascii}, - {"cmath", PyInit_cmath}, - {"errno", PyInit_errno}, - {"gc", PyInit_gc}, - {"math", PyInit_math}, - {"nt", PyInit_nt}, /* Use the NT os functions, not posix */ - {"operator", PyInit_operator}, - {"signal", PyInit_signal}, - {"_md5", PyInit__md5}, - {"_sha1", PyInit__sha1}, - {"_sha256", PyInit__sha256}, - {"_sha512", PyInit__sha512}, - {"time", PyInit_time}, + {"binascii", PyInit_binascii}, + {"cmath", PyInit_cmath}, + {"errno", PyInit_errno}, + {"gc", PyInit_gc}, + {"math", PyInit_math}, + {"nt", PyInit_nt}, /* Use the NT os functions, not posix */ + {"operator", PyInit_operator}, + {"signal", PyInit_signal}, + {"_md5", PyInit__md5}, + {"_sha1", PyInit__sha1}, + {"_sha256", PyInit__sha256}, + {"_sha512", PyInit__sha512}, + {"time", PyInit_time}, #ifdef WITH_THREAD - {"_thread", PyInit__thread}, + {"_thread", PyInit__thread}, #endif #ifdef WIN32 - {"msvcrt", PyInit_msvcrt}, - {"_locale", PyInit__locale}, + {"msvcrt", PyInit_msvcrt}, + {"_locale", PyInit__locale}, #endif - /* XXX Should _subprocess go in a WIN32 block? not WIN64? */ - {"_subprocess", PyInit__subprocess}, + /* XXX Should _subprocess go in a WIN32 block? not WIN64? */ + {"_subprocess", PyInit__subprocess}, - {"_codecs", PyInit__codecs}, - {"_weakref", PyInit__weakref}, - {"_random", PyInit__random}, - {"_bisect", PyInit__bisect}, - {"_heapq", PyInit__heapq}, - {"_lsprof", PyInit__lsprof}, - {"itertools", PyInit_itertools}, - {"_collections", PyInit__collections}, - {"_symtable", PyInit__symtable}, - {"mmap", PyInit_mmap}, - {"_csv", PyInit__csv}, - {"_sre", PyInit__sre}, - {"parser", PyInit_parser}, - {"winreg", PyInit_winreg}, - {"_struct", PyInit__struct}, - {"datetime", PyInit_datetime}, - {"_functools", PyInit__functools}, - {"_json", PyInit__json}, - - {"xxsubtype", PyInit_xxsubtype}, - {"zipimport", PyInit_zipimport}, - {"zlib", PyInit_zlib}, - - /* CJK codecs */ - {"_multibytecodec", PyInit__multibytecodec}, - {"_codecs_cn", PyInit__codecs_cn}, - {"_codecs_hk", PyInit__codecs_hk}, - {"_codecs_iso2022", PyInit__codecs_iso2022}, - {"_codecs_jp", PyInit__codecs_jp}, - {"_codecs_kr", PyInit__codecs_kr}, - {"_codecs_tw", PyInit__codecs_tw}, + {"_codecs", PyInit__codecs}, + {"_weakref", PyInit__weakref}, + {"_random", PyInit__random}, + {"_bisect", PyInit__bisect}, + {"_heapq", PyInit__heapq}, + {"_lsprof", PyInit__lsprof}, + {"itertools", PyInit_itertools}, + {"_collections", PyInit__collections}, + {"_symtable", PyInit__symtable}, + {"mmap", PyInit_mmap}, + {"_csv", PyInit__csv}, + {"_sre", PyInit__sre}, + {"parser", PyInit_parser}, + {"winreg", PyInit_winreg}, + {"_struct", PyInit__struct}, + {"datetime", PyInit_datetime}, + {"_functools", PyInit__functools}, + {"_json", PyInit__json}, + + {"xxsubtype", PyInit_xxsubtype}, + {"zipimport", PyInit_zipimport}, + {"zlib", PyInit_zlib}, + + /* CJK codecs */ + {"_multibytecodec", PyInit__multibytecodec}, + {"_codecs_cn", PyInit__codecs_cn}, + {"_codecs_hk", PyInit__codecs_hk}, + {"_codecs_iso2022", PyInit__codecs_iso2022}, + {"_codecs_jp", PyInit__codecs_jp}, + {"_codecs_kr", PyInit__codecs_kr}, + {"_codecs_tw", PyInit__codecs_tw}, /* tools/freeze/makeconfig.py marker for additional "_inittab" entries */ /* -- ADDMODULE MARKER 2 -- */ - /* This module "lives in" with marshal.c */ - {"marshal", PyMarshal_Init}, + /* This module "lives in" with marshal.c */ + {"marshal", PyMarshal_Init}, - /* This lives it with import.c */ - {"imp", PyInit_imp}, + /* This lives it with import.c */ + {"imp", PyInit_imp}, - /* These entries are here for sys.builtin_module_names */ - {"__main__", NULL}, - {"builtins", NULL}, - {"sys", NULL}, - {"_warnings", _PyWarnings_Init}, - - {"_io", PyInit__io}, - {"_pickle", PyInit__pickle}, - {"atexit", PyInit_atexit}, + /* These entries are here for sys.builtin_module_names */ + {"__main__", NULL}, + {"builtins", NULL}, + {"sys", NULL}, + {"_warnings", _PyWarnings_Init}, + + {"_io", PyInit__io}, + {"_pickle", PyInit__pickle}, + {"atexit", PyInit_atexit}, - /* Sentinel */ - {0, 0} + /* Sentinel */ + {0, 0} }; Modified: python/branches/py3k/PC/dl_nt.c ============================================================================== --- python/branches/py3k/PC/dl_nt.c (original) +++ python/branches/py3k/PC/dl_nt.c Sun May 9 17:52:27 2010 @@ -3,7 +3,7 @@ Entry point for the Windows NT DLL. About the only reason for having this, is so initall() can automatically -be called, removing that burden (and possible source of frustration if +be called, removing that burden (and possible source of frustration if forgotten) from the programmer. */ @@ -46,61 +46,61 @@ void _LoadActCtxPointers() { - HINSTANCE hKernel32 = GetModuleHandleW(L"kernel32.dll"); - if (hKernel32) - pfnGetCurrentActCtx = (PFN_GETCURRENTACTCTX) GetProcAddress(hKernel32, "GetCurrentActCtx"); - // If we can't load GetCurrentActCtx (ie, pre XP) , don't bother with the rest. - if (pfnGetCurrentActCtx) { - pfnActivateActCtx = (PFN_ACTIVATEACTCTX) GetProcAddress(hKernel32, "ActivateActCtx"); - pfnDeactivateActCtx = (PFN_DEACTIVATEACTCTX) GetProcAddress(hKernel32, "DeactivateActCtx"); - pfnAddRefActCtx = (PFN_ADDREFACTCTX) GetProcAddress(hKernel32, "AddRefActCtx"); - pfnReleaseActCtx = (PFN_RELEASEACTCTX) GetProcAddress(hKernel32, "ReleaseActCtx"); - } + HINSTANCE hKernel32 = GetModuleHandleW(L"kernel32.dll"); + if (hKernel32) + pfnGetCurrentActCtx = (PFN_GETCURRENTACTCTX) GetProcAddress(hKernel32, "GetCurrentActCtx"); + // If we can't load GetCurrentActCtx (ie, pre XP) , don't bother with the rest. + if (pfnGetCurrentActCtx) { + pfnActivateActCtx = (PFN_ACTIVATEACTCTX) GetProcAddress(hKernel32, "ActivateActCtx"); + pfnDeactivateActCtx = (PFN_DEACTIVATEACTCTX) GetProcAddress(hKernel32, "DeactivateActCtx"); + pfnAddRefActCtx = (PFN_ADDREFACTCTX) GetProcAddress(hKernel32, "AddRefActCtx"); + pfnReleaseActCtx = (PFN_RELEASEACTCTX) GetProcAddress(hKernel32, "ReleaseActCtx"); + } } ULONG_PTR _Py_ActivateActCtx() { - ULONG_PTR ret = 0; - if (PyWin_DLLhActivationContext && pfnActivateActCtx) - if (!(*pfnActivateActCtx)(PyWin_DLLhActivationContext, &ret)) { - OutputDebugString("Python failed to activate the activation context before loading a DLL\n"); - ret = 0; // no promise the failing function didn't change it! - } - return ret; + ULONG_PTR ret = 0; + if (PyWin_DLLhActivationContext && pfnActivateActCtx) + if (!(*pfnActivateActCtx)(PyWin_DLLhActivationContext, &ret)) { + OutputDebugString("Python failed to activate the activation context before loading a DLL\n"); + ret = 0; // no promise the failing function didn't change it! + } + return ret; } void _Py_DeactivateActCtx(ULONG_PTR cookie) { - if (cookie && pfnDeactivateActCtx) - if (!(*pfnDeactivateActCtx)(0, cookie)) - OutputDebugString("Python failed to de-activate the activation context\n"); + if (cookie && pfnDeactivateActCtx) + if (!(*pfnDeactivateActCtx)(0, cookie)) + OutputDebugString("Python failed to de-activate the activation context\n"); } -BOOL WINAPI DllMain (HANDLE hInst, - ULONG ul_reason_for_call, - LPVOID lpReserved) +BOOL WINAPI DllMain (HANDLE hInst, + ULONG ul_reason_for_call, + LPVOID lpReserved) { - switch (ul_reason_for_call) - { - case DLL_PROCESS_ATTACH: - PyWin_DLLhModule = hInst; - // 1000 is a magic number I picked out of the air. Could do with a #define, I spose... - LoadString(hInst, 1000, dllVersionBuffer, sizeof(dllVersionBuffer)); - - // and capture our activation context for use when loading extensions. - _LoadActCtxPointers(); - if (pfnGetCurrentActCtx && pfnAddRefActCtx) - if ((*pfnGetCurrentActCtx)(&PyWin_DLLhActivationContext)) - if (!(*pfnAddRefActCtx)(PyWin_DLLhActivationContext)) - OutputDebugString("Python failed to load the default activation context\n"); - break; - - case DLL_PROCESS_DETACH: - if (pfnReleaseActCtx) - (*pfnReleaseActCtx)(PyWin_DLLhActivationContext); - break; - } - return TRUE; + switch (ul_reason_for_call) + { + case DLL_PROCESS_ATTACH: + PyWin_DLLhModule = hInst; + // 1000 is a magic number I picked out of the air. Could do with a #define, I spose... + LoadString(hInst, 1000, dllVersionBuffer, sizeof(dllVersionBuffer)); + + // and capture our activation context for use when loading extensions. + _LoadActCtxPointers(); + if (pfnGetCurrentActCtx && pfnAddRefActCtx) + if ((*pfnGetCurrentActCtx)(&PyWin_DLLhActivationContext)) + if (!(*pfnAddRefActCtx)(PyWin_DLLhActivationContext)) + OutputDebugString("Python failed to load the default activation context\n"); + break; + + case DLL_PROCESS_DETACH: + if (pfnReleaseActCtx) + (*pfnReleaseActCtx)(PyWin_DLLhActivationContext); + break; + } + return TRUE; } #endif /* Py_ENABLE_SHARED */ Modified: python/branches/py3k/PC/errmap.h ============================================================================== --- python/branches/py3k/PC/errmap.h (original) +++ python/branches/py3k/PC/errmap.h Sun May 9 17:52:27 2010 @@ -1,78 +1,78 @@ /* Generated file. Do not edit. */ int winerror_to_errno(int winerror) { - switch(winerror) { - case 2: return 2; - case 3: return 2; - case 4: return 24; - case 5: return 13; - case 6: return 9; - case 7: return 12; - case 8: return 12; - case 9: return 12; - case 10: return 7; - case 11: return 8; - case 15: return 2; - case 16: return 13; - case 17: return 18; - case 18: return 2; - case 19: return 13; - case 20: return 13; - case 21: return 13; - case 22: return 13; - case 23: return 13; - case 24: return 13; - case 25: return 13; - case 26: return 13; - case 27: return 13; - case 28: return 13; - case 29: return 13; - case 30: return 13; - case 31: return 13; - case 32: return 13; - case 33: return 13; - case 34: return 13; - case 35: return 13; - case 36: return 13; - case 53: return 2; - case 65: return 13; - case 67: return 2; - case 80: return 17; - case 82: return 13; - case 83: return 13; - case 89: return 11; - case 108: return 13; - case 109: return 32; - case 112: return 28; - case 114: return 9; - case 128: return 10; - case 129: return 10; - case 130: return 9; - case 132: return 13; - case 145: return 41; - case 158: return 13; - case 161: return 2; - case 164: return 11; - case 167: return 13; - case 183: return 17; - case 188: return 8; - case 189: return 8; - case 190: return 8; - case 191: return 8; - case 192: return 8; - case 193: return 8; - case 194: return 8; - case 195: return 8; - case 196: return 8; - case 197: return 8; - case 198: return 8; - case 199: return 8; - case 200: return 8; - case 201: return 8; - case 202: return 8; - case 206: return 2; - case 215: return 11; - case 1816: return 12; - default: return EINVAL; - } + switch(winerror) { + case 2: return 2; + case 3: return 2; + case 4: return 24; + case 5: return 13; + case 6: return 9; + case 7: return 12; + case 8: return 12; + case 9: return 12; + case 10: return 7; + case 11: return 8; + case 15: return 2; + case 16: return 13; + case 17: return 18; + case 18: return 2; + case 19: return 13; + case 20: return 13; + case 21: return 13; + case 22: return 13; + case 23: return 13; + case 24: return 13; + case 25: return 13; + case 26: return 13; + case 27: return 13; + case 28: return 13; + case 29: return 13; + case 30: return 13; + case 31: return 13; + case 32: return 13; + case 33: return 13; + case 34: return 13; + case 35: return 13; + case 36: return 13; + case 53: return 2; + case 65: return 13; + case 67: return 2; + case 80: return 17; + case 82: return 13; + case 83: return 13; + case 89: return 11; + case 108: return 13; + case 109: return 32; + case 112: return 28; + case 114: return 9; + case 128: return 10; + case 129: return 10; + case 130: return 9; + case 132: return 13; + case 145: return 41; + case 158: return 13; + case 161: return 2; + case 164: return 11; + case 167: return 13; + case 183: return 17; + case 188: return 8; + case 189: return 8; + case 190: return 8; + case 191: return 8; + case 192: return 8; + case 193: return 8; + case 194: return 8; + case 195: return 8; + case 196: return 8; + case 197: return 8; + case 198: return 8; + case 199: return 8; + case 200: return 8; + case 201: return 8; + case 202: return 8; + case 206: return 2; + case 215: return 11; + case 1816: return 12; + default: return EINVAL; + } } Modified: python/branches/py3k/PC/example_nt/example.c ============================================================================== --- python/branches/py3k/PC/example_nt/example.c (original) +++ python/branches/py3k/PC/example_nt/example.c Sun May 9 17:52:27 2010 @@ -3,30 +3,30 @@ static PyObject * ex_foo(PyObject *self, PyObject *args) { - printf("Hello, world\n"); - Py_INCREF(Py_None); - return Py_None; + printf("Hello, world\n"); + Py_INCREF(Py_None); + return Py_None; } static PyMethodDef example_methods[] = { - {"foo", ex_foo, METH_VARARGS, "foo() doc string"}, - {NULL, NULL} + {"foo", ex_foo, METH_VARARGS, "foo() doc string"}, + {NULL, NULL} }; static struct PyModuleDef examplemodule = { - PyModuleDef_HEAD_INIT, - "example", - "example module doc string", - -1, - example_methods, - NULL, - NULL, - NULL, - NULL + PyModuleDef_HEAD_INIT, + "example", + "example module doc string", + -1, + example_methods, + NULL, + NULL, + NULL, + NULL }; PyMODINIT_FUNC PyInit_example(void) { - return PyModule_Create(&examplemodule); + return PyModule_Create(&examplemodule); } Modified: python/branches/py3k/PC/frozen_dllmain.c ============================================================================== --- python/branches/py3k/PC/frozen_dllmain.c (original) +++ python/branches/py3k/PC/frozen_dllmain.c Sun May 9 17:52:27 2010 @@ -9,7 +9,7 @@ The solution is: * Each module checks for a frozen build, and if so, defines its DLLMain - function as "__declspec(dllexport) DllMain%module%" + function as "__declspec(dllexport) DllMain%module%" (eg, DllMainpythoncom, or DllMainpywintypes) * The frozen .EXE/.DLL links against this module, which provides @@ -47,10 +47,10 @@ #include "windows.h" static char *possibleModules[] = { - "pywintypes", - "pythoncom", - "win32ui", - NULL, + "pywintypes", + "pythoncom", + "win32ui", + NULL, }; BOOL CallModuleDllMain(char *modName, DWORD dwReason); @@ -62,73 +62,73 @@ */ void PyWinFreeze_ExeInit(void) { - char **modName; - for (modName = possibleModules;*modName;*modName++) { -/* printf("Initialising '%s'\n", *modName); */ - CallModuleDllMain(*modName, DLL_PROCESS_ATTACH); - } + char **modName; + for (modName = possibleModules;*modName;*modName++) { +/* printf("Initialising '%s'\n", *modName); */ + CallModuleDllMain(*modName, DLL_PROCESS_ATTACH); + } } /* Called by a frozen .EXE only, so that built-in extension - modules are cleaned up + modules are cleaned up */ void PyWinFreeze_ExeTerm(void) { - // Must go backwards - char **modName; - for (modName = possibleModules+(sizeof(possibleModules) / sizeof(char *))-2; - modName >= possibleModules; - *modName--) { -/* printf("Terminating '%s'\n", *modName);*/ - CallModuleDllMain(*modName, DLL_PROCESS_DETACH); - } + // Must go backwards + char **modName; + for (modName = possibleModules+(sizeof(possibleModules) / sizeof(char *))-2; + modName >= possibleModules; + *modName--) { +/* printf("Terminating '%s'\n", *modName);*/ + CallModuleDllMain(*modName, DLL_PROCESS_DETACH); + } } BOOL WINAPI DllMain(HINSTANCE hInstance, DWORD dwReason, LPVOID lpReserved) { - BOOL ret = TRUE; - switch (dwReason) { - case DLL_PROCESS_ATTACH: - { - char **modName; - for (modName = possibleModules;*modName;*modName++) { - BOOL ok = CallModuleDllMain(*modName, dwReason); - if (!ok) - ret = FALSE; - } - break; - } - case DLL_PROCESS_DETACH: - { - // Must go backwards - char **modName; - for (modName = possibleModules+(sizeof(possibleModules) / sizeof(char *))-2; - modName >= possibleModules; - *modName--) - CallModuleDllMain(*modName, DLL_PROCESS_DETACH); - break; - } - } - return ret; + BOOL ret = TRUE; + switch (dwReason) { + case DLL_PROCESS_ATTACH: + { + char **modName; + for (modName = possibleModules;*modName;*modName++) { + BOOL ok = CallModuleDllMain(*modName, dwReason); + if (!ok) + ret = FALSE; + } + break; + } + case DLL_PROCESS_DETACH: + { + // Must go backwards + char **modName; + for (modName = possibleModules+(sizeof(possibleModules) / sizeof(char *))-2; + modName >= possibleModules; + *modName--) + CallModuleDllMain(*modName, DLL_PROCESS_DETACH); + break; + } + } + return ret; } BOOL CallModuleDllMain(char *modName, DWORD dwReason) { - BOOL (WINAPI * pfndllmain)(HINSTANCE, DWORD, LPVOID); + BOOL (WINAPI * pfndllmain)(HINSTANCE, DWORD, LPVOID); - char funcName[255]; - HMODULE hmod = GetModuleHandle(NULL); - strcpy(funcName, "_DllMain"); - strcat(funcName, modName); - strcat(funcName, "@12"); // stdcall convention. - pfndllmain = (BOOL (WINAPI *)(HINSTANCE, DWORD, LPVOID))GetProcAddress(hmod, funcName); - if (pfndllmain==NULL) { - /* No function by that name exported - then that module does - not appear in our frozen program - return OK - */ - return TRUE; - } - return (*pfndllmain)(hmod, dwReason, NULL); + char funcName[255]; + HMODULE hmod = GetModuleHandle(NULL); + strcpy(funcName, "_DllMain"); + strcat(funcName, modName); + strcat(funcName, "@12"); // stdcall convention. + pfndllmain = (BOOL (WINAPI *)(HINSTANCE, DWORD, LPVOID))GetProcAddress(hmod, funcName); + if (pfndllmain==NULL) { + /* No function by that name exported - then that module does + not appear in our frozen program - return OK + */ + return TRUE; + } + return (*pfndllmain)(hmod, dwReason, NULL); } Modified: python/branches/py3k/PC/generrmap.c ============================================================================== --- python/branches/py3k/PC/generrmap.c (original) +++ python/branches/py3k/PC/generrmap.c Sun May 9 17:52:27 2010 @@ -5,16 +5,16 @@ int main() { - int i; - printf("/* Generated file. Do not edit. */\n"); - printf("int winerror_to_errno(int winerror)\n"); - printf("{\n\tswitch(winerror) {\n"); - for(i=1; i < 65000; i++) { - _dosmaperr(i); - if (errno == EINVAL) - continue; - printf("\t\tcase %d: return %d;\n", i, errno); - } - printf("\t\tdefault: return EINVAL;\n"); - printf("\t}\n}\n"); + int i; + printf("/* Generated file. Do not edit. */\n"); + printf("int winerror_to_errno(int winerror)\n"); + printf("{\n\tswitch(winerror) {\n"); + for(i=1; i < 65000; i++) { + _dosmaperr(i); + if (errno == EINVAL) + continue; + printf("\t\tcase %d: return %d;\n", i, errno); + } + printf("\t\tdefault: return EINVAL;\n"); + printf("\t}\n}\n"); } Modified: python/branches/py3k/PC/getpathp.c ============================================================================== --- python/branches/py3k/PC/getpathp.c (original) +++ python/branches/py3k/PC/getpathp.c Sun May 9 17:52:27 2010 @@ -4,8 +4,8 @@ /* ---------------------------------------------------------------- PATH RULES FOR WINDOWS: - This describes how sys.path is formed on Windows. It describes the - functionality, not the implementation (ie, the order in which these + This describes how sys.path is formed on Windows. It describes the + functionality, not the implementation (ie, the order in which these are actually fetched is different) * Python always adds an empty entry at the start, which corresponds @@ -24,15 +24,15 @@ * We attempt to locate the "Python Home" - if the PYTHONHOME env var is set, we believe it. Otherwise, we use the path of our host .EXE's to try and locate our "landmark" (lib\\os.py) and deduce our home. - - If we DO have a Python Home: The relevant sub-directories (Lib, + - If we DO have a Python Home: The relevant sub-directories (Lib, plat-win, etc) are based on the Python Home - If we DO NOT have a Python Home, the core Python Path is - loaded from the registry. This is the main PythonPath key, + loaded from the registry. This is the main PythonPath key, and both HKLM and HKCU are combined to form the path) * Iff - we can not locate the Python Home, have not had a PYTHONPATH specified, and can't locate any Registry entries (ie, we have _nothing_ - we can assume is a good path), a default path with relative entries is + we can assume is a good path), a default path with relative entries is used (eg. .\Lib;.\plat-win, etc) @@ -42,9 +42,9 @@ the core path is deduced, and the core paths in the registry are ignored. Other "application paths" in the registry are always read. - * When Python is hosted in another exe (different directory, embedded via + * When Python is hosted in another exe (different directory, embedded via COM, etc), the Python Home will not be deduced, so the core path from - the registry is used. Other "application paths" in the registry are + the registry is used. Other "application paths" in the registry are always read. * If Python can't find its home and there is no registry (eg, frozen @@ -92,12 +92,12 @@ static int -is_sep(wchar_t ch) /* determine if "ch" is a separator character */ +is_sep(wchar_t ch) /* determine if "ch" is a separator character */ { #ifdef ALTSEP - return ch == SEP || ch == ALTSEP; + return ch == SEP || ch == ALTSEP; #else - return ch == SEP; + return ch == SEP; #endif } @@ -107,35 +107,35 @@ static void reduce(wchar_t *dir) { - size_t i = wcslen(dir); - while (i > 0 && !is_sep(dir[i])) - --i; - dir[i] = '\0'; + size_t i = wcslen(dir); + while (i > 0 && !is_sep(dir[i])) + --i; + dir[i] = '\0'; } - + static int exists(wchar_t *filename) { - return GetFileAttributesW(filename) != 0xFFFFFFFF; + return GetFileAttributesW(filename) != 0xFFFFFFFF; } -/* Assumes 'filename' MAXPATHLEN+1 bytes long - +/* Assumes 'filename' MAXPATHLEN+1 bytes long - may extend 'filename' by one character. */ static int -ismodule(wchar_t *filename) /* Is module -- check for .pyc/.pyo too */ +ismodule(wchar_t *filename) /* Is module -- check for .pyc/.pyo too */ { - if (exists(filename)) - return 1; + if (exists(filename)) + return 1; - /* Check for the compiled version of prefix. */ - if (wcslen(filename) < MAXPATHLEN) { - wcscat(filename, Py_OptimizeFlag ? L"o" : L"c"); - if (exists(filename)) - return 1; - } - return 0; + /* Check for the compiled version of prefix. */ + if (wcslen(filename) < MAXPATHLEN) { + wcscat(filename, Py_OptimizeFlag ? L"o" : L"c"); + if (exists(filename)) + return 1; + } + return 0; } /* Add a path component, by appending stuff to buffer. @@ -150,21 +150,21 @@ static void join(wchar_t *buffer, wchar_t *stuff) { - size_t n, k; - if (is_sep(stuff[0])) - n = 0; - else { - n = wcslen(buffer); - if (n > 0 && !is_sep(buffer[n-1]) && n < MAXPATHLEN) - buffer[n++] = SEP; - } - if (n > MAXPATHLEN) - Py_FatalError("buffer overflow in getpathp.c's joinpath()"); - k = wcslen(stuff); - if (n + k > MAXPATHLEN) - k = MAXPATHLEN - n; - wcsncpy(buffer+n, stuff, k); - buffer[n+k] = '\0'; + size_t n, k; + if (is_sep(stuff[0])) + n = 0; + else { + n = wcslen(buffer); + if (n > 0 && !is_sep(buffer[n-1]) && n < MAXPATHLEN) + buffer[n++] = SEP; + } + if (n > MAXPATHLEN) + Py_FatalError("buffer overflow in getpathp.c's joinpath()"); + k = wcslen(stuff); + if (n + k > MAXPATHLEN) + k = MAXPATHLEN - n; + wcsncpy(buffer+n, stuff, k); + buffer[n+k] = '\0'; } /* gotlandmark only called by search_for_prefix, which ensures @@ -174,29 +174,29 @@ static int gotlandmark(wchar_t *landmark) { - int ok; - Py_ssize_t n; + int ok; + Py_ssize_t n; - n = wcslen(prefix); - join(prefix, landmark); - ok = ismodule(prefix); - prefix[n] = '\0'; - return ok; + n = wcslen(prefix); + join(prefix, landmark); + ok = ismodule(prefix); + prefix[n] = '\0'; + return ok; } -/* assumes argv0_path is MAXPATHLEN+1 bytes long, already \0 term'd. +/* assumes argv0_path is MAXPATHLEN+1 bytes long, already \0 term'd. assumption provided by only caller, calculate_path() */ static int search_for_prefix(wchar_t *argv0_path, wchar_t *landmark) { - /* Search from argv0_path, until landmark is found */ - wcscpy(prefix, argv0_path); - do { - if (gotlandmark(landmark)) - return 1; - reduce(prefix); - } while (prefix[0]); - return 0; + /* Search from argv0_path, until landmark is found */ + wcscpy(prefix, argv0_path); + do { + if (gotlandmark(landmark)) + return 1; + reduce(prefix); + } while (prefix[0]); + return 0; } #ifdef MS_WINDOWS @@ -222,133 +222,133 @@ static wchar_t * getpythonregpath(HKEY keyBase, int skipcore) { - HKEY newKey = 0; - DWORD dataSize = 0; - DWORD numKeys = 0; - LONG rc; - wchar_t *retval = NULL; - WCHAR *dataBuf = NULL; - static const WCHAR keyPrefix[] = L"Software\\Python\\PythonCore\\"; - static const WCHAR keySuffix[] = L"\\PythonPath"; - size_t versionLen; - DWORD index; - WCHAR *keyBuf = NULL; - WCHAR *keyBufPtr; - WCHAR **ppPaths = NULL; - - /* Tried to use sysget("winver") but here is too early :-( */ - versionLen = strlen(PyWin_DLLVersionString); - /* Space for all the chars, plus one \0 */ - keyBuf = keyBufPtr = malloc(sizeof(keyPrefix) + - sizeof(WCHAR)*(versionLen-1) + - sizeof(keySuffix)); - if (keyBuf==NULL) goto done; - - memcpy(keyBufPtr, keyPrefix, sizeof(keyPrefix)-sizeof(WCHAR)); - keyBufPtr += sizeof(keyPrefix)/sizeof(WCHAR) - 1; - mbstowcs(keyBufPtr, PyWin_DLLVersionString, versionLen); - keyBufPtr += versionLen; - /* NULL comes with this one! */ - memcpy(keyBufPtr, keySuffix, sizeof(keySuffix)); - /* Open the root Python key */ - rc=RegOpenKeyExW(keyBase, - keyBuf, /* subkey */ - 0, /* reserved */ - KEY_READ, - &newKey); - if (rc!=ERROR_SUCCESS) goto done; - /* Find out how big our core buffer is, and how many subkeys we have */ - rc = RegQueryInfoKey(newKey, NULL, NULL, NULL, &numKeys, NULL, NULL, - NULL, NULL, &dataSize, NULL, NULL); - if (rc!=ERROR_SUCCESS) goto done; - if (skipcore) dataSize = 0; /* Only count core ones if we want them! */ - /* Allocate a temp array of char buffers, so we only need to loop - reading the registry once - */ - ppPaths = malloc( sizeof(WCHAR *) * numKeys ); - if (ppPaths==NULL) goto done; - memset(ppPaths, 0, sizeof(WCHAR *) * numKeys); - /* Loop over all subkeys, allocating a temp sub-buffer. */ - for(index=0;index 0) { - *(szCur++) = L';'; - dataSize--; - } - if (ppPaths[index]) { - Py_ssize_t len = wcslen(ppPaths[index]); - wcsncpy(szCur, ppPaths[index], len); - szCur += len; - assert(dataSize > (DWORD)len); - dataSize -= (DWORD)len; - } - } - if (skipcore) - *szCur = '\0'; - else { - /* If we have no values, we dont need a ';' */ - if (numKeys) { - *(szCur++) = L';'; - dataSize--; - } - /* Now append the core path entries - - this will include the NULL - */ - rc = RegQueryValueExW(newKey, NULL, 0, NULL, - (LPBYTE)szCur, &dataSize); - } - /* And set the result - caller must free */ - retval = dataBuf; - } + HKEY newKey = 0; + DWORD dataSize = 0; + DWORD numKeys = 0; + LONG rc; + wchar_t *retval = NULL; + WCHAR *dataBuf = NULL; + static const WCHAR keyPrefix[] = L"Software\\Python\\PythonCore\\"; + static const WCHAR keySuffix[] = L"\\PythonPath"; + size_t versionLen; + DWORD index; + WCHAR *keyBuf = NULL; + WCHAR *keyBufPtr; + WCHAR **ppPaths = NULL; + + /* Tried to use sysget("winver") but here is too early :-( */ + versionLen = strlen(PyWin_DLLVersionString); + /* Space for all the chars, plus one \0 */ + keyBuf = keyBufPtr = malloc(sizeof(keyPrefix) + + sizeof(WCHAR)*(versionLen-1) + + sizeof(keySuffix)); + if (keyBuf==NULL) goto done; + + memcpy(keyBufPtr, keyPrefix, sizeof(keyPrefix)-sizeof(WCHAR)); + keyBufPtr += sizeof(keyPrefix)/sizeof(WCHAR) - 1; + mbstowcs(keyBufPtr, PyWin_DLLVersionString, versionLen); + keyBufPtr += versionLen; + /* NULL comes with this one! */ + memcpy(keyBufPtr, keySuffix, sizeof(keySuffix)); + /* Open the root Python key */ + rc=RegOpenKeyExW(keyBase, + keyBuf, /* subkey */ + 0, /* reserved */ + KEY_READ, + &newKey); + if (rc!=ERROR_SUCCESS) goto done; + /* Find out how big our core buffer is, and how many subkeys we have */ + rc = RegQueryInfoKey(newKey, NULL, NULL, NULL, &numKeys, NULL, NULL, + NULL, NULL, &dataSize, NULL, NULL); + if (rc!=ERROR_SUCCESS) goto done; + if (skipcore) dataSize = 0; /* Only count core ones if we want them! */ + /* Allocate a temp array of char buffers, so we only need to loop + reading the registry once + */ + ppPaths = malloc( sizeof(WCHAR *) * numKeys ); + if (ppPaths==NULL) goto done; + memset(ppPaths, 0, sizeof(WCHAR *) * numKeys); + /* Loop over all subkeys, allocating a temp sub-buffer. */ + for(index=0;index 0) { + *(szCur++) = L';'; + dataSize--; + } + if (ppPaths[index]) { + Py_ssize_t len = wcslen(ppPaths[index]); + wcsncpy(szCur, ppPaths[index], len); + szCur += len; + assert(dataSize > (DWORD)len); + dataSize -= (DWORD)len; + } + } + if (skipcore) + *szCur = '\0'; + else { + /* If we have no values, we dont need a ';' */ + if (numKeys) { + *(szCur++) = L';'; + dataSize--; + } + /* Now append the core path entries - + this will include the NULL + */ + rc = RegQueryValueExW(newKey, NULL, 0, NULL, + (LPBYTE)szCur, &dataSize); + } + /* And set the result - caller must free */ + retval = dataBuf; + } done: - /* Loop freeing my temp buffers */ - if (ppPaths) { - for(index=0;index= MAXPATHLEN) - envpath = NULL; - } + char *_envpath = Py_GETENV("PYTHONPATH"); + wchar_t wenvpath[MAXPATHLEN+1]; + if (_envpath) { + size_t r = mbstowcs(wenvpath, _envpath, MAXPATHLEN+1); + envpath = wenvpath; + if (r == (size_t)-1 || r >= MAXPATHLEN) + envpath = NULL; + } #endif - get_progpath(); - /* progpath guaranteed \0 terminated in MAXPATH+1 bytes. */ - wcscpy(argv0_path, progpath); - reduce(argv0_path); - if (pythonhome == NULL || *pythonhome == '\0') { - if (search_for_prefix(argv0_path, LANDMARK)) - pythonhome = prefix; - else - pythonhome = NULL; - } - else - wcsncpy(prefix, pythonhome, MAXPATHLEN); + get_progpath(); + /* progpath guaranteed \0 terminated in MAXPATH+1 bytes. */ + wcscpy(argv0_path, progpath); + reduce(argv0_path); + if (pythonhome == NULL || *pythonhome == '\0') { + if (search_for_prefix(argv0_path, LANDMARK)) + pythonhome = prefix; + else + pythonhome = NULL; + } + else + wcsncpy(prefix, pythonhome, MAXPATHLEN); - if (envpath && *envpath == '\0') - envpath = NULL; + if (envpath && *envpath == '\0') + envpath = NULL; #ifdef MS_WINDOWS - /* Calculate zip archive path */ - if (dllpath[0]) /* use name of python DLL */ - wcsncpy(zip_path, dllpath, MAXPATHLEN); - else /* use name of executable program */ - wcsncpy(zip_path, progpath, MAXPATHLEN); - zip_path[MAXPATHLEN] = '\0'; - len = wcslen(zip_path); - if (len > 4) { - zip_path[len-3] = 'z'; /* change ending to "zip" */ - zip_path[len-2] = 'i'; - zip_path[len-1] = 'p'; - } - else { - zip_path[0] = 0; - } - - skiphome = pythonhome==NULL ? 0 : 1; + /* Calculate zip archive path */ + if (dllpath[0]) /* use name of python DLL */ + wcsncpy(zip_path, dllpath, MAXPATHLEN); + else /* use name of executable program */ + wcsncpy(zip_path, progpath, MAXPATHLEN); + zip_path[MAXPATHLEN] = '\0'; + len = wcslen(zip_path); + if (len > 4) { + zip_path[len-3] = 'z'; /* change ending to "zip" */ + zip_path[len-2] = 'i'; + zip_path[len-1] = 'p'; + } + else { + zip_path[0] = 0; + } + + skiphome = pythonhome==NULL ? 0 : 1; #ifdef Py_ENABLE_SHARED - machinepath = getpythonregpath(HKEY_LOCAL_MACHINE, skiphome); - userpath = getpythonregpath(HKEY_CURRENT_USER, skiphome); + machinepath = getpythonregpath(HKEY_LOCAL_MACHINE, skiphome); + userpath = getpythonregpath(HKEY_CURRENT_USER, skiphome); #endif - /* We only use the default relative PYTHONPATH if we havent - anything better to use! */ - skipdefault = envpath!=NULL || pythonhome!=NULL || \ - machinepath!=NULL || userpath!=NULL; + /* We only use the default relative PYTHONPATH if we havent + anything better to use! */ + skipdefault = envpath!=NULL || pythonhome!=NULL || \ + machinepath!=NULL || userpath!=NULL; #endif - /* We need to construct a path from the following parts. - (1) the PYTHONPATH environment variable, if set; - (2) for Win32, the zip archive file path; - (3) for Win32, the machinepath and userpath, if set; - (4) the PYTHONPATH config macro, with the leading "." - of each component replaced with pythonhome, if set; - (5) the directory containing the executable (argv0_path). - The length calculation calculates #4 first. - Extra rules: - - If PYTHONHOME is set (in any way) item (3) is ignored. - - If registry values are used, (4) and (5) are ignored. - */ - - /* Calculate size of return buffer */ - if (pythonhome != NULL) { - wchar_t *p; - bufsz = 1; - for (p = PYTHONPATH; *p; p++) { - if (*p == DELIM) - bufsz++; /* number of DELIM plus one */ - } - bufsz *= wcslen(pythonhome); - } - else - bufsz = 0; - bufsz += wcslen(PYTHONPATH) + 1; - bufsz += wcslen(argv0_path) + 1; + /* We need to construct a path from the following parts. + (1) the PYTHONPATH environment variable, if set; + (2) for Win32, the zip archive file path; + (3) for Win32, the machinepath and userpath, if set; + (4) the PYTHONPATH config macro, with the leading "." + of each component replaced with pythonhome, if set; + (5) the directory containing the executable (argv0_path). + The length calculation calculates #4 first. + Extra rules: + - If PYTHONHOME is set (in any way) item (3) is ignored. + - If registry values are used, (4) and (5) are ignored. + */ + + /* Calculate size of return buffer */ + if (pythonhome != NULL) { + wchar_t *p; + bufsz = 1; + for (p = PYTHONPATH; *p; p++) { + if (*p == DELIM) + bufsz++; /* number of DELIM plus one */ + } + bufsz *= wcslen(pythonhome); + } + else + bufsz = 0; + bufsz += wcslen(PYTHONPATH) + 1; + bufsz += wcslen(argv0_path) + 1; #ifdef MS_WINDOWS - if (userpath) - bufsz += wcslen(userpath) + 1; - if (machinepath) - bufsz += wcslen(machinepath) + 1; - bufsz += wcslen(zip_path) + 1; + if (userpath) + bufsz += wcslen(userpath) + 1; + if (machinepath) + bufsz += wcslen(machinepath) + 1; + bufsz += wcslen(zip_path) + 1; #endif - if (envpath != NULL) - bufsz += wcslen(envpath) + 1; + if (envpath != NULL) + bufsz += wcslen(envpath) + 1; - module_search_path = buf = malloc(bufsz*sizeof(wchar_t)); - if (buf == NULL) { - /* We can't exit, so print a warning and limp along */ - fprintf(stderr, "Can't malloc dynamic PYTHONPATH.\n"); - if (envpath) { - fprintf(stderr, "Using environment $PYTHONPATH.\n"); - module_search_path = envpath; - } - else { - fprintf(stderr, "Using default static path.\n"); - module_search_path = PYTHONPATH; - } + module_search_path = buf = malloc(bufsz*sizeof(wchar_t)); + if (buf == NULL) { + /* We can't exit, so print a warning and limp along */ + fprintf(stderr, "Can't malloc dynamic PYTHONPATH.\n"); + if (envpath) { + fprintf(stderr, "Using environment $PYTHONPATH.\n"); + module_search_path = envpath; + } + else { + fprintf(stderr, "Using default static path.\n"); + module_search_path = PYTHONPATH; + } #ifdef MS_WINDOWS - if (machinepath) - free(machinepath); - if (userpath) - free(userpath); + if (machinepath) + free(machinepath); + if (userpath) + free(userpath); #endif /* MS_WINDOWS */ - return; - } + return; + } - if (envpath) { - wcscpy(buf, envpath); - buf = wcschr(buf, L'\0'); - *buf++ = DELIM; - } + if (envpath) { + wcscpy(buf, envpath); + buf = wcschr(buf, L'\0'); + *buf++ = DELIM; + } #ifdef MS_WINDOWS - if (zip_path[0]) { - wcscpy(buf, zip_path); - buf = wcschr(buf, L'\0'); - *buf++ = DELIM; - } - if (userpath) { - wcscpy(buf, userpath); - buf = wcschr(buf, L'\0'); - *buf++ = DELIM; - free(userpath); - } - if (machinepath) { - wcscpy(buf, machinepath); - buf = wcschr(buf, L'\0'); - *buf++ = DELIM; - free(machinepath); - } - if (pythonhome == NULL) { - if (!skipdefault) { - wcscpy(buf, PYTHONPATH); - buf = wcschr(buf, L'\0'); - } - } + if (zip_path[0]) { + wcscpy(buf, zip_path); + buf = wcschr(buf, L'\0'); + *buf++ = DELIM; + } + if (userpath) { + wcscpy(buf, userpath); + buf = wcschr(buf, L'\0'); + *buf++ = DELIM; + free(userpath); + } + if (machinepath) { + wcscpy(buf, machinepath); + buf = wcschr(buf, L'\0'); + *buf++ = DELIM; + free(machinepath); + } + if (pythonhome == NULL) { + if (!skipdefault) { + wcscpy(buf, PYTHONPATH); + buf = wcschr(buf, L'\0'); + } + } #else - if (pythonhome == NULL) { - wcscpy(buf, PYTHONPATH); - buf = wcschr(buf, L'\0'); - } + if (pythonhome == NULL) { + wcscpy(buf, PYTHONPATH); + buf = wcschr(buf, L'\0'); + } #endif /* MS_WINDOWS */ - else { - wchar_t *p = PYTHONPATH; - wchar_t *q; - size_t n; - for (;;) { - q = wcschr(p, DELIM); - if (q == NULL) - n = wcslen(p); - else - n = q-p; - if (p[0] == '.' && is_sep(p[1])) { - wcscpy(buf, pythonhome); - buf = wcschr(buf, L'\0'); - p++; - n--; - } - wcsncpy(buf, p, n); - buf += n; - if (q == NULL) - break; - *buf++ = DELIM; - p = q+1; - } - } - if (argv0_path) { - *buf++ = DELIM; - wcscpy(buf, argv0_path); - buf = wcschr(buf, L'\0'); - } - *buf = L'\0'; - /* Now to pull one last hack/trick. If sys.prefix is - empty, then try and find it somewhere on the paths - we calculated. We scan backwards, as our general policy - is that Python core directories are at the *end* of - sys.path. We assume that our "lib" directory is - on the path, and that our 'prefix' directory is - the parent of that. - */ - if (*prefix==L'\0') { - wchar_t lookBuf[MAXPATHLEN+1]; - wchar_t *look = buf - 1; /* 'buf' is at the end of the buffer */ - while (1) { - Py_ssize_t nchars; - wchar_t *lookEnd = look; - /* 'look' will end up one character before the - start of the path in question - even if this - is one character before the start of the buffer - */ - while (look >= module_search_path && *look != DELIM) - look--; - nchars = lookEnd-look; - wcsncpy(lookBuf, look+1, nchars); - lookBuf[nchars] = L'\0'; - /* Up one level to the parent */ - reduce(lookBuf); - if (search_for_prefix(lookBuf, LANDMARK)) { - break; - } - /* If we are out of paths to search - give up */ - if (look < module_search_path) - break; - look--; - } - } + else { + wchar_t *p = PYTHONPATH; + wchar_t *q; + size_t n; + for (;;) { + q = wcschr(p, DELIM); + if (q == NULL) + n = wcslen(p); + else + n = q-p; + if (p[0] == '.' && is_sep(p[1])) { + wcscpy(buf, pythonhome); + buf = wcschr(buf, L'\0'); + p++; + n--; + } + wcsncpy(buf, p, n); + buf += n; + if (q == NULL) + break; + *buf++ = DELIM; + p = q+1; + } + } + if (argv0_path) { + *buf++ = DELIM; + wcscpy(buf, argv0_path); + buf = wcschr(buf, L'\0'); + } + *buf = L'\0'; + /* Now to pull one last hack/trick. If sys.prefix is + empty, then try and find it somewhere on the paths + we calculated. We scan backwards, as our general policy + is that Python core directories are at the *end* of + sys.path. We assume that our "lib" directory is + on the path, and that our 'prefix' directory is + the parent of that. + */ + if (*prefix==L'\0') { + wchar_t lookBuf[MAXPATHLEN+1]; + wchar_t *look = buf - 1; /* 'buf' is at the end of the buffer */ + while (1) { + Py_ssize_t nchars; + wchar_t *lookEnd = look; + /* 'look' will end up one character before the + start of the path in question - even if this + is one character before the start of the buffer + */ + while (look >= module_search_path && *look != DELIM) + look--; + nchars = lookEnd-look; + wcsncpy(lookBuf, look+1, nchars); + lookBuf[nchars] = L'\0'; + /* Up one level to the parent */ + reduce(lookBuf); + if (search_for_prefix(lookBuf, LANDMARK)) { + break; + } + /* If we are out of paths to search - give up */ + if (look < module_search_path) + break; + look--; + } + } } @@ -657,29 +657,29 @@ wchar_t * Py_GetPath(void) { - if (!module_search_path) - calculate_path(); - return module_search_path; + if (!module_search_path) + calculate_path(); + return module_search_path; } wchar_t * Py_GetPrefix(void) { - if (!module_search_path) - calculate_path(); - return prefix; + if (!module_search_path) + calculate_path(); + return prefix; } wchar_t * Py_GetExecPrefix(void) { - return Py_GetPrefix(); + return Py_GetPrefix(); } wchar_t * Py_GetProgramFullPath(void) { - if (!module_search_path) - calculate_path(); - return progpath; + if (!module_search_path) + calculate_path(); + return progpath; } Modified: python/branches/py3k/PC/import_nt.c ============================================================================== --- python/branches/py3k/PC/import_nt.c (original) +++ python/branches/py3k/PC/import_nt.c Sun May 9 17:52:27 2010 @@ -1,6 +1,6 @@ /******************************************************************** - import_nt.c + import_nt.c Win32 specific import code. @@ -16,71 +16,71 @@ extern const char *PyWin_DLLVersionString; FILE *PyWin_FindRegisteredModule(const char *moduleName, - struct filedescr **ppFileDesc, - char *pathBuf, - Py_ssize_t pathLen) + struct filedescr **ppFileDesc, + char *pathBuf, + Py_ssize_t pathLen) { - char *moduleKey; - const char keyPrefix[] = "Software\\Python\\PythonCore\\"; - const char keySuffix[] = "\\Modules\\"; + char *moduleKey; + const char keyPrefix[] = "Software\\Python\\PythonCore\\"; + const char keySuffix[] = "\\Modules\\"; #ifdef _DEBUG - /* In debugging builds, we _must_ have the debug version - * registered. - */ - const char debugString[] = "\\Debug"; + /* In debugging builds, we _must_ have the debug version + * registered. + */ + const char debugString[] = "\\Debug"; #else - const char debugString[] = ""; + const char debugString[] = ""; #endif - struct filedescr *fdp = NULL; - FILE *fp; - HKEY keyBase = HKEY_CURRENT_USER; - int modNameSize; - long regStat; - - /* Calculate the size for the sprintf buffer. - * Get the size of the chars only, plus 1 NULL. - */ - size_t bufSize = sizeof(keyPrefix)-1 + - strlen(PyWin_DLLVersionString) + - sizeof(keySuffix) + - strlen(moduleName) + - sizeof(debugString) - 1; - /* alloca == no free required, but memory only local to fn, - * also no heap fragmentation! - */ - moduleKey = alloca(bufSize); - PyOS_snprintf(moduleKey, bufSize, - "Software\\Python\\PythonCore\\%s\\Modules\\%s%s", - PyWin_DLLVersionString, moduleName, debugString); - - assert(pathLen < INT_MAX); - modNameSize = (int)pathLen; - regStat = RegQueryValue(keyBase, moduleKey, pathBuf, &modNameSize); - if (regStat != ERROR_SUCCESS) { - /* No user setting - lookup in machine settings */ - keyBase = HKEY_LOCAL_MACHINE; - /* be anal - failure may have reset size param */ - modNameSize = (int)pathLen; - regStat = RegQueryValue(keyBase, moduleKey, - pathBuf, &modNameSize); - - if (regStat != ERROR_SUCCESS) - return NULL; - } - /* use the file extension to locate the type entry. */ - for (fdp = _PyImport_Filetab; fdp->suffix != NULL; fdp++) { - size_t extLen = strlen(fdp->suffix); - assert(modNameSize >= 0); /* else cast to size_t is wrong */ - if ((size_t)modNameSize > extLen && - strnicmp(pathBuf + ((size_t)modNameSize-extLen-1), - fdp->suffix, - extLen) == 0) - break; - } - if (fdp->suffix == NULL) - return NULL; - fp = fopen(pathBuf, fdp->mode); - if (fp != NULL) - *ppFileDesc = fdp; - return fp; + struct filedescr *fdp = NULL; + FILE *fp; + HKEY keyBase = HKEY_CURRENT_USER; + int modNameSize; + long regStat; + + /* Calculate the size for the sprintf buffer. + * Get the size of the chars only, plus 1 NULL. + */ + size_t bufSize = sizeof(keyPrefix)-1 + + strlen(PyWin_DLLVersionString) + + sizeof(keySuffix) + + strlen(moduleName) + + sizeof(debugString) - 1; + /* alloca == no free required, but memory only local to fn, + * also no heap fragmentation! + */ + moduleKey = alloca(bufSize); + PyOS_snprintf(moduleKey, bufSize, + "Software\\Python\\PythonCore\\%s\\Modules\\%s%s", + PyWin_DLLVersionString, moduleName, debugString); + + assert(pathLen < INT_MAX); + modNameSize = (int)pathLen; + regStat = RegQueryValue(keyBase, moduleKey, pathBuf, &modNameSize); + if (regStat != ERROR_SUCCESS) { + /* No user setting - lookup in machine settings */ + keyBase = HKEY_LOCAL_MACHINE; + /* be anal - failure may have reset size param */ + modNameSize = (int)pathLen; + regStat = RegQueryValue(keyBase, moduleKey, + pathBuf, &modNameSize); + + if (regStat != ERROR_SUCCESS) + return NULL; + } + /* use the file extension to locate the type entry. */ + for (fdp = _PyImport_Filetab; fdp->suffix != NULL; fdp++) { + size_t extLen = strlen(fdp->suffix); + assert(modNameSize >= 0); /* else cast to size_t is wrong */ + if ((size_t)modNameSize > extLen && + strnicmp(pathBuf + ((size_t)modNameSize-extLen-1), + fdp->suffix, + extLen) == 0) + break; + } + if (fdp->suffix == NULL) + return NULL; + fp = fopen(pathBuf, fdp->mode); + if (fp != NULL) + *ppFileDesc = fdp; + return fp; } Modified: python/branches/py3k/PC/make_versioninfo.c ============================================================================== --- python/branches/py3k/PC/make_versioninfo.c (original) +++ python/branches/py3k/PC/make_versioninfo.c Sun May 9 17:52:27 2010 @@ -22,17 +22,17 @@ */ int main(int argc, char **argv) { - printf("/* This file created by make_versioninfo.exe */\n"); - printf("#define FIELD3 %d\n", - PY_MICRO_VERSION*1000 + PY_RELEASE_LEVEL*10 + PY_RELEASE_SERIAL); - printf("#define MS_DLL_ID \"%d.%d\"\n", - PY_MAJOR_VERSION, PY_MINOR_VERSION); - printf("#ifndef _DEBUG\n"); - printf("#define PYTHON_DLL_NAME \"python%d%d.dll\"\n", - PY_MAJOR_VERSION, PY_MINOR_VERSION); - printf("#else\n"); - printf("#define PYTHON_DLL_NAME \"python%d%d_d.dll\"\n", - PY_MAJOR_VERSION, PY_MINOR_VERSION); - printf("#endif\n"); - return 0; + printf("/* This file created by make_versioninfo.exe */\n"); + printf("#define FIELD3 %d\n", + PY_MICRO_VERSION*1000 + PY_RELEASE_LEVEL*10 + PY_RELEASE_SERIAL); + printf("#define MS_DLL_ID \"%d.%d\"\n", + PY_MAJOR_VERSION, PY_MINOR_VERSION); + printf("#ifndef _DEBUG\n"); + printf("#define PYTHON_DLL_NAME \"python%d%d.dll\"\n", + PY_MAJOR_VERSION, PY_MINOR_VERSION); + printf("#else\n"); + printf("#define PYTHON_DLL_NAME \"python%d%d_d.dll\"\n", + PY_MAJOR_VERSION, PY_MINOR_VERSION); + printf("#endif\n"); + return 0; } Modified: python/branches/py3k/PC/msvcrtmodule.c ============================================================================== --- python/branches/py3k/PC/msvcrtmodule.c (original) +++ python/branches/py3k/PC/msvcrtmodule.c Sun May 9 17:52:27 2010 @@ -1,18 +1,18 @@ /********************************************************* - msvcrtmodule.c + msvcrtmodule.c - A Python interface to the Microsoft Visual C Runtime - Library, providing access to those non-portable, but - still useful routines. + A Python interface to the Microsoft Visual C Runtime + Library, providing access to those non-portable, but + still useful routines. - Only ever compiled with an MS compiler, so no attempt - has been made to avoid MS language extensions, etc... + Only ever compiled with an MS compiler, so no attempt + has been made to avoid MS language extensions, etc... - This may only work on NT or 95... + This may only work on NT or 95... - Author: Mark Hammond and Guido van Rossum. - Maintenance: Guido van Rossum. + Author: Mark Hammond and Guido van Rossum. + Maintenance: Guido van Rossum. ***********************************************************/ @@ -35,14 +35,14 @@ static PyObject * msvcrt_heapmin(PyObject *self, PyObject *args) { - if (!PyArg_ParseTuple(args, ":heapmin")) - return NULL; + if (!PyArg_ParseTuple(args, ":heapmin")) + return NULL; - if (_heapmin() != 0) - return PyErr_SetFromErrno(PyExc_IOError); + if (_heapmin() != 0) + return PyErr_SetFromErrno(PyExc_IOError); - Py_INCREF(Py_None); - return Py_None; + Py_INCREF(Py_None); + return Py_None; } PyDoc_STRVAR(heapmin_doc, @@ -55,22 +55,22 @@ static PyObject * msvcrt_locking(PyObject *self, PyObject *args) { - int fd; - int mode; - long nbytes; - int err; - - if (!PyArg_ParseTuple(args, "iil:locking", &fd, &mode, &nbytes)) - return NULL; - - Py_BEGIN_ALLOW_THREADS - err = _locking(fd, mode, nbytes); - Py_END_ALLOW_THREADS - if (err != 0) - return PyErr_SetFromErrno(PyExc_IOError); + int fd; + int mode; + long nbytes; + int err; + + if (!PyArg_ParseTuple(args, "iil:locking", &fd, &mode, &nbytes)) + return NULL; + + Py_BEGIN_ALLOW_THREADS + err = _locking(fd, mode, nbytes); + Py_END_ALLOW_THREADS + if (err != 0) + return PyErr_SetFromErrno(PyExc_IOError); - Py_INCREF(Py_None); - return Py_None; + Py_INCREF(Py_None); + return Py_None; } PyDoc_STRVAR(locking_doc, @@ -88,16 +88,16 @@ static PyObject * msvcrt_setmode(PyObject *self, PyObject *args) { - int fd; - int flags; - if (!PyArg_ParseTuple(args,"ii:setmode", &fd, &flags)) - return NULL; - - flags = _setmode(fd, flags); - if (flags == -1) - return PyErr_SetFromErrno(PyExc_IOError); + int fd; + int flags; + if (!PyArg_ParseTuple(args,"ii:setmode", &fd, &flags)) + return NULL; + + flags = _setmode(fd, flags); + if (flags == -1) + return PyErr_SetFromErrno(PyExc_IOError); - return PyLong_FromLong(flags); + return PyLong_FromLong(flags); } PyDoc_STRVAR(setmode_doc, @@ -111,18 +111,18 @@ static PyObject * msvcrt_open_osfhandle(PyObject *self, PyObject *args) { - long handle; - int flags; - int fd; - - if (!PyArg_ParseTuple(args, "li:open_osfhandle", &handle, &flags)) - return NULL; - - fd = _open_osfhandle(handle, flags); - if (fd == -1) - return PyErr_SetFromErrno(PyExc_IOError); + long handle; + int flags; + int fd; + + if (!PyArg_ParseTuple(args, "li:open_osfhandle", &handle, &flags)) + return NULL; + + fd = _open_osfhandle(handle, flags); + if (fd == -1) + return PyErr_SetFromErrno(PyExc_IOError); - return PyLong_FromLong(fd); + return PyLong_FromLong(fd); } PyDoc_STRVAR(open_osfhandle_doc, @@ -137,20 +137,20 @@ static PyObject * msvcrt_get_osfhandle(PyObject *self, PyObject *args) { - int fd; - Py_intptr_t handle; + int fd; + Py_intptr_t handle; - if (!PyArg_ParseTuple(args,"i:get_osfhandle", &fd)) - return NULL; + if (!PyArg_ParseTuple(args,"i:get_osfhandle", &fd)) + return NULL; - handle = _get_osfhandle(fd); - if (handle == -1) - return PyErr_SetFromErrno(PyExc_IOError); - - /* technically 'handle' is not a pointer, but a integer as - large as a pointer, Python's *VoidPtr interface is the - most appropriate here */ - return PyLong_FromVoidPtr((void*)handle); + handle = _get_osfhandle(fd); + if (handle == -1) + return PyErr_SetFromErrno(PyExc_IOError); + + /* technically 'handle' is not a pointer, but a integer as + large as a pointer, Python's *VoidPtr interface is the + most appropriate here */ + return PyLong_FromVoidPtr((void*)handle); } PyDoc_STRVAR(get_osfhandle_doc, @@ -164,13 +164,13 @@ static PyObject * msvcrt_kbhit(PyObject *self, PyObject *args) { - int ok; + int ok; - if (!PyArg_ParseTuple(args, ":kbhit")) - return NULL; + if (!PyArg_ParseTuple(args, ":kbhit")) + return NULL; - ok = _kbhit(); - return PyLong_FromLong(ok); + ok = _kbhit(); + return PyLong_FromLong(ok); } PyDoc_STRVAR(kbhit_doc, @@ -181,17 +181,17 @@ static PyObject * msvcrt_getch(PyObject *self, PyObject *args) { - int ch; - char s[1]; + int ch; + char s[1]; - if (!PyArg_ParseTuple(args, ":getch")) - return NULL; + if (!PyArg_ParseTuple(args, ":getch")) + return NULL; - Py_BEGIN_ALLOW_THREADS - ch = _getch(); - Py_END_ALLOW_THREADS - s[0] = ch; - return PyBytes_FromStringAndSize(s, 1); + Py_BEGIN_ALLOW_THREADS + ch = _getch(); + Py_END_ALLOW_THREADS + s[0] = ch; + return PyBytes_FromStringAndSize(s, 1); } PyDoc_STRVAR(getch_doc, @@ -208,17 +208,17 @@ static PyObject * msvcrt_getwch(PyObject *self, PyObject *args) { - Py_UNICODE ch; - Py_UNICODE u[1]; + Py_UNICODE ch; + Py_UNICODE u[1]; - if (!PyArg_ParseTuple(args, ":getwch")) - return NULL; + if (!PyArg_ParseTuple(args, ":getwch")) + return NULL; - Py_BEGIN_ALLOW_THREADS - ch = _getwch(); - Py_END_ALLOW_THREADS - u[0] = ch; - return PyUnicode_FromUnicode(u, 1); + Py_BEGIN_ALLOW_THREADS + ch = _getwch(); + Py_END_ALLOW_THREADS + u[0] = ch; + return PyUnicode_FromUnicode(u, 1); } PyDoc_STRVAR(getwch_doc, @@ -230,17 +230,17 @@ static PyObject * msvcrt_getche(PyObject *self, PyObject *args) { - int ch; - char s[1]; + int ch; + char s[1]; - if (!PyArg_ParseTuple(args, ":getche")) - return NULL; + if (!PyArg_ParseTuple(args, ":getche")) + return NULL; - Py_BEGIN_ALLOW_THREADS - ch = _getche(); - Py_END_ALLOW_THREADS - s[0] = ch; - return PyBytes_FromStringAndSize(s, 1); + Py_BEGIN_ALLOW_THREADS + ch = _getche(); + Py_END_ALLOW_THREADS + s[0] = ch; + return PyBytes_FromStringAndSize(s, 1); } PyDoc_STRVAR(getche_doc, @@ -253,17 +253,17 @@ static PyObject * msvcrt_getwche(PyObject *self, PyObject *args) { - Py_UNICODE ch; - Py_UNICODE s[1]; + Py_UNICODE ch; + Py_UNICODE s[1]; - if (!PyArg_ParseTuple(args, ":getwche")) - return NULL; + if (!PyArg_ParseTuple(args, ":getwche")) + return NULL; - Py_BEGIN_ALLOW_THREADS - ch = _getwche(); - Py_END_ALLOW_THREADS - s[0] = ch; - return PyUnicode_FromUnicode(s, 1); + Py_BEGIN_ALLOW_THREADS + ch = _getwche(); + Py_END_ALLOW_THREADS + s[0] = ch; + return PyUnicode_FromUnicode(s, 1); } PyDoc_STRVAR(getwche_doc, @@ -275,14 +275,14 @@ static PyObject * msvcrt_putch(PyObject *self, PyObject *args) { - char ch; + char ch; - if (!PyArg_ParseTuple(args, "c:putch", &ch)) - return NULL; + if (!PyArg_ParseTuple(args, "c:putch", &ch)) + return NULL; - _putch(ch); - Py_INCREF(Py_None); - return Py_None; + _putch(ch); + Py_INCREF(Py_None); + return Py_None; } PyDoc_STRVAR(putch_doc, @@ -294,13 +294,13 @@ static PyObject * msvcrt_putwch(PyObject *self, PyObject *args) { - int ch; + int ch; - if (!PyArg_ParseTuple(args, "C:putwch", &ch)) - return NULL; + if (!PyArg_ParseTuple(args, "C:putwch", &ch)) + return NULL; - _putwch(ch); - Py_RETURN_NONE; + _putwch(ch); + Py_RETURN_NONE; } @@ -313,15 +313,15 @@ static PyObject * msvcrt_ungetch(PyObject *self, PyObject *args) { - char ch; + char ch; - if (!PyArg_ParseTuple(args, "c:ungetch", &ch)) - return NULL; + if (!PyArg_ParseTuple(args, "c:ungetch", &ch)) + return NULL; - if (_ungetch(ch) == EOF) - return PyErr_SetFromErrno(PyExc_IOError); - Py_INCREF(Py_None); - return Py_None; + if (_ungetch(ch) == EOF) + return PyErr_SetFromErrno(PyExc_IOError); + Py_INCREF(Py_None); + return Py_None; } PyDoc_STRVAR(ungetch_doc, @@ -334,15 +334,15 @@ static PyObject * msvcrt_ungetwch(PyObject *self, PyObject *args) { - int ch; + int ch; - if (!PyArg_ParseTuple(args, "C:ungetwch", &ch)) - return NULL; + if (!PyArg_ParseTuple(args, "C:ungetwch", &ch)) + return NULL; - if (_ungetwch(ch) == WEOF) - return PyErr_SetFromErrno(PyExc_IOError); - Py_INCREF(Py_None); - return Py_None; + if (_ungetwch(ch) == WEOF) + return PyErr_SetFromErrno(PyExc_IOError); + Py_INCREF(Py_None); + return Py_None; } PyDoc_STRVAR(ungetwch_doc, @@ -354,15 +354,15 @@ static void insertint(PyObject *d, char *name, int value) { - PyObject *v = PyLong_FromLong((long) value); - if (v == NULL) { - /* Don't bother reporting this error */ - PyErr_Clear(); - } - else { - PyDict_SetItemString(d, name, v); - Py_DECREF(v); - } + PyObject *v = PyLong_FromLong((long) value); + if (v == NULL) { + /* Don't bother reporting this error */ + PyErr_Clear(); + } + else { + PyDict_SetItemString(d, name, v); + Py_DECREF(v); + } } #ifdef _DEBUG @@ -370,40 +370,40 @@ static PyObject* msvcrt_setreportfile(PyObject *self, PyObject *args) { - int type, file; - _HFILE res; + int type, file; + _HFILE res; - if (!PyArg_ParseTuple(args, "ii", &type, &file)) - return NULL; - res = _CrtSetReportFile(type, (_HFILE)file); - return PyLong_FromLong((long)res); - Py_INCREF(Py_None); - return Py_None; + if (!PyArg_ParseTuple(args, "ii", &type, &file)) + return NULL; + res = _CrtSetReportFile(type, (_HFILE)file); + return PyLong_FromLong((long)res); + Py_INCREF(Py_None); + return Py_None; } static PyObject* msvcrt_setreportmode(PyObject *self, PyObject *args) { - int type, mode; - int res; + int type, mode; + int res; - if (!PyArg_ParseTuple(args, "ii", &type, &mode)) - return NULL; - res = _CrtSetReportMode(type, mode); - if (res == -1) - return PyErr_SetFromErrno(PyExc_IOError); - return PyLong_FromLong(res); + if (!PyArg_ParseTuple(args, "ii", &type, &mode)) + return NULL; + res = _CrtSetReportMode(type, mode); + if (res == -1) + return PyErr_SetFromErrno(PyExc_IOError); + return PyLong_FromLong(res); } static PyObject* msvcrt_seterrormode(PyObject *self, PyObject *args) { - int mode, res; + int mode, res; - if (!PyArg_ParseTuple(args, "i", &mode)) - return NULL; - res = _set_error_mode(mode); - return PyLong_FromLong(res); + if (!PyArg_ParseTuple(args, "i", &mode)) + return NULL; + res = _set_error_mode(mode); + return PyLong_FromLong(res); } #endif @@ -411,104 +411,104 @@ static PyObject* seterrormode(PyObject *self, PyObject *args) { - unsigned int mode, res; + unsigned int mode, res; - if (!PyArg_ParseTuple(args, "I", &mode)) - return NULL; - res = SetErrorMode(mode); - return PyLong_FromUnsignedLong(res); + if (!PyArg_ParseTuple(args, "I", &mode)) + return NULL; + res = SetErrorMode(mode); + return PyLong_FromUnsignedLong(res); } /* List of functions exported by this module */ static struct PyMethodDef msvcrt_functions[] = { - {"heapmin", msvcrt_heapmin, METH_VARARGS, heapmin_doc}, - {"locking", msvcrt_locking, METH_VARARGS, locking_doc}, - {"setmode", msvcrt_setmode, METH_VARARGS, setmode_doc}, - {"open_osfhandle", msvcrt_open_osfhandle, METH_VARARGS, open_osfhandle_doc}, - {"get_osfhandle", msvcrt_get_osfhandle, METH_VARARGS, get_osfhandle_doc}, - {"kbhit", msvcrt_kbhit, METH_VARARGS, kbhit_doc}, - {"getch", msvcrt_getch, METH_VARARGS, getch_doc}, - {"getche", msvcrt_getche, METH_VARARGS, getche_doc}, - {"putch", msvcrt_putch, METH_VARARGS, putch_doc}, - {"ungetch", msvcrt_ungetch, METH_VARARGS, ungetch_doc}, - {"SetErrorMode", seterrormode, METH_VARARGS}, + {"heapmin", msvcrt_heapmin, METH_VARARGS, heapmin_doc}, + {"locking", msvcrt_locking, METH_VARARGS, locking_doc}, + {"setmode", msvcrt_setmode, METH_VARARGS, setmode_doc}, + {"open_osfhandle", msvcrt_open_osfhandle, METH_VARARGS, open_osfhandle_doc}, + {"get_osfhandle", msvcrt_get_osfhandle, METH_VARARGS, get_osfhandle_doc}, + {"kbhit", msvcrt_kbhit, METH_VARARGS, kbhit_doc}, + {"getch", msvcrt_getch, METH_VARARGS, getch_doc}, + {"getche", msvcrt_getche, METH_VARARGS, getche_doc}, + {"putch", msvcrt_putch, METH_VARARGS, putch_doc}, + {"ungetch", msvcrt_ungetch, METH_VARARGS, ungetch_doc}, + {"SetErrorMode", seterrormode, METH_VARARGS}, #ifdef _DEBUG - {"CrtSetReportFile", msvcrt_setreportfile, METH_VARARGS}, - {"CrtSetReportMode", msvcrt_setreportmode, METH_VARARGS}, - {"set_error_mode", msvcrt_seterrormode, METH_VARARGS}, + {"CrtSetReportFile", msvcrt_setreportfile, METH_VARARGS}, + {"CrtSetReportMode", msvcrt_setreportmode, METH_VARARGS}, + {"set_error_mode", msvcrt_seterrormode, METH_VARARGS}, #endif #ifdef _WCONIO_DEFINED - {"getwch", msvcrt_getwch, METH_VARARGS, getwch_doc}, - {"getwche", msvcrt_getwche, METH_VARARGS, getwche_doc}, - {"putwch", msvcrt_putwch, METH_VARARGS, putwch_doc}, - {"ungetwch", msvcrt_ungetwch, METH_VARARGS, ungetwch_doc}, + {"getwch", msvcrt_getwch, METH_VARARGS, getwch_doc}, + {"getwche", msvcrt_getwche, METH_VARARGS, getwche_doc}, + {"putwch", msvcrt_putwch, METH_VARARGS, putwch_doc}, + {"ungetwch", msvcrt_ungetwch, METH_VARARGS, ungetwch_doc}, #endif - {NULL, NULL} + {NULL, NULL} }; static struct PyModuleDef msvcrtmodule = { - PyModuleDef_HEAD_INIT, - "msvcrt", - NULL, - -1, - msvcrt_functions, - NULL, - NULL, - NULL, - NULL + PyModuleDef_HEAD_INIT, + "msvcrt", + NULL, + -1, + msvcrt_functions, + NULL, + NULL, + NULL, + NULL }; PyMODINIT_FUNC PyInit_msvcrt(void) { - int st; - PyObject *d; - PyObject *m = PyModule_Create(&msvcrtmodule); - if (m == NULL) - return NULL; - d = PyModule_GetDict(m); - - /* constants for the locking() function's mode argument */ - insertint(d, "LK_LOCK", _LK_LOCK); - insertint(d, "LK_NBLCK", _LK_NBLCK); - insertint(d, "LK_NBRLCK", _LK_NBRLCK); - insertint(d, "LK_RLCK", _LK_RLCK); - insertint(d, "LK_UNLCK", _LK_UNLCK); - insertint(d, "SEM_FAILCRITICALERRORS", SEM_FAILCRITICALERRORS); - insertint(d, "SEM_NOALIGNMENTFAULTEXCEPT", SEM_NOALIGNMENTFAULTEXCEPT); - insertint(d, "SEM_NOGPFAULTERRORBOX", SEM_NOGPFAULTERRORBOX); - insertint(d, "SEM_NOOPENFILEERRORBOX", SEM_NOOPENFILEERRORBOX); + int st; + PyObject *d; + PyObject *m = PyModule_Create(&msvcrtmodule); + if (m == NULL) + return NULL; + d = PyModule_GetDict(m); + + /* constants for the locking() function's mode argument */ + insertint(d, "LK_LOCK", _LK_LOCK); + insertint(d, "LK_NBLCK", _LK_NBLCK); + insertint(d, "LK_NBRLCK", _LK_NBRLCK); + insertint(d, "LK_RLCK", _LK_RLCK); + insertint(d, "LK_UNLCK", _LK_UNLCK); + insertint(d, "SEM_FAILCRITICALERRORS", SEM_FAILCRITICALERRORS); + insertint(d, "SEM_NOALIGNMENTFAULTEXCEPT", SEM_NOALIGNMENTFAULTEXCEPT); + insertint(d, "SEM_NOGPFAULTERRORBOX", SEM_NOGPFAULTERRORBOX); + insertint(d, "SEM_NOOPENFILEERRORBOX", SEM_NOOPENFILEERRORBOX); #ifdef _DEBUG - insertint(d, "CRT_WARN", _CRT_WARN); - insertint(d, "CRT_ERROR", _CRT_ERROR); - insertint(d, "CRT_ASSERT", _CRT_ASSERT); - insertint(d, "CRTDBG_MODE_DEBUG", _CRTDBG_MODE_DEBUG); - insertint(d, "CRTDBG_MODE_FILE", _CRTDBG_MODE_FILE); - insertint(d, "CRTDBG_MODE_WNDW", _CRTDBG_MODE_WNDW); - insertint(d, "CRTDBG_REPORT_MODE", _CRTDBG_REPORT_MODE); - insertint(d, "CRTDBG_FILE_STDERR", (int)_CRTDBG_FILE_STDERR); - insertint(d, "CRTDBG_FILE_STDOUT", (int)_CRTDBG_FILE_STDOUT); - insertint(d, "CRTDBG_REPORT_FILE", (int)_CRTDBG_REPORT_FILE); + insertint(d, "CRT_WARN", _CRT_WARN); + insertint(d, "CRT_ERROR", _CRT_ERROR); + insertint(d, "CRT_ASSERT", _CRT_ASSERT); + insertint(d, "CRTDBG_MODE_DEBUG", _CRTDBG_MODE_DEBUG); + insertint(d, "CRTDBG_MODE_FILE", _CRTDBG_MODE_FILE); + insertint(d, "CRTDBG_MODE_WNDW", _CRTDBG_MODE_WNDW); + insertint(d, "CRTDBG_REPORT_MODE", _CRTDBG_REPORT_MODE); + insertint(d, "CRTDBG_FILE_STDERR", (int)_CRTDBG_FILE_STDERR); + insertint(d, "CRTDBG_FILE_STDOUT", (int)_CRTDBG_FILE_STDOUT); + insertint(d, "CRTDBG_REPORT_FILE", (int)_CRTDBG_REPORT_FILE); #endif - /* constants for the crt versions */ + /* constants for the crt versions */ #ifdef _VC_ASSEMBLY_PUBLICKEYTOKEN - st = PyModule_AddStringConstant(m, "VC_ASSEMBLY_PUBLICKEYTOKEN", - _VC_ASSEMBLY_PUBLICKEYTOKEN); - if (st < 0) return NULL; + st = PyModule_AddStringConstant(m, "VC_ASSEMBLY_PUBLICKEYTOKEN", + _VC_ASSEMBLY_PUBLICKEYTOKEN); + if (st < 0) return NULL; #endif #ifdef _CRT_ASSEMBLY_VERSION - st = PyModule_AddStringConstant(m, "CRT_ASSEMBLY_VERSION", - _CRT_ASSEMBLY_VERSION); - if (st < 0) return NULL; + st = PyModule_AddStringConstant(m, "CRT_ASSEMBLY_VERSION", + _CRT_ASSEMBLY_VERSION); + if (st < 0) return NULL; #endif #ifdef __LIBRARIES_ASSEMBLY_NAME_PREFIX - st = PyModule_AddStringConstant(m, "LIBRARIES_ASSEMBLY_NAME_PREFIX", - __LIBRARIES_ASSEMBLY_NAME_PREFIX); - if (st < 0) return NULL; + st = PyModule_AddStringConstant(m, "LIBRARIES_ASSEMBLY_NAME_PREFIX", + __LIBRARIES_ASSEMBLY_NAME_PREFIX); + if (st < 0) return NULL; #endif - return m; + return m; } Modified: python/branches/py3k/PC/os2emx/config.c ============================================================================== --- python/branches/py3k/PC/os2emx/config.c (original) +++ python/branches/py3k/PC/os2emx/config.c Sun May 9 17:52:27 2010 @@ -95,71 +95,71 @@ struct _inittab _PyImport_Inittab[] = { - {"os2", initos2}, - {"signal", initsignal}, + {"os2", initos2}, + {"signal", initsignal}, #ifdef WITH_THREAD - {"_thread", init_thread}, + {"_thread", init_thread}, #endif - {"_codecs", init_codecs}, - {"_csv", init_csv}, - {"_locale", init_locale}, - {"_random", init_random}, - {"_sre", init_sre}, - {"_symtable", init_symtable}, - {"_weakref", init_weakref}, - {"array", initarray}, - {"binascii", initbinascii}, - {"collections", initcollections}, - {"cmath", initcmath}, - {"datetime", initdatetime}, - {"dl", initdl}, - {"errno", initerrno}, - {"fcntl", initfcntl}, - {"_functools", init_functools}, - {"_heapq", init_heapq}, - {"imageop", initimageop}, - {"itertools", inititertools}, - {"math", initmath}, - {"operator", initoperator}, - {"_sha256", init_sha256}, - {"_sha512", init_sha512}, - {"_struct", init_struct}, - {"termios", inittermios}, - {"time", inittime}, - {"xxsubtype", initxxsubtype}, - {"zipimport", initzipimport}, + {"_codecs", init_codecs}, + {"_csv", init_csv}, + {"_locale", init_locale}, + {"_random", init_random}, + {"_sre", init_sre}, + {"_symtable", init_symtable}, + {"_weakref", init_weakref}, + {"array", initarray}, + {"binascii", initbinascii}, + {"collections", initcollections}, + {"cmath", initcmath}, + {"datetime", initdatetime}, + {"dl", initdl}, + {"errno", initerrno}, + {"fcntl", initfcntl}, + {"_functools", init_functools}, + {"_heapq", init_heapq}, + {"imageop", initimageop}, + {"itertools", inititertools}, + {"math", initmath}, + {"operator", initoperator}, + {"_sha256", init_sha256}, + {"_sha512", init_sha512}, + {"_struct", init_struct}, + {"termios", inittermios}, + {"time", inittime}, + {"xxsubtype", initxxsubtype}, + {"zipimport", initzipimport}, #if !HAVE_DYNAMIC_LOADING - {"_curses", init_curses}, - {"_curses_panel", init_curses_panel}, - {"_testcapi", init_testcapi}, - {"bz2", initbz2}, - {"fpectl", initfpectl}, - {"fpetest", initfpetest}, - {"parser", initparser}, - {"pwd", initpwd}, - {"unicodedata", initunicodedata}, - {"zlib", initzlib}, + {"_curses", init_curses}, + {"_curses_panel", init_curses_panel}, + {"_testcapi", init_testcapi}, + {"bz2", initbz2}, + {"fpectl", initfpectl}, + {"fpetest", initfpetest}, + {"parser", initparser}, + {"pwd", initpwd}, + {"unicodedata", initunicodedata}, + {"zlib", initzlib}, #ifdef USE_SOCKET - {"_socket", init_socket}, - {"select", initselect}, + {"_socket", init_socket}, + {"select", initselect}, #endif #endif /* -- ADDMODULE MARKER 2 -- */ - /* This module "lives in" with marshal.c */ - {"marshal", PyMarshal_Init}, + /* This module "lives in" with marshal.c */ + {"marshal", PyMarshal_Init}, - /* This lives it with import.c */ - {"imp", initimp}, + /* This lives it with import.c */ + {"imp", initimp}, - /* These entries are here for sys.builtin_module_names */ - {"__main__", NULL}, - {"builtins", NULL}, - {"sys", NULL}, + /* These entries are here for sys.builtin_module_names */ + {"__main__", NULL}, + {"builtins", NULL}, + {"sys", NULL}, - /* This lives in gcmodule.c */ - {"gc", initgc}, + /* This lives in gcmodule.c */ + {"gc", initgc}, - /* Sentinel */ - {0, 0} + /* Sentinel */ + {0, 0} }; Modified: python/branches/py3k/PC/os2emx/dlfcn.c ============================================================================== --- python/branches/py3k/PC/os2emx/dlfcn.c (original) +++ python/branches/py3k/PC/os2emx/dlfcn.c Sun May 9 17:52:27 2010 @@ -46,178 +46,178 @@ #include typedef struct _track_rec { - char *name; - HMODULE handle; - void *id; - struct _track_rec *next; + char *name; + HMODULE handle; + void *id; + struct _track_rec *next; } tDLLchain, *DLLchain; -static DLLchain dlload = NULL; /* A simple chained list of DLL names */ -static char dlerr [256]; /* last error text string */ +static DLLchain dlload = NULL; /* A simple chained list of DLL names */ +static char dlerr [256]; /* last error text string */ static void *last_id; static DLLchain find_id(void *id) { - DLLchain tmp; + DLLchain tmp; - for (tmp = dlload; tmp; tmp = tmp->next) - if (id == tmp->id) - return tmp; + for (tmp = dlload; tmp; tmp = tmp->next) + if (id == tmp->id) + return tmp; - return NULL; + return NULL; } /* load a dynamic-link library and return handle */ void *dlopen(char *filename, int flags) { - HMODULE hm; - DLLchain tmp; - char err[256]; - char *errtxt; - int rc = 0, set_chain = 0; - - for (tmp = dlload; tmp; tmp = tmp->next) - if (strnicmp(tmp->name, filename, 999) == 0) - break; - - if (!tmp) - { - tmp = (DLLchain) malloc(sizeof(tDLLchain)); - if (!tmp) - goto nomem; - tmp->name = strdup(filename); - tmp->next = dlload; - set_chain = 1; - } - - switch (rc = DosLoadModule((PSZ)&err, sizeof(err), filename, &hm)) - { - case NO_ERROR: - tmp->handle = hm; - if (set_chain) - { - do - last_id++; - while ((last_id == 0) || (find_id(last_id))); - tmp->id = last_id; - dlload = tmp; - } - return tmp->id; - case ERROR_FILE_NOT_FOUND: - case ERROR_PATH_NOT_FOUND: - errtxt = "module `%s' not found"; - break; - case ERROR_TOO_MANY_OPEN_FILES: - case ERROR_NOT_ENOUGH_MEMORY: - case ERROR_SHARING_BUFFER_EXCEEDED: + HMODULE hm; + DLLchain tmp; + char err[256]; + char *errtxt; + int rc = 0, set_chain = 0; + + for (tmp = dlload; tmp; tmp = tmp->next) + if (strnicmp(tmp->name, filename, 999) == 0) + break; + + if (!tmp) + { + tmp = (DLLchain) malloc(sizeof(tDLLchain)); + if (!tmp) + goto nomem; + tmp->name = strdup(filename); + tmp->next = dlload; + set_chain = 1; + } + + switch (rc = DosLoadModule((PSZ)&err, sizeof(err), filename, &hm)) + { + case NO_ERROR: + tmp->handle = hm; + if (set_chain) + { + do + last_id++; + while ((last_id == 0) || (find_id(last_id))); + tmp->id = last_id; + dlload = tmp; + } + return tmp->id; + case ERROR_FILE_NOT_FOUND: + case ERROR_PATH_NOT_FOUND: + errtxt = "module `%s' not found"; + break; + case ERROR_TOO_MANY_OPEN_FILES: + case ERROR_NOT_ENOUGH_MEMORY: + case ERROR_SHARING_BUFFER_EXCEEDED: nomem: - errtxt = "out of system resources"; - break; - case ERROR_ACCESS_DENIED: - errtxt = "access denied"; - break; - case ERROR_BAD_FORMAT: - case ERROR_INVALID_SEGMENT_NUMBER: - case ERROR_INVALID_ORDINAL: - case ERROR_INVALID_MODULETYPE: - case ERROR_INVALID_EXE_SIGNATURE: - case ERROR_EXE_MARKED_INVALID: - case ERROR_ITERATED_DATA_EXCEEDS_64K: - case ERROR_INVALID_MINALLOCSIZE: - case ERROR_INVALID_SEGDPL: - case ERROR_AUTODATASEG_EXCEEDS_64K: - case ERROR_RELOCSRC_CHAIN_EXCEEDS_SEGLIMIT: - errtxt = "invalid module format"; - break; - case ERROR_INVALID_NAME: - errtxt = "filename doesn't match module name"; - break; - case ERROR_SHARING_VIOLATION: - case ERROR_LOCK_VIOLATION: - errtxt = "sharing violation"; - break; - case ERROR_INIT_ROUTINE_FAILED: - errtxt = "module initialization failed"; - break; - default: - errtxt = "cause `%s', error code = %d"; - break; - } - snprintf(dlerr, sizeof(dlerr), errtxt, &err, rc); - if (tmp) - { - if (tmp->name) - free(tmp->name); - free(tmp); - } - return 0; + errtxt = "out of system resources"; + break; + case ERROR_ACCESS_DENIED: + errtxt = "access denied"; + break; + case ERROR_BAD_FORMAT: + case ERROR_INVALID_SEGMENT_NUMBER: + case ERROR_INVALID_ORDINAL: + case ERROR_INVALID_MODULETYPE: + case ERROR_INVALID_EXE_SIGNATURE: + case ERROR_EXE_MARKED_INVALID: + case ERROR_ITERATED_DATA_EXCEEDS_64K: + case ERROR_INVALID_MINALLOCSIZE: + case ERROR_INVALID_SEGDPL: + case ERROR_AUTODATASEG_EXCEEDS_64K: + case ERROR_RELOCSRC_CHAIN_EXCEEDS_SEGLIMIT: + errtxt = "invalid module format"; + break; + case ERROR_INVALID_NAME: + errtxt = "filename doesn't match module name"; + break; + case ERROR_SHARING_VIOLATION: + case ERROR_LOCK_VIOLATION: + errtxt = "sharing violation"; + break; + case ERROR_INIT_ROUTINE_FAILED: + errtxt = "module initialization failed"; + break; + default: + errtxt = "cause `%s', error code = %d"; + break; + } + snprintf(dlerr, sizeof(dlerr), errtxt, &err, rc); + if (tmp) + { + if (tmp->name) + free(tmp->name); + free(tmp); + } + return 0; } /* return a pointer to the `symbol' in DLL */ void *dlsym(void *handle, char *symbol) { - int rc = 0; - PFN addr; - char *errtxt; - int symord = 0; - DLLchain tmp = find_id(handle); - - if (!tmp) - goto inv_handle; - - if (*symbol == '#') - symord = atoi(symbol + 1); - - switch (rc = DosQueryProcAddr(tmp->handle, symord, symbol, &addr)) - { - case NO_ERROR: - return (void *)addr; - case ERROR_INVALID_HANDLE: + int rc = 0; + PFN addr; + char *errtxt; + int symord = 0; + DLLchain tmp = find_id(handle); + + if (!tmp) + goto inv_handle; + + if (*symbol == '#') + symord = atoi(symbol + 1); + + switch (rc = DosQueryProcAddr(tmp->handle, symord, symbol, &addr)) + { + case NO_ERROR: + return (void *)addr; + case ERROR_INVALID_HANDLE: inv_handle: - errtxt = "invalid module handle"; - break; - case ERROR_PROC_NOT_FOUND: - case ERROR_INVALID_NAME: - errtxt = "no symbol `%s' in module"; - break; - default: - errtxt = "symbol `%s', error code = %d"; - break; - } - snprintf(dlerr, sizeof(dlerr), errtxt, symbol, rc); - return NULL; + errtxt = "invalid module handle"; + break; + case ERROR_PROC_NOT_FOUND: + case ERROR_INVALID_NAME: + errtxt = "no symbol `%s' in module"; + break; + default: + errtxt = "symbol `%s', error code = %d"; + break; + } + snprintf(dlerr, sizeof(dlerr), errtxt, symbol, rc); + return NULL; } /* free dynamicaly-linked library */ int dlclose(void *handle) { - int rc; - DLLchain tmp = find_id(handle); + int rc; + DLLchain tmp = find_id(handle); - if (!tmp) - goto inv_handle; + if (!tmp) + goto inv_handle; - switch (rc = DosFreeModule(tmp->handle)) - { - case NO_ERROR: - free(tmp->name); - dlload = tmp->next; - free(tmp); - return 0; - case ERROR_INVALID_HANDLE: + switch (rc = DosFreeModule(tmp->handle)) + { + case NO_ERROR: + free(tmp->name); + dlload = tmp->next; + free(tmp); + return 0; + case ERROR_INVALID_HANDLE: inv_handle: - strcpy(dlerr, "invalid module handle"); - return -1; - case ERROR_INVALID_ACCESS: - strcpy(dlerr, "access denied"); - return -1; - default: - return -1; - } + strcpy(dlerr, "invalid module handle"); + return -1; + case ERROR_INVALID_ACCESS: + strcpy(dlerr, "access denied"); + return -1; + default: + return -1; + } } /* return a string describing last occurred dl error */ char *dlerror() { - return dlerr; + return dlerr; } Modified: python/branches/py3k/PC/os2emx/dllentry.c ============================================================================== --- python/branches/py3k/PC/os2emx/dllentry.c (original) +++ python/branches/py3k/PC/os2emx/dllentry.c Sun May 9 17:52:27 2010 @@ -4,7 +4,7 @@ #define NULL 0 -#define REF(s) extern void s(); void *____ref_##s = &s; +#define REF(s) extern void s(); void *____ref_##s = &s; /* Make references to imported symbols to pull them from static library */ REF(Py_Main); @@ -18,25 +18,25 @@ unsigned long _DLL_InitTerm(unsigned long mod_handle, unsigned long flag) { - switch (flag) - { - case 0: - if (_CRT_init()) - return 0; - __ctordtorInit(); - - /* Ignore fatal signals */ - signal(SIGSEGV, SIG_IGN); - signal(SIGFPE, SIG_IGN); - - return 1; - - case 1: - __ctordtorTerm(); - _CRT_term(); - return 1; - - default: - return 0; - } + switch (flag) + { + case 0: + if (_CRT_init()) + return 0; + __ctordtorInit(); + + /* Ignore fatal signals */ + signal(SIGSEGV, SIG_IGN); + signal(SIGFPE, SIG_IGN); + + return 1; + + case 1: + __ctordtorTerm(); + _CRT_term(); + return 1; + + default: + return 0; + } } Modified: python/branches/py3k/PC/os2emx/getpathp.c ============================================================================== --- python/branches/py3k/PC/os2emx/getpathp.c (original) +++ python/branches/py3k/PC/os2emx/getpathp.c Sun May 9 17:52:27 2010 @@ -4,8 +4,8 @@ /* ---------------------------------------------------------------- PATH RULES FOR OS/2+EMX: - This describes how sys.path is formed on OS/2+EMX. It describes the - functionality, not the implementation (ie, the order in which these + This describes how sys.path is formed on OS/2+EMX. It describes the + functionality, not the implementation (ie, the order in which these are actually fetched is different) * Python always adds an empty entry at the start, which corresponds @@ -16,10 +16,10 @@ * We attempt to locate the "Python Home" - if the PYTHONHOME env var is set, we believe it. Otherwise, we use the path of our host .EXE's to try and locate our "landmark" (lib\\os.py) and deduce our home. - - If we DO have a Python Home: The relevant sub-directories (Lib, + - If we DO have a Python Home: The relevant sub-directories (Lib, plat-win, etc) are based on the Python Home - If we DO NOT have a Python Home, the core Python Path is - loaded from the registry. This is the main PythonPath key, + loaded from the registry. This is the main PythonPath key, and both HKLM and HKCU are combined to form the path) * Iff - we can not locate the Python Home, and have not had a PYTHONPATH @@ -32,9 +32,9 @@ (either an installed version, or directly from the PCbuild directory), the core path is deduced. - * When Python is hosted in another exe (different directory, embedded via + * When Python is hosted in another exe (different directory, embedded via COM, etc), the Python Home will not be deduced, so the core path from - the registry is used. Other "application paths "in the registry are + the registry is used. Other "application paths "in the registry are always read. * If Python can't find its home and there is no registry (eg, frozen @@ -85,12 +85,12 @@ static int -is_sep(char ch) /* determine if "ch" is a separator character */ +is_sep(char ch) /* determine if "ch" is a separator character */ { #ifdef ALTSEP - return ch == SEP || ch == ALTSEP; + return ch == SEP || ch == ALTSEP; #else - return ch == SEP; + return ch == SEP; #endif } @@ -100,36 +100,36 @@ static void reduce(char *dir) { - size_t i = strlen(dir); - while (i > 0 && !is_sep(dir[i])) - --i; - dir[i] = '\0'; + size_t i = strlen(dir); + while (i > 0 && !is_sep(dir[i])) + --i; + dir[i] = '\0'; } - + static int exists(char *filename) { - struct stat buf; - return stat(filename, &buf) == 0; + struct stat buf; + return stat(filename, &buf) == 0; } /* Is module (check for .pyc/.pyo too) - * Assumes 'filename' MAXPATHLEN+1 bytes long - + * Assumes 'filename' MAXPATHLEN+1 bytes long - * may extend 'filename' by one character. */ static int ismodule(char *filename) { - if (exists(filename)) - return 1; + if (exists(filename)) + return 1; - /* Check for the compiled version of prefix. */ - if (strlen(filename) < MAXPATHLEN) { - strcat(filename, Py_OptimizeFlag ? "o" : "c"); - if (exists(filename)) - return 1; - } - return 0; + /* Check for the compiled version of prefix. */ + if (strlen(filename) < MAXPATHLEN) { + strcat(filename, Py_OptimizeFlag ? "o" : "c"); + if (exists(filename)) + return 1; + } + return 0; } /* Add a path component, by appending stuff to buffer. @@ -145,21 +145,21 @@ static void join(char *buffer, char *stuff) { - size_t n, k; - if (is_sep(stuff[0])) - n = 0; - else { - n = strlen(buffer); - if (n > 0 && !is_sep(buffer[n-1]) && n < MAXPATHLEN) - buffer[n++] = SEP; - } - if (n > MAXPATHLEN) - Py_FatalError("buffer overflow in getpathp.c's joinpath()"); - k = strlen(stuff); - if (n + k > MAXPATHLEN) - k = MAXPATHLEN - n; - strncpy(buffer+n, stuff, k); - buffer[n+k] = '\0'; + size_t n, k; + if (is_sep(stuff[0])) + n = 0; + else { + n = strlen(buffer); + if (n > 0 && !is_sep(buffer[n-1]) && n < MAXPATHLEN) + buffer[n++] = SEP; + } + if (n > MAXPATHLEN) + Py_FatalError("buffer overflow in getpathp.c's joinpath()"); + k = strlen(stuff); + if (n + k > MAXPATHLEN) + k = MAXPATHLEN - n; + strncpy(buffer+n, stuff, k); + buffer[n+k] = '\0'; } /* gotlandmark only called by search_for_prefix, which ensures @@ -169,219 +169,219 @@ static int gotlandmark(char *landmark) { - int n, ok; + int n, ok; - n = strlen(prefix); - join(prefix, landmark); - ok = ismodule(prefix); - prefix[n] = '\0'; - return ok; + n = strlen(prefix); + join(prefix, landmark); + ok = ismodule(prefix); + prefix[n] = '\0'; + return ok; } -/* assumes argv0_path is MAXPATHLEN+1 bytes long, already \0 term'd. +/* assumes argv0_path is MAXPATHLEN+1 bytes long, already \0 term'd. * assumption provided by only caller, calculate_path() */ static int search_for_prefix(char *argv0_path, char *landmark) { - /* Search from argv0_path, until landmark is found */ - strcpy(prefix, argv0_path); - do { - if (gotlandmark(landmark)) - return 1; - reduce(prefix); - } while (prefix[0]); - return 0; + /* Search from argv0_path, until landmark is found */ + strcpy(prefix, argv0_path); + do { + if (gotlandmark(landmark)) + return 1; + reduce(prefix); + } while (prefix[0]); + return 0; } static void get_progpath(void) { - extern char *Py_GetProgramName(void); - char *path = getenv("PATH"); - char *prog = Py_GetProgramName(); - - PPIB pib; - if ((DosGetInfoBlocks(NULL, &pib) == 0) && - (DosQueryModuleName(pib->pib_hmte, sizeof(progpath), progpath) == 0)) - return; - - if (prog == NULL || *prog == '\0') - prog = "python"; - - /* If there is no slash in the argv0 path, then we have to - * assume python is on the user's $PATH, since there's no - * other way to find a directory to start the search from. If - * $PATH isn't exported, you lose. - */ + extern char *Py_GetProgramName(void); + char *path = getenv("PATH"); + char *prog = Py_GetProgramName(); + + PPIB pib; + if ((DosGetInfoBlocks(NULL, &pib) == 0) && + (DosQueryModuleName(pib->pib_hmte, sizeof(progpath), progpath) == 0)) + return; + + if (prog == NULL || *prog == '\0') + prog = "python"; + + /* If there is no slash in the argv0 path, then we have to + * assume python is on the user's $PATH, since there's no + * other way to find a directory to start the search from. If + * $PATH isn't exported, you lose. + */ #ifdef ALTSEP - if (strchr(prog, SEP) || strchr(prog, ALTSEP)) + if (strchr(prog, SEP) || strchr(prog, ALTSEP)) #else - if (strchr(prog, SEP)) + if (strchr(prog, SEP)) #endif - strncpy(progpath, prog, MAXPATHLEN); - else if (path) { - while (1) { - char *delim = strchr(path, DELIM); - - if (delim) { - size_t len = delim - path; - /* ensure we can't overwrite buffer */ + strncpy(progpath, prog, MAXPATHLEN); + else if (path) { + while (1) { + char *delim = strchr(path, DELIM); + + if (delim) { + size_t len = delim - path; + /* ensure we can't overwrite buffer */ #if !defined(PYCC_GCC) - len = min(MAXPATHLEN,len); + len = min(MAXPATHLEN,len); #else - len = MAXPATHLEN < len ? MAXPATHLEN : len; + len = MAXPATHLEN < len ? MAXPATHLEN : len; #endif - strncpy(progpath, path, len); - *(progpath + len) = '\0'; - } - else - strncpy(progpath, path, MAXPATHLEN); - - /* join() is safe for MAXPATHLEN+1 size buffer */ - join(progpath, prog); - if (exists(progpath)) - break; - - if (!delim) { - progpath[0] = '\0'; - break; - } - path = delim + 1; - } - } - else - progpath[0] = '\0'; + strncpy(progpath, path, len); + *(progpath + len) = '\0'; + } + else + strncpy(progpath, path, MAXPATHLEN); + + /* join() is safe for MAXPATHLEN+1 size buffer */ + join(progpath, prog); + if (exists(progpath)) + break; + + if (!delim) { + progpath[0] = '\0'; + break; + } + path = delim + 1; + } + } + else + progpath[0] = '\0'; } static void calculate_path(void) { - char argv0_path[MAXPATHLEN+1]; - char *buf; - size_t bufsz; - char *pythonhome = Py_GetPythonHome(); - char *envpath = getenv("PYTHONPATH"); - char zip_path[MAXPATHLEN+1]; - size_t len; - - get_progpath(); - /* progpath guaranteed \0 terminated in MAXPATH+1 bytes. */ - strcpy(argv0_path, progpath); - reduce(argv0_path); - if (pythonhome == NULL || *pythonhome == '\0') { - if (search_for_prefix(argv0_path, LANDMARK)) - pythonhome = prefix; - else - pythonhome = NULL; - } - else - strncpy(prefix, pythonhome, MAXPATHLEN); - - if (envpath && *envpath == '\0') - envpath = NULL; - - /* Calculate zip archive path */ - strncpy(zip_path, progpath, MAXPATHLEN); - zip_path[MAXPATHLEN] = '\0'; - len = strlen(zip_path); - if (len > 4) { - zip_path[len-3] = 'z'; /* change ending to "zip" */ - zip_path[len-2] = 'i'; - zip_path[len-1] = 'p'; - } - else { - zip_path[0] = 0; - } - - /* We need to construct a path from the following parts. - * (1) the PYTHONPATH environment variable, if set; - * (2) the zip archive file path; - * (3) the PYTHONPATH config macro, with the leading "." - * of each component replaced with pythonhome, if set; - * (4) the directory containing the executable (argv0_path). - * The length calculation calculates #3 first. - */ - - /* Calculate size of return buffer */ - if (pythonhome != NULL) { - char *p; - bufsz = 1; - for (p = PYTHONPATH; *p; p++) { - if (*p == DELIM) - bufsz++; /* number of DELIM plus one */ - } - bufsz *= strlen(pythonhome); - } - else - bufsz = 0; - bufsz += strlen(PYTHONPATH) + 1; - bufsz += strlen(argv0_path) + 1; - bufsz += strlen(zip_path) + 1; - if (envpath != NULL) - bufsz += strlen(envpath) + 1; - - module_search_path = buf = malloc(bufsz); - if (buf == NULL) { - /* We can't exit, so print a warning and limp along */ - fprintf(stderr, "Can't malloc dynamic PYTHONPATH.\n"); - if (envpath) { - fprintf(stderr, "Using environment $PYTHONPATH.\n"); - module_search_path = envpath; - } - else { - fprintf(stderr, "Using default static path.\n"); - module_search_path = PYTHONPATH; - } - return; - } - - if (envpath) { - strcpy(buf, envpath); - buf = strchr(buf, '\0'); - *buf++ = DELIM; - } - if (zip_path[0]) { - strcpy(buf, zip_path); - buf = strchr(buf, '\0'); - *buf++ = DELIM; - } - - if (pythonhome == NULL) { - strcpy(buf, PYTHONPATH); - buf = strchr(buf, '\0'); - } - else { - char *p = PYTHONPATH; - char *q; - size_t n; - for (;;) { - q = strchr(p, DELIM); - if (q == NULL) - n = strlen(p); - else - n = q-p; - if (p[0] == '.' && is_sep(p[1])) { - strcpy(buf, pythonhome); - buf = strchr(buf, '\0'); - p++; - n--; - } - strncpy(buf, p, n); - buf += n; - if (q == NULL) - break; - *buf++ = DELIM; - p = q+1; - } - } - if (argv0_path) { - *buf++ = DELIM; - strcpy(buf, argv0_path); - buf = strchr(buf, '\0'); - } - *buf = '\0'; + char argv0_path[MAXPATHLEN+1]; + char *buf; + size_t bufsz; + char *pythonhome = Py_GetPythonHome(); + char *envpath = getenv("PYTHONPATH"); + char zip_path[MAXPATHLEN+1]; + size_t len; + + get_progpath(); + /* progpath guaranteed \0 terminated in MAXPATH+1 bytes. */ + strcpy(argv0_path, progpath); + reduce(argv0_path); + if (pythonhome == NULL || *pythonhome == '\0') { + if (search_for_prefix(argv0_path, LANDMARK)) + pythonhome = prefix; + else + pythonhome = NULL; + } + else + strncpy(prefix, pythonhome, MAXPATHLEN); + + if (envpath && *envpath == '\0') + envpath = NULL; + + /* Calculate zip archive path */ + strncpy(zip_path, progpath, MAXPATHLEN); + zip_path[MAXPATHLEN] = '\0'; + len = strlen(zip_path); + if (len > 4) { + zip_path[len-3] = 'z'; /* change ending to "zip" */ + zip_path[len-2] = 'i'; + zip_path[len-1] = 'p'; + } + else { + zip_path[0] = 0; + } + + /* We need to construct a path from the following parts. + * (1) the PYTHONPATH environment variable, if set; + * (2) the zip archive file path; + * (3) the PYTHONPATH config macro, with the leading "." + * of each component replaced with pythonhome, if set; + * (4) the directory containing the executable (argv0_path). + * The length calculation calculates #3 first. + */ + + /* Calculate size of return buffer */ + if (pythonhome != NULL) { + char *p; + bufsz = 1; + for (p = PYTHONPATH; *p; p++) { + if (*p == DELIM) + bufsz++; /* number of DELIM plus one */ + } + bufsz *= strlen(pythonhome); + } + else + bufsz = 0; + bufsz += strlen(PYTHONPATH) + 1; + bufsz += strlen(argv0_path) + 1; + bufsz += strlen(zip_path) + 1; + if (envpath != NULL) + bufsz += strlen(envpath) + 1; + + module_search_path = buf = malloc(bufsz); + if (buf == NULL) { + /* We can't exit, so print a warning and limp along */ + fprintf(stderr, "Can't malloc dynamic PYTHONPATH.\n"); + if (envpath) { + fprintf(stderr, "Using environment $PYTHONPATH.\n"); + module_search_path = envpath; + } + else { + fprintf(stderr, "Using default static path.\n"); + module_search_path = PYTHONPATH; + } + return; + } + + if (envpath) { + strcpy(buf, envpath); + buf = strchr(buf, '\0'); + *buf++ = DELIM; + } + if (zip_path[0]) { + strcpy(buf, zip_path); + buf = strchr(buf, '\0'); + *buf++ = DELIM; + } + + if (pythonhome == NULL) { + strcpy(buf, PYTHONPATH); + buf = strchr(buf, '\0'); + } + else { + char *p = PYTHONPATH; + char *q; + size_t n; + for (;;) { + q = strchr(p, DELIM); + if (q == NULL) + n = strlen(p); + else + n = q-p; + if (p[0] == '.' && is_sep(p[1])) { + strcpy(buf, pythonhome); + buf = strchr(buf, '\0'); + p++; + n--; + } + strncpy(buf, p, n); + buf += n; + if (q == NULL) + break; + *buf++ = DELIM; + p = q+1; + } + } + if (argv0_path) { + *buf++ = DELIM; + strcpy(buf, argv0_path); + buf = strchr(buf, '\0'); + } + *buf = '\0'; } @@ -390,29 +390,29 @@ char * Py_GetPath(void) { - if (!module_search_path) - calculate_path(); - return module_search_path; + if (!module_search_path) + calculate_path(); + return module_search_path; } char * Py_GetPrefix(void) { - if (!module_search_path) - calculate_path(); - return prefix; + if (!module_search_path) + calculate_path(); + return prefix; } char * Py_GetExecPrefix(void) { - return Py_GetPrefix(); + return Py_GetPrefix(); } char * Py_GetProgramFullPath(void) { - if (!module_search_path) - calculate_path(); - return progpath; + if (!module_search_path) + calculate_path(); + return progpath; } Modified: python/branches/py3k/PC/os2emx/pythonpm.c ============================================================================== --- python/branches/py3k/PC/os2emx/pythonpm.c (original) +++ python/branches/py3k/PC/os2emx/pythonpm.c Sun May 9 17:52:27 2010 @@ -27,10 +27,10 @@ /* use structure to pass command line to Python thread */ typedef struct { - int argc; - char **argv; - HWND Frame; - int running; + int argc; + char **argv; + HWND Frame; + int running; } arglist; /* make this a global to simplify access. @@ -45,80 +45,80 @@ int main(int argc, char **argv) { - ULONG FrameFlags = FCF_TITLEBAR | - FCF_SYSMENU | - FCF_SIZEBORDER | - FCF_HIDEBUTTON | - FCF_SHELLPOSITION | - FCF_TASKLIST; - HAB hab; - HMQ hmq; - HWND Client; - QMSG qmsg; - arglist args; - int python_tid; - - /* init PM and create message queue */ - hab = WinInitialize(0); - hmq = WinCreateMsgQueue(hab, 0); - - /* create a (hidden) Window to house the window procedure */ - args.Frame = WinCreateStdWindow(HWND_DESKTOP, - 0, - &FrameFlags, - NULL, - "PythonPM", - 0L, - 0, - 0, - &Client); - - /* run Python interpreter in a thread */ - args.argc = argc; - args.argv = argv; - args.running = 0; - if (-1 == (python_tid = _beginthread(PythonThread, NULL, 1024 * 1024, &args))) - { - /* couldn't start thread */ - WinAlarm(HWND_DESKTOP, WA_ERROR); - PythonRC = 1; - } - else - { - /* process PM messages, until Python exits */ - while (WinGetMsg(hab, &qmsg, NULLHANDLE, 0, 0)) - WinDispatchMsg(hab, &qmsg); - if (args.running > 0) - DosKillThread(python_tid); - } - - /* destroy window, shutdown message queue and PM */ - WinDestroyWindow(args.Frame); - WinDestroyMsgQueue(hmq); - WinTerminate(hab); + ULONG FrameFlags = FCF_TITLEBAR | + FCF_SYSMENU | + FCF_SIZEBORDER | + FCF_HIDEBUTTON | + FCF_SHELLPOSITION | + FCF_TASKLIST; + HAB hab; + HMQ hmq; + HWND Client; + QMSG qmsg; + arglist args; + int python_tid; + + /* init PM and create message queue */ + hab = WinInitialize(0); + hmq = WinCreateMsgQueue(hab, 0); + + /* create a (hidden) Window to house the window procedure */ + args.Frame = WinCreateStdWindow(HWND_DESKTOP, + 0, + &FrameFlags, + NULL, + "PythonPM", + 0L, + 0, + 0, + &Client); + + /* run Python interpreter in a thread */ + args.argc = argc; + args.argv = argv; + args.running = 0; + if (-1 == (python_tid = _beginthread(PythonThread, NULL, 1024 * 1024, &args))) + { + /* couldn't start thread */ + WinAlarm(HWND_DESKTOP, WA_ERROR); + PythonRC = 1; + } + else + { + /* process PM messages, until Python exits */ + while (WinGetMsg(hab, &qmsg, NULLHANDLE, 0, 0)) + WinDispatchMsg(hab, &qmsg); + if (args.running > 0) + DosKillThread(python_tid); + } + + /* destroy window, shutdown message queue and PM */ + WinDestroyWindow(args.Frame); + WinDestroyMsgQueue(hmq); + WinTerminate(hab); - return PythonRC; + return PythonRC; } void PythonThread(void *argl) { - HAB hab; - arglist *args; + HAB hab; + arglist *args; - /* PM initialisation */ - hab = WinInitialize(0); + /* PM initialisation */ + hab = WinInitialize(0); - /* start Python */ - args = (arglist *)argl; - args->running = 1; - PythonRC = Py_Main(args->argc, args->argv); - - /* enter a critical section and send the termination message */ - DosEnterCritSec(); - args->running = 0; - WinPostMsg(args->Frame, WM_QUIT, NULL, NULL); - - /* shutdown PM and terminate thread */ - WinTerminate(hab); - _endthread(); + /* start Python */ + args = (arglist *)argl; + args->running = 1; + PythonRC = Py_Main(args->argc, args->argv); + + /* enter a critical section and send the termination message */ + DosEnterCritSec(); + args->running = 0; + WinPostMsg(args->Frame, WM_QUIT, NULL, NULL); + + /* shutdown PM and terminate thread */ + WinTerminate(hab); + _endthread(); } Modified: python/branches/py3k/PC/os2vacpp/getpathp.c ============================================================================== --- python/branches/py3k/PC/os2vacpp/getpathp.c (original) +++ python/branches/py3k/PC/os2vacpp/getpathp.c Sun May 9 17:52:27 2010 @@ -55,12 +55,12 @@ static int -is_sep(char ch) /* determine if "ch" is a separator character */ +is_sep(char ch) /* determine if "ch" is a separator character */ { #ifdef ALTSEP - return ch == SEP || ch == ALTSEP; + return ch == SEP || ch == ALTSEP; #else - return ch == SEP; + return ch == SEP; #endif } @@ -68,18 +68,18 @@ static void reduce(char *dir) { - int i = strlen(dir); - while (i > 0 && !is_sep(dir[i])) - --i; - dir[i] = '\0'; + int i = strlen(dir); + while (i > 0 && !is_sep(dir[i])) + --i; + dir[i] = '\0'; } - + static int exists(char *filename) { - struct stat buf; - return stat(filename, &buf) == 0; + struct stat buf; + return stat(filename, &buf) == 0; } @@ -95,42 +95,42 @@ static void join(char *buffer, char *stuff) { - int n, k; - if (is_sep(stuff[0])) - n = 0; - else { - n = strlen(buffer); - if (n > 0 && !is_sep(buffer[n-1]) && n < MAXPATHLEN) - buffer[n++] = SEP; - } - if (n > MAXPATHLEN) - Py_FatalError("buffer overflow in getpathp.c's joinpath()"); - k = strlen(stuff); - if (n + k > MAXPATHLEN) - k = MAXPATHLEN - n; - strncpy(buffer+n, stuff, k); - buffer[n+k] = '\0'; + int n, k; + if (is_sep(stuff[0])) + n = 0; + else { + n = strlen(buffer); + if (n > 0 && !is_sep(buffer[n-1]) && n < MAXPATHLEN) + buffer[n++] = SEP; + } + if (n > MAXPATHLEN) + Py_FatalError("buffer overflow in getpathp.c's joinpath()"); + k = strlen(stuff); + if (n + k > MAXPATHLEN) + k = MAXPATHLEN - n; + strncpy(buffer+n, stuff, k); + buffer[n+k] = '\0'; } static int search_for_prefix(char *argv0_path, char *landmark) { - int n; + int n; - /* Search from argv0_path, until root is found */ - strcpy(prefix, argv0_path); - do { - n = strlen(prefix); - join(prefix, landmark); - if (exists(prefix)) { - prefix[n] = '\0'; - return 1; - } - prefix[n] = '\0'; - reduce(prefix); - } while (prefix[0]); - return 0; + /* Search from argv0_path, until root is found */ + strcpy(prefix, argv0_path); + do { + n = strlen(prefix); + join(prefix, landmark); + if (exists(prefix)) { + prefix[n] = '\0'; + return 1; + } + prefix[n] = '\0'; + reduce(prefix); + } while (prefix[0]); + return 0; } #ifdef MS_WIN32 @@ -147,299 +147,299 @@ static char * getpythonregpath(HKEY keyBase, BOOL bWin32s) { - HKEY newKey = 0; - DWORD nameSize = 0; - DWORD dataSize = 0; - DWORD numEntries = 0; - LONG rc; - char *retval = NULL; - char *dataBuf; - const char keyPrefix[] = "Software\\Python\\PythonCore\\"; - const char keySuffix[] = "\\PythonPath"; - int versionLen; - char *keyBuf; - - // Tried to use sysget("winver") but here is too early :-( - versionLen = strlen(PyWin_DLLVersionString); - // alloca == no free required, but memory only local to fn. - // also no heap fragmentation! Am I being silly? - keyBuf = alloca(sizeof(keyPrefix)-1 + versionLen + sizeof(keySuffix)); // chars only, plus 1 NULL. - // lots of constants here for the compiler to optimize away :-) - memcpy(keyBuf, keyPrefix, sizeof(keyPrefix)-1); - memcpy(keyBuf+sizeof(keyPrefix)-1, PyWin_DLLVersionString, versionLen); - memcpy(keyBuf+sizeof(keyPrefix)-1+versionLen, keySuffix, sizeof(keySuffix)); // NULL comes with this one! - - rc=RegOpenKey(keyBase, - keyBuf, - &newKey); - if (rc==ERROR_SUCCESS) { - RegQueryInfoKey(newKey, NULL, NULL, NULL, NULL, NULL, NULL, - &numEntries, &nameSize, &dataSize, NULL, NULL); - } - if (bWin32s && numEntries==0 && dataSize==0) { - /* must hardcode for Win32s */ - numEntries = 1; - dataSize = 511; - } - if (numEntries) { - /* Loop over all subkeys. */ - /* Win32s doesnt know how many subkeys, so we do - it twice */ - char keyBuf[MAX_PATH+1]; - int index = 0; - int off = 0; - for(index=0;;index++) { - long reqdSize = 0; - DWORD rc = RegEnumKey(newKey, - index, keyBuf, MAX_PATH+1); - if (rc) break; - rc = RegQueryValue(newKey, keyBuf, NULL, &reqdSize); - if (rc) break; - if (bWin32s && reqdSize==0) reqdSize = 512; - dataSize += reqdSize + 1; /* 1 for the ";" */ - } - dataBuf = malloc(dataSize+1); - if (dataBuf==NULL) - return NULL; /* pretty serious? Raise error? */ - /* Now loop over, grabbing the paths. - Subkeys before main library */ - for(index=0;;index++) { - int adjust; - long reqdSize = dataSize; - DWORD rc = RegEnumKey(newKey, - index, keyBuf,MAX_PATH+1); - if (rc) break; - rc = RegQueryValue(newKey, - keyBuf, dataBuf+off, &reqdSize); - if (rc) break; - if (reqdSize>1) { - /* If Nothing, or only '\0' copied. */ - adjust = strlen(dataBuf+off); - dataSize -= adjust; - off += adjust; - dataBuf[off++] = ';'; - dataBuf[off] = '\0'; - dataSize--; - } - } - /* Additionally, win32s doesnt work as expected, so - the specific strlen() is required for 3.1. */ - rc = RegQueryValue(newKey, "", dataBuf+off, &dataSize); - if (rc==ERROR_SUCCESS) { - if (strlen(dataBuf)==0) - free(dataBuf); - else - retval = dataBuf; /* caller will free */ - } - else - free(dataBuf); - } - - if (newKey) - RegCloseKey(newKey); - return retval; + HKEY newKey = 0; + DWORD nameSize = 0; + DWORD dataSize = 0; + DWORD numEntries = 0; + LONG rc; + char *retval = NULL; + char *dataBuf; + const char keyPrefix[] = "Software\\Python\\PythonCore\\"; + const char keySuffix[] = "\\PythonPath"; + int versionLen; + char *keyBuf; + + // Tried to use sysget("winver") but here is too early :-( + versionLen = strlen(PyWin_DLLVersionString); + // alloca == no free required, but memory only local to fn. + // also no heap fragmentation! Am I being silly? + keyBuf = alloca(sizeof(keyPrefix)-1 + versionLen + sizeof(keySuffix)); // chars only, plus 1 NULL. + // lots of constants here for the compiler to optimize away :-) + memcpy(keyBuf, keyPrefix, sizeof(keyPrefix)-1); + memcpy(keyBuf+sizeof(keyPrefix)-1, PyWin_DLLVersionString, versionLen); + memcpy(keyBuf+sizeof(keyPrefix)-1+versionLen, keySuffix, sizeof(keySuffix)); // NULL comes with this one! + + rc=RegOpenKey(keyBase, + keyBuf, + &newKey); + if (rc==ERROR_SUCCESS) { + RegQueryInfoKey(newKey, NULL, NULL, NULL, NULL, NULL, NULL, + &numEntries, &nameSize, &dataSize, NULL, NULL); + } + if (bWin32s && numEntries==0 && dataSize==0) { + /* must hardcode for Win32s */ + numEntries = 1; + dataSize = 511; + } + if (numEntries) { + /* Loop over all subkeys. */ + /* Win32s doesnt know how many subkeys, so we do + it twice */ + char keyBuf[MAX_PATH+1]; + int index = 0; + int off = 0; + for(index=0;;index++) { + long reqdSize = 0; + DWORD rc = RegEnumKey(newKey, + index, keyBuf, MAX_PATH+1); + if (rc) break; + rc = RegQueryValue(newKey, keyBuf, NULL, &reqdSize); + if (rc) break; + if (bWin32s && reqdSize==0) reqdSize = 512; + dataSize += reqdSize + 1; /* 1 for the ";" */ + } + dataBuf = malloc(dataSize+1); + if (dataBuf==NULL) + return NULL; /* pretty serious? Raise error? */ + /* Now loop over, grabbing the paths. + Subkeys before main library */ + for(index=0;;index++) { + int adjust; + long reqdSize = dataSize; + DWORD rc = RegEnumKey(newKey, + index, keyBuf,MAX_PATH+1); + if (rc) break; + rc = RegQueryValue(newKey, + keyBuf, dataBuf+off, &reqdSize); + if (rc) break; + if (reqdSize>1) { + /* If Nothing, or only '\0' copied. */ + adjust = strlen(dataBuf+off); + dataSize -= adjust; + off += adjust; + dataBuf[off++] = ';'; + dataBuf[off] = '\0'; + dataSize--; + } + } + /* Additionally, win32s doesnt work as expected, so + the specific strlen() is required for 3.1. */ + rc = RegQueryValue(newKey, "", dataBuf+off, &dataSize); + if (rc==ERROR_SUCCESS) { + if (strlen(dataBuf)==0) + free(dataBuf); + else + retval = dataBuf; /* caller will free */ + } + else + free(dataBuf); + } + + if (newKey) + RegCloseKey(newKey); + return retval; } #endif /* MS_WIN32 */ static void get_progpath(void) { - extern char *Py_GetProgramName(void); - char *path = getenv("PATH"); - char *prog = Py_GetProgramName(); + extern char *Py_GetProgramName(void); + char *path = getenv("PATH"); + char *prog = Py_GetProgramName(); #ifdef MS_WIN32 - if (GetModuleFileName(NULL, progpath, MAXPATHLEN)) - return; + if (GetModuleFileName(NULL, progpath, MAXPATHLEN)) + return; #endif - if (prog == NULL || *prog == '\0') - prog = "python"; + if (prog == NULL || *prog == '\0') + prog = "python"; - /* If there is no slash in the argv0 path, then we have to - * assume python is on the user's $PATH, since there's no - * other way to find a directory to start the search from. If - * $PATH isn't exported, you lose. - */ + /* If there is no slash in the argv0 path, then we have to + * assume python is on the user's $PATH, since there's no + * other way to find a directory to start the search from. If + * $PATH isn't exported, you lose. + */ #ifdef ALTSEP - if (strchr(prog, SEP) || strchr(prog, ALTSEP)) + if (strchr(prog, SEP) || strchr(prog, ALTSEP)) #else - if (strchr(prog, SEP)) + if (strchr(prog, SEP)) #endif - strcpy(progpath, prog); - else if (path) { - while (1) { - char *delim = strchr(path, DELIM); - - if (delim) { - int len = delim - path; - strncpy(progpath, path, len); - *(progpath + len) = '\0'; - } - else - strcpy(progpath, path); - - join(progpath, prog); - if (exists(progpath)) - break; - - if (!delim) { - progpath[0] = '\0'; - break; - } - path = delim + 1; - } - } - else - progpath[0] = '\0'; + strcpy(progpath, prog); + else if (path) { + while (1) { + char *delim = strchr(path, DELIM); + + if (delim) { + int len = delim - path; + strncpy(progpath, path, len); + *(progpath + len) = '\0'; + } + else + strcpy(progpath, path); + + join(progpath, prog); + if (exists(progpath)) + break; + + if (!delim) { + progpath[0] = '\0'; + break; + } + path = delim + 1; + } + } + else + progpath[0] = '\0'; } static void calculate_path(void) { - char argv0_path[MAXPATHLEN+1]; - char *buf; - int bufsz; - char *pythonhome = Py_GetPythonHome(); - char *envpath = Py_GETENV("PYTHONPATH"); + char argv0_path[MAXPATHLEN+1]; + char *buf; + int bufsz; + char *pythonhome = Py_GetPythonHome(); + char *envpath = Py_GETENV("PYTHONPATH"); #ifdef MS_WIN32 - char *machinepath, *userpath; + char *machinepath, *userpath; - /* Are we running under Windows 3.1(1) Win32s? */ - if (PyWin_IsWin32s()) { - /* Only CLASSES_ROOT is supported */ - machinepath = getpythonregpath(HKEY_CLASSES_ROOT, TRUE); - userpath = NULL; - } else { - machinepath = getpythonregpath(HKEY_LOCAL_MACHINE, FALSE); - userpath = getpythonregpath(HKEY_CURRENT_USER, FALSE); - } + /* Are we running under Windows 3.1(1) Win32s? */ + if (PyWin_IsWin32s()) { + /* Only CLASSES_ROOT is supported */ + machinepath = getpythonregpath(HKEY_CLASSES_ROOT, TRUE); + userpath = NULL; + } else { + machinepath = getpythonregpath(HKEY_LOCAL_MACHINE, FALSE); + userpath = getpythonregpath(HKEY_CURRENT_USER, FALSE); + } #endif - get_progpath(); - strcpy(argv0_path, progpath); - reduce(argv0_path); - if (pythonhome == NULL || *pythonhome == '\0') { - if (search_for_prefix(argv0_path, LANDMARK)) - pythonhome = prefix; - else - pythonhome = NULL; - } - else { - char *delim; - - strcpy(prefix, pythonhome); - - /* Extract Any Optional Trailing EXEC_PREFIX */ - /* e.g. PYTHONHOME=: */ - delim = strchr(prefix, DELIM); - if (delim) { - *delim = '\0'; - strcpy(exec_prefix, delim+1); - } else - strcpy(exec_prefix, EXEC_PREFIX); - } - - if (envpath && *envpath == '\0') - envpath = NULL; - - /* We need to construct a path from the following parts: - (1) the PYTHONPATH environment variable, if set; - (2) for Win32, the machinepath and userpath, if set; - (3) the PYTHONPATH config macro, with the leading "." - of each component replaced with pythonhome, if set; - (4) the directory containing the executable (argv0_path). - The length calculation calculates #3 first. - */ - - /* Calculate size of return buffer */ - if (pythonhome != NULL) { - char *p; - bufsz = 1; - for (p = PYTHONPATH; *p; p++) { - if (*p == DELIM) - bufsz++; /* number of DELIM plus one */ - } - bufsz *= strlen(pythonhome); - } - else - bufsz = 0; - bufsz += strlen(PYTHONPATH) + 1; - if (envpath != NULL) - bufsz += strlen(envpath) + 1; - bufsz += strlen(argv0_path) + 1; + get_progpath(); + strcpy(argv0_path, progpath); + reduce(argv0_path); + if (pythonhome == NULL || *pythonhome == '\0') { + if (search_for_prefix(argv0_path, LANDMARK)) + pythonhome = prefix; + else + pythonhome = NULL; + } + else { + char *delim; + + strcpy(prefix, pythonhome); + + /* Extract Any Optional Trailing EXEC_PREFIX */ + /* e.g. PYTHONHOME=: */ + delim = strchr(prefix, DELIM); + if (delim) { + *delim = '\0'; + strcpy(exec_prefix, delim+1); + } else + strcpy(exec_prefix, EXEC_PREFIX); + } + + if (envpath && *envpath == '\0') + envpath = NULL; + + /* We need to construct a path from the following parts: + (1) the PYTHONPATH environment variable, if set; + (2) for Win32, the machinepath and userpath, if set; + (3) the PYTHONPATH config macro, with the leading "." + of each component replaced with pythonhome, if set; + (4) the directory containing the executable (argv0_path). + The length calculation calculates #3 first. + */ + + /* Calculate size of return buffer */ + if (pythonhome != NULL) { + char *p; + bufsz = 1; + for (p = PYTHONPATH; *p; p++) { + if (*p == DELIM) + bufsz++; /* number of DELIM plus one */ + } + bufsz *= strlen(pythonhome); + } + else + bufsz = 0; + bufsz += strlen(PYTHONPATH) + 1; + if (envpath != NULL) + bufsz += strlen(envpath) + 1; + bufsz += strlen(argv0_path) + 1; #ifdef MS_WIN32 - if (machinepath) - bufsz += strlen(machinepath) + 1; - if (userpath) - bufsz += strlen(userpath) + 1; + if (machinepath) + bufsz += strlen(machinepath) + 1; + if (userpath) + bufsz += strlen(userpath) + 1; #endif - module_search_path = buf = malloc(bufsz); - if (buf == NULL) { - /* We can't exit, so print a warning and limp along */ - fprintf(stderr, "Can't malloc dynamic PYTHONPATH.\n"); - if (envpath) { - fprintf(stderr, "Using default static $PYTHONPATH.\n"); - module_search_path = envpath; - } - else { - fprintf(stderr, "Using environment $PYTHONPATH.\n"); - module_search_path = PYTHONPATH; - } - return; - } - - if (envpath) { - strcpy(buf, envpath); - buf = strchr(buf, '\0'); - *buf++ = DELIM; - } + module_search_path = buf = malloc(bufsz); + if (buf == NULL) { + /* We can't exit, so print a warning and limp along */ + fprintf(stderr, "Can't malloc dynamic PYTHONPATH.\n"); + if (envpath) { + fprintf(stderr, "Using default static $PYTHONPATH.\n"); + module_search_path = envpath; + } + else { + fprintf(stderr, "Using environment $PYTHONPATH.\n"); + module_search_path = PYTHONPATH; + } + return; + } + + if (envpath) { + strcpy(buf, envpath); + buf = strchr(buf, '\0'); + *buf++ = DELIM; + } #ifdef MS_WIN32 - if (machinepath) { - strcpy(buf, machinepath); - buf = strchr(buf, '\0'); - *buf++ = DELIM; - } - if (userpath) { - strcpy(buf, userpath); - buf = strchr(buf, '\0'); - *buf++ = DELIM; - } + if (machinepath) { + strcpy(buf, machinepath); + buf = strchr(buf, '\0'); + *buf++ = DELIM; + } + if (userpath) { + strcpy(buf, userpath); + buf = strchr(buf, '\0'); + *buf++ = DELIM; + } #endif - if (pythonhome == NULL) { - strcpy(buf, PYTHONPATH); - buf = strchr(buf, '\0'); - } - else { - char *p = PYTHONPATH; - char *q; - int n; - for (;;) { - q = strchr(p, DELIM); - if (q == NULL) - n = strlen(p); - else - n = q-p; - if (p[0] == '.' && is_sep(p[1])) { - strcpy(buf, pythonhome); - buf = strchr(buf, '\0'); - p++; - n--; - } - strncpy(buf, p, n); - buf += n; - if (q == NULL) - break; - *buf++ = DELIM; - p = q+1; - } - } - if (argv0_path) { - *buf++ = DELIM; - strcpy(buf, argv0_path); - buf = strchr(buf, '\0'); - } - *buf = '\0'; + if (pythonhome == NULL) { + strcpy(buf, PYTHONPATH); + buf = strchr(buf, '\0'); + } + else { + char *p = PYTHONPATH; + char *q; + int n; + for (;;) { + q = strchr(p, DELIM); + if (q == NULL) + n = strlen(p); + else + n = q-p; + if (p[0] == '.' && is_sep(p[1])) { + strcpy(buf, pythonhome); + buf = strchr(buf, '\0'); + p++; + n--; + } + strncpy(buf, p, n); + buf += n; + if (q == NULL) + break; + *buf++ = DELIM; + p = q+1; + } + } + if (argv0_path) { + *buf++ = DELIM; + strcpy(buf, argv0_path); + buf = strchr(buf, '\0'); + } + *buf = '\0'; } @@ -448,35 +448,35 @@ char * Py_GetPath(void) { - if (!module_search_path) - calculate_path(); + if (!module_search_path) + calculate_path(); - return module_search_path; + return module_search_path; } char * Py_GetPrefix(void) { - if (!module_search_path) - calculate_path(); + if (!module_search_path) + calculate_path(); - return prefix; + return prefix; } char * Py_GetExecPrefix(void) { - if (!module_search_path) - calculate_path(); + if (!module_search_path) + calculate_path(); - return exec_prefix; + return exec_prefix; } char * Py_GetProgramFullPath(void) { - if (!module_search_path) - calculate_path(); + if (!module_search_path) + calculate_path(); - return progpath; + return progpath; } Modified: python/branches/py3k/PC/winreg.c ============================================================================== --- python/branches/py3k/PC/winreg.c (original) +++ python/branches/py3k/PC/winreg.c Sun May 9 17:52:27 2010 @@ -4,7 +4,7 @@ Windows Registry access module for Python. * Simple registry access written by Mark Hammond in win32api - module circa 1995. + module circa 1995. * Bill Tutt expanded the support significantly not long after. * Numerous other people have submitted patches since then. * Ripped from win32api module 03-Feb-2000 by Mark Hammond, and @@ -28,7 +28,7 @@ want to lose this info... */ #define PyErr_SetFromWindowsErrWithFunction(rc, fnname) \ - PyErr_SetFromWindowsErr(rc) + PyErr_SetFromWindowsErr(rc) /* Forward declares */ @@ -383,8 +383,8 @@ ************************************************************************/ typedef struct { - PyObject_VAR_HEAD - HKEY hkey; + PyObject_VAR_HEAD + HKEY hkey; } PyHKEYObject; #define PyHKEY_Check(op) ((op)->ob_type == &PyHKEY_Type) @@ -394,95 +394,95 @@ static PyObject * PyHKEY_unaryFailureFunc(PyObject *ob) { - PyErr_SetString(PyExc_TypeError, failMsg); - return NULL; + PyErr_SetString(PyExc_TypeError, failMsg); + return NULL; } static PyObject * PyHKEY_binaryFailureFunc(PyObject *ob1, PyObject *ob2) { - PyErr_SetString(PyExc_TypeError, failMsg); - return NULL; + PyErr_SetString(PyExc_TypeError, failMsg); + return NULL; } static PyObject * PyHKEY_ternaryFailureFunc(PyObject *ob1, PyObject *ob2, PyObject *ob3) { - PyErr_SetString(PyExc_TypeError, failMsg); - return NULL; + PyErr_SetString(PyExc_TypeError, failMsg); + return NULL; } static void PyHKEY_deallocFunc(PyObject *ob) { - /* Can not call PyHKEY_Close, as the ob->tp_type - has already been cleared, thus causing the type - check to fail! - */ - PyHKEYObject *obkey = (PyHKEYObject *)ob; - if (obkey->hkey) - RegCloseKey((HKEY)obkey->hkey); - PyObject_DEL(ob); + /* Can not call PyHKEY_Close, as the ob->tp_type + has already been cleared, thus causing the type + check to fail! + */ + PyHKEYObject *obkey = (PyHKEYObject *)ob; + if (obkey->hkey) + RegCloseKey((HKEY)obkey->hkey); + PyObject_DEL(ob); } static int PyHKEY_boolFunc(PyObject *ob) { - return ((PyHKEYObject *)ob)->hkey != 0; + return ((PyHKEYObject *)ob)->hkey != 0; } static PyObject * PyHKEY_intFunc(PyObject *ob) { - PyHKEYObject *pyhkey = (PyHKEYObject *)ob; - return PyLong_FromVoidPtr(pyhkey->hkey); + PyHKEYObject *pyhkey = (PyHKEYObject *)ob; + return PyLong_FromVoidPtr(pyhkey->hkey); } static PyObject * PyHKEY_strFunc(PyObject *ob) { - PyHKEYObject *pyhkey = (PyHKEYObject *)ob; - return PyUnicode_FromFormat("", pyhkey->hkey); + PyHKEYObject *pyhkey = (PyHKEYObject *)ob; + return PyUnicode_FromFormat("", pyhkey->hkey); } static int PyHKEY_compareFunc(PyObject *ob1, PyObject *ob2) { - PyHKEYObject *pyhkey1 = (PyHKEYObject *)ob1; - PyHKEYObject *pyhkey2 = (PyHKEYObject *)ob2; - return pyhkey1 == pyhkey2 ? 0 : - (pyhkey1 < pyhkey2 ? -1 : 1); + PyHKEYObject *pyhkey1 = (PyHKEYObject *)ob1; + PyHKEYObject *pyhkey2 = (PyHKEYObject *)ob2; + return pyhkey1 == pyhkey2 ? 0 : + (pyhkey1 < pyhkey2 ? -1 : 1); } static long PyHKEY_hashFunc(PyObject *ob) { - /* Just use the address. - XXX - should we use the handle value? - */ - return _Py_HashPointer(ob); + /* Just use the address. + XXX - should we use the handle value? + */ + return _Py_HashPointer(ob); } static PyNumberMethods PyHKEY_NumberMethods = { - PyHKEY_binaryFailureFunc, /* nb_add */ - PyHKEY_binaryFailureFunc, /* nb_subtract */ - PyHKEY_binaryFailureFunc, /* nb_multiply */ - PyHKEY_binaryFailureFunc, /* nb_remainder */ - PyHKEY_binaryFailureFunc, /* nb_divmod */ - PyHKEY_ternaryFailureFunc, /* nb_power */ - PyHKEY_unaryFailureFunc, /* nb_negative */ - PyHKEY_unaryFailureFunc, /* nb_positive */ - PyHKEY_unaryFailureFunc, /* nb_absolute */ - PyHKEY_boolFunc, /* nb_bool */ - PyHKEY_unaryFailureFunc, /* nb_invert */ - PyHKEY_binaryFailureFunc, /* nb_lshift */ - PyHKEY_binaryFailureFunc, /* nb_rshift */ - PyHKEY_binaryFailureFunc, /* nb_and */ - PyHKEY_binaryFailureFunc, /* nb_xor */ - PyHKEY_binaryFailureFunc, /* nb_or */ - PyHKEY_intFunc, /* nb_int */ - 0, /* nb_reserved */ - PyHKEY_unaryFailureFunc, /* nb_float */ + PyHKEY_binaryFailureFunc, /* nb_add */ + PyHKEY_binaryFailureFunc, /* nb_subtract */ + PyHKEY_binaryFailureFunc, /* nb_multiply */ + PyHKEY_binaryFailureFunc, /* nb_remainder */ + PyHKEY_binaryFailureFunc, /* nb_divmod */ + PyHKEY_ternaryFailureFunc, /* nb_power */ + PyHKEY_unaryFailureFunc, /* nb_negative */ + PyHKEY_unaryFailureFunc, /* nb_positive */ + PyHKEY_unaryFailureFunc, /* nb_absolute */ + PyHKEY_boolFunc, /* nb_bool */ + PyHKEY_unaryFailureFunc, /* nb_invert */ + PyHKEY_binaryFailureFunc, /* nb_lshift */ + PyHKEY_binaryFailureFunc, /* nb_rshift */ + PyHKEY_binaryFailureFunc, /* nb_and */ + PyHKEY_binaryFailureFunc, /* nb_xor */ + PyHKEY_binaryFailureFunc, /* nb_or */ + PyHKEY_intFunc, /* nb_int */ + 0, /* nb_reserved */ + PyHKEY_unaryFailureFunc, /* nb_float */ }; static PyObject *PyHKEY_CloseMethod(PyObject *self, PyObject *args); @@ -491,51 +491,51 @@ static PyObject *PyHKEY_Exit(PyObject *self, PyObject *args); static struct PyMethodDef PyHKEY_methods[] = { - {"Close", PyHKEY_CloseMethod, METH_VARARGS, PyHKEY_Close_doc}, - {"Detach", PyHKEY_DetachMethod, METH_VARARGS, PyHKEY_Detach_doc}, - {"__enter__", (PyCFunction)PyHKEY_Enter, METH_NOARGS, NULL}, - {"__exit__", PyHKEY_Exit, METH_VARARGS, NULL}, - {NULL} + {"Close", PyHKEY_CloseMethod, METH_VARARGS, PyHKEY_Close_doc}, + {"Detach", PyHKEY_DetachMethod, METH_VARARGS, PyHKEY_Detach_doc}, + {"__enter__", (PyCFunction)PyHKEY_Enter, METH_NOARGS, NULL}, + {"__exit__", PyHKEY_Exit, METH_VARARGS, NULL}, + {NULL} }; #define OFF(e) offsetof(PyHKEYObject, e) static PyMemberDef PyHKEY_memberlist[] = { - {"handle", T_INT, OFF(hkey), READONLY}, - {NULL} /* Sentinel */ + {"handle", T_INT, OFF(hkey), READONLY}, + {NULL} /* Sentinel */ }; /* The type itself */ PyTypeObject PyHKEY_Type = { - PyVarObject_HEAD_INIT(0, 0) /* fill in type at module init */ - "PyHKEY", - sizeof(PyHKEYObject), - 0, - PyHKEY_deallocFunc, /* tp_dealloc */ - 0, /* tp_print */ - 0, /* tp_getattr */ - 0, /* tp_setattr */ - 0, /* tp_reserved */ - 0, /* tp_repr */ - &PyHKEY_NumberMethods, /* tp_as_number */ - 0, /* tp_as_sequence */ - 0, /* tp_as_mapping */ - PyHKEY_hashFunc, /* tp_hash */ - 0, /* tp_call */ - PyHKEY_strFunc, /* tp_str */ - 0, /* tp_getattro */ - 0, /* tp_setattro */ - 0, /* tp_as_buffer */ - 0, /* tp_flags */ - PyHKEY_doc, /* tp_doc */ - 0, /*tp_traverse*/ - 0, /*tp_clear*/ - 0, /*tp_richcompare*/ - 0, /*tp_weaklistoffset*/ - 0, /*tp_iter*/ - 0, /*tp_iternext*/ - PyHKEY_methods, /*tp_methods*/ - PyHKEY_memberlist, /*tp_members*/ + PyVarObject_HEAD_INIT(0, 0) /* fill in type at module init */ + "PyHKEY", + sizeof(PyHKEYObject), + 0, + PyHKEY_deallocFunc, /* tp_dealloc */ + 0, /* tp_print */ + 0, /* tp_getattr */ + 0, /* tp_setattr */ + 0, /* tp_reserved */ + 0, /* tp_repr */ + &PyHKEY_NumberMethods, /* tp_as_number */ + 0, /* tp_as_sequence */ + 0, /* tp_as_mapping */ + PyHKEY_hashFunc, /* tp_hash */ + 0, /* tp_call */ + PyHKEY_strFunc, /* tp_str */ + 0, /* tp_getattro */ + 0, /* tp_setattro */ + 0, /* tp_as_buffer */ + 0, /* tp_flags */ + PyHKEY_doc, /* tp_doc */ + 0, /*tp_traverse*/ + 0, /*tp_clear*/ + 0, /*tp_richcompare*/ + 0, /*tp_weaklistoffset*/ + 0, /*tp_iter*/ + 0, /*tp_iternext*/ + PyHKEY_methods, /*tp_methods*/ + PyHKEY_memberlist, /*tp_members*/ }; /************************************************************************ @@ -546,39 +546,39 @@ static PyObject * PyHKEY_CloseMethod(PyObject *self, PyObject *args) { - if (!PyArg_ParseTuple(args, ":Close")) - return NULL; - if (!PyHKEY_Close(self)) - return NULL; - Py_INCREF(Py_None); - return Py_None; + if (!PyArg_ParseTuple(args, ":Close")) + return NULL; + if (!PyHKEY_Close(self)) + return NULL; + Py_INCREF(Py_None); + return Py_None; } static PyObject * PyHKEY_DetachMethod(PyObject *self, PyObject *args) { - void* ret; - PyHKEYObject *pThis = (PyHKEYObject *)self; - if (!PyArg_ParseTuple(args, ":Detach")) - return NULL; - ret = (void*)pThis->hkey; - pThis->hkey = 0; - return PyLong_FromVoidPtr(ret); + void* ret; + PyHKEYObject *pThis = (PyHKEYObject *)self; + if (!PyArg_ParseTuple(args, ":Detach")) + return NULL; + ret = (void*)pThis->hkey; + pThis->hkey = 0; + return PyLong_FromVoidPtr(ret); } static PyObject * PyHKEY_Enter(PyObject *self) { - Py_XINCREF(self); - return self; + Py_XINCREF(self); + return self; } static PyObject * PyHKEY_Exit(PyObject *self, PyObject *args) { - if (!PyHKEY_Close(self)) - return NULL; - Py_RETURN_NONE; + if (!PyHKEY_Close(self)) + return NULL; + Py_RETURN_NONE; } @@ -588,74 +588,74 @@ PyObject * PyHKEY_New(HKEY hInit) { - PyHKEYObject *key = PyObject_NEW(PyHKEYObject, &PyHKEY_Type); - if (key) - key->hkey = hInit; - return (PyObject *)key; + PyHKEYObject *key = PyObject_NEW(PyHKEYObject, &PyHKEY_Type); + if (key) + key->hkey = hInit; + return (PyObject *)key; } BOOL PyHKEY_Close(PyObject *ob_handle) { - LONG rc; - PyHKEYObject *key; + LONG rc; + PyHKEYObject *key; - if (!PyHKEY_Check(ob_handle)) { - PyErr_SetString(PyExc_TypeError, "bad operand type"); - return FALSE; - } - key = (PyHKEYObject *)ob_handle; - rc = key->hkey ? RegCloseKey((HKEY)key->hkey) : ERROR_SUCCESS; - key->hkey = 0; - if (rc != ERROR_SUCCESS) - PyErr_SetFromWindowsErrWithFunction(rc, "RegCloseKey"); - return rc == ERROR_SUCCESS; + if (!PyHKEY_Check(ob_handle)) { + PyErr_SetString(PyExc_TypeError, "bad operand type"); + return FALSE; + } + key = (PyHKEYObject *)ob_handle; + rc = key->hkey ? RegCloseKey((HKEY)key->hkey) : ERROR_SUCCESS; + key->hkey = 0; + if (rc != ERROR_SUCCESS) + PyErr_SetFromWindowsErrWithFunction(rc, "RegCloseKey"); + return rc == ERROR_SUCCESS; } BOOL PyHKEY_AsHKEY(PyObject *ob, HKEY *pHANDLE, BOOL bNoneOK) { - if (ob == Py_None) { - if (!bNoneOK) { - PyErr_SetString( - PyExc_TypeError, - "None is not a valid HKEY in this context"); - return FALSE; - } - *pHANDLE = (HKEY)0; - } - else if (PyHKEY_Check(ob)) { - PyHKEYObject *pH = (PyHKEYObject *)ob; - *pHANDLE = pH->hkey; - } - else if (PyLong_Check(ob)) { - /* We also support integers */ - PyErr_Clear(); - *pHANDLE = (HKEY)PyLong_AsVoidPtr(ob); - if (PyErr_Occurred()) - return FALSE; - } - else { - PyErr_SetString( - PyExc_TypeError, - "The object is not a PyHKEY object"); - return FALSE; - } - return TRUE; + if (ob == Py_None) { + if (!bNoneOK) { + PyErr_SetString( + PyExc_TypeError, + "None is not a valid HKEY in this context"); + return FALSE; + } + *pHANDLE = (HKEY)0; + } + else if (PyHKEY_Check(ob)) { + PyHKEYObject *pH = (PyHKEYObject *)ob; + *pHANDLE = pH->hkey; + } + else if (PyLong_Check(ob)) { + /* We also support integers */ + PyErr_Clear(); + *pHANDLE = (HKEY)PyLong_AsVoidPtr(ob); + if (PyErr_Occurred()) + return FALSE; + } + else { + PyErr_SetString( + PyExc_TypeError, + "The object is not a PyHKEY object"); + return FALSE; + } + return TRUE; } PyObject * PyHKEY_FromHKEY(HKEY h) { - PyHKEYObject *op; + PyHKEYObject *op; - /* Inline PyObject_New */ - op = (PyHKEYObject *) PyObject_MALLOC(sizeof(PyHKEYObject)); - if (op == NULL) - return PyErr_NoMemory(); - PyObject_INIT(op, &PyHKEY_Type); - op->hkey = h; - return (PyObject *)op; + /* Inline PyObject_New */ + op = (PyHKEYObject *) PyObject_MALLOC(sizeof(PyHKEYObject)); + if (op == NULL) + return PyErr_NoMemory(); + PyObject_INIT(op, &PyHKEY_Type); + op->hkey = h; + return (PyObject *)op; } @@ -665,32 +665,32 @@ BOOL PyWinObject_CloseHKEY(PyObject *obHandle) { - BOOL ok; - if (PyHKEY_Check(obHandle)) { - ok = PyHKEY_Close(obHandle); - } + BOOL ok; + if (PyHKEY_Check(obHandle)) { + ok = PyHKEY_Close(obHandle); + } #if SIZEOF_LONG >= SIZEOF_HKEY - else if (PyLong_Check(obHandle)) { - long rc = RegCloseKey((HKEY)PyLong_AsLong(obHandle)); - ok = (rc == ERROR_SUCCESS); - if (!ok) - PyErr_SetFromWindowsErrWithFunction(rc, "RegCloseKey"); - } + else if (PyLong_Check(obHandle)) { + long rc = RegCloseKey((HKEY)PyLong_AsLong(obHandle)); + ok = (rc == ERROR_SUCCESS); + if (!ok) + PyErr_SetFromWindowsErrWithFunction(rc, "RegCloseKey"); + } #else - else if (PyLong_Check(obHandle)) { - long rc = RegCloseKey((HKEY)PyLong_AsVoidPtr(obHandle)); - ok = (rc == ERROR_SUCCESS); - if (!ok) - PyErr_SetFromWindowsErrWithFunction(rc, "RegCloseKey"); - } + else if (PyLong_Check(obHandle)) { + long rc = RegCloseKey((HKEY)PyLong_AsVoidPtr(obHandle)); + ok = (rc == ERROR_SUCCESS); + if (!ok) + PyErr_SetFromWindowsErrWithFunction(rc, "RegCloseKey"); + } #endif - else { - PyErr_SetString( - PyExc_TypeError, - "A handle must be a HKEY object or an integer"); - return FALSE; - } - return ok; + else { + PyErr_SetString( + PyExc_TypeError, + "A handle must be a HKEY object or an integer"); + return FALSE; + } + return ok; } @@ -707,29 +707,29 @@ static void fixupMultiSZ(wchar_t **str, wchar_t *data, int len) { - wchar_t *P; - int i; - wchar_t *Q; - - Q = data + len; - for (P = data, i = 0; P < Q && *P != '\0'; P++, i++) { - str[i] = P; - for(; *P != '\0'; P++) - ; - } + wchar_t *P; + int i; + wchar_t *Q; + + Q = data + len; + for (P = data, i = 0; P < Q && *P != '\0'; P++, i++) { + str[i] = P; + for(; *P != '\0'; P++) + ; + } } static int countStrings(wchar_t *data, int len) { - int strings; - wchar_t *P; - wchar_t *Q = data + len; - - for (P = data, strings = 0; P < Q && *P != '\0'; P++, strings++) - for (; P < Q && *P != '\0'; P++) - ; - return strings; + int strings; + wchar_t *P; + wchar_t *Q = data + len; + + for (P = data, strings = 0; P < Q && *P != '\0'; P++, strings++) + for (; P < Q && *P != '\0'; P++) + ; + return strings; } /* Convert PyObject into Registry data. @@ -737,200 +737,200 @@ static BOOL Py2Reg(PyObject *value, DWORD typ, BYTE **retDataBuf, DWORD *retDataSize) { - Py_ssize_t i,j; - switch (typ) { - case REG_DWORD: - if (value != Py_None && !PyLong_Check(value)) - return FALSE; - *retDataBuf = (BYTE *)PyMem_NEW(DWORD, 1); - if (*retDataBuf==NULL){ - PyErr_NoMemory(); - return FALSE; - } - *retDataSize = sizeof(DWORD); - if (value == Py_None) { - DWORD zero = 0; - memcpy(*retDataBuf, &zero, sizeof(DWORD)); - } - else { - DWORD d = PyLong_AsLong(value); - memcpy(*retDataBuf, &d, sizeof(DWORD)); - } - break; - case REG_SZ: - case REG_EXPAND_SZ: - { - if (value == Py_None) - *retDataSize = 1; - else { - if (!PyUnicode_Check(value)) - return FALSE; - - *retDataSize = 2 + PyUnicode_GET_DATA_SIZE(value); - } - *retDataBuf = (BYTE *)PyMem_NEW(DWORD, *retDataSize); - if (*retDataBuf==NULL){ - PyErr_NoMemory(); - return FALSE; - } - if (value == Py_None) - wcscpy((wchar_t *)*retDataBuf, L""); - else - wcscpy((wchar_t *)*retDataBuf, - PyUnicode_AS_UNICODE(value)); - break; - } - case REG_MULTI_SZ: - { - DWORD size = 0; - wchar_t *P; - - if (value == Py_None) - i = 0; - else { - if (!PyList_Check(value)) - return FALSE; - i = PyList_Size(value); - } - for (j = 0; j < i; j++) - { - PyObject *t; - t = PyList_GET_ITEM(value, j); - if (!PyUnicode_Check(t)) - return FALSE; - size += 2 + PyUnicode_GET_DATA_SIZE(t); - } - - *retDataSize = size + 2; - *retDataBuf = (BYTE *)PyMem_NEW(char, - *retDataSize); - if (*retDataBuf==NULL){ - PyErr_NoMemory(); - return FALSE; - } - P = (wchar_t *)*retDataBuf; - - for (j = 0; j < i; j++) - { - PyObject *t; - t = PyList_GET_ITEM(value, j); - wcscpy(P, PyUnicode_AS_UNICODE(t)); - P += 1 + wcslen( - PyUnicode_AS_UNICODE(t)); - } - /* And doubly-terminate the list... */ - *P = '\0'; - break; - } - case REG_BINARY: - /* ALSO handle ALL unknown data types here. Even if we can't - support it natively, we should handle the bits. */ - default: - if (value == Py_None) - *retDataSize = 0; - else { - Py_buffer view; - - if (!PyObject_CheckBuffer(value)) { - PyErr_Format(PyExc_TypeError, - "Objects of type '%s' can not " - "be used as binary registry values", - value->ob_type->tp_name); - return FALSE; - } - - if (PyObject_GetBuffer(value, &view, PyBUF_SIMPLE) < 0) - return FALSE; - - *retDataBuf = (BYTE *)PyMem_NEW(char, view.len); - if (*retDataBuf==NULL){ - PyBuffer_Release(&view); - PyErr_NoMemory(); - return FALSE; - } - *retDataSize = view.len; - memcpy(*retDataBuf, view.buf, view.len); - PyBuffer_Release(&view); - } - break; - } - return TRUE; + Py_ssize_t i,j; + switch (typ) { + case REG_DWORD: + if (value != Py_None && !PyLong_Check(value)) + return FALSE; + *retDataBuf = (BYTE *)PyMem_NEW(DWORD, 1); + if (*retDataBuf==NULL){ + PyErr_NoMemory(); + return FALSE; + } + *retDataSize = sizeof(DWORD); + if (value == Py_None) { + DWORD zero = 0; + memcpy(*retDataBuf, &zero, sizeof(DWORD)); + } + else { + DWORD d = PyLong_AsLong(value); + memcpy(*retDataBuf, &d, sizeof(DWORD)); + } + break; + case REG_SZ: + case REG_EXPAND_SZ: + { + if (value == Py_None) + *retDataSize = 1; + else { + if (!PyUnicode_Check(value)) + return FALSE; + + *retDataSize = 2 + PyUnicode_GET_DATA_SIZE(value); + } + *retDataBuf = (BYTE *)PyMem_NEW(DWORD, *retDataSize); + if (*retDataBuf==NULL){ + PyErr_NoMemory(); + return FALSE; + } + if (value == Py_None) + wcscpy((wchar_t *)*retDataBuf, L""); + else + wcscpy((wchar_t *)*retDataBuf, + PyUnicode_AS_UNICODE(value)); + break; + } + case REG_MULTI_SZ: + { + DWORD size = 0; + wchar_t *P; + + if (value == Py_None) + i = 0; + else { + if (!PyList_Check(value)) + return FALSE; + i = PyList_Size(value); + } + for (j = 0; j < i; j++) + { + PyObject *t; + t = PyList_GET_ITEM(value, j); + if (!PyUnicode_Check(t)) + return FALSE; + size += 2 + PyUnicode_GET_DATA_SIZE(t); + } + + *retDataSize = size + 2; + *retDataBuf = (BYTE *)PyMem_NEW(char, + *retDataSize); + if (*retDataBuf==NULL){ + PyErr_NoMemory(); + return FALSE; + } + P = (wchar_t *)*retDataBuf; + + for (j = 0; j < i; j++) + { + PyObject *t; + t = PyList_GET_ITEM(value, j); + wcscpy(P, PyUnicode_AS_UNICODE(t)); + P += 1 + wcslen( + PyUnicode_AS_UNICODE(t)); + } + /* And doubly-terminate the list... */ + *P = '\0'; + break; + } + case REG_BINARY: + /* ALSO handle ALL unknown data types here. Even if we can't + support it natively, we should handle the bits. */ + default: + if (value == Py_None) + *retDataSize = 0; + else { + Py_buffer view; + + if (!PyObject_CheckBuffer(value)) { + PyErr_Format(PyExc_TypeError, + "Objects of type '%s' can not " + "be used as binary registry values", + value->ob_type->tp_name); + return FALSE; + } + + if (PyObject_GetBuffer(value, &view, PyBUF_SIMPLE) < 0) + return FALSE; + + *retDataBuf = (BYTE *)PyMem_NEW(char, view.len); + if (*retDataBuf==NULL){ + PyBuffer_Release(&view); + PyErr_NoMemory(); + return FALSE; + } + *retDataSize = view.len; + memcpy(*retDataBuf, view.buf, view.len); + PyBuffer_Release(&view); + } + break; + } + return TRUE; } /* Convert Registry data into PyObject*/ static PyObject * Reg2Py(BYTE *retDataBuf, DWORD retDataSize, DWORD typ) { - PyObject *obData; + PyObject *obData; - switch (typ) { - case REG_DWORD: - if (retDataSize == 0) - obData = PyLong_FromLong(0); - else - obData = PyLong_FromLong(*(int *)retDataBuf); - break; - case REG_SZ: - case REG_EXPAND_SZ: - { - /* the buffer may or may not have a trailing NULL */ - wchar_t *data = (wchar_t *)retDataBuf; - int len = retDataSize / 2; - if (retDataSize && data[len-1] == '\0') - retDataSize -= 2; - if (retDataSize <= 0) - data = L""; - obData = PyUnicode_FromUnicode(data, retDataSize/2); - break; - } - case REG_MULTI_SZ: - if (retDataSize == 0) - obData = PyList_New(0); - else - { - int index = 0; - wchar_t *data = (wchar_t *)retDataBuf; - int len = retDataSize / 2; - int s = countStrings(data, len); - wchar_t **str = (wchar_t **)malloc(sizeof(wchar_t *)*s); - if (str == NULL) - return PyErr_NoMemory(); - - fixupMultiSZ(str, data, len); - obData = PyList_New(s); - if (obData == NULL) - return NULL; - for (index = 0; index < s; index++) - { - size_t len = wcslen(str[index]); - if (len > INT_MAX) { - PyErr_SetString(PyExc_OverflowError, - "registry string is too long for a Python string"); - Py_DECREF(obData); - return NULL; - } - PyList_SetItem(obData, - index, - PyUnicode_FromUnicode(str[index], len)); - } - free(str); - - break; - } - case REG_BINARY: - /* ALSO handle ALL unknown data types here. Even if we can't - support it natively, we should handle the bits. */ - default: - if (retDataSize == 0) { - Py_INCREF(Py_None); - obData = Py_None; - } - else - obData = PyBytes_FromStringAndSize( - (char *)retDataBuf, retDataSize); - break; - } - return obData; + switch (typ) { + case REG_DWORD: + if (retDataSize == 0) + obData = PyLong_FromLong(0); + else + obData = PyLong_FromLong(*(int *)retDataBuf); + break; + case REG_SZ: + case REG_EXPAND_SZ: + { + /* the buffer may or may not have a trailing NULL */ + wchar_t *data = (wchar_t *)retDataBuf; + int len = retDataSize / 2; + if (retDataSize && data[len-1] == '\0') + retDataSize -= 2; + if (retDataSize <= 0) + data = L""; + obData = PyUnicode_FromUnicode(data, retDataSize/2); + break; + } + case REG_MULTI_SZ: + if (retDataSize == 0) + obData = PyList_New(0); + else + { + int index = 0; + wchar_t *data = (wchar_t *)retDataBuf; + int len = retDataSize / 2; + int s = countStrings(data, len); + wchar_t **str = (wchar_t **)malloc(sizeof(wchar_t *)*s); + if (str == NULL) + return PyErr_NoMemory(); + + fixupMultiSZ(str, data, len); + obData = PyList_New(s); + if (obData == NULL) + return NULL; + for (index = 0; index < s; index++) + { + size_t len = wcslen(str[index]); + if (len > INT_MAX) { + PyErr_SetString(PyExc_OverflowError, + "registry string is too long for a Python string"); + Py_DECREF(obData); + return NULL; + } + PyList_SetItem(obData, + index, + PyUnicode_FromUnicode(str[index], len)); + } + free(str); + + break; + } + case REG_BINARY: + /* ALSO handle ALL unknown data types here. Even if we can't + support it natively, we should handle the bits. */ + default: + if (retDataSize == 0) { + Py_INCREF(Py_None); + obData = Py_None; + } + else + obData = PyBytes_FromStringAndSize( + (char *)retDataBuf, retDataSize); + break; + } + return obData; } /* The Python methods */ @@ -938,344 +938,344 @@ static PyObject * PyCloseKey(PyObject *self, PyObject *args) { - PyObject *obKey; - if (!PyArg_ParseTuple(args, "O:CloseKey", &obKey)) - return NULL; - if (!PyHKEY_Close(obKey)) - return NULL; - Py_INCREF(Py_None); - return Py_None; + PyObject *obKey; + if (!PyArg_ParseTuple(args, "O:CloseKey", &obKey)) + return NULL; + if (!PyHKEY_Close(obKey)) + return NULL; + Py_INCREF(Py_None); + return Py_None; } static PyObject * PyConnectRegistry(PyObject *self, PyObject *args) { - HKEY hKey; - PyObject *obKey; - wchar_t *szCompName = NULL; - HKEY retKey; - long rc; - if (!PyArg_ParseTuple(args, "ZO:ConnectRegistry", &szCompName, &obKey)) - return NULL; - if (!PyHKEY_AsHKEY(obKey, &hKey, FALSE)) - return NULL; - Py_BEGIN_ALLOW_THREADS - rc = RegConnectRegistryW(szCompName, hKey, &retKey); - Py_END_ALLOW_THREADS - if (rc != ERROR_SUCCESS) - return PyErr_SetFromWindowsErrWithFunction(rc, - "ConnectRegistry"); - return PyHKEY_FromHKEY(retKey); + HKEY hKey; + PyObject *obKey; + wchar_t *szCompName = NULL; + HKEY retKey; + long rc; + if (!PyArg_ParseTuple(args, "ZO:ConnectRegistry", &szCompName, &obKey)) + return NULL; + if (!PyHKEY_AsHKEY(obKey, &hKey, FALSE)) + return NULL; + Py_BEGIN_ALLOW_THREADS + rc = RegConnectRegistryW(szCompName, hKey, &retKey); + Py_END_ALLOW_THREADS + if (rc != ERROR_SUCCESS) + return PyErr_SetFromWindowsErrWithFunction(rc, + "ConnectRegistry"); + return PyHKEY_FromHKEY(retKey); } static PyObject * PyCreateKey(PyObject *self, PyObject *args) { - HKEY hKey; - PyObject *obKey; - wchar_t *subKey; - HKEY retKey; - long rc; - if (!PyArg_ParseTuple(args, "OZ:CreateKey", &obKey, &subKey)) - return NULL; - if (!PyHKEY_AsHKEY(obKey, &hKey, FALSE)) - return NULL; - rc = RegCreateKeyW(hKey, subKey, &retKey); - if (rc != ERROR_SUCCESS) - return PyErr_SetFromWindowsErrWithFunction(rc, "CreateKey"); - return PyHKEY_FromHKEY(retKey); + HKEY hKey; + PyObject *obKey; + wchar_t *subKey; + HKEY retKey; + long rc; + if (!PyArg_ParseTuple(args, "OZ:CreateKey", &obKey, &subKey)) + return NULL; + if (!PyHKEY_AsHKEY(obKey, &hKey, FALSE)) + return NULL; + rc = RegCreateKeyW(hKey, subKey, &retKey); + if (rc != ERROR_SUCCESS) + return PyErr_SetFromWindowsErrWithFunction(rc, "CreateKey"); + return PyHKEY_FromHKEY(retKey); } static PyObject * PyCreateKeyEx(PyObject *self, PyObject *args) { - HKEY hKey; - PyObject *obKey; - wchar_t *subKey; - HKEY retKey; - int res = 0; - REGSAM sam = KEY_WRITE; - long rc; - if (!PyArg_ParseTuple(args, "OZ|ii:CreateKeyEx", &obKey, &subKey, - &res, &sam)) - return NULL; - if (!PyHKEY_AsHKEY(obKey, &hKey, FALSE)) - return NULL; - - rc = RegCreateKeyExW(hKey, subKey, res, NULL, (DWORD)NULL, - sam, NULL, &retKey, NULL); - if (rc != ERROR_SUCCESS) - return PyErr_SetFromWindowsErrWithFunction(rc, "CreateKeyEx"); - return PyHKEY_FromHKEY(retKey); + HKEY hKey; + PyObject *obKey; + wchar_t *subKey; + HKEY retKey; + int res = 0; + REGSAM sam = KEY_WRITE; + long rc; + if (!PyArg_ParseTuple(args, "OZ|ii:CreateKeyEx", &obKey, &subKey, + &res, &sam)) + return NULL; + if (!PyHKEY_AsHKEY(obKey, &hKey, FALSE)) + return NULL; + + rc = RegCreateKeyExW(hKey, subKey, res, NULL, (DWORD)NULL, + sam, NULL, &retKey, NULL); + if (rc != ERROR_SUCCESS) + return PyErr_SetFromWindowsErrWithFunction(rc, "CreateKeyEx"); + return PyHKEY_FromHKEY(retKey); } static PyObject * PyDeleteKey(PyObject *self, PyObject *args) { - HKEY hKey; - PyObject *obKey; - wchar_t *subKey; - long rc; - if (!PyArg_ParseTuple(args, "Ou:DeleteKey", &obKey, &subKey)) - return NULL; - if (!PyHKEY_AsHKEY(obKey, &hKey, FALSE)) - return NULL; - rc = RegDeleteKeyW(hKey, subKey ); - if (rc != ERROR_SUCCESS) - return PyErr_SetFromWindowsErrWithFunction(rc, "RegDeleteKey"); - Py_INCREF(Py_None); - return Py_None; + HKEY hKey; + PyObject *obKey; + wchar_t *subKey; + long rc; + if (!PyArg_ParseTuple(args, "Ou:DeleteKey", &obKey, &subKey)) + return NULL; + if (!PyHKEY_AsHKEY(obKey, &hKey, FALSE)) + return NULL; + rc = RegDeleteKeyW(hKey, subKey ); + if (rc != ERROR_SUCCESS) + return PyErr_SetFromWindowsErrWithFunction(rc, "RegDeleteKey"); + Py_INCREF(Py_None); + return Py_None; } static PyObject * PyDeleteKeyEx(PyObject *self, PyObject *args) { - HKEY hKey; - PyObject *obKey; - HMODULE hMod; - typedef LONG (WINAPI *RDKEFunc)(HKEY, const wchar_t*, REGSAM, int); - RDKEFunc pfn = NULL; - wchar_t *subKey; - long rc; - int res = 0; - REGSAM sam = KEY_WOW64_64KEY; - - if (!PyArg_ParseTuple(args, "Ou|ii:DeleteKeyEx", - &obKey, &subKey, &sam, &res)) - return NULL; - if (!PyHKEY_AsHKEY(obKey, &hKey, FALSE)) - return NULL; - - /* Only available on 64bit platforms, so we must load it - dynamically. */ - hMod = GetModuleHandle("advapi32.dll"); - if (hMod) - pfn = (RDKEFunc)GetProcAddress(hMod, - "RegDeleteKeyExW"); - if (!pfn) { - PyErr_SetString(PyExc_NotImplementedError, - "not implemented on this platform"); - return NULL; - } - Py_BEGIN_ALLOW_THREADS - rc = (*pfn)(hKey, subKey, sam, res); - Py_END_ALLOW_THREADS - - if (rc != ERROR_SUCCESS) - return PyErr_SetFromWindowsErrWithFunction(rc, "RegDeleteKeyEx"); - Py_INCREF(Py_None); - return Py_None; + HKEY hKey; + PyObject *obKey; + HMODULE hMod; + typedef LONG (WINAPI *RDKEFunc)(HKEY, const wchar_t*, REGSAM, int); + RDKEFunc pfn = NULL; + wchar_t *subKey; + long rc; + int res = 0; + REGSAM sam = KEY_WOW64_64KEY; + + if (!PyArg_ParseTuple(args, "Ou|ii:DeleteKeyEx", + &obKey, &subKey, &sam, &res)) + return NULL; + if (!PyHKEY_AsHKEY(obKey, &hKey, FALSE)) + return NULL; + + /* Only available on 64bit platforms, so we must load it + dynamically. */ + hMod = GetModuleHandle("advapi32.dll"); + if (hMod) + pfn = (RDKEFunc)GetProcAddress(hMod, + "RegDeleteKeyExW"); + if (!pfn) { + PyErr_SetString(PyExc_NotImplementedError, + "not implemented on this platform"); + return NULL; + } + Py_BEGIN_ALLOW_THREADS + rc = (*pfn)(hKey, subKey, sam, res); + Py_END_ALLOW_THREADS + + if (rc != ERROR_SUCCESS) + return PyErr_SetFromWindowsErrWithFunction(rc, "RegDeleteKeyEx"); + Py_INCREF(Py_None); + return Py_None; } static PyObject * PyDeleteValue(PyObject *self, PyObject *args) { - HKEY hKey; - PyObject *obKey; - wchar_t *subKey; - long rc; - if (!PyArg_ParseTuple(args, "OZ:DeleteValue", &obKey, &subKey)) - return NULL; - if (!PyHKEY_AsHKEY(obKey, &hKey, FALSE)) - return NULL; - Py_BEGIN_ALLOW_THREADS - rc = RegDeleteValueW(hKey, subKey); - Py_END_ALLOW_THREADS - if (rc !=ERROR_SUCCESS) - return PyErr_SetFromWindowsErrWithFunction(rc, - "RegDeleteValue"); - Py_INCREF(Py_None); - return Py_None; + HKEY hKey; + PyObject *obKey; + wchar_t *subKey; + long rc; + if (!PyArg_ParseTuple(args, "OZ:DeleteValue", &obKey, &subKey)) + return NULL; + if (!PyHKEY_AsHKEY(obKey, &hKey, FALSE)) + return NULL; + Py_BEGIN_ALLOW_THREADS + rc = RegDeleteValueW(hKey, subKey); + Py_END_ALLOW_THREADS + if (rc !=ERROR_SUCCESS) + return PyErr_SetFromWindowsErrWithFunction(rc, + "RegDeleteValue"); + Py_INCREF(Py_None); + return Py_None; } static PyObject * PyEnumKey(PyObject *self, PyObject *args) { - HKEY hKey; - PyObject *obKey; - int index; - long rc; - PyObject *retStr; - wchar_t tmpbuf[256]; /* max key name length is 255 */ - DWORD len = sizeof(tmpbuf); /* includes NULL terminator */ - - if (!PyArg_ParseTuple(args, "Oi:EnumKey", &obKey, &index)) - return NULL; - if (!PyHKEY_AsHKEY(obKey, &hKey, FALSE)) - return NULL; - - Py_BEGIN_ALLOW_THREADS - rc = RegEnumKeyExW(hKey, index, tmpbuf, &len, NULL, NULL, NULL, NULL); - Py_END_ALLOW_THREADS - if (rc != ERROR_SUCCESS) - return PyErr_SetFromWindowsErrWithFunction(rc, "RegEnumKeyEx"); + HKEY hKey; + PyObject *obKey; + int index; + long rc; + PyObject *retStr; + wchar_t tmpbuf[256]; /* max key name length is 255 */ + DWORD len = sizeof(tmpbuf); /* includes NULL terminator */ + + if (!PyArg_ParseTuple(args, "Oi:EnumKey", &obKey, &index)) + return NULL; + if (!PyHKEY_AsHKEY(obKey, &hKey, FALSE)) + return NULL; + + Py_BEGIN_ALLOW_THREADS + rc = RegEnumKeyExW(hKey, index, tmpbuf, &len, NULL, NULL, NULL, NULL); + Py_END_ALLOW_THREADS + if (rc != ERROR_SUCCESS) + return PyErr_SetFromWindowsErrWithFunction(rc, "RegEnumKeyEx"); - retStr = PyUnicode_FromUnicode(tmpbuf, len); - return retStr; /* can be NULL */ + retStr = PyUnicode_FromUnicode(tmpbuf, len); + return retStr; /* can be NULL */ } static PyObject * PyEnumValue(PyObject *self, PyObject *args) { - HKEY hKey; - PyObject *obKey; - int index; - long rc; - wchar_t *retValueBuf; - BYTE *retDataBuf; - DWORD retValueSize; - DWORD retDataSize; - DWORD typ; - PyObject *obData; - PyObject *retVal; - - if (!PyArg_ParseTuple(args, "Oi:EnumValue", &obKey, &index)) - return NULL; - if (!PyHKEY_AsHKEY(obKey, &hKey, FALSE)) - return NULL; - - if ((rc = RegQueryInfoKeyW(hKey, NULL, NULL, NULL, NULL, NULL, NULL, - NULL, - &retValueSize, &retDataSize, NULL, NULL)) - != ERROR_SUCCESS) - return PyErr_SetFromWindowsErrWithFunction(rc, - "RegQueryInfoKey"); - ++retValueSize; /* include null terminators */ - ++retDataSize; - retValueBuf = (wchar_t *)PyMem_Malloc(sizeof(wchar_t) * retValueSize); - if (retValueBuf == NULL) - return PyErr_NoMemory(); - retDataBuf = (BYTE *)PyMem_Malloc(retDataSize); - if (retDataBuf == NULL) { - PyMem_Free(retValueBuf); - return PyErr_NoMemory(); - } - - Py_BEGIN_ALLOW_THREADS - rc = RegEnumValueW(hKey, - index, - retValueBuf, - &retValueSize, - NULL, - &typ, - retDataBuf, - &retDataSize); - Py_END_ALLOW_THREADS - - if (rc != ERROR_SUCCESS) { - retVal = PyErr_SetFromWindowsErrWithFunction(rc, - "PyRegEnumValue"); - goto fail; - } - obData = Reg2Py(retDataBuf, retDataSize, typ); - if (obData == NULL) { - retVal = NULL; - goto fail; - } - retVal = Py_BuildValue("uOi", retValueBuf, obData, typ); - Py_DECREF(obData); + HKEY hKey; + PyObject *obKey; + int index; + long rc; + wchar_t *retValueBuf; + BYTE *retDataBuf; + DWORD retValueSize; + DWORD retDataSize; + DWORD typ; + PyObject *obData; + PyObject *retVal; + + if (!PyArg_ParseTuple(args, "Oi:EnumValue", &obKey, &index)) + return NULL; + if (!PyHKEY_AsHKEY(obKey, &hKey, FALSE)) + return NULL; + + if ((rc = RegQueryInfoKeyW(hKey, NULL, NULL, NULL, NULL, NULL, NULL, + NULL, + &retValueSize, &retDataSize, NULL, NULL)) + != ERROR_SUCCESS) + return PyErr_SetFromWindowsErrWithFunction(rc, + "RegQueryInfoKey"); + ++retValueSize; /* include null terminators */ + ++retDataSize; + retValueBuf = (wchar_t *)PyMem_Malloc(sizeof(wchar_t) * retValueSize); + if (retValueBuf == NULL) + return PyErr_NoMemory(); + retDataBuf = (BYTE *)PyMem_Malloc(retDataSize); + if (retDataBuf == NULL) { + PyMem_Free(retValueBuf); + return PyErr_NoMemory(); + } + + Py_BEGIN_ALLOW_THREADS + rc = RegEnumValueW(hKey, + index, + retValueBuf, + &retValueSize, + NULL, + &typ, + retDataBuf, + &retDataSize); + Py_END_ALLOW_THREADS + + if (rc != ERROR_SUCCESS) { + retVal = PyErr_SetFromWindowsErrWithFunction(rc, + "PyRegEnumValue"); + goto fail; + } + obData = Reg2Py(retDataBuf, retDataSize, typ); + if (obData == NULL) { + retVal = NULL; + goto fail; + } + retVal = Py_BuildValue("uOi", retValueBuf, obData, typ); + Py_DECREF(obData); fail: - PyMem_Free(retValueBuf); - PyMem_Free(retDataBuf); - return retVal; + PyMem_Free(retValueBuf); + PyMem_Free(retDataBuf); + return retVal; } static PyObject * PyExpandEnvironmentStrings(PyObject *self, PyObject *args) { - Py_UNICODE *retValue = NULL; - Py_UNICODE *src; - DWORD retValueSize; - DWORD rc; - PyObject *o; - - if (!PyArg_ParseTuple(args, "u:ExpandEnvironmentStrings", &src)) - return NULL; - - retValueSize = ExpandEnvironmentStringsW(src, retValue, 0); - if (retValueSize == 0) { - return PyErr_SetFromWindowsErrWithFunction(retValueSize, - "ExpandEnvironmentStrings"); - } - retValue = (Py_UNICODE *)PyMem_Malloc(retValueSize * sizeof(Py_UNICODE)); - if (retValue == NULL) { - return PyErr_NoMemory(); - } - - rc = ExpandEnvironmentStringsW(src, retValue, retValueSize); - if (rc == 0) { - PyMem_Free(retValue); - return PyErr_SetFromWindowsErrWithFunction(retValueSize, - "ExpandEnvironmentStrings"); - } - o = PyUnicode_FromUnicode(retValue, wcslen(retValue)); - PyMem_Free(retValue); - return o; + Py_UNICODE *retValue = NULL; + Py_UNICODE *src; + DWORD retValueSize; + DWORD rc; + PyObject *o; + + if (!PyArg_ParseTuple(args, "u:ExpandEnvironmentStrings", &src)) + return NULL; + + retValueSize = ExpandEnvironmentStringsW(src, retValue, 0); + if (retValueSize == 0) { + return PyErr_SetFromWindowsErrWithFunction(retValueSize, + "ExpandEnvironmentStrings"); + } + retValue = (Py_UNICODE *)PyMem_Malloc(retValueSize * sizeof(Py_UNICODE)); + if (retValue == NULL) { + return PyErr_NoMemory(); + } + + rc = ExpandEnvironmentStringsW(src, retValue, retValueSize); + if (rc == 0) { + PyMem_Free(retValue); + return PyErr_SetFromWindowsErrWithFunction(retValueSize, + "ExpandEnvironmentStrings"); + } + o = PyUnicode_FromUnicode(retValue, wcslen(retValue)); + PyMem_Free(retValue); + return o; } static PyObject * PyFlushKey(PyObject *self, PyObject *args) { - HKEY hKey; - PyObject *obKey; - long rc; - if (!PyArg_ParseTuple(args, "O:FlushKey", &obKey)) - return NULL; - if (!PyHKEY_AsHKEY(obKey, &hKey, FALSE)) - return NULL; - Py_BEGIN_ALLOW_THREADS - rc = RegFlushKey(hKey); - Py_END_ALLOW_THREADS - if (rc != ERROR_SUCCESS) - return PyErr_SetFromWindowsErrWithFunction(rc, "RegFlushKey"); - Py_INCREF(Py_None); - return Py_None; + HKEY hKey; + PyObject *obKey; + long rc; + if (!PyArg_ParseTuple(args, "O:FlushKey", &obKey)) + return NULL; + if (!PyHKEY_AsHKEY(obKey, &hKey, FALSE)) + return NULL; + Py_BEGIN_ALLOW_THREADS + rc = RegFlushKey(hKey); + Py_END_ALLOW_THREADS + if (rc != ERROR_SUCCESS) + return PyErr_SetFromWindowsErrWithFunction(rc, "RegFlushKey"); + Py_INCREF(Py_None); + return Py_None; } static PyObject * PyLoadKey(PyObject *self, PyObject *args) { - HKEY hKey; - PyObject *obKey; - wchar_t *subKey; - wchar_t *fileName; - - long rc; - if (!PyArg_ParseTuple(args, "Ouu:LoadKey", &obKey, &subKey, &fileName)) - return NULL; - if (!PyHKEY_AsHKEY(obKey, &hKey, FALSE)) - return NULL; - Py_BEGIN_ALLOW_THREADS - rc = RegLoadKeyW(hKey, subKey, fileName ); - Py_END_ALLOW_THREADS - if (rc != ERROR_SUCCESS) - return PyErr_SetFromWindowsErrWithFunction(rc, "RegLoadKey"); - Py_INCREF(Py_None); - return Py_None; + HKEY hKey; + PyObject *obKey; + wchar_t *subKey; + wchar_t *fileName; + + long rc; + if (!PyArg_ParseTuple(args, "Ouu:LoadKey", &obKey, &subKey, &fileName)) + return NULL; + if (!PyHKEY_AsHKEY(obKey, &hKey, FALSE)) + return NULL; + Py_BEGIN_ALLOW_THREADS + rc = RegLoadKeyW(hKey, subKey, fileName ); + Py_END_ALLOW_THREADS + if (rc != ERROR_SUCCESS) + return PyErr_SetFromWindowsErrWithFunction(rc, "RegLoadKey"); + Py_INCREF(Py_None); + return Py_None; } static PyObject * PyOpenKey(PyObject *self, PyObject *args) { - HKEY hKey; - PyObject *obKey; + HKEY hKey; + PyObject *obKey; - wchar_t *subKey; - int res = 0; - HKEY retKey; - long rc; - REGSAM sam = KEY_READ; - if (!PyArg_ParseTuple(args, "OZ|ii:OpenKey", &obKey, &subKey, - &res, &sam)) - return NULL; - if (!PyHKEY_AsHKEY(obKey, &hKey, FALSE)) - return NULL; - - Py_BEGIN_ALLOW_THREADS - rc = RegOpenKeyExW(hKey, subKey, res, sam, &retKey); - Py_END_ALLOW_THREADS - if (rc != ERROR_SUCCESS) - return PyErr_SetFromWindowsErrWithFunction(rc, "RegOpenKeyEx"); - return PyHKEY_FromHKEY(retKey); + wchar_t *subKey; + int res = 0; + HKEY retKey; + long rc; + REGSAM sam = KEY_READ; + if (!PyArg_ParseTuple(args, "OZ|ii:OpenKey", &obKey, &subKey, + &res, &sam)) + return NULL; + if (!PyHKEY_AsHKEY(obKey, &hKey, FALSE)) + return NULL; + + Py_BEGIN_ALLOW_THREADS + rc = RegOpenKeyExW(hKey, subKey, res, sam, &retKey); + Py_END_ALLOW_THREADS + if (rc != ERROR_SUCCESS) + return PyErr_SetFromWindowsErrWithFunction(rc, "RegOpenKeyEx"); + return PyHKEY_FromHKEY(retKey); } @@ -1291,18 +1291,18 @@ PyObject *l; PyObject *ret; if (!PyArg_ParseTuple(args, "O:QueryInfoKey", &obKey)) - return NULL; + return NULL; if (!PyHKEY_AsHKEY(obKey, &hKey, FALSE)) - return NULL; + return NULL; if ((rc = RegQueryInfoKey(hKey, NULL, NULL, 0, &nSubKeys, NULL, NULL, - &nValues, NULL, NULL, NULL, &ft)) + &nValues, NULL, NULL, NULL, &ft)) != ERROR_SUCCESS) - return PyErr_SetFromWindowsErrWithFunction(rc, "RegQueryInfoKey"); + return PyErr_SetFromWindowsErrWithFunction(rc, "RegQueryInfoKey"); li.LowPart = ft.dwLowDateTime; li.HighPart = ft.dwHighDateTime; l = PyLong_FromLongLong(li.QuadPart); if (l == NULL) - return NULL; + return NULL; ret = Py_BuildValue("iiO", nSubKeys, nValues, l); Py_DECREF(l); return ret; @@ -1311,328 +1311,328 @@ static PyObject * PyQueryValue(PyObject *self, PyObject *args) { - HKEY hKey; - PyObject *obKey; - wchar_t *subKey; - long rc; - PyObject *retStr; - wchar_t *retBuf; - long bufSize = 0; - - if (!PyArg_ParseTuple(args, "OZ:QueryValue", &obKey, &subKey)) - return NULL; - - if (!PyHKEY_AsHKEY(obKey, &hKey, FALSE)) - return NULL; - if ((rc = RegQueryValueW(hKey, subKey, NULL, &bufSize)) - != ERROR_SUCCESS) - return PyErr_SetFromWindowsErrWithFunction(rc, - "RegQueryValue"); - retBuf = (wchar_t *)PyMem_Malloc(bufSize); - if (retBuf == NULL) - return PyErr_NoMemory(); - - if ((rc = RegQueryValueW(hKey, subKey, retBuf, &bufSize)) - != ERROR_SUCCESS) { - PyMem_Free(retBuf); - return PyErr_SetFromWindowsErrWithFunction(rc, - "RegQueryValue"); - } - - retStr = PyUnicode_FromUnicode(retBuf, wcslen(retBuf)); - PyMem_Free(retBuf); - return retStr; + HKEY hKey; + PyObject *obKey; + wchar_t *subKey; + long rc; + PyObject *retStr; + wchar_t *retBuf; + long bufSize = 0; + + if (!PyArg_ParseTuple(args, "OZ:QueryValue", &obKey, &subKey)) + return NULL; + + if (!PyHKEY_AsHKEY(obKey, &hKey, FALSE)) + return NULL; + if ((rc = RegQueryValueW(hKey, subKey, NULL, &bufSize)) + != ERROR_SUCCESS) + return PyErr_SetFromWindowsErrWithFunction(rc, + "RegQueryValue"); + retBuf = (wchar_t *)PyMem_Malloc(bufSize); + if (retBuf == NULL) + return PyErr_NoMemory(); + + if ((rc = RegQueryValueW(hKey, subKey, retBuf, &bufSize)) + != ERROR_SUCCESS) { + PyMem_Free(retBuf); + return PyErr_SetFromWindowsErrWithFunction(rc, + "RegQueryValue"); + } + + retStr = PyUnicode_FromUnicode(retBuf, wcslen(retBuf)); + PyMem_Free(retBuf); + return retStr; } static PyObject * PyQueryValueEx(PyObject *self, PyObject *args) { - HKEY hKey; - PyObject *obKey; - wchar_t *valueName; - - long rc; - BYTE *retBuf; - DWORD bufSize = 0; - DWORD typ; - PyObject *obData; - PyObject *result; - - if (!PyArg_ParseTuple(args, "OZ:QueryValueEx", &obKey, &valueName)) - return NULL; - - if (!PyHKEY_AsHKEY(obKey, &hKey, FALSE)) - return NULL; - if ((rc = RegQueryValueExW(hKey, valueName, - NULL, NULL, NULL, - &bufSize)) - != ERROR_SUCCESS) - return PyErr_SetFromWindowsErrWithFunction(rc, - "RegQueryValueEx"); - retBuf = (BYTE *)PyMem_Malloc(bufSize); - if (retBuf == NULL) - return PyErr_NoMemory(); - if ((rc = RegQueryValueExW(hKey, valueName, NULL, - &typ, retBuf, &bufSize)) - != ERROR_SUCCESS) { - PyMem_Free(retBuf); - return PyErr_SetFromWindowsErrWithFunction(rc, - "RegQueryValueEx"); - } - obData = Reg2Py(retBuf, bufSize, typ); - PyMem_Free(retBuf); - if (obData == NULL) - return NULL; - result = Py_BuildValue("Oi", obData, typ); - Py_DECREF(obData); - return result; + HKEY hKey; + PyObject *obKey; + wchar_t *valueName; + + long rc; + BYTE *retBuf; + DWORD bufSize = 0; + DWORD typ; + PyObject *obData; + PyObject *result; + + if (!PyArg_ParseTuple(args, "OZ:QueryValueEx", &obKey, &valueName)) + return NULL; + + if (!PyHKEY_AsHKEY(obKey, &hKey, FALSE)) + return NULL; + if ((rc = RegQueryValueExW(hKey, valueName, + NULL, NULL, NULL, + &bufSize)) + != ERROR_SUCCESS) + return PyErr_SetFromWindowsErrWithFunction(rc, + "RegQueryValueEx"); + retBuf = (BYTE *)PyMem_Malloc(bufSize); + if (retBuf == NULL) + return PyErr_NoMemory(); + if ((rc = RegQueryValueExW(hKey, valueName, NULL, + &typ, retBuf, &bufSize)) + != ERROR_SUCCESS) { + PyMem_Free(retBuf); + return PyErr_SetFromWindowsErrWithFunction(rc, + "RegQueryValueEx"); + } + obData = Reg2Py(retBuf, bufSize, typ); + PyMem_Free(retBuf); + if (obData == NULL) + return NULL; + result = Py_BuildValue("Oi", obData, typ); + Py_DECREF(obData); + return result; } static PyObject * PySaveKey(PyObject *self, PyObject *args) { - HKEY hKey; - PyObject *obKey; - wchar_t *fileName; - LPSECURITY_ATTRIBUTES pSA = NULL; - - long rc; - if (!PyArg_ParseTuple(args, "Ou:SaveKey", &obKey, &fileName)) - return NULL; - if (!PyHKEY_AsHKEY(obKey, &hKey, FALSE)) - return NULL; + HKEY hKey; + PyObject *obKey; + wchar_t *fileName; + LPSECURITY_ATTRIBUTES pSA = NULL; + + long rc; + if (!PyArg_ParseTuple(args, "Ou:SaveKey", &obKey, &fileName)) + return NULL; + if (!PyHKEY_AsHKEY(obKey, &hKey, FALSE)) + return NULL; /* One day we may get security into the core? - if (!PyWinObject_AsSECURITY_ATTRIBUTES(obSA, &pSA, TRUE)) - return NULL; + if (!PyWinObject_AsSECURITY_ATTRIBUTES(obSA, &pSA, TRUE)) + return NULL; */ - Py_BEGIN_ALLOW_THREADS - rc = RegSaveKeyW(hKey, fileName, pSA ); - Py_END_ALLOW_THREADS - if (rc != ERROR_SUCCESS) - return PyErr_SetFromWindowsErrWithFunction(rc, "RegSaveKey"); - Py_INCREF(Py_None); - return Py_None; + Py_BEGIN_ALLOW_THREADS + rc = RegSaveKeyW(hKey, fileName, pSA ); + Py_END_ALLOW_THREADS + if (rc != ERROR_SUCCESS) + return PyErr_SetFromWindowsErrWithFunction(rc, "RegSaveKey"); + Py_INCREF(Py_None); + return Py_None; } static PyObject * PySetValue(PyObject *self, PyObject *args) { - HKEY hKey; - PyObject *obKey; - wchar_t *subKey; - wchar_t *str; - DWORD typ; - DWORD len; - long rc; - if (!PyArg_ParseTuple(args, "OZiu#:SetValue", - &obKey, - &subKey, - &typ, - &str, - &len)) - return NULL; - if (!PyHKEY_AsHKEY(obKey, &hKey, FALSE)) - return NULL; - if (typ != REG_SZ) { - PyErr_SetString(PyExc_TypeError, - "Type must be winreg.REG_SZ"); - return NULL; - } - - Py_BEGIN_ALLOW_THREADS - rc = RegSetValueW(hKey, subKey, REG_SZ, str, len+1); - Py_END_ALLOW_THREADS - if (rc != ERROR_SUCCESS) - return PyErr_SetFromWindowsErrWithFunction(rc, "RegSetValue"); - Py_INCREF(Py_None); - return Py_None; + HKEY hKey; + PyObject *obKey; + wchar_t *subKey; + wchar_t *str; + DWORD typ; + DWORD len; + long rc; + if (!PyArg_ParseTuple(args, "OZiu#:SetValue", + &obKey, + &subKey, + &typ, + &str, + &len)) + return NULL; + if (!PyHKEY_AsHKEY(obKey, &hKey, FALSE)) + return NULL; + if (typ != REG_SZ) { + PyErr_SetString(PyExc_TypeError, + "Type must be winreg.REG_SZ"); + return NULL; + } + + Py_BEGIN_ALLOW_THREADS + rc = RegSetValueW(hKey, subKey, REG_SZ, str, len+1); + Py_END_ALLOW_THREADS + if (rc != ERROR_SUCCESS) + return PyErr_SetFromWindowsErrWithFunction(rc, "RegSetValue"); + Py_INCREF(Py_None); + return Py_None; } static PyObject * PySetValueEx(PyObject *self, PyObject *args) { - HKEY hKey; - PyObject *obKey; - Py_UNICODE *valueName; - PyObject *obRes; - PyObject *value; - BYTE *data; - DWORD len; - DWORD typ; - - LONG rc; - - if (!PyArg_ParseTuple(args, "OZOiO:SetValueEx", - &obKey, - &valueName, - &obRes, - &typ, - &value)) - return NULL; - if (!PyHKEY_AsHKEY(obKey, &hKey, FALSE)) - return NULL; - if (!Py2Reg(value, typ, &data, &len)) - { - if (!PyErr_Occurred()) - PyErr_SetString(PyExc_ValueError, - "Could not convert the data to the specified type."); - return NULL; - } - Py_BEGIN_ALLOW_THREADS - rc = RegSetValueExW(hKey, valueName, 0, typ, data, len); - Py_END_ALLOW_THREADS - PyMem_DEL(data); - if (rc != ERROR_SUCCESS) - return PyErr_SetFromWindowsErrWithFunction(rc, - "RegSetValueEx"); - Py_INCREF(Py_None); - return Py_None; + HKEY hKey; + PyObject *obKey; + Py_UNICODE *valueName; + PyObject *obRes; + PyObject *value; + BYTE *data; + DWORD len; + DWORD typ; + + LONG rc; + + if (!PyArg_ParseTuple(args, "OZOiO:SetValueEx", + &obKey, + &valueName, + &obRes, + &typ, + &value)) + return NULL; + if (!PyHKEY_AsHKEY(obKey, &hKey, FALSE)) + return NULL; + if (!Py2Reg(value, typ, &data, &len)) + { + if (!PyErr_Occurred()) + PyErr_SetString(PyExc_ValueError, + "Could not convert the data to the specified type."); + return NULL; + } + Py_BEGIN_ALLOW_THREADS + rc = RegSetValueExW(hKey, valueName, 0, typ, data, len); + Py_END_ALLOW_THREADS + PyMem_DEL(data); + if (rc != ERROR_SUCCESS) + return PyErr_SetFromWindowsErrWithFunction(rc, + "RegSetValueEx"); + Py_INCREF(Py_None); + return Py_None; } static PyObject * PyDisableReflectionKey(PyObject *self, PyObject *args) { - HKEY hKey; - PyObject *obKey; - HMODULE hMod; - typedef LONG (WINAPI *RDRKFunc)(HKEY); - RDRKFunc pfn = NULL; - LONG rc; - - if (!PyArg_ParseTuple(args, "O:DisableReflectionKey", &obKey)) - return NULL; - if (!PyHKEY_AsHKEY(obKey, &hKey, FALSE)) - return NULL; - - /* Only available on 64bit platforms, so we must load it - dynamically.*/ - hMod = GetModuleHandle("advapi32.dll"); - if (hMod) - pfn = (RDRKFunc)GetProcAddress(hMod, - "RegDisableReflectionKey"); - if (!pfn) { - PyErr_SetString(PyExc_NotImplementedError, - "not implemented on this platform"); - return NULL; - } - Py_BEGIN_ALLOW_THREADS - rc = (*pfn)(hKey); - Py_END_ALLOW_THREADS - if (rc != ERROR_SUCCESS) - return PyErr_SetFromWindowsErrWithFunction(rc, - "RegDisableReflectionKey"); - Py_INCREF(Py_None); - return Py_None; + HKEY hKey; + PyObject *obKey; + HMODULE hMod; + typedef LONG (WINAPI *RDRKFunc)(HKEY); + RDRKFunc pfn = NULL; + LONG rc; + + if (!PyArg_ParseTuple(args, "O:DisableReflectionKey", &obKey)) + return NULL; + if (!PyHKEY_AsHKEY(obKey, &hKey, FALSE)) + return NULL; + + /* Only available on 64bit platforms, so we must load it + dynamically.*/ + hMod = GetModuleHandle("advapi32.dll"); + if (hMod) + pfn = (RDRKFunc)GetProcAddress(hMod, + "RegDisableReflectionKey"); + if (!pfn) { + PyErr_SetString(PyExc_NotImplementedError, + "not implemented on this platform"); + return NULL; + } + Py_BEGIN_ALLOW_THREADS + rc = (*pfn)(hKey); + Py_END_ALLOW_THREADS + if (rc != ERROR_SUCCESS) + return PyErr_SetFromWindowsErrWithFunction(rc, + "RegDisableReflectionKey"); + Py_INCREF(Py_None); + return Py_None; } static PyObject * PyEnableReflectionKey(PyObject *self, PyObject *args) { - HKEY hKey; - PyObject *obKey; - HMODULE hMod; - typedef LONG (WINAPI *RERKFunc)(HKEY); - RERKFunc pfn = NULL; - LONG rc; - - if (!PyArg_ParseTuple(args, "O:EnableReflectionKey", &obKey)) - return NULL; - if (!PyHKEY_AsHKEY(obKey, &hKey, FALSE)) - return NULL; - - /* Only available on 64bit platforms, so we must load it - dynamically.*/ - hMod = GetModuleHandle("advapi32.dll"); - if (hMod) - pfn = (RERKFunc)GetProcAddress(hMod, - "RegEnableReflectionKey"); - if (!pfn) { - PyErr_SetString(PyExc_NotImplementedError, - "not implemented on this platform"); - return NULL; - } - Py_BEGIN_ALLOW_THREADS - rc = (*pfn)(hKey); - Py_END_ALLOW_THREADS - if (rc != ERROR_SUCCESS) - return PyErr_SetFromWindowsErrWithFunction(rc, - "RegEnableReflectionKey"); - Py_INCREF(Py_None); - return Py_None; + HKEY hKey; + PyObject *obKey; + HMODULE hMod; + typedef LONG (WINAPI *RERKFunc)(HKEY); + RERKFunc pfn = NULL; + LONG rc; + + if (!PyArg_ParseTuple(args, "O:EnableReflectionKey", &obKey)) + return NULL; + if (!PyHKEY_AsHKEY(obKey, &hKey, FALSE)) + return NULL; + + /* Only available on 64bit platforms, so we must load it + dynamically.*/ + hMod = GetModuleHandle("advapi32.dll"); + if (hMod) + pfn = (RERKFunc)GetProcAddress(hMod, + "RegEnableReflectionKey"); + if (!pfn) { + PyErr_SetString(PyExc_NotImplementedError, + "not implemented on this platform"); + return NULL; + } + Py_BEGIN_ALLOW_THREADS + rc = (*pfn)(hKey); + Py_END_ALLOW_THREADS + if (rc != ERROR_SUCCESS) + return PyErr_SetFromWindowsErrWithFunction(rc, + "RegEnableReflectionKey"); + Py_INCREF(Py_None); + return Py_None; } static PyObject * PyQueryReflectionKey(PyObject *self, PyObject *args) { - HKEY hKey; - PyObject *obKey; - HMODULE hMod; - typedef LONG (WINAPI *RQRKFunc)(HKEY, BOOL *); - RQRKFunc pfn = NULL; - BOOL result; - LONG rc; - - if (!PyArg_ParseTuple(args, "O:QueryReflectionKey", &obKey)) - return NULL; - if (!PyHKEY_AsHKEY(obKey, &hKey, FALSE)) - return NULL; - - /* Only available on 64bit platforms, so we must load it - dynamically.*/ - hMod = GetModuleHandle("advapi32.dll"); - if (hMod) - pfn = (RQRKFunc)GetProcAddress(hMod, - "RegQueryReflectionKey"); - if (!pfn) { - PyErr_SetString(PyExc_NotImplementedError, - "not implemented on this platform"); - return NULL; - } - Py_BEGIN_ALLOW_THREADS - rc = (*pfn)(hKey, &result); - Py_END_ALLOW_THREADS - if (rc != ERROR_SUCCESS) - return PyErr_SetFromWindowsErrWithFunction(rc, - "RegQueryReflectionKey"); - return PyBool_FromLong(result); + HKEY hKey; + PyObject *obKey; + HMODULE hMod; + typedef LONG (WINAPI *RQRKFunc)(HKEY, BOOL *); + RQRKFunc pfn = NULL; + BOOL result; + LONG rc; + + if (!PyArg_ParseTuple(args, "O:QueryReflectionKey", &obKey)) + return NULL; + if (!PyHKEY_AsHKEY(obKey, &hKey, FALSE)) + return NULL; + + /* Only available on 64bit platforms, so we must load it + dynamically.*/ + hMod = GetModuleHandle("advapi32.dll"); + if (hMod) + pfn = (RQRKFunc)GetProcAddress(hMod, + "RegQueryReflectionKey"); + if (!pfn) { + PyErr_SetString(PyExc_NotImplementedError, + "not implemented on this platform"); + return NULL; + } + Py_BEGIN_ALLOW_THREADS + rc = (*pfn)(hKey, &result); + Py_END_ALLOW_THREADS + if (rc != ERROR_SUCCESS) + return PyErr_SetFromWindowsErrWithFunction(rc, + "RegQueryReflectionKey"); + return PyBool_FromLong(result); } static struct PyMethodDef winreg_methods[] = { - {"CloseKey", PyCloseKey, METH_VARARGS, CloseKey_doc}, - {"ConnectRegistry", PyConnectRegistry, METH_VARARGS, ConnectRegistry_doc}, - {"CreateKey", PyCreateKey, METH_VARARGS, CreateKey_doc}, - {"CreateKeyEx", PyCreateKeyEx, METH_VARARGS, CreateKeyEx_doc}, - {"DeleteKey", PyDeleteKey, METH_VARARGS, DeleteKey_doc}, - {"DeleteKeyEx", PyDeleteKeyEx, METH_VARARGS, DeleteKeyEx_doc}, - {"DeleteValue", PyDeleteValue, METH_VARARGS, DeleteValue_doc}, - {"DisableReflectionKey", PyDisableReflectionKey, METH_VARARGS, DisableReflectionKey_doc}, - {"EnableReflectionKey", PyEnableReflectionKey, METH_VARARGS, EnableReflectionKey_doc}, - {"EnumKey", PyEnumKey, METH_VARARGS, EnumKey_doc}, - {"EnumValue", PyEnumValue, METH_VARARGS, EnumValue_doc}, - {"ExpandEnvironmentStrings", PyExpandEnvironmentStrings, METH_VARARGS, - ExpandEnvironmentStrings_doc }, - {"FlushKey", PyFlushKey, METH_VARARGS, FlushKey_doc}, - {"LoadKey", PyLoadKey, METH_VARARGS, LoadKey_doc}, - {"OpenKey", PyOpenKey, METH_VARARGS, OpenKey_doc}, - {"OpenKeyEx", PyOpenKey, METH_VARARGS, OpenKeyEx_doc}, - {"QueryValue", PyQueryValue, METH_VARARGS, QueryValue_doc}, - {"QueryValueEx", PyQueryValueEx, METH_VARARGS, QueryValueEx_doc}, - {"QueryInfoKey", PyQueryInfoKey, METH_VARARGS, QueryInfoKey_doc}, - {"QueryReflectionKey",PyQueryReflectionKey,METH_VARARGS, QueryReflectionKey_doc}, - {"SaveKey", PySaveKey, METH_VARARGS, SaveKey_doc}, - {"SetValue", PySetValue, METH_VARARGS, SetValue_doc}, - {"SetValueEx", PySetValueEx, METH_VARARGS, SetValueEx_doc}, - NULL, + {"CloseKey", PyCloseKey, METH_VARARGS, CloseKey_doc}, + {"ConnectRegistry", PyConnectRegistry, METH_VARARGS, ConnectRegistry_doc}, + {"CreateKey", PyCreateKey, METH_VARARGS, CreateKey_doc}, + {"CreateKeyEx", PyCreateKeyEx, METH_VARARGS, CreateKeyEx_doc}, + {"DeleteKey", PyDeleteKey, METH_VARARGS, DeleteKey_doc}, + {"DeleteKeyEx", PyDeleteKeyEx, METH_VARARGS, DeleteKeyEx_doc}, + {"DeleteValue", PyDeleteValue, METH_VARARGS, DeleteValue_doc}, + {"DisableReflectionKey", PyDisableReflectionKey, METH_VARARGS, DisableReflectionKey_doc}, + {"EnableReflectionKey", PyEnableReflectionKey, METH_VARARGS, EnableReflectionKey_doc}, + {"EnumKey", PyEnumKey, METH_VARARGS, EnumKey_doc}, + {"EnumValue", PyEnumValue, METH_VARARGS, EnumValue_doc}, + {"ExpandEnvironmentStrings", PyExpandEnvironmentStrings, METH_VARARGS, + ExpandEnvironmentStrings_doc }, + {"FlushKey", PyFlushKey, METH_VARARGS, FlushKey_doc}, + {"LoadKey", PyLoadKey, METH_VARARGS, LoadKey_doc}, + {"OpenKey", PyOpenKey, METH_VARARGS, OpenKey_doc}, + {"OpenKeyEx", PyOpenKey, METH_VARARGS, OpenKeyEx_doc}, + {"QueryValue", PyQueryValue, METH_VARARGS, QueryValue_doc}, + {"QueryValueEx", PyQueryValueEx, METH_VARARGS, QueryValueEx_doc}, + {"QueryInfoKey", PyQueryInfoKey, METH_VARARGS, QueryInfoKey_doc}, + {"QueryReflectionKey",PyQueryReflectionKey,METH_VARARGS, QueryReflectionKey_doc}, + {"SaveKey", PySaveKey, METH_VARARGS, SaveKey_doc}, + {"SetValue", PySetValue, METH_VARARGS, SetValue_doc}, + {"SetValueEx", PySetValueEx, METH_VARARGS, SetValueEx_doc}, + NULL, }; static void insint(PyObject * d, char * name, long value) { - PyObject *v = PyLong_FromLong(value); - if (!v || PyDict_SetItemString(d, name, v)) - PyErr_Clear(); - Py_XDECREF(v); + PyObject *v = PyLong_FromLong(value); + if (!v || PyDict_SetItemString(d, name, v)) + PyErr_Clear(); + Py_XDECREF(v); } #define ADD_INT(val) insint(d, #val, val) @@ -1640,104 +1640,104 @@ static void inskey(PyObject * d, char * name, HKEY key) { - PyObject *v = PyLong_FromVoidPtr(key); - if (!v || PyDict_SetItemString(d, name, v)) - PyErr_Clear(); - Py_XDECREF(v); + PyObject *v = PyLong_FromVoidPtr(key); + if (!v || PyDict_SetItemString(d, name, v)) + PyErr_Clear(); + Py_XDECREF(v); } #define ADD_KEY(val) inskey(d, #val, val) static struct PyModuleDef winregmodule = { - PyModuleDef_HEAD_INIT, - "winreg", - module_doc, - -1, - winreg_methods, - NULL, - NULL, - NULL, - NULL + PyModuleDef_HEAD_INIT, + "winreg", + module_doc, + -1, + winreg_methods, + NULL, + NULL, + NULL, + NULL }; PyMODINIT_FUNC PyInit_winreg(void) { - PyObject *m, *d; - m = PyModule_Create(&winregmodule); - if (m == NULL) - return NULL; - d = PyModule_GetDict(m); - PyHKEY_Type.tp_doc = PyHKEY_doc; - if (PyType_Ready(&PyHKEY_Type) < 0) - return NULL; - Py_INCREF(&PyHKEY_Type); - if (PyDict_SetItemString(d, "HKEYType", - (PyObject *)&PyHKEY_Type) != 0) - return NULL; - Py_INCREF(PyExc_WindowsError); - if (PyDict_SetItemString(d, "error", - PyExc_WindowsError) != 0) - return NULL; - - /* Add the relevant constants */ - ADD_KEY(HKEY_CLASSES_ROOT); - ADD_KEY(HKEY_CURRENT_USER); - ADD_KEY(HKEY_LOCAL_MACHINE); - ADD_KEY(HKEY_USERS); - ADD_KEY(HKEY_PERFORMANCE_DATA); + PyObject *m, *d; + m = PyModule_Create(&winregmodule); + if (m == NULL) + return NULL; + d = PyModule_GetDict(m); + PyHKEY_Type.tp_doc = PyHKEY_doc; + if (PyType_Ready(&PyHKEY_Type) < 0) + return NULL; + Py_INCREF(&PyHKEY_Type); + if (PyDict_SetItemString(d, "HKEYType", + (PyObject *)&PyHKEY_Type) != 0) + return NULL; + Py_INCREF(PyExc_WindowsError); + if (PyDict_SetItemString(d, "error", + PyExc_WindowsError) != 0) + return NULL; + + /* Add the relevant constants */ + ADD_KEY(HKEY_CLASSES_ROOT); + ADD_KEY(HKEY_CURRENT_USER); + ADD_KEY(HKEY_LOCAL_MACHINE); + ADD_KEY(HKEY_USERS); + ADD_KEY(HKEY_PERFORMANCE_DATA); #ifdef HKEY_CURRENT_CONFIG - ADD_KEY(HKEY_CURRENT_CONFIG); + ADD_KEY(HKEY_CURRENT_CONFIG); #endif #ifdef HKEY_DYN_DATA - ADD_KEY(HKEY_DYN_DATA); + ADD_KEY(HKEY_DYN_DATA); #endif - ADD_INT(KEY_QUERY_VALUE); - ADD_INT(KEY_SET_VALUE); - ADD_INT(KEY_CREATE_SUB_KEY); - ADD_INT(KEY_ENUMERATE_SUB_KEYS); - ADD_INT(KEY_NOTIFY); - ADD_INT(KEY_CREATE_LINK); - ADD_INT(KEY_READ); - ADD_INT(KEY_WRITE); - ADD_INT(KEY_EXECUTE); - ADD_INT(KEY_ALL_ACCESS); + ADD_INT(KEY_QUERY_VALUE); + ADD_INT(KEY_SET_VALUE); + ADD_INT(KEY_CREATE_SUB_KEY); + ADD_INT(KEY_ENUMERATE_SUB_KEYS); + ADD_INT(KEY_NOTIFY); + ADD_INT(KEY_CREATE_LINK); + ADD_INT(KEY_READ); + ADD_INT(KEY_WRITE); + ADD_INT(KEY_EXECUTE); + ADD_INT(KEY_ALL_ACCESS); #ifdef KEY_WOW64_64KEY - ADD_INT(KEY_WOW64_64KEY); + ADD_INT(KEY_WOW64_64KEY); #endif #ifdef KEY_WOW64_32KEY - ADD_INT(KEY_WOW64_32KEY); + ADD_INT(KEY_WOW64_32KEY); #endif - ADD_INT(REG_OPTION_RESERVED); - ADD_INT(REG_OPTION_NON_VOLATILE); - ADD_INT(REG_OPTION_VOLATILE); - ADD_INT(REG_OPTION_CREATE_LINK); - ADD_INT(REG_OPTION_BACKUP_RESTORE); - ADD_INT(REG_OPTION_OPEN_LINK); - ADD_INT(REG_LEGAL_OPTION); - ADD_INT(REG_CREATED_NEW_KEY); - ADD_INT(REG_OPENED_EXISTING_KEY); - ADD_INT(REG_WHOLE_HIVE_VOLATILE); - ADD_INT(REG_REFRESH_HIVE); - ADD_INT(REG_NO_LAZY_FLUSH); - ADD_INT(REG_NOTIFY_CHANGE_NAME); - ADD_INT(REG_NOTIFY_CHANGE_ATTRIBUTES); - ADD_INT(REG_NOTIFY_CHANGE_LAST_SET); - ADD_INT(REG_NOTIFY_CHANGE_SECURITY); - ADD_INT(REG_LEGAL_CHANGE_FILTER); - ADD_INT(REG_NONE); - ADD_INT(REG_SZ); - ADD_INT(REG_EXPAND_SZ); - ADD_INT(REG_BINARY); - ADD_INT(REG_DWORD); - ADD_INT(REG_DWORD_LITTLE_ENDIAN); - ADD_INT(REG_DWORD_BIG_ENDIAN); - ADD_INT(REG_LINK); - ADD_INT(REG_MULTI_SZ); - ADD_INT(REG_RESOURCE_LIST); - ADD_INT(REG_FULL_RESOURCE_DESCRIPTOR); - ADD_INT(REG_RESOURCE_REQUIREMENTS_LIST); - return m; + ADD_INT(REG_OPTION_RESERVED); + ADD_INT(REG_OPTION_NON_VOLATILE); + ADD_INT(REG_OPTION_VOLATILE); + ADD_INT(REG_OPTION_CREATE_LINK); + ADD_INT(REG_OPTION_BACKUP_RESTORE); + ADD_INT(REG_OPTION_OPEN_LINK); + ADD_INT(REG_LEGAL_OPTION); + ADD_INT(REG_CREATED_NEW_KEY); + ADD_INT(REG_OPENED_EXISTING_KEY); + ADD_INT(REG_WHOLE_HIVE_VOLATILE); + ADD_INT(REG_REFRESH_HIVE); + ADD_INT(REG_NO_LAZY_FLUSH); + ADD_INT(REG_NOTIFY_CHANGE_NAME); + ADD_INT(REG_NOTIFY_CHANGE_ATTRIBUTES); + ADD_INT(REG_NOTIFY_CHANGE_LAST_SET); + ADD_INT(REG_NOTIFY_CHANGE_SECURITY); + ADD_INT(REG_LEGAL_CHANGE_FILTER); + ADD_INT(REG_NONE); + ADD_INT(REG_SZ); + ADD_INT(REG_EXPAND_SZ); + ADD_INT(REG_BINARY); + ADD_INT(REG_DWORD); + ADD_INT(REG_DWORD_LITTLE_ENDIAN); + ADD_INT(REG_DWORD_BIG_ENDIAN); + ADD_INT(REG_LINK); + ADD_INT(REG_MULTI_SZ); + ADD_INT(REG_RESOURCE_LIST); + ADD_INT(REG_FULL_RESOURCE_DESCRIPTOR); + ADD_INT(REG_RESOURCE_REQUIREMENTS_LIST); + return m; } Modified: python/branches/py3k/PC/winsound.c ============================================================================== --- python/branches/py3k/PC/winsound.c (original) +++ python/branches/py3k/PC/winsound.c Sun May 9 17:52:27 2010 @@ -78,14 +78,14 @@ int ok; if(!PyArg_ParseTuple(args,"z#i:PlaySound",&sound,&length,&flags)) { - return NULL; + return NULL; } if(flags&SND_ASYNC && flags &SND_MEMORY) { - /* Sidestep reference counting headache; unfortunately this also - prevent SND_LOOP from memory. */ - PyErr_SetString(PyExc_RuntimeError,"Cannot play asynchronously from memory"); - return NULL; + /* Sidestep reference counting headache; unfortunately this also + prevent SND_LOOP from memory. */ + PyErr_SetString(PyExc_RuntimeError,"Cannot play asynchronously from memory"); + return NULL; } Py_BEGIN_ALLOW_THREADS @@ -93,8 +93,8 @@ Py_END_ALLOW_THREADS if(!ok) { - PyErr_SetString(PyExc_RuntimeError,"Failed to play sound"); - return NULL; + PyErr_SetString(PyExc_RuntimeError,"Failed to play sound"); + return NULL; } Py_INCREF(Py_None); @@ -104,40 +104,40 @@ static PyObject * sound_beep(PyObject *self, PyObject *args) { - int freq; - int dur; - BOOL ok; - - if (!PyArg_ParseTuple(args, "ii:Beep", &freq, &dur)) - return NULL; - - if (freq < 37 || freq > 32767) { - PyErr_SetString(PyExc_ValueError, - "frequency must be in 37 thru 32767"); - return NULL; - } - - Py_BEGIN_ALLOW_THREADS - ok = Beep(freq, dur); - Py_END_ALLOW_THREADS - if (!ok) { - PyErr_SetString(PyExc_RuntimeError,"Failed to beep"); - return NULL; - } + int freq; + int dur; + BOOL ok; + + if (!PyArg_ParseTuple(args, "ii:Beep", &freq, &dur)) + return NULL; + + if (freq < 37 || freq > 32767) { + PyErr_SetString(PyExc_ValueError, + "frequency must be in 37 thru 32767"); + return NULL; + } + + Py_BEGIN_ALLOW_THREADS + ok = Beep(freq, dur); + Py_END_ALLOW_THREADS + if (!ok) { + PyErr_SetString(PyExc_RuntimeError,"Failed to beep"); + return NULL; + } - Py_INCREF(Py_None); - return Py_None; + Py_INCREF(Py_None); + return Py_None; } static PyObject * sound_msgbeep(PyObject *self, PyObject *args) { - int x = MB_OK; - if (!PyArg_ParseTuple(args, "|i:MessageBeep", &x)) - return NULL; - MessageBeep(x); - Py_INCREF(Py_None); - return Py_None; + int x = MB_OK; + if (!PyArg_ParseTuple(args, "|i:MessageBeep", &x)) + return NULL; + MessageBeep(x); + Py_INCREF(Py_None); + return Py_None; } static struct PyMethodDef sound_methods[] = @@ -155,7 +155,7 @@ PyObject *v=PyLong_FromLong(value); if(v&&k) { - PyDict_SetItem(dict,k,v); + PyDict_SetItem(dict,k,v); } Py_XDECREF(k); Py_XDECREF(v); @@ -165,41 +165,41 @@ static struct PyModuleDef winsoundmodule = { - PyModuleDef_HEAD_INIT, - "winsound", - sound_module_doc, - -1, - sound_methods, - NULL, - NULL, - NULL, - NULL + PyModuleDef_HEAD_INIT, + "winsound", + sound_module_doc, + -1, + sound_methods, + NULL, + NULL, + NULL, + NULL }; PyMODINIT_FUNC PyInit_winsound(void) { - PyObject *dict; - PyObject *module = PyModule_Create(&winsoundmodule); - if (module == NULL) - return NULL; - dict = PyModule_GetDict(module); - - ADD_DEFINE(SND_ASYNC); - ADD_DEFINE(SND_NODEFAULT); - ADD_DEFINE(SND_NOSTOP); - ADD_DEFINE(SND_NOWAIT); - ADD_DEFINE(SND_ALIAS); - ADD_DEFINE(SND_FILENAME); - ADD_DEFINE(SND_MEMORY); - ADD_DEFINE(SND_PURGE); - ADD_DEFINE(SND_LOOP); - ADD_DEFINE(SND_APPLICATION); - - ADD_DEFINE(MB_OK); - ADD_DEFINE(MB_ICONASTERISK); - ADD_DEFINE(MB_ICONEXCLAMATION); - ADD_DEFINE(MB_ICONHAND); - ADD_DEFINE(MB_ICONQUESTION); - return module; + PyObject *dict; + PyObject *module = PyModule_Create(&winsoundmodule); + if (module == NULL) + return NULL; + dict = PyModule_GetDict(module); + + ADD_DEFINE(SND_ASYNC); + ADD_DEFINE(SND_NODEFAULT); + ADD_DEFINE(SND_NOSTOP); + ADD_DEFINE(SND_NOWAIT); + ADD_DEFINE(SND_ALIAS); + ADD_DEFINE(SND_FILENAME); + ADD_DEFINE(SND_MEMORY); + ADD_DEFINE(SND_PURGE); + ADD_DEFINE(SND_LOOP); + ADD_DEFINE(SND_APPLICATION); + + ADD_DEFINE(MB_OK); + ADD_DEFINE(MB_ICONASTERISK); + ADD_DEFINE(MB_ICONEXCLAMATION); + ADD_DEFINE(MB_ICONHAND); + ADD_DEFINE(MB_ICONQUESTION); + return module; } Modified: python/branches/py3k/PCbuild/make_buildinfo.c ============================================================================== --- python/branches/py3k/PCbuild/make_buildinfo.c (original) +++ python/branches/py3k/PCbuild/make_buildinfo.c Sun May 9 17:52:27 2010 @@ -23,72 +23,72 @@ int make_buildinfo2() { - struct _stat st; - HKEY hTortoise; - char command[CMD_SIZE+1]; - DWORD type, size; - if (_stat(".svn", &st) < 0) - return 0; - /* Allow suppression of subwcrev.exe invocation if a no_subwcrev file is present. */ - if (_stat("no_subwcrev", &st) == 0) - return 0; - if (RegOpenKey(HKEY_LOCAL_MACHINE, "Software\\TortoiseSVN", &hTortoise) != ERROR_SUCCESS && - RegOpenKey(HKEY_CURRENT_USER, "Software\\TortoiseSVN", &hTortoise) != ERROR_SUCCESS) - /* Tortoise not installed */ - return 0; - command[0] = '"'; /* quote the path to the executable */ - size = sizeof(command) - 1; - if (RegQueryValueEx(hTortoise, "Directory", 0, &type, command+1, &size) != ERROR_SUCCESS || - type != REG_SZ) - /* Registry corrupted */ - return 0; - strcat_s(command, CMD_SIZE, "bin\\subwcrev.exe"); - if (_stat(command+1, &st) < 0) - /* subwcrev.exe not part of the release */ - return 0; - strcat_s(command, CMD_SIZE, "\" .. ..\\Modules\\getbuildinfo.c getbuildinfo2.c"); - puts(command); fflush(stdout); - if (system(command) < 0) - return 0; - return 1; + struct _stat st; + HKEY hTortoise; + char command[CMD_SIZE+1]; + DWORD type, size; + if (_stat(".svn", &st) < 0) + return 0; + /* Allow suppression of subwcrev.exe invocation if a no_subwcrev file is present. */ + if (_stat("no_subwcrev", &st) == 0) + return 0; + if (RegOpenKey(HKEY_LOCAL_MACHINE, "Software\\TortoiseSVN", &hTortoise) != ERROR_SUCCESS && + RegOpenKey(HKEY_CURRENT_USER, "Software\\TortoiseSVN", &hTortoise) != ERROR_SUCCESS) + /* Tortoise not installed */ + return 0; + command[0] = '"'; /* quote the path to the executable */ + size = sizeof(command) - 1; + if (RegQueryValueEx(hTortoise, "Directory", 0, &type, command+1, &size) != ERROR_SUCCESS || + type != REG_SZ) + /* Registry corrupted */ + return 0; + strcat_s(command, CMD_SIZE, "bin\\subwcrev.exe"); + if (_stat(command+1, &st) < 0) + /* subwcrev.exe not part of the release */ + return 0; + strcat_s(command, CMD_SIZE, "\" .. ..\\Modules\\getbuildinfo.c getbuildinfo2.c"); + puts(command); fflush(stdout); + if (system(command) < 0) + return 0; + return 1; } int main(int argc, char*argv[]) { - char command[500] = "cl.exe -c -D_WIN32 -DUSE_DL_EXPORT -D_WINDOWS -DWIN32 -D_WINDLL "; - int do_unlink, result; - if (argc != 2) { - fprintf(stderr, "make_buildinfo $(ConfigurationName)\n"); - return EXIT_FAILURE; - } - if (strcmp(argv[1], "Release") == 0) { - strcat_s(command, CMD_SIZE, "-MD "); - } - else if (strcmp(argv[1], "Debug") == 0) { - strcat_s(command, CMD_SIZE, "-D_DEBUG -MDd "); - } - else if (strcmp(argv[1], "ReleaseItanium") == 0) { - strcat_s(command, CMD_SIZE, "-MD /USECL:MS_ITANIUM "); - } - else if (strcmp(argv[1], "ReleaseAMD64") == 0) { - strcat_s(command, CMD_SIZE, "-MD "); - strcat_s(command, CMD_SIZE, "-MD /USECL:MS_OPTERON "); - } - else { - fprintf(stderr, "unsupported configuration %s\n", argv[1]); - return EXIT_FAILURE; - } + char command[500] = "cl.exe -c -D_WIN32 -DUSE_DL_EXPORT -D_WINDOWS -DWIN32 -D_WINDLL "; + int do_unlink, result; + if (argc != 2) { + fprintf(stderr, "make_buildinfo $(ConfigurationName)\n"); + return EXIT_FAILURE; + } + if (strcmp(argv[1], "Release") == 0) { + strcat_s(command, CMD_SIZE, "-MD "); + } + else if (strcmp(argv[1], "Debug") == 0) { + strcat_s(command, CMD_SIZE, "-D_DEBUG -MDd "); + } + else if (strcmp(argv[1], "ReleaseItanium") == 0) { + strcat_s(command, CMD_SIZE, "-MD /USECL:MS_ITANIUM "); + } + else if (strcmp(argv[1], "ReleaseAMD64") == 0) { + strcat_s(command, CMD_SIZE, "-MD "); + strcat_s(command, CMD_SIZE, "-MD /USECL:MS_OPTERON "); + } + else { + fprintf(stderr, "unsupported configuration %s\n", argv[1]); + return EXIT_FAILURE; + } - if ((do_unlink = make_buildinfo2())) - strcat_s(command, CMD_SIZE, "getbuildinfo2.c -DSUBWCREV "); - else - strcat_s(command, CMD_SIZE, "..\\Modules\\getbuildinfo.c"); - strcat_s(command, CMD_SIZE, " -Fogetbuildinfo.o -I..\\Include -I..\\PC"); - puts(command); fflush(stdout); - result = system(command); - if (do_unlink) - _unlink("getbuildinfo2.c"); - if (result < 0) - return EXIT_FAILURE; - return 0; -} \ No newline at end of file + if ((do_unlink = make_buildinfo2())) + strcat_s(command, CMD_SIZE, "getbuildinfo2.c -DSUBWCREV "); + else + strcat_s(command, CMD_SIZE, "..\\Modules\\getbuildinfo.c"); + strcat_s(command, CMD_SIZE, " -Fogetbuildinfo.o -I..\\Include -I..\\PC"); + puts(command); fflush(stdout); + result = system(command); + if (do_unlink) + _unlink("getbuildinfo2.c"); + if (result < 0) + return EXIT_FAILURE; + return 0; +} Modified: python/branches/py3k/Parser/acceler.c ============================================================================== --- python/branches/py3k/Parser/acceler.c (original) +++ python/branches/py3k/Parser/acceler.c Sun May 9 17:52:27 2010 @@ -23,103 +23,103 @@ void PyGrammar_AddAccelerators(grammar *g) { - dfa *d; - int i; - d = g->g_dfa; - for (i = g->g_ndfas; --i >= 0; d++) - fixdfa(g, d); - g->g_accel = 1; + dfa *d; + int i; + d = g->g_dfa; + for (i = g->g_ndfas; --i >= 0; d++) + fixdfa(g, d); + g->g_accel = 1; } void PyGrammar_RemoveAccelerators(grammar *g) { - dfa *d; - int i; - g->g_accel = 0; - d = g->g_dfa; - for (i = g->g_ndfas; --i >= 0; d++) { - state *s; - int j; - s = d->d_state; - for (j = 0; j < d->d_nstates; j++, s++) { - if (s->s_accel) - PyObject_FREE(s->s_accel); - s->s_accel = NULL; - } - } + dfa *d; + int i; + g->g_accel = 0; + d = g->g_dfa; + for (i = g->g_ndfas; --i >= 0; d++) { + state *s; + int j; + s = d->d_state; + for (j = 0; j < d->d_nstates; j++, s++) { + if (s->s_accel) + PyObject_FREE(s->s_accel); + s->s_accel = NULL; + } + } } static void fixdfa(grammar *g, dfa *d) { - state *s; - int j; - s = d->d_state; - for (j = 0; j < d->d_nstates; j++, s++) - fixstate(g, s); + state *s; + int j; + s = d->d_state; + for (j = 0; j < d->d_nstates; j++, s++) + fixstate(g, s); } static void fixstate(grammar *g, state *s) { - arc *a; - int k; - int *accel; - int nl = g->g_ll.ll_nlabels; - s->s_accept = 0; - accel = (int *) PyObject_MALLOC(nl * sizeof(int)); - if (accel == NULL) { - fprintf(stderr, "no mem to build parser accelerators\n"); - exit(1); - } - for (k = 0; k < nl; k++) - accel[k] = -1; - a = s->s_arc; - for (k = s->s_narcs; --k >= 0; a++) { - int lbl = a->a_lbl; - label *l = &g->g_ll.ll_label[lbl]; - int type = l->lb_type; - if (a->a_arrow >= (1 << 7)) { - printf("XXX too many states!\n"); - continue; - } - if (ISNONTERMINAL(type)) { - dfa *d1 = PyGrammar_FindDFA(g, type); - int ibit; - if (type - NT_OFFSET >= (1 << 7)) { - printf("XXX too high nonterminal number!\n"); - continue; - } - for (ibit = 0; ibit < g->g_ll.ll_nlabels; ibit++) { - if (testbit(d1->d_first, ibit)) { - if (accel[ibit] != -1) - printf("XXX ambiguity!\n"); - accel[ibit] = a->a_arrow | (1 << 7) | - ((type - NT_OFFSET) << 8); - } - } - } - else if (lbl == EMPTY) - s->s_accept = 1; - else if (lbl >= 0 && lbl < nl) - accel[lbl] = a->a_arrow; - } - while (nl > 0 && accel[nl-1] == -1) - nl--; - for (k = 0; k < nl && accel[k] == -1;) - k++; - if (k < nl) { - int i; - s->s_accel = (int *) PyObject_MALLOC((nl-k) * sizeof(int)); - if (s->s_accel == NULL) { - fprintf(stderr, "no mem to add parser accelerators\n"); - exit(1); - } - s->s_lower = k; - s->s_upper = nl; - for (i = 0; k < nl; i++, k++) - s->s_accel[i] = accel[k]; - } - PyObject_FREE(accel); + arc *a; + int k; + int *accel; + int nl = g->g_ll.ll_nlabels; + s->s_accept = 0; + accel = (int *) PyObject_MALLOC(nl * sizeof(int)); + if (accel == NULL) { + fprintf(stderr, "no mem to build parser accelerators\n"); + exit(1); + } + for (k = 0; k < nl; k++) + accel[k] = -1; + a = s->s_arc; + for (k = s->s_narcs; --k >= 0; a++) { + int lbl = a->a_lbl; + label *l = &g->g_ll.ll_label[lbl]; + int type = l->lb_type; + if (a->a_arrow >= (1 << 7)) { + printf("XXX too many states!\n"); + continue; + } + if (ISNONTERMINAL(type)) { + dfa *d1 = PyGrammar_FindDFA(g, type); + int ibit; + if (type - NT_OFFSET >= (1 << 7)) { + printf("XXX too high nonterminal number!\n"); + continue; + } + for (ibit = 0; ibit < g->g_ll.ll_nlabels; ibit++) { + if (testbit(d1->d_first, ibit)) { + if (accel[ibit] != -1) + printf("XXX ambiguity!\n"); + accel[ibit] = a->a_arrow | (1 << 7) | + ((type - NT_OFFSET) << 8); + } + } + } + else if (lbl == EMPTY) + s->s_accept = 1; + else if (lbl >= 0 && lbl < nl) + accel[lbl] = a->a_arrow; + } + while (nl > 0 && accel[nl-1] == -1) + nl--; + for (k = 0; k < nl && accel[k] == -1;) + k++; + if (k < nl) { + int i; + s->s_accel = (int *) PyObject_MALLOC((nl-k) * sizeof(int)); + if (s->s_accel == NULL) { + fprintf(stderr, "no mem to add parser accelerators\n"); + exit(1); + } + s->s_lower = k; + s->s_upper = nl; + for (i = 0; k < nl; i++, k++) + s->s_accel[i] = accel[k]; + } + PyObject_FREE(accel); } Modified: python/branches/py3k/Parser/bitset.c ============================================================================== --- python/branches/py3k/Parser/bitset.c (original) +++ python/branches/py3k/Parser/bitset.c Sun May 9 17:52:27 2010 @@ -7,60 +7,60 @@ bitset newbitset(int nbits) { - int nbytes = NBYTES(nbits); - bitset ss = (char *)PyObject_MALLOC(sizeof(BYTE) * nbytes); - - if (ss == NULL) - Py_FatalError("no mem for bitset"); - - ss += nbytes; - while (--nbytes >= 0) - *--ss = 0; - return ss; + int nbytes = NBYTES(nbits); + bitset ss = (char *)PyObject_MALLOC(sizeof(BYTE) * nbytes); + + if (ss == NULL) + Py_FatalError("no mem for bitset"); + + ss += nbytes; + while (--nbytes >= 0) + *--ss = 0; + return ss; } void delbitset(bitset ss) { - PyObject_FREE(ss); + PyObject_FREE(ss); } int addbit(bitset ss, int ibit) { - int ibyte = BIT2BYTE(ibit); - BYTE mask = BIT2MASK(ibit); - - if (ss[ibyte] & mask) - return 0; /* Bit already set */ - ss[ibyte] |= mask; - return 1; + int ibyte = BIT2BYTE(ibit); + BYTE mask = BIT2MASK(ibit); + + if (ss[ibyte] & mask) + return 0; /* Bit already set */ + ss[ibyte] |= mask; + return 1; } #if 0 /* Now a macro */ int testbit(bitset ss, int ibit) { - return (ss[BIT2BYTE(ibit)] & BIT2MASK(ibit)) != 0; + return (ss[BIT2BYTE(ibit)] & BIT2MASK(ibit)) != 0; } #endif int samebitset(bitset ss1, bitset ss2, int nbits) { - int i; - - for (i = NBYTES(nbits); --i >= 0; ) - if (*ss1++ != *ss2++) - return 0; - return 1; + int i; + + for (i = NBYTES(nbits); --i >= 0; ) + if (*ss1++ != *ss2++) + return 0; + return 1; } void mergebitset(bitset ss1, bitset ss2, int nbits) { - int i; - - for (i = NBYTES(nbits); --i >= 0; ) - *ss1++ |= *ss2++; + int i; + + for (i = NBYTES(nbits); --i >= 0; ) + *ss1++ |= *ss2++; } Modified: python/branches/py3k/Parser/firstsets.c ============================================================================== --- python/branches/py3k/Parser/firstsets.c (original) +++ python/branches/py3k/Parser/firstsets.c Sun May 9 17:52:27 2010 @@ -13,101 +13,101 @@ void addfirstsets(grammar *g) { - int i; - dfa *d; + int i; + dfa *d; - if (Py_DebugFlag) - printf("Adding FIRST sets ...\n"); - for (i = 0; i < g->g_ndfas; i++) { - d = &g->g_dfa[i]; - if (d->d_first == NULL) - calcfirstset(g, d); - } + if (Py_DebugFlag) + printf("Adding FIRST sets ...\n"); + for (i = 0; i < g->g_ndfas; i++) { + d = &g->g_dfa[i]; + if (d->d_first == NULL) + calcfirstset(g, d); + } } static void calcfirstset(grammar *g, dfa *d) { - int i, j; - state *s; - arc *a; - int nsyms; - int *sym; - int nbits; - static bitset dummy; - bitset result; - int type; - dfa *d1; - label *l0; - - if (Py_DebugFlag) - printf("Calculate FIRST set for '%s'\n", d->d_name); - - if (dummy == NULL) - dummy = newbitset(1); - if (d->d_first == dummy) { - fprintf(stderr, "Left-recursion for '%s'\n", d->d_name); - return; - } - if (d->d_first != NULL) { - fprintf(stderr, "Re-calculating FIRST set for '%s' ???\n", - d->d_name); - } - d->d_first = dummy; - - l0 = g->g_ll.ll_label; - nbits = g->g_ll.ll_nlabels; - result = newbitset(nbits); - - sym = (int *)PyObject_MALLOC(sizeof(int)); - if (sym == NULL) - Py_FatalError("no mem for new sym in calcfirstset"); - nsyms = 1; - sym[0] = findlabel(&g->g_ll, d->d_type, (char *)NULL); - - s = &d->d_state[d->d_initial]; - for (i = 0; i < s->s_narcs; i++) { - a = &s->s_arc[i]; - for (j = 0; j < nsyms; j++) { - if (sym[j] == a->a_lbl) - break; - } - if (j >= nsyms) { /* New label */ - sym = (int *)PyObject_REALLOC(sym, - sizeof(int) * (nsyms + 1)); - if (sym == NULL) - Py_FatalError( - "no mem to resize sym in calcfirstset"); - sym[nsyms++] = a->a_lbl; - type = l0[a->a_lbl].lb_type; - if (ISNONTERMINAL(type)) { - d1 = PyGrammar_FindDFA(g, type); - if (d1->d_first == dummy) { - fprintf(stderr, - "Left-recursion below '%s'\n", - d->d_name); - } - else { - if (d1->d_first == NULL) - calcfirstset(g, d1); - mergebitset(result, - d1->d_first, nbits); - } - } - else if (ISTERMINAL(type)) { - addbit(result, a->a_lbl); - } - } - } - d->d_first = result; - if (Py_DebugFlag) { - printf("FIRST set for '%s': {", d->d_name); - for (i = 0; i < nbits; i++) { - if (testbit(result, i)) - printf(" %s", PyGrammar_LabelRepr(&l0[i])); - } - printf(" }\n"); - } + int i, j; + state *s; + arc *a; + int nsyms; + int *sym; + int nbits; + static bitset dummy; + bitset result; + int type; + dfa *d1; + label *l0; - PyObject_FREE(sym); + if (Py_DebugFlag) + printf("Calculate FIRST set for '%s'\n", d->d_name); + + if (dummy == NULL) + dummy = newbitset(1); + if (d->d_first == dummy) { + fprintf(stderr, "Left-recursion for '%s'\n", d->d_name); + return; + } + if (d->d_first != NULL) { + fprintf(stderr, "Re-calculating FIRST set for '%s' ???\n", + d->d_name); + } + d->d_first = dummy; + + l0 = g->g_ll.ll_label; + nbits = g->g_ll.ll_nlabels; + result = newbitset(nbits); + + sym = (int *)PyObject_MALLOC(sizeof(int)); + if (sym == NULL) + Py_FatalError("no mem for new sym in calcfirstset"); + nsyms = 1; + sym[0] = findlabel(&g->g_ll, d->d_type, (char *)NULL); + + s = &d->d_state[d->d_initial]; + for (i = 0; i < s->s_narcs; i++) { + a = &s->s_arc[i]; + for (j = 0; j < nsyms; j++) { + if (sym[j] == a->a_lbl) + break; + } + if (j >= nsyms) { /* New label */ + sym = (int *)PyObject_REALLOC(sym, + sizeof(int) * (nsyms + 1)); + if (sym == NULL) + Py_FatalError( + "no mem to resize sym in calcfirstset"); + sym[nsyms++] = a->a_lbl; + type = l0[a->a_lbl].lb_type; + if (ISNONTERMINAL(type)) { + d1 = PyGrammar_FindDFA(g, type); + if (d1->d_first == dummy) { + fprintf(stderr, + "Left-recursion below '%s'\n", + d->d_name); + } + else { + if (d1->d_first == NULL) + calcfirstset(g, d1); + mergebitset(result, + d1->d_first, nbits); + } + } + else if (ISTERMINAL(type)) { + addbit(result, a->a_lbl); + } + } + } + d->d_first = result; + if (Py_DebugFlag) { + printf("FIRST set for '%s': {", d->d_name); + for (i = 0; i < nbits; i++) { + if (testbit(result, i)) + printf(" %s", PyGrammar_LabelRepr(&l0[i])); + } + printf(" }\n"); + } + + PyObject_FREE(sym); } Modified: python/branches/py3k/Parser/grammar.c ============================================================================== --- python/branches/py3k/Parser/grammar.c (original) +++ python/branches/py3k/Parser/grammar.c Sun May 9 17:52:27 2010 @@ -14,98 +14,98 @@ grammar * newgrammar(int start) { - grammar *g; - - g = (grammar *)PyObject_MALLOC(sizeof(grammar)); - if (g == NULL) - Py_FatalError("no mem for new grammar"); - g->g_ndfas = 0; - g->g_dfa = NULL; - g->g_start = start; - g->g_ll.ll_nlabels = 0; - g->g_ll.ll_label = NULL; - g->g_accel = 0; - return g; + grammar *g; + + g = (grammar *)PyObject_MALLOC(sizeof(grammar)); + if (g == NULL) + Py_FatalError("no mem for new grammar"); + g->g_ndfas = 0; + g->g_dfa = NULL; + g->g_start = start; + g->g_ll.ll_nlabels = 0; + g->g_ll.ll_label = NULL; + g->g_accel = 0; + return g; } dfa * adddfa(grammar *g, int type, char *name) { - dfa *d; - - g->g_dfa = (dfa *)PyObject_REALLOC(g->g_dfa, - sizeof(dfa) * (g->g_ndfas + 1)); - if (g->g_dfa == NULL) - Py_FatalError("no mem to resize dfa in adddfa"); - d = &g->g_dfa[g->g_ndfas++]; - d->d_type = type; - d->d_name = strdup(name); - d->d_nstates = 0; - d->d_state = NULL; - d->d_initial = -1; - d->d_first = NULL; - return d; /* Only use while fresh! */ + dfa *d; + + g->g_dfa = (dfa *)PyObject_REALLOC(g->g_dfa, + sizeof(dfa) * (g->g_ndfas + 1)); + if (g->g_dfa == NULL) + Py_FatalError("no mem to resize dfa in adddfa"); + d = &g->g_dfa[g->g_ndfas++]; + d->d_type = type; + d->d_name = strdup(name); + d->d_nstates = 0; + d->d_state = NULL; + d->d_initial = -1; + d->d_first = NULL; + return d; /* Only use while fresh! */ } int addstate(dfa *d) { - state *s; - - d->d_state = (state *)PyObject_REALLOC(d->d_state, - sizeof(state) * (d->d_nstates + 1)); - if (d->d_state == NULL) - Py_FatalError("no mem to resize state in addstate"); - s = &d->d_state[d->d_nstates++]; - s->s_narcs = 0; - s->s_arc = NULL; - s->s_lower = 0; - s->s_upper = 0; - s->s_accel = NULL; - s->s_accept = 0; - return s - d->d_state; + state *s; + + d->d_state = (state *)PyObject_REALLOC(d->d_state, + sizeof(state) * (d->d_nstates + 1)); + if (d->d_state == NULL) + Py_FatalError("no mem to resize state in addstate"); + s = &d->d_state[d->d_nstates++]; + s->s_narcs = 0; + s->s_arc = NULL; + s->s_lower = 0; + s->s_upper = 0; + s->s_accel = NULL; + s->s_accept = 0; + return s - d->d_state; } void addarc(dfa *d, int from, int to, int lbl) { - state *s; - arc *a; - - assert(0 <= from && from < d->d_nstates); - assert(0 <= to && to < d->d_nstates); - - s = &d->d_state[from]; - s->s_arc = (arc *)PyObject_REALLOC(s->s_arc, sizeof(arc) * (s->s_narcs + 1)); - if (s->s_arc == NULL) - Py_FatalError("no mem to resize arc list in addarc"); - a = &s->s_arc[s->s_narcs++]; - a->a_lbl = lbl; - a->a_arrow = to; + state *s; + arc *a; + + assert(0 <= from && from < d->d_nstates); + assert(0 <= to && to < d->d_nstates); + + s = &d->d_state[from]; + s->s_arc = (arc *)PyObject_REALLOC(s->s_arc, sizeof(arc) * (s->s_narcs + 1)); + if (s->s_arc == NULL) + Py_FatalError("no mem to resize arc list in addarc"); + a = &s->s_arc[s->s_narcs++]; + a->a_lbl = lbl; + a->a_arrow = to; } int addlabel(labellist *ll, int type, char *str) { - int i; - label *lb; - - for (i = 0; i < ll->ll_nlabels; i++) { - if (ll->ll_label[i].lb_type == type && - strcmp(ll->ll_label[i].lb_str, str) == 0) - return i; - } - ll->ll_label = (label *)PyObject_REALLOC(ll->ll_label, - sizeof(label) * (ll->ll_nlabels + 1)); - if (ll->ll_label == NULL) - Py_FatalError("no mem to resize labellist in addlabel"); - lb = &ll->ll_label[ll->ll_nlabels++]; - lb->lb_type = type; - lb->lb_str = strdup(str); - if (Py_DebugFlag) - printf("Label @ %8p, %d: %s\n", ll, ll->ll_nlabels, - PyGrammar_LabelRepr(lb)); - return lb - ll->ll_label; + int i; + label *lb; + + for (i = 0; i < ll->ll_nlabels; i++) { + if (ll->ll_label[i].lb_type == type && + strcmp(ll->ll_label[i].lb_str, str) == 0) + return i; + } + ll->ll_label = (label *)PyObject_REALLOC(ll->ll_label, + sizeof(label) * (ll->ll_nlabels + 1)); + if (ll->ll_label == NULL) + Py_FatalError("no mem to resize labellist in addlabel"); + lb = &ll->ll_label[ll->ll_nlabels++]; + lb->lb_type = type; + lb->lb_str = strdup(str); + if (Py_DebugFlag) + printf("Label @ %8p, %d: %s\n", ll, ll->ll_nlabels, + PyGrammar_LabelRepr(lb)); + return lb - ll->ll_label; } /* Same, but rather dies than adds */ @@ -113,16 +113,16 @@ int findlabel(labellist *ll, int type, char *str) { - int i; - - for (i = 0; i < ll->ll_nlabels; i++) { - if (ll->ll_label[i].lb_type == type /*&& - strcmp(ll->ll_label[i].lb_str, str) == 0*/) - return i; - } - fprintf(stderr, "Label %d/'%s' not found\n", type, str); - Py_FatalError("grammar.c:findlabel()"); - return 0; /* Make gcc -Wall happy */ + int i; + + for (i = 0; i < ll->ll_nlabels; i++) { + if (ll->ll_label[i].lb_type == type /*&& + strcmp(ll->ll_label[i].lb_str, str) == 0*/) + return i; + } + fprintf(stderr, "Label %d/'%s' not found\n", type, str); + Py_FatalError("grammar.c:findlabel()"); + return 0; /* Make gcc -Wall happy */ } /* Forward */ @@ -131,120 +131,120 @@ void translatelabels(grammar *g) { - int i; + int i; #ifdef Py_DEBUG - printf("Translating labels ...\n"); + printf("Translating labels ...\n"); #endif - /* Don't translate EMPTY */ - for (i = EMPTY+1; i < g->g_ll.ll_nlabels; i++) - translabel(g, &g->g_ll.ll_label[i]); + /* Don't translate EMPTY */ + for (i = EMPTY+1; i < g->g_ll.ll_nlabels; i++) + translabel(g, &g->g_ll.ll_label[i]); } static void translabel(grammar *g, label *lb) { - int i; - - if (Py_DebugFlag) - printf("Translating label %s ...\n", PyGrammar_LabelRepr(lb)); - - if (lb->lb_type == NAME) { - for (i = 0; i < g->g_ndfas; i++) { - if (strcmp(lb->lb_str, g->g_dfa[i].d_name) == 0) { - if (Py_DebugFlag) - printf( - "Label %s is non-terminal %d.\n", - lb->lb_str, - g->g_dfa[i].d_type); - lb->lb_type = g->g_dfa[i].d_type; - free(lb->lb_str); - lb->lb_str = NULL; - return; - } - } - for (i = 0; i < (int)N_TOKENS; i++) { - if (strcmp(lb->lb_str, _PyParser_TokenNames[i]) == 0) { - if (Py_DebugFlag) - printf("Label %s is terminal %d.\n", - lb->lb_str, i); - lb->lb_type = i; - free(lb->lb_str); - lb->lb_str = NULL; - return; - } - } - printf("Can't translate NAME label '%s'\n", lb->lb_str); - return; - } - - if (lb->lb_type == STRING) { - if (isalpha(Py_CHARMASK(lb->lb_str[1])) || - lb->lb_str[1] == '_') { - char *p; - char *src; - char *dest; - size_t name_len; - if (Py_DebugFlag) - printf("Label %s is a keyword\n", lb->lb_str); - lb->lb_type = NAME; - src = lb->lb_str + 1; - p = strchr(src, '\''); - if (p) - name_len = p - src; - else - name_len = strlen(src); - dest = (char *)malloc(name_len + 1); - if (!dest) { - printf("Can't alloc dest '%s'\n", src); - return; - } - strncpy(dest, src, name_len); - dest[name_len] = '\0'; - free(lb->lb_str); - lb->lb_str = dest; - } - else if (lb->lb_str[2] == lb->lb_str[0]) { - int type = (int) PyToken_OneChar(lb->lb_str[1]); - if (type != OP) { - lb->lb_type = type; - free(lb->lb_str); - lb->lb_str = NULL; - } - else - printf("Unknown OP label %s\n", - lb->lb_str); - } - else if (lb->lb_str[2] && lb->lb_str[3] == lb->lb_str[0]) { - int type = (int) PyToken_TwoChars(lb->lb_str[1], - lb->lb_str[2]); - if (type != OP) { - lb->lb_type = type; - free(lb->lb_str); - lb->lb_str = NULL; - } - else - printf("Unknown OP label %s\n", - lb->lb_str); - } - else if (lb->lb_str[2] && lb->lb_str[3] && lb->lb_str[4] == lb->lb_str[0]) { - int type = (int) PyToken_ThreeChars(lb->lb_str[1], - lb->lb_str[2], - lb->lb_str[3]); - if (type != OP) { - lb->lb_type = type; - free(lb->lb_str); - lb->lb_str = NULL; - } - else - printf("Unknown OP label %s\n", - lb->lb_str); - } - else - printf("Can't translate STRING label %s\n", - lb->lb_str); - } - else - printf("Can't translate label '%s'\n", - PyGrammar_LabelRepr(lb)); + int i; + + if (Py_DebugFlag) + printf("Translating label %s ...\n", PyGrammar_LabelRepr(lb)); + + if (lb->lb_type == NAME) { + for (i = 0; i < g->g_ndfas; i++) { + if (strcmp(lb->lb_str, g->g_dfa[i].d_name) == 0) { + if (Py_DebugFlag) + printf( + "Label %s is non-terminal %d.\n", + lb->lb_str, + g->g_dfa[i].d_type); + lb->lb_type = g->g_dfa[i].d_type; + free(lb->lb_str); + lb->lb_str = NULL; + return; + } + } + for (i = 0; i < (int)N_TOKENS; i++) { + if (strcmp(lb->lb_str, _PyParser_TokenNames[i]) == 0) { + if (Py_DebugFlag) + printf("Label %s is terminal %d.\n", + lb->lb_str, i); + lb->lb_type = i; + free(lb->lb_str); + lb->lb_str = NULL; + return; + } + } + printf("Can't translate NAME label '%s'\n", lb->lb_str); + return; + } + + if (lb->lb_type == STRING) { + if (isalpha(Py_CHARMASK(lb->lb_str[1])) || + lb->lb_str[1] == '_') { + char *p; + char *src; + char *dest; + size_t name_len; + if (Py_DebugFlag) + printf("Label %s is a keyword\n", lb->lb_str); + lb->lb_type = NAME; + src = lb->lb_str + 1; + p = strchr(src, '\''); + if (p) + name_len = p - src; + else + name_len = strlen(src); + dest = (char *)malloc(name_len + 1); + if (!dest) { + printf("Can't alloc dest '%s'\n", src); + return; + } + strncpy(dest, src, name_len); + dest[name_len] = '\0'; + free(lb->lb_str); + lb->lb_str = dest; + } + else if (lb->lb_str[2] == lb->lb_str[0]) { + int type = (int) PyToken_OneChar(lb->lb_str[1]); + if (type != OP) { + lb->lb_type = type; + free(lb->lb_str); + lb->lb_str = NULL; + } + else + printf("Unknown OP label %s\n", + lb->lb_str); + } + else if (lb->lb_str[2] && lb->lb_str[3] == lb->lb_str[0]) { + int type = (int) PyToken_TwoChars(lb->lb_str[1], + lb->lb_str[2]); + if (type != OP) { + lb->lb_type = type; + free(lb->lb_str); + lb->lb_str = NULL; + } + else + printf("Unknown OP label %s\n", + lb->lb_str); + } + else if (lb->lb_str[2] && lb->lb_str[3] && lb->lb_str[4] == lb->lb_str[0]) { + int type = (int) PyToken_ThreeChars(lb->lb_str[1], + lb->lb_str[2], + lb->lb_str[3]); + if (type != OP) { + lb->lb_type = type; + free(lb->lb_str); + lb->lb_str = NULL; + } + else + printf("Unknown OP label %s\n", + lb->lb_str); + } + else + printf("Can't translate STRING label %s\n", + lb->lb_str); + } + else + printf("Can't translate label '%s'\n", + PyGrammar_LabelRepr(lb)); } Modified: python/branches/py3k/Parser/grammar1.c ============================================================================== --- python/branches/py3k/Parser/grammar1.c (original) +++ python/branches/py3k/Parser/grammar1.c Sun May 9 17:52:27 2010 @@ -11,47 +11,47 @@ dfa * PyGrammar_FindDFA(grammar *g, register int type) { - register dfa *d; + register dfa *d; #if 1 - /* Massive speed-up */ - d = &g->g_dfa[type - NT_OFFSET]; - assert(d->d_type == type); - return d; + /* Massive speed-up */ + d = &g->g_dfa[type - NT_OFFSET]; + assert(d->d_type == type); + return d; #else - /* Old, slow version */ - register int i; - - for (i = g->g_ndfas, d = g->g_dfa; --i >= 0; d++) { - if (d->d_type == type) - return d; - } - assert(0); - /* NOTREACHED */ + /* Old, slow version */ + register int i; + + for (i = g->g_ndfas, d = g->g_dfa; --i >= 0; d++) { + if (d->d_type == type) + return d; + } + assert(0); + /* NOTREACHED */ #endif } char * PyGrammar_LabelRepr(label *lb) { - static char buf[100]; - - if (lb->lb_type == ENDMARKER) - return "EMPTY"; - else if (ISNONTERMINAL(lb->lb_type)) { - if (lb->lb_str == NULL) { - PyOS_snprintf(buf, sizeof(buf), "NT%d", lb->lb_type); - return buf; - } - else - return lb->lb_str; - } - else { - if (lb->lb_str == NULL) - return _PyParser_TokenNames[lb->lb_type]; - else { - PyOS_snprintf(buf, sizeof(buf), "%.32s(%.32s)", - _PyParser_TokenNames[lb->lb_type], lb->lb_str); - return buf; - } - } + static char buf[100]; + + if (lb->lb_type == ENDMARKER) + return "EMPTY"; + else if (ISNONTERMINAL(lb->lb_type)) { + if (lb->lb_str == NULL) { + PyOS_snprintf(buf, sizeof(buf), "NT%d", lb->lb_type); + return buf; + } + else + return lb->lb_str; + } + else { + if (lb->lb_str == NULL) + return _PyParser_TokenNames[lb->lb_type]; + else { + PyOS_snprintf(buf, sizeof(buf), "%.32s(%.32s)", + _PyParser_TokenNames[lb->lb_type], lb->lb_str); + return buf; + } + } } Modified: python/branches/py3k/Parser/intrcheck.c ============================================================================== --- python/branches/py3k/Parser/intrcheck.c (original) +++ python/branches/py3k/Parser/intrcheck.c Sun May 9 17:52:27 2010 @@ -21,7 +21,7 @@ int PyOS_InterruptOccurred(void) { - _wyield(); + _wyield(); } #define OK @@ -47,7 +47,7 @@ void PyOS_InitInterrupts(void) { - _go32_want_ctrl_break(1 /* TRUE */); + _go32_want_ctrl_break(1 /* TRUE */); } void @@ -58,7 +58,7 @@ int PyOS_InterruptOccurred(void) { - return _go32_was_ctrl_break_hit(); + return _go32_was_ctrl_break_hit(); } #else /* !__GNUC__ */ @@ -78,12 +78,12 @@ int PyOS_InterruptOccurred(void) { - int interrupted = 0; - while (kbhit()) { - if (getch() == '\003') - interrupted = 1; - } - return interrupted; + int interrupted = 0; + while (kbhit()) { + if (getch() == '\003') + interrupted = 1; + } + return interrupted; } #endif /* __GNUC__ */ @@ -106,7 +106,7 @@ void PyErr_SetInterrupt(void) { - interrupted = 1; + interrupted = 1; } extern int PyErr_CheckSignals(void); @@ -114,28 +114,28 @@ static int checksignals_witharg(void * arg) { - return PyErr_CheckSignals(); + return PyErr_CheckSignals(); } static void intcatcher(int sig) { - extern void Py_Exit(int); - static char message[] = + extern void Py_Exit(int); + static char message[] = "python: to interrupt a truly hanging Python program, interrupt once more.\n"; - switch (interrupted++) { - case 0: - break; - case 1: - write(2, message, strlen(message)); - break; - case 2: - interrupted = 0; - Py_Exit(1); - break; - } - PyOS_setsig(SIGINT, intcatcher); - Py_AddPendingCall(checksignals_witharg, NULL); + switch (interrupted++) { + case 0: + break; + case 1: + write(2, message, strlen(message)); + break; + case 2: + interrupted = 0; + Py_Exit(1); + break; + } + PyOS_setsig(SIGINT, intcatcher); + Py_AddPendingCall(checksignals_witharg, NULL); } static void (*old_siginthandler)(int) = SIG_DFL; @@ -143,23 +143,23 @@ void PyOS_InitInterrupts(void) { - if ((old_siginthandler = PyOS_setsig(SIGINT, SIG_IGN)) != SIG_IGN) - PyOS_setsig(SIGINT, intcatcher); + if ((old_siginthandler = PyOS_setsig(SIGINT, SIG_IGN)) != SIG_IGN) + PyOS_setsig(SIGINT, intcatcher); } void PyOS_FiniInterrupts(void) { - PyOS_setsig(SIGINT, old_siginthandler); + PyOS_setsig(SIGINT, old_siginthandler); } int PyOS_InterruptOccurred(void) { - if (!interrupted) - return 0; - interrupted = 0; - return 1; + if (!interrupted) + return 0; + interrupted = 0; + return 1; } #endif /* !OK */ @@ -168,7 +168,7 @@ PyOS_AfterFork(void) { #ifdef WITH_THREAD - PyEval_ReInitThreads(); - PyThread_ReInitTLS(); + PyEval_ReInitThreads(); + PyThread_ReInitTLS(); #endif } Modified: python/branches/py3k/Parser/listnode.c ============================================================================== --- python/branches/py3k/Parser/listnode.c (original) +++ python/branches/py3k/Parser/listnode.c Sun May 9 17:52:27 2010 @@ -12,7 +12,7 @@ void PyNode_ListTree(node *n) { - listnode(stdout, n); + listnode(stdout, n); } static int level, atbol; @@ -20,47 +20,47 @@ static void listnode(FILE *fp, node *n) { - level = 0; - atbol = 1; - list1node(fp, n); + level = 0; + atbol = 1; + list1node(fp, n); } static void list1node(FILE *fp, node *n) { - if (n == 0) - return; - if (ISNONTERMINAL(TYPE(n))) { - int i; - for (i = 0; i < NCH(n); i++) - list1node(fp, CHILD(n, i)); - } - else if (ISTERMINAL(TYPE(n))) { - switch (TYPE(n)) { - case INDENT: - ++level; - break; - case DEDENT: - --level; - break; - default: - if (atbol) { - int i; - for (i = 0; i < level; ++i) - fprintf(fp, "\t"); - atbol = 0; - } - if (TYPE(n) == NEWLINE) { - if (STR(n) != NULL) - fprintf(fp, "%s", STR(n)); - fprintf(fp, "\n"); - atbol = 1; - } - else - fprintf(fp, "%s ", STR(n)); - break; - } - } - else - fprintf(fp, "? "); + if (n == 0) + return; + if (ISNONTERMINAL(TYPE(n))) { + int i; + for (i = 0; i < NCH(n); i++) + list1node(fp, CHILD(n, i)); + } + else if (ISTERMINAL(TYPE(n))) { + switch (TYPE(n)) { + case INDENT: + ++level; + break; + case DEDENT: + --level; + break; + default: + if (atbol) { + int i; + for (i = 0; i < level; ++i) + fprintf(fp, "\t"); + atbol = 0; + } + if (TYPE(n) == NEWLINE) { + if (STR(n) != NULL) + fprintf(fp, "%s", STR(n)); + fprintf(fp, "\n"); + atbol = 1; + } + else + fprintf(fp, "%s ", STR(n)); + break; + } + } + else + fprintf(fp, "? "); } Modified: python/branches/py3k/Parser/metagrammar.c ============================================================================== --- python/branches/py3k/Parser/metagrammar.c (original) +++ python/branches/py3k/Parser/metagrammar.c Sun May 9 17:52:27 2010 @@ -4,152 +4,152 @@ #include "grammar.h" #include "pgen.h" static arc arcs_0_0[3] = { - {2, 0}, - {3, 0}, - {4, 1}, + {2, 0}, + {3, 0}, + {4, 1}, }; static arc arcs_0_1[1] = { - {0, 1}, + {0, 1}, }; static state states_0[2] = { - {3, arcs_0_0}, - {1, arcs_0_1}, + {3, arcs_0_0}, + {1, arcs_0_1}, }; static arc arcs_1_0[1] = { - {5, 1}, + {5, 1}, }; static arc arcs_1_1[1] = { - {6, 2}, + {6, 2}, }; static arc arcs_1_2[1] = { - {7, 3}, + {7, 3}, }; static arc arcs_1_3[1] = { - {3, 4}, + {3, 4}, }; static arc arcs_1_4[1] = { - {0, 4}, + {0, 4}, }; static state states_1[5] = { - {1, arcs_1_0}, - {1, arcs_1_1}, - {1, arcs_1_2}, - {1, arcs_1_3}, - {1, arcs_1_4}, + {1, arcs_1_0}, + {1, arcs_1_1}, + {1, arcs_1_2}, + {1, arcs_1_3}, + {1, arcs_1_4}, }; static arc arcs_2_0[1] = { - {8, 1}, + {8, 1}, }; static arc arcs_2_1[2] = { - {9, 0}, - {0, 1}, + {9, 0}, + {0, 1}, }; static state states_2[2] = { - {1, arcs_2_0}, - {2, arcs_2_1}, + {1, arcs_2_0}, + {2, arcs_2_1}, }; static arc arcs_3_0[1] = { - {10, 1}, + {10, 1}, }; static arc arcs_3_1[2] = { - {10, 1}, - {0, 1}, + {10, 1}, + {0, 1}, }; static state states_3[2] = { - {1, arcs_3_0}, - {2, arcs_3_1}, + {1, arcs_3_0}, + {2, arcs_3_1}, }; static arc arcs_4_0[2] = { - {11, 1}, - {13, 2}, + {11, 1}, + {13, 2}, }; static arc arcs_4_1[1] = { - {7, 3}, + {7, 3}, }; static arc arcs_4_2[3] = { - {14, 4}, - {15, 4}, - {0, 2}, + {14, 4}, + {15, 4}, + {0, 2}, }; static arc arcs_4_3[1] = { - {12, 4}, + {12, 4}, }; static arc arcs_4_4[1] = { - {0, 4}, + {0, 4}, }; static state states_4[5] = { - {2, arcs_4_0}, - {1, arcs_4_1}, - {3, arcs_4_2}, - {1, arcs_4_3}, - {1, arcs_4_4}, + {2, arcs_4_0}, + {1, arcs_4_1}, + {3, arcs_4_2}, + {1, arcs_4_3}, + {1, arcs_4_4}, }; static arc arcs_5_0[3] = { - {5, 1}, - {16, 1}, - {17, 2}, + {5, 1}, + {16, 1}, + {17, 2}, }; static arc arcs_5_1[1] = { - {0, 1}, + {0, 1}, }; static arc arcs_5_2[1] = { - {7, 3}, + {7, 3}, }; static arc arcs_5_3[1] = { - {18, 1}, + {18, 1}, }; static state states_5[4] = { - {3, arcs_5_0}, - {1, arcs_5_1}, - {1, arcs_5_2}, - {1, arcs_5_3}, + {3, arcs_5_0}, + {1, arcs_5_1}, + {1, arcs_5_2}, + {1, arcs_5_3}, }; static dfa dfas[6] = { - {256, "MSTART", 0, 2, states_0, - "\070\000\000"}, - {257, "RULE", 0, 5, states_1, - "\040\000\000"}, - {258, "RHS", 0, 2, states_2, - "\040\010\003"}, - {259, "ALT", 0, 2, states_3, - "\040\010\003"}, - {260, "ITEM", 0, 5, states_4, - "\040\010\003"}, - {261, "ATOM", 0, 4, states_5, - "\040\000\003"}, + {256, "MSTART", 0, 2, states_0, + "\070\000\000"}, + {257, "RULE", 0, 5, states_1, + "\040\000\000"}, + {258, "RHS", 0, 2, states_2, + "\040\010\003"}, + {259, "ALT", 0, 2, states_3, + "\040\010\003"}, + {260, "ITEM", 0, 5, states_4, + "\040\010\003"}, + {261, "ATOM", 0, 4, states_5, + "\040\000\003"}, }; static label labels[19] = { - {0, "EMPTY"}, - {256, 0}, - {257, 0}, - {4, 0}, - {0, 0}, - {1, 0}, - {11, 0}, - {258, 0}, - {259, 0}, - {18, 0}, - {260, 0}, - {9, 0}, - {10, 0}, - {261, 0}, - {16, 0}, - {14, 0}, - {3, 0}, - {7, 0}, - {8, 0}, + {0, "EMPTY"}, + {256, 0}, + {257, 0}, + {4, 0}, + {0, 0}, + {1, 0}, + {11, 0}, + {258, 0}, + {259, 0}, + {18, 0}, + {260, 0}, + {9, 0}, + {10, 0}, + {261, 0}, + {16, 0}, + {14, 0}, + {3, 0}, + {7, 0}, + {8, 0}, }; static grammar _PyParser_Grammar = { - 6, - dfas, - {19, labels}, - 256 + 6, + dfas, + {19, labels}, + 256 }; grammar * meta_grammar(void) { - return &_PyParser_Grammar; + return &_PyParser_Grammar; } grammar * Modified: python/branches/py3k/Parser/myreadline.c ============================================================================== --- python/branches/py3k/Parser/myreadline.c (original) +++ python/branches/py3k/Parser/myreadline.c Sun May 9 17:52:27 2010 @@ -35,64 +35,64 @@ static int my_fgets(char *buf, int len, FILE *fp) { - char *p; - if (PyOS_InputHook != NULL) - (void)(PyOS_InputHook)(); - errno = 0; - p = fgets(buf, len, fp); - if (p != NULL) - return 0; /* No error */ + char *p; + if (PyOS_InputHook != NULL) + (void)(PyOS_InputHook)(); + errno = 0; + p = fgets(buf, len, fp); + if (p != NULL) + return 0; /* No error */ #ifdef MS_WINDOWS - /* In the case of a Ctrl+C or some other external event - interrupting the operation: - Win2k/NT: ERROR_OPERATION_ABORTED is the most recent Win32 - error code (and feof() returns TRUE). - Win9x: Ctrl+C seems to have no effect on fgets() returning - early - the signal handler is called, but the fgets() - only returns "normally" (ie, when Enter hit or feof()) - */ - if (GetLastError()==ERROR_OPERATION_ABORTED) { - /* Signals come asynchronously, so we sleep a brief - moment before checking if the handler has been - triggered (we cant just return 1 before the - signal handler has been called, as the later - signal may be treated as a separate interrupt). - */ - Sleep(1); - if (PyOS_InterruptOccurred()) { - return 1; /* Interrupt */ - } - /* Either the sleep wasn't long enough (need a - short loop retrying?) or not interrupted at all - (in which case we should revisit the whole thing!) - Logging some warning would be nice. assert is not - viable as under the debugger, the various dialogs - mean the condition is not true. - */ - } + /* In the case of a Ctrl+C or some other external event + interrupting the operation: + Win2k/NT: ERROR_OPERATION_ABORTED is the most recent Win32 + error code (and feof() returns TRUE). + Win9x: Ctrl+C seems to have no effect on fgets() returning + early - the signal handler is called, but the fgets() + only returns "normally" (ie, when Enter hit or feof()) + */ + if (GetLastError()==ERROR_OPERATION_ABORTED) { + /* Signals come asynchronously, so we sleep a brief + moment before checking if the handler has been + triggered (we cant just return 1 before the + signal handler has been called, as the later + signal may be treated as a separate interrupt). + */ + Sleep(1); + if (PyOS_InterruptOccurred()) { + return 1; /* Interrupt */ + } + /* Either the sleep wasn't long enough (need a + short loop retrying?) or not interrupted at all + (in which case we should revisit the whole thing!) + Logging some warning would be nice. assert is not + viable as under the debugger, the various dialogs + mean the condition is not true. + */ + } #endif /* MS_WINDOWS */ - if (feof(fp)) { - return -1; /* EOF */ - } + if (feof(fp)) { + return -1; /* EOF */ + } #ifdef EINTR - if (errno == EINTR) { - int s; + if (errno == EINTR) { + int s; #ifdef WITH_THREAD - PyEval_RestoreThread(_PyOS_ReadlineTState); + PyEval_RestoreThread(_PyOS_ReadlineTState); #endif - s = PyErr_CheckSignals(); + s = PyErr_CheckSignals(); #ifdef WITH_THREAD - PyEval_SaveThread(); + PyEval_SaveThread(); #endif - if (s < 0) { - return 1; - } - } -#endif - if (PyOS_InterruptOccurred()) { - return 1; /* Interrupt */ - } - return -2; /* Error */ + if (s < 0) { + return 1; + } + } +#endif + if (PyOS_InterruptOccurred()) { + return 1; /* Interrupt */ + } + return -2; /* Error */ } @@ -101,41 +101,41 @@ char * PyOS_StdioReadline(FILE *sys_stdin, FILE *sys_stdout, char *prompt) { - size_t n; - char *p; - n = 100; - if ((p = (char *)PyMem_MALLOC(n)) == NULL) - return NULL; - fflush(sys_stdout); - if (prompt) - fprintf(stderr, "%s", prompt); - fflush(stderr); - switch (my_fgets(p, (int)n, sys_stdin)) { - case 0: /* Normal case */ - break; - case 1: /* Interrupt */ - PyMem_FREE(p); - return NULL; - case -1: /* EOF */ - case -2: /* Error */ - default: /* Shouldn't happen */ - *p = '\0'; - break; - } - n = strlen(p); - while (n > 0 && p[n-1] != '\n') { - size_t incr = n+2; - p = (char *)PyMem_REALLOC(p, n + incr); - if (p == NULL) - return NULL; - if (incr > INT_MAX) { - PyErr_SetString(PyExc_OverflowError, "input line too long"); - } - if (my_fgets(p+n, (int)incr, sys_stdin) != 0) - break; - n += strlen(p+n); - } - return (char *)PyMem_REALLOC(p, n+1); + size_t n; + char *p; + n = 100; + if ((p = (char *)PyMem_MALLOC(n)) == NULL) + return NULL; + fflush(sys_stdout); + if (prompt) + fprintf(stderr, "%s", prompt); + fflush(stderr); + switch (my_fgets(p, (int)n, sys_stdin)) { + case 0: /* Normal case */ + break; + case 1: /* Interrupt */ + PyMem_FREE(p); + return NULL; + case -1: /* EOF */ + case -2: /* Error */ + default: /* Shouldn't happen */ + *p = '\0'; + break; + } + n = strlen(p); + while (n > 0 && p[n-1] != '\n') { + size_t incr = n+2; + p = (char *)PyMem_REALLOC(p, n + incr); + if (p == NULL) + return NULL; + if (incr > INT_MAX) { + PyErr_SetString(PyExc_OverflowError, "input line too long"); + } + if (my_fgets(p+n, (int)incr, sys_stdin) != 0) + break; + n += strlen(p+n); + } + return (char *)PyMem_REALLOC(p, n+1); } @@ -152,52 +152,52 @@ char * PyOS_Readline(FILE *sys_stdin, FILE *sys_stdout, char *prompt) { - char *rv; + char *rv; - if (_PyOS_ReadlineTState == PyThreadState_GET()) { - PyErr_SetString(PyExc_RuntimeError, - "can't re-enter readline"); - return NULL; - } - + if (_PyOS_ReadlineTState == PyThreadState_GET()) { + PyErr_SetString(PyExc_RuntimeError, + "can't re-enter readline"); + return NULL; + } - if (PyOS_ReadlineFunctionPointer == NULL) { + + if (PyOS_ReadlineFunctionPointer == NULL) { #ifdef __VMS - PyOS_ReadlineFunctionPointer = vms__StdioReadline; + PyOS_ReadlineFunctionPointer = vms__StdioReadline; #else - PyOS_ReadlineFunctionPointer = PyOS_StdioReadline; + PyOS_ReadlineFunctionPointer = PyOS_StdioReadline; #endif - } - + } + #ifdef WITH_THREAD - if (_PyOS_ReadlineLock == NULL) { - _PyOS_ReadlineLock = PyThread_allocate_lock(); - } + if (_PyOS_ReadlineLock == NULL) { + _PyOS_ReadlineLock = PyThread_allocate_lock(); + } #endif - _PyOS_ReadlineTState = PyThreadState_GET(); - Py_BEGIN_ALLOW_THREADS + _PyOS_ReadlineTState = PyThreadState_GET(); + Py_BEGIN_ALLOW_THREADS #ifdef WITH_THREAD - PyThread_acquire_lock(_PyOS_ReadlineLock, 1); + PyThread_acquire_lock(_PyOS_ReadlineLock, 1); #endif - /* This is needed to handle the unlikely case that the - * interpreter is in interactive mode *and* stdin/out are not - * a tty. This can happen, for example if python is run like - * this: python -i < test1.py - */ - if (!isatty (fileno (sys_stdin)) || !isatty (fileno (sys_stdout))) - rv = PyOS_StdioReadline (sys_stdin, sys_stdout, prompt); - else - rv = (*PyOS_ReadlineFunctionPointer)(sys_stdin, sys_stdout, - prompt); - Py_END_ALLOW_THREADS + /* This is needed to handle the unlikely case that the + * interpreter is in interactive mode *and* stdin/out are not + * a tty. This can happen, for example if python is run like + * this: python -i < test1.py + */ + if (!isatty (fileno (sys_stdin)) || !isatty (fileno (sys_stdout))) + rv = PyOS_StdioReadline (sys_stdin, sys_stdout, prompt); + else + rv = (*PyOS_ReadlineFunctionPointer)(sys_stdin, sys_stdout, + prompt); + Py_END_ALLOW_THREADS #ifdef WITH_THREAD - PyThread_release_lock(_PyOS_ReadlineLock); + PyThread_release_lock(_PyOS_ReadlineLock); #endif - _PyOS_ReadlineTState = NULL; + _PyOS_ReadlineTState = NULL; - return rv; + return rv; } Modified: python/branches/py3k/Parser/node.c ============================================================================== --- python/branches/py3k/Parser/node.c (original) +++ python/branches/py3k/Parser/node.c Sun May 9 17:52:27 2010 @@ -7,30 +7,30 @@ node * PyNode_New(int type) { - node *n = (node *) PyObject_MALLOC(1 * sizeof(node)); - if (n == NULL) - return NULL; - n->n_type = type; - n->n_str = NULL; - n->n_lineno = 0; - n->n_nchildren = 0; - n->n_child = NULL; - return n; + node *n = (node *) PyObject_MALLOC(1 * sizeof(node)); + if (n == NULL) + return NULL; + n->n_type = type; + n->n_str = NULL; + n->n_lineno = 0; + n->n_nchildren = 0; + n->n_child = NULL; + return n; } /* See comments at XXXROUNDUP below. Returns -1 on overflow. */ static int fancy_roundup(int n) { - /* Round up to the closest power of 2 >= n. */ - int result = 256; - assert(n > 128); - while (result < n) { - result <<= 1; - if (result <= 0) - return -1; - } - return result; + /* Round up to the closest power of 2 >= n. */ + int result = 256; + assert(n > 128); + while (result < n) { + result <<= 1; + if (result <= 0) + return -1; + } + return result; } /* A gimmick to make massive numbers of reallocs quicker. The result is @@ -70,46 +70,46 @@ * Note that this would be straightforward if a node stored its current * capacity. The code is tricky to avoid that. */ -#define XXXROUNDUP(n) ((n) <= 1 ? (n) : \ - (n) <= 128 ? (((n) + 3) & ~3) : \ - fancy_roundup(n)) +#define XXXROUNDUP(n) ((n) <= 1 ? (n) : \ + (n) <= 128 ? (((n) + 3) & ~3) : \ + fancy_roundup(n)) int PyNode_AddChild(register node *n1, int type, char *str, int lineno, int col_offset) { - const int nch = n1->n_nchildren; - int current_capacity; - int required_capacity; - node *n; - - if (nch == INT_MAX || nch < 0) - return E_OVERFLOW; - - current_capacity = XXXROUNDUP(nch); - required_capacity = XXXROUNDUP(nch + 1); - if (current_capacity < 0 || required_capacity < 0) - return E_OVERFLOW; - if (current_capacity < required_capacity) { - if (required_capacity > PY_SIZE_MAX / sizeof(node)) { - return E_NOMEM; - } - n = n1->n_child; - n = (node *) PyObject_REALLOC(n, - required_capacity * sizeof(node)); - if (n == NULL) - return E_NOMEM; - n1->n_child = n; - } - - n = &n1->n_child[n1->n_nchildren++]; - n->n_type = type; - n->n_str = str; - n->n_lineno = lineno; - n->n_col_offset = col_offset; - n->n_nchildren = 0; - n->n_child = NULL; - return 0; + const int nch = n1->n_nchildren; + int current_capacity; + int required_capacity; + node *n; + + if (nch == INT_MAX || nch < 0) + return E_OVERFLOW; + + current_capacity = XXXROUNDUP(nch); + required_capacity = XXXROUNDUP(nch + 1); + if (current_capacity < 0 || required_capacity < 0) + return E_OVERFLOW; + if (current_capacity < required_capacity) { + if (required_capacity > PY_SIZE_MAX / sizeof(node)) { + return E_NOMEM; + } + n = n1->n_child; + n = (node *) PyObject_REALLOC(n, + required_capacity * sizeof(node)); + if (n == NULL) + return E_NOMEM; + n1->n_child = n; + } + + n = &n1->n_child[n1->n_nchildren++]; + n->n_type = type; + n->n_str = str; + n->n_lineno = lineno; + n->n_col_offset = col_offset; + n->n_nchildren = 0; + n->n_child = NULL; + return 0; } /* Forward */ @@ -119,20 +119,20 @@ void PyNode_Free(node *n) { - if (n != NULL) { - freechildren(n); - PyObject_FREE(n); - } + if (n != NULL) { + freechildren(n); + PyObject_FREE(n); + } } static void freechildren(node *n) { - int i; - for (i = NCH(n); --i >= 0; ) - freechildren(CHILD(n, i)); - if (n->n_child != NULL) - PyObject_FREE(n->n_child); - if (STR(n) != NULL) - PyObject_FREE(STR(n)); + int i; + for (i = NCH(n); --i >= 0; ) + freechildren(CHILD(n, i)); + if (n->n_child != NULL) + PyObject_FREE(n->n_child); + if (STR(n) != NULL) + PyObject_FREE(STR(n)); } Modified: python/branches/py3k/Parser/parser.c ============================================================================== --- python/branches/py3k/Parser/parser.c (original) +++ python/branches/py3k/Parser/parser.c Sun May 9 17:52:27 2010 @@ -29,7 +29,7 @@ static void s_reset(stack *s) { - s->s_top = &s->s_base[MAXSTACK]; + s->s_top = &s->s_base[MAXSTACK]; } #define s_empty(s) ((s)->s_top == &(s)->s_base[MAXSTACK]) @@ -37,16 +37,16 @@ static int s_push(register stack *s, dfa *d, node *parent) { - register stackentry *top; - if (s->s_top == s->s_base) { - fprintf(stderr, "s_push: parser stack overflow\n"); - return E_NOMEM; - } - top = --s->s_top; - top->s_dfa = d; - top->s_parent = parent; - top->s_state = 0; - return 0; + register stackentry *top; + if (s->s_top == s->s_base) { + fprintf(stderr, "s_push: parser stack overflow\n"); + return E_NOMEM; + } + top = --s->s_top; + top->s_dfa = d; + top->s_parent = parent; + top->s_state = 0; + return 0; } #ifdef Py_DEBUG @@ -54,9 +54,9 @@ static void s_pop(register stack *s) { - if (s_empty(s)) - Py_FatalError("s_pop: parser stack underflow -- FATAL"); - s->s_top++; + if (s_empty(s)) + Py_FatalError("s_pop: parser stack underflow -- FATAL"); + s->s_top++; } #else /* !Py_DEBUG */ @@ -71,34 +71,34 @@ parser_state * PyParser_New(grammar *g, int start) { - parser_state *ps; - - if (!g->g_accel) - PyGrammar_AddAccelerators(g); - ps = (parser_state *)PyMem_MALLOC(sizeof(parser_state)); - if (ps == NULL) - return NULL; - ps->p_grammar = g; + parser_state *ps; + + if (!g->g_accel) + PyGrammar_AddAccelerators(g); + ps = (parser_state *)PyMem_MALLOC(sizeof(parser_state)); + if (ps == NULL) + return NULL; + ps->p_grammar = g; #ifdef PY_PARSER_REQUIRES_FUTURE_KEYWORD - ps->p_flags = 0; + ps->p_flags = 0; #endif - ps->p_tree = PyNode_New(start); - if (ps->p_tree == NULL) { - PyMem_FREE(ps); - return NULL; - } - s_reset(&ps->p_stack); - (void) s_push(&ps->p_stack, PyGrammar_FindDFA(g, start), ps->p_tree); - return ps; + ps->p_tree = PyNode_New(start); + if (ps->p_tree == NULL) { + PyMem_FREE(ps); + return NULL; + } + s_reset(&ps->p_stack); + (void) s_push(&ps->p_stack, PyGrammar_FindDFA(g, start), ps->p_tree); + return ps; } void PyParser_Delete(parser_state *ps) { - /* NB If you want to save the parse tree, - you must set p_tree to NULL before calling delparser! */ - PyNode_Free(ps->p_tree); - PyMem_FREE(ps); + /* NB If you want to save the parse tree, + you must set p_tree to NULL before calling delparser! */ + PyNode_Free(ps->p_tree); + PyMem_FREE(ps); } @@ -107,27 +107,27 @@ static int shift(register stack *s, int type, char *str, int newstate, int lineno, int col_offset) { - int err; - assert(!s_empty(s)); - err = PyNode_AddChild(s->s_top->s_parent, type, str, lineno, col_offset); - if (err) - return err; - s->s_top->s_state = newstate; - return 0; + int err; + assert(!s_empty(s)); + err = PyNode_AddChild(s->s_top->s_parent, type, str, lineno, col_offset); + if (err) + return err; + s->s_top->s_state = newstate; + return 0; } static int push(register stack *s, int type, dfa *d, int newstate, int lineno, int col_offset) { - int err; - register node *n; - n = s->s_top->s_parent; - assert(!s_empty(s)); - err = PyNode_AddChild(n, type, (char *)NULL, lineno, col_offset); - if (err) - return err; - s->s_top->s_state = newstate; - return s_push(s, d, CHILD(n, NCH(n)-1)); + int err; + register node *n; + n = s->s_top->s_parent; + assert(!s_empty(s)); + err = PyNode_AddChild(n, type, (char *)NULL, lineno, col_offset); + if (err) + return err; + s->s_top->s_state = newstate; + return s_push(s, d, CHILD(n, NCH(n)-1)); } @@ -136,47 +136,47 @@ static int classify(parser_state *ps, int type, char *str) { - grammar *g = ps->p_grammar; - register int n = g->g_ll.ll_nlabels; - - if (type == NAME) { - register char *s = str; - register label *l = g->g_ll.ll_label; - register int i; - for (i = n; i > 0; i--, l++) { - if (l->lb_type != NAME || l->lb_str == NULL || - l->lb_str[0] != s[0] || - strcmp(l->lb_str, s) != 0) - continue; + grammar *g = ps->p_grammar; + register int n = g->g_ll.ll_nlabels; + + if (type == NAME) { + register char *s = str; + register label *l = g->g_ll.ll_label; + register int i; + for (i = n; i > 0; i--, l++) { + if (l->lb_type != NAME || l->lb_str == NULL || + l->lb_str[0] != s[0] || + strcmp(l->lb_str, s) != 0) + continue; #ifdef PY_PARSER_REQUIRES_FUTURE_KEYWORD #if 0 - /* Leaving this in as an example */ - if (!(ps->p_flags & CO_FUTURE_WITH_STATEMENT)) { - if (s[0] == 'w' && strcmp(s, "with") == 0) - break; /* not a keyword yet */ - else if (s[0] == 'a' && strcmp(s, "as") == 0) - break; /* not a keyword yet */ - } + /* Leaving this in as an example */ + if (!(ps->p_flags & CO_FUTURE_WITH_STATEMENT)) { + if (s[0] == 'w' && strcmp(s, "with") == 0) + break; /* not a keyword yet */ + else if (s[0] == 'a' && strcmp(s, "as") == 0) + break; /* not a keyword yet */ + } #endif #endif - D(printf("It's a keyword\n")); - return n - i; - } - } - - { - register label *l = g->g_ll.ll_label; - register int i; - for (i = n; i > 0; i--, l++) { - if (l->lb_type == type && l->lb_str == NULL) { - D(printf("It's a token we know\n")); - return n - i; - } - } - } - - D(printf("Illegal token\n")); - return -1; + D(printf("It's a keyword\n")); + return n - i; + } + } + + { + register label *l = g->g_ll.ll_label; + register int i; + for (i = n; i > 0; i--, l++) { + if (l->lb_type == type && l->lb_str == NULL) { + D(printf("It's a token we know\n")); + return n - i; + } + } + } + + D(printf("Illegal token\n")); + return -1; } #ifdef PY_PARSER_REQUIRES_FUTURE_KEYWORD @@ -185,152 +185,152 @@ static void future_hack(parser_state *ps) { - node *n = ps->p_stack.s_top->s_parent; - node *ch, *cch; - int i; - - /* from __future__ import ..., must have at least 4 children */ - n = CHILD(n, 0); - if (NCH(n) < 4) - return; - ch = CHILD(n, 0); - if (STR(ch) == NULL || strcmp(STR(ch), "from") != 0) - return; - ch = CHILD(n, 1); - if (NCH(ch) == 1 && STR(CHILD(ch, 0)) && - strcmp(STR(CHILD(ch, 0)), "__future__") != 0) - return; - ch = CHILD(n, 3); - /* ch can be a star, a parenthesis or import_as_names */ - if (TYPE(ch) == STAR) - return; - if (TYPE(ch) == LPAR) - ch = CHILD(n, 4); - - for (i = 0; i < NCH(ch); i += 2) { - cch = CHILD(ch, i); - if (NCH(cch) >= 1 && TYPE(CHILD(cch, 0)) == NAME) { - char *str_ch = STR(CHILD(cch, 0)); - if (strcmp(str_ch, FUTURE_WITH_STATEMENT) == 0) { - ps->p_flags |= CO_FUTURE_WITH_STATEMENT; - } else if (strcmp(str_ch, FUTURE_PRINT_FUNCTION) == 0) { - ps->p_flags |= CO_FUTURE_PRINT_FUNCTION; - } else if (strcmp(str_ch, FUTURE_UNICODE_LITERALS) == 0) { - ps->p_flags |= CO_FUTURE_UNICODE_LITERALS; - } - } - } + node *n = ps->p_stack.s_top->s_parent; + node *ch, *cch; + int i; + + /* from __future__ import ..., must have at least 4 children */ + n = CHILD(n, 0); + if (NCH(n) < 4) + return; + ch = CHILD(n, 0); + if (STR(ch) == NULL || strcmp(STR(ch), "from") != 0) + return; + ch = CHILD(n, 1); + if (NCH(ch) == 1 && STR(CHILD(ch, 0)) && + strcmp(STR(CHILD(ch, 0)), "__future__") != 0) + return; + ch = CHILD(n, 3); + /* ch can be a star, a parenthesis or import_as_names */ + if (TYPE(ch) == STAR) + return; + if (TYPE(ch) == LPAR) + ch = CHILD(n, 4); + + for (i = 0; i < NCH(ch); i += 2) { + cch = CHILD(ch, i); + if (NCH(cch) >= 1 && TYPE(CHILD(cch, 0)) == NAME) { + char *str_ch = STR(CHILD(cch, 0)); + if (strcmp(str_ch, FUTURE_WITH_STATEMENT) == 0) { + ps->p_flags |= CO_FUTURE_WITH_STATEMENT; + } else if (strcmp(str_ch, FUTURE_PRINT_FUNCTION) == 0) { + ps->p_flags |= CO_FUTURE_PRINT_FUNCTION; + } else if (strcmp(str_ch, FUTURE_UNICODE_LITERALS) == 0) { + ps->p_flags |= CO_FUTURE_UNICODE_LITERALS; + } + } + } } #endif #endif /* future keyword */ int PyParser_AddToken(register parser_state *ps, register int type, char *str, - int lineno, int col_offset, int *expected_ret) + int lineno, int col_offset, int *expected_ret) { - register int ilabel; - int err; - - D(printf("Token %s/'%s' ... ", _PyParser_TokenNames[type], str)); - - /* Find out which label this token is */ - ilabel = classify(ps, type, str); - if (ilabel < 0) - return E_SYNTAX; - - /* Loop until the token is shifted or an error occurred */ - for (;;) { - /* Fetch the current dfa and state */ - register dfa *d = ps->p_stack.s_top->s_dfa; - register state *s = &d->d_state[ps->p_stack.s_top->s_state]; - - D(printf(" DFA '%s', state %d:", - d->d_name, ps->p_stack.s_top->s_state)); - - /* Check accelerator */ - if (s->s_lower <= ilabel && ilabel < s->s_upper) { - register int x = s->s_accel[ilabel - s->s_lower]; - if (x != -1) { - if (x & (1<<7)) { - /* Push non-terminal */ - int nt = (x >> 8) + NT_OFFSET; - int arrow = x & ((1<<7)-1); - dfa *d1 = PyGrammar_FindDFA( - ps->p_grammar, nt); - if ((err = push(&ps->p_stack, nt, d1, - arrow, lineno, col_offset)) > 0) { - D(printf(" MemError: push\n")); - return err; - } - D(printf(" Push ...\n")); - continue; - } - - /* Shift the token */ - if ((err = shift(&ps->p_stack, type, str, - x, lineno, col_offset)) > 0) { - D(printf(" MemError: shift.\n")); - return err; - } - D(printf(" Shift.\n")); - /* Pop while we are in an accept-only state */ - while (s = &d->d_state - [ps->p_stack.s_top->s_state], - s->s_accept && s->s_narcs == 1) { - D(printf(" DFA '%s', state %d: " - "Direct pop.\n", - d->d_name, - ps->p_stack.s_top->s_state)); + register int ilabel; + int err; + + D(printf("Token %s/'%s' ... ", _PyParser_TokenNames[type], str)); + + /* Find out which label this token is */ + ilabel = classify(ps, type, str); + if (ilabel < 0) + return E_SYNTAX; + + /* Loop until the token is shifted or an error occurred */ + for (;;) { + /* Fetch the current dfa and state */ + register dfa *d = ps->p_stack.s_top->s_dfa; + register state *s = &d->d_state[ps->p_stack.s_top->s_state]; + + D(printf(" DFA '%s', state %d:", + d->d_name, ps->p_stack.s_top->s_state)); + + /* Check accelerator */ + if (s->s_lower <= ilabel && ilabel < s->s_upper) { + register int x = s->s_accel[ilabel - s->s_lower]; + if (x != -1) { + if (x & (1<<7)) { + /* Push non-terminal */ + int nt = (x >> 8) + NT_OFFSET; + int arrow = x & ((1<<7)-1); + dfa *d1 = PyGrammar_FindDFA( + ps->p_grammar, nt); + if ((err = push(&ps->p_stack, nt, d1, + arrow, lineno, col_offset)) > 0) { + D(printf(" MemError: push\n")); + return err; + } + D(printf(" Push ...\n")); + continue; + } + + /* Shift the token */ + if ((err = shift(&ps->p_stack, type, str, + x, lineno, col_offset)) > 0) { + D(printf(" MemError: shift.\n")); + return err; + } + D(printf(" Shift.\n")); + /* Pop while we are in an accept-only state */ + while (s = &d->d_state + [ps->p_stack.s_top->s_state], + s->s_accept && s->s_narcs == 1) { + D(printf(" DFA '%s', state %d: " + "Direct pop.\n", + d->d_name, + ps->p_stack.s_top->s_state)); #ifdef PY_PARSER_REQUIRES_FUTURE_KEYWORD #if 0 - if (d->d_name[0] == 'i' && - strcmp(d->d_name, - "import_stmt") == 0) - future_hack(ps); + if (d->d_name[0] == 'i' && + strcmp(d->d_name, + "import_stmt") == 0) + future_hack(ps); #endif #endif - s_pop(&ps->p_stack); - if (s_empty(&ps->p_stack)) { - D(printf(" ACCEPT.\n")); - return E_DONE; - } - d = ps->p_stack.s_top->s_dfa; - } - return E_OK; - } - } - - if (s->s_accept) { + s_pop(&ps->p_stack); + if (s_empty(&ps->p_stack)) { + D(printf(" ACCEPT.\n")); + return E_DONE; + } + d = ps->p_stack.s_top->s_dfa; + } + return E_OK; + } + } + + if (s->s_accept) { #ifdef PY_PARSER_REQUIRES_FUTURE_KEYWORD #if 0 - if (d->d_name[0] == 'i' && - strcmp(d->d_name, "import_stmt") == 0) - future_hack(ps); + if (d->d_name[0] == 'i' && + strcmp(d->d_name, "import_stmt") == 0) + future_hack(ps); #endif #endif - /* Pop this dfa and try again */ - s_pop(&ps->p_stack); - D(printf(" Pop ...\n")); - if (s_empty(&ps->p_stack)) { - D(printf(" Error: bottom of stack.\n")); - return E_SYNTAX; - } - continue; - } - - /* Stuck, report syntax error */ - D(printf(" Error.\n")); - if (expected_ret) { - if (s->s_lower == s->s_upper - 1) { - /* Only one possible expected token */ - *expected_ret = ps->p_grammar-> - g_ll.ll_label[s->s_lower].lb_type; - } - else - *expected_ret = -1; - } - return E_SYNTAX; - } + /* Pop this dfa and try again */ + s_pop(&ps->p_stack); + D(printf(" Pop ...\n")); + if (s_empty(&ps->p_stack)) { + D(printf(" Error: bottom of stack.\n")); + return E_SYNTAX; + } + continue; + } + + /* Stuck, report syntax error */ + D(printf(" Error.\n")); + if (expected_ret) { + if (s->s_lower == s->s_upper - 1) { + /* Only one possible expected token */ + *expected_ret = ps->p_grammar-> + g_ll.ll_label[s->s_lower].lb_type; + } + else + *expected_ret = -1; + } + return E_SYNTAX; + } } @@ -341,62 +341,62 @@ void dumptree(grammar *g, node *n) { - int i; - - if (n == NULL) - printf("NIL"); - else { - label l; - l.lb_type = TYPE(n); - l.lb_str = STR(n); - printf("%s", PyGrammar_LabelRepr(&l)); - if (ISNONTERMINAL(TYPE(n))) { - printf("("); - for (i = 0; i < NCH(n); i++) { - if (i > 0) - printf(","); - dumptree(g, CHILD(n, i)); - } - printf(")"); - } - } + int i; + + if (n == NULL) + printf("NIL"); + else { + label l; + l.lb_type = TYPE(n); + l.lb_str = STR(n); + printf("%s", PyGrammar_LabelRepr(&l)); + if (ISNONTERMINAL(TYPE(n))) { + printf("("); + for (i = 0; i < NCH(n); i++) { + if (i > 0) + printf(","); + dumptree(g, CHILD(n, i)); + } + printf(")"); + } + } } void showtree(grammar *g, node *n) { - int i; - - if (n == NULL) - return; - if (ISNONTERMINAL(TYPE(n))) { - for (i = 0; i < NCH(n); i++) - showtree(g, CHILD(n, i)); - } - else if (ISTERMINAL(TYPE(n))) { - printf("%s", _PyParser_TokenNames[TYPE(n)]); - if (TYPE(n) == NUMBER || TYPE(n) == NAME) - printf("(%s)", STR(n)); - printf(" "); - } - else - printf("? "); + int i; + + if (n == NULL) + return; + if (ISNONTERMINAL(TYPE(n))) { + for (i = 0; i < NCH(n); i++) + showtree(g, CHILD(n, i)); + } + else if (ISTERMINAL(TYPE(n))) { + printf("%s", _PyParser_TokenNames[TYPE(n)]); + if (TYPE(n) == NUMBER || TYPE(n) == NAME) + printf("(%s)", STR(n)); + printf(" "); + } + else + printf("? "); } void printtree(parser_state *ps) { - if (Py_DebugFlag) { - printf("Parse tree:\n"); - dumptree(ps->p_grammar, ps->p_tree); - printf("\n"); - printf("Tokens:\n"); - showtree(ps->p_grammar, ps->p_tree); - printf("\n"); - } - printf("Listing:\n"); - PyNode_ListTree(ps->p_tree); - printf("\n"); + if (Py_DebugFlag) { + printf("Parse tree:\n"); + dumptree(ps->p_grammar, ps->p_tree); + printf("\n"); + printf("Tokens:\n"); + showtree(ps->p_grammar, ps->p_tree); + printf("\n"); + } + printf("Listing:\n"); + PyNode_ListTree(ps->p_tree); + printf("\n"); } #endif /* Py_DEBUG */ @@ -431,15 +431,15 @@ As an example, consider this grammar: -expr: term (OP term)* -term: CONSTANT | '(' expr ')' +expr: term (OP term)* +term: CONSTANT | '(' expr ')' The DFA corresponding to the rule for expr is: ------->.---term-->.-------> - ^ | - | | - \----OP----/ + ^ | + | | + \----OP----/ The parse tree generated for the input a+b is: Modified: python/branches/py3k/Parser/parsetok.c ============================================================================== --- python/branches/py3k/Parser/parsetok.c (original) +++ python/branches/py3k/Parser/parsetok.c Sun May 9 17:52:27 2010 @@ -19,85 +19,85 @@ node * PyParser_ParseString(const char *s, grammar *g, int start, perrdetail *err_ret) { - return PyParser_ParseStringFlagsFilename(s, NULL, g, start, err_ret, 0); + return PyParser_ParseStringFlagsFilename(s, NULL, g, start, err_ret, 0); } node * PyParser_ParseStringFlags(const char *s, grammar *g, int start, - perrdetail *err_ret, int flags) + perrdetail *err_ret, int flags) { - return PyParser_ParseStringFlagsFilename(s, NULL, - g, start, err_ret, flags); + return PyParser_ParseStringFlagsFilename(s, NULL, + g, start, err_ret, flags); } node * PyParser_ParseStringFlagsFilename(const char *s, const char *filename, - grammar *g, int start, - perrdetail *err_ret, int flags) + grammar *g, int start, + perrdetail *err_ret, int flags) { - int iflags = flags; - return PyParser_ParseStringFlagsFilenameEx(s, filename, g, start, - err_ret, &iflags); + int iflags = flags; + return PyParser_ParseStringFlagsFilenameEx(s, filename, g, start, + err_ret, &iflags); } node * PyParser_ParseStringFlagsFilenameEx(const char *s, const char *filename, - grammar *g, int start, - perrdetail *err_ret, int *flags) + grammar *g, int start, + perrdetail *err_ret, int *flags) { - struct tok_state *tok; - int exec_input = start == file_input; + struct tok_state *tok; + int exec_input = start == file_input; - initerr(err_ret, filename); + initerr(err_ret, filename); - if (*flags & PyPARSE_IGNORE_COOKIE) - tok = PyTokenizer_FromUTF8(s, exec_input); - else - tok = PyTokenizer_FromString(s, exec_input); - if (tok == NULL) { - err_ret->error = PyErr_Occurred() ? E_DECODE : E_NOMEM; - return NULL; - } + if (*flags & PyPARSE_IGNORE_COOKIE) + tok = PyTokenizer_FromUTF8(s, exec_input); + else + tok = PyTokenizer_FromString(s, exec_input); + if (tok == NULL) { + err_ret->error = PyErr_Occurred() ? E_DECODE : E_NOMEM; + return NULL; + } - tok->filename = filename ? filename : ""; - return parsetok(tok, g, start, err_ret, flags); + tok->filename = filename ? filename : ""; + return parsetok(tok, g, start, err_ret, flags); } /* Parse input coming from a file. Return error code, print some errors. */ node * PyParser_ParseFile(FILE *fp, const char *filename, grammar *g, int start, - char *ps1, char *ps2, perrdetail *err_ret) + char *ps1, char *ps2, perrdetail *err_ret) { - return PyParser_ParseFileFlags(fp, filename, NULL, - g, start, ps1, ps2, err_ret, 0); + return PyParser_ParseFileFlags(fp, filename, NULL, + g, start, ps1, ps2, err_ret, 0); } node * PyParser_ParseFileFlags(FILE *fp, const char *filename, const char *enc, - grammar *g, int start, - char *ps1, char *ps2, perrdetail *err_ret, int flags) + grammar *g, int start, + char *ps1, char *ps2, perrdetail *err_ret, int flags) { - int iflags = flags; - return PyParser_ParseFileFlagsEx(fp, filename, enc, g, start, ps1, - ps2, err_ret, &iflags); + int iflags = flags; + return PyParser_ParseFileFlagsEx(fp, filename, enc, g, start, ps1, + ps2, err_ret, &iflags); } node * -PyParser_ParseFileFlagsEx(FILE *fp, const char *filename, - const char *enc, grammar *g, int start, - char *ps1, char *ps2, perrdetail *err_ret, int *flags) +PyParser_ParseFileFlagsEx(FILE *fp, const char *filename, + const char *enc, grammar *g, int start, + char *ps1, char *ps2, perrdetail *err_ret, int *flags) { - struct tok_state *tok; + struct tok_state *tok; - initerr(err_ret, filename); + initerr(err_ret, filename); - if ((tok = PyTokenizer_FromFile(fp, (char *)enc, ps1, ps2)) == NULL) { - err_ret->error = E_NOMEM; - return NULL; - } - tok->filename = filename; - return parsetok(tok, g, start, err_ret, flags); + if ((tok = PyTokenizer_FromFile(fp, (char *)enc, ps1, ps2)) == NULL) { + err_ret->error = E_NOMEM; + return NULL; + } + tok->filename = filename; + return parsetok(tok, g, start, err_ret, flags); } #ifdef PY_PARSER_REQUIRES_FUTURE_KEYWORD @@ -111,9 +111,9 @@ static void warn(const char *msg, const char *filename, int lineno) { - if (filename == NULL) - filename = ""; - PySys_WriteStderr(msg, filename, lineno); + if (filename == NULL) + filename = ""; + PySys_WriteStderr(msg, filename, lineno); } #endif #endif @@ -123,159 +123,159 @@ static node * parsetok(struct tok_state *tok, grammar *g, int start, perrdetail *err_ret, - int *flags) + int *flags) { - parser_state *ps; - node *n; - int started = 0, handling_import = 0, handling_with = 0; - - if ((ps = PyParser_New(g, start)) == NULL) { - fprintf(stderr, "no mem for new parser\n"); - err_ret->error = E_NOMEM; - PyTokenizer_Free(tok); - return NULL; - } + parser_state *ps; + node *n; + int started = 0, handling_import = 0, handling_with = 0; + + if ((ps = PyParser_New(g, start)) == NULL) { + fprintf(stderr, "no mem for new parser\n"); + err_ret->error = E_NOMEM; + PyTokenizer_Free(tok); + return NULL; + } #ifdef PY_PARSER_REQUIRES_FUTURE_KEYWORD - if (*flags & PyPARSE_BARRY_AS_BDFL) - ps->p_flags |= CO_FUTURE_BARRY_AS_BDFL; + if (*flags & PyPARSE_BARRY_AS_BDFL) + ps->p_flags |= CO_FUTURE_BARRY_AS_BDFL; #endif - for (;;) { - char *a, *b; - int type; - size_t len; - char *str; - int col_offset; - - type = PyTokenizer_Get(tok, &a, &b); - if (type == ERRORTOKEN) { - err_ret->error = tok->done; - break; - } - if (type == ENDMARKER && started) { - type = NEWLINE; /* Add an extra newline */ - handling_with = handling_import = 0; - started = 0; - /* Add the right number of dedent tokens, - except if a certain flag is given -- - codeop.py uses this. */ - if (tok->indent && - !(*flags & PyPARSE_DONT_IMPLY_DEDENT)) - { - tok->pendin = -tok->indent; - tok->indent = 0; - } - } - else - started = 1; - len = b - a; /* XXX this may compute NULL - NULL */ - str = (char *) PyObject_MALLOC(len + 1); - if (str == NULL) { - fprintf(stderr, "no mem for next token\n"); - err_ret->error = E_NOMEM; - break; - } - if (len > 0) - strncpy(str, a, len); - str[len] = '\0'; + for (;;) { + char *a, *b; + int type; + size_t len; + char *str; + int col_offset; + + type = PyTokenizer_Get(tok, &a, &b); + if (type == ERRORTOKEN) { + err_ret->error = tok->done; + break; + } + if (type == ENDMARKER && started) { + type = NEWLINE; /* Add an extra newline */ + handling_with = handling_import = 0; + started = 0; + /* Add the right number of dedent tokens, + except if a certain flag is given -- + codeop.py uses this. */ + if (tok->indent && + !(*flags & PyPARSE_DONT_IMPLY_DEDENT)) + { + tok->pendin = -tok->indent; + tok->indent = 0; + } + } + else + started = 1; + len = b - a; /* XXX this may compute NULL - NULL */ + str = (char *) PyObject_MALLOC(len + 1); + if (str == NULL) { + fprintf(stderr, "no mem for next token\n"); + err_ret->error = E_NOMEM; + break; + } + if (len > 0) + strncpy(str, a, len); + str[len] = '\0'; #ifdef PY_PARSER_REQUIRES_FUTURE_KEYWORD - if (type == NOTEQUAL) { - if (!(ps->p_flags & CO_FUTURE_BARRY_AS_BDFL) && - strcmp(str, "!=")) { - err_ret->error = E_SYNTAX; - break; - } - else if ((ps->p_flags & CO_FUTURE_BARRY_AS_BDFL) && - strcmp(str, "<>")) { - err_ret->text = "with Barry as BDFL, use '<>' " - "instead of '!='"; - err_ret->error = E_SYNTAX; - break; - } - } + if (type == NOTEQUAL) { + if (!(ps->p_flags & CO_FUTURE_BARRY_AS_BDFL) && + strcmp(str, "!=")) { + err_ret->error = E_SYNTAX; + break; + } + else if ((ps->p_flags & CO_FUTURE_BARRY_AS_BDFL) && + strcmp(str, "<>")) { + err_ret->text = "with Barry as BDFL, use '<>' " + "instead of '!='"; + err_ret->error = E_SYNTAX; + break; + } + } #endif - if (a >= tok->line_start) - col_offset = a - tok->line_start; - else - col_offset = -1; - - if ((err_ret->error = - PyParser_AddToken(ps, (int)type, str, - tok->lineno, col_offset, - &(err_ret->expected))) != E_OK) { - if (err_ret->error != E_DONE) { - PyObject_FREE(str); - err_ret->token = type; - } - break; - } - } - - if (err_ret->error == E_DONE) { - n = ps->p_tree; - ps->p_tree = NULL; - } - else - n = NULL; + if (a >= tok->line_start) + col_offset = a - tok->line_start; + else + col_offset = -1; + + if ((err_ret->error = + PyParser_AddToken(ps, (int)type, str, + tok->lineno, col_offset, + &(err_ret->expected))) != E_OK) { + if (err_ret->error != E_DONE) { + PyObject_FREE(str); + err_ret->token = type; + } + break; + } + } + + if (err_ret->error == E_DONE) { + n = ps->p_tree; + ps->p_tree = NULL; + } + else + n = NULL; #ifdef PY_PARSER_REQUIRES_FUTURE_KEYWORD - *flags = ps->p_flags; + *flags = ps->p_flags; #endif - PyParser_Delete(ps); + PyParser_Delete(ps); - if (n == NULL) { - if (tok->lineno <= 1 && tok->done == E_EOF) - err_ret->error = E_EOF; - err_ret->lineno = tok->lineno; - if (tok->buf != NULL) { - size_t len; - assert(tok->cur - tok->buf < INT_MAX); - err_ret->offset = (int)(tok->cur - tok->buf); - len = tok->inp - tok->buf; - err_ret->text = (char *) PyObject_MALLOC(len + 1); - if (err_ret->text != NULL) { - if (len > 0) - strncpy(err_ret->text, tok->buf, len); - err_ret->text[len] = '\0'; - } - } - } else if (tok->encoding != NULL) { - /* 'nodes->n_str' uses PyObject_*, while 'tok->encoding' was - * allocated using PyMem_ - */ - node* r = PyNode_New(encoding_decl); - if (r) - r->n_str = PyObject_MALLOC(strlen(tok->encoding)+1); - if (!r || !r->n_str) { - err_ret->error = E_NOMEM; - if (r) - PyObject_FREE(r); - n = NULL; - goto done; - } - strcpy(r->n_str, tok->encoding); - PyMem_FREE(tok->encoding); - tok->encoding = NULL; - r->n_nchildren = 1; - r->n_child = n; - n = r; - } + if (n == NULL) { + if (tok->lineno <= 1 && tok->done == E_EOF) + err_ret->error = E_EOF; + err_ret->lineno = tok->lineno; + if (tok->buf != NULL) { + size_t len; + assert(tok->cur - tok->buf < INT_MAX); + err_ret->offset = (int)(tok->cur - tok->buf); + len = tok->inp - tok->buf; + err_ret->text = (char *) PyObject_MALLOC(len + 1); + if (err_ret->text != NULL) { + if (len > 0) + strncpy(err_ret->text, tok->buf, len); + err_ret->text[len] = '\0'; + } + } + } else if (tok->encoding != NULL) { + /* 'nodes->n_str' uses PyObject_*, while 'tok->encoding' was + * allocated using PyMem_ + */ + node* r = PyNode_New(encoding_decl); + if (r) + r->n_str = PyObject_MALLOC(strlen(tok->encoding)+1); + if (!r || !r->n_str) { + err_ret->error = E_NOMEM; + if (r) + PyObject_FREE(r); + n = NULL; + goto done; + } + strcpy(r->n_str, tok->encoding); + PyMem_FREE(tok->encoding); + tok->encoding = NULL; + r->n_nchildren = 1; + r->n_child = n; + n = r; + } done: - PyTokenizer_Free(tok); + PyTokenizer_Free(tok); - return n; + return n; } static void initerr(perrdetail *err_ret, const char *filename) { - err_ret->error = E_OK; - err_ret->filename = filename; - err_ret->lineno = 0; - err_ret->offset = 0; - err_ret->text = NULL; - err_ret->token = -1; - err_ret->expected = -1; + err_ret->error = E_OK; + err_ret->filename = filename; + err_ret->lineno = 0; + err_ret->offset = 0; + err_ret->text = NULL; + err_ret->token = -1; + err_ret->expected = -1; } Modified: python/branches/py3k/Parser/pgen.c ============================================================================== --- python/branches/py3k/Parser/pgen.c (original) +++ python/branches/py3k/Parser/pgen.c Sun May 9 17:52:27 2010 @@ -17,85 +17,85 @@ /* PART ONE -- CONSTRUCT NFA -- Cf. Algorithm 3.2 from [Aho&Ullman 77] */ typedef struct _nfaarc { - int ar_label; - int ar_arrow; + int ar_label; + int ar_arrow; } nfaarc; typedef struct _nfastate { - int st_narcs; - nfaarc *st_arc; + int st_narcs; + nfaarc *st_arc; } nfastate; typedef struct _nfa { - int nf_type; - char *nf_name; - int nf_nstates; - nfastate *nf_state; - int nf_start, nf_finish; + int nf_type; + char *nf_name; + int nf_nstates; + nfastate *nf_state; + int nf_start, nf_finish; } nfa; /* Forward */ static void compile_rhs(labellist *ll, - nfa *nf, node *n, int *pa, int *pb); + nfa *nf, node *n, int *pa, int *pb); static void compile_alt(labellist *ll, - nfa *nf, node *n, int *pa, int *pb); + nfa *nf, node *n, int *pa, int *pb); static void compile_item(labellist *ll, - nfa *nf, node *n, int *pa, int *pb); + nfa *nf, node *n, int *pa, int *pb); static void compile_atom(labellist *ll, - nfa *nf, node *n, int *pa, int *pb); + nfa *nf, node *n, int *pa, int *pb); static int addnfastate(nfa *nf) { - nfastate *st; - - nf->nf_state = (nfastate *)PyObject_REALLOC(nf->nf_state, - sizeof(nfastate) * (nf->nf_nstates + 1)); - if (nf->nf_state == NULL) - Py_FatalError("out of mem"); - st = &nf->nf_state[nf->nf_nstates++]; - st->st_narcs = 0; - st->st_arc = NULL; - return st - nf->nf_state; + nfastate *st; + + nf->nf_state = (nfastate *)PyObject_REALLOC(nf->nf_state, + sizeof(nfastate) * (nf->nf_nstates + 1)); + if (nf->nf_state == NULL) + Py_FatalError("out of mem"); + st = &nf->nf_state[nf->nf_nstates++]; + st->st_narcs = 0; + st->st_arc = NULL; + return st - nf->nf_state; } static void addnfaarc(nfa *nf, int from, int to, int lbl) { - nfastate *st; - nfaarc *ar; - - st = &nf->nf_state[from]; - st->st_arc = (nfaarc *)PyObject_REALLOC(st->st_arc, - sizeof(nfaarc) * (st->st_narcs + 1)); - if (st->st_arc == NULL) - Py_FatalError("out of mem"); - ar = &st->st_arc[st->st_narcs++]; - ar->ar_label = lbl; - ar->ar_arrow = to; + nfastate *st; + nfaarc *ar; + + st = &nf->nf_state[from]; + st->st_arc = (nfaarc *)PyObject_REALLOC(st->st_arc, + sizeof(nfaarc) * (st->st_narcs + 1)); + if (st->st_arc == NULL) + Py_FatalError("out of mem"); + ar = &st->st_arc[st->st_narcs++]; + ar->ar_label = lbl; + ar->ar_arrow = to; } static nfa * newnfa(char *name) { - nfa *nf; - static int type = NT_OFFSET; /* All types will be disjunct */ - - nf = (nfa *)PyObject_MALLOC(sizeof(nfa)); - if (nf == NULL) - Py_FatalError("no mem for new nfa"); - nf->nf_type = type++; - nf->nf_name = name; /* XXX strdup(name) ??? */ - nf->nf_nstates = 0; - nf->nf_state = NULL; - nf->nf_start = nf->nf_finish = -1; - return nf; + nfa *nf; + static int type = NT_OFFSET; /* All types will be disjunct */ + + nf = (nfa *)PyObject_MALLOC(sizeof(nfa)); + if (nf == NULL) + Py_FatalError("no mem for new nfa"); + nf->nf_type = type++; + nf->nf_name = name; /* XXX strdup(name) ??? */ + nf->nf_nstates = 0; + nf->nf_state = NULL; + nf->nf_start = nf->nf_finish = -1; + return nf; } typedef struct _nfagrammar { - int gr_nnfas; - nfa **gr_nfa; - labellist gr_ll; + int gr_nnfas; + nfa **gr_nfa; + labellist gr_ll; } nfagrammar; /* Forward */ @@ -104,32 +104,32 @@ static nfagrammar * newnfagrammar(void) { - nfagrammar *gr; - - gr = (nfagrammar *)PyObject_MALLOC(sizeof(nfagrammar)); - if (gr == NULL) - Py_FatalError("no mem for new nfa grammar"); - gr->gr_nnfas = 0; - gr->gr_nfa = NULL; - gr->gr_ll.ll_nlabels = 0; - gr->gr_ll.ll_label = NULL; - addlabel(&gr->gr_ll, ENDMARKER, "EMPTY"); - return gr; + nfagrammar *gr; + + gr = (nfagrammar *)PyObject_MALLOC(sizeof(nfagrammar)); + if (gr == NULL) + Py_FatalError("no mem for new nfa grammar"); + gr->gr_nnfas = 0; + gr->gr_nfa = NULL; + gr->gr_ll.ll_nlabels = 0; + gr->gr_ll.ll_label = NULL; + addlabel(&gr->gr_ll, ENDMARKER, "EMPTY"); + return gr; } static nfa * addnfa(nfagrammar *gr, char *name) { - nfa *nf; - - nf = newnfa(name); - gr->gr_nfa = (nfa **)PyObject_REALLOC(gr->gr_nfa, - sizeof(nfa*) * (gr->gr_nnfas + 1)); - if (gr->gr_nfa == NULL) - Py_FatalError("out of mem"); - gr->gr_nfa[gr->gr_nnfas++] = nf; - addlabel(&gr->gr_ll, NAME, nf->nf_name); - return nf; + nfa *nf; + + nf = newnfa(name); + gr->gr_nfa = (nfa **)PyObject_REALLOC(gr->gr_nfa, + sizeof(nfa*) * (gr->gr_nnfas + 1)); + if (gr->gr_nfa == NULL) + Py_FatalError("out of mem"); + gr->gr_nfa[gr->gr_nnfas++] = nf; + addlabel(&gr->gr_ll, NAME, nf->nf_name); + return nf; } #ifdef Py_DEBUG @@ -137,203 +137,203 @@ static char REQNFMT[] = "metacompile: less than %d children\n"; #define REQN(i, count) \ - if (i < count) { \ - fprintf(stderr, REQNFMT, count); \ - Py_FatalError("REQN"); \ - } else + if (i < count) { \ + fprintf(stderr, REQNFMT, count); \ + Py_FatalError("REQN"); \ + } else #else -#define REQN(i, count) /* empty */ +#define REQN(i, count) /* empty */ #endif static nfagrammar * metacompile(node *n) { - nfagrammar *gr; - int i; + nfagrammar *gr; + int i; - if (Py_DebugFlag) - printf("Compiling (meta-) parse tree into NFA grammar\n"); - gr = newnfagrammar(); - REQ(n, MSTART); - i = n->n_nchildren - 1; /* Last child is ENDMARKER */ - n = n->n_child; - for (; --i >= 0; n++) { - if (n->n_type != NEWLINE) - compile_rule(gr, n); - } - return gr; + if (Py_DebugFlag) + printf("Compiling (meta-) parse tree into NFA grammar\n"); + gr = newnfagrammar(); + REQ(n, MSTART); + i = n->n_nchildren - 1; /* Last child is ENDMARKER */ + n = n->n_child; + for (; --i >= 0; n++) { + if (n->n_type != NEWLINE) + compile_rule(gr, n); + } + return gr; } static void compile_rule(nfagrammar *gr, node *n) { - nfa *nf; - - REQ(n, RULE); - REQN(n->n_nchildren, 4); - n = n->n_child; - REQ(n, NAME); - nf = addnfa(gr, n->n_str); - n++; - REQ(n, COLON); - n++; - REQ(n, RHS); - compile_rhs(&gr->gr_ll, nf, n, &nf->nf_start, &nf->nf_finish); - n++; - REQ(n, NEWLINE); + nfa *nf; + + REQ(n, RULE); + REQN(n->n_nchildren, 4); + n = n->n_child; + REQ(n, NAME); + nf = addnfa(gr, n->n_str); + n++; + REQ(n, COLON); + n++; + REQ(n, RHS); + compile_rhs(&gr->gr_ll, nf, n, &nf->nf_start, &nf->nf_finish); + n++; + REQ(n, NEWLINE); } static void compile_rhs(labellist *ll, nfa *nf, node *n, int *pa, int *pb) { - int i; - int a, b; - - REQ(n, RHS); - i = n->n_nchildren; - REQN(i, 1); - n = n->n_child; - REQ(n, ALT); - compile_alt(ll, nf, n, pa, pb); - if (--i <= 0) - return; - n++; - a = *pa; - b = *pb; - *pa = addnfastate(nf); - *pb = addnfastate(nf); - addnfaarc(nf, *pa, a, EMPTY); - addnfaarc(nf, b, *pb, EMPTY); - for (; --i >= 0; n++) { - REQ(n, VBAR); - REQN(i, 1); - --i; - n++; - REQ(n, ALT); - compile_alt(ll, nf, n, &a, &b); - addnfaarc(nf, *pa, a, EMPTY); - addnfaarc(nf, b, *pb, EMPTY); - } + int i; + int a, b; + + REQ(n, RHS); + i = n->n_nchildren; + REQN(i, 1); + n = n->n_child; + REQ(n, ALT); + compile_alt(ll, nf, n, pa, pb); + if (--i <= 0) + return; + n++; + a = *pa; + b = *pb; + *pa = addnfastate(nf); + *pb = addnfastate(nf); + addnfaarc(nf, *pa, a, EMPTY); + addnfaarc(nf, b, *pb, EMPTY); + for (; --i >= 0; n++) { + REQ(n, VBAR); + REQN(i, 1); + --i; + n++; + REQ(n, ALT); + compile_alt(ll, nf, n, &a, &b); + addnfaarc(nf, *pa, a, EMPTY); + addnfaarc(nf, b, *pb, EMPTY); + } } static void compile_alt(labellist *ll, nfa *nf, node *n, int *pa, int *pb) { - int i; - int a, b; - - REQ(n, ALT); - i = n->n_nchildren; - REQN(i, 1); - n = n->n_child; - REQ(n, ITEM); - compile_item(ll, nf, n, pa, pb); - --i; - n++; - for (; --i >= 0; n++) { - REQ(n, ITEM); - compile_item(ll, nf, n, &a, &b); - addnfaarc(nf, *pb, a, EMPTY); - *pb = b; - } + int i; + int a, b; + + REQ(n, ALT); + i = n->n_nchildren; + REQN(i, 1); + n = n->n_child; + REQ(n, ITEM); + compile_item(ll, nf, n, pa, pb); + --i; + n++; + for (; --i >= 0; n++) { + REQ(n, ITEM); + compile_item(ll, nf, n, &a, &b); + addnfaarc(nf, *pb, a, EMPTY); + *pb = b; + } } static void compile_item(labellist *ll, nfa *nf, node *n, int *pa, int *pb) { - int i; - int a, b; - - REQ(n, ITEM); - i = n->n_nchildren; - REQN(i, 1); - n = n->n_child; - if (n->n_type == LSQB) { - REQN(i, 3); - n++; - REQ(n, RHS); - *pa = addnfastate(nf); - *pb = addnfastate(nf); - addnfaarc(nf, *pa, *pb, EMPTY); - compile_rhs(ll, nf, n, &a, &b); - addnfaarc(nf, *pa, a, EMPTY); - addnfaarc(nf, b, *pb, EMPTY); - REQN(i, 1); - n++; - REQ(n, RSQB); - } - else { - compile_atom(ll, nf, n, pa, pb); - if (--i <= 0) - return; - n++; - addnfaarc(nf, *pb, *pa, EMPTY); - if (n->n_type == STAR) - *pb = *pa; - else - REQ(n, PLUS); - } + int i; + int a, b; + + REQ(n, ITEM); + i = n->n_nchildren; + REQN(i, 1); + n = n->n_child; + if (n->n_type == LSQB) { + REQN(i, 3); + n++; + REQ(n, RHS); + *pa = addnfastate(nf); + *pb = addnfastate(nf); + addnfaarc(nf, *pa, *pb, EMPTY); + compile_rhs(ll, nf, n, &a, &b); + addnfaarc(nf, *pa, a, EMPTY); + addnfaarc(nf, b, *pb, EMPTY); + REQN(i, 1); + n++; + REQ(n, RSQB); + } + else { + compile_atom(ll, nf, n, pa, pb); + if (--i <= 0) + return; + n++; + addnfaarc(nf, *pb, *pa, EMPTY); + if (n->n_type == STAR) + *pb = *pa; + else + REQ(n, PLUS); + } } static void compile_atom(labellist *ll, nfa *nf, node *n, int *pa, int *pb) { - int i; - - REQ(n, ATOM); - i = n->n_nchildren; - REQN(i, 1); - n = n->n_child; - if (n->n_type == LPAR) { - REQN(i, 3); - n++; - REQ(n, RHS); - compile_rhs(ll, nf, n, pa, pb); - n++; - REQ(n, RPAR); - } - else if (n->n_type == NAME || n->n_type == STRING) { - *pa = addnfastate(nf); - *pb = addnfastate(nf); - addnfaarc(nf, *pa, *pb, addlabel(ll, n->n_type, n->n_str)); - } - else - REQ(n, NAME); + int i; + + REQ(n, ATOM); + i = n->n_nchildren; + REQN(i, 1); + n = n->n_child; + if (n->n_type == LPAR) { + REQN(i, 3); + n++; + REQ(n, RHS); + compile_rhs(ll, nf, n, pa, pb); + n++; + REQ(n, RPAR); + } + else if (n->n_type == NAME || n->n_type == STRING) { + *pa = addnfastate(nf); + *pb = addnfastate(nf); + addnfaarc(nf, *pa, *pb, addlabel(ll, n->n_type, n->n_str)); + } + else + REQ(n, NAME); } static void dumpstate(labellist *ll, nfa *nf, int istate) { - nfastate *st; - int i; - nfaarc *ar; - - printf("%c%2d%c", - istate == nf->nf_start ? '*' : ' ', - istate, - istate == nf->nf_finish ? '.' : ' '); - st = &nf->nf_state[istate]; - ar = st->st_arc; - for (i = 0; i < st->st_narcs; i++) { - if (i > 0) - printf("\n "); - printf("-> %2d %s", ar->ar_arrow, - PyGrammar_LabelRepr(&ll->ll_label[ar->ar_label])); - ar++; - } - printf("\n"); + nfastate *st; + int i; + nfaarc *ar; + + printf("%c%2d%c", + istate == nf->nf_start ? '*' : ' ', + istate, + istate == nf->nf_finish ? '.' : ' '); + st = &nf->nf_state[istate]; + ar = st->st_arc; + for (i = 0; i < st->st_narcs; i++) { + if (i > 0) + printf("\n "); + printf("-> %2d %s", ar->ar_arrow, + PyGrammar_LabelRepr(&ll->ll_label[ar->ar_label])); + ar++; + } + printf("\n"); } static void dumpnfa(labellist *ll, nfa *nf) { - int i; - - printf("NFA '%s' has %d states; start %d, finish %d\n", - nf->nf_name, nf->nf_nstates, nf->nf_start, nf->nf_finish); - for (i = 0; i < nf->nf_nstates; i++) - dumpstate(ll, nf, i); + int i; + + printf("NFA '%s' has %d states; start %d, finish %d\n", + nf->nf_name, nf->nf_nstates, nf->nf_start, nf->nf_finish); + for (i = 0; i < nf->nf_nstates; i++) + dumpstate(ll, nf, i); } @@ -342,184 +342,184 @@ static void addclosure(bitset ss, nfa *nf, int istate) { - if (addbit(ss, istate)) { - nfastate *st = &nf->nf_state[istate]; - nfaarc *ar = st->st_arc; - int i; - - for (i = st->st_narcs; --i >= 0; ) { - if (ar->ar_label == EMPTY) - addclosure(ss, nf, ar->ar_arrow); - ar++; - } - } + if (addbit(ss, istate)) { + nfastate *st = &nf->nf_state[istate]; + nfaarc *ar = st->st_arc; + int i; + + for (i = st->st_narcs; --i >= 0; ) { + if (ar->ar_label == EMPTY) + addclosure(ss, nf, ar->ar_arrow); + ar++; + } + } } typedef struct _ss_arc { - bitset sa_bitset; - int sa_arrow; - int sa_label; + bitset sa_bitset; + int sa_arrow; + int sa_label; } ss_arc; typedef struct _ss_state { - bitset ss_ss; - int ss_narcs; - struct _ss_arc *ss_arc; - int ss_deleted; - int ss_finish; - int ss_rename; + bitset ss_ss; + int ss_narcs; + struct _ss_arc *ss_arc; + int ss_deleted; + int ss_finish; + int ss_rename; } ss_state; typedef struct _ss_dfa { - int sd_nstates; - ss_state *sd_state; + int sd_nstates; + ss_state *sd_state; } ss_dfa; /* Forward */ static void printssdfa(int xx_nstates, ss_state *xx_state, int nbits, - labellist *ll, char *msg); + labellist *ll, char *msg); static void simplify(int xx_nstates, ss_state *xx_state); static void convert(dfa *d, int xx_nstates, ss_state *xx_state); static void makedfa(nfagrammar *gr, nfa *nf, dfa *d) { - int nbits = nf->nf_nstates; - bitset ss; - int xx_nstates; - ss_state *xx_state, *yy; - ss_arc *zz; - int istate, jstate, iarc, jarc, ibit; - nfastate *st; - nfaarc *ar; - - ss = newbitset(nbits); - addclosure(ss, nf, nf->nf_start); - xx_state = (ss_state *)PyObject_MALLOC(sizeof(ss_state)); - if (xx_state == NULL) - Py_FatalError("no mem for xx_state in makedfa"); - xx_nstates = 1; - yy = &xx_state[0]; - yy->ss_ss = ss; - yy->ss_narcs = 0; - yy->ss_arc = NULL; - yy->ss_deleted = 0; - yy->ss_finish = testbit(ss, nf->nf_finish); - if (yy->ss_finish) - printf("Error: nonterminal '%s' may produce empty.\n", - nf->nf_name); - - /* This algorithm is from a book written before - the invention of structured programming... */ - - /* For each unmarked state... */ - for (istate = 0; istate < xx_nstates; ++istate) { - size_t size; - yy = &xx_state[istate]; - ss = yy->ss_ss; - /* For all its states... */ - for (ibit = 0; ibit < nf->nf_nstates; ++ibit) { - if (!testbit(ss, ibit)) - continue; - st = &nf->nf_state[ibit]; - /* For all non-empty arcs from this state... */ - for (iarc = 0; iarc < st->st_narcs; iarc++) { - ar = &st->st_arc[iarc]; - if (ar->ar_label == EMPTY) - continue; - /* Look up in list of arcs from this state */ - for (jarc = 0; jarc < yy->ss_narcs; ++jarc) { - zz = &yy->ss_arc[jarc]; - if (ar->ar_label == zz->sa_label) - goto found; - } - /* Add new arc for this state */ - size = sizeof(ss_arc) * (yy->ss_narcs + 1); - yy->ss_arc = (ss_arc *)PyObject_REALLOC( - yy->ss_arc, size); - if (yy->ss_arc == NULL) - Py_FatalError("out of mem"); - zz = &yy->ss_arc[yy->ss_narcs++]; - zz->sa_label = ar->ar_label; - zz->sa_bitset = newbitset(nbits); - zz->sa_arrow = -1; - found: ; - /* Add destination */ - addclosure(zz->sa_bitset, nf, ar->ar_arrow); - } - } - /* Now look up all the arrow states */ - for (jarc = 0; jarc < xx_state[istate].ss_narcs; jarc++) { - zz = &xx_state[istate].ss_arc[jarc]; - for (jstate = 0; jstate < xx_nstates; jstate++) { - if (samebitset(zz->sa_bitset, - xx_state[jstate].ss_ss, nbits)) { - zz->sa_arrow = jstate; - goto done; - } - } - size = sizeof(ss_state) * (xx_nstates + 1); - xx_state = (ss_state *)PyObject_REALLOC(xx_state, - size); - if (xx_state == NULL) - Py_FatalError("out of mem"); - zz->sa_arrow = xx_nstates; - yy = &xx_state[xx_nstates++]; - yy->ss_ss = zz->sa_bitset; - yy->ss_narcs = 0; - yy->ss_arc = NULL; - yy->ss_deleted = 0; - yy->ss_finish = testbit(yy->ss_ss, nf->nf_finish); - done: ; - } - } - - if (Py_DebugFlag) - printssdfa(xx_nstates, xx_state, nbits, &gr->gr_ll, - "before minimizing"); - - simplify(xx_nstates, xx_state); - - if (Py_DebugFlag) - printssdfa(xx_nstates, xx_state, nbits, &gr->gr_ll, - "after minimizing"); - - convert(d, xx_nstates, xx_state); - - /* XXX cleanup */ - PyObject_FREE(xx_state); + int nbits = nf->nf_nstates; + bitset ss; + int xx_nstates; + ss_state *xx_state, *yy; + ss_arc *zz; + int istate, jstate, iarc, jarc, ibit; + nfastate *st; + nfaarc *ar; + + ss = newbitset(nbits); + addclosure(ss, nf, nf->nf_start); + xx_state = (ss_state *)PyObject_MALLOC(sizeof(ss_state)); + if (xx_state == NULL) + Py_FatalError("no mem for xx_state in makedfa"); + xx_nstates = 1; + yy = &xx_state[0]; + yy->ss_ss = ss; + yy->ss_narcs = 0; + yy->ss_arc = NULL; + yy->ss_deleted = 0; + yy->ss_finish = testbit(ss, nf->nf_finish); + if (yy->ss_finish) + printf("Error: nonterminal '%s' may produce empty.\n", + nf->nf_name); + + /* This algorithm is from a book written before + the invention of structured programming... */ + + /* For each unmarked state... */ + for (istate = 0; istate < xx_nstates; ++istate) { + size_t size; + yy = &xx_state[istate]; + ss = yy->ss_ss; + /* For all its states... */ + for (ibit = 0; ibit < nf->nf_nstates; ++ibit) { + if (!testbit(ss, ibit)) + continue; + st = &nf->nf_state[ibit]; + /* For all non-empty arcs from this state... */ + for (iarc = 0; iarc < st->st_narcs; iarc++) { + ar = &st->st_arc[iarc]; + if (ar->ar_label == EMPTY) + continue; + /* Look up in list of arcs from this state */ + for (jarc = 0; jarc < yy->ss_narcs; ++jarc) { + zz = &yy->ss_arc[jarc]; + if (ar->ar_label == zz->sa_label) + goto found; + } + /* Add new arc for this state */ + size = sizeof(ss_arc) * (yy->ss_narcs + 1); + yy->ss_arc = (ss_arc *)PyObject_REALLOC( + yy->ss_arc, size); + if (yy->ss_arc == NULL) + Py_FatalError("out of mem"); + zz = &yy->ss_arc[yy->ss_narcs++]; + zz->sa_label = ar->ar_label; + zz->sa_bitset = newbitset(nbits); + zz->sa_arrow = -1; + found: ; + /* Add destination */ + addclosure(zz->sa_bitset, nf, ar->ar_arrow); + } + } + /* Now look up all the arrow states */ + for (jarc = 0; jarc < xx_state[istate].ss_narcs; jarc++) { + zz = &xx_state[istate].ss_arc[jarc]; + for (jstate = 0; jstate < xx_nstates; jstate++) { + if (samebitset(zz->sa_bitset, + xx_state[jstate].ss_ss, nbits)) { + zz->sa_arrow = jstate; + goto done; + } + } + size = sizeof(ss_state) * (xx_nstates + 1); + xx_state = (ss_state *)PyObject_REALLOC(xx_state, + size); + if (xx_state == NULL) + Py_FatalError("out of mem"); + zz->sa_arrow = xx_nstates; + yy = &xx_state[xx_nstates++]; + yy->ss_ss = zz->sa_bitset; + yy->ss_narcs = 0; + yy->ss_arc = NULL; + yy->ss_deleted = 0; + yy->ss_finish = testbit(yy->ss_ss, nf->nf_finish); + done: ; + } + } + + if (Py_DebugFlag) + printssdfa(xx_nstates, xx_state, nbits, &gr->gr_ll, + "before minimizing"); + + simplify(xx_nstates, xx_state); + + if (Py_DebugFlag) + printssdfa(xx_nstates, xx_state, nbits, &gr->gr_ll, + "after minimizing"); + + convert(d, xx_nstates, xx_state); + + /* XXX cleanup */ + PyObject_FREE(xx_state); } static void printssdfa(int xx_nstates, ss_state *xx_state, int nbits, - labellist *ll, char *msg) + labellist *ll, char *msg) { - int i, ibit, iarc; - ss_state *yy; - ss_arc *zz; - - printf("Subset DFA %s\n", msg); - for (i = 0; i < xx_nstates; i++) { - yy = &xx_state[i]; - if (yy->ss_deleted) - continue; - printf(" Subset %d", i); - if (yy->ss_finish) - printf(" (finish)"); - printf(" { "); - for (ibit = 0; ibit < nbits; ibit++) { - if (testbit(yy->ss_ss, ibit)) - printf("%d ", ibit); - } - printf("}\n"); - for (iarc = 0; iarc < yy->ss_narcs; iarc++) { - zz = &yy->ss_arc[iarc]; - printf(" Arc to state %d, label %s\n", - zz->sa_arrow, - PyGrammar_LabelRepr( - &ll->ll_label[zz->sa_label])); - } - } + int i, ibit, iarc; + ss_state *yy; + ss_arc *zz; + + printf("Subset DFA %s\n", msg); + for (i = 0; i < xx_nstates; i++) { + yy = &xx_state[i]; + if (yy->ss_deleted) + continue; + printf(" Subset %d", i); + if (yy->ss_finish) + printf(" (finish)"); + printf(" { "); + for (ibit = 0; ibit < nbits; ibit++) { + if (testbit(yy->ss_ss, ibit)) + printf("%d ", ibit); + } + printf("}\n"); + for (iarc = 0; iarc < yy->ss_narcs; iarc++) { + zz = &yy->ss_arc[iarc]; + printf(" Arc to state %d, label %s\n", + zz->sa_arrow, + PyGrammar_LabelRepr( + &ll->ll_label[zz->sa_label])); + } + } } @@ -535,59 +535,59 @@ static int samestate(ss_state *s1, ss_state *s2) { - int i; - - if (s1->ss_narcs != s2->ss_narcs || s1->ss_finish != s2->ss_finish) - return 0; - for (i = 0; i < s1->ss_narcs; i++) { - if (s1->ss_arc[i].sa_arrow != s2->ss_arc[i].sa_arrow || - s1->ss_arc[i].sa_label != s2->ss_arc[i].sa_label) - return 0; - } - return 1; + int i; + + if (s1->ss_narcs != s2->ss_narcs || s1->ss_finish != s2->ss_finish) + return 0; + for (i = 0; i < s1->ss_narcs; i++) { + if (s1->ss_arc[i].sa_arrow != s2->ss_arc[i].sa_arrow || + s1->ss_arc[i].sa_label != s2->ss_arc[i].sa_label) + return 0; + } + return 1; } static void renamestates(int xx_nstates, ss_state *xx_state, int from, int to) { - int i, j; - - if (Py_DebugFlag) - printf("Rename state %d to %d.\n", from, to); - for (i = 0; i < xx_nstates; i++) { - if (xx_state[i].ss_deleted) - continue; - for (j = 0; j < xx_state[i].ss_narcs; j++) { - if (xx_state[i].ss_arc[j].sa_arrow == from) - xx_state[i].ss_arc[j].sa_arrow = to; - } - } + int i, j; + + if (Py_DebugFlag) + printf("Rename state %d to %d.\n", from, to); + for (i = 0; i < xx_nstates; i++) { + if (xx_state[i].ss_deleted) + continue; + for (j = 0; j < xx_state[i].ss_narcs; j++) { + if (xx_state[i].ss_arc[j].sa_arrow == from) + xx_state[i].ss_arc[j].sa_arrow = to; + } + } } static void simplify(int xx_nstates, ss_state *xx_state) { - int changes; - int i, j; - - do { - changes = 0; - for (i = 1; i < xx_nstates; i++) { - if (xx_state[i].ss_deleted) - continue; - for (j = 0; j < i; j++) { - if (xx_state[j].ss_deleted) - continue; - if (samestate(&xx_state[i], &xx_state[j])) { - xx_state[i].ss_deleted++; - renamestates(xx_nstates, xx_state, - i, j); - changes++; - break; - } - } - } - } while (changes); + int changes; + int i, j; + + do { + changes = 0; + for (i = 1; i < xx_nstates; i++) { + if (xx_state[i].ss_deleted) + continue; + for (j = 0; j < i; j++) { + if (xx_state[j].ss_deleted) + continue; + if (samestate(&xx_state[i], &xx_state[j])) { + xx_state[i].ss_deleted++; + renamestates(xx_nstates, xx_state, + i, j); + changes++; + break; + } + } + } + } while (changes); } @@ -598,32 +598,32 @@ static void convert(dfa *d, int xx_nstates, ss_state *xx_state) { - int i, j; - ss_state *yy; - ss_arc *zz; - - for (i = 0; i < xx_nstates; i++) { - yy = &xx_state[i]; - if (yy->ss_deleted) - continue; - yy->ss_rename = addstate(d); - } - - for (i = 0; i < xx_nstates; i++) { - yy = &xx_state[i]; - if (yy->ss_deleted) - continue; - for (j = 0; j < yy->ss_narcs; j++) { - zz = &yy->ss_arc[j]; - addarc(d, yy->ss_rename, - xx_state[zz->sa_arrow].ss_rename, - zz->sa_label); - } - if (yy->ss_finish) - addarc(d, yy->ss_rename, yy->ss_rename, 0); - } - - d->d_initial = 0; + int i, j; + ss_state *yy; + ss_arc *zz; + + for (i = 0; i < xx_nstates; i++) { + yy = &xx_state[i]; + if (yy->ss_deleted) + continue; + yy->ss_rename = addstate(d); + } + + for (i = 0; i < xx_nstates; i++) { + yy = &xx_state[i]; + if (yy->ss_deleted) + continue; + for (j = 0; j < yy->ss_narcs; j++) { + zz = &yy->ss_arc[j]; + addarc(d, yy->ss_rename, + xx_state[zz->sa_arrow].ss_rename, + zz->sa_label); + } + if (yy->ss_finish) + addarc(d, yy->ss_rename, yy->ss_rename, 0); + } + + d->d_initial = 0; } @@ -632,43 +632,43 @@ static grammar * maketables(nfagrammar *gr) { - int i; - nfa *nf; - dfa *d; - grammar *g; - - if (gr->gr_nnfas == 0) - return NULL; - g = newgrammar(gr->gr_nfa[0]->nf_type); - /* XXX first rule must be start rule */ - g->g_ll = gr->gr_ll; - - for (i = 0; i < gr->gr_nnfas; i++) { - nf = gr->gr_nfa[i]; - if (Py_DebugFlag) { - printf("Dump of NFA for '%s' ...\n", nf->nf_name); - dumpnfa(&gr->gr_ll, nf); - printf("Making DFA for '%s' ...\n", nf->nf_name); - } - d = adddfa(g, nf->nf_type, nf->nf_name); - makedfa(gr, gr->gr_nfa[i], d); - } - - return g; + int i; + nfa *nf; + dfa *d; + grammar *g; + + if (gr->gr_nnfas == 0) + return NULL; + g = newgrammar(gr->gr_nfa[0]->nf_type); + /* XXX first rule must be start rule */ + g->g_ll = gr->gr_ll; + + for (i = 0; i < gr->gr_nnfas; i++) { + nf = gr->gr_nfa[i]; + if (Py_DebugFlag) { + printf("Dump of NFA for '%s' ...\n", nf->nf_name); + dumpnfa(&gr->gr_ll, nf); + printf("Making DFA for '%s' ...\n", nf->nf_name); + } + d = adddfa(g, nf->nf_type, nf->nf_name); + makedfa(gr, gr->gr_nfa[i], d); + } + + return g; } grammar * pgen(node *n) { - nfagrammar *gr; - grammar *g; - - gr = metacompile(n); - g = maketables(gr); - translatelabels(g); - addfirstsets(g); - PyObject_FREE(gr); - return g; + nfagrammar *gr; + grammar *g; + + gr = metacompile(n); + g = maketables(gr); + translatelabels(g); + addfirstsets(g); + PyObject_FREE(gr); + return g; } grammar * @@ -702,7 +702,7 @@ --------- [Aho&Ullman 77] - Aho&Ullman, Principles of Compiler Design, Addison-Wesley 1977 - (first edition) + Aho&Ullman, Principles of Compiler Design, Addison-Wesley 1977 + (first edition) */ Modified: python/branches/py3k/Parser/pgenmain.c ============================================================================== --- python/branches/py3k/Parser/pgenmain.c (original) +++ python/branches/py3k/Parser/pgenmain.c Sun May 9 17:52:27 2010 @@ -30,104 +30,104 @@ void Py_Exit(int sts) { - exit(sts); + exit(sts); } int main(int argc, char **argv) { - grammar *g; - FILE *fp; - char *filename, *graminit_h, *graminit_c; - - if (argc != 4) { - fprintf(stderr, - "usage: %s grammar graminit.h graminit.c\n", argv[0]); - Py_Exit(2); - } - filename = argv[1]; - graminit_h = argv[2]; - graminit_c = argv[3]; - g = getgrammar(filename); - fp = fopen(graminit_c, "w"); - if (fp == NULL) { - perror(graminit_c); - Py_Exit(1); - } - if (Py_DebugFlag) - printf("Writing %s ...\n", graminit_c); - printgrammar(g, fp); - fclose(fp); - fp = fopen(graminit_h, "w"); - if (fp == NULL) { - perror(graminit_h); - Py_Exit(1); - } - if (Py_DebugFlag) - printf("Writing %s ...\n", graminit_h); - printnonterminals(g, fp); - fclose(fp); - Py_Exit(0); - return 0; /* Make gcc -Wall happy */ + grammar *g; + FILE *fp; + char *filename, *graminit_h, *graminit_c; + + if (argc != 4) { + fprintf(stderr, + "usage: %s grammar graminit.h graminit.c\n", argv[0]); + Py_Exit(2); + } + filename = argv[1]; + graminit_h = argv[2]; + graminit_c = argv[3]; + g = getgrammar(filename); + fp = fopen(graminit_c, "w"); + if (fp == NULL) { + perror(graminit_c); + Py_Exit(1); + } + if (Py_DebugFlag) + printf("Writing %s ...\n", graminit_c); + printgrammar(g, fp); + fclose(fp); + fp = fopen(graminit_h, "w"); + if (fp == NULL) { + perror(graminit_h); + Py_Exit(1); + } + if (Py_DebugFlag) + printf("Writing %s ...\n", graminit_h); + printnonterminals(g, fp); + fclose(fp); + Py_Exit(0); + return 0; /* Make gcc -Wall happy */ } grammar * getgrammar(char *filename) { - FILE *fp; - node *n; - grammar *g0, *g; - perrdetail err; - - fp = fopen(filename, "r"); - if (fp == NULL) { - perror(filename); - Py_Exit(1); - } - g0 = meta_grammar(); - n = PyParser_ParseFile(fp, filename, g0, g0->g_start, - (char *)NULL, (char *)NULL, &err); - fclose(fp); - if (n == NULL) { - fprintf(stderr, "Parsing error %d, line %d.\n", - err.error, err.lineno); - if (err.text != NULL) { - size_t i; - fprintf(stderr, "%s", err.text); - i = strlen(err.text); - if (i == 0 || err.text[i-1] != '\n') - fprintf(stderr, "\n"); - for (i = 0; i < err.offset; i++) { - if (err.text[i] == '\t') - putc('\t', stderr); - else - putc(' ', stderr); - } - fprintf(stderr, "^\n"); - PyObject_FREE(err.text); - } - Py_Exit(1); - } - g = pgen(n); - if (g == NULL) { - printf("Bad grammar.\n"); - Py_Exit(1); - } - return g; + FILE *fp; + node *n; + grammar *g0, *g; + perrdetail err; + + fp = fopen(filename, "r"); + if (fp == NULL) { + perror(filename); + Py_Exit(1); + } + g0 = meta_grammar(); + n = PyParser_ParseFile(fp, filename, g0, g0->g_start, + (char *)NULL, (char *)NULL, &err); + fclose(fp); + if (n == NULL) { + fprintf(stderr, "Parsing error %d, line %d.\n", + err.error, err.lineno); + if (err.text != NULL) { + size_t i; + fprintf(stderr, "%s", err.text); + i = strlen(err.text); + if (i == 0 || err.text[i-1] != '\n') + fprintf(stderr, "\n"); + for (i = 0; i < err.offset; i++) { + if (err.text[i] == '\t') + putc('\t', stderr); + else + putc(' ', stderr); + } + fprintf(stderr, "^\n"); + PyObject_FREE(err.text); + } + Py_Exit(1); + } + g = pgen(n); + if (g == NULL) { + printf("Bad grammar.\n"); + Py_Exit(1); + } + return g; } /* Can't happen in pgen */ PyObject* PyErr_Occurred() { - return 0; + return 0; } void Py_FatalError(const char *msg) { - fprintf(stderr, "pgen: FATAL ERROR: %s\n", msg); - Py_Exit(1); + fprintf(stderr, "pgen: FATAL ERROR: %s\n", msg); + Py_Exit(1); } /* No-nonsense my_readline() for tokenizer.c */ @@ -135,28 +135,28 @@ char * PyOS_Readline(FILE *sys_stdin, FILE *sys_stdout, char *prompt) { - size_t n = 1000; - char *p = (char *)PyMem_MALLOC(n); - char *q; - if (p == NULL) - return NULL; - fprintf(stderr, "%s", prompt); - q = fgets(p, n, sys_stdin); - if (q == NULL) { - *p = '\0'; - return p; - } - n = strlen(p); - if (n > 0 && p[n-1] != '\n') - p[n-1] = '\n'; - return (char *)PyMem_REALLOC(p, n+1); + size_t n = 1000; + char *p = (char *)PyMem_MALLOC(n); + char *q; + if (p == NULL) + return NULL; + fprintf(stderr, "%s", prompt); + q = fgets(p, n, sys_stdin); + if (q == NULL) { + *p = '\0'; + return p; + } + n = strlen(p); + if (n > 0 && p[n-1] != '\n') + p[n-1] = '\n'; + return (char *)PyMem_REALLOC(p, n+1); } /* No-nonsense fgets */ char * Py_UniversalNewlineFgets(char *buf, int n, FILE *stream, PyObject *fobj) { - return fgets(buf, n, stream); + return fgets(buf, n, stream); } @@ -165,9 +165,9 @@ void PySys_WriteStderr(const char *format, ...) { - va_list va; + va_list va; - va_start(va, format); - vfprintf(stderr, format, va); - va_end(va); + va_start(va, format); + vfprintf(stderr, format, va); + va_end(va); } Modified: python/branches/py3k/Parser/printgrammar.c ============================================================================== --- python/branches/py3k/Parser/printgrammar.c (original) +++ python/branches/py3k/Parser/printgrammar.c Sun May 9 17:52:27 2010 @@ -13,105 +13,105 @@ void printgrammar(grammar *g, FILE *fp) { - fprintf(fp, "/* Generated by Parser/pgen */\n\n"); - fprintf(fp, "#include \"pgenheaders.h\"\n"); - fprintf(fp, "#include \"grammar.h\"\n"); - fprintf(fp, "PyAPI_DATA(grammar) _PyParser_Grammar;\n"); - printdfas(g, fp); - printlabels(g, fp); - fprintf(fp, "grammar _PyParser_Grammar = {\n"); - fprintf(fp, "\t%d,\n", g->g_ndfas); - fprintf(fp, "\tdfas,\n"); - fprintf(fp, "\t{%d, labels},\n", g->g_ll.ll_nlabels); - fprintf(fp, "\t%d\n", g->g_start); - fprintf(fp, "};\n"); + fprintf(fp, "/* Generated by Parser/pgen */\n\n"); + fprintf(fp, "#include \"pgenheaders.h\"\n"); + fprintf(fp, "#include \"grammar.h\"\n"); + fprintf(fp, "PyAPI_DATA(grammar) _PyParser_Grammar;\n"); + printdfas(g, fp); + printlabels(g, fp); + fprintf(fp, "grammar _PyParser_Grammar = {\n"); + fprintf(fp, "\t%d,\n", g->g_ndfas); + fprintf(fp, "\tdfas,\n"); + fprintf(fp, "\t{%d, labels},\n", g->g_ll.ll_nlabels); + fprintf(fp, "\t%d\n", g->g_start); + fprintf(fp, "};\n"); } void printnonterminals(grammar *g, FILE *fp) { - dfa *d; - int i; - - fprintf(fp, "/* Generated by Parser/pgen */\n\n"); - - d = g->g_dfa; - for (i = g->g_ndfas; --i >= 0; d++) - fprintf(fp, "#define %s %d\n", d->d_name, d->d_type); + dfa *d; + int i; + + fprintf(fp, "/* Generated by Parser/pgen */\n\n"); + + d = g->g_dfa; + for (i = g->g_ndfas; --i >= 0; d++) + fprintf(fp, "#define %s %d\n", d->d_name, d->d_type); } static void printarcs(int i, dfa *d, FILE *fp) { - arc *a; - state *s; - int j, k; - - s = d->d_state; - for (j = 0; j < d->d_nstates; j++, s++) { - fprintf(fp, "static arc arcs_%d_%d[%d] = {\n", - i, j, s->s_narcs); - a = s->s_arc; - for (k = 0; k < s->s_narcs; k++, a++) - fprintf(fp, "\t{%d, %d},\n", a->a_lbl, a->a_arrow); - fprintf(fp, "};\n"); - } + arc *a; + state *s; + int j, k; + + s = d->d_state; + for (j = 0; j < d->d_nstates; j++, s++) { + fprintf(fp, "static arc arcs_%d_%d[%d] = {\n", + i, j, s->s_narcs); + a = s->s_arc; + for (k = 0; k < s->s_narcs; k++, a++) + fprintf(fp, "\t{%d, %d},\n", a->a_lbl, a->a_arrow); + fprintf(fp, "};\n"); + } } static void printstates(grammar *g, FILE *fp) { - state *s; - dfa *d; - int i, j; - - d = g->g_dfa; - for (i = 0; i < g->g_ndfas; i++, d++) { - printarcs(i, d, fp); - fprintf(fp, "static state states_%d[%d] = {\n", - i, d->d_nstates); - s = d->d_state; - for (j = 0; j < d->d_nstates; j++, s++) - fprintf(fp, "\t{%d, arcs_%d_%d},\n", - s->s_narcs, i, j); - fprintf(fp, "};\n"); - } + state *s; + dfa *d; + int i, j; + + d = g->g_dfa; + for (i = 0; i < g->g_ndfas; i++, d++) { + printarcs(i, d, fp); + fprintf(fp, "static state states_%d[%d] = {\n", + i, d->d_nstates); + s = d->d_state; + for (j = 0; j < d->d_nstates; j++, s++) + fprintf(fp, "\t{%d, arcs_%d_%d},\n", + s->s_narcs, i, j); + fprintf(fp, "};\n"); + } } static void printdfas(grammar *g, FILE *fp) { - dfa *d; - int i, j; - - printstates(g, fp); - fprintf(fp, "static dfa dfas[%d] = {\n", g->g_ndfas); - d = g->g_dfa; - for (i = 0; i < g->g_ndfas; i++, d++) { - fprintf(fp, "\t{%d, \"%s\", %d, %d, states_%d,\n", - d->d_type, d->d_name, d->d_initial, d->d_nstates, i); - fprintf(fp, "\t \""); - for (j = 0; j < NBYTES(g->g_ll.ll_nlabels); j++) - fprintf(fp, "\\%03o", d->d_first[j] & 0xff); - fprintf(fp, "\"},\n"); - } - fprintf(fp, "};\n"); + dfa *d; + int i, j; + + printstates(g, fp); + fprintf(fp, "static dfa dfas[%d] = {\n", g->g_ndfas); + d = g->g_dfa; + for (i = 0; i < g->g_ndfas; i++, d++) { + fprintf(fp, "\t{%d, \"%s\", %d, %d, states_%d,\n", + d->d_type, d->d_name, d->d_initial, d->d_nstates, i); + fprintf(fp, "\t \""); + for (j = 0; j < NBYTES(g->g_ll.ll_nlabels); j++) + fprintf(fp, "\\%03o", d->d_first[j] & 0xff); + fprintf(fp, "\"},\n"); + } + fprintf(fp, "};\n"); } static void printlabels(grammar *g, FILE *fp) { - label *l; - int i; - - fprintf(fp, "static label labels[%d] = {\n", g->g_ll.ll_nlabels); - l = g->g_ll.ll_label; - for (i = g->g_ll.ll_nlabels; --i >= 0; l++) { - if (l->lb_str == NULL) - fprintf(fp, "\t{%d, 0},\n", l->lb_type); - else - fprintf(fp, "\t{%d, \"%s\"},\n", - l->lb_type, l->lb_str); - } - fprintf(fp, "};\n"); + label *l; + int i; + + fprintf(fp, "static label labels[%d] = {\n", g->g_ll.ll_nlabels); + l = g->g_ll.ll_label; + for (i = g->g_ll.ll_nlabels; --i >= 0; l++) { + if (l->lb_str == NULL) + fprintf(fp, "\t{%d, 0},\n", l->lb_type); + else + fprintf(fp, "\t{%d, \"%s\"},\n", + l->lb_type, l->lb_str); + } + fprintf(fp, "};\n"); } Modified: python/branches/py3k/Parser/tokenizer.c ============================================================================== --- python/branches/py3k/Parser/tokenizer.c (original) +++ python/branches/py3k/Parser/tokenizer.c Sun May 9 17:52:27 2010 @@ -19,17 +19,17 @@ #endif /* PGEN */ #define is_potential_identifier_start(c) (\ - (c >= 'a' && c <= 'z')\ - || (c >= 'A' && c <= 'Z')\ - || c == '_'\ - || (c >= 128)) + (c >= 'a' && c <= 'z')\ + || (c >= 'A' && c <= 'Z')\ + || c == '_'\ + || (c >= 128)) #define is_potential_identifier_char(c) (\ - (c >= 'a' && c <= 'z')\ - || (c >= 'A' && c <= 'Z')\ - || (c >= '0' && c <= '9')\ - || c == '_'\ - || (c >= 128)) + (c >= 'a' && c <= 'z')\ + || (c >= 'A' && c <= 'Z')\ + || (c >= '0' && c <= '9')\ + || c == '_'\ + || (c >= 128)) extern char *PyOS_Readline(FILE *, FILE *, char *); /* Return malloc'ed string including trailing \n; @@ -48,62 +48,62 @@ /* Token names */ char *_PyParser_TokenNames[] = { - "ENDMARKER", - "NAME", - "NUMBER", - "STRING", - "NEWLINE", - "INDENT", - "DEDENT", - "LPAR", - "RPAR", - "LSQB", - "RSQB", - "COLON", - "COMMA", - "SEMI", - "PLUS", - "MINUS", - "STAR", - "SLASH", - "VBAR", - "AMPER", - "LESS", - "GREATER", - "EQUAL", - "DOT", - "PERCENT", - "LBRACE", - "RBRACE", - "EQEQUAL", - "NOTEQUAL", - "LESSEQUAL", - "GREATEREQUAL", - "TILDE", - "CIRCUMFLEX", - "LEFTSHIFT", - "RIGHTSHIFT", - "DOUBLESTAR", - "PLUSEQUAL", - "MINEQUAL", - "STAREQUAL", - "SLASHEQUAL", - "PERCENTEQUAL", - "AMPEREQUAL", - "VBAREQUAL", - "CIRCUMFLEXEQUAL", - "LEFTSHIFTEQUAL", - "RIGHTSHIFTEQUAL", - "DOUBLESTAREQUAL", - "DOUBLESLASH", - "DOUBLESLASHEQUAL", - "AT", - "RARROW", - "ELLIPSIS", - /* This table must match the #defines in token.h! */ - "OP", - "", - "" + "ENDMARKER", + "NAME", + "NUMBER", + "STRING", + "NEWLINE", + "INDENT", + "DEDENT", + "LPAR", + "RPAR", + "LSQB", + "RSQB", + "COLON", + "COMMA", + "SEMI", + "PLUS", + "MINUS", + "STAR", + "SLASH", + "VBAR", + "AMPER", + "LESS", + "GREATER", + "EQUAL", + "DOT", + "PERCENT", + "LBRACE", + "RBRACE", + "EQEQUAL", + "NOTEQUAL", + "LESSEQUAL", + "GREATEREQUAL", + "TILDE", + "CIRCUMFLEX", + "LEFTSHIFT", + "RIGHTSHIFT", + "DOUBLESTAR", + "PLUSEQUAL", + "MINEQUAL", + "STAREQUAL", + "SLASHEQUAL", + "PERCENTEQUAL", + "AMPEREQUAL", + "VBAREQUAL", + "CIRCUMFLEXEQUAL", + "LEFTSHIFTEQUAL", + "RIGHTSHIFTEQUAL", + "DOUBLESTAREQUAL", + "DOUBLESLASH", + "DOUBLESLASHEQUAL", + "AT", + "RARROW", + "ELLIPSIS", + /* This table must match the #defines in token.h! */ + "OP", + "", + "" }; @@ -112,49 +112,49 @@ static struct tok_state * tok_new(void) { - struct tok_state *tok = (struct tok_state *)PyMem_MALLOC( - sizeof(struct tok_state)); - if (tok == NULL) - return NULL; - tok->buf = tok->cur = tok->end = tok->inp = tok->start = NULL; - tok->done = E_OK; - tok->fp = NULL; - tok->input = NULL; - tok->tabsize = TABSIZE; - tok->indent = 0; - tok->indstack[0] = 0; - tok->atbol = 1; - tok->pendin = 0; - tok->prompt = tok->nextprompt = NULL; - tok->lineno = 0; - tok->level = 0; - tok->filename = NULL; - tok->altwarning = 1; - tok->alterror = 1; - tok->alttabsize = 1; - tok->altindstack[0] = 0; - tok->decoding_state = STATE_INIT; - tok->decoding_erred = 0; - tok->read_coding_spec = 0; - tok->enc = NULL; - tok->encoding = NULL; - tok->cont_line = 0; + struct tok_state *tok = (struct tok_state *)PyMem_MALLOC( + sizeof(struct tok_state)); + if (tok == NULL) + return NULL; + tok->buf = tok->cur = tok->end = tok->inp = tok->start = NULL; + tok->done = E_OK; + tok->fp = NULL; + tok->input = NULL; + tok->tabsize = TABSIZE; + tok->indent = 0; + tok->indstack[0] = 0; + tok->atbol = 1; + tok->pendin = 0; + tok->prompt = tok->nextprompt = NULL; + tok->lineno = 0; + tok->level = 0; + tok->filename = NULL; + tok->altwarning = 1; + tok->alterror = 1; + tok->alttabsize = 1; + tok->altindstack[0] = 0; + tok->decoding_state = STATE_INIT; + tok->decoding_erred = 0; + tok->read_coding_spec = 0; + tok->enc = NULL; + tok->encoding = NULL; + tok->cont_line = 0; #ifndef PGEN - tok->decoding_readline = NULL; - tok->decoding_buffer = NULL; + tok->decoding_readline = NULL; + tok->decoding_buffer = NULL; #endif - return tok; + return tok; } static char * new_string(const char *s, Py_ssize_t len) { - char* result = (char *)PyMem_MALLOC(len + 1); - if (result != NULL) { - memcpy(result, s, len); - result[len] = '\0'; - } - return result; + char* result = (char *)PyMem_MALLOC(len + 1); + if (result != NULL) { + memcpy(result, s, len); + result[len] = '\0'; + } + return result; } #ifdef PGEN @@ -162,19 +162,19 @@ static char * decoding_fgets(char *s, int size, struct tok_state *tok) { - return fgets(s, size, tok->fp); + return fgets(s, size, tok->fp); } static int decoding_feof(struct tok_state *tok) { - return feof(tok->fp); + return feof(tok->fp); } static char * decode_str(const char *str, int exec_input, struct tok_state *tok) { - return new_string(str, strlen(str)); + return new_string(str, strlen(str)); } #else /* PGEN */ @@ -182,41 +182,41 @@ static char * error_ret(struct tok_state *tok) /* XXX */ { - tok->decoding_erred = 1; - if (tok->fp != NULL && tok->buf != NULL) /* see PyTokenizer_Free */ - PyMem_FREE(tok->buf); - tok->buf = NULL; - return NULL; /* as if it were EOF */ + tok->decoding_erred = 1; + if (tok->fp != NULL && tok->buf != NULL) /* see PyTokenizer_Free */ + PyMem_FREE(tok->buf); + tok->buf = NULL; + return NULL; /* as if it were EOF */ } static char * -get_normal_name(char *s) /* for utf-8 and latin-1 */ +get_normal_name(char *s) /* for utf-8 and latin-1 */ { - char buf[13]; - int i; - for (i = 0; i < 12; i++) { - int c = s[i]; - if (c == '\0') - break; - else if (c == '_') - buf[i] = '-'; - else - buf[i] = tolower(c); - } - buf[i] = '\0'; - if (strcmp(buf, "utf-8") == 0 || - strncmp(buf, "utf-8-", 6) == 0) - return "utf-8"; - else if (strcmp(buf, "latin-1") == 0 || - strcmp(buf, "iso-8859-1") == 0 || - strcmp(buf, "iso-latin-1") == 0 || - strncmp(buf, "latin-1-", 8) == 0 || - strncmp(buf, "iso-8859-1-", 11) == 0 || - strncmp(buf, "iso-latin-1-", 12) == 0) - return "iso-8859-1"; - else - return s; + char buf[13]; + int i; + for (i = 0; i < 12; i++) { + int c = s[i]; + if (c == '\0') + break; + else if (c == '_') + buf[i] = '-'; + else + buf[i] = tolower(c); + } + buf[i] = '\0'; + if (strcmp(buf, "utf-8") == 0 || + strncmp(buf, "utf-8-", 6) == 0) + return "utf-8"; + else if (strcmp(buf, "latin-1") == 0 || + strcmp(buf, "iso-8859-1") == 0 || + strcmp(buf, "iso-latin-1") == 0 || + strncmp(buf, "latin-1-", 8) == 0 || + strncmp(buf, "iso-8859-1-", 11) == 0 || + strncmp(buf, "iso-latin-1-", 12) == 0) + return "iso-8859-1"; + else + return s; } /* Return the coding spec in S, or NULL if none is found. */ @@ -224,43 +224,43 @@ static char * get_coding_spec(const char *s, Py_ssize_t size) { - Py_ssize_t i; - /* Coding spec must be in a comment, and that comment must be - * the only statement on the source code line. */ - for (i = 0; i < size - 6; i++) { - if (s[i] == '#') - break; - if (s[i] != ' ' && s[i] != '\t' && s[i] != '\014') - return NULL; - } - for (; i < size - 6; i++) { /* XXX inefficient search */ - const char* t = s + i; - if (strncmp(t, "coding", 6) == 0) { - const char* begin = NULL; - t += 6; - if (t[0] != ':' && t[0] != '=') - continue; - do { - t++; - } while (t[0] == '\x20' || t[0] == '\t'); - - begin = t; - while (Py_ISALNUM(t[0]) || - t[0] == '-' || t[0] == '_' || t[0] == '.') - t++; - - if (begin < t) { - char* r = new_string(begin, t - begin); - char* q = get_normal_name(r); - if (r != q) { - PyMem_FREE(r); - r = new_string(q, strlen(q)); - } - return r; - } - } - } - return NULL; + Py_ssize_t i; + /* Coding spec must be in a comment, and that comment must be + * the only statement on the source code line. */ + for (i = 0; i < size - 6; i++) { + if (s[i] == '#') + break; + if (s[i] != ' ' && s[i] != '\t' && s[i] != '\014') + return NULL; + } + for (; i < size - 6; i++) { /* XXX inefficient search */ + const char* t = s + i; + if (strncmp(t, "coding", 6) == 0) { + const char* begin = NULL; + t += 6; + if (t[0] != ':' && t[0] != '=') + continue; + do { + t++; + } while (t[0] == '\x20' || t[0] == '\t'); + + begin = t; + while (Py_ISALNUM(t[0]) || + t[0] == '-' || t[0] == '_' || t[0] == '.') + t++; + + if (begin < t) { + char* r = new_string(begin, t - begin); + char* q = get_normal_name(r); + if (r != q) { + PyMem_FREE(r); + r = new_string(q, strlen(q)); + } + return r; + } + } + } + return NULL; } /* Check whether the line contains a coding spec. If it does, @@ -270,42 +270,42 @@ static int check_coding_spec(const char* line, Py_ssize_t size, struct tok_state *tok, - int set_readline(struct tok_state *, const char *)) + int set_readline(struct tok_state *, const char *)) { - char * cs; - int r = 1; + char * cs; + int r = 1; - if (tok->cont_line) - /* It's a continuation line, so it can't be a coding spec. */ - return 1; - cs = get_coding_spec(line, size); - if (cs != NULL) { - tok->read_coding_spec = 1; - if (tok->encoding == NULL) { - assert(tok->decoding_state == STATE_RAW); - if (strcmp(cs, "utf-8") == 0) { - tok->encoding = cs; - } else { - r = set_readline(tok, cs); - if (r) { - tok->encoding = cs; - tok->decoding_state = STATE_NORMAL; - } - else - PyMem_FREE(cs); - } - } else { /* then, compare cs with BOM */ - r = (strcmp(tok->encoding, cs) == 0); - PyMem_FREE(cs); - } - } - if (!r) { - cs = tok->encoding; - if (!cs) - cs = "with BOM"; - PyErr_Format(PyExc_SyntaxError, "encoding problem: %s", cs); - } - return r; + if (tok->cont_line) + /* It's a continuation line, so it can't be a coding spec. */ + return 1; + cs = get_coding_spec(line, size); + if (cs != NULL) { + tok->read_coding_spec = 1; + if (tok->encoding == NULL) { + assert(tok->decoding_state == STATE_RAW); + if (strcmp(cs, "utf-8") == 0) { + tok->encoding = cs; + } else { + r = set_readline(tok, cs); + if (r) { + tok->encoding = cs; + tok->decoding_state = STATE_NORMAL; + } + else + PyMem_FREE(cs); + } + } else { /* then, compare cs with BOM */ + r = (strcmp(tok->encoding, cs) == 0); + PyMem_FREE(cs); + } + } + if (!r) { + cs = tok->encoding; + if (!cs) + cs = "with BOM"; + PyErr_Format(PyExc_SyntaxError, "encoding problem: %s", cs); + } + return r; } /* See whether the file starts with a BOM. If it does, @@ -314,62 +314,62 @@ static int check_bom(int get_char(struct tok_state *), - void unget_char(int, struct tok_state *), - int set_readline(struct tok_state *, const char *), - struct tok_state *tok) -{ - int ch1, ch2, ch3; - ch1 = get_char(tok); - tok->decoding_state = STATE_RAW; - if (ch1 == EOF) { - return 1; - } else if (ch1 == 0xEF) { - ch2 = get_char(tok); - if (ch2 != 0xBB) { - unget_char(ch2, tok); - unget_char(ch1, tok); - return 1; - } - ch3 = get_char(tok); - if (ch3 != 0xBF) { - unget_char(ch3, tok); - unget_char(ch2, tok); - unget_char(ch1, tok); - return 1; - } + void unget_char(int, struct tok_state *), + int set_readline(struct tok_state *, const char *), + struct tok_state *tok) +{ + int ch1, ch2, ch3; + ch1 = get_char(tok); + tok->decoding_state = STATE_RAW; + if (ch1 == EOF) { + return 1; + } else if (ch1 == 0xEF) { + ch2 = get_char(tok); + if (ch2 != 0xBB) { + unget_char(ch2, tok); + unget_char(ch1, tok); + return 1; + } + ch3 = get_char(tok); + if (ch3 != 0xBF) { + unget_char(ch3, tok); + unget_char(ch2, tok); + unget_char(ch1, tok); + return 1; + } #if 0 - /* Disable support for UTF-16 BOMs until a decision - is made whether this needs to be supported. */ - } else if (ch1 == 0xFE) { - ch2 = get_char(tok); - if (ch2 != 0xFF) { - unget_char(ch2, tok); - unget_char(ch1, tok); - return 1; - } - if (!set_readline(tok, "utf-16-be")) - return 0; - tok->decoding_state = STATE_NORMAL; - } else if (ch1 == 0xFF) { - ch2 = get_char(tok); - if (ch2 != 0xFE) { - unget_char(ch2, tok); - unget_char(ch1, tok); - return 1; - } - if (!set_readline(tok, "utf-16-le")) - return 0; - tok->decoding_state = STATE_NORMAL; + /* Disable support for UTF-16 BOMs until a decision + is made whether this needs to be supported. */ + } else if (ch1 == 0xFE) { + ch2 = get_char(tok); + if (ch2 != 0xFF) { + unget_char(ch2, tok); + unget_char(ch1, tok); + return 1; + } + if (!set_readline(tok, "utf-16-be")) + return 0; + tok->decoding_state = STATE_NORMAL; + } else if (ch1 == 0xFF) { + ch2 = get_char(tok); + if (ch2 != 0xFE) { + unget_char(ch2, tok); + unget_char(ch1, tok); + return 1; + } + if (!set_readline(tok, "utf-16-le")) + return 0; + tok->decoding_state = STATE_NORMAL; #endif - } else { - unget_char(ch1, tok); - return 1; - } - if (tok->encoding != NULL) - PyMem_FREE(tok->encoding); - tok->encoding = new_string("utf-8", 5); /* resulting is in utf-8 */ - /* No need to set_readline: input is already utf-8 */ - return 1; + } else { + unget_char(ch1, tok); + return 1; + } + if (tok->encoding != NULL) + PyMem_FREE(tok->encoding); + tok->encoding = new_string("utf-8", 5); /* resulting is in utf-8 */ + /* No need to set_readline: input is already utf-8 */ + return 1; } /* Read a line of text from TOK into S, using the stream in TOK. @@ -378,74 +378,74 @@ On entry, tok->decoding_buffer will be one of: 1) NULL: need to call tok->decoding_readline to get a new line 2) PyUnicodeObject *: decoding_feof has called tok->decoding_readline and - stored the result in tok->decoding_buffer + stored the result in tok->decoding_buffer 3) PyByteArrayObject *: previous call to fp_readl did not have enough room - (in the s buffer) to copy entire contents of the line read - by tok->decoding_readline. tok->decoding_buffer has the overflow. - In this case, fp_readl is called in a loop (with an expanded buffer) - until the buffer ends with a '\n' (or until the end of the file is - reached): see tok_nextc and its calls to decoding_fgets. + (in the s buffer) to copy entire contents of the line read + by tok->decoding_readline. tok->decoding_buffer has the overflow. + In this case, fp_readl is called in a loop (with an expanded buffer) + until the buffer ends with a '\n' (or until the end of the file is + reached): see tok_nextc and its calls to decoding_fgets. */ static char * fp_readl(char *s, int size, struct tok_state *tok) { - PyObject* bufobj; - const char *buf; - Py_ssize_t buflen; - - /* Ask for one less byte so we can terminate it */ - assert(size > 0); - size--; - - if (tok->decoding_buffer) { - bufobj = tok->decoding_buffer; - Py_INCREF(bufobj); - } - else - { - bufobj = PyObject_CallObject(tok->decoding_readline, NULL); - if (bufobj == NULL) - goto error; - } - if (PyUnicode_CheckExact(bufobj)) - { - buf = _PyUnicode_AsStringAndSize(bufobj, &buflen); - if (buf == NULL) { - goto error; - } - } - else - { - buf = PyByteArray_AsString(bufobj); - if (buf == NULL) { - goto error; - } - buflen = PyByteArray_GET_SIZE(bufobj); - } - - Py_XDECREF(tok->decoding_buffer); - if (buflen > size) { - /* Too many chars, the rest goes into tok->decoding_buffer */ - tok->decoding_buffer = PyByteArray_FromStringAndSize(buf+size, - buflen-size); - if (tok->decoding_buffer == NULL) - goto error; - buflen = size; - } - else - tok->decoding_buffer = NULL; - - memcpy(s, buf, buflen); - s[buflen] = '\0'; - if (buflen == 0) /* EOF */ - s = NULL; - Py_DECREF(bufobj); - return s; + PyObject* bufobj; + const char *buf; + Py_ssize_t buflen; + + /* Ask for one less byte so we can terminate it */ + assert(size > 0); + size--; + + if (tok->decoding_buffer) { + bufobj = tok->decoding_buffer; + Py_INCREF(bufobj); + } + else + { + bufobj = PyObject_CallObject(tok->decoding_readline, NULL); + if (bufobj == NULL) + goto error; + } + if (PyUnicode_CheckExact(bufobj)) + { + buf = _PyUnicode_AsStringAndSize(bufobj, &buflen); + if (buf == NULL) { + goto error; + } + } + else + { + buf = PyByteArray_AsString(bufobj); + if (buf == NULL) { + goto error; + } + buflen = PyByteArray_GET_SIZE(bufobj); + } + + Py_XDECREF(tok->decoding_buffer); + if (buflen > size) { + /* Too many chars, the rest goes into tok->decoding_buffer */ + tok->decoding_buffer = PyByteArray_FromStringAndSize(buf+size, + buflen-size); + if (tok->decoding_buffer == NULL) + goto error; + buflen = size; + } + else + tok->decoding_buffer = NULL; + + memcpy(s, buf, buflen); + s[buflen] = '\0'; + if (buflen == 0) /* EOF */ + s = NULL; + Py_DECREF(bufobj); + return s; error: - Py_XDECREF(bufobj); - return error_ret(tok); + Py_XDECREF(bufobj); + return error_ret(tok); } /* Set the readline function for TOK to a StreamReader's @@ -461,49 +461,49 @@ static int fp_setreadl(struct tok_state *tok, const char* enc) { - PyObject *readline = NULL, *stream = NULL, *io = NULL; + PyObject *readline = NULL, *stream = NULL, *io = NULL; - io = PyImport_ImportModuleNoBlock("io"); - if (io == NULL) - goto cleanup; - - if (tok->filename) - stream = PyObject_CallMethod(io, "open", "ssis", - tok->filename, "r", -1, enc); - else - stream = PyObject_CallMethod(io, "open", "isisOOO", - fileno(tok->fp), "r", -1, enc, Py_None, Py_None, Py_False); - if (stream == NULL) - goto cleanup; - - Py_XDECREF(tok->decoding_readline); - readline = PyObject_GetAttrString(stream, "readline"); - tok->decoding_readline = readline; - - /* The file has been reopened; parsing will restart from - * the beginning of the file, we have to reset the line number. - * But this function has been called from inside tok_nextc() which - * will increment lineno before it returns. So we set it -1 so that - * the next call to tok_nextc() will start with tok->lineno == 0. - */ - tok->lineno = -1; + io = PyImport_ImportModuleNoBlock("io"); + if (io == NULL) + goto cleanup; + + if (tok->filename) + stream = PyObject_CallMethod(io, "open", "ssis", + tok->filename, "r", -1, enc); + else + stream = PyObject_CallMethod(io, "open", "isisOOO", + fileno(tok->fp), "r", -1, enc, Py_None, Py_None, Py_False); + if (stream == NULL) + goto cleanup; + + Py_XDECREF(tok->decoding_readline); + readline = PyObject_GetAttrString(stream, "readline"); + tok->decoding_readline = readline; + + /* The file has been reopened; parsing will restart from + * the beginning of the file, we have to reset the line number. + * But this function has been called from inside tok_nextc() which + * will increment lineno before it returns. So we set it -1 so that + * the next call to tok_nextc() will start with tok->lineno == 0. + */ + tok->lineno = -1; cleanup: - Py_XDECREF(stream); - Py_XDECREF(io); - return readline != NULL; + Py_XDECREF(stream); + Py_XDECREF(io); + return readline != NULL; } /* Fetch the next byte from TOK. */ static int fp_getc(struct tok_state *tok) { - return getc(tok->fp); + return getc(tok->fp); } /* Unfetch the last byte back into TOK. */ static void fp_ungetc(int c, struct tok_state *tok) { - ungetc(c, tok->fp); + ungetc(c, tok->fp); } /* Check whether the characters at s start a valid @@ -511,27 +511,27 @@ the sequence if yes, 0 if not. */ static int valid_utf8(const unsigned char* s) { - int expected = 0; - int length; - if (*s < 0x80) - /* single-byte code */ - return 1; - if (*s < 0xc0) - /* following byte */ - return 0; - if (*s < 0xE0) - expected = 1; - else if (*s < 0xF0) - expected = 2; - else if (*s < 0xF8) - expected = 3; - else - return 0; - length = expected + 1; - for (; expected; expected--) - if (s[expected] < 0x80 || s[expected] >= 0xC0) - return 0; - return length; + int expected = 0; + int length; + if (*s < 0x80) + /* single-byte code */ + return 1; + if (*s < 0xc0) + /* following byte */ + return 0; + if (*s < 0xE0) + expected = 1; + else if (*s < 0xF0) + expected = 2; + else if (*s < 0xF8) + expected = 3; + else + return 0; + length = expected + 1; + for (; expected; expected--) + if (s[expected] < 0x80 || s[expected] >= 0xC0) + return 0; + return length; } /* Read a line of input from TOK. Determine encoding @@ -540,93 +540,93 @@ static char * decoding_fgets(char *s, int size, struct tok_state *tok) { - char *line = NULL; - int badchar = 0; - for (;;) { - if (tok->decoding_state == STATE_NORMAL) { - /* We already have a codec associated with - this input. */ - line = fp_readl(s, size, tok); - break; - } else if (tok->decoding_state == STATE_RAW) { - /* We want a 'raw' read. */ - line = Py_UniversalNewlineFgets(s, size, - tok->fp, NULL); - break; - } else { - /* We have not yet determined the encoding. - If an encoding is found, use the file-pointer - reader functions from now on. */ - if (!check_bom(fp_getc, fp_ungetc, fp_setreadl, tok)) - return error_ret(tok); - assert(tok->decoding_state != STATE_INIT); - } - } - if (line != NULL && tok->lineno < 2 && !tok->read_coding_spec) { - if (!check_coding_spec(line, strlen(line), tok, fp_setreadl)) { - return error_ret(tok); - } - } + char *line = NULL; + int badchar = 0; + for (;;) { + if (tok->decoding_state == STATE_NORMAL) { + /* We already have a codec associated with + this input. */ + line = fp_readl(s, size, tok); + break; + } else if (tok->decoding_state == STATE_RAW) { + /* We want a 'raw' read. */ + line = Py_UniversalNewlineFgets(s, size, + tok->fp, NULL); + break; + } else { + /* We have not yet determined the encoding. + If an encoding is found, use the file-pointer + reader functions from now on. */ + if (!check_bom(fp_getc, fp_ungetc, fp_setreadl, tok)) + return error_ret(tok); + assert(tok->decoding_state != STATE_INIT); + } + } + if (line != NULL && tok->lineno < 2 && !tok->read_coding_spec) { + if (!check_coding_spec(line, strlen(line), tok, fp_setreadl)) { + return error_ret(tok); + } + } #ifndef PGEN - /* The default encoding is UTF-8, so make sure we don't have any - non-UTF-8 sequences in it. */ - if (line && !tok->encoding) { - unsigned char *c; - int length; - for (c = (unsigned char *)line; *c; c += length) - if (!(length = valid_utf8(c))) { - badchar = *c; - break; - } - } - if (badchar) { - /* Need to add 1 to the line number, since this line - has not been counted, yet. */ - PyErr_Format(PyExc_SyntaxError, - "Non-UTF-8 code starting with '\\x%.2x' " - "in file %.200s on line %i, " - "but no encoding declared; " - "see http://python.org/dev/peps/pep-0263/ for details", - badchar, tok->filename, tok->lineno + 1); - return error_ret(tok); - } + /* The default encoding is UTF-8, so make sure we don't have any + non-UTF-8 sequences in it. */ + if (line && !tok->encoding) { + unsigned char *c; + int length; + for (c = (unsigned char *)line; *c; c += length) + if (!(length = valid_utf8(c))) { + badchar = *c; + break; + } + } + if (badchar) { + /* Need to add 1 to the line number, since this line + has not been counted, yet. */ + PyErr_Format(PyExc_SyntaxError, + "Non-UTF-8 code starting with '\\x%.2x' " + "in file %.200s on line %i, " + "but no encoding declared; " + "see http://python.org/dev/peps/pep-0263/ for details", + badchar, tok->filename, tok->lineno + 1); + return error_ret(tok); + } #endif - return line; + return line; } static int decoding_feof(struct tok_state *tok) { - if (tok->decoding_state != STATE_NORMAL) { - return feof(tok->fp); - } else { - PyObject* buf = tok->decoding_buffer; - if (buf == NULL) { - buf = PyObject_CallObject(tok->decoding_readline, NULL); - if (buf == NULL) { - error_ret(tok); - return 1; - } else { - tok->decoding_buffer = buf; - } - } - return PyObject_Length(buf) == 0; - } + if (tok->decoding_state != STATE_NORMAL) { + return feof(tok->fp); + } else { + PyObject* buf = tok->decoding_buffer; + if (buf == NULL) { + buf = PyObject_CallObject(tok->decoding_readline, NULL); + if (buf == NULL) { + error_ret(tok); + return 1; + } else { + tok->decoding_buffer = buf; + } + } + return PyObject_Length(buf) == 0; + } } /* Fetch a byte from TOK, using the string buffer. */ static int buf_getc(struct tok_state *tok) { - return Py_CHARMASK(*tok->str++); + return Py_CHARMASK(*tok->str++); } /* Unfetch a byte from TOK, using the string buffer. */ static void buf_ungetc(int c, struct tok_state *tok) { - tok->str--; - assert(Py_CHARMASK(*tok->str) == c); /* tok->cur may point to read-only segment */ + tok->str--; + assert(Py_CHARMASK(*tok->str) == c); /* tok->cur may point to read-only segment */ } /* Set the readline function for TOK to ENC. For the string-based @@ -634,8 +634,8 @@ static int buf_setreadl(struct tok_state *tok, const char* enc) { - tok->enc = enc; - return 1; + tok->enc = enc; + return 1; } /* Return a UTF-8 encoding Python string object from the @@ -643,54 +643,54 @@ static PyObject * translate_into_utf8(const char* str, const char* enc) { - PyObject *utf8; - PyObject* buf = PyUnicode_Decode(str, strlen(str), enc, NULL); - if (buf == NULL) - return NULL; - utf8 = PyUnicode_AsUTF8String(buf); - Py_DECREF(buf); - return utf8; + PyObject *utf8; + PyObject* buf = PyUnicode_Decode(str, strlen(str), enc, NULL); + if (buf == NULL) + return NULL; + utf8 = PyUnicode_AsUTF8String(buf); + Py_DECREF(buf); + return utf8; } static char * translate_newlines(const char *s, int exec_input, struct tok_state *tok) { - int skip_next_lf = 0, needed_length = strlen(s) + 2, final_length; - char *buf, *current; - char c = '\0'; - buf = PyMem_MALLOC(needed_length); - if (buf == NULL) { - tok->done = E_NOMEM; - return NULL; - } - for (current = buf; *s; s++, current++) { - c = *s; - if (skip_next_lf) { - skip_next_lf = 0; - if (c == '\n') { - c = *++s; - if (!c) - break; - } - } - if (c == '\r') { - skip_next_lf = 1; - c = '\n'; - } - *current = c; - } - /* If this is exec input, add a newline to the end of the string if - there isn't one already. */ - if (exec_input && c != '\n') { - *current = '\n'; - current++; - } - *current = '\0'; - final_length = current - buf + 1; - if (final_length < needed_length && final_length) - /* should never fail */ - buf = PyMem_REALLOC(buf, final_length); - return buf; + int skip_next_lf = 0, needed_length = strlen(s) + 2, final_length; + char *buf, *current; + char c = '\0'; + buf = PyMem_MALLOC(needed_length); + if (buf == NULL) { + tok->done = E_NOMEM; + return NULL; + } + for (current = buf; *s; s++, current++) { + c = *s; + if (skip_next_lf) { + skip_next_lf = 0; + if (c == '\n') { + c = *++s; + if (!c) + break; + } + } + if (c == '\r') { + skip_next_lf = 1; + c = '\n'; + } + *current = c; + } + /* If this is exec input, add a newline to the end of the string if + there isn't one already. */ + if (exec_input && c != '\n') { + *current = '\n'; + current++; + } + *current = '\0'; + final_length = current - buf + 1; + if (final_length < needed_length && final_length) + /* should never fail */ + buf = PyMem_REALLOC(buf, final_length); + return buf; } /* Decode a byte string STR for use as the buffer of TOK. @@ -700,57 +700,57 @@ static const char * decode_str(const char *input, int single, struct tok_state *tok) { - PyObject* utf8 = NULL; - const char *str; - const char *s; - const char *newl[2] = {NULL, NULL}; - int lineno = 0; - tok->input = str = translate_newlines(input, single, tok); - if (str == NULL) - return NULL; - tok->enc = NULL; - tok->str = str; - if (!check_bom(buf_getc, buf_ungetc, buf_setreadl, tok)) - return error_ret(tok); - str = tok->str; /* string after BOM if any */ - assert(str); - if (tok->enc != NULL) { - utf8 = translate_into_utf8(str, tok->enc); - if (utf8 == NULL) - return error_ret(tok); - str = PyBytes_AsString(utf8); - } - for (s = str;; s++) { - if (*s == '\0') break; - else if (*s == '\n') { - assert(lineno < 2); - newl[lineno] = s; - lineno++; - if (lineno == 2) break; - } - } - tok->enc = NULL; - /* need to check line 1 and 2 separately since check_coding_spec - assumes a single line as input */ - if (newl[0]) { - if (!check_coding_spec(str, newl[0] - str, tok, buf_setreadl)) - return error_ret(tok); - if (tok->enc == NULL && newl[1]) { - if (!check_coding_spec(newl[0]+1, newl[1] - newl[0], - tok, buf_setreadl)) - return error_ret(tok); - } - } - if (tok->enc != NULL) { - assert(utf8 == NULL); - utf8 = translate_into_utf8(str, tok->enc); - if (utf8 == NULL) - return error_ret(tok); - str = PyBytes_AS_STRING(utf8); - } - assert(tok->decoding_buffer == NULL); - tok->decoding_buffer = utf8; /* CAUTION */ - return str; + PyObject* utf8 = NULL; + const char *str; + const char *s; + const char *newl[2] = {NULL, NULL}; + int lineno = 0; + tok->input = str = translate_newlines(input, single, tok); + if (str == NULL) + return NULL; + tok->enc = NULL; + tok->str = str; + if (!check_bom(buf_getc, buf_ungetc, buf_setreadl, tok)) + return error_ret(tok); + str = tok->str; /* string after BOM if any */ + assert(str); + if (tok->enc != NULL) { + utf8 = translate_into_utf8(str, tok->enc); + if (utf8 == NULL) + return error_ret(tok); + str = PyBytes_AsString(utf8); + } + for (s = str;; s++) { + if (*s == '\0') break; + else if (*s == '\n') { + assert(lineno < 2); + newl[lineno] = s; + lineno++; + if (lineno == 2) break; + } + } + tok->enc = NULL; + /* need to check line 1 and 2 separately since check_coding_spec + assumes a single line as input */ + if (newl[0]) { + if (!check_coding_spec(str, newl[0] - str, tok, buf_setreadl)) + return error_ret(tok); + if (tok->enc == NULL && newl[1]) { + if (!check_coding_spec(newl[0]+1, newl[1] - newl[0], + tok, buf_setreadl)) + return error_ret(tok); + } + } + if (tok->enc != NULL) { + assert(utf8 == NULL); + utf8 = translate_into_utf8(str, tok->enc); + if (utf8 == NULL) + return error_ret(tok); + str = PyBytes_AS_STRING(utf8); + } + assert(tok->decoding_buffer == NULL); + tok->decoding_buffer = utf8; /* CAUTION */ + return str; } #endif /* PGEN */ @@ -760,47 +760,47 @@ struct tok_state * PyTokenizer_FromString(const char *str, int exec_input) { - struct tok_state *tok = tok_new(); - if (tok == NULL) - return NULL; - str = (char *)decode_str(str, exec_input, tok); - if (str == NULL) { - PyTokenizer_Free(tok); - return NULL; - } - - /* XXX: constify members. */ - tok->buf = tok->cur = tok->end = tok->inp = (char*)str; - return tok; + struct tok_state *tok = tok_new(); + if (tok == NULL) + return NULL; + str = (char *)decode_str(str, exec_input, tok); + if (str == NULL) { + PyTokenizer_Free(tok); + return NULL; + } + + /* XXX: constify members. */ + tok->buf = tok->cur = tok->end = tok->inp = (char*)str; + return tok; } struct tok_state * PyTokenizer_FromUTF8(const char *str, int exec_input) { - struct tok_state *tok = tok_new(); - if (tok == NULL) - return NULL; + struct tok_state *tok = tok_new(); + if (tok == NULL) + return NULL; #ifndef PGEN - tok->input = str = translate_newlines(str, exec_input, tok); + tok->input = str = translate_newlines(str, exec_input, tok); #endif - if (str == NULL) { - PyTokenizer_Free(tok); - return NULL; - } - tok->decoding_state = STATE_RAW; - tok->read_coding_spec = 1; - tok->enc = NULL; - tok->str = str; - tok->encoding = (char *)PyMem_MALLOC(6); - if (!tok->encoding) { - PyTokenizer_Free(tok); - return NULL; - } - strcpy(tok->encoding, "utf-8"); - - /* XXX: constify members. */ - tok->buf = tok->cur = tok->end = tok->inp = (char*)str; - return tok; + if (str == NULL) { + PyTokenizer_Free(tok); + return NULL; + } + tok->decoding_state = STATE_RAW; + tok->read_coding_spec = 1; + tok->enc = NULL; + tok->str = str; + tok->encoding = (char *)PyMem_MALLOC(6); + if (!tok->encoding) { + PyTokenizer_Free(tok); + return NULL; + } + strcpy(tok->encoding, "utf-8"); + + /* XXX: constify members. */ + tok->buf = tok->cur = tok->end = tok->inp = (char*)str; + return tok; } /* Set up tokenizer for file */ @@ -808,30 +808,30 @@ struct tok_state * PyTokenizer_FromFile(FILE *fp, char* enc, char *ps1, char *ps2) { - struct tok_state *tok = tok_new(); - if (tok == NULL) - return NULL; - if ((tok->buf = (char *)PyMem_MALLOC(BUFSIZ)) == NULL) { - PyTokenizer_Free(tok); - return NULL; - } - tok->cur = tok->inp = tok->buf; - tok->end = tok->buf + BUFSIZ; - tok->fp = fp; - tok->prompt = ps1; - tok->nextprompt = ps2; - if (enc != NULL) { - /* Must copy encoding declaration since it - gets copied into the parse tree. */ - tok->encoding = PyMem_MALLOC(strlen(enc)+1); - if (!tok->encoding) { - PyTokenizer_Free(tok); - return NULL; - } - strcpy(tok->encoding, enc); - tok->decoding_state = STATE_NORMAL; - } - return tok; + struct tok_state *tok = tok_new(); + if (tok == NULL) + return NULL; + if ((tok->buf = (char *)PyMem_MALLOC(BUFSIZ)) == NULL) { + PyTokenizer_Free(tok); + return NULL; + } + tok->cur = tok->inp = tok->buf; + tok->end = tok->buf + BUFSIZ; + tok->fp = fp; + tok->prompt = ps1; + tok->nextprompt = ps2; + if (enc != NULL) { + /* Must copy encoding declaration since it + gets copied into the parse tree. */ + tok->encoding = PyMem_MALLOC(strlen(enc)+1); + if (!tok->encoding) { + PyTokenizer_Free(tok); + return NULL; + } + strcpy(tok->encoding, enc); + tok->decoding_state = STATE_NORMAL; + } + return tok; } @@ -840,17 +840,17 @@ void PyTokenizer_Free(struct tok_state *tok) { - if (tok->encoding != NULL) - PyMem_FREE(tok->encoding); + if (tok->encoding != NULL) + PyMem_FREE(tok->encoding); #ifndef PGEN - Py_XDECREF(tok->decoding_readline); - Py_XDECREF(tok->decoding_buffer); + Py_XDECREF(tok->decoding_readline); + Py_XDECREF(tok->decoding_buffer); #endif - if (tok->fp != NULL && tok->buf != NULL) - PyMem_FREE(tok->buf); - if (tok->input) - PyMem_FREE((char *)tok->input); - PyMem_FREE(tok); + if (tok->fp != NULL && tok->buf != NULL) + PyMem_FREE(tok->buf); + if (tok->input) + PyMem_FREE((char *)tok->input); + PyMem_FREE(tok); } /* Get next char, updating state; error code goes into tok->done */ @@ -858,188 +858,188 @@ static int tok_nextc(register struct tok_state *tok) { - for (;;) { - if (tok->cur != tok->inp) { - return Py_CHARMASK(*tok->cur++); /* Fast path */ - } - if (tok->done != E_OK) - return EOF; - if (tok->fp == NULL) { - char *end = strchr(tok->inp, '\n'); - if (end != NULL) - end++; - else { - end = strchr(tok->inp, '\0'); - if (end == tok->inp) { - tok->done = E_EOF; - return EOF; - } - } - if (tok->start == NULL) - tok->buf = tok->cur; - tok->line_start = tok->cur; - tok->lineno++; - tok->inp = end; - return Py_CHARMASK(*tok->cur++); - } - if (tok->prompt != NULL) { - char *newtok = PyOS_Readline(stdin, stdout, tok->prompt); + for (;;) { + if (tok->cur != tok->inp) { + return Py_CHARMASK(*tok->cur++); /* Fast path */ + } + if (tok->done != E_OK) + return EOF; + if (tok->fp == NULL) { + char *end = strchr(tok->inp, '\n'); + if (end != NULL) + end++; + else { + end = strchr(tok->inp, '\0'); + if (end == tok->inp) { + tok->done = E_EOF; + return EOF; + } + } + if (tok->start == NULL) + tok->buf = tok->cur; + tok->line_start = tok->cur; + tok->lineno++; + tok->inp = end; + return Py_CHARMASK(*tok->cur++); + } + if (tok->prompt != NULL) { + char *newtok = PyOS_Readline(stdin, stdout, tok->prompt); #ifndef PGEN - if (tok->encoding && newtok && *newtok) { - /* Recode to UTF-8 */ - Py_ssize_t buflen; - const char* buf; - PyObject *u = translate_into_utf8(newtok, tok->encoding); - PyMem_FREE(newtok); - if (!u) { - tok->done = E_DECODE; - return EOF; - } - buflen = PyBytes_GET_SIZE(u); - buf = PyBytes_AS_STRING(u); - if (!buf) { - Py_DECREF(u); - tok->done = E_DECODE; - return EOF; - } - newtok = PyMem_MALLOC(buflen+1); - strcpy(newtok, buf); - Py_DECREF(u); - } + if (tok->encoding && newtok && *newtok) { + /* Recode to UTF-8 */ + Py_ssize_t buflen; + const char* buf; + PyObject *u = translate_into_utf8(newtok, tok->encoding); + PyMem_FREE(newtok); + if (!u) { + tok->done = E_DECODE; + return EOF; + } + buflen = PyBytes_GET_SIZE(u); + buf = PyBytes_AS_STRING(u); + if (!buf) { + Py_DECREF(u); + tok->done = E_DECODE; + return EOF; + } + newtok = PyMem_MALLOC(buflen+1); + strcpy(newtok, buf); + Py_DECREF(u); + } #endif - if (tok->nextprompt != NULL) - tok->prompt = tok->nextprompt; - if (newtok == NULL) - tok->done = E_INTR; - else if (*newtok == '\0') { - PyMem_FREE(newtok); - tok->done = E_EOF; - } - else if (tok->start != NULL) { - size_t start = tok->start - tok->buf; - size_t oldlen = tok->cur - tok->buf; - size_t newlen = oldlen + strlen(newtok); - char *buf = tok->buf; - buf = (char *)PyMem_REALLOC(buf, newlen+1); - tok->lineno++; - if (buf == NULL) { - PyMem_FREE(tok->buf); - tok->buf = NULL; - PyMem_FREE(newtok); - tok->done = E_NOMEM; - return EOF; - } - tok->buf = buf; - tok->cur = tok->buf + oldlen; - tok->line_start = tok->cur; - strcpy(tok->buf + oldlen, newtok); - PyMem_FREE(newtok); - tok->inp = tok->buf + newlen; - tok->end = tok->inp + 1; - tok->start = tok->buf + start; - } - else { - tok->lineno++; - if (tok->buf != NULL) - PyMem_FREE(tok->buf); - tok->buf = newtok; - tok->line_start = tok->buf; - tok->cur = tok->buf; - tok->line_start = tok->buf; - tok->inp = strchr(tok->buf, '\0'); - tok->end = tok->inp + 1; - } - } - else { - int done = 0; - Py_ssize_t cur = 0; - char *pt; - if (tok->start == NULL) { - if (tok->buf == NULL) { - tok->buf = (char *) - PyMem_MALLOC(BUFSIZ); - if (tok->buf == NULL) { - tok->done = E_NOMEM; - return EOF; - } - tok->end = tok->buf + BUFSIZ; - } - if (decoding_fgets(tok->buf, (int)(tok->end - tok->buf), - tok) == NULL) { - tok->done = E_EOF; - done = 1; - } - else { - tok->done = E_OK; - tok->inp = strchr(tok->buf, '\0'); - done = tok->inp[-1] == '\n'; - } - } - else { - cur = tok->cur - tok->buf; - if (decoding_feof(tok)) { - tok->done = E_EOF; - done = 1; - } - else - tok->done = E_OK; - } - tok->lineno++; - /* Read until '\n' or EOF */ - while (!done) { - Py_ssize_t curstart = tok->start == NULL ? -1 : - tok->start - tok->buf; - Py_ssize_t curvalid = tok->inp - tok->buf; - Py_ssize_t newsize = curvalid + BUFSIZ; - char *newbuf = tok->buf; - newbuf = (char *)PyMem_REALLOC(newbuf, - newsize); - if (newbuf == NULL) { - tok->done = E_NOMEM; - tok->cur = tok->inp; - return EOF; - } - tok->buf = newbuf; - tok->inp = tok->buf + curvalid; - tok->end = tok->buf + newsize; - tok->start = curstart < 0 ? NULL : - tok->buf + curstart; - if (decoding_fgets(tok->inp, - (int)(tok->end - tok->inp), - tok) == NULL) { - /* Break out early on decoding - errors, as tok->buf will be NULL - */ - if (tok->decoding_erred) - return EOF; - /* Last line does not end in \n, - fake one */ - strcpy(tok->inp, "\n"); - } - tok->inp = strchr(tok->inp, '\0'); - done = tok->inp[-1] == '\n'; - } - if (tok->buf != NULL) { - tok->cur = tok->buf + cur; - tok->line_start = tok->cur; - /* replace "\r\n" with "\n" */ - /* For Mac leave the \r, giving a syntax error */ - pt = tok->inp - 2; - if (pt >= tok->buf && *pt == '\r') { - *pt++ = '\n'; - *pt = '\0'; - tok->inp = pt; - } - } - } - if (tok->done != E_OK) { - if (tok->prompt != NULL) - PySys_WriteStderr("\n"); - tok->cur = tok->inp; - return EOF; - } - } - /*NOTREACHED*/ + if (tok->nextprompt != NULL) + tok->prompt = tok->nextprompt; + if (newtok == NULL) + tok->done = E_INTR; + else if (*newtok == '\0') { + PyMem_FREE(newtok); + tok->done = E_EOF; + } + else if (tok->start != NULL) { + size_t start = tok->start - tok->buf; + size_t oldlen = tok->cur - tok->buf; + size_t newlen = oldlen + strlen(newtok); + char *buf = tok->buf; + buf = (char *)PyMem_REALLOC(buf, newlen+1); + tok->lineno++; + if (buf == NULL) { + PyMem_FREE(tok->buf); + tok->buf = NULL; + PyMem_FREE(newtok); + tok->done = E_NOMEM; + return EOF; + } + tok->buf = buf; + tok->cur = tok->buf + oldlen; + tok->line_start = tok->cur; + strcpy(tok->buf + oldlen, newtok); + PyMem_FREE(newtok); + tok->inp = tok->buf + newlen; + tok->end = tok->inp + 1; + tok->start = tok->buf + start; + } + else { + tok->lineno++; + if (tok->buf != NULL) + PyMem_FREE(tok->buf); + tok->buf = newtok; + tok->line_start = tok->buf; + tok->cur = tok->buf; + tok->line_start = tok->buf; + tok->inp = strchr(tok->buf, '\0'); + tok->end = tok->inp + 1; + } + } + else { + int done = 0; + Py_ssize_t cur = 0; + char *pt; + if (tok->start == NULL) { + if (tok->buf == NULL) { + tok->buf = (char *) + PyMem_MALLOC(BUFSIZ); + if (tok->buf == NULL) { + tok->done = E_NOMEM; + return EOF; + } + tok->end = tok->buf + BUFSIZ; + } + if (decoding_fgets(tok->buf, (int)(tok->end - tok->buf), + tok) == NULL) { + tok->done = E_EOF; + done = 1; + } + else { + tok->done = E_OK; + tok->inp = strchr(tok->buf, '\0'); + done = tok->inp[-1] == '\n'; + } + } + else { + cur = tok->cur - tok->buf; + if (decoding_feof(tok)) { + tok->done = E_EOF; + done = 1; + } + else + tok->done = E_OK; + } + tok->lineno++; + /* Read until '\n' or EOF */ + while (!done) { + Py_ssize_t curstart = tok->start == NULL ? -1 : + tok->start - tok->buf; + Py_ssize_t curvalid = tok->inp - tok->buf; + Py_ssize_t newsize = curvalid + BUFSIZ; + char *newbuf = tok->buf; + newbuf = (char *)PyMem_REALLOC(newbuf, + newsize); + if (newbuf == NULL) { + tok->done = E_NOMEM; + tok->cur = tok->inp; + return EOF; + } + tok->buf = newbuf; + tok->inp = tok->buf + curvalid; + tok->end = tok->buf + newsize; + tok->start = curstart < 0 ? NULL : + tok->buf + curstart; + if (decoding_fgets(tok->inp, + (int)(tok->end - tok->inp), + tok) == NULL) { + /* Break out early on decoding + errors, as tok->buf will be NULL + */ + if (tok->decoding_erred) + return EOF; + /* Last line does not end in \n, + fake one */ + strcpy(tok->inp, "\n"); + } + tok->inp = strchr(tok->inp, '\0'); + done = tok->inp[-1] == '\n'; + } + if (tok->buf != NULL) { + tok->cur = tok->buf + cur; + tok->line_start = tok->cur; + /* replace "\r\n" with "\n" */ + /* For Mac leave the \r, giving a syntax error */ + pt = tok->inp - 2; + if (pt >= tok->buf && *pt == '\r') { + *pt++ = '\n'; + *pt = '\0'; + tok->inp = pt; + } + } + } + if (tok->done != E_OK) { + if (tok->prompt != NULL) + PySys_WriteStderr("\n"); + tok->cur = tok->inp; + return EOF; + } + } + /*NOTREACHED*/ } @@ -1048,12 +1048,12 @@ static void tok_backup(register struct tok_state *tok, register int c) { - if (c != EOF) { - if (--tok->cur < tok->buf) - Py_FatalError("tok_backup: beginning of buffer"); - if (*tok->cur != c) - *tok->cur = c; - } + if (c != EOF) { + if (--tok->cur < tok->buf) + Py_FatalError("tok_backup: beginning of buffer"); + if (*tok->cur != c) + *tok->cur = c; + } } @@ -1062,181 +1062,181 @@ int PyToken_OneChar(int c) { - switch (c) { - case '(': return LPAR; - case ')': return RPAR; - case '[': return LSQB; - case ']': return RSQB; - case ':': return COLON; - case ',': return COMMA; - case ';': return SEMI; - case '+': return PLUS; - case '-': return MINUS; - case '*': return STAR; - case '/': return SLASH; - case '|': return VBAR; - case '&': return AMPER; - case '<': return LESS; - case '>': return GREATER; - case '=': return EQUAL; - case '.': return DOT; - case '%': return PERCENT; - case '{': return LBRACE; - case '}': return RBRACE; - case '^': return CIRCUMFLEX; - case '~': return TILDE; - case '@': return AT; - default: return OP; - } + switch (c) { + case '(': return LPAR; + case ')': return RPAR; + case '[': return LSQB; + case ']': return RSQB; + case ':': return COLON; + case ',': return COMMA; + case ';': return SEMI; + case '+': return PLUS; + case '-': return MINUS; + case '*': return STAR; + case '/': return SLASH; + case '|': return VBAR; + case '&': return AMPER; + case '<': return LESS; + case '>': return GREATER; + case '=': return EQUAL; + case '.': return DOT; + case '%': return PERCENT; + case '{': return LBRACE; + case '}': return RBRACE; + case '^': return CIRCUMFLEX; + case '~': return TILDE; + case '@': return AT; + default: return OP; + } } int PyToken_TwoChars(int c1, int c2) { - switch (c1) { - case '=': - switch (c2) { - case '=': return EQEQUAL; - } - break; - case '!': - switch (c2) { - case '=': return NOTEQUAL; - } - break; - case '<': - switch (c2) { - case '>': return NOTEQUAL; - case '=': return LESSEQUAL; - case '<': return LEFTSHIFT; - } - break; - case '>': - switch (c2) { - case '=': return GREATEREQUAL; - case '>': return RIGHTSHIFT; - } - break; - case '+': - switch (c2) { - case '=': return PLUSEQUAL; - } - break; - case '-': - switch (c2) { - case '=': return MINEQUAL; - case '>': return RARROW; - } - break; - case '*': - switch (c2) { - case '*': return DOUBLESTAR; - case '=': return STAREQUAL; - } - break; - case '/': - switch (c2) { - case '/': return DOUBLESLASH; - case '=': return SLASHEQUAL; - } - break; - case '|': - switch (c2) { - case '=': return VBAREQUAL; - } - break; - case '%': - switch (c2) { - case '=': return PERCENTEQUAL; - } - break; - case '&': - switch (c2) { - case '=': return AMPEREQUAL; - } - break; - case '^': - switch (c2) { - case '=': return CIRCUMFLEXEQUAL; - } - break; - } - return OP; + switch (c1) { + case '=': + switch (c2) { + case '=': return EQEQUAL; + } + break; + case '!': + switch (c2) { + case '=': return NOTEQUAL; + } + break; + case '<': + switch (c2) { + case '>': return NOTEQUAL; + case '=': return LESSEQUAL; + case '<': return LEFTSHIFT; + } + break; + case '>': + switch (c2) { + case '=': return GREATEREQUAL; + case '>': return RIGHTSHIFT; + } + break; + case '+': + switch (c2) { + case '=': return PLUSEQUAL; + } + break; + case '-': + switch (c2) { + case '=': return MINEQUAL; + case '>': return RARROW; + } + break; + case '*': + switch (c2) { + case '*': return DOUBLESTAR; + case '=': return STAREQUAL; + } + break; + case '/': + switch (c2) { + case '/': return DOUBLESLASH; + case '=': return SLASHEQUAL; + } + break; + case '|': + switch (c2) { + case '=': return VBAREQUAL; + } + break; + case '%': + switch (c2) { + case '=': return PERCENTEQUAL; + } + break; + case '&': + switch (c2) { + case '=': return AMPEREQUAL; + } + break; + case '^': + switch (c2) { + case '=': return CIRCUMFLEXEQUAL; + } + break; + } + return OP; } int PyToken_ThreeChars(int c1, int c2, int c3) { - switch (c1) { - case '<': - switch (c2) { - case '<': - switch (c3) { - case '=': - return LEFTSHIFTEQUAL; - } - break; - } - break; - case '>': - switch (c2) { - case '>': - switch (c3) { - case '=': - return RIGHTSHIFTEQUAL; - } - break; - } - break; - case '*': - switch (c2) { - case '*': - switch (c3) { - case '=': - return DOUBLESTAREQUAL; - } - break; - } - break; - case '/': - switch (c2) { - case '/': - switch (c3) { - case '=': - return DOUBLESLASHEQUAL; - } - break; - } - break; + switch (c1) { + case '<': + switch (c2) { + case '<': + switch (c3) { + case '=': + return LEFTSHIFTEQUAL; + } + break; + } + break; + case '>': + switch (c2) { + case '>': + switch (c3) { + case '=': + return RIGHTSHIFTEQUAL; + } + break; + } + break; + case '*': + switch (c2) { + case '*': + switch (c3) { + case '=': + return DOUBLESTAREQUAL; + } + break; + } + break; + case '/': + switch (c2) { + case '/': + switch (c3) { + case '=': + return DOUBLESLASHEQUAL; + } + break; + } + break; + case '.': + switch (c2) { case '.': - switch (c2) { - case '.': - switch (c3) { - case '.': - return ELLIPSIS; - } - break; - } - break; - } - return OP; + switch (c3) { + case '.': + return ELLIPSIS; + } + break; + } + break; + } + return OP; } static int indenterror(struct tok_state *tok) { - if (tok->alterror) { - tok->done = E_TABSPACE; - tok->cur = tok->inp; - return 1; - } - if (tok->altwarning) { - PySys_WriteStderr("%s: inconsistent use of tabs and spaces " - "in indentation\n", tok->filename); - tok->altwarning = 0; - } - return 0; + if (tok->alterror) { + tok->done = E_TABSPACE; + tok->cur = tok->inp; + return 1; + } + if (tok->altwarning) { + PySys_WriteStderr("%s: inconsistent use of tabs and spaces " + "in indentation\n", tok->filename); + tok->altwarning = 0; + } + return 0; } #ifdef PGEN @@ -1246,23 +1246,23 @@ static int verify_identifier(struct tok_state *tok) { - PyObject *s; - int result; - s = PyUnicode_DecodeUTF8(tok->start, tok->cur - tok->start, NULL); - if (s == NULL) { - if (PyErr_ExceptionMatches(PyExc_UnicodeDecodeError)) { - PyErr_Clear(); - tok->done = E_IDENTIFIER; - } else { - tok->done = E_ERROR; - } - return 0; - } - result = PyUnicode_IsIdentifier(s); - Py_DECREF(s); - if (result == 0) - tok->done = E_IDENTIFIER; - return result; + PyObject *s; + int result; + s = PyUnicode_DecodeUTF8(tok->start, tok->cur - tok->start, NULL); + if (s == NULL) { + if (PyErr_ExceptionMatches(PyExc_UnicodeDecodeError)) { + PyErr_Clear(); + tok->done = E_IDENTIFIER; + } else { + tok->done = E_ERROR; + } + return 0; + } + result = PyUnicode_IsIdentifier(s); + Py_DECREF(s); + if (result == 0) + tok->done = E_IDENTIFIER; + return result; } #endif @@ -1271,407 +1271,407 @@ static int tok_get(register struct tok_state *tok, char **p_start, char **p_end) { - register int c; - int blankline, nonascii; + register int c; + int blankline, nonascii; - *p_start = *p_end = NULL; + *p_start = *p_end = NULL; nextline: - tok->start = NULL; - blankline = 0; + tok->start = NULL; + blankline = 0; - /* Get indentation level */ - if (tok->atbol) { - register int col = 0; - register int altcol = 0; - tok->atbol = 0; - for (;;) { - c = tok_nextc(tok); - if (c == ' ') - col++, altcol++; - else if (c == '\t') { - col = (col/tok->tabsize + 1) * tok->tabsize; - altcol = (altcol/tok->alttabsize + 1) - * tok->alttabsize; - } - else if (c == '\014') /* Control-L (formfeed) */ - col = altcol = 0; /* For Emacs users */ - else - break; - } - tok_backup(tok, c); - if (c == '#' || c == '\n') { - /* Lines with only whitespace and/or comments - shouldn't affect the indentation and are - not passed to the parser as NEWLINE tokens, - except *totally* empty lines in interactive - mode, which signal the end of a command group. */ - if (col == 0 && c == '\n' && tok->prompt != NULL) - blankline = 0; /* Let it through */ - else - blankline = 1; /* Ignore completely */ - /* We can't jump back right here since we still - may need to skip to the end of a comment */ - } - if (!blankline && tok->level == 0) { - if (col == tok->indstack[tok->indent]) { - /* No change */ - if (altcol != tok->altindstack[tok->indent]) { - if (indenterror(tok)) - return ERRORTOKEN; - } - } - else if (col > tok->indstack[tok->indent]) { - /* Indent -- always one */ - if (tok->indent+1 >= MAXINDENT) { - tok->done = E_TOODEEP; - tok->cur = tok->inp; - return ERRORTOKEN; - } - if (altcol <= tok->altindstack[tok->indent]) { - if (indenterror(tok)) - return ERRORTOKEN; - } - tok->pendin++; - tok->indstack[++tok->indent] = col; - tok->altindstack[tok->indent] = altcol; - } - else /* col < tok->indstack[tok->indent] */ { - /* Dedent -- any number, must be consistent */ - while (tok->indent > 0 && - col < tok->indstack[tok->indent]) { - tok->pendin--; - tok->indent--; - } - if (col != tok->indstack[tok->indent]) { - tok->done = E_DEDENT; - tok->cur = tok->inp; - return ERRORTOKEN; - } - if (altcol != tok->altindstack[tok->indent]) { - if (indenterror(tok)) - return ERRORTOKEN; - } - } - } - } - - tok->start = tok->cur; - - /* Return pending indents/dedents */ - if (tok->pendin != 0) { - if (tok->pendin < 0) { - tok->pendin++; - return DEDENT; - } - else { - tok->pendin--; - return INDENT; - } - } + /* Get indentation level */ + if (tok->atbol) { + register int col = 0; + register int altcol = 0; + tok->atbol = 0; + for (;;) { + c = tok_nextc(tok); + if (c == ' ') + col++, altcol++; + else if (c == '\t') { + col = (col/tok->tabsize + 1) * tok->tabsize; + altcol = (altcol/tok->alttabsize + 1) + * tok->alttabsize; + } + else if (c == '\014') /* Control-L (formfeed) */ + col = altcol = 0; /* For Emacs users */ + else + break; + } + tok_backup(tok, c); + if (c == '#' || c == '\n') { + /* Lines with only whitespace and/or comments + shouldn't affect the indentation and are + not passed to the parser as NEWLINE tokens, + except *totally* empty lines in interactive + mode, which signal the end of a command group. */ + if (col == 0 && c == '\n' && tok->prompt != NULL) + blankline = 0; /* Let it through */ + else + blankline = 1; /* Ignore completely */ + /* We can't jump back right here since we still + may need to skip to the end of a comment */ + } + if (!blankline && tok->level == 0) { + if (col == tok->indstack[tok->indent]) { + /* No change */ + if (altcol != tok->altindstack[tok->indent]) { + if (indenterror(tok)) + return ERRORTOKEN; + } + } + else if (col > tok->indstack[tok->indent]) { + /* Indent -- always one */ + if (tok->indent+1 >= MAXINDENT) { + tok->done = E_TOODEEP; + tok->cur = tok->inp; + return ERRORTOKEN; + } + if (altcol <= tok->altindstack[tok->indent]) { + if (indenterror(tok)) + return ERRORTOKEN; + } + tok->pendin++; + tok->indstack[++tok->indent] = col; + tok->altindstack[tok->indent] = altcol; + } + else /* col < tok->indstack[tok->indent] */ { + /* Dedent -- any number, must be consistent */ + while (tok->indent > 0 && + col < tok->indstack[tok->indent]) { + tok->pendin--; + tok->indent--; + } + if (col != tok->indstack[tok->indent]) { + tok->done = E_DEDENT; + tok->cur = tok->inp; + return ERRORTOKEN; + } + if (altcol != tok->altindstack[tok->indent]) { + if (indenterror(tok)) + return ERRORTOKEN; + } + } + } + } + + tok->start = tok->cur; + + /* Return pending indents/dedents */ + if (tok->pendin != 0) { + if (tok->pendin < 0) { + tok->pendin++; + return DEDENT; + } + else { + tok->pendin--; + return INDENT; + } + } again: - tok->start = NULL; - /* Skip spaces */ - do { - c = tok_nextc(tok); - } while (c == ' ' || c == '\t' || c == '\014'); - - /* Set start of current token */ - tok->start = tok->cur - 1; - - /* Skip comment */ - if (c == '#') - while (c != EOF && c != '\n') - c = tok_nextc(tok); - - /* Check for EOF and errors now */ - if (c == EOF) { - return tok->done == E_EOF ? ENDMARKER : ERRORTOKEN; - } - - /* Identifier (most frequent token!) */ - nonascii = 0; - if (is_potential_identifier_start(c)) { - /* Process b"", r"" and br"" */ - if (c == 'b' || c == 'B') { - c = tok_nextc(tok); - if (c == '"' || c == '\'') - goto letter_quote; - } - if (c == 'r' || c == 'R') { - c = tok_nextc(tok); - if (c == '"' || c == '\'') - goto letter_quote; - } - while (is_potential_identifier_char(c)) { - if (c >= 128) - nonascii = 1; - c = tok_nextc(tok); - } - tok_backup(tok, c); - if (nonascii && - !verify_identifier(tok)) { - tok->done = E_IDENTIFIER; - return ERRORTOKEN; - } - *p_start = tok->start; - *p_end = tok->cur; - return NAME; - } - - /* Newline */ - if (c == '\n') { - tok->atbol = 1; - if (blankline || tok->level > 0) - goto nextline; - *p_start = tok->start; - *p_end = tok->cur - 1; /* Leave '\n' out of the string */ - tok->cont_line = 0; - return NEWLINE; - } - - /* Period or number starting with period? */ - if (c == '.') { - c = tok_nextc(tok); - if (isdigit(c)) { - goto fraction; - } else if (c == '.') { - c = tok_nextc(tok); - if (c == '.') { - *p_start = tok->start; - *p_end = tok->cur; - return ELLIPSIS; - } else { - tok_backup(tok, c); - } - tok_backup(tok, '.'); - } else { - tok_backup(tok, c); - } - *p_start = tok->start; - *p_end = tok->cur; - return DOT; - } - - /* Number */ - if (isdigit(c)) { - if (c == '0') { - /* Hex, octal or binary -- maybe. */ - c = tok_nextc(tok); - if (c == '.') - goto fraction; - if (c == 'j' || c == 'J') - goto imaginary; - if (c == 'x' || c == 'X') { - - /* Hex */ - c = tok_nextc(tok); - if (!isxdigit(c)) { - tok->done = E_TOKEN; - tok_backup(tok, c); - return ERRORTOKEN; - } - do { - c = tok_nextc(tok); - } while (isxdigit(c)); - } - else if (c == 'o' || c == 'O') { - /* Octal */ - c = tok_nextc(tok); - if (c < '0' || c >= '8') { - tok->done = E_TOKEN; - tok_backup(tok, c); - return ERRORTOKEN; - } - do { - c = tok_nextc(tok); - } while ('0' <= c && c < '8'); - } - else if (c == 'b' || c == 'B') { - /* Binary */ - c = tok_nextc(tok); - if (c != '0' && c != '1') { - tok->done = E_TOKEN; - tok_backup(tok, c); - return ERRORTOKEN; - } - do { - c = tok_nextc(tok); - } while (c == '0' || c == '1'); - } - else { - int nonzero = 0; - /* maybe old-style octal; c is first char of it */ - /* in any case, allow '0' as a literal */ - while (c == '0') - c = tok_nextc(tok); - while (isdigit(c)) { - nonzero = 1; - c = tok_nextc(tok); - } - if (c == '.') - goto fraction; - else if (c == 'e' || c == 'E') - goto exponent; - else if (c == 'j' || c == 'J') - goto imaginary; - else if (nonzero) { - tok->done = E_TOKEN; - tok_backup(tok, c); - return ERRORTOKEN; - } - } - } - else { - /* Decimal */ - do { - c = tok_nextc(tok); - } while (isdigit(c)); - { - /* Accept floating point numbers. */ - if (c == '.') { - fraction: - /* Fraction */ - do { - c = tok_nextc(tok); - } while (isdigit(c)); - } - if (c == 'e' || c == 'E') { - exponent: - /* Exponent part */ - c = tok_nextc(tok); - if (c == '+' || c == '-') - c = tok_nextc(tok); - if (!isdigit(c)) { - tok->done = E_TOKEN; - tok_backup(tok, c); - return ERRORTOKEN; - } - do { - c = tok_nextc(tok); - } while (isdigit(c)); - } - if (c == 'j' || c == 'J') - /* Imaginary part */ - imaginary: - c = tok_nextc(tok); - } - } - tok_backup(tok, c); - *p_start = tok->start; - *p_end = tok->cur; - return NUMBER; - } + tok->start = NULL; + /* Skip spaces */ + do { + c = tok_nextc(tok); + } while (c == ' ' || c == '\t' || c == '\014'); + + /* Set start of current token */ + tok->start = tok->cur - 1; + + /* Skip comment */ + if (c == '#') + while (c != EOF && c != '\n') + c = tok_nextc(tok); + + /* Check for EOF and errors now */ + if (c == EOF) { + return tok->done == E_EOF ? ENDMARKER : ERRORTOKEN; + } + + /* Identifier (most frequent token!) */ + nonascii = 0; + if (is_potential_identifier_start(c)) { + /* Process b"", r"" and br"" */ + if (c == 'b' || c == 'B') { + c = tok_nextc(tok); + if (c == '"' || c == '\'') + goto letter_quote; + } + if (c == 'r' || c == 'R') { + c = tok_nextc(tok); + if (c == '"' || c == '\'') + goto letter_quote; + } + while (is_potential_identifier_char(c)) { + if (c >= 128) + nonascii = 1; + c = tok_nextc(tok); + } + tok_backup(tok, c); + if (nonascii && + !verify_identifier(tok)) { + tok->done = E_IDENTIFIER; + return ERRORTOKEN; + } + *p_start = tok->start; + *p_end = tok->cur; + return NAME; + } + + /* Newline */ + if (c == '\n') { + tok->atbol = 1; + if (blankline || tok->level > 0) + goto nextline; + *p_start = tok->start; + *p_end = tok->cur - 1; /* Leave '\n' out of the string */ + tok->cont_line = 0; + return NEWLINE; + } + + /* Period or number starting with period? */ + if (c == '.') { + c = tok_nextc(tok); + if (isdigit(c)) { + goto fraction; + } else if (c == '.') { + c = tok_nextc(tok); + if (c == '.') { + *p_start = tok->start; + *p_end = tok->cur; + return ELLIPSIS; + } else { + tok_backup(tok, c); + } + tok_backup(tok, '.'); + } else { + tok_backup(tok, c); + } + *p_start = tok->start; + *p_end = tok->cur; + return DOT; + } + + /* Number */ + if (isdigit(c)) { + if (c == '0') { + /* Hex, octal or binary -- maybe. */ + c = tok_nextc(tok); + if (c == '.') + goto fraction; + if (c == 'j' || c == 'J') + goto imaginary; + if (c == 'x' || c == 'X') { + + /* Hex */ + c = tok_nextc(tok); + if (!isxdigit(c)) { + tok->done = E_TOKEN; + tok_backup(tok, c); + return ERRORTOKEN; + } + do { + c = tok_nextc(tok); + } while (isxdigit(c)); + } + else if (c == 'o' || c == 'O') { + /* Octal */ + c = tok_nextc(tok); + if (c < '0' || c >= '8') { + tok->done = E_TOKEN; + tok_backup(tok, c); + return ERRORTOKEN; + } + do { + c = tok_nextc(tok); + } while ('0' <= c && c < '8'); + } + else if (c == 'b' || c == 'B') { + /* Binary */ + c = tok_nextc(tok); + if (c != '0' && c != '1') { + tok->done = E_TOKEN; + tok_backup(tok, c); + return ERRORTOKEN; + } + do { + c = tok_nextc(tok); + } while (c == '0' || c == '1'); + } + else { + int nonzero = 0; + /* maybe old-style octal; c is first char of it */ + /* in any case, allow '0' as a literal */ + while (c == '0') + c = tok_nextc(tok); + while (isdigit(c)) { + nonzero = 1; + c = tok_nextc(tok); + } + if (c == '.') + goto fraction; + else if (c == 'e' || c == 'E') + goto exponent; + else if (c == 'j' || c == 'J') + goto imaginary; + else if (nonzero) { + tok->done = E_TOKEN; + tok_backup(tok, c); + return ERRORTOKEN; + } + } + } + else { + /* Decimal */ + do { + c = tok_nextc(tok); + } while (isdigit(c)); + { + /* Accept floating point numbers. */ + if (c == '.') { + fraction: + /* Fraction */ + do { + c = tok_nextc(tok); + } while (isdigit(c)); + } + if (c == 'e' || c == 'E') { + exponent: + /* Exponent part */ + c = tok_nextc(tok); + if (c == '+' || c == '-') + c = tok_nextc(tok); + if (!isdigit(c)) { + tok->done = E_TOKEN; + tok_backup(tok, c); + return ERRORTOKEN; + } + do { + c = tok_nextc(tok); + } while (isdigit(c)); + } + if (c == 'j' || c == 'J') + /* Imaginary part */ + imaginary: + c = tok_nextc(tok); + } + } + tok_backup(tok, c); + *p_start = tok->start; + *p_end = tok->cur; + return NUMBER; + } letter_quote: - /* String */ - if (c == '\'' || c == '"') { - int quote = c; - int quote_size = 1; /* 1 or 3 */ - int end_quote_size = 0; - - /* Find the quote size and start of string */ - c = tok_nextc(tok); - if (c == quote) { - c = tok_nextc(tok); - if (c == quote) - quote_size = 3; - else - end_quote_size = 1; /* empty string found */ - } - if (c != quote) - tok_backup(tok, c); - - /* Get rest of string */ - while (end_quote_size != quote_size) { - c = tok_nextc(tok); - if (c == EOF) { - if (quote_size == 3) - tok->done = E_EOFS; - else - tok->done = E_EOLS; - tok->cur = tok->inp; - return ERRORTOKEN; - } - if (quote_size == 1 && c == '\n') { - tok->done = E_EOLS; - tok->cur = tok->inp; - return ERRORTOKEN; - } - if (c == quote) - end_quote_size += 1; - else { - end_quote_size = 0; - if (c == '\\') - c = tok_nextc(tok); /* skip escaped char */ - } - } - - *p_start = tok->start; - *p_end = tok->cur; - return STRING; - } - - /* Line continuation */ - if (c == '\\') { - c = tok_nextc(tok); - if (c != '\n') { - tok->done = E_LINECONT; - tok->cur = tok->inp; - return ERRORTOKEN; - } - tok->cont_line = 1; - goto again; /* Read next line */ - } - - /* Check for two-character token */ - { - int c2 = tok_nextc(tok); - int token = PyToken_TwoChars(c, c2); - if (token != OP) { - int c3 = tok_nextc(tok); - int token3 = PyToken_ThreeChars(c, c2, c3); - if (token3 != OP) { - token = token3; - } else { - tok_backup(tok, c3); - } - *p_start = tok->start; - *p_end = tok->cur; - return token; - } - tok_backup(tok, c2); - } - - /* Keep track of parentheses nesting level */ - switch (c) { - case '(': - case '[': - case '{': - tok->level++; - break; - case ')': - case ']': - case '}': - tok->level--; - break; - } - - /* Punctuation character */ - *p_start = tok->start; - *p_end = tok->cur; - return PyToken_OneChar(c); + /* String */ + if (c == '\'' || c == '"') { + int quote = c; + int quote_size = 1; /* 1 or 3 */ + int end_quote_size = 0; + + /* Find the quote size and start of string */ + c = tok_nextc(tok); + if (c == quote) { + c = tok_nextc(tok); + if (c == quote) + quote_size = 3; + else + end_quote_size = 1; /* empty string found */ + } + if (c != quote) + tok_backup(tok, c); + + /* Get rest of string */ + while (end_quote_size != quote_size) { + c = tok_nextc(tok); + if (c == EOF) { + if (quote_size == 3) + tok->done = E_EOFS; + else + tok->done = E_EOLS; + tok->cur = tok->inp; + return ERRORTOKEN; + } + if (quote_size == 1 && c == '\n') { + tok->done = E_EOLS; + tok->cur = tok->inp; + return ERRORTOKEN; + } + if (c == quote) + end_quote_size += 1; + else { + end_quote_size = 0; + if (c == '\\') + c = tok_nextc(tok); /* skip escaped char */ + } + } + + *p_start = tok->start; + *p_end = tok->cur; + return STRING; + } + + /* Line continuation */ + if (c == '\\') { + c = tok_nextc(tok); + if (c != '\n') { + tok->done = E_LINECONT; + tok->cur = tok->inp; + return ERRORTOKEN; + } + tok->cont_line = 1; + goto again; /* Read next line */ + } + + /* Check for two-character token */ + { + int c2 = tok_nextc(tok); + int token = PyToken_TwoChars(c, c2); + if (token != OP) { + int c3 = tok_nextc(tok); + int token3 = PyToken_ThreeChars(c, c2, c3); + if (token3 != OP) { + token = token3; + } else { + tok_backup(tok, c3); + } + *p_start = tok->start; + *p_end = tok->cur; + return token; + } + tok_backup(tok, c2); + } + + /* Keep track of parentheses nesting level */ + switch (c) { + case '(': + case '[': + case '{': + tok->level++; + break; + case ')': + case ']': + case '}': + tok->level--; + break; + } + + /* Punctuation character */ + *p_start = tok->start; + *p_end = tok->cur; + return PyToken_OneChar(c); } int PyTokenizer_Get(struct tok_state *tok, char **p_start, char **p_end) { - int result = tok_get(tok, p_start, p_end); - if (tok->decoding_erred) { - result = ERRORTOKEN; - tok->done = E_DECODE; - } - return result; + int result = tok_get(tok, p_start, p_end); + if (tok->decoding_erred) { + result = ERRORTOKEN; + tok->done = E_DECODE; + } + return result; } /* Get -*- encoding -*- from a Python file. @@ -1686,34 +1686,34 @@ char * PyTokenizer_FindEncoding(int fd) { - struct tok_state *tok; - FILE *fp; - char *p_start =NULL , *p_end =NULL , *encoding = NULL; - - fd = dup(fd); - if (fd < 0) { - return NULL; - } - fp = fdopen(fd, "r"); - if (fp == NULL) { - return NULL; - } - tok = PyTokenizer_FromFile(fp, NULL, NULL, NULL); - if (tok == NULL) { - fclose(fp); - return NULL; - } - while (tok->lineno < 2 && tok->done == E_OK) { - PyTokenizer_Get(tok, &p_start, &p_end); - } - fclose(fp); - if (tok->encoding) { - encoding = (char *)PyMem_MALLOC(strlen(tok->encoding) + 1); - if (encoding) - strcpy(encoding, tok->encoding); - } - PyTokenizer_Free(tok); - return encoding; + struct tok_state *tok; + FILE *fp; + char *p_start =NULL , *p_end =NULL , *encoding = NULL; + + fd = dup(fd); + if (fd < 0) { + return NULL; + } + fp = fdopen(fd, "r"); + if (fp == NULL) { + return NULL; + } + tok = PyTokenizer_FromFile(fp, NULL, NULL, NULL); + if (tok == NULL) { + fclose(fp); + return NULL; + } + while (tok->lineno < 2 && tok->done == E_OK) { + PyTokenizer_Get(tok, &p_start, &p_end); + } + fclose(fp); + if (tok->encoding) { + encoding = (char *)PyMem_MALLOC(strlen(tok->encoding) + 1); + if (encoding) + strcpy(encoding, tok->encoding); + } + PyTokenizer_Free(tok); + return encoding; } #ifdef Py_DEBUG @@ -1721,9 +1721,9 @@ void tok_dump(int type, char *start, char *end) { - printf("%s", _PyParser_TokenNames[type]); - if (type == NAME || type == NUMBER || type == STRING || type == OP) - printf("(%.*s)", (int)(end - start), start); + printf("%s", _PyParser_TokenNames[type]); + if (type == NAME || type == NUMBER || type == STRING || type == OP) + printf("(%.*s)", (int)(end - start), start); } #endif Modified: python/branches/py3k/Parser/tokenizer.h ============================================================================== --- python/branches/py3k/Parser/tokenizer.h (original) +++ python/branches/py3k/Parser/tokenizer.h Sun May 9 17:52:27 2010 @@ -8,67 +8,67 @@ /* Tokenizer interface */ -#include "token.h" /* For token types */ +#include "token.h" /* For token types */ -#define MAXINDENT 100 /* Max indentation level */ +#define MAXINDENT 100 /* Max indentation level */ enum decoding_state { - STATE_INIT, - STATE_RAW, - STATE_NORMAL, /* have a codec associated with input */ + STATE_INIT, + STATE_RAW, + STATE_NORMAL, /* have a codec associated with input */ }; /* Tokenizer state */ struct tok_state { - /* Input state; buf <= cur <= inp <= end */ - /* NB an entire line is held in the buffer */ - char *buf; /* Input buffer, or NULL; malloc'ed if fp != NULL */ - char *cur; /* Next character in buffer */ - char *inp; /* End of data in buffer */ - char *end; /* End of input buffer if buf != NULL */ - char *start; /* Start of current token if not NULL */ - int done; /* E_OK normally, E_EOF at EOF, otherwise error code */ - /* NB If done != E_OK, cur must be == inp!!! */ - FILE *fp; /* Rest of input; NULL if tokenizing a string */ - int tabsize; /* Tab spacing */ - int indent; /* Current indentation index */ - int indstack[MAXINDENT]; /* Stack of indents */ - int atbol; /* Nonzero if at begin of new line */ - int pendin; /* Pending indents (if > 0) or dedents (if < 0) */ - char *prompt, *nextprompt; /* For interactive prompting */ - int lineno; /* Current line number */ - int level; /* () [] {} Parentheses nesting level */ - /* Used to allow free continuations inside them */ - /* Stuff for checking on different tab sizes */ - const char *filename; /* For error messages */ - int altwarning; /* Issue warning if alternate tabs don't match */ - int alterror; /* Issue error if alternate tabs don't match */ - int alttabsize; /* Alternate tab spacing */ - int altindstack[MAXINDENT]; /* Stack of alternate indents */ - /* Stuff for PEP 0263 */ - enum decoding_state decoding_state; - int decoding_erred; /* whether erred in decoding */ - int read_coding_spec; /* whether 'coding:...' has been read */ - char *encoding; /* Source encoding. */ - int cont_line; /* whether we are in a continuation line. */ - const char* line_start; /* pointer to start of current line */ + /* Input state; buf <= cur <= inp <= end */ + /* NB an entire line is held in the buffer */ + char *buf; /* Input buffer, or NULL; malloc'ed if fp != NULL */ + char *cur; /* Next character in buffer */ + char *inp; /* End of data in buffer */ + char *end; /* End of input buffer if buf != NULL */ + char *start; /* Start of current token if not NULL */ + int done; /* E_OK normally, E_EOF at EOF, otherwise error code */ + /* NB If done != E_OK, cur must be == inp!!! */ + FILE *fp; /* Rest of input; NULL if tokenizing a string */ + int tabsize; /* Tab spacing */ + int indent; /* Current indentation index */ + int indstack[MAXINDENT]; /* Stack of indents */ + int atbol; /* Nonzero if at begin of new line */ + int pendin; /* Pending indents (if > 0) or dedents (if < 0) */ + char *prompt, *nextprompt; /* For interactive prompting */ + int lineno; /* Current line number */ + int level; /* () [] {} Parentheses nesting level */ + /* Used to allow free continuations inside them */ + /* Stuff for checking on different tab sizes */ + const char *filename; /* For error messages */ + int altwarning; /* Issue warning if alternate tabs don't match */ + int alterror; /* Issue error if alternate tabs don't match */ + int alttabsize; /* Alternate tab spacing */ + int altindstack[MAXINDENT]; /* Stack of alternate indents */ + /* Stuff for PEP 0263 */ + enum decoding_state decoding_state; + int decoding_erred; /* whether erred in decoding */ + int read_coding_spec; /* whether 'coding:...' has been read */ + char *encoding; /* Source encoding. */ + int cont_line; /* whether we are in a continuation line. */ + const char* line_start; /* pointer to start of current line */ #ifndef PGEN - PyObject *decoding_readline; /* codecs.open(...).readline */ - PyObject *decoding_buffer; + PyObject *decoding_readline; /* codecs.open(...).readline */ + PyObject *decoding_buffer; #endif - const char* enc; /* Encoding for the current str. */ - const char* str; - const char* input; /* Tokenizer's newline translated copy of the string. */ + const char* enc; /* Encoding for the current str. */ + const char* str; + const char* input; /* Tokenizer's newline translated copy of the string. */ }; extern struct tok_state *PyTokenizer_FromString(const char *, int); extern struct tok_state *PyTokenizer_FromUTF8(const char *, int); extern struct tok_state *PyTokenizer_FromFile(FILE *, char*, - char *, char *); + char *, char *); extern void PyTokenizer_Free(struct tok_state *); extern int PyTokenizer_Get(struct tok_state *, char **, char **); -extern char * PyTokenizer_RestoreEncoding(struct tok_state* tok, - int len, int *offset); +extern char * PyTokenizer_RestoreEncoding(struct tok_state* tok, + int len, int *offset); extern char * PyTokenizer_FindEncoding(int); #ifdef __cplusplus Modified: python/branches/py3k/Python/_warnings.c ============================================================================== --- python/branches/py3k/Python/_warnings.c (original) +++ python/branches/py3k/Python/_warnings.c Sun May 9 17:52:27 2010 @@ -85,10 +85,10 @@ default_action = get_warnings_attr("defaultaction"); if (default_action == NULL) { - if (PyErr_Occurred()) { - return NULL; - } - return _default_action; + if (PyErr_Occurred()) { + return NULL; + } + return _default_action; } Py_DECREF(_default_action); @@ -202,12 +202,12 @@ mod_str = _PyUnicode_AsString(filename); if (mod_str == NULL) - return NULL; + return NULL; len = PyUnicode_GetSize(filename); if (len < 0) return NULL; if (len >= 3 && - strncmp(mod_str + (len - 3), ".py", 3) == 0) { + strncmp(mod_str + (len - 3), ".py", 3) == 0) { module = PyUnicode_FromStringAndSize(mod_str, len-3); } else { @@ -243,15 +243,15 @@ show_warning(PyObject *filename, int lineno, PyObject *text, PyObject *category, PyObject *sourceline) { - PyObject *f_stderr; - PyObject *name; + PyObject *f_stderr; + PyObject *name; char lineno_str[128]; PyOS_snprintf(lineno_str, sizeof(lineno_str), ":%d: ", lineno); name = PyObject_GetAttrString(category, "__name__"); if (name == NULL) /* XXX Can an object lack a '__name__' attribute? */ - return; + return; f_stderr = PySys_GetObject("stderr"); if (f_stderr == NULL) { @@ -272,8 +272,8 @@ /* Print " source_line\n" */ if (sourceline) { char *source_line_str = _PyUnicode_AsString(sourceline); - if (source_line_str == NULL) - return; + if (source_line_str == NULL) + return; while (*source_line_str == ' ' || *source_line_str == '\t' || *source_line_str == '\014') source_line_str++; @@ -284,12 +284,12 @@ else if (_Py_DisplaySourceLine(f_stderr, _PyUnicode_AsString(filename), lineno, 2) < 0) - return; + return; PyErr_Clear(); } static PyObject * -warn_explicit(PyObject *category, PyObject *message, +warn_explicit(PyObject *category, PyObject *message, PyObject *filename, int lineno, PyObject *module, PyObject *registry, PyObject *sourceline) { @@ -297,7 +297,7 @@ PyObject *item = Py_None; const char *action; int rc; - + if (registry && !PyDict_Check(registry) && (registry != Py_None)) { PyErr_SetString(PyExc_TypeError, "'registry' must be a dict"); return NULL; @@ -344,7 +344,7 @@ rc = already_warned(registry, key, 0); if (rc == -1) goto cleanup; - else if (rc == 1) + else if (rc == 1) goto return_none; /* Else this warning hasn't been generated before. */ } @@ -374,12 +374,12 @@ goto cleanup; } /* _once_registry[(text, category)] = 1 */ - rc = update_registry(registry, text, category, 0); + rc = update_registry(registry, text, category, 0); } else if (strcmp(action, "module") == 0) { /* registry[(text, category, 0)] = 1 */ if (registry != NULL && registry != Py_None) - rc = update_registry(registry, text, category, 0); + rc = update_registry(registry, text, category, 0); } else if (strcmp(action, "default") != 0) { PyObject *to_str = PyObject_Str(item); @@ -387,9 +387,9 @@ if (to_str != NULL) { err_str = _PyUnicode_AsString(to_str); - if (err_str == NULL) - goto cleanup; - } + if (err_str == NULL) + goto cleanup; + } PyErr_Format(PyExc_RuntimeError, "Unrecognized action (%s) in warnings.filters:\n %s", action, err_str); @@ -500,7 +500,7 @@ if (*filename != NULL) { Py_ssize_t len = PyUnicode_GetSize(*filename); const char *file_str = _PyUnicode_AsString(*filename); - if (file_str == NULL || (len < 0 && PyErr_Occurred())) + if (file_str == NULL || (len < 0 && PyErr_Occurred())) goto handle_error; /* if filename.lower().endswith((".pyc", ".pyo")): */ @@ -512,16 +512,16 @@ tolower(file_str[len-1]) == 'o')) { *filename = PyUnicode_FromStringAndSize(file_str, len-1); - if (*filename == NULL) - goto handle_error; - } - else + if (*filename == NULL) + goto handle_error; + } + else Py_INCREF(*filename); } else { const char *module_str = _PyUnicode_AsString(*module); - if (module_str == NULL) - goto handle_error; + if (module_str == NULL) + goto handle_error; if (strcmp(module_str, "__main__") == 0) { PyObject *argv = PySys_GetObject("argv"); if (argv != NULL && PyList_Size(argv) > 0) { @@ -544,8 +544,8 @@ else { /* embedded interpreters don't have sys.argv, see bug #839151 */ *filename = PyUnicode_FromString("__main__"); - if (*filename == NULL) - goto handle_error; + if (*filename == NULL) + goto handle_error; } } if (*filename == NULL) { @@ -616,7 +616,7 @@ PyObject *message, *category = NULL; Py_ssize_t stack_level = 1; - if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|On:warn", kw_list, + if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|On:warn", kw_list, &message, &category, &stack_level)) return NULL; @@ -794,7 +794,7 @@ METH_VARARGS | METH_KEYWORDS, warn_explicit_doc}, /* XXX(brett.cannon): add showwarning? */ /* XXX(brett.cannon): Reasonable to add formatwarning? */ - {NULL, NULL} /* sentinel */ + {NULL, NULL} /* sentinel */ }; @@ -875,15 +875,15 @@ } static struct PyModuleDef warningsmodule = { - PyModuleDef_HEAD_INIT, - MODULE_NAME, - warnings__doc__, - 0, - warnings_functions, - NULL, - NULL, - NULL, - NULL + PyModuleDef_HEAD_INIT, + MODULE_NAME, + warnings__doc__, + 0, + warnings_functions, + NULL, + NULL, + NULL, + NULL }; Modified: python/branches/py3k/Python/asdl.c ============================================================================== --- python/branches/py3k/Python/asdl.c (original) +++ python/branches/py3k/Python/asdl.c Sun May 9 17:52:27 2010 @@ -4,61 +4,61 @@ asdl_seq * asdl_seq_new(int size, PyArena *arena) { - asdl_seq *seq = NULL; - size_t n = (size ? (sizeof(void *) * (size - 1)) : 0); + asdl_seq *seq = NULL; + size_t n = (size ? (sizeof(void *) * (size - 1)) : 0); - /* check size is sane */ - if (size < 0 || size == INT_MIN || - (size && ((size - 1) > (PY_SIZE_MAX / sizeof(void *))))) { - PyErr_NoMemory(); - return NULL; - } - - /* check if size can be added safely */ - if (n > PY_SIZE_MAX - sizeof(asdl_seq)) { - PyErr_NoMemory(); - return NULL; - } - - n += sizeof(asdl_seq); - - seq = (asdl_seq *)PyArena_Malloc(arena, n); - if (!seq) { - PyErr_NoMemory(); - return NULL; - } - memset(seq, 0, n); - seq->size = size; - return seq; + /* check size is sane */ + if (size < 0 || size == INT_MIN || + (size && ((size - 1) > (PY_SIZE_MAX / sizeof(void *))))) { + PyErr_NoMemory(); + return NULL; + } + + /* check if size can be added safely */ + if (n > PY_SIZE_MAX - sizeof(asdl_seq)) { + PyErr_NoMemory(); + return NULL; + } + + n += sizeof(asdl_seq); + + seq = (asdl_seq *)PyArena_Malloc(arena, n); + if (!seq) { + PyErr_NoMemory(); + return NULL; + } + memset(seq, 0, n); + seq->size = size; + return seq; } asdl_int_seq * asdl_int_seq_new(int size, PyArena *arena) { - asdl_int_seq *seq = NULL; - size_t n = (size ? (sizeof(void *) * (size - 1)) : 0); + asdl_int_seq *seq = NULL; + size_t n = (size ? (sizeof(void *) * (size - 1)) : 0); - /* check size is sane */ - if (size < 0 || size == INT_MIN || - (size && ((size - 1) > (PY_SIZE_MAX / sizeof(void *))))) { - PyErr_NoMemory(); - return NULL; - } - - /* check if size can be added safely */ - if (n > PY_SIZE_MAX - sizeof(asdl_seq)) { - PyErr_NoMemory(); - return NULL; - } - - n += sizeof(asdl_seq); - - seq = (asdl_int_seq *)PyArena_Malloc(arena, n); - if (!seq) { - PyErr_NoMemory(); - return NULL; - } - memset(seq, 0, n); - seq->size = size; - return seq; + /* check size is sane */ + if (size < 0 || size == INT_MIN || + (size && ((size - 1) > (PY_SIZE_MAX / sizeof(void *))))) { + PyErr_NoMemory(); + return NULL; + } + + /* check if size can be added safely */ + if (n > PY_SIZE_MAX - sizeof(asdl_seq)) { + PyErr_NoMemory(); + return NULL; + } + + n += sizeof(asdl_seq); + + seq = (asdl_int_seq *)PyArena_Malloc(arena, n); + if (!seq) { + PyErr_NoMemory(); + return NULL; + } + memset(seq, 0, n); + seq->size = size; + return seq; } Modified: python/branches/py3k/Python/ast.c ============================================================================== --- python/branches/py3k/Python/ast.c (original) +++ python/branches/py3k/Python/ast.c Sun May 9 17:52:27 2010 @@ -58,19 +58,19 @@ /* Check whether there are non-ASCII characters in the identifier; if so, normalize to NFKC. */ for (; *u; u++) { - if (*u >= 128) { - PyObject *m = PyImport_ImportModuleNoBlock("unicodedata"); - PyObject *id2; - if (!m) - return NULL; - id2 = PyObject_CallMethod(m, "normalize", "sO", "NFKC", id); - Py_DECREF(m); - if (!id2) - return NULL; - Py_DECREF(id); - id = id2; - break; - } + if (*u >= 128) { + PyObject *m = PyImport_ImportModuleNoBlock("unicodedata"); + PyObject *id2; + if (!m) + return NULL; + id2 = PyObject_CallMethod(m, "normalize", "sO", "NFKC", id); + Py_DECREF(m); + if (!id2) + return NULL; + Py_DECREF(id); + id = id2; + break; + } } PyUnicode_InternInPlace(&id); PyArena_AddPyObject(arena, id); @@ -226,7 +226,7 @@ c.c_encoding = STR(n); n = CHILD(n, 0); } else { - /* PEP 3120 */ + /* PEP 3120 */ c.c_encoding = "utf-8"; } c.c_arena = arena; @@ -481,8 +481,8 @@ expr_name = "conditional expression"; break; default: - PyErr_Format(PyExc_SystemError, - "unexpected expression in assignment %d (line %d)", + PyErr_Format(PyExc_SystemError, + "unexpected expression in assignment %d (line %d)", e->kind, e->lineno); return 0; } @@ -497,7 +497,7 @@ } /* If the LHS is a list or tuple, we need to set the assignment - context for all the contained elements. + context for all the contained elements. */ if (s) { int i; @@ -603,7 +603,7 @@ static asdl_seq * seq_for_testlist(struct compiling *c, const node *n) { - /* testlist: test (',' test)* [','] + /* testlist: test (',' test)* [','] testlist_star_expr: test|star_expr (',' test|star_expr)* [','] */ asdl_seq *seq; @@ -616,7 +616,7 @@ return NULL; for (i = 0; i < NCH(n); i += 2) { - const node *ch = CHILD(n, i); + const node *ch = CHILD(n, i); assert(TYPE(ch) == test || TYPE(ch) == test_nocond || TYPE(ch) == star_expr); expression = ast_for_expr(c, ch); @@ -726,7 +726,7 @@ } return i; error: - return -1; + return -1; } /* Create AST for argument list. */ @@ -739,12 +739,12 @@ parameters: '(' [typedargslist] ')' typedargslist: ((tfpdef ['=' test] ',')* - ('*' [tfpdef] (',' tfpdef ['=' test])* [',' '**' tfpdef] + ('*' [tfpdef] (',' tfpdef ['=' test])* [',' '**' tfpdef] | '**' tfpdef) | tfpdef ['=' test] (',' tfpdef ['=' test])* [',']) tfpdef: NAME [':' test] varargslist: ((vfpdef ['=' test] ',')* - ('*' [vfpdef] (',' vfpdef ['=' test])* [',' '**' vfpdef] + ('*' [vfpdef] (',' vfpdef ['=' test])* [',' '**' vfpdef] | '**' vfpdef) | vfpdef ['=' test] (',' vfpdef ['=' test])* [',']) vfpdef: NAME @@ -785,7 +785,7 @@ if (TYPE(ch) == vfpdef || TYPE(ch) == tfpdef) nposargs++; if (TYPE(ch) == EQUAL) nposdefaults++; } - /* count the number of keyword only args & + /* count the number of keyword only args & defaults for keyword only args */ for ( ; i < NCH(n); ++i) { ch = CHILD(n, i); @@ -799,11 +799,11 @@ asdl_seq_new(nkwonlyargs, c->c_arena) : NULL); if (!kwonlyargs && nkwonlyargs) goto error; - posdefaults = (nposdefaults ? + posdefaults = (nposdefaults ? asdl_seq_new(nposdefaults, c->c_arena) : NULL); if (!posdefaults && nposdefaults) goto error; - /* The length of kwonlyargs and kwdefaults are same + /* The length of kwonlyargs and kwdefaults are same since we set NULL as default for keyword only argument w/o default - we have sequence data structure, but no dictionary */ kwdefaults = (nkwonlyargs ? @@ -840,7 +840,7 @@ found_default = 1; } else if (found_default) { - ast_error(n, + ast_error(n, "non-default argument follows default argument"); goto error; } @@ -852,7 +852,7 @@ break; case STAR: if (i+1 >= NCH(n)) { - ast_error(CHILD(n, i), + ast_error(CHILD(n, i), "named arguments must follow bare *"); goto error; } @@ -953,15 +953,15 @@ /* decorator: '@' dotted_name [ '(' [arglist] ')' ] NEWLINE */ expr_ty d = NULL; expr_ty name_expr; - + REQ(n, decorator); REQ(CHILD(n, 0), AT); REQ(RCHILD(n, -1), NEWLINE); - + name_expr = ast_for_dotted_name(c, CHILD(n, 1)); if (!name_expr) return NULL; - + if (NCH(n) == 3) { /* No arguments */ d = name_expr; name_expr = NULL; @@ -989,12 +989,12 @@ asdl_seq* decorator_seq; expr_ty d; int i; - + REQ(n, decorators); decorator_seq = asdl_seq_new(NCH(n), c->c_arena); if (!decorator_seq) return NULL; - + for (i = 0; i < NCH(n); i++) { d = ast_for_decorator(c, CHILD(n, i)); if (!d) @@ -1052,7 +1052,7 @@ return NULL; assert(TYPE(CHILD(n, 1)) == funcdef || - TYPE(CHILD(n, 1)) == classdef); + TYPE(CHILD(n, 1)) == classdef); if (TYPE(CHILD(n, 1)) == funcdef) { thing = ast_for_funcdef(c, CHILD(n, 1), decorator_seq); @@ -1100,7 +1100,7 @@ static expr_ty ast_for_ifexpr(struct compiling *c, const node *n) { - /* test: or_test 'if' or_test 'else' test */ + /* test: or_test 'if' or_test 'else' test */ expr_ty expression, body, orelse; assert(NCH(n) == 5); @@ -1197,9 +1197,9 @@ asdl_seq *t; expr_ty expression, first; node *for_ch; - + REQ(n, comp_for); - + for_ch = CHILD(n, 1); t = ast_for_exprlist(c, for_ch, Store); if (!t) @@ -1223,7 +1223,7 @@ if (NCH(n) == 5) { int j, n_ifs; asdl_seq *ifs; - + n = CHILD(n, 4); n_ifs = count_comp_ifs(c, n); if (n_ifs == -1) @@ -1237,7 +1237,7 @@ REQ(n, comp_iter); n = CHILD(n, 0); REQ(n, comp_if); - + expression = ast_for_expr(c, CHILD(n, 1)); if (!expression) return NULL; @@ -1262,13 +1262,13 @@ argument: [test '='] test [comp_for] # Really [keyword '='] test */ expr_ty elt; asdl_seq *comps; - + assert(NCH(n) > 1); - + elt = ast_for_expr(c, CHILD(n, 0)); if (!elt) return NULL; - + comps = ast_for_comprehension(c, CHILD(n, 1)); if (!comps) return NULL; @@ -1289,21 +1289,21 @@ { expr_ty key, value; asdl_seq *comps; - + assert(NCH(n) > 3); REQ(CHILD(n, 1), COLON); - + key = ast_for_expr(c, CHILD(n, 0)); if (!key) return NULL; value = ast_for_expr(c, CHILD(n, 2)); if (!value) return NULL; - + comps = ast_for_comprehension(c, CHILD(n, 3)); if (!comps) return NULL; - + return DictComp(key, value, comps, LINENO(n), n->n_col_offset, c->c_arena); } @@ -1338,7 +1338,7 @@ */ node *ch = CHILD(n, 0); int bytesmode = 0; - + switch (TYPE(ch)) { case NAME: { /* All names start in Load context, but may later be @@ -1389,24 +1389,24 @@ return Ellipsis(LINENO(n), n->n_col_offset, c->c_arena); case LPAR: /* some parenthesized expressions */ ch = CHILD(n, 1); - + if (TYPE(ch) == RPAR) return Tuple(NULL, Load, LINENO(n), n->n_col_offset, c->c_arena); - + if (TYPE(ch) == yield_expr) return ast_for_expr(c, ch); - /* testlist_comp: test ( comp_for | (',' test)* [','] ) */ + /* testlist_comp: test ( comp_for | (',' test)* [','] ) */ if ((NCH(ch) > 1) && (TYPE(CHILD(ch, 1)) == comp_for)) return ast_for_genexp(c, ch); return ast_for_testlist(c, ch); case LSQB: /* list (or list comprehension) */ ch = CHILD(n, 1); - + if (TYPE(ch) == RSQB) return List(NULL, Load, LINENO(n), n->n_col_offset, c->c_arena); - + REQ(ch, testlist_comp); if (NCH(ch) == 1 || TYPE(CHILD(ch, 1)) == COMMA) { asdl_seq *elts = seq_for_testlist(c, ch); @@ -1453,14 +1453,14 @@ keys = asdl_seq_new(size, c->c_arena); if (!keys) return NULL; - + values = asdl_seq_new(size, c->c_arena); if (!values) return NULL; - + for (i = 0; i < NCH(ch); i += 4) { expr_ty expression; - + expression = ast_for_expr(c, CHILD(ch, i)); if (!expression) return NULL; @@ -1498,10 +1498,10 @@ if (NCH(n) == 1 && TYPE(ch) == test) { /* 'step' variable hold no significance in terms of being used over other vars */ - step = ast_for_expr(c, ch); + step = ast_for_expr(c, ch); if (!step) return NULL; - + return Index(step, c->c_arena); } @@ -1551,7 +1551,7 @@ ast_for_binop(struct compiling *c, const node *n) { /* Must account for a sequence of expressions. - How should A op B op C by represented? + How should A op B op C by represented? BinOp(BinOp(A, op, B), op, C). */ @@ -1589,10 +1589,10 @@ if (!tmp) return NULL; - tmp_result = BinOp(result, newoperator, tmp, + tmp_result = BinOp(result, newoperator, tmp, LINENO(next_oper), next_oper->n_col_offset, c->c_arena); - if (!tmp_result) + if (!tmp_result) return NULL; result = tmp_result; } @@ -1602,7 +1602,7 @@ static expr_ty ast_for_trailer(struct compiling *c, const node *n, expr_ty left_expr) { - /* trailer: '(' [arglist] ')' | '[' subscriptlist ']' | '.' NAME + /* trailer: '(' [arglist] ')' | '[' subscriptlist ']' | '.' NAME subscriptlist: subscript (',' subscript)* [','] subscript: '.' '.' '.' | test | [test] ':' [test] [sliceop] */ @@ -1633,7 +1633,7 @@ c->c_arena); } else { - /* The grammar is ambiguous here. The ambiguity is resolved + /* The grammar is ambiguous here. The ambiguity is resolved by treating the sequence as a tuple literal if there are no slice features. */ @@ -1786,7 +1786,7 @@ /* handle the full range of simple expressions test: or_test ['if' or_test 'else' test] | lambdef test_nocond: or_test | lambdef_nocond - or_test: and_test ('or' and_test)* + or_test: and_test ('or' and_test)* and_test: not_test ('and' not_test)* not_test: 'not' not_test | comparison comparison: expr (comp_op expr)* @@ -1874,7 +1874,7 @@ if (!expression) { return NULL; } - + asdl_seq_SET(ops, i / 2, newoperator); asdl_seq_SET(cmps, i / 2, expression); } @@ -1882,14 +1882,14 @@ if (!expression) { return NULL; } - + return Compare(expression, ops, cmps, LINENO(n), n->n_col_offset, c->c_arena); } break; case star_expr: - return ast_for_starred(c, n); + return ast_for_starred(c, n); /* The next five cases all handle BinOps. The main body of code is the same in each case, but the switch turned inside out to reuse the code for each type of operator. @@ -1998,7 +1998,7 @@ if (!e) return NULL; asdl_seq_SET(args, nargs++, e); - } + } else if (TYPE(CHILD(ch, 1)) == comp_for) { e = ast_for_genexp(c, ch); if (!e) @@ -2010,7 +2010,7 @@ identifier key, tmp; int k; - /* CHILD(ch, 0) is test, but must be an identifier? */ + /* CHILD(ch, 0) is test, but must be an identifier? */ e = ast_for_expr(c, CHILD(ch, 0)); if (!e) return NULL; @@ -2026,8 +2026,8 @@ ast_error(CHILD(ch, 0), "keyword can't be an expression"); return NULL; } else if (forbidden_name(e->v.Name.id, ch, 1)) { - return NULL; - } + return NULL; + } key = e->v.Name.id; for (k = 0; k < nkeywords; k++) { tmp = ((keyword_ty)asdl_seq_GET(keywords, k))->arg; @@ -2090,7 +2090,7 @@ ast_for_expr_stmt(struct compiling *c, const node *n) { REQ(n, expr_stmt); - /* expr_stmt: testlist_star_expr (augassign (yield_expr|testlist) + /* expr_stmt: testlist_star_expr (augassign (yield_expr|testlist) | ('=' (yield_expr|testlist))*) testlist_star_expr: (test|star_expr) (',' test|star_expr)* [','] augassign: '+=' | '-=' | '*=' | '/=' | '%=' | '&=' | '|=' | '^=' @@ -2164,7 +2164,7 @@ e = ast_for_testlist(c, ch); /* set context to assign */ - if (!e) + if (!e) return NULL; if (!set_context(c, e, Store, CHILD(n, i))) @@ -2211,7 +2211,7 @@ ast_for_del_stmt(struct compiling *c, const node *n) { asdl_seq *expr_list; - + /* del_stmt: 'del' exprlist */ REQ(n, del_stmt); @@ -2349,7 +2349,7 @@ int i; size_t len; char *s; - PyObject *uni; + PyObject *uni; len = 0; for (i = 0; i < NCH(n); i += 2) @@ -2370,13 +2370,13 @@ } --s; *s = '\0'; - uni = PyUnicode_DecodeUTF8(PyBytes_AS_STRING(str), - PyBytes_GET_SIZE(str), - NULL); - Py_DECREF(str); - if (!uni) - return NULL; - str = uni; + uni = PyUnicode_DecodeUTF8(PyBytes_AS_STRING(str), + PyBytes_GET_SIZE(str), + NULL); + Py_DECREF(str); + if (!uni) + return NULL; + str = uni; PyUnicode_InternInPlace(&str); PyArena_AddPyObject(c->c_arena, str); return alias(str, NULL, c->c_arena); @@ -2433,7 +2433,7 @@ int idx, ndots = 0; alias_ty mod = NULL; identifier modname = NULL; - + /* Count the number of dots (for relative imports) and check for the optional module name */ for (idx = 1; idx < NCH(n); idx++) { @@ -2444,7 +2444,7 @@ idx++; break; } else if (TYPE(CHILD(n, idx)) == ELLIPSIS) { - /* three consecutive dots are tokenized as one ELLIPSIS */ + /* three consecutive dots are tokenized as one ELLIPSIS */ ndots += 3; continue; } else if (TYPE(CHILD(n, idx)) != DOT) { @@ -2571,7 +2571,7 @@ expr2 = ast_for_expr(c, CHILD(n, 3)); if (!expr2) return NULL; - + return Assert(expr1, expr2, LINENO(n), n->n_col_offset, c->c_arena); } PyErr_Format(PyExc_SystemError, @@ -2598,7 +2598,7 @@ if (TYPE(CHILD(n, 0)) == simple_stmt) { n = CHILD(n, 0); /* simple_stmt always ends with a NEWLINE, - and may have a trailing SEMI + and may have a trailing SEMI */ end = NCH(n) - 1; if (TYPE(CHILD(n, end - 1)) == SEMI) @@ -2663,10 +2663,10 @@ expression = ast_for_expr(c, CHILD(n, 1)); if (!expression) return NULL; - suite_seq = ast_for_suite(c, CHILD(n, 3)); + suite_seq = ast_for_suite(c, CHILD(n, 3)); if (!suite_seq) return NULL; - + return If(expression, suite_seq, NULL, LINENO(n), n->n_col_offset, c->c_arena); } @@ -2724,8 +2724,8 @@ if (!suite_seq2) return NULL; - asdl_seq_SET(orelse, 0, - If(expression, suite_seq, suite_seq2, + asdl_seq_SET(orelse, 0, + If(expression, suite_seq, suite_seq2, LINENO(CHILD(n, NCH(n) - 6)), CHILD(n, NCH(n) - 6)->n_col_offset, c->c_arena)); @@ -2746,7 +2746,7 @@ return NULL; asdl_seq_SET(newobj, 0, - If(expression, suite_seq, orelse, + If(expression, suite_seq, orelse, LINENO(CHILD(n, off)), CHILD(n, off)->n_col_offset, c->c_arena)); orelse = newobj; @@ -2943,7 +2943,7 @@ ast_error(n, "malformed 'try' statement"); return NULL; } - + if (n_except > 0) { int i; stmt_ty except_st; @@ -3160,8 +3160,8 @@ return ast_for_funcdef(c, ch, NULL); case classdef: return ast_for_classdef(c, ch, NULL); - case decorated: - return ast_for_decorated(c, ch); + case decorated: + return ast_for_decorated(c, ch); default: PyErr_Format(PyExc_SystemError, "unhandled small_stmt: TYPE=%d NCH=%d\n", @@ -3317,7 +3317,7 @@ if (quote == 'b' || quote == 'B') { quote = *++s; *bytesmode = 1; - } + } if (quote == 'r' || quote == 'R') { quote = *++s; rawmode = 1; @@ -3330,7 +3330,7 @@ s++; len = strlen(s); if (len > INT_MAX) { - PyErr_SetString(PyExc_OverflowError, + PyErr_SetString(PyExc_OverflowError, "string to parse is too long"); return NULL; } @@ -3374,7 +3374,7 @@ return PyBytes_FromStringAndSize(s, len); } else if (strcmp(c->c_encoding, "utf-8") == 0) { return PyUnicode_FromStringAndSize(s, len); - } else { + } else { return PyUnicode_DecodeLatin1(s, len, NULL); } } Modified: python/branches/py3k/Python/bltinmodule.c ============================================================================== --- python/branches/py3k/Python/bltinmodule.c (original) +++ python/branches/py3k/Python/bltinmodule.c Sun May 9 17:52:27 2010 @@ -29,138 +29,138 @@ int _Py_SetFileSystemEncoding(PyObject *s) { - PyObject *defenc, *codec; - if (!PyUnicode_Check(s)) { - PyErr_BadInternalCall(); - return -1; - } - defenc = _PyUnicode_AsDefaultEncodedString(s, NULL); - if (!defenc) - return -1; - codec = _PyCodec_Lookup(PyBytes_AsString(defenc)); - if (codec == NULL) - return -1; - Py_DECREF(codec); - if (!Py_HasFileSystemDefaultEncoding && Py_FileSystemDefaultEncoding) - /* A file system encoding was set at run-time */ - free((char*)Py_FileSystemDefaultEncoding); - Py_FileSystemDefaultEncoding = strdup(PyBytes_AsString(defenc)); - Py_HasFileSystemDefaultEncoding = 0; - return 0; + PyObject *defenc, *codec; + if (!PyUnicode_Check(s)) { + PyErr_BadInternalCall(); + return -1; + } + defenc = _PyUnicode_AsDefaultEncodedString(s, NULL); + if (!defenc) + return -1; + codec = _PyCodec_Lookup(PyBytes_AsString(defenc)); + if (codec == NULL) + return -1; + Py_DECREF(codec); + if (!Py_HasFileSystemDefaultEncoding && Py_FileSystemDefaultEncoding) + /* A file system encoding was set at run-time */ + free((char*)Py_FileSystemDefaultEncoding); + Py_FileSystemDefaultEncoding = strdup(PyBytes_AsString(defenc)); + Py_HasFileSystemDefaultEncoding = 0; + return 0; } static PyObject * builtin___build_class__(PyObject *self, PyObject *args, PyObject *kwds) { - PyObject *func, *name, *bases, *mkw, *meta, *prep, *ns, *cell; - PyObject *cls = NULL; - Py_ssize_t nargs, nbases; - - assert(args != NULL); - if (!PyTuple_Check(args)) { - PyErr_SetString(PyExc_TypeError, - "__build_class__: args is not a tuple"); - return NULL; - } - nargs = PyTuple_GET_SIZE(args); - if (nargs < 2) { - PyErr_SetString(PyExc_TypeError, - "__build_class__: not enough arguments"); - return NULL; - } - func = PyTuple_GET_ITEM(args, 0); /* Better be callable */ - name = PyTuple_GET_ITEM(args, 1); - if (!PyUnicode_Check(name)) { - PyErr_SetString(PyExc_TypeError, - "__build_class__: name is not a string"); - return NULL; - } - bases = PyTuple_GetSlice(args, 2, nargs); - if (bases == NULL) - return NULL; - nbases = nargs - 2; - - if (kwds == NULL) { - meta = NULL; - mkw = NULL; - } - else { - mkw = PyDict_Copy(kwds); /* Don't modify kwds passed in! */ - if (mkw == NULL) { - Py_DECREF(bases); - return NULL; - } - meta = PyDict_GetItemString(mkw, "metaclass"); - if (meta != NULL) { - Py_INCREF(meta); - if (PyDict_DelItemString(mkw, "metaclass") < 0) { - Py_DECREF(meta); - Py_DECREF(mkw); - Py_DECREF(bases); - return NULL; - } - } - } - if (meta == NULL) { - if (PyTuple_GET_SIZE(bases) == 0) - meta = (PyObject *) (&PyType_Type); - else { - PyObject *base0 = PyTuple_GET_ITEM(bases, 0); - meta = (PyObject *) (base0->ob_type); - } - Py_INCREF(meta); - } - prep = PyObject_GetAttrString(meta, "__prepare__"); - if (prep == NULL) { - if (PyErr_ExceptionMatches(PyExc_AttributeError)) { - PyErr_Clear(); - ns = PyDict_New(); - } - else { - Py_DECREF(meta); - Py_XDECREF(mkw); - Py_DECREF(bases); - return NULL; - } - } - else { - PyObject *pargs = PyTuple_Pack(2, name, bases); - if (pargs == NULL) { - Py_DECREF(prep); - Py_DECREF(meta); - Py_XDECREF(mkw); - Py_DECREF(bases); - return NULL; - } - ns = PyEval_CallObjectWithKeywords(prep, pargs, mkw); - Py_DECREF(pargs); - Py_DECREF(prep); - } - if (ns == NULL) { - Py_DECREF(meta); - Py_XDECREF(mkw); - Py_DECREF(bases); - return NULL; - } - cell = PyObject_CallFunctionObjArgs(func, ns, NULL); - if (cell != NULL) { - PyObject *margs; - margs = PyTuple_Pack(3, name, bases, ns); - if (margs != NULL) { - cls = PyEval_CallObjectWithKeywords(meta, margs, mkw); - Py_DECREF(margs); - } - if (cls != NULL && PyCell_Check(cell)) { - Py_INCREF(cls); - PyCell_SET(cell, cls); - } - Py_DECREF(cell); - } - Py_DECREF(ns); - Py_DECREF(meta); - Py_XDECREF(mkw); - Py_DECREF(bases); - return cls; + PyObject *func, *name, *bases, *mkw, *meta, *prep, *ns, *cell; + PyObject *cls = NULL; + Py_ssize_t nargs, nbases; + + assert(args != NULL); + if (!PyTuple_Check(args)) { + PyErr_SetString(PyExc_TypeError, + "__build_class__: args is not a tuple"); + return NULL; + } + nargs = PyTuple_GET_SIZE(args); + if (nargs < 2) { + PyErr_SetString(PyExc_TypeError, + "__build_class__: not enough arguments"); + return NULL; + } + func = PyTuple_GET_ITEM(args, 0); /* Better be callable */ + name = PyTuple_GET_ITEM(args, 1); + if (!PyUnicode_Check(name)) { + PyErr_SetString(PyExc_TypeError, + "__build_class__: name is not a string"); + return NULL; + } + bases = PyTuple_GetSlice(args, 2, nargs); + if (bases == NULL) + return NULL; + nbases = nargs - 2; + + if (kwds == NULL) { + meta = NULL; + mkw = NULL; + } + else { + mkw = PyDict_Copy(kwds); /* Don't modify kwds passed in! */ + if (mkw == NULL) { + Py_DECREF(bases); + return NULL; + } + meta = PyDict_GetItemString(mkw, "metaclass"); + if (meta != NULL) { + Py_INCREF(meta); + if (PyDict_DelItemString(mkw, "metaclass") < 0) { + Py_DECREF(meta); + Py_DECREF(mkw); + Py_DECREF(bases); + return NULL; + } + } + } + if (meta == NULL) { + if (PyTuple_GET_SIZE(bases) == 0) + meta = (PyObject *) (&PyType_Type); + else { + PyObject *base0 = PyTuple_GET_ITEM(bases, 0); + meta = (PyObject *) (base0->ob_type); + } + Py_INCREF(meta); + } + prep = PyObject_GetAttrString(meta, "__prepare__"); + if (prep == NULL) { + if (PyErr_ExceptionMatches(PyExc_AttributeError)) { + PyErr_Clear(); + ns = PyDict_New(); + } + else { + Py_DECREF(meta); + Py_XDECREF(mkw); + Py_DECREF(bases); + return NULL; + } + } + else { + PyObject *pargs = PyTuple_Pack(2, name, bases); + if (pargs == NULL) { + Py_DECREF(prep); + Py_DECREF(meta); + Py_XDECREF(mkw); + Py_DECREF(bases); + return NULL; + } + ns = PyEval_CallObjectWithKeywords(prep, pargs, mkw); + Py_DECREF(pargs); + Py_DECREF(prep); + } + if (ns == NULL) { + Py_DECREF(meta); + Py_XDECREF(mkw); + Py_DECREF(bases); + return NULL; + } + cell = PyObject_CallFunctionObjArgs(func, ns, NULL); + if (cell != NULL) { + PyObject *margs; + margs = PyTuple_Pack(3, name, bases, ns); + if (margs != NULL) { + cls = PyEval_CallObjectWithKeywords(meta, margs, mkw); + Py_DECREF(margs); + } + if (cls != NULL && PyCell_Check(cell)) { + Py_INCREF(cls); + PyCell_SET(cell, cls); + } + Py_DECREF(cell); + } + Py_DECREF(ns); + Py_DECREF(meta); + Py_XDECREF(mkw); + Py_DECREF(bases); + return cls; } PyDoc_STRVAR(build_class_doc, @@ -171,19 +171,19 @@ static PyObject * builtin___import__(PyObject *self, PyObject *args, PyObject *kwds) { - static char *kwlist[] = {"name", "globals", "locals", "fromlist", - "level", 0}; - char *name; - PyObject *globals = NULL; - PyObject *locals = NULL; - PyObject *fromlist = NULL; - int level = -1; - - if (!PyArg_ParseTupleAndKeywords(args, kwds, "s|OOOi:__import__", - kwlist, &name, &globals, &locals, &fromlist, &level)) - return NULL; - return PyImport_ImportModuleLevel(name, globals, locals, - fromlist, level); + static char *kwlist[] = {"name", "globals", "locals", "fromlist", + "level", 0}; + char *name; + PyObject *globals = NULL; + PyObject *locals = NULL; + PyObject *fromlist = NULL; + int level = -1; + + if (!PyArg_ParseTupleAndKeywords(args, kwds, "s|OOOi:__import__", + kwlist, &name, &globals, &locals, &fromlist, &level)) + return NULL; + return PyImport_ImportModuleLevel(name, globals, locals, + fromlist, level); } PyDoc_STRVAR(import_doc, @@ -204,7 +204,7 @@ static PyObject * builtin_abs(PyObject *self, PyObject *v) { - return PyNumber_Absolute(v); + return PyNumber_Absolute(v); } PyDoc_STRVAR(abs_doc, @@ -215,38 +215,38 @@ static PyObject * builtin_all(PyObject *self, PyObject *v) { - PyObject *it, *item; - PyObject *(*iternext)(PyObject *); - int cmp; - - it = PyObject_GetIter(v); - if (it == NULL) - return NULL; - iternext = *Py_TYPE(it)->tp_iternext; - - for (;;) { - item = iternext(it); - if (item == NULL) - break; - cmp = PyObject_IsTrue(item); - Py_DECREF(item); - if (cmp < 0) { - Py_DECREF(it); - return NULL; - } - if (cmp == 0) { - Py_DECREF(it); - Py_RETURN_FALSE; - } - } - Py_DECREF(it); - if (PyErr_Occurred()) { - if (PyErr_ExceptionMatches(PyExc_StopIteration)) - PyErr_Clear(); - else - return NULL; - } - Py_RETURN_TRUE; + PyObject *it, *item; + PyObject *(*iternext)(PyObject *); + int cmp; + + it = PyObject_GetIter(v); + if (it == NULL) + return NULL; + iternext = *Py_TYPE(it)->tp_iternext; + + for (;;) { + item = iternext(it); + if (item == NULL) + break; + cmp = PyObject_IsTrue(item); + Py_DECREF(item); + if (cmp < 0) { + Py_DECREF(it); + return NULL; + } + if (cmp == 0) { + Py_DECREF(it); + Py_RETURN_FALSE; + } + } + Py_DECREF(it); + if (PyErr_Occurred()) { + if (PyErr_ExceptionMatches(PyExc_StopIteration)) + PyErr_Clear(); + else + return NULL; + } + Py_RETURN_TRUE; } PyDoc_STRVAR(all_doc, @@ -257,38 +257,38 @@ static PyObject * builtin_any(PyObject *self, PyObject *v) { - PyObject *it, *item; - PyObject *(*iternext)(PyObject *); - int cmp; - - it = PyObject_GetIter(v); - if (it == NULL) - return NULL; - iternext = *Py_TYPE(it)->tp_iternext; - - for (;;) { - item = iternext(it); - if (item == NULL) - break; - cmp = PyObject_IsTrue(item); - Py_DECREF(item); - if (cmp < 0) { - Py_DECREF(it); - return NULL; - } - if (cmp == 1) { - Py_DECREF(it); - Py_RETURN_TRUE; - } - } - Py_DECREF(it); - if (PyErr_Occurred()) { - if (PyErr_ExceptionMatches(PyExc_StopIteration)) - PyErr_Clear(); - else - return NULL; - } - Py_RETURN_FALSE; + PyObject *it, *item; + PyObject *(*iternext)(PyObject *); + int cmp; + + it = PyObject_GetIter(v); + if (it == NULL) + return NULL; + iternext = *Py_TYPE(it)->tp_iternext; + + for (;;) { + item = iternext(it); + if (item == NULL) + break; + cmp = PyObject_IsTrue(item); + Py_DECREF(item); + if (cmp < 0) { + Py_DECREF(it); + return NULL; + } + if (cmp == 1) { + Py_DECREF(it); + Py_RETURN_TRUE; + } + } + Py_DECREF(it); + if (PyErr_Occurred()) { + if (PyErr_ExceptionMatches(PyExc_StopIteration)) + PyErr_Clear(); + else + return NULL; + } + Py_RETURN_FALSE; } PyDoc_STRVAR(any_doc, @@ -299,7 +299,7 @@ static PyObject * builtin_ascii(PyObject *self, PyObject *v) { - return PyObject_ASCII(v); + return PyObject_ASCII(v); } PyDoc_STRVAR(ascii_doc, @@ -314,7 +314,7 @@ static PyObject * builtin_bin(PyObject *self, PyObject *v) { - return PyNumber_ToBase(v, 2); + return PyNumber_ToBase(v, 2); } PyDoc_STRVAR(bin_doc, @@ -324,90 +324,90 @@ typedef struct { - PyObject_HEAD - PyObject *func; - PyObject *it; + PyObject_HEAD + PyObject *func; + PyObject *it; } filterobject; static PyObject * filter_new(PyTypeObject *type, PyObject *args, PyObject *kwds) { - PyObject *func, *seq; - PyObject *it; - filterobject *lz; - - if (type == &PyFilter_Type && !_PyArg_NoKeywords("filter()", kwds)) - return NULL; - - if (!PyArg_UnpackTuple(args, "filter", 2, 2, &func, &seq)) - return NULL; - - /* Get iterator. */ - it = PyObject_GetIter(seq); - if (it == NULL) - return NULL; - - /* create filterobject structure */ - lz = (filterobject *)type->tp_alloc(type, 0); - if (lz == NULL) { - Py_DECREF(it); - return NULL; - } - Py_INCREF(func); - lz->func = func; - lz->it = it; + PyObject *func, *seq; + PyObject *it; + filterobject *lz; + + if (type == &PyFilter_Type && !_PyArg_NoKeywords("filter()", kwds)) + return NULL; + + if (!PyArg_UnpackTuple(args, "filter", 2, 2, &func, &seq)) + return NULL; + + /* Get iterator. */ + it = PyObject_GetIter(seq); + if (it == NULL) + return NULL; - return (PyObject *)lz; + /* create filterobject structure */ + lz = (filterobject *)type->tp_alloc(type, 0); + if (lz == NULL) { + Py_DECREF(it); + return NULL; + } + Py_INCREF(func); + lz->func = func; + lz->it = it; + + return (PyObject *)lz; } static void filter_dealloc(filterobject *lz) { - PyObject_GC_UnTrack(lz); - Py_XDECREF(lz->func); - Py_XDECREF(lz->it); - Py_TYPE(lz)->tp_free(lz); + PyObject_GC_UnTrack(lz); + Py_XDECREF(lz->func); + Py_XDECREF(lz->it); + Py_TYPE(lz)->tp_free(lz); } static int filter_traverse(filterobject *lz, visitproc visit, void *arg) { - Py_VISIT(lz->it); - Py_VISIT(lz->func); - return 0; + Py_VISIT(lz->it); + Py_VISIT(lz->func); + return 0; } static PyObject * filter_next(filterobject *lz) { - PyObject *item; - PyObject *it = lz->it; - long ok; - PyObject *(*iternext)(PyObject *); - - iternext = *Py_TYPE(it)->tp_iternext; - for (;;) { - item = iternext(it); - if (item == NULL) - return NULL; - - if (lz->func == Py_None || lz->func == (PyObject *)&PyBool_Type) { - ok = PyObject_IsTrue(item); - } else { - PyObject *good; - good = PyObject_CallFunctionObjArgs(lz->func, - item, NULL); - if (good == NULL) { - Py_DECREF(item); - return NULL; - } - ok = PyObject_IsTrue(good); - Py_DECREF(good); - } - if (ok) - return item; - Py_DECREF(item); - } + PyObject *item; + PyObject *it = lz->it; + long ok; + PyObject *(*iternext)(PyObject *); + + iternext = *Py_TYPE(it)->tp_iternext; + for (;;) { + item = iternext(it); + if (item == NULL) + return NULL; + + if (lz->func == Py_None || lz->func == (PyObject *)&PyBool_Type) { + ok = PyObject_IsTrue(item); + } else { + PyObject *good; + good = PyObject_CallFunctionObjArgs(lz->func, + item, NULL); + if (good == NULL) { + Py_DECREF(item); + return NULL; + } + ok = PyObject_IsTrue(good); + Py_DECREF(good); + } + if (ok) + return item; + Py_DECREF(item); + } } PyDoc_STRVAR(filter_doc, @@ -417,47 +417,47 @@ is true. If function is None, return the items that are true."); PyTypeObject PyFilter_Type = { - PyVarObject_HEAD_INIT(&PyType_Type, 0) - "filter", /* tp_name */ - sizeof(filterobject), /* tp_basicsize */ - 0, /* tp_itemsize */ - /* methods */ - (destructor)filter_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 | - Py_TPFLAGS_BASETYPE, /* tp_flags */ - filter_doc, /* tp_doc */ - (traverseproc)filter_traverse, /* tp_traverse */ - 0, /* tp_clear */ - 0, /* tp_richcompare */ - 0, /* tp_weaklistoffset */ - PyObject_SelfIter, /* tp_iter */ - (iternextfunc)filter_next, /* tp_iternext */ - 0, /* tp_methods */ - 0, /* tp_members */ - 0, /* tp_getset */ - 0, /* tp_base */ - 0, /* tp_dict */ - 0, /* tp_descr_get */ - 0, /* tp_descr_set */ - 0, /* tp_dictoffset */ - 0, /* tp_init */ - PyType_GenericAlloc, /* tp_alloc */ - filter_new, /* tp_new */ - PyObject_GC_Del, /* tp_free */ + PyVarObject_HEAD_INIT(&PyType_Type, 0) + "filter", /* tp_name */ + sizeof(filterobject), /* tp_basicsize */ + 0, /* tp_itemsize */ + /* methods */ + (destructor)filter_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 | + Py_TPFLAGS_BASETYPE, /* tp_flags */ + filter_doc, /* tp_doc */ + (traverseproc)filter_traverse, /* tp_traverse */ + 0, /* tp_clear */ + 0, /* tp_richcompare */ + 0, /* tp_weaklistoffset */ + PyObject_SelfIter, /* tp_iter */ + (iternextfunc)filter_next, /* tp_iternext */ + 0, /* tp_methods */ + 0, /* tp_members */ + 0, /* tp_getset */ + 0, /* tp_base */ + 0, /* tp_dict */ + 0, /* tp_descr_get */ + 0, /* tp_descr_set */ + 0, /* tp_dictoffset */ + 0, /* tp_init */ + PyType_GenericAlloc, /* tp_alloc */ + filter_new, /* tp_new */ + PyObject_GC_Del, /* tp_free */ }; @@ -468,7 +468,7 @@ PyObject *format_spec = NULL; if (!PyArg_ParseTuple(args, "O|U:format", &value, &format_spec)) - return NULL; + return NULL; return PyObject_Format(value, format_spec); } @@ -482,12 +482,12 @@ static PyObject * builtin_chr(PyObject *self, PyObject *args) { - int x; + int x; - if (!PyArg_ParseTuple(args, "i:chr", &x)) - return NULL; + if (!PyArg_ParseTuple(args, "i:chr", &x)) + return NULL; - return PyUnicode_FromOrdinal(x); + return PyUnicode_FromOrdinal(x); } PyDoc_VAR(chr_doc) = PyDoc_STR( @@ -506,111 +506,111 @@ static char * source_as_string(PyObject *cmd, char *funcname, char *what, PyCompilerFlags *cf) { - char *str; - Py_ssize_t size; + char *str; + Py_ssize_t size; - if (PyUnicode_Check(cmd)) { - cf->cf_flags |= PyCF_IGNORE_COOKIE; - cmd = _PyUnicode_AsDefaultEncodedString(cmd, NULL); - if (cmd == NULL) - return NULL; - } - else if (!PyObject_CheckReadBuffer(cmd)) { - PyErr_Format(PyExc_TypeError, - "%s() arg 1 must be a %s object", - funcname, what); - return NULL; - } - if (PyObject_AsReadBuffer(cmd, (const void **)&str, &size) < 0) { - return NULL; - } - if (strlen(str) != size) { - PyErr_SetString(PyExc_TypeError, - "source code string cannot contain null bytes"); - return NULL; - } - return str; + if (PyUnicode_Check(cmd)) { + cf->cf_flags |= PyCF_IGNORE_COOKIE; + cmd = _PyUnicode_AsDefaultEncodedString(cmd, NULL); + if (cmd == NULL) + return NULL; + } + else if (!PyObject_CheckReadBuffer(cmd)) { + PyErr_Format(PyExc_TypeError, + "%s() arg 1 must be a %s object", + funcname, what); + return NULL; + } + if (PyObject_AsReadBuffer(cmd, (const void **)&str, &size) < 0) { + return NULL; + } + if (strlen(str) != size) { + PyErr_SetString(PyExc_TypeError, + "source code string cannot contain null bytes"); + return NULL; + } + return str; } static PyObject * builtin_compile(PyObject *self, PyObject *args, PyObject *kwds) { - char *str; - char *filename; - char *startstr; - int mode = -1; - int dont_inherit = 0; - int supplied_flags = 0; - int is_ast; - PyCompilerFlags cf; - PyObject *cmd; - static char *kwlist[] = {"source", "filename", "mode", "flags", - "dont_inherit", NULL}; - int start[] = {Py_file_input, Py_eval_input, Py_single_input}; - - if (!PyArg_ParseTupleAndKeywords(args, kwds, "Oss|ii:compile", - kwlist, &cmd, &filename, &startstr, - &supplied_flags, &dont_inherit)) - return NULL; - - cf.cf_flags = supplied_flags | PyCF_SOURCE_IS_UTF8; - - if (supplied_flags & - ~(PyCF_MASK | PyCF_MASK_OBSOLETE | PyCF_DONT_IMPLY_DEDENT | PyCF_ONLY_AST)) - { - PyErr_SetString(PyExc_ValueError, - "compile(): unrecognised flags"); - return NULL; - } - /* XXX Warn if (supplied_flags & PyCF_MASK_OBSOLETE) != 0? */ - - if (!dont_inherit) { - PyEval_MergeCompilerFlags(&cf); - } - - if (strcmp(startstr, "exec") == 0) - mode = 0; - else if (strcmp(startstr, "eval") == 0) - mode = 1; - else if (strcmp(startstr, "single") == 0) - mode = 2; - else { - PyErr_SetString(PyExc_ValueError, - "compile() arg 3 must be 'exec', 'eval' or 'single'"); - return NULL; - } - - is_ast = PyAST_Check(cmd); - if (is_ast == -1) - return NULL; - if (is_ast) { - PyObject *result; - if (supplied_flags & PyCF_ONLY_AST) { - Py_INCREF(cmd); - result = cmd; - } - else { - PyArena *arena; - mod_ty mod; - - arena = PyArena_New(); - mod = PyAST_obj2mod(cmd, arena, mode); - if (mod == NULL) { - PyArena_Free(arena); - return NULL; - } - result = (PyObject*)PyAST_Compile(mod, filename, - &cf, arena); - PyArena_Free(arena); - } - return result; - } - - str = source_as_string(cmd, "compile", "string, bytes, AST or code", &cf); - if (str == NULL) - return NULL; + char *str; + char *filename; + char *startstr; + int mode = -1; + int dont_inherit = 0; + int supplied_flags = 0; + int is_ast; + PyCompilerFlags cf; + PyObject *cmd; + static char *kwlist[] = {"source", "filename", "mode", "flags", + "dont_inherit", NULL}; + int start[] = {Py_file_input, Py_eval_input, Py_single_input}; + + if (!PyArg_ParseTupleAndKeywords(args, kwds, "Oss|ii:compile", + kwlist, &cmd, &filename, &startstr, + &supplied_flags, &dont_inherit)) + return NULL; + + cf.cf_flags = supplied_flags | PyCF_SOURCE_IS_UTF8; + + if (supplied_flags & + ~(PyCF_MASK | PyCF_MASK_OBSOLETE | PyCF_DONT_IMPLY_DEDENT | PyCF_ONLY_AST)) + { + PyErr_SetString(PyExc_ValueError, + "compile(): unrecognised flags"); + return NULL; + } + /* XXX Warn if (supplied_flags & PyCF_MASK_OBSOLETE) != 0? */ + + if (!dont_inherit) { + PyEval_MergeCompilerFlags(&cf); + } + + if (strcmp(startstr, "exec") == 0) + mode = 0; + else if (strcmp(startstr, "eval") == 0) + mode = 1; + else if (strcmp(startstr, "single") == 0) + mode = 2; + else { + PyErr_SetString(PyExc_ValueError, + "compile() arg 3 must be 'exec', 'eval' or 'single'"); + return NULL; + } + + is_ast = PyAST_Check(cmd); + if (is_ast == -1) + return NULL; + if (is_ast) { + PyObject *result; + if (supplied_flags & PyCF_ONLY_AST) { + Py_INCREF(cmd); + result = cmd; + } + else { + PyArena *arena; + mod_ty mod; + + arena = PyArena_New(); + mod = PyAST_obj2mod(cmd, arena, mode); + if (mod == NULL) { + PyArena_Free(arena); + return NULL; + } + result = (PyObject*)PyAST_Compile(mod, filename, + &cf, arena); + PyArena_Free(arena); + } + return result; + } - return Py_CompileStringFlags(str, filename, start[mode], &cf); + str = source_as_string(cmd, "compile", "string, bytes, AST or code", &cf); + if (str == NULL) + return NULL; + + return Py_CompileStringFlags(str, filename, start[mode], &cf); } PyDoc_STRVAR(compile_doc, @@ -631,11 +631,11 @@ static PyObject * builtin_dir(PyObject *self, PyObject *args) { - PyObject *arg = NULL; + PyObject *arg = NULL; - if (!PyArg_UnpackTuple(args, "dir", 0, 1, &arg)) - return NULL; - return PyObject_Dir(arg); + if (!PyArg_UnpackTuple(args, "dir", 0, 1, &arg)) + return NULL; + return PyObject_Dir(arg); } PyDoc_STRVAR(dir_doc, @@ -655,11 +655,11 @@ static PyObject * builtin_divmod(PyObject *self, PyObject *args) { - PyObject *v, *w; + PyObject *v, *w; - if (!PyArg_UnpackTuple(args, "divmod", 2, 2, &v, &w)) - return NULL; - return PyNumber_Divmod(v, w); + if (!PyArg_UnpackTuple(args, "divmod", 2, 2, &v, &w)) + return NULL; + return PyNumber_Divmod(v, w); } PyDoc_STRVAR(divmod_doc, @@ -671,65 +671,65 @@ static PyObject * builtin_eval(PyObject *self, PyObject *args) { - PyObject *cmd, *result, *tmp = NULL; - PyObject *globals = Py_None, *locals = Py_None; - char *str; - PyCompilerFlags cf; - - if (!PyArg_UnpackTuple(args, "eval", 1, 3, &cmd, &globals, &locals)) - return NULL; - if (locals != Py_None && !PyMapping_Check(locals)) { - PyErr_SetString(PyExc_TypeError, "locals must be a mapping"); - return NULL; - } - if (globals != Py_None && !PyDict_Check(globals)) { - PyErr_SetString(PyExc_TypeError, PyMapping_Check(globals) ? - "globals must be a real dict; try eval(expr, {}, mapping)" - : "globals must be a dict"); - return NULL; - } - if (globals == Py_None) { - globals = PyEval_GetGlobals(); - if (locals == Py_None) - locals = PyEval_GetLocals(); - } - else if (locals == Py_None) - locals = globals; - - if (globals == NULL || locals == NULL) { - PyErr_SetString(PyExc_TypeError, - "eval must be given globals and locals " - "when called without a frame"); - return NULL; - } - - if (PyDict_GetItemString(globals, "__builtins__") == NULL) { - if (PyDict_SetItemString(globals, "__builtins__", - PyEval_GetBuiltins()) != 0) - return NULL; - } - - if (PyCode_Check(cmd)) { - if (PyCode_GetNumFree((PyCodeObject *)cmd) > 0) { - PyErr_SetString(PyExc_TypeError, - "code object passed to eval() may not contain free variables"); - return NULL; - } - return PyEval_EvalCode((PyCodeObject *) cmd, globals, locals); - } - - cf.cf_flags = PyCF_SOURCE_IS_UTF8; - str = source_as_string(cmd, "eval", "string, bytes or code", &cf); - if (str == NULL) - return NULL; - - while (*str == ' ' || *str == '\t') - str++; - - (void)PyEval_MergeCompilerFlags(&cf); - result = PyRun_StringFlags(str, Py_eval_input, globals, locals, &cf); - Py_XDECREF(tmp); - return result; + PyObject *cmd, *result, *tmp = NULL; + PyObject *globals = Py_None, *locals = Py_None; + char *str; + PyCompilerFlags cf; + + if (!PyArg_UnpackTuple(args, "eval", 1, 3, &cmd, &globals, &locals)) + return NULL; + if (locals != Py_None && !PyMapping_Check(locals)) { + PyErr_SetString(PyExc_TypeError, "locals must be a mapping"); + return NULL; + } + if (globals != Py_None && !PyDict_Check(globals)) { + PyErr_SetString(PyExc_TypeError, PyMapping_Check(globals) ? + "globals must be a real dict; try eval(expr, {}, mapping)" + : "globals must be a dict"); + return NULL; + } + if (globals == Py_None) { + globals = PyEval_GetGlobals(); + if (locals == Py_None) + locals = PyEval_GetLocals(); + } + else if (locals == Py_None) + locals = globals; + + if (globals == NULL || locals == NULL) { + PyErr_SetString(PyExc_TypeError, + "eval must be given globals and locals " + "when called without a frame"); + return NULL; + } + + if (PyDict_GetItemString(globals, "__builtins__") == NULL) { + if (PyDict_SetItemString(globals, "__builtins__", + PyEval_GetBuiltins()) != 0) + return NULL; + } + + if (PyCode_Check(cmd)) { + if (PyCode_GetNumFree((PyCodeObject *)cmd) > 0) { + PyErr_SetString(PyExc_TypeError, + "code object passed to eval() may not contain free variables"); + return NULL; + } + return PyEval_EvalCode((PyCodeObject *) cmd, globals, locals); + } + + cf.cf_flags = PyCF_SOURCE_IS_UTF8; + str = source_as_string(cmd, "eval", "string, bytes or code", &cf); + if (str == NULL) + return NULL; + + while (*str == ' ' || *str == '\t') + str++; + + (void)PyEval_MergeCompilerFlags(&cf); + result = PyRun_StringFlags(str, Py_eval_input, globals, locals, &cf); + Py_XDECREF(tmp); + return result; } PyDoc_STRVAR(eval_doc, @@ -745,72 +745,72 @@ static PyObject * builtin_exec(PyObject *self, PyObject *args) { - PyObject *v; - PyObject *prog, *globals = Py_None, *locals = Py_None; - int plain = 0; - - if (!PyArg_UnpackTuple(args, "exec", 1, 3, &prog, &globals, &locals)) - return NULL; - - if (globals == Py_None) { - globals = PyEval_GetGlobals(); - if (locals == Py_None) { - locals = PyEval_GetLocals(); - plain = 1; - } - if (!globals || !locals) { - PyErr_SetString(PyExc_SystemError, - "globals and locals cannot be NULL"); - return NULL; - } - } - else if (locals == Py_None) - locals = globals; - - if (!PyDict_Check(globals)) { - PyErr_Format(PyExc_TypeError, "exec() arg 2 must be a dict, not %.100s", - globals->ob_type->tp_name); - return NULL; - } - if (!PyMapping_Check(locals)) { - PyErr_Format(PyExc_TypeError, - "arg 3 must be a mapping or None, not %.100s", - locals->ob_type->tp_name); - return NULL; - } - if (PyDict_GetItemString(globals, "__builtins__") == NULL) { - if (PyDict_SetItemString(globals, "__builtins__", - PyEval_GetBuiltins()) != 0) - return NULL; - } - - if (PyCode_Check(prog)) { - if (PyCode_GetNumFree((PyCodeObject *)prog) > 0) { - PyErr_SetString(PyExc_TypeError, - "code object passed to exec() may not " - "contain free variables"); - return NULL; - } - v = PyEval_EvalCode((PyCodeObject *) prog, globals, locals); - } - else { - char *str; - PyCompilerFlags cf; - cf.cf_flags = PyCF_SOURCE_IS_UTF8; - str = source_as_string(prog, "exec", - "string, bytes or code", &cf); - if (str == NULL) - return NULL; - if (PyEval_MergeCompilerFlags(&cf)) - v = PyRun_StringFlags(str, Py_file_input, globals, - locals, &cf); - else - v = PyRun_String(str, Py_file_input, globals, locals); - } - if (v == NULL) - return NULL; - Py_DECREF(v); - Py_RETURN_NONE; + PyObject *v; + PyObject *prog, *globals = Py_None, *locals = Py_None; + int plain = 0; + + if (!PyArg_UnpackTuple(args, "exec", 1, 3, &prog, &globals, &locals)) + return NULL; + + if (globals == Py_None) { + globals = PyEval_GetGlobals(); + if (locals == Py_None) { + locals = PyEval_GetLocals(); + plain = 1; + } + if (!globals || !locals) { + PyErr_SetString(PyExc_SystemError, + "globals and locals cannot be NULL"); + return NULL; + } + } + else if (locals == Py_None) + locals = globals; + + if (!PyDict_Check(globals)) { + PyErr_Format(PyExc_TypeError, "exec() arg 2 must be a dict, not %.100s", + globals->ob_type->tp_name); + return NULL; + } + if (!PyMapping_Check(locals)) { + PyErr_Format(PyExc_TypeError, + "arg 3 must be a mapping or None, not %.100s", + locals->ob_type->tp_name); + return NULL; + } + if (PyDict_GetItemString(globals, "__builtins__") == NULL) { + if (PyDict_SetItemString(globals, "__builtins__", + PyEval_GetBuiltins()) != 0) + return NULL; + } + + if (PyCode_Check(prog)) { + if (PyCode_GetNumFree((PyCodeObject *)prog) > 0) { + PyErr_SetString(PyExc_TypeError, + "code object passed to exec() may not " + "contain free variables"); + return NULL; + } + v = PyEval_EvalCode((PyCodeObject *) prog, globals, locals); + } + else { + char *str; + PyCompilerFlags cf; + cf.cf_flags = PyCF_SOURCE_IS_UTF8; + str = source_as_string(prog, "exec", + "string, bytes or code", &cf); + if (str == NULL) + return NULL; + if (PyEval_MergeCompilerFlags(&cf)) + v = PyRun_StringFlags(str, Py_file_input, globals, + locals, &cf); + else + v = PyRun_String(str, Py_file_input, globals, locals); + } + if (v == NULL) + return NULL; + Py_DECREF(v); + Py_RETURN_NONE; } PyDoc_STRVAR(exec_doc, @@ -825,26 +825,26 @@ static PyObject * builtin_getattr(PyObject *self, PyObject *args) { - PyObject *v, *result, *dflt = NULL; - PyObject *name; + PyObject *v, *result, *dflt = NULL; + PyObject *name; - if (!PyArg_UnpackTuple(args, "getattr", 2, 3, &v, &name, &dflt)) - return NULL; + if (!PyArg_UnpackTuple(args, "getattr", 2, 3, &v, &name, &dflt)) + return NULL; - if (!PyUnicode_Check(name)) { - PyErr_SetString(PyExc_TypeError, - "getattr(): attribute name must be string"); - return NULL; - } - result = PyObject_GetAttr(v, name); - if (result == NULL && dflt != NULL && - PyErr_ExceptionMatches(PyExc_AttributeError)) - { - PyErr_Clear(); - Py_INCREF(dflt); - result = dflt; - } - return result; + if (!PyUnicode_Check(name)) { + PyErr_SetString(PyExc_TypeError, + "getattr(): attribute name must be string"); + return NULL; + } + result = PyObject_GetAttr(v, name); + if (result == NULL && dflt != NULL && + PyErr_ExceptionMatches(PyExc_AttributeError)) + { + PyErr_Clear(); + Py_INCREF(dflt); + result = dflt; + } + return result; } PyDoc_STRVAR(getattr_doc, @@ -858,11 +858,11 @@ static PyObject * builtin_globals(PyObject *self) { - PyObject *d; + PyObject *d; - d = PyEval_GetGlobals(); - Py_XINCREF(d); - return d; + d = PyEval_GetGlobals(); + Py_XINCREF(d); + return d; } PyDoc_STRVAR(globals_doc, @@ -874,29 +874,29 @@ static PyObject * builtin_hasattr(PyObject *self, PyObject *args) { - PyObject *v; - PyObject *name; + PyObject *v; + PyObject *name; - if (!PyArg_UnpackTuple(args, "hasattr", 2, 2, &v, &name)) - return NULL; - if (!PyUnicode_Check(name)) { - PyErr_SetString(PyExc_TypeError, - "hasattr(): attribute name must be string"); - return NULL; - } - v = PyObject_GetAttr(v, name); - if (v == NULL) { - if (!PyErr_ExceptionMatches(PyExc_Exception)) - return NULL; - else { - PyErr_Clear(); - Py_INCREF(Py_False); - return Py_False; - } - } - Py_DECREF(v); - Py_INCREF(Py_True); - return Py_True; + if (!PyArg_UnpackTuple(args, "hasattr", 2, 2, &v, &name)) + return NULL; + if (!PyUnicode_Check(name)) { + PyErr_SetString(PyExc_TypeError, + "hasattr(): attribute name must be string"); + return NULL; + } + v = PyObject_GetAttr(v, name); + if (v == NULL) { + if (!PyErr_ExceptionMatches(PyExc_Exception)) + return NULL; + else { + PyErr_Clear(); + Py_INCREF(Py_False); + return Py_False; + } + } + Py_DECREF(v); + Py_INCREF(Py_True); + return Py_True; } PyDoc_STRVAR(hasattr_doc, @@ -909,7 +909,7 @@ static PyObject * builtin_id(PyObject *self, PyObject *v) { - return PyLong_FromVoidPtr(v); + return PyLong_FromVoidPtr(v); } PyDoc_STRVAR(id_doc, @@ -922,181 +922,181 @@ /* map object ************************************************************/ typedef struct { - PyObject_HEAD - PyObject *iters; - PyObject *func; + PyObject_HEAD + PyObject *iters; + PyObject *func; } mapobject; static PyObject * map_new(PyTypeObject *type, PyObject *args, PyObject *kwds) { - PyObject *it, *iters, *func; - mapobject *lz; - Py_ssize_t numargs, i; - - if (type == &PyMap_Type && !_PyArg_NoKeywords("map()", kwds)) - return NULL; - - numargs = PyTuple_Size(args); - if (numargs < 2) { - PyErr_SetString(PyExc_TypeError, - "map() must have at least two arguments."); - return NULL; - } - - iters = PyTuple_New(numargs-1); - if (iters == NULL) - return NULL; - - for (i=1 ; itp_alloc(type, 0); - if (lz == NULL) { - Py_DECREF(iters); - return NULL; - } - lz->iters = iters; - func = PyTuple_GET_ITEM(args, 0); - Py_INCREF(func); - lz->func = func; + PyObject *it, *iters, *func; + mapobject *lz; + Py_ssize_t numargs, i; - return (PyObject *)lz; + if (type == &PyMap_Type && !_PyArg_NoKeywords("map()", kwds)) + return NULL; + + numargs = PyTuple_Size(args); + if (numargs < 2) { + PyErr_SetString(PyExc_TypeError, + "map() must have at least two arguments."); + return NULL; + } + + iters = PyTuple_New(numargs-1); + if (iters == NULL) + return NULL; + + for (i=1 ; itp_alloc(type, 0); + if (lz == NULL) { + Py_DECREF(iters); + return NULL; + } + lz->iters = iters; + func = PyTuple_GET_ITEM(args, 0); + Py_INCREF(func); + lz->func = func; + + return (PyObject *)lz; } static void map_dealloc(mapobject *lz) { - PyObject_GC_UnTrack(lz); - Py_XDECREF(lz->iters); - Py_XDECREF(lz->func); - Py_TYPE(lz)->tp_free(lz); + PyObject_GC_UnTrack(lz); + Py_XDECREF(lz->iters); + Py_XDECREF(lz->func); + Py_TYPE(lz)->tp_free(lz); } static int map_traverse(mapobject *lz, visitproc visit, void *arg) { - Py_VISIT(lz->iters); - Py_VISIT(lz->func); - return 0; + Py_VISIT(lz->iters); + Py_VISIT(lz->func); + return 0; } static PyObject * map_next(mapobject *lz) { - PyObject *val; - PyObject *argtuple; - PyObject *result; - Py_ssize_t numargs, i; - - numargs = PyTuple_Size(lz->iters); - argtuple = PyTuple_New(numargs); - if (argtuple == NULL) - return NULL; - - for (i=0 ; iiters, i)); - if (val == NULL) { - Py_DECREF(argtuple); - return NULL; - } - PyTuple_SET_ITEM(argtuple, i, val); - } - result = PyObject_Call(lz->func, argtuple, NULL); - Py_DECREF(argtuple); - return result; + PyObject *val; + PyObject *argtuple; + PyObject *result; + Py_ssize_t numargs, i; + + numargs = PyTuple_Size(lz->iters); + argtuple = PyTuple_New(numargs); + if (argtuple == NULL) + return NULL; + + for (i=0 ; iiters, i)); + if (val == NULL) { + Py_DECREF(argtuple); + return NULL; + } + PyTuple_SET_ITEM(argtuple, i, val); + } + result = PyObject_Call(lz->func, argtuple, NULL); + Py_DECREF(argtuple); + return result; } PyDoc_STRVAR(map_doc, "map(func, *iterables) --> map object\n\ \n\ Make an iterator that computes the function using arguments from\n\ -each of the iterables. Stops when the shortest iterable is exhausted."); +each of the iterables. Stops when the shortest iterable is exhausted."); PyTypeObject PyMap_Type = { - PyVarObject_HEAD_INIT(&PyType_Type, 0) - "map", /* tp_name */ - sizeof(mapobject), /* tp_basicsize */ - 0, /* tp_itemsize */ - /* methods */ - (destructor)map_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 | - Py_TPFLAGS_BASETYPE, /* tp_flags */ - map_doc, /* tp_doc */ - (traverseproc)map_traverse, /* tp_traverse */ - 0, /* tp_clear */ - 0, /* tp_richcompare */ - 0, /* tp_weaklistoffset */ - PyObject_SelfIter, /* tp_iter */ - (iternextfunc)map_next, /* tp_iternext */ - 0, /* tp_methods */ - 0, /* tp_members */ - 0, /* tp_getset */ - 0, /* tp_base */ - 0, /* tp_dict */ - 0, /* tp_descr_get */ - 0, /* tp_descr_set */ - 0, /* tp_dictoffset */ - 0, /* tp_init */ - PyType_GenericAlloc, /* tp_alloc */ - map_new, /* tp_new */ - PyObject_GC_Del, /* tp_free */ + PyVarObject_HEAD_INIT(&PyType_Type, 0) + "map", /* tp_name */ + sizeof(mapobject), /* tp_basicsize */ + 0, /* tp_itemsize */ + /* methods */ + (destructor)map_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 | + Py_TPFLAGS_BASETYPE, /* tp_flags */ + map_doc, /* tp_doc */ + (traverseproc)map_traverse, /* tp_traverse */ + 0, /* tp_clear */ + 0, /* tp_richcompare */ + 0, /* tp_weaklistoffset */ + PyObject_SelfIter, /* tp_iter */ + (iternextfunc)map_next, /* tp_iternext */ + 0, /* tp_methods */ + 0, /* tp_members */ + 0, /* tp_getset */ + 0, /* tp_base */ + 0, /* tp_dict */ + 0, /* tp_descr_get */ + 0, /* tp_descr_set */ + 0, /* tp_dictoffset */ + 0, /* tp_init */ + PyType_GenericAlloc, /* tp_alloc */ + map_new, /* tp_new */ + PyObject_GC_Del, /* tp_free */ }; static PyObject * builtin_next(PyObject *self, PyObject *args) { - PyObject *it, *res; - PyObject *def = NULL; + PyObject *it, *res; + PyObject *def = NULL; + + if (!PyArg_UnpackTuple(args, "next", 1, 2, &it, &def)) + return NULL; + if (!PyIter_Check(it)) { + PyErr_Format(PyExc_TypeError, + "%.200s object is not an iterator", + it->ob_type->tp_name); + return NULL; + } - if (!PyArg_UnpackTuple(args, "next", 1, 2, &it, &def)) - return NULL; - if (!PyIter_Check(it)) { - PyErr_Format(PyExc_TypeError, - "%.200s object is not an iterator", - it->ob_type->tp_name); - return NULL; - } - - res = (*it->ob_type->tp_iternext)(it); - if (res != NULL) { - return res; - } else if (def != NULL) { - if (PyErr_Occurred()) { - if(!PyErr_ExceptionMatches(PyExc_StopIteration)) - return NULL; - PyErr_Clear(); - } - Py_INCREF(def); - return def; - } else if (PyErr_Occurred()) { - return NULL; - } else { - PyErr_SetNone(PyExc_StopIteration); - return NULL; - } + res = (*it->ob_type->tp_iternext)(it); + if (res != NULL) { + return res; + } else if (def != NULL) { + if (PyErr_Occurred()) { + if(!PyErr_ExceptionMatches(PyExc_StopIteration)) + return NULL; + PyErr_Clear(); + } + Py_INCREF(def); + return def; + } else if (PyErr_Occurred()) { + return NULL; + } else { + PyErr_SetNone(PyExc_StopIteration); + return NULL; + } } PyDoc_STRVAR(next_doc, @@ -1109,16 +1109,16 @@ static PyObject * builtin_setattr(PyObject *self, PyObject *args) { - PyObject *v; - PyObject *name; - PyObject *value; - - if (!PyArg_UnpackTuple(args, "setattr", 3, 3, &v, &name, &value)) - return NULL; - if (PyObject_SetAttr(v, name, value) != 0) - return NULL; - Py_INCREF(Py_None); - return Py_None; + PyObject *v; + PyObject *name; + PyObject *value; + + if (!PyArg_UnpackTuple(args, "setattr", 3, 3, &v, &name, &value)) + return NULL; + if (PyObject_SetAttr(v, name, value) != 0) + return NULL; + Py_INCREF(Py_None); + return Py_None; } PyDoc_STRVAR(setattr_doc, @@ -1131,15 +1131,15 @@ static PyObject * builtin_delattr(PyObject *self, PyObject *args) { - PyObject *v; - PyObject *name; + PyObject *v; + PyObject *name; - if (!PyArg_UnpackTuple(args, "delattr", 2, 2, &v, &name)) - return NULL; - if (PyObject_SetAttr(v, name, (PyObject *)NULL) != 0) - return NULL; - Py_INCREF(Py_None); - return Py_None; + if (!PyArg_UnpackTuple(args, "delattr", 2, 2, &v, &name)) + return NULL; + if (PyObject_SetAttr(v, name, (PyObject *)NULL) != 0) + return NULL; + Py_INCREF(Py_None); + return Py_None; } PyDoc_STRVAR(delattr_doc, @@ -1152,12 +1152,12 @@ static PyObject * builtin_hash(PyObject *self, PyObject *v) { - long x; + long x; - x = PyObject_Hash(v); - if (x == -1) - return NULL; - return PyLong_FromLong(x); + x = PyObject_Hash(v); + if (x == -1) + return NULL; + return PyLong_FromLong(x); } PyDoc_STRVAR(hash_doc, @@ -1170,7 +1170,7 @@ static PyObject * builtin_hex(PyObject *self, PyObject *v) { - return PyNumber_ToBase(v, 16); + return PyNumber_ToBase(v, 16); } PyDoc_STRVAR(hex_doc, @@ -1182,18 +1182,18 @@ static PyObject * builtin_iter(PyObject *self, PyObject *args) { - PyObject *v, *w = NULL; + PyObject *v, *w = NULL; - if (!PyArg_UnpackTuple(args, "iter", 1, 2, &v, &w)) - return NULL; - if (w == NULL) - return PyObject_GetIter(v); - if (!PyCallable_Check(v)) { - PyErr_SetString(PyExc_TypeError, - "iter(v, w): v must be callable"); - return NULL; - } - return PyCallIter_New(v, w); + if (!PyArg_UnpackTuple(args, "iter", 1, 2, &v, &w)) + return NULL; + if (w == NULL) + return PyObject_GetIter(v); + if (!PyCallable_Check(v)) { + PyErr_SetString(PyExc_TypeError, + "iter(v, w): v must be callable"); + return NULL; + } + return PyCallIter_New(v, w); } PyDoc_STRVAR(iter_doc, @@ -1208,12 +1208,12 @@ static PyObject * builtin_len(PyObject *self, PyObject *v) { - Py_ssize_t res; + Py_ssize_t res; - res = PyObject_Size(v); - if (res < 0 && PyErr_Occurred()) - return NULL; - return PyLong_FromSsize_t(res); + res = PyObject_Size(v); + if (res < 0 && PyErr_Occurred()) + return NULL; + return PyLong_FromSsize_t(res); } PyDoc_STRVAR(len_doc, @@ -1225,11 +1225,11 @@ static PyObject * builtin_locals(PyObject *self) { - PyObject *d; + PyObject *d; - d = PyEval_GetLocals(); - Py_XINCREF(d); - return d; + d = PyEval_GetLocals(); + Py_XINCREF(d); + return d; } PyDoc_STRVAR(locals_doc, @@ -1241,96 +1241,96 @@ static PyObject * min_max(PyObject *args, PyObject *kwds, int op) { - PyObject *v, *it, *item, *val, *maxitem, *maxval, *keyfunc=NULL; - const char *name = op == Py_LT ? "min" : "max"; + PyObject *v, *it, *item, *val, *maxitem, *maxval, *keyfunc=NULL; + const char *name = op == Py_LT ? "min" : "max"; + + if (PyTuple_Size(args) > 1) + v = args; + else if (!PyArg_UnpackTuple(args, (char *)name, 1, 1, &v)) + return NULL; - if (PyTuple_Size(args) > 1) - v = args; - else if (!PyArg_UnpackTuple(args, (char *)name, 1, 1, &v)) - return NULL; - - if (kwds != NULL && PyDict_Check(kwds) && PyDict_Size(kwds)) { - keyfunc = PyDict_GetItemString(kwds, "key"); - if (PyDict_Size(kwds)!=1 || keyfunc == NULL) { - PyErr_Format(PyExc_TypeError, - "%s() got an unexpected keyword argument", name); - return NULL; - } - Py_INCREF(keyfunc); - } - - it = PyObject_GetIter(v); - if (it == NULL) { - Py_XDECREF(keyfunc); - return NULL; - } - - maxitem = NULL; /* the result */ - maxval = NULL; /* the value associated with the result */ - while (( item = PyIter_Next(it) )) { - /* get the value from the key function */ - if (keyfunc != NULL) { - val = PyObject_CallFunctionObjArgs(keyfunc, item, NULL); - if (val == NULL) - goto Fail_it_item; - } - /* no key function; the value is the item */ - else { - val = item; - Py_INCREF(val); - } - - /* maximum value and item are unset; set them */ - if (maxval == NULL) { - maxitem = item; - maxval = val; - } - /* maximum value and item are set; update them as necessary */ - else { - int cmp = PyObject_RichCompareBool(val, maxval, op); - if (cmp < 0) - goto Fail_it_item_and_val; - else if (cmp > 0) { - Py_DECREF(maxval); - Py_DECREF(maxitem); - maxval = val; - maxitem = item; - } - else { - Py_DECREF(item); - Py_DECREF(val); - } - } - } - if (PyErr_Occurred()) - goto Fail_it; - if (maxval == NULL) { - PyErr_Format(PyExc_ValueError, - "%s() arg is an empty sequence", name); - assert(maxitem == NULL); - } - else - Py_DECREF(maxval); - Py_DECREF(it); - Py_XDECREF(keyfunc); - return maxitem; + if (kwds != NULL && PyDict_Check(kwds) && PyDict_Size(kwds)) { + keyfunc = PyDict_GetItemString(kwds, "key"); + if (PyDict_Size(kwds)!=1 || keyfunc == NULL) { + PyErr_Format(PyExc_TypeError, + "%s() got an unexpected keyword argument", name); + return NULL; + } + Py_INCREF(keyfunc); + } + + it = PyObject_GetIter(v); + if (it == NULL) { + Py_XDECREF(keyfunc); + return NULL; + } + + maxitem = NULL; /* the result */ + maxval = NULL; /* the value associated with the result */ + while (( item = PyIter_Next(it) )) { + /* get the value from the key function */ + if (keyfunc != NULL) { + val = PyObject_CallFunctionObjArgs(keyfunc, item, NULL); + if (val == NULL) + goto Fail_it_item; + } + /* no key function; the value is the item */ + else { + val = item; + Py_INCREF(val); + } + + /* maximum value and item are unset; set them */ + if (maxval == NULL) { + maxitem = item; + maxval = val; + } + /* maximum value and item are set; update them as necessary */ + else { + int cmp = PyObject_RichCompareBool(val, maxval, op); + if (cmp < 0) + goto Fail_it_item_and_val; + else if (cmp > 0) { + Py_DECREF(maxval); + Py_DECREF(maxitem); + maxval = val; + maxitem = item; + } + else { + Py_DECREF(item); + Py_DECREF(val); + } + } + } + if (PyErr_Occurred()) + goto Fail_it; + if (maxval == NULL) { + PyErr_Format(PyExc_ValueError, + "%s() arg is an empty sequence", name); + assert(maxitem == NULL); + } + else + Py_DECREF(maxval); + Py_DECREF(it); + Py_XDECREF(keyfunc); + return maxitem; Fail_it_item_and_val: - Py_DECREF(val); + Py_DECREF(val); Fail_it_item: - Py_DECREF(item); + Py_DECREF(item); Fail_it: - Py_XDECREF(maxval); - Py_XDECREF(maxitem); - Py_DECREF(it); - Py_XDECREF(keyfunc); - return NULL; + Py_XDECREF(maxval); + Py_XDECREF(maxitem); + Py_DECREF(it); + Py_XDECREF(keyfunc); + return NULL; } static PyObject * builtin_min(PyObject *self, PyObject *args, PyObject *kwds) { - return min_max(args, kwds, Py_LT); + return min_max(args, kwds, Py_LT); } PyDoc_STRVAR(min_doc, @@ -1344,7 +1344,7 @@ static PyObject * builtin_max(PyObject *self, PyObject *args, PyObject *kwds) { - return min_max(args, kwds, Py_GT); + return min_max(args, kwds, Py_GT); } PyDoc_STRVAR(max_doc, @@ -1358,7 +1358,7 @@ static PyObject * builtin_oct(PyObject *self, PyObject *v) { - return PyNumber_ToBase(v, 8); + return PyNumber_ToBase(v, 8); } PyDoc_STRVAR(oct_doc, @@ -1370,56 +1370,56 @@ static PyObject * builtin_ord(PyObject *self, PyObject* obj) { - long ord; - Py_ssize_t size; + long ord; + Py_ssize_t size; - if (PyBytes_Check(obj)) { - size = PyBytes_GET_SIZE(obj); - if (size == 1) { - ord = (long)((unsigned char)*PyBytes_AS_STRING(obj)); - return PyLong_FromLong(ord); - } - } - else if (PyUnicode_Check(obj)) { - size = PyUnicode_GET_SIZE(obj); - if (size == 1) { - ord = (long)*PyUnicode_AS_UNICODE(obj); - return PyLong_FromLong(ord); - } + if (PyBytes_Check(obj)) { + size = PyBytes_GET_SIZE(obj); + if (size == 1) { + ord = (long)((unsigned char)*PyBytes_AS_STRING(obj)); + return PyLong_FromLong(ord); + } + } + else if (PyUnicode_Check(obj)) { + size = PyUnicode_GET_SIZE(obj); + if (size == 1) { + ord = (long)*PyUnicode_AS_UNICODE(obj); + return PyLong_FromLong(ord); + } #ifndef Py_UNICODE_WIDE - if (size == 2) { - /* Decode a valid surrogate pair */ - int c0 = PyUnicode_AS_UNICODE(obj)[0]; - int c1 = PyUnicode_AS_UNICODE(obj)[1]; - if (0xD800 <= c0 && c0 <= 0xDBFF && - 0xDC00 <= c1 && c1 <= 0xDFFF) { - ord = ((((c0 & 0x03FF) << 10) | (c1 & 0x03FF)) + - 0x00010000); - return PyLong_FromLong(ord); - } - } + if (size == 2) { + /* Decode a valid surrogate pair */ + int c0 = PyUnicode_AS_UNICODE(obj)[0]; + int c1 = PyUnicode_AS_UNICODE(obj)[1]; + if (0xD800 <= c0 && c0 <= 0xDBFF && + 0xDC00 <= c1 && c1 <= 0xDFFF) { + ord = ((((c0 & 0x03FF) << 10) | (c1 & 0x03FF)) + + 0x00010000); + return PyLong_FromLong(ord); + } + } #endif - } - else if (PyByteArray_Check(obj)) { - /* XXX Hopefully this is temporary */ - size = PyByteArray_GET_SIZE(obj); - if (size == 1) { - ord = (long)((unsigned char)*PyByteArray_AS_STRING(obj)); - return PyLong_FromLong(ord); - } - } - else { - PyErr_Format(PyExc_TypeError, - "ord() expected string of length 1, but " \ - "%.200s found", obj->ob_type->tp_name); - return NULL; - } - - PyErr_Format(PyExc_TypeError, - "ord() expected a character, " - "but string of length %zd found", - size); - return NULL; + } + else if (PyByteArray_Check(obj)) { + /* XXX Hopefully this is temporary */ + size = PyByteArray_GET_SIZE(obj); + if (size == 1) { + ord = (long)((unsigned char)*PyByteArray_AS_STRING(obj)); + return PyLong_FromLong(ord); + } + } + else { + PyErr_Format(PyExc_TypeError, + "ord() expected string of length 1, but " \ + "%.200s found", obj->ob_type->tp_name); + return NULL; + } + + PyErr_Format(PyExc_TypeError, + "ord() expected a character, " + "but string of length %zd found", + size); + return NULL; } PyDoc_VAR(ord_doc) = PyDoc_STR( @@ -1438,11 +1438,11 @@ static PyObject * builtin_pow(PyObject *self, PyObject *args) { - PyObject *v, *w, *z = Py_None; + PyObject *v, *w, *z = Py_None; - if (!PyArg_UnpackTuple(args, "pow", 2, 3, &v, &w, &z)) - return NULL; - return PyNumber_Power(v, w, z); + if (!PyArg_UnpackTuple(args, "pow", 2, 3, &v, &w, &z)) + return NULL; + return PyNumber_Power(v, w, z); } PyDoc_STRVAR(pow_doc, @@ -1456,68 +1456,68 @@ static PyObject * builtin_print(PyObject *self, PyObject *args, PyObject *kwds) { - static char *kwlist[] = {"sep", "end", "file", 0}; - static PyObject *dummy_args; - PyObject *sep = NULL, *end = NULL, *file = NULL; - int i, err; - - if (dummy_args == NULL) { - if (!(dummy_args = PyTuple_New(0))) - return NULL; - } - if (!PyArg_ParseTupleAndKeywords(dummy_args, kwds, "|OOO:print", - kwlist, &sep, &end, &file)) - return NULL; - if (file == NULL || file == Py_None) { - file = PySys_GetObject("stdout"); - /* sys.stdout may be None when FILE* stdout isn't connected */ - if (file == Py_None) - Py_RETURN_NONE; - } - - if (sep == Py_None) { - sep = NULL; - } - else if (sep && !PyUnicode_Check(sep)) { - PyErr_Format(PyExc_TypeError, - "sep must be None or a string, not %.200s", - sep->ob_type->tp_name); - return NULL; - } - if (end == Py_None) { - end = NULL; - } - else if (end && !PyUnicode_Check(end)) { - PyErr_Format(PyExc_TypeError, - "end must be None or a string, not %.200s", - end->ob_type->tp_name); - return NULL; - } - - for (i = 0; i < PyTuple_Size(args); i++) { - if (i > 0) { - if (sep == NULL) - err = PyFile_WriteString(" ", file); - else - err = PyFile_WriteObject(sep, file, - Py_PRINT_RAW); - if (err) - return NULL; - } - err = PyFile_WriteObject(PyTuple_GetItem(args, i), file, - Py_PRINT_RAW); - if (err) - return NULL; - } - - if (end == NULL) - err = PyFile_WriteString("\n", file); - else - err = PyFile_WriteObject(end, file, Py_PRINT_RAW); - if (err) - return NULL; + static char *kwlist[] = {"sep", "end", "file", 0}; + static PyObject *dummy_args; + PyObject *sep = NULL, *end = NULL, *file = NULL; + int i, err; + + if (dummy_args == NULL) { + if (!(dummy_args = PyTuple_New(0))) + return NULL; + } + if (!PyArg_ParseTupleAndKeywords(dummy_args, kwds, "|OOO:print", + kwlist, &sep, &end, &file)) + return NULL; + if (file == NULL || file == Py_None) { + file = PySys_GetObject("stdout"); + /* sys.stdout may be None when FILE* stdout isn't connected */ + if (file == Py_None) + Py_RETURN_NONE; + } + + if (sep == Py_None) { + sep = NULL; + } + else if (sep && !PyUnicode_Check(sep)) { + PyErr_Format(PyExc_TypeError, + "sep must be None or a string, not %.200s", + sep->ob_type->tp_name); + return NULL; + } + if (end == Py_None) { + end = NULL; + } + else if (end && !PyUnicode_Check(end)) { + PyErr_Format(PyExc_TypeError, + "end must be None or a string, not %.200s", + end->ob_type->tp_name); + return NULL; + } + + for (i = 0; i < PyTuple_Size(args); i++) { + if (i > 0) { + if (sep == NULL) + err = PyFile_WriteString(" ", file); + else + err = PyFile_WriteObject(sep, file, + Py_PRINT_RAW); + if (err) + return NULL; + } + err = PyFile_WriteObject(PyTuple_GetItem(args, i), file, + Py_PRINT_RAW); + if (err) + return NULL; + } + + if (end == NULL) + err = PyFile_WriteString("\n", file); + else + err = PyFile_WriteObject(end, file, Py_PRINT_RAW); + if (err) + return NULL; - Py_RETURN_NONE; + Py_RETURN_NONE; } PyDoc_STRVAR(print_doc, @@ -1533,164 +1533,164 @@ static PyObject * builtin_input(PyObject *self, PyObject *args) { - PyObject *promptarg = NULL; - PyObject *fin = PySys_GetObject("stdin"); - PyObject *fout = PySys_GetObject("stdout"); - PyObject *ferr = PySys_GetObject("stderr"); - PyObject *tmp; - long fd; - int tty; - - /* Parse arguments */ - if (!PyArg_UnpackTuple(args, "input", 0, 1, &promptarg)) - return NULL; - - /* Check that stdin/out/err are intact */ - if (fin == NULL || fin == Py_None) { - PyErr_SetString(PyExc_RuntimeError, - "input(): lost sys.stdin"); - return NULL; - } - if (fout == NULL || fout == Py_None) { - PyErr_SetString(PyExc_RuntimeError, - "input(): lost sys.stdout"); - return NULL; - } - if (ferr == NULL || ferr == Py_None) { - PyErr_SetString(PyExc_RuntimeError, - "input(): lost sys.stderr"); - return NULL; - } - - /* First of all, flush stderr */ - tmp = PyObject_CallMethod(ferr, "flush", ""); - if (tmp == NULL) - PyErr_Clear(); - else - Py_DECREF(tmp); - - /* We should only use (GNU) readline if Python's sys.stdin and - sys.stdout are the same as C's stdin and stdout, because we - need to pass it those. */ - tmp = PyObject_CallMethod(fin, "fileno", ""); - if (tmp == NULL) { - PyErr_Clear(); - tty = 0; - } - else { - fd = PyLong_AsLong(tmp); - Py_DECREF(tmp); - if (fd < 0 && PyErr_Occurred()) - return NULL; - tty = fd == fileno(stdin) && isatty(fd); - } - if (tty) { - tmp = PyObject_CallMethod(fout, "fileno", ""); - if (tmp == NULL) - PyErr_Clear(); - else { - fd = PyLong_AsLong(tmp); - Py_DECREF(tmp); - if (fd < 0 && PyErr_Occurred()) - return NULL; - tty = fd == fileno(stdout) && isatty(fd); - } - } - - /* If we're interactive, use (GNU) readline */ - if (tty) { - PyObject *po; - char *prompt; - char *s; - PyObject *stdin_encoding; - PyObject *result; - - stdin_encoding = PyObject_GetAttrString(fin, "encoding"); - if (!stdin_encoding) - /* stdin is a text stream, so it must have an - encoding. */ - return NULL; - tmp = PyObject_CallMethod(fout, "flush", ""); - if (tmp == NULL) - PyErr_Clear(); - else - Py_DECREF(tmp); - if (promptarg != NULL) { - PyObject *stringpo; - PyObject *stdout_encoding; - stdout_encoding = PyObject_GetAttrString(fout, - "encoding"); - if (stdout_encoding == NULL) { - Py_DECREF(stdin_encoding); - return NULL; - } - stringpo = PyObject_Str(promptarg); - if (stringpo == NULL) { - Py_DECREF(stdin_encoding); - Py_DECREF(stdout_encoding); - return NULL; - } - po = PyUnicode_AsEncodedString(stringpo, - _PyUnicode_AsString(stdout_encoding), NULL); - Py_DECREF(stdout_encoding); - Py_DECREF(stringpo); - if (po == NULL) { - Py_DECREF(stdin_encoding); - return NULL; - } - prompt = PyBytes_AsString(po); - if (prompt == NULL) { - Py_DECREF(stdin_encoding); - Py_DECREF(po); - return NULL; - } - } - else { - po = NULL; - prompt = ""; - } - s = PyOS_Readline(stdin, stdout, prompt); - Py_XDECREF(po); - if (s == NULL) { - if (!PyErr_Occurred()) - PyErr_SetNone(PyExc_KeyboardInterrupt); - Py_DECREF(stdin_encoding); - return NULL; - } - if (*s == '\0') { - PyErr_SetNone(PyExc_EOFError); - result = NULL; - } - else { /* strip trailing '\n' */ - size_t len = strlen(s); - if (len > PY_SSIZE_T_MAX) { - PyErr_SetString(PyExc_OverflowError, - "input: input too long"); - result = NULL; - } - else { - result = PyUnicode_Decode - (s, len-1, - _PyUnicode_AsString(stdin_encoding), - NULL); - } - } - Py_DECREF(stdin_encoding); - PyMem_FREE(s); - return result; - } - - /* Fallback if we're not interactive */ - if (promptarg != NULL) { - if (PyFile_WriteObject(promptarg, fout, Py_PRINT_RAW) != 0) - return NULL; - } - tmp = PyObject_CallMethod(fout, "flush", ""); - if (tmp == NULL) - PyErr_Clear(); - else - Py_DECREF(tmp); - return PyFile_GetLine(fin, -1); + PyObject *promptarg = NULL; + PyObject *fin = PySys_GetObject("stdin"); + PyObject *fout = PySys_GetObject("stdout"); + PyObject *ferr = PySys_GetObject("stderr"); + PyObject *tmp; + long fd; + int tty; + + /* Parse arguments */ + if (!PyArg_UnpackTuple(args, "input", 0, 1, &promptarg)) + return NULL; + + /* Check that stdin/out/err are intact */ + if (fin == NULL || fin == Py_None) { + PyErr_SetString(PyExc_RuntimeError, + "input(): lost sys.stdin"); + return NULL; + } + if (fout == NULL || fout == Py_None) { + PyErr_SetString(PyExc_RuntimeError, + "input(): lost sys.stdout"); + return NULL; + } + if (ferr == NULL || ferr == Py_None) { + PyErr_SetString(PyExc_RuntimeError, + "input(): lost sys.stderr"); + return NULL; + } + + /* First of all, flush stderr */ + tmp = PyObject_CallMethod(ferr, "flush", ""); + if (tmp == NULL) + PyErr_Clear(); + else + Py_DECREF(tmp); + + /* We should only use (GNU) readline if Python's sys.stdin and + sys.stdout are the same as C's stdin and stdout, because we + need to pass it those. */ + tmp = PyObject_CallMethod(fin, "fileno", ""); + if (tmp == NULL) { + PyErr_Clear(); + tty = 0; + } + else { + fd = PyLong_AsLong(tmp); + Py_DECREF(tmp); + if (fd < 0 && PyErr_Occurred()) + return NULL; + tty = fd == fileno(stdin) && isatty(fd); + } + if (tty) { + tmp = PyObject_CallMethod(fout, "fileno", ""); + if (tmp == NULL) + PyErr_Clear(); + else { + fd = PyLong_AsLong(tmp); + Py_DECREF(tmp); + if (fd < 0 && PyErr_Occurred()) + return NULL; + tty = fd == fileno(stdout) && isatty(fd); + } + } + + /* If we're interactive, use (GNU) readline */ + if (tty) { + PyObject *po; + char *prompt; + char *s; + PyObject *stdin_encoding; + PyObject *result; + + stdin_encoding = PyObject_GetAttrString(fin, "encoding"); + if (!stdin_encoding) + /* stdin is a text stream, so it must have an + encoding. */ + return NULL; + tmp = PyObject_CallMethod(fout, "flush", ""); + if (tmp == NULL) + PyErr_Clear(); + else + Py_DECREF(tmp); + if (promptarg != NULL) { + PyObject *stringpo; + PyObject *stdout_encoding; + stdout_encoding = PyObject_GetAttrString(fout, + "encoding"); + if (stdout_encoding == NULL) { + Py_DECREF(stdin_encoding); + return NULL; + } + stringpo = PyObject_Str(promptarg); + if (stringpo == NULL) { + Py_DECREF(stdin_encoding); + Py_DECREF(stdout_encoding); + return NULL; + } + po = PyUnicode_AsEncodedString(stringpo, + _PyUnicode_AsString(stdout_encoding), NULL); + Py_DECREF(stdout_encoding); + Py_DECREF(stringpo); + if (po == NULL) { + Py_DECREF(stdin_encoding); + return NULL; + } + prompt = PyBytes_AsString(po); + if (prompt == NULL) { + Py_DECREF(stdin_encoding); + Py_DECREF(po); + return NULL; + } + } + else { + po = NULL; + prompt = ""; + } + s = PyOS_Readline(stdin, stdout, prompt); + Py_XDECREF(po); + if (s == NULL) { + if (!PyErr_Occurred()) + PyErr_SetNone(PyExc_KeyboardInterrupt); + Py_DECREF(stdin_encoding); + return NULL; + } + if (*s == '\0') { + PyErr_SetNone(PyExc_EOFError); + result = NULL; + } + else { /* strip trailing '\n' */ + size_t len = strlen(s); + if (len > PY_SSIZE_T_MAX) { + PyErr_SetString(PyExc_OverflowError, + "input: input too long"); + result = NULL; + } + else { + result = PyUnicode_Decode + (s, len-1, + _PyUnicode_AsString(stdin_encoding), + NULL); + } + } + Py_DECREF(stdin_encoding); + PyMem_FREE(s); + return result; + } + + /* Fallback if we're not interactive */ + if (promptarg != NULL) { + if (PyFile_WriteObject(promptarg, fout, Py_PRINT_RAW) != 0) + return NULL; + } + tmp = PyObject_CallMethod(fout, "flush", ""); + if (tmp == NULL) + PyErr_Clear(); + else + Py_DECREF(tmp); + return PyFile_GetLine(fin, -1); } PyDoc_STRVAR(input_doc, @@ -1705,7 +1705,7 @@ static PyObject * builtin_repr(PyObject *self, PyObject *v) { - return PyObject_Repr(v); + return PyObject_Repr(v); } PyDoc_STRVAR(repr_doc, @@ -1718,38 +1718,38 @@ static PyObject * builtin_round(PyObject *self, PyObject *args, PyObject *kwds) { - static PyObject *round_str = NULL; - PyObject *ndigits = NULL; - static char *kwlist[] = {"number", "ndigits", 0}; - PyObject *number, *round; - - if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|O:round", - kwlist, &number, &ndigits)) - return NULL; - - if (Py_TYPE(number)->tp_dict == NULL) { - if (PyType_Ready(Py_TYPE(number)) < 0) - return NULL; - } - - if (round_str == NULL) { - round_str = PyUnicode_InternFromString("__round__"); - if (round_str == NULL) - return NULL; - } - - round = _PyType_Lookup(Py_TYPE(number), round_str); - if (round == NULL) { - PyErr_Format(PyExc_TypeError, - "type %.100s doesn't define __round__ method", - Py_TYPE(number)->tp_name); - return NULL; - } - - if (ndigits == NULL) - return PyObject_CallFunction(round, "O", number); - else - return PyObject_CallFunction(round, "OO", number, ndigits); + static PyObject *round_str = NULL; + PyObject *ndigits = NULL; + static char *kwlist[] = {"number", "ndigits", 0}; + PyObject *number, *round; + + if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|O:round", + kwlist, &number, &ndigits)) + return NULL; + + if (Py_TYPE(number)->tp_dict == NULL) { + if (PyType_Ready(Py_TYPE(number)) < 0) + return NULL; + } + + if (round_str == NULL) { + round_str = PyUnicode_InternFromString("__round__"); + if (round_str == NULL) + return NULL; + } + + round = _PyType_Lookup(Py_TYPE(number), round_str); + if (round == NULL) { + PyErr_Format(PyExc_TypeError, + "type %.100s doesn't define __round__ method", + Py_TYPE(number)->tp_name); + return NULL; + } + + if (ndigits == NULL) + return PyObject_CallFunction(round, "O", number); + else + return PyObject_CallFunction(round, "OO", number, ndigits); } PyDoc_STRVAR(round_doc, @@ -1763,42 +1763,42 @@ static PyObject * builtin_sorted(PyObject *self, PyObject *args, PyObject *kwds) { - PyObject *newlist, *v, *seq, *keyfunc=NULL, *newargs; - PyObject *callable; - static char *kwlist[] = {"iterable", "key", "reverse", 0}; - int reverse; - - /* args 1-3 should match listsort in Objects/listobject.c */ - if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|Oi:sorted", - kwlist, &seq, &keyfunc, &reverse)) - return NULL; - - newlist = PySequence_List(seq); - if (newlist == NULL) - return NULL; - - callable = PyObject_GetAttrString(newlist, "sort"); - if (callable == NULL) { - Py_DECREF(newlist); - return NULL; - } - - newargs = PyTuple_GetSlice(args, 1, 4); - if (newargs == NULL) { - Py_DECREF(newlist); - Py_DECREF(callable); - return NULL; - } - - v = PyObject_Call(callable, newargs, kwds); - Py_DECREF(newargs); - Py_DECREF(callable); - if (v == NULL) { - Py_DECREF(newlist); - return NULL; - } - Py_DECREF(v); - return newlist; + PyObject *newlist, *v, *seq, *keyfunc=NULL, *newargs; + PyObject *callable; + static char *kwlist[] = {"iterable", "key", "reverse", 0}; + int reverse; + + /* args 1-3 should match listsort in Objects/listobject.c */ + if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|Oi:sorted", + kwlist, &seq, &keyfunc, &reverse)) + return NULL; + + newlist = PySequence_List(seq); + if (newlist == NULL) + return NULL; + + callable = PyObject_GetAttrString(newlist, "sort"); + if (callable == NULL) { + Py_DECREF(newlist); + return NULL; + } + + newargs = PyTuple_GetSlice(args, 1, 4); + if (newargs == NULL) { + Py_DECREF(newlist); + Py_DECREF(callable); + return NULL; + } + + v = PyObject_Call(callable, newargs, kwds); + Py_DECREF(newargs); + Py_DECREF(callable); + if (v == NULL) { + Py_DECREF(newlist); + return NULL; + } + Py_DECREF(v); + return newlist; } PyDoc_STRVAR(sorted_doc, @@ -1807,30 +1807,30 @@ static PyObject * builtin_vars(PyObject *self, PyObject *args) { - PyObject *v = NULL; - PyObject *d; + PyObject *v = NULL; + PyObject *d; - if (!PyArg_UnpackTuple(args, "vars", 0, 1, &v)) - return NULL; - if (v == NULL) { - d = PyEval_GetLocals(); - if (d == NULL) { - if (!PyErr_Occurred()) - PyErr_SetString(PyExc_SystemError, - "vars(): no locals!?"); - } - else - Py_INCREF(d); - } - else { - d = PyObject_GetAttrString(v, "__dict__"); - if (d == NULL) { - PyErr_SetString(PyExc_TypeError, - "vars() argument must have __dict__ attribute"); - return NULL; - } - } - return d; + if (!PyArg_UnpackTuple(args, "vars", 0, 1, &v)) + return NULL; + if (v == NULL) { + d = PyEval_GetLocals(); + if (d == NULL) { + if (!PyErr_Occurred()) + PyErr_SetString(PyExc_SystemError, + "vars(): no locals!?"); + } + else + Py_INCREF(d); + } + else { + d = PyObject_GetAttrString(v, "__dict__"); + if (d == NULL) { + PyErr_SetString(PyExc_TypeError, + "vars() argument must have __dict__ attribute"); + return NULL; + } + } + return d; } PyDoc_STRVAR(vars_doc, @@ -1842,156 +1842,156 @@ static PyObject* builtin_sum(PyObject *self, PyObject *args) { - PyObject *seq; - PyObject *result = NULL; - PyObject *temp, *item, *iter; - - if (!PyArg_UnpackTuple(args, "sum", 1, 2, &seq, &result)) - return NULL; - - iter = PyObject_GetIter(seq); - if (iter == NULL) - return NULL; - - if (result == NULL) { - result = PyLong_FromLong(0); - if (result == NULL) { - Py_DECREF(iter); - return NULL; - } - } else { - /* reject string values for 'start' parameter */ - if (PyUnicode_Check(result)) { - PyErr_SetString(PyExc_TypeError, - "sum() can't sum strings [use ''.join(seq) instead]"); - Py_DECREF(iter); - return NULL; - } - if (PyByteArray_Check(result)) { - PyErr_SetString(PyExc_TypeError, - "sum() can't sum bytes [use b''.join(seq) instead]"); - Py_DECREF(iter); - return NULL; - } + PyObject *seq; + PyObject *result = NULL; + PyObject *temp, *item, *iter; - Py_INCREF(result); - } + if (!PyArg_UnpackTuple(args, "sum", 1, 2, &seq, &result)) + return NULL; + + iter = PyObject_GetIter(seq); + if (iter == NULL) + return NULL; + + if (result == NULL) { + result = PyLong_FromLong(0); + if (result == NULL) { + Py_DECREF(iter); + return NULL; + } + } else { + /* reject string values for 'start' parameter */ + if (PyUnicode_Check(result)) { + PyErr_SetString(PyExc_TypeError, + "sum() can't sum strings [use ''.join(seq) instead]"); + Py_DECREF(iter); + return NULL; + } + if (PyByteArray_Check(result)) { + PyErr_SetString(PyExc_TypeError, + "sum() can't sum bytes [use b''.join(seq) instead]"); + Py_DECREF(iter); + return NULL; + } + + Py_INCREF(result); + } #ifndef SLOW_SUM - /* Fast addition by keeping temporary sums in C instead of new Python objects. - Assumes all inputs are the same type. If the assumption fails, default - to the more general routine. - */ - if (PyLong_CheckExact(result)) { - int overflow; - long i_result = PyLong_AsLongAndOverflow(result, &overflow); - /* If this already overflowed, don't even enter the loop. */ - if (overflow == 0) { - Py_DECREF(result); - result = NULL; - } - while(result == NULL) { - item = PyIter_Next(iter); - if (item == NULL) { - Py_DECREF(iter); - if (PyErr_Occurred()) - return NULL; - return PyLong_FromLong(i_result); - } - if (PyLong_CheckExact(item)) { - long b = PyLong_AsLongAndOverflow(item, &overflow); - long x = i_result + b; - if (overflow == 0 && ((x^i_result) >= 0 || (x^b) >= 0)) { - i_result = x; - Py_DECREF(item); - continue; - } - } - /* Either overflowed or is not an int. Restore real objects and process normally */ - result = PyLong_FromLong(i_result); - temp = PyNumber_Add(result, item); - Py_DECREF(result); - Py_DECREF(item); - result = temp; - if (result == NULL) { - Py_DECREF(iter); - return NULL; - } - } - } - - if (PyFloat_CheckExact(result)) { - double f_result = PyFloat_AS_DOUBLE(result); - Py_DECREF(result); - result = NULL; - while(result == NULL) { - item = PyIter_Next(iter); - if (item == NULL) { - Py_DECREF(iter); - if (PyErr_Occurred()) - return NULL; - return PyFloat_FromDouble(f_result); - } - if (PyFloat_CheckExact(item)) { - PyFPE_START_PROTECT("add", Py_DECREF(item); Py_DECREF(iter); return 0) - f_result += PyFloat_AS_DOUBLE(item); - PyFPE_END_PROTECT(f_result) - Py_DECREF(item); - continue; - } - if (PyLong_CheckExact(item)) { - long value; - int overflow; - value = PyLong_AsLongAndOverflow(item, &overflow); - if (!overflow) { - PyFPE_START_PROTECT("add", Py_DECREF(item); Py_DECREF(iter); return 0) - f_result += (double)value; - PyFPE_END_PROTECT(f_result) - Py_DECREF(item); - continue; - } - } - result = PyFloat_FromDouble(f_result); - temp = PyNumber_Add(result, item); - Py_DECREF(result); - Py_DECREF(item); - result = temp; - if (result == NULL) { - Py_DECREF(iter); - return NULL; - } - } - } + /* Fast addition by keeping temporary sums in C instead of new Python objects. + Assumes all inputs are the same type. If the assumption fails, default + to the more general routine. + */ + if (PyLong_CheckExact(result)) { + int overflow; + long i_result = PyLong_AsLongAndOverflow(result, &overflow); + /* If this already overflowed, don't even enter the loop. */ + if (overflow == 0) { + Py_DECREF(result); + result = NULL; + } + while(result == NULL) { + item = PyIter_Next(iter); + if (item == NULL) { + Py_DECREF(iter); + if (PyErr_Occurred()) + return NULL; + return PyLong_FromLong(i_result); + } + if (PyLong_CheckExact(item)) { + long b = PyLong_AsLongAndOverflow(item, &overflow); + long x = i_result + b; + if (overflow == 0 && ((x^i_result) >= 0 || (x^b) >= 0)) { + i_result = x; + Py_DECREF(item); + continue; + } + } + /* Either overflowed or is not an int. Restore real objects and process normally */ + result = PyLong_FromLong(i_result); + temp = PyNumber_Add(result, item); + Py_DECREF(result); + Py_DECREF(item); + result = temp; + if (result == NULL) { + Py_DECREF(iter); + return NULL; + } + } + } + + if (PyFloat_CheckExact(result)) { + double f_result = PyFloat_AS_DOUBLE(result); + Py_DECREF(result); + result = NULL; + while(result == NULL) { + item = PyIter_Next(iter); + if (item == NULL) { + Py_DECREF(iter); + if (PyErr_Occurred()) + return NULL; + return PyFloat_FromDouble(f_result); + } + if (PyFloat_CheckExact(item)) { + PyFPE_START_PROTECT("add", Py_DECREF(item); Py_DECREF(iter); return 0) + f_result += PyFloat_AS_DOUBLE(item); + PyFPE_END_PROTECT(f_result) + Py_DECREF(item); + continue; + } + if (PyLong_CheckExact(item)) { + long value; + int overflow; + value = PyLong_AsLongAndOverflow(item, &overflow); + if (!overflow) { + PyFPE_START_PROTECT("add", Py_DECREF(item); Py_DECREF(iter); return 0) + f_result += (double)value; + PyFPE_END_PROTECT(f_result) + Py_DECREF(item); + continue; + } + } + result = PyFloat_FromDouble(f_result); + temp = PyNumber_Add(result, item); + Py_DECREF(result); + Py_DECREF(item); + result = temp; + if (result == NULL) { + Py_DECREF(iter); + return NULL; + } + } + } #endif - for(;;) { - item = PyIter_Next(iter); - if (item == NULL) { - /* error, or end-of-sequence */ - if (PyErr_Occurred()) { - Py_DECREF(result); - result = NULL; - } - break; - } - /* It's tempting to use PyNumber_InPlaceAdd instead of - PyNumber_Add here, to avoid quadratic running time - when doing 'sum(list_of_lists, [])'. However, this - would produce a change in behaviour: a snippet like - - empty = [] - sum([[x] for x in range(10)], empty) - - would change the value of empty. */ - temp = PyNumber_Add(result, item); - Py_DECREF(result); - Py_DECREF(item); - result = temp; - if (result == NULL) - break; - } - Py_DECREF(iter); - return result; + for(;;) { + item = PyIter_Next(iter); + if (item == NULL) { + /* error, or end-of-sequence */ + if (PyErr_Occurred()) { + Py_DECREF(result); + result = NULL; + } + break; + } + /* It's tempting to use PyNumber_InPlaceAdd instead of + PyNumber_Add here, to avoid quadratic running time + when doing 'sum(list_of_lists, [])'. However, this + would produce a change in behaviour: a snippet like + + empty = [] + sum([[x] for x in range(10)], empty) + + would change the value of empty. */ + temp = PyNumber_Add(result, item); + Py_DECREF(result); + Py_DECREF(item); + result = temp; + if (result == NULL) + break; + } + Py_DECREF(iter); + return result; } PyDoc_STRVAR(sum_doc, @@ -2005,17 +2005,17 @@ static PyObject * builtin_isinstance(PyObject *self, PyObject *args) { - PyObject *inst; - PyObject *cls; - int retval; - - if (!PyArg_UnpackTuple(args, "isinstance", 2, 2, &inst, &cls)) - return NULL; - - retval = PyObject_IsInstance(inst, cls); - if (retval < 0) - return NULL; - return PyBool_FromLong(retval); + PyObject *inst; + PyObject *cls; + int retval; + + if (!PyArg_UnpackTuple(args, "isinstance", 2, 2, &inst, &cls)) + return NULL; + + retval = PyObject_IsInstance(inst, cls); + if (retval < 0) + return NULL; + return PyBool_FromLong(retval); } PyDoc_STRVAR(isinstance_doc, @@ -2030,17 +2030,17 @@ static PyObject * builtin_issubclass(PyObject *self, PyObject *args) { - PyObject *derived; - PyObject *cls; - int retval; - - if (!PyArg_UnpackTuple(args, "issubclass", 2, 2, &derived, &cls)) - return NULL; - - retval = PyObject_IsSubclass(derived, cls); - if (retval < 0) - return NULL; - return PyBool_FromLong(retval); + PyObject *derived; + PyObject *cls; + int retval; + + if (!PyArg_UnpackTuple(args, "issubclass", 2, 2, &derived, &cls)) + return NULL; + + retval = PyObject_IsSubclass(derived, cls); + if (retval < 0) + return NULL; + return PyBool_FromLong(retval); } PyDoc_STRVAR(issubclass_doc, @@ -2052,127 +2052,127 @@ typedef struct { - PyObject_HEAD - Py_ssize_t tuplesize; - PyObject *ittuple; /* tuple of iterators */ - PyObject *result; + PyObject_HEAD + Py_ssize_t tuplesize; + PyObject *ittuple; /* tuple of iterators */ + PyObject *result; } zipobject; static PyObject * zip_new(PyTypeObject *type, PyObject *args, PyObject *kwds) { - zipobject *lz; - Py_ssize_t i; - PyObject *ittuple; /* tuple of iterators */ - PyObject *result; - Py_ssize_t tuplesize = PySequence_Length(args); - - if (type == &PyZip_Type && !_PyArg_NoKeywords("zip()", kwds)) - return NULL; - - /* args must be a tuple */ - assert(PyTuple_Check(args)); - - /* obtain iterators */ - ittuple = PyTuple_New(tuplesize); - if (ittuple == NULL) - return NULL; - for (i=0; i < tuplesize; ++i) { - PyObject *item = PyTuple_GET_ITEM(args, i); - PyObject *it = PyObject_GetIter(item); - if (it == NULL) { - if (PyErr_ExceptionMatches(PyExc_TypeError)) - PyErr_Format(PyExc_TypeError, - "zip argument #%zd must support iteration", - i+1); - Py_DECREF(ittuple); - return NULL; - } - PyTuple_SET_ITEM(ittuple, i, it); - } - - /* create a result holder */ - result = PyTuple_New(tuplesize); - if (result == NULL) { - Py_DECREF(ittuple); - return NULL; - } - for (i=0 ; i < tuplesize ; i++) { - Py_INCREF(Py_None); - PyTuple_SET_ITEM(result, i, Py_None); - } - - /* create zipobject structure */ - lz = (zipobject *)type->tp_alloc(type, 0); - if (lz == NULL) { - Py_DECREF(ittuple); - Py_DECREF(result); - return NULL; - } - lz->ittuple = ittuple; - lz->tuplesize = tuplesize; - lz->result = result; + zipobject *lz; + Py_ssize_t i; + PyObject *ittuple; /* tuple of iterators */ + PyObject *result; + Py_ssize_t tuplesize = PySequence_Length(args); + + if (type == &PyZip_Type && !_PyArg_NoKeywords("zip()", kwds)) + return NULL; + + /* args must be a tuple */ + assert(PyTuple_Check(args)); - return (PyObject *)lz; + /* obtain iterators */ + ittuple = PyTuple_New(tuplesize); + if (ittuple == NULL) + return NULL; + for (i=0; i < tuplesize; ++i) { + PyObject *item = PyTuple_GET_ITEM(args, i); + PyObject *it = PyObject_GetIter(item); + if (it == NULL) { + if (PyErr_ExceptionMatches(PyExc_TypeError)) + PyErr_Format(PyExc_TypeError, + "zip argument #%zd must support iteration", + i+1); + Py_DECREF(ittuple); + return NULL; + } + PyTuple_SET_ITEM(ittuple, i, it); + } + + /* create a result holder */ + result = PyTuple_New(tuplesize); + if (result == NULL) { + Py_DECREF(ittuple); + return NULL; + } + for (i=0 ; i < tuplesize ; i++) { + Py_INCREF(Py_None); + PyTuple_SET_ITEM(result, i, Py_None); + } + + /* create zipobject structure */ + lz = (zipobject *)type->tp_alloc(type, 0); + if (lz == NULL) { + Py_DECREF(ittuple); + Py_DECREF(result); + return NULL; + } + lz->ittuple = ittuple; + lz->tuplesize = tuplesize; + lz->result = result; + + return (PyObject *)lz; } static void zip_dealloc(zipobject *lz) { - PyObject_GC_UnTrack(lz); - Py_XDECREF(lz->ittuple); - Py_XDECREF(lz->result); - Py_TYPE(lz)->tp_free(lz); + PyObject_GC_UnTrack(lz); + Py_XDECREF(lz->ittuple); + Py_XDECREF(lz->result); + Py_TYPE(lz)->tp_free(lz); } static int zip_traverse(zipobject *lz, visitproc visit, void *arg) { - Py_VISIT(lz->ittuple); - Py_VISIT(lz->result); - return 0; + Py_VISIT(lz->ittuple); + Py_VISIT(lz->result); + return 0; } static PyObject * zip_next(zipobject *lz) { - Py_ssize_t i; - Py_ssize_t tuplesize = lz->tuplesize; - PyObject *result = lz->result; - PyObject *it; - PyObject *item; - PyObject *olditem; - - if (tuplesize == 0) - return NULL; - if (Py_REFCNT(result) == 1) { - Py_INCREF(result); - for (i=0 ; i < tuplesize ; i++) { - it = PyTuple_GET_ITEM(lz->ittuple, i); - item = (*Py_TYPE(it)->tp_iternext)(it); - if (item == NULL) { - Py_DECREF(result); - return NULL; - } - olditem = PyTuple_GET_ITEM(result, i); - PyTuple_SET_ITEM(result, i, item); - Py_DECREF(olditem); - } - } else { - result = PyTuple_New(tuplesize); - if (result == NULL) - return NULL; - for (i=0 ; i < tuplesize ; i++) { - it = PyTuple_GET_ITEM(lz->ittuple, i); - item = (*Py_TYPE(it)->tp_iternext)(it); - if (item == NULL) { - Py_DECREF(result); - return NULL; - } - PyTuple_SET_ITEM(result, i, item); - } - } - return result; + Py_ssize_t i; + Py_ssize_t tuplesize = lz->tuplesize; + PyObject *result = lz->result; + PyObject *it; + PyObject *item; + PyObject *olditem; + + if (tuplesize == 0) + return NULL; + if (Py_REFCNT(result) == 1) { + Py_INCREF(result); + for (i=0 ; i < tuplesize ; i++) { + it = PyTuple_GET_ITEM(lz->ittuple, i); + item = (*Py_TYPE(it)->tp_iternext)(it); + if (item == NULL) { + Py_DECREF(result); + return NULL; + } + olditem = PyTuple_GET_ITEM(result, i); + PyTuple_SET_ITEM(result, i, item); + Py_DECREF(olditem); + } + } else { + result = PyTuple_New(tuplesize); + if (result == NULL) + return NULL; + for (i=0 ; i < tuplesize ; i++) { + it = PyTuple_GET_ITEM(lz->ittuple, i); + item = (*Py_TYPE(it)->tp_iternext)(it); + if (item == NULL) { + Py_DECREF(result); + return NULL; + } + PyTuple_SET_ITEM(result, i, item); + } + } + return result; } PyDoc_STRVAR(zip_doc, @@ -2184,93 +2184,93 @@ is exhausted and then it raises StopIteration."); PyTypeObject PyZip_Type = { - PyVarObject_HEAD_INIT(&PyType_Type, 0) - "zip", /* tp_name */ - sizeof(zipobject), /* tp_basicsize */ - 0, /* tp_itemsize */ - /* methods */ - (destructor)zip_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 | - Py_TPFLAGS_BASETYPE, /* tp_flags */ - zip_doc, /* tp_doc */ - (traverseproc)zip_traverse, /* tp_traverse */ - 0, /* tp_clear */ - 0, /* tp_richcompare */ - 0, /* tp_weaklistoffset */ - PyObject_SelfIter, /* tp_iter */ - (iternextfunc)zip_next, /* tp_iternext */ - 0, /* tp_methods */ - 0, /* tp_members */ - 0, /* tp_getset */ - 0, /* tp_base */ - 0, /* tp_dict */ - 0, /* tp_descr_get */ - 0, /* tp_descr_set */ - 0, /* tp_dictoffset */ - 0, /* tp_init */ - PyType_GenericAlloc, /* tp_alloc */ - zip_new, /* tp_new */ - PyObject_GC_Del, /* tp_free */ + PyVarObject_HEAD_INIT(&PyType_Type, 0) + "zip", /* tp_name */ + sizeof(zipobject), /* tp_basicsize */ + 0, /* tp_itemsize */ + /* methods */ + (destructor)zip_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 | + Py_TPFLAGS_BASETYPE, /* tp_flags */ + zip_doc, /* tp_doc */ + (traverseproc)zip_traverse, /* tp_traverse */ + 0, /* tp_clear */ + 0, /* tp_richcompare */ + 0, /* tp_weaklistoffset */ + PyObject_SelfIter, /* tp_iter */ + (iternextfunc)zip_next, /* tp_iternext */ + 0, /* tp_methods */ + 0, /* tp_members */ + 0, /* tp_getset */ + 0, /* tp_base */ + 0, /* tp_dict */ + 0, /* tp_descr_get */ + 0, /* tp_descr_set */ + 0, /* tp_dictoffset */ + 0, /* tp_init */ + PyType_GenericAlloc, /* tp_alloc */ + zip_new, /* tp_new */ + PyObject_GC_Del, /* tp_free */ }; static PyMethodDef builtin_methods[] = { - {"__build_class__", (PyCFunction)builtin___build_class__, - METH_VARARGS | METH_KEYWORDS, build_class_doc}, - {"__import__", (PyCFunction)builtin___import__, METH_VARARGS | METH_KEYWORDS, import_doc}, - {"abs", builtin_abs, METH_O, abs_doc}, - {"all", builtin_all, METH_O, all_doc}, - {"any", builtin_any, METH_O, any_doc}, - {"ascii", builtin_ascii, METH_O, ascii_doc}, - {"bin", builtin_bin, METH_O, bin_doc}, - {"chr", builtin_chr, METH_VARARGS, chr_doc}, - {"compile", (PyCFunction)builtin_compile, METH_VARARGS | METH_KEYWORDS, compile_doc}, - {"delattr", builtin_delattr, METH_VARARGS, delattr_doc}, - {"dir", builtin_dir, METH_VARARGS, dir_doc}, - {"divmod", builtin_divmod, METH_VARARGS, divmod_doc}, - {"eval", builtin_eval, METH_VARARGS, eval_doc}, - {"exec", builtin_exec, METH_VARARGS, exec_doc}, - {"format", builtin_format, METH_VARARGS, format_doc}, - {"getattr", builtin_getattr, METH_VARARGS, getattr_doc}, - {"globals", (PyCFunction)builtin_globals, METH_NOARGS, globals_doc}, - {"hasattr", builtin_hasattr, METH_VARARGS, hasattr_doc}, - {"hash", builtin_hash, METH_O, hash_doc}, - {"hex", builtin_hex, METH_O, hex_doc}, - {"id", builtin_id, METH_O, id_doc}, - {"input", builtin_input, METH_VARARGS, input_doc}, - {"isinstance", builtin_isinstance, METH_VARARGS, isinstance_doc}, - {"issubclass", builtin_issubclass, METH_VARARGS, issubclass_doc}, - {"iter", builtin_iter, METH_VARARGS, iter_doc}, - {"len", builtin_len, METH_O, len_doc}, - {"locals", (PyCFunction)builtin_locals, METH_NOARGS, locals_doc}, - {"max", (PyCFunction)builtin_max, METH_VARARGS | METH_KEYWORDS, max_doc}, - {"min", (PyCFunction)builtin_min, METH_VARARGS | METH_KEYWORDS, min_doc}, - {"next", (PyCFunction)builtin_next, METH_VARARGS, next_doc}, - {"oct", builtin_oct, METH_O, oct_doc}, - {"ord", builtin_ord, METH_O, ord_doc}, - {"pow", builtin_pow, METH_VARARGS, pow_doc}, - {"print", (PyCFunction)builtin_print, METH_VARARGS | METH_KEYWORDS, print_doc}, - {"repr", builtin_repr, METH_O, repr_doc}, - {"round", (PyCFunction)builtin_round, METH_VARARGS | METH_KEYWORDS, round_doc}, - {"setattr", builtin_setattr, METH_VARARGS, setattr_doc}, - {"sorted", (PyCFunction)builtin_sorted, METH_VARARGS | METH_KEYWORDS, sorted_doc}, - {"sum", builtin_sum, METH_VARARGS, sum_doc}, - {"vars", builtin_vars, METH_VARARGS, vars_doc}, - {NULL, NULL}, + {"__build_class__", (PyCFunction)builtin___build_class__, + METH_VARARGS | METH_KEYWORDS, build_class_doc}, + {"__import__", (PyCFunction)builtin___import__, METH_VARARGS | METH_KEYWORDS, import_doc}, + {"abs", builtin_abs, METH_O, abs_doc}, + {"all", builtin_all, METH_O, all_doc}, + {"any", builtin_any, METH_O, any_doc}, + {"ascii", builtin_ascii, METH_O, ascii_doc}, + {"bin", builtin_bin, METH_O, bin_doc}, + {"chr", builtin_chr, METH_VARARGS, chr_doc}, + {"compile", (PyCFunction)builtin_compile, METH_VARARGS | METH_KEYWORDS, compile_doc}, + {"delattr", builtin_delattr, METH_VARARGS, delattr_doc}, + {"dir", builtin_dir, METH_VARARGS, dir_doc}, + {"divmod", builtin_divmod, METH_VARARGS, divmod_doc}, + {"eval", builtin_eval, METH_VARARGS, eval_doc}, + {"exec", builtin_exec, METH_VARARGS, exec_doc}, + {"format", builtin_format, METH_VARARGS, format_doc}, + {"getattr", builtin_getattr, METH_VARARGS, getattr_doc}, + {"globals", (PyCFunction)builtin_globals, METH_NOARGS, globals_doc}, + {"hasattr", builtin_hasattr, METH_VARARGS, hasattr_doc}, + {"hash", builtin_hash, METH_O, hash_doc}, + {"hex", builtin_hex, METH_O, hex_doc}, + {"id", builtin_id, METH_O, id_doc}, + {"input", builtin_input, METH_VARARGS, input_doc}, + {"isinstance", builtin_isinstance, METH_VARARGS, isinstance_doc}, + {"issubclass", builtin_issubclass, METH_VARARGS, issubclass_doc}, + {"iter", builtin_iter, METH_VARARGS, iter_doc}, + {"len", builtin_len, METH_O, len_doc}, + {"locals", (PyCFunction)builtin_locals, METH_NOARGS, locals_doc}, + {"max", (PyCFunction)builtin_max, METH_VARARGS | METH_KEYWORDS, max_doc}, + {"min", (PyCFunction)builtin_min, METH_VARARGS | METH_KEYWORDS, min_doc}, + {"next", (PyCFunction)builtin_next, METH_VARARGS, next_doc}, + {"oct", builtin_oct, METH_O, oct_doc}, + {"ord", builtin_ord, METH_O, ord_doc}, + {"pow", builtin_pow, METH_VARARGS, pow_doc}, + {"print", (PyCFunction)builtin_print, METH_VARARGS | METH_KEYWORDS, print_doc}, + {"repr", builtin_repr, METH_O, repr_doc}, + {"round", (PyCFunction)builtin_round, METH_VARARGS | METH_KEYWORDS, round_doc}, + {"setattr", builtin_setattr, METH_VARARGS, setattr_doc}, + {"sorted", (PyCFunction)builtin_sorted, METH_VARARGS | METH_KEYWORDS, sorted_doc}, + {"sum", builtin_sum, METH_VARARGS, sum_doc}, + {"vars", builtin_vars, METH_VARARGS, vars_doc}, + {NULL, NULL}, }; PyDoc_STRVAR(builtin_doc, @@ -2279,83 +2279,83 @@ Noteworthy: None is the `nil' object; Ellipsis represents `...' in slices."); static struct PyModuleDef builtinsmodule = { - PyModuleDef_HEAD_INIT, - "builtins", - builtin_doc, - -1, /* multiple "initialization" just copies the module dict. */ - builtin_methods, - NULL, - NULL, - NULL, - NULL + PyModuleDef_HEAD_INIT, + "builtins", + builtin_doc, + -1, /* multiple "initialization" just copies the module dict. */ + builtin_methods, + NULL, + NULL, + NULL, + NULL }; PyObject * _PyBuiltin_Init(void) { - PyObject *mod, *dict, *debug; - mod = PyModule_Create(&builtinsmodule); - if (mod == NULL) - return NULL; - dict = PyModule_GetDict(mod); + PyObject *mod, *dict, *debug; + mod = PyModule_Create(&builtinsmodule); + if (mod == NULL) + return NULL; + dict = PyModule_GetDict(mod); #ifdef Py_TRACE_REFS - /* "builtins" exposes a number of statically allocated objects - * that, before this code was added in 2.3, never showed up in - * the list of "all objects" maintained by Py_TRACE_REFS. As a - * result, programs leaking references to None and False (etc) - * couldn't be diagnosed by examining sys.getobjects(0). - */ + /* "builtins" exposes a number of statically allocated objects + * that, before this code was added in 2.3, never showed up in + * the list of "all objects" maintained by Py_TRACE_REFS. As a + * result, programs leaking references to None and False (etc) + * couldn't be diagnosed by examining sys.getobjects(0). + */ #define ADD_TO_ALL(OBJECT) _Py_AddToAllObjects((PyObject *)(OBJECT), 0) #else #define ADD_TO_ALL(OBJECT) (void)0 #endif #define SETBUILTIN(NAME, OBJECT) \ - if (PyDict_SetItemString(dict, NAME, (PyObject *)OBJECT) < 0) \ - return NULL; \ - ADD_TO_ALL(OBJECT) - - SETBUILTIN("None", Py_None); - SETBUILTIN("Ellipsis", Py_Ellipsis); - SETBUILTIN("NotImplemented", Py_NotImplemented); - SETBUILTIN("False", Py_False); - SETBUILTIN("True", Py_True); - SETBUILTIN("bool", &PyBool_Type); - SETBUILTIN("memoryview", &PyMemoryView_Type); - SETBUILTIN("bytearray", &PyByteArray_Type); - SETBUILTIN("bytes", &PyBytes_Type); - SETBUILTIN("classmethod", &PyClassMethod_Type); - SETBUILTIN("complex", &PyComplex_Type); - SETBUILTIN("dict", &PyDict_Type); - SETBUILTIN("enumerate", &PyEnum_Type); - SETBUILTIN("filter", &PyFilter_Type); - SETBUILTIN("float", &PyFloat_Type); - SETBUILTIN("frozenset", &PyFrozenSet_Type); - SETBUILTIN("property", &PyProperty_Type); - SETBUILTIN("int", &PyLong_Type); - SETBUILTIN("list", &PyList_Type); - SETBUILTIN("map", &PyMap_Type); - SETBUILTIN("object", &PyBaseObject_Type); - SETBUILTIN("range", &PyRange_Type); - SETBUILTIN("reversed", &PyReversed_Type); - SETBUILTIN("set", &PySet_Type); - SETBUILTIN("slice", &PySlice_Type); - SETBUILTIN("staticmethod", &PyStaticMethod_Type); - SETBUILTIN("str", &PyUnicode_Type); - SETBUILTIN("super", &PySuper_Type); - SETBUILTIN("tuple", &PyTuple_Type); - SETBUILTIN("type", &PyType_Type); - SETBUILTIN("zip", &PyZip_Type); - debug = PyBool_FromLong(Py_OptimizeFlag == 0); - if (PyDict_SetItemString(dict, "__debug__", debug) < 0) { - Py_XDECREF(debug); - return NULL; - } - Py_XDECREF(debug); + if (PyDict_SetItemString(dict, NAME, (PyObject *)OBJECT) < 0) \ + return NULL; \ + ADD_TO_ALL(OBJECT) + + SETBUILTIN("None", Py_None); + SETBUILTIN("Ellipsis", Py_Ellipsis); + SETBUILTIN("NotImplemented", Py_NotImplemented); + SETBUILTIN("False", Py_False); + SETBUILTIN("True", Py_True); + SETBUILTIN("bool", &PyBool_Type); + SETBUILTIN("memoryview", &PyMemoryView_Type); + SETBUILTIN("bytearray", &PyByteArray_Type); + SETBUILTIN("bytes", &PyBytes_Type); + SETBUILTIN("classmethod", &PyClassMethod_Type); + SETBUILTIN("complex", &PyComplex_Type); + SETBUILTIN("dict", &PyDict_Type); + SETBUILTIN("enumerate", &PyEnum_Type); + SETBUILTIN("filter", &PyFilter_Type); + SETBUILTIN("float", &PyFloat_Type); + SETBUILTIN("frozenset", &PyFrozenSet_Type); + SETBUILTIN("property", &PyProperty_Type); + SETBUILTIN("int", &PyLong_Type); + SETBUILTIN("list", &PyList_Type); + SETBUILTIN("map", &PyMap_Type); + SETBUILTIN("object", &PyBaseObject_Type); + SETBUILTIN("range", &PyRange_Type); + SETBUILTIN("reversed", &PyReversed_Type); + SETBUILTIN("set", &PySet_Type); + SETBUILTIN("slice", &PySlice_Type); + SETBUILTIN("staticmethod", &PyStaticMethod_Type); + SETBUILTIN("str", &PyUnicode_Type); + SETBUILTIN("super", &PySuper_Type); + SETBUILTIN("tuple", &PyTuple_Type); + SETBUILTIN("type", &PyType_Type); + SETBUILTIN("zip", &PyZip_Type); + debug = PyBool_FromLong(Py_OptimizeFlag == 0); + if (PyDict_SetItemString(dict, "__debug__", debug) < 0) { + Py_XDECREF(debug); + return NULL; + } + Py_XDECREF(debug); - return mod; + return mod; #undef ADD_TO_ALL #undef SETBUILTIN } Modified: python/branches/py3k/Python/ceval.c ============================================================================== --- python/branches/py3k/Python/ceval.c (original) +++ python/branches/py3k/Python/ceval.c Sun May 9 17:52:27 2010 @@ -28,27 +28,27 @@ typedef unsigned long long uint64; #if defined(__ppc__) /* <- Don't know if this is the correct symbol; this - section should work for GCC on any PowerPC - platform, irrespective of OS. - POWER? Who knows :-) */ + section should work for GCC on any PowerPC + platform, irrespective of OS. + POWER? Who knows :-) */ #define READ_TIMESTAMP(var) ppc_getcounter(&var) static void ppc_getcounter(uint64 *v) { - register unsigned long tbu, tb, tbu2; + register unsigned long tbu, tb, tbu2; loop: - asm volatile ("mftbu %0" : "=r" (tbu) ); - asm volatile ("mftb %0" : "=r" (tb) ); - asm volatile ("mftbu %0" : "=r" (tbu2)); - if (__builtin_expect(tbu != tbu2, 0)) goto loop; - - /* The slightly peculiar way of writing the next lines is - compiled better by GCC than any other way I tried. */ - ((long*)(v))[0] = tbu; - ((long*)(v))[1] = tb; + asm volatile ("mftbu %0" : "=r" (tbu) ); + asm volatile ("mftb %0" : "=r" (tb) ); + asm volatile ("mftbu %0" : "=r" (tbu2)); + if (__builtin_expect(tbu != tbu2, 0)) goto loop; + + /* The slightly peculiar way of writing the next lines is + compiled better by GCC than any other way I tried. */ + ((long*)(v))[0] = tbu; + ((long*)(v))[1] = tb; } #elif defined(__i386__) @@ -77,17 +77,17 @@ #endif void dump_tsc(int opcode, int ticked, uint64 inst0, uint64 inst1, - uint64 loop0, uint64 loop1, uint64 intr0, uint64 intr1) + uint64 loop0, uint64 loop1, uint64 intr0, uint64 intr1) { - uint64 intr, inst, loop; - PyThreadState *tstate = PyThreadState_Get(); - if (!tstate->interp->tscdump) - return; - intr = intr1 - intr0; - inst = inst1 - inst0 - intr; - loop = loop1 - loop0 - intr; - fprintf(stderr, "opcode=%03d t=%d inst=%06lld loop=%06lld\n", - opcode, ticked, inst, loop); + uint64 intr, inst, loop; + PyThreadState *tstate = PyThreadState_Get(); + if (!tstate->interp->tscdump) + return; + intr = intr1 - intr0; + inst = inst1 - inst0 - intr; + loop = loop1 - loop0 - intr; + fprintf(stderr, "opcode=%03d t=%d inst=%06lld loop=%06lld\n", + opcode, ticked, inst, loop); } #endif @@ -97,8 +97,8 @@ #ifdef Py_DEBUG /* For debugging the interpreter: */ -#define LLTRACE 1 /* Low-level trace feature */ -#define CHECKEXC 1 /* Double-check exception checking */ +#define LLTRACE 1 /* Low-level trace feature */ +#define CHECKEXC 1 /* Double-check exception checking */ #endif typedef PyObject *(*callproc)(PyObject *, PyObject *, PyObject *); @@ -113,7 +113,7 @@ static PyObject * do_call(PyObject *, PyObject ***, int, int); static PyObject * ext_do_call(PyObject *, PyObject ***, int, int, int); static PyObject * update_keyword_args(PyObject *, int, PyObject ***, - PyObject *); + PyObject *); static PyObject * update_star_args(int, int, PyObject *, PyObject ***); static PyObject * load_args(PyObject ***, int); #define CALL_FLAG_VAR 1 @@ -124,12 +124,12 @@ static int prtrace(PyObject *, char *); #endif static int call_trace(Py_tracefunc, PyObject *, PyFrameObject *, - int, PyObject *); + int, PyObject *); static int call_trace_protected(Py_tracefunc, PyObject *, - PyFrameObject *, int, PyObject *); + PyFrameObject *, int, PyObject *); static void call_exc_trace(Py_tracefunc, PyObject *, PyFrameObject *); static int maybe_call_line_trace(Py_tracefunc, PyObject *, - PyFrameObject *, int *, int *, int *); + PyFrameObject *, int *, int *, int *); static PyObject * cmp_outcome(int, PyObject *, PyObject *); static PyObject * import_from(PyObject *, PyObject *); @@ -140,14 +140,14 @@ static PyObject * special_lookup(PyObject *, char *, PyObject **); #define NAME_ERROR_MSG \ - "name '%.200s' is not defined" + "name '%.200s' is not defined" #define GLOBAL_NAME_ERROR_MSG \ - "global name '%.200s' is not defined" + "global name '%.200s' is not defined" #define UNBOUNDLOCAL_ERROR_MSG \ - "local variable '%.200s' referenced before assignment" + "local variable '%.200s' referenced before assignment" #define UNBOUNDFREE_ERROR_MSG \ - "free variable '%.200s' referenced before assignment" \ - " in enclosing scope" + "free variable '%.200s' referenced before assignment" \ + " in enclosing scope" /* Dynamic execution profile */ #ifdef DYNAMIC_EXECUTION_PROFILE @@ -199,10 +199,10 @@ PyObject * PyEval_GetCallStats(PyObject *self) { - return Py_BuildValue("iiiiiiiiiii", - pcall[0], pcall[1], pcall[2], pcall[3], - pcall[4], pcall[5], pcall[6], pcall[7], - pcall[8], pcall[9], pcall[10]); + return Py_BuildValue("iiiiiiiiiii", + pcall[0], pcall[1], pcall[2], pcall[3], + pcall[4], pcall[5], pcall[6], pcall[7], + pcall[8], pcall[9], pcall[10]); } #else #define PCALL(O) @@ -210,8 +210,8 @@ PyObject * PyEval_GetCallStats(PyObject *self) { - Py_INCREF(Py_None); - return Py_None; + Py_INCREF(Py_None); + return Py_None; } #endif @@ -220,45 +220,45 @@ 1. We believe this is all right because the eval loop will release the GIL eventually anyway. */ #define COMPUTE_EVAL_BREAKER() \ - _Py_atomic_store_relaxed( \ - &eval_breaker, \ - _Py_atomic_load_relaxed(&gil_drop_request) | \ - _Py_atomic_load_relaxed(&pendingcalls_to_do) | \ - pending_async_exc) + _Py_atomic_store_relaxed( \ + &eval_breaker, \ + _Py_atomic_load_relaxed(&gil_drop_request) | \ + _Py_atomic_load_relaxed(&pendingcalls_to_do) | \ + pending_async_exc) #define SET_GIL_DROP_REQUEST() \ - do { \ - _Py_atomic_store_relaxed(&gil_drop_request, 1); \ - _Py_atomic_store_relaxed(&eval_breaker, 1); \ - } while (0) + do { \ + _Py_atomic_store_relaxed(&gil_drop_request, 1); \ + _Py_atomic_store_relaxed(&eval_breaker, 1); \ + } while (0) #define RESET_GIL_DROP_REQUEST() \ - do { \ - _Py_atomic_store_relaxed(&gil_drop_request, 0); \ - COMPUTE_EVAL_BREAKER(); \ - } while (0) + do { \ + _Py_atomic_store_relaxed(&gil_drop_request, 0); \ + COMPUTE_EVAL_BREAKER(); \ + } while (0) /* Pending calls are only modified under pending_lock */ #define SIGNAL_PENDING_CALLS() \ - do { \ - _Py_atomic_store_relaxed(&pendingcalls_to_do, 1); \ - _Py_atomic_store_relaxed(&eval_breaker, 1); \ - } while (0) + do { \ + _Py_atomic_store_relaxed(&pendingcalls_to_do, 1); \ + _Py_atomic_store_relaxed(&eval_breaker, 1); \ + } while (0) #define UNSIGNAL_PENDING_CALLS() \ - do { \ - _Py_atomic_store_relaxed(&pendingcalls_to_do, 0); \ - COMPUTE_EVAL_BREAKER(); \ - } while (0) + do { \ + _Py_atomic_store_relaxed(&pendingcalls_to_do, 0); \ + COMPUTE_EVAL_BREAKER(); \ + } while (0) #define SIGNAL_ASYNC_EXC() \ - do { \ - pending_async_exc = 1; \ - _Py_atomic_store_relaxed(&eval_breaker, 1); \ - } while (0) + do { \ + pending_async_exc = 1; \ + _Py_atomic_store_relaxed(&eval_breaker, 1); \ + } while (0) #define UNSIGNAL_ASYNC_EXC() \ - do { pending_async_exc = 0; COMPUTE_EVAL_BREAKER(); } while (0) + do { pending_async_exc = 0; COMPUTE_EVAL_BREAKER(); } while (0) #ifdef WITH_THREAD @@ -286,62 +286,62 @@ int PyEval_ThreadsInitialized(void) { - return gil_created(); + return gil_created(); } void PyEval_InitThreads(void) { - if (gil_created()) - return; - create_gil(); - take_gil(PyThreadState_GET()); - main_thread = PyThread_get_thread_ident(); - if (!pending_lock) - pending_lock = PyThread_allocate_lock(); + if (gil_created()) + return; + create_gil(); + take_gil(PyThreadState_GET()); + main_thread = PyThread_get_thread_ident(); + if (!pending_lock) + pending_lock = PyThread_allocate_lock(); } void PyEval_AcquireLock(void) { - PyThreadState *tstate = PyThreadState_GET(); - if (tstate == NULL) - Py_FatalError("PyEval_AcquireLock: current thread state is NULL"); - take_gil(tstate); + PyThreadState *tstate = PyThreadState_GET(); + if (tstate == NULL) + Py_FatalError("PyEval_AcquireLock: current thread state is NULL"); + take_gil(tstate); } void PyEval_ReleaseLock(void) { - /* This function must succeed when the current thread state is NULL. - We therefore avoid PyThreadState_GET() which dumps a fatal error - in debug mode. - */ - drop_gil((PyThreadState*)_Py_atomic_load_relaxed( - &_PyThreadState_Current)); + /* This function must succeed when the current thread state is NULL. + We therefore avoid PyThreadState_GET() which dumps a fatal error + in debug mode. + */ + drop_gil((PyThreadState*)_Py_atomic_load_relaxed( + &_PyThreadState_Current)); } void PyEval_AcquireThread(PyThreadState *tstate) { - if (tstate == NULL) - Py_FatalError("PyEval_AcquireThread: NULL new thread state"); - /* Check someone has called PyEval_InitThreads() to create the lock */ - assert(gil_created()); - take_gil(tstate); - if (PyThreadState_Swap(tstate) != NULL) - Py_FatalError( - "PyEval_AcquireThread: non-NULL old thread state"); + if (tstate == NULL) + Py_FatalError("PyEval_AcquireThread: NULL new thread state"); + /* Check someone has called PyEval_InitThreads() to create the lock */ + assert(gil_created()); + take_gil(tstate); + if (PyThreadState_Swap(tstate) != NULL) + Py_FatalError( + "PyEval_AcquireThread: non-NULL old thread state"); } void PyEval_ReleaseThread(PyThreadState *tstate) { - if (tstate == NULL) - Py_FatalError("PyEval_ReleaseThread: NULL thread state"); - if (PyThreadState_Swap(NULL) != tstate) - Py_FatalError("PyEval_ReleaseThread: wrong thread state"); - drop_gil(tstate); + if (tstate == NULL) + Py_FatalError("PyEval_ReleaseThread: NULL thread state"); + if (PyThreadState_Swap(NULL) != tstate) + Py_FatalError("PyEval_ReleaseThread: wrong thread state"); + drop_gil(tstate); } /* This function is called from PyOS_AfterFork to ensure that newly @@ -352,36 +352,36 @@ void PyEval_ReInitThreads(void) { - PyObject *threading, *result; - PyThreadState *tstate = PyThreadState_GET(); + PyObject *threading, *result; + PyThreadState *tstate = PyThreadState_GET(); - if (!gil_created()) - return; - /*XXX Can't use PyThread_free_lock here because it does too - much error-checking. Doing this cleanly would require - adding a new function to each thread_*.h. Instead, just - create a new lock and waste a little bit of memory */ - recreate_gil(); - pending_lock = PyThread_allocate_lock(); - take_gil(tstate); - main_thread = PyThread_get_thread_ident(); - - /* Update the threading module with the new state. - */ - tstate = PyThreadState_GET(); - threading = PyMapping_GetItemString(tstate->interp->modules, - "threading"); - if (threading == NULL) { - /* threading not imported */ - PyErr_Clear(); - return; - } - result = PyObject_CallMethod(threading, "_after_fork", NULL); - if (result == NULL) - PyErr_WriteUnraisable(threading); - else - Py_DECREF(result); - Py_DECREF(threading); + if (!gil_created()) + return; + /*XXX Can't use PyThread_free_lock here because it does too + much error-checking. Doing this cleanly would require + adding a new function to each thread_*.h. Instead, just + create a new lock and waste a little bit of memory */ + recreate_gil(); + pending_lock = PyThread_allocate_lock(); + take_gil(tstate); + main_thread = PyThread_get_thread_ident(); + + /* Update the threading module with the new state. + */ + tstate = PyThreadState_GET(); + threading = PyMapping_GetItemString(tstate->interp->modules, + "threading"); + if (threading == NULL) { + /* threading not imported */ + PyErr_Clear(); + return; + } + result = PyObject_CallMethod(threading, "_after_fork", NULL); + if (result == NULL) + PyErr_WriteUnraisable(threading); + else + Py_DECREF(result); + Py_DECREF(threading); } #else @@ -396,7 +396,7 @@ void _PyEval_SignalAsyncExc(void) { - SIGNAL_ASYNC_EXC(); + SIGNAL_ASYNC_EXC(); } /* Functions save_thread and restore_thread are always defined so @@ -406,29 +406,29 @@ PyThreadState * PyEval_SaveThread(void) { - PyThreadState *tstate = PyThreadState_Swap(NULL); - if (tstate == NULL) - Py_FatalError("PyEval_SaveThread: NULL tstate"); + PyThreadState *tstate = PyThreadState_Swap(NULL); + if (tstate == NULL) + Py_FatalError("PyEval_SaveThread: NULL tstate"); #ifdef WITH_THREAD - if (gil_created()) - drop_gil(tstate); + if (gil_created()) + drop_gil(tstate); #endif - return tstate; + return tstate; } void PyEval_RestoreThread(PyThreadState *tstate) { - if (tstate == NULL) - Py_FatalError("PyEval_RestoreThread: NULL tstate"); + if (tstate == NULL) + Py_FatalError("PyEval_RestoreThread: NULL tstate"); #ifdef WITH_THREAD - if (gil_created()) { - int err = errno; - take_gil(tstate); - errno = err; - } + if (gil_created()) { + int err = errno; + take_gil(tstate); + errno = err; + } #endif - PyThreadState_Swap(tstate); + PyThreadState_Swap(tstate); } @@ -465,8 +465,8 @@ #define NPENDINGCALLS 32 static struct { - int (*func)(void *); - void *arg; + int (*func)(void *); + void *arg; } pendingcalls[NPENDINGCALLS]; static int pendingfirst = 0; static int pendinglast = 0; @@ -475,95 +475,95 @@ int Py_AddPendingCall(int (*func)(void *), void *arg) { - int i, j, result=0; - PyThread_type_lock lock = pending_lock; - - /* try a few times for the lock. Since this mechanism is used - * for signal handling (on the main thread), there is a (slim) - * chance that a signal is delivered on the same thread while we - * hold the lock during the Py_MakePendingCalls() function. - * This avoids a deadlock in that case. - * Note that signals can be delivered on any thread. In particular, - * on Windows, a SIGINT is delivered on a system-created worker - * thread. - * We also check for lock being NULL, in the unlikely case that - * this function is called before any bytecode evaluation takes place. - */ - if (lock != NULL) { - for (i = 0; i<100; i++) { - if (PyThread_acquire_lock(lock, NOWAIT_LOCK)) - break; - } - if (i == 100) - return -1; - } - - i = pendinglast; - j = (i + 1) % NPENDINGCALLS; - if (j == pendingfirst) { - result = -1; /* Queue full */ - } else { - pendingcalls[i].func = func; - pendingcalls[i].arg = arg; - pendinglast = j; - } - /* signal main loop */ - SIGNAL_PENDING_CALLS(); - if (lock != NULL) - PyThread_release_lock(lock); - return result; + int i, j, result=0; + PyThread_type_lock lock = pending_lock; + + /* try a few times for the lock. Since this mechanism is used + * for signal handling (on the main thread), there is a (slim) + * chance that a signal is delivered on the same thread while we + * hold the lock during the Py_MakePendingCalls() function. + * This avoids a deadlock in that case. + * Note that signals can be delivered on any thread. In particular, + * on Windows, a SIGINT is delivered on a system-created worker + * thread. + * We also check for lock being NULL, in the unlikely case that + * this function is called before any bytecode evaluation takes place. + */ + if (lock != NULL) { + for (i = 0; i<100; i++) { + if (PyThread_acquire_lock(lock, NOWAIT_LOCK)) + break; + } + if (i == 100) + return -1; + } + + i = pendinglast; + j = (i + 1) % NPENDINGCALLS; + if (j == pendingfirst) { + result = -1; /* Queue full */ + } else { + pendingcalls[i].func = func; + pendingcalls[i].arg = arg; + pendinglast = j; + } + /* signal main loop */ + SIGNAL_PENDING_CALLS(); + if (lock != NULL) + PyThread_release_lock(lock); + return result; } int Py_MakePendingCalls(void) { - int i; - int r = 0; + int i; + int r = 0; - if (!pending_lock) { - /* initial allocation of the lock */ - pending_lock = PyThread_allocate_lock(); - if (pending_lock == NULL) - return -1; - } - - /* only service pending calls on main thread */ - if (main_thread && PyThread_get_thread_ident() != main_thread) - return 0; - /* don't perform recursive pending calls */ - if (pendingbusy) - return 0; - pendingbusy = 1; - /* perform a bounded number of calls, in case of recursion */ - for (i=0; irecursion_depth; - PyErr_SetString(PyExc_MemoryError, "Stack overflow"); - return -1; - } -#endif - _Py_CheckRecursionLimit = recursion_limit; - if (tstate->recursion_critical) - /* Somebody asked that we don't check for recursion. */ - return 0; - if (tstate->overflowed) { - if (tstate->recursion_depth > recursion_limit + 50) { - /* Overflowing while handling an overflow. Give up. */ - Py_FatalError("Cannot recover from stack overflow."); - } - return 0; - } - if (tstate->recursion_depth > recursion_limit) { - --tstate->recursion_depth; - tstate->overflowed = 1; - PyErr_Format(PyExc_RuntimeError, - "maximum recursion depth exceeded%s", - where); - return -1; - } - return 0; + if (PyOS_CheckStack()) { + --tstate->recursion_depth; + PyErr_SetString(PyExc_MemoryError, "Stack overflow"); + return -1; + } +#endif + _Py_CheckRecursionLimit = recursion_limit; + if (tstate->recursion_critical) + /* Somebody asked that we don't check for recursion. */ + return 0; + if (tstate->overflowed) { + if (tstate->recursion_depth > recursion_limit + 50) { + /* Overflowing while handling an overflow. Give up. */ + Py_FatalError("Cannot recover from stack overflow."); + } + return 0; + } + if (tstate->recursion_depth > recursion_limit) { + --tstate->recursion_depth; + tstate->overflowed = 1; + PyErr_Format(PyExc_RuntimeError, + "maximum recursion depth exceeded%s", + where); + return -1; + } + return 0; } /* Status code for main loop (reason for stack unwind) */ enum why_code { - WHY_NOT = 0x0001, /* No error */ - WHY_EXCEPTION = 0x0002, /* Exception occurred */ - WHY_RERAISE = 0x0004, /* Exception re-raised by 'finally' */ - WHY_RETURN = 0x0008, /* 'return' statement */ - WHY_BREAK = 0x0010, /* 'break' statement */ - WHY_CONTINUE = 0x0020, /* 'continue' statement */ - WHY_YIELD = 0x0040, /* 'yield' operator */ - WHY_SILENCED = 0x0080 /* Exception silenced by 'with' */ + WHY_NOT = 0x0001, /* No error */ + WHY_EXCEPTION = 0x0002, /* Exception occurred */ + WHY_RERAISE = 0x0004, /* Exception re-raised by 'finally' */ + WHY_RETURN = 0x0008, /* 'return' statement */ + WHY_BREAK = 0x0010, /* 'break' statement */ + WHY_CONTINUE = 0x0020, /* 'continue' statement */ + WHY_YIELD = 0x0040, /* 'yield' operator */ + WHY_SILENCED = 0x0080 /* Exception silenced by 'with' */ }; static enum why_code do_raise(PyObject *, PyObject *); @@ -743,12 +743,12 @@ PyObject * PyEval_EvalCode(PyCodeObject *co, PyObject *globals, PyObject *locals) { - return PyEval_EvalCodeEx(co, - globals, locals, - (PyObject **)NULL, 0, - (PyObject **)NULL, 0, - (PyObject **)NULL, 0, - NULL, NULL); + return PyEval_EvalCodeEx(co, + globals, locals, + (PyObject **)NULL, 0, + (PyObject **)NULL, 0, + (PyObject **)NULL, 0, + NULL, NULL); } @@ -756,49 +756,49 @@ PyObject * PyEval_EvalFrame(PyFrameObject *f) { - /* This is for backward compatibility with extension modules that - used this API; core interpreter code should call - PyEval_EvalFrameEx() */ - return PyEval_EvalFrameEx(f, 0); + /* This is for backward compatibility with extension modules that + used this API; core interpreter code should call + PyEval_EvalFrameEx() */ + return PyEval_EvalFrameEx(f, 0); } PyObject * PyEval_EvalFrameEx(PyFrameObject *f, int throwflag) { #ifdef DXPAIRS - int lastopcode = 0; + int lastopcode = 0; #endif - register PyObject **stack_pointer; /* Next free slot in value stack */ - register unsigned char *next_instr; - register int opcode; /* Current opcode */ - register int oparg; /* Current opcode argument, if any */ - register enum why_code why; /* Reason for block stack unwind */ - register int err; /* Error status -- nonzero if error */ - register PyObject *x; /* Result object -- NULL if error */ - register PyObject *v; /* Temporary objects popped off stack */ - register PyObject *w; - register PyObject *u; - register PyObject *t; - register PyObject **fastlocals, **freevars; - PyObject *retval = NULL; /* Return value */ - PyThreadState *tstate = PyThreadState_GET(); - PyCodeObject *co; - - /* when tracing we set things up so that - - not (instr_lb <= current_bytecode_offset < instr_ub) - - is true when the line being executed has changed. The - initial values are such as to make this false the first - time it is tested. */ - int instr_ub = -1, instr_lb = 0, instr_prev = -1; - - unsigned char *first_instr; - PyObject *names; - PyObject *consts; + register PyObject **stack_pointer; /* Next free slot in value stack */ + register unsigned char *next_instr; + register int opcode; /* Current opcode */ + register int oparg; /* Current opcode argument, if any */ + register enum why_code why; /* Reason for block stack unwind */ + register int err; /* Error status -- nonzero if error */ + register PyObject *x; /* Result object -- NULL if error */ + register PyObject *v; /* Temporary objects popped off stack */ + register PyObject *w; + register PyObject *u; + register PyObject *t; + register PyObject **fastlocals, **freevars; + PyObject *retval = NULL; /* Return value */ + PyThreadState *tstate = PyThreadState_GET(); + PyCodeObject *co; + + /* when tracing we set things up so that + + not (instr_lb <= current_bytecode_offset < instr_ub) + + is true when the line being executed has changed. The + initial values are such as to make this false the first + time it is tested. */ + int instr_ub = -1, instr_lb = 0, instr_prev = -1; + + unsigned char *first_instr; + PyObject *names; + PyObject *consts; #if defined(Py_DEBUG) || defined(LLTRACE) - /* Make it easier to find out where we are with a debugger */ - char *filename; + /* Make it easier to find out where we are with a debugger */ + char *filename; #endif /* Computed GOTOs, or @@ -807,7 +807,7 @@ (http://gcc.gnu.org/onlinedocs/gcc/Labels-as-Values.html). The traditional bytecode evaluation loop uses a "switch" statement, which - decent compilers will optimize as a single indirect branch instruction + decent compilers will optimize as a single indirect branch instruction combined with a lookup table of jump addresses. However, since the indirect jump instruction is shared by all opcodes, the CPU will have a hard time making the right prediction for where to jump next (actually, @@ -822,7 +822,7 @@ a much better chance to turn out valid, especially in small bytecode loops. A mispredicted branch on a modern CPU flushes the whole pipeline and - can cost several CPU cycles (depending on the pipeline depth), + can cost several CPU cycles (depending on the pipeline depth), and potentially many more instructions (depending on the pipeline width). A correctly predicted branch, however, is nearly free. @@ -851,56 +851,56 @@ /* This macro is used when several opcodes defer to the same implementation (e.g. SETUP_LOOP, SETUP_FINALLY) */ #define TARGET_WITH_IMPL(op, impl) \ - TARGET_##op: \ - opcode = op; \ - if (HAS_ARG(op)) \ - oparg = NEXTARG(); \ - case op: \ - goto impl; \ + TARGET_##op: \ + opcode = op; \ + if (HAS_ARG(op)) \ + oparg = NEXTARG(); \ + case op: \ + goto impl; \ #define TARGET(op) \ - TARGET_##op: \ - opcode = op; \ - if (HAS_ARG(op)) \ - oparg = NEXTARG(); \ - case op: + TARGET_##op: \ + opcode = op; \ + if (HAS_ARG(op)) \ + oparg = NEXTARG(); \ + case op: #define DISPATCH() \ - { \ - if (!_Py_atomic_load_relaxed(&eval_breaker)) { \ - FAST_DISPATCH(); \ - } \ - continue; \ - } + { \ + if (!_Py_atomic_load_relaxed(&eval_breaker)) { \ + FAST_DISPATCH(); \ + } \ + continue; \ + } #ifdef LLTRACE #define FAST_DISPATCH() \ - { \ - if (!lltrace && !_Py_TracingPossible) { \ - f->f_lasti = INSTR_OFFSET(); \ - goto *opcode_targets[*next_instr++]; \ - } \ - goto fast_next_opcode; \ - } + { \ + if (!lltrace && !_Py_TracingPossible) { \ + f->f_lasti = INSTR_OFFSET(); \ + goto *opcode_targets[*next_instr++]; \ + } \ + goto fast_next_opcode; \ + } #else #define FAST_DISPATCH() \ - { \ - if (!_Py_TracingPossible) { \ - f->f_lasti = INSTR_OFFSET(); \ - goto *opcode_targets[*next_instr++]; \ - } \ - goto fast_next_opcode; \ - } + { \ + if (!_Py_TracingPossible) { \ + f->f_lasti = INSTR_OFFSET(); \ + goto *opcode_targets[*next_instr++]; \ + } \ + goto fast_next_opcode; \ + } #endif #else #define TARGET(op) \ - case op: + case op: #define TARGET_WITH_IMPL(op, impl) \ - /* silence compiler warnings about `impl` unused */ \ - if (0) goto impl; \ - case op: + /* silence compiler warnings about `impl` unused */ \ + if (0) goto impl; \ + case op: #define DISPATCH() continue #define FAST_DISPATCH() goto fast_next_opcode #endif @@ -942,62 +942,62 @@ CALL_FUNCTION (and friends) */ - uint64 inst0, inst1, loop0, loop1, intr0 = 0, intr1 = 0; - int ticked = 0; + uint64 inst0, inst1, loop0, loop1, intr0 = 0, intr1 = 0; + int ticked = 0; - READ_TIMESTAMP(inst0); - READ_TIMESTAMP(inst1); - READ_TIMESTAMP(loop0); - READ_TIMESTAMP(loop1); + READ_TIMESTAMP(inst0); + READ_TIMESTAMP(inst1); + READ_TIMESTAMP(loop0); + READ_TIMESTAMP(loop1); - /* shut up the compiler */ - opcode = 0; + /* shut up the compiler */ + opcode = 0; #endif /* Code access macros */ -#define INSTR_OFFSET() ((int)(next_instr - first_instr)) -#define NEXTOP() (*next_instr++) -#define NEXTARG() (next_instr += 2, (next_instr[-1]<<8) + next_instr[-2]) -#define PEEKARG() ((next_instr[2]<<8) + next_instr[1]) -#define JUMPTO(x) (next_instr = first_instr + (x)) -#define JUMPBY(x) (next_instr += (x)) +#define INSTR_OFFSET() ((int)(next_instr - first_instr)) +#define NEXTOP() (*next_instr++) +#define NEXTARG() (next_instr += 2, (next_instr[-1]<<8) + next_instr[-2]) +#define PEEKARG() ((next_instr[2]<<8) + next_instr[1]) +#define JUMPTO(x) (next_instr = first_instr + (x)) +#define JUMPBY(x) (next_instr += (x)) /* OpCode prediction macros - Some opcodes tend to come in pairs thus making it possible to - predict the second code when the first is run. For example, - COMPARE_OP is often followed by JUMP_IF_FALSE or JUMP_IF_TRUE. And, - those opcodes are often followed by a POP_TOP. - - Verifying the prediction costs a single high-speed test of a register - variable against a constant. If the pairing was good, then the - processor's own internal branch predication has a high likelihood of - success, resulting in a nearly zero-overhead transition to the - next opcode. A successful prediction saves a trip through the eval-loop - including its two unpredictable branches, the HAS_ARG test and the - switch-case. Combined with the processor's internal branch prediction, - a successful PREDICT has the effect of making the two opcodes run as if - they were a single new opcode with the bodies combined. + Some opcodes tend to come in pairs thus making it possible to + predict the second code when the first is run. For example, + COMPARE_OP is often followed by JUMP_IF_FALSE or JUMP_IF_TRUE. And, + those opcodes are often followed by a POP_TOP. + + Verifying the prediction costs a single high-speed test of a register + variable against a constant. If the pairing was good, then the + processor's own internal branch predication has a high likelihood of + success, resulting in a nearly zero-overhead transition to the + next opcode. A successful prediction saves a trip through the eval-loop + including its two unpredictable branches, the HAS_ARG test and the + switch-case. Combined with the processor's internal branch prediction, + a successful PREDICT has the effect of making the two opcodes run as if + they were a single new opcode with the bodies combined. If collecting opcode statistics, your choices are to either keep the - predictions turned-on and interpret the results as if some opcodes - had been combined or turn-off predictions so that the opcode frequency - counter updates for both opcodes. + predictions turned-on and interpret the results as if some opcodes + had been combined or turn-off predictions so that the opcode frequency + counter updates for both opcodes. Opcode prediction is disabled with threaded code, since the latter allows - the CPU to record separate branch prediction information for each - opcode. + the CPU to record separate branch prediction information for each + opcode. */ #if defined(DYNAMIC_EXECUTION_PROFILE) || defined(USE_COMPUTED_GOTOS) -#define PREDICT(op) if (0) goto PRED_##op -#define PREDICTED(op) PRED_##op: -#define PREDICTED_WITH_ARG(op) PRED_##op: +#define PREDICT(op) if (0) goto PRED_##op +#define PREDICTED(op) PRED_##op: +#define PREDICTED_WITH_ARG(op) PRED_##op: #else -#define PREDICT(op) if (*next_instr == op) goto PRED_##op -#define PREDICTED(op) PRED_##op: next_instr++ -#define PREDICTED_WITH_ARG(op) PRED_##op: oparg = PEEKARG(); next_instr += 3 +#define PREDICT(op) if (*next_instr == op) goto PRED_##op +#define PREDICTED(op) PRED_##op: next_instr++ +#define PREDICTED_WITH_ARG(op) PRED_##op: oparg = PEEKARG(); next_instr += 3 #endif @@ -1005,44 +1005,44 @@ /* The stack can grow at most MAXINT deep, as co_nlocals and co_stacksize are ints. */ -#define STACK_LEVEL() ((int)(stack_pointer - f->f_valuestack)) -#define EMPTY() (STACK_LEVEL() == 0) -#define TOP() (stack_pointer[-1]) -#define SECOND() (stack_pointer[-2]) -#define THIRD() (stack_pointer[-3]) -#define FOURTH() (stack_pointer[-4]) +#define STACK_LEVEL() ((int)(stack_pointer - f->f_valuestack)) +#define EMPTY() (STACK_LEVEL() == 0) +#define TOP() (stack_pointer[-1]) +#define SECOND() (stack_pointer[-2]) +#define THIRD() (stack_pointer[-3]) +#define FOURTH() (stack_pointer[-4]) #define PEEK(n) (stack_pointer[-(n)]) -#define SET_TOP(v) (stack_pointer[-1] = (v)) -#define SET_SECOND(v) (stack_pointer[-2] = (v)) -#define SET_THIRD(v) (stack_pointer[-3] = (v)) -#define SET_FOURTH(v) (stack_pointer[-4] = (v)) +#define SET_TOP(v) (stack_pointer[-1] = (v)) +#define SET_SECOND(v) (stack_pointer[-2] = (v)) +#define SET_THIRD(v) (stack_pointer[-3] = (v)) +#define SET_FOURTH(v) (stack_pointer[-4] = (v)) #define SET_VALUE(n, v) (stack_pointer[-(n)] = (v)) -#define BASIC_STACKADJ(n) (stack_pointer += n) -#define BASIC_PUSH(v) (*stack_pointer++ = (v)) -#define BASIC_POP() (*--stack_pointer) +#define BASIC_STACKADJ(n) (stack_pointer += n) +#define BASIC_PUSH(v) (*stack_pointer++ = (v)) +#define BASIC_POP() (*--stack_pointer) #ifdef LLTRACE -#define PUSH(v) { (void)(BASIC_PUSH(v), \ - lltrace && prtrace(TOP(), "push")); \ - assert(STACK_LEVEL() <= co->co_stacksize); } -#define POP() ((void)(lltrace && prtrace(TOP(), "pop")), \ - BASIC_POP()) -#define STACKADJ(n) { (void)(BASIC_STACKADJ(n), \ - lltrace && prtrace(TOP(), "stackadj")); \ - assert(STACK_LEVEL() <= co->co_stacksize); } +#define PUSH(v) { (void)(BASIC_PUSH(v), \ + lltrace && prtrace(TOP(), "push")); \ + assert(STACK_LEVEL() <= co->co_stacksize); } +#define POP() ((void)(lltrace && prtrace(TOP(), "pop")), \ + BASIC_POP()) +#define STACKADJ(n) { (void)(BASIC_STACKADJ(n), \ + lltrace && prtrace(TOP(), "stackadj")); \ + assert(STACK_LEVEL() <= co->co_stacksize); } #define EXT_POP(STACK_POINTER) ((void)(lltrace && \ - prtrace((STACK_POINTER)[-1], "ext_pop")), \ - *--(STACK_POINTER)) + prtrace((STACK_POINTER)[-1], "ext_pop")), \ + *--(STACK_POINTER)) #else -#define PUSH(v) BASIC_PUSH(v) -#define POP() BASIC_POP() -#define STACKADJ(n) BASIC_STACKADJ(n) +#define PUSH(v) BASIC_PUSH(v) +#define POP() BASIC_POP() +#define STACKADJ(n) BASIC_STACKADJ(n) #define EXT_POP(STACK_POINTER) (*--(STACK_POINTER)) #endif /* Local variable macros */ -#define GETLOCAL(i) (fastlocals[i]) +#define GETLOCAL(i) (fastlocals[i]) /* The SETLOCAL() macro must not DECREF the local variable in-place and then store the new value; it must copy the old value to a temporary @@ -1050,2006 +1050,2006 @@ This is because it is possible that during the DECREF the frame is accessed by other code (e.g. a __del__ method or gc.collect()) and the variable would be pointing to already-freed memory. */ -#define SETLOCAL(i, value) do { PyObject *tmp = GETLOCAL(i); \ - GETLOCAL(i) = value; \ - Py_XDECREF(tmp); } while (0) +#define SETLOCAL(i, value) do { PyObject *tmp = GETLOCAL(i); \ + GETLOCAL(i) = value; \ + Py_XDECREF(tmp); } while (0) #define UNWIND_BLOCK(b) \ - while (STACK_LEVEL() > (b)->b_level) { \ - PyObject *v = POP(); \ - Py_XDECREF(v); \ - } + while (STACK_LEVEL() > (b)->b_level) { \ + PyObject *v = POP(); \ + Py_XDECREF(v); \ + } #define UNWIND_EXCEPT_HANDLER(b) \ - { \ - PyObject *type, *value, *traceback; \ - assert(STACK_LEVEL() >= (b)->b_level + 3); \ - while (STACK_LEVEL() > (b)->b_level + 3) { \ - value = POP(); \ - Py_XDECREF(value); \ - } \ - type = tstate->exc_type; \ - value = tstate->exc_value; \ - traceback = tstate->exc_traceback; \ - tstate->exc_type = POP(); \ - tstate->exc_value = POP(); \ - tstate->exc_traceback = POP(); \ - Py_XDECREF(type); \ - Py_XDECREF(value); \ - Py_XDECREF(traceback); \ - } + { \ + PyObject *type, *value, *traceback; \ + assert(STACK_LEVEL() >= (b)->b_level + 3); \ + while (STACK_LEVEL() > (b)->b_level + 3) { \ + value = POP(); \ + Py_XDECREF(value); \ + } \ + type = tstate->exc_type; \ + value = tstate->exc_value; \ + traceback = tstate->exc_traceback; \ + tstate->exc_type = POP(); \ + tstate->exc_value = POP(); \ + tstate->exc_traceback = POP(); \ + Py_XDECREF(type); \ + Py_XDECREF(value); \ + Py_XDECREF(traceback); \ + } #define SAVE_EXC_STATE() \ - { \ - PyObject *type, *value, *traceback; \ - Py_XINCREF(tstate->exc_type); \ - Py_XINCREF(tstate->exc_value); \ - Py_XINCREF(tstate->exc_traceback); \ - type = f->f_exc_type; \ - value = f->f_exc_value; \ - traceback = f->f_exc_traceback; \ - f->f_exc_type = tstate->exc_type; \ - f->f_exc_value = tstate->exc_value; \ - f->f_exc_traceback = tstate->exc_traceback; \ - Py_XDECREF(type); \ - Py_XDECREF(value); \ - Py_XDECREF(traceback); \ - } + { \ + PyObject *type, *value, *traceback; \ + Py_XINCREF(tstate->exc_type); \ + Py_XINCREF(tstate->exc_value); \ + Py_XINCREF(tstate->exc_traceback); \ + type = f->f_exc_type; \ + value = f->f_exc_value; \ + traceback = f->f_exc_traceback; \ + f->f_exc_type = tstate->exc_type; \ + f->f_exc_value = tstate->exc_value; \ + f->f_exc_traceback = tstate->exc_traceback; \ + Py_XDECREF(type); \ + Py_XDECREF(value); \ + Py_XDECREF(traceback); \ + } #define SWAP_EXC_STATE() \ - { \ - PyObject *tmp; \ - tmp = tstate->exc_type; \ - tstate->exc_type = f->f_exc_type; \ - f->f_exc_type = tmp; \ - tmp = tstate->exc_value; \ - tstate->exc_value = f->f_exc_value; \ - f->f_exc_value = tmp; \ - tmp = tstate->exc_traceback; \ - tstate->exc_traceback = f->f_exc_traceback; \ - f->f_exc_traceback = tmp; \ - } + { \ + PyObject *tmp; \ + tmp = tstate->exc_type; \ + tstate->exc_type = f->f_exc_type; \ + f->f_exc_type = tmp; \ + tmp = tstate->exc_value; \ + tstate->exc_value = f->f_exc_value; \ + f->f_exc_value = tmp; \ + tmp = tstate->exc_traceback; \ + tstate->exc_traceback = f->f_exc_traceback; \ + f->f_exc_traceback = tmp; \ + } /* Start of code */ - if (f == NULL) - return NULL; + if (f == NULL) + return NULL; - /* push frame */ - if (Py_EnterRecursiveCall("")) - return NULL; - - tstate->frame = f; - - if (tstate->use_tracing) { - if (tstate->c_tracefunc != NULL) { - /* tstate->c_tracefunc, if defined, is a - function that will be called on *every* entry - to a code block. Its return value, if not - None, is a function that will be called at - the start of each executed line of code. - (Actually, the function must return itself - in order to continue tracing.) The trace - functions are called with three arguments: - a pointer to the current frame, a string - indicating why the function is called, and - an argument which depends on the situation. - The global trace function is also called - whenever an exception is detected. */ - if (call_trace_protected(tstate->c_tracefunc, - tstate->c_traceobj, - f, PyTrace_CALL, Py_None)) { - /* Trace function raised an error */ - goto exit_eval_frame; - } - } - if (tstate->c_profilefunc != NULL) { - /* Similar for c_profilefunc, except it needn't - return itself and isn't called for "line" events */ - if (call_trace_protected(tstate->c_profilefunc, - tstate->c_profileobj, - f, PyTrace_CALL, Py_None)) { - /* Profile function raised an error */ - goto exit_eval_frame; - } - } - } - - co = f->f_code; - names = co->co_names; - consts = co->co_consts; - fastlocals = f->f_localsplus; - freevars = f->f_localsplus + co->co_nlocals; - first_instr = (unsigned char*) PyBytes_AS_STRING(co->co_code); - /* An explanation is in order for the next line. - - f->f_lasti now refers to the index of the last instruction - executed. You might think this was obvious from the name, but - this wasn't always true before 2.3! PyFrame_New now sets - f->f_lasti to -1 (i.e. the index *before* the first instruction) - and YIELD_VALUE doesn't fiddle with f_lasti any more. So this - does work. Promise. - - When the PREDICT() macros are enabled, some opcode pairs follow in - direct succession without updating f->f_lasti. A successful - prediction effectively links the two codes together as if they - were a single new opcode; accordingly,f->f_lasti will point to - the first code in the pair (for instance, GET_ITER followed by - FOR_ITER is effectively a single opcode and f->f_lasti will point - at to the beginning of the combined pair.) - */ - next_instr = first_instr + f->f_lasti + 1; - stack_pointer = f->f_stacktop; - assert(stack_pointer != NULL); - f->f_stacktop = NULL; /* remains NULL unless yield suspends frame */ - - if (co->co_flags & CO_GENERATOR && !throwflag) { - if (f->f_exc_type != NULL && f->f_exc_type != Py_None) { - /* We were in an except handler when we left, - restore the exception state which was put aside - (see YIELD_VALUE). */ - SWAP_EXC_STATE(); - } - else { - SAVE_EXC_STATE(); - } - } + /* push frame */ + if (Py_EnterRecursiveCall("")) + return NULL; + + tstate->frame = f; + + if (tstate->use_tracing) { + if (tstate->c_tracefunc != NULL) { + /* tstate->c_tracefunc, if defined, is a + function that will be called on *every* entry + to a code block. Its return value, if not + None, is a function that will be called at + the start of each executed line of code. + (Actually, the function must return itself + in order to continue tracing.) The trace + functions are called with three arguments: + a pointer to the current frame, a string + indicating why the function is called, and + an argument which depends on the situation. + The global trace function is also called + whenever an exception is detected. */ + if (call_trace_protected(tstate->c_tracefunc, + tstate->c_traceobj, + f, PyTrace_CALL, Py_None)) { + /* Trace function raised an error */ + goto exit_eval_frame; + } + } + if (tstate->c_profilefunc != NULL) { + /* Similar for c_profilefunc, except it needn't + return itself and isn't called for "line" events */ + if (call_trace_protected(tstate->c_profilefunc, + tstate->c_profileobj, + f, PyTrace_CALL, Py_None)) { + /* Profile function raised an error */ + goto exit_eval_frame; + } + } + } + + co = f->f_code; + names = co->co_names; + consts = co->co_consts; + fastlocals = f->f_localsplus; + freevars = f->f_localsplus + co->co_nlocals; + first_instr = (unsigned char*) PyBytes_AS_STRING(co->co_code); + /* An explanation is in order for the next line. + + f->f_lasti now refers to the index of the last instruction + executed. You might think this was obvious from the name, but + this wasn't always true before 2.3! PyFrame_New now sets + f->f_lasti to -1 (i.e. the index *before* the first instruction) + and YIELD_VALUE doesn't fiddle with f_lasti any more. So this + does work. Promise. + + When the PREDICT() macros are enabled, some opcode pairs follow in + direct succession without updating f->f_lasti. A successful + prediction effectively links the two codes together as if they + were a single new opcode; accordingly,f->f_lasti will point to + the first code in the pair (for instance, GET_ITER followed by + FOR_ITER is effectively a single opcode and f->f_lasti will point + at to the beginning of the combined pair.) + */ + next_instr = first_instr + f->f_lasti + 1; + stack_pointer = f->f_stacktop; + assert(stack_pointer != NULL); + f->f_stacktop = NULL; /* remains NULL unless yield suspends frame */ + + if (co->co_flags & CO_GENERATOR && !throwflag) { + if (f->f_exc_type != NULL && f->f_exc_type != Py_None) { + /* We were in an except handler when we left, + restore the exception state which was put aside + (see YIELD_VALUE). */ + SWAP_EXC_STATE(); + } + else { + SAVE_EXC_STATE(); + } + } #ifdef LLTRACE - lltrace = PyDict_GetItemString(f->f_globals, "__lltrace__") != NULL; + lltrace = PyDict_GetItemString(f->f_globals, "__lltrace__") != NULL; #endif #if defined(Py_DEBUG) || defined(LLTRACE) - filename = _PyUnicode_AsString(co->co_filename); + filename = _PyUnicode_AsString(co->co_filename); #endif - why = WHY_NOT; - err = 0; - x = Py_None; /* Not a reference, just anything non-NULL */ - w = NULL; + why = WHY_NOT; + err = 0; + x = Py_None; /* Not a reference, just anything non-NULL */ + w = NULL; - if (throwflag) { /* support for generator.throw() */ - why = WHY_EXCEPTION; - goto on_error; - } + if (throwflag) { /* support for generator.throw() */ + why = WHY_EXCEPTION; + goto on_error; + } - for (;;) { + for (;;) { #ifdef WITH_TSC - if (inst1 == 0) { - /* Almost surely, the opcode executed a break - or a continue, preventing inst1 from being set - on the way out of the loop. - */ - READ_TIMESTAMP(inst1); - loop1 = inst1; - } - dump_tsc(opcode, ticked, inst0, inst1, loop0, loop1, - intr0, intr1); - ticked = 0; - inst1 = 0; - intr0 = 0; - intr1 = 0; - READ_TIMESTAMP(loop0); -#endif - assert(stack_pointer >= f->f_valuestack); /* else underflow */ - assert(STACK_LEVEL() <= co->co_stacksize); /* else overflow */ - - /* Do periodic things. Doing this every time through - the loop would add too much overhead, so we do it - only every Nth instruction. We also do it if - ``pendingcalls_to_do'' is set, i.e. when an asynchronous - event needs attention (e.g. a signal handler or - async I/O handler); see Py_AddPendingCall() and - Py_MakePendingCalls() above. */ - - if (_Py_atomic_load_relaxed(&eval_breaker)) { - if (*next_instr == SETUP_FINALLY) { - /* Make the last opcode before - a try: finally: block uninterruptable. */ - goto fast_next_opcode; - } - tstate->tick_counter++; + if (inst1 == 0) { + /* Almost surely, the opcode executed a break + or a continue, preventing inst1 from being set + on the way out of the loop. + */ + READ_TIMESTAMP(inst1); + loop1 = inst1; + } + dump_tsc(opcode, ticked, inst0, inst1, loop0, loop1, + intr0, intr1); + ticked = 0; + inst1 = 0; + intr0 = 0; + intr1 = 0; + READ_TIMESTAMP(loop0); +#endif + assert(stack_pointer >= f->f_valuestack); /* else underflow */ + assert(STACK_LEVEL() <= co->co_stacksize); /* else overflow */ + + /* Do periodic things. Doing this every time through + the loop would add too much overhead, so we do it + only every Nth instruction. We also do it if + ``pendingcalls_to_do'' is set, i.e. when an asynchronous + event needs attention (e.g. a signal handler or + async I/O handler); see Py_AddPendingCall() and + Py_MakePendingCalls() above. */ + + if (_Py_atomic_load_relaxed(&eval_breaker)) { + if (*next_instr == SETUP_FINALLY) { + /* Make the last opcode before + a try: finally: block uninterruptable. */ + goto fast_next_opcode; + } + tstate->tick_counter++; #ifdef WITH_TSC - ticked = 1; + ticked = 1; #endif - if (_Py_atomic_load_relaxed(&pendingcalls_to_do)) { - if (Py_MakePendingCalls() < 0) { - why = WHY_EXCEPTION; - goto on_error; - } - } - if (_Py_atomic_load_relaxed(&gil_drop_request)) { + if (_Py_atomic_load_relaxed(&pendingcalls_to_do)) { + if (Py_MakePendingCalls() < 0) { + why = WHY_EXCEPTION; + goto on_error; + } + } + if (_Py_atomic_load_relaxed(&gil_drop_request)) { #ifdef WITH_THREAD - /* Give another thread a chance */ - if (PyThreadState_Swap(NULL) != tstate) - Py_FatalError("ceval: tstate mix-up"); - drop_gil(tstate); - - /* Other threads may run now */ - - take_gil(tstate); - if (PyThreadState_Swap(tstate) != NULL) - Py_FatalError("ceval: orphan tstate"); -#endif - } - /* Check for asynchronous exceptions. */ - if (tstate->async_exc != NULL) { - x = tstate->async_exc; - tstate->async_exc = NULL; - UNSIGNAL_ASYNC_EXC(); - PyErr_SetNone(x); - Py_DECREF(x); - why = WHY_EXCEPTION; - goto on_error; - } - } - - fast_next_opcode: - f->f_lasti = INSTR_OFFSET(); - - /* line-by-line tracing support */ - - if (_Py_TracingPossible && - tstate->c_tracefunc != NULL && !tstate->tracing) { - /* see maybe_call_line_trace - for expository comments */ - f->f_stacktop = stack_pointer; - - err = maybe_call_line_trace(tstate->c_tracefunc, - tstate->c_traceobj, - f, &instr_lb, &instr_ub, - &instr_prev); - /* Reload possibly changed frame fields */ - JUMPTO(f->f_lasti); - if (f->f_stacktop != NULL) { - stack_pointer = f->f_stacktop; - f->f_stacktop = NULL; - } - if (err) { - /* trace function raised an exception */ - goto on_error; - } - } - - /* Extract opcode and argument */ - - opcode = NEXTOP(); - oparg = 0; /* allows oparg to be stored in a register because - it doesn't have to be remembered across a full loop */ - if (HAS_ARG(opcode)) - oparg = NEXTARG(); - dispatch_opcode: + /* Give another thread a chance */ + if (PyThreadState_Swap(NULL) != tstate) + Py_FatalError("ceval: tstate mix-up"); + drop_gil(tstate); + + /* Other threads may run now */ + + take_gil(tstate); + if (PyThreadState_Swap(tstate) != NULL) + Py_FatalError("ceval: orphan tstate"); +#endif + } + /* Check for asynchronous exceptions. */ + if (tstate->async_exc != NULL) { + x = tstate->async_exc; + tstate->async_exc = NULL; + UNSIGNAL_ASYNC_EXC(); + PyErr_SetNone(x); + Py_DECREF(x); + why = WHY_EXCEPTION; + goto on_error; + } + } + + fast_next_opcode: + f->f_lasti = INSTR_OFFSET(); + + /* line-by-line tracing support */ + + if (_Py_TracingPossible && + tstate->c_tracefunc != NULL && !tstate->tracing) { + /* see maybe_call_line_trace + for expository comments */ + f->f_stacktop = stack_pointer; + + err = maybe_call_line_trace(tstate->c_tracefunc, + tstate->c_traceobj, + f, &instr_lb, &instr_ub, + &instr_prev); + /* Reload possibly changed frame fields */ + JUMPTO(f->f_lasti); + if (f->f_stacktop != NULL) { + stack_pointer = f->f_stacktop; + f->f_stacktop = NULL; + } + if (err) { + /* trace function raised an exception */ + goto on_error; + } + } + + /* Extract opcode and argument */ + + opcode = NEXTOP(); + oparg = 0; /* allows oparg to be stored in a register because + it doesn't have to be remembered across a full loop */ + if (HAS_ARG(opcode)) + oparg = NEXTARG(); + dispatch_opcode: #ifdef DYNAMIC_EXECUTION_PROFILE #ifdef DXPAIRS - dxpairs[lastopcode][opcode]++; - lastopcode = opcode; + dxpairs[lastopcode][opcode]++; + lastopcode = opcode; #endif - dxp[opcode]++; + dxp[opcode]++; #endif #ifdef LLTRACE - /* Instruction tracing */ + /* Instruction tracing */ - if (lltrace) { - if (HAS_ARG(opcode)) { - printf("%d: %d, %d\n", - f->f_lasti, opcode, oparg); - } - else { - printf("%d: %d\n", - f->f_lasti, opcode); - } - } -#endif - - /* Main switch on opcode */ - READ_TIMESTAMP(inst0); - - switch (opcode) { - - /* BEWARE! - It is essential that any operation that fails sets either - x to NULL, err to nonzero, or why to anything but WHY_NOT, - and that no operation that succeeds does this! */ - - /* case STOP_CODE: this is an error! */ - - TARGET(NOP) - FAST_DISPATCH(); - - TARGET(LOAD_FAST) - x = GETLOCAL(oparg); - if (x != NULL) { - Py_INCREF(x); - PUSH(x); - FAST_DISPATCH(); - } - format_exc_check_arg(PyExc_UnboundLocalError, - UNBOUNDLOCAL_ERROR_MSG, - PyTuple_GetItem(co->co_varnames, oparg)); - break; - - TARGET(LOAD_CONST) - x = GETITEM(consts, oparg); - Py_INCREF(x); - PUSH(x); - FAST_DISPATCH(); - - PREDICTED_WITH_ARG(STORE_FAST); - TARGET(STORE_FAST) - v = POP(); - SETLOCAL(oparg, v); - FAST_DISPATCH(); - - TARGET(POP_TOP) - v = POP(); - Py_DECREF(v); - FAST_DISPATCH(); - - TARGET(ROT_TWO) - v = TOP(); - w = SECOND(); - SET_TOP(w); - SET_SECOND(v); - FAST_DISPATCH(); - - TARGET(ROT_THREE) - v = TOP(); - w = SECOND(); - x = THIRD(); - SET_TOP(w); - SET_SECOND(x); - SET_THIRD(v); - FAST_DISPATCH(); - - TARGET(ROT_FOUR) - u = TOP(); - v = SECOND(); - w = THIRD(); - x = FOURTH(); - SET_TOP(v); - SET_SECOND(w); - SET_THIRD(x); - SET_FOURTH(u); - FAST_DISPATCH(); - - TARGET(DUP_TOP) - v = TOP(); - Py_INCREF(v); - PUSH(v); - FAST_DISPATCH(); - - TARGET(DUP_TOPX) - if (oparg == 2) { - x = TOP(); - Py_INCREF(x); - w = SECOND(); - Py_INCREF(w); - STACKADJ(2); - SET_TOP(x); - SET_SECOND(w); - FAST_DISPATCH(); - } else if (oparg == 3) { - x = TOP(); - Py_INCREF(x); - w = SECOND(); - Py_INCREF(w); - v = THIRD(); - Py_INCREF(v); - STACKADJ(3); - SET_TOP(x); - SET_SECOND(w); - SET_THIRD(v); - FAST_DISPATCH(); - } - Py_FatalError("invalid argument to DUP_TOPX" - " (bytecode corruption?)"); - /* Never returns, so don't bother to set why. */ - break; - - TARGET(UNARY_POSITIVE) - v = TOP(); - x = PyNumber_Positive(v); - Py_DECREF(v); - SET_TOP(x); - if (x != NULL) DISPATCH(); - break; - - TARGET(UNARY_NEGATIVE) - v = TOP(); - x = PyNumber_Negative(v); - Py_DECREF(v); - SET_TOP(x); - if (x != NULL) DISPATCH(); - break; - - TARGET(UNARY_NOT) - v = TOP(); - err = PyObject_IsTrue(v); - Py_DECREF(v); - if (err == 0) { - Py_INCREF(Py_True); - SET_TOP(Py_True); - DISPATCH(); - } - else if (err > 0) { - Py_INCREF(Py_False); - SET_TOP(Py_False); - err = 0; - DISPATCH(); - } - STACKADJ(-1); - break; - - TARGET(UNARY_INVERT) - v = TOP(); - x = PyNumber_Invert(v); - Py_DECREF(v); - SET_TOP(x); - if (x != NULL) DISPATCH(); - break; - - TARGET(BINARY_POWER) - w = POP(); - v = TOP(); - x = PyNumber_Power(v, w, Py_None); - Py_DECREF(v); - Py_DECREF(w); - SET_TOP(x); - if (x != NULL) DISPATCH(); - break; - - TARGET(BINARY_MULTIPLY) - w = POP(); - v = TOP(); - x = PyNumber_Multiply(v, w); - Py_DECREF(v); - Py_DECREF(w); - SET_TOP(x); - if (x != NULL) DISPATCH(); - break; - - TARGET(BINARY_TRUE_DIVIDE) - w = POP(); - v = TOP(); - x = PyNumber_TrueDivide(v, w); - Py_DECREF(v); - Py_DECREF(w); - SET_TOP(x); - if (x != NULL) DISPATCH(); - break; - - TARGET(BINARY_FLOOR_DIVIDE) - w = POP(); - v = TOP(); - x = PyNumber_FloorDivide(v, w); - Py_DECREF(v); - Py_DECREF(w); - SET_TOP(x); - if (x != NULL) DISPATCH(); - break; - - TARGET(BINARY_MODULO) - w = POP(); - v = TOP(); - if (PyUnicode_CheckExact(v)) - x = PyUnicode_Format(v, w); - else - x = PyNumber_Remainder(v, w); - Py_DECREF(v); - Py_DECREF(w); - SET_TOP(x); - if (x != NULL) DISPATCH(); - break; - - TARGET(BINARY_ADD) - w = POP(); - v = TOP(); - if (PyUnicode_CheckExact(v) && - PyUnicode_CheckExact(w)) { - x = unicode_concatenate(v, w, f, next_instr); - /* unicode_concatenate consumed the ref to v */ - goto skip_decref_vx; - } - else { - x = PyNumber_Add(v, w); - } - Py_DECREF(v); - skip_decref_vx: - Py_DECREF(w); - SET_TOP(x); - if (x != NULL) DISPATCH(); - break; - - TARGET(BINARY_SUBTRACT) - w = POP(); - v = TOP(); - x = PyNumber_Subtract(v, w); - Py_DECREF(v); - Py_DECREF(w); - SET_TOP(x); - if (x != NULL) DISPATCH(); - break; - - TARGET(BINARY_SUBSCR) - w = POP(); - v = TOP(); - x = PyObject_GetItem(v, w); - Py_DECREF(v); - Py_DECREF(w); - SET_TOP(x); - if (x != NULL) DISPATCH(); - break; - - TARGET(BINARY_LSHIFT) - w = POP(); - v = TOP(); - x = PyNumber_Lshift(v, w); - Py_DECREF(v); - Py_DECREF(w); - SET_TOP(x); - if (x != NULL) DISPATCH(); - break; - - TARGET(BINARY_RSHIFT) - w = POP(); - v = TOP(); - x = PyNumber_Rshift(v, w); - Py_DECREF(v); - Py_DECREF(w); - SET_TOP(x); - if (x != NULL) DISPATCH(); - break; - - TARGET(BINARY_AND) - w = POP(); - v = TOP(); - x = PyNumber_And(v, w); - Py_DECREF(v); - Py_DECREF(w); - SET_TOP(x); - if (x != NULL) DISPATCH(); - break; - - TARGET(BINARY_XOR) - w = POP(); - v = TOP(); - x = PyNumber_Xor(v, w); - Py_DECREF(v); - Py_DECREF(w); - SET_TOP(x); - if (x != NULL) DISPATCH(); - break; - - TARGET(BINARY_OR) - w = POP(); - v = TOP(); - x = PyNumber_Or(v, w); - Py_DECREF(v); - Py_DECREF(w); - SET_TOP(x); - if (x != NULL) DISPATCH(); - break; - - TARGET(LIST_APPEND) - w = POP(); - v = PEEK(oparg); - err = PyList_Append(v, w); - Py_DECREF(w); - if (err == 0) { - PREDICT(JUMP_ABSOLUTE); - DISPATCH(); - } - break; - - TARGET(SET_ADD) - w = POP(); - v = stack_pointer[-oparg]; - err = PySet_Add(v, w); - Py_DECREF(w); - if (err == 0) { - PREDICT(JUMP_ABSOLUTE); - DISPATCH(); - } - break; - - TARGET(INPLACE_POWER) - w = POP(); - v = TOP(); - x = PyNumber_InPlacePower(v, w, Py_None); - Py_DECREF(v); - Py_DECREF(w); - SET_TOP(x); - if (x != NULL) DISPATCH(); - break; - - TARGET(INPLACE_MULTIPLY) - w = POP(); - v = TOP(); - x = PyNumber_InPlaceMultiply(v, w); - Py_DECREF(v); - Py_DECREF(w); - SET_TOP(x); - if (x != NULL) DISPATCH(); - break; - - TARGET(INPLACE_TRUE_DIVIDE) - w = POP(); - v = TOP(); - x = PyNumber_InPlaceTrueDivide(v, w); - Py_DECREF(v); - Py_DECREF(w); - SET_TOP(x); - if (x != NULL) DISPATCH(); - break; - - TARGET(INPLACE_FLOOR_DIVIDE) - w = POP(); - v = TOP(); - x = PyNumber_InPlaceFloorDivide(v, w); - Py_DECREF(v); - Py_DECREF(w); - SET_TOP(x); - if (x != NULL) DISPATCH(); - break; - - TARGET(INPLACE_MODULO) - w = POP(); - v = TOP(); - x = PyNumber_InPlaceRemainder(v, w); - Py_DECREF(v); - Py_DECREF(w); - SET_TOP(x); - if (x != NULL) DISPATCH(); - break; - - TARGET(INPLACE_ADD) - w = POP(); - v = TOP(); - if (PyUnicode_CheckExact(v) && - PyUnicode_CheckExact(w)) { - x = unicode_concatenate(v, w, f, next_instr); - /* unicode_concatenate consumed the ref to v */ - goto skip_decref_v; - } - else { - x = PyNumber_InPlaceAdd(v, w); - } - Py_DECREF(v); - skip_decref_v: - Py_DECREF(w); - SET_TOP(x); - if (x != NULL) DISPATCH(); - break; - - TARGET(INPLACE_SUBTRACT) - w = POP(); - v = TOP(); - x = PyNumber_InPlaceSubtract(v, w); - Py_DECREF(v); - Py_DECREF(w); - SET_TOP(x); - if (x != NULL) DISPATCH(); - break; - - TARGET(INPLACE_LSHIFT) - w = POP(); - v = TOP(); - x = PyNumber_InPlaceLshift(v, w); - Py_DECREF(v); - Py_DECREF(w); - SET_TOP(x); - if (x != NULL) DISPATCH(); - break; - - TARGET(INPLACE_RSHIFT) - w = POP(); - v = TOP(); - x = PyNumber_InPlaceRshift(v, w); - Py_DECREF(v); - Py_DECREF(w); - SET_TOP(x); - if (x != NULL) DISPATCH(); - break; - - TARGET(INPLACE_AND) - w = POP(); - v = TOP(); - x = PyNumber_InPlaceAnd(v, w); - Py_DECREF(v); - Py_DECREF(w); - SET_TOP(x); - if (x != NULL) DISPATCH(); - break; - - TARGET(INPLACE_XOR) - w = POP(); - v = TOP(); - x = PyNumber_InPlaceXor(v, w); - Py_DECREF(v); - Py_DECREF(w); - SET_TOP(x); - if (x != NULL) DISPATCH(); - break; - - TARGET(INPLACE_OR) - w = POP(); - v = TOP(); - x = PyNumber_InPlaceOr(v, w); - Py_DECREF(v); - Py_DECREF(w); - SET_TOP(x); - if (x != NULL) DISPATCH(); - break; - - TARGET(STORE_SUBSCR) - w = TOP(); - v = SECOND(); - u = THIRD(); - STACKADJ(-3); - /* v[w] = u */ - err = PyObject_SetItem(v, w, u); - Py_DECREF(u); - Py_DECREF(v); - Py_DECREF(w); - if (err == 0) DISPATCH(); - break; - - TARGET(DELETE_SUBSCR) - w = TOP(); - v = SECOND(); - STACKADJ(-2); - /* del v[w] */ - err = PyObject_DelItem(v, w); - Py_DECREF(v); - Py_DECREF(w); - if (err == 0) DISPATCH(); - break; - - TARGET(PRINT_EXPR) - v = POP(); - w = PySys_GetObject("displayhook"); - if (w == NULL) { - PyErr_SetString(PyExc_RuntimeError, - "lost sys.displayhook"); - err = -1; - x = NULL; - } - if (err == 0) { - x = PyTuple_Pack(1, v); - if (x == NULL) - err = -1; - } - if (err == 0) { - w = PyEval_CallObject(w, x); - Py_XDECREF(w); - if (w == NULL) - err = -1; - } - Py_DECREF(v); - Py_XDECREF(x); - break; + if (lltrace) { + if (HAS_ARG(opcode)) { + printf("%d: %d, %d\n", + f->f_lasti, opcode, oparg); + } + else { + printf("%d: %d\n", + f->f_lasti, opcode); + } + } +#endif + + /* Main switch on opcode */ + READ_TIMESTAMP(inst0); + + switch (opcode) { + + /* BEWARE! + It is essential that any operation that fails sets either + x to NULL, err to nonzero, or why to anything but WHY_NOT, + and that no operation that succeeds does this! */ + + /* case STOP_CODE: this is an error! */ + + TARGET(NOP) + FAST_DISPATCH(); + + TARGET(LOAD_FAST) + x = GETLOCAL(oparg); + if (x != NULL) { + Py_INCREF(x); + PUSH(x); + FAST_DISPATCH(); + } + format_exc_check_arg(PyExc_UnboundLocalError, + UNBOUNDLOCAL_ERROR_MSG, + PyTuple_GetItem(co->co_varnames, oparg)); + break; + + TARGET(LOAD_CONST) + x = GETITEM(consts, oparg); + Py_INCREF(x); + PUSH(x); + FAST_DISPATCH(); + + PREDICTED_WITH_ARG(STORE_FAST); + TARGET(STORE_FAST) + v = POP(); + SETLOCAL(oparg, v); + FAST_DISPATCH(); + + TARGET(POP_TOP) + v = POP(); + Py_DECREF(v); + FAST_DISPATCH(); + + TARGET(ROT_TWO) + v = TOP(); + w = SECOND(); + SET_TOP(w); + SET_SECOND(v); + FAST_DISPATCH(); + + TARGET(ROT_THREE) + v = TOP(); + w = SECOND(); + x = THIRD(); + SET_TOP(w); + SET_SECOND(x); + SET_THIRD(v); + FAST_DISPATCH(); + + TARGET(ROT_FOUR) + u = TOP(); + v = SECOND(); + w = THIRD(); + x = FOURTH(); + SET_TOP(v); + SET_SECOND(w); + SET_THIRD(x); + SET_FOURTH(u); + FAST_DISPATCH(); + + TARGET(DUP_TOP) + v = TOP(); + Py_INCREF(v); + PUSH(v); + FAST_DISPATCH(); + + TARGET(DUP_TOPX) + if (oparg == 2) { + x = TOP(); + Py_INCREF(x); + w = SECOND(); + Py_INCREF(w); + STACKADJ(2); + SET_TOP(x); + SET_SECOND(w); + FAST_DISPATCH(); + } else if (oparg == 3) { + x = TOP(); + Py_INCREF(x); + w = SECOND(); + Py_INCREF(w); + v = THIRD(); + Py_INCREF(v); + STACKADJ(3); + SET_TOP(x); + SET_SECOND(w); + SET_THIRD(v); + FAST_DISPATCH(); + } + Py_FatalError("invalid argument to DUP_TOPX" + " (bytecode corruption?)"); + /* Never returns, so don't bother to set why. */ + break; + + TARGET(UNARY_POSITIVE) + v = TOP(); + x = PyNumber_Positive(v); + Py_DECREF(v); + SET_TOP(x); + if (x != NULL) DISPATCH(); + break; + + TARGET(UNARY_NEGATIVE) + v = TOP(); + x = PyNumber_Negative(v); + Py_DECREF(v); + SET_TOP(x); + if (x != NULL) DISPATCH(); + break; + + TARGET(UNARY_NOT) + v = TOP(); + err = PyObject_IsTrue(v); + Py_DECREF(v); + if (err == 0) { + Py_INCREF(Py_True); + SET_TOP(Py_True); + DISPATCH(); + } + else if (err > 0) { + Py_INCREF(Py_False); + SET_TOP(Py_False); + err = 0; + DISPATCH(); + } + STACKADJ(-1); + break; + + TARGET(UNARY_INVERT) + v = TOP(); + x = PyNumber_Invert(v); + Py_DECREF(v); + SET_TOP(x); + if (x != NULL) DISPATCH(); + break; + + TARGET(BINARY_POWER) + w = POP(); + v = TOP(); + x = PyNumber_Power(v, w, Py_None); + Py_DECREF(v); + Py_DECREF(w); + SET_TOP(x); + if (x != NULL) DISPATCH(); + break; + + TARGET(BINARY_MULTIPLY) + w = POP(); + v = TOP(); + x = PyNumber_Multiply(v, w); + Py_DECREF(v); + Py_DECREF(w); + SET_TOP(x); + if (x != NULL) DISPATCH(); + break; + + TARGET(BINARY_TRUE_DIVIDE) + w = POP(); + v = TOP(); + x = PyNumber_TrueDivide(v, w); + Py_DECREF(v); + Py_DECREF(w); + SET_TOP(x); + if (x != NULL) DISPATCH(); + break; + + TARGET(BINARY_FLOOR_DIVIDE) + w = POP(); + v = TOP(); + x = PyNumber_FloorDivide(v, w); + Py_DECREF(v); + Py_DECREF(w); + SET_TOP(x); + if (x != NULL) DISPATCH(); + break; + + TARGET(BINARY_MODULO) + w = POP(); + v = TOP(); + if (PyUnicode_CheckExact(v)) + x = PyUnicode_Format(v, w); + else + x = PyNumber_Remainder(v, w); + Py_DECREF(v); + Py_DECREF(w); + SET_TOP(x); + if (x != NULL) DISPATCH(); + break; + + TARGET(BINARY_ADD) + w = POP(); + v = TOP(); + if (PyUnicode_CheckExact(v) && + PyUnicode_CheckExact(w)) { + x = unicode_concatenate(v, w, f, next_instr); + /* unicode_concatenate consumed the ref to v */ + goto skip_decref_vx; + } + else { + x = PyNumber_Add(v, w); + } + Py_DECREF(v); + skip_decref_vx: + Py_DECREF(w); + SET_TOP(x); + if (x != NULL) DISPATCH(); + break; + + TARGET(BINARY_SUBTRACT) + w = POP(); + v = TOP(); + x = PyNumber_Subtract(v, w); + Py_DECREF(v); + Py_DECREF(w); + SET_TOP(x); + if (x != NULL) DISPATCH(); + break; + + TARGET(BINARY_SUBSCR) + w = POP(); + v = TOP(); + x = PyObject_GetItem(v, w); + Py_DECREF(v); + Py_DECREF(w); + SET_TOP(x); + if (x != NULL) DISPATCH(); + break; + + TARGET(BINARY_LSHIFT) + w = POP(); + v = TOP(); + x = PyNumber_Lshift(v, w); + Py_DECREF(v); + Py_DECREF(w); + SET_TOP(x); + if (x != NULL) DISPATCH(); + break; + + TARGET(BINARY_RSHIFT) + w = POP(); + v = TOP(); + x = PyNumber_Rshift(v, w); + Py_DECREF(v); + Py_DECREF(w); + SET_TOP(x); + if (x != NULL) DISPATCH(); + break; + + TARGET(BINARY_AND) + w = POP(); + v = TOP(); + x = PyNumber_And(v, w); + Py_DECREF(v); + Py_DECREF(w); + SET_TOP(x); + if (x != NULL) DISPATCH(); + break; + + TARGET(BINARY_XOR) + w = POP(); + v = TOP(); + x = PyNumber_Xor(v, w); + Py_DECREF(v); + Py_DECREF(w); + SET_TOP(x); + if (x != NULL) DISPATCH(); + break; + + TARGET(BINARY_OR) + w = POP(); + v = TOP(); + x = PyNumber_Or(v, w); + Py_DECREF(v); + Py_DECREF(w); + SET_TOP(x); + if (x != NULL) DISPATCH(); + break; + + TARGET(LIST_APPEND) + w = POP(); + v = PEEK(oparg); + err = PyList_Append(v, w); + Py_DECREF(w); + if (err == 0) { + PREDICT(JUMP_ABSOLUTE); + DISPATCH(); + } + break; + + TARGET(SET_ADD) + w = POP(); + v = stack_pointer[-oparg]; + err = PySet_Add(v, w); + Py_DECREF(w); + if (err == 0) { + PREDICT(JUMP_ABSOLUTE); + DISPATCH(); + } + break; + + TARGET(INPLACE_POWER) + w = POP(); + v = TOP(); + x = PyNumber_InPlacePower(v, w, Py_None); + Py_DECREF(v); + Py_DECREF(w); + SET_TOP(x); + if (x != NULL) DISPATCH(); + break; + + TARGET(INPLACE_MULTIPLY) + w = POP(); + v = TOP(); + x = PyNumber_InPlaceMultiply(v, w); + Py_DECREF(v); + Py_DECREF(w); + SET_TOP(x); + if (x != NULL) DISPATCH(); + break; + + TARGET(INPLACE_TRUE_DIVIDE) + w = POP(); + v = TOP(); + x = PyNumber_InPlaceTrueDivide(v, w); + Py_DECREF(v); + Py_DECREF(w); + SET_TOP(x); + if (x != NULL) DISPATCH(); + break; + + TARGET(INPLACE_FLOOR_DIVIDE) + w = POP(); + v = TOP(); + x = PyNumber_InPlaceFloorDivide(v, w); + Py_DECREF(v); + Py_DECREF(w); + SET_TOP(x); + if (x != NULL) DISPATCH(); + break; + + TARGET(INPLACE_MODULO) + w = POP(); + v = TOP(); + x = PyNumber_InPlaceRemainder(v, w); + Py_DECREF(v); + Py_DECREF(w); + SET_TOP(x); + if (x != NULL) DISPATCH(); + break; + + TARGET(INPLACE_ADD) + w = POP(); + v = TOP(); + if (PyUnicode_CheckExact(v) && + PyUnicode_CheckExact(w)) { + x = unicode_concatenate(v, w, f, next_instr); + /* unicode_concatenate consumed the ref to v */ + goto skip_decref_v; + } + else { + x = PyNumber_InPlaceAdd(v, w); + } + Py_DECREF(v); + skip_decref_v: + Py_DECREF(w); + SET_TOP(x); + if (x != NULL) DISPATCH(); + break; + + TARGET(INPLACE_SUBTRACT) + w = POP(); + v = TOP(); + x = PyNumber_InPlaceSubtract(v, w); + Py_DECREF(v); + Py_DECREF(w); + SET_TOP(x); + if (x != NULL) DISPATCH(); + break; + + TARGET(INPLACE_LSHIFT) + w = POP(); + v = TOP(); + x = PyNumber_InPlaceLshift(v, w); + Py_DECREF(v); + Py_DECREF(w); + SET_TOP(x); + if (x != NULL) DISPATCH(); + break; + + TARGET(INPLACE_RSHIFT) + w = POP(); + v = TOP(); + x = PyNumber_InPlaceRshift(v, w); + Py_DECREF(v); + Py_DECREF(w); + SET_TOP(x); + if (x != NULL) DISPATCH(); + break; + + TARGET(INPLACE_AND) + w = POP(); + v = TOP(); + x = PyNumber_InPlaceAnd(v, w); + Py_DECREF(v); + Py_DECREF(w); + SET_TOP(x); + if (x != NULL) DISPATCH(); + break; + + TARGET(INPLACE_XOR) + w = POP(); + v = TOP(); + x = PyNumber_InPlaceXor(v, w); + Py_DECREF(v); + Py_DECREF(w); + SET_TOP(x); + if (x != NULL) DISPATCH(); + break; + + TARGET(INPLACE_OR) + w = POP(); + v = TOP(); + x = PyNumber_InPlaceOr(v, w); + Py_DECREF(v); + Py_DECREF(w); + SET_TOP(x); + if (x != NULL) DISPATCH(); + break; + + TARGET(STORE_SUBSCR) + w = TOP(); + v = SECOND(); + u = THIRD(); + STACKADJ(-3); + /* v[w] = u */ + err = PyObject_SetItem(v, w, u); + Py_DECREF(u); + Py_DECREF(v); + Py_DECREF(w); + if (err == 0) DISPATCH(); + break; + + TARGET(DELETE_SUBSCR) + w = TOP(); + v = SECOND(); + STACKADJ(-2); + /* del v[w] */ + err = PyObject_DelItem(v, w); + Py_DECREF(v); + Py_DECREF(w); + if (err == 0) DISPATCH(); + break; + + TARGET(PRINT_EXPR) + v = POP(); + w = PySys_GetObject("displayhook"); + if (w == NULL) { + PyErr_SetString(PyExc_RuntimeError, + "lost sys.displayhook"); + err = -1; + x = NULL; + } + if (err == 0) { + x = PyTuple_Pack(1, v); + if (x == NULL) + err = -1; + } + if (err == 0) { + w = PyEval_CallObject(w, x); + Py_XDECREF(w); + if (w == NULL) + err = -1; + } + Py_DECREF(v); + Py_XDECREF(x); + break; #ifdef CASE_TOO_BIG - default: switch (opcode) { + default: switch (opcode) { #endif - TARGET(RAISE_VARARGS) - v = w = NULL; - switch (oparg) { - case 2: - v = POP(); /* cause */ - case 1: - w = POP(); /* exc */ - case 0: /* Fallthrough */ - why = do_raise(w, v); - break; - default: - PyErr_SetString(PyExc_SystemError, - "bad RAISE_VARARGS oparg"); - why = WHY_EXCEPTION; - break; - } - break; - - TARGET(STORE_LOCALS) - x = POP(); - v = f->f_locals; - Py_XDECREF(v); - f->f_locals = x; - DISPATCH(); - - TARGET(RETURN_VALUE) - retval = POP(); - why = WHY_RETURN; - goto fast_block_end; - - TARGET(YIELD_VALUE) - retval = POP(); - f->f_stacktop = stack_pointer; - why = WHY_YIELD; - /* Put aside the current exception state and restore - that of the calling frame. This only serves when - "yield" is used inside an except handler. */ - SWAP_EXC_STATE(); - goto fast_yield; - - TARGET(POP_EXCEPT) - { - PyTryBlock *b = PyFrame_BlockPop(f); - if (b->b_type != EXCEPT_HANDLER) { - PyErr_SetString(PyExc_SystemError, - "popped block is not an except handler"); - why = WHY_EXCEPTION; - break; - } - UNWIND_EXCEPT_HANDLER(b); - } - DISPATCH(); - - TARGET(POP_BLOCK) - { - PyTryBlock *b = PyFrame_BlockPop(f); - UNWIND_BLOCK(b); - } - DISPATCH(); - - PREDICTED(END_FINALLY); - TARGET(END_FINALLY) - v = POP(); - if (PyLong_Check(v)) { - why = (enum why_code) PyLong_AS_LONG(v); - assert(why != WHY_YIELD); - if (why == WHY_RETURN || - why == WHY_CONTINUE) - retval = POP(); - if (why == WHY_SILENCED) { - /* An exception was silenced by 'with', we must - manually unwind the EXCEPT_HANDLER block which was - created when the exception was caught, otherwise - the stack will be in an inconsistent state. */ - PyTryBlock *b = PyFrame_BlockPop(f); - assert(b->b_type == EXCEPT_HANDLER); - UNWIND_EXCEPT_HANDLER(b); - why = WHY_NOT; - } - } - else if (PyExceptionClass_Check(v)) { - w = POP(); - u = POP(); - PyErr_Restore(v, w, u); - why = WHY_RERAISE; - break; - } - else if (v != Py_None) { - PyErr_SetString(PyExc_SystemError, - "'finally' pops bad exception"); - why = WHY_EXCEPTION; - } - Py_DECREF(v); - break; - - TARGET(LOAD_BUILD_CLASS) - x = PyDict_GetItemString(f->f_builtins, - "__build_class__"); - if (x == NULL) { - PyErr_SetString(PyExc_ImportError, - "__build_class__ not found"); - break; - } - Py_INCREF(x); - PUSH(x); - break; - - TARGET(STORE_NAME) - w = GETITEM(names, oparg); - v = POP(); - if ((x = f->f_locals) != NULL) { - if (PyDict_CheckExact(x)) - err = PyDict_SetItem(x, w, v); - else - err = PyObject_SetItem(x, w, v); - Py_DECREF(v); - if (err == 0) DISPATCH(); - break; - } - PyErr_Format(PyExc_SystemError, - "no locals found when storing %R", w); - break; - - TARGET(DELETE_NAME) - w = GETITEM(names, oparg); - if ((x = f->f_locals) != NULL) { - if ((err = PyObject_DelItem(x, w)) != 0) - format_exc_check_arg(PyExc_NameError, - NAME_ERROR_MSG, - w); - break; - } - PyErr_Format(PyExc_SystemError, - "no locals when deleting %R", w); - break; - - PREDICTED_WITH_ARG(UNPACK_SEQUENCE); - TARGET(UNPACK_SEQUENCE) - v = POP(); - if (PyTuple_CheckExact(v) && - PyTuple_GET_SIZE(v) == oparg) { - PyObject **items = \ - ((PyTupleObject *)v)->ob_item; - while (oparg--) { - w = items[oparg]; - Py_INCREF(w); - PUSH(w); - } - Py_DECREF(v); - DISPATCH(); - } else if (PyList_CheckExact(v) && - PyList_GET_SIZE(v) == oparg) { - PyObject **items = \ - ((PyListObject *)v)->ob_item; - while (oparg--) { - w = items[oparg]; - Py_INCREF(w); - PUSH(w); - } - } else if (unpack_iterable(v, oparg, -1, - stack_pointer + oparg)) { - STACKADJ(oparg); - } else { - /* unpack_iterable() raised an exception */ - why = WHY_EXCEPTION; - } - Py_DECREF(v); - break; - - TARGET(UNPACK_EX) - { - int totalargs = 1 + (oparg & 0xFF) + (oparg >> 8); - v = POP(); - - if (unpack_iterable(v, oparg & 0xFF, oparg >> 8, - stack_pointer + totalargs)) { - stack_pointer += totalargs; - } else { - why = WHY_EXCEPTION; - } - Py_DECREF(v); - break; - } - - TARGET(STORE_ATTR) - w = GETITEM(names, oparg); - v = TOP(); - u = SECOND(); - STACKADJ(-2); - err = PyObject_SetAttr(v, w, u); /* v.w = u */ - Py_DECREF(v); - Py_DECREF(u); - if (err == 0) DISPATCH(); - break; - - TARGET(DELETE_ATTR) - w = GETITEM(names, oparg); - v = POP(); - err = PyObject_SetAttr(v, w, (PyObject *)NULL); - /* del v.w */ - Py_DECREF(v); - break; - - TARGET(STORE_GLOBAL) - w = GETITEM(names, oparg); - v = POP(); - err = PyDict_SetItem(f->f_globals, w, v); - Py_DECREF(v); - if (err == 0) DISPATCH(); - break; - - TARGET(DELETE_GLOBAL) - w = GETITEM(names, oparg); - if ((err = PyDict_DelItem(f->f_globals, w)) != 0) - format_exc_check_arg( - PyExc_NameError, GLOBAL_NAME_ERROR_MSG, w); - break; - - TARGET(LOAD_NAME) - w = GETITEM(names, oparg); - if ((v = f->f_locals) == NULL) { - PyErr_Format(PyExc_SystemError, - "no locals when loading %R", w); - why = WHY_EXCEPTION; - break; - } - if (PyDict_CheckExact(v)) { - x = PyDict_GetItem(v, w); - Py_XINCREF(x); - } - else { - x = PyObject_GetItem(v, w); - if (x == NULL && PyErr_Occurred()) { - if (!PyErr_ExceptionMatches( - PyExc_KeyError)) - break; - PyErr_Clear(); - } - } - if (x == NULL) { - x = PyDict_GetItem(f->f_globals, w); - if (x == NULL) { - x = PyDict_GetItem(f->f_builtins, w); - if (x == NULL) { - format_exc_check_arg( - PyExc_NameError, - NAME_ERROR_MSG, w); - break; - } - } - Py_INCREF(x); - } - PUSH(x); - DISPATCH(); - - TARGET(LOAD_GLOBAL) - w = GETITEM(names, oparg); - if (PyUnicode_CheckExact(w)) { - /* Inline the PyDict_GetItem() calls. - WARNING: this is an extreme speed hack. - Do not try this at home. */ - long hash = ((PyUnicodeObject *)w)->hash; - if (hash != -1) { - PyDictObject *d; - PyDictEntry *e; - d = (PyDictObject *)(f->f_globals); - e = d->ma_lookup(d, w, hash); - if (e == NULL) { - x = NULL; - break; - } - x = e->me_value; - if (x != NULL) { - Py_INCREF(x); - PUSH(x); - DISPATCH(); - } - d = (PyDictObject *)(f->f_builtins); - e = d->ma_lookup(d, w, hash); - if (e == NULL) { - x = NULL; - break; - } - x = e->me_value; - if (x != NULL) { - Py_INCREF(x); - PUSH(x); - DISPATCH(); - } - goto load_global_error; - } - } - /* This is the un-inlined version of the code above */ - x = PyDict_GetItem(f->f_globals, w); - if (x == NULL) { - x = PyDict_GetItem(f->f_builtins, w); - if (x == NULL) { - load_global_error: - format_exc_check_arg( - PyExc_NameError, - GLOBAL_NAME_ERROR_MSG, w); - break; - } - } - Py_INCREF(x); - PUSH(x); - DISPATCH(); - - TARGET(DELETE_FAST) - x = GETLOCAL(oparg); - if (x != NULL) { - SETLOCAL(oparg, NULL); - DISPATCH(); - } - format_exc_check_arg( - PyExc_UnboundLocalError, - UNBOUNDLOCAL_ERROR_MSG, - PyTuple_GetItem(co->co_varnames, oparg) - ); - break; - - TARGET(LOAD_CLOSURE) - x = freevars[oparg]; - Py_INCREF(x); - PUSH(x); - if (x != NULL) DISPATCH(); - break; - - TARGET(LOAD_DEREF) - x = freevars[oparg]; - w = PyCell_Get(x); - if (w != NULL) { - PUSH(w); - DISPATCH(); - } - err = -1; - /* Don't stomp existing exception */ - if (PyErr_Occurred()) - break; - if (oparg < PyTuple_GET_SIZE(co->co_cellvars)) { - v = PyTuple_GET_ITEM(co->co_cellvars, - oparg); - format_exc_check_arg( - PyExc_UnboundLocalError, - UNBOUNDLOCAL_ERROR_MSG, - v); - } else { - v = PyTuple_GET_ITEM(co->co_freevars, oparg - - PyTuple_GET_SIZE(co->co_cellvars)); - format_exc_check_arg(PyExc_NameError, - UNBOUNDFREE_ERROR_MSG, v); - } - break; - - TARGET(STORE_DEREF) - w = POP(); - x = freevars[oparg]; - PyCell_Set(x, w); - Py_DECREF(w); - DISPATCH(); - - TARGET(BUILD_TUPLE) - x = PyTuple_New(oparg); - if (x != NULL) { - for (; --oparg >= 0;) { - w = POP(); - PyTuple_SET_ITEM(x, oparg, w); - } - PUSH(x); - DISPATCH(); - } - break; - - TARGET(BUILD_LIST) - x = PyList_New(oparg); - if (x != NULL) { - for (; --oparg >= 0;) { - w = POP(); - PyList_SET_ITEM(x, oparg, w); - } - PUSH(x); - DISPATCH(); - } - break; - - TARGET(BUILD_SET) - x = PySet_New(NULL); - if (x != NULL) { - for (; --oparg >= 0;) { - w = POP(); - if (err == 0) - err = PySet_Add(x, w); - Py_DECREF(w); - } - if (err != 0) { - Py_DECREF(x); - break; - } - PUSH(x); - DISPATCH(); - } - break; - - TARGET(BUILD_MAP) - x = _PyDict_NewPresized((Py_ssize_t)oparg); - PUSH(x); - if (x != NULL) DISPATCH(); - break; - - TARGET(STORE_MAP) - w = TOP(); /* key */ - u = SECOND(); /* value */ - v = THIRD(); /* dict */ - STACKADJ(-2); - assert (PyDict_CheckExact(v)); - err = PyDict_SetItem(v, w, u); /* v[w] = u */ - Py_DECREF(u); - Py_DECREF(w); - if (err == 0) DISPATCH(); - break; - - TARGET(MAP_ADD) - w = TOP(); /* key */ - u = SECOND(); /* value */ - STACKADJ(-2); - v = stack_pointer[-oparg]; /* dict */ - assert (PyDict_CheckExact(v)); - err = PyDict_SetItem(v, w, u); /* v[w] = u */ - Py_DECREF(u); - Py_DECREF(w); - if (err == 0) { - PREDICT(JUMP_ABSOLUTE); - DISPATCH(); - } - break; - - TARGET(LOAD_ATTR) - w = GETITEM(names, oparg); - v = TOP(); - x = PyObject_GetAttr(v, w); - Py_DECREF(v); - SET_TOP(x); - if (x != NULL) DISPATCH(); - break; - - TARGET(COMPARE_OP) - w = POP(); - v = TOP(); - x = cmp_outcome(oparg, v, w); - Py_DECREF(v); - Py_DECREF(w); - SET_TOP(x); - if (x == NULL) break; - PREDICT(POP_JUMP_IF_FALSE); - PREDICT(POP_JUMP_IF_TRUE); - DISPATCH(); - - TARGET(IMPORT_NAME) - w = GETITEM(names, oparg); - x = PyDict_GetItemString(f->f_builtins, "__import__"); - if (x == NULL) { - PyErr_SetString(PyExc_ImportError, - "__import__ not found"); - break; - } - Py_INCREF(x); - v = POP(); - u = TOP(); - if (PyLong_AsLong(u) != -1 || PyErr_Occurred()) - w = PyTuple_Pack(5, - w, - f->f_globals, - f->f_locals == NULL ? - Py_None : f->f_locals, - v, - u); - else - w = PyTuple_Pack(4, - w, - f->f_globals, - f->f_locals == NULL ? - Py_None : f->f_locals, - v); - Py_DECREF(v); - Py_DECREF(u); - if (w == NULL) { - u = POP(); - Py_DECREF(x); - x = NULL; - break; - } - READ_TIMESTAMP(intr0); - v = x; - x = PyEval_CallObject(v, w); - Py_DECREF(v); - READ_TIMESTAMP(intr1); - Py_DECREF(w); - SET_TOP(x); - if (x != NULL) DISPATCH(); - break; - - TARGET(IMPORT_STAR) - v = POP(); - PyFrame_FastToLocals(f); - if ((x = f->f_locals) == NULL) { - PyErr_SetString(PyExc_SystemError, - "no locals found during 'import *'"); - break; - } - READ_TIMESTAMP(intr0); - err = import_all_from(x, v); - READ_TIMESTAMP(intr1); - PyFrame_LocalsToFast(f, 0); - Py_DECREF(v); - if (err == 0) DISPATCH(); - break; - - TARGET(IMPORT_FROM) - w = GETITEM(names, oparg); - v = TOP(); - READ_TIMESTAMP(intr0); - x = import_from(v, w); - READ_TIMESTAMP(intr1); - PUSH(x); - if (x != NULL) DISPATCH(); - break; - - TARGET(JUMP_FORWARD) - JUMPBY(oparg); - FAST_DISPATCH(); - - PREDICTED_WITH_ARG(POP_JUMP_IF_FALSE); - TARGET(POP_JUMP_IF_FALSE) - w = POP(); - if (w == Py_True) { - Py_DECREF(w); - FAST_DISPATCH(); - } - if (w == Py_False) { - Py_DECREF(w); - JUMPTO(oparg); - FAST_DISPATCH(); - } - err = PyObject_IsTrue(w); - Py_DECREF(w); - if (err > 0) - err = 0; - else if (err == 0) - JUMPTO(oparg); - else - break; - DISPATCH(); - - PREDICTED_WITH_ARG(POP_JUMP_IF_TRUE); - TARGET(POP_JUMP_IF_TRUE) - w = POP(); - if (w == Py_False) { - Py_DECREF(w); - FAST_DISPATCH(); - } - if (w == Py_True) { - Py_DECREF(w); - JUMPTO(oparg); - FAST_DISPATCH(); - } - err = PyObject_IsTrue(w); - Py_DECREF(w); - if (err > 0) { - err = 0; - JUMPTO(oparg); - } - else if (err == 0) - ; - else - break; - DISPATCH(); - - TARGET(JUMP_IF_FALSE_OR_POP) - w = TOP(); - if (w == Py_True) { - STACKADJ(-1); - Py_DECREF(w); - FAST_DISPATCH(); - } - if (w == Py_False) { - JUMPTO(oparg); - FAST_DISPATCH(); - } - err = PyObject_IsTrue(w); - if (err > 0) { - STACKADJ(-1); - Py_DECREF(w); - err = 0; - } - else if (err == 0) - JUMPTO(oparg); - else - break; - DISPATCH(); - - TARGET(JUMP_IF_TRUE_OR_POP) - w = TOP(); - if (w == Py_False) { - STACKADJ(-1); - Py_DECREF(w); - FAST_DISPATCH(); - } - if (w == Py_True) { - JUMPTO(oparg); - FAST_DISPATCH(); - } - err = PyObject_IsTrue(w); - if (err > 0) { - err = 0; - JUMPTO(oparg); - } - else if (err == 0) { - STACKADJ(-1); - Py_DECREF(w); - } - else - break; - DISPATCH(); - - PREDICTED_WITH_ARG(JUMP_ABSOLUTE); - TARGET(JUMP_ABSOLUTE) - JUMPTO(oparg); + TARGET(RAISE_VARARGS) + v = w = NULL; + switch (oparg) { + case 2: + v = POP(); /* cause */ + case 1: + w = POP(); /* exc */ + case 0: /* Fallthrough */ + why = do_raise(w, v); + break; + default: + PyErr_SetString(PyExc_SystemError, + "bad RAISE_VARARGS oparg"); + why = WHY_EXCEPTION; + break; + } + break; + + TARGET(STORE_LOCALS) + x = POP(); + v = f->f_locals; + Py_XDECREF(v); + f->f_locals = x; + DISPATCH(); + + TARGET(RETURN_VALUE) + retval = POP(); + why = WHY_RETURN; + goto fast_block_end; + + TARGET(YIELD_VALUE) + retval = POP(); + f->f_stacktop = stack_pointer; + why = WHY_YIELD; + /* Put aside the current exception state and restore + that of the calling frame. This only serves when + "yield" is used inside an except handler. */ + SWAP_EXC_STATE(); + goto fast_yield; + + TARGET(POP_EXCEPT) + { + PyTryBlock *b = PyFrame_BlockPop(f); + if (b->b_type != EXCEPT_HANDLER) { + PyErr_SetString(PyExc_SystemError, + "popped block is not an except handler"); + why = WHY_EXCEPTION; + break; + } + UNWIND_EXCEPT_HANDLER(b); + } + DISPATCH(); + + TARGET(POP_BLOCK) + { + PyTryBlock *b = PyFrame_BlockPop(f); + UNWIND_BLOCK(b); + } + DISPATCH(); + + PREDICTED(END_FINALLY); + TARGET(END_FINALLY) + v = POP(); + if (PyLong_Check(v)) { + why = (enum why_code) PyLong_AS_LONG(v); + assert(why != WHY_YIELD); + if (why == WHY_RETURN || + why == WHY_CONTINUE) + retval = POP(); + if (why == WHY_SILENCED) { + /* An exception was silenced by 'with', we must + manually unwind the EXCEPT_HANDLER block which was + created when the exception was caught, otherwise + the stack will be in an inconsistent state. */ + PyTryBlock *b = PyFrame_BlockPop(f); + assert(b->b_type == EXCEPT_HANDLER); + UNWIND_EXCEPT_HANDLER(b); + why = WHY_NOT; + } + } + else if (PyExceptionClass_Check(v)) { + w = POP(); + u = POP(); + PyErr_Restore(v, w, u); + why = WHY_RERAISE; + break; + } + else if (v != Py_None) { + PyErr_SetString(PyExc_SystemError, + "'finally' pops bad exception"); + why = WHY_EXCEPTION; + } + Py_DECREF(v); + break; + + TARGET(LOAD_BUILD_CLASS) + x = PyDict_GetItemString(f->f_builtins, + "__build_class__"); + if (x == NULL) { + PyErr_SetString(PyExc_ImportError, + "__build_class__ not found"); + break; + } + Py_INCREF(x); + PUSH(x); + break; + + TARGET(STORE_NAME) + w = GETITEM(names, oparg); + v = POP(); + if ((x = f->f_locals) != NULL) { + if (PyDict_CheckExact(x)) + err = PyDict_SetItem(x, w, v); + else + err = PyObject_SetItem(x, w, v); + Py_DECREF(v); + if (err == 0) DISPATCH(); + break; + } + PyErr_Format(PyExc_SystemError, + "no locals found when storing %R", w); + break; + + TARGET(DELETE_NAME) + w = GETITEM(names, oparg); + if ((x = f->f_locals) != NULL) { + if ((err = PyObject_DelItem(x, w)) != 0) + format_exc_check_arg(PyExc_NameError, + NAME_ERROR_MSG, + w); + break; + } + PyErr_Format(PyExc_SystemError, + "no locals when deleting %R", w); + break; + + PREDICTED_WITH_ARG(UNPACK_SEQUENCE); + TARGET(UNPACK_SEQUENCE) + v = POP(); + if (PyTuple_CheckExact(v) && + PyTuple_GET_SIZE(v) == oparg) { + PyObject **items = \ + ((PyTupleObject *)v)->ob_item; + while (oparg--) { + w = items[oparg]; + Py_INCREF(w); + PUSH(w); + } + Py_DECREF(v); + DISPATCH(); + } else if (PyList_CheckExact(v) && + PyList_GET_SIZE(v) == oparg) { + PyObject **items = \ + ((PyListObject *)v)->ob_item; + while (oparg--) { + w = items[oparg]; + Py_INCREF(w); + PUSH(w); + } + } else if (unpack_iterable(v, oparg, -1, + stack_pointer + oparg)) { + STACKADJ(oparg); + } else { + /* unpack_iterable() raised an exception */ + why = WHY_EXCEPTION; + } + Py_DECREF(v); + break; + + TARGET(UNPACK_EX) + { + int totalargs = 1 + (oparg & 0xFF) + (oparg >> 8); + v = POP(); + + if (unpack_iterable(v, oparg & 0xFF, oparg >> 8, + stack_pointer + totalargs)) { + stack_pointer += totalargs; + } else { + why = WHY_EXCEPTION; + } + Py_DECREF(v); + break; + } + + TARGET(STORE_ATTR) + w = GETITEM(names, oparg); + v = TOP(); + u = SECOND(); + STACKADJ(-2); + err = PyObject_SetAttr(v, w, u); /* v.w = u */ + Py_DECREF(v); + Py_DECREF(u); + if (err == 0) DISPATCH(); + break; + + TARGET(DELETE_ATTR) + w = GETITEM(names, oparg); + v = POP(); + err = PyObject_SetAttr(v, w, (PyObject *)NULL); + /* del v.w */ + Py_DECREF(v); + break; + + TARGET(STORE_GLOBAL) + w = GETITEM(names, oparg); + v = POP(); + err = PyDict_SetItem(f->f_globals, w, v); + Py_DECREF(v); + if (err == 0) DISPATCH(); + break; + + TARGET(DELETE_GLOBAL) + w = GETITEM(names, oparg); + if ((err = PyDict_DelItem(f->f_globals, w)) != 0) + format_exc_check_arg( + PyExc_NameError, GLOBAL_NAME_ERROR_MSG, w); + break; + + TARGET(LOAD_NAME) + w = GETITEM(names, oparg); + if ((v = f->f_locals) == NULL) { + PyErr_Format(PyExc_SystemError, + "no locals when loading %R", w); + why = WHY_EXCEPTION; + break; + } + if (PyDict_CheckExact(v)) { + x = PyDict_GetItem(v, w); + Py_XINCREF(x); + } + else { + x = PyObject_GetItem(v, w); + if (x == NULL && PyErr_Occurred()) { + if (!PyErr_ExceptionMatches( + PyExc_KeyError)) + break; + PyErr_Clear(); + } + } + if (x == NULL) { + x = PyDict_GetItem(f->f_globals, w); + if (x == NULL) { + x = PyDict_GetItem(f->f_builtins, w); + if (x == NULL) { + format_exc_check_arg( + PyExc_NameError, + NAME_ERROR_MSG, w); + break; + } + } + Py_INCREF(x); + } + PUSH(x); + DISPATCH(); + + TARGET(LOAD_GLOBAL) + w = GETITEM(names, oparg); + if (PyUnicode_CheckExact(w)) { + /* Inline the PyDict_GetItem() calls. + WARNING: this is an extreme speed hack. + Do not try this at home. */ + long hash = ((PyUnicodeObject *)w)->hash; + if (hash != -1) { + PyDictObject *d; + PyDictEntry *e; + d = (PyDictObject *)(f->f_globals); + e = d->ma_lookup(d, w, hash); + if (e == NULL) { + x = NULL; + break; + } + x = e->me_value; + if (x != NULL) { + Py_INCREF(x); + PUSH(x); + DISPATCH(); + } + d = (PyDictObject *)(f->f_builtins); + e = d->ma_lookup(d, w, hash); + if (e == NULL) { + x = NULL; + break; + } + x = e->me_value; + if (x != NULL) { + Py_INCREF(x); + PUSH(x); + DISPATCH(); + } + goto load_global_error; + } + } + /* This is the un-inlined version of the code above */ + x = PyDict_GetItem(f->f_globals, w); + if (x == NULL) { + x = PyDict_GetItem(f->f_builtins, w); + if (x == NULL) { + load_global_error: + format_exc_check_arg( + PyExc_NameError, + GLOBAL_NAME_ERROR_MSG, w); + break; + } + } + Py_INCREF(x); + PUSH(x); + DISPATCH(); + + TARGET(DELETE_FAST) + x = GETLOCAL(oparg); + if (x != NULL) { + SETLOCAL(oparg, NULL); + DISPATCH(); + } + format_exc_check_arg( + PyExc_UnboundLocalError, + UNBOUNDLOCAL_ERROR_MSG, + PyTuple_GetItem(co->co_varnames, oparg) + ); + break; + + TARGET(LOAD_CLOSURE) + x = freevars[oparg]; + Py_INCREF(x); + PUSH(x); + if (x != NULL) DISPATCH(); + break; + + TARGET(LOAD_DEREF) + x = freevars[oparg]; + w = PyCell_Get(x); + if (w != NULL) { + PUSH(w); + DISPATCH(); + } + err = -1; + /* Don't stomp existing exception */ + if (PyErr_Occurred()) + break; + if (oparg < PyTuple_GET_SIZE(co->co_cellvars)) { + v = PyTuple_GET_ITEM(co->co_cellvars, + oparg); + format_exc_check_arg( + PyExc_UnboundLocalError, + UNBOUNDLOCAL_ERROR_MSG, + v); + } else { + v = PyTuple_GET_ITEM(co->co_freevars, oparg - + PyTuple_GET_SIZE(co->co_cellvars)); + format_exc_check_arg(PyExc_NameError, + UNBOUNDFREE_ERROR_MSG, v); + } + break; + + TARGET(STORE_DEREF) + w = POP(); + x = freevars[oparg]; + PyCell_Set(x, w); + Py_DECREF(w); + DISPATCH(); + + TARGET(BUILD_TUPLE) + x = PyTuple_New(oparg); + if (x != NULL) { + for (; --oparg >= 0;) { + w = POP(); + PyTuple_SET_ITEM(x, oparg, w); + } + PUSH(x); + DISPATCH(); + } + break; + + TARGET(BUILD_LIST) + x = PyList_New(oparg); + if (x != NULL) { + for (; --oparg >= 0;) { + w = POP(); + PyList_SET_ITEM(x, oparg, w); + } + PUSH(x); + DISPATCH(); + } + break; + + TARGET(BUILD_SET) + x = PySet_New(NULL); + if (x != NULL) { + for (; --oparg >= 0;) { + w = POP(); + if (err == 0) + err = PySet_Add(x, w); + Py_DECREF(w); + } + if (err != 0) { + Py_DECREF(x); + break; + } + PUSH(x); + DISPATCH(); + } + break; + + TARGET(BUILD_MAP) + x = _PyDict_NewPresized((Py_ssize_t)oparg); + PUSH(x); + if (x != NULL) DISPATCH(); + break; + + TARGET(STORE_MAP) + w = TOP(); /* key */ + u = SECOND(); /* value */ + v = THIRD(); /* dict */ + STACKADJ(-2); + assert (PyDict_CheckExact(v)); + err = PyDict_SetItem(v, w, u); /* v[w] = u */ + Py_DECREF(u); + Py_DECREF(w); + if (err == 0) DISPATCH(); + break; + + TARGET(MAP_ADD) + w = TOP(); /* key */ + u = SECOND(); /* value */ + STACKADJ(-2); + v = stack_pointer[-oparg]; /* dict */ + assert (PyDict_CheckExact(v)); + err = PyDict_SetItem(v, w, u); /* v[w] = u */ + Py_DECREF(u); + Py_DECREF(w); + if (err == 0) { + PREDICT(JUMP_ABSOLUTE); + DISPATCH(); + } + break; + + TARGET(LOAD_ATTR) + w = GETITEM(names, oparg); + v = TOP(); + x = PyObject_GetAttr(v, w); + Py_DECREF(v); + SET_TOP(x); + if (x != NULL) DISPATCH(); + break; + + TARGET(COMPARE_OP) + w = POP(); + v = TOP(); + x = cmp_outcome(oparg, v, w); + Py_DECREF(v); + Py_DECREF(w); + SET_TOP(x); + if (x == NULL) break; + PREDICT(POP_JUMP_IF_FALSE); + PREDICT(POP_JUMP_IF_TRUE); + DISPATCH(); + + TARGET(IMPORT_NAME) + w = GETITEM(names, oparg); + x = PyDict_GetItemString(f->f_builtins, "__import__"); + if (x == NULL) { + PyErr_SetString(PyExc_ImportError, + "__import__ not found"); + break; + } + Py_INCREF(x); + v = POP(); + u = TOP(); + if (PyLong_AsLong(u) != -1 || PyErr_Occurred()) + w = PyTuple_Pack(5, + w, + f->f_globals, + f->f_locals == NULL ? + Py_None : f->f_locals, + v, + u); + else + w = PyTuple_Pack(4, + w, + f->f_globals, + f->f_locals == NULL ? + Py_None : f->f_locals, + v); + Py_DECREF(v); + Py_DECREF(u); + if (w == NULL) { + u = POP(); + Py_DECREF(x); + x = NULL; + break; + } + READ_TIMESTAMP(intr0); + v = x; + x = PyEval_CallObject(v, w); + Py_DECREF(v); + READ_TIMESTAMP(intr1); + Py_DECREF(w); + SET_TOP(x); + if (x != NULL) DISPATCH(); + break; + + TARGET(IMPORT_STAR) + v = POP(); + PyFrame_FastToLocals(f); + if ((x = f->f_locals) == NULL) { + PyErr_SetString(PyExc_SystemError, + "no locals found during 'import *'"); + break; + } + READ_TIMESTAMP(intr0); + err = import_all_from(x, v); + READ_TIMESTAMP(intr1); + PyFrame_LocalsToFast(f, 0); + Py_DECREF(v); + if (err == 0) DISPATCH(); + break; + + TARGET(IMPORT_FROM) + w = GETITEM(names, oparg); + v = TOP(); + READ_TIMESTAMP(intr0); + x = import_from(v, w); + READ_TIMESTAMP(intr1); + PUSH(x); + if (x != NULL) DISPATCH(); + break; + + TARGET(JUMP_FORWARD) + JUMPBY(oparg); + FAST_DISPATCH(); + + PREDICTED_WITH_ARG(POP_JUMP_IF_FALSE); + TARGET(POP_JUMP_IF_FALSE) + w = POP(); + if (w == Py_True) { + Py_DECREF(w); + FAST_DISPATCH(); + } + if (w == Py_False) { + Py_DECREF(w); + JUMPTO(oparg); + FAST_DISPATCH(); + } + err = PyObject_IsTrue(w); + Py_DECREF(w); + if (err > 0) + err = 0; + else if (err == 0) + JUMPTO(oparg); + else + break; + DISPATCH(); + + PREDICTED_WITH_ARG(POP_JUMP_IF_TRUE); + TARGET(POP_JUMP_IF_TRUE) + w = POP(); + if (w == Py_False) { + Py_DECREF(w); + FAST_DISPATCH(); + } + if (w == Py_True) { + Py_DECREF(w); + JUMPTO(oparg); + FAST_DISPATCH(); + } + err = PyObject_IsTrue(w); + Py_DECREF(w); + if (err > 0) { + err = 0; + JUMPTO(oparg); + } + else if (err == 0) + ; + else + break; + DISPATCH(); + + TARGET(JUMP_IF_FALSE_OR_POP) + w = TOP(); + if (w == Py_True) { + STACKADJ(-1); + Py_DECREF(w); + FAST_DISPATCH(); + } + if (w == Py_False) { + JUMPTO(oparg); + FAST_DISPATCH(); + } + err = PyObject_IsTrue(w); + if (err > 0) { + STACKADJ(-1); + Py_DECREF(w); + err = 0; + } + else if (err == 0) + JUMPTO(oparg); + else + break; + DISPATCH(); + + TARGET(JUMP_IF_TRUE_OR_POP) + w = TOP(); + if (w == Py_False) { + STACKADJ(-1); + Py_DECREF(w); + FAST_DISPATCH(); + } + if (w == Py_True) { + JUMPTO(oparg); + FAST_DISPATCH(); + } + err = PyObject_IsTrue(w); + if (err > 0) { + err = 0; + JUMPTO(oparg); + } + else if (err == 0) { + STACKADJ(-1); + Py_DECREF(w); + } + else + break; + DISPATCH(); + + PREDICTED_WITH_ARG(JUMP_ABSOLUTE); + TARGET(JUMP_ABSOLUTE) + JUMPTO(oparg); #if FAST_LOOPS - /* Enabling this path speeds-up all while and for-loops by bypassing - the per-loop checks for signals. By default, this should be turned-off - because it prevents detection of a control-break in tight loops like - "while 1: pass". Compile with this option turned-on when you need - the speed-up and do not need break checking inside tight loops (ones - that contain only instructions ending with FAST_DISPATCH). - */ - FAST_DISPATCH(); + /* Enabling this path speeds-up all while and for-loops by bypassing + the per-loop checks for signals. By default, this should be turned-off + because it prevents detection of a control-break in tight loops like + "while 1: pass". Compile with this option turned-on when you need + the speed-up and do not need break checking inside tight loops (ones + that contain only instructions ending with FAST_DISPATCH). + */ + FAST_DISPATCH(); #else - DISPATCH(); + DISPATCH(); #endif - TARGET(GET_ITER) - /* before: [obj]; after [getiter(obj)] */ - v = TOP(); - x = PyObject_GetIter(v); - Py_DECREF(v); - if (x != NULL) { - SET_TOP(x); - PREDICT(FOR_ITER); - DISPATCH(); - } - STACKADJ(-1); - break; - - PREDICTED_WITH_ARG(FOR_ITER); - TARGET(FOR_ITER) - /* before: [iter]; after: [iter, iter()] *or* [] */ - v = TOP(); - x = (*v->ob_type->tp_iternext)(v); - if (x != NULL) { - PUSH(x); - PREDICT(STORE_FAST); - PREDICT(UNPACK_SEQUENCE); - DISPATCH(); - } - if (PyErr_Occurred()) { - if (!PyErr_ExceptionMatches( - PyExc_StopIteration)) - break; - PyErr_Clear(); - } - /* iterator ended normally */ - x = v = POP(); - Py_DECREF(v); - JUMPBY(oparg); - DISPATCH(); - - TARGET(BREAK_LOOP) - why = WHY_BREAK; - goto fast_block_end; - - TARGET(CONTINUE_LOOP) - retval = PyLong_FromLong(oparg); - if (!retval) { - x = NULL; - break; - } - why = WHY_CONTINUE; - goto fast_block_end; - - TARGET_WITH_IMPL(SETUP_LOOP, _setup_finally) - TARGET_WITH_IMPL(SETUP_EXCEPT, _setup_finally) - TARGET(SETUP_FINALLY) - _setup_finally: - /* NOTE: If you add any new block-setup opcodes that - are not try/except/finally handlers, you may need - to update the PyGen_NeedsFinalizing() function. - */ - - PyFrame_BlockSetup(f, opcode, INSTR_OFFSET() + oparg, - STACK_LEVEL()); - DISPATCH(); - - TARGET(SETUP_WITH) - { - static PyObject *exit, *enter; - w = TOP(); - x = special_lookup(w, "__exit__", &exit); - if (!x) - break; - SET_TOP(x); - u = special_lookup(w, "__enter__", &enter); - Py_DECREF(w); - if (!u) { - x = NULL; - break; - } - x = PyObject_CallFunctionObjArgs(u, NULL); - Py_DECREF(u); - if (!x) - break; - /* Setup the finally block before pushing the result - of __enter__ on the stack. */ - PyFrame_BlockSetup(f, SETUP_FINALLY, INSTR_OFFSET() + oparg, - STACK_LEVEL()); - - PUSH(x); - DISPATCH(); - } - - TARGET(WITH_CLEANUP) - { - /* At the top of the stack are 1-3 values indicating - how/why we entered the finally clause: - - TOP = None - - (TOP, SECOND) = (WHY_{RETURN,CONTINUE}), retval - - TOP = WHY_*; no retval below it - - (TOP, SECOND, THIRD) = exc_info() - (FOURTH, FITH, SIXTH) = previous exception for EXCEPT_HANDLER - Below them is EXIT, the context.__exit__ bound method. - In the last case, we must call - EXIT(TOP, SECOND, THIRD) - otherwise we must call - EXIT(None, None, None) - - In the first two cases, we remove EXIT from the - stack, leaving the rest in the same order. In the - third case, we shift the bottom 3 values of the - stack down, and replace the empty spot with NULL. - - In addition, if the stack represents an exception, - *and* the function call returns a 'true' value, we - push WHY_SILENCED onto the stack. END_FINALLY will - then not re-raise the exception. (But non-local - gotos should still be resumed.) - */ - - PyObject *exit_func; - u = TOP(); - if (u == Py_None) { - (void)POP(); - exit_func = TOP(); - SET_TOP(u); - v = w = Py_None; - } - else if (PyLong_Check(u)) { - (void)POP(); - switch(PyLong_AsLong(u)) { - case WHY_RETURN: - case WHY_CONTINUE: - /* Retval in TOP. */ - exit_func = SECOND(); - SET_SECOND(TOP()); - SET_TOP(u); - break; - default: - exit_func = TOP(); - SET_TOP(u); - break; - } - u = v = w = Py_None; - } - else { - PyObject *tp, *exc, *tb; - PyTryBlock *block; - v = SECOND(); - w = THIRD(); - tp = FOURTH(); - exc = PEEK(5); - tb = PEEK(6); - exit_func = PEEK(7); - SET_VALUE(7, tb); - SET_VALUE(6, exc); - SET_VALUE(5, tp); - /* UNWIND_EXCEPT_HANDLER will pop this off. */ - SET_FOURTH(NULL); - /* We just shifted the stack down, so we have - to tell the except handler block that the - values are lower than it expects. */ - block = &f->f_blockstack[f->f_iblock - 1]; - assert(block->b_type == EXCEPT_HANDLER); - block->b_level--; - } - /* XXX Not the fastest way to call it... */ - x = PyObject_CallFunctionObjArgs(exit_func, u, v, w, - NULL); - Py_DECREF(exit_func); - if (x == NULL) - break; /* Go to error exit */ - - if (u != Py_None) - err = PyObject_IsTrue(x); - else - err = 0; - Py_DECREF(x); - - if (err < 0) - break; /* Go to error exit */ - else if (err > 0) { - err = 0; - /* There was an exception and a True return */ - PUSH(PyLong_FromLong((long) WHY_SILENCED)); - } - PREDICT(END_FINALLY); - break; - } - - TARGET(CALL_FUNCTION) - { - PyObject **sp; - PCALL(PCALL_ALL); - sp = stack_pointer; + TARGET(GET_ITER) + /* before: [obj]; after [getiter(obj)] */ + v = TOP(); + x = PyObject_GetIter(v); + Py_DECREF(v); + if (x != NULL) { + SET_TOP(x); + PREDICT(FOR_ITER); + DISPATCH(); + } + STACKADJ(-1); + break; + + PREDICTED_WITH_ARG(FOR_ITER); + TARGET(FOR_ITER) + /* before: [iter]; after: [iter, iter()] *or* [] */ + v = TOP(); + x = (*v->ob_type->tp_iternext)(v); + if (x != NULL) { + PUSH(x); + PREDICT(STORE_FAST); + PREDICT(UNPACK_SEQUENCE); + DISPATCH(); + } + if (PyErr_Occurred()) { + if (!PyErr_ExceptionMatches( + PyExc_StopIteration)) + break; + PyErr_Clear(); + } + /* iterator ended normally */ + x = v = POP(); + Py_DECREF(v); + JUMPBY(oparg); + DISPATCH(); + + TARGET(BREAK_LOOP) + why = WHY_BREAK; + goto fast_block_end; + + TARGET(CONTINUE_LOOP) + retval = PyLong_FromLong(oparg); + if (!retval) { + x = NULL; + break; + } + why = WHY_CONTINUE; + goto fast_block_end; + + TARGET_WITH_IMPL(SETUP_LOOP, _setup_finally) + TARGET_WITH_IMPL(SETUP_EXCEPT, _setup_finally) + TARGET(SETUP_FINALLY) + _setup_finally: + /* NOTE: If you add any new block-setup opcodes that + are not try/except/finally handlers, you may need + to update the PyGen_NeedsFinalizing() function. + */ + + PyFrame_BlockSetup(f, opcode, INSTR_OFFSET() + oparg, + STACK_LEVEL()); + DISPATCH(); + + TARGET(SETUP_WITH) + { + static PyObject *exit, *enter; + w = TOP(); + x = special_lookup(w, "__exit__", &exit); + if (!x) + break; + SET_TOP(x); + u = special_lookup(w, "__enter__", &enter); + Py_DECREF(w); + if (!u) { + x = NULL; + break; + } + x = PyObject_CallFunctionObjArgs(u, NULL); + Py_DECREF(u); + if (!x) + break; + /* Setup the finally block before pushing the result + of __enter__ on the stack. */ + PyFrame_BlockSetup(f, SETUP_FINALLY, INSTR_OFFSET() + oparg, + STACK_LEVEL()); + + PUSH(x); + DISPATCH(); + } + + TARGET(WITH_CLEANUP) + { + /* At the top of the stack are 1-3 values indicating + how/why we entered the finally clause: + - TOP = None + - (TOP, SECOND) = (WHY_{RETURN,CONTINUE}), retval + - TOP = WHY_*; no retval below it + - (TOP, SECOND, THIRD) = exc_info() + (FOURTH, FITH, SIXTH) = previous exception for EXCEPT_HANDLER + Below them is EXIT, the context.__exit__ bound method. + In the last case, we must call + EXIT(TOP, SECOND, THIRD) + otherwise we must call + EXIT(None, None, None) + + In the first two cases, we remove EXIT from the + stack, leaving the rest in the same order. In the + third case, we shift the bottom 3 values of the + stack down, and replace the empty spot with NULL. + + In addition, if the stack represents an exception, + *and* the function call returns a 'true' value, we + push WHY_SILENCED onto the stack. END_FINALLY will + then not re-raise the exception. (But non-local + gotos should still be resumed.) + */ + + PyObject *exit_func; + u = TOP(); + if (u == Py_None) { + (void)POP(); + exit_func = TOP(); + SET_TOP(u); + v = w = Py_None; + } + else if (PyLong_Check(u)) { + (void)POP(); + switch(PyLong_AsLong(u)) { + case WHY_RETURN: + case WHY_CONTINUE: + /* Retval in TOP. */ + exit_func = SECOND(); + SET_SECOND(TOP()); + SET_TOP(u); + break; + default: + exit_func = TOP(); + SET_TOP(u); + break; + } + u = v = w = Py_None; + } + else { + PyObject *tp, *exc, *tb; + PyTryBlock *block; + v = SECOND(); + w = THIRD(); + tp = FOURTH(); + exc = PEEK(5); + tb = PEEK(6); + exit_func = PEEK(7); + SET_VALUE(7, tb); + SET_VALUE(6, exc); + SET_VALUE(5, tp); + /* UNWIND_EXCEPT_HANDLER will pop this off. */ + SET_FOURTH(NULL); + /* We just shifted the stack down, so we have + to tell the except handler block that the + values are lower than it expects. */ + block = &f->f_blockstack[f->f_iblock - 1]; + assert(block->b_type == EXCEPT_HANDLER); + block->b_level--; + } + /* XXX Not the fastest way to call it... */ + x = PyObject_CallFunctionObjArgs(exit_func, u, v, w, + NULL); + Py_DECREF(exit_func); + if (x == NULL) + break; /* Go to error exit */ + + if (u != Py_None) + err = PyObject_IsTrue(x); + else + err = 0; + Py_DECREF(x); + + if (err < 0) + break; /* Go to error exit */ + else if (err > 0) { + err = 0; + /* There was an exception and a True return */ + PUSH(PyLong_FromLong((long) WHY_SILENCED)); + } + PREDICT(END_FINALLY); + break; + } + + TARGET(CALL_FUNCTION) + { + PyObject **sp; + PCALL(PCALL_ALL); + sp = stack_pointer; #ifdef WITH_TSC - x = call_function(&sp, oparg, &intr0, &intr1); + x = call_function(&sp, oparg, &intr0, &intr1); #else - x = call_function(&sp, oparg); + x = call_function(&sp, oparg); #endif - stack_pointer = sp; - PUSH(x); - if (x != NULL) - DISPATCH(); - break; - } - - TARGET_WITH_IMPL(CALL_FUNCTION_VAR, _call_function_var_kw) - TARGET_WITH_IMPL(CALL_FUNCTION_KW, _call_function_var_kw) - TARGET(CALL_FUNCTION_VAR_KW) - _call_function_var_kw: - { - int na = oparg & 0xff; - int nk = (oparg>>8) & 0xff; - int flags = (opcode - CALL_FUNCTION) & 3; - int n = na + 2 * nk; - PyObject **pfunc, *func, **sp; - PCALL(PCALL_ALL); - if (flags & CALL_FLAG_VAR) - n++; - if (flags & CALL_FLAG_KW) - n++; - pfunc = stack_pointer - n - 1; - func = *pfunc; - - if (PyMethod_Check(func) - && PyMethod_GET_SELF(func) != NULL) { - PyObject *self = PyMethod_GET_SELF(func); - Py_INCREF(self); - func = PyMethod_GET_FUNCTION(func); - Py_INCREF(func); - Py_DECREF(*pfunc); - *pfunc = self; - na++; - n++; - } else - Py_INCREF(func); - sp = stack_pointer; - READ_TIMESTAMP(intr0); - x = ext_do_call(func, &sp, flags, na, nk); - READ_TIMESTAMP(intr1); - stack_pointer = sp; - Py_DECREF(func); - - while (stack_pointer > pfunc) { - w = POP(); - Py_DECREF(w); - } - PUSH(x); - if (x != NULL) - DISPATCH(); - break; - } - - TARGET_WITH_IMPL(MAKE_CLOSURE, _make_function) - TARGET(MAKE_FUNCTION) - _make_function: - { - int posdefaults = oparg & 0xff; - int kwdefaults = (oparg>>8) & 0xff; - int num_annotations = (oparg >> 16) & 0x7fff; - - v = POP(); /* code object */ - x = PyFunction_New(v, f->f_globals); - Py_DECREF(v); - - if (x != NULL && opcode == MAKE_CLOSURE) { - v = POP(); - if (PyFunction_SetClosure(x, v) != 0) { - /* Can't happen unless bytecode is corrupt. */ - why = WHY_EXCEPTION; - } - Py_DECREF(v); - } - - if (x != NULL && num_annotations > 0) { - Py_ssize_t name_ix; - u = POP(); /* names of args with annotations */ - v = PyDict_New(); - if (v == NULL) { - Py_DECREF(x); - x = NULL; - break; - } - name_ix = PyTuple_Size(u); - assert(num_annotations == name_ix+1); - while (name_ix > 0) { - --name_ix; - t = PyTuple_GET_ITEM(u, name_ix); - w = POP(); - /* XXX(nnorwitz): check for errors */ - PyDict_SetItem(v, t, w); - Py_DECREF(w); - } - - if (PyFunction_SetAnnotations(x, v) != 0) { - /* Can't happen unless - PyFunction_SetAnnotations changes. */ - why = WHY_EXCEPTION; - } - Py_DECREF(v); - Py_DECREF(u); - } - - /* XXX Maybe this should be a separate opcode? */ - if (x != NULL && posdefaults > 0) { - v = PyTuple_New(posdefaults); - if (v == NULL) { - Py_DECREF(x); - x = NULL; - break; - } - while (--posdefaults >= 0) { - w = POP(); - PyTuple_SET_ITEM(v, posdefaults, w); - } - if (PyFunction_SetDefaults(x, v) != 0) { - /* Can't happen unless - PyFunction_SetDefaults changes. */ - why = WHY_EXCEPTION; - } - Py_DECREF(v); - } - if (x != NULL && kwdefaults > 0) { - v = PyDict_New(); - if (v == NULL) { - Py_DECREF(x); - x = NULL; - break; - } - while (--kwdefaults >= 0) { - w = POP(); /* default value */ - u = POP(); /* kw only arg name */ - /* XXX(nnorwitz): check for errors */ - PyDict_SetItem(v, u, w); - Py_DECREF(w); - Py_DECREF(u); - } - if (PyFunction_SetKwDefaults(x, v) != 0) { - /* Can't happen unless - PyFunction_SetKwDefaults changes. */ - why = WHY_EXCEPTION; - } - Py_DECREF(v); - } - PUSH(x); - break; - } - - TARGET(BUILD_SLICE) - if (oparg == 3) - w = POP(); - else - w = NULL; - v = POP(); - u = TOP(); - x = PySlice_New(u, v, w); - Py_DECREF(u); - Py_DECREF(v); - Py_XDECREF(w); - SET_TOP(x); - if (x != NULL) DISPATCH(); - break; - - TARGET(EXTENDED_ARG) - opcode = NEXTOP(); - oparg = oparg<<16 | NEXTARG(); - goto dispatch_opcode; + stack_pointer = sp; + PUSH(x); + if (x != NULL) + DISPATCH(); + break; + } + + TARGET_WITH_IMPL(CALL_FUNCTION_VAR, _call_function_var_kw) + TARGET_WITH_IMPL(CALL_FUNCTION_KW, _call_function_var_kw) + TARGET(CALL_FUNCTION_VAR_KW) + _call_function_var_kw: + { + int na = oparg & 0xff; + int nk = (oparg>>8) & 0xff; + int flags = (opcode - CALL_FUNCTION) & 3; + int n = na + 2 * nk; + PyObject **pfunc, *func, **sp; + PCALL(PCALL_ALL); + if (flags & CALL_FLAG_VAR) + n++; + if (flags & CALL_FLAG_KW) + n++; + pfunc = stack_pointer - n - 1; + func = *pfunc; + + if (PyMethod_Check(func) + && PyMethod_GET_SELF(func) != NULL) { + PyObject *self = PyMethod_GET_SELF(func); + Py_INCREF(self); + func = PyMethod_GET_FUNCTION(func); + Py_INCREF(func); + Py_DECREF(*pfunc); + *pfunc = self; + na++; + n++; + } else + Py_INCREF(func); + sp = stack_pointer; + READ_TIMESTAMP(intr0); + x = ext_do_call(func, &sp, flags, na, nk); + READ_TIMESTAMP(intr1); + stack_pointer = sp; + Py_DECREF(func); + + while (stack_pointer > pfunc) { + w = POP(); + Py_DECREF(w); + } + PUSH(x); + if (x != NULL) + DISPATCH(); + break; + } + + TARGET_WITH_IMPL(MAKE_CLOSURE, _make_function) + TARGET(MAKE_FUNCTION) + _make_function: + { + int posdefaults = oparg & 0xff; + int kwdefaults = (oparg>>8) & 0xff; + int num_annotations = (oparg >> 16) & 0x7fff; + + v = POP(); /* code object */ + x = PyFunction_New(v, f->f_globals); + Py_DECREF(v); + + if (x != NULL && opcode == MAKE_CLOSURE) { + v = POP(); + if (PyFunction_SetClosure(x, v) != 0) { + /* Can't happen unless bytecode is corrupt. */ + why = WHY_EXCEPTION; + } + Py_DECREF(v); + } + + if (x != NULL && num_annotations > 0) { + Py_ssize_t name_ix; + u = POP(); /* names of args with annotations */ + v = PyDict_New(); + if (v == NULL) { + Py_DECREF(x); + x = NULL; + break; + } + name_ix = PyTuple_Size(u); + assert(num_annotations == name_ix+1); + while (name_ix > 0) { + --name_ix; + t = PyTuple_GET_ITEM(u, name_ix); + w = POP(); + /* XXX(nnorwitz): check for errors */ + PyDict_SetItem(v, t, w); + Py_DECREF(w); + } + + if (PyFunction_SetAnnotations(x, v) != 0) { + /* Can't happen unless + PyFunction_SetAnnotations changes. */ + why = WHY_EXCEPTION; + } + Py_DECREF(v); + Py_DECREF(u); + } + + /* XXX Maybe this should be a separate opcode? */ + if (x != NULL && posdefaults > 0) { + v = PyTuple_New(posdefaults); + if (v == NULL) { + Py_DECREF(x); + x = NULL; + break; + } + while (--posdefaults >= 0) { + w = POP(); + PyTuple_SET_ITEM(v, posdefaults, w); + } + if (PyFunction_SetDefaults(x, v) != 0) { + /* Can't happen unless + PyFunction_SetDefaults changes. */ + why = WHY_EXCEPTION; + } + Py_DECREF(v); + } + if (x != NULL && kwdefaults > 0) { + v = PyDict_New(); + if (v == NULL) { + Py_DECREF(x); + x = NULL; + break; + } + while (--kwdefaults >= 0) { + w = POP(); /* default value */ + u = POP(); /* kw only arg name */ + /* XXX(nnorwitz): check for errors */ + PyDict_SetItem(v, u, w); + Py_DECREF(w); + Py_DECREF(u); + } + if (PyFunction_SetKwDefaults(x, v) != 0) { + /* Can't happen unless + PyFunction_SetKwDefaults changes. */ + why = WHY_EXCEPTION; + } + Py_DECREF(v); + } + PUSH(x); + break; + } + + TARGET(BUILD_SLICE) + if (oparg == 3) + w = POP(); + else + w = NULL; + v = POP(); + u = TOP(); + x = PySlice_New(u, v, w); + Py_DECREF(u); + Py_DECREF(v); + Py_XDECREF(w); + SET_TOP(x); + if (x != NULL) DISPATCH(); + break; + + TARGET(EXTENDED_ARG) + opcode = NEXTOP(); + oparg = oparg<<16 | NEXTARG(); + goto dispatch_opcode; #ifdef USE_COMPUTED_GOTOS - _unknown_opcode: + _unknown_opcode: #endif - default: - fprintf(stderr, - "XXX lineno: %d, opcode: %d\n", - PyFrame_GetLineNumber(f), - opcode); - PyErr_SetString(PyExc_SystemError, "unknown opcode"); - why = WHY_EXCEPTION; - break; + default: + fprintf(stderr, + "XXX lineno: %d, opcode: %d\n", + PyFrame_GetLineNumber(f), + opcode); + PyErr_SetString(PyExc_SystemError, "unknown opcode"); + why = WHY_EXCEPTION; + break; #ifdef CASE_TOO_BIG - } + } #endif - } /* switch */ + } /* switch */ - on_error: + on_error: - READ_TIMESTAMP(inst1); + READ_TIMESTAMP(inst1); - /* Quickly continue if no error occurred */ + /* Quickly continue if no error occurred */ - if (why == WHY_NOT) { - if (err == 0 && x != NULL) { + if (why == WHY_NOT) { + if (err == 0 && x != NULL) { #ifdef CHECKEXC - /* This check is expensive! */ - if (PyErr_Occurred()) - fprintf(stderr, - "XXX undetected error\n"); - else { + /* This check is expensive! */ + if (PyErr_Occurred()) + fprintf(stderr, + "XXX undetected error\n"); + else { #endif - READ_TIMESTAMP(loop1); - continue; /* Normal, fast path */ + READ_TIMESTAMP(loop1); + continue; /* Normal, fast path */ #ifdef CHECKEXC - } + } #endif - } - why = WHY_EXCEPTION; - x = Py_None; - err = 0; - } - - /* Double-check exception status */ - - if (why == WHY_EXCEPTION || why == WHY_RERAISE) { - if (!PyErr_Occurred()) { - PyErr_SetString(PyExc_SystemError, - "error return without exception set"); - why = WHY_EXCEPTION; - } - } + } + why = WHY_EXCEPTION; + x = Py_None; + err = 0; + } + + /* Double-check exception status */ + + if (why == WHY_EXCEPTION || why == WHY_RERAISE) { + if (!PyErr_Occurred()) { + PyErr_SetString(PyExc_SystemError, + "error return without exception set"); + why = WHY_EXCEPTION; + } + } #ifdef CHECKEXC - else { - /* This check is expensive! */ - if (PyErr_Occurred()) { - char buf[128]; - sprintf(buf, "Stack unwind with exception " - "set and why=%d", why); - Py_FatalError(buf); - } - } + else { + /* This check is expensive! */ + if (PyErr_Occurred()) { + char buf[128]; + sprintf(buf, "Stack unwind with exception " + "set and why=%d", why); + Py_FatalError(buf); + } + } #endif - /* Log traceback info if this is a real exception */ + /* Log traceback info if this is a real exception */ - if (why == WHY_EXCEPTION) { - PyTraceBack_Here(f); + if (why == WHY_EXCEPTION) { + PyTraceBack_Here(f); - if (tstate->c_tracefunc != NULL) - call_exc_trace(tstate->c_tracefunc, - tstate->c_traceobj, f); - } + if (tstate->c_tracefunc != NULL) + call_exc_trace(tstate->c_tracefunc, + tstate->c_traceobj, f); + } - /* For the rest, treat WHY_RERAISE as WHY_EXCEPTION */ + /* For the rest, treat WHY_RERAISE as WHY_EXCEPTION */ - if (why == WHY_RERAISE) - why = WHY_EXCEPTION; + if (why == WHY_RERAISE) + why = WHY_EXCEPTION; - /* Unwind stacks if a (pseudo) exception occurred */ + /* Unwind stacks if a (pseudo) exception occurred */ fast_block_end: - while (why != WHY_NOT && f->f_iblock > 0) { - /* Peek at the current block. */ - PyTryBlock *b = &f->f_blockstack[f->f_iblock - 1]; - - assert(why != WHY_YIELD); - if (b->b_type == SETUP_LOOP && why == WHY_CONTINUE) { - why = WHY_NOT; - JUMPTO(PyLong_AS_LONG(retval)); - Py_DECREF(retval); - break; - } - /* Now we have to pop the block. */ - f->f_iblock--; - - if (b->b_type == EXCEPT_HANDLER) { - UNWIND_EXCEPT_HANDLER(b); - continue; - } - UNWIND_BLOCK(b); - if (b->b_type == SETUP_LOOP && why == WHY_BREAK) { - why = WHY_NOT; - JUMPTO(b->b_handler); - break; - } - if (why == WHY_EXCEPTION && (b->b_type == SETUP_EXCEPT - || b->b_type == SETUP_FINALLY)) { - PyObject *exc, *val, *tb; - int handler = b->b_handler; - /* Beware, this invalidates all b->b_* fields */ - PyFrame_BlockSetup(f, EXCEPT_HANDLER, -1, STACK_LEVEL()); - PUSH(tstate->exc_traceback); - PUSH(tstate->exc_value); - if (tstate->exc_type != NULL) { - PUSH(tstate->exc_type); - } - else { - Py_INCREF(Py_None); - PUSH(Py_None); - } - PyErr_Fetch(&exc, &val, &tb); - /* Make the raw exception data - available to the handler, - so a program can emulate the - Python main loop. */ - PyErr_NormalizeException( - &exc, &val, &tb); - PyException_SetTraceback(val, tb); - Py_INCREF(exc); - tstate->exc_type = exc; - Py_INCREF(val); - tstate->exc_value = val; - tstate->exc_traceback = tb; - if (tb == NULL) - tb = Py_None; - Py_INCREF(tb); - PUSH(tb); - PUSH(val); - PUSH(exc); - why = WHY_NOT; - JUMPTO(handler); - break; - } - if (b->b_type == SETUP_FINALLY) { - if (why & (WHY_RETURN | WHY_CONTINUE)) - PUSH(retval); - PUSH(PyLong_FromLong((long)why)); - why = WHY_NOT; - JUMPTO(b->b_handler); - break; - } - } /* unwind stack */ - - /* End the loop if we still have an error (or return) */ - - if (why != WHY_NOT) - break; - READ_TIMESTAMP(loop1); - - } /* main loop */ - - assert(why != WHY_YIELD); - /* Pop remaining stack entries. */ - while (!EMPTY()) { - v = POP(); - Py_XDECREF(v); - } + while (why != WHY_NOT && f->f_iblock > 0) { + /* Peek at the current block. */ + PyTryBlock *b = &f->f_blockstack[f->f_iblock - 1]; + + assert(why != WHY_YIELD); + if (b->b_type == SETUP_LOOP && why == WHY_CONTINUE) { + why = WHY_NOT; + JUMPTO(PyLong_AS_LONG(retval)); + Py_DECREF(retval); + break; + } + /* Now we have to pop the block. */ + f->f_iblock--; + + if (b->b_type == EXCEPT_HANDLER) { + UNWIND_EXCEPT_HANDLER(b); + continue; + } + UNWIND_BLOCK(b); + if (b->b_type == SETUP_LOOP && why == WHY_BREAK) { + why = WHY_NOT; + JUMPTO(b->b_handler); + break; + } + if (why == WHY_EXCEPTION && (b->b_type == SETUP_EXCEPT + || b->b_type == SETUP_FINALLY)) { + PyObject *exc, *val, *tb; + int handler = b->b_handler; + /* Beware, this invalidates all b->b_* fields */ + PyFrame_BlockSetup(f, EXCEPT_HANDLER, -1, STACK_LEVEL()); + PUSH(tstate->exc_traceback); + PUSH(tstate->exc_value); + if (tstate->exc_type != NULL) { + PUSH(tstate->exc_type); + } + else { + Py_INCREF(Py_None); + PUSH(Py_None); + } + PyErr_Fetch(&exc, &val, &tb); + /* Make the raw exception data + available to the handler, + so a program can emulate the + Python main loop. */ + PyErr_NormalizeException( + &exc, &val, &tb); + PyException_SetTraceback(val, tb); + Py_INCREF(exc); + tstate->exc_type = exc; + Py_INCREF(val); + tstate->exc_value = val; + tstate->exc_traceback = tb; + if (tb == NULL) + tb = Py_None; + Py_INCREF(tb); + PUSH(tb); + PUSH(val); + PUSH(exc); + why = WHY_NOT; + JUMPTO(handler); + break; + } + if (b->b_type == SETUP_FINALLY) { + if (why & (WHY_RETURN | WHY_CONTINUE)) + PUSH(retval); + PUSH(PyLong_FromLong((long)why)); + why = WHY_NOT; + JUMPTO(b->b_handler); + break; + } + } /* unwind stack */ + + /* End the loop if we still have an error (or return) */ + + if (why != WHY_NOT) + break; + READ_TIMESTAMP(loop1); + + } /* main loop */ + + assert(why != WHY_YIELD); + /* Pop remaining stack entries. */ + while (!EMPTY()) { + v = POP(); + Py_XDECREF(v); + } - if (why != WHY_RETURN) - retval = NULL; + if (why != WHY_RETURN) + retval = NULL; fast_yield: - if (tstate->use_tracing) { - if (tstate->c_tracefunc) { - if (why == WHY_RETURN || why == WHY_YIELD) { - if (call_trace(tstate->c_tracefunc, - tstate->c_traceobj, f, - PyTrace_RETURN, retval)) { - Py_XDECREF(retval); - retval = NULL; - why = WHY_EXCEPTION; - } - } - else if (why == WHY_EXCEPTION) { - call_trace_protected(tstate->c_tracefunc, - tstate->c_traceobj, f, - PyTrace_RETURN, NULL); - } - } - if (tstate->c_profilefunc) { - if (why == WHY_EXCEPTION) - call_trace_protected(tstate->c_profilefunc, - tstate->c_profileobj, f, - PyTrace_RETURN, NULL); - else if (call_trace(tstate->c_profilefunc, - tstate->c_profileobj, f, - PyTrace_RETURN, retval)) { - Py_XDECREF(retval); - retval = NULL; - why = WHY_EXCEPTION; - } - } - } + if (tstate->use_tracing) { + if (tstate->c_tracefunc) { + if (why == WHY_RETURN || why == WHY_YIELD) { + if (call_trace(tstate->c_tracefunc, + tstate->c_traceobj, f, + PyTrace_RETURN, retval)) { + Py_XDECREF(retval); + retval = NULL; + why = WHY_EXCEPTION; + } + } + else if (why == WHY_EXCEPTION) { + call_trace_protected(tstate->c_tracefunc, + tstate->c_traceobj, f, + PyTrace_RETURN, NULL); + } + } + if (tstate->c_profilefunc) { + if (why == WHY_EXCEPTION) + call_trace_protected(tstate->c_profilefunc, + tstate->c_profileobj, f, + PyTrace_RETURN, NULL); + else if (call_trace(tstate->c_profilefunc, + tstate->c_profileobj, f, + PyTrace_RETURN, retval)) { + Py_XDECREF(retval); + retval = NULL; + why = WHY_EXCEPTION; + } + } + } - /* pop frame */ + /* pop frame */ exit_eval_frame: - Py_LeaveRecursiveCall(); - tstate->frame = f->f_back; + Py_LeaveRecursiveCall(); + tstate->frame = f->f_back; - return retval; + return retval; } /* This is gonna seem *real weird*, but if you put some other code between @@ -3058,279 +3058,279 @@ PyObject * PyEval_EvalCodeEx(PyCodeObject *co, PyObject *globals, PyObject *locals, - PyObject **args, int argcount, PyObject **kws, int kwcount, - PyObject **defs, int defcount, PyObject *kwdefs, PyObject *closure) + PyObject **args, int argcount, PyObject **kws, int kwcount, + PyObject **defs, int defcount, PyObject *kwdefs, PyObject *closure) { - register PyFrameObject *f; - register PyObject *retval = NULL; - register PyObject **fastlocals, **freevars; - PyThreadState *tstate = PyThreadState_GET(); - PyObject *x, *u; - int total_args = co->co_argcount + co->co_kwonlyargcount; - - if (globals == NULL) { - PyErr_SetString(PyExc_SystemError, - "PyEval_EvalCodeEx: NULL globals"); - return NULL; - } - - assert(tstate != NULL); - assert(globals != NULL); - f = PyFrame_New(tstate, co, globals, locals); - if (f == NULL) - return NULL; - - fastlocals = f->f_localsplus; - freevars = f->f_localsplus + co->co_nlocals; - - if (total_args || co->co_flags & (CO_VARARGS | CO_VARKEYWORDS)) { - int i; - int n = argcount; - PyObject *kwdict = NULL; - if (co->co_flags & CO_VARKEYWORDS) { - kwdict = PyDict_New(); - if (kwdict == NULL) - goto fail; - i = total_args; - if (co->co_flags & CO_VARARGS) - i++; - SETLOCAL(i, kwdict); - } - if (argcount > co->co_argcount) { - if (!(co->co_flags & CO_VARARGS)) { - PyErr_Format(PyExc_TypeError, - "%U() takes %s %d " - "argument%s (%d given)", - co->co_name, - defcount ? "at most" : "exactly", - total_args, - total_args == 1 ? "" : "s", - argcount + kwcount); - goto fail; - } - n = co->co_argcount; - } - for (i = 0; i < n; i++) { - x = args[i]; - Py_INCREF(x); - SETLOCAL(i, x); - } - if (co->co_flags & CO_VARARGS) { - u = PyTuple_New(argcount - n); - if (u == NULL) - goto fail; - SETLOCAL(total_args, u); - for (i = n; i < argcount; i++) { - x = args[i]; - Py_INCREF(x); - PyTuple_SET_ITEM(u, i-n, x); - } - } - for (i = 0; i < kwcount; i++) { - PyObject **co_varnames; - PyObject *keyword = kws[2*i]; - PyObject *value = kws[2*i + 1]; - int j; - if (keyword == NULL || !PyUnicode_Check(keyword)) { - PyErr_Format(PyExc_TypeError, - "%U() keywords must be strings", - co->co_name); - goto fail; - } - /* Speed hack: do raw pointer compares. As names are - normally interned this should almost always hit. */ - co_varnames = ((PyTupleObject *)(co->co_varnames))->ob_item; - for (j = 0; j < total_args; j++) { - PyObject *nm = co_varnames[j]; - if (nm == keyword) - goto kw_found; - } - /* Slow fallback, just in case */ - for (j = 0; j < total_args; j++) { - PyObject *nm = co_varnames[j]; - int cmp = PyObject_RichCompareBool( - keyword, nm, Py_EQ); - if (cmp > 0) - goto kw_found; - else if (cmp < 0) - goto fail; - } - if (j >= total_args && kwdict == NULL) { - PyErr_Format(PyExc_TypeError, - "%U() got an unexpected " - "keyword argument '%S'", - co->co_name, - keyword); - goto fail; - } - PyDict_SetItem(kwdict, keyword, value); - continue; - kw_found: - if (GETLOCAL(j) != NULL) { - PyErr_Format(PyExc_TypeError, - "%U() got multiple " - "values for keyword " - "argument '%S'", - co->co_name, - keyword); - goto fail; - } - Py_INCREF(value); - SETLOCAL(j, value); - } - if (co->co_kwonlyargcount > 0) { - for (i = co->co_argcount; i < total_args; i++) { - PyObject *name; - if (GETLOCAL(i) != NULL) - continue; - name = PyTuple_GET_ITEM(co->co_varnames, i); - if (kwdefs != NULL) { - PyObject *def = PyDict_GetItem(kwdefs, name); - if (def) { - Py_INCREF(def); - SETLOCAL(i, def); - continue; - } - } - PyErr_Format(PyExc_TypeError, - "%U() needs keyword-only argument %S", - co->co_name, name); - goto fail; - } - } - if (argcount < co->co_argcount) { - int m = co->co_argcount - defcount; - for (i = argcount; i < m; i++) { - if (GETLOCAL(i) == NULL) { - int j, given = 0; - for (j = 0; j < co->co_argcount; j++) - if (GETLOCAL(j)) - given++; - PyErr_Format(PyExc_TypeError, - "%U() takes %s %d " - "argument%s " - "(%d given)", - co->co_name, - ((co->co_flags & CO_VARARGS) || - defcount) ? "at least" - : "exactly", - m, m == 1 ? "" : "s", given); - goto fail; - } - } - if (n > m) - i = n - m; - else - i = 0; - for (; i < defcount; i++) { - if (GETLOCAL(m+i) == NULL) { - PyObject *def = defs[i]; - Py_INCREF(def); - SETLOCAL(m+i, def); - } - } - } - } - else if (argcount > 0 || kwcount > 0) { - PyErr_Format(PyExc_TypeError, - "%U() takes no arguments (%d given)", - co->co_name, - argcount + kwcount); - goto fail; - } - /* Allocate and initialize storage for cell vars, and copy free - vars into frame. This isn't too efficient right now. */ - if (PyTuple_GET_SIZE(co->co_cellvars)) { - int i, j, nargs, found; - Py_UNICODE *cellname, *argname; - PyObject *c; - - nargs = total_args; - if (co->co_flags & CO_VARARGS) - nargs++; - if (co->co_flags & CO_VARKEYWORDS) - nargs++; - - /* Initialize each cell var, taking into account - cell vars that are initialized from arguments. - - Should arrange for the compiler to put cellvars - that are arguments at the beginning of the cellvars - list so that we can march over it more efficiently? - */ - for (i = 0; i < PyTuple_GET_SIZE(co->co_cellvars); ++i) { - cellname = PyUnicode_AS_UNICODE( - PyTuple_GET_ITEM(co->co_cellvars, i)); - found = 0; - for (j = 0; j < nargs; j++) { - argname = PyUnicode_AS_UNICODE( - PyTuple_GET_ITEM(co->co_varnames, j)); - if (Py_UNICODE_strcmp(cellname, argname) == 0) { - c = PyCell_New(GETLOCAL(j)); - if (c == NULL) - goto fail; - GETLOCAL(co->co_nlocals + i) = c; - found = 1; - break; - } - } - if (found == 0) { - c = PyCell_New(NULL); - if (c == NULL) - goto fail; - SETLOCAL(co->co_nlocals + i, c); - } - } - } - if (PyTuple_GET_SIZE(co->co_freevars)) { - int i; - for (i = 0; i < PyTuple_GET_SIZE(co->co_freevars); ++i) { - PyObject *o = PyTuple_GET_ITEM(closure, i); - Py_INCREF(o); - freevars[PyTuple_GET_SIZE(co->co_cellvars) + i] = o; - } - } - - if (co->co_flags & CO_GENERATOR) { - /* Don't need to keep the reference to f_back, it will be set - * when the generator is resumed. */ - Py_XDECREF(f->f_back); - f->f_back = NULL; - - PCALL(PCALL_GENERATOR); - - /* Create a new generator that owns the ready to run frame - * and return that as the value. */ - return PyGen_New(f); - } + register PyFrameObject *f; + register PyObject *retval = NULL; + register PyObject **fastlocals, **freevars; + PyThreadState *tstate = PyThreadState_GET(); + PyObject *x, *u; + int total_args = co->co_argcount + co->co_kwonlyargcount; + + if (globals == NULL) { + PyErr_SetString(PyExc_SystemError, + "PyEval_EvalCodeEx: NULL globals"); + return NULL; + } + + assert(tstate != NULL); + assert(globals != NULL); + f = PyFrame_New(tstate, co, globals, locals); + if (f == NULL) + return NULL; + + fastlocals = f->f_localsplus; + freevars = f->f_localsplus + co->co_nlocals; + + if (total_args || co->co_flags & (CO_VARARGS | CO_VARKEYWORDS)) { + int i; + int n = argcount; + PyObject *kwdict = NULL; + if (co->co_flags & CO_VARKEYWORDS) { + kwdict = PyDict_New(); + if (kwdict == NULL) + goto fail; + i = total_args; + if (co->co_flags & CO_VARARGS) + i++; + SETLOCAL(i, kwdict); + } + if (argcount > co->co_argcount) { + if (!(co->co_flags & CO_VARARGS)) { + PyErr_Format(PyExc_TypeError, + "%U() takes %s %d " + "argument%s (%d given)", + co->co_name, + defcount ? "at most" : "exactly", + total_args, + total_args == 1 ? "" : "s", + argcount + kwcount); + goto fail; + } + n = co->co_argcount; + } + for (i = 0; i < n; i++) { + x = args[i]; + Py_INCREF(x); + SETLOCAL(i, x); + } + if (co->co_flags & CO_VARARGS) { + u = PyTuple_New(argcount - n); + if (u == NULL) + goto fail; + SETLOCAL(total_args, u); + for (i = n; i < argcount; i++) { + x = args[i]; + Py_INCREF(x); + PyTuple_SET_ITEM(u, i-n, x); + } + } + for (i = 0; i < kwcount; i++) { + PyObject **co_varnames; + PyObject *keyword = kws[2*i]; + PyObject *value = kws[2*i + 1]; + int j; + if (keyword == NULL || !PyUnicode_Check(keyword)) { + PyErr_Format(PyExc_TypeError, + "%U() keywords must be strings", + co->co_name); + goto fail; + } + /* Speed hack: do raw pointer compares. As names are + normally interned this should almost always hit. */ + co_varnames = ((PyTupleObject *)(co->co_varnames))->ob_item; + for (j = 0; j < total_args; j++) { + PyObject *nm = co_varnames[j]; + if (nm == keyword) + goto kw_found; + } + /* Slow fallback, just in case */ + for (j = 0; j < total_args; j++) { + PyObject *nm = co_varnames[j]; + int cmp = PyObject_RichCompareBool( + keyword, nm, Py_EQ); + if (cmp > 0) + goto kw_found; + else if (cmp < 0) + goto fail; + } + if (j >= total_args && kwdict == NULL) { + PyErr_Format(PyExc_TypeError, + "%U() got an unexpected " + "keyword argument '%S'", + co->co_name, + keyword); + goto fail; + } + PyDict_SetItem(kwdict, keyword, value); + continue; + kw_found: + if (GETLOCAL(j) != NULL) { + PyErr_Format(PyExc_TypeError, + "%U() got multiple " + "values for keyword " + "argument '%S'", + co->co_name, + keyword); + goto fail; + } + Py_INCREF(value); + SETLOCAL(j, value); + } + if (co->co_kwonlyargcount > 0) { + for (i = co->co_argcount; i < total_args; i++) { + PyObject *name; + if (GETLOCAL(i) != NULL) + continue; + name = PyTuple_GET_ITEM(co->co_varnames, i); + if (kwdefs != NULL) { + PyObject *def = PyDict_GetItem(kwdefs, name); + if (def) { + Py_INCREF(def); + SETLOCAL(i, def); + continue; + } + } + PyErr_Format(PyExc_TypeError, + "%U() needs keyword-only argument %S", + co->co_name, name); + goto fail; + } + } + if (argcount < co->co_argcount) { + int m = co->co_argcount - defcount; + for (i = argcount; i < m; i++) { + if (GETLOCAL(i) == NULL) { + int j, given = 0; + for (j = 0; j < co->co_argcount; j++) + if (GETLOCAL(j)) + given++; + PyErr_Format(PyExc_TypeError, + "%U() takes %s %d " + "argument%s " + "(%d given)", + co->co_name, + ((co->co_flags & CO_VARARGS) || + defcount) ? "at least" + : "exactly", + m, m == 1 ? "" : "s", given); + goto fail; + } + } + if (n > m) + i = n - m; + else + i = 0; + for (; i < defcount; i++) { + if (GETLOCAL(m+i) == NULL) { + PyObject *def = defs[i]; + Py_INCREF(def); + SETLOCAL(m+i, def); + } + } + } + } + else if (argcount > 0 || kwcount > 0) { + PyErr_Format(PyExc_TypeError, + "%U() takes no arguments (%d given)", + co->co_name, + argcount + kwcount); + goto fail; + } + /* Allocate and initialize storage for cell vars, and copy free + vars into frame. This isn't too efficient right now. */ + if (PyTuple_GET_SIZE(co->co_cellvars)) { + int i, j, nargs, found; + Py_UNICODE *cellname, *argname; + PyObject *c; + + nargs = total_args; + if (co->co_flags & CO_VARARGS) + nargs++; + if (co->co_flags & CO_VARKEYWORDS) + nargs++; + + /* Initialize each cell var, taking into account + cell vars that are initialized from arguments. + + Should arrange for the compiler to put cellvars + that are arguments at the beginning of the cellvars + list so that we can march over it more efficiently? + */ + for (i = 0; i < PyTuple_GET_SIZE(co->co_cellvars); ++i) { + cellname = PyUnicode_AS_UNICODE( + PyTuple_GET_ITEM(co->co_cellvars, i)); + found = 0; + for (j = 0; j < nargs; j++) { + argname = PyUnicode_AS_UNICODE( + PyTuple_GET_ITEM(co->co_varnames, j)); + if (Py_UNICODE_strcmp(cellname, argname) == 0) { + c = PyCell_New(GETLOCAL(j)); + if (c == NULL) + goto fail; + GETLOCAL(co->co_nlocals + i) = c; + found = 1; + break; + } + } + if (found == 0) { + c = PyCell_New(NULL); + if (c == NULL) + goto fail; + SETLOCAL(co->co_nlocals + i, c); + } + } + } + if (PyTuple_GET_SIZE(co->co_freevars)) { + int i; + for (i = 0; i < PyTuple_GET_SIZE(co->co_freevars); ++i) { + PyObject *o = PyTuple_GET_ITEM(closure, i); + Py_INCREF(o); + freevars[PyTuple_GET_SIZE(co->co_cellvars) + i] = o; + } + } + + if (co->co_flags & CO_GENERATOR) { + /* Don't need to keep the reference to f_back, it will be set + * when the generator is resumed. */ + Py_XDECREF(f->f_back); + f->f_back = NULL; + + PCALL(PCALL_GENERATOR); + + /* Create a new generator that owns the ready to run frame + * and return that as the value. */ + return PyGen_New(f); + } - retval = PyEval_EvalFrameEx(f,0); + retval = PyEval_EvalFrameEx(f,0); fail: /* Jump here from prelude on failure */ - /* decref'ing the frame can cause __del__ methods to get invoked, - which can call back into Python. While we're done with the - current Python frame (f), the associated C stack is still in use, - so recursion_depth must be boosted for the duration. - */ - assert(tstate != NULL); - ++tstate->recursion_depth; - Py_DECREF(f); - --tstate->recursion_depth; - return retval; + /* decref'ing the frame can cause __del__ methods to get invoked, + which can call back into Python. While we're done with the + current Python frame (f), the associated C stack is still in use, + so recursion_depth must be boosted for the duration. + */ + assert(tstate != NULL); + ++tstate->recursion_depth; + Py_DECREF(f); + --tstate->recursion_depth; + return retval; } static PyObject * special_lookup(PyObject *o, char *meth, PyObject **cache) { - PyObject *res; - res = _PyObject_LookupSpecial(o, meth, cache); - if (res == NULL && !PyErr_Occurred()) { - PyErr_SetObject(PyExc_AttributeError, *cache); - return NULL; - } - return res; + PyObject *res; + res = _PyObject_LookupSpecial(o, meth, cache); + if (res == NULL && !PyErr_Occurred()) { + PyErr_SetObject(PyExc_AttributeError, *cache); + return NULL; + } + return res; } @@ -3339,83 +3339,83 @@ static enum why_code do_raise(PyObject *exc, PyObject *cause) { - PyObject *type = NULL, *value = NULL; + PyObject *type = NULL, *value = NULL; - if (exc == NULL) { - /* Reraise */ - PyThreadState *tstate = PyThreadState_GET(); - PyObject *tb; - type = tstate->exc_type; - value = tstate->exc_value; - tb = tstate->exc_traceback; - if (type == Py_None) { - PyErr_SetString(PyExc_RuntimeError, - "No active exception to reraise"); - return WHY_EXCEPTION; - } - Py_XINCREF(type); - Py_XINCREF(value); - Py_XINCREF(tb); - PyErr_Restore(type, value, tb); - return WHY_RERAISE; - } + if (exc == NULL) { + /* Reraise */ + PyThreadState *tstate = PyThreadState_GET(); + PyObject *tb; + type = tstate->exc_type; + value = tstate->exc_value; + tb = tstate->exc_traceback; + if (type == Py_None) { + PyErr_SetString(PyExc_RuntimeError, + "No active exception to reraise"); + return WHY_EXCEPTION; + } + Py_XINCREF(type); + Py_XINCREF(value); + Py_XINCREF(tb); + PyErr_Restore(type, value, tb); + return WHY_RERAISE; + } - /* We support the following forms of raise: - raise + /* We support the following forms of raise: + raise raise raise */ - if (PyExceptionClass_Check(exc)) { - type = exc; - value = PyObject_CallObject(exc, NULL); - if (value == NULL) - goto raise_error; - } - else if (PyExceptionInstance_Check(exc)) { - value = exc; - type = PyExceptionInstance_Class(exc); - Py_INCREF(type); - } - else { - /* Not something you can raise. You get an exception - anyway, just not what you specified :-) */ - Py_DECREF(exc); - PyErr_SetString(PyExc_TypeError, - "exceptions must derive from BaseException"); - goto raise_error; - } - - if (cause) { - PyObject *fixed_cause; - if (PyExceptionClass_Check(cause)) { - fixed_cause = PyObject_CallObject(cause, NULL); - if (fixed_cause == NULL) - goto raise_error; - Py_DECREF(cause); - } - else if (PyExceptionInstance_Check(cause)) { - fixed_cause = cause; - } - else { - PyErr_SetString(PyExc_TypeError, - "exception causes must derive from " - "BaseException"); - goto raise_error; - } - PyException_SetCause(value, fixed_cause); - } - - PyErr_SetObject(type, value); - /* PyErr_SetObject incref's its arguments */ - Py_XDECREF(value); - Py_XDECREF(type); - return WHY_EXCEPTION; + if (PyExceptionClass_Check(exc)) { + type = exc; + value = PyObject_CallObject(exc, NULL); + if (value == NULL) + goto raise_error; + } + else if (PyExceptionInstance_Check(exc)) { + value = exc; + type = PyExceptionInstance_Class(exc); + Py_INCREF(type); + } + else { + /* Not something you can raise. You get an exception + anyway, just not what you specified :-) */ + Py_DECREF(exc); + PyErr_SetString(PyExc_TypeError, + "exceptions must derive from BaseException"); + goto raise_error; + } + + if (cause) { + PyObject *fixed_cause; + if (PyExceptionClass_Check(cause)) { + fixed_cause = PyObject_CallObject(cause, NULL); + if (fixed_cause == NULL) + goto raise_error; + Py_DECREF(cause); + } + else if (PyExceptionInstance_Check(cause)) { + fixed_cause = cause; + } + else { + PyErr_SetString(PyExc_TypeError, + "exception causes must derive from " + "BaseException"); + goto raise_error; + } + PyException_SetCause(value, fixed_cause); + } + + PyErr_SetObject(type, value); + /* PyErr_SetObject incref's its arguments */ + Py_XDECREF(value); + Py_XDECREF(type); + return WHY_EXCEPTION; raise_error: - Py_XDECREF(value); - Py_XDECREF(type); - Py_XDECREF(cause); - return WHY_EXCEPTION; + Py_XDECREF(value); + Py_XDECREF(type); + Py_XDECREF(cause); + return WHY_EXCEPTION; } /* Iterate v argcnt times and store the results on the stack (via decreasing @@ -3428,73 +3428,73 @@ static int unpack_iterable(PyObject *v, int argcnt, int argcntafter, PyObject **sp) { - int i = 0, j = 0; - Py_ssize_t ll = 0; - PyObject *it; /* iter(v) */ - PyObject *w; - PyObject *l = NULL; /* variable list */ - - assert(v != NULL); - - it = PyObject_GetIter(v); - if (it == NULL) - goto Error; - - for (; i < argcnt; i++) { - w = PyIter_Next(it); - if (w == NULL) { - /* Iterator done, via error or exhaustion. */ - if (!PyErr_Occurred()) { - PyErr_Format(PyExc_ValueError, - "need more than %d value%s to unpack", - i, i == 1 ? "" : "s"); - } - goto Error; - } - *--sp = w; - } - - if (argcntafter == -1) { - /* We better have exhausted the iterator now. */ - w = PyIter_Next(it); - if (w == NULL) { - if (PyErr_Occurred()) - goto Error; - Py_DECREF(it); - return 1; - } - Py_DECREF(w); - PyErr_SetString(PyExc_ValueError, "too many values to unpack"); - goto Error; - } - - l = PySequence_List(it); - if (l == NULL) - goto Error; - *--sp = l; - i++; - - ll = PyList_GET_SIZE(l); - if (ll < argcntafter) { - PyErr_Format(PyExc_ValueError, "need more than %zd values to unpack", - argcnt + ll); - goto Error; - } - - /* Pop the "after-variable" args off the list. */ - for (j = argcntafter; j > 0; j--, i++) { - *--sp = PyList_GET_ITEM(l, ll - j); - } - /* Resize the list. */ - Py_SIZE(l) = ll - argcntafter; - Py_DECREF(it); - return 1; + int i = 0, j = 0; + Py_ssize_t ll = 0; + PyObject *it; /* iter(v) */ + PyObject *w; + PyObject *l = NULL; /* variable list */ + + assert(v != NULL); + + it = PyObject_GetIter(v); + if (it == NULL) + goto Error; + + for (; i < argcnt; i++) { + w = PyIter_Next(it); + if (w == NULL) { + /* Iterator done, via error or exhaustion. */ + if (!PyErr_Occurred()) { + PyErr_Format(PyExc_ValueError, + "need more than %d value%s to unpack", + i, i == 1 ? "" : "s"); + } + goto Error; + } + *--sp = w; + } + + if (argcntafter == -1) { + /* We better have exhausted the iterator now. */ + w = PyIter_Next(it); + if (w == NULL) { + if (PyErr_Occurred()) + goto Error; + Py_DECREF(it); + return 1; + } + Py_DECREF(w); + PyErr_SetString(PyExc_ValueError, "too many values to unpack"); + goto Error; + } + + l = PySequence_List(it); + if (l == NULL) + goto Error; + *--sp = l; + i++; + + ll = PyList_GET_SIZE(l); + if (ll < argcntafter) { + PyErr_Format(PyExc_ValueError, "need more than %zd values to unpack", + argcnt + ll); + goto Error; + } + + /* Pop the "after-variable" args off the list. */ + for (j = argcntafter; j > 0; j--, i++) { + *--sp = PyList_GET_ITEM(l, ll - j); + } + /* Resize the list. */ + Py_SIZE(l) = ll - argcntafter; + Py_DECREF(it); + return 1; Error: - for (; i > 0; i--, sp++) - Py_DECREF(*sp); - Py_XDECREF(it); - return 0; + for (; i > 0; i--, sp++) + Py_DECREF(*sp); + Py_XDECREF(it); + return 0; } @@ -3502,220 +3502,220 @@ static int prtrace(PyObject *v, char *str) { - printf("%s ", str); - if (PyObject_Print(v, stdout, 0) != 0) - PyErr_Clear(); /* Don't know what else to do */ - printf("\n"); - return 1; + printf("%s ", str); + if (PyObject_Print(v, stdout, 0) != 0) + PyErr_Clear(); /* Don't know what else to do */ + printf("\n"); + return 1; } #endif static void call_exc_trace(Py_tracefunc func, PyObject *self, PyFrameObject *f) { - PyObject *type, *value, *traceback, *arg; - int err; - PyErr_Fetch(&type, &value, &traceback); - if (value == NULL) { - value = Py_None; - Py_INCREF(value); - } - arg = PyTuple_Pack(3, type, value, traceback); - if (arg == NULL) { - PyErr_Restore(type, value, traceback); - return; - } - err = call_trace(func, self, f, PyTrace_EXCEPTION, arg); - Py_DECREF(arg); - if (err == 0) - PyErr_Restore(type, value, traceback); - else { - Py_XDECREF(type); - Py_XDECREF(value); - Py_XDECREF(traceback); - } + PyObject *type, *value, *traceback, *arg; + int err; + PyErr_Fetch(&type, &value, &traceback); + if (value == NULL) { + value = Py_None; + Py_INCREF(value); + } + arg = PyTuple_Pack(3, type, value, traceback); + if (arg == NULL) { + PyErr_Restore(type, value, traceback); + return; + } + err = call_trace(func, self, f, PyTrace_EXCEPTION, arg); + Py_DECREF(arg); + if (err == 0) + PyErr_Restore(type, value, traceback); + else { + Py_XDECREF(type); + Py_XDECREF(value); + Py_XDECREF(traceback); + } } static int call_trace_protected(Py_tracefunc func, PyObject *obj, PyFrameObject *frame, - int what, PyObject *arg) + int what, PyObject *arg) { - PyObject *type, *value, *traceback; - int err; - PyErr_Fetch(&type, &value, &traceback); - err = call_trace(func, obj, frame, what, arg); - if (err == 0) - { - PyErr_Restore(type, value, traceback); - return 0; - } - else { - Py_XDECREF(type); - Py_XDECREF(value); - Py_XDECREF(traceback); - return -1; - } + PyObject *type, *value, *traceback; + int err; + PyErr_Fetch(&type, &value, &traceback); + err = call_trace(func, obj, frame, what, arg); + if (err == 0) + { + PyErr_Restore(type, value, traceback); + return 0; + } + else { + Py_XDECREF(type); + Py_XDECREF(value); + Py_XDECREF(traceback); + return -1; + } } static int call_trace(Py_tracefunc func, PyObject *obj, PyFrameObject *frame, - int what, PyObject *arg) + int what, PyObject *arg) { - register PyThreadState *tstate = frame->f_tstate; - int result; - if (tstate->tracing) - return 0; - tstate->tracing++; - tstate->use_tracing = 0; - result = func(obj, frame, what, arg); - tstate->use_tracing = ((tstate->c_tracefunc != NULL) - || (tstate->c_profilefunc != NULL)); - tstate->tracing--; - return result; + register PyThreadState *tstate = frame->f_tstate; + int result; + if (tstate->tracing) + return 0; + tstate->tracing++; + tstate->use_tracing = 0; + result = func(obj, frame, what, arg); + tstate->use_tracing = ((tstate->c_tracefunc != NULL) + || (tstate->c_profilefunc != NULL)); + tstate->tracing--; + return result; } PyObject * _PyEval_CallTracing(PyObject *func, PyObject *args) { - PyFrameObject *frame = PyEval_GetFrame(); - PyThreadState *tstate = frame->f_tstate; - int save_tracing = tstate->tracing; - int save_use_tracing = tstate->use_tracing; - PyObject *result; - - tstate->tracing = 0; - tstate->use_tracing = ((tstate->c_tracefunc != NULL) - || (tstate->c_profilefunc != NULL)); - result = PyObject_Call(func, args, NULL); - tstate->tracing = save_tracing; - tstate->use_tracing = save_use_tracing; - return result; + PyFrameObject *frame = PyEval_GetFrame(); + PyThreadState *tstate = frame->f_tstate; + int save_tracing = tstate->tracing; + int save_use_tracing = tstate->use_tracing; + PyObject *result; + + tstate->tracing = 0; + tstate->use_tracing = ((tstate->c_tracefunc != NULL) + || (tstate->c_profilefunc != NULL)); + result = PyObject_Call(func, args, NULL); + tstate->tracing = save_tracing; + tstate->use_tracing = save_use_tracing; + return result; } /* See Objects/lnotab_notes.txt for a description of how tracing works. */ static int maybe_call_line_trace(Py_tracefunc func, PyObject *obj, - PyFrameObject *frame, int *instr_lb, int *instr_ub, - int *instr_prev) + PyFrameObject *frame, int *instr_lb, int *instr_ub, + int *instr_prev) { - int result = 0; - int line = frame->f_lineno; + int result = 0; + int line = frame->f_lineno; - /* If the last instruction executed isn't in the current - instruction window, reset the window. - */ - if (frame->f_lasti < *instr_lb || frame->f_lasti >= *instr_ub) { - PyAddrPair bounds; - line = _PyCode_CheckLineNumber(frame->f_code, frame->f_lasti, - &bounds); - *instr_lb = bounds.ap_lower; - *instr_ub = bounds.ap_upper; - } - /* If the last instruction falls at the start of a line or if - it represents a jump backwards, update the frame's line - number and call the trace function. */ - if (frame->f_lasti == *instr_lb || frame->f_lasti < *instr_prev) { - frame->f_lineno = line; - result = call_trace(func, obj, frame, PyTrace_LINE, Py_None); - } - *instr_prev = frame->f_lasti; - return result; + /* If the last instruction executed isn't in the current + instruction window, reset the window. + */ + if (frame->f_lasti < *instr_lb || frame->f_lasti >= *instr_ub) { + PyAddrPair bounds; + line = _PyCode_CheckLineNumber(frame->f_code, frame->f_lasti, + &bounds); + *instr_lb = bounds.ap_lower; + *instr_ub = bounds.ap_upper; + } + /* If the last instruction falls at the start of a line or if + it represents a jump backwards, update the frame's line + number and call the trace function. */ + if (frame->f_lasti == *instr_lb || frame->f_lasti < *instr_prev) { + frame->f_lineno = line; + result = call_trace(func, obj, frame, PyTrace_LINE, Py_None); + } + *instr_prev = frame->f_lasti; + return result; } void PyEval_SetProfile(Py_tracefunc func, PyObject *arg) { - PyThreadState *tstate = PyThreadState_GET(); - PyObject *temp = tstate->c_profileobj; - Py_XINCREF(arg); - tstate->c_profilefunc = NULL; - tstate->c_profileobj = NULL; - /* Must make sure that tracing is not ignored if 'temp' is freed */ - tstate->use_tracing = tstate->c_tracefunc != NULL; - Py_XDECREF(temp); - tstate->c_profilefunc = func; - tstate->c_profileobj = arg; - /* Flag that tracing or profiling is turned on */ - tstate->use_tracing = (func != NULL) || (tstate->c_tracefunc != NULL); + PyThreadState *tstate = PyThreadState_GET(); + PyObject *temp = tstate->c_profileobj; + Py_XINCREF(arg); + tstate->c_profilefunc = NULL; + tstate->c_profileobj = NULL; + /* Must make sure that tracing is not ignored if 'temp' is freed */ + tstate->use_tracing = tstate->c_tracefunc != NULL; + Py_XDECREF(temp); + tstate->c_profilefunc = func; + tstate->c_profileobj = arg; + /* Flag that tracing or profiling is turned on */ + tstate->use_tracing = (func != NULL) || (tstate->c_tracefunc != NULL); } void PyEval_SetTrace(Py_tracefunc func, PyObject *arg) { - PyThreadState *tstate = PyThreadState_GET(); - PyObject *temp = tstate->c_traceobj; - _Py_TracingPossible += (func != NULL) - (tstate->c_tracefunc != NULL); - Py_XINCREF(arg); - tstate->c_tracefunc = NULL; - tstate->c_traceobj = NULL; - /* Must make sure that profiling is not ignored if 'temp' is freed */ - tstate->use_tracing = tstate->c_profilefunc != NULL; - Py_XDECREF(temp); - tstate->c_tracefunc = func; - tstate->c_traceobj = arg; - /* Flag that tracing or profiling is turned on */ - tstate->use_tracing = ((func != NULL) - || (tstate->c_profilefunc != NULL)); + PyThreadState *tstate = PyThreadState_GET(); + PyObject *temp = tstate->c_traceobj; + _Py_TracingPossible += (func != NULL) - (tstate->c_tracefunc != NULL); + Py_XINCREF(arg); + tstate->c_tracefunc = NULL; + tstate->c_traceobj = NULL; + /* Must make sure that profiling is not ignored if 'temp' is freed */ + tstate->use_tracing = tstate->c_profilefunc != NULL; + Py_XDECREF(temp); + tstate->c_tracefunc = func; + tstate->c_traceobj = arg; + /* Flag that tracing or profiling is turned on */ + tstate->use_tracing = ((func != NULL) + || (tstate->c_profilefunc != NULL)); } PyObject * PyEval_GetBuiltins(void) { - PyFrameObject *current_frame = PyEval_GetFrame(); - if (current_frame == NULL) - return PyThreadState_GET()->interp->builtins; - else - return current_frame->f_builtins; + PyFrameObject *current_frame = PyEval_GetFrame(); + if (current_frame == NULL) + return PyThreadState_GET()->interp->builtins; + else + return current_frame->f_builtins; } PyObject * PyEval_GetLocals(void) { - PyFrameObject *current_frame = PyEval_GetFrame(); - if (current_frame == NULL) - return NULL; - PyFrame_FastToLocals(current_frame); - return current_frame->f_locals; + PyFrameObject *current_frame = PyEval_GetFrame(); + if (current_frame == NULL) + return NULL; + PyFrame_FastToLocals(current_frame); + return current_frame->f_locals; } PyObject * PyEval_GetGlobals(void) { - PyFrameObject *current_frame = PyEval_GetFrame(); - if (current_frame == NULL) - return NULL; - else - return current_frame->f_globals; + PyFrameObject *current_frame = PyEval_GetFrame(); + if (current_frame == NULL) + return NULL; + else + return current_frame->f_globals; } PyFrameObject * PyEval_GetFrame(void) { - PyThreadState *tstate = PyThreadState_GET(); - return _PyThreadState_GetFrame(tstate); + PyThreadState *tstate = PyThreadState_GET(); + return _PyThreadState_GetFrame(tstate); } int PyEval_MergeCompilerFlags(PyCompilerFlags *cf) { - PyFrameObject *current_frame = PyEval_GetFrame(); - int result = cf->cf_flags != 0; + PyFrameObject *current_frame = PyEval_GetFrame(); + int result = cf->cf_flags != 0; - if (current_frame != NULL) { - const int codeflags = current_frame->f_code->co_flags; - const int compilerflags = codeflags & PyCF_MASK; - if (compilerflags) { - result = 1; - cf->cf_flags |= compilerflags; - } + if (current_frame != NULL) { + const int codeflags = current_frame->f_code->co_flags; + const int compilerflags = codeflags & PyCF_MASK; + if (compilerflags) { + result = 1; + cf->cf_flags |= compilerflags; + } #if 0 /* future keyword */ - if (codeflags & CO_GENERATOR_ALLOWED) { - result = 1; - cf->cf_flags |= CO_GENERATOR_ALLOWED; - } + if (codeflags & CO_GENERATOR_ALLOWED) { + result = 1; + cf->cf_flags |= CO_GENERATOR_ALLOWED; + } #endif - } - return result; + } + return result; } @@ -3725,186 +3725,186 @@ PyObject * PyEval_CallObjectWithKeywords(PyObject *func, PyObject *arg, PyObject *kw) { - PyObject *result; + PyObject *result; - if (arg == NULL) { - arg = PyTuple_New(0); - if (arg == NULL) - return NULL; - } - else if (!PyTuple_Check(arg)) { - PyErr_SetString(PyExc_TypeError, - "argument list must be a tuple"); - return NULL; - } - else - Py_INCREF(arg); - - if (kw != NULL && !PyDict_Check(kw)) { - PyErr_SetString(PyExc_TypeError, - "keyword list must be a dictionary"); - Py_DECREF(arg); - return NULL; - } - - result = PyObject_Call(func, arg, kw); - Py_DECREF(arg); - return result; + if (arg == NULL) { + arg = PyTuple_New(0); + if (arg == NULL) + return NULL; + } + else if (!PyTuple_Check(arg)) { + PyErr_SetString(PyExc_TypeError, + "argument list must be a tuple"); + return NULL; + } + else + Py_INCREF(arg); + + if (kw != NULL && !PyDict_Check(kw)) { + PyErr_SetString(PyExc_TypeError, + "keyword list must be a dictionary"); + Py_DECREF(arg); + return NULL; + } + + result = PyObject_Call(func, arg, kw); + Py_DECREF(arg); + return result; } const char * PyEval_GetFuncName(PyObject *func) { - if (PyMethod_Check(func)) - return PyEval_GetFuncName(PyMethod_GET_FUNCTION(func)); - else if (PyFunction_Check(func)) - return _PyUnicode_AsString(((PyFunctionObject*)func)->func_name); - else if (PyCFunction_Check(func)) - return ((PyCFunctionObject*)func)->m_ml->ml_name; - else - return func->ob_type->tp_name; + if (PyMethod_Check(func)) + return PyEval_GetFuncName(PyMethod_GET_FUNCTION(func)); + else if (PyFunction_Check(func)) + return _PyUnicode_AsString(((PyFunctionObject*)func)->func_name); + else if (PyCFunction_Check(func)) + return ((PyCFunctionObject*)func)->m_ml->ml_name; + else + return func->ob_type->tp_name; } const char * PyEval_GetFuncDesc(PyObject *func) { - if (PyMethod_Check(func)) - return "()"; - else if (PyFunction_Check(func)) - return "()"; - else if (PyCFunction_Check(func)) - return "()"; - else - return " object"; + if (PyMethod_Check(func)) + return "()"; + else if (PyFunction_Check(func)) + return "()"; + else if (PyCFunction_Check(func)) + return "()"; + else + return " object"; } static void err_args(PyObject *func, int flags, int nargs) { - if (flags & METH_NOARGS) - PyErr_Format(PyExc_TypeError, - "%.200s() takes no arguments (%d given)", - ((PyCFunctionObject *)func)->m_ml->ml_name, - nargs); - else - PyErr_Format(PyExc_TypeError, - "%.200s() takes exactly one argument (%d given)", - ((PyCFunctionObject *)func)->m_ml->ml_name, - nargs); + if (flags & METH_NOARGS) + PyErr_Format(PyExc_TypeError, + "%.200s() takes no arguments (%d given)", + ((PyCFunctionObject *)func)->m_ml->ml_name, + nargs); + else + PyErr_Format(PyExc_TypeError, + "%.200s() takes exactly one argument (%d given)", + ((PyCFunctionObject *)func)->m_ml->ml_name, + nargs); } #define C_TRACE(x, call) \ if (tstate->use_tracing && tstate->c_profilefunc) { \ - if (call_trace(tstate->c_profilefunc, \ - tstate->c_profileobj, \ - tstate->frame, PyTrace_C_CALL, \ - func)) { \ - x = NULL; \ - } \ - else { \ - x = call; \ - if (tstate->c_profilefunc != NULL) { \ - if (x == NULL) { \ - call_trace_protected(tstate->c_profilefunc, \ - tstate->c_profileobj, \ - tstate->frame, PyTrace_C_EXCEPTION, \ - func); \ - /* XXX should pass (type, value, tb) */ \ - } else { \ - if (call_trace(tstate->c_profilefunc, \ - tstate->c_profileobj, \ - tstate->frame, PyTrace_C_RETURN, \ - func)) { \ - Py_DECREF(x); \ - x = NULL; \ - } \ - } \ - } \ - } \ + if (call_trace(tstate->c_profilefunc, \ + tstate->c_profileobj, \ + tstate->frame, PyTrace_C_CALL, \ + func)) { \ + x = NULL; \ + } \ + else { \ + x = call; \ + if (tstate->c_profilefunc != NULL) { \ + if (x == NULL) { \ + call_trace_protected(tstate->c_profilefunc, \ + tstate->c_profileobj, \ + tstate->frame, PyTrace_C_EXCEPTION, \ + func); \ + /* XXX should pass (type, value, tb) */ \ + } else { \ + if (call_trace(tstate->c_profilefunc, \ + tstate->c_profileobj, \ + tstate->frame, PyTrace_C_RETURN, \ + func)) { \ + Py_DECREF(x); \ + x = NULL; \ + } \ + } \ + } \ + } \ } else { \ - x = call; \ - } + x = call; \ + } static PyObject * call_function(PyObject ***pp_stack, int oparg #ifdef WITH_TSC - , uint64* pintr0, uint64* pintr1 + , uint64* pintr0, uint64* pintr1 #endif - ) + ) { - int na = oparg & 0xff; - int nk = (oparg>>8) & 0xff; - int n = na + 2 * nk; - PyObject **pfunc = (*pp_stack) - n - 1; - PyObject *func = *pfunc; - PyObject *x, *w; - - /* Always dispatch PyCFunction first, because these are - presumed to be the most frequent callable object. - */ - if (PyCFunction_Check(func) && nk == 0) { - int flags = PyCFunction_GET_FLAGS(func); - PyThreadState *tstate = PyThreadState_GET(); - - PCALL(PCALL_CFUNCTION); - if (flags & (METH_NOARGS | METH_O)) { - PyCFunction meth = PyCFunction_GET_FUNCTION(func); - PyObject *self = PyCFunction_GET_SELF(func); - if (flags & METH_NOARGS && na == 0) { - C_TRACE(x, (*meth)(self,NULL)); - } - else if (flags & METH_O && na == 1) { - PyObject *arg = EXT_POP(*pp_stack); - C_TRACE(x, (*meth)(self,arg)); - Py_DECREF(arg); - } - else { - err_args(func, flags, na); - x = NULL; - } - } - else { - PyObject *callargs; - callargs = load_args(pp_stack, na); - READ_TIMESTAMP(*pintr0); - C_TRACE(x, PyCFunction_Call(func,callargs,NULL)); - READ_TIMESTAMP(*pintr1); - Py_XDECREF(callargs); - } - } else { - if (PyMethod_Check(func) && PyMethod_GET_SELF(func) != NULL) { - /* optimize access to bound methods */ - PyObject *self = PyMethod_GET_SELF(func); - PCALL(PCALL_METHOD); - PCALL(PCALL_BOUND_METHOD); - Py_INCREF(self); - func = PyMethod_GET_FUNCTION(func); - Py_INCREF(func); - Py_DECREF(*pfunc); - *pfunc = self; - na++; - n++; - } else - Py_INCREF(func); - READ_TIMESTAMP(*pintr0); - if (PyFunction_Check(func)) - x = fast_function(func, pp_stack, n, na, nk); - else - x = do_call(func, pp_stack, na, nk); - READ_TIMESTAMP(*pintr1); - Py_DECREF(func); - } - - /* Clear the stack of the function object. Also removes - the arguments in case they weren't consumed already - (fast_function() and err_args() leave them on the stack). - */ - while ((*pp_stack) > pfunc) { - w = EXT_POP(*pp_stack); - Py_DECREF(w); - PCALL(PCALL_POP); - } - return x; + int na = oparg & 0xff; + int nk = (oparg>>8) & 0xff; + int n = na + 2 * nk; + PyObject **pfunc = (*pp_stack) - n - 1; + PyObject *func = *pfunc; + PyObject *x, *w; + + /* Always dispatch PyCFunction first, because these are + presumed to be the most frequent callable object. + */ + if (PyCFunction_Check(func) && nk == 0) { + int flags = PyCFunction_GET_FLAGS(func); + PyThreadState *tstate = PyThreadState_GET(); + + PCALL(PCALL_CFUNCTION); + if (flags & (METH_NOARGS | METH_O)) { + PyCFunction meth = PyCFunction_GET_FUNCTION(func); + PyObject *self = PyCFunction_GET_SELF(func); + if (flags & METH_NOARGS && na == 0) { + C_TRACE(x, (*meth)(self,NULL)); + } + else if (flags & METH_O && na == 1) { + PyObject *arg = EXT_POP(*pp_stack); + C_TRACE(x, (*meth)(self,arg)); + Py_DECREF(arg); + } + else { + err_args(func, flags, na); + x = NULL; + } + } + else { + PyObject *callargs; + callargs = load_args(pp_stack, na); + READ_TIMESTAMP(*pintr0); + C_TRACE(x, PyCFunction_Call(func,callargs,NULL)); + READ_TIMESTAMP(*pintr1); + Py_XDECREF(callargs); + } + } else { + if (PyMethod_Check(func) && PyMethod_GET_SELF(func) != NULL) { + /* optimize access to bound methods */ + PyObject *self = PyMethod_GET_SELF(func); + PCALL(PCALL_METHOD); + PCALL(PCALL_BOUND_METHOD); + Py_INCREF(self); + func = PyMethod_GET_FUNCTION(func); + Py_INCREF(func); + Py_DECREF(*pfunc); + *pfunc = self; + na++; + n++; + } else + Py_INCREF(func); + READ_TIMESTAMP(*pintr0); + if (PyFunction_Check(func)) + x = fast_function(func, pp_stack, n, na, nk); + else + x = do_call(func, pp_stack, na, nk); + READ_TIMESTAMP(*pintr1); + Py_DECREF(func); + } + + /* Clear the stack of the function object. Also removes + the arguments in case they weren't consumed already + (fast_function() and err_args() leave them on the stack). + */ + while ((*pp_stack) > pfunc) { + w = EXT_POP(*pp_stack); + Py_DECREF(w); + PCALL(PCALL_POP); + } + return x; } /* The fast_function() function optimize calls for which no argument @@ -3919,275 +3919,275 @@ static PyObject * fast_function(PyObject *func, PyObject ***pp_stack, int n, int na, int nk) { - PyCodeObject *co = (PyCodeObject *)PyFunction_GET_CODE(func); - PyObject *globals = PyFunction_GET_GLOBALS(func); - PyObject *argdefs = PyFunction_GET_DEFAULTS(func); - PyObject *kwdefs = PyFunction_GET_KW_DEFAULTS(func); - PyObject **d = NULL; - int nd = 0; - - PCALL(PCALL_FUNCTION); - PCALL(PCALL_FAST_FUNCTION); - if (argdefs == NULL && co->co_argcount == n && - co->co_kwonlyargcount == 0 && nk==0 && - co->co_flags == (CO_OPTIMIZED | CO_NEWLOCALS | CO_NOFREE)) { - PyFrameObject *f; - PyObject *retval = NULL; - PyThreadState *tstate = PyThreadState_GET(); - PyObject **fastlocals, **stack; - int i; - - PCALL(PCALL_FASTER_FUNCTION); - assert(globals != NULL); - /* XXX Perhaps we should create a specialized - PyFrame_New() that doesn't take locals, but does - take builtins without sanity checking them. - */ - assert(tstate != NULL); - f = PyFrame_New(tstate, co, globals, NULL); - if (f == NULL) - return NULL; - - fastlocals = f->f_localsplus; - stack = (*pp_stack) - n; - - for (i = 0; i < n; i++) { - Py_INCREF(*stack); - fastlocals[i] = *stack++; - } - retval = PyEval_EvalFrameEx(f,0); - ++tstate->recursion_depth; - Py_DECREF(f); - --tstate->recursion_depth; - return retval; - } - if (argdefs != NULL) { - d = &PyTuple_GET_ITEM(argdefs, 0); - nd = Py_SIZE(argdefs); - } - return PyEval_EvalCodeEx(co, globals, - (PyObject *)NULL, (*pp_stack)-n, na, - (*pp_stack)-2*nk, nk, d, nd, kwdefs, - PyFunction_GET_CLOSURE(func)); + PyCodeObject *co = (PyCodeObject *)PyFunction_GET_CODE(func); + PyObject *globals = PyFunction_GET_GLOBALS(func); + PyObject *argdefs = PyFunction_GET_DEFAULTS(func); + PyObject *kwdefs = PyFunction_GET_KW_DEFAULTS(func); + PyObject **d = NULL; + int nd = 0; + + PCALL(PCALL_FUNCTION); + PCALL(PCALL_FAST_FUNCTION); + if (argdefs == NULL && co->co_argcount == n && + co->co_kwonlyargcount == 0 && nk==0 && + co->co_flags == (CO_OPTIMIZED | CO_NEWLOCALS | CO_NOFREE)) { + PyFrameObject *f; + PyObject *retval = NULL; + PyThreadState *tstate = PyThreadState_GET(); + PyObject **fastlocals, **stack; + int i; + + PCALL(PCALL_FASTER_FUNCTION); + assert(globals != NULL); + /* XXX Perhaps we should create a specialized + PyFrame_New() that doesn't take locals, but does + take builtins without sanity checking them. + */ + assert(tstate != NULL); + f = PyFrame_New(tstate, co, globals, NULL); + if (f == NULL) + return NULL; + + fastlocals = f->f_localsplus; + stack = (*pp_stack) - n; + + for (i = 0; i < n; i++) { + Py_INCREF(*stack); + fastlocals[i] = *stack++; + } + retval = PyEval_EvalFrameEx(f,0); + ++tstate->recursion_depth; + Py_DECREF(f); + --tstate->recursion_depth; + return retval; + } + if (argdefs != NULL) { + d = &PyTuple_GET_ITEM(argdefs, 0); + nd = Py_SIZE(argdefs); + } + return PyEval_EvalCodeEx(co, globals, + (PyObject *)NULL, (*pp_stack)-n, na, + (*pp_stack)-2*nk, nk, d, nd, kwdefs, + PyFunction_GET_CLOSURE(func)); } static PyObject * update_keyword_args(PyObject *orig_kwdict, int nk, PyObject ***pp_stack, PyObject *func) { - PyObject *kwdict = NULL; - if (orig_kwdict == NULL) - kwdict = PyDict_New(); - else { - kwdict = PyDict_Copy(orig_kwdict); - Py_DECREF(orig_kwdict); - } - if (kwdict == NULL) - return NULL; - while (--nk >= 0) { - int err; - PyObject *value = EXT_POP(*pp_stack); - PyObject *key = EXT_POP(*pp_stack); - if (PyDict_GetItem(kwdict, key) != NULL) { - PyErr_Format(PyExc_TypeError, - "%.200s%s got multiple values " - "for keyword argument '%U'", - PyEval_GetFuncName(func), - PyEval_GetFuncDesc(func), - key); - Py_DECREF(key); - Py_DECREF(value); - Py_DECREF(kwdict); - return NULL; - } - err = PyDict_SetItem(kwdict, key, value); - Py_DECREF(key); - Py_DECREF(value); - if (err) { - Py_DECREF(kwdict); - return NULL; - } - } - return kwdict; + PyObject *kwdict = NULL; + if (orig_kwdict == NULL) + kwdict = PyDict_New(); + else { + kwdict = PyDict_Copy(orig_kwdict); + Py_DECREF(orig_kwdict); + } + if (kwdict == NULL) + return NULL; + while (--nk >= 0) { + int err; + PyObject *value = EXT_POP(*pp_stack); + PyObject *key = EXT_POP(*pp_stack); + if (PyDict_GetItem(kwdict, key) != NULL) { + PyErr_Format(PyExc_TypeError, + "%.200s%s got multiple values " + "for keyword argument '%U'", + PyEval_GetFuncName(func), + PyEval_GetFuncDesc(func), + key); + Py_DECREF(key); + Py_DECREF(value); + Py_DECREF(kwdict); + return NULL; + } + err = PyDict_SetItem(kwdict, key, value); + Py_DECREF(key); + Py_DECREF(value); + if (err) { + Py_DECREF(kwdict); + return NULL; + } + } + return kwdict; } static PyObject * update_star_args(int nstack, int nstar, PyObject *stararg, - PyObject ***pp_stack) + PyObject ***pp_stack) { - PyObject *callargs, *w; + PyObject *callargs, *w; - callargs = PyTuple_New(nstack + nstar); - if (callargs == NULL) { - return NULL; - } - if (nstar) { - int i; - for (i = 0; i < nstar; i++) { - PyObject *a = PyTuple_GET_ITEM(stararg, i); - Py_INCREF(a); - PyTuple_SET_ITEM(callargs, nstack + i, a); - } - } - while (--nstack >= 0) { - w = EXT_POP(*pp_stack); - PyTuple_SET_ITEM(callargs, nstack, w); - } - return callargs; + callargs = PyTuple_New(nstack + nstar); + if (callargs == NULL) { + return NULL; + } + if (nstar) { + int i; + for (i = 0; i < nstar; i++) { + PyObject *a = PyTuple_GET_ITEM(stararg, i); + Py_INCREF(a); + PyTuple_SET_ITEM(callargs, nstack + i, a); + } + } + while (--nstack >= 0) { + w = EXT_POP(*pp_stack); + PyTuple_SET_ITEM(callargs, nstack, w); + } + return callargs; } static PyObject * load_args(PyObject ***pp_stack, int na) { - PyObject *args = PyTuple_New(na); - PyObject *w; + PyObject *args = PyTuple_New(na); + PyObject *w; - if (args == NULL) - return NULL; - while (--na >= 0) { - w = EXT_POP(*pp_stack); - PyTuple_SET_ITEM(args, na, w); - } - return args; + if (args == NULL) + return NULL; + while (--na >= 0) { + w = EXT_POP(*pp_stack); + PyTuple_SET_ITEM(args, na, w); + } + return args; } static PyObject * do_call(PyObject *func, PyObject ***pp_stack, int na, int nk) { - PyObject *callargs = NULL; - PyObject *kwdict = NULL; - PyObject *result = NULL; - - if (nk > 0) { - kwdict = update_keyword_args(NULL, nk, pp_stack, func); - if (kwdict == NULL) - goto call_fail; - } - callargs = load_args(pp_stack, na); - if (callargs == NULL) - goto call_fail; + PyObject *callargs = NULL; + PyObject *kwdict = NULL; + PyObject *result = NULL; + + if (nk > 0) { + kwdict = update_keyword_args(NULL, nk, pp_stack, func); + if (kwdict == NULL) + goto call_fail; + } + callargs = load_args(pp_stack, na); + if (callargs == NULL) + goto call_fail; #ifdef CALL_PROFILE - /* At this point, we have to look at the type of func to - update the call stats properly. Do it here so as to avoid - exposing the call stats machinery outside ceval.c - */ - if (PyFunction_Check(func)) - PCALL(PCALL_FUNCTION); - else if (PyMethod_Check(func)) - PCALL(PCALL_METHOD); - else if (PyType_Check(func)) - PCALL(PCALL_TYPE); - else if (PyCFunction_Check(func)) - PCALL(PCALL_CFUNCTION); - else - PCALL(PCALL_OTHER); -#endif - if (PyCFunction_Check(func)) { - PyThreadState *tstate = PyThreadState_GET(); - C_TRACE(result, PyCFunction_Call(func, callargs, kwdict)); - } - else - result = PyObject_Call(func, callargs, kwdict); + /* At this point, we have to look at the type of func to + update the call stats properly. Do it here so as to avoid + exposing the call stats machinery outside ceval.c + */ + if (PyFunction_Check(func)) + PCALL(PCALL_FUNCTION); + else if (PyMethod_Check(func)) + PCALL(PCALL_METHOD); + else if (PyType_Check(func)) + PCALL(PCALL_TYPE); + else if (PyCFunction_Check(func)) + PCALL(PCALL_CFUNCTION); + else + PCALL(PCALL_OTHER); +#endif + if (PyCFunction_Check(func)) { + PyThreadState *tstate = PyThreadState_GET(); + C_TRACE(result, PyCFunction_Call(func, callargs, kwdict)); + } + else + result = PyObject_Call(func, callargs, kwdict); call_fail: - Py_XDECREF(callargs); - Py_XDECREF(kwdict); - return result; + Py_XDECREF(callargs); + Py_XDECREF(kwdict); + return result; } static PyObject * ext_do_call(PyObject *func, PyObject ***pp_stack, int flags, int na, int nk) { - int nstar = 0; - PyObject *callargs = NULL; - PyObject *stararg = NULL; - PyObject *kwdict = NULL; - PyObject *result = NULL; - - if (flags & CALL_FLAG_KW) { - kwdict = EXT_POP(*pp_stack); - if (!PyDict_Check(kwdict)) { - PyObject *d; - d = PyDict_New(); - if (d == NULL) - goto ext_call_fail; - if (PyDict_Update(d, kwdict) != 0) { - Py_DECREF(d); - /* PyDict_Update raises attribute - * error (percolated from an attempt - * to get 'keys' attribute) instead of - * a type error if its second argument - * is not a mapping. - */ - if (PyErr_ExceptionMatches(PyExc_AttributeError)) { - PyErr_Format(PyExc_TypeError, - "%.200s%.200s argument after ** " - "must be a mapping, not %.200s", - PyEval_GetFuncName(func), - PyEval_GetFuncDesc(func), - kwdict->ob_type->tp_name); - } - goto ext_call_fail; - } - Py_DECREF(kwdict); - kwdict = d; - } - } - if (flags & CALL_FLAG_VAR) { - stararg = EXT_POP(*pp_stack); - if (!PyTuple_Check(stararg)) { - PyObject *t = NULL; - t = PySequence_Tuple(stararg); - if (t == NULL) { - if (PyErr_ExceptionMatches(PyExc_TypeError)) { - PyErr_Format(PyExc_TypeError, - "%.200s%.200s argument after * " - "must be a sequence, not %200s", - PyEval_GetFuncName(func), - PyEval_GetFuncDesc(func), - stararg->ob_type->tp_name); - } - goto ext_call_fail; - } - Py_DECREF(stararg); - stararg = t; - } - nstar = PyTuple_GET_SIZE(stararg); - } - if (nk > 0) { - kwdict = update_keyword_args(kwdict, nk, pp_stack, func); - if (kwdict == NULL) - goto ext_call_fail; - } - callargs = update_star_args(na, nstar, stararg, pp_stack); - if (callargs == NULL) - goto ext_call_fail; + int nstar = 0; + PyObject *callargs = NULL; + PyObject *stararg = NULL; + PyObject *kwdict = NULL; + PyObject *result = NULL; + + if (flags & CALL_FLAG_KW) { + kwdict = EXT_POP(*pp_stack); + if (!PyDict_Check(kwdict)) { + PyObject *d; + d = PyDict_New(); + if (d == NULL) + goto ext_call_fail; + if (PyDict_Update(d, kwdict) != 0) { + Py_DECREF(d); + /* PyDict_Update raises attribute + * error (percolated from an attempt + * to get 'keys' attribute) instead of + * a type error if its second argument + * is not a mapping. + */ + if (PyErr_ExceptionMatches(PyExc_AttributeError)) { + PyErr_Format(PyExc_TypeError, + "%.200s%.200s argument after ** " + "must be a mapping, not %.200s", + PyEval_GetFuncName(func), + PyEval_GetFuncDesc(func), + kwdict->ob_type->tp_name); + } + goto ext_call_fail; + } + Py_DECREF(kwdict); + kwdict = d; + } + } + if (flags & CALL_FLAG_VAR) { + stararg = EXT_POP(*pp_stack); + if (!PyTuple_Check(stararg)) { + PyObject *t = NULL; + t = PySequence_Tuple(stararg); + if (t == NULL) { + if (PyErr_ExceptionMatches(PyExc_TypeError)) { + PyErr_Format(PyExc_TypeError, + "%.200s%.200s argument after * " + "must be a sequence, not %200s", + PyEval_GetFuncName(func), + PyEval_GetFuncDesc(func), + stararg->ob_type->tp_name); + } + goto ext_call_fail; + } + Py_DECREF(stararg); + stararg = t; + } + nstar = PyTuple_GET_SIZE(stararg); + } + if (nk > 0) { + kwdict = update_keyword_args(kwdict, nk, pp_stack, func); + if (kwdict == NULL) + goto ext_call_fail; + } + callargs = update_star_args(na, nstar, stararg, pp_stack); + if (callargs == NULL) + goto ext_call_fail; #ifdef CALL_PROFILE - /* At this point, we have to look at the type of func to - update the call stats properly. Do it here so as to avoid - exposing the call stats machinery outside ceval.c - */ - if (PyFunction_Check(func)) - PCALL(PCALL_FUNCTION); - else if (PyMethod_Check(func)) - PCALL(PCALL_METHOD); - else if (PyType_Check(func)) - PCALL(PCALL_TYPE); - else if (PyCFunction_Check(func)) - PCALL(PCALL_CFUNCTION); - else - PCALL(PCALL_OTHER); -#endif - if (PyCFunction_Check(func)) { - PyThreadState *tstate = PyThreadState_GET(); - C_TRACE(result, PyCFunction_Call(func, callargs, kwdict)); - } - else - result = PyObject_Call(func, callargs, kwdict); + /* At this point, we have to look at the type of func to + update the call stats properly. Do it here so as to avoid + exposing the call stats machinery outside ceval.c + */ + if (PyFunction_Check(func)) + PCALL(PCALL_FUNCTION); + else if (PyMethod_Check(func)) + PCALL(PCALL_METHOD); + else if (PyType_Check(func)) + PCALL(PCALL_TYPE); + else if (PyCFunction_Check(func)) + PCALL(PCALL_CFUNCTION); + else + PCALL(PCALL_OTHER); +#endif + if (PyCFunction_Check(func)) { + PyThreadState *tstate = PyThreadState_GET(); + C_TRACE(result, PyCFunction_Call(func, callargs, kwdict)); + } + else + result = PyObject_Call(func, callargs, kwdict); ext_call_fail: - Py_XDECREF(callargs); - Py_XDECREF(kwdict); - Py_XDECREF(stararg); - return result; + Py_XDECREF(callargs); + Py_XDECREF(kwdict); + Py_XDECREF(stararg); + return result; } /* Extract a slice index from a PyInt or PyLong or an object with the @@ -4203,245 +4203,245 @@ int _PyEval_SliceIndex(PyObject *v, Py_ssize_t *pi) { - if (v != NULL) { - Py_ssize_t x; - if (PyIndex_Check(v)) { - x = PyNumber_AsSsize_t(v, NULL); - if (x == -1 && PyErr_Occurred()) - return 0; - } - else { - PyErr_SetString(PyExc_TypeError, - "slice indices must be integers or " - "None or have an __index__ method"); - return 0; - } - *pi = x; - } - return 1; + if (v != NULL) { + Py_ssize_t x; + if (PyIndex_Check(v)) { + x = PyNumber_AsSsize_t(v, NULL); + if (x == -1 && PyErr_Occurred()) + return 0; + } + else { + PyErr_SetString(PyExc_TypeError, + "slice indices must be integers or " + "None or have an __index__ method"); + return 0; + } + *pi = x; + } + return 1; } #define CANNOT_CATCH_MSG "catching classes that do not inherit from "\ - "BaseException is not allowed" + "BaseException is not allowed" static PyObject * cmp_outcome(int op, register PyObject *v, register PyObject *w) { - int res = 0; - switch (op) { - case PyCmp_IS: - res = (v == w); - break; - case PyCmp_IS_NOT: - res = (v != w); - break; - case PyCmp_IN: - res = PySequence_Contains(w, v); - if (res < 0) - return NULL; - break; - case PyCmp_NOT_IN: - res = PySequence_Contains(w, v); - if (res < 0) - return NULL; - res = !res; - break; - case PyCmp_EXC_MATCH: - if (PyTuple_Check(w)) { - Py_ssize_t i, length; - length = PyTuple_Size(w); - for (i = 0; i < length; i += 1) { - PyObject *exc = PyTuple_GET_ITEM(w, i); - if (!PyExceptionClass_Check(exc)) { - PyErr_SetString(PyExc_TypeError, - CANNOT_CATCH_MSG); - return NULL; - } - } - } - else { - if (!PyExceptionClass_Check(w)) { - PyErr_SetString(PyExc_TypeError, - CANNOT_CATCH_MSG); - return NULL; - } - } - res = PyErr_GivenExceptionMatches(v, w); - break; - default: - return PyObject_RichCompare(v, w, op); - } - v = res ? Py_True : Py_False; - Py_INCREF(v); - return v; + int res = 0; + switch (op) { + case PyCmp_IS: + res = (v == w); + break; + case PyCmp_IS_NOT: + res = (v != w); + break; + case PyCmp_IN: + res = PySequence_Contains(w, v); + if (res < 0) + return NULL; + break; + case PyCmp_NOT_IN: + res = PySequence_Contains(w, v); + if (res < 0) + return NULL; + res = !res; + break; + case PyCmp_EXC_MATCH: + if (PyTuple_Check(w)) { + Py_ssize_t i, length; + length = PyTuple_Size(w); + for (i = 0; i < length; i += 1) { + PyObject *exc = PyTuple_GET_ITEM(w, i); + if (!PyExceptionClass_Check(exc)) { + PyErr_SetString(PyExc_TypeError, + CANNOT_CATCH_MSG); + return NULL; + } + } + } + else { + if (!PyExceptionClass_Check(w)) { + PyErr_SetString(PyExc_TypeError, + CANNOT_CATCH_MSG); + return NULL; + } + } + res = PyErr_GivenExceptionMatches(v, w); + break; + default: + return PyObject_RichCompare(v, w, op); + } + v = res ? Py_True : Py_False; + Py_INCREF(v); + return v; } static PyObject * import_from(PyObject *v, PyObject *name) { - PyObject *x; + PyObject *x; - x = PyObject_GetAttr(v, name); - if (x == NULL && PyErr_ExceptionMatches(PyExc_AttributeError)) { - PyErr_Format(PyExc_ImportError, "cannot import name %S", name); - } - return x; + x = PyObject_GetAttr(v, name); + if (x == NULL && PyErr_ExceptionMatches(PyExc_AttributeError)) { + PyErr_Format(PyExc_ImportError, "cannot import name %S", name); + } + return x; } static int import_all_from(PyObject *locals, PyObject *v) { - PyObject *all = PyObject_GetAttrString(v, "__all__"); - PyObject *dict, *name, *value; - int skip_leading_underscores = 0; - int pos, err; - - if (all == NULL) { - if (!PyErr_ExceptionMatches(PyExc_AttributeError)) - return -1; /* Unexpected error */ - PyErr_Clear(); - dict = PyObject_GetAttrString(v, "__dict__"); - if (dict == NULL) { - if (!PyErr_ExceptionMatches(PyExc_AttributeError)) - return -1; - PyErr_SetString(PyExc_ImportError, - "from-import-* object has no __dict__ and no __all__"); - return -1; - } - all = PyMapping_Keys(dict); - Py_DECREF(dict); - if (all == NULL) - return -1; - skip_leading_underscores = 1; - } - - for (pos = 0, err = 0; ; pos++) { - name = PySequence_GetItem(all, pos); - if (name == NULL) { - if (!PyErr_ExceptionMatches(PyExc_IndexError)) - err = -1; - else - PyErr_Clear(); - break; - } - if (skip_leading_underscores && - PyUnicode_Check(name) && - PyUnicode_AS_UNICODE(name)[0] == '_') - { - Py_DECREF(name); - continue; - } - value = PyObject_GetAttr(v, name); - if (value == NULL) - err = -1; - else if (PyDict_CheckExact(locals)) - err = PyDict_SetItem(locals, name, value); - else - err = PyObject_SetItem(locals, name, value); - Py_DECREF(name); - Py_XDECREF(value); - if (err != 0) - break; - } - Py_DECREF(all); - return err; + PyObject *all = PyObject_GetAttrString(v, "__all__"); + PyObject *dict, *name, *value; + int skip_leading_underscores = 0; + int pos, err; + + if (all == NULL) { + if (!PyErr_ExceptionMatches(PyExc_AttributeError)) + return -1; /* Unexpected error */ + PyErr_Clear(); + dict = PyObject_GetAttrString(v, "__dict__"); + if (dict == NULL) { + if (!PyErr_ExceptionMatches(PyExc_AttributeError)) + return -1; + PyErr_SetString(PyExc_ImportError, + "from-import-* object has no __dict__ and no __all__"); + return -1; + } + all = PyMapping_Keys(dict); + Py_DECREF(dict); + if (all == NULL) + return -1; + skip_leading_underscores = 1; + } + + for (pos = 0, err = 0; ; pos++) { + name = PySequence_GetItem(all, pos); + if (name == NULL) { + if (!PyErr_ExceptionMatches(PyExc_IndexError)) + err = -1; + else + PyErr_Clear(); + break; + } + if (skip_leading_underscores && + PyUnicode_Check(name) && + PyUnicode_AS_UNICODE(name)[0] == '_') + { + Py_DECREF(name); + continue; + } + value = PyObject_GetAttr(v, name); + if (value == NULL) + err = -1; + else if (PyDict_CheckExact(locals)) + err = PyDict_SetItem(locals, name, value); + else + err = PyObject_SetItem(locals, name, value); + Py_DECREF(name); + Py_XDECREF(value); + if (err != 0) + break; + } + Py_DECREF(all); + return err; } static void format_exc_check_arg(PyObject *exc, const char *format_str, PyObject *obj) { - const char *obj_str; + const char *obj_str; - if (!obj) - return; + if (!obj) + return; - obj_str = _PyUnicode_AsString(obj); - if (!obj_str) - return; + obj_str = _PyUnicode_AsString(obj); + if (!obj_str) + return; - PyErr_Format(exc, format_str, obj_str); + PyErr_Format(exc, format_str, obj_str); } static PyObject * unicode_concatenate(PyObject *v, PyObject *w, - PyFrameObject *f, unsigned char *next_instr) + PyFrameObject *f, unsigned char *next_instr) { - /* This function implements 'variable += expr' when both arguments - are (Unicode) strings. */ - Py_ssize_t v_len = PyUnicode_GET_SIZE(v); - Py_ssize_t w_len = PyUnicode_GET_SIZE(w); - Py_ssize_t new_len = v_len + w_len; - if (new_len < 0) { - PyErr_SetString(PyExc_OverflowError, - "strings are too large to concat"); - return NULL; - } - - if (v->ob_refcnt == 2) { - /* In the common case, there are 2 references to the value - * stored in 'variable' when the += is performed: one on the - * value stack (in 'v') and one still stored in the - * 'variable'. We try to delete the variable now to reduce - * the refcnt to 1. - */ - switch (*next_instr) { - case STORE_FAST: - { - int oparg = PEEKARG(); - PyObject **fastlocals = f->f_localsplus; - if (GETLOCAL(oparg) == v) - SETLOCAL(oparg, NULL); - break; - } - case STORE_DEREF: - { - PyObject **freevars = (f->f_localsplus + - f->f_code->co_nlocals); - PyObject *c = freevars[PEEKARG()]; - if (PyCell_GET(c) == v) - PyCell_Set(c, NULL); - break; - } - case STORE_NAME: - { - PyObject *names = f->f_code->co_names; - PyObject *name = GETITEM(names, PEEKARG()); - PyObject *locals = f->f_locals; - if (PyDict_CheckExact(locals) && - PyDict_GetItem(locals, name) == v) { - if (PyDict_DelItem(locals, name) != 0) { - PyErr_Clear(); - } - } - break; - } - } - } - - if (v->ob_refcnt == 1 && !PyUnicode_CHECK_INTERNED(v)) { - /* Now we own the last reference to 'v', so we can resize it - * in-place. - */ - if (PyUnicode_Resize(&v, new_len) != 0) { - /* XXX if PyUnicode_Resize() fails, 'v' has been - * deallocated so it cannot be put back into - * 'variable'. The MemoryError is raised when there - * is no value in 'variable', which might (very - * remotely) be a cause of incompatibilities. - */ - return NULL; - } - /* copy 'w' into the newly allocated area of 'v' */ - memcpy(PyUnicode_AS_UNICODE(v) + v_len, - PyUnicode_AS_UNICODE(w), w_len*sizeof(Py_UNICODE)); - return v; - } - else { - /* When in-place resizing is not an option. */ - w = PyUnicode_Concat(v, w); - Py_DECREF(v); - return w; - } + /* This function implements 'variable += expr' when both arguments + are (Unicode) strings. */ + Py_ssize_t v_len = PyUnicode_GET_SIZE(v); + Py_ssize_t w_len = PyUnicode_GET_SIZE(w); + Py_ssize_t new_len = v_len + w_len; + if (new_len < 0) { + PyErr_SetString(PyExc_OverflowError, + "strings are too large to concat"); + return NULL; + } + + if (v->ob_refcnt == 2) { + /* In the common case, there are 2 references to the value + * stored in 'variable' when the += is performed: one on the + * value stack (in 'v') and one still stored in the + * 'variable'. We try to delete the variable now to reduce + * the refcnt to 1. + */ + switch (*next_instr) { + case STORE_FAST: + { + int oparg = PEEKARG(); + PyObject **fastlocals = f->f_localsplus; + if (GETLOCAL(oparg) == v) + SETLOCAL(oparg, NULL); + break; + } + case STORE_DEREF: + { + PyObject **freevars = (f->f_localsplus + + f->f_code->co_nlocals); + PyObject *c = freevars[PEEKARG()]; + if (PyCell_GET(c) == v) + PyCell_Set(c, NULL); + break; + } + case STORE_NAME: + { + PyObject *names = f->f_code->co_names; + PyObject *name = GETITEM(names, PEEKARG()); + PyObject *locals = f->f_locals; + if (PyDict_CheckExact(locals) && + PyDict_GetItem(locals, name) == v) { + if (PyDict_DelItem(locals, name) != 0) { + PyErr_Clear(); + } + } + break; + } + } + } + + if (v->ob_refcnt == 1 && !PyUnicode_CHECK_INTERNED(v)) { + /* Now we own the last reference to 'v', so we can resize it + * in-place. + */ + if (PyUnicode_Resize(&v, new_len) != 0) { + /* XXX if PyUnicode_Resize() fails, 'v' has been + * deallocated so it cannot be put back into + * 'variable'. The MemoryError is raised when there + * is no value in 'variable', which might (very + * remotely) be a cause of incompatibilities. + */ + return NULL; + } + /* copy 'w' into the newly allocated area of 'v' */ + memcpy(PyUnicode_AS_UNICODE(v) + v_len, + PyUnicode_AS_UNICODE(w), w_len*sizeof(Py_UNICODE)); + return v; + } + else { + /* When in-place resizing is not an option. */ + w = PyUnicode_Concat(v, w); + Py_DECREF(v); + return w; + } } #ifdef DYNAMIC_EXECUTION_PROFILE @@ -4449,40 +4449,40 @@ static PyObject * getarray(long a[256]) { - int i; - PyObject *l = PyList_New(256); - if (l == NULL) return NULL; - for (i = 0; i < 256; i++) { - PyObject *x = PyLong_FromLong(a[i]); - if (x == NULL) { - Py_DECREF(l); - return NULL; - } - PyList_SetItem(l, i, x); - } - for (i = 0; i < 256; i++) - a[i] = 0; - return l; + int i; + PyObject *l = PyList_New(256); + if (l == NULL) return NULL; + for (i = 0; i < 256; i++) { + PyObject *x = PyLong_FromLong(a[i]); + if (x == NULL) { + Py_DECREF(l); + return NULL; + } + PyList_SetItem(l, i, x); + } + for (i = 0; i < 256; i++) + a[i] = 0; + return l; } PyObject * _Py_GetDXProfile(PyObject *self, PyObject *args) { #ifndef DXPAIRS - return getarray(dxp); + return getarray(dxp); #else - int i; - PyObject *l = PyList_New(257); - if (l == NULL) return NULL; - for (i = 0; i < 257; i++) { - PyObject *x = getarray(dxpairs[i]); - if (x == NULL) { - Py_DECREF(l); - return NULL; - } - PyList_SetItem(l, i, x); - } - return l; + int i; + PyObject *l = PyList_New(257); + if (l == NULL) return NULL; + for (i = 0; i < 257; i++) { + PyObject *x = getarray(dxpairs[i]); + if (x == NULL) { + Py_DECREF(l); + return NULL; + } + PyList_SetItem(l, i, x); + } + return l; #endif } Modified: python/branches/py3k/Python/codecs.c ============================================================================== --- python/branches/py3k/Python/codecs.c (original) +++ python/branches/py3k/Python/codecs.c Sun May 9 17:52:27 2010 @@ -30,14 +30,14 @@ { PyInterpreterState *interp = PyThreadState_GET()->interp; if (interp->codec_search_path == NULL && _PyCodecRegistry_Init()) - goto onError; + goto onError; if (search_function == NULL) { - PyErr_BadArgument(); - goto onError; + PyErr_BadArgument(); + goto onError; } if (!PyCallable_Check(search_function)) { - PyErr_SetString(PyExc_TypeError, "argument must be callable"); - goto onError; + PyErr_SetString(PyExc_TypeError, "argument must be callable"); + goto onError; } return PyList_Append(interp->codec_search_path, search_function); @@ -57,8 +57,8 @@ PyObject *v; if (len > PY_SSIZE_T_MAX) { - PyErr_SetString(PyExc_OverflowError, "string is too large"); - return NULL; + PyErr_SetString(PyExc_OverflowError, "string is too large"); + return NULL; } p = PyMem_Malloc(len + 1); @@ -70,7 +70,7 @@ ch = '-'; else ch = tolower(Py_CHARMASK(ch)); - p[i] = ch; + p[i] = ch; } p[i] = '\0'; v = PyUnicode_FromString(p); @@ -102,78 +102,78 @@ Py_ssize_t i, len; if (encoding == NULL) { - PyErr_BadArgument(); - goto onError; + PyErr_BadArgument(); + goto onError; } interp = PyThreadState_GET()->interp; if (interp->codec_search_path == NULL && _PyCodecRegistry_Init()) - goto onError; + goto onError; /* Convert the encoding to a normalized Python string: all characters are converted to lower case, spaces and hyphens are replaced with underscores. */ v = normalizestring(encoding); if (v == NULL) - goto onError; + goto onError; PyUnicode_InternInPlace(&v); /* First, try to lookup the name in the registry dictionary */ result = PyDict_GetItem(interp->codec_search_cache, v); if (result != NULL) { - Py_INCREF(result); - Py_DECREF(v); - return result; + Py_INCREF(result); + Py_DECREF(v); + return result; } /* Next, scan the search functions in order of registration */ args = PyTuple_New(1); if (args == NULL) - goto onError; + goto onError; PyTuple_SET_ITEM(args,0,v); len = PyList_Size(interp->codec_search_path); if (len < 0) - goto onError; + goto onError; if (len == 0) { - PyErr_SetString(PyExc_LookupError, - "no codec search functions registered: " - "can't find encoding"); - goto onError; + PyErr_SetString(PyExc_LookupError, + "no codec search functions registered: " + "can't find encoding"); + goto onError; } for (i = 0; i < len; i++) { - PyObject *func; + PyObject *func; - func = PyList_GetItem(interp->codec_search_path, i); - if (func == NULL) - goto onError; - result = PyEval_CallObject(func, args); - if (result == NULL) - goto onError; - if (result == Py_None) { - Py_DECREF(result); - continue; - } - if (!PyTuple_Check(result) || PyTuple_GET_SIZE(result) != 4) { - PyErr_SetString(PyExc_TypeError, - "codec search functions must return 4-tuples"); - Py_DECREF(result); - goto onError; - } - break; + func = PyList_GetItem(interp->codec_search_path, i); + if (func == NULL) + goto onError; + result = PyEval_CallObject(func, args); + if (result == NULL) + goto onError; + if (result == Py_None) { + Py_DECREF(result); + continue; + } + if (!PyTuple_Check(result) || PyTuple_GET_SIZE(result) != 4) { + PyErr_SetString(PyExc_TypeError, + "codec search functions must return 4-tuples"); + Py_DECREF(result); + goto onError; + } + break; } if (i == len) { - /* XXX Perhaps we should cache misses too ? */ - PyErr_Format(PyExc_LookupError, + /* XXX Perhaps we should cache misses too ? */ + PyErr_Format(PyExc_LookupError, "unknown encoding: %s", encoding); - goto onError; + goto onError; } /* Cache and return the result */ if (PyDict_SetItem(interp->codec_search_cache, v, result) < 0) { - Py_DECREF(result); - goto onError; + Py_DECREF(result); + goto onError; } Py_DECREF(args); return result; @@ -188,38 +188,38 @@ int PyCodec_KnownEncoding(const char *encoding) { PyObject *codecs; - + codecs = _PyCodec_Lookup(encoding); if (!codecs) { - PyErr_Clear(); - return 0; + PyErr_Clear(); + return 0; } else { - Py_DECREF(codecs); - return 1; + Py_DECREF(codecs); + return 1; } } static PyObject *args_tuple(PyObject *object, - const char *errors) + const char *errors) { PyObject *args; args = PyTuple_New(1 + (errors != NULL)); if (args == NULL) - return NULL; + return NULL; Py_INCREF(object); PyTuple_SET_ITEM(args,0,object); if (errors) { - PyObject *v; + PyObject *v; - v = PyUnicode_FromString(errors); - if (v == NULL) { - Py_DECREF(args); - return NULL; - } - PyTuple_SET_ITEM(args, 1, v); + v = PyUnicode_FromString(errors); + if (v == NULL) { + Py_DECREF(args); + return NULL; + } + PyTuple_SET_ITEM(args, 1, v); } return args; } @@ -234,7 +234,7 @@ codecs = _PyCodec_Lookup(encoding); if (codecs == NULL) - return NULL; + return NULL; v = PyTuple_GET_ITEM(codecs, index); Py_DECREF(codecs); Py_INCREF(v); @@ -245,22 +245,22 @@ static PyObject *codec_getincrementalcodec(const char *encoding, - const char *errors, - const char *attrname) + const char *errors, + const char *attrname) { PyObject *codecs, *ret, *inccodec; codecs = _PyCodec_Lookup(encoding); if (codecs == NULL) - return NULL; + return NULL; inccodec = PyObject_GetAttrString(codecs, attrname); Py_DECREF(codecs); if (inccodec == NULL) - return NULL; + return NULL; if (errors) - ret = PyObject_CallFunction(inccodec, "s", errors); + ret = PyObject_CallFunction(inccodec, "s", errors); else - ret = PyObject_CallFunction(inccodec, NULL); + ret = PyObject_CallFunction(inccodec, NULL); Py_DECREF(inccodec); return ret; } @@ -269,21 +269,21 @@ static PyObject *codec_getstreamcodec(const char *encoding, - PyObject *stream, - const char *errors, - const int index) + PyObject *stream, + const char *errors, + const int index) { PyObject *codecs, *streamcodec, *codeccls; codecs = _PyCodec_Lookup(encoding); if (codecs == NULL) - return NULL; + return NULL; codeccls = PyTuple_GET_ITEM(codecs, index); if (errors != NULL) - streamcodec = PyObject_CallFunction(codeccls, "Os", stream, errors); + streamcodec = PyObject_CallFunction(codeccls, "Os", stream, errors); else - streamcodec = PyObject_CallFunction(codeccls, "O", stream); + streamcodec = PyObject_CallFunction(codeccls, "O", stream); Py_DECREF(codecs); return streamcodec; } @@ -305,27 +305,27 @@ } PyObject *PyCodec_IncrementalEncoder(const char *encoding, - const char *errors) + const char *errors) { return codec_getincrementalcodec(encoding, errors, "incrementalencoder"); } PyObject *PyCodec_IncrementalDecoder(const char *encoding, - const char *errors) + const char *errors) { return codec_getincrementalcodec(encoding, errors, "incrementaldecoder"); } PyObject *PyCodec_StreamReader(const char *encoding, - PyObject *stream, - const char *errors) + PyObject *stream, + const char *errors) { return codec_getstreamcodec(encoding, stream, errors, 2); } PyObject *PyCodec_StreamWriter(const char *encoding, - PyObject *stream, - const char *errors) + PyObject *stream, + const char *errors) { return codec_getstreamcodec(encoding, stream, errors, 3); } @@ -336,8 +336,8 @@ errors is passed to the encoder factory as argument if non-NULL. */ PyObject *PyCodec_Encode(PyObject *object, - const char *encoding, - const char *errors) + const char *encoding, + const char *errors) { PyObject *encoder = NULL; PyObject *args = NULL, *result = NULL; @@ -345,21 +345,21 @@ encoder = PyCodec_Encoder(encoding); if (encoder == NULL) - goto onError; + goto onError; args = args_tuple(object, errors); if (args == NULL) - goto onError; + goto onError; result = PyEval_CallObject(encoder, args); if (result == NULL) - goto onError; + goto onError; if (!PyTuple_Check(result) || - PyTuple_GET_SIZE(result) != 2) { - PyErr_SetString(PyExc_TypeError, - "encoder must return a tuple (object, integer)"); - goto onError; + PyTuple_GET_SIZE(result) != 2) { + PyErr_SetString(PyExc_TypeError, + "encoder must return a tuple (object, integer)"); + goto onError; } v = PyTuple_GET_ITEM(result,0); Py_INCREF(v); @@ -369,7 +369,7 @@ Py_DECREF(encoder); Py_DECREF(result); return v; - + onError: Py_XDECREF(result); Py_XDECREF(args); @@ -383,8 +383,8 @@ errors is passed to the decoder factory as argument if non-NULL. */ PyObject *PyCodec_Decode(PyObject *object, - const char *encoding, - const char *errors) + const char *encoding, + const char *errors) { PyObject *decoder = NULL; PyObject *args = NULL, *result = NULL; @@ -392,20 +392,20 @@ decoder = PyCodec_Decoder(encoding); if (decoder == NULL) - goto onError; + goto onError; args = args_tuple(object, errors); if (args == NULL) - goto onError; + goto onError; result = PyEval_CallObject(decoder,args); if (result == NULL) - goto onError; + goto onError; if (!PyTuple_Check(result) || - PyTuple_GET_SIZE(result) != 2) { - PyErr_SetString(PyExc_TypeError, - "decoder must return a tuple (object,integer)"); - goto onError; + PyTuple_GET_SIZE(result) != 2) { + PyErr_SetString(PyExc_TypeError, + "decoder must return a tuple (object,integer)"); + goto onError; } v = PyTuple_GET_ITEM(result,0); Py_INCREF(v); @@ -433,13 +433,13 @@ { PyInterpreterState *interp = PyThreadState_GET()->interp; if (interp->codec_search_path == NULL && _PyCodecRegistry_Init()) - return -1; + return -1; if (!PyCallable_Check(error)) { - PyErr_SetString(PyExc_TypeError, "handler must be callable"); - return -1; + PyErr_SetString(PyExc_TypeError, "handler must be callable"); + return -1; } return PyDict_SetItemString(interp->codec_error_registry, - (char *)name, error); + (char *)name, error); } /* Lookup the error handling callback function registered under the @@ -451,15 +451,15 @@ PyInterpreterState *interp = PyThreadState_GET()->interp; if (interp->codec_search_path == NULL && _PyCodecRegistry_Init()) - return NULL; + return NULL; if (name==NULL) - name = "strict"; + name = "strict"; handler = PyDict_GetItemString(interp->codec_error_registry, (char *)name); if (!handler) - PyErr_Format(PyExc_LookupError, "unknown error handler name '%.400s'", name); + PyErr_Format(PyExc_LookupError, "unknown error handler name '%.400s'", name); else - Py_INCREF(handler); + Py_INCREF(handler); return handler; } @@ -482,7 +482,7 @@ if (PyExceptionInstance_Check(exc)) PyErr_SetObject(PyExceptionInstance_Class(exc), exc); else - PyErr_SetString(PyExc_TypeError, "codec must pass exception instance"); + PyErr_SetString(PyExc_TypeError, "codec must pass exception instance"); return NULL; } @@ -491,20 +491,20 @@ { Py_ssize_t end; if (PyObject_IsInstance(exc, PyExc_UnicodeEncodeError)) { - if (PyUnicodeEncodeError_GetEnd(exc, &end)) - return NULL; + if (PyUnicodeEncodeError_GetEnd(exc, &end)) + return NULL; } else if (PyObject_IsInstance(exc, PyExc_UnicodeDecodeError)) { - if (PyUnicodeDecodeError_GetEnd(exc, &end)) - return NULL; + if (PyUnicodeDecodeError_GetEnd(exc, &end)) + return NULL; } else if (PyObject_IsInstance(exc, PyExc_UnicodeTranslateError)) { - if (PyUnicodeTranslateError_GetEnd(exc, &end)) - return NULL; + if (PyUnicodeTranslateError_GetEnd(exc, &end)) + return NULL; } else { - wrong_exception_type(exc); - return NULL; + wrong_exception_type(exc); + return NULL; } /* ouch: passing NULL, 0, pos gives None instead of u'' */ return Py_BuildValue("(u#n)", &end, 0, end); @@ -519,155 +519,155 @@ Py_ssize_t i; if (PyObject_IsInstance(exc, PyExc_UnicodeEncodeError)) { - PyObject *res; - Py_UNICODE *p; - if (PyUnicodeEncodeError_GetStart(exc, &start)) - return NULL; - if (PyUnicodeEncodeError_GetEnd(exc, &end)) - return NULL; - res = PyUnicode_FromUnicode(NULL, end-start); - if (res == NULL) - return NULL; - for (p = PyUnicode_AS_UNICODE(res), i = start; - i0) { - *outp++ = '0' + c/base; - c %= base; - base /= 10; - } - *outp++ = ';'; - } - restuple = Py_BuildValue("(On)", res, end); - Py_DECREF(res); - Py_DECREF(object); - return restuple; + while (digits-->0) { + *outp++ = '0' + c/base; + c %= base; + base /= 10; + } + *outp++ = ';'; + } + restuple = Py_BuildValue("(On)", res, end); + Py_DECREF(res); + Py_DECREF(object); + return restuple; } else { - wrong_exception_type(exc); - return NULL; + wrong_exception_type(exc); + return NULL; } } @@ -679,72 +679,72 @@ PyObject *PyCodec_BackslashReplaceErrors(PyObject *exc) { if (PyObject_IsInstance(exc, PyExc_UnicodeEncodeError)) { - PyObject *restuple; - PyObject *object; - Py_ssize_t start; - Py_ssize_t end; - PyObject *res; - Py_UNICODE *p; - Py_UNICODE *startp; - Py_UNICODE *outp; - int ressize; - if (PyUnicodeEncodeError_GetStart(exc, &start)) - return NULL; - if (PyUnicodeEncodeError_GetEnd(exc, &end)) - return NULL; - if (!(object = PyUnicodeEncodeError_GetObject(exc))) - return NULL; - startp = PyUnicode_AS_UNICODE(object); - for (p = startp+start, ressize = 0; p < startp+end; ++p) { + PyObject *restuple; + PyObject *object; + Py_ssize_t start; + Py_ssize_t end; + PyObject *res; + Py_UNICODE *p; + Py_UNICODE *startp; + Py_UNICODE *outp; + int ressize; + if (PyUnicodeEncodeError_GetStart(exc, &start)) + return NULL; + if (PyUnicodeEncodeError_GetEnd(exc, &end)) + return NULL; + if (!(object = PyUnicodeEncodeError_GetObject(exc))) + return NULL; + startp = PyUnicode_AS_UNICODE(object); + for (p = startp+start, ressize = 0; p < startp+end; ++p) { #ifdef Py_UNICODE_WIDE - if (*p >= 0x00010000) - ressize += 1+1+8; - else + if (*p >= 0x00010000) + ressize += 1+1+8; + else #endif - if (*p >= 0x100) { - ressize += 1+1+4; - } - else - ressize += 1+1+2; - } - res = PyUnicode_FromUnicode(NULL, ressize); - if (res==NULL) - return NULL; - for (p = startp+start, outp = PyUnicode_AS_UNICODE(res); - p < startp+end; ++p) { - Py_UNICODE c = *p; - *outp++ = '\\'; + if (*p >= 0x100) { + ressize += 1+1+4; + } + else + ressize += 1+1+2; + } + res = PyUnicode_FromUnicode(NULL, ressize); + if (res==NULL) + return NULL; + for (p = startp+start, outp = PyUnicode_AS_UNICODE(res); + p < startp+end; ++p) { + Py_UNICODE c = *p; + *outp++ = '\\'; #ifdef Py_UNICODE_WIDE - if (c >= 0x00010000) { - *outp++ = 'U'; - *outp++ = hexdigits[(c>>28)&0xf]; - *outp++ = hexdigits[(c>>24)&0xf]; - *outp++ = hexdigits[(c>>20)&0xf]; - *outp++ = hexdigits[(c>>16)&0xf]; - *outp++ = hexdigits[(c>>12)&0xf]; - *outp++ = hexdigits[(c>>8)&0xf]; - } - else + if (c >= 0x00010000) { + *outp++ = 'U'; + *outp++ = hexdigits[(c>>28)&0xf]; + *outp++ = hexdigits[(c>>24)&0xf]; + *outp++ = hexdigits[(c>>20)&0xf]; + *outp++ = hexdigits[(c>>16)&0xf]; + *outp++ = hexdigits[(c>>12)&0xf]; + *outp++ = hexdigits[(c>>8)&0xf]; + } + else #endif - if (c >= 0x100) { - *outp++ = 'u'; - *outp++ = hexdigits[(c>>12)&0xf]; - *outp++ = hexdigits[(c>>8)&0xf]; - } - else - *outp++ = 'x'; - *outp++ = hexdigits[(c>>4)&0xf]; - *outp++ = hexdigits[c&0xf]; - } - - restuple = Py_BuildValue("(On)", res, end); - Py_DECREF(res); - Py_DECREF(object); - return restuple; + if (c >= 0x100) { + *outp++ = 'u'; + *outp++ = hexdigits[(c>>12)&0xf]; + *outp++ = hexdigits[(c>>8)&0xf]; + } + else + *outp++ = 'x'; + *outp++ = hexdigits[(c>>4)&0xf]; + *outp++ = hexdigits[c&0xf]; + } + + restuple = Py_BuildValue("(On)", res, end); + Py_DECREF(res); + Py_DECREF(object); + return restuple; } else { - wrong_exception_type(exc); - return NULL; + wrong_exception_type(exc); + return NULL; } } @@ -759,73 +759,73 @@ Py_ssize_t end; PyObject *res; if (PyObject_IsInstance(exc, PyExc_UnicodeEncodeError)) { - Py_UNICODE *p; - Py_UNICODE *startp; - char *outp; - if (PyUnicodeEncodeError_GetStart(exc, &start)) - return NULL; - if (PyUnicodeEncodeError_GetEnd(exc, &end)) - return NULL; - if (!(object = PyUnicodeEncodeError_GetObject(exc))) - return NULL; - startp = PyUnicode_AS_UNICODE(object); - res = PyBytes_FromStringAndSize(NULL, 3*(end-start)); - if (!res) { - Py_DECREF(object); - return NULL; - } - outp = PyBytes_AsString(res); - for (p = startp+start; p < startp+end; p++) { - Py_UNICODE ch = *p; - if (ch < 0xd800 || ch > 0xdfff) { - /* Not a surrogate, fail with original exception */ - PyErr_SetObject(PyExceptionInstance_Class(exc), exc); - Py_DECREF(res); - Py_DECREF(object); - return NULL; - } - *outp++ = (char)(0xe0 | (ch >> 12)); - *outp++ = (char)(0x80 | ((ch >> 6) & 0x3f)); - *outp++ = (char)(0x80 | (ch & 0x3f)); - } - restuple = Py_BuildValue("(On)", res, end); - Py_DECREF(res); - Py_DECREF(object); - return restuple; + Py_UNICODE *p; + Py_UNICODE *startp; + char *outp; + if (PyUnicodeEncodeError_GetStart(exc, &start)) + return NULL; + if (PyUnicodeEncodeError_GetEnd(exc, &end)) + return NULL; + if (!(object = PyUnicodeEncodeError_GetObject(exc))) + return NULL; + startp = PyUnicode_AS_UNICODE(object); + res = PyBytes_FromStringAndSize(NULL, 3*(end-start)); + if (!res) { + Py_DECREF(object); + return NULL; + } + outp = PyBytes_AsString(res); + for (p = startp+start; p < startp+end; p++) { + Py_UNICODE ch = *p; + if (ch < 0xd800 || ch > 0xdfff) { + /* Not a surrogate, fail with original exception */ + PyErr_SetObject(PyExceptionInstance_Class(exc), exc); + Py_DECREF(res); + Py_DECREF(object); + return NULL; + } + *outp++ = (char)(0xe0 | (ch >> 12)); + *outp++ = (char)(0x80 | ((ch >> 6) & 0x3f)); + *outp++ = (char)(0x80 | (ch & 0x3f)); + } + restuple = Py_BuildValue("(On)", res, end); + Py_DECREF(res); + Py_DECREF(object); + return restuple; } else if (PyObject_IsInstance(exc, PyExc_UnicodeDecodeError)) { - unsigned char *p; - Py_UNICODE ch = 0; - if (PyUnicodeDecodeError_GetStart(exc, &start)) - return NULL; - if (!(object = PyUnicodeDecodeError_GetObject(exc))) - return NULL; - if (!(p = (unsigned char*)PyBytes_AsString(object))) { - Py_DECREF(object); - return NULL; - } - /* Try decoding a single surrogate character. If - there are more, let the codec call us again. */ - p += start; - if ((p[0] & 0xf0) == 0xe0 || - (p[1] & 0xc0) == 0x80 || - (p[2] & 0xc0) == 0x80) { - /* it's a three-byte code */ - ch = ((p[0] & 0x0f) << 12) + ((p[1] & 0x3f) << 6) + (p[2] & 0x3f); - if (ch < 0xd800 || ch > 0xdfff) - /* it's not a surrogate - fail */ - ch = 0; - } - Py_DECREF(object); - if (ch == 0) { - PyErr_SetObject(PyExceptionInstance_Class(exc), exc); - return NULL; - } - return Py_BuildValue("(u#n)", &ch, 1, start+3); + unsigned char *p; + Py_UNICODE ch = 0; + if (PyUnicodeDecodeError_GetStart(exc, &start)) + return NULL; + if (!(object = PyUnicodeDecodeError_GetObject(exc))) + return NULL; + if (!(p = (unsigned char*)PyBytes_AsString(object))) { + Py_DECREF(object); + return NULL; + } + /* Try decoding a single surrogate character. If + there are more, let the codec call us again. */ + p += start; + if ((p[0] & 0xf0) == 0xe0 || + (p[1] & 0xc0) == 0x80 || + (p[2] & 0xc0) == 0x80) { + /* it's a three-byte code */ + ch = ((p[0] & 0x0f) << 12) + ((p[1] & 0x3f) << 6) + (p[2] & 0x3f); + if (ch < 0xd800 || ch > 0xdfff) + /* it's not a surrogate - fail */ + ch = 0; + } + Py_DECREF(object); + if (ch == 0) { + PyErr_SetObject(PyExceptionInstance_Class(exc), exc); + return NULL; + } + return Py_BuildValue("(u#n)", &ch, 1, start+3); } else { - wrong_exception_type(exc); - return NULL; + wrong_exception_type(exc); + return NULL; } } @@ -838,74 +838,74 @@ Py_ssize_t end; PyObject *res; if (PyObject_IsInstance(exc, PyExc_UnicodeEncodeError)) { - Py_UNICODE *p; - Py_UNICODE *startp; - char *outp; - if (PyUnicodeEncodeError_GetStart(exc, &start)) - return NULL; - if (PyUnicodeEncodeError_GetEnd(exc, &end)) - return NULL; - if (!(object = PyUnicodeEncodeError_GetObject(exc))) - return NULL; - startp = PyUnicode_AS_UNICODE(object); - res = PyBytes_FromStringAndSize(NULL, end-start); - if (!res) { - Py_DECREF(object); - return NULL; - } - outp = PyBytes_AsString(res); - for (p = startp+start; p < startp+end; p++) { - Py_UNICODE ch = *p; - if (ch < 0xdc80 || ch > 0xdcff) { - /* Not a UTF-8b surrogate, fail with original exception */ - PyErr_SetObject(PyExceptionInstance_Class(exc), exc); - Py_DECREF(res); - Py_DECREF(object); - return NULL; - } - *outp++ = ch - 0xdc00; - } - restuple = Py_BuildValue("(On)", res, end); - Py_DECREF(res); - Py_DECREF(object); - return restuple; + Py_UNICODE *p; + Py_UNICODE *startp; + char *outp; + if (PyUnicodeEncodeError_GetStart(exc, &start)) + return NULL; + if (PyUnicodeEncodeError_GetEnd(exc, &end)) + return NULL; + if (!(object = PyUnicodeEncodeError_GetObject(exc))) + return NULL; + startp = PyUnicode_AS_UNICODE(object); + res = PyBytes_FromStringAndSize(NULL, end-start); + if (!res) { + Py_DECREF(object); + return NULL; + } + outp = PyBytes_AsString(res); + for (p = startp+start; p < startp+end; p++) { + Py_UNICODE ch = *p; + if (ch < 0xdc80 || ch > 0xdcff) { + /* Not a UTF-8b surrogate, fail with original exception */ + PyErr_SetObject(PyExceptionInstance_Class(exc), exc); + Py_DECREF(res); + Py_DECREF(object); + return NULL; + } + *outp++ = ch - 0xdc00; + } + restuple = Py_BuildValue("(On)", res, end); + Py_DECREF(res); + Py_DECREF(object); + return restuple; } else if (PyObject_IsInstance(exc, PyExc_UnicodeDecodeError)) { - unsigned char *p; - Py_UNICODE ch[4]; /* decode up to 4 bad bytes. */ - int consumed = 0; - if (PyUnicodeDecodeError_GetStart(exc, &start)) - return NULL; - if (PyUnicodeDecodeError_GetEnd(exc, &end)) - return NULL; - if (!(object = PyUnicodeDecodeError_GetObject(exc))) - return NULL; - if (!(p = (unsigned char*)PyBytes_AsString(object))) { - Py_DECREF(object); - return NULL; - } - while (consumed < 4 && consumed < end-start) { - /* Refuse to escape ASCII bytes. */ - if (p[start+consumed] < 128) - break; - ch[consumed] = 0xdc00 + p[start+consumed]; - consumed++; - } - Py_DECREF(object); - if (!consumed) { - /* codec complained about ASCII byte. */ - PyErr_SetObject(PyExceptionInstance_Class(exc), exc); - return NULL; - } - return Py_BuildValue("(u#n)", ch, consumed, start+consumed); + unsigned char *p; + Py_UNICODE ch[4]; /* decode up to 4 bad bytes. */ + int consumed = 0; + if (PyUnicodeDecodeError_GetStart(exc, &start)) + return NULL; + if (PyUnicodeDecodeError_GetEnd(exc, &end)) + return NULL; + if (!(object = PyUnicodeDecodeError_GetObject(exc))) + return NULL; + if (!(p = (unsigned char*)PyBytes_AsString(object))) { + Py_DECREF(object); + return NULL; + } + while (consumed < 4 && consumed < end-start) { + /* Refuse to escape ASCII bytes. */ + if (p[start+consumed] < 128) + break; + ch[consumed] = 0xdc00 + p[start+consumed]; + consumed++; + } + Py_DECREF(object); + if (!consumed) { + /* codec complained about ASCII byte. */ + PyErr_SetObject(PyExceptionInstance_Class(exc), exc); + return NULL; + } + return Py_BuildValue("(u#n)", ch, consumed, start+consumed); } else { - wrong_exception_type(exc); - return NULL; + wrong_exception_type(exc); + return NULL; } } - + static PyObject *strict_errors(PyObject *self, PyObject *exc) { return PyCodec_StrictErrors(exc); @@ -948,78 +948,78 @@ static int _PyCodecRegistry_Init(void) { static struct { - char *name; - PyMethodDef def; + char *name; + PyMethodDef def; } methods[] = { - { - "strict", - { - "strict_errors", - strict_errors, - METH_O, - PyDoc_STR("Implements the 'strict' error handling, which " - "raises a UnicodeError on coding errors.") - } - }, - { - "ignore", - { - "ignore_errors", - ignore_errors, - METH_O, - PyDoc_STR("Implements the 'ignore' error handling, which " - "ignores malformed data and continues.") - } - }, - { - "replace", - { - "replace_errors", - replace_errors, - METH_O, - PyDoc_STR("Implements the 'replace' error handling, which " - "replaces malformed data with a replacement marker.") - } - }, - { - "xmlcharrefreplace", - { - "xmlcharrefreplace_errors", - xmlcharrefreplace_errors, - METH_O, - PyDoc_STR("Implements the 'xmlcharrefreplace' error handling, " - "which replaces an unencodable character with the " - "appropriate XML character reference.") - } - }, - { - "backslashreplace", - { - "backslashreplace_errors", - backslashreplace_errors, - METH_O, - PyDoc_STR("Implements the 'backslashreplace' error handling, " - "which replaces an unencodable character with a " - "backslashed escape sequence.") - } - }, - { - "surrogatepass", - { - "surrogatepass", - surrogatepass_errors, - METH_O - } - }, - { - "surrogateescape", - { - "surrogateescape", - surrogateescape_errors, - METH_O - } - } + { + "strict", + { + "strict_errors", + strict_errors, + METH_O, + PyDoc_STR("Implements the 'strict' error handling, which " + "raises a UnicodeError on coding errors.") + } + }, + { + "ignore", + { + "ignore_errors", + ignore_errors, + METH_O, + PyDoc_STR("Implements the 'ignore' error handling, which " + "ignores malformed data and continues.") + } + }, + { + "replace", + { + "replace_errors", + replace_errors, + METH_O, + PyDoc_STR("Implements the 'replace' error handling, which " + "replaces malformed data with a replacement marker.") + } + }, + { + "xmlcharrefreplace", + { + "xmlcharrefreplace_errors", + xmlcharrefreplace_errors, + METH_O, + PyDoc_STR("Implements the 'xmlcharrefreplace' error handling, " + "which replaces an unencodable character with the " + "appropriate XML character reference.") + } + }, + { + "backslashreplace", + { + "backslashreplace_errors", + backslashreplace_errors, + METH_O, + PyDoc_STR("Implements the 'backslashreplace' error handling, " + "which replaces an unencodable character with a " + "backslashed escape sequence.") + } + }, + { + "surrogatepass", + { + "surrogatepass", + surrogatepass_errors, + METH_O + } + }, + { + "surrogateescape", + { + "surrogateescape", + surrogateescape_errors, + METH_O + } + } }; PyInterpreterState *interp = PyThreadState_GET()->interp; @@ -1027,42 +1027,42 @@ unsigned i; if (interp->codec_search_path != NULL) - return 0; + return 0; interp->codec_search_path = PyList_New(0); interp->codec_search_cache = PyDict_New(); interp->codec_error_registry = PyDict_New(); if (interp->codec_error_registry) { - for (i = 0; i < sizeof(methods)/sizeof(methods[0]); ++i) { - PyObject *func = PyCFunction_New(&methods[i].def, NULL); - int res; - if (!func) - Py_FatalError("can't initialize codec error registry"); - res = PyCodec_RegisterError(methods[i].name, func); - Py_DECREF(func); - if (res) - Py_FatalError("can't initialize codec error registry"); - } + for (i = 0; i < sizeof(methods)/sizeof(methods[0]); ++i) { + PyObject *func = PyCFunction_New(&methods[i].def, NULL); + int res; + if (!func) + Py_FatalError("can't initialize codec error registry"); + res = PyCodec_RegisterError(methods[i].name, func); + Py_DECREF(func); + if (res) + Py_FatalError("can't initialize codec error registry"); + } } if (interp->codec_search_path == NULL || - interp->codec_search_cache == NULL || - interp->codec_error_registry == NULL) - Py_FatalError("can't initialize codec registry"); + interp->codec_search_cache == NULL || + interp->codec_error_registry == NULL) + Py_FatalError("can't initialize codec registry"); mod = PyImport_ImportModuleNoBlock("encodings"); if (mod == NULL) { - if (PyErr_ExceptionMatches(PyExc_ImportError)) { - /* Ignore ImportErrors... this is done so that - distributions can disable the encodings package. Note - that other errors are not masked, e.g. SystemErrors - raised to inform the user of an error in the Python - configuration are still reported back to the user. */ - PyErr_Clear(); - return 0; - } - return -1; + if (PyErr_ExceptionMatches(PyExc_ImportError)) { + /* Ignore ImportErrors... this is done so that + distributions can disable the encodings package. Note + that other errors are not masked, e.g. SystemErrors + raised to inform the user of an error in the Python + configuration are still reported back to the user. */ + PyErr_Clear(); + return 0; + } + return -1; } Py_DECREF(mod); interp->codecs_initialized = 1; Modified: python/branches/py3k/Python/compile.c ============================================================================== --- python/branches/py3k/Python/compile.c (original) +++ python/branches/py3k/Python/compile.c Sun May 9 17:52:27 2010 @@ -5,10 +5,10 @@ * PyCodeObject. The compiler makes several passes to build the code * object: * 1. Checks for future statements. See future.c - * 2. Builds a symbol table. See symtable.c. + * 2. Builds a symbol table. See symtable.c. * 3. Generate code for basic blocks. See compiler_mod() in this file. * 4. Assemble the basic blocks into final code. See assemble() in - * this file. + * this file. * 5. Optimize the byte code (peephole optimizations). See peephole.c * * Note that compiler_mod() suggests module, but the module ast type @@ -45,37 +45,37 @@ #define COMP_DICTCOMP 3 struct instr { - unsigned i_jabs : 1; - unsigned i_jrel : 1; - unsigned i_hasarg : 1; - unsigned char i_opcode; - int i_oparg; - struct basicblock_ *i_target; /* target block (if jump instruction) */ - int i_lineno; + unsigned i_jabs : 1; + unsigned i_jrel : 1; + unsigned i_hasarg : 1; + unsigned char i_opcode; + int i_oparg; + struct basicblock_ *i_target; /* target block (if jump instruction) */ + int i_lineno; }; typedef struct basicblock_ { /* Each basicblock in a compilation unit is linked via b_list in the reverse order that the block are allocated. b_list points to the next block, not to be confused with b_next, which is next by control flow. */ - struct basicblock_ *b_list; - /* number of instructions used */ - int b_iused; - /* length of instruction array (b_instr) */ - int b_ialloc; - /* pointer to an array of instructions, initially NULL */ - struct instr *b_instr; - /* If b_next is non-NULL, it is a pointer to the next - block reached by normal control flow. */ - struct basicblock_ *b_next; - /* b_seen is used to perform a DFS of basicblocks. */ - unsigned b_seen : 1; - /* b_return is true if a RETURN_VALUE opcode is inserted. */ - unsigned b_return : 1; - /* depth of stack upon entry of block, computed by stackdepth() */ - int b_startdepth; - /* instruction offset for block, computed by assemble_jump_offsets() */ - int b_offset; + struct basicblock_ *b_list; + /* number of instructions used */ + int b_iused; + /* length of instruction array (b_instr) */ + int b_ialloc; + /* pointer to an array of instructions, initially NULL */ + struct instr *b_instr; + /* If b_next is non-NULL, it is a pointer to the next + block reached by normal control flow. */ + struct basicblock_ *b_next; + /* b_seen is used to perform a DFS of basicblocks. */ + unsigned b_seen : 1; + /* b_return is true if a RETURN_VALUE opcode is inserted. */ + unsigned b_return : 1; + /* depth of stack upon entry of block, computed by stackdepth() */ + int b_startdepth; + /* instruction offset for block, computed by assemble_jump_offsets() */ + int b_offset; } basicblock; /* fblockinfo tracks the current frame block. @@ -88,64 +88,64 @@ enum fblocktype { LOOP, EXCEPT, FINALLY_TRY, FINALLY_END }; struct fblockinfo { - enum fblocktype fb_type; - basicblock *fb_block; + enum fblocktype fb_type; + basicblock *fb_block; }; /* The following items change on entry and exit of code blocks. They must be saved and restored when returning to a block. */ struct compiler_unit { - PySTEntryObject *u_ste; + PySTEntryObject *u_ste; - PyObject *u_name; - /* The following fields are dicts that map objects to - the index of them in co_XXX. The index is used as - the argument for opcodes that refer to those collections. - */ - PyObject *u_consts; /* all constants */ - PyObject *u_names; /* all names */ - PyObject *u_varnames; /* local variables */ - PyObject *u_cellvars; /* cell variables */ - PyObject *u_freevars; /* free variables */ - - PyObject *u_private; /* for private name mangling */ - - int u_argcount; /* number of arguments for block */ - int u_kwonlyargcount; /* number of keyword only arguments for block */ - /* Pointer to the most recently allocated block. By following b_list - members, you can reach all early allocated blocks. */ - basicblock *u_blocks; - basicblock *u_curblock; /* pointer to current block */ - - int u_nfblocks; - struct fblockinfo u_fblock[CO_MAXBLOCKS]; - - int u_firstlineno; /* the first lineno of the block */ - int u_lineno; /* the lineno for the current stmt */ - int u_lineno_set; /* boolean to indicate whether instr - has been generated with current lineno */ + PyObject *u_name; + /* The following fields are dicts that map objects to + the index of them in co_XXX. The index is used as + the argument for opcodes that refer to those collections. + */ + PyObject *u_consts; /* all constants */ + PyObject *u_names; /* all names */ + PyObject *u_varnames; /* local variables */ + PyObject *u_cellvars; /* cell variables */ + PyObject *u_freevars; /* free variables */ + + PyObject *u_private; /* for private name mangling */ + + int u_argcount; /* number of arguments for block */ + int u_kwonlyargcount; /* number of keyword only arguments for block */ + /* Pointer to the most recently allocated block. By following b_list + members, you can reach all early allocated blocks. */ + basicblock *u_blocks; + basicblock *u_curblock; /* pointer to current block */ + + int u_nfblocks; + struct fblockinfo u_fblock[CO_MAXBLOCKS]; + + int u_firstlineno; /* the first lineno of the block */ + int u_lineno; /* the lineno for the current stmt */ + int u_lineno_set; /* boolean to indicate whether instr + has been generated with current lineno */ }; -/* This struct captures the global state of a compilation. +/* This struct captures the global state of a compilation. The u pointer points to the current compilation unit, while units -for enclosing blocks are stored in c_stack. The u and c_stack are +for enclosing blocks are stored in c_stack. The u and c_stack are managed by compiler_enter_scope() and compiler_exit_scope(). */ struct compiler { - const char *c_filename; - struct symtable *c_st; - PyFutureFeatures *c_future; /* pointer to module's __future__ */ - PyCompilerFlags *c_flags; - - int c_interactive; /* true if in interactive mode */ - int c_nestlevel; - - struct compiler_unit *u; /* compiler state for current block */ - PyObject *c_stack; /* Python list holding compiler_unit ptrs */ - PyArena *c_arena; /* pointer to memory allocation arena */ + const char *c_filename; + struct symtable *c_st; + PyFutureFeatures *c_future; /* pointer to module's __future__ */ + PyCompilerFlags *c_flags; + + int c_interactive; /* true if in interactive mode */ + int c_nestlevel; + + struct compiler_unit *u; /* compiler state for current block */ + PyObject *c_stack; /* Python list holding compiler_unit ptrs */ + PyArena *c_arena; /* pointer to memory allocation arena */ }; static int compiler_enter_scope(struct compiler *, identifier, void *, int); @@ -166,12 +166,12 @@ static int compiler_visit_expr(struct compiler *, expr_ty); static int compiler_augassign(struct compiler *, stmt_ty); static int compiler_visit_slice(struct compiler *, slice_ty, - expr_context_ty); + expr_context_ty); static int compiler_push_fblock(struct compiler *, enum fblocktype, - basicblock *); + basicblock *); static void compiler_pop_fblock(struct compiler *, enum fblocktype, - basicblock *); + basicblock *); /* Returns true if there is a loop on the fblock stack. */ static int compiler_in_loop(struct compiler *); @@ -180,10 +180,10 @@ static int compiler_with(struct compiler *, stmt_ty); static int compiler_call_helper(struct compiler *c, int n, - asdl_seq *args, - asdl_seq *keywords, - expr_ty starargs, - expr_ty kwargs); + asdl_seq *args, + asdl_seq *keywords, + expr_ty starargs, + expr_ty kwargs); static PyCodeObject *assemble(struct compiler *, int addNone); static PyObject *__doc__; @@ -193,172 +193,172 @@ PyObject * _Py_Mangle(PyObject *privateobj, PyObject *ident) { - /* Name mangling: __private becomes _classname__private. - This is independent from how the name is used. */ - const Py_UNICODE *p, *name = PyUnicode_AS_UNICODE(ident); - Py_UNICODE *buffer; - size_t nlen, plen; - if (privateobj == NULL || !PyUnicode_Check(privateobj) || - name == NULL || name[0] != '_' || name[1] != '_') { - Py_INCREF(ident); - return ident; - } - p = PyUnicode_AS_UNICODE(privateobj); - nlen = Py_UNICODE_strlen(name); - /* Don't mangle __id__ or names with dots. - - The only time a name with a dot can occur is when - we are compiling an import statement that has a - package name. - - TODO(jhylton): Decide whether we want to support - mangling of the module name, e.g. __M.X. - */ - if ((name[nlen-1] == '_' && name[nlen-2] == '_') - || Py_UNICODE_strchr(name, '.')) { - Py_INCREF(ident); - return ident; /* Don't mangle __whatever__ */ - } - /* Strip leading underscores from class name */ - while (*p == '_') - p++; - if (*p == 0) { - Py_INCREF(ident); - return ident; /* Don't mangle if class is just underscores */ - } - plen = Py_UNICODE_strlen(p); - - assert(1 <= PY_SSIZE_T_MAX - nlen); - assert(1 + nlen <= PY_SSIZE_T_MAX - plen); - - ident = PyUnicode_FromStringAndSize(NULL, 1 + nlen + plen); - if (!ident) - return 0; - /* ident = "_" + p[:plen] + name # i.e. 1+plen+nlen bytes */ - buffer = PyUnicode_AS_UNICODE(ident); - buffer[0] = '_'; - Py_UNICODE_strncpy(buffer+1, p, plen); - Py_UNICODE_strcpy(buffer+1+plen, name); - return ident; + /* Name mangling: __private becomes _classname__private. + This is independent from how the name is used. */ + const Py_UNICODE *p, *name = PyUnicode_AS_UNICODE(ident); + Py_UNICODE *buffer; + size_t nlen, plen; + if (privateobj == NULL || !PyUnicode_Check(privateobj) || + name == NULL || name[0] != '_' || name[1] != '_') { + Py_INCREF(ident); + return ident; + } + p = PyUnicode_AS_UNICODE(privateobj); + nlen = Py_UNICODE_strlen(name); + /* Don't mangle __id__ or names with dots. + + The only time a name with a dot can occur is when + we are compiling an import statement that has a + package name. + + TODO(jhylton): Decide whether we want to support + mangling of the module name, e.g. __M.X. + */ + if ((name[nlen-1] == '_' && name[nlen-2] == '_') + || Py_UNICODE_strchr(name, '.')) { + Py_INCREF(ident); + return ident; /* Don't mangle __whatever__ */ + } + /* Strip leading underscores from class name */ + while (*p == '_') + p++; + if (*p == 0) { + Py_INCREF(ident); + return ident; /* Don't mangle if class is just underscores */ + } + plen = Py_UNICODE_strlen(p); + + assert(1 <= PY_SSIZE_T_MAX - nlen); + assert(1 + nlen <= PY_SSIZE_T_MAX - plen); + + ident = PyUnicode_FromStringAndSize(NULL, 1 + nlen + plen); + if (!ident) + return 0; + /* ident = "_" + p[:plen] + name # i.e. 1+plen+nlen bytes */ + buffer = PyUnicode_AS_UNICODE(ident); + buffer[0] = '_'; + Py_UNICODE_strncpy(buffer+1, p, plen); + Py_UNICODE_strcpy(buffer+1+plen, name); + return ident; } static int compiler_init(struct compiler *c) { - memset(c, 0, sizeof(struct compiler)); + memset(c, 0, sizeof(struct compiler)); - c->c_stack = PyList_New(0); - if (!c->c_stack) - return 0; + c->c_stack = PyList_New(0); + if (!c->c_stack) + return 0; - return 1; + return 1; } PyCodeObject * PyAST_Compile(mod_ty mod, const char *filename, PyCompilerFlags *flags, - PyArena *arena) + PyArena *arena) { - struct compiler c; - PyCodeObject *co = NULL; - PyCompilerFlags local_flags; - int merged; - - if (!__doc__) { - __doc__ = PyUnicode_InternFromString("__doc__"); - if (!__doc__) - return NULL; - } - - if (!compiler_init(&c)) - return NULL; - c.c_filename = filename; - c.c_arena = arena; - c.c_future = PyFuture_FromAST(mod, filename); - if (c.c_future == NULL) - goto finally; - if (!flags) { - local_flags.cf_flags = 0; - flags = &local_flags; - } - merged = c.c_future->ff_features | flags->cf_flags; - c.c_future->ff_features = merged; - flags->cf_flags = merged; - c.c_flags = flags; - c.c_nestlevel = 0; - - c.c_st = PySymtable_Build(mod, filename, c.c_future); - if (c.c_st == NULL) { - if (!PyErr_Occurred()) - PyErr_SetString(PyExc_SystemError, "no symtable"); - goto finally; - } + struct compiler c; + PyCodeObject *co = NULL; + PyCompilerFlags local_flags; + int merged; + + if (!__doc__) { + __doc__ = PyUnicode_InternFromString("__doc__"); + if (!__doc__) + return NULL; + } + + if (!compiler_init(&c)) + return NULL; + c.c_filename = filename; + c.c_arena = arena; + c.c_future = PyFuture_FromAST(mod, filename); + if (c.c_future == NULL) + goto finally; + if (!flags) { + local_flags.cf_flags = 0; + flags = &local_flags; + } + merged = c.c_future->ff_features | flags->cf_flags; + c.c_future->ff_features = merged; + flags->cf_flags = merged; + c.c_flags = flags; + c.c_nestlevel = 0; + + c.c_st = PySymtable_Build(mod, filename, c.c_future); + if (c.c_st == NULL) { + if (!PyErr_Occurred()) + PyErr_SetString(PyExc_SystemError, "no symtable"); + goto finally; + } - co = compiler_mod(&c, mod); + co = compiler_mod(&c, mod); finally: - compiler_free(&c); - assert(co || PyErr_Occurred()); - return co; + compiler_free(&c); + assert(co || PyErr_Occurred()); + return co; } PyCodeObject * PyNode_Compile(struct _node *n, const char *filename) { - PyCodeObject *co = NULL; - mod_ty mod; - PyArena *arena = PyArena_New(); - if (!arena) - return NULL; - mod = PyAST_FromNode(n, NULL, filename, arena); - if (mod) - co = PyAST_Compile(mod, filename, NULL, arena); - PyArena_Free(arena); - return co; + PyCodeObject *co = NULL; + mod_ty mod; + PyArena *arena = PyArena_New(); + if (!arena) + return NULL; + mod = PyAST_FromNode(n, NULL, filename, arena); + if (mod) + co = PyAST_Compile(mod, filename, NULL, arena); + PyArena_Free(arena); + return co; } static void compiler_free(struct compiler *c) { - if (c->c_st) - PySymtable_Free(c->c_st); - if (c->c_future) - PyObject_Free(c->c_future); - Py_DECREF(c->c_stack); + if (c->c_st) + PySymtable_Free(c->c_st); + if (c->c_future) + PyObject_Free(c->c_future); + Py_DECREF(c->c_stack); } static PyObject * list2dict(PyObject *list) { - Py_ssize_t i, n; - PyObject *v, *k; - PyObject *dict = PyDict_New(); - if (!dict) return NULL; - - n = PyList_Size(list); - for (i = 0; i < n; i++) { - v = PyLong_FromLong(i); - if (!v) { - Py_DECREF(dict); - return NULL; - } - k = PyList_GET_ITEM(list, i); - k = PyTuple_Pack(2, k, k->ob_type); - if (k == NULL || PyDict_SetItem(dict, k, v) < 0) { - Py_XDECREF(k); - Py_DECREF(v); - Py_DECREF(dict); - return NULL; - } - Py_DECREF(k); - Py_DECREF(v); - } - return dict; + Py_ssize_t i, n; + PyObject *v, *k; + PyObject *dict = PyDict_New(); + if (!dict) return NULL; + + n = PyList_Size(list); + for (i = 0; i < n; i++) { + v = PyLong_FromLong(i); + if (!v) { + Py_DECREF(dict); + return NULL; + } + k = PyList_GET_ITEM(list, i); + k = PyTuple_Pack(2, k, k->ob_type); + if (k == NULL || PyDict_SetItem(dict, k, v) < 0) { + Py_XDECREF(k); + Py_DECREF(v); + Py_DECREF(dict); + return NULL; + } + Py_DECREF(k); + Py_DECREF(v); + } + return dict; } /* Return new dict containing names from src that match scope(s). src is a symbol table dictionary. If the scope of a name matches -either scope_type or flag is set, insert it into the new dict. The +either scope_type or flag is set, insert it into the new dict. The values are integers, starting at offset and increasing by one for each key. */ @@ -366,182 +366,182 @@ static PyObject * dictbytype(PyObject *src, int scope_type, int flag, int offset) { - Py_ssize_t pos = 0, i = offset, scope; - PyObject *k, *v, *dest = PyDict_New(); + Py_ssize_t pos = 0, i = offset, scope; + PyObject *k, *v, *dest = PyDict_New(); - assert(offset >= 0); - if (dest == NULL) - return NULL; - - while (PyDict_Next(src, &pos, &k, &v)) { - /* XXX this should probably be a macro in symtable.h */ - long vi; - assert(PyLong_Check(v)); - vi = PyLong_AS_LONG(v); - scope = (vi >> SCOPE_OFFSET) & SCOPE_MASK; - - if (scope == scope_type || vi & flag) { - PyObject *tuple, *item = PyLong_FromLong(i); - if (item == NULL) { - Py_DECREF(dest); - return NULL; - } - i++; - tuple = PyTuple_Pack(2, k, k->ob_type); - if (!tuple || PyDict_SetItem(dest, tuple, item) < 0) { - Py_DECREF(item); - Py_DECREF(dest); - Py_XDECREF(tuple); - return NULL; - } - Py_DECREF(item); - Py_DECREF(tuple); - } - } - return dest; + assert(offset >= 0); + if (dest == NULL) + return NULL; + + while (PyDict_Next(src, &pos, &k, &v)) { + /* XXX this should probably be a macro in symtable.h */ + long vi; + assert(PyLong_Check(v)); + vi = PyLong_AS_LONG(v); + scope = (vi >> SCOPE_OFFSET) & SCOPE_MASK; + + if (scope == scope_type || vi & flag) { + PyObject *tuple, *item = PyLong_FromLong(i); + if (item == NULL) { + Py_DECREF(dest); + return NULL; + } + i++; + tuple = PyTuple_Pack(2, k, k->ob_type); + if (!tuple || PyDict_SetItem(dest, tuple, item) < 0) { + Py_DECREF(item); + Py_DECREF(dest); + Py_XDECREF(tuple); + return NULL; + } + Py_DECREF(item); + Py_DECREF(tuple); + } + } + return dest; } static void compiler_unit_check(struct compiler_unit *u) { - basicblock *block; - for (block = u->u_blocks; block != NULL; block = block->b_list) { - assert((void *)block != (void *)0xcbcbcbcb); - assert((void *)block != (void *)0xfbfbfbfb); - assert((void *)block != (void *)0xdbdbdbdb); - if (block->b_instr != NULL) { - assert(block->b_ialloc > 0); - assert(block->b_iused > 0); - assert(block->b_ialloc >= block->b_iused); - } - else { - assert (block->b_iused == 0); - assert (block->b_ialloc == 0); - } - } + basicblock *block; + for (block = u->u_blocks; block != NULL; block = block->b_list) { + assert((void *)block != (void *)0xcbcbcbcb); + assert((void *)block != (void *)0xfbfbfbfb); + assert((void *)block != (void *)0xdbdbdbdb); + if (block->b_instr != NULL) { + assert(block->b_ialloc > 0); + assert(block->b_iused > 0); + assert(block->b_ialloc >= block->b_iused); + } + else { + assert (block->b_iused == 0); + assert (block->b_ialloc == 0); + } + } } static void compiler_unit_free(struct compiler_unit *u) { - basicblock *b, *next; + basicblock *b, *next; - compiler_unit_check(u); - b = u->u_blocks; - while (b != NULL) { - if (b->b_instr) - PyObject_Free((void *)b->b_instr); - next = b->b_list; - PyObject_Free((void *)b); - b = next; - } - Py_CLEAR(u->u_ste); - Py_CLEAR(u->u_name); - Py_CLEAR(u->u_consts); - Py_CLEAR(u->u_names); - Py_CLEAR(u->u_varnames); - Py_CLEAR(u->u_freevars); - Py_CLEAR(u->u_cellvars); - Py_CLEAR(u->u_private); - PyObject_Free(u); + compiler_unit_check(u); + b = u->u_blocks; + while (b != NULL) { + if (b->b_instr) + PyObject_Free((void *)b->b_instr); + next = b->b_list; + PyObject_Free((void *)b); + b = next; + } + Py_CLEAR(u->u_ste); + Py_CLEAR(u->u_name); + Py_CLEAR(u->u_consts); + Py_CLEAR(u->u_names); + Py_CLEAR(u->u_varnames); + Py_CLEAR(u->u_freevars); + Py_CLEAR(u->u_cellvars); + Py_CLEAR(u->u_private); + PyObject_Free(u); } static int compiler_enter_scope(struct compiler *c, identifier name, void *key, - int lineno) + int lineno) { - struct compiler_unit *u; + struct compiler_unit *u; - u = (struct compiler_unit *)PyObject_Malloc(sizeof( - struct compiler_unit)); - if (!u) { - PyErr_NoMemory(); - return 0; - } - memset(u, 0, sizeof(struct compiler_unit)); - u->u_argcount = 0; - u->u_kwonlyargcount = 0; - u->u_ste = PySymtable_Lookup(c->c_st, key); - if (!u->u_ste) { - compiler_unit_free(u); - return 0; - } - Py_INCREF(name); - u->u_name = name; - u->u_varnames = list2dict(u->u_ste->ste_varnames); - u->u_cellvars = dictbytype(u->u_ste->ste_symbols, CELL, 0, 0); - if (!u->u_varnames || !u->u_cellvars) { - compiler_unit_free(u); - return 0; - } - - u->u_freevars = dictbytype(u->u_ste->ste_symbols, FREE, DEF_FREE_CLASS, - PyDict_Size(u->u_cellvars)); - if (!u->u_freevars) { - compiler_unit_free(u); - return 0; - } - - u->u_blocks = NULL; - u->u_nfblocks = 0; - u->u_firstlineno = lineno; - u->u_lineno = 0; - u->u_lineno_set = 0; - u->u_consts = PyDict_New(); - if (!u->u_consts) { - compiler_unit_free(u); - return 0; - } - u->u_names = PyDict_New(); - if (!u->u_names) { - compiler_unit_free(u); - return 0; - } - - u->u_private = NULL; - - /* Push the old compiler_unit on the stack. */ - if (c->u) { - PyObject *capsule = PyCapsule_New(c->u, COMPILER_CAPSULE_NAME_COMPILER_UNIT, NULL); - if (!capsule || PyList_Append(c->c_stack, capsule) < 0) { - Py_XDECREF(capsule); - compiler_unit_free(u); - return 0; - } - Py_DECREF(capsule); - u->u_private = c->u->u_private; - Py_XINCREF(u->u_private); - } - c->u = u; - - c->c_nestlevel++; - if (compiler_use_new_block(c) == NULL) - return 0; + u = (struct compiler_unit *)PyObject_Malloc(sizeof( + struct compiler_unit)); + if (!u) { + PyErr_NoMemory(); + return 0; + } + memset(u, 0, sizeof(struct compiler_unit)); + u->u_argcount = 0; + u->u_kwonlyargcount = 0; + u->u_ste = PySymtable_Lookup(c->c_st, key); + if (!u->u_ste) { + compiler_unit_free(u); + return 0; + } + Py_INCREF(name); + u->u_name = name; + u->u_varnames = list2dict(u->u_ste->ste_varnames); + u->u_cellvars = dictbytype(u->u_ste->ste_symbols, CELL, 0, 0); + if (!u->u_varnames || !u->u_cellvars) { + compiler_unit_free(u); + return 0; + } + + u->u_freevars = dictbytype(u->u_ste->ste_symbols, FREE, DEF_FREE_CLASS, + PyDict_Size(u->u_cellvars)); + if (!u->u_freevars) { + compiler_unit_free(u); + return 0; + } + + u->u_blocks = NULL; + u->u_nfblocks = 0; + u->u_firstlineno = lineno; + u->u_lineno = 0; + u->u_lineno_set = 0; + u->u_consts = PyDict_New(); + if (!u->u_consts) { + compiler_unit_free(u); + return 0; + } + u->u_names = PyDict_New(); + if (!u->u_names) { + compiler_unit_free(u); + return 0; + } + + u->u_private = NULL; + + /* Push the old compiler_unit on the stack. */ + if (c->u) { + PyObject *capsule = PyCapsule_New(c->u, COMPILER_CAPSULE_NAME_COMPILER_UNIT, NULL); + if (!capsule || PyList_Append(c->c_stack, capsule) < 0) { + Py_XDECREF(capsule); + compiler_unit_free(u); + return 0; + } + Py_DECREF(capsule); + u->u_private = c->u->u_private; + Py_XINCREF(u->u_private); + } + c->u = u; + + c->c_nestlevel++; + if (compiler_use_new_block(c) == NULL) + return 0; - return 1; + return 1; } static void compiler_exit_scope(struct compiler *c) { - int n; - PyObject *capsule; + int n; + PyObject *capsule; - c->c_nestlevel--; - compiler_unit_free(c->u); - /* Restore c->u to the parent unit. */ - n = PyList_GET_SIZE(c->c_stack) - 1; - if (n >= 0) { - capsule = PyList_GET_ITEM(c->c_stack, n); - c->u = (struct compiler_unit *)PyCapsule_GetPointer(capsule, COMPILER_CAPSULE_NAME_COMPILER_UNIT); - assert(c->u); - /* we are deleting from a list so this really shouldn't fail */ - if (PySequence_DelItem(c->c_stack, n) < 0) - Py_FatalError("compiler_exit_scope()"); - compiler_unit_check(c->u); - } - else - c->u = NULL; + c->c_nestlevel--; + compiler_unit_free(c->u); + /* Restore c->u to the parent unit. */ + n = PyList_GET_SIZE(c->c_stack) - 1; + if (n >= 0) { + capsule = PyList_GET_ITEM(c->c_stack, n); + c->u = (struct compiler_unit *)PyCapsule_GetPointer(capsule, COMPILER_CAPSULE_NAME_COMPILER_UNIT); + assert(c->u); + /* we are deleting from a list so this really shouldn't fail */ + if (PySequence_DelItem(c->c_stack, n) < 0) + Py_FatalError("compiler_exit_scope()"); + compiler_unit_check(c->u); + } + else + c->u = NULL; } @@ -552,50 +552,50 @@ static basicblock * compiler_new_block(struct compiler *c) { - basicblock *b; - struct compiler_unit *u; + basicblock *b; + struct compiler_unit *u; - u = c->u; - b = (basicblock *)PyObject_Malloc(sizeof(basicblock)); - if (b == NULL) { - PyErr_NoMemory(); - return NULL; - } - memset((void *)b, 0, sizeof(basicblock)); - /* Extend the singly linked list of blocks with new block. */ - b->b_list = u->u_blocks; - u->u_blocks = b; - return b; + u = c->u; + b = (basicblock *)PyObject_Malloc(sizeof(basicblock)); + if (b == NULL) { + PyErr_NoMemory(); + return NULL; + } + memset((void *)b, 0, sizeof(basicblock)); + /* Extend the singly linked list of blocks with new block. */ + b->b_list = u->u_blocks; + u->u_blocks = b; + return b; } static basicblock * compiler_use_new_block(struct compiler *c) { - basicblock *block = compiler_new_block(c); - if (block == NULL) - return NULL; - c->u->u_curblock = block; - return block; + basicblock *block = compiler_new_block(c); + if (block == NULL) + return NULL; + c->u->u_curblock = block; + return block; } static basicblock * compiler_next_block(struct compiler *c) { - basicblock *block = compiler_new_block(c); - if (block == NULL) - return NULL; - c->u->u_curblock->b_next = block; - c->u->u_curblock = block; - return block; + basicblock *block = compiler_new_block(c); + if (block == NULL) + return NULL; + c->u->u_curblock->b_next = block; + c->u->u_curblock = block; + return block; } static basicblock * compiler_use_next_block(struct compiler *c, basicblock *block) { - assert(block != NULL); - c->u->u_curblock->b_next = block; - c->u->u_curblock = block; - return block; + assert(block != NULL); + c->u->u_curblock->b_next = block; + c->u->u_curblock = block; + return block; } /* Returns the offset of the next instruction in the current block's @@ -606,44 +606,44 @@ static int compiler_next_instr(struct compiler *c, basicblock *b) { - assert(b != NULL); - if (b->b_instr == NULL) { - b->b_instr = (struct instr *)PyObject_Malloc( - sizeof(struct instr) * DEFAULT_BLOCK_SIZE); - if (b->b_instr == NULL) { - PyErr_NoMemory(); - return -1; - } - b->b_ialloc = DEFAULT_BLOCK_SIZE; - memset((char *)b->b_instr, 0, - sizeof(struct instr) * DEFAULT_BLOCK_SIZE); - } - else if (b->b_iused == b->b_ialloc) { - struct instr *tmp; - size_t oldsize, newsize; - oldsize = b->b_ialloc * sizeof(struct instr); - newsize = oldsize << 1; - - if (oldsize > (PY_SIZE_MAX >> 1)) { - PyErr_NoMemory(); - return -1; - } - - if (newsize == 0) { - PyErr_NoMemory(); - return -1; - } - b->b_ialloc <<= 1; - tmp = (struct instr *)PyObject_Realloc( - (void *)b->b_instr, newsize); - if (tmp == NULL) { - PyErr_NoMemory(); - return -1; - } - b->b_instr = tmp; - memset((char *)b->b_instr + oldsize, 0, newsize - oldsize); - } - return b->b_iused++; + assert(b != NULL); + if (b->b_instr == NULL) { + b->b_instr = (struct instr *)PyObject_Malloc( + sizeof(struct instr) * DEFAULT_BLOCK_SIZE); + if (b->b_instr == NULL) { + PyErr_NoMemory(); + return -1; + } + b->b_ialloc = DEFAULT_BLOCK_SIZE; + memset((char *)b->b_instr, 0, + sizeof(struct instr) * DEFAULT_BLOCK_SIZE); + } + else if (b->b_iused == b->b_ialloc) { + struct instr *tmp; + size_t oldsize, newsize; + oldsize = b->b_ialloc * sizeof(struct instr); + newsize = oldsize << 1; + + if (oldsize > (PY_SIZE_MAX >> 1)) { + PyErr_NoMemory(); + return -1; + } + + if (newsize == 0) { + PyErr_NoMemory(); + return -1; + } + b->b_ialloc <<= 1; + tmp = (struct instr *)PyObject_Realloc( + (void *)b->b_instr, newsize); + if (tmp == NULL) { + PyErr_NoMemory(); + return -1; + } + b->b_instr = tmp; + memset((char *)b->b_instr + oldsize, 0, newsize - oldsize); + } + return b->b_iused++; } /* Set the i_lineno member of the instruction at offset off if the @@ -661,210 +661,210 @@ static void compiler_set_lineno(struct compiler *c, int off) { - basicblock *b; - if (c->u->u_lineno_set) - return; - c->u->u_lineno_set = 1; - b = c->u->u_curblock; - b->b_instr[off].i_lineno = c->u->u_lineno; + basicblock *b; + if (c->u->u_lineno_set) + return; + c->u->u_lineno_set = 1; + b = c->u->u_curblock; + b->b_instr[off].i_lineno = c->u->u_lineno; } static int opcode_stack_effect(int opcode, int oparg) { - switch (opcode) { - case POP_TOP: - return -1; - case ROT_TWO: - case ROT_THREE: - return 0; - case DUP_TOP: - return 1; - case ROT_FOUR: - return 0; - - case UNARY_POSITIVE: - case UNARY_NEGATIVE: - case UNARY_NOT: - case UNARY_INVERT: - return 0; - - case SET_ADD: - case LIST_APPEND: - return -1; - case MAP_ADD: - return -2; - - case BINARY_POWER: - case BINARY_MULTIPLY: - case BINARY_MODULO: - case BINARY_ADD: - case BINARY_SUBTRACT: - case BINARY_SUBSCR: - case BINARY_FLOOR_DIVIDE: - case BINARY_TRUE_DIVIDE: - return -1; - case INPLACE_FLOOR_DIVIDE: - case INPLACE_TRUE_DIVIDE: - return -1; - - case INPLACE_ADD: - case INPLACE_SUBTRACT: - case INPLACE_MULTIPLY: - case INPLACE_MODULO: - return -1; - case STORE_SUBSCR: - return -3; - case STORE_MAP: - return -2; - case DELETE_SUBSCR: - return -2; - - case BINARY_LSHIFT: - case BINARY_RSHIFT: - case BINARY_AND: - case BINARY_XOR: - case BINARY_OR: - return -1; - case INPLACE_POWER: - return -1; - case GET_ITER: - return 0; - - case PRINT_EXPR: - return -1; - case LOAD_BUILD_CLASS: - return 1; - case INPLACE_LSHIFT: - case INPLACE_RSHIFT: - case INPLACE_AND: - case INPLACE_XOR: - case INPLACE_OR: - return -1; - case BREAK_LOOP: - return 0; - case SETUP_WITH: - return 7; - case WITH_CLEANUP: - return -1; /* XXX Sometimes more */ - case STORE_LOCALS: - return -1; - case RETURN_VALUE: - return -1; - case IMPORT_STAR: - return -1; - case YIELD_VALUE: - return 0; - - case POP_BLOCK: - return 0; - case POP_EXCEPT: - return 0; /* -3 except if bad bytecode */ - case END_FINALLY: - return -1; /* or -2 or -3 if exception occurred */ - - case STORE_NAME: - return -1; - case DELETE_NAME: - return 0; - case UNPACK_SEQUENCE: - return oparg-1; - case UNPACK_EX: - return (oparg&0xFF) + (oparg>>8); - case FOR_ITER: - return 1; /* or -1, at end of iterator */ - - case STORE_ATTR: - return -2; - case DELETE_ATTR: - return -1; - case STORE_GLOBAL: - return -1; - case DELETE_GLOBAL: - return 0; - case DUP_TOPX: - return oparg; - case LOAD_CONST: - return 1; - case LOAD_NAME: - return 1; - case BUILD_TUPLE: - case BUILD_LIST: - case BUILD_SET: - return 1-oparg; - case BUILD_MAP: - return 1; - case LOAD_ATTR: - return 0; - case COMPARE_OP: - return -1; - case IMPORT_NAME: - return -1; - case IMPORT_FROM: - return 1; - - case JUMP_FORWARD: - case JUMP_IF_TRUE_OR_POP: /* -1 if jump not taken */ - case JUMP_IF_FALSE_OR_POP: /* "" */ - case JUMP_ABSOLUTE: - return 0; - - case POP_JUMP_IF_FALSE: - case POP_JUMP_IF_TRUE: - return -1; - - case LOAD_GLOBAL: - return 1; - - case CONTINUE_LOOP: - return 0; - case SETUP_LOOP: - return 0; - case SETUP_EXCEPT: - case SETUP_FINALLY: - return 6; /* can push 3 values for the new exception - + 3 others for the previous exception state */ - - case LOAD_FAST: - return 1; - case STORE_FAST: - return -1; - case DELETE_FAST: - return 0; + switch (opcode) { + case POP_TOP: + return -1; + case ROT_TWO: + case ROT_THREE: + return 0; + case DUP_TOP: + return 1; + case ROT_FOUR: + return 0; + + case UNARY_POSITIVE: + case UNARY_NEGATIVE: + case UNARY_NOT: + case UNARY_INVERT: + return 0; + + case SET_ADD: + case LIST_APPEND: + return -1; + case MAP_ADD: + return -2; + + case BINARY_POWER: + case BINARY_MULTIPLY: + case BINARY_MODULO: + case BINARY_ADD: + case BINARY_SUBTRACT: + case BINARY_SUBSCR: + case BINARY_FLOOR_DIVIDE: + case BINARY_TRUE_DIVIDE: + return -1; + case INPLACE_FLOOR_DIVIDE: + case INPLACE_TRUE_DIVIDE: + return -1; + + case INPLACE_ADD: + case INPLACE_SUBTRACT: + case INPLACE_MULTIPLY: + case INPLACE_MODULO: + return -1; + case STORE_SUBSCR: + return -3; + case STORE_MAP: + return -2; + case DELETE_SUBSCR: + return -2; + + case BINARY_LSHIFT: + case BINARY_RSHIFT: + case BINARY_AND: + case BINARY_XOR: + case BINARY_OR: + return -1; + case INPLACE_POWER: + return -1; + case GET_ITER: + return 0; + + case PRINT_EXPR: + return -1; + case LOAD_BUILD_CLASS: + return 1; + case INPLACE_LSHIFT: + case INPLACE_RSHIFT: + case INPLACE_AND: + case INPLACE_XOR: + case INPLACE_OR: + return -1; + case BREAK_LOOP: + return 0; + case SETUP_WITH: + return 7; + case WITH_CLEANUP: + return -1; /* XXX Sometimes more */ + case STORE_LOCALS: + return -1; + case RETURN_VALUE: + return -1; + case IMPORT_STAR: + return -1; + case YIELD_VALUE: + return 0; + + case POP_BLOCK: + return 0; + case POP_EXCEPT: + return 0; /* -3 except if bad bytecode */ + case END_FINALLY: + return -1; /* or -2 or -3 if exception occurred */ + + case STORE_NAME: + return -1; + case DELETE_NAME: + return 0; + case UNPACK_SEQUENCE: + return oparg-1; + case UNPACK_EX: + return (oparg&0xFF) + (oparg>>8); + case FOR_ITER: + return 1; /* or -1, at end of iterator */ + + case STORE_ATTR: + return -2; + case DELETE_ATTR: + return -1; + case STORE_GLOBAL: + return -1; + case DELETE_GLOBAL: + return 0; + case DUP_TOPX: + return oparg; + case LOAD_CONST: + return 1; + case LOAD_NAME: + return 1; + case BUILD_TUPLE: + case BUILD_LIST: + case BUILD_SET: + return 1-oparg; + case BUILD_MAP: + return 1; + case LOAD_ATTR: + return 0; + case COMPARE_OP: + return -1; + case IMPORT_NAME: + return -1; + case IMPORT_FROM: + return 1; + + case JUMP_FORWARD: + case JUMP_IF_TRUE_OR_POP: /* -1 if jump not taken */ + case JUMP_IF_FALSE_OR_POP: /* "" */ + case JUMP_ABSOLUTE: + return 0; + + case POP_JUMP_IF_FALSE: + case POP_JUMP_IF_TRUE: + return -1; + + case LOAD_GLOBAL: + return 1; + + case CONTINUE_LOOP: + return 0; + case SETUP_LOOP: + return 0; + case SETUP_EXCEPT: + case SETUP_FINALLY: + return 6; /* can push 3 values for the new exception + + 3 others for the previous exception state */ + + case LOAD_FAST: + return 1; + case STORE_FAST: + return -1; + case DELETE_FAST: + return 0; - case RAISE_VARARGS: - return -oparg; + case RAISE_VARARGS: + return -oparg; #define NARGS(o) (((o) % 256) + 2*(((o) / 256) % 256)) - case CALL_FUNCTION: - return -NARGS(oparg); - case CALL_FUNCTION_VAR: - case CALL_FUNCTION_KW: - return -NARGS(oparg)-1; - case CALL_FUNCTION_VAR_KW: - return -NARGS(oparg)-2; - case MAKE_FUNCTION: - return -NARGS(oparg) - ((oparg >> 16) & 0xffff); - case MAKE_CLOSURE: - return -1 - NARGS(oparg) - ((oparg >> 16) & 0xffff); + case CALL_FUNCTION: + return -NARGS(oparg); + case CALL_FUNCTION_VAR: + case CALL_FUNCTION_KW: + return -NARGS(oparg)-1; + case CALL_FUNCTION_VAR_KW: + return -NARGS(oparg)-2; + case MAKE_FUNCTION: + return -NARGS(oparg) - ((oparg >> 16) & 0xffff); + case MAKE_CLOSURE: + return -1 - NARGS(oparg) - ((oparg >> 16) & 0xffff); #undef NARGS - case BUILD_SLICE: - if (oparg == 3) - return -2; - else - return -1; - - case LOAD_CLOSURE: - return 1; - case LOAD_DEREF: - return 1; - case STORE_DEREF: - return -1; - default: - fprintf(stderr, "opcode = %d\n", opcode); - Py_FatalError("opcode_stack_effect()"); + case BUILD_SLICE: + if (oparg == 3) + return -2; + else + return -1; + + case LOAD_CLOSURE: + return 1; + case LOAD_DEREF: + return 1; + case STORE_DEREF: + return -1; + default: + fprintf(stderr, "opcode = %d\n", opcode); + Py_FatalError("opcode_stack_effect()"); - } - return 0; /* not reachable */ + } + return 0; /* not reachable */ } /* Add an opcode with no argument. @@ -874,116 +874,116 @@ static int compiler_addop(struct compiler *c, int opcode) { - basicblock *b; - struct instr *i; - int off; - off = compiler_next_instr(c, c->u->u_curblock); - if (off < 0) - return 0; - b = c->u->u_curblock; - i = &b->b_instr[off]; - i->i_opcode = opcode; - i->i_hasarg = 0; - if (opcode == RETURN_VALUE) - b->b_return = 1; - compiler_set_lineno(c, off); - return 1; + basicblock *b; + struct instr *i; + int off; + off = compiler_next_instr(c, c->u->u_curblock); + if (off < 0) + return 0; + b = c->u->u_curblock; + i = &b->b_instr[off]; + i->i_opcode = opcode; + i->i_hasarg = 0; + if (opcode == RETURN_VALUE) + b->b_return = 1; + compiler_set_lineno(c, off); + return 1; } static int compiler_add_o(struct compiler *c, PyObject *dict, PyObject *o) { - PyObject *t, *v; - Py_ssize_t arg; - double d; - - /* necessary to make sure types aren't coerced (e.g., int and long) */ - /* _and_ to distinguish 0.0 from -0.0 e.g. on IEEE platforms */ - if (PyFloat_Check(o)) { - d = PyFloat_AS_DOUBLE(o); - /* all we need is to make the tuple different in either the 0.0 - * or -0.0 case from all others, just to avoid the "coercion". - */ - if (d == 0.0 && copysign(1.0, d) < 0.0) - t = PyTuple_Pack(3, o, o->ob_type, Py_None); - else - t = PyTuple_Pack(2, o, o->ob_type); - } - else if (PyComplex_Check(o)) { - Py_complex z; - int real_negzero, imag_negzero; - /* For the complex case we must make complex(x, 0.) - different from complex(x, -0.) and complex(0., y) - different from complex(-0., y), for any x and y. - All four complex zeros must be distinguished.*/ - z = PyComplex_AsCComplex(o); - real_negzero = z.real == 0.0 && copysign(1.0, z.real) < 0.0; - imag_negzero = z.imag == 0.0 && copysign(1.0, z.imag) < 0.0; - if (real_negzero && imag_negzero) { - t = PyTuple_Pack(5, o, o->ob_type, - Py_None, Py_None, Py_None); - } - else if (imag_negzero) { - t = PyTuple_Pack(4, o, o->ob_type, Py_None, Py_None); - } - else if (real_negzero) { - t = PyTuple_Pack(3, o, o->ob_type, Py_None); - } - else { - t = PyTuple_Pack(2, o, o->ob_type); - } - } - else { - t = PyTuple_Pack(2, o, o->ob_type); - } - if (t == NULL) - return -1; - - v = PyDict_GetItem(dict, t); - if (!v) { - if (PyErr_Occurred()) - return -1; - arg = PyDict_Size(dict); - v = PyLong_FromLong(arg); - if (!v) { - Py_DECREF(t); - return -1; - } - if (PyDict_SetItem(dict, t, v) < 0) { - Py_DECREF(t); - Py_DECREF(v); - return -1; - } - Py_DECREF(v); - } - else - arg = PyLong_AsLong(v); - Py_DECREF(t); - return arg; + PyObject *t, *v; + Py_ssize_t arg; + double d; + + /* necessary to make sure types aren't coerced (e.g., int and long) */ + /* _and_ to distinguish 0.0 from -0.0 e.g. on IEEE platforms */ + if (PyFloat_Check(o)) { + d = PyFloat_AS_DOUBLE(o); + /* all we need is to make the tuple different in either the 0.0 + * or -0.0 case from all others, just to avoid the "coercion". + */ + if (d == 0.0 && copysign(1.0, d) < 0.0) + t = PyTuple_Pack(3, o, o->ob_type, Py_None); + else + t = PyTuple_Pack(2, o, o->ob_type); + } + else if (PyComplex_Check(o)) { + Py_complex z; + int real_negzero, imag_negzero; + /* For the complex case we must make complex(x, 0.) + different from complex(x, -0.) and complex(0., y) + different from complex(-0., y), for any x and y. + All four complex zeros must be distinguished.*/ + z = PyComplex_AsCComplex(o); + real_negzero = z.real == 0.0 && copysign(1.0, z.real) < 0.0; + imag_negzero = z.imag == 0.0 && copysign(1.0, z.imag) < 0.0; + if (real_negzero && imag_negzero) { + t = PyTuple_Pack(5, o, o->ob_type, + Py_None, Py_None, Py_None); + } + else if (imag_negzero) { + t = PyTuple_Pack(4, o, o->ob_type, Py_None, Py_None); + } + else if (real_negzero) { + t = PyTuple_Pack(3, o, o->ob_type, Py_None); + } + else { + t = PyTuple_Pack(2, o, o->ob_type); + } + } + else { + t = PyTuple_Pack(2, o, o->ob_type); + } + if (t == NULL) + return -1; + + v = PyDict_GetItem(dict, t); + if (!v) { + if (PyErr_Occurred()) + return -1; + arg = PyDict_Size(dict); + v = PyLong_FromLong(arg); + if (!v) { + Py_DECREF(t); + return -1; + } + if (PyDict_SetItem(dict, t, v) < 0) { + Py_DECREF(t); + Py_DECREF(v); + return -1; + } + Py_DECREF(v); + } + else + arg = PyLong_AsLong(v); + Py_DECREF(t); + return arg; } static int compiler_addop_o(struct compiler *c, int opcode, PyObject *dict, - PyObject *o) + PyObject *o) { int arg = compiler_add_o(c, dict, o); if (arg < 0) - return 0; + return 0; return compiler_addop_i(c, opcode, arg); } static int compiler_addop_name(struct compiler *c, int opcode, PyObject *dict, - PyObject *o) + PyObject *o) { int arg; PyObject *mangled = _Py_Mangle(c->u->u_private, o); if (!mangled) - return 0; + return 0; arg = compiler_add_o(c, dict, mangled); Py_DECREF(mangled); if (arg < 0) - return 0; + return 0; return compiler_addop_i(c, opcode, arg); } @@ -994,43 +994,43 @@ static int compiler_addop_i(struct compiler *c, int opcode, int oparg) { - struct instr *i; - int off; - off = compiler_next_instr(c, c->u->u_curblock); - if (off < 0) - return 0; - i = &c->u->u_curblock->b_instr[off]; - i->i_opcode = opcode; - i->i_oparg = oparg; - i->i_hasarg = 1; - compiler_set_lineno(c, off); - return 1; + struct instr *i; + int off; + off = compiler_next_instr(c, c->u->u_curblock); + if (off < 0) + return 0; + i = &c->u->u_curblock->b_instr[off]; + i->i_opcode = opcode; + i->i_oparg = oparg; + i->i_hasarg = 1; + compiler_set_lineno(c, off); + return 1; } static int compiler_addop_j(struct compiler *c, int opcode, basicblock *b, int absolute) { - struct instr *i; - int off; + struct instr *i; + int off; - assert(b != NULL); - off = compiler_next_instr(c, c->u->u_curblock); - if (off < 0) - return 0; - i = &c->u->u_curblock->b_instr[off]; - i->i_opcode = opcode; - i->i_target = b; - i->i_hasarg = 1; - if (absolute) - i->i_jabs = 1; - else - i->i_jrel = 1; - compiler_set_lineno(c, off); - return 1; + assert(b != NULL); + off = compiler_next_instr(c, c->u->u_curblock); + if (off < 0) + return 0; + i = &c->u->u_curblock->b_instr[off]; + i->i_opcode = opcode; + i->i_target = b; + i->i_hasarg = 1; + if (absolute) + i->i_jabs = 1; + else + i->i_jrel = 1; + compiler_set_lineno(c, off); + return 1; } -/* The distinction between NEW_BLOCK and NEXT_BLOCK is subtle. (I'd - like to find better names.) NEW_BLOCK() creates a new block and sets +/* The distinction between NEW_BLOCK and NEXT_BLOCK is subtle. (I'd + like to find better names.) NEW_BLOCK() creates a new block and sets it as the current block. NEXT_BLOCK() also creates an implicit jump from the current block to the new block. */ @@ -1041,50 +1041,50 @@ #define NEW_BLOCK(C) { \ - if (compiler_use_new_block((C)) == NULL) \ - return 0; \ + if (compiler_use_new_block((C)) == NULL) \ + return 0; \ } #define NEXT_BLOCK(C) { \ - if (compiler_next_block((C)) == NULL) \ - return 0; \ + if (compiler_next_block((C)) == NULL) \ + return 0; \ } #define ADDOP(C, OP) { \ - if (!compiler_addop((C), (OP))) \ - return 0; \ + if (!compiler_addop((C), (OP))) \ + return 0; \ } #define ADDOP_IN_SCOPE(C, OP) { \ - if (!compiler_addop((C), (OP))) { \ - compiler_exit_scope(c); \ - return 0; \ - } \ + if (!compiler_addop((C), (OP))) { \ + compiler_exit_scope(c); \ + return 0; \ + } \ } #define ADDOP_O(C, OP, O, TYPE) { \ - if (!compiler_addop_o((C), (OP), (C)->u->u_ ## TYPE, (O))) \ - return 0; \ + if (!compiler_addop_o((C), (OP), (C)->u->u_ ## TYPE, (O))) \ + return 0; \ } #define ADDOP_NAME(C, OP, O, TYPE) { \ - if (!compiler_addop_name((C), (OP), (C)->u->u_ ## TYPE, (O))) \ - return 0; \ + if (!compiler_addop_name((C), (OP), (C)->u->u_ ## TYPE, (O))) \ + return 0; \ } #define ADDOP_I(C, OP, O) { \ - if (!compiler_addop_i((C), (OP), (O))) \ - return 0; \ + if (!compiler_addop_i((C), (OP), (O))) \ + return 0; \ } #define ADDOP_JABS(C, OP, O) { \ - if (!compiler_addop_j((C), (OP), (O), 1)) \ - return 0; \ + if (!compiler_addop_j((C), (OP), (O), 1)) \ + return 0; \ } #define ADDOP_JREL(C, OP, O) { \ - if (!compiler_addop_j((C), (OP), (O), 0)) \ - return 0; \ + if (!compiler_addop_j((C), (OP), (O), 0)) \ + return 0; \ } /* VISIT and VISIT_SEQ takes an ASDL type as their second argument. They use @@ -1092,49 +1092,49 @@ */ #define VISIT(C, TYPE, V) {\ - if (!compiler_visit_ ## TYPE((C), (V))) \ - return 0; \ + if (!compiler_visit_ ## TYPE((C), (V))) \ + return 0; \ } #define VISIT_IN_SCOPE(C, TYPE, V) {\ - if (!compiler_visit_ ## TYPE((C), (V))) { \ - compiler_exit_scope(c); \ - return 0; \ - } \ + if (!compiler_visit_ ## TYPE((C), (V))) { \ + compiler_exit_scope(c); \ + return 0; \ + } \ } #define VISIT_SLICE(C, V, CTX) {\ - if (!compiler_visit_slice((C), (V), (CTX))) \ - return 0; \ + if (!compiler_visit_slice((C), (V), (CTX))) \ + return 0; \ } #define VISIT_SEQ(C, TYPE, SEQ) { \ - int _i; \ - asdl_seq *seq = (SEQ); /* avoid variable capture */ \ - for (_i = 0; _i < asdl_seq_LEN(seq); _i++) { \ - TYPE ## _ty elt = (TYPE ## _ty)asdl_seq_GET(seq, _i); \ - if (!compiler_visit_ ## TYPE((C), elt)) \ - return 0; \ - } \ + int _i; \ + asdl_seq *seq = (SEQ); /* avoid variable capture */ \ + for (_i = 0; _i < asdl_seq_LEN(seq); _i++) { \ + TYPE ## _ty elt = (TYPE ## _ty)asdl_seq_GET(seq, _i); \ + if (!compiler_visit_ ## TYPE((C), elt)) \ + return 0; \ + } \ } #define VISIT_SEQ_IN_SCOPE(C, TYPE, SEQ) { \ - int _i; \ - asdl_seq *seq = (SEQ); /* avoid variable capture */ \ - for (_i = 0; _i < asdl_seq_LEN(seq); _i++) { \ - TYPE ## _ty elt = (TYPE ## _ty)asdl_seq_GET(seq, _i); \ - if (!compiler_visit_ ## TYPE((C), elt)) { \ - compiler_exit_scope(c); \ - return 0; \ - } \ - } \ + int _i; \ + asdl_seq *seq = (SEQ); /* avoid variable capture */ \ + for (_i = 0; _i < asdl_seq_LEN(seq); _i++) { \ + TYPE ## _ty elt = (TYPE ## _ty)asdl_seq_GET(seq, _i); \ + if (!compiler_visit_ ## TYPE((C), elt)) { \ + compiler_exit_scope(c); \ + return 0; \ + } \ + } \ } static int compiler_isdocstring(stmt_ty s) { if (s->kind != Expr_kind) - return 0; + return 0; return s->v.Expr.value->kind == Str_kind; } @@ -1143,67 +1143,67 @@ static int compiler_body(struct compiler *c, asdl_seq *stmts) { - int i = 0; - stmt_ty st; + int i = 0; + stmt_ty st; - if (!asdl_seq_LEN(stmts)) - return 1; - st = (stmt_ty)asdl_seq_GET(stmts, 0); - if (compiler_isdocstring(st) && Py_OptimizeFlag < 2) { - /* don't generate docstrings if -OO */ - i = 1; - VISIT(c, expr, st->v.Expr.value); - if (!compiler_nameop(c, __doc__, Store)) - return 0; - } - for (; i < asdl_seq_LEN(stmts); i++) - VISIT(c, stmt, (stmt_ty)asdl_seq_GET(stmts, i)); - return 1; + if (!asdl_seq_LEN(stmts)) + return 1; + st = (stmt_ty)asdl_seq_GET(stmts, 0); + if (compiler_isdocstring(st) && Py_OptimizeFlag < 2) { + /* don't generate docstrings if -OO */ + i = 1; + VISIT(c, expr, st->v.Expr.value); + if (!compiler_nameop(c, __doc__, Store)) + return 0; + } + for (; i < asdl_seq_LEN(stmts); i++) + VISIT(c, stmt, (stmt_ty)asdl_seq_GET(stmts, i)); + return 1; } static PyCodeObject * compiler_mod(struct compiler *c, mod_ty mod) { - PyCodeObject *co; - int addNone = 1; - static PyObject *module; - if (!module) { - module = PyUnicode_InternFromString(""); - if (!module) - return NULL; - } - /* Use 0 for firstlineno initially, will fixup in assemble(). */ - if (!compiler_enter_scope(c, module, mod, 0)) - return NULL; - switch (mod->kind) { - case Module_kind: - if (!compiler_body(c, mod->v.Module.body)) { - compiler_exit_scope(c); - return 0; - } - break; - case Interactive_kind: - c->c_interactive = 1; - VISIT_SEQ_IN_SCOPE(c, stmt, - mod->v.Interactive.body); - break; - case Expression_kind: - VISIT_IN_SCOPE(c, expr, mod->v.Expression.body); - addNone = 0; - break; - case Suite_kind: - PyErr_SetString(PyExc_SystemError, - "suite should not be possible"); - return 0; - default: - PyErr_Format(PyExc_SystemError, - "module kind %d should not be possible", - mod->kind); - return 0; - } - co = assemble(c, addNone); - compiler_exit_scope(c); - return co; + PyCodeObject *co; + int addNone = 1; + static PyObject *module; + if (!module) { + module = PyUnicode_InternFromString(""); + if (!module) + return NULL; + } + /* Use 0 for firstlineno initially, will fixup in assemble(). */ + if (!compiler_enter_scope(c, module, mod, 0)) + return NULL; + switch (mod->kind) { + case Module_kind: + if (!compiler_body(c, mod->v.Module.body)) { + compiler_exit_scope(c); + return 0; + } + break; + case Interactive_kind: + c->c_interactive = 1; + VISIT_SEQ_IN_SCOPE(c, stmt, + mod->v.Interactive.body); + break; + case Expression_kind: + VISIT_IN_SCOPE(c, expr, mod->v.Expression.body); + addNone = 0; + break; + case Suite_kind: + PyErr_SetString(PyExc_SystemError, + "suite should not be possible"); + return 0; + default: + PyErr_Format(PyExc_SystemError, + "module kind %d should not be possible", + mod->kind); + return 0; + } + co = assemble(c, addNone); + compiler_exit_scope(c); + return co; } /* The test for LOCAL must come before the test for FREE in order to @@ -1214,24 +1214,24 @@ static int get_ref_type(struct compiler *c, PyObject *name) { - int scope = PyST_GetScope(c->u->u_ste, name); - if (scope == 0) { - char buf[350]; - PyOS_snprintf(buf, sizeof(buf), - "unknown scope for %.100s in %.100s(%s) in %s\n" - "symbols: %s\nlocals: %s\nglobals: %s", - PyBytes_AS_STRING(name), - PyBytes_AS_STRING(c->u->u_name), - PyObject_REPR(c->u->u_ste->ste_id), - c->c_filename, - PyObject_REPR(c->u->u_ste->ste_symbols), - PyObject_REPR(c->u->u_varnames), - PyObject_REPR(c->u->u_names) - ); - Py_FatalError(buf); - } + int scope = PyST_GetScope(c->u->u_ste, name); + if (scope == 0) { + char buf[350]; + PyOS_snprintf(buf, sizeof(buf), + "unknown scope for %.100s in %.100s(%s) in %s\n" + "symbols: %s\nlocals: %s\nglobals: %s", + PyBytes_AS_STRING(name), + PyBytes_AS_STRING(c->u->u_name), + PyObject_REPR(c->u->u_ste->ste_id), + c->c_filename, + PyObject_REPR(c->u->u_ste->ste_symbols), + PyObject_REPR(c->u->u_varnames), + PyObject_REPR(c->u->u_names) + ); + Py_FatalError(buf); + } - return scope; + return scope; } static int @@ -1240,636 +1240,636 @@ PyObject *k, *v; k = PyTuple_Pack(2, name, name->ob_type); if (k == NULL) - return -1; + return -1; v = PyDict_GetItem(dict, k); Py_DECREF(k); if (v == NULL) - return -1; + return -1; return PyLong_AS_LONG(v); } static int compiler_make_closure(struct compiler *c, PyCodeObject *co, int args) { - int i, free = PyCode_GetNumFree(co); - if (free == 0) { - ADDOP_O(c, LOAD_CONST, (PyObject*)co, consts); - ADDOP_I(c, MAKE_FUNCTION, args); - return 1; - } - for (i = 0; i < free; ++i) { - /* Bypass com_addop_varname because it will generate - LOAD_DEREF but LOAD_CLOSURE is needed. - */ - PyObject *name = PyTuple_GET_ITEM(co->co_freevars, i); - int arg, reftype; - - /* Special case: If a class contains a method with a - free variable that has the same name as a method, - the name will be considered free *and* local in the - class. It should be handled by the closure, as - well as by the normal name loookup logic. - */ - reftype = get_ref_type(c, name); - if (reftype == CELL) - arg = compiler_lookup_arg(c->u->u_cellvars, name); - else /* (reftype == FREE) */ - arg = compiler_lookup_arg(c->u->u_freevars, name); - if (arg == -1) { - fprintf(stderr, - "lookup %s in %s %d %d\n" - "freevars of %s: %s\n", - PyObject_REPR(name), - PyBytes_AS_STRING(c->u->u_name), - reftype, arg, - _PyUnicode_AsString(co->co_name), - PyObject_REPR(co->co_freevars)); - Py_FatalError("compiler_make_closure()"); - } - ADDOP_I(c, LOAD_CLOSURE, arg); - } - ADDOP_I(c, BUILD_TUPLE, free); - ADDOP_O(c, LOAD_CONST, (PyObject*)co, consts); - ADDOP_I(c, MAKE_CLOSURE, args); - return 1; + int i, free = PyCode_GetNumFree(co); + if (free == 0) { + ADDOP_O(c, LOAD_CONST, (PyObject*)co, consts); + ADDOP_I(c, MAKE_FUNCTION, args); + return 1; + } + for (i = 0; i < free; ++i) { + /* Bypass com_addop_varname because it will generate + LOAD_DEREF but LOAD_CLOSURE is needed. + */ + PyObject *name = PyTuple_GET_ITEM(co->co_freevars, i); + int arg, reftype; + + /* Special case: If a class contains a method with a + free variable that has the same name as a method, + the name will be considered free *and* local in the + class. It should be handled by the closure, as + well as by the normal name loookup logic. + */ + reftype = get_ref_type(c, name); + if (reftype == CELL) + arg = compiler_lookup_arg(c->u->u_cellvars, name); + else /* (reftype == FREE) */ + arg = compiler_lookup_arg(c->u->u_freevars, name); + if (arg == -1) { + fprintf(stderr, + "lookup %s in %s %d %d\n" + "freevars of %s: %s\n", + PyObject_REPR(name), + PyBytes_AS_STRING(c->u->u_name), + reftype, arg, + _PyUnicode_AsString(co->co_name), + PyObject_REPR(co->co_freevars)); + Py_FatalError("compiler_make_closure()"); + } + ADDOP_I(c, LOAD_CLOSURE, arg); + } + ADDOP_I(c, BUILD_TUPLE, free); + ADDOP_O(c, LOAD_CONST, (PyObject*)co, consts); + ADDOP_I(c, MAKE_CLOSURE, args); + return 1; } static int compiler_decorators(struct compiler *c, asdl_seq* decos) { - int i; + int i; - if (!decos) - return 1; + if (!decos) + return 1; - for (i = 0; i < asdl_seq_LEN(decos); i++) { - VISIT(c, expr, (expr_ty)asdl_seq_GET(decos, i)); - } - return 1; + for (i = 0; i < asdl_seq_LEN(decos); i++) { + VISIT(c, expr, (expr_ty)asdl_seq_GET(decos, i)); + } + return 1; } static int compiler_visit_kwonlydefaults(struct compiler *c, asdl_seq *kwonlyargs, - asdl_seq *kw_defaults) + asdl_seq *kw_defaults) { - int i, default_count = 0; - for (i = 0; i < asdl_seq_LEN(kwonlyargs); i++) { - arg_ty arg = asdl_seq_GET(kwonlyargs, i); - expr_ty default_ = asdl_seq_GET(kw_defaults, i); - if (default_) { - ADDOP_O(c, LOAD_CONST, arg->arg, consts); - if (!compiler_visit_expr(c, default_)) { - return -1; - } - default_count++; - } - } - return default_count; + int i, default_count = 0; + for (i = 0; i < asdl_seq_LEN(kwonlyargs); i++) { + arg_ty arg = asdl_seq_GET(kwonlyargs, i); + expr_ty default_ = asdl_seq_GET(kw_defaults, i); + if (default_) { + ADDOP_O(c, LOAD_CONST, arg->arg, consts); + if (!compiler_visit_expr(c, default_)) { + return -1; + } + default_count++; + } + } + return default_count; } static int compiler_visit_argannotation(struct compiler *c, identifier id, expr_ty annotation, PyObject *names) { - if (annotation) { - VISIT(c, expr, annotation); - if (PyList_Append(names, id)) - return -1; - } - return 0; + if (annotation) { + VISIT(c, expr, annotation); + if (PyList_Append(names, id)) + return -1; + } + return 0; } static int compiler_visit_argannotations(struct compiler *c, asdl_seq* args, PyObject *names) { - int i, error; - for (i = 0; i < asdl_seq_LEN(args); i++) { - arg_ty arg = (arg_ty)asdl_seq_GET(args, i); - error = compiler_visit_argannotation( - c, - arg->arg, - arg->annotation, - names); - if (error) - return error; - } - return 0; + int i, error; + for (i = 0; i < asdl_seq_LEN(args); i++) { + arg_ty arg = (arg_ty)asdl_seq_GET(args, i); + error = compiler_visit_argannotation( + c, + arg->arg, + arg->annotation, + names); + if (error) + return error; + } + return 0; } static int compiler_visit_annotations(struct compiler *c, arguments_ty args, expr_ty returns) { - /* Push arg annotations and a list of the argument names. Return the # - of items pushed. The expressions are evaluated out-of-order wrt the - source code. - - More than 2^16-1 annotations is a SyntaxError. Returns -1 on error. - */ - static identifier return_str; - PyObject *names; - int len; - names = PyList_New(0); - if (!names) - return -1; - - if (compiler_visit_argannotations(c, args->args, names)) - goto error; - if (args->varargannotation && - compiler_visit_argannotation(c, args->vararg, - args->varargannotation, names)) - goto error; - if (compiler_visit_argannotations(c, args->kwonlyargs, names)) - goto error; - if (args->kwargannotation && - compiler_visit_argannotation(c, args->kwarg, - args->kwargannotation, names)) - goto error; - - if (!return_str) { - return_str = PyUnicode_InternFromString("return"); - if (!return_str) - goto error; - } - if (compiler_visit_argannotation(c, return_str, returns, names)) { - goto error; - } - - len = PyList_GET_SIZE(names); - if (len > 65534) { - /* len must fit in 16 bits, and len is incremented below */ - PyErr_SetString(PyExc_SyntaxError, - "too many annotations"); - goto error; - } - if (len) { - /* convert names to a tuple and place on stack */ - PyObject *elt; - int i; - PyObject *s = PyTuple_New(len); - if (!s) - goto error; - for (i = 0; i < len; i++) { - elt = PyList_GET_ITEM(names, i); - Py_INCREF(elt); - PyTuple_SET_ITEM(s, i, elt); - } - ADDOP_O(c, LOAD_CONST, s, consts); - Py_DECREF(s); - len++; /* include the just-pushed tuple */ - } - Py_DECREF(names); - return len; + /* Push arg annotations and a list of the argument names. Return the # + of items pushed. The expressions are evaluated out-of-order wrt the + source code. + + More than 2^16-1 annotations is a SyntaxError. Returns -1 on error. + */ + static identifier return_str; + PyObject *names; + int len; + names = PyList_New(0); + if (!names) + return -1; + + if (compiler_visit_argannotations(c, args->args, names)) + goto error; + if (args->varargannotation && + compiler_visit_argannotation(c, args->vararg, + args->varargannotation, names)) + goto error; + if (compiler_visit_argannotations(c, args->kwonlyargs, names)) + goto error; + if (args->kwargannotation && + compiler_visit_argannotation(c, args->kwarg, + args->kwargannotation, names)) + goto error; + + if (!return_str) { + return_str = PyUnicode_InternFromString("return"); + if (!return_str) + goto error; + } + if (compiler_visit_argannotation(c, return_str, returns, names)) { + goto error; + } + + len = PyList_GET_SIZE(names); + if (len > 65534) { + /* len must fit in 16 bits, and len is incremented below */ + PyErr_SetString(PyExc_SyntaxError, + "too many annotations"); + goto error; + } + if (len) { + /* convert names to a tuple and place on stack */ + PyObject *elt; + int i; + PyObject *s = PyTuple_New(len); + if (!s) + goto error; + for (i = 0; i < len; i++) { + elt = PyList_GET_ITEM(names, i); + Py_INCREF(elt); + PyTuple_SET_ITEM(s, i, elt); + } + ADDOP_O(c, LOAD_CONST, s, consts); + Py_DECREF(s); + len++; /* include the just-pushed tuple */ + } + Py_DECREF(names); + return len; error: - Py_DECREF(names); - return -1; + Py_DECREF(names); + return -1; } static int compiler_function(struct compiler *c, stmt_ty s) { - PyCodeObject *co; - PyObject *first_const = Py_None; - arguments_ty args = s->v.FunctionDef.args; - expr_ty returns = s->v.FunctionDef.returns; - asdl_seq* decos = s->v.FunctionDef.decorator_list; - stmt_ty st; - int i, n, docstring, kw_default_count = 0, arglength; - int num_annotations; - - assert(s->kind == FunctionDef_kind); - - if (!compiler_decorators(c, decos)) - return 0; - if (args->kwonlyargs) { - int res = compiler_visit_kwonlydefaults(c, args->kwonlyargs, - args->kw_defaults); - if (res < 0) - return 0; - kw_default_count = res; - } - if (args->defaults) - VISIT_SEQ(c, expr, args->defaults); - num_annotations = compiler_visit_annotations(c, args, returns); - if (num_annotations < 0) - return 0; - assert((num_annotations & 0xFFFF) == num_annotations); - - if (!compiler_enter_scope(c, s->v.FunctionDef.name, (void *)s, - s->lineno)) - return 0; - - st = (stmt_ty)asdl_seq_GET(s->v.FunctionDef.body, 0); - docstring = compiler_isdocstring(st); - if (docstring && Py_OptimizeFlag < 2) - first_const = st->v.Expr.value->v.Str.s; - if (compiler_add_o(c, c->u->u_consts, first_const) < 0) { - compiler_exit_scope(c); - return 0; - } - - c->u->u_argcount = asdl_seq_LEN(args->args); - c->u->u_kwonlyargcount = asdl_seq_LEN(args->kwonlyargs); - n = asdl_seq_LEN(s->v.FunctionDef.body); - /* if there was a docstring, we need to skip the first statement */ - for (i = docstring; i < n; i++) { - st = (stmt_ty)asdl_seq_GET(s->v.FunctionDef.body, i); - VISIT_IN_SCOPE(c, stmt, st); - } - co = assemble(c, 1); - compiler_exit_scope(c); - if (co == NULL) - return 0; - - arglength = asdl_seq_LEN(args->defaults); - arglength |= kw_default_count << 8; - arglength |= num_annotations << 16; - compiler_make_closure(c, co, arglength); - Py_DECREF(co); - - /* decorators */ - for (i = 0; i < asdl_seq_LEN(decos); i++) { - ADDOP_I(c, CALL_FUNCTION, 1); - } + PyCodeObject *co; + PyObject *first_const = Py_None; + arguments_ty args = s->v.FunctionDef.args; + expr_ty returns = s->v.FunctionDef.returns; + asdl_seq* decos = s->v.FunctionDef.decorator_list; + stmt_ty st; + int i, n, docstring, kw_default_count = 0, arglength; + int num_annotations; + + assert(s->kind == FunctionDef_kind); + + if (!compiler_decorators(c, decos)) + return 0; + if (args->kwonlyargs) { + int res = compiler_visit_kwonlydefaults(c, args->kwonlyargs, + args->kw_defaults); + if (res < 0) + return 0; + kw_default_count = res; + } + if (args->defaults) + VISIT_SEQ(c, expr, args->defaults); + num_annotations = compiler_visit_annotations(c, args, returns); + if (num_annotations < 0) + return 0; + assert((num_annotations & 0xFFFF) == num_annotations); + + if (!compiler_enter_scope(c, s->v.FunctionDef.name, (void *)s, + s->lineno)) + return 0; + + st = (stmt_ty)asdl_seq_GET(s->v.FunctionDef.body, 0); + docstring = compiler_isdocstring(st); + if (docstring && Py_OptimizeFlag < 2) + first_const = st->v.Expr.value->v.Str.s; + if (compiler_add_o(c, c->u->u_consts, first_const) < 0) { + compiler_exit_scope(c); + return 0; + } - return compiler_nameop(c, s->v.FunctionDef.name, Store); + c->u->u_argcount = asdl_seq_LEN(args->args); + c->u->u_kwonlyargcount = asdl_seq_LEN(args->kwonlyargs); + n = asdl_seq_LEN(s->v.FunctionDef.body); + /* if there was a docstring, we need to skip the first statement */ + for (i = docstring; i < n; i++) { + st = (stmt_ty)asdl_seq_GET(s->v.FunctionDef.body, i); + VISIT_IN_SCOPE(c, stmt, st); + } + co = assemble(c, 1); + compiler_exit_scope(c); + if (co == NULL) + return 0; + + arglength = asdl_seq_LEN(args->defaults); + arglength |= kw_default_count << 8; + arglength |= num_annotations << 16; + compiler_make_closure(c, co, arglength); + Py_DECREF(co); + + /* decorators */ + for (i = 0; i < asdl_seq_LEN(decos); i++) { + ADDOP_I(c, CALL_FUNCTION, 1); + } + + return compiler_nameop(c, s->v.FunctionDef.name, Store); } static int compiler_class(struct compiler *c, stmt_ty s) { - PyCodeObject *co; - PyObject *str; - int i; - asdl_seq* decos = s->v.ClassDef.decorator_list; - - if (!compiler_decorators(c, decos)) - return 0; + PyCodeObject *co; + PyObject *str; + int i; + asdl_seq* decos = s->v.ClassDef.decorator_list; + + if (!compiler_decorators(c, decos)) + return 0; + + /* ultimately generate code for: + = __build_class__(, , *, **) + where: + is a function/closure created from the class body; + it has a single argument (__locals__) where the dict + (or MutableSequence) representing the locals is passed + is the class name + is the positional arguments and *varargs argument + is the keyword arguments and **kwds argument + This borrows from compiler_call. + */ + + /* 1. compile the class body into a code object */ + if (!compiler_enter_scope(c, s->v.ClassDef.name, (void *)s, s->lineno)) + return 0; + /* this block represents what we do in the new scope */ + { + /* use the class name for name mangling */ + Py_INCREF(s->v.ClassDef.name); + Py_XDECREF(c->u->u_private); + c->u->u_private = s->v.ClassDef.name; + /* force it to have one mandatory argument */ + c->u->u_argcount = 1; + /* load the first argument (__locals__) ... */ + ADDOP_I(c, LOAD_FAST, 0); + /* ... and store it into f_locals */ + ADDOP_IN_SCOPE(c, STORE_LOCALS); + /* load (global) __name__ ... */ + str = PyUnicode_InternFromString("__name__"); + if (!str || !compiler_nameop(c, str, Load)) { + Py_XDECREF(str); + compiler_exit_scope(c); + return 0; + } + Py_DECREF(str); + /* ... and store it as __module__ */ + str = PyUnicode_InternFromString("__module__"); + if (!str || !compiler_nameop(c, str, Store)) { + Py_XDECREF(str); + compiler_exit_scope(c); + return 0; + } + Py_DECREF(str); + /* compile the body proper */ + if (!compiler_body(c, s->v.ClassDef.body)) { + compiler_exit_scope(c); + return 0; + } + /* return the (empty) __class__ cell */ + str = PyUnicode_InternFromString("__class__"); + if (str == NULL) { + compiler_exit_scope(c); + return 0; + } + i = compiler_lookup_arg(c->u->u_cellvars, str); + Py_DECREF(str); + if (i == -1) { + /* This happens when nobody references the cell */ + PyErr_Clear(); + /* Return None */ + ADDOP_O(c, LOAD_CONST, Py_None, consts); + } + else { + /* Return the cell where to store __class__ */ + ADDOP_I(c, LOAD_CLOSURE, i); + } + ADDOP_IN_SCOPE(c, RETURN_VALUE); + /* create the code object */ + co = assemble(c, 1); + } + /* leave the new scope */ + compiler_exit_scope(c); + if (co == NULL) + return 0; + + /* 2. load the 'build_class' function */ + ADDOP(c, LOAD_BUILD_CLASS); + + /* 3. load a function (or closure) made from the code object */ + compiler_make_closure(c, co, 0); + Py_DECREF(co); + + /* 4. load class name */ + ADDOP_O(c, LOAD_CONST, s->v.ClassDef.name, consts); + + /* 5. generate the rest of the code for the call */ + if (!compiler_call_helper(c, 2, + s->v.ClassDef.bases, + s->v.ClassDef.keywords, + s->v.ClassDef.starargs, + s->v.ClassDef.kwargs)) + return 0; + + /* 6. apply decorators */ + for (i = 0; i < asdl_seq_LEN(decos); i++) { + ADDOP_I(c, CALL_FUNCTION, 1); + } - /* ultimately generate code for: - = __build_class__(, , *, **) - where: - is a function/closure created from the class body; - it has a single argument (__locals__) where the dict - (or MutableSequence) representing the locals is passed - is the class name - is the positional arguments and *varargs argument - is the keyword arguments and **kwds argument - This borrows from compiler_call. - */ - - /* 1. compile the class body into a code object */ - if (!compiler_enter_scope(c, s->v.ClassDef.name, (void *)s, s->lineno)) - return 0; - /* this block represents what we do in the new scope */ - { - /* use the class name for name mangling */ - Py_INCREF(s->v.ClassDef.name); - Py_XDECREF(c->u->u_private); - c->u->u_private = s->v.ClassDef.name; - /* force it to have one mandatory argument */ - c->u->u_argcount = 1; - /* load the first argument (__locals__) ... */ - ADDOP_I(c, LOAD_FAST, 0); - /* ... and store it into f_locals */ - ADDOP_IN_SCOPE(c, STORE_LOCALS); - /* load (global) __name__ ... */ - str = PyUnicode_InternFromString("__name__"); - if (!str || !compiler_nameop(c, str, Load)) { - Py_XDECREF(str); - compiler_exit_scope(c); - return 0; - } - Py_DECREF(str); - /* ... and store it as __module__ */ - str = PyUnicode_InternFromString("__module__"); - if (!str || !compiler_nameop(c, str, Store)) { - Py_XDECREF(str); - compiler_exit_scope(c); - return 0; - } - Py_DECREF(str); - /* compile the body proper */ - if (!compiler_body(c, s->v.ClassDef.body)) { - compiler_exit_scope(c); - return 0; - } - /* return the (empty) __class__ cell */ - str = PyUnicode_InternFromString("__class__"); - if (str == NULL) { - compiler_exit_scope(c); - return 0; - } - i = compiler_lookup_arg(c->u->u_cellvars, str); - Py_DECREF(str); - if (i == -1) { - /* This happens when nobody references the cell */ - PyErr_Clear(); - /* Return None */ - ADDOP_O(c, LOAD_CONST, Py_None, consts); - } - else { - /* Return the cell where to store __class__ */ - ADDOP_I(c, LOAD_CLOSURE, i); - } - ADDOP_IN_SCOPE(c, RETURN_VALUE); - /* create the code object */ - co = assemble(c, 1); - } - /* leave the new scope */ - compiler_exit_scope(c); - if (co == NULL) - return 0; - - /* 2. load the 'build_class' function */ - ADDOP(c, LOAD_BUILD_CLASS); - - /* 3. load a function (or closure) made from the code object */ - compiler_make_closure(c, co, 0); - Py_DECREF(co); - - /* 4. load class name */ - ADDOP_O(c, LOAD_CONST, s->v.ClassDef.name, consts); - - /* 5. generate the rest of the code for the call */ - if (!compiler_call_helper(c, 2, - s->v.ClassDef.bases, - s->v.ClassDef.keywords, - s->v.ClassDef.starargs, - s->v.ClassDef.kwargs)) - return 0; - - /* 6. apply decorators */ - for (i = 0; i < asdl_seq_LEN(decos); i++) { - ADDOP_I(c, CALL_FUNCTION, 1); - } - - /* 7. store into */ - if (!compiler_nameop(c, s->v.ClassDef.name, Store)) - return 0; - return 1; + /* 7. store into */ + if (!compiler_nameop(c, s->v.ClassDef.name, Store)) + return 0; + return 1; } static int compiler_ifexp(struct compiler *c, expr_ty e) { - basicblock *end, *next; - - assert(e->kind == IfExp_kind); - end = compiler_new_block(c); - if (end == NULL) - return 0; - next = compiler_new_block(c); - if (next == NULL) - return 0; - VISIT(c, expr, e->v.IfExp.test); - ADDOP_JABS(c, POP_JUMP_IF_FALSE, next); - VISIT(c, expr, e->v.IfExp.body); - ADDOP_JREL(c, JUMP_FORWARD, end); - compiler_use_next_block(c, next); - VISIT(c, expr, e->v.IfExp.orelse); - compiler_use_next_block(c, end); - return 1; + basicblock *end, *next; + + assert(e->kind == IfExp_kind); + end = compiler_new_block(c); + if (end == NULL) + return 0; + next = compiler_new_block(c); + if (next == NULL) + return 0; + VISIT(c, expr, e->v.IfExp.test); + ADDOP_JABS(c, POP_JUMP_IF_FALSE, next); + VISIT(c, expr, e->v.IfExp.body); + ADDOP_JREL(c, JUMP_FORWARD, end); + compiler_use_next_block(c, next); + VISIT(c, expr, e->v.IfExp.orelse); + compiler_use_next_block(c, end); + return 1; } static int compiler_lambda(struct compiler *c, expr_ty e) { - PyCodeObject *co; - static identifier name; - int kw_default_count = 0, arglength; - arguments_ty args = e->v.Lambda.args; - assert(e->kind == Lambda_kind); - - if (!name) { - name = PyUnicode_InternFromString(""); - if (!name) - return 0; - } - - if (args->kwonlyargs) { - int res = compiler_visit_kwonlydefaults(c, args->kwonlyargs, - args->kw_defaults); - if (res < 0) return 0; - kw_default_count = res; - } - if (args->defaults) - VISIT_SEQ(c, expr, args->defaults); - if (!compiler_enter_scope(c, name, (void *)e, e->lineno)) - return 0; - - /* Make None the first constant, so the lambda can't have a - docstring. */ - if (compiler_add_o(c, c->u->u_consts, Py_None) < 0) - return 0; - - c->u->u_argcount = asdl_seq_LEN(args->args); - c->u->u_kwonlyargcount = asdl_seq_LEN(args->kwonlyargs); - VISIT_IN_SCOPE(c, expr, e->v.Lambda.body); - if (c->u->u_ste->ste_generator) { - ADDOP_IN_SCOPE(c, POP_TOP); - } - else { - ADDOP_IN_SCOPE(c, RETURN_VALUE); - } - co = assemble(c, 1); - compiler_exit_scope(c); - if (co == NULL) - return 0; - - arglength = asdl_seq_LEN(args->defaults); - arglength |= kw_default_count << 8; - compiler_make_closure(c, co, arglength); - Py_DECREF(co); + PyCodeObject *co; + static identifier name; + int kw_default_count = 0, arglength; + arguments_ty args = e->v.Lambda.args; + assert(e->kind == Lambda_kind); + + if (!name) { + name = PyUnicode_InternFromString(""); + if (!name) + return 0; + } - return 1; + if (args->kwonlyargs) { + int res = compiler_visit_kwonlydefaults(c, args->kwonlyargs, + args->kw_defaults); + if (res < 0) return 0; + kw_default_count = res; + } + if (args->defaults) + VISIT_SEQ(c, expr, args->defaults); + if (!compiler_enter_scope(c, name, (void *)e, e->lineno)) + return 0; + + /* Make None the first constant, so the lambda can't have a + docstring. */ + if (compiler_add_o(c, c->u->u_consts, Py_None) < 0) + return 0; + + c->u->u_argcount = asdl_seq_LEN(args->args); + c->u->u_kwonlyargcount = asdl_seq_LEN(args->kwonlyargs); + VISIT_IN_SCOPE(c, expr, e->v.Lambda.body); + if (c->u->u_ste->ste_generator) { + ADDOP_IN_SCOPE(c, POP_TOP); + } + else { + ADDOP_IN_SCOPE(c, RETURN_VALUE); + } + co = assemble(c, 1); + compiler_exit_scope(c); + if (co == NULL) + return 0; + + arglength = asdl_seq_LEN(args->defaults); + arglength |= kw_default_count << 8; + compiler_make_closure(c, co, arglength); + Py_DECREF(co); + + return 1; } static int compiler_if(struct compiler *c, stmt_ty s) { - basicblock *end, *next; - int constant; - assert(s->kind == If_kind); - end = compiler_new_block(c); - if (end == NULL) - return 0; - - constant = expr_constant(s->v.If.test); - /* constant = 0: "if 0" - * constant = 1: "if 1", "if 2", ... - * constant = -1: rest */ - if (constant == 0) { - if (s->v.If.orelse) - VISIT_SEQ(c, stmt, s->v.If.orelse); - } else if (constant == 1) { - VISIT_SEQ(c, stmt, s->v.If.body); - } else { - if (s->v.If.orelse) { - next = compiler_new_block(c); - if (next == NULL) - return 0; - } - else - next = end; - VISIT(c, expr, s->v.If.test); - ADDOP_JABS(c, POP_JUMP_IF_FALSE, next); - VISIT_SEQ(c, stmt, s->v.If.body); - ADDOP_JREL(c, JUMP_FORWARD, end); - if (s->v.If.orelse) { - compiler_use_next_block(c, next); - VISIT_SEQ(c, stmt, s->v.If.orelse); - } - } - compiler_use_next_block(c, end); - return 1; + basicblock *end, *next; + int constant; + assert(s->kind == If_kind); + end = compiler_new_block(c); + if (end == NULL) + return 0; + + constant = expr_constant(s->v.If.test); + /* constant = 0: "if 0" + * constant = 1: "if 1", "if 2", ... + * constant = -1: rest */ + if (constant == 0) { + if (s->v.If.orelse) + VISIT_SEQ(c, stmt, s->v.If.orelse); + } else if (constant == 1) { + VISIT_SEQ(c, stmt, s->v.If.body); + } else { + if (s->v.If.orelse) { + next = compiler_new_block(c); + if (next == NULL) + return 0; + } + else + next = end; + VISIT(c, expr, s->v.If.test); + ADDOP_JABS(c, POP_JUMP_IF_FALSE, next); + VISIT_SEQ(c, stmt, s->v.If.body); + ADDOP_JREL(c, JUMP_FORWARD, end); + if (s->v.If.orelse) { + compiler_use_next_block(c, next); + VISIT_SEQ(c, stmt, s->v.If.orelse); + } + } + compiler_use_next_block(c, end); + return 1; } static int compiler_for(struct compiler *c, stmt_ty s) { - basicblock *start, *cleanup, *end; + basicblock *start, *cleanup, *end; - start = compiler_new_block(c); - cleanup = compiler_new_block(c); - end = compiler_new_block(c); - if (start == NULL || end == NULL || cleanup == NULL) - return 0; - ADDOP_JREL(c, SETUP_LOOP, end); - if (!compiler_push_fblock(c, LOOP, start)) - return 0; - VISIT(c, expr, s->v.For.iter); - ADDOP(c, GET_ITER); - compiler_use_next_block(c, start); - ADDOP_JREL(c, FOR_ITER, cleanup); - VISIT(c, expr, s->v.For.target); - VISIT_SEQ(c, stmt, s->v.For.body); - ADDOP_JABS(c, JUMP_ABSOLUTE, start); - compiler_use_next_block(c, cleanup); - ADDOP(c, POP_BLOCK); - compiler_pop_fblock(c, LOOP, start); - VISIT_SEQ(c, stmt, s->v.For.orelse); - compiler_use_next_block(c, end); - return 1; + start = compiler_new_block(c); + cleanup = compiler_new_block(c); + end = compiler_new_block(c); + if (start == NULL || end == NULL || cleanup == NULL) + return 0; + ADDOP_JREL(c, SETUP_LOOP, end); + if (!compiler_push_fblock(c, LOOP, start)) + return 0; + VISIT(c, expr, s->v.For.iter); + ADDOP(c, GET_ITER); + compiler_use_next_block(c, start); + ADDOP_JREL(c, FOR_ITER, cleanup); + VISIT(c, expr, s->v.For.target); + VISIT_SEQ(c, stmt, s->v.For.body); + ADDOP_JABS(c, JUMP_ABSOLUTE, start); + compiler_use_next_block(c, cleanup); + ADDOP(c, POP_BLOCK); + compiler_pop_fblock(c, LOOP, start); + VISIT_SEQ(c, stmt, s->v.For.orelse); + compiler_use_next_block(c, end); + return 1; } static int compiler_while(struct compiler *c, stmt_ty s) { - basicblock *loop, *orelse, *end, *anchor = NULL; - int constant = expr_constant(s->v.While.test); + basicblock *loop, *orelse, *end, *anchor = NULL; + int constant = expr_constant(s->v.While.test); + + if (constant == 0) { + if (s->v.While.orelse) + VISIT_SEQ(c, stmt, s->v.While.orelse); + return 1; + } + loop = compiler_new_block(c); + end = compiler_new_block(c); + if (constant == -1) { + anchor = compiler_new_block(c); + if (anchor == NULL) + return 0; + } + if (loop == NULL || end == NULL) + return 0; + if (s->v.While.orelse) { + orelse = compiler_new_block(c); + if (orelse == NULL) + return 0; + } + else + orelse = NULL; + + ADDOP_JREL(c, SETUP_LOOP, end); + compiler_use_next_block(c, loop); + if (!compiler_push_fblock(c, LOOP, loop)) + return 0; + if (constant == -1) { + VISIT(c, expr, s->v.While.test); + ADDOP_JABS(c, POP_JUMP_IF_FALSE, anchor); + } + VISIT_SEQ(c, stmt, s->v.While.body); + ADDOP_JABS(c, JUMP_ABSOLUTE, loop); - if (constant == 0) { - if (s->v.While.orelse) - VISIT_SEQ(c, stmt, s->v.While.orelse); - return 1; - } - loop = compiler_new_block(c); - end = compiler_new_block(c); - if (constant == -1) { - anchor = compiler_new_block(c); - if (anchor == NULL) - return 0; - } - if (loop == NULL || end == NULL) - return 0; - if (s->v.While.orelse) { - orelse = compiler_new_block(c); - if (orelse == NULL) - return 0; - } - else - orelse = NULL; - - ADDOP_JREL(c, SETUP_LOOP, end); - compiler_use_next_block(c, loop); - if (!compiler_push_fblock(c, LOOP, loop)) - return 0; - if (constant == -1) { - VISIT(c, expr, s->v.While.test); - ADDOP_JABS(c, POP_JUMP_IF_FALSE, anchor); - } - VISIT_SEQ(c, stmt, s->v.While.body); - ADDOP_JABS(c, JUMP_ABSOLUTE, loop); - - /* XXX should the two POP instructions be in a separate block - if there is no else clause ? - */ - - if (constant == -1) { - compiler_use_next_block(c, anchor); - ADDOP(c, POP_BLOCK); - } - compiler_pop_fblock(c, LOOP, loop); - if (orelse != NULL) /* what if orelse is just pass? */ - VISIT_SEQ(c, stmt, s->v.While.orelse); - compiler_use_next_block(c, end); + /* XXX should the two POP instructions be in a separate block + if there is no else clause ? + */ + + if (constant == -1) { + compiler_use_next_block(c, anchor); + ADDOP(c, POP_BLOCK); + } + compiler_pop_fblock(c, LOOP, loop); + if (orelse != NULL) /* what if orelse is just pass? */ + VISIT_SEQ(c, stmt, s->v.While.orelse); + compiler_use_next_block(c, end); - return 1; + return 1; } static int compiler_continue(struct compiler *c) { - static const char LOOP_ERROR_MSG[] = "'continue' not properly in loop"; - static const char IN_FINALLY_ERROR_MSG[] = - "'continue' not supported inside 'finally' clause"; - int i; - - if (!c->u->u_nfblocks) - return compiler_error(c, LOOP_ERROR_MSG); - i = c->u->u_nfblocks - 1; - switch (c->u->u_fblock[i].fb_type) { - case LOOP: - ADDOP_JABS(c, JUMP_ABSOLUTE, c->u->u_fblock[i].fb_block); - break; - case EXCEPT: - case FINALLY_TRY: - while (--i >= 0 && c->u->u_fblock[i].fb_type != LOOP) { - /* Prevent continue anywhere under a finally - even if hidden in a sub-try or except. */ - if (c->u->u_fblock[i].fb_type == FINALLY_END) - return compiler_error(c, IN_FINALLY_ERROR_MSG); - } - if (i == -1) - return compiler_error(c, LOOP_ERROR_MSG); - ADDOP_JABS(c, CONTINUE_LOOP, c->u->u_fblock[i].fb_block); - break; - case FINALLY_END: - return compiler_error(c, IN_FINALLY_ERROR_MSG); - } + static const char LOOP_ERROR_MSG[] = "'continue' not properly in loop"; + static const char IN_FINALLY_ERROR_MSG[] = + "'continue' not supported inside 'finally' clause"; + int i; + + if (!c->u->u_nfblocks) + return compiler_error(c, LOOP_ERROR_MSG); + i = c->u->u_nfblocks - 1; + switch (c->u->u_fblock[i].fb_type) { + case LOOP: + ADDOP_JABS(c, JUMP_ABSOLUTE, c->u->u_fblock[i].fb_block); + break; + case EXCEPT: + case FINALLY_TRY: + while (--i >= 0 && c->u->u_fblock[i].fb_type != LOOP) { + /* Prevent continue anywhere under a finally + even if hidden in a sub-try or except. */ + if (c->u->u_fblock[i].fb_type == FINALLY_END) + return compiler_error(c, IN_FINALLY_ERROR_MSG); + } + if (i == -1) + return compiler_error(c, LOOP_ERROR_MSG); + ADDOP_JABS(c, CONTINUE_LOOP, c->u->u_fblock[i].fb_block); + break; + case FINALLY_END: + return compiler_error(c, IN_FINALLY_ERROR_MSG); + } - return 1; + return 1; } /* Code generated for "try: finally: " is as follows: - - SETUP_FINALLY L - - POP_BLOCK - LOAD_CONST - L: - END_FINALLY - + + SETUP_FINALLY L + + POP_BLOCK + LOAD_CONST + L: + END_FINALLY + The special instructions use the block stack. Each block stack entry contains the instruction that created it (here SETUP_FINALLY), the level of the value stack at the time the block stack entry was created, and a label (here L). - + SETUP_FINALLY: - Pushes the current value stack level and the label - onto the block stack. + Pushes the current value stack level and the label + onto the block stack. POP_BLOCK: - Pops en entry from the block stack, and pops the value - stack until its level is the same as indicated on the - block stack. (The label is ignored.) + Pops en entry from the block stack, and pops the value + stack until its level is the same as indicated on the + block stack. (The label is ignored.) END_FINALLY: - Pops a variable number of entries from the *value* stack - and re-raises the exception they specify. The number of - entries popped depends on the (pseudo) exception type. - + Pops a variable number of entries from the *value* stack + and re-raises the exception they specify. The number of + entries popped depends on the (pseudo) exception type. + The block stack is unwound when an exception is raised: when a SETUP_FINALLY entry is found, the exception is pushed onto the value stack (and the exception condition is cleared), @@ -1880,29 +1880,29 @@ static int compiler_try_finally(struct compiler *c, stmt_ty s) { - basicblock *body, *end; - body = compiler_new_block(c); - end = compiler_new_block(c); - if (body == NULL || end == NULL) - return 0; - - ADDOP_JREL(c, SETUP_FINALLY, end); - compiler_use_next_block(c, body); - if (!compiler_push_fblock(c, FINALLY_TRY, body)) - return 0; - VISIT_SEQ(c, stmt, s->v.TryFinally.body); - ADDOP(c, POP_BLOCK); - compiler_pop_fblock(c, FINALLY_TRY, body); - - ADDOP_O(c, LOAD_CONST, Py_None, consts); - compiler_use_next_block(c, end); - if (!compiler_push_fblock(c, FINALLY_END, end)) - return 0; - VISIT_SEQ(c, stmt, s->v.TryFinally.finalbody); - ADDOP(c, END_FINALLY); - compiler_pop_fblock(c, FINALLY_END, end); + basicblock *body, *end; + body = compiler_new_block(c); + end = compiler_new_block(c); + if (body == NULL || end == NULL) + return 0; + + ADDOP_JREL(c, SETUP_FINALLY, end); + compiler_use_next_block(c, body); + if (!compiler_push_fblock(c, FINALLY_TRY, body)) + return 0; + VISIT_SEQ(c, stmt, s->v.TryFinally.body); + ADDOP(c, POP_BLOCK); + compiler_pop_fblock(c, FINALLY_TRY, body); - return 1; + ADDOP_O(c, LOAD_CONST, Py_None, consts); + compiler_use_next_block(c, end); + if (!compiler_push_fblock(c, FINALLY_END, end)) + return 0; + VISIT_SEQ(c, stmt, s->v.TryFinally.finalbody); + ADDOP(c, END_FINALLY); + compiler_pop_fblock(c, FINALLY_END, end); + + return 1; } /* @@ -1910,864 +1910,864 @@ (The contents of the value stack is shown in [], with the top at the right; 'tb' is trace-back info, 'val' the exception's associated value, and 'exc' the exception.) - - Value stack Label Instruction Argument - [] SETUP_EXCEPT L1 - [] - [] POP_BLOCK - [] JUMP_FORWARD L0 - - [tb, val, exc] L1: DUP ) - [tb, val, exc, exc] ) - [tb, val, exc, exc, E1] COMPARE_OP EXC_MATCH ) only if E1 - [tb, val, exc, 1-or-0] POP_JUMP_IF_FALSE L2 ) - [tb, val, exc] POP - [tb, val] (or POP if no V1) - [tb] POP - [] - JUMP_FORWARD L0 - - [tb, val, exc] L2: DUP + + Value stack Label Instruction Argument + [] SETUP_EXCEPT L1 + [] + [] POP_BLOCK + [] JUMP_FORWARD L0 + + [tb, val, exc] L1: DUP ) + [tb, val, exc, exc] ) + [tb, val, exc, exc, E1] COMPARE_OP EXC_MATCH ) only if E1 + [tb, val, exc, 1-or-0] POP_JUMP_IF_FALSE L2 ) + [tb, val, exc] POP + [tb, val] (or POP if no V1) + [tb] POP + [] + JUMP_FORWARD L0 + + [tb, val, exc] L2: DUP .............................etc....................... - [tb, val, exc] Ln+1: END_FINALLY # re-raise exception - - [] L0: - + [tb, val, exc] Ln+1: END_FINALLY # re-raise exception + + [] L0: + Of course, parts are not generated if Vi or Ei is not present. */ static int compiler_try_except(struct compiler *c, stmt_ty s) { - basicblock *body, *orelse, *except, *end; - int i, n; + basicblock *body, *orelse, *except, *end; + int i, n; - body = compiler_new_block(c); - except = compiler_new_block(c); - orelse = compiler_new_block(c); - end = compiler_new_block(c); - if (body == NULL || except == NULL || orelse == NULL || end == NULL) - return 0; - ADDOP_JREL(c, SETUP_EXCEPT, except); - compiler_use_next_block(c, body); - if (!compiler_push_fblock(c, EXCEPT, body)) - return 0; - VISIT_SEQ(c, stmt, s->v.TryExcept.body); - ADDOP(c, POP_BLOCK); - compiler_pop_fblock(c, EXCEPT, body); - ADDOP_JREL(c, JUMP_FORWARD, orelse); - n = asdl_seq_LEN(s->v.TryExcept.handlers); - compiler_use_next_block(c, except); - for (i = 0; i < n; i++) { - excepthandler_ty handler = (excepthandler_ty)asdl_seq_GET( - s->v.TryExcept.handlers, i); - if (!handler->v.ExceptHandler.type && i < n-1) - return compiler_error(c, "default 'except:' must be last"); - c->u->u_lineno_set = 0; - c->u->u_lineno = handler->lineno; - except = compiler_new_block(c); - if (except == NULL) - return 0; - if (handler->v.ExceptHandler.type) { - ADDOP(c, DUP_TOP); - VISIT(c, expr, handler->v.ExceptHandler.type); - ADDOP_I(c, COMPARE_OP, PyCmp_EXC_MATCH); - ADDOP_JABS(c, POP_JUMP_IF_FALSE, except); - } - ADDOP(c, POP_TOP); - if (handler->v.ExceptHandler.name) { - basicblock *cleanup_end, *cleanup_body; - - cleanup_end = compiler_new_block(c); - cleanup_body = compiler_new_block(c); - if(!(cleanup_end || cleanup_body)) - return 0; + body = compiler_new_block(c); + except = compiler_new_block(c); + orelse = compiler_new_block(c); + end = compiler_new_block(c); + if (body == NULL || except == NULL || orelse == NULL || end == NULL) + return 0; + ADDOP_JREL(c, SETUP_EXCEPT, except); + compiler_use_next_block(c, body); + if (!compiler_push_fblock(c, EXCEPT, body)) + return 0; + VISIT_SEQ(c, stmt, s->v.TryExcept.body); + ADDOP(c, POP_BLOCK); + compiler_pop_fblock(c, EXCEPT, body); + ADDOP_JREL(c, JUMP_FORWARD, orelse); + n = asdl_seq_LEN(s->v.TryExcept.handlers); + compiler_use_next_block(c, except); + for (i = 0; i < n; i++) { + excepthandler_ty handler = (excepthandler_ty)asdl_seq_GET( + s->v.TryExcept.handlers, i); + if (!handler->v.ExceptHandler.type && i < n-1) + return compiler_error(c, "default 'except:' must be last"); + c->u->u_lineno_set = 0; + c->u->u_lineno = handler->lineno; + except = compiler_new_block(c); + if (except == NULL) + return 0; + if (handler->v.ExceptHandler.type) { + ADDOP(c, DUP_TOP); + VISIT(c, expr, handler->v.ExceptHandler.type); + ADDOP_I(c, COMPARE_OP, PyCmp_EXC_MATCH); + ADDOP_JABS(c, POP_JUMP_IF_FALSE, except); + } + ADDOP(c, POP_TOP); + if (handler->v.ExceptHandler.name) { + basicblock *cleanup_end, *cleanup_body; - compiler_nameop(c, handler->v.ExceptHandler.name, Store); - ADDOP(c, POP_TOP); + cleanup_end = compiler_new_block(c); + cleanup_body = compiler_new_block(c); + if(!(cleanup_end || cleanup_body)) + return 0; - /* - try: - # body - except type as name: - try: - # body - finally: - name = None - del name - */ - - /* second try: */ - ADDOP_JREL(c, SETUP_FINALLY, cleanup_end); - compiler_use_next_block(c, cleanup_body); - if (!compiler_push_fblock(c, FINALLY_TRY, cleanup_body)) - return 0; - - /* second # body */ - VISIT_SEQ(c, stmt, handler->v.ExceptHandler.body); - ADDOP(c, POP_BLOCK); - ADDOP(c, POP_EXCEPT); - compiler_pop_fblock(c, FINALLY_TRY, cleanup_body); - - /* finally: */ - ADDOP_O(c, LOAD_CONST, Py_None, consts); - compiler_use_next_block(c, cleanup_end); - if (!compiler_push_fblock(c, FINALLY_END, cleanup_end)) - return 0; + compiler_nameop(c, handler->v.ExceptHandler.name, Store); + ADDOP(c, POP_TOP); - /* name = None */ - ADDOP_O(c, LOAD_CONST, Py_None, consts); - compiler_nameop(c, handler->v.ExceptHandler.name, Store); + /* + try: + # body + except type as name: + try: + # body + finally: + name = None + del name + */ + + /* second try: */ + ADDOP_JREL(c, SETUP_FINALLY, cleanup_end); + compiler_use_next_block(c, cleanup_body); + if (!compiler_push_fblock(c, FINALLY_TRY, cleanup_body)) + return 0; + + /* second # body */ + VISIT_SEQ(c, stmt, handler->v.ExceptHandler.body); + ADDOP(c, POP_BLOCK); + ADDOP(c, POP_EXCEPT); + compiler_pop_fblock(c, FINALLY_TRY, cleanup_body); + + /* finally: */ + ADDOP_O(c, LOAD_CONST, Py_None, consts); + compiler_use_next_block(c, cleanup_end); + if (!compiler_push_fblock(c, FINALLY_END, cleanup_end)) + return 0; + + /* name = None */ + ADDOP_O(c, LOAD_CONST, Py_None, consts); + compiler_nameop(c, handler->v.ExceptHandler.name, Store); - /* del name */ - compiler_nameop(c, handler->v.ExceptHandler.name, Del); + /* del name */ + compiler_nameop(c, handler->v.ExceptHandler.name, Del); - ADDOP(c, END_FINALLY); - compiler_pop_fblock(c, FINALLY_END, cleanup_end); - } - else { - basicblock *cleanup_body; + ADDOP(c, END_FINALLY); + compiler_pop_fblock(c, FINALLY_END, cleanup_end); + } + else { + basicblock *cleanup_body; - cleanup_body = compiler_new_block(c); - if(!cleanup_body) - return 0; + cleanup_body = compiler_new_block(c); + if(!cleanup_body) + return 0; - ADDOP(c, POP_TOP); ADDOP(c, POP_TOP); - compiler_use_next_block(c, cleanup_body); - if (!compiler_push_fblock(c, FINALLY_TRY, cleanup_body)) - return 0; - VISIT_SEQ(c, stmt, handler->v.ExceptHandler.body); - ADDOP(c, POP_EXCEPT); - compiler_pop_fblock(c, FINALLY_TRY, cleanup_body); - } - ADDOP_JREL(c, JUMP_FORWARD, end); - compiler_use_next_block(c, except); - } - ADDOP(c, END_FINALLY); - compiler_use_next_block(c, orelse); - VISIT_SEQ(c, stmt, s->v.TryExcept.orelse); - compiler_use_next_block(c, end); - return 1; + ADDOP(c, POP_TOP); + compiler_use_next_block(c, cleanup_body); + if (!compiler_push_fblock(c, FINALLY_TRY, cleanup_body)) + return 0; + VISIT_SEQ(c, stmt, handler->v.ExceptHandler.body); + ADDOP(c, POP_EXCEPT); + compiler_pop_fblock(c, FINALLY_TRY, cleanup_body); + } + ADDOP_JREL(c, JUMP_FORWARD, end); + compiler_use_next_block(c, except); + } + ADDOP(c, END_FINALLY); + compiler_use_next_block(c, orelse); + VISIT_SEQ(c, stmt, s->v.TryExcept.orelse); + compiler_use_next_block(c, end); + return 1; } static int compiler_import_as(struct compiler *c, identifier name, identifier asname) { - /* The IMPORT_NAME opcode was already generated. This function - merely needs to bind the result to a name. + /* The IMPORT_NAME opcode was already generated. This function + merely needs to bind the result to a name. - If there is a dot in name, we need to split it and emit a - LOAD_ATTR for each name. - */ - const Py_UNICODE *src = PyUnicode_AS_UNICODE(name); - const Py_UNICODE *dot = Py_UNICODE_strchr(src, '.'); - if (dot) { - /* Consume the base module name to get the first attribute */ - src = dot + 1; - while (dot) { - /* NB src is only defined when dot != NULL */ - PyObject *attr; - dot = Py_UNICODE_strchr(src, '.'); - attr = PyUnicode_FromUnicode(src, - dot ? dot - src : Py_UNICODE_strlen(src)); - if (!attr) - return -1; - ADDOP_O(c, LOAD_ATTR, attr, names); - Py_DECREF(attr); - src = dot + 1; - } - } - return compiler_nameop(c, asname, Store); + If there is a dot in name, we need to split it and emit a + LOAD_ATTR for each name. + */ + const Py_UNICODE *src = PyUnicode_AS_UNICODE(name); + const Py_UNICODE *dot = Py_UNICODE_strchr(src, '.'); + if (dot) { + /* Consume the base module name to get the first attribute */ + src = dot + 1; + while (dot) { + /* NB src is only defined when dot != NULL */ + PyObject *attr; + dot = Py_UNICODE_strchr(src, '.'); + attr = PyUnicode_FromUnicode(src, + dot ? dot - src : Py_UNICODE_strlen(src)); + if (!attr) + return -1; + ADDOP_O(c, LOAD_ATTR, attr, names); + Py_DECREF(attr); + src = dot + 1; + } + } + return compiler_nameop(c, asname, Store); } static int compiler_import(struct compiler *c, stmt_ty s) { - /* The Import node stores a module name like a.b.c as a single - string. This is convenient for all cases except - import a.b.c as d - where we need to parse that string to extract the individual - module names. - XXX Perhaps change the representation to make this case simpler? - */ - int i, n = asdl_seq_LEN(s->v.Import.names); - - for (i = 0; i < n; i++) { - alias_ty alias = (alias_ty)asdl_seq_GET(s->v.Import.names, i); - int r; - PyObject *level; - - level = PyLong_FromLong(0); - if (level == NULL) - return 0; - - ADDOP_O(c, LOAD_CONST, level, consts); - Py_DECREF(level); - ADDOP_O(c, LOAD_CONST, Py_None, consts); - ADDOP_NAME(c, IMPORT_NAME, alias->name, names); - - if (alias->asname) { - r = compiler_import_as(c, alias->name, alias->asname); - if (!r) - return r; - } - else { - identifier tmp = alias->name; - const Py_UNICODE *base = PyUnicode_AS_UNICODE(alias->name); - Py_UNICODE *dot = Py_UNICODE_strchr(base, '.'); - if (dot) - tmp = PyUnicode_FromUnicode(base, - dot - base); - r = compiler_nameop(c, tmp, Store); - if (dot) { - Py_DECREF(tmp); - } - if (!r) - return r; - } - } - return 1; + /* The Import node stores a module name like a.b.c as a single + string. This is convenient for all cases except + import a.b.c as d + where we need to parse that string to extract the individual + module names. + XXX Perhaps change the representation to make this case simpler? + */ + int i, n = asdl_seq_LEN(s->v.Import.names); + + for (i = 0; i < n; i++) { + alias_ty alias = (alias_ty)asdl_seq_GET(s->v.Import.names, i); + int r; + PyObject *level; + + level = PyLong_FromLong(0); + if (level == NULL) + return 0; + + ADDOP_O(c, LOAD_CONST, level, consts); + Py_DECREF(level); + ADDOP_O(c, LOAD_CONST, Py_None, consts); + ADDOP_NAME(c, IMPORT_NAME, alias->name, names); + + if (alias->asname) { + r = compiler_import_as(c, alias->name, alias->asname); + if (!r) + return r; + } + else { + identifier tmp = alias->name; + const Py_UNICODE *base = PyUnicode_AS_UNICODE(alias->name); + Py_UNICODE *dot = Py_UNICODE_strchr(base, '.'); + if (dot) + tmp = PyUnicode_FromUnicode(base, + dot - base); + r = compiler_nameop(c, tmp, Store); + if (dot) { + Py_DECREF(tmp); + } + if (!r) + return r; + } + } + return 1; } static int compiler_from_import(struct compiler *c, stmt_ty s) { - int i, n = asdl_seq_LEN(s->v.ImportFrom.names); + int i, n = asdl_seq_LEN(s->v.ImportFrom.names); + + PyObject *names = PyTuple_New(n); + PyObject *level; + static PyObject *empty_string; + + if (!empty_string) { + empty_string = PyUnicode_FromString(""); + if (!empty_string) + return 0; + } + + if (!names) + return 0; + + level = PyLong_FromLong(s->v.ImportFrom.level); + if (!level) { + Py_DECREF(names); + return 0; + } - PyObject *names = PyTuple_New(n); - PyObject *level; - static PyObject *empty_string; - - if (!empty_string) { - empty_string = PyUnicode_FromString(""); - if (!empty_string) - return 0; - } - - if (!names) - return 0; - - level = PyLong_FromLong(s->v.ImportFrom.level); - if (!level) { - Py_DECREF(names); - return 0; - } - - /* build up the names */ - for (i = 0; i < n; i++) { - alias_ty alias = (alias_ty)asdl_seq_GET(s->v.ImportFrom.names, i); - Py_INCREF(alias->name); - PyTuple_SET_ITEM(names, i, alias->name); - } - - if (s->lineno > c->c_future->ff_lineno && s->v.ImportFrom.module && - !PyUnicode_CompareWithASCIIString(s->v.ImportFrom.module, "__future__")) { - Py_DECREF(level); - Py_DECREF(names); - return compiler_error(c, "from __future__ imports must occur " - "at the beginning of the file"); - } - - ADDOP_O(c, LOAD_CONST, level, consts); - Py_DECREF(level); - ADDOP_O(c, LOAD_CONST, names, consts); - Py_DECREF(names); - if (s->v.ImportFrom.module) { - ADDOP_NAME(c, IMPORT_NAME, s->v.ImportFrom.module, names); - } - else { - ADDOP_NAME(c, IMPORT_NAME, empty_string, names); - } - for (i = 0; i < n; i++) { - alias_ty alias = (alias_ty)asdl_seq_GET(s->v.ImportFrom.names, i); - identifier store_name; - - if (i == 0 && *PyUnicode_AS_UNICODE(alias->name) == '*') { - assert(n == 1); - ADDOP(c, IMPORT_STAR); - return 1; - } - - ADDOP_NAME(c, IMPORT_FROM, alias->name, names); - store_name = alias->name; - if (alias->asname) - store_name = alias->asname; - - if (!compiler_nameop(c, store_name, Store)) { - Py_DECREF(names); - return 0; - } - } - /* remove imported module */ - ADDOP(c, POP_TOP); - return 1; + /* build up the names */ + for (i = 0; i < n; i++) { + alias_ty alias = (alias_ty)asdl_seq_GET(s->v.ImportFrom.names, i); + Py_INCREF(alias->name); + PyTuple_SET_ITEM(names, i, alias->name); + } + + if (s->lineno > c->c_future->ff_lineno && s->v.ImportFrom.module && + !PyUnicode_CompareWithASCIIString(s->v.ImportFrom.module, "__future__")) { + Py_DECREF(level); + Py_DECREF(names); + return compiler_error(c, "from __future__ imports must occur " + "at the beginning of the file"); + } + + ADDOP_O(c, LOAD_CONST, level, consts); + Py_DECREF(level); + ADDOP_O(c, LOAD_CONST, names, consts); + Py_DECREF(names); + if (s->v.ImportFrom.module) { + ADDOP_NAME(c, IMPORT_NAME, s->v.ImportFrom.module, names); + } + else { + ADDOP_NAME(c, IMPORT_NAME, empty_string, names); + } + for (i = 0; i < n; i++) { + alias_ty alias = (alias_ty)asdl_seq_GET(s->v.ImportFrom.names, i); + identifier store_name; + + if (i == 0 && *PyUnicode_AS_UNICODE(alias->name) == '*') { + assert(n == 1); + ADDOP(c, IMPORT_STAR); + return 1; + } + + ADDOP_NAME(c, IMPORT_FROM, alias->name, names); + store_name = alias->name; + if (alias->asname) + store_name = alias->asname; + + if (!compiler_nameop(c, store_name, Store)) { + Py_DECREF(names); + return 0; + } + } + /* remove imported module */ + ADDOP(c, POP_TOP); + return 1; } static int compiler_assert(struct compiler *c, stmt_ty s) { - static PyObject *assertion_error = NULL; - basicblock *end; + static PyObject *assertion_error = NULL; + basicblock *end; - if (Py_OptimizeFlag) - return 1; - if (assertion_error == NULL) { - assertion_error = PyUnicode_InternFromString("AssertionError"); - if (assertion_error == NULL) - return 0; - } - if (s->v.Assert.test->kind == Tuple_kind && - asdl_seq_LEN(s->v.Assert.test->v.Tuple.elts) > 0) { - const char* msg = - "assertion is always true, perhaps remove parentheses?"; - if (PyErr_WarnExplicit(PyExc_SyntaxWarning, msg, c->c_filename, - c->u->u_lineno, NULL, NULL) == -1) - return 0; - } - VISIT(c, expr, s->v.Assert.test); - end = compiler_new_block(c); - if (end == NULL) - return 0; - ADDOP_JABS(c, POP_JUMP_IF_TRUE, end); - ADDOP_O(c, LOAD_GLOBAL, assertion_error, names); - if (s->v.Assert.msg) { - VISIT(c, expr, s->v.Assert.msg); - ADDOP_I(c, CALL_FUNCTION, 1); - } - ADDOP_I(c, RAISE_VARARGS, 1); - compiler_use_next_block(c, end); - return 1; + if (Py_OptimizeFlag) + return 1; + if (assertion_error == NULL) { + assertion_error = PyUnicode_InternFromString("AssertionError"); + if (assertion_error == NULL) + return 0; + } + if (s->v.Assert.test->kind == Tuple_kind && + asdl_seq_LEN(s->v.Assert.test->v.Tuple.elts) > 0) { + const char* msg = + "assertion is always true, perhaps remove parentheses?"; + if (PyErr_WarnExplicit(PyExc_SyntaxWarning, msg, c->c_filename, + c->u->u_lineno, NULL, NULL) == -1) + return 0; + } + VISIT(c, expr, s->v.Assert.test); + end = compiler_new_block(c); + if (end == NULL) + return 0; + ADDOP_JABS(c, POP_JUMP_IF_TRUE, end); + ADDOP_O(c, LOAD_GLOBAL, assertion_error, names); + if (s->v.Assert.msg) { + VISIT(c, expr, s->v.Assert.msg); + ADDOP_I(c, CALL_FUNCTION, 1); + } + ADDOP_I(c, RAISE_VARARGS, 1); + compiler_use_next_block(c, end); + return 1; } static int compiler_visit_stmt(struct compiler *c, stmt_ty s) { - int i, n; + int i, n; - /* Always assign a lineno to the next instruction for a stmt. */ - c->u->u_lineno = s->lineno; - c->u->u_lineno_set = 0; - - switch (s->kind) { - case FunctionDef_kind: - return compiler_function(c, s); - case ClassDef_kind: - return compiler_class(c, s); - case Return_kind: - if (c->u->u_ste->ste_type != FunctionBlock) - return compiler_error(c, "'return' outside function"); - if (s->v.Return.value) { - VISIT(c, expr, s->v.Return.value); - } - else - ADDOP_O(c, LOAD_CONST, Py_None, consts); - ADDOP(c, RETURN_VALUE); - break; - case Delete_kind: - VISIT_SEQ(c, expr, s->v.Delete.targets) - break; - case Assign_kind: - n = asdl_seq_LEN(s->v.Assign.targets); - VISIT(c, expr, s->v.Assign.value); - for (i = 0; i < n; i++) { - if (i < n - 1) - ADDOP(c, DUP_TOP); - VISIT(c, expr, - (expr_ty)asdl_seq_GET(s->v.Assign.targets, i)); - } - break; - case AugAssign_kind: - return compiler_augassign(c, s); - case For_kind: - return compiler_for(c, s); - case While_kind: - return compiler_while(c, s); - case If_kind: - return compiler_if(c, s); - case Raise_kind: - n = 0; - if (s->v.Raise.exc) { - VISIT(c, expr, s->v.Raise.exc); - n++; - if (s->v.Raise.cause) { - VISIT(c, expr, s->v.Raise.cause); - n++; - } - } - ADDOP_I(c, RAISE_VARARGS, n); - break; - case TryExcept_kind: - return compiler_try_except(c, s); - case TryFinally_kind: - return compiler_try_finally(c, s); - case Assert_kind: - return compiler_assert(c, s); - case Import_kind: - return compiler_import(c, s); - case ImportFrom_kind: - return compiler_from_import(c, s); - case Global_kind: - case Nonlocal_kind: - break; - case Expr_kind: - if (c->c_interactive && c->c_nestlevel <= 1) { - VISIT(c, expr, s->v.Expr.value); - ADDOP(c, PRINT_EXPR); - } - else if (s->v.Expr.value->kind != Str_kind && - s->v.Expr.value->kind != Num_kind) { - VISIT(c, expr, s->v.Expr.value); - ADDOP(c, POP_TOP); - } - break; - case Pass_kind: - break; - case Break_kind: - if (!compiler_in_loop(c)) - return compiler_error(c, "'break' outside loop"); - ADDOP(c, BREAK_LOOP); - break; - case Continue_kind: - return compiler_continue(c); - case With_kind: - return compiler_with(c, s); - } - return 1; + /* Always assign a lineno to the next instruction for a stmt. */ + c->u->u_lineno = s->lineno; + c->u->u_lineno_set = 0; + + switch (s->kind) { + case FunctionDef_kind: + return compiler_function(c, s); + case ClassDef_kind: + return compiler_class(c, s); + case Return_kind: + if (c->u->u_ste->ste_type != FunctionBlock) + return compiler_error(c, "'return' outside function"); + if (s->v.Return.value) { + VISIT(c, expr, s->v.Return.value); + } + else + ADDOP_O(c, LOAD_CONST, Py_None, consts); + ADDOP(c, RETURN_VALUE); + break; + case Delete_kind: + VISIT_SEQ(c, expr, s->v.Delete.targets) + break; + case Assign_kind: + n = asdl_seq_LEN(s->v.Assign.targets); + VISIT(c, expr, s->v.Assign.value); + for (i = 0; i < n; i++) { + if (i < n - 1) + ADDOP(c, DUP_TOP); + VISIT(c, expr, + (expr_ty)asdl_seq_GET(s->v.Assign.targets, i)); + } + break; + case AugAssign_kind: + return compiler_augassign(c, s); + case For_kind: + return compiler_for(c, s); + case While_kind: + return compiler_while(c, s); + case If_kind: + return compiler_if(c, s); + case Raise_kind: + n = 0; + if (s->v.Raise.exc) { + VISIT(c, expr, s->v.Raise.exc); + n++; + if (s->v.Raise.cause) { + VISIT(c, expr, s->v.Raise.cause); + n++; + } + } + ADDOP_I(c, RAISE_VARARGS, n); + break; + case TryExcept_kind: + return compiler_try_except(c, s); + case TryFinally_kind: + return compiler_try_finally(c, s); + case Assert_kind: + return compiler_assert(c, s); + case Import_kind: + return compiler_import(c, s); + case ImportFrom_kind: + return compiler_from_import(c, s); + case Global_kind: + case Nonlocal_kind: + break; + case Expr_kind: + if (c->c_interactive && c->c_nestlevel <= 1) { + VISIT(c, expr, s->v.Expr.value); + ADDOP(c, PRINT_EXPR); + } + else if (s->v.Expr.value->kind != Str_kind && + s->v.Expr.value->kind != Num_kind) { + VISIT(c, expr, s->v.Expr.value); + ADDOP(c, POP_TOP); + } + break; + case Pass_kind: + break; + case Break_kind: + if (!compiler_in_loop(c)) + return compiler_error(c, "'break' outside loop"); + ADDOP(c, BREAK_LOOP); + break; + case Continue_kind: + return compiler_continue(c); + case With_kind: + return compiler_with(c, s); + } + return 1; } static int unaryop(unaryop_ty op) { - switch (op) { - case Invert: - return UNARY_INVERT; - case Not: - return UNARY_NOT; - case UAdd: - return UNARY_POSITIVE; - case USub: - return UNARY_NEGATIVE; - default: - PyErr_Format(PyExc_SystemError, - "unary op %d should not be possible", op); - return 0; - } + switch (op) { + case Invert: + return UNARY_INVERT; + case Not: + return UNARY_NOT; + case UAdd: + return UNARY_POSITIVE; + case USub: + return UNARY_NEGATIVE; + default: + PyErr_Format(PyExc_SystemError, + "unary op %d should not be possible", op); + return 0; + } } static int binop(struct compiler *c, operator_ty op) { - switch (op) { - case Add: - return BINARY_ADD; - case Sub: - return BINARY_SUBTRACT; - case Mult: - return BINARY_MULTIPLY; - case Div: - return BINARY_TRUE_DIVIDE; - case Mod: - return BINARY_MODULO; - case Pow: - return BINARY_POWER; - case LShift: - return BINARY_LSHIFT; - case RShift: - return BINARY_RSHIFT; - case BitOr: - return BINARY_OR; - case BitXor: - return BINARY_XOR; - case BitAnd: - return BINARY_AND; - case FloorDiv: - return BINARY_FLOOR_DIVIDE; - default: - PyErr_Format(PyExc_SystemError, - "binary op %d should not be possible", op); - return 0; - } + switch (op) { + case Add: + return BINARY_ADD; + case Sub: + return BINARY_SUBTRACT; + case Mult: + return BINARY_MULTIPLY; + case Div: + return BINARY_TRUE_DIVIDE; + case Mod: + return BINARY_MODULO; + case Pow: + return BINARY_POWER; + case LShift: + return BINARY_LSHIFT; + case RShift: + return BINARY_RSHIFT; + case BitOr: + return BINARY_OR; + case BitXor: + return BINARY_XOR; + case BitAnd: + return BINARY_AND; + case FloorDiv: + return BINARY_FLOOR_DIVIDE; + default: + PyErr_Format(PyExc_SystemError, + "binary op %d should not be possible", op); + return 0; + } } static int cmpop(cmpop_ty op) { - switch (op) { - case Eq: - return PyCmp_EQ; - case NotEq: - return PyCmp_NE; - case Lt: - return PyCmp_LT; - case LtE: - return PyCmp_LE; - case Gt: - return PyCmp_GT; - case GtE: - return PyCmp_GE; - case Is: - return PyCmp_IS; - case IsNot: - return PyCmp_IS_NOT; - case In: - return PyCmp_IN; - case NotIn: - return PyCmp_NOT_IN; - default: - return PyCmp_BAD; - } + switch (op) { + case Eq: + return PyCmp_EQ; + case NotEq: + return PyCmp_NE; + case Lt: + return PyCmp_LT; + case LtE: + return PyCmp_LE; + case Gt: + return PyCmp_GT; + case GtE: + return PyCmp_GE; + case Is: + return PyCmp_IS; + case IsNot: + return PyCmp_IS_NOT; + case In: + return PyCmp_IN; + case NotIn: + return PyCmp_NOT_IN; + default: + return PyCmp_BAD; + } } static int inplace_binop(struct compiler *c, operator_ty op) { - switch (op) { - case Add: - return INPLACE_ADD; - case Sub: - return INPLACE_SUBTRACT; - case Mult: - return INPLACE_MULTIPLY; - case Div: - return INPLACE_TRUE_DIVIDE; - case Mod: - return INPLACE_MODULO; - case Pow: - return INPLACE_POWER; - case LShift: - return INPLACE_LSHIFT; - case RShift: - return INPLACE_RSHIFT; - case BitOr: - return INPLACE_OR; - case BitXor: - return INPLACE_XOR; - case BitAnd: - return INPLACE_AND; - case FloorDiv: - return INPLACE_FLOOR_DIVIDE; - default: - PyErr_Format(PyExc_SystemError, - "inplace binary op %d should not be possible", op); - return 0; - } + switch (op) { + case Add: + return INPLACE_ADD; + case Sub: + return INPLACE_SUBTRACT; + case Mult: + return INPLACE_MULTIPLY; + case Div: + return INPLACE_TRUE_DIVIDE; + case Mod: + return INPLACE_MODULO; + case Pow: + return INPLACE_POWER; + case LShift: + return INPLACE_LSHIFT; + case RShift: + return INPLACE_RSHIFT; + case BitOr: + return INPLACE_OR; + case BitXor: + return INPLACE_XOR; + case BitAnd: + return INPLACE_AND; + case FloorDiv: + return INPLACE_FLOOR_DIVIDE; + default: + PyErr_Format(PyExc_SystemError, + "inplace binary op %d should not be possible", op); + return 0; + } } static int compiler_nameop(struct compiler *c, identifier name, expr_context_ty ctx) { - int op, scope, arg; - enum { OP_FAST, OP_GLOBAL, OP_DEREF, OP_NAME } optype; + int op, scope, arg; + enum { OP_FAST, OP_GLOBAL, OP_DEREF, OP_NAME } optype; + + PyObject *dict = c->u->u_names; + PyObject *mangled; + /* XXX AugStore isn't used anywhere! */ + + mangled = _Py_Mangle(c->u->u_private, name); + if (!mangled) + return 0; - PyObject *dict = c->u->u_names; - PyObject *mangled; - /* XXX AugStore isn't used anywhere! */ - - mangled = _Py_Mangle(c->u->u_private, name); - if (!mangled) - return 0; - - op = 0; - optype = OP_NAME; - scope = PyST_GetScope(c->u->u_ste, mangled); - switch (scope) { - case FREE: - dict = c->u->u_freevars; - optype = OP_DEREF; - break; - case CELL: - dict = c->u->u_cellvars; - optype = OP_DEREF; - break; - case LOCAL: - if (c->u->u_ste->ste_type == FunctionBlock) - optype = OP_FAST; - break; - case GLOBAL_IMPLICIT: - if (c->u->u_ste->ste_type == FunctionBlock && - !c->u->u_ste->ste_unoptimized) - optype = OP_GLOBAL; - break; - case GLOBAL_EXPLICIT: - optype = OP_GLOBAL; - break; - default: - /* scope can be 0 */ - break; - } - - /* XXX Leave assert here, but handle __doc__ and the like better */ - assert(scope || PyUnicode_AS_UNICODE(name)[0] == '_'); - - switch (optype) { - case OP_DEREF: - switch (ctx) { - case Load: op = LOAD_DEREF; break; - case Store: op = STORE_DEREF; break; - case AugLoad: - case AugStore: - break; - case Del: - PyErr_Format(PyExc_SyntaxError, - "can not delete variable '%S' referenced " - "in nested scope", - name); - Py_DECREF(mangled); - return 0; - case Param: - default: - PyErr_SetString(PyExc_SystemError, - "param invalid for deref variable"); - return 0; - } - break; - case OP_FAST: - switch (ctx) { - case Load: op = LOAD_FAST; break; - case Store: op = STORE_FAST; break; - case Del: op = DELETE_FAST; break; - case AugLoad: - case AugStore: - break; - case Param: - default: - PyErr_SetString(PyExc_SystemError, - "param invalid for local variable"); - return 0; - } - ADDOP_O(c, op, mangled, varnames); - Py_DECREF(mangled); - return 1; - case OP_GLOBAL: - switch (ctx) { - case Load: op = LOAD_GLOBAL; break; - case Store: op = STORE_GLOBAL; break; - case Del: op = DELETE_GLOBAL; break; - case AugLoad: - case AugStore: - break; - case Param: - default: - PyErr_SetString(PyExc_SystemError, - "param invalid for global variable"); - return 0; - } - break; - case OP_NAME: - switch (ctx) { - case Load: op = LOAD_NAME; break; - case Store: op = STORE_NAME; break; - case Del: op = DELETE_NAME; break; - case AugLoad: - case AugStore: - break; - case Param: - default: - PyErr_SetString(PyExc_SystemError, - "param invalid for name variable"); - return 0; - } - break; - } - - assert(op); - arg = compiler_add_o(c, dict, mangled); - Py_DECREF(mangled); - if (arg < 0) - return 0; - return compiler_addop_i(c, op, arg); + op = 0; + optype = OP_NAME; + scope = PyST_GetScope(c->u->u_ste, mangled); + switch (scope) { + case FREE: + dict = c->u->u_freevars; + optype = OP_DEREF; + break; + case CELL: + dict = c->u->u_cellvars; + optype = OP_DEREF; + break; + case LOCAL: + if (c->u->u_ste->ste_type == FunctionBlock) + optype = OP_FAST; + break; + case GLOBAL_IMPLICIT: + if (c->u->u_ste->ste_type == FunctionBlock && + !c->u->u_ste->ste_unoptimized) + optype = OP_GLOBAL; + break; + case GLOBAL_EXPLICIT: + optype = OP_GLOBAL; + break; + default: + /* scope can be 0 */ + break; + } + + /* XXX Leave assert here, but handle __doc__ and the like better */ + assert(scope || PyUnicode_AS_UNICODE(name)[0] == '_'); + + switch (optype) { + case OP_DEREF: + switch (ctx) { + case Load: op = LOAD_DEREF; break; + case Store: op = STORE_DEREF; break; + case AugLoad: + case AugStore: + break; + case Del: + PyErr_Format(PyExc_SyntaxError, + "can not delete variable '%S' referenced " + "in nested scope", + name); + Py_DECREF(mangled); + return 0; + case Param: + default: + PyErr_SetString(PyExc_SystemError, + "param invalid for deref variable"); + return 0; + } + break; + case OP_FAST: + switch (ctx) { + case Load: op = LOAD_FAST; break; + case Store: op = STORE_FAST; break; + case Del: op = DELETE_FAST; break; + case AugLoad: + case AugStore: + break; + case Param: + default: + PyErr_SetString(PyExc_SystemError, + "param invalid for local variable"); + return 0; + } + ADDOP_O(c, op, mangled, varnames); + Py_DECREF(mangled); + return 1; + case OP_GLOBAL: + switch (ctx) { + case Load: op = LOAD_GLOBAL; break; + case Store: op = STORE_GLOBAL; break; + case Del: op = DELETE_GLOBAL; break; + case AugLoad: + case AugStore: + break; + case Param: + default: + PyErr_SetString(PyExc_SystemError, + "param invalid for global variable"); + return 0; + } + break; + case OP_NAME: + switch (ctx) { + case Load: op = LOAD_NAME; break; + case Store: op = STORE_NAME; break; + case Del: op = DELETE_NAME; break; + case AugLoad: + case AugStore: + break; + case Param: + default: + PyErr_SetString(PyExc_SystemError, + "param invalid for name variable"); + return 0; + } + break; + } + + assert(op); + arg = compiler_add_o(c, dict, mangled); + Py_DECREF(mangled); + if (arg < 0) + return 0; + return compiler_addop_i(c, op, arg); } static int compiler_boolop(struct compiler *c, expr_ty e) { - basicblock *end; - int jumpi, i, n; - asdl_seq *s; - - assert(e->kind == BoolOp_kind); - if (e->v.BoolOp.op == And) - jumpi = JUMP_IF_FALSE_OR_POP; - else - jumpi = JUMP_IF_TRUE_OR_POP; - end = compiler_new_block(c); - if (end == NULL) - return 0; - s = e->v.BoolOp.values; - n = asdl_seq_LEN(s) - 1; - assert(n >= 0); - for (i = 0; i < n; ++i) { - VISIT(c, expr, (expr_ty)asdl_seq_GET(s, i)); - ADDOP_JABS(c, jumpi, end); - } - VISIT(c, expr, (expr_ty)asdl_seq_GET(s, n)); - compiler_use_next_block(c, end); - return 1; + basicblock *end; + int jumpi, i, n; + asdl_seq *s; + + assert(e->kind == BoolOp_kind); + if (e->v.BoolOp.op == And) + jumpi = JUMP_IF_FALSE_OR_POP; + else + jumpi = JUMP_IF_TRUE_OR_POP; + end = compiler_new_block(c); + if (end == NULL) + return 0; + s = e->v.BoolOp.values; + n = asdl_seq_LEN(s) - 1; + assert(n >= 0); + for (i = 0; i < n; ++i) { + VISIT(c, expr, (expr_ty)asdl_seq_GET(s, i)); + ADDOP_JABS(c, jumpi, end); + } + VISIT(c, expr, (expr_ty)asdl_seq_GET(s, n)); + compiler_use_next_block(c, end); + return 1; } static int compiler_list(struct compiler *c, expr_ty e) { - int n = asdl_seq_LEN(e->v.List.elts); - if (e->v.List.ctx == Store) { - int i, seen_star = 0; - for (i = 0; i < n; i++) { - expr_ty elt = asdl_seq_GET(e->v.List.elts, i); - if (elt->kind == Starred_kind && !seen_star) { - if ((i >= (1 << 8)) || - (n-i-1 >= (INT_MAX >> 8))) - return compiler_error(c, - "too many expressions in " - "star-unpacking assignment"); - ADDOP_I(c, UNPACK_EX, (i + ((n-i-1) << 8))); - seen_star = 1; - asdl_seq_SET(e->v.List.elts, i, elt->v.Starred.value); - } else if (elt->kind == Starred_kind) { - return compiler_error(c, - "two starred expressions in assignment"); - } - } - if (!seen_star) { - ADDOP_I(c, UNPACK_SEQUENCE, n); - } - } - VISIT_SEQ(c, expr, e->v.List.elts); - if (e->v.List.ctx == Load) { - ADDOP_I(c, BUILD_LIST, n); - } - return 1; + int n = asdl_seq_LEN(e->v.List.elts); + if (e->v.List.ctx == Store) { + int i, seen_star = 0; + for (i = 0; i < n; i++) { + expr_ty elt = asdl_seq_GET(e->v.List.elts, i); + if (elt->kind == Starred_kind && !seen_star) { + if ((i >= (1 << 8)) || + (n-i-1 >= (INT_MAX >> 8))) + return compiler_error(c, + "too many expressions in " + "star-unpacking assignment"); + ADDOP_I(c, UNPACK_EX, (i + ((n-i-1) << 8))); + seen_star = 1; + asdl_seq_SET(e->v.List.elts, i, elt->v.Starred.value); + } else if (elt->kind == Starred_kind) { + return compiler_error(c, + "two starred expressions in assignment"); + } + } + if (!seen_star) { + ADDOP_I(c, UNPACK_SEQUENCE, n); + } + } + VISIT_SEQ(c, expr, e->v.List.elts); + if (e->v.List.ctx == Load) { + ADDOP_I(c, BUILD_LIST, n); + } + return 1; } static int compiler_tuple(struct compiler *c, expr_ty e) { - int n = asdl_seq_LEN(e->v.Tuple.elts); - if (e->v.Tuple.ctx == Store) { - int i, seen_star = 0; - for (i = 0; i < n; i++) { - expr_ty elt = asdl_seq_GET(e->v.Tuple.elts, i); - if (elt->kind == Starred_kind && !seen_star) { - if ((i >= (1 << 8)) || - (n-i-1 >= (INT_MAX >> 8))) - return compiler_error(c, - "too many expressions in " - "star-unpacking assignment"); - ADDOP_I(c, UNPACK_EX, (i + ((n-i-1) << 8))); - seen_star = 1; - asdl_seq_SET(e->v.Tuple.elts, i, elt->v.Starred.value); - } else if (elt->kind == Starred_kind) { - return compiler_error(c, - "two starred expressions in assignment"); - } - } - if (!seen_star) { - ADDOP_I(c, UNPACK_SEQUENCE, n); - } - } - VISIT_SEQ(c, expr, e->v.Tuple.elts); - if (e->v.Tuple.ctx == Load) { - ADDOP_I(c, BUILD_TUPLE, n); - } - return 1; + int n = asdl_seq_LEN(e->v.Tuple.elts); + if (e->v.Tuple.ctx == Store) { + int i, seen_star = 0; + for (i = 0; i < n; i++) { + expr_ty elt = asdl_seq_GET(e->v.Tuple.elts, i); + if (elt->kind == Starred_kind && !seen_star) { + if ((i >= (1 << 8)) || + (n-i-1 >= (INT_MAX >> 8))) + return compiler_error(c, + "too many expressions in " + "star-unpacking assignment"); + ADDOP_I(c, UNPACK_EX, (i + ((n-i-1) << 8))); + seen_star = 1; + asdl_seq_SET(e->v.Tuple.elts, i, elt->v.Starred.value); + } else if (elt->kind == Starred_kind) { + return compiler_error(c, + "two starred expressions in assignment"); + } + } + if (!seen_star) { + ADDOP_I(c, UNPACK_SEQUENCE, n); + } + } + VISIT_SEQ(c, expr, e->v.Tuple.elts); + if (e->v.Tuple.ctx == Load) { + ADDOP_I(c, BUILD_TUPLE, n); + } + return 1; } static int compiler_compare(struct compiler *c, expr_ty e) { - int i, n; - basicblock *cleanup = NULL; + int i, n; + basicblock *cleanup = NULL; - /* XXX the logic can be cleaned up for 1 or multiple comparisons */ - VISIT(c, expr, e->v.Compare.left); - n = asdl_seq_LEN(e->v.Compare.ops); - assert(n > 0); - if (n > 1) { - cleanup = compiler_new_block(c); - if (cleanup == NULL) - return 0; - VISIT(c, expr, - (expr_ty)asdl_seq_GET(e->v.Compare.comparators, 0)); - } - for (i = 1; i < n; i++) { - ADDOP(c, DUP_TOP); - ADDOP(c, ROT_THREE); - ADDOP_I(c, COMPARE_OP, - cmpop((cmpop_ty)(asdl_seq_GET( - e->v.Compare.ops, i - 1)))); - ADDOP_JABS(c, JUMP_IF_FALSE_OR_POP, cleanup); - NEXT_BLOCK(c); - if (i < (n - 1)) - VISIT(c, expr, - (expr_ty)asdl_seq_GET(e->v.Compare.comparators, i)); - } - VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Compare.comparators, n - 1)); - ADDOP_I(c, COMPARE_OP, - cmpop((cmpop_ty)(asdl_seq_GET(e->v.Compare.ops, n - 1)))); - if (n > 1) { - basicblock *end = compiler_new_block(c); - if (end == NULL) - return 0; - ADDOP_JREL(c, JUMP_FORWARD, end); - compiler_use_next_block(c, cleanup); - ADDOP(c, ROT_TWO); - ADDOP(c, POP_TOP); - compiler_use_next_block(c, end); - } - return 1; + /* XXX the logic can be cleaned up for 1 or multiple comparisons */ + VISIT(c, expr, e->v.Compare.left); + n = asdl_seq_LEN(e->v.Compare.ops); + assert(n > 0); + if (n > 1) { + cleanup = compiler_new_block(c); + if (cleanup == NULL) + return 0; + VISIT(c, expr, + (expr_ty)asdl_seq_GET(e->v.Compare.comparators, 0)); + } + for (i = 1; i < n; i++) { + ADDOP(c, DUP_TOP); + ADDOP(c, ROT_THREE); + ADDOP_I(c, COMPARE_OP, + cmpop((cmpop_ty)(asdl_seq_GET( + e->v.Compare.ops, i - 1)))); + ADDOP_JABS(c, JUMP_IF_FALSE_OR_POP, cleanup); + NEXT_BLOCK(c); + if (i < (n - 1)) + VISIT(c, expr, + (expr_ty)asdl_seq_GET(e->v.Compare.comparators, i)); + } + VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Compare.comparators, n - 1)); + ADDOP_I(c, COMPARE_OP, + cmpop((cmpop_ty)(asdl_seq_GET(e->v.Compare.ops, n - 1)))); + if (n > 1) { + basicblock *end = compiler_new_block(c); + if (end == NULL) + return 0; + ADDOP_JREL(c, JUMP_FORWARD, end); + compiler_use_next_block(c, cleanup); + ADDOP(c, ROT_TWO); + ADDOP(c, POP_TOP); + compiler_use_next_block(c, end); + } + return 1; } static int compiler_call(struct compiler *c, expr_ty e) { - VISIT(c, expr, e->v.Call.func); - return compiler_call_helper(c, 0, - e->v.Call.args, - e->v.Call.keywords, - e->v.Call.starargs, - e->v.Call.kwargs); + VISIT(c, expr, e->v.Call.func); + return compiler_call_helper(c, 0, + e->v.Call.args, + e->v.Call.keywords, + e->v.Call.starargs, + e->v.Call.kwargs); } /* shared code between compiler_call and compiler_class */ static int compiler_call_helper(struct compiler *c, - int n, /* Args already pushed */ - asdl_seq *args, - asdl_seq *keywords, - expr_ty starargs, - expr_ty kwargs) -{ - int code = 0; - - n += asdl_seq_LEN(args); - VISIT_SEQ(c, expr, args); - if (keywords) { - VISIT_SEQ(c, keyword, keywords); - n |= asdl_seq_LEN(keywords) << 8; - } - if (starargs) { - VISIT(c, expr, starargs); - code |= 1; - } - if (kwargs) { - VISIT(c, expr, kwargs); - code |= 2; - } - switch (code) { - case 0: - ADDOP_I(c, CALL_FUNCTION, n); - break; - case 1: - ADDOP_I(c, CALL_FUNCTION_VAR, n); - break; - case 2: - ADDOP_I(c, CALL_FUNCTION_KW, n); - break; - case 3: - ADDOP_I(c, CALL_FUNCTION_VAR_KW, n); - break; - } - return 1; + int n, /* Args already pushed */ + asdl_seq *args, + asdl_seq *keywords, + expr_ty starargs, + expr_ty kwargs) +{ + int code = 0; + + n += asdl_seq_LEN(args); + VISIT_SEQ(c, expr, args); + if (keywords) { + VISIT_SEQ(c, keyword, keywords); + n |= asdl_seq_LEN(keywords) << 8; + } + if (starargs) { + VISIT(c, expr, starargs); + code |= 1; + } + if (kwargs) { + VISIT(c, expr, kwargs); + code |= 2; + } + switch (code) { + case 0: + ADDOP_I(c, CALL_FUNCTION, n); + break; + case 1: + ADDOP_I(c, CALL_FUNCTION_VAR, n); + break; + case 2: + ADDOP_I(c, CALL_FUNCTION_KW, n); + break; + case 3: + ADDOP_I(c, CALL_FUNCTION_VAR_KW, n); + break; + } + return 1; } @@ -2787,228 +2787,228 @@ */ static int -compiler_comprehension_generator(struct compiler *c, - asdl_seq *generators, int gen_index, - expr_ty elt, expr_ty val, int type) -{ - /* generate code for the iterator, then each of the ifs, - and then write to the element */ - - comprehension_ty gen; - basicblock *start, *anchor, *skip, *if_cleanup; - int i, n; - - start = compiler_new_block(c); - skip = compiler_new_block(c); - if_cleanup = compiler_new_block(c); - anchor = compiler_new_block(c); - - if (start == NULL || skip == NULL || if_cleanup == NULL || - anchor == NULL) - return 0; - - gen = (comprehension_ty)asdl_seq_GET(generators, gen_index); - - if (gen_index == 0) { - /* Receive outermost iter as an implicit argument */ - c->u->u_argcount = 1; - ADDOP_I(c, LOAD_FAST, 0); - } - else { - /* Sub-iter - calculate on the fly */ - VISIT(c, expr, gen->iter); - ADDOP(c, GET_ITER); - } - compiler_use_next_block(c, start); - ADDOP_JREL(c, FOR_ITER, anchor); - NEXT_BLOCK(c); - VISIT(c, expr, gen->target); - - /* XXX this needs to be cleaned up...a lot! */ - n = asdl_seq_LEN(gen->ifs); - for (i = 0; i < n; i++) { - expr_ty e = (expr_ty)asdl_seq_GET(gen->ifs, i); - VISIT(c, expr, e); - ADDOP_JABS(c, POP_JUMP_IF_FALSE, if_cleanup); - NEXT_BLOCK(c); - } - - if (++gen_index < asdl_seq_LEN(generators)) - if (!compiler_comprehension_generator(c, - generators, gen_index, - elt, val, type)) - return 0; - - /* only append after the last for generator */ - if (gen_index >= asdl_seq_LEN(generators)) { - /* comprehension specific code */ - switch (type) { - case COMP_GENEXP: - VISIT(c, expr, elt); - ADDOP(c, YIELD_VALUE); - ADDOP(c, POP_TOP); - break; - case COMP_LISTCOMP: - VISIT(c, expr, elt); - ADDOP_I(c, LIST_APPEND, gen_index + 1); - break; - case COMP_SETCOMP: - VISIT(c, expr, elt); - ADDOP_I(c, SET_ADD, gen_index + 1); - break; - case COMP_DICTCOMP: - /* With 'd[k] = v', v is evaluated before k, so we do - the same. */ - VISIT(c, expr, val); - VISIT(c, expr, elt); - ADDOP_I(c, MAP_ADD, gen_index + 1); - break; - default: - return 0; - } - - compiler_use_next_block(c, skip); - } - compiler_use_next_block(c, if_cleanup); - ADDOP_JABS(c, JUMP_ABSOLUTE, start); - compiler_use_next_block(c, anchor); +compiler_comprehension_generator(struct compiler *c, + asdl_seq *generators, int gen_index, + expr_ty elt, expr_ty val, int type) +{ + /* generate code for the iterator, then each of the ifs, + and then write to the element */ + + comprehension_ty gen; + basicblock *start, *anchor, *skip, *if_cleanup; + int i, n; + + start = compiler_new_block(c); + skip = compiler_new_block(c); + if_cleanup = compiler_new_block(c); + anchor = compiler_new_block(c); + + if (start == NULL || skip == NULL || if_cleanup == NULL || + anchor == NULL) + return 0; + + gen = (comprehension_ty)asdl_seq_GET(generators, gen_index); + + if (gen_index == 0) { + /* Receive outermost iter as an implicit argument */ + c->u->u_argcount = 1; + ADDOP_I(c, LOAD_FAST, 0); + } + else { + /* Sub-iter - calculate on the fly */ + VISIT(c, expr, gen->iter); + ADDOP(c, GET_ITER); + } + compiler_use_next_block(c, start); + ADDOP_JREL(c, FOR_ITER, anchor); + NEXT_BLOCK(c); + VISIT(c, expr, gen->target); + + /* XXX this needs to be cleaned up...a lot! */ + n = asdl_seq_LEN(gen->ifs); + for (i = 0; i < n; i++) { + expr_ty e = (expr_ty)asdl_seq_GET(gen->ifs, i); + VISIT(c, expr, e); + ADDOP_JABS(c, POP_JUMP_IF_FALSE, if_cleanup); + NEXT_BLOCK(c); + } + + if (++gen_index < asdl_seq_LEN(generators)) + if (!compiler_comprehension_generator(c, + generators, gen_index, + elt, val, type)) + return 0; + + /* only append after the last for generator */ + if (gen_index >= asdl_seq_LEN(generators)) { + /* comprehension specific code */ + switch (type) { + case COMP_GENEXP: + VISIT(c, expr, elt); + ADDOP(c, YIELD_VALUE); + ADDOP(c, POP_TOP); + break; + case COMP_LISTCOMP: + VISIT(c, expr, elt); + ADDOP_I(c, LIST_APPEND, gen_index + 1); + break; + case COMP_SETCOMP: + VISIT(c, expr, elt); + ADDOP_I(c, SET_ADD, gen_index + 1); + break; + case COMP_DICTCOMP: + /* With 'd[k] = v', v is evaluated before k, so we do + the same. */ + VISIT(c, expr, val); + VISIT(c, expr, elt); + ADDOP_I(c, MAP_ADD, gen_index + 1); + break; + default: + return 0; + } + + compiler_use_next_block(c, skip); + } + compiler_use_next_block(c, if_cleanup); + ADDOP_JABS(c, JUMP_ABSOLUTE, start); + compiler_use_next_block(c, anchor); - return 1; + return 1; } static int compiler_comprehension(struct compiler *c, expr_ty e, int type, identifier name, - asdl_seq *generators, expr_ty elt, expr_ty val) + asdl_seq *generators, expr_ty elt, expr_ty val) { - PyCodeObject *co = NULL; - expr_ty outermost_iter; + PyCodeObject *co = NULL; + expr_ty outermost_iter; + + outermost_iter = ((comprehension_ty) + asdl_seq_GET(generators, 0))->iter; - outermost_iter = ((comprehension_ty) - asdl_seq_GET(generators, 0))->iter; + if (!compiler_enter_scope(c, name, (void *)e, e->lineno)) + goto error; + + if (type != COMP_GENEXP) { + int op; + switch (type) { + case COMP_LISTCOMP: + op = BUILD_LIST; + break; + case COMP_SETCOMP: + op = BUILD_SET; + break; + case COMP_DICTCOMP: + op = BUILD_MAP; + break; + default: + PyErr_Format(PyExc_SystemError, + "unknown comprehension type %d", type); + goto error_in_scope; + } + + ADDOP_I(c, op, 0); + } - if (!compiler_enter_scope(c, name, (void *)e, e->lineno)) - goto error; - - if (type != COMP_GENEXP) { - int op; - switch (type) { - case COMP_LISTCOMP: - op = BUILD_LIST; - break; - case COMP_SETCOMP: - op = BUILD_SET; - break; - case COMP_DICTCOMP: - op = BUILD_MAP; - break; - default: - PyErr_Format(PyExc_SystemError, - "unknown comprehension type %d", type); - goto error_in_scope; - } - - ADDOP_I(c, op, 0); - } - - if (!compiler_comprehension_generator(c, generators, 0, elt, - val, type)) - goto error_in_scope; - - if (type != COMP_GENEXP) { - ADDOP(c, RETURN_VALUE); - } - - co = assemble(c, 1); - compiler_exit_scope(c); - if (co == NULL) - goto error; - - if (!compiler_make_closure(c, co, 0)) - goto error; - Py_DECREF(co); - - VISIT(c, expr, outermost_iter); - ADDOP(c, GET_ITER); - ADDOP_I(c, CALL_FUNCTION, 1); - return 1; + if (!compiler_comprehension_generator(c, generators, 0, elt, + val, type)) + goto error_in_scope; + + if (type != COMP_GENEXP) { + ADDOP(c, RETURN_VALUE); + } + + co = assemble(c, 1); + compiler_exit_scope(c); + if (co == NULL) + goto error; + + if (!compiler_make_closure(c, co, 0)) + goto error; + Py_DECREF(co); + + VISIT(c, expr, outermost_iter); + ADDOP(c, GET_ITER); + ADDOP_I(c, CALL_FUNCTION, 1); + return 1; error_in_scope: - compiler_exit_scope(c); + compiler_exit_scope(c); error: - Py_XDECREF(co); - return 0; + Py_XDECREF(co); + return 0; } static int compiler_genexp(struct compiler *c, expr_ty e) { - static identifier name; - if (!name) { - name = PyUnicode_FromString(""); - if (!name) - return 0; - } - assert(e->kind == GeneratorExp_kind); - return compiler_comprehension(c, e, COMP_GENEXP, name, - e->v.GeneratorExp.generators, - e->v.GeneratorExp.elt, NULL); + static identifier name; + if (!name) { + name = PyUnicode_FromString(""); + if (!name) + return 0; + } + assert(e->kind == GeneratorExp_kind); + return compiler_comprehension(c, e, COMP_GENEXP, name, + e->v.GeneratorExp.generators, + e->v.GeneratorExp.elt, NULL); } static int compiler_listcomp(struct compiler *c, expr_ty e) { - static identifier name; - if (!name) { - name = PyUnicode_FromString(""); - if (!name) - return 0; - } - assert(e->kind == ListComp_kind); - return compiler_comprehension(c, e, COMP_LISTCOMP, name, - e->v.ListComp.generators, - e->v.ListComp.elt, NULL); + static identifier name; + if (!name) { + name = PyUnicode_FromString(""); + if (!name) + return 0; + } + assert(e->kind == ListComp_kind); + return compiler_comprehension(c, e, COMP_LISTCOMP, name, + e->v.ListComp.generators, + e->v.ListComp.elt, NULL); } static int compiler_setcomp(struct compiler *c, expr_ty e) { - static identifier name; - if (!name) { - name = PyUnicode_FromString(""); - if (!name) - return 0; - } - assert(e->kind == SetComp_kind); - return compiler_comprehension(c, e, COMP_SETCOMP, name, - e->v.SetComp.generators, - e->v.SetComp.elt, NULL); + static identifier name; + if (!name) { + name = PyUnicode_FromString(""); + if (!name) + return 0; + } + assert(e->kind == SetComp_kind); + return compiler_comprehension(c, e, COMP_SETCOMP, name, + e->v.SetComp.generators, + e->v.SetComp.elt, NULL); } static int compiler_dictcomp(struct compiler *c, expr_ty e) { - static identifier name; - if (!name) { - name = PyUnicode_FromString(""); - if (!name) - return 0; - } - assert(e->kind == DictComp_kind); - return compiler_comprehension(c, e, COMP_DICTCOMP, name, - e->v.DictComp.generators, - e->v.DictComp.key, e->v.DictComp.value); + static identifier name; + if (!name) { + name = PyUnicode_FromString(""); + if (!name) + return 0; + } + assert(e->kind == DictComp_kind); + return compiler_comprehension(c, e, COMP_DICTCOMP, name, + e->v.DictComp.generators, + e->v.DictComp.key, e->v.DictComp.value); } static int compiler_visit_keyword(struct compiler *c, keyword_ty k) { - ADDOP_O(c, LOAD_CONST, k->arg, consts); - VISIT(c, expr, k->value); - return 1; + ADDOP_O(c, LOAD_CONST, k->arg, consts); + VISIT(c, expr, k->value); + return 1; } -/* Test whether expression is constant. For constants, report +/* Test whether expression is constant. For constants, report whether they are true or false. Return values: 1 for true, 0 for false, -1 for non-constant. @@ -3017,39 +3017,39 @@ static int expr_constant(expr_ty e) { - char *id; - switch (e->kind) { - case Ellipsis_kind: - return 1; - case Num_kind: - return PyObject_IsTrue(e->v.Num.n); - case Str_kind: - return PyObject_IsTrue(e->v.Str.s); - case Name_kind: - /* optimize away names that can't be reassigned */ - id = PyBytes_AS_STRING( - _PyUnicode_AsDefaultEncodedString(e->v.Name.id, NULL)); - if (strcmp(id, "True") == 0) return 1; - if (strcmp(id, "False") == 0) return 0; - if (strcmp(id, "None") == 0) return 0; - if (strcmp(id, "__debug__") == 0) - return ! Py_OptimizeFlag; - /* fall through */ - default: - return -1; - } + char *id; + switch (e->kind) { + case Ellipsis_kind: + return 1; + case Num_kind: + return PyObject_IsTrue(e->v.Num.n); + case Str_kind: + return PyObject_IsTrue(e->v.Str.s); + case Name_kind: + /* optimize away names that can't be reassigned */ + id = PyBytes_AS_STRING( + _PyUnicode_AsDefaultEncodedString(e->v.Name.id, NULL)); + if (strcmp(id, "True") == 0) return 1; + if (strcmp(id, "False") == 0) return 0; + if (strcmp(id, "None") == 0) return 0; + if (strcmp(id, "__debug__") == 0) + return ! Py_OptimizeFlag; + /* fall through */ + default: + return -1; + } } /* Implements the with statement from PEP 343. - The semantics outlined in that PEP are as follows: + The semantics outlined in that PEP are as follows: with EXPR as VAR: BLOCK - + It is implemented roughly as: - + context = EXPR exit = context.__exit__ # not calling it value = context.__enter__() @@ -3058,9 +3058,9 @@ BLOCK finally: if an exception was raised: - exc = copy of (exception, instance, traceback) + exc = copy of (exception, instance, traceback) else: - exc = (None, None, None) + exc = (None, None, None) exit(*exc) */ static int @@ -3073,7 +3073,7 @@ block = compiler_new_block(c); finally = compiler_new_block(c); if (!block || !finally) - return 0; + return 0; /* Evaluate EXPR */ VISIT(c, expr, s->v.With.context_expr); @@ -3082,15 +3082,15 @@ /* SETUP_WITH pushes a finally block. */ compiler_use_next_block(c, block); if (!compiler_push_fblock(c, FINALLY_TRY, block)) { - return 0; + return 0; } if (s->v.With.optional_vars) { - VISIT(c, expr, s->v.With.optional_vars); + VISIT(c, expr, s->v.With.optional_vars); } else { - /* Discard result from context.__enter__() */ - ADDOP(c, POP_TOP); + /* Discard result from context.__enter__() */ + ADDOP(c, POP_TOP); } /* BLOCK code */ @@ -3103,7 +3103,7 @@ ADDOP_O(c, LOAD_CONST, Py_None, consts); compiler_use_next_block(c, finally); if (!compiler_push_fblock(c, FINALLY_END, finally)) - return 0; + return 0; /* Finally block starts; context.__exit__ is on the stack under the exception or return information. Just issue our magic @@ -3119,240 +3119,240 @@ static int compiler_visit_expr(struct compiler *c, expr_ty e) { - int i, n; + int i, n; - /* If expr e has a different line number than the last expr/stmt, - set a new line number for the next instruction. - */ - if (e->lineno > c->u->u_lineno) { - c->u->u_lineno = e->lineno; - c->u->u_lineno_set = 0; - } - switch (e->kind) { - case BoolOp_kind: - return compiler_boolop(c, e); - case BinOp_kind: - VISIT(c, expr, e->v.BinOp.left); - VISIT(c, expr, e->v.BinOp.right); - ADDOP(c, binop(c, e->v.BinOp.op)); - break; - case UnaryOp_kind: - VISIT(c, expr, e->v.UnaryOp.operand); - ADDOP(c, unaryop(e->v.UnaryOp.op)); - break; - case Lambda_kind: - return compiler_lambda(c, e); - case IfExp_kind: - return compiler_ifexp(c, e); - case Dict_kind: - n = asdl_seq_LEN(e->v.Dict.values); - ADDOP_I(c, BUILD_MAP, (n>0xFFFF ? 0xFFFF : n)); - for (i = 0; i < n; i++) { - VISIT(c, expr, - (expr_ty)asdl_seq_GET(e->v.Dict.values, i)); - VISIT(c, expr, - (expr_ty)asdl_seq_GET(e->v.Dict.keys, i)); - ADDOP(c, STORE_MAP); - } - break; - case Set_kind: - n = asdl_seq_LEN(e->v.Set.elts); - VISIT_SEQ(c, expr, e->v.Set.elts); - ADDOP_I(c, BUILD_SET, n); - break; - case GeneratorExp_kind: - return compiler_genexp(c, e); - case ListComp_kind: - return compiler_listcomp(c, e); - case SetComp_kind: - return compiler_setcomp(c, e); - case DictComp_kind: - return compiler_dictcomp(c, e); - case Yield_kind: - if (c->u->u_ste->ste_type != FunctionBlock) - return compiler_error(c, "'yield' outside function"); - if (e->v.Yield.value) { - VISIT(c, expr, e->v.Yield.value); - } - else { - ADDOP_O(c, LOAD_CONST, Py_None, consts); - } - ADDOP(c, YIELD_VALUE); - break; - case Compare_kind: - return compiler_compare(c, e); - case Call_kind: - return compiler_call(c, e); - case Num_kind: - ADDOP_O(c, LOAD_CONST, e->v.Num.n, consts); - break; - case Str_kind: - ADDOP_O(c, LOAD_CONST, e->v.Str.s, consts); - break; - case Bytes_kind: - ADDOP_O(c, LOAD_CONST, e->v.Bytes.s, consts); - break; - case Ellipsis_kind: - ADDOP_O(c, LOAD_CONST, Py_Ellipsis, consts); - break; - /* The following exprs can be assignment targets. */ - case Attribute_kind: - if (e->v.Attribute.ctx != AugStore) - VISIT(c, expr, e->v.Attribute.value); - switch (e->v.Attribute.ctx) { - case AugLoad: - ADDOP(c, DUP_TOP); - /* Fall through to load */ - case Load: - ADDOP_NAME(c, LOAD_ATTR, e->v.Attribute.attr, names); - break; - case AugStore: - ADDOP(c, ROT_TWO); - /* Fall through to save */ - case Store: - ADDOP_NAME(c, STORE_ATTR, e->v.Attribute.attr, names); - break; - case Del: - ADDOP_NAME(c, DELETE_ATTR, e->v.Attribute.attr, names); - break; - case Param: - default: - PyErr_SetString(PyExc_SystemError, - "param invalid in attribute expression"); - return 0; - } - break; - case Subscript_kind: - switch (e->v.Subscript.ctx) { - case AugLoad: - VISIT(c, expr, e->v.Subscript.value); - VISIT_SLICE(c, e->v.Subscript.slice, AugLoad); - break; - case Load: - VISIT(c, expr, e->v.Subscript.value); - VISIT_SLICE(c, e->v.Subscript.slice, Load); - break; - case AugStore: - VISIT_SLICE(c, e->v.Subscript.slice, AugStore); - break; - case Store: - VISIT(c, expr, e->v.Subscript.value); - VISIT_SLICE(c, e->v.Subscript.slice, Store); - break; - case Del: - VISIT(c, expr, e->v.Subscript.value); - VISIT_SLICE(c, e->v.Subscript.slice, Del); - break; - case Param: - default: - PyErr_SetString(PyExc_SystemError, - "param invalid in subscript expression"); - return 0; - } - break; - case Starred_kind: - switch (e->v.Starred.ctx) { - case Store: - /* In all legitimate cases, the Starred node was already replaced - * by compiler_list/compiler_tuple. XXX: is that okay? */ - return compiler_error(c, - "starred assignment target must be in a list or tuple"); - default: - return compiler_error(c, - "can use starred expression only as assignment target"); - } - break; - case Name_kind: - return compiler_nameop(c, e->v.Name.id, e->v.Name.ctx); - /* child nodes of List and Tuple will have expr_context set */ - case List_kind: - return compiler_list(c, e); - case Tuple_kind: - return compiler_tuple(c, e); - } - return 1; + /* If expr e has a different line number than the last expr/stmt, + set a new line number for the next instruction. + */ + if (e->lineno > c->u->u_lineno) { + c->u->u_lineno = e->lineno; + c->u->u_lineno_set = 0; + } + switch (e->kind) { + case BoolOp_kind: + return compiler_boolop(c, e); + case BinOp_kind: + VISIT(c, expr, e->v.BinOp.left); + VISIT(c, expr, e->v.BinOp.right); + ADDOP(c, binop(c, e->v.BinOp.op)); + break; + case UnaryOp_kind: + VISIT(c, expr, e->v.UnaryOp.operand); + ADDOP(c, unaryop(e->v.UnaryOp.op)); + break; + case Lambda_kind: + return compiler_lambda(c, e); + case IfExp_kind: + return compiler_ifexp(c, e); + case Dict_kind: + n = asdl_seq_LEN(e->v.Dict.values); + ADDOP_I(c, BUILD_MAP, (n>0xFFFF ? 0xFFFF : n)); + for (i = 0; i < n; i++) { + VISIT(c, expr, + (expr_ty)asdl_seq_GET(e->v.Dict.values, i)); + VISIT(c, expr, + (expr_ty)asdl_seq_GET(e->v.Dict.keys, i)); + ADDOP(c, STORE_MAP); + } + break; + case Set_kind: + n = asdl_seq_LEN(e->v.Set.elts); + VISIT_SEQ(c, expr, e->v.Set.elts); + ADDOP_I(c, BUILD_SET, n); + break; + case GeneratorExp_kind: + return compiler_genexp(c, e); + case ListComp_kind: + return compiler_listcomp(c, e); + case SetComp_kind: + return compiler_setcomp(c, e); + case DictComp_kind: + return compiler_dictcomp(c, e); + case Yield_kind: + if (c->u->u_ste->ste_type != FunctionBlock) + return compiler_error(c, "'yield' outside function"); + if (e->v.Yield.value) { + VISIT(c, expr, e->v.Yield.value); + } + else { + ADDOP_O(c, LOAD_CONST, Py_None, consts); + } + ADDOP(c, YIELD_VALUE); + break; + case Compare_kind: + return compiler_compare(c, e); + case Call_kind: + return compiler_call(c, e); + case Num_kind: + ADDOP_O(c, LOAD_CONST, e->v.Num.n, consts); + break; + case Str_kind: + ADDOP_O(c, LOAD_CONST, e->v.Str.s, consts); + break; + case Bytes_kind: + ADDOP_O(c, LOAD_CONST, e->v.Bytes.s, consts); + break; + case Ellipsis_kind: + ADDOP_O(c, LOAD_CONST, Py_Ellipsis, consts); + break; + /* The following exprs can be assignment targets. */ + case Attribute_kind: + if (e->v.Attribute.ctx != AugStore) + VISIT(c, expr, e->v.Attribute.value); + switch (e->v.Attribute.ctx) { + case AugLoad: + ADDOP(c, DUP_TOP); + /* Fall through to load */ + case Load: + ADDOP_NAME(c, LOAD_ATTR, e->v.Attribute.attr, names); + break; + case AugStore: + ADDOP(c, ROT_TWO); + /* Fall through to save */ + case Store: + ADDOP_NAME(c, STORE_ATTR, e->v.Attribute.attr, names); + break; + case Del: + ADDOP_NAME(c, DELETE_ATTR, e->v.Attribute.attr, names); + break; + case Param: + default: + PyErr_SetString(PyExc_SystemError, + "param invalid in attribute expression"); + return 0; + } + break; + case Subscript_kind: + switch (e->v.Subscript.ctx) { + case AugLoad: + VISIT(c, expr, e->v.Subscript.value); + VISIT_SLICE(c, e->v.Subscript.slice, AugLoad); + break; + case Load: + VISIT(c, expr, e->v.Subscript.value); + VISIT_SLICE(c, e->v.Subscript.slice, Load); + break; + case AugStore: + VISIT_SLICE(c, e->v.Subscript.slice, AugStore); + break; + case Store: + VISIT(c, expr, e->v.Subscript.value); + VISIT_SLICE(c, e->v.Subscript.slice, Store); + break; + case Del: + VISIT(c, expr, e->v.Subscript.value); + VISIT_SLICE(c, e->v.Subscript.slice, Del); + break; + case Param: + default: + PyErr_SetString(PyExc_SystemError, + "param invalid in subscript expression"); + return 0; + } + break; + case Starred_kind: + switch (e->v.Starred.ctx) { + case Store: + /* In all legitimate cases, the Starred node was already replaced + * by compiler_list/compiler_tuple. XXX: is that okay? */ + return compiler_error(c, + "starred assignment target must be in a list or tuple"); + default: + return compiler_error(c, + "can use starred expression only as assignment target"); + } + break; + case Name_kind: + return compiler_nameop(c, e->v.Name.id, e->v.Name.ctx); + /* child nodes of List and Tuple will have expr_context set */ + case List_kind: + return compiler_list(c, e); + case Tuple_kind: + return compiler_tuple(c, e); + } + return 1; } static int compiler_augassign(struct compiler *c, stmt_ty s) { - expr_ty e = s->v.AugAssign.target; - expr_ty auge; + expr_ty e = s->v.AugAssign.target; + expr_ty auge; - assert(s->kind == AugAssign_kind); + assert(s->kind == AugAssign_kind); - switch (e->kind) { - case Attribute_kind: - auge = Attribute(e->v.Attribute.value, e->v.Attribute.attr, - AugLoad, e->lineno, e->col_offset, c->c_arena); - if (auge == NULL) - return 0; - VISIT(c, expr, auge); - VISIT(c, expr, s->v.AugAssign.value); - ADDOP(c, inplace_binop(c, s->v.AugAssign.op)); - auge->v.Attribute.ctx = AugStore; - VISIT(c, expr, auge); - break; - case Subscript_kind: - auge = Subscript(e->v.Subscript.value, e->v.Subscript.slice, - AugLoad, e->lineno, e->col_offset, c->c_arena); - if (auge == NULL) - return 0; - VISIT(c, expr, auge); - VISIT(c, expr, s->v.AugAssign.value); - ADDOP(c, inplace_binop(c, s->v.AugAssign.op)); - auge->v.Subscript.ctx = AugStore; - VISIT(c, expr, auge); - break; - case Name_kind: - if (!compiler_nameop(c, e->v.Name.id, Load)) - return 0; - VISIT(c, expr, s->v.AugAssign.value); - ADDOP(c, inplace_binop(c, s->v.AugAssign.op)); - return compiler_nameop(c, e->v.Name.id, Store); - default: - PyErr_Format(PyExc_SystemError, - "invalid node type (%d) for augmented assignment", - e->kind); - return 0; - } - return 1; + switch (e->kind) { + case Attribute_kind: + auge = Attribute(e->v.Attribute.value, e->v.Attribute.attr, + AugLoad, e->lineno, e->col_offset, c->c_arena); + if (auge == NULL) + return 0; + VISIT(c, expr, auge); + VISIT(c, expr, s->v.AugAssign.value); + ADDOP(c, inplace_binop(c, s->v.AugAssign.op)); + auge->v.Attribute.ctx = AugStore; + VISIT(c, expr, auge); + break; + case Subscript_kind: + auge = Subscript(e->v.Subscript.value, e->v.Subscript.slice, + AugLoad, e->lineno, e->col_offset, c->c_arena); + if (auge == NULL) + return 0; + VISIT(c, expr, auge); + VISIT(c, expr, s->v.AugAssign.value); + ADDOP(c, inplace_binop(c, s->v.AugAssign.op)); + auge->v.Subscript.ctx = AugStore; + VISIT(c, expr, auge); + break; + case Name_kind: + if (!compiler_nameop(c, e->v.Name.id, Load)) + return 0; + VISIT(c, expr, s->v.AugAssign.value); + ADDOP(c, inplace_binop(c, s->v.AugAssign.op)); + return compiler_nameop(c, e->v.Name.id, Store); + default: + PyErr_Format(PyExc_SystemError, + "invalid node type (%d) for augmented assignment", + e->kind); + return 0; + } + return 1; } static int compiler_push_fblock(struct compiler *c, enum fblocktype t, basicblock *b) { - struct fblockinfo *f; - if (c->u->u_nfblocks >= CO_MAXBLOCKS) { - PyErr_SetString(PyExc_SystemError, - "too many statically nested blocks"); - return 0; - } - f = &c->u->u_fblock[c->u->u_nfblocks++]; - f->fb_type = t; - f->fb_block = b; - return 1; + struct fblockinfo *f; + if (c->u->u_nfblocks >= CO_MAXBLOCKS) { + PyErr_SetString(PyExc_SystemError, + "too many statically nested blocks"); + return 0; + } + f = &c->u->u_fblock[c->u->u_nfblocks++]; + f->fb_type = t; + f->fb_block = b; + return 1; } static void compiler_pop_fblock(struct compiler *c, enum fblocktype t, basicblock *b) { - struct compiler_unit *u = c->u; - assert(u->u_nfblocks > 0); - u->u_nfblocks--; - assert(u->u_fblock[u->u_nfblocks].fb_type == t); - assert(u->u_fblock[u->u_nfblocks].fb_block == b); + struct compiler_unit *u = c->u; + assert(u->u_nfblocks > 0); + u->u_nfblocks--; + assert(u->u_fblock[u->u_nfblocks].fb_type == t); + assert(u->u_fblock[u->u_nfblocks].fb_block == b); } static int compiler_in_loop(struct compiler *c) { - int i; - struct compiler_unit *u = c->u; - for (i = 0; i < u->u_nfblocks; ++i) { - if (u->u_fblock[i].fb_type == LOOP) - return 1; - } - return 0; + int i; + struct compiler_unit *u = c->u; + for (i = 0; i < u->u_nfblocks; ++i) { + if (u->u_fblock[i].fb_type == LOOP) + return 1; + } + return 0; } /* Raises a SyntaxError and returns 0. If something goes wrong, a different exception may be raised. @@ -3361,143 +3361,143 @@ static int compiler_error(struct compiler *c, const char *errstr) { - PyObject *loc; - PyObject *u = NULL, *v = NULL; + PyObject *loc; + PyObject *u = NULL, *v = NULL; - loc = PyErr_ProgramText(c->c_filename, c->u->u_lineno); - if (!loc) { - Py_INCREF(Py_None); - loc = Py_None; - } - u = Py_BuildValue("(ziOO)", c->c_filename, c->u->u_lineno, - Py_None, loc); - if (!u) - goto exit; - v = Py_BuildValue("(zO)", errstr, u); - if (!v) - goto exit; - PyErr_SetObject(PyExc_SyntaxError, v); + loc = PyErr_ProgramText(c->c_filename, c->u->u_lineno); + if (!loc) { + Py_INCREF(Py_None); + loc = Py_None; + } + u = Py_BuildValue("(ziOO)", c->c_filename, c->u->u_lineno, + Py_None, loc); + if (!u) + goto exit; + v = Py_BuildValue("(zO)", errstr, u); + if (!v) + goto exit; + PyErr_SetObject(PyExc_SyntaxError, v); exit: - Py_DECREF(loc); - Py_XDECREF(u); - Py_XDECREF(v); - return 0; + Py_DECREF(loc); + Py_XDECREF(u); + Py_XDECREF(v); + return 0; } static int -compiler_handle_subscr(struct compiler *c, const char *kind, - expr_context_ty ctx) -{ - int op = 0; - - /* XXX this code is duplicated */ - switch (ctx) { - case AugLoad: /* fall through to Load */ - case Load: op = BINARY_SUBSCR; break; - case AugStore:/* fall through to Store */ - case Store: op = STORE_SUBSCR; break; - case Del: op = DELETE_SUBSCR; break; - case Param: - PyErr_Format(PyExc_SystemError, - "invalid %s kind %d in subscript\n", - kind, ctx); - return 0; - } - if (ctx == AugLoad) { - ADDOP_I(c, DUP_TOPX, 2); - } - else if (ctx == AugStore) { - ADDOP(c, ROT_THREE); - } - ADDOP(c, op); - return 1; +compiler_handle_subscr(struct compiler *c, const char *kind, + expr_context_ty ctx) +{ + int op = 0; + + /* XXX this code is duplicated */ + switch (ctx) { + case AugLoad: /* fall through to Load */ + case Load: op = BINARY_SUBSCR; break; + case AugStore:/* fall through to Store */ + case Store: op = STORE_SUBSCR; break; + case Del: op = DELETE_SUBSCR; break; + case Param: + PyErr_Format(PyExc_SystemError, + "invalid %s kind %d in subscript\n", + kind, ctx); + return 0; + } + if (ctx == AugLoad) { + ADDOP_I(c, DUP_TOPX, 2); + } + else if (ctx == AugStore) { + ADDOP(c, ROT_THREE); + } + ADDOP(c, op); + return 1; } static int compiler_slice(struct compiler *c, slice_ty s, expr_context_ty ctx) { - int n = 2; - assert(s->kind == Slice_kind); + int n = 2; + assert(s->kind == Slice_kind); - /* only handles the cases where BUILD_SLICE is emitted */ - if (s->v.Slice.lower) { - VISIT(c, expr, s->v.Slice.lower); - } - else { - ADDOP_O(c, LOAD_CONST, Py_None, consts); - } - - if (s->v.Slice.upper) { - VISIT(c, expr, s->v.Slice.upper); - } - else { - ADDOP_O(c, LOAD_CONST, Py_None, consts); - } - - if (s->v.Slice.step) { - n++; - VISIT(c, expr, s->v.Slice.step); - } - ADDOP_I(c, BUILD_SLICE, n); - return 1; + /* only handles the cases where BUILD_SLICE is emitted */ + if (s->v.Slice.lower) { + VISIT(c, expr, s->v.Slice.lower); + } + else { + ADDOP_O(c, LOAD_CONST, Py_None, consts); + } + + if (s->v.Slice.upper) { + VISIT(c, expr, s->v.Slice.upper); + } + else { + ADDOP_O(c, LOAD_CONST, Py_None, consts); + } + + if (s->v.Slice.step) { + n++; + VISIT(c, expr, s->v.Slice.step); + } + ADDOP_I(c, BUILD_SLICE, n); + return 1; } static int -compiler_visit_nested_slice(struct compiler *c, slice_ty s, - expr_context_ty ctx) -{ - switch (s->kind) { - case Slice_kind: - return compiler_slice(c, s, ctx); - case Index_kind: - VISIT(c, expr, s->v.Index.value); - break; - case ExtSlice_kind: - default: - PyErr_SetString(PyExc_SystemError, - "extended slice invalid in nested slice"); - return 0; - } - return 1; +compiler_visit_nested_slice(struct compiler *c, slice_ty s, + expr_context_ty ctx) +{ + switch (s->kind) { + case Slice_kind: + return compiler_slice(c, s, ctx); + case Index_kind: + VISIT(c, expr, s->v.Index.value); + break; + case ExtSlice_kind: + default: + PyErr_SetString(PyExc_SystemError, + "extended slice invalid in nested slice"); + return 0; + } + return 1; } static int compiler_visit_slice(struct compiler *c, slice_ty s, expr_context_ty ctx) { - char * kindname = NULL; - switch (s->kind) { - case Index_kind: - kindname = "index"; - if (ctx != AugStore) { - VISIT(c, expr, s->v.Index.value); - } - break; - case Slice_kind: - kindname = "slice"; - if (ctx != AugStore) { - if (!compiler_slice(c, s, ctx)) - return 0; - } - break; - case ExtSlice_kind: - kindname = "extended slice"; - if (ctx != AugStore) { - int i, n = asdl_seq_LEN(s->v.ExtSlice.dims); - for (i = 0; i < n; i++) { - slice_ty sub = (slice_ty)asdl_seq_GET( - s->v.ExtSlice.dims, i); - if (!compiler_visit_nested_slice(c, sub, ctx)) - return 0; - } - ADDOP_I(c, BUILD_TUPLE, n); - } - break; - default: - PyErr_Format(PyExc_SystemError, - "invalid subscript kind %d", s->kind); - return 0; - } - return compiler_handle_subscr(c, kindname, ctx); + char * kindname = NULL; + switch (s->kind) { + case Index_kind: + kindname = "index"; + if (ctx != AugStore) { + VISIT(c, expr, s->v.Index.value); + } + break; + case Slice_kind: + kindname = "slice"; + if (ctx != AugStore) { + if (!compiler_slice(c, s, ctx)) + return 0; + } + break; + case ExtSlice_kind: + kindname = "extended slice"; + if (ctx != AugStore) { + int i, n = asdl_seq_LEN(s->v.ExtSlice.dims); + for (i = 0; i < n; i++) { + slice_ty sub = (slice_ty)asdl_seq_GET( + s->v.ExtSlice.dims, i); + if (!compiler_visit_nested_slice(c, sub, ctx)) + return 0; + } + ADDOP_I(c, BUILD_TUPLE, n); + } + break; + default: + PyErr_Format(PyExc_SystemError, + "invalid subscript kind %d", s->kind); + return 0; + } + return compiler_handle_subscr(c, kindname, ctx); } /* End of the compiler section, beginning of the assembler section */ @@ -3509,73 +3509,73 @@ */ struct assembler { - PyObject *a_bytecode; /* string containing bytecode */ - int a_offset; /* offset into bytecode */ - int a_nblocks; /* number of reachable blocks */ - basicblock **a_postorder; /* list of blocks in dfs postorder */ - PyObject *a_lnotab; /* string containing lnotab */ - int a_lnotab_off; /* offset into lnotab */ - int a_lineno; /* last lineno of emitted instruction */ - int a_lineno_off; /* bytecode offset of last lineno */ + PyObject *a_bytecode; /* string containing bytecode */ + int a_offset; /* offset into bytecode */ + int a_nblocks; /* number of reachable blocks */ + basicblock **a_postorder; /* list of blocks in dfs postorder */ + PyObject *a_lnotab; /* string containing lnotab */ + int a_lnotab_off; /* offset into lnotab */ + int a_lineno; /* last lineno of emitted instruction */ + int a_lineno_off; /* bytecode offset of last lineno */ }; static void dfs(struct compiler *c, basicblock *b, struct assembler *a) { - int i; - struct instr *instr = NULL; + int i; + struct instr *instr = NULL; - if (b->b_seen) - return; - b->b_seen = 1; - if (b->b_next != NULL) - dfs(c, b->b_next, a); - for (i = 0; i < b->b_iused; i++) { - instr = &b->b_instr[i]; - if (instr->i_jrel || instr->i_jabs) - dfs(c, instr->i_target, a); - } - a->a_postorder[a->a_nblocks++] = b; + if (b->b_seen) + return; + b->b_seen = 1; + if (b->b_next != NULL) + dfs(c, b->b_next, a); + for (i = 0; i < b->b_iused; i++) { + instr = &b->b_instr[i]; + if (instr->i_jrel || instr->i_jabs) + dfs(c, instr->i_target, a); + } + a->a_postorder[a->a_nblocks++] = b; } static int stackdepth_walk(struct compiler *c, basicblock *b, int depth, int maxdepth) { - int i, target_depth; - struct instr *instr; - if (b->b_seen || b->b_startdepth >= depth) - return maxdepth; - b->b_seen = 1; - b->b_startdepth = depth; - for (i = 0; i < b->b_iused; i++) { - instr = &b->b_instr[i]; - depth += opcode_stack_effect(instr->i_opcode, instr->i_oparg); - if (depth > maxdepth) - maxdepth = depth; - assert(depth >= 0); /* invalid code or bug in stackdepth() */ - if (instr->i_jrel || instr->i_jabs) { - target_depth = depth; - if (instr->i_opcode == FOR_ITER) { - target_depth = depth-2; - } else if (instr->i_opcode == SETUP_FINALLY || - instr->i_opcode == SETUP_EXCEPT) { - target_depth = depth+3; - if (target_depth > maxdepth) - maxdepth = target_depth; - } - maxdepth = stackdepth_walk(c, instr->i_target, - target_depth, maxdepth); - if (instr->i_opcode == JUMP_ABSOLUTE || - instr->i_opcode == JUMP_FORWARD) { - goto out; /* remaining code is dead */ - } - } - } - if (b->b_next) - maxdepth = stackdepth_walk(c, b->b_next, depth, maxdepth); + int i, target_depth; + struct instr *instr; + if (b->b_seen || b->b_startdepth >= depth) + return maxdepth; + b->b_seen = 1; + b->b_startdepth = depth; + for (i = 0; i < b->b_iused; i++) { + instr = &b->b_instr[i]; + depth += opcode_stack_effect(instr->i_opcode, instr->i_oparg); + if (depth > maxdepth) + maxdepth = depth; + assert(depth >= 0); /* invalid code or bug in stackdepth() */ + if (instr->i_jrel || instr->i_jabs) { + target_depth = depth; + if (instr->i_opcode == FOR_ITER) { + target_depth = depth-2; + } else if (instr->i_opcode == SETUP_FINALLY || + instr->i_opcode == SETUP_EXCEPT) { + target_depth = depth+3; + if (target_depth > maxdepth) + maxdepth = target_depth; + } + maxdepth = stackdepth_walk(c, instr->i_target, + target_depth, maxdepth); + if (instr->i_opcode == JUMP_ABSOLUTE || + instr->i_opcode == JUMP_FORWARD) { + goto out; /* remaining code is dead */ + } + } + } + if (b->b_next) + maxdepth = stackdepth_walk(c, b->b_next, depth, maxdepth); out: - b->b_seen = 0; - return maxdepth; + b->b_seen = 0; + return maxdepth; } /* Find the flow path that needs the largest stack. We assume that @@ -3584,49 +3584,49 @@ static int stackdepth(struct compiler *c) { - basicblock *b, *entryblock; - entryblock = NULL; - for (b = c->u->u_blocks; b != NULL; b = b->b_list) { - b->b_seen = 0; - b->b_startdepth = INT_MIN; - entryblock = b; - } - if (!entryblock) - return 0; - return stackdepth_walk(c, entryblock, 0, 0); + basicblock *b, *entryblock; + entryblock = NULL; + for (b = c->u->u_blocks; b != NULL; b = b->b_list) { + b->b_seen = 0; + b->b_startdepth = INT_MIN; + entryblock = b; + } + if (!entryblock) + return 0; + return stackdepth_walk(c, entryblock, 0, 0); } static int assemble_init(struct assembler *a, int nblocks, int firstlineno) { - memset(a, 0, sizeof(struct assembler)); - a->a_lineno = firstlineno; - a->a_bytecode = PyBytes_FromStringAndSize(NULL, DEFAULT_CODE_SIZE); - if (!a->a_bytecode) - return 0; - a->a_lnotab = PyBytes_FromStringAndSize(NULL, DEFAULT_LNOTAB_SIZE); - if (!a->a_lnotab) - return 0; - if (nblocks > PY_SIZE_MAX / sizeof(basicblock *)) { - PyErr_NoMemory(); - return 0; - } - a->a_postorder = (basicblock **)PyObject_Malloc( - sizeof(basicblock *) * nblocks); - if (!a->a_postorder) { - PyErr_NoMemory(); - return 0; - } - return 1; + memset(a, 0, sizeof(struct assembler)); + a->a_lineno = firstlineno; + a->a_bytecode = PyBytes_FromStringAndSize(NULL, DEFAULT_CODE_SIZE); + if (!a->a_bytecode) + return 0; + a->a_lnotab = PyBytes_FromStringAndSize(NULL, DEFAULT_LNOTAB_SIZE); + if (!a->a_lnotab) + return 0; + if (nblocks > PY_SIZE_MAX / sizeof(basicblock *)) { + PyErr_NoMemory(); + return 0; + } + a->a_postorder = (basicblock **)PyObject_Malloc( + sizeof(basicblock *) * nblocks); + if (!a->a_postorder) { + PyErr_NoMemory(); + return 0; + } + return 1; } static void assemble_free(struct assembler *a) { - Py_XDECREF(a->a_bytecode); - Py_XDECREF(a->a_lnotab); - if (a->a_postorder) - PyObject_Free(a->a_postorder); + Py_XDECREF(a->a_bytecode); + Py_XDECREF(a->a_lnotab); + if (a->a_postorder) + PyObject_Free(a->a_postorder); } /* Return the size of a basic block in bytes. */ @@ -3634,22 +3634,22 @@ static int instrsize(struct instr *instr) { - if (!instr->i_hasarg) - return 1; /* 1 byte for the opcode*/ - if (instr->i_oparg > 0xffff) - return 6; /* 1 (opcode) + 1 (EXTENDED_ARG opcode) + 2 (oparg) + 2(oparg extended) */ - return 3; /* 1 (opcode) + 2 (oparg) */ + if (!instr->i_hasarg) + return 1; /* 1 byte for the opcode*/ + if (instr->i_oparg > 0xffff) + return 6; /* 1 (opcode) + 1 (EXTENDED_ARG opcode) + 2 (oparg) + 2(oparg extended) */ + return 3; /* 1 (opcode) + 2 (oparg) */ } static int blocksize(basicblock *b) { - int i; - int size = 0; + int i; + int size = 0; - for (i = 0; i < b->b_iused; i++) - size += instrsize(&b->b_instr[i]); - return size; + for (i = 0; i < b->b_iused; i++) + size += instrsize(&b->b_instr[i]); + return size; } /* Appends a pair to the end of the line number table, a_lnotab, representing @@ -3659,94 +3659,94 @@ static int assemble_lnotab(struct assembler *a, struct instr *i) { - int d_bytecode, d_lineno; - int len; - unsigned char *lnotab; - - d_bytecode = a->a_offset - a->a_lineno_off; - d_lineno = i->i_lineno - a->a_lineno; - - assert(d_bytecode >= 0); - assert(d_lineno >= 0); - - if(d_bytecode == 0 && d_lineno == 0) - return 1; - - if (d_bytecode > 255) { - int j, nbytes, ncodes = d_bytecode / 255; - nbytes = a->a_lnotab_off + 2 * ncodes; - len = PyBytes_GET_SIZE(a->a_lnotab); - if (nbytes >= len) { - if ((len <= INT_MAX / 2) && (len * 2 < nbytes)) - len = nbytes; - else if (len <= INT_MAX / 2) - len *= 2; - else { - PyErr_NoMemory(); - return 0; - } - if (_PyBytes_Resize(&a->a_lnotab, len) < 0) - return 0; - } - lnotab = (unsigned char *) - PyBytes_AS_STRING(a->a_lnotab) + a->a_lnotab_off; - for (j = 0; j < ncodes; j++) { - *lnotab++ = 255; - *lnotab++ = 0; - } - d_bytecode -= ncodes * 255; - a->a_lnotab_off += ncodes * 2; - } - assert(d_bytecode <= 255); - if (d_lineno > 255) { - int j, nbytes, ncodes = d_lineno / 255; - nbytes = a->a_lnotab_off + 2 * ncodes; - len = PyBytes_GET_SIZE(a->a_lnotab); - if (nbytes >= len) { - if ((len <= INT_MAX / 2) && len * 2 < nbytes) - len = nbytes; - else if (len <= INT_MAX / 2) - len *= 2; - else { - PyErr_NoMemory(); - return 0; - } - if (_PyBytes_Resize(&a->a_lnotab, len) < 0) - return 0; - } - lnotab = (unsigned char *) - PyBytes_AS_STRING(a->a_lnotab) + a->a_lnotab_off; - *lnotab++ = d_bytecode; - *lnotab++ = 255; - d_bytecode = 0; - for (j = 1; j < ncodes; j++) { - *lnotab++ = 0; - *lnotab++ = 255; - } - d_lineno -= ncodes * 255; - a->a_lnotab_off += ncodes * 2; - } - - len = PyBytes_GET_SIZE(a->a_lnotab); - if (a->a_lnotab_off + 2 >= len) { - if (_PyBytes_Resize(&a->a_lnotab, len * 2) < 0) - return 0; - } - lnotab = (unsigned char *) - PyBytes_AS_STRING(a->a_lnotab) + a->a_lnotab_off; - - a->a_lnotab_off += 2; - if (d_bytecode) { - *lnotab++ = d_bytecode; - *lnotab++ = d_lineno; - } - else { /* First line of a block; def stmt, etc. */ - *lnotab++ = 0; - *lnotab++ = d_lineno; - } - a->a_lineno = i->i_lineno; - a->a_lineno_off = a->a_offset; - return 1; + int d_bytecode, d_lineno; + int len; + unsigned char *lnotab; + + d_bytecode = a->a_offset - a->a_lineno_off; + d_lineno = i->i_lineno - a->a_lineno; + + assert(d_bytecode >= 0); + assert(d_lineno >= 0); + + if(d_bytecode == 0 && d_lineno == 0) + return 1; + + if (d_bytecode > 255) { + int j, nbytes, ncodes = d_bytecode / 255; + nbytes = a->a_lnotab_off + 2 * ncodes; + len = PyBytes_GET_SIZE(a->a_lnotab); + if (nbytes >= len) { + if ((len <= INT_MAX / 2) && (len * 2 < nbytes)) + len = nbytes; + else if (len <= INT_MAX / 2) + len *= 2; + else { + PyErr_NoMemory(); + return 0; + } + if (_PyBytes_Resize(&a->a_lnotab, len) < 0) + return 0; + } + lnotab = (unsigned char *) + PyBytes_AS_STRING(a->a_lnotab) + a->a_lnotab_off; + for (j = 0; j < ncodes; j++) { + *lnotab++ = 255; + *lnotab++ = 0; + } + d_bytecode -= ncodes * 255; + a->a_lnotab_off += ncodes * 2; + } + assert(d_bytecode <= 255); + if (d_lineno > 255) { + int j, nbytes, ncodes = d_lineno / 255; + nbytes = a->a_lnotab_off + 2 * ncodes; + len = PyBytes_GET_SIZE(a->a_lnotab); + if (nbytes >= len) { + if ((len <= INT_MAX / 2) && len * 2 < nbytes) + len = nbytes; + else if (len <= INT_MAX / 2) + len *= 2; + else { + PyErr_NoMemory(); + return 0; + } + if (_PyBytes_Resize(&a->a_lnotab, len) < 0) + return 0; + } + lnotab = (unsigned char *) + PyBytes_AS_STRING(a->a_lnotab) + a->a_lnotab_off; + *lnotab++ = d_bytecode; + *lnotab++ = 255; + d_bytecode = 0; + for (j = 1; j < ncodes; j++) { + *lnotab++ = 0; + *lnotab++ = 255; + } + d_lineno -= ncodes * 255; + a->a_lnotab_off += ncodes * 2; + } + + len = PyBytes_GET_SIZE(a->a_lnotab); + if (a->a_lnotab_off + 2 >= len) { + if (_PyBytes_Resize(&a->a_lnotab, len * 2) < 0) + return 0; + } + lnotab = (unsigned char *) + PyBytes_AS_STRING(a->a_lnotab) + a->a_lnotab_off; + + a->a_lnotab_off += 2; + if (d_bytecode) { + *lnotab++ = d_bytecode; + *lnotab++ = d_lineno; + } + else { /* First line of a block; def stmt, etc. */ + *lnotab++ = 0; + *lnotab++ = d_lineno; + } + a->a_lineno = i->i_lineno; + a->a_lineno_off = a->a_offset; + return 1; } /* assemble_emit() @@ -3757,227 +3757,227 @@ static int assemble_emit(struct assembler *a, struct instr *i) { - int size, arg = 0, ext = 0; - Py_ssize_t len = PyBytes_GET_SIZE(a->a_bytecode); - char *code; - - size = instrsize(i); - if (i->i_hasarg) { - arg = i->i_oparg; - ext = arg >> 16; - } - if (i->i_lineno && !assemble_lnotab(a, i)) - return 0; - if (a->a_offset + size >= len) { - if (len > PY_SSIZE_T_MAX / 2) - return 0; - if (_PyBytes_Resize(&a->a_bytecode, len * 2) < 0) - return 0; - } - code = PyBytes_AS_STRING(a->a_bytecode) + a->a_offset; - a->a_offset += size; - if (size == 6) { - assert(i->i_hasarg); - *code++ = (char)EXTENDED_ARG; - *code++ = ext & 0xff; - *code++ = ext >> 8; - arg &= 0xffff; - } - *code++ = i->i_opcode; - if (i->i_hasarg) { - assert(size == 3 || size == 6); - *code++ = arg & 0xff; - *code++ = arg >> 8; - } - return 1; + int size, arg = 0, ext = 0; + Py_ssize_t len = PyBytes_GET_SIZE(a->a_bytecode); + char *code; + + size = instrsize(i); + if (i->i_hasarg) { + arg = i->i_oparg; + ext = arg >> 16; + } + if (i->i_lineno && !assemble_lnotab(a, i)) + return 0; + if (a->a_offset + size >= len) { + if (len > PY_SSIZE_T_MAX / 2) + return 0; + if (_PyBytes_Resize(&a->a_bytecode, len * 2) < 0) + return 0; + } + code = PyBytes_AS_STRING(a->a_bytecode) + a->a_offset; + a->a_offset += size; + if (size == 6) { + assert(i->i_hasarg); + *code++ = (char)EXTENDED_ARG; + *code++ = ext & 0xff; + *code++ = ext >> 8; + arg &= 0xffff; + } + *code++ = i->i_opcode; + if (i->i_hasarg) { + assert(size == 3 || size == 6); + *code++ = arg & 0xff; + *code++ = arg >> 8; + } + return 1; } static void assemble_jump_offsets(struct assembler *a, struct compiler *c) { - basicblock *b; - int bsize, totsize, extended_arg_count = 0, last_extended_arg_count; - int i; - - /* Compute the size of each block and fixup jump args. - Replace block pointer with position in bytecode. */ - do { - totsize = 0; - for (i = a->a_nblocks - 1; i >= 0; i--) { - b = a->a_postorder[i]; - bsize = blocksize(b); - b->b_offset = totsize; - totsize += bsize; - } - last_extended_arg_count = extended_arg_count; - extended_arg_count = 0; - for (b = c->u->u_blocks; b != NULL; b = b->b_list) { - bsize = b->b_offset; - for (i = 0; i < b->b_iused; i++) { - struct instr *instr = &b->b_instr[i]; - /* Relative jumps are computed relative to - the instruction pointer after fetching - the jump instruction. - */ - bsize += instrsize(instr); - if (instr->i_jabs) - instr->i_oparg = instr->i_target->b_offset; - else if (instr->i_jrel) { - int delta = instr->i_target->b_offset - bsize; - instr->i_oparg = delta; - } - else - continue; - if (instr->i_oparg > 0xffff) - extended_arg_count++; - } - } - - /* XXX: This is an awful hack that could hurt performance, but - on the bright side it should work until we come up - with a better solution. - - The issue is that in the first loop blocksize() is called - which calls instrsize() which requires i_oparg be set - appropriately. There is a bootstrap problem because - i_oparg is calculated in the second loop above. - - So we loop until we stop seeing new EXTENDED_ARGs. - The only EXTENDED_ARGs that could be popping up are - ones in jump instructions. So this should converge - fairly quickly. - */ - } while (last_extended_arg_count != extended_arg_count); + basicblock *b; + int bsize, totsize, extended_arg_count = 0, last_extended_arg_count; + int i; + + /* Compute the size of each block and fixup jump args. + Replace block pointer with position in bytecode. */ + do { + totsize = 0; + for (i = a->a_nblocks - 1; i >= 0; i--) { + b = a->a_postorder[i]; + bsize = blocksize(b); + b->b_offset = totsize; + totsize += bsize; + } + last_extended_arg_count = extended_arg_count; + extended_arg_count = 0; + for (b = c->u->u_blocks; b != NULL; b = b->b_list) { + bsize = b->b_offset; + for (i = 0; i < b->b_iused; i++) { + struct instr *instr = &b->b_instr[i]; + /* Relative jumps are computed relative to + the instruction pointer after fetching + the jump instruction. + */ + bsize += instrsize(instr); + if (instr->i_jabs) + instr->i_oparg = instr->i_target->b_offset; + else if (instr->i_jrel) { + int delta = instr->i_target->b_offset - bsize; + instr->i_oparg = delta; + } + else + continue; + if (instr->i_oparg > 0xffff) + extended_arg_count++; + } + } + + /* XXX: This is an awful hack that could hurt performance, but + on the bright side it should work until we come up + with a better solution. + + The issue is that in the first loop blocksize() is called + which calls instrsize() which requires i_oparg be set + appropriately. There is a bootstrap problem because + i_oparg is calculated in the second loop above. + + So we loop until we stop seeing new EXTENDED_ARGs. + The only EXTENDED_ARGs that could be popping up are + ones in jump instructions. So this should converge + fairly quickly. + */ + } while (last_extended_arg_count != extended_arg_count); } static PyObject * dict_keys_inorder(PyObject *dict, int offset) { - PyObject *tuple, *k, *v; - Py_ssize_t i, pos = 0, size = PyDict_Size(dict); + PyObject *tuple, *k, *v; + Py_ssize_t i, pos = 0, size = PyDict_Size(dict); - tuple = PyTuple_New(size); - if (tuple == NULL) - return NULL; - while (PyDict_Next(dict, &pos, &k, &v)) { - i = PyLong_AS_LONG(v); - /* The keys of the dictionary are tuples. (see compiler_add_o) - The object we want is always first, though. */ - k = PyTuple_GET_ITEM(k, 0); - Py_INCREF(k); - assert((i - offset) < size); - assert((i - offset) >= 0); - PyTuple_SET_ITEM(tuple, i - offset, k); - } - return tuple; + tuple = PyTuple_New(size); + if (tuple == NULL) + return NULL; + while (PyDict_Next(dict, &pos, &k, &v)) { + i = PyLong_AS_LONG(v); + /* The keys of the dictionary are tuples. (see compiler_add_o) + The object we want is always first, though. */ + k = PyTuple_GET_ITEM(k, 0); + Py_INCREF(k); + assert((i - offset) < size); + assert((i - offset) >= 0); + PyTuple_SET_ITEM(tuple, i - offset, k); + } + return tuple; } static int compute_code_flags(struct compiler *c) { - PySTEntryObject *ste = c->u->u_ste; - int flags = 0, n; - if (ste->ste_type != ModuleBlock) - flags |= CO_NEWLOCALS; - if (ste->ste_type == FunctionBlock) { - if (!ste->ste_unoptimized) - flags |= CO_OPTIMIZED; - if (ste->ste_nested) - flags |= CO_NESTED; - if (ste->ste_generator) - flags |= CO_GENERATOR; - if (ste->ste_varargs) - flags |= CO_VARARGS; - if (ste->ste_varkeywords) - flags |= CO_VARKEYWORDS; - } - - /* (Only) inherit compilerflags in PyCF_MASK */ - flags |= (c->c_flags->cf_flags & PyCF_MASK); - - n = PyDict_Size(c->u->u_freevars); - if (n < 0) - return -1; - if (n == 0) { - n = PyDict_Size(c->u->u_cellvars); - if (n < 0) - return -1; - if (n == 0) { - flags |= CO_NOFREE; - } - } + PySTEntryObject *ste = c->u->u_ste; + int flags = 0, n; + if (ste->ste_type != ModuleBlock) + flags |= CO_NEWLOCALS; + if (ste->ste_type == FunctionBlock) { + if (!ste->ste_unoptimized) + flags |= CO_OPTIMIZED; + if (ste->ste_nested) + flags |= CO_NESTED; + if (ste->ste_generator) + flags |= CO_GENERATOR; + if (ste->ste_varargs) + flags |= CO_VARARGS; + if (ste->ste_varkeywords) + flags |= CO_VARKEYWORDS; + } + + /* (Only) inherit compilerflags in PyCF_MASK */ + flags |= (c->c_flags->cf_flags & PyCF_MASK); + + n = PyDict_Size(c->u->u_freevars); + if (n < 0) + return -1; + if (n == 0) { + n = PyDict_Size(c->u->u_cellvars); + if (n < 0) + return -1; + if (n == 0) { + flags |= CO_NOFREE; + } + } - return flags; + return flags; } static PyCodeObject * makecode(struct compiler *c, struct assembler *a) { - PyObject *tmp; - PyCodeObject *co = NULL; - PyObject *consts = NULL; - PyObject *names = NULL; - PyObject *varnames = NULL; - PyObject *filename = NULL; - PyObject *name = NULL; - PyObject *freevars = NULL; - PyObject *cellvars = NULL; - PyObject *bytecode = NULL; - int nlocals, flags; - - tmp = dict_keys_inorder(c->u->u_consts, 0); - if (!tmp) - goto error; - consts = PySequence_List(tmp); /* optimize_code requires a list */ - Py_DECREF(tmp); - - names = dict_keys_inorder(c->u->u_names, 0); - varnames = dict_keys_inorder(c->u->u_varnames, 0); - if (!consts || !names || !varnames) - goto error; - - cellvars = dict_keys_inorder(c->u->u_cellvars, 0); - if (!cellvars) - goto error; - freevars = dict_keys_inorder(c->u->u_freevars, PyTuple_Size(cellvars)); - if (!freevars) - goto error; - filename = PyUnicode_DecodeFSDefault(c->c_filename); - if (!filename) - goto error; - - nlocals = PyDict_Size(c->u->u_varnames); - flags = compute_code_flags(c); - if (flags < 0) - goto error; - - bytecode = PyCode_Optimize(a->a_bytecode, consts, names, a->a_lnotab); - if (!bytecode) - goto error; - - tmp = PyList_AsTuple(consts); /* PyCode_New requires a tuple */ - if (!tmp) - goto error; - Py_DECREF(consts); - consts = tmp; - - co = PyCode_New(c->u->u_argcount, c->u->u_kwonlyargcount, - nlocals, stackdepth(c), flags, - bytecode, consts, names, varnames, - freevars, cellvars, - filename, c->u->u_name, - c->u->u_firstlineno, - a->a_lnotab); + PyObject *tmp; + PyCodeObject *co = NULL; + PyObject *consts = NULL; + PyObject *names = NULL; + PyObject *varnames = NULL; + PyObject *filename = NULL; + PyObject *name = NULL; + PyObject *freevars = NULL; + PyObject *cellvars = NULL; + PyObject *bytecode = NULL; + int nlocals, flags; + + tmp = dict_keys_inorder(c->u->u_consts, 0); + if (!tmp) + goto error; + consts = PySequence_List(tmp); /* optimize_code requires a list */ + Py_DECREF(tmp); + + names = dict_keys_inorder(c->u->u_names, 0); + varnames = dict_keys_inorder(c->u->u_varnames, 0); + if (!consts || !names || !varnames) + goto error; + + cellvars = dict_keys_inorder(c->u->u_cellvars, 0); + if (!cellvars) + goto error; + freevars = dict_keys_inorder(c->u->u_freevars, PyTuple_Size(cellvars)); + if (!freevars) + goto error; + filename = PyUnicode_DecodeFSDefault(c->c_filename); + if (!filename) + goto error; + + nlocals = PyDict_Size(c->u->u_varnames); + flags = compute_code_flags(c); + if (flags < 0) + goto error; + + bytecode = PyCode_Optimize(a->a_bytecode, consts, names, a->a_lnotab); + if (!bytecode) + goto error; + + tmp = PyList_AsTuple(consts); /* PyCode_New requires a tuple */ + if (!tmp) + goto error; + Py_DECREF(consts); + consts = tmp; + + co = PyCode_New(c->u->u_argcount, c->u->u_kwonlyargcount, + nlocals, stackdepth(c), flags, + bytecode, consts, names, varnames, + freevars, cellvars, + filename, c->u->u_name, + c->u->u_firstlineno, + a->a_lnotab); error: - Py_XDECREF(consts); - Py_XDECREF(names); - Py_XDECREF(varnames); - Py_XDECREF(filename); - Py_XDECREF(name); - Py_XDECREF(freevars); - Py_XDECREF(cellvars); - Py_XDECREF(bytecode); - return co; + Py_XDECREF(consts); + Py_XDECREF(names); + Py_XDECREF(varnames); + Py_XDECREF(filename); + Py_XDECREF(name); + Py_XDECREF(freevars); + Py_XDECREF(cellvars); + Py_XDECREF(bytecode); + return co; } @@ -3986,90 +3986,90 @@ static void dump_instr(const struct instr *i) { - const char *jrel = i->i_jrel ? "jrel " : ""; - const char *jabs = i->i_jabs ? "jabs " : ""; - char arg[128]; - - *arg = '\0'; - if (i->i_hasarg) - sprintf(arg, "arg: %d ", i->i_oparg); + const char *jrel = i->i_jrel ? "jrel " : ""; + const char *jabs = i->i_jabs ? "jabs " : ""; + char arg[128]; + + *arg = '\0'; + if (i->i_hasarg) + sprintf(arg, "arg: %d ", i->i_oparg); - fprintf(stderr, "line: %d, opcode: %d %s%s%s\n", - i->i_lineno, i->i_opcode, arg, jabs, jrel); + fprintf(stderr, "line: %d, opcode: %d %s%s%s\n", + i->i_lineno, i->i_opcode, arg, jabs, jrel); } static void dump_basicblock(const basicblock *b) { - const char *seen = b->b_seen ? "seen " : ""; - const char *b_return = b->b_return ? "return " : ""; - fprintf(stderr, "used: %d, depth: %d, offset: %d %s%s\n", - b->b_iused, b->b_startdepth, b->b_offset, seen, b_return); - if (b->b_instr) { - int i; - for (i = 0; i < b->b_iused; i++) { - fprintf(stderr, " [%02d] ", i); - dump_instr(b->b_instr + i); - } - } + const char *seen = b->b_seen ? "seen " : ""; + const char *b_return = b->b_return ? "return " : ""; + fprintf(stderr, "used: %d, depth: %d, offset: %d %s%s\n", + b->b_iused, b->b_startdepth, b->b_offset, seen, b_return); + if (b->b_instr) { + int i; + for (i = 0; i < b->b_iused; i++) { + fprintf(stderr, " [%02d] ", i); + dump_instr(b->b_instr + i); + } + } } #endif static PyCodeObject * assemble(struct compiler *c, int addNone) { - basicblock *b, *entryblock; - struct assembler a; - int i, j, nblocks; - PyCodeObject *co = NULL; - - /* Make sure every block that falls off the end returns None. - XXX NEXT_BLOCK() isn't quite right, because if the last - block ends with a jump or return b_next shouldn't set. - */ - if (!c->u->u_curblock->b_return) { - NEXT_BLOCK(c); - if (addNone) - ADDOP_O(c, LOAD_CONST, Py_None, consts); - ADDOP(c, RETURN_VALUE); - } - - nblocks = 0; - entryblock = NULL; - for (b = c->u->u_blocks; b != NULL; b = b->b_list) { - nblocks++; - entryblock = b; - } - - /* Set firstlineno if it wasn't explicitly set. */ - if (!c->u->u_firstlineno) { - if (entryblock && entryblock->b_instr) - c->u->u_firstlineno = entryblock->b_instr->i_lineno; - else - c->u->u_firstlineno = 1; - } - if (!assemble_init(&a, nblocks, c->u->u_firstlineno)) - goto error; - dfs(c, entryblock, &a); - - /* Can't modify the bytecode after computing jump offsets. */ - assemble_jump_offsets(&a, c); - - /* Emit code in reverse postorder from dfs. */ - for (i = a.a_nblocks - 1; i >= 0; i--) { - b = a.a_postorder[i]; - for (j = 0; j < b->b_iused; j++) - if (!assemble_emit(&a, &b->b_instr[j])) - goto error; - } - - if (_PyBytes_Resize(&a.a_lnotab, a.a_lnotab_off) < 0) - goto error; - if (_PyBytes_Resize(&a.a_bytecode, a.a_offset) < 0) - goto error; + basicblock *b, *entryblock; + struct assembler a; + int i, j, nblocks; + PyCodeObject *co = NULL; + + /* Make sure every block that falls off the end returns None. + XXX NEXT_BLOCK() isn't quite right, because if the last + block ends with a jump or return b_next shouldn't set. + */ + if (!c->u->u_curblock->b_return) { + NEXT_BLOCK(c); + if (addNone) + ADDOP_O(c, LOAD_CONST, Py_None, consts); + ADDOP(c, RETURN_VALUE); + } + + nblocks = 0; + entryblock = NULL; + for (b = c->u->u_blocks; b != NULL; b = b->b_list) { + nblocks++; + entryblock = b; + } + + /* Set firstlineno if it wasn't explicitly set. */ + if (!c->u->u_firstlineno) { + if (entryblock && entryblock->b_instr) + c->u->u_firstlineno = entryblock->b_instr->i_lineno; + else + c->u->u_firstlineno = 1; + } + if (!assemble_init(&a, nblocks, c->u->u_firstlineno)) + goto error; + dfs(c, entryblock, &a); + + /* Can't modify the bytecode after computing jump offsets. */ + assemble_jump_offsets(&a, c); + + /* Emit code in reverse postorder from dfs. */ + for (i = a.a_nblocks - 1; i >= 0; i--) { + b = a.a_postorder[i]; + for (j = 0; j < b->b_iused; j++) + if (!assemble_emit(&a, &b->b_instr[j])) + goto error; + } + + if (_PyBytes_Resize(&a.a_lnotab, a.a_lnotab_off) < 0) + goto error; + if (_PyBytes_Resize(&a.a_bytecode, a.a_offset) < 0) + goto error; - co = makecode(c, &a); + co = makecode(c, &a); error: - assemble_free(&a); - return co; + assemble_free(&a); + return co; } Modified: python/branches/py3k/Python/dynload_aix.c ============================================================================== --- python/branches/py3k/Python/dynload_aix.c (original) +++ python/branches/py3k/Python/dynload_aix.c Sun May 9 17:52:27 2010 @@ -4,10 +4,10 @@ #include "Python.h" #include "importdl.h" -#include /* for isdigit() */ -#include /* for global errno */ -#include /* for strerror() */ -#include /* for malloc(), free() */ +#include /* for isdigit() */ +#include /* for global errno */ +#include /* for strerror() */ +#include /* for malloc(), free() */ #include @@ -22,85 +22,85 @@ extern char *Py_GetProgramName(void); typedef struct Module { - struct Module *next; - void *entry; + struct Module *next; + void *entry; } Module, *ModulePtr; const struct filedescr _PyImport_DynLoadFiletab[] = { - {".so", "rb", C_EXTENSION}, - {"module.so", "rb", C_EXTENSION}, - {0, 0} + {".so", "rb", C_EXTENSION}, + {"module.so", "rb", C_EXTENSION}, + {0, 0} }; static int aix_getoldmodules(void **modlistptr) { - register ModulePtr modptr, prevmodptr; - register struct ld_info *ldiptr; - register char *ldibuf; - register int errflag, bufsize = 1024; - register unsigned int offset; - char *progname = Py_GetProgramName(); - - /* - -- Get the list of loaded modules into ld_info structures. - */ - if ((ldibuf = malloc(bufsize)) == NULL) { - PyErr_SetString(PyExc_ImportError, strerror(errno)); - return -1; - } - while ((errflag = loadquery(L_GETINFO, ldibuf, bufsize)) == -1 - && errno == ENOMEM) { - free(ldibuf); - bufsize += 1024; - if ((ldibuf = malloc(bufsize)) == NULL) { - PyErr_SetString(PyExc_ImportError, strerror(errno)); - return -1; - } - } - if (errflag == -1) { - PyErr_SetString(PyExc_ImportError, strerror(errno)); - return -1; - } - /* - -- Make the modules list from the ld_info structures. - */ - ldiptr = (struct ld_info *)ldibuf; - prevmodptr = NULL; - do { - if (strstr(progname, ldiptr->ldinfo_filename) == NULL && - strstr(ldiptr->ldinfo_filename, "python") == NULL) { - /* - -- Extract only the modules belonging to the main - -- executable + those containing "python" as a - -- substring (like the "python[version]" binary or - -- "libpython[version].a" in case it's a shared lib). - */ - offset = (unsigned int)ldiptr->ldinfo_next; - ldiptr = (struct ld_info *)((char*)ldiptr + offset); - continue; - } - if ((modptr = (ModulePtr)malloc(sizeof(Module))) == NULL) { - PyErr_SetString(PyExc_ImportError, strerror(errno)); - while (*modlistptr) { - modptr = (ModulePtr)*modlistptr; - *modlistptr = (void *)modptr->next; - free(modptr); - } - return -1; - } - modptr->entry = ldiptr->ldinfo_dataorg; - modptr->next = NULL; - if (prevmodptr == NULL) - *modlistptr = (void *)modptr; - else - prevmodptr->next = modptr; - prevmodptr = modptr; - offset = (unsigned int)ldiptr->ldinfo_next; - ldiptr = (struct ld_info *)((char*)ldiptr + offset); - } while (offset); - free(ldibuf); - return 0; + register ModulePtr modptr, prevmodptr; + register struct ld_info *ldiptr; + register char *ldibuf; + register int errflag, bufsize = 1024; + register unsigned int offset; + char *progname = Py_GetProgramName(); + + /* + -- Get the list of loaded modules into ld_info structures. + */ + if ((ldibuf = malloc(bufsize)) == NULL) { + PyErr_SetString(PyExc_ImportError, strerror(errno)); + return -1; + } + while ((errflag = loadquery(L_GETINFO, ldibuf, bufsize)) == -1 + && errno == ENOMEM) { + free(ldibuf); + bufsize += 1024; + if ((ldibuf = malloc(bufsize)) == NULL) { + PyErr_SetString(PyExc_ImportError, strerror(errno)); + return -1; + } + } + if (errflag == -1) { + PyErr_SetString(PyExc_ImportError, strerror(errno)); + return -1; + } + /* + -- Make the modules list from the ld_info structures. + */ + ldiptr = (struct ld_info *)ldibuf; + prevmodptr = NULL; + do { + if (strstr(progname, ldiptr->ldinfo_filename) == NULL && + strstr(ldiptr->ldinfo_filename, "python") == NULL) { + /* + -- Extract only the modules belonging to the main + -- executable + those containing "python" as a + -- substring (like the "python[version]" binary or + -- "libpython[version].a" in case it's a shared lib). + */ + offset = (unsigned int)ldiptr->ldinfo_next; + ldiptr = (struct ld_info *)((char*)ldiptr + offset); + continue; + } + if ((modptr = (ModulePtr)malloc(sizeof(Module))) == NULL) { + PyErr_SetString(PyExc_ImportError, strerror(errno)); + while (*modlistptr) { + modptr = (ModulePtr)*modlistptr; + *modlistptr = (void *)modptr->next; + free(modptr); + } + return -1; + } + modptr->entry = ldiptr->ldinfo_dataorg; + modptr->next = NULL; + if (prevmodptr == NULL) + *modlistptr = (void *)modptr; + else + prevmodptr->next = modptr; + prevmodptr = modptr; + offset = (unsigned int)ldiptr->ldinfo_next; + ldiptr = (struct ld_info *)((char*)ldiptr + offset); + } while (offset); + free(ldibuf); + return 0; } @@ -108,76 +108,76 @@ aix_loaderror(const char *pathname) { - char *message[1024], errbuf[1024]; - register int i,j; + char *message[1024], errbuf[1024]; + register int i,j; - struct errtab { - int errNo; - char *errstr; - } load_errtab[] = { - {L_ERROR_TOOMANY, "too many errors, rest skipped."}, - {L_ERROR_NOLIB, "can't load library:"}, - {L_ERROR_UNDEF, "can't find symbol in library:"}, - {L_ERROR_RLDBAD, - "RLD index out of range or bad relocation type:"}, - {L_ERROR_FORMAT, "not a valid, executable xcoff file:"}, - {L_ERROR_MEMBER, - "file not an archive or does not contain requested member:"}, - {L_ERROR_TYPE, "symbol table mismatch:"}, - {L_ERROR_ALIGN, "text alignment in file is wrong."}, - {L_ERROR_SYSTEM, "System error:"}, - {L_ERROR_ERRNO, NULL} - }; + struct errtab { + int errNo; + char *errstr; + } load_errtab[] = { + {L_ERROR_TOOMANY, "too many errors, rest skipped."}, + {L_ERROR_NOLIB, "can't load library:"}, + {L_ERROR_UNDEF, "can't find symbol in library:"}, + {L_ERROR_RLDBAD, + "RLD index out of range or bad relocation type:"}, + {L_ERROR_FORMAT, "not a valid, executable xcoff file:"}, + {L_ERROR_MEMBER, + "file not an archive or does not contain requested member:"}, + {L_ERROR_TYPE, "symbol table mismatch:"}, + {L_ERROR_ALIGN, "text alignment in file is wrong."}, + {L_ERROR_SYSTEM, "System error:"}, + {L_ERROR_ERRNO, NULL} + }; -#define LOAD_ERRTAB_LEN (sizeof(load_errtab)/sizeof(load_errtab[0])) +#define LOAD_ERRTAB_LEN (sizeof(load_errtab)/sizeof(load_errtab[0])) #define ERRBUF_APPEND(s) strncat(errbuf, s, sizeof(errbuf)-strlen(errbuf)-1) - PyOS_snprintf(errbuf, sizeof(errbuf), "from module %.200s ", pathname); + PyOS_snprintf(errbuf, sizeof(errbuf), "from module %.200s ", pathname); - if (!loadquery(L_GETMESSAGES, &message[0], sizeof(message))) { - ERRBUF_APPEND(strerror(errno)); - ERRBUF_APPEND("\n"); - } - for(i = 0; message[i] && *message[i]; i++) { - int nerr = atoi(message[i]); - for (j=0; j const struct filedescr _PyImport_DynLoadFiletab[] = { - {".so", "rb", C_EXTENSION}, - {"module.so", "rb", C_EXTENSION}, - {0, 0} + {".so", "rb", C_EXTENSION}, + {"module.so", "rb", C_EXTENSION}, + {0, 0} }; /* @@ -29,86 +29,86 @@ #define LINKOPTIONS NSLINKMODULE_OPTION_BINDNOW|NSLINKMODULE_OPTION_RETURN_ON_ERROR #else #define LINKOPTIONS NSLINKMODULE_OPTION_BINDNOW| \ - NSLINKMODULE_OPTION_RETURN_ON_ERROR|NSLINKMODULE_OPTION_PRIVATE + NSLINKMODULE_OPTION_RETURN_ON_ERROR|NSLINKMODULE_OPTION_PRIVATE #endif dl_funcptr _PyImport_GetDynLoadFunc(const char *fqname, const char *shortname, - const char *pathname, FILE *fp) + const char *pathname, FILE *fp) { - dl_funcptr p = NULL; - char funcname[258]; - NSObjectFileImageReturnCode rc; - NSObjectFileImage image; - NSModule newModule; - NSSymbol theSym; - const char *errString; - char errBuf[512]; + dl_funcptr p = NULL; + char funcname[258]; + NSObjectFileImageReturnCode rc; + NSObjectFileImage image; + NSModule newModule; + NSSymbol theSym; + const char *errString; + char errBuf[512]; - PyOS_snprintf(funcname, sizeof(funcname), "_PyInit_%.200s", shortname); + PyOS_snprintf(funcname, sizeof(funcname), "_PyInit_%.200s", shortname); #ifdef USE_DYLD_GLOBAL_NAMESPACE - if (NSIsSymbolNameDefined(funcname)) { - theSym = NSLookupAndBindSymbol(funcname); - p = (dl_funcptr)NSAddressOfSymbol(theSym); - return p; - } + if (NSIsSymbolNameDefined(funcname)) { + theSym = NSLookupAndBindSymbol(funcname); + p = (dl_funcptr)NSAddressOfSymbol(theSym); + return p; + } #endif - rc = NSCreateObjectFileImageFromFile(pathname, &image); - switch(rc) { - default: - case NSObjectFileImageFailure: - case NSObjectFileImageFormat: - /* for these a message is printed on stderr by dyld */ - errString = "Can't create object file image"; - break; - case NSObjectFileImageSuccess: - errString = NULL; - break; - case NSObjectFileImageInappropriateFile: - errString = "Inappropriate file type for dynamic loading"; - break; - case NSObjectFileImageArch: - errString = "Wrong CPU type in object file"; - break; - case NSObjectFileImageAccess: - errString = "Can't read object file (no access)"; - break; - } - if (errString == NULL) { - newModule = NSLinkModule(image, pathname, LINKOPTIONS); - if (newModule == NULL) { - int errNo; - const char *fileName, *moreErrorStr; - NSLinkEditErrors c; - NSLinkEditError( &c, &errNo, &fileName, &moreErrorStr ); - PyOS_snprintf(errBuf, 512, "Failure linking new module: %s: %s", - fileName, moreErrorStr); - errString = errBuf; - } - } - if (errString != NULL) { - PyErr_SetString(PyExc_ImportError, errString); - return NULL; - } + rc = NSCreateObjectFileImageFromFile(pathname, &image); + switch(rc) { + default: + case NSObjectFileImageFailure: + case NSObjectFileImageFormat: + /* for these a message is printed on stderr by dyld */ + errString = "Can't create object file image"; + break; + case NSObjectFileImageSuccess: + errString = NULL; + break; + case NSObjectFileImageInappropriateFile: + errString = "Inappropriate file type for dynamic loading"; + break; + case NSObjectFileImageArch: + errString = "Wrong CPU type in object file"; + break; + case NSObjectFileImageAccess: + errString = "Can't read object file (no access)"; + break; + } + if (errString == NULL) { + newModule = NSLinkModule(image, pathname, LINKOPTIONS); + if (newModule == NULL) { + int errNo; + const char *fileName, *moreErrorStr; + NSLinkEditErrors c; + NSLinkEditError( &c, &errNo, &fileName, &moreErrorStr ); + PyOS_snprintf(errBuf, 512, "Failure linking new module: %s: %s", + fileName, moreErrorStr); + errString = errBuf; + } + } + if (errString != NULL) { + PyErr_SetString(PyExc_ImportError, errString); + return NULL; + } #ifdef USE_DYLD_GLOBAL_NAMESPACE - if (!NSIsSymbolNameDefined(funcname)) { - /* UnlinkModule() isn't implemented in current versions, but calling it does no harm */ - /* NSUnLinkModule(newModule, FALSE); removed: causes problems for ObjC code */ - PyErr_Format(PyExc_ImportError, - "Loaded module does not contain symbol %.200s", - funcname); - return NULL; - } - theSym = NSLookupAndBindSymbol(funcname); + if (!NSIsSymbolNameDefined(funcname)) { + /* UnlinkModule() isn't implemented in current versions, but calling it does no harm */ + /* NSUnLinkModule(newModule, FALSE); removed: causes problems for ObjC code */ + PyErr_Format(PyExc_ImportError, + "Loaded module does not contain symbol %.200s", + funcname); + return NULL; + } + theSym = NSLookupAndBindSymbol(funcname); #else - theSym = NSLookupSymbolInModule(newModule, funcname); - if ( theSym == NULL ) { - /* NSUnLinkModule(newModule, FALSE); removed: causes problems for ObjC code */ - PyErr_Format(PyExc_ImportError, - "Loaded module does not contain symbol %.200s", - funcname); - return NULL; - } + theSym = NSLookupSymbolInModule(newModule, funcname); + if ( theSym == NULL ) { + /* NSUnLinkModule(newModule, FALSE); removed: causes problems for ObjC code */ + PyErr_Format(PyExc_ImportError, + "Loaded module does not contain symbol %.200s", + funcname); + return NULL; + } #endif - p = (dl_funcptr)NSAddressOfSymbol(theSym); - return p; + p = (dl_funcptr)NSAddressOfSymbol(theSym); + return p; } Modified: python/branches/py3k/Python/dynload_os2.c ============================================================================== --- python/branches/py3k/Python/dynload_os2.c (original) +++ python/branches/py3k/Python/dynload_os2.c Sun May 9 17:52:27 2010 @@ -10,37 +10,37 @@ const struct filedescr _PyImport_DynLoadFiletab[] = { - {".pyd", "rb", C_EXTENSION}, - {".dll", "rb", C_EXTENSION}, - {0, 0} + {".pyd", "rb", C_EXTENSION}, + {".dll", "rb", C_EXTENSION}, + {0, 0} }; dl_funcptr _PyImport_GetDynLoadFunc(const char *fqname, const char *shortname, - const char *pathname, FILE *fp) + const char *pathname, FILE *fp) { - dl_funcptr p; - APIRET rc; - HMODULE hDLL; - char failreason[256]; - char funcname[258]; - - rc = DosLoadModule(failreason, - sizeof(failreason), - pathname, - &hDLL); - - if (rc != NO_ERROR) { - char errBuf[256]; - PyOS_snprintf(errBuf, sizeof(errBuf), - "DLL load failed, rc = %d: %.200s", - rc, failreason); - PyErr_SetString(PyExc_ImportError, errBuf); - return NULL; - } - - PyOS_snprintf(funcname, sizeof(funcname), "PyInit_%.200s", shortname); - rc = DosQueryProcAddr(hDLL, 0L, funcname, &p); - if (rc != NO_ERROR) - p = NULL; /* Signify Failure to Acquire Entrypoint */ - return p; + dl_funcptr p; + APIRET rc; + HMODULE hDLL; + char failreason[256]; + char funcname[258]; + + rc = DosLoadModule(failreason, + sizeof(failreason), + pathname, + &hDLL); + + if (rc != NO_ERROR) { + char errBuf[256]; + PyOS_snprintf(errBuf, sizeof(errBuf), + "DLL load failed, rc = %d: %.200s", + rc, failreason); + PyErr_SetString(PyExc_ImportError, errBuf); + return NULL; + } + + PyOS_snprintf(funcname, sizeof(funcname), "PyInit_%.200s", shortname); + rc = DosQueryProcAddr(hDLL, 0L, funcname, &p); + if (rc != NO_ERROR) + p = NULL; /* Signify Failure to Acquire Entrypoint */ + return p; } Modified: python/branches/py3k/Python/dynload_shlib.c ============================================================================== --- python/branches/py3k/Python/dynload_shlib.c (original) +++ python/branches/py3k/Python/dynload_shlib.c Sun May 9 17:52:27 2010 @@ -33,111 +33,111 @@ const struct filedescr _PyImport_DynLoadFiletab[] = { #ifdef __CYGWIN__ - {".dll", "rb", C_EXTENSION}, - {"module.dll", "rb", C_EXTENSION}, + {".dll", "rb", C_EXTENSION}, + {"module.dll", "rb", C_EXTENSION}, #else #if defined(PYOS_OS2) && defined(PYCC_GCC) - {".pyd", "rb", C_EXTENSION}, - {".dll", "rb", C_EXTENSION}, + {".pyd", "rb", C_EXTENSION}, + {".dll", "rb", C_EXTENSION}, #else #ifdef __VMS - {".exe", "rb", C_EXTENSION}, - {".EXE", "rb", C_EXTENSION}, - {"module.exe", "rb", C_EXTENSION}, - {"MODULE.EXE", "rb", C_EXTENSION}, + {".exe", "rb", C_EXTENSION}, + {".EXE", "rb", C_EXTENSION}, + {"module.exe", "rb", C_EXTENSION}, + {"MODULE.EXE", "rb", C_EXTENSION}, #else - {".so", "rb", C_EXTENSION}, - {"module.so", "rb", C_EXTENSION}, + {".so", "rb", C_EXTENSION}, + {"module.so", "rb", C_EXTENSION}, #endif #endif #endif - {0, 0} + {0, 0} }; static struct { - dev_t dev; + dev_t dev; #ifdef __VMS - ino_t ino[3]; + ino_t ino[3]; #else - ino_t ino; + ino_t ino; #endif - void *handle; + void *handle; } handles[128]; static int nhandles = 0; dl_funcptr _PyImport_GetDynLoadFunc(const char *fqname, const char *shortname, - const char *pathname, FILE *fp) + const char *pathname, FILE *fp) { - dl_funcptr p; - void *handle; - char funcname[258]; - char pathbuf[260]; - int dlopenflags=0; - - if (strchr(pathname, '/') == NULL) { - /* Prefix bare filename with "./" */ - PyOS_snprintf(pathbuf, sizeof(pathbuf), "./%-.255s", pathname); - pathname = pathbuf; - } - - PyOS_snprintf(funcname, sizeof(funcname), - LEAD_UNDERSCORE "PyInit_%.200s", shortname); - - if (fp != NULL) { - int i; - struct stat statb; - fstat(fileno(fp), &statb); - for (i = 0; i < nhandles; i++) { - if (statb.st_dev == handles[i].dev && - statb.st_ino == handles[i].ino) { - p = (dl_funcptr) dlsym(handles[i].handle, - funcname); - return p; - } - } - if (nhandles < 128) { - handles[nhandles].dev = statb.st_dev; + dl_funcptr p; + void *handle; + char funcname[258]; + char pathbuf[260]; + int dlopenflags=0; + + if (strchr(pathname, '/') == NULL) { + /* Prefix bare filename with "./" */ + PyOS_snprintf(pathbuf, sizeof(pathbuf), "./%-.255s", pathname); + pathname = pathbuf; + } + + PyOS_snprintf(funcname, sizeof(funcname), + LEAD_UNDERSCORE "PyInit_%.200s", shortname); + + if (fp != NULL) { + int i; + struct stat statb; + fstat(fileno(fp), &statb); + for (i = 0; i < nhandles; i++) { + if (statb.st_dev == handles[i].dev && + statb.st_ino == handles[i].ino) { + p = (dl_funcptr) dlsym(handles[i].handle, + funcname); + return p; + } + } + if (nhandles < 128) { + handles[nhandles].dev = statb.st_dev; #ifdef __VMS - handles[nhandles].ino[0] = statb.st_ino[0]; - handles[nhandles].ino[1] = statb.st_ino[1]; - handles[nhandles].ino[2] = statb.st_ino[2]; + handles[nhandles].ino[0] = statb.st_ino[0]; + handles[nhandles].ino[1] = statb.st_ino[1]; + handles[nhandles].ino[2] = statb.st_ino[2]; #else - handles[nhandles].ino = statb.st_ino; + handles[nhandles].ino = statb.st_ino; #endif - } - } + } + } #if !(defined(PYOS_OS2) && defined(PYCC_GCC)) - dlopenflags = PyThreadState_GET()->interp->dlopenflags; + dlopenflags = PyThreadState_GET()->interp->dlopenflags; #endif - if (Py_VerboseFlag) - PySys_WriteStderr("dlopen(\"%s\", %x);\n", pathname, - dlopenflags); + if (Py_VerboseFlag) + PySys_WriteStderr("dlopen(\"%s\", %x);\n", pathname, + dlopenflags); #ifdef __VMS - /* VMS currently don't allow a pathname, use a logical name instead */ - /* Concatenate 'python_module_' and shortname */ - /* so "import vms.bar" will use the logical python_module_bar */ - /* As C module use only one name space this is probably not a */ - /* important limitation */ - PyOS_snprintf(pathbuf, sizeof(pathbuf), "python_module_%-.200s", - shortname); - pathname = pathbuf; -#endif - - handle = dlopen(pathname, dlopenflags); - - if (handle == NULL) { - const char *error = dlerror(); - if (error == NULL) - error = "unknown dlopen() error"; - PyErr_SetString(PyExc_ImportError, error); - return NULL; - } - if (fp != NULL && nhandles < 128) - handles[nhandles++].handle = handle; - p = (dl_funcptr) dlsym(handle, funcname); - return p; + /* VMS currently don't allow a pathname, use a logical name instead */ + /* Concatenate 'python_module_' and shortname */ + /* so "import vms.bar" will use the logical python_module_bar */ + /* As C module use only one name space this is probably not a */ + /* important limitation */ + PyOS_snprintf(pathbuf, sizeof(pathbuf), "python_module_%-.200s", + shortname); + pathname = pathbuf; +#endif + + handle = dlopen(pathname, dlopenflags); + + if (handle == NULL) { + const char *error = dlerror(); + if (error == NULL) + error = "unknown dlopen() error"; + PyErr_SetString(PyExc_ImportError, error); + return NULL; + } + if (fp != NULL && nhandles < 128) + handles[nhandles++].handle = handle; + p = (dl_funcptr) dlsym(handle, funcname); + return p; } Modified: python/branches/py3k/Python/dynload_win.c ============================================================================== --- python/branches/py3k/Python/dynload_win.c (original) +++ python/branches/py3k/Python/dynload_win.c Sun May 9 17:52:27 2010 @@ -17,11 +17,11 @@ const struct filedescr _PyImport_DynLoadFiletab[] = { #ifdef _DEBUG - {"_d.pyd", "rb", C_EXTENSION}, + {"_d.pyd", "rb", C_EXTENSION}, #else - {".pyd", "rb", C_EXTENSION}, + {".pyd", "rb", C_EXTENSION}, #endif - {0, 0} + {0, 0} }; @@ -29,18 +29,18 @@ C RTL implementations */ static int strcasecmp (char *string1, char *string2) -{ - int first, second; +{ + int first, second; - do { - first = tolower(*string1); - second = tolower(*string2); - string1++; - string2++; - } while (first && first == second); + do { + first = tolower(*string1); + second = tolower(*string2); + string1++; + string2++; + } while (first && first == second); - return (first - second); -} + return (first - second); +} /* Function to return the name of the "python" DLL that the supplied module @@ -66,213 +66,213 @@ static char *GetPythonImport (HINSTANCE hModule) { - unsigned char *dllbase, *import_data, *import_name; - DWORD pe_offset, opt_offset; - WORD opt_magic; - int num_dict_off, import_off; - - /* Safety check input */ - if (hModule == NULL) { - return NULL; - } - - /* Module instance is also the base load address. First portion of - memory is the MS-DOS loader, which holds the offset to the PE - header (from the load base) at 0x3C */ - dllbase = (unsigned char *)hModule; - pe_offset = DWORD_AT(dllbase + 0x3C); - - /* The PE signature must be "PE\0\0" */ - if (memcmp(dllbase+pe_offset,"PE\0\0",4)) { - return NULL; - } - - /* Following the PE signature is the standard COFF header (20 - bytes) and then the optional header. The optional header starts - with a magic value of 0x10B for PE32 or 0x20B for PE32+ (PE32+ - uses 64-bits for some fields). It might also be 0x107 for a ROM - image, but we don't process that here. - - The optional header ends with a data dictionary that directly - points to certain types of data, among them the import entries - (in the second table entry). Based on the header type, we - determine offsets for the data dictionary count and the entry - within the dictionary pointing to the imports. */ - - opt_offset = pe_offset + 4 + 20; - opt_magic = WORD_AT(dllbase+opt_offset); - if (opt_magic == 0x10B) { - /* PE32 */ - num_dict_off = 92; - import_off = 104; - } else if (opt_magic == 0x20B) { - /* PE32+ */ - num_dict_off = 108; - import_off = 120; - } else { - /* Unsupported */ - return NULL; - } - - /* Now if an import table exists, offset to it and walk the list of - imports. The import table is an array (ending when an entry has - empty values) of structures (20 bytes each), which contains (at - offset 12) a relative address (to the module base) at which a - string constant holding the import name is located. */ - - if (DWORD_AT(dllbase + opt_offset + num_dict_off) >= 2) { - /* We have at least 2 tables - the import table is the second - one. But still it may be that the table size is zero */ - if (0 == DWORD_AT(dllbase + opt_offset + import_off + sizeof(DWORD))) - return NULL; - import_data = dllbase + DWORD_AT(dllbase + - opt_offset + - import_off); - while (DWORD_AT(import_data)) { - import_name = dllbase + DWORD_AT(import_data+12); - if (strlen(import_name) >= 6 && - !strncmp(import_name,"python",6)) { - char *pch; - - /* Ensure python prefix is followed only - by numbers to the end of the basename */ - pch = import_name + 6; + unsigned char *dllbase, *import_data, *import_name; + DWORD pe_offset, opt_offset; + WORD opt_magic; + int num_dict_off, import_off; + + /* Safety check input */ + if (hModule == NULL) { + return NULL; + } + + /* Module instance is also the base load address. First portion of + memory is the MS-DOS loader, which holds the offset to the PE + header (from the load base) at 0x3C */ + dllbase = (unsigned char *)hModule; + pe_offset = DWORD_AT(dllbase + 0x3C); + + /* The PE signature must be "PE\0\0" */ + if (memcmp(dllbase+pe_offset,"PE\0\0",4)) { + return NULL; + } + + /* Following the PE signature is the standard COFF header (20 + bytes) and then the optional header. The optional header starts + with a magic value of 0x10B for PE32 or 0x20B for PE32+ (PE32+ + uses 64-bits for some fields). It might also be 0x107 for a ROM + image, but we don't process that here. + + The optional header ends with a data dictionary that directly + points to certain types of data, among them the import entries + (in the second table entry). Based on the header type, we + determine offsets for the data dictionary count and the entry + within the dictionary pointing to the imports. */ + + opt_offset = pe_offset + 4 + 20; + opt_magic = WORD_AT(dllbase+opt_offset); + if (opt_magic == 0x10B) { + /* PE32 */ + num_dict_off = 92; + import_off = 104; + } else if (opt_magic == 0x20B) { + /* PE32+ */ + num_dict_off = 108; + import_off = 120; + } else { + /* Unsupported */ + return NULL; + } + + /* Now if an import table exists, offset to it and walk the list of + imports. The import table is an array (ending when an entry has + empty values) of structures (20 bytes each), which contains (at + offset 12) a relative address (to the module base) at which a + string constant holding the import name is located. */ + + if (DWORD_AT(dllbase + opt_offset + num_dict_off) >= 2) { + /* We have at least 2 tables - the import table is the second + one. But still it may be that the table size is zero */ + if (0 == DWORD_AT(dllbase + opt_offset + import_off + sizeof(DWORD))) + return NULL; + import_data = dllbase + DWORD_AT(dllbase + + opt_offset + + import_off); + while (DWORD_AT(import_data)) { + import_name = dllbase + DWORD_AT(import_data+12); + if (strlen(import_name) >= 6 && + !strncmp(import_name,"python",6)) { + char *pch; + + /* Ensure python prefix is followed only + by numbers to the end of the basename */ + pch = import_name + 6; #ifdef _DEBUG - while (*pch && pch[0] != '_' && pch[1] != 'd' && pch[2] != '.') { + while (*pch && pch[0] != '_' && pch[1] != 'd' && pch[2] != '.') { #else - while (*pch && *pch != '.') { + while (*pch && *pch != '.') { #endif - if (*pch >= '0' && *pch <= '9') { - pch++; - } else { - pch = NULL; - break; - } - } - - if (pch) { - /* Found it - return the name */ - return import_name; - } - } - import_data += 20; - } - } + if (*pch >= '0' && *pch <= '9') { + pch++; + } else { + pch = NULL; + break; + } + } + + if (pch) { + /* Found it - return the name */ + return import_name; + } + } + import_data += 20; + } + } - return NULL; + return NULL; } dl_funcptr _PyImport_GetDynLoadFunc(const char *fqname, const char *shortname, - const char *pathname, FILE *fp) + const char *pathname, FILE *fp) { - dl_funcptr p; - char funcname[258], *import_python; + dl_funcptr p; + char funcname[258], *import_python; - PyOS_snprintf(funcname, sizeof(funcname), "PyInit_%.200s", shortname); + PyOS_snprintf(funcname, sizeof(funcname), "PyInit_%.200s", shortname); - { - HINSTANCE hDLL = NULL; - char pathbuf[260]; - LPTSTR dummy; - unsigned int old_mode; - ULONG_PTR cookie = 0; - /* We use LoadLibraryEx so Windows looks for dependent DLLs - in directory of pathname first. However, Windows95 - can sometimes not work correctly unless the absolute - path is used. If GetFullPathName() fails, the LoadLibrary - will certainly fail too, so use its error code */ - - /* Don't display a message box when Python can't load a DLL */ - old_mode = SetErrorMode(SEM_FAILCRITICALERRORS); - - if (GetFullPathName(pathname, - sizeof(pathbuf), - pathbuf, - &dummy)) { - ULONG_PTR cookie = _Py_ActivateActCtx(); - /* XXX This call doesn't exist in Windows CE */ - hDLL = LoadLibraryEx(pathname, NULL, - LOAD_WITH_ALTERED_SEARCH_PATH); - _Py_DeactivateActCtx(cookie); - } - - /* restore old error mode settings */ - SetErrorMode(old_mode); - - if (hDLL==NULL){ - PyObject *message; - unsigned int errorCode; - - /* Get an error string from Win32 error code */ - wchar_t theInfo[256]; /* Pointer to error text - from system */ - int theLength; /* Length of error text */ - - errorCode = GetLastError(); - - theLength = FormatMessageW( - FORMAT_MESSAGE_FROM_SYSTEM | - FORMAT_MESSAGE_IGNORE_INSERTS, /* flags */ - NULL, /* message source */ - errorCode, /* the message (error) ID */ - MAKELANGID(LANG_NEUTRAL, - SUBLANG_DEFAULT), - /* Default language */ - theInfo, /* the buffer */ - sizeof(theInfo), /* the buffer size */ - NULL); /* no additional format args. */ - - /* Problem: could not get the error message. - This should not happen if called correctly. */ - if (theLength == 0) { - message = PyUnicode_FromFormat( - "DLL load failed with error code %d", - errorCode); - } else { - /* For some reason a \r\n - is appended to the text */ - if (theLength >= 2 && - theInfo[theLength-2] == '\r' && - theInfo[theLength-1] == '\n') { - theLength -= 2; - theInfo[theLength] = '\0'; - } - message = PyUnicode_FromString( - "DLL load failed: "); - - PyUnicode_AppendAndDel(&message, - PyUnicode_FromUnicode( - theInfo, - theLength)); - } - PyErr_SetObject(PyExc_ImportError, message); - Py_XDECREF(message); - return NULL; - } else { - char buffer[256]; + { + HINSTANCE hDLL = NULL; + char pathbuf[260]; + LPTSTR dummy; + unsigned int old_mode; + ULONG_PTR cookie = 0; + /* We use LoadLibraryEx so Windows looks for dependent DLLs + in directory of pathname first. However, Windows95 + can sometimes not work correctly unless the absolute + path is used. If GetFullPathName() fails, the LoadLibrary + will certainly fail too, so use its error code */ + + /* Don't display a message box when Python can't load a DLL */ + old_mode = SetErrorMode(SEM_FAILCRITICALERRORS); + + if (GetFullPathName(pathname, + sizeof(pathbuf), + pathbuf, + &dummy)) { + ULONG_PTR cookie = _Py_ActivateActCtx(); + /* XXX This call doesn't exist in Windows CE */ + hDLL = LoadLibraryEx(pathname, NULL, + LOAD_WITH_ALTERED_SEARCH_PATH); + _Py_DeactivateActCtx(cookie); + } + + /* restore old error mode settings */ + SetErrorMode(old_mode); + + if (hDLL==NULL){ + PyObject *message; + unsigned int errorCode; + + /* Get an error string from Win32 error code */ + wchar_t theInfo[256]; /* Pointer to error text + from system */ + int theLength; /* Length of error text */ + + errorCode = GetLastError(); + + theLength = FormatMessageW( + FORMAT_MESSAGE_FROM_SYSTEM | + FORMAT_MESSAGE_IGNORE_INSERTS, /* flags */ + NULL, /* message source */ + errorCode, /* the message (error) ID */ + MAKELANGID(LANG_NEUTRAL, + SUBLANG_DEFAULT), + /* Default language */ + theInfo, /* the buffer */ + sizeof(theInfo), /* the buffer size */ + NULL); /* no additional format args. */ + + /* Problem: could not get the error message. + This should not happen if called correctly. */ + if (theLength == 0) { + message = PyUnicode_FromFormat( + "DLL load failed with error code %d", + errorCode); + } else { + /* For some reason a \r\n + is appended to the text */ + if (theLength >= 2 && + theInfo[theLength-2] == '\r' && + theInfo[theLength-1] == '\n') { + theLength -= 2; + theInfo[theLength] = '\0'; + } + message = PyUnicode_FromString( + "DLL load failed: "); + + PyUnicode_AppendAndDel(&message, + PyUnicode_FromUnicode( + theInfo, + theLength)); + } + PyErr_SetObject(PyExc_ImportError, message); + Py_XDECREF(message); + return NULL; + } else { + char buffer[256]; #ifdef _DEBUG - PyOS_snprintf(buffer, sizeof(buffer), "python%d%d_d.dll", + PyOS_snprintf(buffer, sizeof(buffer), "python%d%d_d.dll", #else - PyOS_snprintf(buffer, sizeof(buffer), "python%d%d.dll", + PyOS_snprintf(buffer, sizeof(buffer), "python%d%d.dll", #endif - PY_MAJOR_VERSION,PY_MINOR_VERSION); - import_python = GetPythonImport(hDLL); + PY_MAJOR_VERSION,PY_MINOR_VERSION); + import_python = GetPythonImport(hDLL); - if (import_python && - strcasecmp(buffer,import_python)) { - PyOS_snprintf(buffer, sizeof(buffer), - "Module use of %.150s conflicts " - "with this version of Python.", - import_python); - PyErr_SetString(PyExc_ImportError,buffer); - FreeLibrary(hDLL); - return NULL; - } - } - p = GetProcAddress(hDLL, funcname); - } + if (import_python && + strcasecmp(buffer,import_python)) { + PyOS_snprintf(buffer, sizeof(buffer), + "Module use of %.150s conflicts " + "with this version of Python.", + import_python); + PyErr_SetString(PyExc_ImportError,buffer); + FreeLibrary(hDLL); + return NULL; + } + } + p = GetProcAddress(hDLL, funcname); + } - return p; + return p; } Modified: python/branches/py3k/Python/errors.c ============================================================================== --- python/branches/py3k/Python/errors.c (original) +++ python/branches/py3k/Python/errors.c Sun May 9 17:52:27 2010 @@ -24,166 +24,166 @@ void PyErr_Restore(PyObject *type, PyObject *value, PyObject *traceback) { - PyThreadState *tstate = PyThreadState_GET(); - PyObject *oldtype, *oldvalue, *oldtraceback; + PyThreadState *tstate = PyThreadState_GET(); + PyObject *oldtype, *oldvalue, *oldtraceback; - if (traceback != NULL && !PyTraceBack_Check(traceback)) { - /* XXX Should never happen -- fatal error instead? */ - /* Well, it could be None. */ - Py_DECREF(traceback); - traceback = NULL; - } - - /* Save these in locals to safeguard against recursive - invocation through Py_XDECREF */ - oldtype = tstate->curexc_type; - oldvalue = tstate->curexc_value; - oldtraceback = tstate->curexc_traceback; - - tstate->curexc_type = type; - tstate->curexc_value = value; - tstate->curexc_traceback = traceback; - - Py_XDECREF(oldtype); - Py_XDECREF(oldvalue); - Py_XDECREF(oldtraceback); + if (traceback != NULL && !PyTraceBack_Check(traceback)) { + /* XXX Should never happen -- fatal error instead? */ + /* Well, it could be None. */ + Py_DECREF(traceback); + traceback = NULL; + } + + /* Save these in locals to safeguard against recursive + invocation through Py_XDECREF */ + oldtype = tstate->curexc_type; + oldvalue = tstate->curexc_value; + oldtraceback = tstate->curexc_traceback; + + tstate->curexc_type = type; + tstate->curexc_value = value; + tstate->curexc_traceback = traceback; + + Py_XDECREF(oldtype); + Py_XDECREF(oldvalue); + Py_XDECREF(oldtraceback); } void PyErr_SetObject(PyObject *exception, PyObject *value) { - PyThreadState *tstate = PyThreadState_GET(); - PyObject *exc_value; - PyObject *tb = NULL; - - if (exception != NULL && - !PyExceptionClass_Check(exception)) { - PyErr_Format(PyExc_SystemError, - "exception %R not a BaseException subclass", - exception); - return; - } - Py_XINCREF(value); - exc_value = tstate->exc_value; - if (exc_value != NULL && exc_value != Py_None) { - /* Implicit exception chaining */ - Py_INCREF(exc_value); - if (value == NULL || !PyExceptionInstance_Check(value)) { - /* We must normalize the value right now */ - PyObject *args, *fixed_value; - if (value == NULL || value == Py_None) - args = PyTuple_New(0); - else if (PyTuple_Check(value)) { - Py_INCREF(value); - args = value; - } - else - args = PyTuple_Pack(1, value); - fixed_value = args ? - PyEval_CallObject(exception, args) : NULL; - Py_XDECREF(args); - Py_XDECREF(value); - if (fixed_value == NULL) - return; - value = fixed_value; - } - /* Avoid reference cycles through the context chain. - This is O(chain length) but context chains are - usually very short. Sensitive readers may try - to inline the call to PyException_GetContext. */ - if (exc_value != value) { - PyObject *o = exc_value, *context; - while ((context = PyException_GetContext(o))) { - Py_DECREF(context); - if (context == value) { - PyException_SetContext(o, NULL); - break; - } - o = context; - } - PyException_SetContext(value, exc_value); - } else { - Py_DECREF(exc_value); - } - } - if (value != NULL && PyExceptionInstance_Check(value)) - tb = PyException_GetTraceback(value); - Py_XINCREF(exception); - PyErr_Restore(exception, value, tb); + PyThreadState *tstate = PyThreadState_GET(); + PyObject *exc_value; + PyObject *tb = NULL; + + if (exception != NULL && + !PyExceptionClass_Check(exception)) { + PyErr_Format(PyExc_SystemError, + "exception %R not a BaseException subclass", + exception); + return; + } + Py_XINCREF(value); + exc_value = tstate->exc_value; + if (exc_value != NULL && exc_value != Py_None) { + /* Implicit exception chaining */ + Py_INCREF(exc_value); + if (value == NULL || !PyExceptionInstance_Check(value)) { + /* We must normalize the value right now */ + PyObject *args, *fixed_value; + if (value == NULL || value == Py_None) + args = PyTuple_New(0); + else if (PyTuple_Check(value)) { + Py_INCREF(value); + args = value; + } + else + args = PyTuple_Pack(1, value); + fixed_value = args ? + PyEval_CallObject(exception, args) : NULL; + Py_XDECREF(args); + Py_XDECREF(value); + if (fixed_value == NULL) + return; + value = fixed_value; + } + /* Avoid reference cycles through the context chain. + This is O(chain length) but context chains are + usually very short. Sensitive readers may try + to inline the call to PyException_GetContext. */ + if (exc_value != value) { + PyObject *o = exc_value, *context; + while ((context = PyException_GetContext(o))) { + Py_DECREF(context); + if (context == value) { + PyException_SetContext(o, NULL); + break; + } + o = context; + } + PyException_SetContext(value, exc_value); + } else { + Py_DECREF(exc_value); + } + } + if (value != NULL && PyExceptionInstance_Check(value)) + tb = PyException_GetTraceback(value); + Py_XINCREF(exception); + PyErr_Restore(exception, value, tb); } void PyErr_SetNone(PyObject *exception) { - PyErr_SetObject(exception, (PyObject *)NULL); + PyErr_SetObject(exception, (PyObject *)NULL); } void PyErr_SetString(PyObject *exception, const char *string) { - PyObject *value = PyUnicode_FromString(string); - PyErr_SetObject(exception, value); - Py_XDECREF(value); + PyObject *value = PyUnicode_FromString(string); + PyErr_SetObject(exception, value); + Py_XDECREF(value); } PyObject * PyErr_Occurred(void) { - PyThreadState *tstate = PyThreadState_GET(); + PyThreadState *tstate = PyThreadState_GET(); - return tstate->curexc_type; + return tstate->curexc_type; } int PyErr_GivenExceptionMatches(PyObject *err, PyObject *exc) { - if (err == NULL || exc == NULL) { - /* maybe caused by "import exceptions" that failed early on */ - return 0; - } - if (PyTuple_Check(exc)) { - Py_ssize_t i, n; - n = PyTuple_Size(exc); - for (i = 0; i < n; i++) { - /* Test recursively */ - if (PyErr_GivenExceptionMatches( - err, PyTuple_GET_ITEM(exc, i))) - { - return 1; - } - } - return 0; - } - /* err might be an instance, so check its class. */ - if (PyExceptionInstance_Check(err)) - err = PyExceptionInstance_Class(err); - - if (PyExceptionClass_Check(err) && PyExceptionClass_Check(exc)) { - int res = 0; - PyObject *exception, *value, *tb; - PyErr_Fetch(&exception, &value, &tb); - /* PyObject_IsSubclass() can recurse and therefore is - not safe (see test_bad_getattr in test.pickletester). */ - res = PyType_IsSubtype((PyTypeObject *)err, (PyTypeObject *)exc); - /* This function must not fail, so print the error here */ - if (res == -1) { - PyErr_WriteUnraisable(err); - res = 0; - } - PyErr_Restore(exception, value, tb); - return res; - } + if (err == NULL || exc == NULL) { + /* maybe caused by "import exceptions" that failed early on */ + return 0; + } + if (PyTuple_Check(exc)) { + Py_ssize_t i, n; + n = PyTuple_Size(exc); + for (i = 0; i < n; i++) { + /* Test recursively */ + if (PyErr_GivenExceptionMatches( + err, PyTuple_GET_ITEM(exc, i))) + { + return 1; + } + } + return 0; + } + /* err might be an instance, so check its class. */ + if (PyExceptionInstance_Check(err)) + err = PyExceptionInstance_Class(err); + + if (PyExceptionClass_Check(err) && PyExceptionClass_Check(exc)) { + int res = 0; + PyObject *exception, *value, *tb; + PyErr_Fetch(&exception, &value, &tb); + /* PyObject_IsSubclass() can recurse and therefore is + not safe (see test_bad_getattr in test.pickletester). */ + res = PyType_IsSubtype((PyTypeObject *)err, (PyTypeObject *)exc); + /* This function must not fail, so print the error here */ + if (res == -1) { + PyErr_WriteUnraisable(err); + res = 0; + } + PyErr_Restore(exception, value, tb); + return res; + } - return err == exc; + return err == exc; } int PyErr_ExceptionMatches(PyObject *exc) { - return PyErr_GivenExceptionMatches(PyErr_Occurred(), exc); + return PyErr_GivenExceptionMatches(PyErr_Occurred(), exc); } @@ -191,128 +191,128 @@ eval_code2(), do_raise(), and PyErr_Print() XXX: should PyErr_NormalizeException() also call - PyException_SetTraceback() with the resulting value and tb? + PyException_SetTraceback() with the resulting value and tb? */ void PyErr_NormalizeException(PyObject **exc, PyObject **val, PyObject **tb) { - PyObject *type = *exc; - PyObject *value = *val; - PyObject *inclass = NULL; - PyObject *initial_tb = NULL; - PyThreadState *tstate = NULL; - - if (type == NULL) { - /* There was no exception, so nothing to do. */ - return; - } - - /* If PyErr_SetNone() was used, the value will have been actually - set to NULL. - */ - if (!value) { - value = Py_None; - Py_INCREF(value); - } - - if (PyExceptionInstance_Check(value)) - inclass = PyExceptionInstance_Class(value); - - /* Normalize the exception so that if the type is a class, the - value will be an instance. - */ - if (PyExceptionClass_Check(type)) { - /* if the value was not an instance, or is not an instance - whose class is (or is derived from) type, then use the - value as an argument to instantiation of the type - class. - */ - if (!inclass || !PyObject_IsSubclass(inclass, type)) { - PyObject *args, *res; - - if (value == Py_None) - args = PyTuple_New(0); - else if (PyTuple_Check(value)) { - Py_INCREF(value); - args = value; - } - else - args = PyTuple_Pack(1, value); - - if (args == NULL) - goto finally; - res = PyEval_CallObject(type, args); - Py_DECREF(args); - if (res == NULL) - goto finally; - Py_DECREF(value); - value = res; - } - /* if the class of the instance doesn't exactly match the - class of the type, believe the instance - */ - else if (inclass != type) { - Py_DECREF(type); - type = inclass; - Py_INCREF(type); - } - } - *exc = type; - *val = value; - return; + PyObject *type = *exc; + PyObject *value = *val; + PyObject *inclass = NULL; + PyObject *initial_tb = NULL; + PyThreadState *tstate = NULL; + + if (type == NULL) { + /* There was no exception, so nothing to do. */ + return; + } + + /* If PyErr_SetNone() was used, the value will have been actually + set to NULL. + */ + if (!value) { + value = Py_None; + Py_INCREF(value); + } + + if (PyExceptionInstance_Check(value)) + inclass = PyExceptionInstance_Class(value); + + /* Normalize the exception so that if the type is a class, the + value will be an instance. + */ + if (PyExceptionClass_Check(type)) { + /* if the value was not an instance, or is not an instance + whose class is (or is derived from) type, then use the + value as an argument to instantiation of the type + class. + */ + if (!inclass || !PyObject_IsSubclass(inclass, type)) { + PyObject *args, *res; + + if (value == Py_None) + args = PyTuple_New(0); + else if (PyTuple_Check(value)) { + Py_INCREF(value); + args = value; + } + else + args = PyTuple_Pack(1, value); + + if (args == NULL) + goto finally; + res = PyEval_CallObject(type, args); + Py_DECREF(args); + if (res == NULL) + goto finally; + Py_DECREF(value); + value = res; + } + /* if the class of the instance doesn't exactly match the + class of the type, believe the instance + */ + else if (inclass != type) { + Py_DECREF(type); + type = inclass; + Py_INCREF(type); + } + } + *exc = type; + *val = value; + return; finally: - Py_DECREF(type); - Py_DECREF(value); - /* If the new exception doesn't set a traceback and the old - exception had a traceback, use the old traceback for the - new exception. It's better than nothing. - */ - initial_tb = *tb; - PyErr_Fetch(exc, val, tb); - if (initial_tb != NULL) { - if (*tb == NULL) - *tb = initial_tb; - else - Py_DECREF(initial_tb); - } - /* normalize recursively */ - tstate = PyThreadState_GET(); - if (++tstate->recursion_depth > Py_GetRecursionLimit()) { - --tstate->recursion_depth; - /* throw away the old exception... */ - Py_DECREF(*exc); - Py_DECREF(*val); - /* ... and use the recursion error instead */ - *exc = PyExc_RuntimeError; - *val = PyExc_RecursionErrorInst; - Py_INCREF(*exc); - Py_INCREF(*val); - /* just keeping the old traceback */ - return; - } - PyErr_NormalizeException(exc, val, tb); - --tstate->recursion_depth; + Py_DECREF(type); + Py_DECREF(value); + /* If the new exception doesn't set a traceback and the old + exception had a traceback, use the old traceback for the + new exception. It's better than nothing. + */ + initial_tb = *tb; + PyErr_Fetch(exc, val, tb); + if (initial_tb != NULL) { + if (*tb == NULL) + *tb = initial_tb; + else + Py_DECREF(initial_tb); + } + /* normalize recursively */ + tstate = PyThreadState_GET(); + if (++tstate->recursion_depth > Py_GetRecursionLimit()) { + --tstate->recursion_depth; + /* throw away the old exception... */ + Py_DECREF(*exc); + Py_DECREF(*val); + /* ... and use the recursion error instead */ + *exc = PyExc_RuntimeError; + *val = PyExc_RecursionErrorInst; + Py_INCREF(*exc); + Py_INCREF(*val); + /* just keeping the old traceback */ + return; + } + PyErr_NormalizeException(exc, val, tb); + --tstate->recursion_depth; } void PyErr_Fetch(PyObject **p_type, PyObject **p_value, PyObject **p_traceback) { - PyThreadState *tstate = PyThreadState_GET(); + PyThreadState *tstate = PyThreadState_GET(); - *p_type = tstate->curexc_type; - *p_value = tstate->curexc_value; - *p_traceback = tstate->curexc_traceback; - - tstate->curexc_type = NULL; - tstate->curexc_value = NULL; - tstate->curexc_traceback = NULL; + *p_type = tstate->curexc_type; + *p_value = tstate->curexc_value; + *p_traceback = tstate->curexc_traceback; + + tstate->curexc_type = NULL; + tstate->curexc_value = NULL; + tstate->curexc_traceback = NULL; } void PyErr_Clear(void) { - PyErr_Restore(NULL, NULL, NULL); + PyErr_Restore(NULL, NULL, NULL); } /* Convenience functions to set a type error exception and return 0 */ @@ -320,284 +320,284 @@ int PyErr_BadArgument(void) { - PyErr_SetString(PyExc_TypeError, - "bad argument type for built-in operation"); - return 0; + PyErr_SetString(PyExc_TypeError, + "bad argument type for built-in operation"); + return 0; } PyObject * PyErr_NoMemory(void) { - if (PyErr_ExceptionMatches(PyExc_MemoryError)) - /* already current */ - return NULL; - - /* raise the pre-allocated instance if it still exists */ - if (PyExc_MemoryErrorInst) - { - /* Clear the previous traceback, otherwise it will be appended - * to the current one. - * - * The following statement is not likely to raise any error; - * if it does, we simply discard it. - */ - PyException_SetTraceback(PyExc_MemoryErrorInst, Py_None); - - PyErr_SetObject(PyExc_MemoryError, PyExc_MemoryErrorInst); - } - else - /* this will probably fail since there's no memory and hee, - hee, we have to instantiate this class - */ - PyErr_SetNone(PyExc_MemoryError); + if (PyErr_ExceptionMatches(PyExc_MemoryError)) + /* already current */ + return NULL; + + /* raise the pre-allocated instance if it still exists */ + if (PyExc_MemoryErrorInst) + { + /* Clear the previous traceback, otherwise it will be appended + * to the current one. + * + * The following statement is not likely to raise any error; + * if it does, we simply discard it. + */ + PyException_SetTraceback(PyExc_MemoryErrorInst, Py_None); + + PyErr_SetObject(PyExc_MemoryError, PyExc_MemoryErrorInst); + } + else + /* this will probably fail since there's no memory and hee, + hee, we have to instantiate this class + */ + PyErr_SetNone(PyExc_MemoryError); - return NULL; + return NULL; } PyObject * PyErr_SetFromErrnoWithFilenameObject(PyObject *exc, PyObject *filenameObject) { - PyObject *message; - PyObject *v; - int i = errno; + PyObject *message; + PyObject *v; + int i = errno; #ifndef MS_WINDOWS - char *s; + char *s; #else - WCHAR *s_buf = NULL; + WCHAR *s_buf = NULL; #endif /* Unix/Windows */ #ifdef EINTR - if (i == EINTR && PyErr_CheckSignals()) - return NULL; + if (i == EINTR && PyErr_CheckSignals()) + return NULL; #endif #ifndef MS_WINDOWS - if (i == 0) - s = "Error"; /* Sometimes errno didn't get set */ - else - s = strerror(i); - message = PyUnicode_DecodeUTF8(s, strlen(s), "ignore"); + if (i == 0) + s = "Error"; /* Sometimes errno didn't get set */ + else + s = strerror(i); + message = PyUnicode_DecodeUTF8(s, strlen(s), "ignore"); #else - if (i == 0) - message = PyUnicode_FromString("Error"); /* Sometimes errno didn't get set */ - else - { - /* Note that the Win32 errors do not lineup with the - errno error. So if the error is in the MSVC error - table, we use it, otherwise we assume it really _is_ - a Win32 error code - */ - if (i > 0 && i < _sys_nerr) { - message = PyUnicode_FromString(_sys_errlist[i]); - } - else { - int len = FormatMessageW( - FORMAT_MESSAGE_ALLOCATE_BUFFER | - FORMAT_MESSAGE_FROM_SYSTEM | - FORMAT_MESSAGE_IGNORE_INSERTS, - NULL, /* no message source */ - i, - MAKELANGID(LANG_NEUTRAL, - SUBLANG_DEFAULT), - /* Default language */ - (LPWSTR) &s_buf, - 0, /* size not used */ - NULL); /* no args */ - if (len==0) { - /* Only ever seen this in out-of-mem - situations */ - s_buf = NULL; - message = PyUnicode_FromFormat("Windows Error 0x%X", i); - } else { - /* remove trailing cr/lf and dots */ - while (len > 0 && (s_buf[len-1] <= L' ' || s_buf[len-1] == L'.')) - s_buf[--len] = L'\0'; - message = PyUnicode_FromUnicode(s_buf, len); - } - } - } + if (i == 0) + message = PyUnicode_FromString("Error"); /* Sometimes errno didn't get set */ + else + { + /* Note that the Win32 errors do not lineup with the + errno error. So if the error is in the MSVC error + table, we use it, otherwise we assume it really _is_ + a Win32 error code + */ + if (i > 0 && i < _sys_nerr) { + message = PyUnicode_FromString(_sys_errlist[i]); + } + else { + int len = FormatMessageW( + FORMAT_MESSAGE_ALLOCATE_BUFFER | + FORMAT_MESSAGE_FROM_SYSTEM | + FORMAT_MESSAGE_IGNORE_INSERTS, + NULL, /* no message source */ + i, + MAKELANGID(LANG_NEUTRAL, + SUBLANG_DEFAULT), + /* Default language */ + (LPWSTR) &s_buf, + 0, /* size not used */ + NULL); /* no args */ + if (len==0) { + /* Only ever seen this in out-of-mem + situations */ + s_buf = NULL; + message = PyUnicode_FromFormat("Windows Error 0x%X", i); + } else { + /* remove trailing cr/lf and dots */ + while (len > 0 && (s_buf[len-1] <= L' ' || s_buf[len-1] == L'.')) + s_buf[--len] = L'\0'; + message = PyUnicode_FromUnicode(s_buf, len); + } + } + } #endif /* Unix/Windows */ - if (message == NULL) - { + if (message == NULL) + { #ifdef MS_WINDOWS - LocalFree(s_buf); + LocalFree(s_buf); #endif - return NULL; - } + return NULL; + } - if (filenameObject != NULL) - v = Py_BuildValue("(iOO)", i, message, filenameObject); - else - v = Py_BuildValue("(iO)", i, message); - Py_DECREF(message); - - if (v != NULL) { - PyErr_SetObject(exc, v); - Py_DECREF(v); - } + if (filenameObject != NULL) + v = Py_BuildValue("(iOO)", i, message, filenameObject); + else + v = Py_BuildValue("(iO)", i, message); + Py_DECREF(message); + + if (v != NULL) { + PyErr_SetObject(exc, v); + Py_DECREF(v); + } #ifdef MS_WINDOWS - LocalFree(s_buf); + LocalFree(s_buf); #endif - return NULL; + return NULL; } PyObject * PyErr_SetFromErrnoWithFilename(PyObject *exc, const char *filename) { - PyObject *name = filename ? PyUnicode_DecodeFSDefault(filename) : NULL; - PyObject *result = PyErr_SetFromErrnoWithFilenameObject(exc, name); - Py_XDECREF(name); - return result; + PyObject *name = filename ? PyUnicode_DecodeFSDefault(filename) : NULL; + PyObject *result = PyErr_SetFromErrnoWithFilenameObject(exc, name); + Py_XDECREF(name); + return result; } #ifdef MS_WINDOWS PyObject * PyErr_SetFromErrnoWithUnicodeFilename(PyObject *exc, const Py_UNICODE *filename) { - PyObject *name = filename ? - PyUnicode_FromUnicode(filename, wcslen(filename)) : - NULL; - PyObject *result = PyErr_SetFromErrnoWithFilenameObject(exc, name); - Py_XDECREF(name); - return result; + PyObject *name = filename ? + PyUnicode_FromUnicode(filename, wcslen(filename)) : + NULL; + PyObject *result = PyErr_SetFromErrnoWithFilenameObject(exc, name); + Py_XDECREF(name); + return result; } #endif /* MS_WINDOWS */ PyObject * PyErr_SetFromErrno(PyObject *exc) { - return PyErr_SetFromErrnoWithFilenameObject(exc, NULL); + return PyErr_SetFromErrnoWithFilenameObject(exc, NULL); } #ifdef MS_WINDOWS /* Windows specific error code handling */ PyObject *PyErr_SetExcFromWindowsErrWithFilenameObject( - PyObject *exc, - int ierr, - PyObject *filenameObject) -{ - int len; - WCHAR *s_buf = NULL; /* Free via LocalFree */ - PyObject *message; - PyObject *v; - DWORD err = (DWORD)ierr; - if (err==0) err = GetLastError(); - len = FormatMessageW( - /* Error API error */ - FORMAT_MESSAGE_ALLOCATE_BUFFER | - FORMAT_MESSAGE_FROM_SYSTEM | - FORMAT_MESSAGE_IGNORE_INSERTS, - NULL, /* no message source */ - err, - MAKELANGID(LANG_NEUTRAL, - SUBLANG_DEFAULT), /* Default language */ - (LPWSTR) &s_buf, - 0, /* size not used */ - NULL); /* no args */ - if (len==0) { - /* Only seen this in out of mem situations */ - message = PyUnicode_FromFormat("Windows Error 0x%X", err); - s_buf = NULL; - } else { - /* remove trailing cr/lf and dots */ - while (len > 0 && (s_buf[len-1] <= L' ' || s_buf[len-1] == L'.')) - s_buf[--len] = L'\0'; - message = PyUnicode_FromUnicode(s_buf, len); - } - - if (message == NULL) - { - LocalFree(s_buf); - return NULL; - } - - if (filenameObject != NULL) - v = Py_BuildValue("(iOO)", err, message, filenameObject); - else - v = Py_BuildValue("(iO)", err, message); - Py_DECREF(message); - - if (v != NULL) { - PyErr_SetObject(exc, v); - Py_DECREF(v); - } - LocalFree(s_buf); - return NULL; + PyObject *exc, + int ierr, + PyObject *filenameObject) +{ + int len; + WCHAR *s_buf = NULL; /* Free via LocalFree */ + PyObject *message; + PyObject *v; + DWORD err = (DWORD)ierr; + if (err==0) err = GetLastError(); + len = FormatMessageW( + /* Error API error */ + FORMAT_MESSAGE_ALLOCATE_BUFFER | + FORMAT_MESSAGE_FROM_SYSTEM | + FORMAT_MESSAGE_IGNORE_INSERTS, + NULL, /* no message source */ + err, + MAKELANGID(LANG_NEUTRAL, + SUBLANG_DEFAULT), /* Default language */ + (LPWSTR) &s_buf, + 0, /* size not used */ + NULL); /* no args */ + if (len==0) { + /* Only seen this in out of mem situations */ + message = PyUnicode_FromFormat("Windows Error 0x%X", err); + s_buf = NULL; + } else { + /* remove trailing cr/lf and dots */ + while (len > 0 && (s_buf[len-1] <= L' ' || s_buf[len-1] == L'.')) + s_buf[--len] = L'\0'; + message = PyUnicode_FromUnicode(s_buf, len); + } + + if (message == NULL) + { + LocalFree(s_buf); + return NULL; + } + + if (filenameObject != NULL) + v = Py_BuildValue("(iOO)", err, message, filenameObject); + else + v = Py_BuildValue("(iO)", err, message); + Py_DECREF(message); + + if (v != NULL) { + PyErr_SetObject(exc, v); + Py_DECREF(v); + } + LocalFree(s_buf); + return NULL; } PyObject *PyErr_SetExcFromWindowsErrWithFilename( - PyObject *exc, - int ierr, - const char *filename) -{ - PyObject *name = filename ? PyUnicode_FromString(filename) : NULL; - PyObject *ret = PyErr_SetExcFromWindowsErrWithFilenameObject(exc, - ierr, - name); - Py_XDECREF(name); - return ret; + PyObject *exc, + int ierr, + const char *filename) +{ + PyObject *name = filename ? PyUnicode_FromString(filename) : NULL; + PyObject *ret = PyErr_SetExcFromWindowsErrWithFilenameObject(exc, + ierr, + name); + Py_XDECREF(name); + return ret; } PyObject *PyErr_SetExcFromWindowsErrWithUnicodeFilename( - PyObject *exc, - int ierr, - const Py_UNICODE *filename) -{ - PyObject *name = filename ? - PyUnicode_FromUnicode(filename, wcslen(filename)) : - NULL; - PyObject *ret = PyErr_SetExcFromWindowsErrWithFilenameObject(exc, - ierr, - name); - Py_XDECREF(name); - return ret; + PyObject *exc, + int ierr, + const Py_UNICODE *filename) +{ + PyObject *name = filename ? + PyUnicode_FromUnicode(filename, wcslen(filename)) : + NULL; + PyObject *ret = PyErr_SetExcFromWindowsErrWithFilenameObject(exc, + ierr, + name); + Py_XDECREF(name); + return ret; } PyObject *PyErr_SetExcFromWindowsErr(PyObject *exc, int ierr) { - return PyErr_SetExcFromWindowsErrWithFilename(exc, ierr, NULL); + return PyErr_SetExcFromWindowsErrWithFilename(exc, ierr, NULL); } PyObject *PyErr_SetFromWindowsErr(int ierr) { - return PyErr_SetExcFromWindowsErrWithFilename(PyExc_WindowsError, - ierr, NULL); + return PyErr_SetExcFromWindowsErrWithFilename(PyExc_WindowsError, + ierr, NULL); } PyObject *PyErr_SetFromWindowsErrWithFilename( - int ierr, - const char *filename) + int ierr, + const char *filename) { - PyObject *name = filename ? PyUnicode_FromString(filename) : NULL; - PyObject *result = PyErr_SetExcFromWindowsErrWithFilenameObject( - PyExc_WindowsError, - ierr, name); - Py_XDECREF(name); - return result; + PyObject *name = filename ? PyUnicode_FromString(filename) : NULL; + PyObject *result = PyErr_SetExcFromWindowsErrWithFilenameObject( + PyExc_WindowsError, + ierr, name); + Py_XDECREF(name); + return result; } PyObject *PyErr_SetFromWindowsErrWithUnicodeFilename( - int ierr, - const Py_UNICODE *filename) + int ierr, + const Py_UNICODE *filename) { - PyObject *name = filename ? - PyUnicode_FromUnicode(filename, wcslen(filename)) : - NULL; - PyObject *result = PyErr_SetExcFromWindowsErrWithFilenameObject( - PyExc_WindowsError, - ierr, name); - Py_XDECREF(name); - return result; + PyObject *name = filename ? + PyUnicode_FromUnicode(filename, wcslen(filename)) : + NULL; + PyObject *result = PyErr_SetExcFromWindowsErrWithFilenameObject( + PyExc_WindowsError, + ierr, name); + Py_XDECREF(name); + return result; } #endif /* MS_WINDOWS */ void _PyErr_BadInternalCall(const char *filename, int lineno) { - PyErr_Format(PyExc_SystemError, - "%s:%d: bad argument to internal function", - filename, lineno); + PyErr_Format(PyExc_SystemError, + "%s:%d: bad argument to internal function", + filename, lineno); } /* Remove the preprocessor macro for PyErr_BadInternalCall() so that we can @@ -606,8 +606,8 @@ void PyErr_BadInternalCall(void) { - PyErr_Format(PyExc_SystemError, - "bad argument to internal function"); + PyErr_Format(PyExc_SystemError, + "bad argument to internal function"); } #define PyErr_BadInternalCall() _PyErr_BadInternalCall(__FILE__, __LINE__) @@ -616,20 +616,20 @@ PyObject * PyErr_Format(PyObject *exception, const char *format, ...) { - va_list vargs; - PyObject* string; + va_list vargs; + PyObject* string; #ifdef HAVE_STDARG_PROTOTYPES - va_start(vargs, format); + va_start(vargs, format); #else - va_start(vargs); + va_start(vargs); #endif - string = PyUnicode_FromFormatV(format, vargs); - PyErr_SetObject(exception, string); - Py_XDECREF(string); - va_end(vargs); - return NULL; + string = PyUnicode_FromFormatV(format, vargs); + PyErr_SetObject(exception, string); + Py_XDECREF(string); + va_end(vargs); + return NULL; } @@ -637,85 +637,85 @@ PyObject * PyErr_NewException(const char *name, PyObject *base, PyObject *dict) { - const char *dot; - PyObject *modulename = NULL; - PyObject *classname = NULL; - PyObject *mydict = NULL; - PyObject *bases = NULL; - PyObject *result = NULL; - dot = strrchr(name, '.'); - if (dot == NULL) { - PyErr_SetString(PyExc_SystemError, - "PyErr_NewException: name must be module.class"); - return NULL; - } - if (base == NULL) - base = PyExc_Exception; - if (dict == NULL) { - dict = mydict = PyDict_New(); - if (dict == NULL) - goto failure; - } - if (PyDict_GetItemString(dict, "__module__") == NULL) { - modulename = PyUnicode_FromStringAndSize(name, - (Py_ssize_t)(dot-name)); - if (modulename == NULL) - goto failure; - if (PyDict_SetItemString(dict, "__module__", modulename) != 0) - goto failure; - } - if (PyTuple_Check(base)) { - bases = base; - /* INCREF as we create a new ref in the else branch */ - Py_INCREF(bases); - } else { - bases = PyTuple_Pack(1, base); - if (bases == NULL) - goto failure; - } - /* Create a real new-style class. */ - result = PyObject_CallFunction((PyObject *)&PyType_Type, "UOO", - dot+1, bases, dict); + const char *dot; + PyObject *modulename = NULL; + PyObject *classname = NULL; + PyObject *mydict = NULL; + PyObject *bases = NULL; + PyObject *result = NULL; + dot = strrchr(name, '.'); + if (dot == NULL) { + PyErr_SetString(PyExc_SystemError, + "PyErr_NewException: name must be module.class"); + return NULL; + } + if (base == NULL) + base = PyExc_Exception; + if (dict == NULL) { + dict = mydict = PyDict_New(); + if (dict == NULL) + goto failure; + } + if (PyDict_GetItemString(dict, "__module__") == NULL) { + modulename = PyUnicode_FromStringAndSize(name, + (Py_ssize_t)(dot-name)); + if (modulename == NULL) + goto failure; + if (PyDict_SetItemString(dict, "__module__", modulename) != 0) + goto failure; + } + if (PyTuple_Check(base)) { + bases = base; + /* INCREF as we create a new ref in the else branch */ + Py_INCREF(bases); + } else { + bases = PyTuple_Pack(1, base); + if (bases == NULL) + goto failure; + } + /* Create a real new-style class. */ + result = PyObject_CallFunction((PyObject *)&PyType_Type, "UOO", + dot+1, bases, dict); failure: - Py_XDECREF(bases); - Py_XDECREF(mydict); - Py_XDECREF(classname); - Py_XDECREF(modulename); - return result; + Py_XDECREF(bases); + Py_XDECREF(mydict); + Py_XDECREF(classname); + Py_XDECREF(modulename); + return result; } /* Create an exception with docstring */ PyObject * PyErr_NewExceptionWithDoc(const char *name, const char *doc, - PyObject *base, PyObject *dict) + PyObject *base, PyObject *dict) { - int result; - PyObject *ret = NULL; - PyObject *mydict = NULL; /* points to the dict only if we create it */ - PyObject *docobj; - - if (dict == NULL) { - dict = mydict = PyDict_New(); - if (dict == NULL) { - return NULL; - } - } - - if (doc != NULL) { - docobj = PyUnicode_FromString(doc); - if (docobj == NULL) - goto failure; - result = PyDict_SetItemString(dict, "__doc__", docobj); - Py_DECREF(docobj); - if (result < 0) - goto failure; - } + int result; + PyObject *ret = NULL; + PyObject *mydict = NULL; /* points to the dict only if we create it */ + PyObject *docobj; + + if (dict == NULL) { + dict = mydict = PyDict_New(); + if (dict == NULL) { + return NULL; + } + } + + if (doc != NULL) { + docobj = PyUnicode_FromString(doc); + if (docobj == NULL) + goto failure; + result = PyDict_SetItemString(dict, "__doc__", docobj); + Py_DECREF(docobj); + if (result < 0) + goto failure; + } - ret = PyErr_NewException(name, base, dict); + ret = PyErr_NewException(name, base, dict); failure: - Py_XDECREF(mydict); - return ret; + Py_XDECREF(mydict); + return ret; } @@ -724,52 +724,52 @@ void PyErr_WriteUnraisable(PyObject *obj) { - PyObject *f, *t, *v, *tb; - PyErr_Fetch(&t, &v, &tb); - f = PySys_GetObject("stderr"); - if (f != NULL && f != Py_None) { - PyFile_WriteString("Exception ", f); - if (t) { - PyObject* moduleName; - char* className; - assert(PyExceptionClass_Check(t)); - className = PyExceptionClass_Name(t); - if (className != NULL) { - char *dot = strrchr(className, '.'); - if (dot != NULL) - className = dot+1; - } - - moduleName = PyObject_GetAttrString(t, "__module__"); - if (moduleName == NULL) - PyFile_WriteString("", f); - else { - char* modstr = _PyUnicode_AsString(moduleName); - if (modstr && - strcmp(modstr, "builtins") != 0) - { - PyFile_WriteString(modstr, f); - PyFile_WriteString(".", f); - } - } - if (className == NULL) - PyFile_WriteString("", f); - else - PyFile_WriteString(className, f); - if (v && v != Py_None) { - PyFile_WriteString(": ", f); - PyFile_WriteObject(v, f, 0); - } - Py_XDECREF(moduleName); - } - PyFile_WriteString(" in ", f); - PyFile_WriteObject(obj, f, 0); - PyFile_WriteString(" ignored\n", f); - PyErr_Clear(); /* Just in case */ - } - Py_XDECREF(t); - Py_XDECREF(v); - Py_XDECREF(tb); + PyObject *f, *t, *v, *tb; + PyErr_Fetch(&t, &v, &tb); + f = PySys_GetObject("stderr"); + if (f != NULL && f != Py_None) { + PyFile_WriteString("Exception ", f); + if (t) { + PyObject* moduleName; + char* className; + assert(PyExceptionClass_Check(t)); + className = PyExceptionClass_Name(t); + if (className != NULL) { + char *dot = strrchr(className, '.'); + if (dot != NULL) + className = dot+1; + } + + moduleName = PyObject_GetAttrString(t, "__module__"); + if (moduleName == NULL) + PyFile_WriteString("", f); + else { + char* modstr = _PyUnicode_AsString(moduleName); + if (modstr && + strcmp(modstr, "builtins") != 0) + { + PyFile_WriteString(modstr, f); + PyFile_WriteString(".", f); + } + } + if (className == NULL) + PyFile_WriteString("", f); + else + PyFile_WriteString(className, f); + if (v && v != Py_None) { + PyFile_WriteString(": ", f); + PyFile_WriteObject(v, f, 0); + } + Py_XDECREF(moduleName); + } + PyFile_WriteString(" in ", f); + PyFile_WriteObject(obj, f, 0); + PyFile_WriteString(" ignored\n", f); + PyErr_Clear(); /* Just in case */ + } + Py_XDECREF(t); + Py_XDECREF(v); + Py_XDECREF(tb); } extern PyObject *PyModule_GetWarningsModule(void); @@ -782,59 +782,59 @@ void PyErr_SyntaxLocation(const char *filename, int lineno) { - PyObject *exc, *v, *tb, *tmp; + PyObject *exc, *v, *tb, *tmp; - /* add attributes for the line number and filename for the error */ - PyErr_Fetch(&exc, &v, &tb); - PyErr_NormalizeException(&exc, &v, &tb); - /* XXX check that it is, indeed, a syntax error. It might not - * be, though. */ - tmp = PyLong_FromLong(lineno); - if (tmp == NULL) - PyErr_Clear(); - else { - if (PyObject_SetAttrString(v, "lineno", tmp)) - PyErr_Clear(); - Py_DECREF(tmp); - } - if (filename != NULL) { - tmp = PyUnicode_FromString(filename); - if (tmp == NULL) - PyErr_Clear(); - else { - if (PyObject_SetAttrString(v, "filename", tmp)) - PyErr_Clear(); - Py_DECREF(tmp); - } - - tmp = PyErr_ProgramText(filename, lineno); - if (tmp) { - if (PyObject_SetAttrString(v, "text", tmp)) - PyErr_Clear(); - Py_DECREF(tmp); - } - } - if (PyObject_SetAttrString(v, "offset", Py_None)) { - PyErr_Clear(); - } - if (exc != PyExc_SyntaxError) { - if (!PyObject_HasAttrString(v, "msg")) { - tmp = PyObject_Str(v); - if (tmp) { - if (PyObject_SetAttrString(v, "msg", tmp)) - PyErr_Clear(); - Py_DECREF(tmp); - } else { - PyErr_Clear(); - } - } - if (!PyObject_HasAttrString(v, "print_file_and_line")) { - if (PyObject_SetAttrString(v, "print_file_and_line", - Py_None)) - PyErr_Clear(); - } - } - PyErr_Restore(exc, v, tb); + /* add attributes for the line number and filename for the error */ + PyErr_Fetch(&exc, &v, &tb); + PyErr_NormalizeException(&exc, &v, &tb); + /* XXX check that it is, indeed, a syntax error. It might not + * be, though. */ + tmp = PyLong_FromLong(lineno); + if (tmp == NULL) + PyErr_Clear(); + else { + if (PyObject_SetAttrString(v, "lineno", tmp)) + PyErr_Clear(); + Py_DECREF(tmp); + } + if (filename != NULL) { + tmp = PyUnicode_FromString(filename); + if (tmp == NULL) + PyErr_Clear(); + else { + if (PyObject_SetAttrString(v, "filename", tmp)) + PyErr_Clear(); + Py_DECREF(tmp); + } + + tmp = PyErr_ProgramText(filename, lineno); + if (tmp) { + if (PyObject_SetAttrString(v, "text", tmp)) + PyErr_Clear(); + Py_DECREF(tmp); + } + } + if (PyObject_SetAttrString(v, "offset", Py_None)) { + PyErr_Clear(); + } + if (exc != PyExc_SyntaxError) { + if (!PyObject_HasAttrString(v, "msg")) { + tmp = PyObject_Str(v); + if (tmp) { + if (PyObject_SetAttrString(v, "msg", tmp)) + PyErr_Clear(); + Py_DECREF(tmp); + } else { + PyErr_Clear(); + } + } + if (!PyObject_HasAttrString(v, "print_file_and_line")) { + if (PyObject_SetAttrString(v, "print_file_and_line", + Py_None)) + PyErr_Clear(); + } + } + PyErr_Restore(exc, v, tb); } /* Attempt to load the line of text that the exception refers to. If it @@ -846,41 +846,41 @@ PyObject * PyErr_ProgramText(const char *filename, int lineno) { - FILE *fp; - int i; - char linebuf[1000]; - - if (filename == NULL || *filename == '\0' || lineno <= 0) - return NULL; - fp = fopen(filename, "r" PY_STDIOTEXTMODE); - if (fp == NULL) - return NULL; - for (i = 0; i < lineno; i++) { - char *pLastChar = &linebuf[sizeof(linebuf) - 2]; - do { - *pLastChar = '\0'; - if (Py_UniversalNewlineFgets(linebuf, sizeof linebuf, - fp, NULL) == NULL) - break; - /* fgets read *something*; if it didn't get as - far as pLastChar, it must have found a newline - or hit the end of the file; if pLastChar is \n, - it obviously found a newline; else we haven't - yet seen a newline, so must continue */ - } while (*pLastChar != '\0' && *pLastChar != '\n'); - } - fclose(fp); - if (i == lineno) { - char *p = linebuf; - PyObject *res; - while (*p == ' ' || *p == '\t' || *p == '\014') - p++; - res = PyUnicode_FromString(p); - if (res == NULL) - PyErr_Clear(); - return res; - } - return NULL; + FILE *fp; + int i; + char linebuf[1000]; + + if (filename == NULL || *filename == '\0' || lineno <= 0) + return NULL; + fp = fopen(filename, "r" PY_STDIOTEXTMODE); + if (fp == NULL) + return NULL; + for (i = 0; i < lineno; i++) { + char *pLastChar = &linebuf[sizeof(linebuf) - 2]; + do { + *pLastChar = '\0'; + if (Py_UniversalNewlineFgets(linebuf, sizeof linebuf, + fp, NULL) == NULL) + break; + /* fgets read *something*; if it didn't get as + far as pLastChar, it must have found a newline + or hit the end of the file; if pLastChar is \n, + it obviously found a newline; else we haven't + yet seen a newline, so must continue */ + } while (*pLastChar != '\0' && *pLastChar != '\n'); + } + fclose(fp); + if (i == lineno) { + char *p = linebuf; + PyObject *res; + while (*p == ' ' || *p == '\t' || *p == '\014') + p++; + res = PyUnicode_FromString(p); + if (res == NULL) + PyErr_Clear(); + return res; + } + return NULL; } #ifdef __cplusplus Modified: python/branches/py3k/Python/frozen.c ============================================================================== --- python/branches/py3k/Python/frozen.c (original) +++ python/branches/py3k/Python/frozen.c Sun May 9 17:52:27 2010 @@ -12,25 +12,25 @@ the appropriate bytes from M___main__.c. */ static unsigned char M___hello__[] = { - 99,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0, - 0,64,0,0,0,115,10,0,0,0,100,1,0,90,1,0, - 100,0,0,83,40,2,0,0,0,78,84,40,2,0,0,0, - 117,4,0,0,0,84,114,117,101,117,11,0,0,0,105,110, - 105,116,105,97,108,105,122,101,100,40,0,0,0,0,40,0, - 0,0,0,40,0,0,0,0,117,7,0,0,0,102,108,97, - 103,46,112,121,117,8,0,0,0,60,109,111,100,117,108,101, - 62,1,0,0,0,115,0,0,0,0, + 99,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0, + 0,64,0,0,0,115,10,0,0,0,100,1,0,90,1,0, + 100,0,0,83,40,2,0,0,0,78,84,40,2,0,0,0, + 117,4,0,0,0,84,114,117,101,117,11,0,0,0,105,110, + 105,116,105,97,108,105,122,101,100,40,0,0,0,0,40,0, + 0,0,0,40,0,0,0,0,117,7,0,0,0,102,108,97, + 103,46,112,121,117,8,0,0,0,60,109,111,100,117,108,101, + 62,1,0,0,0,115,0,0,0,0, }; #define SIZE (int)sizeof(M___hello__) static struct _frozen _PyImport_FrozenModules[] = { - /* Test module */ - {"__hello__", M___hello__, SIZE}, - /* Test package (negative size indicates package-ness) */ - {"__phello__", M___hello__, -SIZE}, - {"__phello__.spam", M___hello__, SIZE}, - {0, 0, 0} /* sentinel */ + /* Test module */ + {"__hello__", M___hello__, SIZE}, + /* Test package (negative size indicates package-ness) */ + {"__phello__", M___hello__, -SIZE}, + {"__phello__.spam", M___hello__, SIZE}, + {0, 0, 0} /* sentinel */ }; /* Embedding apps may change this pointer to point to their favorite Modified: python/branches/py3k/Python/frozenmain.c ============================================================================== --- python/branches/py3k/Python/frozenmain.c (original) +++ python/branches/py3k/Python/frozenmain.c Sun May 9 17:52:27 2010 @@ -15,96 +15,96 @@ int Py_FrozenMain(int argc, char **argv) { - char *p; - int i, n, sts; - int inspect = 0; - int unbuffered = 0; - char *oldloc; - wchar_t **argv_copy = PyMem_Malloc(sizeof(wchar_t*)*argc); - /* We need a second copies, as Python might modify the first one. */ - wchar_t **argv_copy2 = PyMem_Malloc(sizeof(wchar_t*)*argc); - - Py_FrozenFlag = 1; /* Suppress errors from getpath.c */ - - if ((p = Py_GETENV("PYTHONINSPECT")) && *p != '\0') - inspect = 1; - if ((p = Py_GETENV("PYTHONUNBUFFERED")) && *p != '\0') - unbuffered = 1; - - if (unbuffered) { - setbuf(stdin, (char *)NULL); - setbuf(stdout, (char *)NULL); - setbuf(stderr, (char *)NULL); - } - - if (!argv_copy) { - fprintf(stderr, "out of memory\n"); - return 1; - } - - oldloc = setlocale(LC_ALL, NULL); - setlocale(LC_ALL, ""); - for (i = 0; i < argc; i++) { + char *p; + int i, n, sts; + int inspect = 0; + int unbuffered = 0; + char *oldloc; + wchar_t **argv_copy = PyMem_Malloc(sizeof(wchar_t*)*argc); + /* We need a second copies, as Python might modify the first one. */ + wchar_t **argv_copy2 = PyMem_Malloc(sizeof(wchar_t*)*argc); + + Py_FrozenFlag = 1; /* Suppress errors from getpath.c */ + + if ((p = Py_GETENV("PYTHONINSPECT")) && *p != '\0') + inspect = 1; + if ((p = Py_GETENV("PYTHONUNBUFFERED")) && *p != '\0') + unbuffered = 1; + + if (unbuffered) { + setbuf(stdin, (char *)NULL); + setbuf(stdout, (char *)NULL); + setbuf(stderr, (char *)NULL); + } + + if (!argv_copy) { + fprintf(stderr, "out of memory\n"); + return 1; + } + + oldloc = setlocale(LC_ALL, NULL); + setlocale(LC_ALL, ""); + for (i = 0; i < argc; i++) { #ifdef HAVE_BROKEN_MBSTOWCS - size_t argsize = strlen(argv[i]); + size_t argsize = strlen(argv[i]); #else - size_t argsize = mbstowcs(NULL, argv[i], 0); + size_t argsize = mbstowcs(NULL, argv[i], 0); #endif - size_t count; - if (argsize == (size_t)-1) { - fprintf(stderr, "Could not convert argument %d to string\n", i); - return 1; - } - argv_copy[i] = PyMem_Malloc((argsize+1)*sizeof(wchar_t)); - argv_copy2[i] = argv_copy[i]; - if (!argv_copy[i]) { - fprintf(stderr, "out of memory\n"); - return 1; - } - count = mbstowcs(argv_copy[i], argv[i], argsize+1); - if (count == (size_t)-1) { - fprintf(stderr, "Could not convert argument %d to string\n", i); - return 1; - } - } - setlocale(LC_ALL, oldloc); + size_t count; + if (argsize == (size_t)-1) { + fprintf(stderr, "Could not convert argument %d to string\n", i); + return 1; + } + argv_copy[i] = PyMem_Malloc((argsize+1)*sizeof(wchar_t)); + argv_copy2[i] = argv_copy[i]; + if (!argv_copy[i]) { + fprintf(stderr, "out of memory\n"); + return 1; + } + count = mbstowcs(argv_copy[i], argv[i], argsize+1); + if (count == (size_t)-1) { + fprintf(stderr, "Could not convert argument %d to string\n", i); + return 1; + } + } + setlocale(LC_ALL, oldloc); #ifdef MS_WINDOWS - PyInitFrozenExtensions(); + PyInitFrozenExtensions(); #endif /* MS_WINDOWS */ - Py_SetProgramName(argv_copy[0]); - Py_Initialize(); + Py_SetProgramName(argv_copy[0]); + Py_Initialize(); #ifdef MS_WINDOWS - PyWinFreeze_ExeInit(); + PyWinFreeze_ExeInit(); #endif - if (Py_VerboseFlag) - fprintf(stderr, "Python %s\n%s\n", - Py_GetVersion(), Py_GetCopyright()); - - PySys_SetArgv(argc, argv_copy); - - n = PyImport_ImportFrozenModule("__main__"); - if (n == 0) - Py_FatalError("__main__ not frozen"); - if (n < 0) { - PyErr_Print(); - sts = 1; - } - else - sts = 0; + if (Py_VerboseFlag) + fprintf(stderr, "Python %s\n%s\n", + Py_GetVersion(), Py_GetCopyright()); + + PySys_SetArgv(argc, argv_copy); + + n = PyImport_ImportFrozenModule("__main__"); + if (n == 0) + Py_FatalError("__main__ not frozen"); + if (n < 0) { + PyErr_Print(); + sts = 1; + } + else + sts = 0; - if (inspect && isatty((int)fileno(stdin))) - sts = PyRun_AnyFile(stdin, "") != 0; + if (inspect && isatty((int)fileno(stdin))) + sts = PyRun_AnyFile(stdin, "") != 0; #ifdef MS_WINDOWS - PyWinFreeze_ExeTerm(); + PyWinFreeze_ExeTerm(); #endif - Py_Finalize(); - for (i = 0; i < argc; i++) { - PyMem_Free(argv_copy2[i]); - } - PyMem_Free(argv_copy); - PyMem_Free(argv_copy2); - return sts; + Py_Finalize(); + for (i = 0; i < argc; i++) { + PyMem_Free(argv_copy2[i]); + } + PyMem_Free(argv_copy); + PyMem_Free(argv_copy2); + return sts; } Modified: python/branches/py3k/Python/future.c ============================================================================== --- python/branches/py3k/Python/future.c (original) +++ python/branches/py3k/Python/future.c Sun May 9 17:52:27 2010 @@ -14,131 +14,131 @@ static int future_check_features(PyFutureFeatures *ff, stmt_ty s, const char *filename) { - int i; - asdl_seq *names; + int i; + asdl_seq *names; - assert(s->kind == ImportFrom_kind); + assert(s->kind == ImportFrom_kind); - names = s->v.ImportFrom.names; - for (i = 0; i < asdl_seq_LEN(names); i++) { - alias_ty name = (alias_ty)asdl_seq_GET(names, i); - const char *feature = _PyUnicode_AsString(name->name); - if (!feature) - return 0; - if (strcmp(feature, FUTURE_NESTED_SCOPES) == 0) { - continue; - } else if (strcmp(feature, FUTURE_GENERATORS) == 0) { - continue; - } else if (strcmp(feature, FUTURE_DIVISION) == 0) { - continue; - } else if (strcmp(feature, FUTURE_ABSOLUTE_IMPORT) == 0) { - continue; - } else if (strcmp(feature, FUTURE_WITH_STATEMENT) == 0) { - continue; - } else if (strcmp(feature, FUTURE_PRINT_FUNCTION) == 0) { - continue; - } else if (strcmp(feature, FUTURE_UNICODE_LITERALS) == 0) { - continue; - } else if (strcmp(feature, FUTURE_BARRY_AS_BDFL) == 0) { - ff->ff_features |= CO_FUTURE_BARRY_AS_BDFL; - } else if (strcmp(feature, "braces") == 0) { - PyErr_SetString(PyExc_SyntaxError, - "not a chance"); - PyErr_SyntaxLocation(filename, s->lineno); - return 0; - } else { - PyErr_Format(PyExc_SyntaxError, - UNDEFINED_FUTURE_FEATURE, feature); - PyErr_SyntaxLocation(filename, s->lineno); - return 0; - } - } - return 1; + names = s->v.ImportFrom.names; + for (i = 0; i < asdl_seq_LEN(names); i++) { + alias_ty name = (alias_ty)asdl_seq_GET(names, i); + const char *feature = _PyUnicode_AsString(name->name); + if (!feature) + return 0; + if (strcmp(feature, FUTURE_NESTED_SCOPES) == 0) { + continue; + } else if (strcmp(feature, FUTURE_GENERATORS) == 0) { + continue; + } else if (strcmp(feature, FUTURE_DIVISION) == 0) { + continue; + } else if (strcmp(feature, FUTURE_ABSOLUTE_IMPORT) == 0) { + continue; + } else if (strcmp(feature, FUTURE_WITH_STATEMENT) == 0) { + continue; + } else if (strcmp(feature, FUTURE_PRINT_FUNCTION) == 0) { + continue; + } else if (strcmp(feature, FUTURE_UNICODE_LITERALS) == 0) { + continue; + } else if (strcmp(feature, FUTURE_BARRY_AS_BDFL) == 0) { + ff->ff_features |= CO_FUTURE_BARRY_AS_BDFL; + } else if (strcmp(feature, "braces") == 0) { + PyErr_SetString(PyExc_SyntaxError, + "not a chance"); + PyErr_SyntaxLocation(filename, s->lineno); + return 0; + } else { + PyErr_Format(PyExc_SyntaxError, + UNDEFINED_FUTURE_FEATURE, feature); + PyErr_SyntaxLocation(filename, s->lineno); + return 0; + } + } + return 1; } static int future_parse(PyFutureFeatures *ff, mod_ty mod, const char *filename) { - int i, found_docstring = 0, done = 0, prev_line = 0; + int i, found_docstring = 0, done = 0, prev_line = 0; - static PyObject *future; - if (!future) { - future = PyUnicode_InternFromString("__future__"); - if (!future) - return 0; - } - - if (!(mod->kind == Module_kind || mod->kind == Interactive_kind)) - return 1; - - /* A subsequent pass will detect future imports that don't - appear at the beginning of the file. There's one case, - however, that is easier to handle here: A series of imports - joined by semi-colons, where the first import is a future - statement but some subsequent import has the future form - but is preceded by a regular import. - */ - - - for (i = 0; i < asdl_seq_LEN(mod->v.Module.body); i++) { - stmt_ty s = (stmt_ty)asdl_seq_GET(mod->v.Module.body, i); - - if (done && s->lineno > prev_line) - return 1; - prev_line = s->lineno; - - /* The tests below will return from this function unless it is - still possible to find a future statement. The only things - that can precede a future statement are another future - statement and a doc string. - */ - - if (s->kind == ImportFrom_kind) { - if (s->v.ImportFrom.module == future) { - if (done) { - PyErr_SetString(PyExc_SyntaxError, - ERR_LATE_FUTURE); - PyErr_SyntaxLocation(filename, - s->lineno); - return 0; - } - if (!future_check_features(ff, s, filename)) - return 0; - ff->ff_lineno = s->lineno; - } - else - done = 1; - } - else if (s->kind == Expr_kind && !found_docstring) { - expr_ty e = s->v.Expr.value; - if (e->kind != Str_kind) - done = 1; - else - found_docstring = 1; - } - else - done = 1; - } - return 1; + static PyObject *future; + if (!future) { + future = PyUnicode_InternFromString("__future__"); + if (!future) + return 0; + } + + if (!(mod->kind == Module_kind || mod->kind == Interactive_kind)) + return 1; + + /* A subsequent pass will detect future imports that don't + appear at the beginning of the file. There's one case, + however, that is easier to handle here: A series of imports + joined by semi-colons, where the first import is a future + statement but some subsequent import has the future form + but is preceded by a regular import. + */ + + + for (i = 0; i < asdl_seq_LEN(mod->v.Module.body); i++) { + stmt_ty s = (stmt_ty)asdl_seq_GET(mod->v.Module.body, i); + + if (done && s->lineno > prev_line) + return 1; + prev_line = s->lineno; + + /* The tests below will return from this function unless it is + still possible to find a future statement. The only things + that can precede a future statement are another future + statement and a doc string. + */ + + if (s->kind == ImportFrom_kind) { + if (s->v.ImportFrom.module == future) { + if (done) { + PyErr_SetString(PyExc_SyntaxError, + ERR_LATE_FUTURE); + PyErr_SyntaxLocation(filename, + s->lineno); + return 0; + } + if (!future_check_features(ff, s, filename)) + return 0; + ff->ff_lineno = s->lineno; + } + else + done = 1; + } + else if (s->kind == Expr_kind && !found_docstring) { + expr_ty e = s->v.Expr.value; + if (e->kind != Str_kind) + done = 1; + else + found_docstring = 1; + } + else + done = 1; + } + return 1; } PyFutureFeatures * PyFuture_FromAST(mod_ty mod, const char *filename) { - PyFutureFeatures *ff; + PyFutureFeatures *ff; - ff = (PyFutureFeatures *)PyObject_Malloc(sizeof(PyFutureFeatures)); - if (ff == NULL) { - PyErr_NoMemory(); - return NULL; - } - ff->ff_features = 0; - ff->ff_lineno = -1; - - if (!future_parse(ff, mod, filename)) { - PyObject_Free(ff); - return NULL; - } - return ff; + ff = (PyFutureFeatures *)PyObject_Malloc(sizeof(PyFutureFeatures)); + if (ff == NULL) { + PyErr_NoMemory(); + return NULL; + } + ff->ff_features = 0; + ff->ff_lineno = -1; + + if (!future_parse(ff, mod, filename)) { + PyObject_Free(ff); + return NULL; + } + return ff; } Modified: python/branches/py3k/Python/getargs.c ============================================================================== --- python/branches/py3k/Python/getargs.c (original) +++ python/branches/py3k/Python/getargs.c Sun May 9 17:52:27 2010 @@ -14,9 +14,9 @@ int PyArg_VaParse(PyObject *, const char *, va_list); int PyArg_ParseTupleAndKeywords(PyObject *, PyObject *, - const char *, char **, ...); + const char *, char **, ...); int PyArg_VaParseTupleAndKeywords(PyObject *, PyObject *, - const char *, char **, va_list); + const char *, char **, va_list); #ifdef HAVE_DECLSPEC_DLL /* Export functions */ @@ -40,100 +40,100 @@ static char *convertitem(PyObject *, const char **, va_list *, int, int *, char *, size_t, PyObject **); static char *converttuple(PyObject *, const char **, va_list *, int, - int *, char *, size_t, int, PyObject **); + int *, char *, size_t, int, PyObject **); static char *convertsimple(PyObject *, const char **, va_list *, int, char *, - size_t, PyObject **); + size_t, PyObject **); static Py_ssize_t convertbuffer(PyObject *, void **p, char **); static int getbuffer(PyObject *, Py_buffer *, char**); static int vgetargskeywords(PyObject *, PyObject *, - const char *, char **, va_list *, int); + const char *, char **, va_list *, int); static char *skipitem(const char **, va_list *, int); int PyArg_Parse(PyObject *args, const char *format, ...) { - int retval; - va_list va; + int retval; + va_list va; - va_start(va, format); - retval = vgetargs1(args, format, &va, FLAG_COMPAT); - va_end(va); - return retval; + va_start(va, format); + retval = vgetargs1(args, format, &va, FLAG_COMPAT); + va_end(va); + return retval; } int _PyArg_Parse_SizeT(PyObject *args, char *format, ...) { - int retval; - va_list va; + int retval; + va_list va; - va_start(va, format); - retval = vgetargs1(args, format, &va, FLAG_COMPAT|FLAG_SIZE_T); - va_end(va); - return retval; + va_start(va, format); + retval = vgetargs1(args, format, &va, FLAG_COMPAT|FLAG_SIZE_T); + va_end(va); + return retval; } int PyArg_ParseTuple(PyObject *args, const char *format, ...) { - int retval; - va_list va; + int retval; + va_list va; - va_start(va, format); - retval = vgetargs1(args, format, &va, 0); - va_end(va); - return retval; + va_start(va, format); + retval = vgetargs1(args, format, &va, 0); + va_end(va); + return retval; } int _PyArg_ParseTuple_SizeT(PyObject *args, char *format, ...) { - int retval; - va_list va; + int retval; + va_list va; - va_start(va, format); - retval = vgetargs1(args, format, &va, FLAG_SIZE_T); - va_end(va); - return retval; + va_start(va, format); + retval = vgetargs1(args, format, &va, FLAG_SIZE_T); + va_end(va); + return retval; } int PyArg_VaParse(PyObject *args, const char *format, va_list va) { - va_list lva; + va_list lva; #ifdef VA_LIST_IS_ARRAY - memcpy(lva, va, sizeof(va_list)); + memcpy(lva, va, sizeof(va_list)); #else #ifdef __va_copy - __va_copy(lva, va); + __va_copy(lva, va); #else - lva = va; + lva = va; #endif #endif - return vgetargs1(args, format, &lva, 0); + return vgetargs1(args, format, &lva, 0); } int _PyArg_VaParse_SizeT(PyObject *args, char *format, va_list va) { - va_list lva; + va_list lva; #ifdef VA_LIST_IS_ARRAY - memcpy(lva, va, sizeof(va_list)); + memcpy(lva, va, sizeof(va_list)); #else #ifdef __va_copy - __va_copy(lva, va); + __va_copy(lva, va); #else - lva = va; + lva = va; #endif #endif - return vgetargs1(args, format, &lva, FLAG_SIZE_T); + return vgetargs1(args, format, &lva, FLAG_SIZE_T); } @@ -146,261 +146,261 @@ static void cleanup_ptr(PyObject *self) { - void *ptr = PyCapsule_GetPointer(self, GETARGS_CAPSULE_NAME_CLEANUP_PTR); - if (ptr) { - PyMem_FREE(ptr); - } + void *ptr = PyCapsule_GetPointer(self, GETARGS_CAPSULE_NAME_CLEANUP_PTR); + if (ptr) { + PyMem_FREE(ptr); + } } static void cleanup_buffer(PyObject *self) { - Py_buffer *ptr = (Py_buffer *)PyCapsule_GetPointer(self, GETARGS_CAPSULE_NAME_CLEANUP_BUFFER); - if (ptr) { - PyBuffer_Release(ptr); - } + Py_buffer *ptr = (Py_buffer *)PyCapsule_GetPointer(self, GETARGS_CAPSULE_NAME_CLEANUP_BUFFER); + if (ptr) { + PyBuffer_Release(ptr); + } } static int addcleanup(void *ptr, PyObject **freelist, PyCapsule_Destructor destr) { - PyObject *cobj; - const char *name; + PyObject *cobj; + const char *name; - if (!*freelist) { - *freelist = PyList_New(0); - if (!*freelist) { - destr(ptr); - return -1; - } - } - - if (destr == cleanup_ptr) { - name = GETARGS_CAPSULE_NAME_CLEANUP_PTR; - } else if (destr == cleanup_buffer) { - name = GETARGS_CAPSULE_NAME_CLEANUP_BUFFER; - } else { - return -1; - } - cobj = PyCapsule_New(ptr, name, destr); - if (!cobj) { - destr(ptr); - return -1; - } - if (PyList_Append(*freelist, cobj)) { - Py_DECREF(cobj); - return -1; - } + if (!*freelist) { + *freelist = PyList_New(0); + if (!*freelist) { + destr(ptr); + return -1; + } + } + + if (destr == cleanup_ptr) { + name = GETARGS_CAPSULE_NAME_CLEANUP_PTR; + } else if (destr == cleanup_buffer) { + name = GETARGS_CAPSULE_NAME_CLEANUP_BUFFER; + } else { + return -1; + } + cobj = PyCapsule_New(ptr, name, destr); + if (!cobj) { + destr(ptr); + return -1; + } + if (PyList_Append(*freelist, cobj)) { Py_DECREF(cobj); - return 0; + return -1; + } + Py_DECREF(cobj); + return 0; } static void cleanup_convert(PyObject *self) { - typedef int (*destr_t)(PyObject *, void *); - destr_t destr = (destr_t)PyCapsule_GetContext(self); - void *ptr = PyCapsule_GetPointer(self, - GETARGS_CAPSULE_NAME_CLEANUP_CONVERT); - if (ptr && destr) - destr(NULL, ptr); + typedef int (*destr_t)(PyObject *, void *); + destr_t destr = (destr_t)PyCapsule_GetContext(self); + void *ptr = PyCapsule_GetPointer(self, + GETARGS_CAPSULE_NAME_CLEANUP_CONVERT); + if (ptr && destr) + destr(NULL, ptr); } static int addcleanup_convert(void *ptr, PyObject **freelist, int (*destr)(PyObject*,void*)) { - PyObject *cobj; - if (!*freelist) { - *freelist = PyList_New(0); - if (!*freelist) { - destr(NULL, ptr); - return -1; - } - } - cobj = PyCapsule_New(ptr, GETARGS_CAPSULE_NAME_CLEANUP_CONVERT, - cleanup_convert); - if (!cobj) { - destr(NULL, ptr); - return -1; - } - if (PyCapsule_SetContext(cobj, destr) == -1) { - /* This really should not happen. */ - Py_FatalError("capsule refused setting of context."); - } - if (PyList_Append(*freelist, cobj)) { - Py_DECREF(cobj); /* This will also call destr. */ - return -1; - } - Py_DECREF(cobj); - return 0; + PyObject *cobj; + if (!*freelist) { + *freelist = PyList_New(0); + if (!*freelist) { + destr(NULL, ptr); + return -1; + } + } + cobj = PyCapsule_New(ptr, GETARGS_CAPSULE_NAME_CLEANUP_CONVERT, + cleanup_convert); + if (!cobj) { + destr(NULL, ptr); + return -1; + } + if (PyCapsule_SetContext(cobj, destr) == -1) { + /* This really should not happen. */ + Py_FatalError("capsule refused setting of context."); + } + if (PyList_Append(*freelist, cobj)) { + Py_DECREF(cobj); /* This will also call destr. */ + return -1; + } + Py_DECREF(cobj); + return 0; } static int cleanreturn(int retval, PyObject *freelist) { - if (freelist && retval != 0) { - /* We were successful, reset the destructors so that they - don't get called. */ - Py_ssize_t len = PyList_GET_SIZE(freelist), i; - for (i = 0; i < len; i++) - PyCapsule_SetDestructor(PyList_GET_ITEM(freelist, i), NULL); - } - Py_XDECREF(freelist); - return retval; + if (freelist && retval != 0) { + /* We were successful, reset the destructors so that they + don't get called. */ + Py_ssize_t len = PyList_GET_SIZE(freelist), i; + for (i = 0; i < len; i++) + PyCapsule_SetDestructor(PyList_GET_ITEM(freelist, i), NULL); + } + Py_XDECREF(freelist); + return retval; } static int vgetargs1(PyObject *args, const char *format, va_list *p_va, int flags) { - char msgbuf[256]; - int levels[32]; - const char *fname = NULL; - const char *message = NULL; - int min = -1; - int max = 0; - int level = 0; - int endfmt = 0; - const char *formatsave = format; - Py_ssize_t i, len; - char *msg; - PyObject *freelist = NULL; - int compat = flags & FLAG_COMPAT; - - assert(compat || (args != (PyObject*)NULL)); - flags = flags & ~FLAG_COMPAT; - - while (endfmt == 0) { - int c = *format++; - switch (c) { - case '(': - if (level == 0) - max++; - level++; - if (level >= 30) - Py_FatalError("too many tuple nesting levels " - "in argument format string"); - break; - case ')': - if (level == 0) - Py_FatalError("excess ')' in getargs format"); - else - level--; - break; - case '\0': - endfmt = 1; - break; - case ':': - fname = format; - endfmt = 1; - break; - case ';': - message = format; - endfmt = 1; - break; - default: - if (level == 0) { - if (c == 'O') - max++; - else if (isalpha(Py_CHARMASK(c))) { - if (c != 'e') /* skip encoded */ - max++; - } else if (c == '|') - min = max; - } - break; - } - } - - if (level != 0) - Py_FatalError(/* '(' */ "missing ')' in getargs format"); - - if (min < 0) - min = max; - - format = formatsave; - - if (compat) { - if (max == 0) { - if (args == NULL) - return 1; - PyOS_snprintf(msgbuf, sizeof(msgbuf), - "%.200s%s takes no arguments", - fname==NULL ? "function" : fname, - fname==NULL ? "" : "()"); - PyErr_SetString(PyExc_TypeError, msgbuf); - return 0; - } - else if (min == 1 && max == 1) { - if (args == NULL) { - PyOS_snprintf(msgbuf, sizeof(msgbuf), - "%.200s%s takes at least one argument", - fname==NULL ? "function" : fname, - fname==NULL ? "" : "()"); - PyErr_SetString(PyExc_TypeError, msgbuf); - return 0; - } - msg = convertitem(args, &format, p_va, flags, levels, - msgbuf, sizeof(msgbuf), &freelist); - if (msg == NULL) - return cleanreturn(1, freelist); - seterror(levels[0], msg, levels+1, fname, message); - return cleanreturn(0, freelist); - } - else { - PyErr_SetString(PyExc_SystemError, - "old style getargs format uses new features"); - return 0; - } - } - - if (!PyTuple_Check(args)) { - PyErr_SetString(PyExc_SystemError, - "new style getargs format but argument is not a tuple"); - return 0; - } - - len = PyTuple_GET_SIZE(args); - - if (len < min || max < len) { - if (message == NULL) { - PyOS_snprintf(msgbuf, sizeof(msgbuf), - "%.150s%s takes %s %d argument%s " - "(%ld given)", - fname==NULL ? "function" : fname, - fname==NULL ? "" : "()", - min==max ? "exactly" - : len < min ? "at least" : "at most", - len < min ? min : max, - (len < min ? min : max) == 1 ? "" : "s", - Py_SAFE_DOWNCAST(len, Py_ssize_t, long)); - message = msgbuf; - } - PyErr_SetString(PyExc_TypeError, message); - return 0; - } - - for (i = 0; i < len; i++) { - if (*format == '|') - format++; - msg = convertitem(PyTuple_GET_ITEM(args, i), &format, p_va, - flags, levels, msgbuf, - sizeof(msgbuf), &freelist); - if (msg) { - seterror(i+1, msg, levels, fname, msg); - return cleanreturn(0, freelist); - } - } - - if (*format != '\0' && !isalpha(Py_CHARMASK(*format)) && - *format != '(' && - *format != '|' && *format != ':' && *format != ';') { - PyErr_Format(PyExc_SystemError, - "bad format string: %.200s", formatsave); - return cleanreturn(0, freelist); - } + char msgbuf[256]; + int levels[32]; + const char *fname = NULL; + const char *message = NULL; + int min = -1; + int max = 0; + int level = 0; + int endfmt = 0; + const char *formatsave = format; + Py_ssize_t i, len; + char *msg; + PyObject *freelist = NULL; + int compat = flags & FLAG_COMPAT; + + assert(compat || (args != (PyObject*)NULL)); + flags = flags & ~FLAG_COMPAT; + + while (endfmt == 0) { + int c = *format++; + switch (c) { + case '(': + if (level == 0) + max++; + level++; + if (level >= 30) + Py_FatalError("too many tuple nesting levels " + "in argument format string"); + break; + case ')': + if (level == 0) + Py_FatalError("excess ')' in getargs format"); + else + level--; + break; + case '\0': + endfmt = 1; + break; + case ':': + fname = format; + endfmt = 1; + break; + case ';': + message = format; + endfmt = 1; + break; + default: + if (level == 0) { + if (c == 'O') + max++; + else if (isalpha(Py_CHARMASK(c))) { + if (c != 'e') /* skip encoded */ + max++; + } else if (c == '|') + min = max; + } + break; + } + } + + if (level != 0) + Py_FatalError(/* '(' */ "missing ')' in getargs format"); + + if (min < 0) + min = max; + + format = formatsave; + + if (compat) { + if (max == 0) { + if (args == NULL) + return 1; + PyOS_snprintf(msgbuf, sizeof(msgbuf), + "%.200s%s takes no arguments", + fname==NULL ? "function" : fname, + fname==NULL ? "" : "()"); + PyErr_SetString(PyExc_TypeError, msgbuf); + return 0; + } + else if (min == 1 && max == 1) { + if (args == NULL) { + PyOS_snprintf(msgbuf, sizeof(msgbuf), + "%.200s%s takes at least one argument", + fname==NULL ? "function" : fname, + fname==NULL ? "" : "()"); + PyErr_SetString(PyExc_TypeError, msgbuf); + return 0; + } + msg = convertitem(args, &format, p_va, flags, levels, + msgbuf, sizeof(msgbuf), &freelist); + if (msg == NULL) + return cleanreturn(1, freelist); + seterror(levels[0], msg, levels+1, fname, message); + return cleanreturn(0, freelist); + } + else { + PyErr_SetString(PyExc_SystemError, + "old style getargs format uses new features"); + return 0; + } + } + + if (!PyTuple_Check(args)) { + PyErr_SetString(PyExc_SystemError, + "new style getargs format but argument is not a tuple"); + return 0; + } + + len = PyTuple_GET_SIZE(args); + + if (len < min || max < len) { + if (message == NULL) { + PyOS_snprintf(msgbuf, sizeof(msgbuf), + "%.150s%s takes %s %d argument%s " + "(%ld given)", + fname==NULL ? "function" : fname, + fname==NULL ? "" : "()", + min==max ? "exactly" + : len < min ? "at least" : "at most", + len < min ? min : max, + (len < min ? min : max) == 1 ? "" : "s", + Py_SAFE_DOWNCAST(len, Py_ssize_t, long)); + message = msgbuf; + } + PyErr_SetString(PyExc_TypeError, message); + return 0; + } + + for (i = 0; i < len; i++) { + if (*format == '|') + format++; + msg = convertitem(PyTuple_GET_ITEM(args, i), &format, p_va, + flags, levels, msgbuf, + sizeof(msgbuf), &freelist); + if (msg) { + seterror(i+1, msg, levels, fname, msg); + return cleanreturn(0, freelist); + } + } + + if (*format != '\0' && !isalpha(Py_CHARMASK(*format)) && + *format != '(' && + *format != '|' && *format != ':' && *format != ';') { + PyErr_Format(PyExc_SystemError, + "bad format string: %.200s", formatsave); + return cleanreturn(0, freelist); + } - return cleanreturn(1, freelist); + return cleanreturn(1, freelist); } @@ -409,37 +409,37 @@ seterror(int iarg, const char *msg, int *levels, const char *fname, const char *message) { - char buf[512]; - int i; - char *p = buf; - - if (PyErr_Occurred()) - return; - else if (message == NULL) { - if (fname != NULL) { - PyOS_snprintf(p, sizeof(buf), "%.200s() ", fname); - p += strlen(p); - } - if (iarg != 0) { - PyOS_snprintf(p, sizeof(buf) - (p - buf), - "argument %d", iarg); - i = 0; - p += strlen(p); - while (levels[i] > 0 && i < 32 && (int)(p-buf) < 220) { - PyOS_snprintf(p, sizeof(buf) - (p - buf), - ", item %d", levels[i]-1); - p += strlen(p); - i++; - } - } - else { - PyOS_snprintf(p, sizeof(buf) - (p - buf), "argument"); - p += strlen(p); - } - PyOS_snprintf(p, sizeof(buf) - (p - buf), " %.256s", msg); - message = buf; - } - PyErr_SetString(PyExc_TypeError, message); + char buf[512]; + int i; + char *p = buf; + + if (PyErr_Occurred()) + return; + else if (message == NULL) { + if (fname != NULL) { + PyOS_snprintf(p, sizeof(buf), "%.200s() ", fname); + p += strlen(p); + } + if (iarg != 0) { + PyOS_snprintf(p, sizeof(buf) - (p - buf), + "argument %d", iarg); + i = 0; + p += strlen(p); + while (levels[i] > 0 && i < 32 && (int)(p-buf) < 220) { + PyOS_snprintf(p, sizeof(buf) - (p - buf), + ", item %d", levels[i]-1); + p += strlen(p); + i++; + } + } + else { + PyOS_snprintf(p, sizeof(buf) - (p - buf), "argument"); + p += strlen(p); + } + PyOS_snprintf(p, sizeof(buf) - (p - buf), " %.256s", msg); + message = buf; + } + PyErr_SetString(PyExc_TypeError, message); } @@ -455,9 +455,9 @@ *p_va is undefined, *levels is a 0-terminated list of item numbers, *msgbuf contains an error message, whose format is: - "must be , not ", where: - is the name of the expected type, and - is the name of the actual type, + "must be , not ", where: + is the name of the expected type, and + is the name of the actual type, and msgbuf is returned. */ @@ -466,72 +466,72 @@ int *levels, char *msgbuf, size_t bufsize, int toplevel, PyObject **freelist) { - int level = 0; - int n = 0; - const char *format = *p_format; - int i; - - for (;;) { - int c = *format++; - if (c == '(') { - if (level == 0) - n++; - level++; - } - else if (c == ')') { - if (level == 0) - break; - level--; - } - else if (c == ':' || c == ';' || c == '\0') - break; - else if (level == 0 && isalpha(Py_CHARMASK(c))) - n++; - } - - if (!PySequence_Check(arg) || PyBytes_Check(arg)) { - levels[0] = 0; - PyOS_snprintf(msgbuf, bufsize, - toplevel ? "expected %d arguments, not %.50s" : - "must be %d-item sequence, not %.50s", - n, - arg == Py_None ? "None" : arg->ob_type->tp_name); - return msgbuf; - } - - if ((i = PySequence_Size(arg)) != n) { - levels[0] = 0; - PyOS_snprintf(msgbuf, bufsize, - toplevel ? "expected %d arguments, not %d" : - "must be sequence of length %d, not %d", - n, i); - return msgbuf; - } - - format = *p_format; - for (i = 0; i < n; i++) { - char *msg; - PyObject *item; - item = PySequence_GetItem(arg, i); - if (item == NULL) { - PyErr_Clear(); - levels[0] = i+1; - levels[1] = 0; - strncpy(msgbuf, "is not retrievable", bufsize); - return msgbuf; - } - msg = convertitem(item, &format, p_va, flags, levels+1, - msgbuf, bufsize, freelist); - /* PySequence_GetItem calls tp->sq_item, which INCREFs */ - Py_XDECREF(item); - if (msg != NULL) { - levels[0] = i+1; - return msg; - } - } + int level = 0; + int n = 0; + const char *format = *p_format; + int i; + + for (;;) { + int c = *format++; + if (c == '(') { + if (level == 0) + n++; + level++; + } + else if (c == ')') { + if (level == 0) + break; + level--; + } + else if (c == ':' || c == ';' || c == '\0') + break; + else if (level == 0 && isalpha(Py_CHARMASK(c))) + n++; + } + + if (!PySequence_Check(arg) || PyBytes_Check(arg)) { + levels[0] = 0; + PyOS_snprintf(msgbuf, bufsize, + toplevel ? "expected %d arguments, not %.50s" : + "must be %d-item sequence, not %.50s", + n, + arg == Py_None ? "None" : arg->ob_type->tp_name); + return msgbuf; + } + + if ((i = PySequence_Size(arg)) != n) { + levels[0] = 0; + PyOS_snprintf(msgbuf, bufsize, + toplevel ? "expected %d arguments, not %d" : + "must be sequence of length %d, not %d", + n, i); + return msgbuf; + } + + format = *p_format; + for (i = 0; i < n; i++) { + char *msg; + PyObject *item; + item = PySequence_GetItem(arg, i); + if (item == NULL) { + PyErr_Clear(); + levels[0] = i+1; + levels[1] = 0; + strncpy(msgbuf, "is not retrievable", bufsize); + return msgbuf; + } + msg = convertitem(item, &format, p_va, flags, levels+1, + msgbuf, bufsize, freelist); + /* PySequence_GetItem calls tp->sq_item, which INCREFs */ + Py_XDECREF(item); + if (msg != NULL) { + levels[0] = i+1; + return msg; + } + } - *p_format = format; - return NULL; + *p_format = format; + return NULL; } @@ -541,43 +541,43 @@ convertitem(PyObject *arg, const char **p_format, va_list *p_va, int flags, int *levels, char *msgbuf, size_t bufsize, PyObject **freelist) { - char *msg; - const char *format = *p_format; + char *msg; + const char *format = *p_format; - if (*format == '(' /* ')' */) { - format++; - msg = converttuple(arg, &format, p_va, flags, levels, msgbuf, - bufsize, 0, freelist); - if (msg == NULL) - format++; - } - else { - msg = convertsimple(arg, &format, p_va, flags, - msgbuf, bufsize, freelist); - if (msg != NULL) - levels[0] = 0; - } - if (msg == NULL) - *p_format = format; - return msg; + if (*format == '(' /* ')' */) { + format++; + msg = converttuple(arg, &format, p_va, flags, levels, msgbuf, + bufsize, 0, freelist); + if (msg == NULL) + format++; + } + else { + msg = convertsimple(arg, &format, p_va, flags, + msgbuf, bufsize, freelist); + if (msg != NULL) + levels[0] = 0; + } + if (msg == NULL) + *p_format = format; + return msg; } #define UNICODE_DEFAULT_ENCODING(arg) \ - _PyUnicode_AsDefaultEncodedString(arg, NULL) + _PyUnicode_AsDefaultEncodedString(arg, NULL) /* Format an error message generated by convertsimple(). */ static char * converterr(const char *expected, PyObject *arg, char *msgbuf, size_t bufsize) { - assert(expected != NULL); - assert(arg != NULL); - PyOS_snprintf(msgbuf, bufsize, - "must be %.50s, not %.50s", expected, - arg == Py_None ? "None" : arg->ob_type->tp_name); - return msgbuf; + assert(expected != NULL); + assert(arg != NULL); + PyOS_snprintf(msgbuf, bufsize, + "must be %.50s, not %.50s", expected, + arg == Py_None ? "None" : arg->ob_type->tp_name); + return msgbuf; } #define CONV_UNICODE "(unicode conversion error)" @@ -587,12 +587,12 @@ static int float_argument_warning(PyObject *arg) { - if (PyFloat_Check(arg) && - PyErr_Warn(PyExc_DeprecationWarning, - "integer argument expected, got float" )) - return 1; - else - return 0; + if (PyFloat_Check(arg) && + PyErr_Warn(PyExc_DeprecationWarning, + "integer argument expected, got float" )) + return 1; + else + return 0; } /* Explicitly check for float arguments when integers are expected. @@ -600,13 +600,13 @@ static int float_argument_error(PyObject *arg) { - if (PyFloat_Check(arg)) { - PyErr_SetString(PyExc_TypeError, - "integer argument expected, got float" ); - return 1; - } - else - return 0; + if (PyFloat_Check(arg)) { + PyErr_SetString(PyExc_TypeError, + "integer argument expected, got float" ); + return 1; + } + else + return 0; } /* Convert a non-tuple argument. Return NULL if conversion went OK, @@ -622,837 +622,837 @@ convertsimple(PyObject *arg, const char **p_format, va_list *p_va, int flags, char *msgbuf, size_t bufsize, PyObject **freelist) { - /* For # codes */ -#define FETCH_SIZE int *q=NULL;Py_ssize_t *q2=NULL;\ - if (flags & FLAG_SIZE_T) q2=va_arg(*p_va, Py_ssize_t*); \ - else q=va_arg(*p_va, int*); + /* For # codes */ +#define FETCH_SIZE int *q=NULL;Py_ssize_t *q2=NULL;\ + if (flags & FLAG_SIZE_T) q2=va_arg(*p_va, Py_ssize_t*); \ + else q=va_arg(*p_va, int*); #define STORE_SIZE(s) if (flags & FLAG_SIZE_T) *q2=s; else *q=s; #define BUFFER_LEN ((flags & FLAG_SIZE_T) ? *q2:*q) - const char *format = *p_format; - char c = *format++; - PyObject *uarg; - - switch (c) { - - case 'b': { /* unsigned byte -- very short int */ - char *p = va_arg(*p_va, char *); - long ival; - if (float_argument_error(arg)) - return converterr("integer", arg, msgbuf, bufsize); - ival = PyLong_AsLong(arg); - if (ival == -1 && PyErr_Occurred()) - return converterr("integer", arg, msgbuf, bufsize); - else if (ival < 0) { - PyErr_SetString(PyExc_OverflowError, - "unsigned byte integer is less than minimum"); - return converterr("integer", arg, msgbuf, bufsize); - } - else if (ival > UCHAR_MAX) { - PyErr_SetString(PyExc_OverflowError, - "unsigned byte integer is greater than maximum"); - return converterr("integer", arg, msgbuf, bufsize); - } - else - *p = (unsigned char) ival; - break; - } - - case 'B': {/* byte sized bitfield - both signed and unsigned - values allowed */ - char *p = va_arg(*p_va, char *); - long ival; - if (float_argument_error(arg)) - return converterr("integer", arg, msgbuf, bufsize); - ival = PyLong_AsUnsignedLongMask(arg); - if (ival == -1 && PyErr_Occurred()) - return converterr("integer", arg, msgbuf, bufsize); - else - *p = (unsigned char) ival; - break; - } - - case 'h': {/* signed short int */ - short *p = va_arg(*p_va, short *); - long ival; - if (float_argument_error(arg)) - return converterr("integer", arg, msgbuf, bufsize); - ival = PyLong_AsLong(arg); - if (ival == -1 && PyErr_Occurred()) - return converterr("integer", arg, msgbuf, bufsize); - else if (ival < SHRT_MIN) { - PyErr_SetString(PyExc_OverflowError, - "signed short integer is less than minimum"); - return converterr("integer", arg, msgbuf, bufsize); - } - else if (ival > SHRT_MAX) { - PyErr_SetString(PyExc_OverflowError, - "signed short integer is greater than maximum"); - return converterr("integer", arg, msgbuf, bufsize); - } - else - *p = (short) ival; - break; - } - - case 'H': { /* short int sized bitfield, both signed and - unsigned allowed */ - unsigned short *p = va_arg(*p_va, unsigned short *); - long ival; - if (float_argument_error(arg)) - return converterr("integer", arg, msgbuf, bufsize); - ival = PyLong_AsUnsignedLongMask(arg); - if (ival == -1 && PyErr_Occurred()) - return converterr("integer", arg, msgbuf, bufsize); - else - *p = (unsigned short) ival; - break; - } - - case 'i': {/* signed int */ - int *p = va_arg(*p_va, int *); - long ival; - if (float_argument_error(arg)) - return converterr("integer", arg, msgbuf, bufsize); - ival = PyLong_AsLong(arg); - if (ival == -1 && PyErr_Occurred()) - return converterr("integer", arg, msgbuf, bufsize); - else if (ival > INT_MAX) { - PyErr_SetString(PyExc_OverflowError, - "signed integer is greater than maximum"); - return converterr("integer", arg, msgbuf, bufsize); - } - else if (ival < INT_MIN) { - PyErr_SetString(PyExc_OverflowError, - "signed integer is less than minimum"); - return converterr("integer", arg, msgbuf, bufsize); - } - else - *p = ival; - break; - } - - case 'I': { /* int sized bitfield, both signed and - unsigned allowed */ - unsigned int *p = va_arg(*p_va, unsigned int *); - unsigned int ival; - if (float_argument_error(arg)) - return converterr("integer", arg, msgbuf, bufsize); - ival = (unsigned int)PyLong_AsUnsignedLongMask(arg); - if (ival == (unsigned int)-1 && PyErr_Occurred()) - return converterr("integer", arg, msgbuf, bufsize); - else - *p = ival; - break; - } - - case 'n': /* Py_ssize_t */ - { - PyObject *iobj; - Py_ssize_t *p = va_arg(*p_va, Py_ssize_t *); - Py_ssize_t ival = -1; - if (float_argument_error(arg)) - return converterr("integer", arg, msgbuf, bufsize); - iobj = PyNumber_Index(arg); - if (iobj != NULL) { - ival = PyLong_AsSsize_t(iobj); - Py_DECREF(iobj); - } - if (ival == -1 && PyErr_Occurred()) - return converterr("integer", arg, msgbuf, bufsize); - *p = ival; - break; - } - case 'l': {/* long int */ - long *p = va_arg(*p_va, long *); - long ival; - if (float_argument_error(arg)) - return converterr("integer", arg, msgbuf, bufsize); - ival = PyLong_AsLong(arg); - if (ival == -1 && PyErr_Occurred()) - return converterr("integer", arg, msgbuf, bufsize); - else - *p = ival; - break; - } - - case 'k': { /* long sized bitfield */ - unsigned long *p = va_arg(*p_va, unsigned long *); - unsigned long ival; - if (PyLong_Check(arg)) - ival = PyLong_AsUnsignedLongMask(arg); - else - return converterr("integer", arg, msgbuf, bufsize); - *p = ival; - break; - } + const char *format = *p_format; + char c = *format++; + PyObject *uarg; + + switch (c) { + + case 'b': { /* unsigned byte -- very short int */ + char *p = va_arg(*p_va, char *); + long ival; + if (float_argument_error(arg)) + return converterr("integer", arg, msgbuf, bufsize); + ival = PyLong_AsLong(arg); + if (ival == -1 && PyErr_Occurred()) + return converterr("integer", arg, msgbuf, bufsize); + else if (ival < 0) { + PyErr_SetString(PyExc_OverflowError, + "unsigned byte integer is less than minimum"); + return converterr("integer", arg, msgbuf, bufsize); + } + else if (ival > UCHAR_MAX) { + PyErr_SetString(PyExc_OverflowError, + "unsigned byte integer is greater than maximum"); + return converterr("integer", arg, msgbuf, bufsize); + } + else + *p = (unsigned char) ival; + break; + } + + case 'B': {/* byte sized bitfield - both signed and unsigned + values allowed */ + char *p = va_arg(*p_va, char *); + long ival; + if (float_argument_error(arg)) + return converterr("integer", arg, msgbuf, bufsize); + ival = PyLong_AsUnsignedLongMask(arg); + if (ival == -1 && PyErr_Occurred()) + return converterr("integer", arg, msgbuf, bufsize); + else + *p = (unsigned char) ival; + break; + } + + case 'h': {/* signed short int */ + short *p = va_arg(*p_va, short *); + long ival; + if (float_argument_error(arg)) + return converterr("integer", arg, msgbuf, bufsize); + ival = PyLong_AsLong(arg); + if (ival == -1 && PyErr_Occurred()) + return converterr("integer", arg, msgbuf, bufsize); + else if (ival < SHRT_MIN) { + PyErr_SetString(PyExc_OverflowError, + "signed short integer is less than minimum"); + return converterr("integer", arg, msgbuf, bufsize); + } + else if (ival > SHRT_MAX) { + PyErr_SetString(PyExc_OverflowError, + "signed short integer is greater than maximum"); + return converterr("integer", arg, msgbuf, bufsize); + } + else + *p = (short) ival; + break; + } + + case 'H': { /* short int sized bitfield, both signed and + unsigned allowed */ + unsigned short *p = va_arg(*p_va, unsigned short *); + long ival; + if (float_argument_error(arg)) + return converterr("integer", arg, msgbuf, bufsize); + ival = PyLong_AsUnsignedLongMask(arg); + if (ival == -1 && PyErr_Occurred()) + return converterr("integer", arg, msgbuf, bufsize); + else + *p = (unsigned short) ival; + break; + } + + case 'i': {/* signed int */ + int *p = va_arg(*p_va, int *); + long ival; + if (float_argument_error(arg)) + return converterr("integer", arg, msgbuf, bufsize); + ival = PyLong_AsLong(arg); + if (ival == -1 && PyErr_Occurred()) + return converterr("integer", arg, msgbuf, bufsize); + else if (ival > INT_MAX) { + PyErr_SetString(PyExc_OverflowError, + "signed integer is greater than maximum"); + return converterr("integer", arg, msgbuf, bufsize); + } + else if (ival < INT_MIN) { + PyErr_SetString(PyExc_OverflowError, + "signed integer is less than minimum"); + return converterr("integer", arg, msgbuf, bufsize); + } + else + *p = ival; + break; + } + + case 'I': { /* int sized bitfield, both signed and + unsigned allowed */ + unsigned int *p = va_arg(*p_va, unsigned int *); + unsigned int ival; + if (float_argument_error(arg)) + return converterr("integer", arg, msgbuf, bufsize); + ival = (unsigned int)PyLong_AsUnsignedLongMask(arg); + if (ival == (unsigned int)-1 && PyErr_Occurred()) + return converterr("integer", arg, msgbuf, bufsize); + else + *p = ival; + break; + } + + case 'n': /* Py_ssize_t */ + { + PyObject *iobj; + Py_ssize_t *p = va_arg(*p_va, Py_ssize_t *); + Py_ssize_t ival = -1; + if (float_argument_error(arg)) + return converterr("integer", arg, msgbuf, bufsize); + iobj = PyNumber_Index(arg); + if (iobj != NULL) { + ival = PyLong_AsSsize_t(iobj); + Py_DECREF(iobj); + } + if (ival == -1 && PyErr_Occurred()) + return converterr("integer", arg, msgbuf, bufsize); + *p = ival; + break; + } + case 'l': {/* long int */ + long *p = va_arg(*p_va, long *); + long ival; + if (float_argument_error(arg)) + return converterr("integer", arg, msgbuf, bufsize); + ival = PyLong_AsLong(arg); + if (ival == -1 && PyErr_Occurred()) + return converterr("integer", arg, msgbuf, bufsize); + else + *p = ival; + break; + } + + case 'k': { /* long sized bitfield */ + unsigned long *p = va_arg(*p_va, unsigned long *); + unsigned long ival; + if (PyLong_Check(arg)) + ival = PyLong_AsUnsignedLongMask(arg); + else + return converterr("integer", arg, msgbuf, bufsize); + *p = ival; + break; + } #ifdef HAVE_LONG_LONG - case 'L': {/* PY_LONG_LONG */ - PY_LONG_LONG *p = va_arg( *p_va, PY_LONG_LONG * ); - PY_LONG_LONG ival; - if (float_argument_warning(arg)) - return converterr("long", arg, msgbuf, bufsize); - ival = PyLong_AsLongLong(arg); - if (ival == (PY_LONG_LONG)-1 && PyErr_Occurred() ) { - return converterr("long", arg, msgbuf, bufsize); - } else { - *p = ival; - } - break; - } - - case 'K': { /* long long sized bitfield */ - unsigned PY_LONG_LONG *p = va_arg(*p_va, unsigned PY_LONG_LONG *); - unsigned PY_LONG_LONG ival; - if (PyLong_Check(arg)) - ival = PyLong_AsUnsignedLongLongMask(arg); - else - return converterr("integer", arg, msgbuf, bufsize); - *p = ival; - break; - } + case 'L': {/* PY_LONG_LONG */ + PY_LONG_LONG *p = va_arg( *p_va, PY_LONG_LONG * ); + PY_LONG_LONG ival; + if (float_argument_warning(arg)) + return converterr("long", arg, msgbuf, bufsize); + ival = PyLong_AsLongLong(arg); + if (ival == (PY_LONG_LONG)-1 && PyErr_Occurred() ) { + return converterr("long", arg, msgbuf, bufsize); + } else { + *p = ival; + } + break; + } + + case 'K': { /* long long sized bitfield */ + unsigned PY_LONG_LONG *p = va_arg(*p_va, unsigned PY_LONG_LONG *); + unsigned PY_LONG_LONG ival; + if (PyLong_Check(arg)) + ival = PyLong_AsUnsignedLongLongMask(arg); + else + return converterr("integer", arg, msgbuf, bufsize); + *p = ival; + break; + } #endif - case 'f': {/* float */ - float *p = va_arg(*p_va, float *); - double dval = PyFloat_AsDouble(arg); - if (PyErr_Occurred()) - return converterr("float", arg, msgbuf, bufsize); - else - *p = (float) dval; - break; - } - - case 'd': {/* double */ - double *p = va_arg(*p_va, double *); - double dval = PyFloat_AsDouble(arg); - if (PyErr_Occurred()) - return converterr("float", arg, msgbuf, bufsize); - else - *p = dval; - break; - } - - case 'D': {/* complex double */ - Py_complex *p = va_arg(*p_va, Py_complex *); - Py_complex cval; - cval = PyComplex_AsCComplex(arg); - if (PyErr_Occurred()) - return converterr("complex", arg, msgbuf, bufsize); - else - *p = cval; - break; - } - - case 'c': {/* char */ - char *p = va_arg(*p_va, char *); - if (PyBytes_Check(arg) && PyBytes_Size(arg) == 1) - *p = PyBytes_AS_STRING(arg)[0]; - else - return converterr("a byte string of length 1", arg, msgbuf, bufsize); - break; - } - - case 'C': {/* unicode char */ - int *p = va_arg(*p_va, int *); - if (PyUnicode_Check(arg) && - PyUnicode_GET_SIZE(arg) == 1) - *p = PyUnicode_AS_UNICODE(arg)[0]; - else - return converterr("a unicode character", arg, msgbuf, bufsize); - break; - } - - /* XXX WAAAAH! 's', 'y', 'z', 'u', 'Z', 'e', 'w', 't' codes all - need to be cleaned up! */ - - case 's': {/* text string */ - if (*format == '*') { - Py_buffer *p = (Py_buffer *)va_arg(*p_va, Py_buffer *); - - if (PyUnicode_Check(arg)) { - uarg = UNICODE_DEFAULT_ENCODING(arg); - if (uarg == NULL) - return converterr(CONV_UNICODE, - arg, msgbuf, bufsize); - PyBuffer_FillInfo(p, arg, - PyBytes_AS_STRING(uarg), PyBytes_GET_SIZE(uarg), - 1, 0); - } - else { /* any buffer-like object */ - char *buf; - if (getbuffer(arg, p, &buf) < 0) - return converterr(buf, arg, msgbuf, bufsize); - } - if (addcleanup(p, freelist, cleanup_buffer)) { - return converterr( - "(cleanup problem)", - arg, msgbuf, bufsize); - } - format++; - } else if (*format == '#') { - void **p = (void **)va_arg(*p_va, char **); - FETCH_SIZE; - - if (PyUnicode_Check(arg)) { - uarg = UNICODE_DEFAULT_ENCODING(arg); - if (uarg == NULL) - return converterr(CONV_UNICODE, - arg, msgbuf, bufsize); - *p = PyBytes_AS_STRING(uarg); - STORE_SIZE(PyBytes_GET_SIZE(uarg)); - } - else { /* any buffer-like object */ - /* XXX Really? */ - char *buf; - Py_ssize_t count = convertbuffer(arg, p, &buf); - if (count < 0) - return converterr(buf, arg, msgbuf, bufsize); - STORE_SIZE(count); - } - format++; - } else { - char **p = va_arg(*p_va, char **); - - if (PyUnicode_Check(arg)) { - uarg = UNICODE_DEFAULT_ENCODING(arg); - if (uarg == NULL) - return converterr(CONV_UNICODE, - arg, msgbuf, bufsize); - *p = PyBytes_AS_STRING(uarg); - } - else - return converterr("string", arg, msgbuf, bufsize); - if ((Py_ssize_t) strlen(*p) != PyBytes_GET_SIZE(uarg)) - return converterr("string without null bytes", - arg, msgbuf, bufsize); - } - break; - } - - case 'y': {/* any buffer-like object, but not PyUnicode */ - void **p = (void **)va_arg(*p_va, char **); - char *buf; - Py_ssize_t count; - if (*format == '*') { - if (getbuffer(arg, (Py_buffer*)p, &buf) < 0) - return converterr(buf, arg, msgbuf, bufsize); - format++; - if (addcleanup(p, freelist, cleanup_buffer)) { - return converterr( - "(cleanup problem)", - arg, msgbuf, bufsize); - } - break; - } - count = convertbuffer(arg, p, &buf); - if (count < 0) - return converterr(buf, arg, msgbuf, bufsize); - else if (*format == '#') { - FETCH_SIZE; - STORE_SIZE(count); - format++; - } - break; - } - - case 'z': {/* like 's' or 's#', but None is okay, stored as NULL */ - if (*format == '*') { - Py_buffer *p = (Py_buffer *)va_arg(*p_va, Py_buffer *); - - if (arg == Py_None) - PyBuffer_FillInfo(p, NULL, NULL, 0, 1, 0); - else if (PyUnicode_Check(arg)) { - uarg = UNICODE_DEFAULT_ENCODING(arg); - if (uarg == NULL) - return converterr(CONV_UNICODE, - arg, msgbuf, bufsize); - PyBuffer_FillInfo(p, arg, - PyBytes_AS_STRING(uarg), PyBytes_GET_SIZE(uarg), - 1, 0); - } - else { /* any buffer-like object */ - char *buf; - if (getbuffer(arg, p, &buf) < 0) - return converterr(buf, arg, msgbuf, bufsize); - } - if (addcleanup(p, freelist, cleanup_buffer)) { - return converterr( - "(cleanup problem)", - arg, msgbuf, bufsize); - } - format++; - } else if (*format == '#') { /* any buffer-like object */ - void **p = (void **)va_arg(*p_va, char **); - FETCH_SIZE; - - if (arg == Py_None) { - *p = 0; - STORE_SIZE(0); - } - else if (PyUnicode_Check(arg)) { - uarg = UNICODE_DEFAULT_ENCODING(arg); - if (uarg == NULL) - return converterr(CONV_UNICODE, - arg, msgbuf, bufsize); - *p = PyBytes_AS_STRING(uarg); - STORE_SIZE(PyBytes_GET_SIZE(uarg)); - } - else { /* any buffer-like object */ - /* XXX Really? */ - char *buf; - Py_ssize_t count = convertbuffer(arg, p, &buf); - if (count < 0) - return converterr(buf, arg, msgbuf, bufsize); - STORE_SIZE(count); - } - format++; - } else { - char **p = va_arg(*p_va, char **); - uarg = NULL; - - if (arg == Py_None) - *p = 0; - else if (PyBytes_Check(arg)) { - /* Enable null byte check below */ - uarg = arg; - *p = PyBytes_AS_STRING(arg); - } - else if (PyUnicode_Check(arg)) { - uarg = UNICODE_DEFAULT_ENCODING(arg); - if (uarg == NULL) - return converterr(CONV_UNICODE, - arg, msgbuf, bufsize); - *p = PyBytes_AS_STRING(uarg); - } - else - return converterr("string or None", - arg, msgbuf, bufsize); - if (*format == '#') { - FETCH_SIZE; - assert(0); /* XXX redundant with if-case */ - if (arg == Py_None) { - STORE_SIZE(0); - } - else { - STORE_SIZE(PyBytes_Size(arg)); - } - format++; - } - else if (*p != NULL && uarg != NULL && - (Py_ssize_t) strlen(*p) != PyBytes_GET_SIZE(uarg)) - return converterr( - "string without null bytes or None", - arg, msgbuf, bufsize); - } - break; - } - - case 'Z': {/* unicode, may be NULL (None) */ - if (*format == '#') { /* any buffer-like object */ - Py_UNICODE **p = va_arg(*p_va, Py_UNICODE **); - FETCH_SIZE; - - if (arg == Py_None) { - *p = 0; - STORE_SIZE(0); - } - else if (PyUnicode_Check(arg)) { - *p = PyUnicode_AS_UNICODE(arg); - STORE_SIZE(PyUnicode_GET_SIZE(arg)); - } - format++; - } else { - Py_UNICODE **p = va_arg(*p_va, Py_UNICODE **); - - if (arg == Py_None) - *p = 0; - else if (PyUnicode_Check(arg)) - *p = PyUnicode_AS_UNICODE(arg); - else - return converterr("string or None", - arg, msgbuf, bufsize); - } - break; - } - - case 'e': {/* encoded string */ - char **buffer; - const char *encoding; - PyObject *s; - int recode_strings; - Py_ssize_t size; - const char *ptr; - - /* Get 'e' parameter: the encoding name */ - encoding = (const char *)va_arg(*p_va, const char *); - if (encoding == NULL) - encoding = PyUnicode_GetDefaultEncoding(); - - /* Get output buffer parameter: - 's' (recode all objects via Unicode) or - 't' (only recode non-string objects) - */ - if (*format == 's') - recode_strings = 1; - else if (*format == 't') - recode_strings = 0; - else - return converterr( - "(unknown parser marker combination)", - arg, msgbuf, bufsize); - buffer = (char **)va_arg(*p_va, char **); - format++; - if (buffer == NULL) - return converterr("(buffer is NULL)", - arg, msgbuf, bufsize); - - /* Encode object */ - if (!recode_strings && - (PyBytes_Check(arg) || PyByteArray_Check(arg))) { - s = arg; - Py_INCREF(s); - if (PyObject_AsCharBuffer(s, &ptr, &size) < 0) - return converterr("(AsCharBuffer failed)", - arg, msgbuf, bufsize); - } - else { - PyObject *u; - - /* Convert object to Unicode */ - u = PyUnicode_FromObject(arg); - if (u == NULL) - return converterr( - "string or unicode or text buffer", - arg, msgbuf, bufsize); - - /* Encode object; use default error handling */ - s = PyUnicode_AsEncodedString(u, - encoding, - NULL); - Py_DECREF(u); - if (s == NULL) - return converterr("(encoding failed)", - arg, msgbuf, bufsize); - if (!PyBytes_Check(s)) { - Py_DECREF(s); - return converterr( - "(encoder failed to return bytes)", - arg, msgbuf, bufsize); - } - size = PyBytes_GET_SIZE(s); - ptr = PyBytes_AS_STRING(s); - if (ptr == NULL) - ptr = ""; - } - - /* Write output; output is guaranteed to be 0-terminated */ - if (*format == '#') { - /* Using buffer length parameter '#': - - - if *buffer is NULL, a new buffer of the - needed size is allocated and the data - copied into it; *buffer is updated to point - to the new buffer; the caller is - responsible for PyMem_Free()ing it after - usage - - - if *buffer is not NULL, the data is - copied to *buffer; *buffer_len has to be - set to the size of the buffer on input; - buffer overflow is signalled with an error; - buffer has to provide enough room for the - encoded string plus the trailing 0-byte - - - in both cases, *buffer_len is updated to - the size of the buffer /excluding/ the - trailing 0-byte - - */ - FETCH_SIZE; - - format++; - if (q == NULL && q2 == NULL) { - Py_DECREF(s); - return converterr( - "(buffer_len is NULL)", - arg, msgbuf, bufsize); - } - if (*buffer == NULL) { - *buffer = PyMem_NEW(char, size + 1); - if (*buffer == NULL) { - Py_DECREF(s); - return converterr( - "(memory error)", - arg, msgbuf, bufsize); - } - if (addcleanup(*buffer, freelist, cleanup_ptr)) { - Py_DECREF(s); - return converterr( - "(cleanup problem)", - arg, msgbuf, bufsize); - } - } else { - if (size + 1 > BUFFER_LEN) { - Py_DECREF(s); - return converterr( - "(buffer overflow)", - arg, msgbuf, bufsize); - } - } - memcpy(*buffer, ptr, size+1); - STORE_SIZE(size); - } else { - /* Using a 0-terminated buffer: - - - the encoded string has to be 0-terminated - for this variant to work; if it is not, an - error raised - - - a new buffer of the needed size is - allocated and the data copied into it; - *buffer is updated to point to the new - buffer; the caller is responsible for - PyMem_Free()ing it after usage - - */ - if ((Py_ssize_t)strlen(ptr) != size) { - Py_DECREF(s); - return converterr( - "encoded string without NULL bytes", - arg, msgbuf, bufsize); - } - *buffer = PyMem_NEW(char, size + 1); - if (*buffer == NULL) { - Py_DECREF(s); - return converterr("(memory error)", - arg, msgbuf, bufsize); - } - if (addcleanup(*buffer, freelist, cleanup_ptr)) { - Py_DECREF(s); - return converterr("(cleanup problem)", - arg, msgbuf, bufsize); - } - memcpy(*buffer, ptr, size+1); - } - Py_DECREF(s); - break; - } - - case 'u': {/* raw unicode buffer (Py_UNICODE *) */ - Py_UNICODE **p = va_arg(*p_va, Py_UNICODE **); - if (!PyUnicode_Check(arg)) - return converterr("str", arg, msgbuf, bufsize); - *p = PyUnicode_AS_UNICODE(arg); - if (*format == '#') { /* store pointer and size */ - FETCH_SIZE; - STORE_SIZE(PyUnicode_GET_SIZE(arg)); - format++; - } - break; - } - - case 'S': { /* PyBytes object */ - PyObject **p = va_arg(*p_va, PyObject **); - if (PyBytes_Check(arg)) - *p = arg; - else - return converterr("bytes", arg, msgbuf, bufsize); - break; - } - - case 'Y': { /* PyByteArray object */ - PyObject **p = va_arg(*p_va, PyObject **); - if (PyByteArray_Check(arg)) - *p = arg; - else - return converterr("buffer", arg, msgbuf, bufsize); - break; - } - - case 'U': { /* PyUnicode object */ - PyObject **p = va_arg(*p_va, PyObject **); - if (PyUnicode_Check(arg)) - *p = arg; - else - return converterr("str", arg, msgbuf, bufsize); - break; - } - - case 'O': { /* object */ - PyTypeObject *type; - PyObject **p; - if (*format == '!') { - type = va_arg(*p_va, PyTypeObject*); - p = va_arg(*p_va, PyObject **); - format++; - if (PyType_IsSubtype(arg->ob_type, type)) - *p = arg; - else - return converterr(type->tp_name, arg, msgbuf, bufsize); - - } - else if (*format == '?') { - inquiry pred = va_arg(*p_va, inquiry); - p = va_arg(*p_va, PyObject **); - format++; - if ((*pred)(arg)) - *p = arg; - else - return converterr("(unspecified)", - arg, msgbuf, bufsize); - - } - else if (*format == '&') { - typedef int (*converter)(PyObject *, void *); - converter convert = va_arg(*p_va, converter); - void *addr = va_arg(*p_va, void *); - int res; - format++; - if (! (res = (*convert)(arg, addr))) - return converterr("(unspecified)", - arg, msgbuf, bufsize); - if (res == Py_CLEANUP_SUPPORTED && - addcleanup_convert(addr, freelist, convert) == -1) - return converterr("(cleanup problem)", - arg, msgbuf, bufsize); - } - else { - p = va_arg(*p_va, PyObject **); - *p = arg; - } - break; - } - - - case 'w': { /* memory buffer, read-write access */ - void **p = va_arg(*p_va, void **); - PyBufferProcs *pb = arg->ob_type->tp_as_buffer; - Py_ssize_t count; - int temp=-1; - Py_buffer view; - - if (pb && pb->bf_releasebuffer && *format != '*') - /* Buffer must be released, yet caller does not use - the Py_buffer protocol. */ - return converterr("pinned buffer", arg, msgbuf, bufsize); - - - if (pb && pb->bf_getbuffer && *format == '*') { - /* Caller is interested in Py_buffer, and the object - supports it directly. */ - format++; - if (PyObject_GetBuffer(arg, (Py_buffer*)p, PyBUF_WRITABLE) < 0) { - PyErr_Clear(); - return converterr("read-write buffer", arg, msgbuf, bufsize); - } - if (addcleanup(p, freelist, cleanup_buffer)) { - return converterr( - "(cleanup problem)", - arg, msgbuf, bufsize); - } - if (!PyBuffer_IsContiguous((Py_buffer*)p, 'C')) - return converterr("contiguous buffer", arg, msgbuf, bufsize); - break; - } - - /* Here we have processed w*, only w and w# remain. */ - if (pb == NULL || - pb->bf_getbuffer == NULL || - ((temp = PyObject_GetBuffer(arg, &view, - PyBUF_SIMPLE)) != 0) || - view.readonly == 1) { - if (temp==0) { - PyBuffer_Release(&view); - } - return converterr("single-segment read-write buffer", - arg, msgbuf, bufsize); + case 'f': {/* float */ + float *p = va_arg(*p_va, float *); + double dval = PyFloat_AsDouble(arg); + if (PyErr_Occurred()) + return converterr("float", arg, msgbuf, bufsize); + else + *p = (float) dval; + break; + } + + case 'd': {/* double */ + double *p = va_arg(*p_va, double *); + double dval = PyFloat_AsDouble(arg); + if (PyErr_Occurred()) + return converterr("float", arg, msgbuf, bufsize); + else + *p = dval; + break; + } + + case 'D': {/* complex double */ + Py_complex *p = va_arg(*p_va, Py_complex *); + Py_complex cval; + cval = PyComplex_AsCComplex(arg); + if (PyErr_Occurred()) + return converterr("complex", arg, msgbuf, bufsize); + else + *p = cval; + break; + } + + case 'c': {/* char */ + char *p = va_arg(*p_va, char *); + if (PyBytes_Check(arg) && PyBytes_Size(arg) == 1) + *p = PyBytes_AS_STRING(arg)[0]; + else + return converterr("a byte string of length 1", arg, msgbuf, bufsize); + break; + } + + case 'C': {/* unicode char */ + int *p = va_arg(*p_va, int *); + if (PyUnicode_Check(arg) && + PyUnicode_GET_SIZE(arg) == 1) + *p = PyUnicode_AS_UNICODE(arg)[0]; + else + return converterr("a unicode character", arg, msgbuf, bufsize); + break; + } + + /* XXX WAAAAH! 's', 'y', 'z', 'u', 'Z', 'e', 'w', 't' codes all + need to be cleaned up! */ + + case 's': {/* text string */ + if (*format == '*') { + Py_buffer *p = (Py_buffer *)va_arg(*p_va, Py_buffer *); + + if (PyUnicode_Check(arg)) { + uarg = UNICODE_DEFAULT_ENCODING(arg); + if (uarg == NULL) + return converterr(CONV_UNICODE, + arg, msgbuf, bufsize); + PyBuffer_FillInfo(p, arg, + PyBytes_AS_STRING(uarg), PyBytes_GET_SIZE(uarg), + 1, 0); + } + else { /* any buffer-like object */ + char *buf; + if (getbuffer(arg, p, &buf) < 0) + return converterr(buf, arg, msgbuf, bufsize); + } + if (addcleanup(p, freelist, cleanup_buffer)) { + return converterr( + "(cleanup problem)", + arg, msgbuf, bufsize); + } + format++; + } else if (*format == '#') { + void **p = (void **)va_arg(*p_va, char **); + FETCH_SIZE; + + if (PyUnicode_Check(arg)) { + uarg = UNICODE_DEFAULT_ENCODING(arg); + if (uarg == NULL) + return converterr(CONV_UNICODE, + arg, msgbuf, bufsize); + *p = PyBytes_AS_STRING(uarg); + STORE_SIZE(PyBytes_GET_SIZE(uarg)); + } + else { /* any buffer-like object */ + /* XXX Really? */ + char *buf; + Py_ssize_t count = convertbuffer(arg, p, &buf); + if (count < 0) + return converterr(buf, arg, msgbuf, bufsize); + STORE_SIZE(count); + } + format++; + } else { + char **p = va_arg(*p_va, char **); + + if (PyUnicode_Check(arg)) { + uarg = UNICODE_DEFAULT_ENCODING(arg); + if (uarg == NULL) + return converterr(CONV_UNICODE, + arg, msgbuf, bufsize); + *p = PyBytes_AS_STRING(uarg); + } + else + return converterr("string", arg, msgbuf, bufsize); + if ((Py_ssize_t) strlen(*p) != PyBytes_GET_SIZE(uarg)) + return converterr("string without null bytes", + arg, msgbuf, bufsize); + } + break; + } + + case 'y': {/* any buffer-like object, but not PyUnicode */ + void **p = (void **)va_arg(*p_va, char **); + char *buf; + Py_ssize_t count; + if (*format == '*') { + if (getbuffer(arg, (Py_buffer*)p, &buf) < 0) + return converterr(buf, arg, msgbuf, bufsize); + format++; + if (addcleanup(p, freelist, cleanup_buffer)) { + return converterr( + "(cleanup problem)", + arg, msgbuf, bufsize); + } + break; + } + count = convertbuffer(arg, p, &buf); + if (count < 0) + return converterr(buf, arg, msgbuf, bufsize); + else if (*format == '#') { + FETCH_SIZE; + STORE_SIZE(count); + format++; + } + break; + } + + case 'z': {/* like 's' or 's#', but None is okay, stored as NULL */ + if (*format == '*') { + Py_buffer *p = (Py_buffer *)va_arg(*p_va, Py_buffer *); + + if (arg == Py_None) + PyBuffer_FillInfo(p, NULL, NULL, 0, 1, 0); + else if (PyUnicode_Check(arg)) { + uarg = UNICODE_DEFAULT_ENCODING(arg); + if (uarg == NULL) + return converterr(CONV_UNICODE, + arg, msgbuf, bufsize); + PyBuffer_FillInfo(p, arg, + PyBytes_AS_STRING(uarg), PyBytes_GET_SIZE(uarg), + 1, 0); + } + else { /* any buffer-like object */ + char *buf; + if (getbuffer(arg, p, &buf) < 0) + return converterr(buf, arg, msgbuf, bufsize); + } + if (addcleanup(p, freelist, cleanup_buffer)) { + return converterr( + "(cleanup problem)", + arg, msgbuf, bufsize); + } + format++; + } else if (*format == '#') { /* any buffer-like object */ + void **p = (void **)va_arg(*p_va, char **); + FETCH_SIZE; + + if (arg == Py_None) { + *p = 0; + STORE_SIZE(0); + } + else if (PyUnicode_Check(arg)) { + uarg = UNICODE_DEFAULT_ENCODING(arg); + if (uarg == NULL) + return converterr(CONV_UNICODE, + arg, msgbuf, bufsize); + *p = PyBytes_AS_STRING(uarg); + STORE_SIZE(PyBytes_GET_SIZE(uarg)); + } + else { /* any buffer-like object */ + /* XXX Really? */ + char *buf; + Py_ssize_t count = convertbuffer(arg, p, &buf); + if (count < 0) + return converterr(buf, arg, msgbuf, bufsize); + STORE_SIZE(count); + } + format++; + } else { + char **p = va_arg(*p_va, char **); + uarg = NULL; + + if (arg == Py_None) + *p = 0; + else if (PyBytes_Check(arg)) { + /* Enable null byte check below */ + uarg = arg; + *p = PyBytes_AS_STRING(arg); + } + else if (PyUnicode_Check(arg)) { + uarg = UNICODE_DEFAULT_ENCODING(arg); + if (uarg == NULL) + return converterr(CONV_UNICODE, + arg, msgbuf, bufsize); + *p = PyBytes_AS_STRING(uarg); + } + else + return converterr("string or None", + arg, msgbuf, bufsize); + if (*format == '#') { + FETCH_SIZE; + assert(0); /* XXX redundant with if-case */ + if (arg == Py_None) { + STORE_SIZE(0); + } + else { + STORE_SIZE(PyBytes_Size(arg)); + } + format++; + } + else if (*p != NULL && uarg != NULL && + (Py_ssize_t) strlen(*p) != PyBytes_GET_SIZE(uarg)) + return converterr( + "string without null bytes or None", + arg, msgbuf, bufsize); + } + break; + } + + case 'Z': {/* unicode, may be NULL (None) */ + if (*format == '#') { /* any buffer-like object */ + Py_UNICODE **p = va_arg(*p_va, Py_UNICODE **); + FETCH_SIZE; + + if (arg == Py_None) { + *p = 0; + STORE_SIZE(0); + } + else if (PyUnicode_Check(arg)) { + *p = PyUnicode_AS_UNICODE(arg); + STORE_SIZE(PyUnicode_GET_SIZE(arg)); + } + format++; + } else { + Py_UNICODE **p = va_arg(*p_va, Py_UNICODE **); + + if (arg == Py_None) + *p = 0; + else if (PyUnicode_Check(arg)) + *p = PyUnicode_AS_UNICODE(arg); + else + return converterr("string or None", + arg, msgbuf, bufsize); + } + break; + } + + case 'e': {/* encoded string */ + char **buffer; + const char *encoding; + PyObject *s; + int recode_strings; + Py_ssize_t size; + const char *ptr; + + /* Get 'e' parameter: the encoding name */ + encoding = (const char *)va_arg(*p_va, const char *); + if (encoding == NULL) + encoding = PyUnicode_GetDefaultEncoding(); + + /* Get output buffer parameter: + 's' (recode all objects via Unicode) or + 't' (only recode non-string objects) + */ + if (*format == 's') + recode_strings = 1; + else if (*format == 't') + recode_strings = 0; + else + return converterr( + "(unknown parser marker combination)", + arg, msgbuf, bufsize); + buffer = (char **)va_arg(*p_va, char **); + format++; + if (buffer == NULL) + return converterr("(buffer is NULL)", + arg, msgbuf, bufsize); + + /* Encode object */ + if (!recode_strings && + (PyBytes_Check(arg) || PyByteArray_Check(arg))) { + s = arg; + Py_INCREF(s); + if (PyObject_AsCharBuffer(s, &ptr, &size) < 0) + return converterr("(AsCharBuffer failed)", + arg, msgbuf, bufsize); + } + else { + PyObject *u; + + /* Convert object to Unicode */ + u = PyUnicode_FromObject(arg); + if (u == NULL) + return converterr( + "string or unicode or text buffer", + arg, msgbuf, bufsize); + + /* Encode object; use default error handling */ + s = PyUnicode_AsEncodedString(u, + encoding, + NULL); + Py_DECREF(u); + if (s == NULL) + return converterr("(encoding failed)", + arg, msgbuf, bufsize); + if (!PyBytes_Check(s)) { + Py_DECREF(s); + return converterr( + "(encoder failed to return bytes)", + arg, msgbuf, bufsize); + } + size = PyBytes_GET_SIZE(s); + ptr = PyBytes_AS_STRING(s); + if (ptr == NULL) + ptr = ""; + } + + /* Write output; output is guaranteed to be 0-terminated */ + if (*format == '#') { + /* Using buffer length parameter '#': + + - if *buffer is NULL, a new buffer of the + needed size is allocated and the data + copied into it; *buffer is updated to point + to the new buffer; the caller is + responsible for PyMem_Free()ing it after + usage + + - if *buffer is not NULL, the data is + copied to *buffer; *buffer_len has to be + set to the size of the buffer on input; + buffer overflow is signalled with an error; + buffer has to provide enough room for the + encoded string plus the trailing 0-byte + + - in both cases, *buffer_len is updated to + the size of the buffer /excluding/ the + trailing 0-byte + + */ + FETCH_SIZE; + + format++; + if (q == NULL && q2 == NULL) { + Py_DECREF(s); + return converterr( + "(buffer_len is NULL)", + arg, msgbuf, bufsize); + } + if (*buffer == NULL) { + *buffer = PyMem_NEW(char, size + 1); + if (*buffer == NULL) { + Py_DECREF(s); + return converterr( + "(memory error)", + arg, msgbuf, bufsize); + } + if (addcleanup(*buffer, freelist, cleanup_ptr)) { + Py_DECREF(s); + return converterr( + "(cleanup problem)", + arg, msgbuf, bufsize); + } + } else { + if (size + 1 > BUFFER_LEN) { + Py_DECREF(s); + return converterr( + "(buffer overflow)", + arg, msgbuf, bufsize); } + } + memcpy(*buffer, ptr, size+1); + STORE_SIZE(size); + } else { + /* Using a 0-terminated buffer: + + - the encoded string has to be 0-terminated + for this variant to work; if it is not, an + error raised + + - a new buffer of the needed size is + allocated and the data copied into it; + *buffer is updated to point to the new + buffer; the caller is responsible for + PyMem_Free()ing it after usage + + */ + if ((Py_ssize_t)strlen(ptr) != size) { + Py_DECREF(s); + return converterr( + "encoded string without NULL bytes", + arg, msgbuf, bufsize); + } + *buffer = PyMem_NEW(char, size + 1); + if (*buffer == NULL) { + Py_DECREF(s); + return converterr("(memory error)", + arg, msgbuf, bufsize); + } + if (addcleanup(*buffer, freelist, cleanup_ptr)) { + Py_DECREF(s); + return converterr("(cleanup problem)", + arg, msgbuf, bufsize); + } + memcpy(*buffer, ptr, size+1); + } + Py_DECREF(s); + break; + } + + case 'u': {/* raw unicode buffer (Py_UNICODE *) */ + Py_UNICODE **p = va_arg(*p_va, Py_UNICODE **); + if (!PyUnicode_Check(arg)) + return converterr("str", arg, msgbuf, bufsize); + *p = PyUnicode_AS_UNICODE(arg); + if (*format == '#') { /* store pointer and size */ + FETCH_SIZE; + STORE_SIZE(PyUnicode_GET_SIZE(arg)); + format++; + } + break; + } + + case 'S': { /* PyBytes object */ + PyObject **p = va_arg(*p_va, PyObject **); + if (PyBytes_Check(arg)) + *p = arg; + else + return converterr("bytes", arg, msgbuf, bufsize); + break; + } + + case 'Y': { /* PyByteArray object */ + PyObject **p = va_arg(*p_va, PyObject **); + if (PyByteArray_Check(arg)) + *p = arg; + else + return converterr("buffer", arg, msgbuf, bufsize); + break; + } + + case 'U': { /* PyUnicode object */ + PyObject **p = va_arg(*p_va, PyObject **); + if (PyUnicode_Check(arg)) + *p = arg; + else + return converterr("str", arg, msgbuf, bufsize); + break; + } + + case 'O': { /* object */ + PyTypeObject *type; + PyObject **p; + if (*format == '!') { + type = va_arg(*p_va, PyTypeObject*); + p = va_arg(*p_va, PyObject **); + format++; + if (PyType_IsSubtype(arg->ob_type, type)) + *p = arg; + else + return converterr(type->tp_name, arg, msgbuf, bufsize); + + } + else if (*format == '?') { + inquiry pred = va_arg(*p_va, inquiry); + p = va_arg(*p_va, PyObject **); + format++; + if ((*pred)(arg)) + *p = arg; + else + return converterr("(unspecified)", + arg, msgbuf, bufsize); + + } + else if (*format == '&') { + typedef int (*converter)(PyObject *, void *); + converter convert = va_arg(*p_va, converter); + void *addr = va_arg(*p_va, void *); + int res; + format++; + if (! (res = (*convert)(arg, addr))) + return converterr("(unspecified)", + arg, msgbuf, bufsize); + if (res == Py_CLEANUP_SUPPORTED && + addcleanup_convert(addr, freelist, convert) == -1) + return converterr("(cleanup problem)", + arg, msgbuf, bufsize); + } + else { + p = va_arg(*p_va, PyObject **); + *p = arg; + } + break; + } + + + case 'w': { /* memory buffer, read-write access */ + void **p = va_arg(*p_va, void **); + PyBufferProcs *pb = arg->ob_type->tp_as_buffer; + Py_ssize_t count; + int temp=-1; + Py_buffer view; + + if (pb && pb->bf_releasebuffer && *format != '*') + /* Buffer must be released, yet caller does not use + the Py_buffer protocol. */ + return converterr("pinned buffer", arg, msgbuf, bufsize); + + + if (pb && pb->bf_getbuffer && *format == '*') { + /* Caller is interested in Py_buffer, and the object + supports it directly. */ + format++; + if (PyObject_GetBuffer(arg, (Py_buffer*)p, PyBUF_WRITABLE) < 0) { + PyErr_Clear(); + return converterr("read-write buffer", arg, msgbuf, bufsize); + } + if (addcleanup(p, freelist, cleanup_buffer)) { + return converterr( + "(cleanup problem)", + arg, msgbuf, bufsize); + } + if (!PyBuffer_IsContiguous((Py_buffer*)p, 'C')) + return converterr("contiguous buffer", arg, msgbuf, bufsize); + break; + } + + /* Here we have processed w*, only w and w# remain. */ + if (pb == NULL || + pb->bf_getbuffer == NULL || + ((temp = PyObject_GetBuffer(arg, &view, + PyBUF_SIMPLE)) != 0) || + view.readonly == 1) { + if (temp==0) { + PyBuffer_Release(&view); + } + return converterr("single-segment read-write buffer", + arg, msgbuf, bufsize); + } + + if ((count = view.len) < 0) + return converterr("(unspecified)", arg, msgbuf, bufsize); + *p = view.buf; + if (*format == '#') { + FETCH_SIZE; + STORE_SIZE(count); + format++; + } + break; + } + + /*TEO: This can be eliminated --- here only for backward + compatibility */ + case 't': { /* 8-bit character buffer, read-only access */ + char **p = va_arg(*p_va, char **); + PyBufferProcs *pb = arg->ob_type->tp_as_buffer; + Py_ssize_t count; + Py_buffer view; - if ((count = view.len) < 0) - return converterr("(unspecified)", arg, msgbuf, bufsize); - *p = view.buf; - if (*format == '#') { - FETCH_SIZE; - STORE_SIZE(count); - format++; - } - break; - } - - /*TEO: This can be eliminated --- here only for backward - compatibility */ - case 't': { /* 8-bit character buffer, read-only access */ - char **p = va_arg(*p_va, char **); - PyBufferProcs *pb = arg->ob_type->tp_as_buffer; - Py_ssize_t count; - Py_buffer view; - - if (*format++ != '#') - return converterr( - "invalid use of 't' format character", - arg, msgbuf, bufsize); - if (pb == NULL || pb->bf_getbuffer == NULL) - return converterr( - "bytes or read-only character buffer", - arg, msgbuf, bufsize); - - if (PyObject_GetBuffer(arg, &view, PyBUF_SIMPLE) != 0) - return converterr("string or single-segment read-only buffer", - arg, msgbuf, bufsize); - - count = view.len; - *p = view.buf; - if (pb->bf_releasebuffer) - return converterr( - "string or pinned buffer", - arg, msgbuf, bufsize); - - PyBuffer_Release(&view); - - if (count < 0) - return converterr("(unspecified)", arg, msgbuf, bufsize); - { - FETCH_SIZE; - STORE_SIZE(count); - } - break; - } + if (*format++ != '#') + return converterr( + "invalid use of 't' format character", + arg, msgbuf, bufsize); + if (pb == NULL || pb->bf_getbuffer == NULL) + return converterr( + "bytes or read-only character buffer", + arg, msgbuf, bufsize); + + if (PyObject_GetBuffer(arg, &view, PyBUF_SIMPLE) != 0) + return converterr("string or single-segment read-only buffer", + arg, msgbuf, bufsize); - default: - return converterr("impossible", arg, msgbuf, bufsize); + count = view.len; + *p = view.buf; + if (pb->bf_releasebuffer) + return converterr( + "string or pinned buffer", + arg, msgbuf, bufsize); + + PyBuffer_Release(&view); + + if (count < 0) + return converterr("(unspecified)", arg, msgbuf, bufsize); + { + FETCH_SIZE; + STORE_SIZE(count); + } + break; + } - } + default: + return converterr("impossible", arg, msgbuf, bufsize); - *p_format = format; - return NULL; + } + + *p_format = format; + return NULL; } static Py_ssize_t convertbuffer(PyObject *arg, void **p, char **errmsg) { - PyBufferProcs *pb = arg->ob_type->tp_as_buffer; - Py_ssize_t count; - Py_buffer view; - - *errmsg = NULL; - *p = NULL; - if (pb == NULL || - pb->bf_getbuffer == NULL || - pb->bf_releasebuffer != NULL) { - *errmsg = "bytes or read-only buffer"; - return -1; - } - - if (PyObject_GetBuffer(arg, &view, PyBUF_SIMPLE) != 0) { - *errmsg = "bytes or single-segment read-only buffer"; - return -1; - } - count = view.len; - *p = view.buf; - PyBuffer_Release(&view); - return count; + PyBufferProcs *pb = arg->ob_type->tp_as_buffer; + Py_ssize_t count; + Py_buffer view; + + *errmsg = NULL; + *p = NULL; + if (pb == NULL || + pb->bf_getbuffer == NULL || + pb->bf_releasebuffer != NULL) { + *errmsg = "bytes or read-only buffer"; + return -1; + } + + if (PyObject_GetBuffer(arg, &view, PyBUF_SIMPLE) != 0) { + *errmsg = "bytes or single-segment read-only buffer"; + return -1; + } + count = view.len; + *p = view.buf; + PyBuffer_Release(&view); + return count; } /* XXX for 3.x, getbuffer and convertbuffer can probably @@ -1460,32 +1460,32 @@ static int getbuffer(PyObject *arg, Py_buffer *view, char **errmsg) { - void *buf; - Py_ssize_t count; - PyBufferProcs *pb = arg->ob_type->tp_as_buffer; - if (pb == NULL) { - *errmsg = "bytes or buffer"; - return -1; - } - if (pb->bf_getbuffer) { - if (PyObject_GetBuffer(arg, view, 0) < 0) { - *errmsg = "convertible to a buffer"; - return -1; - } - if (!PyBuffer_IsContiguous(view, 'C')) { - *errmsg = "contiguous buffer"; - return -1; - } - return 0; - } - - count = convertbuffer(arg, &buf, errmsg); - if (count < 0) { - *errmsg = "convertible to a buffer"; - return count; - } - PyBuffer_FillInfo(view, NULL, buf, count, 1, 0); - return 0; + void *buf; + Py_ssize_t count; + PyBufferProcs *pb = arg->ob_type->tp_as_buffer; + if (pb == NULL) { + *errmsg = "bytes or buffer"; + return -1; + } + if (pb->bf_getbuffer) { + if (PyObject_GetBuffer(arg, view, 0) < 0) { + *errmsg = "convertible to a buffer"; + return -1; + } + if (!PyBuffer_IsContiguous(view, 'C')) { + *errmsg = "contiguous buffer"; + return -1; + } + return 0; + } + + count = convertbuffer(arg, &buf, errmsg); + if (count < 0) { + *errmsg = "convertible to a buffer"; + return count; + } + PyBuffer_FillInfo(view, NULL, buf, count, 1, 0); + return 0; } /* Support for keyword arguments donated by @@ -1494,51 +1494,51 @@ /* Return false (0) for error, else true. */ int PyArg_ParseTupleAndKeywords(PyObject *args, - PyObject *keywords, - const char *format, - char **kwlist, ...) -{ - int retval; - va_list va; - - if ((args == NULL || !PyTuple_Check(args)) || - (keywords != NULL && !PyDict_Check(keywords)) || - format == NULL || - kwlist == NULL) - { - PyErr_BadInternalCall(); - return 0; - } - - va_start(va, kwlist); - retval = vgetargskeywords(args, keywords, format, kwlist, &va, 0); - va_end(va); - return retval; + PyObject *keywords, + const char *format, + char **kwlist, ...) +{ + int retval; + va_list va; + + if ((args == NULL || !PyTuple_Check(args)) || + (keywords != NULL && !PyDict_Check(keywords)) || + format == NULL || + kwlist == NULL) + { + PyErr_BadInternalCall(); + return 0; + } + + va_start(va, kwlist); + retval = vgetargskeywords(args, keywords, format, kwlist, &va, 0); + va_end(va); + return retval; } int _PyArg_ParseTupleAndKeywords_SizeT(PyObject *args, - PyObject *keywords, - const char *format, - char **kwlist, ...) -{ - int retval; - va_list va; - - if ((args == NULL || !PyTuple_Check(args)) || - (keywords != NULL && !PyDict_Check(keywords)) || - format == NULL || - kwlist == NULL) - { - PyErr_BadInternalCall(); - return 0; - } - - va_start(va, kwlist); - retval = vgetargskeywords(args, keywords, format, - kwlist, &va, FLAG_SIZE_T); - va_end(va); - return retval; + PyObject *keywords, + const char *format, + char **kwlist, ...) +{ + int retval; + va_list va; + + if ((args == NULL || !PyTuple_Check(args)) || + (keywords != NULL && !PyDict_Check(keywords)) || + format == NULL || + kwlist == NULL) + { + PyErr_BadInternalCall(); + return 0; + } + + va_start(va, kwlist); + retval = vgetargskeywords(args, keywords, format, + kwlist, &va, FLAG_SIZE_T); + va_end(va); + return retval; } @@ -1548,422 +1548,422 @@ const char *format, char **kwlist, va_list va) { - int retval; - va_list lva; + int retval; + va_list lva; - if ((args == NULL || !PyTuple_Check(args)) || - (keywords != NULL && !PyDict_Check(keywords)) || - format == NULL || - kwlist == NULL) - { - PyErr_BadInternalCall(); - return 0; - } + if ((args == NULL || !PyTuple_Check(args)) || + (keywords != NULL && !PyDict_Check(keywords)) || + format == NULL || + kwlist == NULL) + { + PyErr_BadInternalCall(); + return 0; + } #ifdef VA_LIST_IS_ARRAY - memcpy(lva, va, sizeof(va_list)); + memcpy(lva, va, sizeof(va_list)); #else #ifdef __va_copy - __va_copy(lva, va); + __va_copy(lva, va); #else - lva = va; + lva = va; #endif #endif - retval = vgetargskeywords(args, keywords, format, kwlist, &lva, 0); - return retval; + retval = vgetargskeywords(args, keywords, format, kwlist, &lva, 0); + return retval; } int _PyArg_VaParseTupleAndKeywords_SizeT(PyObject *args, - PyObject *keywords, - const char *format, - char **kwlist, va_list va) -{ - int retval; - va_list lva; - - if ((args == NULL || !PyTuple_Check(args)) || - (keywords != NULL && !PyDict_Check(keywords)) || - format == NULL || - kwlist == NULL) - { - PyErr_BadInternalCall(); - return 0; - } + PyObject *keywords, + const char *format, + char **kwlist, va_list va) +{ + int retval; + va_list lva; + + if ((args == NULL || !PyTuple_Check(args)) || + (keywords != NULL && !PyDict_Check(keywords)) || + format == NULL || + kwlist == NULL) + { + PyErr_BadInternalCall(); + return 0; + } #ifdef VA_LIST_IS_ARRAY - memcpy(lva, va, sizeof(va_list)); + memcpy(lva, va, sizeof(va_list)); #else #ifdef __va_copy - __va_copy(lva, va); + __va_copy(lva, va); #else - lva = va; + lva = va; #endif #endif - retval = vgetargskeywords(args, keywords, format, - kwlist, &lva, FLAG_SIZE_T); - return retval; + retval = vgetargskeywords(args, keywords, format, + kwlist, &lva, FLAG_SIZE_T); + return retval; } int PyArg_ValidateKeywordArguments(PyObject *kwargs) { - if (!PyDict_CheckExact(kwargs)) { - PyErr_BadInternalCall(); - return 0; - } - if (!_PyDict_HasOnlyStringKeys(kwargs)) { - PyErr_SetString(PyExc_TypeError, - "keyword arguments must be strings"); - return 0; - } - return 1; + if (!PyDict_CheckExact(kwargs)) { + PyErr_BadInternalCall(); + return 0; + } + if (!_PyDict_HasOnlyStringKeys(kwargs)) { + PyErr_SetString(PyExc_TypeError, + "keyword arguments must be strings"); + return 0; + } + return 1; } #define IS_END_OF_FORMAT(c) (c == '\0' || c == ';' || c == ':') static int vgetargskeywords(PyObject *args, PyObject *keywords, const char *format, - char **kwlist, va_list *p_va, int flags) + char **kwlist, va_list *p_va, int flags) { - char msgbuf[512]; - int levels[32]; - const char *fname, *msg, *custom_msg, *keyword; - int min = INT_MAX; - int i, len, nargs, nkeywords; - PyObject *freelist = NULL, *current_arg; - - assert(args != NULL && PyTuple_Check(args)); - assert(keywords == NULL || PyDict_Check(keywords)); - assert(format != NULL); - assert(kwlist != NULL); - assert(p_va != NULL); - - /* grab the function name or custom error msg first (mutually exclusive) */ - fname = strchr(format, ':'); - if (fname) { - fname++; - custom_msg = NULL; - } - else { - custom_msg = strchr(format,';'); - if (custom_msg) - custom_msg++; - } - - /* scan kwlist and get greatest possible nbr of args */ - for (len=0; kwlist[len]; len++) - continue; - - nargs = PyTuple_GET_SIZE(args); - nkeywords = (keywords == NULL) ? 0 : PyDict_Size(keywords); - if (nargs + nkeywords > len) { - PyErr_Format(PyExc_TypeError, "%s%s takes at most %d " - "argument%s (%d given)", - (fname == NULL) ? "function" : fname, - (fname == NULL) ? "" : "()", - len, - (len == 1) ? "" : "s", - nargs + nkeywords); - return 0; - } - - /* convert tuple args and keyword args in same loop, using kwlist to drive process */ - for (i = 0; i < len; i++) { - keyword = kwlist[i]; - if (*format == '|') { - min = i; - format++; - } - if (IS_END_OF_FORMAT(*format)) { - PyErr_Format(PyExc_RuntimeError, - "More keyword list entries (%d) than " - "format specifiers (%d)", len, i); - return cleanreturn(0, freelist); - } - current_arg = NULL; - if (nkeywords) { - current_arg = PyDict_GetItemString(keywords, keyword); - } - if (current_arg) { - --nkeywords; - if (i < nargs) { - /* arg present in tuple and in dict */ - PyErr_Format(PyExc_TypeError, - "Argument given by name ('%s') " - "and position (%d)", - keyword, i+1); - return cleanreturn(0, freelist); - } - } - else if (nkeywords && PyErr_Occurred()) - return cleanreturn(0, freelist); - else if (i < nargs) - current_arg = PyTuple_GET_ITEM(args, i); - - if (current_arg) { - msg = convertitem(current_arg, &format, p_va, flags, - levels, msgbuf, sizeof(msgbuf), &freelist); - if (msg) { - seterror(i+1, msg, levels, fname, custom_msg); - return cleanreturn(0, freelist); - } - continue; - } - - if (i < min) { - PyErr_Format(PyExc_TypeError, "Required argument " - "'%s' (pos %d) not found", - keyword, i+1); - return cleanreturn(0, freelist); - } - /* current code reports success when all required args - * fulfilled and no keyword args left, with no further - * validation. XXX Maybe skip this in debug build ? - */ - if (!nkeywords) - return cleanreturn(1, freelist); - - /* We are into optional args, skip thru to any remaining - * keyword args */ - msg = skipitem(&format, p_va, flags); - if (msg) { - PyErr_Format(PyExc_RuntimeError, "%s: '%s'", msg, - format); - return cleanreturn(0, freelist); - } - } - - if (!IS_END_OF_FORMAT(*format) && *format != '|') { - PyErr_Format(PyExc_RuntimeError, - "more argument specifiers than keyword list entries " - "(remaining format:'%s')", format); - return cleanreturn(0, freelist); - } - - /* make sure there are no extraneous keyword arguments */ - if (nkeywords > 0) { - PyObject *key, *value; - Py_ssize_t pos = 0; - while (PyDict_Next(keywords, &pos, &key, &value)) { - int match = 0; - char *ks; - if (!PyUnicode_Check(key)) { - PyErr_SetString(PyExc_TypeError, - "keywords must be strings"); - return cleanreturn(0, freelist); - } - ks = _PyUnicode_AsString(key); - for (i = 0; i < len; i++) { - if (!strcmp(ks, kwlist[i])) { - match = 1; - break; - } - } - if (!match) { - PyErr_Format(PyExc_TypeError, - "'%s' is an invalid keyword " - "argument for this function", - ks); - return cleanreturn(0, freelist); - } - } - } + char msgbuf[512]; + int levels[32]; + const char *fname, *msg, *custom_msg, *keyword; + int min = INT_MAX; + int i, len, nargs, nkeywords; + PyObject *freelist = NULL, *current_arg; + + assert(args != NULL && PyTuple_Check(args)); + assert(keywords == NULL || PyDict_Check(keywords)); + assert(format != NULL); + assert(kwlist != NULL); + assert(p_va != NULL); + + /* grab the function name or custom error msg first (mutually exclusive) */ + fname = strchr(format, ':'); + if (fname) { + fname++; + custom_msg = NULL; + } + else { + custom_msg = strchr(format,';'); + if (custom_msg) + custom_msg++; + } + + /* scan kwlist and get greatest possible nbr of args */ + for (len=0; kwlist[len]; len++) + continue; + + nargs = PyTuple_GET_SIZE(args); + nkeywords = (keywords == NULL) ? 0 : PyDict_Size(keywords); + if (nargs + nkeywords > len) { + PyErr_Format(PyExc_TypeError, "%s%s takes at most %d " + "argument%s (%d given)", + (fname == NULL) ? "function" : fname, + (fname == NULL) ? "" : "()", + len, + (len == 1) ? "" : "s", + nargs + nkeywords); + return 0; + } + + /* convert tuple args and keyword args in same loop, using kwlist to drive process */ + for (i = 0; i < len; i++) { + keyword = kwlist[i]; + if (*format == '|') { + min = i; + format++; + } + if (IS_END_OF_FORMAT(*format)) { + PyErr_Format(PyExc_RuntimeError, + "More keyword list entries (%d) than " + "format specifiers (%d)", len, i); + return cleanreturn(0, freelist); + } + current_arg = NULL; + if (nkeywords) { + current_arg = PyDict_GetItemString(keywords, keyword); + } + if (current_arg) { + --nkeywords; + if (i < nargs) { + /* arg present in tuple and in dict */ + PyErr_Format(PyExc_TypeError, + "Argument given by name ('%s') " + "and position (%d)", + keyword, i+1); + return cleanreturn(0, freelist); + } + } + else if (nkeywords && PyErr_Occurred()) + return cleanreturn(0, freelist); + else if (i < nargs) + current_arg = PyTuple_GET_ITEM(args, i); + + if (current_arg) { + msg = convertitem(current_arg, &format, p_va, flags, + levels, msgbuf, sizeof(msgbuf), &freelist); + if (msg) { + seterror(i+1, msg, levels, fname, custom_msg); + return cleanreturn(0, freelist); + } + continue; + } + + if (i < min) { + PyErr_Format(PyExc_TypeError, "Required argument " + "'%s' (pos %d) not found", + keyword, i+1); + return cleanreturn(0, freelist); + } + /* current code reports success when all required args + * fulfilled and no keyword args left, with no further + * validation. XXX Maybe skip this in debug build ? + */ + if (!nkeywords) + return cleanreturn(1, freelist); + + /* We are into optional args, skip thru to any remaining + * keyword args */ + msg = skipitem(&format, p_va, flags); + if (msg) { + PyErr_Format(PyExc_RuntimeError, "%s: '%s'", msg, + format); + return cleanreturn(0, freelist); + } + } + + if (!IS_END_OF_FORMAT(*format) && *format != '|') { + PyErr_Format(PyExc_RuntimeError, + "more argument specifiers than keyword list entries " + "(remaining format:'%s')", format); + return cleanreturn(0, freelist); + } + + /* make sure there are no extraneous keyword arguments */ + if (nkeywords > 0) { + PyObject *key, *value; + Py_ssize_t pos = 0; + while (PyDict_Next(keywords, &pos, &key, &value)) { + int match = 0; + char *ks; + if (!PyUnicode_Check(key)) { + PyErr_SetString(PyExc_TypeError, + "keywords must be strings"); + return cleanreturn(0, freelist); + } + ks = _PyUnicode_AsString(key); + for (i = 0; i < len; i++) { + if (!strcmp(ks, kwlist[i])) { + match = 1; + break; + } + } + if (!match) { + PyErr_Format(PyExc_TypeError, + "'%s' is an invalid keyword " + "argument for this function", + ks); + return cleanreturn(0, freelist); + } + } + } - return cleanreturn(1, freelist); + return cleanreturn(1, freelist); } static char * skipitem(const char **p_format, va_list *p_va, int flags) { - const char *format = *p_format; - char c = *format++; + const char *format = *p_format; + char c = *format++; - switch (c) { + switch (c) { - /* simple codes - * The individual types (second arg of va_arg) are irrelevant */ + /* simple codes + * The individual types (second arg of va_arg) are irrelevant */ - case 'b': /* byte -- very short int */ - case 'B': /* byte as bitfield */ - case 'h': /* short int */ - case 'H': /* short int as bitfield */ - case 'i': /* int */ - case 'I': /* int sized bitfield */ - case 'l': /* long int */ - case 'k': /* long int sized bitfield */ + case 'b': /* byte -- very short int */ + case 'B': /* byte as bitfield */ + case 'h': /* short int */ + case 'H': /* short int as bitfield */ + case 'i': /* int */ + case 'I': /* int sized bitfield */ + case 'l': /* long int */ + case 'k': /* long int sized bitfield */ #ifdef HAVE_LONG_LONG - case 'L': /* PY_LONG_LONG */ - case 'K': /* PY_LONG_LONG sized bitfield */ + case 'L': /* PY_LONG_LONG */ + case 'K': /* PY_LONG_LONG sized bitfield */ #endif - case 'f': /* float */ - case 'd': /* double */ - case 'D': /* complex double */ - case 'c': /* char */ - case 'C': /* unicode char */ - { - (void) va_arg(*p_va, void *); - break; - } - - case 'n': /* Py_ssize_t */ - { - (void) va_arg(*p_va, Py_ssize_t *); - break; - } - - /* string codes */ - - case 'e': /* string with encoding */ - { - (void) va_arg(*p_va, const char *); - if (!(*format == 's' || *format == 't')) - /* after 'e', only 's' and 't' is allowed */ - goto err; - format++; - /* explicit fallthrough to string cases */ - } - - case 's': /* string */ - case 'z': /* string or None */ - case 'y': /* bytes */ - case 'u': /* unicode string */ - case 't': /* buffer, read-only */ - case 'w': /* buffer, read-write */ - { - (void) va_arg(*p_va, char **); - if (*format == '#') { - if (flags & FLAG_SIZE_T) - (void) va_arg(*p_va, Py_ssize_t *); - else - (void) va_arg(*p_va, int *); - format++; - } else if ((c == 's' || c == 'z' || c == 'y') && *format == '*') { - format++; - } - break; - } - - /* object codes */ - - case 'S': /* string object */ - case 'Y': /* string object */ - case 'U': /* unicode string object */ - { - (void) va_arg(*p_va, PyObject **); - break; - } - - case 'O': /* object */ - { - if (*format == '!') { - format++; - (void) va_arg(*p_va, PyTypeObject*); - (void) va_arg(*p_va, PyObject **); - } - else if (*format == '&') { - typedef int (*converter)(PyObject *, void *); - (void) va_arg(*p_va, converter); - (void) va_arg(*p_va, void *); - format++; - } - else { - (void) va_arg(*p_va, PyObject **); - } - break; - } - - case '(': /* bypass tuple, not handled at all previously */ - { - char *msg; - for (;;) { - if (*format==')') - break; - if (IS_END_OF_FORMAT(*format)) - return "Unmatched left paren in format " - "string"; - msg = skipitem(&format, p_va, flags); - if (msg) - return msg; - } - format++; - break; - } + case 'f': /* float */ + case 'd': /* double */ + case 'D': /* complex double */ + case 'c': /* char */ + case 'C': /* unicode char */ + { + (void) va_arg(*p_va, void *); + break; + } + + case 'n': /* Py_ssize_t */ + { + (void) va_arg(*p_va, Py_ssize_t *); + break; + } + + /* string codes */ + + case 'e': /* string with encoding */ + { + (void) va_arg(*p_va, const char *); + if (!(*format == 's' || *format == 't')) + /* after 'e', only 's' and 't' is allowed */ + goto err; + format++; + /* explicit fallthrough to string cases */ + } + + case 's': /* string */ + case 'z': /* string or None */ + case 'y': /* bytes */ + case 'u': /* unicode string */ + case 't': /* buffer, read-only */ + case 'w': /* buffer, read-write */ + { + (void) va_arg(*p_va, char **); + if (*format == '#') { + if (flags & FLAG_SIZE_T) + (void) va_arg(*p_va, Py_ssize_t *); + else + (void) va_arg(*p_va, int *); + format++; + } else if ((c == 's' || c == 'z' || c == 'y') && *format == '*') { + format++; + } + break; + } + + /* object codes */ + + case 'S': /* string object */ + case 'Y': /* string object */ + case 'U': /* unicode string object */ + { + (void) va_arg(*p_va, PyObject **); + break; + } + + case 'O': /* object */ + { + if (*format == '!') { + format++; + (void) va_arg(*p_va, PyTypeObject*); + (void) va_arg(*p_va, PyObject **); + } + else if (*format == '&') { + typedef int (*converter)(PyObject *, void *); + (void) va_arg(*p_va, converter); + (void) va_arg(*p_va, void *); + format++; + } + else { + (void) va_arg(*p_va, PyObject **); + } + break; + } + + case '(': /* bypass tuple, not handled at all previously */ + { + char *msg; + for (;;) { + if (*format==')') + break; + if (IS_END_OF_FORMAT(*format)) + return "Unmatched left paren in format " + "string"; + msg = skipitem(&format, p_va, flags); + if (msg) + return msg; + } + format++; + break; + } - case ')': - return "Unmatched right paren in format string"; + case ')': + return "Unmatched right paren in format string"; - default: + default: err: - return "impossible"; + return "impossible"; - } + } - *p_format = format; - return NULL; + *p_format = format; + return NULL; } int PyArg_UnpackTuple(PyObject *args, const char *name, Py_ssize_t min, Py_ssize_t max, ...) { - Py_ssize_t i, l; - PyObject **o; - va_list vargs; + Py_ssize_t i, l; + PyObject **o; + va_list vargs; #ifdef HAVE_STDARG_PROTOTYPES - va_start(vargs, max); + va_start(vargs, max); #else - va_start(vargs); + va_start(vargs); #endif - assert(min >= 0); - assert(min <= max); - if (!PyTuple_Check(args)) { - PyErr_SetString(PyExc_SystemError, - "PyArg_UnpackTuple() argument list is not a tuple"); - return 0; - } - l = PyTuple_GET_SIZE(args); - if (l < min) { - if (name != NULL) - PyErr_Format( - PyExc_TypeError, - "%s expected %s%zd arguments, got %zd", - name, (min == max ? "" : "at least "), min, l); - else - PyErr_Format( - PyExc_TypeError, - "unpacked tuple should have %s%zd elements," - " but has %zd", - (min == max ? "" : "at least "), min, l); - va_end(vargs); - return 0; - } - if (l > max) { - if (name != NULL) - PyErr_Format( - PyExc_TypeError, - "%s expected %s%zd arguments, got %zd", - name, (min == max ? "" : "at most "), max, l); - else - PyErr_Format( - PyExc_TypeError, - "unpacked tuple should have %s%zd elements," - " but has %zd", - (min == max ? "" : "at most "), max, l); - va_end(vargs); - return 0; - } - for (i = 0; i < l; i++) { - o = va_arg(vargs, PyObject **); - *o = PyTuple_GET_ITEM(args, i); - } - va_end(vargs); - return 1; + assert(min >= 0); + assert(min <= max); + if (!PyTuple_Check(args)) { + PyErr_SetString(PyExc_SystemError, + "PyArg_UnpackTuple() argument list is not a tuple"); + return 0; + } + l = PyTuple_GET_SIZE(args); + if (l < min) { + if (name != NULL) + PyErr_Format( + PyExc_TypeError, + "%s expected %s%zd arguments, got %zd", + name, (min == max ? "" : "at least "), min, l); + else + PyErr_Format( + PyExc_TypeError, + "unpacked tuple should have %s%zd elements," + " but has %zd", + (min == max ? "" : "at least "), min, l); + va_end(vargs); + return 0; + } + if (l > max) { + if (name != NULL) + PyErr_Format( + PyExc_TypeError, + "%s expected %s%zd arguments, got %zd", + name, (min == max ? "" : "at most "), max, l); + else + PyErr_Format( + PyExc_TypeError, + "unpacked tuple should have %s%zd elements," + " but has %zd", + (min == max ? "" : "at most "), max, l); + va_end(vargs); + return 0; + } + for (i = 0; i < l; i++) { + o = va_arg(vargs, PyObject **); + *o = PyTuple_GET_ITEM(args, i); + } + va_end(vargs); + return 1; } @@ -1975,18 +1975,18 @@ int _PyArg_NoKeywords(const char *funcname, PyObject *kw) { - if (kw == NULL) - return 1; - if (!PyDict_CheckExact(kw)) { - PyErr_BadInternalCall(); - return 0; - } - if (PyDict_Size(kw) == 0) - return 1; - - PyErr_Format(PyExc_TypeError, "%s does not take keyword arguments", - funcname); - return 0; + if (kw == NULL) + return 1; + if (!PyDict_CheckExact(kw)) { + PyErr_BadInternalCall(); + return 0; + } + if (PyDict_Size(kw) == 0) + return 1; + + PyErr_Format(PyExc_TypeError, "%s does not take keyword arguments", + funcname); + return 0; } #ifdef __cplusplus }; Modified: python/branches/py3k/Python/getcwd.c ============================================================================== --- python/branches/py3k/Python/getcwd.c (original) +++ python/branches/py3k/Python/getcwd.c Sun May 9 17:52:27 2010 @@ -26,24 +26,24 @@ char * getcwd(char *buf, int size) { - char localbuf[MAXPATHLEN+1]; - char *ret; - - if (size <= 0) { - errno = EINVAL; - return NULL; - } - ret = getwd(localbuf); - if (ret != NULL && strlen(localbuf) >= (size_t)size) { - errno = ERANGE; - return NULL; - } - if (ret == NULL) { - errno = EACCES; /* Most likely error */ - return NULL; - } - strncpy(buf, localbuf, size); - return buf; + char localbuf[MAXPATHLEN+1]; + char *ret; + + if (size <= 0) { + errno = EINVAL; + return NULL; + } + ret = getwd(localbuf); + if (ret != NULL && strlen(localbuf) >= (size_t)size) { + errno = ERANGE; + return NULL; + } + if (ret == NULL) { + errno = EACCES; /* Most likely error */ + return NULL; + } + strncpy(buf, localbuf, size); + return buf; } #else /* !HAVE_GETWD */ @@ -57,27 +57,27 @@ char * getcwd(char *buf, int size) { - FILE *fp; - char *p; - int sts; - if (size <= 0) { - errno = EINVAL; - return NULL; - } - if ((fp = popen(PWD_CMD, "r")) == NULL) - return NULL; - if (fgets(buf, size, fp) == NULL || (sts = pclose(fp)) != 0) { - errno = EACCES; /* Most likely error */ - return NULL; - } - for (p = buf; *p != '\n'; p++) { - if (*p == '\0') { - errno = ERANGE; - return NULL; - } - } - *p = '\0'; - return buf; + FILE *fp; + char *p; + int sts; + if (size <= 0) { + errno = EINVAL; + return NULL; + } + if ((fp = popen(PWD_CMD, "r")) == NULL) + return NULL; + if (fgets(buf, size, fp) == NULL || (sts = pclose(fp)) != 0) { + errno = EACCES; /* Most likely error */ + return NULL; + } + for (p = buf; *p != '\n'; p++) { + if (*p == '\0') { + errno = ERANGE; + return NULL; + } + } + *p = '\0'; + return buf; } #endif /* !HAVE_GETWD */ Modified: python/branches/py3k/Python/getopt.c ============================================================================== --- python/branches/py3k/Python/getopt.c (original) +++ python/branches/py3k/Python/getopt.c Sun May 9 17:52:27 2010 @@ -7,8 +7,8 @@ * * All Rights Reserved * - * Permission to use, copy, modify, and distribute this software and its - * documentation for any purpose and without fee is hereby granted, + * 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, this permission notice and * the following disclaimer notice appear unmodified in all copies. * @@ -43,84 +43,84 @@ int _PyOS_GetOpt(int argc, wchar_t **argv, wchar_t *optstring) { - static wchar_t *opt_ptr = L""; - wchar_t *ptr; - wchar_t option; + static wchar_t *opt_ptr = L""; + wchar_t *ptr; + wchar_t option; - if (*opt_ptr == '\0') { + if (*opt_ptr == '\0') { - if (_PyOS_optind >= argc) - return -1; + if (_PyOS_optind >= argc) + return -1; #ifdef MS_WINDOWS - else if (wcscmp(argv[_PyOS_optind], L"/?") == 0) { - ++_PyOS_optind; - return 'h'; - } + else if (wcscmp(argv[_PyOS_optind], L"/?") == 0) { + ++_PyOS_optind; + return 'h'; + } #endif - else if (argv[_PyOS_optind][0] != L'-' || - argv[_PyOS_optind][1] == L'\0' /* lone dash */ ) - return -1; - - else if (wcscmp(argv[_PyOS_optind], L"--") == 0) { - ++_PyOS_optind; - return -1; - } - - else if (wcscmp(argv[_PyOS_optind], L"--help") == 0) { - ++_PyOS_optind; - return 'h'; - } - - else if (wcscmp(argv[_PyOS_optind], L"--version") == 0) { - ++_PyOS_optind; - return 'V'; - } - - - opt_ptr = &argv[_PyOS_optind++][1]; - } - - if ( (option = *opt_ptr++) == L'\0') - return -1; - - if (option == 'J') { - fprintf(stderr, "-J is reserved for Jython\n"); - return '_'; - } - - if (option == 'X') { - fprintf(stderr, - "-X is reserved for implementation-specific arguments\n"); - return '_'; - } - - if ((ptr = wcschr(optstring, option)) == NULL) { - if (_PyOS_opterr) - fprintf(stderr, "Unknown option: -%c\n", (char)option); - - return '_'; - } - - if (*(ptr + 1) == L':') { - if (*opt_ptr != L'\0') { - _PyOS_optarg = opt_ptr; - opt_ptr = L""; - } - - else { - if (_PyOS_optind >= argc) { - if (_PyOS_opterr) - fprintf(stderr, - "Argument expected for the -%c option\n", (char)option); - return '_'; - } - - _PyOS_optarg = argv[_PyOS_optind++]; - } - } + else if (argv[_PyOS_optind][0] != L'-' || + argv[_PyOS_optind][1] == L'\0' /* lone dash */ ) + return -1; + + else if (wcscmp(argv[_PyOS_optind], L"--") == 0) { + ++_PyOS_optind; + return -1; + } + + else if (wcscmp(argv[_PyOS_optind], L"--help") == 0) { + ++_PyOS_optind; + return 'h'; + } + + else if (wcscmp(argv[_PyOS_optind], L"--version") == 0) { + ++_PyOS_optind; + return 'V'; + } + + + opt_ptr = &argv[_PyOS_optind++][1]; + } + + if ( (option = *opt_ptr++) == L'\0') + return -1; + + if (option == 'J') { + fprintf(stderr, "-J is reserved for Jython\n"); + return '_'; + } + + if (option == 'X') { + fprintf(stderr, + "-X is reserved for implementation-specific arguments\n"); + return '_'; + } + + if ((ptr = wcschr(optstring, option)) == NULL) { + if (_PyOS_opterr) + fprintf(stderr, "Unknown option: -%c\n", (char)option); + + return '_'; + } + + if (*(ptr + 1) == L':') { + if (*opt_ptr != L'\0') { + _PyOS_optarg = opt_ptr; + opt_ptr = L""; + } + + else { + if (_PyOS_optind >= argc) { + if (_PyOS_opterr) + fprintf(stderr, + "Argument expected for the -%c option\n", (char)option); + return '_'; + } + + _PyOS_optarg = argv[_PyOS_optind++]; + } + } - return option; + return option; } #ifdef __cplusplus Modified: python/branches/py3k/Python/import.c ============================================================================== --- python/branches/py3k/Python/import.c (original) +++ python/branches/py3k/Python/import.c Sun May 9 17:52:27 2010 @@ -76,31 +76,31 @@ Python 2.5b3: 62101 (fix wrong code: for x, in ...) Python 2.5b3: 62111 (fix wrong code: x += yield) Python 2.5c1: 62121 (fix wrong lnotab with for loops and - storing constants that should have been removed) + storing constants that should have been removed) Python 2.5c2: 62131 (fix wrong code: for x, in ... in listcomp/genexp) Python 2.6a0: 62151 (peephole optimizations and STORE_MAP opcode) Python 2.6a1: 62161 (WITH_CLEANUP optimization) Python 3000: 3000 - 3010 (removed UNARY_CONVERT) - 3020 (added BUILD_SET) - 3030 (added keyword-only parameters) - 3040 (added signature annotations) - 3050 (print becomes a function) - 3060 (PEP 3115 metaclass syntax) - 3061 (string literals become unicode) - 3071 (PEP 3109 raise changes) - 3081 (PEP 3137 make __file__ and __name__ unicode) - 3091 (kill str8 interning) - 3101 (merge from 2.6a0, see 62151) - 3103 (__file__ points to source file) + 3010 (removed UNARY_CONVERT) + 3020 (added BUILD_SET) + 3030 (added keyword-only parameters) + 3040 (added signature annotations) + 3050 (print becomes a function) + 3060 (PEP 3115 metaclass syntax) + 3061 (string literals become unicode) + 3071 (PEP 3109 raise changes) + 3081 (PEP 3137 make __file__ and __name__ unicode) + 3091 (kill str8 interning) + 3101 (merge from 2.6a0, see 62151) + 3103 (__file__ points to source file) Python 3.0a4: 3111 (WITH_CLEANUP optimization). Python 3.0a5: 3131 (lexical exception stacking, including POP_EXCEPT) Python 3.1a0: 3141 (optimize list, set and dict comprehensions: - change LIST_APPEND and SET_ADD, add MAP_ADD) + change LIST_APPEND and SET_ADD, add MAP_ADD) Python 3.1a0: 3151 (optimize conditional branches: - introduce POP_JUMP_IF_FALSE and POP_JUMP_IF_TRUE) + introduce POP_JUMP_IF_FALSE and POP_JUMP_IF_TRUE) Python 3.2a0: 3160 (add SETUP_WITH) - tag: cpython-32 + tag: cpython-32 */ /* If you change MAGIC, you must change TAG and you must insert the old value @@ -128,12 +128,12 @@ struct filedescr * _PyImport_Filetab = NULL; static const struct filedescr _PyImport_StandardFiletab[] = { - {".py", "U", PY_SOURCE}, + {".py", "U", PY_SOURCE}, #ifdef MS_WINDOWS - {".pyw", "U", PY_SOURCE}, + {".pyw", "U", PY_SOURCE}, #endif - {".pyc", "rb", PY_COMPILED}, - {0, 0} + {".pyc", "rb", PY_COMPILED}, + {0, 0} }; @@ -142,119 +142,119 @@ void _PyImport_Init(void) { - const struct filedescr *scan; - struct filedescr *filetab; - int countD = 0; - int countS = 0; - - /* prepare _PyImport_Filetab: copy entries from - _PyImport_DynLoadFiletab and _PyImport_StandardFiletab. - */ + const struct filedescr *scan; + struct filedescr *filetab; + int countD = 0; + int countS = 0; + + /* prepare _PyImport_Filetab: copy entries from + _PyImport_DynLoadFiletab and _PyImport_StandardFiletab. + */ #ifdef HAVE_DYNAMIC_LOADING - for (scan = _PyImport_DynLoadFiletab; scan->suffix != NULL; ++scan) - ++countD; + for (scan = _PyImport_DynLoadFiletab; scan->suffix != NULL; ++scan) + ++countD; #endif - for (scan = _PyImport_StandardFiletab; scan->suffix != NULL; ++scan) - ++countS; - filetab = PyMem_NEW(struct filedescr, countD + countS + 1); - if (filetab == NULL) - Py_FatalError("Can't initialize import file table."); + for (scan = _PyImport_StandardFiletab; scan->suffix != NULL; ++scan) + ++countS; + filetab = PyMem_NEW(struct filedescr, countD + countS + 1); + if (filetab == NULL) + Py_FatalError("Can't initialize import file table."); #ifdef HAVE_DYNAMIC_LOADING - memcpy(filetab, _PyImport_DynLoadFiletab, - countD * sizeof(struct filedescr)); + memcpy(filetab, _PyImport_DynLoadFiletab, + countD * sizeof(struct filedescr)); #endif - memcpy(filetab + countD, _PyImport_StandardFiletab, - countS * sizeof(struct filedescr)); - filetab[countD + countS].suffix = NULL; - - _PyImport_Filetab = filetab; - - if (Py_OptimizeFlag) { - /* Replace ".pyc" with ".pyo" in _PyImport_Filetab */ - for (; filetab->suffix != NULL; filetab++) { - if (strcmp(filetab->suffix, ".pyc") == 0) - filetab->suffix = ".pyo"; - } - } + memcpy(filetab + countD, _PyImport_StandardFiletab, + countS * sizeof(struct filedescr)); + filetab[countD + countS].suffix = NULL; + + _PyImport_Filetab = filetab; + + if (Py_OptimizeFlag) { + /* Replace ".pyc" with ".pyo" in _PyImport_Filetab */ + for (; filetab->suffix != NULL; filetab++) { + if (strcmp(filetab->suffix, ".pyc") == 0) + filetab->suffix = ".pyo"; + } + } } void _PyImportHooks_Init(void) { - PyObject *v, *path_hooks = NULL, *zimpimport; - int err = 0; + PyObject *v, *path_hooks = NULL, *zimpimport; + int err = 0; - /* adding sys.path_hooks and sys.path_importer_cache, setting up - zipimport */ - if (PyType_Ready(&PyNullImporter_Type) < 0) - goto error; - - if (Py_VerboseFlag) - PySys_WriteStderr("# installing zipimport hook\n"); - - v = PyList_New(0); - if (v == NULL) - goto error; - err = PySys_SetObject("meta_path", v); - Py_DECREF(v); - if (err) - goto error; - v = PyDict_New(); - if (v == NULL) - goto error; - err = PySys_SetObject("path_importer_cache", v); - Py_DECREF(v); - if (err) - goto error; - path_hooks = PyList_New(0); - if (path_hooks == NULL) - goto error; - err = PySys_SetObject("path_hooks", path_hooks); - if (err) { + /* adding sys.path_hooks and sys.path_importer_cache, setting up + zipimport */ + if (PyType_Ready(&PyNullImporter_Type) < 0) + goto error; + + if (Py_VerboseFlag) + PySys_WriteStderr("# installing zipimport hook\n"); + + v = PyList_New(0); + if (v == NULL) + goto error; + err = PySys_SetObject("meta_path", v); + Py_DECREF(v); + if (err) + goto error; + v = PyDict_New(); + if (v == NULL) + goto error; + err = PySys_SetObject("path_importer_cache", v); + Py_DECREF(v); + if (err) + goto error; + path_hooks = PyList_New(0); + if (path_hooks == NULL) + goto error; + err = PySys_SetObject("path_hooks", path_hooks); + if (err) { error: - PyErr_Print(); - Py_FatalError("initializing sys.meta_path, sys.path_hooks, " - "path_importer_cache, or NullImporter failed" - ); - } - - zimpimport = PyImport_ImportModule("zipimport"); - if (zimpimport == NULL) { - PyErr_Clear(); /* No zip import module -- okay */ - if (Py_VerboseFlag) - PySys_WriteStderr("# can't import zipimport\n"); - } - else { - PyObject *zipimporter = PyObject_GetAttrString(zimpimport, - "zipimporter"); - Py_DECREF(zimpimport); - if (zipimporter == NULL) { - PyErr_Clear(); /* No zipimporter object -- okay */ - if (Py_VerboseFlag) - PySys_WriteStderr( - "# can't import zipimport.zipimporter\n"); - } - else { - /* sys.path_hooks.append(zipimporter) */ - err = PyList_Append(path_hooks, zipimporter); - Py_DECREF(zipimporter); - if (err) - goto error; - if (Py_VerboseFlag) - PySys_WriteStderr( - "# installed zipimport hook\n"); - } - } - Py_DECREF(path_hooks); + PyErr_Print(); + Py_FatalError("initializing sys.meta_path, sys.path_hooks, " + "path_importer_cache, or NullImporter failed" + ); + } + + zimpimport = PyImport_ImportModule("zipimport"); + if (zimpimport == NULL) { + PyErr_Clear(); /* No zip import module -- okay */ + if (Py_VerboseFlag) + PySys_WriteStderr("# can't import zipimport\n"); + } + else { + PyObject *zipimporter = PyObject_GetAttrString(zimpimport, + "zipimporter"); + Py_DECREF(zimpimport); + if (zipimporter == NULL) { + PyErr_Clear(); /* No zipimporter object -- okay */ + if (Py_VerboseFlag) + PySys_WriteStderr( + "# can't import zipimport.zipimporter\n"); + } + else { + /* sys.path_hooks.append(zipimporter) */ + err = PyList_Append(path_hooks, zipimporter); + Py_DECREF(zipimporter); + if (err) + goto error; + if (Py_VerboseFlag) + PySys_WriteStderr( + "# installed zipimport hook\n"); + } + } + Py_DECREF(path_hooks); } void _PyImport_Fini(void) { - Py_XDECREF(extensions); - extensions = NULL; - PyMem_DEL(_PyImport_Filetab); - _PyImport_Filetab = NULL; + Py_XDECREF(extensions); + extensions = NULL; + PyMem_DEL(_PyImport_Filetab); + _PyImport_Filetab = NULL; } @@ -273,42 +273,42 @@ void _PyImport_AcquireLock(void) { - long me = PyThread_get_thread_ident(); - if (me == -1) - return; /* Too bad */ - if (import_lock == NULL) { - import_lock = PyThread_allocate_lock(); - if (import_lock == NULL) - return; /* Nothing much we can do. */ - } - if (import_lock_thread == me) { - import_lock_level++; - return; - } - if (import_lock_thread != -1 || !PyThread_acquire_lock(import_lock, 0)) - { - PyThreadState *tstate = PyEval_SaveThread(); - PyThread_acquire_lock(import_lock, 1); - PyEval_RestoreThread(tstate); - } - import_lock_thread = me; - import_lock_level = 1; + long me = PyThread_get_thread_ident(); + if (me == -1) + return; /* Too bad */ + if (import_lock == NULL) { + import_lock = PyThread_allocate_lock(); + if (import_lock == NULL) + return; /* Nothing much we can do. */ + } + if (import_lock_thread == me) { + import_lock_level++; + return; + } + if (import_lock_thread != -1 || !PyThread_acquire_lock(import_lock, 0)) + { + PyThreadState *tstate = PyEval_SaveThread(); + PyThread_acquire_lock(import_lock, 1); + PyEval_RestoreThread(tstate); + } + import_lock_thread = me; + import_lock_level = 1; } int _PyImport_ReleaseLock(void) { - long me = PyThread_get_thread_ident(); - if (me == -1 || import_lock == NULL) - return 0; /* Too bad */ - if (import_lock_thread != me) - return -1; - import_lock_level--; - if (import_lock_level == 0) { - import_lock_thread = -1; - PyThread_release_lock(import_lock); - } - return 1; + long me = PyThread_get_thread_ident(); + if (me == -1 || import_lock == NULL) + return 0; /* Too bad */ + if (import_lock_thread != me) + return -1; + import_lock_level--; + if (import_lock_level == 0) { + import_lock_thread = -1; + PyThread_release_lock(import_lock); + } + return 1; } /* This function is called from PyOS_AfterFork to ensure that newly @@ -319,10 +319,10 @@ void _PyImport_ReInitLock(void) { - if (import_lock != NULL) - import_lock = PyThread_allocate_lock(); - import_lock_thread = -1; - import_lock_level = 0; + if (import_lock != NULL) + import_lock = PyThread_allocate_lock(); + import_lock_thread = -1; + import_lock_level = 0; } #endif @@ -331,9 +331,9 @@ imp_lock_held(PyObject *self, PyObject *noargs) { #ifdef WITH_THREAD - return PyBool_FromLong(import_lock_thread != -1); + return PyBool_FromLong(import_lock_thread != -1); #else - return PyBool_FromLong(0); + return PyBool_FromLong(0); #endif } @@ -341,32 +341,32 @@ imp_acquire_lock(PyObject *self, PyObject *noargs) { #ifdef WITH_THREAD - _PyImport_AcquireLock(); + _PyImport_AcquireLock(); #endif - Py_INCREF(Py_None); - return Py_None; + Py_INCREF(Py_None); + return Py_None; } static PyObject * imp_release_lock(PyObject *self, PyObject *noargs) { #ifdef WITH_THREAD - if (_PyImport_ReleaseLock() < 0) { - PyErr_SetString(PyExc_RuntimeError, - "not holding the import lock"); - return NULL; - } + if (_PyImport_ReleaseLock() < 0) { + PyErr_SetString(PyExc_RuntimeError, + "not holding the import lock"); + return NULL; + } #endif - Py_INCREF(Py_None); - return Py_None; + Py_INCREF(Py_None); + return Py_None; } static void imp_modules_reloading_clear(void) { - PyInterpreterState *interp = PyThreadState_Get()->interp; - if (interp->modules_reloading != NULL) - PyDict_Clear(interp->modules_reloading); + PyInterpreterState *interp = PyThreadState_Get()->interp; + if (interp->modules_reloading != NULL) + PyDict_Clear(interp->modules_reloading); } /* Helper for sys */ @@ -374,28 +374,28 @@ PyObject * PyImport_GetModuleDict(void) { - PyInterpreterState *interp = PyThreadState_GET()->interp; - if (interp->modules == NULL) - Py_FatalError("PyImport_GetModuleDict: no module dictionary!"); - return interp->modules; + PyInterpreterState *interp = PyThreadState_GET()->interp; + if (interp->modules == NULL) + Py_FatalError("PyImport_GetModuleDict: no module dictionary!"); + return interp->modules; } /* List of names to clear in sys */ static char* sys_deletes[] = { - "path", "argv", "ps1", "ps2", - "last_type", "last_value", "last_traceback", - "path_hooks", "path_importer_cache", "meta_path", - /* misc stuff */ - "flags", "float_info", - NULL + "path", "argv", "ps1", "ps2", + "last_type", "last_value", "last_traceback", + "path_hooks", "path_importer_cache", "meta_path", + /* misc stuff */ + "flags", "float_info", + NULL }; static char* sys_files[] = { - "stdin", "__stdin__", - "stdout", "__stdout__", - "stderr", "__stderr__", - NULL + "stdin", "__stdin__", + "stdout", "__stdout__", + "stderr", "__stderr__", + NULL }; @@ -404,132 +404,132 @@ void PyImport_Cleanup(void) { - Py_ssize_t pos, ndone; - char *name; - PyObject *key, *value, *dict; - PyInterpreterState *interp = PyThreadState_GET()->interp; - PyObject *modules = interp->modules; - - if (modules == NULL) - return; /* Already done */ - - /* Delete some special variables first. These are common - places where user values hide and people complain when their - destructors fail. Since the modules containing them are - deleted *last* of all, they would come too late in the normal - destruction order. Sigh. */ - - value = PyDict_GetItemString(modules, "builtins"); - if (value != NULL && PyModule_Check(value)) { - dict = PyModule_GetDict(value); - if (Py_VerboseFlag) - PySys_WriteStderr("# clear builtins._\n"); - PyDict_SetItemString(dict, "_", Py_None); - } - value = PyDict_GetItemString(modules, "sys"); - if (value != NULL && PyModule_Check(value)) { - char **p; - PyObject *v; - dict = PyModule_GetDict(value); - for (p = sys_deletes; *p != NULL; p++) { - if (Py_VerboseFlag) - PySys_WriteStderr("# clear sys.%s\n", *p); - PyDict_SetItemString(dict, *p, Py_None); - } - for (p = sys_files; *p != NULL; p+=2) { - if (Py_VerboseFlag) - PySys_WriteStderr("# restore sys.%s\n", *p); - v = PyDict_GetItemString(dict, *(p+1)); - if (v == NULL) - v = Py_None; - PyDict_SetItemString(dict, *p, v); - } - } - - /* First, delete __main__ */ - value = PyDict_GetItemString(modules, "__main__"); - if (value != NULL && PyModule_Check(value)) { - if (Py_VerboseFlag) - PySys_WriteStderr("# cleanup __main__\n"); - _PyModule_Clear(value); - PyDict_SetItemString(modules, "__main__", Py_None); - } - - /* The special treatment of "builtins" here is because even - when it's not referenced as a module, its dictionary is - referenced by almost every module's __builtins__. Since - deleting a module clears its dictionary (even if there are - references left to it), we need to delete the "builtins" - module last. Likewise, we don't delete sys until the very - end because it is implicitly referenced (e.g. by print). - - Also note that we 'delete' modules by replacing their entry - in the modules dict with None, rather than really deleting - them; this avoids a rehash of the modules dictionary and - also marks them as "non existent" so they won't be - re-imported. */ - - /* Next, repeatedly delete modules with a reference count of - one (skipping builtins and sys) and delete them */ - do { - ndone = 0; - pos = 0; - while (PyDict_Next(modules, &pos, &key, &value)) { - if (value->ob_refcnt != 1) - continue; - if (PyUnicode_Check(key) && PyModule_Check(value)) { - name = _PyUnicode_AsString(key); - if (strcmp(name, "builtins") == 0) - continue; - if (strcmp(name, "sys") == 0) - continue; - if (Py_VerboseFlag) - PySys_WriteStderr( - "# cleanup[1] %s\n", name); - _PyModule_Clear(value); - PyDict_SetItem(modules, key, Py_None); - ndone++; - } - } - } while (ndone > 0); - - /* Next, delete all modules (still skipping builtins and sys) */ - pos = 0; - while (PyDict_Next(modules, &pos, &key, &value)) { - if (PyUnicode_Check(key) && PyModule_Check(value)) { - name = _PyUnicode_AsString(key); - if (strcmp(name, "builtins") == 0) - continue; - if (strcmp(name, "sys") == 0) - continue; - if (Py_VerboseFlag) - PySys_WriteStderr("# cleanup[2] %s\n", name); - _PyModule_Clear(value); - PyDict_SetItem(modules, key, Py_None); - } - } - - /* Next, delete sys and builtins (in that order) */ - value = PyDict_GetItemString(modules, "sys"); - if (value != NULL && PyModule_Check(value)) { - if (Py_VerboseFlag) - PySys_WriteStderr("# cleanup sys\n"); - _PyModule_Clear(value); - PyDict_SetItemString(modules, "sys", Py_None); - } - value = PyDict_GetItemString(modules, "builtins"); - if (value != NULL && PyModule_Check(value)) { - if (Py_VerboseFlag) - PySys_WriteStderr("# cleanup builtins\n"); - _PyModule_Clear(value); - PyDict_SetItemString(modules, "builtins", Py_None); - } - - /* Finally, clear and delete the modules directory */ - PyDict_Clear(modules); - interp->modules = NULL; - Py_DECREF(modules); - Py_CLEAR(interp->modules_reloading); + Py_ssize_t pos, ndone; + char *name; + PyObject *key, *value, *dict; + PyInterpreterState *interp = PyThreadState_GET()->interp; + PyObject *modules = interp->modules; + + if (modules == NULL) + return; /* Already done */ + + /* Delete some special variables first. These are common + places where user values hide and people complain when their + destructors fail. Since the modules containing them are + deleted *last* of all, they would come too late in the normal + destruction order. Sigh. */ + + value = PyDict_GetItemString(modules, "builtins"); + if (value != NULL && PyModule_Check(value)) { + dict = PyModule_GetDict(value); + if (Py_VerboseFlag) + PySys_WriteStderr("# clear builtins._\n"); + PyDict_SetItemString(dict, "_", Py_None); + } + value = PyDict_GetItemString(modules, "sys"); + if (value != NULL && PyModule_Check(value)) { + char **p; + PyObject *v; + dict = PyModule_GetDict(value); + for (p = sys_deletes; *p != NULL; p++) { + if (Py_VerboseFlag) + PySys_WriteStderr("# clear sys.%s\n", *p); + PyDict_SetItemString(dict, *p, Py_None); + } + for (p = sys_files; *p != NULL; p+=2) { + if (Py_VerboseFlag) + PySys_WriteStderr("# restore sys.%s\n", *p); + v = PyDict_GetItemString(dict, *(p+1)); + if (v == NULL) + v = Py_None; + PyDict_SetItemString(dict, *p, v); + } + } + + /* First, delete __main__ */ + value = PyDict_GetItemString(modules, "__main__"); + if (value != NULL && PyModule_Check(value)) { + if (Py_VerboseFlag) + PySys_WriteStderr("# cleanup __main__\n"); + _PyModule_Clear(value); + PyDict_SetItemString(modules, "__main__", Py_None); + } + + /* The special treatment of "builtins" here is because even + when it's not referenced as a module, its dictionary is + referenced by almost every module's __builtins__. Since + deleting a module clears its dictionary (even if there are + references left to it), we need to delete the "builtins" + module last. Likewise, we don't delete sys until the very + end because it is implicitly referenced (e.g. by print). + + Also note that we 'delete' modules by replacing their entry + in the modules dict with None, rather than really deleting + them; this avoids a rehash of the modules dictionary and + also marks them as "non existent" so they won't be + re-imported. */ + + /* Next, repeatedly delete modules with a reference count of + one (skipping builtins and sys) and delete them */ + do { + ndone = 0; + pos = 0; + while (PyDict_Next(modules, &pos, &key, &value)) { + if (value->ob_refcnt != 1) + continue; + if (PyUnicode_Check(key) && PyModule_Check(value)) { + name = _PyUnicode_AsString(key); + if (strcmp(name, "builtins") == 0) + continue; + if (strcmp(name, "sys") == 0) + continue; + if (Py_VerboseFlag) + PySys_WriteStderr( + "# cleanup[1] %s\n", name); + _PyModule_Clear(value); + PyDict_SetItem(modules, key, Py_None); + ndone++; + } + } + } while (ndone > 0); + + /* Next, delete all modules (still skipping builtins and sys) */ + pos = 0; + while (PyDict_Next(modules, &pos, &key, &value)) { + if (PyUnicode_Check(key) && PyModule_Check(value)) { + name = _PyUnicode_AsString(key); + if (strcmp(name, "builtins") == 0) + continue; + if (strcmp(name, "sys") == 0) + continue; + if (Py_VerboseFlag) + PySys_WriteStderr("# cleanup[2] %s\n", name); + _PyModule_Clear(value); + PyDict_SetItem(modules, key, Py_None); + } + } + + /* Next, delete sys and builtins (in that order) */ + value = PyDict_GetItemString(modules, "sys"); + if (value != NULL && PyModule_Check(value)) { + if (Py_VerboseFlag) + PySys_WriteStderr("# cleanup sys\n"); + _PyModule_Clear(value); + PyDict_SetItemString(modules, "sys", Py_None); + } + value = PyDict_GetItemString(modules, "builtins"); + if (value != NULL && PyModule_Check(value)) { + if (Py_VerboseFlag) + PySys_WriteStderr("# cleanup builtins\n"); + _PyModule_Clear(value); + PyDict_SetItemString(modules, "builtins", Py_None); + } + + /* Finally, clear and delete the modules directory */ + PyDict_Clear(modules); + interp->modules = NULL; + Py_DECREF(modules); + Py_CLEAR(interp->modules_reloading); } @@ -538,14 +538,14 @@ long PyImport_GetMagicNumber(void) { - return pyc_magic; + return pyc_magic; } const char * PyImport_GetMagicTag(void) { - return pyc_tag; + return pyc_tag; } /* Magic for extension modules (built-in as well as dynamically @@ -567,89 +567,89 @@ int _PyImport_FixupExtension(PyObject *mod, char *name, char *filename) { - PyObject *modules, *dict; - struct PyModuleDef *def; - if (extensions == NULL) { - extensions = PyDict_New(); - if (extensions == NULL) - return -1; - } - if (mod == NULL || !PyModule_Check(mod)) { - PyErr_BadInternalCall(); - return -1; - } - def = PyModule_GetDef(mod); - if (!def) { - PyErr_BadInternalCall(); - return -1; - } - modules = PyImport_GetModuleDict(); - if (PyDict_SetItemString(modules, name, mod) < 0) - return -1; - if (_PyState_AddModule(mod, def) < 0) { - PyDict_DelItemString(modules, name); - return -1; - } - if (def->m_size == -1) { - if (def->m_base.m_copy) { - /* Somebody already imported the module, - likely under a different name. - XXX this should really not happen. */ - Py_DECREF(def->m_base.m_copy); - def->m_base.m_copy = NULL; - } - dict = PyModule_GetDict(mod); - if (dict == NULL) - return -1; - def->m_base.m_copy = PyDict_Copy(dict); - if (def->m_base.m_copy == NULL) - return -1; - } - PyDict_SetItemString(extensions, filename, (PyObject*)def); - return 0; + PyObject *modules, *dict; + struct PyModuleDef *def; + if (extensions == NULL) { + extensions = PyDict_New(); + if (extensions == NULL) + return -1; + } + if (mod == NULL || !PyModule_Check(mod)) { + PyErr_BadInternalCall(); + return -1; + } + def = PyModule_GetDef(mod); + if (!def) { + PyErr_BadInternalCall(); + return -1; + } + modules = PyImport_GetModuleDict(); + if (PyDict_SetItemString(modules, name, mod) < 0) + return -1; + if (_PyState_AddModule(mod, def) < 0) { + PyDict_DelItemString(modules, name); + return -1; + } + if (def->m_size == -1) { + if (def->m_base.m_copy) { + /* Somebody already imported the module, + likely under a different name. + XXX this should really not happen. */ + Py_DECREF(def->m_base.m_copy); + def->m_base.m_copy = NULL; + } + dict = PyModule_GetDict(mod); + if (dict == NULL) + return -1; + def->m_base.m_copy = PyDict_Copy(dict); + if (def->m_base.m_copy == NULL) + return -1; + } + PyDict_SetItemString(extensions, filename, (PyObject*)def); + return 0; } PyObject * _PyImport_FindExtension(char *name, char *filename) { - PyObject *mod, *mdict; - PyModuleDef* def; - if (extensions == NULL) - return NULL; - def = (PyModuleDef*)PyDict_GetItemString(extensions, filename); - if (def == NULL) - return NULL; - if (def->m_size == -1) { - /* Module does not support repeated initialization */ - if (def->m_base.m_copy == NULL) - return NULL; - mod = PyImport_AddModule(name); - if (mod == NULL) - return NULL; - mdict = PyModule_GetDict(mod); - if (mdict == NULL) - return NULL; - if (PyDict_Update(mdict, def->m_base.m_copy)) - return NULL; - } - else { - if (def->m_base.m_init == NULL) - return NULL; - mod = def->m_base.m_init(); - if (mod == NULL) - return NULL; - PyDict_SetItemString(PyImport_GetModuleDict(), name, mod); - Py_DECREF(mod); - } - if (_PyState_AddModule(mod, def) < 0) { - PyDict_DelItemString(PyImport_GetModuleDict(), name); - Py_DECREF(mod); - return NULL; - } - if (Py_VerboseFlag) - PySys_WriteStderr("import %s # previously loaded (%s)\n", - name, filename); - return mod; + PyObject *mod, *mdict; + PyModuleDef* def; + if (extensions == NULL) + return NULL; + def = (PyModuleDef*)PyDict_GetItemString(extensions, filename); + if (def == NULL) + return NULL; + if (def->m_size == -1) { + /* Module does not support repeated initialization */ + if (def->m_base.m_copy == NULL) + return NULL; + mod = PyImport_AddModule(name); + if (mod == NULL) + return NULL; + mdict = PyModule_GetDict(mod); + if (mdict == NULL) + return NULL; + if (PyDict_Update(mdict, def->m_base.m_copy)) + return NULL; + } + else { + if (def->m_base.m_init == NULL) + return NULL; + mod = def->m_base.m_init(); + if (mod == NULL) + return NULL; + PyDict_SetItemString(PyImport_GetModuleDict(), name, mod); + Py_DECREF(mod); + } + if (_PyState_AddModule(mod, def) < 0) { + PyDict_DelItemString(PyImport_GetModuleDict(), name); + Py_DECREF(mod); + return NULL; + } + if (Py_VerboseFlag) + PySys_WriteStderr("import %s # previously loaded (%s)\n", + name, filename); + return mod; } @@ -663,40 +663,40 @@ PyObject * PyImport_AddModule(const char *name) { - PyObject *modules = PyImport_GetModuleDict(); - PyObject *m; + PyObject *modules = PyImport_GetModuleDict(); + PyObject *m; - if ((m = PyDict_GetItemString(modules, name)) != NULL && - PyModule_Check(m)) - return m; - m = PyModule_New(name); - if (m == NULL) - return NULL; - if (PyDict_SetItemString(modules, name, m) != 0) { - Py_DECREF(m); - return NULL; - } - Py_DECREF(m); /* Yes, it still exists, in modules! */ + if ((m = PyDict_GetItemString(modules, name)) != NULL && + PyModule_Check(m)) + return m; + m = PyModule_New(name); + if (m == NULL) + return NULL; + if (PyDict_SetItemString(modules, name, m) != 0) { + Py_DECREF(m); + return NULL; + } + Py_DECREF(m); /* Yes, it still exists, in modules! */ - return m; + return m; } /* Remove name from sys.modules, if it's there. */ static void remove_module(const char *name) { - PyObject *modules = PyImport_GetModuleDict(); - if (PyDict_GetItemString(modules, name) == NULL) - return; - if (PyDict_DelItemString(modules, name) < 0) - Py_FatalError("import: deleting existing key in" - "sys.modules failed"); + PyObject *modules = PyImport_GetModuleDict(); + if (PyDict_GetItemString(modules, name) == NULL) + return; + if (PyDict_DelItemString(modules, name) < 0) + Py_FatalError("import: deleting existing key in" + "sys.modules failed"); } static PyObject * get_sourcefile(char *file); static char *make_source_pathname(char *pathname, char *buf); static char *make_compiled_pathname(char *pathname, char *buf, size_t buflen, - int debug); + int debug); /* Execute a code object in a module and return the module object * WITH INCREMENTED REFERENCE COUNT. If an error occurs, name is @@ -711,83 +711,83 @@ PyObject * PyImport_ExecCodeModule(char *name, PyObject *co) { - return PyImport_ExecCodeModuleWithPathnames( - name, co, (char *)NULL, (char *)NULL); + return PyImport_ExecCodeModuleWithPathnames( + name, co, (char *)NULL, (char *)NULL); } PyObject * PyImport_ExecCodeModuleEx(char *name, PyObject *co, char *pathname) { - return PyImport_ExecCodeModuleWithPathnames( - name, co, pathname, (char *)NULL); + return PyImport_ExecCodeModuleWithPathnames( + name, co, pathname, (char *)NULL); } PyObject * PyImport_ExecCodeModuleWithPathnames(char *name, PyObject *co, char *pathname, - char *cpathname) + char *cpathname) { - PyObject *modules = PyImport_GetModuleDict(); - PyObject *m, *d, *v; + PyObject *modules = PyImport_GetModuleDict(); + PyObject *m, *d, *v; - m = PyImport_AddModule(name); - if (m == NULL) - return NULL; - /* If the module is being reloaded, we get the old module back - and re-use its dict to exec the new code. */ - d = PyModule_GetDict(m); - if (PyDict_GetItemString(d, "__builtins__") == NULL) { - if (PyDict_SetItemString(d, "__builtins__", - PyEval_GetBuiltins()) != 0) - goto error; - } - /* Remember the filename as the __file__ attribute */ - v = NULL; - if (pathname != NULL) { - v = get_sourcefile(pathname); - if (v == NULL) - PyErr_Clear(); - } - if (v == NULL) { - v = ((PyCodeObject *)co)->co_filename; - Py_INCREF(v); - } - if (PyDict_SetItemString(d, "__file__", v) != 0) - PyErr_Clear(); /* Not important enough to report */ - Py_DECREF(v); - - /* Remember the pyc path name as the __cached__ attribute. */ - if (cpathname == NULL) { - v = Py_None; - Py_INCREF(v); - } - else if ((v = PyUnicode_FromString(cpathname)) == NULL) { - PyErr_Clear(); /* Not important enough to report */ - v = Py_None; - Py_INCREF(v); - } - if (PyDict_SetItemString(d, "__cached__", v) != 0) - PyErr_Clear(); /* Not important enough to report */ - Py_DECREF(v); - - v = PyEval_EvalCode((PyCodeObject *)co, d, d); - if (v == NULL) - goto error; - Py_DECREF(v); - - if ((m = PyDict_GetItemString(modules, name)) == NULL) { - PyErr_Format(PyExc_ImportError, - "Loaded module %.200s not found in sys.modules", - name); - return NULL; - } + m = PyImport_AddModule(name); + if (m == NULL) + return NULL; + /* If the module is being reloaded, we get the old module back + and re-use its dict to exec the new code. */ + d = PyModule_GetDict(m); + if (PyDict_GetItemString(d, "__builtins__") == NULL) { + if (PyDict_SetItemString(d, "__builtins__", + PyEval_GetBuiltins()) != 0) + goto error; + } + /* Remember the filename as the __file__ attribute */ + v = NULL; + if (pathname != NULL) { + v = get_sourcefile(pathname); + if (v == NULL) + PyErr_Clear(); + } + if (v == NULL) { + v = ((PyCodeObject *)co)->co_filename; + Py_INCREF(v); + } + if (PyDict_SetItemString(d, "__file__", v) != 0) + PyErr_Clear(); /* Not important enough to report */ + Py_DECREF(v); + + /* Remember the pyc path name as the __cached__ attribute. */ + if (cpathname == NULL) { + v = Py_None; + Py_INCREF(v); + } + else if ((v = PyUnicode_FromString(cpathname)) == NULL) { + PyErr_Clear(); /* Not important enough to report */ + v = Py_None; + Py_INCREF(v); + } + if (PyDict_SetItemString(d, "__cached__", v) != 0) + PyErr_Clear(); /* Not important enough to report */ + Py_DECREF(v); + + v = PyEval_EvalCode((PyCodeObject *)co, d, d); + if (v == NULL) + goto error; + Py_DECREF(v); + + if ((m = PyDict_GetItemString(modules, name)) == NULL) { + PyErr_Format(PyExc_ImportError, + "Loaded module %.200s not found in sys.modules", + name); + return NULL; + } - Py_INCREF(m); + Py_INCREF(m); - return m; + return m; error: - remove_module(name); - return NULL; + remove_module(name); + return NULL; } @@ -797,18 +797,18 @@ static char * rightmost_sep(char *s) { - char *found, c; - for (found = NULL; (c = *s); s++) { - if (c == SEP + char *found, c; + for (found = NULL; (c = *s); s++) { + if (c == SEP #ifdef ALTSEP - || c == ALTSEP + || c == ALTSEP #endif - ) - { - found = s; - } - } - return found; + ) + { + found = s; + } + } + return found; } @@ -820,104 +820,104 @@ static char * make_compiled_pathname(char *pathname, char *buf, size_t buflen, int debug) { - /* foo.py -> __pycache__/foo..pyc */ - size_t len = strlen(pathname); - size_t i, save; - char *pos; - int sep = SEP; - - /* Sanity check that the buffer has roughly enough space to hold what - will eventually be the full path to the compiled file. The 5 extra - bytes include the slash afer __pycache__, the two extra dots, the - extra trailing character ('c' or 'o') and null. This isn't exact - because the contents of the buffer can affect how many actual - characters of the string get into the buffer. We'll do a final - sanity check before writing the extension to ensure we do not - overflow the buffer. - */ - if (len + strlen(CACHEDIR) + strlen(pyc_tag) + 5 > buflen) - return NULL; - - /* Find the last path separator and copy everything from the start of - the source string up to and including the separator. - */ - if ((pos = rightmost_sep(pathname)) == NULL) { - i = 0; - } - else { - sep = *pos; - i = pos - pathname + 1; - strncpy(buf, pathname, i); - } - - save = i; - buf[i++] = '\0'; - /* Add __pycache__/ */ - strcat(buf, CACHEDIR); - i += strlen(CACHEDIR) - 1; - buf[i++] = sep; - buf[i++] = '\0'; - /* Add the base filename, but remove the .py or .pyw extension, since - the tag name must go before the extension. - */ - strcat(buf, pathname + save); - if ((pos = strrchr(buf, '.')) != NULL) - *++pos = '\0'; - strcat(buf, pyc_tag); - /* The length test above assumes that we're only adding one character - to the end of what would normally be the extension. What if there - is no extension, or the string ends in '.' or '.p', and otherwise - fills the buffer? By appending 4 more characters onto the string - here, we could overrun the buffer. - - As a simple example, let's say buflen=32 and the input string is - 'xxx.py'. strlen() would be 6 and the test above would yield: - - (6 + 11 + 10 + 5 == 32) > 32 - - which is false and so the name mangling would continue. This would - be fine because we'd end up with this string in buf: - - __pycache__/xxx.cpython-32.pyc\0 - - strlen(of that) == 30 + the nul fits inside a 32 character buffer. - We can even handle an input string of say 'xxxxx' above because - that's (5 + 11 + 10 + 5 == 31) > 32 which is also false. Name - mangling that yields: - - __pycache__/xxxxxcpython-32.pyc\0 - - which is 32 characters including the nul, and thus fits in the - buffer. However, an input string of 'xxxxxx' would yield a result - string of: - - __pycache__/xxxxxxcpython-32.pyc\0 - - which is 33 characters long (including the nul), thus overflowing - the buffer, even though the first test would fail, i.e.: the input - string is also 6 characters long, so 32 > 32 is false. - - The reason the first test fails but we still overflow the buffer is - that the test above only expects to add one extra character to be - added to the extension, and here we're adding three (pyc). We - don't add the first dot, so that reclaims one of expected - positions, leaving us overflowing by 1 byte (3 extra - 1 reclaimed - dot - 1 expected extra == 1 overflowed). - - The best we can do is ensure that we still have enough room in the - target buffer before we write the extension. Because it's always - only the extension that can cause the overflow, and never the other - path bytes we've written, it's sufficient to just do one more test - here. Still, the assertion that follows can't hurt. - */ + /* foo.py -> __pycache__/foo..pyc */ + size_t len = strlen(pathname); + size_t i, save; + char *pos; + int sep = SEP; + + /* Sanity check that the buffer has roughly enough space to hold what + will eventually be the full path to the compiled file. The 5 extra + bytes include the slash afer __pycache__, the two extra dots, the + extra trailing character ('c' or 'o') and null. This isn't exact + because the contents of the buffer can affect how many actual + characters of the string get into the buffer. We'll do a final + sanity check before writing the extension to ensure we do not + overflow the buffer. + */ + if (len + strlen(CACHEDIR) + strlen(pyc_tag) + 5 > buflen) + return NULL; + + /* Find the last path separator and copy everything from the start of + the source string up to and including the separator. + */ + if ((pos = rightmost_sep(pathname)) == NULL) { + i = 0; + } + else { + sep = *pos; + i = pos - pathname + 1; + strncpy(buf, pathname, i); + } + + save = i; + buf[i++] = '\0'; + /* Add __pycache__/ */ + strcat(buf, CACHEDIR); + i += strlen(CACHEDIR) - 1; + buf[i++] = sep; + buf[i++] = '\0'; + /* Add the base filename, but remove the .py or .pyw extension, since + the tag name must go before the extension. + */ + strcat(buf, pathname + save); + if ((pos = strrchr(buf, '.')) != NULL) + *++pos = '\0'; + strcat(buf, pyc_tag); + /* The length test above assumes that we're only adding one character + to the end of what would normally be the extension. What if there + is no extension, or the string ends in '.' or '.p', and otherwise + fills the buffer? By appending 4 more characters onto the string + here, we could overrun the buffer. + + As a simple example, let's say buflen=32 and the input string is + 'xxx.py'. strlen() would be 6 and the test above would yield: + + (6 + 11 + 10 + 5 == 32) > 32 + + which is false and so the name mangling would continue. This would + be fine because we'd end up with this string in buf: + + __pycache__/xxx.cpython-32.pyc\0 + + strlen(of that) == 30 + the nul fits inside a 32 character buffer. + We can even handle an input string of say 'xxxxx' above because + that's (5 + 11 + 10 + 5 == 31) > 32 which is also false. Name + mangling that yields: + + __pycache__/xxxxxcpython-32.pyc\0 + + which is 32 characters including the nul, and thus fits in the + buffer. However, an input string of 'xxxxxx' would yield a result + string of: + + __pycache__/xxxxxxcpython-32.pyc\0 + + which is 33 characters long (including the nul), thus overflowing + the buffer, even though the first test would fail, i.e.: the input + string is also 6 characters long, so 32 > 32 is false. + + The reason the first test fails but we still overflow the buffer is + that the test above only expects to add one extra character to be + added to the extension, and here we're adding three (pyc). We + don't add the first dot, so that reclaims one of expected + positions, leaving us overflowing by 1 byte (3 extra - 1 reclaimed + dot - 1 expected extra == 1 overflowed). + + The best we can do is ensure that we still have enough room in the + target buffer before we write the extension. Because it's always + only the extension that can cause the overflow, and never the other + path bytes we've written, it's sufficient to just do one more test + here. Still, the assertion that follows can't hurt. + */ #if 0 - printf("strlen(buf): %d; buflen: %d\n", (int)strlen(buf), (int)buflen); + printf("strlen(buf): %d; buflen: %d\n", (int)strlen(buf), (int)buflen); #endif - if (strlen(buf) + 5 > buflen) - return NULL; - strcat(buf, debug ? ".pyc" : ".pyo"); - assert(strlen(buf) < buflen); - return buf; + if (strlen(buf) + 5 > buflen) + return NULL; + strcat(buf, debug ? ".pyc" : ".pyo"); + assert(strlen(buf) < buflen); + return buf; } @@ -926,52 +926,52 @@ for any file existence, however, if the pyc file name does not match PEP 3147 style, NULL is returned. buf must be at least as big as pathname; the resulting path will always be shorter. */ - + static char * make_source_pathname(char *pathname, char *buf) { - /* __pycache__/foo..pyc -> foo.py */ - size_t i, j; - char *left, *right, *dot0, *dot1, sep; - - /* Look back two slashes from the end. In between these two slashes - must be the string __pycache__ or this is not a PEP 3147 style - path. It's possible for there to be only one slash. - */ - if ((right = rightmost_sep(pathname)) == NULL) - return NULL; - sep = *right; - *right = '\0'; - left = rightmost_sep(pathname); - *right = sep; - if (left == NULL) - left = pathname; - else - left++; - if (right-left != strlen(CACHEDIR) || - strncmp(left, CACHEDIR, right-left) != 0) - return NULL; - - /* Now verify that the path component to the right of the last slash - has two dots in it. - */ - if ((dot0 = strchr(right + 1, '.')) == NULL) - return NULL; - if ((dot1 = strchr(dot0 + 1, '.')) == NULL) - return NULL; - /* Too many dots? */ - if (strchr(dot1 + 1, '.') != NULL) - return NULL; - - /* This is a PEP 3147 path. Start by copying everything from the - start of pathname up to and including the leftmost slash. Then - copy the file's basename, removing the magic tag and adding a .py - suffix. - */ - strncpy(buf, pathname, (i=left-pathname)); - strncpy(buf+i, right+1, (j=dot0-right)); - strcpy(buf+i+j, "py"); - return buf; + /* __pycache__/foo..pyc -> foo.py */ + size_t i, j; + char *left, *right, *dot0, *dot1, sep; + + /* Look back two slashes from the end. In between these two slashes + must be the string __pycache__ or this is not a PEP 3147 style + path. It's possible for there to be only one slash. + */ + if ((right = rightmost_sep(pathname)) == NULL) + return NULL; + sep = *right; + *right = '\0'; + left = rightmost_sep(pathname); + *right = sep; + if (left == NULL) + left = pathname; + else + left++; + if (right-left != strlen(CACHEDIR) || + strncmp(left, CACHEDIR, right-left) != 0) + return NULL; + + /* Now verify that the path component to the right of the last slash + has two dots in it. + */ + if ((dot0 = strchr(right + 1, '.')) == NULL) + return NULL; + if ((dot1 = strchr(dot0 + 1, '.')) == NULL) + return NULL; + /* Too many dots? */ + if (strchr(dot1 + 1, '.') != NULL) + return NULL; + + /* This is a PEP 3147 path. Start by copying everything from the + start of pathname up to and including the leftmost slash. Then + copy the file's basename, removing the magic tag and adding a .py + suffix. + */ + strncpy(buf, pathname, (i=left-pathname)); + strncpy(buf+i, right+1, (j=dot0-right)); + strcpy(buf+i+j, "py"); + return buf; } /* Given a pathname for a Python source file, its time of last @@ -984,30 +984,30 @@ static FILE * check_compiled_module(char *pathname, time_t mtime, char *cpathname) { - FILE *fp; - long magic; - long pyc_mtime; - - fp = fopen(cpathname, "rb"); - if (fp == NULL) - return NULL; - magic = PyMarshal_ReadLongFromFile(fp); - if (magic != pyc_magic) { - if (Py_VerboseFlag) - PySys_WriteStderr("# %s has bad magic\n", cpathname); - fclose(fp); - return NULL; - } - pyc_mtime = PyMarshal_ReadLongFromFile(fp); - if (pyc_mtime != mtime) { - if (Py_VerboseFlag) - PySys_WriteStderr("# %s has bad mtime\n", cpathname); - fclose(fp); - return NULL; - } - if (Py_VerboseFlag) - PySys_WriteStderr("# %s matches %s\n", cpathname, pathname); - return fp; + FILE *fp; + long magic; + long pyc_mtime; + + fp = fopen(cpathname, "rb"); + if (fp == NULL) + return NULL; + magic = PyMarshal_ReadLongFromFile(fp); + if (magic != pyc_magic) { + if (Py_VerboseFlag) + PySys_WriteStderr("# %s has bad magic\n", cpathname); + fclose(fp); + return NULL; + } + pyc_mtime = PyMarshal_ReadLongFromFile(fp); + if (pyc_mtime != mtime) { + if (Py_VerboseFlag) + PySys_WriteStderr("# %s has bad mtime\n", cpathname); + fclose(fp); + return NULL; + } + if (Py_VerboseFlag) + PySys_WriteStderr("# %s matches %s\n", cpathname, pathname); + return fp; } @@ -1016,18 +1016,18 @@ static PyCodeObject * read_compiled_module(char *cpathname, FILE *fp) { - PyObject *co; + PyObject *co; - co = PyMarshal_ReadLastObjectFromFile(fp); - if (co == NULL) - return NULL; - if (!PyCode_Check(co)) { - PyErr_Format(PyExc_ImportError, - "Non-code object in %.200s", cpathname); - Py_DECREF(co); - return NULL; - } - return (PyCodeObject *)co; + co = PyMarshal_ReadLastObjectFromFile(fp); + if (co == NULL) + return NULL; + if (!PyCode_Check(co)) { + PyErr_Format(PyExc_ImportError, + "Non-code object in %.200s", cpathname); + Py_DECREF(co); + return NULL; + } + return (PyCodeObject *)co; } @@ -1037,28 +1037,28 @@ static PyObject * load_compiled_module(char *name, char *cpathname, FILE *fp) { - long magic; - PyCodeObject *co; - PyObject *m; - - magic = PyMarshal_ReadLongFromFile(fp); - if (magic != pyc_magic) { - PyErr_Format(PyExc_ImportError, - "Bad magic number in %.200s", cpathname); - return NULL; - } - (void) PyMarshal_ReadLongFromFile(fp); - co = read_compiled_module(cpathname, fp); - if (co == NULL) - return NULL; - if (Py_VerboseFlag) - PySys_WriteStderr("import %s # precompiled from %s\n", - name, cpathname); - m = PyImport_ExecCodeModuleWithPathnames( - name, (PyObject *)co, cpathname, cpathname); - Py_DECREF(co); + long magic; + PyCodeObject *co; + PyObject *m; + + magic = PyMarshal_ReadLongFromFile(fp); + if (magic != pyc_magic) { + PyErr_Format(PyExc_ImportError, + "Bad magic number in %.200s", cpathname); + return NULL; + } + (void) PyMarshal_ReadLongFromFile(fp); + co = read_compiled_module(cpathname, fp); + if (co == NULL) + return NULL; + if (Py_VerboseFlag) + PySys_WriteStderr("import %s # precompiled from %s\n", + name, cpathname); + m = PyImport_ExecCodeModuleWithPathnames( + name, (PyObject *)co, cpathname, cpathname); + Py_DECREF(co); - return m; + return m; } /* Parse a source file and return the corresponding code object */ @@ -1066,22 +1066,22 @@ static PyCodeObject * parse_source_module(const char *pathname, FILE *fp) { - PyCodeObject *co = NULL; - mod_ty mod; - PyCompilerFlags flags; - PyArena *arena = PyArena_New(); - if (arena == NULL) - return NULL; - - flags.cf_flags = 0; - mod = PyParser_ASTFromFile(fp, pathname, NULL, - Py_file_input, 0, 0, &flags, - NULL, arena); - if (mod) { - co = PyAST_Compile(mod, pathname, NULL, arena); - } - PyArena_Free(arena); - return co; + PyCodeObject *co = NULL; + mod_ty mod; + PyCompilerFlags flags; + PyArena *arena = PyArena_New(); + if (arena == NULL) + return NULL; + + flags.cf_flags = 0; + mod = PyParser_ASTFromFile(fp, pathname, NULL, + Py_file_input, 0, 0, &flags, + NULL, arena); + if (mod) { + co = PyAST_Compile(mod, pathname, NULL, arena); + } + PyArena_Free(arena); + return co; } @@ -1091,30 +1091,30 @@ open_exclusive(char *filename, mode_t mode) { #if defined(O_EXCL)&&defined(O_CREAT)&&defined(O_WRONLY)&&defined(O_TRUNC) - /* Use O_EXCL to avoid a race condition when another process tries to - write the same file. When that happens, our open() call fails, - which is just fine (since it's only a cache). - XXX If the file exists and is writable but the directory is not - writable, the file will never be written. Oh well. - */ - int fd; - (void) unlink(filename); - fd = open(filename, O_EXCL|O_CREAT|O_WRONLY|O_TRUNC + /* Use O_EXCL to avoid a race condition when another process tries to + write the same file. When that happens, our open() call fails, + which is just fine (since it's only a cache). + XXX If the file exists and is writable but the directory is not + writable, the file will never be written. Oh well. + */ + int fd; + (void) unlink(filename); + fd = open(filename, O_EXCL|O_CREAT|O_WRONLY|O_TRUNC #ifdef O_BINARY - |O_BINARY /* necessary for Windows */ + |O_BINARY /* necessary for Windows */ #endif #ifdef __VMS - , mode, "ctxt=bin", "shr=nil" + , mode, "ctxt=bin", "shr=nil" #else - , mode + , mode #endif - ); - if (fd < 0) - return NULL; - return fdopen(fd, "wb"); + ); + if (fd < 0) + return NULL; + return fdopen(fd, "wb"); #else - /* Best we can do -- on Windows this can't happen anyway */ - return fopen(filename, "wb"); + /* Best we can do -- on Windows this can't happen anyway */ + return fopen(filename, "wb"); #endif } @@ -1127,116 +1127,116 @@ static void write_compiled_module(PyCodeObject *co, char *cpathname, struct stat *srcstat) { - FILE *fp; - char *dirpath; - time_t mtime = srcstat->st_mtime; + FILE *fp; + char *dirpath; + time_t mtime = srcstat->st_mtime; #ifdef MS_WINDOWS /* since Windows uses different permissions */ - mode_t mode = srcstat->st_mode & ~S_IEXEC; - mode_t dirmode = srcstat->st_mode | S_IEXEC; /* XXX Is this correct - for Windows? - 2010-04-07 BAW */ + mode_t mode = srcstat->st_mode & ~S_IEXEC; + mode_t dirmode = srcstat->st_mode | S_IEXEC; /* XXX Is this correct + for Windows? + 2010-04-07 BAW */ #else - mode_t mode = srcstat->st_mode & ~S_IXUSR & ~S_IXGRP & ~S_IXOTH; - mode_t dirmode = (srcstat->st_mode | - S_IXUSR | S_IXGRP | S_IXOTH | - S_IWUSR | S_IWGRP | S_IWOTH); -#endif - int saved; - - /* Ensure that the __pycache__ directory exists. */ - dirpath = rightmost_sep(cpathname); - if (dirpath == NULL) { - if (Py_VerboseFlag) - PySys_WriteStderr( - "# no %s path found %s\n", - CACHEDIR, cpathname); - return; - } - saved = *dirpath; - *dirpath = '\0'; - /* XXX call os.mkdir() or maybe CreateDirectoryA() on Windows? */ - if (mkdir(cpathname, dirmode) < 0 && errno != EEXIST) { - *dirpath = saved; - if (Py_VerboseFlag) - PySys_WriteStderr( - "# cannot create cache dir %s\n", cpathname); - return; - } - *dirpath = saved; - - fp = open_exclusive(cpathname, mode); - if (fp == NULL) { - if (Py_VerboseFlag) - PySys_WriteStderr( - "# can't create %s\n", cpathname); - return; - } - PyMarshal_WriteLongToFile(pyc_magic, fp, Py_MARSHAL_VERSION); - /* First write a 0 for mtime */ - PyMarshal_WriteLongToFile(0L, fp, Py_MARSHAL_VERSION); - PyMarshal_WriteObjectToFile((PyObject *)co, fp, Py_MARSHAL_VERSION); - if (fflush(fp) != 0 || ferror(fp)) { - if (Py_VerboseFlag) - PySys_WriteStderr("# can't write %s\n", cpathname); - /* Don't keep partial file */ - fclose(fp); - (void) unlink(cpathname); - return; - } - /* Now write the true mtime */ - fseek(fp, 4L, 0); - assert(mtime < LONG_MAX); - PyMarshal_WriteLongToFile((long)mtime, fp, Py_MARSHAL_VERSION); - fflush(fp); - fclose(fp); - if (Py_VerboseFlag) - PySys_WriteStderr("# wrote %s\n", cpathname); + mode_t mode = srcstat->st_mode & ~S_IXUSR & ~S_IXGRP & ~S_IXOTH; + mode_t dirmode = (srcstat->st_mode | + S_IXUSR | S_IXGRP | S_IXOTH | + S_IWUSR | S_IWGRP | S_IWOTH); +#endif + int saved; + + /* Ensure that the __pycache__ directory exists. */ + dirpath = rightmost_sep(cpathname); + if (dirpath == NULL) { + if (Py_VerboseFlag) + PySys_WriteStderr( + "# no %s path found %s\n", + CACHEDIR, cpathname); + return; + } + saved = *dirpath; + *dirpath = '\0'; + /* XXX call os.mkdir() or maybe CreateDirectoryA() on Windows? */ + if (mkdir(cpathname, dirmode) < 0 && errno != EEXIST) { + *dirpath = saved; + if (Py_VerboseFlag) + PySys_WriteStderr( + "# cannot create cache dir %s\n", cpathname); + return; + } + *dirpath = saved; + + fp = open_exclusive(cpathname, mode); + if (fp == NULL) { + if (Py_VerboseFlag) + PySys_WriteStderr( + "# can't create %s\n", cpathname); + return; + } + PyMarshal_WriteLongToFile(pyc_magic, fp, Py_MARSHAL_VERSION); + /* First write a 0 for mtime */ + PyMarshal_WriteLongToFile(0L, fp, Py_MARSHAL_VERSION); + PyMarshal_WriteObjectToFile((PyObject *)co, fp, Py_MARSHAL_VERSION); + if (fflush(fp) != 0 || ferror(fp)) { + if (Py_VerboseFlag) + PySys_WriteStderr("# can't write %s\n", cpathname); + /* Don't keep partial file */ + fclose(fp); + (void) unlink(cpathname); + return; + } + /* Now write the true mtime */ + fseek(fp, 4L, 0); + assert(mtime < LONG_MAX); + PyMarshal_WriteLongToFile((long)mtime, fp, Py_MARSHAL_VERSION); + fflush(fp); + fclose(fp); + if (Py_VerboseFlag) + PySys_WriteStderr("# wrote %s\n", cpathname); } static void update_code_filenames(PyCodeObject *co, PyObject *oldname, PyObject *newname) { - PyObject *constants, *tmp; - Py_ssize_t i, n; + PyObject *constants, *tmp; + Py_ssize_t i, n; - if (PyUnicode_Compare(co->co_filename, oldname)) - return; + if (PyUnicode_Compare(co->co_filename, oldname)) + return; - tmp = co->co_filename; - co->co_filename = newname; - Py_INCREF(co->co_filename); - Py_DECREF(tmp); - - constants = co->co_consts; - n = PyTuple_GET_SIZE(constants); - for (i = 0; i < n; i++) { - tmp = PyTuple_GET_ITEM(constants, i); - if (PyCode_Check(tmp)) - update_code_filenames((PyCodeObject *)tmp, - oldname, newname); - } + tmp = co->co_filename; + co->co_filename = newname; + Py_INCREF(co->co_filename); + Py_DECREF(tmp); + + constants = co->co_consts; + n = PyTuple_GET_SIZE(constants); + for (i = 0; i < n; i++) { + tmp = PyTuple_GET_ITEM(constants, i); + if (PyCode_Check(tmp)) + update_code_filenames((PyCodeObject *)tmp, + oldname, newname); + } } static int update_compiled_module(PyCodeObject *co, char *pathname) { - PyObject *oldname, *newname; + PyObject *oldname, *newname; - newname = PyUnicode_DecodeFSDefault(pathname); - if (newname == NULL) - return -1; - - if (!PyUnicode_Compare(co->co_filename, newname)) { - Py_DECREF(newname); - return 0; - } - - oldname = co->co_filename; - Py_INCREF(oldname); - update_code_filenames(co, oldname, newname); - Py_DECREF(oldname); - Py_DECREF(newname); - return 1; + newname = PyUnicode_DecodeFSDefault(pathname); + if (newname == NULL) + return -1; + + if (!PyUnicode_Compare(co->co_filename, newname)) { + Py_DECREF(newname); + return 0; + } + + oldname = co->co_filename; + Py_INCREF(oldname); + update_code_filenames(co, oldname, newname); + Py_DECREF(oldname); + Py_DECREF(newname); + return 1; } /* Load a source module from a given file and return its module @@ -1246,63 +1246,63 @@ static PyObject * load_source_module(char *name, char *pathname, FILE *fp) { - struct stat st; - FILE *fpc; - char buf[MAXPATHLEN+1]; - char *cpathname; - PyCodeObject *co; - PyObject *m; - - if (fstat(fileno(fp), &st) != 0) { - PyErr_Format(PyExc_RuntimeError, - "unable to get file status from '%s'", - pathname); - return NULL; - } + struct stat st; + FILE *fpc; + char buf[MAXPATHLEN+1]; + char *cpathname; + PyCodeObject *co; + PyObject *m; + + if (fstat(fileno(fp), &st) != 0) { + PyErr_Format(PyExc_RuntimeError, + "unable to get file status from '%s'", + pathname); + return NULL; + } #if SIZEOF_TIME_T > 4 - /* Python's .pyc timestamp handling presumes that the timestamp fits - in 4 bytes. This will be fine until sometime in the year 2038, - when a 4-byte signed time_t will overflow. - */ - if (st.st_mtime >> 32) { - PyErr_SetString(PyExc_OverflowError, - "modification time overflows a 4 byte field"); - return NULL; - } -#endif - cpathname = make_compiled_pathname( - pathname, buf, (size_t)MAXPATHLEN + 1, !Py_OptimizeFlag); - if (cpathname != NULL && - (fpc = check_compiled_module(pathname, st.st_mtime, cpathname))) { - co = read_compiled_module(cpathname, fpc); - fclose(fpc); - if (co == NULL) - return NULL; - if (update_compiled_module(co, pathname) < 0) - return NULL; - if (Py_VerboseFlag) - PySys_WriteStderr("import %s # precompiled from %s\n", - name, cpathname); - pathname = cpathname; - } - else { - co = parse_source_module(pathname, fp); - if (co == NULL) - return NULL; - if (Py_VerboseFlag) - PySys_WriteStderr("import %s # from %s\n", - name, pathname); - if (cpathname) { - PyObject *ro = PySys_GetObject("dont_write_bytecode"); - if (ro == NULL || !PyObject_IsTrue(ro)) - write_compiled_module(co, cpathname, &st); - } - } - m = PyImport_ExecCodeModuleWithPathnames( - name, (PyObject *)co, pathname, cpathname); - Py_DECREF(co); + /* Python's .pyc timestamp handling presumes that the timestamp fits + in 4 bytes. This will be fine until sometime in the year 2038, + when a 4-byte signed time_t will overflow. + */ + if (st.st_mtime >> 32) { + PyErr_SetString(PyExc_OverflowError, + "modification time overflows a 4 byte field"); + return NULL; + } +#endif + cpathname = make_compiled_pathname( + pathname, buf, (size_t)MAXPATHLEN + 1, !Py_OptimizeFlag); + if (cpathname != NULL && + (fpc = check_compiled_module(pathname, st.st_mtime, cpathname))) { + co = read_compiled_module(cpathname, fpc); + fclose(fpc); + if (co == NULL) + return NULL; + if (update_compiled_module(co, pathname) < 0) + return NULL; + if (Py_VerboseFlag) + PySys_WriteStderr("import %s # precompiled from %s\n", + name, cpathname); + pathname = cpathname; + } + else { + co = parse_source_module(pathname, fp); + if (co == NULL) + return NULL; + if (Py_VerboseFlag) + PySys_WriteStderr("import %s # from %s\n", + name, pathname); + if (cpathname) { + PyObject *ro = PySys_GetObject("dont_write_bytecode"); + if (ro == NULL || !PyObject_IsTrue(ro)) + write_compiled_module(co, cpathname, &st); + } + } + m = PyImport_ExecCodeModuleWithPathnames( + name, (PyObject *)co, pathname, cpathname); + Py_DECREF(co); - return m; + return m; } /* Get source file -> unicode or None @@ -1311,44 +1311,44 @@ static PyObject * get_sourcefile(char *file) { - char py[MAXPATHLEN + 1]; - Py_ssize_t len; - PyObject *u; - struct stat statbuf; - - if (!file || !*file) { - Py_RETURN_NONE; - } - - len = strlen(file); - /* match '*.py?' */ - if (len > MAXPATHLEN || PyOS_strnicmp(&file[len-4], ".py", 3) != 0) { - return PyUnicode_DecodeFSDefault(file); - } - - /* Start by trying to turn PEP 3147 path into source path. If that - * fails, just chop off the trailing character, i.e. legacy pyc path - * to py. - */ - if (make_source_pathname(file, py) == NULL) { - strncpy(py, file, len-1); - py[len-1] = '\0'; - } - - if (stat(py, &statbuf) == 0 && - S_ISREG(statbuf.st_mode)) { - u = PyUnicode_DecodeFSDefault(py); - } - else { - u = PyUnicode_DecodeFSDefault(file); - } - return u; + char py[MAXPATHLEN + 1]; + Py_ssize_t len; + PyObject *u; + struct stat statbuf; + + if (!file || !*file) { + Py_RETURN_NONE; + } + + len = strlen(file); + /* match '*.py?' */ + if (len > MAXPATHLEN || PyOS_strnicmp(&file[len-4], ".py", 3) != 0) { + return PyUnicode_DecodeFSDefault(file); + } + + /* Start by trying to turn PEP 3147 path into source path. If that + * fails, just chop off the trailing character, i.e. legacy pyc path + * to py. + */ + if (make_source_pathname(file, py) == NULL) { + strncpy(py, file, len-1); + py[len-1] = '\0'; + } + + if (stat(py, &statbuf) == 0 && + S_ISREG(statbuf.st_mode)) { + u = PyUnicode_DecodeFSDefault(py); + } + else { + u = PyUnicode_DecodeFSDefault(file); + } + return u; } /* Forward */ static PyObject *load_module(char *, FILE *, char *, int, PyObject *); static struct filedescr *find_module(char *, char *, PyObject *, - char *, size_t, FILE **, PyObject **); + char *, size_t, FILE **, PyObject **); static struct _frozen * find_frozen(char *); /* Load a package and return its module object WITH INCREMENTED @@ -1357,54 +1357,54 @@ static PyObject * load_package(char *name, char *pathname) { - PyObject *m, *d; - PyObject *file = NULL; - PyObject *path = NULL; - int err; - char buf[MAXPATHLEN+1]; - FILE *fp = NULL; - struct filedescr *fdp; - - m = PyImport_AddModule(name); - if (m == NULL) - return NULL; - if (Py_VerboseFlag) - PySys_WriteStderr("import %s # directory %s\n", - name, pathname); - d = PyModule_GetDict(m); - file = get_sourcefile(pathname); - if (file == NULL) - goto error; - path = Py_BuildValue("[O]", file); - if (path == NULL) - goto error; - err = PyDict_SetItemString(d, "__file__", file); - if (err == 0) - err = PyDict_SetItemString(d, "__path__", path); - if (err != 0) - goto error; - buf[0] = '\0'; - fdp = find_module(name, "__init__", path, buf, sizeof(buf), &fp, NULL); - if (fdp == NULL) { - if (PyErr_ExceptionMatches(PyExc_ImportError)) { - PyErr_Clear(); - Py_INCREF(m); - } - else - m = NULL; - goto cleanup; - } - m = load_module(name, fp, buf, fdp->type, NULL); - if (fp != NULL) - fclose(fp); - goto cleanup; + PyObject *m, *d; + PyObject *file = NULL; + PyObject *path = NULL; + int err; + char buf[MAXPATHLEN+1]; + FILE *fp = NULL; + struct filedescr *fdp; + + m = PyImport_AddModule(name); + if (m == NULL) + return NULL; + if (Py_VerboseFlag) + PySys_WriteStderr("import %s # directory %s\n", + name, pathname); + d = PyModule_GetDict(m); + file = get_sourcefile(pathname); + if (file == NULL) + goto error; + path = Py_BuildValue("[O]", file); + if (path == NULL) + goto error; + err = PyDict_SetItemString(d, "__file__", file); + if (err == 0) + err = PyDict_SetItemString(d, "__path__", path); + if (err != 0) + goto error; + buf[0] = '\0'; + fdp = find_module(name, "__init__", path, buf, sizeof(buf), &fp, NULL); + if (fdp == NULL) { + if (PyErr_ExceptionMatches(PyExc_ImportError)) { + PyErr_Clear(); + Py_INCREF(m); + } + else + m = NULL; + goto cleanup; + } + m = load_module(name, fp, buf, fdp->type, NULL); + if (fp != NULL) + fclose(fp); + goto cleanup; error: - m = NULL; + m = NULL; cleanup: - Py_XDECREF(path); - Py_XDECREF(file); - return m; + Py_XDECREF(path); + Py_XDECREF(file); + return m; } @@ -1413,16 +1413,16 @@ static int is_builtin(char *name) { - int i; - for (i = 0; PyImport_Inittab[i].name != NULL; i++) { - if (strcmp(name, PyImport_Inittab[i].name) == 0) { - if (PyImport_Inittab[i].initfunc == NULL) - return -1; - else - return 1; - } - } - return 0; + int i; + for (i = 0; PyImport_Inittab[i].name != NULL; i++) { + if (strcmp(name, PyImport_Inittab[i].name) == 0) { + if (PyImport_Inittab[i].initfunc == NULL) + return -1; + else + return 1; + } + } + return 0; } @@ -1436,72 +1436,72 @@ static PyObject * get_path_importer(PyObject *path_importer_cache, PyObject *path_hooks, - PyObject *p) + PyObject *p) { - PyObject *importer; - Py_ssize_t j, nhooks; + PyObject *importer; + Py_ssize_t j, nhooks; - /* These conditions are the caller's responsibility: */ - assert(PyList_Check(path_hooks)); - assert(PyDict_Check(path_importer_cache)); - - nhooks = PyList_Size(path_hooks); - if (nhooks < 0) - return NULL; /* Shouldn't happen */ - - importer = PyDict_GetItem(path_importer_cache, p); - if (importer != NULL) - return importer; - - /* set path_importer_cache[p] to None to avoid recursion */ - if (PyDict_SetItem(path_importer_cache, p, Py_None) != 0) - return NULL; - - for (j = 0; j < nhooks; j++) { - PyObject *hook = PyList_GetItem(path_hooks, j); - if (hook == NULL) - return NULL; - importer = PyObject_CallFunctionObjArgs(hook, p, NULL); - if (importer != NULL) - break; - - if (!PyErr_ExceptionMatches(PyExc_ImportError)) { - return NULL; - } - PyErr_Clear(); - } - if (importer == NULL) { - importer = PyObject_CallFunctionObjArgs( - (PyObject *)&PyNullImporter_Type, p, NULL - ); - if (importer == NULL) { - if (PyErr_ExceptionMatches(PyExc_ImportError)) { - PyErr_Clear(); - return Py_None; - } - } - } - if (importer != NULL) { - int err = PyDict_SetItem(path_importer_cache, p, importer); - Py_DECREF(importer); - if (err != 0) - return NULL; - } - return importer; + /* These conditions are the caller's responsibility: */ + assert(PyList_Check(path_hooks)); + assert(PyDict_Check(path_importer_cache)); + + nhooks = PyList_Size(path_hooks); + if (nhooks < 0) + return NULL; /* Shouldn't happen */ + + importer = PyDict_GetItem(path_importer_cache, p); + if (importer != NULL) + return importer; + + /* set path_importer_cache[p] to None to avoid recursion */ + if (PyDict_SetItem(path_importer_cache, p, Py_None) != 0) + return NULL; + + for (j = 0; j < nhooks; j++) { + PyObject *hook = PyList_GetItem(path_hooks, j); + if (hook == NULL) + return NULL; + importer = PyObject_CallFunctionObjArgs(hook, p, NULL); + if (importer != NULL) + break; + + if (!PyErr_ExceptionMatches(PyExc_ImportError)) { + return NULL; + } + PyErr_Clear(); + } + if (importer == NULL) { + importer = PyObject_CallFunctionObjArgs( + (PyObject *)&PyNullImporter_Type, p, NULL + ); + if (importer == NULL) { + if (PyErr_ExceptionMatches(PyExc_ImportError)) { + PyErr_Clear(); + return Py_None; + } + } + } + if (importer != NULL) { + int err = PyDict_SetItem(path_importer_cache, p, importer); + Py_DECREF(importer); + if (err != 0) + return NULL; + } + return importer; } PyAPI_FUNC(PyObject *) PyImport_GetImporter(PyObject *path) { - PyObject *importer=NULL, *path_importer_cache=NULL, *path_hooks=NULL; + PyObject *importer=NULL, *path_importer_cache=NULL, *path_hooks=NULL; - if ((path_importer_cache = PySys_GetObject("path_importer_cache"))) { - if ((path_hooks = PySys_GetObject("path_hooks"))) { - importer = get_path_importer(path_importer_cache, - path_hooks, path); - } - } - Py_XINCREF(importer); /* get_path_importer returns a borrowed reference */ - return importer; + if ((path_importer_cache = PySys_GetObject("path_importer_cache"))) { + if ((path_hooks = PySys_GetObject("path_hooks"))) { + importer = get_path_importer(path_importer_cache, + path_hooks, path); + } + } + Py_XINCREF(importer); /* get_path_importer returns a borrowed reference */ + return importer; } /* Search the path (default sys.path) for a module. Return the @@ -1510,7 +1510,7 @@ #ifdef MS_COREDLL extern FILE *PyWin_FindRegisteredModule(const char *, struct filedescr **, - char *, Py_ssize_t); + char *, Py_ssize_t); #endif static int case_ok(char *, Py_ssize_t, Py_ssize_t, char *); @@ -1519,276 +1519,276 @@ static struct filedescr * find_module(char *fullname, char *subname, PyObject *path, char *buf, - size_t buflen, FILE **p_fp, PyObject **p_loader) + size_t buflen, FILE **p_fp, PyObject **p_loader) { - Py_ssize_t i, npath; - size_t len, namelen; - struct filedescr *fdp = NULL; - char *filemode; - FILE *fp = NULL; - PyObject *path_hooks, *path_importer_cache; - struct stat statbuf; - static struct filedescr fd_frozen = {"", "", PY_FROZEN}; - static struct filedescr fd_builtin = {"", "", C_BUILTIN}; - static struct filedescr fd_package = {"", "", PKG_DIRECTORY}; - char name[MAXPATHLEN+1]; + Py_ssize_t i, npath; + size_t len, namelen; + struct filedescr *fdp = NULL; + char *filemode; + FILE *fp = NULL; + PyObject *path_hooks, *path_importer_cache; + struct stat statbuf; + static struct filedescr fd_frozen = {"", "", PY_FROZEN}; + static struct filedescr fd_builtin = {"", "", C_BUILTIN}; + static struct filedescr fd_package = {"", "", PKG_DIRECTORY}; + char name[MAXPATHLEN+1]; #if defined(PYOS_OS2) - size_t saved_len; - size_t saved_namelen; - char *saved_buf = NULL; -#endif - if (p_loader != NULL) - *p_loader = NULL; - - if (strlen(subname) > MAXPATHLEN) { - PyErr_SetString(PyExc_OverflowError, - "module name is too long"); - return NULL; - } - strcpy(name, subname); - - /* sys.meta_path import hook */ - if (p_loader != NULL) { - PyObject *meta_path; - - meta_path = PySys_GetObject("meta_path"); - if (meta_path == NULL || !PyList_Check(meta_path)) { - PyErr_SetString(PyExc_ImportError, - "sys.meta_path must be a list of " - "import hooks"); - return NULL; - } - Py_INCREF(meta_path); /* zap guard */ - npath = PyList_Size(meta_path); - for (i = 0; i < npath; i++) { - PyObject *loader; - PyObject *hook = PyList_GetItem(meta_path, i); - loader = PyObject_CallMethod(hook, "find_module", - "sO", fullname, - path != NULL ? - path : Py_None); - if (loader == NULL) { - Py_DECREF(meta_path); - return NULL; /* true error */ - } - if (loader != Py_None) { - /* a loader was found */ - *p_loader = loader; - Py_DECREF(meta_path); - return &importhookdescr; - } - Py_DECREF(loader); - } - Py_DECREF(meta_path); - } - - if (find_frozen(fullname) != NULL) { - strcpy(buf, fullname); - return &fd_frozen; - } - - if (path == NULL) { - if (is_builtin(name)) { - strcpy(buf, name); - return &fd_builtin; - } + size_t saved_len; + size_t saved_namelen; + char *saved_buf = NULL; +#endif + if (p_loader != NULL) + *p_loader = NULL; + + if (strlen(subname) > MAXPATHLEN) { + PyErr_SetString(PyExc_OverflowError, + "module name is too long"); + return NULL; + } + strcpy(name, subname); + + /* sys.meta_path import hook */ + if (p_loader != NULL) { + PyObject *meta_path; + + meta_path = PySys_GetObject("meta_path"); + if (meta_path == NULL || !PyList_Check(meta_path)) { + PyErr_SetString(PyExc_ImportError, + "sys.meta_path must be a list of " + "import hooks"); + return NULL; + } + Py_INCREF(meta_path); /* zap guard */ + npath = PyList_Size(meta_path); + for (i = 0; i < npath; i++) { + PyObject *loader; + PyObject *hook = PyList_GetItem(meta_path, i); + loader = PyObject_CallMethod(hook, "find_module", + "sO", fullname, + path != NULL ? + path : Py_None); + if (loader == NULL) { + Py_DECREF(meta_path); + return NULL; /* true error */ + } + if (loader != Py_None) { + /* a loader was found */ + *p_loader = loader; + Py_DECREF(meta_path); + return &importhookdescr; + } + Py_DECREF(loader); + } + Py_DECREF(meta_path); + } + + if (find_frozen(fullname) != NULL) { + strcpy(buf, fullname); + return &fd_frozen; + } + + if (path == NULL) { + if (is_builtin(name)) { + strcpy(buf, name); + return &fd_builtin; + } #ifdef MS_COREDLL - fp = PyWin_FindRegisteredModule(name, &fdp, buf, buflen); - if (fp != NULL) { - *p_fp = fp; - return fdp; - } -#endif - path = PySys_GetObject("path"); - } - - if (path == NULL || !PyList_Check(path)) { - PyErr_SetString(PyExc_ImportError, - "sys.path must be a list of directory names"); - return NULL; - } - - path_hooks = PySys_GetObject("path_hooks"); - if (path_hooks == NULL || !PyList_Check(path_hooks)) { - PyErr_SetString(PyExc_ImportError, - "sys.path_hooks must be a list of " - "import hooks"); - return NULL; - } - path_importer_cache = PySys_GetObject("path_importer_cache"); - if (path_importer_cache == NULL || - !PyDict_Check(path_importer_cache)) { - PyErr_SetString(PyExc_ImportError, - "sys.path_importer_cache must be a dict"); - return NULL; - } - - npath = PyList_Size(path); - namelen = strlen(name); - for (i = 0; i < npath; i++) { - PyObject *v = PyList_GetItem(path, i); - PyObject *origv = v; - const char *base; - Py_ssize_t size; - if (!v) - return NULL; - if (PyUnicode_Check(v)) { - v = PyUnicode_AsEncodedString(v, - Py_FileSystemDefaultEncoding, NULL); - if (v == NULL) - return NULL; - } - else if (!PyBytes_Check(v)) - continue; - else - Py_INCREF(v); - - base = PyBytes_AS_STRING(v); - size = PyBytes_GET_SIZE(v); - len = size; - if (len + 2 + namelen + MAXSUFFIXSIZE >= buflen) { - Py_DECREF(v); - continue; /* Too long */ - } - strcpy(buf, base); - Py_DECREF(v); - - if (strlen(buf) != len) { - continue; /* v contains '\0' */ - } - - /* sys.path_hooks import hook */ - if (p_loader != NULL) { - PyObject *importer; - - importer = get_path_importer(path_importer_cache, - path_hooks, origv); - if (importer == NULL) { - return NULL; - } - /* Note: importer is a borrowed reference */ - if (importer != Py_None) { - PyObject *loader; - loader = PyObject_CallMethod(importer, - "find_module", - "s", fullname); - if (loader == NULL) - return NULL; /* error */ - if (loader != Py_None) { - /* a loader was found */ - *p_loader = loader; - return &importhookdescr; - } - Py_DECREF(loader); - continue; - } - } - /* no hook was found, use builtin import */ + fp = PyWin_FindRegisteredModule(name, &fdp, buf, buflen); + if (fp != NULL) { + *p_fp = fp; + return fdp; + } +#endif + path = PySys_GetObject("path"); + } + + if (path == NULL || !PyList_Check(path)) { + PyErr_SetString(PyExc_ImportError, + "sys.path must be a list of directory names"); + return NULL; + } + + path_hooks = PySys_GetObject("path_hooks"); + if (path_hooks == NULL || !PyList_Check(path_hooks)) { + PyErr_SetString(PyExc_ImportError, + "sys.path_hooks must be a list of " + "import hooks"); + return NULL; + } + path_importer_cache = PySys_GetObject("path_importer_cache"); + if (path_importer_cache == NULL || + !PyDict_Check(path_importer_cache)) { + PyErr_SetString(PyExc_ImportError, + "sys.path_importer_cache must be a dict"); + return NULL; + } + + npath = PyList_Size(path); + namelen = strlen(name); + for (i = 0; i < npath; i++) { + PyObject *v = PyList_GetItem(path, i); + PyObject *origv = v; + const char *base; + Py_ssize_t size; + if (!v) + return NULL; + if (PyUnicode_Check(v)) { + v = PyUnicode_AsEncodedString(v, + Py_FileSystemDefaultEncoding, NULL); + if (v == NULL) + return NULL; + } + else if (!PyBytes_Check(v)) + continue; + else + Py_INCREF(v); + + base = PyBytes_AS_STRING(v); + size = PyBytes_GET_SIZE(v); + len = size; + if (len + 2 + namelen + MAXSUFFIXSIZE >= buflen) { + Py_DECREF(v); + continue; /* Too long */ + } + strcpy(buf, base); + Py_DECREF(v); + + if (strlen(buf) != len) { + continue; /* v contains '\0' */ + } + + /* sys.path_hooks import hook */ + if (p_loader != NULL) { + PyObject *importer; + + importer = get_path_importer(path_importer_cache, + path_hooks, origv); + if (importer == NULL) { + return NULL; + } + /* Note: importer is a borrowed reference */ + if (importer != Py_None) { + PyObject *loader; + loader = PyObject_CallMethod(importer, + "find_module", + "s", fullname); + if (loader == NULL) + return NULL; /* error */ + if (loader != Py_None) { + /* a loader was found */ + *p_loader = loader; + return &importhookdescr; + } + Py_DECREF(loader); + continue; + } + } + /* no hook was found, use builtin import */ - if (len > 0 && buf[len-1] != SEP + if (len > 0 && buf[len-1] != SEP #ifdef ALTSEP - && buf[len-1] != ALTSEP + && buf[len-1] != ALTSEP #endif - ) - buf[len++] = SEP; - strcpy(buf+len, name); - len += namelen; + ) + buf[len++] = SEP; + strcpy(buf+len, name); + len += namelen; - /* Check for package import (buf holds a directory name, - and there's an __init__ module in that directory */ + /* Check for package import (buf holds a directory name, + and there's an __init__ module in that directory */ #ifdef HAVE_STAT - if (stat(buf, &statbuf) == 0 && /* it exists */ - S_ISDIR(statbuf.st_mode) && /* it's a directory */ - case_ok(buf, len, namelen, name)) { /* case matches */ - if (find_init_module(buf)) { /* and has __init__.py */ - return &fd_package; - } - else { - char warnstr[MAXPATHLEN+80]; - sprintf(warnstr, "Not importing directory " - "'%.*s': missing __init__.py", - MAXPATHLEN, buf); - if (PyErr_WarnEx(PyExc_ImportWarning, - warnstr, 1)) { - return NULL; - } - } - } + if (stat(buf, &statbuf) == 0 && /* it exists */ + S_ISDIR(statbuf.st_mode) && /* it's a directory */ + case_ok(buf, len, namelen, name)) { /* case matches */ + if (find_init_module(buf)) { /* and has __init__.py */ + return &fd_package; + } + else { + char warnstr[MAXPATHLEN+80]; + sprintf(warnstr, "Not importing directory " + "'%.*s': missing __init__.py", + MAXPATHLEN, buf); + if (PyErr_WarnEx(PyExc_ImportWarning, + warnstr, 1)) { + return NULL; + } + } + } #endif #if defined(PYOS_OS2) - /* take a snapshot of the module spec for restoration - * after the 8 character DLL hackery - */ - saved_buf = strdup(buf); - saved_len = len; - saved_namelen = namelen; + /* take a snapshot of the module spec for restoration + * after the 8 character DLL hackery + */ + saved_buf = strdup(buf); + saved_len = len; + saved_namelen = namelen; #endif /* PYOS_OS2 */ - for (fdp = _PyImport_Filetab; fdp->suffix != NULL; fdp++) { + for (fdp = _PyImport_Filetab; fdp->suffix != NULL; fdp++) { #if defined(PYOS_OS2) && defined(HAVE_DYNAMIC_LOADING) - /* OS/2 limits DLLs to 8 character names (w/o - extension) - * so if the name is longer than that and its a - * dynamically loaded module we're going to try, - * truncate the name before trying - */ - if (strlen(subname) > 8) { - /* is this an attempt to load a C extension? */ - const struct filedescr *scan; - scan = _PyImport_DynLoadFiletab; - while (scan->suffix != NULL) { - if (!strcmp(scan->suffix, fdp->suffix)) - break; - else - scan++; - } - if (scan->suffix != NULL) { - /* yes, so truncate the name */ - namelen = 8; - len -= strlen(subname) - namelen; - buf[len] = '\0'; - } - } + /* OS/2 limits DLLs to 8 character names (w/o + extension) + * so if the name is longer than that and its a + * dynamically loaded module we're going to try, + * truncate the name before trying + */ + if (strlen(subname) > 8) { + /* is this an attempt to load a C extension? */ + const struct filedescr *scan; + scan = _PyImport_DynLoadFiletab; + while (scan->suffix != NULL) { + if (!strcmp(scan->suffix, fdp->suffix)) + break; + else + scan++; + } + if (scan->suffix != NULL) { + /* yes, so truncate the name */ + namelen = 8; + len -= strlen(subname) - namelen; + buf[len] = '\0'; + } + } #endif /* PYOS_OS2 */ - strcpy(buf+len, fdp->suffix); - if (Py_VerboseFlag > 1) - PySys_WriteStderr("# trying %s\n", buf); - filemode = fdp->mode; - if (filemode[0] == 'U') - filemode = "r" PY_STDIOTEXTMODE; - fp = fopen(buf, filemode); - if (fp != NULL) { - if (case_ok(buf, len, namelen, name)) - break; - else { /* continue search */ - fclose(fp); - fp = NULL; - } - } + strcpy(buf+len, fdp->suffix); + if (Py_VerboseFlag > 1) + PySys_WriteStderr("# trying %s\n", buf); + filemode = fdp->mode; + if (filemode[0] == 'U') + filemode = "r" PY_STDIOTEXTMODE; + fp = fopen(buf, filemode); + if (fp != NULL) { + if (case_ok(buf, len, namelen, name)) + break; + else { /* continue search */ + fclose(fp); + fp = NULL; + } + } #if defined(PYOS_OS2) - /* restore the saved snapshot */ - strcpy(buf, saved_buf); - len = saved_len; - namelen = saved_namelen; + /* restore the saved snapshot */ + strcpy(buf, saved_buf); + len = saved_len; + namelen = saved_namelen; #endif - } + } #if defined(PYOS_OS2) - /* don't need/want the module name snapshot anymore */ - if (saved_buf) - { - free(saved_buf); - saved_buf = NULL; - } -#endif - if (fp != NULL) - break; - } - if (fp == NULL) { - PyErr_Format(PyExc_ImportError, - "No module named %.200s", name); - return NULL; - } - *p_fp = fp; - return fdp; + /* don't need/want the module name snapshot anymore */ + if (saved_buf) + { + free(saved_buf); + saved_buf = NULL; + } +#endif + if (fp != NULL) + break; + } + if (fp == NULL) { + PyErr_Format(PyExc_ImportError, + "No module named %.200s", name); + return NULL; + } + *p_fp = fp; + return fdp; } /* Helpers for main.c @@ -1796,15 +1796,15 @@ */ struct filedescr * _PyImport_FindModule(const char *name, PyObject *path, char *buf, - size_t buflen, FILE **p_fp, PyObject **p_loader) + size_t buflen, FILE **p_fp, PyObject **p_loader) { - return find_module((char *) name, (char *) name, path, - buf, buflen, p_fp, p_loader); + return find_module((char *) name, (char *) name, path, + buf, buflen, p_fp, p_loader); } PyAPI_FUNC(int) _PyImport_IsScript(struct filedescr * fd) { - return fd->type == PY_SOURCE || fd->type == PY_COMPILED; + return fd->type == PY_SOURCE || fd->type == PY_COMPILED; } /* case_ok(char* buf, Py_ssize_t len, Py_ssize_t namelen, char* name) @@ -1860,103 +1860,103 @@ /* MS_WINDOWS */ #if defined(MS_WINDOWS) - WIN32_FIND_DATA data; - HANDLE h; + WIN32_FIND_DATA data; + HANDLE h; - if (Py_GETENV("PYTHONCASEOK") != NULL) - return 1; + if (Py_GETENV("PYTHONCASEOK") != NULL) + return 1; - h = FindFirstFile(buf, &data); - if (h == INVALID_HANDLE_VALUE) { - PyErr_Format(PyExc_NameError, - "Can't find file for module %.100s\n(filename %.300s)", - name, buf); - return 0; - } - FindClose(h); - return strncmp(data.cFileName, name, namelen) == 0; + h = FindFirstFile(buf, &data); + if (h == INVALID_HANDLE_VALUE) { + PyErr_Format(PyExc_NameError, + "Can't find file for module %.100s\n(filename %.300s)", + name, buf); + return 0; + } + FindClose(h); + return strncmp(data.cFileName, name, namelen) == 0; /* DJGPP */ #elif defined(DJGPP) - struct ffblk ffblk; - int done; + struct ffblk ffblk; + int done; - if (Py_GETENV("PYTHONCASEOK") != NULL) - return 1; + if (Py_GETENV("PYTHONCASEOK") != NULL) + return 1; - done = findfirst(buf, &ffblk, FA_ARCH|FA_RDONLY|FA_HIDDEN|FA_DIREC); - if (done) { - PyErr_Format(PyExc_NameError, - "Can't find file for module %.100s\n(filename %.300s)", - name, buf); - return 0; - } - return strncmp(ffblk.ff_name, name, namelen) == 0; + done = findfirst(buf, &ffblk, FA_ARCH|FA_RDONLY|FA_HIDDEN|FA_DIREC); + if (done) { + PyErr_Format(PyExc_NameError, + "Can't find file for module %.100s\n(filename %.300s)", + name, buf); + return 0; + } + return strncmp(ffblk.ff_name, name, namelen) == 0; /* new-fangled macintosh (macosx) or Cygwin */ #elif (defined(__MACH__) && defined(__APPLE__) || defined(__CYGWIN__)) && defined(HAVE_DIRENT_H) - DIR *dirp; - struct dirent *dp; - char dirname[MAXPATHLEN + 1]; - const int dirlen = len - namelen - 1; /* don't want trailing SEP */ - - if (Py_GETENV("PYTHONCASEOK") != NULL) - return 1; - - /* Copy the dir component into dirname; substitute "." if empty */ - if (dirlen <= 0) { - dirname[0] = '.'; - dirname[1] = '\0'; - } - else { - assert(dirlen <= MAXPATHLEN); - memcpy(dirname, buf, dirlen); - dirname[dirlen] = '\0'; - } - /* Open the directory and search the entries for an exact match. */ - dirp = opendir(dirname); - if (dirp) { - char *nameWithExt = buf + len - namelen; - while ((dp = readdir(dirp)) != NULL) { - const int thislen = + DIR *dirp; + struct dirent *dp; + char dirname[MAXPATHLEN + 1]; + const int dirlen = len - namelen - 1; /* don't want trailing SEP */ + + if (Py_GETENV("PYTHONCASEOK") != NULL) + return 1; + + /* Copy the dir component into dirname; substitute "." if empty */ + if (dirlen <= 0) { + dirname[0] = '.'; + dirname[1] = '\0'; + } + else { + assert(dirlen <= MAXPATHLEN); + memcpy(dirname, buf, dirlen); + dirname[dirlen] = '\0'; + } + /* Open the directory and search the entries for an exact match. */ + dirp = opendir(dirname); + if (dirp) { + char *nameWithExt = buf + len - namelen; + while ((dp = readdir(dirp)) != NULL) { + const int thislen = #ifdef _DIRENT_HAVE_D_NAMELEN - dp->d_namlen; + dp->d_namlen; #else - strlen(dp->d_name); + strlen(dp->d_name); #endif - if (thislen >= namelen && - strcmp(dp->d_name, nameWithExt) == 0) { - (void)closedir(dirp); - return 1; /* Found */ - } - } - (void)closedir(dirp); - } - return 0 ; /* Not found */ + if (thislen >= namelen && + strcmp(dp->d_name, nameWithExt) == 0) { + (void)closedir(dirp); + return 1; /* Found */ + } + } + (void)closedir(dirp); + } + return 0 ; /* Not found */ /* OS/2 */ #elif defined(PYOS_OS2) - HDIR hdir = 1; - ULONG srchcnt = 1; - FILEFINDBUF3 ffbuf; - APIRET rc; - - if (Py_GETENV("PYTHONCASEOK") != NULL) - return 1; - - rc = DosFindFirst(buf, - &hdir, - FILE_READONLY | FILE_HIDDEN | FILE_SYSTEM | FILE_DIRECTORY, - &ffbuf, sizeof(ffbuf), - &srchcnt, - FIL_STANDARD); - if (rc != NO_ERROR) - return 0; - return strncmp(ffbuf.achName, name, namelen) == 0; + HDIR hdir = 1; + ULONG srchcnt = 1; + FILEFINDBUF3 ffbuf; + APIRET rc; + + if (Py_GETENV("PYTHONCASEOK") != NULL) + return 1; + + rc = DosFindFirst(buf, + &hdir, + FILE_READONLY | FILE_HIDDEN | FILE_SYSTEM | FILE_DIRECTORY, + &ffbuf, sizeof(ffbuf), + &srchcnt, + FIL_STANDARD); + if (rc != NO_ERROR) + return 0; + return strncmp(ffbuf.achName, name, namelen) == 0; /* assuming it's a case-sensitive filesystem, so there's nothing to do! */ #else - return 1; + return 1; #endif } @@ -1967,46 +1967,46 @@ static int find_init_module(char *buf) { - const size_t save_len = strlen(buf); - size_t i = save_len; - char *pname; /* pointer to start of __init__ */ - struct stat statbuf; - -/* For calling case_ok(buf, len, namelen, name): - * /a/b/c/d/e/f/g/h/i/j/k/some_long_module_name.py\0 - * ^ ^ ^ ^ - * |--------------------- buf ---------------------| - * |------------------- len ------------------| - * |------ name -------| - * |----- namelen -----| + const size_t save_len = strlen(buf); + size_t i = save_len; + char *pname; /* pointer to start of __init__ */ + struct stat statbuf; + +/* For calling case_ok(buf, len, namelen, name): + * /a/b/c/d/e/f/g/h/i/j/k/some_long_module_name.py\0 + * ^ ^ ^ ^ + * |--------------------- buf ---------------------| + * |------------------- len ------------------| + * |------ name -------| + * |----- namelen -----| */ - if (save_len + 13 >= MAXPATHLEN) - return 0; - buf[i++] = SEP; - pname = buf + i; - strcpy(pname, "__init__.py"); - if (stat(buf, &statbuf) == 0) { - if (case_ok(buf, - save_len + 9, /* len("/__init__") */ - 8, /* len("__init__") */ - pname)) { - buf[save_len] = '\0'; - return 1; - } - } - i += strlen(pname); - strcpy(buf+i, Py_OptimizeFlag ? "o" : "c"); - if (stat(buf, &statbuf) == 0) { - if (case_ok(buf, - save_len + 9, /* len("/__init__") */ - 8, /* len("__init__") */ - pname)) { - buf[save_len] = '\0'; - return 1; - } - } - buf[save_len] = '\0'; - return 0; + if (save_len + 13 >= MAXPATHLEN) + return 0; + buf[i++] = SEP; + pname = buf + i; + strcpy(pname, "__init__.py"); + if (stat(buf, &statbuf) == 0) { + if (case_ok(buf, + save_len + 9, /* len("/__init__") */ + 8, /* len("__init__") */ + pname)) { + buf[save_len] = '\0'; + return 1; + } + } + i += strlen(pname); + strcpy(buf+i, Py_OptimizeFlag ? "o" : "c"); + if (stat(buf, &statbuf) == 0) { + if (case_ok(buf, + save_len + 9, /* len("/__init__") */ + 8, /* len("__init__") */ + pname)) { + buf[save_len] = '\0'; + return 1; + } + } + buf[save_len] = '\0'; + return 0; } #endif /* HAVE_STAT */ @@ -2020,93 +2020,93 @@ static PyObject * load_module(char *name, FILE *fp, char *pathname, int type, PyObject *loader) { - PyObject *modules; - PyObject *m; - int err; - - /* First check that there's an open file (if we need one) */ - switch (type) { - case PY_SOURCE: - case PY_COMPILED: - if (fp == NULL) { - PyErr_Format(PyExc_ValueError, - "file object required for import (type code %d)", - type); - return NULL; - } - } - - switch (type) { - - case PY_SOURCE: - m = load_source_module(name, pathname, fp); - break; - - case PY_COMPILED: - m = load_compiled_module(name, pathname, fp); - break; + PyObject *modules; + PyObject *m; + int err; + + /* First check that there's an open file (if we need one) */ + switch (type) { + case PY_SOURCE: + case PY_COMPILED: + if (fp == NULL) { + PyErr_Format(PyExc_ValueError, + "file object required for import (type code %d)", + type); + return NULL; + } + } + + switch (type) { + + case PY_SOURCE: + m = load_source_module(name, pathname, fp); + break; + + case PY_COMPILED: + m = load_compiled_module(name, pathname, fp); + break; #ifdef HAVE_DYNAMIC_LOADING - case C_EXTENSION: - m = _PyImport_LoadDynamicModule(name, pathname, fp); - break; -#endif - - case PKG_DIRECTORY: - m = load_package(name, pathname); - break; - - case C_BUILTIN: - case PY_FROZEN: - if (pathname != NULL && pathname[0] != '\0') - name = pathname; - if (type == C_BUILTIN) - err = init_builtin(name); - else - err = PyImport_ImportFrozenModule(name); - if (err < 0) - return NULL; - if (err == 0) { - PyErr_Format(PyExc_ImportError, - "Purported %s module %.200s not found", - type == C_BUILTIN ? - "builtin" : "frozen", - name); - return NULL; - } - modules = PyImport_GetModuleDict(); - m = PyDict_GetItemString(modules, name); - if (m == NULL) { - PyErr_Format( - PyExc_ImportError, - "%s module %.200s not properly initialized", - type == C_BUILTIN ? - "builtin" : "frozen", - name); - return NULL; - } - Py_INCREF(m); - break; - - case IMP_HOOK: { - if (loader == NULL) { - PyErr_SetString(PyExc_ImportError, - "import hook without loader"); - return NULL; - } - m = PyObject_CallMethod(loader, "load_module", "s", name); - break; - } - - default: - PyErr_Format(PyExc_ImportError, - "Don't know how to import %.200s (type code %d)", - name, type); - m = NULL; + case C_EXTENSION: + m = _PyImport_LoadDynamicModule(name, pathname, fp); + break; +#endif + + case PKG_DIRECTORY: + m = load_package(name, pathname); + break; + + case C_BUILTIN: + case PY_FROZEN: + if (pathname != NULL && pathname[0] != '\0') + name = pathname; + if (type == C_BUILTIN) + err = init_builtin(name); + else + err = PyImport_ImportFrozenModule(name); + if (err < 0) + return NULL; + if (err == 0) { + PyErr_Format(PyExc_ImportError, + "Purported %s module %.200s not found", + type == C_BUILTIN ? + "builtin" : "frozen", + name); + return NULL; + } + modules = PyImport_GetModuleDict(); + m = PyDict_GetItemString(modules, name); + if (m == NULL) { + PyErr_Format( + PyExc_ImportError, + "%s module %.200s not properly initialized", + type == C_BUILTIN ? + "builtin" : "frozen", + name); + return NULL; + } + Py_INCREF(m); + break; + + case IMP_HOOK: { + if (loader == NULL) { + PyErr_SetString(PyExc_ImportError, + "import hook without loader"); + return NULL; + } + m = PyObject_CallMethod(loader, "load_module", "s", name); + break; + } + + default: + PyErr_Format(PyExc_ImportError, + "Don't know how to import %.200s (type code %d)", + name, type); + m = NULL; - } + } - return m; + return m; } @@ -2117,34 +2117,34 @@ static int init_builtin(char *name) { - struct _inittab *p; + struct _inittab *p; - if (_PyImport_FindExtension(name, name) != NULL) - return 1; + if (_PyImport_FindExtension(name, name) != NULL) + return 1; - for (p = PyImport_Inittab; p->name != NULL; p++) { - PyObject *mod; - if (strcmp(name, p->name) == 0) { - if (p->initfunc == NULL) { - PyErr_Format(PyExc_ImportError, - "Cannot re-init internal module %.200s", - name); - return -1; - } - if (Py_VerboseFlag) - PySys_WriteStderr("import %s # builtin\n", name); - mod = (*p->initfunc)(); - if (mod == 0) - return -1; - if (_PyImport_FixupExtension(mod, name, name) < 0) - return -1; - /* FixupExtension has put the module into sys.modules, - so we can release our own reference. */ - Py_DECREF(mod); - return 1; - } - } - return 0; + for (p = PyImport_Inittab; p->name != NULL; p++) { + PyObject *mod; + if (strcmp(name, p->name) == 0) { + if (p->initfunc == NULL) { + PyErr_Format(PyExc_ImportError, + "Cannot re-init internal module %.200s", + name); + return -1; + } + if (Py_VerboseFlag) + PySys_WriteStderr("import %s # builtin\n", name); + mod = (*p->initfunc)(); + if (mod == 0) + return -1; + if (_PyImport_FixupExtension(mod, name, name) < 0) + return -1; + /* FixupExtension has put the module into sys.modules, + so we can release our own reference. */ + Py_DECREF(mod); + return 1; + } + } + return 0; } @@ -2153,63 +2153,63 @@ static struct _frozen * find_frozen(char *name) { - struct _frozen *p; + struct _frozen *p; - if (!name) - return NULL; + if (!name) + return NULL; - for (p = PyImport_FrozenModules; ; p++) { - if (p->name == NULL) - return NULL; - if (strcmp(p->name, name) == 0) - break; - } - return p; + for (p = PyImport_FrozenModules; ; p++) { + if (p->name == NULL) + return NULL; + if (strcmp(p->name, name) == 0) + break; + } + return p; } static PyObject * get_frozen_object(char *name) { - struct _frozen *p = find_frozen(name); - int size; + struct _frozen *p = find_frozen(name); + int size; - if (p == NULL) { - PyErr_Format(PyExc_ImportError, - "No such frozen object named %.200s", - name); - return NULL; - } - if (p->code == NULL) { - PyErr_Format(PyExc_ImportError, - "Excluded frozen object named %.200s", - name); - return NULL; - } - size = p->size; - if (size < 0) - size = -size; - return PyMarshal_ReadObjectFromString((char *)p->code, size); + if (p == NULL) { + PyErr_Format(PyExc_ImportError, + "No such frozen object named %.200s", + name); + return NULL; + } + if (p->code == NULL) { + PyErr_Format(PyExc_ImportError, + "Excluded frozen object named %.200s", + name); + return NULL; + } + size = p->size; + if (size < 0) + size = -size; + return PyMarshal_ReadObjectFromString((char *)p->code, size); } static PyObject * is_frozen_package(char *name) { - struct _frozen *p = find_frozen(name); - int size; + struct _frozen *p = find_frozen(name); + int size; - if (p == NULL) { - PyErr_Format(PyExc_ImportError, - "No such frozen object named %.200s", - name); - return NULL; - } - - size = p->size; - - if (size < 0) - Py_RETURN_TRUE; - else - Py_RETURN_FALSE; + if (p == NULL) { + PyErr_Format(PyExc_ImportError, + "No such frozen object named %.200s", + name); + return NULL; + } + + size = p->size; + + if (size < 0) + Py_RETURN_TRUE; + else + Py_RETURN_FALSE; } @@ -2221,67 +2221,67 @@ int PyImport_ImportFrozenModule(char *name) { - struct _frozen *p = find_frozen(name); - PyObject *co; - PyObject *m; - int ispackage; - int size; - - if (p == NULL) - return 0; - if (p->code == NULL) { - PyErr_Format(PyExc_ImportError, - "Excluded frozen object named %.200s", - name); - return -1; - } - size = p->size; - ispackage = (size < 0); - if (ispackage) - size = -size; - if (Py_VerboseFlag) - PySys_WriteStderr("import %s # frozen%s\n", - name, ispackage ? " package" : ""); - co = PyMarshal_ReadObjectFromString((char *)p->code, size); - if (co == NULL) - return -1; - if (!PyCode_Check(co)) { - PyErr_Format(PyExc_TypeError, - "frozen object %.200s is not a code object", - name); - goto err_return; - } - if (ispackage) { - /* Set __path__ to the package name */ - PyObject *d, *s, *l; - int err; - m = PyImport_AddModule(name); - if (m == NULL) - goto err_return; - d = PyModule_GetDict(m); - s = PyUnicode_InternFromString(name); - if (s == NULL) - goto err_return; - l = PyList_New(1); - if (l == NULL) { - Py_DECREF(s); - goto err_return; - } - PyList_SET_ITEM(l, 0, s); - err = PyDict_SetItemString(d, "__path__", l); - Py_DECREF(l); - if (err != 0) - goto err_return; - } - m = PyImport_ExecCodeModuleEx(name, co, ""); - if (m == NULL) - goto err_return; - Py_DECREF(co); - Py_DECREF(m); - return 1; + struct _frozen *p = find_frozen(name); + PyObject *co; + PyObject *m; + int ispackage; + int size; + + if (p == NULL) + return 0; + if (p->code == NULL) { + PyErr_Format(PyExc_ImportError, + "Excluded frozen object named %.200s", + name); + return -1; + } + size = p->size; + ispackage = (size < 0); + if (ispackage) + size = -size; + if (Py_VerboseFlag) + PySys_WriteStderr("import %s # frozen%s\n", + name, ispackage ? " package" : ""); + co = PyMarshal_ReadObjectFromString((char *)p->code, size); + if (co == NULL) + return -1; + if (!PyCode_Check(co)) { + PyErr_Format(PyExc_TypeError, + "frozen object %.200s is not a code object", + name); + goto err_return; + } + if (ispackage) { + /* Set __path__ to the package name */ + PyObject *d, *s, *l; + int err; + m = PyImport_AddModule(name); + if (m == NULL) + goto err_return; + d = PyModule_GetDict(m); + s = PyUnicode_InternFromString(name); + if (s == NULL) + goto err_return; + l = PyList_New(1); + if (l == NULL) { + Py_DECREF(s); + goto err_return; + } + PyList_SET_ITEM(l, 0, s); + err = PyDict_SetItemString(d, "__path__", l); + Py_DECREF(l); + if (err != 0) + goto err_return; + } + m = PyImport_ExecCodeModuleEx(name, co, ""); + if (m == NULL) + goto err_return; + Py_DECREF(co); + Py_DECREF(m); + return 1; err_return: - Py_DECREF(co); - return -1; + Py_DECREF(co); + return -1; } @@ -2291,15 +2291,15 @@ PyObject * PyImport_ImportModule(const char *name) { - PyObject *pname; - PyObject *result; + PyObject *pname; + PyObject *result; - pname = PyUnicode_FromString(name); - if (pname == NULL) - return NULL; - result = PyImport_Import(pname); - Py_DECREF(pname); - return result; + pname = PyUnicode_FromString(name); + if (pname == NULL) + return NULL; + result = PyImport_Import(pname); + Py_DECREF(pname); + return result; } /* Import a module without blocking @@ -2314,137 +2314,137 @@ PyObject * PyImport_ImportModuleNoBlock(const char *name) { - PyObject *result; - PyObject *modules; - long me; - - /* Try to get the module from sys.modules[name] */ - modules = PyImport_GetModuleDict(); - if (modules == NULL) - return NULL; - - result = PyDict_GetItemString(modules, name); - if (result != NULL) { - Py_INCREF(result); - return result; - } - else { - PyErr_Clear(); - } + PyObject *result; + PyObject *modules; + long me; + + /* Try to get the module from sys.modules[name] */ + modules = PyImport_GetModuleDict(); + if (modules == NULL) + return NULL; + + result = PyDict_GetItemString(modules, name); + if (result != NULL) { + Py_INCREF(result); + return result; + } + else { + PyErr_Clear(); + } #ifdef WITH_THREAD - /* check the import lock - * me might be -1 but I ignore the error here, the lock function - * takes care of the problem */ - me = PyThread_get_thread_ident(); - if (import_lock_thread == -1 || import_lock_thread == me) { - /* no thread or me is holding the lock */ - return PyImport_ImportModule(name); - } - else { - PyErr_Format(PyExc_ImportError, - "Failed to import %.200s because the import lock" - "is held by another thread.", - name); - return NULL; - } + /* check the import lock + * me might be -1 but I ignore the error here, the lock function + * takes care of the problem */ + me = PyThread_get_thread_ident(); + if (import_lock_thread == -1 || import_lock_thread == me) { + /* no thread or me is holding the lock */ + return PyImport_ImportModule(name); + } + else { + PyErr_Format(PyExc_ImportError, + "Failed to import %.200s because the import lock" + "is held by another thread.", + name); + return NULL; + } #else - return PyImport_ImportModule(name); + return PyImport_ImportModule(name); #endif } /* Forward declarations for helper routines */ static PyObject *get_parent(PyObject *globals, char *buf, - Py_ssize_t *p_buflen, int level); + Py_ssize_t *p_buflen, int level); static PyObject *load_next(PyObject *mod, PyObject *altmod, - char **p_name, char *buf, Py_ssize_t *p_buflen); + char **p_name, char *buf, Py_ssize_t *p_buflen); static int mark_miss(char *name); static int ensure_fromlist(PyObject *mod, PyObject *fromlist, - char *buf, Py_ssize_t buflen, int recursive); + char *buf, Py_ssize_t buflen, int recursive); static PyObject * import_submodule(PyObject *mod, char *name, char *fullname); /* The Magnum Opus of dotted-name import :-) */ static PyObject * import_module_level(char *name, PyObject *globals, PyObject *locals, - PyObject *fromlist, int level) + PyObject *fromlist, int level) { - char buf[MAXPATHLEN+1]; - Py_ssize_t buflen = 0; - PyObject *parent, *head, *next, *tail; + char buf[MAXPATHLEN+1]; + Py_ssize_t buflen = 0; + PyObject *parent, *head, *next, *tail; - if (strchr(name, '/') != NULL + if (strchr(name, '/') != NULL #ifdef MS_WINDOWS - || strchr(name, '\\') != NULL + || strchr(name, '\\') != NULL #endif - ) { - PyErr_SetString(PyExc_ImportError, - "Import by filename is not supported."); - return NULL; - } - - parent = get_parent(globals, buf, &buflen, level); - if (parent == NULL) - return NULL; - - head = load_next(parent, Py_None, &name, buf, &buflen); - if (head == NULL) - return NULL; - - tail = head; - Py_INCREF(tail); - while (name) { - next = load_next(tail, tail, &name, buf, &buflen); - Py_DECREF(tail); - if (next == NULL) { - Py_DECREF(head); - return NULL; - } - tail = next; - } - if (tail == Py_None) { - /* If tail is Py_None, both get_parent and load_next found - an empty module name: someone called __import__("") or - doctored faulty bytecode */ - Py_DECREF(tail); - Py_DECREF(head); - PyErr_SetString(PyExc_ValueError, - "Empty module name"); - return NULL; - } - - if (fromlist != NULL) { - if (fromlist == Py_None || !PyObject_IsTrue(fromlist)) - fromlist = NULL; - } - - if (fromlist == NULL) { - Py_DECREF(tail); - return head; - } - - Py_DECREF(head); - if (!ensure_fromlist(tail, fromlist, buf, buflen, 0)) { - Py_DECREF(tail); - return NULL; - } + ) { + PyErr_SetString(PyExc_ImportError, + "Import by filename is not supported."); + return NULL; + } + + parent = get_parent(globals, buf, &buflen, level); + if (parent == NULL) + return NULL; + + head = load_next(parent, Py_None, &name, buf, &buflen); + if (head == NULL) + return NULL; + + tail = head; + Py_INCREF(tail); + while (name) { + next = load_next(tail, tail, &name, buf, &buflen); + Py_DECREF(tail); + if (next == NULL) { + Py_DECREF(head); + return NULL; + } + tail = next; + } + if (tail == Py_None) { + /* If tail is Py_None, both get_parent and load_next found + an empty module name: someone called __import__("") or + doctored faulty bytecode */ + Py_DECREF(tail); + Py_DECREF(head); + PyErr_SetString(PyExc_ValueError, + "Empty module name"); + return NULL; + } + + if (fromlist != NULL) { + if (fromlist == Py_None || !PyObject_IsTrue(fromlist)) + fromlist = NULL; + } + + if (fromlist == NULL) { + Py_DECREF(tail); + return head; + } + + Py_DECREF(head); + if (!ensure_fromlist(tail, fromlist, buf, buflen, 0)) { + Py_DECREF(tail); + return NULL; + } - return tail; + return tail; } PyObject * PyImport_ImportModuleLevel(char *name, PyObject *globals, PyObject *locals, - PyObject *fromlist, int level) + PyObject *fromlist, int level) { - PyObject *result; - _PyImport_AcquireLock(); - result = import_module_level(name, globals, locals, fromlist, level); - if (_PyImport_ReleaseLock() < 0) { - Py_XDECREF(result); - PyErr_SetString(PyExc_RuntimeError, - "not holding the import lock"); - return NULL; - } - return result; + PyObject *result; + _PyImport_AcquireLock(); + result = import_module_level(name, globals, locals, fromlist, level); + if (_PyImport_ReleaseLock() < 0) { + Py_XDECREF(result); + PyErr_SetString(PyExc_RuntimeError, + "not holding the import lock"); + return NULL; + } + return result; } /* Return the package that an import is being performed in. If globals comes @@ -2461,420 +2461,420 @@ static PyObject * get_parent(PyObject *globals, char *buf, Py_ssize_t *p_buflen, int level) { - static PyObject *namestr = NULL; - static PyObject *pathstr = NULL; - static PyObject *pkgstr = NULL; - PyObject *pkgname, *modname, *modpath, *modules, *parent; - int orig_level = level; - - if (globals == NULL || !PyDict_Check(globals) || !level) - return Py_None; - - if (namestr == NULL) { - namestr = PyUnicode_InternFromString("__name__"); - if (namestr == NULL) - return NULL; - } - if (pathstr == NULL) { - pathstr = PyUnicode_InternFromString("__path__"); - if (pathstr == NULL) - return NULL; - } - if (pkgstr == NULL) { - pkgstr = PyUnicode_InternFromString("__package__"); - if (pkgstr == NULL) - return NULL; - } - - *buf = '\0'; - *p_buflen = 0; - pkgname = PyDict_GetItem(globals, pkgstr); - - if ((pkgname != NULL) && (pkgname != Py_None)) { - /* __package__ is set, so use it */ - char *pkgname_str; - Py_ssize_t len; - - if (!PyUnicode_Check(pkgname)) { - PyErr_SetString(PyExc_ValueError, - "__package__ set to non-string"); - return NULL; - } - pkgname_str = _PyUnicode_AsStringAndSize(pkgname, &len); - if (len == 0) { - if (level > 0) { - PyErr_SetString(PyExc_ValueError, - "Attempted relative import in non-package"); - return NULL; - } - return Py_None; - } - if (len > MAXPATHLEN) { - PyErr_SetString(PyExc_ValueError, - "Package name too long"); - return NULL; - } - strcpy(buf, pkgname_str); - } else { - /* __package__ not set, so figure it out and set it */ - modname = PyDict_GetItem(globals, namestr); - if (modname == NULL || !PyUnicode_Check(modname)) - return Py_None; - - modpath = PyDict_GetItem(globals, pathstr); - if (modpath != NULL) { - /* __path__ is set, so modname is already the package name */ - char *modname_str; - Py_ssize_t len; - int error; - - modname_str = _PyUnicode_AsStringAndSize(modname, &len); - if (len > MAXPATHLEN) { - PyErr_SetString(PyExc_ValueError, - "Module name too long"); - return NULL; - } - strcpy(buf, modname_str); - error = PyDict_SetItem(globals, pkgstr, modname); - if (error) { - PyErr_SetString(PyExc_ValueError, - "Could not set __package__"); - return NULL; - } - } else { - /* Normal module, so work out the package name if any */ - char *start = _PyUnicode_AsString(modname); - char *lastdot = strrchr(start, '.'); - size_t len; - int error; - if (lastdot == NULL && level > 0) { - PyErr_SetString(PyExc_ValueError, - "Attempted relative import in non-package"); - return NULL; - } - if (lastdot == NULL) { - error = PyDict_SetItem(globals, pkgstr, Py_None); - if (error) { - PyErr_SetString(PyExc_ValueError, - "Could not set __package__"); - return NULL; - } - return Py_None; - } - len = lastdot - start; - if (len >= MAXPATHLEN) { - PyErr_SetString(PyExc_ValueError, - "Module name too long"); - return NULL; - } - strncpy(buf, start, len); - buf[len] = '\0'; - pkgname = PyUnicode_FromString(buf); - if (pkgname == NULL) { - return NULL; - } - error = PyDict_SetItem(globals, pkgstr, pkgname); - Py_DECREF(pkgname); - if (error) { - PyErr_SetString(PyExc_ValueError, - "Could not set __package__"); - return NULL; - } - } - } - while (--level > 0) { - char *dot = strrchr(buf, '.'); - if (dot == NULL) { - PyErr_SetString(PyExc_ValueError, - "Attempted relative import beyond " - "toplevel package"); - return NULL; - } - *dot = '\0'; - } - *p_buflen = strlen(buf); - - modules = PyImport_GetModuleDict(); - parent = PyDict_GetItemString(modules, buf); - if (parent == NULL) { - if (orig_level < 1) { - PyObject *err_msg = PyBytes_FromFormat( - "Parent module '%.200s' not found " - "while handling absolute import", buf); - if (err_msg == NULL) { - return NULL; - } - if (!PyErr_WarnEx(PyExc_RuntimeWarning, - PyBytes_AsString(err_msg), 1)) { - *buf = '\0'; - *p_buflen = 0; - parent = Py_None; - } - Py_DECREF(err_msg); - } else { - PyErr_Format(PyExc_SystemError, - "Parent module '%.200s' not loaded, " - "cannot perform relative import", buf); - } - } - return parent; - /* We expect, but can't guarantee, if parent != None, that: - - parent.__name__ == buf - - parent.__dict__ is globals - If this is violated... Who cares? */ + static PyObject *namestr = NULL; + static PyObject *pathstr = NULL; + static PyObject *pkgstr = NULL; + PyObject *pkgname, *modname, *modpath, *modules, *parent; + int orig_level = level; + + if (globals == NULL || !PyDict_Check(globals) || !level) + return Py_None; + + if (namestr == NULL) { + namestr = PyUnicode_InternFromString("__name__"); + if (namestr == NULL) + return NULL; + } + if (pathstr == NULL) { + pathstr = PyUnicode_InternFromString("__path__"); + if (pathstr == NULL) + return NULL; + } + if (pkgstr == NULL) { + pkgstr = PyUnicode_InternFromString("__package__"); + if (pkgstr == NULL) + return NULL; + } + + *buf = '\0'; + *p_buflen = 0; + pkgname = PyDict_GetItem(globals, pkgstr); + + if ((pkgname != NULL) && (pkgname != Py_None)) { + /* __package__ is set, so use it */ + char *pkgname_str; + Py_ssize_t len; + + if (!PyUnicode_Check(pkgname)) { + PyErr_SetString(PyExc_ValueError, + "__package__ set to non-string"); + return NULL; + } + pkgname_str = _PyUnicode_AsStringAndSize(pkgname, &len); + if (len == 0) { + if (level > 0) { + PyErr_SetString(PyExc_ValueError, + "Attempted relative import in non-package"); + return NULL; + } + return Py_None; + } + if (len > MAXPATHLEN) { + PyErr_SetString(PyExc_ValueError, + "Package name too long"); + return NULL; + } + strcpy(buf, pkgname_str); + } else { + /* __package__ not set, so figure it out and set it */ + modname = PyDict_GetItem(globals, namestr); + if (modname == NULL || !PyUnicode_Check(modname)) + return Py_None; + + modpath = PyDict_GetItem(globals, pathstr); + if (modpath != NULL) { + /* __path__ is set, so modname is already the package name */ + char *modname_str; + Py_ssize_t len; + int error; + + modname_str = _PyUnicode_AsStringAndSize(modname, &len); + if (len > MAXPATHLEN) { + PyErr_SetString(PyExc_ValueError, + "Module name too long"); + return NULL; + } + strcpy(buf, modname_str); + error = PyDict_SetItem(globals, pkgstr, modname); + if (error) { + PyErr_SetString(PyExc_ValueError, + "Could not set __package__"); + return NULL; + } + } else { + /* Normal module, so work out the package name if any */ + char *start = _PyUnicode_AsString(modname); + char *lastdot = strrchr(start, '.'); + size_t len; + int error; + if (lastdot == NULL && level > 0) { + PyErr_SetString(PyExc_ValueError, + "Attempted relative import in non-package"); + return NULL; + } + if (lastdot == NULL) { + error = PyDict_SetItem(globals, pkgstr, Py_None); + if (error) { + PyErr_SetString(PyExc_ValueError, + "Could not set __package__"); + return NULL; + } + return Py_None; + } + len = lastdot - start; + if (len >= MAXPATHLEN) { + PyErr_SetString(PyExc_ValueError, + "Module name too long"); + return NULL; + } + strncpy(buf, start, len); + buf[len] = '\0'; + pkgname = PyUnicode_FromString(buf); + if (pkgname == NULL) { + return NULL; + } + error = PyDict_SetItem(globals, pkgstr, pkgname); + Py_DECREF(pkgname); + if (error) { + PyErr_SetString(PyExc_ValueError, + "Could not set __package__"); + return NULL; + } + } + } + while (--level > 0) { + char *dot = strrchr(buf, '.'); + if (dot == NULL) { + PyErr_SetString(PyExc_ValueError, + "Attempted relative import beyond " + "toplevel package"); + return NULL; + } + *dot = '\0'; + } + *p_buflen = strlen(buf); + + modules = PyImport_GetModuleDict(); + parent = PyDict_GetItemString(modules, buf); + if (parent == NULL) { + if (orig_level < 1) { + PyObject *err_msg = PyBytes_FromFormat( + "Parent module '%.200s' not found " + "while handling absolute import", buf); + if (err_msg == NULL) { + return NULL; + } + if (!PyErr_WarnEx(PyExc_RuntimeWarning, + PyBytes_AsString(err_msg), 1)) { + *buf = '\0'; + *p_buflen = 0; + parent = Py_None; + } + Py_DECREF(err_msg); + } else { + PyErr_Format(PyExc_SystemError, + "Parent module '%.200s' not loaded, " + "cannot perform relative import", buf); + } + } + return parent; + /* We expect, but can't guarantee, if parent != None, that: + - parent.__name__ == buf + - parent.__dict__ is globals + If this is violated... Who cares? */ } /* altmod is either None or same as mod */ static PyObject * load_next(PyObject *mod, PyObject *altmod, char **p_name, char *buf, - Py_ssize_t *p_buflen) + Py_ssize_t *p_buflen) { - char *name = *p_name; - char *dot = strchr(name, '.'); - size_t len; - char *p; - PyObject *result; - - if (strlen(name) == 0) { - /* completely empty module name should only happen in - 'from . import' (or '__import__("")')*/ - Py_INCREF(mod); - *p_name = NULL; - return mod; - } - - if (dot == NULL) { - *p_name = NULL; - len = strlen(name); - } - else { - *p_name = dot+1; - len = dot-name; - } - if (len == 0) { - PyErr_SetString(PyExc_ValueError, - "Empty module name"); - return NULL; - } - - p = buf + *p_buflen; - if (p != buf) - *p++ = '.'; - if (p+len-buf >= MAXPATHLEN) { - PyErr_SetString(PyExc_ValueError, - "Module name too long"); - return NULL; - } - strncpy(p, name, len); - p[len] = '\0'; - *p_buflen = p+len-buf; - - result = import_submodule(mod, p, buf); - if (result == Py_None && altmod != mod) { - Py_DECREF(result); - /* Here, altmod must be None and mod must not be None */ - result = import_submodule(altmod, p, p); - if (result != NULL && result != Py_None) { - if (mark_miss(buf) != 0) { - Py_DECREF(result); - return NULL; - } - strncpy(buf, name, len); - buf[len] = '\0'; - *p_buflen = len; - } - } - if (result == NULL) - return NULL; - - if (result == Py_None) { - Py_DECREF(result); - PyErr_Format(PyExc_ImportError, - "No module named %.200s", name); - return NULL; - } + char *name = *p_name; + char *dot = strchr(name, '.'); + size_t len; + char *p; + PyObject *result; + + if (strlen(name) == 0) { + /* completely empty module name should only happen in + 'from . import' (or '__import__("")')*/ + Py_INCREF(mod); + *p_name = NULL; + return mod; + } + + if (dot == NULL) { + *p_name = NULL; + len = strlen(name); + } + else { + *p_name = dot+1; + len = dot-name; + } + if (len == 0) { + PyErr_SetString(PyExc_ValueError, + "Empty module name"); + return NULL; + } + + p = buf + *p_buflen; + if (p != buf) + *p++ = '.'; + if (p+len-buf >= MAXPATHLEN) { + PyErr_SetString(PyExc_ValueError, + "Module name too long"); + return NULL; + } + strncpy(p, name, len); + p[len] = '\0'; + *p_buflen = p+len-buf; + + result = import_submodule(mod, p, buf); + if (result == Py_None && altmod != mod) { + Py_DECREF(result); + /* Here, altmod must be None and mod must not be None */ + result = import_submodule(altmod, p, p); + if (result != NULL && result != Py_None) { + if (mark_miss(buf) != 0) { + Py_DECREF(result); + return NULL; + } + strncpy(buf, name, len); + buf[len] = '\0'; + *p_buflen = len; + } + } + if (result == NULL) + return NULL; + + if (result == Py_None) { + Py_DECREF(result); + PyErr_Format(PyExc_ImportError, + "No module named %.200s", name); + return NULL; + } - return result; + return result; } static int mark_miss(char *name) { - PyObject *modules = PyImport_GetModuleDict(); - return PyDict_SetItemString(modules, name, Py_None); + PyObject *modules = PyImport_GetModuleDict(); + return PyDict_SetItemString(modules, name, Py_None); } static int ensure_fromlist(PyObject *mod, PyObject *fromlist, char *buf, Py_ssize_t buflen, - int recursive) + int recursive) { - int i; + int i; - if (!PyObject_HasAttrString(mod, "__path__")) - return 1; + if (!PyObject_HasAttrString(mod, "__path__")) + return 1; - for (i = 0; ; i++) { - PyObject *item = PySequence_GetItem(fromlist, i); - int hasit; - if (item == NULL) { - if (PyErr_ExceptionMatches(PyExc_IndexError)) { - PyErr_Clear(); - return 1; - } - return 0; - } - if (!PyUnicode_Check(item)) { - PyErr_SetString(PyExc_TypeError, - "Item in ``from list'' not a string"); - Py_DECREF(item); - return 0; - } - if (PyUnicode_AS_UNICODE(item)[0] == '*') { - PyObject *all; - Py_DECREF(item); - /* See if the package defines __all__ */ - if (recursive) - continue; /* Avoid endless recursion */ - all = PyObject_GetAttrString(mod, "__all__"); - if (all == NULL) - PyErr_Clear(); - else { - int ret = ensure_fromlist(mod, all, buf, buflen, 1); - Py_DECREF(all); - if (!ret) - return 0; - } - continue; - } - hasit = PyObject_HasAttr(mod, item); - if (!hasit) { - PyObject *item8; - char *subname; - PyObject *submod; - char *p; - if (!Py_FileSystemDefaultEncoding) { - item8 = PyUnicode_EncodeASCII(PyUnicode_AsUnicode(item), - PyUnicode_GetSize(item), - NULL); - } else { - item8 = PyUnicode_AsEncodedString(item, - Py_FileSystemDefaultEncoding, NULL); - } - if (!item8) { - PyErr_SetString(PyExc_ValueError, "Cannot encode path item"); - return 0; - } - subname = PyBytes_AS_STRING(item8); - if (buflen + strlen(subname) >= MAXPATHLEN) { - PyErr_SetString(PyExc_ValueError, - "Module name too long"); - Py_DECREF(item); - return 0; - } - p = buf + buflen; - *p++ = '.'; - strcpy(p, subname); - submod = import_submodule(mod, subname, buf); - Py_DECREF(item8); - Py_XDECREF(submod); - if (submod == NULL) { - Py_DECREF(item); - return 0; - } - } - Py_DECREF(item); - } + for (i = 0; ; i++) { + PyObject *item = PySequence_GetItem(fromlist, i); + int hasit; + if (item == NULL) { + if (PyErr_ExceptionMatches(PyExc_IndexError)) { + PyErr_Clear(); + return 1; + } + return 0; + } + if (!PyUnicode_Check(item)) { + PyErr_SetString(PyExc_TypeError, + "Item in ``from list'' not a string"); + Py_DECREF(item); + return 0; + } + if (PyUnicode_AS_UNICODE(item)[0] == '*') { + PyObject *all; + Py_DECREF(item); + /* See if the package defines __all__ */ + if (recursive) + continue; /* Avoid endless recursion */ + all = PyObject_GetAttrString(mod, "__all__"); + if (all == NULL) + PyErr_Clear(); + else { + int ret = ensure_fromlist(mod, all, buf, buflen, 1); + Py_DECREF(all); + if (!ret) + return 0; + } + continue; + } + hasit = PyObject_HasAttr(mod, item); + if (!hasit) { + PyObject *item8; + char *subname; + PyObject *submod; + char *p; + if (!Py_FileSystemDefaultEncoding) { + item8 = PyUnicode_EncodeASCII(PyUnicode_AsUnicode(item), + PyUnicode_GetSize(item), + NULL); + } else { + item8 = PyUnicode_AsEncodedString(item, + Py_FileSystemDefaultEncoding, NULL); + } + if (!item8) { + PyErr_SetString(PyExc_ValueError, "Cannot encode path item"); + return 0; + } + subname = PyBytes_AS_STRING(item8); + if (buflen + strlen(subname) >= MAXPATHLEN) { + PyErr_SetString(PyExc_ValueError, + "Module name too long"); + Py_DECREF(item); + return 0; + } + p = buf + buflen; + *p++ = '.'; + strcpy(p, subname); + submod = import_submodule(mod, subname, buf); + Py_DECREF(item8); + Py_XDECREF(submod); + if (submod == NULL) { + Py_DECREF(item); + return 0; + } + } + Py_DECREF(item); + } - /* NOTREACHED */ + /* NOTREACHED */ } static int add_submodule(PyObject *mod, PyObject *submod, char *fullname, char *subname, - PyObject *modules) + PyObject *modules) { - if (mod == Py_None) - return 1; - /* Irrespective of the success of this load, make a - reference to it in the parent package module. A copy gets - saved in the modules dictionary under the full name, so get a - reference from there, if need be. (The exception is when the - load failed with a SyntaxError -- then there's no trace in - sys.modules. In that case, of course, do nothing extra.) */ - if (submod == NULL) { - submod = PyDict_GetItemString(modules, fullname); - if (submod == NULL) - return 1; - } - if (PyModule_Check(mod)) { - /* We can't use setattr here since it can give a - * spurious warning if the submodule name shadows a - * builtin name */ - PyObject *dict = PyModule_GetDict(mod); - if (!dict) - return 0; - if (PyDict_SetItemString(dict, subname, submod) < 0) - return 0; - } - else { - if (PyObject_SetAttrString(mod, subname, submod) < 0) - return 0; - } - return 1; + if (mod == Py_None) + return 1; + /* Irrespective of the success of this load, make a + reference to it in the parent package module. A copy gets + saved in the modules dictionary under the full name, so get a + reference from there, if need be. (The exception is when the + load failed with a SyntaxError -- then there's no trace in + sys.modules. In that case, of course, do nothing extra.) */ + if (submod == NULL) { + submod = PyDict_GetItemString(modules, fullname); + if (submod == NULL) + return 1; + } + if (PyModule_Check(mod)) { + /* We can't use setattr here since it can give a + * spurious warning if the submodule name shadows a + * builtin name */ + PyObject *dict = PyModule_GetDict(mod); + if (!dict) + return 0; + if (PyDict_SetItemString(dict, subname, submod) < 0) + return 0; + } + else { + if (PyObject_SetAttrString(mod, subname, submod) < 0) + return 0; + } + return 1; } static PyObject * import_submodule(PyObject *mod, char *subname, char *fullname) { - PyObject *modules = PyImport_GetModuleDict(); - PyObject *m = NULL; + PyObject *modules = PyImport_GetModuleDict(); + PyObject *m = NULL; - /* Require: - if mod == None: subname == fullname - else: mod.__name__ + "." + subname == fullname - */ - - if ((m = PyDict_GetItemString(modules, fullname)) != NULL) { - Py_INCREF(m); - } - else { - PyObject *path, *loader = NULL; - char buf[MAXPATHLEN+1]; - struct filedescr *fdp; - FILE *fp = NULL; - - if (mod == Py_None) - path = NULL; - else { - path = PyObject_GetAttrString(mod, "__path__"); - if (path == NULL) { - PyErr_Clear(); - Py_INCREF(Py_None); - return Py_None; - } - } - - buf[0] = '\0'; - fdp = find_module(fullname, subname, path, buf, MAXPATHLEN+1, - &fp, &loader); - Py_XDECREF(path); - if (fdp == NULL) { - if (!PyErr_ExceptionMatches(PyExc_ImportError)) - return NULL; - PyErr_Clear(); - Py_INCREF(Py_None); - return Py_None; - } - m = load_module(fullname, fp, buf, fdp->type, loader); - Py_XDECREF(loader); - if (fp) - fclose(fp); - if (!add_submodule(mod, m, fullname, subname, modules)) { - Py_XDECREF(m); - m = NULL; - } - } + /* Require: + if mod == None: subname == fullname + else: mod.__name__ + "." + subname == fullname + */ + + if ((m = PyDict_GetItemString(modules, fullname)) != NULL) { + Py_INCREF(m); + } + else { + PyObject *path, *loader = NULL; + char buf[MAXPATHLEN+1]; + struct filedescr *fdp; + FILE *fp = NULL; + + if (mod == Py_None) + path = NULL; + else { + path = PyObject_GetAttrString(mod, "__path__"); + if (path == NULL) { + PyErr_Clear(); + Py_INCREF(Py_None); + return Py_None; + } + } + + buf[0] = '\0'; + fdp = find_module(fullname, subname, path, buf, MAXPATHLEN+1, + &fp, &loader); + Py_XDECREF(path); + if (fdp == NULL) { + if (!PyErr_ExceptionMatches(PyExc_ImportError)) + return NULL; + PyErr_Clear(); + Py_INCREF(Py_None); + return Py_None; + } + m = load_module(fullname, fp, buf, fdp->type, loader); + Py_XDECREF(loader); + if (fp) + fclose(fp); + if (!add_submodule(mod, m, fullname, subname, modules)) { + Py_XDECREF(m); + m = NULL; + } + } - return m; + return m; } @@ -2884,96 +2884,96 @@ PyObject * PyImport_ReloadModule(PyObject *m) { - PyInterpreterState *interp = PyThreadState_Get()->interp; - PyObject *modules_reloading = interp->modules_reloading; - PyObject *modules = PyImport_GetModuleDict(); - PyObject *path = NULL, *loader = NULL, *existing_m = NULL; - char *name, *subname; - char buf[MAXPATHLEN+1]; - struct filedescr *fdp; - FILE *fp = NULL; - PyObject *newm; - - if (modules_reloading == NULL) { - Py_FatalError("PyImport_ReloadModule: " - "no modules_reloading dictionary!"); - return NULL; - } - - if (m == NULL || !PyModule_Check(m)) { - PyErr_SetString(PyExc_TypeError, - "reload() argument must be module"); - return NULL; - } - name = (char*)PyModule_GetName(m); - if (name == NULL) - return NULL; - if (m != PyDict_GetItemString(modules, name)) { - PyErr_Format(PyExc_ImportError, - "reload(): module %.200s not in sys.modules", - name); - return NULL; - } - existing_m = PyDict_GetItemString(modules_reloading, name); - if (existing_m != NULL) { - /* Due to a recursive reload, this module is already - being reloaded. */ - Py_INCREF(existing_m); - return existing_m; - } - if (PyDict_SetItemString(modules_reloading, name, m) < 0) - return NULL; - - subname = strrchr(name, '.'); - if (subname == NULL) - subname = name; - else { - PyObject *parentname, *parent; - parentname = PyUnicode_FromStringAndSize(name, (subname-name)); - if (parentname == NULL) { - imp_modules_reloading_clear(); - return NULL; - } - parent = PyDict_GetItem(modules, parentname); - if (parent == NULL) { - PyErr_Format(PyExc_ImportError, - "reload(): parent %U not in sys.modules", - parentname); - Py_DECREF(parentname); - imp_modules_reloading_clear(); - return NULL; - } - Py_DECREF(parentname); - subname++; - path = PyObject_GetAttrString(parent, "__path__"); - if (path == NULL) - PyErr_Clear(); - } - buf[0] = '\0'; - fdp = find_module(name, subname, path, buf, MAXPATHLEN+1, &fp, &loader); - Py_XDECREF(path); - - if (fdp == NULL) { - Py_XDECREF(loader); - imp_modules_reloading_clear(); - return NULL; - } - - newm = load_module(name, fp, buf, fdp->type, loader); - Py_XDECREF(loader); - - if (fp) - fclose(fp); - if (newm == NULL) { - /* load_module probably removed name from modules because of - * the error. Put back the original module object. We're - * going to return NULL in this case regardless of whether - * replacing name succeeds, so the return value is ignored. - */ - PyDict_SetItemString(modules, name, m); - } - imp_modules_reloading_clear(); - return newm; + PyInterpreterState *interp = PyThreadState_Get()->interp; + PyObject *modules_reloading = interp->modules_reloading; + PyObject *modules = PyImport_GetModuleDict(); + PyObject *path = NULL, *loader = NULL, *existing_m = NULL; + char *name, *subname; + char buf[MAXPATHLEN+1]; + struct filedescr *fdp; + FILE *fp = NULL; + PyObject *newm; + + if (modules_reloading == NULL) { + Py_FatalError("PyImport_ReloadModule: " + "no modules_reloading dictionary!"); + return NULL; + } + + if (m == NULL || !PyModule_Check(m)) { + PyErr_SetString(PyExc_TypeError, + "reload() argument must be module"); + return NULL; + } + name = (char*)PyModule_GetName(m); + if (name == NULL) + return NULL; + if (m != PyDict_GetItemString(modules, name)) { + PyErr_Format(PyExc_ImportError, + "reload(): module %.200s not in sys.modules", + name); + return NULL; + } + existing_m = PyDict_GetItemString(modules_reloading, name); + if (existing_m != NULL) { + /* Due to a recursive reload, this module is already + being reloaded. */ + Py_INCREF(existing_m); + return existing_m; + } + if (PyDict_SetItemString(modules_reloading, name, m) < 0) + return NULL; + + subname = strrchr(name, '.'); + if (subname == NULL) + subname = name; + else { + PyObject *parentname, *parent; + parentname = PyUnicode_FromStringAndSize(name, (subname-name)); + if (parentname == NULL) { + imp_modules_reloading_clear(); + return NULL; + } + parent = PyDict_GetItem(modules, parentname); + if (parent == NULL) { + PyErr_Format(PyExc_ImportError, + "reload(): parent %U not in sys.modules", + parentname); + Py_DECREF(parentname); + imp_modules_reloading_clear(); + return NULL; + } + Py_DECREF(parentname); + subname++; + path = PyObject_GetAttrString(parent, "__path__"); + if (path == NULL) + PyErr_Clear(); + } + buf[0] = '\0'; + fdp = find_module(name, subname, path, buf, MAXPATHLEN+1, &fp, &loader); + Py_XDECREF(path); + + if (fdp == NULL) { + Py_XDECREF(loader); + imp_modules_reloading_clear(); + return NULL; + } + + newm = load_module(name, fp, buf, fdp->type, loader); + Py_XDECREF(loader); + + if (fp) + fclose(fp); + if (newm == NULL) { + /* load_module probably removed name from modules because of + * the error. Put back the original module object. We're + * going to return NULL in this case regardless of whether + * replacing name succeeds, so the return value is ignored. + */ + PyDict_SetItemString(modules, name, m); + } + imp_modules_reloading_clear(); + return newm; } @@ -2989,68 +2989,68 @@ PyObject * PyImport_Import(PyObject *module_name) { - static PyObject *silly_list = NULL; - static PyObject *builtins_str = NULL; - static PyObject *import_str = NULL; - PyObject *globals = NULL; - PyObject *import = NULL; - PyObject *builtins = NULL; - PyObject *r = NULL; - - /* Initialize constant string objects */ - if (silly_list == NULL) { - import_str = PyUnicode_InternFromString("__import__"); - if (import_str == NULL) - return NULL; - builtins_str = PyUnicode_InternFromString("__builtins__"); - if (builtins_str == NULL) - return NULL; - silly_list = Py_BuildValue("[s]", "__doc__"); - if (silly_list == NULL) - return NULL; - } - - /* Get the builtins from current globals */ - globals = PyEval_GetGlobals(); - if (globals != NULL) { - Py_INCREF(globals); - builtins = PyObject_GetItem(globals, builtins_str); - if (builtins == NULL) - goto err; - } - else { - /* No globals -- use standard builtins, and fake globals */ - builtins = PyImport_ImportModuleLevel("builtins", - NULL, NULL, NULL, 0); - if (builtins == NULL) - return NULL; - globals = Py_BuildValue("{OO}", builtins_str, builtins); - if (globals == NULL) - goto err; - } - - /* Get the __import__ function from the builtins */ - if (PyDict_Check(builtins)) { - import = PyObject_GetItem(builtins, import_str); - if (import == NULL) - PyErr_SetObject(PyExc_KeyError, import_str); - } - else - import = PyObject_GetAttr(builtins, import_str); - if (import == NULL) - goto err; - - /* Call the __import__ function with the proper argument list - * Always use absolute import here. */ - r = PyObject_CallFunction(import, "OOOOi", module_name, globals, - globals, silly_list, 0, NULL); + static PyObject *silly_list = NULL; + static PyObject *builtins_str = NULL; + static PyObject *import_str = NULL; + PyObject *globals = NULL; + PyObject *import = NULL; + PyObject *builtins = NULL; + PyObject *r = NULL; + + /* Initialize constant string objects */ + if (silly_list == NULL) { + import_str = PyUnicode_InternFromString("__import__"); + if (import_str == NULL) + return NULL; + builtins_str = PyUnicode_InternFromString("__builtins__"); + if (builtins_str == NULL) + return NULL; + silly_list = Py_BuildValue("[s]", "__doc__"); + if (silly_list == NULL) + return NULL; + } + + /* Get the builtins from current globals */ + globals = PyEval_GetGlobals(); + if (globals != NULL) { + Py_INCREF(globals); + builtins = PyObject_GetItem(globals, builtins_str); + if (builtins == NULL) + goto err; + } + else { + /* No globals -- use standard builtins, and fake globals */ + builtins = PyImport_ImportModuleLevel("builtins", + NULL, NULL, NULL, 0); + if (builtins == NULL) + return NULL; + globals = Py_BuildValue("{OO}", builtins_str, builtins); + if (globals == NULL) + goto err; + } + + /* Get the __import__ function from the builtins */ + if (PyDict_Check(builtins)) { + import = PyObject_GetItem(builtins, import_str); + if (import == NULL) + PyErr_SetObject(PyExc_KeyError, import_str); + } + else + import = PyObject_GetAttr(builtins, import_str); + if (import == NULL) + goto err; + + /* Call the __import__ function with the proper argument list + * Always use absolute import here. */ + r = PyObject_CallFunction(import, "OOOOi", module_name, globals, + globals, silly_list, 0, NULL); err: - Py_XDECREF(globals); - Py_XDECREF(builtins); - Py_XDECREF(import); + Py_XDECREF(globals); + Py_XDECREF(builtins); + Py_XDECREF(import); - return r; + return r; } @@ -3061,257 +3061,257 @@ static PyObject * imp_make_magic(long magic) { - char buf[4]; + char buf[4]; - buf[0] = (char) ((magic >> 0) & 0xff); - buf[1] = (char) ((magic >> 8) & 0xff); - buf[2] = (char) ((magic >> 16) & 0xff); - buf[3] = (char) ((magic >> 24) & 0xff); + buf[0] = (char) ((magic >> 0) & 0xff); + buf[1] = (char) ((magic >> 8) & 0xff); + buf[2] = (char) ((magic >> 16) & 0xff); + buf[3] = (char) ((magic >> 24) & 0xff); - return PyBytes_FromStringAndSize(buf, 4); -}; + return PyBytes_FromStringAndSize(buf, 4); +}; static PyObject * imp_get_magic(PyObject *self, PyObject *noargs) { - return imp_make_magic(pyc_magic); + return imp_make_magic(pyc_magic); } static PyObject * imp_get_tag(PyObject *self, PyObject *noargs) { - return PyUnicode_FromString(pyc_tag); + return PyUnicode_FromString(pyc_tag); } static PyObject * imp_get_suffixes(PyObject *self, PyObject *noargs) { - PyObject *list; - struct filedescr *fdp; + PyObject *list; + struct filedescr *fdp; - list = PyList_New(0); - if (list == NULL) - return NULL; - for (fdp = _PyImport_Filetab; fdp->suffix != NULL; fdp++) { - PyObject *item = Py_BuildValue("ssi", - fdp->suffix, fdp->mode, fdp->type); - if (item == NULL) { - Py_DECREF(list); - return NULL; - } - if (PyList_Append(list, item) < 0) { - Py_DECREF(list); - Py_DECREF(item); - return NULL; - } - Py_DECREF(item); - } - return list; + list = PyList_New(0); + if (list == NULL) + return NULL; + for (fdp = _PyImport_Filetab; fdp->suffix != NULL; fdp++) { + PyObject *item = Py_BuildValue("ssi", + fdp->suffix, fdp->mode, fdp->type); + if (item == NULL) { + Py_DECREF(list); + return NULL; + } + if (PyList_Append(list, item) < 0) { + Py_DECREF(list); + Py_DECREF(item); + return NULL; + } + Py_DECREF(item); + } + return list; } static PyObject * call_find_module(char *name, PyObject *path) { - extern int fclose(FILE *); - PyObject *fob, *ret; - PyObject *pathobj; - struct filedescr *fdp; - char pathname[MAXPATHLEN+1]; - FILE *fp = NULL; - int fd = -1; - char *found_encoding = NULL; - char *encoding = NULL; - - pathname[0] = '\0'; - if (path == Py_None) - path = NULL; - fdp = find_module(NULL, name, path, pathname, MAXPATHLEN+1, &fp, NULL); - if (fdp == NULL) - return NULL; - if (fp != NULL) { - fd = fileno(fp); - if (fd != -1) - fd = dup(fd); - fclose(fp); - fp = NULL; - } - if (fd != -1) { - if (strchr(fdp->mode, 'b') == NULL) { - /* PyTokenizer_FindEncoding() returns PyMem_MALLOC'ed - memory. */ - found_encoding = PyTokenizer_FindEncoding(fd); - lseek(fd, 0, 0); /* Reset position */ - if (found_encoding == NULL && PyErr_Occurred()) - return NULL; - encoding = (found_encoding != NULL) ? found_encoding : - (char*)PyUnicode_GetDefaultEncoding(); - } - fob = PyFile_FromFd(fd, pathname, fdp->mode, -1, - (char*)encoding, NULL, NULL, 1); - if (fob == NULL) { - close(fd); - PyMem_FREE(found_encoding); - return NULL; - } - } - else { - fob = Py_None; - Py_INCREF(fob); - } - pathobj = PyUnicode_DecodeFSDefault(pathname); - ret = Py_BuildValue("NN(ssi)", - fob, pathobj, fdp->suffix, fdp->mode, fdp->type); - PyMem_FREE(found_encoding); + extern int fclose(FILE *); + PyObject *fob, *ret; + PyObject *pathobj; + struct filedescr *fdp; + char pathname[MAXPATHLEN+1]; + FILE *fp = NULL; + int fd = -1; + char *found_encoding = NULL; + char *encoding = NULL; + + pathname[0] = '\0'; + if (path == Py_None) + path = NULL; + fdp = find_module(NULL, name, path, pathname, MAXPATHLEN+1, &fp, NULL); + if (fdp == NULL) + return NULL; + if (fp != NULL) { + fd = fileno(fp); + if (fd != -1) + fd = dup(fd); + fclose(fp); + fp = NULL; + } + if (fd != -1) { + if (strchr(fdp->mode, 'b') == NULL) { + /* PyTokenizer_FindEncoding() returns PyMem_MALLOC'ed + memory. */ + found_encoding = PyTokenizer_FindEncoding(fd); + lseek(fd, 0, 0); /* Reset position */ + if (found_encoding == NULL && PyErr_Occurred()) + return NULL; + encoding = (found_encoding != NULL) ? found_encoding : + (char*)PyUnicode_GetDefaultEncoding(); + } + fob = PyFile_FromFd(fd, pathname, fdp->mode, -1, + (char*)encoding, NULL, NULL, 1); + if (fob == NULL) { + close(fd); + PyMem_FREE(found_encoding); + return NULL; + } + } + else { + fob = Py_None; + Py_INCREF(fob); + } + pathobj = PyUnicode_DecodeFSDefault(pathname); + ret = Py_BuildValue("NN(ssi)", + fob, pathobj, fdp->suffix, fdp->mode, fdp->type); + PyMem_FREE(found_encoding); - return ret; + return ret; } static PyObject * imp_find_module(PyObject *self, PyObject *args) { - char *name; - PyObject *ret, *path = NULL; - if (!PyArg_ParseTuple(args, "es|O:find_module", - Py_FileSystemDefaultEncoding, &name, - &path)) - return NULL; - ret = call_find_module(name, path); - PyMem_Free(name); - return ret; + char *name; + PyObject *ret, *path = NULL; + if (!PyArg_ParseTuple(args, "es|O:find_module", + Py_FileSystemDefaultEncoding, &name, + &path)) + return NULL; + ret = call_find_module(name, path); + PyMem_Free(name); + return ret; } static PyObject * imp_init_builtin(PyObject *self, PyObject *args) { - char *name; - int ret; - PyObject *m; - if (!PyArg_ParseTuple(args, "s:init_builtin", &name)) - return NULL; - ret = init_builtin(name); - if (ret < 0) - return NULL; - if (ret == 0) { - Py_INCREF(Py_None); - return Py_None; - } - m = PyImport_AddModule(name); - Py_XINCREF(m); - return m; + char *name; + int ret; + PyObject *m; + if (!PyArg_ParseTuple(args, "s:init_builtin", &name)) + return NULL; + ret = init_builtin(name); + if (ret < 0) + return NULL; + if (ret == 0) { + Py_INCREF(Py_None); + return Py_None; + } + m = PyImport_AddModule(name); + Py_XINCREF(m); + return m; } static PyObject * imp_init_frozen(PyObject *self, PyObject *args) { - char *name; - int ret; - PyObject *m; - if (!PyArg_ParseTuple(args, "s:init_frozen", &name)) - return NULL; - ret = PyImport_ImportFrozenModule(name); - if (ret < 0) - return NULL; - if (ret == 0) { - Py_INCREF(Py_None); - return Py_None; - } - m = PyImport_AddModule(name); - Py_XINCREF(m); - return m; + char *name; + int ret; + PyObject *m; + if (!PyArg_ParseTuple(args, "s:init_frozen", &name)) + return NULL; + ret = PyImport_ImportFrozenModule(name); + if (ret < 0) + return NULL; + if (ret == 0) { + Py_INCREF(Py_None); + return Py_None; + } + m = PyImport_AddModule(name); + Py_XINCREF(m); + return m; } static PyObject * imp_get_frozen_object(PyObject *self, PyObject *args) { - char *name; + char *name; - if (!PyArg_ParseTuple(args, "s:get_frozen_object", &name)) - return NULL; - return get_frozen_object(name); + if (!PyArg_ParseTuple(args, "s:get_frozen_object", &name)) + return NULL; + return get_frozen_object(name); } static PyObject * imp_is_frozen_package(PyObject *self, PyObject *args) { - char *name; + char *name; - if (!PyArg_ParseTuple(args, "s:is_frozen_package", &name)) - return NULL; - return is_frozen_package(name); + if (!PyArg_ParseTuple(args, "s:is_frozen_package", &name)) + return NULL; + return is_frozen_package(name); } static PyObject * imp_is_builtin(PyObject *self, PyObject *args) { - char *name; - if (!PyArg_ParseTuple(args, "s:is_builtin", &name)) - return NULL; - return PyLong_FromLong(is_builtin(name)); + char *name; + if (!PyArg_ParseTuple(args, "s:is_builtin", &name)) + return NULL; + return PyLong_FromLong(is_builtin(name)); } static PyObject * imp_is_frozen(PyObject *self, PyObject *args) { - char *name; - struct _frozen *p; - if (!PyArg_ParseTuple(args, "s:is_frozen", &name)) - return NULL; - p = find_frozen(name); - return PyBool_FromLong((long) (p == NULL ? 0 : p->size)); + char *name; + struct _frozen *p; + if (!PyArg_ParseTuple(args, "s:is_frozen", &name)) + return NULL; + p = find_frozen(name); + return PyBool_FromLong((long) (p == NULL ? 0 : p->size)); } static FILE * get_file(char *pathname, PyObject *fob, char *mode) { - FILE *fp; - if (mode[0] == 'U') - mode = "r" PY_STDIOTEXTMODE; - if (fob == NULL) { - fp = fopen(pathname, mode); - } - else { - int fd = PyObject_AsFileDescriptor(fob); - if (fd == -1) - return NULL; - if (!_PyVerify_fd(fd)) - goto error; - /* the FILE struct gets a new fd, so that it can be closed - * independently of the file descriptor given - */ - fd = dup(fd); - if (fd == -1) - goto error; - fp = fdopen(fd, mode); - } - if (fp) - return fp; + FILE *fp; + if (mode[0] == 'U') + mode = "r" PY_STDIOTEXTMODE; + if (fob == NULL) { + fp = fopen(pathname, mode); + } + else { + int fd = PyObject_AsFileDescriptor(fob); + if (fd == -1) + return NULL; + if (!_PyVerify_fd(fd)) + goto error; + /* the FILE struct gets a new fd, so that it can be closed + * independently of the file descriptor given + */ + fd = dup(fd); + if (fd == -1) + goto error; + fp = fdopen(fd, mode); + } + if (fp) + return fp; error: - PyErr_SetFromErrno(PyExc_IOError); - return NULL; + PyErr_SetFromErrno(PyExc_IOError); + return NULL; } static PyObject * imp_load_compiled(PyObject *self, PyObject *args) { - char *name; - char *pathname; - PyObject *fob = NULL; - PyObject *m; - FILE *fp; - if (!PyArg_ParseTuple(args, "ses|O:load_compiled", - &name, - Py_FileSystemDefaultEncoding, &pathname, - &fob)) - return NULL; - fp = get_file(pathname, fob, "rb"); - if (fp == NULL) { - PyMem_Free(pathname); - return NULL; - } - m = load_compiled_module(name, pathname, fp); - fclose(fp); - PyMem_Free(pathname); - return m; + char *name; + char *pathname; + PyObject *fob = NULL; + PyObject *m; + FILE *fp; + if (!PyArg_ParseTuple(args, "ses|O:load_compiled", + &name, + Py_FileSystemDefaultEncoding, &pathname, + &fob)) + return NULL; + fp = get_file(pathname, fob, "rb"); + if (fp == NULL) { + PyMem_Free(pathname); + return NULL; + } + m = load_compiled_module(name, pathname, fp); + fclose(fp); + PyMem_Free(pathname); + return m; } #ifdef HAVE_DYNAMIC_LOADING @@ -3319,28 +3319,28 @@ static PyObject * imp_load_dynamic(PyObject *self, PyObject *args) { - char *name; - char *pathname; - PyObject *fob = NULL; - PyObject *m; - FILE *fp = NULL; - if (!PyArg_ParseTuple(args, "ses|O:load_dynamic", - &name, - Py_FileSystemDefaultEncoding, &pathname, - &fob)) - return NULL; - if (fob) { - fp = get_file(pathname, fob, "r"); - if (fp == NULL) { - PyMem_Free(pathname); - return NULL; - } - } - m = _PyImport_LoadDynamicModule(name, pathname, fp); - PyMem_Free(pathname); - if (fp) - fclose(fp); - return m; + char *name; + char *pathname; + PyObject *fob = NULL; + PyObject *m; + FILE *fp = NULL; + if (!PyArg_ParseTuple(args, "ses|O:load_dynamic", + &name, + Py_FileSystemDefaultEncoding, &pathname, + &fob)) + return NULL; + if (fob) { + fp = get_file(pathname, fob, "r"); + if (fp == NULL) { + PyMem_Free(pathname); + return NULL; + } + } + m = _PyImport_LoadDynamicModule(name, pathname, fp); + PyMem_Free(pathname); + if (fp) + fclose(fp); + return m; } #endif /* HAVE_DYNAMIC_LOADING */ @@ -3348,99 +3348,99 @@ static PyObject * imp_load_source(PyObject *self, PyObject *args) { - char *name; - char *pathname; - PyObject *fob = NULL; - PyObject *m; - FILE *fp; - if (!PyArg_ParseTuple(args, "ses|O:load_source", - &name, - Py_FileSystemDefaultEncoding, &pathname, - &fob)) - return NULL; - fp = get_file(pathname, fob, "r"); - if (fp == NULL) { - PyMem_Free(pathname); - return NULL; - } - m = load_source_module(name, pathname, fp); - PyMem_Free(pathname); - fclose(fp); - return m; + char *name; + char *pathname; + PyObject *fob = NULL; + PyObject *m; + FILE *fp; + if (!PyArg_ParseTuple(args, "ses|O:load_source", + &name, + Py_FileSystemDefaultEncoding, &pathname, + &fob)) + return NULL; + fp = get_file(pathname, fob, "r"); + if (fp == NULL) { + PyMem_Free(pathname); + return NULL; + } + m = load_source_module(name, pathname, fp); + PyMem_Free(pathname); + fclose(fp); + return m; } static PyObject * imp_load_module(PyObject *self, PyObject *args) { - char *name; - PyObject *fob; - char *pathname; - PyObject * ret; - char *suffix; /* Unused */ - char *mode; - int type; - FILE *fp; - - if (!PyArg_ParseTuple(args, "sOes(ssi):load_module", - &name, &fob, - Py_FileSystemDefaultEncoding, &pathname, - &suffix, &mode, &type)) - return NULL; - if (*mode) { - /* Mode must start with 'r' or 'U' and must not contain '+'. - Implicit in this test is the assumption that the mode - may contain other modifiers like 'b' or 't'. */ - - if (!(*mode == 'r' || *mode == 'U') || strchr(mode, '+')) { - PyErr_Format(PyExc_ValueError, - "invalid file open mode %.200s", mode); - PyMem_Free(pathname); - return NULL; - } - } - if (fob == Py_None) - fp = NULL; - else { - fp = get_file(NULL, fob, mode); - if (fp == NULL) { - PyMem_Free(pathname); - return NULL; - } - } - ret = load_module(name, fp, pathname, type, NULL); - PyMem_Free(pathname); - if (fp) - fclose(fp); - return ret; + char *name; + PyObject *fob; + char *pathname; + PyObject * ret; + char *suffix; /* Unused */ + char *mode; + int type; + FILE *fp; + + if (!PyArg_ParseTuple(args, "sOes(ssi):load_module", + &name, &fob, + Py_FileSystemDefaultEncoding, &pathname, + &suffix, &mode, &type)) + return NULL; + if (*mode) { + /* Mode must start with 'r' or 'U' and must not contain '+'. + Implicit in this test is the assumption that the mode + may contain other modifiers like 'b' or 't'. */ + + if (!(*mode == 'r' || *mode == 'U') || strchr(mode, '+')) { + PyErr_Format(PyExc_ValueError, + "invalid file open mode %.200s", mode); + PyMem_Free(pathname); + return NULL; + } + } + if (fob == Py_None) + fp = NULL; + else { + fp = get_file(NULL, fob, mode); + if (fp == NULL) { + PyMem_Free(pathname); + return NULL; + } + } + ret = load_module(name, fp, pathname, type, NULL); + PyMem_Free(pathname); + if (fp) + fclose(fp); + return ret; } static PyObject * imp_load_package(PyObject *self, PyObject *args) { - char *name; - char *pathname; - PyObject * ret; - if (!PyArg_ParseTuple(args, "ses:load_package", - &name, Py_FileSystemDefaultEncoding, &pathname)) - return NULL; - ret = load_package(name, pathname); - PyMem_Free(pathname); - return ret; + char *name; + char *pathname; + PyObject * ret; + if (!PyArg_ParseTuple(args, "ses:load_package", + &name, Py_FileSystemDefaultEncoding, &pathname)) + return NULL; + ret = load_package(name, pathname); + PyMem_Free(pathname); + return ret; } static PyObject * imp_new_module(PyObject *self, PyObject *args) { - char *name; - if (!PyArg_ParseTuple(args, "s:new_module", &name)) - return NULL; - return PyModule_New(name); + char *name; + if (!PyArg_ParseTuple(args, "s:new_module", &name)) + return NULL; + return PyModule_New(name); } static PyObject * imp_reload(PyObject *self, PyObject *v) { - return PyImport_ReloadModule(v); + return PyImport_ReloadModule(v); } PyDoc_STRVAR(doc_reload, @@ -3451,30 +3451,30 @@ static PyObject * imp_cache_from_source(PyObject *self, PyObject *args, PyObject *kws) { - static char *kwlist[] = {"path", "debug_override", NULL}; + static char *kwlist[] = {"path", "debug_override", NULL}; - char buf[MAXPATHLEN+1]; - char *pathname, *cpathname; - PyObject *debug_override = Py_None; - int debug = !Py_OptimizeFlag; - - if (!PyArg_ParseTupleAndKeywords( - args, kws, "es|O", kwlist, - Py_FileSystemDefaultEncoding, &pathname, &debug_override)) - return NULL; - - if (debug_override != Py_None) - if ((debug = PyObject_IsTrue(debug_override)) < 0) - return NULL; - - cpathname = make_compiled_pathname(pathname, buf, MAXPATHLEN+1, debug); - PyMem_Free(pathname); - - if (cpathname == NULL) { - PyErr_Format(PyExc_SystemError, "path buffer too short"); - return NULL; - } - return PyUnicode_FromString(buf); + char buf[MAXPATHLEN+1]; + char *pathname, *cpathname; + PyObject *debug_override = Py_None; + int debug = !Py_OptimizeFlag; + + if (!PyArg_ParseTupleAndKeywords( + args, kws, "es|O", kwlist, + Py_FileSystemDefaultEncoding, &pathname, &debug_override)) + return NULL; + + if (debug_override != Py_None) + if ((debug = PyObject_IsTrue(debug_override)) < 0) + return NULL; + + cpathname = make_compiled_pathname(pathname, buf, MAXPATHLEN+1, debug); + PyMem_Free(pathname); + + if (cpathname == NULL) { + PyErr_Format(PyExc_SystemError, "path buffer too short"); + return NULL; + } + return PyUnicode_FromString(buf); } PyDoc_STRVAR(doc_cache_from_source, @@ -3490,24 +3490,24 @@ static PyObject * imp_source_from_cache(PyObject *self, PyObject *args, PyObject *kws) { - static char *kwlist[] = {"path", NULL}; + static char *kwlist[] = {"path", NULL}; - char *pathname; - char buf[MAXPATHLEN+1]; + char *pathname; + char buf[MAXPATHLEN+1]; - if (!PyArg_ParseTupleAndKeywords( - args, kws, "es", kwlist, - Py_FileSystemDefaultEncoding, &pathname)) - return NULL; - - if (make_source_pathname(pathname, buf) == NULL) { - PyErr_Format(PyExc_ValueError, "Not a PEP 3147 pyc path: %s", - pathname); - PyMem_Free(pathname); - return NULL; - } - PyMem_Free(pathname); - return PyUnicode_FromString(buf); + if (!PyArg_ParseTupleAndKeywords( + args, kws, "es", kwlist, + Py_FileSystemDefaultEncoding, &pathname)) + return NULL; + + if (make_source_pathname(pathname, buf) == NULL) { + PyErr_Format(PyExc_ValueError, "Not a PEP 3147 pyc path: %s", + pathname); + PyMem_Free(pathname); + return NULL; + } + PyMem_Free(pathname); + return PyUnicode_FromString(buf); } PyDoc_STRVAR(doc_source_from_cache, @@ -3571,46 +3571,46 @@ On platforms without threads, this function does nothing."); static PyMethodDef imp_methods[] = { - {"find_module", imp_find_module, METH_VARARGS, doc_find_module}, - {"get_magic", imp_get_magic, METH_NOARGS, doc_get_magic}, - {"get_tag", imp_get_tag, METH_NOARGS, doc_get_tag}, - {"get_suffixes", imp_get_suffixes, METH_NOARGS, doc_get_suffixes}, - {"load_module", imp_load_module, METH_VARARGS, doc_load_module}, - {"new_module", imp_new_module, METH_VARARGS, doc_new_module}, - {"lock_held", imp_lock_held, METH_NOARGS, doc_lock_held}, - {"acquire_lock", imp_acquire_lock, METH_NOARGS, doc_acquire_lock}, - {"release_lock", imp_release_lock, METH_NOARGS, doc_release_lock}, - {"reload", imp_reload, METH_O, doc_reload}, - {"cache_from_source", (PyCFunction)imp_cache_from_source, - METH_VARARGS | METH_KEYWORDS, doc_cache_from_source}, - {"source_from_cache", (PyCFunction)imp_source_from_cache, - METH_VARARGS | METH_KEYWORDS, doc_source_from_cache}, - /* The rest are obsolete */ - {"get_frozen_object", imp_get_frozen_object, METH_VARARGS}, - {"is_frozen_package", imp_is_frozen_package, METH_VARARGS}, - {"init_builtin", imp_init_builtin, METH_VARARGS}, - {"init_frozen", imp_init_frozen, METH_VARARGS}, - {"is_builtin", imp_is_builtin, METH_VARARGS}, - {"is_frozen", imp_is_frozen, METH_VARARGS}, - {"load_compiled", imp_load_compiled, METH_VARARGS}, + {"find_module", imp_find_module, METH_VARARGS, doc_find_module}, + {"get_magic", imp_get_magic, METH_NOARGS, doc_get_magic}, + {"get_tag", imp_get_tag, METH_NOARGS, doc_get_tag}, + {"get_suffixes", imp_get_suffixes, METH_NOARGS, doc_get_suffixes}, + {"load_module", imp_load_module, METH_VARARGS, doc_load_module}, + {"new_module", imp_new_module, METH_VARARGS, doc_new_module}, + {"lock_held", imp_lock_held, METH_NOARGS, doc_lock_held}, + {"acquire_lock", imp_acquire_lock, METH_NOARGS, doc_acquire_lock}, + {"release_lock", imp_release_lock, METH_NOARGS, doc_release_lock}, + {"reload", imp_reload, METH_O, doc_reload}, + {"cache_from_source", (PyCFunction)imp_cache_from_source, + METH_VARARGS | METH_KEYWORDS, doc_cache_from_source}, + {"source_from_cache", (PyCFunction)imp_source_from_cache, + METH_VARARGS | METH_KEYWORDS, doc_source_from_cache}, + /* The rest are obsolete */ + {"get_frozen_object", imp_get_frozen_object, METH_VARARGS}, + {"is_frozen_package", imp_is_frozen_package, METH_VARARGS}, + {"init_builtin", imp_init_builtin, METH_VARARGS}, + {"init_frozen", imp_init_frozen, METH_VARARGS}, + {"is_builtin", imp_is_builtin, METH_VARARGS}, + {"is_frozen", imp_is_frozen, METH_VARARGS}, + {"load_compiled", imp_load_compiled, METH_VARARGS}, #ifdef HAVE_DYNAMIC_LOADING - {"load_dynamic", imp_load_dynamic, METH_VARARGS}, + {"load_dynamic", imp_load_dynamic, METH_VARARGS}, #endif - {"load_package", imp_load_package, METH_VARARGS}, - {"load_source", imp_load_source, METH_VARARGS}, - {NULL, NULL} /* sentinel */ + {"load_package", imp_load_package, METH_VARARGS}, + {"load_source", imp_load_source, METH_VARARGS}, + {NULL, NULL} /* sentinel */ }; static int setint(PyObject *d, char *name, int value) { - PyObject *v; - int err; + PyObject *v; + int err; - v = PyLong_FromLong((long)value); - err = PyDict_SetItemString(d, name, v); - Py_XDECREF(v); - return err; + v = PyLong_FromLong((long)value); + err = PyDict_SetItemString(d, name, v); + Py_XDECREF(v); + return err; } typedef struct { @@ -3620,158 +3620,158 @@ static int NullImporter_init(NullImporter *self, PyObject *args, PyObject *kwds) { - char *path; - Py_ssize_t pathlen; + char *path; + Py_ssize_t pathlen; - if (!_PyArg_NoKeywords("NullImporter()", kwds)) - return -1; + if (!_PyArg_NoKeywords("NullImporter()", kwds)) + return -1; - if (!PyArg_ParseTuple(args, "es:NullImporter", - Py_FileSystemDefaultEncoding, &path)) - return -1; - - pathlen = strlen(path); - if (pathlen == 0) { - PyMem_Free(path); - PyErr_SetString(PyExc_ImportError, "empty pathname"); - return -1; - } else { + if (!PyArg_ParseTuple(args, "es:NullImporter", + Py_FileSystemDefaultEncoding, &path)) + return -1; + + pathlen = strlen(path); + if (pathlen == 0) { + PyMem_Free(path); + PyErr_SetString(PyExc_ImportError, "empty pathname"); + return -1; + } else { #ifndef MS_WINDOWS - struct stat statbuf; - int rv; + struct stat statbuf; + int rv; - rv = stat(path, &statbuf); - PyMem_Free(path); - if (rv == 0) { - /* it exists */ - if (S_ISDIR(statbuf.st_mode)) { - /* it's a directory */ - PyErr_SetString(PyExc_ImportError, - "existing directory"); - return -1; - } - } + rv = stat(path, &statbuf); + PyMem_Free(path); + if (rv == 0) { + /* it exists */ + if (S_ISDIR(statbuf.st_mode)) { + /* it's a directory */ + PyErr_SetString(PyExc_ImportError, + "existing directory"); + return -1; + } + } #else /* MS_WINDOWS */ - DWORD rv; - /* see issue1293 and issue3677: - * stat() on Windows doesn't recognise paths like - * "e:\\shared\\" and "\\\\whiterab-c2znlh\\shared" as dirs. - */ - rv = GetFileAttributesA(path); - PyMem_Free(path); - if (rv != INVALID_FILE_ATTRIBUTES) { - /* it exists */ - if (rv & FILE_ATTRIBUTE_DIRECTORY) { - /* it's a directory */ - PyErr_SetString(PyExc_ImportError, - "existing directory"); - return -1; - } - } + DWORD rv; + /* see issue1293 and issue3677: + * stat() on Windows doesn't recognise paths like + * "e:\\shared\\" and "\\\\whiterab-c2znlh\\shared" as dirs. + */ + rv = GetFileAttributesA(path); + PyMem_Free(path); + if (rv != INVALID_FILE_ATTRIBUTES) { + /* it exists */ + if (rv & FILE_ATTRIBUTE_DIRECTORY) { + /* it's a directory */ + PyErr_SetString(PyExc_ImportError, + "existing directory"); + return -1; + } + } #endif - } - return 0; + } + return 0; } static PyObject * NullImporter_find_module(NullImporter *self, PyObject *args) { - Py_RETURN_NONE; + Py_RETURN_NONE; } static PyMethodDef NullImporter_methods[] = { - {"find_module", (PyCFunction)NullImporter_find_module, METH_VARARGS, - "Always return None" - }, - {NULL} /* Sentinel */ + {"find_module", (PyCFunction)NullImporter_find_module, METH_VARARGS, + "Always return None" + }, + {NULL} /* Sentinel */ }; PyTypeObject PyNullImporter_Type = { - PyVarObject_HEAD_INIT(NULL, 0) - "imp.NullImporter", /*tp_name*/ - sizeof(NullImporter), /*tp_basicsize*/ - 0, /*tp_itemsize*/ - 0, /*tp_dealloc*/ - 0, /*tp_print*/ - 0, /*tp_getattr*/ - 0, /*tp_setattr*/ - 0, /*tp_reserved*/ - 0, /*tp_repr*/ - 0, /*tp_as_number*/ - 0, /*tp_as_sequence*/ - 0, /*tp_as_mapping*/ - 0, /*tp_hash */ - 0, /*tp_call*/ - 0, /*tp_str*/ - 0, /*tp_getattro*/ - 0, /*tp_setattro*/ - 0, /*tp_as_buffer*/ - Py_TPFLAGS_DEFAULT, /*tp_flags*/ - "Null importer object", /* tp_doc */ - 0, /* tp_traverse */ - 0, /* tp_clear */ - 0, /* tp_richcompare */ - 0, /* tp_weaklistoffset */ - 0, /* tp_iter */ - 0, /* tp_iternext */ - NullImporter_methods, /* tp_methods */ - 0, /* tp_members */ - 0, /* tp_getset */ - 0, /* tp_base */ - 0, /* tp_dict */ - 0, /* tp_descr_get */ - 0, /* tp_descr_set */ - 0, /* tp_dictoffset */ - (initproc)NullImporter_init, /* tp_init */ - 0, /* tp_alloc */ - PyType_GenericNew /* tp_new */ + PyVarObject_HEAD_INIT(NULL, 0) + "imp.NullImporter", /*tp_name*/ + sizeof(NullImporter), /*tp_basicsize*/ + 0, /*tp_itemsize*/ + 0, /*tp_dealloc*/ + 0, /*tp_print*/ + 0, /*tp_getattr*/ + 0, /*tp_setattr*/ + 0, /*tp_reserved*/ + 0, /*tp_repr*/ + 0, /*tp_as_number*/ + 0, /*tp_as_sequence*/ + 0, /*tp_as_mapping*/ + 0, /*tp_hash */ + 0, /*tp_call*/ + 0, /*tp_str*/ + 0, /*tp_getattro*/ + 0, /*tp_setattro*/ + 0, /*tp_as_buffer*/ + Py_TPFLAGS_DEFAULT, /*tp_flags*/ + "Null importer object", /* tp_doc */ + 0, /* tp_traverse */ + 0, /* tp_clear */ + 0, /* tp_richcompare */ + 0, /* tp_weaklistoffset */ + 0, /* tp_iter */ + 0, /* tp_iternext */ + NullImporter_methods, /* tp_methods */ + 0, /* tp_members */ + 0, /* tp_getset */ + 0, /* tp_base */ + 0, /* tp_dict */ + 0, /* tp_descr_get */ + 0, /* tp_descr_set */ + 0, /* tp_dictoffset */ + (initproc)NullImporter_init, /* tp_init */ + 0, /* tp_alloc */ + PyType_GenericNew /* tp_new */ }; static struct PyModuleDef impmodule = { - PyModuleDef_HEAD_INIT, - "imp", - doc_imp, - 0, - imp_methods, - NULL, - NULL, - NULL, - NULL + PyModuleDef_HEAD_INIT, + "imp", + doc_imp, + 0, + imp_methods, + NULL, + NULL, + NULL, + NULL }; PyMODINIT_FUNC PyInit_imp(void) { - PyObject *m, *d; + PyObject *m, *d; - if (PyType_Ready(&PyNullImporter_Type) < 0) - return NULL; + if (PyType_Ready(&PyNullImporter_Type) < 0) + return NULL; - m = PyModule_Create(&impmodule); - if (m == NULL) - goto failure; - d = PyModule_GetDict(m); - if (d == NULL) - goto failure; - - if (setint(d, "SEARCH_ERROR", SEARCH_ERROR) < 0) goto failure; - if (setint(d, "PY_SOURCE", PY_SOURCE) < 0) goto failure; - if (setint(d, "PY_COMPILED", PY_COMPILED) < 0) goto failure; - if (setint(d, "C_EXTENSION", C_EXTENSION) < 0) goto failure; - if (setint(d, "PY_RESOURCE", PY_RESOURCE) < 0) goto failure; - if (setint(d, "PKG_DIRECTORY", PKG_DIRECTORY) < 0) goto failure; - if (setint(d, "C_BUILTIN", C_BUILTIN) < 0) goto failure; - if (setint(d, "PY_FROZEN", PY_FROZEN) < 0) goto failure; - if (setint(d, "PY_CODERESOURCE", PY_CODERESOURCE) < 0) goto failure; - if (setint(d, "IMP_HOOK", IMP_HOOK) < 0) goto failure; - - Py_INCREF(&PyNullImporter_Type); - PyModule_AddObject(m, "NullImporter", (PyObject *)&PyNullImporter_Type); - return m; + m = PyModule_Create(&impmodule); + if (m == NULL) + goto failure; + d = PyModule_GetDict(m); + if (d == NULL) + goto failure; + + if (setint(d, "SEARCH_ERROR", SEARCH_ERROR) < 0) goto failure; + if (setint(d, "PY_SOURCE", PY_SOURCE) < 0) goto failure; + if (setint(d, "PY_COMPILED", PY_COMPILED) < 0) goto failure; + if (setint(d, "C_EXTENSION", C_EXTENSION) < 0) goto failure; + if (setint(d, "PY_RESOURCE", PY_RESOURCE) < 0) goto failure; + if (setint(d, "PKG_DIRECTORY", PKG_DIRECTORY) < 0) goto failure; + if (setint(d, "C_BUILTIN", C_BUILTIN) < 0) goto failure; + if (setint(d, "PY_FROZEN", PY_FROZEN) < 0) goto failure; + if (setint(d, "PY_CODERESOURCE", PY_CODERESOURCE) < 0) goto failure; + if (setint(d, "IMP_HOOK", IMP_HOOK) < 0) goto failure; + + Py_INCREF(&PyNullImporter_Type); + PyModule_AddObject(m, "NullImporter", (PyObject *)&PyNullImporter_Type); + return m; failure: - Py_XDECREF(m); - return NULL; + Py_XDECREF(m); + return NULL; } @@ -3785,31 +3785,31 @@ int PyImport_ExtendInittab(struct _inittab *newtab) { - static struct _inittab *our_copy = NULL; - struct _inittab *p; - int i, n; - - /* Count the number of entries in both tables */ - for (n = 0; newtab[n].name != NULL; n++) - ; - if (n == 0) - return 0; /* Nothing to do */ - for (i = 0; PyImport_Inittab[i].name != NULL; i++) - ; - - /* Allocate new memory for the combined table */ - p = our_copy; - PyMem_RESIZE(p, struct _inittab, i+n+1); - if (p == NULL) - return -1; - - /* Copy the tables into the new memory */ - if (our_copy != PyImport_Inittab) - memcpy(p, PyImport_Inittab, (i+1) * sizeof(struct _inittab)); - PyImport_Inittab = our_copy = p; - memcpy(p+i, newtab, (n+1) * sizeof(struct _inittab)); + static struct _inittab *our_copy = NULL; + struct _inittab *p; + int i, n; + + /* Count the number of entries in both tables */ + for (n = 0; newtab[n].name != NULL; n++) + ; + if (n == 0) + return 0; /* Nothing to do */ + for (i = 0; PyImport_Inittab[i].name != NULL; i++) + ; + + /* Allocate new memory for the combined table */ + p = our_copy; + PyMem_RESIZE(p, struct _inittab, i+n+1); + if (p == NULL) + return -1; + + /* Copy the tables into the new memory */ + if (our_copy != PyImport_Inittab) + memcpy(p, PyImport_Inittab, (i+1) * sizeof(struct _inittab)); + PyImport_Inittab = our_copy = p; + memcpy(p+i, newtab, (n+1) * sizeof(struct _inittab)); - return 0; + return 0; } /* Shorthand to add a single entry given a name and a function */ @@ -3817,14 +3817,14 @@ int PyImport_AppendInittab(const char *name, PyObject* (*initfunc)(void)) { - struct _inittab newtab[2]; + struct _inittab newtab[2]; - memset(newtab, '\0', sizeof newtab); + memset(newtab, '\0', sizeof newtab); - newtab[0].name = (char *)name; - newtab[0].initfunc = initfunc; + newtab[0].name = (char *)name; + newtab[0].initfunc = initfunc; - return PyImport_ExtendInittab(newtab); + return PyImport_ExtendInittab(newtab); } #ifdef __cplusplus Modified: python/branches/py3k/Python/importdl.c ============================================================================== --- python/branches/py3k/Python/importdl.c (original) +++ python/branches/py3k/Python/importdl.c Sun May 9 17:52:27 2010 @@ -13,76 +13,76 @@ #include "importdl.h" extern dl_funcptr _PyImport_GetDynLoadFunc(const char *name, - const char *shortname, - const char *pathname, FILE *fp); + const char *shortname, + const char *pathname, FILE *fp); PyObject * _PyImport_LoadDynamicModule(char *name, char *pathname, FILE *fp) { - PyObject *m; - PyObject *path; - char *lastdot, *shortname, *packagecontext, *oldcontext; - dl_funcptr p0; - PyObject* (*p)(void); - struct PyModuleDef *def; - - if ((m = _PyImport_FindExtension(name, pathname)) != NULL) { - Py_INCREF(m); - return m; - } - lastdot = strrchr(name, '.'); - if (lastdot == NULL) { - packagecontext = NULL; - shortname = name; - } - else { - packagecontext = name; - shortname = lastdot+1; - } - - p0 = _PyImport_GetDynLoadFunc(name, shortname, pathname, fp); - p = (PyObject*(*)(void))p0; - if (PyErr_Occurred()) - return NULL; - if (p == NULL) { - PyErr_Format(PyExc_ImportError, - "dynamic module does not define init function (PyInit_%.200s)", - shortname); - return NULL; - } - oldcontext = _Py_PackageContext; - _Py_PackageContext = packagecontext; - m = (*p)(); - _Py_PackageContext = oldcontext; - if (m == NULL) - return NULL; - - if (PyErr_Occurred()) { - Py_DECREF(m); - PyErr_Format(PyExc_SystemError, - "initialization of %s raised unreported exception", - shortname); - return NULL; - } - - /* Remember pointer to module init function. */ - def = PyModule_GetDef(m); - def->m_base.m_init = p; - - /* Remember the filename as the __file__ attribute */ - path = PyUnicode_DecodeFSDefault(pathname); - if (PyModule_AddObject(m, "__file__", path) < 0) - PyErr_Clear(); /* Not important enough to report */ - - if (_PyImport_FixupExtension(m, name, pathname) < 0) - return NULL; - if (Py_VerboseFlag) - PySys_WriteStderr( - "import %s # dynamically loaded from %s\n", - name, pathname); - return m; + PyObject *m; + PyObject *path; + char *lastdot, *shortname, *packagecontext, *oldcontext; + dl_funcptr p0; + PyObject* (*p)(void); + struct PyModuleDef *def; + + if ((m = _PyImport_FindExtension(name, pathname)) != NULL) { + Py_INCREF(m); + return m; + } + lastdot = strrchr(name, '.'); + if (lastdot == NULL) { + packagecontext = NULL; + shortname = name; + } + else { + packagecontext = name; + shortname = lastdot+1; + } + + p0 = _PyImport_GetDynLoadFunc(name, shortname, pathname, fp); + p = (PyObject*(*)(void))p0; + if (PyErr_Occurred()) + return NULL; + if (p == NULL) { + PyErr_Format(PyExc_ImportError, + "dynamic module does not define init function (PyInit_%.200s)", + shortname); + return NULL; + } + oldcontext = _Py_PackageContext; + _Py_PackageContext = packagecontext; + m = (*p)(); + _Py_PackageContext = oldcontext; + if (m == NULL) + return NULL; + + if (PyErr_Occurred()) { + Py_DECREF(m); + PyErr_Format(PyExc_SystemError, + "initialization of %s raised unreported exception", + shortname); + return NULL; + } + + /* Remember pointer to module init function. */ + def = PyModule_GetDef(m); + def->m_base.m_init = p; + + /* Remember the filename as the __file__ attribute */ + path = PyUnicode_DecodeFSDefault(pathname); + if (PyModule_AddObject(m, "__file__", path) < 0) + PyErr_Clear(); /* Not important enough to report */ + + if (_PyImport_FixupExtension(m, name, pathname) < 0) + return NULL; + if (Py_VerboseFlag) + PySys_WriteStderr( + "import %s # dynamically loaded from %s\n", + name, pathname); + return m; } #endif /* HAVE_DYNAMIC_LOADING */ Modified: python/branches/py3k/Python/importdl.h ============================================================================== --- python/branches/py3k/Python/importdl.h (original) +++ python/branches/py3k/Python/importdl.h Sun May 9 17:52:27 2010 @@ -8,28 +8,28 @@ /* Definitions for dynamic loading of extension modules */ enum filetype { - SEARCH_ERROR, - PY_SOURCE, - PY_COMPILED, - C_EXTENSION, - PY_RESOURCE, /* Mac only */ - PKG_DIRECTORY, - C_BUILTIN, - PY_FROZEN, - PY_CODERESOURCE, /* Mac only */ - IMP_HOOK + SEARCH_ERROR, + PY_SOURCE, + PY_COMPILED, + C_EXTENSION, + PY_RESOURCE, /* Mac only */ + PKG_DIRECTORY, + C_BUILTIN, + PY_FROZEN, + PY_CODERESOURCE, /* Mac only */ + IMP_HOOK }; struct filedescr { - char *suffix; - char *mode; - enum filetype type; + char *suffix; + char *mode; + enum filetype type; }; extern struct filedescr * _PyImport_Filetab; extern const struct filedescr _PyImport_DynLoadFiletab[]; extern PyObject *_PyImport_LoadDynamicModule(char *name, char *pathname, - FILE *); + FILE *); /* Max length of module suffix searched for -- accommodates "module.slb" */ #define MAXSUFFIXSIZE 12 Modified: python/branches/py3k/Python/makeopcodetargets.py ============================================================================== --- python/branches/py3k/Python/makeopcodetargets.py (original) +++ python/branches/py3k/Python/makeopcodetargets.py Sun May 9 17:52:27 2010 @@ -28,7 +28,7 @@ continue targets[op] = "TARGET_%s" % opname f.write("static void *opcode_targets[256] = {\n") - f.write(",\n".join(["\t&&%s" % s for s in targets])) + f.write(",\n".join([" &&%s" % s for s in targets])) f.write("\n};\n") Modified: python/branches/py3k/Python/marshal.c ============================================================================== --- python/branches/py3k/Python/marshal.c (original) +++ python/branches/py3k/Python/marshal.c Sun May 9 17:52:27 2010 @@ -24,28 +24,28 @@ #define MAX_MARSHAL_STACK_DEPTH 2000 #endif -#define TYPE_NULL '0' -#define TYPE_NONE 'N' -#define TYPE_FALSE 'F' -#define TYPE_TRUE 'T' -#define TYPE_STOPITER 'S' -#define TYPE_ELLIPSIS '.' -#define TYPE_INT 'i' -#define TYPE_INT64 'I' -#define TYPE_FLOAT 'f' -#define TYPE_BINARY_FLOAT 'g' -#define TYPE_COMPLEX 'x' -#define TYPE_BINARY_COMPLEX 'y' -#define TYPE_LONG 'l' -#define TYPE_STRING 's' -#define TYPE_TUPLE '(' -#define TYPE_LIST '[' -#define TYPE_DICT '{' -#define TYPE_CODE 'c' -#define TYPE_UNICODE 'u' -#define TYPE_UNKNOWN '?' -#define TYPE_SET '<' -#define TYPE_FROZENSET '>' +#define TYPE_NULL '0' +#define TYPE_NONE 'N' +#define TYPE_FALSE 'F' +#define TYPE_TRUE 'T' +#define TYPE_STOPITER 'S' +#define TYPE_ELLIPSIS '.' +#define TYPE_INT 'i' +#define TYPE_INT64 'I' +#define TYPE_FLOAT 'f' +#define TYPE_BINARY_FLOAT 'g' +#define TYPE_COMPLEX 'x' +#define TYPE_BINARY_COMPLEX 'y' +#define TYPE_LONG 'l' +#define TYPE_STRING 's' +#define TYPE_TUPLE '(' +#define TYPE_LIST '[' +#define TYPE_DICT '{' +#define TYPE_CODE 'c' +#define TYPE_UNICODE 'u' +#define TYPE_UNKNOWN '?' +#define TYPE_SET '<' +#define TYPE_FROZENSET '>' #define WFERR_OK 0 #define WFERR_UNMARSHALLABLE 1 @@ -53,79 +53,79 @@ #define WFERR_NOMEMORY 3 typedef struct { - FILE *fp; - int error; /* see WFERR_* values */ - int depth; - /* If fp == NULL, the following are valid: */ - PyObject *str; - char *ptr; - char *end; - PyObject *strings; /* dict on marshal, list on unmarshal */ - int version; + FILE *fp; + int error; /* see WFERR_* values */ + int depth; + /* If fp == NULL, the following are valid: */ + PyObject *str; + char *ptr; + char *end; + PyObject *strings; /* dict on marshal, list on unmarshal */ + int version; } WFILE; #define w_byte(c, p) if (((p)->fp)) putc((c), (p)->fp); \ - else if ((p)->ptr != (p)->end) *(p)->ptr++ = (c); \ - else w_more(c, p) + else if ((p)->ptr != (p)->end) *(p)->ptr++ = (c); \ + else w_more(c, p) static void w_more(int c, WFILE *p) { - Py_ssize_t size, newsize; - if (p->str == NULL) - return; /* An error already occurred */ - size = PyBytes_Size(p->str); - newsize = size + size + 1024; - if (newsize > 32*1024*1024) { - newsize = size + (size >> 3); /* 12.5% overallocation */ - } - if (_PyBytes_Resize(&p->str, newsize) != 0) { - p->ptr = p->end = NULL; - } - else { - p->ptr = PyBytes_AS_STRING((PyBytesObject *)p->str) + size; - p->end = - PyBytes_AS_STRING((PyBytesObject *)p->str) + newsize; - *p->ptr++ = Py_SAFE_DOWNCAST(c, int, char); - } + Py_ssize_t size, newsize; + if (p->str == NULL) + return; /* An error already occurred */ + size = PyBytes_Size(p->str); + newsize = size + size + 1024; + if (newsize > 32*1024*1024) { + newsize = size + (size >> 3); /* 12.5% overallocation */ + } + if (_PyBytes_Resize(&p->str, newsize) != 0) { + p->ptr = p->end = NULL; + } + else { + p->ptr = PyBytes_AS_STRING((PyBytesObject *)p->str) + size; + p->end = + PyBytes_AS_STRING((PyBytesObject *)p->str) + newsize; + *p->ptr++ = Py_SAFE_DOWNCAST(c, int, char); + } } static void w_string(char *s, int n, WFILE *p) { - if (p->fp != NULL) { - fwrite(s, 1, n, p->fp); - } - else { - while (--n >= 0) { - w_byte(*s, p); - s++; - } - } + if (p->fp != NULL) { + fwrite(s, 1, n, p->fp); + } + else { + while (--n >= 0) { + w_byte(*s, p); + s++; + } + } } static void w_short(int x, WFILE *p) { - w_byte((char)( x & 0xff), p); - w_byte((char)((x>> 8) & 0xff), p); + w_byte((char)( x & 0xff), p); + w_byte((char)((x>> 8) & 0xff), p); } static void w_long(long x, WFILE *p) { - w_byte((char)( x & 0xff), p); - w_byte((char)((x>> 8) & 0xff), p); - w_byte((char)((x>>16) & 0xff), p); - w_byte((char)((x>>24) & 0xff), p); + w_byte((char)( x & 0xff), p); + w_byte((char)((x>> 8) & 0xff), p); + w_byte((char)((x>>16) & 0xff), p); + w_byte((char)((x>>24) & 0xff), p); } #if SIZEOF_LONG > 4 static void w_long64(long x, WFILE *p) { - w_long(x, p); - w_long(x>>32, p); + w_long(x, p); + w_long(x>>32, p); } #endif @@ -144,322 +144,322 @@ static void w_PyLong(const PyLongObject *ob, WFILE *p) { - Py_ssize_t i, j, n, l; - digit d; + Py_ssize_t i, j, n, l; + digit d; - w_byte(TYPE_LONG, p); - if (Py_SIZE(ob) == 0) { - w_long((long)0, p); - return; - } - - /* set l to number of base PyLong_MARSHAL_BASE digits */ - n = ABS(Py_SIZE(ob)); - l = (n-1) * PyLong_MARSHAL_RATIO; - d = ob->ob_digit[n-1]; - assert(d != 0); /* a PyLong is always normalized */ - do { - d >>= PyLong_MARSHAL_SHIFT; - l++; - } while (d != 0); - w_long((long)(Py_SIZE(ob) > 0 ? l : -l), p); - - for (i=0; i < n-1; i++) { - d = ob->ob_digit[i]; - for (j=0; j < PyLong_MARSHAL_RATIO; j++) { - w_short(d & PyLong_MARSHAL_MASK, p); - d >>= PyLong_MARSHAL_SHIFT; - } - assert (d == 0); - } - d = ob->ob_digit[n-1]; - do { - w_short(d & PyLong_MARSHAL_MASK, p); - d >>= PyLong_MARSHAL_SHIFT; - } while (d != 0); + w_byte(TYPE_LONG, p); + if (Py_SIZE(ob) == 0) { + w_long((long)0, p); + return; + } + + /* set l to number of base PyLong_MARSHAL_BASE digits */ + n = ABS(Py_SIZE(ob)); + l = (n-1) * PyLong_MARSHAL_RATIO; + d = ob->ob_digit[n-1]; + assert(d != 0); /* a PyLong is always normalized */ + do { + d >>= PyLong_MARSHAL_SHIFT; + l++; + } while (d != 0); + w_long((long)(Py_SIZE(ob) > 0 ? l : -l), p); + + for (i=0; i < n-1; i++) { + d = ob->ob_digit[i]; + for (j=0; j < PyLong_MARSHAL_RATIO; j++) { + w_short(d & PyLong_MARSHAL_MASK, p); + d >>= PyLong_MARSHAL_SHIFT; + } + assert (d == 0); + } + d = ob->ob_digit[n-1]; + do { + w_short(d & PyLong_MARSHAL_MASK, p); + d >>= PyLong_MARSHAL_SHIFT; + } while (d != 0); } static void w_object(PyObject *v, WFILE *p) { - Py_ssize_t i, n; + Py_ssize_t i, n; - p->depth++; + p->depth++; - if (p->depth > MAX_MARSHAL_STACK_DEPTH) { - p->error = WFERR_NESTEDTOODEEP; - } - else if (v == NULL) { - w_byte(TYPE_NULL, p); - } - else if (v == Py_None) { - w_byte(TYPE_NONE, p); - } - else if (v == PyExc_StopIteration) { - w_byte(TYPE_STOPITER, p); - } - else if (v == Py_Ellipsis) { - w_byte(TYPE_ELLIPSIS, p); - } - else if (v == Py_False) { - w_byte(TYPE_FALSE, p); - } - else if (v == Py_True) { - w_byte(TYPE_TRUE, p); - } - else if (PyLong_CheckExact(v)) { - long x = PyLong_AsLong(v); - if ((x == -1) && PyErr_Occurred()) { - PyLongObject *ob = (PyLongObject *)v; - PyErr_Clear(); - w_PyLong(ob, p); - } - else { + if (p->depth > MAX_MARSHAL_STACK_DEPTH) { + p->error = WFERR_NESTEDTOODEEP; + } + else if (v == NULL) { + w_byte(TYPE_NULL, p); + } + else if (v == Py_None) { + w_byte(TYPE_NONE, p); + } + else if (v == PyExc_StopIteration) { + w_byte(TYPE_STOPITER, p); + } + else if (v == Py_Ellipsis) { + w_byte(TYPE_ELLIPSIS, p); + } + else if (v == Py_False) { + w_byte(TYPE_FALSE, p); + } + else if (v == Py_True) { + w_byte(TYPE_TRUE, p); + } + else if (PyLong_CheckExact(v)) { + long x = PyLong_AsLong(v); + if ((x == -1) && PyErr_Occurred()) { + PyLongObject *ob = (PyLongObject *)v; + PyErr_Clear(); + w_PyLong(ob, p); + } + else { #if SIZEOF_LONG > 4 - long y = Py_ARITHMETIC_RIGHT_SHIFT(long, x, 31); - if (y && y != -1) { - w_byte(TYPE_INT64, p); - w_long64(x, p); - } - else + long y = Py_ARITHMETIC_RIGHT_SHIFT(long, x, 31); + if (y && y != -1) { + w_byte(TYPE_INT64, p); + w_long64(x, p); + } + else #endif - { - w_byte(TYPE_INT, p); - w_long(x, p); - } - } - } - else if (PyFloat_CheckExact(v)) { - if (p->version > 1) { - unsigned char buf[8]; - if (_PyFloat_Pack8(PyFloat_AsDouble(v), - buf, 1) < 0) { - p->error = WFERR_UNMARSHALLABLE; - return; - } - w_byte(TYPE_BINARY_FLOAT, p); - w_string((char*)buf, 8, p); - } - else { - char *buf = PyOS_double_to_string(PyFloat_AS_DOUBLE(v), - 'g', 17, 0, NULL); - if (!buf) { - p->error = WFERR_NOMEMORY; - return; - } - n = strlen(buf); - w_byte(TYPE_FLOAT, p); - w_byte((int)n, p); - w_string(buf, (int)n, p); - PyMem_Free(buf); - } - } - else if (PyComplex_CheckExact(v)) { - if (p->version > 1) { - unsigned char buf[8]; - if (_PyFloat_Pack8(PyComplex_RealAsDouble(v), - buf, 1) < 0) { - p->error = WFERR_UNMARSHALLABLE; - return; - } - w_byte(TYPE_BINARY_COMPLEX, p); - w_string((char*)buf, 8, p); - if (_PyFloat_Pack8(PyComplex_ImagAsDouble(v), - buf, 1) < 0) { - p->error = WFERR_UNMARSHALLABLE; - return; - } - w_string((char*)buf, 8, p); - } - else { - char *buf; - w_byte(TYPE_COMPLEX, p); - buf = PyOS_double_to_string(PyComplex_RealAsDouble(v), - 'g', 17, 0, NULL); - if (!buf) { - p->error = WFERR_NOMEMORY; - return; - } - n = strlen(buf); - w_byte((int)n, p); - w_string(buf, (int)n, p); - PyMem_Free(buf); - buf = PyOS_double_to_string(PyComplex_ImagAsDouble(v), - 'g', 17, 0, NULL); - if (!buf) { - p->error = WFERR_NOMEMORY; - return; - } - n = strlen(buf); - w_byte((int)n, p); - w_string(buf, (int)n, p); - PyMem_Free(buf); - } - } - else if (PyBytes_CheckExact(v)) { - w_byte(TYPE_STRING, p); - n = PyBytes_GET_SIZE(v); - if (n > INT_MAX) { - /* huge strings are not supported */ - p->depth--; - p->error = WFERR_UNMARSHALLABLE; - return; - } - w_long((long)n, p); - w_string(PyBytes_AS_STRING(v), (int)n, p); - } - else if (PyUnicode_CheckExact(v)) { - PyObject *utf8; - utf8 = PyUnicode_EncodeUTF8(PyUnicode_AS_UNICODE(v), - PyUnicode_GET_SIZE(v), - "surrogatepass"); - if (utf8 == NULL) { - p->depth--; - p->error = WFERR_UNMARSHALLABLE; - return; - } - w_byte(TYPE_UNICODE, p); - n = PyBytes_GET_SIZE(utf8); - if (n > INT_MAX) { - p->depth--; - p->error = WFERR_UNMARSHALLABLE; - return; - } - w_long((long)n, p); - w_string(PyBytes_AS_STRING(utf8), (int)n, p); - Py_DECREF(utf8); - } - else if (PyTuple_CheckExact(v)) { - w_byte(TYPE_TUPLE, p); - n = PyTuple_Size(v); - w_long((long)n, p); - for (i = 0; i < n; i++) { - w_object(PyTuple_GET_ITEM(v, i), p); - } - } - else if (PyList_CheckExact(v)) { - w_byte(TYPE_LIST, p); - n = PyList_GET_SIZE(v); - w_long((long)n, p); - for (i = 0; i < n; i++) { - w_object(PyList_GET_ITEM(v, i), p); - } - } - else if (PyDict_CheckExact(v)) { - Py_ssize_t pos; - PyObject *key, *value; - w_byte(TYPE_DICT, p); - /* This one is NULL object terminated! */ - pos = 0; - while (PyDict_Next(v, &pos, &key, &value)) { - w_object(key, p); - w_object(value, p); - } - w_object((PyObject *)NULL, p); - } - else if (PyAnySet_CheckExact(v)) { - PyObject *value, *it; - - if (PyObject_TypeCheck(v, &PySet_Type)) - w_byte(TYPE_SET, p); - else - w_byte(TYPE_FROZENSET, p); - n = PyObject_Size(v); - if (n == -1) { - p->depth--; - p->error = WFERR_UNMARSHALLABLE; - return; - } - w_long((long)n, p); - it = PyObject_GetIter(v); - if (it == NULL) { - p->depth--; - p->error = WFERR_UNMARSHALLABLE; - return; - } - while ((value = PyIter_Next(it)) != NULL) { - w_object(value, p); - Py_DECREF(value); - } - Py_DECREF(it); - if (PyErr_Occurred()) { - p->depth--; - p->error = WFERR_UNMARSHALLABLE; - return; - } - } - else if (PyCode_Check(v)) { - PyCodeObject *co = (PyCodeObject *)v; - w_byte(TYPE_CODE, p); - w_long(co->co_argcount, p); - w_long(co->co_kwonlyargcount, p); - w_long(co->co_nlocals, p); - w_long(co->co_stacksize, p); - w_long(co->co_flags, p); - w_object(co->co_code, p); - w_object(co->co_consts, p); - w_object(co->co_names, p); - w_object(co->co_varnames, p); - w_object(co->co_freevars, p); - w_object(co->co_cellvars, p); - w_object(co->co_filename, p); - w_object(co->co_name, p); - w_long(co->co_firstlineno, p); - w_object(co->co_lnotab, p); - } - else if (PyObject_CheckBuffer(v)) { - /* Write unknown buffer-style objects as a string */ - char *s; - PyBufferProcs *pb = v->ob_type->tp_as_buffer; - Py_buffer view; - if ((*pb->bf_getbuffer)(v, &view, PyBUF_SIMPLE) != 0) { - w_byte(TYPE_UNKNOWN, p); - p->error = WFERR_UNMARSHALLABLE; - } - w_byte(TYPE_STRING, p); - n = view.len; - s = view.buf; - if (n > INT_MAX) { - p->depth--; - p->error = WFERR_UNMARSHALLABLE; - return; - } - w_long((long)n, p); - w_string(s, (int)n, p); - if (pb->bf_releasebuffer != NULL) - (*pb->bf_releasebuffer)(v, &view); - } - else { - w_byte(TYPE_UNKNOWN, p); - p->error = WFERR_UNMARSHALLABLE; - } - p->depth--; + { + w_byte(TYPE_INT, p); + w_long(x, p); + } + } + } + else if (PyFloat_CheckExact(v)) { + if (p->version > 1) { + unsigned char buf[8]; + if (_PyFloat_Pack8(PyFloat_AsDouble(v), + buf, 1) < 0) { + p->error = WFERR_UNMARSHALLABLE; + return; + } + w_byte(TYPE_BINARY_FLOAT, p); + w_string((char*)buf, 8, p); + } + else { + char *buf = PyOS_double_to_string(PyFloat_AS_DOUBLE(v), + 'g', 17, 0, NULL); + if (!buf) { + p->error = WFERR_NOMEMORY; + return; + } + n = strlen(buf); + w_byte(TYPE_FLOAT, p); + w_byte((int)n, p); + w_string(buf, (int)n, p); + PyMem_Free(buf); + } + } + else if (PyComplex_CheckExact(v)) { + if (p->version > 1) { + unsigned char buf[8]; + if (_PyFloat_Pack8(PyComplex_RealAsDouble(v), + buf, 1) < 0) { + p->error = WFERR_UNMARSHALLABLE; + return; + } + w_byte(TYPE_BINARY_COMPLEX, p); + w_string((char*)buf, 8, p); + if (_PyFloat_Pack8(PyComplex_ImagAsDouble(v), + buf, 1) < 0) { + p->error = WFERR_UNMARSHALLABLE; + return; + } + w_string((char*)buf, 8, p); + } + else { + char *buf; + w_byte(TYPE_COMPLEX, p); + buf = PyOS_double_to_string(PyComplex_RealAsDouble(v), + 'g', 17, 0, NULL); + if (!buf) { + p->error = WFERR_NOMEMORY; + return; + } + n = strlen(buf); + w_byte((int)n, p); + w_string(buf, (int)n, p); + PyMem_Free(buf); + buf = PyOS_double_to_string(PyComplex_ImagAsDouble(v), + 'g', 17, 0, NULL); + if (!buf) { + p->error = WFERR_NOMEMORY; + return; + } + n = strlen(buf); + w_byte((int)n, p); + w_string(buf, (int)n, p); + PyMem_Free(buf); + } + } + else if (PyBytes_CheckExact(v)) { + w_byte(TYPE_STRING, p); + n = PyBytes_GET_SIZE(v); + if (n > INT_MAX) { + /* huge strings are not supported */ + p->depth--; + p->error = WFERR_UNMARSHALLABLE; + return; + } + w_long((long)n, p); + w_string(PyBytes_AS_STRING(v), (int)n, p); + } + else if (PyUnicode_CheckExact(v)) { + PyObject *utf8; + utf8 = PyUnicode_EncodeUTF8(PyUnicode_AS_UNICODE(v), + PyUnicode_GET_SIZE(v), + "surrogatepass"); + if (utf8 == NULL) { + p->depth--; + p->error = WFERR_UNMARSHALLABLE; + return; + } + w_byte(TYPE_UNICODE, p); + n = PyBytes_GET_SIZE(utf8); + if (n > INT_MAX) { + p->depth--; + p->error = WFERR_UNMARSHALLABLE; + return; + } + w_long((long)n, p); + w_string(PyBytes_AS_STRING(utf8), (int)n, p); + Py_DECREF(utf8); + } + else if (PyTuple_CheckExact(v)) { + w_byte(TYPE_TUPLE, p); + n = PyTuple_Size(v); + w_long((long)n, p); + for (i = 0; i < n; i++) { + w_object(PyTuple_GET_ITEM(v, i), p); + } + } + else if (PyList_CheckExact(v)) { + w_byte(TYPE_LIST, p); + n = PyList_GET_SIZE(v); + w_long((long)n, p); + for (i = 0; i < n; i++) { + w_object(PyList_GET_ITEM(v, i), p); + } + } + else if (PyDict_CheckExact(v)) { + Py_ssize_t pos; + PyObject *key, *value; + w_byte(TYPE_DICT, p); + /* This one is NULL object terminated! */ + pos = 0; + while (PyDict_Next(v, &pos, &key, &value)) { + w_object(key, p); + w_object(value, p); + } + w_object((PyObject *)NULL, p); + } + else if (PyAnySet_CheckExact(v)) { + PyObject *value, *it; + + if (PyObject_TypeCheck(v, &PySet_Type)) + w_byte(TYPE_SET, p); + else + w_byte(TYPE_FROZENSET, p); + n = PyObject_Size(v); + if (n == -1) { + p->depth--; + p->error = WFERR_UNMARSHALLABLE; + return; + } + w_long((long)n, p); + it = PyObject_GetIter(v); + if (it == NULL) { + p->depth--; + p->error = WFERR_UNMARSHALLABLE; + return; + } + while ((value = PyIter_Next(it)) != NULL) { + w_object(value, p); + Py_DECREF(value); + } + Py_DECREF(it); + if (PyErr_Occurred()) { + p->depth--; + p->error = WFERR_UNMARSHALLABLE; + return; + } + } + else if (PyCode_Check(v)) { + PyCodeObject *co = (PyCodeObject *)v; + w_byte(TYPE_CODE, p); + w_long(co->co_argcount, p); + w_long(co->co_kwonlyargcount, p); + w_long(co->co_nlocals, p); + w_long(co->co_stacksize, p); + w_long(co->co_flags, p); + w_object(co->co_code, p); + w_object(co->co_consts, p); + w_object(co->co_names, p); + w_object(co->co_varnames, p); + w_object(co->co_freevars, p); + w_object(co->co_cellvars, p); + w_object(co->co_filename, p); + w_object(co->co_name, p); + w_long(co->co_firstlineno, p); + w_object(co->co_lnotab, p); + } + else if (PyObject_CheckBuffer(v)) { + /* Write unknown buffer-style objects as a string */ + char *s; + PyBufferProcs *pb = v->ob_type->tp_as_buffer; + Py_buffer view; + if ((*pb->bf_getbuffer)(v, &view, PyBUF_SIMPLE) != 0) { + w_byte(TYPE_UNKNOWN, p); + p->error = WFERR_UNMARSHALLABLE; + } + w_byte(TYPE_STRING, p); + n = view.len; + s = view.buf; + if (n > INT_MAX) { + p->depth--; + p->error = WFERR_UNMARSHALLABLE; + return; + } + w_long((long)n, p); + w_string(s, (int)n, p); + if (pb->bf_releasebuffer != NULL) + (*pb->bf_releasebuffer)(v, &view); + } + else { + w_byte(TYPE_UNKNOWN, p); + p->error = WFERR_UNMARSHALLABLE; + } + p->depth--; } /* version currently has no effect for writing longs. */ void PyMarshal_WriteLongToFile(long x, FILE *fp, int version) { - WFILE wf; - wf.fp = fp; - wf.error = WFERR_OK; - wf.depth = 0; - wf.strings = NULL; - wf.version = version; - w_long(x, &wf); + WFILE wf; + wf.fp = fp; + wf.error = WFERR_OK; + wf.depth = 0; + wf.strings = NULL; + wf.version = version; + w_long(x, &wf); } void PyMarshal_WriteObjectToFile(PyObject *x, FILE *fp, int version) { - WFILE wf; - wf.fp = fp; - wf.error = WFERR_OK; - wf.depth = 0; - wf.strings = (version > 0) ? PyDict_New() : NULL; - wf.version = version; - w_object(x, &wf); - Py_XDECREF(wf.strings); + WFILE wf; + wf.fp = fp; + wf.error = WFERR_OK; + wf.depth = 0; + wf.strings = (version > 0) ? PyDict_New() : NULL; + wf.version = version; + w_object(x, &wf); + Py_XDECREF(wf.strings); } typedef WFILE RFILE; /* Same struct with different invariants */ @@ -471,49 +471,49 @@ static int r_string(char *s, int n, RFILE *p) { - if (p->fp != NULL) - /* The result fits into int because it must be <=n. */ - return (int)fread(s, 1, n, p->fp); - if (p->end - p->ptr < n) - n = (int)(p->end - p->ptr); - memcpy(s, p->ptr, n); - p->ptr += n; - return n; + if (p->fp != NULL) + /* The result fits into int because it must be <=n. */ + return (int)fread(s, 1, n, p->fp); + if (p->end - p->ptr < n) + n = (int)(p->end - p->ptr); + memcpy(s, p->ptr, n); + p->ptr += n; + return n; } static int r_short(RFILE *p) { - register short x; - x = r_byte(p); - x |= r_byte(p) << 8; - /* Sign-extension, in case short greater than 16 bits */ - x |= -(x & 0x8000); - return x; + register short x; + x = r_byte(p); + x |= r_byte(p) << 8; + /* Sign-extension, in case short greater than 16 bits */ + x |= -(x & 0x8000); + return x; } static long r_long(RFILE *p) { - register long x; - register FILE *fp = p->fp; - if (fp) { - x = getc(fp); - x |= (long)getc(fp) << 8; - x |= (long)getc(fp) << 16; - x |= (long)getc(fp) << 24; - } - else { - x = rs_byte(p); - x |= (long)rs_byte(p) << 8; - x |= (long)rs_byte(p) << 16; - x |= (long)rs_byte(p) << 24; - } + register long x; + register FILE *fp = p->fp; + if (fp) { + x = getc(fp); + x |= (long)getc(fp) << 8; + x |= (long)getc(fp) << 16; + x |= (long)getc(fp) << 24; + } + else { + x = rs_byte(p); + x |= (long)rs_byte(p) << 8; + x |= (long)rs_byte(p) << 16; + x |= (long)rs_byte(p) << 24; + } #if SIZEOF_LONG > 4 - /* Sign extension for 64-bit machines */ - x |= -(x & 0x80000000L); + /* Sign extension for 64-bit machines */ + x |= -(x & 0x80000000L); #endif - return x; + return x; } /* r_long64 deals with the TYPE_INT64 code. On a machine with @@ -526,534 +526,534 @@ static PyObject * r_long64(RFILE *p) { - long lo4 = r_long(p); - long hi4 = r_long(p); + long lo4 = r_long(p); + long hi4 = r_long(p); #if SIZEOF_LONG > 4 - long x = (hi4 << 32) | (lo4 & 0xFFFFFFFFL); - return PyLong_FromLong(x); + long x = (hi4 << 32) | (lo4 & 0xFFFFFFFFL); + return PyLong_FromLong(x); #else - unsigned char buf[8]; - int one = 1; - int is_little_endian = (int)*(char*)&one; - if (is_little_endian) { - memcpy(buf, &lo4, 4); - memcpy(buf+4, &hi4, 4); - } - else { - memcpy(buf, &hi4, 4); - memcpy(buf+4, &lo4, 4); - } - return _PyLong_FromByteArray(buf, 8, is_little_endian, 1); + unsigned char buf[8]; + int one = 1; + int is_little_endian = (int)*(char*)&one; + if (is_little_endian) { + memcpy(buf, &lo4, 4); + memcpy(buf+4, &hi4, 4); + } + else { + memcpy(buf, &hi4, 4); + memcpy(buf+4, &lo4, 4); + } + return _PyLong_FromByteArray(buf, 8, is_little_endian, 1); #endif } static PyObject * r_PyLong(RFILE *p) { - PyLongObject *ob; - int size, i, j, md, shorts_in_top_digit; - long n; - digit d; - - n = r_long(p); - if (n == 0) - return (PyObject *)_PyLong_New(0); - if (n < -INT_MAX || n > INT_MAX) { - PyErr_SetString(PyExc_ValueError, - "bad marshal data (long size out of range)"); - return NULL; - } - - size = 1 + (ABS(n) - 1) / PyLong_MARSHAL_RATIO; - shorts_in_top_digit = 1 + (ABS(n) - 1) % PyLong_MARSHAL_RATIO; - ob = _PyLong_New(size); - if (ob == NULL) - return NULL; - Py_SIZE(ob) = n > 0 ? size : -size; - - for (i = 0; i < size-1; i++) { - d = 0; - for (j=0; j < PyLong_MARSHAL_RATIO; j++) { - md = r_short(p); - if (md < 0 || md > PyLong_MARSHAL_BASE) - goto bad_digit; - d += (digit)md << j*PyLong_MARSHAL_SHIFT; - } - ob->ob_digit[i] = d; - } - d = 0; - for (j=0; j < shorts_in_top_digit; j++) { - md = r_short(p); - if (md < 0 || md > PyLong_MARSHAL_BASE) - goto bad_digit; - /* topmost marshal digit should be nonzero */ - if (md == 0 && j == shorts_in_top_digit - 1) { - Py_DECREF(ob); - PyErr_SetString(PyExc_ValueError, - "bad marshal data (unnormalized long data)"); - return NULL; - } - d += (digit)md << j*PyLong_MARSHAL_SHIFT; - } - /* top digit should be nonzero, else the resulting PyLong won't be - normalized */ - ob->ob_digit[size-1] = d; - return (PyObject *)ob; + PyLongObject *ob; + int size, i, j, md, shorts_in_top_digit; + long n; + digit d; + + n = r_long(p); + if (n == 0) + return (PyObject *)_PyLong_New(0); + if (n < -INT_MAX || n > INT_MAX) { + PyErr_SetString(PyExc_ValueError, + "bad marshal data (long size out of range)"); + return NULL; + } + + size = 1 + (ABS(n) - 1) / PyLong_MARSHAL_RATIO; + shorts_in_top_digit = 1 + (ABS(n) - 1) % PyLong_MARSHAL_RATIO; + ob = _PyLong_New(size); + if (ob == NULL) + return NULL; + Py_SIZE(ob) = n > 0 ? size : -size; + + for (i = 0; i < size-1; i++) { + d = 0; + for (j=0; j < PyLong_MARSHAL_RATIO; j++) { + md = r_short(p); + if (md < 0 || md > PyLong_MARSHAL_BASE) + goto bad_digit; + d += (digit)md << j*PyLong_MARSHAL_SHIFT; + } + ob->ob_digit[i] = d; + } + d = 0; + for (j=0; j < shorts_in_top_digit; j++) { + md = r_short(p); + if (md < 0 || md > PyLong_MARSHAL_BASE) + goto bad_digit; + /* topmost marshal digit should be nonzero */ + if (md == 0 && j == shorts_in_top_digit - 1) { + Py_DECREF(ob); + PyErr_SetString(PyExc_ValueError, + "bad marshal data (unnormalized long data)"); + return NULL; + } + d += (digit)md << j*PyLong_MARSHAL_SHIFT; + } + /* top digit should be nonzero, else the resulting PyLong won't be + normalized */ + ob->ob_digit[size-1] = d; + return (PyObject *)ob; bad_digit: - Py_DECREF(ob); - PyErr_SetString(PyExc_ValueError, - "bad marshal data (digit out of range in long)"); - return NULL; + Py_DECREF(ob); + PyErr_SetString(PyExc_ValueError, + "bad marshal data (digit out of range in long)"); + return NULL; } static PyObject * r_object(RFILE *p) { - /* NULL is a valid return value, it does not necessarily means that - an exception is set. */ - PyObject *v, *v2; - long i, n; - int type = r_byte(p); - PyObject *retval; - - p->depth++; - - if (p->depth > MAX_MARSHAL_STACK_DEPTH) { - p->depth--; - PyErr_SetString(PyExc_ValueError, "recursion limit exceeded"); - return NULL; - } - - switch (type) { - - case EOF: - PyErr_SetString(PyExc_EOFError, - "EOF read where object expected"); - retval = NULL; - break; - - case TYPE_NULL: - retval = NULL; - break; - - case TYPE_NONE: - Py_INCREF(Py_None); - retval = Py_None; - break; - - case TYPE_STOPITER: - Py_INCREF(PyExc_StopIteration); - retval = PyExc_StopIteration; - break; - - case TYPE_ELLIPSIS: - Py_INCREF(Py_Ellipsis); - retval = Py_Ellipsis; - break; - - case TYPE_FALSE: - Py_INCREF(Py_False); - retval = Py_False; - break; - - case TYPE_TRUE: - Py_INCREF(Py_True); - retval = Py_True; - break; - - case TYPE_INT: - retval = PyLong_FromLong(r_long(p)); - break; - - case TYPE_INT64: - retval = r_long64(p); - break; - - case TYPE_LONG: - retval = r_PyLong(p); - break; - - case TYPE_FLOAT: - { - char buf[256]; - double dx; - retval = NULL; - n = r_byte(p); - if (n == EOF || r_string(buf, (int)n, p) != n) { - PyErr_SetString(PyExc_EOFError, - "EOF read where object expected"); - break; - } - buf[n] = '\0'; - dx = PyOS_string_to_double(buf, NULL, NULL); - if (dx == -1.0 && PyErr_Occurred()) - break; - retval = PyFloat_FromDouble(dx); - break; - } - - case TYPE_BINARY_FLOAT: - { - unsigned char buf[8]; - double x; - if (r_string((char*)buf, 8, p) != 8) { - PyErr_SetString(PyExc_EOFError, - "EOF read where object expected"); - retval = NULL; - break; - } - x = _PyFloat_Unpack8(buf, 1); - if (x == -1.0 && PyErr_Occurred()) { - retval = NULL; - break; - } - retval = PyFloat_FromDouble(x); - break; - } - - case TYPE_COMPLEX: - { - char buf[256]; - Py_complex c; - retval = NULL; - n = r_byte(p); - if (n == EOF || r_string(buf, (int)n, p) != n) { - PyErr_SetString(PyExc_EOFError, - "EOF read where object expected"); - break; - } - buf[n] = '\0'; - c.real = PyOS_string_to_double(buf, NULL, NULL); - if (c.real == -1.0 && PyErr_Occurred()) - break; - n = r_byte(p); - if (n == EOF || r_string(buf, (int)n, p) != n) { - PyErr_SetString(PyExc_EOFError, - "EOF read where object expected"); - break; - } - buf[n] = '\0'; - c.imag = PyOS_string_to_double(buf, NULL, NULL); - if (c.imag == -1.0 && PyErr_Occurred()) - break; - retval = PyComplex_FromCComplex(c); - break; - } - - case TYPE_BINARY_COMPLEX: - { - unsigned char buf[8]; - Py_complex c; - if (r_string((char*)buf, 8, p) != 8) { - PyErr_SetString(PyExc_EOFError, - "EOF read where object expected"); - retval = NULL; - break; - } - c.real = _PyFloat_Unpack8(buf, 1); - if (c.real == -1.0 && PyErr_Occurred()) { - retval = NULL; - break; - } - if (r_string((char*)buf, 8, p) != 8) { - PyErr_SetString(PyExc_EOFError, - "EOF read where object expected"); - retval = NULL; - break; - } - c.imag = _PyFloat_Unpack8(buf, 1); - if (c.imag == -1.0 && PyErr_Occurred()) { - retval = NULL; - break; - } - retval = PyComplex_FromCComplex(c); - break; - } - - case TYPE_STRING: - n = r_long(p); - if (n < 0 || n > INT_MAX) { - PyErr_SetString(PyExc_ValueError, "bad marshal data (string size out of range)"); - retval = NULL; - break; - } - v = PyBytes_FromStringAndSize((char *)NULL, n); - if (v == NULL) { - retval = NULL; - break; - } - if (r_string(PyBytes_AS_STRING(v), (int)n, p) != n) { - Py_DECREF(v); - PyErr_SetString(PyExc_EOFError, - "EOF read where object expected"); - retval = NULL; - break; - } - retval = v; - break; - - case TYPE_UNICODE: - { - char *buffer; - - n = r_long(p); - if (n < 0 || n > INT_MAX) { - PyErr_SetString(PyExc_ValueError, "bad marshal data (unicode size out of range)"); - retval = NULL; - break; - } - buffer = PyMem_NEW(char, n); - if (buffer == NULL) { - retval = PyErr_NoMemory(); - break; - } - if (r_string(buffer, (int)n, p) != n) { - PyMem_DEL(buffer); - PyErr_SetString(PyExc_EOFError, - "EOF read where object expected"); - retval = NULL; - break; - } - v = PyUnicode_DecodeUTF8(buffer, n, "surrogatepass"); - PyMem_DEL(buffer); - retval = v; - break; - } - - case TYPE_TUPLE: - n = r_long(p); - if (n < 0 || n > INT_MAX) { - PyErr_SetString(PyExc_ValueError, "bad marshal data (tuple size out of range)"); - retval = NULL; - break; - } - v = PyTuple_New((int)n); - if (v == NULL) { - retval = NULL; - break; - } - for (i = 0; i < n; i++) { - v2 = r_object(p); - if ( v2 == NULL ) { - if (!PyErr_Occurred()) - PyErr_SetString(PyExc_TypeError, - "NULL object in marshal data for tuple"); - Py_DECREF(v); - v = NULL; - break; - } - PyTuple_SET_ITEM(v, (int)i, v2); - } - retval = v; - break; - - case TYPE_LIST: - n = r_long(p); - if (n < 0 || n > INT_MAX) { - PyErr_SetString(PyExc_ValueError, "bad marshal data (list size out of range)"); - retval = NULL; - break; - } - v = PyList_New((int)n); - if (v == NULL) { - retval = NULL; - break; - } - for (i = 0; i < n; i++) { - v2 = r_object(p); - if ( v2 == NULL ) { - if (!PyErr_Occurred()) - PyErr_SetString(PyExc_TypeError, - "NULL object in marshal data for list"); - Py_DECREF(v); - v = NULL; - break; - } - PyList_SET_ITEM(v, (int)i, v2); - } - retval = v; - break; - - case TYPE_DICT: - v = PyDict_New(); - if (v == NULL) { - retval = NULL; - break; - } - for (;;) { - PyObject *key, *val; - key = r_object(p); - if (key == NULL) - break; - val = r_object(p); - if (val != NULL) - PyDict_SetItem(v, key, val); - Py_DECREF(key); - Py_XDECREF(val); - } - if (PyErr_Occurred()) { - Py_DECREF(v); - v = NULL; - } - retval = v; - break; - - case TYPE_SET: - case TYPE_FROZENSET: - n = r_long(p); - if (n < 0 || n > INT_MAX) { - PyErr_SetString(PyExc_ValueError, "bad marshal data (set size out of range)"); - retval = NULL; - break; - } - v = (type == TYPE_SET) ? PySet_New(NULL) : PyFrozenSet_New(NULL); - if (v == NULL) { - retval = NULL; - break; - } - for (i = 0; i < n; i++) { - v2 = r_object(p); - if ( v2 == NULL ) { - if (!PyErr_Occurred()) - PyErr_SetString(PyExc_TypeError, - "NULL object in marshal data for set"); - Py_DECREF(v); - v = NULL; - break; - } - if (PySet_Add(v, v2) == -1) { - Py_DECREF(v); - Py_DECREF(v2); - v = NULL; - break; - } - Py_DECREF(v2); - } - retval = v; - break; - - case TYPE_CODE: - { - int argcount; - int kwonlyargcount; - int nlocals; - int stacksize; - int flags; - PyObject *code = NULL; - PyObject *consts = NULL; - PyObject *names = NULL; - PyObject *varnames = NULL; - PyObject *freevars = NULL; - PyObject *cellvars = NULL; - PyObject *filename = NULL; - PyObject *name = NULL; - int firstlineno; - PyObject *lnotab = NULL; - - v = NULL; - - /* XXX ignore long->int overflows for now */ - argcount = (int)r_long(p); - kwonlyargcount = (int)r_long(p); - nlocals = (int)r_long(p); - stacksize = (int)r_long(p); - flags = (int)r_long(p); - code = r_object(p); - if (code == NULL) - goto code_error; - consts = r_object(p); - if (consts == NULL) - goto code_error; - names = r_object(p); - if (names == NULL) - goto code_error; - varnames = r_object(p); - if (varnames == NULL) - goto code_error; - freevars = r_object(p); - if (freevars == NULL) - goto code_error; - cellvars = r_object(p); - if (cellvars == NULL) - goto code_error; - filename = r_object(p); - if (filename == NULL) - goto code_error; - name = r_object(p); - if (name == NULL) - goto code_error; - firstlineno = (int)r_long(p); - lnotab = r_object(p); - if (lnotab == NULL) - goto code_error; - - v = (PyObject *) PyCode_New( - argcount, kwonlyargcount, - nlocals, stacksize, flags, - code, consts, names, varnames, - freevars, cellvars, filename, name, - firstlineno, lnotab); - - code_error: - Py_XDECREF(code); - Py_XDECREF(consts); - Py_XDECREF(names); - Py_XDECREF(varnames); - Py_XDECREF(freevars); - Py_XDECREF(cellvars); - Py_XDECREF(filename); - Py_XDECREF(name); - Py_XDECREF(lnotab); - } - retval = v; - break; - - default: - /* Bogus data got written, which isn't ideal. - This will let you keep working and recover. */ - PyErr_SetString(PyExc_ValueError, "bad marshal data (unknown type code)"); - retval = NULL; - break; - - } - p->depth--; - return retval; + /* NULL is a valid return value, it does not necessarily means that + an exception is set. */ + PyObject *v, *v2; + long i, n; + int type = r_byte(p); + PyObject *retval; + + p->depth++; + + if (p->depth > MAX_MARSHAL_STACK_DEPTH) { + p->depth--; + PyErr_SetString(PyExc_ValueError, "recursion limit exceeded"); + return NULL; + } + + switch (type) { + + case EOF: + PyErr_SetString(PyExc_EOFError, + "EOF read where object expected"); + retval = NULL; + break; + + case TYPE_NULL: + retval = NULL; + break; + + case TYPE_NONE: + Py_INCREF(Py_None); + retval = Py_None; + break; + + case TYPE_STOPITER: + Py_INCREF(PyExc_StopIteration); + retval = PyExc_StopIteration; + break; + + case TYPE_ELLIPSIS: + Py_INCREF(Py_Ellipsis); + retval = Py_Ellipsis; + break; + + case TYPE_FALSE: + Py_INCREF(Py_False); + retval = Py_False; + break; + + case TYPE_TRUE: + Py_INCREF(Py_True); + retval = Py_True; + break; + + case TYPE_INT: + retval = PyLong_FromLong(r_long(p)); + break; + + case TYPE_INT64: + retval = r_long64(p); + break; + + case TYPE_LONG: + retval = r_PyLong(p); + break; + + case TYPE_FLOAT: + { + char buf[256]; + double dx; + retval = NULL; + n = r_byte(p); + if (n == EOF || r_string(buf, (int)n, p) != n) { + PyErr_SetString(PyExc_EOFError, + "EOF read where object expected"); + break; + } + buf[n] = '\0'; + dx = PyOS_string_to_double(buf, NULL, NULL); + if (dx == -1.0 && PyErr_Occurred()) + break; + retval = PyFloat_FromDouble(dx); + break; + } + + case TYPE_BINARY_FLOAT: + { + unsigned char buf[8]; + double x; + if (r_string((char*)buf, 8, p) != 8) { + PyErr_SetString(PyExc_EOFError, + "EOF read where object expected"); + retval = NULL; + break; + } + x = _PyFloat_Unpack8(buf, 1); + if (x == -1.0 && PyErr_Occurred()) { + retval = NULL; + break; + } + retval = PyFloat_FromDouble(x); + break; + } + + case TYPE_COMPLEX: + { + char buf[256]; + Py_complex c; + retval = NULL; + n = r_byte(p); + if (n == EOF || r_string(buf, (int)n, p) != n) { + PyErr_SetString(PyExc_EOFError, + "EOF read where object expected"); + break; + } + buf[n] = '\0'; + c.real = PyOS_string_to_double(buf, NULL, NULL); + if (c.real == -1.0 && PyErr_Occurred()) + break; + n = r_byte(p); + if (n == EOF || r_string(buf, (int)n, p) != n) { + PyErr_SetString(PyExc_EOFError, + "EOF read where object expected"); + break; + } + buf[n] = '\0'; + c.imag = PyOS_string_to_double(buf, NULL, NULL); + if (c.imag == -1.0 && PyErr_Occurred()) + break; + retval = PyComplex_FromCComplex(c); + break; + } + + case TYPE_BINARY_COMPLEX: + { + unsigned char buf[8]; + Py_complex c; + if (r_string((char*)buf, 8, p) != 8) { + PyErr_SetString(PyExc_EOFError, + "EOF read where object expected"); + retval = NULL; + break; + } + c.real = _PyFloat_Unpack8(buf, 1); + if (c.real == -1.0 && PyErr_Occurred()) { + retval = NULL; + break; + } + if (r_string((char*)buf, 8, p) != 8) { + PyErr_SetString(PyExc_EOFError, + "EOF read where object expected"); + retval = NULL; + break; + } + c.imag = _PyFloat_Unpack8(buf, 1); + if (c.imag == -1.0 && PyErr_Occurred()) { + retval = NULL; + break; + } + retval = PyComplex_FromCComplex(c); + break; + } + + case TYPE_STRING: + n = r_long(p); + if (n < 0 || n > INT_MAX) { + PyErr_SetString(PyExc_ValueError, "bad marshal data (string size out of range)"); + retval = NULL; + break; + } + v = PyBytes_FromStringAndSize((char *)NULL, n); + if (v == NULL) { + retval = NULL; + break; + } + if (r_string(PyBytes_AS_STRING(v), (int)n, p) != n) { + Py_DECREF(v); + PyErr_SetString(PyExc_EOFError, + "EOF read where object expected"); + retval = NULL; + break; + } + retval = v; + break; + + case TYPE_UNICODE: + { + char *buffer; + + n = r_long(p); + if (n < 0 || n > INT_MAX) { + PyErr_SetString(PyExc_ValueError, "bad marshal data (unicode size out of range)"); + retval = NULL; + break; + } + buffer = PyMem_NEW(char, n); + if (buffer == NULL) { + retval = PyErr_NoMemory(); + break; + } + if (r_string(buffer, (int)n, p) != n) { + PyMem_DEL(buffer); + PyErr_SetString(PyExc_EOFError, + "EOF read where object expected"); + retval = NULL; + break; + } + v = PyUnicode_DecodeUTF8(buffer, n, "surrogatepass"); + PyMem_DEL(buffer); + retval = v; + break; + } + + case TYPE_TUPLE: + n = r_long(p); + if (n < 0 || n > INT_MAX) { + PyErr_SetString(PyExc_ValueError, "bad marshal data (tuple size out of range)"); + retval = NULL; + break; + } + v = PyTuple_New((int)n); + if (v == NULL) { + retval = NULL; + break; + } + for (i = 0; i < n; i++) { + v2 = r_object(p); + if ( v2 == NULL ) { + if (!PyErr_Occurred()) + PyErr_SetString(PyExc_TypeError, + "NULL object in marshal data for tuple"); + Py_DECREF(v); + v = NULL; + break; + } + PyTuple_SET_ITEM(v, (int)i, v2); + } + retval = v; + break; + + case TYPE_LIST: + n = r_long(p); + if (n < 0 || n > INT_MAX) { + PyErr_SetString(PyExc_ValueError, "bad marshal data (list size out of range)"); + retval = NULL; + break; + } + v = PyList_New((int)n); + if (v == NULL) { + retval = NULL; + break; + } + for (i = 0; i < n; i++) { + v2 = r_object(p); + if ( v2 == NULL ) { + if (!PyErr_Occurred()) + PyErr_SetString(PyExc_TypeError, + "NULL object in marshal data for list"); + Py_DECREF(v); + v = NULL; + break; + } + PyList_SET_ITEM(v, (int)i, v2); + } + retval = v; + break; + + case TYPE_DICT: + v = PyDict_New(); + if (v == NULL) { + retval = NULL; + break; + } + for (;;) { + PyObject *key, *val; + key = r_object(p); + if (key == NULL) + break; + val = r_object(p); + if (val != NULL) + PyDict_SetItem(v, key, val); + Py_DECREF(key); + Py_XDECREF(val); + } + if (PyErr_Occurred()) { + Py_DECREF(v); + v = NULL; + } + retval = v; + break; + + case TYPE_SET: + case TYPE_FROZENSET: + n = r_long(p); + if (n < 0 || n > INT_MAX) { + PyErr_SetString(PyExc_ValueError, "bad marshal data (set size out of range)"); + retval = NULL; + break; + } + v = (type == TYPE_SET) ? PySet_New(NULL) : PyFrozenSet_New(NULL); + if (v == NULL) { + retval = NULL; + break; + } + for (i = 0; i < n; i++) { + v2 = r_object(p); + if ( v2 == NULL ) { + if (!PyErr_Occurred()) + PyErr_SetString(PyExc_TypeError, + "NULL object in marshal data for set"); + Py_DECREF(v); + v = NULL; + break; + } + if (PySet_Add(v, v2) == -1) { + Py_DECREF(v); + Py_DECREF(v2); + v = NULL; + break; + } + Py_DECREF(v2); + } + retval = v; + break; + + case TYPE_CODE: + { + int argcount; + int kwonlyargcount; + int nlocals; + int stacksize; + int flags; + PyObject *code = NULL; + PyObject *consts = NULL; + PyObject *names = NULL; + PyObject *varnames = NULL; + PyObject *freevars = NULL; + PyObject *cellvars = NULL; + PyObject *filename = NULL; + PyObject *name = NULL; + int firstlineno; + PyObject *lnotab = NULL; + + v = NULL; + + /* XXX ignore long->int overflows for now */ + argcount = (int)r_long(p); + kwonlyargcount = (int)r_long(p); + nlocals = (int)r_long(p); + stacksize = (int)r_long(p); + flags = (int)r_long(p); + code = r_object(p); + if (code == NULL) + goto code_error; + consts = r_object(p); + if (consts == NULL) + goto code_error; + names = r_object(p); + if (names == NULL) + goto code_error; + varnames = r_object(p); + if (varnames == NULL) + goto code_error; + freevars = r_object(p); + if (freevars == NULL) + goto code_error; + cellvars = r_object(p); + if (cellvars == NULL) + goto code_error; + filename = r_object(p); + if (filename == NULL) + goto code_error; + name = r_object(p); + if (name == NULL) + goto code_error; + firstlineno = (int)r_long(p); + lnotab = r_object(p); + if (lnotab == NULL) + goto code_error; + + v = (PyObject *) PyCode_New( + argcount, kwonlyargcount, + nlocals, stacksize, flags, + code, consts, names, varnames, + freevars, cellvars, filename, name, + firstlineno, lnotab); + + code_error: + Py_XDECREF(code); + Py_XDECREF(consts); + Py_XDECREF(names); + Py_XDECREF(varnames); + Py_XDECREF(freevars); + Py_XDECREF(cellvars); + Py_XDECREF(filename); + Py_XDECREF(name); + Py_XDECREF(lnotab); + } + retval = v; + break; + + default: + /* Bogus data got written, which isn't ideal. + This will let you keep working and recover. */ + PyErr_SetString(PyExc_ValueError, "bad marshal data (unknown type code)"); + retval = NULL; + break; + + } + p->depth--; + return retval; } static PyObject * read_object(RFILE *p) { - PyObject *v; - if (PyErr_Occurred()) { - fprintf(stderr, "XXX readobject called with exception set\n"); - return NULL; - } - v = r_object(p); - if (v == NULL && !PyErr_Occurred()) - PyErr_SetString(PyExc_TypeError, "NULL object in marshal data for object"); - return v; + PyObject *v; + if (PyErr_Occurred()) { + fprintf(stderr, "XXX readobject called with exception set\n"); + return NULL; + } + v = r_object(p); + if (v == NULL && !PyErr_Occurred()) + PyErr_SetString(PyExc_TypeError, "NULL object in marshal data for object"); + return v; } int PyMarshal_ReadShortFromFile(FILE *fp) { - RFILE rf; - assert(fp); - rf.fp = fp; - rf.strings = NULL; - rf.end = rf.ptr = NULL; - return r_short(&rf); + RFILE rf; + assert(fp); + rf.fp = fp; + rf.strings = NULL; + rf.end = rf.ptr = NULL; + return r_short(&rf); } long PyMarshal_ReadLongFromFile(FILE *fp) { - RFILE rf; - rf.fp = fp; - rf.strings = NULL; - rf.ptr = rf.end = NULL; - return r_long(&rf); + RFILE rf; + rf.fp = fp; + rf.strings = NULL; + rf.ptr = rf.end = NULL; + return r_long(&rf); } #ifdef HAVE_FSTAT @@ -1061,11 +1061,11 @@ static off_t getfilesize(FILE *fp) { - struct stat st; - if (fstat(fileno(fp), &st) != 0) - return -1; - else - return st.st_size; + struct stat st; + if (fstat(fileno(fp), &st) != 0) + return -1; + else + return st.st_size; } #endif @@ -1081,27 +1081,27 @@ /* REASONABLE_FILE_LIMIT is by defn something big enough for Tkinter.pyc. */ #define REASONABLE_FILE_LIMIT (1L << 18) #ifdef HAVE_FSTAT - off_t filesize; - filesize = getfilesize(fp); - if (filesize > 0 && filesize <= REASONABLE_FILE_LIMIT) { - char* pBuf = (char *)PyMem_MALLOC(filesize); - if (pBuf != NULL) { - PyObject* v; - size_t n; - /* filesize must fit into an int, because it - is smaller than REASONABLE_FILE_LIMIT */ - n = fread(pBuf, 1, (int)filesize, fp); - v = PyMarshal_ReadObjectFromString(pBuf, n); - PyMem_FREE(pBuf); - return v; - } + off_t filesize; + filesize = getfilesize(fp); + if (filesize > 0 && filesize <= REASONABLE_FILE_LIMIT) { + char* pBuf = (char *)PyMem_MALLOC(filesize); + if (pBuf != NULL) { + PyObject* v; + size_t n; + /* filesize must fit into an int, because it + is smaller than REASONABLE_FILE_LIMIT */ + n = fread(pBuf, 1, (int)filesize, fp); + v = PyMarshal_ReadObjectFromString(pBuf, n); + PyMem_FREE(pBuf); + return v; + } - } + } #endif - /* We don't have fstat, or we do but the file is larger than - * REASONABLE_FILE_LIMIT or malloc failed -- read a byte at a time. - */ - return PyMarshal_ReadObjectFromFile(fp); + /* We don't have fstat, or we do but the file is larger than + * REASONABLE_FILE_LIMIT or malloc failed -- read a byte at a time. + */ + return PyMarshal_ReadObjectFromFile(fp); #undef REASONABLE_FILE_LIMIT } @@ -1109,77 +1109,77 @@ PyObject * PyMarshal_ReadObjectFromFile(FILE *fp) { - RFILE rf; - PyObject *result; - rf.fp = fp; - rf.strings = PyList_New(0); - rf.depth = 0; - rf.ptr = rf.end = NULL; - result = r_object(&rf); - Py_DECREF(rf.strings); - return result; + RFILE rf; + PyObject *result; + rf.fp = fp; + rf.strings = PyList_New(0); + rf.depth = 0; + rf.ptr = rf.end = NULL; + result = r_object(&rf); + Py_DECREF(rf.strings); + return result; } PyObject * PyMarshal_ReadObjectFromString(char *str, Py_ssize_t len) { - RFILE rf; - PyObject *result; - rf.fp = NULL; - rf.ptr = str; - rf.end = str + len; - rf.strings = PyList_New(0); - rf.depth = 0; - result = r_object(&rf); - Py_DECREF(rf.strings); - return result; + RFILE rf; + PyObject *result; + rf.fp = NULL; + rf.ptr = str; + rf.end = str + len; + rf.strings = PyList_New(0); + rf.depth = 0; + result = r_object(&rf); + Py_DECREF(rf.strings); + return result; } PyObject * PyMarshal_WriteObjectToString(PyObject *x, int version) { - WFILE wf; - PyObject *res = NULL; + WFILE wf; + PyObject *res = NULL; - wf.fp = NULL; - wf.str = PyBytes_FromStringAndSize((char *)NULL, 50); - if (wf.str == NULL) - return NULL; - wf.ptr = PyBytes_AS_STRING((PyBytesObject *)wf.str); - wf.end = wf.ptr + PyBytes_Size(wf.str); - wf.error = WFERR_OK; - wf.depth = 0; - wf.version = version; - wf.strings = (version > 0) ? PyDict_New() : NULL; - w_object(x, &wf); - Py_XDECREF(wf.strings); - if (wf.str != NULL) { - char *base = PyBytes_AS_STRING((PyBytesObject *)wf.str); - if (wf.ptr - base > PY_SSIZE_T_MAX) { - Py_DECREF(wf.str); - PyErr_SetString(PyExc_OverflowError, - "too much marshal data for a string"); - return NULL; - } - if (_PyBytes_Resize(&wf.str, (Py_ssize_t)(wf.ptr - base)) < 0) - return NULL; - } - if (wf.error != WFERR_OK) { - Py_XDECREF(wf.str); - if (wf.error == WFERR_NOMEMORY) - PyErr_NoMemory(); - else - PyErr_SetString(PyExc_ValueError, - (wf.error==WFERR_UNMARSHALLABLE)?"unmarshallable object" - :"object too deeply nested to marshal"); - return NULL; - } - if (wf.str != NULL) { - /* XXX Quick hack -- need to do this differently */ - res = PyBytes_FromObject(wf.str); - Py_DECREF(wf.str); - } - return res; + wf.fp = NULL; + wf.str = PyBytes_FromStringAndSize((char *)NULL, 50); + if (wf.str == NULL) + return NULL; + wf.ptr = PyBytes_AS_STRING((PyBytesObject *)wf.str); + wf.end = wf.ptr + PyBytes_Size(wf.str); + wf.error = WFERR_OK; + wf.depth = 0; + wf.version = version; + wf.strings = (version > 0) ? PyDict_New() : NULL; + w_object(x, &wf); + Py_XDECREF(wf.strings); + if (wf.str != NULL) { + char *base = PyBytes_AS_STRING((PyBytesObject *)wf.str); + if (wf.ptr - base > PY_SSIZE_T_MAX) { + Py_DECREF(wf.str); + PyErr_SetString(PyExc_OverflowError, + "too much marshal data for a string"); + return NULL; + } + if (_PyBytes_Resize(&wf.str, (Py_ssize_t)(wf.ptr - base)) < 0) + return NULL; + } + if (wf.error != WFERR_OK) { + Py_XDECREF(wf.str); + if (wf.error == WFERR_NOMEMORY) + PyErr_NoMemory(); + else + PyErr_SetString(PyExc_ValueError, + (wf.error==WFERR_UNMARSHALLABLE)?"unmarshallable object" + :"object too deeply nested to marshal"); + return NULL; + } + if (wf.str != NULL) { + /* XXX Quick hack -- need to do this differently */ + res = PyBytes_FromObject(wf.str); + Py_DECREF(wf.str); + } + return res; } /* And an interface for Python programs... */ @@ -1187,20 +1187,20 @@ static PyObject * marshal_dump(PyObject *self, PyObject *args) { - /* XXX Quick hack -- need to do this differently */ - PyObject *x; - PyObject *f; - int version = Py_MARSHAL_VERSION; - PyObject *s; - PyObject *res; - if (!PyArg_ParseTuple(args, "OO|i:dump", &x, &f, &version)) - return NULL; - s = PyMarshal_WriteObjectToString(x, version); - if (s == NULL) - return NULL; - res = PyObject_CallMethod(f, "write", "O", s); - Py_DECREF(s); - return res; + /* XXX Quick hack -- need to do this differently */ + PyObject *x; + PyObject *f; + int version = Py_MARSHAL_VERSION; + PyObject *s; + PyObject *res; + if (!PyArg_ParseTuple(args, "OO|i:dump", &x, &f, &version)) + return NULL; + s = PyMarshal_WriteObjectToString(x, version); + if (s == NULL) + return NULL; + res = PyObject_CallMethod(f, "write", "O", s); + Py_DECREF(s); + return res; } PyDoc_STRVAR(dump_doc, @@ -1219,35 +1219,35 @@ static PyObject * marshal_load(PyObject *self, PyObject *f) { - /* XXX Quick hack -- need to do this differently */ - PyObject *data, *result; - RFILE rf; - data = PyObject_CallMethod(f, "read", ""); - if (data == NULL) - return NULL; - rf.fp = NULL; - if (PyBytes_Check(data)) { - rf.ptr = PyBytes_AS_STRING(data); - rf.end = rf.ptr + PyBytes_GET_SIZE(data); - } - else if (PyBytes_Check(data)) { - rf.ptr = PyBytes_AS_STRING(data); - rf.end = rf.ptr + PyBytes_GET_SIZE(data); - } - else { - PyErr_Format(PyExc_TypeError, - "f.read() returned neither string " - "nor bytes but %.100s", - data->ob_type->tp_name); - Py_DECREF(data); - return NULL; - } - rf.strings = PyList_New(0); - rf.depth = 0; - result = read_object(&rf); - Py_DECREF(rf.strings); - Py_DECREF(data); - return result; + /* XXX Quick hack -- need to do this differently */ + PyObject *data, *result; + RFILE rf; + data = PyObject_CallMethod(f, "read", ""); + if (data == NULL) + return NULL; + rf.fp = NULL; + if (PyBytes_Check(data)) { + rf.ptr = PyBytes_AS_STRING(data); + rf.end = rf.ptr + PyBytes_GET_SIZE(data); + } + else if (PyBytes_Check(data)) { + rf.ptr = PyBytes_AS_STRING(data); + rf.end = rf.ptr + PyBytes_GET_SIZE(data); + } + else { + PyErr_Format(PyExc_TypeError, + "f.read() returned neither string " + "nor bytes but %.100s", + data->ob_type->tp_name); + Py_DECREF(data); + return NULL; + } + rf.strings = PyList_New(0); + rf.depth = 0; + result = read_object(&rf); + Py_DECREF(rf.strings); + Py_DECREF(data); + return result; } PyDoc_STRVAR(load_doc, @@ -1266,11 +1266,11 @@ static PyObject * marshal_dumps(PyObject *self, PyObject *args) { - PyObject *x; - int version = Py_MARSHAL_VERSION; - if (!PyArg_ParseTuple(args, "O|i:dumps", &x, &version)) - return NULL; - return PyMarshal_WriteObjectToString(x, version); + PyObject *x; + int version = Py_MARSHAL_VERSION; + if (!PyArg_ParseTuple(args, "O|i:dumps", &x, &version)) + return NULL; + return PyMarshal_WriteObjectToString(x, version); } PyDoc_STRVAR(dumps_doc, @@ -1286,24 +1286,24 @@ static PyObject * marshal_loads(PyObject *self, PyObject *args) { - RFILE rf; - Py_buffer p; - char *s; - Py_ssize_t n; - PyObject* result; - if (!PyArg_ParseTuple(args, "s*:loads", &p)) - return NULL; - s = p.buf; - n = p.len; - rf.fp = NULL; - rf.ptr = s; - rf.end = s + n; - rf.strings = PyList_New(0); - rf.depth = 0; - result = read_object(&rf); - Py_DECREF(rf.strings); - PyBuffer_Release(&p); - return result; + RFILE rf; + Py_buffer p; + char *s; + Py_ssize_t n; + PyObject* result; + if (!PyArg_ParseTuple(args, "s*:loads", &p)) + return NULL; + s = p.buf; + n = p.len; + rf.fp = NULL; + rf.ptr = s; + rf.end = s + n; + rf.strings = PyList_New(0); + rf.depth = 0; + result = read_object(&rf); + Py_DECREF(rf.strings); + PyBuffer_Release(&p); + return result; } PyDoc_STRVAR(loads_doc, @@ -1314,11 +1314,11 @@ ignored."); static PyMethodDef marshal_methods[] = { - {"dump", marshal_dump, METH_VARARGS, dump_doc}, - {"load", marshal_load, METH_O, load_doc}, - {"dumps", marshal_dumps, METH_VARARGS, dumps_doc}, - {"loads", marshal_loads, METH_VARARGS, loads_doc}, - {NULL, NULL} /* sentinel */ + {"dump", marshal_dump, METH_VARARGS, dump_doc}, + {"load", marshal_load, METH_O, load_doc}, + {"dumps", marshal_dumps, METH_VARARGS, dumps_doc}, + {"loads", marshal_loads, METH_VARARGS, loads_doc}, + {NULL, NULL} /* sentinel */ }; @@ -1353,23 +1353,23 @@ static struct PyModuleDef marshalmodule = { - PyModuleDef_HEAD_INIT, - "marshal", - module_doc, - 0, - marshal_methods, - NULL, - NULL, - NULL, - NULL + PyModuleDef_HEAD_INIT, + "marshal", + module_doc, + 0, + marshal_methods, + NULL, + NULL, + NULL, + NULL }; PyMODINIT_FUNC PyMarshal_Init(void) { - PyObject *mod = PyModule_Create(&marshalmodule); - if (mod == NULL) - return NULL; - PyModule_AddIntConstant(mod, "version", Py_MARSHAL_VERSION); - return mod; + PyObject *mod = PyModule_Create(&marshalmodule); + if (mod == NULL) + return NULL; + PyModule_AddIntConstant(mod, "version", Py_MARSHAL_VERSION); + return mod; } Modified: python/branches/py3k/Python/modsupport.c ============================================================================== --- python/branches/py3k/Python/modsupport.c (original) +++ python/branches/py3k/Python/modsupport.c Sun May 9 17:52:27 2010 @@ -16,41 +16,41 @@ static int countformat(const char *format, int endchar) { - int count = 0; - int level = 0; - while (level > 0 || *format != endchar) { - switch (*format) { - case '\0': - /* Premature end */ - PyErr_SetString(PyExc_SystemError, - "unmatched paren in format"); - return -1; - case '(': - case '[': - case '{': - if (level == 0) - count++; - level++; - break; - case ')': - case ']': - case '}': - level--; - break; - case '#': - case '&': - case ',': - case ':': - case ' ': - case '\t': - break; - default: - if (level == 0) - count++; - } - format++; - } - return count; + int count = 0; + int level = 0; + while (level > 0 || *format != endchar) { + switch (*format) { + case '\0': + /* Premature end */ + PyErr_SetString(PyExc_SystemError, + "unmatched paren in format"); + return -1; + case '(': + case '[': + case '{': + if (level == 0) + count++; + level++; + break; + case ')': + case ']': + case '}': + level--; + break; + case '#': + case '&': + case ',': + case ':': + case ' ': + case '\t': + break; + default: + if (level == 0) + count++; + } + format++; + } + return count; } @@ -66,550 +66,550 @@ static PyObject * do_mkdict(const char **p_format, va_list *p_va, int endchar, int n, int flags) { - PyObject *d; - int i; - int itemfailed = 0; - if (n < 0) - return NULL; - if ((d = PyDict_New()) == NULL) - return NULL; - /* Note that we can't bail immediately on error as this will leak - refcounts on any 'N' arguments. */ - for (i = 0; i < n; i+= 2) { - PyObject *k, *v; - int err; - k = do_mkvalue(p_format, p_va, flags); - if (k == NULL) { - itemfailed = 1; - Py_INCREF(Py_None); - k = Py_None; - } - v = do_mkvalue(p_format, p_va, flags); - if (v == NULL) { - itemfailed = 1; - Py_INCREF(Py_None); - v = Py_None; - } - err = PyDict_SetItem(d, k, v); - Py_DECREF(k); - Py_DECREF(v); - if (err < 0 || itemfailed) { - Py_DECREF(d); - return NULL; - } - } - if (d != NULL && **p_format != endchar) { - Py_DECREF(d); - d = NULL; - PyErr_SetString(PyExc_SystemError, - "Unmatched paren in format"); - } - else if (endchar) - ++*p_format; - return d; + PyObject *d; + int i; + int itemfailed = 0; + if (n < 0) + return NULL; + if ((d = PyDict_New()) == NULL) + return NULL; + /* Note that we can't bail immediately on error as this will leak + refcounts on any 'N' arguments. */ + for (i = 0; i < n; i+= 2) { + PyObject *k, *v; + int err; + k = do_mkvalue(p_format, p_va, flags); + if (k == NULL) { + itemfailed = 1; + Py_INCREF(Py_None); + k = Py_None; + } + v = do_mkvalue(p_format, p_va, flags); + if (v == NULL) { + itemfailed = 1; + Py_INCREF(Py_None); + v = Py_None; + } + err = PyDict_SetItem(d, k, v); + Py_DECREF(k); + Py_DECREF(v); + if (err < 0 || itemfailed) { + Py_DECREF(d); + return NULL; + } + } + if (d != NULL && **p_format != endchar) { + Py_DECREF(d); + d = NULL; + PyErr_SetString(PyExc_SystemError, + "Unmatched paren in format"); + } + else if (endchar) + ++*p_format; + return d; } static PyObject * do_mklist(const char **p_format, va_list *p_va, int endchar, int n, int flags) { - PyObject *v; - int i; - int itemfailed = 0; - if (n < 0) - return NULL; - v = PyList_New(n); - if (v == NULL) - return NULL; - /* Note that we can't bail immediately on error as this will leak - refcounts on any 'N' arguments. */ - for (i = 0; i < n; i++) { - PyObject *w = do_mkvalue(p_format, p_va, flags); - if (w == NULL) { - itemfailed = 1; - Py_INCREF(Py_None); - w = Py_None; - } - PyList_SET_ITEM(v, i, w); - } - - if (itemfailed) { - /* do_mkvalue() should have already set an error */ - Py_DECREF(v); - return NULL; - } - if (**p_format != endchar) { - Py_DECREF(v); - PyErr_SetString(PyExc_SystemError, - "Unmatched paren in format"); - return NULL; - } - if (endchar) - ++*p_format; - return v; + PyObject *v; + int i; + int itemfailed = 0; + if (n < 0) + return NULL; + v = PyList_New(n); + if (v == NULL) + return NULL; + /* Note that we can't bail immediately on error as this will leak + refcounts on any 'N' arguments. */ + for (i = 0; i < n; i++) { + PyObject *w = do_mkvalue(p_format, p_va, flags); + if (w == NULL) { + itemfailed = 1; + Py_INCREF(Py_None); + w = Py_None; + } + PyList_SET_ITEM(v, i, w); + } + + if (itemfailed) { + /* do_mkvalue() should have already set an error */ + Py_DECREF(v); + return NULL; + } + if (**p_format != endchar) { + Py_DECREF(v); + PyErr_SetString(PyExc_SystemError, + "Unmatched paren in format"); + return NULL; + } + if (endchar) + ++*p_format; + return v; } static int _ustrlen(Py_UNICODE *u) { - int i = 0; - Py_UNICODE *v = u; - while (*v != 0) { i++; v++; } - return i; + int i = 0; + Py_UNICODE *v = u; + while (*v != 0) { i++; v++; } + return i; } static PyObject * do_mktuple(const char **p_format, va_list *p_va, int endchar, int n, int flags) { - PyObject *v; - int i; - int itemfailed = 0; - if (n < 0) - return NULL; - if ((v = PyTuple_New(n)) == NULL) - return NULL; - /* Note that we can't bail immediately on error as this will leak - refcounts on any 'N' arguments. */ - for (i = 0; i < n; i++) { - PyObject *w = do_mkvalue(p_format, p_va, flags); - if (w == NULL) { - itemfailed = 1; - Py_INCREF(Py_None); - w = Py_None; - } - PyTuple_SET_ITEM(v, i, w); - } - if (itemfailed) { - /* do_mkvalue() should have already set an error */ - Py_DECREF(v); - return NULL; - } - if (**p_format != endchar) { - Py_DECREF(v); - PyErr_SetString(PyExc_SystemError, - "Unmatched paren in format"); - return NULL; - } - if (endchar) - ++*p_format; - return v; + PyObject *v; + int i; + int itemfailed = 0; + if (n < 0) + return NULL; + if ((v = PyTuple_New(n)) == NULL) + return NULL; + /* Note that we can't bail immediately on error as this will leak + refcounts on any 'N' arguments. */ + for (i = 0; i < n; i++) { + PyObject *w = do_mkvalue(p_format, p_va, flags); + if (w == NULL) { + itemfailed = 1; + Py_INCREF(Py_None); + w = Py_None; + } + PyTuple_SET_ITEM(v, i, w); + } + if (itemfailed) { + /* do_mkvalue() should have already set an error */ + Py_DECREF(v); + return NULL; + } + if (**p_format != endchar) { + Py_DECREF(v); + PyErr_SetString(PyExc_SystemError, + "Unmatched paren in format"); + return NULL; + } + if (endchar) + ++*p_format; + return v; } static PyObject * do_mkvalue(const char **p_format, va_list *p_va, int flags) { - for (;;) { - switch (*(*p_format)++) { - case '(': - return do_mktuple(p_format, p_va, ')', - countformat(*p_format, ')'), flags); - - case '[': - return do_mklist(p_format, p_va, ']', - countformat(*p_format, ']'), flags); - - case '{': - return do_mkdict(p_format, p_va, '}', - countformat(*p_format, '}'), flags); - - case 'b': - case 'B': - case 'h': - case 'i': - return PyLong_FromLong((long)va_arg(*p_va, int)); - - case 'H': - return PyLong_FromLong((long)va_arg(*p_va, unsigned int)); - - case 'I': - { - unsigned int n; - n = va_arg(*p_va, unsigned int); - return PyLong_FromUnsignedLong(n); - } - - case 'n': + for (;;) { + switch (*(*p_format)++) { + case '(': + return do_mktuple(p_format, p_va, ')', + countformat(*p_format, ')'), flags); + + case '[': + return do_mklist(p_format, p_va, ']', + countformat(*p_format, ']'), flags); + + case '{': + return do_mkdict(p_format, p_va, '}', + countformat(*p_format, '}'), flags); + + case 'b': + case 'B': + case 'h': + case 'i': + return PyLong_FromLong((long)va_arg(*p_va, int)); + + case 'H': + return PyLong_FromLong((long)va_arg(*p_va, unsigned int)); + + case 'I': + { + unsigned int n; + n = va_arg(*p_va, unsigned int); + return PyLong_FromUnsignedLong(n); + } + + case 'n': #if SIZEOF_SIZE_T!=SIZEOF_LONG - return PyLong_FromSsize_t(va_arg(*p_va, Py_ssize_t)); + return PyLong_FromSsize_t(va_arg(*p_va, Py_ssize_t)); #endif - /* Fall through from 'n' to 'l' if Py_ssize_t is long */ - case 'l': - return PyLong_FromLong(va_arg(*p_va, long)); - - case 'k': - { - unsigned long n; - n = va_arg(*p_va, unsigned long); - return PyLong_FromUnsignedLong(n); - } + /* Fall through from 'n' to 'l' if Py_ssize_t is long */ + case 'l': + return PyLong_FromLong(va_arg(*p_va, long)); + + case 'k': + { + unsigned long n; + n = va_arg(*p_va, unsigned long); + return PyLong_FromUnsignedLong(n); + } #ifdef HAVE_LONG_LONG - case 'L': - return PyLong_FromLongLong((PY_LONG_LONG)va_arg(*p_va, PY_LONG_LONG)); + case 'L': + return PyLong_FromLongLong((PY_LONG_LONG)va_arg(*p_va, PY_LONG_LONG)); - case 'K': - return PyLong_FromUnsignedLongLong((PY_LONG_LONG)va_arg(*p_va, unsigned PY_LONG_LONG)); + case 'K': + return PyLong_FromUnsignedLongLong((PY_LONG_LONG)va_arg(*p_va, unsigned PY_LONG_LONG)); #endif - case 'u': - { - PyObject *v; - Py_UNICODE *u = va_arg(*p_va, Py_UNICODE *); - Py_ssize_t n; - if (**p_format == '#') { - ++*p_format; - if (flags & FLAG_SIZE_T) - n = va_arg(*p_va, Py_ssize_t); - else - n = va_arg(*p_va, int); - } - else - n = -1; - if (u == NULL) { - v = Py_None; - Py_INCREF(v); - } - else { - if (n < 0) - n = _ustrlen(u); - v = PyUnicode_FromUnicode(u, n); - } - return v; - } - case 'f': - case 'd': - return PyFloat_FromDouble( - (double)va_arg(*p_va, va_double)); - - case 'D': - return PyComplex_FromCComplex( - *((Py_complex *)va_arg(*p_va, Py_complex *))); - - case 'c': - { - char p[1]; - p[0] = (char)va_arg(*p_va, int); - return PyBytes_FromStringAndSize(p, 1); - } - case 'C': - { - int i = va_arg(*p_va, int); - if (i < 0 || i > PyUnicode_GetMax()) { - PyErr_SetString(PyExc_OverflowError, - "%c arg not in range(0x110000)"); - return NULL; - } - return PyUnicode_FromOrdinal(i); - } - - case 's': - case 'z': - { - PyObject *v; - char *str = va_arg(*p_va, char *); - Py_ssize_t n; - if (**p_format == '#') { - ++*p_format; - if (flags & FLAG_SIZE_T) - n = va_arg(*p_va, Py_ssize_t); - else - n = va_arg(*p_va, int); - } - else - n = -1; - if (str == NULL) { - v = Py_None; - Py_INCREF(v); - } - else { - if (n < 0) { - size_t m = strlen(str); - if (m > PY_SSIZE_T_MAX) { - PyErr_SetString(PyExc_OverflowError, - "string too long for Python string"); - return NULL; - } - n = (Py_ssize_t)m; - } - v = PyUnicode_FromStringAndSize(str, n); - } - return v; - } - - case 'U': - { - PyObject *v; - char *str = va_arg(*p_va, char *); - Py_ssize_t n; - if (**p_format == '#') { - ++*p_format; - if (flags & FLAG_SIZE_T) - n = va_arg(*p_va, Py_ssize_t); - else - n = va_arg(*p_va, int); - } - else - n = -1; - if (str == NULL) { - v = Py_None; - Py_INCREF(v); - } - else { - if (n < 0) { - size_t m = strlen(str); - if (m > PY_SSIZE_T_MAX) { - PyErr_SetString(PyExc_OverflowError, - "string too long for Python string"); - return NULL; - } - n = (Py_ssize_t)m; - } - v = PyUnicode_FromStringAndSize(str, n); - } - return v; - } - - case 'y': - { - PyObject *v; - char *str = va_arg(*p_va, char *); - Py_ssize_t n; - if (**p_format == '#') { - ++*p_format; - if (flags & FLAG_SIZE_T) - n = va_arg(*p_va, Py_ssize_t); - else - n = va_arg(*p_va, int); - } - else - n = -1; - if (str == NULL) { - v = Py_None; - Py_INCREF(v); - } - else { - if (n < 0) { - size_t m = strlen(str); - if (m > PY_SSIZE_T_MAX) { - PyErr_SetString(PyExc_OverflowError, - "string too long for Python bytes"); - return NULL; - } - n = (Py_ssize_t)m; - } - v = PyBytes_FromStringAndSize(str, n); - } - return v; - } - - case 'N': - case 'S': - case 'O': - if (**p_format == '&') { - typedef PyObject *(*converter)(void *); - converter func = va_arg(*p_va, converter); - void *arg = va_arg(*p_va, void *); - ++*p_format; - return (*func)(arg); - } - else { - PyObject *v; - v = va_arg(*p_va, PyObject *); - if (v != NULL) { - if (*(*p_format - 1) != 'N') - Py_INCREF(v); - } - else if (!PyErr_Occurred()) - /* If a NULL was passed - * because a call that should - * have constructed a value - * failed, that's OK, and we - * pass the error on; but if - * no error occurred it's not - * clear that the caller knew - * what she was doing. */ - PyErr_SetString(PyExc_SystemError, - "NULL object passed to Py_BuildValue"); - return v; - } - - case ':': - case ',': - case ' ': - case '\t': - break; - - default: - PyErr_SetString(PyExc_SystemError, - "bad format char passed to Py_BuildValue"); - return NULL; + case 'u': + { + PyObject *v; + Py_UNICODE *u = va_arg(*p_va, Py_UNICODE *); + Py_ssize_t n; + if (**p_format == '#') { + ++*p_format; + if (flags & FLAG_SIZE_T) + n = va_arg(*p_va, Py_ssize_t); + else + n = va_arg(*p_va, int); + } + else + n = -1; + if (u == NULL) { + v = Py_None; + Py_INCREF(v); + } + else { + if (n < 0) + n = _ustrlen(u); + v = PyUnicode_FromUnicode(u, n); + } + return v; + } + case 'f': + case 'd': + return PyFloat_FromDouble( + (double)va_arg(*p_va, va_double)); + + case 'D': + return PyComplex_FromCComplex( + *((Py_complex *)va_arg(*p_va, Py_complex *))); + + case 'c': + { + char p[1]; + p[0] = (char)va_arg(*p_va, int); + return PyBytes_FromStringAndSize(p, 1); + } + case 'C': + { + int i = va_arg(*p_va, int); + if (i < 0 || i > PyUnicode_GetMax()) { + PyErr_SetString(PyExc_OverflowError, + "%c arg not in range(0x110000)"); + return NULL; + } + return PyUnicode_FromOrdinal(i); + } + + case 's': + case 'z': + { + PyObject *v; + char *str = va_arg(*p_va, char *); + Py_ssize_t n; + if (**p_format == '#') { + ++*p_format; + if (flags & FLAG_SIZE_T) + n = va_arg(*p_va, Py_ssize_t); + else + n = va_arg(*p_va, int); + } + else + n = -1; + if (str == NULL) { + v = Py_None; + Py_INCREF(v); + } + else { + if (n < 0) { + size_t m = strlen(str); + if (m > PY_SSIZE_T_MAX) { + PyErr_SetString(PyExc_OverflowError, + "string too long for Python string"); + return NULL; + } + n = (Py_ssize_t)m; + } + v = PyUnicode_FromStringAndSize(str, n); + } + return v; + } + + case 'U': + { + PyObject *v; + char *str = va_arg(*p_va, char *); + Py_ssize_t n; + if (**p_format == '#') { + ++*p_format; + if (flags & FLAG_SIZE_T) + n = va_arg(*p_va, Py_ssize_t); + else + n = va_arg(*p_va, int); + } + else + n = -1; + if (str == NULL) { + v = Py_None; + Py_INCREF(v); + } + else { + if (n < 0) { + size_t m = strlen(str); + if (m > PY_SSIZE_T_MAX) { + PyErr_SetString(PyExc_OverflowError, + "string too long for Python string"); + return NULL; + } + n = (Py_ssize_t)m; + } + v = PyUnicode_FromStringAndSize(str, n); + } + return v; + } + + case 'y': + { + PyObject *v; + char *str = va_arg(*p_va, char *); + Py_ssize_t n; + if (**p_format == '#') { + ++*p_format; + if (flags & FLAG_SIZE_T) + n = va_arg(*p_va, Py_ssize_t); + else + n = va_arg(*p_va, int); + } + else + n = -1; + if (str == NULL) { + v = Py_None; + Py_INCREF(v); + } + else { + if (n < 0) { + size_t m = strlen(str); + if (m > PY_SSIZE_T_MAX) { + PyErr_SetString(PyExc_OverflowError, + "string too long for Python bytes"); + return NULL; + } + n = (Py_ssize_t)m; + } + v = PyBytes_FromStringAndSize(str, n); + } + return v; + } + + case 'N': + case 'S': + case 'O': + if (**p_format == '&') { + typedef PyObject *(*converter)(void *); + converter func = va_arg(*p_va, converter); + void *arg = va_arg(*p_va, void *); + ++*p_format; + return (*func)(arg); + } + else { + PyObject *v; + v = va_arg(*p_va, PyObject *); + if (v != NULL) { + if (*(*p_format - 1) != 'N') + Py_INCREF(v); + } + else if (!PyErr_Occurred()) + /* If a NULL was passed + * because a call that should + * have constructed a value + * failed, that's OK, and we + * pass the error on; but if + * no error occurred it's not + * clear that the caller knew + * what she was doing. */ + PyErr_SetString(PyExc_SystemError, + "NULL object passed to Py_BuildValue"); + return v; + } + + case ':': + case ',': + case ' ': + case '\t': + break; + + default: + PyErr_SetString(PyExc_SystemError, + "bad format char passed to Py_BuildValue"); + return NULL; - } - } + } + } } PyObject * Py_BuildValue(const char *format, ...) { - va_list va; - PyObject* retval; - va_start(va, format); - retval = va_build_value(format, va, 0); - va_end(va); - return retval; + va_list va; + PyObject* retval; + va_start(va, format); + retval = va_build_value(format, va, 0); + va_end(va); + return retval; } PyObject * _Py_BuildValue_SizeT(const char *format, ...) { - va_list va; - PyObject* retval; - va_start(va, format); - retval = va_build_value(format, va, FLAG_SIZE_T); - va_end(va); - return retval; + va_list va; + PyObject* retval; + va_start(va, format); + retval = va_build_value(format, va, FLAG_SIZE_T); + va_end(va); + return retval; } PyObject * Py_VaBuildValue(const char *format, va_list va) { - return va_build_value(format, va, 0); + return va_build_value(format, va, 0); } PyObject * _Py_VaBuildValue_SizeT(const char *format, va_list va) { - return va_build_value(format, va, FLAG_SIZE_T); + return va_build_value(format, va, FLAG_SIZE_T); } static PyObject * va_build_value(const char *format, va_list va, int flags) { - const char *f = format; - int n = countformat(f, '\0'); - va_list lva; + const char *f = format; + int n = countformat(f, '\0'); + va_list lva; #ifdef VA_LIST_IS_ARRAY - memcpy(lva, va, sizeof(va_list)); + memcpy(lva, va, sizeof(va_list)); #else #ifdef __va_copy - __va_copy(lva, va); + __va_copy(lva, va); #else - lva = va; + lva = va; #endif #endif - if (n < 0) - return NULL; - if (n == 0) { - Py_INCREF(Py_None); - return Py_None; - } - if (n == 1) - return do_mkvalue(&f, &lva, flags); - return do_mktuple(&f, &lva, '\0', n, flags); + if (n < 0) + return NULL; + if (n == 0) { + Py_INCREF(Py_None); + return Py_None; + } + if (n == 1) + return do_mkvalue(&f, &lva, flags); + return do_mktuple(&f, &lva, '\0', n, flags); } PyObject * PyEval_CallFunction(PyObject *obj, const char *format, ...) { - va_list vargs; - PyObject *args; - PyObject *res; + va_list vargs; + PyObject *args; + PyObject *res; - va_start(vargs, format); + va_start(vargs, format); - args = Py_VaBuildValue(format, vargs); - va_end(vargs); + args = Py_VaBuildValue(format, vargs); + va_end(vargs); - if (args == NULL) - return NULL; + if (args == NULL) + return NULL; - res = PyEval_CallObject(obj, args); - Py_DECREF(args); + res = PyEval_CallObject(obj, args); + Py_DECREF(args); - return res; + return res; } PyObject * PyEval_CallMethod(PyObject *obj, const char *methodname, const char *format, ...) { - va_list vargs; - PyObject *meth; - PyObject *args; - PyObject *res; - - meth = PyObject_GetAttrString(obj, methodname); - if (meth == NULL) - return NULL; - - va_start(vargs, format); - - args = Py_VaBuildValue(format, vargs); - va_end(vargs); - - if (args == NULL) { - Py_DECREF(meth); - return NULL; - } - - res = PyEval_CallObject(meth, args); - Py_DECREF(meth); - Py_DECREF(args); + va_list vargs; + PyObject *meth; + PyObject *args; + PyObject *res; + + meth = PyObject_GetAttrString(obj, methodname); + if (meth == NULL) + return NULL; + + va_start(vargs, format); + + args = Py_VaBuildValue(format, vargs); + va_end(vargs); + + if (args == NULL) { + Py_DECREF(meth); + return NULL; + } + + res = PyEval_CallObject(meth, args); + Py_DECREF(meth); + Py_DECREF(args); - return res; + return res; } int PyModule_AddObject(PyObject *m, const char *name, PyObject *o) { - PyObject *dict; - if (!PyModule_Check(m)) { - PyErr_SetString(PyExc_TypeError, - "PyModule_AddObject() needs module as first arg"); - return -1; - } - if (!o) { - if (!PyErr_Occurred()) - PyErr_SetString(PyExc_TypeError, - "PyModule_AddObject() needs non-NULL value"); - return -1; - } - - dict = PyModule_GetDict(m); - if (dict == NULL) { - /* Internal error -- modules must have a dict! */ - PyErr_Format(PyExc_SystemError, "module '%s' has no __dict__", - PyModule_GetName(m)); - return -1; - } - if (PyDict_SetItemString(dict, name, o)) - return -1; - Py_DECREF(o); - return 0; + PyObject *dict; + if (!PyModule_Check(m)) { + PyErr_SetString(PyExc_TypeError, + "PyModule_AddObject() needs module as first arg"); + return -1; + } + if (!o) { + if (!PyErr_Occurred()) + PyErr_SetString(PyExc_TypeError, + "PyModule_AddObject() needs non-NULL value"); + return -1; + } + + dict = PyModule_GetDict(m); + if (dict == NULL) { + /* Internal error -- modules must have a dict! */ + PyErr_Format(PyExc_SystemError, "module '%s' has no __dict__", + PyModule_GetName(m)); + return -1; + } + if (PyDict_SetItemString(dict, name, o)) + return -1; + Py_DECREF(o); + return 0; } -int +int PyModule_AddIntConstant(PyObject *m, const char *name, long value) { - PyObject *o = PyLong_FromLong(value); - if (!o) - return -1; - if (PyModule_AddObject(m, name, o) == 0) - return 0; - Py_DECREF(o); - return -1; + PyObject *o = PyLong_FromLong(value); + if (!o) + return -1; + if (PyModule_AddObject(m, name, o) == 0) + return 0; + Py_DECREF(o); + return -1; } -int +int PyModule_AddStringConstant(PyObject *m, const char *name, const char *value) { - PyObject *o = PyUnicode_FromString(value); - if (!o) - return -1; - if (PyModule_AddObject(m, name, o) == 0) - return 0; - Py_DECREF(o); - return -1; + PyObject *o = PyUnicode_FromString(value); + if (!o) + return -1; + if (PyModule_AddObject(m, name, o) == 0) + return 0; + Py_DECREF(o); + return -1; } Modified: python/branches/py3k/Python/mysnprintf.c ============================================================================== --- python/branches/py3k/Python/mysnprintf.c (original) +++ python/branches/py3k/Python/mysnprintf.c Sun May 9 17:52:27 2010 @@ -19,20 +19,20 @@ Return value (rv): - When 0 <= rv < size, the output conversion was unexceptional, and - rv characters were written to str (excluding a trailing \0 byte at - str[rv]). - - When rv >= size, output conversion was truncated, and a buffer of - size rv+1 would have been needed to avoid truncation. str[size-1] - is \0 in this case. - - When rv < 0, "something bad happened". str[size-1] is \0 in this - case too, but the rest of str is unreliable. It could be that - an error in format codes was detected by libc, or on platforms - with a non-C99 vsnprintf simply that the buffer wasn't big enough - to avoid truncation, or on platforms without any vsnprintf that - PyMem_Malloc couldn't obtain space for a temp buffer. + When 0 <= rv < size, the output conversion was unexceptional, and + rv characters were written to str (excluding a trailing \0 byte at + str[rv]). + + When rv >= size, output conversion was truncated, and a buffer of + size rv+1 would have been needed to avoid truncation. str[size-1] + is \0 in this case. + + When rv < 0, "something bad happened". str[size-1] is \0 in this + case too, but the rest of str is unreliable. It could be that + an error in format codes was detected by libc, or on platforms + with a non-C99 vsnprintf simply that the buffer wasn't big enough + to avoid truncation, or on platforms without any vsnprintf that + PyMem_Malloc couldn't obtain space for a temp buffer. CAUTION: Unlike C99, str != NULL and size > 0 are required. */ @@ -40,65 +40,65 @@ int PyOS_snprintf(char *str, size_t size, const char *format, ...) { - int rc; - va_list va; + int rc; + va_list va; - va_start(va, format); - rc = PyOS_vsnprintf(str, size, format, va); - va_end(va); - return rc; + va_start(va, format); + rc = PyOS_vsnprintf(str, size, format, va); + va_end(va); + return rc; } int PyOS_vsnprintf(char *str, size_t size, const char *format, va_list va) { - int len; /* # bytes written, excluding \0 */ + int len; /* # bytes written, excluding \0 */ #ifdef HAVE_SNPRINTF #define _PyOS_vsnprintf_EXTRA_SPACE 1 #else #define _PyOS_vsnprintf_EXTRA_SPACE 512 - char *buffer; + char *buffer; #endif - assert(str != NULL); - assert(size > 0); - assert(format != NULL); - /* We take a size_t as input but return an int. Sanity check - * our input so that it won't cause an overflow in the - * vsnprintf return value or the buffer malloc size. */ - if (size > INT_MAX - _PyOS_vsnprintf_EXTRA_SPACE) { - len = -666; - goto Done; - } + assert(str != NULL); + assert(size > 0); + assert(format != NULL); + /* We take a size_t as input but return an int. Sanity check + * our input so that it won't cause an overflow in the + * vsnprintf return value or the buffer malloc size. */ + if (size > INT_MAX - _PyOS_vsnprintf_EXTRA_SPACE) { + len = -666; + goto Done; + } #ifdef HAVE_SNPRINTF - len = vsnprintf(str, size, format, va); + len = vsnprintf(str, size, format, va); #else - /* Emulate it. */ - buffer = PyMem_MALLOC(size + _PyOS_vsnprintf_EXTRA_SPACE); - if (buffer == NULL) { - len = -666; - goto Done; - } - - len = vsprintf(buffer, format, va); - if (len < 0) - /* ignore the error */; - - else if ((size_t)len >= size + _PyOS_vsnprintf_EXTRA_SPACE) - Py_FatalError("Buffer overflow in PyOS_snprintf/PyOS_vsnprintf"); - - else { - const size_t to_copy = (size_t)len < size ? - (size_t)len : size - 1; - assert(to_copy < size); - memcpy(str, buffer, to_copy); - str[to_copy] = '\0'; - } - PyMem_FREE(buffer); + /* Emulate it. */ + buffer = PyMem_MALLOC(size + _PyOS_vsnprintf_EXTRA_SPACE); + if (buffer == NULL) { + len = -666; + goto Done; + } + + len = vsprintf(buffer, format, va); + if (len < 0) + /* ignore the error */; + + else if ((size_t)len >= size + _PyOS_vsnprintf_EXTRA_SPACE) + Py_FatalError("Buffer overflow in PyOS_snprintf/PyOS_vsnprintf"); + + else { + const size_t to_copy = (size_t)len < size ? + (size_t)len : size - 1; + assert(to_copy < size); + memcpy(str, buffer, to_copy); + str[to_copy] = '\0'; + } + PyMem_FREE(buffer); #endif Done: - if (size > 0) - str[size-1] = '\0'; - return len; + if (size > 0) + str[size-1] = '\0'; + return len; #undef _PyOS_vsnprintf_EXTRA_SPACE } Modified: python/branches/py3k/Python/mystrtoul.c ============================================================================== --- python/branches/py3k/Python/mystrtoul.c (original) +++ python/branches/py3k/Python/mystrtoul.c Sun May 9 17:52:27 2010 @@ -18,43 +18,43 @@ * i * base doesn't overflow unsigned long. */ static unsigned long smallmax[] = { - 0, /* bases 0 and 1 are invalid */ - 0, - ULONG_MAX / 2, - ULONG_MAX / 3, - ULONG_MAX / 4, - ULONG_MAX / 5, - ULONG_MAX / 6, - ULONG_MAX / 7, - ULONG_MAX / 8, - ULONG_MAX / 9, - ULONG_MAX / 10, - ULONG_MAX / 11, - ULONG_MAX / 12, - ULONG_MAX / 13, - ULONG_MAX / 14, - ULONG_MAX / 15, - ULONG_MAX / 16, - ULONG_MAX / 17, - ULONG_MAX / 18, - ULONG_MAX / 19, - ULONG_MAX / 20, - ULONG_MAX / 21, - ULONG_MAX / 22, - ULONG_MAX / 23, - ULONG_MAX / 24, - ULONG_MAX / 25, - ULONG_MAX / 26, - ULONG_MAX / 27, - ULONG_MAX / 28, - ULONG_MAX / 29, - ULONG_MAX / 30, - ULONG_MAX / 31, - ULONG_MAX / 32, - ULONG_MAX / 33, - ULONG_MAX / 34, - ULONG_MAX / 35, - ULONG_MAX / 36, + 0, /* bases 0 and 1 are invalid */ + 0, + ULONG_MAX / 2, + ULONG_MAX / 3, + ULONG_MAX / 4, + ULONG_MAX / 5, + ULONG_MAX / 6, + ULONG_MAX / 7, + ULONG_MAX / 8, + ULONG_MAX / 9, + ULONG_MAX / 10, + ULONG_MAX / 11, + ULONG_MAX / 12, + ULONG_MAX / 13, + ULONG_MAX / 14, + ULONG_MAX / 15, + ULONG_MAX / 16, + ULONG_MAX / 17, + ULONG_MAX / 18, + ULONG_MAX / 19, + ULONG_MAX / 20, + ULONG_MAX / 21, + ULONG_MAX / 22, + ULONG_MAX / 23, + ULONG_MAX / 24, + ULONG_MAX / 25, + ULONG_MAX / 26, + ULONG_MAX / 27, + ULONG_MAX / 28, + ULONG_MAX / 29, + ULONG_MAX / 30, + ULONG_MAX / 31, + ULONG_MAX / 32, + ULONG_MAX / 33, + ULONG_MAX / 34, + ULONG_MAX / 35, + ULONG_MAX / 36, }; /* maximum digits that can't ever overflow for bases 2 through 36, @@ -63,229 +63,229 @@ */ #if SIZEOF_LONG == 4 static int digitlimit[] = { - 0, 0, 32, 20, 16, 13, 12, 11, 10, 10, /* 0 - 9 */ - 9, 9, 8, 8, 8, 8, 8, 7, 7, 7, /* 10 - 19 */ - 7, 7, 7, 7, 6, 6, 6, 6, 6, 6, /* 20 - 29 */ - 6, 6, 6, 6, 6, 6, 6}; /* 30 - 36 */ + 0, 0, 32, 20, 16, 13, 12, 11, 10, 10, /* 0 - 9 */ + 9, 9, 8, 8, 8, 8, 8, 7, 7, 7, /* 10 - 19 */ + 7, 7, 7, 7, 6, 6, 6, 6, 6, 6, /* 20 - 29 */ + 6, 6, 6, 6, 6, 6, 6}; /* 30 - 36 */ #elif SIZEOF_LONG == 8 /* [int(math.floor(math.log(2**64, i))) for i in range(2, 37)] */ static int digitlimit[] = { - 0, 0, 64, 40, 32, 27, 24, 22, 21, 20, /* 0 - 9 */ - 19, 18, 17, 17, 16, 16, 16, 15, 15, 15, /* 10 - 19 */ - 14, 14, 14, 14, 13, 13, 13, 13, 13, 13, /* 20 - 29 */ - 13, 12, 12, 12, 12, 12, 12}; /* 30 - 36 */ + 0, 0, 64, 40, 32, 27, 24, 22, 21, 20, /* 0 - 9 */ + 19, 18, 17, 17, 16, 16, 16, 15, 15, 15, /* 10 - 19 */ + 14, 14, 14, 14, 13, 13, 13, 13, 13, 13, /* 20 - 29 */ + 13, 12, 12, 12, 12, 12, 12}; /* 30 - 36 */ #else #error "Need table for SIZEOF_LONG" #endif /* -** strtoul -** This is a general purpose routine for converting -** an ascii string to an integer in an arbitrary base. -** Leading white space is ignored. If 'base' is zero -** it looks for a leading 0b, 0o or 0x to tell which -** base. If these are absent it defaults to 10. -** Base must be 0 or between 2 and 36 (inclusive). -** If 'ptr' is non-NULL it will contain a pointer to -** the end of the scan. -** Errors due to bad pointers will probably result in -** exceptions - we don't check for them. +** strtoul +** This is a general purpose routine for converting +** an ascii string to an integer in an arbitrary base. +** Leading white space is ignored. If 'base' is zero +** it looks for a leading 0b, 0o or 0x to tell which +** base. If these are absent it defaults to 10. +** Base must be 0 or between 2 and 36 (inclusive). +** If 'ptr' is non-NULL it will contain a pointer to +** the end of the scan. +** Errors due to bad pointers will probably result in +** exceptions - we don't check for them. */ unsigned long PyOS_strtoul(register char *str, char **ptr, int base) { - register unsigned long result = 0; /* return value of the function */ - register int c; /* current input character */ - register int ovlimit; /* required digits to overflow */ - - /* skip leading white space */ - while (*str && isspace(Py_CHARMASK(*str))) - ++str; - - /* check for leading 0b, 0o or 0x for auto-base or base 16 */ - switch (base) { - case 0: /* look for leading 0b, 0o or 0x */ - if (*str == '0') { - ++str; - if (*str == 'x' || *str == 'X') { - /* there must be at least one digit after 0x */ - if (_PyLong_DigitValue[Py_CHARMASK(str[1])] >= 16) { - if (ptr) - *ptr = str; - return 0; - } - ++str; - base = 16; - } else if (*str == 'o' || *str == 'O') { - /* there must be at least one digit after 0o */ - if (_PyLong_DigitValue[Py_CHARMASK(str[1])] >= 8) { - if (ptr) - *ptr = str; - return 0; - } - ++str; - base = 8; - } else if (*str == 'b' || *str == 'B') { - /* there must be at least one digit after 0b */ - if (_PyLong_DigitValue[Py_CHARMASK(str[1])] >= 2) { - if (ptr) - *ptr = str; - return 0; - } - ++str; - base = 2; - } else { - /* skip all zeroes... */ - while (*str == '0') - ++str; - while (isspace(Py_CHARMASK(*str))) - ++str; - if (ptr) - *ptr = str; - return 0; - } - } - else - base = 10; - break; - - /* even with explicit base, skip leading 0? prefix */ - case 16: - if (*str == '0') { - ++str; - if (*str == 'x' || *str == 'X') { - /* there must be at least one digit after 0x */ - if (_PyLong_DigitValue[Py_CHARMASK(str[1])] >= 16) { - if (ptr) - *ptr = str; - return 0; - } - ++str; - } - } - break; - case 8: - if (*str == '0') { - ++str; - if (*str == 'o' || *str == 'O') { - /* there must be at least one digit after 0o */ - if (_PyLong_DigitValue[Py_CHARMASK(str[1])] >= 8) { - if (ptr) - *ptr = str; - return 0; - } - ++str; - } - } - break; - case 2: - if(*str == '0') { - ++str; - if (*str == 'b' || *str == 'B') { - /* there must be at least one digit after 0b */ - if (_PyLong_DigitValue[Py_CHARMASK(str[1])] >= 2) { - if (ptr) - *ptr = str; - return 0; - } - ++str; - } - } - break; - } - - /* catch silly bases */ - if (base < 2 || base > 36) { - if (ptr) - *ptr = str; - return 0; - } - - /* skip leading zeroes */ - while (*str == '0') - ++str; - - /* base is guaranteed to be in [2, 36] at this point */ - ovlimit = digitlimit[base]; - - /* do the conversion until non-digit character encountered */ - while ((c = _PyLong_DigitValue[Py_CHARMASK(*str)]) < base) { - if (ovlimit > 0) /* no overflow check required */ - result = result * base + c; - else { /* requires overflow check */ - register unsigned long temp_result; - - if (ovlimit < 0) /* guaranteed overflow */ - goto overflowed; - - /* there could be an overflow */ - /* check overflow just from shifting */ - if (result > smallmax[base]) - goto overflowed; - - result *= base; - - /* check overflow from the digit's value */ - temp_result = result + c; - if (temp_result < result) - goto overflowed; - - result = temp_result; - } - - ++str; - --ovlimit; - } - - /* set pointer to point to the last character scanned */ - if (ptr) - *ptr = str; + register unsigned long result = 0; /* return value of the function */ + register int c; /* current input character */ + register int ovlimit; /* required digits to overflow */ + + /* skip leading white space */ + while (*str && isspace(Py_CHARMASK(*str))) + ++str; + + /* check for leading 0b, 0o or 0x for auto-base or base 16 */ + switch (base) { + case 0: /* look for leading 0b, 0o or 0x */ + if (*str == '0') { + ++str; + if (*str == 'x' || *str == 'X') { + /* there must be at least one digit after 0x */ + if (_PyLong_DigitValue[Py_CHARMASK(str[1])] >= 16) { + if (ptr) + *ptr = str; + return 0; + } + ++str; + base = 16; + } else if (*str == 'o' || *str == 'O') { + /* there must be at least one digit after 0o */ + if (_PyLong_DigitValue[Py_CHARMASK(str[1])] >= 8) { + if (ptr) + *ptr = str; + return 0; + } + ++str; + base = 8; + } else if (*str == 'b' || *str == 'B') { + /* there must be at least one digit after 0b */ + if (_PyLong_DigitValue[Py_CHARMASK(str[1])] >= 2) { + if (ptr) + *ptr = str; + return 0; + } + ++str; + base = 2; + } else { + /* skip all zeroes... */ + while (*str == '0') + ++str; + while (isspace(Py_CHARMASK(*str))) + ++str; + if (ptr) + *ptr = str; + return 0; + } + } + else + base = 10; + break; + + /* even with explicit base, skip leading 0? prefix */ + case 16: + if (*str == '0') { + ++str; + if (*str == 'x' || *str == 'X') { + /* there must be at least one digit after 0x */ + if (_PyLong_DigitValue[Py_CHARMASK(str[1])] >= 16) { + if (ptr) + *ptr = str; + return 0; + } + ++str; + } + } + break; + case 8: + if (*str == '0') { + ++str; + if (*str == 'o' || *str == 'O') { + /* there must be at least one digit after 0o */ + if (_PyLong_DigitValue[Py_CHARMASK(str[1])] >= 8) { + if (ptr) + *ptr = str; + return 0; + } + ++str; + } + } + break; + case 2: + if(*str == '0') { + ++str; + if (*str == 'b' || *str == 'B') { + /* there must be at least one digit after 0b */ + if (_PyLong_DigitValue[Py_CHARMASK(str[1])] >= 2) { + if (ptr) + *ptr = str; + return 0; + } + ++str; + } + } + break; + } + + /* catch silly bases */ + if (base < 2 || base > 36) { + if (ptr) + *ptr = str; + return 0; + } + + /* skip leading zeroes */ + while (*str == '0') + ++str; + + /* base is guaranteed to be in [2, 36] at this point */ + ovlimit = digitlimit[base]; + + /* do the conversion until non-digit character encountered */ + while ((c = _PyLong_DigitValue[Py_CHARMASK(*str)]) < base) { + if (ovlimit > 0) /* no overflow check required */ + result = result * base + c; + else { /* requires overflow check */ + register unsigned long temp_result; + + if (ovlimit < 0) /* guaranteed overflow */ + goto overflowed; + + /* there could be an overflow */ + /* check overflow just from shifting */ + if (result > smallmax[base]) + goto overflowed; + + result *= base; + + /* check overflow from the digit's value */ + temp_result = result + c; + if (temp_result < result) + goto overflowed; + + result = temp_result; + } + + ++str; + --ovlimit; + } + + /* set pointer to point to the last character scanned */ + if (ptr) + *ptr = str; - return result; + return result; overflowed: - if (ptr) { - /* spool through remaining digit characters */ - while (_PyLong_DigitValue[Py_CHARMASK(*str)] < base) - ++str; - *ptr = str; - } - errno = ERANGE; - return (unsigned long)-1; + if (ptr) { + /* spool through remaining digit characters */ + while (_PyLong_DigitValue[Py_CHARMASK(*str)] < base) + ++str; + *ptr = str; + } + errno = ERANGE; + return (unsigned long)-1; } /* Checking for overflow in PyOS_strtol is a PITA; see comments * about PY_ABS_LONG_MIN in longobject.c. */ -#define PY_ABS_LONG_MIN (0-(unsigned long)LONG_MIN) +#define PY_ABS_LONG_MIN (0-(unsigned long)LONG_MIN) long PyOS_strtol(char *str, char **ptr, int base) { - long result; - unsigned long uresult; - char sign; - - while (*str && isspace(Py_CHARMASK(*str))) - str++; - - sign = *str; - if (sign == '+' || sign == '-') - str++; - - uresult = PyOS_strtoul(str, ptr, base); - - if (uresult <= (unsigned long)LONG_MAX) { - result = (long)uresult; - if (sign == '-') - result = -result; - } - else if (sign == '-' && uresult == PY_ABS_LONG_MIN) { - result = LONG_MIN; - } - else { - errno = ERANGE; - result = LONG_MAX; - } - return result; + long result; + unsigned long uresult; + char sign; + + while (*str && isspace(Py_CHARMASK(*str))) + str++; + + sign = *str; + if (sign == '+' || sign == '-') + str++; + + uresult = PyOS_strtoul(str, ptr, base); + + if (uresult <= (unsigned long)LONG_MAX) { + result = (long)uresult; + if (sign == '-') + result = -result; + } + else if (sign == '-' && uresult == PY_ABS_LONG_MIN) { + result = LONG_MIN; + } + else { + errno = ERANGE; + result = LONG_MAX; + } + return result; } Modified: python/branches/py3k/Python/opcode_targets.h ============================================================================== --- python/branches/py3k/Python/opcode_targets.h (original) +++ python/branches/py3k/Python/opcode_targets.h Sun May 9 17:52:27 2010 @@ -1,258 +1,258 @@ static void *opcode_targets[256] = { - &&_unknown_opcode, - &&TARGET_POP_TOP, - &&TARGET_ROT_TWO, - &&TARGET_ROT_THREE, - &&TARGET_DUP_TOP, - &&TARGET_ROT_FOUR, - &&_unknown_opcode, - &&_unknown_opcode, - &&_unknown_opcode, - &&TARGET_NOP, - &&TARGET_UNARY_POSITIVE, - &&TARGET_UNARY_NEGATIVE, - &&TARGET_UNARY_NOT, - &&_unknown_opcode, - &&_unknown_opcode, - &&TARGET_UNARY_INVERT, - &&_unknown_opcode, - &&_unknown_opcode, - &&_unknown_opcode, - &&TARGET_BINARY_POWER, - &&TARGET_BINARY_MULTIPLY, - &&_unknown_opcode, - &&TARGET_BINARY_MODULO, - &&TARGET_BINARY_ADD, - &&TARGET_BINARY_SUBTRACT, - &&TARGET_BINARY_SUBSCR, - &&TARGET_BINARY_FLOOR_DIVIDE, - &&TARGET_BINARY_TRUE_DIVIDE, - &&TARGET_INPLACE_FLOOR_DIVIDE, - &&TARGET_INPLACE_TRUE_DIVIDE, - &&_unknown_opcode, - &&_unknown_opcode, - &&_unknown_opcode, - &&_unknown_opcode, - &&_unknown_opcode, - &&_unknown_opcode, - &&_unknown_opcode, - &&_unknown_opcode, - &&_unknown_opcode, - &&_unknown_opcode, - &&_unknown_opcode, - &&_unknown_opcode, - &&_unknown_opcode, - &&_unknown_opcode, - &&_unknown_opcode, - &&_unknown_opcode, - &&_unknown_opcode, - &&_unknown_opcode, - &&_unknown_opcode, - &&_unknown_opcode, - &&_unknown_opcode, - &&_unknown_opcode, - &&_unknown_opcode, - &&_unknown_opcode, - &&TARGET_STORE_MAP, - &&TARGET_INPLACE_ADD, - &&TARGET_INPLACE_SUBTRACT, - &&TARGET_INPLACE_MULTIPLY, - &&_unknown_opcode, - &&TARGET_INPLACE_MODULO, - &&TARGET_STORE_SUBSCR, - &&TARGET_DELETE_SUBSCR, - &&TARGET_BINARY_LSHIFT, - &&TARGET_BINARY_RSHIFT, - &&TARGET_BINARY_AND, - &&TARGET_BINARY_XOR, - &&TARGET_BINARY_OR, - &&TARGET_INPLACE_POWER, - &&TARGET_GET_ITER, - &&TARGET_STORE_LOCALS, - &&TARGET_PRINT_EXPR, - &&TARGET_LOAD_BUILD_CLASS, - &&_unknown_opcode, - &&_unknown_opcode, - &&_unknown_opcode, - &&TARGET_INPLACE_LSHIFT, - &&TARGET_INPLACE_RSHIFT, - &&TARGET_INPLACE_AND, - &&TARGET_INPLACE_XOR, - &&TARGET_INPLACE_OR, - &&TARGET_BREAK_LOOP, - &&TARGET_WITH_CLEANUP, - &&_unknown_opcode, - &&TARGET_RETURN_VALUE, - &&TARGET_IMPORT_STAR, - &&_unknown_opcode, - &&TARGET_YIELD_VALUE, - &&TARGET_POP_BLOCK, - &&TARGET_END_FINALLY, - &&TARGET_POP_EXCEPT, - &&TARGET_STORE_NAME, - &&TARGET_DELETE_NAME, - &&TARGET_UNPACK_SEQUENCE, - &&TARGET_FOR_ITER, - &&TARGET_UNPACK_EX, - &&TARGET_STORE_ATTR, - &&TARGET_DELETE_ATTR, - &&TARGET_STORE_GLOBAL, - &&TARGET_DELETE_GLOBAL, - &&TARGET_DUP_TOPX, - &&TARGET_LOAD_CONST, - &&TARGET_LOAD_NAME, - &&TARGET_BUILD_TUPLE, - &&TARGET_BUILD_LIST, - &&TARGET_BUILD_SET, - &&TARGET_BUILD_MAP, - &&TARGET_LOAD_ATTR, - &&TARGET_COMPARE_OP, - &&TARGET_IMPORT_NAME, - &&TARGET_IMPORT_FROM, - &&TARGET_JUMP_FORWARD, - &&TARGET_JUMP_IF_FALSE_OR_POP, - &&TARGET_JUMP_IF_TRUE_OR_POP, - &&TARGET_JUMP_ABSOLUTE, - &&TARGET_POP_JUMP_IF_FALSE, - &&TARGET_POP_JUMP_IF_TRUE, - &&TARGET_LOAD_GLOBAL, - &&_unknown_opcode, - &&_unknown_opcode, - &&TARGET_CONTINUE_LOOP, - &&TARGET_SETUP_LOOP, - &&TARGET_SETUP_EXCEPT, - &&TARGET_SETUP_FINALLY, - &&_unknown_opcode, - &&TARGET_LOAD_FAST, - &&TARGET_STORE_FAST, - &&TARGET_DELETE_FAST, - &&_unknown_opcode, - &&_unknown_opcode, - &&_unknown_opcode, - &&TARGET_RAISE_VARARGS, - &&TARGET_CALL_FUNCTION, - &&TARGET_MAKE_FUNCTION, - &&TARGET_BUILD_SLICE, - &&TARGET_MAKE_CLOSURE, - &&TARGET_LOAD_CLOSURE, - &&TARGET_LOAD_DEREF, - &&TARGET_STORE_DEREF, - &&_unknown_opcode, - &&_unknown_opcode, - &&TARGET_CALL_FUNCTION_VAR, - &&TARGET_CALL_FUNCTION_KW, - &&TARGET_CALL_FUNCTION_VAR_KW, - &&TARGET_SETUP_WITH, - &&TARGET_EXTENDED_ARG, - &&TARGET_LIST_APPEND, - &&TARGET_SET_ADD, - &&TARGET_MAP_ADD, - &&_unknown_opcode, - &&_unknown_opcode, - &&_unknown_opcode, - &&_unknown_opcode, - &&_unknown_opcode, - &&_unknown_opcode, - &&_unknown_opcode, - &&_unknown_opcode, - &&_unknown_opcode, - &&_unknown_opcode, - &&_unknown_opcode, - &&_unknown_opcode, - &&_unknown_opcode, - &&_unknown_opcode, - &&_unknown_opcode, - &&_unknown_opcode, - &&_unknown_opcode, - &&_unknown_opcode, - &&_unknown_opcode, - &&_unknown_opcode, - &&_unknown_opcode, - &&_unknown_opcode, - &&_unknown_opcode, - &&_unknown_opcode, - &&_unknown_opcode, - &&_unknown_opcode, - &&_unknown_opcode, - &&_unknown_opcode, - &&_unknown_opcode, - &&_unknown_opcode, - &&_unknown_opcode, - &&_unknown_opcode, - &&_unknown_opcode, - &&_unknown_opcode, - &&_unknown_opcode, - &&_unknown_opcode, - &&_unknown_opcode, - &&_unknown_opcode, - &&_unknown_opcode, - &&_unknown_opcode, - &&_unknown_opcode, - &&_unknown_opcode, - &&_unknown_opcode, - &&_unknown_opcode, - &&_unknown_opcode, - &&_unknown_opcode, - &&_unknown_opcode, - &&_unknown_opcode, - &&_unknown_opcode, - &&_unknown_opcode, - &&_unknown_opcode, - &&_unknown_opcode, - &&_unknown_opcode, - &&_unknown_opcode, - &&_unknown_opcode, - &&_unknown_opcode, - &&_unknown_opcode, - &&_unknown_opcode, - &&_unknown_opcode, - &&_unknown_opcode, - &&_unknown_opcode, - &&_unknown_opcode, - &&_unknown_opcode, - &&_unknown_opcode, - &&_unknown_opcode, - &&_unknown_opcode, - &&_unknown_opcode, - &&_unknown_opcode, - &&_unknown_opcode, - &&_unknown_opcode, - &&_unknown_opcode, - &&_unknown_opcode, - &&_unknown_opcode, - &&_unknown_opcode, - &&_unknown_opcode, - &&_unknown_opcode, - &&_unknown_opcode, - &&_unknown_opcode, - &&_unknown_opcode, - &&_unknown_opcode, - &&_unknown_opcode, - &&_unknown_opcode, - &&_unknown_opcode, - &&_unknown_opcode, - &&_unknown_opcode, - &&_unknown_opcode, - &&_unknown_opcode, - &&_unknown_opcode, - &&_unknown_opcode, - &&_unknown_opcode, - &&_unknown_opcode, - &&_unknown_opcode, - &&_unknown_opcode, - &&_unknown_opcode, - &&_unknown_opcode, - &&_unknown_opcode, - &&_unknown_opcode, - &&_unknown_opcode, - &&_unknown_opcode, - &&_unknown_opcode, - &&_unknown_opcode, - &&_unknown_opcode, - &&_unknown_opcode, - &&_unknown_opcode, - &&_unknown_opcode, - &&_unknown_opcode, - &&_unknown_opcode, - &&_unknown_opcode + &&_unknown_opcode, + &&TARGET_POP_TOP, + &&TARGET_ROT_TWO, + &&TARGET_ROT_THREE, + &&TARGET_DUP_TOP, + &&TARGET_ROT_FOUR, + &&_unknown_opcode, + &&_unknown_opcode, + &&_unknown_opcode, + &&TARGET_NOP, + &&TARGET_UNARY_POSITIVE, + &&TARGET_UNARY_NEGATIVE, + &&TARGET_UNARY_NOT, + &&_unknown_opcode, + &&_unknown_opcode, + &&TARGET_UNARY_INVERT, + &&_unknown_opcode, + &&_unknown_opcode, + &&_unknown_opcode, + &&TARGET_BINARY_POWER, + &&TARGET_BINARY_MULTIPLY, + &&_unknown_opcode, + &&TARGET_BINARY_MODULO, + &&TARGET_BINARY_ADD, + &&TARGET_BINARY_SUBTRACT, + &&TARGET_BINARY_SUBSCR, + &&TARGET_BINARY_FLOOR_DIVIDE, + &&TARGET_BINARY_TRUE_DIVIDE, + &&TARGET_INPLACE_FLOOR_DIVIDE, + &&TARGET_INPLACE_TRUE_DIVIDE, + &&_unknown_opcode, + &&_unknown_opcode, + &&_unknown_opcode, + &&_unknown_opcode, + &&_unknown_opcode, + &&_unknown_opcode, + &&_unknown_opcode, + &&_unknown_opcode, + &&_unknown_opcode, + &&_unknown_opcode, + &&_unknown_opcode, + &&_unknown_opcode, + &&_unknown_opcode, + &&_unknown_opcode, + &&_unknown_opcode, + &&_unknown_opcode, + &&_unknown_opcode, + &&_unknown_opcode, + &&_unknown_opcode, + &&_unknown_opcode, + &&_unknown_opcode, + &&_unknown_opcode, + &&_unknown_opcode, + &&_unknown_opcode, + &&TARGET_STORE_MAP, + &&TARGET_INPLACE_ADD, + &&TARGET_INPLACE_SUBTRACT, + &&TARGET_INPLACE_MULTIPLY, + &&_unknown_opcode, + &&TARGET_INPLACE_MODULO, + &&TARGET_STORE_SUBSCR, + &&TARGET_DELETE_SUBSCR, + &&TARGET_BINARY_LSHIFT, + &&TARGET_BINARY_RSHIFT, + &&TARGET_BINARY_AND, + &&TARGET_BINARY_XOR, + &&TARGET_BINARY_OR, + &&TARGET_INPLACE_POWER, + &&TARGET_GET_ITER, + &&TARGET_STORE_LOCALS, + &&TARGET_PRINT_EXPR, + &&TARGET_LOAD_BUILD_CLASS, + &&_unknown_opcode, + &&_unknown_opcode, + &&_unknown_opcode, + &&TARGET_INPLACE_LSHIFT, + &&TARGET_INPLACE_RSHIFT, + &&TARGET_INPLACE_AND, + &&TARGET_INPLACE_XOR, + &&TARGET_INPLACE_OR, + &&TARGET_BREAK_LOOP, + &&TARGET_WITH_CLEANUP, + &&_unknown_opcode, + &&TARGET_RETURN_VALUE, + &&TARGET_IMPORT_STAR, + &&_unknown_opcode, + &&TARGET_YIELD_VALUE, + &&TARGET_POP_BLOCK, + &&TARGET_END_FINALLY, + &&TARGET_POP_EXCEPT, + &&TARGET_STORE_NAME, + &&TARGET_DELETE_NAME, + &&TARGET_UNPACK_SEQUENCE, + &&TARGET_FOR_ITER, + &&TARGET_UNPACK_EX, + &&TARGET_STORE_ATTR, + &&TARGET_DELETE_ATTR, + &&TARGET_STORE_GLOBAL, + &&TARGET_DELETE_GLOBAL, + &&TARGET_DUP_TOPX, + &&TARGET_LOAD_CONST, + &&TARGET_LOAD_NAME, + &&TARGET_BUILD_TUPLE, + &&TARGET_BUILD_LIST, + &&TARGET_BUILD_SET, + &&TARGET_BUILD_MAP, + &&TARGET_LOAD_ATTR, + &&TARGET_COMPARE_OP, + &&TARGET_IMPORT_NAME, + &&TARGET_IMPORT_FROM, + &&TARGET_JUMP_FORWARD, + &&TARGET_JUMP_IF_FALSE_OR_POP, + &&TARGET_JUMP_IF_TRUE_OR_POP, + &&TARGET_JUMP_ABSOLUTE, + &&TARGET_POP_JUMP_IF_FALSE, + &&TARGET_POP_JUMP_IF_TRUE, + &&TARGET_LOAD_GLOBAL, + &&_unknown_opcode, + &&_unknown_opcode, + &&TARGET_CONTINUE_LOOP, + &&TARGET_SETUP_LOOP, + &&TARGET_SETUP_EXCEPT, + &&TARGET_SETUP_FINALLY, + &&_unknown_opcode, + &&TARGET_LOAD_FAST, + &&TARGET_STORE_FAST, + &&TARGET_DELETE_FAST, + &&_unknown_opcode, + &&_unknown_opcode, + &&_unknown_opcode, + &&TARGET_RAISE_VARARGS, + &&TARGET_CALL_FUNCTION, + &&TARGET_MAKE_FUNCTION, + &&TARGET_BUILD_SLICE, + &&TARGET_MAKE_CLOSURE, + &&TARGET_LOAD_CLOSURE, + &&TARGET_LOAD_DEREF, + &&TARGET_STORE_DEREF, + &&_unknown_opcode, + &&_unknown_opcode, + &&TARGET_CALL_FUNCTION_VAR, + &&TARGET_CALL_FUNCTION_KW, + &&TARGET_CALL_FUNCTION_VAR_KW, + &&TARGET_SETUP_WITH, + &&TARGET_EXTENDED_ARG, + &&TARGET_LIST_APPEND, + &&TARGET_SET_ADD, + &&TARGET_MAP_ADD, + &&_unknown_opcode, + &&_unknown_opcode, + &&_unknown_opcode, + &&_unknown_opcode, + &&_unknown_opcode, + &&_unknown_opcode, + &&_unknown_opcode, + &&_unknown_opcode, + &&_unknown_opcode, + &&_unknown_opcode, + &&_unknown_opcode, + &&_unknown_opcode, + &&_unknown_opcode, + &&_unknown_opcode, + &&_unknown_opcode, + &&_unknown_opcode, + &&_unknown_opcode, + &&_unknown_opcode, + &&_unknown_opcode, + &&_unknown_opcode, + &&_unknown_opcode, + &&_unknown_opcode, + &&_unknown_opcode, + &&_unknown_opcode, + &&_unknown_opcode, + &&_unknown_opcode, + &&_unknown_opcode, + &&_unknown_opcode, + &&_unknown_opcode, + &&_unknown_opcode, + &&_unknown_opcode, + &&_unknown_opcode, + &&_unknown_opcode, + &&_unknown_opcode, + &&_unknown_opcode, + &&_unknown_opcode, + &&_unknown_opcode, + &&_unknown_opcode, + &&_unknown_opcode, + &&_unknown_opcode, + &&_unknown_opcode, + &&_unknown_opcode, + &&_unknown_opcode, + &&_unknown_opcode, + &&_unknown_opcode, + &&_unknown_opcode, + &&_unknown_opcode, + &&_unknown_opcode, + &&_unknown_opcode, + &&_unknown_opcode, + &&_unknown_opcode, + &&_unknown_opcode, + &&_unknown_opcode, + &&_unknown_opcode, + &&_unknown_opcode, + &&_unknown_opcode, + &&_unknown_opcode, + &&_unknown_opcode, + &&_unknown_opcode, + &&_unknown_opcode, + &&_unknown_opcode, + &&_unknown_opcode, + &&_unknown_opcode, + &&_unknown_opcode, + &&_unknown_opcode, + &&_unknown_opcode, + &&_unknown_opcode, + &&_unknown_opcode, + &&_unknown_opcode, + &&_unknown_opcode, + &&_unknown_opcode, + &&_unknown_opcode, + &&_unknown_opcode, + &&_unknown_opcode, + &&_unknown_opcode, + &&_unknown_opcode, + &&_unknown_opcode, + &&_unknown_opcode, + &&_unknown_opcode, + &&_unknown_opcode, + &&_unknown_opcode, + &&_unknown_opcode, + &&_unknown_opcode, + &&_unknown_opcode, + &&_unknown_opcode, + &&_unknown_opcode, + &&_unknown_opcode, + &&_unknown_opcode, + &&_unknown_opcode, + &&_unknown_opcode, + &&_unknown_opcode, + &&_unknown_opcode, + &&_unknown_opcode, + &&_unknown_opcode, + &&_unknown_opcode, + &&_unknown_opcode, + &&_unknown_opcode, + &&_unknown_opcode, + &&_unknown_opcode, + &&_unknown_opcode, + &&_unknown_opcode, + &&_unknown_opcode, + &&_unknown_opcode, + &&_unknown_opcode, + &&_unknown_opcode, + &&_unknown_opcode, + &&_unknown_opcode, + &&_unknown_opcode }; Modified: python/branches/py3k/Python/peephole.c ============================================================================== --- python/branches/py3k/Python/peephole.c (original) +++ python/branches/py3k/Python/peephole.c Sun May 9 17:52:27 2010 @@ -12,271 +12,271 @@ #include "opcode.h" #define GETARG(arr, i) ((int)((arr[i+2]<<8) + arr[i+1])) -#define UNCONDITIONAL_JUMP(op) (op==JUMP_ABSOLUTE || op==JUMP_FORWARD) +#define UNCONDITIONAL_JUMP(op) (op==JUMP_ABSOLUTE || op==JUMP_FORWARD) #define CONDITIONAL_JUMP(op) (op==POP_JUMP_IF_FALSE || op==POP_JUMP_IF_TRUE \ - || op==JUMP_IF_FALSE_OR_POP || op==JUMP_IF_TRUE_OR_POP) + || op==JUMP_IF_FALSE_OR_POP || op==JUMP_IF_TRUE_OR_POP) #define ABSOLUTE_JUMP(op) (op==JUMP_ABSOLUTE || op==CONTINUE_LOOP \ - || op==POP_JUMP_IF_FALSE || op==POP_JUMP_IF_TRUE \ - || op==JUMP_IF_FALSE_OR_POP || op==JUMP_IF_TRUE_OR_POP) + || op==POP_JUMP_IF_FALSE || op==POP_JUMP_IF_TRUE \ + || op==JUMP_IF_FALSE_OR_POP || op==JUMP_IF_TRUE_OR_POP) #define JUMPS_ON_TRUE(op) (op==POP_JUMP_IF_TRUE || op==JUMP_IF_TRUE_OR_POP) #define GETJUMPTGT(arr, i) (GETARG(arr,i) + (ABSOLUTE_JUMP(arr[i]) ? 0 : i+3)) #define SETARG(arr, i, val) arr[i+2] = val>>8; arr[i+1] = val & 255 #define CODESIZE(op) (HAS_ARG(op) ? 3 : 1) #define ISBASICBLOCK(blocks, start, bytes) \ - (blocks[start]==blocks[start+bytes-1]) + (blocks[start]==blocks[start+bytes-1]) /* Replace LOAD_CONST c1. LOAD_CONST c2 ... LOAD_CONST cn BUILD_TUPLE n - with LOAD_CONST (c1, c2, ... cn). + with LOAD_CONST (c1, c2, ... cn). The consts table must still be in list form so that the new constant (c1, c2, ... cn) can be appended. Called with codestr pointing to the first LOAD_CONST. - Bails out with no change if one or more of the LOAD_CONSTs is missing. + Bails out with no change if one or more of the LOAD_CONSTs is missing. Also works for BUILD_LIST and BUILT_SET when followed by an "in" or "not in" test; for BUILD_SET it assembles a frozenset rather than a tuple. */ static int tuple_of_constants(unsigned char *codestr, Py_ssize_t n, PyObject *consts) { - PyObject *newconst, *constant; - Py_ssize_t i, arg, len_consts; + PyObject *newconst, *constant; + Py_ssize_t i, arg, len_consts; - /* Pre-conditions */ - assert(PyList_CheckExact(consts)); - assert(codestr[n*3] == BUILD_TUPLE || codestr[n*3] == BUILD_LIST || codestr[n*3] == BUILD_SET); - assert(GETARG(codestr, (n*3)) == n); - for (i=0 ; i 20) { - Py_DECREF(newconst); - return 0; - } - - /* Append folded constant into consts table */ - len_consts = PyList_GET_SIZE(consts); - if (PyList_Append(consts, newconst)) { - Py_DECREF(newconst); - return 0; - } - Py_DECREF(newconst); - - /* Write NOP NOP NOP NOP LOAD_CONST newconst */ - memset(codestr, NOP, 4); - codestr[4] = LOAD_CONST; - SETARG(codestr, 4, len_consts); - return 1; + PyObject *newconst, *v, *w; + Py_ssize_t len_consts, size; + int opcode; + + /* Pre-conditions */ + assert(PyList_CheckExact(consts)); + assert(codestr[0] == LOAD_CONST); + assert(codestr[3] == LOAD_CONST); + + /* Create new constant */ + v = PyList_GET_ITEM(consts, GETARG(codestr, 0)); + w = PyList_GET_ITEM(consts, GETARG(codestr, 3)); + opcode = codestr[6]; + switch (opcode) { + case BINARY_POWER: + newconst = PyNumber_Power(v, w, Py_None); + break; + case BINARY_MULTIPLY: + newconst = PyNumber_Multiply(v, w); + break; + case BINARY_TRUE_DIVIDE: + newconst = PyNumber_TrueDivide(v, w); + break; + case BINARY_FLOOR_DIVIDE: + newconst = PyNumber_FloorDivide(v, w); + break; + case BINARY_MODULO: + newconst = PyNumber_Remainder(v, w); + break; + case BINARY_ADD: + newconst = PyNumber_Add(v, w); + break; + case BINARY_SUBTRACT: + newconst = PyNumber_Subtract(v, w); + break; + case BINARY_SUBSCR: + newconst = PyObject_GetItem(v, w); + break; + case BINARY_LSHIFT: + newconst = PyNumber_Lshift(v, w); + break; + case BINARY_RSHIFT: + newconst = PyNumber_Rshift(v, w); + break; + case BINARY_AND: + newconst = PyNumber_And(v, w); + break; + case BINARY_XOR: + newconst = PyNumber_Xor(v, w); + break; + case BINARY_OR: + newconst = PyNumber_Or(v, w); + break; + default: + /* Called with an unknown opcode */ + PyErr_Format(PyExc_SystemError, + "unexpected binary operation %d on a constant", + opcode); + return 0; + } + if (newconst == NULL) { + PyErr_Clear(); + return 0; + } + size = PyObject_Size(newconst); + if (size == -1) + PyErr_Clear(); + else if (size > 20) { + Py_DECREF(newconst); + return 0; + } + + /* Append folded constant into consts table */ + len_consts = PyList_GET_SIZE(consts); + if (PyList_Append(consts, newconst)) { + Py_DECREF(newconst); + return 0; + } + Py_DECREF(newconst); + + /* Write NOP NOP NOP NOP LOAD_CONST newconst */ + memset(codestr, NOP, 4); + codestr[4] = LOAD_CONST; + SETARG(codestr, 4, len_consts); + return 1; } static int fold_unaryops_on_constants(unsigned char *codestr, PyObject *consts) { - PyObject *newconst=NULL, *v; - Py_ssize_t len_consts; - int opcode; - - /* Pre-conditions */ - assert(PyList_CheckExact(consts)); - assert(codestr[0] == LOAD_CONST); - - /* Create new constant */ - v = PyList_GET_ITEM(consts, GETARG(codestr, 0)); - opcode = codestr[3]; - switch (opcode) { - case UNARY_NEGATIVE: - /* Preserve the sign of -0.0 */ - if (PyObject_IsTrue(v) == 1) - newconst = PyNumber_Negative(v); - break; - case UNARY_INVERT: - newconst = PyNumber_Invert(v); - break; - case UNARY_POSITIVE: - newconst = PyNumber_Positive(v); - break; - default: - /* Called with an unknown opcode */ - PyErr_Format(PyExc_SystemError, - "unexpected unary operation %d on a constant", - opcode); - return 0; - } - if (newconst == NULL) { - PyErr_Clear(); - return 0; - } - - /* Append folded constant into consts table */ - len_consts = PyList_GET_SIZE(consts); - if (PyList_Append(consts, newconst)) { - Py_DECREF(newconst); - return 0; - } - Py_DECREF(newconst); - - /* Write NOP LOAD_CONST newconst */ - codestr[0] = NOP; - codestr[1] = LOAD_CONST; - SETARG(codestr, 1, len_consts); - return 1; + PyObject *newconst=NULL, *v; + Py_ssize_t len_consts; + int opcode; + + /* Pre-conditions */ + assert(PyList_CheckExact(consts)); + assert(codestr[0] == LOAD_CONST); + + /* Create new constant */ + v = PyList_GET_ITEM(consts, GETARG(codestr, 0)); + opcode = codestr[3]; + switch (opcode) { + case UNARY_NEGATIVE: + /* Preserve the sign of -0.0 */ + if (PyObject_IsTrue(v) == 1) + newconst = PyNumber_Negative(v); + break; + case UNARY_INVERT: + newconst = PyNumber_Invert(v); + break; + case UNARY_POSITIVE: + newconst = PyNumber_Positive(v); + break; + default: + /* Called with an unknown opcode */ + PyErr_Format(PyExc_SystemError, + "unexpected unary operation %d on a constant", + opcode); + return 0; + } + if (newconst == NULL) { + PyErr_Clear(); + return 0; + } + + /* Append folded constant into consts table */ + len_consts = PyList_GET_SIZE(consts); + if (PyList_Append(consts, newconst)) { + Py_DECREF(newconst); + return 0; + } + Py_DECREF(newconst); + + /* Write NOP LOAD_CONST newconst */ + codestr[0] = NOP; + codestr[1] = LOAD_CONST; + SETARG(codestr, 1, len_consts); + return 1; } static unsigned int * markblocks(unsigned char *code, Py_ssize_t len) { - unsigned int *blocks = (unsigned int *)PyMem_Malloc(len*sizeof(int)); - int i,j, opcode, blockcnt = 0; + unsigned int *blocks = (unsigned int *)PyMem_Malloc(len*sizeof(int)); + int i,j, opcode, blockcnt = 0; - if (blocks == NULL) { - PyErr_NoMemory(); - return NULL; - } - memset(blocks, 0, len*sizeof(int)); - - /* Mark labels in the first pass */ - for (i=0 ; i= 255. EXTENDED_ARG can appear before MAKE_FUNCTION; in this case both opcodes are skipped. EXTENDED_ARG preceding any other opcode causes the optimizer to bail. Optimizations are restricted to simple transformations occuring within a - single basic block. All transformations keep the code size the same or - smaller. For those that reduce size, the gaps are initially filled with - NOPs. Later those NOPs are removed and the jump addresses retargeted in + single basic block. All transformations keep the code size the same or + smaller. For those that reduce size, the gaps are initially filled with + NOPs. Later those NOPs are removed and the jump addresses retargeted in a single pass. Line numbering is adjusted accordingly. */ PyObject * PyCode_Optimize(PyObject *code, PyObject* consts, PyObject *names, PyObject *lineno_obj) { - Py_ssize_t i, j, codelen; - int nops, h, adj; - int tgt, tgttgt, opcode; - unsigned char *codestr = NULL; - unsigned char *lineno; - int *addrmap = NULL; - int new_line, cum_orig_line, last_line, tabsiz; - int cumlc=0, lastlc=0; /* Count runs of consecutive LOAD_CONSTs */ - unsigned int *blocks = NULL; - char *name; - - /* Bail out if an exception is set */ - if (PyErr_Occurred()) - goto exitError; - - /* Bypass optimization when the lineno table is too complex */ - assert(PyBytes_Check(lineno_obj)); - lineno = (unsigned char*)PyBytes_AS_STRING(lineno_obj); - tabsiz = PyBytes_GET_SIZE(lineno_obj); - if (memchr(lineno, 255, tabsiz) != NULL) - goto exitUnchanged; - - /* Avoid situations where jump retargeting could overflow */ - assert(PyBytes_Check(code)); - codelen = PyBytes_GET_SIZE(code); - if (codelen > 32700) - goto exitUnchanged; - - /* Make a modifiable copy of the code string */ - codestr = (unsigned char *)PyMem_Malloc(codelen); - if (codestr == NULL) - goto exitError; - codestr = (unsigned char *)memcpy(codestr, - PyBytes_AS_STRING(code), codelen); - - /* Verify that RETURN_VALUE terminates the codestring. This allows - the various transformation patterns to look ahead several - instructions without additional checks to make sure they are not - looking beyond the end of the code string. - */ - if (codestr[codelen-1] != RETURN_VALUE) - goto exitUnchanged; - - /* Mapping to new jump targets after NOPs are removed */ - addrmap = (int *)PyMem_Malloc(codelen * sizeof(int)); - if (addrmap == NULL) - goto exitError; - - blocks = markblocks(codestr, codelen); - if (blocks == NULL) - goto exitError; - assert(PyList_Check(consts)); - - for (i=0 ; i a is not b - not a in b --> a not in b - not a is not b --> a is b - not a not in b --> a in b - */ - case COMPARE_OP: - j = GETARG(codestr, i); - if (j < 6 || j > 9 || - codestr[i+3] != UNARY_NOT || - !ISBASICBLOCK(blocks,i,4)) - continue; - SETARG(codestr, i, (j^1)); - codestr[i+3] = NOP; - break; - - /* Replace LOAD_GLOBAL/LOAD_NAME None/True/False - with LOAD_CONST None/True/False */ - case LOAD_NAME: - case LOAD_GLOBAL: - j = GETARG(codestr, i); - name = _PyUnicode_AsString(PyTuple_GET_ITEM(names, j)); - h = load_global(codestr, i, name, consts); - if (h < 0) - goto exitError; - else if (h == 0) - continue; - cumlc = lastlc + 1; - break; - - /* Skip over LOAD_CONST trueconst - POP_JUMP_IF_FALSE xx. This improves - "while 1" performance. */ - case LOAD_CONST: - cumlc = lastlc + 1; - j = GETARG(codestr, i); - if (codestr[i+3] != POP_JUMP_IF_FALSE || - !ISBASICBLOCK(blocks,i,6) || - !PyObject_IsTrue(PyList_GET_ITEM(consts, j))) - continue; - memset(codestr+i, NOP, 6); - cumlc = 0; - break; - - /* Try to fold tuples of constants (includes a case for lists and sets - which are only used for "in" and "not in" tests). - Skip over BUILD_SEQN 1 UNPACK_SEQN 1. - Replace BUILD_SEQN 2 UNPACK_SEQN 2 with ROT2. - Replace BUILD_SEQN 3 UNPACK_SEQN 3 with ROT3 ROT2. */ - case BUILD_TUPLE: - case BUILD_LIST: - case BUILD_SET: - j = GETARG(codestr, i); - h = i - 3 * j; - if (h >= 0 && - j <= lastlc && - ((opcode == BUILD_TUPLE && - ISBASICBLOCK(blocks, h, 3*(j+1))) || - ((opcode == BUILD_LIST || opcode == BUILD_SET) && - codestr[i+3]==COMPARE_OP && - ISBASICBLOCK(blocks, h, 3*(j+2)) && - (GETARG(codestr,i+3)==6 || - GETARG(codestr,i+3)==7))) && - tuple_of_constants(&codestr[h], j, consts)) { - assert(codestr[i] == LOAD_CONST); - cumlc = 1; - break; - } - if (codestr[i+3] != UNPACK_SEQUENCE || - !ISBASICBLOCK(blocks,i,6) || - j != GETARG(codestr, i+3)) - continue; - if (j == 1) { - memset(codestr+i, NOP, 6); - } else if (j == 2) { - codestr[i] = ROT_TWO; - memset(codestr+i+1, NOP, 5); - } else if (j == 3) { - codestr[i] = ROT_THREE; - codestr[i+1] = ROT_TWO; - memset(codestr+i+2, NOP, 4); - } - break; - - /* Fold binary ops on constants. - LOAD_CONST c1 LOAD_CONST c2 BINOP --> LOAD_CONST binop(c1,c2) */ - case BINARY_POWER: - case BINARY_MULTIPLY: - case BINARY_TRUE_DIVIDE: - case BINARY_FLOOR_DIVIDE: - case BINARY_MODULO: - case BINARY_ADD: - case BINARY_SUBTRACT: - case BINARY_SUBSCR: - case BINARY_LSHIFT: - case BINARY_RSHIFT: - case BINARY_AND: - case BINARY_XOR: - case BINARY_OR: - if (lastlc >= 2 && - ISBASICBLOCK(blocks, i-6, 7) && - fold_binops_on_constants(&codestr[i-6], consts)) { - i -= 2; - assert(codestr[i] == LOAD_CONST); - cumlc = 1; - } - break; - - /* Fold unary ops on constants. - LOAD_CONST c1 UNARY_OP --> LOAD_CONST unary_op(c) */ - case UNARY_NEGATIVE: - case UNARY_INVERT: - case UNARY_POSITIVE: - if (lastlc >= 1 && - ISBASICBLOCK(blocks, i-3, 4) && - fold_unaryops_on_constants(&codestr[i-3], consts)) { - i -= 2; - assert(codestr[i] == LOAD_CONST); - cumlc = 1; - } - break; - - /* Simplify conditional jump to conditional jump where the - result of the first test implies the success of a similar - test or the failure of the opposite test. - Arises in code like: - "if a and b:" - "if a or b:" - "a and b or c" - "(a and b) and c" - x:JUMP_IF_FALSE_OR_POP y y:JUMP_IF_FALSE_OR_POP z - --> x:JUMP_IF_FALSE_OR_POP z - x:JUMP_IF_FALSE_OR_POP y y:JUMP_IF_TRUE_OR_POP z - --> x:POP_JUMP_IF_FALSE y+3 - where y+3 is the instruction following the second test. - */ - case JUMP_IF_FALSE_OR_POP: - case JUMP_IF_TRUE_OR_POP: - tgt = GETJUMPTGT(codestr, i); - j = codestr[tgt]; - if (CONDITIONAL_JUMP(j)) { - /* NOTE: all possible jumps here are - absolute! */ - if (JUMPS_ON_TRUE(j) == JUMPS_ON_TRUE(opcode)) { - /* The second jump will be - taken iff the first is. */ - tgttgt = GETJUMPTGT(codestr, tgt); - /* The current opcode inherits - its target's stack behaviour */ - codestr[i] = j; - SETARG(codestr, i, tgttgt); - goto reoptimize_current; - } else { - /* The second jump is not taken - if the first is (so jump past - it), and all conditional - jumps pop their argument when - they're not taken (so change - the first jump to pop its - argument when it's taken). */ - if (JUMPS_ON_TRUE(opcode)) - codestr[i] = POP_JUMP_IF_TRUE; - else - codestr[i] = POP_JUMP_IF_FALSE; - SETARG(codestr, i, (tgt + 3)); - goto reoptimize_current; - } - } - /* Intentional fallthrough */ - - /* Replace jumps to unconditional jumps */ - case POP_JUMP_IF_FALSE: - case POP_JUMP_IF_TRUE: - case FOR_ITER: - case JUMP_FORWARD: - case JUMP_ABSOLUTE: - case CONTINUE_LOOP: - case SETUP_LOOP: - case SETUP_EXCEPT: - case SETUP_FINALLY: - case SETUP_WITH: - tgt = GETJUMPTGT(codestr, i); - /* Replace JUMP_* to a RETURN into just a RETURN */ - if (UNCONDITIONAL_JUMP(opcode) && - codestr[tgt] == RETURN_VALUE) { - codestr[i] = RETURN_VALUE; - memset(codestr+i+1, NOP, 2); - continue; - } - if (!UNCONDITIONAL_JUMP(codestr[tgt])) - continue; - tgttgt = GETJUMPTGT(codestr, tgt); - if (opcode == JUMP_FORWARD) /* JMP_ABS can go backwards */ - opcode = JUMP_ABSOLUTE; - if (!ABSOLUTE_JUMP(opcode)) - tgttgt -= i + 3; /* Calc relative jump addr */ - if (tgttgt < 0) /* No backward relative jumps */ - continue; - codestr[i] = opcode; - SETARG(codestr, i, tgttgt); - break; - - case EXTENDED_ARG: - if (codestr[i+3] != MAKE_FUNCTION) - goto exitUnchanged; - /* don't visit MAKE_FUNCTION as GETARG will be wrong */ - i += 3; - break; - - /* Replace RETURN LOAD_CONST None RETURN with just RETURN */ - /* Remove unreachable JUMPs after RETURN */ - case RETURN_VALUE: - if (i+4 >= codelen) - continue; - if (codestr[i+4] == RETURN_VALUE && - ISBASICBLOCK(blocks,i,5)) - memset(codestr+i+1, NOP, 4); - else if (UNCONDITIONAL_JUMP(codestr[i+1]) && - ISBASICBLOCK(blocks,i,4)) - memset(codestr+i+1, NOP, 3); - break; - } - } - - /* Fixup linenotab */ - for (i=0, nops=0 ; i 32700) + goto exitUnchanged; + + /* Make a modifiable copy of the code string */ + codestr = (unsigned char *)PyMem_Malloc(codelen); + if (codestr == NULL) + goto exitError; + codestr = (unsigned char *)memcpy(codestr, + PyBytes_AS_STRING(code), codelen); + + /* Verify that RETURN_VALUE terminates the codestring. This allows + the various transformation patterns to look ahead several + instructions without additional checks to make sure they are not + looking beyond the end of the code string. + */ + if (codestr[codelen-1] != RETURN_VALUE) + goto exitUnchanged; + + /* Mapping to new jump targets after NOPs are removed */ + addrmap = (int *)PyMem_Malloc(codelen * sizeof(int)); + if (addrmap == NULL) + goto exitError; + + blocks = markblocks(codestr, codelen); + if (blocks == NULL) + goto exitError; + assert(PyList_Check(consts)); + + for (i=0 ; i a is not b + not a in b --> a not in b + not a is not b --> a is b + not a not in b --> a in b + */ + case COMPARE_OP: + j = GETARG(codestr, i); + if (j < 6 || j > 9 || + codestr[i+3] != UNARY_NOT || + !ISBASICBLOCK(blocks,i,4)) + continue; + SETARG(codestr, i, (j^1)); + codestr[i+3] = NOP; + break; + + /* Replace LOAD_GLOBAL/LOAD_NAME None/True/False + with LOAD_CONST None/True/False */ + case LOAD_NAME: + case LOAD_GLOBAL: + j = GETARG(codestr, i); + name = _PyUnicode_AsString(PyTuple_GET_ITEM(names, j)); + h = load_global(codestr, i, name, consts); + if (h < 0) + goto exitError; + else if (h == 0) + continue; + cumlc = lastlc + 1; + break; + + /* Skip over LOAD_CONST trueconst + POP_JUMP_IF_FALSE xx. This improves + "while 1" performance. */ + case LOAD_CONST: + cumlc = lastlc + 1; + j = GETARG(codestr, i); + if (codestr[i+3] != POP_JUMP_IF_FALSE || + !ISBASICBLOCK(blocks,i,6) || + !PyObject_IsTrue(PyList_GET_ITEM(consts, j))) + continue; + memset(codestr+i, NOP, 6); + cumlc = 0; + break; + + /* Try to fold tuples of constants (includes a case for lists and sets + which are only used for "in" and "not in" tests). + Skip over BUILD_SEQN 1 UNPACK_SEQN 1. + Replace BUILD_SEQN 2 UNPACK_SEQN 2 with ROT2. + Replace BUILD_SEQN 3 UNPACK_SEQN 3 with ROT3 ROT2. */ + case BUILD_TUPLE: + case BUILD_LIST: + case BUILD_SET: + j = GETARG(codestr, i); + h = i - 3 * j; + if (h >= 0 && + j <= lastlc && + ((opcode == BUILD_TUPLE && + ISBASICBLOCK(blocks, h, 3*(j+1))) || + ((opcode == BUILD_LIST || opcode == BUILD_SET) && + codestr[i+3]==COMPARE_OP && + ISBASICBLOCK(blocks, h, 3*(j+2)) && + (GETARG(codestr,i+3)==6 || + GETARG(codestr,i+3)==7))) && + tuple_of_constants(&codestr[h], j, consts)) { + assert(codestr[i] == LOAD_CONST); + cumlc = 1; + break; + } + if (codestr[i+3] != UNPACK_SEQUENCE || + !ISBASICBLOCK(blocks,i,6) || + j != GETARG(codestr, i+3)) + continue; + if (j == 1) { + memset(codestr+i, NOP, 6); + } else if (j == 2) { + codestr[i] = ROT_TWO; + memset(codestr+i+1, NOP, 5); + } else if (j == 3) { + codestr[i] = ROT_THREE; + codestr[i+1] = ROT_TWO; + memset(codestr+i+2, NOP, 4); + } + break; + + /* Fold binary ops on constants. + LOAD_CONST c1 LOAD_CONST c2 BINOP --> LOAD_CONST binop(c1,c2) */ + case BINARY_POWER: + case BINARY_MULTIPLY: + case BINARY_TRUE_DIVIDE: + case BINARY_FLOOR_DIVIDE: + case BINARY_MODULO: + case BINARY_ADD: + case BINARY_SUBTRACT: + case BINARY_SUBSCR: + case BINARY_LSHIFT: + case BINARY_RSHIFT: + case BINARY_AND: + case BINARY_XOR: + case BINARY_OR: + if (lastlc >= 2 && + ISBASICBLOCK(blocks, i-6, 7) && + fold_binops_on_constants(&codestr[i-6], consts)) { + i -= 2; + assert(codestr[i] == LOAD_CONST); + cumlc = 1; + } + break; + + /* Fold unary ops on constants. + LOAD_CONST c1 UNARY_OP --> LOAD_CONST unary_op(c) */ + case UNARY_NEGATIVE: + case UNARY_INVERT: + case UNARY_POSITIVE: + if (lastlc >= 1 && + ISBASICBLOCK(blocks, i-3, 4) && + fold_unaryops_on_constants(&codestr[i-3], consts)) { + i -= 2; + assert(codestr[i] == LOAD_CONST); + cumlc = 1; + } + break; + + /* Simplify conditional jump to conditional jump where the + result of the first test implies the success of a similar + test or the failure of the opposite test. + Arises in code like: + "if a and b:" + "if a or b:" + "a and b or c" + "(a and b) and c" + x:JUMP_IF_FALSE_OR_POP y y:JUMP_IF_FALSE_OR_POP z + --> x:JUMP_IF_FALSE_OR_POP z + x:JUMP_IF_FALSE_OR_POP y y:JUMP_IF_TRUE_OR_POP z + --> x:POP_JUMP_IF_FALSE y+3 + where y+3 is the instruction following the second test. + */ + case JUMP_IF_FALSE_OR_POP: + case JUMP_IF_TRUE_OR_POP: + tgt = GETJUMPTGT(codestr, i); + j = codestr[tgt]; + if (CONDITIONAL_JUMP(j)) { + /* NOTE: all possible jumps here are + absolute! */ + if (JUMPS_ON_TRUE(j) == JUMPS_ON_TRUE(opcode)) { + /* The second jump will be + taken iff the first is. */ + tgttgt = GETJUMPTGT(codestr, tgt); + /* The current opcode inherits + its target's stack behaviour */ + codestr[i] = j; + SETARG(codestr, i, tgttgt); + goto reoptimize_current; + } else { + /* The second jump is not taken + if the first is (so jump past + it), and all conditional + jumps pop their argument when + they're not taken (so change + the first jump to pop its + argument when it's taken). */ + if (JUMPS_ON_TRUE(opcode)) + codestr[i] = POP_JUMP_IF_TRUE; + else + codestr[i] = POP_JUMP_IF_FALSE; + SETARG(codestr, i, (tgt + 3)); + goto reoptimize_current; + } + } + /* Intentional fallthrough */ + + /* Replace jumps to unconditional jumps */ + case POP_JUMP_IF_FALSE: + case POP_JUMP_IF_TRUE: + case FOR_ITER: + case JUMP_FORWARD: + case JUMP_ABSOLUTE: + case CONTINUE_LOOP: + case SETUP_LOOP: + case SETUP_EXCEPT: + case SETUP_FINALLY: + case SETUP_WITH: + tgt = GETJUMPTGT(codestr, i); + /* Replace JUMP_* to a RETURN into just a RETURN */ + if (UNCONDITIONAL_JUMP(opcode) && + codestr[tgt] == RETURN_VALUE) { + codestr[i] = RETURN_VALUE; + memset(codestr+i+1, NOP, 2); + continue; + } + if (!UNCONDITIONAL_JUMP(codestr[tgt])) + continue; + tgttgt = GETJUMPTGT(codestr, tgt); + if (opcode == JUMP_FORWARD) /* JMP_ABS can go backwards */ + opcode = JUMP_ABSOLUTE; + if (!ABSOLUTE_JUMP(opcode)) + tgttgt -= i + 3; /* Calc relative jump addr */ + if (tgttgt < 0) /* No backward relative jumps */ + continue; + codestr[i] = opcode; + SETARG(codestr, i, tgttgt); + break; + + case EXTENDED_ARG: + if (codestr[i+3] != MAKE_FUNCTION) + goto exitUnchanged; + /* don't visit MAKE_FUNCTION as GETARG will be wrong */ + i += 3; + break; + + /* Replace RETURN LOAD_CONST None RETURN with just RETURN */ + /* Remove unreachable JUMPs after RETURN */ + case RETURN_VALUE: + if (i+4 >= codelen) + continue; + if (codestr[i+4] == RETURN_VALUE && + ISBASICBLOCK(blocks,i,5)) + memset(codestr+i+1, NOP, 4); + else if (UNCONDITIONAL_JUMP(codestr[i+1]) && + ISBASICBLOCK(blocks,i,4)) + memset(codestr+i+1, NOP, 3); + break; + } + } + + /* Fixup linenotab */ + for (i=0, nops=0 ; iab_size = size; - b->ab_mem = (void *)(b + 1); - b->ab_next = NULL; - b->ab_offset = ROUNDUP((Py_uintptr_t)(b->ab_mem)) - - (Py_uintptr_t)(b->ab_mem); - return b; + /* Allocate header and block as one unit. + ab_mem points just past header. */ + block *b = (block *)malloc(sizeof(block) + size); + if (!b) + return NULL; + b->ab_size = size; + b->ab_mem = (void *)(b + 1); + b->ab_next = NULL; + b->ab_offset = ROUNDUP((Py_uintptr_t)(b->ab_mem)) - + (Py_uintptr_t)(b->ab_mem); + return b; } static void block_free(block *b) { - while (b) { - block *next = b->ab_next; - free(b); - b = next; - } + while (b) { + block *next = b->ab_next; + free(b); + b = next; + } } static void * block_alloc(block *b, size_t size) { - void *p; - assert(b); - size = ROUNDUP(size); - if (b->ab_offset + size > b->ab_size) { - /* If we need to allocate more memory than will fit in - the default block, allocate a one-off block that is - exactly the right size. */ - /* TODO(jhylton): Think about space waste at end of block */ - block *newbl = block_new( - size < DEFAULT_BLOCK_SIZE ? - DEFAULT_BLOCK_SIZE : size); - if (!newbl) - return NULL; - assert(!b->ab_next); - b->ab_next = newbl; - b = newbl; - } - - assert(b->ab_offset + size <= b->ab_size); - p = (void *)(((char *)b->ab_mem) + b->ab_offset); - b->ab_offset += size; - return p; + void *p; + assert(b); + size = ROUNDUP(size); + if (b->ab_offset + size > b->ab_size) { + /* If we need to allocate more memory than will fit in + the default block, allocate a one-off block that is + exactly the right size. */ + /* TODO(jhylton): Think about space waste at end of block */ + block *newbl = block_new( + size < DEFAULT_BLOCK_SIZE ? + DEFAULT_BLOCK_SIZE : size); + if (!newbl) + return NULL; + assert(!b->ab_next); + b->ab_next = newbl; + b = newbl; + } + + assert(b->ab_offset + size <= b->ab_size); + p = (void *)(((char *)b->ab_mem) + b->ab_offset); + b->ab_offset += size; + return p; } PyArena * PyArena_New() { - PyArena* arena = (PyArena *)malloc(sizeof(PyArena)); - if (!arena) - return (PyArena*)PyErr_NoMemory(); - - arena->a_head = block_new(DEFAULT_BLOCK_SIZE); - arena->a_cur = arena->a_head; - if (!arena->a_head) { - free((void *)arena); - return (PyArena*)PyErr_NoMemory(); - } - arena->a_objects = PyList_New(0); - if (!arena->a_objects) { - block_free(arena->a_head); - free((void *)arena); - return (PyArena*)PyErr_NoMemory(); - } + PyArena* arena = (PyArena *)malloc(sizeof(PyArena)); + if (!arena) + return (PyArena*)PyErr_NoMemory(); + + arena->a_head = block_new(DEFAULT_BLOCK_SIZE); + arena->a_cur = arena->a_head; + if (!arena->a_head) { + free((void *)arena); + return (PyArena*)PyErr_NoMemory(); + } + arena->a_objects = PyList_New(0); + if (!arena->a_objects) { + block_free(arena->a_head); + free((void *)arena); + return (PyArena*)PyErr_NoMemory(); + } #if defined(Py_DEBUG) - arena->total_allocs = 0; - arena->total_size = 0; - arena->total_blocks = 1; - arena->total_block_size = DEFAULT_BLOCK_SIZE; - arena->total_big_blocks = 0; + arena->total_allocs = 0; + arena->total_size = 0; + arena->total_blocks = 1; + arena->total_block_size = DEFAULT_BLOCK_SIZE; + arena->total_big_blocks = 0; #endif - return arena; + return arena; } void PyArena_Free(PyArena *arena) { - int r; - assert(arena); + int r; + assert(arena); #if defined(Py_DEBUG) - /* - fprintf(stderr, - "alloc=%d size=%d blocks=%d block_size=%d big=%d objects=%d\n", - arena->total_allocs, arena->total_size, arena->total_blocks, - arena->total_block_size, arena->total_big_blocks, - PyList_Size(arena->a_objects)); - */ + /* + fprintf(stderr, + "alloc=%d size=%d blocks=%d block_size=%d big=%d objects=%d\n", + arena->total_allocs, arena->total_size, arena->total_blocks, + arena->total_block_size, arena->total_big_blocks, + PyList_Size(arena->a_objects)); + */ #endif - block_free(arena->a_head); - /* This property normally holds, except when the code being compiled - is sys.getobjects(0), in which case there will be two references. - assert(arena->a_objects->ob_refcnt == 1); - */ - - /* Clear all the elements from the list. This is necessary - to guarantee that they will be DECREFed. */ - r = PyList_SetSlice(arena->a_objects, - 0, PyList_GET_SIZE(arena->a_objects), NULL); - assert(r == 0); - assert(PyList_GET_SIZE(arena->a_objects) == 0); - Py_DECREF(arena->a_objects); - free(arena); + block_free(arena->a_head); + /* This property normally holds, except when the code being compiled + is sys.getobjects(0), in which case there will be two references. + assert(arena->a_objects->ob_refcnt == 1); + */ + + /* Clear all the elements from the list. This is necessary + to guarantee that they will be DECREFed. */ + r = PyList_SetSlice(arena->a_objects, + 0, PyList_GET_SIZE(arena->a_objects), NULL); + assert(r == 0); + assert(PyList_GET_SIZE(arena->a_objects) == 0); + Py_DECREF(arena->a_objects); + free(arena); } void * PyArena_Malloc(PyArena *arena, size_t size) { - void *p = block_alloc(arena->a_cur, size); - if (!p) - return PyErr_NoMemory(); + void *p = block_alloc(arena->a_cur, size); + if (!p) + return PyErr_NoMemory(); #if defined(Py_DEBUG) - arena->total_allocs++; - arena->total_size += size; + arena->total_allocs++; + arena->total_size += size; #endif - /* Reset cur if we allocated a new block. */ - if (arena->a_cur->ab_next) { - arena->a_cur = arena->a_cur->ab_next; + /* Reset cur if we allocated a new block. */ + if (arena->a_cur->ab_next) { + arena->a_cur = arena->a_cur->ab_next; #if defined(Py_DEBUG) - arena->total_blocks++; - arena->total_block_size += arena->a_cur->ab_size; - if (arena->a_cur->ab_size > DEFAULT_BLOCK_SIZE) - ++arena->total_big_blocks; + arena->total_blocks++; + arena->total_block_size += arena->a_cur->ab_size; + if (arena->a_cur->ab_size > DEFAULT_BLOCK_SIZE) + ++arena->total_big_blocks; #endif - } - return p; + } + return p; } int PyArena_AddPyObject(PyArena *arena, PyObject *obj) { - int r = PyList_Append(arena->a_objects, obj); - if (r >= 0) { - Py_DECREF(obj); - } - return r; + int r = PyList_Append(arena->a_objects, obj); + if (r >= 0) { + Py_DECREF(obj); + } + return r; } Modified: python/branches/py3k/Python/pymath.c ============================================================================== --- python/branches/py3k/Python/pymath.c (original) +++ python/branches/py3k/Python/pymath.c Sun May 9 17:52:27 2010 @@ -7,9 +7,9 @@ thus rounding from extended precision to double precision. */ double _Py_force_double(double x) { - volatile double y; - y = x; - return y; + volatile double y; + y = x; + return y; } #endif @@ -34,21 +34,21 @@ #ifndef HAVE_HYPOT double hypot(double x, double y) { - double yx; + double yx; - x = fabs(x); - y = fabs(y); - if (x < y) { - double temp = x; - x = y; - y = temp; - } - if (x == 0.) - return 0.; - else { - yx = y/x; - return x*sqrt(1.+yx*yx); - } + x = fabs(x); + y = fabs(y); + if (x < y) { + double temp = x; + x = y; + y = temp; + } + if (x == 0.) + return 0.; + else { + yx = y/x; + return x*sqrt(1.+yx*yx); + } } #endif /* HAVE_HYPOT */ @@ -56,12 +56,12 @@ double copysign(double x, double y) { - /* use atan2 to distinguish -0. from 0. */ - if (y > 0. || (y == 0. && atan2(y, -1.) > 0.)) { - return fabs(x); - } else { - return -fabs(x); - } + /* use atan2 to distinguish -0. from 0. */ + if (y > 0. || (y == 0. && atan2(y, -1.) > 0.)) { + return fabs(x); + } else { + return -fabs(x); + } } #endif /* HAVE_COPYSIGN */ @@ -73,7 +73,7 @@ absx = fabs(x); y = floor(absx); if (absx - y >= 0.5) - y += 1.0; + y += 1.0; return copysign(y, x); } #endif /* HAVE_ROUND */ Modified: python/branches/py3k/Python/pystate.c ============================================================================== --- python/branches/py3k/Python/pystate.c (original) +++ python/branches/py3k/Python/pystate.c Sun May 9 17:52:27 2010 @@ -60,95 +60,95 @@ PyInterpreterState * PyInterpreterState_New(void) { - PyInterpreterState *interp = (PyInterpreterState *) - malloc(sizeof(PyInterpreterState)); + PyInterpreterState *interp = (PyInterpreterState *) + malloc(sizeof(PyInterpreterState)); - if (interp != NULL) { - HEAD_INIT(); + if (interp != NULL) { + HEAD_INIT(); #ifdef WITH_THREAD - if (head_mutex == NULL) - Py_FatalError("Can't initialize threads for interpreter"); + if (head_mutex == NULL) + Py_FatalError("Can't initialize threads for interpreter"); #endif - interp->modules = NULL; - interp->modules_reloading = NULL; - interp->modules_by_index = NULL; - interp->sysdict = NULL; - interp->builtins = NULL; - interp->tstate_head = NULL; - interp->codec_search_path = NULL; - interp->codec_search_cache = NULL; - interp->codec_error_registry = NULL; - interp->codecs_initialized = 0; + interp->modules = NULL; + interp->modules_reloading = NULL; + interp->modules_by_index = NULL; + interp->sysdict = NULL; + interp->builtins = NULL; + interp->tstate_head = NULL; + interp->codec_search_path = NULL; + interp->codec_search_cache = NULL; + interp->codec_error_registry = NULL; + interp->codecs_initialized = 0; #ifdef HAVE_DLOPEN #ifdef RTLD_NOW - interp->dlopenflags = RTLD_NOW; + interp->dlopenflags = RTLD_NOW; #else - interp->dlopenflags = RTLD_LAZY; + interp->dlopenflags = RTLD_LAZY; #endif #endif #ifdef WITH_TSC - interp->tscdump = 0; + interp->tscdump = 0; #endif - HEAD_LOCK(); - interp->next = interp_head; - interp_head = interp; - HEAD_UNLOCK(); - } + HEAD_LOCK(); + interp->next = interp_head; + interp_head = interp; + HEAD_UNLOCK(); + } - return interp; + return interp; } void PyInterpreterState_Clear(PyInterpreterState *interp) { - PyThreadState *p; - HEAD_LOCK(); - for (p = interp->tstate_head; p != NULL; p = p->next) - PyThreadState_Clear(p); - HEAD_UNLOCK(); - Py_CLEAR(interp->codec_search_path); - Py_CLEAR(interp->codec_search_cache); - Py_CLEAR(interp->codec_error_registry); - Py_CLEAR(interp->modules); - Py_CLEAR(interp->modules_by_index); - Py_CLEAR(interp->modules_reloading); - Py_CLEAR(interp->sysdict); - Py_CLEAR(interp->builtins); + PyThreadState *p; + HEAD_LOCK(); + for (p = interp->tstate_head; p != NULL; p = p->next) + PyThreadState_Clear(p); + HEAD_UNLOCK(); + Py_CLEAR(interp->codec_search_path); + Py_CLEAR(interp->codec_search_cache); + Py_CLEAR(interp->codec_error_registry); + Py_CLEAR(interp->modules); + Py_CLEAR(interp->modules_by_index); + Py_CLEAR(interp->modules_reloading); + Py_CLEAR(interp->sysdict); + Py_CLEAR(interp->builtins); } static void zapthreads(PyInterpreterState *interp) { - PyThreadState *p; - /* No need to lock the mutex here because this should only happen - when the threads are all really dead (XXX famous last words). */ - while ((p = interp->tstate_head) != NULL) { - PyThreadState_Delete(p); - } + PyThreadState *p; + /* No need to lock the mutex here because this should only happen + when the threads are all really dead (XXX famous last words). */ + while ((p = interp->tstate_head) != NULL) { + PyThreadState_Delete(p); + } } void PyInterpreterState_Delete(PyInterpreterState *interp) { - PyInterpreterState **p; - zapthreads(interp); - HEAD_LOCK(); - for (p = &interp_head; ; p = &(*p)->next) { - if (*p == NULL) - Py_FatalError( - "PyInterpreterState_Delete: invalid interp"); - if (*p == interp) - break; - } - if (interp->tstate_head != NULL) - Py_FatalError("PyInterpreterState_Delete: remaining threads"); - *p = interp->next; - HEAD_UNLOCK(); - free(interp); + PyInterpreterState **p; + zapthreads(interp); + HEAD_LOCK(); + for (p = &interp_head; ; p = &(*p)->next) { + if (*p == NULL) + Py_FatalError( + "PyInterpreterState_Delete: invalid interp"); + if (*p == interp) + break; + } + if (interp->tstate_head != NULL) + Py_FatalError("PyInterpreterState_Delete: remaining threads"); + *p = interp->next; + HEAD_UNLOCK(); + free(interp); } @@ -156,141 +156,141 @@ static struct _frame * threadstate_getframe(PyThreadState *self) { - return self->frame; + return self->frame; } static PyThreadState * new_threadstate(PyInterpreterState *interp, int init) { - PyThreadState *tstate = (PyThreadState *)malloc(sizeof(PyThreadState)); + PyThreadState *tstate = (PyThreadState *)malloc(sizeof(PyThreadState)); - if (_PyThreadState_GetFrame == NULL) - _PyThreadState_GetFrame = threadstate_getframe; + if (_PyThreadState_GetFrame == NULL) + _PyThreadState_GetFrame = threadstate_getframe; - if (tstate != NULL) { - tstate->interp = interp; + if (tstate != NULL) { + tstate->interp = interp; - tstate->frame = NULL; - tstate->recursion_depth = 0; - tstate->overflowed = 0; - tstate->recursion_critical = 0; - tstate->tracing = 0; - tstate->use_tracing = 0; - tstate->tick_counter = 0; - tstate->gilstate_counter = 0; - tstate->async_exc = NULL; + tstate->frame = NULL; + tstate->recursion_depth = 0; + tstate->overflowed = 0; + tstate->recursion_critical = 0; + tstate->tracing = 0; + tstate->use_tracing = 0; + tstate->tick_counter = 0; + tstate->gilstate_counter = 0; + tstate->async_exc = NULL; #ifdef WITH_THREAD - tstate->thread_id = PyThread_get_thread_ident(); + tstate->thread_id = PyThread_get_thread_ident(); #else - tstate->thread_id = 0; + tstate->thread_id = 0; #endif - tstate->dict = NULL; + tstate->dict = NULL; - tstate->curexc_type = NULL; - tstate->curexc_value = NULL; - tstate->curexc_traceback = NULL; - - tstate->exc_type = NULL; - tstate->exc_value = NULL; - tstate->exc_traceback = NULL; - - tstate->c_profilefunc = NULL; - tstate->c_tracefunc = NULL; - tstate->c_profileobj = NULL; - tstate->c_traceobj = NULL; - - if (init) - _PyThreadState_Init(tstate); - - HEAD_LOCK(); - tstate->next = interp->tstate_head; - interp->tstate_head = tstate; - HEAD_UNLOCK(); - } + tstate->curexc_type = NULL; + tstate->curexc_value = NULL; + tstate->curexc_traceback = NULL; + + tstate->exc_type = NULL; + tstate->exc_value = NULL; + tstate->exc_traceback = NULL; + + tstate->c_profilefunc = NULL; + tstate->c_tracefunc = NULL; + tstate->c_profileobj = NULL; + tstate->c_traceobj = NULL; + + if (init) + _PyThreadState_Init(tstate); + + HEAD_LOCK(); + tstate->next = interp->tstate_head; + interp->tstate_head = tstate; + HEAD_UNLOCK(); + } - return tstate; + return tstate; } PyThreadState * PyThreadState_New(PyInterpreterState *interp) { - return new_threadstate(interp, 1); + return new_threadstate(interp, 1); } PyThreadState * _PyThreadState_Prealloc(PyInterpreterState *interp) { - return new_threadstate(interp, 0); + return new_threadstate(interp, 0); } void _PyThreadState_Init(PyThreadState *tstate) { #ifdef WITH_THREAD - _PyGILState_NoteThreadState(tstate); + _PyGILState_NoteThreadState(tstate); #endif } PyObject* PyState_FindModule(struct PyModuleDef* m) { - Py_ssize_t index = m->m_base.m_index; - PyInterpreterState *state = PyThreadState_GET()->interp; - PyObject *res; - if (index == 0) - return NULL; - if (state->modules_by_index == NULL) - return NULL; - if (index > PyList_GET_SIZE(state->modules_by_index)) - return NULL; - res = PyList_GET_ITEM(state->modules_by_index, index); - return res==Py_None ? NULL : res; + Py_ssize_t index = m->m_base.m_index; + PyInterpreterState *state = PyThreadState_GET()->interp; + PyObject *res; + if (index == 0) + return NULL; + if (state->modules_by_index == NULL) + return NULL; + if (index > PyList_GET_SIZE(state->modules_by_index)) + return NULL; + res = PyList_GET_ITEM(state->modules_by_index, index); + return res==Py_None ? NULL : res; } int _PyState_AddModule(PyObject* module, struct PyModuleDef* def) { - PyInterpreterState *state = PyThreadState_GET()->interp; - if (!def) - return -1; - if (!state->modules_by_index) { - state->modules_by_index = PyList_New(0); - if (!state->modules_by_index) - return -1; - } - while(PyList_GET_SIZE(state->modules_by_index) <= def->m_base.m_index) - if (PyList_Append(state->modules_by_index, Py_None) < 0) - return -1; - Py_INCREF(module); - return PyList_SetItem(state->modules_by_index, - def->m_base.m_index, module); + PyInterpreterState *state = PyThreadState_GET()->interp; + if (!def) + return -1; + if (!state->modules_by_index) { + state->modules_by_index = PyList_New(0); + if (!state->modules_by_index) + return -1; + } + while(PyList_GET_SIZE(state->modules_by_index) <= def->m_base.m_index) + if (PyList_Append(state->modules_by_index, Py_None) < 0) + return -1; + Py_INCREF(module); + return PyList_SetItem(state->modules_by_index, + def->m_base.m_index, module); } void PyThreadState_Clear(PyThreadState *tstate) { - if (Py_VerboseFlag && tstate->frame != NULL) - fprintf(stderr, - "PyThreadState_Clear: warning: thread still has a frame\n"); - - Py_CLEAR(tstate->frame); - - Py_CLEAR(tstate->dict); - Py_CLEAR(tstate->async_exc); - - Py_CLEAR(tstate->curexc_type); - Py_CLEAR(tstate->curexc_value); - Py_CLEAR(tstate->curexc_traceback); - - Py_CLEAR(tstate->exc_type); - Py_CLEAR(tstate->exc_value); - Py_CLEAR(tstate->exc_traceback); - - tstate->c_profilefunc = NULL; - tstate->c_tracefunc = NULL; - Py_CLEAR(tstate->c_profileobj); - Py_CLEAR(tstate->c_traceobj); + if (Py_VerboseFlag && tstate->frame != NULL) + fprintf(stderr, + "PyThreadState_Clear: warning: thread still has a frame\n"); + + Py_CLEAR(tstate->frame); + + Py_CLEAR(tstate->dict); + Py_CLEAR(tstate->async_exc); + + Py_CLEAR(tstate->curexc_type); + Py_CLEAR(tstate->curexc_value); + Py_CLEAR(tstate->curexc_traceback); + + Py_CLEAR(tstate->exc_type); + Py_CLEAR(tstate->exc_value); + Py_CLEAR(tstate->exc_traceback); + + tstate->c_profilefunc = NULL; + tstate->c_tracefunc = NULL; + Py_CLEAR(tstate->c_profileobj); + Py_CLEAR(tstate->c_traceobj); } @@ -298,50 +298,50 @@ static void tstate_delete_common(PyThreadState *tstate) { - PyInterpreterState *interp; - PyThreadState **p; - PyThreadState *prev_p = NULL; - if (tstate == NULL) - Py_FatalError("PyThreadState_Delete: NULL tstate"); - interp = tstate->interp; - if (interp == NULL) - Py_FatalError("PyThreadState_Delete: NULL interp"); - HEAD_LOCK(); - for (p = &interp->tstate_head; ; p = &(*p)->next) { - if (*p == NULL) - Py_FatalError( - "PyThreadState_Delete: invalid tstate"); - if (*p == tstate) - break; - /* Sanity check. These states should never happen but if - * they do we must abort. Otherwise we'll end up spinning in - * in a tight loop with the lock held. A similar check is done - * in thread.c find_key(). */ - if (*p == prev_p) - Py_FatalError( - "PyThreadState_Delete: small circular list(!)" - " and tstate not found."); - prev_p = *p; - if ((*p)->next == interp->tstate_head) - Py_FatalError( - "PyThreadState_Delete: circular list(!) and" - " tstate not found."); - } - *p = tstate->next; - HEAD_UNLOCK(); - free(tstate); + PyInterpreterState *interp; + PyThreadState **p; + PyThreadState *prev_p = NULL; + if (tstate == NULL) + Py_FatalError("PyThreadState_Delete: NULL tstate"); + interp = tstate->interp; + if (interp == NULL) + Py_FatalError("PyThreadState_Delete: NULL interp"); + HEAD_LOCK(); + for (p = &interp->tstate_head; ; p = &(*p)->next) { + if (*p == NULL) + Py_FatalError( + "PyThreadState_Delete: invalid tstate"); + if (*p == tstate) + break; + /* Sanity check. These states should never happen but if + * they do we must abort. Otherwise we'll end up spinning in + * in a tight loop with the lock held. A similar check is done + * in thread.c find_key(). */ + if (*p == prev_p) + Py_FatalError( + "PyThreadState_Delete: small circular list(!)" + " and tstate not found."); + prev_p = *p; + if ((*p)->next == interp->tstate_head) + Py_FatalError( + "PyThreadState_Delete: circular list(!) and" + " tstate not found."); + } + *p = tstate->next; + HEAD_UNLOCK(); + free(tstate); } void PyThreadState_Delete(PyThreadState *tstate) { - if (tstate == _Py_atomic_load_relaxed(&_PyThreadState_Current)) - Py_FatalError("PyThreadState_Delete: tstate is still current"); - tstate_delete_common(tstate); + if (tstate == _Py_atomic_load_relaxed(&_PyThreadState_Current)) + Py_FatalError("PyThreadState_Delete: tstate is still current"); + tstate_delete_common(tstate); #ifdef WITH_THREAD - if (autoTLSkey && PyThread_get_key_value(autoTLSkey) == tstate) - PyThread_delete_key_value(autoTLSkey); + if (autoTLSkey && PyThread_get_key_value(autoTLSkey) == tstate) + PyThread_delete_key_value(autoTLSkey); #endif /* WITH_THREAD */ } @@ -350,16 +350,16 @@ void PyThreadState_DeleteCurrent() { - PyThreadState *tstate = (PyThreadState*)_Py_atomic_load_relaxed( - &_PyThreadState_Current); - if (tstate == NULL) - Py_FatalError( - "PyThreadState_DeleteCurrent: no current tstate"); - _Py_atomic_store_relaxed(&_PyThreadState_Current, NULL); - tstate_delete_common(tstate); - if (autoTLSkey && PyThread_get_key_value(autoTLSkey) == tstate) - PyThread_delete_key_value(autoTLSkey); - PyEval_ReleaseLock(); + PyThreadState *tstate = (PyThreadState*)_Py_atomic_load_relaxed( + &_PyThreadState_Current); + if (tstate == NULL) + Py_FatalError( + "PyThreadState_DeleteCurrent: no current tstate"); + _Py_atomic_store_relaxed(&_PyThreadState_Current, NULL); + tstate_delete_common(tstate); + if (autoTLSkey && PyThread_get_key_value(autoTLSkey) == tstate) + PyThread_delete_key_value(autoTLSkey); + PyEval_ReleaseLock(); } #endif /* WITH_THREAD */ @@ -367,39 +367,39 @@ PyThreadState * PyThreadState_Get(void) { - PyThreadState *tstate = (PyThreadState*)_Py_atomic_load_relaxed( - &_PyThreadState_Current); - if (tstate == NULL) - Py_FatalError("PyThreadState_Get: no current thread"); + PyThreadState *tstate = (PyThreadState*)_Py_atomic_load_relaxed( + &_PyThreadState_Current); + if (tstate == NULL) + Py_FatalError("PyThreadState_Get: no current thread"); - return tstate; + return tstate; } PyThreadState * PyThreadState_Swap(PyThreadState *newts) { - PyThreadState *oldts = (PyThreadState*)_Py_atomic_load_relaxed( - &_PyThreadState_Current); + PyThreadState *oldts = (PyThreadState*)_Py_atomic_load_relaxed( + &_PyThreadState_Current); - _Py_atomic_store_relaxed(&_PyThreadState_Current, newts); - /* It should not be possible for more than one thread state - to be used for a thread. Check this the best we can in debug - builds. - */ + _Py_atomic_store_relaxed(&_PyThreadState_Current, newts); + /* It should not be possible for more than one thread state + to be used for a thread. Check this the best we can in debug + builds. + */ #if defined(Py_DEBUG) && defined(WITH_THREAD) - if (newts) { - /* This can be called from PyEval_RestoreThread(). Similar - to it, we need to ensure errno doesn't change. - */ - int err = errno; - PyThreadState *check = PyGILState_GetThisThreadState(); - if (check && check->interp == newts->interp && check != newts) - Py_FatalError("Invalid thread state for this thread"); - errno = err; - } + if (newts) { + /* This can be called from PyEval_RestoreThread(). Similar + to it, we need to ensure errno doesn't change. + */ + int err = errno; + PyThreadState *check = PyGILState_GetThisThreadState(); + if (check && check->interp == newts->interp && check != newts) + Py_FatalError("Invalid thread state for this thread"); + errno = err; + } #endif - return oldts; + return oldts; } /* An extension mechanism to store arbitrary additional per-thread state. @@ -411,18 +411,18 @@ PyObject * PyThreadState_GetDict(void) { - PyThreadState *tstate = (PyThreadState*)_Py_atomic_load_relaxed( - &_PyThreadState_Current); - if (tstate == NULL) - return NULL; - - if (tstate->dict == NULL) { - PyObject *d; - tstate->dict = d = PyDict_New(); - if (d == NULL) - PyErr_Clear(); - } - return tstate->dict; + PyThreadState *tstate = (PyThreadState*)_Py_atomic_load_relaxed( + &_PyThreadState_Current); + if (tstate == NULL) + return NULL; + + if (tstate->dict == NULL) { + PyObject *d; + tstate->dict = d = PyDict_New(); + if (d == NULL) + PyErr_Clear(); + } + return tstate->dict; } @@ -436,37 +436,37 @@ int PyThreadState_SetAsyncExc(long id, PyObject *exc) { - PyThreadState *tstate = PyThreadState_GET(); - PyInterpreterState *interp = tstate->interp; - PyThreadState *p; - - /* Although the GIL is held, a few C API functions can be called - * without the GIL held, and in particular some that create and - * destroy thread and interpreter states. Those can mutate the - * list of thread states we're traversing, so to prevent that we lock - * head_mutex for the duration. - */ - HEAD_LOCK(); - for (p = interp->tstate_head; p != NULL; p = p->next) { - if (p->thread_id == id) { - /* Tricky: we need to decref the current value - * (if any) in p->async_exc, but that can in turn - * allow arbitrary Python code to run, including - * perhaps calls to this function. To prevent - * deadlock, we need to release head_mutex before - * the decref. - */ - PyObject *old_exc = p->async_exc; - Py_XINCREF(exc); - p->async_exc = exc; - HEAD_UNLOCK(); - Py_XDECREF(old_exc); - _PyEval_SignalAsyncExc(); - return 1; - } - } - HEAD_UNLOCK(); - return 0; + PyThreadState *tstate = PyThreadState_GET(); + PyInterpreterState *interp = tstate->interp; + PyThreadState *p; + + /* Although the GIL is held, a few C API functions can be called + * without the GIL held, and in particular some that create and + * destroy thread and interpreter states. Those can mutate the + * list of thread states we're traversing, so to prevent that we lock + * head_mutex for the duration. + */ + HEAD_LOCK(); + for (p = interp->tstate_head; p != NULL; p = p->next) { + if (p->thread_id == id) { + /* Tricky: we need to decref the current value + * (if any) in p->async_exc, but that can in turn + * allow arbitrary Python code to run, including + * perhaps calls to this function. To prevent + * deadlock, we need to release head_mutex before + * the decref. + */ + PyObject *old_exc = p->async_exc; + Py_XINCREF(exc); + p->async_exc = exc; + HEAD_UNLOCK(); + Py_XDECREF(old_exc); + _PyEval_SignalAsyncExc(); + return 1; + } + } + HEAD_UNLOCK(); + return 0; } @@ -476,22 +476,22 @@ PyInterpreterState * PyInterpreterState_Head(void) { - return interp_head; + return interp_head; } PyInterpreterState * PyInterpreterState_Next(PyInterpreterState *interp) { - return interp->next; + return interp->next; } PyThreadState * PyInterpreterState_ThreadHead(PyInterpreterState *interp) { - return interp->tstate_head; + return interp->tstate_head; } PyThreadState * PyThreadState_Next(PyThreadState *tstate) { - return tstate->next; + return tstate->next; } /* The implementation of sys._current_frames(). This is intended to be @@ -502,44 +502,44 @@ PyObject * _PyThread_CurrentFrames(void) { - PyObject *result; - PyInterpreterState *i; + PyObject *result; + PyInterpreterState *i; - result = PyDict_New(); - if (result == NULL) - return NULL; - - /* for i in all interpreters: - * for t in all of i's thread states: - * if t's frame isn't NULL, map t's id to its frame - * Because these lists can mutute even when the GIL is held, we - * need to grab head_mutex for the duration. - */ - HEAD_LOCK(); - for (i = interp_head; i != NULL; i = i->next) { - PyThreadState *t; - for (t = i->tstate_head; t != NULL; t = t->next) { - PyObject *id; - int stat; - struct _frame *frame = t->frame; - if (frame == NULL) - continue; - id = PyLong_FromLong(t->thread_id); - if (id == NULL) - goto Fail; - stat = PyDict_SetItem(result, id, (PyObject *)frame); - Py_DECREF(id); - if (stat < 0) - goto Fail; - } - } - HEAD_UNLOCK(); - return result; + result = PyDict_New(); + if (result == NULL) + return NULL; + + /* for i in all interpreters: + * for t in all of i's thread states: + * if t's frame isn't NULL, map t's id to its frame + * Because these lists can mutute even when the GIL is held, we + * need to grab head_mutex for the duration. + */ + HEAD_LOCK(); + for (i = interp_head; i != NULL; i = i->next) { + PyThreadState *t; + for (t = i->tstate_head; t != NULL; t = t->next) { + PyObject *id; + int stat; + struct _frame *frame = t->frame; + if (frame == NULL) + continue; + id = PyLong_FromLong(t->thread_id); + if (id == NULL) + goto Fail; + stat = PyDict_SetItem(result, id, (PyObject *)frame); + Py_DECREF(id); + if (stat < 0) + goto Fail; + } + } + HEAD_UNLOCK(); + return result; Fail: - HEAD_UNLOCK(); - Py_DECREF(result); - return NULL; + HEAD_UNLOCK(); + Py_DECREF(result); + return NULL; } /* Python "auto thread state" API. */ @@ -556,9 +556,9 @@ static int PyThreadState_IsCurrent(PyThreadState *tstate) { - /* Must be the tstate for this thread */ - assert(PyGILState_GetThisThreadState()==tstate); - return tstate == _Py_atomic_load_relaxed(&_PyThreadState_Current); + /* Must be the tstate for this thread */ + assert(PyGILState_GetThisThreadState()==tstate); + return tstate == _Py_atomic_load_relaxed(&_PyThreadState_Current); } /* Internal initialization/finalization functions called by @@ -567,21 +567,21 @@ void _PyGILState_Init(PyInterpreterState *i, PyThreadState *t) { - assert(i && t); /* must init with valid states */ - autoTLSkey = PyThread_create_key(); - autoInterpreterState = i; - assert(PyThread_get_key_value(autoTLSkey) == NULL); - assert(t->gilstate_counter == 0); + assert(i && t); /* must init with valid states */ + autoTLSkey = PyThread_create_key(); + autoInterpreterState = i; + assert(PyThread_get_key_value(autoTLSkey) == NULL); + assert(t->gilstate_counter == 0); - _PyGILState_NoteThreadState(t); + _PyGILState_NoteThreadState(t); } void _PyGILState_Fini(void) { - PyThread_delete_key(autoTLSkey); - autoTLSkey = 0; - autoInterpreterState = NULL; + PyThread_delete_key(autoTLSkey); + autoTLSkey = 0; + autoInterpreterState = NULL; } /* When a thread state is created for a thread by some mechanism other than @@ -592,113 +592,113 @@ static void _PyGILState_NoteThreadState(PyThreadState* tstate) { - /* If autoTLSkey is 0, this must be the very first threadstate created - in Py_Initialize(). Don't do anything for now (we'll be back here - when _PyGILState_Init is called). */ - if (!autoTLSkey) - return; - - /* Stick the thread state for this thread in thread local storage. - - The only situation where you can legitimately have more than one - thread state for an OS level thread is when there are multiple - interpreters, when: - - a) You shouldn't really be using the PyGILState_ APIs anyway, - and: - - b) The slightly odd way PyThread_set_key_value works (see - comments by its implementation) means that the first thread - state created for that given OS level thread will "win", - which seems reasonable behaviour. - */ - if (PyThread_set_key_value(autoTLSkey, (void *)tstate) < 0) - Py_FatalError("Couldn't create autoTLSkey mapping"); + /* If autoTLSkey is 0, this must be the very first threadstate created + in Py_Initialize(). Don't do anything for now (we'll be back here + when _PyGILState_Init is called). */ + if (!autoTLSkey) + return; + + /* Stick the thread state for this thread in thread local storage. + + The only situation where you can legitimately have more than one + thread state for an OS level thread is when there are multiple + interpreters, when: + + a) You shouldn't really be using the PyGILState_ APIs anyway, + and: + + b) The slightly odd way PyThread_set_key_value works (see + comments by its implementation) means that the first thread + state created for that given OS level thread will "win", + which seems reasonable behaviour. + */ + if (PyThread_set_key_value(autoTLSkey, (void *)tstate) < 0) + Py_FatalError("Couldn't create autoTLSkey mapping"); - /* PyGILState_Release must not try to delete this thread state. */ - tstate->gilstate_counter = 1; + /* PyGILState_Release must not try to delete this thread state. */ + tstate->gilstate_counter = 1; } /* The public functions */ PyThreadState * PyGILState_GetThisThreadState(void) { - if (autoInterpreterState == NULL || autoTLSkey == 0) - return NULL; - return (PyThreadState *)PyThread_get_key_value(autoTLSkey); + if (autoInterpreterState == NULL || autoTLSkey == 0) + return NULL; + return (PyThreadState *)PyThread_get_key_value(autoTLSkey); } PyGILState_STATE PyGILState_Ensure(void) { - int current; - PyThreadState *tcur; - /* Note that we do not auto-init Python here - apart from - potential races with 2 threads auto-initializing, pep-311 - spells out other issues. Embedders are expected to have - called Py_Initialize() and usually PyEval_InitThreads(). - */ - assert(autoInterpreterState); /* Py_Initialize() hasn't been called! */ - tcur = (PyThreadState *)PyThread_get_key_value(autoTLSkey); - if (tcur == NULL) { - /* Create a new thread state for this thread */ - tcur = PyThreadState_New(autoInterpreterState); - if (tcur == NULL) - Py_FatalError("Couldn't create thread-state for new thread"); - /* This is our thread state! We'll need to delete it in the - matching call to PyGILState_Release(). */ - tcur->gilstate_counter = 0; - current = 0; /* new thread state is never current */ - } - else - current = PyThreadState_IsCurrent(tcur); - if (current == 0) - PyEval_RestoreThread(tcur); - /* Update our counter in the thread-state - no need for locks: - - tcur will remain valid as we hold the GIL. - - the counter is safe as we are the only thread "allowed" - to modify this value - */ - ++tcur->gilstate_counter; - return current ? PyGILState_LOCKED : PyGILState_UNLOCKED; + int current; + PyThreadState *tcur; + /* Note that we do not auto-init Python here - apart from + potential races with 2 threads auto-initializing, pep-311 + spells out other issues. Embedders are expected to have + called Py_Initialize() and usually PyEval_InitThreads(). + */ + assert(autoInterpreterState); /* Py_Initialize() hasn't been called! */ + tcur = (PyThreadState *)PyThread_get_key_value(autoTLSkey); + if (tcur == NULL) { + /* Create a new thread state for this thread */ + tcur = PyThreadState_New(autoInterpreterState); + if (tcur == NULL) + Py_FatalError("Couldn't create thread-state for new thread"); + /* This is our thread state! We'll need to delete it in the + matching call to PyGILState_Release(). */ + tcur->gilstate_counter = 0; + current = 0; /* new thread state is never current */ + } + else + current = PyThreadState_IsCurrent(tcur); + if (current == 0) + PyEval_RestoreThread(tcur); + /* Update our counter in the thread-state - no need for locks: + - tcur will remain valid as we hold the GIL. + - the counter is safe as we are the only thread "allowed" + to modify this value + */ + ++tcur->gilstate_counter; + return current ? PyGILState_LOCKED : PyGILState_UNLOCKED; } void PyGILState_Release(PyGILState_STATE oldstate) { - PyThreadState *tcur = (PyThreadState *)PyThread_get_key_value( - autoTLSkey); - if (tcur == NULL) - Py_FatalError("auto-releasing thread-state, " - "but no thread-state for this thread"); - /* We must hold the GIL and have our thread state current */ - /* XXX - remove the check - the assert should be fine, - but while this is very new (April 2003), the extra check - by release-only users can't hurt. - */ - if (! PyThreadState_IsCurrent(tcur)) - Py_FatalError("This thread state must be current when releasing"); - assert(PyThreadState_IsCurrent(tcur)); - --tcur->gilstate_counter; - assert(tcur->gilstate_counter >= 0); /* illegal counter value */ - - /* If we're going to destroy this thread-state, we must - * clear it while the GIL is held, as destructors may run. - */ - if (tcur->gilstate_counter == 0) { - /* can't have been locked when we created it */ - assert(oldstate == PyGILState_UNLOCKED); - PyThreadState_Clear(tcur); - /* Delete the thread-state. Note this releases the GIL too! - * It's vital that the GIL be held here, to avoid shutdown - * races; see bugs 225673 and 1061968 (that nasty bug has a - * habit of coming back). - */ - PyThreadState_DeleteCurrent(); - } - /* Release the lock if necessary */ - else if (oldstate == PyGILState_UNLOCKED) - PyEval_SaveThread(); + PyThreadState *tcur = (PyThreadState *)PyThread_get_key_value( + autoTLSkey); + if (tcur == NULL) + Py_FatalError("auto-releasing thread-state, " + "but no thread-state for this thread"); + /* We must hold the GIL and have our thread state current */ + /* XXX - remove the check - the assert should be fine, + but while this is very new (April 2003), the extra check + by release-only users can't hurt. + */ + if (! PyThreadState_IsCurrent(tcur)) + Py_FatalError("This thread state must be current when releasing"); + assert(PyThreadState_IsCurrent(tcur)); + --tcur->gilstate_counter; + assert(tcur->gilstate_counter >= 0); /* illegal counter value */ + + /* If we're going to destroy this thread-state, we must + * clear it while the GIL is held, as destructors may run. + */ + if (tcur->gilstate_counter == 0) { + /* can't have been locked when we created it */ + assert(oldstate == PyGILState_UNLOCKED); + PyThreadState_Clear(tcur); + /* Delete the thread-state. Note this releases the GIL too! + * It's vital that the GIL be held here, to avoid shutdown + * races; see bugs 225673 and 1061968 (that nasty bug has a + * habit of coming back). + */ + PyThreadState_DeleteCurrent(); + } + /* Release the lock if necessary */ + else if (oldstate == PyGILState_UNLOCKED) + PyEval_SaveThread(); } #ifdef __cplusplus Modified: python/branches/py3k/Python/pystrcmp.c ============================================================================== --- python/branches/py3k/Python/pystrcmp.c (original) +++ python/branches/py3k/Python/pystrcmp.c Sun May 9 17:52:27 2010 @@ -6,21 +6,21 @@ int PyOS_mystrnicmp(const char *s1, const char *s2, Py_ssize_t size) { - if (size == 0) - return 0; - while ((--size > 0) && - (tolower((unsigned)*s1) == tolower((unsigned)*s2))) { - if (!*s1++ || !*s2++) - break; - } - return tolower((unsigned)*s1) - tolower((unsigned)*s2); + if (size == 0) + return 0; + while ((--size > 0) && + (tolower((unsigned)*s1) == tolower((unsigned)*s2))) { + if (!*s1++ || !*s2++) + break; + } + return tolower((unsigned)*s1) - tolower((unsigned)*s2); } int PyOS_mystricmp(const char *s1, const char *s2) { - while (*s1 && (tolower((unsigned)*s1++) == tolower((unsigned)*s2++))) { - ; - } - return (tolower((unsigned)*s1) - tolower((unsigned)*s2)); + while (*s1 && (tolower((unsigned)*s1++) == tolower((unsigned)*s2++))) { + ; + } + return (tolower((unsigned)*s1) - tolower((unsigned)*s2)); } Modified: python/branches/py3k/Python/pystrtod.c ============================================================================== --- python/branches/py3k/Python/pystrtod.c (original) +++ python/branches/py3k/Python/pystrtod.c Sun May 9 17:52:27 2010 @@ -9,11 +9,11 @@ static int case_insensitive_match(const char *s, const char *t) { - while(*t && Py_TOLOWER(*s) == *t) { - s++; - t++; - } - return *t ? 0 : 1; + while(*t && Py_TOLOWER(*s) == *t) { + s++; + t++; + } + return *t ? 0 : 1; } /* _Py_parse_inf_or_nan: Attempt to parse a string of the form "nan", "inf" or @@ -25,36 +25,36 @@ double _Py_parse_inf_or_nan(const char *p, char **endptr) { - double retval; - const char *s; - int negate = 0; - - s = p; - if (*s == '-') { - negate = 1; - s++; - } - else if (*s == '+') { - s++; - } - if (case_insensitive_match(s, "inf")) { - s += 3; - if (case_insensitive_match(s, "inity")) - s += 5; - retval = negate ? -Py_HUGE_VAL : Py_HUGE_VAL; - } + double retval; + const char *s; + int negate = 0; + + s = p; + if (*s == '-') { + negate = 1; + s++; + } + else if (*s == '+') { + s++; + } + if (case_insensitive_match(s, "inf")) { + s += 3; + if (case_insensitive_match(s, "inity")) + s += 5; + retval = negate ? -Py_HUGE_VAL : Py_HUGE_VAL; + } #ifdef Py_NAN - else if (case_insensitive_match(s, "nan")) { - s += 3; - retval = negate ? -Py_NAN : Py_NAN; - } + else if (case_insensitive_match(s, "nan")) { + s += 3; + retval = negate ? -Py_NAN : Py_NAN; + } #endif - else { - s = p; - retval = -1.0; - } - *endptr = (char *)s; - return retval; + else { + s = p; + retval = -1.0; + } + *endptr = (char *)s; + return retval; } /** @@ -62,7 +62,7 @@ * @nptr: the string to convert to a numeric value. * @endptr: if non-%NULL, it returns the character after * the last character used in the conversion. - * + * * Converts a string to a #gdouble value. * This function behaves like the standard strtod() function * does in the C locale. It does this without actually @@ -79,7 +79,7 @@ * stored in %errno. If the correct value would cause underflow, * zero is returned and %ERANGE is stored in %errno. * If memory allocation fails, %ENOMEM is stored in %errno. - * + * * This function resets %errno before calling strtod() so that * you can reliably detect overflow and underflow. * @@ -91,23 +91,23 @@ static double _PyOS_ascii_strtod(const char *nptr, char **endptr) { - double result; - _Py_SET_53BIT_PRECISION_HEADER; + double result; + _Py_SET_53BIT_PRECISION_HEADER; - assert(nptr != NULL); - /* Set errno to zero, so that we can distinguish zero results - and underflows */ - errno = 0; - - _Py_SET_53BIT_PRECISION_START; - result = _Py_dg_strtod(nptr, endptr); - _Py_SET_53BIT_PRECISION_END; - - if (*endptr == nptr) - /* string might represent an inf or nan */ - result = _Py_parse_inf_or_nan(nptr, endptr); + assert(nptr != NULL); + /* Set errno to zero, so that we can distinguish zero results + and underflows */ + errno = 0; + + _Py_SET_53BIT_PRECISION_START; + result = _Py_dg_strtod(nptr, endptr); + _Py_SET_53BIT_PRECISION_END; + + if (*endptr == nptr) + /* string might represent an inf or nan */ + result = _Py_parse_inf_or_nan(nptr, endptr); - return result; + return result; } @@ -124,148 +124,148 @@ static double _PyOS_ascii_strtod(const char *nptr, char **endptr) { - char *fail_pos; - double val = -1.0; - struct lconv *locale_data; - const char *decimal_point; - size_t decimal_point_len; - const char *p, *decimal_point_pos; - const char *end = NULL; /* Silence gcc */ - const char *digits_pos = NULL; - int negate = 0; - - assert(nptr != NULL); - - fail_pos = NULL; - - locale_data = localeconv(); - decimal_point = locale_data->decimal_point; - decimal_point_len = strlen(decimal_point); - - assert(decimal_point_len != 0); - - decimal_point_pos = NULL; - - /* Parse infinities and nans */ - val = _Py_parse_inf_or_nan(nptr, endptr); - if (*endptr != nptr) - return val; - - /* Set errno to zero, so that we can distinguish zero results - and underflows */ - errno = 0; - - /* We process the optional sign manually, then pass the remainder to - the system strtod. This ensures that the result of an underflow - has the correct sign. (bug #1725) */ - p = nptr; - /* Process leading sign, if present */ - if (*p == '-') { - negate = 1; - p++; - } - else if (*p == '+') { - p++; - } - - /* Some platform strtods accept hex floats; Python shouldn't (at the - moment), so we check explicitly for strings starting with '0x'. */ - if (*p == '0' && (*(p+1) == 'x' || *(p+1) == 'X')) - goto invalid_string; - - /* Check that what's left begins with a digit or decimal point */ - if (!Py_ISDIGIT(*p) && *p != '.') - goto invalid_string; - - digits_pos = p; - if (decimal_point[0] != '.' || - decimal_point[1] != 0) - { - /* Look for a '.' in the input; if present, it'll need to be - swapped for the current locale's decimal point before we - call strtod. On the other hand, if we find the current - locale's decimal point then the input is invalid. */ - while (Py_ISDIGIT(*p)) - p++; - - if (*p == '.') - { - decimal_point_pos = p++; - - /* locate end of number */ - while (Py_ISDIGIT(*p)) - p++; - - if (*p == 'e' || *p == 'E') - p++; - if (*p == '+' || *p == '-') - p++; - while (Py_ISDIGIT(*p)) - p++; - end = p; - } - else if (strncmp(p, decimal_point, decimal_point_len) == 0) - /* Python bug #1417699 */ - goto invalid_string; - /* For the other cases, we need not convert the decimal - point */ - } - - if (decimal_point_pos) { - char *copy, *c; - /* Create a copy of the input, with the '.' converted to the - locale-specific decimal point */ - copy = (char *)PyMem_MALLOC(end - digits_pos + - 1 + decimal_point_len); - if (copy == NULL) { - *endptr = (char *)nptr; - errno = ENOMEM; - return val; - } - - c = copy; - memcpy(c, digits_pos, decimal_point_pos - digits_pos); - c += decimal_point_pos - digits_pos; - memcpy(c, decimal_point, decimal_point_len); - c += decimal_point_len; - memcpy(c, decimal_point_pos + 1, - end - (decimal_point_pos + 1)); - c += end - (decimal_point_pos + 1); - *c = 0; - - val = strtod(copy, &fail_pos); - - if (fail_pos) - { - if (fail_pos > decimal_point_pos) - fail_pos = (char *)digits_pos + - (fail_pos - copy) - - (decimal_point_len - 1); - else - fail_pos = (char *)digits_pos + - (fail_pos - copy); - } - - PyMem_FREE(copy); - - } - else { - val = strtod(digits_pos, &fail_pos); - } - - if (fail_pos == digits_pos) - goto invalid_string; - - if (negate && fail_pos != nptr) - val = -val; - *endptr = fail_pos; + char *fail_pos; + double val = -1.0; + struct lconv *locale_data; + const char *decimal_point; + size_t decimal_point_len; + const char *p, *decimal_point_pos; + const char *end = NULL; /* Silence gcc */ + const char *digits_pos = NULL; + int negate = 0; + + assert(nptr != NULL); + + fail_pos = NULL; + + locale_data = localeconv(); + decimal_point = locale_data->decimal_point; + decimal_point_len = strlen(decimal_point); + + assert(decimal_point_len != 0); + + decimal_point_pos = NULL; + + /* Parse infinities and nans */ + val = _Py_parse_inf_or_nan(nptr, endptr); + if (*endptr != nptr) + return val; + + /* Set errno to zero, so that we can distinguish zero results + and underflows */ + errno = 0; + + /* We process the optional sign manually, then pass the remainder to + the system strtod. This ensures that the result of an underflow + has the correct sign. (bug #1725) */ + p = nptr; + /* Process leading sign, if present */ + if (*p == '-') { + negate = 1; + p++; + } + else if (*p == '+') { + p++; + } + + /* Some platform strtods accept hex floats; Python shouldn't (at the + moment), so we check explicitly for strings starting with '0x'. */ + if (*p == '0' && (*(p+1) == 'x' || *(p+1) == 'X')) + goto invalid_string; + + /* Check that what's left begins with a digit or decimal point */ + if (!Py_ISDIGIT(*p) && *p != '.') + goto invalid_string; + + digits_pos = p; + if (decimal_point[0] != '.' || + decimal_point[1] != 0) + { + /* Look for a '.' in the input; if present, it'll need to be + swapped for the current locale's decimal point before we + call strtod. On the other hand, if we find the current + locale's decimal point then the input is invalid. */ + while (Py_ISDIGIT(*p)) + p++; + + if (*p == '.') + { + decimal_point_pos = p++; + + /* locate end of number */ + while (Py_ISDIGIT(*p)) + p++; + + if (*p == 'e' || *p == 'E') + p++; + if (*p == '+' || *p == '-') + p++; + while (Py_ISDIGIT(*p)) + p++; + end = p; + } + else if (strncmp(p, decimal_point, decimal_point_len) == 0) + /* Python bug #1417699 */ + goto invalid_string; + /* For the other cases, we need not convert the decimal + point */ + } + + if (decimal_point_pos) { + char *copy, *c; + /* Create a copy of the input, with the '.' converted to the + locale-specific decimal point */ + copy = (char *)PyMem_MALLOC(end - digits_pos + + 1 + decimal_point_len); + if (copy == NULL) { + *endptr = (char *)nptr; + errno = ENOMEM; + return val; + } + + c = copy; + memcpy(c, digits_pos, decimal_point_pos - digits_pos); + c += decimal_point_pos - digits_pos; + memcpy(c, decimal_point, decimal_point_len); + c += decimal_point_len; + memcpy(c, decimal_point_pos + 1, + end - (decimal_point_pos + 1)); + c += end - (decimal_point_pos + 1); + *c = 0; + + val = strtod(copy, &fail_pos); + + if (fail_pos) + { + if (fail_pos > decimal_point_pos) + fail_pos = (char *)digits_pos + + (fail_pos - copy) - + (decimal_point_len - 1); + else + fail_pos = (char *)digits_pos + + (fail_pos - copy); + } + + PyMem_FREE(copy); + + } + else { + val = strtod(digits_pos, &fail_pos); + } + + if (fail_pos == digits_pos) + goto invalid_string; + + if (negate && fail_pos != nptr) + val = -val; + *endptr = fail_pos; - return val; + return val; invalid_string: - *endptr = (char*)nptr; - errno = EINVAL; - return -1.0; + *endptr = (char*)nptr; + errno = EINVAL; + return -1.0; } #endif @@ -296,39 +296,39 @@ double PyOS_string_to_double(const char *s, - char **endptr, - PyObject *overflow_exception) + char **endptr, + PyObject *overflow_exception) { - double x, result=-1.0; - char *fail_pos; + double x, result=-1.0; + char *fail_pos; - errno = 0; - PyFPE_START_PROTECT("PyOS_string_to_double", return -1.0) - x = _PyOS_ascii_strtod(s, &fail_pos); - PyFPE_END_PROTECT(x) - - if (errno == ENOMEM) { - PyErr_NoMemory(); - fail_pos = (char *)s; - } - else if (!endptr && (fail_pos == s || *fail_pos != '\0')) - PyErr_Format(PyExc_ValueError, - "could not convert string to float: " - "%.200s", s); - else if (fail_pos == s) - PyErr_Format(PyExc_ValueError, - "could not convert string to float: " - "%.200s", s); - else if (errno == ERANGE && fabs(x) >= 1.0 && overflow_exception) - PyErr_Format(overflow_exception, - "value too large to convert to float: " - "%.200s", s); - else - result = x; - - if (endptr != NULL) - *endptr = fail_pos; - return result; + errno = 0; + PyFPE_START_PROTECT("PyOS_string_to_double", return -1.0) + x = _PyOS_ascii_strtod(s, &fail_pos); + PyFPE_END_PROTECT(x) + + if (errno == ENOMEM) { + PyErr_NoMemory(); + fail_pos = (char *)s; + } + else if (!endptr && (fail_pos == s || *fail_pos != '\0')) + PyErr_Format(PyExc_ValueError, + "could not convert string to float: " + "%.200s", s); + else if (fail_pos == s) + PyErr_Format(PyExc_ValueError, + "could not convert string to float: " + "%.200s", s); + else if (errno == ERANGE && fabs(x) >= 1.0 && overflow_exception) + PyErr_Format(overflow_exception, + "value too large to convert to float: " + "%.200s", s); + else + result = x; + + if (endptr != NULL) + *endptr = fail_pos; + return result; } #ifdef PY_NO_SHORT_FLOAT_REPR @@ -339,30 +339,30 @@ Py_LOCAL_INLINE(void) change_decimal_from_locale_to_dot(char* buffer) { - struct lconv *locale_data = localeconv(); - const char *decimal_point = locale_data->decimal_point; + struct lconv *locale_data = localeconv(); + const char *decimal_point = locale_data->decimal_point; - if (decimal_point[0] != '.' || decimal_point[1] != 0) { - size_t decimal_point_len = strlen(decimal_point); + if (decimal_point[0] != '.' || decimal_point[1] != 0) { + size_t decimal_point_len = strlen(decimal_point); - if (*buffer == '+' || *buffer == '-') - buffer++; - while (Py_ISDIGIT(*buffer)) - buffer++; - if (strncmp(buffer, decimal_point, decimal_point_len) == 0) { - *buffer = '.'; - buffer++; - if (decimal_point_len > 1) { - /* buffer needs to get smaller */ - size_t rest_len = strlen(buffer + - (decimal_point_len - 1)); - memmove(buffer, - buffer + (decimal_point_len - 1), - rest_len); - buffer[rest_len] = 0; - } - } - } + if (*buffer == '+' || *buffer == '-') + buffer++; + while (Py_ISDIGIT(*buffer)) + buffer++; + if (strncmp(buffer, decimal_point, decimal_point_len) == 0) { + *buffer = '.'; + buffer++; + if (decimal_point_len > 1) { + /* buffer needs to get smaller */ + size_t rest_len = strlen(buffer + + (decimal_point_len - 1)); + memmove(buffer, + buffer + (decimal_point_len - 1), + rest_len); + buffer[rest_len] = 0; + } + } + } } @@ -377,65 +377,65 @@ Py_LOCAL_INLINE(void) ensure_minimum_exponent_length(char* buffer, size_t buf_size) { - char *p = strpbrk(buffer, "eE"); - if (p && (*(p + 1) == '-' || *(p + 1) == '+')) { - char *start = p + 2; - int exponent_digit_cnt = 0; - int leading_zero_cnt = 0; - int in_leading_zeros = 1; - int significant_digit_cnt; - - /* Skip over the exponent and the sign. */ - p += 2; - - /* Find the end of the exponent, keeping track of leading - zeros. */ - while (*p && Py_ISDIGIT(*p)) { - if (in_leading_zeros && *p == '0') - ++leading_zero_cnt; - if (*p != '0') - in_leading_zeros = 0; - ++p; - ++exponent_digit_cnt; - } - - significant_digit_cnt = exponent_digit_cnt - leading_zero_cnt; - if (exponent_digit_cnt == MIN_EXPONENT_DIGITS) { - /* If there are 2 exactly digits, we're done, - regardless of what they contain */ - } - else if (exponent_digit_cnt > MIN_EXPONENT_DIGITS) { - int extra_zeros_cnt; - - /* There are more than 2 digits in the exponent. See - if we can delete some of the leading zeros */ - if (significant_digit_cnt < MIN_EXPONENT_DIGITS) - significant_digit_cnt = MIN_EXPONENT_DIGITS; - extra_zeros_cnt = exponent_digit_cnt - - significant_digit_cnt; - - /* Delete extra_zeros_cnt worth of characters from the - front of the exponent */ - assert(extra_zeros_cnt >= 0); - - /* Add one to significant_digit_cnt to copy the - trailing 0 byte, thus setting the length */ - memmove(start, - start + extra_zeros_cnt, - significant_digit_cnt + 1); - } - else { - /* If there are fewer than 2 digits, add zeros - until there are 2, if there's enough room */ - int zeros = MIN_EXPONENT_DIGITS - exponent_digit_cnt; - if (start + zeros + exponent_digit_cnt + 1 - < buffer + buf_size) { - memmove(start + zeros, start, - exponent_digit_cnt + 1); - memset(start, '0', zeros); - } - } - } + char *p = strpbrk(buffer, "eE"); + if (p && (*(p + 1) == '-' || *(p + 1) == '+')) { + char *start = p + 2; + int exponent_digit_cnt = 0; + int leading_zero_cnt = 0; + int in_leading_zeros = 1; + int significant_digit_cnt; + + /* Skip over the exponent and the sign. */ + p += 2; + + /* Find the end of the exponent, keeping track of leading + zeros. */ + while (*p && Py_ISDIGIT(*p)) { + if (in_leading_zeros && *p == '0') + ++leading_zero_cnt; + if (*p != '0') + in_leading_zeros = 0; + ++p; + ++exponent_digit_cnt; + } + + significant_digit_cnt = exponent_digit_cnt - leading_zero_cnt; + if (exponent_digit_cnt == MIN_EXPONENT_DIGITS) { + /* If there are 2 exactly digits, we're done, + regardless of what they contain */ + } + else if (exponent_digit_cnt > MIN_EXPONENT_DIGITS) { + int extra_zeros_cnt; + + /* There are more than 2 digits in the exponent. See + if we can delete some of the leading zeros */ + if (significant_digit_cnt < MIN_EXPONENT_DIGITS) + significant_digit_cnt = MIN_EXPONENT_DIGITS; + extra_zeros_cnt = exponent_digit_cnt - + significant_digit_cnt; + + /* Delete extra_zeros_cnt worth of characters from the + front of the exponent */ + assert(extra_zeros_cnt >= 0); + + /* Add one to significant_digit_cnt to copy the + trailing 0 byte, thus setting the length */ + memmove(start, + start + extra_zeros_cnt, + significant_digit_cnt + 1); + } + else { + /* If there are fewer than 2 digits, add zeros + until there are 2, if there's enough room */ + int zeros = MIN_EXPONENT_DIGITS - exponent_digit_cnt; + if (start + zeros + exponent_digit_cnt + 1 + < buffer + buf_size) { + memmove(start + zeros, start, + exponent_digit_cnt + 1); + memset(start, '0', zeros); + } + } + } } /* Remove trailing zeros after the decimal point from a numeric string; also @@ -445,40 +445,40 @@ Py_LOCAL_INLINE(void) remove_trailing_zeros(char *buffer) { - char *old_fraction_end, *new_fraction_end, *end, *p; + char *old_fraction_end, *new_fraction_end, *end, *p; - p = buffer; - if (*p == '-' || *p == '+') - /* Skip leading sign, if present */ - ++p; - while (Py_ISDIGIT(*p)) - ++p; - - /* if there's no decimal point there's nothing to do */ - if (*p++ != '.') - return; - - /* scan any digits after the point */ - while (Py_ISDIGIT(*p)) - ++p; - old_fraction_end = p; - - /* scan up to ending '\0' */ - while (*p != '\0') - p++; - /* +1 to make sure that we move the null byte as well */ - end = p+1; - - /* scan back from fraction_end, looking for removable zeros */ - p = old_fraction_end; - while (*(p-1) == '0') - --p; - /* and remove point if we've got that far */ - if (*(p-1) == '.') - --p; - new_fraction_end = p; + p = buffer; + if (*p == '-' || *p == '+') + /* Skip leading sign, if present */ + ++p; + while (Py_ISDIGIT(*p)) + ++p; + + /* if there's no decimal point there's nothing to do */ + if (*p++ != '.') + return; + + /* scan any digits after the point */ + while (Py_ISDIGIT(*p)) + ++p; + old_fraction_end = p; + + /* scan up to ending '\0' */ + while (*p != '\0') + p++; + /* +1 to make sure that we move the null byte as well */ + end = p+1; + + /* scan back from fraction_end, looking for removable zeros */ + p = old_fraction_end; + while (*(p-1) == '0') + --p; + /* and remove point if we've got that far */ + if (*(p-1) == '.') + --p; + new_fraction_end = p; - memmove(new_fraction_end, old_fraction_end, end-old_fraction_end); + memmove(new_fraction_end, old_fraction_end, end-old_fraction_end); } /* Ensure that buffer has a decimal point in it. The decimal point will not @@ -491,91 +491,91 @@ Py_LOCAL_INLINE(char *) ensure_decimal_point(char* buffer, size_t buf_size, int precision) { - int digit_count, insert_count = 0, convert_to_exp = 0; - char *chars_to_insert, *digits_start; + int digit_count, insert_count = 0, convert_to_exp = 0; + char *chars_to_insert, *digits_start; - /* search for the first non-digit character */ - char *p = buffer; - if (*p == '-' || *p == '+') - /* Skip leading sign, if present. I think this could only - ever be '-', but it can't hurt to check for both. */ - ++p; - digits_start = p; - while (*p && Py_ISDIGIT(*p)) - ++p; - digit_count = Py_SAFE_DOWNCAST(p - digits_start, Py_ssize_t, int); - - if (*p == '.') { - if (Py_ISDIGIT(*(p+1))) { - /* Nothing to do, we already have a decimal - point and a digit after it */ - } - else { - /* We have a decimal point, but no following - digit. Insert a zero after the decimal. */ - /* can't ever get here via PyOS_double_to_string */ - assert(precision == -1); - ++p; - chars_to_insert = "0"; - insert_count = 1; - } - } - else if (!(*p == 'e' || *p == 'E')) { - /* Don't add ".0" if we have an exponent. */ - if (digit_count == precision) { - /* issue 5864: don't add a trailing .0 in the case - where the '%g'-formatted result already has as many - significant digits as were requested. Switch to - exponential notation instead. */ - convert_to_exp = 1; - /* no exponent, no point, and we shouldn't land here - for infs and nans, so we must be at the end of the - string. */ - assert(*p == '\0'); - } - else { - assert(precision == -1 || digit_count < precision); - chars_to_insert = ".0"; - insert_count = 2; - } - } - if (insert_count) { - size_t buf_len = strlen(buffer); - if (buf_len + insert_count + 1 >= buf_size) { - /* If there is not enough room in the buffer - for the additional text, just skip it. It's - not worth generating an error over. */ - } - else { - memmove(p + insert_count, p, - buffer + strlen(buffer) - p + 1); - memcpy(p, chars_to_insert, insert_count); - } - } - if (convert_to_exp) { - int written; - size_t buf_avail; - p = digits_start; - /* insert decimal point */ - assert(digit_count >= 1); - memmove(p+2, p+1, digit_count); /* safe, but overwrites nul */ - p[1] = '.'; - p += digit_count+1; - assert(p <= buf_size+buffer); - buf_avail = buf_size+buffer-p; - if (buf_avail == 0) - return NULL; - /* Add exponent. It's okay to use lower case 'e': we only - arrive here as a result of using the empty format code or - repr/str builtins and those never want an upper case 'E' */ - written = PyOS_snprintf(p, buf_avail, "e%+.02d", digit_count-1); - if (!(0 <= written && - written < Py_SAFE_DOWNCAST(buf_avail, size_t, int))) - /* output truncated, or something else bad happened */ - return NULL; - remove_trailing_zeros(buffer); - } - return buffer; + /* search for the first non-digit character */ + char *p = buffer; + if (*p == '-' || *p == '+') + /* Skip leading sign, if present. I think this could only + ever be '-', but it can't hurt to check for both. */ + ++p; + digits_start = p; + while (*p && Py_ISDIGIT(*p)) + ++p; + digit_count = Py_SAFE_DOWNCAST(p - digits_start, Py_ssize_t, int); + + if (*p == '.') { + if (Py_ISDIGIT(*(p+1))) { + /* Nothing to do, we already have a decimal + point and a digit after it */ + } + else { + /* We have a decimal point, but no following + digit. Insert a zero after the decimal. */ + /* can't ever get here via PyOS_double_to_string */ + assert(precision == -1); + ++p; + chars_to_insert = "0"; + insert_count = 1; + } + } + else if (!(*p == 'e' || *p == 'E')) { + /* Don't add ".0" if we have an exponent. */ + if (digit_count == precision) { + /* issue 5864: don't add a trailing .0 in the case + where the '%g'-formatted result already has as many + significant digits as were requested. Switch to + exponential notation instead. */ + convert_to_exp = 1; + /* no exponent, no point, and we shouldn't land here + for infs and nans, so we must be at the end of the + string. */ + assert(*p == '\0'); + } + else { + assert(precision == -1 || digit_count < precision); + chars_to_insert = ".0"; + insert_count = 2; + } + } + if (insert_count) { + size_t buf_len = strlen(buffer); + if (buf_len + insert_count + 1 >= buf_size) { + /* If there is not enough room in the buffer + for the additional text, just skip it. It's + not worth generating an error over. */ + } + else { + memmove(p + insert_count, p, + buffer + strlen(buffer) - p + 1); + memcpy(p, chars_to_insert, insert_count); + } + } + if (convert_to_exp) { + int written; + size_t buf_avail; + p = digits_start; + /* insert decimal point */ + assert(digit_count >= 1); + memmove(p+2, p+1, digit_count); /* safe, but overwrites nul */ + p[1] = '.'; + p += digit_count+1; + assert(p <= buf_size+buffer); + buf_avail = buf_size+buffer-p; + if (buf_avail == 0) + return NULL; + /* Add exponent. It's okay to use lower case 'e': we only + arrive here as a result of using the empty format code or + repr/str builtins and those never want an upper case 'E' */ + written = PyOS_snprintf(p, buf_avail, "e%+.02d", digit_count-1); + if (!(0 <= written && + written < Py_SAFE_DOWNCAST(buf_avail, size_t, int))) + /* output truncated, or something else bad happened */ + return NULL; + remove_trailing_zeros(buffer); + } + return buffer; } /* see FORMATBUFLEN in unicodeobject.c */ @@ -586,7 +586,7 @@ * @buffer: A buffer to place the resulting string in * @buf_size: The length of the buffer. * @format: The printf()-style format to use for the - * code to use for converting. + * code to use for converting. * @d: The #gdouble to convert * @precision: The precision to use when formatting. * @@ -594,7 +594,7 @@ * decimal point. To format the number you pass in * a printf()-style format string. Allowed conversion * specifiers are 'e', 'E', 'f', 'F', 'g', 'G', and 'Z'. - * + * * 'Z' is the same as 'g', except it always has a decimal and * at least one digit after the decimal. * @@ -602,83 +602,83 @@ * On failure returns NULL but does not set any Python exception. **/ static char * -_PyOS_ascii_formatd(char *buffer, - size_t buf_size, - const char *format, - double d, - int precision) +_PyOS_ascii_formatd(char *buffer, + size_t buf_size, + const char *format, + double d, + int precision) { - char format_char; - size_t format_len = strlen(format); + char format_char; + size_t format_len = strlen(format); - /* Issue 2264: code 'Z' requires copying the format. 'Z' is 'g', but - also with at least one character past the decimal. */ - char tmp_format[FLOAT_FORMATBUFLEN]; - - /* The last character in the format string must be the format char */ - format_char = format[format_len - 1]; - - if (format[0] != '%') - return NULL; - - /* I'm not sure why this test is here. It's ensuring that the format - string after the first character doesn't have a single quote, a - lowercase l, or a percent. This is the reverse of the commented-out - test about 10 lines ago. */ - if (strpbrk(format + 1, "'l%")) - return NULL; - - /* Also curious about this function is that it accepts format strings - like "%xg", which are invalid for floats. In general, the - interface to this function is not very good, but changing it is - difficult because it's a public API. */ - - if (!(format_char == 'e' || format_char == 'E' || - format_char == 'f' || format_char == 'F' || - format_char == 'g' || format_char == 'G' || - format_char == 'Z')) - return NULL; - - /* Map 'Z' format_char to 'g', by copying the format string and - replacing the final char with a 'g' */ - if (format_char == 'Z') { - if (format_len + 1 >= sizeof(tmp_format)) { - /* The format won't fit in our copy. Error out. In - practice, this will never happen and will be - detected by returning NULL */ - return NULL; - } - strcpy(tmp_format, format); - tmp_format[format_len - 1] = 'g'; - format = tmp_format; - } - - - /* Have PyOS_snprintf do the hard work */ - PyOS_snprintf(buffer, buf_size, format, d); - - /* Do various fixups on the return string */ - - /* Get the current locale, and find the decimal point string. - Convert that string back to a dot. */ - change_decimal_from_locale_to_dot(buffer); - - /* If an exponent exists, ensure that the exponent is at least - MIN_EXPONENT_DIGITS digits, providing the buffer is large enough - for the extra zeros. Also, if there are more than - MIN_EXPONENT_DIGITS, remove as many zeros as possible until we get - back to MIN_EXPONENT_DIGITS */ - ensure_minimum_exponent_length(buffer, buf_size); - - /* If format_char is 'Z', make sure we have at least one character - after the decimal point (and make sure we have a decimal point); - also switch to exponential notation in some edge cases where the - extra character would produce more significant digits that we - really want. */ - if (format_char == 'Z') - buffer = ensure_decimal_point(buffer, buf_size, precision); + /* Issue 2264: code 'Z' requires copying the format. 'Z' is 'g', but + also with at least one character past the decimal. */ + char tmp_format[FLOAT_FORMATBUFLEN]; + + /* The last character in the format string must be the format char */ + format_char = format[format_len - 1]; + + if (format[0] != '%') + return NULL; + + /* I'm not sure why this test is here. It's ensuring that the format + string after the first character doesn't have a single quote, a + lowercase l, or a percent. This is the reverse of the commented-out + test about 10 lines ago. */ + if (strpbrk(format + 1, "'l%")) + return NULL; + + /* Also curious about this function is that it accepts format strings + like "%xg", which are invalid for floats. In general, the + interface to this function is not very good, but changing it is + difficult because it's a public API. */ + + if (!(format_char == 'e' || format_char == 'E' || + format_char == 'f' || format_char == 'F' || + format_char == 'g' || format_char == 'G' || + format_char == 'Z')) + return NULL; + + /* Map 'Z' format_char to 'g', by copying the format string and + replacing the final char with a 'g' */ + if (format_char == 'Z') { + if (format_len + 1 >= sizeof(tmp_format)) { + /* The format won't fit in our copy. Error out. In + practice, this will never happen and will be + detected by returning NULL */ + return NULL; + } + strcpy(tmp_format, format); + tmp_format[format_len - 1] = 'g'; + format = tmp_format; + } + + + /* Have PyOS_snprintf do the hard work */ + PyOS_snprintf(buffer, buf_size, format, d); + + /* Do various fixups on the return string */ + + /* Get the current locale, and find the decimal point string. + Convert that string back to a dot. */ + change_decimal_from_locale_to_dot(buffer); + + /* If an exponent exists, ensure that the exponent is at least + MIN_EXPONENT_DIGITS digits, providing the buffer is large enough + for the extra zeros. Also, if there are more than + MIN_EXPONENT_DIGITS, remove as many zeros as possible until we get + back to MIN_EXPONENT_DIGITS */ + ensure_minimum_exponent_length(buffer, buf_size); + + /* If format_char is 'Z', make sure we have at least one character + after the decimal point (and make sure we have a decimal point); + also switch to exponential notation in some edge cases where the + extra character would produce more significant digits that we + really want. */ + if (format_char == 'Z') + buffer = ensure_decimal_point(buffer, buf_size, precision); - return buffer; + return buffer; } /* The fallback code to use if _Py_dg_dtoa is not available. */ @@ -689,146 +689,146 @@ int flags, int *type) { - char format[32]; - Py_ssize_t bufsize; - char *buf; - int t, exp; - int upper = 0; - - /* Validate format_code, and map upper and lower case */ - switch (format_code) { - case 'e': /* exponent */ - case 'f': /* fixed */ - case 'g': /* general */ - break; - case 'E': - upper = 1; - format_code = 'e'; - break; - case 'F': - upper = 1; - format_code = 'f'; - break; - case 'G': - upper = 1; - format_code = 'g'; - break; - case 'r': /* repr format */ - /* Supplied precision is unused, must be 0. */ - if (precision != 0) { - PyErr_BadInternalCall(); - return NULL; - } - /* The repr() precision (17 significant decimal digits) is the - minimal number that is guaranteed to have enough precision - so that if the number is read back in the exact same binary - value is recreated. This is true for IEEE floating point - by design, and also happens to work for all other modern - hardware. */ - precision = 17; - format_code = 'g'; - break; - default: - PyErr_BadInternalCall(); - return NULL; - } - - /* Here's a quick-and-dirty calculation to figure out how big a buffer - we need. In general, for a finite float we need: - - 1 byte for each digit of the decimal significand, and - - 1 for a possible sign - 1 for a possible decimal point - 2 for a possible [eE][+-] - 1 for each digit of the exponent; if we allow 19 digits - total then we're safe up to exponents of 2**63. - 1 for the trailing nul byte - - This gives a total of 24 + the number of digits in the significand, - and the number of digits in the significand is: - - for 'g' format: at most precision, except possibly - when precision == 0, when it's 1. - for 'e' format: precision+1 - for 'f' format: precision digits after the point, at least 1 - before. To figure out how many digits appear before the point - we have to examine the size of the number. If fabs(val) < 1.0 - then there will be only one digit before the point. If - fabs(val) >= 1.0, then there are at most - - 1+floor(log10(ceiling(fabs(val)))) - - digits before the point (where the 'ceiling' allows for the - possibility that the rounding rounds the integer part of val - up). A safe upper bound for the above quantity is - 1+floor(exp/3), where exp is the unique integer such that 0.5 - <= fabs(val)/2**exp < 1.0. This exp can be obtained from - frexp. - - So we allow room for precision+1 digits for all formats, plus an - extra floor(exp/3) digits for 'f' format. - - */ - - if (Py_IS_NAN(val) || Py_IS_INFINITY(val)) - /* 3 for 'inf'/'nan', 1 for sign, 1 for '\0' */ - bufsize = 5; - else { - bufsize = 25 + precision; - if (format_code == 'f' && fabs(val) >= 1.0) { - frexp(val, &exp); - bufsize += exp/3; - } - } - - buf = PyMem_Malloc(bufsize); - if (buf == NULL) { - PyErr_NoMemory(); - return NULL; - } - - /* Handle nan and inf. */ - if (Py_IS_NAN(val)) { - strcpy(buf, "nan"); - t = Py_DTST_NAN; - } else if (Py_IS_INFINITY(val)) { - if (copysign(1., val) == 1.) - strcpy(buf, "inf"); - else - strcpy(buf, "-inf"); - t = Py_DTST_INFINITE; - } else { - t = Py_DTST_FINITE; - if (flags & Py_DTSF_ADD_DOT_0) - format_code = 'Z'; - - PyOS_snprintf(format, sizeof(format), "%%%s.%i%c", - (flags & Py_DTSF_ALT ? "#" : ""), precision, - format_code); - _PyOS_ascii_formatd(buf, bufsize, format, val, precision); - } - - /* Add sign when requested. It's convenient (esp. when formatting - complex numbers) to include a sign even for inf and nan. */ - if (flags & Py_DTSF_SIGN && buf[0] != '-') { - size_t len = strlen(buf); - /* the bufsize calculations above should ensure that we've got - space to add a sign */ - assert((size_t)bufsize >= len+2); - memmove(buf+1, buf, len+1); - buf[0] = '+'; - } - if (upper) { - /* Convert to upper case. */ - char *p1; - for (p1 = buf; *p1; p1++) - *p1 = Py_TOUPPER(*p1); - } - - if (type) - *type = t; - return buf; + char format[32]; + Py_ssize_t bufsize; + char *buf; + int t, exp; + int upper = 0; + + /* Validate format_code, and map upper and lower case */ + switch (format_code) { + case 'e': /* exponent */ + case 'f': /* fixed */ + case 'g': /* general */ + break; + case 'E': + upper = 1; + format_code = 'e'; + break; + case 'F': + upper = 1; + format_code = 'f'; + break; + case 'G': + upper = 1; + format_code = 'g'; + break; + case 'r': /* repr format */ + /* Supplied precision is unused, must be 0. */ + if (precision != 0) { + PyErr_BadInternalCall(); + return NULL; + } + /* The repr() precision (17 significant decimal digits) is the + minimal number that is guaranteed to have enough precision + so that if the number is read back in the exact same binary + value is recreated. This is true for IEEE floating point + by design, and also happens to work for all other modern + hardware. */ + precision = 17; + format_code = 'g'; + break; + default: + PyErr_BadInternalCall(); + return NULL; + } + + /* Here's a quick-and-dirty calculation to figure out how big a buffer + we need. In general, for a finite float we need: + + 1 byte for each digit of the decimal significand, and + + 1 for a possible sign + 1 for a possible decimal point + 2 for a possible [eE][+-] + 1 for each digit of the exponent; if we allow 19 digits + total then we're safe up to exponents of 2**63. + 1 for the trailing nul byte + + This gives a total of 24 + the number of digits in the significand, + and the number of digits in the significand is: + + for 'g' format: at most precision, except possibly + when precision == 0, when it's 1. + for 'e' format: precision+1 + for 'f' format: precision digits after the point, at least 1 + before. To figure out how many digits appear before the point + we have to examine the size of the number. If fabs(val) < 1.0 + then there will be only one digit before the point. If + fabs(val) >= 1.0, then there are at most + + 1+floor(log10(ceiling(fabs(val)))) + + digits before the point (where the 'ceiling' allows for the + possibility that the rounding rounds the integer part of val + up). A safe upper bound for the above quantity is + 1+floor(exp/3), where exp is the unique integer such that 0.5 + <= fabs(val)/2**exp < 1.0. This exp can be obtained from + frexp. + + So we allow room for precision+1 digits for all formats, plus an + extra floor(exp/3) digits for 'f' format. + + */ + + if (Py_IS_NAN(val) || Py_IS_INFINITY(val)) + /* 3 for 'inf'/'nan', 1 for sign, 1 for '\0' */ + bufsize = 5; + else { + bufsize = 25 + precision; + if (format_code == 'f' && fabs(val) >= 1.0) { + frexp(val, &exp); + bufsize += exp/3; + } + } + + buf = PyMem_Malloc(bufsize); + if (buf == NULL) { + PyErr_NoMemory(); + return NULL; + } + + /* Handle nan and inf. */ + if (Py_IS_NAN(val)) { + strcpy(buf, "nan"); + t = Py_DTST_NAN; + } else if (Py_IS_INFINITY(val)) { + if (copysign(1., val) == 1.) + strcpy(buf, "inf"); + else + strcpy(buf, "-inf"); + t = Py_DTST_INFINITE; + } else { + t = Py_DTST_FINITE; + if (flags & Py_DTSF_ADD_DOT_0) + format_code = 'Z'; + + PyOS_snprintf(format, sizeof(format), "%%%s.%i%c", + (flags & Py_DTSF_ALT ? "#" : ""), precision, + format_code); + _PyOS_ascii_formatd(buf, bufsize, format, val, precision); + } + + /* Add sign when requested. It's convenient (esp. when formatting + complex numbers) to include a sign even for inf and nan. */ + if (flags & Py_DTSF_SIGN && buf[0] != '-') { + size_t len = strlen(buf); + /* the bufsize calculations above should ensure that we've got + space to add a sign */ + assert((size_t)bufsize >= len+2); + memmove(buf+1, buf, len+1); + buf[0] = '+'; + } + if (upper) { + /* Convert to upper case. */ + char *p1; + for (p1 = buf; *p1; p1++) + *p1 = Py_TOUPPER(*p1); + } + + if (type) + *type = t; + return buf; } #else @@ -843,14 +843,14 @@ /* The lengths of these are known to the code below, so don't change them */ static char *lc_float_strings[] = { - "inf", - "nan", - "e", + "inf", + "nan", + "e", }; static char *uc_float_strings[] = { - "INF", - "NAN", - "E", + "INF", + "NAN", + "E", }; @@ -874,9 +874,9 @@ be nonzero. type, if non-NULL, will be set to one of these constants to identify the type of the 'd' argument: - Py_DTST_FINITE - Py_DTST_INFINITE - Py_DTST_NAN + Py_DTST_FINITE + Py_DTST_INFINITE + Py_DTST_NAN Returns a PyMem_Malloc'd block of memory containing the resulting string, or NULL on error. If NULL is returned, the Python error has been set. @@ -884,315 +884,315 @@ static char * format_float_short(double d, char format_code, - int mode, Py_ssize_t precision, - int always_add_sign, int add_dot_0_if_integer, - int use_alt_formatting, char **float_strings, int *type) + int mode, Py_ssize_t precision, + int always_add_sign, int add_dot_0_if_integer, + int use_alt_formatting, char **float_strings, int *type) { - char *buf = NULL; - char *p = NULL; - Py_ssize_t bufsize = 0; - char *digits, *digits_end; - int decpt_as_int, sign, exp_len, exp = 0, use_exp = 0; - Py_ssize_t decpt, digits_len, vdigits_start, vdigits_end; - _Py_SET_53BIT_PRECISION_HEADER; - - /* _Py_dg_dtoa returns a digit string (no decimal point or exponent). - Must be matched by a call to _Py_dg_freedtoa. */ - _Py_SET_53BIT_PRECISION_START; - digits = _Py_dg_dtoa(d, mode, precision, &decpt_as_int, &sign, - &digits_end); - _Py_SET_53BIT_PRECISION_END; - - decpt = (Py_ssize_t)decpt_as_int; - if (digits == NULL) { - /* The only failure mode is no memory. */ - PyErr_NoMemory(); - goto exit; - } - assert(digits_end != NULL && digits_end >= digits); - digits_len = digits_end - digits; - - if (digits_len && !Py_ISDIGIT(digits[0])) { - /* Infinities and nans here; adapt Gay's output, - so convert Infinity to inf and NaN to nan, and - ignore sign of nan. Then return. */ - - /* ignore the actual sign of a nan */ - if (digits[0] == 'n' || digits[0] == 'N') - sign = 0; - - /* We only need 5 bytes to hold the result "+inf\0" . */ - bufsize = 5; /* Used later in an assert. */ - buf = (char *)PyMem_Malloc(bufsize); - if (buf == NULL) { - PyErr_NoMemory(); - goto exit; - } - p = buf; - - if (sign == 1) { - *p++ = '-'; - } - else if (always_add_sign) { - *p++ = '+'; - } - if (digits[0] == 'i' || digits[0] == 'I') { - strncpy(p, float_strings[OFS_INF], 3); - p += 3; - - if (type) - *type = Py_DTST_INFINITE; - } - else if (digits[0] == 'n' || digits[0] == 'N') { - strncpy(p, float_strings[OFS_NAN], 3); - p += 3; - - if (type) - *type = Py_DTST_NAN; - } - else { - /* shouldn't get here: Gay's code should always return - something starting with a digit, an 'I', or 'N' */ - strncpy(p, "ERR", 3); - p += 3; - assert(0); - } - goto exit; - } - - /* The result must be finite (not inf or nan). */ - if (type) - *type = Py_DTST_FINITE; - - - /* We got digits back, format them. We may need to pad 'digits' - either on the left or right (or both) with extra zeros, so in - general the resulting string has the form - - [][] - - where either of the pieces could be empty, and there's a - decimal point that could appear either in or in the - leading or trailing . - - Imagine an infinite 'virtual' string vdigits, consisting of the - string 'digits' (starting at index 0) padded on both the left and - right with infinite strings of zeros. We want to output a slice - - vdigits[vdigits_start : vdigits_end] - - of this virtual string. Thus if vdigits_start < 0 then we'll end - up producing some leading zeros; if vdigits_end > digits_len there - will be trailing zeros in the output. The next section of code - determines whether to use an exponent or not, figures out the - position 'decpt' of the decimal point, and computes 'vdigits_start' - and 'vdigits_end'. */ - vdigits_end = digits_len; - switch (format_code) { - case 'e': - use_exp = 1; - vdigits_end = precision; - break; - case 'f': - vdigits_end = decpt + precision; - break; - case 'g': - if (decpt <= -4 || decpt > - (add_dot_0_if_integer ? precision-1 : precision)) - use_exp = 1; - if (use_alt_formatting) - vdigits_end = precision; - break; - case 'r': - /* convert to exponential format at 1e16. We used to convert - at 1e17, but that gives odd-looking results for some values - when a 16-digit 'shortest' repr is padded with bogus zeros. - For example, repr(2e16+8) would give 20000000000000010.0; - the true value is 20000000000000008.0. */ - if (decpt <= -4 || decpt > 16) - use_exp = 1; - break; - default: - PyErr_BadInternalCall(); - goto exit; - } - - /* if using an exponent, reset decimal point position to 1 and adjust - exponent accordingly.*/ - if (use_exp) { - exp = decpt - 1; - decpt = 1; - } - /* ensure vdigits_start < decpt <= vdigits_end, or vdigits_start < - decpt < vdigits_end if add_dot_0_if_integer and no exponent */ - vdigits_start = decpt <= 0 ? decpt-1 : 0; - if (!use_exp && add_dot_0_if_integer) - vdigits_end = vdigits_end > decpt ? vdigits_end : decpt + 1; - else - vdigits_end = vdigits_end > decpt ? vdigits_end : decpt; - - /* double check inequalities */ - assert(vdigits_start <= 0 && - 0 <= digits_len && - digits_len <= vdigits_end); - /* decimal point should be in (vdigits_start, vdigits_end] */ - assert(vdigits_start < decpt && decpt <= vdigits_end); - - /* Compute an upper bound how much memory we need. This might be a few - chars too long, but no big deal. */ - bufsize = - /* sign, decimal point and trailing 0 byte */ - 3 + - - /* total digit count (including zero padding on both sides) */ - (vdigits_end - vdigits_start) + - - /* exponent "e+100", max 3 numerical digits */ - (use_exp ? 5 : 0); - - /* Now allocate the memory and initialize p to point to the start of - it. */ - buf = (char *)PyMem_Malloc(bufsize); - if (buf == NULL) { - PyErr_NoMemory(); - goto exit; - } - p = buf; - - /* Add a negative sign if negative, and a plus sign if non-negative - and always_add_sign is true. */ - if (sign == 1) - *p++ = '-'; - else if (always_add_sign) - *p++ = '+'; - - /* note that exactly one of the three 'if' conditions is true, - so we include exactly one decimal point */ - /* Zero padding on left of digit string */ - if (decpt <= 0) { - memset(p, '0', decpt-vdigits_start); - p += decpt - vdigits_start; - *p++ = '.'; - memset(p, '0', 0-decpt); - p += 0-decpt; - } - else { - memset(p, '0', 0-vdigits_start); - p += 0 - vdigits_start; - } - - /* Digits, with included decimal point */ - if (0 < decpt && decpt <= digits_len) { - strncpy(p, digits, decpt-0); - p += decpt-0; - *p++ = '.'; - strncpy(p, digits+decpt, digits_len-decpt); - p += digits_len-decpt; - } - else { - strncpy(p, digits, digits_len); - p += digits_len; - } - - /* And zeros on the right */ - if (digits_len < decpt) { - memset(p, '0', decpt-digits_len); - p += decpt-digits_len; - *p++ = '.'; - memset(p, '0', vdigits_end-decpt); - p += vdigits_end-decpt; - } - else { - memset(p, '0', vdigits_end-digits_len); - p += vdigits_end-digits_len; - } - - /* Delete a trailing decimal pt unless using alternative formatting. */ - if (p[-1] == '.' && !use_alt_formatting) - p--; - - /* Now that we've done zero padding, add an exponent if needed. */ - if (use_exp) { - *p++ = float_strings[OFS_E][0]; - exp_len = sprintf(p, "%+.02d", exp); - p += exp_len; - } + char *buf = NULL; + char *p = NULL; + Py_ssize_t bufsize = 0; + char *digits, *digits_end; + int decpt_as_int, sign, exp_len, exp = 0, use_exp = 0; + Py_ssize_t decpt, digits_len, vdigits_start, vdigits_end; + _Py_SET_53BIT_PRECISION_HEADER; + + /* _Py_dg_dtoa returns a digit string (no decimal point or exponent). + Must be matched by a call to _Py_dg_freedtoa. */ + _Py_SET_53BIT_PRECISION_START; + digits = _Py_dg_dtoa(d, mode, precision, &decpt_as_int, &sign, + &digits_end); + _Py_SET_53BIT_PRECISION_END; + + decpt = (Py_ssize_t)decpt_as_int; + if (digits == NULL) { + /* The only failure mode is no memory. */ + PyErr_NoMemory(); + goto exit; + } + assert(digits_end != NULL && digits_end >= digits); + digits_len = digits_end - digits; + + if (digits_len && !Py_ISDIGIT(digits[0])) { + /* Infinities and nans here; adapt Gay's output, + so convert Infinity to inf and NaN to nan, and + ignore sign of nan. Then return. */ + + /* ignore the actual sign of a nan */ + if (digits[0] == 'n' || digits[0] == 'N') + sign = 0; + + /* We only need 5 bytes to hold the result "+inf\0" . */ + bufsize = 5; /* Used later in an assert. */ + buf = (char *)PyMem_Malloc(bufsize); + if (buf == NULL) { + PyErr_NoMemory(); + goto exit; + } + p = buf; + + if (sign == 1) { + *p++ = '-'; + } + else if (always_add_sign) { + *p++ = '+'; + } + if (digits[0] == 'i' || digits[0] == 'I') { + strncpy(p, float_strings[OFS_INF], 3); + p += 3; + + if (type) + *type = Py_DTST_INFINITE; + } + else if (digits[0] == 'n' || digits[0] == 'N') { + strncpy(p, float_strings[OFS_NAN], 3); + p += 3; + + if (type) + *type = Py_DTST_NAN; + } + else { + /* shouldn't get here: Gay's code should always return + something starting with a digit, an 'I', or 'N' */ + strncpy(p, "ERR", 3); + p += 3; + assert(0); + } + goto exit; + } + + /* The result must be finite (not inf or nan). */ + if (type) + *type = Py_DTST_FINITE; + + + /* We got digits back, format them. We may need to pad 'digits' + either on the left or right (or both) with extra zeros, so in + general the resulting string has the form + + [][] + + where either of the pieces could be empty, and there's a + decimal point that could appear either in or in the + leading or trailing . + + Imagine an infinite 'virtual' string vdigits, consisting of the + string 'digits' (starting at index 0) padded on both the left and + right with infinite strings of zeros. We want to output a slice + + vdigits[vdigits_start : vdigits_end] + + of this virtual string. Thus if vdigits_start < 0 then we'll end + up producing some leading zeros; if vdigits_end > digits_len there + will be trailing zeros in the output. The next section of code + determines whether to use an exponent or not, figures out the + position 'decpt' of the decimal point, and computes 'vdigits_start' + and 'vdigits_end'. */ + vdigits_end = digits_len; + switch (format_code) { + case 'e': + use_exp = 1; + vdigits_end = precision; + break; + case 'f': + vdigits_end = decpt + precision; + break; + case 'g': + if (decpt <= -4 || decpt > + (add_dot_0_if_integer ? precision-1 : precision)) + use_exp = 1; + if (use_alt_formatting) + vdigits_end = precision; + break; + case 'r': + /* convert to exponential format at 1e16. We used to convert + at 1e17, but that gives odd-looking results for some values + when a 16-digit 'shortest' repr is padded with bogus zeros. + For example, repr(2e16+8) would give 20000000000000010.0; + the true value is 20000000000000008.0. */ + if (decpt <= -4 || decpt > 16) + use_exp = 1; + break; + default: + PyErr_BadInternalCall(); + goto exit; + } + + /* if using an exponent, reset decimal point position to 1 and adjust + exponent accordingly.*/ + if (use_exp) { + exp = decpt - 1; + decpt = 1; + } + /* ensure vdigits_start < decpt <= vdigits_end, or vdigits_start < + decpt < vdigits_end if add_dot_0_if_integer and no exponent */ + vdigits_start = decpt <= 0 ? decpt-1 : 0; + if (!use_exp && add_dot_0_if_integer) + vdigits_end = vdigits_end > decpt ? vdigits_end : decpt + 1; + else + vdigits_end = vdigits_end > decpt ? vdigits_end : decpt; + + /* double check inequalities */ + assert(vdigits_start <= 0 && + 0 <= digits_len && + digits_len <= vdigits_end); + /* decimal point should be in (vdigits_start, vdigits_end] */ + assert(vdigits_start < decpt && decpt <= vdigits_end); + + /* Compute an upper bound how much memory we need. This might be a few + chars too long, but no big deal. */ + bufsize = + /* sign, decimal point and trailing 0 byte */ + 3 + + + /* total digit count (including zero padding on both sides) */ + (vdigits_end - vdigits_start) + + + /* exponent "e+100", max 3 numerical digits */ + (use_exp ? 5 : 0); + + /* Now allocate the memory and initialize p to point to the start of + it. */ + buf = (char *)PyMem_Malloc(bufsize); + if (buf == NULL) { + PyErr_NoMemory(); + goto exit; + } + p = buf; + + /* Add a negative sign if negative, and a plus sign if non-negative + and always_add_sign is true. */ + if (sign == 1) + *p++ = '-'; + else if (always_add_sign) + *p++ = '+'; + + /* note that exactly one of the three 'if' conditions is true, + so we include exactly one decimal point */ + /* Zero padding on left of digit string */ + if (decpt <= 0) { + memset(p, '0', decpt-vdigits_start); + p += decpt - vdigits_start; + *p++ = '.'; + memset(p, '0', 0-decpt); + p += 0-decpt; + } + else { + memset(p, '0', 0-vdigits_start); + p += 0 - vdigits_start; + } + + /* Digits, with included decimal point */ + if (0 < decpt && decpt <= digits_len) { + strncpy(p, digits, decpt-0); + p += decpt-0; + *p++ = '.'; + strncpy(p, digits+decpt, digits_len-decpt); + p += digits_len-decpt; + } + else { + strncpy(p, digits, digits_len); + p += digits_len; + } + + /* And zeros on the right */ + if (digits_len < decpt) { + memset(p, '0', decpt-digits_len); + p += decpt-digits_len; + *p++ = '.'; + memset(p, '0', vdigits_end-decpt); + p += vdigits_end-decpt; + } + else { + memset(p, '0', vdigits_end-digits_len); + p += vdigits_end-digits_len; + } + + /* Delete a trailing decimal pt unless using alternative formatting. */ + if (p[-1] == '.' && !use_alt_formatting) + p--; + + /* Now that we've done zero padding, add an exponent if needed. */ + if (use_exp) { + *p++ = float_strings[OFS_E][0]; + exp_len = sprintf(p, "%+.02d", exp); + p += exp_len; + } exit: - if (buf) { - *p = '\0'; - /* It's too late if this fails, as we've already stepped on - memory that isn't ours. But it's an okay debugging test. */ - assert(p-buf < bufsize); - } - if (digits) - _Py_dg_freedtoa(digits); + if (buf) { + *p = '\0'; + /* It's too late if this fails, as we've already stepped on + memory that isn't ours. But it's an okay debugging test. */ + assert(p-buf < bufsize); + } + if (digits) + _Py_dg_freedtoa(digits); - return buf; + return buf; } PyAPI_FUNC(char *) PyOS_double_to_string(double val, - char format_code, - int precision, - int flags, - int *type) + char format_code, + int precision, + int flags, + int *type) { - char **float_strings = lc_float_strings; - int mode; + char **float_strings = lc_float_strings; + int mode; - /* Validate format_code, and map upper and lower case. Compute the - mode and make any adjustments as needed. */ - switch (format_code) { - /* exponent */ - case 'E': - float_strings = uc_float_strings; - format_code = 'e'; - /* Fall through. */ - case 'e': - mode = 2; - precision++; - break; - - /* fixed */ - case 'F': - float_strings = uc_float_strings; - format_code = 'f'; - /* Fall through. */ - case 'f': - mode = 3; - break; - - /* general */ - case 'G': - float_strings = uc_float_strings; - format_code = 'g'; - /* Fall through. */ - case 'g': - mode = 2; - /* precision 0 makes no sense for 'g' format; interpret as 1 */ - if (precision == 0) - precision = 1; - break; - - /* repr format */ - case 'r': - mode = 0; - /* Supplied precision is unused, must be 0. */ - if (precision != 0) { - PyErr_BadInternalCall(); - return NULL; - } - break; - - default: - PyErr_BadInternalCall(); - return NULL; - } - - return format_float_short(val, format_code, mode, precision, - flags & Py_DTSF_SIGN, - flags & Py_DTSF_ADD_DOT_0, - flags & Py_DTSF_ALT, - float_strings, type); + /* Validate format_code, and map upper and lower case. Compute the + mode and make any adjustments as needed. */ + switch (format_code) { + /* exponent */ + case 'E': + float_strings = uc_float_strings; + format_code = 'e'; + /* Fall through. */ + case 'e': + mode = 2; + precision++; + break; + + /* fixed */ + case 'F': + float_strings = uc_float_strings; + format_code = 'f'; + /* Fall through. */ + case 'f': + mode = 3; + break; + + /* general */ + case 'G': + float_strings = uc_float_strings; + format_code = 'g'; + /* Fall through. */ + case 'g': + mode = 2; + /* precision 0 makes no sense for 'g' format; interpret as 1 */ + if (precision == 0) + precision = 1; + break; + + /* repr format */ + case 'r': + mode = 0; + /* Supplied precision is unused, must be 0. */ + if (precision != 0) { + PyErr_BadInternalCall(); + return NULL; + } + break; + + default: + PyErr_BadInternalCall(); + return NULL; + } + + return format_float_short(val, format_code, mode, precision, + flags & Py_DTSF_SIGN, + flags & Py_DTSF_ADD_DOT_0, + flags & Py_DTSF_ALT, + float_strings, type); } #endif /* ifdef PY_NO_SHORT_FLOAT_REPR */ Modified: python/branches/py3k/Python/pythonrun.c ============================================================================== --- python/branches/py3k/Python/pythonrun.c (original) +++ python/branches/py3k/Python/pythonrun.c Sun May 9 17:52:27 2010 @@ -42,9 +42,9 @@ #ifndef Py_REF_DEBUG #define PRINT_TOTAL_REFS() #else /* Py_REF_DEBUG */ -#define PRINT_TOTAL_REFS() fprintf(stderr, \ - "[%" PY_FORMAT_SIZE_T "d refs]\n", \ - _Py_GetRefTotal()) +#define PRINT_TOTAL_REFS() fprintf(stderr, \ + "[%" PY_FORMAT_SIZE_T "d refs]\n", \ + _Py_GetRefTotal()) #endif #ifdef __cplusplus @@ -61,9 +61,9 @@ static int initstdio(void); static void flush_io(void); static PyObject *run_mod(mod_ty, const char *, PyObject *, PyObject *, - PyCompilerFlags *, PyArena *); + PyCompilerFlags *, PyArena *); static PyObject *run_pyc_file(FILE *, const char *, PyObject *, PyObject *, - PyCompilerFlags *); + PyCompilerFlags *); static void err_input(perrdetail *); static void initsigs(void); static void call_py_exitfuncs(void); @@ -97,7 +97,7 @@ PyObject * PyModule_GetWarningsModule(void) { - return PyImport_ImportModule("warnings"); + return PyImport_ImportModule("warnings"); } static int initialized = 0; @@ -107,7 +107,7 @@ int Py_IsInitialized(void) { - return initialized; + return initialized; } /* Global initializations. Can be undone by Py_Finalize(). Don't @@ -125,191 +125,191 @@ static int add_flag(int flag, const char *envs) { - int env = atoi(envs); - if (flag < env) - flag = env; - if (flag < 1) - flag = 1; - return flag; + int env = atoi(envs); + if (flag < env) + flag = env; + if (flag < 1) + flag = 1; + return flag; } #if defined(HAVE_LANGINFO_H) && defined(CODESET) static char* get_codeset(void) { - char* codeset; - PyObject *codec, *name; + char* codeset; + PyObject *codec, *name; - codeset = nl_langinfo(CODESET); - if (!codeset || codeset[0] == '\0') - return NULL; - - codec = _PyCodec_Lookup(codeset); - if (!codec) - goto error; - - name = PyObject_GetAttrString(codec, "name"); - Py_CLEAR(codec); - if (!name) - goto error; - - codeset = strdup(_PyUnicode_AsString(name)); - Py_DECREF(name); - return codeset; + codeset = nl_langinfo(CODESET); + if (!codeset || codeset[0] == '\0') + return NULL; + + codec = _PyCodec_Lookup(codeset); + if (!codec) + goto error; + + name = PyObject_GetAttrString(codec, "name"); + Py_CLEAR(codec); + if (!name) + goto error; + + codeset = strdup(_PyUnicode_AsString(name)); + Py_DECREF(name); + return codeset; error: - Py_XDECREF(codec); - PyErr_Clear(); - return NULL; + Py_XDECREF(codec); + PyErr_Clear(); + return NULL; } #endif void Py_InitializeEx(int install_sigs) { - PyInterpreterState *interp; - PyThreadState *tstate; - PyObject *bimod, *sysmod, *pstderr; - char *p; + PyInterpreterState *interp; + PyThreadState *tstate; + PyObject *bimod, *sysmod, *pstderr; + char *p; #if defined(HAVE_LANGINFO_H) && defined(CODESET) - char *codeset; + char *codeset; #endif - extern void _Py_ReadyTypes(void); + extern void _Py_ReadyTypes(void); - if (initialized) - return; - initialized = 1; + if (initialized) + return; + initialized = 1; #if defined(HAVE_LANGINFO_H) && defined(HAVE_SETLOCALE) - /* Set up the LC_CTYPE locale, so we can obtain - the locale's charset without having to switch - locales. */ - setlocale(LC_CTYPE, ""); -#endif - - if ((p = Py_GETENV("PYTHONDEBUG")) && *p != '\0') - Py_DebugFlag = add_flag(Py_DebugFlag, p); - if ((p = Py_GETENV("PYTHONVERBOSE")) && *p != '\0') - Py_VerboseFlag = add_flag(Py_VerboseFlag, p); - if ((p = Py_GETENV("PYTHONOPTIMIZE")) && *p != '\0') - Py_OptimizeFlag = add_flag(Py_OptimizeFlag, p); - if ((p = Py_GETENV("PYTHONDONTWRITEBYTECODE")) && *p != '\0') - Py_DontWriteBytecodeFlag = add_flag(Py_DontWriteBytecodeFlag, p); - - interp = PyInterpreterState_New(); - if (interp == NULL) - Py_FatalError("Py_Initialize: can't make first interpreter"); - - tstate = PyThreadState_New(interp); - if (tstate == NULL) - Py_FatalError("Py_Initialize: can't make first thread"); - (void) PyThreadState_Swap(tstate); - - _Py_ReadyTypes(); - - if (!_PyFrame_Init()) - Py_FatalError("Py_Initialize: can't init frames"); - - if (!_PyLong_Init()) - Py_FatalError("Py_Initialize: can't init longs"); - - if (!PyByteArray_Init()) - Py_FatalError("Py_Initialize: can't init bytearray"); - - _PyFloat_Init(); - - interp->modules = PyDict_New(); - if (interp->modules == NULL) - Py_FatalError("Py_Initialize: can't make modules dictionary"); - interp->modules_reloading = PyDict_New(); - if (interp->modules_reloading == NULL) - Py_FatalError("Py_Initialize: can't make modules_reloading dictionary"); - - /* Init Unicode implementation; relies on the codec registry */ - _PyUnicode_Init(); - - bimod = _PyBuiltin_Init(); - if (bimod == NULL) - Py_FatalError("Py_Initialize: can't initialize builtins modules"); - _PyImport_FixupExtension(bimod, "builtins", "builtins"); - interp->builtins = PyModule_GetDict(bimod); - if (interp->builtins == NULL) - Py_FatalError("Py_Initialize: can't initialize builtins dict"); - Py_INCREF(interp->builtins); - - /* initialize builtin exceptions */ - _PyExc_Init(); - - sysmod = _PySys_Init(); - if (sysmod == NULL) - Py_FatalError("Py_Initialize: can't initialize sys"); - interp->sysdict = PyModule_GetDict(sysmod); - if (interp->sysdict == NULL) - Py_FatalError("Py_Initialize: can't initialize sys dict"); - Py_INCREF(interp->sysdict); - _PyImport_FixupExtension(sysmod, "sys", "sys"); - PySys_SetPath(Py_GetPath()); - PyDict_SetItemString(interp->sysdict, "modules", - interp->modules); - - /* Set up a preliminary stderr printer until we have enough - infrastructure for the io module in place. */ - pstderr = PyFile_NewStdPrinter(fileno(stderr)); - if (pstderr == NULL) - Py_FatalError("Py_Initialize: can't set preliminary stderr"); - PySys_SetObject("stderr", pstderr); - PySys_SetObject("__stderr__", pstderr); + /* Set up the LC_CTYPE locale, so we can obtain + the locale's charset without having to switch + locales. */ + setlocale(LC_CTYPE, ""); +#endif + + if ((p = Py_GETENV("PYTHONDEBUG")) && *p != '\0') + Py_DebugFlag = add_flag(Py_DebugFlag, p); + if ((p = Py_GETENV("PYTHONVERBOSE")) && *p != '\0') + Py_VerboseFlag = add_flag(Py_VerboseFlag, p); + if ((p = Py_GETENV("PYTHONOPTIMIZE")) && *p != '\0') + Py_OptimizeFlag = add_flag(Py_OptimizeFlag, p); + if ((p = Py_GETENV("PYTHONDONTWRITEBYTECODE")) && *p != '\0') + Py_DontWriteBytecodeFlag = add_flag(Py_DontWriteBytecodeFlag, p); + + interp = PyInterpreterState_New(); + if (interp == NULL) + Py_FatalError("Py_Initialize: can't make first interpreter"); + + tstate = PyThreadState_New(interp); + if (tstate == NULL) + Py_FatalError("Py_Initialize: can't make first thread"); + (void) PyThreadState_Swap(tstate); + + _Py_ReadyTypes(); + + if (!_PyFrame_Init()) + Py_FatalError("Py_Initialize: can't init frames"); + + if (!_PyLong_Init()) + Py_FatalError("Py_Initialize: can't init longs"); + + if (!PyByteArray_Init()) + Py_FatalError("Py_Initialize: can't init bytearray"); + + _PyFloat_Init(); + + interp->modules = PyDict_New(); + if (interp->modules == NULL) + Py_FatalError("Py_Initialize: can't make modules dictionary"); + interp->modules_reloading = PyDict_New(); + if (interp->modules_reloading == NULL) + Py_FatalError("Py_Initialize: can't make modules_reloading dictionary"); + + /* Init Unicode implementation; relies on the codec registry */ + _PyUnicode_Init(); + + bimod = _PyBuiltin_Init(); + if (bimod == NULL) + Py_FatalError("Py_Initialize: can't initialize builtins modules"); + _PyImport_FixupExtension(bimod, "builtins", "builtins"); + interp->builtins = PyModule_GetDict(bimod); + if (interp->builtins == NULL) + Py_FatalError("Py_Initialize: can't initialize builtins dict"); + Py_INCREF(interp->builtins); + + /* initialize builtin exceptions */ + _PyExc_Init(); + + sysmod = _PySys_Init(); + if (sysmod == NULL) + Py_FatalError("Py_Initialize: can't initialize sys"); + interp->sysdict = PyModule_GetDict(sysmod); + if (interp->sysdict == NULL) + Py_FatalError("Py_Initialize: can't initialize sys dict"); + Py_INCREF(interp->sysdict); + _PyImport_FixupExtension(sysmod, "sys", "sys"); + PySys_SetPath(Py_GetPath()); + PyDict_SetItemString(interp->sysdict, "modules", + interp->modules); + + /* Set up a preliminary stderr printer until we have enough + infrastructure for the io module in place. */ + pstderr = PyFile_NewStdPrinter(fileno(stderr)); + if (pstderr == NULL) + Py_FatalError("Py_Initialize: can't set preliminary stderr"); + PySys_SetObject("stderr", pstderr); + PySys_SetObject("__stderr__", pstderr); - _PyImport_Init(); + _PyImport_Init(); - _PyImportHooks_Init(); + _PyImportHooks_Init(); #if defined(HAVE_LANGINFO_H) && defined(CODESET) - /* On Unix, set the file system encoding according to the - user's preference, if the CODESET names a well-known - Python codec, and Py_FileSystemDefaultEncoding isn't - initialized by other means. Also set the encoding of - stdin and stdout if these are terminals. */ - - codeset = get_codeset(); - if (codeset) { - if (!Py_FileSystemDefaultEncoding) - Py_FileSystemDefaultEncoding = codeset; - else - free(codeset); - } -#endif - - if (install_sigs) - initsigs(); /* Signal handling stuff, including initintr() */ - - /* Initialize warnings. */ - _PyWarnings_Init(); - if (PySys_HasWarnOptions()) { - PyObject *warnings_module = PyImport_ImportModule("warnings"); - if (!warnings_module) - PyErr_Clear(); - Py_XDECREF(warnings_module); - } - - initmain(); /* Module __main__ */ - if (initstdio() < 0) - Py_FatalError( - "Py_Initialize: can't initialize sys standard streams"); + /* On Unix, set the file system encoding according to the + user's preference, if the CODESET names a well-known + Python codec, and Py_FileSystemDefaultEncoding isn't + initialized by other means. Also set the encoding of + stdin and stdout if these are terminals. */ + + codeset = get_codeset(); + if (codeset) { + if (!Py_FileSystemDefaultEncoding) + Py_FileSystemDefaultEncoding = codeset; + else + free(codeset); + } +#endif + + if (install_sigs) + initsigs(); /* Signal handling stuff, including initintr() */ + + /* Initialize warnings. */ + _PyWarnings_Init(); + if (PySys_HasWarnOptions()) { + PyObject *warnings_module = PyImport_ImportModule("warnings"); + if (!warnings_module) + PyErr_Clear(); + Py_XDECREF(warnings_module); + } + + initmain(); /* Module __main__ */ + if (initstdio() < 0) + Py_FatalError( + "Py_Initialize: can't initialize sys standard streams"); - /* auto-thread-state API, if available */ + /* auto-thread-state API, if available */ #ifdef WITH_THREAD - _PyGILState_Init(interp, tstate); + _PyGILState_Init(interp, tstate); #endif /* WITH_THREAD */ - if (!Py_NoSiteFlag) - initsite(); /* Module site */ + if (!Py_NoSiteFlag) + initsite(); /* Module site */ } void Py_Initialize(void) { - Py_InitializeEx(1); + Py_InitializeEx(1); } @@ -322,25 +322,25 @@ static void flush_std_files(void) { - PyObject *fout = PySys_GetObject("stdout"); - PyObject *ferr = PySys_GetObject("stderr"); - PyObject *tmp; - - if (fout != NULL && fout != Py_None) { - tmp = PyObject_CallMethod(fout, "flush", ""); - if (tmp == NULL) - PyErr_Clear(); - else - Py_DECREF(tmp); - } - - if (ferr != NULL || ferr != Py_None) { - tmp = PyObject_CallMethod(ferr, "flush", ""); - if (tmp == NULL) - PyErr_Clear(); - else - Py_DECREF(tmp); - } + PyObject *fout = PySys_GetObject("stdout"); + PyObject *ferr = PySys_GetObject("stderr"); + PyObject *tmp; + + if (fout != NULL && fout != Py_None) { + tmp = PyObject_CallMethod(fout, "flush", ""); + if (tmp == NULL) + PyErr_Clear(); + else + Py_DECREF(tmp); + } + + if (ferr != NULL || ferr != Py_None) { + tmp = PyObject_CallMethod(ferr, "flush", ""); + if (tmp == NULL) + PyErr_Clear(); + else + Py_DECREF(tmp); + } } /* Undo the effect of Py_Initialize(). @@ -360,169 +360,169 @@ void Py_Finalize(void) { - PyInterpreterState *interp; - PyThreadState *tstate; + PyInterpreterState *interp; + PyThreadState *tstate; - if (!initialized) - return; + if (!initialized) + return; - wait_for_thread_shutdown(); + wait_for_thread_shutdown(); - /* The interpreter is still entirely intact at this point, and the - * exit funcs may be relying on that. In particular, if some thread - * or exit func is still waiting to do an import, the import machinery - * expects Py_IsInitialized() to return true. So don't say the - * interpreter is uninitialized until after the exit funcs have run. - * Note that Threading.py uses an exit func to do a join on all the - * threads created thru it, so this also protects pending imports in - * the threads created via Threading. - */ - call_py_exitfuncs(); - initialized = 0; - - /* Flush stdout+stderr */ - flush_std_files(); - - /* Get current thread state and interpreter pointer */ - tstate = PyThreadState_GET(); - interp = tstate->interp; - - /* Disable signal handling */ - PyOS_FiniInterrupts(); - - /* Clear type lookup cache */ - PyType_ClearCache(); - - /* Collect garbage. This may call finalizers; it's nice to call these - * before all modules are destroyed. - * XXX If a __del__ or weakref callback is triggered here, and tries to - * XXX import a module, bad things can happen, because Python no - * XXX longer believes it's initialized. - * XXX Fatal Python error: Interpreter not initialized (version mismatch?) - * XXX is easy to provoke that way. I've also seen, e.g., - * XXX Exception exceptions.ImportError: 'No module named sha' - * XXX in ignored - * XXX but I'm unclear on exactly how that one happens. In any case, - * XXX I haven't seen a real-life report of either of these. - */ - PyGC_Collect(); + /* The interpreter is still entirely intact at this point, and the + * exit funcs may be relying on that. In particular, if some thread + * or exit func is still waiting to do an import, the import machinery + * expects Py_IsInitialized() to return true. So don't say the + * interpreter is uninitialized until after the exit funcs have run. + * Note that Threading.py uses an exit func to do a join on all the + * threads created thru it, so this also protects pending imports in + * the threads created via Threading. + */ + call_py_exitfuncs(); + initialized = 0; + + /* Flush stdout+stderr */ + flush_std_files(); + + /* Get current thread state and interpreter pointer */ + tstate = PyThreadState_GET(); + interp = tstate->interp; + + /* Disable signal handling */ + PyOS_FiniInterrupts(); + + /* Clear type lookup cache */ + PyType_ClearCache(); + + /* Collect garbage. This may call finalizers; it's nice to call these + * before all modules are destroyed. + * XXX If a __del__ or weakref callback is triggered here, and tries to + * XXX import a module, bad things can happen, because Python no + * XXX longer believes it's initialized. + * XXX Fatal Python error: Interpreter not initialized (version mismatch?) + * XXX is easy to provoke that way. I've also seen, e.g., + * XXX Exception exceptions.ImportError: 'No module named sha' + * XXX in ignored + * XXX but I'm unclear on exactly how that one happens. In any case, + * XXX I haven't seen a real-life report of either of these. + */ + PyGC_Collect(); #ifdef COUNT_ALLOCS - /* With COUNT_ALLOCS, it helps to run GC multiple times: - each collection might release some types from the type - list, so they become garbage. */ - while (PyGC_Collect() > 0) - /* nothing */; -#endif - - /* Destroy all modules */ - PyImport_Cleanup(); - - /* Flush stdout+stderr (again, in case more was printed) */ - flush_std_files(); - - /* Collect final garbage. This disposes of cycles created by - * new-style class definitions, for example. - * XXX This is disabled because it caused too many problems. If - * XXX a __del__ or weakref callback triggers here, Python code has - * XXX a hard time running, because even the sys module has been - * XXX cleared out (sys.stdout is gone, sys.excepthook is gone, etc). - * XXX One symptom is a sequence of information-free messages - * XXX coming from threads (if a __del__ or callback is invoked, - * XXX other threads can execute too, and any exception they encounter - * XXX triggers a comedy of errors as subsystem after subsystem - * XXX fails to find what it *expects* to find in sys to help report - * XXX the exception and consequent unexpected failures). I've also - * XXX seen segfaults then, after adding print statements to the - * XXX Python code getting called. - */ + /* With COUNT_ALLOCS, it helps to run GC multiple times: + each collection might release some types from the type + list, so they become garbage. */ + while (PyGC_Collect() > 0) + /* nothing */; +#endif + + /* Destroy all modules */ + PyImport_Cleanup(); + + /* Flush stdout+stderr (again, in case more was printed) */ + flush_std_files(); + + /* Collect final garbage. This disposes of cycles created by + * new-style class definitions, for example. + * XXX This is disabled because it caused too many problems. If + * XXX a __del__ or weakref callback triggers here, Python code has + * XXX a hard time running, because even the sys module has been + * XXX cleared out (sys.stdout is gone, sys.excepthook is gone, etc). + * XXX One symptom is a sequence of information-free messages + * XXX coming from threads (if a __del__ or callback is invoked, + * XXX other threads can execute too, and any exception they encounter + * XXX triggers a comedy of errors as subsystem after subsystem + * XXX fails to find what it *expects* to find in sys to help report + * XXX the exception and consequent unexpected failures). I've also + * XXX seen segfaults then, after adding print statements to the + * XXX Python code getting called. + */ #if 0 - PyGC_Collect(); + PyGC_Collect(); #endif - /* Destroy the database used by _PyImport_{Fixup,Find}Extension */ - _PyImport_Fini(); + /* Destroy the database used by _PyImport_{Fixup,Find}Extension */ + _PyImport_Fini(); - /* Debugging stuff */ + /* Debugging stuff */ #ifdef COUNT_ALLOCS - dump_counts(stdout); + dump_counts(stdout); #endif - PRINT_TOTAL_REFS(); + PRINT_TOTAL_REFS(); #ifdef Py_TRACE_REFS - /* Display all objects still alive -- this can invoke arbitrary - * __repr__ overrides, so requires a mostly-intact interpreter. - * Alas, a lot of stuff may still be alive now that will be cleaned - * up later. - */ - if (Py_GETENV("PYTHONDUMPREFS")) - _Py_PrintReferences(stderr); + /* Display all objects still alive -- this can invoke arbitrary + * __repr__ overrides, so requires a mostly-intact interpreter. + * Alas, a lot of stuff may still be alive now that will be cleaned + * up later. + */ + if (Py_GETENV("PYTHONDUMPREFS")) + _Py_PrintReferences(stderr); #endif /* Py_TRACE_REFS */ - /* Clear interpreter state */ - PyInterpreterState_Clear(interp); + /* Clear interpreter state */ + PyInterpreterState_Clear(interp); - /* Now we decref the exception classes. After this point nothing - can raise an exception. That's okay, because each Fini() method - below has been checked to make sure no exceptions are ever - raised. - */ + /* Now we decref the exception classes. After this point nothing + can raise an exception. That's okay, because each Fini() method + below has been checked to make sure no exceptions are ever + raised. + */ - _PyExc_Fini(); + _PyExc_Fini(); - /* Cleanup auto-thread-state */ + /* Cleanup auto-thread-state */ #ifdef WITH_THREAD - _PyGILState_Fini(); + _PyGILState_Fini(); #endif /* WITH_THREAD */ - /* Delete current thread */ - PyThreadState_Swap(NULL); - PyInterpreterState_Delete(interp); - - /* Sundry finalizers */ - PyMethod_Fini(); - PyFrame_Fini(); - PyCFunction_Fini(); - PyTuple_Fini(); - PyList_Fini(); - PySet_Fini(); - PyBytes_Fini(); - PyByteArray_Fini(); - PyLong_Fini(); - PyFloat_Fini(); - PyDict_Fini(); - - /* Cleanup Unicode implementation */ - _PyUnicode_Fini(); - - /* reset file system default encoding */ - if (!Py_HasFileSystemDefaultEncoding) { - free((char*)Py_FileSystemDefaultEncoding); - Py_FileSystemDefaultEncoding = NULL; - } - - /* XXX Still allocated: - - various static ad-hoc pointers to interned strings - - int and float free list blocks - - whatever various modules and libraries allocate - */ + /* Delete current thread */ + PyThreadState_Swap(NULL); + PyInterpreterState_Delete(interp); + + /* Sundry finalizers */ + PyMethod_Fini(); + PyFrame_Fini(); + PyCFunction_Fini(); + PyTuple_Fini(); + PyList_Fini(); + PySet_Fini(); + PyBytes_Fini(); + PyByteArray_Fini(); + PyLong_Fini(); + PyFloat_Fini(); + PyDict_Fini(); + + /* Cleanup Unicode implementation */ + _PyUnicode_Fini(); + + /* reset file system default encoding */ + if (!Py_HasFileSystemDefaultEncoding) { + free((char*)Py_FileSystemDefaultEncoding); + Py_FileSystemDefaultEncoding = NULL; + } + + /* XXX Still allocated: + - various static ad-hoc pointers to interned strings + - int and float free list blocks + - whatever various modules and libraries allocate + */ - PyGrammar_RemoveAccelerators(&_PyParser_Grammar); + PyGrammar_RemoveAccelerators(&_PyParser_Grammar); #ifdef Py_TRACE_REFS - /* Display addresses (& refcnts) of all objects still alive. - * An address can be used to find the repr of the object, printed - * above by _Py_PrintReferences. - */ - if (Py_GETENV("PYTHONDUMPREFS")) - _Py_PrintReferenceAddresses(stderr); + /* Display addresses (& refcnts) of all objects still alive. + * An address can be used to find the repr of the object, printed + * above by _Py_PrintReferences. + */ + if (Py_GETENV("PYTHONDUMPREFS")) + _Py_PrintReferenceAddresses(stderr); #endif /* Py_TRACE_REFS */ #ifdef PYMALLOC_DEBUG - if (Py_GETENV("PYTHONMALLOCSTATS")) - _PyObject_DebugMallocStats(); + if (Py_GETENV("PYTHONMALLOCSTATS")) + _PyObject_DebugMallocStats(); #endif - call_ll_exitfuncs(); + call_ll_exitfuncs(); } /* Create and initialize a new interpreter and thread, and return the @@ -541,81 +541,81 @@ PyThreadState * Py_NewInterpreter(void) { - PyInterpreterState *interp; - PyThreadState *tstate, *save_tstate; - PyObject *bimod, *sysmod; - - if (!initialized) - Py_FatalError("Py_NewInterpreter: call Py_Initialize first"); - - interp = PyInterpreterState_New(); - if (interp == NULL) - return NULL; - - tstate = PyThreadState_New(interp); - if (tstate == NULL) { - PyInterpreterState_Delete(interp); - return NULL; - } - - save_tstate = PyThreadState_Swap(tstate); - - /* XXX The following is lax in error checking */ - - interp->modules = PyDict_New(); - interp->modules_reloading = PyDict_New(); - - bimod = _PyImport_FindExtension("builtins", "builtins"); - if (bimod != NULL) { - interp->builtins = PyModule_GetDict(bimod); - if (interp->builtins == NULL) - goto handle_error; - Py_INCREF(interp->builtins); - } - - /* initialize builtin exceptions */ - _PyExc_Init(); - - sysmod = _PyImport_FindExtension("sys", "sys"); - if (bimod != NULL && sysmod != NULL) { - PyObject *pstderr; - interp->sysdict = PyModule_GetDict(sysmod); - if (interp->sysdict == NULL) - goto handle_error; - Py_INCREF(interp->sysdict); - PySys_SetPath(Py_GetPath()); - PyDict_SetItemString(interp->sysdict, "modules", - interp->modules); - /* Set up a preliminary stderr printer until we have enough - infrastructure for the io module in place. */ - pstderr = PyFile_NewStdPrinter(fileno(stderr)); - if (pstderr == NULL) - Py_FatalError("Py_Initialize: can't set preliminary stderr"); - PySys_SetObject("stderr", pstderr); - PySys_SetObject("__stderr__", pstderr); - - _PyImportHooks_Init(); - if (initstdio() < 0) - Py_FatalError( - "Py_Initialize: can't initialize sys standard streams"); - initmain(); - if (!Py_NoSiteFlag) - initsite(); - } + PyInterpreterState *interp; + PyThreadState *tstate, *save_tstate; + PyObject *bimod, *sysmod; + + if (!initialized) + Py_FatalError("Py_NewInterpreter: call Py_Initialize first"); + + interp = PyInterpreterState_New(); + if (interp == NULL) + return NULL; + + tstate = PyThreadState_New(interp); + if (tstate == NULL) { + PyInterpreterState_Delete(interp); + return NULL; + } + + save_tstate = PyThreadState_Swap(tstate); + + /* XXX The following is lax in error checking */ + + interp->modules = PyDict_New(); + interp->modules_reloading = PyDict_New(); + + bimod = _PyImport_FindExtension("builtins", "builtins"); + if (bimod != NULL) { + interp->builtins = PyModule_GetDict(bimod); + if (interp->builtins == NULL) + goto handle_error; + Py_INCREF(interp->builtins); + } + + /* initialize builtin exceptions */ + _PyExc_Init(); + + sysmod = _PyImport_FindExtension("sys", "sys"); + if (bimod != NULL && sysmod != NULL) { + PyObject *pstderr; + interp->sysdict = PyModule_GetDict(sysmod); + if (interp->sysdict == NULL) + goto handle_error; + Py_INCREF(interp->sysdict); + PySys_SetPath(Py_GetPath()); + PyDict_SetItemString(interp->sysdict, "modules", + interp->modules); + /* Set up a preliminary stderr printer until we have enough + infrastructure for the io module in place. */ + pstderr = PyFile_NewStdPrinter(fileno(stderr)); + if (pstderr == NULL) + Py_FatalError("Py_Initialize: can't set preliminary stderr"); + PySys_SetObject("stderr", pstderr); + PySys_SetObject("__stderr__", pstderr); + + _PyImportHooks_Init(); + if (initstdio() < 0) + Py_FatalError( + "Py_Initialize: can't initialize sys standard streams"); + initmain(); + if (!Py_NoSiteFlag) + initsite(); + } - if (!PyErr_Occurred()) - return tstate; + if (!PyErr_Occurred()) + return tstate; handle_error: - /* Oops, it didn't work. Undo it all. */ + /* Oops, it didn't work. Undo it all. */ - PyErr_Print(); - PyThreadState_Clear(tstate); - PyThreadState_Swap(save_tstate); - PyThreadState_Delete(tstate); - PyInterpreterState_Delete(interp); + PyErr_Print(); + PyThreadState_Clear(tstate); + PyThreadState_Swap(save_tstate); + PyThreadState_Delete(tstate); + PyInterpreterState_Delete(interp); - return NULL; + return NULL; } /* Delete an interpreter and its last thread. This requires that the @@ -633,19 +633,19 @@ void Py_EndInterpreter(PyThreadState *tstate) { - PyInterpreterState *interp = tstate->interp; + PyInterpreterState *interp = tstate->interp; - if (tstate != PyThreadState_GET()) - Py_FatalError("Py_EndInterpreter: thread is not current"); - if (tstate->frame != NULL) - Py_FatalError("Py_EndInterpreter: thread still has a frame"); - if (tstate != interp->tstate_head || tstate->next != NULL) - Py_FatalError("Py_EndInterpreter: not the last thread"); - - PyImport_Cleanup(); - PyInterpreterState_Clear(interp); - PyThreadState_Swap(NULL); - PyInterpreterState_Delete(interp); + if (tstate != PyThreadState_GET()) + Py_FatalError("Py_EndInterpreter: thread is not current"); + if (tstate->frame != NULL) + Py_FatalError("Py_EndInterpreter: thread still has a frame"); + if (tstate != interp->tstate_head || tstate->next != NULL) + Py_FatalError("Py_EndInterpreter: not the last thread"); + + PyImport_Cleanup(); + PyInterpreterState_Clear(interp); + PyThreadState_Swap(NULL); + PyInterpreterState_Delete(interp); } static wchar_t *progname = L"python"; @@ -653,14 +653,14 @@ void Py_SetProgramName(wchar_t *pn) { - if (pn && *pn) - progname = pn; + if (pn && *pn) + progname = pn; } wchar_t * Py_GetProgramName(void) { - return progname; + return progname; } static wchar_t *default_home = NULL; @@ -669,23 +669,23 @@ void Py_SetPythonHome(wchar_t *home) { - default_home = home; + default_home = home; } wchar_t * Py_GetPythonHome(void) { - wchar_t *home = default_home; - if (home == NULL && !Py_IgnoreEnvironmentFlag) { - char* chome = Py_GETENV("PYTHONHOME"); - if (chome) { - size_t r = mbstowcs(env_home, chome, PATH_MAX+1); - if (r != (size_t)-1 && r <= PATH_MAX) - home = env_home; - } + wchar_t *home = default_home; + if (home == NULL && !Py_IgnoreEnvironmentFlag) { + char* chome = Py_GETENV("PYTHONHOME"); + if (chome) { + size_t r = mbstowcs(env_home, chome, PATH_MAX+1); + if (r != (size_t)-1 && r <= PATH_MAX) + home = env_home; + } - } - return home; + } + return home; } /* Create __main__ module */ @@ -693,18 +693,18 @@ static void initmain(void) { - PyObject *m, *d; - m = PyImport_AddModule("__main__"); - if (m == NULL) - Py_FatalError("can't create __main__ module"); - d = PyModule_GetDict(m); - if (PyDict_GetItemString(d, "__builtins__") == NULL) { - PyObject *bimod = PyImport_ImportModule("builtins"); - if (bimod == NULL || - PyDict_SetItemString(d, "__builtins__", bimod) != 0) - Py_FatalError("can't add __builtins__ to __main__"); - Py_DECREF(bimod); - } + PyObject *m, *d; + m = PyImport_AddModule("__main__"); + if (m == NULL) + Py_FatalError("can't create __main__ module"); + d = PyModule_GetDict(m); + if (PyDict_GetItemString(d, "__builtins__") == NULL) { + PyObject *bimod = PyImport_ImportModule("builtins"); + if (bimod == NULL || + PyDict_SetItemString(d, "__builtins__", bimod) != 0) + Py_FatalError("can't add __builtins__ to __main__"); + Py_DECREF(bimod); + } } /* Import the site module (not into __main__ though) */ @@ -712,386 +712,386 @@ static void initsite(void) { - PyObject *m; - m = PyImport_ImportModule("site"); - if (m == NULL) { - PyErr_Print(); - Py_Finalize(); - exit(1); - } - else { - Py_DECREF(m); - } + PyObject *m; + m = PyImport_ImportModule("site"); + if (m == NULL) { + PyErr_Print(); + Py_Finalize(); + exit(1); + } + else { + Py_DECREF(m); + } } static PyObject* create_stdio(PyObject* io, - int fd, int write_mode, char* name, - char* encoding, char* errors) + int fd, int write_mode, char* name, + char* encoding, char* errors) { - PyObject *buf = NULL, *stream = NULL, *text = NULL, *raw = NULL, *res; - const char* mode; - PyObject *line_buffering; - int buffering, isatty; - - /* stdin is always opened in buffered mode, first because it shouldn't - make a difference in common use cases, second because TextIOWrapper - depends on the presence of a read1() method which only exists on - buffered streams. - */ - if (Py_UnbufferedStdioFlag && write_mode) - buffering = 0; - else - buffering = -1; - if (write_mode) - mode = "wb"; - else - mode = "rb"; - buf = PyObject_CallMethod(io, "open", "isiOOOi", - fd, mode, buffering, - Py_None, Py_None, Py_None, 0); - if (buf == NULL) - goto error; - - if (buffering) { - raw = PyObject_GetAttrString(buf, "raw"); - if (raw == NULL) - goto error; - } - else { - raw = buf; - Py_INCREF(raw); - } - - text = PyUnicode_FromString(name); - if (text == NULL || PyObject_SetAttrString(raw, "name", text) < 0) - goto error; - res = PyObject_CallMethod(raw, "isatty", ""); - if (res == NULL) - goto error; - isatty = PyObject_IsTrue(res); - Py_DECREF(res); - if (isatty == -1) - goto error; - if (isatty || Py_UnbufferedStdioFlag) - line_buffering = Py_True; - else - line_buffering = Py_False; - - Py_CLEAR(raw); - Py_CLEAR(text); - - stream = PyObject_CallMethod(io, "TextIOWrapper", "OsssO", - buf, encoding, errors, - "\n", line_buffering); - Py_CLEAR(buf); - if (stream == NULL) - goto error; - - if (write_mode) - mode = "w"; - else - mode = "r"; - text = PyUnicode_FromString(mode); - if (!text || PyObject_SetAttrString(stream, "mode", text) < 0) - goto error; - Py_CLEAR(text); - return stream; + PyObject *buf = NULL, *stream = NULL, *text = NULL, *raw = NULL, *res; + const char* mode; + PyObject *line_buffering; + int buffering, isatty; + + /* stdin is always opened in buffered mode, first because it shouldn't + make a difference in common use cases, second because TextIOWrapper + depends on the presence of a read1() method which only exists on + buffered streams. + */ + if (Py_UnbufferedStdioFlag && write_mode) + buffering = 0; + else + buffering = -1; + if (write_mode) + mode = "wb"; + else + mode = "rb"; + buf = PyObject_CallMethod(io, "open", "isiOOOi", + fd, mode, buffering, + Py_None, Py_None, Py_None, 0); + if (buf == NULL) + goto error; + + if (buffering) { + raw = PyObject_GetAttrString(buf, "raw"); + if (raw == NULL) + goto error; + } + else { + raw = buf; + Py_INCREF(raw); + } + + text = PyUnicode_FromString(name); + if (text == NULL || PyObject_SetAttrString(raw, "name", text) < 0) + goto error; + res = PyObject_CallMethod(raw, "isatty", ""); + if (res == NULL) + goto error; + isatty = PyObject_IsTrue(res); + Py_DECREF(res); + if (isatty == -1) + goto error; + if (isatty || Py_UnbufferedStdioFlag) + line_buffering = Py_True; + else + line_buffering = Py_False; + + Py_CLEAR(raw); + Py_CLEAR(text); + + stream = PyObject_CallMethod(io, "TextIOWrapper", "OsssO", + buf, encoding, errors, + "\n", line_buffering); + Py_CLEAR(buf); + if (stream == NULL) + goto error; + + if (write_mode) + mode = "w"; + else + mode = "r"; + text = PyUnicode_FromString(mode); + if (!text || PyObject_SetAttrString(stream, "mode", text) < 0) + goto error; + Py_CLEAR(text); + return stream; error: - Py_XDECREF(buf); - Py_XDECREF(stream); - Py_XDECREF(text); - Py_XDECREF(raw); - return NULL; + Py_XDECREF(buf); + Py_XDECREF(stream); + Py_XDECREF(text); + Py_XDECREF(raw); + return NULL; } /* Initialize sys.stdin, stdout, stderr and builtins.open */ static int initstdio(void) { - PyObject *iomod = NULL, *wrapper; - PyObject *bimod = NULL; - PyObject *m; - PyObject *std = NULL; - int status = 0, fd; - PyObject * encoding_attr; - char *encoding = NULL, *errors; - - /* Hack to avoid a nasty recursion issue when Python is invoked - in verbose mode: pre-import the Latin-1 and UTF-8 codecs */ - if ((m = PyImport_ImportModule("encodings.utf_8")) == NULL) { - goto error; - } - Py_DECREF(m); - - if (!(m = PyImport_ImportModule("encodings.latin_1"))) { - goto error; - } - Py_DECREF(m); - - if (!(bimod = PyImport_ImportModule("builtins"))) { - goto error; - } - - if (!(iomod = PyImport_ImportModule("io"))) { - goto error; - } - if (!(wrapper = PyObject_GetAttrString(iomod, "OpenWrapper"))) { - goto error; - } - - /* Set builtins.open */ - if (PyObject_SetAttrString(bimod, "open", wrapper) == -1) { - goto error; - } - - encoding = Py_GETENV("PYTHONIOENCODING"); - errors = NULL; - if (encoding) { - encoding = strdup(encoding); - errors = strchr(encoding, ':'); - if (errors) { - *errors = '\0'; - errors++; - } - } - - /* Set sys.stdin */ - fd = fileno(stdin); - /* Under some conditions stdin, stdout and stderr may not be connected - * and fileno() may point to an invalid file descriptor. For example - * GUI apps don't have valid standard streams by default. - */ - if (fd < 0) { + PyObject *iomod = NULL, *wrapper; + PyObject *bimod = NULL; + PyObject *m; + PyObject *std = NULL; + int status = 0, fd; + PyObject * encoding_attr; + char *encoding = NULL, *errors; + + /* Hack to avoid a nasty recursion issue when Python is invoked + in verbose mode: pre-import the Latin-1 and UTF-8 codecs */ + if ((m = PyImport_ImportModule("encodings.utf_8")) == NULL) { + goto error; + } + Py_DECREF(m); + + if (!(m = PyImport_ImportModule("encodings.latin_1"))) { + goto error; + } + Py_DECREF(m); + + if (!(bimod = PyImport_ImportModule("builtins"))) { + goto error; + } + + if (!(iomod = PyImport_ImportModule("io"))) { + goto error; + } + if (!(wrapper = PyObject_GetAttrString(iomod, "OpenWrapper"))) { + goto error; + } + + /* Set builtins.open */ + if (PyObject_SetAttrString(bimod, "open", wrapper) == -1) { + goto error; + } + + encoding = Py_GETENV("PYTHONIOENCODING"); + errors = NULL; + if (encoding) { + encoding = strdup(encoding); + errors = strchr(encoding, ':'); + if (errors) { + *errors = '\0'; + errors++; + } + } + + /* Set sys.stdin */ + fd = fileno(stdin); + /* Under some conditions stdin, stdout and stderr may not be connected + * and fileno() may point to an invalid file descriptor. For example + * GUI apps don't have valid standard streams by default. + */ + if (fd < 0) { #ifdef MS_WINDOWS - std = Py_None; - Py_INCREF(std); + std = Py_None; + Py_INCREF(std); #else - goto error; + goto error; #endif - } - else { - std = create_stdio(iomod, fd, 0, "", encoding, errors); - if (std == NULL) - goto error; - } /* if (fd < 0) */ - PySys_SetObject("__stdin__", std); - PySys_SetObject("stdin", std); - Py_DECREF(std); - - /* Set sys.stdout */ - fd = fileno(stdout); - if (fd < 0) { + } + else { + std = create_stdio(iomod, fd, 0, "", encoding, errors); + if (std == NULL) + goto error; + } /* if (fd < 0) */ + PySys_SetObject("__stdin__", std); + PySys_SetObject("stdin", std); + Py_DECREF(std); + + /* Set sys.stdout */ + fd = fileno(stdout); + if (fd < 0) { #ifdef MS_WINDOWS - std = Py_None; - Py_INCREF(std); + std = Py_None; + Py_INCREF(std); #else - goto error; + goto error; #endif - } - else { - std = create_stdio(iomod, fd, 1, "", encoding, errors); - if (std == NULL) - goto error; - } /* if (fd < 0) */ - PySys_SetObject("__stdout__", std); - PySys_SetObject("stdout", std); - Py_DECREF(std); + } + else { + std = create_stdio(iomod, fd, 1, "", encoding, errors); + if (std == NULL) + goto error; + } /* if (fd < 0) */ + PySys_SetObject("__stdout__", std); + PySys_SetObject("stdout", std); + Py_DECREF(std); #if 1 /* Disable this if you have trouble debugging bootstrap stuff */ - /* Set sys.stderr, replaces the preliminary stderr */ - fd = fileno(stderr); - if (fd < 0) { + /* Set sys.stderr, replaces the preliminary stderr */ + fd = fileno(stderr); + if (fd < 0) { #ifdef MS_WINDOWS - std = Py_None; - Py_INCREF(std); + std = Py_None; + Py_INCREF(std); #else - goto error; + goto error; #endif - } - else { - std = create_stdio(iomod, fd, 1, "", encoding, "backslashreplace"); - if (std == NULL) - goto error; - } /* if (fd < 0) */ - - /* Same as hack above, pre-import stderr's codec to avoid recursion - when import.c tries to write to stderr in verbose mode. */ - encoding_attr = PyObject_GetAttrString(std, "encoding"); - if (encoding_attr != NULL) { - const char * encoding; - encoding = _PyUnicode_AsString(encoding_attr); - if (encoding != NULL) { - _PyCodec_Lookup(encoding); - } - } - PyErr_Clear(); /* Not a fatal error if codec isn't available */ - - PySys_SetObject("__stderr__", std); - PySys_SetObject("stderr", std); - Py_DECREF(std); + } + else { + std = create_stdio(iomod, fd, 1, "", encoding, "backslashreplace"); + if (std == NULL) + goto error; + } /* if (fd < 0) */ + + /* Same as hack above, pre-import stderr's codec to avoid recursion + when import.c tries to write to stderr in verbose mode. */ + encoding_attr = PyObject_GetAttrString(std, "encoding"); + if (encoding_attr != NULL) { + const char * encoding; + encoding = _PyUnicode_AsString(encoding_attr); + if (encoding != NULL) { + _PyCodec_Lookup(encoding); + } + } + PyErr_Clear(); /* Not a fatal error if codec isn't available */ + + PySys_SetObject("__stderr__", std); + PySys_SetObject("stderr", std); + Py_DECREF(std); #endif - if (0) { + if (0) { error: - status = -1; - } + status = -1; + } - if (encoding) - free(encoding); - Py_XDECREF(bimod); - Py_XDECREF(iomod); - return status; + if (encoding) + free(encoding); + Py_XDECREF(bimod); + Py_XDECREF(iomod); + return status; } /* Parse input from a file and execute it */ int PyRun_AnyFileExFlags(FILE *fp, const char *filename, int closeit, - PyCompilerFlags *flags) + PyCompilerFlags *flags) { - if (filename == NULL) - filename = "???"; - if (Py_FdIsInteractive(fp, filename)) { - int err = PyRun_InteractiveLoopFlags(fp, filename, flags); - if (closeit) - fclose(fp); - return err; - } - else - return PyRun_SimpleFileExFlags(fp, filename, closeit, flags); + if (filename == NULL) + filename = "???"; + if (Py_FdIsInteractive(fp, filename)) { + int err = PyRun_InteractiveLoopFlags(fp, filename, flags); + if (closeit) + fclose(fp); + return err; + } + else + return PyRun_SimpleFileExFlags(fp, filename, closeit, flags); } int PyRun_InteractiveLoopFlags(FILE *fp, const char *filename, PyCompilerFlags *flags) { - PyObject *v; - int ret; - PyCompilerFlags local_flags; - - if (flags == NULL) { - flags = &local_flags; - local_flags.cf_flags = 0; - } - v = PySys_GetObject("ps1"); - if (v == NULL) { - PySys_SetObject("ps1", v = PyUnicode_FromString(">>> ")); - Py_XDECREF(v); - } - v = PySys_GetObject("ps2"); - if (v == NULL) { - PySys_SetObject("ps2", v = PyUnicode_FromString("... ")); - Py_XDECREF(v); - } - for (;;) { - ret = PyRun_InteractiveOneFlags(fp, filename, flags); - PRINT_TOTAL_REFS(); - if (ret == E_EOF) - return 0; - /* - if (ret == E_NOMEM) - return -1; - */ - } + PyObject *v; + int ret; + PyCompilerFlags local_flags; + + if (flags == NULL) { + flags = &local_flags; + local_flags.cf_flags = 0; + } + v = PySys_GetObject("ps1"); + if (v == NULL) { + PySys_SetObject("ps1", v = PyUnicode_FromString(">>> ")); + Py_XDECREF(v); + } + v = PySys_GetObject("ps2"); + if (v == NULL) { + PySys_SetObject("ps2", v = PyUnicode_FromString("... ")); + Py_XDECREF(v); + } + for (;;) { + ret = PyRun_InteractiveOneFlags(fp, filename, flags); + PRINT_TOTAL_REFS(); + if (ret == E_EOF) + return 0; + /* + if (ret == E_NOMEM) + return -1; + */ + } } /* compute parser flags based on compiler flags */ static int PARSER_FLAGS(PyCompilerFlags *flags) { - int parser_flags = 0; - if (!flags) - return 0; - if (flags->cf_flags & PyCF_DONT_IMPLY_DEDENT) - parser_flags |= PyPARSE_DONT_IMPLY_DEDENT; - if (flags->cf_flags & PyCF_IGNORE_COOKIE) - parser_flags |= PyPARSE_IGNORE_COOKIE; - if (flags->cf_flags & CO_FUTURE_BARRY_AS_BDFL) - parser_flags |= PyPARSE_BARRY_AS_BDFL; - return parser_flags; + int parser_flags = 0; + if (!flags) + return 0; + if (flags->cf_flags & PyCF_DONT_IMPLY_DEDENT) + parser_flags |= PyPARSE_DONT_IMPLY_DEDENT; + if (flags->cf_flags & PyCF_IGNORE_COOKIE) + parser_flags |= PyPARSE_IGNORE_COOKIE; + if (flags->cf_flags & CO_FUTURE_BARRY_AS_BDFL) + parser_flags |= PyPARSE_BARRY_AS_BDFL; + return parser_flags; } #if 0 /* Keep an example of flags with future keyword support. */ #define PARSER_FLAGS(flags) \ - ((flags) ? ((((flags)->cf_flags & PyCF_DONT_IMPLY_DEDENT) ? \ - PyPARSE_DONT_IMPLY_DEDENT : 0) \ - | ((flags)->cf_flags & CO_FUTURE_WITH_STATEMENT ? \ - PyPARSE_WITH_IS_KEYWORD : 0)) : 0) + ((flags) ? ((((flags)->cf_flags & PyCF_DONT_IMPLY_DEDENT) ? \ + PyPARSE_DONT_IMPLY_DEDENT : 0) \ + | ((flags)->cf_flags & CO_FUTURE_WITH_STATEMENT ? \ + PyPARSE_WITH_IS_KEYWORD : 0)) : 0) #endif int PyRun_InteractiveOneFlags(FILE *fp, const char *filename, PyCompilerFlags *flags) { - PyObject *m, *d, *v, *w, *oenc = NULL; - mod_ty mod; - PyArena *arena; - char *ps1 = "", *ps2 = "", *enc = NULL; - int errcode = 0; - - if (fp == stdin) { - /* Fetch encoding from sys.stdin */ - v = PySys_GetObject("stdin"); - if (v == NULL || v == Py_None) - return -1; - oenc = PyObject_GetAttrString(v, "encoding"); - if (!oenc) - return -1; - enc = _PyUnicode_AsString(oenc); - } - v = PySys_GetObject("ps1"); - if (v != NULL) { - v = PyObject_Str(v); - if (v == NULL) - PyErr_Clear(); - else if (PyUnicode_Check(v)) - ps1 = _PyUnicode_AsString(v); - } - w = PySys_GetObject("ps2"); - if (w != NULL) { - w = PyObject_Str(w); - if (w == NULL) - PyErr_Clear(); - else if (PyUnicode_Check(w)) - ps2 = _PyUnicode_AsString(w); - } - arena = PyArena_New(); - if (arena == NULL) { - Py_XDECREF(v); - Py_XDECREF(w); - Py_XDECREF(oenc); - return -1; - } - mod = PyParser_ASTFromFile(fp, filename, enc, - Py_single_input, ps1, ps2, - flags, &errcode, arena); - Py_XDECREF(v); - Py_XDECREF(w); - Py_XDECREF(oenc); - if (mod == NULL) { - PyArena_Free(arena); - if (errcode == E_EOF) { - PyErr_Clear(); - return E_EOF; - } - PyErr_Print(); - return -1; - } - m = PyImport_AddModule("__main__"); - if (m == NULL) { - PyArena_Free(arena); - return -1; - } - d = PyModule_GetDict(m); - v = run_mod(mod, filename, d, d, flags, arena); - PyArena_Free(arena); - flush_io(); - if (v == NULL) { - PyErr_Print(); - return -1; - } - Py_DECREF(v); - return 0; + PyObject *m, *d, *v, *w, *oenc = NULL; + mod_ty mod; + PyArena *arena; + char *ps1 = "", *ps2 = "", *enc = NULL; + int errcode = 0; + + if (fp == stdin) { + /* Fetch encoding from sys.stdin */ + v = PySys_GetObject("stdin"); + if (v == NULL || v == Py_None) + return -1; + oenc = PyObject_GetAttrString(v, "encoding"); + if (!oenc) + return -1; + enc = _PyUnicode_AsString(oenc); + } + v = PySys_GetObject("ps1"); + if (v != NULL) { + v = PyObject_Str(v); + if (v == NULL) + PyErr_Clear(); + else if (PyUnicode_Check(v)) + ps1 = _PyUnicode_AsString(v); + } + w = PySys_GetObject("ps2"); + if (w != NULL) { + w = PyObject_Str(w); + if (w == NULL) + PyErr_Clear(); + else if (PyUnicode_Check(w)) + ps2 = _PyUnicode_AsString(w); + } + arena = PyArena_New(); + if (arena == NULL) { + Py_XDECREF(v); + Py_XDECREF(w); + Py_XDECREF(oenc); + return -1; + } + mod = PyParser_ASTFromFile(fp, filename, enc, + Py_single_input, ps1, ps2, + flags, &errcode, arena); + Py_XDECREF(v); + Py_XDECREF(w); + Py_XDECREF(oenc); + if (mod == NULL) { + PyArena_Free(arena); + if (errcode == E_EOF) { + PyErr_Clear(); + return E_EOF; + } + PyErr_Print(); + return -1; + } + m = PyImport_AddModule("__main__"); + if (m == NULL) { + PyArena_Free(arena); + return -1; + } + d = PyModule_GetDict(m); + v = run_mod(mod, filename, d, d, flags, arena); + PyArena_Free(arena); + flush_io(); + if (v == NULL) { + PyErr_Print(); + return -1; + } + Py_DECREF(v); + return 0; } /* Check whether a file maybe a pyc file: Look at the extension, @@ -1100,739 +1100,739 @@ static int maybe_pyc_file(FILE *fp, const char* filename, const char* ext, int closeit) { - if (strcmp(ext, ".pyc") == 0 || strcmp(ext, ".pyo") == 0) - return 1; + if (strcmp(ext, ".pyc") == 0 || strcmp(ext, ".pyo") == 0) + return 1; - /* Only look into the file if we are allowed to close it, since - it then should also be seekable. */ - if (closeit) { - /* Read only two bytes of the magic. If the file was opened in - text mode, the bytes 3 and 4 of the magic (\r\n) might not - be read as they are on disk. */ - unsigned int halfmagic = PyImport_GetMagicNumber() & 0xFFFF; - unsigned char buf[2]; - /* Mess: In case of -x, the stream is NOT at its start now, - and ungetc() was used to push back the first newline, - which makes the current stream position formally undefined, - and a x-platform nightmare. - Unfortunately, we have no direct way to know whether -x - was specified. So we use a terrible hack: if the current - stream position is not 0, we assume -x was specified, and - give up. Bug 132850 on SourceForge spells out the - hopelessness of trying anything else (fseek and ftell - don't work predictably x-platform for text-mode files). - */ - int ispyc = 0; - if (ftell(fp) == 0) { - if (fread(buf, 1, 2, fp) == 2 && - ((unsigned int)buf[1]<<8 | buf[0]) == halfmagic) - ispyc = 1; - rewind(fp); - } - return ispyc; - } - return 0; + /* Only look into the file if we are allowed to close it, since + it then should also be seekable. */ + if (closeit) { + /* Read only two bytes of the magic. If the file was opened in + text mode, the bytes 3 and 4 of the magic (\r\n) might not + be read as they are on disk. */ + unsigned int halfmagic = PyImport_GetMagicNumber() & 0xFFFF; + unsigned char buf[2]; + /* Mess: In case of -x, the stream is NOT at its start now, + and ungetc() was used to push back the first newline, + which makes the current stream position formally undefined, + and a x-platform nightmare. + Unfortunately, we have no direct way to know whether -x + was specified. So we use a terrible hack: if the current + stream position is not 0, we assume -x was specified, and + give up. Bug 132850 on SourceForge spells out the + hopelessness of trying anything else (fseek and ftell + don't work predictably x-platform for text-mode files). + */ + int ispyc = 0; + if (ftell(fp) == 0) { + if (fread(buf, 1, 2, fp) == 2 && + ((unsigned int)buf[1]<<8 | buf[0]) == halfmagic) + ispyc = 1; + rewind(fp); + } + return ispyc; + } + return 0; } int PyRun_SimpleFileExFlags(FILE *fp, const char *filename, int closeit, - PyCompilerFlags *flags) + PyCompilerFlags *flags) { - PyObject *m, *d, *v; - const char *ext; - int set_file_name = 0, ret, len; - - m = PyImport_AddModule("__main__"); - if (m == NULL) - return -1; - d = PyModule_GetDict(m); - if (PyDict_GetItemString(d, "__file__") == NULL) { - PyObject *f; - f = PyUnicode_DecodeFSDefault(filename); - if (f == NULL) - return -1; - if (PyDict_SetItemString(d, "__file__", f) < 0) { - Py_DECREF(f); - return -1; - } - if (PyDict_SetItemString(d, "__cached__", Py_None) < 0) - return -1; - set_file_name = 1; - Py_DECREF(f); - } - len = strlen(filename); - ext = filename + len - (len > 4 ? 4 : 0); - if (maybe_pyc_file(fp, filename, ext, closeit)) { - /* Try to run a pyc file. First, re-open in binary */ - if (closeit) - fclose(fp); - if ((fp = fopen(filename, "rb")) == NULL) { - fprintf(stderr, "python: Can't reopen .pyc file\n"); - ret = -1; - goto done; - } - /* Turn on optimization if a .pyo file is given */ - if (strcmp(ext, ".pyo") == 0) - Py_OptimizeFlag = 1; - v = run_pyc_file(fp, filename, d, d, flags); - } else { - v = PyRun_FileExFlags(fp, filename, Py_file_input, d, d, - closeit, flags); - } - flush_io(); - if (v == NULL) { - PyErr_Print(); - ret = -1; - goto done; - } - Py_DECREF(v); - ret = 0; + PyObject *m, *d, *v; + const char *ext; + int set_file_name = 0, ret, len; + + m = PyImport_AddModule("__main__"); + if (m == NULL) + return -1; + d = PyModule_GetDict(m); + if (PyDict_GetItemString(d, "__file__") == NULL) { + PyObject *f; + f = PyUnicode_DecodeFSDefault(filename); + if (f == NULL) + return -1; + if (PyDict_SetItemString(d, "__file__", f) < 0) { + Py_DECREF(f); + return -1; + } + if (PyDict_SetItemString(d, "__cached__", Py_None) < 0) + return -1; + set_file_name = 1; + Py_DECREF(f); + } + len = strlen(filename); + ext = filename + len - (len > 4 ? 4 : 0); + if (maybe_pyc_file(fp, filename, ext, closeit)) { + /* Try to run a pyc file. First, re-open in binary */ + if (closeit) + fclose(fp); + if ((fp = fopen(filename, "rb")) == NULL) { + fprintf(stderr, "python: Can't reopen .pyc file\n"); + ret = -1; + goto done; + } + /* Turn on optimization if a .pyo file is given */ + if (strcmp(ext, ".pyo") == 0) + Py_OptimizeFlag = 1; + v = run_pyc_file(fp, filename, d, d, flags); + } else { + v = PyRun_FileExFlags(fp, filename, Py_file_input, d, d, + closeit, flags); + } + flush_io(); + if (v == NULL) { + PyErr_Print(); + ret = -1; + goto done; + } + Py_DECREF(v); + ret = 0; done: - if (set_file_name && PyDict_DelItemString(d, "__file__")) - PyErr_Clear(); - return ret; + if (set_file_name && PyDict_DelItemString(d, "__file__")) + PyErr_Clear(); + return ret; } int PyRun_SimpleStringFlags(const char *command, PyCompilerFlags *flags) { - PyObject *m, *d, *v; - m = PyImport_AddModule("__main__"); - if (m == NULL) - return -1; - d = PyModule_GetDict(m); - v = PyRun_StringFlags(command, Py_file_input, d, d, flags); - if (v == NULL) { - PyErr_Print(); - return -1; - } - Py_DECREF(v); - return 0; + PyObject *m, *d, *v; + m = PyImport_AddModule("__main__"); + if (m == NULL) + return -1; + d = PyModule_GetDict(m); + v = PyRun_StringFlags(command, Py_file_input, d, d, flags); + if (v == NULL) { + PyErr_Print(); + return -1; + } + Py_DECREF(v); + return 0; } static int parse_syntax_error(PyObject *err, PyObject **message, const char **filename, - int *lineno, int *offset, const char **text) + int *lineno, int *offset, const char **text) { - long hold; - PyObject *v; + long hold; + PyObject *v; - /* old style errors */ - if (PyTuple_Check(err)) - return PyArg_ParseTuple(err, "O(ziiz)", message, filename, - lineno, offset, text); - - /* new style errors. `err' is an instance */ - - if (! (v = PyObject_GetAttrString(err, "msg"))) - goto finally; - *message = v; - - if (!(v = PyObject_GetAttrString(err, "filename"))) - goto finally; - if (v == Py_None) - *filename = NULL; - else if (! (*filename = _PyUnicode_AsString(v))) - goto finally; - - Py_DECREF(v); - if (!(v = PyObject_GetAttrString(err, "lineno"))) - goto finally; - hold = PyLong_AsLong(v); - Py_DECREF(v); - v = NULL; - if (hold < 0 && PyErr_Occurred()) - goto finally; - *lineno = (int)hold; - - if (!(v = PyObject_GetAttrString(err, "offset"))) - goto finally; - if (v == Py_None) { - *offset = -1; - Py_DECREF(v); - v = NULL; - } else { - hold = PyLong_AsLong(v); - Py_DECREF(v); - v = NULL; - if (hold < 0 && PyErr_Occurred()) - goto finally; - *offset = (int)hold; - } - - if (!(v = PyObject_GetAttrString(err, "text"))) - goto finally; - if (v == Py_None) - *text = NULL; - else if (!PyUnicode_Check(v) || - !(*text = _PyUnicode_AsString(v))) - goto finally; - Py_DECREF(v); - return 1; + /* old style errors */ + if (PyTuple_Check(err)) + return PyArg_ParseTuple(err, "O(ziiz)", message, filename, + lineno, offset, text); + + /* new style errors. `err' is an instance */ + + if (! (v = PyObject_GetAttrString(err, "msg"))) + goto finally; + *message = v; + + if (!(v = PyObject_GetAttrString(err, "filename"))) + goto finally; + if (v == Py_None) + *filename = NULL; + else if (! (*filename = _PyUnicode_AsString(v))) + goto finally; + + Py_DECREF(v); + if (!(v = PyObject_GetAttrString(err, "lineno"))) + goto finally; + hold = PyLong_AsLong(v); + Py_DECREF(v); + v = NULL; + if (hold < 0 && PyErr_Occurred()) + goto finally; + *lineno = (int)hold; + + if (!(v = PyObject_GetAttrString(err, "offset"))) + goto finally; + if (v == Py_None) { + *offset = -1; + Py_DECREF(v); + v = NULL; + } else { + hold = PyLong_AsLong(v); + Py_DECREF(v); + v = NULL; + if (hold < 0 && PyErr_Occurred()) + goto finally; + *offset = (int)hold; + } + + if (!(v = PyObject_GetAttrString(err, "text"))) + goto finally; + if (v == Py_None) + *text = NULL; + else if (!PyUnicode_Check(v) || + !(*text = _PyUnicode_AsString(v))) + goto finally; + Py_DECREF(v); + return 1; finally: - Py_XDECREF(v); - return 0; + Py_XDECREF(v); + return 0; } void PyErr_Print(void) { - PyErr_PrintEx(1); + PyErr_PrintEx(1); } static void print_error_text(PyObject *f, int offset, const char *text) { - char *nl; - if (offset >= 0) { - if (offset > 0 && offset == (int)strlen(text)) - offset--; - for (;;) { - nl = strchr(text, '\n'); - if (nl == NULL || nl-text >= offset) - break; - offset -= (int)(nl+1-text); - text = nl+1; - } - while (*text == ' ' || *text == '\t') { - text++; - offset--; - } - } - PyFile_WriteString(" ", f); - PyFile_WriteString(text, f); - if (*text == '\0' || text[strlen(text)-1] != '\n') - PyFile_WriteString("\n", f); - if (offset == -1) - return; - PyFile_WriteString(" ", f); - offset--; - while (offset > 0) { - PyFile_WriteString(" ", f); - offset--; - } - PyFile_WriteString("^\n", f); + char *nl; + if (offset >= 0) { + if (offset > 0 && offset == (int)strlen(text)) + offset--; + for (;;) { + nl = strchr(text, '\n'); + if (nl == NULL || nl-text >= offset) + break; + offset -= (int)(nl+1-text); + text = nl+1; + } + while (*text == ' ' || *text == '\t') { + text++; + offset--; + } + } + PyFile_WriteString(" ", f); + PyFile_WriteString(text, f); + if (*text == '\0' || text[strlen(text)-1] != '\n') + PyFile_WriteString("\n", f); + if (offset == -1) + return; + PyFile_WriteString(" ", f); + offset--; + while (offset > 0) { + PyFile_WriteString(" ", f); + offset--; + } + PyFile_WriteString("^\n", f); } static void handle_system_exit(void) { - PyObject *exception, *value, *tb; - int exitcode = 0; + PyObject *exception, *value, *tb; + int exitcode = 0; - if (Py_InspectFlag) - /* Don't exit if -i flag was given. This flag is set to 0 - * when entering interactive mode for inspecting. */ - return; - - PyErr_Fetch(&exception, &value, &tb); - fflush(stdout); - if (value == NULL || value == Py_None) - goto done; - if (PyExceptionInstance_Check(value)) { - /* The error code should be in the `code' attribute. */ - PyObject *code = PyObject_GetAttrString(value, "code"); - if (code) { - Py_DECREF(value); - value = code; - if (value == Py_None) - goto done; - } - /* If we failed to dig out the 'code' attribute, - just let the else clause below print the error. */ - } - if (PyLong_Check(value)) - exitcode = (int)PyLong_AsLong(value); - else { - PyObject_Print(value, stderr, Py_PRINT_RAW); - PySys_WriteStderr("\n"); - exitcode = 1; - } + if (Py_InspectFlag) + /* Don't exit if -i flag was given. This flag is set to 0 + * when entering interactive mode for inspecting. */ + return; + + PyErr_Fetch(&exception, &value, &tb); + fflush(stdout); + if (value == NULL || value == Py_None) + goto done; + if (PyExceptionInstance_Check(value)) { + /* The error code should be in the `code' attribute. */ + PyObject *code = PyObject_GetAttrString(value, "code"); + if (code) { + Py_DECREF(value); + value = code; + if (value == Py_None) + goto done; + } + /* If we failed to dig out the 'code' attribute, + just let the else clause below print the error. */ + } + if (PyLong_Check(value)) + exitcode = (int)PyLong_AsLong(value); + else { + PyObject_Print(value, stderr, Py_PRINT_RAW); + PySys_WriteStderr("\n"); + exitcode = 1; + } done: - /* Restore and clear the exception info, in order to properly decref - * the exception, value, and traceback. If we just exit instead, - * these leak, which confuses PYTHONDUMPREFS output, and may prevent - * some finalizers from running. - */ - PyErr_Restore(exception, value, tb); - PyErr_Clear(); - Py_Exit(exitcode); - /* NOTREACHED */ + /* Restore and clear the exception info, in order to properly decref + * the exception, value, and traceback. If we just exit instead, + * these leak, which confuses PYTHONDUMPREFS output, and may prevent + * some finalizers from running. + */ + PyErr_Restore(exception, value, tb); + PyErr_Clear(); + Py_Exit(exitcode); + /* NOTREACHED */ } void PyErr_PrintEx(int set_sys_last_vars) { - PyObject *exception, *v, *tb, *hook; + PyObject *exception, *v, *tb, *hook; - if (PyErr_ExceptionMatches(PyExc_SystemExit)) { - handle_system_exit(); - } - PyErr_Fetch(&exception, &v, &tb); - if (exception == NULL) - return; - PyErr_NormalizeException(&exception, &v, &tb); - if (tb == NULL) { - tb = Py_None; - Py_INCREF(tb); - } - PyException_SetTraceback(v, tb); - if (exception == NULL) - return; - /* Now we know v != NULL too */ - if (set_sys_last_vars) { - PySys_SetObject("last_type", exception); - PySys_SetObject("last_value", v); - PySys_SetObject("last_traceback", tb); - } - hook = PySys_GetObject("excepthook"); - if (hook) { - PyObject *args = PyTuple_Pack(3, exception, v, tb); - PyObject *result = PyEval_CallObject(hook, args); - if (result == NULL) { - PyObject *exception2, *v2, *tb2; - if (PyErr_ExceptionMatches(PyExc_SystemExit)) { - handle_system_exit(); - } - PyErr_Fetch(&exception2, &v2, &tb2); - PyErr_NormalizeException(&exception2, &v2, &tb2); - /* It should not be possible for exception2 or v2 - to be NULL. However PyErr_Display() can't - tolerate NULLs, so just be safe. */ - if (exception2 == NULL) { - exception2 = Py_None; - Py_INCREF(exception2); - } - if (v2 == NULL) { - v2 = Py_None; - Py_INCREF(v2); - } - fflush(stdout); - PySys_WriteStderr("Error in sys.excepthook:\n"); - PyErr_Display(exception2, v2, tb2); - PySys_WriteStderr("\nOriginal exception was:\n"); - PyErr_Display(exception, v, tb); - Py_DECREF(exception2); - Py_DECREF(v2); - Py_XDECREF(tb2); - } - Py_XDECREF(result); - Py_XDECREF(args); - } else { - PySys_WriteStderr("sys.excepthook is missing\n"); - PyErr_Display(exception, v, tb); - } - Py_XDECREF(exception); - Py_XDECREF(v); - Py_XDECREF(tb); + if (PyErr_ExceptionMatches(PyExc_SystemExit)) { + handle_system_exit(); + } + PyErr_Fetch(&exception, &v, &tb); + if (exception == NULL) + return; + PyErr_NormalizeException(&exception, &v, &tb); + if (tb == NULL) { + tb = Py_None; + Py_INCREF(tb); + } + PyException_SetTraceback(v, tb); + if (exception == NULL) + return; + /* Now we know v != NULL too */ + if (set_sys_last_vars) { + PySys_SetObject("last_type", exception); + PySys_SetObject("last_value", v); + PySys_SetObject("last_traceback", tb); + } + hook = PySys_GetObject("excepthook"); + if (hook) { + PyObject *args = PyTuple_Pack(3, exception, v, tb); + PyObject *result = PyEval_CallObject(hook, args); + if (result == NULL) { + PyObject *exception2, *v2, *tb2; + if (PyErr_ExceptionMatches(PyExc_SystemExit)) { + handle_system_exit(); + } + PyErr_Fetch(&exception2, &v2, &tb2); + PyErr_NormalizeException(&exception2, &v2, &tb2); + /* It should not be possible for exception2 or v2 + to be NULL. However PyErr_Display() can't + tolerate NULLs, so just be safe. */ + if (exception2 == NULL) { + exception2 = Py_None; + Py_INCREF(exception2); + } + if (v2 == NULL) { + v2 = Py_None; + Py_INCREF(v2); + } + fflush(stdout); + PySys_WriteStderr("Error in sys.excepthook:\n"); + PyErr_Display(exception2, v2, tb2); + PySys_WriteStderr("\nOriginal exception was:\n"); + PyErr_Display(exception, v, tb); + Py_DECREF(exception2); + Py_DECREF(v2); + Py_XDECREF(tb2); + } + Py_XDECREF(result); + Py_XDECREF(args); + } else { + PySys_WriteStderr("sys.excepthook is missing\n"); + PyErr_Display(exception, v, tb); + } + Py_XDECREF(exception); + Py_XDECREF(v); + Py_XDECREF(tb); } static void print_exception(PyObject *f, PyObject *value) { - int err = 0; - PyObject *type, *tb; + int err = 0; + PyObject *type, *tb; - if (!PyExceptionInstance_Check(value)) { - PyFile_WriteString("TypeError: print_exception(): Exception expected for value, ", f); - PyFile_WriteString(Py_TYPE(value)->tp_name, f); - PyFile_WriteString(" found\n", f); - return; - } - - Py_INCREF(value); - fflush(stdout); - type = (PyObject *) Py_TYPE(value); - tb = PyException_GetTraceback(value); - if (tb && tb != Py_None) - err = PyTraceBack_Print(tb, f); - if (err == 0 && - PyObject_HasAttrString(value, "print_file_and_line")) - { - PyObject *message; - const char *filename, *text; - int lineno, offset; - if (!parse_syntax_error(value, &message, &filename, - &lineno, &offset, &text)) - PyErr_Clear(); - else { - char buf[10]; - PyFile_WriteString(" File \"", f); - if (filename == NULL) - PyFile_WriteString("", f); - else - PyFile_WriteString(filename, f); - PyFile_WriteString("\", line ", f); - PyOS_snprintf(buf, sizeof(buf), "%d", lineno); - PyFile_WriteString(buf, f); - PyFile_WriteString("\n", f); - if (text != NULL) - print_error_text(f, offset, text); - Py_DECREF(value); - value = message; - /* Can't be bothered to check all those - PyFile_WriteString() calls */ - if (PyErr_Occurred()) - err = -1; - } - } - if (err) { - /* Don't do anything else */ - } - else { - PyObject* moduleName; - char* className; - assert(PyExceptionClass_Check(type)); - className = PyExceptionClass_Name(type); - if (className != NULL) { - char *dot = strrchr(className, '.'); - if (dot != NULL) - className = dot+1; - } - - moduleName = PyObject_GetAttrString(type, "__module__"); - if (moduleName == NULL || !PyUnicode_Check(moduleName)) - { - Py_DECREF(moduleName); - err = PyFile_WriteString("", f); - } - else { - char* modstr = _PyUnicode_AsString(moduleName); - if (modstr && strcmp(modstr, "builtins")) - { - err = PyFile_WriteString(modstr, f); - err += PyFile_WriteString(".", f); - } - Py_DECREF(moduleName); - } - if (err == 0) { - if (className == NULL) - err = PyFile_WriteString("", f); - else - err = PyFile_WriteString(className, f); - } - } - if (err == 0 && (value != Py_None)) { - PyObject *s = PyObject_Str(value); - /* only print colon if the str() of the - object is not the empty string - */ - if (s == NULL) - err = -1; - else if (!PyUnicode_Check(s) || - PyUnicode_GetSize(s) != 0) - err = PyFile_WriteString(": ", f); - if (err == 0) - err = PyFile_WriteObject(s, f, Py_PRINT_RAW); - Py_XDECREF(s); - } - /* try to write a newline in any case */ - err += PyFile_WriteString("\n", f); - Py_XDECREF(tb); - Py_DECREF(value); - /* If an error happened here, don't show it. - XXX This is wrong, but too many callers rely on this behavior. */ - if (err != 0) - PyErr_Clear(); + if (!PyExceptionInstance_Check(value)) { + PyFile_WriteString("TypeError: print_exception(): Exception expected for value, ", f); + PyFile_WriteString(Py_TYPE(value)->tp_name, f); + PyFile_WriteString(" found\n", f); + return; + } + + Py_INCREF(value); + fflush(stdout); + type = (PyObject *) Py_TYPE(value); + tb = PyException_GetTraceback(value); + if (tb && tb != Py_None) + err = PyTraceBack_Print(tb, f); + if (err == 0 && + PyObject_HasAttrString(value, "print_file_and_line")) + { + PyObject *message; + const char *filename, *text; + int lineno, offset; + if (!parse_syntax_error(value, &message, &filename, + &lineno, &offset, &text)) + PyErr_Clear(); + else { + char buf[10]; + PyFile_WriteString(" File \"", f); + if (filename == NULL) + PyFile_WriteString("", f); + else + PyFile_WriteString(filename, f); + PyFile_WriteString("\", line ", f); + PyOS_snprintf(buf, sizeof(buf), "%d", lineno); + PyFile_WriteString(buf, f); + PyFile_WriteString("\n", f); + if (text != NULL) + print_error_text(f, offset, text); + Py_DECREF(value); + value = message; + /* Can't be bothered to check all those + PyFile_WriteString() calls */ + if (PyErr_Occurred()) + err = -1; + } + } + if (err) { + /* Don't do anything else */ + } + else { + PyObject* moduleName; + char* className; + assert(PyExceptionClass_Check(type)); + className = PyExceptionClass_Name(type); + if (className != NULL) { + char *dot = strrchr(className, '.'); + if (dot != NULL) + className = dot+1; + } + + moduleName = PyObject_GetAttrString(type, "__module__"); + if (moduleName == NULL || !PyUnicode_Check(moduleName)) + { + Py_DECREF(moduleName); + err = PyFile_WriteString("", f); + } + else { + char* modstr = _PyUnicode_AsString(moduleName); + if (modstr && strcmp(modstr, "builtins")) + { + err = PyFile_WriteString(modstr, f); + err += PyFile_WriteString(".", f); + } + Py_DECREF(moduleName); + } + if (err == 0) { + if (className == NULL) + err = PyFile_WriteString("", f); + else + err = PyFile_WriteString(className, f); + } + } + if (err == 0 && (value != Py_None)) { + PyObject *s = PyObject_Str(value); + /* only print colon if the str() of the + object is not the empty string + */ + if (s == NULL) + err = -1; + else if (!PyUnicode_Check(s) || + PyUnicode_GetSize(s) != 0) + err = PyFile_WriteString(": ", f); + if (err == 0) + err = PyFile_WriteObject(s, f, Py_PRINT_RAW); + Py_XDECREF(s); + } + /* try to write a newline in any case */ + err += PyFile_WriteString("\n", f); + Py_XDECREF(tb); + Py_DECREF(value); + /* If an error happened here, don't show it. + XXX This is wrong, but too many callers rely on this behavior. */ + if (err != 0) + PyErr_Clear(); } static const char *cause_message = - "\nThe above exception was the direct cause " - "of the following exception:\n\n"; + "\nThe above exception was the direct cause " + "of the following exception:\n\n"; static const char *context_message = - "\nDuring handling of the above exception, " - "another exception occurred:\n\n"; + "\nDuring handling of the above exception, " + "another exception occurred:\n\n"; static void print_exception_recursive(PyObject *f, PyObject *value, PyObject *seen) { - int err = 0, res; - PyObject *cause, *context; + int err = 0, res; + PyObject *cause, *context; - if (seen != NULL) { - /* Exception chaining */ - if (PySet_Add(seen, value) == -1) - PyErr_Clear(); - else if (PyExceptionInstance_Check(value)) { - cause = PyException_GetCause(value); - context = PyException_GetContext(value); - if (cause) { - res = PySet_Contains(seen, cause); - if (res == -1) - PyErr_Clear(); - if (res == 0) { - print_exception_recursive( - f, cause, seen); - err |= PyFile_WriteString( - cause_message, f); - } - } - else if (context) { - res = PySet_Contains(seen, context); - if (res == -1) - PyErr_Clear(); - if (res == 0) { - print_exception_recursive( - f, context, seen); - err |= PyFile_WriteString( - context_message, f); - } - } - Py_XDECREF(context); - Py_XDECREF(cause); - } - } - print_exception(f, value); - if (err != 0) - PyErr_Clear(); + if (seen != NULL) { + /* Exception chaining */ + if (PySet_Add(seen, value) == -1) + PyErr_Clear(); + else if (PyExceptionInstance_Check(value)) { + cause = PyException_GetCause(value); + context = PyException_GetContext(value); + if (cause) { + res = PySet_Contains(seen, cause); + if (res == -1) + PyErr_Clear(); + if (res == 0) { + print_exception_recursive( + f, cause, seen); + err |= PyFile_WriteString( + cause_message, f); + } + } + else if (context) { + res = PySet_Contains(seen, context); + if (res == -1) + PyErr_Clear(); + if (res == 0) { + print_exception_recursive( + f, context, seen); + err |= PyFile_WriteString( + context_message, f); + } + } + Py_XDECREF(context); + Py_XDECREF(cause); + } + } + print_exception(f, value); + if (err != 0) + PyErr_Clear(); } void PyErr_Display(PyObject *exception, PyObject *value, PyObject *tb) { - PyObject *seen; - PyObject *f = PySys_GetObject("stderr"); - if (f == Py_None) { - /* pass */ - } - else if (f == NULL) { - _PyObject_Dump(value); - fprintf(stderr, "lost sys.stderr\n"); - } - else { - /* We choose to ignore seen being possibly NULL, and report - at least the main exception (it could be a MemoryError). - */ - seen = PySet_New(NULL); - if (seen == NULL) - PyErr_Clear(); - print_exception_recursive(f, value, seen); - Py_XDECREF(seen); - } + PyObject *seen; + PyObject *f = PySys_GetObject("stderr"); + if (f == Py_None) { + /* pass */ + } + else if (f == NULL) { + _PyObject_Dump(value); + fprintf(stderr, "lost sys.stderr\n"); + } + else { + /* We choose to ignore seen being possibly NULL, and report + at least the main exception (it could be a MemoryError). + */ + seen = PySet_New(NULL); + if (seen == NULL) + PyErr_Clear(); + print_exception_recursive(f, value, seen); + Py_XDECREF(seen); + } } PyObject * PyRun_StringFlags(const char *str, int start, PyObject *globals, - PyObject *locals, PyCompilerFlags *flags) + PyObject *locals, PyCompilerFlags *flags) { - PyObject *ret = NULL; - mod_ty mod; - PyArena *arena = PyArena_New(); - if (arena == NULL) - return NULL; - - mod = PyParser_ASTFromString(str, "", start, flags, arena); - if (mod != NULL) - ret = run_mod(mod, "", globals, locals, flags, arena); - PyArena_Free(arena); - return ret; + PyObject *ret = NULL; + mod_ty mod; + PyArena *arena = PyArena_New(); + if (arena == NULL) + return NULL; + + mod = PyParser_ASTFromString(str, "", start, flags, arena); + if (mod != NULL) + ret = run_mod(mod, "", globals, locals, flags, arena); + PyArena_Free(arena); + return ret; } PyObject * PyRun_FileExFlags(FILE *fp, const char *filename, int start, PyObject *globals, - PyObject *locals, int closeit, PyCompilerFlags *flags) + PyObject *locals, int closeit, PyCompilerFlags *flags) { - PyObject *ret; - mod_ty mod; - PyArena *arena = PyArena_New(); - if (arena == NULL) - return NULL; - - mod = PyParser_ASTFromFile(fp, filename, NULL, start, 0, 0, - flags, NULL, arena); - if (closeit) - fclose(fp); - if (mod == NULL) { - PyArena_Free(arena); - return NULL; - } - ret = run_mod(mod, filename, globals, locals, flags, arena); - PyArena_Free(arena); - return ret; + PyObject *ret; + mod_ty mod; + PyArena *arena = PyArena_New(); + if (arena == NULL) + return NULL; + + mod = PyParser_ASTFromFile(fp, filename, NULL, start, 0, 0, + flags, NULL, arena); + if (closeit) + fclose(fp); + if (mod == NULL) { + PyArena_Free(arena); + return NULL; + } + ret = run_mod(mod, filename, globals, locals, flags, arena); + PyArena_Free(arena); + return ret; } static void flush_io(void) { - PyObject *f, *r; - PyObject *type, *value, *traceback; + PyObject *f, *r; + PyObject *type, *value, *traceback; - /* Save the current exception */ - PyErr_Fetch(&type, &value, &traceback); + /* Save the current exception */ + PyErr_Fetch(&type, &value, &traceback); - f = PySys_GetObject("stderr"); - if (f != NULL) { - r = PyObject_CallMethod(f, "flush", ""); - if (r) - Py_DECREF(r); - else - PyErr_Clear(); - } - f = PySys_GetObject("stdout"); - if (f != NULL) { - r = PyObject_CallMethod(f, "flush", ""); - if (r) - Py_DECREF(r); - else - PyErr_Clear(); - } + f = PySys_GetObject("stderr"); + if (f != NULL) { + r = PyObject_CallMethod(f, "flush", ""); + if (r) + Py_DECREF(r); + else + PyErr_Clear(); + } + f = PySys_GetObject("stdout"); + if (f != NULL) { + r = PyObject_CallMethod(f, "flush", ""); + if (r) + Py_DECREF(r); + else + PyErr_Clear(); + } - PyErr_Restore(type, value, traceback); + PyErr_Restore(type, value, traceback); } static PyObject * run_mod(mod_ty mod, const char *filename, PyObject *globals, PyObject *locals, - PyCompilerFlags *flags, PyArena *arena) + PyCompilerFlags *flags, PyArena *arena) { - PyCodeObject *co; - PyObject *v; - co = PyAST_Compile(mod, filename, flags, arena); - if (co == NULL) - return NULL; - v = PyEval_EvalCode(co, globals, locals); - Py_DECREF(co); - return v; + PyCodeObject *co; + PyObject *v; + co = PyAST_Compile(mod, filename, flags, arena); + if (co == NULL) + return NULL; + v = PyEval_EvalCode(co, globals, locals); + Py_DECREF(co); + return v; } static PyObject * run_pyc_file(FILE *fp, const char *filename, PyObject *globals, - PyObject *locals, PyCompilerFlags *flags) + PyObject *locals, PyCompilerFlags *flags) { - PyCodeObject *co; - PyObject *v; - long magic; - long PyImport_GetMagicNumber(void); - - magic = PyMarshal_ReadLongFromFile(fp); - if (magic != PyImport_GetMagicNumber()) { - PyErr_SetString(PyExc_RuntimeError, - "Bad magic number in .pyc file"); - return NULL; - } - (void) PyMarshal_ReadLongFromFile(fp); - v = PyMarshal_ReadLastObjectFromFile(fp); - fclose(fp); - if (v == NULL || !PyCode_Check(v)) { - Py_XDECREF(v); - PyErr_SetString(PyExc_RuntimeError, - "Bad code object in .pyc file"); - return NULL; - } - co = (PyCodeObject *)v; - v = PyEval_EvalCode(co, globals, locals); - if (v && flags) - flags->cf_flags |= (co->co_flags & PyCF_MASK); - Py_DECREF(co); - return v; + PyCodeObject *co; + PyObject *v; + long magic; + long PyImport_GetMagicNumber(void); + + magic = PyMarshal_ReadLongFromFile(fp); + if (magic != PyImport_GetMagicNumber()) { + PyErr_SetString(PyExc_RuntimeError, + "Bad magic number in .pyc file"); + return NULL; + } + (void) PyMarshal_ReadLongFromFile(fp); + v = PyMarshal_ReadLastObjectFromFile(fp); + fclose(fp); + if (v == NULL || !PyCode_Check(v)) { + Py_XDECREF(v); + PyErr_SetString(PyExc_RuntimeError, + "Bad code object in .pyc file"); + return NULL; + } + co = (PyCodeObject *)v; + v = PyEval_EvalCode(co, globals, locals); + if (v && flags) + flags->cf_flags |= (co->co_flags & PyCF_MASK); + Py_DECREF(co); + return v; } PyObject * Py_CompileStringFlags(const char *str, const char *filename, int start, - PyCompilerFlags *flags) + PyCompilerFlags *flags) { - PyCodeObject *co; - mod_ty mod; - PyArena *arena = PyArena_New(); - if (arena == NULL) - return NULL; - - mod = PyParser_ASTFromString(str, filename, start, flags, arena); - if (mod == NULL) { - PyArena_Free(arena); - return NULL; - } - if (flags && (flags->cf_flags & PyCF_ONLY_AST)) { - PyObject *result = PyAST_mod2obj(mod); - PyArena_Free(arena); - return result; - } - co = PyAST_Compile(mod, filename, flags, arena); - PyArena_Free(arena); - return (PyObject *)co; + PyCodeObject *co; + mod_ty mod; + PyArena *arena = PyArena_New(); + if (arena == NULL) + return NULL; + + mod = PyParser_ASTFromString(str, filename, start, flags, arena); + if (mod == NULL) { + PyArena_Free(arena); + return NULL; + } + if (flags && (flags->cf_flags & PyCF_ONLY_AST)) { + PyObject *result = PyAST_mod2obj(mod); + PyArena_Free(arena); + return result; + } + co = PyAST_Compile(mod, filename, flags, arena); + PyArena_Free(arena); + return (PyObject *)co; } struct symtable * Py_SymtableString(const char *str, const char *filename, int start) { - struct symtable *st; - mod_ty mod; - PyCompilerFlags flags; - PyArena *arena = PyArena_New(); - if (arena == NULL) - return NULL; - - flags.cf_flags = 0; - mod = PyParser_ASTFromString(str, filename, start, &flags, arena); - if (mod == NULL) { - PyArena_Free(arena); - return NULL; - } - st = PySymtable_Build(mod, filename, 0); - PyArena_Free(arena); - return st; + struct symtable *st; + mod_ty mod; + PyCompilerFlags flags; + PyArena *arena = PyArena_New(); + if (arena == NULL) + return NULL; + + flags.cf_flags = 0; + mod = PyParser_ASTFromString(str, filename, start, &flags, arena); + if (mod == NULL) { + PyArena_Free(arena); + return NULL; + } + st = PySymtable_Build(mod, filename, 0); + PyArena_Free(arena); + return st; } /* Preferred access to parser is through AST. */ mod_ty PyParser_ASTFromString(const char *s, const char *filename, int start, - PyCompilerFlags *flags, PyArena *arena) + PyCompilerFlags *flags, PyArena *arena) { - mod_ty mod; - PyCompilerFlags localflags; - perrdetail err; - int iflags = PARSER_FLAGS(flags); - - node *n = PyParser_ParseStringFlagsFilenameEx(s, filename, - &_PyParser_Grammar, start, &err, - &iflags); - if (flags == NULL) { - localflags.cf_flags = 0; - flags = &localflags; - } - if (n) { - flags->cf_flags |= iflags & PyCF_MASK; - mod = PyAST_FromNode(n, flags, filename, arena); - PyNode_Free(n); - return mod; - } - else { - err_input(&err); - return NULL; - } + mod_ty mod; + PyCompilerFlags localflags; + perrdetail err; + int iflags = PARSER_FLAGS(flags); + + node *n = PyParser_ParseStringFlagsFilenameEx(s, filename, + &_PyParser_Grammar, start, &err, + &iflags); + if (flags == NULL) { + localflags.cf_flags = 0; + flags = &localflags; + } + if (n) { + flags->cf_flags |= iflags & PyCF_MASK; + mod = PyAST_FromNode(n, flags, filename, arena); + PyNode_Free(n); + return mod; + } + else { + err_input(&err); + return NULL; + } } mod_ty PyParser_ASTFromFile(FILE *fp, const char *filename, const char* enc, - int start, char *ps1, - char *ps2, PyCompilerFlags *flags, int *errcode, - PyArena *arena) -{ - mod_ty mod; - PyCompilerFlags localflags; - perrdetail err; - int iflags = PARSER_FLAGS(flags); - - node *n = PyParser_ParseFileFlagsEx(fp, filename, enc, - &_PyParser_Grammar, - start, ps1, ps2, &err, &iflags); - if (flags == NULL) { - localflags.cf_flags = 0; - flags = &localflags; - } - if (n) { - flags->cf_flags |= iflags & PyCF_MASK; - mod = PyAST_FromNode(n, flags, filename, arena); - PyNode_Free(n); - return mod; - } - else { - err_input(&err); - if (errcode) - *errcode = err.error; - return NULL; - } + int start, char *ps1, + char *ps2, PyCompilerFlags *flags, int *errcode, + PyArena *arena) +{ + mod_ty mod; + PyCompilerFlags localflags; + perrdetail err; + int iflags = PARSER_FLAGS(flags); + + node *n = PyParser_ParseFileFlagsEx(fp, filename, enc, + &_PyParser_Grammar, + start, ps1, ps2, &err, &iflags); + if (flags == NULL) { + localflags.cf_flags = 0; + flags = &localflags; + } + if (n) { + flags->cf_flags |= iflags & PyCF_MASK; + mod = PyAST_FromNode(n, flags, filename, arena); + PyNode_Free(n); + return mod; + } + else { + err_input(&err); + if (errcode) + *errcode = err.error; + return NULL; + } } /* Simplified interface to parsefile -- return node or set exception */ @@ -1840,14 +1840,14 @@ node * PyParser_SimpleParseFileFlags(FILE *fp, const char *filename, int start, int flags) { - perrdetail err; - node *n = PyParser_ParseFileFlags(fp, filename, NULL, - &_PyParser_Grammar, - start, NULL, NULL, &err, flags); - if (n == NULL) - err_input(&err); + perrdetail err; + node *n = PyParser_ParseFileFlags(fp, filename, NULL, + &_PyParser_Grammar, + start, NULL, NULL, &err, flags); + if (n == NULL) + err_input(&err); - return n; + return n; } /* Simplified interface to parsestring -- return node or set exception */ @@ -1855,30 +1855,30 @@ node * PyParser_SimpleParseStringFlags(const char *str, int start, int flags) { - perrdetail err; - node *n = PyParser_ParseStringFlags(str, &_PyParser_Grammar, - start, &err, flags); - if (n == NULL) - err_input(&err); - return n; + perrdetail err; + node *n = PyParser_ParseStringFlags(str, &_PyParser_Grammar, + start, &err, flags); + if (n == NULL) + err_input(&err); + return n; } node * PyParser_SimpleParseStringFlagsFilename(const char *str, const char *filename, - int start, int flags) + int start, int flags) { - perrdetail err; - node *n = PyParser_ParseStringFlagsFilename(str, filename, - &_PyParser_Grammar, start, &err, flags); - if (n == NULL) - err_input(&err); - return n; + perrdetail err; + node *n = PyParser_ParseStringFlagsFilename(str, filename, + &_PyParser_Grammar, start, &err, flags); + if (n == NULL) + err_input(&err); + return n; } node * PyParser_SimpleParseStringFilename(const char *str, const char *filename, int start) { - return PyParser_SimpleParseStringFlagsFilename(str, filename, start, 0); + return PyParser_SimpleParseStringFlagsFilename(str, filename, start, 0); } /* May want to move a more generalized form of this to parsetok.c or @@ -1887,7 +1887,7 @@ void PyParser_SetError(perrdetail *err) { - err_input(err); + err_input(err); } /* Set the error appropriate to the given input error code (see errcode.h) */ @@ -1895,110 +1895,110 @@ static void err_input(perrdetail *err) { - PyObject *v, *w, *errtype, *errtext; - PyObject *msg_obj = NULL; - char *msg = NULL; - errtype = PyExc_SyntaxError; - switch (err->error) { - case E_ERROR: - return; - case E_SYNTAX: - errtype = PyExc_IndentationError; - if (err->expected == INDENT) - msg = "expected an indented block"; - else if (err->token == INDENT) - msg = "unexpected indent"; - else if (err->token == DEDENT) - msg = "unexpected unindent"; - else { - errtype = PyExc_SyntaxError; - msg = "invalid syntax"; - } - break; - case E_TOKEN: - msg = "invalid token"; - break; - case E_EOFS: - msg = "EOF while scanning triple-quoted string literal"; - break; - case E_EOLS: - msg = "EOL while scanning string literal"; - break; - case E_INTR: - if (!PyErr_Occurred()) - PyErr_SetNone(PyExc_KeyboardInterrupt); - goto cleanup; - case E_NOMEM: - PyErr_NoMemory(); - goto cleanup; - case E_EOF: - msg = "unexpected EOF while parsing"; - break; - case E_TABSPACE: - errtype = PyExc_TabError; - msg = "inconsistent use of tabs and spaces in indentation"; - break; - case E_OVERFLOW: - msg = "expression too long"; - break; - case E_DEDENT: - errtype = PyExc_IndentationError; - msg = "unindent does not match any outer indentation level"; - break; - case E_TOODEEP: - errtype = PyExc_IndentationError; - msg = "too many levels of indentation"; - break; - case E_DECODE: { - PyObject *type, *value, *tb; - PyErr_Fetch(&type, &value, &tb); - msg = "unknown decode error"; - if (value != NULL) - msg_obj = PyObject_Str(value); - Py_XDECREF(type); - Py_XDECREF(value); - Py_XDECREF(tb); - break; - } - case E_LINECONT: - msg = "unexpected character after line continuation character"; - break; - - case E_IDENTIFIER: - msg = "invalid character in identifier"; - break; - default: - fprintf(stderr, "error=%d\n", err->error); - msg = "unknown parsing error"; - break; - } - /* err->text may not be UTF-8 in case of decoding errors. - Explicitly convert to an object. */ - if (!err->text) { - errtext = Py_None; - Py_INCREF(Py_None); - } else { - errtext = PyUnicode_DecodeUTF8(err->text, strlen(err->text), - "replace"); - } - v = Py_BuildValue("(ziiN)", err->filename, - err->lineno, err->offset, errtext); - if (v != NULL) { - if (msg_obj) - w = Py_BuildValue("(OO)", msg_obj, v); - else - w = Py_BuildValue("(sO)", msg, v); - } else - w = NULL; - Py_XDECREF(v); - PyErr_SetObject(errtype, w); - Py_XDECREF(w); + PyObject *v, *w, *errtype, *errtext; + PyObject *msg_obj = NULL; + char *msg = NULL; + errtype = PyExc_SyntaxError; + switch (err->error) { + case E_ERROR: + return; + case E_SYNTAX: + errtype = PyExc_IndentationError; + if (err->expected == INDENT) + msg = "expected an indented block"; + else if (err->token == INDENT) + msg = "unexpected indent"; + else if (err->token == DEDENT) + msg = "unexpected unindent"; + else { + errtype = PyExc_SyntaxError; + msg = "invalid syntax"; + } + break; + case E_TOKEN: + msg = "invalid token"; + break; + case E_EOFS: + msg = "EOF while scanning triple-quoted string literal"; + break; + case E_EOLS: + msg = "EOL while scanning string literal"; + break; + case E_INTR: + if (!PyErr_Occurred()) + PyErr_SetNone(PyExc_KeyboardInterrupt); + goto cleanup; + case E_NOMEM: + PyErr_NoMemory(); + goto cleanup; + case E_EOF: + msg = "unexpected EOF while parsing"; + break; + case E_TABSPACE: + errtype = PyExc_TabError; + msg = "inconsistent use of tabs and spaces in indentation"; + break; + case E_OVERFLOW: + msg = "expression too long"; + break; + case E_DEDENT: + errtype = PyExc_IndentationError; + msg = "unindent does not match any outer indentation level"; + break; + case E_TOODEEP: + errtype = PyExc_IndentationError; + msg = "too many levels of indentation"; + break; + case E_DECODE: { + PyObject *type, *value, *tb; + PyErr_Fetch(&type, &value, &tb); + msg = "unknown decode error"; + if (value != NULL) + msg_obj = PyObject_Str(value); + Py_XDECREF(type); + Py_XDECREF(value); + Py_XDECREF(tb); + break; + } + case E_LINECONT: + msg = "unexpected character after line continuation character"; + break; + + case E_IDENTIFIER: + msg = "invalid character in identifier"; + break; + default: + fprintf(stderr, "error=%d\n", err->error); + msg = "unknown parsing error"; + break; + } + /* err->text may not be UTF-8 in case of decoding errors. + Explicitly convert to an object. */ + if (!err->text) { + errtext = Py_None; + Py_INCREF(Py_None); + } else { + errtext = PyUnicode_DecodeUTF8(err->text, strlen(err->text), + "replace"); + } + v = Py_BuildValue("(ziiN)", err->filename, + err->lineno, err->offset, errtext); + if (v != NULL) { + if (msg_obj) + w = Py_BuildValue("(OO)", msg_obj, v); + else + w = Py_BuildValue("(sO)", msg, v); + } else + w = NULL; + Py_XDECREF(v); + PyErr_SetObject(errtype, w); + Py_XDECREF(w); cleanup: - Py_XDECREF(msg_obj); - if (err->text != NULL) { - PyObject_FREE(err->text); - err->text = NULL; - } + Py_XDECREF(msg_obj); + if (err->text != NULL) { + PyObject_FREE(err->text); + err->text = NULL; + } } /* Print fatal error message and abort */ @@ -2006,32 +2006,32 @@ void Py_FatalError(const char *msg) { - fprintf(stderr, "Fatal Python error: %s\n", msg); - fflush(stderr); /* it helps in Windows debug build */ - if (PyErr_Occurred()) { - PyErr_Print(); - } + fprintf(stderr, "Fatal Python error: %s\n", msg); + fflush(stderr); /* it helps in Windows debug build */ + if (PyErr_Occurred()) { + PyErr_Print(); + } #ifdef MS_WINDOWS - { - size_t len = strlen(msg); - WCHAR* buffer; - size_t i; - - /* Convert the message to wchar_t. This uses a simple one-to-one - conversion, assuming that the this error message actually uses ASCII - only. If this ceases to be true, we will have to convert. */ - buffer = alloca( (len+1) * (sizeof *buffer)); - for( i=0; i<=len; ++i) - buffer[i] = msg[i]; - OutputDebugStringW(L"Fatal Python error: "); - OutputDebugStringW(buffer); - OutputDebugStringW(L"\n"); - } + { + size_t len = strlen(msg); + WCHAR* buffer; + size_t i; + + /* Convert the message to wchar_t. This uses a simple one-to-one + conversion, assuming that the this error message actually uses ASCII + only. If this ceases to be true, we will have to convert. */ + buffer = alloca( (len+1) * (sizeof *buffer)); + for( i=0; i<=len; ++i) + buffer[i] = msg[i]; + OutputDebugStringW(L"Fatal Python error: "); + OutputDebugStringW(buffer); + OutputDebugStringW(L"\n"); + } #ifdef _DEBUG - DebugBreak(); + DebugBreak(); #endif #endif /* MS_WINDOWS */ - abort(); + abort(); } /* Clean up and exit */ @@ -2044,17 +2044,17 @@ /* For the atexit module. */ void _Py_PyAtExit(void (*func)(void)) { - pyexitfunc = func; + pyexitfunc = func; } static void call_py_exitfuncs(void) { - if (pyexitfunc == NULL) - return; + if (pyexitfunc == NULL) + return; - (*pyexitfunc)(); - PyErr_Clear(); + (*pyexitfunc)(); + PyErr_Clear(); } /* Wait until threading._shutdown completes, provided @@ -2065,23 +2065,23 @@ wait_for_thread_shutdown(void) { #ifdef WITH_THREAD - PyObject *result; - PyThreadState *tstate = PyThreadState_GET(); - PyObject *threading = PyMapping_GetItemString(tstate->interp->modules, - "threading"); - if (threading == NULL) { - /* threading not imported */ - PyErr_Clear(); - return; - } - result = PyObject_CallMethod(threading, "_shutdown", ""); - if (result == NULL) { - PyErr_WriteUnraisable(threading); - } - else { - Py_DECREF(result); - } - Py_DECREF(threading); + PyObject *result; + PyThreadState *tstate = PyThreadState_GET(); + PyObject *threading = PyMapping_GetItemString(tstate->interp->modules, + "threading"); + if (threading == NULL) { + /* threading not imported */ + PyErr_Clear(); + return; + } + result = PyObject_CallMethod(threading, "_shutdown", ""); + if (result == NULL) { + PyErr_WriteUnraisable(threading); + } + else { + Py_DECREF(result); + } + Py_DECREF(threading); #endif } @@ -2091,43 +2091,43 @@ int Py_AtExit(void (*func)(void)) { - if (nexitfuncs >= NEXITFUNCS) - return -1; - exitfuncs[nexitfuncs++] = func; - return 0; + if (nexitfuncs >= NEXITFUNCS) + return -1; + exitfuncs[nexitfuncs++] = func; + return 0; } static void call_ll_exitfuncs(void) { - while (nexitfuncs > 0) - (*exitfuncs[--nexitfuncs])(); + while (nexitfuncs > 0) + (*exitfuncs[--nexitfuncs])(); - fflush(stdout); - fflush(stderr); + fflush(stdout); + fflush(stderr); } void Py_Exit(int sts) { - Py_Finalize(); + Py_Finalize(); - exit(sts); + exit(sts); } static void initsigs(void) { #ifdef SIGPIPE - PyOS_setsig(SIGPIPE, SIG_IGN); + PyOS_setsig(SIGPIPE, SIG_IGN); #endif #ifdef SIGXFZ - PyOS_setsig(SIGXFZ, SIG_IGN); + PyOS_setsig(SIGXFZ, SIG_IGN); #endif #ifdef SIGXFSZ - PyOS_setsig(SIGXFSZ, SIG_IGN); + PyOS_setsig(SIGXFSZ, SIG_IGN); #endif - PyOS_InitInterrupts(); /* May imply initsignal() */ + PyOS_InitInterrupts(); /* May imply initsignal() */ } @@ -2141,13 +2141,13 @@ _Py_RestoreSignals(void) { #ifdef SIGPIPE - PyOS_setsig(SIGPIPE, SIG_DFL); + PyOS_setsig(SIGPIPE, SIG_DFL); #endif #ifdef SIGXFZ - PyOS_setsig(SIGXFZ, SIG_DFL); + PyOS_setsig(SIGXFZ, SIG_DFL); #endif #ifdef SIGXFSZ - PyOS_setsig(SIGXFSZ, SIG_DFL); + PyOS_setsig(SIGXFSZ, SIG_DFL); #endif } @@ -2161,13 +2161,13 @@ int Py_FdIsInteractive(FILE *fp, const char *filename) { - if (isatty((int)fileno(fp))) - return 1; - if (!Py_InteractiveFlag) - return 0; - return (filename == NULL) || - (strcmp(filename, "") == 0) || - (strcmp(filename, "???") == 0); + if (isatty((int)fileno(fp))) + return 1; + if (!Py_InteractiveFlag) + return 0; + return (filename == NULL) || + (strcmp(filename, "") == 0) || + (strcmp(filename, "???") == 0); } @@ -2185,21 +2185,21 @@ int PyOS_CheckStack(void) { - __try { - /* alloca throws a stack overflow exception if there's - not enough space left on the stack */ - alloca(PYOS_STACK_MARGIN * sizeof(void*)); - return 0; - } __except (GetExceptionCode() == STATUS_STACK_OVERFLOW ? - EXCEPTION_EXECUTE_HANDLER : - EXCEPTION_CONTINUE_SEARCH) { - int errcode = _resetstkoflw(); - if (errcode == 0) - { - Py_FatalError("Could not reset the stack!"); - } - } - return 1; + __try { + /* alloca throws a stack overflow exception if there's + not enough space left on the stack */ + alloca(PYOS_STACK_MARGIN * sizeof(void*)); + return 0; + } __except (GetExceptionCode() == STATUS_STACK_OVERFLOW ? + EXCEPTION_EXECUTE_HANDLER : + EXCEPTION_CONTINUE_SEARCH) { + int errcode = _resetstkoflw(); + if (errcode == 0) + { + Py_FatalError("Could not reset the stack!"); + } + } + return 1; } #endif /* WIN32 && _MSC_VER */ @@ -2215,33 +2215,33 @@ PyOS_getsig(int sig) { #ifdef HAVE_SIGACTION - struct sigaction context; - if (sigaction(sig, NULL, &context) == -1) - return SIG_ERR; - return context.sa_handler; + struct sigaction context; + if (sigaction(sig, NULL, &context) == -1) + return SIG_ERR; + return context.sa_handler; #else - PyOS_sighandler_t handler; + PyOS_sighandler_t handler; /* Special signal handling for the secure CRT in Visual Studio 2005 */ #if defined(_MSC_VER) && _MSC_VER >= 1400 - switch (sig) { - /* Only these signals are valid */ - case SIGINT: - case SIGILL: - case SIGFPE: - case SIGSEGV: - case SIGTERM: - case SIGBREAK: - case SIGABRT: - break; - /* Don't call signal() with other values or it will assert */ - default: - return SIG_ERR; - } + switch (sig) { + /* Only these signals are valid */ + case SIGINT: + case SIGILL: + case SIGFPE: + case SIGSEGV: + case SIGTERM: + case SIGBREAK: + case SIGABRT: + break; + /* Don't call signal() with other values or it will assert */ + default: + return SIG_ERR; + } #endif /* _MSC_VER && _MSC_VER >= 1400 */ - handler = signal(sig, SIG_IGN); - if (handler != SIG_ERR) - signal(sig, handler); - return handler; + handler = signal(sig, SIG_IGN); + if (handler != SIG_ERR) + signal(sig, handler); + return handler; #endif } @@ -2254,24 +2254,24 @@ PyOS_setsig(int sig, PyOS_sighandler_t handler) { #ifdef HAVE_SIGACTION - /* Some code in Modules/signalmodule.c depends on sigaction() being - * used here if HAVE_SIGACTION is defined. Fix that if this code - * changes to invalidate that assumption. - */ - struct sigaction context, ocontext; - context.sa_handler = handler; - sigemptyset(&context.sa_mask); - context.sa_flags = 0; - if (sigaction(sig, &context, &ocontext) == -1) - return SIG_ERR; - return ocontext.sa_handler; + /* Some code in Modules/signalmodule.c depends on sigaction() being + * used here if HAVE_SIGACTION is defined. Fix that if this code + * changes to invalidate that assumption. + */ + struct sigaction context, ocontext; + context.sa_handler = handler; + sigemptyset(&context.sa_mask); + context.sa_flags = 0; + if (sigaction(sig, &context, &ocontext) == -1) + return SIG_ERR; + return ocontext.sa_handler; #else - PyOS_sighandler_t oldhandler; - oldhandler = signal(sig, handler); + PyOS_sighandler_t oldhandler; + oldhandler = signal(sig, handler); #ifdef HAVE_SIGINTERRUPT - siginterrupt(sig, 1); + siginterrupt(sig, 1); #endif - return oldhandler; + return oldhandler; #endif } @@ -2281,71 +2281,71 @@ PyAPI_FUNC(node *) PyParser_SimpleParseFile(FILE *fp, const char *filename, int start) { - return PyParser_SimpleParseFileFlags(fp, filename, start, 0); + return PyParser_SimpleParseFileFlags(fp, filename, start, 0); } #undef PyParser_SimpleParseString PyAPI_FUNC(node *) PyParser_SimpleParseString(const char *str, int start) { - return PyParser_SimpleParseStringFlags(str, start, 0); + return PyParser_SimpleParseStringFlags(str, start, 0); } #undef PyRun_AnyFile PyAPI_FUNC(int) PyRun_AnyFile(FILE *fp, const char *name) { - return PyRun_AnyFileExFlags(fp, name, 0, NULL); + return PyRun_AnyFileExFlags(fp, name, 0, NULL); } #undef PyRun_AnyFileEx PyAPI_FUNC(int) PyRun_AnyFileEx(FILE *fp, const char *name, int closeit) { - return PyRun_AnyFileExFlags(fp, name, closeit, NULL); + return PyRun_AnyFileExFlags(fp, name, closeit, NULL); } #undef PyRun_AnyFileFlags PyAPI_FUNC(int) PyRun_AnyFileFlags(FILE *fp, const char *name, PyCompilerFlags *flags) { - return PyRun_AnyFileExFlags(fp, name, 0, flags); + return PyRun_AnyFileExFlags(fp, name, 0, flags); } #undef PyRun_File PyAPI_FUNC(PyObject *) PyRun_File(FILE *fp, const char *p, int s, PyObject *g, PyObject *l) { - return PyRun_FileExFlags(fp, p, s, g, l, 0, NULL); + return PyRun_FileExFlags(fp, p, s, g, l, 0, NULL); } #undef PyRun_FileEx PyAPI_FUNC(PyObject *) PyRun_FileEx(FILE *fp, const char *p, int s, PyObject *g, PyObject *l, int c) { - return PyRun_FileExFlags(fp, p, s, g, l, c, NULL); + return PyRun_FileExFlags(fp, p, s, g, l, c, NULL); } #undef PyRun_FileFlags PyAPI_FUNC(PyObject *) PyRun_FileFlags(FILE *fp, const char *p, int s, PyObject *g, PyObject *l, - PyCompilerFlags *flags) + PyCompilerFlags *flags) { - return PyRun_FileExFlags(fp, p, s, g, l, 0, flags); + return PyRun_FileExFlags(fp, p, s, g, l, 0, flags); } #undef PyRun_SimpleFile PyAPI_FUNC(int) PyRun_SimpleFile(FILE *f, const char *p) { - return PyRun_SimpleFileExFlags(f, p, 0, NULL); + return PyRun_SimpleFileExFlags(f, p, 0, NULL); } #undef PyRun_SimpleFileEx PyAPI_FUNC(int) PyRun_SimpleFileEx(FILE *f, const char *p, int c) { - return PyRun_SimpleFileExFlags(f, p, c, NULL); + return PyRun_SimpleFileExFlags(f, p, c, NULL); } @@ -2353,35 +2353,35 @@ PyAPI_FUNC(PyObject *) PyRun_String(const char *str, int s, PyObject *g, PyObject *l) { - return PyRun_StringFlags(str, s, g, l, NULL); + return PyRun_StringFlags(str, s, g, l, NULL); } #undef PyRun_SimpleString PyAPI_FUNC(int) PyRun_SimpleString(const char *s) { - return PyRun_SimpleStringFlags(s, NULL); + return PyRun_SimpleStringFlags(s, NULL); } #undef Py_CompileString PyAPI_FUNC(PyObject *) Py_CompileString(const char *str, const char *p, int s) { - return Py_CompileStringFlags(str, p, s, NULL); + return Py_CompileStringFlags(str, p, s, NULL); } #undef PyRun_InteractiveOne PyAPI_FUNC(int) PyRun_InteractiveOne(FILE *f, const char *p) { - return PyRun_InteractiveOneFlags(f, p, NULL); + return PyRun_InteractiveOneFlags(f, p, NULL); } #undef PyRun_InteractiveLoop PyAPI_FUNC(int) PyRun_InteractiveLoop(FILE *f, const char *p) { - return PyRun_InteractiveLoopFlags(f, p, NULL); + return PyRun_InteractiveLoopFlags(f, p, NULL); } #ifdef __cplusplus Modified: python/branches/py3k/Python/structmember.c ============================================================================== --- python/branches/py3k/Python/structmember.c (original) +++ python/branches/py3k/Python/structmember.c Sun May 9 17:52:27 2010 @@ -8,293 +8,293 @@ PyObject * PyMember_GetOne(const char *addr, PyMemberDef *l) { - PyObject *v; + PyObject *v; - addr += l->offset; - switch (l->type) { - case T_BOOL: - v = PyBool_FromLong(*(char*)addr); - break; - case T_BYTE: - v = PyLong_FromLong(*(char*)addr); - break; - case T_UBYTE: - v = PyLong_FromUnsignedLong(*(unsigned char*)addr); - break; - case T_SHORT: - v = PyLong_FromLong(*(short*)addr); - break; - case T_USHORT: - v = PyLong_FromUnsignedLong(*(unsigned short*)addr); - break; - case T_INT: - v = PyLong_FromLong(*(int*)addr); - break; - case T_UINT: - v = PyLong_FromUnsignedLong(*(unsigned int*)addr); - break; - case T_LONG: - v = PyLong_FromLong(*(long*)addr); - break; - case T_ULONG: - v = PyLong_FromUnsignedLong(*(unsigned long*)addr); - break; - case T_PYSSIZET: - v = PyLong_FromSsize_t(*(Py_ssize_t*)addr); - break; - case T_FLOAT: - v = PyFloat_FromDouble((double)*(float*)addr); - break; - case T_DOUBLE: - v = PyFloat_FromDouble(*(double*)addr); - break; - case T_STRING: - if (*(char**)addr == NULL) { - Py_INCREF(Py_None); - v = Py_None; - } - else - v = PyUnicode_FromString(*(char**)addr); - break; - case T_STRING_INPLACE: - v = PyUnicode_FromString((char*)addr); - break; - case T_CHAR: - v = PyUnicode_FromStringAndSize((char*)addr, 1); - break; - case T_OBJECT: - v = *(PyObject **)addr; - if (v == NULL) - v = Py_None; - Py_INCREF(v); - break; - case T_OBJECT_EX: - v = *(PyObject **)addr; - if (v == NULL) - PyErr_SetString(PyExc_AttributeError, l->name); - Py_XINCREF(v); - break; + addr += l->offset; + switch (l->type) { + case T_BOOL: + v = PyBool_FromLong(*(char*)addr); + break; + case T_BYTE: + v = PyLong_FromLong(*(char*)addr); + break; + case T_UBYTE: + v = PyLong_FromUnsignedLong(*(unsigned char*)addr); + break; + case T_SHORT: + v = PyLong_FromLong(*(short*)addr); + break; + case T_USHORT: + v = PyLong_FromUnsignedLong(*(unsigned short*)addr); + break; + case T_INT: + v = PyLong_FromLong(*(int*)addr); + break; + case T_UINT: + v = PyLong_FromUnsignedLong(*(unsigned int*)addr); + break; + case T_LONG: + v = PyLong_FromLong(*(long*)addr); + break; + case T_ULONG: + v = PyLong_FromUnsignedLong(*(unsigned long*)addr); + break; + case T_PYSSIZET: + v = PyLong_FromSsize_t(*(Py_ssize_t*)addr); + break; + case T_FLOAT: + v = PyFloat_FromDouble((double)*(float*)addr); + break; + case T_DOUBLE: + v = PyFloat_FromDouble(*(double*)addr); + break; + case T_STRING: + if (*(char**)addr == NULL) { + Py_INCREF(Py_None); + v = Py_None; + } + else + v = PyUnicode_FromString(*(char**)addr); + break; + case T_STRING_INPLACE: + v = PyUnicode_FromString((char*)addr); + break; + case T_CHAR: + v = PyUnicode_FromStringAndSize((char*)addr, 1); + break; + case T_OBJECT: + v = *(PyObject **)addr; + if (v == NULL) + v = Py_None; + Py_INCREF(v); + break; + case T_OBJECT_EX: + v = *(PyObject **)addr; + if (v == NULL) + PyErr_SetString(PyExc_AttributeError, l->name); + Py_XINCREF(v); + break; #ifdef HAVE_LONG_LONG - case T_LONGLONG: - v = PyLong_FromLongLong(*(PY_LONG_LONG *)addr); - break; - case T_ULONGLONG: - v = PyLong_FromUnsignedLongLong(*(unsigned PY_LONG_LONG *)addr); - break; + case T_LONGLONG: + v = PyLong_FromLongLong(*(PY_LONG_LONG *)addr); + break; + case T_ULONGLONG: + v = PyLong_FromUnsignedLongLong(*(unsigned PY_LONG_LONG *)addr); + break; #endif /* HAVE_LONG_LONG */ - case T_NONE: - v = Py_None; - Py_INCREF(v); - break; - default: - PyErr_SetString(PyExc_SystemError, "bad memberdescr type"); - v = NULL; - } - return v; + case T_NONE: + v = Py_None; + Py_INCREF(v); + break; + default: + PyErr_SetString(PyExc_SystemError, "bad memberdescr type"); + v = NULL; + } + return v; } -#define WARN(msg) \ - do { \ - if (PyErr_WarnEx(PyExc_RuntimeWarning, msg, 1) < 0) \ - return -1; \ +#define WARN(msg) \ + do { \ + if (PyErr_WarnEx(PyExc_RuntimeWarning, msg, 1) < 0) \ + return -1; \ } while (0) int PyMember_SetOne(char *addr, PyMemberDef *l, PyObject *v) { - PyObject *oldv; + PyObject *oldv; - addr += l->offset; + addr += l->offset; - if ((l->flags & READONLY)) - { - PyErr_SetString(PyExc_AttributeError, "readonly attribute"); - return -1; - } - if (v == NULL) { - if (l->type == T_OBJECT_EX) { - /* Check if the attribute is set. */ - if (*(PyObject **)addr == NULL) { - PyErr_SetString(PyExc_AttributeError, l->name); - return -1; - } - } - else if (l->type != T_OBJECT) { - PyErr_SetString(PyExc_TypeError, - "can't delete numeric/char attribute"); - return -1; - } - } - switch (l->type) { - case T_BOOL:{ - if (!PyBool_Check(v)) { - PyErr_SetString(PyExc_TypeError, - "attribute value type must be bool"); - return -1; - } - if (v == Py_True) - *(char*)addr = (char) 1; - else - *(char*)addr = (char) 0; - break; - } - case T_BYTE:{ - long long_val = PyLong_AsLong(v); - if ((long_val == -1) && PyErr_Occurred()) - return -1; - *(char*)addr = (char)long_val; - /* XXX: For compatibility, only warn about truncations - for now. */ - if ((long_val > CHAR_MAX) || (long_val < CHAR_MIN)) - WARN("Truncation of value to char"); - break; - } - case T_UBYTE:{ - long long_val = PyLong_AsLong(v); - if ((long_val == -1) && PyErr_Occurred()) - return -1; - *(unsigned char*)addr = (unsigned char)long_val; - if ((long_val > UCHAR_MAX) || (long_val < 0)) - WARN("Truncation of value to unsigned char"); - break; - } - case T_SHORT:{ - long long_val = PyLong_AsLong(v); - if ((long_val == -1) && PyErr_Occurred()) - return -1; - *(short*)addr = (short)long_val; - if ((long_val > SHRT_MAX) || (long_val < SHRT_MIN)) - WARN("Truncation of value to short"); - break; - } - case T_USHORT:{ - long long_val = PyLong_AsLong(v); - if ((long_val == -1) && PyErr_Occurred()) - return -1; - *(unsigned short*)addr = (unsigned short)long_val; - if ((long_val > USHRT_MAX) || (long_val < 0)) - WARN("Truncation of value to unsigned short"); - break; - } - case T_INT:{ - long long_val = PyLong_AsLong(v); - if ((long_val == -1) && PyErr_Occurred()) - return -1; - *(int *)addr = (int)long_val; - if ((long_val > INT_MAX) || (long_val < INT_MIN)) - WARN("Truncation of value to int"); - break; - } - case T_UINT:{ - unsigned long ulong_val = PyLong_AsUnsignedLong(v); - if ((ulong_val == (unsigned long)-1) && PyErr_Occurred()) { - /* XXX: For compatibility, accept negative int values - as well. */ - PyErr_Clear(); - ulong_val = PyLong_AsLong(v); - if ((ulong_val == (unsigned long)-1) && - PyErr_Occurred()) - return -1; - *(unsigned int *)addr = (unsigned int)ulong_val; - WARN("Writing negative value into unsigned field"); - } else - *(unsigned int *)addr = (unsigned int)ulong_val; - if (ulong_val > UINT_MAX) - WARN("Truncation of value to unsigned int"); - break; - } - case T_LONG:{ - *(long*)addr = PyLong_AsLong(v); - if ((*(long*)addr == -1) && PyErr_Occurred()) - return -1; - break; - } - case T_ULONG:{ - *(unsigned long*)addr = PyLong_AsUnsignedLong(v); - if ((*(unsigned long*)addr == (unsigned long)-1) - && PyErr_Occurred()) { - /* XXX: For compatibility, accept negative int values - as well. */ - PyErr_Clear(); - *(unsigned long*)addr = PyLong_AsLong(v); - if ((*(unsigned long*)addr == (unsigned long)-1) - && PyErr_Occurred()) - return -1; - WARN("Writing negative value into unsigned field"); - } - break; - } - case T_PYSSIZET:{ - *(Py_ssize_t*)addr = PyLong_AsSsize_t(v); - if ((*(Py_ssize_t*)addr == (Py_ssize_t)-1) - && PyErr_Occurred()) - return -1; - break; - } - case T_FLOAT:{ - double double_val = PyFloat_AsDouble(v); - if ((double_val == -1) && PyErr_Occurred()) - return -1; - *(float*)addr = (float)double_val; - break; - } - case T_DOUBLE: - *(double*)addr = PyFloat_AsDouble(v); - if ((*(double*)addr == -1) && PyErr_Occurred()) - return -1; - break; - case T_OBJECT: - case T_OBJECT_EX: - Py_XINCREF(v); - oldv = *(PyObject **)addr; - *(PyObject **)addr = v; - Py_XDECREF(oldv); - break; - case T_CHAR: { - char *string; - Py_ssize_t len; + if ((l->flags & READONLY)) + { + PyErr_SetString(PyExc_AttributeError, "readonly attribute"); + return -1; + } + if (v == NULL) { + if (l->type == T_OBJECT_EX) { + /* Check if the attribute is set. */ + if (*(PyObject **)addr == NULL) { + PyErr_SetString(PyExc_AttributeError, l->name); + return -1; + } + } + else if (l->type != T_OBJECT) { + PyErr_SetString(PyExc_TypeError, + "can't delete numeric/char attribute"); + return -1; + } + } + switch (l->type) { + case T_BOOL:{ + if (!PyBool_Check(v)) { + PyErr_SetString(PyExc_TypeError, + "attribute value type must be bool"); + return -1; + } + if (v == Py_True) + *(char*)addr = (char) 1; + else + *(char*)addr = (char) 0; + break; + } + case T_BYTE:{ + long long_val = PyLong_AsLong(v); + if ((long_val == -1) && PyErr_Occurred()) + return -1; + *(char*)addr = (char)long_val; + /* XXX: For compatibility, only warn about truncations + for now. */ + if ((long_val > CHAR_MAX) || (long_val < CHAR_MIN)) + WARN("Truncation of value to char"); + break; + } + case T_UBYTE:{ + long long_val = PyLong_AsLong(v); + if ((long_val == -1) && PyErr_Occurred()) + return -1; + *(unsigned char*)addr = (unsigned char)long_val; + if ((long_val > UCHAR_MAX) || (long_val < 0)) + WARN("Truncation of value to unsigned char"); + break; + } + case T_SHORT:{ + long long_val = PyLong_AsLong(v); + if ((long_val == -1) && PyErr_Occurred()) + return -1; + *(short*)addr = (short)long_val; + if ((long_val > SHRT_MAX) || (long_val < SHRT_MIN)) + WARN("Truncation of value to short"); + break; + } + case T_USHORT:{ + long long_val = PyLong_AsLong(v); + if ((long_val == -1) && PyErr_Occurred()) + return -1; + *(unsigned short*)addr = (unsigned short)long_val; + if ((long_val > USHRT_MAX) || (long_val < 0)) + WARN("Truncation of value to unsigned short"); + break; + } + case T_INT:{ + long long_val = PyLong_AsLong(v); + if ((long_val == -1) && PyErr_Occurred()) + return -1; + *(int *)addr = (int)long_val; + if ((long_val > INT_MAX) || (long_val < INT_MIN)) + WARN("Truncation of value to int"); + break; + } + case T_UINT:{ + unsigned long ulong_val = PyLong_AsUnsignedLong(v); + if ((ulong_val == (unsigned long)-1) && PyErr_Occurred()) { + /* XXX: For compatibility, accept negative int values + as well. */ + PyErr_Clear(); + ulong_val = PyLong_AsLong(v); + if ((ulong_val == (unsigned long)-1) && + PyErr_Occurred()) + return -1; + *(unsigned int *)addr = (unsigned int)ulong_val; + WARN("Writing negative value into unsigned field"); + } else + *(unsigned int *)addr = (unsigned int)ulong_val; + if (ulong_val > UINT_MAX) + WARN("Truncation of value to unsigned int"); + break; + } + case T_LONG:{ + *(long*)addr = PyLong_AsLong(v); + if ((*(long*)addr == -1) && PyErr_Occurred()) + return -1; + break; + } + case T_ULONG:{ + *(unsigned long*)addr = PyLong_AsUnsignedLong(v); + if ((*(unsigned long*)addr == (unsigned long)-1) + && PyErr_Occurred()) { + /* XXX: For compatibility, accept negative int values + as well. */ + PyErr_Clear(); + *(unsigned long*)addr = PyLong_AsLong(v); + if ((*(unsigned long*)addr == (unsigned long)-1) + && PyErr_Occurred()) + return -1; + WARN("Writing negative value into unsigned field"); + } + break; + } + case T_PYSSIZET:{ + *(Py_ssize_t*)addr = PyLong_AsSsize_t(v); + if ((*(Py_ssize_t*)addr == (Py_ssize_t)-1) + && PyErr_Occurred()) + return -1; + break; + } + case T_FLOAT:{ + double double_val = PyFloat_AsDouble(v); + if ((double_val == -1) && PyErr_Occurred()) + return -1; + *(float*)addr = (float)double_val; + break; + } + case T_DOUBLE: + *(double*)addr = PyFloat_AsDouble(v); + if ((*(double*)addr == -1) && PyErr_Occurred()) + return -1; + break; + case T_OBJECT: + case T_OBJECT_EX: + Py_XINCREF(v); + oldv = *(PyObject **)addr; + *(PyObject **)addr = v; + Py_XDECREF(oldv); + break; + case T_CHAR: { + char *string; + Py_ssize_t len; - if (!PyUnicode_Check(v)) { - PyErr_BadArgument(); - return -1; - } - string = _PyUnicode_AsStringAndSize(v, &len); - if (len != 1) { - PyErr_BadArgument(); - return -1; - } - *(char*)addr = string[0]; - break; - } - case T_STRING: - case T_STRING_INPLACE: - PyErr_SetString(PyExc_TypeError, "readonly attribute"); - return -1; + if (!PyUnicode_Check(v)) { + PyErr_BadArgument(); + return -1; + } + string = _PyUnicode_AsStringAndSize(v, &len); + if (len != 1) { + PyErr_BadArgument(); + return -1; + } + *(char*)addr = string[0]; + break; + } + case T_STRING: + case T_STRING_INPLACE: + PyErr_SetString(PyExc_TypeError, "readonly attribute"); + return -1; #ifdef HAVE_LONG_LONG - case T_LONGLONG:{ - PY_LONG_LONG value; - *(PY_LONG_LONG*)addr = value = PyLong_AsLongLong(v); - if ((value == -1) && PyErr_Occurred()) - return -1; - break; - } - case T_ULONGLONG:{ - unsigned PY_LONG_LONG value; - /* ??? PyLong_AsLongLong accepts an int, but PyLong_AsUnsignedLongLong - doesn't ??? */ - if (PyLong_Check(v)) - *(unsigned PY_LONG_LONG*)addr = value = PyLong_AsUnsignedLongLong(v); - else - *(unsigned PY_LONG_LONG*)addr = value = PyLong_AsLong(v); - if ((value == (unsigned PY_LONG_LONG)-1) && PyErr_Occurred()) - return -1; - break; - } + case T_LONGLONG:{ + PY_LONG_LONG value; + *(PY_LONG_LONG*)addr = value = PyLong_AsLongLong(v); + if ((value == -1) && PyErr_Occurred()) + return -1; + break; + } + case T_ULONGLONG:{ + unsigned PY_LONG_LONG value; + /* ??? PyLong_AsLongLong accepts an int, but PyLong_AsUnsignedLongLong + doesn't ??? */ + if (PyLong_Check(v)) + *(unsigned PY_LONG_LONG*)addr = value = PyLong_AsUnsignedLongLong(v); + else + *(unsigned PY_LONG_LONG*)addr = value = PyLong_AsLong(v); + if ((value == (unsigned PY_LONG_LONG)-1) && PyErr_Occurred()) + return -1; + break; + } #endif /* HAVE_LONG_LONG */ - default: - PyErr_Format(PyExc_SystemError, - "bad memberdescr type for %s", l->name); - return -1; - } - return 0; + default: + PyErr_Format(PyExc_SystemError, + "bad memberdescr type for %s", l->name); + return -1; + } + return 0; } Modified: python/branches/py3k/Python/symtable.c ============================================================================== --- python/branches/py3k/Python/symtable.c (original) +++ python/branches/py3k/Python/symtable.c Sun May 9 17:52:27 2010 @@ -25,145 +25,145 @@ static PySTEntryObject * ste_new(struct symtable *st, identifier name, _Py_block_ty block, - void *key, int lineno) + void *key, int lineno) { - PySTEntryObject *ste = NULL; - PyObject *k; + PySTEntryObject *ste = NULL; + PyObject *k; - k = PyLong_FromVoidPtr(key); - if (k == NULL) - goto fail; - ste = PyObject_New(PySTEntryObject, &PySTEntry_Type); - if (ste == NULL) - goto fail; - ste->ste_table = st; - ste->ste_id = k; - - ste->ste_name = name; - Py_INCREF(name); - - ste->ste_symbols = NULL; - ste->ste_varnames = NULL; - ste->ste_children = NULL; - - ste->ste_symbols = PyDict_New(); - if (ste->ste_symbols == NULL) - goto fail; - - ste->ste_varnames = PyList_New(0); - if (ste->ste_varnames == NULL) - goto fail; - - ste->ste_children = PyList_New(0); - if (ste->ste_children == NULL) - goto fail; - - ste->ste_type = block; - ste->ste_unoptimized = 0; - ste->ste_nested = 0; - ste->ste_free = 0; - ste->ste_varargs = 0; - ste->ste_varkeywords = 0; - ste->ste_opt_lineno = 0; - ste->ste_lineno = lineno; - - if (st->st_cur != NULL && - (st->st_cur->ste_nested || - st->st_cur->ste_type == FunctionBlock)) - ste->ste_nested = 1; - ste->ste_child_free = 0; - ste->ste_generator = 0; - ste->ste_returns_value = 0; - - if (PyDict_SetItem(st->st_blocks, ste->ste_id, (PyObject *)ste) < 0) - goto fail; - - return ste; + k = PyLong_FromVoidPtr(key); + if (k == NULL) + goto fail; + ste = PyObject_New(PySTEntryObject, &PySTEntry_Type); + if (ste == NULL) + goto fail; + ste->ste_table = st; + ste->ste_id = k; + + ste->ste_name = name; + Py_INCREF(name); + + ste->ste_symbols = NULL; + ste->ste_varnames = NULL; + ste->ste_children = NULL; + + ste->ste_symbols = PyDict_New(); + if (ste->ste_symbols == NULL) + goto fail; + + ste->ste_varnames = PyList_New(0); + if (ste->ste_varnames == NULL) + goto fail; + + ste->ste_children = PyList_New(0); + if (ste->ste_children == NULL) + goto fail; + + ste->ste_type = block; + ste->ste_unoptimized = 0; + ste->ste_nested = 0; + ste->ste_free = 0; + ste->ste_varargs = 0; + ste->ste_varkeywords = 0; + ste->ste_opt_lineno = 0; + ste->ste_lineno = lineno; + + if (st->st_cur != NULL && + (st->st_cur->ste_nested || + st->st_cur->ste_type == FunctionBlock)) + ste->ste_nested = 1; + ste->ste_child_free = 0; + ste->ste_generator = 0; + ste->ste_returns_value = 0; + + if (PyDict_SetItem(st->st_blocks, ste->ste_id, (PyObject *)ste) < 0) + goto fail; + + return ste; fail: - Py_XDECREF(ste); - return NULL; + Py_XDECREF(ste); + return NULL; } static PyObject * ste_repr(PySTEntryObject *ste) { - return PyUnicode_FromFormat("", - ste->ste_name, - PyLong_AS_LONG(ste->ste_id), ste->ste_lineno); + return PyUnicode_FromFormat("", + ste->ste_name, + PyLong_AS_LONG(ste->ste_id), ste->ste_lineno); } static void ste_dealloc(PySTEntryObject *ste) { - ste->ste_table = NULL; - Py_XDECREF(ste->ste_id); - Py_XDECREF(ste->ste_name); - Py_XDECREF(ste->ste_symbols); - Py_XDECREF(ste->ste_varnames); - Py_XDECREF(ste->ste_children); - PyObject_Del(ste); + ste->ste_table = NULL; + Py_XDECREF(ste->ste_id); + Py_XDECREF(ste->ste_name); + Py_XDECREF(ste->ste_symbols); + Py_XDECREF(ste->ste_varnames); + Py_XDECREF(ste->ste_children); + PyObject_Del(ste); } #define OFF(x) offsetof(PySTEntryObject, x) static PyMemberDef ste_memberlist[] = { - {"id", T_OBJECT, OFF(ste_id), READONLY}, - {"name", T_OBJECT, OFF(ste_name), READONLY}, - {"symbols", T_OBJECT, OFF(ste_symbols), READONLY}, - {"varnames", T_OBJECT, OFF(ste_varnames), READONLY}, - {"children", T_OBJECT, OFF(ste_children), READONLY}, - {"optimized",T_INT, OFF(ste_unoptimized), READONLY}, - {"nested", T_INT, OFF(ste_nested), READONLY}, - {"type", T_INT, OFF(ste_type), READONLY}, - {"lineno", T_INT, OFF(ste_lineno), READONLY}, - {NULL} + {"id", T_OBJECT, OFF(ste_id), READONLY}, + {"name", T_OBJECT, OFF(ste_name), READONLY}, + {"symbols", T_OBJECT, OFF(ste_symbols), READONLY}, + {"varnames", T_OBJECT, OFF(ste_varnames), READONLY}, + {"children", T_OBJECT, OFF(ste_children), READONLY}, + {"optimized",T_INT, OFF(ste_unoptimized), READONLY}, + {"nested", T_INT, OFF(ste_nested), READONLY}, + {"type", T_INT, OFF(ste_type), READONLY}, + {"lineno", T_INT, OFF(ste_lineno), READONLY}, + {NULL} }; PyTypeObject PySTEntry_Type = { - PyVarObject_HEAD_INIT(&PyType_Type, 0) - "symtable entry", - sizeof(PySTEntryObject), - 0, - (destructor)ste_dealloc, /* tp_dealloc */ - 0, /* tp_print */ - 0, /* tp_getattr */ - 0, /* tp_setattr */ - 0, /* tp_reserved */ - (reprfunc)ste_repr, /* tp_repr */ - 0, /* tp_as_number */ - 0, /* tp_as_sequence */ - 0, /* tp_as_mapping */ - 0, /* tp_hash */ - 0, /* tp_call */ - 0, /* tp_str */ - PyObject_GenericGetAttr, /* tp_getattro */ - 0, /* tp_setattro */ - 0, /* tp_as_buffer */ - Py_TPFLAGS_DEFAULT, /* tp_flags */ - 0, /* tp_doc */ - 0, /* tp_traverse */ - 0, /* tp_clear */ - 0, /* tp_richcompare */ - 0, /* tp_weaklistoffset */ - 0, /* tp_iter */ - 0, /* tp_iternext */ - 0, /* tp_methods */ - ste_memberlist, /* tp_members */ - 0, /* tp_getset */ - 0, /* tp_base */ - 0, /* tp_dict */ - 0, /* tp_descr_get */ - 0, /* tp_descr_set */ - 0, /* tp_dictoffset */ - 0, /* tp_init */ - 0, /* tp_alloc */ - 0, /* tp_new */ + PyVarObject_HEAD_INIT(&PyType_Type, 0) + "symtable entry", + sizeof(PySTEntryObject), + 0, + (destructor)ste_dealloc, /* tp_dealloc */ + 0, /* tp_print */ + 0, /* tp_getattr */ + 0, /* tp_setattr */ + 0, /* tp_reserved */ + (reprfunc)ste_repr, /* tp_repr */ + 0, /* tp_as_number */ + 0, /* tp_as_sequence */ + 0, /* tp_as_mapping */ + 0, /* tp_hash */ + 0, /* tp_call */ + 0, /* tp_str */ + PyObject_GenericGetAttr, /* tp_getattro */ + 0, /* tp_setattro */ + 0, /* tp_as_buffer */ + Py_TPFLAGS_DEFAULT, /* tp_flags */ + 0, /* tp_doc */ + 0, /* tp_traverse */ + 0, /* tp_clear */ + 0, /* tp_richcompare */ + 0, /* tp_weaklistoffset */ + 0, /* tp_iter */ + 0, /* tp_iternext */ + 0, /* tp_methods */ + ste_memberlist, /* tp_members */ + 0, /* tp_getset */ + 0, /* tp_base */ + 0, /* tp_dict */ + 0, /* tp_descr_get */ + 0, /* tp_descr_set */ + 0, /* tp_dictoffset */ + 0, /* tp_init */ + 0, /* tp_alloc */ + 0, /* tp_new */ }; static int symtable_analyze(struct symtable *st); static int symtable_warn(struct symtable *st, char *msg, int lineno); -static int symtable_enter_block(struct symtable *st, identifier name, - _Py_block_ty block, void *ast, int lineno); +static int symtable_enter_block(struct symtable *st, identifier name, + _Py_block_ty block, void *ast, int lineno); static int symtable_exit_block(struct symtable *st, void *ast); static int symtable_visit_stmt(struct symtable *st, stmt_ty s); static int symtable_visit_expr(struct symtable *st, expr_ty s); @@ -184,11 +184,11 @@ static identifier top = NULL, lambda = NULL, genexpr = NULL, - listcomp = NULL, setcomp = NULL, dictcomp = NULL, - __class__ = NULL, __locals__ = NULL; + listcomp = NULL, setcomp = NULL, dictcomp = NULL, + __class__ = NULL, __locals__ = NULL; #define GET_IDENTIFIER(VAR) \ - ((VAR) ? (VAR) : ((VAR) = PyUnicode_InternFromString(# VAR))) + ((VAR) ? (VAR) : ((VAR) = PyUnicode_InternFromString(# VAR))) #define DUPLICATE_ARGUMENT \ "duplicate argument '%U' in function definition" @@ -196,135 +196,135 @@ static struct symtable * symtable_new(void) { - struct symtable *st; + struct symtable *st; - st = (struct symtable *)PyMem_Malloc(sizeof(struct symtable)); - if (st == NULL) - return NULL; - - st->st_filename = NULL; - st->st_blocks = NULL; - - if ((st->st_stack = PyList_New(0)) == NULL) - goto fail; - if ((st->st_blocks = PyDict_New()) == NULL) - goto fail; - st->st_cur = NULL; - st->st_private = NULL; - return st; + st = (struct symtable *)PyMem_Malloc(sizeof(struct symtable)); + if (st == NULL) + return NULL; + + st->st_filename = NULL; + st->st_blocks = NULL; + + if ((st->st_stack = PyList_New(0)) == NULL) + goto fail; + if ((st->st_blocks = PyDict_New()) == NULL) + goto fail; + st->st_cur = NULL; + st->st_private = NULL; + return st; fail: - PySymtable_Free(st); - return NULL; + PySymtable_Free(st); + return NULL; } struct symtable * PySymtable_Build(mod_ty mod, const char *filename, PyFutureFeatures *future) { - struct symtable *st = symtable_new(); - asdl_seq *seq; - int i; - - if (st == NULL) - return st; - st->st_filename = filename; - st->st_future = future; - /* Make the initial symbol information gathering pass */ - if (!GET_IDENTIFIER(top) || - !symtable_enter_block(st, top, ModuleBlock, (void *)mod, 0)) { - PySymtable_Free(st); - return NULL; - } - - st->st_top = st->st_cur; - st->st_cur->ste_unoptimized = OPT_TOPLEVEL; - switch (mod->kind) { - case Module_kind: - seq = mod->v.Module.body; - for (i = 0; i < asdl_seq_LEN(seq); i++) - if (!symtable_visit_stmt(st, - (stmt_ty)asdl_seq_GET(seq, i))) - goto error; - break; - case Expression_kind: - if (!symtable_visit_expr(st, mod->v.Expression.body)) - goto error; - break; - case Interactive_kind: - seq = mod->v.Interactive.body; - for (i = 0; i < asdl_seq_LEN(seq); i++) - if (!symtable_visit_stmt(st, - (stmt_ty)asdl_seq_GET(seq, i))) - goto error; - break; - case Suite_kind: - PyErr_SetString(PyExc_RuntimeError, - "this compiler does not handle Suites"); - goto error; - } - if (!symtable_exit_block(st, (void *)mod)) { - PySymtable_Free(st); - return NULL; - } - /* Make the second symbol analysis pass */ - if (symtable_analyze(st)) - return st; - PySymtable_Free(st); - return NULL; + struct symtable *st = symtable_new(); + asdl_seq *seq; + int i; + + if (st == NULL) + return st; + st->st_filename = filename; + st->st_future = future; + /* Make the initial symbol information gathering pass */ + if (!GET_IDENTIFIER(top) || + !symtable_enter_block(st, top, ModuleBlock, (void *)mod, 0)) { + PySymtable_Free(st); + return NULL; + } + + st->st_top = st->st_cur; + st->st_cur->ste_unoptimized = OPT_TOPLEVEL; + switch (mod->kind) { + case Module_kind: + seq = mod->v.Module.body; + for (i = 0; i < asdl_seq_LEN(seq); i++) + if (!symtable_visit_stmt(st, + (stmt_ty)asdl_seq_GET(seq, i))) + goto error; + break; + case Expression_kind: + if (!symtable_visit_expr(st, mod->v.Expression.body)) + goto error; + break; + case Interactive_kind: + seq = mod->v.Interactive.body; + for (i = 0; i < asdl_seq_LEN(seq); i++) + if (!symtable_visit_stmt(st, + (stmt_ty)asdl_seq_GET(seq, i))) + goto error; + break; + case Suite_kind: + PyErr_SetString(PyExc_RuntimeError, + "this compiler does not handle Suites"); + goto error; + } + if (!symtable_exit_block(st, (void *)mod)) { + PySymtable_Free(st); + return NULL; + } + /* Make the second symbol analysis pass */ + if (symtable_analyze(st)) + return st; + PySymtable_Free(st); + return NULL; error: - (void) symtable_exit_block(st, (void *)mod); - PySymtable_Free(st); - return NULL; + (void) symtable_exit_block(st, (void *)mod); + PySymtable_Free(st); + return NULL; } void PySymtable_Free(struct symtable *st) { - Py_XDECREF(st->st_blocks); - Py_XDECREF(st->st_stack); - PyMem_Free((void *)st); + Py_XDECREF(st->st_blocks); + Py_XDECREF(st->st_stack); + PyMem_Free((void *)st); } PySTEntryObject * PySymtable_Lookup(struct symtable *st, void *key) { - PyObject *k, *v; + PyObject *k, *v; - k = PyLong_FromVoidPtr(key); - if (k == NULL) - return NULL; - v = PyDict_GetItem(st->st_blocks, k); - if (v) { - assert(PySTEntry_Check(v)); - Py_INCREF(v); - } - else { - PyErr_SetString(PyExc_KeyError, - "unknown symbol table entry"); - } + k = PyLong_FromVoidPtr(key); + if (k == NULL) + return NULL; + v = PyDict_GetItem(st->st_blocks, k); + if (v) { + assert(PySTEntry_Check(v)); + Py_INCREF(v); + } + else { + PyErr_SetString(PyExc_KeyError, + "unknown symbol table entry"); + } - Py_DECREF(k); - return (PySTEntryObject *)v; + Py_DECREF(k); + return (PySTEntryObject *)v; } -int +int PyST_GetScope(PySTEntryObject *ste, PyObject *name) { - PyObject *v = PyDict_GetItem(ste->ste_symbols, name); - if (!v) - return 0; - assert(PyLong_Check(v)); - return (PyLong_AS_LONG(v) >> SCOPE_OFFSET) & SCOPE_MASK; + PyObject *v = PyDict_GetItem(ste->ste_symbols, name); + if (!v) + return 0; + assert(PyLong_Check(v)); + return (PyLong_AS_LONG(v) >> SCOPE_OFFSET) & SCOPE_MASK; } /* Analyze raw symbol information to determine scope of each name. The next several functions are helpers for symtable_analyze(), - which determines whether a name is local, global, or free. In addition, + which determines whether a name is local, global, or free. In addition, it determines which local variables are cell variables; they provide - bindings that are used for free variables in enclosed blocks. + bindings that are used for free variables in enclosed blocks. - There are also two kinds of global variables, implicit and explicit. An + There are also two kinds of global variables, implicit and explicit. An explicit global is declared with the global statement. An implicit global is a free variable for which the compiler has found no binding in an enclosing function scope. The implicit global is either a global @@ -340,7 +340,7 @@ PySTEntryObjects created during pass 1. When a function is entered during the second pass, the parent passes - the set of all name bindings visible to its children. These bindings + the set of all name bindings visible to its children. These bindings are used to determine if non-local variables are free or implicit globals. Names which are explicitly declared nonlocal must exist in this set of visible names - if they do not, a syntax error is raised. After doing @@ -363,14 +363,14 @@ */ #define SET_SCOPE(DICT, NAME, I) { \ - PyObject *o = PyLong_FromLong(I); \ - if (!o) \ - return 0; \ - if (PyDict_SetItem((DICT), (NAME), o) < 0) { \ - Py_DECREF(o); \ - return 0; \ - } \ - Py_DECREF(o); \ + PyObject *o = PyLong_FromLong(I); \ + if (!o) \ + return 0; \ + if (PyDict_SetItem((DICT), (NAME), o) < 0) { \ + Py_DECREF(o); \ + return 0; \ + } \ + Py_DECREF(o); \ } /* Decide on scope of name, given flags. @@ -380,86 +380,86 @@ global. A name that was global can be changed to local. */ -static int +static int analyze_name(PySTEntryObject *ste, PyObject *scopes, PyObject *name, long flags, - PyObject *bound, PyObject *local, PyObject *free, - PyObject *global) + PyObject *bound, PyObject *local, PyObject *free, + PyObject *global) { - if (flags & DEF_GLOBAL) { - if (flags & DEF_PARAM) { - PyErr_Format(PyExc_SyntaxError, - "name '%U' is parameter and global", - name); - PyErr_SyntaxLocation(ste->ste_table->st_filename, - ste->ste_lineno); - - return 0; - } - if (flags & DEF_NONLOCAL) { - PyErr_Format(PyExc_SyntaxError, - "name '%U' is nonlocal and global", - name); - return 0; - } - SET_SCOPE(scopes, name, GLOBAL_EXPLICIT); - if (PySet_Add(global, name) < 0) - return 0; - if (bound && (PySet_Discard(bound, name) < 0)) - return 0; - return 1; - } + if (flags & DEF_GLOBAL) { + if (flags & DEF_PARAM) { + PyErr_Format(PyExc_SyntaxError, + "name '%U' is parameter and global", + name); + PyErr_SyntaxLocation(ste->ste_table->st_filename, + ste->ste_lineno); + + return 0; + } if (flags & DEF_NONLOCAL) { - if (flags & DEF_PARAM) { - PyErr_Format(PyExc_SyntaxError, - "name '%U' is parameter and nonlocal", - name); - return 0; - } - if (!bound) { - PyErr_Format(PyExc_SyntaxError, - "nonlocal declaration not allowed at module level"); - return 0; - } - if (!PySet_Contains(bound, name)) { - PyErr_Format(PyExc_SyntaxError, - "no binding for nonlocal '%U' found", - name); - - return 0; - } - SET_SCOPE(scopes, name, FREE); - ste->ste_free = 1; - return PySet_Add(free, name) >= 0; - } - if (flags & DEF_BOUND) { - SET_SCOPE(scopes, name, LOCAL); - if (PySet_Add(local, name) < 0) - return 0; - if (PySet_Discard(global, name) < 0) - return 0; - return 1; - } - /* If an enclosing block has a binding for this name, it - is a free variable rather than a global variable. - Note that having a non-NULL bound implies that the block - is nested. - */ - if (bound && PySet_Contains(bound, name)) { - SET_SCOPE(scopes, name, FREE); - ste->ste_free = 1; - return PySet_Add(free, name) >= 0; - } - /* If a parent has a global statement, then call it global - explicit? It could also be global implicit. - */ - if (global && PySet_Contains(global, name)) { - SET_SCOPE(scopes, name, GLOBAL_IMPLICIT); - return 1; - } - if (ste->ste_nested) - ste->ste_free = 1; - SET_SCOPE(scopes, name, GLOBAL_IMPLICIT); - return 1; + PyErr_Format(PyExc_SyntaxError, + "name '%U' is nonlocal and global", + name); + return 0; + } + SET_SCOPE(scopes, name, GLOBAL_EXPLICIT); + if (PySet_Add(global, name) < 0) + return 0; + if (bound && (PySet_Discard(bound, name) < 0)) + return 0; + return 1; + } + if (flags & DEF_NONLOCAL) { + if (flags & DEF_PARAM) { + PyErr_Format(PyExc_SyntaxError, + "name '%U' is parameter and nonlocal", + name); + return 0; + } + if (!bound) { + PyErr_Format(PyExc_SyntaxError, + "nonlocal declaration not allowed at module level"); + return 0; + } + if (!PySet_Contains(bound, name)) { + PyErr_Format(PyExc_SyntaxError, + "no binding for nonlocal '%U' found", + name); + + return 0; + } + SET_SCOPE(scopes, name, FREE); + ste->ste_free = 1; + return PySet_Add(free, name) >= 0; + } + if (flags & DEF_BOUND) { + SET_SCOPE(scopes, name, LOCAL); + if (PySet_Add(local, name) < 0) + return 0; + if (PySet_Discard(global, name) < 0) + return 0; + return 1; + } + /* If an enclosing block has a binding for this name, it + is a free variable rather than a global variable. + Note that having a non-NULL bound implies that the block + is nested. + */ + if (bound && PySet_Contains(bound, name)) { + SET_SCOPE(scopes, name, FREE); + ste->ste_free = 1; + return PySet_Add(free, name) >= 0; + } + /* If a parent has a global statement, then call it global + explicit? It could also be global implicit. + */ + if (global && PySet_Contains(global, name)) { + SET_SCOPE(scopes, name, GLOBAL_IMPLICIT); + return 1; + } + if (ste->ste_nested) + ste->ste_free = 1; + SET_SCOPE(scopes, name, GLOBAL_IMPLICIT); + return 1; } #undef SET_SCOPE @@ -478,153 +478,153 @@ static int analyze_cells(PyObject *scopes, PyObject *free, const char *restricted) { - PyObject *name, *v, *v_cell; - int success = 0; - Py_ssize_t pos = 0; - - v_cell = PyLong_FromLong(CELL); - if (!v_cell) - return 0; - while (PyDict_Next(scopes, &pos, &name, &v)) { - long scope; - assert(PyLong_Check(v)); - scope = PyLong_AS_LONG(v); - if (scope != LOCAL) - continue; - if (!PySet_Contains(free, name)) - continue; - if (restricted != NULL && - PyUnicode_CompareWithASCIIString(name, restricted)) - continue; - /* Replace LOCAL with CELL for this name, and remove - from free. It is safe to replace the value of name - in the dict, because it will not cause a resize. - */ - if (PyDict_SetItem(scopes, name, v_cell) < 0) - goto error; - if (PySet_Discard(free, name) < 0) - goto error; - } - success = 1; + PyObject *name, *v, *v_cell; + int success = 0; + Py_ssize_t pos = 0; + + v_cell = PyLong_FromLong(CELL); + if (!v_cell) + return 0; + while (PyDict_Next(scopes, &pos, &name, &v)) { + long scope; + assert(PyLong_Check(v)); + scope = PyLong_AS_LONG(v); + if (scope != LOCAL) + continue; + if (!PySet_Contains(free, name)) + continue; + if (restricted != NULL && + PyUnicode_CompareWithASCIIString(name, restricted)) + continue; + /* Replace LOCAL with CELL for this name, and remove + from free. It is safe to replace the value of name + in the dict, because it will not cause a resize. + */ + if (PyDict_SetItem(scopes, name, v_cell) < 0) + goto error; + if (PySet_Discard(free, name) < 0) + goto error; + } + success = 1; error: - Py_DECREF(v_cell); - return success; + Py_DECREF(v_cell); + return success; } /* Check for illegal statements in unoptimized namespaces */ static int check_unoptimized(const PySTEntryObject* ste) { - const char* trailer; + const char* trailer; - if (ste->ste_type != FunctionBlock || !ste->ste_unoptimized - || !(ste->ste_free || ste->ste_child_free)) - return 1; - - trailer = (ste->ste_child_free ? - "contains a nested function with free variables" : - "is a nested function"); - - switch (ste->ste_unoptimized) { - case OPT_TOPLEVEL: /* import * at top-level is fine */ - return 1; - case OPT_IMPORT_STAR: - PyErr_Format(PyExc_SyntaxError, - "import * is not allowed in function '%U' because it %s", - ste->ste_name, trailer); - break; - } - - PyErr_SyntaxLocation(ste->ste_table->st_filename, - ste->ste_opt_lineno); - return 0; + if (ste->ste_type != FunctionBlock || !ste->ste_unoptimized + || !(ste->ste_free || ste->ste_child_free)) + return 1; + + trailer = (ste->ste_child_free ? + "contains a nested function with free variables" : + "is a nested function"); + + switch (ste->ste_unoptimized) { + case OPT_TOPLEVEL: /* import * at top-level is fine */ + return 1; + case OPT_IMPORT_STAR: + PyErr_Format(PyExc_SyntaxError, + "import * is not allowed in function '%U' because it %s", + ste->ste_name, trailer); + break; + } + + PyErr_SyntaxLocation(ste->ste_table->st_filename, + ste->ste_opt_lineno); + return 0; } -/* Enter the final scope information into the ste_symbols dict. - * +/* Enter the final scope information into the ste_symbols dict. + * * All arguments are dicts. Modifies symbols, others are read-only. */ static int -update_symbols(PyObject *symbols, PyObject *scopes, +update_symbols(PyObject *symbols, PyObject *scopes, PyObject *bound, PyObject *free, int classflag) { - PyObject *name = NULL, *itr = NULL; - PyObject *v = NULL, *v_scope = NULL, *v_new = NULL, *v_free = NULL; - Py_ssize_t pos = 0; - - /* Update scope information for all symbols in this scope */ - while (PyDict_Next(symbols, &pos, &name, &v)) { - long scope, flags; - assert(PyLong_Check(v)); - flags = PyLong_AS_LONG(v); - v_scope = PyDict_GetItem(scopes, name); - assert(v_scope && PyLong_Check(v_scope)); - scope = PyLong_AS_LONG(v_scope); - flags |= (scope << SCOPE_OFFSET); - v_new = PyLong_FromLong(flags); - if (!v_new) - return 0; - if (PyDict_SetItem(symbols, name, v_new) < 0) { - Py_DECREF(v_new); - return 0; - } - Py_DECREF(v_new); - } - - /* Record not yet resolved free variables from children (if any) */ - v_free = PyLong_FromLong(FREE << SCOPE_OFFSET); - if (!v_free) - return 0; - - itr = PyObject_GetIter(free); - if (!itr) - goto error; - - while ((name = PyIter_Next(itr))) { - v = PyDict_GetItem(symbols, name); - - /* Handle symbol that already exists in this scope */ - if (v) { - /* Handle a free variable in a method of - the class that has the same name as a local - or global in the class scope. - */ - if (classflag && - PyLong_AS_LONG(v) & (DEF_BOUND | DEF_GLOBAL)) { - long flags = PyLong_AS_LONG(v) | DEF_FREE_CLASS; - v_new = PyLong_FromLong(flags); - if (!v_new) { - goto error; - } - if (PyDict_SetItem(symbols, name, v_new) < 0) { - Py_DECREF(v_new); - goto error; - } - Py_DECREF(v_new); - } - /* It's a cell, or already free in this scope */ - Py_DECREF(name); - continue; - } - /* Handle global symbol */ - if (!PySet_Contains(bound, name)) { - Py_DECREF(name); - continue; /* it's a global */ - } - /* Propagate new free symbol up the lexical stack */ - if (PyDict_SetItem(symbols, name, v_free) < 0) { - goto error; - } - Py_DECREF(name); - } - Py_DECREF(itr); - Py_DECREF(v_free); - return 1; + PyObject *name = NULL, *itr = NULL; + PyObject *v = NULL, *v_scope = NULL, *v_new = NULL, *v_free = NULL; + Py_ssize_t pos = 0; + + /* Update scope information for all symbols in this scope */ + while (PyDict_Next(symbols, &pos, &name, &v)) { + long scope, flags; + assert(PyLong_Check(v)); + flags = PyLong_AS_LONG(v); + v_scope = PyDict_GetItem(scopes, name); + assert(v_scope && PyLong_Check(v_scope)); + scope = PyLong_AS_LONG(v_scope); + flags |= (scope << SCOPE_OFFSET); + v_new = PyLong_FromLong(flags); + if (!v_new) + return 0; + if (PyDict_SetItem(symbols, name, v_new) < 0) { + Py_DECREF(v_new); + return 0; + } + Py_DECREF(v_new); + } + + /* Record not yet resolved free variables from children (if any) */ + v_free = PyLong_FromLong(FREE << SCOPE_OFFSET); + if (!v_free) + return 0; + + itr = PyObject_GetIter(free); + if (!itr) + goto error; + + while ((name = PyIter_Next(itr))) { + v = PyDict_GetItem(symbols, name); + + /* Handle symbol that already exists in this scope */ + if (v) { + /* Handle a free variable in a method of + the class that has the same name as a local + or global in the class scope. + */ + if (classflag && + PyLong_AS_LONG(v) & (DEF_BOUND | DEF_GLOBAL)) { + long flags = PyLong_AS_LONG(v) | DEF_FREE_CLASS; + v_new = PyLong_FromLong(flags); + if (!v_new) { + goto error; + } + if (PyDict_SetItem(symbols, name, v_new) < 0) { + Py_DECREF(v_new); + goto error; + } + Py_DECREF(v_new); + } + /* It's a cell, or already free in this scope */ + Py_DECREF(name); + continue; + } + /* Handle global symbol */ + if (!PySet_Contains(bound, name)) { + Py_DECREF(name); + continue; /* it's a global */ + } + /* Propagate new free symbol up the lexical stack */ + if (PyDict_SetItem(symbols, name, v_free) < 0) { + goto error; + } + Py_DECREF(name); + } + Py_DECREF(itr); + Py_DECREF(v_free); + return 1; error: - Py_XDECREF(v_free); - Py_XDECREF(itr); - Py_XDECREF(name); - return 0; -} + Py_XDECREF(v_free); + Py_XDECREF(itr); + Py_XDECREF(name); + return 0; +} /* Make final symbol table decisions for block of ste. @@ -647,238 +647,238 @@ */ static int -analyze_child_block(PySTEntryObject *entry, PyObject *bound, PyObject *free, - PyObject *global, PyObject* child_free); +analyze_child_block(PySTEntryObject *entry, PyObject *bound, PyObject *free, + PyObject *global, PyObject* child_free); static int -analyze_block(PySTEntryObject *ste, PyObject *bound, PyObject *free, - PyObject *global) +analyze_block(PySTEntryObject *ste, PyObject *bound, PyObject *free, + PyObject *global) { - PyObject *name, *v, *local = NULL, *scopes = NULL, *newbound = NULL; - PyObject *newglobal = NULL, *newfree = NULL, *allfree = NULL; - PyObject *temp; - int i, success = 0; - Py_ssize_t pos = 0; - - local = PySet_New(NULL); /* collect new names bound in block */ - if (!local) - goto error; - scopes = PyDict_New(); /* collect scopes defined for each name */ - if (!scopes) - goto error; - - /* Allocate new global and bound variable dictionaries. These - dictionaries hold the names visible in nested blocks. For - ClassBlocks, the bound and global names are initialized - before analyzing names, because class bindings aren't - visible in methods. For other blocks, they are initialized - after names are analyzed. - */ - - /* TODO(jhylton): Package these dicts in a struct so that we - can write reasonable helper functions? - */ - newglobal = PySet_New(NULL); - if (!newglobal) - goto error; - newfree = PySet_New(NULL); - if (!newfree) - goto error; - newbound = PySet_New(NULL); - if (!newbound) - goto error; - - /* Class namespace has no effect on names visible in - nested functions, so populate the global and bound - sets to be passed to child blocks before analyzing - this one. - */ - if (ste->ste_type == ClassBlock) { - /* Pass down known globals */ - temp = PyNumber_InPlaceOr(newglobal, global); - if (!temp) - goto error; - Py_DECREF(temp); - /* Pass down previously bound symbols */ - if (bound) { - temp = PyNumber_InPlaceOr(newbound, bound); - if (!temp) - goto error; - Py_DECREF(temp); - } - } - - while (PyDict_Next(ste->ste_symbols, &pos, &name, &v)) { - long flags = PyLong_AS_LONG(v); - if (!analyze_name(ste, scopes, name, flags, - bound, local, free, global)) - goto error; - } - - /* Populate global and bound sets to be passed to children. */ - if (ste->ste_type != ClassBlock) { - /* Add function locals to bound set */ - if (ste->ste_type == FunctionBlock) { - temp = PyNumber_InPlaceOr(newbound, local); - if (!temp) - goto error; - Py_DECREF(temp); - } - /* Pass down previously bound symbols */ - if (bound) { - temp = PyNumber_InPlaceOr(newbound, bound); - if (!temp) - goto error; - Py_DECREF(temp); - } - /* Pass down known globals */ - temp = PyNumber_InPlaceOr(newglobal, global); - if (!temp) - goto error; - Py_DECREF(temp); - } - else { - /* Special-case __class__ */ - if (!GET_IDENTIFIER(__class__)) - goto error; - assert(PySet_Contains(local, __class__) == 1); - if (PySet_Add(newbound, __class__) < 0) - goto error; - } - - /* Recursively call analyze_block() on each child block. - - newbound, newglobal now contain the names visible in - nested blocks. The free variables in the children will - be collected in allfree. - */ - allfree = PySet_New(NULL); - if (!allfree) - goto error; - for (i = 0; i < PyList_GET_SIZE(ste->ste_children); ++i) { - PyObject *c = PyList_GET_ITEM(ste->ste_children, i); - PySTEntryObject* entry; - assert(c && PySTEntry_Check(c)); - entry = (PySTEntryObject*)c; - if (!analyze_child_block(entry, newbound, newfree, newglobal, - allfree)) - goto error; - /* Check if any children have free variables */ - if (entry->ste_free || entry->ste_child_free) - ste->ste_child_free = 1; - } - - temp = PyNumber_InPlaceOr(newfree, allfree); - if (!temp) - goto error; - Py_DECREF(temp); - - /* Check if any local variables must be converted to cell variables */ - if (ste->ste_type == FunctionBlock && !analyze_cells(scopes, newfree, - NULL)) - goto error; - else if (ste->ste_type == ClassBlock && !analyze_cells(scopes, newfree, - "__class__")) - goto error; - /* Records the results of the analysis in the symbol table entry */ - if (!update_symbols(ste->ste_symbols, scopes, bound, newfree, - ste->ste_type == ClassBlock)) - goto error; - if (!check_unoptimized(ste)) - goto error; - - temp = PyNumber_InPlaceOr(free, newfree); - if (!temp) - goto error; - Py_DECREF(temp); - success = 1; + PyObject *name, *v, *local = NULL, *scopes = NULL, *newbound = NULL; + PyObject *newglobal = NULL, *newfree = NULL, *allfree = NULL; + PyObject *temp; + int i, success = 0; + Py_ssize_t pos = 0; + + local = PySet_New(NULL); /* collect new names bound in block */ + if (!local) + goto error; + scopes = PyDict_New(); /* collect scopes defined for each name */ + if (!scopes) + goto error; + + /* Allocate new global and bound variable dictionaries. These + dictionaries hold the names visible in nested blocks. For + ClassBlocks, the bound and global names are initialized + before analyzing names, because class bindings aren't + visible in methods. For other blocks, they are initialized + after names are analyzed. + */ + + /* TODO(jhylton): Package these dicts in a struct so that we + can write reasonable helper functions? + */ + newglobal = PySet_New(NULL); + if (!newglobal) + goto error; + newfree = PySet_New(NULL); + if (!newfree) + goto error; + newbound = PySet_New(NULL); + if (!newbound) + goto error; + + /* Class namespace has no effect on names visible in + nested functions, so populate the global and bound + sets to be passed to child blocks before analyzing + this one. + */ + if (ste->ste_type == ClassBlock) { + /* Pass down known globals */ + temp = PyNumber_InPlaceOr(newglobal, global); + if (!temp) + goto error; + Py_DECREF(temp); + /* Pass down previously bound symbols */ + if (bound) { + temp = PyNumber_InPlaceOr(newbound, bound); + if (!temp) + goto error; + Py_DECREF(temp); + } + } + + while (PyDict_Next(ste->ste_symbols, &pos, &name, &v)) { + long flags = PyLong_AS_LONG(v); + if (!analyze_name(ste, scopes, name, flags, + bound, local, free, global)) + goto error; + } + + /* Populate global and bound sets to be passed to children. */ + if (ste->ste_type != ClassBlock) { + /* Add function locals to bound set */ + if (ste->ste_type == FunctionBlock) { + temp = PyNumber_InPlaceOr(newbound, local); + if (!temp) + goto error; + Py_DECREF(temp); + } + /* Pass down previously bound symbols */ + if (bound) { + temp = PyNumber_InPlaceOr(newbound, bound); + if (!temp) + goto error; + Py_DECREF(temp); + } + /* Pass down known globals */ + temp = PyNumber_InPlaceOr(newglobal, global); + if (!temp) + goto error; + Py_DECREF(temp); + } + else { + /* Special-case __class__ */ + if (!GET_IDENTIFIER(__class__)) + goto error; + assert(PySet_Contains(local, __class__) == 1); + if (PySet_Add(newbound, __class__) < 0) + goto error; + } + + /* Recursively call analyze_block() on each child block. + + newbound, newglobal now contain the names visible in + nested blocks. The free variables in the children will + be collected in allfree. + */ + allfree = PySet_New(NULL); + if (!allfree) + goto error; + for (i = 0; i < PyList_GET_SIZE(ste->ste_children); ++i) { + PyObject *c = PyList_GET_ITEM(ste->ste_children, i); + PySTEntryObject* entry; + assert(c && PySTEntry_Check(c)); + entry = (PySTEntryObject*)c; + if (!analyze_child_block(entry, newbound, newfree, newglobal, + allfree)) + goto error; + /* Check if any children have free variables */ + if (entry->ste_free || entry->ste_child_free) + ste->ste_child_free = 1; + } + + temp = PyNumber_InPlaceOr(newfree, allfree); + if (!temp) + goto error; + Py_DECREF(temp); + + /* Check if any local variables must be converted to cell variables */ + if (ste->ste_type == FunctionBlock && !analyze_cells(scopes, newfree, + NULL)) + goto error; + else if (ste->ste_type == ClassBlock && !analyze_cells(scopes, newfree, + "__class__")) + goto error; + /* Records the results of the analysis in the symbol table entry */ + if (!update_symbols(ste->ste_symbols, scopes, bound, newfree, + ste->ste_type == ClassBlock)) + goto error; + if (!check_unoptimized(ste)) + goto error; + + temp = PyNumber_InPlaceOr(free, newfree); + if (!temp) + goto error; + Py_DECREF(temp); + success = 1; error: - Py_XDECREF(scopes); - Py_XDECREF(local); - Py_XDECREF(newbound); - Py_XDECREF(newglobal); - Py_XDECREF(newfree); - Py_XDECREF(allfree); - if (!success) - assert(PyErr_Occurred()); - return success; + Py_XDECREF(scopes); + Py_XDECREF(local); + Py_XDECREF(newbound); + Py_XDECREF(newglobal); + Py_XDECREF(newfree); + Py_XDECREF(allfree); + if (!success) + assert(PyErr_Occurred()); + return success; } static int -analyze_child_block(PySTEntryObject *entry, PyObject *bound, PyObject *free, - PyObject *global, PyObject* child_free) -{ - PyObject *temp_bound = NULL, *temp_global = NULL, *temp_free = NULL; - PyObject *temp; - - /* Copy the bound and global dictionaries. - - These dictionary are used by all blocks enclosed by the - current block. The analyze_block() call modifies these - dictionaries. - - */ - temp_bound = PySet_New(bound); - if (!temp_bound) - goto error; - temp_free = PySet_New(free); - if (!temp_free) - goto error; - temp_global = PySet_New(global); - if (!temp_global) - goto error; - - if (!analyze_block(entry, temp_bound, temp_free, temp_global)) - goto error; - temp = PyNumber_InPlaceOr(child_free, temp_free); - if (!temp) - goto error; - Py_DECREF(temp); - Py_DECREF(temp_bound); - Py_DECREF(temp_free); - Py_DECREF(temp_global); - return 1; +analyze_child_block(PySTEntryObject *entry, PyObject *bound, PyObject *free, + PyObject *global, PyObject* child_free) +{ + PyObject *temp_bound = NULL, *temp_global = NULL, *temp_free = NULL; + PyObject *temp; + + /* Copy the bound and global dictionaries. + + These dictionary are used by all blocks enclosed by the + current block. The analyze_block() call modifies these + dictionaries. + + */ + temp_bound = PySet_New(bound); + if (!temp_bound) + goto error; + temp_free = PySet_New(free); + if (!temp_free) + goto error; + temp_global = PySet_New(global); + if (!temp_global) + goto error; + + if (!analyze_block(entry, temp_bound, temp_free, temp_global)) + goto error; + temp = PyNumber_InPlaceOr(child_free, temp_free); + if (!temp) + goto error; + Py_DECREF(temp); + Py_DECREF(temp_bound); + Py_DECREF(temp_free); + Py_DECREF(temp_global); + return 1; error: - Py_XDECREF(temp_bound); - Py_XDECREF(temp_free); - Py_XDECREF(temp_global); - return 0; + Py_XDECREF(temp_bound); + Py_XDECREF(temp_free); + Py_XDECREF(temp_global); + return 0; } static int symtable_analyze(struct symtable *st) { - PyObject *free, *global; - int r; + PyObject *free, *global; + int r; - free = PySet_New(NULL); - if (!free) - return 0; - global = PySet_New(NULL); - if (!global) { - Py_DECREF(free); - return 0; - } - r = analyze_block(st->st_top, NULL, free, global); - Py_DECREF(free); - Py_DECREF(global); - return r; + free = PySet_New(NULL); + if (!free) + return 0; + global = PySet_New(NULL); + if (!global) { + Py_DECREF(free); + return 0; + } + r = analyze_block(st->st_top, NULL, free, global); + Py_DECREF(free); + Py_DECREF(global); + return r; } static int symtable_warn(struct symtable *st, char *msg, int lineno) { - if (PyErr_WarnExplicit(PyExc_SyntaxWarning, msg, st->st_filename, - lineno, NULL, NULL) < 0) { - if (PyErr_ExceptionMatches(PyExc_SyntaxWarning)) { - PyErr_SetString(PyExc_SyntaxError, msg); - PyErr_SyntaxLocation(st->st_filename, - st->st_cur->ste_lineno); - } - return 0; - } - return 1; + if (PyErr_WarnExplicit(PyExc_SyntaxWarning, msg, st->st_filename, + lineno, NULL, NULL) < 0) { + if (PyErr_ExceptionMatches(PyExc_SyntaxWarning)) { + PyErr_SetString(PyExc_SyntaxError, msg); + PyErr_SyntaxLocation(st->st_filename, + st->st_cur->ste_lineno); + } + return 0; + } + return 1; } /* symtable_enter_block() gets a reference via ste_new. @@ -889,792 +889,792 @@ static int symtable_exit_block(struct symtable *st, void *ast) { - Py_ssize_t end; + Py_ssize_t end; - Py_CLEAR(st->st_cur); - end = PyList_GET_SIZE(st->st_stack) - 1; - if (end >= 0) { - st->st_cur = (PySTEntryObject *)PyList_GET_ITEM(st->st_stack, - end); - if (st->st_cur == NULL) - return 0; - Py_INCREF(st->st_cur); - if (PySequence_DelItem(st->st_stack, end) < 0) - return 0; - } - return 1; + Py_CLEAR(st->st_cur); + end = PyList_GET_SIZE(st->st_stack) - 1; + if (end >= 0) { + st->st_cur = (PySTEntryObject *)PyList_GET_ITEM(st->st_stack, + end); + if (st->st_cur == NULL) + return 0; + Py_INCREF(st->st_cur); + if (PySequence_DelItem(st->st_stack, end) < 0) + return 0; + } + return 1; } static int -symtable_enter_block(struct symtable *st, identifier name, _Py_block_ty block, - void *ast, int lineno) -{ - PySTEntryObject *prev = NULL; - - if (st->st_cur) { - prev = st->st_cur; - if (PyList_Append(st->st_stack, (PyObject *)st->st_cur) < 0) { - return 0; - } - Py_DECREF(st->st_cur); - } - st->st_cur = ste_new(st, name, block, ast, lineno); - if (st->st_cur == NULL) - return 0; - if (name == GET_IDENTIFIER(top)) - st->st_global = st->st_cur->ste_symbols; - if (prev) { - if (PyList_Append(prev->ste_children, - (PyObject *)st->st_cur) < 0) { - return 0; - } - } - return 1; +symtable_enter_block(struct symtable *st, identifier name, _Py_block_ty block, + void *ast, int lineno) +{ + PySTEntryObject *prev = NULL; + + if (st->st_cur) { + prev = st->st_cur; + if (PyList_Append(st->st_stack, (PyObject *)st->st_cur) < 0) { + return 0; + } + Py_DECREF(st->st_cur); + } + st->st_cur = ste_new(st, name, block, ast, lineno); + if (st->st_cur == NULL) + return 0; + if (name == GET_IDENTIFIER(top)) + st->st_global = st->st_cur->ste_symbols; + if (prev) { + if (PyList_Append(prev->ste_children, + (PyObject *)st->st_cur) < 0) { + return 0; + } + } + return 1; } static long symtable_lookup(struct symtable *st, PyObject *name) { - PyObject *o; - PyObject *mangled = _Py_Mangle(st->st_private, name); - if (!mangled) - return 0; - o = PyDict_GetItem(st->st_cur->ste_symbols, mangled); - Py_DECREF(mangled); - if (!o) - return 0; - return PyLong_AsLong(o); + PyObject *o; + PyObject *mangled = _Py_Mangle(st->st_private, name); + if (!mangled) + return 0; + o = PyDict_GetItem(st->st_cur->ste_symbols, mangled); + Py_DECREF(mangled); + if (!o) + return 0; + return PyLong_AsLong(o); } static int -symtable_add_def(struct symtable *st, PyObject *name, int flag) -{ - PyObject *o; - PyObject *dict; - long val; - PyObject *mangled = _Py_Mangle(st->st_private, name); - - - if (!mangled) - return 0; - dict = st->st_cur->ste_symbols; - if ((o = PyDict_GetItem(dict, mangled))) { - val = PyLong_AS_LONG(o); - if ((flag & DEF_PARAM) && (val & DEF_PARAM)) { - /* Is it better to use 'mangled' or 'name' here? */ - PyErr_Format(PyExc_SyntaxError, DUPLICATE_ARGUMENT, name); - PyErr_SyntaxLocation(st->st_filename, - st->st_cur->ste_lineno); - goto error; - } - val |= flag; - } else - val = flag; - o = PyLong_FromLong(val); +symtable_add_def(struct symtable *st, PyObject *name, int flag) +{ + PyObject *o; + PyObject *dict; + long val; + PyObject *mangled = _Py_Mangle(st->st_private, name); + + + if (!mangled) + return 0; + dict = st->st_cur->ste_symbols; + if ((o = PyDict_GetItem(dict, mangled))) { + val = PyLong_AS_LONG(o); + if ((flag & DEF_PARAM) && (val & DEF_PARAM)) { + /* Is it better to use 'mangled' or 'name' here? */ + PyErr_Format(PyExc_SyntaxError, DUPLICATE_ARGUMENT, name); + PyErr_SyntaxLocation(st->st_filename, + st->st_cur->ste_lineno); + goto error; + } + val |= flag; + } else + val = flag; + o = PyLong_FromLong(val); + if (o == NULL) + goto error; + if (PyDict_SetItem(dict, mangled, o) < 0) { + Py_DECREF(o); + goto error; + } + Py_DECREF(o); + + if (flag & DEF_PARAM) { + if (PyList_Append(st->st_cur->ste_varnames, mangled) < 0) + goto error; + } else if (flag & DEF_GLOBAL) { + /* XXX need to update DEF_GLOBAL for other flags too; + perhaps only DEF_FREE_GLOBAL */ + val = flag; + if ((o = PyDict_GetItem(st->st_global, mangled))) { + val |= PyLong_AS_LONG(o); + } + o = PyLong_FromLong(val); if (o == NULL) - goto error; - if (PyDict_SetItem(dict, mangled, o) < 0) { - Py_DECREF(o); - goto error; - } - Py_DECREF(o); - - if (flag & DEF_PARAM) { - if (PyList_Append(st->st_cur->ste_varnames, mangled) < 0) - goto error; - } else if (flag & DEF_GLOBAL) { - /* XXX need to update DEF_GLOBAL for other flags too; - perhaps only DEF_FREE_GLOBAL */ - val = flag; - if ((o = PyDict_GetItem(st->st_global, mangled))) { - val |= PyLong_AS_LONG(o); - } - o = PyLong_FromLong(val); - if (o == NULL) - goto error; - if (PyDict_SetItem(st->st_global, mangled, o) < 0) { - Py_DECREF(o); - goto error; - } - Py_DECREF(o); - } - Py_DECREF(mangled); - return 1; + goto error; + if (PyDict_SetItem(st->st_global, mangled, o) < 0) { + Py_DECREF(o); + goto error; + } + Py_DECREF(o); + } + Py_DECREF(mangled); + return 1; error: - Py_DECREF(mangled); - return 0; + Py_DECREF(mangled); + return 0; } /* VISIT, VISIT_SEQ and VIST_SEQ_TAIL take an ASDL type as their second argument. They use the ASDL name to synthesize the name of the C type and the visit - function. - + function. + VISIT_SEQ_TAIL permits the start of an ASDL sequence to be skipped, which is useful if the first node in the sequence requires special treatment. */ #define VISIT(ST, TYPE, V) \ - if (!symtable_visit_ ## TYPE((ST), (V))) \ - return 0; + if (!symtable_visit_ ## TYPE((ST), (V))) \ + return 0; #define VISIT_IN_BLOCK(ST, TYPE, V, S) \ - if (!symtable_visit_ ## TYPE((ST), (V))) { \ - symtable_exit_block((ST), (S)); \ - return 0; \ - } + if (!symtable_visit_ ## TYPE((ST), (V))) { \ + symtable_exit_block((ST), (S)); \ + return 0; \ + } #define VISIT_SEQ(ST, TYPE, SEQ) { \ - int i; \ - asdl_seq *seq = (SEQ); /* avoid variable capture */ \ - for (i = 0; i < asdl_seq_LEN(seq); i++) { \ - TYPE ## _ty elt = (TYPE ## _ty)asdl_seq_GET(seq, i); \ - if (!symtable_visit_ ## TYPE((ST), elt)) \ - return 0; \ - } \ + int i; \ + asdl_seq *seq = (SEQ); /* avoid variable capture */ \ + for (i = 0; i < asdl_seq_LEN(seq); i++) { \ + TYPE ## _ty elt = (TYPE ## _ty)asdl_seq_GET(seq, i); \ + if (!symtable_visit_ ## TYPE((ST), elt)) \ + return 0; \ + } \ } #define VISIT_SEQ_IN_BLOCK(ST, TYPE, SEQ, S) { \ - int i; \ - asdl_seq *seq = (SEQ); /* avoid variable capture */ \ - for (i = 0; i < asdl_seq_LEN(seq); i++) { \ - TYPE ## _ty elt = (TYPE ## _ty)asdl_seq_GET(seq, i); \ - if (!symtable_visit_ ## TYPE((ST), elt)) { \ - symtable_exit_block((ST), (S)); \ - return 0; \ - } \ - } \ + int i; \ + asdl_seq *seq = (SEQ); /* avoid variable capture */ \ + for (i = 0; i < asdl_seq_LEN(seq); i++) { \ + TYPE ## _ty elt = (TYPE ## _ty)asdl_seq_GET(seq, i); \ + if (!symtable_visit_ ## TYPE((ST), elt)) { \ + symtable_exit_block((ST), (S)); \ + return 0; \ + } \ + } \ } #define VISIT_SEQ_TAIL(ST, TYPE, SEQ, START) { \ - int i; \ - asdl_seq *seq = (SEQ); /* avoid variable capture */ \ - for (i = (START); i < asdl_seq_LEN(seq); i++) { \ - TYPE ## _ty elt = (TYPE ## _ty)asdl_seq_GET(seq, i); \ - if (!symtable_visit_ ## TYPE((ST), elt)) \ - return 0; \ - } \ + int i; \ + asdl_seq *seq = (SEQ); /* avoid variable capture */ \ + for (i = (START); i < asdl_seq_LEN(seq); i++) { \ + TYPE ## _ty elt = (TYPE ## _ty)asdl_seq_GET(seq, i); \ + if (!symtable_visit_ ## TYPE((ST), elt)) \ + return 0; \ + } \ } #define VISIT_SEQ_TAIL_IN_BLOCK(ST, TYPE, SEQ, START, S) { \ - int i; \ - asdl_seq *seq = (SEQ); /* avoid variable capture */ \ - for (i = (START); i < asdl_seq_LEN(seq); i++) { \ - TYPE ## _ty elt = (TYPE ## _ty)asdl_seq_GET(seq, i); \ - if (!symtable_visit_ ## TYPE((ST), elt)) { \ - symtable_exit_block((ST), (S)); \ - return 0; \ - } \ - } \ + int i; \ + asdl_seq *seq = (SEQ); /* avoid variable capture */ \ + for (i = (START); i < asdl_seq_LEN(seq); i++) { \ + TYPE ## _ty elt = (TYPE ## _ty)asdl_seq_GET(seq, i); \ + if (!symtable_visit_ ## TYPE((ST), elt)) { \ + symtable_exit_block((ST), (S)); \ + return 0; \ + } \ + } \ } #define VISIT_KWONLYDEFAULTS(ST, KW_DEFAULTS) { \ - int i = 0; \ - asdl_seq *seq = (KW_DEFAULTS); /* avoid variable capture */ \ - for (i = 0; i < asdl_seq_LEN(seq); i++) { \ - expr_ty elt = (expr_ty)asdl_seq_GET(seq, i); \ - if (!elt) continue; /* can be NULL */ \ - if (!symtable_visit_expr((ST), elt)) \ - return 0; \ - } \ + int i = 0; \ + asdl_seq *seq = (KW_DEFAULTS); /* avoid variable capture */ \ + for (i = 0; i < asdl_seq_LEN(seq); i++) { \ + expr_ty elt = (expr_ty)asdl_seq_GET(seq, i); \ + if (!elt) continue; /* can be NULL */ \ + if (!symtable_visit_expr((ST), elt)) \ + return 0; \ + } \ } static int symtable_new_tmpname(struct symtable *st) { - char tmpname[256]; - identifier tmp; + char tmpname[256]; + identifier tmp; - PyOS_snprintf(tmpname, sizeof(tmpname), "_[%d]", - ++st->st_cur->ste_tmpname); - tmp = PyUnicode_InternFromString(tmpname); - if (!tmp) - return 0; - if (!symtable_add_def(st, tmp, DEF_LOCAL)) - return 0; - Py_DECREF(tmp); - return 1; + PyOS_snprintf(tmpname, sizeof(tmpname), "_[%d]", + ++st->st_cur->ste_tmpname); + tmp = PyUnicode_InternFromString(tmpname); + if (!tmp) + return 0; + if (!symtable_add_def(st, tmp, DEF_LOCAL)) + return 0; + Py_DECREF(tmp); + return 1; } static int symtable_visit_stmt(struct symtable *st, stmt_ty s) { - switch (s->kind) { - case FunctionDef_kind: - if (!symtable_add_def(st, s->v.FunctionDef.name, DEF_LOCAL)) - return 0; - if (s->v.FunctionDef.args->defaults) - VISIT_SEQ(st, expr, s->v.FunctionDef.args->defaults); - if (s->v.FunctionDef.args->kw_defaults) - VISIT_KWONLYDEFAULTS(st, - s->v.FunctionDef.args->kw_defaults); - if (!symtable_visit_annotations(st, s)) - return 0; - if (s->v.FunctionDef.decorator_list) - VISIT_SEQ(st, expr, s->v.FunctionDef.decorator_list); - if (!symtable_enter_block(st, s->v.FunctionDef.name, - FunctionBlock, (void *)s, s->lineno)) - return 0; - VISIT_IN_BLOCK(st, arguments, s->v.FunctionDef.args, s); - VISIT_SEQ_IN_BLOCK(st, stmt, s->v.FunctionDef.body, s); - if (!symtable_exit_block(st, s)) - return 0; - break; - case ClassDef_kind: { - PyObject *tmp; - if (!symtable_add_def(st, s->v.ClassDef.name, DEF_LOCAL)) - return 0; - VISIT_SEQ(st, expr, s->v.ClassDef.bases); - VISIT_SEQ(st, keyword, s->v.ClassDef.keywords); - if (s->v.ClassDef.starargs) - VISIT(st, expr, s->v.ClassDef.starargs); - if (s->v.ClassDef.kwargs) - VISIT(st, expr, s->v.ClassDef.kwargs); - if (s->v.ClassDef.decorator_list) - VISIT_SEQ(st, expr, s->v.ClassDef.decorator_list); - if (!symtable_enter_block(st, s->v.ClassDef.name, ClassBlock, - (void *)s, s->lineno)) - return 0; - if (!GET_IDENTIFIER(__class__) || - !symtable_add_def(st, __class__, DEF_LOCAL) || - !GET_IDENTIFIER(__locals__) || - !symtable_add_def(st, __locals__, DEF_PARAM)) { - symtable_exit_block(st, s); - return 0; - } - tmp = st->st_private; - st->st_private = s->v.ClassDef.name; - VISIT_SEQ_IN_BLOCK(st, stmt, s->v.ClassDef.body, s); - st->st_private = tmp; - if (!symtable_exit_block(st, s)) - return 0; - break; - } - case Return_kind: - if (s->v.Return.value) { - VISIT(st, expr, s->v.Return.value); - st->st_cur->ste_returns_value = 1; - if (st->st_cur->ste_generator) { - PyErr_SetString(PyExc_SyntaxError, - RETURN_VAL_IN_GENERATOR); - PyErr_SyntaxLocation(st->st_filename, - s->lineno); - return 0; - } - } - break; - case Delete_kind: - VISIT_SEQ(st, expr, s->v.Delete.targets); - break; - case Assign_kind: - VISIT_SEQ(st, expr, s->v.Assign.targets); - VISIT(st, expr, s->v.Assign.value); - break; - case AugAssign_kind: - VISIT(st, expr, s->v.AugAssign.target); - VISIT(st, expr, s->v.AugAssign.value); - break; - case For_kind: - VISIT(st, expr, s->v.For.target); - VISIT(st, expr, s->v.For.iter); - VISIT_SEQ(st, stmt, s->v.For.body); - if (s->v.For.orelse) - VISIT_SEQ(st, stmt, s->v.For.orelse); - break; - case While_kind: - VISIT(st, expr, s->v.While.test); - VISIT_SEQ(st, stmt, s->v.While.body); - if (s->v.While.orelse) - VISIT_SEQ(st, stmt, s->v.While.orelse); - break; - case If_kind: - /* XXX if 0: and lookup_yield() hacks */ - VISIT(st, expr, s->v.If.test); - VISIT_SEQ(st, stmt, s->v.If.body); - if (s->v.If.orelse) - VISIT_SEQ(st, stmt, s->v.If.orelse); - break; - case Raise_kind: - if (s->v.Raise.exc) { - VISIT(st, expr, s->v.Raise.exc); - if (s->v.Raise.cause) { - VISIT(st, expr, s->v.Raise.cause); + switch (s->kind) { + case FunctionDef_kind: + if (!symtable_add_def(st, s->v.FunctionDef.name, DEF_LOCAL)) + return 0; + if (s->v.FunctionDef.args->defaults) + VISIT_SEQ(st, expr, s->v.FunctionDef.args->defaults); + if (s->v.FunctionDef.args->kw_defaults) + VISIT_KWONLYDEFAULTS(st, + s->v.FunctionDef.args->kw_defaults); + if (!symtable_visit_annotations(st, s)) + return 0; + if (s->v.FunctionDef.decorator_list) + VISIT_SEQ(st, expr, s->v.FunctionDef.decorator_list); + if (!symtable_enter_block(st, s->v.FunctionDef.name, + FunctionBlock, (void *)s, s->lineno)) + return 0; + VISIT_IN_BLOCK(st, arguments, s->v.FunctionDef.args, s); + VISIT_SEQ_IN_BLOCK(st, stmt, s->v.FunctionDef.body, s); + if (!symtable_exit_block(st, s)) + return 0; + break; + case ClassDef_kind: { + PyObject *tmp; + if (!symtable_add_def(st, s->v.ClassDef.name, DEF_LOCAL)) + return 0; + VISIT_SEQ(st, expr, s->v.ClassDef.bases); + VISIT_SEQ(st, keyword, s->v.ClassDef.keywords); + if (s->v.ClassDef.starargs) + VISIT(st, expr, s->v.ClassDef.starargs); + if (s->v.ClassDef.kwargs) + VISIT(st, expr, s->v.ClassDef.kwargs); + if (s->v.ClassDef.decorator_list) + VISIT_SEQ(st, expr, s->v.ClassDef.decorator_list); + if (!symtable_enter_block(st, s->v.ClassDef.name, ClassBlock, + (void *)s, s->lineno)) + return 0; + if (!GET_IDENTIFIER(__class__) || + !symtable_add_def(st, __class__, DEF_LOCAL) || + !GET_IDENTIFIER(__locals__) || + !symtable_add_def(st, __locals__, DEF_PARAM)) { + symtable_exit_block(st, s); + return 0; + } + tmp = st->st_private; + st->st_private = s->v.ClassDef.name; + VISIT_SEQ_IN_BLOCK(st, stmt, s->v.ClassDef.body, s); + st->st_private = tmp; + if (!symtable_exit_block(st, s)) + return 0; + break; + } + case Return_kind: + if (s->v.Return.value) { + VISIT(st, expr, s->v.Return.value); + st->st_cur->ste_returns_value = 1; + if (st->st_cur->ste_generator) { + PyErr_SetString(PyExc_SyntaxError, + RETURN_VAL_IN_GENERATOR); + PyErr_SyntaxLocation(st->st_filename, + s->lineno); + return 0; } - } - break; - case TryExcept_kind: - VISIT_SEQ(st, stmt, s->v.TryExcept.body); - VISIT_SEQ(st, stmt, s->v.TryExcept.orelse); - VISIT_SEQ(st, excepthandler, s->v.TryExcept.handlers); - break; - case TryFinally_kind: - VISIT_SEQ(st, stmt, s->v.TryFinally.body); - VISIT_SEQ(st, stmt, s->v.TryFinally.finalbody); - break; - case Assert_kind: - VISIT(st, expr, s->v.Assert.test); - if (s->v.Assert.msg) - VISIT(st, expr, s->v.Assert.msg); - break; - case Import_kind: - VISIT_SEQ(st, alias, s->v.Import.names); - /* XXX Don't have the lineno available inside - visit_alias */ - if (st->st_cur->ste_unoptimized && !st->st_cur->ste_opt_lineno) - st->st_cur->ste_opt_lineno = s->lineno; - break; - case ImportFrom_kind: - VISIT_SEQ(st, alias, s->v.ImportFrom.names); - /* XXX Don't have the lineno available inside - visit_alias */ - if (st->st_cur->ste_unoptimized && !st->st_cur->ste_opt_lineno) - st->st_cur->ste_opt_lineno = s->lineno; - break; - case Global_kind: { - int i; - asdl_seq *seq = s->v.Global.names; - for (i = 0; i < asdl_seq_LEN(seq); i++) { - identifier name = (identifier)asdl_seq_GET(seq, i); - char *c_name = _PyUnicode_AsString(name); - long cur = symtable_lookup(st, name); - if (cur < 0) - return 0; - if (cur & (DEF_LOCAL | USE)) { - char buf[256]; - if (cur & DEF_LOCAL) - PyOS_snprintf(buf, sizeof(buf), - GLOBAL_AFTER_ASSIGN, - c_name); - else - PyOS_snprintf(buf, sizeof(buf), - GLOBAL_AFTER_USE, - c_name); - if (!symtable_warn(st, buf, s->lineno)) - return 0; - } - if (!symtable_add_def(st, name, DEF_GLOBAL)) - return 0; - } - break; - } - case Nonlocal_kind: { - int i; - asdl_seq *seq = s->v.Nonlocal.names; - for (i = 0; i < asdl_seq_LEN(seq); i++) { - identifier name = (identifier)asdl_seq_GET(seq, i); - char *c_name = _PyUnicode_AsString(name); - long cur = symtable_lookup(st, name); - if (cur < 0) - return 0; - if (cur & (DEF_LOCAL | USE)) { - char buf[256]; - if (cur & DEF_LOCAL) - PyOS_snprintf(buf, sizeof(buf), - NONLOCAL_AFTER_ASSIGN, - c_name); - else - PyOS_snprintf(buf, sizeof(buf), - NONLOCAL_AFTER_USE, - c_name); - if (!symtable_warn(st, buf, s->lineno)) - return 0; - } - if (!symtable_add_def(st, name, DEF_NONLOCAL)) - return 0; - } - break; - } - case Expr_kind: - VISIT(st, expr, s->v.Expr.value); - break; - case Pass_kind: - case Break_kind: - case Continue_kind: - /* nothing to do here */ - break; - case With_kind: - VISIT(st, expr, s->v.With.context_expr); - if (s->v.With.optional_vars) { - VISIT(st, expr, s->v.With.optional_vars); - } - VISIT_SEQ(st, stmt, s->v.With.body); - break; - } - return 1; + } + break; + case Delete_kind: + VISIT_SEQ(st, expr, s->v.Delete.targets); + break; + case Assign_kind: + VISIT_SEQ(st, expr, s->v.Assign.targets); + VISIT(st, expr, s->v.Assign.value); + break; + case AugAssign_kind: + VISIT(st, expr, s->v.AugAssign.target); + VISIT(st, expr, s->v.AugAssign.value); + break; + case For_kind: + VISIT(st, expr, s->v.For.target); + VISIT(st, expr, s->v.For.iter); + VISIT_SEQ(st, stmt, s->v.For.body); + if (s->v.For.orelse) + VISIT_SEQ(st, stmt, s->v.For.orelse); + break; + case While_kind: + VISIT(st, expr, s->v.While.test); + VISIT_SEQ(st, stmt, s->v.While.body); + if (s->v.While.orelse) + VISIT_SEQ(st, stmt, s->v.While.orelse); + break; + case If_kind: + /* XXX if 0: and lookup_yield() hacks */ + VISIT(st, expr, s->v.If.test); + VISIT_SEQ(st, stmt, s->v.If.body); + if (s->v.If.orelse) + VISIT_SEQ(st, stmt, s->v.If.orelse); + break; + case Raise_kind: + if (s->v.Raise.exc) { + VISIT(st, expr, s->v.Raise.exc); + if (s->v.Raise.cause) { + VISIT(st, expr, s->v.Raise.cause); + } + } + break; + case TryExcept_kind: + VISIT_SEQ(st, stmt, s->v.TryExcept.body); + VISIT_SEQ(st, stmt, s->v.TryExcept.orelse); + VISIT_SEQ(st, excepthandler, s->v.TryExcept.handlers); + break; + case TryFinally_kind: + VISIT_SEQ(st, stmt, s->v.TryFinally.body); + VISIT_SEQ(st, stmt, s->v.TryFinally.finalbody); + break; + case Assert_kind: + VISIT(st, expr, s->v.Assert.test); + if (s->v.Assert.msg) + VISIT(st, expr, s->v.Assert.msg); + break; + case Import_kind: + VISIT_SEQ(st, alias, s->v.Import.names); + /* XXX Don't have the lineno available inside + visit_alias */ + if (st->st_cur->ste_unoptimized && !st->st_cur->ste_opt_lineno) + st->st_cur->ste_opt_lineno = s->lineno; + break; + case ImportFrom_kind: + VISIT_SEQ(st, alias, s->v.ImportFrom.names); + /* XXX Don't have the lineno available inside + visit_alias */ + if (st->st_cur->ste_unoptimized && !st->st_cur->ste_opt_lineno) + st->st_cur->ste_opt_lineno = s->lineno; + break; + case Global_kind: { + int i; + asdl_seq *seq = s->v.Global.names; + for (i = 0; i < asdl_seq_LEN(seq); i++) { + identifier name = (identifier)asdl_seq_GET(seq, i); + char *c_name = _PyUnicode_AsString(name); + long cur = symtable_lookup(st, name); + if (cur < 0) + return 0; + if (cur & (DEF_LOCAL | USE)) { + char buf[256]; + if (cur & DEF_LOCAL) + PyOS_snprintf(buf, sizeof(buf), + GLOBAL_AFTER_ASSIGN, + c_name); + else + PyOS_snprintf(buf, sizeof(buf), + GLOBAL_AFTER_USE, + c_name); + if (!symtable_warn(st, buf, s->lineno)) + return 0; + } + if (!symtable_add_def(st, name, DEF_GLOBAL)) + return 0; + } + break; + } + case Nonlocal_kind: { + int i; + asdl_seq *seq = s->v.Nonlocal.names; + for (i = 0; i < asdl_seq_LEN(seq); i++) { + identifier name = (identifier)asdl_seq_GET(seq, i); + char *c_name = _PyUnicode_AsString(name); + long cur = symtable_lookup(st, name); + if (cur < 0) + return 0; + if (cur & (DEF_LOCAL | USE)) { + char buf[256]; + if (cur & DEF_LOCAL) + PyOS_snprintf(buf, sizeof(buf), + NONLOCAL_AFTER_ASSIGN, + c_name); + else + PyOS_snprintf(buf, sizeof(buf), + NONLOCAL_AFTER_USE, + c_name); + if (!symtable_warn(st, buf, s->lineno)) + return 0; + } + if (!symtable_add_def(st, name, DEF_NONLOCAL)) + return 0; + } + break; + } + case Expr_kind: + VISIT(st, expr, s->v.Expr.value); + break; + case Pass_kind: + case Break_kind: + case Continue_kind: + /* nothing to do here */ + break; + case With_kind: + VISIT(st, expr, s->v.With.context_expr); + if (s->v.With.optional_vars) { + VISIT(st, expr, s->v.With.optional_vars); + } + VISIT_SEQ(st, stmt, s->v.With.body); + break; + } + return 1; } -static int +static int symtable_visit_expr(struct symtable *st, expr_ty e) { - switch (e->kind) { - case BoolOp_kind: - VISIT_SEQ(st, expr, e->v.BoolOp.values); - break; - case BinOp_kind: - VISIT(st, expr, e->v.BinOp.left); - VISIT(st, expr, e->v.BinOp.right); - break; - case UnaryOp_kind: - VISIT(st, expr, e->v.UnaryOp.operand); - break; - case Lambda_kind: { - if (!GET_IDENTIFIER(lambda)) - return 0; - if (e->v.Lambda.args->defaults) - VISIT_SEQ(st, expr, e->v.Lambda.args->defaults); - if (!symtable_enter_block(st, lambda, - FunctionBlock, (void *)e, e->lineno)) - return 0; - VISIT_IN_BLOCK(st, arguments, e->v.Lambda.args, (void*)e); - VISIT_IN_BLOCK(st, expr, e->v.Lambda.body, (void*)e); - if (!symtable_exit_block(st, (void *)e)) - return 0; - break; - } - case IfExp_kind: - VISIT(st, expr, e->v.IfExp.test); - VISIT(st, expr, e->v.IfExp.body); - VISIT(st, expr, e->v.IfExp.orelse); - break; - case Dict_kind: - VISIT_SEQ(st, expr, e->v.Dict.keys); - VISIT_SEQ(st, expr, e->v.Dict.values); - break; - case Set_kind: - VISIT_SEQ(st, expr, e->v.Set.elts); - break; - case GeneratorExp_kind: - if (!symtable_visit_genexp(st, e)) - return 0; - break; - case ListComp_kind: - if (!symtable_visit_listcomp(st, e)) - return 0; - break; - case SetComp_kind: - if (!symtable_visit_setcomp(st, e)) - return 0; - break; - case DictComp_kind: - if (!symtable_visit_dictcomp(st, e)) - return 0; - break; - case Yield_kind: - if (e->v.Yield.value) - VISIT(st, expr, e->v.Yield.value); - st->st_cur->ste_generator = 1; - if (st->st_cur->ste_returns_value) { - PyErr_SetString(PyExc_SyntaxError, - RETURN_VAL_IN_GENERATOR); - PyErr_SyntaxLocation(st->st_filename, - e->lineno); - return 0; - } - break; - case Compare_kind: - VISIT(st, expr, e->v.Compare.left); - VISIT_SEQ(st, expr, e->v.Compare.comparators); - break; - case Call_kind: - VISIT(st, expr, e->v.Call.func); - VISIT_SEQ(st, expr, e->v.Call.args); - VISIT_SEQ(st, keyword, e->v.Call.keywords); - if (e->v.Call.starargs) - VISIT(st, expr, e->v.Call.starargs); - if (e->v.Call.kwargs) - VISIT(st, expr, e->v.Call.kwargs); - break; - case Num_kind: - case Str_kind: - case Bytes_kind: - case Ellipsis_kind: - /* Nothing to do here. */ - break; - /* The following exprs can be assignment targets. */ - case Attribute_kind: - VISIT(st, expr, e->v.Attribute.value); - break; - case Subscript_kind: - VISIT(st, expr, e->v.Subscript.value); - VISIT(st, slice, e->v.Subscript.slice); - break; - case Starred_kind: - VISIT(st, expr, e->v.Starred.value); - break; - case Name_kind: - if (!symtable_add_def(st, e->v.Name.id, - e->v.Name.ctx == Load ? USE : DEF_LOCAL)) - return 0; - /* Special-case super: it counts as a use of __class__ */ - if (e->v.Name.ctx == Load && - st->st_cur->ste_type == FunctionBlock && - !PyUnicode_CompareWithASCIIString(e->v.Name.id, "super")) { - if (!GET_IDENTIFIER(__class__) || - !symtable_add_def(st, __class__, USE)) - return 0; - } - break; - /* child nodes of List and Tuple will have expr_context set */ - case List_kind: - VISIT_SEQ(st, expr, e->v.List.elts); - break; - case Tuple_kind: - VISIT_SEQ(st, expr, e->v.Tuple.elts); - break; - } - return 1; + switch (e->kind) { + case BoolOp_kind: + VISIT_SEQ(st, expr, e->v.BoolOp.values); + break; + case BinOp_kind: + VISIT(st, expr, e->v.BinOp.left); + VISIT(st, expr, e->v.BinOp.right); + break; + case UnaryOp_kind: + VISIT(st, expr, e->v.UnaryOp.operand); + break; + case Lambda_kind: { + if (!GET_IDENTIFIER(lambda)) + return 0; + if (e->v.Lambda.args->defaults) + VISIT_SEQ(st, expr, e->v.Lambda.args->defaults); + if (!symtable_enter_block(st, lambda, + FunctionBlock, (void *)e, e->lineno)) + return 0; + VISIT_IN_BLOCK(st, arguments, e->v.Lambda.args, (void*)e); + VISIT_IN_BLOCK(st, expr, e->v.Lambda.body, (void*)e); + if (!symtable_exit_block(st, (void *)e)) + return 0; + break; + } + case IfExp_kind: + VISIT(st, expr, e->v.IfExp.test); + VISIT(st, expr, e->v.IfExp.body); + VISIT(st, expr, e->v.IfExp.orelse); + break; + case Dict_kind: + VISIT_SEQ(st, expr, e->v.Dict.keys); + VISIT_SEQ(st, expr, e->v.Dict.values); + break; + case Set_kind: + VISIT_SEQ(st, expr, e->v.Set.elts); + break; + case GeneratorExp_kind: + if (!symtable_visit_genexp(st, e)) + return 0; + break; + case ListComp_kind: + if (!symtable_visit_listcomp(st, e)) + return 0; + break; + case SetComp_kind: + if (!symtable_visit_setcomp(st, e)) + return 0; + break; + case DictComp_kind: + if (!symtable_visit_dictcomp(st, e)) + return 0; + break; + case Yield_kind: + if (e->v.Yield.value) + VISIT(st, expr, e->v.Yield.value); + st->st_cur->ste_generator = 1; + if (st->st_cur->ste_returns_value) { + PyErr_SetString(PyExc_SyntaxError, + RETURN_VAL_IN_GENERATOR); + PyErr_SyntaxLocation(st->st_filename, + e->lineno); + return 0; + } + break; + case Compare_kind: + VISIT(st, expr, e->v.Compare.left); + VISIT_SEQ(st, expr, e->v.Compare.comparators); + break; + case Call_kind: + VISIT(st, expr, e->v.Call.func); + VISIT_SEQ(st, expr, e->v.Call.args); + VISIT_SEQ(st, keyword, e->v.Call.keywords); + if (e->v.Call.starargs) + VISIT(st, expr, e->v.Call.starargs); + if (e->v.Call.kwargs) + VISIT(st, expr, e->v.Call.kwargs); + break; + case Num_kind: + case Str_kind: + case Bytes_kind: + case Ellipsis_kind: + /* Nothing to do here. */ + break; + /* The following exprs can be assignment targets. */ + case Attribute_kind: + VISIT(st, expr, e->v.Attribute.value); + break; + case Subscript_kind: + VISIT(st, expr, e->v.Subscript.value); + VISIT(st, slice, e->v.Subscript.slice); + break; + case Starred_kind: + VISIT(st, expr, e->v.Starred.value); + break; + case Name_kind: + if (!symtable_add_def(st, e->v.Name.id, + e->v.Name.ctx == Load ? USE : DEF_LOCAL)) + return 0; + /* Special-case super: it counts as a use of __class__ */ + if (e->v.Name.ctx == Load && + st->st_cur->ste_type == FunctionBlock && + !PyUnicode_CompareWithASCIIString(e->v.Name.id, "super")) { + if (!GET_IDENTIFIER(__class__) || + !symtable_add_def(st, __class__, USE)) + return 0; + } + break; + /* child nodes of List and Tuple will have expr_context set */ + case List_kind: + VISIT_SEQ(st, expr, e->v.List.elts); + break; + case Tuple_kind: + VISIT_SEQ(st, expr, e->v.Tuple.elts); + break; + } + return 1; } static int symtable_implicit_arg(struct symtable *st, int pos) { - PyObject *id = PyUnicode_FromFormat(".%d", pos); - if (id == NULL) - return 0; - if (!symtable_add_def(st, id, DEF_PARAM)) { - Py_DECREF(id); - return 0; - } - Py_DECREF(id); - return 1; + PyObject *id = PyUnicode_FromFormat(".%d", pos); + if (id == NULL) + return 0; + if (!symtable_add_def(st, id, DEF_PARAM)) { + Py_DECREF(id); + return 0; + } + Py_DECREF(id); + return 1; } -static int +static int symtable_visit_params(struct symtable *st, asdl_seq *args) { - int i; + int i; + + if (!args) + return -1; - if (!args) - return -1; - - for (i = 0; i < asdl_seq_LEN(args); i++) { - arg_ty arg = (arg_ty)asdl_seq_GET(args, i); - if (!symtable_add_def(st, arg->arg, DEF_PARAM)) - return 0; - } + for (i = 0; i < asdl_seq_LEN(args); i++) { + arg_ty arg = (arg_ty)asdl_seq_GET(args, i); + if (!symtable_add_def(st, arg->arg, DEF_PARAM)) + return 0; + } - return 1; + return 1; } -static int +static int symtable_visit_argannotations(struct symtable *st, asdl_seq *args) { - int i; + int i; + + if (!args) + return -1; - if (!args) - return -1; - - for (i = 0; i < asdl_seq_LEN(args); i++) { - arg_ty arg = (arg_ty)asdl_seq_GET(args, i); - if (arg->annotation) - VISIT(st, expr, arg->annotation); - } + for (i = 0; i < asdl_seq_LEN(args); i++) { + arg_ty arg = (arg_ty)asdl_seq_GET(args, i); + if (arg->annotation) + VISIT(st, expr, arg->annotation); + } - return 1; + return 1; } static int symtable_visit_annotations(struct symtable *st, stmt_ty s) { - arguments_ty a = s->v.FunctionDef.args; - - if (a->args && !symtable_visit_argannotations(st, a->args)) - return 0; - if (a->varargannotation) - VISIT(st, expr, a->varargannotation); - if (a->kwargannotation) - VISIT(st, expr, a->kwargannotation); - if (a->kwonlyargs && !symtable_visit_argannotations(st, a->kwonlyargs)) - return 0; - if (s->v.FunctionDef.returns) - VISIT(st, expr, s->v.FunctionDef.returns); - return 1; + arguments_ty a = s->v.FunctionDef.args; + + if (a->args && !symtable_visit_argannotations(st, a->args)) + return 0; + if (a->varargannotation) + VISIT(st, expr, a->varargannotation); + if (a->kwargannotation) + VISIT(st, expr, a->kwargannotation); + if (a->kwonlyargs && !symtable_visit_argannotations(st, a->kwonlyargs)) + return 0; + if (s->v.FunctionDef.returns) + VISIT(st, expr, s->v.FunctionDef.returns); + return 1; } -static int +static int symtable_visit_arguments(struct symtable *st, arguments_ty a) { - /* skip default arguments inside function block - XXX should ast be different? - */ - if (a->args && !symtable_visit_params(st, a->args)) - return 0; - if (a->kwonlyargs && !symtable_visit_params(st, a->kwonlyargs)) - return 0; - if (a->vararg) { - if (!symtable_add_def(st, a->vararg, DEF_PARAM)) - return 0; - st->st_cur->ste_varargs = 1; - } - if (a->kwarg) { - if (!symtable_add_def(st, a->kwarg, DEF_PARAM)) - return 0; - st->st_cur->ste_varkeywords = 1; - } - return 1; + /* skip default arguments inside function block + XXX should ast be different? + */ + if (a->args && !symtable_visit_params(st, a->args)) + return 0; + if (a->kwonlyargs && !symtable_visit_params(st, a->kwonlyargs)) + return 0; + if (a->vararg) { + if (!symtable_add_def(st, a->vararg, DEF_PARAM)) + return 0; + st->st_cur->ste_varargs = 1; + } + if (a->kwarg) { + if (!symtable_add_def(st, a->kwarg, DEF_PARAM)) + return 0; + st->st_cur->ste_varkeywords = 1; + } + return 1; } -static int +static int symtable_visit_excepthandler(struct symtable *st, excepthandler_ty eh) { - if (eh->v.ExceptHandler.type) - VISIT(st, expr, eh->v.ExceptHandler.type); - if (eh->v.ExceptHandler.name) - if (!symtable_add_def(st, eh->v.ExceptHandler.name, DEF_LOCAL)) - return 0; - VISIT_SEQ(st, stmt, eh->v.ExceptHandler.body); - return 1; + if (eh->v.ExceptHandler.type) + VISIT(st, expr, eh->v.ExceptHandler.type); + if (eh->v.ExceptHandler.name) + if (!symtable_add_def(st, eh->v.ExceptHandler.name, DEF_LOCAL)) + return 0; + VISIT_SEQ(st, stmt, eh->v.ExceptHandler.body); + return 1; } -static int +static int symtable_visit_alias(struct symtable *st, alias_ty a) { - /* Compute store_name, the name actually bound by the import - operation. It is diferent than a->name when a->name is a - dotted package name (e.g. spam.eggs) - */ - PyObject *store_name; - PyObject *name = (a->asname == NULL) ? a->name : a->asname; - const Py_UNICODE *base = PyUnicode_AS_UNICODE(name); - Py_UNICODE *dot = Py_UNICODE_strchr(base, '.'); - if (dot) { - store_name = PyUnicode_FromUnicode(base, dot - base); - if (!store_name) - return 0; - } - else { - store_name = name; - Py_INCREF(store_name); - } - if (PyUnicode_CompareWithASCIIString(name, "*")) { - int r = symtable_add_def(st, store_name, DEF_IMPORT); - Py_DECREF(store_name); - return r; - } - else { - if (st->st_cur->ste_type != ModuleBlock) { - int lineno = st->st_cur->ste_lineno; - PyErr_SetString(PyExc_SyntaxError, IMPORT_STAR_WARNING); - PyErr_SyntaxLocation(st->st_filename, lineno); - Py_DECREF(store_name); - return 0; - } - st->st_cur->ste_unoptimized |= OPT_IMPORT_STAR; - Py_DECREF(store_name); - return 1; - } + /* Compute store_name, the name actually bound by the import + operation. It is diferent than a->name when a->name is a + dotted package name (e.g. spam.eggs) + */ + PyObject *store_name; + PyObject *name = (a->asname == NULL) ? a->name : a->asname; + const Py_UNICODE *base = PyUnicode_AS_UNICODE(name); + Py_UNICODE *dot = Py_UNICODE_strchr(base, '.'); + if (dot) { + store_name = PyUnicode_FromUnicode(base, dot - base); + if (!store_name) + return 0; + } + else { + store_name = name; + Py_INCREF(store_name); + } + if (PyUnicode_CompareWithASCIIString(name, "*")) { + int r = symtable_add_def(st, store_name, DEF_IMPORT); + Py_DECREF(store_name); + return r; + } + else { + if (st->st_cur->ste_type != ModuleBlock) { + int lineno = st->st_cur->ste_lineno; + PyErr_SetString(PyExc_SyntaxError, IMPORT_STAR_WARNING); + PyErr_SyntaxLocation(st->st_filename, lineno); + Py_DECREF(store_name); + return 0; + } + st->st_cur->ste_unoptimized |= OPT_IMPORT_STAR; + Py_DECREF(store_name); + return 1; + } } -static int +static int symtable_visit_comprehension(struct symtable *st, comprehension_ty lc) { - VISIT(st, expr, lc->target); - VISIT(st, expr, lc->iter); - VISIT_SEQ(st, expr, lc->ifs); - return 1; + VISIT(st, expr, lc->target); + VISIT(st, expr, lc->iter); + VISIT_SEQ(st, expr, lc->ifs); + return 1; } -static int +static int symtable_visit_keyword(struct symtable *st, keyword_ty k) { - VISIT(st, expr, k->value); - return 1; + VISIT(st, expr, k->value); + return 1; } -static int +static int symtable_visit_slice(struct symtable *st, slice_ty s) { - switch (s->kind) { - case Slice_kind: - if (s->v.Slice.lower) - VISIT(st, expr, s->v.Slice.lower) - if (s->v.Slice.upper) - VISIT(st, expr, s->v.Slice.upper) - if (s->v.Slice.step) - VISIT(st, expr, s->v.Slice.step) - break; - case ExtSlice_kind: - VISIT_SEQ(st, slice, s->v.ExtSlice.dims) - break; - case Index_kind: - VISIT(st, expr, s->v.Index.value) - break; - } - return 1; + switch (s->kind) { + case Slice_kind: + if (s->v.Slice.lower) + VISIT(st, expr, s->v.Slice.lower) + if (s->v.Slice.upper) + VISIT(st, expr, s->v.Slice.upper) + if (s->v.Slice.step) + VISIT(st, expr, s->v.Slice.step) + break; + case ExtSlice_kind: + VISIT_SEQ(st, slice, s->v.ExtSlice.dims) + break; + case Index_kind: + VISIT(st, expr, s->v.Index.value) + break; + } + return 1; } -static int +static int symtable_handle_comprehension(struct symtable *st, expr_ty e, identifier scope_name, asdl_seq *generators, expr_ty elt, expr_ty value) { - int is_generator = (e->kind == GeneratorExp_kind); - int needs_tmp = !is_generator; - comprehension_ty outermost = ((comprehension_ty) - asdl_seq_GET(generators, 0)); - /* Outermost iterator is evaluated in current scope */ - VISIT(st, expr, outermost->iter); - /* Create comprehension scope for the rest */ - if (!scope_name || - !symtable_enter_block(st, scope_name, FunctionBlock, (void *)e, e->lineno)) { - return 0; - } - st->st_cur->ste_generator = is_generator; - /* Outermost iter is received as an argument */ - if (!symtable_implicit_arg(st, 0)) { - symtable_exit_block(st, (void *)e); - return 0; - } - /* Allocate temporary name if needed */ - if (needs_tmp && !symtable_new_tmpname(st)) { - symtable_exit_block(st, (void *)e); - return 0; - } - VISIT_IN_BLOCK(st, expr, outermost->target, (void*)e); - VISIT_SEQ_IN_BLOCK(st, expr, outermost->ifs, (void*)e); - VISIT_SEQ_TAIL_IN_BLOCK(st, comprehension, - generators, 1, (void*)e); - if (value) - VISIT_IN_BLOCK(st, expr, value, (void*)e); - VISIT_IN_BLOCK(st, expr, elt, (void*)e); - return symtable_exit_block(st, (void *)e); + int is_generator = (e->kind == GeneratorExp_kind); + int needs_tmp = !is_generator; + comprehension_ty outermost = ((comprehension_ty) + asdl_seq_GET(generators, 0)); + /* Outermost iterator is evaluated in current scope */ + VISIT(st, expr, outermost->iter); + /* Create comprehension scope for the rest */ + if (!scope_name || + !symtable_enter_block(st, scope_name, FunctionBlock, (void *)e, e->lineno)) { + return 0; + } + st->st_cur->ste_generator = is_generator; + /* Outermost iter is received as an argument */ + if (!symtable_implicit_arg(st, 0)) { + symtable_exit_block(st, (void *)e); + return 0; + } + /* Allocate temporary name if needed */ + if (needs_tmp && !symtable_new_tmpname(st)) { + symtable_exit_block(st, (void *)e); + return 0; + } + VISIT_IN_BLOCK(st, expr, outermost->target, (void*)e); + VISIT_SEQ_IN_BLOCK(st, expr, outermost->ifs, (void*)e); + VISIT_SEQ_TAIL_IN_BLOCK(st, comprehension, + generators, 1, (void*)e); + if (value) + VISIT_IN_BLOCK(st, expr, value, (void*)e); + VISIT_IN_BLOCK(st, expr, elt, (void*)e); + return symtable_exit_block(st, (void *)e); } -static int +static int symtable_visit_genexp(struct symtable *st, expr_ty e) { - return symtable_handle_comprehension(st, e, GET_IDENTIFIER(genexpr), - e->v.GeneratorExp.generators, - e->v.GeneratorExp.elt, NULL); + return symtable_handle_comprehension(st, e, GET_IDENTIFIER(genexpr), + e->v.GeneratorExp.generators, + e->v.GeneratorExp.elt, NULL); } -static int +static int symtable_visit_listcomp(struct symtable *st, expr_ty e) { - return symtable_handle_comprehension(st, e, GET_IDENTIFIER(listcomp), - e->v.ListComp.generators, - e->v.ListComp.elt, NULL); + return symtable_handle_comprehension(st, e, GET_IDENTIFIER(listcomp), + e->v.ListComp.generators, + e->v.ListComp.elt, NULL); } static int symtable_visit_setcomp(struct symtable *st, expr_ty e) { - return symtable_handle_comprehension(st, e, GET_IDENTIFIER(setcomp), - e->v.SetComp.generators, - e->v.SetComp.elt, NULL); + return symtable_handle_comprehension(st, e, GET_IDENTIFIER(setcomp), + e->v.SetComp.generators, + e->v.SetComp.elt, NULL); } static int symtable_visit_dictcomp(struct symtable *st, expr_ty e) { - return symtable_handle_comprehension(st, e, GET_IDENTIFIER(dictcomp), - e->v.DictComp.generators, - e->v.DictComp.key, - e->v.DictComp.value); + return symtable_handle_comprehension(st, e, GET_IDENTIFIER(dictcomp), + e->v.DictComp.generators, + e->v.DictComp.key, + e->v.DictComp.value); } Modified: python/branches/py3k/Python/sysmodule.c ============================================================================== --- python/branches/py3k/Python/sysmodule.c (original) +++ python/branches/py3k/Python/sysmodule.c Sun May 9 17:52:27 2010 @@ -45,63 +45,63 @@ PyObject * PySys_GetObject(const char *name) { - PyThreadState *tstate = PyThreadState_GET(); - PyObject *sd = tstate->interp->sysdict; - if (sd == NULL) - return NULL; - return PyDict_GetItemString(sd, name); + PyThreadState *tstate = PyThreadState_GET(); + PyObject *sd = tstate->interp->sysdict; + if (sd == NULL) + return NULL; + return PyDict_GetItemString(sd, name); } int PySys_SetObject(const char *name, PyObject *v) { - PyThreadState *tstate = PyThreadState_GET(); - PyObject *sd = tstate->interp->sysdict; - if (v == NULL) { - if (PyDict_GetItemString(sd, name) == NULL) - return 0; - else - return PyDict_DelItemString(sd, name); - } - else - return PyDict_SetItemString(sd, name, v); + PyThreadState *tstate = PyThreadState_GET(); + PyObject *sd = tstate->interp->sysdict; + if (v == NULL) { + if (PyDict_GetItemString(sd, name) == NULL) + return 0; + else + return PyDict_DelItemString(sd, name); + } + else + return PyDict_SetItemString(sd, name, v); } static PyObject * sys_displayhook(PyObject *self, PyObject *o) { - PyObject *outf; - PyInterpreterState *interp = PyThreadState_GET()->interp; - PyObject *modules = interp->modules; - PyObject *builtins = PyDict_GetItemString(modules, "builtins"); - - if (builtins == NULL) { - PyErr_SetString(PyExc_RuntimeError, "lost builtins module"); - return NULL; - } - - /* Print value except if None */ - /* After printing, also assign to '_' */ - /* Before, set '_' to None to avoid recursion */ - if (o == Py_None) { - Py_INCREF(Py_None); - return Py_None; - } - if (PyObject_SetAttrString(builtins, "_", Py_None) != 0) - return NULL; - outf = PySys_GetObject("stdout"); - if (outf == NULL || outf == Py_None) { - PyErr_SetString(PyExc_RuntimeError, "lost sys.stdout"); - return NULL; - } - if (PyFile_WriteObject(o, outf, 0) != 0) - return NULL; - if (PyFile_WriteString("\n", outf) != 0) - return NULL; - if (PyObject_SetAttrString(builtins, "_", o) != 0) - return NULL; - Py_INCREF(Py_None); - return Py_None; + PyObject *outf; + PyInterpreterState *interp = PyThreadState_GET()->interp; + PyObject *modules = interp->modules; + PyObject *builtins = PyDict_GetItemString(modules, "builtins"); + + if (builtins == NULL) { + PyErr_SetString(PyExc_RuntimeError, "lost builtins module"); + return NULL; + } + + /* Print value except if None */ + /* After printing, also assign to '_' */ + /* Before, set '_' to None to avoid recursion */ + if (o == Py_None) { + Py_INCREF(Py_None); + return Py_None; + } + if (PyObject_SetAttrString(builtins, "_", Py_None) != 0) + return NULL; + outf = PySys_GetObject("stdout"); + if (outf == NULL || outf == Py_None) { + PyErr_SetString(PyExc_RuntimeError, "lost sys.stdout"); + return NULL; + } + if (PyFile_WriteObject(o, outf, 0) != 0) + return NULL; + if (PyFile_WriteString("\n", outf) != 0) + return NULL; + if (PyObject_SetAttrString(builtins, "_", o) != 0) + return NULL; + Py_INCREF(Py_None); + return Py_None; } PyDoc_STRVAR(displayhook_doc, @@ -113,12 +113,12 @@ static PyObject * sys_excepthook(PyObject* self, PyObject* args) { - PyObject *exc, *value, *tb; - if (!PyArg_UnpackTuple(args, "excepthook", 3, 3, &exc, &value, &tb)) - return NULL; - PyErr_Display(exc, value, tb); - Py_INCREF(Py_None); - return Py_None; + PyObject *exc, *value, *tb; + if (!PyArg_UnpackTuple(args, "excepthook", 3, 3, &exc, &value, &tb)) + return NULL; + PyErr_Display(exc, value, tb); + Py_INCREF(Py_None); + return Py_None; } PyDoc_STRVAR(excepthook_doc, @@ -130,14 +130,14 @@ static PyObject * sys_exc_info(PyObject *self, PyObject *noargs) { - PyThreadState *tstate; - tstate = PyThreadState_GET(); - return Py_BuildValue( - "(OOO)", - tstate->exc_type != NULL ? tstate->exc_type : Py_None, - tstate->exc_value != NULL ? tstate->exc_value : Py_None, - tstate->exc_traceback != NULL ? - tstate->exc_traceback : Py_None); + PyThreadState *tstate; + tstate = PyThreadState_GET(); + return Py_BuildValue( + "(OOO)", + tstate->exc_type != NULL ? tstate->exc_type : Py_None, + tstate->exc_value != NULL ? tstate->exc_value : Py_None, + tstate->exc_traceback != NULL ? + tstate->exc_traceback : Py_None); } PyDoc_STRVAR(exc_info_doc, @@ -150,12 +150,12 @@ static PyObject * sys_exit(PyObject *self, PyObject *args) { - PyObject *exit_code = 0; - if (!PyArg_UnpackTuple(args, "exit", 0, 1, &exit_code)) - return NULL; - /* Raise SystemExit so callers may catch it or clean up. */ - PyErr_SetObject(PyExc_SystemExit, exit_code); - return NULL; + PyObject *exit_code = 0; + if (!PyArg_UnpackTuple(args, "exit", 0, 1, &exit_code)) + return NULL; + /* Raise SystemExit so callers may catch it or clean up. */ + PyErr_SetObject(PyExc_SystemExit, exit_code); + return NULL; } PyDoc_STRVAR(exit_doc, @@ -172,7 +172,7 @@ static PyObject * sys_getdefaultencoding(PyObject *self) { - return PyUnicode_FromString(PyUnicode_GetDefaultEncoding()); + return PyUnicode_FromString(PyUnicode_GetDefaultEncoding()); } PyDoc_STRVAR(getdefaultencoding_doc, @@ -185,13 +185,13 @@ static PyObject * sys_setdefaultencoding(PyObject *self, PyObject *args) { - char *encoding; - if (!PyArg_ParseTuple(args, "s:setdefaultencoding", &encoding)) - return NULL; - if (PyUnicode_SetDefaultEncoding(encoding)) - return NULL; - Py_INCREF(Py_None); - return Py_None; + char *encoding; + if (!PyArg_ParseTuple(args, "s:setdefaultencoding", &encoding)) + return NULL; + if (PyUnicode_SetDefaultEncoding(encoding)) + return NULL; + Py_INCREF(Py_None); + return Py_None; } PyDoc_STRVAR(setdefaultencoding_doc, @@ -203,10 +203,10 @@ static PyObject * sys_getfilesystemencoding(PyObject *self) { - if (Py_FileSystemDefaultEncoding) - return PyUnicode_FromString(Py_FileSystemDefaultEncoding); - Py_INCREF(Py_None); - return Py_None; + if (Py_FileSystemDefaultEncoding) + return PyUnicode_FromString(Py_FileSystemDefaultEncoding); + Py_INCREF(Py_None); + return Py_None; } PyDoc_STRVAR(getfilesystemencoding_doc, @@ -219,13 +219,13 @@ static PyObject * sys_setfilesystemencoding(PyObject *self, PyObject *args) { - PyObject *new_encoding; - if (!PyArg_ParseTuple(args, "U:setfilesystemencoding", &new_encoding)) - return NULL; - if (_Py_SetFileSystemEncoding(new_encoding)) - return NULL; - Py_INCREF(Py_None); - return Py_None; + PyObject *new_encoding; + if (!PyArg_ParseTuple(args, "U:setfilesystemencoding", &new_encoding)) + return NULL; + if (_Py_SetFileSystemEncoding(new_encoding)) + return NULL; + Py_INCREF(Py_None); + return Py_None; } PyDoc_STRVAR(setfilesystemencoding_doc, @@ -238,19 +238,19 @@ static PyObject * sys_intern(PyObject *self, PyObject *args) { - PyObject *s; - if (!PyArg_ParseTuple(args, "U:intern", &s)) - return NULL; - if (PyUnicode_CheckExact(s)) { - Py_INCREF(s); - PyUnicode_InternInPlace(&s); - return s; - } - else { - PyErr_Format(PyExc_TypeError, - "can't intern %.400s", s->ob_type->tp_name); - return NULL; - } + PyObject *s; + if (!PyArg_ParseTuple(args, "U:intern", &s)) + return NULL; + if (PyUnicode_CheckExact(s)) { + Py_INCREF(s); + PyUnicode_InternInPlace(&s); + return s; + } + else { + PyErr_Format(PyExc_TypeError, + "can't intern %.400s", s->ob_type->tp_name); + return NULL; + } } PyDoc_STRVAR(intern_doc, @@ -271,116 +271,116 @@ static int trace_init(void) { - static char *whatnames[7] = {"call", "exception", "line", "return", - "c_call", "c_exception", "c_return"}; - PyObject *name; - int i; - for (i = 0; i < 7; ++i) { - if (whatstrings[i] == NULL) { - name = PyUnicode_InternFromString(whatnames[i]); - if (name == NULL) - return -1; - whatstrings[i] = name; - } - } - return 0; + static char *whatnames[7] = {"call", "exception", "line", "return", + "c_call", "c_exception", "c_return"}; + PyObject *name; + int i; + for (i = 0; i < 7; ++i) { + if (whatstrings[i] == NULL) { + name = PyUnicode_InternFromString(whatnames[i]); + if (name == NULL) + return -1; + whatstrings[i] = name; + } + } + return 0; } static PyObject * call_trampoline(PyThreadState *tstate, PyObject* callback, - PyFrameObject *frame, int what, PyObject *arg) + PyFrameObject *frame, int what, PyObject *arg) { - PyObject *args = PyTuple_New(3); - PyObject *whatstr; - PyObject *result; - - if (args == NULL) - return NULL; - Py_INCREF(frame); - whatstr = whatstrings[what]; - Py_INCREF(whatstr); - if (arg == NULL) - arg = Py_None; - Py_INCREF(arg); - PyTuple_SET_ITEM(args, 0, (PyObject *)frame); - PyTuple_SET_ITEM(args, 1, whatstr); - PyTuple_SET_ITEM(args, 2, arg); - - /* call the Python-level function */ - PyFrame_FastToLocals(frame); - result = PyEval_CallObject(callback, args); - PyFrame_LocalsToFast(frame, 1); - if (result == NULL) - PyTraceBack_Here(frame); - - /* cleanup */ - Py_DECREF(args); - return result; + PyObject *args = PyTuple_New(3); + PyObject *whatstr; + PyObject *result; + + if (args == NULL) + return NULL; + Py_INCREF(frame); + whatstr = whatstrings[what]; + Py_INCREF(whatstr); + if (arg == NULL) + arg = Py_None; + Py_INCREF(arg); + PyTuple_SET_ITEM(args, 0, (PyObject *)frame); + PyTuple_SET_ITEM(args, 1, whatstr); + PyTuple_SET_ITEM(args, 2, arg); + + /* call the Python-level function */ + PyFrame_FastToLocals(frame); + result = PyEval_CallObject(callback, args); + PyFrame_LocalsToFast(frame, 1); + if (result == NULL) + PyTraceBack_Here(frame); + + /* cleanup */ + Py_DECREF(args); + return result; } static int profile_trampoline(PyObject *self, PyFrameObject *frame, - int what, PyObject *arg) + int what, PyObject *arg) { - PyThreadState *tstate = frame->f_tstate; - PyObject *result; + PyThreadState *tstate = frame->f_tstate; + PyObject *result; - if (arg == NULL) - arg = Py_None; - result = call_trampoline(tstate, self, frame, what, arg); - if (result == NULL) { - PyEval_SetProfile(NULL, NULL); - return -1; - } - Py_DECREF(result); - return 0; + if (arg == NULL) + arg = Py_None; + result = call_trampoline(tstate, self, frame, what, arg); + if (result == NULL) { + PyEval_SetProfile(NULL, NULL); + return -1; + } + Py_DECREF(result); + return 0; } static int trace_trampoline(PyObject *self, PyFrameObject *frame, - int what, PyObject *arg) + int what, PyObject *arg) { - PyThreadState *tstate = frame->f_tstate; - PyObject *callback; - PyObject *result; - - if (what == PyTrace_CALL) - callback = self; - else - callback = frame->f_trace; - if (callback == NULL) - return 0; - result = call_trampoline(tstate, callback, frame, what, arg); - if (result == NULL) { - PyEval_SetTrace(NULL, NULL); - Py_XDECREF(frame->f_trace); - frame->f_trace = NULL; - return -1; - } - if (result != Py_None) { - PyObject *temp = frame->f_trace; - frame->f_trace = NULL; - Py_XDECREF(temp); - frame->f_trace = result; - } - else { - Py_DECREF(result); - } - return 0; + PyThreadState *tstate = frame->f_tstate; + PyObject *callback; + PyObject *result; + + if (what == PyTrace_CALL) + callback = self; + else + callback = frame->f_trace; + if (callback == NULL) + return 0; + result = call_trampoline(tstate, callback, frame, what, arg); + if (result == NULL) { + PyEval_SetTrace(NULL, NULL); + Py_XDECREF(frame->f_trace); + frame->f_trace = NULL; + return -1; + } + if (result != Py_None) { + PyObject *temp = frame->f_trace; + frame->f_trace = NULL; + Py_XDECREF(temp); + frame->f_trace = result; + } + else { + Py_DECREF(result); + } + return 0; } static PyObject * sys_settrace(PyObject *self, PyObject *args) { - if (trace_init() == -1) - return NULL; - if (args == Py_None) - PyEval_SetTrace(NULL, NULL); - else - PyEval_SetTrace(trace_trampoline, args); - Py_INCREF(Py_None); - return Py_None; + if (trace_init() == -1) + return NULL; + if (args == Py_None) + PyEval_SetTrace(NULL, NULL); + else + PyEval_SetTrace(trace_trampoline, args); + Py_INCREF(Py_None); + return Py_None; } PyDoc_STRVAR(settrace_doc, @@ -393,13 +393,13 @@ static PyObject * sys_gettrace(PyObject *self, PyObject *args) { - PyThreadState *tstate = PyThreadState_GET(); - PyObject *temp = tstate->c_traceobj; + PyThreadState *tstate = PyThreadState_GET(); + PyObject *temp = tstate->c_traceobj; - if (temp == NULL) - temp = Py_None; - Py_INCREF(temp); - return temp; + if (temp == NULL) + temp = Py_None; + Py_INCREF(temp); + return temp; } PyDoc_STRVAR(gettrace_doc, @@ -412,14 +412,14 @@ static PyObject * sys_setprofile(PyObject *self, PyObject *args) { - if (trace_init() == -1) - return NULL; - if (args == Py_None) - PyEval_SetProfile(NULL, NULL); - else - PyEval_SetProfile(profile_trampoline, args); - Py_INCREF(Py_None); - return Py_None; + if (trace_init() == -1) + return NULL; + if (args == Py_None) + PyEval_SetProfile(NULL, NULL); + else + PyEval_SetProfile(profile_trampoline, args); + Py_INCREF(Py_None); + return Py_None; } PyDoc_STRVAR(setprofile_doc, @@ -432,13 +432,13 @@ static PyObject * sys_getprofile(PyObject *self, PyObject *args) { - PyThreadState *tstate = PyThreadState_GET(); - PyObject *temp = tstate->c_profileobj; + PyThreadState *tstate = PyThreadState_GET(); + PyObject *temp = tstate->c_profileobj; - if (temp == NULL) - temp = Py_None; - Py_INCREF(temp); - return temp; + if (temp == NULL) + temp = Py_None; + Py_INCREF(temp); + return temp; } PyDoc_STRVAR(getprofile_doc, @@ -453,15 +453,15 @@ static PyObject * sys_setcheckinterval(PyObject *self, PyObject *args) { - if (PyErr_WarnEx(PyExc_DeprecationWarning, - "sys.getcheckinterval() and sys.setcheckinterval() " - "are deprecated. Use sys.setswitchinterval() " - "instead.", 1) < 0) - return NULL; - if (!PyArg_ParseTuple(args, "i:setcheckinterval", &_check_interval)) - return NULL; - Py_INCREF(Py_None); - return Py_None; + if (PyErr_WarnEx(PyExc_DeprecationWarning, + "sys.getcheckinterval() and sys.setcheckinterval() " + "are deprecated. Use sys.setswitchinterval() " + "instead.", 1) < 0) + return NULL; + if (!PyArg_ParseTuple(args, "i:setcheckinterval", &_check_interval)) + return NULL; + Py_INCREF(Py_None); + return Py_None; } PyDoc_STRVAR(setcheckinterval_doc, @@ -474,12 +474,12 @@ static PyObject * sys_getcheckinterval(PyObject *self, PyObject *args) { - if (PyErr_WarnEx(PyExc_DeprecationWarning, - "sys.getcheckinterval() and sys.setcheckinterval() " - "are deprecated. Use sys.getswitchinterval() " - "instead.", 1) < 0) - return NULL; - return PyLong_FromLong(_check_interval); + if (PyErr_WarnEx(PyExc_DeprecationWarning, + "sys.getcheckinterval() and sys.setcheckinterval() " + "are deprecated. Use sys.getswitchinterval() " + "instead.", 1) < 0) + return NULL; + return PyLong_FromLong(_check_interval); } PyDoc_STRVAR(getcheckinterval_doc, @@ -490,17 +490,17 @@ static PyObject * sys_setswitchinterval(PyObject *self, PyObject *args) { - double d; - if (!PyArg_ParseTuple(args, "d:setswitchinterval", &d)) - return NULL; - if (d <= 0.0) { - PyErr_SetString(PyExc_ValueError, - "switch interval must be strictly positive"); - return NULL; - } - _PyEval_SetSwitchInterval((unsigned long) (1e6 * d)); - Py_INCREF(Py_None); - return Py_None; + double d; + if (!PyArg_ParseTuple(args, "d:setswitchinterval", &d)) + return NULL; + if (d <= 0.0) { + PyErr_SetString(PyExc_ValueError, + "switch interval must be strictly positive"); + return NULL; + } + _PyEval_SetSwitchInterval((unsigned long) (1e6 * d)); + Py_INCREF(Py_None); + return Py_None; } PyDoc_STRVAR(setswitchinterval_doc, @@ -518,7 +518,7 @@ static PyObject * sys_getswitchinterval(PyObject *self, PyObject *args) { - return PyFloat_FromDouble(1e-6 * _PyEval_GetSwitchInterval()); + return PyFloat_FromDouble(1e-6 * _PyEval_GetSwitchInterval()); } PyDoc_STRVAR(getswitchinterval_doc, @@ -531,17 +531,17 @@ static PyObject * sys_settscdump(PyObject *self, PyObject *args) { - int bool; - PyThreadState *tstate = PyThreadState_Get(); + int bool; + PyThreadState *tstate = PyThreadState_Get(); - if (!PyArg_ParseTuple(args, "i:settscdump", &bool)) - return NULL; - if (bool) - tstate->interp->tscdump = 1; - else - tstate->interp->tscdump = 0; - Py_INCREF(Py_None); - return Py_None; + if (!PyArg_ParseTuple(args, "i:settscdump", &bool)) + return NULL; + if (bool) + tstate->interp->tscdump = 1; + else + tstate->interp->tscdump = 0; + Py_INCREF(Py_None); + return Py_None; } @@ -557,17 +557,17 @@ static PyObject * sys_setrecursionlimit(PyObject *self, PyObject *args) { - int new_limit; - if (!PyArg_ParseTuple(args, "i:setrecursionlimit", &new_limit)) - return NULL; - if (new_limit <= 0) { - PyErr_SetString(PyExc_ValueError, - "recursion limit must be positive"); - return NULL; - } - Py_SetRecursionLimit(new_limit); - Py_INCREF(Py_None); - return Py_None; + int new_limit; + if (!PyArg_ParseTuple(args, "i:setrecursionlimit", &new_limit)) + return NULL; + if (new_limit <= 0) { + PyErr_SetString(PyExc_ValueError, + "recursion limit must be positive"); + return NULL; + } + Py_SetRecursionLimit(new_limit); + Py_INCREF(Py_None); + return Py_None; } PyDoc_STRVAR(setrecursionlimit_doc, @@ -582,7 +582,7 @@ static PyObject * sys_getrecursionlimit(PyObject *self) { - return PyLong_FromLong(Py_GetRecursionLimit()); + return PyLong_FromLong(Py_GetRecursionLimit()); } PyDoc_STRVAR(getrecursionlimit_doc, @@ -610,52 +610,52 @@ static PyTypeObject WindowsVersionType = {0, 0, 0, 0, 0, 0}; static PyStructSequence_Field windows_version_fields[] = { - {"major", "Major version number"}, - {"minor", "Minor version number"}, - {"build", "Build number"}, - {"platform", "Operating system platform"}, - {"service_pack", "Latest Service Pack installed on the system"}, - {"service_pack_major", "Service Pack major version number"}, - {"service_pack_minor", "Service Pack minor version number"}, - {"suite_mask", "Bit mask identifying available product suites"}, - {"product_type", "System product type"}, - {0} + {"major", "Major version number"}, + {"minor", "Minor version number"}, + {"build", "Build number"}, + {"platform", "Operating system platform"}, + {"service_pack", "Latest Service Pack installed on the system"}, + {"service_pack_major", "Service Pack major version number"}, + {"service_pack_minor", "Service Pack minor version number"}, + {"suite_mask", "Bit mask identifying available product suites"}, + {"product_type", "System product type"}, + {0} }; static PyStructSequence_Desc windows_version_desc = { - "sys.getwindowsversion", /* name */ - getwindowsversion_doc, /* doc */ - windows_version_fields, /* fields */ - 5 /* For backward compatibility, - only the first 5 items are accessible - via indexing, the rest are name only */ + "sys.getwindowsversion", /* name */ + getwindowsversion_doc, /* doc */ + windows_version_fields, /* fields */ + 5 /* For backward compatibility, + only the first 5 items are accessible + via indexing, the rest are name only */ }; static PyObject * sys_getwindowsversion(PyObject *self) { - PyObject *version; - int pos = 0; - OSVERSIONINFOEX ver; - ver.dwOSVersionInfoSize = sizeof(ver); - if (!GetVersionEx((OSVERSIONINFO*) &ver)) - return PyErr_SetFromWindowsErr(0); - - version = PyStructSequence_New(&WindowsVersionType); - if (version == NULL) - return NULL; - - PyStructSequence_SET_ITEM(version, pos++, PyLong_FromLong(ver.dwMajorVersion)); - PyStructSequence_SET_ITEM(version, pos++, PyLong_FromLong(ver.dwMinorVersion)); - PyStructSequence_SET_ITEM(version, pos++, PyLong_FromLong(ver.dwBuildNumber)); - PyStructSequence_SET_ITEM(version, pos++, PyLong_FromLong(ver.dwPlatformId)); - PyStructSequence_SET_ITEM(version, pos++, PyUnicode_FromString(ver.szCSDVersion)); - PyStructSequence_SET_ITEM(version, pos++, PyLong_FromLong(ver.wServicePackMajor)); - PyStructSequence_SET_ITEM(version, pos++, PyLong_FromLong(ver.wServicePackMinor)); - PyStructSequence_SET_ITEM(version, pos++, PyLong_FromLong(ver.wSuiteMask)); - PyStructSequence_SET_ITEM(version, pos++, PyLong_FromLong(ver.wProductType)); + PyObject *version; + int pos = 0; + OSVERSIONINFOEX ver; + ver.dwOSVersionInfoSize = sizeof(ver); + if (!GetVersionEx((OSVERSIONINFO*) &ver)) + return PyErr_SetFromWindowsErr(0); + + version = PyStructSequence_New(&WindowsVersionType); + if (version == NULL) + return NULL; + + PyStructSequence_SET_ITEM(version, pos++, PyLong_FromLong(ver.dwMajorVersion)); + PyStructSequence_SET_ITEM(version, pos++, PyLong_FromLong(ver.dwMinorVersion)); + PyStructSequence_SET_ITEM(version, pos++, PyLong_FromLong(ver.dwBuildNumber)); + PyStructSequence_SET_ITEM(version, pos++, PyLong_FromLong(ver.dwPlatformId)); + PyStructSequence_SET_ITEM(version, pos++, PyUnicode_FromString(ver.szCSDVersion)); + PyStructSequence_SET_ITEM(version, pos++, PyLong_FromLong(ver.wServicePackMajor)); + PyStructSequence_SET_ITEM(version, pos++, PyLong_FromLong(ver.wServicePackMinor)); + PyStructSequence_SET_ITEM(version, pos++, PyLong_FromLong(ver.wSuiteMask)); + PyStructSequence_SET_ITEM(version, pos++, PyLong_FromLong(ver.wProductType)); - return version; + return version; } #endif /* MS_WINDOWS */ @@ -664,15 +664,15 @@ static PyObject * sys_setdlopenflags(PyObject *self, PyObject *args) { - int new_val; - PyThreadState *tstate = PyThreadState_GET(); - if (!PyArg_ParseTuple(args, "i:setdlopenflags", &new_val)) - return NULL; - if (!tstate) - return NULL; - tstate->interp->dlopenflags = new_val; - Py_INCREF(Py_None); - return Py_None; + int new_val; + PyThreadState *tstate = PyThreadState_GET(); + if (!PyArg_ParseTuple(args, "i:setdlopenflags", &new_val)) + return NULL; + if (!tstate) + return NULL; + tstate->interp->dlopenflags = new_val; + Py_INCREF(Py_None); + return Py_None; } PyDoc_STRVAR(setdlopenflags_doc, @@ -690,10 +690,10 @@ static PyObject * sys_getdlopenflags(PyObject *self, PyObject *args) { - PyThreadState *tstate = PyThreadState_GET(); - if (!tstate) - return NULL; - return PyLong_FromLong(tstate->interp->dlopenflags); + PyThreadState *tstate = PyThreadState_GET(); + if (!tstate) + return NULL; + return PyLong_FromLong(tstate->interp->dlopenflags); } PyDoc_STRVAR(getdlopenflags_doc, @@ -702,7 +702,7 @@ Return the current value of the flags that are used for dlopen calls.\n\ The flag constants are defined in the ctypes and DLFCN modules."); -#endif /* HAVE_DLOPEN */ +#endif /* HAVE_DLOPEN */ #ifdef USE_MALLOPT /* Link with -lmalloc (or -lmpc) on an SGI */ @@ -711,70 +711,70 @@ static PyObject * sys_mdebug(PyObject *self, PyObject *args) { - int flag; - if (!PyArg_ParseTuple(args, "i:mdebug", &flag)) - return NULL; - mallopt(M_DEBUG, flag); - Py_INCREF(Py_None); - return Py_None; + int flag; + if (!PyArg_ParseTuple(args, "i:mdebug", &flag)) + return NULL; + mallopt(M_DEBUG, flag); + Py_INCREF(Py_None); + return Py_None; } #endif /* USE_MALLOPT */ static PyObject * sys_getsizeof(PyObject *self, PyObject *args, PyObject *kwds) { - PyObject *res = NULL; - static PyObject *str__sizeof__ = NULL, *gc_head_size = NULL; - static char *kwlist[] = {"object", "default", 0}; - PyObject *o, *dflt = NULL; - PyObject *method; - - if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|O:getsizeof", - kwlist, &o, &dflt)) - return NULL; - - /* Initialize static variable for GC head size */ - if (gc_head_size == NULL) { - gc_head_size = PyLong_FromSsize_t(sizeof(PyGC_Head)); - if (gc_head_size == NULL) - return NULL; - } - - /* Make sure the type is initialized. float gets initialized late */ - if (PyType_Ready(Py_TYPE(o)) < 0) - return NULL; - - method = _PyObject_LookupSpecial(o, "__sizeof__", - &str__sizeof__); - if (method == NULL) { - if (!PyErr_Occurred()) - PyErr_Format(PyExc_TypeError, - "Type %.100s doesn't define __sizeof__", - Py_TYPE(o)->tp_name); - } - else { - res = PyObject_CallFunctionObjArgs(method, NULL); - Py_DECREF(method); - } - - /* Has a default value been given */ - if ((res == NULL) && (dflt != NULL) && - PyErr_ExceptionMatches(PyExc_TypeError)) - { - PyErr_Clear(); - Py_INCREF(dflt); - return dflt; - } - else if (res == NULL) - return res; - - /* add gc_head size */ - if (PyObject_IS_GC(o)) { - PyObject *tmp = res; - res = PyNumber_Add(tmp, gc_head_size); - Py_DECREF(tmp); - } - return res; + PyObject *res = NULL; + static PyObject *str__sizeof__ = NULL, *gc_head_size = NULL; + static char *kwlist[] = {"object", "default", 0}; + PyObject *o, *dflt = NULL; + PyObject *method; + + if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|O:getsizeof", + kwlist, &o, &dflt)) + return NULL; + + /* Initialize static variable for GC head size */ + if (gc_head_size == NULL) { + gc_head_size = PyLong_FromSsize_t(sizeof(PyGC_Head)); + if (gc_head_size == NULL) + return NULL; + } + + /* Make sure the type is initialized. float gets initialized late */ + if (PyType_Ready(Py_TYPE(o)) < 0) + return NULL; + + method = _PyObject_LookupSpecial(o, "__sizeof__", + &str__sizeof__); + if (method == NULL) { + if (!PyErr_Occurred()) + PyErr_Format(PyExc_TypeError, + "Type %.100s doesn't define __sizeof__", + Py_TYPE(o)->tp_name); + } + else { + res = PyObject_CallFunctionObjArgs(method, NULL); + Py_DECREF(method); + } + + /* Has a default value been given */ + if ((res == NULL) && (dflt != NULL) && + PyErr_ExceptionMatches(PyExc_TypeError)) + { + PyErr_Clear(); + Py_INCREF(dflt); + return dflt; + } + else if (res == NULL) + return res; + + /* add gc_head size */ + if (PyObject_IS_GC(o)) { + PyObject *tmp = res; + res = PyNumber_Add(tmp, gc_head_size); + Py_DECREF(tmp); + } + return res; } PyDoc_STRVAR(getsizeof_doc, @@ -785,14 +785,14 @@ static PyObject * sys_getrefcount(PyObject *self, PyObject *arg) { - return PyLong_FromSsize_t(arg->ob_refcnt); + return PyLong_FromSsize_t(arg->ob_refcnt); } #ifdef Py_REF_DEBUG static PyObject * sys_gettotalrefcount(PyObject *self) { - return PyLong_FromSsize_t(_Py_GetRefTotal()); + return PyLong_FromSsize_t(_Py_GetRefTotal()); } #endif /* Py_REF_DEBUG */ @@ -808,9 +808,9 @@ static PyObject * sys_getcounts(PyObject *self) { - extern PyObject *get_counts(void); + extern PyObject *get_counts(void); - return get_counts(); + return get_counts(); } #endif @@ -829,23 +829,23 @@ static PyObject * sys_getframe(PyObject *self, PyObject *args) { - PyFrameObject *f = PyThreadState_GET()->frame; - int depth = -1; + PyFrameObject *f = PyThreadState_GET()->frame; + int depth = -1; - if (!PyArg_ParseTuple(args, "|i:_getframe", &depth)) - return NULL; + if (!PyArg_ParseTuple(args, "|i:_getframe", &depth)) + return NULL; - while (depth > 0 && f != NULL) { - f = f->f_back; - --depth; - } - if (f == NULL) { - PyErr_SetString(PyExc_ValueError, - "call stack is not deep enough"); - return NULL; - } - Py_INCREF(f); - return (PyObject*)f; + while (depth > 0 && f != NULL) { + f = f->f_back; + --depth; + } + if (f == NULL) { + PyErr_SetString(PyExc_ValueError, + "call stack is not deep enough"); + return NULL; + } + Py_INCREF(f); + return (PyObject*)f; } PyDoc_STRVAR(current_frames_doc, @@ -860,7 +860,7 @@ static PyObject * sys_current_frames(PyObject *self, PyObject *noargs) { - return _PyThread_CurrentFrames(); + return _PyThread_CurrentFrames(); } PyDoc_STRVAR(call_tracing_doc, @@ -874,10 +874,10 @@ static PyObject * sys_call_tracing(PyObject *self, PyObject *args) { - PyObject *func, *funcargs; - if (!PyArg_ParseTuple(args, "OO!:call_tracing", &func, &PyTuple_Type, &funcargs)) - return NULL; - return _PyEval_CallTracing(func, funcargs); + PyObject *func, *funcargs; + if (!PyArg_ParseTuple(args, "OO!:call_tracing", &func, &PyTuple_Type, &funcargs)) + return NULL; + return _PyEval_CallTracing(func, funcargs); } PyDoc_STRVAR(callstats_doc, @@ -924,8 +924,8 @@ static PyObject * sys_clear_type_cache(PyObject* self, PyObject* args) { - PyType_ClearCache(); - Py_RETURN_NONE; + PyType_ClearCache(); + Py_RETURN_NONE; } PyDoc_STRVAR(sys_clear_type_cache__doc__, @@ -934,107 +934,107 @@ static PyMethodDef sys_methods[] = { - /* Might as well keep this in alphabetic order */ - {"callstats", (PyCFunction)PyEval_GetCallStats, METH_NOARGS, - callstats_doc}, - {"_clear_type_cache", sys_clear_type_cache, METH_NOARGS, - sys_clear_type_cache__doc__}, - {"_current_frames", sys_current_frames, METH_NOARGS, - current_frames_doc}, - {"displayhook", sys_displayhook, METH_O, displayhook_doc}, - {"exc_info", sys_exc_info, METH_NOARGS, exc_info_doc}, - {"excepthook", sys_excepthook, METH_VARARGS, excepthook_doc}, - {"exit", sys_exit, METH_VARARGS, exit_doc}, - {"getdefaultencoding", (PyCFunction)sys_getdefaultencoding, - METH_NOARGS, getdefaultencoding_doc}, + /* Might as well keep this in alphabetic order */ + {"callstats", (PyCFunction)PyEval_GetCallStats, METH_NOARGS, + callstats_doc}, + {"_clear_type_cache", sys_clear_type_cache, METH_NOARGS, + sys_clear_type_cache__doc__}, + {"_current_frames", sys_current_frames, METH_NOARGS, + current_frames_doc}, + {"displayhook", sys_displayhook, METH_O, displayhook_doc}, + {"exc_info", sys_exc_info, METH_NOARGS, exc_info_doc}, + {"excepthook", sys_excepthook, METH_VARARGS, excepthook_doc}, + {"exit", sys_exit, METH_VARARGS, exit_doc}, + {"getdefaultencoding", (PyCFunction)sys_getdefaultencoding, + METH_NOARGS, getdefaultencoding_doc}, #ifdef HAVE_DLOPEN - {"getdlopenflags", (PyCFunction)sys_getdlopenflags, METH_NOARGS, - getdlopenflags_doc}, + {"getdlopenflags", (PyCFunction)sys_getdlopenflags, METH_NOARGS, + getdlopenflags_doc}, #endif #ifdef COUNT_ALLOCS - {"getcounts", (PyCFunction)sys_getcounts, METH_NOARGS}, + {"getcounts", (PyCFunction)sys_getcounts, METH_NOARGS}, #endif #ifdef DYNAMIC_EXECUTION_PROFILE - {"getdxp", _Py_GetDXProfile, METH_VARARGS}, + {"getdxp", _Py_GetDXProfile, METH_VARARGS}, #endif - {"getfilesystemencoding", (PyCFunction)sys_getfilesystemencoding, - METH_NOARGS, getfilesystemencoding_doc}, + {"getfilesystemencoding", (PyCFunction)sys_getfilesystemencoding, + METH_NOARGS, getfilesystemencoding_doc}, #ifdef Py_TRACE_REFS - {"getobjects", _Py_GetObjects, METH_VARARGS}, + {"getobjects", _Py_GetObjects, METH_VARARGS}, #endif #ifdef Py_REF_DEBUG - {"gettotalrefcount", (PyCFunction)sys_gettotalrefcount, METH_NOARGS}, + {"gettotalrefcount", (PyCFunction)sys_gettotalrefcount, METH_NOARGS}, #endif - {"getrefcount", (PyCFunction)sys_getrefcount, METH_O, getrefcount_doc}, - {"getrecursionlimit", (PyCFunction)sys_getrecursionlimit, METH_NOARGS, - getrecursionlimit_doc}, - {"getsizeof", (PyCFunction)sys_getsizeof, - METH_VARARGS | METH_KEYWORDS, getsizeof_doc}, - {"_getframe", sys_getframe, METH_VARARGS, getframe_doc}, + {"getrefcount", (PyCFunction)sys_getrefcount, METH_O, getrefcount_doc}, + {"getrecursionlimit", (PyCFunction)sys_getrecursionlimit, METH_NOARGS, + getrecursionlimit_doc}, + {"getsizeof", (PyCFunction)sys_getsizeof, + METH_VARARGS | METH_KEYWORDS, getsizeof_doc}, + {"_getframe", sys_getframe, METH_VARARGS, getframe_doc}, #ifdef MS_WINDOWS - {"getwindowsversion", (PyCFunction)sys_getwindowsversion, METH_NOARGS, - getwindowsversion_doc}, + {"getwindowsversion", (PyCFunction)sys_getwindowsversion, METH_NOARGS, + getwindowsversion_doc}, #endif /* MS_WINDOWS */ - {"intern", sys_intern, METH_VARARGS, intern_doc}, + {"intern", sys_intern, METH_VARARGS, intern_doc}, #ifdef USE_MALLOPT - {"mdebug", sys_mdebug, METH_VARARGS}, + {"mdebug", sys_mdebug, METH_VARARGS}, #endif - {"setdefaultencoding", sys_setdefaultencoding, METH_VARARGS, - setdefaultencoding_doc}, - {"setfilesystemencoding", sys_setfilesystemencoding, METH_VARARGS, - setfilesystemencoding_doc}, - {"setcheckinterval", sys_setcheckinterval, METH_VARARGS, - setcheckinterval_doc}, - {"getcheckinterval", sys_getcheckinterval, METH_NOARGS, - getcheckinterval_doc}, + {"setdefaultencoding", sys_setdefaultencoding, METH_VARARGS, + setdefaultencoding_doc}, + {"setfilesystemencoding", sys_setfilesystemencoding, METH_VARARGS, + setfilesystemencoding_doc}, + {"setcheckinterval", sys_setcheckinterval, METH_VARARGS, + setcheckinterval_doc}, + {"getcheckinterval", sys_getcheckinterval, METH_NOARGS, + getcheckinterval_doc}, #ifdef WITH_THREAD - {"setswitchinterval", sys_setswitchinterval, METH_VARARGS, - setswitchinterval_doc}, - {"getswitchinterval", sys_getswitchinterval, METH_NOARGS, - getswitchinterval_doc}, + {"setswitchinterval", sys_setswitchinterval, METH_VARARGS, + setswitchinterval_doc}, + {"getswitchinterval", sys_getswitchinterval, METH_NOARGS, + getswitchinterval_doc}, #endif #ifdef HAVE_DLOPEN - {"setdlopenflags", sys_setdlopenflags, METH_VARARGS, - setdlopenflags_doc}, + {"setdlopenflags", sys_setdlopenflags, METH_VARARGS, + setdlopenflags_doc}, #endif - {"setprofile", sys_setprofile, METH_O, setprofile_doc}, - {"getprofile", sys_getprofile, METH_NOARGS, getprofile_doc}, - {"setrecursionlimit", sys_setrecursionlimit, METH_VARARGS, - setrecursionlimit_doc}, + {"setprofile", sys_setprofile, METH_O, setprofile_doc}, + {"getprofile", sys_getprofile, METH_NOARGS, getprofile_doc}, + {"setrecursionlimit", sys_setrecursionlimit, METH_VARARGS, + setrecursionlimit_doc}, #ifdef WITH_TSC - {"settscdump", sys_settscdump, METH_VARARGS, settscdump_doc}, + {"settscdump", sys_settscdump, METH_VARARGS, settscdump_doc}, #endif - {"settrace", sys_settrace, METH_O, settrace_doc}, - {"gettrace", sys_gettrace, METH_NOARGS, gettrace_doc}, - {"call_tracing", sys_call_tracing, METH_VARARGS, call_tracing_doc}, - {NULL, NULL} /* sentinel */ + {"settrace", sys_settrace, METH_O, settrace_doc}, + {"gettrace", sys_gettrace, METH_NOARGS, gettrace_doc}, + {"call_tracing", sys_call_tracing, METH_VARARGS, call_tracing_doc}, + {NULL, NULL} /* sentinel */ }; static PyObject * list_builtin_module_names(void) { - PyObject *list = PyList_New(0); - int i; - if (list == NULL) - return NULL; - for (i = 0; PyImport_Inittab[i].name != NULL; i++) { - PyObject *name = PyUnicode_FromString( - PyImport_Inittab[i].name); - if (name == NULL) - break; - PyList_Append(list, name); - Py_DECREF(name); - } - if (PyList_Sort(list) != 0) { - Py_DECREF(list); - list = NULL; - } - if (list) { - PyObject *v = PyList_AsTuple(list); - Py_DECREF(list); - list = v; - } - return list; + PyObject *list = PyList_New(0); + int i; + if (list == NULL) + return NULL; + for (i = 0; PyImport_Inittab[i].name != NULL; i++) { + PyObject *name = PyUnicode_FromString( + PyImport_Inittab[i].name); + if (name == NULL) + break; + PyList_Append(list, name); + Py_DECREF(name); + } + if (PyList_Sort(list) != 0) { + Py_DECREF(list); + list = NULL; + } + if (list) { + PyObject *v = PyList_AsTuple(list); + Py_DECREF(list); + list = v; + } + return list; } static PyObject *warnoptions = NULL; @@ -1042,27 +1042,27 @@ void PySys_ResetWarnOptions(void) { - if (warnoptions == NULL || !PyList_Check(warnoptions)) - return; - PyList_SetSlice(warnoptions, 0, PyList_GET_SIZE(warnoptions), NULL); + if (warnoptions == NULL || !PyList_Check(warnoptions)) + return; + PyList_SetSlice(warnoptions, 0, PyList_GET_SIZE(warnoptions), NULL); } void PySys_AddWarnOption(const wchar_t *s) { - PyObject *str; + PyObject *str; - if (warnoptions == NULL || !PyList_Check(warnoptions)) { - Py_XDECREF(warnoptions); - warnoptions = PyList_New(0); - if (warnoptions == NULL) - return; - } - str = PyUnicode_FromWideChar(s, -1); - if (str != NULL) { - PyList_Append(warnoptions, str); - Py_DECREF(str); - } + if (warnoptions == NULL || !PyList_Check(warnoptions)) { + Py_XDECREF(warnoptions); + warnoptions = PyList_New(0); + if (warnoptions == NULL) + return; + } + str = PyUnicode_FromWideChar(s, -1); + if (str != NULL) { + PyList_Append(warnoptions, str); + Py_DECREF(str); + } } int @@ -1174,64 +1174,64 @@ static void svnversion_init(void) { - const char *python, *br_start, *br_end, *br_end2, *svnversion; - Py_ssize_t len; - int istag = 0; - - if (svn_initialized) - return; - - python = strstr(headurl, "/python/"); - if (!python) { - strcpy(branch, "unknown branch"); - strcpy(shortbranch, "unknown"); - } - else { - br_start = python + 8; - br_end = strchr(br_start, '/'); - assert(br_end); - - /* Works even for trunk, - as we are in trunk/Python/sysmodule.c */ - br_end2 = strchr(br_end+1, '/'); - - istag = strncmp(br_start, "tags", 4) == 0; - if (strncmp(br_start, "trunk", 5) == 0) { - strcpy(branch, "trunk"); - strcpy(shortbranch, "trunk"); - } - else if (istag || strncmp(br_start, "branches", 8) == 0) { - len = br_end2 - br_start; - strncpy(branch, br_start, len); - branch[len] = '\0'; - - len = br_end2 - (br_end + 1); - strncpy(shortbranch, br_end + 1, len); - shortbranch[len] = '\0'; - } - else { - Py_FatalError("bad HeadURL"); - return; - } - } - - - svnversion = _Py_svnversion(); - if (strcmp(svnversion, "Unversioned directory") != 0 && strcmp(svnversion, "exported") != 0) - svn_revision = svnversion; - else if (istag) { - len = strlen(_patchlevel_revision); - assert(len >= 13); - assert(len < (sizeof(patchlevel_revision) + 13)); - strncpy(patchlevel_revision, _patchlevel_revision + 11, - len - 13); - patchlevel_revision[len - 13] = '\0'; - svn_revision = patchlevel_revision; - } - else - svn_revision = ""; + const char *python, *br_start, *br_end, *br_end2, *svnversion; + Py_ssize_t len; + int istag = 0; + + if (svn_initialized) + return; + + python = strstr(headurl, "/python/"); + if (!python) { + strcpy(branch, "unknown branch"); + strcpy(shortbranch, "unknown"); + } + else { + br_start = python + 8; + br_end = strchr(br_start, '/'); + assert(br_end); + + /* Works even for trunk, + as we are in trunk/Python/sysmodule.c */ + br_end2 = strchr(br_end+1, '/'); + + istag = strncmp(br_start, "tags", 4) == 0; + if (strncmp(br_start, "trunk", 5) == 0) { + strcpy(branch, "trunk"); + strcpy(shortbranch, "trunk"); + } + else if (istag || strncmp(br_start, "branches", 8) == 0) { + len = br_end2 - br_start; + strncpy(branch, br_start, len); + branch[len] = '\0'; + + len = br_end2 - (br_end + 1); + strncpy(shortbranch, br_end + 1, len); + shortbranch[len] = '\0'; + } + else { + Py_FatalError("bad HeadURL"); + return; + } + } + + + svnversion = _Py_svnversion(); + if (strcmp(svnversion, "Unversioned directory") != 0 && strcmp(svnversion, "exported") != 0) + svn_revision = svnversion; + else if (istag) { + len = strlen(_patchlevel_revision); + assert(len >= 13); + assert(len < (sizeof(patchlevel_revision) + 13)); + strncpy(patchlevel_revision, _patchlevel_revision + 11, + len - 13); + patchlevel_revision[len - 13] = '\0'; + svn_revision = patchlevel_revision; + } + else + svn_revision = ""; - svn_initialized = 1; + svn_initialized = 1; } /* Return svnversion output if available. @@ -1240,15 +1240,15 @@ const char* Py_SubversionRevision() { - svnversion_init(); - return svn_revision; + svnversion_init(); + return svn_revision; } const char* Py_SubversionShortBranch() { - svnversion_init(); - return shortbranch; + svnversion_init(); + return shortbranch; } @@ -1260,71 +1260,71 @@ static PyTypeObject FlagsType; static PyStructSequence_Field flags_fields[] = { - {"debug", "-d"}, - {"division_warning", "-Q"}, - {"inspect", "-i"}, - {"interactive", "-i"}, - {"optimize", "-O or -OO"}, - {"dont_write_bytecode", "-B"}, - {"no_user_site", "-s"}, - {"no_site", "-S"}, - {"ignore_environment", "-E"}, - {"verbose", "-v"}, + {"debug", "-d"}, + {"division_warning", "-Q"}, + {"inspect", "-i"}, + {"interactive", "-i"}, + {"optimize", "-O or -OO"}, + {"dont_write_bytecode", "-B"}, + {"no_user_site", "-s"}, + {"no_site", "-S"}, + {"ignore_environment", "-E"}, + {"verbose", "-v"}, #ifdef RISCOS - {"riscos_wimp", "???"}, + {"riscos_wimp", "???"}, #endif - /* {"unbuffered", "-u"}, */ - /* {"skip_first", "-x"}, */ - {"bytes_warning", "-b"}, - {0} + /* {"unbuffered", "-u"}, */ + /* {"skip_first", "-x"}, */ + {"bytes_warning", "-b"}, + {0} }; static PyStructSequence_Desc flags_desc = { - "sys.flags", /* name */ - flags__doc__, /* doc */ - flags_fields, /* fields */ + "sys.flags", /* name */ + flags__doc__, /* doc */ + flags_fields, /* fields */ #ifdef RISCOS - 12 + 12 #else - 11 + 11 #endif }; static PyObject* make_flags(void) { - int pos = 0; - PyObject *seq; + int pos = 0; + PyObject *seq; - seq = PyStructSequence_New(&FlagsType); - if (seq == NULL) - return NULL; + seq = PyStructSequence_New(&FlagsType); + if (seq == NULL) + return NULL; #define SetFlag(flag) \ - PyStructSequence_SET_ITEM(seq, pos++, PyLong_FromLong(flag)) + PyStructSequence_SET_ITEM(seq, pos++, PyLong_FromLong(flag)) - SetFlag(Py_DebugFlag); - SetFlag(Py_DivisionWarningFlag); - SetFlag(Py_InspectFlag); - SetFlag(Py_InteractiveFlag); - SetFlag(Py_OptimizeFlag); - SetFlag(Py_DontWriteBytecodeFlag); - SetFlag(Py_NoUserSiteDirectory); - SetFlag(Py_NoSiteFlag); - SetFlag(Py_IgnoreEnvironmentFlag); - SetFlag(Py_VerboseFlag); + SetFlag(Py_DebugFlag); + SetFlag(Py_DivisionWarningFlag); + SetFlag(Py_InspectFlag); + SetFlag(Py_InteractiveFlag); + SetFlag(Py_OptimizeFlag); + SetFlag(Py_DontWriteBytecodeFlag); + SetFlag(Py_NoUserSiteDirectory); + SetFlag(Py_NoSiteFlag); + SetFlag(Py_IgnoreEnvironmentFlag); + SetFlag(Py_VerboseFlag); #ifdef RISCOS - SetFlag(Py_RISCOSWimpFlag); + SetFlag(Py_RISCOSWimpFlag); #endif - /* SetFlag(saw_unbuffered_flag); */ - /* SetFlag(skipfirstline); */ + /* SetFlag(saw_unbuffered_flag); */ + /* SetFlag(skipfirstline); */ SetFlag(Py_BytesWarningFlag); #undef SetFlag - if (PyErr_Occurred()) { - return NULL; - } - return seq; + if (PyErr_Occurred()) { + return NULL; + } + return seq; } PyDoc_STRVAR(version_info__doc__, @@ -1335,330 +1335,330 @@ static PyTypeObject VersionInfoType; static PyStructSequence_Field version_info_fields[] = { - {"major", "Major release number"}, - {"minor", "Minor release number"}, - {"micro", "Patch release number"}, - {"releaselevel", "'alpha', 'beta', 'candidate', or 'release'"}, - {"serial", "Serial release number"}, - {0} + {"major", "Major release number"}, + {"minor", "Minor release number"}, + {"micro", "Patch release number"}, + {"releaselevel", "'alpha', 'beta', 'candidate', or 'release'"}, + {"serial", "Serial release number"}, + {0} }; static PyStructSequence_Desc version_info_desc = { - "sys.version_info", /* name */ - version_info__doc__, /* doc */ - version_info_fields, /* fields */ - 5 + "sys.version_info", /* name */ + version_info__doc__, /* doc */ + version_info_fields, /* fields */ + 5 }; static PyObject * make_version_info(void) { - PyObject *version_info; - char *s; - int pos = 0; - - version_info = PyStructSequence_New(&VersionInfoType); - if (version_info == NULL) { - return NULL; - } - - /* - * These release level checks are mutually exclusive and cover - * the field, so don't get too fancy with the pre-processor! - */ + PyObject *version_info; + char *s; + int pos = 0; + + version_info = PyStructSequence_New(&VersionInfoType); + if (version_info == NULL) { + return NULL; + } + + /* + * These release level checks are mutually exclusive and cover + * the field, so don't get too fancy with the pre-processor! + */ #if PY_RELEASE_LEVEL == PY_RELEASE_LEVEL_ALPHA - s = "alpha"; + s = "alpha"; #elif PY_RELEASE_LEVEL == PY_RELEASE_LEVEL_BETA - s = "beta"; + s = "beta"; #elif PY_RELEASE_LEVEL == PY_RELEASE_LEVEL_GAMMA - s = "candidate"; + s = "candidate"; #elif PY_RELEASE_LEVEL == PY_RELEASE_LEVEL_FINAL - s = "final"; + s = "final"; #endif #define SetIntItem(flag) \ - PyStructSequence_SET_ITEM(version_info, pos++, PyLong_FromLong(flag)) + PyStructSequence_SET_ITEM(version_info, pos++, PyLong_FromLong(flag)) #define SetStrItem(flag) \ - PyStructSequence_SET_ITEM(version_info, pos++, PyUnicode_FromString(flag)) + PyStructSequence_SET_ITEM(version_info, pos++, PyUnicode_FromString(flag)) - SetIntItem(PY_MAJOR_VERSION); - SetIntItem(PY_MINOR_VERSION); - SetIntItem(PY_MICRO_VERSION); - SetStrItem(s); - SetIntItem(PY_RELEASE_SERIAL); + SetIntItem(PY_MAJOR_VERSION); + SetIntItem(PY_MINOR_VERSION); + SetIntItem(PY_MICRO_VERSION); + SetStrItem(s); + SetIntItem(PY_RELEASE_SERIAL); #undef SetIntItem #undef SetStrItem - if (PyErr_Occurred()) { - Py_CLEAR(version_info); - return NULL; - } - return version_info; + if (PyErr_Occurred()) { + Py_CLEAR(version_info); + return NULL; + } + return version_info; } static struct PyModuleDef sysmodule = { - PyModuleDef_HEAD_INIT, - "sys", - sys_doc, - -1, /* multiple "initialization" just copies the module dict. */ - sys_methods, - NULL, - NULL, - NULL, - NULL + PyModuleDef_HEAD_INIT, + "sys", + sys_doc, + -1, /* multiple "initialization" just copies the module dict. */ + sys_methods, + NULL, + NULL, + NULL, + NULL }; PyObject * _PySys_Init(void) { - PyObject *m, *v, *sysdict; - char *s; + PyObject *m, *v, *sysdict; + char *s; - m = PyModule_Create(&sysmodule); - if (m == NULL) - return NULL; - sysdict = PyModule_GetDict(m); -#define SET_SYS_FROM_STRING(key, value) \ - v = value; \ - if (v != NULL) \ - PyDict_SetItemString(sysdict, key, v); \ - Py_XDECREF(v) - - /* Check that stdin is not a directory - Using shell redirection, you can redirect stdin to a directory, - crashing the Python interpreter. Catch this common mistake here - and output a useful error message. Note that under MS Windows, - the shell already prevents that. */ + m = PyModule_Create(&sysmodule); + if (m == NULL) + return NULL; + sysdict = PyModule_GetDict(m); +#define SET_SYS_FROM_STRING(key, value) \ + v = value; \ + if (v != NULL) \ + PyDict_SetItemString(sysdict, key, v); \ + Py_XDECREF(v) + + /* Check that stdin is not a directory + Using shell redirection, you can redirect stdin to a directory, + crashing the Python interpreter. Catch this common mistake here + and output a useful error message. Note that under MS Windows, + the shell already prevents that. */ #if !defined(MS_WINDOWS) - { - struct stat sb; - if (fstat(fileno(stdin), &sb) == 0 && - S_ISDIR(sb.st_mode)) { - /* There's nothing more we can do. */ - /* Py_FatalError() will core dump, so just exit. */ - PySys_WriteStderr("Python error: is a directory, cannot continue\n"); - exit(EXIT_FAILURE); - } - } -#endif - - /* stdin/stdout/stderr are now set by pythonrun.c */ - - PyDict_SetItemString(sysdict, "__displayhook__", - PyDict_GetItemString(sysdict, "displayhook")); - PyDict_SetItemString(sysdict, "__excepthook__", - PyDict_GetItemString(sysdict, "excepthook")); - SET_SYS_FROM_STRING("version", - PyUnicode_FromString(Py_GetVersion())); - SET_SYS_FROM_STRING("hexversion", - PyLong_FromLong(PY_VERSION_HEX)); - svnversion_init(); - SET_SYS_FROM_STRING("subversion", - Py_BuildValue("(UUU)", "CPython", branch, - svn_revision)); - SET_SYS_FROM_STRING("dont_write_bytecode", - PyBool_FromLong(Py_DontWriteBytecodeFlag)); - SET_SYS_FROM_STRING("api_version", - PyLong_FromLong(PYTHON_API_VERSION)); - SET_SYS_FROM_STRING("copyright", - PyUnicode_FromString(Py_GetCopyright())); - SET_SYS_FROM_STRING("platform", - PyUnicode_FromString(Py_GetPlatform())); - SET_SYS_FROM_STRING("executable", - PyUnicode_FromWideChar( - Py_GetProgramFullPath(), -1)); - SET_SYS_FROM_STRING("prefix", - PyUnicode_FromWideChar(Py_GetPrefix(), -1)); - SET_SYS_FROM_STRING("exec_prefix", - PyUnicode_FromWideChar(Py_GetExecPrefix(), -1)); - SET_SYS_FROM_STRING("maxsize", - PyLong_FromSsize_t(PY_SSIZE_T_MAX)); - SET_SYS_FROM_STRING("float_info", - PyFloat_GetInfo()); - SET_SYS_FROM_STRING("int_info", - PyLong_GetInfo()); - SET_SYS_FROM_STRING("maxunicode", - PyLong_FromLong(PyUnicode_GetMax())); - SET_SYS_FROM_STRING("builtin_module_names", - list_builtin_module_names()); - { - /* Assumes that longs are at least 2 bytes long. - Should be safe! */ - unsigned long number = 1; - char *value; - - s = (char *) &number; - if (s[0] == 0) - value = "big"; - else - value = "little"; - SET_SYS_FROM_STRING("byteorder", - PyUnicode_FromString(value)); - } + { + struct stat sb; + if (fstat(fileno(stdin), &sb) == 0 && + S_ISDIR(sb.st_mode)) { + /* There's nothing more we can do. */ + /* Py_FatalError() will core dump, so just exit. */ + PySys_WriteStderr("Python error: is a directory, cannot continue\n"); + exit(EXIT_FAILURE); + } + } +#endif + + /* stdin/stdout/stderr are now set by pythonrun.c */ + + PyDict_SetItemString(sysdict, "__displayhook__", + PyDict_GetItemString(sysdict, "displayhook")); + PyDict_SetItemString(sysdict, "__excepthook__", + PyDict_GetItemString(sysdict, "excepthook")); + SET_SYS_FROM_STRING("version", + PyUnicode_FromString(Py_GetVersion())); + SET_SYS_FROM_STRING("hexversion", + PyLong_FromLong(PY_VERSION_HEX)); + svnversion_init(); + SET_SYS_FROM_STRING("subversion", + Py_BuildValue("(UUU)", "CPython", branch, + svn_revision)); + SET_SYS_FROM_STRING("dont_write_bytecode", + PyBool_FromLong(Py_DontWriteBytecodeFlag)); + SET_SYS_FROM_STRING("api_version", + PyLong_FromLong(PYTHON_API_VERSION)); + SET_SYS_FROM_STRING("copyright", + PyUnicode_FromString(Py_GetCopyright())); + SET_SYS_FROM_STRING("platform", + PyUnicode_FromString(Py_GetPlatform())); + SET_SYS_FROM_STRING("executable", + PyUnicode_FromWideChar( + Py_GetProgramFullPath(), -1)); + SET_SYS_FROM_STRING("prefix", + PyUnicode_FromWideChar(Py_GetPrefix(), -1)); + SET_SYS_FROM_STRING("exec_prefix", + PyUnicode_FromWideChar(Py_GetExecPrefix(), -1)); + SET_SYS_FROM_STRING("maxsize", + PyLong_FromSsize_t(PY_SSIZE_T_MAX)); + SET_SYS_FROM_STRING("float_info", + PyFloat_GetInfo()); + SET_SYS_FROM_STRING("int_info", + PyLong_GetInfo()); + SET_SYS_FROM_STRING("maxunicode", + PyLong_FromLong(PyUnicode_GetMax())); + SET_SYS_FROM_STRING("builtin_module_names", + list_builtin_module_names()); + { + /* Assumes that longs are at least 2 bytes long. + Should be safe! */ + unsigned long number = 1; + char *value; + + s = (char *) &number; + if (s[0] == 0) + value = "big"; + else + value = "little"; + SET_SYS_FROM_STRING("byteorder", + PyUnicode_FromString(value)); + } #ifdef MS_COREDLL - SET_SYS_FROM_STRING("dllhandle", - PyLong_FromVoidPtr(PyWin_DLLhModule)); - SET_SYS_FROM_STRING("winver", - PyUnicode_FromString(PyWin_DLLVersionString)); -#endif - if (warnoptions == NULL) { - warnoptions = PyList_New(0); - } - else { - Py_INCREF(warnoptions); - } - if (warnoptions != NULL) { - PyDict_SetItemString(sysdict, "warnoptions", warnoptions); - } - - /* version_info */ - if (VersionInfoType.tp_name == 0) - PyStructSequence_InitType(&VersionInfoType, &version_info_desc); - SET_SYS_FROM_STRING("version_info", make_version_info()); - /* prevent user from creating new instances */ - VersionInfoType.tp_init = NULL; - VersionInfoType.tp_new = NULL; - - /* flags */ - if (FlagsType.tp_name == 0) - PyStructSequence_InitType(&FlagsType, &flags_desc); - SET_SYS_FROM_STRING("flags", make_flags()); - /* prevent user from creating new instances */ - FlagsType.tp_init = NULL; - FlagsType.tp_new = NULL; + SET_SYS_FROM_STRING("dllhandle", + PyLong_FromVoidPtr(PyWin_DLLhModule)); + SET_SYS_FROM_STRING("winver", + PyUnicode_FromString(PyWin_DLLVersionString)); +#endif + if (warnoptions == NULL) { + warnoptions = PyList_New(0); + } + else { + Py_INCREF(warnoptions); + } + if (warnoptions != NULL) { + PyDict_SetItemString(sysdict, "warnoptions", warnoptions); + } + + /* version_info */ + if (VersionInfoType.tp_name == 0) + PyStructSequence_InitType(&VersionInfoType, &version_info_desc); + SET_SYS_FROM_STRING("version_info", make_version_info()); + /* prevent user from creating new instances */ + VersionInfoType.tp_init = NULL; + VersionInfoType.tp_new = NULL; + + /* flags */ + if (FlagsType.tp_name == 0) + PyStructSequence_InitType(&FlagsType, &flags_desc); + SET_SYS_FROM_STRING("flags", make_flags()); + /* prevent user from creating new instances */ + FlagsType.tp_init = NULL; + FlagsType.tp_new = NULL; #if defined(MS_WINDOWS) - /* getwindowsversion */ - if (WindowsVersionType.tp_name == 0) - PyStructSequence_InitType(&WindowsVersionType, &windows_version_desc); - /* prevent user from creating new instances */ - WindowsVersionType.tp_init = NULL; - WindowsVersionType.tp_new = NULL; + /* getwindowsversion */ + if (WindowsVersionType.tp_name == 0) + PyStructSequence_InitType(&WindowsVersionType, &windows_version_desc); + /* prevent user from creating new instances */ + WindowsVersionType.tp_init = NULL; + WindowsVersionType.tp_new = NULL; #endif - /* float repr style: 0.03 (short) vs 0.029999999999999999 (legacy) */ + /* float repr style: 0.03 (short) vs 0.029999999999999999 (legacy) */ #ifndef PY_NO_SHORT_FLOAT_REPR - SET_SYS_FROM_STRING("float_repr_style", - PyUnicode_FromString("short")); + SET_SYS_FROM_STRING("float_repr_style", + PyUnicode_FromString("short")); #else - SET_SYS_FROM_STRING("float_repr_style", - PyUnicode_FromString("legacy")); + SET_SYS_FROM_STRING("float_repr_style", + PyUnicode_FromString("legacy")); #endif #undef SET_SYS_FROM_STRING - if (PyErr_Occurred()) - return NULL; - return m; + if (PyErr_Occurred()) + return NULL; + return m; } static PyObject * makepathobject(const wchar_t *path, wchar_t delim) { - int i, n; - const wchar_t *p; - PyObject *v, *w; - - n = 1; - p = path; - while ((p = wcschr(p, delim)) != NULL) { - n++; - p++; - } - v = PyList_New(n); - if (v == NULL) - return NULL; - for (i = 0; ; i++) { - p = wcschr(path, delim); - if (p == NULL) - p = path + wcslen(path); /* End of string */ - w = PyUnicode_FromWideChar(path, (Py_ssize_t)(p - path)); - if (w == NULL) { - Py_DECREF(v); - return NULL; - } - PyList_SetItem(v, i, w); - if (*p == '\0') - break; - path = p+1; - } - return v; + int i, n; + const wchar_t *p; + PyObject *v, *w; + + n = 1; + p = path; + while ((p = wcschr(p, delim)) != NULL) { + n++; + p++; + } + v = PyList_New(n); + if (v == NULL) + return NULL; + for (i = 0; ; i++) { + p = wcschr(path, delim); + if (p == NULL) + p = path + wcslen(path); /* End of string */ + w = PyUnicode_FromWideChar(path, (Py_ssize_t)(p - path)); + if (w == NULL) { + Py_DECREF(v); + return NULL; + } + PyList_SetItem(v, i, w); + if (*p == '\0') + break; + path = p+1; + } + return v; } void PySys_SetPath(const wchar_t *path) { - PyObject *v; - if ((v = makepathobject(path, DELIM)) == NULL) - Py_FatalError("can't create sys.path"); - if (PySys_SetObject("path", v) != 0) - Py_FatalError("can't assign sys.path"); - Py_DECREF(v); + PyObject *v; + if ((v = makepathobject(path, DELIM)) == NULL) + Py_FatalError("can't create sys.path"); + if (PySys_SetObject("path", v) != 0) + Py_FatalError("can't assign sys.path"); + Py_DECREF(v); } static PyObject * makeargvobject(int argc, wchar_t **argv) { - PyObject *av; - if (argc <= 0 || argv == NULL) { - /* Ensure at least one (empty) argument is seen */ - static wchar_t *empty_argv[1] = {L""}; - argv = empty_argv; - argc = 1; - } - av = PyList_New(argc); - if (av != NULL) { - int i; - for (i = 0; i < argc; i++) { + PyObject *av; + if (argc <= 0 || argv == NULL) { + /* Ensure at least one (empty) argument is seen */ + static wchar_t *empty_argv[1] = {L""}; + argv = empty_argv; + argc = 1; + } + av = PyList_New(argc); + if (av != NULL) { + int i; + for (i = 0; i < argc; i++) { #ifdef __VMS - PyObject *v; + PyObject *v; - /* argv[0] is the script pathname if known */ - if (i == 0) { - char* fn = decc$translate_vms(argv[0]); - if ((fn == (char *)0) || fn == (char *)-1) - v = PyUnicode_FromString(argv[0]); - else - v = PyUnicode_FromString( - decc$translate_vms(argv[0])); - } else - v = PyUnicode_FromString(argv[i]); + /* argv[0] is the script pathname if known */ + if (i == 0) { + char* fn = decc$translate_vms(argv[0]); + if ((fn == (char *)0) || fn == (char *)-1) + v = PyUnicode_FromString(argv[0]); + else + v = PyUnicode_FromString( + decc$translate_vms(argv[0])); + } else + v = PyUnicode_FromString(argv[i]); #else - PyObject *v = PyUnicode_FromWideChar(argv[i], -1); + PyObject *v = PyUnicode_FromWideChar(argv[i], -1); #endif - if (v == NULL) { - Py_DECREF(av); - av = NULL; - break; - } - PyList_SetItem(av, i, v); - } - } - return av; + if (v == NULL) { + Py_DECREF(av); + av = NULL; + break; + } + PyList_SetItem(av, i, v); + } + } + return av; } #ifdef HAVE_REALPATH static wchar_t* _wrealpath(const wchar_t *path, wchar_t *resolved_path) { - char cpath[PATH_MAX]; - char cresolved_path[PATH_MAX]; - char *res; - size_t r; - r = wcstombs(cpath, path, PATH_MAX); - if (r == (size_t)-1 || r >= PATH_MAX) { - errno = EINVAL; - return NULL; - } - res = realpath(cpath, cresolved_path); - if (res == NULL) - return NULL; - r = mbstowcs(resolved_path, cresolved_path, PATH_MAX); - if (r == (size_t)-1 || r >= PATH_MAX) { - errno = EINVAL; - return NULL; - } - return resolved_path; + char cpath[PATH_MAX]; + char cresolved_path[PATH_MAX]; + char *res; + size_t r; + r = wcstombs(cpath, path, PATH_MAX); + if (r == (size_t)-1 || r >= PATH_MAX) { + errno = EINVAL; + return NULL; + } + res = realpath(cpath, cresolved_path); + if (res == NULL) + return NULL; + r = mbstowcs(resolved_path, cresolved_path, PATH_MAX); + if (r == (size_t)-1 || r >= PATH_MAX) { + errno = EINVAL; + return NULL; + } + return resolved_path; } #endif @@ -1666,101 +1666,101 @@ PySys_SetArgv(int argc, wchar_t **argv) { #if defined(HAVE_REALPATH) - wchar_t fullpath[MAXPATHLEN]; + wchar_t fullpath[MAXPATHLEN]; #elif defined(MS_WINDOWS) && !defined(MS_WINCE) - wchar_t fullpath[MAX_PATH]; + wchar_t fullpath[MAX_PATH]; #endif - PyObject *av = makeargvobject(argc, argv); - PyObject *path = PySys_GetObject("path"); - if (av == NULL) - Py_FatalError("no mem for sys.argv"); - if (PySys_SetObject("argv", av) != 0) - Py_FatalError("can't assign sys.argv"); - if (path != NULL) { - wchar_t *argv0 = argv[0]; - wchar_t *p = NULL; - Py_ssize_t n = 0; - PyObject *a; - extern int _Py_wreadlink(const wchar_t *, wchar_t *, size_t); + PyObject *av = makeargvobject(argc, argv); + PyObject *path = PySys_GetObject("path"); + if (av == NULL) + Py_FatalError("no mem for sys.argv"); + if (PySys_SetObject("argv", av) != 0) + Py_FatalError("can't assign sys.argv"); + if (path != NULL) { + wchar_t *argv0 = argv[0]; + wchar_t *p = NULL; + Py_ssize_t n = 0; + PyObject *a; + extern int _Py_wreadlink(const wchar_t *, wchar_t *, size_t); #ifdef HAVE_READLINK - wchar_t link[MAXPATHLEN+1]; - wchar_t argv0copy[2*MAXPATHLEN+1]; - int nr = 0; - if (argc > 0 && argv0 != NULL && wcscmp(argv0, L"-c") != 0) - nr = _Py_wreadlink(argv0, link, MAXPATHLEN); - if (nr > 0) { - /* It's a symlink */ - link[nr] = '\0'; - if (link[0] == SEP) - argv0 = link; /* Link to absolute path */ - else if (wcschr(link, SEP) == NULL) - ; /* Link without path */ - else { - /* Must join(dirname(argv0), link) */ - wchar_t *q = wcsrchr(argv0, SEP); - if (q == NULL) - argv0 = link; /* argv0 without path */ - else { - /* Must make a copy */ - wcscpy(argv0copy, argv0); - q = wcsrchr(argv0copy, SEP); - wcscpy(q+1, link); - argv0 = argv0copy; - } - } - } + wchar_t link[MAXPATHLEN+1]; + wchar_t argv0copy[2*MAXPATHLEN+1]; + int nr = 0; + if (argc > 0 && argv0 != NULL && wcscmp(argv0, L"-c") != 0) + nr = _Py_wreadlink(argv0, link, MAXPATHLEN); + if (nr > 0) { + /* It's a symlink */ + link[nr] = '\0'; + if (link[0] == SEP) + argv0 = link; /* Link to absolute path */ + else if (wcschr(link, SEP) == NULL) + ; /* Link without path */ + else { + /* Must join(dirname(argv0), link) */ + wchar_t *q = wcsrchr(argv0, SEP); + if (q == NULL) + argv0 = link; /* argv0 without path */ + else { + /* Must make a copy */ + wcscpy(argv0copy, argv0); + q = wcsrchr(argv0copy, SEP); + wcscpy(q+1, link); + argv0 = argv0copy; + } + } + } #endif /* HAVE_READLINK */ #if SEP == '\\' /* Special case for MS filename syntax */ - if (argc > 0 && argv0 != NULL && wcscmp(argv0, L"-c") != 0) { - wchar_t *q; + if (argc > 0 && argv0 != NULL && wcscmp(argv0, L"-c") != 0) { + wchar_t *q; #if defined(MS_WINDOWS) && !defined(MS_WINCE) - /* This code here replaces the first element in argv with the full - path that it represents. Under CE, there are no relative paths so - the argument must be the full path anyway. */ - wchar_t *ptemp; - if (GetFullPathNameW(argv0, - sizeof(fullpath)/sizeof(fullpath[0]), - fullpath, - &ptemp)) { - argv0 = fullpath; - } -#endif - p = wcsrchr(argv0, SEP); - /* Test for alternate separator */ - q = wcsrchr(p ? p : argv0, '/'); - if (q != NULL) - p = q; - if (p != NULL) { - n = p + 1 - argv0; - if (n > 1 && p[-1] != ':') - n--; /* Drop trailing separator */ - } - } + /* This code here replaces the first element in argv with the full + path that it represents. Under CE, there are no relative paths so + the argument must be the full path anyway. */ + wchar_t *ptemp; + if (GetFullPathNameW(argv0, + sizeof(fullpath)/sizeof(fullpath[0]), + fullpath, + &ptemp)) { + argv0 = fullpath; + } +#endif + p = wcsrchr(argv0, SEP); + /* Test for alternate separator */ + q = wcsrchr(p ? p : argv0, '/'); + if (q != NULL) + p = q; + if (p != NULL) { + n = p + 1 - argv0; + if (n > 1 && p[-1] != ':') + n--; /* Drop trailing separator */ + } + } #else /* All other filename syntaxes */ - if (argc > 0 && argv0 != NULL && wcscmp(argv0, L"-c") != 0) { + if (argc > 0 && argv0 != NULL && wcscmp(argv0, L"-c") != 0) { #if defined(HAVE_REALPATH) - if (_wrealpath(argv0, fullpath)) { - argv0 = fullpath; - } -#endif - p = wcsrchr(argv0, SEP); - } - if (p != NULL) { - n = p + 1 - argv0; + if (_wrealpath(argv0, fullpath)) { + argv0 = fullpath; + } +#endif + p = wcsrchr(argv0, SEP); + } + if (p != NULL) { + n = p + 1 - argv0; #if SEP == '/' /* Special case for Unix filename syntax */ - if (n > 1) - n--; /* Drop trailing separator */ + if (n > 1) + n--; /* Drop trailing separator */ #endif /* Unix */ - } + } #endif /* All others */ - a = PyUnicode_FromWideChar(argv0, n); - if (a == NULL) - Py_FatalError("no mem for sys.path insertion"); - if (PyList_Insert(path, 0, a) < 0) - Py_FatalError("sys.path.insert(0) failed"); - Py_DECREF(a); - } - Py_DECREF(av); + a = PyUnicode_FromWideChar(argv0, n); + if (a == NULL) + Py_FatalError("no mem for sys.path insertion"); + if (PyList_Insert(path, 0, a) < 0) + Py_FatalError("sys.path.insert(0) failed"); + Py_DECREF(a); + } + Py_DECREF(av); } /* Reimplementation of PyFile_WriteString() no calling indirectly @@ -1769,37 +1769,37 @@ static int sys_pyfile_write(const char *text, PyObject *file) { - PyObject *unicode = NULL, *writer = NULL, *args = NULL, *result = NULL; - int err; + PyObject *unicode = NULL, *writer = NULL, *args = NULL, *result = NULL; + int err; - unicode = PyUnicode_FromString(text); - if (unicode == NULL) - goto error; - - writer = PyObject_GetAttrString(file, "write"); - if (writer == NULL) - goto error; - - args = PyTuple_Pack(1, unicode); - if (args == NULL) - goto error; - - result = PyEval_CallObject(writer, args); - if (result == NULL) { - goto error; - } else { - err = 0; - goto finally; - } + unicode = PyUnicode_FromString(text); + if (unicode == NULL) + goto error; + + writer = PyObject_GetAttrString(file, "write"); + if (writer == NULL) + goto error; + + args = PyTuple_Pack(1, unicode); + if (args == NULL) + goto error; + + result = PyEval_CallObject(writer, args); + if (result == NULL) { + goto error; + } else { + err = 0; + goto finally; + } error: - err = -1; + err = -1; finally: - Py_XDECREF(unicode); - Py_XDECREF(writer); - Py_XDECREF(args); - Py_XDECREF(result); - return err; + Py_XDECREF(unicode); + Py_XDECREF(writer); + Py_XDECREF(args); + Py_XDECREF(result); + return err; } @@ -1834,44 +1834,44 @@ static void mywrite(char *name, FILE *fp, const char *format, va_list va) { - PyObject *file; - PyObject *error_type, *error_value, *error_traceback; - char buffer[1001]; - int written; - - PyErr_Fetch(&error_type, &error_value, &error_traceback); - file = PySys_GetObject(name); - written = PyOS_vsnprintf(buffer, sizeof(buffer), format, va); - if (sys_pyfile_write(buffer, file) != 0) { - PyErr_Clear(); - fputs(buffer, fp); - } - if (written < 0 || (size_t)written >= sizeof(buffer)) { - const char *truncated = "... truncated"; - if (sys_pyfile_write(truncated, file) != 0) { - PyErr_Clear(); - fputs(truncated, fp); - } - } - PyErr_Restore(error_type, error_value, error_traceback); + PyObject *file; + PyObject *error_type, *error_value, *error_traceback; + char buffer[1001]; + int written; + + PyErr_Fetch(&error_type, &error_value, &error_traceback); + file = PySys_GetObject(name); + written = PyOS_vsnprintf(buffer, sizeof(buffer), format, va); + if (sys_pyfile_write(buffer, file) != 0) { + PyErr_Clear(); + fputs(buffer, fp); + } + if (written < 0 || (size_t)written >= sizeof(buffer)) { + const char *truncated = "... truncated"; + if (sys_pyfile_write(truncated, file) != 0) { + PyErr_Clear(); + fputs(truncated, fp); + } + } + PyErr_Restore(error_type, error_value, error_traceback); } void PySys_WriteStdout(const char *format, ...) { - va_list va; + va_list va; - va_start(va, format); - mywrite("stdout", stdout, format, va); - va_end(va); + va_start(va, format); + mywrite("stdout", stdout, format, va); + va_end(va); } void PySys_WriteStderr(const char *format, ...) { - va_list va; + va_list va; - va_start(va, format); - mywrite("stderr", stderr, format, va); - va_end(va); + va_start(va, format); + mywrite("stderr", stderr, format, va); + va_end(va); } Modified: python/branches/py3k/Python/thread.c ============================================================================== --- python/branches/py3k/Python/thread.c (original) +++ python/branches/py3k/Python/thread.c Sun May 9 17:52:27 2010 @@ -40,7 +40,7 @@ #endif /* Check if we're running on HP-UX and _SC_THREADS is defined. If so, then - enough of the Posix threads package is implimented to support python + enough of the Posix threads package is implimented to support python threads. This is valid for HP-UX 11.23 running on an ia64 system. If needed, add @@ -58,8 +58,8 @@ #ifdef Py_DEBUG static int thread_debug = 0; -#define dprintf(args) (void)((thread_debug & 1) && printf args) -#define d2printf(args) ((thread_debug & 8) && printf args) +#define dprintf(args) (void)((thread_debug & 1) && printf args) +#define d2printf(args) ((thread_debug & 8) && printf args) #else #define dprintf(args) #define d2printf(args) @@ -73,20 +73,20 @@ PyThread_init_thread(void) { #ifdef Py_DEBUG - char *p = Py_GETENV("PYTHONTHREADDEBUG"); + char *p = Py_GETENV("PYTHONTHREADDEBUG"); - if (p) { - if (*p) - thread_debug = atoi(p); - else - thread_debug = 1; - } + if (p) { + if (*p) + thread_debug = atoi(p); + else + thread_debug = 1; + } #endif /* Py_DEBUG */ - if (initialized) - return; - initialized = 1; - dprintf(("PyThread_init_thread called\n")); - PyThread__init_thread(); + if (initialized) + return; + initialized = 1; + dprintf(("PyThread_init_thread called\n")); + PyThread__init_thread(); } /* Support for runtime thread stack size tuning. @@ -145,21 +145,21 @@ size_t PyThread_get_stacksize(void) { - return _pythread_stacksize; + return _pythread_stacksize; } /* Only platforms defining a THREAD_SET_STACKSIZE() macro in thread_.h support changing the stack size. Return 0 if stack size is valid, - -1 if stack size value is invalid, - -2 if setting stack size is not supported. */ + -1 if stack size value is invalid, + -2 if setting stack size is not supported. */ int PyThread_set_stacksize(size_t size) { #if defined(THREAD_SET_STACKSIZE) - return THREAD_SET_STACKSIZE(size); + return THREAD_SET_STACKSIZE(size); #else - return -2; + return -2; #endif } @@ -211,15 +211,15 @@ * to enforce exclusion internally. */ struct key { - /* Next record in the list, or NULL if this is the last record. */ - struct key *next; + /* Next record in the list, or NULL if this is the last record. */ + struct key *next; - /* The thread id, according to PyThread_get_thread_ident(). */ - long id; + /* The thread id, according to PyThread_get_thread_ident(). */ + long id; - /* The key and its associated value. */ - int key; - void *value; + /* The key and its associated value. */ + int key; + void *value; }; static struct key *keyhead = NULL; @@ -250,41 +250,41 @@ static struct key * find_key(int key, void *value) { - struct key *p, *prev_p; - long id = PyThread_get_thread_ident(); + struct key *p, *prev_p; + long id = PyThread_get_thread_ident(); - if (!keymutex) - return NULL; - PyThread_acquire_lock(keymutex, 1); - prev_p = NULL; - for (p = keyhead; p != NULL; p = p->next) { - if (p->id == id && p->key == key) - goto Done; - /* Sanity check. These states should never happen but if - * they do we must abort. Otherwise we'll end up spinning in - * in a tight loop with the lock held. A similar check is done - * in pystate.c tstate_delete_common(). */ - if (p == prev_p) - Py_FatalError("tls find_key: small circular list(!)"); - prev_p = p; - if (p->next == keyhead) - Py_FatalError("tls find_key: circular list(!)"); - } - if (value == NULL) { - assert(p == NULL); - goto Done; - } - p = (struct key *)malloc(sizeof(struct key)); - if (p != NULL) { - p->id = id; - p->key = key; - p->value = value; - p->next = keyhead; - keyhead = p; - } + if (!keymutex) + return NULL; + PyThread_acquire_lock(keymutex, 1); + prev_p = NULL; + for (p = keyhead; p != NULL; p = p->next) { + if (p->id == id && p->key == key) + goto Done; + /* Sanity check. These states should never happen but if + * they do we must abort. Otherwise we'll end up spinning in + * in a tight loop with the lock held. A similar check is done + * in pystate.c tstate_delete_common(). */ + if (p == prev_p) + Py_FatalError("tls find_key: small circular list(!)"); + prev_p = p; + if (p->next == keyhead) + Py_FatalError("tls find_key: circular list(!)"); + } + if (value == NULL) { + assert(p == NULL); + goto Done; + } + p = (struct key *)malloc(sizeof(struct key)); + if (p != NULL) { + p->id = id; + p->key = key; + p->value = value; + p->next = keyhead; + keyhead = p; + } Done: - PyThread_release_lock(keymutex); - return p; + PyThread_release_lock(keymutex); + return p; } /* Return a new key. This must be called before any other functions in @@ -294,32 +294,32 @@ int PyThread_create_key(void) { - /* All parts of this function are wrong if it's called by multiple - * threads simultaneously. - */ - if (keymutex == NULL) - keymutex = PyThread_allocate_lock(); - return ++nkeys; + /* All parts of this function are wrong if it's called by multiple + * threads simultaneously. + */ + if (keymutex == NULL) + keymutex = PyThread_allocate_lock(); + return ++nkeys; } /* Forget the associations for key across *all* threads. */ void PyThread_delete_key(int key) { - struct key *p, **q; + struct key *p, **q; - PyThread_acquire_lock(keymutex, 1); - q = &keyhead; - while ((p = *q) != NULL) { - if (p->key == key) { - *q = p->next; - free((void *)p); - /* NB This does *not* free p->value! */ - } - else - q = &p->next; - } - PyThread_release_lock(keymutex); + PyThread_acquire_lock(keymutex, 1); + q = &keyhead; + while ((p = *q) != NULL) { + if (p->key == key) { + *q = p->next; + free((void *)p); + /* NB This does *not* free p->value! */ + } + else + q = &p->next; + } + PyThread_release_lock(keymutex); } /* Confusing: If the current thread has an association for key, @@ -331,14 +331,14 @@ int PyThread_set_key_value(int key, void *value) { - struct key *p; + struct key *p; - assert(value != NULL); - p = find_key(key, value); - if (p == NULL) - return -1; - else - return 0; + assert(value != NULL); + p = find_key(key, value); + if (p == NULL) + return -1; + else + return 0; } /* Retrieve the value associated with key in the current thread, or NULL @@ -347,34 +347,34 @@ void * PyThread_get_key_value(int key) { - struct key *p = find_key(key, NULL); + struct key *p = find_key(key, NULL); - if (p == NULL) - return NULL; - else - return p->value; + if (p == NULL) + return NULL; + else + return p->value; } /* Forget the current thread's association for key, if any. */ void PyThread_delete_key_value(int key) { - long id = PyThread_get_thread_ident(); - struct key *p, **q; + long id = PyThread_get_thread_ident(); + struct key *p, **q; - PyThread_acquire_lock(keymutex, 1); - q = &keyhead; - while ((p = *q) != NULL) { - if (p->key == key && p->id == id) { - *q = p->next; - free((void *)p); - /* NB This does *not* free p->value! */ - break; - } - else - q = &p->next; - } - PyThread_release_lock(keymutex); + PyThread_acquire_lock(keymutex, 1); + q = &keyhead; + while ((p = *q) != NULL) { + if (p->key == key && p->id == id) { + *q = p->next; + free((void *)p); + /* NB This does *not* free p->value! */ + break; + } + else + q = &p->next; + } + PyThread_release_lock(keymutex); } /* Forget everything not associated with the current thread id. @@ -385,27 +385,27 @@ void PyThread_ReInitTLS(void) { - long id = PyThread_get_thread_ident(); - struct key *p, **q; + long id = PyThread_get_thread_ident(); + struct key *p, **q; - if (!keymutex) - return; - - /* As with interpreter_lock in PyEval_ReInitThreads() - we just create a new lock without freeing the old one */ - keymutex = PyThread_allocate_lock(); - - /* Delete all keys which do not match the current thread id */ - q = &keyhead; - while ((p = *q) != NULL) { - if (p->id != id) { - *q = p->next; - free((void *)p); - /* NB This does *not* free p->value! */ - } - else - q = &p->next; - } + if (!keymutex) + return; + + /* As with interpreter_lock in PyEval_ReInitThreads() + we just create a new lock without freeing the old one */ + keymutex = PyThread_allocate_lock(); + + /* Delete all keys which do not match the current thread id */ + q = &keyhead; + while ((p = *q) != NULL) { + if (p->id != id) { + *q = p->next; + free((void *)p); + /* NB This does *not* free p->value! */ + } + else + q = &p->next; + } } #endif /* Py_HAVE_NATIVE_TLS */ Modified: python/branches/py3k/Python/thread_cthread.h ============================================================================== --- python/branches/py3k/Python/thread_cthread.h (original) +++ python/branches/py3k/Python/thread_cthread.h Sun May 9 17:52:27 2010 @@ -14,12 +14,12 @@ PyThread__init_thread(void) { #ifndef HURD_C_THREADS - /* Roland McGrath said this should not be used since this is - done while linking to threads */ - cthread_init(); + /* Roland McGrath said this should not be used since this is + done while linking to threads */ + cthread_init(); #else /* do nothing */ - ; + ; #endif } @@ -29,34 +29,34 @@ long PyThread_start_new_thread(void (*func)(void *), void *arg) { - int success = 0; /* init not needed when SOLARIS_THREADS and */ - /* C_THREADS implemented properly */ + int success = 0; /* init not needed when SOLARIS_THREADS and */ + /* C_THREADS implemented properly */ - dprintf(("PyThread_start_new_thread called\n")); - if (!initialized) - PyThread_init_thread(); - /* looks like solaris detaches the thread to never rejoin - * so well do it here - */ - cthread_detach(cthread_fork((cthread_fn_t) func, arg)); - return success < 0 ? -1 : 0; + dprintf(("PyThread_start_new_thread called\n")); + if (!initialized) + PyThread_init_thread(); + /* looks like solaris detaches the thread to never rejoin + * so well do it here + */ + cthread_detach(cthread_fork((cthread_fn_t) func, arg)); + return success < 0 ? -1 : 0; } long PyThread_get_thread_ident(void) { - if (!initialized) - PyThread_init_thread(); - return (long) cthread_self(); + if (!initialized) + PyThread_init_thread(); + return (long) cthread_self(); } void PyThread_exit_thread(void) { - dprintf(("PyThread_exit_thread called\n")); - if (!initialized) - exit(0); - cthread_exit(0); + dprintf(("PyThread_exit_thread called\n")); + if (!initialized) + exit(0); + cthread_exit(0); } /* @@ -65,48 +65,48 @@ PyThread_type_lock PyThread_allocate_lock(void) { - mutex_t lock; + mutex_t lock; - dprintf(("PyThread_allocate_lock called\n")); - if (!initialized) - PyThread_init_thread(); - - lock = mutex_alloc(); - if (mutex_init(lock)) { - perror("mutex_init"); - free((void *) lock); - lock = 0; - } - dprintf(("PyThread_allocate_lock() -> %p\n", lock)); - return (PyThread_type_lock) lock; + dprintf(("PyThread_allocate_lock called\n")); + if (!initialized) + PyThread_init_thread(); + + lock = mutex_alloc(); + if (mutex_init(lock)) { + perror("mutex_init"); + free((void *) lock); + lock = 0; + } + dprintf(("PyThread_allocate_lock() -> %p\n", lock)); + return (PyThread_type_lock) lock; } void PyThread_free_lock(PyThread_type_lock lock) { - dprintf(("PyThread_free_lock(%p) called\n", lock)); - mutex_free(lock); + dprintf(("PyThread_free_lock(%p) called\n", lock)); + mutex_free(lock); } int PyThread_acquire_lock(PyThread_type_lock lock, int waitflag) { - int success = FALSE; + int success = FALSE; - dprintf(("PyThread_acquire_lock(%p, %d) called\n", lock, waitflag)); - if (waitflag) { /* blocking */ - mutex_lock((mutex_t)lock); - success = TRUE; - } else { /* non blocking */ - success = mutex_try_lock((mutex_t)lock); - } - dprintf(("PyThread_acquire_lock(%p, %d) -> %d\n", lock, waitflag, success)); - return success; + dprintf(("PyThread_acquire_lock(%p, %d) called\n", lock, waitflag)); + if (waitflag) { /* blocking */ + mutex_lock((mutex_t)lock); + success = TRUE; + } else { /* non blocking */ + success = mutex_try_lock((mutex_t)lock); + } + dprintf(("PyThread_acquire_lock(%p, %d) -> %d\n", lock, waitflag, success)); + return success; } void PyThread_release_lock(PyThread_type_lock lock) { - dprintf(("PyThread_release_lock(%p) called\n", lock)); - mutex_unlock((mutex_t )lock); + dprintf(("PyThread_release_lock(%p) called\n", lock)); + mutex_unlock((mutex_t )lock); } Modified: python/branches/py3k/Python/thread_foobar.h ============================================================================== --- python/branches/py3k/Python/thread_foobar.h (original) +++ python/branches/py3k/Python/thread_foobar.h Sun May 9 17:52:27 2010 @@ -13,28 +13,28 @@ long PyThread_start_new_thread(void (*func)(void *), void *arg) { - int success = 0; /* init not needed when SOLARIS_THREADS and */ - /* C_THREADS implemented properly */ + int success = 0; /* init not needed when SOLARIS_THREADS and */ + /* C_THREADS implemented properly */ - dprintf(("PyThread_start_new_thread called\n")); - if (!initialized) - PyThread_init_thread(); - return success < 0 ? -1 : 0; + dprintf(("PyThread_start_new_thread called\n")); + if (!initialized) + PyThread_init_thread(); + return success < 0 ? -1 : 0; } long PyThread_get_thread_ident(void) { - if (!initialized) - PyThread_init_thread(); + if (!initialized) + PyThread_init_thread(); } void PyThread_exit_thread(void) { - dprintf(("PyThread_exit_thread called\n")); - if (!initialized) - exit(0); + dprintf(("PyThread_exit_thread called\n")); + if (!initialized) + exit(0); } /* @@ -44,32 +44,32 @@ PyThread_allocate_lock(void) { - dprintf(("PyThread_allocate_lock called\n")); - if (!initialized) - PyThread_init_thread(); + dprintf(("PyThread_allocate_lock called\n")); + if (!initialized) + PyThread_init_thread(); - dprintf(("PyThread_allocate_lock() -> %p\n", lock)); - return (PyThread_type_lock) lock; + dprintf(("PyThread_allocate_lock() -> %p\n", lock)); + return (PyThread_type_lock) lock; } void PyThread_free_lock(PyThread_type_lock lock) { - dprintf(("PyThread_free_lock(%p) called\n", lock)); + dprintf(("PyThread_free_lock(%p) called\n", lock)); } int PyThread_acquire_lock(PyThread_type_lock lock, int waitflag) { - int success; + int success; - dprintf(("PyThread_acquire_lock(%p, %d) called\n", lock, waitflag)); - dprintf(("PyThread_acquire_lock(%p, %d) -> %d\n", lock, waitflag, success)); - return success; + dprintf(("PyThread_acquire_lock(%p, %d) called\n", lock, waitflag)); + dprintf(("PyThread_acquire_lock(%p, %d) -> %d\n", lock, waitflag, success)); + return success; } void PyThread_release_lock(PyThread_type_lock lock) { - dprintf(("PyThread_release_lock(%p) called\n", lock)); + dprintf(("PyThread_release_lock(%p) called\n", lock)); } Modified: python/branches/py3k/Python/thread_lwp.h ============================================================================== --- python/branches/py3k/Python/thread_lwp.h (original) +++ python/branches/py3k/Python/thread_lwp.h Sun May 9 17:52:27 2010 @@ -3,13 +3,13 @@ #include #include -#define STACKSIZE 1000 /* stacksize for a thread */ -#define NSTACKS 2 /* # stacks to be put in cache initially */ +#define STACKSIZE 1000 /* stacksize for a thread */ +#define NSTACKS 2 /* # stacks to be put in cache initially */ struct lock { - int lock_locked; - cv_t lock_condvar; - mon_t lock_monitor; + int lock_locked; + cv_t lock_condvar; + mon_t lock_monitor; }; @@ -18,7 +18,7 @@ */ static void PyThread__init_thread(void) { - lwp_setstkcache(STACKSIZE, NSTACKS); + lwp_setstkcache(STACKSIZE, NSTACKS); } /* @@ -28,31 +28,31 @@ long PyThread_start_new_thread(void (*func)(void *), void *arg) { - thread_t tid; - int success; - dprintf(("PyThread_start_new_thread called\n")); - if (!initialized) - PyThread_init_thread(); - success = lwp_create(&tid, func, MINPRIO, 0, lwp_newstk(), 1, arg); - return success < 0 ? -1 : 0; + thread_t tid; + int success; + dprintf(("PyThread_start_new_thread called\n")); + if (!initialized) + PyThread_init_thread(); + success = lwp_create(&tid, func, MINPRIO, 0, lwp_newstk(), 1, arg); + return success < 0 ? -1 : 0; } long PyThread_get_thread_ident(void) { - thread_t tid; - if (!initialized) - PyThread_init_thread(); - if (lwp_self(&tid) < 0) - return -1; - return tid.thread_id; + thread_t tid; + if (!initialized) + PyThread_init_thread(); + if (lwp_self(&tid) < 0) + return -1; + return tid.thread_id; } void PyThread_exit_thread(void) { - dprintf(("PyThread_exit_thread called\n")); - if (!initialized) - exit(0); - lwp_destroy(SELF); + dprintf(("PyThread_exit_thread called\n")); + if (!initialized) + exit(0); + lwp_destroy(SELF); } /* @@ -60,54 +60,54 @@ */ PyThread_type_lock PyThread_allocate_lock(void) { - struct lock *lock; - extern char *malloc(size_t); + struct lock *lock; + extern char *malloc(size_t); - dprintf(("PyThread_allocate_lock called\n")); - if (!initialized) - PyThread_init_thread(); - - lock = (struct lock *) malloc(sizeof(struct lock)); - lock->lock_locked = 0; - (void) mon_create(&lock->lock_monitor); - (void) cv_create(&lock->lock_condvar, lock->lock_monitor); - dprintf(("PyThread_allocate_lock() -> %p\n", lock)); - return (PyThread_type_lock) lock; + dprintf(("PyThread_allocate_lock called\n")); + if (!initialized) + PyThread_init_thread(); + + lock = (struct lock *) malloc(sizeof(struct lock)); + lock->lock_locked = 0; + (void) mon_create(&lock->lock_monitor); + (void) cv_create(&lock->lock_condvar, lock->lock_monitor); + dprintf(("PyThread_allocate_lock() -> %p\n", lock)); + return (PyThread_type_lock) lock; } void PyThread_free_lock(PyThread_type_lock lock) { - dprintf(("PyThread_free_lock(%p) called\n", lock)); - mon_destroy(((struct lock *) lock)->lock_monitor); - free((char *) lock); + dprintf(("PyThread_free_lock(%p) called\n", lock)); + mon_destroy(((struct lock *) lock)->lock_monitor); + free((char *) lock); } int PyThread_acquire_lock(PyThread_type_lock lock, int waitflag) { - int success; + int success; - dprintf(("PyThread_acquire_lock(%p, %d) called\n", lock, waitflag)); - success = 0; + dprintf(("PyThread_acquire_lock(%p, %d) called\n", lock, waitflag)); + success = 0; - (void) mon_enter(((struct lock *) lock)->lock_monitor); - if (waitflag) - while (((struct lock *) lock)->lock_locked) - cv_wait(((struct lock *) lock)->lock_condvar); - if (!((struct lock *) lock)->lock_locked) { - success = 1; - ((struct lock *) lock)->lock_locked = 1; - } - cv_broadcast(((struct lock *) lock)->lock_condvar); - mon_exit(((struct lock *) lock)->lock_monitor); - dprintf(("PyThread_acquire_lock(%p, %d) -> %d\n", lock, waitflag, success)); - return success; + (void) mon_enter(((struct lock *) lock)->lock_monitor); + if (waitflag) + while (((struct lock *) lock)->lock_locked) + cv_wait(((struct lock *) lock)->lock_condvar); + if (!((struct lock *) lock)->lock_locked) { + success = 1; + ((struct lock *) lock)->lock_locked = 1; + } + cv_broadcast(((struct lock *) lock)->lock_condvar); + mon_exit(((struct lock *) lock)->lock_monitor); + dprintf(("PyThread_acquire_lock(%p, %d) -> %d\n", lock, waitflag, success)); + return success; } void PyThread_release_lock(PyThread_type_lock lock) { - dprintf(("PyThread_release_lock(%p) called\n", lock)); - (void) mon_enter(((struct lock *) lock)->lock_monitor); - ((struct lock *) lock)->lock_locked = 0; - cv_broadcast(((struct lock *) lock)->lock_condvar); - mon_exit(((struct lock *) lock)->lock_monitor); + dprintf(("PyThread_release_lock(%p) called\n", lock)); + (void) mon_enter(((struct lock *) lock)->lock_monitor); + ((struct lock *) lock)->lock_locked = 0; + cv_broadcast(((struct lock *) lock)->lock_condvar); + mon_exit(((struct lock *) lock)->lock_monitor); } Modified: python/branches/py3k/Python/thread_nt.h ============================================================================== --- python/branches/py3k/Python/thread_nt.h (original) +++ python/branches/py3k/Python/thread_nt.h Sun May 9 17:52:27 2010 @@ -10,81 +10,81 @@ #endif typedef struct NRMUTEX { - LONG owned ; - DWORD thread_id ; - HANDLE hevent ; + LONG owned ; + DWORD thread_id ; + HANDLE hevent ; } NRMUTEX, *PNRMUTEX ; BOOL InitializeNonRecursiveMutex(PNRMUTEX mutex) { - mutex->owned = -1 ; /* No threads have entered NonRecursiveMutex */ - mutex->thread_id = 0 ; - mutex->hevent = CreateEvent(NULL, FALSE, FALSE, NULL) ; - return mutex->hevent != NULL ; /* TRUE if the mutex is created */ + mutex->owned = -1 ; /* No threads have entered NonRecursiveMutex */ + mutex->thread_id = 0 ; + mutex->hevent = CreateEvent(NULL, FALSE, FALSE, NULL) ; + return mutex->hevent != NULL ; /* TRUE if the mutex is created */ } VOID DeleteNonRecursiveMutex(PNRMUTEX mutex) { - /* No in-use check */ - CloseHandle(mutex->hevent) ; - mutex->hevent = NULL ; /* Just in case */ + /* No in-use check */ + CloseHandle(mutex->hevent) ; + mutex->hevent = NULL ; /* Just in case */ } DWORD EnterNonRecursiveMutex(PNRMUTEX mutex, DWORD milliseconds) { - /* Assume that the thread waits successfully */ - DWORD ret ; + /* Assume that the thread waits successfully */ + DWORD ret ; - /* InterlockedIncrement(&mutex->owned) == 0 means that no thread currently owns the mutex */ - if (milliseconds == 0) - { - if (InterlockedCompareExchange(&mutex->owned, 0, -1) != -1) - return WAIT_TIMEOUT ; - ret = WAIT_OBJECT_0 ; - } - else - ret = InterlockedIncrement(&mutex->owned) ? - /* Some thread owns the mutex, let's wait... */ - WaitForSingleObject(mutex->hevent, milliseconds) : WAIT_OBJECT_0 ; + /* InterlockedIncrement(&mutex->owned) == 0 means that no thread currently owns the mutex */ + if (milliseconds == 0) + { + if (InterlockedCompareExchange(&mutex->owned, 0, -1) != -1) + return WAIT_TIMEOUT ; + ret = WAIT_OBJECT_0 ; + } + else + ret = InterlockedIncrement(&mutex->owned) ? + /* Some thread owns the mutex, let's wait... */ + WaitForSingleObject(mutex->hevent, milliseconds) : WAIT_OBJECT_0 ; - mutex->thread_id = GetCurrentThreadId() ; /* We own it */ - return ret ; + mutex->thread_id = GetCurrentThreadId() ; /* We own it */ + return ret ; } BOOL LeaveNonRecursiveMutex(PNRMUTEX mutex) { - /* We don't own the mutex */ - mutex->thread_id = 0 ; - return - InterlockedDecrement(&mutex->owned) < 0 || - SetEvent(mutex->hevent) ; /* Other threads are waiting, wake one on them up */ + /* We don't own the mutex */ + mutex->thread_id = 0 ; + return + InterlockedDecrement(&mutex->owned) < 0 || + SetEvent(mutex->hevent) ; /* Other threads are waiting, wake one on them up */ } PNRMUTEX AllocNonRecursiveMutex(void) { - PNRMUTEX mutex = (PNRMUTEX)malloc(sizeof(NRMUTEX)) ; - if (mutex && !InitializeNonRecursiveMutex(mutex)) - { - free(mutex) ; - mutex = NULL ; - } - return mutex ; + PNRMUTEX mutex = (PNRMUTEX)malloc(sizeof(NRMUTEX)) ; + if (mutex && !InitializeNonRecursiveMutex(mutex)) + { + free(mutex) ; + mutex = NULL ; + } + return mutex ; } void FreeNonRecursiveMutex(PNRMUTEX mutex) { - if (mutex) - { - DeleteNonRecursiveMutex(mutex) ; - free(mutex) ; - } + if (mutex) + { + DeleteNonRecursiveMutex(mutex) ; + free(mutex) ; + } } long PyThread_get_thread_ident(void); @@ -102,8 +102,8 @@ */ typedef struct { - void (*func)(void*); - void *arg; + void (*func)(void*); + void *arg; } callobj; /* thunker to call adapt between the function type used by the system's @@ -115,66 +115,66 @@ #endif bootstrap(void *call) { - callobj *obj = (callobj*)call; - void (*func)(void*) = obj->func; - void *arg = obj->arg; - HeapFree(GetProcessHeap(), 0, obj); - func(arg); - return 0; + callobj *obj = (callobj*)call; + void (*func)(void*) = obj->func; + void *arg = obj->arg; + HeapFree(GetProcessHeap(), 0, obj); + func(arg); + return 0; } long PyThread_start_new_thread(void (*func)(void *), void *arg) { - HANDLE hThread; - unsigned threadID; - callobj *obj; - - dprintf(("%ld: PyThread_start_new_thread called\n", - PyThread_get_thread_ident())); - if (!initialized) - PyThread_init_thread(); - - obj = (callobj*)HeapAlloc(GetProcessHeap(), 0, sizeof(*obj)); - if (!obj) - return -1; - obj->func = func; - obj->arg = arg; + HANDLE hThread; + unsigned threadID; + callobj *obj; + + dprintf(("%ld: PyThread_start_new_thread called\n", + PyThread_get_thread_ident())); + if (!initialized) + PyThread_init_thread(); + + obj = (callobj*)HeapAlloc(GetProcessHeap(), 0, sizeof(*obj)); + if (!obj) + return -1; + obj->func = func; + obj->arg = arg; #if defined(MS_WINCE) - hThread = CreateThread(NULL, - Py_SAFE_DOWNCAST(_pythread_stacksize, Py_ssize_t, SIZE_T), - bootstrap, obj, 0, &threadID); + hThread = CreateThread(NULL, + Py_SAFE_DOWNCAST(_pythread_stacksize, Py_ssize_t, SIZE_T), + bootstrap, obj, 0, &threadID); #else - hThread = (HANDLE)_beginthreadex(0, - Py_SAFE_DOWNCAST(_pythread_stacksize, - Py_ssize_t, unsigned int), - bootstrap, obj, - 0, &threadID); + hThread = (HANDLE)_beginthreadex(0, + Py_SAFE_DOWNCAST(_pythread_stacksize, + Py_ssize_t, unsigned int), + bootstrap, obj, + 0, &threadID); #endif - if (hThread == 0) { + if (hThread == 0) { #if defined(MS_WINCE) - /* Save error in variable, to prevent PyThread_get_thread_ident - from clobbering it. */ - unsigned e = GetLastError(); - dprintf(("%ld: PyThread_start_new_thread failed, win32 error code %u\n", - PyThread_get_thread_ident(), e)); + /* Save error in variable, to prevent PyThread_get_thread_ident + from clobbering it. */ + unsigned e = GetLastError(); + dprintf(("%ld: PyThread_start_new_thread failed, win32 error code %u\n", + PyThread_get_thread_ident(), e)); #else - /* I've seen errno == EAGAIN here, which means "there are - * too many threads". - */ - int e = errno; - dprintf(("%ld: PyThread_start_new_thread failed, errno %d\n", - PyThread_get_thread_ident(), e)); + /* I've seen errno == EAGAIN here, which means "there are + * too many threads". + */ + int e = errno; + dprintf(("%ld: PyThread_start_new_thread failed, errno %d\n", + PyThread_get_thread_ident(), e)); #endif - threadID = (unsigned)-1; - HeapFree(GetProcessHeap(), 0, obj); - } - else { - dprintf(("%ld: PyThread_start_new_thread succeeded: %p\n", - PyThread_get_thread_ident(), (void*)hThread)); - CloseHandle(hThread); - } - return (long) threadID; + threadID = (unsigned)-1; + HeapFree(GetProcessHeap(), 0, obj); + } + else { + dprintf(("%ld: PyThread_start_new_thread succeeded: %p\n", + PyThread_get_thread_ident(), (void*)hThread)); + CloseHandle(hThread); + } + return (long) threadID; } /* @@ -184,22 +184,22 @@ long PyThread_get_thread_ident(void) { - if (!initialized) - PyThread_init_thread(); + if (!initialized) + PyThread_init_thread(); - return GetCurrentThreadId(); + return GetCurrentThreadId(); } void PyThread_exit_thread(void) { - dprintf(("%ld: PyThread_exit_thread called\n", PyThread_get_thread_ident())); - if (!initialized) - exit(0); + dprintf(("%ld: PyThread_exit_thread called\n", PyThread_get_thread_ident())); + if (!initialized) + exit(0); #if defined(MS_WINCE) - ExitThread(0); + ExitThread(0); #else - _endthreadex(0); + _endthreadex(0); #endif } @@ -211,25 +211,25 @@ PyThread_type_lock PyThread_allocate_lock(void) { - PNRMUTEX aLock; + PNRMUTEX aLock; - dprintf(("PyThread_allocate_lock called\n")); - if (!initialized) - PyThread_init_thread(); + dprintf(("PyThread_allocate_lock called\n")); + if (!initialized) + PyThread_init_thread(); - aLock = AllocNonRecursiveMutex() ; + aLock = AllocNonRecursiveMutex() ; - dprintf(("%ld: PyThread_allocate_lock() -> %p\n", PyThread_get_thread_ident(), aLock)); + dprintf(("%ld: PyThread_allocate_lock() -> %p\n", PyThread_get_thread_ident(), aLock)); - return (PyThread_type_lock) aLock; + return (PyThread_type_lock) aLock; } void PyThread_free_lock(PyThread_type_lock aLock) { - dprintf(("%ld: PyThread_free_lock(%p) called\n", PyThread_get_thread_ident(),aLock)); + dprintf(("%ld: PyThread_free_lock(%p) called\n", PyThread_get_thread_ident(),aLock)); - FreeNonRecursiveMutex(aLock) ; + FreeNonRecursiveMutex(aLock) ; } /* @@ -241,48 +241,48 @@ int PyThread_acquire_lock_timed(PyThread_type_lock aLock, PY_TIMEOUT_T microseconds) { - int success ; - PY_TIMEOUT_T milliseconds; + int success ; + PY_TIMEOUT_T milliseconds; - if (microseconds >= 0) { - milliseconds = microseconds / 1000; - if (microseconds % 1000 > 0) - ++milliseconds; - if ((DWORD) milliseconds != milliseconds) - Py_FatalError("Timeout too large for a DWORD, " - "please check PY_TIMEOUT_MAX"); - } - else - milliseconds = INFINITE; - - dprintf(("%ld: PyThread_acquire_lock_timed(%p, %lld) called\n", - PyThread_get_thread_ident(), aLock, microseconds)); + if (microseconds >= 0) { + milliseconds = microseconds / 1000; + if (microseconds % 1000 > 0) + ++milliseconds; + if ((DWORD) milliseconds != milliseconds) + Py_FatalError("Timeout too large for a DWORD, " + "please check PY_TIMEOUT_MAX"); + } + else + milliseconds = INFINITE; + + dprintf(("%ld: PyThread_acquire_lock_timed(%p, %lld) called\n", + PyThread_get_thread_ident(), aLock, microseconds)); - success = aLock && EnterNonRecursiveMutex((PNRMUTEX) aLock, (DWORD) milliseconds) == WAIT_OBJECT_0 ; + success = aLock && EnterNonRecursiveMutex((PNRMUTEX) aLock, (DWORD) milliseconds) == WAIT_OBJECT_0 ; - dprintf(("%ld: PyThread_acquire_lock(%p, %lld) -> %d\n", - PyThread_get_thread_ident(), aLock, microseconds, success)); + dprintf(("%ld: PyThread_acquire_lock(%p, %lld) -> %d\n", + PyThread_get_thread_ident(), aLock, microseconds, success)); - return success; + return success; } int PyThread_acquire_lock(PyThread_type_lock aLock, int waitflag) { - return PyThread_acquire_lock_timed(aLock, waitflag ? -1 : 0); + return PyThread_acquire_lock_timed(aLock, waitflag ? -1 : 0); } void PyThread_release_lock(PyThread_type_lock aLock) { - dprintf(("%ld: PyThread_release_lock(%p) called\n", PyThread_get_thread_ident(),aLock)); + dprintf(("%ld: PyThread_release_lock(%p) called\n", PyThread_get_thread_ident(),aLock)); - if (!(aLock && LeaveNonRecursiveMutex((PNRMUTEX) aLock))) - dprintf(("%ld: Could not PyThread_release_lock(%p) error: %ld\n", PyThread_get_thread_ident(), aLock, GetLastError())); + if (!(aLock && LeaveNonRecursiveMutex((PNRMUTEX) aLock))) + dprintf(("%ld: Could not PyThread_release_lock(%p) error: %ld\n", PyThread_get_thread_ident(), aLock, GetLastError())); } /* minimum/maximum thread stack sizes supported */ -#define THREAD_MIN_STACKSIZE 0x8000 /* 32kB */ -#define THREAD_MAX_STACKSIZE 0x10000000 /* 256MB */ +#define THREAD_MIN_STACKSIZE 0x8000 /* 32kB */ +#define THREAD_MAX_STACKSIZE 0x10000000 /* 256MB */ /* set the thread stack size. * Return 0 if size is valid, -1 otherwise. @@ -290,22 +290,22 @@ static int _pythread_nt_set_stacksize(size_t size) { - /* set to default */ - if (size == 0) { - _pythread_stacksize = 0; - return 0; - } - - /* valid range? */ - if (size >= THREAD_MIN_STACKSIZE && size < THREAD_MAX_STACKSIZE) { - _pythread_stacksize = size; - return 0; - } + /* set to default */ + if (size == 0) { + _pythread_stacksize = 0; + return 0; + } + + /* valid range? */ + if (size >= THREAD_MIN_STACKSIZE && size < THREAD_MAX_STACKSIZE) { + _pythread_stacksize = size; + return 0; + } - return -1; + return -1; } -#define THREAD_SET_STACKSIZE(x) _pythread_nt_set_stacksize(x) +#define THREAD_SET_STACKSIZE(x) _pythread_nt_set_stacksize(x) /* use native Windows TLS functions */ @@ -315,13 +315,13 @@ int PyThread_create_key(void) { - return (int) TlsAlloc(); + return (int) TlsAlloc(); } void PyThread_delete_key(int key) { - TlsFree(key); + TlsFree(key); } /* We must be careful to emulate the strange semantics implemented in thread.c, @@ -330,42 +330,42 @@ int PyThread_set_key_value(int key, void *value) { - BOOL ok; - void *oldvalue; + BOOL ok; + void *oldvalue; - assert(value != NULL); - oldvalue = TlsGetValue(key); - if (oldvalue != NULL) - /* ignore value if already set */ - return 0; - ok = TlsSetValue(key, value); - if (!ok) - return -1; - return 0; + assert(value != NULL); + oldvalue = TlsGetValue(key); + if (oldvalue != NULL) + /* ignore value if already set */ + return 0; + ok = TlsSetValue(key, value); + if (!ok) + return -1; + return 0; } void * PyThread_get_key_value(int key) { - /* because TLS is used in the Py_END_ALLOW_THREAD macro, - * it is necessary to preserve the windows error state, because - * it is assumed to be preserved across the call to the macro. - * Ideally, the macro should be fixed, but it is simpler to - * do it here. - */ - DWORD error = GetLastError(); - void *result = TlsGetValue(key); - SetLastError(error); - return result; + /* because TLS is used in the Py_END_ALLOW_THREAD macro, + * it is necessary to preserve the windows error state, because + * it is assumed to be preserved across the call to the macro. + * Ideally, the macro should be fixed, but it is simpler to + * do it here. + */ + DWORD error = GetLastError(); + void *result = TlsGetValue(key); + SetLastError(error); + return result; } void PyThread_delete_key_value(int key) { - /* NULL is used as "key missing", and it is also the default - * given by TlsGetValue() if nothing has been set yet. - */ - TlsSetValue(key, NULL); + /* NULL is used as "key missing", and it is also the default + * given by TlsGetValue() if nothing has been set yet. + */ + TlsSetValue(key, NULL); } /* reinitialization of TLS is not necessary after fork when using Modified: python/branches/py3k/Python/thread_os2.h ============================================================================== --- python/branches/py3k/Python/thread_os2.h (original) +++ python/branches/py3k/Python/thread_os2.h Sun May 9 17:52:27 2010 @@ -16,10 +16,10 @@ /* default thread stack size of 64kB */ #if !defined(THREAD_STACK_SIZE) -#define THREAD_STACK_SIZE 0x10000 +#define THREAD_STACK_SIZE 0x10000 #endif -#define OS2_STACKSIZE(x) (x ? x : THREAD_STACK_SIZE) +#define OS2_STACKSIZE(x) (x ? x : THREAD_STACK_SIZE) /* * Initialization of the C package, should not be needed. @@ -35,113 +35,113 @@ long PyThread_start_new_thread(void (*func)(void *), void *arg) { - int thread_id; + int thread_id; - thread_id = _beginthread(func, - NULL, - OS2_STACKSIZE(_pythread_stacksize), - arg); - - if (thread_id == -1) { - dprintf(("_beginthread failed. return %ld\n", errno)); - } + thread_id = _beginthread(func, + NULL, + OS2_STACKSIZE(_pythread_stacksize), + arg); + + if (thread_id == -1) { + dprintf(("_beginthread failed. return %ld\n", errno)); + } - return thread_id; + return thread_id; } long PyThread_get_thread_ident(void) { #if !defined(PYCC_GCC) - PPIB pib; - PTIB tib; + PPIB pib; + PTIB tib; #endif - if (!initialized) - PyThread_init_thread(); + if (!initialized) + PyThread_init_thread(); #if defined(PYCC_GCC) - return _gettid(); + return _gettid(); #else - DosGetInfoBlocks(&tib, &pib); - return tib->tib_ptib2->tib2_ultid; + DosGetInfoBlocks(&tib, &pib); + return tib->tib_ptib2->tib2_ultid; #endif } void PyThread_exit_thread(void) { - dprintf(("%ld: PyThread_exit_thread called\n", - PyThread_get_thread_ident())); - if (!initialized) - exit(0); - _endthread(); + dprintf(("%ld: PyThread_exit_thread called\n", + PyThread_get_thread_ident())); + if (!initialized) + exit(0); + _endthread(); } /* * Lock support. This is implemented with an event semaphore and critical - * sections to make it behave more like a posix mutex than its OS/2 + * sections to make it behave more like a posix mutex than its OS/2 * counterparts. */ typedef struct os2_lock_t { - int is_set; - HEV changed; + int is_set; + HEV changed; } *type_os2_lock; -PyThread_type_lock +PyThread_type_lock PyThread_allocate_lock(void) { #if defined(PYCC_GCC) - _fmutex *sem = malloc(sizeof(_fmutex)); - if (!initialized) - PyThread_init_thread(); - dprintf(("%ld: PyThread_allocate_lock() -> %lx\n", - PyThread_get_thread_ident(), - (long)sem)); - if (_fmutex_create(sem, 0)) { - free(sem); - sem = NULL; - } - return (PyThread_type_lock)sem; + _fmutex *sem = malloc(sizeof(_fmutex)); + if (!initialized) + PyThread_init_thread(); + dprintf(("%ld: PyThread_allocate_lock() -> %lx\n", + PyThread_get_thread_ident(), + (long)sem)); + if (_fmutex_create(sem, 0)) { + free(sem); + sem = NULL; + } + return (PyThread_type_lock)sem; #else - APIRET rc; - type_os2_lock lock = (type_os2_lock)malloc(sizeof(struct os2_lock_t)); + APIRET rc; + type_os2_lock lock = (type_os2_lock)malloc(sizeof(struct os2_lock_t)); - dprintf(("PyThread_allocate_lock called\n")); - if (!initialized) - PyThread_init_thread(); + dprintf(("PyThread_allocate_lock called\n")); + if (!initialized) + PyThread_init_thread(); - lock->is_set = 0; + lock->is_set = 0; - DosCreateEventSem(NULL, &lock->changed, 0, 0); + DosCreateEventSem(NULL, &lock->changed, 0, 0); - dprintf(("%ld: PyThread_allocate_lock() -> %p\n", - PyThread_get_thread_ident(), - lock->changed)); + dprintf(("%ld: PyThread_allocate_lock() -> %p\n", + PyThread_get_thread_ident(), + lock->changed)); - return (PyThread_type_lock)lock; + return (PyThread_type_lock)lock; #endif } -void +void PyThread_free_lock(PyThread_type_lock aLock) { #if !defined(PYCC_GCC) - type_os2_lock lock = (type_os2_lock)aLock; + type_os2_lock lock = (type_os2_lock)aLock; #endif - dprintf(("%ld: PyThread_free_lock(%p) called\n", - PyThread_get_thread_ident(),aLock)); + dprintf(("%ld: PyThread_free_lock(%p) called\n", + PyThread_get_thread_ident(),aLock)); #if defined(PYCC_GCC) - if (aLock) { - _fmutex_close((_fmutex *)aLock); - free((_fmutex *)aLock); - } + if (aLock) { + _fmutex_close((_fmutex *)aLock); + free((_fmutex *)aLock); + } #else - DosCloseEventSem(lock->changed); - free(aLock); + DosCloseEventSem(lock->changed); + free(aLock); #endif } @@ -150,98 +150,98 @@ * * and 0 if the lock was not acquired. */ -int +int PyThread_acquire_lock(PyThread_type_lock aLock, int waitflag) { #if !defined(PYCC_GCC) - int done = 0; - ULONG count; - PID pid = 0; - TID tid = 0; - type_os2_lock lock = (type_os2_lock)aLock; + int done = 0; + ULONG count; + PID pid = 0; + TID tid = 0; + type_os2_lock lock = (type_os2_lock)aLock; #endif - dprintf(("%ld: PyThread_acquire_lock(%p, %d) called\n", - PyThread_get_thread_ident(), - aLock, - waitflag)); + dprintf(("%ld: PyThread_acquire_lock(%p, %d) called\n", + PyThread_get_thread_ident(), + aLock, + waitflag)); #if defined(PYCC_GCC) - /* always successful if the lock doesn't exist */ - if (aLock && - _fmutex_request((_fmutex *)aLock, waitflag ? 0 : _FMR_NOWAIT)) - return 0; + /* always successful if the lock doesn't exist */ + if (aLock && + _fmutex_request((_fmutex *)aLock, waitflag ? 0 : _FMR_NOWAIT)) + return 0; #else - while (!done) { - /* if the lock is currently set, we have to wait for - * the state to change - */ - if (lock->is_set) { - if (!waitflag) - return 0; - DosWaitEventSem(lock->changed, SEM_INDEFINITE_WAIT); - } - - /* enter a critical section and try to get the semaphore. If - * it is still locked, we will try again. - */ - if (DosEnterCritSec()) - return 0; - - if (!lock->is_set) { - lock->is_set = 1; - DosResetEventSem(lock->changed, &count); - done = 1; - } + while (!done) { + /* if the lock is currently set, we have to wait for + * the state to change + */ + if (lock->is_set) { + if (!waitflag) + return 0; + DosWaitEventSem(lock->changed, SEM_INDEFINITE_WAIT); + } + + /* enter a critical section and try to get the semaphore. If + * it is still locked, we will try again. + */ + if (DosEnterCritSec()) + return 0; + + if (!lock->is_set) { + lock->is_set = 1; + DosResetEventSem(lock->changed, &count); + done = 1; + } - DosExitCritSec(); - } + DosExitCritSec(); + } #endif - return 1; + return 1; } void PyThread_release_lock(PyThread_type_lock aLock) { #if !defined(PYCC_GCC) - type_os2_lock lock = (type_os2_lock)aLock; + type_os2_lock lock = (type_os2_lock)aLock; #endif - dprintf(("%ld: PyThread_release_lock(%p) called\n", - PyThread_get_thread_ident(), - aLock)); + dprintf(("%ld: PyThread_release_lock(%p) called\n", + PyThread_get_thread_ident(), + aLock)); #if defined(PYCC_GCC) - if (aLock) - _fmutex_release((_fmutex *)aLock); + if (aLock) + _fmutex_release((_fmutex *)aLock); #else - if (!lock->is_set) { - dprintf(("%ld: Could not PyThread_release_lock(%p) error: %l\n", - PyThread_get_thread_ident(), - aLock, - GetLastError())); - return; - } - - if (DosEnterCritSec()) { - dprintf(("%ld: Could not PyThread_release_lock(%p) error: %l\n", - PyThread_get_thread_ident(), - aLock, - GetLastError())); - return; - } + if (!lock->is_set) { + dprintf(("%ld: Could not PyThread_release_lock(%p) error: %l\n", + PyThread_get_thread_ident(), + aLock, + GetLastError())); + return; + } + + if (DosEnterCritSec()) { + dprintf(("%ld: Could not PyThread_release_lock(%p) error: %l\n", + PyThread_get_thread_ident(), + aLock, + GetLastError())); + return; + } - lock->is_set = 0; - DosPostEventSem(lock->changed); + lock->is_set = 0; + DosPostEventSem(lock->changed); - DosExitCritSec(); + DosExitCritSec(); #endif } /* minimum/maximum thread stack sizes supported */ -#define THREAD_MIN_STACKSIZE 0x8000 /* 32kB */ -#define THREAD_MAX_STACKSIZE 0x2000000 /* 32MB */ +#define THREAD_MIN_STACKSIZE 0x8000 /* 32kB */ +#define THREAD_MAX_STACKSIZE 0x2000000 /* 32MB */ /* set the thread stack size. * Return 0 if size is valid, -1 otherwise. @@ -249,19 +249,19 @@ static int _pythread_os2_set_stacksize(size_t size) { - /* set to default */ - if (size == 0) { - _pythread_stacksize = 0; - return 0; - } - - /* valid range? */ - if (size >= THREAD_MIN_STACKSIZE && size < THREAD_MAX_STACKSIZE) { - _pythread_stacksize = size; - return 0; - } + /* set to default */ + if (size == 0) { + _pythread_stacksize = 0; + return 0; + } + + /* valid range? */ + if (size >= THREAD_MIN_STACKSIZE && size < THREAD_MAX_STACKSIZE) { + _pythread_stacksize = size; + return 0; + } - return -1; + return -1; } -#define THREAD_SET_STACKSIZE(x) _pythread_os2_set_stacksize(x) +#define THREAD_SET_STACKSIZE(x) _pythread_os2_set_stacksize(x) Modified: python/branches/py3k/Python/thread_pth.h ============================================================================== --- python/branches/py3k/Python/thread_pth.h (original) +++ python/branches/py3k/Python/thread_pth.h Sun May 9 17:52:27 2010 @@ -3,7 +3,7 @@ http://www.gnu.org/software/pth 2000-05-03 Andy Dustman - Adapted from Posix threads interface + Adapted from Posix threads interface 12 May 1997 -- david arnold */ @@ -22,10 +22,10 @@ */ typedef struct { - char locked; /* 0=unlocked, 1=locked */ - /* a pair to handle an acquire of a locked lock */ - pth_cond_t lock_released; - pth_mutex_t mut; + char locked; /* 0=unlocked, 1=locked */ + /* a pair to handle an acquire of a locked lock */ + pth_cond_t lock_released; + pth_mutex_t mut; } pth_lock; #define CHECK_STATUS(name) if (status == -1) { printf("%d ", status); perror(name); error = 1; } @@ -38,10 +38,10 @@ static void PyThread__init_thread(void) { - pth_init(); - PyThread_attr = pth_attr_new(); - pth_attr_set(PyThread_attr, PTH_ATTR_STACK_SIZE, 1<<18); - pth_attr_set(PyThread_attr, PTH_ATTR_JOINABLE, FALSE); + pth_init(); + PyThread_attr = pth_attr_new(); + pth_attr_set(PyThread_attr, PTH_ATTR_STACK_SIZE, 1<<18); + pth_attr_set(PyThread_attr, PTH_ATTR_JOINABLE, FALSE); } /* @@ -51,35 +51,35 @@ long PyThread_start_new_thread(void (*func)(void *), void *arg) { - pth_t th; - dprintf(("PyThread_start_new_thread called\n")); - if (!initialized) - PyThread_init_thread(); - - th = pth_spawn(PyThread_attr, - (void* (*)(void *))func, - (void *)arg - ); + pth_t th; + dprintf(("PyThread_start_new_thread called\n")); + if (!initialized) + PyThread_init_thread(); + + th = pth_spawn(PyThread_attr, + (void* (*)(void *))func, + (void *)arg + ); - return th; + return th; } long PyThread_get_thread_ident(void) { - volatile pth_t threadid; - if (!initialized) - PyThread_init_thread(); - /* Jump through some hoops for Alpha OSF/1 */ - threadid = pth_self(); - return (long) *(long *) &threadid; + volatile pth_t threadid; + if (!initialized) + PyThread_init_thread(); + /* Jump through some hoops for Alpha OSF/1 */ + threadid = pth_self(); + return (long) *(long *) &threadid; } void PyThread_exit_thread(void) { - dprintf(("PyThread_exit_thread called\n")); - if (!initialized) { - exit(0); - } + dprintf(("PyThread_exit_thread called\n")); + if (!initialized) { + exit(0); + } } /* @@ -87,92 +87,92 @@ */ PyThread_type_lock PyThread_allocate_lock(void) { - pth_lock *lock; - int status, error = 0; + pth_lock *lock; + int status, error = 0; - dprintf(("PyThread_allocate_lock called\n")); - if (!initialized) - PyThread_init_thread(); - - lock = (pth_lock *) malloc(sizeof(pth_lock)); - memset((void *)lock, '\0', sizeof(pth_lock)); - if (lock) { - lock->locked = 0; - status = pth_mutex_init(&lock->mut); - CHECK_STATUS("pth_mutex_init"); - status = pth_cond_init(&lock->lock_released); - CHECK_STATUS("pth_cond_init"); - if (error) { - free((void *)lock); - lock = NULL; - } - } - dprintf(("PyThread_allocate_lock() -> %p\n", lock)); - return (PyThread_type_lock) lock; + dprintf(("PyThread_allocate_lock called\n")); + if (!initialized) + PyThread_init_thread(); + + lock = (pth_lock *) malloc(sizeof(pth_lock)); + memset((void *)lock, '\0', sizeof(pth_lock)); + if (lock) { + lock->locked = 0; + status = pth_mutex_init(&lock->mut); + CHECK_STATUS("pth_mutex_init"); + status = pth_cond_init(&lock->lock_released); + CHECK_STATUS("pth_cond_init"); + if (error) { + free((void *)lock); + lock = NULL; + } + } + dprintf(("PyThread_allocate_lock() -> %p\n", lock)); + return (PyThread_type_lock) lock; } void PyThread_free_lock(PyThread_type_lock lock) { - pth_lock *thelock = (pth_lock *)lock; + pth_lock *thelock = (pth_lock *)lock; - dprintf(("PyThread_free_lock(%p) called\n", lock)); + dprintf(("PyThread_free_lock(%p) called\n", lock)); - free((void *)thelock); + free((void *)thelock); } int PyThread_acquire_lock(PyThread_type_lock lock, int waitflag) { - int success; - pth_lock *thelock = (pth_lock *)lock; - int status, error = 0; - - dprintf(("PyThread_acquire_lock(%p, %d) called\n", lock, waitflag)); - - status = pth_mutex_acquire(&thelock->mut, !waitflag, NULL); - CHECK_STATUS("pth_mutex_acquire[1]"); - success = thelock->locked == 0; - if (success) thelock->locked = 1; - status = pth_mutex_release( &thelock->mut ); - CHECK_STATUS("pth_mutex_release[1]"); - - if ( !success && waitflag ) { - /* continue trying until we get the lock */ - - /* mut must be locked by me -- part of the condition - * protocol */ - status = pth_mutex_acquire( &thelock->mut, !waitflag, NULL ); - CHECK_STATUS("pth_mutex_acquire[2]"); - while ( thelock->locked ) { - status = pth_cond_await(&thelock->lock_released, - &thelock->mut, NULL); - CHECK_STATUS("pth_cond_await"); - } - thelock->locked = 1; - status = pth_mutex_release( &thelock->mut ); - CHECK_STATUS("pth_mutex_release[2]"); - success = 1; + int success; + pth_lock *thelock = (pth_lock *)lock; + int status, error = 0; + + dprintf(("PyThread_acquire_lock(%p, %d) called\n", lock, waitflag)); + + status = pth_mutex_acquire(&thelock->mut, !waitflag, NULL); + CHECK_STATUS("pth_mutex_acquire[1]"); + success = thelock->locked == 0; + if (success) thelock->locked = 1; + status = pth_mutex_release( &thelock->mut ); + CHECK_STATUS("pth_mutex_release[1]"); + + if ( !success && waitflag ) { + /* continue trying until we get the lock */ + + /* mut must be locked by me -- part of the condition + * protocol */ + status = pth_mutex_acquire( &thelock->mut, !waitflag, NULL ); + CHECK_STATUS("pth_mutex_acquire[2]"); + while ( thelock->locked ) { + status = pth_cond_await(&thelock->lock_released, + &thelock->mut, NULL); + CHECK_STATUS("pth_cond_await"); } - if (error) success = 0; - dprintf(("PyThread_acquire_lock(%p, %d) -> %d\n", lock, waitflag, success)); - return success; + thelock->locked = 1; + status = pth_mutex_release( &thelock->mut ); + CHECK_STATUS("pth_mutex_release[2]"); + success = 1; + } + if (error) success = 0; + dprintf(("PyThread_acquire_lock(%p, %d) -> %d\n", lock, waitflag, success)); + return success; } void PyThread_release_lock(PyThread_type_lock lock) { - pth_lock *thelock = (pth_lock *)lock; - int status, error = 0; + pth_lock *thelock = (pth_lock *)lock; + int status, error = 0; - dprintf(("PyThread_release_lock(%p) called\n", lock)); + dprintf(("PyThread_release_lock(%p) called\n", lock)); - status = pth_mutex_acquire( &thelock->mut, 0, NULL ); - CHECK_STATUS("pth_mutex_acquire[3]"); + status = pth_mutex_acquire( &thelock->mut, 0, NULL ); + CHECK_STATUS("pth_mutex_acquire[3]"); - thelock->locked = 0; + thelock->locked = 0; - status = pth_mutex_release( &thelock->mut ); - CHECK_STATUS("pth_mutex_release[3]"); + status = pth_mutex_release( &thelock->mut ); + CHECK_STATUS("pth_mutex_release[3]"); - /* wake up someone (anyone, if any) waiting on the lock */ - status = pth_cond_notify( &thelock->lock_released, 0 ); - CHECK_STATUS("pth_cond_notify"); + /* wake up someone (anyone, if any) waiting on the lock */ + status = pth_cond_notify( &thelock->lock_released, 0 ); + CHECK_STATUS("pth_cond_notify"); } Modified: python/branches/py3k/Python/thread_pthread.h ============================================================================== --- python/branches/py3k/Python/thread_pthread.h (original) +++ python/branches/py3k/Python/thread_pthread.h Sun May 9 17:52:27 2010 @@ -16,10 +16,10 @@ be conditional on _POSIX_THREAD_ATTR_STACKSIZE being defined. */ #ifdef _POSIX_THREAD_ATTR_STACKSIZE #ifndef THREAD_STACK_SIZE -#define THREAD_STACK_SIZE 0 /* use default stack size */ +#define THREAD_STACK_SIZE 0 /* use default stack size */ #endif /* for safety, ensure a viable minimum stacksize */ -#define THREAD_STACK_MIN 0x8000 /* 32kB */ +#define THREAD_STACK_MIN 0x8000 /* 32kB */ #else /* !_POSIX_THREAD_ATTR_STACKSIZE */ #ifdef THREAD_STACK_SIZE #error "THREAD_STACK_SIZE defined but _POSIX_THREAD_ATTR_STACKSIZE undefined" @@ -28,9 +28,9 @@ /* The POSIX spec says that implementations supporting the sem_* family of functions must indicate this by defining - _POSIX_SEMAPHORES. */ + _POSIX_SEMAPHORES. */ #ifdef _POSIX_SEMAPHORES -/* On FreeBSD 4.x, _POSIX_SEMAPHORES is defined empty, so +/* On FreeBSD 4.x, _POSIX_SEMAPHORES is defined empty, so we need to add 0 to make it work there as well. */ #if (_POSIX_SEMAPHORES+0) == -1 #define HAVE_BROKEN_POSIX_SEMAPHORES @@ -92,14 +92,14 @@ #define MICROSECONDS_TO_TIMESPEC(microseconds, ts) \ do { \ - struct timeval tv; \ - GETTIMEOFDAY(&tv); \ - tv.tv_usec += microseconds % 1000000; \ - tv.tv_sec += microseconds / 1000000; \ - tv.tv_sec += tv.tv_usec / 1000000; \ - tv.tv_usec %= 1000000; \ - ts.tv_sec = tv.tv_sec; \ - ts.tv_nsec = tv.tv_usec * 1000; \ + struct timeval tv; \ + GETTIMEOFDAY(&tv); \ + tv.tv_usec += microseconds % 1000000; \ + tv.tv_sec += microseconds / 1000000; \ + tv.tv_sec += tv.tv_usec / 1000000; \ + tv.tv_usec %= 1000000; \ + ts.tv_sec = tv.tv_sec; \ + ts.tv_nsec = tv.tv_usec * 1000; \ } while(0) @@ -119,10 +119,10 @@ */ typedef struct { - char locked; /* 0=unlocked, 1=locked */ - /* a pair to handle an acquire of a locked lock */ - pthread_cond_t lock_released; - pthread_mutex_t mut; + char locked; /* 0=unlocked, 1=locked */ + /* a pair to handle an acquire of a locked lock */ + pthread_cond_t lock_released; + pthread_mutex_t mut; } pthread_lock; #define CHECK_STATUS(name) if (status != 0) { perror(name); error = 1; } @@ -140,11 +140,11 @@ static void PyThread__init_thread(void) { - /* DO AN INIT BY STARTING THE THREAD */ - static int dummy = 0; - pthread_t thread1; - pthread_create(&thread1, NULL, (void *) _noop, &dummy); - pthread_join(thread1, NULL); + /* DO AN INIT BY STARTING THE THREAD */ + static int dummy = 0; + pthread_t thread1; + pthread_create(&thread1, NULL, (void *) _noop, &dummy); + pthread_join(thread1, NULL); } #else /* !_HAVE_BSDI */ @@ -153,7 +153,7 @@ PyThread__init_thread(void) { #if defined(_AIX) && defined(__GNUC__) - pthread_init(); + pthread_init(); #endif } @@ -167,59 +167,59 @@ long PyThread_start_new_thread(void (*func)(void *), void *arg) { - pthread_t th; - int status; + pthread_t th; + int status; #if defined(THREAD_STACK_SIZE) || defined(PTHREAD_SYSTEM_SCHED_SUPPORTED) - pthread_attr_t attrs; + pthread_attr_t attrs; #endif #if defined(THREAD_STACK_SIZE) - size_t tss; + size_t tss; #endif - dprintf(("PyThread_start_new_thread called\n")); - if (!initialized) - PyThread_init_thread(); + dprintf(("PyThread_start_new_thread called\n")); + if (!initialized) + PyThread_init_thread(); #if defined(THREAD_STACK_SIZE) || defined(PTHREAD_SYSTEM_SCHED_SUPPORTED) - if (pthread_attr_init(&attrs) != 0) - return -1; + if (pthread_attr_init(&attrs) != 0) + return -1; #endif #if defined(THREAD_STACK_SIZE) - tss = (_pythread_stacksize != 0) ? _pythread_stacksize - : THREAD_STACK_SIZE; - if (tss != 0) { - if (pthread_attr_setstacksize(&attrs, tss) != 0) { - pthread_attr_destroy(&attrs); - return -1; - } - } + tss = (_pythread_stacksize != 0) ? _pythread_stacksize + : THREAD_STACK_SIZE; + if (tss != 0) { + if (pthread_attr_setstacksize(&attrs, tss) != 0) { + pthread_attr_destroy(&attrs); + return -1; + } + } #endif #if defined(PTHREAD_SYSTEM_SCHED_SUPPORTED) - pthread_attr_setscope(&attrs, PTHREAD_SCOPE_SYSTEM); + pthread_attr_setscope(&attrs, PTHREAD_SCOPE_SYSTEM); #endif - status = pthread_create(&th, + status = pthread_create(&th, #if defined(THREAD_STACK_SIZE) || defined(PTHREAD_SYSTEM_SCHED_SUPPORTED) - &attrs, + &attrs, #else - (pthread_attr_t*)NULL, + (pthread_attr_t*)NULL, #endif - (void* (*)(void *))func, - (void *)arg - ); + (void* (*)(void *))func, + (void *)arg + ); #if defined(THREAD_STACK_SIZE) || defined(PTHREAD_SYSTEM_SCHED_SUPPORTED) - pthread_attr_destroy(&attrs); + pthread_attr_destroy(&attrs); #endif - if (status != 0) - return -1; + if (status != 0) + return -1; - pthread_detach(th); + pthread_detach(th); #if SIZEOF_PTHREAD_T <= SIZEOF_LONG - return (long) th; + return (long) th; #else - return (long) *(long *) &th; + return (long) *(long *) &th; #endif } @@ -230,28 +230,28 @@ - It is not clear that the 'volatile' (for AIX?) and ugly casting in the latter return statement (for Alpha OSF/1) are any longer necessary. */ -long +long PyThread_get_thread_ident(void) { - volatile pthread_t threadid; - if (!initialized) - PyThread_init_thread(); - /* Jump through some hoops for Alpha OSF/1 */ - threadid = pthread_self(); + volatile pthread_t threadid; + if (!initialized) + PyThread_init_thread(); + /* Jump through some hoops for Alpha OSF/1 */ + threadid = pthread_self(); #if SIZEOF_PTHREAD_T <= SIZEOF_LONG - return (long) threadid; + return (long) threadid; #else - return (long) *(long *) &threadid; + return (long) *(long *) &threadid; #endif } -void +void PyThread_exit_thread(void) { - dprintf(("PyThread_exit_thread called\n")); - if (!initialized) { - exit(0); - } + dprintf(("PyThread_exit_thread called\n")); + if (!initialized) { + exit(0); + } } #ifdef USE_SEMAPHORES @@ -260,47 +260,47 @@ * Lock support. */ -PyThread_type_lock +PyThread_type_lock PyThread_allocate_lock(void) { - sem_t *lock; - int status, error = 0; + sem_t *lock; + int status, error = 0; - dprintf(("PyThread_allocate_lock called\n")); - if (!initialized) - PyThread_init_thread(); + dprintf(("PyThread_allocate_lock called\n")); + if (!initialized) + PyThread_init_thread(); - lock = (sem_t *)malloc(sizeof(sem_t)); + lock = (sem_t *)malloc(sizeof(sem_t)); - if (lock) { - status = sem_init(lock,0,1); - CHECK_STATUS("sem_init"); + if (lock) { + status = sem_init(lock,0,1); + CHECK_STATUS("sem_init"); - if (error) { - free((void *)lock); - lock = NULL; - } - } + if (error) { + free((void *)lock); + lock = NULL; + } + } - dprintf(("PyThread_allocate_lock() -> %p\n", lock)); - return (PyThread_type_lock)lock; + dprintf(("PyThread_allocate_lock() -> %p\n", lock)); + return (PyThread_type_lock)lock; } -void +void PyThread_free_lock(PyThread_type_lock lock) { - sem_t *thelock = (sem_t *)lock; - int status, error = 0; + sem_t *thelock = (sem_t *)lock; + int status, error = 0; - dprintf(("PyThread_free_lock(%p) called\n", lock)); + dprintf(("PyThread_free_lock(%p) called\n", lock)); - if (!thelock) - return; + if (!thelock) + return; - status = sem_destroy(thelock); - CHECK_STATUS("sem_destroy"); + status = sem_destroy(thelock); + CHECK_STATUS("sem_destroy"); - free((void *)thelock); + free((void *)thelock); } /* @@ -312,66 +312,66 @@ static int fix_status(int status) { - return (status == -1) ? errno : status; + return (status == -1) ? errno : status; } int PyThread_acquire_lock_timed(PyThread_type_lock lock, PY_TIMEOUT_T microseconds) { - int success; - sem_t *thelock = (sem_t *)lock; - int status, error = 0; - struct timespec ts; - - dprintf(("PyThread_acquire_lock_timed(%p, %lld) called\n", - lock, microseconds)); - - if (microseconds > 0) - MICROSECONDS_TO_TIMESPEC(microseconds, ts); - do { - if (microseconds > 0) - status = fix_status(sem_timedwait(thelock, &ts)); - else if (microseconds == 0) - status = fix_status(sem_trywait(thelock)); - else - status = fix_status(sem_wait(thelock)); - } while (status == EINTR); /* Retry if interrupted by a signal */ - - if (microseconds > 0) { - if (status != ETIMEDOUT) - CHECK_STATUS("sem_timedwait"); - } - else if (microseconds == 0) { - if (status != EAGAIN) - CHECK_STATUS("sem_trywait"); - } - else { - CHECK_STATUS("sem_wait"); - } - - success = (status == 0) ? 1 : 0; - - dprintf(("PyThread_acquire_lock_timed(%p, %lld) -> %d\n", - lock, microseconds, success)); - return success; + int success; + sem_t *thelock = (sem_t *)lock; + int status, error = 0; + struct timespec ts; + + dprintf(("PyThread_acquire_lock_timed(%p, %lld) called\n", + lock, microseconds)); + + if (microseconds > 0) + MICROSECONDS_TO_TIMESPEC(microseconds, ts); + do { + if (microseconds > 0) + status = fix_status(sem_timedwait(thelock, &ts)); + else if (microseconds == 0) + status = fix_status(sem_trywait(thelock)); + else + status = fix_status(sem_wait(thelock)); + } while (status == EINTR); /* Retry if interrupted by a signal */ + + if (microseconds > 0) { + if (status != ETIMEDOUT) + CHECK_STATUS("sem_timedwait"); + } + else if (microseconds == 0) { + if (status != EAGAIN) + CHECK_STATUS("sem_trywait"); + } + else { + CHECK_STATUS("sem_wait"); + } + + success = (status == 0) ? 1 : 0; + + dprintf(("PyThread_acquire_lock_timed(%p, %lld) -> %d\n", + lock, microseconds, success)); + return success; } -int +int PyThread_acquire_lock(PyThread_type_lock lock, int waitflag) { - return PyThread_acquire_lock_timed(lock, waitflag ? -1 : 0); + return PyThread_acquire_lock_timed(lock, waitflag ? -1 : 0); } -void +void PyThread_release_lock(PyThread_type_lock lock) { - sem_t *thelock = (sem_t *)lock; - int status, error = 0; + sem_t *thelock = (sem_t *)lock; + int status, error = 0; - dprintf(("PyThread_release_lock(%p) called\n", lock)); + dprintf(("PyThread_release_lock(%p) called\n", lock)); - status = sem_post(thelock); - CHECK_STATUS("sem_post"); + status = sem_post(thelock); + CHECK_STATUS("sem_post"); } #else /* USE_SEMAPHORES */ @@ -379,137 +379,137 @@ /* * Lock support. */ -PyThread_type_lock +PyThread_type_lock PyThread_allocate_lock(void) { - pthread_lock *lock; - int status, error = 0; + pthread_lock *lock; + int status, error = 0; - dprintf(("PyThread_allocate_lock called\n")); - if (!initialized) - PyThread_init_thread(); - - lock = (pthread_lock *) malloc(sizeof(pthread_lock)); - if (lock) { - memset((void *)lock, '\0', sizeof(pthread_lock)); - lock->locked = 0; - - status = pthread_mutex_init(&lock->mut, - pthread_mutexattr_default); - CHECK_STATUS("pthread_mutex_init"); - /* Mark the pthread mutex underlying a Python mutex as - pure happens-before. We can't simply mark the - Python-level mutex as a mutex because it can be - acquired and released in different threads, which - will cause errors. */ - _Py_ANNOTATE_PURE_HAPPENS_BEFORE_MUTEX(&lock->mut); - - status = pthread_cond_init(&lock->lock_released, - pthread_condattr_default); - CHECK_STATUS("pthread_cond_init"); - - if (error) { - free((void *)lock); - lock = 0; - } - } + dprintf(("PyThread_allocate_lock called\n")); + if (!initialized) + PyThread_init_thread(); + + lock = (pthread_lock *) malloc(sizeof(pthread_lock)); + if (lock) { + memset((void *)lock, '\0', sizeof(pthread_lock)); + lock->locked = 0; + + status = pthread_mutex_init(&lock->mut, + pthread_mutexattr_default); + CHECK_STATUS("pthread_mutex_init"); + /* Mark the pthread mutex underlying a Python mutex as + pure happens-before. We can't simply mark the + Python-level mutex as a mutex because it can be + acquired and released in different threads, which + will cause errors. */ + _Py_ANNOTATE_PURE_HAPPENS_BEFORE_MUTEX(&lock->mut); + + status = pthread_cond_init(&lock->lock_released, + pthread_condattr_default); + CHECK_STATUS("pthread_cond_init"); + + if (error) { + free((void *)lock); + lock = 0; + } + } - dprintf(("PyThread_allocate_lock() -> %p\n", lock)); - return (PyThread_type_lock) lock; + dprintf(("PyThread_allocate_lock() -> %p\n", lock)); + return (PyThread_type_lock) lock; } -void +void PyThread_free_lock(PyThread_type_lock lock) { - pthread_lock *thelock = (pthread_lock *)lock; - int status, error = 0; + pthread_lock *thelock = (pthread_lock *)lock; + int status, error = 0; - dprintf(("PyThread_free_lock(%p) called\n", lock)); + dprintf(("PyThread_free_lock(%p) called\n", lock)); - status = pthread_mutex_destroy( &thelock->mut ); - CHECK_STATUS("pthread_mutex_destroy"); + status = pthread_mutex_destroy( &thelock->mut ); + CHECK_STATUS("pthread_mutex_destroy"); - status = pthread_cond_destroy( &thelock->lock_released ); - CHECK_STATUS("pthread_cond_destroy"); + status = pthread_cond_destroy( &thelock->lock_released ); + CHECK_STATUS("pthread_cond_destroy"); - free((void *)thelock); + free((void *)thelock); } int PyThread_acquire_lock_timed(PyThread_type_lock lock, PY_TIMEOUT_T microseconds) { - int success; - pthread_lock *thelock = (pthread_lock *)lock; - int status, error = 0; - - dprintf(("PyThread_acquire_lock_timed(%p, %lld) called\n", - lock, microseconds)); - - status = pthread_mutex_lock( &thelock->mut ); - CHECK_STATUS("pthread_mutex_lock[1]"); - success = thelock->locked == 0; - - if (!success && microseconds != 0) { - struct timespec ts; - if (microseconds > 0) - MICROSECONDS_TO_TIMESPEC(microseconds, ts); - /* continue trying until we get the lock */ - - /* mut must be locked by me -- part of the condition - * protocol */ - while (thelock->locked) { - if (microseconds > 0) { - status = pthread_cond_timedwait( - &thelock->lock_released, - &thelock->mut, &ts); - if (status == ETIMEDOUT) - break; - CHECK_STATUS("pthread_cond_timed_wait"); - } - else { - status = pthread_cond_wait( - &thelock->lock_released, - &thelock->mut); - CHECK_STATUS("pthread_cond_wait"); - } - } - success = (status == 0); - } - if (success) thelock->locked = 1; - status = pthread_mutex_unlock( &thelock->mut ); - CHECK_STATUS("pthread_mutex_unlock[1]"); - - if (error) success = 0; - dprintf(("PyThread_acquire_lock_timed(%p, %lld) -> %d\n", - lock, microseconds, success)); - return success; + int success; + pthread_lock *thelock = (pthread_lock *)lock; + int status, error = 0; + + dprintf(("PyThread_acquire_lock_timed(%p, %lld) called\n", + lock, microseconds)); + + status = pthread_mutex_lock( &thelock->mut ); + CHECK_STATUS("pthread_mutex_lock[1]"); + success = thelock->locked == 0; + + if (!success && microseconds != 0) { + struct timespec ts; + if (microseconds > 0) + MICROSECONDS_TO_TIMESPEC(microseconds, ts); + /* continue trying until we get the lock */ + + /* mut must be locked by me -- part of the condition + * protocol */ + while (thelock->locked) { + if (microseconds > 0) { + status = pthread_cond_timedwait( + &thelock->lock_released, + &thelock->mut, &ts); + if (status == ETIMEDOUT) + break; + CHECK_STATUS("pthread_cond_timed_wait"); + } + else { + status = pthread_cond_wait( + &thelock->lock_released, + &thelock->mut); + CHECK_STATUS("pthread_cond_wait"); + } + } + success = (status == 0); + } + if (success) thelock->locked = 1; + status = pthread_mutex_unlock( &thelock->mut ); + CHECK_STATUS("pthread_mutex_unlock[1]"); + + if (error) success = 0; + dprintf(("PyThread_acquire_lock_timed(%p, %lld) -> %d\n", + lock, microseconds, success)); + return success; } -int +int PyThread_acquire_lock(PyThread_type_lock lock, int waitflag) { - return PyThread_acquire_lock_timed(lock, waitflag ? -1 : 0); + return PyThread_acquire_lock_timed(lock, waitflag ? -1 : 0); } -void +void PyThread_release_lock(PyThread_type_lock lock) { - pthread_lock *thelock = (pthread_lock *)lock; - int status, error = 0; + pthread_lock *thelock = (pthread_lock *)lock; + int status, error = 0; - dprintf(("PyThread_release_lock(%p) called\n", lock)); + dprintf(("PyThread_release_lock(%p) called\n", lock)); - status = pthread_mutex_lock( &thelock->mut ); - CHECK_STATUS("pthread_mutex_lock[3]"); + status = pthread_mutex_lock( &thelock->mut ); + CHECK_STATUS("pthread_mutex_lock[3]"); - thelock->locked = 0; + thelock->locked = 0; - status = pthread_mutex_unlock( &thelock->mut ); - CHECK_STATUS("pthread_mutex_unlock[3]"); + status = pthread_mutex_unlock( &thelock->mut ); + CHECK_STATUS("pthread_mutex_unlock[3]"); - /* wake up someone (anyone, if any) waiting on the lock */ - status = pthread_cond_signal( &thelock->lock_released ); - CHECK_STATUS("pthread_cond_signal"); + /* wake up someone (anyone, if any) waiting on the lock */ + status = pthread_cond_signal( &thelock->lock_released ); + CHECK_STATUS("pthread_cond_signal"); } #endif /* USE_SEMAPHORES */ @@ -522,39 +522,39 @@ _pythread_pthread_set_stacksize(size_t size) { #if defined(THREAD_STACK_SIZE) - pthread_attr_t attrs; - size_t tss_min; - int rc = 0; + pthread_attr_t attrs; + size_t tss_min; + int rc = 0; #endif - /* set to default */ - if (size == 0) { - _pythread_stacksize = 0; - return 0; - } + /* set to default */ + if (size == 0) { + _pythread_stacksize = 0; + return 0; + } #if defined(THREAD_STACK_SIZE) #if defined(PTHREAD_STACK_MIN) - tss_min = PTHREAD_STACK_MIN > THREAD_STACK_MIN ? PTHREAD_STACK_MIN - : THREAD_STACK_MIN; + tss_min = PTHREAD_STACK_MIN > THREAD_STACK_MIN ? PTHREAD_STACK_MIN + : THREAD_STACK_MIN; #else - tss_min = THREAD_STACK_MIN; + tss_min = THREAD_STACK_MIN; #endif - if (size >= tss_min) { - /* validate stack size by setting thread attribute */ - if (pthread_attr_init(&attrs) == 0) { - rc = pthread_attr_setstacksize(&attrs, size); - pthread_attr_destroy(&attrs); - if (rc == 0) { - _pythread_stacksize = size; - return 0; - } - } - } - return -1; + if (size >= tss_min) { + /* validate stack size by setting thread attribute */ + if (pthread_attr_init(&attrs) == 0) { + rc = pthread_attr_setstacksize(&attrs, size); + pthread_attr_destroy(&attrs); + if (rc == 0) { + _pythread_stacksize = size; + return 0; + } + } + } + return -1; #else - return -2; + return -2; #endif } -#define THREAD_SET_STACKSIZE(x) _pythread_pthread_set_stacksize(x) +#define THREAD_SET_STACKSIZE(x) _pythread_pthread_set_stacksize(x) Modified: python/branches/py3k/Python/thread_sgi.h ============================================================================== --- python/branches/py3k/Python/thread_sgi.h (original) +++ python/branches/py3k/Python/thread_sgi.h Sun May 9 17:52:27 2010 @@ -8,67 +8,67 @@ #include #include -#define HDR_SIZE 2680 /* sizeof(ushdr_t) */ -#define MAXPROC 100 /* max # of threads that can be started */ +#define HDR_SIZE 2680 /* sizeof(ushdr_t) */ +#define MAXPROC 100 /* max # of threads that can be started */ static usptr_t *shared_arena; -static ulock_t count_lock; /* protection for some variables */ -static ulock_t wait_lock; /* lock used to wait for other threads */ -static int waiting_for_threads; /* protected by count_lock */ -static int nthreads; /* protected by count_lock */ +static ulock_t count_lock; /* protection for some variables */ +static ulock_t wait_lock; /* lock used to wait for other threads */ +static int waiting_for_threads; /* protected by count_lock */ +static int nthreads; /* protected by count_lock */ static int exit_status; -static int exiting; /* we're already exiting (for maybe_exit) */ -static pid_t my_pid; /* PID of main thread */ +static int exiting; /* we're already exiting (for maybe_exit) */ +static pid_t my_pid; /* PID of main thread */ static struct pidlist { - pid_t parent; - pid_t child; -} pidlist[MAXPROC]; /* PIDs of other threads; protected by count_lock */ -static int maxpidindex; /* # of PIDs in pidlist */ + pid_t parent; + pid_t child; +} pidlist[MAXPROC]; /* PIDs of other threads; protected by count_lock */ +static int maxpidindex; /* # of PIDs in pidlist */ /* * Initialization. */ static void PyThread__init_thread(void) { #ifdef USE_DL - long addr, size; + long addr, size; #endif /* USE_DL */ #ifdef USE_DL - if ((size = usconfig(CONF_INITSIZE, 64*1024)) < 0) - perror("usconfig - CONF_INITSIZE (check)"); - if (usconfig(CONF_INITSIZE, size) < 0) - perror("usconfig - CONF_INITSIZE (reset)"); - addr = (long) dl_getrange(size + HDR_SIZE); - dprintf(("trying to use addr %p-%p for shared arena\n", addr, addr+size)); - errno = 0; - if ((addr = usconfig(CONF_ATTACHADDR, addr)) < 0 && errno != 0) - perror("usconfig - CONF_ATTACHADDR (set)"); -#endif /* USE_DL */ - if (usconfig(CONF_INITUSERS, 16) < 0) - perror("usconfig - CONF_INITUSERS"); - my_pid = getpid(); /* so that we know which is the main thread */ - if (usconfig(CONF_ARENATYPE, US_SHAREDONLY) < 0) - perror("usconfig - CONF_ARENATYPE"); - usconfig(CONF_LOCKTYPE, US_DEBUG); /* XXX */ + if ((size = usconfig(CONF_INITSIZE, 64*1024)) < 0) + perror("usconfig - CONF_INITSIZE (check)"); + if (usconfig(CONF_INITSIZE, size) < 0) + perror("usconfig - CONF_INITSIZE (reset)"); + addr = (long) dl_getrange(size + HDR_SIZE); + dprintf(("trying to use addr %p-%p for shared arena\n", addr, addr+size)); + errno = 0; + if ((addr = usconfig(CONF_ATTACHADDR, addr)) < 0 && errno != 0) + perror("usconfig - CONF_ATTACHADDR (set)"); +#endif /* USE_DL */ + if (usconfig(CONF_INITUSERS, 16) < 0) + perror("usconfig - CONF_INITUSERS"); + my_pid = getpid(); /* so that we know which is the main thread */ + if (usconfig(CONF_ARENATYPE, US_SHAREDONLY) < 0) + perror("usconfig - CONF_ARENATYPE"); + usconfig(CONF_LOCKTYPE, US_DEBUG); /* XXX */ #ifdef Py_DEBUG - if (thread_debug & 4) - usconfig(CONF_LOCKTYPE, US_DEBUGPLUS); - else if (thread_debug & 2) - usconfig(CONF_LOCKTYPE, US_DEBUG); + if (thread_debug & 4) + usconfig(CONF_LOCKTYPE, US_DEBUGPLUS); + else if (thread_debug & 2) + usconfig(CONF_LOCKTYPE, US_DEBUG); #endif /* Py_DEBUG */ - if ((shared_arena = usinit(tmpnam(0))) == 0) - perror("usinit"); + if ((shared_arena = usinit(tmpnam(0))) == 0) + perror("usinit"); #ifdef USE_DL - if (usconfig(CONF_ATTACHADDR, addr) < 0) /* reset address */ - perror("usconfig - CONF_ATTACHADDR (reset)"); + if (usconfig(CONF_ATTACHADDR, addr) < 0) /* reset address */ + perror("usconfig - CONF_ATTACHADDR (reset)"); #endif /* USE_DL */ - if ((count_lock = usnewlock(shared_arena)) == NULL) - perror("usnewlock (count_lock)"); - (void) usinitlock(count_lock); - if ((wait_lock = usnewlock(shared_arena)) == NULL) - perror("usnewlock (wait_lock)"); - dprintf(("arena start: %p, arena size: %ld\n", shared_arena, (long) usconfig(CONF_GETSIZE, shared_arena))); + if ((count_lock = usnewlock(shared_arena)) == NULL) + perror("usnewlock (count_lock)"); + (void) usinitlock(count_lock); + if ((wait_lock = usnewlock(shared_arena)) == NULL) + perror("usnewlock (wait_lock)"); + dprintf(("arena start: %p, arena size: %ld\n", shared_arena, (long) usconfig(CONF_GETSIZE, shared_arena))); } /* @@ -77,138 +77,138 @@ static void clean_threads(void) { - int i, j; - pid_t mypid, pid; + int i, j; + pid_t mypid, pid; - /* clean up any exited threads */ - mypid = getpid(); - i = 0; - while (i < maxpidindex) { - if (pidlist[i].parent == mypid && (pid = pidlist[i].child) > 0) { - pid = waitpid(pid, 0, WNOHANG); - if (pid > 0) { - /* a thread has exited */ - pidlist[i] = pidlist[--maxpidindex]; - /* remove references to children of dead proc */ - for (j = 0; j < maxpidindex; j++) - if (pidlist[j].parent == pid) - pidlist[j].child = -1; - continue; /* don't increment i */ - } - } - i++; - } - /* clean up the list */ - i = 0; - while (i < maxpidindex) { - if (pidlist[i].child == -1) { - pidlist[i] = pidlist[--maxpidindex]; - continue; /* don't increment i */ - } - i++; - } + /* clean up any exited threads */ + mypid = getpid(); + i = 0; + while (i < maxpidindex) { + if (pidlist[i].parent == mypid && (pid = pidlist[i].child) > 0) { + pid = waitpid(pid, 0, WNOHANG); + if (pid > 0) { + /* a thread has exited */ + pidlist[i] = pidlist[--maxpidindex]; + /* remove references to children of dead proc */ + for (j = 0; j < maxpidindex; j++) + if (pidlist[j].parent == pid) + pidlist[j].child = -1; + continue; /* don't increment i */ + } + } + i++; + } + /* clean up the list */ + i = 0; + while (i < maxpidindex) { + if (pidlist[i].child == -1) { + pidlist[i] = pidlist[--maxpidindex]; + continue; /* don't increment i */ + } + i++; + } } long PyThread_start_new_thread(void (*func)(void *), void *arg) { #ifdef USE_DL - long addr, size; - static int local_initialized = 0; + long addr, size; + static int local_initialized = 0; #endif /* USE_DL */ - int success = 0; /* init not needed when SOLARIS_THREADS and */ - /* C_THREADS implemented properly */ + int success = 0; /* init not needed when SOLARIS_THREADS and */ + /* C_THREADS implemented properly */ - dprintf(("PyThread_start_new_thread called\n")); - if (!initialized) - PyThread_init_thread(); - switch (ussetlock(count_lock)) { - case 0: return 0; - case -1: perror("ussetlock (count_lock)"); - } - if (maxpidindex >= MAXPROC) - success = -1; - else { -#ifdef USE_DL - if (!local_initialized) { - if ((size = usconfig(CONF_INITSIZE, 64*1024)) < 0) - perror("usconfig - CONF_INITSIZE (check)"); - if (usconfig(CONF_INITSIZE, size) < 0) - perror("usconfig - CONF_INITSIZE (reset)"); - addr = (long) dl_getrange(size + HDR_SIZE); - dprintf(("trying to use addr %p-%p for sproc\n", - addr, addr+size)); - errno = 0; - if ((addr = usconfig(CONF_ATTACHADDR, addr)) < 0 && - errno != 0) - perror("usconfig - CONF_ATTACHADDR (set)"); - } -#endif /* USE_DL */ - clean_threads(); - if ((success = sproc(func, PR_SALL, arg)) < 0) - perror("sproc"); -#ifdef USE_DL - if (!local_initialized) { - if (usconfig(CONF_ATTACHADDR, addr) < 0) - /* reset address */ - perror("usconfig - CONF_ATTACHADDR (reset)"); - local_initialized = 1; - } -#endif /* USE_DL */ - if (success >= 0) { - nthreads++; - pidlist[maxpidindex].parent = getpid(); - pidlist[maxpidindex++].child = success; - dprintf(("pidlist[%d] = %d\n", - maxpidindex-1, success)); - } - } - if (usunsetlock(count_lock) < 0) - perror("usunsetlock (count_lock)"); - return success; + dprintf(("PyThread_start_new_thread called\n")); + if (!initialized) + PyThread_init_thread(); + switch (ussetlock(count_lock)) { + case 0: return 0; + case -1: perror("ussetlock (count_lock)"); + } + if (maxpidindex >= MAXPROC) + success = -1; + else { +#ifdef USE_DL + if (!local_initialized) { + if ((size = usconfig(CONF_INITSIZE, 64*1024)) < 0) + perror("usconfig - CONF_INITSIZE (check)"); + if (usconfig(CONF_INITSIZE, size) < 0) + perror("usconfig - CONF_INITSIZE (reset)"); + addr = (long) dl_getrange(size + HDR_SIZE); + dprintf(("trying to use addr %p-%p for sproc\n", + addr, addr+size)); + errno = 0; + if ((addr = usconfig(CONF_ATTACHADDR, addr)) < 0 && + errno != 0) + perror("usconfig - CONF_ATTACHADDR (set)"); + } +#endif /* USE_DL */ + clean_threads(); + if ((success = sproc(func, PR_SALL, arg)) < 0) + perror("sproc"); +#ifdef USE_DL + if (!local_initialized) { + if (usconfig(CONF_ATTACHADDR, addr) < 0) + /* reset address */ + perror("usconfig - CONF_ATTACHADDR (reset)"); + local_initialized = 1; + } +#endif /* USE_DL */ + if (success >= 0) { + nthreads++; + pidlist[maxpidindex].parent = getpid(); + pidlist[maxpidindex++].child = success; + dprintf(("pidlist[%d] = %d\n", + maxpidindex-1, success)); + } + } + if (usunsetlock(count_lock) < 0) + perror("usunsetlock (count_lock)"); + return success; } long PyThread_get_thread_ident(void) { - return getpid(); + return getpid(); } void PyThread_exit_thread(void) { - dprintf(("PyThread_exit_thread called\n")); - if (!initialized) - exit(0); - if (ussetlock(count_lock) < 0) - perror("ussetlock (count_lock)"); - nthreads--; - if (getpid() == my_pid) { - /* main thread; wait for other threads to exit */ - exiting = 1; - waiting_for_threads = 1; - if (ussetlock(wait_lock) < 0) - perror("ussetlock (wait_lock)"); - for (;;) { - if (nthreads < 0) { - dprintf(("really exit (%d)\n", exit_status)); - exit(exit_status); - } - if (usunsetlock(count_lock) < 0) - perror("usunsetlock (count_lock)"); - dprintf(("waiting for other threads (%d)\n", nthreads)); - if (ussetlock(wait_lock) < 0) - perror("ussetlock (wait_lock)"); - if (ussetlock(count_lock) < 0) - perror("ussetlock (count_lock)"); - } - } - /* not the main thread */ - if (waiting_for_threads) { - dprintf(("main thread is waiting\n")); - if (usunsetlock(wait_lock) < 0) - perror("usunsetlock (wait_lock)"); - } - if (usunsetlock(count_lock) < 0) - perror("usunsetlock (count_lock)"); - _exit(0); + dprintf(("PyThread_exit_thread called\n")); + if (!initialized) + exit(0); + if (ussetlock(count_lock) < 0) + perror("ussetlock (count_lock)"); + nthreads--; + if (getpid() == my_pid) { + /* main thread; wait for other threads to exit */ + exiting = 1; + waiting_for_threads = 1; + if (ussetlock(wait_lock) < 0) + perror("ussetlock (wait_lock)"); + for (;;) { + if (nthreads < 0) { + dprintf(("really exit (%d)\n", exit_status)); + exit(exit_status); + } + if (usunsetlock(count_lock) < 0) + perror("usunsetlock (count_lock)"); + dprintf(("waiting for other threads (%d)\n", nthreads)); + if (ussetlock(wait_lock) < 0) + perror("ussetlock (wait_lock)"); + if (ussetlock(count_lock) < 0) + perror("ussetlock (count_lock)"); + } + } + /* not the main thread */ + if (waiting_for_threads) { + dprintf(("main thread is waiting\n")); + if (usunsetlock(wait_lock) < 0) + perror("usunsetlock (wait_lock)"); + } + if (usunsetlock(count_lock) < 0) + perror("usunsetlock (count_lock)"); + _exit(0); } /* @@ -216,44 +216,44 @@ */ PyThread_type_lock PyThread_allocate_lock(void) { - ulock_t lock; + ulock_t lock; - dprintf(("PyThread_allocate_lock called\n")); - if (!initialized) - PyThread_init_thread(); - - if ((lock = usnewlock(shared_arena)) == NULL) - perror("usnewlock"); - (void) usinitlock(lock); - dprintf(("PyThread_allocate_lock() -> %p\n", lock)); - return (PyThread_type_lock) lock; + dprintf(("PyThread_allocate_lock called\n")); + if (!initialized) + PyThread_init_thread(); + + if ((lock = usnewlock(shared_arena)) == NULL) + perror("usnewlock"); + (void) usinitlock(lock); + dprintf(("PyThread_allocate_lock() -> %p\n", lock)); + return (PyThread_type_lock) lock; } void PyThread_free_lock(PyThread_type_lock lock) { - dprintf(("PyThread_free_lock(%p) called\n", lock)); - usfreelock((ulock_t) lock, shared_arena); + dprintf(("PyThread_free_lock(%p) called\n", lock)); + usfreelock((ulock_t) lock, shared_arena); } int PyThread_acquire_lock(PyThread_type_lock lock, int waitflag) { - int success; + int success; - dprintf(("PyThread_acquire_lock(%p, %d) called\n", lock, waitflag)); - errno = 0; /* clear it just in case */ - if (waitflag) - success = ussetlock((ulock_t) lock); - else - success = uscsetlock((ulock_t) lock, 1); /* Try it once */ - if (success < 0) - perror(waitflag ? "ussetlock" : "uscsetlock"); - dprintf(("PyThread_acquire_lock(%p, %d) -> %d\n", lock, waitflag, success)); - return success; + dprintf(("PyThread_acquire_lock(%p, %d) called\n", lock, waitflag)); + errno = 0; /* clear it just in case */ + if (waitflag) + success = ussetlock((ulock_t) lock); + else + success = uscsetlock((ulock_t) lock, 1); /* Try it once */ + if (success < 0) + perror(waitflag ? "ussetlock" : "uscsetlock"); + dprintf(("PyThread_acquire_lock(%p, %d) -> %d\n", lock, waitflag, success)); + return success; } void PyThread_release_lock(PyThread_type_lock lock) { - dprintf(("PyThread_release_lock(%p) called\n", lock)); - if (usunsetlock((ulock_t) lock) < 0) - perror("usunsetlock"); + dprintf(("PyThread_release_lock(%p) called\n", lock)); + if (usunsetlock((ulock_t) lock) < 0) + perror("usunsetlock"); } Modified: python/branches/py3k/Python/thread_solaris.h ============================================================================== --- python/branches/py3k/Python/thread_solaris.h (original) +++ python/branches/py3k/Python/thread_solaris.h Sun May 9 17:52:27 2010 @@ -17,114 +17,114 @@ * Thread support. */ struct func_arg { - void (*func)(void *); - void *arg; + void (*func)(void *); + void *arg; }; static void * new_func(void *funcarg) { - void (*func)(void *); - void *arg; + void (*func)(void *); + void *arg; - func = ((struct func_arg *) funcarg)->func; - arg = ((struct func_arg *) funcarg)->arg; - free(funcarg); - (*func)(arg); - return 0; + func = ((struct func_arg *) funcarg)->func; + arg = ((struct func_arg *) funcarg)->arg; + free(funcarg); + (*func)(arg); + return 0; } long PyThread_start_new_thread(void (*func)(void *), void *arg) { - thread_t tid; - struct func_arg *funcarg; + thread_t tid; + struct func_arg *funcarg; - dprintf(("PyThread_start_new_thread called\n")); - if (!initialized) - PyThread_init_thread(); - funcarg = (struct func_arg *) malloc(sizeof(struct func_arg)); - funcarg->func = func; - funcarg->arg = arg; - if (thr_create(0, 0, new_func, funcarg, - THR_DETACHED | THR_NEW_LWP, &tid)) { - perror("thr_create"); - free((void *) funcarg); - return -1; - } - return tid; + dprintf(("PyThread_start_new_thread called\n")); + if (!initialized) + PyThread_init_thread(); + funcarg = (struct func_arg *) malloc(sizeof(struct func_arg)); + funcarg->func = func; + funcarg->arg = arg; + if (thr_create(0, 0, new_func, funcarg, + THR_DETACHED | THR_NEW_LWP, &tid)) { + perror("thr_create"); + free((void *) funcarg); + return -1; + } + return tid; } long PyThread_get_thread_ident(void) { - if (!initialized) - PyThread_init_thread(); - return thr_self(); + if (!initialized) + PyThread_init_thread(); + return thr_self(); } -void +void PyThread_exit_thread(void) { - dprintf(("PyThread_exit_thread called\n")); - if (!initialized) - exit(0); - thr_exit(0); + dprintf(("PyThread_exit_thread called\n")); + if (!initialized) + exit(0); + thr_exit(0); } /* * Lock support. */ -PyThread_type_lock +PyThread_type_lock PyThread_allocate_lock(void) { - mutex_t *lock; + mutex_t *lock; - dprintf(("PyThread_allocate_lock called\n")); - if (!initialized) - PyThread_init_thread(); - - lock = (mutex_t *) malloc(sizeof(mutex_t)); - if (mutex_init(lock, USYNC_THREAD, 0)) { - perror("mutex_init"); - free((void *) lock); - lock = 0; - } - dprintf(("PyThread_allocate_lock() -> %p\n", lock)); - return (PyThread_type_lock) lock; + dprintf(("PyThread_allocate_lock called\n")); + if (!initialized) + PyThread_init_thread(); + + lock = (mutex_t *) malloc(sizeof(mutex_t)); + if (mutex_init(lock, USYNC_THREAD, 0)) { + perror("mutex_init"); + free((void *) lock); + lock = 0; + } + dprintf(("PyThread_allocate_lock() -> %p\n", lock)); + return (PyThread_type_lock) lock; } -void +void PyThread_free_lock(PyThread_type_lock lock) { - dprintf(("PyThread_free_lock(%p) called\n", lock)); - mutex_destroy((mutex_t *) lock); - free((void *) lock); + dprintf(("PyThread_free_lock(%p) called\n", lock)); + mutex_destroy((mutex_t *) lock); + free((void *) lock); } -int +int PyThread_acquire_lock(PyThread_type_lock lock, int waitflag) { - int success; + int success; - dprintf(("PyThread_acquire_lock(%p, %d) called\n", lock, waitflag)); - if (waitflag) - success = mutex_lock((mutex_t *) lock); - else - success = mutex_trylock((mutex_t *) lock); - if (success < 0) - perror(waitflag ? "mutex_lock" : "mutex_trylock"); - else - success = !success; /* solaris does it the other way round */ - dprintf(("PyThread_acquire_lock(%p, %d) -> %d\n", lock, waitflag, success)); - return success; + dprintf(("PyThread_acquire_lock(%p, %d) called\n", lock, waitflag)); + if (waitflag) + success = mutex_lock((mutex_t *) lock); + else + success = mutex_trylock((mutex_t *) lock); + if (success < 0) + perror(waitflag ? "mutex_lock" : "mutex_trylock"); + else + success = !success; /* solaris does it the other way round */ + dprintf(("PyThread_acquire_lock(%p, %d) -> %d\n", lock, waitflag, success)); + return success; } -void +void PyThread_release_lock(PyThread_type_lock lock) { - dprintf(("PyThread_release_lock(%p) called\n", lock)); - if (mutex_unlock((mutex_t *) lock)) - perror("mutex_unlock"); + dprintf(("PyThread_release_lock(%p) called\n", lock)); + if (mutex_unlock((mutex_t *) lock)) + perror("mutex_unlock"); } Modified: python/branches/py3k/Python/thread_wince.h ============================================================================== --- python/branches/py3k/Python/thread_wince.h (original) +++ python/branches/py3k/Python/thread_wince.h Sun May 9 17:52:27 2010 @@ -24,21 +24,21 @@ */ long PyThread_start_new_thread(void (*func)(void *), void *arg) { - long rv; - int success = -1; + long rv; + int success = -1; - dprintf(("%ld: PyThread_start_new_thread called\n", PyThread_get_thread_ident())); - if (!initialized) - PyThread_init_thread(); - - rv = _beginthread(func, 0, arg); /* use default stack size */ - - if (rv != -1) { - success = 0; - dprintf(("%ld: PyThread_start_new_thread succeeded:\n", PyThread_get_thread_ident())); - } + dprintf(("%ld: PyThread_start_new_thread called\n", PyThread_get_thread_ident())); + if (!initialized) + PyThread_init_thread(); + + rv = _beginthread(func, 0, arg); /* use default stack size */ - return success; + if (rv != -1) { + success = 0; + dprintf(("%ld: PyThread_start_new_thread succeeded:\n", PyThread_get_thread_ident())); + } + + return success; } /* @@ -47,18 +47,18 @@ */ long PyThread_get_thread_ident(void) { - if (!initialized) - PyThread_init_thread(); - - return GetCurrentThreadId(); + if (!initialized) + PyThread_init_thread(); + + return GetCurrentThreadId(); } void PyThread_exit_thread(void) { - dprintf(("%ld: PyThread_exit_thread called\n", PyThread_get_thread_ident())); - if (!initialized) - exit(0); - _endthread(); + dprintf(("%ld: PyThread_exit_thread called\n", PyThread_get_thread_ident())); + if (!initialized) + exit(0); + _endthread(); } /* @@ -72,12 +72,12 @@ dprintf(("PyThread_allocate_lock called\n")); if (!initialized) - PyThread_init_thread(); + PyThread_init_thread(); aLock = CreateEvent(NULL, /* Security attributes */ - 0, /* Manual-Reset */ - 1, /* Is initially signalled */ - NULL); /* Name of event */ + 0, /* Manual-Reset */ + 1, /* Is initially signalled */ + NULL); /* Name of event */ dprintf(("%ld: PyThread_allocate_lock() -> %p\n", PyThread_get_thread_ident(), aLock)); @@ -107,22 +107,22 @@ #ifndef DEBUG waitResult = WaitForSingleObject(aLock, (waitflag ? INFINITE : 0)); #else - /* To aid in debugging, we regularly wake up. This allows us to - break into the debugger */ - while (TRUE) { - waitResult = WaitForSingleObject(aLock, waitflag ? 3000 : 0); - if (waitflag==0 || (waitflag && waitResult == WAIT_OBJECT_0)) - break; - } + /* To aid in debugging, we regularly wake up. This allows us to + break into the debugger */ + while (TRUE) { + waitResult = WaitForSingleObject(aLock, waitflag ? 3000 : 0); + if (waitflag==0 || (waitflag && waitResult == WAIT_OBJECT_0)) + break; + } #endif if (waitResult != WAIT_OBJECT_0) { - success = 0; /* We failed */ + success = 0; /* We failed */ } - dprintf(("%ld: PyThread_acquire_lock(%p, %d) -> %d\n", PyThread_get_thread_ident(),aLock, waitflag, success)); + dprintf(("%ld: PyThread_acquire_lock(%p, %d) -> %d\n", PyThread_get_thread_ident(),aLock, waitflag, success)); - return success; + return success; } void PyThread_release_lock(PyThread_type_lock aLock) @@ -130,7 +130,7 @@ dprintf(("%ld: PyThread_release_lock(%p) called\n", PyThread_get_thread_ident(),aLock)); if (!SetEvent(aLock)) - dprintf(("%ld: Could not PyThread_release_lock(%p) error: %l\n", PyThread_get_thread_ident(), aLock, GetLastError())); + dprintf(("%ld: Could not PyThread_release_lock(%p) error: %l\n", PyThread_get_thread_ident(), aLock, GetLastError())); } Modified: python/branches/py3k/Python/traceback.c ============================================================================== --- python/branches/py3k/Python/traceback.c (original) +++ python/branches/py3k/Python/traceback.c Sun May 9 17:52:27 2010 @@ -30,303 +30,303 @@ }; static PyMemberDef tb_memberlist[] = { - {"tb_next", T_OBJECT, OFF(tb_next), READONLY}, - {"tb_frame", T_OBJECT, OFF(tb_frame), READONLY}, - {"tb_lasti", T_INT, OFF(tb_lasti), READONLY}, - {"tb_lineno", T_INT, OFF(tb_lineno), READONLY}, - {NULL} /* Sentinel */ + {"tb_next", T_OBJECT, OFF(tb_next), READONLY}, + {"tb_frame", T_OBJECT, OFF(tb_frame), READONLY}, + {"tb_lasti", T_INT, OFF(tb_lasti), READONLY}, + {"tb_lineno", T_INT, OFF(tb_lineno), READONLY}, + {NULL} /* Sentinel */ }; static void tb_dealloc(PyTracebackObject *tb) { - PyObject_GC_UnTrack(tb); - Py_TRASHCAN_SAFE_BEGIN(tb) - Py_XDECREF(tb->tb_next); - Py_XDECREF(tb->tb_frame); - PyObject_GC_Del(tb); - Py_TRASHCAN_SAFE_END(tb) + PyObject_GC_UnTrack(tb); + Py_TRASHCAN_SAFE_BEGIN(tb) + Py_XDECREF(tb->tb_next); + Py_XDECREF(tb->tb_frame); + PyObject_GC_Del(tb); + Py_TRASHCAN_SAFE_END(tb) } static int tb_traverse(PyTracebackObject *tb, visitproc visit, void *arg) { - Py_VISIT(tb->tb_next); - Py_VISIT(tb->tb_frame); - return 0; + Py_VISIT(tb->tb_next); + Py_VISIT(tb->tb_frame); + return 0; } static void tb_clear(PyTracebackObject *tb) { - Py_CLEAR(tb->tb_next); - Py_CLEAR(tb->tb_frame); + Py_CLEAR(tb->tb_next); + Py_CLEAR(tb->tb_frame); } PyTypeObject PyTraceBack_Type = { - PyVarObject_HEAD_INIT(&PyType_Type, 0) - "traceback", - sizeof(PyTracebackObject), - 0, - (destructor)tb_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)tb_traverse, /* tp_traverse */ - (inquiry)tb_clear, /* tp_clear */ - 0, /* tp_richcompare */ - 0, /* tp_weaklistoffset */ - 0, /* tp_iter */ - 0, /* tp_iternext */ - tb_methods, /* tp_methods */ - tb_memberlist, /* tp_members */ - 0, /* tp_getset */ - 0, /* tp_base */ - 0, /* tp_dict */ + PyVarObject_HEAD_INIT(&PyType_Type, 0) + "traceback", + sizeof(PyTracebackObject), + 0, + (destructor)tb_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)tb_traverse, /* tp_traverse */ + (inquiry)tb_clear, /* tp_clear */ + 0, /* tp_richcompare */ + 0, /* tp_weaklistoffset */ + 0, /* tp_iter */ + 0, /* tp_iternext */ + tb_methods, /* tp_methods */ + tb_memberlist, /* tp_members */ + 0, /* tp_getset */ + 0, /* tp_base */ + 0, /* tp_dict */ }; static PyTracebackObject * newtracebackobject(PyTracebackObject *next, PyFrameObject *frame) { - PyTracebackObject *tb; - if ((next != NULL && !PyTraceBack_Check(next)) || - frame == NULL || !PyFrame_Check(frame)) { - PyErr_BadInternalCall(); - return NULL; - } - tb = PyObject_GC_New(PyTracebackObject, &PyTraceBack_Type); - if (tb != NULL) { - Py_XINCREF(next); - tb->tb_next = next; - Py_XINCREF(frame); - tb->tb_frame = frame; - tb->tb_lasti = frame->f_lasti; - tb->tb_lineno = PyFrame_GetLineNumber(frame); - PyObject_GC_Track(tb); - } - return tb; + PyTracebackObject *tb; + if ((next != NULL && !PyTraceBack_Check(next)) || + frame == NULL || !PyFrame_Check(frame)) { + PyErr_BadInternalCall(); + return NULL; + } + tb = PyObject_GC_New(PyTracebackObject, &PyTraceBack_Type); + if (tb != NULL) { + Py_XINCREF(next); + tb->tb_next = next; + Py_XINCREF(frame); + tb->tb_frame = frame; + tb->tb_lasti = frame->f_lasti; + tb->tb_lineno = PyFrame_GetLineNumber(frame); + PyObject_GC_Track(tb); + } + return tb; } int PyTraceBack_Here(PyFrameObject *frame) { - PyThreadState *tstate = PyThreadState_GET(); - PyTracebackObject *oldtb = (PyTracebackObject *) tstate->curexc_traceback; - PyTracebackObject *tb = newtracebackobject(oldtb, frame); - if (tb == NULL) - return -1; - tstate->curexc_traceback = (PyObject *)tb; - Py_XDECREF(oldtb); - return 0; + PyThreadState *tstate = PyThreadState_GET(); + PyTracebackObject *oldtb = (PyTracebackObject *) tstate->curexc_traceback; + PyTracebackObject *tb = newtracebackobject(oldtb, frame); + if (tb == NULL) + return -1; + tstate->curexc_traceback = (PyObject *)tb; + Py_XDECREF(oldtb); + return 0; } static int _Py_FindSourceFile(const char* filename, char* namebuf, size_t namelen, int open_flags) { - int i; - int fd = -1; - PyObject *v; - Py_ssize_t _npath; - int npath; - size_t taillen; - PyObject *syspath; - const char* path; - const char* tail; - Py_ssize_t len; - - /* Search tail of filename in sys.path before giving up */ - tail = strrchr(filename, SEP); - if (tail == NULL) - tail = filename; - else - tail++; - taillen = strlen(tail); - - syspath = PySys_GetObject("path"); - if (syspath == NULL || !PyList_Check(syspath)) - return -1; - _npath = PyList_Size(syspath); - npath = Py_SAFE_DOWNCAST(_npath, Py_ssize_t, int); - - for (i = 0; i < npath; i++) { - v = PyList_GetItem(syspath, i); - if (v == NULL) { - PyErr_Clear(); - break; - } - if (!PyUnicode_Check(v)) - continue; - path = _PyUnicode_AsStringAndSize(v, &len); - if (len + 1 + (Py_ssize_t)taillen >= (Py_ssize_t)namelen - 1) - continue; /* Too long */ - strcpy(namebuf, path); - if (strlen(namebuf) != len) - continue; /* v contains '\0' */ - if (len > 0 && namebuf[len-1] != SEP) - namebuf[len++] = SEP; - strcpy(namebuf+len, tail); - Py_BEGIN_ALLOW_THREADS - fd = open(namebuf, open_flags); - Py_END_ALLOW_THREADS - if (0 <= fd) { - return fd; - } - } - return -1; + int i; + int fd = -1; + PyObject *v; + Py_ssize_t _npath; + int npath; + size_t taillen; + PyObject *syspath; + const char* path; + const char* tail; + Py_ssize_t len; + + /* Search tail of filename in sys.path before giving up */ + tail = strrchr(filename, SEP); + if (tail == NULL) + tail = filename; + else + tail++; + taillen = strlen(tail); + + syspath = PySys_GetObject("path"); + if (syspath == NULL || !PyList_Check(syspath)) + return -1; + _npath = PyList_Size(syspath); + npath = Py_SAFE_DOWNCAST(_npath, Py_ssize_t, int); + + for (i = 0; i < npath; i++) { + v = PyList_GetItem(syspath, i); + if (v == NULL) { + PyErr_Clear(); + break; + } + if (!PyUnicode_Check(v)) + continue; + path = _PyUnicode_AsStringAndSize(v, &len); + if (len + 1 + (Py_ssize_t)taillen >= (Py_ssize_t)namelen - 1) + continue; /* Too long */ + strcpy(namebuf, path); + if (strlen(namebuf) != len) + continue; /* v contains '\0' */ + if (len > 0 && namebuf[len-1] != SEP) + namebuf[len++] = SEP; + strcpy(namebuf+len, tail); + Py_BEGIN_ALLOW_THREADS + fd = open(namebuf, open_flags); + Py_END_ALLOW_THREADS + if (0 <= fd) { + return fd; + } + } + return -1; } int _Py_DisplaySourceLine(PyObject *f, const char *filename, int lineno, int indent) { - int err = 0; - int fd; - int i; - char *found_encoding; - char *encoding; - PyObject *fob = NULL; - PyObject *lineobj = NULL; + int err = 0; + int fd; + int i; + char *found_encoding; + char *encoding; + PyObject *fob = NULL; + PyObject *lineobj = NULL; #ifdef O_BINARY - const int open_flags = O_RDONLY | O_BINARY; /* necessary for Windows */ + const int open_flags = O_RDONLY | O_BINARY; /* necessary for Windows */ #else - const int open_flags = O_RDONLY; + const int open_flags = O_RDONLY; #endif - char buf[MAXPATHLEN+1]; - Py_UNICODE *u, *p; - Py_ssize_t len; - - /* open the file */ - if (filename == NULL) - return 0; - Py_BEGIN_ALLOW_THREADS - fd = open(filename, open_flags); - Py_END_ALLOW_THREADS - if (fd < 0) { - fd = _Py_FindSourceFile(filename, buf, sizeof(buf), open_flags); - if (fd < 0) - return 0; - filename = buf; - } - - /* use the right encoding to decode the file as unicode */ - found_encoding = PyTokenizer_FindEncoding(fd); - encoding = (found_encoding != NULL) ? found_encoding : - (char*)PyUnicode_GetDefaultEncoding(); - lseek(fd, 0, 0); /* Reset position */ - fob = PyFile_FromFd(fd, (char*)filename, "r", -1, (char*)encoding, - NULL, NULL, 1); - PyMem_FREE(found_encoding); - if (fob == NULL) { - PyErr_Clear(); - close(fd); - return 0; - } - - /* get the line number lineno */ - for (i = 0; i < lineno; i++) { - Py_XDECREF(lineobj); - lineobj = PyFile_GetLine(fob, -1); - if (!lineobj) { - err = -1; - break; - } - } - Py_DECREF(fob); - if (!lineobj || !PyUnicode_Check(lineobj)) { - Py_XDECREF(lineobj); - return err; - } - - /* remove the indentation of the line */ - u = PyUnicode_AS_UNICODE(lineobj); - len = PyUnicode_GET_SIZE(lineobj); - for (p=u; *p == ' ' || *p == '\t' || *p == '\014'; p++) - len--; - if (u != p) { - PyObject *truncated; - truncated = PyUnicode_FromUnicode(p, len); - if (truncated) { - Py_DECREF(lineobj); - lineobj = truncated; - } else { - PyErr_Clear(); - } - } - - /* Write some spaces before the line */ - strcpy(buf, " "); - assert (strlen(buf) == 10); - while (indent > 0) { - if(indent < 10) - buf[indent] = '\0'; - err = PyFile_WriteString(buf, f); - if (err != 0) - break; - indent -= 10; - } - - /* finally display the line */ - if (err == 0) - err = PyFile_WriteObject(lineobj, f, Py_PRINT_RAW); - Py_DECREF(lineobj); - if (err == 0) - err = PyFile_WriteString("\n", f); - return err; + char buf[MAXPATHLEN+1]; + Py_UNICODE *u, *p; + Py_ssize_t len; + + /* open the file */ + if (filename == NULL) + return 0; + Py_BEGIN_ALLOW_THREADS + fd = open(filename, open_flags); + Py_END_ALLOW_THREADS + if (fd < 0) { + fd = _Py_FindSourceFile(filename, buf, sizeof(buf), open_flags); + if (fd < 0) + return 0; + filename = buf; + } + + /* use the right encoding to decode the file as unicode */ + found_encoding = PyTokenizer_FindEncoding(fd); + encoding = (found_encoding != NULL) ? found_encoding : + (char*)PyUnicode_GetDefaultEncoding(); + lseek(fd, 0, 0); /* Reset position */ + fob = PyFile_FromFd(fd, (char*)filename, "r", -1, (char*)encoding, + NULL, NULL, 1); + PyMem_FREE(found_encoding); + if (fob == NULL) { + PyErr_Clear(); + close(fd); + return 0; + } + + /* get the line number lineno */ + for (i = 0; i < lineno; i++) { + Py_XDECREF(lineobj); + lineobj = PyFile_GetLine(fob, -1); + if (!lineobj) { + err = -1; + break; + } + } + Py_DECREF(fob); + if (!lineobj || !PyUnicode_Check(lineobj)) { + Py_XDECREF(lineobj); + return err; + } + + /* remove the indentation of the line */ + u = PyUnicode_AS_UNICODE(lineobj); + len = PyUnicode_GET_SIZE(lineobj); + for (p=u; *p == ' ' || *p == '\t' || *p == '\014'; p++) + len--; + if (u != p) { + PyObject *truncated; + truncated = PyUnicode_FromUnicode(p, len); + if (truncated) { + Py_DECREF(lineobj); + lineobj = truncated; + } else { + PyErr_Clear(); + } + } + + /* Write some spaces before the line */ + strcpy(buf, " "); + assert (strlen(buf) == 10); + while (indent > 0) { + if(indent < 10) + buf[indent] = '\0'; + err = PyFile_WriteString(buf, f); + if (err != 0) + break; + indent -= 10; + } + + /* finally display the line */ + if (err == 0) + err = PyFile_WriteObject(lineobj, f, Py_PRINT_RAW); + Py_DECREF(lineobj); + if (err == 0) + err = PyFile_WriteString("\n", f); + return err; } static int tb_displayline(PyObject *f, const char *filename, int lineno, const char *name) { - int err = 0; - char linebuf[2000]; + int err = 0; + char linebuf[2000]; - if (filename == NULL || name == NULL) - return -1; - /* This is needed by Emacs' compile command */ + if (filename == NULL || name == NULL) + return -1; + /* This is needed by Emacs' compile command */ #define FMT " File \"%.500s\", line %d, in %.500s\n" - PyOS_snprintf(linebuf, sizeof(linebuf), FMT, filename, lineno, name); - err = PyFile_WriteString(linebuf, f); - if (err != 0) - return err; - return _Py_DisplaySourceLine(f, filename, lineno, 4); + PyOS_snprintf(linebuf, sizeof(linebuf), FMT, filename, lineno, name); + err = PyFile_WriteString(linebuf, f); + if (err != 0) + return err; + return _Py_DisplaySourceLine(f, filename, lineno, 4); } static int tb_printinternal(PyTracebackObject *tb, PyObject *f, long limit) { - int err = 0; - long depth = 0; - PyTracebackObject *tb1 = tb; - while (tb1 != NULL) { - depth++; - tb1 = tb1->tb_next; - } - while (tb != NULL && err == 0) { - if (depth <= limit) { - err = tb_displayline(f, - _PyUnicode_AsString( - tb->tb_frame->f_code->co_filename), - tb->tb_lineno, - _PyUnicode_AsString(tb->tb_frame->f_code->co_name)); - } - depth--; - tb = tb->tb_next; - if (err == 0) - err = PyErr_CheckSignals(); - } - return err; + int err = 0; + long depth = 0; + PyTracebackObject *tb1 = tb; + while (tb1 != NULL) { + depth++; + tb1 = tb1->tb_next; + } + while (tb != NULL && err == 0) { + if (depth <= limit) { + err = tb_displayline(f, + _PyUnicode_AsString( + tb->tb_frame->f_code->co_filename), + tb->tb_lineno, + _PyUnicode_AsString(tb->tb_frame->f_code->co_name)); + } + depth--; + tb = tb->tb_next; + if (err == 0) + err = PyErr_CheckSignals(); + } + return err; } #define PyTraceBack_LIMIT 1000 @@ -334,40 +334,40 @@ int PyTraceBack_Print(PyObject *v, PyObject *f) { - int err; - PyObject *limitv; - long limit = PyTraceBack_LIMIT; - - if (v == NULL) - return 0; - if (!PyTraceBack_Check(v)) { - PyErr_BadInternalCall(); - return -1; - } - limitv = PySys_GetObject("tracebacklimit"); - if (limitv) { - PyObject *exc_type, *exc_value, *exc_tb; - - PyErr_Fetch(&exc_type, &exc_value, &exc_tb); - limit = PyLong_AsLong(limitv); - if (limit == -1 && PyErr_Occurred()) { - if (PyErr_ExceptionMatches(PyExc_OverflowError)) { - limit = PyTraceBack_LIMIT; - } - else { - Py_XDECREF(exc_type); - Py_XDECREF(exc_value); - Py_XDECREF(exc_tb); - return 0; - } - } - else if (limit <= 0) { - limit = PyTraceBack_LIMIT; - } - PyErr_Restore(exc_type, exc_value, exc_tb); - } - err = PyFile_WriteString("Traceback (most recent call last):\n", f); - if (!err) - err = tb_printinternal((PyTracebackObject *)v, f, limit); - return err; + int err; + PyObject *limitv; + long limit = PyTraceBack_LIMIT; + + if (v == NULL) + return 0; + if (!PyTraceBack_Check(v)) { + PyErr_BadInternalCall(); + return -1; + } + limitv = PySys_GetObject("tracebacklimit"); + if (limitv) { + PyObject *exc_type, *exc_value, *exc_tb; + + PyErr_Fetch(&exc_type, &exc_value, &exc_tb); + limit = PyLong_AsLong(limitv); + if (limit == -1 && PyErr_Occurred()) { + if (PyErr_ExceptionMatches(PyExc_OverflowError)) { + limit = PyTraceBack_LIMIT; + } + else { + Py_XDECREF(exc_type); + Py_XDECREF(exc_value); + Py_XDECREF(exc_tb); + return 0; + } + } + else if (limit <= 0) { + limit = PyTraceBack_LIMIT; + } + PyErr_Restore(exc_type, exc_value, exc_tb); + } + err = PyFile_WriteString("Traceback (most recent call last):\n", f); + if (!err) + err = tb_printinternal((PyTracebackObject *)v, f, limit); + return err; } Modified: python/branches/py3k/Tools/msi/msisupport.c ============================================================================== --- python/branches/py3k/Tools/msi/msisupport.c (original) +++ python/branches/py3k/Tools/msi/msisupport.c Sun May 9 17:52:27 2010 @@ -7,13 +7,13 @@ */ static UINT debug(MSIHANDLE hInstall, LPCSTR msg) { - MSIHANDLE hRec = MsiCreateRecord(1); - if (!hRec || MsiRecordSetStringA(hRec, 1, msg) != ERROR_SUCCESS) { - return ERROR_INSTALL_FAILURE; - } - MsiProcessMessage(hInstall, INSTALLMESSAGE_INFO, hRec); - MsiCloseHandle(hRec); - return ERROR_SUCCESS; + MSIHANDLE hRec = MsiCreateRecord(1); + if (!hRec || MsiRecordSetStringA(hRec, 1, msg) != ERROR_SUCCESS) { + return ERROR_INSTALL_FAILURE; + } + MsiProcessMessage(hInstall, INSTALLMESSAGE_INFO, hRec); + MsiCloseHandle(hRec); + return ERROR_SUCCESS; } /* Check whether the TARGETDIR exists and is a directory. @@ -22,27 +22,27 @@ UINT __declspec(dllexport) __stdcall CheckDir(MSIHANDLE hInstall) { #define PSIZE 1024 - WCHAR wpath[PSIZE]; - char path[PSIZE]; - UINT result; - DWORD size = PSIZE; - DWORD attributes; - - - result = MsiGetPropertyW(hInstall, L"TARGETDIR", wpath, &size); - if (result != ERROR_SUCCESS) - return result; - wpath[size] = L'\0'; - path[size] = L'\0'; - - attributes = GetFileAttributesW(wpath); - if (attributes == INVALID_FILE_ATTRIBUTES || - !(attributes & FILE_ATTRIBUTE_DIRECTORY)) - { - return MsiSetPropertyA(hInstall, "TargetExists", "0"); - } else { - return MsiSetPropertyA(hInstall, "TargetExists", "1"); - } + WCHAR wpath[PSIZE]; + char path[PSIZE]; + UINT result; + DWORD size = PSIZE; + DWORD attributes; + + + result = MsiGetPropertyW(hInstall, L"TARGETDIR", wpath, &size); + if (result != ERROR_SUCCESS) + return result; + wpath[size] = L'\0'; + path[size] = L'\0'; + + attributes = GetFileAttributesW(wpath); + if (attributes == INVALID_FILE_ATTRIBUTES || + !(attributes & FILE_ATTRIBUTE_DIRECTORY)) + { + return MsiSetPropertyA(hInstall, "TargetExists", "0"); + } else { + return MsiSetPropertyA(hInstall, "TargetExists", "1"); + } } /* Update the state of the REGISTRY.tcl component according to the @@ -51,41 +51,41 @@ */ UINT __declspec(dllexport) __stdcall UpdateEditIDLE(MSIHANDLE hInstall) { - INSTALLSTATE ext_old, ext_new, tcl_old, tcl_new, reg_new; - UINT result; + INSTALLSTATE ext_old, ext_new, tcl_old, tcl_new, reg_new; + UINT result; - result = MsiGetFeatureStateA(hInstall, "Extensions", &ext_old, &ext_new); - if (result != ERROR_SUCCESS) - return result; - result = MsiGetFeatureStateA(hInstall, "TclTk", &tcl_old, &tcl_new); - if (result != ERROR_SUCCESS) - return result; - - /* If the current state is Absent, and the user did not select - the feature in the UI, Installer apparently sets the "selected" - state to unknown. Update it to the current value, then. */ - if (ext_new == INSTALLSTATE_UNKNOWN) - ext_new = ext_old; - if (tcl_new == INSTALLSTATE_UNKNOWN) - tcl_new = tcl_old; - - // XXX consider current state of REGISTRY.tcl? - if (((tcl_new == INSTALLSTATE_LOCAL) || - (tcl_new == INSTALLSTATE_SOURCE) || - (tcl_new == INSTALLSTATE_DEFAULT)) && - ((ext_new == INSTALLSTATE_LOCAL) || - (ext_new == INSTALLSTATE_SOURCE) || - (ext_new == INSTALLSTATE_DEFAULT))) { - reg_new = INSTALLSTATE_SOURCE; - } else { - reg_new = INSTALLSTATE_ABSENT; - } - result = MsiSetComponentStateA(hInstall, "REGISTRY.tcl", reg_new); - return result; + result = MsiGetFeatureStateA(hInstall, "Extensions", &ext_old, &ext_new); + if (result != ERROR_SUCCESS) + return result; + result = MsiGetFeatureStateA(hInstall, "TclTk", &tcl_old, &tcl_new); + if (result != ERROR_SUCCESS) + return result; + + /* If the current state is Absent, and the user did not select + the feature in the UI, Installer apparently sets the "selected" + state to unknown. Update it to the current value, then. */ + if (ext_new == INSTALLSTATE_UNKNOWN) + ext_new = ext_old; + if (tcl_new == INSTALLSTATE_UNKNOWN) + tcl_new = tcl_old; + + // XXX consider current state of REGISTRY.tcl? + if (((tcl_new == INSTALLSTATE_LOCAL) || + (tcl_new == INSTALLSTATE_SOURCE) || + (tcl_new == INSTALLSTATE_DEFAULT)) && + ((ext_new == INSTALLSTATE_LOCAL) || + (ext_new == INSTALLSTATE_SOURCE) || + (ext_new == INSTALLSTATE_DEFAULT))) { + reg_new = INSTALLSTATE_SOURCE; + } else { + reg_new = INSTALLSTATE_ABSENT; + } + result = MsiSetComponentStateA(hInstall, "REGISTRY.tcl", reg_new); + return result; } -BOOL APIENTRY DllMain(HANDLE hModule, - DWORD ul_reason_for_call, +BOOL APIENTRY DllMain(HANDLE hModule, + DWORD ul_reason_for_call, LPVOID lpReserved) { return TRUE; From python-checkins at python.org Sun May 9 18:14:32 2010 From: python-checkins at python.org (antoine.pitrou) Date: Sun, 9 May 2010 18:14:32 +0200 (CEST) Subject: [Python-checkins] r81033 - in python/branches/release31-maint: Demo/embed/demo.c Demo/embed/loop.c Demo/pysvr/pysvr.c Include/abstract.h Include/ceval.h Include/datetime.h Include/descrobject.h Include/dictobject.h Include/object.h Include/objimpl.h Include/pyerrors.h Include/pymacconfig.h Include/pyport.h Include/pythonrun.h Include/setobject.h Include/structseq.h Include/symtable.h Include/unicodeobject.h Misc/setuid-prog.c Modules/_bisectmodule.c Modules/_codecsmodule.c Modules/_collectionsmodule.c Modules/_csv.c Modules/_ctypes/_ctypes.c Modules/_ctypes/_ctypes_test.c Modules/_ctypes/callbacks.c Modules/_ctypes/callproc.c Modules/_ctypes/cfield.c Modules/_ctypes/ctypes.h Modules/_ctypes/darwin/dlfcn_simple.c Modules/_ctypes/malloc_closure.c Modules/_ctypes/stgdict.c Modules/_curses_panel.c Modules/_dbmmodule.c Modules/_functoolsmodule.c Modules/_gdbmmodule.c Modules/_gestalt.c Modules/_heapqmodule.c Modules/_json.c Modules/_localemodule.c Modules/_lsprof.c Modules/_multiprocessing/connection.h Modules/_multiprocessing/multiprocessing.c Modules/_multiprocessing/multiprocessing.h Modules/_multiprocessing/pipe_connection.c Modules/_multiprocessing/semaphore.c Modules/_multiprocessing/socket_connection.c Modules/_multiprocessing/win32_functions.c Modules/_randommodule.c Modules/_scproxy.c Modules/_sqlite/module.c Modules/_struct.c Modules/_testcapimodule.c Modules/_threadmodule.c Modules/_tkinter.c Modules/addrinfo.h Modules/arraymodule.c Modules/audioop.c Modules/binascii.c Modules/bz2module.c Modules/cjkcodecs/_codecs_cn.c Modules/cjkcodecs/_codecs_hk.c Modules/cjkcodecs/_codecs_iso2022.c Modules/cjkcodecs/_codecs_jp.c Modules/cjkcodecs/_codecs_kr.c Modules/cjkcodecs/_codecs_tw.c Modules/cjkcodecs/alg_jisx0201.h Modules/cjkcodecs/cjkcodecs.h Modules/cjkcodecs/emu_jisx0213_2000.h Modules/cjkcodecs/multibytecodec.c Modules/cjkcodecs/multibytecodec.h Modules/cmathmodule.c Modules/cryptmodule.c Modules/datetimemodule.c Modules/errnomodule.c Modules/fcntlmodule.c Modules/fpectlmodule.c Modules/fpetestmodule.c Modules/gcmodule.c Modules/getaddrinfo.c Modules/getbuildinfo.c Modules/getnameinfo.c Modules/getpath.c Modules/grpmodule.c Modules/itertoolsmodule.c Modules/main.c Modules/mathmodule.c Modules/md5module.c Modules/mmapmodule.c Modules/nismodule.c Modules/operator.c Modules/ossaudiodev.c Modules/parsermodule.c Modules/pwdmodule.c Modules/pyexpat.c Modules/python.c Modules/readline.c Modules/resource.c Modules/rotatingtree.c Modules/selectmodule.c Modules/sha1module.c Modules/sha256module.c Modules/sha512module.c Modules/signalmodule.c Modules/socketmodule.c Modules/socketmodule.h Modules/spwdmodule.c Modules/symtablemodule.c Modules/syslogmodule.c Modules/termios.c Modules/testcapi_long.h Modules/timemodule.c Modules/tkappinit.c Modules/unicodedata.c Modules/xxmodule.c Modules/xxsubtype.c Modules/zipimport.c Modules/zlibmodule.c Objects/abstract.c Objects/boolobject.c Objects/bytes_methods.c Objects/bytesobject.c Objects/cellobject.c Objects/classobject.c Objects/codeobject.c Objects/complexobject.c Objects/descrobject.c Objects/dictobject.c Objects/enumobject.c Objects/exceptions.c Objects/fileobject.c Objects/floatobject.c Objects/frameobject.c Objects/funcobject.c Objects/genobject.c Objects/iterobject.c Objects/listobject.c Objects/longobject.c Objects/methodobject.c Objects/moduleobject.c Objects/object.c Objects/obmalloc.c Objects/rangeobject.c Objects/setobject.c Objects/sliceobject.c Objects/stringlib/eq.h Objects/stringlib/partition.h Objects/stringlib/string_format.h Objects/stringlib/transmogrify.h Objects/structseq.c Objects/tupleobject.c Objects/typeobject.c Objects/unicodectype.c Objects/weakrefobject.c PC/VS7.1/make_buildinfo.c PC/VS8.0/make_buildinfo.c PC/_msi.c PC/_subprocess.c PC/bdist_wininst/archive.h PC/bdist_wininst/extract.c PC/bdist_wininst/install.c PC/config.c PC/dl_nt.c PC/errmap.h PC/example_nt/example.c PC/frozen_dllmain.c PC/generrmap.c PC/getpathp.c PC/import_nt.c PC/make_versioninfo.c PC/msvcrtmodule.c PC/os2emx/config.c PC/os2emx/dlfcn.c PC/os2emx/dllentry.c PC/os2emx/getpathp.c PC/os2emx/pythonpm.c PC/os2vacpp/getpathp.c PC/winreg.c PC/winsound.c PCbuild/make_buildinfo.c Parser/acceler.c Parser/bitset.c Parser/firstsets.c Parser/grammar.c Parser/grammar1.c Parser/intrcheck.c Parser/listnode.c Parser/metagrammar.c Parser/myreadline.c Parser/node.c Parser/parser.c Parser/parsetok.c Parser/pgen.c Parser/pgenmain.c Parser/printgrammar.c Parser/tokenizer.c Parser/tokenizer.h Python/_warnings.c Python/asdl.c Python/ast.c Python/bltinmodule.c Python/ceval.c Python/codecs.c Python/compile.c Python/dynload_aix.c Python/dynload_atheos.c Python/dynload_hpux.c Python/dynload_next.c Python/dynload_os2.c Python/dynload_shlib.c Python/dynload_win.c Python/errors.c Python/frozen.c Python/frozenmain.c Python/future.c Python/getargs.c Python/getcwd.c Python/getopt.c Python/import.c Python/importdl.c Python/importdl.h Python/makeopcodetargets.py Python/marshal.c Python/modsupport.c Python/mysnprintf.c Python/mystrtoul.c Python/opcode_targets.h Python/peephole.c Python/pyarena.c Python/pymath.c Python/pystate.c Python/pystrcmp.c Python/pystrtod.c Python/pythonrun.c Python/structmember.c Python/symtable.c Python/sysmodule.c Python/thread.c Python/thread_atheos.h Python/thread_cthread.h Python/thread_foobar.h Python/thread_lwp.h Python/thread_nt.h Python/thread_os2.h Python/thread_pth.h Python/thread_pthread.h Python/thread_sgi.h Python/thread_solaris.h Python/thread_wince.h Python/traceback.c Tools/msi/msisupport.c Message-ID: <20100509161432.618E8FA8F@mail.python.org> Author: antoine.pitrou Date: Sun May 9 18:14:21 2010 New Revision: 81033 Log: Recorded merge of revisions 81032 via svnmerge from svn+ssh://pythondev at svn.python.org/python/branches/py3k ................ r81032 | antoine.pitrou | 2010-05-09 17:52:27 +0200 (dim., 09 mai 2010) | 9 lines Recorded merge of revisions 81029 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r81029 | antoine.pitrou | 2010-05-09 16:46:46 +0200 (dim., 09 mai 2010) | 3 lines Untabify C files. Will watch buildbots. ........ ................ Modified: python/branches/release31-maint/ (props changed) python/branches/release31-maint/Demo/embed/demo.c python/branches/release31-maint/Demo/embed/loop.c python/branches/release31-maint/Demo/pysvr/pysvr.c python/branches/release31-maint/Include/abstract.h python/branches/release31-maint/Include/ceval.h python/branches/release31-maint/Include/datetime.h python/branches/release31-maint/Include/descrobject.h python/branches/release31-maint/Include/dictobject.h python/branches/release31-maint/Include/object.h python/branches/release31-maint/Include/objimpl.h python/branches/release31-maint/Include/pyerrors.h python/branches/release31-maint/Include/pymacconfig.h python/branches/release31-maint/Include/pyport.h python/branches/release31-maint/Include/pythonrun.h python/branches/release31-maint/Include/setobject.h python/branches/release31-maint/Include/structseq.h python/branches/release31-maint/Include/symtable.h python/branches/release31-maint/Include/unicodeobject.h python/branches/release31-maint/Misc/setuid-prog.c python/branches/release31-maint/Modules/_bisectmodule.c python/branches/release31-maint/Modules/_codecsmodule.c python/branches/release31-maint/Modules/_collectionsmodule.c python/branches/release31-maint/Modules/_csv.c python/branches/release31-maint/Modules/_ctypes/_ctypes.c python/branches/release31-maint/Modules/_ctypes/_ctypes_test.c python/branches/release31-maint/Modules/_ctypes/callbacks.c python/branches/release31-maint/Modules/_ctypes/callproc.c python/branches/release31-maint/Modules/_ctypes/cfield.c python/branches/release31-maint/Modules/_ctypes/ctypes.h python/branches/release31-maint/Modules/_ctypes/darwin/dlfcn_simple.c python/branches/release31-maint/Modules/_ctypes/malloc_closure.c python/branches/release31-maint/Modules/_ctypes/stgdict.c python/branches/release31-maint/Modules/_curses_panel.c python/branches/release31-maint/Modules/_dbmmodule.c python/branches/release31-maint/Modules/_functoolsmodule.c python/branches/release31-maint/Modules/_gdbmmodule.c python/branches/release31-maint/Modules/_gestalt.c python/branches/release31-maint/Modules/_heapqmodule.c python/branches/release31-maint/Modules/_json.c python/branches/release31-maint/Modules/_localemodule.c python/branches/release31-maint/Modules/_lsprof.c python/branches/release31-maint/Modules/_multiprocessing/connection.h python/branches/release31-maint/Modules/_multiprocessing/multiprocessing.c python/branches/release31-maint/Modules/_multiprocessing/multiprocessing.h python/branches/release31-maint/Modules/_multiprocessing/pipe_connection.c python/branches/release31-maint/Modules/_multiprocessing/semaphore.c python/branches/release31-maint/Modules/_multiprocessing/socket_connection.c python/branches/release31-maint/Modules/_multiprocessing/win32_functions.c python/branches/release31-maint/Modules/_randommodule.c python/branches/release31-maint/Modules/_scproxy.c python/branches/release31-maint/Modules/_sqlite/module.c python/branches/release31-maint/Modules/_struct.c python/branches/release31-maint/Modules/_testcapimodule.c python/branches/release31-maint/Modules/_threadmodule.c python/branches/release31-maint/Modules/_tkinter.c python/branches/release31-maint/Modules/addrinfo.h python/branches/release31-maint/Modules/arraymodule.c python/branches/release31-maint/Modules/audioop.c python/branches/release31-maint/Modules/binascii.c python/branches/release31-maint/Modules/bz2module.c python/branches/release31-maint/Modules/cjkcodecs/_codecs_cn.c python/branches/release31-maint/Modules/cjkcodecs/_codecs_hk.c python/branches/release31-maint/Modules/cjkcodecs/_codecs_iso2022.c python/branches/release31-maint/Modules/cjkcodecs/_codecs_jp.c python/branches/release31-maint/Modules/cjkcodecs/_codecs_kr.c python/branches/release31-maint/Modules/cjkcodecs/_codecs_tw.c python/branches/release31-maint/Modules/cjkcodecs/alg_jisx0201.h python/branches/release31-maint/Modules/cjkcodecs/cjkcodecs.h python/branches/release31-maint/Modules/cjkcodecs/emu_jisx0213_2000.h python/branches/release31-maint/Modules/cjkcodecs/multibytecodec.c python/branches/release31-maint/Modules/cjkcodecs/multibytecodec.h python/branches/release31-maint/Modules/cmathmodule.c python/branches/release31-maint/Modules/cryptmodule.c python/branches/release31-maint/Modules/datetimemodule.c python/branches/release31-maint/Modules/errnomodule.c python/branches/release31-maint/Modules/fcntlmodule.c python/branches/release31-maint/Modules/fpectlmodule.c python/branches/release31-maint/Modules/fpetestmodule.c python/branches/release31-maint/Modules/gcmodule.c python/branches/release31-maint/Modules/getaddrinfo.c python/branches/release31-maint/Modules/getbuildinfo.c python/branches/release31-maint/Modules/getnameinfo.c python/branches/release31-maint/Modules/getpath.c python/branches/release31-maint/Modules/grpmodule.c python/branches/release31-maint/Modules/itertoolsmodule.c python/branches/release31-maint/Modules/main.c python/branches/release31-maint/Modules/mathmodule.c python/branches/release31-maint/Modules/md5module.c python/branches/release31-maint/Modules/mmapmodule.c python/branches/release31-maint/Modules/nismodule.c python/branches/release31-maint/Modules/operator.c python/branches/release31-maint/Modules/ossaudiodev.c python/branches/release31-maint/Modules/parsermodule.c python/branches/release31-maint/Modules/pwdmodule.c python/branches/release31-maint/Modules/pyexpat.c python/branches/release31-maint/Modules/python.c python/branches/release31-maint/Modules/readline.c python/branches/release31-maint/Modules/resource.c python/branches/release31-maint/Modules/rotatingtree.c python/branches/release31-maint/Modules/selectmodule.c python/branches/release31-maint/Modules/sha1module.c python/branches/release31-maint/Modules/sha256module.c python/branches/release31-maint/Modules/sha512module.c python/branches/release31-maint/Modules/signalmodule.c python/branches/release31-maint/Modules/socketmodule.c python/branches/release31-maint/Modules/socketmodule.h python/branches/release31-maint/Modules/spwdmodule.c python/branches/release31-maint/Modules/symtablemodule.c python/branches/release31-maint/Modules/syslogmodule.c python/branches/release31-maint/Modules/termios.c python/branches/release31-maint/Modules/testcapi_long.h python/branches/release31-maint/Modules/timemodule.c python/branches/release31-maint/Modules/tkappinit.c python/branches/release31-maint/Modules/unicodedata.c python/branches/release31-maint/Modules/xxmodule.c python/branches/release31-maint/Modules/xxsubtype.c python/branches/release31-maint/Modules/zipimport.c python/branches/release31-maint/Modules/zlibmodule.c python/branches/release31-maint/Objects/abstract.c python/branches/release31-maint/Objects/boolobject.c python/branches/release31-maint/Objects/bytes_methods.c python/branches/release31-maint/Objects/bytesobject.c python/branches/release31-maint/Objects/cellobject.c python/branches/release31-maint/Objects/classobject.c python/branches/release31-maint/Objects/codeobject.c python/branches/release31-maint/Objects/complexobject.c python/branches/release31-maint/Objects/descrobject.c python/branches/release31-maint/Objects/dictobject.c python/branches/release31-maint/Objects/enumobject.c python/branches/release31-maint/Objects/exceptions.c python/branches/release31-maint/Objects/fileobject.c python/branches/release31-maint/Objects/floatobject.c python/branches/release31-maint/Objects/frameobject.c python/branches/release31-maint/Objects/funcobject.c python/branches/release31-maint/Objects/genobject.c python/branches/release31-maint/Objects/iterobject.c python/branches/release31-maint/Objects/listobject.c python/branches/release31-maint/Objects/longobject.c python/branches/release31-maint/Objects/methodobject.c python/branches/release31-maint/Objects/moduleobject.c python/branches/release31-maint/Objects/object.c python/branches/release31-maint/Objects/obmalloc.c python/branches/release31-maint/Objects/rangeobject.c python/branches/release31-maint/Objects/setobject.c python/branches/release31-maint/Objects/sliceobject.c python/branches/release31-maint/Objects/stringlib/eq.h python/branches/release31-maint/Objects/stringlib/partition.h python/branches/release31-maint/Objects/stringlib/string_format.h python/branches/release31-maint/Objects/stringlib/transmogrify.h python/branches/release31-maint/Objects/structseq.c python/branches/release31-maint/Objects/tupleobject.c python/branches/release31-maint/Objects/typeobject.c python/branches/release31-maint/Objects/unicodectype.c python/branches/release31-maint/Objects/weakrefobject.c python/branches/release31-maint/PC/VS7.1/make_buildinfo.c python/branches/release31-maint/PC/VS8.0/make_buildinfo.c python/branches/release31-maint/PC/_msi.c python/branches/release31-maint/PC/_subprocess.c python/branches/release31-maint/PC/bdist_wininst/archive.h python/branches/release31-maint/PC/bdist_wininst/extract.c python/branches/release31-maint/PC/bdist_wininst/install.c python/branches/release31-maint/PC/config.c python/branches/release31-maint/PC/dl_nt.c python/branches/release31-maint/PC/errmap.h python/branches/release31-maint/PC/example_nt/example.c python/branches/release31-maint/PC/frozen_dllmain.c python/branches/release31-maint/PC/generrmap.c python/branches/release31-maint/PC/getpathp.c python/branches/release31-maint/PC/import_nt.c python/branches/release31-maint/PC/make_versioninfo.c python/branches/release31-maint/PC/msvcrtmodule.c python/branches/release31-maint/PC/os2emx/config.c python/branches/release31-maint/PC/os2emx/dlfcn.c python/branches/release31-maint/PC/os2emx/dllentry.c python/branches/release31-maint/PC/os2emx/getpathp.c python/branches/release31-maint/PC/os2emx/pythonpm.c python/branches/release31-maint/PC/os2vacpp/getpathp.c python/branches/release31-maint/PC/winreg.c python/branches/release31-maint/PC/winsound.c python/branches/release31-maint/PCbuild/make_buildinfo.c python/branches/release31-maint/Parser/acceler.c python/branches/release31-maint/Parser/bitset.c python/branches/release31-maint/Parser/firstsets.c python/branches/release31-maint/Parser/grammar.c python/branches/release31-maint/Parser/grammar1.c python/branches/release31-maint/Parser/intrcheck.c python/branches/release31-maint/Parser/listnode.c python/branches/release31-maint/Parser/metagrammar.c python/branches/release31-maint/Parser/myreadline.c python/branches/release31-maint/Parser/node.c python/branches/release31-maint/Parser/parser.c python/branches/release31-maint/Parser/parsetok.c python/branches/release31-maint/Parser/pgen.c python/branches/release31-maint/Parser/pgenmain.c python/branches/release31-maint/Parser/printgrammar.c python/branches/release31-maint/Parser/tokenizer.c python/branches/release31-maint/Parser/tokenizer.h python/branches/release31-maint/Python/_warnings.c python/branches/release31-maint/Python/asdl.c python/branches/release31-maint/Python/ast.c python/branches/release31-maint/Python/bltinmodule.c python/branches/release31-maint/Python/ceval.c python/branches/release31-maint/Python/codecs.c python/branches/release31-maint/Python/compile.c python/branches/release31-maint/Python/dynload_aix.c python/branches/release31-maint/Python/dynload_atheos.c python/branches/release31-maint/Python/dynload_hpux.c python/branches/release31-maint/Python/dynload_next.c python/branches/release31-maint/Python/dynload_os2.c python/branches/release31-maint/Python/dynload_shlib.c python/branches/release31-maint/Python/dynload_win.c python/branches/release31-maint/Python/errors.c python/branches/release31-maint/Python/frozen.c python/branches/release31-maint/Python/frozenmain.c python/branches/release31-maint/Python/future.c python/branches/release31-maint/Python/getargs.c python/branches/release31-maint/Python/getcwd.c python/branches/release31-maint/Python/getopt.c python/branches/release31-maint/Python/import.c python/branches/release31-maint/Python/importdl.c python/branches/release31-maint/Python/importdl.h python/branches/release31-maint/Python/makeopcodetargets.py python/branches/release31-maint/Python/marshal.c python/branches/release31-maint/Python/modsupport.c python/branches/release31-maint/Python/mysnprintf.c python/branches/release31-maint/Python/mystrtoul.c python/branches/release31-maint/Python/opcode_targets.h python/branches/release31-maint/Python/peephole.c python/branches/release31-maint/Python/pyarena.c python/branches/release31-maint/Python/pymath.c python/branches/release31-maint/Python/pystate.c python/branches/release31-maint/Python/pystrcmp.c python/branches/release31-maint/Python/pystrtod.c python/branches/release31-maint/Python/pythonrun.c python/branches/release31-maint/Python/structmember.c python/branches/release31-maint/Python/symtable.c python/branches/release31-maint/Python/sysmodule.c python/branches/release31-maint/Python/thread.c python/branches/release31-maint/Python/thread_atheos.h python/branches/release31-maint/Python/thread_cthread.h python/branches/release31-maint/Python/thread_foobar.h python/branches/release31-maint/Python/thread_lwp.h python/branches/release31-maint/Python/thread_nt.h python/branches/release31-maint/Python/thread_os2.h python/branches/release31-maint/Python/thread_pth.h python/branches/release31-maint/Python/thread_pthread.h python/branches/release31-maint/Python/thread_sgi.h python/branches/release31-maint/Python/thread_solaris.h python/branches/release31-maint/Python/thread_wince.h python/branches/release31-maint/Python/traceback.c python/branches/release31-maint/Tools/msi/msisupport.c Modified: python/branches/release31-maint/Demo/embed/demo.c ============================================================================== --- python/branches/release31-maint/Demo/embed/demo.c (original) +++ python/branches/release31-maint/Demo/embed/demo.c Sun May 9 18:14:21 2010 @@ -6,44 +6,44 @@ main(int argc, char **argv) { - /* Ignore passed-in argc/argv. If desired, conversion - should use mbstowcs to convert them. */ - wchar_t *args[] = {L"embed", L"hello", 0}; - - /* Pass argv[0] to the Python interpreter */ - Py_SetProgramName(args[0]); - - /* Add a static module */ - PyImport_AppendInittab("xyzzy", PyInit_xyzzy); - - /* Initialize the Python interpreter. Required. */ - Py_Initialize(); - - /* Define sys.argv. It is up to the application if you - want this; you can also let it undefined (since the Python - code is generally not a main program it has no business - touching sys.argv...) */ - PySys_SetArgv(2, args); - - /* Do some application specific code */ - printf("Hello, brave new world\n\n"); - - /* Execute some Python statements (in module __main__) */ - PyRun_SimpleString("import sys\n"); - PyRun_SimpleString("print(sys.builtin_module_names)\n"); - PyRun_SimpleString("print(sys.modules.keys())\n"); - PyRun_SimpleString("print(sys.executable)\n"); - PyRun_SimpleString("print(sys.argv)\n"); - - /* Note that you can call any public function of the Python - interpreter here, e.g. call_object(). */ - - /* Some more application specific code */ - printf("\nGoodbye, cruel world\n"); - - /* Exit, cleaning up the interpreter */ - Py_Exit(0); - /*NOTREACHED*/ + /* Ignore passed-in argc/argv. If desired, conversion + should use mbstowcs to convert them. */ + wchar_t *args[] = {L"embed", L"hello", 0}; + + /* Pass argv[0] to the Python interpreter */ + Py_SetProgramName(args[0]); + + /* Add a static module */ + PyImport_AppendInittab("xyzzy", PyInit_xyzzy); + + /* Initialize the Python interpreter. Required. */ + Py_Initialize(); + + /* Define sys.argv. It is up to the application if you + want this; you can also let it undefined (since the Python + code is generally not a main program it has no business + touching sys.argv...) */ + PySys_SetArgv(2, args); + + /* Do some application specific code */ + printf("Hello, brave new world\n\n"); + + /* Execute some Python statements (in module __main__) */ + PyRun_SimpleString("import sys\n"); + PyRun_SimpleString("print(sys.builtin_module_names)\n"); + PyRun_SimpleString("print(sys.modules.keys())\n"); + PyRun_SimpleString("print(sys.executable)\n"); + PyRun_SimpleString("print(sys.argv)\n"); + + /* Note that you can call any public function of the Python + interpreter here, e.g. call_object(). */ + + /* Some more application specific code */ + printf("\nGoodbye, cruel world\n"); + + /* Exit, cleaning up the interpreter */ + Py_Exit(0); + /*NOTREACHED*/ } /* A static module */ @@ -52,29 +52,29 @@ static PyObject * xyzzy_foo(PyObject *self, PyObject* args) { - return PyLong_FromLong(42L); + return PyLong_FromLong(42L); } static PyMethodDef xyzzy_methods[] = { - {"foo", xyzzy_foo, METH_NOARGS, - "Return the meaning of everything."}, - {NULL, NULL} /* sentinel */ + {"foo", xyzzy_foo, METH_NOARGS, + "Return the meaning of everything."}, + {NULL, NULL} /* sentinel */ }; static struct PyModuleDef xyzzymodule = { - {}, /* m_base */ - "xyzzy", /* m_name */ - 0, /* m_doc */ - 0, /* m_size */ - xyzzy_methods, /* m_methods */ - 0, /* m_reload */ - 0, /* m_traverse */ - 0, /* m_clear */ - 0, /* m_free */ + {}, /* m_base */ + "xyzzy", /* m_name */ + 0, /* m_doc */ + 0, /* m_size */ + xyzzy_methods, /* m_methods */ + 0, /* m_reload */ + 0, /* m_traverse */ + 0, /* m_clear */ + 0, /* m_free */ }; PyObject* PyInit_xyzzy(void) { - return PyModule_Create(&xyzzymodule); + return PyModule_Create(&xyzzymodule); } Modified: python/branches/release31-maint/Demo/embed/loop.c ============================================================================== --- python/branches/release31-maint/Demo/embed/loop.c (original) +++ python/branches/release31-maint/Demo/embed/loop.c Sun May 9 18:14:21 2010 @@ -6,28 +6,28 @@ main(int argc, char **argv) { - int count = -1; - char *command; + int count = -1; + char *command; - if (argc < 2 || argc > 3) { - fprintf(stderr, "usage: loop [count]\n"); - exit(2); - } - command = argv[1]; - - if (argc == 3) { - count = atoi(argv[2]); - } - - Py_SetProgramName(argv[0]); - - /* uncomment this if you don't want to load site.py */ - /* Py_NoSiteFlag = 1; */ - - while (count == -1 || --count >= 0 ) { - Py_Initialize(); - PyRun_SimpleString(command); - Py_Finalize(); - } - return 0; + if (argc < 2 || argc > 3) { + fprintf(stderr, "usage: loop [count]\n"); + exit(2); + } + command = argv[1]; + + if (argc == 3) { + count = atoi(argv[2]); + } + + Py_SetProgramName(argv[0]); + + /* uncomment this if you don't want to load site.py */ + /* Py_NoSiteFlag = 1; */ + + while (count == -1 || --count >= 0 ) { + Py_Initialize(); + PyRun_SimpleString(command); + Py_Finalize(); + } + return 0; } Modified: python/branches/release31-maint/Demo/pysvr/pysvr.c ============================================================================== --- python/branches/release31-maint/Demo/pysvr/pysvr.c (original) +++ python/branches/release31-maint/Demo/pysvr/pysvr.c Sun May 9 18:14:21 2010 @@ -34,8 +34,8 @@ #endif struct workorder { - int conn; - struct sockaddr_in addr; + int conn; + struct sockaddr_in addr; }; /* Forward */ @@ -55,40 +55,40 @@ main(int argc, char **argv) { - int port = PORT; - int c; + int port = PORT; + int c; - if (argc > 0 && argv[0] != NULL && argv[0][0] != '\0') - progname = argv[0]; + if (argc > 0 && argv[0] != NULL && argv[0][0] != '\0') + progname = argv[0]; - while ((c = getopt(argc, argv, "v")) != EOF) { - switch (c) { - case 'v': - Py_VerboseFlag++; - break; - default: - usage(); - } - } - - if (optind < argc) { - if (optind+1 < argc) { - oprogname(); - fprintf(stderr, "too many arguments\n"); - usage(); - } - port = atoi(argv[optind]); - if (port <= 0) { - fprintf(stderr, "bad port (%s)\n", argv[optind]); - usage(); - } - } + while ((c = getopt(argc, argv, "v")) != EOF) { + switch (c) { + case 'v': + Py_VerboseFlag++; + break; + default: + usage(); + } + } + + if (optind < argc) { + if (optind+1 < argc) { + oprogname(); + fprintf(stderr, "too many arguments\n"); + usage(); + } + port = atoi(argv[optind]); + if (port <= 0) { + fprintf(stderr, "bad port (%s)\n", argv[optind]); + usage(); + } + } - main_thread(port); + main_thread(port); - fprintf(stderr, "Bye.\n"); + fprintf(stderr, "Bye.\n"); - exit(0); + exit(0); } static char usage_line[] = "usage: %s [port]\n"; @@ -96,120 +96,120 @@ static void usage(void) { - fprintf(stderr, usage_line, progname); - exit(2); + fprintf(stderr, usage_line, progname); + exit(2); } static void main_thread(int port) { - int sock, conn, size, i; - struct sockaddr_in addr, clientaddr; + int sock, conn, size, i; + struct sockaddr_in addr, clientaddr; - sock = socket(PF_INET, SOCK_STREAM, 0); - if (sock < 0) { - oprogname(); - perror("can't create socket"); - exit(1); - } + sock = socket(PF_INET, SOCK_STREAM, 0); + if (sock < 0) { + oprogname(); + perror("can't create socket"); + exit(1); + } #ifdef SO_REUSEADDR - i = 1; - setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, (char *) &i, sizeof i); + i = 1; + setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, (char *) &i, sizeof i); #endif - memset((char *)&addr, '\0', sizeof addr); - addr.sin_family = AF_INET; - addr.sin_port = htons(port); - addr.sin_addr.s_addr = 0L; - if (bind(sock, (struct sockaddr *)&addr, sizeof addr) < 0) { - oprogname(); - perror("can't bind socket to address"); - exit(1); - } - - if (listen(sock, 5) < 0) { - oprogname(); - perror("can't listen on socket"); - exit(1); - } - - fprintf(stderr, "Listening on port %d...\n", port); - - for (i = 0; ; i++) { - size = sizeof clientaddr; - memset((char *) &clientaddr, '\0', size); - conn = accept(sock, (struct sockaddr *) &clientaddr, &size); - if (conn < 0) { - oprogname(); - perror("can't accept connection from socket"); - exit(1); - } - - size = sizeof addr; - memset((char *) &addr, '\0', size); - if (getsockname(conn, (struct sockaddr *)&addr, &size) < 0) { - oprogname(); - perror("can't get socket name of connection"); - exit(1); - } - if (clientaddr.sin_addr.s_addr != addr.sin_addr.s_addr) { - oprogname(); - perror("connection from non-local host refused"); - fprintf(stderr, "(addr=%lx, clientaddr=%lx)\n", - ntohl(addr.sin_addr.s_addr), - ntohl(clientaddr.sin_addr.s_addr)); - close(conn); - continue; - } - if (i == 4) { - close(conn); - break; - } - create_thread(conn, &clientaddr); - } - - close(sock); - - if (gtstate) { - PyEval_AcquireThread(gtstate); - gtstate = NULL; - Py_Finalize(); - /* And a second time, just because we can. */ - Py_Finalize(); /* This should be harmless. */ - } - exit(0); + memset((char *)&addr, '\0', sizeof addr); + addr.sin_family = AF_INET; + addr.sin_port = htons(port); + addr.sin_addr.s_addr = 0L; + if (bind(sock, (struct sockaddr *)&addr, sizeof addr) < 0) { + oprogname(); + perror("can't bind socket to address"); + exit(1); + } + + if (listen(sock, 5) < 0) { + oprogname(); + perror("can't listen on socket"); + exit(1); + } + + fprintf(stderr, "Listening on port %d...\n", port); + + for (i = 0; ; i++) { + size = sizeof clientaddr; + memset((char *) &clientaddr, '\0', size); + conn = accept(sock, (struct sockaddr *) &clientaddr, &size); + if (conn < 0) { + oprogname(); + perror("can't accept connection from socket"); + exit(1); + } + + size = sizeof addr; + memset((char *) &addr, '\0', size); + if (getsockname(conn, (struct sockaddr *)&addr, &size) < 0) { + oprogname(); + perror("can't get socket name of connection"); + exit(1); + } + if (clientaddr.sin_addr.s_addr != addr.sin_addr.s_addr) { + oprogname(); + perror("connection from non-local host refused"); + fprintf(stderr, "(addr=%lx, clientaddr=%lx)\n", + ntohl(addr.sin_addr.s_addr), + ntohl(clientaddr.sin_addr.s_addr)); + close(conn); + continue; + } + if (i == 4) { + close(conn); + break; + } + create_thread(conn, &clientaddr); + } + + close(sock); + + if (gtstate) { + PyEval_AcquireThread(gtstate); + gtstate = NULL; + Py_Finalize(); + /* And a second time, just because we can. */ + Py_Finalize(); /* This should be harmless. */ + } + exit(0); } static void create_thread(int conn, struct sockaddr_in *addr) { - struct workorder *work; - pthread_t tdata; + struct workorder *work; + pthread_t tdata; - work = malloc(sizeof(struct workorder)); - if (work == NULL) { - oprogname(); - fprintf(stderr, "out of memory for thread.\n"); - close(conn); - return; - } - work->conn = conn; - work->addr = *addr; - - init_python(); - - if (pthread_create(&tdata, NULL, (void *)service_thread, work) < 0) { - oprogname(); - perror("can't create new thread"); - close(conn); - return; - } - - if (pthread_detach(tdata) < 0) { - oprogname(); - perror("can't detach from thread"); - } + work = malloc(sizeof(struct workorder)); + if (work == NULL) { + oprogname(); + fprintf(stderr, "out of memory for thread.\n"); + close(conn); + return; + } + work->conn = conn; + work->addr = *addr; + + init_python(); + + if (pthread_create(&tdata, NULL, (void *)service_thread, work) < 0) { + oprogname(); + perror("can't create new thread"); + close(conn); + return; + } + + if (pthread_detach(tdata) < 0) { + oprogname(); + perror("can't detach from thread"); + } } static PyThreadState *the_tstate; @@ -219,152 +219,152 @@ static void init_python(void) { - if (gtstate) - return; - Py_Initialize(); /* Initialize the interpreter */ - PyEval_InitThreads(); /* Create (and acquire) the interpreter lock */ - gtstate = PyEval_SaveThread(); /* Release the thread state */ + if (gtstate) + return; + Py_Initialize(); /* Initialize the interpreter */ + PyEval_InitThreads(); /* Create (and acquire) the interpreter lock */ + gtstate = PyEval_SaveThread(); /* Release the thread state */ } static void * service_thread(struct workorder *work) { - FILE *input, *output; + FILE *input, *output; - fprintf(stderr, "Start thread for connection %d.\n", work->conn); + fprintf(stderr, "Start thread for connection %d.\n", work->conn); - ps(); + ps(); - input = fdopen(work->conn, "r"); - if (input == NULL) { - oprogname(); - perror("can't create input stream"); - goto done; - } - - output = fdopen(work->conn, "w"); - if (output == NULL) { - oprogname(); - perror("can't create output stream"); - fclose(input); - goto done; - } + input = fdopen(work->conn, "r"); + if (input == NULL) { + oprogname(); + perror("can't create input stream"); + goto done; + } + + output = fdopen(work->conn, "w"); + if (output == NULL) { + oprogname(); + perror("can't create output stream"); + fclose(input); + goto done; + } - setvbuf(input, NULL, _IONBF, 0); - setvbuf(output, NULL, _IONBF, 0); + setvbuf(input, NULL, _IONBF, 0); + setvbuf(output, NULL, _IONBF, 0); - run_interpreter(input, output); + run_interpreter(input, output); - fclose(input); - fclose(output); + fclose(input); + fclose(output); done: - fprintf(stderr, "End thread for connection %d.\n", work->conn); - close(work->conn); - free(work); + fprintf(stderr, "End thread for connection %d.\n", work->conn); + close(work->conn); + free(work); } static void oprogname(void) { - int save = errno; - fprintf(stderr, "%s: ", progname); - errno = save; + int save = errno; + fprintf(stderr, "%s: ", progname); + errno = save; } static void run_interpreter(FILE *input, FILE *output) { - PyThreadState *tstate; - PyObject *new_stdin, *new_stdout; - PyObject *mainmod, *globals; - char buffer[1000]; - char *p, *q; - int n, end; - - PyEval_AcquireLock(); - tstate = Py_NewInterpreter(); - if (tstate == NULL) { - fprintf(output, "Sorry -- can't create an interpreter\n"); - return; - } - - mainmod = PyImport_AddModule("__main__"); - globals = PyModule_GetDict(mainmod); - Py_INCREF(globals); - - new_stdin = PyFile_FromFile(input, "", "r", NULL); - new_stdout = PyFile_FromFile(output, "", "w", NULL); - - PySys_SetObject("stdin", new_stdin); - PySys_SetObject("stdout", new_stdout); - PySys_SetObject("stderr", new_stdout); - - for (n = 1; !PyErr_Occurred(); n++) { - Py_BEGIN_ALLOW_THREADS - fprintf(output, "%d> ", n); - p = fgets(buffer, sizeof buffer, input); - Py_END_ALLOW_THREADS - - if (p == NULL) - break; - if (p[0] == '\377' && p[1] == '\354') - break; - - q = strrchr(p, '\r'); - if (q && q[1] == '\n' && q[2] == '\0') { - *q++ = '\n'; - *q++ = '\0'; - } - - while (*p && isspace(*p)) - p++; - if (p[0] == '#' || p[0] == '\0') - continue; - - end = run_command(buffer, globals); - if (end < 0) - PyErr_Print(); - - if (end) - break; - } - - Py_XDECREF(globals); - Py_XDECREF(new_stdin); - Py_XDECREF(new_stdout); + PyThreadState *tstate; + PyObject *new_stdin, *new_stdout; + PyObject *mainmod, *globals; + char buffer[1000]; + char *p, *q; + int n, end; + + PyEval_AcquireLock(); + tstate = Py_NewInterpreter(); + if (tstate == NULL) { + fprintf(output, "Sorry -- can't create an interpreter\n"); + return; + } + + mainmod = PyImport_AddModule("__main__"); + globals = PyModule_GetDict(mainmod); + Py_INCREF(globals); + + new_stdin = PyFile_FromFile(input, "", "r", NULL); + new_stdout = PyFile_FromFile(output, "", "w", NULL); + + PySys_SetObject("stdin", new_stdin); + PySys_SetObject("stdout", new_stdout); + PySys_SetObject("stderr", new_stdout); + + for (n = 1; !PyErr_Occurred(); n++) { + Py_BEGIN_ALLOW_THREADS + fprintf(output, "%d> ", n); + p = fgets(buffer, sizeof buffer, input); + Py_END_ALLOW_THREADS + + if (p == NULL) + break; + if (p[0] == '\377' && p[1] == '\354') + break; + + q = strrchr(p, '\r'); + if (q && q[1] == '\n' && q[2] == '\0') { + *q++ = '\n'; + *q++ = '\0'; + } + + while (*p && isspace(*p)) + p++; + if (p[0] == '#' || p[0] == '\0') + continue; + + end = run_command(buffer, globals); + if (end < 0) + PyErr_Print(); + + if (end) + break; + } + + Py_XDECREF(globals); + Py_XDECREF(new_stdin); + Py_XDECREF(new_stdout); - Py_EndInterpreter(tstate); - PyEval_ReleaseLock(); + Py_EndInterpreter(tstate); + PyEval_ReleaseLock(); - fprintf(output, "Goodbye!\n"); + fprintf(output, "Goodbye!\n"); } static int run_command(char *buffer, PyObject *globals) { - PyObject *m, *d, *v; - fprintf(stderr, "run_command: %s", buffer); - if (strchr(buffer, '\n') == NULL) - fprintf(stderr, "\n"); - v = PyRun_String(buffer, Py_single_input, globals, globals); - if (v == NULL) { - if (PyErr_Occurred() == PyExc_SystemExit) { - PyErr_Clear(); - return 1; - } - PyErr_Print(); - return 0; - } - Py_DECREF(v); - return 0; + PyObject *m, *d, *v; + fprintf(stderr, "run_command: %s", buffer); + if (strchr(buffer, '\n') == NULL) + fprintf(stderr, "\n"); + v = PyRun_String(buffer, Py_single_input, globals, globals); + if (v == NULL) { + if (PyErr_Occurred() == PyExc_SystemExit) { + PyErr_Clear(); + return 1; + } + PyErr_Print(); + return 0; + } + Py_DECREF(v); + return 0; } static void ps(void) { - char buffer[100]; - PyOS_snprintf(buffer, sizeof(buffer), - "ps -l -p %d ob_type->tp_as_buffer != NULL) && \ - ((obj)->ob_type->tp_as_buffer->bf_getbuffer != NULL)) + (((obj)->ob_type->tp_as_buffer != NULL) && \ + ((obj)->ob_type->tp_as_buffer->bf_getbuffer != NULL)) - /* Return 1 if the getbuffer function is available, otherwise - return 0 */ + /* Return 1 if the getbuffer function is available, otherwise + return 0 */ - PyAPI_FUNC(int) PyObject_GetBuffer(PyObject *obj, Py_buffer *view, - int flags); + PyAPI_FUNC(int) PyObject_GetBuffer(PyObject *obj, Py_buffer *view, + int flags); - /* This is a C-API version of the getbuffer function call. It checks - to make sure object has the required function pointer and issues the - call. Returns -1 and raises an error on failure and returns 0 on - success - */ + /* This is a C-API version of the getbuffer function call. It checks + to make sure object has the required function pointer and issues the + call. Returns -1 and raises an error on failure and returns 0 on + success + */ PyAPI_FUNC(void *) PyBuffer_GetPointer(Py_buffer *view, Py_ssize_t *indices); - - /* Get the memory area pointed to by the indices for the buffer given. - Note that view->ndim is the assumed size of indices - */ + + /* Get the memory area pointed to by the indices for the buffer given. + Note that view->ndim is the assumed size of indices + */ PyAPI_FUNC(int) PyBuffer_SizeFromFormat(const char *); - - /* Return the implied itemsize of the data-format area from a - struct-style description */ - - + /* Return the implied itemsize of the data-format area from a + struct-style description */ + + + PyAPI_FUNC(int) PyBuffer_ToContiguous(void *buf, Py_buffer *view, - Py_ssize_t len, char fort); + Py_ssize_t len, char fort); - PyAPI_FUNC(int) PyBuffer_FromContiguous(Py_buffer *view, void *buf, - Py_ssize_t len, char fort); + PyAPI_FUNC(int) PyBuffer_FromContiguous(Py_buffer *view, void *buf, + Py_ssize_t len, char fort); - /* Copy len bytes of data from the contiguous chunk of memory - pointed to by buf into the buffer exported by obj. Return - 0 on success and return -1 and raise a PyBuffer_Error on - error (i.e. the object does not have a buffer interface or - it is not working). - - If fort is 'F', then if the object is multi-dimensional, - then the data will be copied into the array in - Fortran-style (first dimension varies the fastest). If - fort is 'C', then the data will be copied into the array - in C-style (last dimension varies the fastest). If fort - is 'A', then it does not matter and the copy will be made - in whatever way is more efficient. + /* Copy len bytes of data from the contiguous chunk of memory + pointed to by buf into the buffer exported by obj. Return + 0 on success and return -1 and raise a PyBuffer_Error on + error (i.e. the object does not have a buffer interface or + it is not working). + + If fort is 'F', then if the object is multi-dimensional, + then the data will be copied into the array in + Fortran-style (first dimension varies the fastest). If + fort is 'C', then the data will be copied into the array + in C-style (last dimension varies the fastest). If fort + is 'A', then it does not matter and the copy will be made + in whatever way is more efficient. - */ + */ PyAPI_FUNC(int) PyObject_CopyData(PyObject *dest, PyObject *src); - - /* Copy the data from the src buffer to the buffer of destination - */ + + /* Copy the data from the src buffer to the buffer of destination + */ PyAPI_FUNC(int) PyBuffer_IsContiguous(Py_buffer *view, char fort); - PyAPI_FUNC(void) PyBuffer_FillContiguousStrides(int ndims, - Py_ssize_t *shape, - Py_ssize_t *strides, - int itemsize, - char fort); - - /* Fill the strides array with byte-strides of a contiguous - (Fortran-style if fort is 'F' or C-style otherwise) - array of the given shape with the given number of bytes - per element. - */ + PyAPI_FUNC(void) PyBuffer_FillContiguousStrides(int ndims, + Py_ssize_t *shape, + Py_ssize_t *strides, + int itemsize, + char fort); + + /* Fill the strides array with byte-strides of a contiguous + (Fortran-style if fort is 'F' or C-style otherwise) + array of the given shape with the given number of bytes + per element. + */ PyAPI_FUNC(int) PyBuffer_FillInfo(Py_buffer *view, PyObject *o, void *buf, - Py_ssize_t len, int readonly, - int flags); + Py_ssize_t len, int readonly, + int flags); - /* Fills in a buffer-info structure correctly for an exporter - that can only share a contiguous chunk of memory of - "unsigned bytes" of the given length. Returns 0 on success - and -1 (with raising an error) on error. - */ + /* Fills in a buffer-info structure correctly for an exporter + that can only share a contiguous chunk of memory of + "unsigned bytes" of the given length. Returns 0 on success + and -1 (with raising an error) on error. + */ PyAPI_FUNC(void) PyBuffer_Release(Py_buffer *view); /* Releases a Py_buffer obtained from getbuffer ParseTuple's s*. - */ + */ PyAPI_FUNC(PyObject *) PyObject_Format(PyObject* obj, - PyObject *format_spec); + PyObject *format_spec); /* - Takes an arbitrary object and returns the result of - calling obj.__format__(format_spec). + Takes an arbitrary object and returns the result of + calling obj.__format__(format_spec). */ /* Iterators */ PyAPI_FUNC(PyObject *) PyObject_GetIter(PyObject *); /* Takes an object and returns an iterator for it. - This is typically a new iterator but if the argument - is an iterator, this returns itself. */ + This is typically a new iterator but if the argument + is an iterator, this returns itself. */ #define PyIter_Check(obj) \ ((obj)->ob_type->tp_iternext != NULL && \ @@ -594,314 +594,314 @@ PyAPI_FUNC(PyObject *) PyIter_Next(PyObject *); /* Takes an iterator object and calls its tp_iternext slot, - returning the next value. If the iterator is exhausted, - this returns NULL without setting an exception. - NULL with an exception means an error occurred. */ + returning the next value. If the iterator is exhausted, + this returns NULL without setting an exception. + NULL with an exception means an error occurred. */ /* Number Protocol:*/ PyAPI_FUNC(int) PyNumber_Check(PyObject *o); /* - Returns 1 if the object, o, provides numeric protocols, and - false otherwise. + Returns 1 if the object, o, provides numeric protocols, and + false otherwise. - This function always succeeds. + This function always succeeds. */ PyAPI_FUNC(PyObject *) PyNumber_Add(PyObject *o1, PyObject *o2); /* - Returns the result of adding o1 and o2, or null on failure. - This is the equivalent of the Python expression: o1+o2. + Returns the result of adding o1 and o2, or null on failure. + This is the equivalent of the Python expression: o1+o2. */ PyAPI_FUNC(PyObject *) PyNumber_Subtract(PyObject *o1, PyObject *o2); /* - Returns the result of subtracting o2 from o1, or null on - failure. This is the equivalent of the Python expression: - o1-o2. + Returns the result of subtracting o2 from o1, or null on + failure. This is the equivalent of the Python expression: + o1-o2. */ PyAPI_FUNC(PyObject *) PyNumber_Multiply(PyObject *o1, PyObject *o2); /* - Returns the result of multiplying o1 and o2, or null on - failure. This is the equivalent of the Python expression: - o1*o2. + Returns the result of multiplying o1 and o2, or null on + failure. This is the equivalent of the Python expression: + o1*o2. */ PyAPI_FUNC(PyObject *) PyNumber_FloorDivide(PyObject *o1, PyObject *o2); /* - Returns the result of dividing o1 by o2 giving an integral result, - or null on failure. - This is the equivalent of the Python expression: o1//o2. + Returns the result of dividing o1 by o2 giving an integral result, + or null on failure. + This is the equivalent of the Python expression: o1//o2. */ PyAPI_FUNC(PyObject *) PyNumber_TrueDivide(PyObject *o1, PyObject *o2); /* - Returns the result of dividing o1 by o2 giving a float result, - or null on failure. - This is the equivalent of the Python expression: o1/o2. + Returns the result of dividing o1 by o2 giving a float result, + or null on failure. + This is the equivalent of the Python expression: o1/o2. */ PyAPI_FUNC(PyObject *) PyNumber_Remainder(PyObject *o1, PyObject *o2); /* - Returns the remainder of dividing o1 by o2, or null on - failure. This is the equivalent of the Python expression: - o1%o2. + Returns the remainder of dividing o1 by o2, or null on + failure. This is the equivalent of the Python expression: + o1%o2. */ PyAPI_FUNC(PyObject *) PyNumber_Divmod(PyObject *o1, PyObject *o2); /* - See the built-in function divmod. Returns NULL on failure. - This is the equivalent of the Python expression: - divmod(o1,o2). + See the built-in function divmod. Returns NULL on failure. + This is the equivalent of the Python expression: + divmod(o1,o2). */ PyAPI_FUNC(PyObject *) PyNumber_Power(PyObject *o1, PyObject *o2, PyObject *o3); /* - See the built-in function pow. Returns NULL on failure. - This is the equivalent of the Python expression: - pow(o1,o2,o3), where o3 is optional. + See the built-in function pow. Returns NULL on failure. + This is the equivalent of the Python expression: + pow(o1,o2,o3), where o3 is optional. */ PyAPI_FUNC(PyObject *) PyNumber_Negative(PyObject *o); /* - Returns the negation of o on success, or null on failure. - This is the equivalent of the Python expression: -o. + Returns the negation of o on success, or null on failure. + This is the equivalent of the Python expression: -o. */ PyAPI_FUNC(PyObject *) PyNumber_Positive(PyObject *o); /* - Returns the (what?) of o on success, or NULL on failure. - This is the equivalent of the Python expression: +o. + Returns the (what?) of o on success, or NULL on failure. + This is the equivalent of the Python expression: +o. */ PyAPI_FUNC(PyObject *) PyNumber_Absolute(PyObject *o); /* - Returns the absolute value of o, or null on failure. This is - the equivalent of the Python expression: abs(o). + Returns the absolute value of o, or null on failure. This is + the equivalent of the Python expression: abs(o). */ PyAPI_FUNC(PyObject *) PyNumber_Invert(PyObject *o); /* - Returns the bitwise negation of o on success, or NULL on - failure. This is the equivalent of the Python expression: - ~o. + Returns the bitwise negation of o on success, or NULL on + failure. This is the equivalent of the Python expression: + ~o. */ PyAPI_FUNC(PyObject *) PyNumber_Lshift(PyObject *o1, PyObject *o2); /* - Returns the result of left shifting o1 by o2 on success, or - NULL on failure. This is the equivalent of the Python - expression: o1 << o2. + Returns the result of left shifting o1 by o2 on success, or + NULL on failure. This is the equivalent of the Python + expression: o1 << o2. */ PyAPI_FUNC(PyObject *) PyNumber_Rshift(PyObject *o1, PyObject *o2); /* - Returns the result of right shifting o1 by o2 on success, or - NULL on failure. This is the equivalent of the Python - expression: o1 >> o2. + Returns the result of right shifting o1 by o2 on success, or + NULL on failure. This is the equivalent of the Python + expression: o1 >> o2. */ PyAPI_FUNC(PyObject *) PyNumber_And(PyObject *o1, PyObject *o2); /* - Returns the result of bitwise and of o1 and o2 on success, or - NULL on failure. This is the equivalent of the Python - expression: o1&o2. + Returns the result of bitwise and of o1 and o2 on success, or + NULL on failure. This is the equivalent of the Python + expression: o1&o2. */ PyAPI_FUNC(PyObject *) PyNumber_Xor(PyObject *o1, PyObject *o2); /* - Returns the bitwise exclusive or of o1 by o2 on success, or - NULL on failure. This is the equivalent of the Python - expression: o1^o2. + Returns the bitwise exclusive or of o1 by o2 on success, or + NULL on failure. This is the equivalent of the Python + expression: o1^o2. */ PyAPI_FUNC(PyObject *) PyNumber_Or(PyObject *o1, PyObject *o2); /* - Returns the result of bitwise or on o1 and o2 on success, or - NULL on failure. This is the equivalent of the Python - expression: o1|o2. + Returns the result of bitwise or on o1 and o2 on success, or + NULL on failure. This is the equivalent of the Python + expression: o1|o2. */ #define PyIndex_Check(obj) \ ((obj)->ob_type->tp_as_number != NULL && \ (obj)->ob_type->tp_as_number->nb_index != NULL) - + PyAPI_FUNC(PyObject *) PyNumber_Index(PyObject *o); /* - Returns the object converted to a Python long or int - or NULL with an error raised on failure. + Returns the object converted to a Python long or int + or NULL with an error raised on failure. */ PyAPI_FUNC(Py_ssize_t) PyNumber_AsSsize_t(PyObject *o, PyObject *exc); /* - Returns the Integral instance converted to an int. The - instance is expected to be int or long or have an __int__ - method. Steals integral's reference. error_format will be - used to create the TypeError if integral isn't actually an - Integral instance. error_format should be a format string - that can accept a char* naming integral's type. + Returns the Integral instance converted to an int. The + instance is expected to be int or long or have an __int__ + method. Steals integral's reference. error_format will be + used to create the TypeError if integral isn't actually an + Integral instance. error_format should be a format string + that can accept a char* naming integral's type. */ PyAPI_FUNC(PyObject *) _PyNumber_ConvertIntegralToInt( - PyObject *integral, - const char* error_format); + PyObject *integral, + const char* error_format); /* - Returns the object converted to Py_ssize_t by going through - PyNumber_Index first. If an overflow error occurs while - converting the int-or-long to Py_ssize_t, then the second argument - is the error-type to return. If it is NULL, then the overflow error - is cleared and the value is clipped. + Returns the object converted to Py_ssize_t by going through + PyNumber_Index first. If an overflow error occurs while + converting the int-or-long to Py_ssize_t, then the second argument + is the error-type to return. If it is NULL, then the overflow error + is cleared and the value is clipped. */ PyAPI_FUNC(PyObject *) PyNumber_Long(PyObject *o); /* - Returns the o converted to an integer object on success, or - NULL on failure. This is the equivalent of the Python - expression: int(o). + Returns the o converted to an integer object on success, or + NULL on failure. This is the equivalent of the Python + expression: int(o). */ PyAPI_FUNC(PyObject *) PyNumber_Float(PyObject *o); /* - Returns the o converted to a float object on success, or NULL - on failure. This is the equivalent of the Python expression: - float(o). + Returns the o converted to a float object on success, or NULL + on failure. This is the equivalent of the Python expression: + float(o). */ - + /* In-place variants of (some of) the above number protocol functions */ PyAPI_FUNC(PyObject *) PyNumber_InPlaceAdd(PyObject *o1, PyObject *o2); /* - Returns the result of adding o2 to o1, possibly in-place, or null - on failure. This is the equivalent of the Python expression: - o1 += o2. + Returns the result of adding o2 to o1, possibly in-place, or null + on failure. This is the equivalent of the Python expression: + o1 += o2. */ PyAPI_FUNC(PyObject *) PyNumber_InPlaceSubtract(PyObject *o1, PyObject *o2); /* - Returns the result of subtracting o2 from o1, possibly in-place or - null on failure. This is the equivalent of the Python expression: - o1 -= o2. + Returns the result of subtracting o2 from o1, possibly in-place or + null on failure. This is the equivalent of the Python expression: + o1 -= o2. */ PyAPI_FUNC(PyObject *) PyNumber_InPlaceMultiply(PyObject *o1, PyObject *o2); /* - Returns the result of multiplying o1 by o2, possibly in-place, or - null on failure. This is the equivalent of the Python expression: - o1 *= o2. + Returns the result of multiplying o1 by o2, possibly in-place, or + null on failure. This is the equivalent of the Python expression: + o1 *= o2. */ PyAPI_FUNC(PyObject *) PyNumber_InPlaceFloorDivide(PyObject *o1, - PyObject *o2); + PyObject *o2); /* - Returns the result of dividing o1 by o2 giving an integral result, - possibly in-place, or null on failure. - This is the equivalent of the Python expression: - o1 /= o2. + Returns the result of dividing o1 by o2 giving an integral result, + possibly in-place, or null on failure. + This is the equivalent of the Python expression: + o1 /= o2. */ PyAPI_FUNC(PyObject *) PyNumber_InPlaceTrueDivide(PyObject *o1, - PyObject *o2); + PyObject *o2); /* - Returns the result of dividing o1 by o2 giving a float result, - possibly in-place, or null on failure. - This is the equivalent of the Python expression: - o1 /= o2. + Returns the result of dividing o1 by o2 giving a float result, + possibly in-place, or null on failure. + This is the equivalent of the Python expression: + o1 /= o2. */ PyAPI_FUNC(PyObject *) PyNumber_InPlaceRemainder(PyObject *o1, PyObject *o2); /* - Returns the remainder of dividing o1 by o2, possibly in-place, or - null on failure. This is the equivalent of the Python expression: - o1 %= o2. + Returns the remainder of dividing o1 by o2, possibly in-place, or + null on failure. This is the equivalent of the Python expression: + o1 %= o2. */ PyAPI_FUNC(PyObject *) PyNumber_InPlacePower(PyObject *o1, PyObject *o2, - PyObject *o3); + PyObject *o3); /* - Returns the result of raising o1 to the power of o2, possibly - in-place, or null on failure. This is the equivalent of the Python - expression: o1 **= o2, or pow(o1, o2, o3) if o3 is present. + Returns the result of raising o1 to the power of o2, possibly + in-place, or null on failure. This is the equivalent of the Python + expression: o1 **= o2, or pow(o1, o2, o3) if o3 is present. */ PyAPI_FUNC(PyObject *) PyNumber_InPlaceLshift(PyObject *o1, PyObject *o2); /* - Returns the result of left shifting o1 by o2, possibly in-place, or - null on failure. This is the equivalent of the Python expression: - o1 <<= o2. + Returns the result of left shifting o1 by o2, possibly in-place, or + null on failure. This is the equivalent of the Python expression: + o1 <<= o2. */ PyAPI_FUNC(PyObject *) PyNumber_InPlaceRshift(PyObject *o1, PyObject *o2); /* - Returns the result of right shifting o1 by o2, possibly in-place or - null on failure. This is the equivalent of the Python expression: - o1 >>= o2. + Returns the result of right shifting o1 by o2, possibly in-place or + null on failure. This is the equivalent of the Python expression: + o1 >>= o2. */ PyAPI_FUNC(PyObject *) PyNumber_InPlaceAnd(PyObject *o1, PyObject *o2); /* - Returns the result of bitwise and of o1 and o2, possibly in-place, - or null on failure. This is the equivalent of the Python - expression: o1 &= o2. + Returns the result of bitwise and of o1 and o2, possibly in-place, + or null on failure. This is the equivalent of the Python + expression: o1 &= o2. */ PyAPI_FUNC(PyObject *) PyNumber_InPlaceXor(PyObject *o1, PyObject *o2); /* - Returns the bitwise exclusive or of o1 by o2, possibly in-place, or - null on failure. This is the equivalent of the Python expression: - o1 ^= o2. + Returns the bitwise exclusive or of o1 by o2, possibly in-place, or + null on failure. This is the equivalent of the Python expression: + o1 ^= o2. */ PyAPI_FUNC(PyObject *) PyNumber_InPlaceOr(PyObject *o1, PyObject *o2); /* - Returns the result of bitwise or of o1 and o2, possibly in-place, - or null on failure. This is the equivalent of the Python - expression: o1 |= o2. + Returns the result of bitwise or of o1 and o2, possibly in-place, + or null on failure. This is the equivalent of the Python + expression: o1 |= o2. */ PyAPI_FUNC(PyObject *) PyNumber_ToBase(PyObject *n, int base); /* - Returns the integer n converted to a string with a base, with a base - marker of 0b, 0o or 0x prefixed if applicable. - If n is not an int object, it is converted with PyNumber_Index first. + Returns the integer n converted to a string with a base, with a base + marker of 0b, 0o or 0x prefixed if applicable. + If n is not an int object, it is converted with PyNumber_Index first. */ @@ -910,16 +910,16 @@ PyAPI_FUNC(int) PySequence_Check(PyObject *o); /* - Return 1 if the object provides sequence protocol, and zero - otherwise. + Return 1 if the object provides sequence protocol, and zero + otherwise. - This function always succeeds. + This function always succeeds. */ PyAPI_FUNC(Py_ssize_t) PySequence_Size(PyObject *o); /* - Return the size of sequence object o, or -1 on failure. + Return the size of sequence object o, or -1 on failure. */ /* For DLL compatibility */ @@ -931,147 +931,147 @@ PyAPI_FUNC(PyObject *) PySequence_Concat(PyObject *o1, PyObject *o2); /* - Return the concatenation of o1 and o2 on success, and NULL on - failure. This is the equivalent of the Python - expression: o1+o2. + Return the concatenation of o1 and o2 on success, and NULL on + failure. This is the equivalent of the Python + expression: o1+o2. */ PyAPI_FUNC(PyObject *) PySequence_Repeat(PyObject *o, Py_ssize_t count); /* - Return the result of repeating sequence object o count times, - or NULL on failure. This is the equivalent of the Python - expression: o1*count. + Return the result of repeating sequence object o count times, + or NULL on failure. This is the equivalent of the Python + expression: o1*count. */ PyAPI_FUNC(PyObject *) PySequence_GetItem(PyObject *o, Py_ssize_t i); /* - Return the ith element of o, or NULL on failure. This is the - equivalent of the Python expression: o[i]. + Return the ith element of o, or NULL on failure. This is the + equivalent of the Python expression: o[i]. */ PyAPI_FUNC(PyObject *) PySequence_GetSlice(PyObject *o, Py_ssize_t i1, Py_ssize_t i2); /* - Return the slice of sequence object o between i1 and i2, or - NULL on failure. This is the equivalent of the Python - expression: o[i1:i2]. + Return the slice of sequence object o between i1 and i2, or + NULL on failure. This is the equivalent of the Python + expression: o[i1:i2]. */ PyAPI_FUNC(int) PySequence_SetItem(PyObject *o, Py_ssize_t i, PyObject *v); /* - Assign object v to the ith element of o. Returns - -1 on failure. This is the equivalent of the Python - statement: o[i]=v. + Assign object v to the ith element of o. Returns + -1 on failure. This is the equivalent of the Python + statement: o[i]=v. */ PyAPI_FUNC(int) PySequence_DelItem(PyObject *o, Py_ssize_t i); /* - Delete the ith element of object v. Returns - -1 on failure. This is the equivalent of the Python - statement: del o[i]. + Delete the ith element of object v. Returns + -1 on failure. This is the equivalent of the Python + statement: del o[i]. */ PyAPI_FUNC(int) PySequence_SetSlice(PyObject *o, Py_ssize_t i1, Py_ssize_t i2, PyObject *v); /* - Assign the sequence object, v, to the slice in sequence - object, o, from i1 to i2. Returns -1 on failure. This is the - equivalent of the Python statement: o[i1:i2]=v. + Assign the sequence object, v, to the slice in sequence + object, o, from i1 to i2. Returns -1 on failure. This is the + equivalent of the Python statement: o[i1:i2]=v. */ PyAPI_FUNC(int) PySequence_DelSlice(PyObject *o, Py_ssize_t i1, Py_ssize_t i2); /* - Delete the slice in sequence object, o, from i1 to i2. - Returns -1 on failure. This is the equivalent of the Python - statement: del o[i1:i2]. + Delete the slice in sequence object, o, from i1 to i2. + Returns -1 on failure. This is the equivalent of the Python + statement: del o[i1:i2]. */ PyAPI_FUNC(PyObject *) PySequence_Tuple(PyObject *o); /* - Returns the sequence, o, as a tuple on success, and NULL on failure. - This is equivalent to the Python expression: tuple(o) + Returns the sequence, o, as a tuple on success, and NULL on failure. + This is equivalent to the Python expression: tuple(o) */ PyAPI_FUNC(PyObject *) PySequence_List(PyObject *o); /* - Returns the sequence, o, as a list on success, and NULL on failure. - This is equivalent to the Python expression: list(o) + Returns the sequence, o, as a list on success, and NULL on failure. + This is equivalent to the Python expression: list(o) */ PyAPI_FUNC(PyObject *) PySequence_Fast(PyObject *o, const char* m); /* - Returns the sequence, o, as a tuple, unless it's already a - tuple or list. Use PySequence_Fast_GET_ITEM to access the - members of this list, and PySequence_Fast_GET_SIZE to get its length. + Returns the sequence, o, as a tuple, unless it's already a + tuple or list. Use PySequence_Fast_GET_ITEM to access the + members of this list, and PySequence_Fast_GET_SIZE to get its length. - Returns NULL on failure. If the object does not support iteration, - raises a TypeError exception with m as the message text. + Returns NULL on failure. If the object does not support iteration, + raises a TypeError exception with m as the message text. */ #define PySequence_Fast_GET_SIZE(o) \ - (PyList_Check(o) ? PyList_GET_SIZE(o) : PyTuple_GET_SIZE(o)) + (PyList_Check(o) ? PyList_GET_SIZE(o) : PyTuple_GET_SIZE(o)) /* - Return the size of o, assuming that o was returned by - PySequence_Fast and is not NULL. + Return the size of o, assuming that o was returned by + PySequence_Fast and is not NULL. */ #define PySequence_Fast_GET_ITEM(o, i)\ (PyList_Check(o) ? PyList_GET_ITEM(o, i) : PyTuple_GET_ITEM(o, i)) /* - Return the ith element of o, assuming that o was returned by - PySequence_Fast, and that i is within bounds. + Return the ith element of o, assuming that o was returned by + PySequence_Fast, and that i is within bounds. */ #define PySequence_ITEM(o, i)\ - ( Py_TYPE(o)->tp_as_sequence->sq_item(o, i) ) + ( Py_TYPE(o)->tp_as_sequence->sq_item(o, i) ) /* Assume tp_as_sequence and sq_item exist and that i does not - need to be corrected for a negative index - */ + need to be corrected for a negative index + */ #define PySequence_Fast_ITEMS(sf) \ - (PyList_Check(sf) ? ((PyListObject *)(sf))->ob_item \ - : ((PyTupleObject *)(sf))->ob_item) - /* Return a pointer to the underlying item array for - an object retured by PySequence_Fast */ + (PyList_Check(sf) ? ((PyListObject *)(sf))->ob_item \ + : ((PyTupleObject *)(sf))->ob_item) + /* Return a pointer to the underlying item array for + an object retured by PySequence_Fast */ PyAPI_FUNC(Py_ssize_t) PySequence_Count(PyObject *o, PyObject *value); /* - Return the number of occurrences on value on o, that is, - return the number of keys for which o[key]==value. On - failure, return -1. This is equivalent to the Python - expression: o.count(value). + Return the number of occurrences on value on o, that is, + return the number of keys for which o[key]==value. On + failure, return -1. This is equivalent to the Python + expression: o.count(value). */ PyAPI_FUNC(int) PySequence_Contains(PyObject *seq, PyObject *ob); /* - Return -1 if error; 1 if ob in seq; 0 if ob not in seq. - Use __contains__ if possible, else _PySequence_IterSearch(). + Return -1 if error; 1 if ob in seq; 0 if ob not in seq. + Use __contains__ if possible, else _PySequence_IterSearch(). */ #define PY_ITERSEARCH_COUNT 1 #define PY_ITERSEARCH_INDEX 2 #define PY_ITERSEARCH_CONTAINS 3 PyAPI_FUNC(Py_ssize_t) _PySequence_IterSearch(PyObject *seq, - PyObject *obj, int operation); - /* - Iterate over seq. Result depends on the operation: - PY_ITERSEARCH_COUNT: return # of times obj appears in seq; -1 if - error. - PY_ITERSEARCH_INDEX: return 0-based index of first occurrence of - obj in seq; set ValueError and return -1 if none found; - also return -1 on error. - PY_ITERSEARCH_CONTAINS: return 1 if obj in seq, else 0; -1 on - error. - */ + PyObject *obj, int operation); + /* + Iterate over seq. Result depends on the operation: + PY_ITERSEARCH_COUNT: return # of times obj appears in seq; -1 if + error. + PY_ITERSEARCH_INDEX: return 0-based index of first occurrence of + obj in seq; set ValueError and return -1 if none found; + also return -1 on error. + PY_ITERSEARCH_CONTAINS: return 1 if obj in seq, else 0; -1 on + error. + */ /* For DLL-level backwards compatibility */ #undef PySequence_In @@ -1081,17 +1081,17 @@ #define PySequence_In PySequence_Contains /* - Determine if o contains value. If an item in o is equal to - X, return 1, otherwise return 0. On error, return -1. This - is equivalent to the Python expression: value in o. + Determine if o contains value. If an item in o is equal to + X, return 1, otherwise return 0. On error, return -1. This + is equivalent to the Python expression: value in o. */ PyAPI_FUNC(Py_ssize_t) PySequence_Index(PyObject *o, PyObject *value); /* - Return the first index for which o[i]=value. On error, - return -1. This is equivalent to the Python - expression: o.index(value). + Return the first index for which o[i]=value. On error, + return -1. This is equivalent to the Python + expression: o.index(value). */ /* In-place versions of some of the above Sequence functions. */ @@ -1099,18 +1099,18 @@ PyAPI_FUNC(PyObject *) PySequence_InPlaceConcat(PyObject *o1, PyObject *o2); /* - Append o2 to o1, in-place when possible. Return the resulting - object, which could be o1, or NULL on failure. This is the - equivalent of the Python expression: o1 += o2. + Append o2 to o1, in-place when possible. Return the resulting + object, which could be o1, or NULL on failure. This is the + equivalent of the Python expression: o1 += o2. */ PyAPI_FUNC(PyObject *) PySequence_InPlaceRepeat(PyObject *o, Py_ssize_t count); /* - Repeat o1 by count, in-place when possible. Return the resulting - object, which could be o1, or NULL on failure. This is the - equivalent of the Python expression: o1 *= count. + Repeat o1 by count, in-place when possible. Return the resulting + object, which could be o1, or NULL on failure. This is the + equivalent of the Python expression: o1 *= count. */ @@ -1119,18 +1119,18 @@ PyAPI_FUNC(int) PyMapping_Check(PyObject *o); /* - Return 1 if the object provides mapping protocol, and zero - otherwise. + Return 1 if the object provides mapping protocol, and zero + otherwise. - This function always succeeds. + This function always succeeds. */ PyAPI_FUNC(Py_ssize_t) PyMapping_Size(PyObject *o); /* - Returns the number of keys in object o on success, and -1 on - failure. For objects that do not provide sequence protocol, - this is equivalent to the Python expression: len(o). + Returns the number of keys in object o on success, and -1 on + failure. For objects that do not provide sequence protocol, + this is equivalent to the Python expression: len(o). */ /* For DLL compatibility */ @@ -1143,9 +1143,9 @@ int PyMapping_DelItemString(PyObject *o, char *key); - Remove the mapping for object, key, from the object *o. - Returns -1 on failure. This is equivalent to - the Python statement: del o[key]. + Remove the mapping for object, key, from the object *o. + Returns -1 on failure. This is equivalent to + the Python statement: del o[key]. */ #define PyMapping_DelItemString(O,K) PyObject_DelItemString((O),(K)) @@ -1153,71 +1153,71 @@ int PyMapping_DelItem(PyObject *o, PyObject *key); - Remove the mapping for object, key, from the object *o. - Returns -1 on failure. This is equivalent to - the Python statement: del o[key]. + Remove the mapping for object, key, from the object *o. + Returns -1 on failure. This is equivalent to + the Python statement: del o[key]. */ #define PyMapping_DelItem(O,K) PyObject_DelItem((O),(K)) PyAPI_FUNC(int) PyMapping_HasKeyString(PyObject *o, char *key); /* - On success, return 1 if the mapping object has the key, key, - and 0 otherwise. This is equivalent to the Python expression: - key in o. + On success, return 1 if the mapping object has the key, key, + and 0 otherwise. This is equivalent to the Python expression: + key in o. - This function always succeeds. + This function always succeeds. */ PyAPI_FUNC(int) PyMapping_HasKey(PyObject *o, PyObject *key); /* - Return 1 if the mapping object has the key, key, - and 0 otherwise. This is equivalent to the Python expression: - key in o. + Return 1 if the mapping object has the key, key, + and 0 otherwise. This is equivalent to the Python expression: + key in o. - This function always succeeds. + This function always succeeds. */ PyAPI_FUNC(PyObject *) PyMapping_Keys(PyObject *o); /* - On success, return a list or tuple of the keys in object o. - On failure, return NULL. + On success, return a list or tuple of the keys in object o. + On failure, return NULL. */ PyAPI_FUNC(PyObject *) PyMapping_Values(PyObject *o); /* - On success, return a list or tuple of the values in object o. - On failure, return NULL. + On success, return a list or tuple of the values in object o. + On failure, return NULL. */ PyAPI_FUNC(PyObject *) PyMapping_Items(PyObject *o); /* - On success, return a list or tuple of the items in object o, - where each item is a tuple containing a key-value pair. - On failure, return NULL. + On success, return a list or tuple of the items in object o, + where each item is a tuple containing a key-value pair. + On failure, return NULL. */ PyAPI_FUNC(PyObject *) PyMapping_GetItemString(PyObject *o, char *key); /* - Return element of o corresponding to the object, key, or NULL - on failure. This is the equivalent of the Python expression: - o[key]. + Return element of o corresponding to the object, key, or NULL + on failure. This is the equivalent of the Python expression: + o[key]. */ PyAPI_FUNC(int) PyMapping_SetItemString(PyObject *o, char *key, PyObject *value); /* - Map the object, key, to the value, v. Returns - -1 on failure. This is the equivalent of the Python - statement: o[key]=v. + Map the object, key, to the value, v. Returns + -1 on failure. This is the equivalent of the Python + statement: o[key]=v. */ Modified: python/branches/release31-maint/Include/ceval.h ============================================================================== --- python/branches/release31-maint/Include/ceval.h (original) +++ python/branches/release31-maint/Include/ceval.h Sun May 9 18:14:21 2010 @@ -8,7 +8,7 @@ /* Interface to random parts in ceval.c */ PyAPI_FUNC(PyObject *) PyEval_CallObjectWithKeywords( - PyObject *, PyObject *, PyObject *); + PyObject *, PyObject *, PyObject *); /* DLL-level Backwards compatibility: */ #undef PyEval_CallObject @@ -16,7 +16,7 @@ /* Inline this */ #define PyEval_CallObject(func,arg) \ - PyEval_CallObjectWithKeywords(func, arg, (PyObject *)NULL) + PyEval_CallObjectWithKeywords(func, arg, (PyObject *)NULL) PyAPI_FUNC(PyObject *) PyEval_CallFunction(PyObject *obj, const char *format, ...); @@ -49,7 +49,7 @@ exceeds the current recursion limit. It raises a RuntimeError, and sets the "overflowed" flag in the thread state structure. This flag temporarily *disables* the normal protection; this allows cleanup code - to potentially outgrow the recursion limit while processing the + to potentially outgrow the recursion limit while processing the RuntimeError. * "last chance" anti-recursion protection is triggered when the recursion level exceeds "current recursion limit + 50". By construction, this @@ -71,12 +71,12 @@ PyAPI_FUNC(int) Py_GetRecursionLimit(void); #define Py_EnterRecursiveCall(where) \ - (_Py_MakeRecCheck(PyThreadState_GET()->recursion_depth) && \ - _Py_CheckRecursiveCall(where)) -#define Py_LeaveRecursiveCall() \ + (_Py_MakeRecCheck(PyThreadState_GET()->recursion_depth) && \ + _Py_CheckRecursiveCall(where)) +#define Py_LeaveRecursiveCall() \ do{ if(_Py_MakeEndRecCheck(PyThreadState_GET()->recursion_depth)) \ - PyThreadState_GET()->overflowed = 0; \ - } while(0) + PyThreadState_GET()->overflowed = 0; \ + } while(0) PyAPI_FUNC(int) _Py_CheckRecursiveCall(char *where); PyAPI_DATA(int) _Py_CheckRecursionLimit; @@ -87,15 +87,15 @@ of _Py_CheckRecursionLimit for _Py_MakeEndRecCheck() to function properly. */ # define _Py_MakeRecCheck(x) \ - (++(x) > (_Py_CheckRecursionLimit += PyThreadState_GET()->overflowed - 1)) + (++(x) > (_Py_CheckRecursionLimit += PyThreadState_GET()->overflowed - 1)) #else # define _Py_MakeRecCheck(x) (++(x) > _Py_CheckRecursionLimit) #endif #define _Py_MakeEndRecCheck(x) \ - (--(x) < ((_Py_CheckRecursionLimit > 100) \ - ? (_Py_CheckRecursionLimit - 50) \ - : (3 * (_Py_CheckRecursionLimit >> 2)))) + (--(x) < ((_Py_CheckRecursionLimit > 100) \ + ? (_Py_CheckRecursionLimit - 50) \ + : (3 * (_Py_CheckRecursionLimit >> 2)))) #define Py_ALLOW_RECURSION \ do { unsigned char _old = PyThreadState_GET()->recursion_critical;\ @@ -122,31 +122,31 @@ that lasts a long time and doesn't touch Python data) can allow other threads to run as follows: - ...preparations here... - Py_BEGIN_ALLOW_THREADS - ...blocking system call here... - Py_END_ALLOW_THREADS - ...interpret result here... + ...preparations here... + Py_BEGIN_ALLOW_THREADS + ...blocking system call here... + Py_END_ALLOW_THREADS + ...interpret result here... The Py_BEGIN_ALLOW_THREADS/Py_END_ALLOW_THREADS pair expands to a {}-surrounded block. To leave the block in the middle (e.g., with return), you must insert a line containing Py_BLOCK_THREADS before the return, e.g. - if (...premature_exit...) { - Py_BLOCK_THREADS - PyErr_SetFromErrno(PyExc_IOError); - return NULL; - } + if (...premature_exit...) { + Py_BLOCK_THREADS + PyErr_SetFromErrno(PyExc_IOError); + return NULL; + } An alternative is: - Py_BLOCK_THREADS - if (...premature_exit...) { - PyErr_SetFromErrno(PyExc_IOError); - return NULL; - } - Py_UNBLOCK_THREADS + Py_BLOCK_THREADS + if (...premature_exit...) { + PyErr_SetFromErrno(PyExc_IOError); + return NULL; + } + Py_UNBLOCK_THREADS For convenience, that the value of 'errno' is restored across Py_END_ALLOW_THREADS and Py_BLOCK_THREADS. @@ -175,12 +175,12 @@ PyAPI_FUNC(void) PyEval_ReInitThreads(void); #define Py_BEGIN_ALLOW_THREADS { \ - PyThreadState *_save; \ - _save = PyEval_SaveThread(); -#define Py_BLOCK_THREADS PyEval_RestoreThread(_save); -#define Py_UNBLOCK_THREADS _save = PyEval_SaveThread(); -#define Py_END_ALLOW_THREADS PyEval_RestoreThread(_save); \ - } + PyThreadState *_save; \ + _save = PyEval_SaveThread(); +#define Py_BLOCK_THREADS PyEval_RestoreThread(_save); +#define Py_UNBLOCK_THREADS _save = PyEval_SaveThread(); +#define Py_END_ALLOW_THREADS PyEval_RestoreThread(_save); \ + } #else /* !WITH_THREAD */ Modified: python/branches/release31-maint/Include/datetime.h ============================================================================== --- python/branches/release31-maint/Include/datetime.h (original) +++ python/branches/release31-maint/Include/datetime.h Sun May 9 18:14:21 2010 @@ -11,13 +11,13 @@ * big-endian, unless otherwise noted: * * byte offset - * 0 year 2 bytes, 1-9999 - * 2 month 1 byte, 1-12 - * 3 day 1 byte, 1-31 - * 4 hour 1 byte, 0-23 - * 5 minute 1 byte, 0-59 - * 6 second 1 byte, 0-59 - * 7 usecond 3 bytes, 0-999999 + * 0 year 2 bytes, 1-9999 + * 2 month 1 byte, 1-12 + * 3 day 1 byte, 1-31 + * 4 hour 1 byte, 0-23 + * 5 minute 1 byte, 0-59 + * 6 second 1 byte, 0-59 + * 7 usecond 3 bytes, 0-999999 * 10 */ @@ -33,26 +33,26 @@ typedef struct { - PyObject_HEAD - long hashcode; /* -1 when unknown */ - int days; /* -MAX_DELTA_DAYS <= days <= MAX_DELTA_DAYS */ - int seconds; /* 0 <= seconds < 24*3600 is invariant */ - int microseconds; /* 0 <= microseconds < 1000000 is invariant */ + PyObject_HEAD + long hashcode; /* -1 when unknown */ + int days; /* -MAX_DELTA_DAYS <= days <= MAX_DELTA_DAYS */ + int seconds; /* 0 <= seconds < 24*3600 is invariant */ + int microseconds; /* 0 <= microseconds < 1000000 is invariant */ } PyDateTime_Delta; typedef struct { - PyObject_HEAD /* a pure abstract base clase */ + PyObject_HEAD /* a pure abstract base clase */ } PyDateTime_TZInfo; /* The datetime and time types have hashcodes, and an optional tzinfo member, * present if and only if hastzinfo is true. */ -#define _PyTZINFO_HEAD \ - PyObject_HEAD \ - long hashcode; \ - char hastzinfo; /* boolean flag */ +#define _PyTZINFO_HEAD \ + PyObject_HEAD \ + long hashcode; \ + char hastzinfo; /* boolean flag */ /* No _PyDateTime_BaseTZInfo is allocated; it's just to have something * convenient to cast to, when getting at the hastzinfo member of objects @@ -60,7 +60,7 @@ */ typedef struct { - _PyTZINFO_HEAD + _PyTZINFO_HEAD } _PyDateTime_BaseTZInfo; /* All time objects are of PyDateTime_TimeType, but that can be allocated @@ -69,20 +69,20 @@ * internal struct used to allocate the right amount of space for the * "without" case. */ -#define _PyDateTime_TIMEHEAD \ - _PyTZINFO_HEAD \ - unsigned char data[_PyDateTime_TIME_DATASIZE]; +#define _PyDateTime_TIMEHEAD \ + _PyTZINFO_HEAD \ + unsigned char data[_PyDateTime_TIME_DATASIZE]; typedef struct { - _PyDateTime_TIMEHEAD -} _PyDateTime_BaseTime; /* hastzinfo false */ + _PyDateTime_TIMEHEAD +} _PyDateTime_BaseTime; /* hastzinfo false */ typedef struct { - _PyDateTime_TIMEHEAD - PyObject *tzinfo; -} PyDateTime_Time; /* hastzinfo true */ + _PyDateTime_TIMEHEAD + PyObject *tzinfo; +} PyDateTime_Time; /* hastzinfo true */ /* All datetime objects are of PyDateTime_DateTimeType, but that can be @@ -92,48 +92,48 @@ */ typedef struct { - _PyTZINFO_HEAD - unsigned char data[_PyDateTime_DATE_DATASIZE]; + _PyTZINFO_HEAD + unsigned char data[_PyDateTime_DATE_DATASIZE]; } PyDateTime_Date; -#define _PyDateTime_DATETIMEHEAD \ - _PyTZINFO_HEAD \ - unsigned char data[_PyDateTime_DATETIME_DATASIZE]; +#define _PyDateTime_DATETIMEHEAD \ + _PyTZINFO_HEAD \ + unsigned char data[_PyDateTime_DATETIME_DATASIZE]; typedef struct { - _PyDateTime_DATETIMEHEAD -} _PyDateTime_BaseDateTime; /* hastzinfo false */ + _PyDateTime_DATETIMEHEAD +} _PyDateTime_BaseDateTime; /* hastzinfo false */ typedef struct { - _PyDateTime_DATETIMEHEAD - PyObject *tzinfo; -} PyDateTime_DateTime; /* hastzinfo true */ + _PyDateTime_DATETIMEHEAD + PyObject *tzinfo; +} PyDateTime_DateTime; /* hastzinfo true */ /* Apply for date and datetime instances. */ #define PyDateTime_GET_YEAR(o) ((((PyDateTime_Date*)o)->data[0] << 8) | \ - ((PyDateTime_Date*)o)->data[1]) + ((PyDateTime_Date*)o)->data[1]) #define PyDateTime_GET_MONTH(o) (((PyDateTime_Date*)o)->data[2]) #define PyDateTime_GET_DAY(o) (((PyDateTime_Date*)o)->data[3]) #define PyDateTime_DATE_GET_HOUR(o) (((PyDateTime_DateTime*)o)->data[4]) #define PyDateTime_DATE_GET_MINUTE(o) (((PyDateTime_DateTime*)o)->data[5]) #define PyDateTime_DATE_GET_SECOND(o) (((PyDateTime_DateTime*)o)->data[6]) -#define PyDateTime_DATE_GET_MICROSECOND(o) \ - ((((PyDateTime_DateTime*)o)->data[7] << 16) | \ - (((PyDateTime_DateTime*)o)->data[8] << 8) | \ - ((PyDateTime_DateTime*)o)->data[9]) +#define PyDateTime_DATE_GET_MICROSECOND(o) \ + ((((PyDateTime_DateTime*)o)->data[7] << 16) | \ + (((PyDateTime_DateTime*)o)->data[8] << 8) | \ + ((PyDateTime_DateTime*)o)->data[9]) /* Apply for time instances. */ #define PyDateTime_TIME_GET_HOUR(o) (((PyDateTime_Time*)o)->data[0]) #define PyDateTime_TIME_GET_MINUTE(o) (((PyDateTime_Time*)o)->data[1]) #define PyDateTime_TIME_GET_SECOND(o) (((PyDateTime_Time*)o)->data[2]) -#define PyDateTime_TIME_GET_MICROSECOND(o) \ - ((((PyDateTime_Time*)o)->data[3] << 16) | \ - (((PyDateTime_Time*)o)->data[4] << 8) | \ - ((PyDateTime_Time*)o)->data[5]) +#define PyDateTime_TIME_GET_MICROSECOND(o) \ + ((((PyDateTime_Time*)o)->data[3] << 16) | \ + (((PyDateTime_Time*)o)->data[4] << 8) | \ + ((PyDateTime_Time*)o)->data[5]) /* Define structure for C API. */ @@ -148,7 +148,7 @@ /* constructors */ PyObject *(*Date_FromDate)(int, int, int, PyTypeObject*); PyObject *(*DateTime_FromDateAndTime)(int, int, int, int, int, int, int, - PyObject*, PyTypeObject*); + PyObject*, PyTypeObject*); PyObject *(*Time_FromTime)(int, int, int, int, PyObject*, PyTypeObject*); PyObject *(*Delta_FromDelta)(int, int, int, int, PyTypeObject*); @@ -185,7 +185,7 @@ static PyDateTime_CAPI *PyDateTimeAPI; #define PyDateTime_IMPORT \ - PyDateTimeAPI = (PyDateTime_CAPI *)PyCapsule_Import(PyDateTime_CAPSULE_NAME, 0) + PyDateTimeAPI = (PyDateTime_CAPI *)PyCapsule_Import(PyDateTime_CAPSULE_NAME, 0) /* Macros for type checking when not building the Python core. */ #define PyDate_Check(op) PyObject_TypeCheck(op, PyDateTimeAPI->DateType) @@ -205,30 +205,30 @@ /* Macros for accessing constructors in a simplified fashion. */ #define PyDate_FromDate(year, month, day) \ - PyDateTimeAPI->Date_FromDate(year, month, day, PyDateTimeAPI->DateType) + PyDateTimeAPI->Date_FromDate(year, month, day, PyDateTimeAPI->DateType) #define PyDateTime_FromDateAndTime(year, month, day, hour, min, sec, usec) \ - PyDateTimeAPI->DateTime_FromDateAndTime(year, month, day, hour, \ - min, sec, usec, Py_None, PyDateTimeAPI->DateTimeType) + PyDateTimeAPI->DateTime_FromDateAndTime(year, month, day, hour, \ + min, sec, usec, Py_None, PyDateTimeAPI->DateTimeType) #define PyTime_FromTime(hour, minute, second, usecond) \ - PyDateTimeAPI->Time_FromTime(hour, minute, second, usecond, \ - Py_None, PyDateTimeAPI->TimeType) + PyDateTimeAPI->Time_FromTime(hour, minute, second, usecond, \ + Py_None, PyDateTimeAPI->TimeType) #define PyDelta_FromDSU(days, seconds, useconds) \ - PyDateTimeAPI->Delta_FromDelta(days, seconds, useconds, 1, \ - PyDateTimeAPI->DeltaType) + PyDateTimeAPI->Delta_FromDelta(days, seconds, useconds, 1, \ + PyDateTimeAPI->DeltaType) /* Macros supporting the DB API. */ #define PyDateTime_FromTimestamp(args) \ - PyDateTimeAPI->DateTime_FromTimestamp( \ - (PyObject*) (PyDateTimeAPI->DateTimeType), args, NULL) + PyDateTimeAPI->DateTime_FromTimestamp( \ + (PyObject*) (PyDateTimeAPI->DateTimeType), args, NULL) #define PyDate_FromTimestamp(args) \ - PyDateTimeAPI->Date_FromTimestamp( \ - (PyObject*) (PyDateTimeAPI->DateType), args) + PyDateTimeAPI->Date_FromTimestamp( \ + (PyObject*) (PyDateTimeAPI->DateType), args) -#endif /* Py_BUILD_CORE */ +#endif /* Py_BUILD_CORE */ #ifdef __cplusplus } Modified: python/branches/release31-maint/Include/descrobject.h ============================================================================== --- python/branches/release31-maint/Include/descrobject.h (original) +++ python/branches/release31-maint/Include/descrobject.h Sun May 9 18:14:21 2010 @@ -9,27 +9,27 @@ typedef int (*setter)(PyObject *, PyObject *, void *); typedef struct PyGetSetDef { - char *name; - getter get; - setter set; - char *doc; - void *closure; + char *name; + getter get; + setter set; + char *doc; + void *closure; } PyGetSetDef; typedef PyObject *(*wrapperfunc)(PyObject *self, PyObject *args, - void *wrapped); + void *wrapped); typedef PyObject *(*wrapperfunc_kwds)(PyObject *self, PyObject *args, - void *wrapped, PyObject *kwds); + void *wrapped, PyObject *kwds); struct wrapperbase { - char *name; - int offset; - void *function; - wrapperfunc wrapper; - char *doc; - int flags; - PyObject *name_strobj; + char *name; + int offset; + void *function; + wrapperfunc wrapper; + char *doc; + int flags; + PyObject *name_strobj; }; /* Flags for above struct */ @@ -38,33 +38,33 @@ /* Various kinds of descriptor objects */ #define PyDescr_COMMON \ - PyObject_HEAD \ - PyTypeObject *d_type; \ - PyObject *d_name + PyObject_HEAD \ + PyTypeObject *d_type; \ + PyObject *d_name typedef struct { - PyDescr_COMMON; + PyDescr_COMMON; } PyDescrObject; typedef struct { - PyDescr_COMMON; - PyMethodDef *d_method; + PyDescr_COMMON; + PyMethodDef *d_method; } PyMethodDescrObject; typedef struct { - PyDescr_COMMON; - struct PyMemberDef *d_member; + PyDescr_COMMON; + struct PyMemberDef *d_member; } PyMemberDescrObject; typedef struct { - PyDescr_COMMON; - PyGetSetDef *d_getset; + PyDescr_COMMON; + PyGetSetDef *d_getset; } PyGetSetDescrObject; typedef struct { - PyDescr_COMMON; - struct wrapperbase *d_base; - void *d_wrapped; /* This can be any function pointer */ + PyDescr_COMMON; + struct wrapperbase *d_base; + void *d_wrapped; /* This can be any function pointer */ } PyWrapperDescrObject; PyAPI_DATA(PyTypeObject) PyClassMethodDescr_Type; @@ -77,11 +77,11 @@ PyAPI_FUNC(PyObject *) PyDescr_NewMethod(PyTypeObject *, PyMethodDef *); PyAPI_FUNC(PyObject *) PyDescr_NewClassMethod(PyTypeObject *, PyMethodDef *); PyAPI_FUNC(PyObject *) PyDescr_NewMember(PyTypeObject *, - struct PyMemberDef *); + struct PyMemberDef *); PyAPI_FUNC(PyObject *) PyDescr_NewGetSet(PyTypeObject *, - struct PyGetSetDef *); + struct PyGetSetDef *); PyAPI_FUNC(PyObject *) PyDescr_NewWrapper(PyTypeObject *, - struct wrapperbase *, void *); + struct wrapperbase *, void *); #define PyDescr_IsData(d) (Py_TYPE(d)->tp_descr_set != NULL) PyAPI_FUNC(PyObject *) PyDictProxy_New(PyObject *); Modified: python/branches/release31-maint/Include/dictobject.h ============================================================================== --- python/branches/release31-maint/Include/dictobject.h (original) +++ python/branches/release31-maint/Include/dictobject.h Sun May 9 18:14:21 2010 @@ -48,13 +48,13 @@ #define PyDict_MINSIZE 8 typedef struct { - /* Cached hash code of me_key. Note that hash codes are C longs. - * We have to use Py_ssize_t instead because dict_popitem() abuses - * me_hash to hold a search finger. - */ - Py_ssize_t me_hash; - PyObject *me_key; - PyObject *me_value; + /* Cached hash code of me_key. Note that hash codes are C longs. + * We have to use Py_ssize_t instead because dict_popitem() abuses + * me_hash to hold a search finger. + */ + Py_ssize_t me_hash; + PyObject *me_key; + PyObject *me_value; } PyDictEntry; /* @@ -68,24 +68,24 @@ */ typedef struct _dictobject PyDictObject; struct _dictobject { - PyObject_HEAD - Py_ssize_t ma_fill; /* # Active + # Dummy */ - Py_ssize_t ma_used; /* # Active */ - - /* The table contains ma_mask + 1 slots, and that's a power of 2. - * We store the mask instead of the size because the mask is more - * frequently needed. - */ - Py_ssize_t ma_mask; - - /* ma_table points to ma_smalltable for small tables, else to - * additional malloc'ed memory. ma_table is never NULL! This rule - * saves repeated runtime null-tests in the workhorse getitem and - * setitem calls. - */ - PyDictEntry *ma_table; - PyDictEntry *(*ma_lookup)(PyDictObject *mp, PyObject *key, long hash); - PyDictEntry ma_smalltable[PyDict_MINSIZE]; + PyObject_HEAD + Py_ssize_t ma_fill; /* # Active + # Dummy */ + Py_ssize_t ma_used; /* # Active */ + + /* The table contains ma_mask + 1 slots, and that's a power of 2. + * We store the mask instead of the size because the mask is more + * frequently needed. + */ + Py_ssize_t ma_mask; + + /* ma_table points to ma_smalltable for small tables, else to + * additional malloc'ed memory. ma_table is never NULL! This rule + * saves repeated runtime null-tests in the workhorse getitem and + * setitem calls. + */ + PyDictEntry *ma_table; + PyDictEntry *(*ma_lookup)(PyDictObject *mp, PyObject *key, long hash); + PyDictEntry ma_smalltable[PyDict_MINSIZE]; }; PyAPI_DATA(PyTypeObject) PyDict_Type; @@ -104,7 +104,7 @@ #define PyDictValues_Check(op) (Py_TYPE(op) == &PyDictValues_Type) /* This excludes Values, since they are not sets. */ # define PyDictViewSet_Check(op) \ - (PyDictKeys_Check(op) || PyDictItems_Check(op)) + (PyDictKeys_Check(op) || PyDictItems_Check(op)) PyAPI_FUNC(PyObject *) PyDict_New(void); @@ -114,9 +114,9 @@ PyAPI_FUNC(int) PyDict_DelItem(PyObject *mp, PyObject *key); PyAPI_FUNC(void) PyDict_Clear(PyObject *mp); PyAPI_FUNC(int) PyDict_Next( - PyObject *mp, Py_ssize_t *pos, PyObject **key, PyObject **value); + PyObject *mp, Py_ssize_t *pos, PyObject **key, PyObject **value); PyAPI_FUNC(int) _PyDict_Next( - PyObject *mp, Py_ssize_t *pos, PyObject **key, PyObject **value, long *hash); + PyObject *mp, Py_ssize_t *pos, PyObject **key, PyObject **value, long *hash); PyAPI_FUNC(PyObject *) PyDict_Keys(PyObject *mp); PyAPI_FUNC(PyObject *) PyDict_Values(PyObject *mp); PyAPI_FUNC(PyObject *) PyDict_Items(PyObject *mp); @@ -136,8 +136,8 @@ dict.update(other) is equivalent to PyDict_Merge(dict, other, 1). */ PyAPI_FUNC(int) PyDict_Merge(PyObject *mp, - PyObject *other, - int override); + PyObject *other, + int override); /* PyDict_MergeFromSeq2 updates/merges from an iterable object producing iterable objects of length 2. If override is true, the last occurrence @@ -145,8 +145,8 @@ is equivalent to dict={}; PyDict_MergeFromSeq(dict, seq2, 1). */ PyAPI_FUNC(int) PyDict_MergeFromSeq2(PyObject *d, - PyObject *seq2, - int override); + PyObject *seq2, + int override); PyAPI_FUNC(PyObject *) PyDict_GetItemString(PyObject *dp, const char *key); PyAPI_FUNC(int) PyDict_SetItemString(PyObject *dp, const char *key, PyObject *item); Modified: python/branches/release31-maint/Include/object.h ============================================================================== --- python/branches/release31-maint/Include/object.h (original) +++ python/branches/release31-maint/Include/object.h Sun May 9 18:14:21 2010 @@ -63,9 +63,9 @@ #ifdef Py_TRACE_REFS /* Define pointers to support a doubly-linked list of all live heap objects. */ -#define _PyObject_HEAD_EXTRA \ - struct _object *_ob_next; \ - struct _object *_ob_prev; +#define _PyObject_HEAD_EXTRA \ + struct _object *_ob_next; \ + struct _object *_ob_prev; #define _PyObject_EXTRA_INIT 0, 0, @@ -75,14 +75,14 @@ #endif /* PyObject_HEAD defines the initial segment of every PyObject. */ -#define PyObject_HEAD PyObject ob_base; +#define PyObject_HEAD PyObject ob_base; -#define PyObject_HEAD_INIT(type) \ - { _PyObject_EXTRA_INIT \ - 1, type }, +#define PyObject_HEAD_INIT(type) \ + { _PyObject_EXTRA_INIT \ + 1, type }, -#define PyVarObject_HEAD_INIT(type, size) \ - { PyObject_HEAD_INIT(type) size }, +#define PyVarObject_HEAD_INIT(type, size) \ + { PyObject_HEAD_INIT(type) size }, /* PyObject_VAR_HEAD defines the initial segment of all variable-size * container objects. These end with a declaration of an array with 1 @@ -99,19 +99,19 @@ * in addition, be cast to PyVarObject*. */ typedef struct _object { - _PyObject_HEAD_EXTRA - Py_ssize_t ob_refcnt; - struct _typeobject *ob_type; + _PyObject_HEAD_EXTRA + Py_ssize_t ob_refcnt; + struct _typeobject *ob_type; } PyObject; typedef struct { - PyObject ob_base; - Py_ssize_t ob_size; /* Number of items in variable part */ + PyObject ob_base; + Py_ssize_t ob_size; /* Number of items in variable part */ } PyVarObject; -#define Py_REFCNT(ob) (((PyObject*)(ob))->ob_refcnt) -#define Py_TYPE(ob) (((PyObject*)(ob))->ob_type) -#define Py_SIZE(ob) (((PyVarObject*)(ob))->ob_size) +#define Py_REFCNT(ob) (((PyObject*)(ob))->ob_refcnt) +#define Py_TYPE(ob) (((PyObject*)(ob))->ob_type) +#define Py_SIZE(ob) (((PyVarObject*)(ob))->ob_size) /* Type objects contain a string containing the type name (to help somewhat @@ -142,26 +142,26 @@ /* buffer interface */ typedef struct bufferinfo { - void *buf; - PyObject *obj; /* owned reference */ - Py_ssize_t len; - Py_ssize_t itemsize; /* This is Py_ssize_t so it can be - pointed to by strides in simple case.*/ - int readonly; - int ndim; - char *format; - Py_ssize_t *shape; - Py_ssize_t *strides; - Py_ssize_t *suboffsets; - Py_ssize_t smalltable[2]; /* static store for shape and strides of - mono-dimensional buffers. */ - void *internal; + void *buf; + PyObject *obj; /* owned reference */ + Py_ssize_t len; + Py_ssize_t itemsize; /* This is Py_ssize_t so it can be + pointed to by strides in simple case.*/ + int readonly; + int ndim; + char *format; + Py_ssize_t *shape; + Py_ssize_t *strides; + Py_ssize_t *suboffsets; + Py_ssize_t smalltable[2]; /* static store for shape and strides of + mono-dimensional buffers. */ + void *internal; } Py_buffer; typedef int (*getbufferproc)(PyObject *, Py_buffer *, int); typedef void (*releasebufferproc)(PyObject *, Py_buffer *); - /* Flags for getting buffers */ + /* Flags for getting buffers */ #define PyBUF_SIMPLE 0 #define PyBUF_WRITABLE 0x0001 /* we used to include an E, backwards compatible alias */ @@ -198,67 +198,67 @@ typedef int (*traverseproc)(PyObject *, visitproc, void *); typedef struct { - /* Number implementations must check *both* - arguments for proper type and implement the necessary conversions - in the slot functions themselves. */ - - binaryfunc nb_add; - binaryfunc nb_subtract; - binaryfunc nb_multiply; - binaryfunc nb_remainder; - binaryfunc nb_divmod; - ternaryfunc nb_power; - unaryfunc nb_negative; - unaryfunc nb_positive; - unaryfunc nb_absolute; - inquiry nb_bool; - unaryfunc nb_invert; - binaryfunc nb_lshift; - binaryfunc nb_rshift; - binaryfunc nb_and; - binaryfunc nb_xor; - binaryfunc nb_or; - unaryfunc nb_int; - void *nb_reserved; /* the slot formerly known as nb_long */ - unaryfunc nb_float; - - binaryfunc nb_inplace_add; - binaryfunc nb_inplace_subtract; - binaryfunc nb_inplace_multiply; - binaryfunc nb_inplace_remainder; - ternaryfunc nb_inplace_power; - binaryfunc nb_inplace_lshift; - binaryfunc nb_inplace_rshift; - binaryfunc nb_inplace_and; - binaryfunc nb_inplace_xor; - binaryfunc nb_inplace_or; - - binaryfunc nb_floor_divide; - binaryfunc nb_true_divide; - binaryfunc nb_inplace_floor_divide; - binaryfunc nb_inplace_true_divide; + /* Number implementations must check *both* + arguments for proper type and implement the necessary conversions + in the slot functions themselves. */ + + binaryfunc nb_add; + binaryfunc nb_subtract; + binaryfunc nb_multiply; + binaryfunc nb_remainder; + binaryfunc nb_divmod; + ternaryfunc nb_power; + unaryfunc nb_negative; + unaryfunc nb_positive; + unaryfunc nb_absolute; + inquiry nb_bool; + unaryfunc nb_invert; + binaryfunc nb_lshift; + binaryfunc nb_rshift; + binaryfunc nb_and; + binaryfunc nb_xor; + binaryfunc nb_or; + unaryfunc nb_int; + void *nb_reserved; /* the slot formerly known as nb_long */ + unaryfunc nb_float; + + binaryfunc nb_inplace_add; + binaryfunc nb_inplace_subtract; + binaryfunc nb_inplace_multiply; + binaryfunc nb_inplace_remainder; + ternaryfunc nb_inplace_power; + binaryfunc nb_inplace_lshift; + binaryfunc nb_inplace_rshift; + binaryfunc nb_inplace_and; + binaryfunc nb_inplace_xor; + binaryfunc nb_inplace_or; + + binaryfunc nb_floor_divide; + binaryfunc nb_true_divide; + binaryfunc nb_inplace_floor_divide; + binaryfunc nb_inplace_true_divide; - unaryfunc nb_index; + unaryfunc nb_index; } PyNumberMethods; typedef struct { - lenfunc sq_length; - binaryfunc sq_concat; - ssizeargfunc sq_repeat; - ssizeargfunc sq_item; - void *was_sq_slice; - ssizeobjargproc sq_ass_item; - void *was_sq_ass_slice; - objobjproc sq_contains; + lenfunc sq_length; + binaryfunc sq_concat; + ssizeargfunc sq_repeat; + ssizeargfunc sq_item; + void *was_sq_slice; + ssizeobjargproc sq_ass_item; + void *was_sq_ass_slice; + objobjproc sq_contains; - binaryfunc sq_inplace_concat; - ssizeargfunc sq_inplace_repeat; + binaryfunc sq_inplace_concat; + ssizeargfunc sq_inplace_repeat; } PySequenceMethods; typedef struct { - lenfunc mp_length; - binaryfunc mp_subscript; - objobjargproc mp_ass_subscript; + lenfunc mp_length; + binaryfunc mp_subscript; + objobjargproc mp_ass_subscript; } PyMappingMethods; @@ -286,109 +286,109 @@ typedef PyObject *(*allocfunc)(struct _typeobject *, Py_ssize_t); typedef struct _typeobject { - PyObject_VAR_HEAD - const char *tp_name; /* For printing, in format "." */ - Py_ssize_t tp_basicsize, tp_itemsize; /* For allocation */ - - /* Methods to implement standard operations */ - - destructor tp_dealloc; - printfunc tp_print; - getattrfunc tp_getattr; - setattrfunc tp_setattr; - void *tp_reserved; /* formerly known as tp_compare */ - reprfunc tp_repr; - - /* Method suites for standard classes */ - - PyNumberMethods *tp_as_number; - PySequenceMethods *tp_as_sequence; - PyMappingMethods *tp_as_mapping; - - /* More standard operations (here for binary compatibility) */ - - hashfunc tp_hash; - ternaryfunc tp_call; - reprfunc tp_str; - getattrofunc tp_getattro; - setattrofunc tp_setattro; - - /* Functions to access object as input/output buffer */ - PyBufferProcs *tp_as_buffer; - - /* Flags to define presence of optional/expanded features */ - long tp_flags; - - const char *tp_doc; /* Documentation string */ - - /* Assigned meaning in release 2.0 */ - /* call function for all accessible objects */ - traverseproc tp_traverse; - - /* delete references to contained objects */ - inquiry tp_clear; - - /* Assigned meaning in release 2.1 */ - /* rich comparisons */ - richcmpfunc tp_richcompare; - - /* weak reference enabler */ - Py_ssize_t tp_weaklistoffset; - - /* Iterators */ - getiterfunc tp_iter; - iternextfunc tp_iternext; - - /* Attribute descriptor and subclassing stuff */ - struct PyMethodDef *tp_methods; - struct PyMemberDef *tp_members; - struct PyGetSetDef *tp_getset; - struct _typeobject *tp_base; - PyObject *tp_dict; - descrgetfunc tp_descr_get; - descrsetfunc tp_descr_set; - Py_ssize_t tp_dictoffset; - initproc tp_init; - allocfunc tp_alloc; - newfunc tp_new; - freefunc tp_free; /* Low-level free-memory routine */ - inquiry tp_is_gc; /* For PyObject_IS_GC */ - PyObject *tp_bases; - PyObject *tp_mro; /* method resolution order */ - PyObject *tp_cache; - PyObject *tp_subclasses; - PyObject *tp_weaklist; - destructor tp_del; + PyObject_VAR_HEAD + const char *tp_name; /* For printing, in format "." */ + Py_ssize_t tp_basicsize, tp_itemsize; /* For allocation */ + + /* Methods to implement standard operations */ + + destructor tp_dealloc; + printfunc tp_print; + getattrfunc tp_getattr; + setattrfunc tp_setattr; + void *tp_reserved; /* formerly known as tp_compare */ + reprfunc tp_repr; + + /* Method suites for standard classes */ + + PyNumberMethods *tp_as_number; + PySequenceMethods *tp_as_sequence; + PyMappingMethods *tp_as_mapping; + + /* More standard operations (here for binary compatibility) */ + + hashfunc tp_hash; + ternaryfunc tp_call; + reprfunc tp_str; + getattrofunc tp_getattro; + setattrofunc tp_setattro; + + /* Functions to access object as input/output buffer */ + PyBufferProcs *tp_as_buffer; + + /* Flags to define presence of optional/expanded features */ + long tp_flags; + + const char *tp_doc; /* Documentation string */ + + /* Assigned meaning in release 2.0 */ + /* call function for all accessible objects */ + traverseproc tp_traverse; + + /* delete references to contained objects */ + inquiry tp_clear; + + /* Assigned meaning in release 2.1 */ + /* rich comparisons */ + richcmpfunc tp_richcompare; + + /* weak reference enabler */ + Py_ssize_t tp_weaklistoffset; + + /* Iterators */ + getiterfunc tp_iter; + iternextfunc tp_iternext; + + /* Attribute descriptor and subclassing stuff */ + struct PyMethodDef *tp_methods; + struct PyMemberDef *tp_members; + struct PyGetSetDef *tp_getset; + struct _typeobject *tp_base; + PyObject *tp_dict; + descrgetfunc tp_descr_get; + descrsetfunc tp_descr_set; + Py_ssize_t tp_dictoffset; + initproc tp_init; + allocfunc tp_alloc; + newfunc tp_new; + freefunc tp_free; /* Low-level free-memory routine */ + inquiry tp_is_gc; /* For PyObject_IS_GC */ + PyObject *tp_bases; + PyObject *tp_mro; /* method resolution order */ + PyObject *tp_cache; + PyObject *tp_subclasses; + PyObject *tp_weaklist; + destructor tp_del; - /* Type attribute cache version tag. Added in version 2.6 */ - unsigned int tp_version_tag; + /* Type attribute cache version tag. Added in version 2.6 */ + unsigned int tp_version_tag; #ifdef COUNT_ALLOCS - /* these must be last and never explicitly initialized */ - Py_ssize_t tp_allocs; - Py_ssize_t tp_frees; - Py_ssize_t tp_maxalloc; - struct _typeobject *tp_prev; - struct _typeobject *tp_next; + /* these must be last and never explicitly initialized */ + Py_ssize_t tp_allocs; + Py_ssize_t tp_frees; + Py_ssize_t tp_maxalloc; + struct _typeobject *tp_prev; + struct _typeobject *tp_next; #endif } PyTypeObject; /* The *real* layout of a type object when allocated on the heap */ typedef struct _heaptypeobject { - /* Note: there's a dependency on the order of these members - in slotptr() in typeobject.c . */ - PyTypeObject ht_type; - PyNumberMethods as_number; - PyMappingMethods as_mapping; - PySequenceMethods as_sequence; /* as_sequence comes after as_mapping, - so that the mapping wins when both - the mapping and the sequence define - a given operator (e.g. __getitem__). - see add_operators() in typeobject.c . */ - PyBufferProcs as_buffer; - PyObject *ht_name, *ht_slots; - /* here are optional user slots, followed by the members. */ + /* Note: there's a dependency on the order of these members + in slotptr() in typeobject.c . */ + PyTypeObject ht_type; + PyNumberMethods as_number; + PyMappingMethods as_mapping; + PySequenceMethods as_sequence; /* as_sequence comes after as_mapping, + so that the mapping wins when both + the mapping and the sequence define + a given operator (e.g. __getitem__). + see add_operators() in typeobject.c . */ + PyBufferProcs as_buffer; + PyObject *ht_name, *ht_slots; + /* here are optional user slots, followed by the members. */ } PyHeapTypeObject; /* access macro to the members which are floating "behind" the object */ @@ -399,20 +399,20 @@ /* Generic type check */ PyAPI_FUNC(int) PyType_IsSubtype(PyTypeObject *, PyTypeObject *); #define PyObject_TypeCheck(ob, tp) \ - (Py_TYPE(ob) == (tp) || PyType_IsSubtype(Py_TYPE(ob), (tp))) + (Py_TYPE(ob) == (tp) || PyType_IsSubtype(Py_TYPE(ob), (tp))) PyAPI_DATA(PyTypeObject) PyType_Type; /* built-in 'type' */ PyAPI_DATA(PyTypeObject) PyBaseObject_Type; /* built-in 'object' */ PyAPI_DATA(PyTypeObject) PySuper_Type; /* built-in 'super' */ #define PyType_Check(op) \ - PyType_FastSubclass(Py_TYPE(op), Py_TPFLAGS_TYPE_SUBCLASS) + PyType_FastSubclass(Py_TYPE(op), Py_TPFLAGS_TYPE_SUBCLASS) #define PyType_CheckExact(op) (Py_TYPE(op) == &PyType_Type) PyAPI_FUNC(int) PyType_Ready(PyTypeObject *); PyAPI_FUNC(PyObject *) PyType_GenericAlloc(PyTypeObject *, Py_ssize_t); PyAPI_FUNC(PyObject *) PyType_GenericNew(PyTypeObject *, - PyObject *, PyObject *); + PyObject *, PyObject *); PyAPI_FUNC(PyObject *) _PyType_Lookup(PyTypeObject *, PyObject *); PyAPI_FUNC(PyObject *) _PyObject_LookupSpecial(PyObject *, char *, PyObject **); PyAPI_FUNC(unsigned int) PyType_ClearCache(void); @@ -439,7 +439,7 @@ PyAPI_FUNC(PyObject *) _PyObject_NextNotImplemented(PyObject *); PyAPI_FUNC(PyObject *) PyObject_GenericGetAttr(PyObject *, PyObject *); PyAPI_FUNC(int) PyObject_GenericSetAttr(PyObject *, - PyObject *, PyObject *); + PyObject *, PyObject *); PyAPI_FUNC(long) PyObject_Hash(PyObject *); PyAPI_FUNC(long) PyObject_HashNotImplemented(PyObject *); PyAPI_FUNC(int) PyObject_IsTrue(PyObject *); @@ -469,7 +469,7 @@ #define PyObject_REPR(obj) _PyUnicode_AsString(PyObject_Repr(obj)) /* Flag bits for printing: */ -#define Py_PRINT_RAW 1 /* No string quotes etc. */ +#define Py_PRINT_RAW 1 /* No string quotes etc. */ /* `Type flags (tp_flags) @@ -524,20 +524,20 @@ #define Py_TPFLAGS_IS_ABSTRACT (1L<<20) /* These flags are used to determine if a type is a subclass. */ -#define Py_TPFLAGS_INT_SUBCLASS (1L<<23) -#define Py_TPFLAGS_LONG_SUBCLASS (1L<<24) -#define Py_TPFLAGS_LIST_SUBCLASS (1L<<25) -#define Py_TPFLAGS_TUPLE_SUBCLASS (1L<<26) -#define Py_TPFLAGS_BYTES_SUBCLASS (1L<<27) -#define Py_TPFLAGS_UNICODE_SUBCLASS (1L<<28) -#define Py_TPFLAGS_DICT_SUBCLASS (1L<<29) -#define Py_TPFLAGS_BASE_EXC_SUBCLASS (1L<<30) -#define Py_TPFLAGS_TYPE_SUBCLASS (1L<<31) +#define Py_TPFLAGS_INT_SUBCLASS (1L<<23) +#define Py_TPFLAGS_LONG_SUBCLASS (1L<<24) +#define Py_TPFLAGS_LIST_SUBCLASS (1L<<25) +#define Py_TPFLAGS_TUPLE_SUBCLASS (1L<<26) +#define Py_TPFLAGS_BYTES_SUBCLASS (1L<<27) +#define Py_TPFLAGS_UNICODE_SUBCLASS (1L<<28) +#define Py_TPFLAGS_DICT_SUBCLASS (1L<<29) +#define Py_TPFLAGS_BASE_EXC_SUBCLASS (1L<<30) +#define Py_TPFLAGS_TYPE_SUBCLASS (1L<<31) #define Py_TPFLAGS_DEFAULT ( \ - Py_TPFLAGS_HAVE_STACKLESS_EXTENSION | \ - Py_TPFLAGS_HAVE_VERSION_TAG | \ - 0) + Py_TPFLAGS_HAVE_STACKLESS_EXTENSION | \ + Py_TPFLAGS_HAVE_VERSION_TAG | \ + 0) #define PyType_HasFeature(t,f) (((t)->tp_flags & (f)) != 0) #define PyType_FastSubclass(t,f) PyType_HasFeature(t,f) @@ -589,32 +589,32 @@ #ifdef Py_REF_DEBUG PyAPI_DATA(Py_ssize_t) _Py_RefTotal; PyAPI_FUNC(void) _Py_NegativeRefcount(const char *fname, - int lineno, PyObject *op); + int lineno, PyObject *op); PyAPI_FUNC(PyObject *) _PyDict_Dummy(void); PyAPI_FUNC(PyObject *) _PySet_Dummy(void); PyAPI_FUNC(Py_ssize_t) _Py_GetRefTotal(void); -#define _Py_INC_REFTOTAL _Py_RefTotal++ -#define _Py_DEC_REFTOTAL _Py_RefTotal-- -#define _Py_REF_DEBUG_COMMA , -#define _Py_CHECK_REFCNT(OP) \ -{ if (((PyObject*)OP)->ob_refcnt < 0) \ - _Py_NegativeRefcount(__FILE__, __LINE__, \ - (PyObject *)(OP)); \ +#define _Py_INC_REFTOTAL _Py_RefTotal++ +#define _Py_DEC_REFTOTAL _Py_RefTotal-- +#define _Py_REF_DEBUG_COMMA , +#define _Py_CHECK_REFCNT(OP) \ +{ if (((PyObject*)OP)->ob_refcnt < 0) \ + _Py_NegativeRefcount(__FILE__, __LINE__, \ + (PyObject *)(OP)); \ } #else #define _Py_INC_REFTOTAL #define _Py_DEC_REFTOTAL #define _Py_REF_DEBUG_COMMA -#define _Py_CHECK_REFCNT(OP) /* a semicolon */; +#define _Py_CHECK_REFCNT(OP) /* a semicolon */; #endif /* Py_REF_DEBUG */ #ifdef COUNT_ALLOCS PyAPI_FUNC(void) inc_count(PyTypeObject *); PyAPI_FUNC(void) dec_count(PyTypeObject *); -#define _Py_INC_TPALLOCS(OP) inc_count(Py_TYPE(OP)) -#define _Py_INC_TPFREES(OP) dec_count(Py_TYPE(OP)) -#define _Py_DEC_TPFREES(OP) Py_TYPE(OP)->tp_frees-- -#define _Py_COUNT_ALLOCS_COMMA , +#define _Py_INC_TPALLOCS(OP) inc_count(Py_TYPE(OP)) +#define _Py_INC_TPFREES(OP) dec_count(Py_TYPE(OP)) +#define _Py_DEC_TPFREES(OP) Py_TYPE(OP)->tp_frees-- +#define _Py_COUNT_ALLOCS_COMMA , #else #define _Py_INC_TPALLOCS(OP) #define _Py_INC_TPFREES(OP) @@ -635,30 +635,30 @@ /* Without Py_TRACE_REFS, there's little enough to do that we expand code * inline. */ -#define _Py_NewReference(op) ( \ - _Py_INC_TPALLOCS(op) _Py_COUNT_ALLOCS_COMMA \ - _Py_INC_REFTOTAL _Py_REF_DEBUG_COMMA \ - Py_REFCNT(op) = 1) +#define _Py_NewReference(op) ( \ + _Py_INC_TPALLOCS(op) _Py_COUNT_ALLOCS_COMMA \ + _Py_INC_REFTOTAL _Py_REF_DEBUG_COMMA \ + Py_REFCNT(op) = 1) #define _Py_ForgetReference(op) _Py_INC_TPFREES(op) -#define _Py_Dealloc(op) ( \ - _Py_INC_TPFREES(op) _Py_COUNT_ALLOCS_COMMA \ - (*Py_TYPE(op)->tp_dealloc)((PyObject *)(op))) +#define _Py_Dealloc(op) ( \ + _Py_INC_TPFREES(op) _Py_COUNT_ALLOCS_COMMA \ + (*Py_TYPE(op)->tp_dealloc)((PyObject *)(op))) #endif /* !Py_TRACE_REFS */ -#define Py_INCREF(op) ( \ - _Py_INC_REFTOTAL _Py_REF_DEBUG_COMMA \ - ((PyObject*)(op))->ob_refcnt++) - -#define Py_DECREF(op) \ - do { \ - if (_Py_DEC_REFTOTAL _Py_REF_DEBUG_COMMA \ - --((PyObject*)(op))->ob_refcnt != 0) \ - _Py_CHECK_REFCNT(op) \ - else \ - _Py_Dealloc((PyObject *)(op)); \ - } while (0) +#define Py_INCREF(op) ( \ + _Py_INC_REFTOTAL _Py_REF_DEBUG_COMMA \ + ((PyObject*)(op))->ob_refcnt++) + +#define Py_DECREF(op) \ + do { \ + if (_Py_DEC_REFTOTAL _Py_REF_DEBUG_COMMA \ + --((PyObject*)(op))->ob_refcnt != 0) \ + _Py_CHECK_REFCNT(op) \ + else \ + _Py_Dealloc((PyObject *)(op)); \ + } while (0) /* Safely decref `op` and set `op` to NULL, especially useful in tp_clear * and tp_dealloc implementatons. @@ -694,14 +694,14 @@ * Python integers aren't currently weakly referencable. Best practice is * to use Py_CLEAR() even if you can't think of a reason for why you need to. */ -#define Py_CLEAR(op) \ - do { \ - if (op) { \ - PyObject *_py_tmp = (PyObject *)(op); \ - (op) = NULL; \ - Py_DECREF(_py_tmp); \ - } \ - } while (0) +#define Py_CLEAR(op) \ + do { \ + if (op) { \ + PyObject *_py_tmp = (PyObject *)(op); \ + (op) = NULL; \ + Py_DECREF(_py_tmp); \ + } \ + } while (0) /* Macros to use in case the object pointer may be NULL: */ #define Py_XINCREF(op) do { if ((op) == NULL) ; else Py_INCREF(op); } while (0) @@ -813,13 +813,13 @@ static void mytype_dealloc(mytype *p) { - ... declarations go here ... + ... declarations go here ... - PyObject_GC_UnTrack(p); // must untrack first - Py_TRASHCAN_SAFE_BEGIN(p) - ... The body of the deallocator goes here, including all calls ... - ... to Py_DECREF on contained objects. ... - Py_TRASHCAN_SAFE_END(p) + PyObject_GC_UnTrack(p); // must untrack first + Py_TRASHCAN_SAFE_BEGIN(p) + ... The body of the deallocator goes here, including all calls ... + ... to Py_DECREF on contained objects. ... + Py_TRASHCAN_SAFE_END(p) } CAUTION: Never return from the middle of the body! If the body needs to @@ -849,16 +849,16 @@ #define PyTrash_UNWIND_LEVEL 50 #define Py_TRASHCAN_SAFE_BEGIN(op) \ - if (_PyTrash_delete_nesting < PyTrash_UNWIND_LEVEL) { \ - ++_PyTrash_delete_nesting; - /* The body of the deallocator is here. */ + if (_PyTrash_delete_nesting < PyTrash_UNWIND_LEVEL) { \ + ++_PyTrash_delete_nesting; + /* The body of the deallocator is here. */ #define Py_TRASHCAN_SAFE_END(op) \ - --_PyTrash_delete_nesting; \ - if (_PyTrash_delete_later && _PyTrash_delete_nesting <= 0) \ - _PyTrash_destroy_chain(); \ - } \ - else \ - _PyTrash_deposit_object((PyObject*)op); + --_PyTrash_delete_nesting; \ + if (_PyTrash_delete_later && _PyTrash_delete_nesting <= 0) \ + _PyTrash_destroy_chain(); \ + } \ + else \ + _PyTrash_deposit_object((PyObject*)op); #ifdef __cplusplus } Modified: python/branches/release31-maint/Include/objimpl.h ============================================================================== --- python/branches/release31-maint/Include/objimpl.h (original) +++ python/branches/release31-maint/Include/objimpl.h Sun May 9 18:14:21 2010 @@ -101,35 +101,35 @@ /* Macros */ #ifdef WITH_PYMALLOC -#ifdef PYMALLOC_DEBUG /* WITH_PYMALLOC && PYMALLOC_DEBUG */ +#ifdef PYMALLOC_DEBUG /* WITH_PYMALLOC && PYMALLOC_DEBUG */ PyAPI_FUNC(void *) _PyObject_DebugMalloc(size_t nbytes); PyAPI_FUNC(void *) _PyObject_DebugRealloc(void *p, size_t nbytes); PyAPI_FUNC(void) _PyObject_DebugFree(void *p); PyAPI_FUNC(void) _PyObject_DebugDumpAddress(const void *p); PyAPI_FUNC(void) _PyObject_DebugCheckAddress(const void *p); PyAPI_FUNC(void) _PyObject_DebugMallocStats(void); -#define PyObject_MALLOC _PyObject_DebugMalloc -#define PyObject_Malloc _PyObject_DebugMalloc -#define PyObject_REALLOC _PyObject_DebugRealloc -#define PyObject_Realloc _PyObject_DebugRealloc -#define PyObject_FREE _PyObject_DebugFree -#define PyObject_Free _PyObject_DebugFree - -#else /* WITH_PYMALLOC && ! PYMALLOC_DEBUG */ -#define PyObject_MALLOC PyObject_Malloc -#define PyObject_REALLOC PyObject_Realloc -#define PyObject_FREE PyObject_Free +#define PyObject_MALLOC _PyObject_DebugMalloc +#define PyObject_Malloc _PyObject_DebugMalloc +#define PyObject_REALLOC _PyObject_DebugRealloc +#define PyObject_Realloc _PyObject_DebugRealloc +#define PyObject_FREE _PyObject_DebugFree +#define PyObject_Free _PyObject_DebugFree + +#else /* WITH_PYMALLOC && ! PYMALLOC_DEBUG */ +#define PyObject_MALLOC PyObject_Malloc +#define PyObject_REALLOC PyObject_Realloc +#define PyObject_FREE PyObject_Free #endif -#else /* ! WITH_PYMALLOC */ -#define PyObject_MALLOC PyMem_MALLOC -#define PyObject_REALLOC PyMem_REALLOC -#define PyObject_FREE PyMem_FREE +#else /* ! WITH_PYMALLOC */ +#define PyObject_MALLOC PyMem_MALLOC +#define PyObject_REALLOC PyMem_REALLOC +#define PyObject_FREE PyMem_FREE -#endif /* WITH_PYMALLOC */ +#endif /* WITH_PYMALLOC */ -#define PyObject_Del PyObject_Free -#define PyObject_DEL PyObject_FREE +#define PyObject_Del PyObject_Free +#define PyObject_DEL PyObject_FREE /* * Generic object allocator interface @@ -144,16 +144,16 @@ PyAPI_FUNC(PyVarObject *) _PyObject_NewVar(PyTypeObject *, Py_ssize_t); #define PyObject_New(type, typeobj) \ - ( (type *) _PyObject_New(typeobj) ) + ( (type *) _PyObject_New(typeobj) ) #define PyObject_NewVar(type, typeobj, n) \ - ( (type *) _PyObject_NewVar((typeobj), (n)) ) + ( (type *) _PyObject_NewVar((typeobj), (n)) ) /* Macros trading binary compatibility for speed. See also pymem.h. Note that these macros expect non-NULL object pointers.*/ #define PyObject_INIT(op, typeobj) \ - ( Py_TYPE(op) = (typeobj), _Py_NewReference((PyObject *)(op)), (op) ) + ( Py_TYPE(op) = (typeobj), _Py_NewReference((PyObject *)(op)), (op) ) #define PyObject_INIT_VAR(op, typeobj, size) \ - ( Py_SIZE(op) = (size), PyObject_INIT((op), (typeobj)) ) + ( Py_SIZE(op) = (size), PyObject_INIT((op), (typeobj)) ) #define _PyObject_SIZE(typeobj) ( (typeobj)->tp_basicsize ) @@ -171,17 +171,17 @@ # error "_PyObject_VAR_SIZE requires SIZEOF_VOID_P be a power of 2" #endif -#define _PyObject_VAR_SIZE(typeobj, nitems) \ - (size_t) \ - ( ( (typeobj)->tp_basicsize + \ - (nitems)*(typeobj)->tp_itemsize + \ - (SIZEOF_VOID_P - 1) \ - ) & ~(SIZEOF_VOID_P - 1) \ - ) +#define _PyObject_VAR_SIZE(typeobj, nitems) \ + (size_t) \ + ( ( (typeobj)->tp_basicsize + \ + (nitems)*(typeobj)->tp_itemsize + \ + (SIZEOF_VOID_P - 1) \ + ) & ~(SIZEOF_VOID_P - 1) \ + ) #define PyObject_NEW(type, typeobj) \ ( (type *) PyObject_Init( \ - (PyObject *) PyObject_MALLOC( _PyObject_SIZE(typeobj) ), (typeobj)) ) + (PyObject *) PyObject_MALLOC( _PyObject_SIZE(typeobj) ), (typeobj)) ) #define PyObject_NEW_VAR(type, typeobj, n) \ ( (type *) PyObject_InitVar( \ @@ -193,7 +193,7 @@ distinction between two steps (at least): 1) the actual allocation of the object storage; 2) the initialization of the Python specific fields - in this storage with PyObject_{Init, InitVar}. + in this storage with PyObject_{Init, InitVar}. PyObject * YourObject_New(...) @@ -202,7 +202,7 @@ op = (PyObject *) Your_Allocator(_PyObject_SIZE(YourTypeStruct)); if (op == NULL) - return PyErr_NoMemory(); + return PyErr_NoMemory(); PyObject_Init(op, &YourTypeStruct); @@ -229,44 +229,44 @@ /* Test if an object has a GC head */ #define PyObject_IS_GC(o) (PyType_IS_GC(Py_TYPE(o)) && \ - (Py_TYPE(o)->tp_is_gc == NULL || Py_TYPE(o)->tp_is_gc(o))) + (Py_TYPE(o)->tp_is_gc == NULL || Py_TYPE(o)->tp_is_gc(o))) PyAPI_FUNC(PyVarObject *) _PyObject_GC_Resize(PyVarObject *, Py_ssize_t); #define PyObject_GC_Resize(type, op, n) \ - ( (type *) _PyObject_GC_Resize((PyVarObject *)(op), (n)) ) + ( (type *) _PyObject_GC_Resize((PyVarObject *)(op), (n)) ) /* for source compatibility with 2.2 */ #define _PyObject_GC_Del PyObject_GC_Del /* GC information is stored BEFORE the object structure. */ typedef union _gc_head { - struct { - union _gc_head *gc_next; - union _gc_head *gc_prev; - Py_ssize_t gc_refs; - } gc; - long double dummy; /* force worst-case alignment */ + struct { + union _gc_head *gc_next; + union _gc_head *gc_prev; + Py_ssize_t gc_refs; + } gc; + long double dummy; /* force worst-case alignment */ } PyGC_Head; extern PyGC_Head *_PyGC_generation0; #define _Py_AS_GC(o) ((PyGC_Head *)(o)-1) -#define _PyGC_REFS_UNTRACKED (-2) -#define _PyGC_REFS_REACHABLE (-3) -#define _PyGC_REFS_TENTATIVELY_UNREACHABLE (-4) +#define _PyGC_REFS_UNTRACKED (-2) +#define _PyGC_REFS_REACHABLE (-3) +#define _PyGC_REFS_TENTATIVELY_UNREACHABLE (-4) /* Tell the GC to track this object. NB: While the object is tracked the * collector it must be safe to call the ob_traverse method. */ #define _PyObject_GC_TRACK(o) do { \ - PyGC_Head *g = _Py_AS_GC(o); \ - if (g->gc.gc_refs != _PyGC_REFS_UNTRACKED) \ - Py_FatalError("GC object already tracked"); \ - g->gc.gc_refs = _PyGC_REFS_REACHABLE; \ - g->gc.gc_next = _PyGC_generation0; \ - g->gc.gc_prev = _PyGC_generation0->gc.gc_prev; \ - g->gc.gc_prev->gc.gc_next = g; \ - _PyGC_generation0->gc.gc_prev = g; \ + PyGC_Head *g = _Py_AS_GC(o); \ + if (g->gc.gc_refs != _PyGC_REFS_UNTRACKED) \ + Py_FatalError("GC object already tracked"); \ + g->gc.gc_refs = _PyGC_REFS_REACHABLE; \ + g->gc.gc_next = _PyGC_generation0; \ + g->gc.gc_prev = _PyGC_generation0->gc.gc_prev; \ + g->gc.gc_prev->gc.gc_next = g; \ + _PyGC_generation0->gc.gc_prev = g; \ } while (0); /* Tell the GC to stop tracking this object. @@ -274,23 +274,23 @@ * way to provoke memory errors if calling code is confused. */ #define _PyObject_GC_UNTRACK(o) do { \ - PyGC_Head *g = _Py_AS_GC(o); \ - assert(g->gc.gc_refs != _PyGC_REFS_UNTRACKED); \ - g->gc.gc_refs = _PyGC_REFS_UNTRACKED; \ - g->gc.gc_prev->gc.gc_next = g->gc.gc_next; \ - g->gc.gc_next->gc.gc_prev = g->gc.gc_prev; \ - g->gc.gc_next = NULL; \ + PyGC_Head *g = _Py_AS_GC(o); \ + assert(g->gc.gc_refs != _PyGC_REFS_UNTRACKED); \ + g->gc.gc_refs = _PyGC_REFS_UNTRACKED; \ + g->gc.gc_prev->gc.gc_next = g->gc.gc_next; \ + g->gc.gc_next->gc.gc_prev = g->gc.gc_prev; \ + g->gc.gc_next = NULL; \ } while (0); /* True if the object is currently tracked by the GC. */ #define _PyObject_GC_IS_TRACKED(o) \ - ((_Py_AS_GC(o))->gc.gc_refs != _PyGC_REFS_UNTRACKED) - + ((_Py_AS_GC(o))->gc.gc_refs != _PyGC_REFS_UNTRACKED) + /* True if the object may be tracked by the GC in the future, or already is. This can be useful to implement some optimizations. */ #define _PyObject_GC_MAY_BE_TRACKED(obj) \ - (PyObject_IS_GC(obj) && \ - (!PyTuple_CheckExact(obj) || _PyObject_GC_IS_TRACKED(obj))) + (PyObject_IS_GC(obj) && \ + (!PyTuple_CheckExact(obj) || _PyObject_GC_IS_TRACKED(obj))) PyAPI_FUNC(PyObject *) _PyObject_GC_Malloc(size_t); @@ -301,9 +301,9 @@ PyAPI_FUNC(void) PyObject_GC_Del(void *); #define PyObject_GC_New(type, typeobj) \ - ( (type *) _PyObject_GC_New(typeobj) ) + ( (type *) _PyObject_GC_New(typeobj) ) #define PyObject_GC_NewVar(type, typeobj, n) \ - ( (type *) _PyObject_GC_NewVar((typeobj), (n)) ) + ( (type *) _PyObject_GC_NewVar((typeobj), (n)) ) /* Utility macro to help write tp_traverse functions. @@ -311,14 +311,14 @@ * "visit" and "arg". This is intended to keep tp_traverse functions * looking as much alike as possible. */ -#define Py_VISIT(op) \ - do { \ - if (op) { \ - int vret = visit((PyObject *)(op), arg); \ - if (vret) \ - return vret; \ - } \ - } while (0) +#define Py_VISIT(op) \ + do { \ + if (op) { \ + int vret = visit((PyObject *)(op), arg); \ + if (vret) \ + return vret; \ + } \ + } while (0) /* This is here for the sake of backwards compatibility. Extensions that * use the old GC API will still compile but the objects will not be @@ -334,7 +334,7 @@ #define PyType_SUPPORTS_WEAKREFS(t) ((t)->tp_weaklistoffset > 0) #define PyObject_GET_WEAKREFS_LISTPTR(o) \ - ((PyObject **) (((char *) (o)) + Py_TYPE(o)->tp_weaklistoffset)) + ((PyObject **) (((char *) (o)) + Py_TYPE(o)->tp_weaklistoffset)) #ifdef __cplusplus } Modified: python/branches/release31-maint/Include/pyerrors.h ============================================================================== --- python/branches/release31-maint/Include/pyerrors.h (original) +++ python/branches/release31-maint/Include/pyerrors.h Sun May 9 18:14:21 2010 @@ -8,8 +8,8 @@ /* PyException_HEAD defines the initial segment of every exception class. */ #define PyException_HEAD PyObject_HEAD PyObject *dict;\ - PyObject *args; PyObject *traceback;\ - PyObject *context; PyObject *cause; + PyObject *args; PyObject *traceback;\ + PyObject *context; PyObject *cause; typedef struct { PyException_HEAD @@ -92,15 +92,15 @@ /* */ -#define PyExceptionClass_Check(x) \ - (PyType_Check((x)) && \ - PyType_FastSubclass((PyTypeObject*)(x), Py_TPFLAGS_BASE_EXC_SUBCLASS)) +#define PyExceptionClass_Check(x) \ + (PyType_Check((x)) && \ + PyType_FastSubclass((PyTypeObject*)(x), Py_TPFLAGS_BASE_EXC_SUBCLASS)) -#define PyExceptionInstance_Check(x) \ - PyType_FastSubclass((x)->ob_type, Py_TPFLAGS_BASE_EXC_SUBCLASS) +#define PyExceptionInstance_Check(x) \ + PyType_FastSubclass((x)->ob_type, Py_TPFLAGS_BASE_EXC_SUBCLASS) #define PyExceptionClass_Name(x) \ - ((char *)(((PyTypeObject*)(x))->tp_name)) + ((char *)(((PyTypeObject*)(x))->tp_name)) #define PyExceptionInstance_Class(x) ((PyObject*)((x)->ob_type)) @@ -175,29 +175,29 @@ PyAPI_FUNC(PyObject *) PyErr_NoMemory(void); PyAPI_FUNC(PyObject *) PyErr_SetFromErrno(PyObject *); PyAPI_FUNC(PyObject *) PyErr_SetFromErrnoWithFilenameObject( - PyObject *, PyObject *); + PyObject *, PyObject *); PyAPI_FUNC(PyObject *) PyErr_SetFromErrnoWithFilename(PyObject *, const char *); #ifdef MS_WINDOWS PyAPI_FUNC(PyObject *) PyErr_SetFromErrnoWithUnicodeFilename( - PyObject *, const Py_UNICODE *); + PyObject *, const Py_UNICODE *); #endif /* MS_WINDOWS */ PyAPI_FUNC(PyObject *) PyErr_Format(PyObject *, const char *, ...); #ifdef MS_WINDOWS PyAPI_FUNC(PyObject *) PyErr_SetFromWindowsErrWithFilenameObject( - int, const char *); + int, const char *); PyAPI_FUNC(PyObject *) PyErr_SetFromWindowsErrWithFilename( - int, const char *); + int, const char *); PyAPI_FUNC(PyObject *) PyErr_SetFromWindowsErrWithUnicodeFilename( - int, const Py_UNICODE *); + int, const Py_UNICODE *); PyAPI_FUNC(PyObject *) PyErr_SetFromWindowsErr(int); PyAPI_FUNC(PyObject *) PyErr_SetExcFromWindowsErrWithFilenameObject( - PyObject *,int, PyObject *); + PyObject *,int, PyObject *); PyAPI_FUNC(PyObject *) PyErr_SetExcFromWindowsErrWithFilename( - PyObject *,int, const char *); + PyObject *,int, const char *); PyAPI_FUNC(PyObject *) PyErr_SetExcFromWindowsErrWithUnicodeFilename( - PyObject *,int, const Py_UNICODE *); + PyObject *,int, const Py_UNICODE *); PyAPI_FUNC(PyObject *) PyErr_SetExcFromWindowsErr(PyObject *, int); #endif /* MS_WINDOWS */ @@ -229,15 +229,15 @@ /* create a UnicodeDecodeError object */ PyAPI_FUNC(PyObject *) PyUnicodeDecodeError_Create( - const char *, const char *, Py_ssize_t, Py_ssize_t, Py_ssize_t, const char *); + const char *, const char *, Py_ssize_t, Py_ssize_t, Py_ssize_t, const char *); /* create a UnicodeEncodeError object */ PyAPI_FUNC(PyObject *) PyUnicodeEncodeError_Create( - const char *, const Py_UNICODE *, Py_ssize_t, Py_ssize_t, Py_ssize_t, const char *); + const char *, const Py_UNICODE *, Py_ssize_t, Py_ssize_t, Py_ssize_t, const char *); /* create a UnicodeTranslateError object */ PyAPI_FUNC(PyObject *) PyUnicodeTranslateError_Create( - const Py_UNICODE *, Py_ssize_t, Py_ssize_t, Py_ssize_t, const char *); + const Py_UNICODE *, Py_ssize_t, Py_ssize_t, Py_ssize_t, const char *); /* get the encoding attribute */ PyAPI_FUNC(PyObject *) PyUnicodeEncodeError_GetEncoding(PyObject *); @@ -280,11 +280,11 @@ /* assign a new value to the reason attribute return 0 on success, -1 on failure */ PyAPI_FUNC(int) PyUnicodeEncodeError_SetReason( - PyObject *, const char *); + PyObject *, const char *); PyAPI_FUNC(int) PyUnicodeDecodeError_SetReason( - PyObject *, const char *); + PyObject *, const char *); PyAPI_FUNC(int) PyUnicodeTranslateError_SetReason( - PyObject *, const char *); + PyObject *, const char *); /* These APIs aren't really part of the error implementation, but @@ -303,9 +303,9 @@ #include PyAPI_FUNC(int) PyOS_snprintf(char *str, size_t size, const char *format, ...) - Py_GCC_ATTRIBUTE((format(printf, 3, 4))); + Py_GCC_ATTRIBUTE((format(printf, 3, 4))); PyAPI_FUNC(int) PyOS_vsnprintf(char *str, size_t size, const char *format, va_list va) - Py_GCC_ATTRIBUTE((format(printf, 3, 0))); + Py_GCC_ATTRIBUTE((format(printf, 3, 0))); #ifdef __cplusplus } Modified: python/branches/release31-maint/Include/pymacconfig.h ============================================================================== --- python/branches/release31-maint/Include/pymacconfig.h (original) +++ python/branches/release31-maint/Include/pymacconfig.h Sun May 9 18:14:21 2010 @@ -4,7 +4,7 @@ * This file moves some of the autoconf magic to compile-time * when building on MacOSX. This is needed for building 4-way * universal binaries and for 64-bit universal binaries because - * the values redefined below aren't configure-time constant but + * the values redefined below aren't configure-time constant but * only compile-time constant in these scenarios. */ @@ -34,36 +34,36 @@ # undef SIZEOF_LONG # ifdef __LP64__ -# define SIZEOF__BOOL 1 -# define SIZEOF__BOOL 1 -# define SIZEOF_LONG 8 -# define SIZEOF_PTHREAD_T 8 -# define SIZEOF_SIZE_T 8 -# define SIZEOF_TIME_T 8 -# define SIZEOF_VOID_P 8 +# define SIZEOF__BOOL 1 +# define SIZEOF__BOOL 1 +# define SIZEOF_LONG 8 +# define SIZEOF_PTHREAD_T 8 +# define SIZEOF_SIZE_T 8 +# define SIZEOF_TIME_T 8 +# define SIZEOF_VOID_P 8 # else # ifdef __ppc__ -# define SIZEOF__BOOL 4 +# define SIZEOF__BOOL 4 # else -# define SIZEOF__BOOL 1 +# define SIZEOF__BOOL 1 # endif -# define SIZEOF_LONG 4 -# define SIZEOF_PTHREAD_T 4 -# define SIZEOF_SIZE_T 4 -# define SIZEOF_TIME_T 4 -# define SIZEOF_VOID_P 4 +# define SIZEOF_LONG 4 +# define SIZEOF_PTHREAD_T 4 +# define SIZEOF_SIZE_T 4 +# define SIZEOF_TIME_T 4 +# define SIZEOF_VOID_P 4 # endif # if defined(__LP64__) - /* MacOSX 10.4 (the first release to suppport 64-bit code - * at all) only supports 64-bit in the UNIX layer. - * Therefore surpress the toolbox-glue in 64-bit mode. - */ - - /* In 64-bit mode setpgrp always has no argments, in 32-bit - * mode that depends on the compilation environment - */ -# undef SETPGRP_HAVE_ARG + /* MacOSX 10.4 (the first release to suppport 64-bit code + * at all) only supports 64-bit in the UNIX layer. + * Therefore surpress the toolbox-glue in 64-bit mode. + */ + + /* In 64-bit mode setpgrp always has no argments, in 32-bit + * mode that depends on the compilation environment + */ +# undef SETPGRP_HAVE_ARG # endif @@ -78,17 +78,17 @@ # define HAVE_GCC_ASM_FOR_X87 #endif - /* - * The definition in pyconfig.h is only valid on the OS release - * where configure ran on and not necessarily for all systems where - * the executable can be used on. - * - * Specifically: OSX 10.4 has limited supported for '%zd', while - * 10.5 has full support for '%zd'. A binary built on 10.5 won't - * work properly on 10.4 unless we surpress the definition - * of PY_FORMAT_SIZE_T - */ -#undef PY_FORMAT_SIZE_T + /* + * The definition in pyconfig.h is only valid on the OS release + * where configure ran on and not necessarily for all systems where + * the executable can be used on. + * + * Specifically: OSX 10.4 has limited supported for '%zd', while + * 10.5 has full support for '%zd'. A binary built on 10.5 won't + * work properly on 10.4 unless we surpress the definition + * of PY_FORMAT_SIZE_T + */ +#undef PY_FORMAT_SIZE_T #endif /* defined(_APPLE__) */ Modified: python/branches/release31-maint/Include/pyport.h ============================================================================== --- python/branches/release31-maint/Include/pyport.h (original) +++ python/branches/release31-maint/Include/pyport.h Sun May 9 18:14:21 2010 @@ -132,20 +132,20 @@ * integral type. */ #ifdef HAVE_UINTPTR_T -typedef uintptr_t Py_uintptr_t; -typedef intptr_t Py_intptr_t; +typedef uintptr_t Py_uintptr_t; +typedef intptr_t Py_intptr_t; #elif SIZEOF_VOID_P <= SIZEOF_INT -typedef unsigned int Py_uintptr_t; -typedef int Py_intptr_t; +typedef unsigned int Py_uintptr_t; +typedef int Py_intptr_t; #elif SIZEOF_VOID_P <= SIZEOF_LONG -typedef unsigned long Py_uintptr_t; -typedef long Py_intptr_t; +typedef unsigned long Py_uintptr_t; +typedef long Py_intptr_t; #elif defined(HAVE_LONG_LONG) && (SIZEOF_VOID_P <= SIZEOF_LONG_LONG) -typedef unsigned PY_LONG_LONG Py_uintptr_t; -typedef PY_LONG_LONG Py_intptr_t; +typedef unsigned PY_LONG_LONG Py_uintptr_t; +typedef PY_LONG_LONG Py_intptr_t; #else # error "Python needs a typedef for Py_uintptr_t in pyport.h." @@ -156,9 +156,9 @@ * unsigned integral type). See PEP 353 for details. */ #ifdef HAVE_SSIZE_T -typedef ssize_t Py_ssize_t; +typedef ssize_t Py_ssize_t; #elif SIZEOF_VOID_P == SIZEOF_SIZE_T -typedef Py_intptr_t Py_ssize_t; +typedef Py_intptr_t Py_ssize_t; #else # error "Python needs a typedef for Py_ssize_t in pyport.h." #endif @@ -166,7 +166,7 @@ /* Largest possible value of size_t. SIZE_MAX is part of C99, so it might be defined on some platforms. If it is not defined, (size_t)-1 is a portable - definition for C89, due to the way signed->unsigned + definition for C89, due to the way signed->unsigned conversion is defined. */ #ifdef SIZE_MAX #define PY_SIZE_MAX SIZE_MAX @@ -243,7 +243,7 @@ /* enable more aggressive optimization for visual studio */ #pragma optimize("agtw", on) #endif -/* ignore warnings if the compiler decides not to inline a function */ +/* ignore warnings if the compiler decides not to inline a function */ #pragma warning(disable: 4710) /* fastest possible local call under MSVC */ #define Py_LOCAL(type) static type __fastcall @@ -263,16 +263,16 @@ */ #if defined(_MSC_VER) -#define Py_MEMCPY(target, source, length) do { \ - size_t i_, n_ = (length); \ - char *t_ = (void*) (target); \ - const char *s_ = (void*) (source); \ - if (n_ >= 16) \ - memcpy(t_, s_, n_); \ - else \ - for (i_ = 0; i_ < n_; i_++) \ - t_[i_] = s_[i_]; \ - } while (0) +#define Py_MEMCPY(target, source, length) do { \ + size_t i_, n_ = (length); \ + char *t_ = (void*) (target); \ + const char *s_ = (void*) (source); \ + if (n_ >= 16) \ + memcpy(t_, s_, n_); \ + else \ + for (i_ = 0; i_ < n_; i_++) \ + t_[i_] = s_[i_]; \ + } while (0) #else #define Py_MEMCPY memcpy #endif @@ -383,7 +383,7 @@ */ #ifdef SIGNED_RIGHT_SHIFT_ZERO_FILLS #define Py_ARITHMETIC_RIGHT_SHIFT(TYPE, I, J) \ - ((I) < 0 ? -1-((-1-(I)) >> (J)) : (I) >> (J)) + ((I) < 0 ? -1-((-1-(I)) >> (J)) : (I) >> (J)) #else #define Py_ARITHMETIC_RIGHT_SHIFT(TYPE, I, J) ((I) >> (J)) #endif @@ -403,7 +403,7 @@ */ #ifdef Py_DEBUG #define Py_SAFE_DOWNCAST(VALUE, WIDE, NARROW) \ - (assert((WIDE)(NARROW)(VALUE) == (VALUE)), (NARROW)(VALUE)) + (assert((WIDE)(NARROW)(VALUE) == (VALUE)), (NARROW)(VALUE)) #else #define Py_SAFE_DOWNCAST(VALUE, WIDE, NARROW) (NARROW)(VALUE) #endif @@ -423,13 +423,13 @@ #define _Py_SET_EDOM_FOR_NAN(X) ; #endif #define Py_SET_ERRNO_ON_MATH_ERROR(X) \ - do { \ - if (errno == 0) { \ - if ((X) == Py_HUGE_VAL || (X) == -Py_HUGE_VAL) \ - errno = ERANGE; \ - else _Py_SET_EDOM_FOR_NAN(X) \ - } \ - } while(0) + do { \ + if (errno == 0) { \ + if ((X) == Py_HUGE_VAL || (X) == -Py_HUGE_VAL) \ + errno = ERANGE; \ + else _Py_SET_EDOM_FOR_NAN(X) \ + } \ + } while(0) /* Py_SET_ERANGE_ON_OVERFLOW(x) * An alias of Py_SET_ERRNO_ON_MATH_ERROR for backward-compatibility. @@ -450,26 +450,26 @@ * This isn't reliable. See Py_OVERFLOWED comments. * X and Y may be evaluated more than once. */ -#define Py_ADJUST_ERANGE1(X) \ - do { \ - if (errno == 0) { \ - if ((X) == Py_HUGE_VAL || (X) == -Py_HUGE_VAL) \ - errno = ERANGE; \ - } \ - else if (errno == ERANGE && (X) == 0.0) \ - errno = 0; \ - } while(0) - -#define Py_ADJUST_ERANGE2(X, Y) \ - do { \ - if ((X) == Py_HUGE_VAL || (X) == -Py_HUGE_VAL || \ - (Y) == Py_HUGE_VAL || (Y) == -Py_HUGE_VAL) { \ - if (errno == 0) \ - errno = ERANGE; \ - } \ - else if (errno == ERANGE) \ - errno = 0; \ - } while(0) +#define Py_ADJUST_ERANGE1(X) \ + do { \ + if (errno == 0) { \ + if ((X) == Py_HUGE_VAL || (X) == -Py_HUGE_VAL) \ + errno = ERANGE; \ + } \ + else if (errno == ERANGE && (X) == 0.0) \ + errno = 0; \ + } while(0) + +#define Py_ADJUST_ERANGE2(X, Y) \ + do { \ + if ((X) == Py_HUGE_VAL || (X) == -Py_HUGE_VAL || \ + (Y) == Py_HUGE_VAL || (Y) == -Py_HUGE_VAL) { \ + if (errno == 0) \ + errno = ERANGE; \ + } \ + else if (errno == ERANGE) \ + errno = 0; \ + } while(0) /* The functions _Py_dg_strtod and _Py_dg_dtoa in Python/dtoa.c (which are * required to support the short float repr introduced in Python 3.1) require @@ -498,18 +498,18 @@ #ifdef HAVE_GCC_ASM_FOR_X87 #define HAVE_PY_SET_53BIT_PRECISION 1 /* _Py_get/set_387controlword functions are defined in Python/pymath.c */ -#define _Py_SET_53BIT_PRECISION_HEADER \ - unsigned short old_387controlword, new_387controlword -#define _Py_SET_53BIT_PRECISION_START \ - do { \ - old_387controlword = _Py_get_387controlword(); \ - new_387controlword = (old_387controlword & ~0x0f00) | 0x0200; \ - if (new_387controlword != old_387controlword) \ - _Py_set_387controlword(new_387controlword); \ - } while (0) -#define _Py_SET_53BIT_PRECISION_END \ - if (new_387controlword != old_387controlword) \ - _Py_set_387controlword(old_387controlword) +#define _Py_SET_53BIT_PRECISION_HEADER \ + unsigned short old_387controlword, new_387controlword +#define _Py_SET_53BIT_PRECISION_START \ + do { \ + old_387controlword = _Py_get_387controlword(); \ + new_387controlword = (old_387controlword & ~0x0f00) | 0x0200; \ + if (new_387controlword != old_387controlword) \ + _Py_set_387controlword(new_387controlword); \ + } while (0) +#define _Py_SET_53BIT_PRECISION_END \ + if (new_387controlword != old_387controlword) \ + _Py_set_387controlword(old_387controlword) #endif /* default definitions are empty */ @@ -553,7 +553,7 @@ * extern int x() Py_DEPRECATED(2.5); */ #if defined(__GNUC__) && ((__GNUC__ >= 4) || \ - (__GNUC__ == 3) && (__GNUC_MINOR__ >= 1)) + (__GNUC__ == 3) && (__GNUC_MINOR__ >= 1)) #define Py_DEPRECATED(VERSION_UNUSED) __attribute__((__deprecated__)) #else #define Py_DEPRECATED(VERSION_UNUSED) @@ -573,7 +573,7 @@ #endif #ifdef HAVE__GETPTY -#include /* we need to import mode_t */ +#include /* we need to import mode_t */ extern char * _getpty(int *, int, mode_t, int); #endif @@ -654,54 +654,54 @@ linkage handling and it uses __declspec(). */ #if defined(__CYGWIN__) -# define HAVE_DECLSPEC_DLL +# define HAVE_DECLSPEC_DLL #endif /* only get special linkage if built as shared or platform is Cygwin */ #if defined(Py_ENABLE_SHARED) || defined(__CYGWIN__) -# if defined(HAVE_DECLSPEC_DLL) -# ifdef Py_BUILD_CORE -# define PyAPI_FUNC(RTYPE) __declspec(dllexport) RTYPE -# define PyAPI_DATA(RTYPE) extern __declspec(dllexport) RTYPE - /* module init functions inside the core need no external linkage */ - /* except for Cygwin to handle embedding */ -# if defined(__CYGWIN__) -# define PyMODINIT_FUNC __declspec(dllexport) PyObject* -# else /* __CYGWIN__ */ -# define PyMODINIT_FUNC PyObject* -# endif /* __CYGWIN__ */ -# else /* Py_BUILD_CORE */ - /* Building an extension module, or an embedded situation */ - /* public Python functions and data are imported */ - /* Under Cygwin, auto-import functions to prevent compilation */ - /* failures similar to http://python.org/doc/FAQ.html#3.24 */ -# if !defined(__CYGWIN__) -# define PyAPI_FUNC(RTYPE) __declspec(dllimport) RTYPE -# endif /* !__CYGWIN__ */ -# define PyAPI_DATA(RTYPE) extern __declspec(dllimport) RTYPE - /* module init functions outside the core must be exported */ -# if defined(__cplusplus) -# define PyMODINIT_FUNC extern "C" __declspec(dllexport) PyObject* -# else /* __cplusplus */ -# define PyMODINIT_FUNC __declspec(dllexport) PyObject* -# endif /* __cplusplus */ -# endif /* Py_BUILD_CORE */ -# endif /* HAVE_DECLSPEC */ +# if defined(HAVE_DECLSPEC_DLL) +# ifdef Py_BUILD_CORE +# define PyAPI_FUNC(RTYPE) __declspec(dllexport) RTYPE +# define PyAPI_DATA(RTYPE) extern __declspec(dllexport) RTYPE + /* module init functions inside the core need no external linkage */ + /* except for Cygwin to handle embedding */ +# if defined(__CYGWIN__) +# define PyMODINIT_FUNC __declspec(dllexport) PyObject* +# else /* __CYGWIN__ */ +# define PyMODINIT_FUNC PyObject* +# endif /* __CYGWIN__ */ +# else /* Py_BUILD_CORE */ + /* Building an extension module, or an embedded situation */ + /* public Python functions and data are imported */ + /* Under Cygwin, auto-import functions to prevent compilation */ + /* failures similar to http://python.org/doc/FAQ.html#3.24 */ +# if !defined(__CYGWIN__) +# define PyAPI_FUNC(RTYPE) __declspec(dllimport) RTYPE +# endif /* !__CYGWIN__ */ +# define PyAPI_DATA(RTYPE) extern __declspec(dllimport) RTYPE + /* module init functions outside the core must be exported */ +# if defined(__cplusplus) +# define PyMODINIT_FUNC extern "C" __declspec(dllexport) PyObject* +# else /* __cplusplus */ +# define PyMODINIT_FUNC __declspec(dllexport) PyObject* +# endif /* __cplusplus */ +# endif /* Py_BUILD_CORE */ +# endif /* HAVE_DECLSPEC */ #endif /* Py_ENABLE_SHARED */ /* If no external linkage macros defined by now, create defaults */ #ifndef PyAPI_FUNC -# define PyAPI_FUNC(RTYPE) RTYPE +# define PyAPI_FUNC(RTYPE) RTYPE #endif #ifndef PyAPI_DATA -# define PyAPI_DATA(RTYPE) extern RTYPE +# define PyAPI_DATA(RTYPE) extern RTYPE #endif #ifndef PyMODINIT_FUNC -# if defined(__cplusplus) -# define PyMODINIT_FUNC extern "C" PyObject* -# else /* __cplusplus */ -# define PyMODINIT_FUNC PyObject* -# endif /* __cplusplus */ +# if defined(__cplusplus) +# define PyMODINIT_FUNC extern "C" PyObject* +# else /* __cplusplus */ +# define PyMODINIT_FUNC PyObject* +# endif /* __cplusplus */ #endif /* limits.h constants that may be missing */ Modified: python/branches/release31-maint/Include/pythonrun.h ============================================================================== --- python/branches/release31-maint/Include/pythonrun.h (original) +++ python/branches/release31-maint/Include/pythonrun.h Sun May 9 18:14:21 2010 @@ -17,7 +17,7 @@ #define PyCF_IGNORE_COOKIE 0x0800 typedef struct { - int cf_flags; /* bitmask of CO_xxx flags relevant to future */ + int cf_flags; /* bitmask of CO_xxx flags relevant to future */ } PyCompilerFlags; PyAPI_FUNC(void) Py_SetProgramName(wchar_t *); @@ -40,33 +40,33 @@ PyAPI_FUNC(int) PyRun_InteractiveOneFlags(FILE *, const char *, PyCompilerFlags *); PyAPI_FUNC(int) PyRun_InteractiveLoopFlags(FILE *, const char *, PyCompilerFlags *); -PyAPI_FUNC(struct _mod *) PyParser_ASTFromString(const char *, const char *, - int, PyCompilerFlags *flags, +PyAPI_FUNC(struct _mod *) PyParser_ASTFromString(const char *, const char *, + int, PyCompilerFlags *flags, PyArena *); -PyAPI_FUNC(struct _mod *) PyParser_ASTFromFile(FILE *, const char *, - const char*, int, - char *, char *, +PyAPI_FUNC(struct _mod *) PyParser_ASTFromFile(FILE *, const char *, + const char*, int, + char *, char *, PyCompilerFlags *, int *, PyArena *); #define PyParser_SimpleParseString(S, B) \ - PyParser_SimpleParseStringFlags(S, B, 0) + PyParser_SimpleParseStringFlags(S, B, 0) #define PyParser_SimpleParseFile(FP, S, B) \ - PyParser_SimpleParseFileFlags(FP, S, B, 0) -PyAPI_FUNC(struct _node *) PyParser_SimpleParseStringFlags(const char *, int, - int); + PyParser_SimpleParseFileFlags(FP, S, B, 0) +PyAPI_FUNC(struct _node *) PyParser_SimpleParseStringFlags(const char *, int, + int); PyAPI_FUNC(struct _node *) PyParser_SimpleParseFileFlags(FILE *, const char *, - int, int); + int, int); -PyAPI_FUNC(PyObject *) PyRun_StringFlags(const char *, int, PyObject *, - PyObject *, PyCompilerFlags *); +PyAPI_FUNC(PyObject *) PyRun_StringFlags(const char *, int, PyObject *, + PyObject *, PyCompilerFlags *); -PyAPI_FUNC(PyObject *) PyRun_FileExFlags(FILE *, const char *, int, - PyObject *, PyObject *, int, - PyCompilerFlags *); +PyAPI_FUNC(PyObject *) PyRun_FileExFlags(FILE *, const char *, int, + PyObject *, PyObject *, int, + PyCompilerFlags *); #define Py_CompileString(str, p, s) Py_CompileStringFlags(str, p, s, NULL) PyAPI_FUNC(PyObject *) Py_CompileStringFlags(const char *, const char *, int, - PyCompilerFlags *); + PyCompilerFlags *); PyAPI_FUNC(struct symtable *) Py_SymtableString(const char *, const char *, int); PyAPI_FUNC(void) PyErr_Print(void); @@ -90,20 +90,20 @@ #define PyRun_String(str, s, g, l) PyRun_StringFlags(str, s, g, l, NULL) #define PyRun_AnyFile(fp, name) PyRun_AnyFileExFlags(fp, name, 0, NULL) #define PyRun_AnyFileEx(fp, name, closeit) \ - PyRun_AnyFileExFlags(fp, name, closeit, NULL) + PyRun_AnyFileExFlags(fp, name, closeit, NULL) #define PyRun_AnyFileFlags(fp, name, flags) \ - PyRun_AnyFileExFlags(fp, name, 0, flags) + PyRun_AnyFileExFlags(fp, name, 0, flags) #define PyRun_SimpleString(s) PyRun_SimpleStringFlags(s, NULL) #define PyRun_SimpleFile(f, p) PyRun_SimpleFileExFlags(f, p, 0, NULL) #define PyRun_SimpleFileEx(f, p, c) PyRun_SimpleFileExFlags(f, p, c, NULL) #define PyRun_InteractiveOne(f, p) PyRun_InteractiveOneFlags(f, p, NULL) #define PyRun_InteractiveLoop(f, p) PyRun_InteractiveLoopFlags(f, p, NULL) #define PyRun_File(fp, p, s, g, l) \ - PyRun_FileExFlags(fp, p, s, g, l, 0, NULL) + PyRun_FileExFlags(fp, p, s, g, l, 0, NULL) #define PyRun_FileEx(fp, p, s, g, l, c) \ - PyRun_FileExFlags(fp, p, s, g, l, c, NULL) + PyRun_FileExFlags(fp, p, s, g, l, c, NULL) #define PyRun_FileFlags(fp, p, s, g, l, flags) \ - PyRun_FileExFlags(fp, p, s, g, l, 0, flags) + PyRun_FileExFlags(fp, p, s, g, l, 0, flags) /* In getpath.c */ PyAPI_FUNC(wchar_t *) Py_GetProgramFullPath(void); Modified: python/branches/release31-maint/Include/setobject.h ============================================================================== --- python/branches/release31-maint/Include/setobject.h (original) +++ python/branches/release31-maint/Include/setobject.h Sun May 9 18:14:21 2010 @@ -22,8 +22,8 @@ #define PySet_MINSIZE 8 typedef struct { - long hash; /* cached hash code for the entry key */ - PyObject *key; + long hash; /* cached hash code for the entry key */ + PyObject *key; } setentry; @@ -33,27 +33,27 @@ typedef struct _setobject PySetObject; struct _setobject { - PyObject_HEAD + PyObject_HEAD - Py_ssize_t fill; /* # Active + # Dummy */ - Py_ssize_t used; /* # Active */ + Py_ssize_t fill; /* # Active + # Dummy */ + Py_ssize_t used; /* # Active */ - /* The table contains mask + 1 slots, and that's a power of 2. - * We store the mask instead of the size because the mask is more - * frequently needed. - */ - Py_ssize_t mask; - - /* table points to smalltable for small tables, else to - * additional malloc'ed memory. table is never NULL! This rule - * saves repeated runtime null-tests. - */ - setentry *table; - setentry *(*lookup)(PySetObject *so, PyObject *key, long hash); - setentry smalltable[PySet_MINSIZE]; + /* The table contains mask + 1 slots, and that's a power of 2. + * We store the mask instead of the size because the mask is more + * frequently needed. + */ + Py_ssize_t mask; + + /* table points to smalltable for small tables, else to + * additional malloc'ed memory. table is never NULL! This rule + * saves repeated runtime null-tests. + */ + setentry *table; + setentry *(*lookup)(PySetObject *so, PyObject *key, long hash); + setentry smalltable[PySet_MINSIZE]; - long hash; /* only used by frozenset objects */ - PyObject *weakreflist; /* List of weak references */ + long hash; /* only used by frozenset objects */ + PyObject *weakreflist; /* List of weak references */ }; PyAPI_DATA(PyTypeObject) PySet_Type; @@ -69,17 +69,17 @@ #define PyFrozenSet_CheckExact(ob) (Py_TYPE(ob) == &PyFrozenSet_Type) #define PyAnySet_CheckExact(ob) \ - (Py_TYPE(ob) == &PySet_Type || Py_TYPE(ob) == &PyFrozenSet_Type) + (Py_TYPE(ob) == &PySet_Type || Py_TYPE(ob) == &PyFrozenSet_Type) #define PyAnySet_Check(ob) \ - (Py_TYPE(ob) == &PySet_Type || Py_TYPE(ob) == &PyFrozenSet_Type || \ - PyType_IsSubtype(Py_TYPE(ob), &PySet_Type) || \ - PyType_IsSubtype(Py_TYPE(ob), &PyFrozenSet_Type)) + (Py_TYPE(ob) == &PySet_Type || Py_TYPE(ob) == &PyFrozenSet_Type || \ + PyType_IsSubtype(Py_TYPE(ob), &PySet_Type) || \ + PyType_IsSubtype(Py_TYPE(ob), &PyFrozenSet_Type)) #define PySet_Check(ob) \ - (Py_TYPE(ob) == &PySet_Type || \ - PyType_IsSubtype(Py_TYPE(ob), &PySet_Type)) + (Py_TYPE(ob) == &PySet_Type || \ + PyType_IsSubtype(Py_TYPE(ob), &PySet_Type)) #define PyFrozenSet_Check(ob) \ - (Py_TYPE(ob) == &PyFrozenSet_Type || \ - PyType_IsSubtype(Py_TYPE(ob), &PyFrozenSet_Type)) + (Py_TYPE(ob) == &PyFrozenSet_Type || \ + PyType_IsSubtype(Py_TYPE(ob), &PyFrozenSet_Type)) PyAPI_FUNC(PyObject *) PySet_New(PyObject *); PyAPI_FUNC(PyObject *) PyFrozenSet_New(PyObject *); Modified: python/branches/release31-maint/Include/structseq.h ============================================================================== --- python/branches/release31-maint/Include/structseq.h (original) +++ python/branches/release31-maint/Include/structseq.h Sun May 9 18:14:21 2010 @@ -8,35 +8,35 @@ #endif typedef struct PyStructSequence_Field { - char *name; - char *doc; + char *name; + char *doc; } PyStructSequence_Field; typedef struct PyStructSequence_Desc { - char *name; - char *doc; - struct PyStructSequence_Field *fields; - int n_in_sequence; + char *name; + char *doc; + struct PyStructSequence_Field *fields; + int n_in_sequence; } PyStructSequence_Desc; extern char* PyStructSequence_UnnamedField; PyAPI_FUNC(void) PyStructSequence_InitType(PyTypeObject *type, - PyStructSequence_Desc *desc); + PyStructSequence_Desc *desc); PyAPI_FUNC(PyObject *) PyStructSequence_New(PyTypeObject* type); typedef struct { - PyObject_VAR_HEAD - PyObject *ob_item[1]; + PyObject_VAR_HEAD + PyObject *ob_item[1]; } PyStructSequence; /* Macro, *only* to be used to fill in brand new objects */ #define PyStructSequence_SET_ITEM(op, i, v) \ - (((PyStructSequence *)(op))->ob_item[i] = v) + (((PyStructSequence *)(op))->ob_item[i] = v) #define PyStructSequence_GET_ITEM(op, i) \ - (((PyStructSequence *)(op))->ob_item[i]) + (((PyStructSequence *)(op))->ob_item[i]) #ifdef __cplusplus Modified: python/branches/release31-maint/Include/symtable.h ============================================================================== --- python/branches/release31-maint/Include/symtable.h (original) +++ python/branches/release31-maint/Include/symtable.h Sun May 9 18:14:21 2010 @@ -15,40 +15,40 @@ struct _symtable_entry; struct symtable { - const char *st_filename; /* name of file being compiled */ - struct _symtable_entry *st_cur; /* current symbol table entry */ - struct _symtable_entry *st_top; /* symbol table entry for module */ - PyObject *st_blocks; /* dict: map AST node addresses - * to symbol table entries */ - PyObject *st_stack; /* list: stack of namespace info */ - PyObject *st_global; /* borrowed ref to st_top->st_symbols */ - int st_nblocks; /* number of blocks used */ - PyObject *st_private; /* name of current class or NULL */ - PyFutureFeatures *st_future; /* module's future features */ + const char *st_filename; /* name of file being compiled */ + struct _symtable_entry *st_cur; /* current symbol table entry */ + struct _symtable_entry *st_top; /* symbol table entry for module */ + PyObject *st_blocks; /* dict: map AST node addresses + * to symbol table entries */ + PyObject *st_stack; /* list: stack of namespace info */ + PyObject *st_global; /* borrowed ref to st_top->st_symbols */ + int st_nblocks; /* number of blocks used */ + PyObject *st_private; /* name of current class or NULL */ + PyFutureFeatures *st_future; /* module's future features */ }; typedef struct _symtable_entry { - PyObject_HEAD - PyObject *ste_id; /* int: key in ste_table->st_blocks */ - PyObject *ste_symbols; /* dict: variable names to flags */ - PyObject *ste_name; /* string: name of current block */ - PyObject *ste_varnames; /* list of variable names */ - PyObject *ste_children; /* list of child blocks */ - _Py_block_ty ste_type; /* module, class, or function */ - int ste_unoptimized; /* false if namespace is optimized */ - int ste_nested; /* true if block is nested */ - unsigned ste_free : 1; /* true if block has free variables */ - unsigned ste_child_free : 1; /* true if a child block has free vars, - including free refs to globals */ - unsigned ste_generator : 1; /* true if namespace is a generator */ - unsigned ste_varargs : 1; /* true if block has varargs */ - unsigned ste_varkeywords : 1; /* true if block has varkeywords */ - unsigned ste_returns_value : 1; /* true if namespace uses return with - an argument */ - int ste_lineno; /* first line of block */ - int ste_opt_lineno; /* lineno of last exec or import * */ - int ste_tmpname; /* counter for listcomp temp vars */ - struct symtable *ste_table; + PyObject_HEAD + PyObject *ste_id; /* int: key in ste_table->st_blocks */ + PyObject *ste_symbols; /* dict: variable names to flags */ + PyObject *ste_name; /* string: name of current block */ + PyObject *ste_varnames; /* list of variable names */ + PyObject *ste_children; /* list of child blocks */ + _Py_block_ty ste_type; /* module, class, or function */ + int ste_unoptimized; /* false if namespace is optimized */ + int ste_nested; /* true if block is nested */ + unsigned ste_free : 1; /* true if block has free variables */ + unsigned ste_child_free : 1; /* true if a child block has free vars, + including free refs to globals */ + unsigned ste_generator : 1; /* true if namespace is a generator */ + unsigned ste_varargs : 1; /* true if block has varargs */ + unsigned ste_varkeywords : 1; /* true if block has varkeywords */ + unsigned ste_returns_value : 1; /* true if namespace uses return with + an argument */ + int ste_lineno; /* first line of block */ + int ste_opt_lineno; /* lineno of last exec or import * */ + int ste_tmpname; /* counter for listcomp temp vars */ + struct symtable *ste_table; } PySTEntryObject; PyAPI_DATA(PyTypeObject) PySTEntry_Type; @@ -57,8 +57,8 @@ PyAPI_FUNC(int) PyST_GetScope(PySTEntryObject *, PyObject *); -PyAPI_FUNC(struct symtable *) PySymtable_Build(mod_ty, const char *, - PyFutureFeatures *); +PyAPI_FUNC(struct symtable *) PySymtable_Build(mod_ty, const char *, + PyFutureFeatures *); PyAPI_FUNC(PySTEntryObject *) PySymtable_Lookup(struct symtable *, void *); PyAPI_FUNC(void) PySymtable_Free(struct symtable *); @@ -81,7 +81,7 @@ #define DEF_BOUND (DEF_LOCAL | DEF_PARAM | DEF_IMPORT) /* GLOBAL_EXPLICIT and GLOBAL_IMPLICIT are used internally by the symbol - table. GLOBAL is returned from PyST_GetScope() for either of them. + table. GLOBAL is returned from PyST_GetScope() for either of them. It is stored in ste_symbols at bits 12-15. */ #define SCOPE_OFFSET 11 Modified: python/branches/release31-maint/Include/unicodeobject.h ============================================================================== --- python/branches/release31-maint/Include/unicodeobject.h (original) +++ python/branches/release31-maint/Include/unicodeobject.h Sun May 9 18:14:21 2010 @@ -28,14 +28,14 @@ * * -------------------------------------------------------------------- * This Unicode String Type is - * + * * Copyright (c) 1999 by Secret Labs AB * Copyright (c) 1999 by Fredrik Lundh - * + * * By obtaining, using, and/or copying this software and/or its * associated documentation, you agree that you have read, understood, * and will comply with the following terms and conditions: - * + * * Permission to use, copy, modify, and distribute this software and its * associated documentation for any purpose and without fee is hereby * granted, provided that the above copyright notice appears in all @@ -44,7 +44,7 @@ * AB or the author not be used in advertising or publicity pertaining to * distribution of the software without specific, written prior * permission. - * + * * SECRET LABS AB AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO * THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND * FITNESS. IN NO EVENT SHALL SECRET LABS AB OR THE AUTHOR BE LIABLE FOR @@ -61,7 +61,7 @@ /* --- Internal Unicode Format -------------------------------------------- */ /* Python 3.x requires unicode */ -#define Py_USING_UNICODE +#define Py_USING_UNICODE /* FIXME: MvL's new implementation assumes that Py_UNICODE_SIZE is properly set, but the default rules below doesn't set it. I'll @@ -120,10 +120,10 @@ * Use this typedef when you need to represent a UTF-16 surrogate pair * as single unsigned integer. */ -#if SIZEOF_INT >= 4 -typedef unsigned int Py_UCS4; +#if SIZEOF_INT >= 4 +typedef unsigned int Py_UCS4; #elif SIZEOF_LONG >= 4 -typedef unsigned long Py_UCS4; +typedef unsigned long Py_UCS4; #endif /* Py_UNICODE is the native Unicode storage format (code unit) used by @@ -382,7 +382,7 @@ */ #define Py_UNICODE_ISSPACE(ch) \ - ((ch) < 128U ? _Py_ascii_whitespace[(ch)] : _PyUnicode_IsWhitespace(ch)) + ((ch) < 128U ? _Py_ascii_whitespace[(ch)] : _PyUnicode_IsWhitespace(ch)) #define Py_UNICODE_ISLOWER(ch) _PyUnicode_IsLowercase(ch) #define Py_UNICODE_ISUPPER(ch) _PyUnicode_IsUppercase(ch) @@ -408,16 +408,16 @@ #define Py_UNICODE_ISALNUM(ch) \ (Py_UNICODE_ISALPHA(ch) || \ - Py_UNICODE_ISDECIMAL(ch) || \ - Py_UNICODE_ISDIGIT(ch) || \ - Py_UNICODE_ISNUMERIC(ch)) + Py_UNICODE_ISDECIMAL(ch) || \ + Py_UNICODE_ISDIGIT(ch) || \ + Py_UNICODE_ISNUMERIC(ch)) -#define Py_UNICODE_COPY(target, source, length) \ - Py_MEMCPY((target), (source), (length)*sizeof(Py_UNICODE)) +#define Py_UNICODE_COPY(target, source, length) \ + Py_MEMCPY((target), (source), (length)*sizeof(Py_UNICODE)) #define Py_UNICODE_FILL(target, value, length) \ do {Py_ssize_t i_; Py_UNICODE *t_ = (target); Py_UNICODE v_ = (value);\ - for (i_ = 0; i_ < (length); i_++) t_[i_] = v_;\ + for (i_ = 0; i_ < (length); i_++) t_[i_] = v_;\ } while (0) /* Check if substring matches at given offset. the offset must be @@ -436,15 +436,15 @@ typedef struct { PyObject_HEAD - Py_ssize_t length; /* Length of raw Unicode data in buffer */ - Py_UNICODE *str; /* Raw Unicode buffer */ - long hash; /* Hash value; -1 if not set */ - int state; /* != 0 if interned. In this case the two - * references from the dictionary to this object - * are *not* counted in ob_refcnt. */ - PyObject *defenc; /* (Default) Encoded version as Python - string, or NULL; this is used for - implementing the buffer protocol */ + Py_ssize_t length; /* Length of raw Unicode data in buffer */ + Py_UNICODE *str; /* Raw Unicode buffer */ + long hash; /* Hash value; -1 if not set */ + int state; /* != 0 if interned. In this case the two + * references from the dictionary to this object + * are *not* counted in ob_refcnt. */ + PyObject *defenc; /* (Default) Encoded version as Python + string, or NULL; this is used for + implementing the buffer protocol */ } PyUnicodeObject; PyAPI_DATA(PyTypeObject) PyUnicode_Type; @@ -460,13 +460,13 @@ /* Fast access macros */ #define PyUnicode_GET_SIZE(op) \ - (assert(PyUnicode_Check(op)),(((PyUnicodeObject *)(op))->length)) + (assert(PyUnicode_Check(op)),(((PyUnicodeObject *)(op))->length)) #define PyUnicode_GET_DATA_SIZE(op) \ - (assert(PyUnicode_Check(op)),(((PyUnicodeObject *)(op))->length * sizeof(Py_UNICODE))) + (assert(PyUnicode_Check(op)),(((PyUnicodeObject *)(op))->length * sizeof(Py_UNICODE))) #define PyUnicode_AS_UNICODE(op) \ - (assert(PyUnicode_Check(op)),(((PyUnicodeObject *)(op))->str)) + (assert(PyUnicode_Check(op)),(((PyUnicodeObject *)(op))->str)) #define PyUnicode_AS_DATA(op) \ - (assert(PyUnicode_Check(op)),((const char *)((PyUnicodeObject *)(op))->str)) + (assert(PyUnicode_Check(op)),((const char *)((PyUnicodeObject *)(op))->str)) /* --- Constants ---------------------------------------------------------- */ @@ -482,7 +482,7 @@ /* --- Plain Py_UNICODE --------------------------------------------------- */ /* Create a Unicode Object from the Py_UNICODE buffer u of the given - size. + size. u may be NULL which causes the contents to be undefined. It is the user's responsibility to fill in the needed data afterwards. Note @@ -512,13 +512,13 @@ Py_UNICODE buffer. */ PyAPI_FUNC(Py_UNICODE *) PyUnicode_AsUnicode( - PyObject *unicode /* Unicode object */ + PyObject *unicode /* Unicode object */ ); /* Get the length of the Unicode object. */ PyAPI_FUNC(Py_ssize_t) PyUnicode_GetSize( - PyObject *unicode /* Unicode object */ + PyObject *unicode /* Unicode object */ ); /* Get the maximum ordinal for a Unicode character. */ @@ -539,8 +539,8 @@ */ PyAPI_FUNC(int) PyUnicode_Resize( - PyObject **unicode, /* Pointer to the Unicode object */ - Py_ssize_t length /* New length */ + PyObject **unicode, /* Pointer to the Unicode object */ + Py_ssize_t length /* New length */ ); /* Coerce obj to an Unicode object and return a reference with @@ -561,14 +561,14 @@ */ PyAPI_FUNC(PyObject*) PyUnicode_FromEncodedObject( - register PyObject *obj, /* Object */ + register PyObject *obj, /* Object */ const char *encoding, /* encoding */ const char *errors /* error handling */ ); /* Coerce obj to an Unicode object and return a reference with *incremented* refcount. - + Unicode objects are passed back as-is (subclasses are converted to true Unicode objects), all other objects are delegated to PyUnicode_FromEncodedObject(obj, NULL, "strict") which results in @@ -580,7 +580,7 @@ */ PyAPI_FUNC(PyObject*) PyUnicode_FromObject( - register PyObject *obj /* Object */ + register PyObject *obj /* Object */ ); PyAPI_FUNC(PyObject *) PyUnicode_FromFormatV(const char*, va_list); @@ -636,8 +636,8 @@ /* --- Unicode ordinals --------------------------------------------------- */ -/* Create a Unicode Object from the given Unicode code point ordinal. - +/* Create a Unicode Object from the given Unicode code point ordinal. + The ordinal must be in range(0x10000) on narrow Python builds (UCS2), and range(0x110000) on wide builds (UCS4). A ValueError is raised in case it is not. @@ -657,11 +657,11 @@ PyAPI_FUNC(int) PyUnicode_ClearFreeList(void); -/* === Builtin Codecs ===================================================== +/* === Builtin Codecs ===================================================== Many of these APIs take two arguments encoding and errors. These parameters encoding and errors have the same semantics as the ones - of the builtin unicode() API. + of the builtin unicode() API. Setting encoding to NULL causes the default encoding to be used. @@ -678,7 +678,7 @@ /* --- Manage the default encoding ---------------------------------------- */ /* Return a Python string holding the default encoded value of the - Unicode object. + Unicode object. The resulting string is cached in the Unicode object for subsequent usage by this function. The cached version is needed to implement @@ -710,7 +710,7 @@ */ PyAPI_FUNC(char *) _PyUnicode_AsStringAndSize( - PyObject *unicode, + PyObject *unicode, Py_ssize_t *size); /* Returns a pointer to the default encoding (normally, UTf-8) of the @@ -735,7 +735,7 @@ process global. This may change in future versions of the interpreter to become a parameter which is managed on a per-thread basis. - + */ PyAPI_FUNC(const char*) PyUnicode_GetDefaultEncoding(void); @@ -743,11 +743,11 @@ /* Sets the currently active default encoding. Returns 0 on success, -1 in case of an error. - + */ PyAPI_FUNC(int) PyUnicode_SetDefaultEncoding( - const char *encoding /* Encoding name in standard form */ + const char *encoding /* Encoding name in standard form */ ); /* --- Generic Codecs ----------------------------------------------------- */ @@ -766,21 +766,21 @@ object. */ PyAPI_FUNC(PyObject*) PyUnicode_AsDecodedObject( - PyObject *unicode, /* Unicode object */ - const char *encoding, /* encoding */ - const char *errors /* error handling */ + PyObject *unicode, /* Unicode object */ + const char *encoding, /* encoding */ + const char *errors /* error handling */ ); /* Decode a Unicode object unicode and return the result as Unicode object. */ PyAPI_FUNC(PyObject*) PyUnicode_AsDecodedUnicode( - PyObject *unicode, /* Unicode object */ - const char *encoding, /* encoding */ - const char *errors /* error handling */ + PyObject *unicode, /* Unicode object */ + const char *encoding, /* encoding */ + const char *errors /* error handling */ ); -/* Encodes a Py_UNICODE buffer of the given size and returns a +/* Encodes a Py_UNICODE buffer of the given size and returns a Python string object. */ PyAPI_FUNC(PyObject*) PyUnicode_Encode( @@ -794,27 +794,27 @@ object. */ PyAPI_FUNC(PyObject*) PyUnicode_AsEncodedObject( - PyObject *unicode, /* Unicode object */ - const char *encoding, /* encoding */ - const char *errors /* error handling */ + PyObject *unicode, /* Unicode object */ + const char *encoding, /* encoding */ + const char *errors /* error handling */ ); /* Encodes a Unicode object and returns the result as Python string object. */ PyAPI_FUNC(PyObject*) PyUnicode_AsEncodedString( - PyObject *unicode, /* Unicode object */ - const char *encoding, /* encoding */ - const char *errors /* error handling */ + PyObject *unicode, /* Unicode object */ + const char *encoding, /* encoding */ + const char *errors /* error handling */ ); /* Encodes a Unicode object and returns the result as Unicode object. */ PyAPI_FUNC(PyObject*) PyUnicode_AsEncodedUnicode( - PyObject *unicode, /* Unicode object */ - const char *encoding, /* encoding */ - const char *errors /* error handling */ + PyObject *unicode, /* Unicode object */ + const char *encoding, /* encoding */ + const char *errors /* error handling */ ); /* Build an encoding map. */ @@ -826,49 +826,49 @@ /* --- UTF-7 Codecs ------------------------------------------------------- */ PyAPI_FUNC(PyObject*) PyUnicode_DecodeUTF7( - const char *string, /* UTF-7 encoded string */ - Py_ssize_t length, /* size of string */ - const char *errors /* error handling */ + const char *string, /* UTF-7 encoded string */ + Py_ssize_t length, /* size of string */ + const char *errors /* error handling */ ); PyAPI_FUNC(PyObject*) PyUnicode_DecodeUTF7Stateful( - const char *string, /* UTF-7 encoded string */ - Py_ssize_t length, /* size of string */ - const char *errors, /* error handling */ - Py_ssize_t *consumed /* bytes consumed */ + const char *string, /* UTF-7 encoded string */ + Py_ssize_t length, /* size of string */ + const char *errors, /* error handling */ + Py_ssize_t *consumed /* bytes consumed */ ); PyAPI_FUNC(PyObject*) PyUnicode_EncodeUTF7( - const Py_UNICODE *data, /* Unicode char buffer */ - Py_ssize_t length, /* number of Py_UNICODE chars to encode */ - int base64SetO, /* Encode RFC2152 Set O characters in base64 */ - int base64WhiteSpace, /* Encode whitespace (sp, ht, nl, cr) in base64 */ - const char *errors /* error handling */ + const Py_UNICODE *data, /* Unicode char buffer */ + Py_ssize_t length, /* number of Py_UNICODE chars to encode */ + int base64SetO, /* Encode RFC2152 Set O characters in base64 */ + int base64WhiteSpace, /* Encode whitespace (sp, ht, nl, cr) in base64 */ + const char *errors /* error handling */ ); /* --- UTF-8 Codecs ------------------------------------------------------- */ PyAPI_FUNC(PyObject*) PyUnicode_DecodeUTF8( - const char *string, /* UTF-8 encoded string */ - Py_ssize_t length, /* size of string */ - const char *errors /* error handling */ + const char *string, /* UTF-8 encoded string */ + Py_ssize_t length, /* size of string */ + const char *errors /* error handling */ ); PyAPI_FUNC(PyObject*) PyUnicode_DecodeUTF8Stateful( - const char *string, /* UTF-8 encoded string */ - Py_ssize_t length, /* size of string */ - const char *errors, /* error handling */ - Py_ssize_t *consumed /* bytes consumed */ + const char *string, /* UTF-8 encoded string */ + Py_ssize_t length, /* size of string */ + const char *errors, /* error handling */ + Py_ssize_t *consumed /* bytes consumed */ ); PyAPI_FUNC(PyObject*) PyUnicode_AsUTF8String( - PyObject *unicode /* Unicode object */ + PyObject *unicode /* Unicode object */ ); PyAPI_FUNC(PyObject*) PyUnicode_EncodeUTF8( - const Py_UNICODE *data, /* Unicode char buffer */ - Py_ssize_t length, /* number of Py_UNICODE chars to encode */ - const char *errors /* error handling */ + const Py_UNICODE *data, /* Unicode char buffer */ + Py_ssize_t length, /* number of Py_UNICODE chars to encode */ + const char *errors /* error handling */ ); /* --- UTF-32 Codecs ------------------------------------------------------ */ @@ -877,14 +877,14 @@ the corresponding Unicode object. errors (if non-NULL) defines the error handling. It defaults - to "strict". + to "strict". If byteorder is non-NULL, the decoder starts decoding using the given byte order: - *byteorder == -1: little endian - *byteorder == 0: native order - *byteorder == 1: big endian + *byteorder == -1: little endian + *byteorder == 0: native order + *byteorder == 1: big endian In native mode, the first four bytes of the stream are checked for a BOM mark. If found, the BOM mark is analysed, the byte order @@ -897,29 +897,29 @@ */ PyAPI_FUNC(PyObject*) PyUnicode_DecodeUTF32( - const char *string, /* UTF-32 encoded string */ - Py_ssize_t length, /* size of string */ - const char *errors, /* error handling */ - int *byteorder /* pointer to byteorder to use - 0=native;-1=LE,1=BE; updated on - exit */ + const char *string, /* UTF-32 encoded string */ + Py_ssize_t length, /* size of string */ + const char *errors, /* error handling */ + int *byteorder /* pointer to byteorder to use + 0=native;-1=LE,1=BE; updated on + exit */ ); PyAPI_FUNC(PyObject*) PyUnicode_DecodeUTF32Stateful( - const char *string, /* UTF-32 encoded string */ - Py_ssize_t length, /* size of string */ - const char *errors, /* error handling */ - int *byteorder, /* pointer to byteorder to use - 0=native;-1=LE,1=BE; updated on - exit */ - Py_ssize_t *consumed /* bytes consumed */ + const char *string, /* UTF-32 encoded string */ + Py_ssize_t length, /* size of string */ + const char *errors, /* error handling */ + int *byteorder, /* pointer to byteorder to use + 0=native;-1=LE,1=BE; updated on + exit */ + Py_ssize_t *consumed /* bytes consumed */ ); /* Returns a Python string using the UTF-32 encoding in native byte order. The string always starts with a BOM mark. */ PyAPI_FUNC(PyObject*) PyUnicode_AsUTF32String( - PyObject *unicode /* Unicode object */ + PyObject *unicode /* Unicode object */ ); /* Returns a Python string object holding the UTF-32 encoded value of @@ -939,10 +939,10 @@ */ PyAPI_FUNC(PyObject*) PyUnicode_EncodeUTF32( - const Py_UNICODE *data, /* Unicode char buffer */ - Py_ssize_t length, /* number of Py_UNICODE chars to encode */ - const char *errors, /* error handling */ - int byteorder /* byteorder to use 0=BOM+native;-1=LE,1=BE */ + const Py_UNICODE *data, /* Unicode char buffer */ + Py_ssize_t length, /* number of Py_UNICODE chars to encode */ + const char *errors, /* error handling */ + int byteorder /* byteorder to use 0=BOM+native;-1=LE,1=BE */ ); /* --- UTF-16 Codecs ------------------------------------------------------ */ @@ -951,14 +951,14 @@ the corresponding Unicode object. errors (if non-NULL) defines the error handling. It defaults - to "strict". + to "strict". If byteorder is non-NULL, the decoder starts decoding using the given byte order: - *byteorder == -1: little endian - *byteorder == 0: native order - *byteorder == 1: big endian + *byteorder == -1: little endian + *byteorder == 0: native order + *byteorder == 1: big endian In native mode, the first two bytes of the stream are checked for a BOM mark. If found, the BOM mark is analysed, the byte order @@ -971,29 +971,29 @@ */ PyAPI_FUNC(PyObject*) PyUnicode_DecodeUTF16( - const char *string, /* UTF-16 encoded string */ - Py_ssize_t length, /* size of string */ - const char *errors, /* error handling */ - int *byteorder /* pointer to byteorder to use - 0=native;-1=LE,1=BE; updated on - exit */ + const char *string, /* UTF-16 encoded string */ + Py_ssize_t length, /* size of string */ + const char *errors, /* error handling */ + int *byteorder /* pointer to byteorder to use + 0=native;-1=LE,1=BE; updated on + exit */ ); PyAPI_FUNC(PyObject*) PyUnicode_DecodeUTF16Stateful( - const char *string, /* UTF-16 encoded string */ - Py_ssize_t length, /* size of string */ - const char *errors, /* error handling */ - int *byteorder, /* pointer to byteorder to use - 0=native;-1=LE,1=BE; updated on - exit */ - Py_ssize_t *consumed /* bytes consumed */ + const char *string, /* UTF-16 encoded string */ + Py_ssize_t length, /* size of string */ + const char *errors, /* error handling */ + int *byteorder, /* pointer to byteorder to use + 0=native;-1=LE,1=BE; updated on + exit */ + Py_ssize_t *consumed /* bytes consumed */ ); /* Returns a Python string using the UTF-16 encoding in native byte order. The string always starts with a BOM mark. */ PyAPI_FUNC(PyObject*) PyUnicode_AsUTF16String( - PyObject *unicode /* Unicode object */ + PyObject *unicode /* Unicode object */ ); /* Returns a Python string object holding the UTF-16 encoded value of @@ -1017,44 +1017,44 @@ */ PyAPI_FUNC(PyObject*) PyUnicode_EncodeUTF16( - const Py_UNICODE *data, /* Unicode char buffer */ - Py_ssize_t length, /* number of Py_UNICODE chars to encode */ - const char *errors, /* error handling */ - int byteorder /* byteorder to use 0=BOM+native;-1=LE,1=BE */ + const Py_UNICODE *data, /* Unicode char buffer */ + Py_ssize_t length, /* number of Py_UNICODE chars to encode */ + const char *errors, /* error handling */ + int byteorder /* byteorder to use 0=BOM+native;-1=LE,1=BE */ ); /* --- Unicode-Escape Codecs ---------------------------------------------- */ PyAPI_FUNC(PyObject*) PyUnicode_DecodeUnicodeEscape( - const char *string, /* Unicode-Escape encoded string */ - Py_ssize_t length, /* size of string */ - const char *errors /* error handling */ + const char *string, /* Unicode-Escape encoded string */ + Py_ssize_t length, /* size of string */ + const char *errors /* error handling */ ); PyAPI_FUNC(PyObject*) PyUnicode_AsUnicodeEscapeString( - PyObject *unicode /* Unicode object */ + PyObject *unicode /* Unicode object */ ); PyAPI_FUNC(PyObject*) PyUnicode_EncodeUnicodeEscape( - const Py_UNICODE *data, /* Unicode char buffer */ - Py_ssize_t length /* Number of Py_UNICODE chars to encode */ + const Py_UNICODE *data, /* Unicode char buffer */ + Py_ssize_t length /* Number of Py_UNICODE chars to encode */ ); /* --- Raw-Unicode-Escape Codecs ------------------------------------------ */ PyAPI_FUNC(PyObject*) PyUnicode_DecodeRawUnicodeEscape( - const char *string, /* Raw-Unicode-Escape encoded string */ - Py_ssize_t length, /* size of string */ - const char *errors /* error handling */ + const char *string, /* Raw-Unicode-Escape encoded string */ + Py_ssize_t length, /* size of string */ + const char *errors /* error handling */ ); PyAPI_FUNC(PyObject*) PyUnicode_AsRawUnicodeEscapeString( - PyObject *unicode /* Unicode object */ + PyObject *unicode /* Unicode object */ ); PyAPI_FUNC(PyObject*) PyUnicode_EncodeRawUnicodeEscape( - const Py_UNICODE *data, /* Unicode char buffer */ - Py_ssize_t length /* Number of Py_UNICODE chars to encode */ + const Py_UNICODE *data, /* Unicode char buffer */ + Py_ssize_t length /* Number of Py_UNICODE chars to encode */ ); /* --- Unicode Internal Codec --------------------------------------------- @@ -1067,53 +1067,53 @@ const char *errors ); -/* --- Latin-1 Codecs ----------------------------------------------------- +/* --- Latin-1 Codecs ----------------------------------------------------- Note: Latin-1 corresponds to the first 256 Unicode ordinals. */ PyAPI_FUNC(PyObject*) PyUnicode_DecodeLatin1( - const char *string, /* Latin-1 encoded string */ - Py_ssize_t length, /* size of string */ - const char *errors /* error handling */ + const char *string, /* Latin-1 encoded string */ + Py_ssize_t length, /* size of string */ + const char *errors /* error handling */ ); PyAPI_FUNC(PyObject*) PyUnicode_AsLatin1String( - PyObject *unicode /* Unicode object */ + PyObject *unicode /* Unicode object */ ); PyAPI_FUNC(PyObject*) PyUnicode_EncodeLatin1( - const Py_UNICODE *data, /* Unicode char buffer */ - Py_ssize_t length, /* Number of Py_UNICODE chars to encode */ - const char *errors /* error handling */ + const Py_UNICODE *data, /* Unicode char buffer */ + Py_ssize_t length, /* Number of Py_UNICODE chars to encode */ + const char *errors /* error handling */ ); -/* --- ASCII Codecs ------------------------------------------------------- +/* --- ASCII Codecs ------------------------------------------------------- Only 7-bit ASCII data is excepted. All other codes generate errors. */ PyAPI_FUNC(PyObject*) PyUnicode_DecodeASCII( - const char *string, /* ASCII encoded string */ - Py_ssize_t length, /* size of string */ - const char *errors /* error handling */ + const char *string, /* ASCII encoded string */ + Py_ssize_t length, /* size of string */ + const char *errors /* error handling */ ); PyAPI_FUNC(PyObject*) PyUnicode_AsASCIIString( - PyObject *unicode /* Unicode object */ + PyObject *unicode /* Unicode object */ ); PyAPI_FUNC(PyObject*) PyUnicode_EncodeASCII( - const Py_UNICODE *data, /* Unicode char buffer */ - Py_ssize_t length, /* Number of Py_UNICODE chars to encode */ - const char *errors /* error handling */ + const Py_UNICODE *data, /* Unicode char buffer */ + Py_ssize_t length, /* Number of Py_UNICODE chars to encode */ + const char *errors /* error handling */ ); -/* --- Character Map Codecs ----------------------------------------------- +/* --- Character Map Codecs ----------------------------------------------- - This codec uses mappings to encode and decode characters. + This codec uses mappings to encode and decode characters. Decoding mappings must map single string characters to single Unicode characters, integers (which are then interpreted as Unicode @@ -1134,25 +1134,25 @@ */ PyAPI_FUNC(PyObject*) PyUnicode_DecodeCharmap( - const char *string, /* Encoded string */ - Py_ssize_t length, /* size of string */ - PyObject *mapping, /* character mapping - (char ordinal -> unicode ordinal) */ - const char *errors /* error handling */ + const char *string, /* Encoded string */ + Py_ssize_t length, /* size of string */ + PyObject *mapping, /* character mapping + (char ordinal -> unicode ordinal) */ + const char *errors /* error handling */ ); PyAPI_FUNC(PyObject*) PyUnicode_AsCharmapString( - PyObject *unicode, /* Unicode object */ - PyObject *mapping /* character mapping - (unicode ordinal -> char ordinal) */ + PyObject *unicode, /* Unicode object */ + PyObject *mapping /* character mapping + (unicode ordinal -> char ordinal) */ ); PyAPI_FUNC(PyObject*) PyUnicode_EncodeCharmap( - const Py_UNICODE *data, /* Unicode char buffer */ - Py_ssize_t length, /* Number of Py_UNICODE chars to encode */ - PyObject *mapping, /* character mapping - (unicode ordinal -> char ordinal) */ - const char *errors /* error handling */ + const Py_UNICODE *data, /* Unicode char buffer */ + Py_ssize_t length, /* Number of Py_UNICODE chars to encode */ + PyObject *mapping, /* character mapping + (unicode ordinal -> char ordinal) */ + const char *errors /* error handling */ ); /* Translate a Py_UNICODE buffer of the given length by applying a @@ -1160,7 +1160,7 @@ object. The mapping table must map Unicode ordinal integers to Unicode - ordinal integers or None (causing deletion of the character). + ordinal integers or None (causing deletion of the character). Mapping tables may be dictionaries or sequences. Unmapped character ordinals (ones which cause a LookupError) are left untouched and @@ -1169,10 +1169,10 @@ */ PyAPI_FUNC(PyObject *) PyUnicode_TranslateCharmap( - const Py_UNICODE *data, /* Unicode char buffer */ - Py_ssize_t length, /* Number of Py_UNICODE chars to encode */ - PyObject *table, /* Translate table */ - const char *errors /* error handling */ + const Py_UNICODE *data, /* Unicode char buffer */ + Py_ssize_t length, /* Number of Py_UNICODE chars to encode */ + PyObject *table, /* Translate table */ + const char *errors /* error handling */ ); #ifdef MS_WIN32 @@ -1221,7 +1221,7 @@ NULL or "strict": raise a ValueError "ignore": ignore the wrong characters (these are not copied to the - output buffer) + output buffer) "replace": replaces illegal characters with '?' Returns 0 on success, -1 on failure. @@ -1229,10 +1229,10 @@ */ PyAPI_FUNC(int) PyUnicode_EncodeDecimal( - Py_UNICODE *s, /* Unicode buffer */ - Py_ssize_t length, /* Number of Py_UNICODE chars to encode */ - char *output, /* Output buffer; must have size >= length */ - const char *errors /* error handling */ + Py_UNICODE *s, /* Unicode buffer */ + Py_ssize_t length, /* Number of Py_UNICODE chars to encode */ + char *output, /* Output buffer; must have size >= length */ + const char *errors /* error handling */ ); /* --- File system encoding ---------------------------------------------- */ @@ -1271,24 +1271,24 @@ /* Concat two strings giving a new Unicode string. */ PyAPI_FUNC(PyObject*) PyUnicode_Concat( - PyObject *left, /* Left string */ - PyObject *right /* Right string */ + PyObject *left, /* Left string */ + PyObject *right /* Right string */ ); /* Concat two strings and put the result in *pleft (sets *pleft to NULL on error) */ PyAPI_FUNC(void) PyUnicode_Append( - PyObject **pleft, /* Pointer to left string */ - PyObject *right /* Right string */ + PyObject **pleft, /* Pointer to left string */ + PyObject *right /* Right string */ ); /* Concat two strings, put the result in *pleft and drop the right object (sets *pleft to NULL on error) */ PyAPI_FUNC(void) PyUnicode_AppendAndDel( - PyObject **pleft, /* Pointer to left string */ - PyObject *right /* Right string */ + PyObject **pleft, /* Pointer to left string */ + PyObject *right /* Right string */ ); /* Split a string giving a list of Unicode strings. @@ -1303,35 +1303,35 @@ */ PyAPI_FUNC(PyObject*) PyUnicode_Split( - PyObject *s, /* String to split */ - PyObject *sep, /* String separator */ - Py_ssize_t maxsplit /* Maxsplit count */ - ); + PyObject *s, /* String to split */ + PyObject *sep, /* String separator */ + Py_ssize_t maxsplit /* Maxsplit count */ + ); /* Dito, but split at line breaks. CRLF is considered to be one line break. Line breaks are not included in the resulting list. */ - + PyAPI_FUNC(PyObject*) PyUnicode_Splitlines( - PyObject *s, /* String to split */ - int keepends /* If true, line end markers are included */ - ); + PyObject *s, /* String to split */ + int keepends /* If true, line end markers are included */ + ); /* Partition a string using a given separator. */ PyAPI_FUNC(PyObject*) PyUnicode_Partition( - PyObject *s, /* String to partition */ - PyObject *sep /* String separator */ - ); + PyObject *s, /* String to partition */ + PyObject *sep /* String separator */ + ); /* Partition a string using a given separator, searching from the end of the string. */ PyAPI_FUNC(PyObject*) PyUnicode_RPartition( - PyObject *s, /* String to partition */ - PyObject *sep /* String separator */ - ); + PyObject *s, /* String to partition */ + PyObject *sep /* String separator */ + ); /* Split a string giving a list of Unicode strings. @@ -1347,16 +1347,16 @@ */ PyAPI_FUNC(PyObject*) PyUnicode_RSplit( - PyObject *s, /* String to split */ - PyObject *sep, /* String separator */ - Py_ssize_t maxsplit /* Maxsplit count */ - ); + PyObject *s, /* String to split */ + PyObject *sep, /* String separator */ + Py_ssize_t maxsplit /* Maxsplit count */ + ); /* Translate a string by applying a character mapping table to it and return the resulting Unicode object. The mapping table must map Unicode ordinal integers to Unicode - ordinal integers or None (causing deletion of the character). + ordinal integers or None (causing deletion of the character). Mapping tables may be dictionaries or sequences. Unmapped character ordinals (ones which cause a LookupError) are left untouched and @@ -1365,28 +1365,28 @@ */ PyAPI_FUNC(PyObject *) PyUnicode_Translate( - PyObject *str, /* String */ - PyObject *table, /* Translate table */ - const char *errors /* error handling */ + PyObject *str, /* String */ + PyObject *table, /* Translate table */ + const char *errors /* error handling */ ); /* Join a sequence of strings using the given separator and return the resulting Unicode string. */ - + PyAPI_FUNC(PyObject*) PyUnicode_Join( - PyObject *separator, /* Separator string */ - PyObject *seq /* Sequence object */ + PyObject *separator, /* Separator string */ + PyObject *seq /* Sequence object */ ); /* Return 1 if substr matches str[start:end] at the given tail end, 0 otherwise. */ PyAPI_FUNC(Py_ssize_t) PyUnicode_Tailmatch( - PyObject *str, /* String */ - PyObject *substr, /* Prefix or Suffix string */ - Py_ssize_t start, /* Start index */ - Py_ssize_t end, /* Stop index */ - int direction /* Tail end: -1 prefix, +1 suffix */ + PyObject *str, /* String */ + PyObject *substr, /* Prefix or Suffix string */ + Py_ssize_t start, /* Start index */ + Py_ssize_t end, /* Stop index */ + int direction /* Tail end: -1 prefix, +1 suffix */ ); /* Return the first position of substr in str[start:end] using the @@ -1394,39 +1394,39 @@ an error occurred and an exception is set. */ PyAPI_FUNC(Py_ssize_t) PyUnicode_Find( - PyObject *str, /* String */ - PyObject *substr, /* Substring to find */ - Py_ssize_t start, /* Start index */ - Py_ssize_t end, /* Stop index */ - int direction /* Find direction: +1 forward, -1 backward */ + PyObject *str, /* String */ + PyObject *substr, /* Substring to find */ + Py_ssize_t start, /* Start index */ + Py_ssize_t end, /* Stop index */ + int direction /* Find direction: +1 forward, -1 backward */ ); /* Count the number of occurrences of substr in str[start:end]. */ PyAPI_FUNC(Py_ssize_t) PyUnicode_Count( - PyObject *str, /* String */ - PyObject *substr, /* Substring to count */ - Py_ssize_t start, /* Start index */ - Py_ssize_t end /* Stop index */ + PyObject *str, /* String */ + PyObject *substr, /* Substring to count */ + Py_ssize_t start, /* Start index */ + Py_ssize_t end /* Stop index */ ); /* Replace at most maxcount occurrences of substr in str with replstr and return the resulting Unicode object. */ PyAPI_FUNC(PyObject *) PyUnicode_Replace( - PyObject *str, /* String */ - PyObject *substr, /* Substring to find */ - PyObject *replstr, /* Substring to replace */ - Py_ssize_t maxcount /* Max. number of replacements to apply; - -1 = all */ + PyObject *str, /* String */ + PyObject *substr, /* Substring to find */ + PyObject *replstr, /* Substring to replace */ + Py_ssize_t maxcount /* Max. number of replacements to apply; + -1 = all */ ); /* Compare two strings and return -1, 0, 1 for less than, equal, greater than resp. */ PyAPI_FUNC(int) PyUnicode_Compare( - PyObject *left, /* Left string */ - PyObject *right /* Right string */ + PyObject *left, /* Left string */ + PyObject *right /* Right string */ ); PyAPI_FUNC(int) PyUnicode_CompareWithASCIIString( @@ -1451,17 +1451,17 @@ */ PyAPI_FUNC(PyObject *) PyUnicode_RichCompare( - PyObject *left, /* Left string */ - PyObject *right, /* Right string */ - int op /* Operation: Py_EQ, Py_NE, Py_GT, etc. */ + PyObject *left, /* Left string */ + PyObject *right, /* Right string */ + int op /* Operation: Py_EQ, Py_NE, Py_GT, etc. */ ); /* Apply a argument tuple or dictionary to a format string and return the resulting Unicode string. */ PyAPI_FUNC(PyObject *) PyUnicode_Format( - PyObject *format, /* Format string */ - PyObject *args /* Argument tuple or dictionary */ + PyObject *format, /* Format string */ + PyObject *args /* Argument tuple or dictionary */ ); /* Checks whether element is contained in container and return 1/0 @@ -1471,8 +1471,8 @@ returned in case of an error. */ PyAPI_FUNC(int) PyUnicode_Contains( - PyObject *container, /* Container string */ - PyObject *element /* Element string */ + PyObject *container, /* Container string */ + PyObject *element /* Element string */ ); /* Checks whether argument is a valid identifier. */ @@ -1513,82 +1513,82 @@ PyAPI_DATA(const unsigned char) _Py_ascii_whitespace[]; /* These should not be used directly. Use the Py_UNICODE_IS* and - Py_UNICODE_TO* macros instead. + Py_UNICODE_TO* macros instead. These APIs are implemented in Objects/unicodectype.c. */ PyAPI_FUNC(int) _PyUnicode_IsLowercase( - Py_UNICODE ch /* Unicode character */ + Py_UNICODE ch /* Unicode character */ ); PyAPI_FUNC(int) _PyUnicode_IsUppercase( - Py_UNICODE ch /* Unicode character */ + Py_UNICODE ch /* Unicode character */ ); PyAPI_FUNC(int) _PyUnicode_IsTitlecase( - Py_UNICODE ch /* Unicode character */ + Py_UNICODE ch /* Unicode character */ ); PyAPI_FUNC(int) _PyUnicode_IsXidStart( - Py_UNICODE ch /* Unicode character */ + Py_UNICODE ch /* Unicode character */ ); PyAPI_FUNC(int) _PyUnicode_IsXidContinue( - Py_UNICODE ch /* Unicode character */ + Py_UNICODE ch /* Unicode character */ ); PyAPI_FUNC(int) _PyUnicode_IsWhitespace( - const Py_UNICODE ch /* Unicode character */ + const Py_UNICODE ch /* Unicode character */ ); PyAPI_FUNC(int) _PyUnicode_IsLinebreak( - const Py_UNICODE ch /* Unicode character */ + const Py_UNICODE ch /* Unicode character */ ); PyAPI_FUNC(Py_UNICODE) _PyUnicode_ToLowercase( - Py_UNICODE ch /* Unicode character */ + Py_UNICODE ch /* Unicode character */ ); PyAPI_FUNC(Py_UNICODE) _PyUnicode_ToUppercase( - Py_UNICODE ch /* Unicode character */ + Py_UNICODE ch /* Unicode character */ ); PyAPI_FUNC(Py_UNICODE) _PyUnicode_ToTitlecase( - Py_UNICODE ch /* Unicode character */ + Py_UNICODE ch /* Unicode character */ ); PyAPI_FUNC(int) _PyUnicode_ToDecimalDigit( - Py_UNICODE ch /* Unicode character */ + Py_UNICODE ch /* Unicode character */ ); PyAPI_FUNC(int) _PyUnicode_ToDigit( - Py_UNICODE ch /* Unicode character */ + Py_UNICODE ch /* Unicode character */ ); PyAPI_FUNC(double) _PyUnicode_ToNumeric( - Py_UNICODE ch /* Unicode character */ + Py_UNICODE ch /* Unicode character */ ); PyAPI_FUNC(int) _PyUnicode_IsDecimalDigit( - Py_UNICODE ch /* Unicode character */ + Py_UNICODE ch /* Unicode character */ ); PyAPI_FUNC(int) _PyUnicode_IsDigit( - Py_UNICODE ch /* Unicode character */ + Py_UNICODE ch /* Unicode character */ ); PyAPI_FUNC(int) _PyUnicode_IsNumeric( - Py_UNICODE ch /* Unicode character */ + Py_UNICODE ch /* Unicode character */ ); PyAPI_FUNC(int) _PyUnicode_IsPrintable( - Py_UNICODE ch /* Unicode character */ + Py_UNICODE ch /* Unicode character */ ); PyAPI_FUNC(int) _PyUnicode_IsAlpha( - Py_UNICODE ch /* Unicode character */ + Py_UNICODE ch /* Unicode character */ ); PyAPI_FUNC(size_t) Py_UNICODE_strlen(const Py_UNICODE *u); Modified: python/branches/release31-maint/Misc/setuid-prog.c ============================================================================== --- python/branches/release31-maint/Misc/setuid-prog.c (original) +++ python/branches/release31-maint/Misc/setuid-prog.c Sun May 9 18:14:21 2010 @@ -21,28 +21,28 @@ Assuming the script is a Bourne shell script, the first line of the script should be - #!/bin/sh - + #!/bin/sh - The - is important, don't omit it. If you're using esh, the first line should be - #!/usr/local/bin/esh -f + #!/usr/local/bin/esh -f and for ksh, the first line should be - #!/usr/local/bin/ksh -p + #!/usr/local/bin/ksh -p The script should then set the variable IFS to the string consisting of , , and . After this (*not* before!), the PATH variable should be set to a reasonable value and exported. Do not expect the PATH to have a reasonable value, so do not trust the old value of PATH. You should then set the umask of the program by calling - umask 077 # or 022 if you want the files to be readable + umask 077 # or 022 if you want the files to be readable If you plan to change directories, you should either unset CDPATH or set it to a good value. Setting CDPATH to just ``.'' (dot) is a good idea. If, for some reason, you want to use csh, the first line should be - #!/bin/csh -fb + #!/bin/csh -fb You should then set the path variable to something reasonable, without trusting the inherited path. Here too, you should set the umask using the command - umask 077 # or 022 if you want the files to be readable + umask 077 # or 022 if you want the files to be readable */ #include @@ -54,14 +54,14 @@ /* CONFIGURATION SECTION */ -#ifndef FULL_PATH /* so that this can be specified from the Makefile */ +#ifndef FULL_PATH /* so that this can be specified from the Makefile */ /* Uncomment the following line: -#define FULL_PATH "/full/path/of/script" +#define FULL_PATH "/full/path/of/script" * Then comment out the #error line. */ #error "You must define FULL_PATH somewhere" #endif #ifndef UMASK -#define UMASK 077 +#define UMASK 077 #endif /* END OF CONFIGURATION SECTION */ @@ -101,76 +101,76 @@ void clean_environ(void) { - char **p; - extern char **environ; + char **p; + extern char **environ; - for (p = environ; *p; p++) { - if (strncmp(*p, "LD_", 3) == 0) - **p = 'X'; - else if (strncmp(*p, "_RLD", 4) == 0) - **p = 'X'; - else if (strncmp(*p, "PYTHON", 6) == 0) - **p = 'X'; - else if (strncmp(*p, "IFS=", 4) == 0) - *p = def_IFS; - else if (strncmp(*p, "CDPATH=", 7) == 0) - *p = def_CDPATH; - else if (strncmp(*p, "ENV=", 4) == 0) - *p = def_ENV; - } - putenv(def_PATH); + for (p = environ; *p; p++) { + if (strncmp(*p, "LD_", 3) == 0) + **p = 'X'; + else if (strncmp(*p, "_RLD", 4) == 0) + **p = 'X'; + else if (strncmp(*p, "PYTHON", 6) == 0) + **p = 'X'; + else if (strncmp(*p, "IFS=", 4) == 0) + *p = def_IFS; + else if (strncmp(*p, "CDPATH=", 7) == 0) + *p = def_CDPATH; + else if (strncmp(*p, "ENV=", 4) == 0) + *p = def_ENV; + } + putenv(def_PATH); } int main(int argc, char **argv) { - struct stat statb; - gid_t egid = getegid(); - uid_t euid = geteuid(); - - /* - Sanity check #1. - This check should be made compile-time, but that's not possible. - If you're sure that you specified a full path name for FULL_PATH, - you can omit this check. - */ - if (FULL_PATH[0] != '/') { - fprintf(stderr, "%s: %s is not a full path name\n", argv[0], - FULL_PATH); - fprintf(stderr, "You can only use this wrapper if you\n"); - fprintf(stderr, "compile it with an absolute path.\n"); - exit(1); - } - - /* - Sanity check #2. - Check that the owner of the script is equal to either the - effective uid or the super user. - */ - if (stat(FULL_PATH, &statb) < 0) { - perror("stat"); - exit(1); - } - if (statb.st_uid != 0 && statb.st_uid != euid) { - fprintf(stderr, "%s: %s has the wrong owner\n", argv[0], - FULL_PATH); - fprintf(stderr, "The script should be owned by root,\n"); - fprintf(stderr, "and shouldn't be writable by anyone.\n"); - exit(1); - } - - if (setregid(egid, egid) < 0) - perror("setregid"); - if (setreuid(euid, euid) < 0) - perror("setreuid"); - - clean_environ(); - - umask(UMASK); - - while (**argv == '-') /* don't let argv[0] start with '-' */ - (*argv)++; - execv(FULL_PATH, argv); - fprintf(stderr, "%s: could not execute the script\n", argv[0]); - exit(1); + struct stat statb; + gid_t egid = getegid(); + uid_t euid = geteuid(); + + /* + Sanity check #1. + This check should be made compile-time, but that's not possible. + If you're sure that you specified a full path name for FULL_PATH, + you can omit this check. + */ + if (FULL_PATH[0] != '/') { + fprintf(stderr, "%s: %s is not a full path name\n", argv[0], + FULL_PATH); + fprintf(stderr, "You can only use this wrapper if you\n"); + fprintf(stderr, "compile it with an absolute path.\n"); + exit(1); + } + + /* + Sanity check #2. + Check that the owner of the script is equal to either the + effective uid or the super user. + */ + if (stat(FULL_PATH, &statb) < 0) { + perror("stat"); + exit(1); + } + if (statb.st_uid != 0 && statb.st_uid != euid) { + fprintf(stderr, "%s: %s has the wrong owner\n", argv[0], + FULL_PATH); + fprintf(stderr, "The script should be owned by root,\n"); + fprintf(stderr, "and shouldn't be writable by anyone.\n"); + exit(1); + } + + if (setregid(egid, egid) < 0) + perror("setregid"); + if (setreuid(euid, euid) < 0) + perror("setreuid"); + + clean_environ(); + + umask(UMASK); + + while (**argv == '-') /* don't let argv[0] start with '-' */ + (*argv)++; + execv(FULL_PATH, argv); + fprintf(stderr, "%s: could not execute the script\n", argv[0]); + exit(1); } Modified: python/branches/release31-maint/Modules/_bisectmodule.c ============================================================================== --- python/branches/release31-maint/Modules/_bisectmodule.c (original) +++ python/branches/release31-maint/Modules/_bisectmodule.c Sun May 9 18:14:21 2010 @@ -8,51 +8,51 @@ static Py_ssize_t internal_bisect_right(PyObject *list, PyObject *item, Py_ssize_t lo, Py_ssize_t hi) { - PyObject *litem; - Py_ssize_t mid, res; + PyObject *litem; + Py_ssize_t mid, res; - if (lo < 0) { - PyErr_SetString(PyExc_ValueError, "lo must be non-negative"); - return -1; - } - if (hi == -1) { - hi = PySequence_Size(list); - if (hi < 0) - return -1; - } - while (lo < hi) { - mid = (lo + hi) / 2; - litem = PySequence_GetItem(list, mid); - if (litem == NULL) - return -1; - res = PyObject_RichCompareBool(item, litem, Py_LT); - Py_DECREF(litem); - if (res < 0) - return -1; - if (res) - hi = mid; - else - lo = mid + 1; - } - return lo; + if (lo < 0) { + PyErr_SetString(PyExc_ValueError, "lo must be non-negative"); + return -1; + } + if (hi == -1) { + hi = PySequence_Size(list); + if (hi < 0) + return -1; + } + while (lo < hi) { + mid = (lo + hi) / 2; + litem = PySequence_GetItem(list, mid); + if (litem == NULL) + return -1; + res = PyObject_RichCompareBool(item, litem, Py_LT); + Py_DECREF(litem); + if (res < 0) + return -1; + if (res) + hi = mid; + else + lo = mid + 1; + } + return lo; } static PyObject * bisect_right(PyObject *self, PyObject *args, PyObject *kw) { - PyObject *list, *item; - Py_ssize_t lo = 0; - Py_ssize_t hi = -1; - Py_ssize_t index; - static char *keywords[] = {"a", "x", "lo", "hi", NULL}; - - if (!PyArg_ParseTupleAndKeywords(args, kw, "OO|nn:bisect_right", - keywords, &list, &item, &lo, &hi)) - return NULL; - index = internal_bisect_right(list, item, lo, hi); - if (index < 0) - return NULL; - return PyLong_FromSsize_t(index); + PyObject *list, *item; + Py_ssize_t lo = 0; + Py_ssize_t hi = -1; + Py_ssize_t index; + static char *keywords[] = {"a", "x", "lo", "hi", NULL}; + + if (!PyArg_ParseTupleAndKeywords(args, kw, "OO|nn:bisect_right", + keywords, &list, &item, &lo, &hi)) + return NULL; + index = internal_bisect_right(list, item, lo, hi); + if (index < 0) + return NULL; + return PyLong_FromSsize_t(index); } PyDoc_STRVAR(bisect_right_doc, @@ -70,30 +70,30 @@ static PyObject * insort_right(PyObject *self, PyObject *args, PyObject *kw) { - PyObject *list, *item, *result; - Py_ssize_t lo = 0; - Py_ssize_t hi = -1; - Py_ssize_t index; - static char *keywords[] = {"a", "x", "lo", "hi", NULL}; - - if (!PyArg_ParseTupleAndKeywords(args, kw, "OO|nn:insort_right", - keywords, &list, &item, &lo, &hi)) - return NULL; - index = internal_bisect_right(list, item, lo, hi); - if (index < 0) - return NULL; - if (PyList_CheckExact(list)) { - if (PyList_Insert(list, index, item) < 0) - return NULL; - } else { - result = PyObject_CallMethod(list, "insert", "nO", - index, item); - if (result == NULL) - return NULL; - Py_DECREF(result); - } + PyObject *list, *item, *result; + Py_ssize_t lo = 0; + Py_ssize_t hi = -1; + Py_ssize_t index; + static char *keywords[] = {"a", "x", "lo", "hi", NULL}; + + if (!PyArg_ParseTupleAndKeywords(args, kw, "OO|nn:insort_right", + keywords, &list, &item, &lo, &hi)) + return NULL; + index = internal_bisect_right(list, item, lo, hi); + if (index < 0) + return NULL; + if (PyList_CheckExact(list)) { + if (PyList_Insert(list, index, item) < 0) + return NULL; + } else { + result = PyObject_CallMethod(list, "insert", "nO", + index, item); + if (result == NULL) + return NULL; + Py_DECREF(result); + } - Py_RETURN_NONE; + Py_RETURN_NONE; } PyDoc_STRVAR(insort_right_doc, @@ -109,51 +109,51 @@ static Py_ssize_t internal_bisect_left(PyObject *list, PyObject *item, Py_ssize_t lo, Py_ssize_t hi) { - PyObject *litem; - Py_ssize_t mid, res; + PyObject *litem; + Py_ssize_t mid, res; - if (lo < 0) { - PyErr_SetString(PyExc_ValueError, "lo must be non-negative"); - return -1; - } - if (hi == -1) { - hi = PySequence_Size(list); - if (hi < 0) - return -1; - } - while (lo < hi) { - mid = (lo + hi) / 2; - litem = PySequence_GetItem(list, mid); - if (litem == NULL) - return -1; - res = PyObject_RichCompareBool(litem, item, Py_LT); - Py_DECREF(litem); - if (res < 0) - return -1; - if (res) - lo = mid + 1; - else - hi = mid; - } - return lo; + if (lo < 0) { + PyErr_SetString(PyExc_ValueError, "lo must be non-negative"); + return -1; + } + if (hi == -1) { + hi = PySequence_Size(list); + if (hi < 0) + return -1; + } + while (lo < hi) { + mid = (lo + hi) / 2; + litem = PySequence_GetItem(list, mid); + if (litem == NULL) + return -1; + res = PyObject_RichCompareBool(litem, item, Py_LT); + Py_DECREF(litem); + if (res < 0) + return -1; + if (res) + lo = mid + 1; + else + hi = mid; + } + return lo; } static PyObject * bisect_left(PyObject *self, PyObject *args, PyObject *kw) { - PyObject *list, *item; - Py_ssize_t lo = 0; - Py_ssize_t hi = -1; - Py_ssize_t index; - static char *keywords[] = {"a", "x", "lo", "hi", NULL}; - - if (!PyArg_ParseTupleAndKeywords(args, kw, "OO|nn:bisect_left", - keywords, &list, &item, &lo, &hi)) - return NULL; - index = internal_bisect_left(list, item, lo, hi); - if (index < 0) - return NULL; - return PyLong_FromSsize_t(index); + PyObject *list, *item; + Py_ssize_t lo = 0; + Py_ssize_t hi = -1; + Py_ssize_t index; + static char *keywords[] = {"a", "x", "lo", "hi", NULL}; + + if (!PyArg_ParseTupleAndKeywords(args, kw, "OO|nn:bisect_left", + keywords, &list, &item, &lo, &hi)) + return NULL; + index = internal_bisect_left(list, item, lo, hi); + if (index < 0) + return NULL; + return PyLong_FromSsize_t(index); } PyDoc_STRVAR(bisect_left_doc, @@ -171,30 +171,30 @@ static PyObject * insort_left(PyObject *self, PyObject *args, PyObject *kw) { - PyObject *list, *item, *result; - Py_ssize_t lo = 0; - Py_ssize_t hi = -1; - Py_ssize_t index; - static char *keywords[] = {"a", "x", "lo", "hi", NULL}; - - if (!PyArg_ParseTupleAndKeywords(args, kw, "OO|nn:insort_left", - keywords, &list, &item, &lo, &hi)) - return NULL; - index = internal_bisect_left(list, item, lo, hi); - if (index < 0) - return NULL; - if (PyList_CheckExact(list)) { - if (PyList_Insert(list, index, item) < 0) - return NULL; - } else { - result = PyObject_CallMethod(list, "insert", "iO", - index, item); - if (result == NULL) - return NULL; - Py_DECREF(result); - } + PyObject *list, *item, *result; + Py_ssize_t lo = 0; + Py_ssize_t hi = -1; + Py_ssize_t index; + static char *keywords[] = {"a", "x", "lo", "hi", NULL}; + + if (!PyArg_ParseTupleAndKeywords(args, kw, "OO|nn:insort_left", + keywords, &list, &item, &lo, &hi)) + return NULL; + index = internal_bisect_left(list, item, lo, hi); + if (index < 0) + return NULL; + if (PyList_CheckExact(list)) { + if (PyList_Insert(list, index, item) < 0) + return NULL; + } else { + result = PyObject_CallMethod(list, "insert", "iO", + index, item); + if (result == NULL) + return NULL; + Py_DECREF(result); + } - Py_RETURN_NONE; + Py_RETURN_NONE; } PyDoc_STRVAR(insort_left_doc, @@ -211,19 +211,19 @@ PyDoc_STRVAR(insort_doc, "Alias for insort_right().\n"); static PyMethodDef bisect_methods[] = { - {"bisect_right", (PyCFunction)bisect_right, - METH_VARARGS|METH_KEYWORDS, bisect_right_doc}, - {"bisect", (PyCFunction)bisect_right, - METH_VARARGS|METH_KEYWORDS, bisect_doc}, - {"insort_right", (PyCFunction)insort_right, - METH_VARARGS|METH_KEYWORDS, insort_right_doc}, - {"insort", (PyCFunction)insort_right, - METH_VARARGS|METH_KEYWORDS, insort_doc}, - {"bisect_left", (PyCFunction)bisect_left, - METH_VARARGS|METH_KEYWORDS, bisect_left_doc}, - {"insort_left", (PyCFunction)insort_left, - METH_VARARGS|METH_KEYWORDS, insort_left_doc}, - {NULL, NULL} /* sentinel */ + {"bisect_right", (PyCFunction)bisect_right, + METH_VARARGS|METH_KEYWORDS, bisect_right_doc}, + {"bisect", (PyCFunction)bisect_right, + METH_VARARGS|METH_KEYWORDS, bisect_doc}, + {"insort_right", (PyCFunction)insort_right, + METH_VARARGS|METH_KEYWORDS, insort_right_doc}, + {"insort", (PyCFunction)insort_right, + METH_VARARGS|METH_KEYWORDS, insort_doc}, + {"bisect_left", (PyCFunction)bisect_left, + METH_VARARGS|METH_KEYWORDS, bisect_left_doc}, + {"insort_left", (PyCFunction)insort_left, + METH_VARARGS|METH_KEYWORDS, insort_left_doc}, + {NULL, NULL} /* sentinel */ }; PyDoc_STRVAR(module_doc, @@ -236,19 +236,19 @@ static struct PyModuleDef _bisectmodule = { - PyModuleDef_HEAD_INIT, - "_bisect", - module_doc, - -1, - bisect_methods, - NULL, - NULL, - NULL, - NULL + PyModuleDef_HEAD_INIT, + "_bisect", + module_doc, + -1, + bisect_methods, + NULL, + NULL, + NULL, + NULL }; PyMODINIT_FUNC PyInit__bisect(void) { - return PyModule_Create(&_bisectmodule); + return PyModule_Create(&_bisectmodule); } Modified: python/branches/release31-maint/Modules/_codecsmodule.c ============================================================================== --- python/branches/release31-maint/Modules/_codecsmodule.c (original) +++ python/branches/release31-maint/Modules/_codecsmodule.c Sun May 9 18:14:21 2010 @@ -15,7 +15,7 @@ The builtin Unicode codecs use the following interface: _encode(Unicode_object[,errors='strict']) -> - (string object, bytes consumed) + (string object, bytes consumed) _decode(char_buffer_obj[,errors='strict']) -> (Unicode object, bytes consumed) @@ -95,7 +95,7 @@ return NULL; if (encoding == NULL) - encoding = PyUnicode_GetDefaultEncoding(); + encoding = PyUnicode_GetDefaultEncoding(); /* Encode via the codec registry */ return PyCodec_Encode(v, encoding, errors); @@ -122,7 +122,7 @@ return NULL; if (encoding == NULL) - encoding = PyUnicode_GetDefaultEncoding(); + encoding = PyUnicode_GetDefaultEncoding(); /* Decode via the codec registry */ return PyCodec_Decode(v, encoding, errors); @@ -132,7 +132,7 @@ static PyObject *codec_tuple(PyObject *unicode, - Py_ssize_t len) + Py_ssize_t len) { PyObject *v; if (unicode == NULL) @@ -145,86 +145,86 @@ /* --- String codecs ------------------------------------------------------ */ static PyObject * escape_decode(PyObject *self, - PyObject *args) + PyObject *args) { const char *errors = NULL; const char *data; Py_ssize_t size; if (!PyArg_ParseTuple(args, "s#|z:escape_decode", - &data, &size, &errors)) - return NULL; + &data, &size, &errors)) + return NULL; return codec_tuple(PyBytes_DecodeEscape(data, size, errors, 0, NULL), - size); + size); } static PyObject * escape_encode(PyObject *self, - PyObject *args) + PyObject *args) { - static const char *hexdigits = "0123456789abcdef"; - PyObject *str; - Py_ssize_t size; - Py_ssize_t newsize; - const char *errors = NULL; - PyObject *v; - - if (!PyArg_ParseTuple(args, "O!|z:escape_encode", - &PyBytes_Type, &str, &errors)) - return NULL; - - size = PyBytes_GET_SIZE(str); - newsize = 4*size; - if (newsize > PY_SSIZE_T_MAX || newsize / 4 != size) { - PyErr_SetString(PyExc_OverflowError, - "string is too large to encode"); - return NULL; - } - v = PyBytes_FromStringAndSize(NULL, newsize); - - if (v == NULL) { - return NULL; - } - else { - register Py_ssize_t i; - register char c; - register char *p = PyBytes_AS_STRING(v); - - for (i = 0; i < size; i++) { - /* There's at least enough room for a hex escape */ - assert(newsize - (p - PyBytes_AS_STRING(v)) >= 4); - c = PyBytes_AS_STRING(str)[i]; - if (c == '\'' || 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++ = hexdigits[(c & 0xf0) >> 4]; - *p++ = hexdigits[c & 0xf]; - } - else - *p++ = c; - } - *p = '\0'; - if (_PyBytes_Resize(&v, (p - PyBytes_AS_STRING(v)))) { - return NULL; - } - } - - return codec_tuple(v, PyBytes_Size(v)); + static const char *hexdigits = "0123456789abcdef"; + PyObject *str; + Py_ssize_t size; + Py_ssize_t newsize; + const char *errors = NULL; + PyObject *v; + + if (!PyArg_ParseTuple(args, "O!|z:escape_encode", + &PyBytes_Type, &str, &errors)) + return NULL; + + size = PyBytes_GET_SIZE(str); + newsize = 4*size; + if (newsize > PY_SSIZE_T_MAX || newsize / 4 != size) { + PyErr_SetString(PyExc_OverflowError, + "string is too large to encode"); + return NULL; + } + v = PyBytes_FromStringAndSize(NULL, newsize); + + if (v == NULL) { + return NULL; + } + else { + register Py_ssize_t i; + register char c; + register char *p = PyBytes_AS_STRING(v); + + for (i = 0; i < size; i++) { + /* There's at least enough room for a hex escape */ + assert(newsize - (p - PyBytes_AS_STRING(v)) >= 4); + c = PyBytes_AS_STRING(str)[i]; + if (c == '\'' || 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++ = hexdigits[(c & 0xf0) >> 4]; + *p++ = hexdigits[c & 0xf]; + } + else + *p++ = c; + } + *p = '\0'; + if (_PyBytes_Resize(&v, (p - PyBytes_AS_STRING(v)))) { + return NULL; + } + } + + return codec_tuple(v, PyBytes_Size(v)); } /* --- Decoder ------------------------------------------------------------ */ static PyObject * unicode_internal_decode(PyObject *self, - PyObject *args) + PyObject *args) { PyObject *obj; const char *errors = NULL; @@ -232,19 +232,19 @@ Py_ssize_t size; if (!PyArg_ParseTuple(args, "O|z:unicode_internal_decode", - &obj, &errors)) - return NULL; + &obj, &errors)) + return NULL; if (PyUnicode_Check(obj)) { - Py_INCREF(obj); - return codec_tuple(obj, PyUnicode_GET_SIZE(obj)); + Py_INCREF(obj); + return codec_tuple(obj, PyUnicode_GET_SIZE(obj)); } else { - if (PyObject_AsReadBuffer(obj, (const void **)&data, &size)) - return NULL; + if (PyObject_AsReadBuffer(obj, (const void **)&data, &size)) + return NULL; - return codec_tuple(_PyUnicode_DecodeUnicodeInternal(data, size, errors), - size); + return codec_tuple(_PyUnicode_DecodeUnicodeInternal(data, size, errors), + size); } } @@ -252,20 +252,20 @@ utf_7_decode(PyObject *self, PyObject *args) { - Py_buffer pbuf; + Py_buffer pbuf; const char *errors = NULL; int final = 0; Py_ssize_t consumed; PyObject *decoded = NULL; if (!PyArg_ParseTuple(args, "y*|zi:utf_7_decode", - &pbuf, &errors, &final)) - return NULL; + &pbuf, &errors, &final)) + return NULL; consumed = pbuf.len; decoded = PyUnicode_DecodeUTF7Stateful(pbuf.buf, pbuf.len, errors, - final ? NULL : &consumed); - PyBuffer_Release(&pbuf); + final ? NULL : &consumed); + PyBuffer_Release(&pbuf); if (decoded == NULL) return NULL; return codec_tuple(decoded, consumed); @@ -273,32 +273,32 @@ static PyObject * utf_8_decode(PyObject *self, - PyObject *args) + PyObject *args) { - Py_buffer pbuf; + Py_buffer pbuf; const char *errors = NULL; int final = 0; Py_ssize_t consumed; PyObject *decoded = NULL; if (!PyArg_ParseTuple(args, "y*|zi:utf_8_decode", - &pbuf, &errors, &final)) - return NULL; + &pbuf, &errors, &final)) + return NULL; consumed = pbuf.len; decoded = PyUnicode_DecodeUTF8Stateful(pbuf.buf, pbuf.len, errors, - final ? NULL : &consumed); - PyBuffer_Release(&pbuf); + final ? NULL : &consumed); + PyBuffer_Release(&pbuf); if (decoded == NULL) - return NULL; + return NULL; return codec_tuple(decoded, consumed); } static PyObject * utf_16_decode(PyObject *self, - PyObject *args) + PyObject *args) { - Py_buffer pbuf; + Py_buffer pbuf; const char *errors = NULL; int byteorder = 0; int final = 0; @@ -306,22 +306,22 @@ PyObject *decoded; if (!PyArg_ParseTuple(args, "y*|zi:utf_16_decode", - &pbuf, &errors, &final)) - return NULL; + &pbuf, &errors, &final)) + return NULL; consumed = pbuf.len; /* This is overwritten unless final is true. */ decoded = PyUnicode_DecodeUTF16Stateful(pbuf.buf, pbuf.len, errors, - &byteorder, final ? NULL : &consumed); - PyBuffer_Release(&pbuf); + &byteorder, final ? NULL : &consumed); + PyBuffer_Release(&pbuf); if (decoded == NULL) - return NULL; + return NULL; return codec_tuple(decoded, consumed); } static PyObject * utf_16_le_decode(PyObject *self, - PyObject *args) + PyObject *args) { - Py_buffer pbuf; + Py_buffer pbuf; const char *errors = NULL; int byteorder = -1; int final = 0; @@ -329,23 +329,23 @@ PyObject *decoded = NULL; if (!PyArg_ParseTuple(args, "y*|zi:utf_16_le_decode", - &pbuf, &errors, &final)) - return NULL; + &pbuf, &errors, &final)) + return NULL; consumed = pbuf.len; /* This is overwritten unless final is true. */ decoded = PyUnicode_DecodeUTF16Stateful(pbuf.buf, pbuf.len, errors, - &byteorder, final ? NULL : &consumed); - PyBuffer_Release(&pbuf); + &byteorder, final ? NULL : &consumed); + PyBuffer_Release(&pbuf); if (decoded == NULL) - return NULL; + return NULL; return codec_tuple(decoded, consumed); } static PyObject * utf_16_be_decode(PyObject *self, - PyObject *args) + PyObject *args) { - Py_buffer pbuf; + Py_buffer pbuf; const char *errors = NULL; int byteorder = 1; int final = 0; @@ -353,15 +353,15 @@ PyObject *decoded = NULL; if (!PyArg_ParseTuple(args, "y*|zi:utf_16_be_decode", - &pbuf, &errors, &final)) - return NULL; + &pbuf, &errors, &final)) + return NULL; consumed = pbuf.len; /* This is overwritten unless final is true. */ decoded = PyUnicode_DecodeUTF16Stateful(pbuf.buf, pbuf.len, errors, - &byteorder, final ? NULL : &consumed); - PyBuffer_Release(&pbuf); + &byteorder, final ? NULL : &consumed); + PyBuffer_Release(&pbuf); if (decoded == NULL) - return NULL; + return NULL; return codec_tuple(decoded, consumed); } @@ -375,9 +375,9 @@ static PyObject * utf_16_ex_decode(PyObject *self, - PyObject *args) + PyObject *args) { - Py_buffer pbuf; + Py_buffer pbuf; const char *errors = NULL; int byteorder = 0; PyObject *unicode, *tuple; @@ -385,14 +385,14 @@ Py_ssize_t consumed; if (!PyArg_ParseTuple(args, "y*|zii:utf_16_ex_decode", - &pbuf, &errors, &byteorder, &final)) - return NULL; + &pbuf, &errors, &byteorder, &final)) + return NULL; consumed = pbuf.len; /* This is overwritten unless final is true. */ unicode = PyUnicode_DecodeUTF16Stateful(pbuf.buf, pbuf.len, errors, - &byteorder, final ? NULL : &consumed); - PyBuffer_Release(&pbuf); + &byteorder, final ? NULL : &consumed); + PyBuffer_Release(&pbuf); if (unicode == NULL) - return NULL; + return NULL; tuple = Py_BuildValue("Oni", unicode, consumed, byteorder); Py_DECREF(unicode); return tuple; @@ -400,9 +400,9 @@ static PyObject * utf_32_decode(PyObject *self, - PyObject *args) + PyObject *args) { - Py_buffer pbuf; + Py_buffer pbuf; const char *errors = NULL; int byteorder = 0; int final = 0; @@ -410,22 +410,22 @@ PyObject *decoded; if (!PyArg_ParseTuple(args, "y*|zi:utf_32_decode", - &pbuf, &errors, &final)) - return NULL; + &pbuf, &errors, &final)) + return NULL; consumed = pbuf.len; /* This is overwritten unless final is true. */ decoded = PyUnicode_DecodeUTF32Stateful(pbuf.buf, pbuf.len, errors, - &byteorder, final ? NULL : &consumed); - PyBuffer_Release(&pbuf); + &byteorder, final ? NULL : &consumed); + PyBuffer_Release(&pbuf); if (decoded == NULL) - return NULL; + return NULL; return codec_tuple(decoded, consumed); } static PyObject * utf_32_le_decode(PyObject *self, - PyObject *args) + PyObject *args) { - Py_buffer pbuf; + Py_buffer pbuf; const char *errors = NULL; int byteorder = -1; int final = 0; @@ -433,22 +433,22 @@ PyObject *decoded; if (!PyArg_ParseTuple(args, "y*|zi:utf_32_le_decode", - &pbuf, &errors, &final)) - return NULL; + &pbuf, &errors, &final)) + return NULL; consumed = pbuf.len; /* This is overwritten unless final is true. */ decoded = PyUnicode_DecodeUTF32Stateful(pbuf.buf, pbuf.len, errors, - &byteorder, final ? NULL : &consumed); - PyBuffer_Release(&pbuf); + &byteorder, final ? NULL : &consumed); + PyBuffer_Release(&pbuf); if (decoded == NULL) - return NULL; + return NULL; return codec_tuple(decoded, consumed); } static PyObject * utf_32_be_decode(PyObject *self, - PyObject *args) + PyObject *args) { - Py_buffer pbuf; + Py_buffer pbuf; const char *errors = NULL; int byteorder = 1; int final = 0; @@ -456,14 +456,14 @@ PyObject *decoded; if (!PyArg_ParseTuple(args, "y*|zi:utf_32_be_decode", - &pbuf, &errors, &final)) - return NULL; + &pbuf, &errors, &final)) + return NULL; consumed = pbuf.len; /* This is overwritten unless final is true. */ decoded = PyUnicode_DecodeUTF32Stateful(pbuf.buf, pbuf.len, errors, - &byteorder, final ? NULL : &consumed); - PyBuffer_Release(&pbuf); + &byteorder, final ? NULL : &consumed); + PyBuffer_Release(&pbuf); if (decoded == NULL) - return NULL; + return NULL; return codec_tuple(decoded, consumed); } @@ -477,9 +477,9 @@ static PyObject * utf_32_ex_decode(PyObject *self, - PyObject *args) + PyObject *args) { - Py_buffer pbuf; + Py_buffer pbuf; const char *errors = NULL; int byteorder = 0; PyObject *unicode, *tuple; @@ -487,14 +487,14 @@ Py_ssize_t consumed; if (!PyArg_ParseTuple(args, "y*|zii:utf_32_ex_decode", - &pbuf, &errors, &byteorder, &final)) - return NULL; + &pbuf, &errors, &byteorder, &final)) + return NULL; consumed = pbuf.len; /* This is overwritten unless final is true. */ unicode = PyUnicode_DecodeUTF32Stateful(pbuf.buf, pbuf.len, errors, - &byteorder, final ? NULL : &consumed); - PyBuffer_Release(&pbuf); + &byteorder, final ? NULL : &consumed); + PyBuffer_Release(&pbuf); if (unicode == NULL) - return NULL; + return NULL; tuple = Py_BuildValue("Oni", unicode, consumed, byteorder); Py_DECREF(unicode); return tuple; @@ -502,114 +502,114 @@ static PyObject * unicode_escape_decode(PyObject *self, - PyObject *args) + PyObject *args) { - Py_buffer pbuf; + Py_buffer pbuf; const char *errors = NULL; - PyObject *unicode; + PyObject *unicode; if (!PyArg_ParseTuple(args, "s*|z:unicode_escape_decode", - &pbuf, &errors)) - return NULL; + &pbuf, &errors)) + return NULL; - unicode = PyUnicode_DecodeUnicodeEscape(pbuf.buf, pbuf.len, errors); - PyBuffer_Release(&pbuf); - return codec_tuple(unicode, pbuf.len); + unicode = PyUnicode_DecodeUnicodeEscape(pbuf.buf, pbuf.len, errors); + PyBuffer_Release(&pbuf); + return codec_tuple(unicode, pbuf.len); } static PyObject * raw_unicode_escape_decode(PyObject *self, - PyObject *args) + PyObject *args) { - Py_buffer pbuf; + Py_buffer pbuf; const char *errors = NULL; - PyObject *unicode; + PyObject *unicode; if (!PyArg_ParseTuple(args, "s*|z:raw_unicode_escape_decode", - &pbuf, &errors)) - return NULL; + &pbuf, &errors)) + return NULL; - unicode = PyUnicode_DecodeRawUnicodeEscape(pbuf.buf, pbuf.len, errors); - PyBuffer_Release(&pbuf); - return codec_tuple(unicode, pbuf.len); + unicode = PyUnicode_DecodeRawUnicodeEscape(pbuf.buf, pbuf.len, errors); + PyBuffer_Release(&pbuf); + return codec_tuple(unicode, pbuf.len); } static PyObject * latin_1_decode(PyObject *self, - PyObject *args) + PyObject *args) { - Py_buffer pbuf; - PyObject *unicode; + Py_buffer pbuf; + PyObject *unicode; const char *errors = NULL; if (!PyArg_ParseTuple(args, "y*|z:latin_1_decode", - &pbuf, &errors)) - return NULL; + &pbuf, &errors)) + return NULL; - unicode = PyUnicode_DecodeLatin1(pbuf.buf, pbuf.len, errors); - PyBuffer_Release(&pbuf); - return codec_tuple(unicode, pbuf.len); + unicode = PyUnicode_DecodeLatin1(pbuf.buf, pbuf.len, errors); + PyBuffer_Release(&pbuf); + return codec_tuple(unicode, pbuf.len); } static PyObject * ascii_decode(PyObject *self, - PyObject *args) + PyObject *args) { - Py_buffer pbuf; - PyObject *unicode; + Py_buffer pbuf; + PyObject *unicode; const char *errors = NULL; if (!PyArg_ParseTuple(args, "y*|z:ascii_decode", - &pbuf, &errors)) - return NULL; + &pbuf, &errors)) + return NULL; - unicode = PyUnicode_DecodeASCII(pbuf.buf, pbuf.len, errors); - PyBuffer_Release(&pbuf); - return codec_tuple(unicode, pbuf.len); + unicode = PyUnicode_DecodeASCII(pbuf.buf, pbuf.len, errors); + PyBuffer_Release(&pbuf); + return codec_tuple(unicode, pbuf.len); } static PyObject * charmap_decode(PyObject *self, - PyObject *args) + PyObject *args) { - Py_buffer pbuf; - PyObject *unicode; + Py_buffer pbuf; + PyObject *unicode; const char *errors = NULL; PyObject *mapping = NULL; if (!PyArg_ParseTuple(args, "y*|zO:charmap_decode", - &pbuf, &errors, &mapping)) - return NULL; + &pbuf, &errors, &mapping)) + return NULL; if (mapping == Py_None) - mapping = NULL; + mapping = NULL; - unicode = PyUnicode_DecodeCharmap(pbuf.buf, pbuf.len, mapping, errors); - PyBuffer_Release(&pbuf); - return codec_tuple(unicode, pbuf.len); + unicode = PyUnicode_DecodeCharmap(pbuf.buf, pbuf.len, mapping, errors); + PyBuffer_Release(&pbuf); + return codec_tuple(unicode, pbuf.len); } #if defined(MS_WINDOWS) && defined(HAVE_USABLE_WCHAR_T) static PyObject * mbcs_decode(PyObject *self, - PyObject *args) + PyObject *args) { - Py_buffer pbuf; + Py_buffer pbuf; const char *errors = NULL; int final = 0; Py_ssize_t consumed; PyObject *decoded = NULL; if (!PyArg_ParseTuple(args, "y*|zi:mbcs_decode", - &pbuf, &errors, &final)) - return NULL; + &pbuf, &errors, &final)) + return NULL; consumed = pbuf.len; decoded = PyUnicode_DecodeMBCSStateful(pbuf.buf, pbuf.len, errors, - final ? NULL : &consumed); - PyBuffer_Release(&pbuf); + final ? NULL : &consumed); + PyBuffer_Release(&pbuf); if (decoded == NULL) - return NULL; + return NULL; return codec_tuple(decoded, consumed); } @@ -619,7 +619,7 @@ static PyObject * readbuffer_encode(PyObject *self, - PyObject *args) + PyObject *args) { Py_buffer pdata; const char *data; @@ -628,8 +628,8 @@ PyObject *result; if (!PyArg_ParseTuple(args, "s*|z:readbuffer_encode", - &pdata, &errors)) - return NULL; + &pdata, &errors)) + return NULL; data = pdata.buf; size = pdata.len; @@ -640,22 +640,22 @@ static PyObject * charbuffer_encode(PyObject *self, - PyObject *args) + PyObject *args) { const char *data; Py_ssize_t size; const char *errors = NULL; if (!PyArg_ParseTuple(args, "t#|z:charbuffer_encode", - &data, &size, &errors)) - return NULL; + &data, &size, &errors)) + return NULL; return codec_tuple(PyBytes_FromStringAndSize(data, size), size); } static PyObject * unicode_internal_encode(PyObject *self, - PyObject *args) + PyObject *args) { PyObject *obj; const char *errors = NULL; @@ -663,64 +663,64 @@ Py_ssize_t size; if (!PyArg_ParseTuple(args, "O|z:unicode_internal_encode", - &obj, &errors)) - return NULL; + &obj, &errors)) + return NULL; if (PyUnicode_Check(obj)) { - data = PyUnicode_AS_DATA(obj); - size = PyUnicode_GET_DATA_SIZE(obj); - return codec_tuple(PyBytes_FromStringAndSize(data, size), - PyUnicode_GET_SIZE(obj)); + data = PyUnicode_AS_DATA(obj); + size = PyUnicode_GET_DATA_SIZE(obj); + return codec_tuple(PyBytes_FromStringAndSize(data, size), + PyUnicode_GET_SIZE(obj)); } else { - if (PyObject_AsReadBuffer(obj, (const void **)&data, &size)) - return NULL; - return codec_tuple(PyBytes_FromStringAndSize(data, size), size); + if (PyObject_AsReadBuffer(obj, (const void **)&data, &size)) + return NULL; + return codec_tuple(PyBytes_FromStringAndSize(data, size), size); } } static PyObject * utf_7_encode(PyObject *self, - PyObject *args) + PyObject *args) { PyObject *str, *v; const char *errors = NULL; if (!PyArg_ParseTuple(args, "O|z:utf_7_encode", - &str, &errors)) - return NULL; + &str, &errors)) + return NULL; str = PyUnicode_FromObject(str); if (str == NULL) - return NULL; + return NULL; v = codec_tuple(PyUnicode_EncodeUTF7(PyUnicode_AS_UNICODE(str), - PyUnicode_GET_SIZE(str), - 0, - 0, - errors), - PyUnicode_GET_SIZE(str)); + PyUnicode_GET_SIZE(str), + 0, + 0, + errors), + PyUnicode_GET_SIZE(str)); Py_DECREF(str); return v; } static PyObject * utf_8_encode(PyObject *self, - PyObject *args) + PyObject *args) { PyObject *str, *v; const char *errors = NULL; if (!PyArg_ParseTuple(args, "O|z:utf_8_encode", - &str, &errors)) - return NULL; + &str, &errors)) + return NULL; str = PyUnicode_FromObject(str); if (str == NULL) - return NULL; + return NULL; v = codec_tuple(PyUnicode_EncodeUTF8(PyUnicode_AS_UNICODE(str), - PyUnicode_GET_SIZE(str), - errors), - PyUnicode_GET_SIZE(str)); + PyUnicode_GET_SIZE(str), + errors), + PyUnicode_GET_SIZE(str)); Py_DECREF(str); return v; } @@ -734,70 +734,70 @@ static PyObject * utf_16_encode(PyObject *self, - PyObject *args) + PyObject *args) { PyObject *str, *v; const char *errors = NULL; int byteorder = 0; if (!PyArg_ParseTuple(args, "O|zi:utf_16_encode", - &str, &errors, &byteorder)) - return NULL; + &str, &errors, &byteorder)) + return NULL; str = PyUnicode_FromObject(str); if (str == NULL) - return NULL; + return NULL; v = codec_tuple(PyUnicode_EncodeUTF16(PyUnicode_AS_UNICODE(str), - PyUnicode_GET_SIZE(str), - errors, - byteorder), - PyUnicode_GET_SIZE(str)); + PyUnicode_GET_SIZE(str), + errors, + byteorder), + PyUnicode_GET_SIZE(str)); Py_DECREF(str); return v; } static PyObject * utf_16_le_encode(PyObject *self, - PyObject *args) + PyObject *args) { PyObject *str, *v; const char *errors = NULL; if (!PyArg_ParseTuple(args, "O|z:utf_16_le_encode", - &str, &errors)) - return NULL; + &str, &errors)) + return NULL; str = PyUnicode_FromObject(str); if (str == NULL) - return NULL; + return NULL; v = codec_tuple(PyUnicode_EncodeUTF16(PyUnicode_AS_UNICODE(str), - PyUnicode_GET_SIZE(str), - errors, - -1), - PyUnicode_GET_SIZE(str)); + PyUnicode_GET_SIZE(str), + errors, + -1), + PyUnicode_GET_SIZE(str)); Py_DECREF(str); return v; } static PyObject * utf_16_be_encode(PyObject *self, - PyObject *args) + PyObject *args) { PyObject *str, *v; const char *errors = NULL; if (!PyArg_ParseTuple(args, "O|z:utf_16_be_encode", - &str, &errors)) - return NULL; + &str, &errors)) + return NULL; str = PyUnicode_FromObject(str); if (str == NULL) - return NULL; + return NULL; v = codec_tuple(PyUnicode_EncodeUTF16(PyUnicode_AS_UNICODE(str), - PyUnicode_GET_SIZE(str), - errors, - +1), - PyUnicode_GET_SIZE(str)); + PyUnicode_GET_SIZE(str), + errors, + +1), + PyUnicode_GET_SIZE(str)); Py_DECREF(str); return v; } @@ -811,186 +811,186 @@ static PyObject * utf_32_encode(PyObject *self, - PyObject *args) + PyObject *args) { PyObject *str, *v; const char *errors = NULL; int byteorder = 0; if (!PyArg_ParseTuple(args, "O|zi:utf_32_encode", - &str, &errors, &byteorder)) - return NULL; + &str, &errors, &byteorder)) + return NULL; str = PyUnicode_FromObject(str); if (str == NULL) - return NULL; + return NULL; v = codec_tuple(PyUnicode_EncodeUTF32(PyUnicode_AS_UNICODE(str), - PyUnicode_GET_SIZE(str), - errors, - byteorder), - PyUnicode_GET_SIZE(str)); + PyUnicode_GET_SIZE(str), + errors, + byteorder), + PyUnicode_GET_SIZE(str)); Py_DECREF(str); return v; } static PyObject * utf_32_le_encode(PyObject *self, - PyObject *args) + PyObject *args) { PyObject *str, *v; const char *errors = NULL; if (!PyArg_ParseTuple(args, "O|z:utf_32_le_encode", - &str, &errors)) - return NULL; + &str, &errors)) + return NULL; str = PyUnicode_FromObject(str); if (str == NULL) - return NULL; + return NULL; v = codec_tuple(PyUnicode_EncodeUTF32(PyUnicode_AS_UNICODE(str), - PyUnicode_GET_SIZE(str), - errors, - -1), - PyUnicode_GET_SIZE(str)); + PyUnicode_GET_SIZE(str), + errors, + -1), + PyUnicode_GET_SIZE(str)); Py_DECREF(str); return v; } static PyObject * utf_32_be_encode(PyObject *self, - PyObject *args) + PyObject *args) { PyObject *str, *v; const char *errors = NULL; if (!PyArg_ParseTuple(args, "O|z:utf_32_be_encode", - &str, &errors)) - return NULL; + &str, &errors)) + return NULL; str = PyUnicode_FromObject(str); if (str == NULL) - return NULL; + return NULL; v = codec_tuple(PyUnicode_EncodeUTF32(PyUnicode_AS_UNICODE(str), - PyUnicode_GET_SIZE(str), - errors, - +1), - PyUnicode_GET_SIZE(str)); + PyUnicode_GET_SIZE(str), + errors, + +1), + PyUnicode_GET_SIZE(str)); Py_DECREF(str); return v; } static PyObject * unicode_escape_encode(PyObject *self, - PyObject *args) + PyObject *args) { PyObject *str, *v; const char *errors = NULL; if (!PyArg_ParseTuple(args, "O|z:unicode_escape_encode", - &str, &errors)) - return NULL; + &str, &errors)) + return NULL; str = PyUnicode_FromObject(str); if (str == NULL) - return NULL; + return NULL; v = codec_tuple(PyUnicode_EncodeUnicodeEscape(PyUnicode_AS_UNICODE(str), - PyUnicode_GET_SIZE(str)), - PyUnicode_GET_SIZE(str)); + PyUnicode_GET_SIZE(str)), + PyUnicode_GET_SIZE(str)); Py_DECREF(str); return v; } static PyObject * raw_unicode_escape_encode(PyObject *self, - PyObject *args) + PyObject *args) { PyObject *str, *v; const char *errors = NULL; if (!PyArg_ParseTuple(args, "O|z:raw_unicode_escape_encode", - &str, &errors)) - return NULL; + &str, &errors)) + return NULL; str = PyUnicode_FromObject(str); if (str == NULL) - return NULL; + return NULL; v = codec_tuple(PyUnicode_EncodeRawUnicodeEscape( - PyUnicode_AS_UNICODE(str), - PyUnicode_GET_SIZE(str)), - PyUnicode_GET_SIZE(str)); + PyUnicode_AS_UNICODE(str), + PyUnicode_GET_SIZE(str)), + PyUnicode_GET_SIZE(str)); Py_DECREF(str); return v; } static PyObject * latin_1_encode(PyObject *self, - PyObject *args) + PyObject *args) { PyObject *str, *v; const char *errors = NULL; if (!PyArg_ParseTuple(args, "O|z:latin_1_encode", - &str, &errors)) - return NULL; + &str, &errors)) + return NULL; str = PyUnicode_FromObject(str); if (str == NULL) - return NULL; + return NULL; v = codec_tuple(PyUnicode_EncodeLatin1( - PyUnicode_AS_UNICODE(str), - PyUnicode_GET_SIZE(str), - errors), - PyUnicode_GET_SIZE(str)); + PyUnicode_AS_UNICODE(str), + PyUnicode_GET_SIZE(str), + errors), + PyUnicode_GET_SIZE(str)); Py_DECREF(str); return v; } static PyObject * ascii_encode(PyObject *self, - PyObject *args) + PyObject *args) { PyObject *str, *v; const char *errors = NULL; if (!PyArg_ParseTuple(args, "O|z:ascii_encode", - &str, &errors)) - return NULL; + &str, &errors)) + return NULL; str = PyUnicode_FromObject(str); if (str == NULL) - return NULL; + return NULL; v = codec_tuple(PyUnicode_EncodeASCII( - PyUnicode_AS_UNICODE(str), - PyUnicode_GET_SIZE(str), - errors), - PyUnicode_GET_SIZE(str)); + PyUnicode_AS_UNICODE(str), + PyUnicode_GET_SIZE(str), + errors), + PyUnicode_GET_SIZE(str)); Py_DECREF(str); return v; } static PyObject * charmap_encode(PyObject *self, - PyObject *args) + PyObject *args) { PyObject *str, *v; const char *errors = NULL; PyObject *mapping = NULL; if (!PyArg_ParseTuple(args, "O|zO:charmap_encode", - &str, &errors, &mapping)) - return NULL; + &str, &errors, &mapping)) + return NULL; if (mapping == Py_None) - mapping = NULL; + mapping = NULL; str = PyUnicode_FromObject(str); if (str == NULL) - return NULL; + return NULL; v = codec_tuple(PyUnicode_EncodeCharmap( - PyUnicode_AS_UNICODE(str), - PyUnicode_GET_SIZE(str), - mapping, - errors), - PyUnicode_GET_SIZE(str)); + PyUnicode_AS_UNICODE(str), + PyUnicode_GET_SIZE(str), + mapping, + errors), + PyUnicode_GET_SIZE(str)); Py_DECREF(str); return v; } @@ -1008,23 +1008,23 @@ static PyObject * mbcs_encode(PyObject *self, - PyObject *args) + PyObject *args) { PyObject *str, *v; const char *errors = NULL; if (!PyArg_ParseTuple(args, "O|z:mbcs_encode", - &str, &errors)) - return NULL; + &str, &errors)) + return NULL; str = PyUnicode_FromObject(str); if (str == NULL) - return NULL; + return NULL; v = codec_tuple(PyUnicode_EncodeMBCS( - PyUnicode_AS_UNICODE(str), - PyUnicode_GET_SIZE(str), - errors), - PyUnicode_GET_SIZE(str)); + PyUnicode_AS_UNICODE(str), + PyUnicode_GET_SIZE(str), + errors), + PyUnicode_GET_SIZE(str)); Py_DECREF(str); return v; } @@ -1048,8 +1048,8 @@ PyObject *handler; if (!PyArg_ParseTuple(args, "sO:register_error", - &name, &handler)) - return NULL; + &name, &handler)) + return NULL; if (PyCodec_RegisterError(name, handler)) return NULL; Py_RETURN_NONE; @@ -1066,82 +1066,82 @@ const char *name; if (!PyArg_ParseTuple(args, "s:lookup_error", - &name)) - return NULL; + &name)) + return NULL; return PyCodec_LookupError(name); } /* --- Module API --------------------------------------------------------- */ static PyMethodDef _codecs_functions[] = { - {"register", codec_register, METH_O, + {"register", codec_register, METH_O, register__doc__}, - {"lookup", codec_lookup, METH_VARARGS, + {"lookup", codec_lookup, METH_VARARGS, lookup__doc__}, - {"encode", codec_encode, METH_VARARGS, - encode__doc__}, - {"decode", codec_decode, METH_VARARGS, - decode__doc__}, - {"escape_encode", escape_encode, METH_VARARGS}, - {"escape_decode", escape_decode, METH_VARARGS}, - {"utf_8_encode", utf_8_encode, METH_VARARGS}, - {"utf_8_decode", utf_8_decode, METH_VARARGS}, - {"utf_7_encode", utf_7_encode, METH_VARARGS}, - {"utf_7_decode", utf_7_decode, METH_VARARGS}, - {"utf_16_encode", utf_16_encode, METH_VARARGS}, - {"utf_16_le_encode", utf_16_le_encode, METH_VARARGS}, - {"utf_16_be_encode", utf_16_be_encode, METH_VARARGS}, - {"utf_16_decode", utf_16_decode, METH_VARARGS}, - {"utf_16_le_decode", utf_16_le_decode, METH_VARARGS}, - {"utf_16_be_decode", utf_16_be_decode, METH_VARARGS}, - {"utf_16_ex_decode", utf_16_ex_decode, METH_VARARGS}, - {"utf_32_encode", utf_32_encode, METH_VARARGS}, - {"utf_32_le_encode", utf_32_le_encode, METH_VARARGS}, - {"utf_32_be_encode", utf_32_be_encode, METH_VARARGS}, - {"utf_32_decode", utf_32_decode, METH_VARARGS}, - {"utf_32_le_decode", utf_32_le_decode, METH_VARARGS}, - {"utf_32_be_decode", utf_32_be_decode, METH_VARARGS}, - {"utf_32_ex_decode", utf_32_ex_decode, METH_VARARGS}, - {"unicode_escape_encode", unicode_escape_encode, METH_VARARGS}, - {"unicode_escape_decode", unicode_escape_decode, METH_VARARGS}, - {"unicode_internal_encode", unicode_internal_encode, METH_VARARGS}, - {"unicode_internal_decode", unicode_internal_decode, METH_VARARGS}, - {"raw_unicode_escape_encode", raw_unicode_escape_encode, METH_VARARGS}, - {"raw_unicode_escape_decode", raw_unicode_escape_decode, METH_VARARGS}, - {"latin_1_encode", latin_1_encode, METH_VARARGS}, - {"latin_1_decode", latin_1_decode, METH_VARARGS}, - {"ascii_encode", ascii_encode, METH_VARARGS}, - {"ascii_decode", ascii_decode, METH_VARARGS}, - {"charmap_encode", charmap_encode, METH_VARARGS}, - {"charmap_decode", charmap_decode, METH_VARARGS}, - {"charmap_build", charmap_build, METH_VARARGS}, - {"readbuffer_encode", readbuffer_encode, METH_VARARGS}, - {"charbuffer_encode", charbuffer_encode, METH_VARARGS}, + {"encode", codec_encode, METH_VARARGS, + encode__doc__}, + {"decode", codec_decode, METH_VARARGS, + decode__doc__}, + {"escape_encode", escape_encode, METH_VARARGS}, + {"escape_decode", escape_decode, METH_VARARGS}, + {"utf_8_encode", utf_8_encode, METH_VARARGS}, + {"utf_8_decode", utf_8_decode, METH_VARARGS}, + {"utf_7_encode", utf_7_encode, METH_VARARGS}, + {"utf_7_decode", utf_7_decode, METH_VARARGS}, + {"utf_16_encode", utf_16_encode, METH_VARARGS}, + {"utf_16_le_encode", utf_16_le_encode, METH_VARARGS}, + {"utf_16_be_encode", utf_16_be_encode, METH_VARARGS}, + {"utf_16_decode", utf_16_decode, METH_VARARGS}, + {"utf_16_le_decode", utf_16_le_decode, METH_VARARGS}, + {"utf_16_be_decode", utf_16_be_decode, METH_VARARGS}, + {"utf_16_ex_decode", utf_16_ex_decode, METH_VARARGS}, + {"utf_32_encode", utf_32_encode, METH_VARARGS}, + {"utf_32_le_encode", utf_32_le_encode, METH_VARARGS}, + {"utf_32_be_encode", utf_32_be_encode, METH_VARARGS}, + {"utf_32_decode", utf_32_decode, METH_VARARGS}, + {"utf_32_le_decode", utf_32_le_decode, METH_VARARGS}, + {"utf_32_be_decode", utf_32_be_decode, METH_VARARGS}, + {"utf_32_ex_decode", utf_32_ex_decode, METH_VARARGS}, + {"unicode_escape_encode", unicode_escape_encode, METH_VARARGS}, + {"unicode_escape_decode", unicode_escape_decode, METH_VARARGS}, + {"unicode_internal_encode", unicode_internal_encode, METH_VARARGS}, + {"unicode_internal_decode", unicode_internal_decode, METH_VARARGS}, + {"raw_unicode_escape_encode", raw_unicode_escape_encode, METH_VARARGS}, + {"raw_unicode_escape_decode", raw_unicode_escape_decode, METH_VARARGS}, + {"latin_1_encode", latin_1_encode, METH_VARARGS}, + {"latin_1_decode", latin_1_decode, METH_VARARGS}, + {"ascii_encode", ascii_encode, METH_VARARGS}, + {"ascii_decode", ascii_decode, METH_VARARGS}, + {"charmap_encode", charmap_encode, METH_VARARGS}, + {"charmap_decode", charmap_decode, METH_VARARGS}, + {"charmap_build", charmap_build, METH_VARARGS}, + {"readbuffer_encode", readbuffer_encode, METH_VARARGS}, + {"charbuffer_encode", charbuffer_encode, METH_VARARGS}, #if defined(MS_WINDOWS) && defined(HAVE_USABLE_WCHAR_T) - {"mbcs_encode", mbcs_encode, METH_VARARGS}, - {"mbcs_decode", mbcs_decode, METH_VARARGS}, + {"mbcs_encode", mbcs_encode, METH_VARARGS}, + {"mbcs_decode", mbcs_decode, METH_VARARGS}, #endif - {"register_error", register_error, METH_VARARGS, + {"register_error", register_error, METH_VARARGS, register_error__doc__}, - {"lookup_error", lookup_error, METH_VARARGS, + {"lookup_error", lookup_error, METH_VARARGS, lookup_error__doc__}, - {NULL, NULL} /* sentinel */ + {NULL, NULL} /* sentinel */ }; static struct PyModuleDef codecsmodule = { - PyModuleDef_HEAD_INIT, - "_codecs", - NULL, - -1, - _codecs_functions, - NULL, - NULL, - NULL, - NULL + PyModuleDef_HEAD_INIT, + "_codecs", + NULL, + -1, + _codecs_functions, + NULL, + NULL, + NULL, + NULL }; PyMODINIT_FUNC PyInit__codecs(void) { - return PyModule_Create(&codecsmodule); + return PyModule_Create(&codecsmodule); } Modified: python/branches/release31-maint/Modules/_collectionsmodule.c ============================================================================== --- python/branches/release31-maint/Modules/_collectionsmodule.c (original) +++ python/branches/release31-maint/Modules/_collectionsmodule.c Sun May 9 18:14:21 2010 @@ -46,9 +46,9 @@ */ typedef struct BLOCK { - struct BLOCK *leftlink; - struct BLOCK *rightlink; - PyObject *data[BLOCKLEN]; + struct BLOCK *leftlink; + struct BLOCK *rightlink; + PyObject *data[BLOCKLEN]; } block; #define MAXFREEBLOCKS 10 @@ -57,71 +57,71 @@ static block * newblock(block *leftlink, block *rightlink, Py_ssize_t len) { - block *b; - /* To prevent len from overflowing PY_SSIZE_T_MAX on 64-bit machines, we - * refuse to allocate new blocks if the current len is dangerously - * close. There is some extra margin to prevent spurious arithmetic - * overflows at various places. The following check ensures that - * the blocks allocated to the deque, in the worst case, can only - * have PY_SSIZE_T_MAX-2 entries in total. - */ - if (len >= PY_SSIZE_T_MAX - 2*BLOCKLEN) { - PyErr_SetString(PyExc_OverflowError, - "cannot add more blocks to the deque"); - return NULL; - } - if (numfreeblocks) { - numfreeblocks -= 1; - b = freeblocks[numfreeblocks]; - } else { - b = PyMem_Malloc(sizeof(block)); - if (b == NULL) { - PyErr_NoMemory(); - return NULL; - } - } - b->leftlink = leftlink; - b->rightlink = rightlink; - return b; + block *b; + /* To prevent len from overflowing PY_SSIZE_T_MAX on 64-bit machines, we + * refuse to allocate new blocks if the current len is dangerously + * close. There is some extra margin to prevent spurious arithmetic + * overflows at various places. The following check ensures that + * the blocks allocated to the deque, in the worst case, can only + * have PY_SSIZE_T_MAX-2 entries in total. + */ + if (len >= PY_SSIZE_T_MAX - 2*BLOCKLEN) { + PyErr_SetString(PyExc_OverflowError, + "cannot add more blocks to the deque"); + return NULL; + } + if (numfreeblocks) { + numfreeblocks -= 1; + b = freeblocks[numfreeblocks]; + } else { + b = PyMem_Malloc(sizeof(block)); + if (b == NULL) { + PyErr_NoMemory(); + return NULL; + } + } + b->leftlink = leftlink; + b->rightlink = rightlink; + return b; } static void freeblock(block *b) { - if (numfreeblocks < MAXFREEBLOCKS) { - freeblocks[numfreeblocks] = b; - numfreeblocks++; - } else { - PyMem_Free(b); - } + if (numfreeblocks < MAXFREEBLOCKS) { + freeblocks[numfreeblocks] = b; + numfreeblocks++; + } else { + PyMem_Free(b); + } } typedef struct { - PyObject_HEAD - block *leftblock; - block *rightblock; - Py_ssize_t leftindex; /* in range(BLOCKLEN) */ - Py_ssize_t rightindex; /* in range(BLOCKLEN) */ - Py_ssize_t len; - Py_ssize_t maxlen; - long state; /* incremented whenever the indices move */ - PyObject *weakreflist; /* List of weak references */ + PyObject_HEAD + block *leftblock; + block *rightblock; + Py_ssize_t leftindex; /* in range(BLOCKLEN) */ + Py_ssize_t rightindex; /* in range(BLOCKLEN) */ + Py_ssize_t len; + Py_ssize_t maxlen; + long state; /* incremented whenever the indices move */ + PyObject *weakreflist; /* List of weak references */ } dequeobject; /* The deque's size limit is d.maxlen. The limit can be zero or positive. * If there is no limit, then d.maxlen == -1. - * + * * After an item is added to a deque, we check to see if the size has grown past * the limit. If it has, we get the size back down to the limit by popping an * item off of the opposite end. The methods that can trigger this are append(), * appendleft(), extend(), and extendleft(). */ -#define TRIM(d, popfunction) \ - if (d->maxlen != -1 && d->len > d->maxlen) { \ - PyObject *rv = popfunction(d, NULL); \ - assert(rv != NULL && d->len <= d->maxlen); \ - Py_DECREF(rv); \ +#define TRIM(d, popfunction) \ + if (d->maxlen != -1 && d->len > d->maxlen) { \ + PyObject *rv = popfunction(d, NULL); \ + assert(rv != NULL && d->len <= d->maxlen); \ + Py_DECREF(rv); \ } static PyTypeObject deque_type; @@ -129,65 +129,65 @@ static PyObject * deque_new(PyTypeObject *type, PyObject *args, PyObject *kwds) { - dequeobject *deque; - block *b; + dequeobject *deque; + block *b; + + /* create dequeobject structure */ + deque = (dequeobject *)type->tp_alloc(type, 0); + if (deque == NULL) + return NULL; + + b = newblock(NULL, NULL, 0); + if (b == NULL) { + Py_DECREF(deque); + return NULL; + } - /* create dequeobject structure */ - deque = (dequeobject *)type->tp_alloc(type, 0); - if (deque == NULL) - return NULL; - - b = newblock(NULL, NULL, 0); - if (b == NULL) { - Py_DECREF(deque); - return NULL; - } - - assert(BLOCKLEN >= 2); - deque->leftblock = b; - deque->rightblock = b; - deque->leftindex = CENTER + 1; - deque->rightindex = CENTER; - deque->len = 0; - deque->state = 0; - deque->weakreflist = NULL; - deque->maxlen = -1; + assert(BLOCKLEN >= 2); + deque->leftblock = b; + deque->rightblock = b; + deque->leftindex = CENTER + 1; + deque->rightindex = CENTER; + deque->len = 0; + deque->state = 0; + deque->weakreflist = NULL; + deque->maxlen = -1; - return (PyObject *)deque; + return (PyObject *)deque; } static PyObject * deque_pop(dequeobject *deque, PyObject *unused) { - PyObject *item; - block *prevblock; + PyObject *item; + block *prevblock; - if (deque->len == 0) { - PyErr_SetString(PyExc_IndexError, "pop from an empty deque"); - return NULL; - } - item = deque->rightblock->data[deque->rightindex]; - deque->rightindex--; - deque->len--; - deque->state++; - - if (deque->rightindex == -1) { - if (deque->len == 0) { - assert(deque->leftblock == deque->rightblock); - assert(deque->leftindex == deque->rightindex+1); - /* re-center instead of freeing a block */ - deque->leftindex = CENTER + 1; - deque->rightindex = CENTER; - } else { - prevblock = deque->rightblock->leftlink; - assert(deque->leftblock != deque->rightblock); - freeblock(deque->rightblock); - prevblock->rightlink = NULL; - deque->rightblock = prevblock; - deque->rightindex = BLOCKLEN - 1; - } - } - return item; + if (deque->len == 0) { + PyErr_SetString(PyExc_IndexError, "pop from an empty deque"); + return NULL; + } + item = deque->rightblock->data[deque->rightindex]; + deque->rightindex--; + deque->len--; + deque->state++; + + if (deque->rightindex == -1) { + if (deque->len == 0) { + assert(deque->leftblock == deque->rightblock); + assert(deque->leftindex == deque->rightindex+1); + /* re-center instead of freeing a block */ + deque->leftindex = CENTER + 1; + deque->rightindex = CENTER; + } else { + prevblock = deque->rightblock->leftlink; + assert(deque->leftblock != deque->rightblock); + freeblock(deque->rightblock); + prevblock->rightlink = NULL; + deque->rightblock = prevblock; + deque->rightindex = BLOCKLEN - 1; + } + } + return item; } PyDoc_STRVAR(pop_doc, "Remove and return the rightmost element."); @@ -195,37 +195,37 @@ static PyObject * deque_popleft(dequeobject *deque, PyObject *unused) { - PyObject *item; - block *prevblock; + PyObject *item; + block *prevblock; - if (deque->len == 0) { - PyErr_SetString(PyExc_IndexError, "pop from an empty deque"); - return NULL; - } - assert(deque->leftblock != NULL); - item = deque->leftblock->data[deque->leftindex]; - deque->leftindex++; - deque->len--; - deque->state++; - - if (deque->leftindex == BLOCKLEN) { - if (deque->len == 0) { - assert(deque->leftblock == deque->rightblock); - assert(deque->leftindex == deque->rightindex+1); - /* re-center instead of freeing a block */ - deque->leftindex = CENTER + 1; - deque->rightindex = CENTER; - } else { - assert(deque->leftblock != deque->rightblock); - prevblock = deque->leftblock->rightlink; - freeblock(deque->leftblock); - assert(prevblock != NULL); - prevblock->leftlink = NULL; - deque->leftblock = prevblock; - deque->leftindex = 0; - } - } - return item; + if (deque->len == 0) { + PyErr_SetString(PyExc_IndexError, "pop from an empty deque"); + return NULL; + } + assert(deque->leftblock != NULL); + item = deque->leftblock->data[deque->leftindex]; + deque->leftindex++; + deque->len--; + deque->state++; + + if (deque->leftindex == BLOCKLEN) { + if (deque->len == 0) { + assert(deque->leftblock == deque->rightblock); + assert(deque->leftindex == deque->rightindex+1); + /* re-center instead of freeing a block */ + deque->leftindex = CENTER + 1; + deque->rightindex = CENTER; + } else { + assert(deque->leftblock != deque->rightblock); + prevblock = deque->leftblock->rightlink; + freeblock(deque->leftblock); + assert(prevblock != NULL); + prevblock->leftlink = NULL; + deque->leftblock = prevblock; + deque->leftindex = 0; + } + } + return item; } PyDoc_STRVAR(popleft_doc, "Remove and return the leftmost element."); @@ -233,22 +233,22 @@ static PyObject * deque_append(dequeobject *deque, PyObject *item) { - deque->state++; - if (deque->rightindex == BLOCKLEN-1) { - block *b = newblock(deque->rightblock, NULL, deque->len); - if (b == NULL) - return NULL; - assert(deque->rightblock->rightlink == NULL); - deque->rightblock->rightlink = b; - deque->rightblock = b; - deque->rightindex = -1; - } - Py_INCREF(item); - deque->len++; - deque->rightindex++; - deque->rightblock->data[deque->rightindex] = item; - TRIM(deque, deque_popleft); - Py_RETURN_NONE; + deque->state++; + if (deque->rightindex == BLOCKLEN-1) { + block *b = newblock(deque->rightblock, NULL, deque->len); + if (b == NULL) + return NULL; + assert(deque->rightblock->rightlink == NULL); + deque->rightblock->rightlink = b; + deque->rightblock = b; + deque->rightindex = -1; + } + Py_INCREF(item); + deque->len++; + deque->rightindex++; + deque->rightblock->data[deque->rightindex] = item; + TRIM(deque, deque_popleft); + Py_RETURN_NONE; } PyDoc_STRVAR(append_doc, "Add an element to the right side of the deque."); @@ -256,90 +256,90 @@ static PyObject * deque_appendleft(dequeobject *deque, PyObject *item) { - deque->state++; - if (deque->leftindex == 0) { - block *b = newblock(NULL, deque->leftblock, deque->len); - if (b == NULL) - return NULL; - assert(deque->leftblock->leftlink == NULL); - deque->leftblock->leftlink = b; - deque->leftblock = b; - deque->leftindex = BLOCKLEN; - } - Py_INCREF(item); - deque->len++; - deque->leftindex--; - deque->leftblock->data[deque->leftindex] = item; - TRIM(deque, deque_pop); - Py_RETURN_NONE; + deque->state++; + if (deque->leftindex == 0) { + block *b = newblock(NULL, deque->leftblock, deque->len); + if (b == NULL) + return NULL; + assert(deque->leftblock->leftlink == NULL); + deque->leftblock->leftlink = b; + deque->leftblock = b; + deque->leftindex = BLOCKLEN; + } + Py_INCREF(item); + deque->len++; + deque->leftindex--; + deque->leftblock->data[deque->leftindex] = item; + TRIM(deque, deque_pop); + Py_RETURN_NONE; } PyDoc_STRVAR(appendleft_doc, "Add an element to the left side of the deque."); -/* Run an iterator to exhaustion. Shortcut for +/* Run an iterator to exhaustion. Shortcut for the extend/extendleft methods when maxlen == 0. */ static PyObject* consume_iterator(PyObject *it) { - PyObject *item; + PyObject *item; - while ((item = PyIter_Next(it)) != NULL) { - Py_DECREF(item); - } - Py_DECREF(it); - if (PyErr_Occurred()) - return NULL; - Py_RETURN_NONE; + while ((item = PyIter_Next(it)) != NULL) { + Py_DECREF(item); + } + Py_DECREF(it); + if (PyErr_Occurred()) + return NULL; + Py_RETURN_NONE; } static PyObject * deque_extend(dequeobject *deque, PyObject *iterable) { - PyObject *it, *item; + PyObject *it, *item; - /* Handle case where id(deque) == id(iterable) */ - if ((PyObject *)deque == iterable) { - PyObject *result; - PyObject *s = PySequence_List(iterable); - if (s == NULL) - return NULL; - result = deque_extend(deque, s); - Py_DECREF(s); - return result; - } - - it = PyObject_GetIter(iterable); - if (it == NULL) - return NULL; - - if (deque->maxlen == 0) - return consume_iterator(it); - - while ((item = PyIter_Next(it)) != NULL) { - deque->state++; - if (deque->rightindex == BLOCKLEN-1) { - block *b = newblock(deque->rightblock, NULL, - deque->len); - if (b == NULL) { - Py_DECREF(item); - Py_DECREF(it); - return NULL; - } - assert(deque->rightblock->rightlink == NULL); - deque->rightblock->rightlink = b; - deque->rightblock = b; - deque->rightindex = -1; - } - deque->len++; - deque->rightindex++; - deque->rightblock->data[deque->rightindex] = item; - TRIM(deque, deque_popleft); - } - Py_DECREF(it); - if (PyErr_Occurred()) - return NULL; - Py_RETURN_NONE; + /* Handle case where id(deque) == id(iterable) */ + if ((PyObject *)deque == iterable) { + PyObject *result; + PyObject *s = PySequence_List(iterable); + if (s == NULL) + return NULL; + result = deque_extend(deque, s); + Py_DECREF(s); + return result; + } + + it = PyObject_GetIter(iterable); + if (it == NULL) + return NULL; + + if (deque->maxlen == 0) + return consume_iterator(it); + + while ((item = PyIter_Next(it)) != NULL) { + deque->state++; + if (deque->rightindex == BLOCKLEN-1) { + block *b = newblock(deque->rightblock, NULL, + deque->len); + if (b == NULL) { + Py_DECREF(item); + Py_DECREF(it); + return NULL; + } + assert(deque->rightblock->rightlink == NULL); + deque->rightblock->rightlink = b; + deque->rightblock = b; + deque->rightindex = -1; + } + deque->len++; + deque->rightindex++; + deque->rightblock->data[deque->rightindex] = item; + TRIM(deque, deque_popleft); + } + Py_DECREF(it); + if (PyErr_Occurred()) + return NULL; + Py_RETURN_NONE; } PyDoc_STRVAR(extend_doc, @@ -348,50 +348,50 @@ static PyObject * deque_extendleft(dequeobject *deque, PyObject *iterable) { - PyObject *it, *item; + PyObject *it, *item; - /* Handle case where id(deque) == id(iterable) */ - if ((PyObject *)deque == iterable) { - PyObject *result; - PyObject *s = PySequence_List(iterable); - if (s == NULL) - return NULL; - result = deque_extendleft(deque, s); - Py_DECREF(s); - return result; - } - - it = PyObject_GetIter(iterable); - if (it == NULL) - return NULL; - - if (deque->maxlen == 0) - return consume_iterator(it); - - while ((item = PyIter_Next(it)) != NULL) { - deque->state++; - if (deque->leftindex == 0) { - block *b = newblock(NULL, deque->leftblock, - deque->len); - if (b == NULL) { - Py_DECREF(item); - Py_DECREF(it); - return NULL; - } - assert(deque->leftblock->leftlink == NULL); - deque->leftblock->leftlink = b; - deque->leftblock = b; - deque->leftindex = BLOCKLEN; - } - deque->len++; - deque->leftindex--; - deque->leftblock->data[deque->leftindex] = item; - TRIM(deque, deque_pop); - } - Py_DECREF(it); - if (PyErr_Occurred()) - return NULL; - Py_RETURN_NONE; + /* Handle case where id(deque) == id(iterable) */ + if ((PyObject *)deque == iterable) { + PyObject *result; + PyObject *s = PySequence_List(iterable); + if (s == NULL) + return NULL; + result = deque_extendleft(deque, s); + Py_DECREF(s); + return result; + } + + it = PyObject_GetIter(iterable); + if (it == NULL) + return NULL; + + if (deque->maxlen == 0) + return consume_iterator(it); + + while ((item = PyIter_Next(it)) != NULL) { + deque->state++; + if (deque->leftindex == 0) { + block *b = newblock(NULL, deque->leftblock, + deque->len); + if (b == NULL) { + Py_DECREF(item); + Py_DECREF(it); + return NULL; + } + assert(deque->leftblock->leftlink == NULL); + deque->leftblock->leftlink = b; + deque->leftblock = b; + deque->leftindex = BLOCKLEN; + } + deque->len++; + deque->leftindex--; + deque->leftblock->data[deque->leftindex] = item; + TRIM(deque, deque_pop); + } + Py_DECREF(it); + if (PyErr_Occurred()) + return NULL; + Py_RETURN_NONE; } PyDoc_STRVAR(extendleft_doc, @@ -400,63 +400,63 @@ static PyObject * deque_inplace_concat(dequeobject *deque, PyObject *other) { - PyObject *result; + PyObject *result; - result = deque_extend(deque, other); - if (result == NULL) - return result; - Py_DECREF(result); - Py_INCREF(deque); - return (PyObject *)deque; + result = deque_extend(deque, other); + if (result == NULL) + return result; + Py_DECREF(result); + Py_INCREF(deque); + return (PyObject *)deque; } static int _deque_rotate(dequeobject *deque, Py_ssize_t n) { - Py_ssize_t i, len=deque->len, halflen=(len+1)>>1; - PyObject *item, *rv; + Py_ssize_t i, len=deque->len, halflen=(len+1)>>1; + PyObject *item, *rv; + + if (len == 0) + return 0; + if (n > halflen || n < -halflen) { + n %= len; + if (n > halflen) + n -= len; + else if (n < -halflen) + n += len; + } - if (len == 0) - return 0; - if (n > halflen || n < -halflen) { - n %= len; - if (n > halflen) - n -= len; - else if (n < -halflen) - n += len; - } - - for (i=0 ; in ; i--) { - item = deque_popleft(deque, NULL); - assert (item != NULL); - rv = deque_append(deque, item); - Py_DECREF(item); - if (rv == NULL) - return -1; - Py_DECREF(rv); - } - return 0; + for (i=0 ; in ; i--) { + item = deque_popleft(deque, NULL); + assert (item != NULL); + rv = deque_append(deque, item); + Py_DECREF(item); + if (rv == NULL) + return -1; + Py_DECREF(rv); + } + return 0; } static PyObject * deque_rotate(dequeobject *deque, PyObject *args) { - Py_ssize_t n=1; + Py_ssize_t n=1; - if (!PyArg_ParseTuple(args, "|n:rotate", &n)) - return NULL; - if (_deque_rotate(deque, n) == 0) - Py_RETURN_NONE; - return NULL; + if (!PyArg_ParseTuple(args, "|n:rotate", &n)) + return NULL; + if (_deque_rotate(deque, n) == 0) + Py_RETURN_NONE; + return NULL; } PyDoc_STRVAR(rotate_doc, @@ -465,39 +465,39 @@ static Py_ssize_t deque_len(dequeobject *deque) { - return deque->len; + return deque->len; } static PyObject * deque_remove(dequeobject *deque, PyObject *value) { - Py_ssize_t i, n=deque->len; + Py_ssize_t i, n=deque->len; - for (i=0 ; ileftblock->data[deque->leftindex]; - int cmp = PyObject_RichCompareBool(item, value, Py_EQ); - - if (deque->len != n) { - PyErr_SetString(PyExc_IndexError, - "deque mutated during remove()."); - return NULL; - } - if (cmp > 0) { - PyObject *tgt = deque_popleft(deque, NULL); - assert (tgt != NULL); - Py_DECREF(tgt); - if (_deque_rotate(deque, i) == -1) - return NULL; - Py_RETURN_NONE; - } - else if (cmp < 0) { - _deque_rotate(deque, i); - return NULL; - } - _deque_rotate(deque, -1); - } - PyErr_SetString(PyExc_ValueError, "deque.remove(x): x not in deque"); - return NULL; + for (i=0 ; ileftblock->data[deque->leftindex]; + int cmp = PyObject_RichCompareBool(item, value, Py_EQ); + + if (deque->len != n) { + PyErr_SetString(PyExc_IndexError, + "deque mutated during remove()."); + return NULL; + } + if (cmp > 0) { + PyObject *tgt = deque_popleft(deque, NULL); + assert (tgt != NULL); + Py_DECREF(tgt); + if (_deque_rotate(deque, i) == -1) + return NULL; + Py_RETURN_NONE; + } + else if (cmp < 0) { + _deque_rotate(deque, i); + return NULL; + } + _deque_rotate(deque, -1); + } + PyErr_SetString(PyExc_ValueError, "deque.remove(x): x not in deque"); + return NULL; } PyDoc_STRVAR(remove_doc, @@ -506,56 +506,56 @@ static int deque_clear(dequeobject *deque) { - PyObject *item; + PyObject *item; - while (deque->len) { - item = deque_pop(deque, NULL); - assert (item != NULL); - Py_DECREF(item); - } - assert(deque->leftblock == deque->rightblock && - deque->leftindex - 1 == deque->rightindex && - deque->len == 0); - return 0; + while (deque->len) { + item = deque_pop(deque, NULL); + assert (item != NULL); + Py_DECREF(item); + } + assert(deque->leftblock == deque->rightblock && + deque->leftindex - 1 == deque->rightindex && + deque->len == 0); + return 0; } static PyObject * deque_item(dequeobject *deque, Py_ssize_t i) { - block *b; - PyObject *item; - Py_ssize_t n, index=i; - - if (i < 0 || i >= deque->len) { - PyErr_SetString(PyExc_IndexError, - "deque index out of range"); - return NULL; - } - - if (i == 0) { - i = deque->leftindex; - b = deque->leftblock; - } else if (i == deque->len - 1) { - i = deque->rightindex; - b = deque->rightblock; - } else { - i += deque->leftindex; - n = i / BLOCKLEN; - i %= BLOCKLEN; - if (index < (deque->len >> 1)) { - b = deque->leftblock; - while (n--) - b = b->rightlink; - } else { - n = (deque->leftindex + deque->len - 1) / BLOCKLEN - n; - b = deque->rightblock; - while (n--) - b = b->leftlink; - } - } - item = b->data[i]; - Py_INCREF(item); - return item; + block *b; + PyObject *item; + Py_ssize_t n, index=i; + + if (i < 0 || i >= deque->len) { + PyErr_SetString(PyExc_IndexError, + "deque index out of range"); + return NULL; + } + + if (i == 0) { + i = deque->leftindex; + b = deque->leftblock; + } else if (i == deque->len - 1) { + i = deque->rightindex; + b = deque->rightblock; + } else { + i += deque->leftindex; + n = i / BLOCKLEN; + i %= BLOCKLEN; + if (index < (deque->len >> 1)) { + b = deque->leftblock; + while (n--) + b = b->rightlink; + } else { + n = (deque->leftindex + deque->len - 1) / BLOCKLEN - n; + b = deque->rightblock; + while (n--) + b = b->leftlink; + } + } + item = b->data[i]; + Py_INCREF(item); + return item; } /* delitem() implemented in terms of rotate for simplicity and reasonable @@ -568,62 +568,62 @@ static int deque_del_item(dequeobject *deque, Py_ssize_t i) { - PyObject *item; + PyObject *item; - assert (i >= 0 && i < deque->len); - if (_deque_rotate(deque, -i) == -1) - return -1; + assert (i >= 0 && i < deque->len); + if (_deque_rotate(deque, -i) == -1) + return -1; - item = deque_popleft(deque, NULL); - assert (item != NULL); - Py_DECREF(item); + item = deque_popleft(deque, NULL); + assert (item != NULL); + Py_DECREF(item); - return _deque_rotate(deque, i); + return _deque_rotate(deque, i); } static int deque_ass_item(dequeobject *deque, Py_ssize_t i, PyObject *v) { - PyObject *old_value; - block *b; - Py_ssize_t n, len=deque->len, halflen=(len+1)>>1, index=i; - - if (i < 0 || i >= len) { - PyErr_SetString(PyExc_IndexError, - "deque index out of range"); - return -1; - } - if (v == NULL) - return deque_del_item(deque, i); - - i += deque->leftindex; - n = i / BLOCKLEN; - i %= BLOCKLEN; - if (index <= halflen) { - b = deque->leftblock; - while (n--) - b = b->rightlink; - } else { - n = (deque->leftindex + len - 1) / BLOCKLEN - n; - b = deque->rightblock; - while (n--) - b = b->leftlink; - } - Py_INCREF(v); - old_value = b->data[i]; - b->data[i] = v; - Py_DECREF(old_value); - return 0; + PyObject *old_value; + block *b; + Py_ssize_t n, len=deque->len, halflen=(len+1)>>1, index=i; + + if (i < 0 || i >= len) { + PyErr_SetString(PyExc_IndexError, + "deque index out of range"); + return -1; + } + if (v == NULL) + return deque_del_item(deque, i); + + i += deque->leftindex; + n = i / BLOCKLEN; + i %= BLOCKLEN; + if (index <= halflen) { + b = deque->leftblock; + while (n--) + b = b->rightlink; + } else { + n = (deque->leftindex + len - 1) / BLOCKLEN - n; + b = deque->rightblock; + while (n--) + b = b->leftlink; + } + Py_INCREF(v); + old_value = b->data[i]; + b->data[i] = v; + Py_DECREF(old_value); + return 0; } static PyObject * deque_clearmethod(dequeobject *deque) { - int rv; + int rv; - rv = deque_clear(deque); - assert (rv != -1); - Py_RETURN_NONE; + rv = deque_clear(deque); + assert (rv != -1); + Py_RETURN_NONE; } PyDoc_STRVAR(clear_doc, "Remove all elements from the deque."); @@ -631,49 +631,49 @@ static void deque_dealloc(dequeobject *deque) { - PyObject_GC_UnTrack(deque); - if (deque->weakreflist != NULL) - PyObject_ClearWeakRefs((PyObject *) deque); - if (deque->leftblock != NULL) { - deque_clear(deque); - assert(deque->leftblock != NULL); - freeblock(deque->leftblock); - } - deque->leftblock = NULL; - deque->rightblock = NULL; - Py_TYPE(deque)->tp_free(deque); + PyObject_GC_UnTrack(deque); + if (deque->weakreflist != NULL) + PyObject_ClearWeakRefs((PyObject *) deque); + if (deque->leftblock != NULL) { + deque_clear(deque); + assert(deque->leftblock != NULL); + freeblock(deque->leftblock); + } + deque->leftblock = NULL; + deque->rightblock = NULL; + Py_TYPE(deque)->tp_free(deque); } static int deque_traverse(dequeobject *deque, visitproc visit, void *arg) { - block *b; - PyObject *item; - Py_ssize_t index; - Py_ssize_t indexlo = deque->leftindex; - - for (b = deque->leftblock; b != NULL; b = b->rightlink) { - const Py_ssize_t indexhi = b == deque->rightblock ? - deque->rightindex : - BLOCKLEN - 1; - - for (index = indexlo; index <= indexhi; ++index) { - item = b->data[index]; - Py_VISIT(item); - } - indexlo = 0; - } - return 0; + block *b; + PyObject *item; + Py_ssize_t index; + Py_ssize_t indexlo = deque->leftindex; + + for (b = deque->leftblock; b != NULL; b = b->rightlink) { + const Py_ssize_t indexhi = b == deque->rightblock ? + deque->rightindex : + BLOCKLEN - 1; + + for (index = indexlo; index <= indexhi; ++index) { + item = b->data[index]; + Py_VISIT(item); + } + indexlo = 0; + } + return 0; } static PyObject * deque_copy(PyObject *deque) { - if (((dequeobject *)deque)->maxlen == -1) - return PyObject_CallFunction((PyObject *)(Py_TYPE(deque)), "O", deque, NULL); - else - return PyObject_CallFunction((PyObject *)(Py_TYPE(deque)), "Oi", - deque, ((dequeobject *)deque)->maxlen, NULL); + if (((dequeobject *)deque)->maxlen == -1) + return PyObject_CallFunction((PyObject *)(Py_TYPE(deque)), "O", deque, NULL); + else + return PyObject_CallFunction((PyObject *)(Py_TYPE(deque)), "Oi", + deque, ((dequeobject *)deque)->maxlen, NULL); } PyDoc_STRVAR(copy_doc, "Return a shallow copy of a deque."); @@ -681,30 +681,30 @@ static PyObject * deque_reduce(dequeobject *deque) { - PyObject *dict, *result, *aslist; + PyObject *dict, *result, *aslist; - dict = PyObject_GetAttrString((PyObject *)deque, "__dict__"); - if (dict == NULL) - PyErr_Clear(); - aslist = PySequence_List((PyObject *)deque); - if (aslist == NULL) { - Py_XDECREF(dict); - return NULL; - } - if (dict == NULL) { - if (deque->maxlen == -1) - result = Py_BuildValue("O(O)", Py_TYPE(deque), aslist); - else - result = Py_BuildValue("O(On)", Py_TYPE(deque), aslist, deque->maxlen); - } else { - if (deque->maxlen == -1) - result = Py_BuildValue("O(OO)O", Py_TYPE(deque), aslist, Py_None, dict); - else - result = Py_BuildValue("O(On)O", Py_TYPE(deque), aslist, deque->maxlen, dict); - } - Py_XDECREF(dict); - Py_DECREF(aslist); - return result; + dict = PyObject_GetAttrString((PyObject *)deque, "__dict__"); + if (dict == NULL) + PyErr_Clear(); + aslist = PySequence_List((PyObject *)deque); + if (aslist == NULL) { + Py_XDECREF(dict); + return NULL; + } + if (dict == NULL) { + if (deque->maxlen == -1) + result = Py_BuildValue("O(O)", Py_TYPE(deque), aslist); + else + result = Py_BuildValue("O(On)", Py_TYPE(deque), aslist, deque->maxlen); + } else { + if (deque->maxlen == -1) + result = Py_BuildValue("O(OO)O", Py_TYPE(deque), aslist, Py_None, dict); + else + result = Py_BuildValue("O(On)O", Py_TYPE(deque), aslist, deque->maxlen, dict); + } + Py_XDECREF(dict); + Py_DECREF(aslist); + return result; } PyDoc_STRVAR(reduce_doc, "Return state information for pickling."); @@ -712,166 +712,166 @@ static PyObject * deque_repr(PyObject *deque) { - PyObject *aslist, *result; - int i; + PyObject *aslist, *result; + int i; + + i = Py_ReprEnter(deque); + if (i != 0) { + if (i < 0) + return NULL; + return PyUnicode_FromString("[...]"); + } + + aslist = PySequence_List(deque); + if (aslist == NULL) { + Py_ReprLeave(deque); + return NULL; + } + if (((dequeobject *)deque)->maxlen != -1) - i = Py_ReprEnter(deque); - if (i != 0) { - if (i < 0) - return NULL; - return PyUnicode_FromString("[...]"); - } - - aslist = PySequence_List(deque); - if (aslist == NULL) { - Py_ReprLeave(deque); - return NULL; - } - if (((dequeobject *)deque)->maxlen != -1) - - result = PyUnicode_FromFormat("deque(%R, maxlen=%zd)", - aslist, ((dequeobject *)deque)->maxlen); - else - result = PyUnicode_FromFormat("deque(%R)", aslist); - Py_DECREF(aslist); - Py_ReprLeave(deque); - return result; + result = PyUnicode_FromFormat("deque(%R, maxlen=%zd)", + aslist, ((dequeobject *)deque)->maxlen); + else + result = PyUnicode_FromFormat("deque(%R)", aslist); + Py_DECREF(aslist); + Py_ReprLeave(deque); + return result; } static PyObject * deque_richcompare(PyObject *v, PyObject *w, int op) { - PyObject *it1=NULL, *it2=NULL, *x, *y; - Py_ssize_t vs, ws; - int b, cmp=-1; - - if (!PyObject_TypeCheck(v, &deque_type) || - !PyObject_TypeCheck(w, &deque_type)) { - Py_INCREF(Py_NotImplemented); - return Py_NotImplemented; - } - - /* Shortcuts */ - vs = ((dequeobject *)v)->len; - ws = ((dequeobject *)w)->len; - if (op == Py_EQ) { - if (v == w) - Py_RETURN_TRUE; - if (vs != ws) - Py_RETURN_FALSE; - } - if (op == Py_NE) { - if (v == w) - Py_RETURN_FALSE; - if (vs != ws) - Py_RETURN_TRUE; - } - - /* Search for the first index where items are different */ - it1 = PyObject_GetIter(v); - if (it1 == NULL) - goto done; - it2 = PyObject_GetIter(w); - if (it2 == NULL) - goto done; - for (;;) { - x = PyIter_Next(it1); - if (x == NULL && PyErr_Occurred()) - goto done; - y = PyIter_Next(it2); - if (x == NULL || y == NULL) - break; - b = PyObject_RichCompareBool(x, y, Py_EQ); - if (b == 0) { - cmp = PyObject_RichCompareBool(x, y, op); - Py_DECREF(x); - Py_DECREF(y); - goto done; - } - Py_DECREF(x); - Py_DECREF(y); - if (b == -1) - goto done; - } - /* We reached the end of one deque or both */ - Py_XDECREF(x); - Py_XDECREF(y); - if (PyErr_Occurred()) - goto done; - switch (op) { - case Py_LT: cmp = y != NULL; break; /* if w was longer */ - case Py_LE: cmp = x == NULL; break; /* if v was not longer */ - case Py_EQ: cmp = x == y; break; /* if we reached the end of both */ - case Py_NE: cmp = x != y; break; /* if one deque continues */ - case Py_GT: cmp = x != NULL; break; /* if v was longer */ - case Py_GE: cmp = y == NULL; break; /* if w was not longer */ - } + PyObject *it1=NULL, *it2=NULL, *x, *y; + Py_ssize_t vs, ws; + int b, cmp=-1; + + if (!PyObject_TypeCheck(v, &deque_type) || + !PyObject_TypeCheck(w, &deque_type)) { + Py_INCREF(Py_NotImplemented); + return Py_NotImplemented; + } + + /* Shortcuts */ + vs = ((dequeobject *)v)->len; + ws = ((dequeobject *)w)->len; + if (op == Py_EQ) { + if (v == w) + Py_RETURN_TRUE; + if (vs != ws) + Py_RETURN_FALSE; + } + if (op == Py_NE) { + if (v == w) + Py_RETURN_FALSE; + if (vs != ws) + Py_RETURN_TRUE; + } + + /* Search for the first index where items are different */ + it1 = PyObject_GetIter(v); + if (it1 == NULL) + goto done; + it2 = PyObject_GetIter(w); + if (it2 == NULL) + goto done; + for (;;) { + x = PyIter_Next(it1); + if (x == NULL && PyErr_Occurred()) + goto done; + y = PyIter_Next(it2); + if (x == NULL || y == NULL) + break; + b = PyObject_RichCompareBool(x, y, Py_EQ); + if (b == 0) { + cmp = PyObject_RichCompareBool(x, y, op); + Py_DECREF(x); + Py_DECREF(y); + goto done; + } + Py_DECREF(x); + Py_DECREF(y); + if (b == -1) + goto done; + } + /* We reached the end of one deque or both */ + Py_XDECREF(x); + Py_XDECREF(y); + if (PyErr_Occurred()) + goto done; + switch (op) { + case Py_LT: cmp = y != NULL; break; /* if w was longer */ + case Py_LE: cmp = x == NULL; break; /* if v was not longer */ + case Py_EQ: cmp = x == y; break; /* if we reached the end of both */ + case Py_NE: cmp = x != y; break; /* if one deque continues */ + case Py_GT: cmp = x != NULL; break; /* if v was longer */ + case Py_GE: cmp = y == NULL; break; /* if w was not longer */ + } done: - Py_XDECREF(it1); - Py_XDECREF(it2); - if (cmp == 1) - Py_RETURN_TRUE; - if (cmp == 0) - Py_RETURN_FALSE; - return NULL; + Py_XDECREF(it1); + Py_XDECREF(it2); + if (cmp == 1) + Py_RETURN_TRUE; + if (cmp == 0) + Py_RETURN_FALSE; + return NULL; } static int deque_init(dequeobject *deque, PyObject *args, PyObject *kwdargs) { - PyObject *iterable = NULL; - PyObject *maxlenobj = NULL; - Py_ssize_t maxlen = -1; - char *kwlist[] = {"iterable", "maxlen", 0}; - - if (!PyArg_ParseTupleAndKeywords(args, kwdargs, "|OO:deque", kwlist, &iterable, &maxlenobj)) - return -1; - if (maxlenobj != NULL && maxlenobj != Py_None) { - maxlen = PyLong_AsSsize_t(maxlenobj); - if (maxlen == -1 && PyErr_Occurred()) - return -1; - if (maxlen < 0) { - PyErr_SetString(PyExc_ValueError, "maxlen must be non-negative"); - return -1; - } - } - deque->maxlen = maxlen; - deque_clear(deque); - if (iterable != NULL) { - PyObject *rv = deque_extend(deque, iterable); - if (rv == NULL) - return -1; - Py_DECREF(rv); - } - return 0; + PyObject *iterable = NULL; + PyObject *maxlenobj = NULL; + Py_ssize_t maxlen = -1; + char *kwlist[] = {"iterable", "maxlen", 0}; + + if (!PyArg_ParseTupleAndKeywords(args, kwdargs, "|OO:deque", kwlist, &iterable, &maxlenobj)) + return -1; + if (maxlenobj != NULL && maxlenobj != Py_None) { + maxlen = PyLong_AsSsize_t(maxlenobj); + if (maxlen == -1 && PyErr_Occurred()) + return -1; + if (maxlen < 0) { + PyErr_SetString(PyExc_ValueError, "maxlen must be non-negative"); + return -1; + } + } + deque->maxlen = maxlen; + deque_clear(deque); + if (iterable != NULL) { + PyObject *rv = deque_extend(deque, iterable); + if (rv == NULL) + return -1; + Py_DECREF(rv); + } + return 0; } static PyObject * deque_get_maxlen(dequeobject *deque) { - if (deque->maxlen == -1) - Py_RETURN_NONE; - return PyLong_FromSsize_t(deque->maxlen); + if (deque->maxlen == -1) + Py_RETURN_NONE; + return PyLong_FromSsize_t(deque->maxlen); } static PyGetSetDef deque_getset[] = { - {"maxlen", (getter)deque_get_maxlen, (setter)NULL, - "maximum size of a deque or None if unbounded"}, - {0} + {"maxlen", (getter)deque_get_maxlen, (setter)NULL, + "maximum size of a deque or None if unbounded"}, + {0} }; static PySequenceMethods deque_as_sequence = { - (lenfunc)deque_len, /* sq_length */ - 0, /* sq_concat */ - 0, /* sq_repeat */ - (ssizeargfunc)deque_item, /* sq_item */ - 0, /* sq_slice */ - (ssizeobjargproc)deque_ass_item, /* sq_ass_item */ - 0, /* sq_ass_slice */ - 0, /* sq_contains */ - (binaryfunc)deque_inplace_concat, /* sq_inplace_concat */ - 0, /* sq_inplace_repeat */ + (lenfunc)deque_len, /* sq_length */ + 0, /* sq_concat */ + 0, /* sq_repeat */ + (ssizeargfunc)deque_item, /* sq_item */ + 0, /* sq_slice */ + (ssizeobjargproc)deque_ass_item, /* sq_ass_item */ + 0, /* sq_ass_slice */ + 0, /* sq_contains */ + (binaryfunc)deque_inplace_concat, /* sq_inplace_concat */ + 0, /* sq_inplace_repeat */ }; @@ -880,34 +880,34 @@ static PyObject *deque_iter(dequeobject *deque); static PyObject *deque_reviter(dequeobject *deque); PyDoc_STRVAR(reversed_doc, - "D.__reversed__() -- return a reverse iterator over the deque"); + "D.__reversed__() -- return a reverse iterator over the deque"); static PyMethodDef deque_methods[] = { - {"append", (PyCFunction)deque_append, - METH_O, append_doc}, - {"appendleft", (PyCFunction)deque_appendleft, - METH_O, appendleft_doc}, - {"clear", (PyCFunction)deque_clearmethod, - METH_NOARGS, clear_doc}, - {"__copy__", (PyCFunction)deque_copy, - METH_NOARGS, copy_doc}, - {"extend", (PyCFunction)deque_extend, - METH_O, extend_doc}, - {"extendleft", (PyCFunction)deque_extendleft, - METH_O, extendleft_doc}, - {"pop", (PyCFunction)deque_pop, - METH_NOARGS, pop_doc}, - {"popleft", (PyCFunction)deque_popleft, - METH_NOARGS, popleft_doc}, - {"__reduce__", (PyCFunction)deque_reduce, - METH_NOARGS, reduce_doc}, - {"remove", (PyCFunction)deque_remove, - METH_O, remove_doc}, - {"__reversed__", (PyCFunction)deque_reviter, - METH_NOARGS, reversed_doc}, - {"rotate", (PyCFunction)deque_rotate, - METH_VARARGS, rotate_doc}, - {NULL, NULL} /* sentinel */ + {"append", (PyCFunction)deque_append, + METH_O, append_doc}, + {"appendleft", (PyCFunction)deque_appendleft, + METH_O, appendleft_doc}, + {"clear", (PyCFunction)deque_clearmethod, + METH_NOARGS, clear_doc}, + {"__copy__", (PyCFunction)deque_copy, + METH_NOARGS, copy_doc}, + {"extend", (PyCFunction)deque_extend, + METH_O, extend_doc}, + {"extendleft", (PyCFunction)deque_extendleft, + METH_O, extendleft_doc}, + {"pop", (PyCFunction)deque_pop, + METH_NOARGS, pop_doc}, + {"popleft", (PyCFunction)deque_popleft, + METH_NOARGS, popleft_doc}, + {"__reduce__", (PyCFunction)deque_reduce, + METH_NOARGS, reduce_doc}, + {"remove", (PyCFunction)deque_remove, + METH_O, remove_doc}, + {"__reversed__", (PyCFunction)deque_reviter, + METH_NOARGS, reversed_doc}, + {"rotate", (PyCFunction)deque_rotate, + METH_VARARGS, rotate_doc}, + {NULL, NULL} /* sentinel */ }; PyDoc_STRVAR(deque_doc, @@ -916,58 +916,58 @@ Build an ordered collection accessible from endpoints only."); static PyTypeObject deque_type = { - PyVarObject_HEAD_INIT(NULL, 0) - "collections.deque", /* tp_name */ - sizeof(dequeobject), /* tp_basicsize */ - 0, /* tp_itemsize */ - /* methods */ - (destructor)deque_dealloc, /* tp_dealloc */ - 0, /* tp_print */ - 0, /* tp_getattr */ - 0, /* tp_setattr */ - 0, /* tp_reserved */ - deque_repr, /* tp_repr */ - 0, /* tp_as_number */ - &deque_as_sequence, /* tp_as_sequence */ - 0, /* tp_as_mapping */ - (hashfunc)PyObject_HashNotImplemented, /* tp_hash */ - 0, /* tp_call */ - 0, /* tp_str */ - PyObject_GenericGetAttr, /* tp_getattro */ - 0, /* tp_setattro */ - 0, /* tp_as_buffer */ - Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC, - /* tp_flags */ - deque_doc, /* tp_doc */ - (traverseproc)deque_traverse, /* tp_traverse */ - (inquiry)deque_clear, /* tp_clear */ - (richcmpfunc)deque_richcompare, /* tp_richcompare */ - offsetof(dequeobject, weakreflist), /* tp_weaklistoffset*/ - (getiterfunc)deque_iter, /* tp_iter */ - 0, /* tp_iternext */ - deque_methods, /* tp_methods */ - 0, /* tp_members */ - deque_getset, /* tp_getset */ - 0, /* tp_base */ - 0, /* tp_dict */ - 0, /* tp_descr_get */ - 0, /* tp_descr_set */ - 0, /* tp_dictoffset */ - (initproc)deque_init, /* tp_init */ - PyType_GenericAlloc, /* tp_alloc */ - deque_new, /* tp_new */ - PyObject_GC_Del, /* tp_free */ + PyVarObject_HEAD_INIT(NULL, 0) + "collections.deque", /* tp_name */ + sizeof(dequeobject), /* tp_basicsize */ + 0, /* tp_itemsize */ + /* methods */ + (destructor)deque_dealloc, /* tp_dealloc */ + 0, /* tp_print */ + 0, /* tp_getattr */ + 0, /* tp_setattr */ + 0, /* tp_reserved */ + deque_repr, /* tp_repr */ + 0, /* tp_as_number */ + &deque_as_sequence, /* tp_as_sequence */ + 0, /* tp_as_mapping */ + (hashfunc)PyObject_HashNotImplemented, /* tp_hash */ + 0, /* tp_call */ + 0, /* tp_str */ + PyObject_GenericGetAttr, /* tp_getattro */ + 0, /* tp_setattro */ + 0, /* tp_as_buffer */ + Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC, + /* tp_flags */ + deque_doc, /* tp_doc */ + (traverseproc)deque_traverse, /* tp_traverse */ + (inquiry)deque_clear, /* tp_clear */ + (richcmpfunc)deque_richcompare, /* tp_richcompare */ + offsetof(dequeobject, weakreflist), /* tp_weaklistoffset*/ + (getiterfunc)deque_iter, /* tp_iter */ + 0, /* tp_iternext */ + deque_methods, /* tp_methods */ + 0, /* tp_members */ + deque_getset, /* tp_getset */ + 0, /* tp_base */ + 0, /* tp_dict */ + 0, /* tp_descr_get */ + 0, /* tp_descr_set */ + 0, /* tp_dictoffset */ + (initproc)deque_init, /* tp_init */ + PyType_GenericAlloc, /* tp_alloc */ + deque_new, /* tp_new */ + PyObject_GC_Del, /* tp_free */ }; /*********************** Deque Iterator **************************/ typedef struct { - PyObject_HEAD - Py_ssize_t index; - block *b; - dequeobject *deque; - long state; /* state when the iterator is created */ - Py_ssize_t counter; /* number of items remaining for iteration */ + PyObject_HEAD + Py_ssize_t index; + block *b; + dequeobject *deque; + long state; /* state when the iterator is created */ + Py_ssize_t counter; /* number of items remaining for iteration */ } dequeiterobject; static PyTypeObject dequeiter_type; @@ -975,107 +975,107 @@ static PyObject * deque_iter(dequeobject *deque) { - dequeiterobject *it; + dequeiterobject *it; - it = PyObject_GC_New(dequeiterobject, &dequeiter_type); - if (it == NULL) - return NULL; - it->b = deque->leftblock; - it->index = deque->leftindex; - Py_INCREF(deque); - it->deque = deque; - it->state = deque->state; - it->counter = deque->len; - PyObject_GC_Track(it); - return (PyObject *)it; + it = PyObject_GC_New(dequeiterobject, &dequeiter_type); + if (it == NULL) + return NULL; + it->b = deque->leftblock; + it->index = deque->leftindex; + Py_INCREF(deque); + it->deque = deque; + it->state = deque->state; + it->counter = deque->len; + PyObject_GC_Track(it); + return (PyObject *)it; } static int dequeiter_traverse(dequeiterobject *dio, visitproc visit, void *arg) { - Py_VISIT(dio->deque); - return 0; + Py_VISIT(dio->deque); + return 0; } static void dequeiter_dealloc(dequeiterobject *dio) { - Py_XDECREF(dio->deque); - PyObject_GC_Del(dio); + Py_XDECREF(dio->deque); + PyObject_GC_Del(dio); } static PyObject * dequeiter_next(dequeiterobject *it) { - PyObject *item; + PyObject *item; - if (it->deque->state != it->state) { - it->counter = 0; - PyErr_SetString(PyExc_RuntimeError, - "deque mutated during iteration"); - return NULL; - } - if (it->counter == 0) - return NULL; - assert (!(it->b == it->deque->rightblock && - it->index > it->deque->rightindex)); - - item = it->b->data[it->index]; - it->index++; - it->counter--; - if (it->index == BLOCKLEN && it->counter > 0) { - assert (it->b->rightlink != NULL); - it->b = it->b->rightlink; - it->index = 0; - } - Py_INCREF(item); - return item; + if (it->deque->state != it->state) { + it->counter = 0; + PyErr_SetString(PyExc_RuntimeError, + "deque mutated during iteration"); + return NULL; + } + if (it->counter == 0) + return NULL; + assert (!(it->b == it->deque->rightblock && + it->index > it->deque->rightindex)); + + item = it->b->data[it->index]; + it->index++; + it->counter--; + if (it->index == BLOCKLEN && it->counter > 0) { + assert (it->b->rightlink != NULL); + it->b = it->b->rightlink; + it->index = 0; + } + Py_INCREF(item); + return item; } static PyObject * dequeiter_len(dequeiterobject *it) { - return PyLong_FromLong(it->counter); + return PyLong_FromLong(it->counter); } PyDoc_STRVAR(length_hint_doc, "Private method returning an estimate of len(list(it))."); static PyMethodDef dequeiter_methods[] = { - {"__length_hint__", (PyCFunction)dequeiter_len, METH_NOARGS, length_hint_doc}, - {NULL, NULL} /* sentinel */ + {"__length_hint__", (PyCFunction)dequeiter_len, METH_NOARGS, length_hint_doc}, + {NULL, NULL} /* sentinel */ }; static PyTypeObject dequeiter_type = { - PyVarObject_HEAD_INIT(NULL, 0) - "deque_iterator", /* tp_name */ - sizeof(dequeiterobject), /* tp_basicsize */ - 0, /* tp_itemsize */ - /* methods */ - (destructor)dequeiter_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)dequeiter_traverse, /* tp_traverse */ - 0, /* tp_clear */ - 0, /* tp_richcompare */ - 0, /* tp_weaklistoffset */ - PyObject_SelfIter, /* tp_iter */ - (iternextfunc)dequeiter_next, /* tp_iternext */ - dequeiter_methods, /* tp_methods */ - 0, + PyVarObject_HEAD_INIT(NULL, 0) + "deque_iterator", /* tp_name */ + sizeof(dequeiterobject), /* tp_basicsize */ + 0, /* tp_itemsize */ + /* methods */ + (destructor)dequeiter_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)dequeiter_traverse, /* tp_traverse */ + 0, /* tp_clear */ + 0, /* tp_richcompare */ + 0, /* tp_weaklistoffset */ + PyObject_SelfIter, /* tp_iter */ + (iternextfunc)dequeiter_next, /* tp_iternext */ + dequeiter_methods, /* tp_methods */ + 0, }; /*********************** Deque Reverse Iterator **************************/ @@ -1085,87 +1085,87 @@ static PyObject * deque_reviter(dequeobject *deque) { - dequeiterobject *it; + dequeiterobject *it; - it = PyObject_GC_New(dequeiterobject, &dequereviter_type); - if (it == NULL) - return NULL; - it->b = deque->rightblock; - it->index = deque->rightindex; - Py_INCREF(deque); - it->deque = deque; - it->state = deque->state; - it->counter = deque->len; - PyObject_GC_Track(it); - return (PyObject *)it; + it = PyObject_GC_New(dequeiterobject, &dequereviter_type); + if (it == NULL) + return NULL; + it->b = deque->rightblock; + it->index = deque->rightindex; + Py_INCREF(deque); + it->deque = deque; + it->state = deque->state; + it->counter = deque->len; + PyObject_GC_Track(it); + return (PyObject *)it; } static PyObject * dequereviter_next(dequeiterobject *it) { - PyObject *item; - if (it->counter == 0) - return NULL; - - if (it->deque->state != it->state) { - it->counter = 0; - PyErr_SetString(PyExc_RuntimeError, - "deque mutated during iteration"); - return NULL; - } - assert (!(it->b == it->deque->leftblock && - it->index < it->deque->leftindex)); - - item = it->b->data[it->index]; - it->index--; - it->counter--; - if (it->index == -1 && it->counter > 0) { - assert (it->b->leftlink != NULL); - it->b = it->b->leftlink; - it->index = BLOCKLEN - 1; - } - Py_INCREF(item); - return item; + PyObject *item; + if (it->counter == 0) + return NULL; + + if (it->deque->state != it->state) { + it->counter = 0; + PyErr_SetString(PyExc_RuntimeError, + "deque mutated during iteration"); + return NULL; + } + assert (!(it->b == it->deque->leftblock && + it->index < it->deque->leftindex)); + + item = it->b->data[it->index]; + it->index--; + it->counter--; + if (it->index == -1 && it->counter > 0) { + assert (it->b->leftlink != NULL); + it->b = it->b->leftlink; + it->index = BLOCKLEN - 1; + } + Py_INCREF(item); + return item; } static PyTypeObject dequereviter_type = { - PyVarObject_HEAD_INIT(NULL, 0) - "deque_reverse_iterator", /* tp_name */ - sizeof(dequeiterobject), /* tp_basicsize */ - 0, /* tp_itemsize */ - /* methods */ - (destructor)dequeiter_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)dequeiter_traverse, /* tp_traverse */ - 0, /* tp_clear */ - 0, /* tp_richcompare */ - 0, /* tp_weaklistoffset */ - PyObject_SelfIter, /* tp_iter */ - (iternextfunc)dequereviter_next, /* tp_iternext */ - dequeiter_methods, /* tp_methods */ - 0, + PyVarObject_HEAD_INIT(NULL, 0) + "deque_reverse_iterator", /* tp_name */ + sizeof(dequeiterobject), /* tp_basicsize */ + 0, /* tp_itemsize */ + /* methods */ + (destructor)dequeiter_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)dequeiter_traverse, /* tp_traverse */ + 0, /* tp_clear */ + 0, /* tp_richcompare */ + 0, /* tp_weaklistoffset */ + PyObject_SelfIter, /* tp_iter */ + (iternextfunc)dequereviter_next, /* tp_iternext */ + dequeiter_methods, /* tp_methods */ + 0, }; /* defaultdict type *********************************************************/ typedef struct { - PyDictObject dict; - PyObject *default_factory; + PyDictObject dict; + PyObject *default_factory; } defdictobject; static PyTypeObject defdict_type; /* Forward */ @@ -1180,25 +1180,25 @@ static PyObject * defdict_missing(defdictobject *dd, PyObject *key) { - PyObject *factory = dd->default_factory; - PyObject *value; - if (factory == NULL || factory == Py_None) { - /* XXX Call dict.__missing__(key) */ - PyObject *tup; - tup = PyTuple_Pack(1, key); - if (!tup) return NULL; - PyErr_SetObject(PyExc_KeyError, tup); - Py_DECREF(tup); - return NULL; - } - value = PyEval_CallObject(factory, NULL); - if (value == NULL) - return value; - if (PyObject_SetItem((PyObject *)dd, key, value) < 0) { - Py_DECREF(value); - return NULL; - } - return value; + PyObject *factory = dd->default_factory; + PyObject *value; + if (factory == NULL || factory == Py_None) { + /* XXX Call dict.__missing__(key) */ + PyObject *tup; + tup = PyTuple_Pack(1, key); + if (!tup) return NULL; + PyErr_SetObject(PyExc_KeyError, tup); + Py_DECREF(tup); + return NULL; + } + value = PyEval_CallObject(factory, NULL); + if (value == NULL) + return value; + if (PyObject_SetItem((PyObject *)dd, key, value) < 0) { + Py_DECREF(value); + return NULL; + } + return value; } PyDoc_STRVAR(defdict_copy_doc, "D.copy() -> a shallow copy of D."); @@ -1206,175 +1206,175 @@ static PyObject * defdict_copy(defdictobject *dd) { - /* This calls the object's class. That only works for subclasses - whose class constructor has the same signature. Subclasses that - define a different constructor signature must override copy(). - */ - - if (dd->default_factory == NULL) - return PyObject_CallFunctionObjArgs((PyObject*)Py_TYPE(dd), Py_None, dd, NULL); - return PyObject_CallFunctionObjArgs((PyObject*)Py_TYPE(dd), - dd->default_factory, dd, NULL); + /* This calls the object's class. That only works for subclasses + whose class constructor has the same signature. Subclasses that + define a different constructor signature must override copy(). + */ + + if (dd->default_factory == NULL) + return PyObject_CallFunctionObjArgs((PyObject*)Py_TYPE(dd), Py_None, dd, NULL); + return PyObject_CallFunctionObjArgs((PyObject*)Py_TYPE(dd), + dd->default_factory, dd, NULL); } static PyObject * defdict_reduce(defdictobject *dd) { - /* __reduce__ must return a 5-tuple as follows: + /* __reduce__ must return a 5-tuple as follows: - - factory function - - tuple of args for the factory function - - additional state (here None) - - sequence iterator (here None) - - dictionary iterator (yielding successive (key, value) pairs - - This API is used by pickle.py and copy.py. - - For this to be useful with pickle.py, the default_factory - must be picklable; e.g., None, a built-in, or a global - function in a module or package. - - Both shallow and deep copying are supported, but for deep - copying, the default_factory must be deep-copyable; e.g. None, - or a built-in (functions are not copyable at this time). - - This only works for subclasses as long as their constructor - signature is compatible; the first argument must be the - optional default_factory, defaulting to None. - */ - PyObject *args; - PyObject *items; - PyObject *iter; - PyObject *result; - if (dd->default_factory == NULL || dd->default_factory == Py_None) - args = PyTuple_New(0); - else - args = PyTuple_Pack(1, dd->default_factory); - if (args == NULL) - return NULL; - items = PyObject_CallMethod((PyObject *)dd, "items", "()"); - if (items == NULL) { - Py_DECREF(args); - return NULL; - } - iter = PyObject_GetIter(items); - if (iter == NULL) { - Py_DECREF(items); - Py_DECREF(args); - return NULL; - } - result = PyTuple_Pack(5, Py_TYPE(dd), args, - Py_None, Py_None, iter); - Py_DECREF(iter); - Py_DECREF(items); - Py_DECREF(args); - return result; + - factory function + - tuple of args for the factory function + - additional state (here None) + - sequence iterator (here None) + - dictionary iterator (yielding successive (key, value) pairs + + This API is used by pickle.py and copy.py. + + For this to be useful with pickle.py, the default_factory + must be picklable; e.g., None, a built-in, or a global + function in a module or package. + + Both shallow and deep copying are supported, but for deep + copying, the default_factory must be deep-copyable; e.g. None, + or a built-in (functions are not copyable at this time). + + This only works for subclasses as long as their constructor + signature is compatible; the first argument must be the + optional default_factory, defaulting to None. + */ + PyObject *args; + PyObject *items; + PyObject *iter; + PyObject *result; + if (dd->default_factory == NULL || dd->default_factory == Py_None) + args = PyTuple_New(0); + else + args = PyTuple_Pack(1, dd->default_factory); + if (args == NULL) + return NULL; + items = PyObject_CallMethod((PyObject *)dd, "items", "()"); + if (items == NULL) { + Py_DECREF(args); + return NULL; + } + iter = PyObject_GetIter(items); + if (iter == NULL) { + Py_DECREF(items); + Py_DECREF(args); + return NULL; + } + result = PyTuple_Pack(5, Py_TYPE(dd), args, + Py_None, Py_None, iter); + Py_DECREF(iter); + Py_DECREF(items); + Py_DECREF(args); + return result; } static PyMethodDef defdict_methods[] = { - {"__missing__", (PyCFunction)defdict_missing, METH_O, - defdict_missing_doc}, - {"copy", (PyCFunction)defdict_copy, METH_NOARGS, - defdict_copy_doc}, - {"__copy__", (PyCFunction)defdict_copy, METH_NOARGS, - defdict_copy_doc}, - {"__reduce__", (PyCFunction)defdict_reduce, METH_NOARGS, - reduce_doc}, - {NULL} + {"__missing__", (PyCFunction)defdict_missing, METH_O, + defdict_missing_doc}, + {"copy", (PyCFunction)defdict_copy, METH_NOARGS, + defdict_copy_doc}, + {"__copy__", (PyCFunction)defdict_copy, METH_NOARGS, + defdict_copy_doc}, + {"__reduce__", (PyCFunction)defdict_reduce, METH_NOARGS, + reduce_doc}, + {NULL} }; static PyMemberDef defdict_members[] = { - {"default_factory", T_OBJECT, - offsetof(defdictobject, default_factory), 0, - PyDoc_STR("Factory for default value called by __missing__().")}, - {NULL} + {"default_factory", T_OBJECT, + offsetof(defdictobject, default_factory), 0, + PyDoc_STR("Factory for default value called by __missing__().")}, + {NULL} }; static void defdict_dealloc(defdictobject *dd) { - Py_CLEAR(dd->default_factory); - PyDict_Type.tp_dealloc((PyObject *)dd); + Py_CLEAR(dd->default_factory); + PyDict_Type.tp_dealloc((PyObject *)dd); } static PyObject * defdict_repr(defdictobject *dd) { - PyObject *baserepr; - PyObject *defrepr; - PyObject *result; - baserepr = PyDict_Type.tp_repr((PyObject *)dd); - if (baserepr == NULL) - return NULL; - if (dd->default_factory == NULL) - defrepr = PyUnicode_FromString("None"); - else - { - int status = Py_ReprEnter(dd->default_factory); - if (status != 0) { - if (status < 0) - return NULL; - defrepr = PyUnicode_FromString("..."); - } - else - defrepr = PyObject_Repr(dd->default_factory); - Py_ReprLeave(dd->default_factory); - } - if (defrepr == NULL) { - Py_DECREF(baserepr); - return NULL; - } - result = PyUnicode_FromFormat("defaultdict(%U, %U)", - defrepr, baserepr); - Py_DECREF(defrepr); - Py_DECREF(baserepr); - return result; + PyObject *baserepr; + PyObject *defrepr; + PyObject *result; + baserepr = PyDict_Type.tp_repr((PyObject *)dd); + if (baserepr == NULL) + return NULL; + if (dd->default_factory == NULL) + defrepr = PyUnicode_FromString("None"); + else + { + int status = Py_ReprEnter(dd->default_factory); + if (status != 0) { + if (status < 0) + return NULL; + defrepr = PyUnicode_FromString("..."); + } + else + defrepr = PyObject_Repr(dd->default_factory); + Py_ReprLeave(dd->default_factory); + } + if (defrepr == NULL) { + Py_DECREF(baserepr); + return NULL; + } + result = PyUnicode_FromFormat("defaultdict(%U, %U)", + defrepr, baserepr); + Py_DECREF(defrepr); + Py_DECREF(baserepr); + return result; } static int defdict_traverse(PyObject *self, visitproc visit, void *arg) { - Py_VISIT(((defdictobject *)self)->default_factory); - return PyDict_Type.tp_traverse(self, visit, arg); + Py_VISIT(((defdictobject *)self)->default_factory); + return PyDict_Type.tp_traverse(self, visit, arg); } static int defdict_tp_clear(defdictobject *dd) { - Py_CLEAR(dd->default_factory); - return PyDict_Type.tp_clear((PyObject *)dd); + Py_CLEAR(dd->default_factory); + return PyDict_Type.tp_clear((PyObject *)dd); } static int defdict_init(PyObject *self, PyObject *args, PyObject *kwds) { - defdictobject *dd = (defdictobject *)self; - PyObject *olddefault = dd->default_factory; - PyObject *newdefault = NULL; - PyObject *newargs; - int result; - if (args == NULL || !PyTuple_Check(args)) - newargs = PyTuple_New(0); - else { - Py_ssize_t n = PyTuple_GET_SIZE(args); - if (n > 0) { - newdefault = PyTuple_GET_ITEM(args, 0); - if (!PyCallable_Check(newdefault) && newdefault != Py_None) { - PyErr_SetString(PyExc_TypeError, - "first argument must be callable"); - return -1; - } - } - newargs = PySequence_GetSlice(args, 1, n); - } - if (newargs == NULL) - return -1; - Py_XINCREF(newdefault); - dd->default_factory = newdefault; - result = PyDict_Type.tp_init(self, newargs, kwds); - Py_DECREF(newargs); - Py_XDECREF(olddefault); - return result; + defdictobject *dd = (defdictobject *)self; + PyObject *olddefault = dd->default_factory; + PyObject *newdefault = NULL; + PyObject *newargs; + int result; + if (args == NULL || !PyTuple_Check(args)) + newargs = PyTuple_New(0); + else { + Py_ssize_t n = PyTuple_GET_SIZE(args); + if (n > 0) { + newdefault = PyTuple_GET_ITEM(args, 0); + if (!PyCallable_Check(newdefault) && newdefault != Py_None) { + PyErr_SetString(PyExc_TypeError, + "first argument must be callable"); + return -1; + } + } + newargs = PySequence_GetSlice(args, 1, n); + } + if (newargs == NULL) + return -1; + Py_XINCREF(newdefault); + dd->default_factory = newdefault; + result = PyDict_Type.tp_init(self, newargs, kwds); + Py_DECREF(newargs); + Py_XDECREF(olddefault); + return result; } PyDoc_STRVAR(defdict_doc, @@ -1389,47 +1389,47 @@ #define DEFERRED_ADDRESS(ADDR) 0 static PyTypeObject defdict_type = { - PyVarObject_HEAD_INIT(DEFERRED_ADDRESS(&PyType_Type), 0) - "collections.defaultdict", /* tp_name */ - sizeof(defdictobject), /* tp_basicsize */ - 0, /* tp_itemsize */ - /* methods */ - (destructor)defdict_dealloc, /* tp_dealloc */ - 0, /* tp_print */ - 0, /* tp_getattr */ - 0, /* tp_setattr */ - 0, /* tp_reserved */ - (reprfunc)defdict_repr, /* 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_BASETYPE | Py_TPFLAGS_HAVE_GC, - /* tp_flags */ - defdict_doc, /* tp_doc */ - defdict_traverse, /* tp_traverse */ - (inquiry)defdict_tp_clear, /* tp_clear */ - 0, /* tp_richcompare */ - 0, /* tp_weaklistoffset*/ - 0, /* tp_iter */ - 0, /* tp_iternext */ - defdict_methods, /* tp_methods */ - defdict_members, /* tp_members */ - 0, /* tp_getset */ - DEFERRED_ADDRESS(&PyDict_Type), /* tp_base */ - 0, /* tp_dict */ - 0, /* tp_descr_get */ - 0, /* tp_descr_set */ - 0, /* tp_dictoffset */ - defdict_init, /* tp_init */ - PyType_GenericAlloc, /* tp_alloc */ - 0, /* tp_new */ - PyObject_GC_Del, /* tp_free */ + PyVarObject_HEAD_INIT(DEFERRED_ADDRESS(&PyType_Type), 0) + "collections.defaultdict", /* tp_name */ + sizeof(defdictobject), /* tp_basicsize */ + 0, /* tp_itemsize */ + /* methods */ + (destructor)defdict_dealloc, /* tp_dealloc */ + 0, /* tp_print */ + 0, /* tp_getattr */ + 0, /* tp_setattr */ + 0, /* tp_reserved */ + (reprfunc)defdict_repr, /* 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_BASETYPE | Py_TPFLAGS_HAVE_GC, + /* tp_flags */ + defdict_doc, /* tp_doc */ + defdict_traverse, /* tp_traverse */ + (inquiry)defdict_tp_clear, /* tp_clear */ + 0, /* tp_richcompare */ + 0, /* tp_weaklistoffset*/ + 0, /* tp_iter */ + 0, /* tp_iternext */ + defdict_methods, /* tp_methods */ + defdict_members, /* tp_members */ + 0, /* tp_getset */ + DEFERRED_ADDRESS(&PyDict_Type), /* tp_base */ + 0, /* tp_dict */ + 0, /* tp_descr_get */ + 0, /* tp_descr_set */ + 0, /* tp_dictoffset */ + defdict_init, /* tp_init */ + PyType_GenericAlloc, /* tp_alloc */ + 0, /* tp_new */ + PyObject_GC_Del, /* tp_free */ }; /* module level code ********************************************************/ @@ -1442,42 +1442,42 @@ static struct PyModuleDef _collectionsmodule = { - PyModuleDef_HEAD_INIT, - "_collections", - module_doc, - -1, - NULL, - NULL, - NULL, - NULL, - NULL + PyModuleDef_HEAD_INIT, + "_collections", + module_doc, + -1, + NULL, + NULL, + NULL, + NULL, + NULL }; PyMODINIT_FUNC PyInit__collections(void) { - PyObject *m; + PyObject *m; - m = PyModule_Create(&_collectionsmodule); - if (m == NULL) - return NULL; - - if (PyType_Ready(&deque_type) < 0) - return NULL; - Py_INCREF(&deque_type); - PyModule_AddObject(m, "deque", (PyObject *)&deque_type); - - defdict_type.tp_base = &PyDict_Type; - if (PyType_Ready(&defdict_type) < 0) - return NULL; - Py_INCREF(&defdict_type); - PyModule_AddObject(m, "defaultdict", (PyObject *)&defdict_type); + m = PyModule_Create(&_collectionsmodule); + if (m == NULL) + return NULL; + + if (PyType_Ready(&deque_type) < 0) + return NULL; + Py_INCREF(&deque_type); + PyModule_AddObject(m, "deque", (PyObject *)&deque_type); + + defdict_type.tp_base = &PyDict_Type; + if (PyType_Ready(&defdict_type) < 0) + return NULL; + Py_INCREF(&defdict_type); + PyModule_AddObject(m, "defaultdict", (PyObject *)&defdict_type); - if (PyType_Ready(&dequeiter_type) < 0) - return NULL; + if (PyType_Ready(&dequeiter_type) < 0) + return NULL; - if (PyType_Ready(&dequereviter_type) < 0) - return NULL; + if (PyType_Ready(&dequereviter_type) < 0) + return NULL; - return m; + return m; } Modified: python/branches/release31-maint/Modules/_csv.c ============================================================================== --- python/branches/release31-maint/Modules/_csv.c (original) +++ python/branches/release31-maint/Modules/_csv.c Sun May 9 18:14:21 2010 @@ -18,65 +18,65 @@ #include "structmember.h" #define IS_BASESTRING(o) \ - PyUnicode_Check(o) + PyUnicode_Check(o) -static PyObject *error_obj; /* CSV exception */ +static PyObject *error_obj; /* CSV exception */ static PyObject *dialects; /* Dialect registry */ -static long field_limit = 128 * 1024; /* max parsed field size */ +static long field_limit = 128 * 1024; /* max parsed field size */ typedef enum { - START_RECORD, START_FIELD, ESCAPED_CHAR, IN_FIELD, - IN_QUOTED_FIELD, ESCAPE_IN_QUOTED_FIELD, QUOTE_IN_QUOTED_FIELD, - EAT_CRNL + START_RECORD, START_FIELD, ESCAPED_CHAR, IN_FIELD, + IN_QUOTED_FIELD, ESCAPE_IN_QUOTED_FIELD, QUOTE_IN_QUOTED_FIELD, + EAT_CRNL } ParserState; typedef enum { - QUOTE_MINIMAL, QUOTE_ALL, QUOTE_NONNUMERIC, QUOTE_NONE + QUOTE_MINIMAL, QUOTE_ALL, QUOTE_NONNUMERIC, QUOTE_NONE } QuoteStyle; typedef struct { - QuoteStyle style; - char *name; + QuoteStyle style; + char *name; } StyleDesc; static StyleDesc quote_styles[] = { - { QUOTE_MINIMAL, "QUOTE_MINIMAL" }, - { QUOTE_ALL, "QUOTE_ALL" }, - { QUOTE_NONNUMERIC, "QUOTE_NONNUMERIC" }, - { QUOTE_NONE, "QUOTE_NONE" }, - { 0 } + { QUOTE_MINIMAL, "QUOTE_MINIMAL" }, + { QUOTE_ALL, "QUOTE_ALL" }, + { QUOTE_NONNUMERIC, "QUOTE_NONNUMERIC" }, + { QUOTE_NONE, "QUOTE_NONE" }, + { 0 } }; typedef struct { - PyObject_HEAD + PyObject_HEAD - int doublequote; /* is " represented by ""? */ - Py_UNICODE delimiter; /* field separator */ - Py_UNICODE quotechar; /* quote character */ - Py_UNICODE escapechar; /* escape character */ - int skipinitialspace; /* ignore spaces following delimiter? */ - PyObject *lineterminator; /* string to write between records */ - int quoting; /* style of quoting to write */ + int doublequote; /* is " represented by ""? */ + Py_UNICODE delimiter; /* field separator */ + Py_UNICODE quotechar; /* quote character */ + Py_UNICODE escapechar; /* escape character */ + int skipinitialspace; /* ignore spaces following delimiter? */ + PyObject *lineterminator; /* string to write between records */ + int quoting; /* style of quoting to write */ - int strict; /* raise exception on bad CSV */ + int strict; /* raise exception on bad CSV */ } DialectObj; static PyTypeObject Dialect_Type; typedef struct { - PyObject_HEAD + PyObject_HEAD - PyObject *input_iter; /* iterate over this for input lines */ + PyObject *input_iter; /* iterate over this for input lines */ - DialectObj *dialect; /* parsing dialect */ + DialectObj *dialect; /* parsing dialect */ - PyObject *fields; /* field list for current record */ - ParserState state; /* current CSV parse state */ - Py_UNICODE *field; /* build current field in here */ - int field_size; /* size of allocated buffer */ - Py_ssize_t field_len; /* length of current field */ - int numeric_field; /* treat field as numeric */ - unsigned long line_num; /* Source-file line number */ + PyObject *fields; /* field list for current record */ + ParserState state; /* current CSV parse state */ + Py_UNICODE *field; /* build current field in here */ + int field_size; /* size of allocated buffer */ + Py_ssize_t field_len; /* length of current field */ + int numeric_field; /* treat field as numeric */ + unsigned long line_num; /* Source-file line number */ } ReaderObj; static PyTypeObject Reader_Type; @@ -84,16 +84,16 @@ #define ReaderObject_Check(v) (Py_TYPE(v) == &Reader_Type) typedef struct { - PyObject_HEAD + PyObject_HEAD - PyObject *writeline; /* write output lines to this file */ + PyObject *writeline; /* write output lines to this file */ - DialectObj *dialect; /* parsing dialect */ + DialectObj *dialect; /* parsing dialect */ - Py_UNICODE *rec; /* buffer for parser.join */ - int rec_size; /* size of allocated record */ - Py_ssize_t rec_len; /* length of record */ - int num_fields; /* number of fields in record */ + Py_UNICODE *rec; /* buffer for parser.join */ + int rec_size; /* size of allocated record */ + Py_ssize_t rec_len; /* length of record */ + int num_fields; /* number of fields in record */ } WriterObj; static PyTypeObject Writer_Type; @@ -105,375 +105,375 @@ static PyObject * get_dialect_from_registry(PyObject * name_obj) { - PyObject *dialect_obj; + PyObject *dialect_obj; - dialect_obj = PyDict_GetItem(dialects, name_obj); - if (dialect_obj == NULL) { - if (!PyErr_Occurred()) - PyErr_Format(error_obj, "unknown dialect"); - } - else - Py_INCREF(dialect_obj); - return dialect_obj; + dialect_obj = PyDict_GetItem(dialects, name_obj); + if (dialect_obj == NULL) { + if (!PyErr_Occurred()) + PyErr_Format(error_obj, "unknown dialect"); + } + else + Py_INCREF(dialect_obj); + return dialect_obj; } static PyObject * get_string(PyObject *str) { - Py_XINCREF(str); - return str; + Py_XINCREF(str); + return str; } static PyObject * get_nullchar_as_None(Py_UNICODE c) { - if (c == '\0') { - Py_INCREF(Py_None); - return Py_None; - } - else - return PyUnicode_FromUnicode((Py_UNICODE *)&c, 1); + if (c == '\0') { + Py_INCREF(Py_None); + return Py_None; + } + else + return PyUnicode_FromUnicode((Py_UNICODE *)&c, 1); } static PyObject * Dialect_get_lineterminator(DialectObj *self) { - return get_string(self->lineterminator); + return get_string(self->lineterminator); } static PyObject * Dialect_get_delimiter(DialectObj *self) { - return get_nullchar_as_None(self->delimiter); + return get_nullchar_as_None(self->delimiter); } static PyObject * Dialect_get_escapechar(DialectObj *self) { - return get_nullchar_as_None(self->escapechar); + return get_nullchar_as_None(self->escapechar); } static PyObject * Dialect_get_quotechar(DialectObj *self) { - return get_nullchar_as_None(self->quotechar); + return get_nullchar_as_None(self->quotechar); } static PyObject * Dialect_get_quoting(DialectObj *self) { - return PyLong_FromLong(self->quoting); + return PyLong_FromLong(self->quoting); } static int _set_bool(const char *name, int *target, PyObject *src, int dflt) { - if (src == NULL) - *target = dflt; - else - *target = PyObject_IsTrue(src); - return 0; + if (src == NULL) + *target = dflt; + else + *target = PyObject_IsTrue(src); + return 0; } static int _set_int(const char *name, int *target, PyObject *src, int dflt) { - if (src == NULL) - *target = dflt; - else { - long value; - if (!PyLong_CheckExact(src)) { - PyErr_Format(PyExc_TypeError, - "\"%s\" must be an integer", name); - return -1; - } - value = PyLong_AsLong(src); - if (value == -1 && PyErr_Occurred()) - return -1; + if (src == NULL) + *target = dflt; + else { + long value; + if (!PyLong_CheckExact(src)) { + PyErr_Format(PyExc_TypeError, + "\"%s\" must be an integer", name); + return -1; + } + value = PyLong_AsLong(src); + if (value == -1 && PyErr_Occurred()) + return -1; #if SIZEOF_LONG > SIZEOF_INT - if (value > INT_MAX || value < INT_MIN) { - PyErr_Format(PyExc_ValueError, - "integer out of range for \"%s\"", name); - return -1; - } + if (value > INT_MAX || value < INT_MIN) { + PyErr_Format(PyExc_ValueError, + "integer out of range for \"%s\"", name); + return -1; + } #endif - *target = (int)value; - } - return 0; + *target = (int)value; + } + return 0; } static int _set_char(const char *name, Py_UNICODE *target, PyObject *src, Py_UNICODE dflt) { - if (src == NULL) - *target = dflt; - else { - *target = '\0'; - if (src != Py_None) { - Py_UNICODE *buf; - Py_ssize_t len; - buf = PyUnicode_AsUnicode(src); - len = PyUnicode_GetSize(src); - if (buf == NULL || len > 1) { - PyErr_Format(PyExc_TypeError, - "\"%s\" must be an 1-character string", - name); - return -1; - } - if (len > 0) - *target = buf[0]; - } - } - return 0; + if (src == NULL) + *target = dflt; + else { + *target = '\0'; + if (src != Py_None) { + Py_UNICODE *buf; + Py_ssize_t len; + buf = PyUnicode_AsUnicode(src); + len = PyUnicode_GetSize(src); + if (buf == NULL || len > 1) { + PyErr_Format(PyExc_TypeError, + "\"%s\" must be an 1-character string", + name); + return -1; + } + if (len > 0) + *target = buf[0]; + } + } + return 0; } static int _set_str(const char *name, PyObject **target, PyObject *src, const char *dflt) { - if (src == NULL) - *target = PyUnicode_DecodeASCII(dflt, strlen(dflt), NULL); - else { - if (src == Py_None) - *target = NULL; - else if (!IS_BASESTRING(src)) { - PyErr_Format(PyExc_TypeError, - "\"%s\" must be a string", name); - return -1; - } - else { - Py_XDECREF(*target); - Py_INCREF(src); - *target = src; - } - } - return 0; + if (src == NULL) + *target = PyUnicode_DecodeASCII(dflt, strlen(dflt), NULL); + else { + if (src == Py_None) + *target = NULL; + else if (!IS_BASESTRING(src)) { + PyErr_Format(PyExc_TypeError, + "\"%s\" must be a string", name); + return -1; + } + else { + Py_XDECREF(*target); + Py_INCREF(src); + *target = src; + } + } + return 0; } static int dialect_check_quoting(int quoting) { - StyleDesc *qs = quote_styles; + StyleDesc *qs = quote_styles; - for (qs = quote_styles; qs->name; qs++) { - if (qs->style == quoting) - return 0; - } - PyErr_Format(PyExc_TypeError, "bad \"quoting\" value"); - return -1; + for (qs = quote_styles; qs->name; qs++) { + if (qs->style == quoting) + return 0; + } + PyErr_Format(PyExc_TypeError, "bad \"quoting\" value"); + return -1; } #define D_OFF(x) offsetof(DialectObj, x) static struct PyMemberDef Dialect_memberlist[] = { - { "skipinitialspace", T_INT, D_OFF(skipinitialspace), READONLY }, - { "doublequote", T_INT, D_OFF(doublequote), READONLY }, - { "strict", T_INT, D_OFF(strict), READONLY }, - { NULL } + { "skipinitialspace", T_INT, D_OFF(skipinitialspace), READONLY }, + { "doublequote", T_INT, D_OFF(doublequote), READONLY }, + { "strict", T_INT, D_OFF(strict), READONLY }, + { NULL } }; static PyGetSetDef Dialect_getsetlist[] = { - { "delimiter", (getter)Dialect_get_delimiter}, - { "escapechar", (getter)Dialect_get_escapechar}, - { "lineterminator", (getter)Dialect_get_lineterminator}, - { "quotechar", (getter)Dialect_get_quotechar}, - { "quoting", (getter)Dialect_get_quoting}, - {NULL}, + { "delimiter", (getter)Dialect_get_delimiter}, + { "escapechar", (getter)Dialect_get_escapechar}, + { "lineterminator", (getter)Dialect_get_lineterminator}, + { "quotechar", (getter)Dialect_get_quotechar}, + { "quoting", (getter)Dialect_get_quoting}, + {NULL}, }; static void Dialect_dealloc(DialectObj *self) { - Py_XDECREF(self->lineterminator); - Py_TYPE(self)->tp_free((PyObject *)self); + Py_XDECREF(self->lineterminator); + Py_TYPE(self)->tp_free((PyObject *)self); } static char *dialect_kws[] = { - "dialect", - "delimiter", - "doublequote", - "escapechar", - "lineterminator", - "quotechar", - "quoting", - "skipinitialspace", - "strict", - NULL + "dialect", + "delimiter", + "doublequote", + "escapechar", + "lineterminator", + "quotechar", + "quoting", + "skipinitialspace", + "strict", + NULL }; static PyObject * dialect_new(PyTypeObject *type, PyObject *args, PyObject *kwargs) { - DialectObj *self; - PyObject *ret = NULL; - PyObject *dialect = NULL; - PyObject *delimiter = NULL; - PyObject *doublequote = NULL; - PyObject *escapechar = NULL; - PyObject *lineterminator = NULL; - PyObject *quotechar = NULL; - PyObject *quoting = NULL; - PyObject *skipinitialspace = NULL; - PyObject *strict = NULL; - - if (!PyArg_ParseTupleAndKeywords(args, kwargs, - "|OOOOOOOOO", dialect_kws, - &dialect, - &delimiter, - &doublequote, - &escapechar, - &lineterminator, - "echar, - "ing, - &skipinitialspace, - &strict)) - return NULL; - - if (dialect != NULL) { - if (IS_BASESTRING(dialect)) { - dialect = get_dialect_from_registry(dialect); - if (dialect == NULL) - return NULL; - } - else - Py_INCREF(dialect); - /* Can we reuse this instance? */ - if (PyObject_TypeCheck(dialect, &Dialect_Type) && - delimiter == 0 && - doublequote == 0 && - escapechar == 0 && - lineterminator == 0 && - quotechar == 0 && - quoting == 0 && - skipinitialspace == 0 && - strict == 0) - return dialect; - } - - self = (DialectObj *)type->tp_alloc(type, 0); - if (self == NULL) { - Py_XDECREF(dialect); - return NULL; - } - self->lineterminator = NULL; - - Py_XINCREF(delimiter); - Py_XINCREF(doublequote); - Py_XINCREF(escapechar); - Py_XINCREF(lineterminator); - Py_XINCREF(quotechar); - Py_XINCREF(quoting); - Py_XINCREF(skipinitialspace); - Py_XINCREF(strict); - if (dialect != NULL) { + DialectObj *self; + PyObject *ret = NULL; + PyObject *dialect = NULL; + PyObject *delimiter = NULL; + PyObject *doublequote = NULL; + PyObject *escapechar = NULL; + PyObject *lineterminator = NULL; + PyObject *quotechar = NULL; + PyObject *quoting = NULL; + PyObject *skipinitialspace = NULL; + PyObject *strict = NULL; + + if (!PyArg_ParseTupleAndKeywords(args, kwargs, + "|OOOOOOOOO", dialect_kws, + &dialect, + &delimiter, + &doublequote, + &escapechar, + &lineterminator, + "echar, + "ing, + &skipinitialspace, + &strict)) + return NULL; + + if (dialect != NULL) { + if (IS_BASESTRING(dialect)) { + dialect = get_dialect_from_registry(dialect); + if (dialect == NULL) + return NULL; + } + else + Py_INCREF(dialect); + /* Can we reuse this instance? */ + if (PyObject_TypeCheck(dialect, &Dialect_Type) && + delimiter == 0 && + doublequote == 0 && + escapechar == 0 && + lineterminator == 0 && + quotechar == 0 && + quoting == 0 && + skipinitialspace == 0 && + strict == 0) + return dialect; + } + + self = (DialectObj *)type->tp_alloc(type, 0); + if (self == NULL) { + Py_XDECREF(dialect); + return NULL; + } + self->lineterminator = NULL; + + Py_XINCREF(delimiter); + Py_XINCREF(doublequote); + Py_XINCREF(escapechar); + Py_XINCREF(lineterminator); + Py_XINCREF(quotechar); + Py_XINCREF(quoting); + Py_XINCREF(skipinitialspace); + Py_XINCREF(strict); + if (dialect != NULL) { #define DIALECT_GETATTR(v, n) \ - if (v == NULL) \ - v = PyObject_GetAttrString(dialect, n) - DIALECT_GETATTR(delimiter, "delimiter"); - DIALECT_GETATTR(doublequote, "doublequote"); - DIALECT_GETATTR(escapechar, "escapechar"); - DIALECT_GETATTR(lineterminator, "lineterminator"); - DIALECT_GETATTR(quotechar, "quotechar"); - DIALECT_GETATTR(quoting, "quoting"); - DIALECT_GETATTR(skipinitialspace, "skipinitialspace"); - DIALECT_GETATTR(strict, "strict"); - PyErr_Clear(); - } + if (v == NULL) \ + v = PyObject_GetAttrString(dialect, n) + DIALECT_GETATTR(delimiter, "delimiter"); + DIALECT_GETATTR(doublequote, "doublequote"); + DIALECT_GETATTR(escapechar, "escapechar"); + DIALECT_GETATTR(lineterminator, "lineterminator"); + DIALECT_GETATTR(quotechar, "quotechar"); + DIALECT_GETATTR(quoting, "quoting"); + DIALECT_GETATTR(skipinitialspace, "skipinitialspace"); + DIALECT_GETATTR(strict, "strict"); + PyErr_Clear(); + } - /* check types and convert to C values */ + /* check types and convert to C values */ #define DIASET(meth, name, target, src, dflt) \ - if (meth(name, target, src, dflt)) \ - goto err - DIASET(_set_char, "delimiter", &self->delimiter, delimiter, ','); - DIASET(_set_bool, "doublequote", &self->doublequote, doublequote, 1); - DIASET(_set_char, "escapechar", &self->escapechar, escapechar, 0); - DIASET(_set_str, "lineterminator", &self->lineterminator, lineterminator, "\r\n"); - DIASET(_set_char, "quotechar", &self->quotechar, quotechar, '"'); - DIASET(_set_int, "quoting", &self->quoting, quoting, QUOTE_MINIMAL); - DIASET(_set_bool, "skipinitialspace", &self->skipinitialspace, skipinitialspace, 0); - DIASET(_set_bool, "strict", &self->strict, strict, 0); - - /* validate options */ - if (dialect_check_quoting(self->quoting)) - goto err; - if (self->delimiter == 0) { - PyErr_SetString(PyExc_TypeError, "delimiter must be set"); - goto err; - } - if (quotechar == Py_None && quoting == NULL) - self->quoting = QUOTE_NONE; - if (self->quoting != QUOTE_NONE && self->quotechar == 0) { - PyErr_SetString(PyExc_TypeError, - "quotechar must be set if quoting enabled"); - goto err; - } - if (self->lineterminator == 0) { - PyErr_SetString(PyExc_TypeError, "lineterminator must be set"); - goto err; - } + if (meth(name, target, src, dflt)) \ + goto err + DIASET(_set_char, "delimiter", &self->delimiter, delimiter, ','); + DIASET(_set_bool, "doublequote", &self->doublequote, doublequote, 1); + DIASET(_set_char, "escapechar", &self->escapechar, escapechar, 0); + DIASET(_set_str, "lineterminator", &self->lineterminator, lineterminator, "\r\n"); + DIASET(_set_char, "quotechar", &self->quotechar, quotechar, '"'); + DIASET(_set_int, "quoting", &self->quoting, quoting, QUOTE_MINIMAL); + DIASET(_set_bool, "skipinitialspace", &self->skipinitialspace, skipinitialspace, 0); + DIASET(_set_bool, "strict", &self->strict, strict, 0); + + /* validate options */ + if (dialect_check_quoting(self->quoting)) + goto err; + if (self->delimiter == 0) { + PyErr_SetString(PyExc_TypeError, "delimiter must be set"); + goto err; + } + if (quotechar == Py_None && quoting == NULL) + self->quoting = QUOTE_NONE; + if (self->quoting != QUOTE_NONE && self->quotechar == 0) { + PyErr_SetString(PyExc_TypeError, + "quotechar must be set if quoting enabled"); + goto err; + } + if (self->lineterminator == 0) { + PyErr_SetString(PyExc_TypeError, "lineterminator must be set"); + goto err; + } - ret = (PyObject *)self; - Py_INCREF(self); + ret = (PyObject *)self; + Py_INCREF(self); err: - Py_XDECREF(self); - Py_XDECREF(dialect); - Py_XDECREF(delimiter); - Py_XDECREF(doublequote); - Py_XDECREF(escapechar); - Py_XDECREF(lineterminator); - Py_XDECREF(quotechar); - Py_XDECREF(quoting); - Py_XDECREF(skipinitialspace); - Py_XDECREF(strict); - return ret; + Py_XDECREF(self); + Py_XDECREF(dialect); + Py_XDECREF(delimiter); + Py_XDECREF(doublequote); + Py_XDECREF(escapechar); + Py_XDECREF(lineterminator); + Py_XDECREF(quotechar); + Py_XDECREF(quoting); + Py_XDECREF(skipinitialspace); + Py_XDECREF(strict); + return ret; } -PyDoc_STRVAR(Dialect_Type_doc, +PyDoc_STRVAR(Dialect_Type_doc, "CSV dialect\n" "\n" "The Dialect type records CSV parsing and generation options.\n"); static PyTypeObject Dialect_Type = { - PyVarObject_HEAD_INIT(NULL, 0) - "_csv.Dialect", /* tp_name */ - sizeof(DialectObj), /* tp_basicsize */ - 0, /* tp_itemsize */ - /* methods */ - (destructor)Dialect_dealloc, /* tp_dealloc */ - (printfunc)0, /* tp_print */ - (getattrfunc)0, /* tp_getattr */ - (setattrfunc)0, /* tp_setattr */ - 0, /* tp_reserved */ - (reprfunc)0, /* tp_repr */ - 0, /* tp_as_number */ - 0, /* tp_as_sequence */ - 0, /* tp_as_mapping */ - (hashfunc)0, /* tp_hash */ - (ternaryfunc)0, /* tp_call */ - (reprfunc)0, /* tp_str */ - 0, /* tp_getattro */ - 0, /* tp_setattro */ - 0, /* tp_as_buffer */ - Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */ - Dialect_Type_doc, /* tp_doc */ - 0, /* tp_traverse */ - 0, /* tp_clear */ - 0, /* tp_richcompare */ - 0, /* tp_weaklistoffset */ - 0, /* tp_iter */ - 0, /* tp_iternext */ - 0, /* tp_methods */ - Dialect_memberlist, /* tp_members */ - Dialect_getsetlist, /* tp_getset */ - 0, /* tp_base */ - 0, /* tp_dict */ - 0, /* tp_descr_get */ - 0, /* tp_descr_set */ - 0, /* tp_dictoffset */ - 0, /* tp_init */ - 0, /* tp_alloc */ - dialect_new, /* tp_new */ - 0, /* tp_free */ + PyVarObject_HEAD_INIT(NULL, 0) + "_csv.Dialect", /* tp_name */ + sizeof(DialectObj), /* tp_basicsize */ + 0, /* tp_itemsize */ + /* methods */ + (destructor)Dialect_dealloc, /* tp_dealloc */ + (printfunc)0, /* tp_print */ + (getattrfunc)0, /* tp_getattr */ + (setattrfunc)0, /* tp_setattr */ + 0, /* tp_reserved */ + (reprfunc)0, /* tp_repr */ + 0, /* tp_as_number */ + 0, /* tp_as_sequence */ + 0, /* tp_as_mapping */ + (hashfunc)0, /* tp_hash */ + (ternaryfunc)0, /* tp_call */ + (reprfunc)0, /* tp_str */ + 0, /* tp_getattro */ + 0, /* tp_setattro */ + 0, /* tp_as_buffer */ + Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */ + Dialect_Type_doc, /* tp_doc */ + 0, /* tp_traverse */ + 0, /* tp_clear */ + 0, /* tp_richcompare */ + 0, /* tp_weaklistoffset */ + 0, /* tp_iter */ + 0, /* tp_iternext */ + 0, /* tp_methods */ + Dialect_memberlist, /* tp_members */ + Dialect_getsetlist, /* tp_getset */ + 0, /* tp_base */ + 0, /* tp_dict */ + 0, /* tp_descr_get */ + 0, /* tp_descr_set */ + 0, /* tp_dictoffset */ + 0, /* tp_init */ + 0, /* tp_alloc */ + dialect_new, /* tp_new */ + 0, /* tp_free */ }; /* @@ -483,15 +483,15 @@ static PyObject * _call_dialect(PyObject *dialect_inst, PyObject *kwargs) { - PyObject *ctor_args; - PyObject *dialect; + PyObject *ctor_args; + PyObject *dialect; - ctor_args = Py_BuildValue(dialect_inst ? "(O)" : "()", dialect_inst); - if (ctor_args == NULL) - return NULL; - dialect = PyObject_Call((PyObject *)&Dialect_Type, ctor_args, kwargs); - Py_DECREF(ctor_args); - return dialect; + ctor_args = Py_BuildValue(dialect_inst ? "(O)" : "()", dialect_inst); + if (ctor_args == NULL) + return NULL; + dialect = PyObject_Call((PyObject *)&Dialect_Type, ctor_args, kwargs); + Py_DECREF(ctor_args); + return dialect; } /* @@ -500,339 +500,339 @@ static int parse_save_field(ReaderObj *self) { - PyObject *field; + PyObject *field; - field = PyUnicode_FromUnicode(self->field, self->field_len); - if (field == NULL) - return -1; - self->field_len = 0; - if (self->numeric_field) { - PyObject *tmp; - - self->numeric_field = 0; - tmp = PyNumber_Float(field); - if (tmp == NULL) { - Py_DECREF(field); - return -1; - } - Py_DECREF(field); - field = tmp; - } - PyList_Append(self->fields, field); - Py_DECREF(field); - return 0; + field = PyUnicode_FromUnicode(self->field, self->field_len); + if (field == NULL) + return -1; + self->field_len = 0; + if (self->numeric_field) { + PyObject *tmp; + + self->numeric_field = 0; + tmp = PyNumber_Float(field); + if (tmp == NULL) { + Py_DECREF(field); + return -1; + } + Py_DECREF(field); + field = tmp; + } + PyList_Append(self->fields, field); + Py_DECREF(field); + return 0; } 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_New(Py_UNICODE, self->field_size); - } - else { - if (self->field_size > INT_MAX / 2) { - PyErr_NoMemory(); - return 0; - } - self->field_size *= 2; - self->field = PyMem_Resize(self->field, Py_UNICODE, - self->field_size); - } - if (self->field == NULL) { - PyErr_NoMemory(); - return 0; - } - return 1; + if (self->field_size == 0) { + self->field_size = 4096; + if (self->field != NULL) + PyMem_Free(self->field); + self->field = PyMem_New(Py_UNICODE, self->field_size); + } + else { + if (self->field_size > INT_MAX / 2) { + PyErr_NoMemory(); + return 0; + } + self->field_size *= 2; + self->field = PyMem_Resize(self->field, Py_UNICODE, + self->field_size); + } + if (self->field == NULL) { + PyErr_NoMemory(); + return 0; + } + return 1; } static int parse_add_char(ReaderObj *self, Py_UNICODE c) { - if (self->field_len >= field_limit) { - PyErr_Format(error_obj, "field larger than field limit (%ld)", - field_limit); - return -1; - } - if (self->field_len == self->field_size && !parse_grow_buff(self)) - return -1; - self->field[self->field_len++] = c; - return 0; + if (self->field_len >= field_limit) { + PyErr_Format(error_obj, "field larger than field limit (%ld)", + field_limit); + return -1; + } + if (self->field_len == self->field_size && !parse_grow_buff(self)) + return -1; + self->field[self->field_len++] = c; + return 0; } static int parse_process_char(ReaderObj *self, Py_UNICODE c) { - DialectObj *dialect = self->dialect; + DialectObj *dialect = self->dialect; - switch (self->state) { - case START_RECORD: - /* start of record */ - if (c == '\0') - /* empty line - return [] */ - break; - else if (c == '\n' || c == '\r') { - self->state = EAT_CRNL; - break; - } - /* normal character - handle as START_FIELD */ - self->state = START_FIELD; - /* fallthru */ - case START_FIELD: - /* expecting field */ - if (c == '\n' || c == '\r' || c == '\0') { - /* save empty field - return [fields] */ - if (parse_save_field(self) < 0) - return -1; - self->state = (c == '\0' ? START_RECORD : EAT_CRNL); - } - else if (c == dialect->quotechar && - dialect->quoting != QUOTE_NONE) { - /* start quoted field */ - self->state = IN_QUOTED_FIELD; - } - else if (c == dialect->escapechar) { - /* possible escaped character */ - self->state = ESCAPED_CHAR; - } - else if (c == ' ' && dialect->skipinitialspace) - /* ignore space at start of field */ - ; - else if (c == dialect->delimiter) { - /* save empty field */ - if (parse_save_field(self) < 0) - return -1; - } - else { - /* begin new unquoted field */ - if (dialect->quoting == QUOTE_NONNUMERIC) - self->numeric_field = 1; - if (parse_add_char(self, c) < 0) - return -1; - self->state = IN_FIELD; - } - break; - - case ESCAPED_CHAR: - if (c == '\0') - c = '\n'; - if (parse_add_char(self, c) < 0) - return -1; - self->state = IN_FIELD; - break; - - case IN_FIELD: - /* in unquoted field */ - if (c == '\n' || c == '\r' || c == '\0') { - /* end of line - return [fields] */ - if (parse_save_field(self) < 0) - return -1; - self->state = (c == '\0' ? START_RECORD : EAT_CRNL); - } - else if (c == dialect->escapechar) { - /* possible escaped character */ - self->state = ESCAPED_CHAR; - } - else if (c == dialect->delimiter) { - /* save field - wait for new field */ - if (parse_save_field(self) < 0) - return -1; - self->state = START_FIELD; - } - else { - /* normal character - save in field */ - if (parse_add_char(self, c) < 0) - return -1; - } - break; - - case IN_QUOTED_FIELD: - /* in quoted field */ - if (c == '\0') - ; - else if (c == dialect->escapechar) { - /* Possible escape character */ - self->state = ESCAPE_IN_QUOTED_FIELD; - } - else if (c == dialect->quotechar && - dialect->quoting != QUOTE_NONE) { - if (dialect->doublequote) { - /* doublequote; " represented by "" */ - self->state = QUOTE_IN_QUOTED_FIELD; - } - else { - /* end of quote part of field */ - self->state = IN_FIELD; - } - } - else { - /* normal character - save in field */ - if (parse_add_char(self, c) < 0) - return -1; - } - break; - - case ESCAPE_IN_QUOTED_FIELD: - if (c == '\0') - c = '\n'; - if (parse_add_char(self, c) < 0) - return -1; - self->state = IN_QUOTED_FIELD; - break; - - case QUOTE_IN_QUOTED_FIELD: - /* doublequote - seen a quote in an quoted field */ - if (dialect->quoting != QUOTE_NONE && - c == dialect->quotechar) { - /* save "" as " */ - if (parse_add_char(self, c) < 0) - return -1; - self->state = IN_QUOTED_FIELD; - } - else if (c == dialect->delimiter) { - /* save field - wait for new field */ - if (parse_save_field(self) < 0) - return -1; - self->state = START_FIELD; - } - else if (c == '\n' || c == '\r' || c == '\0') { - /* end of line - return [fields] */ - if (parse_save_field(self) < 0) - return -1; - self->state = (c == '\0' ? START_RECORD : EAT_CRNL); - } - else if (!dialect->strict) { - if (parse_add_char(self, c) < 0) - return -1; - self->state = IN_FIELD; - } - else { - /* illegal */ - PyErr_Format(error_obj, "'%c' expected after '%c'", - dialect->delimiter, - dialect->quotechar); - return -1; - } - break; - - case EAT_CRNL: - if (c == '\n' || c == '\r') - ; - else if (c == '\0') - self->state = START_RECORD; - else { - PyErr_Format(error_obj, "new-line character seen in unquoted field - do you need to open the file in universal-newline mode?"); - return -1; - } - break; + switch (self->state) { + case START_RECORD: + /* start of record */ + if (c == '\0') + /* empty line - return [] */ + break; + else if (c == '\n' || c == '\r') { + self->state = EAT_CRNL; + break; + } + /* normal character - handle as START_FIELD */ + self->state = START_FIELD; + /* fallthru */ + case START_FIELD: + /* expecting field */ + if (c == '\n' || c == '\r' || c == '\0') { + /* save empty field - return [fields] */ + if (parse_save_field(self) < 0) + return -1; + self->state = (c == '\0' ? START_RECORD : EAT_CRNL); + } + else if (c == dialect->quotechar && + dialect->quoting != QUOTE_NONE) { + /* start quoted field */ + self->state = IN_QUOTED_FIELD; + } + else if (c == dialect->escapechar) { + /* possible escaped character */ + self->state = ESCAPED_CHAR; + } + else if (c == ' ' && dialect->skipinitialspace) + /* ignore space at start of field */ + ; + else if (c == dialect->delimiter) { + /* save empty field */ + if (parse_save_field(self) < 0) + return -1; + } + else { + /* begin new unquoted field */ + if (dialect->quoting == QUOTE_NONNUMERIC) + self->numeric_field = 1; + if (parse_add_char(self, c) < 0) + return -1; + self->state = IN_FIELD; + } + break; - } - return 0; + case ESCAPED_CHAR: + if (c == '\0') + c = '\n'; + if (parse_add_char(self, c) < 0) + return -1; + self->state = IN_FIELD; + break; + + case IN_FIELD: + /* in unquoted field */ + if (c == '\n' || c == '\r' || c == '\0') { + /* end of line - return [fields] */ + if (parse_save_field(self) < 0) + return -1; + self->state = (c == '\0' ? START_RECORD : EAT_CRNL); + } + else if (c == dialect->escapechar) { + /* possible escaped character */ + self->state = ESCAPED_CHAR; + } + else if (c == dialect->delimiter) { + /* save field - wait for new field */ + if (parse_save_field(self) < 0) + return -1; + self->state = START_FIELD; + } + else { + /* normal character - save in field */ + if (parse_add_char(self, c) < 0) + return -1; + } + break; + + case IN_QUOTED_FIELD: + /* in quoted field */ + if (c == '\0') + ; + else if (c == dialect->escapechar) { + /* Possible escape character */ + self->state = ESCAPE_IN_QUOTED_FIELD; + } + else if (c == dialect->quotechar && + dialect->quoting != QUOTE_NONE) { + if (dialect->doublequote) { + /* doublequote; " represented by "" */ + self->state = QUOTE_IN_QUOTED_FIELD; + } + else { + /* end of quote part of field */ + self->state = IN_FIELD; + } + } + else { + /* normal character - save in field */ + if (parse_add_char(self, c) < 0) + return -1; + } + break; + + case ESCAPE_IN_QUOTED_FIELD: + if (c == '\0') + c = '\n'; + if (parse_add_char(self, c) < 0) + return -1; + self->state = IN_QUOTED_FIELD; + break; + + case QUOTE_IN_QUOTED_FIELD: + /* doublequote - seen a quote in an quoted field */ + if (dialect->quoting != QUOTE_NONE && + c == dialect->quotechar) { + /* save "" as " */ + if (parse_add_char(self, c) < 0) + return -1; + self->state = IN_QUOTED_FIELD; + } + else if (c == dialect->delimiter) { + /* save field - wait for new field */ + if (parse_save_field(self) < 0) + return -1; + self->state = START_FIELD; + } + else if (c == '\n' || c == '\r' || c == '\0') { + /* end of line - return [fields] */ + if (parse_save_field(self) < 0) + return -1; + self->state = (c == '\0' ? START_RECORD : EAT_CRNL); + } + else if (!dialect->strict) { + if (parse_add_char(self, c) < 0) + return -1; + self->state = IN_FIELD; + } + else { + /* illegal */ + PyErr_Format(error_obj, "'%c' expected after '%c'", + dialect->delimiter, + dialect->quotechar); + return -1; + } + break; + + case EAT_CRNL: + if (c == '\n' || c == '\r') + ; + else if (c == '\0') + self->state = START_RECORD; + else { + PyErr_Format(error_obj, "new-line character seen in unquoted field - do you need to open the file in universal-newline mode?"); + return -1; + } + break; + + } + return 0; } static int parse_reset(ReaderObj *self) { - Py_XDECREF(self->fields); - self->fields = PyList_New(0); - if (self->fields == NULL) - return -1; - self->field_len = 0; - self->state = START_RECORD; - self->numeric_field = 0; - return 0; + Py_XDECREF(self->fields); + self->fields = PyList_New(0); + if (self->fields == NULL) + return -1; + self->field_len = 0; + self->state = START_RECORD; + self->numeric_field = 0; + return 0; } static PyObject * Reader_iternext(ReaderObj *self) { - PyObject *lineobj; - PyObject *fields = NULL; - Py_UNICODE *line, c; - Py_ssize_t linelen; - - if (parse_reset(self) < 0) - return NULL; - do { - lineobj = PyIter_Next(self->input_iter); - if (lineobj == NULL) { - /* End of input OR exception */ - if (!PyErr_Occurred() && self->field_len != 0) - PyErr_Format(error_obj, - "newline inside string"); - return NULL; - } - if (!PyUnicode_Check(lineobj)) { - PyErr_Format(error_obj, - "iterator should return strings, " - "not %.200s " - "(did you open the file in text mode?)", - lineobj->ob_type->tp_name - ); - Py_DECREF(lineobj); - return NULL; - } - ++self->line_num; - line = PyUnicode_AsUnicode(lineobj); - linelen = PyUnicode_GetSize(lineobj); - if (line == NULL || linelen < 0) { - Py_DECREF(lineobj); - return NULL; - } - while (linelen--) { - c = *line++; - if (c == '\0') { - Py_DECREF(lineobj); - PyErr_Format(error_obj, - "line contains NULL byte"); - goto err; - } - if (parse_process_char(self, c) < 0) { - Py_DECREF(lineobj); - goto err; - } - } + PyObject *lineobj; + PyObject *fields = NULL; + Py_UNICODE *line, c; + Py_ssize_t linelen; + + if (parse_reset(self) < 0) + return NULL; + do { + lineobj = PyIter_Next(self->input_iter); + if (lineobj == NULL) { + /* End of input OR exception */ + if (!PyErr_Occurred() && self->field_len != 0) + PyErr_Format(error_obj, + "newline inside string"); + return NULL; + } + if (!PyUnicode_Check(lineobj)) { + PyErr_Format(error_obj, + "iterator should return strings, " + "not %.200s " + "(did you open the file in text mode?)", + lineobj->ob_type->tp_name + ); + Py_DECREF(lineobj); + return NULL; + } + ++self->line_num; + line = PyUnicode_AsUnicode(lineobj); + linelen = PyUnicode_GetSize(lineobj); + if (line == NULL || linelen < 0) { + Py_DECREF(lineobj); + return NULL; + } + while (linelen--) { + c = *line++; + if (c == '\0') { + Py_DECREF(lineobj); + PyErr_Format(error_obj, + "line contains NULL byte"); + goto err; + } + if (parse_process_char(self, c) < 0) { Py_DECREF(lineobj); - if (parse_process_char(self, 0) < 0) - goto err; - } while (self->state != START_RECORD); + goto err; + } + } + Py_DECREF(lineobj); + if (parse_process_char(self, 0) < 0) + goto err; + } while (self->state != START_RECORD); - fields = self->fields; - self->fields = NULL; + fields = self->fields; + self->fields = NULL; err: - return fields; + return fields; } static void Reader_dealloc(ReaderObj *self) { - PyObject_GC_UnTrack(self); - Py_XDECREF(self->dialect); - Py_XDECREF(self->input_iter); - Py_XDECREF(self->fields); - if (self->field != NULL) - PyMem_Free(self->field); - PyObject_GC_Del(self); + PyObject_GC_UnTrack(self); + Py_XDECREF(self->dialect); + Py_XDECREF(self->input_iter); + Py_XDECREF(self->fields); + if (self->field != NULL) + PyMem_Free(self->field); + PyObject_GC_Del(self); } static int Reader_traverse(ReaderObj *self, visitproc visit, void *arg) { - Py_VISIT(self->dialect); - Py_VISIT(self->input_iter); - Py_VISIT(self->fields); - return 0; + Py_VISIT(self->dialect); + Py_VISIT(self->input_iter); + Py_VISIT(self->fields); + return 0; } static int Reader_clear(ReaderObj *self) { - Py_CLEAR(self->dialect); - Py_CLEAR(self->input_iter); - Py_CLEAR(self->fields); - return 0; + Py_CLEAR(self->dialect); + Py_CLEAR(self->input_iter); + Py_CLEAR(self->fields); + return 0; } PyDoc_STRVAR(Reader_Type_doc, @@ -843,93 +843,93 @@ ); static struct PyMethodDef Reader_methods[] = { - { NULL, NULL } + { NULL, NULL } }; #define R_OFF(x) offsetof(ReaderObj, x) static struct PyMemberDef Reader_memberlist[] = { - { "dialect", T_OBJECT, R_OFF(dialect), READONLY }, - { "line_num", T_ULONG, R_OFF(line_num), READONLY }, - { NULL } + { "dialect", T_OBJECT, R_OFF(dialect), READONLY }, + { "line_num", T_ULONG, R_OFF(line_num), READONLY }, + { NULL } }; static PyTypeObject Reader_Type = { - PyVarObject_HEAD_INIT(NULL, 0) - "_csv.reader", /*tp_name*/ - sizeof(ReaderObj), /*tp_basicsize*/ - 0, /*tp_itemsize*/ - /* methods */ - (destructor)Reader_dealloc, /*tp_dealloc*/ - (printfunc)0, /*tp_print*/ - (getattrfunc)0, /*tp_getattr*/ - (setattrfunc)0, /*tp_setattr*/ - 0, /*tp_reserved*/ - (reprfunc)0, /*tp_repr*/ - 0, /*tp_as_number*/ - 0, /*tp_as_sequence*/ - 0, /*tp_as_mapping*/ - (hashfunc)0, /*tp_hash*/ - (ternaryfunc)0, /*tp_call*/ - (reprfunc)0, /*tp_str*/ - 0, /*tp_getattro*/ - 0, /*tp_setattro*/ - 0, /*tp_as_buffer*/ - Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | - Py_TPFLAGS_HAVE_GC, /*tp_flags*/ - Reader_Type_doc, /*tp_doc*/ - (traverseproc)Reader_traverse, /*tp_traverse*/ - (inquiry)Reader_clear, /*tp_clear*/ - 0, /*tp_richcompare*/ - 0, /*tp_weaklistoffset*/ - PyObject_SelfIter, /*tp_iter*/ - (getiterfunc)Reader_iternext, /*tp_iternext*/ - Reader_methods, /*tp_methods*/ - Reader_memberlist, /*tp_members*/ - 0, /*tp_getset*/ + PyVarObject_HEAD_INIT(NULL, 0) + "_csv.reader", /*tp_name*/ + sizeof(ReaderObj), /*tp_basicsize*/ + 0, /*tp_itemsize*/ + /* methods */ + (destructor)Reader_dealloc, /*tp_dealloc*/ + (printfunc)0, /*tp_print*/ + (getattrfunc)0, /*tp_getattr*/ + (setattrfunc)0, /*tp_setattr*/ + 0, /*tp_reserved*/ + (reprfunc)0, /*tp_repr*/ + 0, /*tp_as_number*/ + 0, /*tp_as_sequence*/ + 0, /*tp_as_mapping*/ + (hashfunc)0, /*tp_hash*/ + (ternaryfunc)0, /*tp_call*/ + (reprfunc)0, /*tp_str*/ + 0, /*tp_getattro*/ + 0, /*tp_setattro*/ + 0, /*tp_as_buffer*/ + Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | + Py_TPFLAGS_HAVE_GC, /*tp_flags*/ + Reader_Type_doc, /*tp_doc*/ + (traverseproc)Reader_traverse, /*tp_traverse*/ + (inquiry)Reader_clear, /*tp_clear*/ + 0, /*tp_richcompare*/ + 0, /*tp_weaklistoffset*/ + PyObject_SelfIter, /*tp_iter*/ + (getiterfunc)Reader_iternext, /*tp_iternext*/ + Reader_methods, /*tp_methods*/ + Reader_memberlist, /*tp_members*/ + 0, /*tp_getset*/ }; static PyObject * csv_reader(PyObject *module, PyObject *args, PyObject *keyword_args) { - PyObject * iterator, * dialect = NULL; - ReaderObj * self = PyObject_GC_New(ReaderObj, &Reader_Type); - - if (!self) - return NULL; + PyObject * iterator, * dialect = NULL; + ReaderObj * self = PyObject_GC_New(ReaderObj, &Reader_Type); - self->dialect = NULL; - self->fields = NULL; - self->input_iter = NULL; - self->field = NULL; - self->field_size = 0; - self->line_num = 0; + if (!self) + return NULL; - if (parse_reset(self) < 0) { - Py_DECREF(self); - return NULL; - } - - if (!PyArg_UnpackTuple(args, "", 1, 2, &iterator, &dialect)) { - Py_DECREF(self); - return NULL; - } - self->input_iter = PyObject_GetIter(iterator); - if (self->input_iter == NULL) { - PyErr_SetString(PyExc_TypeError, - "argument 1 must be an iterator"); - Py_DECREF(self); - return NULL; - } - self->dialect = (DialectObj *)_call_dialect(dialect, keyword_args); - if (self->dialect == NULL) { - Py_DECREF(self); - return NULL; - } + self->dialect = NULL; + self->fields = NULL; + self->input_iter = NULL; + self->field = NULL; + self->field_size = 0; + self->line_num = 0; + + if (parse_reset(self) < 0) { + Py_DECREF(self); + return NULL; + } + + if (!PyArg_UnpackTuple(args, "", 1, 2, &iterator, &dialect)) { + Py_DECREF(self); + return NULL; + } + self->input_iter = PyObject_GetIter(iterator); + if (self->input_iter == NULL) { + PyErr_SetString(PyExc_TypeError, + "argument 1 must be an iterator"); + Py_DECREF(self); + return NULL; + } + self->dialect = (DialectObj *)_call_dialect(dialect, keyword_args); + if (self->dialect == NULL) { + Py_DECREF(self); + return NULL; + } - PyObject_GC_Track(self); - return (PyObject *)self; + PyObject_GC_Track(self); + return (PyObject *)self; } /* @@ -939,8 +939,8 @@ static void join_reset(WriterObj *self) { - self->rec_len = 0; - self->num_fields = 0; + self->rec_len = 0; + self->num_fields = 0; } #define MEM_INCR 32768 @@ -952,90 +952,90 @@ join_append_data(WriterObj *self, Py_UNICODE *field, int quote_empty, int *quoted, int copy_phase) { - DialectObj *dialect = self->dialect; - int i; - int rec_len; - Py_UNICODE *lineterm; + DialectObj *dialect = self->dialect; + int i; + int rec_len; + Py_UNICODE *lineterm; #define ADDCH(c) \ - do {\ - if (copy_phase) \ - self->rec[rec_len] = c;\ - rec_len++;\ - } while(0) - - lineterm = PyUnicode_AsUnicode(dialect->lineterminator); - if (lineterm == NULL) - return -1; - - rec_len = self->rec_len; - - /* If this is not the first field we need a field separator */ - if (self->num_fields > 0) - ADDCH(dialect->delimiter); - - /* Handle preceding quote */ - if (copy_phase && *quoted) - ADDCH(dialect->quotechar); - - /* Copy/count field data */ - /* If field is null just pass over */ - for (i = 0; field; i++) { - Py_UNICODE c = field[i]; - int want_escape = 0; - - if (c == '\0') - break; - - if (c == dialect->delimiter || - c == dialect->escapechar || - c == dialect->quotechar || - Py_UNICODE_strchr(lineterm, c)) { - if (dialect->quoting == QUOTE_NONE) - want_escape = 1; - else { - if (c == dialect->quotechar) { - if (dialect->doublequote) - ADDCH(dialect->quotechar); - else - want_escape = 1; - } - if (!want_escape) - *quoted = 1; - } - if (want_escape) { - if (!dialect->escapechar) { - PyErr_Format(error_obj, - "need to escape, but no escapechar set"); - return -1; - } - ADDCH(dialect->escapechar); - } - } - /* Copy field character into record buffer. - */ - ADDCH(c); - } - - /* If field is empty check if it needs to be quoted. - */ - if (i == 0 && quote_empty) { - if (dialect->quoting == QUOTE_NONE) { - PyErr_Format(error_obj, - "single empty field record must be quoted"); - return -1; - } - else - *quoted = 1; - } - - if (*quoted) { - if (copy_phase) - ADDCH(dialect->quotechar); - else - rec_len += 2; - } - return rec_len; + do {\ + if (copy_phase) \ + self->rec[rec_len] = c;\ + rec_len++;\ + } while(0) + + lineterm = PyUnicode_AsUnicode(dialect->lineterminator); + if (lineterm == NULL) + return -1; + + rec_len = self->rec_len; + + /* If this is not the first field we need a field separator */ + if (self->num_fields > 0) + ADDCH(dialect->delimiter); + + /* Handle preceding quote */ + if (copy_phase && *quoted) + ADDCH(dialect->quotechar); + + /* Copy/count field data */ + /* If field is null just pass over */ + for (i = 0; field; i++) { + Py_UNICODE c = field[i]; + int want_escape = 0; + + if (c == '\0') + break; + + if (c == dialect->delimiter || + c == dialect->escapechar || + c == dialect->quotechar || + Py_UNICODE_strchr(lineterm, c)) { + if (dialect->quoting == QUOTE_NONE) + want_escape = 1; + else { + if (c == dialect->quotechar) { + if (dialect->doublequote) + ADDCH(dialect->quotechar); + else + want_escape = 1; + } + if (!want_escape) + *quoted = 1; + } + if (want_escape) { + if (!dialect->escapechar) { + PyErr_Format(error_obj, + "need to escape, but no escapechar set"); + return -1; + } + ADDCH(dialect->escapechar); + } + } + /* Copy field character into record buffer. + */ + ADDCH(c); + } + + /* If field is empty check if it needs to be quoted. + */ + if (i == 0 && quote_empty) { + if (dialect->quoting == QUOTE_NONE) { + PyErr_Format(error_obj, + "single empty field record must be quoted"); + return -1; + } + else + *quoted = 1; + } + + if (*quoted) { + if (copy_phase) + ADDCH(dialect->quotechar); + else + rec_len += 2; + } + return rec_len; #undef ADDCH } @@ -1043,76 +1043,76 @@ join_check_rec_size(WriterObj *self, int rec_len) { - if (rec_len < 0 || rec_len > INT_MAX - MEM_INCR) { - PyErr_NoMemory(); - return 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_New(Py_UNICODE, self->rec_size); - } - else { - Py_UNICODE* old_rec = self->rec; - - self->rec_size = (rec_len / MEM_INCR + 1) * MEM_INCR; - self->rec = PyMem_Resize(self->rec, Py_UNICODE, - self->rec_size); - if (self->rec == NULL) - PyMem_Free(old_rec); - } - if (self->rec == NULL) { - PyErr_NoMemory(); - return 0; - } - } - return 1; + if (rec_len < 0 || rec_len > INT_MAX - MEM_INCR) { + PyErr_NoMemory(); + return 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_New(Py_UNICODE, self->rec_size); + } + else { + Py_UNICODE* old_rec = self->rec; + + self->rec_size = (rec_len / MEM_INCR + 1) * MEM_INCR; + self->rec = PyMem_Resize(self->rec, Py_UNICODE, + self->rec_size); + if (self->rec == NULL) + PyMem_Free(old_rec); + } + if (self->rec == NULL) { + PyErr_NoMemory(); + return 0; + } + } + return 1; } static int join_append(WriterObj *self, Py_UNICODE *field, int *quoted, int quote_empty) { - int rec_len; + int rec_len; - rec_len = join_append_data(self, field, quote_empty, quoted, 0); - if (rec_len < 0) - return 0; + rec_len = join_append_data(self, field, quote_empty, quoted, 0); + if (rec_len < 0) + return 0; - /* grow record buffer if necessary */ - if (!join_check_rec_size(self, rec_len)) - return 0; + /* grow record buffer if necessary */ + if (!join_check_rec_size(self, rec_len)) + return 0; - self->rec_len = join_append_data(self, field, quote_empty, quoted, 1); - self->num_fields++; + self->rec_len = join_append_data(self, field, quote_empty, quoted, 1); + self->num_fields++; - return 1; + return 1; } static int join_append_lineterminator(WriterObj *self) { - int terminator_len; - Py_UNICODE *terminator; + int terminator_len; + Py_UNICODE *terminator; + + terminator_len = PyUnicode_GetSize(self->dialect->lineterminator); + if (terminator_len == -1) + return 0; - terminator_len = PyUnicode_GetSize(self->dialect->lineterminator); - if (terminator_len == -1) - return 0; - - /* grow record buffer if necessary */ - if (!join_check_rec_size(self, self->rec_len + terminator_len)) - return 0; - - terminator = PyUnicode_AsUnicode(self->dialect->lineterminator); - if (terminator == NULL) - return 0; - memmove(self->rec + self->rec_len, terminator, - sizeof(Py_UNICODE)*terminator_len); - self->rec_len += terminator_len; + /* grow record buffer if necessary */ + if (!join_check_rec_size(self, self->rec_len + terminator_len)) + return 0; + + terminator = PyUnicode_AsUnicode(self->dialect->lineterminator); + if (terminator == NULL) + return 0; + memmove(self->rec + self->rec_len, terminator, + sizeof(Py_UNICODE)*terminator_len); + self->rec_len += terminator_len; - return 1; + return 1; } PyDoc_STRVAR(csv_writerow_doc, @@ -1124,75 +1124,75 @@ static PyObject * csv_writerow(WriterObj *self, PyObject *seq) { - DialectObj *dialect = self->dialect; - int len, i; + DialectObj *dialect = self->dialect; + int len, i; + + if (!PySequence_Check(seq)) + return PyErr_Format(error_obj, "sequence expected"); - if (!PySequence_Check(seq)) - return PyErr_Format(error_obj, "sequence expected"); + len = PySequence_Length(seq); + if (len < 0) + return NULL; + + /* Join all fields in internal buffer. + */ + join_reset(self); + for (i = 0; i < len; i++) { + PyObject *field; + int append_ok; + int quoted; + + field = PySequence_GetItem(seq, i); + if (field == NULL) + return NULL; + + switch (dialect->quoting) { + case QUOTE_NONNUMERIC: + quoted = !PyNumber_Check(field); + break; + case QUOTE_ALL: + quoted = 1; + break; + default: + quoted = 0; + break; + } + + if (PyUnicode_Check(field)) { + append_ok = join_append(self, + PyUnicode_AS_UNICODE(field), + "ed, len == 1); + Py_DECREF(field); + } + else if (field == Py_None) { + append_ok = join_append(self, NULL, + "ed, len == 1); + Py_DECREF(field); + } + else { + PyObject *str; - len = PySequence_Length(seq); - if (len < 0) - return NULL; - - /* Join all fields in internal buffer. - */ - join_reset(self); - for (i = 0; i < len; i++) { - PyObject *field; - int append_ok; - int quoted; - - field = PySequence_GetItem(seq, i); - if (field == NULL) - return NULL; - - switch (dialect->quoting) { - case QUOTE_NONNUMERIC: - quoted = !PyNumber_Check(field); - break; - case QUOTE_ALL: - quoted = 1; - break; - default: - quoted = 0; - break; - } - - if (PyUnicode_Check(field)) { - append_ok = join_append(self, - PyUnicode_AS_UNICODE(field), - "ed, len == 1); - Py_DECREF(field); - } - else if (field == Py_None) { - append_ok = join_append(self, NULL, + str = PyObject_Str(field); + Py_DECREF(field); + if (str == NULL) + return NULL; + append_ok = join_append(self, + PyUnicode_AS_UNICODE(str), "ed, len == 1); - Py_DECREF(field); - } - else { - PyObject *str; - - str = PyObject_Str(field); - Py_DECREF(field); - if (str == NULL) - return NULL; - append_ok = join_append(self, - PyUnicode_AS_UNICODE(str), - "ed, len == 1); - Py_DECREF(str); - } - if (!append_ok) - return NULL; - } - - /* Add line terminator. - */ - if (!join_append_lineterminator(self)) - return 0; - - return PyObject_CallFunction(self->writeline, - "(u#)", self->rec, - self->rec_len); + Py_DECREF(str); + } + if (!append_ok) + return NULL; + } + + /* Add line terminator. + */ + if (!join_append_lineterminator(self)) + return 0; + + return PyObject_CallFunction(self->writeline, + "(u#)", self->rec, + self->rec_len); } PyDoc_STRVAR(csv_writerows_doc, @@ -1204,72 +1204,72 @@ static PyObject * csv_writerows(WriterObj *self, PyObject *seqseq) { - PyObject *row_iter, *row_obj, *result; + PyObject *row_iter, *row_obj, *result; - row_iter = PyObject_GetIter(seqseq); - if (row_iter == NULL) { - PyErr_SetString(PyExc_TypeError, - "writerows() argument must be iterable"); - return NULL; - } - while ((row_obj = PyIter_Next(row_iter))) { - result = csv_writerow(self, row_obj); - Py_DECREF(row_obj); - if (!result) { - Py_DECREF(row_iter); - return NULL; - } - else - Py_DECREF(result); + row_iter = PyObject_GetIter(seqseq); + if (row_iter == NULL) { + PyErr_SetString(PyExc_TypeError, + "writerows() argument must be iterable"); + return NULL; + } + while ((row_obj = PyIter_Next(row_iter))) { + result = csv_writerow(self, row_obj); + Py_DECREF(row_obj); + if (!result) { + Py_DECREF(row_iter); + return NULL; } - Py_DECREF(row_iter); - if (PyErr_Occurred()) - return NULL; - Py_INCREF(Py_None); - return Py_None; + else + Py_DECREF(result); + } + Py_DECREF(row_iter); + if (PyErr_Occurred()) + return NULL; + Py_INCREF(Py_None); + return Py_None; } static struct PyMethodDef Writer_methods[] = { - { "writerow", (PyCFunction)csv_writerow, METH_O, csv_writerow_doc}, - { "writerows", (PyCFunction)csv_writerows, METH_O, csv_writerows_doc}, - { NULL, NULL } + { "writerow", (PyCFunction)csv_writerow, METH_O, csv_writerow_doc}, + { "writerows", (PyCFunction)csv_writerows, METH_O, csv_writerows_doc}, + { NULL, NULL } }; #define W_OFF(x) offsetof(WriterObj, x) static struct PyMemberDef Writer_memberlist[] = { - { "dialect", T_OBJECT, W_OFF(dialect), READONLY }, - { NULL } + { "dialect", T_OBJECT, W_OFF(dialect), READONLY }, + { NULL } }; static void Writer_dealloc(WriterObj *self) { - PyObject_GC_UnTrack(self); - Py_XDECREF(self->dialect); - Py_XDECREF(self->writeline); - if (self->rec != NULL) - PyMem_Free(self->rec); - PyObject_GC_Del(self); + PyObject_GC_UnTrack(self); + Py_XDECREF(self->dialect); + Py_XDECREF(self->writeline); + if (self->rec != NULL) + PyMem_Free(self->rec); + PyObject_GC_Del(self); } static int Writer_traverse(WriterObj *self, visitproc visit, void *arg) { - Py_VISIT(self->dialect); - Py_VISIT(self->writeline); - return 0; + Py_VISIT(self->dialect); + Py_VISIT(self->writeline); + return 0; } static int Writer_clear(WriterObj *self) { - Py_CLEAR(self->dialect); - Py_CLEAR(self->writeline); - return 0; + Py_CLEAR(self->dialect); + Py_CLEAR(self->writeline); + return 0; } -PyDoc_STRVAR(Writer_Type_doc, +PyDoc_STRVAR(Writer_Type_doc, "CSV writer\n" "\n" "Writer objects are responsible for generating tabular data\n" @@ -1277,75 +1277,75 @@ ); static PyTypeObject Writer_Type = { - PyVarObject_HEAD_INIT(NULL, 0) - "_csv.writer", /*tp_name*/ - sizeof(WriterObj), /*tp_basicsize*/ - 0, /*tp_itemsize*/ - /* methods */ - (destructor)Writer_dealloc, /*tp_dealloc*/ - (printfunc)0, /*tp_print*/ - (getattrfunc)0, /*tp_getattr*/ - (setattrfunc)0, /*tp_setattr*/ - 0, /*tp_reserved*/ - (reprfunc)0, /*tp_repr*/ - 0, /*tp_as_number*/ - 0, /*tp_as_sequence*/ - 0, /*tp_as_mapping*/ - (hashfunc)0, /*tp_hash*/ - (ternaryfunc)0, /*tp_call*/ - (reprfunc)0, /*tp_str*/ - 0, /*tp_getattro*/ - 0, /*tp_setattro*/ - 0, /*tp_as_buffer*/ - Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | - Py_TPFLAGS_HAVE_GC, /*tp_flags*/ - Writer_Type_doc, - (traverseproc)Writer_traverse, /*tp_traverse*/ - (inquiry)Writer_clear, /*tp_clear*/ - 0, /*tp_richcompare*/ - 0, /*tp_weaklistoffset*/ - (getiterfunc)0, /*tp_iter*/ - (getiterfunc)0, /*tp_iternext*/ - Writer_methods, /*tp_methods*/ - Writer_memberlist, /*tp_members*/ - 0, /*tp_getset*/ + PyVarObject_HEAD_INIT(NULL, 0) + "_csv.writer", /*tp_name*/ + sizeof(WriterObj), /*tp_basicsize*/ + 0, /*tp_itemsize*/ + /* methods */ + (destructor)Writer_dealloc, /*tp_dealloc*/ + (printfunc)0, /*tp_print*/ + (getattrfunc)0, /*tp_getattr*/ + (setattrfunc)0, /*tp_setattr*/ + 0, /*tp_reserved*/ + (reprfunc)0, /*tp_repr*/ + 0, /*tp_as_number*/ + 0, /*tp_as_sequence*/ + 0, /*tp_as_mapping*/ + (hashfunc)0, /*tp_hash*/ + (ternaryfunc)0, /*tp_call*/ + (reprfunc)0, /*tp_str*/ + 0, /*tp_getattro*/ + 0, /*tp_setattro*/ + 0, /*tp_as_buffer*/ + Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | + Py_TPFLAGS_HAVE_GC, /*tp_flags*/ + Writer_Type_doc, + (traverseproc)Writer_traverse, /*tp_traverse*/ + (inquiry)Writer_clear, /*tp_clear*/ + 0, /*tp_richcompare*/ + 0, /*tp_weaklistoffset*/ + (getiterfunc)0, /*tp_iter*/ + (getiterfunc)0, /*tp_iternext*/ + Writer_methods, /*tp_methods*/ + Writer_memberlist, /*tp_members*/ + 0, /*tp_getset*/ }; static PyObject * csv_writer(PyObject *module, PyObject *args, PyObject *keyword_args) { - PyObject * output_file, * dialect = NULL; - WriterObj * self = PyObject_GC_New(WriterObj, &Writer_Type); + PyObject * output_file, * dialect = NULL; + WriterObj * self = PyObject_GC_New(WriterObj, &Writer_Type); - if (!self) - return NULL; - - self->dialect = NULL; - self->writeline = NULL; + if (!self) + return NULL; - self->rec = NULL; - self->rec_size = 0; - self->rec_len = 0; - self->num_fields = 0; + self->dialect = NULL; + self->writeline = NULL; - if (!PyArg_UnpackTuple(args, "", 1, 2, &output_file, &dialect)) { - Py_DECREF(self); - return NULL; - } - self->writeline = PyObject_GetAttrString(output_file, "write"); - if (self->writeline == NULL || !PyCallable_Check(self->writeline)) { - PyErr_SetString(PyExc_TypeError, - "argument 1 must have a \"write\" method"); - Py_DECREF(self); - return NULL; - } - self->dialect = (DialectObj *)_call_dialect(dialect, keyword_args); - if (self->dialect == NULL) { - Py_DECREF(self); - return NULL; - } - PyObject_GC_Track(self); - return (PyObject *)self; + self->rec = NULL; + self->rec_size = 0; + self->rec_len = 0; + self->num_fields = 0; + + if (!PyArg_UnpackTuple(args, "", 1, 2, &output_file, &dialect)) { + Py_DECREF(self); + return NULL; + } + self->writeline = PyObject_GetAttrString(output_file, "write"); + if (self->writeline == NULL || !PyCallable_Check(self->writeline)) { + PyErr_SetString(PyExc_TypeError, + "argument 1 must have a \"write\" method"); + Py_DECREF(self); + return NULL; + } + self->dialect = (DialectObj *)_call_dialect(dialect, keyword_args); + if (self->dialect == NULL) { + Py_DECREF(self); + return NULL; + } + PyObject_GC_Track(self); + return (PyObject *)self; } /* @@ -1354,70 +1354,70 @@ static PyObject * csv_list_dialects(PyObject *module, PyObject *args) { - return PyDict_Keys(dialects); + return PyDict_Keys(dialects); } static PyObject * csv_register_dialect(PyObject *module, PyObject *args, PyObject *kwargs) { - PyObject *name_obj, *dialect_obj = NULL; - PyObject *dialect; + PyObject *name_obj, *dialect_obj = NULL; + PyObject *dialect; - if (!PyArg_UnpackTuple(args, "", 1, 2, &name_obj, &dialect_obj)) - return NULL; - if (!IS_BASESTRING(name_obj)) { - PyErr_SetString(PyExc_TypeError, - "dialect name must be a string or unicode"); - return NULL; - } - dialect = _call_dialect(dialect_obj, kwargs); - if (dialect == NULL) - return NULL; - if (PyDict_SetItem(dialects, name_obj, dialect) < 0) { - Py_DECREF(dialect); - return NULL; - } - Py_DECREF(dialect); - Py_INCREF(Py_None); - return Py_None; + if (!PyArg_UnpackTuple(args, "", 1, 2, &name_obj, &dialect_obj)) + return NULL; + if (!IS_BASESTRING(name_obj)) { + PyErr_SetString(PyExc_TypeError, + "dialect name must be a string or unicode"); + return NULL; + } + dialect = _call_dialect(dialect_obj, kwargs); + if (dialect == NULL) + return NULL; + if (PyDict_SetItem(dialects, name_obj, dialect) < 0) { + Py_DECREF(dialect); + return NULL; + } + Py_DECREF(dialect); + Py_INCREF(Py_None); + return Py_None; } static PyObject * csv_unregister_dialect(PyObject *module, PyObject *name_obj) { - if (PyDict_DelItem(dialects, name_obj) < 0) - return PyErr_Format(error_obj, "unknown dialect"); - Py_INCREF(Py_None); - return Py_None; + if (PyDict_DelItem(dialects, name_obj) < 0) + return PyErr_Format(error_obj, "unknown dialect"); + Py_INCREF(Py_None); + return Py_None; } static PyObject * csv_get_dialect(PyObject *module, PyObject *name_obj) { - return get_dialect_from_registry(name_obj); + return get_dialect_from_registry(name_obj); } static PyObject * csv_field_size_limit(PyObject *module, PyObject *args) { - PyObject *new_limit = NULL; - long old_limit = field_limit; + PyObject *new_limit = NULL; + long old_limit = field_limit; - if (!PyArg_UnpackTuple(args, "field_size_limit", 0, 1, &new_limit)) - return NULL; - if (new_limit != NULL) { - if (!PyLong_CheckExact(new_limit)) { - PyErr_Format(PyExc_TypeError, - "limit must be an integer"); - return NULL; - } - field_limit = PyLong_AsLong(new_limit); - if (field_limit == -1 && PyErr_Occurred()) { - field_limit = old_limit; - return NULL; - } - } - return PyLong_FromLong(old_limit); + if (!PyArg_UnpackTuple(args, "field_size_limit", 0, 1, &new_limit)) + return NULL; + if (new_limit != NULL) { + if (!PyLong_CheckExact(new_limit)) { + PyErr_Format(PyExc_TypeError, + "limit must be an integer"); + return NULL; + } + field_limit = PyLong_AsLong(new_limit); + if (field_limit == -1 && PyErr_Occurred()) { + field_limit = old_limit; + return NULL; + } + } + return PyLong_FromLong(old_limit); } /* @@ -1535,84 +1535,84 @@ "the old limit is returned"); static struct PyMethodDef csv_methods[] = { - { "reader", (PyCFunction)csv_reader, - METH_VARARGS | METH_KEYWORDS, csv_reader_doc}, - { "writer", (PyCFunction)csv_writer, - METH_VARARGS | METH_KEYWORDS, csv_writer_doc}, - { "list_dialects", (PyCFunction)csv_list_dialects, - METH_NOARGS, csv_list_dialects_doc}, - { "register_dialect", (PyCFunction)csv_register_dialect, - METH_VARARGS | METH_KEYWORDS, csv_register_dialect_doc}, - { "unregister_dialect", (PyCFunction)csv_unregister_dialect, - METH_O, csv_unregister_dialect_doc}, - { "get_dialect", (PyCFunction)csv_get_dialect, - METH_O, csv_get_dialect_doc}, - { "field_size_limit", (PyCFunction)csv_field_size_limit, - METH_VARARGS, csv_field_size_limit_doc}, - { NULL, NULL } + { "reader", (PyCFunction)csv_reader, + METH_VARARGS | METH_KEYWORDS, csv_reader_doc}, + { "writer", (PyCFunction)csv_writer, + METH_VARARGS | METH_KEYWORDS, csv_writer_doc}, + { "list_dialects", (PyCFunction)csv_list_dialects, + METH_NOARGS, csv_list_dialects_doc}, + { "register_dialect", (PyCFunction)csv_register_dialect, + METH_VARARGS | METH_KEYWORDS, csv_register_dialect_doc}, + { "unregister_dialect", (PyCFunction)csv_unregister_dialect, + METH_O, csv_unregister_dialect_doc}, + { "get_dialect", (PyCFunction)csv_get_dialect, + METH_O, csv_get_dialect_doc}, + { "field_size_limit", (PyCFunction)csv_field_size_limit, + METH_VARARGS, csv_field_size_limit_doc}, + { NULL, NULL } }; static struct PyModuleDef _csvmodule = { - PyModuleDef_HEAD_INIT, - "_csv", - csv_module_doc, - -1, - csv_methods, - NULL, - NULL, - NULL, - NULL + PyModuleDef_HEAD_INIT, + "_csv", + csv_module_doc, + -1, + csv_methods, + NULL, + NULL, + NULL, + NULL }; PyMODINIT_FUNC PyInit__csv(void) { - PyObject *module; - StyleDesc *style; - - if (PyType_Ready(&Dialect_Type) < 0) - return NULL; + PyObject *module; + StyleDesc *style; - if (PyType_Ready(&Reader_Type) < 0) - return NULL; + if (PyType_Ready(&Dialect_Type) < 0) + return NULL; - if (PyType_Ready(&Writer_Type) < 0) - return NULL; - - /* Create the module and add the functions */ - module = PyModule_Create(&_csvmodule); - if (module == NULL) - return NULL; - - /* Add version to the module. */ - if (PyModule_AddStringConstant(module, "__version__", - MODULE_VERSION) == -1) - return NULL; - - /* Add _dialects dictionary */ - dialects = PyDict_New(); - if (dialects == NULL) - return NULL; - if (PyModule_AddObject(module, "_dialects", dialects)) - return NULL; - - /* Add quote styles into dictionary */ - for (style = quote_styles; style->name; style++) { - if (PyModule_AddIntConstant(module, style->name, - style->style) == -1) - return NULL; - } - - /* Add the Dialect type */ - Py_INCREF(&Dialect_Type); - if (PyModule_AddObject(module, "Dialect", (PyObject *)&Dialect_Type)) - return NULL; + if (PyType_Ready(&Reader_Type) < 0) + return NULL; - /* Add the CSV exception object to the module. */ - error_obj = PyErr_NewException("_csv.Error", NULL, NULL); - if (error_obj == NULL) - return NULL; - PyModule_AddObject(module, "Error", error_obj); - return module; + if (PyType_Ready(&Writer_Type) < 0) + return NULL; + + /* Create the module and add the functions */ + module = PyModule_Create(&_csvmodule); + if (module == NULL) + return NULL; + + /* Add version to the module. */ + if (PyModule_AddStringConstant(module, "__version__", + MODULE_VERSION) == -1) + return NULL; + + /* Add _dialects dictionary */ + dialects = PyDict_New(); + if (dialects == NULL) + return NULL; + if (PyModule_AddObject(module, "_dialects", dialects)) + return NULL; + + /* Add quote styles into dictionary */ + for (style = quote_styles; style->name; style++) { + if (PyModule_AddIntConstant(module, style->name, + style->style) == -1) + return NULL; + } + + /* Add the Dialect type */ + Py_INCREF(&Dialect_Type); + if (PyModule_AddObject(module, "Dialect", (PyObject *)&Dialect_Type)) + return NULL; + + /* Add the CSV exception object to the module. */ + error_obj = PyErr_NewException("_csv.Error", NULL, NULL); + if (error_obj == NULL) + return NULL; + PyModule_AddObject(module, "Error", error_obj); + return module; } Modified: python/branches/release31-maint/Modules/_ctypes/_ctypes.c ============================================================================== --- python/branches/release31-maint/Modules/_ctypes/_ctypes.c (original) +++ python/branches/release31-maint/Modules/_ctypes/_ctypes.c Sun May 9 18:14:21 2010 @@ -20,20 +20,20 @@ /* -Name methods, members, getsets +Name methods, members, getsets ============================================================================== -PyCStructType_Type __new__(), from_address(), __mul__(), from_param() -UnionType_Type __new__(), from_address(), __mul__(), from_param() -PyCPointerType_Type __new__(), from_address(), __mul__(), from_param(), set_type() -PyCArrayType_Type __new__(), from_address(), __mul__(), from_param() -PyCSimpleType_Type __new__(), from_address(), __mul__(), from_param() +PyCStructType_Type __new__(), from_address(), __mul__(), from_param() +UnionType_Type __new__(), from_address(), __mul__(), from_param() +PyCPointerType_Type __new__(), from_address(), __mul__(), from_param(), set_type() +PyCArrayType_Type __new__(), from_address(), __mul__(), from_param() +PyCSimpleType_Type __new__(), from_address(), __mul__(), from_param() PyCData_Type - Struct_Type __new__(), __init__() - PyCPointer_Type __new__(), __init__(), _as_parameter_, contents - PyCArray_Type __new__(), __init__(), _as_parameter_, __get/setitem__(), __len__() - Simple_Type __new__(), __init__(), _as_parameter_ + Struct_Type __new__(), __init__() + PyCPointer_Type __new__(), __init__(), _as_parameter_, contents + PyCArray_Type __new__(), __init__(), _as_parameter_, __get/setitem__(), __len__() + Simple_Type __new__(), __init__(), _as_parameter_ PyCField_Type PyCStgDict_Type @@ -45,28 +45,28 @@ It has some similarity to the byref() construct compared to pointer() from_address(addr) - - construct an instance from a given memory block (sharing this memory block) + - construct an instance from a given memory block (sharing this memory block) from_param(obj) - - typecheck and convert a Python object into a C function call parameter - the result may be an instance of the type, or an integer or tuple - (typecode, value[, obj]) + - typecheck and convert a Python object into a C function call parameter + the result may be an instance of the type, or an integer or tuple + (typecode, value[, obj]) instance methods/properties --------------------------- _as_parameter_ - - convert self into a C function call parameter - This is either an integer, or a 3-tuple (typecode, value, obj) + - convert self into a C function call parameter + This is either an integer, or a 3-tuple (typecode, value, obj) functions --------- sizeof(cdata) - - return the number of bytes the buffer contains + - return the number of bytes the buffer contains sizeof(ctype) - - return the number of bytes the buffer of an instance would contain + - return the number of bytes the buffer of an instance would contain byref(cdata) @@ -77,7 +77,7 @@ POINTER(ctype) bytes(cdata) - - return the buffer contents as a sequence of bytes (which is currently a string) + - return the buffer contents as a sequence of bytes (which is currently a string) */ @@ -98,7 +98,7 @@ * PyCField_Type * */ - + #define PY_SSIZE_T_CLEAN #include "Python.h" @@ -135,128 +135,128 @@ char *_ctypes_conversion_encoding = NULL; char *_ctypes_conversion_errors = NULL; - + /****************************************************************/ typedef struct { - PyObject_HEAD - PyObject *key; - PyObject *dict; + PyObject_HEAD + PyObject *key; + PyObject *dict; } DictRemoverObject; static void _DictRemover_dealloc(PyObject *_self) { - DictRemoverObject *self = (DictRemoverObject *)_self; - Py_XDECREF(self->key); - Py_XDECREF(self->dict); - Py_TYPE(self)->tp_free(_self); + DictRemoverObject *self = (DictRemoverObject *)_self; + Py_XDECREF(self->key); + Py_XDECREF(self->dict); + Py_TYPE(self)->tp_free(_self); } static PyObject * _DictRemover_call(PyObject *_self, PyObject *args, PyObject *kw) { - DictRemoverObject *self = (DictRemoverObject *)_self; - if (self->key && self->dict) { - if (-1 == PyDict_DelItem(self->dict, self->key)) - /* XXX Error context */ - PyErr_WriteUnraisable(Py_None); - Py_DECREF(self->key); - self->key = NULL; - Py_DECREF(self->dict); - self->dict = NULL; - } - Py_INCREF(Py_None); - return Py_None; + DictRemoverObject *self = (DictRemoverObject *)_self; + if (self->key && self->dict) { + if (-1 == PyDict_DelItem(self->dict, self->key)) + /* XXX Error context */ + PyErr_WriteUnraisable(Py_None); + Py_DECREF(self->key); + self->key = NULL; + Py_DECREF(self->dict); + self->dict = NULL; + } + Py_INCREF(Py_None); + return Py_None; } static PyTypeObject DictRemover_Type = { - PyVarObject_HEAD_INIT(NULL, 0) - "_ctypes.DictRemover", /* tp_name */ - sizeof(DictRemoverObject), /* tp_basicsize */ - 0, /* tp_itemsize */ - _DictRemover_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 */ - _DictRemover_call, /* tp_call */ - 0, /* tp_str */ - 0, /* tp_getattro */ - 0, /* tp_setattro */ - 0, /* tp_as_buffer */ + PyVarObject_HEAD_INIT(NULL, 0) + "_ctypes.DictRemover", /* tp_name */ + sizeof(DictRemoverObject), /* tp_basicsize */ + 0, /* tp_itemsize */ + _DictRemover_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 */ + _DictRemover_call, /* tp_call */ + 0, /* tp_str */ + 0, /* tp_getattro */ + 0, /* tp_setattro */ + 0, /* tp_as_buffer */ /* XXX should participate in GC? */ - Py_TPFLAGS_DEFAULT, /* tp_flags */ - "deletes a key from a dictionary", /* tp_doc */ - 0, /* tp_traverse */ - 0, /* tp_clear */ - 0, /* tp_richcompare */ - 0, /* tp_weaklistoffset */ - 0, /* tp_iter */ - 0, /* tp_iternext */ - 0, /* tp_methods */ - 0, /* tp_members */ - 0, /* tp_getset */ - 0, /* tp_base */ - 0, /* tp_dict */ - 0, /* tp_descr_get */ - 0, /* tp_descr_set */ - 0, /* tp_dictoffset */ - 0, /* tp_init */ - 0, /* tp_alloc */ - 0, /* tp_new */ - 0, /* tp_free */ + Py_TPFLAGS_DEFAULT, /* tp_flags */ + "deletes a key from a dictionary", /* tp_doc */ + 0, /* tp_traverse */ + 0, /* tp_clear */ + 0, /* tp_richcompare */ + 0, /* tp_weaklistoffset */ + 0, /* tp_iter */ + 0, /* tp_iternext */ + 0, /* tp_methods */ + 0, /* tp_members */ + 0, /* tp_getset */ + 0, /* tp_base */ + 0, /* tp_dict */ + 0, /* tp_descr_get */ + 0, /* tp_descr_set */ + 0, /* tp_dictoffset */ + 0, /* tp_init */ + 0, /* tp_alloc */ + 0, /* tp_new */ + 0, /* tp_free */ }; int PyDict_SetItemProxy(PyObject *dict, PyObject *key, PyObject *item) { - PyObject *obj; - DictRemoverObject *remover; - PyObject *proxy; - int result; - - obj = PyObject_CallObject((PyObject *)&DictRemover_Type, NULL); - if (obj == NULL) - return -1; - - remover = (DictRemoverObject *)obj; - assert(remover->key == NULL); - assert(remover->dict == NULL); - Py_INCREF(key); - remover->key = key; - Py_INCREF(dict); - remover->dict = dict; - - proxy = PyWeakref_NewProxy(item, obj); - Py_DECREF(obj); - if (proxy == NULL) - return -1; - - result = PyDict_SetItem(dict, key, proxy); - Py_DECREF(proxy); - return result; + PyObject *obj; + DictRemoverObject *remover; + PyObject *proxy; + int result; + + obj = PyObject_CallObject((PyObject *)&DictRemover_Type, NULL); + if (obj == NULL) + return -1; + + remover = (DictRemoverObject *)obj; + assert(remover->key == NULL); + assert(remover->dict == NULL); + Py_INCREF(key); + remover->key = key; + Py_INCREF(dict); + remover->dict = dict; + + proxy = PyWeakref_NewProxy(item, obj); + Py_DECREF(obj); + if (proxy == NULL) + return -1; + + result = PyDict_SetItem(dict, key, proxy); + Py_DECREF(proxy); + return result; } PyObject * PyDict_GetItemProxy(PyObject *dict, PyObject *key) { - PyObject *result; - PyObject *item = PyDict_GetItem(dict, key); + PyObject *result; + PyObject *item = PyDict_GetItem(dict, key); - if (item == NULL) - return NULL; - if (!PyWeakref_CheckProxy(item)) - return item; - result = PyWeakref_GET_OBJECT(item); - if (result == Py_None) - return NULL; - return result; + if (item == NULL) + return NULL; + if (!PyWeakref_CheckProxy(item)) + return item; + result = PyWeakref_GET_OBJECT(item); + if (result == Py_None) + return NULL; + return result; } /******************************************************************/ @@ -269,25 +269,25 @@ char * _ctypes_alloc_format_string(const char *prefix, const char *suffix) { - size_t len; - char *result; + size_t len; + char *result; - if (suffix == NULL) { - assert(PyErr_Occurred()); - return NULL; - } - len = strlen(suffix); - if (prefix) - len += strlen(prefix); - result = PyMem_Malloc(len + 1); - if (result == NULL) - return NULL; - if (prefix) - strcpy(result, prefix); - else - result[0] = '\0'; - strcat(result, suffix); - return result; + if (suffix == NULL) { + assert(PyErr_Occurred()); + return NULL; + } + len = strlen(suffix); + if (prefix) + len += strlen(prefix); + result = PyMem_Malloc(len + 1); + if (result == NULL) + return NULL; + if (prefix) + strcpy(result, prefix); + else + result[0] = '\0'; + strcat(result, suffix); + return result; } /* @@ -300,100 +300,100 @@ static PyCArgObject * StructUnionType_paramfunc(CDataObject *self) { - PyCArgObject *parg; - StgDictObject *stgdict; - - parg = PyCArgObject_new(); - if (parg == NULL) - return NULL; - - parg->tag = 'V'; - stgdict = PyObject_stgdict((PyObject *)self); - assert(stgdict); /* Cannot be NULL for structure/union instances */ - parg->pffi_type = &stgdict->ffi_type_pointer; - /* For structure parameters (by value), parg->value doesn't contain the structure - data itself, instead parg->value.p *points* to the structure's data - See also _ctypes.c, function _call_function_pointer(). - */ - parg->value.p = self->b_ptr; - parg->size = self->b_size; - Py_INCREF(self); - parg->obj = (PyObject *)self; - return parg; + PyCArgObject *parg; + StgDictObject *stgdict; + + parg = PyCArgObject_new(); + if (parg == NULL) + return NULL; + + parg->tag = 'V'; + stgdict = PyObject_stgdict((PyObject *)self); + assert(stgdict); /* Cannot be NULL for structure/union instances */ + parg->pffi_type = &stgdict->ffi_type_pointer; + /* For structure parameters (by value), parg->value doesn't contain the structure + data itself, instead parg->value.p *points* to the structure's data + See also _ctypes.c, function _call_function_pointer(). + */ + parg->value.p = self->b_ptr; + parg->size = self->b_size; + Py_INCREF(self); + parg->obj = (PyObject *)self; + return parg; } static PyObject * StructUnionType_new(PyTypeObject *type, PyObject *args, PyObject *kwds, int isStruct) { - PyTypeObject *result; - PyObject *fields; - StgDictObject *dict; - - /* create the new instance (which is a class, - since we are a metatype!) */ - result = (PyTypeObject *)PyType_Type.tp_new(type, args, kwds); - if (!result) - return NULL; - - /* keep this for bw compatibility */ - if (PyDict_GetItemString(result->tp_dict, "_abstract_")) - return (PyObject *)result; - - dict = (StgDictObject *)PyObject_CallObject((PyObject *)&PyCStgDict_Type, NULL); - if (!dict) { - Py_DECREF(result); - return NULL; - } - /* replace the class dict by our updated stgdict, which holds info - about storage requirements of the instances */ - if (-1 == PyDict_Update((PyObject *)dict, result->tp_dict)) { - Py_DECREF(result); - Py_DECREF((PyObject *)dict); - return NULL; - } - Py_DECREF(result->tp_dict); - result->tp_dict = (PyObject *)dict; - dict->format = _ctypes_alloc_format_string(NULL, "B"); - if (dict->format == NULL) { - Py_DECREF(result); - return NULL; - } - - dict->paramfunc = StructUnionType_paramfunc; - - fields = PyDict_GetItemString((PyObject *)dict, "_fields_"); - if (!fields) { - StgDictObject *basedict = PyType_stgdict((PyObject *)result->tp_base); - - if (basedict == NULL) - return (PyObject *)result; - /* copy base dict */ - if (-1 == PyCStgDict_clone(dict, basedict)) { - Py_DECREF(result); - return NULL; - } - dict->flags &= ~DICTFLAG_FINAL; /* clear the 'final' flag in the subclass dict */ - basedict->flags |= DICTFLAG_FINAL; /* set the 'final' flag in the baseclass dict */ - return (PyObject *)result; - } - - if (-1 == PyObject_SetAttrString((PyObject *)result, "_fields_", fields)) { - Py_DECREF(result); - return NULL; - } - return (PyObject *)result; + PyTypeObject *result; + PyObject *fields; + StgDictObject *dict; + + /* create the new instance (which is a class, + since we are a metatype!) */ + result = (PyTypeObject *)PyType_Type.tp_new(type, args, kwds); + if (!result) + return NULL; + + /* keep this for bw compatibility */ + if (PyDict_GetItemString(result->tp_dict, "_abstract_")) + return (PyObject *)result; + + dict = (StgDictObject *)PyObject_CallObject((PyObject *)&PyCStgDict_Type, NULL); + if (!dict) { + Py_DECREF(result); + return NULL; + } + /* replace the class dict by our updated stgdict, which holds info + about storage requirements of the instances */ + if (-1 == PyDict_Update((PyObject *)dict, result->tp_dict)) { + Py_DECREF(result); + Py_DECREF((PyObject *)dict); + return NULL; + } + Py_DECREF(result->tp_dict); + result->tp_dict = (PyObject *)dict; + dict->format = _ctypes_alloc_format_string(NULL, "B"); + if (dict->format == NULL) { + Py_DECREF(result); + return NULL; + } + + dict->paramfunc = StructUnionType_paramfunc; + + fields = PyDict_GetItemString((PyObject *)dict, "_fields_"); + if (!fields) { + StgDictObject *basedict = PyType_stgdict((PyObject *)result->tp_base); + + if (basedict == NULL) + return (PyObject *)result; + /* copy base dict */ + if (-1 == PyCStgDict_clone(dict, basedict)) { + Py_DECREF(result); + return NULL; + } + dict->flags &= ~DICTFLAG_FINAL; /* clear the 'final' flag in the subclass dict */ + basedict->flags |= DICTFLAG_FINAL; /* set the 'final' flag in the baseclass dict */ + return (PyObject *)result; + } + + if (-1 == PyObject_SetAttrString((PyObject *)result, "_fields_", fields)) { + Py_DECREF(result); + return NULL; + } + return (PyObject *)result; } static PyObject * PyCStructType_new(PyTypeObject *type, PyObject *args, PyObject *kwds) { - return StructUnionType_new(type, args, kwds, 1); + return StructUnionType_new(type, args, kwds, 1); } static PyObject * UnionType_new(PyTypeObject *type, PyObject *args, PyObject *kwds) { - return StructUnionType_new(type, args, kwds, 0); + return StructUnionType_new(type, args, kwds, 0); } static char from_address_doc[] = @@ -402,16 +402,16 @@ static PyObject * CDataType_from_address(PyObject *type, PyObject *value) { - void *buf; - if (!PyLong_Check(value)) { - PyErr_SetString(PyExc_TypeError, - "integer expected"); - return NULL; - } - buf = (void *)PyLong_AsVoidPtr(value); - if (PyErr_Occurred()) - return NULL; - return PyCData_AtAddress(type, buf); + void *buf; + if (!PyLong_Check(value)) { + PyErr_SetString(PyExc_TypeError, + "integer expected"); + return NULL; + } + buf = (void *)PyLong_AsVoidPtr(value); + if (PyErr_Occurred()) + return NULL; + return PyCData_AtAddress(type, buf); } static char from_buffer_doc[] = @@ -423,51 +423,51 @@ static PyObject * CDataType_from_buffer(PyObject *type, PyObject *args) { - void *buffer; - Py_ssize_t buffer_len; - Py_ssize_t offset = 0; - PyObject *obj, *result; - StgDictObject *dict = PyType_stgdict(type); - assert (dict); + void *buffer; + Py_ssize_t buffer_len; + Py_ssize_t offset = 0; + PyObject *obj, *result; + StgDictObject *dict = PyType_stgdict(type); + assert (dict); - if (!PyArg_ParseTuple(args, + if (!PyArg_ParseTuple(args, #if (PY_VERSION_HEX < 0x02050000) - "O|i:from_buffer", + "O|i:from_buffer", #else - "O|n:from_buffer", + "O|n:from_buffer", #endif - &obj, &offset)) - return NULL; + &obj, &offset)) + return NULL; - if (-1 == PyObject_AsWriteBuffer(obj, &buffer, &buffer_len)) - return NULL; + if (-1 == PyObject_AsWriteBuffer(obj, &buffer, &buffer_len)) + return NULL; - if (offset < 0) { - PyErr_SetString(PyExc_ValueError, - "offset cannot be negative"); - return NULL; - } - if (dict->size > buffer_len - offset) { - PyErr_Format(PyExc_ValueError, + if (offset < 0) { + PyErr_SetString(PyExc_ValueError, + "offset cannot be negative"); + return NULL; + } + if (dict->size > buffer_len - offset) { + PyErr_Format(PyExc_ValueError, #if (PY_VERSION_HEX < 0x02050000) - "Buffer size too small (%d instead of at least %d bytes)", + "Buffer size too small (%d instead of at least %d bytes)", #else - "Buffer size too small (%zd instead of at least %zd bytes)", + "Buffer size too small (%zd instead of at least %zd bytes)", #endif - buffer_len, dict->size + offset); - return NULL; - } - - result = PyCData_AtAddress(type, (char *)buffer + offset); - if (result == NULL) - return NULL; - - Py_INCREF(obj); - if (-1 == KeepRef((CDataObject *)result, -1, obj)) { - Py_DECREF(result); - return NULL; - } - return result; + buffer_len, dict->size + offset); + return NULL; + } + + result = PyCData_AtAddress(type, (char *)buffer + offset); + if (result == NULL) + return NULL; + + Py_INCREF(obj); + if (-1 == KeepRef((CDataObject *)result, -1, obj)) { + Py_DECREF(result); + return NULL; + } + return result; } static char from_buffer_copy_doc[] = @@ -479,48 +479,48 @@ static PyObject * CDataType_from_buffer_copy(PyObject *type, PyObject *args) { - const void *buffer; - Py_ssize_t buffer_len; - Py_ssize_t offset = 0; - PyObject *obj, *result; - StgDictObject *dict = PyType_stgdict(type); - assert (dict); + const void *buffer; + Py_ssize_t buffer_len; + Py_ssize_t offset = 0; + PyObject *obj, *result; + StgDictObject *dict = PyType_stgdict(type); + assert (dict); - if (!PyArg_ParseTuple(args, + if (!PyArg_ParseTuple(args, #if (PY_VERSION_HEX < 0x02050000) - "O|i:from_buffer", + "O|i:from_buffer", #else - "O|n:from_buffer", + "O|n:from_buffer", #endif - &obj, &offset)) - return NULL; + &obj, &offset)) + return NULL; - if (-1 == PyObject_AsReadBuffer(obj, (const void**)&buffer, &buffer_len)) - return NULL; + if (-1 == PyObject_AsReadBuffer(obj, (const void**)&buffer, &buffer_len)) + return NULL; - if (offset < 0) { - PyErr_SetString(PyExc_ValueError, - "offset cannot be negative"); - return NULL; - } + if (offset < 0) { + PyErr_SetString(PyExc_ValueError, + "offset cannot be negative"); + return NULL; + } - if (dict->size > buffer_len - offset) { - PyErr_Format(PyExc_ValueError, + if (dict->size > buffer_len - offset) { + PyErr_Format(PyExc_ValueError, #if (PY_VERSION_HEX < 0x02050000) - "Buffer size too small (%d instead of at least %d bytes)", + "Buffer size too small (%d instead of at least %d bytes)", #else - "Buffer size too small (%zd instead of at least %zd bytes)", + "Buffer size too small (%zd instead of at least %zd bytes)", #endif - buffer_len, dict->size + offset); - return NULL; - } - - result = GenericPyCData_new((PyTypeObject *)type, NULL, NULL); - if (result == NULL) - return NULL; - memcpy(((CDataObject *)result)->b_ptr, - (char *)buffer+offset, dict->size); - return result; + buffer_len, dict->size + offset); + return NULL; + } + + result = GenericPyCData_new((PyTypeObject *)type, NULL, NULL); + if (result == NULL) + return NULL; + memcpy(((CDataObject *)result)->b_ptr, + (char *)buffer+offset, dict->size); + return result; } static char in_dll_doc[] = @@ -529,55 +529,55 @@ static PyObject * CDataType_in_dll(PyObject *type, PyObject *args) { - PyObject *dll; - char *name; - PyObject *obj; - void *handle; - void *address; - - if (!PyArg_ParseTuple(args, "Os:in_dll", &dll, &name)) - return NULL; - - obj = PyObject_GetAttrString(dll, "_handle"); - if (!obj) - return NULL; - if (!PyLong_Check(obj)) { - PyErr_SetString(PyExc_TypeError, - "the _handle attribute of the second argument must be an integer"); - Py_DECREF(obj); - return NULL; - } - handle = (void *)PyLong_AsVoidPtr(obj); - Py_DECREF(obj); - if (PyErr_Occurred()) { - PyErr_SetString(PyExc_ValueError, - "could not convert the _handle attribute to a pointer"); - return NULL; - } + PyObject *dll; + char *name; + PyObject *obj; + void *handle; + void *address; + + if (!PyArg_ParseTuple(args, "Os:in_dll", &dll, &name)) + return NULL; + + obj = PyObject_GetAttrString(dll, "_handle"); + if (!obj) + return NULL; + if (!PyLong_Check(obj)) { + PyErr_SetString(PyExc_TypeError, + "the _handle attribute of the second argument must be an integer"); + Py_DECREF(obj); + return NULL; + } + handle = (void *)PyLong_AsVoidPtr(obj); + Py_DECREF(obj); + if (PyErr_Occurred()) { + PyErr_SetString(PyExc_ValueError, + "could not convert the _handle attribute to a pointer"); + return NULL; + } #ifdef MS_WIN32 - address = (void *)GetProcAddress(handle, name); - if (!address) { - PyErr_Format(PyExc_ValueError, - "symbol '%s' not found", - name); - return NULL; - } + address = (void *)GetProcAddress(handle, name); + if (!address) { + PyErr_Format(PyExc_ValueError, + "symbol '%s' not found", + name); + return NULL; + } #else - address = (void *)ctypes_dlsym(handle, name); - if (!address) { + address = (void *)ctypes_dlsym(handle, name); + if (!address) { #ifdef __CYGWIN__ /* dlerror() isn't very helpful on cygwin */ - PyErr_Format(PyExc_ValueError, - "symbol '%s' not found (%s) ", - name); + PyErr_Format(PyExc_ValueError, + "symbol '%s' not found (%s) ", + name); #else - PyErr_SetString(PyExc_ValueError, ctypes_dlerror()); + PyErr_SetString(PyExc_ValueError, ctypes_dlerror()); #endif - return NULL; - } + return NULL; + } #endif - return PyCData_AtAddress(type, address); + return PyCData_AtAddress(type, address); } static char from_param_doc[] = @@ -586,210 +586,210 @@ static PyObject * CDataType_from_param(PyObject *type, PyObject *value) { - PyObject *as_parameter; - if (1 == PyObject_IsInstance(value, type)) { - Py_INCREF(value); - return value; - } - if (PyCArg_CheckExact(value)) { - PyCArgObject *p = (PyCArgObject *)value; - PyObject *ob = p->obj; - const char *ob_name; - StgDictObject *dict; - dict = PyType_stgdict(type); - - /* If we got a PyCArgObject, we must check if the object packed in it - is an instance of the type's dict->proto */ - if(dict && ob - && PyObject_IsInstance(ob, dict->proto)) { - Py_INCREF(value); - return value; - } - ob_name = (ob) ? Py_TYPE(ob)->tp_name : "???"; - PyErr_Format(PyExc_TypeError, - "expected %s instance instead of pointer to %s", - ((PyTypeObject *)type)->tp_name, ob_name); - return NULL; - } - - as_parameter = PyObject_GetAttrString(value, "_as_parameter_"); - if (as_parameter) { - value = CDataType_from_param(type, as_parameter); - Py_DECREF(as_parameter); - return value; - } - PyErr_Format(PyExc_TypeError, - "expected %s instance instead of %s", - ((PyTypeObject *)type)->tp_name, - Py_TYPE(value)->tp_name); - return NULL; + PyObject *as_parameter; + if (1 == PyObject_IsInstance(value, type)) { + Py_INCREF(value); + return value; + } + if (PyCArg_CheckExact(value)) { + PyCArgObject *p = (PyCArgObject *)value; + PyObject *ob = p->obj; + const char *ob_name; + StgDictObject *dict; + dict = PyType_stgdict(type); + + /* If we got a PyCArgObject, we must check if the object packed in it + is an instance of the type's dict->proto */ + if(dict && ob + && PyObject_IsInstance(ob, dict->proto)) { + Py_INCREF(value); + return value; + } + ob_name = (ob) ? Py_TYPE(ob)->tp_name : "???"; + PyErr_Format(PyExc_TypeError, + "expected %s instance instead of pointer to %s", + ((PyTypeObject *)type)->tp_name, ob_name); + return NULL; + } + + as_parameter = PyObject_GetAttrString(value, "_as_parameter_"); + if (as_parameter) { + value = CDataType_from_param(type, as_parameter); + Py_DECREF(as_parameter); + return value; + } + PyErr_Format(PyExc_TypeError, + "expected %s instance instead of %s", + ((PyTypeObject *)type)->tp_name, + Py_TYPE(value)->tp_name); + return NULL; } static PyMethodDef CDataType_methods[] = { - { "from_param", CDataType_from_param, METH_O, from_param_doc }, - { "from_address", CDataType_from_address, METH_O, from_address_doc }, - { "from_buffer", CDataType_from_buffer, METH_VARARGS, from_buffer_doc, }, - { "from_buffer_copy", CDataType_from_buffer_copy, METH_VARARGS, from_buffer_copy_doc, }, - { "in_dll", CDataType_in_dll, METH_VARARGS, in_dll_doc }, - { NULL, NULL }, + { "from_param", CDataType_from_param, METH_O, from_param_doc }, + { "from_address", CDataType_from_address, METH_O, from_address_doc }, + { "from_buffer", CDataType_from_buffer, METH_VARARGS, from_buffer_doc, }, + { "from_buffer_copy", CDataType_from_buffer_copy, METH_VARARGS, from_buffer_copy_doc, }, + { "in_dll", CDataType_in_dll, METH_VARARGS, in_dll_doc }, + { NULL, NULL }, }; static PyObject * CDataType_repeat(PyObject *self, Py_ssize_t length) { - if (length < 0) - return PyErr_Format(PyExc_ValueError, - "Array length must be >= 0, not %zd", - length); - return PyCArrayType_from_ctype(self, length); + if (length < 0) + return PyErr_Format(PyExc_ValueError, + "Array length must be >= 0, not %zd", + length); + return PyCArrayType_from_ctype(self, length); } static PySequenceMethods CDataType_as_sequence = { - 0, /* inquiry sq_length; */ - 0, /* binaryfunc sq_concat; */ - CDataType_repeat, /* intargfunc sq_repeat; */ - 0, /* intargfunc sq_item; */ - 0, /* intintargfunc sq_slice; */ - 0, /* intobjargproc sq_ass_item; */ - 0, /* intintobjargproc sq_ass_slice; */ - 0, /* objobjproc sq_contains; */ - - 0, /* binaryfunc sq_inplace_concat; */ - 0, /* intargfunc sq_inplace_repeat; */ + 0, /* inquiry sq_length; */ + 0, /* binaryfunc sq_concat; */ + CDataType_repeat, /* intargfunc sq_repeat; */ + 0, /* intargfunc sq_item; */ + 0, /* intintargfunc sq_slice; */ + 0, /* intobjargproc sq_ass_item; */ + 0, /* intintobjargproc sq_ass_slice; */ + 0, /* objobjproc sq_contains; */ + + 0, /* binaryfunc sq_inplace_concat; */ + 0, /* intargfunc sq_inplace_repeat; */ }; static int CDataType_clear(PyTypeObject *self) { - StgDictObject *dict = PyType_stgdict((PyObject *)self); - if (dict) - Py_CLEAR(dict->proto); - return PyType_Type.tp_clear((PyObject *)self); + StgDictObject *dict = PyType_stgdict((PyObject *)self); + if (dict) + Py_CLEAR(dict->proto); + return PyType_Type.tp_clear((PyObject *)self); } static int CDataType_traverse(PyTypeObject *self, visitproc visit, void *arg) { - StgDictObject *dict = PyType_stgdict((PyObject *)self); - if (dict) - Py_VISIT(dict->proto); - return PyType_Type.tp_traverse((PyObject *)self, visit, arg); + StgDictObject *dict = PyType_stgdict((PyObject *)self); + if (dict) + Py_VISIT(dict->proto); + return PyType_Type.tp_traverse((PyObject *)self, visit, arg); } static int PyCStructType_setattro(PyObject *self, PyObject *key, PyObject *value) { - /* XXX Should we disallow deleting _fields_? */ - if (-1 == PyType_Type.tp_setattro(self, key, value)) - return -1; - - if (value && PyUnicode_Check(key) && - /* XXX struni _PyUnicode_AsString can fail (also in other places)! */ - 0 == strcmp(_PyUnicode_AsString(key), "_fields_")) - return PyCStructUnionType_update_stgdict(self, value, 1); - return 0; + /* XXX Should we disallow deleting _fields_? */ + if (-1 == PyType_Type.tp_setattro(self, key, value)) + return -1; + + if (value && PyUnicode_Check(key) && + /* XXX struni _PyUnicode_AsString can fail (also in other places)! */ + 0 == strcmp(_PyUnicode_AsString(key), "_fields_")) + return PyCStructUnionType_update_stgdict(self, value, 1); + return 0; } static int UnionType_setattro(PyObject *self, PyObject *key, PyObject *value) { - /* XXX Should we disallow deleting _fields_? */ - if (-1 == PyObject_GenericSetAttr(self, key, value)) - return -1; - - if (PyUnicode_Check(key) && - 0 == strcmp(_PyUnicode_AsString(key), "_fields_")) - return PyCStructUnionType_update_stgdict(self, value, 0); - return 0; + /* XXX Should we disallow deleting _fields_? */ + if (-1 == PyObject_GenericSetAttr(self, key, value)) + return -1; + + if (PyUnicode_Check(key) && + 0 == strcmp(_PyUnicode_AsString(key), "_fields_")) + return PyCStructUnionType_update_stgdict(self, value, 0); + return 0; } PyTypeObject PyCStructType_Type = { - PyVarObject_HEAD_INIT(NULL, 0) - "_ctypes.PyCStructType", /* tp_name */ - 0, /* tp_basicsize */ - 0, /* tp_itemsize */ - 0, /* tp_dealloc */ - 0, /* tp_print */ - 0, /* tp_getattr */ - 0, /* tp_setattr */ - 0, /* tp_reserved */ - 0, /* tp_repr */ - 0, /* tp_as_number */ - &CDataType_as_sequence, /* tp_as_sequence */ - 0, /* tp_as_mapping */ - 0, /* tp_hash */ - 0, /* tp_call */ - 0, /* tp_str */ - 0, /* tp_getattro */ - PyCStructType_setattro, /* tp_setattro */ - 0, /* tp_as_buffer */ - Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC, /* tp_flags */ - "metatype for the CData Objects", /* tp_doc */ - (traverseproc)CDataType_traverse, /* tp_traverse */ - (inquiry)CDataType_clear, /* tp_clear */ - 0, /* tp_richcompare */ - 0, /* tp_weaklistoffset */ - 0, /* tp_iter */ - 0, /* tp_iternext */ - CDataType_methods, /* tp_methods */ - 0, /* tp_members */ - 0, /* tp_getset */ - 0, /* tp_base */ - 0, /* tp_dict */ - 0, /* tp_descr_get */ - 0, /* tp_descr_set */ - 0, /* tp_dictoffset */ - 0, /* tp_init */ - 0, /* tp_alloc */ - PyCStructType_new, /* tp_new */ - 0, /* tp_free */ + PyVarObject_HEAD_INIT(NULL, 0) + "_ctypes.PyCStructType", /* tp_name */ + 0, /* tp_basicsize */ + 0, /* tp_itemsize */ + 0, /* tp_dealloc */ + 0, /* tp_print */ + 0, /* tp_getattr */ + 0, /* tp_setattr */ + 0, /* tp_reserved */ + 0, /* tp_repr */ + 0, /* tp_as_number */ + &CDataType_as_sequence, /* tp_as_sequence */ + 0, /* tp_as_mapping */ + 0, /* tp_hash */ + 0, /* tp_call */ + 0, /* tp_str */ + 0, /* tp_getattro */ + PyCStructType_setattro, /* tp_setattro */ + 0, /* tp_as_buffer */ + Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC, /* tp_flags */ + "metatype for the CData Objects", /* tp_doc */ + (traverseproc)CDataType_traverse, /* tp_traverse */ + (inquiry)CDataType_clear, /* tp_clear */ + 0, /* tp_richcompare */ + 0, /* tp_weaklistoffset */ + 0, /* tp_iter */ + 0, /* tp_iternext */ + CDataType_methods, /* tp_methods */ + 0, /* tp_members */ + 0, /* tp_getset */ + 0, /* tp_base */ + 0, /* tp_dict */ + 0, /* tp_descr_get */ + 0, /* tp_descr_set */ + 0, /* tp_dictoffset */ + 0, /* tp_init */ + 0, /* tp_alloc */ + PyCStructType_new, /* tp_new */ + 0, /* tp_free */ }; static PyTypeObject UnionType_Type = { - PyVarObject_HEAD_INIT(NULL, 0) - "_ctypes.UnionType", /* tp_name */ - 0, /* tp_basicsize */ - 0, /* tp_itemsize */ - 0, /* tp_dealloc */ - 0, /* tp_print */ - 0, /* tp_getattr */ - 0, /* tp_setattr */ - 0, /* tp_reserved */ - 0, /* tp_repr */ - 0, /* tp_as_number */ - &CDataType_as_sequence, /* tp_as_sequence */ - 0, /* tp_as_mapping */ - 0, /* tp_hash */ - 0, /* tp_call */ - 0, /* tp_str */ - 0, /* tp_getattro */ - UnionType_setattro, /* tp_setattro */ - 0, /* tp_as_buffer */ - Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC, /* tp_flags */ - "metatype for the CData Objects", /* tp_doc */ - (traverseproc)CDataType_traverse, /* tp_traverse */ - (inquiry)CDataType_clear, /* tp_clear */ - 0, /* tp_richcompare */ - 0, /* tp_weaklistoffset */ - 0, /* tp_iter */ - 0, /* tp_iternext */ - CDataType_methods, /* tp_methods */ - 0, /* tp_members */ - 0, /* tp_getset */ - 0, /* tp_base */ - 0, /* tp_dict */ - 0, /* tp_descr_get */ - 0, /* tp_descr_set */ - 0, /* tp_dictoffset */ - 0, /* tp_init */ - 0, /* tp_alloc */ - UnionType_new, /* tp_new */ - 0, /* tp_free */ + PyVarObject_HEAD_INIT(NULL, 0) + "_ctypes.UnionType", /* tp_name */ + 0, /* tp_basicsize */ + 0, /* tp_itemsize */ + 0, /* tp_dealloc */ + 0, /* tp_print */ + 0, /* tp_getattr */ + 0, /* tp_setattr */ + 0, /* tp_reserved */ + 0, /* tp_repr */ + 0, /* tp_as_number */ + &CDataType_as_sequence, /* tp_as_sequence */ + 0, /* tp_as_mapping */ + 0, /* tp_hash */ + 0, /* tp_call */ + 0, /* tp_str */ + 0, /* tp_getattro */ + UnionType_setattro, /* tp_setattro */ + 0, /* tp_as_buffer */ + Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC, /* tp_flags */ + "metatype for the CData Objects", /* tp_doc */ + (traverseproc)CDataType_traverse, /* tp_traverse */ + (inquiry)CDataType_clear, /* tp_clear */ + 0, /* tp_richcompare */ + 0, /* tp_weaklistoffset */ + 0, /* tp_iter */ + 0, /* tp_iternext */ + CDataType_methods, /* tp_methods */ + 0, /* tp_members */ + 0, /* tp_getset */ + 0, /* tp_base */ + 0, /* tp_dict */ + 0, /* tp_descr_get */ + 0, /* tp_descr_set */ + 0, /* tp_dictoffset */ + 0, /* tp_init */ + 0, /* tp_alloc */ + UnionType_new, /* tp_new */ + 0, /* tp_free */ }; - + /******************************************************************/ /* @@ -809,124 +809,124 @@ static int PyCPointerType_SetProto(StgDictObject *stgdict, PyObject *proto) { - if (!proto || !PyType_Check(proto)) { - PyErr_SetString(PyExc_TypeError, - "_type_ must be a type"); - return -1; - } - if (!PyType_stgdict(proto)) { - PyErr_SetString(PyExc_TypeError, - "_type_ must have storage info"); - return -1; - } - Py_INCREF(proto); - Py_XDECREF(stgdict->proto); - stgdict->proto = proto; - return 0; + if (!proto || !PyType_Check(proto)) { + PyErr_SetString(PyExc_TypeError, + "_type_ must be a type"); + return -1; + } + if (!PyType_stgdict(proto)) { + PyErr_SetString(PyExc_TypeError, + "_type_ must have storage info"); + return -1; + } + Py_INCREF(proto); + Py_XDECREF(stgdict->proto); + stgdict->proto = proto; + return 0; } static PyCArgObject * PyCPointerType_paramfunc(CDataObject *self) { - PyCArgObject *parg; + PyCArgObject *parg; - parg = PyCArgObject_new(); - if (parg == NULL) - return NULL; - - parg->tag = 'P'; - parg->pffi_type = &ffi_type_pointer; - Py_INCREF(self); - parg->obj = (PyObject *)self; - parg->value.p = *(void **)self->b_ptr; - return parg; + parg = PyCArgObject_new(); + if (parg == NULL) + return NULL; + + parg->tag = 'P'; + parg->pffi_type = &ffi_type_pointer; + Py_INCREF(self); + parg->obj = (PyObject *)self; + parg->value.p = *(void **)self->b_ptr; + return parg; } static PyObject * PyCPointerType_new(PyTypeObject *type, PyObject *args, PyObject *kwds) { - PyTypeObject *result; - StgDictObject *stgdict; - PyObject *proto; - PyObject *typedict; - - typedict = PyTuple_GetItem(args, 2); - if (!typedict) - return NULL; + PyTypeObject *result; + StgDictObject *stgdict; + PyObject *proto; + PyObject *typedict; + + typedict = PyTuple_GetItem(args, 2); + if (!typedict) + return NULL; /* stgdict items size, align, length contain info about pointers itself, stgdict->proto has info about the pointed to type! */ - stgdict = (StgDictObject *)PyObject_CallObject( - (PyObject *)&PyCStgDict_Type, NULL); - if (!stgdict) - return NULL; - stgdict->size = sizeof(void *); - stgdict->align = _ctypes_get_fielddesc("P")->pffi_type->alignment; - stgdict->length = 1; - stgdict->ffi_type_pointer = ffi_type_pointer; - stgdict->paramfunc = PyCPointerType_paramfunc; - stgdict->flags |= TYPEFLAG_ISPOINTER; - - proto = PyDict_GetItemString(typedict, "_type_"); /* Borrowed ref */ - if (proto && -1 == PyCPointerType_SetProto(stgdict, proto)) { - Py_DECREF((PyObject *)stgdict); - return NULL; - } - - if (proto) { - StgDictObject *itemdict = PyType_stgdict(proto); - assert(itemdict); - /* If itemdict->format is NULL, then this is a pointer to an - incomplete type. We create a generic format string - 'pointer to bytes' in this case. XXX Better would be to - fix the format string later... - */ - stgdict->format = _ctypes_alloc_format_string("&", - itemdict->format ? itemdict->format : "B"); - if (stgdict->format == NULL) { - Py_DECREF((PyObject *)stgdict); - return NULL; - } - } - - /* create the new instance (which is a class, - since we are a metatype!) */ - result = (PyTypeObject *)PyType_Type.tp_new(type, args, kwds); - if (result == NULL) { - Py_DECREF((PyObject *)stgdict); - return NULL; - } - - /* replace the class dict by our updated spam dict */ - if (-1 == PyDict_Update((PyObject *)stgdict, result->tp_dict)) { - Py_DECREF(result); - Py_DECREF((PyObject *)stgdict); - return NULL; - } - Py_DECREF(result->tp_dict); - result->tp_dict = (PyObject *)stgdict; + stgdict = (StgDictObject *)PyObject_CallObject( + (PyObject *)&PyCStgDict_Type, NULL); + if (!stgdict) + return NULL; + stgdict->size = sizeof(void *); + stgdict->align = _ctypes_get_fielddesc("P")->pffi_type->alignment; + stgdict->length = 1; + stgdict->ffi_type_pointer = ffi_type_pointer; + stgdict->paramfunc = PyCPointerType_paramfunc; + stgdict->flags |= TYPEFLAG_ISPOINTER; + + proto = PyDict_GetItemString(typedict, "_type_"); /* Borrowed ref */ + if (proto && -1 == PyCPointerType_SetProto(stgdict, proto)) { + Py_DECREF((PyObject *)stgdict); + return NULL; + } + + if (proto) { + StgDictObject *itemdict = PyType_stgdict(proto); + assert(itemdict); + /* If itemdict->format is NULL, then this is a pointer to an + incomplete type. We create a generic format string + 'pointer to bytes' in this case. XXX Better would be to + fix the format string later... + */ + stgdict->format = _ctypes_alloc_format_string("&", + itemdict->format ? itemdict->format : "B"); + if (stgdict->format == NULL) { + Py_DECREF((PyObject *)stgdict); + return NULL; + } + } + + /* create the new instance (which is a class, + since we are a metatype!) */ + result = (PyTypeObject *)PyType_Type.tp_new(type, args, kwds); + if (result == NULL) { + Py_DECREF((PyObject *)stgdict); + return NULL; + } + + /* replace the class dict by our updated spam dict */ + if (-1 == PyDict_Update((PyObject *)stgdict, result->tp_dict)) { + Py_DECREF(result); + Py_DECREF((PyObject *)stgdict); + return NULL; + } + Py_DECREF(result->tp_dict); + result->tp_dict = (PyObject *)stgdict; - return (PyObject *)result; + return (PyObject *)result; } static PyObject * PyCPointerType_set_type(PyTypeObject *self, PyObject *type) { - StgDictObject *dict; + StgDictObject *dict; - dict = PyType_stgdict((PyObject *)self); - assert(dict); + dict = PyType_stgdict((PyObject *)self); + assert(dict); - if (-1 == PyCPointerType_SetProto(dict, type)) - return NULL; + if (-1 == PyCPointerType_SetProto(dict, type)) + return NULL; - if (-1 == PyDict_SetItemString((PyObject *)dict, "_type_", type)) - return NULL; + if (-1 == PyDict_SetItemString((PyObject *)dict, "_type_", type)) + return NULL; - Py_INCREF(Py_None); - return Py_None; + Py_INCREF(Py_None); + return Py_None; } static PyObject *_byref(PyObject *); @@ -934,98 +934,98 @@ static PyObject * PyCPointerType_from_param(PyObject *type, PyObject *value) { - StgDictObject *typedict; + StgDictObject *typedict; - if (value == Py_None) { - /* ConvParam will convert to a NULL pointer later */ - Py_INCREF(value); - return value; - } - - typedict = PyType_stgdict(type); - assert(typedict); /* Cannot be NULL for pointer types */ - - /* If we expect POINTER(), but receive a instance, accept - it by calling byref(). - */ - switch (PyObject_IsInstance(value, typedict->proto)) { - case 1: - Py_INCREF(value); /* _byref steals a refcount */ - return _byref(value); - case -1: - PyErr_Clear(); - break; - default: - break; - } - - if (PointerObject_Check(value) || ArrayObject_Check(value)) { - /* Array instances are also pointers when - the item types are the same. - */ - StgDictObject *v = PyObject_stgdict(value); - assert(v); /* Cannot be NULL for pointer or array objects */ - if (PyObject_IsSubclass(v->proto, typedict->proto)) { - Py_INCREF(value); - return value; - } - } - return CDataType_from_param(type, value); + if (value == Py_None) { + /* ConvParam will convert to a NULL pointer later */ + Py_INCREF(value); + return value; + } + + typedict = PyType_stgdict(type); + assert(typedict); /* Cannot be NULL for pointer types */ + + /* If we expect POINTER(), but receive a instance, accept + it by calling byref(). + */ + switch (PyObject_IsInstance(value, typedict->proto)) { + case 1: + Py_INCREF(value); /* _byref steals a refcount */ + return _byref(value); + case -1: + PyErr_Clear(); + break; + default: + break; + } + + if (PointerObject_Check(value) || ArrayObject_Check(value)) { + /* Array instances are also pointers when + the item types are the same. + */ + StgDictObject *v = PyObject_stgdict(value); + assert(v); /* Cannot be NULL for pointer or array objects */ + if (PyObject_IsSubclass(v->proto, typedict->proto)) { + Py_INCREF(value); + return value; + } + } + return CDataType_from_param(type, value); } static PyMethodDef PyCPointerType_methods[] = { - { "from_address", CDataType_from_address, METH_O, from_address_doc }, - { "from_buffer", CDataType_from_buffer, METH_VARARGS, from_buffer_doc, }, - { "from_buffer_copy", CDataType_from_buffer_copy, METH_VARARGS, from_buffer_copy_doc, }, - { "in_dll", CDataType_in_dll, METH_VARARGS, in_dll_doc}, - { "from_param", (PyCFunction)PyCPointerType_from_param, METH_O, from_param_doc}, - { "set_type", (PyCFunction)PyCPointerType_set_type, METH_O }, - { NULL, NULL }, + { "from_address", CDataType_from_address, METH_O, from_address_doc }, + { "from_buffer", CDataType_from_buffer, METH_VARARGS, from_buffer_doc, }, + { "from_buffer_copy", CDataType_from_buffer_copy, METH_VARARGS, from_buffer_copy_doc, }, + { "in_dll", CDataType_in_dll, METH_VARARGS, in_dll_doc}, + { "from_param", (PyCFunction)PyCPointerType_from_param, METH_O, from_param_doc}, + { "set_type", (PyCFunction)PyCPointerType_set_type, METH_O }, + { NULL, NULL }, }; PyTypeObject PyCPointerType_Type = { - PyVarObject_HEAD_INIT(NULL, 0) - "_ctypes.PyCPointerType", /* tp_name */ - 0, /* tp_basicsize */ - 0, /* tp_itemsize */ - 0, /* tp_dealloc */ - 0, /* tp_print */ - 0, /* tp_getattr */ - 0, /* tp_setattr */ - 0, /* tp_reserved */ - 0, /* tp_repr */ - 0, /* tp_as_number */ - &CDataType_as_sequence, /* tp_as_sequence */ - 0, /* tp_as_mapping */ - 0, /* tp_hash */ - 0, /* tp_call */ - 0, /* tp_str */ - 0, /* tp_getattro */ - 0, /* tp_setattro */ - 0, /* tp_as_buffer */ - Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC, /* tp_flags */ - "metatype for the Pointer Objects", /* tp_doc */ - (traverseproc)CDataType_traverse, /* tp_traverse */ - (inquiry)CDataType_clear, /* tp_clear */ - 0, /* tp_richcompare */ - 0, /* tp_weaklistoffset */ - 0, /* tp_iter */ - 0, /* tp_iternext */ - PyCPointerType_methods, /* tp_methods */ - 0, /* tp_members */ - 0, /* tp_getset */ - 0, /* tp_base */ - 0, /* tp_dict */ - 0, /* tp_descr_get */ - 0, /* tp_descr_set */ - 0, /* tp_dictoffset */ - 0, /* tp_init */ - 0, /* tp_alloc */ - PyCPointerType_new, /* tp_new */ - 0, /* tp_free */ + PyVarObject_HEAD_INIT(NULL, 0) + "_ctypes.PyCPointerType", /* tp_name */ + 0, /* tp_basicsize */ + 0, /* tp_itemsize */ + 0, /* tp_dealloc */ + 0, /* tp_print */ + 0, /* tp_getattr */ + 0, /* tp_setattr */ + 0, /* tp_reserved */ + 0, /* tp_repr */ + 0, /* tp_as_number */ + &CDataType_as_sequence, /* tp_as_sequence */ + 0, /* tp_as_mapping */ + 0, /* tp_hash */ + 0, /* tp_call */ + 0, /* tp_str */ + 0, /* tp_getattro */ + 0, /* tp_setattro */ + 0, /* tp_as_buffer */ + Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC, /* tp_flags */ + "metatype for the Pointer Objects", /* tp_doc */ + (traverseproc)CDataType_traverse, /* tp_traverse */ + (inquiry)CDataType_clear, /* tp_clear */ + 0, /* tp_richcompare */ + 0, /* tp_weaklistoffset */ + 0, /* tp_iter */ + 0, /* tp_iternext */ + PyCPointerType_methods, /* tp_methods */ + 0, /* tp_members */ + 0, /* tp_getset */ + 0, /* tp_base */ + 0, /* tp_dict */ + 0, /* tp_descr_get */ + 0, /* tp_descr_set */ + 0, /* tp_dictoffset */ + 0, /* tp_init */ + 0, /* tp_alloc */ + PyCPointerType_new, /* tp_new */ + 0, /* tp_free */ }; - + /******************************************************************/ /* PyCArrayType_Type @@ -1038,152 +1038,152 @@ static int CharArray_set_raw(CDataObject *self, PyObject *value) { - char *ptr; - Py_ssize_t size; - Py_buffer view; - - if (PyObject_GetBuffer(value, &view, PyBUF_SIMPLE) < 0) - return -1; - size = view.len; - ptr = view.buf; - if (size > self->b_size) { - PyErr_SetString(PyExc_ValueError, - "string too long"); - goto fail; - } + char *ptr; + Py_ssize_t size; + Py_buffer view; + + if (PyObject_GetBuffer(value, &view, PyBUF_SIMPLE) < 0) + return -1; + size = view.len; + ptr = view.buf; + if (size > self->b_size) { + PyErr_SetString(PyExc_ValueError, + "string too long"); + goto fail; + } - memcpy(self->b_ptr, ptr, size); + memcpy(self->b_ptr, ptr, size); - PyBuffer_Release(&view); - return 0; + PyBuffer_Release(&view); + return 0; fail: - PyBuffer_Release(&view); - return -1; + PyBuffer_Release(&view); + return -1; } static PyObject * CharArray_get_raw(CDataObject *self) { - return PyBytes_FromStringAndSize(self->b_ptr, self->b_size); + return PyBytes_FromStringAndSize(self->b_ptr, self->b_size); } static PyObject * CharArray_get_value(CDataObject *self) { - int i; - char *ptr = self->b_ptr; - for (i = 0; i < self->b_size; ++i) - if (*ptr++ == '\0') - break; - return PyBytes_FromStringAndSize(self->b_ptr, i); + int i; + char *ptr = self->b_ptr; + for (i = 0; i < self->b_size; ++i) + if (*ptr++ == '\0') + break; + return PyBytes_FromStringAndSize(self->b_ptr, i); } static int CharArray_set_value(CDataObject *self, PyObject *value) { - char *ptr; - Py_ssize_t size; + char *ptr; + Py_ssize_t size; + + if (value == NULL) { + PyErr_SetString(PyExc_TypeError, + "can't delete attribute"); + return -1; + } - if (value == NULL) { - PyErr_SetString(PyExc_TypeError, - "can't delete attribute"); - return -1; - } - - if (PyUnicode_Check(value)) { - value = PyUnicode_AsEncodedString(value, - _ctypes_conversion_encoding, - _ctypes_conversion_errors); - if (!value) - return -1; - } else if (!PyBytes_Check(value)) { - PyErr_Format(PyExc_TypeError, - "str/bytes expected instead of %s instance", - Py_TYPE(value)->tp_name); - return -1; - } else - Py_INCREF(value); - size = PyBytes_GET_SIZE(value); - if (size > self->b_size) { - PyErr_SetString(PyExc_ValueError, - "string too long"); - Py_DECREF(value); - return -1; - } - - ptr = PyBytes_AS_STRING(value); - memcpy(self->b_ptr, ptr, size); - if (size < self->b_size) - self->b_ptr[size] = '\0'; - Py_DECREF(value); + if (PyUnicode_Check(value)) { + value = PyUnicode_AsEncodedString(value, + _ctypes_conversion_encoding, + _ctypes_conversion_errors); + if (!value) + return -1; + } else if (!PyBytes_Check(value)) { + PyErr_Format(PyExc_TypeError, + "str/bytes expected instead of %s instance", + Py_TYPE(value)->tp_name); + return -1; + } else + Py_INCREF(value); + size = PyBytes_GET_SIZE(value); + if (size > self->b_size) { + PyErr_SetString(PyExc_ValueError, + "string too long"); + Py_DECREF(value); + return -1; + } - return 0; + ptr = PyBytes_AS_STRING(value); + memcpy(self->b_ptr, ptr, size); + if (size < self->b_size) + self->b_ptr[size] = '\0'; + Py_DECREF(value); + + return 0; } static PyGetSetDef CharArray_getsets[] = { - { "raw", (getter)CharArray_get_raw, (setter)CharArray_set_raw, - "value", NULL }, - { "value", (getter)CharArray_get_value, (setter)CharArray_set_value, - "string value"}, - { NULL, NULL } + { "raw", (getter)CharArray_get_raw, (setter)CharArray_set_raw, + "value", NULL }, + { "value", (getter)CharArray_get_value, (setter)CharArray_set_value, + "string value"}, + { NULL, NULL } }; #ifdef CTYPES_UNICODE static PyObject * WCharArray_get_value(CDataObject *self) { - unsigned int i; - wchar_t *ptr = (wchar_t *)self->b_ptr; - for (i = 0; i < self->b_size/sizeof(wchar_t); ++i) - if (*ptr++ == (wchar_t)0) - break; - return PyUnicode_FromWideChar((wchar_t *)self->b_ptr, i); + unsigned int i; + wchar_t *ptr = (wchar_t *)self->b_ptr; + for (i = 0; i < self->b_size/sizeof(wchar_t); ++i) + if (*ptr++ == (wchar_t)0) + break; + return PyUnicode_FromWideChar((wchar_t *)self->b_ptr, i); } static int WCharArray_set_value(CDataObject *self, PyObject *value) { - Py_ssize_t result = 0; + Py_ssize_t result = 0; - if (value == NULL) { - PyErr_SetString(PyExc_TypeError, - "can't delete attribute"); - return -1; - } - if (PyBytes_Check(value)) { - value = PyUnicode_FromEncodedObject(value, - _ctypes_conversion_encoding, - _ctypes_conversion_errors); - if (!value) - return -1; - } else if (!PyUnicode_Check(value)) { - PyErr_Format(PyExc_TypeError, - "unicode string expected instead of %s instance", - Py_TYPE(value)->tp_name); - return -1; - } else - Py_INCREF(value); - if ((unsigned)PyUnicode_GET_SIZE(value) > self->b_size/sizeof(wchar_t)) { - PyErr_SetString(PyExc_ValueError, - "string too long"); - result = -1; - goto done; - } - result = PyUnicode_AsWideChar((PyUnicodeObject *)value, - (wchar_t *)self->b_ptr, - self->b_size/sizeof(wchar_t)); - if (result >= 0 && (size_t)result < self->b_size/sizeof(wchar_t)) - ((wchar_t *)self->b_ptr)[result] = (wchar_t)0; + if (value == NULL) { + PyErr_SetString(PyExc_TypeError, + "can't delete attribute"); + return -1; + } + if (PyBytes_Check(value)) { + value = PyUnicode_FromEncodedObject(value, + _ctypes_conversion_encoding, + _ctypes_conversion_errors); + if (!value) + return -1; + } else if (!PyUnicode_Check(value)) { + PyErr_Format(PyExc_TypeError, + "unicode string expected instead of %s instance", + Py_TYPE(value)->tp_name); + return -1; + } else + Py_INCREF(value); + if ((unsigned)PyUnicode_GET_SIZE(value) > self->b_size/sizeof(wchar_t)) { + PyErr_SetString(PyExc_ValueError, + "string too long"); + result = -1; + goto done; + } + result = PyUnicode_AsWideChar((PyUnicodeObject *)value, + (wchar_t *)self->b_ptr, + self->b_size/sizeof(wchar_t)); + if (result >= 0 && (size_t)result < self->b_size/sizeof(wchar_t)) + ((wchar_t *)self->b_ptr)[result] = (wchar_t)0; done: - Py_DECREF(value); + Py_DECREF(value); - return result >= 0 ? 0 : -1; + return result >= 0 ? 0 : -1; } static PyGetSetDef WCharArray_getsets[] = { - { "value", (getter)WCharArray_get_value, (setter)WCharArray_set_value, - "string value"}, - { NULL, NULL } + { "value", (getter)WCharArray_get_value, (setter)WCharArray_set_value, + "string value"}, + { NULL, NULL } }; #endif @@ -1198,236 +1198,236 @@ static int add_methods(PyTypeObject *type, PyMethodDef *meth) { - PyObject *dict = type->tp_dict; - for (; meth->ml_name != NULL; meth++) { - PyObject *descr; - descr = PyDescr_NewMethod(type, meth); - if (descr == NULL) - return -1; - if (PyDict_SetItemString(dict,meth->ml_name, descr) < 0) - return -1; - Py_DECREF(descr); - } - return 0; + PyObject *dict = type->tp_dict; + for (; meth->ml_name != NULL; meth++) { + PyObject *descr; + descr = PyDescr_NewMethod(type, meth); + if (descr == NULL) + return -1; + if (PyDict_SetItemString(dict,meth->ml_name, descr) < 0) + return -1; + Py_DECREF(descr); + } + return 0; } static int add_members(PyTypeObject *type, PyMemberDef *memb) { - PyObject *dict = type->tp_dict; - for (; memb->name != NULL; memb++) { - PyObject *descr; - descr = PyDescr_NewMember(type, memb); - if (descr == NULL) - return -1; - if (PyDict_SetItemString(dict, memb->name, descr) < 0) - return -1; - Py_DECREF(descr); - } - return 0; + PyObject *dict = type->tp_dict; + for (; memb->name != NULL; memb++) { + PyObject *descr; + descr = PyDescr_NewMember(type, memb); + if (descr == NULL) + return -1; + if (PyDict_SetItemString(dict, memb->name, descr) < 0) + return -1; + Py_DECREF(descr); + } + return 0; } */ static int add_getset(PyTypeObject *type, PyGetSetDef *gsp) { - PyObject *dict = type->tp_dict; - for (; gsp->name != NULL; gsp++) { - PyObject *descr; - descr = PyDescr_NewGetSet(type, gsp); - if (descr == NULL) - return -1; - if (PyDict_SetItemString(dict, gsp->name, descr) < 0) - return -1; - Py_DECREF(descr); - } - return 0; + PyObject *dict = type->tp_dict; + for (; gsp->name != NULL; gsp++) { + PyObject *descr; + descr = PyDescr_NewGetSet(type, gsp); + if (descr == NULL) + return -1; + if (PyDict_SetItemString(dict, gsp->name, descr) < 0) + return -1; + Py_DECREF(descr); + } + return 0; } static PyCArgObject * PyCArrayType_paramfunc(CDataObject *self) { - PyCArgObject *p = PyCArgObject_new(); - if (p == NULL) - return NULL; - p->tag = 'P'; - p->pffi_type = &ffi_type_pointer; - p->value.p = (char *)self->b_ptr; - Py_INCREF(self); - p->obj = (PyObject *)self; - return p; + PyCArgObject *p = PyCArgObject_new(); + if (p == NULL) + return NULL; + p->tag = 'P'; + p->pffi_type = &ffi_type_pointer; + p->value.p = (char *)self->b_ptr; + Py_INCREF(self); + p->obj = (PyObject *)self; + return p; } static PyObject * PyCArrayType_new(PyTypeObject *type, PyObject *args, PyObject *kwds) { - PyTypeObject *result; - StgDictObject *stgdict; - StgDictObject *itemdict; - PyObject *proto; - PyObject *typedict; - long length; - int overflow; - Py_ssize_t itemsize, itemalign; - char buf[32]; - - typedict = PyTuple_GetItem(args, 2); - if (!typedict) - return NULL; - - proto = PyDict_GetItemString(typedict, "_length_"); /* Borrowed ref */ - if (!proto || !PyLong_Check(proto)) { - PyErr_SetString(PyExc_AttributeError, - "class must define a '_length_' attribute, " - "which must be a positive integer"); - return NULL; - } - length = PyLong_AsLongAndOverflow(proto, &overflow); - if (overflow) { - PyErr_SetString(PyExc_OverflowError, - "The '_length_' attribute is too large"); - return NULL; - } - - proto = PyDict_GetItemString(typedict, "_type_"); /* Borrowed ref */ - if (!proto) { - PyErr_SetString(PyExc_AttributeError, - "class must define a '_type_' attribute"); - return NULL; - } - - stgdict = (StgDictObject *)PyObject_CallObject( - (PyObject *)&PyCStgDict_Type, NULL); - if (!stgdict) - return NULL; - - itemdict = PyType_stgdict(proto); - if (!itemdict) { - PyErr_SetString(PyExc_TypeError, - "_type_ must have storage info"); - Py_DECREF((PyObject *)stgdict); - return NULL; - } - - assert(itemdict->format); - if (itemdict->format[0] == '(') { - sprintf(buf, "(%ld,", length); - stgdict->format = _ctypes_alloc_format_string(buf, itemdict->format+1); - } else { - sprintf(buf, "(%ld)", length); - stgdict->format = _ctypes_alloc_format_string(buf, itemdict->format); - } - if (stgdict->format == NULL) { - Py_DECREF((PyObject *)stgdict); - return NULL; - } - stgdict->ndim = itemdict->ndim + 1; - stgdict->shape = PyMem_Malloc(sizeof(Py_ssize_t *) * stgdict->ndim); - if (stgdict->shape == NULL) { - Py_DECREF((PyObject *)stgdict); - return NULL; - } - stgdict->shape[0] = length; - memmove(&stgdict->shape[1], itemdict->shape, - sizeof(Py_ssize_t) * (stgdict->ndim - 1)); - - itemsize = itemdict->size; - if (length * itemsize < 0) { - PyErr_SetString(PyExc_OverflowError, - "array too large"); - return NULL; - } - - itemalign = itemdict->align; - - if (itemdict->flags & (TYPEFLAG_ISPOINTER | TYPEFLAG_HASPOINTER)) - stgdict->flags |= TYPEFLAG_HASPOINTER; - - stgdict->size = itemsize * length; - stgdict->align = itemalign; - stgdict->length = length; - Py_INCREF(proto); - stgdict->proto = proto; - - stgdict->paramfunc = &PyCArrayType_paramfunc; - - /* Arrays are passed as pointers to function calls. */ - stgdict->ffi_type_pointer = ffi_type_pointer; - - /* create the new instance (which is a class, - since we are a metatype!) */ - result = (PyTypeObject *)PyType_Type.tp_new(type, args, kwds); - if (result == NULL) - return NULL; - - /* replace the class dict by our updated spam dict */ - if (-1 == PyDict_Update((PyObject *)stgdict, result->tp_dict)) { - Py_DECREF(result); - Py_DECREF((PyObject *)stgdict); - return NULL; - } - Py_DECREF(result->tp_dict); - result->tp_dict = (PyObject *)stgdict; - - /* Special case for character arrays. - A permanent annoyance: char arrays are also strings! - */ - if (itemdict->getfunc == _ctypes_get_fielddesc("c")->getfunc) { - if (-1 == add_getset(result, CharArray_getsets)) - return NULL; + PyTypeObject *result; + StgDictObject *stgdict; + StgDictObject *itemdict; + PyObject *proto; + PyObject *typedict; + long length; + int overflow; + Py_ssize_t itemsize, itemalign; + char buf[32]; + + typedict = PyTuple_GetItem(args, 2); + if (!typedict) + return NULL; + + proto = PyDict_GetItemString(typedict, "_length_"); /* Borrowed ref */ + if (!proto || !PyLong_Check(proto)) { + PyErr_SetString(PyExc_AttributeError, + "class must define a '_length_' attribute, " + "which must be a positive integer"); + return NULL; + } + length = PyLong_AsLongAndOverflow(proto, &overflow); + if (overflow) { + PyErr_SetString(PyExc_OverflowError, + "The '_length_' attribute is too large"); + return NULL; + } + + proto = PyDict_GetItemString(typedict, "_type_"); /* Borrowed ref */ + if (!proto) { + PyErr_SetString(PyExc_AttributeError, + "class must define a '_type_' attribute"); + return NULL; + } + + stgdict = (StgDictObject *)PyObject_CallObject( + (PyObject *)&PyCStgDict_Type, NULL); + if (!stgdict) + return NULL; + + itemdict = PyType_stgdict(proto); + if (!itemdict) { + PyErr_SetString(PyExc_TypeError, + "_type_ must have storage info"); + Py_DECREF((PyObject *)stgdict); + return NULL; + } + + assert(itemdict->format); + if (itemdict->format[0] == '(') { + sprintf(buf, "(%ld,", length); + stgdict->format = _ctypes_alloc_format_string(buf, itemdict->format+1); + } else { + sprintf(buf, "(%ld)", length); + stgdict->format = _ctypes_alloc_format_string(buf, itemdict->format); + } + if (stgdict->format == NULL) { + Py_DECREF((PyObject *)stgdict); + return NULL; + } + stgdict->ndim = itemdict->ndim + 1; + stgdict->shape = PyMem_Malloc(sizeof(Py_ssize_t *) * stgdict->ndim); + if (stgdict->shape == NULL) { + Py_DECREF((PyObject *)stgdict); + return NULL; + } + stgdict->shape[0] = length; + memmove(&stgdict->shape[1], itemdict->shape, + sizeof(Py_ssize_t) * (stgdict->ndim - 1)); + + itemsize = itemdict->size; + if (length * itemsize < 0) { + PyErr_SetString(PyExc_OverflowError, + "array too large"); + return NULL; + } + + itemalign = itemdict->align; + + if (itemdict->flags & (TYPEFLAG_ISPOINTER | TYPEFLAG_HASPOINTER)) + stgdict->flags |= TYPEFLAG_HASPOINTER; + + stgdict->size = itemsize * length; + stgdict->align = itemalign; + stgdict->length = length; + Py_INCREF(proto); + stgdict->proto = proto; + + stgdict->paramfunc = &PyCArrayType_paramfunc; + + /* Arrays are passed as pointers to function calls. */ + stgdict->ffi_type_pointer = ffi_type_pointer; + + /* create the new instance (which is a class, + since we are a metatype!) */ + result = (PyTypeObject *)PyType_Type.tp_new(type, args, kwds); + if (result == NULL) + return NULL; + + /* replace the class dict by our updated spam dict */ + if (-1 == PyDict_Update((PyObject *)stgdict, result->tp_dict)) { + Py_DECREF(result); + Py_DECREF((PyObject *)stgdict); + return NULL; + } + Py_DECREF(result->tp_dict); + result->tp_dict = (PyObject *)stgdict; + + /* Special case for character arrays. + A permanent annoyance: char arrays are also strings! + */ + if (itemdict->getfunc == _ctypes_get_fielddesc("c")->getfunc) { + if (-1 == add_getset(result, CharArray_getsets)) + return NULL; #ifdef CTYPES_UNICODE - } else if (itemdict->getfunc == _ctypes_get_fielddesc("u")->getfunc) { - if (-1 == add_getset(result, WCharArray_getsets)) - return NULL; + } else if (itemdict->getfunc == _ctypes_get_fielddesc("u")->getfunc) { + if (-1 == add_getset(result, WCharArray_getsets)) + return NULL; #endif - } + } - return (PyObject *)result; + return (PyObject *)result; } PyTypeObject PyCArrayType_Type = { - PyVarObject_HEAD_INIT(NULL, 0) - "_ctypes.PyCArrayType", /* tp_name */ - 0, /* tp_basicsize */ - 0, /* tp_itemsize */ - 0, /* tp_dealloc */ - 0, /* tp_print */ - 0, /* tp_getattr */ - 0, /* tp_setattr */ - 0, /* tp_reserved */ - 0, /* tp_repr */ - 0, /* tp_as_number */ - &CDataType_as_sequence, /* tp_as_sequence */ - 0, /* tp_as_mapping */ - 0, /* tp_hash */ - 0, /* tp_call */ - 0, /* tp_str */ - 0, /* tp_getattro */ - 0, /* tp_setattro */ - 0, /* tp_as_buffer */ - Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */ - "metatype for the Array Objects", /* tp_doc */ - 0, /* tp_traverse */ - 0, /* tp_clear */ - 0, /* tp_richcompare */ - 0, /* tp_weaklistoffset */ - 0, /* tp_iter */ - 0, /* tp_iternext */ - CDataType_methods, /* tp_methods */ - 0, /* tp_members */ - 0, /* tp_getset */ - 0, /* tp_base */ - 0, /* tp_dict */ - 0, /* tp_descr_get */ - 0, /* tp_descr_set */ - 0, /* tp_dictoffset */ - 0, /* tp_init */ - 0, /* tp_alloc */ - PyCArrayType_new, /* tp_new */ - 0, /* tp_free */ + PyVarObject_HEAD_INIT(NULL, 0) + "_ctypes.PyCArrayType", /* tp_name */ + 0, /* tp_basicsize */ + 0, /* tp_itemsize */ + 0, /* tp_dealloc */ + 0, /* tp_print */ + 0, /* tp_getattr */ + 0, /* tp_setattr */ + 0, /* tp_reserved */ + 0, /* tp_repr */ + 0, /* tp_as_number */ + &CDataType_as_sequence, /* tp_as_sequence */ + 0, /* tp_as_mapping */ + 0, /* tp_hash */ + 0, /* tp_call */ + 0, /* tp_str */ + 0, /* tp_getattro */ + 0, /* tp_setattro */ + 0, /* tp_as_buffer */ + Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */ + "metatype for the Array Objects", /* tp_doc */ + 0, /* tp_traverse */ + 0, /* tp_clear */ + 0, /* tp_richcompare */ + 0, /* tp_weaklistoffset */ + 0, /* tp_iter */ + 0, /* tp_iternext */ + CDataType_methods, /* tp_methods */ + 0, /* tp_members */ + 0, /* tp_getset */ + 0, /* tp_base */ + 0, /* tp_dict */ + 0, /* tp_descr_get */ + 0, /* tp_descr_set */ + 0, /* tp_dictoffset */ + 0, /* tp_init */ + 0, /* tp_alloc */ + PyCArrayType_new, /* tp_new */ + 0, /* tp_free */ }; - + /******************************************************************/ /* PyCSimpleType_Type @@ -1444,273 +1444,273 @@ static PyObject * c_wchar_p_from_param(PyObject *type, PyObject *value) { - PyObject *as_parameter; - if (value == Py_None) { - Py_INCREF(Py_None); - return Py_None; - } - if (PyUnicode_Check(value) || PyBytes_Check(value)) { - PyCArgObject *parg; - struct fielddesc *fd = _ctypes_get_fielddesc("Z"); - - parg = PyCArgObject_new(); - if (parg == NULL) - return NULL; - parg->pffi_type = &ffi_type_pointer; - parg->tag = 'Z'; - parg->obj = fd->setfunc(&parg->value, value, 0); - if (parg->obj == NULL) { - Py_DECREF(parg); - return NULL; - } - return (PyObject *)parg; - } - if (PyObject_IsInstance(value, type)) { - Py_INCREF(value); - return value; - } - if (ArrayObject_Check(value) || PointerObject_Check(value)) { - /* c_wchar array instance or pointer(c_wchar(...)) */ - StgDictObject *dt = PyObject_stgdict(value); - StgDictObject *dict; - assert(dt); /* Cannot be NULL for pointer or array objects */ - dict = dt && dt->proto ? PyType_stgdict(dt->proto) : NULL; - if (dict && (dict->setfunc == _ctypes_get_fielddesc("u")->setfunc)) { - Py_INCREF(value); - return value; - } - } - if (PyCArg_CheckExact(value)) { - /* byref(c_char(...)) */ - PyCArgObject *a = (PyCArgObject *)value; - StgDictObject *dict = PyObject_stgdict(a->obj); - if (dict && (dict->setfunc == _ctypes_get_fielddesc("u")->setfunc)) { - Py_INCREF(value); - return value; - } - } - - as_parameter = PyObject_GetAttrString(value, "_as_parameter_"); - if (as_parameter) { - value = c_wchar_p_from_param(type, as_parameter); - Py_DECREF(as_parameter); - return value; - } - /* XXX better message */ - PyErr_SetString(PyExc_TypeError, - "wrong type"); - return NULL; + PyObject *as_parameter; + if (value == Py_None) { + Py_INCREF(Py_None); + return Py_None; + } + if (PyUnicode_Check(value) || PyBytes_Check(value)) { + PyCArgObject *parg; + struct fielddesc *fd = _ctypes_get_fielddesc("Z"); + + parg = PyCArgObject_new(); + if (parg == NULL) + return NULL; + parg->pffi_type = &ffi_type_pointer; + parg->tag = 'Z'; + parg->obj = fd->setfunc(&parg->value, value, 0); + if (parg->obj == NULL) { + Py_DECREF(parg); + return NULL; + } + return (PyObject *)parg; + } + if (PyObject_IsInstance(value, type)) { + Py_INCREF(value); + return value; + } + if (ArrayObject_Check(value) || PointerObject_Check(value)) { + /* c_wchar array instance or pointer(c_wchar(...)) */ + StgDictObject *dt = PyObject_stgdict(value); + StgDictObject *dict; + assert(dt); /* Cannot be NULL for pointer or array objects */ + dict = dt && dt->proto ? PyType_stgdict(dt->proto) : NULL; + if (dict && (dict->setfunc == _ctypes_get_fielddesc("u")->setfunc)) { + Py_INCREF(value); + return value; + } + } + if (PyCArg_CheckExact(value)) { + /* byref(c_char(...)) */ + PyCArgObject *a = (PyCArgObject *)value; + StgDictObject *dict = PyObject_stgdict(a->obj); + if (dict && (dict->setfunc == _ctypes_get_fielddesc("u")->setfunc)) { + Py_INCREF(value); + return value; + } + } + + as_parameter = PyObject_GetAttrString(value, "_as_parameter_"); + if (as_parameter) { + value = c_wchar_p_from_param(type, as_parameter); + Py_DECREF(as_parameter); + return value; + } + /* XXX better message */ + PyErr_SetString(PyExc_TypeError, + "wrong type"); + return NULL; } static PyObject * c_char_p_from_param(PyObject *type, PyObject *value) { - PyObject *as_parameter; - if (value == Py_None) { - Py_INCREF(Py_None); - return Py_None; - } - if (PyBytes_Check(value) || PyUnicode_Check(value)) { - PyCArgObject *parg; - struct fielddesc *fd = _ctypes_get_fielddesc("z"); - - parg = PyCArgObject_new(); - if (parg == NULL) - return NULL; - parg->pffi_type = &ffi_type_pointer; - parg->tag = 'z'; - parg->obj = fd->setfunc(&parg->value, value, 0); - if (parg->obj == NULL) { - Py_DECREF(parg); - return NULL; - } - return (PyObject *)parg; - } - if (PyObject_IsInstance(value, type)) { - Py_INCREF(value); - return value; - } - if (ArrayObject_Check(value) || PointerObject_Check(value)) { - /* c_char array instance or pointer(c_char(...)) */ - StgDictObject *dt = PyObject_stgdict(value); - StgDictObject *dict; - assert(dt); /* Cannot be NULL for pointer or array objects */ - dict = dt && dt->proto ? PyType_stgdict(dt->proto) : NULL; - if (dict && (dict->setfunc == _ctypes_get_fielddesc("c")->setfunc)) { - Py_INCREF(value); - return value; - } - } - if (PyCArg_CheckExact(value)) { - /* byref(c_char(...)) */ - PyCArgObject *a = (PyCArgObject *)value; - StgDictObject *dict = PyObject_stgdict(a->obj); - if (dict && (dict->setfunc == _ctypes_get_fielddesc("c")->setfunc)) { - Py_INCREF(value); - return value; - } - } - - as_parameter = PyObject_GetAttrString(value, "_as_parameter_"); - if (as_parameter) { - value = c_char_p_from_param(type, as_parameter); - Py_DECREF(as_parameter); - return value; - } - /* XXX better message */ - PyErr_SetString(PyExc_TypeError, - "wrong type"); - return NULL; + PyObject *as_parameter; + if (value == Py_None) { + Py_INCREF(Py_None); + return Py_None; + } + if (PyBytes_Check(value) || PyUnicode_Check(value)) { + PyCArgObject *parg; + struct fielddesc *fd = _ctypes_get_fielddesc("z"); + + parg = PyCArgObject_new(); + if (parg == NULL) + return NULL; + parg->pffi_type = &ffi_type_pointer; + parg->tag = 'z'; + parg->obj = fd->setfunc(&parg->value, value, 0); + if (parg->obj == NULL) { + Py_DECREF(parg); + return NULL; + } + return (PyObject *)parg; + } + if (PyObject_IsInstance(value, type)) { + Py_INCREF(value); + return value; + } + if (ArrayObject_Check(value) || PointerObject_Check(value)) { + /* c_char array instance or pointer(c_char(...)) */ + StgDictObject *dt = PyObject_stgdict(value); + StgDictObject *dict; + assert(dt); /* Cannot be NULL for pointer or array objects */ + dict = dt && dt->proto ? PyType_stgdict(dt->proto) : NULL; + if (dict && (dict->setfunc == _ctypes_get_fielddesc("c")->setfunc)) { + Py_INCREF(value); + return value; + } + } + if (PyCArg_CheckExact(value)) { + /* byref(c_char(...)) */ + PyCArgObject *a = (PyCArgObject *)value; + StgDictObject *dict = PyObject_stgdict(a->obj); + if (dict && (dict->setfunc == _ctypes_get_fielddesc("c")->setfunc)) { + Py_INCREF(value); + return value; + } + } + + as_parameter = PyObject_GetAttrString(value, "_as_parameter_"); + if (as_parameter) { + value = c_char_p_from_param(type, as_parameter); + Py_DECREF(as_parameter); + return value; + } + /* XXX better message */ + PyErr_SetString(PyExc_TypeError, + "wrong type"); + return NULL; } static PyObject * c_void_p_from_param(PyObject *type, PyObject *value) { - StgDictObject *stgd; - PyObject *as_parameter; + StgDictObject *stgd; + PyObject *as_parameter; /* None */ - if (value == Py_None) { - Py_INCREF(Py_None); - return Py_None; - } - /* Should probably allow buffer interface as well */ + if (value == Py_None) { + Py_INCREF(Py_None); + return Py_None; + } + /* Should probably allow buffer interface as well */ /* int, long */ - if (PyLong_Check(value)) { - PyCArgObject *parg; - struct fielddesc *fd = _ctypes_get_fielddesc("P"); - - parg = PyCArgObject_new(); - if (parg == NULL) - return NULL; - parg->pffi_type = &ffi_type_pointer; - parg->tag = 'P'; - parg->obj = fd->setfunc(&parg->value, value, 0); - if (parg->obj == NULL) { - Py_DECREF(parg); - return NULL; - } - return (PyObject *)parg; - } - /* XXX struni: remove later */ + if (PyLong_Check(value)) { + PyCArgObject *parg; + struct fielddesc *fd = _ctypes_get_fielddesc("P"); + + parg = PyCArgObject_new(); + if (parg == NULL) + return NULL; + parg->pffi_type = &ffi_type_pointer; + parg->tag = 'P'; + parg->obj = fd->setfunc(&parg->value, value, 0); + if (parg->obj == NULL) { + Py_DECREF(parg); + return NULL; + } + return (PyObject *)parg; + } + /* XXX struni: remove later */ /* string */ - if (PyBytes_Check(value)) { - PyCArgObject *parg; - struct fielddesc *fd = _ctypes_get_fielddesc("z"); - - parg = PyCArgObject_new(); - if (parg == NULL) - return NULL; - parg->pffi_type = &ffi_type_pointer; - parg->tag = 'z'; - parg->obj = fd->setfunc(&parg->value, value, 0); - if (parg->obj == NULL) { - Py_DECREF(parg); - return NULL; - } - return (PyObject *)parg; - } + if (PyBytes_Check(value)) { + PyCArgObject *parg; + struct fielddesc *fd = _ctypes_get_fielddesc("z"); + + parg = PyCArgObject_new(); + if (parg == NULL) + return NULL; + parg->pffi_type = &ffi_type_pointer; + parg->tag = 'z'; + parg->obj = fd->setfunc(&parg->value, value, 0); + if (parg->obj == NULL) { + Py_DECREF(parg); + return NULL; + } + return (PyObject *)parg; + } /* bytes */ - if (PyByteArray_Check(value)) { - PyCArgObject *parg; - struct fielddesc *fd = _ctypes_get_fielddesc("z"); - - parg = PyCArgObject_new(); - if (parg == NULL) - return NULL; - parg->pffi_type = &ffi_type_pointer; - parg->tag = 'z'; - parg->obj = fd->setfunc(&parg->value, value, 0); - if (parg->obj == NULL) { - Py_DECREF(parg); - return NULL; - } - return (PyObject *)parg; - } + if (PyByteArray_Check(value)) { + PyCArgObject *parg; + struct fielddesc *fd = _ctypes_get_fielddesc("z"); + + parg = PyCArgObject_new(); + if (parg == NULL) + return NULL; + parg->pffi_type = &ffi_type_pointer; + parg->tag = 'z'; + parg->obj = fd->setfunc(&parg->value, value, 0); + if (parg->obj == NULL) { + Py_DECREF(parg); + return NULL; + } + return (PyObject *)parg; + } /* unicode */ - if (PyUnicode_Check(value)) { - PyCArgObject *parg; - struct fielddesc *fd = _ctypes_get_fielddesc("Z"); - - parg = PyCArgObject_new(); - if (parg == NULL) - return NULL; - parg->pffi_type = &ffi_type_pointer; - parg->tag = 'Z'; - parg->obj = fd->setfunc(&parg->value, value, 0); - if (parg->obj == NULL) { - Py_DECREF(parg); - return NULL; - } - return (PyObject *)parg; - } + if (PyUnicode_Check(value)) { + PyCArgObject *parg; + struct fielddesc *fd = _ctypes_get_fielddesc("Z"); + + parg = PyCArgObject_new(); + if (parg == NULL) + return NULL; + parg->pffi_type = &ffi_type_pointer; + parg->tag = 'Z'; + parg->obj = fd->setfunc(&parg->value, value, 0); + if (parg->obj == NULL) { + Py_DECREF(parg); + return NULL; + } + return (PyObject *)parg; + } /* c_void_p instance (or subclass) */ - if (PyObject_IsInstance(value, type)) { - /* c_void_p instances */ - Py_INCREF(value); - return value; - } + if (PyObject_IsInstance(value, type)) { + /* c_void_p instances */ + Py_INCREF(value); + return value; + } /* ctypes array or pointer instance */ - if (ArrayObject_Check(value) || PointerObject_Check(value)) { - /* Any array or pointer is accepted */ - Py_INCREF(value); - return value; - } + if (ArrayObject_Check(value) || PointerObject_Check(value)) { + /* Any array or pointer is accepted */ + Py_INCREF(value); + return value; + } /* byref(...) */ - if (PyCArg_CheckExact(value)) { - /* byref(c_xxx()) */ - PyCArgObject *a = (PyCArgObject *)value; - if (a->tag == 'P') { - Py_INCREF(value); - return value; - } - } + if (PyCArg_CheckExact(value)) { + /* byref(c_xxx()) */ + PyCArgObject *a = (PyCArgObject *)value; + if (a->tag == 'P') { + Py_INCREF(value); + return value; + } + } /* function pointer */ - if (PyCFuncPtrObject_Check(value)) { - PyCArgObject *parg; - PyCFuncPtrObject *func; - func = (PyCFuncPtrObject *)value; - parg = PyCArgObject_new(); - if (parg == NULL) - return NULL; - parg->pffi_type = &ffi_type_pointer; - parg->tag = 'P'; - Py_INCREF(value); - parg->value.p = *(void **)func->b_ptr; - parg->obj = value; - return (PyObject *)parg; - } + if (PyCFuncPtrObject_Check(value)) { + PyCArgObject *parg; + PyCFuncPtrObject *func; + func = (PyCFuncPtrObject *)value; + parg = PyCArgObject_new(); + if (parg == NULL) + return NULL; + parg->pffi_type = &ffi_type_pointer; + parg->tag = 'P'; + Py_INCREF(value); + parg->value.p = *(void **)func->b_ptr; + parg->obj = value; + return (PyObject *)parg; + } /* c_char_p, c_wchar_p */ - stgd = PyObject_stgdict(value); - if (stgd && CDataObject_Check(value) && stgd->proto && PyUnicode_Check(stgd->proto)) { - PyCArgObject *parg; - - switch (_PyUnicode_AsString(stgd->proto)[0]) { - case 'z': /* c_char_p */ - case 'Z': /* c_wchar_p */ - parg = PyCArgObject_new(); - if (parg == NULL) - return NULL; - parg->pffi_type = &ffi_type_pointer; - parg->tag = 'Z'; - Py_INCREF(value); - parg->obj = value; - /* Remember: b_ptr points to where the pointer is stored! */ - parg->value.p = *(void **)(((CDataObject *)value)->b_ptr); - return (PyObject *)parg; - } - } - - as_parameter = PyObject_GetAttrString(value, "_as_parameter_"); - if (as_parameter) { - value = c_void_p_from_param(type, as_parameter); - Py_DECREF(as_parameter); - return value; - } - /* XXX better message */ - PyErr_SetString(PyExc_TypeError, - "wrong type"); - return NULL; + stgd = PyObject_stgdict(value); + if (stgd && CDataObject_Check(value) && stgd->proto && PyUnicode_Check(stgd->proto)) { + PyCArgObject *parg; + + switch (_PyUnicode_AsString(stgd->proto)[0]) { + case 'z': /* c_char_p */ + case 'Z': /* c_wchar_p */ + parg = PyCArgObject_new(); + if (parg == NULL) + return NULL; + parg->pffi_type = &ffi_type_pointer; + parg->tag = 'Z'; + Py_INCREF(value); + parg->obj = value; + /* Remember: b_ptr points to where the pointer is stored! */ + parg->value.p = *(void **)(((CDataObject *)value)->b_ptr); + return (PyObject *)parg; + } + } + + as_parameter = PyObject_GetAttrString(value, "_as_parameter_"); + if (as_parameter) { + value = c_void_p_from_param(type, as_parameter); + Py_DECREF(as_parameter); + return value; + } + /* XXX better message */ + PyErr_SetString(PyExc_TypeError, + "wrong type"); + return NULL; } static PyMethodDef c_void_p_method = { "from_param", c_void_p_from_param, METH_O }; @@ -1718,278 +1718,278 @@ static PyMethodDef c_wchar_p_method = { "from_param", c_wchar_p_from_param, METH_O }; static PyObject *CreateSwappedType(PyTypeObject *type, PyObject *args, PyObject *kwds, - PyObject *proto, struct fielddesc *fmt) + PyObject *proto, struct fielddesc *fmt) { - PyTypeObject *result; - StgDictObject *stgdict; - PyObject *name = PyTuple_GET_ITEM(args, 0); - PyObject *newname; - PyObject *swapped_args; - static PyObject *suffix; - Py_ssize_t i; - - swapped_args = PyTuple_New(PyTuple_GET_SIZE(args)); - if (!swapped_args) - return NULL; + PyTypeObject *result; + StgDictObject *stgdict; + PyObject *name = PyTuple_GET_ITEM(args, 0); + PyObject *newname; + PyObject *swapped_args; + static PyObject *suffix; + Py_ssize_t i; + + swapped_args = PyTuple_New(PyTuple_GET_SIZE(args)); + if (!swapped_args) + return NULL; - if (suffix == NULL) + if (suffix == NULL) #ifdef WORDS_BIGENDIAN - suffix = PyUnicode_InternFromString("_le"); + suffix = PyUnicode_InternFromString("_le"); #else - suffix = PyUnicode_InternFromString("_be"); + suffix = PyUnicode_InternFromString("_be"); #endif - newname = PyUnicode_Concat(name, suffix); - if (newname == NULL) { - return NULL; - } - - PyTuple_SET_ITEM(swapped_args, 0, newname); - for (i=1; iffi_type_pointer = *fmt->pffi_type; - stgdict->align = fmt->pffi_type->alignment; - stgdict->length = 0; - stgdict->size = fmt->pffi_type->size; - stgdict->setfunc = fmt->setfunc_swapped; - stgdict->getfunc = fmt->getfunc_swapped; - - Py_INCREF(proto); - stgdict->proto = proto; - - /* replace the class dict by our updated spam dict */ - if (-1 == PyDict_Update((PyObject *)stgdict, result->tp_dict)) { - Py_DECREF(result); - Py_DECREF((PyObject *)stgdict); - return NULL; - } - Py_DECREF(result->tp_dict); - result->tp_dict = (PyObject *)stgdict; + newname = PyUnicode_Concat(name, suffix); + if (newname == NULL) { + return NULL; + } + + PyTuple_SET_ITEM(swapped_args, 0, newname); + for (i=1; iffi_type_pointer = *fmt->pffi_type; + stgdict->align = fmt->pffi_type->alignment; + stgdict->length = 0; + stgdict->size = fmt->pffi_type->size; + stgdict->setfunc = fmt->setfunc_swapped; + stgdict->getfunc = fmt->getfunc_swapped; + + Py_INCREF(proto); + stgdict->proto = proto; + + /* replace the class dict by our updated spam dict */ + if (-1 == PyDict_Update((PyObject *)stgdict, result->tp_dict)) { + Py_DECREF(result); + Py_DECREF((PyObject *)stgdict); + return NULL; + } + Py_DECREF(result->tp_dict); + result->tp_dict = (PyObject *)stgdict; - return (PyObject *)result; + return (PyObject *)result; } static PyCArgObject * PyCSimpleType_paramfunc(CDataObject *self) { - StgDictObject *dict; - char *fmt; - PyCArgObject *parg; - struct fielddesc *fd; - - dict = PyObject_stgdict((PyObject *)self); - assert(dict); /* Cannot be NULL for CDataObject instances */ - fmt = _PyUnicode_AsString(dict->proto); - assert(fmt); - - fd = _ctypes_get_fielddesc(fmt); - assert(fd); - - parg = PyCArgObject_new(); - if (parg == NULL) - return NULL; - - parg->tag = fmt[0]; - parg->pffi_type = fd->pffi_type; - Py_INCREF(self); - parg->obj = (PyObject *)self; - memcpy(&parg->value, self->b_ptr, self->b_size); - return parg; + StgDictObject *dict; + char *fmt; + PyCArgObject *parg; + struct fielddesc *fd; + + dict = PyObject_stgdict((PyObject *)self); + assert(dict); /* Cannot be NULL for CDataObject instances */ + fmt = _PyUnicode_AsString(dict->proto); + assert(fmt); + + fd = _ctypes_get_fielddesc(fmt); + assert(fd); + + parg = PyCArgObject_new(); + if (parg == NULL) + return NULL; + + parg->tag = fmt[0]; + parg->pffi_type = fd->pffi_type; + Py_INCREF(self); + parg->obj = (PyObject *)self; + memcpy(&parg->value, self->b_ptr, self->b_size); + return parg; } static PyObject * PyCSimpleType_new(PyTypeObject *type, PyObject *args, PyObject *kwds) { - PyTypeObject *result; - StgDictObject *stgdict; - PyObject *proto; - const char *proto_str; - Py_ssize_t proto_len; - PyMethodDef *ml; - struct fielddesc *fmt; - - /* create the new instance (which is a class, - since we are a metatype!) */ - result = (PyTypeObject *)PyType_Type.tp_new(type, args, kwds); - if (result == NULL) - return NULL; - - proto = PyObject_GetAttrString((PyObject *)result, "_type_"); /* new ref */ - if (!proto) { - PyErr_SetString(PyExc_AttributeError, - "class must define a '_type_' attribute"); + PyTypeObject *result; + StgDictObject *stgdict; + PyObject *proto; + const char *proto_str; + Py_ssize_t proto_len; + PyMethodDef *ml; + struct fielddesc *fmt; + + /* create the new instance (which is a class, + since we are a metatype!) */ + result = (PyTypeObject *)PyType_Type.tp_new(type, args, kwds); + if (result == NULL) + return NULL; + + proto = PyObject_GetAttrString((PyObject *)result, "_type_"); /* new ref */ + if (!proto) { + PyErr_SetString(PyExc_AttributeError, + "class must define a '_type_' attribute"); error: - Py_XDECREF(proto); - Py_XDECREF(result); - return NULL; - } - if (PyUnicode_Check(proto)) { - PyObject *v = _PyUnicode_AsDefaultEncodedString(proto, NULL); - if (!v) - goto error; - proto_str = PyBytes_AS_STRING(v); - proto_len = PyBytes_GET_SIZE(v); - } else { - PyErr_SetString(PyExc_TypeError, - "class must define a '_type_' string attribute"); - goto error; - } - if (proto_len != 1) { - PyErr_SetString(PyExc_ValueError, - "class must define a '_type_' attribute " - "which must be a string of length 1"); - goto error; - } - if (!strchr(SIMPLE_TYPE_CHARS, *proto_str)) { - PyErr_Format(PyExc_AttributeError, - "class must define a '_type_' attribute which must be\n" - "a single character string containing one of '%s'.", - SIMPLE_TYPE_CHARS); - goto error; - } - fmt = _ctypes_get_fielddesc(proto_str); - if (fmt == NULL) { - PyErr_Format(PyExc_ValueError, - "_type_ '%s' not supported", proto_str); - goto error; - } - - stgdict = (StgDictObject *)PyObject_CallObject( - (PyObject *)&PyCStgDict_Type, NULL); - if (!stgdict) - goto error; - - stgdict->ffi_type_pointer = *fmt->pffi_type; - stgdict->align = fmt->pffi_type->alignment; - stgdict->length = 0; - stgdict->size = fmt->pffi_type->size; - stgdict->setfunc = fmt->setfunc; - stgdict->getfunc = fmt->getfunc; + Py_XDECREF(proto); + Py_XDECREF(result); + return NULL; + } + if (PyUnicode_Check(proto)) { + PyObject *v = _PyUnicode_AsDefaultEncodedString(proto, NULL); + if (!v) + goto error; + proto_str = PyBytes_AS_STRING(v); + proto_len = PyBytes_GET_SIZE(v); + } else { + PyErr_SetString(PyExc_TypeError, + "class must define a '_type_' string attribute"); + goto error; + } + if (proto_len != 1) { + PyErr_SetString(PyExc_ValueError, + "class must define a '_type_' attribute " + "which must be a string of length 1"); + goto error; + } + if (!strchr(SIMPLE_TYPE_CHARS, *proto_str)) { + PyErr_Format(PyExc_AttributeError, + "class must define a '_type_' attribute which must be\n" + "a single character string containing one of '%s'.", + SIMPLE_TYPE_CHARS); + goto error; + } + fmt = _ctypes_get_fielddesc(proto_str); + if (fmt == NULL) { + PyErr_Format(PyExc_ValueError, + "_type_ '%s' not supported", proto_str); + goto error; + } + + stgdict = (StgDictObject *)PyObject_CallObject( + (PyObject *)&PyCStgDict_Type, NULL); + if (!stgdict) + goto error; + + stgdict->ffi_type_pointer = *fmt->pffi_type; + stgdict->align = fmt->pffi_type->alignment; + stgdict->length = 0; + stgdict->size = fmt->pffi_type->size; + stgdict->setfunc = fmt->setfunc; + stgdict->getfunc = fmt->getfunc; #ifdef WORDS_BIGENDIAN - stgdict->format = _ctypes_alloc_format_string(">", proto_str); + stgdict->format = _ctypes_alloc_format_string(">", proto_str); #else - stgdict->format = _ctypes_alloc_format_string("<", proto_str); + stgdict->format = _ctypes_alloc_format_string("<", proto_str); #endif - if (stgdict->format == NULL) { - Py_DECREF(result); - Py_DECREF(proto); - Py_DECREF((PyObject *)stgdict); - return NULL; - } + if (stgdict->format == NULL) { + Py_DECREF(result); + Py_DECREF(proto); + Py_DECREF((PyObject *)stgdict); + return NULL; + } - stgdict->paramfunc = PyCSimpleType_paramfunc; + stgdict->paramfunc = PyCSimpleType_paramfunc; /* - if (result->tp_base != &Simple_Type) { - stgdict->setfunc = NULL; - stgdict->getfunc = NULL; - } + if (result->tp_base != &Simple_Type) { + stgdict->setfunc = NULL; + stgdict->getfunc = NULL; + } */ - /* This consumes the refcount on proto which we have */ - stgdict->proto = proto; + /* This consumes the refcount on proto which we have */ + stgdict->proto = proto; - /* replace the class dict by our updated spam dict */ - if (-1 == PyDict_Update((PyObject *)stgdict, result->tp_dict)) { - Py_DECREF(result); - Py_DECREF((PyObject *)stgdict); - return NULL; - } - Py_DECREF(result->tp_dict); - result->tp_dict = (PyObject *)stgdict; - - /* Install from_param class methods in ctypes base classes. - Overrides the PyCSimpleType_from_param generic method. - */ - if (result->tp_base == &Simple_Type) { - switch (*proto_str) { - case 'z': /* c_char_p */ - ml = &c_char_p_method; - stgdict->flags |= TYPEFLAG_ISPOINTER; - break; - case 'Z': /* c_wchar_p */ - ml = &c_wchar_p_method; - stgdict->flags |= TYPEFLAG_ISPOINTER; - break; - case 'P': /* c_void_p */ - ml = &c_void_p_method; - stgdict->flags |= TYPEFLAG_ISPOINTER; - break; - case 's': - case 'X': - case 'O': - ml = NULL; - stgdict->flags |= TYPEFLAG_ISPOINTER; - break; - default: - ml = NULL; - break; - } - - if (ml) { - PyObject *meth; - int x; - meth = PyDescr_NewClassMethod(result, ml); - if (!meth) - return NULL; - x = PyDict_SetItemString(result->tp_dict, - ml->ml_name, - meth); - Py_DECREF(meth); - if (x == -1) { - Py_DECREF(result); - return NULL; - } - } - } - - if (type == &PyCSimpleType_Type && fmt->setfunc_swapped && fmt->getfunc_swapped) { - PyObject *swapped = CreateSwappedType(type, args, kwds, - proto, fmt); - StgDictObject *sw_dict; - if (swapped == NULL) { - Py_DECREF(result); - return NULL; - } - sw_dict = PyType_stgdict(swapped); + /* replace the class dict by our updated spam dict */ + if (-1 == PyDict_Update((PyObject *)stgdict, result->tp_dict)) { + Py_DECREF(result); + Py_DECREF((PyObject *)stgdict); + return NULL; + } + Py_DECREF(result->tp_dict); + result->tp_dict = (PyObject *)stgdict; + + /* Install from_param class methods in ctypes base classes. + Overrides the PyCSimpleType_from_param generic method. + */ + if (result->tp_base == &Simple_Type) { + switch (*proto_str) { + case 'z': /* c_char_p */ + ml = &c_char_p_method; + stgdict->flags |= TYPEFLAG_ISPOINTER; + break; + case 'Z': /* c_wchar_p */ + ml = &c_wchar_p_method; + stgdict->flags |= TYPEFLAG_ISPOINTER; + break; + case 'P': /* c_void_p */ + ml = &c_void_p_method; + stgdict->flags |= TYPEFLAG_ISPOINTER; + break; + case 's': + case 'X': + case 'O': + ml = NULL; + stgdict->flags |= TYPEFLAG_ISPOINTER; + break; + default: + ml = NULL; + break; + } + + if (ml) { + PyObject *meth; + int x; + meth = PyDescr_NewClassMethod(result, ml); + if (!meth) + return NULL; + x = PyDict_SetItemString(result->tp_dict, + ml->ml_name, + meth); + Py_DECREF(meth); + if (x == -1) { + Py_DECREF(result); + return NULL; + } + } + } + + if (type == &PyCSimpleType_Type && fmt->setfunc_swapped && fmt->getfunc_swapped) { + PyObject *swapped = CreateSwappedType(type, args, kwds, + proto, fmt); + StgDictObject *sw_dict; + if (swapped == NULL) { + Py_DECREF(result); + return NULL; + } + sw_dict = PyType_stgdict(swapped); #ifdef WORDS_BIGENDIAN - PyObject_SetAttrString((PyObject *)result, "__ctype_le__", swapped); - PyObject_SetAttrString((PyObject *)result, "__ctype_be__", (PyObject *)result); - PyObject_SetAttrString(swapped, "__ctype_be__", (PyObject *)result); - PyObject_SetAttrString(swapped, "__ctype_le__", swapped); - /* We are creating the type for the OTHER endian */ - sw_dict->format = _ctypes_alloc_format_string("<", stgdict->format+1); + PyObject_SetAttrString((PyObject *)result, "__ctype_le__", swapped); + PyObject_SetAttrString((PyObject *)result, "__ctype_be__", (PyObject *)result); + PyObject_SetAttrString(swapped, "__ctype_be__", (PyObject *)result); + PyObject_SetAttrString(swapped, "__ctype_le__", swapped); + /* We are creating the type for the OTHER endian */ + sw_dict->format = _ctypes_alloc_format_string("<", stgdict->format+1); #else - PyObject_SetAttrString((PyObject *)result, "__ctype_be__", swapped); - PyObject_SetAttrString((PyObject *)result, "__ctype_le__", (PyObject *)result); - PyObject_SetAttrString(swapped, "__ctype_le__", (PyObject *)result); - PyObject_SetAttrString(swapped, "__ctype_be__", swapped); - /* We are creating the type for the OTHER endian */ - sw_dict->format = _ctypes_alloc_format_string(">", stgdict->format+1); + PyObject_SetAttrString((PyObject *)result, "__ctype_be__", swapped); + PyObject_SetAttrString((PyObject *)result, "__ctype_le__", (PyObject *)result); + PyObject_SetAttrString(swapped, "__ctype_le__", (PyObject *)result); + PyObject_SetAttrString(swapped, "__ctype_be__", swapped); + /* We are creating the type for the OTHER endian */ + sw_dict->format = _ctypes_alloc_format_string(">", stgdict->format+1); #endif - Py_DECREF(swapped); - if (PyErr_Occurred()) { - Py_DECREF(result); - return NULL; - } - }; + Py_DECREF(swapped); + if (PyErr_Occurred()) { + Py_DECREF(result); + return NULL; + } + }; - return (PyObject *)result; + return (PyObject *)result; } /* @@ -1999,101 +1999,101 @@ static PyObject * PyCSimpleType_from_param(PyObject *type, PyObject *value) { - StgDictObject *dict; - char *fmt; - PyCArgObject *parg; - struct fielddesc *fd; - PyObject *as_parameter; - - /* If the value is already an instance of the requested type, - we can use it as is */ - if (1 == PyObject_IsInstance(value, type)) { - Py_INCREF(value); - return value; - } - - dict = PyType_stgdict(type); - assert(dict); - - /* I think we can rely on this being a one-character string */ - fmt = _PyUnicode_AsString(dict->proto); - assert(fmt); - - fd = _ctypes_get_fielddesc(fmt); - assert(fd); - - parg = PyCArgObject_new(); - if (parg == NULL) - return NULL; - - parg->tag = fmt[0]; - parg->pffi_type = fd->pffi_type; - parg->obj = fd->setfunc(&parg->value, value, 0); - if (parg->obj) - return (PyObject *)parg; - PyErr_Clear(); - Py_DECREF(parg); - - as_parameter = PyObject_GetAttrString(value, "_as_parameter_"); - if (as_parameter) { - value = PyCSimpleType_from_param(type, as_parameter); - Py_DECREF(as_parameter); - return value; - } - PyErr_SetString(PyExc_TypeError, - "wrong type"); - return NULL; + StgDictObject *dict; + char *fmt; + PyCArgObject *parg; + struct fielddesc *fd; + PyObject *as_parameter; + + /* If the value is already an instance of the requested type, + we can use it as is */ + if (1 == PyObject_IsInstance(value, type)) { + Py_INCREF(value); + return value; + } + + dict = PyType_stgdict(type); + assert(dict); + + /* I think we can rely on this being a one-character string */ + fmt = _PyUnicode_AsString(dict->proto); + assert(fmt); + + fd = _ctypes_get_fielddesc(fmt); + assert(fd); + + parg = PyCArgObject_new(); + if (parg == NULL) + return NULL; + + parg->tag = fmt[0]; + parg->pffi_type = fd->pffi_type; + parg->obj = fd->setfunc(&parg->value, value, 0); + if (parg->obj) + return (PyObject *)parg; + PyErr_Clear(); + Py_DECREF(parg); + + as_parameter = PyObject_GetAttrString(value, "_as_parameter_"); + if (as_parameter) { + value = PyCSimpleType_from_param(type, as_parameter); + Py_DECREF(as_parameter); + return value; + } + PyErr_SetString(PyExc_TypeError, + "wrong type"); + return NULL; } static PyMethodDef PyCSimpleType_methods[] = { - { "from_param", PyCSimpleType_from_param, METH_O, from_param_doc }, - { "from_address", CDataType_from_address, METH_O, from_address_doc }, - { "from_buffer", CDataType_from_buffer, METH_VARARGS, from_buffer_doc, }, - { "from_buffer_copy", CDataType_from_buffer_copy, METH_VARARGS, from_buffer_copy_doc, }, - { "in_dll", CDataType_in_dll, METH_VARARGS, in_dll_doc}, - { NULL, NULL }, + { "from_param", PyCSimpleType_from_param, METH_O, from_param_doc }, + { "from_address", CDataType_from_address, METH_O, from_address_doc }, + { "from_buffer", CDataType_from_buffer, METH_VARARGS, from_buffer_doc, }, + { "from_buffer_copy", CDataType_from_buffer_copy, METH_VARARGS, from_buffer_copy_doc, }, + { "in_dll", CDataType_in_dll, METH_VARARGS, in_dll_doc}, + { NULL, NULL }, }; PyTypeObject PyCSimpleType_Type = { - PyVarObject_HEAD_INIT(NULL, 0) - "_ctypes.PyCSimpleType", /* tp_name */ - 0, /* tp_basicsize */ - 0, /* tp_itemsize */ - 0, /* tp_dealloc */ - 0, /* tp_print */ - 0, /* tp_getattr */ - 0, /* tp_setattr */ - 0, /* tp_reserved */ - 0, /* tp_repr */ - 0, /* tp_as_number */ - &CDataType_as_sequence, /* tp_as_sequence */ - 0, /* tp_as_mapping */ - 0, /* tp_hash */ - 0, /* tp_call */ - 0, /* tp_str */ - 0, /* tp_getattro */ - 0, /* tp_setattro */ - 0, /* tp_as_buffer */ - Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */ - "metatype for the PyCSimpleType Objects", /* tp_doc */ - 0, /* tp_traverse */ - 0, /* tp_clear */ - 0, /* tp_richcompare */ - 0, /* tp_weaklistoffset */ - 0, /* tp_iter */ - 0, /* tp_iternext */ - PyCSimpleType_methods, /* tp_methods */ - 0, /* tp_members */ - 0, /* tp_getset */ - 0, /* tp_base */ - 0, /* tp_dict */ - 0, /* tp_descr_get */ - 0, /* tp_descr_set */ - 0, /* tp_dictoffset */ - 0, /* tp_init */ - 0, /* tp_alloc */ - PyCSimpleType_new, /* tp_new */ - 0, /* tp_free */ + PyVarObject_HEAD_INIT(NULL, 0) + "_ctypes.PyCSimpleType", /* tp_name */ + 0, /* tp_basicsize */ + 0, /* tp_itemsize */ + 0, /* tp_dealloc */ + 0, /* tp_print */ + 0, /* tp_getattr */ + 0, /* tp_setattr */ + 0, /* tp_reserved */ + 0, /* tp_repr */ + 0, /* tp_as_number */ + &CDataType_as_sequence, /* tp_as_sequence */ + 0, /* tp_as_mapping */ + 0, /* tp_hash */ + 0, /* tp_call */ + 0, /* tp_str */ + 0, /* tp_getattro */ + 0, /* tp_setattro */ + 0, /* tp_as_buffer */ + Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */ + "metatype for the PyCSimpleType Objects", /* tp_doc */ + 0, /* tp_traverse */ + 0, /* tp_clear */ + 0, /* tp_richcompare */ + 0, /* tp_weaklistoffset */ + 0, /* tp_iter */ + 0, /* tp_iternext */ + PyCSimpleType_methods, /* tp_methods */ + 0, /* tp_members */ + 0, /* tp_getset */ + 0, /* tp_base */ + 0, /* tp_dict */ + 0, /* tp_descr_get */ + 0, /* tp_descr_set */ + 0, /* tp_dictoffset */ + 0, /* tp_init */ + 0, /* tp_alloc */ + PyCSimpleType_new, /* tp_new */ + 0, /* tp_free */ }; /******************************************************************/ @@ -2104,217 +2104,217 @@ static PyObject * converters_from_argtypes(PyObject *ob) { - PyObject *converters; - Py_ssize_t i; - Py_ssize_t nArgs; - - ob = PySequence_Tuple(ob); /* new reference */ - if (!ob) { - PyErr_SetString(PyExc_TypeError, - "_argtypes_ must be a sequence of types"); - return NULL; - } - - nArgs = PyTuple_GET_SIZE(ob); - converters = PyTuple_New(nArgs); - if (!converters) - return NULL; - - /* I have to check if this is correct. Using c_char, which has a size - of 1, will be assumed to be pushed as only one byte! - Aren't these promoted to integers by the C compiler and pushed as 4 bytes? - */ - - for (i = 0; i < nArgs; ++i) { - PyObject *tp = PyTuple_GET_ITEM(ob, i); - PyObject *cnv = PyObject_GetAttrString(tp, "from_param"); - if (!cnv) - goto argtypes_error_1; - PyTuple_SET_ITEM(converters, i, cnv); - } - Py_DECREF(ob); - return converters; + PyObject *converters; + Py_ssize_t i; + Py_ssize_t nArgs; + + ob = PySequence_Tuple(ob); /* new reference */ + if (!ob) { + PyErr_SetString(PyExc_TypeError, + "_argtypes_ must be a sequence of types"); + return NULL; + } + + nArgs = PyTuple_GET_SIZE(ob); + converters = PyTuple_New(nArgs); + if (!converters) + return NULL; + + /* I have to check if this is correct. Using c_char, which has a size + of 1, will be assumed to be pushed as only one byte! + Aren't these promoted to integers by the C compiler and pushed as 4 bytes? + */ + + for (i = 0; i < nArgs; ++i) { + PyObject *tp = PyTuple_GET_ITEM(ob, i); + PyObject *cnv = PyObject_GetAttrString(tp, "from_param"); + if (!cnv) + goto argtypes_error_1; + PyTuple_SET_ITEM(converters, i, cnv); + } + Py_DECREF(ob); + return converters; argtypes_error_1: - Py_XDECREF(converters); - Py_DECREF(ob); - PyErr_Format(PyExc_TypeError, - "item %zd in _argtypes_ has no from_param method", - i+1); - return NULL; + Py_XDECREF(converters); + Py_DECREF(ob); + PyErr_Format(PyExc_TypeError, + "item %zd in _argtypes_ has no from_param method", + i+1); + return NULL; } static int make_funcptrtype_dict(StgDictObject *stgdict) { - PyObject *ob; - PyObject *converters = NULL; + PyObject *ob; + PyObject *converters = NULL; - stgdict->align = _ctypes_get_fielddesc("P")->pffi_type->alignment; - stgdict->length = 1; - stgdict->size = sizeof(void *); - stgdict->setfunc = NULL; - stgdict->getfunc = NULL; - stgdict->ffi_type_pointer = ffi_type_pointer; - - ob = PyDict_GetItemString((PyObject *)stgdict, "_flags_"); - if (!ob || !PyLong_Check(ob)) { - PyErr_SetString(PyExc_TypeError, - "class must define _flags_ which must be an integer"); - return -1; - } - stgdict->flags = PyLong_AS_LONG(ob) | TYPEFLAG_ISPOINTER; - - /* _argtypes_ is optional... */ - ob = PyDict_GetItemString((PyObject *)stgdict, "_argtypes_"); - if (ob) { - converters = converters_from_argtypes(ob); - if (!converters) - goto error; - Py_INCREF(ob); - stgdict->argtypes = ob; - stgdict->converters = converters; - } - - ob = PyDict_GetItemString((PyObject *)stgdict, "_restype_"); - if (ob) { - if (ob != Py_None && !PyType_stgdict(ob) && !PyCallable_Check(ob)) { - PyErr_SetString(PyExc_TypeError, - "_restype_ must be a type, a callable, or None"); - return -1; - } - Py_INCREF(ob); - stgdict->restype = ob; - stgdict->checker = PyObject_GetAttrString(ob, "_check_retval_"); - if (stgdict->checker == NULL) - PyErr_Clear(); - } + stgdict->align = _ctypes_get_fielddesc("P")->pffi_type->alignment; + stgdict->length = 1; + stgdict->size = sizeof(void *); + stgdict->setfunc = NULL; + stgdict->getfunc = NULL; + stgdict->ffi_type_pointer = ffi_type_pointer; + + ob = PyDict_GetItemString((PyObject *)stgdict, "_flags_"); + if (!ob || !PyLong_Check(ob)) { + PyErr_SetString(PyExc_TypeError, + "class must define _flags_ which must be an integer"); + return -1; + } + stgdict->flags = PyLong_AS_LONG(ob) | TYPEFLAG_ISPOINTER; + + /* _argtypes_ is optional... */ + ob = PyDict_GetItemString((PyObject *)stgdict, "_argtypes_"); + if (ob) { + converters = converters_from_argtypes(ob); + if (!converters) + goto error; + Py_INCREF(ob); + stgdict->argtypes = ob; + stgdict->converters = converters; + } + + ob = PyDict_GetItemString((PyObject *)stgdict, "_restype_"); + if (ob) { + if (ob != Py_None && !PyType_stgdict(ob) && !PyCallable_Check(ob)) { + PyErr_SetString(PyExc_TypeError, + "_restype_ must be a type, a callable, or None"); + return -1; + } + Py_INCREF(ob); + stgdict->restype = ob; + stgdict->checker = PyObject_GetAttrString(ob, "_check_retval_"); + if (stgdict->checker == NULL) + PyErr_Clear(); + } /* XXX later, maybe. - ob = PyDict_GetItemString((PyObject *)stgdict, "_errcheck_"); - if (ob) { - if (!PyCallable_Check(ob)) { - PyErr_SetString(PyExc_TypeError, - "_errcheck_ must be callable"); - return -1; - } - Py_INCREF(ob); - stgdict->errcheck = ob; - } + ob = PyDict_GetItemString((PyObject *)stgdict, "_errcheck_"); + if (ob) { + if (!PyCallable_Check(ob)) { + PyErr_SetString(PyExc_TypeError, + "_errcheck_ must be callable"); + return -1; + } + Py_INCREF(ob); + stgdict->errcheck = ob; + } */ - return 0; + return 0; error: - Py_XDECREF(converters); - return -1; + Py_XDECREF(converters); + return -1; } static PyCArgObject * PyCFuncPtrType_paramfunc(CDataObject *self) { - PyCArgObject *parg; - - parg = PyCArgObject_new(); - if (parg == NULL) - return NULL; - - parg->tag = 'P'; - parg->pffi_type = &ffi_type_pointer; - Py_INCREF(self); - parg->obj = (PyObject *)self; - parg->value.p = *(void **)self->b_ptr; - return parg; + PyCArgObject *parg; + + parg = PyCArgObject_new(); + if (parg == NULL) + return NULL; + + parg->tag = 'P'; + parg->pffi_type = &ffi_type_pointer; + Py_INCREF(self); + parg->obj = (PyObject *)self; + parg->value.p = *(void **)self->b_ptr; + return parg; } static PyObject * PyCFuncPtrType_new(PyTypeObject *type, PyObject *args, PyObject *kwds) { - PyTypeObject *result; - StgDictObject *stgdict; + PyTypeObject *result; + StgDictObject *stgdict; - stgdict = (StgDictObject *)PyObject_CallObject( - (PyObject *)&PyCStgDict_Type, NULL); - if (!stgdict) - return NULL; - - stgdict->paramfunc = PyCFuncPtrType_paramfunc; - /* We do NOT expose the function signature in the format string. It - is impossible, generally, because the only requirement for the - argtypes items is that they have a .from_param method - we do not - know the types of the arguments (although, in practice, most - argtypes would be a ctypes type). - */ - stgdict->format = _ctypes_alloc_format_string(NULL, "X{}"); - stgdict->flags |= TYPEFLAG_ISPOINTER; - - /* create the new instance (which is a class, - since we are a metatype!) */ - result = (PyTypeObject *)PyType_Type.tp_new(type, args, kwds); - if (result == NULL) { - Py_DECREF((PyObject *)stgdict); - return NULL; - } - - /* replace the class dict by our updated storage dict */ - if (-1 == PyDict_Update((PyObject *)stgdict, result->tp_dict)) { - Py_DECREF(result); - Py_DECREF((PyObject *)stgdict); - return NULL; - } - Py_DECREF(result->tp_dict); - result->tp_dict = (PyObject *)stgdict; - - if (-1 == make_funcptrtype_dict(stgdict)) { - Py_DECREF(result); - return NULL; - } + stgdict = (StgDictObject *)PyObject_CallObject( + (PyObject *)&PyCStgDict_Type, NULL); + if (!stgdict) + return NULL; + + stgdict->paramfunc = PyCFuncPtrType_paramfunc; + /* We do NOT expose the function signature in the format string. It + is impossible, generally, because the only requirement for the + argtypes items is that they have a .from_param method - we do not + know the types of the arguments (although, in practice, most + argtypes would be a ctypes type). + */ + stgdict->format = _ctypes_alloc_format_string(NULL, "X{}"); + stgdict->flags |= TYPEFLAG_ISPOINTER; + + /* create the new instance (which is a class, + since we are a metatype!) */ + result = (PyTypeObject *)PyType_Type.tp_new(type, args, kwds); + if (result == NULL) { + Py_DECREF((PyObject *)stgdict); + return NULL; + } + + /* replace the class dict by our updated storage dict */ + if (-1 == PyDict_Update((PyObject *)stgdict, result->tp_dict)) { + Py_DECREF(result); + Py_DECREF((PyObject *)stgdict); + return NULL; + } + Py_DECREF(result->tp_dict); + result->tp_dict = (PyObject *)stgdict; + + if (-1 == make_funcptrtype_dict(stgdict)) { + Py_DECREF(result); + return NULL; + } - return (PyObject *)result; + return (PyObject *)result; } PyTypeObject PyCFuncPtrType_Type = { - PyVarObject_HEAD_INIT(NULL, 0) - "_ctypes.PyCFuncPtrType", /* tp_name */ - 0, /* tp_basicsize */ - 0, /* tp_itemsize */ - 0, /* tp_dealloc */ - 0, /* tp_print */ - 0, /* tp_getattr */ - 0, /* tp_setattr */ - 0, /* tp_reserved */ - 0, /* tp_repr */ - 0, /* tp_as_number */ - &CDataType_as_sequence, /* tp_as_sequence */ - 0, /* tp_as_mapping */ - 0, /* tp_hash */ - 0, /* tp_call */ - 0, /* tp_str */ - 0, /* tp_getattro */ - 0, /* tp_setattro */ - 0, /* tp_as_buffer */ - Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC, /* tp_flags */ - "metatype for C function pointers", /* tp_doc */ - (traverseproc)CDataType_traverse, /* tp_traverse */ - (inquiry)CDataType_clear, /* tp_clear */ - 0, /* tp_richcompare */ - 0, /* tp_weaklistoffset */ - 0, /* tp_iter */ - 0, /* tp_iternext */ - CDataType_methods, /* tp_methods */ - 0, /* tp_members */ - 0, /* tp_getset */ - 0, /* tp_base */ - 0, /* tp_dict */ - 0, /* tp_descr_get */ - 0, /* tp_descr_set */ - 0, /* tp_dictoffset */ - 0, /* tp_init */ - 0, /* tp_alloc */ - PyCFuncPtrType_new, /* tp_new */ - 0, /* tp_free */ + PyVarObject_HEAD_INIT(NULL, 0) + "_ctypes.PyCFuncPtrType", /* tp_name */ + 0, /* tp_basicsize */ + 0, /* tp_itemsize */ + 0, /* tp_dealloc */ + 0, /* tp_print */ + 0, /* tp_getattr */ + 0, /* tp_setattr */ + 0, /* tp_reserved */ + 0, /* tp_repr */ + 0, /* tp_as_number */ + &CDataType_as_sequence, /* tp_as_sequence */ + 0, /* tp_as_mapping */ + 0, /* tp_hash */ + 0, /* tp_call */ + 0, /* tp_str */ + 0, /* tp_getattro */ + 0, /* tp_setattro */ + 0, /* tp_as_buffer */ + Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC, /* tp_flags */ + "metatype for C function pointers", /* tp_doc */ + (traverseproc)CDataType_traverse, /* tp_traverse */ + (inquiry)CDataType_clear, /* tp_clear */ + 0, /* tp_richcompare */ + 0, /* tp_weaklistoffset */ + 0, /* tp_iter */ + 0, /* tp_iternext */ + CDataType_methods, /* tp_methods */ + 0, /* tp_members */ + 0, /* tp_getset */ + 0, /* tp_base */ + 0, /* tp_dict */ + 0, /* tp_descr_get */ + 0, /* tp_descr_set */ + 0, /* tp_dictoffset */ + 0, /* tp_init */ + 0, /* tp_alloc */ + PyCFuncPtrType_new, /* tp_new */ + 0, /* tp_free */ }; - + /***************************************************************** * Code to keep needed objects alive */ @@ -2322,46 +2322,46 @@ static CDataObject * PyCData_GetContainer(CDataObject *self) { - while (self->b_base) - self = self->b_base; - if (self->b_objects == NULL) { - if (self->b_length) { - self->b_objects = PyDict_New(); - } else { - Py_INCREF(Py_None); - self->b_objects = Py_None; - } - } - return self; + while (self->b_base) + self = self->b_base; + if (self->b_objects == NULL) { + if (self->b_length) { + self->b_objects = PyDict_New(); + } else { + Py_INCREF(Py_None); + self->b_objects = Py_None; + } + } + return self; } static PyObject * GetKeepedObjects(CDataObject *target) { - return PyCData_GetContainer(target)->b_objects; + return PyCData_GetContainer(target)->b_objects; } static PyObject * unique_key(CDataObject *target, Py_ssize_t index) { - char string[256]; - char *cp = string; - size_t bytes_left; - - assert(sizeof(string) - 1 > sizeof(Py_ssize_t) * 2); - cp += sprintf(cp, "%x", Py_SAFE_DOWNCAST(index, Py_ssize_t, int)); - while (target->b_base) { - bytes_left = sizeof(string) - (cp - string) - 1; - /* Hex format needs 2 characters per byte */ - if (bytes_left < sizeof(Py_ssize_t) * 2) { - PyErr_SetString(PyExc_ValueError, - "ctypes object structure too deep"); - return NULL; - } - cp += sprintf(cp, ":%x", Py_SAFE_DOWNCAST(target->b_index, Py_ssize_t, int)); - target = target->b_base; - } - return PyUnicode_FromStringAndSize(string, cp-string); + char string[256]; + char *cp = string; + size_t bytes_left; + + assert(sizeof(string) - 1 > sizeof(Py_ssize_t) * 2); + cp += sprintf(cp, "%x", Py_SAFE_DOWNCAST(index, Py_ssize_t, int)); + while (target->b_base) { + bytes_left = sizeof(string) - (cp - string) - 1; + /* Hex format needs 2 characters per byte */ + if (bytes_left < sizeof(Py_ssize_t) * 2) { + PyErr_SetString(PyExc_ValueError, + "ctypes object structure too deep"); + return NULL; + } + cp += sprintf(cp, ":%x", Py_SAFE_DOWNCAST(target->b_index, Py_ssize_t, int)); + target = target->b_base; + } + return PyUnicode_FromStringAndSize(string, cp-string); } /* @@ -2385,30 +2385,30 @@ static int KeepRef(CDataObject *target, Py_ssize_t index, PyObject *keep) { - int result; - CDataObject *ob; - PyObject *key; + int result; + CDataObject *ob; + PyObject *key; /* Optimization: no need to store None */ - if (keep == Py_None) { - Py_DECREF(Py_None); - return 0; - } - ob = PyCData_GetContainer(target); - if (ob->b_objects == NULL || !PyDict_CheckExact(ob->b_objects)) { - Py_XDECREF(ob->b_objects); - ob->b_objects = keep; /* refcount consumed */ - return 0; - } - key = unique_key(target, index); - if (key == NULL) { - Py_DECREF(keep); - return -1; - } - result = PyDict_SetItem(ob->b_objects, key, keep); - Py_DECREF(key); - Py_DECREF(keep); - return result; + if (keep == Py_None) { + Py_DECREF(Py_None); + return 0; + } + ob = PyCData_GetContainer(target); + if (ob->b_objects == NULL || !PyDict_CheckExact(ob->b_objects)) { + Py_XDECREF(ob->b_objects); + ob->b_objects = keep; /* refcount consumed */ + return 0; + } + key = unique_key(target, index); + if (key == NULL) { + Py_DECREF(keep); + return -1; + } + result = PyDict_SetItem(ob->b_objects, key, keep); + Py_DECREF(key); + Py_DECREF(keep); + return result; } /******************************************************************/ @@ -2418,75 +2418,75 @@ static int PyCData_traverse(CDataObject *self, visitproc visit, void *arg) { - Py_VISIT(self->b_objects); - Py_VISIT((PyObject *)self->b_base); - return 0; + Py_VISIT(self->b_objects); + Py_VISIT((PyObject *)self->b_base); + return 0; } static int PyCData_clear(CDataObject *self) { - StgDictObject *dict = PyObject_stgdict((PyObject *)self); - assert(dict); /* Cannot be NULL for CDataObject instances */ - Py_CLEAR(self->b_objects); - if ((self->b_needsfree) - && ((size_t)dict->size > sizeof(self->b_value))) - PyMem_Free(self->b_ptr); - self->b_ptr = NULL; - Py_CLEAR(self->b_base); - return 0; + StgDictObject *dict = PyObject_stgdict((PyObject *)self); + assert(dict); /* Cannot be NULL for CDataObject instances */ + Py_CLEAR(self->b_objects); + if ((self->b_needsfree) + && ((size_t)dict->size > sizeof(self->b_value))) + PyMem_Free(self->b_ptr); + self->b_ptr = NULL; + Py_CLEAR(self->b_base); + return 0; } static void PyCData_dealloc(PyObject *self) { - PyCData_clear((CDataObject *)self); - Py_TYPE(self)->tp_free(self); + PyCData_clear((CDataObject *)self); + Py_TYPE(self)->tp_free(self); } static PyMemberDef PyCData_members[] = { - { "_b_base_", T_OBJECT, - offsetof(CDataObject, b_base), READONLY, - "the base object" }, - { "_b_needsfree_", T_INT, - offsetof(CDataObject, b_needsfree), READONLY, - "whether the object owns the memory or not" }, - { "_objects", T_OBJECT, - offsetof(CDataObject, b_objects), READONLY, - "internal objects tree (NEVER CHANGE THIS OBJECT!)"}, - { NULL }, + { "_b_base_", T_OBJECT, + offsetof(CDataObject, b_base), READONLY, + "the base object" }, + { "_b_needsfree_", T_INT, + offsetof(CDataObject, b_needsfree), READONLY, + "whether the object owns the memory or not" }, + { "_objects", T_OBJECT, + offsetof(CDataObject, b_objects), READONLY, + "internal objects tree (NEVER CHANGE THIS OBJECT!)"}, + { NULL }, }; static int PyCData_NewGetBuffer(PyObject *_self, Py_buffer *view, int flags) { - CDataObject *self = (CDataObject *)_self; - StgDictObject *dict = PyObject_stgdict(_self); - Py_ssize_t i; - - if (view == NULL) return 0; - - view->buf = self->b_ptr; - view->obj = _self; - Py_INCREF(_self); - view->len = self->b_size; - view->readonly = 0; - /* use default format character if not set */ - view->format = dict->format ? dict->format : "B"; - view->ndim = dict->ndim; - view->shape = dict->shape; - view->itemsize = self->b_size; - for (i = 0; i < view->ndim; ++i) { - view->itemsize /= dict->shape[i]; - } - view->strides = NULL; - view->suboffsets = NULL; - view->internal = NULL; - return 0; + CDataObject *self = (CDataObject *)_self; + StgDictObject *dict = PyObject_stgdict(_self); + Py_ssize_t i; + + if (view == NULL) return 0; + + view->buf = self->b_ptr; + view->obj = _self; + Py_INCREF(_self); + view->len = self->b_size; + view->readonly = 0; + /* use default format character if not set */ + view->format = dict->format ? dict->format : "B"; + view->ndim = dict->ndim; + view->shape = dict->shape; + view->itemsize = self->b_size; + for (i = 0; i < view->ndim; ++i) { + view->itemsize /= dict->shape[i]; + } + view->strides = NULL; + view->suboffsets = NULL; + view->internal = NULL; + return 0; } static PyBufferProcs PyCData_as_buffer = { - PyCData_NewGetBuffer, - NULL, + PyCData_NewGetBuffer, + NULL, }; /* @@ -2495,47 +2495,47 @@ static long PyCData_nohash(PyObject *self) { - PyErr_SetString(PyExc_TypeError, "unhashable type"); - return -1; + PyErr_SetString(PyExc_TypeError, "unhashable type"); + return -1; } static PyObject * PyCData_reduce(PyObject *_self, PyObject *args) { - CDataObject *self = (CDataObject *)_self; + CDataObject *self = (CDataObject *)_self; - if (PyObject_stgdict(_self)->flags & (TYPEFLAG_ISPOINTER|TYPEFLAG_HASPOINTER)) { - PyErr_SetString(PyExc_ValueError, - "ctypes objects containing pointers cannot be pickled"); - return NULL; - } - return Py_BuildValue("O(O(NN))", - _unpickle, - Py_TYPE(_self), - PyObject_GetAttrString(_self, "__dict__"), - PyBytes_FromStringAndSize(self->b_ptr, self->b_size)); + if (PyObject_stgdict(_self)->flags & (TYPEFLAG_ISPOINTER|TYPEFLAG_HASPOINTER)) { + PyErr_SetString(PyExc_ValueError, + "ctypes objects containing pointers cannot be pickled"); + return NULL; + } + return Py_BuildValue("O(O(NN))", + _unpickle, + Py_TYPE(_self), + PyObject_GetAttrString(_self, "__dict__"), + PyBytes_FromStringAndSize(self->b_ptr, self->b_size)); } static PyObject * PyCData_setstate(PyObject *_self, PyObject *args) { - void *data; - Py_ssize_t len; - int res; - PyObject *dict, *mydict; - CDataObject *self = (CDataObject *)_self; - if (!PyArg_ParseTuple(args, "Os#", &dict, &data, &len)) - return NULL; - if (len > self->b_size) - len = self->b_size; - memmove(self->b_ptr, data, len); - mydict = PyObject_GetAttrString(_self, "__dict__"); - res = PyDict_Update(mydict, dict); - Py_DECREF(mydict); - if (res == -1) - return NULL; - Py_INCREF(Py_None); - return Py_None; + void *data; + Py_ssize_t len; + int res; + PyObject *dict, *mydict; + CDataObject *self = (CDataObject *)_self; + if (!PyArg_ParseTuple(args, "Os#", &dict, &data, &len)) + return NULL; + if (len > self->b_size) + len = self->b_size; + memmove(self->b_ptr, data, len); + mydict = PyObject_GetAttrString(_self, "__dict__"); + res = PyDict_Update(mydict, dict); + Py_DECREF(mydict); + if (res == -1) + return NULL; + Py_INCREF(Py_None); + return Py_None; } /* @@ -2544,124 +2544,124 @@ static PyObject * PyCData_from_outparam(PyObject *self, PyObject *args) { - Py_INCREF(self); - return self; + Py_INCREF(self); + return self; } static PyMethodDef PyCData_methods[] = { - { "__ctypes_from_outparam__", PyCData_from_outparam, METH_NOARGS, }, - { "__reduce__", PyCData_reduce, METH_NOARGS, }, - { "__setstate__", PyCData_setstate, METH_VARARGS, }, - { NULL, NULL }, + { "__ctypes_from_outparam__", PyCData_from_outparam, METH_NOARGS, }, + { "__reduce__", PyCData_reduce, METH_NOARGS, }, + { "__setstate__", PyCData_setstate, METH_VARARGS, }, + { NULL, NULL }, }; PyTypeObject PyCData_Type = { - PyVarObject_HEAD_INIT(NULL, 0) - "_ctypes._CData", - sizeof(CDataObject), /* tp_basicsize */ - 0, /* tp_itemsize */ - PyCData_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 */ - PyCData_nohash, /* tp_hash */ - 0, /* tp_call */ - 0, /* tp_str */ - 0, /* tp_getattro */ - 0, /* tp_setattro */ - &PyCData_as_buffer, /* tp_as_buffer */ - Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */ - "XXX to be provided", /* tp_doc */ - (traverseproc)PyCData_traverse, /* tp_traverse */ - (inquiry)PyCData_clear, /* tp_clear */ - 0, /* tp_richcompare */ - 0, /* tp_weaklistoffset */ - 0, /* tp_iter */ - 0, /* tp_iternext */ - PyCData_methods, /* tp_methods */ - PyCData_members, /* tp_members */ - 0, /* tp_getset */ - 0, /* tp_base */ - 0, /* tp_dict */ - 0, /* tp_descr_get */ - 0, /* tp_descr_set */ - 0, /* tp_dictoffset */ - 0, /* tp_init */ - 0, /* tp_alloc */ - 0, /* tp_new */ - 0, /* tp_free */ + PyVarObject_HEAD_INIT(NULL, 0) + "_ctypes._CData", + sizeof(CDataObject), /* tp_basicsize */ + 0, /* tp_itemsize */ + PyCData_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 */ + PyCData_nohash, /* tp_hash */ + 0, /* tp_call */ + 0, /* tp_str */ + 0, /* tp_getattro */ + 0, /* tp_setattro */ + &PyCData_as_buffer, /* tp_as_buffer */ + Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */ + "XXX to be provided", /* tp_doc */ + (traverseproc)PyCData_traverse, /* tp_traverse */ + (inquiry)PyCData_clear, /* tp_clear */ + 0, /* tp_richcompare */ + 0, /* tp_weaklistoffset */ + 0, /* tp_iter */ + 0, /* tp_iternext */ + PyCData_methods, /* tp_methods */ + PyCData_members, /* tp_members */ + 0, /* tp_getset */ + 0, /* tp_base */ + 0, /* tp_dict */ + 0, /* tp_descr_get */ + 0, /* tp_descr_set */ + 0, /* tp_dictoffset */ + 0, /* tp_init */ + 0, /* tp_alloc */ + 0, /* tp_new */ + 0, /* tp_free */ }; static int PyCData_MallocBuffer(CDataObject *obj, StgDictObject *dict) { - if ((size_t)dict->size <= sizeof(obj->b_value)) { - /* No need to call malloc, can use the default buffer */ - obj->b_ptr = (char *)&obj->b_value; - /* The b_needsfree flag does not mean that we actually did - call PyMem_Malloc to allocate the memory block; instead it - means we are the *owner* of the memory and are responsible - for freeing resources associated with the memory. This is - also the reason that b_needsfree is exposed to Python. - */ - obj->b_needsfree = 1; - } else { - /* In python 2.4, and ctypes 0.9.6, the malloc call took about - 33% of the creation time for c_int(). - */ - obj->b_ptr = (char *)PyMem_Malloc(dict->size); - if (obj->b_ptr == NULL) { - PyErr_NoMemory(); - return -1; - } - obj->b_needsfree = 1; - memset(obj->b_ptr, 0, dict->size); - } - obj->b_size = dict->size; - return 0; + if ((size_t)dict->size <= sizeof(obj->b_value)) { + /* No need to call malloc, can use the default buffer */ + obj->b_ptr = (char *)&obj->b_value; + /* The b_needsfree flag does not mean that we actually did + call PyMem_Malloc to allocate the memory block; instead it + means we are the *owner* of the memory and are responsible + for freeing resources associated with the memory. This is + also the reason that b_needsfree is exposed to Python. + */ + obj->b_needsfree = 1; + } else { + /* In python 2.4, and ctypes 0.9.6, the malloc call took about + 33% of the creation time for c_int(). + */ + obj->b_ptr = (char *)PyMem_Malloc(dict->size); + if (obj->b_ptr == NULL) { + PyErr_NoMemory(); + return -1; + } + obj->b_needsfree = 1; + memset(obj->b_ptr, 0, dict->size); + } + obj->b_size = dict->size; + return 0; } PyObject * PyCData_FromBaseObj(PyObject *type, PyObject *base, Py_ssize_t index, char *adr) { - CDataObject *cmem; - StgDictObject *dict; + CDataObject *cmem; + StgDictObject *dict; - assert(PyType_Check(type)); - dict = PyType_stgdict(type); - if (!dict) { - PyErr_SetString(PyExc_TypeError, - "abstract class"); - return NULL; - } - dict->flags |= DICTFLAG_FINAL; - cmem = (CDataObject *)((PyTypeObject *)type)->tp_alloc((PyTypeObject *)type, 0); - if (cmem == NULL) - return NULL; - assert(CDataObject_Check(cmem)); - - cmem->b_length = dict->length; - cmem->b_size = dict->size; - if (base) { /* use base's buffer */ - assert(CDataObject_Check(base)); - cmem->b_ptr = adr; - cmem->b_needsfree = 0; - Py_INCREF(base); - cmem->b_base = (CDataObject *)base; - cmem->b_index = index; - } else { /* copy contents of adr */ - if (-1 == PyCData_MallocBuffer(cmem, dict)) { - return NULL; - Py_DECREF(cmem); - } - memcpy(cmem->b_ptr, adr, dict->size); - cmem->b_index = index; - } - return (PyObject *)cmem; + assert(PyType_Check(type)); + dict = PyType_stgdict(type); + if (!dict) { + PyErr_SetString(PyExc_TypeError, + "abstract class"); + return NULL; + } + dict->flags |= DICTFLAG_FINAL; + cmem = (CDataObject *)((PyTypeObject *)type)->tp_alloc((PyTypeObject *)type, 0); + if (cmem == NULL) + return NULL; + assert(CDataObject_Check(cmem)); + + cmem->b_length = dict->length; + cmem->b_size = dict->size; + if (base) { /* use base's buffer */ + assert(CDataObject_Check(base)); + cmem->b_ptr = adr; + cmem->b_needsfree = 0; + Py_INCREF(base); + cmem->b_base = (CDataObject *)base; + cmem->b_index = index; + } else { /* copy contents of adr */ + if (-1 == PyCData_MallocBuffer(cmem, dict)) { + return NULL; + Py_DECREF(cmem); + } + memcpy(cmem->b_ptr, adr, dict->size); + cmem->b_index = index; + } + return (PyObject *)cmem; } /* @@ -2670,26 +2670,26 @@ PyObject * PyCData_AtAddress(PyObject *type, void *buf) { - CDataObject *pd; - StgDictObject *dict; + CDataObject *pd; + StgDictObject *dict; - assert(PyType_Check(type)); - dict = PyType_stgdict(type); - if (!dict) { - PyErr_SetString(PyExc_TypeError, - "abstract class"); - return NULL; - } - dict->flags |= DICTFLAG_FINAL; - - pd = (CDataObject *)((PyTypeObject *)type)->tp_alloc((PyTypeObject *)type, 0); - if (!pd) - return NULL; - assert(CDataObject_Check(pd)); - pd->b_ptr = (char *)buf; - pd->b_length = dict->length; - pd->b_size = dict->size; - return (PyObject *)pd; + assert(PyType_Check(type)); + dict = PyType_stgdict(type); + if (!dict) { + PyErr_SetString(PyExc_TypeError, + "abstract class"); + return NULL; + } + dict->flags |= DICTFLAG_FINAL; + + pd = (CDataObject *)((PyTypeObject *)type)->tp_alloc((PyTypeObject *)type, 0); + if (!pd) + return NULL; + assert(CDataObject_Check(pd)); + pd->b_ptr = (char *)buf; + pd->b_length = dict->length; + pd->b_size = dict->size; + return (PyObject *)pd; } /* @@ -2699,25 +2699,25 @@ */ int _ctypes_simple_instance(PyObject *obj) { - PyTypeObject *type = (PyTypeObject *)obj; + PyTypeObject *type = (PyTypeObject *)obj; - if (PyCSimpleTypeObject_Check(type)) - return type->tp_base != &Simple_Type; - return 0; + if (PyCSimpleTypeObject_Check(type)) + return type->tp_base != &Simple_Type; + return 0; } PyObject * PyCData_get(PyObject *type, GETFUNC getfunc, PyObject *src, - Py_ssize_t index, Py_ssize_t size, char *adr) + Py_ssize_t index, Py_ssize_t size, char *adr) { - StgDictObject *dict; - if (getfunc) - return getfunc(adr, size); - assert(type); - dict = PyType_stgdict(type); - if (dict && dict->getfunc && !_ctypes_simple_instance(type)) - return dict->getfunc(adr, size); - return PyCData_FromBaseObj(type, src, index, adr); + StgDictObject *dict; + if (getfunc) + return getfunc(adr, size); + assert(type); + dict = PyType_stgdict(type); + if (dict && dict->getfunc && !_ctypes_simple_instance(type)) + return dict->getfunc(adr, size); + return PyCData_FromBaseObj(type, src, index, adr); } /* @@ -2725,96 +2725,96 @@ */ static PyObject * _PyCData_set(CDataObject *dst, PyObject *type, SETFUNC setfunc, PyObject *value, - Py_ssize_t size, char *ptr) + Py_ssize_t size, char *ptr) { - CDataObject *src; + CDataObject *src; - if (setfunc) - return setfunc(ptr, value, size); - - if (!CDataObject_Check(value)) { - StgDictObject *dict = PyType_stgdict(type); - if (dict && dict->setfunc) - return dict->setfunc(ptr, value, size); - /* - If value is a tuple, we try to call the type with the tuple - and use the result! - */ - assert(PyType_Check(type)); - if (PyTuple_Check(value)) { - PyObject *ob; - PyObject *result; - ob = PyObject_CallObject(type, value); - if (ob == NULL) { - _ctypes_extend_error(PyExc_RuntimeError, "(%s) ", - ((PyTypeObject *)type)->tp_name); - return NULL; - } - result = _PyCData_set(dst, type, setfunc, ob, - size, ptr); - Py_DECREF(ob); - return result; - } else if (value == Py_None && PyCPointerTypeObject_Check(type)) { - *(void **)ptr = NULL; - Py_INCREF(Py_None); - return Py_None; - } else { - PyErr_Format(PyExc_TypeError, - "expected %s instance, got %s", - ((PyTypeObject *)type)->tp_name, - Py_TYPE(value)->tp_name); - return NULL; - } - } - src = (CDataObject *)value; - - if (PyObject_IsInstance(value, type)) { - memcpy(ptr, - src->b_ptr, - size); - - if (PyCPointerTypeObject_Check(type)) - /* XXX */; - - value = GetKeepedObjects(src); - Py_INCREF(value); - return value; - } - - if (PyCPointerTypeObject_Check(type) - && ArrayObject_Check(value)) { - StgDictObject *p1, *p2; - PyObject *keep; - p1 = PyObject_stgdict(value); - assert(p1); /* Cannot be NULL for array instances */ - p2 = PyType_stgdict(type); - assert(p2); /* Cannot be NULL for pointer types */ - - if (p1->proto != p2->proto) { - PyErr_Format(PyExc_TypeError, - "incompatible types, %s instance instead of %s instance", - Py_TYPE(value)->tp_name, - ((PyTypeObject *)type)->tp_name); - return NULL; - } - *(void **)ptr = src->b_ptr; - - keep = GetKeepedObjects(src); - /* - We are assigning an array object to a field which represents - a pointer. This has the same effect as converting an array - into a pointer. So, again, we have to keep the whole object - pointed to (which is the array in this case) alive, and not - only it's object list. So we create a tuple, containing - b_objects list PLUS the array itself, and return that! - */ - return PyTuple_Pack(2, keep, value); - } - PyErr_Format(PyExc_TypeError, - "incompatible types, %s instance instead of %s instance", - Py_TYPE(value)->tp_name, - ((PyTypeObject *)type)->tp_name); - return NULL; + if (setfunc) + return setfunc(ptr, value, size); + + if (!CDataObject_Check(value)) { + StgDictObject *dict = PyType_stgdict(type); + if (dict && dict->setfunc) + return dict->setfunc(ptr, value, size); + /* + If value is a tuple, we try to call the type with the tuple + and use the result! + */ + assert(PyType_Check(type)); + if (PyTuple_Check(value)) { + PyObject *ob; + PyObject *result; + ob = PyObject_CallObject(type, value); + if (ob == NULL) { + _ctypes_extend_error(PyExc_RuntimeError, "(%s) ", + ((PyTypeObject *)type)->tp_name); + return NULL; + } + result = _PyCData_set(dst, type, setfunc, ob, + size, ptr); + Py_DECREF(ob); + return result; + } else if (value == Py_None && PyCPointerTypeObject_Check(type)) { + *(void **)ptr = NULL; + Py_INCREF(Py_None); + return Py_None; + } else { + PyErr_Format(PyExc_TypeError, + "expected %s instance, got %s", + ((PyTypeObject *)type)->tp_name, + Py_TYPE(value)->tp_name); + return NULL; + } + } + src = (CDataObject *)value; + + if (PyObject_IsInstance(value, type)) { + memcpy(ptr, + src->b_ptr, + size); + + if (PyCPointerTypeObject_Check(type)) + /* XXX */; + + value = GetKeepedObjects(src); + Py_INCREF(value); + return value; + } + + if (PyCPointerTypeObject_Check(type) + && ArrayObject_Check(value)) { + StgDictObject *p1, *p2; + PyObject *keep; + p1 = PyObject_stgdict(value); + assert(p1); /* Cannot be NULL for array instances */ + p2 = PyType_stgdict(type); + assert(p2); /* Cannot be NULL for pointer types */ + + if (p1->proto != p2->proto) { + PyErr_Format(PyExc_TypeError, + "incompatible types, %s instance instead of %s instance", + Py_TYPE(value)->tp_name, + ((PyTypeObject *)type)->tp_name); + return NULL; + } + *(void **)ptr = src->b_ptr; + + keep = GetKeepedObjects(src); + /* + We are assigning an array object to a field which represents + a pointer. This has the same effect as converting an array + into a pointer. So, again, we have to keep the whole object + pointed to (which is the array in this case) alive, and not + only it's object list. So we create a tuple, containing + b_objects list PLUS the array itself, and return that! + */ + return PyTuple_Pack(2, keep, value); + } + PyErr_Format(PyExc_TypeError, + "incompatible types, %s instance instead of %s instance", + Py_TYPE(value)->tp_name, + ((PyTypeObject *)type)->tp_name); + return NULL; } /* @@ -2823,58 +2823,58 @@ */ int PyCData_set(PyObject *dst, PyObject *type, SETFUNC setfunc, PyObject *value, - Py_ssize_t index, Py_ssize_t size, char *ptr) + Py_ssize_t index, Py_ssize_t size, char *ptr) { - CDataObject *mem = (CDataObject *)dst; - PyObject *result; + CDataObject *mem = (CDataObject *)dst; + PyObject *result; - if (!CDataObject_Check(dst)) { - PyErr_SetString(PyExc_TypeError, - "not a ctype instance"); - return -1; - } + if (!CDataObject_Check(dst)) { + PyErr_SetString(PyExc_TypeError, + "not a ctype instance"); + return -1; + } - result = _PyCData_set(mem, type, setfunc, value, - size, ptr); - if (result == NULL) - return -1; + result = _PyCData_set(mem, type, setfunc, value, + size, ptr); + if (result == NULL) + return -1; - /* KeepRef steals a refcount from it's last argument */ - /* If KeepRef fails, we are stumped. The dst memory block has already - been changed */ - return KeepRef(mem, index, result); + /* KeepRef steals a refcount from it's last argument */ + /* If KeepRef fails, we are stumped. The dst memory block has already + been changed */ + return KeepRef(mem, index, result); } - + /******************************************************************/ static PyObject * GenericPyCData_new(PyTypeObject *type, PyObject *args, PyObject *kwds) { - CDataObject *obj; - StgDictObject *dict; + CDataObject *obj; + StgDictObject *dict; - dict = PyType_stgdict((PyObject *)type); - if (!dict) { - PyErr_SetString(PyExc_TypeError, - "abstract class"); - return NULL; - } - dict->flags |= DICTFLAG_FINAL; - - obj = (CDataObject *)type->tp_alloc(type, 0); - if (!obj) - return NULL; - - obj->b_base = NULL; - obj->b_index = 0; - obj->b_objects = NULL; - obj->b_length = dict->length; - - if (-1 == PyCData_MallocBuffer(obj, dict)) { - Py_DECREF(obj); - return NULL; - } - return (PyObject *)obj; + dict = PyType_stgdict((PyObject *)type); + if (!dict) { + PyErr_SetString(PyExc_TypeError, + "abstract class"); + return NULL; + } + dict->flags |= DICTFLAG_FINAL; + + obj = (CDataObject *)type->tp_alloc(type, 0); + if (!obj) + return NULL; + + obj->b_base = NULL; + obj->b_index = 0; + obj->b_objects = NULL; + obj->b_length = dict->length; + + if (-1 == PyCData_MallocBuffer(obj, dict)) { + Py_DECREF(obj); + return NULL; + } + return (PyObject *)obj; } /*****************************************************************/ /* @@ -2884,165 +2884,165 @@ static int PyCFuncPtr_set_errcheck(PyCFuncPtrObject *self, PyObject *ob) { - if (ob && !PyCallable_Check(ob)) { - PyErr_SetString(PyExc_TypeError, - "the errcheck attribute must be callable"); - return -1; - } - Py_XDECREF(self->errcheck); - Py_XINCREF(ob); - self->errcheck = ob; - return 0; + if (ob && !PyCallable_Check(ob)) { + PyErr_SetString(PyExc_TypeError, + "the errcheck attribute must be callable"); + return -1; + } + Py_XDECREF(self->errcheck); + Py_XINCREF(ob); + self->errcheck = ob; + return 0; } static PyObject * PyCFuncPtr_get_errcheck(PyCFuncPtrObject *self) { - if (self->errcheck) { - Py_INCREF(self->errcheck); - return self->errcheck; - } - Py_INCREF(Py_None); - return Py_None; + if (self->errcheck) { + Py_INCREF(self->errcheck); + return self->errcheck; + } + Py_INCREF(Py_None); + return Py_None; } static int PyCFuncPtr_set_restype(PyCFuncPtrObject *self, PyObject *ob) { - if (ob == NULL) { - Py_XDECREF(self->restype); - self->restype = NULL; - Py_XDECREF(self->checker); - self->checker = NULL; - return 0; - } - if (ob != Py_None && !PyType_stgdict(ob) && !PyCallable_Check(ob)) { - PyErr_SetString(PyExc_TypeError, - "restype must be a type, a callable, or None"); - return -1; - } - Py_XDECREF(self->checker); - Py_XDECREF(self->restype); - Py_INCREF(ob); - self->restype = ob; - self->checker = PyObject_GetAttrString(ob, "_check_retval_"); - if (self->checker == NULL) - PyErr_Clear(); - return 0; + if (ob == NULL) { + Py_XDECREF(self->restype); + self->restype = NULL; + Py_XDECREF(self->checker); + self->checker = NULL; + return 0; + } + if (ob != Py_None && !PyType_stgdict(ob) && !PyCallable_Check(ob)) { + PyErr_SetString(PyExc_TypeError, + "restype must be a type, a callable, or None"); + return -1; + } + Py_XDECREF(self->checker); + Py_XDECREF(self->restype); + Py_INCREF(ob); + self->restype = ob; + self->checker = PyObject_GetAttrString(ob, "_check_retval_"); + if (self->checker == NULL) + PyErr_Clear(); + return 0; } static PyObject * PyCFuncPtr_get_restype(PyCFuncPtrObject *self) { - StgDictObject *dict; - if (self->restype) { - Py_INCREF(self->restype); - return self->restype; - } - dict = PyObject_stgdict((PyObject *)self); - assert(dict); /* Cannot be NULL for PyCFuncPtrObject instances */ - if (dict->restype) { - Py_INCREF(dict->restype); - return dict->restype; - } else { - Py_INCREF(Py_None); - return Py_None; - } + StgDictObject *dict; + if (self->restype) { + Py_INCREF(self->restype); + return self->restype; + } + dict = PyObject_stgdict((PyObject *)self); + assert(dict); /* Cannot be NULL for PyCFuncPtrObject instances */ + if (dict->restype) { + Py_INCREF(dict->restype); + return dict->restype; + } else { + Py_INCREF(Py_None); + return Py_None; + } } static int PyCFuncPtr_set_argtypes(PyCFuncPtrObject *self, PyObject *ob) { - PyObject *converters; + PyObject *converters; - if (ob == NULL || ob == Py_None) { - Py_XDECREF(self->converters); - self->converters = NULL; - Py_XDECREF(self->argtypes); - self->argtypes = NULL; - } else { - converters = converters_from_argtypes(ob); - if (!converters) - return -1; - Py_XDECREF(self->converters); - self->converters = converters; - Py_XDECREF(self->argtypes); - Py_INCREF(ob); - self->argtypes = ob; - } - return 0; + if (ob == NULL || ob == Py_None) { + Py_XDECREF(self->converters); + self->converters = NULL; + Py_XDECREF(self->argtypes); + self->argtypes = NULL; + } else { + converters = converters_from_argtypes(ob); + if (!converters) + return -1; + Py_XDECREF(self->converters); + self->converters = converters; + Py_XDECREF(self->argtypes); + Py_INCREF(ob); + self->argtypes = ob; + } + return 0; } static PyObject * PyCFuncPtr_get_argtypes(PyCFuncPtrObject *self) { - StgDictObject *dict; - if (self->argtypes) { - Py_INCREF(self->argtypes); - return self->argtypes; - } - dict = PyObject_stgdict((PyObject *)self); - assert(dict); /* Cannot be NULL for PyCFuncPtrObject instances */ - if (dict->argtypes) { - Py_INCREF(dict->argtypes); - return dict->argtypes; - } else { - Py_INCREF(Py_None); - return Py_None; - } + StgDictObject *dict; + if (self->argtypes) { + Py_INCREF(self->argtypes); + return self->argtypes; + } + dict = PyObject_stgdict((PyObject *)self); + assert(dict); /* Cannot be NULL for PyCFuncPtrObject instances */ + if (dict->argtypes) { + Py_INCREF(dict->argtypes); + return dict->argtypes; + } else { + Py_INCREF(Py_None); + return Py_None; + } } static PyGetSetDef PyCFuncPtr_getsets[] = { - { "errcheck", (getter)PyCFuncPtr_get_errcheck, (setter)PyCFuncPtr_set_errcheck, - "a function to check for errors", NULL }, - { "restype", (getter)PyCFuncPtr_get_restype, (setter)PyCFuncPtr_set_restype, - "specify the result type", NULL }, - { "argtypes", (getter)PyCFuncPtr_get_argtypes, - (setter)PyCFuncPtr_set_argtypes, - "specify the argument types", NULL }, - { NULL, NULL } + { "errcheck", (getter)PyCFuncPtr_get_errcheck, (setter)PyCFuncPtr_set_errcheck, + "a function to check for errors", NULL }, + { "restype", (getter)PyCFuncPtr_get_restype, (setter)PyCFuncPtr_set_restype, + "specify the result type", NULL }, + { "argtypes", (getter)PyCFuncPtr_get_argtypes, + (setter)PyCFuncPtr_set_argtypes, + "specify the argument types", NULL }, + { NULL, NULL } }; #ifdef MS_WIN32 static PPROC FindAddress(void *handle, char *name, PyObject *type) { #ifdef MS_WIN64 - /* win64 has no stdcall calling conv, so it should - also not have the name mangling of it. - */ - return (PPROC)GetProcAddress(handle, name); + /* win64 has no stdcall calling conv, so it should + also not have the name mangling of it. + */ + return (PPROC)GetProcAddress(handle, name); #else - PPROC address; - char *mangled_name; - int i; - StgDictObject *dict; - - address = (PPROC)GetProcAddress(handle, name); - if (address) - return address; - if (((size_t)name & ~0xFFFF) == 0) { - return NULL; - } - - dict = PyType_stgdict((PyObject *)type); - /* It should not happen that dict is NULL, but better be safe */ - if (dict==NULL || dict->flags & FUNCFLAG_CDECL) - return address; - - /* for stdcall, try mangled names: - funcname -> _funcname@ - where n is 0, 4, 8, 12, ..., 128 - */ - mangled_name = alloca(strlen(name) + 1 + 1 + 1 + 3); /* \0 _ @ %d */ - if (!mangled_name) - return NULL; - for (i = 0; i < 32; ++i) { - sprintf(mangled_name, "_%s@%d", name, i*4); - address = (PPROC)GetProcAddress(handle, mangled_name); - if (address) - return address; - } - return NULL; + PPROC address; + char *mangled_name; + int i; + StgDictObject *dict; + + address = (PPROC)GetProcAddress(handle, name); + if (address) + return address; + if (((size_t)name & ~0xFFFF) == 0) { + return NULL; + } + + dict = PyType_stgdict((PyObject *)type); + /* It should not happen that dict is NULL, but better be safe */ + if (dict==NULL || dict->flags & FUNCFLAG_CDECL) + return address; + + /* for stdcall, try mangled names: + funcname -> _funcname@ + where n is 0, 4, 8, 12, ..., 128 + */ + mangled_name = alloca(strlen(name) + 1 + 1 + 1 + 3); /* \0 _ @ %d */ + if (!mangled_name) + return NULL; + for (i = 0; i < 32; ++i) { + sprintf(mangled_name, "_%s@%d", name, i*4); + address = (PPROC)GetProcAddress(handle, mangled_name); + if (address) + return address; + } + return NULL; #endif } #endif @@ -3051,227 +3051,227 @@ static int _check_outarg_type(PyObject *arg, Py_ssize_t index) { - StgDictObject *dict; + StgDictObject *dict; - if (PyCPointerTypeObject_Check(arg)) - return 1; + if (PyCPointerTypeObject_Check(arg)) + return 1; - if (PyCArrayTypeObject_Check(arg)) - return 1; + if (PyCArrayTypeObject_Check(arg)) + return 1; - dict = PyType_stgdict(arg); - if (dict - /* simple pointer types, c_void_p, c_wchar_p, BSTR, ... */ - && PyUnicode_Check(dict->proto) + dict = PyType_stgdict(arg); + if (dict + /* simple pointer types, c_void_p, c_wchar_p, BSTR, ... */ + && PyUnicode_Check(dict->proto) /* We only allow c_void_p, c_char_p and c_wchar_p as a simple output parameter type */ - && (strchr("PzZ", _PyUnicode_AsString(dict->proto)[0]))) { - return 1; - } - - PyErr_Format(PyExc_TypeError, - "'out' parameter %d must be a pointer type, not %s", - Py_SAFE_DOWNCAST(index, Py_ssize_t, int), - PyType_Check(arg) ? - ((PyTypeObject *)arg)->tp_name : - Py_TYPE(arg)->tp_name); - return 0; + && (strchr("PzZ", _PyUnicode_AsString(dict->proto)[0]))) { + return 1; + } + + PyErr_Format(PyExc_TypeError, + "'out' parameter %d must be a pointer type, not %s", + Py_SAFE_DOWNCAST(index, Py_ssize_t, int), + PyType_Check(arg) ? + ((PyTypeObject *)arg)->tp_name : + Py_TYPE(arg)->tp_name); + return 0; } /* Returns 1 on success, 0 on error */ static int _validate_paramflags(PyTypeObject *type, PyObject *paramflags) { - Py_ssize_t i, len; - StgDictObject *dict; - PyObject *argtypes; - - dict = PyType_stgdict((PyObject *)type); - assert(dict); /* Cannot be NULL. 'type' is a PyCFuncPtr type. */ - argtypes = dict->argtypes; - - if (paramflags == NULL || dict->argtypes == NULL) - return 1; - - if (!PyTuple_Check(paramflags)) { - PyErr_SetString(PyExc_TypeError, - "paramflags must be a tuple or None"); - return 0; - } - - len = PyTuple_GET_SIZE(paramflags); - if (len != PyTuple_GET_SIZE(dict->argtypes)) { - PyErr_SetString(PyExc_ValueError, - "paramflags must have the same length as argtypes"); - return 0; - } - - for (i = 0; i < len; ++i) { - PyObject *item = PyTuple_GET_ITEM(paramflags, i); - int flag; - char *name; - PyObject *defval; - PyObject *typ; - if (!PyArg_ParseTuple(item, "i|ZO", &flag, &name, &defval)) { - PyErr_SetString(PyExc_TypeError, - "paramflags must be a sequence of (int [,string [,value]]) tuples"); - return 0; - } - typ = PyTuple_GET_ITEM(argtypes, i); - switch (flag & (PARAMFLAG_FIN | PARAMFLAG_FOUT | PARAMFLAG_FLCID)) { - case 0: - case PARAMFLAG_FIN: - case PARAMFLAG_FIN | PARAMFLAG_FLCID: - case PARAMFLAG_FIN | PARAMFLAG_FOUT: - break; - case PARAMFLAG_FOUT: - if (!_check_outarg_type(typ, i+1)) - return 0; - break; - default: - PyErr_Format(PyExc_TypeError, - "paramflag value %d not supported", - flag); - return 0; - } - } - return 1; + Py_ssize_t i, len; + StgDictObject *dict; + PyObject *argtypes; + + dict = PyType_stgdict((PyObject *)type); + assert(dict); /* Cannot be NULL. 'type' is a PyCFuncPtr type. */ + argtypes = dict->argtypes; + + if (paramflags == NULL || dict->argtypes == NULL) + return 1; + + if (!PyTuple_Check(paramflags)) { + PyErr_SetString(PyExc_TypeError, + "paramflags must be a tuple or None"); + return 0; + } + + len = PyTuple_GET_SIZE(paramflags); + if (len != PyTuple_GET_SIZE(dict->argtypes)) { + PyErr_SetString(PyExc_ValueError, + "paramflags must have the same length as argtypes"); + return 0; + } + + for (i = 0; i < len; ++i) { + PyObject *item = PyTuple_GET_ITEM(paramflags, i); + int flag; + char *name; + PyObject *defval; + PyObject *typ; + if (!PyArg_ParseTuple(item, "i|ZO", &flag, &name, &defval)) { + PyErr_SetString(PyExc_TypeError, + "paramflags must be a sequence of (int [,string [,value]]) tuples"); + return 0; + } + typ = PyTuple_GET_ITEM(argtypes, i); + switch (flag & (PARAMFLAG_FIN | PARAMFLAG_FOUT | PARAMFLAG_FLCID)) { + case 0: + case PARAMFLAG_FIN: + case PARAMFLAG_FIN | PARAMFLAG_FLCID: + case PARAMFLAG_FIN | PARAMFLAG_FOUT: + break; + case PARAMFLAG_FOUT: + if (!_check_outarg_type(typ, i+1)) + return 0; + break; + default: + PyErr_Format(PyExc_TypeError, + "paramflag value %d not supported", + flag); + return 0; + } + } + return 1; } static int _get_name(PyObject *obj, char **pname) { #ifdef MS_WIN32 - if (PyLong_Check(obj)) { - /* We have to use MAKEINTRESOURCEA for Windows CE. - Works on Windows as well, of course. - */ - *pname = MAKEINTRESOURCEA(PyLong_AsUnsignedLongMask(obj) & 0xFFFF); - return 1; - } + if (PyLong_Check(obj)) { + /* We have to use MAKEINTRESOURCEA for Windows CE. + Works on Windows as well, of course. + */ + *pname = MAKEINTRESOURCEA(PyLong_AsUnsignedLongMask(obj) & 0xFFFF); + return 1; + } #endif - if (PyBytes_Check(obj)) { - *pname = PyBytes_AS_STRING(obj); - return *pname ? 1 : 0; - } - if (PyUnicode_Check(obj)) { - *pname = _PyUnicode_AsString(obj); - return *pname ? 1 : 0; - } - PyErr_SetString(PyExc_TypeError, - "function name must be string or integer"); - return 0; + if (PyBytes_Check(obj)) { + *pname = PyBytes_AS_STRING(obj); + return *pname ? 1 : 0; + } + if (PyUnicode_Check(obj)) { + *pname = _PyUnicode_AsString(obj); + return *pname ? 1 : 0; + } + PyErr_SetString(PyExc_TypeError, + "function name must be string or integer"); + return 0; } static PyObject * PyCFuncPtr_FromDll(PyTypeObject *type, PyObject *args, PyObject *kwds) { - char *name; - int (* address)(void); - PyObject *dll; - PyObject *obj; - PyCFuncPtrObject *self; - void *handle; - PyObject *paramflags = NULL; - - if (!PyArg_ParseTuple(args, "(O&O)|O", _get_name, &name, &dll, ¶mflags)) - return NULL; - if (paramflags == Py_None) - paramflags = NULL; - - obj = PyObject_GetAttrString(dll, "_handle"); - if (!obj) - return NULL; - if (!PyLong_Check(obj)) { - PyErr_SetString(PyExc_TypeError, - "the _handle attribute of the second argument must be an integer"); - Py_DECREF(obj); - return NULL; - } - handle = (void *)PyLong_AsVoidPtr(obj); - Py_DECREF(obj); - if (PyErr_Occurred()) { - PyErr_SetString(PyExc_ValueError, - "could not convert the _handle attribute to a pointer"); - return NULL; - } + char *name; + int (* address)(void); + PyObject *dll; + PyObject *obj; + PyCFuncPtrObject *self; + void *handle; + PyObject *paramflags = NULL; + + if (!PyArg_ParseTuple(args, "(O&O)|O", _get_name, &name, &dll, ¶mflags)) + return NULL; + if (paramflags == Py_None) + paramflags = NULL; + + obj = PyObject_GetAttrString(dll, "_handle"); + if (!obj) + return NULL; + if (!PyLong_Check(obj)) { + PyErr_SetString(PyExc_TypeError, + "the _handle attribute of the second argument must be an integer"); + Py_DECREF(obj); + return NULL; + } + handle = (void *)PyLong_AsVoidPtr(obj); + Py_DECREF(obj); + if (PyErr_Occurred()) { + PyErr_SetString(PyExc_ValueError, + "could not convert the _handle attribute to a pointer"); + return NULL; + } #ifdef MS_WIN32 - address = FindAddress(handle, name, (PyObject *)type); - if (!address) { - if (!IS_INTRESOURCE(name)) - PyErr_Format(PyExc_AttributeError, - "function '%s' not found", - name); - else - PyErr_Format(PyExc_AttributeError, - "function ordinal %d not found", - (WORD)(size_t)name); - return NULL; - } + address = FindAddress(handle, name, (PyObject *)type); + if (!address) { + if (!IS_INTRESOURCE(name)) + PyErr_Format(PyExc_AttributeError, + "function '%s' not found", + name); + else + PyErr_Format(PyExc_AttributeError, + "function ordinal %d not found", + (WORD)(size_t)name); + return NULL; + } #else - address = (PPROC)ctypes_dlsym(handle, name); - if (!address) { + address = (PPROC)ctypes_dlsym(handle, name); + if (!address) { #ifdef __CYGWIN__ /* dlerror() isn't very helpful on cygwin */ - PyErr_Format(PyExc_AttributeError, - "function '%s' not found (%s) ", - name); + PyErr_Format(PyExc_AttributeError, + "function '%s' not found (%s) ", + name); #else - PyErr_SetString(PyExc_AttributeError, ctypes_dlerror()); + PyErr_SetString(PyExc_AttributeError, ctypes_dlerror()); #endif - return NULL; - } + return NULL; + } #endif - if (!_validate_paramflags(type, paramflags)) - return NULL; + if (!_validate_paramflags(type, paramflags)) + return NULL; - self = (PyCFuncPtrObject *)GenericPyCData_new(type, args, kwds); - if (!self) - return NULL; - - Py_XINCREF(paramflags); - self->paramflags = paramflags; - - *(void **)self->b_ptr = address; - - Py_INCREF((PyObject *)dll); /* for KeepRef */ - if (-1 == KeepRef((CDataObject *)self, 0, dll)) { - Py_DECREF((PyObject *)self); - return NULL; - } - - Py_INCREF(self); - self->callable = (PyObject *)self; - return (PyObject *)self; + self = (PyCFuncPtrObject *)GenericPyCData_new(type, args, kwds); + if (!self) + return NULL; + + Py_XINCREF(paramflags); + self->paramflags = paramflags; + + *(void **)self->b_ptr = address; + + Py_INCREF((PyObject *)dll); /* for KeepRef */ + if (-1 == KeepRef((CDataObject *)self, 0, dll)) { + Py_DECREF((PyObject *)self); + return NULL; + } + + Py_INCREF(self); + self->callable = (PyObject *)self; + return (PyObject *)self; } #ifdef MS_WIN32 static PyObject * PyCFuncPtr_FromVtblIndex(PyTypeObject *type, PyObject *args, PyObject *kwds) { - PyCFuncPtrObject *self; - int index; - char *name = NULL; - PyObject *paramflags = NULL; - GUID *iid = NULL; - Py_ssize_t iid_len = 0; - - if (!PyArg_ParseTuple(args, "is|Oz#", &index, &name, ¶mflags, &iid, &iid_len)) - return NULL; - if (paramflags == Py_None) - paramflags = NULL; - - if (!_validate_paramflags(type, paramflags)) - return NULL; - - self = (PyCFuncPtrObject *)GenericPyCData_new(type, args, kwds); - self->index = index + 0x1000; - Py_XINCREF(paramflags); - self->paramflags = paramflags; - if (iid_len == sizeof(GUID)) - self->iid = iid; - return (PyObject *)self; + PyCFuncPtrObject *self; + int index; + char *name = NULL; + PyObject *paramflags = NULL; + GUID *iid = NULL; + Py_ssize_t iid_len = 0; + + if (!PyArg_ParseTuple(args, "is|Oz#", &index, &name, ¶mflags, &iid, &iid_len)) + return NULL; + if (paramflags == Py_None) + paramflags = NULL; + + if (!_validate_paramflags(type, paramflags)) + return NULL; + + self = (PyCFuncPtrObject *)GenericPyCData_new(type, args, kwds); + self->index = index + 0x1000; + Py_XINCREF(paramflags); + self->paramflags = paramflags; + if (iid_len == sizeof(GUID)) + self->iid = iid; + return (PyObject *)self; } #endif @@ -3291,90 +3291,90 @@ static PyObject * PyCFuncPtr_new(PyTypeObject *type, PyObject *args, PyObject *kwds) { - PyCFuncPtrObject *self; - PyObject *callable; - StgDictObject *dict; - CThunkObject *thunk; + PyCFuncPtrObject *self; + PyObject *callable; + StgDictObject *dict; + CThunkObject *thunk; - if (PyTuple_GET_SIZE(args) == 0) - return GenericPyCData_new(type, args, kwds); + if (PyTuple_GET_SIZE(args) == 0) + return GenericPyCData_new(type, args, kwds); - if (1 <= PyTuple_GET_SIZE(args) && PyTuple_Check(PyTuple_GET_ITEM(args, 0))) - return PyCFuncPtr_FromDll(type, args, kwds); + if (1 <= PyTuple_GET_SIZE(args) && PyTuple_Check(PyTuple_GET_ITEM(args, 0))) + return PyCFuncPtr_FromDll(type, args, kwds); #ifdef MS_WIN32 - if (2 <= PyTuple_GET_SIZE(args) && PyLong_Check(PyTuple_GET_ITEM(args, 0))) - return PyCFuncPtr_FromVtblIndex(type, args, kwds); + if (2 <= PyTuple_GET_SIZE(args) && PyLong_Check(PyTuple_GET_ITEM(args, 0))) + return PyCFuncPtr_FromVtblIndex(type, args, kwds); #endif - if (1 == PyTuple_GET_SIZE(args) - && (PyLong_Check(PyTuple_GET_ITEM(args, 0)))) { - CDataObject *ob; - void *ptr = PyLong_AsVoidPtr(PyTuple_GET_ITEM(args, 0)); - if (ptr == NULL && PyErr_Occurred()) - return NULL; - ob = (CDataObject *)GenericPyCData_new(type, args, kwds); - if (ob == NULL) - return NULL; - *(void **)ob->b_ptr = ptr; - return (PyObject *)ob; - } - - if (!PyArg_ParseTuple(args, "O", &callable)) - return NULL; - if (!PyCallable_Check(callable)) { - PyErr_SetString(PyExc_TypeError, - "argument must be callable or integer function address"); - return NULL; - } - - /* XXX XXX This would allow to pass additional options. For COM - method *implementations*, we would probably want different - behaviour than in 'normal' callback functions: return a HRESULT if - an exception occurrs in the callback, and print the traceback not - only on the console, but also to OutputDebugString() or something - like that. - */ + if (1 == PyTuple_GET_SIZE(args) + && (PyLong_Check(PyTuple_GET_ITEM(args, 0)))) { + CDataObject *ob; + void *ptr = PyLong_AsVoidPtr(PyTuple_GET_ITEM(args, 0)); + if (ptr == NULL && PyErr_Occurred()) + return NULL; + ob = (CDataObject *)GenericPyCData_new(type, args, kwds); + if (ob == NULL) + return NULL; + *(void **)ob->b_ptr = ptr; + return (PyObject *)ob; + } + + if (!PyArg_ParseTuple(args, "O", &callable)) + return NULL; + if (!PyCallable_Check(callable)) { + PyErr_SetString(PyExc_TypeError, + "argument must be callable or integer function address"); + return NULL; + } + + /* XXX XXX This would allow to pass additional options. For COM + method *implementations*, we would probably want different + behaviour than in 'normal' callback functions: return a HRESULT if + an exception occurrs in the callback, and print the traceback not + only on the console, but also to OutputDebugString() or something + like that. + */ /* - if (kwds && PyDict_GetItemString(kwds, "options")) { - ... - } + if (kwds && PyDict_GetItemString(kwds, "options")) { + ... + } */ - dict = PyType_stgdict((PyObject *)type); - /* XXXX Fails if we do: 'PyCFuncPtr(lambda x: x)' */ - if (!dict || !dict->argtypes) { - PyErr_SetString(PyExc_TypeError, - "cannot construct instance of this class:" - " no argtypes"); - return NULL; - } - - thunk = _ctypes_alloc_callback(callable, - dict->argtypes, - dict->restype, - dict->flags); - if (!thunk) - return NULL; - - self = (PyCFuncPtrObject *)GenericPyCData_new(type, args, kwds); - if (self == NULL) { - Py_DECREF(thunk); - return NULL; - } - - Py_INCREF(callable); - self->callable = callable; - - self->thunk = thunk; - *(void **)self->b_ptr = (void *)thunk->pcl; - - Py_INCREF((PyObject *)thunk); /* for KeepRef */ - if (-1 == KeepRef((CDataObject *)self, 0, (PyObject *)thunk)) { - Py_DECREF((PyObject *)self); - return NULL; - } - return (PyObject *)self; + dict = PyType_stgdict((PyObject *)type); + /* XXXX Fails if we do: 'PyCFuncPtr(lambda x: x)' */ + if (!dict || !dict->argtypes) { + PyErr_SetString(PyExc_TypeError, + "cannot construct instance of this class:" + " no argtypes"); + return NULL; + } + + thunk = _ctypes_alloc_callback(callable, + dict->argtypes, + dict->restype, + dict->flags); + if (!thunk) + return NULL; + + self = (PyCFuncPtrObject *)GenericPyCData_new(type, args, kwds); + if (self == NULL) { + Py_DECREF(thunk); + return NULL; + } + + Py_INCREF(callable); + self->callable = callable; + + self->thunk = thunk; + *(void **)self->b_ptr = (void *)thunk->pcl; + + Py_INCREF((PyObject *)thunk); /* for KeepRef */ + if (-1 == KeepRef((CDataObject *)self, 0, (PyObject *)thunk)) { + Py_DECREF((PyObject *)self); + return NULL; + } + return (PyObject *)self; } @@ -3384,54 +3384,54 @@ static PyObject * _byref(PyObject *obj) { - PyCArgObject *parg; - if (!CDataObject_Check(obj)) { - PyErr_SetString(PyExc_TypeError, - "expected CData instance"); - return NULL; - } - - parg = PyCArgObject_new(); - if (parg == NULL) { - Py_DECREF(obj); - return NULL; - } - - parg->tag = 'P'; - parg->pffi_type = &ffi_type_pointer; - parg->obj = obj; - parg->value.p = ((CDataObject *)obj)->b_ptr; - return (PyObject *)parg; + PyCArgObject *parg; + if (!CDataObject_Check(obj)) { + PyErr_SetString(PyExc_TypeError, + "expected CData instance"); + return NULL; + } + + parg = PyCArgObject_new(); + if (parg == NULL) { + Py_DECREF(obj); + return NULL; + } + + parg->tag = 'P'; + parg->pffi_type = &ffi_type_pointer; + parg->obj = obj; + parg->value.p = ((CDataObject *)obj)->b_ptr; + return (PyObject *)parg; } static PyObject * _get_arg(int *pindex, PyObject *name, PyObject *defval, PyObject *inargs, PyObject *kwds) { - PyObject *v; + PyObject *v; - if (*pindex < PyTuple_GET_SIZE(inargs)) { - v = PyTuple_GET_ITEM(inargs, *pindex); - ++*pindex; - Py_INCREF(v); - return v; - } - if (kwds && (v = PyDict_GetItem(kwds, name))) { - ++*pindex; - Py_INCREF(v); - return v; - } - if (defval) { - Py_INCREF(defval); - return defval; - } - /* we can't currently emit a better error message */ - if (name) - PyErr_Format(PyExc_TypeError, - "required argument '%S' missing", name); - else - PyErr_Format(PyExc_TypeError, - "not enough arguments"); - return NULL; + if (*pindex < PyTuple_GET_SIZE(inargs)) { + v = PyTuple_GET_ITEM(inargs, *pindex); + ++*pindex; + Py_INCREF(v); + return v; + } + if (kwds && (v = PyDict_GetItem(kwds, name))) { + ++*pindex; + Py_INCREF(v); + return v; + } + if (defval) { + Py_INCREF(defval); + return defval; + } + /* we can't currently emit a better error message */ + if (name) + PyErr_Format(PyExc_TypeError, + "required argument '%S' missing", name); + else + PyErr_Format(PyExc_TypeError, + "not enough arguments"); + return NULL; } /* @@ -3454,166 +3454,166 @@ */ static PyObject * _build_callargs(PyCFuncPtrObject *self, PyObject *argtypes, - PyObject *inargs, PyObject *kwds, - int *poutmask, int *pinoutmask, unsigned int *pnumretvals) + PyObject *inargs, PyObject *kwds, + int *poutmask, int *pinoutmask, unsigned int *pnumretvals) { - PyObject *paramflags = self->paramflags; - PyObject *callargs; - StgDictObject *dict; - Py_ssize_t i, len; - int inargs_index = 0; - /* It's a little bit difficult to determine how many arguments the - function call requires/accepts. For simplicity, we count the consumed - args and compare this to the number of supplied args. */ - Py_ssize_t actual_args; - - *poutmask = 0; - *pinoutmask = 0; - *pnumretvals = 0; + PyObject *paramflags = self->paramflags; + PyObject *callargs; + StgDictObject *dict; + Py_ssize_t i, len; + int inargs_index = 0; + /* It's a little bit difficult to determine how many arguments the + function call requires/accepts. For simplicity, we count the consumed + args and compare this to the number of supplied args. */ + Py_ssize_t actual_args; + + *poutmask = 0; + *pinoutmask = 0; + *pnumretvals = 0; - /* Trivial cases, where we either return inargs itself, or a slice of it. */ - if (argtypes == NULL || paramflags == NULL || PyTuple_GET_SIZE(argtypes) == 0) { + /* Trivial cases, where we either return inargs itself, or a slice of it. */ + if (argtypes == NULL || paramflags == NULL || PyTuple_GET_SIZE(argtypes) == 0) { #ifdef MS_WIN32 - if (self->index) - return PyTuple_GetSlice(inargs, 1, PyTuple_GET_SIZE(inargs)); + if (self->index) + return PyTuple_GetSlice(inargs, 1, PyTuple_GET_SIZE(inargs)); #endif - Py_INCREF(inargs); - return inargs; - } - - len = PyTuple_GET_SIZE(argtypes); - callargs = PyTuple_New(len); /* the argument tuple we build */ - if (callargs == NULL) - return NULL; + Py_INCREF(inargs); + return inargs; + } + + len = PyTuple_GET_SIZE(argtypes); + callargs = PyTuple_New(len); /* the argument tuple we build */ + if (callargs == NULL) + return NULL; #ifdef MS_WIN32 - /* For a COM method, skip the first arg */ - if (self->index) { - inargs_index = 1; - } + /* For a COM method, skip the first arg */ + if (self->index) { + inargs_index = 1; + } #endif - for (i = 0; i < len; ++i) { - PyObject *item = PyTuple_GET_ITEM(paramflags, i); - PyObject *ob; - int flag; - PyObject *name = NULL; - PyObject *defval = NULL; - - /* This way seems to be ~2 us faster than the PyArg_ParseTuple - calls below. */ - /* We HAVE already checked that the tuple can be parsed with "i|ZO", so... */ - Py_ssize_t tsize = PyTuple_GET_SIZE(item); - flag = PyLong_AS_LONG(PyTuple_GET_ITEM(item, 0)); - name = tsize > 1 ? PyTuple_GET_ITEM(item, 1) : NULL; - defval = tsize > 2 ? PyTuple_GET_ITEM(item, 2) : NULL; - - switch (flag & (PARAMFLAG_FIN | PARAMFLAG_FOUT | PARAMFLAG_FLCID)) { - case PARAMFLAG_FIN | PARAMFLAG_FLCID: - /* ['in', 'lcid'] parameter. Always taken from defval, - if given, else the integer 0. */ - if (defval == NULL) { - defval = PyLong_FromLong(0); - if (defval == NULL) - goto error; - } else - Py_INCREF(defval); - PyTuple_SET_ITEM(callargs, i, defval); - break; - case (PARAMFLAG_FIN | PARAMFLAG_FOUT): - *pinoutmask |= (1 << i); /* mark as inout arg */ - (*pnumretvals)++; - /* fall through to PARAMFLAG_FIN... */ - case 0: - case PARAMFLAG_FIN: - /* 'in' parameter. Copy it from inargs. */ - ob =_get_arg(&inargs_index, name, defval, inargs, kwds); - if (ob == NULL) - goto error; - PyTuple_SET_ITEM(callargs, i, ob); - break; - case PARAMFLAG_FOUT: - /* XXX Refactor this code into a separate function. */ - /* 'out' parameter. - argtypes[i] must be a POINTER to a c type. - - Cannot by supplied in inargs, but a defval will be used - if available. XXX Should we support getting it from kwds? - */ - if (defval) { - /* XXX Using mutable objects as defval will - make the function non-threadsafe, unless we - copy the object in each invocation */ - Py_INCREF(defval); - PyTuple_SET_ITEM(callargs, i, defval); - *poutmask |= (1 << i); /* mark as out arg */ - (*pnumretvals)++; - break; - } - ob = PyTuple_GET_ITEM(argtypes, i); - dict = PyType_stgdict(ob); - if (dict == NULL) { - /* Cannot happen: _validate_paramflags() - would not accept such an object */ - PyErr_Format(PyExc_RuntimeError, - "NULL stgdict unexpected"); - goto error; - } - if (PyUnicode_Check(dict->proto)) { - PyErr_Format( - PyExc_TypeError, - "%s 'out' parameter must be passed as default value", - ((PyTypeObject *)ob)->tp_name); - goto error; - } - if (PyCArrayTypeObject_Check(ob)) - ob = PyObject_CallObject(ob, NULL); - else - /* Create an instance of the pointed-to type */ - ob = PyObject_CallObject(dict->proto, NULL); - /* - XXX Is the following correct any longer? - We must not pass a byref() to the array then but - the array instance itself. Then, we cannot retrive - the result from the PyCArgObject. - */ - if (ob == NULL) - goto error; - /* The .from_param call that will ocurr later will pass this - as a byref parameter. */ - PyTuple_SET_ITEM(callargs, i, ob); - *poutmask |= (1 << i); /* mark as out arg */ - (*pnumretvals)++; - break; - default: - PyErr_Format(PyExc_ValueError, - "paramflag %d not yet implemented", flag); - goto error; - break; - } - } - - /* We have counted the arguments we have consumed in 'inargs_index'. This - must be the same as len(inargs) + len(kwds), otherwise we have - either too much or not enough arguments. */ - - actual_args = PyTuple_GET_SIZE(inargs) + (kwds ? PyDict_Size(kwds) : 0); - if (actual_args != inargs_index) { - /* When we have default values or named parameters, this error - message is misleading. See unittests/test_paramflags.py - */ - PyErr_Format(PyExc_TypeError, - "call takes exactly %d arguments (%zd given)", - inargs_index, actual_args); - goto error; - } - - /* outmask is a bitmask containing indexes into callargs. Items at - these indexes contain values to return. - */ - return callargs; + for (i = 0; i < len; ++i) { + PyObject *item = PyTuple_GET_ITEM(paramflags, i); + PyObject *ob; + int flag; + PyObject *name = NULL; + PyObject *defval = NULL; + + /* This way seems to be ~2 us faster than the PyArg_ParseTuple + calls below. */ + /* We HAVE already checked that the tuple can be parsed with "i|ZO", so... */ + Py_ssize_t tsize = PyTuple_GET_SIZE(item); + flag = PyLong_AS_LONG(PyTuple_GET_ITEM(item, 0)); + name = tsize > 1 ? PyTuple_GET_ITEM(item, 1) : NULL; + defval = tsize > 2 ? PyTuple_GET_ITEM(item, 2) : NULL; + + switch (flag & (PARAMFLAG_FIN | PARAMFLAG_FOUT | PARAMFLAG_FLCID)) { + case PARAMFLAG_FIN | PARAMFLAG_FLCID: + /* ['in', 'lcid'] parameter. Always taken from defval, + if given, else the integer 0. */ + if (defval == NULL) { + defval = PyLong_FromLong(0); + if (defval == NULL) + goto error; + } else + Py_INCREF(defval); + PyTuple_SET_ITEM(callargs, i, defval); + break; + case (PARAMFLAG_FIN | PARAMFLAG_FOUT): + *pinoutmask |= (1 << i); /* mark as inout arg */ + (*pnumretvals)++; + /* fall through to PARAMFLAG_FIN... */ + case 0: + case PARAMFLAG_FIN: + /* 'in' parameter. Copy it from inargs. */ + ob =_get_arg(&inargs_index, name, defval, inargs, kwds); + if (ob == NULL) + goto error; + PyTuple_SET_ITEM(callargs, i, ob); + break; + case PARAMFLAG_FOUT: + /* XXX Refactor this code into a separate function. */ + /* 'out' parameter. + argtypes[i] must be a POINTER to a c type. + + Cannot by supplied in inargs, but a defval will be used + if available. XXX Should we support getting it from kwds? + */ + if (defval) { + /* XXX Using mutable objects as defval will + make the function non-threadsafe, unless we + copy the object in each invocation */ + Py_INCREF(defval); + PyTuple_SET_ITEM(callargs, i, defval); + *poutmask |= (1 << i); /* mark as out arg */ + (*pnumretvals)++; + break; + } + ob = PyTuple_GET_ITEM(argtypes, i); + dict = PyType_stgdict(ob); + if (dict == NULL) { + /* Cannot happen: _validate_paramflags() + would not accept such an object */ + PyErr_Format(PyExc_RuntimeError, + "NULL stgdict unexpected"); + goto error; + } + if (PyUnicode_Check(dict->proto)) { + PyErr_Format( + PyExc_TypeError, + "%s 'out' parameter must be passed as default value", + ((PyTypeObject *)ob)->tp_name); + goto error; + } + if (PyCArrayTypeObject_Check(ob)) + ob = PyObject_CallObject(ob, NULL); + else + /* Create an instance of the pointed-to type */ + ob = PyObject_CallObject(dict->proto, NULL); + /* + XXX Is the following correct any longer? + We must not pass a byref() to the array then but + the array instance itself. Then, we cannot retrive + the result from the PyCArgObject. + */ + if (ob == NULL) + goto error; + /* The .from_param call that will ocurr later will pass this + as a byref parameter. */ + PyTuple_SET_ITEM(callargs, i, ob); + *poutmask |= (1 << i); /* mark as out arg */ + (*pnumretvals)++; + break; + default: + PyErr_Format(PyExc_ValueError, + "paramflag %d not yet implemented", flag); + goto error; + break; + } + } + + /* We have counted the arguments we have consumed in 'inargs_index'. This + must be the same as len(inargs) + len(kwds), otherwise we have + either too much or not enough arguments. */ + + actual_args = PyTuple_GET_SIZE(inargs) + (kwds ? PyDict_Size(kwds) : 0); + if (actual_args != inargs_index) { + /* When we have default values or named parameters, this error + message is misleading. See unittests/test_paramflags.py + */ + PyErr_Format(PyExc_TypeError, + "call takes exactly %d arguments (%zd given)", + inargs_index, actual_args); + goto error; + } + + /* outmask is a bitmask containing indexes into callargs. Items at + these indexes contain values to return. + */ + return callargs; error: - Py_DECREF(callargs); - return NULL; + Py_DECREF(callargs); + return NULL; } /* See also: @@ -3626,307 +3626,307 @@ */ static PyObject * _build_result(PyObject *result, PyObject *callargs, - int outmask, int inoutmask, unsigned int numretvals) + int outmask, int inoutmask, unsigned int numretvals) { - unsigned int i, index; - int bit; - PyObject *tup = NULL; - - if (callargs == NULL) - return result; - if (result == NULL || numretvals == 0) { - Py_DECREF(callargs); - return result; - } - Py_DECREF(result); - - /* tup will not be allocated if numretvals == 1 */ - /* allocate tuple to hold the result */ - if (numretvals > 1) { - tup = PyTuple_New(numretvals); - if (tup == NULL) { - Py_DECREF(callargs); - return NULL; - } - } - - index = 0; - for (bit = 1, i = 0; i < 32; ++i, bit <<= 1) { - PyObject *v; - if (bit & inoutmask) { - v = PyTuple_GET_ITEM(callargs, i); - Py_INCREF(v); - if (numretvals == 1) { - Py_DECREF(callargs); - return v; - } - PyTuple_SET_ITEM(tup, index, v); - index++; - } else if (bit & outmask) { - v = PyTuple_GET_ITEM(callargs, i); - v = PyObject_CallMethod(v, "__ctypes_from_outparam__", NULL); - if (v == NULL || numretvals == 1) { - Py_DECREF(callargs); - return v; - } - PyTuple_SET_ITEM(tup, index, v); - index++; - } - if (index == numretvals) - break; - } + unsigned int i, index; + int bit; + PyObject *tup = NULL; + + if (callargs == NULL) + return result; + if (result == NULL || numretvals == 0) { + Py_DECREF(callargs); + return result; + } + Py_DECREF(result); + + /* tup will not be allocated if numretvals == 1 */ + /* allocate tuple to hold the result */ + if (numretvals > 1) { + tup = PyTuple_New(numretvals); + if (tup == NULL) { + Py_DECREF(callargs); + return NULL; + } + } + + index = 0; + for (bit = 1, i = 0; i < 32; ++i, bit <<= 1) { + PyObject *v; + if (bit & inoutmask) { + v = PyTuple_GET_ITEM(callargs, i); + Py_INCREF(v); + if (numretvals == 1) { + Py_DECREF(callargs); + return v; + } + PyTuple_SET_ITEM(tup, index, v); + index++; + } else if (bit & outmask) { + v = PyTuple_GET_ITEM(callargs, i); + v = PyObject_CallMethod(v, "__ctypes_from_outparam__", NULL); + if (v == NULL || numretvals == 1) { + Py_DECREF(callargs); + return v; + } + PyTuple_SET_ITEM(tup, index, v); + index++; + } + if (index == numretvals) + break; + } - Py_DECREF(callargs); - return tup; + Py_DECREF(callargs); + return tup; } static PyObject * PyCFuncPtr_call(PyCFuncPtrObject *self, PyObject *inargs, PyObject *kwds) { - PyObject *restype; - PyObject *converters; - PyObject *checker; - PyObject *argtypes; - StgDictObject *dict = PyObject_stgdict((PyObject *)self); - PyObject *result; - PyObject *callargs; - PyObject *errcheck; + PyObject *restype; + PyObject *converters; + PyObject *checker; + PyObject *argtypes; + StgDictObject *dict = PyObject_stgdict((PyObject *)self); + PyObject *result; + PyObject *callargs; + PyObject *errcheck; #ifdef MS_WIN32 - IUnknown *piunk = NULL; + IUnknown *piunk = NULL; #endif - void *pProc = NULL; + void *pProc = NULL; - int inoutmask; - int outmask; - unsigned int numretvals; - - assert(dict); /* Cannot be NULL for PyCFuncPtrObject instances */ - restype = self->restype ? self->restype : dict->restype; - converters = self->converters ? self->converters : dict->converters; - checker = self->checker ? self->checker : dict->checker; - argtypes = self->argtypes ? self->argtypes : dict->argtypes; + int inoutmask; + int outmask; + unsigned int numretvals; + + assert(dict); /* Cannot be NULL for PyCFuncPtrObject instances */ + restype = self->restype ? self->restype : dict->restype; + converters = self->converters ? self->converters : dict->converters; + checker = self->checker ? self->checker : dict->checker; + argtypes = self->argtypes ? self->argtypes : dict->argtypes; /* later, we probably want to have an errcheck field in stgdict */ - errcheck = self->errcheck /* ? self->errcheck : dict->errcheck */; + errcheck = self->errcheck /* ? self->errcheck : dict->errcheck */; - pProc = *(void **)self->b_ptr; + pProc = *(void **)self->b_ptr; #ifdef MS_WIN32 - if (self->index) { - /* It's a COM method */ - CDataObject *this; - this = (CDataObject *)PyTuple_GetItem(inargs, 0); /* borrowed ref! */ - if (!this) { - PyErr_SetString(PyExc_ValueError, - "native com method call without 'this' parameter"); - return NULL; - } - if (!CDataObject_Check(this)) { - PyErr_SetString(PyExc_TypeError, - "Expected a COM this pointer as first argument"); - return NULL; - } - /* there should be more checks? No, in Python */ - /* First arg is an pointer to an interface instance */ - if (!this->b_ptr || *(void **)this->b_ptr == NULL) { - PyErr_SetString(PyExc_ValueError, - "NULL COM pointer access"); - return NULL; - } - piunk = *(IUnknown **)this->b_ptr; - if (NULL == piunk->lpVtbl) { - PyErr_SetString(PyExc_ValueError, - "COM method call without VTable"); - return NULL; - } - pProc = ((void **)piunk->lpVtbl)[self->index - 0x1000]; - } + if (self->index) { + /* It's a COM method */ + CDataObject *this; + this = (CDataObject *)PyTuple_GetItem(inargs, 0); /* borrowed ref! */ + if (!this) { + PyErr_SetString(PyExc_ValueError, + "native com method call without 'this' parameter"); + return NULL; + } + if (!CDataObject_Check(this)) { + PyErr_SetString(PyExc_TypeError, + "Expected a COM this pointer as first argument"); + return NULL; + } + /* there should be more checks? No, in Python */ + /* First arg is an pointer to an interface instance */ + if (!this->b_ptr || *(void **)this->b_ptr == NULL) { + PyErr_SetString(PyExc_ValueError, + "NULL COM pointer access"); + return NULL; + } + piunk = *(IUnknown **)this->b_ptr; + if (NULL == piunk->lpVtbl) { + PyErr_SetString(PyExc_ValueError, + "COM method call without VTable"); + return NULL; + } + pProc = ((void **)piunk->lpVtbl)[self->index - 0x1000]; + } #endif - callargs = _build_callargs(self, argtypes, - inargs, kwds, - &outmask, &inoutmask, &numretvals); - if (callargs == NULL) - return NULL; - - if (converters) { - int required = Py_SAFE_DOWNCAST(PyTuple_GET_SIZE(converters), - Py_ssize_t, int); - int actual = Py_SAFE_DOWNCAST(PyTuple_GET_SIZE(callargs), - Py_ssize_t, int); - - if ((dict->flags & FUNCFLAG_CDECL) == FUNCFLAG_CDECL) { - /* For cdecl functions, we allow more actual arguments - than the length of the argtypes tuple. - */ - if (required > actual) { - Py_DECREF(callargs); - PyErr_Format(PyExc_TypeError, - "this function takes at least %d argument%s (%d given)", - required, - required == 1 ? "" : "s", - actual); - return NULL; - } - } else if (required != actual) { - Py_DECREF(callargs); - PyErr_Format(PyExc_TypeError, - "this function takes %d argument%s (%d given)", - required, - required == 1 ? "" : "s", - actual); - return NULL; - } - } + callargs = _build_callargs(self, argtypes, + inargs, kwds, + &outmask, &inoutmask, &numretvals); + if (callargs == NULL) + return NULL; + + if (converters) { + int required = Py_SAFE_DOWNCAST(PyTuple_GET_SIZE(converters), + Py_ssize_t, int); + int actual = Py_SAFE_DOWNCAST(PyTuple_GET_SIZE(callargs), + Py_ssize_t, int); + + if ((dict->flags & FUNCFLAG_CDECL) == FUNCFLAG_CDECL) { + /* For cdecl functions, we allow more actual arguments + than the length of the argtypes tuple. + */ + if (required > actual) { + Py_DECREF(callargs); + PyErr_Format(PyExc_TypeError, + "this function takes at least %d argument%s (%d given)", + required, + required == 1 ? "" : "s", + actual); + return NULL; + } + } else if (required != actual) { + Py_DECREF(callargs); + PyErr_Format(PyExc_TypeError, + "this function takes %d argument%s (%d given)", + required, + required == 1 ? "" : "s", + actual); + return NULL; + } + } - result = _ctypes_callproc(pProc, - callargs, + result = _ctypes_callproc(pProc, + callargs, #ifdef MS_WIN32 - piunk, - self->iid, + piunk, + self->iid, #endif - dict->flags, - converters, - restype, - checker); + dict->flags, + converters, + restype, + checker); /* The 'errcheck' protocol */ - if (result != NULL && errcheck) { - PyObject *v = PyObject_CallFunctionObjArgs(errcheck, - result, - self, - callargs, - NULL); - /* If the errcheck funtion failed, return NULL. - If the errcheck function returned callargs unchanged, - continue normal processing. - If the errcheck function returned something else, - use that as result. - */ - if (v == NULL || v != callargs) { - Py_DECREF(result); - Py_DECREF(callargs); - return v; - } - Py_DECREF(v); - } + if (result != NULL && errcheck) { + PyObject *v = PyObject_CallFunctionObjArgs(errcheck, + result, + self, + callargs, + NULL); + /* If the errcheck funtion failed, return NULL. + If the errcheck function returned callargs unchanged, + continue normal processing. + If the errcheck function returned something else, + use that as result. + */ + if (v == NULL || v != callargs) { + Py_DECREF(result); + Py_DECREF(callargs); + return v; + } + Py_DECREF(v); + } - return _build_result(result, callargs, - outmask, inoutmask, numretvals); + return _build_result(result, callargs, + outmask, inoutmask, numretvals); } static int PyCFuncPtr_traverse(PyCFuncPtrObject *self, visitproc visit, void *arg) { - Py_VISIT(self->callable); - Py_VISIT(self->restype); - Py_VISIT(self->checker); - Py_VISIT(self->errcheck); - Py_VISIT(self->argtypes); - Py_VISIT(self->converters); - Py_VISIT(self->paramflags); - Py_VISIT(self->thunk); - return PyCData_traverse((CDataObject *)self, visit, arg); + Py_VISIT(self->callable); + Py_VISIT(self->restype); + Py_VISIT(self->checker); + Py_VISIT(self->errcheck); + Py_VISIT(self->argtypes); + Py_VISIT(self->converters); + Py_VISIT(self->paramflags); + Py_VISIT(self->thunk); + return PyCData_traverse((CDataObject *)self, visit, arg); } static int PyCFuncPtr_clear(PyCFuncPtrObject *self) { - Py_CLEAR(self->callable); - Py_CLEAR(self->restype); - Py_CLEAR(self->checker); - Py_CLEAR(self->errcheck); - Py_CLEAR(self->argtypes); - Py_CLEAR(self->converters); - Py_CLEAR(self->paramflags); - Py_CLEAR(self->thunk); - return PyCData_clear((CDataObject *)self); + Py_CLEAR(self->callable); + Py_CLEAR(self->restype); + Py_CLEAR(self->checker); + Py_CLEAR(self->errcheck); + Py_CLEAR(self->argtypes); + Py_CLEAR(self->converters); + Py_CLEAR(self->paramflags); + Py_CLEAR(self->thunk); + return PyCData_clear((CDataObject *)self); } static void PyCFuncPtr_dealloc(PyCFuncPtrObject *self) { - PyCFuncPtr_clear(self); - Py_TYPE(self)->tp_free((PyObject *)self); + PyCFuncPtr_clear(self); + Py_TYPE(self)->tp_free((PyObject *)self); } static PyObject * PyCFuncPtr_repr(PyCFuncPtrObject *self) { #ifdef MS_WIN32 - if (self->index) - return PyUnicode_FromFormat("", - self->index - 0x1000, - Py_TYPE(self)->tp_name, - self); + if (self->index) + return PyUnicode_FromFormat("", + self->index - 0x1000, + Py_TYPE(self)->tp_name, + self); #endif - return PyUnicode_FromFormat("<%s object at %p>", - Py_TYPE(self)->tp_name, - self); + return PyUnicode_FromFormat("<%s object at %p>", + Py_TYPE(self)->tp_name, + self); } static int PyCFuncPtr_bool(PyCFuncPtrObject *self) { - return ((*(void **)self->b_ptr != NULL) + return ((*(void **)self->b_ptr != NULL) #ifdef MS_WIN32 - || (self->index != 0) + || (self->index != 0) #endif - ); + ); } static PyNumberMethods PyCFuncPtr_as_number = { - 0, /* nb_add */ - 0, /* nb_subtract */ - 0, /* nb_multiply */ - 0, /* nb_remainder */ - 0, /* nb_divmod */ - 0, /* nb_power */ - 0, /* nb_negative */ - 0, /* nb_positive */ - 0, /* nb_absolute */ - (inquiry)PyCFuncPtr_bool, /* nb_bool */ + 0, /* nb_add */ + 0, /* nb_subtract */ + 0, /* nb_multiply */ + 0, /* nb_remainder */ + 0, /* nb_divmod */ + 0, /* nb_power */ + 0, /* nb_negative */ + 0, /* nb_positive */ + 0, /* nb_absolute */ + (inquiry)PyCFuncPtr_bool, /* nb_bool */ }; PyTypeObject PyCFuncPtr_Type = { - PyVarObject_HEAD_INIT(NULL, 0) - "_ctypes.PyCFuncPtr", - sizeof(PyCFuncPtrObject), /* tp_basicsize */ - 0, /* tp_itemsize */ - (destructor)PyCFuncPtr_dealloc, /* tp_dealloc */ - 0, /* tp_print */ - 0, /* tp_getattr */ - 0, /* tp_setattr */ - 0, /* tp_reserved */ - (reprfunc)PyCFuncPtr_repr, /* tp_repr */ - &PyCFuncPtr_as_number, /* tp_as_number */ - 0, /* tp_as_sequence */ - 0, /* tp_as_mapping */ - 0, /* tp_hash */ - (ternaryfunc)PyCFuncPtr_call, /* tp_call */ - 0, /* tp_str */ - 0, /* tp_getattro */ - 0, /* tp_setattro */ - &PyCData_as_buffer, /* tp_as_buffer */ - Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */ - "Function Pointer", /* tp_doc */ - (traverseproc)PyCFuncPtr_traverse, /* tp_traverse */ - (inquiry)PyCFuncPtr_clear, /* tp_clear */ - 0, /* tp_richcompare */ - 0, /* tp_weaklistoffset */ - 0, /* tp_iter */ - 0, /* tp_iternext */ - 0, /* tp_methods */ - 0, /* tp_members */ - PyCFuncPtr_getsets, /* tp_getset */ - 0, /* tp_base */ - 0, /* tp_dict */ - 0, /* tp_descr_get */ - 0, /* tp_descr_set */ - 0, /* tp_dictoffset */ - 0, /* tp_init */ - 0, /* tp_alloc */ - PyCFuncPtr_new, /* tp_new */ - 0, /* tp_free */ + PyVarObject_HEAD_INIT(NULL, 0) + "_ctypes.PyCFuncPtr", + sizeof(PyCFuncPtrObject), /* tp_basicsize */ + 0, /* tp_itemsize */ + (destructor)PyCFuncPtr_dealloc, /* tp_dealloc */ + 0, /* tp_print */ + 0, /* tp_getattr */ + 0, /* tp_setattr */ + 0, /* tp_reserved */ + (reprfunc)PyCFuncPtr_repr, /* tp_repr */ + &PyCFuncPtr_as_number, /* tp_as_number */ + 0, /* tp_as_sequence */ + 0, /* tp_as_mapping */ + 0, /* tp_hash */ + (ternaryfunc)PyCFuncPtr_call, /* tp_call */ + 0, /* tp_str */ + 0, /* tp_getattro */ + 0, /* tp_setattro */ + &PyCData_as_buffer, /* tp_as_buffer */ + Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */ + "Function Pointer", /* tp_doc */ + (traverseproc)PyCFuncPtr_traverse, /* tp_traverse */ + (inquiry)PyCFuncPtr_clear, /* tp_clear */ + 0, /* tp_richcompare */ + 0, /* tp_weaklistoffset */ + 0, /* tp_iter */ + 0, /* tp_iternext */ + 0, /* tp_methods */ + 0, /* tp_members */ + PyCFuncPtr_getsets, /* tp_getset */ + 0, /* tp_base */ + 0, /* tp_dict */ + 0, /* tp_descr_get */ + 0, /* tp_descr_set */ + 0, /* tp_dictoffset */ + 0, /* tp_init */ + 0, /* tp_alloc */ + PyCFuncPtr_new, /* tp_new */ + 0, /* tp_free */ }; - + /*****************************************************************/ /* Struct_Type @@ -3941,61 +3941,61 @@ */ static int _init_pos_args(PyObject *self, PyTypeObject *type, - PyObject *args, PyObject *kwds, - int index) + PyObject *args, PyObject *kwds, + int index) { - StgDictObject *dict; - PyObject *fields; - int i; - - if (PyType_stgdict((PyObject *)type->tp_base)) { - index = _init_pos_args(self, type->tp_base, - args, kwds, - index); - if (index == -1) - return -1; - } - - dict = PyType_stgdict((PyObject *)type); - fields = PyDict_GetItemString((PyObject *)dict, "_fields_"); - if (fields == NULL) - return index; - - for (i = 0; - i < dict->length && (i+index) < PyTuple_GET_SIZE(args); - ++i) { - PyObject *pair = PySequence_GetItem(fields, i); - PyObject *name, *val; - int res; - if (!pair) - return -1; - name = PySequence_GetItem(pair, 0); - if (!name) { - Py_DECREF(pair); - return -1; - } - val = PyTuple_GET_ITEM(args, i + index); - if (kwds && PyDict_GetItem(kwds, name)) { - char *field = PyBytes_AsString(name); - if (field == NULL) { - PyErr_Clear(); - field = "???"; - } - PyErr_Format(PyExc_TypeError, - "duplicate values for field '%s'", - field); - Py_DECREF(pair); - Py_DECREF(name); - return -1; - } - - res = PyObject_SetAttr(self, name, val); - Py_DECREF(pair); - Py_DECREF(name); - if (res == -1) - return -1; - } - return index + dict->length; + StgDictObject *dict; + PyObject *fields; + int i; + + if (PyType_stgdict((PyObject *)type->tp_base)) { + index = _init_pos_args(self, type->tp_base, + args, kwds, + index); + if (index == -1) + return -1; + } + + dict = PyType_stgdict((PyObject *)type); + fields = PyDict_GetItemString((PyObject *)dict, "_fields_"); + if (fields == NULL) + return index; + + for (i = 0; + i < dict->length && (i+index) < PyTuple_GET_SIZE(args); + ++i) { + PyObject *pair = PySequence_GetItem(fields, i); + PyObject *name, *val; + int res; + if (!pair) + return -1; + name = PySequence_GetItem(pair, 0); + if (!name) { + Py_DECREF(pair); + return -1; + } + val = PyTuple_GET_ITEM(args, i + index); + if (kwds && PyDict_GetItem(kwds, name)) { + char *field = PyBytes_AsString(name); + if (field == NULL) { + PyErr_Clear(); + field = "???"; + } + PyErr_Format(PyExc_TypeError, + "duplicate values for field '%s'", + field); + Py_DECREF(pair); + Py_DECREF(name); + return -1; + } + + res = PyObject_SetAttr(self, name, val); + Py_DECREF(pair); + Py_DECREF(name); + if (res == -1) + return -1; + } + return index + dict->length; } static int @@ -4004,119 +4004,119 @@ /* Optimization possible: Store the attribute names _fields_[x][0] * in C accessible fields somewhere ? */ - if (!PyTuple_Check(args)) { - PyErr_SetString(PyExc_TypeError, - "args not a tuple?"); - return -1; - } - if (PyTuple_GET_SIZE(args)) { - int res = _init_pos_args(self, Py_TYPE(self), - args, kwds, 0); - if (res == -1) - return -1; - if (res < PyTuple_GET_SIZE(args)) { - PyErr_SetString(PyExc_TypeError, - "too many initializers"); - return -1; - } - } - - if (kwds) { - PyObject *key, *value; - Py_ssize_t pos = 0; - while(PyDict_Next(kwds, &pos, &key, &value)) { - if (-1 == PyObject_SetAttr(self, key, value)) - return -1; - } - } - return 0; + if (!PyTuple_Check(args)) { + PyErr_SetString(PyExc_TypeError, + "args not a tuple?"); + return -1; + } + if (PyTuple_GET_SIZE(args)) { + int res = _init_pos_args(self, Py_TYPE(self), + args, kwds, 0); + if (res == -1) + return -1; + if (res < PyTuple_GET_SIZE(args)) { + PyErr_SetString(PyExc_TypeError, + "too many initializers"); + return -1; + } + } + + if (kwds) { + PyObject *key, *value; + Py_ssize_t pos = 0; + while(PyDict_Next(kwds, &pos, &key, &value)) { + if (-1 == PyObject_SetAttr(self, key, value)) + return -1; + } + } + return 0; } static PyTypeObject Struct_Type = { - PyVarObject_HEAD_INIT(NULL, 0) - "_ctypes.Structure", - sizeof(CDataObject), /* tp_basicsize */ - 0, /* tp_itemsize */ - 0, /* tp_dealloc */ - 0, /* tp_print */ - 0, /* tp_getattr */ - 0, /* tp_setattr */ - 0, /* tp_reserved */ - 0, /* tp_repr */ - 0, /* tp_as_number */ - 0, /* tp_as_sequence */ - 0, /* tp_as_mapping */ - 0, /* tp_hash */ - 0, /* tp_call */ - 0, /* tp_str */ - 0, /* tp_getattro */ - 0, /* tp_setattro */ - &PyCData_as_buffer, /* tp_as_buffer */ - Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */ - "Structure base class", /* tp_doc */ - (traverseproc)PyCData_traverse, /* tp_traverse */ - (inquiry)PyCData_clear, /* tp_clear */ - 0, /* tp_richcompare */ - 0, /* tp_weaklistoffset */ - 0, /* tp_iter */ - 0, /* tp_iternext */ - 0, /* tp_methods */ - 0, /* tp_members */ - 0, /* tp_getset */ - 0, /* tp_base */ - 0, /* tp_dict */ - 0, /* tp_descr_get */ - 0, /* tp_descr_set */ - 0, /* tp_dictoffset */ - Struct_init, /* tp_init */ - 0, /* tp_alloc */ - GenericPyCData_new, /* tp_new */ - 0, /* tp_free */ + PyVarObject_HEAD_INIT(NULL, 0) + "_ctypes.Structure", + sizeof(CDataObject), /* tp_basicsize */ + 0, /* tp_itemsize */ + 0, /* tp_dealloc */ + 0, /* tp_print */ + 0, /* tp_getattr */ + 0, /* tp_setattr */ + 0, /* tp_reserved */ + 0, /* tp_repr */ + 0, /* tp_as_number */ + 0, /* tp_as_sequence */ + 0, /* tp_as_mapping */ + 0, /* tp_hash */ + 0, /* tp_call */ + 0, /* tp_str */ + 0, /* tp_getattro */ + 0, /* tp_setattro */ + &PyCData_as_buffer, /* tp_as_buffer */ + Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */ + "Structure base class", /* tp_doc */ + (traverseproc)PyCData_traverse, /* tp_traverse */ + (inquiry)PyCData_clear, /* tp_clear */ + 0, /* tp_richcompare */ + 0, /* tp_weaklistoffset */ + 0, /* tp_iter */ + 0, /* tp_iternext */ + 0, /* tp_methods */ + 0, /* tp_members */ + 0, /* tp_getset */ + 0, /* tp_base */ + 0, /* tp_dict */ + 0, /* tp_descr_get */ + 0, /* tp_descr_set */ + 0, /* tp_dictoffset */ + Struct_init, /* tp_init */ + 0, /* tp_alloc */ + GenericPyCData_new, /* tp_new */ + 0, /* tp_free */ }; static PyTypeObject Union_Type = { - PyVarObject_HEAD_INIT(NULL, 0) - "_ctypes.Union", - sizeof(CDataObject), /* tp_basicsize */ - 0, /* tp_itemsize */ - 0, /* tp_dealloc */ - 0, /* tp_print */ - 0, /* tp_getattr */ - 0, /* tp_setattr */ - 0, /* tp_reserved */ - 0, /* tp_repr */ - 0, /* tp_as_number */ - 0, /* tp_as_sequence */ - 0, /* tp_as_mapping */ - 0, /* tp_hash */ - 0, /* tp_call */ - 0, /* tp_str */ - 0, /* tp_getattro */ - 0, /* tp_setattro */ - &PyCData_as_buffer, /* tp_as_buffer */ - Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */ - "Union base class", /* tp_doc */ - (traverseproc)PyCData_traverse, /* tp_traverse */ - (inquiry)PyCData_clear, /* tp_clear */ - 0, /* tp_richcompare */ - 0, /* tp_weaklistoffset */ - 0, /* tp_iter */ - 0, /* tp_iternext */ - 0, /* tp_methods */ - 0, /* tp_members */ - 0, /* tp_getset */ - 0, /* tp_base */ - 0, /* tp_dict */ - 0, /* tp_descr_get */ - 0, /* tp_descr_set */ - 0, /* tp_dictoffset */ - Struct_init, /* tp_init */ - 0, /* tp_alloc */ - GenericPyCData_new, /* tp_new */ - 0, /* tp_free */ + PyVarObject_HEAD_INIT(NULL, 0) + "_ctypes.Union", + sizeof(CDataObject), /* tp_basicsize */ + 0, /* tp_itemsize */ + 0, /* tp_dealloc */ + 0, /* tp_print */ + 0, /* tp_getattr */ + 0, /* tp_setattr */ + 0, /* tp_reserved */ + 0, /* tp_repr */ + 0, /* tp_as_number */ + 0, /* tp_as_sequence */ + 0, /* tp_as_mapping */ + 0, /* tp_hash */ + 0, /* tp_call */ + 0, /* tp_str */ + 0, /* tp_getattro */ + 0, /* tp_setattro */ + &PyCData_as_buffer, /* tp_as_buffer */ + Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */ + "Union base class", /* tp_doc */ + (traverseproc)PyCData_traverse, /* tp_traverse */ + (inquiry)PyCData_clear, /* tp_clear */ + 0, /* tp_richcompare */ + 0, /* tp_weaklistoffset */ + 0, /* tp_iter */ + 0, /* tp_iternext */ + 0, /* tp_methods */ + 0, /* tp_members */ + 0, /* tp_getset */ + 0, /* tp_base */ + 0, /* tp_dict */ + 0, /* tp_descr_get */ + 0, /* tp_descr_set */ + 0, /* tp_dictoffset */ + Struct_init, /* tp_init */ + 0, /* tp_alloc */ + GenericPyCData_new, /* tp_new */ + 0, /* tp_free */ }; - + /******************************************************************/ /* PyCArray_Type @@ -4124,371 +4124,371 @@ static int Array_init(CDataObject *self, PyObject *args, PyObject *kw) { - Py_ssize_t i; - Py_ssize_t n; + Py_ssize_t i; + Py_ssize_t n; - if (!PyTuple_Check(args)) { - PyErr_SetString(PyExc_TypeError, - "args not a tuple?"); - return -1; - } - n = PyTuple_GET_SIZE(args); - for (i = 0; i < n; ++i) { - PyObject *v; - v = PyTuple_GET_ITEM(args, i); - if (-1 == PySequence_SetItem((PyObject *)self, i, v)) - return -1; - } - return 0; + if (!PyTuple_Check(args)) { + PyErr_SetString(PyExc_TypeError, + "args not a tuple?"); + return -1; + } + n = PyTuple_GET_SIZE(args); + for (i = 0; i < n; ++i) { + PyObject *v; + v = PyTuple_GET_ITEM(args, i); + if (-1 == PySequence_SetItem((PyObject *)self, i, v)) + return -1; + } + return 0; } static PyObject * Array_item(PyObject *_self, Py_ssize_t index) { - CDataObject *self = (CDataObject *)_self; - Py_ssize_t offset, size; - StgDictObject *stgdict; - - - if (index < 0 || index >= self->b_length) { - PyErr_SetString(PyExc_IndexError, - "invalid index"); - return NULL; - } - - stgdict = PyObject_stgdict((PyObject *)self); - assert(stgdict); /* Cannot be NULL for array instances */ - /* Would it be clearer if we got the item size from - stgdict->proto's stgdict? - */ - size = stgdict->size / stgdict->length; - offset = index * size; + CDataObject *self = (CDataObject *)_self; + Py_ssize_t offset, size; + StgDictObject *stgdict; + + + if (index < 0 || index >= self->b_length) { + PyErr_SetString(PyExc_IndexError, + "invalid index"); + return NULL; + } + + stgdict = PyObject_stgdict((PyObject *)self); + assert(stgdict); /* Cannot be NULL for array instances */ + /* Would it be clearer if we got the item size from + stgdict->proto's stgdict? + */ + size = stgdict->size / stgdict->length; + offset = index * size; - return PyCData_get(stgdict->proto, stgdict->getfunc, (PyObject *)self, - index, size, self->b_ptr + offset); + return PyCData_get(stgdict->proto, stgdict->getfunc, (PyObject *)self, + index, size, self->b_ptr + offset); } static PyObject * Array_subscript(PyObject *_self, PyObject *item) { - CDataObject *self = (CDataObject *)_self; + CDataObject *self = (CDataObject *)_self; - 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 += self->b_length; - return Array_item(_self, i); - } - else if PySlice_Check(item) { - StgDictObject *stgdict, *itemdict; - PyObject *proto; - PyObject *np; - Py_ssize_t start, stop, step, slicelen, cur, i; - - if (PySlice_GetIndicesEx((PySliceObject *)item, - self->b_length, &start, &stop, - &step, &slicelen) < 0) { - return NULL; - } - - stgdict = PyObject_stgdict((PyObject *)self); - assert(stgdict); /* Cannot be NULL for array object instances */ - proto = stgdict->proto; - itemdict = PyType_stgdict(proto); - assert(itemdict); /* proto is the item type of the array, a - ctypes type, so this cannot be NULL */ - - if (itemdict->getfunc == _ctypes_get_fielddesc("c")->getfunc) { - char *ptr = (char *)self->b_ptr; - char *dest; - - if (slicelen <= 0) - return PyBytes_FromStringAndSize("", 0); - if (step == 1) { - return PyBytes_FromStringAndSize(ptr + start, - slicelen); - } - dest = (char *)PyMem_Malloc(slicelen); - - if (dest == NULL) - return PyErr_NoMemory(); - - for (cur = start, i = 0; i < slicelen; - cur += step, i++) { - dest[i] = ptr[cur]; - } - - np = PyBytes_FromStringAndSize(dest, slicelen); - PyMem_Free(dest); - return np; - } + 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 += self->b_length; + return Array_item(_self, i); + } + else if PySlice_Check(item) { + StgDictObject *stgdict, *itemdict; + PyObject *proto; + PyObject *np; + Py_ssize_t start, stop, step, slicelen, cur, i; + + if (PySlice_GetIndicesEx((PySliceObject *)item, + self->b_length, &start, &stop, + &step, &slicelen) < 0) { + return NULL; + } + + stgdict = PyObject_stgdict((PyObject *)self); + assert(stgdict); /* Cannot be NULL for array object instances */ + proto = stgdict->proto; + itemdict = PyType_stgdict(proto); + assert(itemdict); /* proto is the item type of the array, a + ctypes type, so this cannot be NULL */ + + if (itemdict->getfunc == _ctypes_get_fielddesc("c")->getfunc) { + char *ptr = (char *)self->b_ptr; + char *dest; + + if (slicelen <= 0) + return PyBytes_FromStringAndSize("", 0); + if (step == 1) { + return PyBytes_FromStringAndSize(ptr + start, + slicelen); + } + dest = (char *)PyMem_Malloc(slicelen); + + if (dest == NULL) + return PyErr_NoMemory(); + + for (cur = start, i = 0; i < slicelen; + cur += step, i++) { + dest[i] = ptr[cur]; + } + + np = PyBytes_FromStringAndSize(dest, slicelen); + PyMem_Free(dest); + return np; + } #ifdef CTYPES_UNICODE - if (itemdict->getfunc == _ctypes_get_fielddesc("u")->getfunc) { - wchar_t *ptr = (wchar_t *)self->b_ptr; - wchar_t *dest; - - if (slicelen <= 0) - return PyUnicode_FromUnicode(NULL, 0); - if (step == 1) { - return PyUnicode_FromWideChar(ptr + start, - slicelen); - } - - dest = (wchar_t *)PyMem_Malloc( - slicelen * sizeof(wchar_t)); - - for (cur = start, i = 0; i < slicelen; - cur += step, i++) { - dest[i] = ptr[cur]; - } - - np = PyUnicode_FromWideChar(dest, slicelen); - PyMem_Free(dest); - return np; - } + if (itemdict->getfunc == _ctypes_get_fielddesc("u")->getfunc) { + wchar_t *ptr = (wchar_t *)self->b_ptr; + wchar_t *dest; + + if (slicelen <= 0) + return PyUnicode_FromUnicode(NULL, 0); + if (step == 1) { + return PyUnicode_FromWideChar(ptr + start, + slicelen); + } + + dest = (wchar_t *)PyMem_Malloc( + slicelen * sizeof(wchar_t)); + + for (cur = start, i = 0; i < slicelen; + cur += step, i++) { + dest[i] = ptr[cur]; + } + + np = PyUnicode_FromWideChar(dest, slicelen); + PyMem_Free(dest); + return np; + } #endif - np = PyList_New(slicelen); - if (np == NULL) - return NULL; - - for (cur = start, i = 0; i < slicelen; - cur += step, i++) { - PyObject *v = Array_item(_self, cur); - PyList_SET_ITEM(np, i, v); - } - return np; - } - else { - PyErr_SetString(PyExc_TypeError, - "indices must be integers"); - return NULL; - } + np = PyList_New(slicelen); + if (np == NULL) + return NULL; + + for (cur = start, i = 0; i < slicelen; + cur += step, i++) { + PyObject *v = Array_item(_self, cur); + PyList_SET_ITEM(np, i, v); + } + return np; + } + else { + PyErr_SetString(PyExc_TypeError, + "indices must be integers"); + return NULL; + } } static int Array_ass_item(PyObject *_self, Py_ssize_t index, PyObject *value) { - CDataObject *self = (CDataObject *)_self; - Py_ssize_t size, offset; - StgDictObject *stgdict; - char *ptr; - - if (value == NULL) { - PyErr_SetString(PyExc_TypeError, - "Array does not support item deletion"); - return -1; - } - - stgdict = PyObject_stgdict((PyObject *)self); - assert(stgdict); /* Cannot be NULL for array object instances */ - if (index < 0 || index >= stgdict->length) { - PyErr_SetString(PyExc_IndexError, - "invalid index"); - return -1; - } - size = stgdict->size / stgdict->length; - offset = index * size; - ptr = self->b_ptr + offset; + CDataObject *self = (CDataObject *)_self; + Py_ssize_t size, offset; + StgDictObject *stgdict; + char *ptr; + + if (value == NULL) { + PyErr_SetString(PyExc_TypeError, + "Array does not support item deletion"); + return -1; + } + + stgdict = PyObject_stgdict((PyObject *)self); + assert(stgdict); /* Cannot be NULL for array object instances */ + if (index < 0 || index >= stgdict->length) { + PyErr_SetString(PyExc_IndexError, + "invalid index"); + return -1; + } + size = stgdict->size / stgdict->length; + offset = index * size; + ptr = self->b_ptr + offset; - return PyCData_set((PyObject *)self, stgdict->proto, stgdict->setfunc, value, - index, size, ptr); + return PyCData_set((PyObject *)self, stgdict->proto, stgdict->setfunc, value, + index, size, ptr); } static int Array_ass_subscript(PyObject *_self, PyObject *item, PyObject *value) { - CDataObject *self = (CDataObject *)_self; - - if (value == NULL) { - PyErr_SetString(PyExc_TypeError, - "Array does not support item deletion"); - return -1; - } - - if (PyIndex_Check(item)) { - Py_ssize_t i = PyNumber_AsSsize_t(item, PyExc_IndexError); - - if (i == -1 && PyErr_Occurred()) - return -1; - if (i < 0) - i += self->b_length; - return Array_ass_item(_self, i, value); - } - else if (PySlice_Check(item)) { - Py_ssize_t start, stop, step, slicelen, otherlen, i, cur; - - if (PySlice_GetIndicesEx((PySliceObject *)item, - self->b_length, &start, &stop, - &step, &slicelen) < 0) { - return -1; - } - if ((step < 0 && start < stop) || - (step > 0 && start > stop)) - stop = start; - - otherlen = PySequence_Length(value); - if (otherlen != slicelen) { - PyErr_SetString(PyExc_ValueError, - "Can only assign sequence of same size"); - return -1; - } - for (cur = start, i = 0; i < otherlen; cur += step, i++) { - PyObject *item = PySequence_GetItem(value, i); - int result; - if (item == NULL) - return -1; - result = Array_ass_item(_self, cur, item); - Py_DECREF(item); - if (result == -1) - return -1; - } - return 0; - } - else { - PyErr_SetString(PyExc_TypeError, - "indices must be integer"); - return -1; - } + CDataObject *self = (CDataObject *)_self; + + if (value == NULL) { + PyErr_SetString(PyExc_TypeError, + "Array does not support item deletion"); + return -1; + } + + if (PyIndex_Check(item)) { + Py_ssize_t i = PyNumber_AsSsize_t(item, PyExc_IndexError); + + if (i == -1 && PyErr_Occurred()) + return -1; + if (i < 0) + i += self->b_length; + return Array_ass_item(_self, i, value); + } + else if (PySlice_Check(item)) { + Py_ssize_t start, stop, step, slicelen, otherlen, i, cur; + + if (PySlice_GetIndicesEx((PySliceObject *)item, + self->b_length, &start, &stop, + &step, &slicelen) < 0) { + return -1; + } + if ((step < 0 && start < stop) || + (step > 0 && start > stop)) + stop = start; + + otherlen = PySequence_Length(value); + if (otherlen != slicelen) { + PyErr_SetString(PyExc_ValueError, + "Can only assign sequence of same size"); + return -1; + } + for (cur = start, i = 0; i < otherlen; cur += step, i++) { + PyObject *item = PySequence_GetItem(value, i); + int result; + if (item == NULL) + return -1; + result = Array_ass_item(_self, cur, item); + Py_DECREF(item); + if (result == -1) + return -1; + } + return 0; + } + else { + PyErr_SetString(PyExc_TypeError, + "indices must be integer"); + return -1; + } } static Py_ssize_t Array_length(PyObject *_self) { - CDataObject *self = (CDataObject *)_self; - return self->b_length; + CDataObject *self = (CDataObject *)_self; + return self->b_length; } static PySequenceMethods Array_as_sequence = { - Array_length, /* sq_length; */ - 0, /* sq_concat; */ - 0, /* sq_repeat; */ - Array_item, /* sq_item; */ - 0, /* sq_slice; */ - Array_ass_item, /* sq_ass_item; */ - 0, /* sq_ass_slice; */ - 0, /* sq_contains; */ - - 0, /* sq_inplace_concat; */ - 0, /* sq_inplace_repeat; */ + Array_length, /* sq_length; */ + 0, /* sq_concat; */ + 0, /* sq_repeat; */ + Array_item, /* sq_item; */ + 0, /* sq_slice; */ + Array_ass_item, /* sq_ass_item; */ + 0, /* sq_ass_slice; */ + 0, /* sq_contains; */ + + 0, /* sq_inplace_concat; */ + 0, /* sq_inplace_repeat; */ }; static PyMappingMethods Array_as_mapping = { - Array_length, - Array_subscript, - Array_ass_subscript, + Array_length, + Array_subscript, + Array_ass_subscript, }; PyTypeObject PyCArray_Type = { - PyVarObject_HEAD_INIT(NULL, 0) - "_ctypes.Array", - sizeof(CDataObject), /* tp_basicsize */ - 0, /* tp_itemsize */ - 0, /* tp_dealloc */ - 0, /* tp_print */ - 0, /* tp_getattr */ - 0, /* tp_setattr */ - 0, /* tp_reserved */ - 0, /* tp_repr */ - 0, /* tp_as_number */ - &Array_as_sequence, /* tp_as_sequence */ - &Array_as_mapping, /* tp_as_mapping */ - 0, /* tp_hash */ - 0, /* tp_call */ - 0, /* tp_str */ - 0, /* tp_getattro */ - 0, /* tp_setattro */ - &PyCData_as_buffer, /* tp_as_buffer */ - Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */ - "XXX to be provided", /* tp_doc */ - (traverseproc)PyCData_traverse, /* tp_traverse */ - (inquiry)PyCData_clear, /* tp_clear */ - 0, /* tp_richcompare */ - 0, /* tp_weaklistoffset */ - 0, /* tp_iter */ - 0, /* tp_iternext */ - 0, /* tp_methods */ - 0, /* tp_members */ - 0, /* tp_getset */ - 0, /* tp_base */ - 0, /* tp_dict */ - 0, /* tp_descr_get */ - 0, /* tp_descr_set */ - 0, /* tp_dictoffset */ - (initproc)Array_init, /* tp_init */ - 0, /* tp_alloc */ - GenericPyCData_new, /* tp_new */ - 0, /* tp_free */ + PyVarObject_HEAD_INIT(NULL, 0) + "_ctypes.Array", + sizeof(CDataObject), /* tp_basicsize */ + 0, /* tp_itemsize */ + 0, /* tp_dealloc */ + 0, /* tp_print */ + 0, /* tp_getattr */ + 0, /* tp_setattr */ + 0, /* tp_reserved */ + 0, /* tp_repr */ + 0, /* tp_as_number */ + &Array_as_sequence, /* tp_as_sequence */ + &Array_as_mapping, /* tp_as_mapping */ + 0, /* tp_hash */ + 0, /* tp_call */ + 0, /* tp_str */ + 0, /* tp_getattro */ + 0, /* tp_setattro */ + &PyCData_as_buffer, /* tp_as_buffer */ + Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */ + "XXX to be provided", /* tp_doc */ + (traverseproc)PyCData_traverse, /* tp_traverse */ + (inquiry)PyCData_clear, /* tp_clear */ + 0, /* tp_richcompare */ + 0, /* tp_weaklistoffset */ + 0, /* tp_iter */ + 0, /* tp_iternext */ + 0, /* tp_methods */ + 0, /* tp_members */ + 0, /* tp_getset */ + 0, /* tp_base */ + 0, /* tp_dict */ + 0, /* tp_descr_get */ + 0, /* tp_descr_set */ + 0, /* tp_dictoffset */ + (initproc)Array_init, /* tp_init */ + 0, /* tp_alloc */ + GenericPyCData_new, /* tp_new */ + 0, /* tp_free */ }; PyObject * PyCArrayType_from_ctype(PyObject *itemtype, Py_ssize_t length) { - static PyObject *cache; - PyObject *key; - PyObject *result; - char name[256]; - PyObject *len; - - if (cache == NULL) { - cache = PyDict_New(); - if (cache == NULL) - return NULL; - } - len = PyLong_FromSsize_t(length); - if (len == NULL) - return NULL; - key = PyTuple_Pack(2, itemtype, len); - Py_DECREF(len); - if (!key) - return NULL; - result = PyDict_GetItemProxy(cache, key); - if (result) { - Py_INCREF(result); - Py_DECREF(key); - return result; - } - - if (!PyType_Check(itemtype)) { - PyErr_SetString(PyExc_TypeError, - "Expected a type object"); - return NULL; - } + static PyObject *cache; + PyObject *key; + PyObject *result; + char name[256]; + PyObject *len; + + if (cache == NULL) { + cache = PyDict_New(); + if (cache == NULL) + return NULL; + } + len = PyLong_FromSsize_t(length); + if (len == NULL) + return NULL; + key = PyTuple_Pack(2, itemtype, len); + Py_DECREF(len); + if (!key) + return NULL; + result = PyDict_GetItemProxy(cache, key); + if (result) { + Py_INCREF(result); + Py_DECREF(key); + return result; + } + + if (!PyType_Check(itemtype)) { + PyErr_SetString(PyExc_TypeError, + "Expected a type object"); + return NULL; + } #ifdef MS_WIN64 - sprintf(name, "%.200s_Array_%Id", - ((PyTypeObject *)itemtype)->tp_name, length); + sprintf(name, "%.200s_Array_%Id", + ((PyTypeObject *)itemtype)->tp_name, length); #else - sprintf(name, "%.200s_Array_%ld", - ((PyTypeObject *)itemtype)->tp_name, (long)length); + sprintf(name, "%.200s_Array_%ld", + ((PyTypeObject *)itemtype)->tp_name, (long)length); #endif - result = PyObject_CallFunction((PyObject *)&PyCArrayType_Type, - "U(O){s:n,s:O}", - name, - &PyCArray_Type, - "_length_", - length, - "_type_", - itemtype - ); - if (result == NULL) { - Py_DECREF(key); - return NULL; - } - if (-1 == PyDict_SetItemProxy(cache, key, result)) { - Py_DECREF(key); - Py_DECREF(result); - return NULL; - } - Py_DECREF(key); - return result; + result = PyObject_CallFunction((PyObject *)&PyCArrayType_Type, + "U(O){s:n,s:O}", + name, + &PyCArray_Type, + "_length_", + length, + "_type_", + itemtype + ); + if (result == NULL) { + Py_DECREF(key); + return NULL; + } + if (-1 == PyDict_SetItemProxy(cache, key, result)) { + Py_DECREF(key); + Py_DECREF(result); + return NULL; + } + Py_DECREF(key); + return result; } - + /******************************************************************/ /* Simple_Type @@ -4497,166 +4497,166 @@ static int Simple_set_value(CDataObject *self, PyObject *value) { - PyObject *result; - StgDictObject *dict = PyObject_stgdict((PyObject *)self); + PyObject *result; + StgDictObject *dict = PyObject_stgdict((PyObject *)self); - if (value == NULL) { - PyErr_SetString(PyExc_TypeError, - "can't delete attribute"); - return -1; - } - assert(dict); /* Cannot be NULL for CDataObject instances */ - assert(dict->setfunc); - result = dict->setfunc(self->b_ptr, value, dict->size); - if (!result) - return -1; + if (value == NULL) { + PyErr_SetString(PyExc_TypeError, + "can't delete attribute"); + return -1; + } + assert(dict); /* Cannot be NULL for CDataObject instances */ + assert(dict->setfunc); + result = dict->setfunc(self->b_ptr, value, dict->size); + if (!result) + return -1; - /* consumes the refcount the setfunc returns */ - return KeepRef(self, 0, result); + /* consumes the refcount the setfunc returns */ + return KeepRef(self, 0, result); } static int Simple_init(CDataObject *self, PyObject *args, PyObject *kw) { - PyObject *value = NULL; - if (!PyArg_UnpackTuple(args, "__init__", 0, 1, &value)) - return -1; - if (value) - return Simple_set_value(self, value); - return 0; + PyObject *value = NULL; + if (!PyArg_UnpackTuple(args, "__init__", 0, 1, &value)) + return -1; + if (value) + return Simple_set_value(self, value); + return 0; } static PyObject * Simple_get_value(CDataObject *self) { - StgDictObject *dict; - dict = PyObject_stgdict((PyObject *)self); - assert(dict); /* Cannot be NULL for CDataObject instances */ - assert(dict->getfunc); - return dict->getfunc(self->b_ptr, self->b_size); + StgDictObject *dict; + dict = PyObject_stgdict((PyObject *)self); + assert(dict); /* Cannot be NULL for CDataObject instances */ + assert(dict->getfunc); + return dict->getfunc(self->b_ptr, self->b_size); } static PyGetSetDef Simple_getsets[] = { - { "value", (getter)Simple_get_value, (setter)Simple_set_value, - "current value", NULL }, - { NULL, NULL } + { "value", (getter)Simple_get_value, (setter)Simple_set_value, + "current value", NULL }, + { NULL, NULL } }; static PyObject * Simple_from_outparm(PyObject *self, PyObject *args) { - if (_ctypes_simple_instance((PyObject *)Py_TYPE(self))) { - Py_INCREF(self); - return self; - } - /* call stgdict->getfunc */ - return Simple_get_value((CDataObject *)self); + if (_ctypes_simple_instance((PyObject *)Py_TYPE(self))) { + Py_INCREF(self); + return self; + } + /* call stgdict->getfunc */ + return Simple_get_value((CDataObject *)self); } static PyMethodDef Simple_methods[] = { - { "__ctypes_from_outparam__", Simple_from_outparm, METH_NOARGS, }, - { NULL, NULL }, + { "__ctypes_from_outparam__", Simple_from_outparm, METH_NOARGS, }, + { NULL, NULL }, }; static int Simple_bool(CDataObject *self) { - return memcmp(self->b_ptr, "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0", self->b_size); + return memcmp(self->b_ptr, "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0", self->b_size); } static PyNumberMethods Simple_as_number = { - 0, /* nb_add */ - 0, /* nb_subtract */ - 0, /* nb_multiply */ - 0, /* nb_remainder */ - 0, /* nb_divmod */ - 0, /* nb_power */ - 0, /* nb_negative */ - 0, /* nb_positive */ - 0, /* nb_absolute */ - (inquiry)Simple_bool, /* nb_bool */ + 0, /* nb_add */ + 0, /* nb_subtract */ + 0, /* nb_multiply */ + 0, /* nb_remainder */ + 0, /* nb_divmod */ + 0, /* nb_power */ + 0, /* nb_negative */ + 0, /* nb_positive */ + 0, /* nb_absolute */ + (inquiry)Simple_bool, /* nb_bool */ }; /* "%s(%s)" % (self.__class__.__name__, self.value) */ static PyObject * Simple_repr(CDataObject *self) { - PyObject *val, *name, *args, *result; - static PyObject *format; + PyObject *val, *name, *args, *result; + static PyObject *format; - if (Py_TYPE(self)->tp_base != &Simple_Type) { - return PyUnicode_FromFormat("<%s object at %p>", - Py_TYPE(self)->tp_name, self); - } - - if (format == NULL) { - format = PyUnicode_InternFromString("%s(%r)"); - if (format == NULL) - return NULL; - } - - val = Simple_get_value(self); - if (val == NULL) - return NULL; - - name = PyUnicode_FromString(Py_TYPE(self)->tp_name); - if (name == NULL) { - Py_DECREF(val); - return NULL; - } - - args = PyTuple_Pack(2, name, val); - Py_DECREF(name); - Py_DECREF(val); - if (args == NULL) - return NULL; - - result = PyUnicode_Format(format, args); - Py_DECREF(args); - return result; + if (Py_TYPE(self)->tp_base != &Simple_Type) { + return PyUnicode_FromFormat("<%s object at %p>", + Py_TYPE(self)->tp_name, self); + } + + if (format == NULL) { + format = PyUnicode_InternFromString("%s(%r)"); + if (format == NULL) + return NULL; + } + + val = Simple_get_value(self); + if (val == NULL) + return NULL; + + name = PyUnicode_FromString(Py_TYPE(self)->tp_name); + if (name == NULL) { + Py_DECREF(val); + return NULL; + } + + args = PyTuple_Pack(2, name, val); + Py_DECREF(name); + Py_DECREF(val); + if (args == NULL) + return NULL; + + result = PyUnicode_Format(format, args); + Py_DECREF(args); + return result; } static PyTypeObject Simple_Type = { - PyVarObject_HEAD_INIT(NULL, 0) - "_ctypes._SimpleCData", - sizeof(CDataObject), /* tp_basicsize */ - 0, /* tp_itemsize */ - 0, /* tp_dealloc */ - 0, /* tp_print */ - 0, /* tp_getattr */ - 0, /* tp_setattr */ - 0, /* tp_reserved */ - (reprfunc)&Simple_repr, /* tp_repr */ - &Simple_as_number, /* tp_as_number */ - 0, /* tp_as_sequence */ - 0, /* tp_as_mapping */ - 0, /* tp_hash */ - 0, /* tp_call */ - 0, /* tp_str */ - 0, /* tp_getattro */ - 0, /* tp_setattro */ - &PyCData_as_buffer, /* tp_as_buffer */ - Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */ - "XXX to be provided", /* tp_doc */ - (traverseproc)PyCData_traverse, /* tp_traverse */ - (inquiry)PyCData_clear, /* tp_clear */ - 0, /* tp_richcompare */ - 0, /* tp_weaklistoffset */ - 0, /* tp_iter */ - 0, /* tp_iternext */ - Simple_methods, /* tp_methods */ - 0, /* tp_members */ - Simple_getsets, /* tp_getset */ - 0, /* tp_base */ - 0, /* tp_dict */ - 0, /* tp_descr_get */ - 0, /* tp_descr_set */ - 0, /* tp_dictoffset */ - (initproc)Simple_init, /* tp_init */ - 0, /* tp_alloc */ - GenericPyCData_new, /* tp_new */ - 0, /* tp_free */ + PyVarObject_HEAD_INIT(NULL, 0) + "_ctypes._SimpleCData", + sizeof(CDataObject), /* tp_basicsize */ + 0, /* tp_itemsize */ + 0, /* tp_dealloc */ + 0, /* tp_print */ + 0, /* tp_getattr */ + 0, /* tp_setattr */ + 0, /* tp_reserved */ + (reprfunc)&Simple_repr, /* tp_repr */ + &Simple_as_number, /* tp_as_number */ + 0, /* tp_as_sequence */ + 0, /* tp_as_mapping */ + 0, /* tp_hash */ + 0, /* tp_call */ + 0, /* tp_str */ + 0, /* tp_getattro */ + 0, /* tp_setattro */ + &PyCData_as_buffer, /* tp_as_buffer */ + Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */ + "XXX to be provided", /* tp_doc */ + (traverseproc)PyCData_traverse, /* tp_traverse */ + (inquiry)PyCData_clear, /* tp_clear */ + 0, /* tp_richcompare */ + 0, /* tp_weaklistoffset */ + 0, /* tp_iter */ + 0, /* tp_iternext */ + Simple_methods, /* tp_methods */ + 0, /* tp_members */ + Simple_getsets, /* tp_getset */ + 0, /* tp_base */ + 0, /* tp_dict */ + 0, /* tp_descr_get */ + 0, /* tp_descr_set */ + 0, /* tp_dictoffset */ + (initproc)Simple_init, /* tp_init */ + 0, /* tp_alloc */ + GenericPyCData_new, /* tp_new */ + 0, /* tp_free */ }; - + /******************************************************************/ /* PyCPointer_Type @@ -4664,377 +4664,377 @@ static PyObject * Pointer_item(PyObject *_self, Py_ssize_t index) { - CDataObject *self = (CDataObject *)_self; - Py_ssize_t size; - Py_ssize_t offset; - StgDictObject *stgdict, *itemdict; - PyObject *proto; - - if (*(void **)self->b_ptr == NULL) { - PyErr_SetString(PyExc_ValueError, - "NULL pointer access"); - return NULL; - } - - stgdict = PyObject_stgdict((PyObject *)self); - assert(stgdict); /* Cannot be NULL for pointer object instances */ - - proto = stgdict->proto; - assert(proto); - itemdict = PyType_stgdict(proto); - assert(itemdict); /* proto is the item type of the pointer, a ctypes - type, so this cannot be NULL */ + CDataObject *self = (CDataObject *)_self; + Py_ssize_t size; + Py_ssize_t offset; + StgDictObject *stgdict, *itemdict; + PyObject *proto; + + if (*(void **)self->b_ptr == NULL) { + PyErr_SetString(PyExc_ValueError, + "NULL pointer access"); + return NULL; + } + + stgdict = PyObject_stgdict((PyObject *)self); + assert(stgdict); /* Cannot be NULL for pointer object instances */ + + proto = stgdict->proto; + assert(proto); + itemdict = PyType_stgdict(proto); + assert(itemdict); /* proto is the item type of the pointer, a ctypes + type, so this cannot be NULL */ - size = itemdict->size; - offset = index * itemdict->size; + size = itemdict->size; + offset = index * itemdict->size; - return PyCData_get(proto, stgdict->getfunc, (PyObject *)self, - index, size, (*(char **)self->b_ptr) + offset); + return PyCData_get(proto, stgdict->getfunc, (PyObject *)self, + index, size, (*(char **)self->b_ptr) + offset); } static int Pointer_ass_item(PyObject *_self, Py_ssize_t index, PyObject *value) { - CDataObject *self = (CDataObject *)_self; - Py_ssize_t size; - Py_ssize_t offset; - StgDictObject *stgdict, *itemdict; - PyObject *proto; - - if (value == NULL) { - PyErr_SetString(PyExc_TypeError, - "Pointer does not support item deletion"); - return -1; - } - - if (*(void **)self->b_ptr == NULL) { - PyErr_SetString(PyExc_ValueError, - "NULL pointer access"); - return -1; - } - - stgdict = PyObject_stgdict((PyObject *)self); - assert(stgdict); /* Cannot be NULL fr pointer instances */ - - proto = stgdict->proto; - assert(proto); - - itemdict = PyType_stgdict(proto); - assert(itemdict); /* Cannot be NULL because the itemtype of a pointer - is always a ctypes type */ + CDataObject *self = (CDataObject *)_self; + Py_ssize_t size; + Py_ssize_t offset; + StgDictObject *stgdict, *itemdict; + PyObject *proto; + + if (value == NULL) { + PyErr_SetString(PyExc_TypeError, + "Pointer does not support item deletion"); + return -1; + } + + if (*(void **)self->b_ptr == NULL) { + PyErr_SetString(PyExc_ValueError, + "NULL pointer access"); + return -1; + } + + stgdict = PyObject_stgdict((PyObject *)self); + assert(stgdict); /* Cannot be NULL fr pointer instances */ + + proto = stgdict->proto; + assert(proto); - size = itemdict->size; - offset = index * itemdict->size; + itemdict = PyType_stgdict(proto); + assert(itemdict); /* Cannot be NULL because the itemtype of a pointer + is always a ctypes type */ - return PyCData_set((PyObject *)self, proto, stgdict->setfunc, value, - index, size, (*(char **)self->b_ptr) + offset); + size = itemdict->size; + offset = index * itemdict->size; + + return PyCData_set((PyObject *)self, proto, stgdict->setfunc, value, + index, size, (*(char **)self->b_ptr) + offset); } static PyObject * Pointer_get_contents(CDataObject *self, void *closure) { - StgDictObject *stgdict; + StgDictObject *stgdict; - if (*(void **)self->b_ptr == NULL) { - PyErr_SetString(PyExc_ValueError, - "NULL pointer access"); - return NULL; - } - - stgdict = PyObject_stgdict((PyObject *)self); - assert(stgdict); /* Cannot be NULL fr pointer instances */ - return PyCData_FromBaseObj(stgdict->proto, - (PyObject *)self, 0, - *(void **)self->b_ptr); + if (*(void **)self->b_ptr == NULL) { + PyErr_SetString(PyExc_ValueError, + "NULL pointer access"); + return NULL; + } + + stgdict = PyObject_stgdict((PyObject *)self); + assert(stgdict); /* Cannot be NULL fr pointer instances */ + return PyCData_FromBaseObj(stgdict->proto, + (PyObject *)self, 0, + *(void **)self->b_ptr); } static int Pointer_set_contents(CDataObject *self, PyObject *value, void *closure) { - StgDictObject *stgdict; - CDataObject *dst; - PyObject *keep; - - if (value == NULL) { - PyErr_SetString(PyExc_TypeError, - "Pointer does not support item deletion"); - return -1; - } - stgdict = PyObject_stgdict((PyObject *)self); - assert(stgdict); /* Cannot be NULL fr pointer instances */ - assert(stgdict->proto); - if (!CDataObject_Check(value) - || 0 == PyObject_IsInstance(value, stgdict->proto)) { - /* XXX PyObject_IsInstance could return -1! */ - PyErr_Format(PyExc_TypeError, - "expected %s instead of %s", - ((PyTypeObject *)(stgdict->proto))->tp_name, - Py_TYPE(value)->tp_name); - return -1; - } - - dst = (CDataObject *)value; - *(void **)self->b_ptr = dst->b_ptr; - - /* - A Pointer instance must keep a the value it points to alive. So, a - pointer instance has b_length set to 2 instead of 1, and we set - 'value' itself as the second item of the b_objects list, additionally. - */ - Py_INCREF(value); - if (-1 == KeepRef(self, 1, value)) - return -1; - - keep = GetKeepedObjects(dst); - Py_INCREF(keep); - return KeepRef(self, 0, keep); + StgDictObject *stgdict; + CDataObject *dst; + PyObject *keep; + + if (value == NULL) { + PyErr_SetString(PyExc_TypeError, + "Pointer does not support item deletion"); + return -1; + } + stgdict = PyObject_stgdict((PyObject *)self); + assert(stgdict); /* Cannot be NULL fr pointer instances */ + assert(stgdict->proto); + if (!CDataObject_Check(value) + || 0 == PyObject_IsInstance(value, stgdict->proto)) { + /* XXX PyObject_IsInstance could return -1! */ + PyErr_Format(PyExc_TypeError, + "expected %s instead of %s", + ((PyTypeObject *)(stgdict->proto))->tp_name, + Py_TYPE(value)->tp_name); + return -1; + } + + dst = (CDataObject *)value; + *(void **)self->b_ptr = dst->b_ptr; + + /* + A Pointer instance must keep a the value it points to alive. So, a + pointer instance has b_length set to 2 instead of 1, and we set + 'value' itself as the second item of the b_objects list, additionally. + */ + Py_INCREF(value); + if (-1 == KeepRef(self, 1, value)) + return -1; + + keep = GetKeepedObjects(dst); + Py_INCREF(keep); + return KeepRef(self, 0, keep); } static PyGetSetDef Pointer_getsets[] = { - { "contents", (getter)Pointer_get_contents, - (setter)Pointer_set_contents, - "the object this pointer points to (read-write)", NULL }, - { NULL, NULL } + { "contents", (getter)Pointer_get_contents, + (setter)Pointer_set_contents, + "the object this pointer points to (read-write)", NULL }, + { NULL, NULL } }; static int Pointer_init(CDataObject *self, PyObject *args, PyObject *kw) { - PyObject *value = NULL; + PyObject *value = NULL; - if (!PyArg_UnpackTuple(args, "POINTER", 0, 1, &value)) - return -1; - if (value == NULL) - return 0; - return Pointer_set_contents(self, value, NULL); + if (!PyArg_UnpackTuple(args, "POINTER", 0, 1, &value)) + return -1; + if (value == NULL) + return 0; + return Pointer_set_contents(self, value, NULL); } static PyObject * Pointer_new(PyTypeObject *type, PyObject *args, PyObject *kw) { - StgDictObject *dict = PyType_stgdict((PyObject *)type); - if (!dict || !dict->proto) { - PyErr_SetString(PyExc_TypeError, - "Cannot create instance: has no _type_"); - return NULL; - } - return GenericPyCData_new(type, args, kw); + StgDictObject *dict = PyType_stgdict((PyObject *)type); + if (!dict || !dict->proto) { + PyErr_SetString(PyExc_TypeError, + "Cannot create instance: has no _type_"); + return NULL; + } + return GenericPyCData_new(type, args, kw); } static PyObject * Pointer_subscript(PyObject *_self, PyObject *item) { - CDataObject *self = (CDataObject *)_self; - if (PyIndex_Check(item)) { - Py_ssize_t i = PyNumber_AsSsize_t(item, PyExc_IndexError); - if (i == -1 && PyErr_Occurred()) - return NULL; - return Pointer_item(_self, i); - } - else if (PySlice_Check(item)) { - PySliceObject *slice = (PySliceObject *)item; - Py_ssize_t start, stop, step; - PyObject *np; - StgDictObject *stgdict, *itemdict; - PyObject *proto; - Py_ssize_t i, len, cur; - - /* Since pointers have no length, and we want to apply - different semantics to negative indices than normal - slicing, we have to dissect the slice object ourselves.*/ - if (slice->step == Py_None) { - step = 1; - } - else { - step = PyNumber_AsSsize_t(slice->step, - PyExc_ValueError); - if (step == -1 && PyErr_Occurred()) - return NULL; - if (step == 0) { - PyErr_SetString(PyExc_ValueError, - "slice step cannot be zero"); - return NULL; - } - } - if (slice->start == Py_None) { - if (step < 0) { - PyErr_SetString(PyExc_ValueError, - "slice start is required " - "for step < 0"); - return NULL; - } - start = 0; - } - else { - start = PyNumber_AsSsize_t(slice->start, - PyExc_ValueError); - if (start == -1 && PyErr_Occurred()) - return NULL; - } - if (slice->stop == Py_None) { - PyErr_SetString(PyExc_ValueError, - "slice stop is required"); - return NULL; - } - stop = PyNumber_AsSsize_t(slice->stop, - PyExc_ValueError); - if (stop == -1 && PyErr_Occurred()) - return NULL; - if ((step > 0 && start > stop) || - (step < 0 && start < stop)) - len = 0; - else if (step > 0) - len = (stop - start - 1) / step + 1; - else - len = (stop - start + 1) / step + 1; - - stgdict = PyObject_stgdict((PyObject *)self); - assert(stgdict); /* Cannot be NULL for pointer instances */ - proto = stgdict->proto; - assert(proto); - itemdict = PyType_stgdict(proto); - assert(itemdict); - if (itemdict->getfunc == _ctypes_get_fielddesc("c")->getfunc) { - char *ptr = *(char **)self->b_ptr; - char *dest; - - if (len <= 0) - return PyBytes_FromStringAndSize("", 0); - if (step == 1) { - return PyBytes_FromStringAndSize(ptr + start, - len); - } - dest = (char *)PyMem_Malloc(len); - if (dest == NULL) - return PyErr_NoMemory(); - for (cur = start, i = 0; i < len; cur += step, i++) { - dest[i] = ptr[cur]; - } - np = PyBytes_FromStringAndSize(dest, len); - PyMem_Free(dest); - return np; - } + CDataObject *self = (CDataObject *)_self; + if (PyIndex_Check(item)) { + Py_ssize_t i = PyNumber_AsSsize_t(item, PyExc_IndexError); + if (i == -1 && PyErr_Occurred()) + return NULL; + return Pointer_item(_self, i); + } + else if (PySlice_Check(item)) { + PySliceObject *slice = (PySliceObject *)item; + Py_ssize_t start, stop, step; + PyObject *np; + StgDictObject *stgdict, *itemdict; + PyObject *proto; + Py_ssize_t i, len, cur; + + /* Since pointers have no length, and we want to apply + different semantics to negative indices than normal + slicing, we have to dissect the slice object ourselves.*/ + if (slice->step == Py_None) { + step = 1; + } + else { + step = PyNumber_AsSsize_t(slice->step, + PyExc_ValueError); + if (step == -1 && PyErr_Occurred()) + return NULL; + if (step == 0) { + PyErr_SetString(PyExc_ValueError, + "slice step cannot be zero"); + return NULL; + } + } + if (slice->start == Py_None) { + if (step < 0) { + PyErr_SetString(PyExc_ValueError, + "slice start is required " + "for step < 0"); + return NULL; + } + start = 0; + } + else { + start = PyNumber_AsSsize_t(slice->start, + PyExc_ValueError); + if (start == -1 && PyErr_Occurred()) + return NULL; + } + if (slice->stop == Py_None) { + PyErr_SetString(PyExc_ValueError, + "slice stop is required"); + return NULL; + } + stop = PyNumber_AsSsize_t(slice->stop, + PyExc_ValueError); + if (stop == -1 && PyErr_Occurred()) + return NULL; + if ((step > 0 && start > stop) || + (step < 0 && start < stop)) + len = 0; + else if (step > 0) + len = (stop - start - 1) / step + 1; + else + len = (stop - start + 1) / step + 1; + + stgdict = PyObject_stgdict((PyObject *)self); + assert(stgdict); /* Cannot be NULL for pointer instances */ + proto = stgdict->proto; + assert(proto); + itemdict = PyType_stgdict(proto); + assert(itemdict); + if (itemdict->getfunc == _ctypes_get_fielddesc("c")->getfunc) { + char *ptr = *(char **)self->b_ptr; + char *dest; + + if (len <= 0) + return PyBytes_FromStringAndSize("", 0); + if (step == 1) { + return PyBytes_FromStringAndSize(ptr + start, + len); + } + dest = (char *)PyMem_Malloc(len); + if (dest == NULL) + return PyErr_NoMemory(); + for (cur = start, i = 0; i < len; cur += step, i++) { + dest[i] = ptr[cur]; + } + np = PyBytes_FromStringAndSize(dest, len); + PyMem_Free(dest); + return np; + } #ifdef CTYPES_UNICODE - if (itemdict->getfunc == _ctypes_get_fielddesc("u")->getfunc) { - wchar_t *ptr = *(wchar_t **)self->b_ptr; - wchar_t *dest; - - if (len <= 0) - return PyUnicode_FromUnicode(NULL, 0); - if (step == 1) { - return PyUnicode_FromWideChar(ptr + start, - len); - } - dest = (wchar_t *)PyMem_Malloc(len * sizeof(wchar_t)); - if (dest == NULL) - return PyErr_NoMemory(); - for (cur = start, i = 0; i < len; cur += step, i++) { - dest[i] = ptr[cur]; - } - np = PyUnicode_FromWideChar(dest, len); - PyMem_Free(dest); - return np; - } + if (itemdict->getfunc == _ctypes_get_fielddesc("u")->getfunc) { + wchar_t *ptr = *(wchar_t **)self->b_ptr; + wchar_t *dest; + + if (len <= 0) + return PyUnicode_FromUnicode(NULL, 0); + if (step == 1) { + return PyUnicode_FromWideChar(ptr + start, + len); + } + dest = (wchar_t *)PyMem_Malloc(len * sizeof(wchar_t)); + if (dest == NULL) + return PyErr_NoMemory(); + for (cur = start, i = 0; i < len; cur += step, i++) { + dest[i] = ptr[cur]; + } + np = PyUnicode_FromWideChar(dest, len); + PyMem_Free(dest); + return np; + } #endif - np = PyList_New(len); - if (np == NULL) - return NULL; - - for (cur = start, i = 0; i < len; cur += step, i++) { - PyObject *v = Pointer_item(_self, cur); - PyList_SET_ITEM(np, i, v); - } - return np; - } - else { - PyErr_SetString(PyExc_TypeError, - "Pointer indices must be integer"); - return NULL; - } + np = PyList_New(len); + if (np == NULL) + return NULL; + + for (cur = start, i = 0; i < len; cur += step, i++) { + PyObject *v = Pointer_item(_self, cur); + PyList_SET_ITEM(np, i, v); + } + return np; + } + else { + PyErr_SetString(PyExc_TypeError, + "Pointer indices must be integer"); + return NULL; + } } static PySequenceMethods Pointer_as_sequence = { - 0, /* inquiry sq_length; */ - 0, /* binaryfunc sq_concat; */ - 0, /* intargfunc sq_repeat; */ - Pointer_item, /* intargfunc sq_item; */ - 0, /* intintargfunc sq_slice; */ - Pointer_ass_item, /* intobjargproc sq_ass_item; */ - 0, /* intintobjargproc sq_ass_slice; */ - 0, /* objobjproc sq_contains; */ - /* Added in release 2.0 */ - 0, /* binaryfunc sq_inplace_concat; */ - 0, /* intargfunc sq_inplace_repeat; */ + 0, /* inquiry sq_length; */ + 0, /* binaryfunc sq_concat; */ + 0, /* intargfunc sq_repeat; */ + Pointer_item, /* intargfunc sq_item; */ + 0, /* intintargfunc sq_slice; */ + Pointer_ass_item, /* intobjargproc sq_ass_item; */ + 0, /* intintobjargproc sq_ass_slice; */ + 0, /* objobjproc sq_contains; */ + /* Added in release 2.0 */ + 0, /* binaryfunc sq_inplace_concat; */ + 0, /* intargfunc sq_inplace_repeat; */ }; static PyMappingMethods Pointer_as_mapping = { - 0, - Pointer_subscript, + 0, + Pointer_subscript, }; static int Pointer_bool(CDataObject *self) { - return (*(void **)self->b_ptr != NULL); + return (*(void **)self->b_ptr != NULL); } static PyNumberMethods Pointer_as_number = { - 0, /* nb_add */ - 0, /* nb_subtract */ - 0, /* nb_multiply */ - 0, /* nb_remainder */ - 0, /* nb_divmod */ - 0, /* nb_power */ - 0, /* nb_negative */ - 0, /* nb_positive */ - 0, /* nb_absolute */ - (inquiry)Pointer_bool, /* nb_bool */ + 0, /* nb_add */ + 0, /* nb_subtract */ + 0, /* nb_multiply */ + 0, /* nb_remainder */ + 0, /* nb_divmod */ + 0, /* nb_power */ + 0, /* nb_negative */ + 0, /* nb_positive */ + 0, /* nb_absolute */ + (inquiry)Pointer_bool, /* nb_bool */ }; PyTypeObject PyCPointer_Type = { - PyVarObject_HEAD_INIT(NULL, 0) - "_ctypes._Pointer", - sizeof(CDataObject), /* tp_basicsize */ - 0, /* tp_itemsize */ - 0, /* tp_dealloc */ - 0, /* tp_print */ - 0, /* tp_getattr */ - 0, /* tp_setattr */ - 0, /* tp_reserved */ - 0, /* tp_repr */ - &Pointer_as_number, /* tp_as_number */ - &Pointer_as_sequence, /* tp_as_sequence */ - &Pointer_as_mapping, /* tp_as_mapping */ - 0, /* tp_hash */ - 0, /* tp_call */ - 0, /* tp_str */ - 0, /* tp_getattro */ - 0, /* tp_setattro */ - &PyCData_as_buffer, /* tp_as_buffer */ - Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */ - "XXX to be provided", /* tp_doc */ - (traverseproc)PyCData_traverse, /* tp_traverse */ - (inquiry)PyCData_clear, /* tp_clear */ - 0, /* tp_richcompare */ - 0, /* tp_weaklistoffset */ - 0, /* tp_iter */ - 0, /* tp_iternext */ - 0, /* tp_methods */ - 0, /* tp_members */ - Pointer_getsets, /* tp_getset */ - 0, /* tp_base */ - 0, /* tp_dict */ - 0, /* tp_descr_get */ - 0, /* tp_descr_set */ - 0, /* tp_dictoffset */ - (initproc)Pointer_init, /* tp_init */ - 0, /* tp_alloc */ - Pointer_new, /* tp_new */ - 0, /* tp_free */ + PyVarObject_HEAD_INIT(NULL, 0) + "_ctypes._Pointer", + sizeof(CDataObject), /* tp_basicsize */ + 0, /* tp_itemsize */ + 0, /* tp_dealloc */ + 0, /* tp_print */ + 0, /* tp_getattr */ + 0, /* tp_setattr */ + 0, /* tp_reserved */ + 0, /* tp_repr */ + &Pointer_as_number, /* tp_as_number */ + &Pointer_as_sequence, /* tp_as_sequence */ + &Pointer_as_mapping, /* tp_as_mapping */ + 0, /* tp_hash */ + 0, /* tp_call */ + 0, /* tp_str */ + 0, /* tp_getattro */ + 0, /* tp_setattro */ + &PyCData_as_buffer, /* tp_as_buffer */ + Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */ + "XXX to be provided", /* tp_doc */ + (traverseproc)PyCData_traverse, /* tp_traverse */ + (inquiry)PyCData_clear, /* tp_clear */ + 0, /* tp_richcompare */ + 0, /* tp_weaklistoffset */ + 0, /* tp_iter */ + 0, /* tp_iternext */ + 0, /* tp_methods */ + 0, /* tp_members */ + Pointer_getsets, /* tp_getset */ + 0, /* tp_base */ + 0, /* tp_dict */ + 0, /* tp_descr_get */ + 0, /* tp_descr_set */ + 0, /* tp_dictoffset */ + (initproc)Pointer_init, /* tp_init */ + 0, /* tp_alloc */ + Pointer_new, /* tp_new */ + 0, /* tp_free */ }; - + /******************************************************************/ /* * Module initialization. @@ -5056,27 +5056,27 @@ int status; if (!_PyArg_NoKeywords(Py_TYPE(self)->tp_name, kwds)) - return -1; + return -1; if (!PyArg_ParseTuple(args, "OOO:COMError", &hresult, &text, &details)) - return -1; + return -1; a = PySequence_GetSlice(args, 1, PySequence_Size(args)); if (!a) - return -1; + return -1; status = PyObject_SetAttrString(self, "args", a); Py_DECREF(a); if (status < 0) - return -1; + return -1; if (PyObject_SetAttrString(self, "hresult", hresult) < 0) - return -1; + return -1; if (PyObject_SetAttrString(self, "text", text) < 0) - return -1; + return -1; if (PyObject_SetAttrString(self, "details", details) < 0) - return -1; + return -1; bself = (PyBaseExceptionObject *)self; Py_DECREF(bself->args); @@ -5131,11 +5131,11 @@ static int create_comerror(void) { - PyComError_Type.tp_base = (PyTypeObject*)PyExc_Exception; - if (PyType_Ready(&PyComError_Type) < 0) - return -1; - ComError = (PyObject*)&PyComError_Type; - return 0; + PyComError_Type.tp_base = (PyTypeObject*)PyExc_Exception; + if (PyType_Ready(&PyComError_Type) < 0) + return -1; + ComError = (PyObject*)&PyComError_Type; + return 0; } #endif @@ -5143,259 +5143,259 @@ static PyObject * string_at(const char *ptr, int size) { - if (size == -1) - return PyBytes_FromStringAndSize(ptr, strlen(ptr)); - return PyBytes_FromStringAndSize(ptr, size); + if (size == -1) + return PyBytes_FromStringAndSize(ptr, strlen(ptr)); + return PyBytes_FromStringAndSize(ptr, size); } static int cast_check_pointertype(PyObject *arg) { - StgDictObject *dict; + StgDictObject *dict; - if (PyCPointerTypeObject_Check(arg)) - return 1; - if (PyCFuncPtrTypeObject_Check(arg)) - return 1; - dict = PyType_stgdict(arg); - if (dict) { - if (PyUnicode_Check(dict->proto) - && (strchr("sPzUZXO", _PyUnicode_AsString(dict->proto)[0]))) { - /* simple pointer types, c_void_p, c_wchar_p, BSTR, ... */ - return 1; - } - } - PyErr_Format(PyExc_TypeError, - "cast() argument 2 must be a pointer type, not %s", - PyType_Check(arg) - ? ((PyTypeObject *)arg)->tp_name - : Py_TYPE(arg)->tp_name); - return 0; + if (PyCPointerTypeObject_Check(arg)) + return 1; + if (PyCFuncPtrTypeObject_Check(arg)) + return 1; + dict = PyType_stgdict(arg); + if (dict) { + if (PyUnicode_Check(dict->proto) + && (strchr("sPzUZXO", _PyUnicode_AsString(dict->proto)[0]))) { + /* simple pointer types, c_void_p, c_wchar_p, BSTR, ... */ + return 1; + } + } + PyErr_Format(PyExc_TypeError, + "cast() argument 2 must be a pointer type, not %s", + PyType_Check(arg) + ? ((PyTypeObject *)arg)->tp_name + : Py_TYPE(arg)->tp_name); + return 0; } static PyObject * cast(void *ptr, PyObject *src, PyObject *ctype) { - CDataObject *result; - if (0 == cast_check_pointertype(ctype)) - return NULL; - result = (CDataObject *)PyObject_CallFunctionObjArgs(ctype, NULL); - if (result == NULL) - return NULL; - - /* - The casted objects '_objects' member: - - It must certainly contain the source objects one. - It must contain the source object itself. - */ - if (CDataObject_Check(src)) { - CDataObject *obj = (CDataObject *)src; - /* PyCData_GetContainer will initialize src.b_objects, we need - this so it can be shared */ - PyCData_GetContainer(obj); - /* But we need a dictionary! */ - if (obj->b_objects == Py_None) { - Py_DECREF(Py_None); - obj->b_objects = PyDict_New(); - if (obj->b_objects == NULL) - goto failed; - } - Py_XINCREF(obj->b_objects); - result->b_objects = obj->b_objects; - if (result->b_objects && PyDict_CheckExact(result->b_objects)) { - PyObject *index; - int rc; - index = PyLong_FromVoidPtr((void *)src); - if (index == NULL) - goto failed; - rc = PyDict_SetItem(result->b_objects, index, src); - Py_DECREF(index); - if (rc == -1) - goto failed; - } - } - /* Should we assert that result is a pointer type? */ - memcpy(result->b_ptr, &ptr, sizeof(void *)); - return (PyObject *)result; + CDataObject *result; + if (0 == cast_check_pointertype(ctype)) + return NULL; + result = (CDataObject *)PyObject_CallFunctionObjArgs(ctype, NULL); + if (result == NULL) + return NULL; + + /* + The casted objects '_objects' member: + + It must certainly contain the source objects one. + It must contain the source object itself. + */ + if (CDataObject_Check(src)) { + CDataObject *obj = (CDataObject *)src; + /* PyCData_GetContainer will initialize src.b_objects, we need + this so it can be shared */ + PyCData_GetContainer(obj); + /* But we need a dictionary! */ + if (obj->b_objects == Py_None) { + Py_DECREF(Py_None); + obj->b_objects = PyDict_New(); + if (obj->b_objects == NULL) + goto failed; + } + Py_XINCREF(obj->b_objects); + result->b_objects = obj->b_objects; + if (result->b_objects && PyDict_CheckExact(result->b_objects)) { + PyObject *index; + int rc; + index = PyLong_FromVoidPtr((void *)src); + if (index == NULL) + goto failed; + rc = PyDict_SetItem(result->b_objects, index, src); + Py_DECREF(index); + if (rc == -1) + goto failed; + } + } + /* Should we assert that result is a pointer type? */ + memcpy(result->b_ptr, &ptr, sizeof(void *)); + return (PyObject *)result; failed: - Py_DECREF(result); - return NULL; + Py_DECREF(result); + return NULL; } #ifdef CTYPES_UNICODE static PyObject * wstring_at(const wchar_t *ptr, int size) { - Py_ssize_t ssize = size; - if (ssize == -1) - ssize = wcslen(ptr); - return PyUnicode_FromWideChar(ptr, ssize); + Py_ssize_t ssize = size; + if (ssize == -1) + ssize = wcslen(ptr); + return PyUnicode_FromWideChar(ptr, ssize); } #endif static struct PyModuleDef _ctypesmodule = { - PyModuleDef_HEAD_INIT, - "_ctypes", - module_docs, - -1, - _ctypes_module_methods, - NULL, - NULL, - NULL, - NULL + PyModuleDef_HEAD_INIT, + "_ctypes", + module_docs, + -1, + _ctypes_module_methods, + NULL, + NULL, + NULL, + NULL }; PyMODINIT_FUNC PyInit__ctypes(void) { - PyObject *m; + PyObject *m; /* Note: ob_type is the metatype (the 'type'), defaults to PyType_Type, tp_base is the base type, defaults to 'object' aka PyBaseObject_Type. */ #ifdef WITH_THREAD - PyEval_InitThreads(); + PyEval_InitThreads(); #endif - m = PyModule_Create(&_ctypesmodule); - if (!m) - return NULL; - - _ctypes_ptrtype_cache = PyDict_New(); - if (_ctypes_ptrtype_cache == NULL) - return NULL; - - PyModule_AddObject(m, "_pointer_type_cache", (PyObject *)_ctypes_ptrtype_cache); - - _unpickle = PyObject_GetAttrString(m, "_unpickle"); - if (_unpickle == NULL) - return NULL; - - if (PyType_Ready(&PyCArg_Type) < 0) - return NULL; - - if (PyType_Ready(&PyCThunk_Type) < 0) - return NULL; - - /* StgDict is derived from PyDict_Type */ - PyCStgDict_Type.tp_base = &PyDict_Type; - if (PyType_Ready(&PyCStgDict_Type) < 0) - return NULL; - - /************************************************* - * - * Metaclasses - */ - - PyCStructType_Type.tp_base = &PyType_Type; - if (PyType_Ready(&PyCStructType_Type) < 0) - return NULL; - - UnionType_Type.tp_base = &PyType_Type; - if (PyType_Ready(&UnionType_Type) < 0) - return NULL; - - PyCPointerType_Type.tp_base = &PyType_Type; - if (PyType_Ready(&PyCPointerType_Type) < 0) - return NULL; - - PyCArrayType_Type.tp_base = &PyType_Type; - if (PyType_Ready(&PyCArrayType_Type) < 0) - return NULL; - - PyCSimpleType_Type.tp_base = &PyType_Type; - if (PyType_Ready(&PyCSimpleType_Type) < 0) - return NULL; - - PyCFuncPtrType_Type.tp_base = &PyType_Type; - if (PyType_Ready(&PyCFuncPtrType_Type) < 0) - return NULL; - - /************************************************* - * - * Classes using a custom metaclass - */ - - if (PyType_Ready(&PyCData_Type) < 0) - return NULL; - - Py_TYPE(&Struct_Type) = &PyCStructType_Type; - Struct_Type.tp_base = &PyCData_Type; - if (PyType_Ready(&Struct_Type) < 0) - return NULL; - PyModule_AddObject(m, "Structure", (PyObject *)&Struct_Type); - - Py_TYPE(&Union_Type) = &UnionType_Type; - Union_Type.tp_base = &PyCData_Type; - if (PyType_Ready(&Union_Type) < 0) - return NULL; - PyModule_AddObject(m, "Union", (PyObject *)&Union_Type); - - Py_TYPE(&PyCPointer_Type) = &PyCPointerType_Type; - PyCPointer_Type.tp_base = &PyCData_Type; - if (PyType_Ready(&PyCPointer_Type) < 0) - return NULL; - PyModule_AddObject(m, "_Pointer", (PyObject *)&PyCPointer_Type); - - Py_TYPE(&PyCArray_Type) = &PyCArrayType_Type; - PyCArray_Type.tp_base = &PyCData_Type; - if (PyType_Ready(&PyCArray_Type) < 0) - return NULL; - PyModule_AddObject(m, "Array", (PyObject *)&PyCArray_Type); - - Py_TYPE(&Simple_Type) = &PyCSimpleType_Type; - Simple_Type.tp_base = &PyCData_Type; - if (PyType_Ready(&Simple_Type) < 0) - return NULL; - PyModule_AddObject(m, "_SimpleCData", (PyObject *)&Simple_Type); - - Py_TYPE(&PyCFuncPtr_Type) = &PyCFuncPtrType_Type; - PyCFuncPtr_Type.tp_base = &PyCData_Type; - if (PyType_Ready(&PyCFuncPtr_Type) < 0) - return NULL; - PyModule_AddObject(m, "CFuncPtr", (PyObject *)&PyCFuncPtr_Type); - - /************************************************* - * - * Simple classes - */ - - /* PyCField_Type is derived from PyBaseObject_Type */ - if (PyType_Ready(&PyCField_Type) < 0) - return NULL; - - /************************************************* - * - * Other stuff - */ - - DictRemover_Type.tp_new = PyType_GenericNew; - if (PyType_Ready(&DictRemover_Type) < 0) - return NULL; + m = PyModule_Create(&_ctypesmodule); + if (!m) + return NULL; + + _ctypes_ptrtype_cache = PyDict_New(); + if (_ctypes_ptrtype_cache == NULL) + return NULL; + + PyModule_AddObject(m, "_pointer_type_cache", (PyObject *)_ctypes_ptrtype_cache); + + _unpickle = PyObject_GetAttrString(m, "_unpickle"); + if (_unpickle == NULL) + return NULL; + + if (PyType_Ready(&PyCArg_Type) < 0) + return NULL; + + if (PyType_Ready(&PyCThunk_Type) < 0) + return NULL; + + /* StgDict is derived from PyDict_Type */ + PyCStgDict_Type.tp_base = &PyDict_Type; + if (PyType_Ready(&PyCStgDict_Type) < 0) + return NULL; + + /************************************************* + * + * Metaclasses + */ + + PyCStructType_Type.tp_base = &PyType_Type; + if (PyType_Ready(&PyCStructType_Type) < 0) + return NULL; + + UnionType_Type.tp_base = &PyType_Type; + if (PyType_Ready(&UnionType_Type) < 0) + return NULL; + + PyCPointerType_Type.tp_base = &PyType_Type; + if (PyType_Ready(&PyCPointerType_Type) < 0) + return NULL; + + PyCArrayType_Type.tp_base = &PyType_Type; + if (PyType_Ready(&PyCArrayType_Type) < 0) + return NULL; + + PyCSimpleType_Type.tp_base = &PyType_Type; + if (PyType_Ready(&PyCSimpleType_Type) < 0) + return NULL; + + PyCFuncPtrType_Type.tp_base = &PyType_Type; + if (PyType_Ready(&PyCFuncPtrType_Type) < 0) + return NULL; + + /************************************************* + * + * Classes using a custom metaclass + */ + + if (PyType_Ready(&PyCData_Type) < 0) + return NULL; + + Py_TYPE(&Struct_Type) = &PyCStructType_Type; + Struct_Type.tp_base = &PyCData_Type; + if (PyType_Ready(&Struct_Type) < 0) + return NULL; + PyModule_AddObject(m, "Structure", (PyObject *)&Struct_Type); + + Py_TYPE(&Union_Type) = &UnionType_Type; + Union_Type.tp_base = &PyCData_Type; + if (PyType_Ready(&Union_Type) < 0) + return NULL; + PyModule_AddObject(m, "Union", (PyObject *)&Union_Type); + + Py_TYPE(&PyCPointer_Type) = &PyCPointerType_Type; + PyCPointer_Type.tp_base = &PyCData_Type; + if (PyType_Ready(&PyCPointer_Type) < 0) + return NULL; + PyModule_AddObject(m, "_Pointer", (PyObject *)&PyCPointer_Type); + + Py_TYPE(&PyCArray_Type) = &PyCArrayType_Type; + PyCArray_Type.tp_base = &PyCData_Type; + if (PyType_Ready(&PyCArray_Type) < 0) + return NULL; + PyModule_AddObject(m, "Array", (PyObject *)&PyCArray_Type); + + Py_TYPE(&Simple_Type) = &PyCSimpleType_Type; + Simple_Type.tp_base = &PyCData_Type; + if (PyType_Ready(&Simple_Type) < 0) + return NULL; + PyModule_AddObject(m, "_SimpleCData", (PyObject *)&Simple_Type); + + Py_TYPE(&PyCFuncPtr_Type) = &PyCFuncPtrType_Type; + PyCFuncPtr_Type.tp_base = &PyCData_Type; + if (PyType_Ready(&PyCFuncPtr_Type) < 0) + return NULL; + PyModule_AddObject(m, "CFuncPtr", (PyObject *)&PyCFuncPtr_Type); + + /************************************************* + * + * Simple classes + */ + + /* PyCField_Type is derived from PyBaseObject_Type */ + if (PyType_Ready(&PyCField_Type) < 0) + return NULL; + + /************************************************* + * + * Other stuff + */ + + DictRemover_Type.tp_new = PyType_GenericNew; + if (PyType_Ready(&DictRemover_Type) < 0) + return NULL; #ifdef MS_WIN32 - if (create_comerror() < 0) - return NULL; - PyModule_AddObject(m, "COMError", ComError); + if (create_comerror() < 0) + return NULL; + PyModule_AddObject(m, "COMError", ComError); - PyModule_AddObject(m, "FUNCFLAG_HRESULT", PyLong_FromLong(FUNCFLAG_HRESULT)); - PyModule_AddObject(m, "FUNCFLAG_STDCALL", PyLong_FromLong(FUNCFLAG_STDCALL)); + PyModule_AddObject(m, "FUNCFLAG_HRESULT", PyLong_FromLong(FUNCFLAG_HRESULT)); + PyModule_AddObject(m, "FUNCFLAG_STDCALL", PyLong_FromLong(FUNCFLAG_STDCALL)); #endif - PyModule_AddObject(m, "FUNCFLAG_CDECL", PyLong_FromLong(FUNCFLAG_CDECL)); - PyModule_AddObject(m, "FUNCFLAG_USE_ERRNO", PyLong_FromLong(FUNCFLAG_USE_ERRNO)); - PyModule_AddObject(m, "FUNCFLAG_USE_LASTERROR", PyLong_FromLong(FUNCFLAG_USE_LASTERROR)); - PyModule_AddObject(m, "FUNCFLAG_PYTHONAPI", PyLong_FromLong(FUNCFLAG_PYTHONAPI)); - PyModule_AddStringConstant(m, "__version__", "1.1.0"); - - PyModule_AddObject(m, "_memmove_addr", PyLong_FromVoidPtr(memmove)); - PyModule_AddObject(m, "_memset_addr", PyLong_FromVoidPtr(memset)); - PyModule_AddObject(m, "_string_at_addr", PyLong_FromVoidPtr(string_at)); - PyModule_AddObject(m, "_cast_addr", PyLong_FromVoidPtr(cast)); + PyModule_AddObject(m, "FUNCFLAG_CDECL", PyLong_FromLong(FUNCFLAG_CDECL)); + PyModule_AddObject(m, "FUNCFLAG_USE_ERRNO", PyLong_FromLong(FUNCFLAG_USE_ERRNO)); + PyModule_AddObject(m, "FUNCFLAG_USE_LASTERROR", PyLong_FromLong(FUNCFLAG_USE_LASTERROR)); + PyModule_AddObject(m, "FUNCFLAG_PYTHONAPI", PyLong_FromLong(FUNCFLAG_PYTHONAPI)); + PyModule_AddStringConstant(m, "__version__", "1.1.0"); + + PyModule_AddObject(m, "_memmove_addr", PyLong_FromVoidPtr(memmove)); + PyModule_AddObject(m, "_memset_addr", PyLong_FromVoidPtr(memset)); + PyModule_AddObject(m, "_string_at_addr", PyLong_FromVoidPtr(string_at)); + PyModule_AddObject(m, "_cast_addr", PyLong_FromVoidPtr(cast)); #ifdef CTYPES_UNICODE - PyModule_AddObject(m, "_wstring_at_addr", PyLong_FromVoidPtr(wstring_at)); + PyModule_AddObject(m, "_wstring_at_addr", PyLong_FromVoidPtr(wstring_at)); #endif /* If RTLD_LOCAL is not defined (Windows!), set it to zero. */ @@ -5410,15 +5410,15 @@ #define RTLD_GLOBAL RTLD_LOCAL #endif - PyModule_AddObject(m, "RTLD_LOCAL", PyLong_FromLong(RTLD_LOCAL)); - PyModule_AddObject(m, "RTLD_GLOBAL", PyLong_FromLong(RTLD_GLOBAL)); - - PyExc_ArgError = PyErr_NewException("ctypes.ArgumentError", NULL, NULL); - if (PyExc_ArgError) { - Py_INCREF(PyExc_ArgError); - PyModule_AddObject(m, "ArgumentError", PyExc_ArgError); - } - return m; + PyModule_AddObject(m, "RTLD_LOCAL", PyLong_FromLong(RTLD_LOCAL)); + PyModule_AddObject(m, "RTLD_GLOBAL", PyLong_FromLong(RTLD_GLOBAL)); + + PyExc_ArgError = PyErr_NewException("ctypes.ArgumentError", NULL, NULL); + if (PyExc_ArgError) { + Py_INCREF(PyExc_ArgError); + PyModule_AddObject(m, "ArgumentError", PyExc_ArgError); + } + return m; } /* Modified: python/branches/release31-maint/Modules/_ctypes/_ctypes_test.c ============================================================================== --- python/branches/release31-maint/Modules/_ctypes/_ctypes_test.c (original) +++ python/branches/release31-maint/Modules/_ctypes/_ctypes_test.c Sun May 9 18:14:21 2010 @@ -14,152 +14,152 @@ EXPORT(void)testfunc_array(int values[4]) { - printf("testfunc_array %d %d %d %d\n", - values[0], - values[1], - values[2], - values[3]); + printf("testfunc_array %d %d %d %d\n", + values[0], + values[1], + values[2], + values[3]); } EXPORT(long double)testfunc_Ddd(double a, double b) { - long double result = (long double)(a * b); - printf("testfunc_Ddd(%p, %p)\n", &a, &b); - printf("testfunc_Ddd(%g, %g)\n", a, b); - return result; + long double result = (long double)(a * b); + printf("testfunc_Ddd(%p, %p)\n", &a, &b); + printf("testfunc_Ddd(%g, %g)\n", a, b); + return result; } EXPORT(long double)testfunc_DDD(long double a, long double b) { - long double result = a * b; - printf("testfunc_DDD(%p, %p)\n", &a, &b); - printf("testfunc_DDD(%Lg, %Lg)\n", a, b); - return result; + long double result = a * b; + printf("testfunc_DDD(%p, %p)\n", &a, &b); + printf("testfunc_DDD(%Lg, %Lg)\n", a, b); + return result; } EXPORT(int)testfunc_iii(int a, int b) { - int result = a * b; - printf("testfunc_iii(%p, %p)\n", &a, &b); - return result; + int result = a * b; + printf("testfunc_iii(%p, %p)\n", &a, &b); + return result; } EXPORT(int)myprintf(char *fmt, ...) { - int result; - va_list argptr; - va_start(argptr, fmt); - result = vprintf(fmt, argptr); - va_end(argptr); - return result; + int result; + va_list argptr; + va_start(argptr, fmt); + result = vprintf(fmt, argptr); + va_end(argptr); + return result; } EXPORT(char *)my_strtok(char *token, const char *delim) { - return strtok(token, delim); + return strtok(token, delim); } EXPORT(char *)my_strchr(const char *s, int c) { - return strchr(s, c); + return strchr(s, c); } EXPORT(double) my_sqrt(double a) { - return sqrt(a); + return sqrt(a); } EXPORT(void) my_qsort(void *base, size_t num, size_t width, int(*compare)(const void*, const void*)) { - qsort(base, num, width, compare); + qsort(base, num, width, compare); } EXPORT(int *) _testfunc_ai8(int a[8]) { - return a; + return a; } EXPORT(void) _testfunc_v(int a, int b, int *presult) { - *presult = a + b; + *presult = a + b; } EXPORT(int) _testfunc_i_bhilfd(signed char b, short h, int i, long l, float f, double d) { -/* printf("_testfunc_i_bhilfd got %d %d %d %ld %f %f\n", - b, h, i, l, f, d); +/* printf("_testfunc_i_bhilfd got %d %d %d %ld %f %f\n", + b, h, i, l, f, d); */ - return (int)(b + h + i + l + f + d); + return (int)(b + h + i + l + f + d); } EXPORT(float) _testfunc_f_bhilfd(signed char b, short h, int i, long l, float f, double d) { -/* printf("_testfunc_f_bhilfd got %d %d %d %ld %f %f\n", - b, h, i, l, f, d); +/* printf("_testfunc_f_bhilfd got %d %d %d %ld %f %f\n", + b, h, i, l, f, d); */ - return (float)(b + h + i + l + f + d); + return (float)(b + h + i + l + f + d); } EXPORT(double) _testfunc_d_bhilfd(signed char b, short h, int i, long l, float f, double d) { -/* printf("_testfunc_d_bhilfd got %d %d %d %ld %f %f\n", - b, h, i, l, f, d); +/* printf("_testfunc_d_bhilfd got %d %d %d %ld %f %f\n", + b, h, i, l, f, d); */ - return (double)(b + h + i + l + f + d); + return (double)(b + h + i + l + f + d); } EXPORT(long double) _testfunc_D_bhilfD(signed char b, short h, int i, long l, float f, long double d) { -/* printf("_testfunc_d_bhilfd got %d %d %d %ld %f %f\n", - b, h, i, l, f, d); +/* printf("_testfunc_d_bhilfd got %d %d %d %ld %f %f\n", + b, h, i, l, f, d); */ - return (long double)(b + h + i + l + f + d); + return (long double)(b + h + i + l + f + d); } EXPORT(char *) _testfunc_p_p(void *s) { - return (char *)s; + return (char *)s; } EXPORT(void *) _testfunc_c_p_p(int *argcp, char **argv) { - return argv[(*argcp)-1]; + return argv[(*argcp)-1]; } EXPORT(void *) get_strchr(void) { - return (void *)strchr; + return (void *)strchr; } EXPORT(char *) my_strdup(char *src) { - char *dst = (char *)malloc(strlen(src)+1); - if (!dst) - return NULL; - strcpy(dst, src); - return dst; + char *dst = (char *)malloc(strlen(src)+1); + if (!dst) + return NULL; + strcpy(dst, src); + return dst; } EXPORT(void)my_free(void *ptr) { - free(ptr); + free(ptr); } #ifdef HAVE_WCHAR_H EXPORT(wchar_t *) my_wcsdup(wchar_t *src) { - size_t len = wcslen(src); - wchar_t *ptr = (wchar_t *)malloc((len + 1) * sizeof(wchar_t)); - if (ptr == NULL) - return NULL; - memcpy(ptr, src, (len+1) * sizeof(wchar_t)); - return ptr; + size_t len = wcslen(src); + wchar_t *ptr = (wchar_t *)malloc((len + 1) * sizeof(wchar_t)); + if (ptr == NULL) + return NULL; + memcpy(ptr, src, (len+1) * sizeof(wchar_t)); + return ptr; } EXPORT(size_t) my_wcslen(wchar_t *src) { - return wcslen(src); + return wcslen(src); } #endif @@ -170,158 +170,158 @@ #endif typedef struct { - int (*c)(int, int); - int (__stdcall *s)(int, int); + int (*c)(int, int); + int (__stdcall *s)(int, int); } FUNCS; EXPORT(int) _testfunc_callfuncp(FUNCS *fp) { - fp->c(1, 2); - fp->s(3, 4); - return 0; + fp->c(1, 2); + fp->s(3, 4); + return 0; } EXPORT(int) _testfunc_deref_pointer(int *pi) { - return *pi; + return *pi; } #ifdef MS_WIN32 EXPORT(int) _testfunc_piunk(IUnknown FAR *piunk) { - piunk->lpVtbl->AddRef(piunk); - return piunk->lpVtbl->Release(piunk); + piunk->lpVtbl->AddRef(piunk); + return piunk->lpVtbl->Release(piunk); } #endif EXPORT(int) _testfunc_callback_with_pointer(int (*func)(int *)) { - int table[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; + int table[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; - return (*func)(table); + return (*func)(table); } #ifdef HAVE_LONG_LONG EXPORT(PY_LONG_LONG) _testfunc_q_bhilfdq(signed char b, short h, int i, long l, float f, - double d, PY_LONG_LONG q) + double d, PY_LONG_LONG q) { - return (PY_LONG_LONG)(b + h + i + l + f + d + q); + return (PY_LONG_LONG)(b + h + i + l + f + d + q); } EXPORT(PY_LONG_LONG) _testfunc_q_bhilfd(signed char b, short h, int i, long l, float f, double d) { - return (PY_LONG_LONG)(b + h + i + l + f + d); + return (PY_LONG_LONG)(b + h + i + l + f + d); } EXPORT(int) _testfunc_callback_i_if(int value, int (*func)(int)) { - int sum = 0; - while (value != 0) { - sum += func(value); - value /= 2; - } - return sum; + int sum = 0; + while (value != 0) { + sum += func(value); + value /= 2; + } + return sum; } EXPORT(PY_LONG_LONG) _testfunc_callback_q_qf(PY_LONG_LONG value, - PY_LONG_LONG (*func)(PY_LONG_LONG)) + PY_LONG_LONG (*func)(PY_LONG_LONG)) { - PY_LONG_LONG sum = 0; + PY_LONG_LONG sum = 0; - while (value != 0) { - sum += func(value); - value /= 2; - } - return sum; + while (value != 0) { + sum += func(value); + value /= 2; + } + return sum; } #endif typedef struct { - char *name; - char *value; + char *name; + char *value; } SPAM; typedef struct { - char *name; - int num_spams; - SPAM *spams; + char *name; + int num_spams; + SPAM *spams; } EGG; SPAM my_spams[2] = { - { "name1", "value1" }, - { "name2", "value2" }, + { "name1", "value1" }, + { "name2", "value2" }, }; EGG my_eggs[1] = { - { "first egg", 1, my_spams } + { "first egg", 1, my_spams } }; EXPORT(int) getSPAMANDEGGS(EGG **eggs) { - *eggs = my_eggs; - return 1; + *eggs = my_eggs; + return 1; } typedef struct tagpoint { - int x; - int y; + int x; + int y; } point; EXPORT(int) _testfunc_byval(point in, point *pout) { - if (pout) { - pout->x = in.x; - pout->y = in.y; - } - return in.x + in.y; + if (pout) { + pout->x = in.x; + pout->y = in.y; + } + return in.x + in.y; } EXPORT (int) an_integer = 42; EXPORT(int) get_an_integer(void) { - return an_integer; + return an_integer; } EXPORT(double) integrate(double a, double b, double (*f)(double), long nstep) { - double x, sum=0.0, dx=(b-a)/(double)nstep; - for(x=a+0.5*dx; (b-x)*(x-a)>0.0; x+=dx) - sum += f(x); - return sum/(double)nstep; + double x, sum=0.0, dx=(b-a)/(double)nstep; + for(x=a+0.5*dx; (b-x)*(x-a)>0.0; x+=dx) + sum += f(x); + return sum/(double)nstep; } typedef struct { - void (*initialize)(void *(*)(int), void(*)(void *)); + void (*initialize)(void *(*)(int), void(*)(void *)); } xxx_library; static void _xxx_init(void *(*Xalloc)(int), void (*Xfree)(void *)) { - void *ptr; - - printf("_xxx_init got %p %p\n", Xalloc, Xfree); - printf("calling\n"); - ptr = Xalloc(32); - Xfree(ptr); - printf("calls done, ptr was %p\n", ptr); + void *ptr; + + printf("_xxx_init got %p %p\n", Xalloc, Xfree); + printf("calling\n"); + ptr = Xalloc(32); + Xfree(ptr); + printf("calls done, ptr was %p\n", ptr); } xxx_library _xxx_lib = { - _xxx_init + _xxx_init }; EXPORT(xxx_library) *library_get(void) { - return &_xxx_lib; + return &_xxx_lib; } #ifdef MS_WIN32 /* See Don Box (german), pp 79ff. */ EXPORT(void) GetString(BSTR *pbstr) { - *pbstr = SysAllocString(L"Goodbye!"); + *pbstr = SysAllocString(L"Goodbye!"); } #endif @@ -330,12 +330,12 @@ */ PyObject *py_func_si(PyObject *self, PyObject *args) { - char *name; - int i; - if (!PyArg_ParseTuple(args, "si", &name, &i)) - return NULL; - Py_INCREF(Py_None); - return Py_None; + char *name; + int i; + if (!PyArg_ParseTuple(args, "si", &name, &i)) + return NULL; + Py_INCREF(Py_None); + return Py_None; } EXPORT(void) _py_func_si(char *s, int i) @@ -344,8 +344,8 @@ PyObject *py_func(PyObject *self, PyObject *args) { - Py_INCREF(Py_None); - return Py_None; + Py_INCREF(Py_None); + return Py_None; } EXPORT(void) _py_func(void) @@ -356,64 +356,64 @@ EXPORT(unsigned PY_LONG_LONG) last_tf_arg_u; struct BITS { - int A: 1, B:2, C:3, D:4, E: 5, F: 6, G: 7, H: 8, I: 9; - short M: 1, N: 2, O: 3, P: 4, Q: 5, R: 6, S: 7; + int A: 1, B:2, C:3, D:4, E: 5, F: 6, G: 7, H: 8, I: 9; + short M: 1, N: 2, O: 3, P: 4, Q: 5, R: 6, S: 7; }; EXPORT(void) set_bitfields(struct BITS *bits, char name, int value) { - switch (name) { - case 'A': bits->A = value; break; - case 'B': bits->B = value; break; - case 'C': bits->C = value; break; - case 'D': bits->D = value; break; - case 'E': bits->E = value; break; - case 'F': bits->F = value; break; - case 'G': bits->G = value; break; - case 'H': bits->H = value; break; - case 'I': bits->I = value; break; - - case 'M': bits->M = value; break; - case 'N': bits->N = value; break; - case 'O': bits->O = value; break; - case 'P': bits->P = value; break; - case 'Q': bits->Q = value; break; - case 'R': bits->R = value; break; - case 'S': bits->S = value; break; - } + switch (name) { + case 'A': bits->A = value; break; + case 'B': bits->B = value; break; + case 'C': bits->C = value; break; + case 'D': bits->D = value; break; + case 'E': bits->E = value; break; + case 'F': bits->F = value; break; + case 'G': bits->G = value; break; + case 'H': bits->H = value; break; + case 'I': bits->I = value; break; + + case 'M': bits->M = value; break; + case 'N': bits->N = value; break; + case 'O': bits->O = value; break; + case 'P': bits->P = value; break; + case 'Q': bits->Q = value; break; + case 'R': bits->R = value; break; + case 'S': bits->S = value; break; + } } EXPORT(int) unpack_bitfields(struct BITS *bits, char name) { - switch (name) { - case 'A': return bits->A; - case 'B': return bits->B; - case 'C': return bits->C; - case 'D': return bits->D; - case 'E': return bits->E; - case 'F': return bits->F; - case 'G': return bits->G; - case 'H': return bits->H; - case 'I': return bits->I; - - case 'M': return bits->M; - case 'N': return bits->N; - case 'O': return bits->O; - case 'P': return bits->P; - case 'Q': return bits->Q; - case 'R': return bits->R; - case 'S': return bits->S; - } - return 0; + switch (name) { + case 'A': return bits->A; + case 'B': return bits->B; + case 'C': return bits->C; + case 'D': return bits->D; + case 'E': return bits->E; + case 'F': return bits->F; + case 'G': return bits->G; + case 'H': return bits->H; + case 'I': return bits->I; + + case 'M': return bits->M; + case 'N': return bits->N; + case 'O': return bits->O; + case 'P': return bits->P; + case 'Q': return bits->Q; + case 'R': return bits->R; + case 'S': return bits->S; + } + return 0; } static PyMethodDef module_methods[] = { -/* {"get_last_tf_arg_s", get_last_tf_arg_s, METH_NOARGS}, - {"get_last_tf_arg_u", get_last_tf_arg_u, METH_NOARGS}, +/* {"get_last_tf_arg_s", get_last_tf_arg_s, METH_NOARGS}, + {"get_last_tf_arg_u", get_last_tf_arg_u, METH_NOARGS}, */ - {"func_si", py_func_si, METH_VARARGS}, - {"func", py_func, METH_NOARGS}, - { NULL, NULL, 0, NULL}, + {"func_si", py_func_si, METH_VARARGS}, + {"func", py_func, METH_NOARGS}, + { NULL, NULL, 0, NULL}, }; #define S last_tf_arg_s = (PY_LONG_LONG)c @@ -483,80 +483,80 @@ #endif /********/ - + #ifndef MS_WIN32 typedef struct { - long x; - long y; + long x; + long y; } POINT; typedef struct { - long left; - long top; - long right; - long bottom; + long left; + long top; + long right; + long bottom; } RECT; #endif EXPORT(int) PointInRect(RECT *prc, POINT pt) { - if (pt.x < prc->left) - return 0; - if (pt.x > prc->right) - return 0; - if (pt.y < prc->top) - return 0; - if (pt.y > prc->bottom) - return 0; - return 1; + if (pt.x < prc->left) + return 0; + if (pt.x > prc->right) + return 0; + if (pt.y < prc->top) + return 0; + if (pt.y > prc->bottom) + return 0; + return 1; } typedef struct { - short x; - short y; + short x; + short y; } S2H; EXPORT(S2H) ret_2h_func(S2H inp) { - inp.x *= 2; - inp.y *= 3; - return inp; + inp.x *= 2; + inp.y *= 3; + return inp; } typedef struct { - int a, b, c, d, e, f, g, h; + int a, b, c, d, e, f, g, h; } S8I; EXPORT(S8I) ret_8i_func(S8I inp) { - inp.a *= 2; - inp.b *= 3; - inp.c *= 4; - inp.d *= 5; - inp.e *= 6; - inp.f *= 7; - inp.g *= 8; - inp.h *= 9; - return inp; + inp.a *= 2; + inp.b *= 3; + inp.c *= 4; + inp.d *= 5; + inp.e *= 6; + inp.f *= 7; + inp.g *= 8; + inp.h *= 9; + return inp; } EXPORT(int) GetRectangle(int flag, RECT *prect) { - if (flag == 0) - return 0; - prect->left = (int)flag; - prect->top = (int)flag + 1; - prect->right = (int)flag + 2; - prect->bottom = (int)flag + 3; - return 1; + if (flag == 0) + return 0; + prect->left = (int)flag; + prect->top = (int)flag + 1; + prect->right = (int)flag + 2; + prect->bottom = (int)flag + 3; + return 1; } EXPORT(void) TwoOutArgs(int a, int *pi, int b, int *pj) { - *pi += a; - *pj += b; + *pi += a; + *pj += b; } #ifdef MS_WIN32 @@ -571,32 +571,32 @@ EXPORT (HRESULT) KeepObject(IUnknown *punk) { - static IUnknown *pobj; - if (punk) - punk->lpVtbl->AddRef(punk); - if (pobj) - pobj->lpVtbl->Release(pobj); - pobj = punk; - return S_OK; + static IUnknown *pobj; + if (punk) + punk->lpVtbl->AddRef(punk); + if (pobj) + pobj->lpVtbl->Release(pobj); + pobj = punk; + return S_OK; } #endif static struct PyModuleDef _ctypes_testmodule = { - PyModuleDef_HEAD_INIT, - "_ctypes_test", - NULL, - -1, - module_methods, - NULL, - NULL, - NULL, - NULL + PyModuleDef_HEAD_INIT, + "_ctypes_test", + NULL, + -1, + module_methods, + NULL, + NULL, + NULL, + NULL }; PyMODINIT_FUNC PyInit__ctypes_test(void) { - return PyModule_Create(&_ctypes_testmodule); + return PyModule_Create(&_ctypes_testmodule); } Modified: python/branches/release31-maint/Modules/_ctypes/callbacks.c ============================================================================== --- python/branches/release31-maint/Modules/_ctypes/callbacks.c (original) +++ python/branches/release31-maint/Modules/_ctypes/callbacks.c Sun May 9 18:14:21 2010 @@ -12,65 +12,65 @@ static void CThunkObject_dealloc(PyObject *_self) { - CThunkObject *self = (CThunkObject *)_self; - Py_XDECREF(self->converters); - Py_XDECREF(self->callable); - Py_XDECREF(self->restype); - if (self->pcl) - _ctypes_free_closure(self->pcl); - PyObject_GC_Del(self); + CThunkObject *self = (CThunkObject *)_self; + Py_XDECREF(self->converters); + Py_XDECREF(self->callable); + Py_XDECREF(self->restype); + if (self->pcl) + _ctypes_free_closure(self->pcl); + PyObject_GC_Del(self); } static int CThunkObject_traverse(PyObject *_self, visitproc visit, void *arg) { - CThunkObject *self = (CThunkObject *)_self; - Py_VISIT(self->converters); - Py_VISIT(self->callable); - Py_VISIT(self->restype); - return 0; + CThunkObject *self = (CThunkObject *)_self; + Py_VISIT(self->converters); + Py_VISIT(self->callable); + Py_VISIT(self->restype); + return 0; } static int CThunkObject_clear(PyObject *_self) { - CThunkObject *self = (CThunkObject *)_self; - Py_CLEAR(self->converters); - Py_CLEAR(self->callable); - Py_CLEAR(self->restype); - return 0; + CThunkObject *self = (CThunkObject *)_self; + Py_CLEAR(self->converters); + Py_CLEAR(self->callable); + Py_CLEAR(self->restype); + return 0; } PyTypeObject PyCThunk_Type = { - PyVarObject_HEAD_INIT(NULL, 0) - "_ctypes.CThunkObject", - sizeof(CThunkObject), /* tp_basicsize */ - sizeof(ffi_type), /* tp_itemsize */ - CThunkObject_dealloc, /* tp_dealloc */ - 0, /* tp_print */ - 0, /* tp_getattr */ - 0, /* tp_setattr */ - 0, /* tp_reserved */ - 0, /* tp_repr */ - 0, /* tp_as_number */ - 0, /* tp_as_sequence */ - 0, /* tp_as_mapping */ - 0, /* tp_hash */ - 0, /* tp_call */ - 0, /* tp_str */ - 0, /* tp_getattro */ - 0, /* tp_setattro */ - 0, /* tp_as_buffer */ - Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC, /* tp_flags */ - "CThunkObject", /* tp_doc */ - CThunkObject_traverse, /* tp_traverse */ - CThunkObject_clear, /* tp_clear */ - 0, /* tp_richcompare */ - 0, /* tp_weaklistoffset */ - 0, /* tp_iter */ - 0, /* tp_iternext */ - 0, /* tp_methods */ - 0, /* tp_members */ + PyVarObject_HEAD_INIT(NULL, 0) + "_ctypes.CThunkObject", + sizeof(CThunkObject), /* tp_basicsize */ + sizeof(ffi_type), /* tp_itemsize */ + CThunkObject_dealloc, /* tp_dealloc */ + 0, /* tp_print */ + 0, /* tp_getattr */ + 0, /* tp_setattr */ + 0, /* tp_reserved */ + 0, /* tp_repr */ + 0, /* tp_as_number */ + 0, /* tp_as_sequence */ + 0, /* tp_as_mapping */ + 0, /* tp_hash */ + 0, /* tp_call */ + 0, /* tp_str */ + 0, /* tp_getattro */ + 0, /* tp_setattro */ + 0, /* tp_as_buffer */ + Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC, /* tp_flags */ + "CThunkObject", /* tp_doc */ + CThunkObject_traverse, /* tp_traverse */ + CThunkObject_clear, /* tp_clear */ + 0, /* tp_richcompare */ + 0, /* tp_weaklistoffset */ + 0, /* tp_iter */ + 0, /* tp_iternext */ + 0, /* tp_methods */ + 0, /* tp_members */ }; /**************************************************************/ @@ -78,75 +78,75 @@ static void PrintError(char *msg, ...) { - char buf[512]; - PyObject *f = PySys_GetObject("stderr"); - va_list marker; - - va_start(marker, msg); - vsnprintf(buf, sizeof(buf), msg, marker); - va_end(marker); - if (f != NULL && f != Py_None) - PyFile_WriteString(buf, f); - PyErr_Print(); + char buf[512]; + PyObject *f = PySys_GetObject("stderr"); + va_list marker; + + va_start(marker, msg); + vsnprintf(buf, sizeof(buf), msg, marker); + va_end(marker); + if (f != NULL && f != Py_None) + PyFile_WriteString(buf, f); + PyErr_Print(); } /* after code that pyrex generates */ void _ctypes_add_traceback(char *funcname, char *filename, int lineno) { - PyObject *py_srcfile = 0; - PyObject *py_funcname = 0; - PyObject *py_globals = 0; - PyObject *empty_tuple = 0; - PyObject *empty_string = 0; - PyCodeObject *py_code = 0; - PyFrameObject *py_frame = 0; - - py_srcfile = PyUnicode_DecodeFSDefault(filename); - if (!py_srcfile) goto bad; - py_funcname = PyUnicode_FromString(funcname); - if (!py_funcname) goto bad; - py_globals = PyDict_New(); - if (!py_globals) goto bad; - empty_tuple = PyTuple_New(0); - if (!empty_tuple) goto bad; - empty_string = PyBytes_FromString(""); - if (!empty_string) goto bad; - py_code = PyCode_New( - 0, /*int argcount,*/ - 0, /*int kwonlyargcount,*/ - 0, /*int nlocals,*/ - 0, /*int stacksize,*/ - 0, /*int flags,*/ - empty_string, /*PyObject *code,*/ - empty_tuple, /*PyObject *consts,*/ - empty_tuple, /*PyObject *names,*/ - empty_tuple, /*PyObject *varnames,*/ - empty_tuple, /*PyObject *freevars,*/ - empty_tuple, /*PyObject *cellvars,*/ - py_srcfile, /*PyObject *filename,*/ - py_funcname, /*PyObject *name,*/ - lineno, /*int firstlineno,*/ - empty_string /*PyObject *lnotab*/ - ); - if (!py_code) goto bad; - py_frame = PyFrame_New( - PyThreadState_Get(), /*PyThreadState *tstate,*/ - py_code, /*PyCodeObject *code,*/ - py_globals, /*PyObject *globals,*/ - 0 /*PyObject *locals*/ - ); - if (!py_frame) goto bad; - py_frame->f_lineno = lineno; - PyTraceBack_Here(py_frame); + PyObject *py_srcfile = 0; + PyObject *py_funcname = 0; + PyObject *py_globals = 0; + PyObject *empty_tuple = 0; + PyObject *empty_string = 0; + PyCodeObject *py_code = 0; + PyFrameObject *py_frame = 0; + + py_srcfile = PyUnicode_DecodeFSDefault(filename); + if (!py_srcfile) goto bad; + py_funcname = PyUnicode_FromString(funcname); + if (!py_funcname) goto bad; + py_globals = PyDict_New(); + if (!py_globals) goto bad; + empty_tuple = PyTuple_New(0); + if (!empty_tuple) goto bad; + empty_string = PyBytes_FromString(""); + if (!empty_string) goto bad; + py_code = PyCode_New( + 0, /*int argcount,*/ + 0, /*int kwonlyargcount,*/ + 0, /*int nlocals,*/ + 0, /*int stacksize,*/ + 0, /*int flags,*/ + empty_string, /*PyObject *code,*/ + empty_tuple, /*PyObject *consts,*/ + empty_tuple, /*PyObject *names,*/ + empty_tuple, /*PyObject *varnames,*/ + empty_tuple, /*PyObject *freevars,*/ + empty_tuple, /*PyObject *cellvars,*/ + py_srcfile, /*PyObject *filename,*/ + py_funcname, /*PyObject *name,*/ + lineno, /*int firstlineno,*/ + empty_string /*PyObject *lnotab*/ + ); + if (!py_code) goto bad; + py_frame = PyFrame_New( + PyThreadState_Get(), /*PyThreadState *tstate,*/ + py_code, /*PyCodeObject *code,*/ + py_globals, /*PyObject *globals,*/ + 0 /*PyObject *locals*/ + ); + if (!py_frame) goto bad; + py_frame->f_lineno = lineno; + PyTraceBack_Here(py_frame); bad: - Py_XDECREF(py_globals); - Py_XDECREF(py_srcfile); - Py_XDECREF(py_funcname); - Py_XDECREF(empty_tuple); - Py_XDECREF(empty_string); - Py_XDECREF(py_code); - Py_XDECREF(py_frame); + Py_XDECREF(py_globals); + Py_XDECREF(py_srcfile); + Py_XDECREF(py_funcname); + Py_XDECREF(empty_tuple); + Py_XDECREF(empty_string); + Py_XDECREF(py_code); + Py_XDECREF(py_frame); } #ifdef MS_WIN32 @@ -163,15 +163,15 @@ static void TryAddRef(StgDictObject *dict, CDataObject *obj) { - IUnknown *punk; + IUnknown *punk; - if (NULL == PyDict_GetItemString((PyObject *)dict, "_needs_com_addref_")) - return; + if (NULL == PyDict_GetItemString((PyObject *)dict, "_needs_com_addref_")) + return; - punk = *(IUnknown **)obj->b_ptr; - if (punk) - punk->lpVtbl->AddRef(punk); - return; + punk = *(IUnknown **)obj->b_ptr; + if (punk) + punk->lpVtbl->AddRef(punk); + return; } #endif @@ -181,421 +181,421 @@ * */ static void _CallPythonObject(void *mem, - ffi_type *restype, - SETFUNC setfunc, - PyObject *callable, - PyObject *converters, - int flags, - void **pArgs) -{ - Py_ssize_t i; - PyObject *result; - PyObject *arglist = NULL; - Py_ssize_t nArgs; - PyObject *error_object = NULL; - int *space; + ffi_type *restype, + SETFUNC setfunc, + PyObject *callable, + PyObject *converters, + int flags, + void **pArgs) +{ + Py_ssize_t i; + PyObject *result; + PyObject *arglist = NULL; + Py_ssize_t nArgs; + PyObject *error_object = NULL; + int *space; #ifdef WITH_THREAD - PyGILState_STATE state = PyGILState_Ensure(); + PyGILState_STATE state = PyGILState_Ensure(); #endif - nArgs = PySequence_Length(converters); - /* Hm. What to return in case of error? - For COM, 0xFFFFFFFF seems better than 0. - */ - if (nArgs < 0) { - PrintError("BUG: PySequence_Length"); - goto Done; - } - - arglist = PyTuple_New(nArgs); - if (!arglist) { - PrintError("PyTuple_New()"); - goto Done; - } - for (i = 0; i < nArgs; ++i) { - /* Note: new reference! */ - PyObject *cnv = PySequence_GetItem(converters, i); - StgDictObject *dict; - if (cnv) - dict = PyType_stgdict(cnv); - else { - PrintError("Getting argument converter %d\n", i); - goto Done; - } - - if (dict && dict->getfunc && !_ctypes_simple_instance(cnv)) { - PyObject *v = dict->getfunc(*pArgs, dict->size); - if (!v) { - PrintError("create argument %d:\n", i); - Py_DECREF(cnv); - goto Done; - } - PyTuple_SET_ITEM(arglist, i, v); - /* XXX XXX XX - We have the problem that c_byte or c_short have dict->size of - 1 resp. 4, but these parameters are pushed as sizeof(int) bytes. - BTW, the same problem occurrs when they are pushed as parameters - */ - } else if (dict) { - /* Hm, shouldn't we use PyCData_AtAddress() or something like that instead? */ - CDataObject *obj = (CDataObject *)PyObject_CallFunctionObjArgs(cnv, NULL); - if (!obj) { - PrintError("create argument %d:\n", i); - Py_DECREF(cnv); - goto Done; - } - if (!CDataObject_Check(obj)) { - Py_DECREF(obj); - Py_DECREF(cnv); - PrintError("unexpected result of create argument %d:\n", i); - goto Done; - } - memcpy(obj->b_ptr, *pArgs, dict->size); - PyTuple_SET_ITEM(arglist, i, (PyObject *)obj); + nArgs = PySequence_Length(converters); + /* Hm. What to return in case of error? + For COM, 0xFFFFFFFF seems better than 0. + */ + if (nArgs < 0) { + PrintError("BUG: PySequence_Length"); + goto Done; + } + + arglist = PyTuple_New(nArgs); + if (!arglist) { + PrintError("PyTuple_New()"); + goto Done; + } + for (i = 0; i < nArgs; ++i) { + /* Note: new reference! */ + PyObject *cnv = PySequence_GetItem(converters, i); + StgDictObject *dict; + if (cnv) + dict = PyType_stgdict(cnv); + else { + PrintError("Getting argument converter %d\n", i); + goto Done; + } + + if (dict && dict->getfunc && !_ctypes_simple_instance(cnv)) { + PyObject *v = dict->getfunc(*pArgs, dict->size); + if (!v) { + PrintError("create argument %d:\n", i); + Py_DECREF(cnv); + goto Done; + } + PyTuple_SET_ITEM(arglist, i, v); + /* XXX XXX XX + We have the problem that c_byte or c_short have dict->size of + 1 resp. 4, but these parameters are pushed as sizeof(int) bytes. + BTW, the same problem occurrs when they are pushed as parameters + */ + } else if (dict) { + /* Hm, shouldn't we use PyCData_AtAddress() or something like that instead? */ + CDataObject *obj = (CDataObject *)PyObject_CallFunctionObjArgs(cnv, NULL); + if (!obj) { + PrintError("create argument %d:\n", i); + Py_DECREF(cnv); + goto Done; + } + if (!CDataObject_Check(obj)) { + Py_DECREF(obj); + Py_DECREF(cnv); + PrintError("unexpected result of create argument %d:\n", i); + goto Done; + } + memcpy(obj->b_ptr, *pArgs, dict->size); + PyTuple_SET_ITEM(arglist, i, (PyObject *)obj); #ifdef MS_WIN32 - TryAddRef(dict, obj); + TryAddRef(dict, obj); #endif - } else { - PyErr_SetString(PyExc_TypeError, - "cannot build parameter"); - PrintError("Parsing argument %d\n", i); - Py_DECREF(cnv); - goto Done; - } - Py_DECREF(cnv); - /* XXX error handling! */ - pArgs++; - } + } else { + PyErr_SetString(PyExc_TypeError, + "cannot build parameter"); + PrintError("Parsing argument %d\n", i); + Py_DECREF(cnv); + goto Done; + } + Py_DECREF(cnv); + /* XXX error handling! */ + pArgs++; + } #define CHECK(what, x) \ if (x == NULL) _ctypes_add_traceback(what, "_ctypes/callbacks.c", __LINE__ - 1), PyErr_Print() - if (flags & (FUNCFLAG_USE_ERRNO | FUNCFLAG_USE_LASTERROR)) { - error_object = _ctypes_get_errobj(&space); - if (error_object == NULL) - goto Done; - if (flags & FUNCFLAG_USE_ERRNO) { - int temp = space[0]; - space[0] = errno; - errno = temp; - } + if (flags & (FUNCFLAG_USE_ERRNO | FUNCFLAG_USE_LASTERROR)) { + error_object = _ctypes_get_errobj(&space); + if (error_object == NULL) + goto Done; + if (flags & FUNCFLAG_USE_ERRNO) { + int temp = space[0]; + space[0] = errno; + errno = temp; + } #ifdef MS_WIN32 - if (flags & FUNCFLAG_USE_LASTERROR) { - int temp = space[1]; - space[1] = GetLastError(); - SetLastError(temp); - } + if (flags & FUNCFLAG_USE_LASTERROR) { + int temp = space[1]; + space[1] = GetLastError(); + SetLastError(temp); + } #endif - } + } - result = PyObject_CallObject(callable, arglist); - CHECK("'calling callback function'", result); + result = PyObject_CallObject(callable, arglist); + CHECK("'calling callback function'", result); #ifdef MS_WIN32 - if (flags & FUNCFLAG_USE_LASTERROR) { - int temp = space[1]; - space[1] = GetLastError(); - SetLastError(temp); - } -#endif - if (flags & FUNCFLAG_USE_ERRNO) { - int temp = space[0]; - space[0] = errno; - errno = temp; - } - Py_XDECREF(error_object); - - if ((restype != &ffi_type_void) && result) { - PyObject *keep; - assert(setfunc); + if (flags & FUNCFLAG_USE_LASTERROR) { + int temp = space[1]; + space[1] = GetLastError(); + SetLastError(temp); + } +#endif + if (flags & FUNCFLAG_USE_ERRNO) { + int temp = space[0]; + space[0] = errno; + errno = temp; + } + Py_XDECREF(error_object); + + if ((restype != &ffi_type_void) && result) { + PyObject *keep; + assert(setfunc); #ifdef WORDS_BIGENDIAN - /* See the corresponding code in callproc.c, around line 961 */ - if (restype->type != FFI_TYPE_FLOAT && restype->size < sizeof(ffi_arg)) - mem = (char *)mem + sizeof(ffi_arg) - restype->size; -#endif - keep = setfunc(mem, result, 0); - CHECK("'converting callback result'", keep); - /* keep is an object we have to keep alive so that the result - stays valid. If there is no such object, the setfunc will - have returned Py_None. - - If there is such an object, we have no choice than to keep - it alive forever - but a refcount and/or memory leak will - be the result. EXCEPT when restype is py_object - Python - itself knows how to manage the refcount of these objects. - */ - if (keep == NULL) /* Could not convert callback result. */ - PyErr_WriteUnraisable(callable); - else if (keep == Py_None) /* Nothing to keep */ - Py_DECREF(keep); - else if (setfunc != _ctypes_get_fielddesc("O")->setfunc) { - if (-1 == PyErr_WarnEx(PyExc_RuntimeWarning, - "memory leak in callback function.", - 1)) - PyErr_WriteUnraisable(callable); - } - } - Py_XDECREF(result); + /* See the corresponding code in callproc.c, around line 961 */ + if (restype->type != FFI_TYPE_FLOAT && restype->size < sizeof(ffi_arg)) + mem = (char *)mem + sizeof(ffi_arg) - restype->size; +#endif + keep = setfunc(mem, result, 0); + CHECK("'converting callback result'", keep); + /* keep is an object we have to keep alive so that the result + stays valid. If there is no such object, the setfunc will + have returned Py_None. + + If there is such an object, we have no choice than to keep + it alive forever - but a refcount and/or memory leak will + be the result. EXCEPT when restype is py_object - Python + itself knows how to manage the refcount of these objects. + */ + if (keep == NULL) /* Could not convert callback result. */ + PyErr_WriteUnraisable(callable); + else if (keep == Py_None) /* Nothing to keep */ + Py_DECREF(keep); + else if (setfunc != _ctypes_get_fielddesc("O")->setfunc) { + if (-1 == PyErr_WarnEx(PyExc_RuntimeWarning, + "memory leak in callback function.", + 1)) + PyErr_WriteUnraisable(callable); + } + } + Py_XDECREF(result); Done: - Py_XDECREF(arglist); + Py_XDECREF(arglist); #ifdef WITH_THREAD - PyGILState_Release(state); + PyGILState_Release(state); #endif } static void closure_fcn(ffi_cif *cif, - void *resp, - void **args, - void *userdata) -{ - CThunkObject *p = (CThunkObject *)userdata; - - _CallPythonObject(resp, - p->ffi_restype, - p->setfunc, - p->callable, - p->converters, - p->flags, - args); + void *resp, + void **args, + void *userdata) +{ + CThunkObject *p = (CThunkObject *)userdata; + + _CallPythonObject(resp, + p->ffi_restype, + p->setfunc, + p->callable, + p->converters, + p->flags, + args); } static CThunkObject* CThunkObject_new(Py_ssize_t nArgs) { - CThunkObject *p; - int i; + CThunkObject *p; + int i; - p = PyObject_GC_NewVar(CThunkObject, &PyCThunk_Type, nArgs); - if (p == NULL) { - PyErr_NoMemory(); - return NULL; - } - - p->pcl = NULL; - memset(&p->cif, 0, sizeof(p->cif)); - p->converters = NULL; - p->callable = NULL; - p->setfunc = NULL; - p->ffi_restype = NULL; - - for (i = 0; i < nArgs + 1; ++i) - p->atypes[i] = NULL; - PyObject_GC_Track((PyObject *)p); - return p; + p = PyObject_GC_NewVar(CThunkObject, &PyCThunk_Type, nArgs); + if (p == NULL) { + PyErr_NoMemory(); + return NULL; + } + + p->pcl = NULL; + memset(&p->cif, 0, sizeof(p->cif)); + p->converters = NULL; + p->callable = NULL; + p->setfunc = NULL; + p->ffi_restype = NULL; + + for (i = 0; i < nArgs + 1; ++i) + p->atypes[i] = NULL; + PyObject_GC_Track((PyObject *)p); + return p; } CThunkObject *_ctypes_alloc_callback(PyObject *callable, - PyObject *converters, - PyObject *restype, - int flags) -{ - int result; - CThunkObject *p; - Py_ssize_t nArgs, i; - ffi_abi cc; - - nArgs = PySequence_Size(converters); - p = CThunkObject_new(nArgs); - if (p == NULL) - return NULL; - - assert(CThunk_CheckExact((PyObject *)p)); - - p->pcl = _ctypes_alloc_closure(); - if (p->pcl == NULL) { - PyErr_NoMemory(); - goto error; - } - - p->flags = flags; - for (i = 0; i < nArgs; ++i) { - PyObject *cnv = PySequence_GetItem(converters, i); - if (cnv == NULL) - goto error; - p->atypes[i] = _ctypes_get_ffi_type(cnv); - Py_DECREF(cnv); - } - p->atypes[i] = NULL; - - Py_INCREF(restype); - p->restype = restype; - if (restype == Py_None) { - p->setfunc = NULL; - p->ffi_restype = &ffi_type_void; - } else { - StgDictObject *dict = PyType_stgdict(restype); - if (dict == NULL || dict->setfunc == NULL) { - PyErr_SetString(PyExc_TypeError, - "invalid result type for callback function"); - goto error; - } - p->setfunc = dict->setfunc; - p->ffi_restype = &dict->ffi_type_pointer; - } + PyObject *converters, + PyObject *restype, + int flags) +{ + int result; + CThunkObject *p; + Py_ssize_t nArgs, i; + ffi_abi cc; + + nArgs = PySequence_Size(converters); + p = CThunkObject_new(nArgs); + if (p == NULL) + return NULL; + + assert(CThunk_CheckExact((PyObject *)p)); + + p->pcl = _ctypes_alloc_closure(); + if (p->pcl == NULL) { + PyErr_NoMemory(); + goto error; + } + + p->flags = flags; + for (i = 0; i < nArgs; ++i) { + PyObject *cnv = PySequence_GetItem(converters, i); + if (cnv == NULL) + goto error; + p->atypes[i] = _ctypes_get_ffi_type(cnv); + Py_DECREF(cnv); + } + p->atypes[i] = NULL; + + Py_INCREF(restype); + p->restype = restype; + if (restype == Py_None) { + p->setfunc = NULL; + p->ffi_restype = &ffi_type_void; + } else { + StgDictObject *dict = PyType_stgdict(restype); + if (dict == NULL || dict->setfunc == NULL) { + PyErr_SetString(PyExc_TypeError, + "invalid result type for callback function"); + goto error; + } + p->setfunc = dict->setfunc; + p->ffi_restype = &dict->ffi_type_pointer; + } - cc = FFI_DEFAULT_ABI; + cc = FFI_DEFAULT_ABI; #if defined(MS_WIN32) && !defined(_WIN32_WCE) && !defined(MS_WIN64) - if ((flags & FUNCFLAG_CDECL) == 0) - cc = FFI_STDCALL; + if ((flags & FUNCFLAG_CDECL) == 0) + cc = FFI_STDCALL; #endif - result = ffi_prep_cif(&p->cif, cc, - Py_SAFE_DOWNCAST(nArgs, Py_ssize_t, int), - _ctypes_get_ffi_type(restype), - &p->atypes[0]); - if (result != FFI_OK) { - PyErr_Format(PyExc_RuntimeError, - "ffi_prep_cif failed with %d", result); - goto error; - } - result = ffi_prep_closure(p->pcl, &p->cif, closure_fcn, p); - if (result != FFI_OK) { - PyErr_Format(PyExc_RuntimeError, - "ffi_prep_closure failed with %d", result); - goto error; - } - - Py_INCREF(converters); - p->converters = converters; - Py_INCREF(callable); - p->callable = callable; - return p; + result = ffi_prep_cif(&p->cif, cc, + Py_SAFE_DOWNCAST(nArgs, Py_ssize_t, int), + _ctypes_get_ffi_type(restype), + &p->atypes[0]); + if (result != FFI_OK) { + PyErr_Format(PyExc_RuntimeError, + "ffi_prep_cif failed with %d", result); + goto error; + } + result = ffi_prep_closure(p->pcl, &p->cif, closure_fcn, p); + if (result != FFI_OK) { + PyErr_Format(PyExc_RuntimeError, + "ffi_prep_closure failed with %d", result); + goto error; + } + + Py_INCREF(converters); + p->converters = converters; + Py_INCREF(callable); + p->callable = callable; + return p; error: - Py_XDECREF(p); - return NULL; + Py_XDECREF(p); + return NULL; } #ifdef MS_WIN32 static void LoadPython(void) { - if (!Py_IsInitialized()) { + if (!Py_IsInitialized()) { #ifdef WITH_THREAD - PyEval_InitThreads(); + PyEval_InitThreads(); #endif - Py_Initialize(); - } + Py_Initialize(); + } } /******************************************************************/ long Call_GetClassObject(REFCLSID rclsid, REFIID riid, LPVOID *ppv) { - PyObject *mod, *func, *result; - long retval; - static PyObject *context; - - if (context == NULL) - context = PyUnicode_InternFromString("_ctypes.DllGetClassObject"); - - mod = PyImport_ImportModuleNoBlock("ctypes"); - if (!mod) { - PyErr_WriteUnraisable(context ? context : Py_None); - /* There has been a warning before about this already */ - return E_FAIL; - } - - func = PyObject_GetAttrString(mod, "DllGetClassObject"); - Py_DECREF(mod); - if (!func) { - PyErr_WriteUnraisable(context ? context : Py_None); - return E_FAIL; - } - - { - PyObject *py_rclsid = PyLong_FromVoidPtr((void *)rclsid); - PyObject *py_riid = PyLong_FromVoidPtr((void *)riid); - PyObject *py_ppv = PyLong_FromVoidPtr(ppv); - if (!py_rclsid || !py_riid || !py_ppv) { - Py_XDECREF(py_rclsid); - Py_XDECREF(py_riid); - Py_XDECREF(py_ppv); - Py_DECREF(func); - PyErr_WriteUnraisable(context ? context : Py_None); - return E_FAIL; - } - result = PyObject_CallFunctionObjArgs(func, - py_rclsid, - py_riid, - py_ppv, - NULL); - Py_DECREF(py_rclsid); - Py_DECREF(py_riid); - Py_DECREF(py_ppv); - } - Py_DECREF(func); - if (!result) { - PyErr_WriteUnraisable(context ? context : Py_None); - return E_FAIL; - } - - retval = PyLong_AsLong(result); - if (PyErr_Occurred()) { - PyErr_WriteUnraisable(context ? context : Py_None); - retval = E_FAIL; - } - Py_DECREF(result); - return retval; + PyObject *mod, *func, *result; + long retval; + static PyObject *context; + + if (context == NULL) + context = PyUnicode_InternFromString("_ctypes.DllGetClassObject"); + + mod = PyImport_ImportModuleNoBlock("ctypes"); + if (!mod) { + PyErr_WriteUnraisable(context ? context : Py_None); + /* There has been a warning before about this already */ + return E_FAIL; + } + + func = PyObject_GetAttrString(mod, "DllGetClassObject"); + Py_DECREF(mod); + if (!func) { + PyErr_WriteUnraisable(context ? context : Py_None); + return E_FAIL; + } + + { + PyObject *py_rclsid = PyLong_FromVoidPtr((void *)rclsid); + PyObject *py_riid = PyLong_FromVoidPtr((void *)riid); + PyObject *py_ppv = PyLong_FromVoidPtr(ppv); + if (!py_rclsid || !py_riid || !py_ppv) { + Py_XDECREF(py_rclsid); + Py_XDECREF(py_riid); + Py_XDECREF(py_ppv); + Py_DECREF(func); + PyErr_WriteUnraisable(context ? context : Py_None); + return E_FAIL; + } + result = PyObject_CallFunctionObjArgs(func, + py_rclsid, + py_riid, + py_ppv, + NULL); + Py_DECREF(py_rclsid); + Py_DECREF(py_riid); + Py_DECREF(py_ppv); + } + Py_DECREF(func); + if (!result) { + PyErr_WriteUnraisable(context ? context : Py_None); + return E_FAIL; + } + + retval = PyLong_AsLong(result); + if (PyErr_Occurred()) { + PyErr_WriteUnraisable(context ? context : Py_None); + retval = E_FAIL; + } + Py_DECREF(result); + return retval; } STDAPI DllGetClassObject(REFCLSID rclsid, - REFIID riid, - LPVOID *ppv) + REFIID riid, + LPVOID *ppv) { - long result; + long result; #ifdef WITH_THREAD - PyGILState_STATE state; + PyGILState_STATE state; #endif - LoadPython(); + LoadPython(); #ifdef WITH_THREAD - state = PyGILState_Ensure(); + state = PyGILState_Ensure(); #endif - result = Call_GetClassObject(rclsid, riid, ppv); + result = Call_GetClassObject(rclsid, riid, ppv); #ifdef WITH_THREAD - PyGILState_Release(state); + PyGILState_Release(state); #endif - return result; + return result; } long Call_CanUnloadNow(void) { - PyObject *mod, *func, *result; - long retval; - static PyObject *context; - - if (context == NULL) - context = PyUnicode_InternFromString("_ctypes.DllCanUnloadNow"); - - mod = PyImport_ImportModuleNoBlock("ctypes"); - if (!mod) { -/* OutputDebugString("Could not import ctypes"); */ - /* We assume that this error can only occur when shutting - down, so we silently ignore it */ - PyErr_Clear(); - return E_FAIL; - } - /* Other errors cannot be raised, but are printed to stderr */ - func = PyObject_GetAttrString(mod, "DllCanUnloadNow"); - Py_DECREF(mod); - if (!func) { - PyErr_WriteUnraisable(context ? context : Py_None); - return E_FAIL; - } - - result = PyObject_CallFunction(func, NULL); - Py_DECREF(func); - if (!result) { - PyErr_WriteUnraisable(context ? context : Py_None); - return E_FAIL; - } - - retval = PyLong_AsLong(result); - if (PyErr_Occurred()) { - PyErr_WriteUnraisable(context ? context : Py_None); - retval = E_FAIL; - } - Py_DECREF(result); - return retval; + PyObject *mod, *func, *result; + long retval; + static PyObject *context; + + if (context == NULL) + context = PyUnicode_InternFromString("_ctypes.DllCanUnloadNow"); + + mod = PyImport_ImportModuleNoBlock("ctypes"); + if (!mod) { +/* OutputDebugString("Could not import ctypes"); */ + /* We assume that this error can only occur when shutting + down, so we silently ignore it */ + PyErr_Clear(); + return E_FAIL; + } + /* Other errors cannot be raised, but are printed to stderr */ + func = PyObject_GetAttrString(mod, "DllCanUnloadNow"); + Py_DECREF(mod); + if (!func) { + PyErr_WriteUnraisable(context ? context : Py_None); + return E_FAIL; + } + + result = PyObject_CallFunction(func, NULL); + Py_DECREF(func); + if (!result) { + PyErr_WriteUnraisable(context ? context : Py_None); + return E_FAIL; + } + + retval = PyLong_AsLong(result); + if (PyErr_Occurred()) { + PyErr_WriteUnraisable(context ? context : Py_None); + retval = E_FAIL; + } + Py_DECREF(result); + return retval; } /* @@ -604,26 +604,26 @@ STDAPI DllCanUnloadNow(void) { - long result; + long result; #ifdef WITH_THREAD - PyGILState_STATE state = PyGILState_Ensure(); + PyGILState_STATE state = PyGILState_Ensure(); #endif - result = Call_CanUnloadNow(); + result = Call_CanUnloadNow(); #ifdef WITH_THREAD - PyGILState_Release(state); + PyGILState_Release(state); #endif - return result; + return result; } #ifndef Py_NO_ENABLE_SHARED BOOL WINAPI DllMain(HINSTANCE hinstDLL, DWORD fdwReason, LPVOID lpvRes) { - switch(fdwReason) { - case DLL_PROCESS_ATTACH: - DisableThreadLibraryCalls(hinstDLL); - break; - } - return TRUE; + switch(fdwReason) { + case DLL_PROCESS_ATTACH: + DisableThreadLibraryCalls(hinstDLL); + break; + } + return TRUE; } #endif Modified: python/branches/release31-maint/Modules/_ctypes/callproc.c ============================================================================== --- python/branches/release31-maint/Modules/_ctypes/callproc.c (original) +++ python/branches/release31-maint/Modules/_ctypes/callproc.c Sun May 9 18:14:21 2010 @@ -4,9 +4,9 @@ */ /* * Related Work: - * - calldll http://www.nightmare.com/software.html - * - libffi http://sourceware.cygnus.com/libffi/ - * - ffcall http://clisp.cons.org/~haible/packages-ffcall.html + * - calldll http://www.nightmare.com/software.html + * - libffi http://sourceware.cygnus.com/libffi/ + * - ffcall http://clisp.cons.org/~haible/packages-ffcall.html * and, of course, Don Beaudry's MESS package, but this is more ctypes * related. */ @@ -82,17 +82,17 @@ static void pymem_destructor(PyObject *ptr) { - void *p = PyCapsule_GetPointer(ptr, CTYPES_CAPSULE_NAME_PYMEM); - if (p) { - PyMem_Free(p); - } + void *p = PyCapsule_GetPointer(ptr, CTYPES_CAPSULE_NAME_PYMEM); + if (p) { + PyMem_Free(p); + } } /* ctypes maintains thread-local storage that has space for two error numbers: private copies of the system 'errno' value and, on Windows, the system error code accessed by the GetLastError() and SetLastError() api functions. - + Foreign functions created with CDLL(..., use_errno=True), when called, swap the system 'errno' value with the private copy just before the actual function call, and swapped again immediately afterwards. The 'use_errno' @@ -125,88 +125,88 @@ PyObject * _ctypes_get_errobj(int **pspace) { - PyObject *dict = PyThreadState_GetDict(); - PyObject *errobj; - static PyObject *error_object_name; - if (dict == 0) { - PyErr_SetString(PyExc_RuntimeError, - "cannot get thread state"); - return NULL; - } - if (error_object_name == NULL) { - error_object_name = PyUnicode_InternFromString("ctypes.error_object"); - if (error_object_name == NULL) - return NULL; - } - errobj = PyDict_GetItem(dict, error_object_name); - if (errobj) { - if (!PyCapsule_IsValid(errobj, CTYPES_CAPSULE_NAME_PYMEM)) { - PyErr_SetString(PyExc_RuntimeError, - "ctypes.error_object is an invalid capsule"); - return NULL; - } - Py_INCREF(errobj); - } - else { - void *space = PyMem_Malloc(sizeof(int) * 2); - if (space == NULL) - return NULL; - memset(space, 0, sizeof(int) * 2); - errobj = PyCapsule_New(space, CTYPES_CAPSULE_NAME_PYMEM, pymem_destructor); - if (errobj == NULL) - return NULL; - if (-1 == PyDict_SetItem(dict, error_object_name, - errobj)) { - Py_DECREF(errobj); - return NULL; - } - } - *pspace = (int *)PyCapsule_GetPointer(errobj, CTYPES_CAPSULE_NAME_PYMEM); - return errobj; + PyObject *dict = PyThreadState_GetDict(); + PyObject *errobj; + static PyObject *error_object_name; + if (dict == 0) { + PyErr_SetString(PyExc_RuntimeError, + "cannot get thread state"); + return NULL; + } + if (error_object_name == NULL) { + error_object_name = PyUnicode_InternFromString("ctypes.error_object"); + if (error_object_name == NULL) + return NULL; + } + errobj = PyDict_GetItem(dict, error_object_name); + if (errobj) { + if (!PyCapsule_IsValid(errobj, CTYPES_CAPSULE_NAME_PYMEM)) { + PyErr_SetString(PyExc_RuntimeError, + "ctypes.error_object is an invalid capsule"); + return NULL; + } + Py_INCREF(errobj); + } + else { + void *space = PyMem_Malloc(sizeof(int) * 2); + if (space == NULL) + return NULL; + memset(space, 0, sizeof(int) * 2); + errobj = PyCapsule_New(space, CTYPES_CAPSULE_NAME_PYMEM, pymem_destructor); + if (errobj == NULL) + return NULL; + if (-1 == PyDict_SetItem(dict, error_object_name, + errobj)) { + Py_DECREF(errobj); + return NULL; + } + } + *pspace = (int *)PyCapsule_GetPointer(errobj, CTYPES_CAPSULE_NAME_PYMEM); + return errobj; } static PyObject * get_error_internal(PyObject *self, PyObject *args, int index) { - int *space; - PyObject *errobj = _ctypes_get_errobj(&space); - PyObject *result; - - if (errobj == NULL) - return NULL; - result = PyLong_FromLong(space[index]); - Py_DECREF(errobj); - return result; + int *space; + PyObject *errobj = _ctypes_get_errobj(&space); + PyObject *result; + + if (errobj == NULL) + return NULL; + result = PyLong_FromLong(space[index]); + Py_DECREF(errobj); + return result; } static PyObject * set_error_internal(PyObject *self, PyObject *args, int index) { - int new_errno, old_errno; - PyObject *errobj; - int *space; - - if (!PyArg_ParseTuple(args, "i", &new_errno)) - return NULL; - errobj = _ctypes_get_errobj(&space); - if (errobj == NULL) - return NULL; - old_errno = space[index]; - space[index] = new_errno; - Py_DECREF(errobj); - return PyLong_FromLong(old_errno); + int new_errno, old_errno; + PyObject *errobj; + int *space; + + if (!PyArg_ParseTuple(args, "i", &new_errno)) + return NULL; + errobj = _ctypes_get_errobj(&space); + if (errobj == NULL) + return NULL; + old_errno = space[index]; + space[index] = new_errno; + Py_DECREF(errobj); + return PyLong_FromLong(old_errno); } static PyObject * get_errno(PyObject *self, PyObject *args) { - return get_error_internal(self, args, 0); + return get_error_internal(self, args, 0); } static PyObject * set_errno(PyObject *self, PyObject *args) { - return set_error_internal(self, args, 0); + return set_error_internal(self, args, 0); } #ifdef MS_WIN32 @@ -214,202 +214,202 @@ static PyObject * get_last_error(PyObject *self, PyObject *args) { - return get_error_internal(self, args, 1); + return get_error_internal(self, args, 1); } static PyObject * set_last_error(PyObject *self, PyObject *args) { - return set_error_internal(self, args, 1); + return set_error_internal(self, args, 1); } PyObject *ComError; static WCHAR *FormatError(DWORD code) { - WCHAR *lpMsgBuf; - DWORD n; - n = FormatMessageW(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM, - NULL, - code, - MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), /* Default language */ - (LPWSTR) &lpMsgBuf, - 0, - NULL); - if (n) { - while (iswspace(lpMsgBuf[n-1])) - --n; - lpMsgBuf[n] = L'\0'; /* rstrip() */ - } - return lpMsgBuf; + WCHAR *lpMsgBuf; + DWORD n; + n = FormatMessageW(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM, + NULL, + code, + MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), /* Default language */ + (LPWSTR) &lpMsgBuf, + 0, + NULL); + if (n) { + while (iswspace(lpMsgBuf[n-1])) + --n; + lpMsgBuf[n] = L'\0'; /* rstrip() */ + } + return lpMsgBuf; } #ifndef DONT_USE_SEH static void SetException(DWORD code, EXCEPTION_RECORD *pr) { - /* The 'code' is a normal win32 error code so it could be handled by - PyErr_SetFromWindowsErr(). However, for some errors, we have additional - information not included in the error code. We handle those here and - delegate all others to the generic function. */ - switch (code) { - case EXCEPTION_ACCESS_VIOLATION: - /* The thread attempted to read from or write - to a virtual address for which it does not - have the appropriate access. */ - if (pr->ExceptionInformation[0] == 0) - PyErr_Format(PyExc_WindowsError, - "exception: access violation reading %p", - pr->ExceptionInformation[1]); - else - PyErr_Format(PyExc_WindowsError, - "exception: access violation writing %p", - pr->ExceptionInformation[1]); - break; - - case EXCEPTION_BREAKPOINT: - /* A breakpoint was encountered. */ - PyErr_SetString(PyExc_WindowsError, - "exception: breakpoint encountered"); - break; - - case EXCEPTION_DATATYPE_MISALIGNMENT: - /* The thread attempted to read or write data that is - misaligned on hardware that does not provide - alignment. For example, 16-bit values must be - aligned on 2-byte boundaries, 32-bit values on - 4-byte boundaries, and so on. */ - PyErr_SetString(PyExc_WindowsError, - "exception: datatype misalignment"); - break; - - case EXCEPTION_SINGLE_STEP: - /* A trace trap or other single-instruction mechanism - signaled that one instruction has been executed. */ - PyErr_SetString(PyExc_WindowsError, - "exception: single step"); - break; - - case EXCEPTION_ARRAY_BOUNDS_EXCEEDED: - /* The thread attempted to access an array element - that is out of bounds, and the underlying hardware - supports bounds checking. */ - PyErr_SetString(PyExc_WindowsError, - "exception: array bounds exceeded"); - break; - - case EXCEPTION_FLT_DENORMAL_OPERAND: - /* One of the operands in a floating-point operation - is denormal. A denormal value is one that is too - small to represent as a standard floating-point - value. */ - PyErr_SetString(PyExc_WindowsError, - "exception: floating-point operand denormal"); - break; - - case EXCEPTION_FLT_DIVIDE_BY_ZERO: - /* The thread attempted to divide a floating-point - value by a floating-point divisor of zero. */ - PyErr_SetString(PyExc_WindowsError, - "exception: float divide by zero"); - break; - - case EXCEPTION_FLT_INEXACT_RESULT: - /* The result of a floating-point operation cannot be - represented exactly as a decimal fraction. */ - PyErr_SetString(PyExc_WindowsError, - "exception: float inexact"); - break; - - case EXCEPTION_FLT_INVALID_OPERATION: - /* This exception represents any floating-point - exception not included in this list. */ - PyErr_SetString(PyExc_WindowsError, - "exception: float invalid operation"); - break; - - case EXCEPTION_FLT_OVERFLOW: - /* The exponent of a floating-point operation is - greater than the magnitude allowed by the - corresponding type. */ - PyErr_SetString(PyExc_WindowsError, - "exception: float overflow"); - break; - - case EXCEPTION_FLT_STACK_CHECK: - /* The stack overflowed or underflowed as the result - of a floating-point operation. */ - PyErr_SetString(PyExc_WindowsError, - "exception: stack over/underflow"); - break; - - case EXCEPTION_STACK_OVERFLOW: - /* The stack overflowed or underflowed as the result - of a floating-point operation. */ - PyErr_SetString(PyExc_WindowsError, - "exception: stack overflow"); - break; - - case EXCEPTION_FLT_UNDERFLOW: - /* The exponent of a floating-point operation is less - than the magnitude allowed by the corresponding - type. */ - PyErr_SetString(PyExc_WindowsError, - "exception: float underflow"); - break; - - case EXCEPTION_INT_DIVIDE_BY_ZERO: - /* The thread attempted to divide an integer value by - an integer divisor of zero. */ - PyErr_SetString(PyExc_WindowsError, - "exception: integer divide by zero"); - break; - - case EXCEPTION_INT_OVERFLOW: - /* The result of an integer operation caused a carry - out of the most significant bit of the result. */ - PyErr_SetString(PyExc_WindowsError, - "exception: integer overflow"); - break; - - case EXCEPTION_PRIV_INSTRUCTION: - /* The thread attempted to execute an instruction - whose operation is not allowed in the current - machine mode. */ - PyErr_SetString(PyExc_WindowsError, - "exception: priviledged instruction"); - break; - - case EXCEPTION_NONCONTINUABLE_EXCEPTION: - /* The thread attempted to continue execution after a - noncontinuable exception occurred. */ - PyErr_SetString(PyExc_WindowsError, - "exception: nocontinuable"); - break; - - default: - PyErr_SetFromWindowsErr(code); - break; - } + /* The 'code' is a normal win32 error code so it could be handled by + PyErr_SetFromWindowsErr(). However, for some errors, we have additional + information not included in the error code. We handle those here and + delegate all others to the generic function. */ + switch (code) { + case EXCEPTION_ACCESS_VIOLATION: + /* The thread attempted to read from or write + to a virtual address for which it does not + have the appropriate access. */ + if (pr->ExceptionInformation[0] == 0) + PyErr_Format(PyExc_WindowsError, + "exception: access violation reading %p", + pr->ExceptionInformation[1]); + else + PyErr_Format(PyExc_WindowsError, + "exception: access violation writing %p", + pr->ExceptionInformation[1]); + break; + + case EXCEPTION_BREAKPOINT: + /* A breakpoint was encountered. */ + PyErr_SetString(PyExc_WindowsError, + "exception: breakpoint encountered"); + break; + + case EXCEPTION_DATATYPE_MISALIGNMENT: + /* The thread attempted to read or write data that is + misaligned on hardware that does not provide + alignment. For example, 16-bit values must be + aligned on 2-byte boundaries, 32-bit values on + 4-byte boundaries, and so on. */ + PyErr_SetString(PyExc_WindowsError, + "exception: datatype misalignment"); + break; + + case EXCEPTION_SINGLE_STEP: + /* A trace trap or other single-instruction mechanism + signaled that one instruction has been executed. */ + PyErr_SetString(PyExc_WindowsError, + "exception: single step"); + break; + + case EXCEPTION_ARRAY_BOUNDS_EXCEEDED: + /* The thread attempted to access an array element + that is out of bounds, and the underlying hardware + supports bounds checking. */ + PyErr_SetString(PyExc_WindowsError, + "exception: array bounds exceeded"); + break; + + case EXCEPTION_FLT_DENORMAL_OPERAND: + /* One of the operands in a floating-point operation + is denormal. A denormal value is one that is too + small to represent as a standard floating-point + value. */ + PyErr_SetString(PyExc_WindowsError, + "exception: floating-point operand denormal"); + break; + + case EXCEPTION_FLT_DIVIDE_BY_ZERO: + /* The thread attempted to divide a floating-point + value by a floating-point divisor of zero. */ + PyErr_SetString(PyExc_WindowsError, + "exception: float divide by zero"); + break; + + case EXCEPTION_FLT_INEXACT_RESULT: + /* The result of a floating-point operation cannot be + represented exactly as a decimal fraction. */ + PyErr_SetString(PyExc_WindowsError, + "exception: float inexact"); + break; + + case EXCEPTION_FLT_INVALID_OPERATION: + /* This exception represents any floating-point + exception not included in this list. */ + PyErr_SetString(PyExc_WindowsError, + "exception: float invalid operation"); + break; + + case EXCEPTION_FLT_OVERFLOW: + /* The exponent of a floating-point operation is + greater than the magnitude allowed by the + corresponding type. */ + PyErr_SetString(PyExc_WindowsError, + "exception: float overflow"); + break; + + case EXCEPTION_FLT_STACK_CHECK: + /* The stack overflowed or underflowed as the result + of a floating-point operation. */ + PyErr_SetString(PyExc_WindowsError, + "exception: stack over/underflow"); + break; + + case EXCEPTION_STACK_OVERFLOW: + /* The stack overflowed or underflowed as the result + of a floating-point operation. */ + PyErr_SetString(PyExc_WindowsError, + "exception: stack overflow"); + break; + + case EXCEPTION_FLT_UNDERFLOW: + /* The exponent of a floating-point operation is less + than the magnitude allowed by the corresponding + type. */ + PyErr_SetString(PyExc_WindowsError, + "exception: float underflow"); + break; + + case EXCEPTION_INT_DIVIDE_BY_ZERO: + /* The thread attempted to divide an integer value by + an integer divisor of zero. */ + PyErr_SetString(PyExc_WindowsError, + "exception: integer divide by zero"); + break; + + case EXCEPTION_INT_OVERFLOW: + /* The result of an integer operation caused a carry + out of the most significant bit of the result. */ + PyErr_SetString(PyExc_WindowsError, + "exception: integer overflow"); + break; + + case EXCEPTION_PRIV_INSTRUCTION: + /* The thread attempted to execute an instruction + whose operation is not allowed in the current + machine mode. */ + PyErr_SetString(PyExc_WindowsError, + "exception: priviledged instruction"); + break; + + case EXCEPTION_NONCONTINUABLE_EXCEPTION: + /* The thread attempted to continue execution after a + noncontinuable exception occurred. */ + PyErr_SetString(PyExc_WindowsError, + "exception: nocontinuable"); + break; + + default: + PyErr_SetFromWindowsErr(code); + break; + } } static DWORD HandleException(EXCEPTION_POINTERS *ptrs, - DWORD *pdw, EXCEPTION_RECORD *record) + DWORD *pdw, EXCEPTION_RECORD *record) { - *pdw = ptrs->ExceptionRecord->ExceptionCode; - *record = *ptrs->ExceptionRecord; - return EXCEPTION_EXECUTE_HANDLER; + *pdw = ptrs->ExceptionRecord->ExceptionCode; + *record = *ptrs->ExceptionRecord; + return EXCEPTION_EXECUTE_HANDLER; } #endif static PyObject * check_hresult(PyObject *self, PyObject *args) { - HRESULT hr; - if (!PyArg_ParseTuple(args, "i", &hr)) - return NULL; - if (FAILED(hr)) - return PyErr_SetFromWindowsErr(hr); - return PyLong_FromLong(hr); + HRESULT hr; + if (!PyArg_ParseTuple(args, "i", &hr)) + return NULL; + if (FAILED(hr)) + return PyErr_SetFromWindowsErr(hr); + return PyLong_FromLong(hr); } #endif @@ -419,132 +419,132 @@ PyCArgObject * PyCArgObject_new(void) { - PyCArgObject *p; - p = PyObject_New(PyCArgObject, &PyCArg_Type); - if (p == NULL) - return NULL; - p->pffi_type = NULL; - p->tag = '\0'; - p->obj = NULL; - memset(&p->value, 0, sizeof(p->value)); - return p; + PyCArgObject *p; + p = PyObject_New(PyCArgObject, &PyCArg_Type); + if (p == NULL) + return NULL; + p->pffi_type = NULL; + p->tag = '\0'; + p->obj = NULL; + memset(&p->value, 0, sizeof(p->value)); + return p; } static void PyCArg_dealloc(PyCArgObject *self) { - Py_XDECREF(self->obj); - PyObject_Del(self); + Py_XDECREF(self->obj); + PyObject_Del(self); } static PyObject * PyCArg_repr(PyCArgObject *self) { - char buffer[256]; - switch(self->tag) { - case 'b': - case 'B': - sprintf(buffer, "", - self->tag, self->value.b); - break; - case 'h': - case 'H': - sprintf(buffer, "", - self->tag, self->value.h); - break; - case 'i': - case 'I': - sprintf(buffer, "", - self->tag, self->value.i); - break; - case 'l': - case 'L': - sprintf(buffer, "", - self->tag, self->value.l); - break; - + char buffer[256]; + switch(self->tag) { + case 'b': + case 'B': + sprintf(buffer, "", + self->tag, self->value.b); + break; + case 'h': + case 'H': + sprintf(buffer, "", + self->tag, self->value.h); + break; + case 'i': + case 'I': + sprintf(buffer, "", + self->tag, self->value.i); + break; + case 'l': + case 'L': + sprintf(buffer, "", + self->tag, self->value.l); + break; + #ifdef HAVE_LONG_LONG - case 'q': - case 'Q': - sprintf(buffer, + case 'q': + case 'Q': + sprintf(buffer, #ifdef MS_WIN32 - "", + "", #else - "", + "", #endif - self->tag, self->value.q); - break; + self->tag, self->value.q); + break; #endif - case 'd': - sprintf(buffer, "", - self->tag, self->value.d); - break; - case 'f': - sprintf(buffer, "", - self->tag, self->value.f); - break; - - case 'c': - sprintf(buffer, "", - self->tag, self->value.c); - break; + case 'd': + sprintf(buffer, "", + self->tag, self->value.d); + break; + case 'f': + sprintf(buffer, "", + self->tag, self->value.f); + break; + + case 'c': + sprintf(buffer, "", + self->tag, self->value.c); + break; /* Hm, are these 'z' and 'Z' codes useful at all? Shouldn't they be replaced by the functionality of c_string and c_wstring ? */ - case 'z': - case 'Z': - case 'P': - sprintf(buffer, "", - self->tag, self->value.p); - break; - - default: - sprintf(buffer, "", - self->tag, self); - break; - } - return PyUnicode_FromString(buffer); + case 'z': + case 'Z': + case 'P': + sprintf(buffer, "", + self->tag, self->value.p); + break; + + default: + sprintf(buffer, "", + self->tag, self); + break; + } + return PyUnicode_FromString(buffer); } static PyMemberDef PyCArgType_members[] = { - { "_obj", T_OBJECT, - offsetof(PyCArgObject, obj), READONLY, - "the wrapped object" }, - { NULL }, + { "_obj", T_OBJECT, + offsetof(PyCArgObject, obj), READONLY, + "the wrapped object" }, + { NULL }, }; PyTypeObject PyCArg_Type = { - PyVarObject_HEAD_INIT(NULL, 0) - "CArgObject", - sizeof(PyCArgObject), - 0, - (destructor)PyCArg_dealloc, /* tp_dealloc */ - 0, /* tp_print */ - 0, /* tp_getattr */ - 0, /* tp_setattr */ - 0, /* tp_reserved */ - (reprfunc)PyCArg_repr, /* tp_repr */ - 0, /* tp_as_number */ - 0, /* tp_as_sequence */ - 0, /* tp_as_mapping */ - 0, /* tp_hash */ - 0, /* tp_call */ - 0, /* tp_str */ - 0, /* tp_getattro */ - 0, /* tp_setattro */ - 0, /* tp_as_buffer */ - Py_TPFLAGS_DEFAULT, /* tp_flags */ - 0, /* tp_doc */ - 0, /* tp_traverse */ - 0, /* tp_clear */ - 0, /* tp_richcompare */ - 0, /* tp_weaklistoffset */ - 0, /* tp_iter */ - 0, /* tp_iternext */ - 0, /* tp_methods */ - PyCArgType_members, /* tp_members */ + PyVarObject_HEAD_INIT(NULL, 0) + "CArgObject", + sizeof(PyCArgObject), + 0, + (destructor)PyCArg_dealloc, /* tp_dealloc */ + 0, /* tp_print */ + 0, /* tp_getattr */ + 0, /* tp_setattr */ + 0, /* tp_reserved */ + (reprfunc)PyCArg_repr, /* tp_repr */ + 0, /* tp_as_number */ + 0, /* tp_as_sequence */ + 0, /* tp_as_mapping */ + 0, /* tp_hash */ + 0, /* tp_call */ + 0, /* tp_str */ + 0, /* tp_getattro */ + 0, /* tp_setattro */ + 0, /* tp_as_buffer */ + Py_TPFLAGS_DEFAULT, /* tp_flags */ + 0, /* tp_doc */ + 0, /* tp_traverse */ + 0, /* tp_clear */ + 0, /* tp_richcompare */ + 0, /* tp_weaklistoffset */ + 0, /* tp_iter */ + 0, /* tp_iternext */ + 0, /* tp_methods */ + PyCArgType_members, /* tp_members */ }; /****************************************************************/ @@ -577,24 +577,24 @@ */ union result { - char c; - char b; - short h; - int i; - long l; + char c; + char b; + short h; + int i; + long l; #ifdef HAVE_LONG_LONG - PY_LONG_LONG q; + PY_LONG_LONG q; #endif - long double D; - double d; - float f; - void *p; + long double D; + double d; + float f; + void *p; }; struct argument { - ffi_type *ffi_type; - PyObject *keep; - union result value; + ffi_type *ffi_type; + PyObject *keep; + union result value; }; /* @@ -602,134 +602,134 @@ */ static int ConvParam(PyObject *obj, Py_ssize_t index, struct argument *pa) { - StgDictObject *dict; - pa->keep = NULL; /* so we cannot forget it later */ + StgDictObject *dict; + pa->keep = NULL; /* so we cannot forget it later */ - dict = PyObject_stgdict(obj); - if (dict) { - PyCArgObject *carg; - assert(dict->paramfunc); - /* If it has an stgdict, it is a CDataObject */ - carg = dict->paramfunc((CDataObject *)obj); - pa->ffi_type = carg->pffi_type; - memcpy(&pa->value, &carg->value, sizeof(pa->value)); - pa->keep = (PyObject *)carg; - return 0; - } - - if (PyCArg_CheckExact(obj)) { - PyCArgObject *carg = (PyCArgObject *)obj; - pa->ffi_type = carg->pffi_type; - Py_INCREF(obj); - pa->keep = obj; - memcpy(&pa->value, &carg->value, sizeof(pa->value)); - return 0; - } - - /* check for None, integer, string or unicode and use directly if successful */ - if (obj == Py_None) { - pa->ffi_type = &ffi_type_pointer; - pa->value.p = NULL; - return 0; - } - - if (PyLong_Check(obj)) { - pa->ffi_type = &ffi_type_sint; - pa->value.i = (long)PyLong_AsUnsignedLong(obj); - if (pa->value.i == -1 && PyErr_Occurred()) { - PyErr_Clear(); - pa->value.i = PyLong_AsLong(obj); - if (pa->value.i == -1 && PyErr_Occurred()) { - PyErr_SetString(PyExc_OverflowError, - "long int too long to convert"); - return -1; - } - } - return 0; - } - - if (PyBytes_Check(obj)) { - pa->ffi_type = &ffi_type_pointer; - pa->value.p = PyBytes_AsString(obj); - Py_INCREF(obj); - pa->keep = obj; - return 0; - } + dict = PyObject_stgdict(obj); + if (dict) { + PyCArgObject *carg; + assert(dict->paramfunc); + /* If it has an stgdict, it is a CDataObject */ + carg = dict->paramfunc((CDataObject *)obj); + pa->ffi_type = carg->pffi_type; + memcpy(&pa->value, &carg->value, sizeof(pa->value)); + pa->keep = (PyObject *)carg; + return 0; + } + + if (PyCArg_CheckExact(obj)) { + PyCArgObject *carg = (PyCArgObject *)obj; + pa->ffi_type = carg->pffi_type; + Py_INCREF(obj); + pa->keep = obj; + memcpy(&pa->value, &carg->value, sizeof(pa->value)); + return 0; + } + + /* check for None, integer, string or unicode and use directly if successful */ + if (obj == Py_None) { + pa->ffi_type = &ffi_type_pointer; + pa->value.p = NULL; + return 0; + } + + if (PyLong_Check(obj)) { + pa->ffi_type = &ffi_type_sint; + pa->value.i = (long)PyLong_AsUnsignedLong(obj); + if (pa->value.i == -1 && PyErr_Occurred()) { + PyErr_Clear(); + pa->value.i = PyLong_AsLong(obj); + if (pa->value.i == -1 && PyErr_Occurred()) { + PyErr_SetString(PyExc_OverflowError, + "long int too long to convert"); + return -1; + } + } + return 0; + } + + if (PyBytes_Check(obj)) { + pa->ffi_type = &ffi_type_pointer; + pa->value.p = PyBytes_AsString(obj); + Py_INCREF(obj); + pa->keep = obj; + return 0; + } #ifdef CTYPES_UNICODE - if (PyUnicode_Check(obj)) { + if (PyUnicode_Check(obj)) { #ifdef HAVE_USABLE_WCHAR_T - pa->ffi_type = &ffi_type_pointer; - pa->value.p = PyUnicode_AS_UNICODE(obj); - Py_INCREF(obj); - pa->keep = obj; - return 0; + pa->ffi_type = &ffi_type_pointer; + pa->value.p = PyUnicode_AS_UNICODE(obj); + Py_INCREF(obj); + pa->keep = obj; + return 0; #else - int size = PyUnicode_GET_SIZE(obj); - pa->ffi_type = &ffi_type_pointer; - size += 1; /* terminating NUL */ - size *= sizeof(wchar_t); - pa->value.p = PyMem_Malloc(size); - if (!pa->value.p) { - PyErr_NoMemory(); - return -1; - } - memset(pa->value.p, 0, size); - pa->keep = PyCapsule_New(pa->value.p, CTYPES_CAPSULE_NAME_PYMEM, pymem_destructor); - if (!pa->keep) { - PyMem_Free(pa->value.p); - return -1; - } - if (-1 == PyUnicode_AsWideChar((PyUnicodeObject *)obj, - pa->value.p, PyUnicode_GET_SIZE(obj))) - return -1; - return 0; -#endif - } -#endif - - { - PyObject *arg; - arg = PyObject_GetAttrString(obj, "_as_parameter_"); - /* Which types should we exactly allow here? - integers are required for using Python classes - as parameters (they have to expose the '_as_parameter_' - attribute) - */ - if (arg) { - int result; - result = ConvParam(arg, index, pa); - Py_DECREF(arg); - return result; - } - PyErr_Format(PyExc_TypeError, - "Don't know how to convert parameter %d", - Py_SAFE_DOWNCAST(index, Py_ssize_t, int)); - return -1; - } + int size = PyUnicode_GET_SIZE(obj); + pa->ffi_type = &ffi_type_pointer; + size += 1; /* terminating NUL */ + size *= sizeof(wchar_t); + pa->value.p = PyMem_Malloc(size); + if (!pa->value.p) { + PyErr_NoMemory(); + return -1; + } + memset(pa->value.p, 0, size); + pa->keep = PyCapsule_New(pa->value.p, CTYPES_CAPSULE_NAME_PYMEM, pymem_destructor); + if (!pa->keep) { + PyMem_Free(pa->value.p); + return -1; + } + if (-1 == PyUnicode_AsWideChar((PyUnicodeObject *)obj, + pa->value.p, PyUnicode_GET_SIZE(obj))) + return -1; + return 0; +#endif + } +#endif + + { + PyObject *arg; + arg = PyObject_GetAttrString(obj, "_as_parameter_"); + /* Which types should we exactly allow here? + integers are required for using Python classes + as parameters (they have to expose the '_as_parameter_' + attribute) + */ + if (arg) { + int result; + result = ConvParam(arg, index, pa); + Py_DECREF(arg); + return result; + } + PyErr_Format(PyExc_TypeError, + "Don't know how to convert parameter %d", + Py_SAFE_DOWNCAST(index, Py_ssize_t, int)); + return -1; + } } ffi_type *_ctypes_get_ffi_type(PyObject *obj) { - StgDictObject *dict; - if (obj == NULL) - return &ffi_type_sint; - dict = PyType_stgdict(obj); - if (dict == NULL) - return &ffi_type_sint; + StgDictObject *dict; + if (obj == NULL) + return &ffi_type_sint; + dict = PyType_stgdict(obj); + if (dict == NULL) + return &ffi_type_sint; #if defined(MS_WIN32) && !defined(_WIN32_WCE) - /* This little trick works correctly with MSVC. - It returns small structures in registers - */ - if (dict->ffi_type_pointer.type == FFI_TYPE_STRUCT) { - if (dict->ffi_type_pointer.size <= 4) - return &ffi_type_sint32; - else if (dict->ffi_type_pointer.size <= 8) - return &ffi_type_sint64; - } + /* This little trick works correctly with MSVC. + It returns small structures in registers + */ + if (dict->ffi_type_pointer.type == FFI_TYPE_STRUCT) { + if (dict->ffi_type_pointer.size <= 4) + return &ffi_type_sint32; + else if (dict->ffi_type_pointer.size <= 8) + return &ffi_type_sint64; + } #endif - return &dict->ffi_type_pointer; + return &dict->ffi_type_pointer; } @@ -737,7 +737,7 @@ * libffi uses: * * ffi_status ffi_prep_cif(ffi_cif *cif, ffi_abi abi, - * unsigned int nargs, + * unsigned int nargs, * ffi_type *rtype, * ffi_type **atypes); * @@ -746,139 +746,139 @@ * void ffi_call(ffi_cif *cif, void *fn, void *rvalue, void **avalues); */ static int _call_function_pointer(int flags, - PPROC pProc, - void **avalues, - ffi_type **atypes, - ffi_type *restype, - void *resmem, - int argcount) + PPROC pProc, + void **avalues, + ffi_type **atypes, + ffi_type *restype, + void *resmem, + int argcount) { #ifdef WITH_THREAD - PyThreadState *_save = NULL; /* For Py_BLOCK_THREADS and Py_UNBLOCK_THREADS */ + PyThreadState *_save = NULL; /* For Py_BLOCK_THREADS and Py_UNBLOCK_THREADS */ #endif - PyObject *error_object = NULL; - int *space; - ffi_cif cif; - int cc; + PyObject *error_object = NULL; + int *space; + ffi_cif cif; + int cc; #ifdef MS_WIN32 - int delta; + int delta; #ifndef DONT_USE_SEH - DWORD dwExceptionCode = 0; - EXCEPTION_RECORD record; + DWORD dwExceptionCode = 0; + EXCEPTION_RECORD record; #endif #endif - /* XXX check before here */ - if (restype == NULL) { - PyErr_SetString(PyExc_RuntimeError, - "No ffi_type for result"); - return -1; - } - - cc = FFI_DEFAULT_ABI; + /* XXX check before here */ + if (restype == NULL) { + PyErr_SetString(PyExc_RuntimeError, + "No ffi_type for result"); + return -1; + } + + cc = FFI_DEFAULT_ABI; #if defined(MS_WIN32) && !defined(MS_WIN64) && !defined(_WIN32_WCE) - if ((flags & FUNCFLAG_CDECL) == 0) - cc = FFI_STDCALL; + if ((flags & FUNCFLAG_CDECL) == 0) + cc = FFI_STDCALL; #endif - if (FFI_OK != ffi_prep_cif(&cif, - cc, - argcount, - restype, - atypes)) { - PyErr_SetString(PyExc_RuntimeError, - "ffi_prep_cif failed"); - return -1; - } - - if (flags & (FUNCFLAG_USE_ERRNO | FUNCFLAG_USE_LASTERROR)) { - error_object = _ctypes_get_errobj(&space); - if (error_object == NULL) - return -1; - } + if (FFI_OK != ffi_prep_cif(&cif, + cc, + argcount, + restype, + atypes)) { + PyErr_SetString(PyExc_RuntimeError, + "ffi_prep_cif failed"); + return -1; + } + + if (flags & (FUNCFLAG_USE_ERRNO | FUNCFLAG_USE_LASTERROR)) { + error_object = _ctypes_get_errobj(&space); + if (error_object == NULL) + return -1; + } #ifdef WITH_THREAD - if ((flags & FUNCFLAG_PYTHONAPI) == 0) - Py_UNBLOCK_THREADS + if ((flags & FUNCFLAG_PYTHONAPI) == 0) + Py_UNBLOCK_THREADS #endif - if (flags & FUNCFLAG_USE_ERRNO) { - int temp = space[0]; - space[0] = errno; - errno = temp; - } + if (flags & FUNCFLAG_USE_ERRNO) { + int temp = space[0]; + space[0] = errno; + errno = temp; + } #ifdef MS_WIN32 - if (flags & FUNCFLAG_USE_LASTERROR) { - int temp = space[1]; - space[1] = GetLastError(); - SetLastError(temp); - } + if (flags & FUNCFLAG_USE_LASTERROR) { + int temp = space[1]; + space[1] = GetLastError(); + SetLastError(temp); + } #ifndef DONT_USE_SEH - __try { + __try { #endif - delta = + delta = #endif - ffi_call(&cif, (void *)pProc, resmem, avalues); + ffi_call(&cif, (void *)pProc, resmem, avalues); #ifdef MS_WIN32 #ifndef DONT_USE_SEH - } - __except (HandleException(GetExceptionInformation(), - &dwExceptionCode, &record)) { - ; - } -#endif - if (flags & FUNCFLAG_USE_LASTERROR) { - int temp = space[1]; - space[1] = GetLastError(); - SetLastError(temp); - } -#endif - if (flags & FUNCFLAG_USE_ERRNO) { - int temp = space[0]; - space[0] = errno; - errno = temp; - } - Py_XDECREF(error_object); + } + __except (HandleException(GetExceptionInformation(), + &dwExceptionCode, &record)) { + ; + } +#endif + if (flags & FUNCFLAG_USE_LASTERROR) { + int temp = space[1]; + space[1] = GetLastError(); + SetLastError(temp); + } +#endif + if (flags & FUNCFLAG_USE_ERRNO) { + int temp = space[0]; + space[0] = errno; + errno = temp; + } + Py_XDECREF(error_object); #ifdef WITH_THREAD - if ((flags & FUNCFLAG_PYTHONAPI) == 0) - Py_BLOCK_THREADS + if ((flags & FUNCFLAG_PYTHONAPI) == 0) + Py_BLOCK_THREADS #endif #ifdef MS_WIN32 #ifndef DONT_USE_SEH - if (dwExceptionCode) { - SetException(dwExceptionCode, &record); - return -1; - } + if (dwExceptionCode) { + SetException(dwExceptionCode, &record); + return -1; + } #endif #ifdef MS_WIN64 - if (delta != 0) { - PyErr_Format(PyExc_RuntimeError, - "ffi_call failed with code %d", - delta); - return -1; - } + if (delta != 0) { + PyErr_Format(PyExc_RuntimeError, + "ffi_call failed with code %d", + delta); + return -1; + } #else - if (delta < 0) { - if (flags & FUNCFLAG_CDECL) - PyErr_Format(PyExc_ValueError, - "Procedure called with not enough " - "arguments (%d bytes missing) " - "or wrong calling convention", - -delta); - else - PyErr_Format(PyExc_ValueError, - "Procedure probably called with not enough " - "arguments (%d bytes missing)", - -delta); - return -1; - } else if (delta > 0) { - PyErr_Format(PyExc_ValueError, - "Procedure probably called with too many " - "arguments (%d bytes in excess)", - delta); - return -1; - } -#endif -#endif - if ((flags & FUNCFLAG_PYTHONAPI) && PyErr_Occurred()) - return -1; - return 0; + if (delta < 0) { + if (flags & FUNCFLAG_CDECL) + PyErr_Format(PyExc_ValueError, + "Procedure called with not enough " + "arguments (%d bytes missing) " + "or wrong calling convention", + -delta); + else + PyErr_Format(PyExc_ValueError, + "Procedure probably called with not enough " + "arguments (%d bytes missing)", + -delta); + return -1; + } else if (delta > 0) { + PyErr_Format(PyExc_ValueError, + "Procedure probably called with too many " + "arguments (%d bytes in excess)", + delta); + return -1; + } +#endif +#endif + if ((flags & FUNCFLAG_PYTHONAPI) && PyErr_Occurred()) + return -1; + return 0; } /* @@ -893,41 +893,41 @@ */ static PyObject *GetResult(PyObject *restype, void *result, PyObject *checker) { - StgDictObject *dict; - PyObject *retval, *v; + StgDictObject *dict; + PyObject *retval, *v; - if (restype == NULL) - return PyLong_FromLong(*(int *)result); + if (restype == NULL) + return PyLong_FromLong(*(int *)result); - if (restype == Py_None) { - Py_INCREF(Py_None); - return Py_None; - } - - dict = PyType_stgdict(restype); - if (dict == NULL) - return PyObject_CallFunction(restype, "i", *(int *)result); - - if (dict->getfunc && !_ctypes_simple_instance(restype)) { - retval = dict->getfunc(result, dict->size); - /* If restype is py_object (detected by comparing getfunc with - O_get), we have to call Py_DECREF because O_get has already - called Py_INCREF. - */ - if (dict->getfunc == _ctypes_get_fielddesc("O")->getfunc) { - Py_DECREF(retval); - } - } else - retval = PyCData_FromBaseObj(restype, NULL, 0, result); - - if (!checker || !retval) - return retval; - - v = PyObject_CallFunctionObjArgs(checker, retval, NULL); - if (v == NULL) - _ctypes_add_traceback("GetResult", "_ctypes/callproc.c", __LINE__-2); - Py_DECREF(retval); - return v; + if (restype == Py_None) { + Py_INCREF(Py_None); + return Py_None; + } + + dict = PyType_stgdict(restype); + if (dict == NULL) + return PyObject_CallFunction(restype, "i", *(int *)result); + + if (dict->getfunc && !_ctypes_simple_instance(restype)) { + retval = dict->getfunc(result, dict->size); + /* If restype is py_object (detected by comparing getfunc with + O_get), we have to call Py_DECREF because O_get has already + called Py_INCREF. + */ + if (dict->getfunc == _ctypes_get_fielddesc("O")->getfunc) { + Py_DECREF(retval); + } + } else + retval = PyCData_FromBaseObj(restype, NULL, 0, result); + + if (!checker || !retval) + return retval; + + v = PyObject_CallFunctionObjArgs(checker, retval, NULL); + if (v == NULL) + _ctypes_add_traceback("GetResult", "_ctypes/callproc.c", __LINE__-2); + Py_DECREF(retval); + return v; } /* @@ -936,40 +936,40 @@ */ void _ctypes_extend_error(PyObject *exc_class, char *fmt, ...) { - va_list vargs; - PyObject *tp, *v, *tb, *s, *cls_str, *msg_str; + va_list vargs; + PyObject *tp, *v, *tb, *s, *cls_str, *msg_str; - va_start(vargs, fmt); - s = PyUnicode_FromFormatV(fmt, vargs); - va_end(vargs); - if (!s) - return; - - PyErr_Fetch(&tp, &v, &tb); - PyErr_NormalizeException(&tp, &v, &tb); - cls_str = PyObject_Str(tp); - if (cls_str) { - PyUnicode_AppendAndDel(&s, cls_str); - PyUnicode_AppendAndDel(&s, PyUnicode_FromString(": ")); - if (s == NULL) - goto error; - } else - PyErr_Clear(); - msg_str = PyObject_Str(v); - if (msg_str) - PyUnicode_AppendAndDel(&s, msg_str); - else { - PyErr_Clear(); - PyUnicode_AppendAndDel(&s, PyUnicode_FromString("???")); - if (s == NULL) - goto error; - } - PyErr_SetObject(exc_class, s); + va_start(vargs, fmt); + s = PyUnicode_FromFormatV(fmt, vargs); + va_end(vargs); + if (!s) + return; + + PyErr_Fetch(&tp, &v, &tb); + PyErr_NormalizeException(&tp, &v, &tb); + cls_str = PyObject_Str(tp); + if (cls_str) { + PyUnicode_AppendAndDel(&s, cls_str); + PyUnicode_AppendAndDel(&s, PyUnicode_FromString(": ")); + if (s == NULL) + goto error; + } else + PyErr_Clear(); + msg_str = PyObject_Str(v); + if (msg_str) + PyUnicode_AppendAndDel(&s, msg_str); + else { + PyErr_Clear(); + PyUnicode_AppendAndDel(&s, PyUnicode_FromString("???")); + if (s == NULL) + goto error; + } + PyErr_SetObject(exc_class, s); error: - Py_XDECREF(tp); - Py_XDECREF(v); - Py_XDECREF(tb); - Py_XDECREF(s); + Py_XDECREF(tp); + Py_XDECREF(v); + Py_XDECREF(tb); + Py_XDECREF(s); } @@ -978,73 +978,73 @@ static PyObject * GetComError(HRESULT errcode, GUID *riid, IUnknown *pIunk) { - HRESULT hr; - ISupportErrorInfo *psei = NULL; - IErrorInfo *pei = NULL; - BSTR descr=NULL, helpfile=NULL, source=NULL; - GUID guid; - DWORD helpcontext=0; - LPOLESTR progid; - PyObject *obj; - LPOLESTR text; - - /* We absolutely have to release the GIL during COM method calls, - otherwise we may get a deadlock! - */ + HRESULT hr; + ISupportErrorInfo *psei = NULL; + IErrorInfo *pei = NULL; + BSTR descr=NULL, helpfile=NULL, source=NULL; + GUID guid; + DWORD helpcontext=0; + LPOLESTR progid; + PyObject *obj; + LPOLESTR text; + + /* We absolutely have to release the GIL during COM method calls, + otherwise we may get a deadlock! + */ #ifdef WITH_THREAD - Py_BEGIN_ALLOW_THREADS + Py_BEGIN_ALLOW_THREADS #endif - hr = pIunk->lpVtbl->QueryInterface(pIunk, &IID_ISupportErrorInfo, (void **)&psei); - if (FAILED(hr)) - goto failed; + hr = pIunk->lpVtbl->QueryInterface(pIunk, &IID_ISupportErrorInfo, (void **)&psei); + if (FAILED(hr)) + goto failed; - hr = psei->lpVtbl->InterfaceSupportsErrorInfo(psei, riid); - psei->lpVtbl->Release(psei); - if (FAILED(hr)) - goto failed; + hr = psei->lpVtbl->InterfaceSupportsErrorInfo(psei, riid); + psei->lpVtbl->Release(psei); + if (FAILED(hr)) + goto failed; - hr = GetErrorInfo(0, &pei); - if (hr != S_OK) - goto failed; + hr = GetErrorInfo(0, &pei); + if (hr != S_OK) + goto failed; - pei->lpVtbl->GetDescription(pei, &descr); - pei->lpVtbl->GetGUID(pei, &guid); - pei->lpVtbl->GetHelpContext(pei, &helpcontext); - pei->lpVtbl->GetHelpFile(pei, &helpfile); - pei->lpVtbl->GetSource(pei, &source); + pei->lpVtbl->GetDescription(pei, &descr); + pei->lpVtbl->GetGUID(pei, &guid); + pei->lpVtbl->GetHelpContext(pei, &helpcontext); + pei->lpVtbl->GetHelpFile(pei, &helpfile); + pei->lpVtbl->GetSource(pei, &source); - pei->lpVtbl->Release(pei); + pei->lpVtbl->Release(pei); failed: #ifdef WITH_THREAD - Py_END_ALLOW_THREADS + Py_END_ALLOW_THREADS #endif - progid = NULL; - ProgIDFromCLSID(&guid, &progid); + progid = NULL; + ProgIDFromCLSID(&guid, &progid); - text = FormatError(errcode); - obj = Py_BuildValue( - "iu(uuuiu)", - errcode, - text, - descr, source, helpfile, helpcontext, - progid); - if (obj) { - PyErr_SetObject(ComError, obj); - Py_DECREF(obj); - } - LocalFree(text); - - if (descr) - SysFreeString(descr); - if (helpfile) - SysFreeString(helpfile); - if (source) - SysFreeString(source); + text = FormatError(errcode); + obj = Py_BuildValue( + "iu(uuuiu)", + errcode, + text, + descr, source, helpfile, helpcontext, + progid); + if (obj) { + PyErr_SetObject(ComError, obj); + Py_DECREF(obj); + } + LocalFree(text); + + if (descr) + SysFreeString(descr); + if (helpfile) + SysFreeString(helpfile); + if (source) + SysFreeString(source); - return NULL; + return NULL; } #endif @@ -1056,158 +1056,158 @@ * - XXX various requirements for restype, not yet collected */ PyObject *_ctypes_callproc(PPROC pProc, - PyObject *argtuple, + PyObject *argtuple, #ifdef MS_WIN32 - IUnknown *pIunk, - GUID *iid, + IUnknown *pIunk, + GUID *iid, #endif - int flags, - PyObject *argtypes, /* misleading name: This is a tuple of - methods, not types: the .from_param - class methods of the types */ - PyObject *restype, - PyObject *checker) -{ - Py_ssize_t i, n, argcount, argtype_count; - void *resbuf; - struct argument *args, *pa; - ffi_type **atypes; - ffi_type *rtype; - void **avalues; - PyObject *retval = NULL; + int flags, + PyObject *argtypes, /* misleading name: This is a tuple of + methods, not types: the .from_param + class methods of the types */ + PyObject *restype, + PyObject *checker) +{ + Py_ssize_t i, n, argcount, argtype_count; + void *resbuf; + struct argument *args, *pa; + ffi_type **atypes; + ffi_type *rtype; + void **avalues; + PyObject *retval = NULL; - n = argcount = PyTuple_GET_SIZE(argtuple); + n = argcount = PyTuple_GET_SIZE(argtuple); #ifdef MS_WIN32 - /* an optional COM object this pointer */ - if (pIunk) - ++argcount; + /* an optional COM object this pointer */ + if (pIunk) + ++argcount; #endif - args = (struct argument *)alloca(sizeof(struct argument) * argcount); - if (!args) { - PyErr_NoMemory(); - return NULL; - } - memset(args, 0, sizeof(struct argument) * argcount); - argtype_count = argtypes ? PyTuple_GET_SIZE(argtypes) : 0; + args = (struct argument *)alloca(sizeof(struct argument) * argcount); + if (!args) { + PyErr_NoMemory(); + return NULL; + } + memset(args, 0, sizeof(struct argument) * argcount); + argtype_count = argtypes ? PyTuple_GET_SIZE(argtypes) : 0; #ifdef MS_WIN32 - if (pIunk) { - args[0].ffi_type = &ffi_type_pointer; - args[0].value.p = pIunk; - pa = &args[1]; - } else -#endif - pa = &args[0]; - - /* Convert the arguments */ - for (i = 0; i < n; ++i, ++pa) { - PyObject *converter; - PyObject *arg; - int err; - - arg = PyTuple_GET_ITEM(argtuple, i); /* borrowed ref */ - /* For cdecl functions, we allow more actual arguments - than the length of the argtypes tuple. - This is checked in _ctypes::PyCFuncPtr_Call - */ - if (argtypes && argtype_count > i) { - PyObject *v; - converter = PyTuple_GET_ITEM(argtypes, i); - v = PyObject_CallFunctionObjArgs(converter, - arg, - NULL); - if (v == NULL) { - _ctypes_extend_error(PyExc_ArgError, "argument %d: ", i+1); - goto cleanup; - } - - err = ConvParam(v, i+1, pa); - Py_DECREF(v); - if (-1 == err) { - _ctypes_extend_error(PyExc_ArgError, "argument %d: ", i+1); - goto cleanup; - } - } else { - err = ConvParam(arg, i+1, pa); - if (-1 == err) { - _ctypes_extend_error(PyExc_ArgError, "argument %d: ", i+1); - goto cleanup; /* leaking ? */ - } - } - } - - rtype = _ctypes_get_ffi_type(restype); - resbuf = alloca(max(rtype->size, sizeof(ffi_arg))); - - avalues = (void **)alloca(sizeof(void *) * argcount); - atypes = (ffi_type **)alloca(sizeof(ffi_type *) * argcount); - if (!resbuf || !avalues || !atypes) { - PyErr_NoMemory(); - goto cleanup; - } - for (i = 0; i < argcount; ++i) { - atypes[i] = args[i].ffi_type; - if (atypes[i]->type == FFI_TYPE_STRUCT + if (pIunk) { + args[0].ffi_type = &ffi_type_pointer; + args[0].value.p = pIunk; + pa = &args[1]; + } else +#endif + pa = &args[0]; + + /* Convert the arguments */ + for (i = 0; i < n; ++i, ++pa) { + PyObject *converter; + PyObject *arg; + int err; + + arg = PyTuple_GET_ITEM(argtuple, i); /* borrowed ref */ + /* For cdecl functions, we allow more actual arguments + than the length of the argtypes tuple. + This is checked in _ctypes::PyCFuncPtr_Call + */ + if (argtypes && argtype_count > i) { + PyObject *v; + converter = PyTuple_GET_ITEM(argtypes, i); + v = PyObject_CallFunctionObjArgs(converter, + arg, + NULL); + if (v == NULL) { + _ctypes_extend_error(PyExc_ArgError, "argument %d: ", i+1); + goto cleanup; + } + + err = ConvParam(v, i+1, pa); + Py_DECREF(v); + if (-1 == err) { + _ctypes_extend_error(PyExc_ArgError, "argument %d: ", i+1); + goto cleanup; + } + } else { + err = ConvParam(arg, i+1, pa); + if (-1 == err) { + _ctypes_extend_error(PyExc_ArgError, "argument %d: ", i+1); + goto cleanup; /* leaking ? */ + } + } + } + + rtype = _ctypes_get_ffi_type(restype); + resbuf = alloca(max(rtype->size, sizeof(ffi_arg))); + + avalues = (void **)alloca(sizeof(void *) * argcount); + atypes = (ffi_type **)alloca(sizeof(ffi_type *) * argcount); + if (!resbuf || !avalues || !atypes) { + PyErr_NoMemory(); + goto cleanup; + } + for (i = 0; i < argcount; ++i) { + atypes[i] = args[i].ffi_type; + if (atypes[i]->type == FFI_TYPE_STRUCT #ifdef _WIN64 - && atypes[i]->size <= sizeof(void *) + && atypes[i]->size <= sizeof(void *) #endif - ) - avalues[i] = (void *)args[i].value.p; - else - avalues[i] = (void *)&args[i].value; - } - - if (-1 == _call_function_pointer(flags, pProc, avalues, atypes, - rtype, resbuf, - Py_SAFE_DOWNCAST(argcount, - Py_ssize_t, - int))) - goto cleanup; + ) + avalues[i] = (void *)args[i].value.p; + else + avalues[i] = (void *)&args[i].value; + } + + if (-1 == _call_function_pointer(flags, pProc, avalues, atypes, + rtype, resbuf, + Py_SAFE_DOWNCAST(argcount, + Py_ssize_t, + int))) + goto cleanup; #ifdef WORDS_BIGENDIAN - /* libffi returns the result in a buffer with sizeof(ffi_arg). This - causes problems on big endian machines, since the result buffer - address cannot simply be used as result pointer, instead we must - adjust the pointer value: - */ - /* - XXX I should find out and clarify why this is needed at all, - especially why adjusting for ffi_type_float must be avoided on - 64-bit platforms. - */ - if (rtype->type != FFI_TYPE_FLOAT - && rtype->type != FFI_TYPE_STRUCT - && rtype->size < sizeof(ffi_arg)) - resbuf = (char *)resbuf + sizeof(ffi_arg) - rtype->size; + /* libffi returns the result in a buffer with sizeof(ffi_arg). This + causes problems on big endian machines, since the result buffer + address cannot simply be used as result pointer, instead we must + adjust the pointer value: + */ + /* + XXX I should find out and clarify why this is needed at all, + especially why adjusting for ffi_type_float must be avoided on + 64-bit platforms. + */ + if (rtype->type != FFI_TYPE_FLOAT + && rtype->type != FFI_TYPE_STRUCT + && rtype->size < sizeof(ffi_arg)) + resbuf = (char *)resbuf + sizeof(ffi_arg) - rtype->size; #endif #ifdef MS_WIN32 - if (iid && pIunk) { - if (*(int *)resbuf & 0x80000000) - retval = GetComError(*(HRESULT *)resbuf, iid, pIunk); - else - retval = PyLong_FromLong(*(int *)resbuf); - } else if (flags & FUNCFLAG_HRESULT) { - if (*(int *)resbuf & 0x80000000) - retval = PyErr_SetFromWindowsErr(*(int *)resbuf); - else - retval = PyLong_FromLong(*(int *)resbuf); - } else + if (iid && pIunk) { + if (*(int *)resbuf & 0x80000000) + retval = GetComError(*(HRESULT *)resbuf, iid, pIunk); + else + retval = PyLong_FromLong(*(int *)resbuf); + } else if (flags & FUNCFLAG_HRESULT) { + if (*(int *)resbuf & 0x80000000) + retval = PyErr_SetFromWindowsErr(*(int *)resbuf); + else + retval = PyLong_FromLong(*(int *)resbuf); + } else #endif - retval = GetResult(restype, resbuf, checker); + retval = GetResult(restype, resbuf, checker); cleanup: - for (i = 0; i < argcount; ++i) - Py_XDECREF(args[i].keep); - return retval; + for (i = 0; i < argcount; ++i) + Py_XDECREF(args[i].keep); + return retval; } static int _parse_voidp(PyObject *obj, void **address) { - *address = PyLong_AsVoidPtr(obj); - if (*address == NULL) - return 0; - return 1; + *address = PyLong_AsVoidPtr(obj); + if (*address == NULL) + return 0; + return 1; } #ifdef MS_WIN32 @@ -1219,21 +1219,21 @@ given, the return value of a call to GetLastError() is used.\n"; static PyObject *format_error(PyObject *self, PyObject *args) { - PyObject *result; - wchar_t *lpMsgBuf; - DWORD code = 0; - if (!PyArg_ParseTuple(args, "|i:FormatError", &code)) - return NULL; - if (code == 0) - code = GetLastError(); - lpMsgBuf = FormatError(code); - if (lpMsgBuf) { - result = PyUnicode_FromWideChar(lpMsgBuf, wcslen(lpMsgBuf)); - LocalFree(lpMsgBuf); - } else { - result = PyUnicode_FromString(""); - } - return result; + PyObject *result; + wchar_t *lpMsgBuf; + DWORD code = 0; + if (!PyArg_ParseTuple(args, "|i:FormatError", &code)) + return NULL; + if (code == 0) + code = GetLastError(); + lpMsgBuf = FormatError(code); + if (lpMsgBuf) { + result = PyUnicode_FromWideChar(lpMsgBuf, wcslen(lpMsgBuf)); + LocalFree(lpMsgBuf); + } else { + result = PyUnicode_FromString(""); + } + return result; } static char load_library_doc[] = @@ -1244,24 +1244,24 @@ module.\n"; static PyObject *load_library(PyObject *self, PyObject *args) { - WCHAR *name; - PyObject *nameobj; - PyObject *ignored; - HMODULE hMod; - if (!PyArg_ParseTuple(args, "O|O:LoadLibrary", &nameobj, &ignored)) - return NULL; - - name = PyUnicode_AsUnicode(nameobj); - if (!name) - return NULL; - - hMod = LoadLibraryW(name); - if (!hMod) - return PyErr_SetFromWindowsErr(GetLastError()); + WCHAR *name; + PyObject *nameobj; + PyObject *ignored; + HMODULE hMod; + if (!PyArg_ParseTuple(args, "O|O:LoadLibrary", &nameobj, &ignored)) + return NULL; + + name = PyUnicode_AsUnicode(nameobj); + if (!name) + return NULL; + + hMod = LoadLibraryW(name); + if (!hMod) + return PyErr_SetFromWindowsErr(GetLastError()); #ifdef _WIN64 - return PyLong_FromVoidPtr(hMod); + return PyLong_FromVoidPtr(hMod); #else - return Py_BuildValue("i", hMod); + return Py_BuildValue("i", hMod); #endif } @@ -1271,13 +1271,13 @@ Free the handle of an executable previously loaded by LoadLibrary.\n"; static PyObject *free_library(PyObject *self, PyObject *args) { - void *hMod; - if (!PyArg_ParseTuple(args, "O&:FreeLibrary", &_parse_voidp, &hMod)) - return NULL; - if (!FreeLibrary((HMODULE)hMod)) - return PyErr_SetFromWindowsErr(GetLastError()); - Py_INCREF(Py_None); - return Py_None; + void *hMod; + if (!PyArg_ParseTuple(args, "O&:FreeLibrary", &_parse_voidp, &hMod)) + return NULL; + if (!FreeLibrary((HMODULE)hMod)) + return PyErr_SetFromWindowsErr(GetLastError()); + Py_INCREF(Py_None); + return Py_None; } /* obsolete, should be removed */ @@ -1285,55 +1285,55 @@ static PyObject * call_commethod(PyObject *self, PyObject *args) { - IUnknown *pIunk; - int index; - PyObject *arguments; - PPROC *lpVtbl; - PyObject *result; - CDataObject *pcom; - PyObject *argtypes = NULL; - - if (!PyArg_ParseTuple(args, - "OiO!|O!", - &pcom, &index, - &PyTuple_Type, &arguments, - &PyTuple_Type, &argtypes)) - return NULL; - - if (argtypes && (PyTuple_GET_SIZE(arguments) != PyTuple_GET_SIZE(argtypes))) { - PyErr_Format(PyExc_TypeError, - "Method takes %d arguments (%d given)", - PyTuple_GET_SIZE(argtypes), PyTuple_GET_SIZE(arguments)); - return NULL; - } - - if (!CDataObject_Check(pcom) || (pcom->b_size != sizeof(void *))) { - PyErr_Format(PyExc_TypeError, - "COM Pointer expected instead of %s instance", - Py_TYPE(pcom)->tp_name); - return NULL; - } - - if ((*(void **)(pcom->b_ptr)) == NULL) { - PyErr_SetString(PyExc_ValueError, - "The COM 'this' pointer is NULL"); - return NULL; - } + IUnknown *pIunk; + int index; + PyObject *arguments; + PPROC *lpVtbl; + PyObject *result; + CDataObject *pcom; + PyObject *argtypes = NULL; + + if (!PyArg_ParseTuple(args, + "OiO!|O!", + &pcom, &index, + &PyTuple_Type, &arguments, + &PyTuple_Type, &argtypes)) + return NULL; + + if (argtypes && (PyTuple_GET_SIZE(arguments) != PyTuple_GET_SIZE(argtypes))) { + PyErr_Format(PyExc_TypeError, + "Method takes %d arguments (%d given)", + PyTuple_GET_SIZE(argtypes), PyTuple_GET_SIZE(arguments)); + return NULL; + } + + if (!CDataObject_Check(pcom) || (pcom->b_size != sizeof(void *))) { + PyErr_Format(PyExc_TypeError, + "COM Pointer expected instead of %s instance", + Py_TYPE(pcom)->tp_name); + return NULL; + } + + if ((*(void **)(pcom->b_ptr)) == NULL) { + PyErr_SetString(PyExc_ValueError, + "The COM 'this' pointer is NULL"); + return NULL; + } - pIunk = (IUnknown *)(*(void **)(pcom->b_ptr)); - lpVtbl = (PPROC *)(pIunk->lpVtbl); + pIunk = (IUnknown *)(*(void **)(pcom->b_ptr)); + lpVtbl = (PPROC *)(pIunk->lpVtbl); - result = _ctypes_callproc(lpVtbl[index], - arguments, + result = _ctypes_callproc(lpVtbl[index], + arguments, #ifdef MS_WIN32 - pIunk, - NULL, + pIunk, + NULL, #endif - FUNCFLAG_HRESULT, /* flags */ - argtypes, /* self->argtypes */ - NULL, /* self->restype */ - NULL); /* checker */ - return result; + FUNCFLAG_HRESULT, /* flags */ + argtypes, /* self->argtypes */ + NULL, /* self->restype */ + NULL); /* checker */ + return result; } static char copy_com_pointer_doc[] = @@ -1342,102 +1342,102 @@ static PyObject * copy_com_pointer(PyObject *self, PyObject *args) { - PyObject *p1, *p2, *r = NULL; - struct argument a, b; - IUnknown *src, **pdst; - if (!PyArg_ParseTuple(args, "OO:CopyComPointer", &p1, &p2)) - return NULL; - a.keep = b.keep = NULL; - - if (-1 == ConvParam(p1, 0, &a) || -1 == ConvParam(p2, 1, &b)) - goto done; - src = (IUnknown *)a.value.p; - pdst = (IUnknown **)b.value.p; - - if (pdst == NULL) - r = PyLong_FromLong(E_POINTER); - else { - if (src) - src->lpVtbl->AddRef(src); - *pdst = src; - r = PyLong_FromLong(S_OK); - } + PyObject *p1, *p2, *r = NULL; + struct argument a, b; + IUnknown *src, **pdst; + if (!PyArg_ParseTuple(args, "OO:CopyComPointer", &p1, &p2)) + return NULL; + a.keep = b.keep = NULL; + + if (-1 == ConvParam(p1, 0, &a) || -1 == ConvParam(p2, 1, &b)) + goto done; + src = (IUnknown *)a.value.p; + pdst = (IUnknown **)b.value.p; + + if (pdst == NULL) + r = PyLong_FromLong(E_POINTER); + else { + if (src) + src->lpVtbl->AddRef(src); + *pdst = src; + r = PyLong_FromLong(S_OK); + } done: - Py_XDECREF(a.keep); - Py_XDECREF(b.keep); - return r; + Py_XDECREF(a.keep); + Py_XDECREF(b.keep); + return r; } #else static PyObject *py_dl_open(PyObject *self, PyObject *args) { - PyObject *name, *name2; - char *name_str; - void * handle; -#ifdef RTLD_LOCAL - int mode = RTLD_NOW | RTLD_LOCAL; + PyObject *name, *name2; + char *name_str; + void * handle; +#ifdef RTLD_LOCAL + int mode = RTLD_NOW | RTLD_LOCAL; #else - /* cygwin doesn't define RTLD_LOCAL */ - int mode = RTLD_NOW; + /* cygwin doesn't define RTLD_LOCAL */ + int mode = RTLD_NOW; #endif - if (!PyArg_ParseTuple(args, "O|i:dlopen", &name, &mode)) - return NULL; - mode |= RTLD_NOW; - if (name != Py_None) { - if (PyUnicode_FSConverter(name, &name2) == 0) - return NULL; - if (PyBytes_Check(name2)) - name_str = PyBytes_AS_STRING(name2); - else - name_str = PyByteArray_AS_STRING(name2); - } else { - name_str = NULL; - name2 = NULL; - } - handle = ctypes_dlopen(name_str, mode); - Py_XDECREF(name2); - if (!handle) { - char *errmsg = ctypes_dlerror(); - if (!errmsg) - errmsg = "dlopen() error"; - PyErr_SetString(PyExc_OSError, - errmsg); - return NULL; - } - return PyLong_FromVoidPtr(handle); + if (!PyArg_ParseTuple(args, "O|i:dlopen", &name, &mode)) + return NULL; + mode |= RTLD_NOW; + if (name != Py_None) { + if (PyUnicode_FSConverter(name, &name2) == 0) + return NULL; + if (PyBytes_Check(name2)) + name_str = PyBytes_AS_STRING(name2); + else + name_str = PyByteArray_AS_STRING(name2); + } else { + name_str = NULL; + name2 = NULL; + } + handle = ctypes_dlopen(name_str, mode); + Py_XDECREF(name2); + if (!handle) { + char *errmsg = ctypes_dlerror(); + if (!errmsg) + errmsg = "dlopen() error"; + PyErr_SetString(PyExc_OSError, + errmsg); + return NULL; + } + return PyLong_FromVoidPtr(handle); } static PyObject *py_dl_close(PyObject *self, PyObject *args) { - void *handle; + void *handle; - if (!PyArg_ParseTuple(args, "O&:dlclose", &_parse_voidp, &handle)) - return NULL; - if (dlclose(handle)) { - PyErr_SetString(PyExc_OSError, - ctypes_dlerror()); - return NULL; - } - Py_INCREF(Py_None); - return Py_None; + if (!PyArg_ParseTuple(args, "O&:dlclose", &_parse_voidp, &handle)) + return NULL; + if (dlclose(handle)) { + PyErr_SetString(PyExc_OSError, + ctypes_dlerror()); + return NULL; + } + Py_INCREF(Py_None); + return Py_None; } static PyObject *py_dl_sym(PyObject *self, PyObject *args) { - char *name; - void *handle; - void *ptr; - - if (!PyArg_ParseTuple(args, "O&s:dlsym", - &_parse_voidp, &handle, &name)) - return NULL; - ptr = ctypes_dlsym((void*)handle, name); - if (!ptr) { - PyErr_SetString(PyExc_OSError, - ctypes_dlerror()); - return NULL; - } - return PyLong_FromVoidPtr(ptr); + char *name; + void *handle; + void *ptr; + + if (!PyArg_ParseTuple(args, "O&s:dlsym", + &_parse_voidp, &handle, &name)) + return NULL; + ptr = ctypes_dlsym((void*)handle, name); + if (!ptr) { + PyErr_SetString(PyExc_OSError, + ctypes_dlerror()); + return NULL; + } + return PyLong_FromVoidPtr(ptr); } #endif @@ -1449,27 +1449,27 @@ static PyObject * call_function(PyObject *self, PyObject *args) { - void *func; - PyObject *arguments; - PyObject *result; - - if (!PyArg_ParseTuple(args, - "O&O!", - &_parse_voidp, &func, - &PyTuple_Type, &arguments)) - return NULL; + void *func; + PyObject *arguments; + PyObject *result; + + if (!PyArg_ParseTuple(args, + "O&O!", + &_parse_voidp, &func, + &PyTuple_Type, &arguments)) + return NULL; - result = _ctypes_callproc((PPROC)func, - arguments, + result = _ctypes_callproc((PPROC)func, + arguments, #ifdef MS_WIN32 - NULL, - NULL, + NULL, + NULL, #endif - 0, /* flags */ - NULL, /* self->argtypes */ - NULL, /* self->restype */ - NULL); /* checker */ - return result; + 0, /* flags */ + NULL, /* self->argtypes */ + NULL, /* self->restype */ + NULL); /* checker */ + return result; } /* @@ -1480,27 +1480,27 @@ static PyObject * call_cdeclfunction(PyObject *self, PyObject *args) { - void *func; - PyObject *arguments; - PyObject *result; - - if (!PyArg_ParseTuple(args, - "O&O!", - &_parse_voidp, &func, - &PyTuple_Type, &arguments)) - return NULL; + void *func; + PyObject *arguments; + PyObject *result; + + if (!PyArg_ParseTuple(args, + "O&O!", + &_parse_voidp, &func, + &PyTuple_Type, &arguments)) + return NULL; - result = _ctypes_callproc((PPROC)func, - arguments, + result = _ctypes_callproc((PPROC)func, + arguments, #ifdef MS_WIN32 - NULL, - NULL, + NULL, + NULL, #endif - FUNCFLAG_CDECL, /* flags */ - NULL, /* self->argtypes */ - NULL, /* self->restype */ - NULL); /* checker */ - return result; + FUNCFLAG_CDECL, /* flags */ + NULL, /* self->argtypes */ + NULL, /* self->restype */ + NULL); /* checker */ + return result; } /***************************************************************** @@ -1514,17 +1514,17 @@ static PyObject * sizeof_func(PyObject *self, PyObject *obj) { - StgDictObject *dict; + StgDictObject *dict; - dict = PyType_stgdict(obj); - if (dict) - return PyLong_FromSsize_t(dict->size); - - if (CDataObject_Check(obj)) - return PyLong_FromSsize_t(((CDataObject *)obj)->b_size); - PyErr_SetString(PyExc_TypeError, - "this type has no size"); - return NULL; + dict = PyType_stgdict(obj); + if (dict) + return PyLong_FromSsize_t(dict->size); + + if (CDataObject_Check(obj)) + return PyLong_FromSsize_t(((CDataObject *)obj)->b_size); + PyErr_SetString(PyExc_TypeError, + "this type has no size"); + return NULL; } static char alignment_doc[] = @@ -1535,19 +1535,19 @@ static PyObject * align_func(PyObject *self, PyObject *obj) { - StgDictObject *dict; + StgDictObject *dict; - dict = PyType_stgdict(obj); - if (dict) - return PyLong_FromSsize_t(dict->align); - - dict = PyObject_stgdict(obj); - if (dict) - return PyLong_FromSsize_t(dict->align); - - PyErr_SetString(PyExc_TypeError, - "no alignment info"); - return NULL; + dict = PyType_stgdict(obj); + if (dict) + return PyLong_FromSsize_t(dict->align); + + dict = PyObject_stgdict(obj); + if (dict) + return PyLong_FromSsize_t(dict->align); + + PyErr_SetString(PyExc_TypeError, + "no alignment info"); + return NULL; } static char byref_doc[] = @@ -1562,36 +1562,36 @@ static PyObject * byref(PyObject *self, PyObject *args) { - PyCArgObject *parg; - PyObject *obj; - PyObject *pyoffset = NULL; - Py_ssize_t offset = 0; - - if (!PyArg_UnpackTuple(args, "byref", 1, 2, - &obj, &pyoffset)) - return NULL; - if (pyoffset) { - offset = PyNumber_AsSsize_t(pyoffset, NULL); - if (offset == -1 && PyErr_Occurred()) - return NULL; - } - if (!CDataObject_Check(obj)) { - PyErr_Format(PyExc_TypeError, - "byref() argument must be a ctypes instance, not '%s'", - Py_TYPE(obj)->tp_name); - return NULL; - } - - parg = PyCArgObject_new(); - if (parg == NULL) - return NULL; - - parg->tag = 'P'; - parg->pffi_type = &ffi_type_pointer; - Py_INCREF(obj); - parg->obj = obj; - parg->value.p = (char *)((CDataObject *)obj)->b_ptr + offset; - return (PyObject *)parg; + PyCArgObject *parg; + PyObject *obj; + PyObject *pyoffset = NULL; + Py_ssize_t offset = 0; + + if (!PyArg_UnpackTuple(args, "byref", 1, 2, + &obj, &pyoffset)) + return NULL; + if (pyoffset) { + offset = PyNumber_AsSsize_t(pyoffset, NULL); + if (offset == -1 && PyErr_Occurred()) + return NULL; + } + if (!CDataObject_Check(obj)) { + PyErr_Format(PyExc_TypeError, + "byref() argument must be a ctypes instance, not '%s'", + Py_TYPE(obj)->tp_name); + return NULL; + } + + parg = PyCArgObject_new(); + if (parg == NULL) + return NULL; + + parg->tag = 'P'; + parg->pffi_type = &ffi_type_pointer; + Py_INCREF(obj); + parg->obj = obj; + parg->value.p = (char *)((CDataObject *)obj)->b_ptr + offset; + return (PyObject *)parg; } static char addressof_doc[] = @@ -1601,44 +1601,44 @@ static PyObject * addressof(PyObject *self, PyObject *obj) { - if (CDataObject_Check(obj)) - return PyLong_FromVoidPtr(((CDataObject *)obj)->b_ptr); - PyErr_SetString(PyExc_TypeError, - "invalid type"); - return NULL; + if (CDataObject_Check(obj)) + return PyLong_FromVoidPtr(((CDataObject *)obj)->b_ptr); + PyErr_SetString(PyExc_TypeError, + "invalid type"); + return NULL; } static int converter(PyObject *obj, void **address) { - *address = PyLong_AsVoidPtr(obj); - return *address != NULL; + *address = PyLong_AsVoidPtr(obj); + return *address != NULL; } static PyObject * My_PyObj_FromPtr(PyObject *self, PyObject *args) { - PyObject *ob; - if (!PyArg_ParseTuple(args, "O&:PyObj_FromPtr", converter, &ob)) - return NULL; - Py_INCREF(ob); - return ob; + PyObject *ob; + if (!PyArg_ParseTuple(args, "O&:PyObj_FromPtr", converter, &ob)) + return NULL; + Py_INCREF(ob); + return ob; } static PyObject * My_Py_INCREF(PyObject *self, PyObject *arg) { - Py_INCREF(arg); /* that's what this function is for */ - Py_INCREF(arg); /* that for returning it */ - return arg; + Py_INCREF(arg); /* that's what this function is for */ + Py_INCREF(arg); /* that for returning it */ + return arg; } static PyObject * My_Py_DECREF(PyObject *self, PyObject *arg) { - Py_DECREF(arg); /* that's what this function is for */ - Py_INCREF(arg); /* that's for returning it */ - return arg; + Py_DECREF(arg); /* that's what this function is for */ + Py_INCREF(arg); /* that's for returning it */ + return arg; } #ifdef CTYPES_UNICODE @@ -1652,234 +1652,234 @@ static PyObject * set_conversion_mode(PyObject *self, PyObject *args) { - char *coding, *mode; - PyObject *result; + char *coding, *mode; + PyObject *result; - if (!PyArg_ParseTuple(args, "zs:set_conversion_mode", &coding, &mode)) - return NULL; - result = Py_BuildValue("(zz)", _ctypes_conversion_encoding, _ctypes_conversion_errors); - if (coding) { - PyMem_Free(_ctypes_conversion_encoding); - _ctypes_conversion_encoding = PyMem_Malloc(strlen(coding) + 1); - strcpy(_ctypes_conversion_encoding, coding); - } else { - _ctypes_conversion_encoding = NULL; - } - PyMem_Free(_ctypes_conversion_errors); - _ctypes_conversion_errors = PyMem_Malloc(strlen(mode) + 1); - strcpy(_ctypes_conversion_errors, mode); - return result; + if (!PyArg_ParseTuple(args, "zs:set_conversion_mode", &coding, &mode)) + return NULL; + result = Py_BuildValue("(zz)", _ctypes_conversion_encoding, _ctypes_conversion_errors); + if (coding) { + PyMem_Free(_ctypes_conversion_encoding); + _ctypes_conversion_encoding = PyMem_Malloc(strlen(coding) + 1); + strcpy(_ctypes_conversion_encoding, coding); + } else { + _ctypes_conversion_encoding = NULL; + } + PyMem_Free(_ctypes_conversion_errors); + _ctypes_conversion_errors = PyMem_Malloc(strlen(mode) + 1); + strcpy(_ctypes_conversion_errors, mode); + return result; } #endif static PyObject * resize(PyObject *self, PyObject *args) { - CDataObject *obj; - StgDictObject *dict; - Py_ssize_t size; - - if (!PyArg_ParseTuple(args, - "On:resize", - &obj, &size)) - return NULL; - - dict = PyObject_stgdict((PyObject *)obj); - if (dict == NULL) { - PyErr_SetString(PyExc_TypeError, - "excepted ctypes instance"); - return NULL; - } - if (size < dict->size) { - PyErr_Format(PyExc_ValueError, - "minimum size is %zd", - dict->size); - return NULL; - } - if (obj->b_needsfree == 0) { - PyErr_Format(PyExc_ValueError, - "Memory cannot be resized because this object doesn't own it"); - return NULL; - } - if (size <= sizeof(obj->b_value)) { - /* internal default buffer is large enough */ - obj->b_size = size; - goto done; - } - if (obj->b_size <= sizeof(obj->b_value)) { - /* We are currently using the objects default buffer, but it - isn't large enough any more. */ - void *ptr = PyMem_Malloc(size); - if (ptr == NULL) - return PyErr_NoMemory(); - memset(ptr, 0, size); - memmove(ptr, obj->b_ptr, obj->b_size); - obj->b_ptr = ptr; - obj->b_size = size; - } else { - void * ptr = PyMem_Realloc(obj->b_ptr, size); - if (ptr == NULL) - return PyErr_NoMemory(); - obj->b_ptr = ptr; - obj->b_size = size; - } + CDataObject *obj; + StgDictObject *dict; + Py_ssize_t size; + + if (!PyArg_ParseTuple(args, + "On:resize", + &obj, &size)) + return NULL; + + dict = PyObject_stgdict((PyObject *)obj); + if (dict == NULL) { + PyErr_SetString(PyExc_TypeError, + "excepted ctypes instance"); + return NULL; + } + if (size < dict->size) { + PyErr_Format(PyExc_ValueError, + "minimum size is %zd", + dict->size); + return NULL; + } + if (obj->b_needsfree == 0) { + PyErr_Format(PyExc_ValueError, + "Memory cannot be resized because this object doesn't own it"); + return NULL; + } + if (size <= sizeof(obj->b_value)) { + /* internal default buffer is large enough */ + obj->b_size = size; + goto done; + } + if (obj->b_size <= sizeof(obj->b_value)) { + /* We are currently using the objects default buffer, but it + isn't large enough any more. */ + void *ptr = PyMem_Malloc(size); + if (ptr == NULL) + return PyErr_NoMemory(); + memset(ptr, 0, size); + memmove(ptr, obj->b_ptr, obj->b_size); + obj->b_ptr = ptr; + obj->b_size = size; + } else { + void * ptr = PyMem_Realloc(obj->b_ptr, size); + if (ptr == NULL) + return PyErr_NoMemory(); + obj->b_ptr = ptr; + obj->b_size = size; + } done: - Py_INCREF(Py_None); - return Py_None; + Py_INCREF(Py_None); + return Py_None; } static PyObject * unpickle(PyObject *self, PyObject *args) { - PyObject *typ; - PyObject *state; - PyObject *result; - PyObject *tmp; - - if (!PyArg_ParseTuple(args, "OO", &typ, &state)) - return NULL; - result = PyObject_CallMethod(typ, "__new__", "O", typ); - if (result == NULL) - return NULL; - tmp = PyObject_CallMethod(result, "__setstate__", "O", state); - if (tmp == NULL) { - Py_DECREF(result); - return NULL; - } - Py_DECREF(tmp); - return result; + PyObject *typ; + PyObject *state; + PyObject *result; + PyObject *tmp; + + if (!PyArg_ParseTuple(args, "OO", &typ, &state)) + return NULL; + result = PyObject_CallMethod(typ, "__new__", "O", typ); + if (result == NULL) + return NULL; + tmp = PyObject_CallMethod(result, "__setstate__", "O", state); + if (tmp == NULL) { + Py_DECREF(result); + return NULL; + } + Py_DECREF(tmp); + return result; } static PyObject * POINTER(PyObject *self, PyObject *cls) { - PyObject *result; - PyTypeObject *typ; - PyObject *key; - char *buf; - - result = PyDict_GetItem(_ctypes_ptrtype_cache, cls); - if (result) { - Py_INCREF(result); - return result; - } - if (PyUnicode_CheckExact(cls)) { - char *name = _PyUnicode_AsString(cls); - buf = alloca(strlen(name) + 3 + 1); - sprintf(buf, "LP_%s", name); - result = PyObject_CallFunction((PyObject *)Py_TYPE(&PyCPointer_Type), - "s(O){}", - buf, - &PyCPointer_Type); - if (result == NULL) - return result; - key = PyLong_FromVoidPtr(result); - } else if (PyType_Check(cls)) { - typ = (PyTypeObject *)cls; - buf = alloca(strlen(typ->tp_name) + 3 + 1); - sprintf(buf, "LP_%s", typ->tp_name); - result = PyObject_CallFunction((PyObject *)Py_TYPE(&PyCPointer_Type), - "s(O){sO}", - buf, - &PyCPointer_Type, - "_type_", cls); - if (result == NULL) - return result; - Py_INCREF(cls); - key = cls; - } else { - PyErr_SetString(PyExc_TypeError, "must be a ctypes type"); - return NULL; - } - if (-1 == PyDict_SetItem(_ctypes_ptrtype_cache, key, result)) { - Py_DECREF(result); - Py_DECREF(key); - return NULL; - } - Py_DECREF(key); - return result; + PyObject *result; + PyTypeObject *typ; + PyObject *key; + char *buf; + + result = PyDict_GetItem(_ctypes_ptrtype_cache, cls); + if (result) { + Py_INCREF(result); + return result; + } + if (PyUnicode_CheckExact(cls)) { + char *name = _PyUnicode_AsString(cls); + buf = alloca(strlen(name) + 3 + 1); + sprintf(buf, "LP_%s", name); + result = PyObject_CallFunction((PyObject *)Py_TYPE(&PyCPointer_Type), + "s(O){}", + buf, + &PyCPointer_Type); + if (result == NULL) + return result; + key = PyLong_FromVoidPtr(result); + } else if (PyType_Check(cls)) { + typ = (PyTypeObject *)cls; + buf = alloca(strlen(typ->tp_name) + 3 + 1); + sprintf(buf, "LP_%s", typ->tp_name); + result = PyObject_CallFunction((PyObject *)Py_TYPE(&PyCPointer_Type), + "s(O){sO}", + buf, + &PyCPointer_Type, + "_type_", cls); + if (result == NULL) + return result; + Py_INCREF(cls); + key = cls; + } else { + PyErr_SetString(PyExc_TypeError, "must be a ctypes type"); + return NULL; + } + if (-1 == PyDict_SetItem(_ctypes_ptrtype_cache, key, result)) { + Py_DECREF(result); + Py_DECREF(key); + return NULL; + } + Py_DECREF(key); + return result; } static PyObject * pointer(PyObject *self, PyObject *arg) { - PyObject *result; - PyObject *typ; + PyObject *result; + PyObject *typ; - typ = PyDict_GetItem(_ctypes_ptrtype_cache, (PyObject *)Py_TYPE(arg)); - if (typ) - return PyObject_CallFunctionObjArgs(typ, arg, NULL); - typ = POINTER(NULL, (PyObject *)Py_TYPE(arg)); - if (typ == NULL) - return NULL; - result = PyObject_CallFunctionObjArgs(typ, arg, NULL); - Py_DECREF(typ); - return result; + typ = PyDict_GetItem(_ctypes_ptrtype_cache, (PyObject *)Py_TYPE(arg)); + if (typ) + return PyObject_CallFunctionObjArgs(typ, arg, NULL); + typ = POINTER(NULL, (PyObject *)Py_TYPE(arg)); + if (typ == NULL) + return NULL; + result = PyObject_CallFunctionObjArgs(typ, arg, NULL); + Py_DECREF(typ); + return result; } static PyObject * buffer_info(PyObject *self, PyObject *arg) { - StgDictObject *dict = PyType_stgdict(arg); - PyObject *shape; - Py_ssize_t i; - - if (dict == NULL) - dict = PyObject_stgdict(arg); - if (dict == NULL) { - PyErr_SetString(PyExc_TypeError, - "not a ctypes type or object"); - return NULL; - } - shape = PyTuple_New(dict->ndim); - if (shape == NULL) - return NULL; - for (i = 0; i < (int)dict->ndim; ++i) - PyTuple_SET_ITEM(shape, i, PyLong_FromSsize_t(dict->shape[i])); - - if (PyErr_Occurred()) { - Py_DECREF(shape); - return NULL; - } - return Py_BuildValue("siN", dict->format, dict->ndim, shape); + StgDictObject *dict = PyType_stgdict(arg); + PyObject *shape; + Py_ssize_t i; + + if (dict == NULL) + dict = PyObject_stgdict(arg); + if (dict == NULL) { + PyErr_SetString(PyExc_TypeError, + "not a ctypes type or object"); + return NULL; + } + shape = PyTuple_New(dict->ndim); + if (shape == NULL) + return NULL; + for (i = 0; i < (int)dict->ndim; ++i) + PyTuple_SET_ITEM(shape, i, PyLong_FromSsize_t(dict->shape[i])); + + if (PyErr_Occurred()) { + Py_DECREF(shape); + return NULL; + } + return Py_BuildValue("siN", dict->format, dict->ndim, shape); } PyMethodDef _ctypes_module_methods[] = { - {"get_errno", get_errno, METH_NOARGS}, - {"set_errno", set_errno, METH_VARARGS}, - {"POINTER", POINTER, METH_O }, - {"pointer", pointer, METH_O }, - {"_unpickle", unpickle, METH_VARARGS }, - {"buffer_info", buffer_info, METH_O, "Return buffer interface information"}, - {"resize", resize, METH_VARARGS, "Resize the memory buffer of a ctypes instance"}, + {"get_errno", get_errno, METH_NOARGS}, + {"set_errno", set_errno, METH_VARARGS}, + {"POINTER", POINTER, METH_O }, + {"pointer", pointer, METH_O }, + {"_unpickle", unpickle, METH_VARARGS }, + {"buffer_info", buffer_info, METH_O, "Return buffer interface information"}, + {"resize", resize, METH_VARARGS, "Resize the memory buffer of a ctypes instance"}, #ifdef CTYPES_UNICODE - {"set_conversion_mode", set_conversion_mode, METH_VARARGS, set_conversion_mode_doc}, + {"set_conversion_mode", set_conversion_mode, METH_VARARGS, set_conversion_mode_doc}, #endif #ifdef MS_WIN32 - {"get_last_error", get_last_error, METH_NOARGS}, - {"set_last_error", set_last_error, METH_VARARGS}, - {"CopyComPointer", copy_com_pointer, METH_VARARGS, copy_com_pointer_doc}, - {"FormatError", format_error, METH_VARARGS, format_error_doc}, - {"LoadLibrary", load_library, METH_VARARGS, load_library_doc}, - {"FreeLibrary", free_library, METH_VARARGS, free_library_doc}, - {"call_commethod", call_commethod, METH_VARARGS }, - {"_check_HRESULT", check_hresult, METH_VARARGS}, + {"get_last_error", get_last_error, METH_NOARGS}, + {"set_last_error", set_last_error, METH_VARARGS}, + {"CopyComPointer", copy_com_pointer, METH_VARARGS, copy_com_pointer_doc}, + {"FormatError", format_error, METH_VARARGS, format_error_doc}, + {"LoadLibrary", load_library, METH_VARARGS, load_library_doc}, + {"FreeLibrary", free_library, METH_VARARGS, free_library_doc}, + {"call_commethod", call_commethod, METH_VARARGS }, + {"_check_HRESULT", check_hresult, METH_VARARGS}, #else - {"dlopen", py_dl_open, METH_VARARGS, - "dlopen(name, flag={RTLD_GLOBAL|RTLD_LOCAL}) open a shared library"}, - {"dlclose", py_dl_close, METH_VARARGS, "dlclose a library"}, - {"dlsym", py_dl_sym, METH_VARARGS, "find symbol in shared library"}, -#endif - {"alignment", align_func, METH_O, alignment_doc}, - {"sizeof", sizeof_func, METH_O, sizeof_doc}, - {"byref", byref, METH_VARARGS, byref_doc}, - {"addressof", addressof, METH_O, addressof_doc}, - {"call_function", call_function, METH_VARARGS }, - {"call_cdeclfunction", call_cdeclfunction, METH_VARARGS }, - {"PyObj_FromPtr", My_PyObj_FromPtr, METH_VARARGS }, - {"Py_INCREF", My_Py_INCREF, METH_O }, - {"Py_DECREF", My_Py_DECREF, METH_O }, - {NULL, NULL} /* Sentinel */ + {"dlopen", py_dl_open, METH_VARARGS, + "dlopen(name, flag={RTLD_GLOBAL|RTLD_LOCAL}) open a shared library"}, + {"dlclose", py_dl_close, METH_VARARGS, "dlclose a library"}, + {"dlsym", py_dl_sym, METH_VARARGS, "find symbol in shared library"}, +#endif + {"alignment", align_func, METH_O, alignment_doc}, + {"sizeof", sizeof_func, METH_O, sizeof_doc}, + {"byref", byref, METH_VARARGS, byref_doc}, + {"addressof", addressof, METH_O, addressof_doc}, + {"call_function", call_function, METH_VARARGS }, + {"call_cdeclfunction", call_cdeclfunction, METH_VARARGS }, + {"PyObj_FromPtr", My_PyObj_FromPtr, METH_VARARGS }, + {"Py_INCREF", My_Py_INCREF, METH_O }, + {"Py_DECREF", My_Py_DECREF, METH_O }, + {NULL, NULL} /* Sentinel */ }; /* Modified: python/branches/release31-maint/Modules/_ctypes/cfield.c ============================================================================== --- python/branches/release31-maint/Modules/_ctypes/cfield.c (original) +++ python/branches/release31-maint/Modules/_ctypes/cfield.c Sun May 9 18:14:21 2010 @@ -11,10 +11,10 @@ static void pymem_destructor(PyObject *ptr) { - void *p = PyCapsule_GetPointer(ptr, CTYPES_CFIELD_CAPSULE_NAME_PYMEM); - if (p) { - PyMem_Free(p); - } + void *p = PyCapsule_GetPointer(ptr, CTYPES_CFIELD_CAPSULE_NAME_PYMEM); + if (p) { + PyMem_Free(p); + } } @@ -25,9 +25,9 @@ static PyObject * PyCField_new(PyTypeObject *type, PyObject *args, PyObject *kwds) { - CFieldObject *obj; - obj = (CFieldObject *)type->tp_alloc(type, 0); - return (PyObject *)obj; + CFieldObject *obj; + obj = (CFieldObject *)type->tp_alloc(type, 0); + return (PyObject *)obj; } /* @@ -44,297 +44,297 @@ */ PyObject * PyCField_FromDesc(PyObject *desc, Py_ssize_t index, - Py_ssize_t *pfield_size, int bitsize, int *pbitofs, - Py_ssize_t *psize, Py_ssize_t *poffset, Py_ssize_t *palign, - int pack, int big_endian) -{ - CFieldObject *self; - PyObject *proto; - Py_ssize_t size, align, length; - SETFUNC setfunc = NULL; - GETFUNC getfunc = NULL; - StgDictObject *dict; - int fieldtype; + Py_ssize_t *pfield_size, int bitsize, int *pbitofs, + Py_ssize_t *psize, Py_ssize_t *poffset, Py_ssize_t *palign, + int pack, int big_endian) +{ + CFieldObject *self; + PyObject *proto; + Py_ssize_t size, align, length; + SETFUNC setfunc = NULL; + GETFUNC getfunc = NULL; + StgDictObject *dict; + int fieldtype; #define NO_BITFIELD 0 #define NEW_BITFIELD 1 #define CONT_BITFIELD 2 #define EXPAND_BITFIELD 3 - self = (CFieldObject *)PyObject_CallObject((PyObject *)&PyCField_Type, - NULL); - if (self == NULL) - return NULL; - dict = PyType_stgdict(desc); - if (!dict) { - PyErr_SetString(PyExc_TypeError, - "has no _stginfo_"); - Py_DECREF(self); - return NULL; - } - if (bitsize /* this is a bitfield request */ - && *pfield_size /* we have a bitfield open */ + self = (CFieldObject *)PyObject_CallObject((PyObject *)&PyCField_Type, + NULL); + if (self == NULL) + return NULL; + dict = PyType_stgdict(desc); + if (!dict) { + PyErr_SetString(PyExc_TypeError, + "has no _stginfo_"); + Py_DECREF(self); + return NULL; + } + if (bitsize /* this is a bitfield request */ + && *pfield_size /* we have a bitfield open */ #ifdef MS_WIN32 - /* MSVC, GCC with -mms-bitfields */ - && dict->size * 8 == *pfield_size + /* MSVC, GCC with -mms-bitfields */ + && dict->size * 8 == *pfield_size #else - /* GCC */ - && dict->size * 8 <= *pfield_size + /* GCC */ + && dict->size * 8 <= *pfield_size #endif - && (*pbitofs + bitsize) <= *pfield_size) { - /* continue bit field */ - fieldtype = CONT_BITFIELD; + && (*pbitofs + bitsize) <= *pfield_size) { + /* continue bit field */ + fieldtype = CONT_BITFIELD; #ifndef MS_WIN32 - } else if (bitsize /* this is a bitfield request */ - && *pfield_size /* we have a bitfield open */ - && dict->size * 8 >= *pfield_size - && (*pbitofs + bitsize) <= dict->size * 8) { - /* expand bit field */ - fieldtype = EXPAND_BITFIELD; -#endif - } else if (bitsize) { - /* start new bitfield */ - fieldtype = NEW_BITFIELD; - *pbitofs = 0; - *pfield_size = dict->size * 8; - } else { - /* not a bit field */ - fieldtype = NO_BITFIELD; - *pbitofs = 0; - *pfield_size = 0; - } - - size = dict->size; - length = dict->length; - proto = desc; - - /* Field descriptors for 'c_char * n' are be scpecial cased to - return a Python string instead of an Array object instance... - */ - if (PyCArrayTypeObject_Check(proto)) { - StgDictObject *adict = PyType_stgdict(proto); - StgDictObject *idict; - if (adict && adict->proto) { - idict = PyType_stgdict(adict->proto); - if (!idict) { - PyErr_SetString(PyExc_TypeError, - "has no _stginfo_"); - Py_DECREF(self); - return NULL; - } - if (idict->getfunc == _ctypes_get_fielddesc("c")->getfunc) { - struct fielddesc *fd = _ctypes_get_fielddesc("s"); - getfunc = fd->getfunc; - setfunc = fd->setfunc; - } + } else if (bitsize /* this is a bitfield request */ + && *pfield_size /* we have a bitfield open */ + && dict->size * 8 >= *pfield_size + && (*pbitofs + bitsize) <= dict->size * 8) { + /* expand bit field */ + fieldtype = EXPAND_BITFIELD; +#endif + } else if (bitsize) { + /* start new bitfield */ + fieldtype = NEW_BITFIELD; + *pbitofs = 0; + *pfield_size = dict->size * 8; + } else { + /* not a bit field */ + fieldtype = NO_BITFIELD; + *pbitofs = 0; + *pfield_size = 0; + } + + size = dict->size; + length = dict->length; + proto = desc; + + /* Field descriptors for 'c_char * n' are be scpecial cased to + return a Python string instead of an Array object instance... + */ + if (PyCArrayTypeObject_Check(proto)) { + StgDictObject *adict = PyType_stgdict(proto); + StgDictObject *idict; + if (adict && adict->proto) { + idict = PyType_stgdict(adict->proto); + if (!idict) { + PyErr_SetString(PyExc_TypeError, + "has no _stginfo_"); + Py_DECREF(self); + return NULL; + } + if (idict->getfunc == _ctypes_get_fielddesc("c")->getfunc) { + struct fielddesc *fd = _ctypes_get_fielddesc("s"); + getfunc = fd->getfunc; + setfunc = fd->setfunc; + } #ifdef CTYPES_UNICODE - if (idict->getfunc == _ctypes_get_fielddesc("u")->getfunc) { - struct fielddesc *fd = _ctypes_get_fielddesc("U"); - getfunc = fd->getfunc; - setfunc = fd->setfunc; - } -#endif - } - } - - self->setfunc = setfunc; - self->getfunc = getfunc; - self->index = index; - - Py_INCREF(proto); - self->proto = proto; - - switch (fieldtype) { - case NEW_BITFIELD: - if (big_endian) - self->size = (bitsize << 16) + *pfield_size - *pbitofs - bitsize; - else - self->size = (bitsize << 16) + *pbitofs; - *pbitofs = bitsize; - /* fall through */ - case NO_BITFIELD: - if (pack) - align = min(pack, dict->align); - else - align = dict->align; - if (align && *poffset % align) { - Py_ssize_t delta = align - (*poffset % align); - *psize += delta; - *poffset += delta; - } - - if (bitsize == 0) - self->size = size; - *psize += size; - - self->offset = *poffset; - *poffset += size; - - *palign = align; - break; - - case EXPAND_BITFIELD: - *poffset += dict->size - *pfield_size/8; - *psize += dict->size - *pfield_size/8; - - *pfield_size = dict->size * 8; - - if (big_endian) - self->size = (bitsize << 16) + *pfield_size - *pbitofs - bitsize; - else - self->size = (bitsize << 16) + *pbitofs; - - self->offset = *poffset - size; /* poffset is already updated for the NEXT field */ - *pbitofs += bitsize; - break; - - case CONT_BITFIELD: - if (big_endian) - self->size = (bitsize << 16) + *pfield_size - *pbitofs - bitsize; - else - self->size = (bitsize << 16) + *pbitofs; - - self->offset = *poffset - size; /* poffset is already updated for the NEXT field */ - *pbitofs += bitsize; - break; - } + if (idict->getfunc == _ctypes_get_fielddesc("u")->getfunc) { + struct fielddesc *fd = _ctypes_get_fielddesc("U"); + getfunc = fd->getfunc; + setfunc = fd->setfunc; + } +#endif + } + } + + self->setfunc = setfunc; + self->getfunc = getfunc; + self->index = index; + + Py_INCREF(proto); + self->proto = proto; + + switch (fieldtype) { + case NEW_BITFIELD: + if (big_endian) + self->size = (bitsize << 16) + *pfield_size - *pbitofs - bitsize; + else + self->size = (bitsize << 16) + *pbitofs; + *pbitofs = bitsize; + /* fall through */ + case NO_BITFIELD: + if (pack) + align = min(pack, dict->align); + else + align = dict->align; + if (align && *poffset % align) { + Py_ssize_t delta = align - (*poffset % align); + *psize += delta; + *poffset += delta; + } + + if (bitsize == 0) + self->size = size; + *psize += size; + + self->offset = *poffset; + *poffset += size; + + *palign = align; + break; + + case EXPAND_BITFIELD: + *poffset += dict->size - *pfield_size/8; + *psize += dict->size - *pfield_size/8; + + *pfield_size = dict->size * 8; + + if (big_endian) + self->size = (bitsize << 16) + *pfield_size - *pbitofs - bitsize; + else + self->size = (bitsize << 16) + *pbitofs; + + self->offset = *poffset - size; /* poffset is already updated for the NEXT field */ + *pbitofs += bitsize; + break; + + case CONT_BITFIELD: + if (big_endian) + self->size = (bitsize << 16) + *pfield_size - *pbitofs - bitsize; + else + self->size = (bitsize << 16) + *pbitofs; + + self->offset = *poffset - size; /* poffset is already updated for the NEXT field */ + *pbitofs += bitsize; + break; + } - return (PyObject *)self; + return (PyObject *)self; } static int PyCField_set(CFieldObject *self, PyObject *inst, PyObject *value) { - CDataObject *dst; - char *ptr; - assert(CDataObject_Check(inst)); - dst = (CDataObject *)inst; - ptr = dst->b_ptr + self->offset; - if (value == NULL) { - PyErr_SetString(PyExc_TypeError, - "can't delete attribute"); - return -1; - } - return PyCData_set(inst, self->proto, self->setfunc, value, - self->index, self->size, ptr); + CDataObject *dst; + char *ptr; + assert(CDataObject_Check(inst)); + dst = (CDataObject *)inst; + ptr = dst->b_ptr + self->offset; + if (value == NULL) { + PyErr_SetString(PyExc_TypeError, + "can't delete attribute"); + return -1; + } + return PyCData_set(inst, self->proto, self->setfunc, value, + self->index, self->size, ptr); } static PyObject * PyCField_get(CFieldObject *self, PyObject *inst, PyTypeObject *type) { - CDataObject *src; - if (inst == NULL) { - Py_INCREF(self); - return (PyObject *)self; - } - assert(CDataObject_Check(inst)); - src = (CDataObject *)inst; - return PyCData_get(self->proto, self->getfunc, inst, - self->index, self->size, src->b_ptr + self->offset); + CDataObject *src; + if (inst == NULL) { + Py_INCREF(self); + return (PyObject *)self; + } + assert(CDataObject_Check(inst)); + src = (CDataObject *)inst; + return PyCData_get(self->proto, self->getfunc, inst, + self->index, self->size, src->b_ptr + self->offset); } static PyObject * PyCField_get_offset(PyObject *self, void *data) { - return PyLong_FromSsize_t(((CFieldObject *)self)->offset); + return PyLong_FromSsize_t(((CFieldObject *)self)->offset); } static PyObject * PyCField_get_size(PyObject *self, void *data) { - return PyLong_FromSsize_t(((CFieldObject *)self)->size); + return PyLong_FromSsize_t(((CFieldObject *)self)->size); } static PyGetSetDef PyCField_getset[] = { - { "offset", PyCField_get_offset, NULL, "offset in bytes of this field" }, - { "size", PyCField_get_size, NULL, "size in bytes of this field" }, - { NULL, NULL, NULL, NULL }, + { "offset", PyCField_get_offset, NULL, "offset in bytes of this field" }, + { "size", PyCField_get_size, NULL, "size in bytes of this field" }, + { NULL, NULL, NULL, NULL }, }; static int PyCField_traverse(CFieldObject *self, visitproc visit, void *arg) { - Py_VISIT(self->proto); - return 0; + Py_VISIT(self->proto); + return 0; } static int PyCField_clear(CFieldObject *self) { - Py_CLEAR(self->proto); - return 0; + Py_CLEAR(self->proto); + return 0; } static void PyCField_dealloc(PyObject *self) { - PyCField_clear((CFieldObject *)self); - self->ob_type->tp_free((PyObject *)self); + PyCField_clear((CFieldObject *)self); + self->ob_type->tp_free((PyObject *)self); } static PyObject * PyCField_repr(CFieldObject *self) { - PyObject *result; - Py_ssize_t bits = self->size >> 16; - Py_ssize_t size = self->size & 0xFFFF; - const char *name; - - name = ((PyTypeObject *)self->proto)->tp_name; - - if (bits) - result = PyUnicode_FromFormat( - "", - name, self->offset, size, bits); - else - result = PyUnicode_FromFormat( - "", - name, self->offset, size); - return result; + PyObject *result; + Py_ssize_t bits = self->size >> 16; + Py_ssize_t size = self->size & 0xFFFF; + const char *name; + + name = ((PyTypeObject *)self->proto)->tp_name; + + if (bits) + result = PyUnicode_FromFormat( + "", + name, self->offset, size, bits); + else + result = PyUnicode_FromFormat( + "", + name, self->offset, size); + return result; } PyTypeObject PyCField_Type = { - PyVarObject_HEAD_INIT(NULL, 0) - "_ctypes.CField", /* tp_name */ - sizeof(CFieldObject), /* tp_basicsize */ - 0, /* tp_itemsize */ - PyCField_dealloc, /* tp_dealloc */ - 0, /* tp_print */ - 0, /* tp_getattr */ - 0, /* tp_setattr */ - 0, /* tp_reserved */ - (reprfunc)PyCField_repr, /* tp_repr */ - 0, /* tp_as_number */ - 0, /* tp_as_sequence */ - 0, /* tp_as_mapping */ - 0, /* tp_hash */ - 0, /* tp_call */ - 0, /* tp_str */ - 0, /* tp_getattro */ - 0, /* tp_setattro */ - 0, /* tp_as_buffer */ - Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC, /* tp_flags */ - "Structure/Union member", /* tp_doc */ - (traverseproc)PyCField_traverse, /* tp_traverse */ - (inquiry)PyCField_clear, /* tp_clear */ - 0, /* tp_richcompare */ - 0, /* tp_weaklistoffset */ - 0, /* tp_iter */ - 0, /* tp_iternext */ - 0, /* tp_methods */ - 0, /* tp_members */ - PyCField_getset, /* tp_getset */ - 0, /* tp_base */ - 0, /* tp_dict */ - (descrgetfunc)PyCField_get, /* tp_descr_get */ - (descrsetfunc)PyCField_set, /* tp_descr_set */ - 0, /* tp_dictoffset */ - 0, /* tp_init */ - 0, /* tp_alloc */ - PyCField_new, /* tp_new */ - 0, /* tp_free */ + PyVarObject_HEAD_INIT(NULL, 0) + "_ctypes.CField", /* tp_name */ + sizeof(CFieldObject), /* tp_basicsize */ + 0, /* tp_itemsize */ + PyCField_dealloc, /* tp_dealloc */ + 0, /* tp_print */ + 0, /* tp_getattr */ + 0, /* tp_setattr */ + 0, /* tp_reserved */ + (reprfunc)PyCField_repr, /* tp_repr */ + 0, /* tp_as_number */ + 0, /* tp_as_sequence */ + 0, /* tp_as_mapping */ + 0, /* tp_hash */ + 0, /* tp_call */ + 0, /* tp_str */ + 0, /* tp_getattro */ + 0, /* tp_setattro */ + 0, /* tp_as_buffer */ + Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC, /* tp_flags */ + "Structure/Union member", /* tp_doc */ + (traverseproc)PyCField_traverse, /* tp_traverse */ + (inquiry)PyCField_clear, /* tp_clear */ + 0, /* tp_richcompare */ + 0, /* tp_weaklistoffset */ + 0, /* tp_iter */ + 0, /* tp_iternext */ + 0, /* tp_methods */ + 0, /* tp_members */ + PyCField_getset, /* tp_getset */ + 0, /* tp_base */ + 0, /* tp_dict */ + (descrgetfunc)PyCField_get, /* tp_descr_get */ + (descrsetfunc)PyCField_set, /* tp_descr_set */ + 0, /* tp_dictoffset */ + 0, /* tp_init */ + 0, /* tp_alloc */ + PyCField_new, /* tp_new */ + 0, /* tp_free */ }; - + /******************************************************************/ /* Accessor functions @@ -347,18 +347,18 @@ static int get_long(PyObject *v, long *p) { - long x; + long x; - if (PyFloat_Check(v)) { - PyErr_SetString(PyExc_TypeError, - "int expected instead of float"); - return -1; - } - x = PyLong_AsUnsignedLongMask(v); - if (x == -1 && PyErr_Occurred()) - return -1; - *p = x; - return 0; + if (PyFloat_Check(v)) { + PyErr_SetString(PyExc_TypeError, + "int expected instead of float"); + return -1; + } + x = PyLong_AsUnsignedLongMask(v); + if (x == -1 && PyErr_Occurred()) + return -1; + *p = x; + return 0; } /* Same, but handling unsigned long */ @@ -366,18 +366,18 @@ static int get_ulong(PyObject *v, unsigned long *p) { - unsigned long x; + unsigned long x; - if (PyFloat_Check(v)) { - PyErr_SetString(PyExc_TypeError, - "int expected instead of float"); - return -1; - } - x = PyLong_AsUnsignedLongMask(v); - if (x == (unsigned long)-1 && PyErr_Occurred()) - return -1; - *p = x; - return 0; + if (PyFloat_Check(v)) { + PyErr_SetString(PyExc_TypeError, + "int expected instead of float"); + return -1; + } + x = PyLong_AsUnsignedLongMask(v); + if (x == (unsigned long)-1 && PyErr_Occurred()) + return -1; + *p = x; + return 0; } #ifdef HAVE_LONG_LONG @@ -387,17 +387,17 @@ static int get_longlong(PyObject *v, PY_LONG_LONG *p) { - PY_LONG_LONG x; - if (PyFloat_Check(v)) { - PyErr_SetString(PyExc_TypeError, - "int expected instead of float"); - return -1; - } - x = PyLong_AsUnsignedLongLongMask(v); - if (x == -1 && PyErr_Occurred()) - return -1; - *p = x; - return 0; + PY_LONG_LONG x; + if (PyFloat_Check(v)) { + PyErr_SetString(PyExc_TypeError, + "int expected instead of float"); + return -1; + } + x = PyLong_AsUnsignedLongLongMask(v); + if (x == -1 && PyErr_Occurred()) + return -1; + *p = x; + return 0; } /* Same, but handling native unsigned long long. */ @@ -405,17 +405,17 @@ static int get_ulonglong(PyObject *v, unsigned PY_LONG_LONG *p) { - unsigned PY_LONG_LONG x; - if (PyFloat_Check(v)) { - PyErr_SetString(PyExc_TypeError, - "int expected instead of float"); - return -1; - } - x = PyLong_AsUnsignedLongLongMask(v); - if (x == (unsigned PY_LONG_LONG)-1 && PyErr_Occurred()) - return -1; - *p = x; - return 0; + unsigned PY_LONG_LONG x; + if (PyFloat_Check(v)) { + PyErr_SetString(PyExc_TypeError, + "int expected instead of float"); + return -1; + } + x = PyLong_AsUnsignedLongLongMask(v); + if (x == (unsigned PY_LONG_LONG)-1 && PyErr_Occurred()) + return -1; + *p = x; + return 0; } #endif @@ -438,49 +438,49 @@ /* This macro CHANGES the first parameter IN PLACE. For proper sign handling, we must first shift left, then right. */ -#define GET_BITFIELD(v, size) \ - if (NUM_BITS(size)) { \ - v <<= (sizeof(v)*8 - LOW_BIT(size) - NUM_BITS(size)); \ - v >>= (sizeof(v)*8 - NUM_BITS(size)); \ - } +#define GET_BITFIELD(v, size) \ + if (NUM_BITS(size)) { \ + v <<= (sizeof(v)*8 - LOW_BIT(size) - NUM_BITS(size)); \ + v >>= (sizeof(v)*8 - NUM_BITS(size)); \ + } /* This macro RETURNS the first parameter with the bit field CHANGED. */ -#define SET(x, v, size) \ - (NUM_BITS(size) ? \ - ( ( x & ~(BIT_MASK(size) << LOW_BIT(size)) ) | ( (v & BIT_MASK(size)) << LOW_BIT(size) ) ) \ - : v) +#define SET(x, v, size) \ + (NUM_BITS(size) ? \ + ( ( x & ~(BIT_MASK(size) << LOW_BIT(size)) ) | ( (v & BIT_MASK(size)) << LOW_BIT(size) ) ) \ + : v) /* byte swapping macros */ -#define SWAP_2(v) \ - ( ( (v >> 8) & 0x00FF) | \ - ( (v << 8) & 0xFF00) ) - -#define SWAP_4(v) \ - ( ( (v & 0x000000FF) << 24 ) | \ - ( (v & 0x0000FF00) << 8 ) | \ - ( (v & 0x00FF0000) >> 8 ) | \ - ( ((v >> 24) & 0xFF)) ) +#define SWAP_2(v) \ + ( ( (v >> 8) & 0x00FF) | \ + ( (v << 8) & 0xFF00) ) + +#define SWAP_4(v) \ + ( ( (v & 0x000000FF) << 24 ) | \ + ( (v & 0x0000FF00) << 8 ) | \ + ( (v & 0x00FF0000) >> 8 ) | \ + ( ((v >> 24) & 0xFF)) ) #ifdef _MSC_VER -#define SWAP_8(v) \ - ( ( (v & 0x00000000000000FFL) << 56 ) | \ - ( (v & 0x000000000000FF00L) << 40 ) | \ - ( (v & 0x0000000000FF0000L) << 24 ) | \ - ( (v & 0x00000000FF000000L) << 8 ) | \ - ( (v & 0x000000FF00000000L) >> 8 ) | \ - ( (v & 0x0000FF0000000000L) >> 24 ) | \ - ( (v & 0x00FF000000000000L) >> 40 ) | \ - ( ((v >> 56) & 0xFF)) ) +#define SWAP_8(v) \ + ( ( (v & 0x00000000000000FFL) << 56 ) | \ + ( (v & 0x000000000000FF00L) << 40 ) | \ + ( (v & 0x0000000000FF0000L) << 24 ) | \ + ( (v & 0x00000000FF000000L) << 8 ) | \ + ( (v & 0x000000FF00000000L) >> 8 ) | \ + ( (v & 0x0000FF0000000000L) >> 24 ) | \ + ( (v & 0x00FF000000000000L) >> 40 ) | \ + ( ((v >> 56) & 0xFF)) ) #else -#define SWAP_8(v) \ - ( ( (v & 0x00000000000000FFLL) << 56 ) | \ - ( (v & 0x000000000000FF00LL) << 40 ) | \ - ( (v & 0x0000000000FF0000LL) << 24 ) | \ - ( (v & 0x00000000FF000000LL) << 8 ) | \ - ( (v & 0x000000FF00000000LL) >> 8 ) | \ - ( (v & 0x0000FF0000000000LL) >> 24 ) | \ - ( (v & 0x00FF000000000000LL) >> 40 ) | \ - ( ((v >> 56) & 0xFF)) ) +#define SWAP_8(v) \ + ( ( (v & 0x00000000000000FFLL) << 56 ) | \ + ( (v & 0x000000000000FF00LL) << 40 ) | \ + ( (v & 0x0000000000FF0000LL) << 24 ) | \ + ( (v & 0x00000000FF000000LL) << 8 ) | \ + ( (v & 0x000000FF00000000LL) >> 8 ) | \ + ( (v & 0x0000FF0000000000LL) >> 24 ) | \ + ( (v & 0x00FF000000000000LL) >> 40 ) | \ + ( ((v >> 56) & 0xFF)) ) #endif #define SWAP_INT SWAP_4 @@ -517,184 +517,184 @@ static PyObject * b_set(void *ptr, PyObject *value, Py_ssize_t size) { - long val; - if (get_long(value, &val) < 0) - return NULL; - *(signed char *)ptr = (signed char)SET(*(signed char *)ptr, (signed char)val, size); - _RET(value); + long val; + if (get_long(value, &val) < 0) + return NULL; + *(signed char *)ptr = (signed char)SET(*(signed char *)ptr, (signed char)val, size); + _RET(value); } static PyObject * b_get(void *ptr, Py_ssize_t size) { - signed char val = *(signed char *)ptr; - GET_BITFIELD(val, size); - return PyLong_FromLong(val); + signed char val = *(signed char *)ptr; + GET_BITFIELD(val, size); + return PyLong_FromLong(val); } static PyObject * B_set(void *ptr, PyObject *value, Py_ssize_t size) { - unsigned long val; - if (get_ulong(value, &val) < 0) - return NULL; - *(unsigned char *)ptr = (unsigned char)SET(*(unsigned char*)ptr, - (unsigned short)val, size); - _RET(value); + unsigned long val; + if (get_ulong(value, &val) < 0) + return NULL; + *(unsigned char *)ptr = (unsigned char)SET(*(unsigned char*)ptr, + (unsigned short)val, size); + _RET(value); } static PyObject * B_get(void *ptr, Py_ssize_t size) { - unsigned char val = *(unsigned char *)ptr; - GET_BITFIELD(val, size); - return PyLong_FromLong(val); + unsigned char val = *(unsigned char *)ptr; + GET_BITFIELD(val, size); + return PyLong_FromLong(val); } static PyObject * h_set(void *ptr, PyObject *value, Py_ssize_t size) { - long val; - short x; - if (get_long(value, &val) < 0) - return NULL; - memcpy(&x, ptr, sizeof(x)); - x = SET(x, (short)val, size); - memcpy(ptr, &x, sizeof(x)); - _RET(value); + long val; + short x; + if (get_long(value, &val) < 0) + return NULL; + memcpy(&x, ptr, sizeof(x)); + x = SET(x, (short)val, size); + memcpy(ptr, &x, sizeof(x)); + _RET(value); } static PyObject * h_set_sw(void *ptr, PyObject *value, Py_ssize_t size) { - long val; - short field; - if (get_long(value, &val) < 0) - return NULL; - memcpy(&field, ptr, sizeof(field)); - field = SWAP_2(field); - field = SET(field, (short)val, size); - field = SWAP_2(field); - memcpy(ptr, &field, sizeof(field)); - _RET(value); + long val; + short field; + if (get_long(value, &val) < 0) + return NULL; + memcpy(&field, ptr, sizeof(field)); + field = SWAP_2(field); + field = SET(field, (short)val, size); + field = SWAP_2(field); + memcpy(ptr, &field, sizeof(field)); + _RET(value); } static PyObject * h_get(void *ptr, Py_ssize_t size) { - short val; - memcpy(&val, ptr, sizeof(val)); - GET_BITFIELD(val, size); - return PyLong_FromLong((long)val); + short val; + memcpy(&val, ptr, sizeof(val)); + GET_BITFIELD(val, size); + return PyLong_FromLong((long)val); } static PyObject * h_get_sw(void *ptr, Py_ssize_t size) { - short val; - memcpy(&val, ptr, sizeof(val)); - val = SWAP_2(val); - GET_BITFIELD(val, size); - return PyLong_FromLong(val); + short val; + memcpy(&val, ptr, sizeof(val)); + val = SWAP_2(val); + GET_BITFIELD(val, size); + return PyLong_FromLong(val); } static PyObject * H_set(void *ptr, PyObject *value, Py_ssize_t size) { - unsigned long val; - unsigned short x; - if (get_ulong(value, &val) < 0) - return NULL; - memcpy(&x, ptr, sizeof(x)); - x = SET(x, (unsigned short)val, size); - memcpy(ptr, &x, sizeof(x)); - _RET(value); + unsigned long val; + unsigned short x; + if (get_ulong(value, &val) < 0) + return NULL; + memcpy(&x, ptr, sizeof(x)); + x = SET(x, (unsigned short)val, size); + memcpy(ptr, &x, sizeof(x)); + _RET(value); } static PyObject * H_set_sw(void *ptr, PyObject *value, Py_ssize_t size) { - unsigned long val; - unsigned short field; - if (get_ulong(value, &val) < 0) - return NULL; - memcpy(&field, ptr, sizeof(field)); - field = SWAP_2(field); - field = SET(field, (unsigned short)val, size); - field = SWAP_2(field); - memcpy(ptr, &field, sizeof(field)); - _RET(value); + unsigned long val; + unsigned short field; + if (get_ulong(value, &val) < 0) + return NULL; + memcpy(&field, ptr, sizeof(field)); + field = SWAP_2(field); + field = SET(field, (unsigned short)val, size); + field = SWAP_2(field); + memcpy(ptr, &field, sizeof(field)); + _RET(value); } static PyObject * H_get(void *ptr, Py_ssize_t size) { - unsigned short val; - memcpy(&val, ptr, sizeof(val)); - GET_BITFIELD(val, size); - return PyLong_FromLong(val); + unsigned short val; + memcpy(&val, ptr, sizeof(val)); + GET_BITFIELD(val, size); + return PyLong_FromLong(val); } static PyObject * H_get_sw(void *ptr, Py_ssize_t size) { - unsigned short val; - memcpy(&val, ptr, sizeof(val)); - val = SWAP_2(val); - GET_BITFIELD(val, size); - return PyLong_FromLong(val); + unsigned short val; + memcpy(&val, ptr, sizeof(val)); + val = SWAP_2(val); + GET_BITFIELD(val, size); + return PyLong_FromLong(val); } static PyObject * i_set(void *ptr, PyObject *value, Py_ssize_t size) { - long val; - int x; - if (get_long(value, &val) < 0) - return NULL; - memcpy(&x, ptr, sizeof(x)); - x = SET(x, (int)val, size); - memcpy(ptr, &x, sizeof(x)); - _RET(value); + long val; + int x; + if (get_long(value, &val) < 0) + return NULL; + memcpy(&x, ptr, sizeof(x)); + x = SET(x, (int)val, size); + memcpy(ptr, &x, sizeof(x)); + _RET(value); } static PyObject * i_set_sw(void *ptr, PyObject *value, Py_ssize_t size) { - long val; - int field; - if (get_long(value, &val) < 0) - return NULL; - memcpy(&field, ptr, sizeof(field)); - field = SWAP_INT(field); - field = SET(field, (int)val, size); - field = SWAP_INT(field); - memcpy(ptr, &field, sizeof(field)); - _RET(value); + long val; + int field; + if (get_long(value, &val) < 0) + return NULL; + memcpy(&field, ptr, sizeof(field)); + field = SWAP_INT(field); + field = SET(field, (int)val, size); + field = SWAP_INT(field); + memcpy(ptr, &field, sizeof(field)); + _RET(value); } static PyObject * i_get(void *ptr, Py_ssize_t size) { - int val; - memcpy(&val, ptr, sizeof(val)); - GET_BITFIELD(val, size); - return PyLong_FromLong(val); + int val; + memcpy(&val, ptr, sizeof(val)); + GET_BITFIELD(val, size); + return PyLong_FromLong(val); } static PyObject * i_get_sw(void *ptr, Py_ssize_t size) { - int val; - memcpy(&val, ptr, sizeof(val)); - val = SWAP_INT(val); - GET_BITFIELD(val, size); - return PyLong_FromLong(val); + int val; + memcpy(&val, ptr, sizeof(val)); + val = SWAP_INT(val); + GET_BITFIELD(val, size); + return PyLong_FromLong(val); } #ifdef MS_WIN32 @@ -702,22 +702,22 @@ static PyObject * vBOOL_set(void *ptr, PyObject *value, Py_ssize_t size) { - switch (PyObject_IsTrue(value)) { - case -1: - return NULL; - case 0: - *(short int *)ptr = VARIANT_FALSE; - _RET(value); - default: - *(short int *)ptr = VARIANT_TRUE; - _RET(value); - } + switch (PyObject_IsTrue(value)) { + case -1: + return NULL; + case 0: + *(short int *)ptr = VARIANT_FALSE; + _RET(value); + default: + *(short int *)ptr = VARIANT_TRUE; + _RET(value); + } } static PyObject * vBOOL_get(void *ptr, Py_ssize_t size) { - return PyBool_FromLong((long)*(short int *)ptr); + return PyBool_FromLong((long)*(short int *)ptr); } #endif @@ -732,260 +732,260 @@ static PyObject * bool_set(void *ptr, PyObject *value, Py_ssize_t size) { - switch (PyObject_IsTrue(value)) { - case -1: - return NULL; - case 0: - *(BOOL_TYPE *)ptr = 0; - _RET(value); - default: - *(BOOL_TYPE *)ptr = 1; - _RET(value); - } + switch (PyObject_IsTrue(value)) { + case -1: + return NULL; + case 0: + *(BOOL_TYPE *)ptr = 0; + _RET(value); + default: + *(BOOL_TYPE *)ptr = 1; + _RET(value); + } } static PyObject * bool_get(void *ptr, Py_ssize_t size) { - return PyBool_FromLong((long)*(BOOL_TYPE *)ptr); + return PyBool_FromLong((long)*(BOOL_TYPE *)ptr); } static PyObject * I_set(void *ptr, PyObject *value, Py_ssize_t size) { - unsigned long val; - unsigned int x; - if (get_ulong(value, &val) < 0) - return NULL; - memcpy(&x, ptr, sizeof(x)); - x = SET(x, (unsigned int)val, size); - memcpy(ptr, &x, sizeof(x)); - _RET(value); + unsigned long val; + unsigned int x; + if (get_ulong(value, &val) < 0) + return NULL; + memcpy(&x, ptr, sizeof(x)); + x = SET(x, (unsigned int)val, size); + memcpy(ptr, &x, sizeof(x)); + _RET(value); } static PyObject * I_set_sw(void *ptr, PyObject *value, Py_ssize_t size) { - unsigned long val; - unsigned int field; - if (get_ulong(value, &val) < 0) - return NULL; - memcpy(&field, ptr, sizeof(field)); - field = (unsigned int)SET(field, (unsigned int)val, size); - field = SWAP_INT(field); - memcpy(ptr, &field, sizeof(field)); - _RET(value); + unsigned long val; + unsigned int field; + if (get_ulong(value, &val) < 0) + return NULL; + memcpy(&field, ptr, sizeof(field)); + field = (unsigned int)SET(field, (unsigned int)val, size); + field = SWAP_INT(field); + memcpy(ptr, &field, sizeof(field)); + _RET(value); } static PyObject * I_get(void *ptr, Py_ssize_t size) { - unsigned int val; - memcpy(&val, ptr, sizeof(val)); - GET_BITFIELD(val, size); - return PyLong_FromUnsignedLong(val); + unsigned int val; + memcpy(&val, ptr, sizeof(val)); + GET_BITFIELD(val, size); + return PyLong_FromUnsignedLong(val); } static PyObject * I_get_sw(void *ptr, Py_ssize_t size) { - unsigned int val; - memcpy(&val, ptr, sizeof(val)); - val = SWAP_INT(val); - GET_BITFIELD(val, size); - return PyLong_FromUnsignedLong(val); + unsigned int val; + memcpy(&val, ptr, sizeof(val)); + val = SWAP_INT(val); + GET_BITFIELD(val, size); + return PyLong_FromUnsignedLong(val); } static PyObject * l_set(void *ptr, PyObject *value, Py_ssize_t size) { - long val; - long x; - if (get_long(value, &val) < 0) - return NULL; - memcpy(&x, ptr, sizeof(x)); - x = SET(x, val, size); - memcpy(ptr, &x, sizeof(x)); - _RET(value); + long val; + long x; + if (get_long(value, &val) < 0) + return NULL; + memcpy(&x, ptr, sizeof(x)); + x = SET(x, val, size); + memcpy(ptr, &x, sizeof(x)); + _RET(value); } static PyObject * l_set_sw(void *ptr, PyObject *value, Py_ssize_t size) { - long val; - long field; - if (get_long(value, &val) < 0) - return NULL; - memcpy(&field, ptr, sizeof(field)); - field = SWAP_LONG(field); - field = (long)SET(field, val, size); - field = SWAP_LONG(field); - memcpy(ptr, &field, sizeof(field)); - _RET(value); + long val; + long field; + if (get_long(value, &val) < 0) + return NULL; + memcpy(&field, ptr, sizeof(field)); + field = SWAP_LONG(field); + field = (long)SET(field, val, size); + field = SWAP_LONG(field); + memcpy(ptr, &field, sizeof(field)); + _RET(value); } static PyObject * l_get(void *ptr, Py_ssize_t size) { - long val; - memcpy(&val, ptr, sizeof(val)); - GET_BITFIELD(val, size); - return PyLong_FromLong(val); + long val; + memcpy(&val, ptr, sizeof(val)); + GET_BITFIELD(val, size); + return PyLong_FromLong(val); } static PyObject * l_get_sw(void *ptr, Py_ssize_t size) { - long val; - memcpy(&val, ptr, sizeof(val)); - val = SWAP_LONG(val); - GET_BITFIELD(val, size); - return PyLong_FromLong(val); + long val; + memcpy(&val, ptr, sizeof(val)); + val = SWAP_LONG(val); + GET_BITFIELD(val, size); + return PyLong_FromLong(val); } static PyObject * L_set(void *ptr, PyObject *value, Py_ssize_t size) { - unsigned long val; - unsigned long x; - if (get_ulong(value, &val) < 0) - return NULL; - memcpy(&x, ptr, sizeof(x)); - x = SET(x, val, size); - memcpy(ptr, &x, sizeof(x)); - _RET(value); + unsigned long val; + unsigned long x; + if (get_ulong(value, &val) < 0) + return NULL; + memcpy(&x, ptr, sizeof(x)); + x = SET(x, val, size); + memcpy(ptr, &x, sizeof(x)); + _RET(value); } static PyObject * L_set_sw(void *ptr, PyObject *value, Py_ssize_t size) { - unsigned long val; - unsigned long field; - if (get_ulong(value, &val) < 0) - return NULL; - memcpy(&field, ptr, sizeof(field)); - field = SWAP_LONG(field); - field = (unsigned long)SET(field, val, size); - field = SWAP_LONG(field); - memcpy(ptr, &field, sizeof(field)); - _RET(value); + unsigned long val; + unsigned long field; + if (get_ulong(value, &val) < 0) + return NULL; + memcpy(&field, ptr, sizeof(field)); + field = SWAP_LONG(field); + field = (unsigned long)SET(field, val, size); + field = SWAP_LONG(field); + memcpy(ptr, &field, sizeof(field)); + _RET(value); } static PyObject * L_get(void *ptr, Py_ssize_t size) { - unsigned long val; - memcpy(&val, ptr, sizeof(val)); - GET_BITFIELD(val, size); - return PyLong_FromUnsignedLong(val); + unsigned long val; + memcpy(&val, ptr, sizeof(val)); + GET_BITFIELD(val, size); + return PyLong_FromUnsignedLong(val); } static PyObject * L_get_sw(void *ptr, Py_ssize_t size) { - unsigned long val; - memcpy(&val, ptr, sizeof(val)); - val = SWAP_LONG(val); - GET_BITFIELD(val, size); - return PyLong_FromUnsignedLong(val); + unsigned long val; + memcpy(&val, ptr, sizeof(val)); + val = SWAP_LONG(val); + GET_BITFIELD(val, size); + return PyLong_FromUnsignedLong(val); } #ifdef HAVE_LONG_LONG static PyObject * q_set(void *ptr, PyObject *value, Py_ssize_t size) { - PY_LONG_LONG val; - PY_LONG_LONG x; - if (get_longlong(value, &val) < 0) - return NULL; - memcpy(&x, ptr, sizeof(x)); - x = SET(x, val, size); - memcpy(ptr, &x, sizeof(x)); - _RET(value); + PY_LONG_LONG val; + PY_LONG_LONG x; + if (get_longlong(value, &val) < 0) + return NULL; + memcpy(&x, ptr, sizeof(x)); + x = SET(x, val, size); + memcpy(ptr, &x, sizeof(x)); + _RET(value); } static PyObject * q_set_sw(void *ptr, PyObject *value, Py_ssize_t size) { - PY_LONG_LONG val; - PY_LONG_LONG field; - if (get_longlong(value, &val) < 0) - return NULL; - memcpy(&field, ptr, sizeof(field)); - field = SWAP_8(field); - field = (PY_LONG_LONG)SET(field, val, size); - field = SWAP_8(field); - memcpy(ptr, &field, sizeof(field)); - _RET(value); + PY_LONG_LONG val; + PY_LONG_LONG field; + if (get_longlong(value, &val) < 0) + return NULL; + memcpy(&field, ptr, sizeof(field)); + field = SWAP_8(field); + field = (PY_LONG_LONG)SET(field, val, size); + field = SWAP_8(field); + memcpy(ptr, &field, sizeof(field)); + _RET(value); } static PyObject * q_get(void *ptr, Py_ssize_t size) { - PY_LONG_LONG val; - memcpy(&val, ptr, sizeof(val)); - GET_BITFIELD(val, size); - return PyLong_FromLongLong(val); + PY_LONG_LONG val; + memcpy(&val, ptr, sizeof(val)); + GET_BITFIELD(val, size); + return PyLong_FromLongLong(val); } static PyObject * q_get_sw(void *ptr, Py_ssize_t size) { - PY_LONG_LONG val; - memcpy(&val, ptr, sizeof(val)); - val = SWAP_8(val); - GET_BITFIELD(val, size); - return PyLong_FromLongLong(val); + PY_LONG_LONG val; + memcpy(&val, ptr, sizeof(val)); + val = SWAP_8(val); + GET_BITFIELD(val, size); + return PyLong_FromLongLong(val); } static PyObject * Q_set(void *ptr, PyObject *value, Py_ssize_t size) { - unsigned PY_LONG_LONG val; - unsigned PY_LONG_LONG x; - if (get_ulonglong(value, &val) < 0) - return NULL; - memcpy(&x, ptr, sizeof(x)); - x = SET(x, val, size); - memcpy(ptr, &x, sizeof(x)); - _RET(value); + unsigned PY_LONG_LONG val; + unsigned PY_LONG_LONG x; + if (get_ulonglong(value, &val) < 0) + return NULL; + memcpy(&x, ptr, sizeof(x)); + x = SET(x, val, size); + memcpy(ptr, &x, sizeof(x)); + _RET(value); } static PyObject * Q_set_sw(void *ptr, PyObject *value, Py_ssize_t size) { - unsigned PY_LONG_LONG val; - unsigned PY_LONG_LONG field; - if (get_ulonglong(value, &val) < 0) - return NULL; - memcpy(&field, ptr, sizeof(field)); - field = SWAP_8(field); - field = (unsigned PY_LONG_LONG)SET(field, val, size); - field = SWAP_8(field); - memcpy(ptr, &field, sizeof(field)); - _RET(value); + unsigned PY_LONG_LONG val; + unsigned PY_LONG_LONG field; + if (get_ulonglong(value, &val) < 0) + return NULL; + memcpy(&field, ptr, sizeof(field)); + field = SWAP_8(field); + field = (unsigned PY_LONG_LONG)SET(field, val, size); + field = SWAP_8(field); + memcpy(ptr, &field, sizeof(field)); + _RET(value); } static PyObject * Q_get(void *ptr, Py_ssize_t size) { - unsigned PY_LONG_LONG val; - memcpy(&val, ptr, sizeof(val)); - GET_BITFIELD(val, size); - return PyLong_FromUnsignedLongLong(val); + unsigned PY_LONG_LONG val; + memcpy(&val, ptr, sizeof(val)); + GET_BITFIELD(val, size); + return PyLong_FromUnsignedLongLong(val); } static PyObject * Q_get_sw(void *ptr, Py_ssize_t size) { - unsigned PY_LONG_LONG val; - memcpy(&val, ptr, sizeof(val)); - val = SWAP_8(val); - GET_BITFIELD(val, size); - return PyLong_FromUnsignedLongLong(val); + unsigned PY_LONG_LONG val; + memcpy(&val, ptr, sizeof(val)); + val = SWAP_8(val); + GET_BITFIELD(val, size); + return PyLong_FromUnsignedLongLong(val); } #endif @@ -997,136 +997,136 @@ static PyObject * g_set(void *ptr, PyObject *value, Py_ssize_t size) { - long double x; + long double x; - x = PyFloat_AsDouble(value); - if (x == -1 && PyErr_Occurred()) { - PyErr_Format(PyExc_TypeError, - " float expected instead of %s instance", - value->ob_type->tp_name); - return NULL; - } - memcpy(ptr, &x, sizeof(long double)); - _RET(value); + x = PyFloat_AsDouble(value); + if (x == -1 && PyErr_Occurred()) { + PyErr_Format(PyExc_TypeError, + " float expected instead of %s instance", + value->ob_type->tp_name); + return NULL; + } + memcpy(ptr, &x, sizeof(long double)); + _RET(value); } static PyObject * g_get(void *ptr, Py_ssize_t size) { - long double val; - memcpy(&val, ptr, sizeof(long double)); - return PyFloat_FromDouble(val); + long double val; + memcpy(&val, ptr, sizeof(long double)); + return PyFloat_FromDouble(val); } static PyObject * d_set(void *ptr, PyObject *value, Py_ssize_t size) { - double x; + double x; - x = PyFloat_AsDouble(value); - if (x == -1 && PyErr_Occurred()) { - PyErr_Format(PyExc_TypeError, - " float expected instead of %s instance", - value->ob_type->tp_name); - return NULL; - } - memcpy(ptr, &x, sizeof(double)); - _RET(value); + x = PyFloat_AsDouble(value); + if (x == -1 && PyErr_Occurred()) { + PyErr_Format(PyExc_TypeError, + " float expected instead of %s instance", + value->ob_type->tp_name); + return NULL; + } + memcpy(ptr, &x, sizeof(double)); + _RET(value); } static PyObject * d_get(void *ptr, Py_ssize_t size) { - double val; - memcpy(&val, ptr, sizeof(val)); - return PyFloat_FromDouble(val); + double val; + memcpy(&val, ptr, sizeof(val)); + return PyFloat_FromDouble(val); } static PyObject * d_set_sw(void *ptr, PyObject *value, Py_ssize_t size) { - double x; + double x; - x = PyFloat_AsDouble(value); - if (x == -1 && PyErr_Occurred()) { - PyErr_Format(PyExc_TypeError, - " float expected instead of %s instance", - value->ob_type->tp_name); - return NULL; - } + x = PyFloat_AsDouble(value); + if (x == -1 && PyErr_Occurred()) { + PyErr_Format(PyExc_TypeError, + " float expected instead of %s instance", + value->ob_type->tp_name); + return NULL; + } #ifdef WORDS_BIGENDIAN - if (_PyFloat_Pack8(x, (unsigned char *)ptr, 1)) - return NULL; + if (_PyFloat_Pack8(x, (unsigned char *)ptr, 1)) + return NULL; #else - if (_PyFloat_Pack8(x, (unsigned char *)ptr, 0)) - return NULL; + if (_PyFloat_Pack8(x, (unsigned char *)ptr, 0)) + return NULL; #endif - _RET(value); + _RET(value); } static PyObject * d_get_sw(void *ptr, Py_ssize_t size) { #ifdef WORDS_BIGENDIAN - return PyFloat_FromDouble(_PyFloat_Unpack8(ptr, 1)); + return PyFloat_FromDouble(_PyFloat_Unpack8(ptr, 1)); #else - return PyFloat_FromDouble(_PyFloat_Unpack8(ptr, 0)); + return PyFloat_FromDouble(_PyFloat_Unpack8(ptr, 0)); #endif } static PyObject * f_set(void *ptr, PyObject *value, Py_ssize_t size) { - float x; + float x; - x = (float)PyFloat_AsDouble(value); - if (x == -1 && PyErr_Occurred()) { - PyErr_Format(PyExc_TypeError, - " float expected instead of %s instance", - value->ob_type->tp_name); - return NULL; - } - memcpy(ptr, &x, sizeof(x)); - _RET(value); + x = (float)PyFloat_AsDouble(value); + if (x == -1 && PyErr_Occurred()) { + PyErr_Format(PyExc_TypeError, + " float expected instead of %s instance", + value->ob_type->tp_name); + return NULL; + } + memcpy(ptr, &x, sizeof(x)); + _RET(value); } static PyObject * f_get(void *ptr, Py_ssize_t size) { - float val; - memcpy(&val, ptr, sizeof(val)); - return PyFloat_FromDouble(val); + float val; + memcpy(&val, ptr, sizeof(val)); + return PyFloat_FromDouble(val); } static PyObject * f_set_sw(void *ptr, PyObject *value, Py_ssize_t size) { - float x; + float x; - x = (float)PyFloat_AsDouble(value); - if (x == -1 && PyErr_Occurred()) { - PyErr_Format(PyExc_TypeError, - " float expected instead of %s instance", - value->ob_type->tp_name); - return NULL; - } + x = (float)PyFloat_AsDouble(value); + if (x == -1 && PyErr_Occurred()) { + PyErr_Format(PyExc_TypeError, + " float expected instead of %s instance", + value->ob_type->tp_name); + return NULL; + } #ifdef WORDS_BIGENDIAN - if (_PyFloat_Pack4(x, (unsigned char *)ptr, 1)) - return NULL; + if (_PyFloat_Pack4(x, (unsigned char *)ptr, 1)) + return NULL; #else - if (_PyFloat_Pack4(x, (unsigned char *)ptr, 0)) - return NULL; + if (_PyFloat_Pack4(x, (unsigned char *)ptr, 0)) + return NULL; #endif - _RET(value); + _RET(value); } static PyObject * f_get_sw(void *ptr, Py_ssize_t size) { #ifdef WORDS_BIGENDIAN - return PyFloat_FromDouble(_PyFloat_Unpack4(ptr, 1)); + return PyFloat_FromDouble(_PyFloat_Unpack4(ptr, 1)); #else - return PyFloat_FromDouble(_PyFloat_Unpack4(ptr, 0)); + return PyFloat_FromDouble(_PyFloat_Unpack4(ptr, 0)); #endif } @@ -1143,72 +1143,72 @@ static PyObject * O_get(void *ptr, Py_ssize_t size) { - PyObject *ob = *(PyObject **)ptr; - if (ob == NULL) { - if (!PyErr_Occurred()) - /* Set an error if not yet set */ - PyErr_SetString(PyExc_ValueError, - "PyObject is NULL"); - return NULL; - } - Py_INCREF(ob); - return ob; + PyObject *ob = *(PyObject **)ptr; + if (ob == NULL) { + if (!PyErr_Occurred()) + /* Set an error if not yet set */ + PyErr_SetString(PyExc_ValueError, + "PyObject is NULL"); + return NULL; + } + Py_INCREF(ob); + return ob; } static PyObject * O_set(void *ptr, PyObject *value, Py_ssize_t size) { - /* Hm, does the memory block need it's own refcount or not? */ - *(PyObject **)ptr = value; - Py_INCREF(value); - return value; + /* Hm, does the memory block need it's own refcount or not? */ + *(PyObject **)ptr = value; + Py_INCREF(value); + return value; } static PyObject * c_set(void *ptr, PyObject *value, Py_ssize_t size) { - if (PyUnicode_Check(value)) { - value = PyUnicode_AsEncodedString(value, - _ctypes_conversion_encoding, - _ctypes_conversion_errors); - if (value == NULL) - return NULL; - if (PyBytes_GET_SIZE(value) != 1) { - Py_DECREF(value); - goto error; - } - *(char *)ptr = PyBytes_AS_STRING(value)[0]; - Py_DECREF(value); - _RET(value); - } - if (PyBytes_Check(value) && PyBytes_GET_SIZE(value) == 1) { - *(char *)ptr = PyBytes_AS_STRING(value)[0]; - _RET(value); - } - if (PyByteArray_Check(value) && PyByteArray_GET_SIZE(value) == 1) { - *(char *)ptr = PyByteArray_AS_STRING(value)[0]; - _RET(value); - } - if (PyLong_Check(value)) - { - long longval = PyLong_AS_LONG(value); - if (longval < 0 || longval >= 256) - goto error; - *(char *)ptr = (char)longval; - _RET(value); - } + if (PyUnicode_Check(value)) { + value = PyUnicode_AsEncodedString(value, + _ctypes_conversion_encoding, + _ctypes_conversion_errors); + if (value == NULL) + return NULL; + if (PyBytes_GET_SIZE(value) != 1) { + Py_DECREF(value); + goto error; + } + *(char *)ptr = PyBytes_AS_STRING(value)[0]; + Py_DECREF(value); + _RET(value); + } + if (PyBytes_Check(value) && PyBytes_GET_SIZE(value) == 1) { + *(char *)ptr = PyBytes_AS_STRING(value)[0]; + _RET(value); + } + if (PyByteArray_Check(value) && PyByteArray_GET_SIZE(value) == 1) { + *(char *)ptr = PyByteArray_AS_STRING(value)[0]; + _RET(value); + } + if (PyLong_Check(value)) + { + long longval = PyLong_AS_LONG(value); + if (longval < 0 || longval >= 256) + goto error; + *(char *)ptr = (char)longval; + _RET(value); + } error: - PyErr_Format(PyExc_TypeError, - "one character string expected"); - return NULL; + PyErr_Format(PyExc_TypeError, + "one character string expected"); + return NULL; } static PyObject * c_get(void *ptr, Py_ssize_t size) { - return PyBytes_FromStringAndSize((char *)ptr, 1); + return PyBytes_FromStringAndSize((char *)ptr, 1); } #ifdef CTYPES_UNICODE @@ -1216,107 +1216,107 @@ static PyObject * u_set(void *ptr, PyObject *value, Py_ssize_t size) { - Py_ssize_t len; - if (PyBytes_Check(value)) { - value = PyUnicode_FromEncodedObject(value, - _ctypes_conversion_encoding, - _ctypes_conversion_errors); - if (!value) - return NULL; - } else if (!PyUnicode_Check(value)) { - PyErr_Format(PyExc_TypeError, - "unicode string expected instead of %s instance", - value->ob_type->tp_name); - return NULL; - } else - Py_INCREF(value); - - len = PyUnicode_GET_SIZE(value); - if (len != 1) { - Py_DECREF(value); - PyErr_SetString(PyExc_TypeError, - "one character unicode string expected"); - return NULL; - } + Py_ssize_t len; + if (PyBytes_Check(value)) { + value = PyUnicode_FromEncodedObject(value, + _ctypes_conversion_encoding, + _ctypes_conversion_errors); + if (!value) + return NULL; + } else if (!PyUnicode_Check(value)) { + PyErr_Format(PyExc_TypeError, + "unicode string expected instead of %s instance", + value->ob_type->tp_name); + return NULL; + } else + Py_INCREF(value); + + len = PyUnicode_GET_SIZE(value); + if (len != 1) { + Py_DECREF(value); + PyErr_SetString(PyExc_TypeError, + "one character unicode string expected"); + return NULL; + } - *(wchar_t *)ptr = PyUnicode_AS_UNICODE(value)[0]; - Py_DECREF(value); + *(wchar_t *)ptr = PyUnicode_AS_UNICODE(value)[0]; + Py_DECREF(value); - _RET(value); + _RET(value); } static PyObject * u_get(void *ptr, Py_ssize_t size) { - return PyUnicode_FromWideChar((wchar_t *)ptr, 1); + return PyUnicode_FromWideChar((wchar_t *)ptr, 1); } /* U - a unicode string */ static PyObject * U_get(void *ptr, Py_ssize_t size) { - PyObject *result; - Py_ssize_t len; - Py_UNICODE *p; - - size /= sizeof(wchar_t); /* we count character units here, not bytes */ - - result = PyUnicode_FromWideChar((wchar_t *)ptr, size); - if (!result) - return NULL; - /* We need 'result' to be able to count the characters with wcslen, - since ptr may not be NUL terminated. If the length is smaller (if - it was actually NUL terminated, we construct a new one and throw - away the result. - */ - /* chop off at the first NUL character, if any. */ - p = PyUnicode_AS_UNICODE(result); - for (len = 0; len < size; ++len) - if (!p[len]) - break; - - if (len < size) { - PyObject *ob = PyUnicode_FromWideChar((wchar_t *)ptr, len); - Py_DECREF(result); - return ob; - } - return result; + PyObject *result; + Py_ssize_t len; + Py_UNICODE *p; + + size /= sizeof(wchar_t); /* we count character units here, not bytes */ + + result = PyUnicode_FromWideChar((wchar_t *)ptr, size); + if (!result) + return NULL; + /* We need 'result' to be able to count the characters with wcslen, + since ptr may not be NUL terminated. If the length is smaller (if + it was actually NUL terminated, we construct a new one and throw + away the result. + */ + /* chop off at the first NUL character, if any. */ + p = PyUnicode_AS_UNICODE(result); + for (len = 0; len < size; ++len) + if (!p[len]) + break; + + if (len < size) { + PyObject *ob = PyUnicode_FromWideChar((wchar_t *)ptr, len); + Py_DECREF(result); + return ob; + } + return result; } static PyObject * U_set(void *ptr, PyObject *value, Py_ssize_t length) { - Py_ssize_t size; + Py_ssize_t size; - /* It's easier to calculate in characters than in bytes */ - length /= sizeof(wchar_t); + /* It's easier to calculate in characters than in bytes */ + length /= sizeof(wchar_t); - if (PyBytes_Check(value)) { - value = PyUnicode_FromEncodedObject(value, - _ctypes_conversion_encoding, - _ctypes_conversion_errors); - if (!value) - return NULL; - } else if (!PyUnicode_Check(value)) { - PyErr_Format(PyExc_TypeError, - "unicode string expected instead of %s instance", - value->ob_type->tp_name); - return NULL; - } else - Py_INCREF(value); - size = PyUnicode_GET_SIZE(value); - if (size > length) { - PyErr_Format(PyExc_ValueError, - "string too long (%zd, maximum length %zd)", - size, length); - Py_DECREF(value); - return NULL; - } else if (size < length-1) - /* copy terminating NUL character if there is space */ - size += 1; - PyUnicode_AsWideChar((PyUnicodeObject *)value, (wchar_t *)ptr, size); - return value; + if (PyBytes_Check(value)) { + value = PyUnicode_FromEncodedObject(value, + _ctypes_conversion_encoding, + _ctypes_conversion_errors); + if (!value) + return NULL; + } else if (!PyUnicode_Check(value)) { + PyErr_Format(PyExc_TypeError, + "unicode string expected instead of %s instance", + value->ob_type->tp_name); + return NULL; + } else + Py_INCREF(value); + size = PyUnicode_GET_SIZE(value); + if (size > length) { + PyErr_Format(PyExc_ValueError, + "string too long (%zd, maximum length %zd)", + size, length); + Py_DECREF(value); + return NULL; + } else if (size < length-1) + /* copy terminating NUL character if there is space */ + size += 1; + PyUnicode_AsWideChar((PyUnicodeObject *)value, (wchar_t *)ptr, size); + return value; } #endif @@ -1324,210 +1324,210 @@ static PyObject * s_get(void *ptr, Py_ssize_t size) { - Py_ssize_t i; - char *p; + Py_ssize_t i; + char *p; - p = (char *)ptr; - for (i = 0; i < size; ++i) { - if (*p++ == '\0') - break; - } + p = (char *)ptr; + for (i = 0; i < size; ++i) { + if (*p++ == '\0') + break; + } - return PyUnicode_FromStringAndSize((char *)ptr, (Py_ssize_t)i); + return PyUnicode_FromStringAndSize((char *)ptr, (Py_ssize_t)i); } static PyObject * s_set(void *ptr, PyObject *value, Py_ssize_t length) { - char *data; - Py_ssize_t size; + char *data; + Py_ssize_t size; - if (PyUnicode_Check(value)) { - value = PyUnicode_AsEncodedString(value, - _ctypes_conversion_encoding, - _ctypes_conversion_errors); - if (value == NULL) - return NULL; - assert(PyBytes_Check(value)); - } else if(PyBytes_Check(value)) { - Py_INCREF(value); - } else { - PyErr_Format(PyExc_TypeError, - "expected string, %s found", - value->ob_type->tp_name); - return NULL; - } - - data = PyBytes_AS_STRING(value); - if (!data) - return NULL; - size = strlen(data); /* XXX Why not Py_SIZE(value)? */ - if (size < length) { - /* This will copy the leading NUL character - * if there is space for it. - */ - ++size; - } else if (size > length) { - PyErr_Format(PyExc_ValueError, - "string too long (%zd, maximum length %zd)", - size, length); - Py_DECREF(value); - return NULL; - } - /* Also copy the terminating NUL character if there is space */ - memcpy((char *)ptr, data, size); + if (PyUnicode_Check(value)) { + value = PyUnicode_AsEncodedString(value, + _ctypes_conversion_encoding, + _ctypes_conversion_errors); + if (value == NULL) + return NULL; + assert(PyBytes_Check(value)); + } else if(PyBytes_Check(value)) { + Py_INCREF(value); + } else { + PyErr_Format(PyExc_TypeError, + "expected string, %s found", + value->ob_type->tp_name); + return NULL; + } + + data = PyBytes_AS_STRING(value); + if (!data) + return NULL; + size = strlen(data); /* XXX Why not Py_SIZE(value)? */ + if (size < length) { + /* This will copy the leading NUL character + * if there is space for it. + */ + ++size; + } else if (size > length) { + PyErr_Format(PyExc_ValueError, + "string too long (%zd, maximum length %zd)", + size, length); + Py_DECREF(value); + return NULL; + } + /* Also copy the terminating NUL character if there is space */ + memcpy((char *)ptr, data, size); - Py_DECREF(value); - _RET(value); + Py_DECREF(value); + _RET(value); } static PyObject * z_set(void *ptr, PyObject *value, Py_ssize_t size) { - if (value == Py_None) { - *(char **)ptr = NULL; - Py_INCREF(value); - return value; - } - if (PyBytes_Check(value)) { - *(char **)ptr = PyBytes_AsString(value); - Py_INCREF(value); - return value; - } else if (PyUnicode_Check(value)) { - PyObject *str = PyUnicode_AsEncodedString(value, - _ctypes_conversion_encoding, - _ctypes_conversion_errors); - if (str == NULL) - return NULL; - *(char **)ptr = PyBytes_AS_STRING(str); - return str; - } else if (PyLong_Check(value)) { + if (value == Py_None) { + *(char **)ptr = NULL; + Py_INCREF(value); + return value; + } + if (PyBytes_Check(value)) { + *(char **)ptr = PyBytes_AsString(value); + Py_INCREF(value); + return value; + } else if (PyUnicode_Check(value)) { + PyObject *str = PyUnicode_AsEncodedString(value, + _ctypes_conversion_encoding, + _ctypes_conversion_errors); + if (str == NULL) + return NULL; + *(char **)ptr = PyBytes_AS_STRING(str); + return str; + } else if (PyLong_Check(value)) { #if SIZEOF_VOID_P == SIZEOF_LONG_LONG - *(char **)ptr = (char *)PyLong_AsUnsignedLongLongMask(value); + *(char **)ptr = (char *)PyLong_AsUnsignedLongLongMask(value); #else - *(char **)ptr = (char *)PyLong_AsUnsignedLongMask(value); + *(char **)ptr = (char *)PyLong_AsUnsignedLongMask(value); #endif - _RET(value); - } - PyErr_Format(PyExc_TypeError, - "string or integer address expected instead of %s instance", - value->ob_type->tp_name); - return NULL; + _RET(value); + } + PyErr_Format(PyExc_TypeError, + "string or integer address expected instead of %s instance", + value->ob_type->tp_name); + return NULL; } static PyObject * z_get(void *ptr, Py_ssize_t size) { - /* XXX What about invalid pointers ??? */ - if (*(void **)ptr) { + /* XXX What about invalid pointers ??? */ + if (*(void **)ptr) { #if defined(MS_WIN32) && !defined(_WIN32_WCE) - if (IsBadStringPtrA(*(char **)ptr, -1)) { - PyErr_Format(PyExc_ValueError, - "invalid string pointer %p", - *(char **)ptr); - return NULL; - } -#endif - return PyBytes_FromStringAndSize(*(char **)ptr, - strlen(*(char **)ptr)); - } else { - Py_INCREF(Py_None); - return Py_None; - } + if (IsBadStringPtrA(*(char **)ptr, -1)) { + PyErr_Format(PyExc_ValueError, + "invalid string pointer %p", + *(char **)ptr); + return NULL; + } +#endif + return PyBytes_FromStringAndSize(*(char **)ptr, + strlen(*(char **)ptr)); + } else { + Py_INCREF(Py_None); + return Py_None; + } } #ifdef CTYPES_UNICODE static PyObject * Z_set(void *ptr, PyObject *value, Py_ssize_t size) { - if (value == Py_None) { - *(wchar_t **)ptr = NULL; - Py_INCREF(value); - return value; - } - if (PyLong_Check(value) || PyLong_Check(value)) { + if (value == Py_None) { + *(wchar_t **)ptr = NULL; + Py_INCREF(value); + return value; + } + if (PyLong_Check(value) || PyLong_Check(value)) { #if SIZEOF_VOID_P == SIZEOF_LONG_LONG - *(wchar_t **)ptr = (wchar_t *)PyLong_AsUnsignedLongLongMask(value); + *(wchar_t **)ptr = (wchar_t *)PyLong_AsUnsignedLongLongMask(value); #else - *(wchar_t **)ptr = (wchar_t *)PyLong_AsUnsignedLongMask(value); + *(wchar_t **)ptr = (wchar_t *)PyLong_AsUnsignedLongMask(value); #endif - Py_INCREF(Py_None); - return Py_None; - } - if (PyBytes_Check(value)) { - value = PyUnicode_FromEncodedObject(value, - _ctypes_conversion_encoding, - _ctypes_conversion_errors); - if (!value) - return NULL; - } else if (!PyUnicode_Check(value)) { - PyErr_Format(PyExc_TypeError, - "unicode string or integer address expected instead of %s instance", - value->ob_type->tp_name); - return NULL; - } else - Py_INCREF(value); + Py_INCREF(Py_None); + return Py_None; + } + if (PyBytes_Check(value)) { + value = PyUnicode_FromEncodedObject(value, + _ctypes_conversion_encoding, + _ctypes_conversion_errors); + if (!value) + return NULL; + } else if (!PyUnicode_Check(value)) { + PyErr_Format(PyExc_TypeError, + "unicode string or integer address expected instead of %s instance", + value->ob_type->tp_name); + return NULL; + } else + Py_INCREF(value); #ifdef HAVE_USABLE_WCHAR_T - /* HAVE_USABLE_WCHAR_T means that Py_UNICODE and wchar_t is the same - type. So we can copy directly. Hm, are unicode objects always NUL - terminated in Python, internally? - */ - *(wchar_t **)ptr = PyUnicode_AS_UNICODE(value); - return value; + /* HAVE_USABLE_WCHAR_T means that Py_UNICODE and wchar_t is the same + type. So we can copy directly. Hm, are unicode objects always NUL + terminated in Python, internally? + */ + *(wchar_t **)ptr = PyUnicode_AS_UNICODE(value); + return value; #else - { - /* We must create a wchar_t* buffer from the unicode object, - and keep it alive */ - PyObject *keep; - wchar_t *buffer; - - int size = PyUnicode_GET_SIZE(value); - size += 1; /* terminating NUL */ - size *= sizeof(wchar_t); - buffer = (wchar_t *)PyMem_Malloc(size); - if (!buffer) { - Py_DECREF(value); - return PyErr_NoMemory(); - } - memset(buffer, 0, size); - keep = PyCapsule_New(buffer, CTYPES_CFIELD_CAPSULE_NAME_PYMEM, pymem_destructor); - if (!keep) { - Py_DECREF(value); - PyMem_Free(buffer); - return NULL; - } - *(wchar_t **)ptr = (wchar_t *)buffer; - if (-1 == PyUnicode_AsWideChar((PyUnicodeObject *)value, - buffer, PyUnicode_GET_SIZE(value))) { - Py_DECREF(value); - Py_DECREF(keep); - return NULL; - } - Py_DECREF(value); - return keep; - } + { + /* We must create a wchar_t* buffer from the unicode object, + and keep it alive */ + PyObject *keep; + wchar_t *buffer; + + int size = PyUnicode_GET_SIZE(value); + size += 1; /* terminating NUL */ + size *= sizeof(wchar_t); + buffer = (wchar_t *)PyMem_Malloc(size); + if (!buffer) { + Py_DECREF(value); + return PyErr_NoMemory(); + } + memset(buffer, 0, size); + keep = PyCapsule_New(buffer, CTYPES_CFIELD_CAPSULE_NAME_PYMEM, pymem_destructor); + if (!keep) { + Py_DECREF(value); + PyMem_Free(buffer); + return NULL; + } + *(wchar_t **)ptr = (wchar_t *)buffer; + if (-1 == PyUnicode_AsWideChar((PyUnicodeObject *)value, + buffer, PyUnicode_GET_SIZE(value))) { + Py_DECREF(value); + Py_DECREF(keep); + return NULL; + } + Py_DECREF(value); + return keep; + } #endif } static PyObject * Z_get(void *ptr, Py_ssize_t size) { - wchar_t *p; - p = *(wchar_t **)ptr; - if (p) { + wchar_t *p; + p = *(wchar_t **)ptr; + if (p) { #if defined(MS_WIN32) && !defined(_WIN32_WCE) - if (IsBadStringPtrW(*(wchar_t **)ptr, -1)) { - PyErr_Format(PyExc_ValueError, - "invalid string pointer %p", - *(wchar_t **)ptr); - return NULL; - } -#endif - return PyUnicode_FromWideChar(p, wcslen(p)); - } else { - Py_INCREF(Py_None); - return Py_None; - } + if (IsBadStringPtrW(*(wchar_t **)ptr, -1)) { + PyErr_Format(PyExc_ValueError, + "invalid string pointer %p", + *(wchar_t **)ptr); + return NULL; + } +#endif + return PyUnicode_FromWideChar(p, wcslen(p)); + } else { + Py_INCREF(Py_None); + return Py_None; + } } #endif @@ -1535,166 +1535,166 @@ static PyObject * BSTR_set(void *ptr, PyObject *value, Py_ssize_t size) { - BSTR bstr; + BSTR bstr; + + /* convert value into a PyUnicodeObject or NULL */ + if (Py_None == value) { + value = NULL; + } else if (PyBytes_Check(value)) { + value = PyUnicode_FromEncodedObject(value, + _ctypes_conversion_encoding, + _ctypes_conversion_errors); + if (!value) + return NULL; + } else if (PyUnicode_Check(value)) { + Py_INCREF(value); /* for the descref below */ + } else { + PyErr_Format(PyExc_TypeError, + "unicode string expected instead of %s instance", + value->ob_type->tp_name); + return NULL; + } + + /* create a BSTR from value */ + if (value) { + Py_ssize_t size = PyUnicode_GET_SIZE(value); + if ((unsigned) size != size) { + PyErr_SetString(PyExc_ValueError, "String too long for BSTR"); + return NULL; + } + bstr = SysAllocStringLen(PyUnicode_AS_UNICODE(value), + (unsigned)size); + Py_DECREF(value); + } else + bstr = NULL; + + /* free the previous contents, if any */ + if (*(BSTR *)ptr) + SysFreeString(*(BSTR *)ptr); - /* convert value into a PyUnicodeObject or NULL */ - if (Py_None == value) { - value = NULL; - } else if (PyBytes_Check(value)) { - value = PyUnicode_FromEncodedObject(value, - _ctypes_conversion_encoding, - _ctypes_conversion_errors); - if (!value) - return NULL; - } else if (PyUnicode_Check(value)) { - Py_INCREF(value); /* for the descref below */ - } else { - PyErr_Format(PyExc_TypeError, - "unicode string expected instead of %s instance", - value->ob_type->tp_name); - return NULL; - } - - /* create a BSTR from value */ - if (value) { - Py_ssize_t size = PyUnicode_GET_SIZE(value); - if ((unsigned) size != size) { - PyErr_SetString(PyExc_ValueError, "String too long for BSTR"); - return NULL; - } - bstr = SysAllocStringLen(PyUnicode_AS_UNICODE(value), - (unsigned)size); - Py_DECREF(value); - } else - bstr = NULL; - - /* free the previous contents, if any */ - if (*(BSTR *)ptr) - SysFreeString(*(BSTR *)ptr); - - /* and store it */ - *(BSTR *)ptr = bstr; + /* and store it */ + *(BSTR *)ptr = bstr; - /* We don't need to keep any other object */ - _RET(value); + /* We don't need to keep any other object */ + _RET(value); } static PyObject * BSTR_get(void *ptr, Py_ssize_t size) { - BSTR p; - p = *(BSTR *)ptr; - if (p) - return PyUnicode_FromWideChar(p, SysStringLen(p)); - else { - /* Hm, it seems NULL pointer and zero length string are the - same in BSTR, see Don Box, p 81 - */ - Py_INCREF(Py_None); - return Py_None; - } + BSTR p; + p = *(BSTR *)ptr; + if (p) + return PyUnicode_FromWideChar(p, SysStringLen(p)); + else { + /* Hm, it seems NULL pointer and zero length string are the + same in BSTR, see Don Box, p 81 + */ + Py_INCREF(Py_None); + return Py_None; + } } #endif static PyObject * P_set(void *ptr, PyObject *value, Py_ssize_t size) { - void *v; - if (value == Py_None) { - *(void **)ptr = NULL; - _RET(value); - } - - if (!PyLong_Check(value) && !PyLong_Check(value)) { - PyErr_SetString(PyExc_TypeError, - "cannot be converted to pointer"); - return NULL; - } + void *v; + if (value == Py_None) { + *(void **)ptr = NULL; + _RET(value); + } + + if (!PyLong_Check(value) && !PyLong_Check(value)) { + PyErr_SetString(PyExc_TypeError, + "cannot be converted to pointer"); + return NULL; + } #if SIZEOF_VOID_P <= SIZEOF_LONG - v = (void *)PyLong_AsUnsignedLongMask(value); + v = (void *)PyLong_AsUnsignedLongMask(value); #else #ifndef HAVE_LONG_LONG # error "PyLong_AsVoidPtr: sizeof(void*) > sizeof(long), but no long long" #elif SIZEOF_LONG_LONG < SIZEOF_VOID_P # error "PyLong_AsVoidPtr: sizeof(PY_LONG_LONG) < sizeof(void*)" #endif - v = (void *)PyLong_AsUnsignedLongLongMask(value); + v = (void *)PyLong_AsUnsignedLongLongMask(value); #endif - if (PyErr_Occurred()) - return NULL; + if (PyErr_Occurred()) + return NULL; - *(void **)ptr = v; - _RET(value); + *(void **)ptr = v; + _RET(value); } static PyObject * P_get(void *ptr, Py_ssize_t size) { - if (*(void **)ptr == NULL) { - Py_INCREF(Py_None); - return Py_None; - } - return PyLong_FromVoidPtr(*(void **)ptr); + if (*(void **)ptr == NULL) { + Py_INCREF(Py_None); + return Py_None; + } + return PyLong_FromVoidPtr(*(void **)ptr); } static struct fielddesc formattable[] = { - { 's', s_set, s_get, &ffi_type_pointer}, - { 'b', b_set, b_get, &ffi_type_schar}, - { 'B', B_set, B_get, &ffi_type_uchar}, - { 'c', c_set, c_get, &ffi_type_schar}, - { 'd', d_set, d_get, &ffi_type_double, d_set_sw, d_get_sw}, - { 'g', g_set, g_get, &ffi_type_longdouble}, - { 'f', f_set, f_get, &ffi_type_float, f_set_sw, f_get_sw}, - { 'h', h_set, h_get, &ffi_type_sshort, h_set_sw, h_get_sw}, - { 'H', H_set, H_get, &ffi_type_ushort, H_set_sw, H_get_sw}, - { 'i', i_set, i_get, &ffi_type_sint, i_set_sw, i_get_sw}, - { 'I', I_set, I_get, &ffi_type_uint, I_set_sw, I_get_sw}, + { 's', s_set, s_get, &ffi_type_pointer}, + { 'b', b_set, b_get, &ffi_type_schar}, + { 'B', B_set, B_get, &ffi_type_uchar}, + { 'c', c_set, c_get, &ffi_type_schar}, + { 'd', d_set, d_get, &ffi_type_double, d_set_sw, d_get_sw}, + { 'g', g_set, g_get, &ffi_type_longdouble}, + { 'f', f_set, f_get, &ffi_type_float, f_set_sw, f_get_sw}, + { 'h', h_set, h_get, &ffi_type_sshort, h_set_sw, h_get_sw}, + { 'H', H_set, H_get, &ffi_type_ushort, H_set_sw, H_get_sw}, + { 'i', i_set, i_get, &ffi_type_sint, i_set_sw, i_get_sw}, + { 'I', I_set, I_get, &ffi_type_uint, I_set_sw, I_get_sw}, /* XXX Hm, sizeof(int) == sizeof(long) doesn't hold on every platform */ /* As soon as we can get rid of the type codes, this is no longer a problem */ #if SIZEOF_LONG == 4 - { 'l', l_set, l_get, &ffi_type_sint32, l_set_sw, l_get_sw}, - { 'L', L_set, L_get, &ffi_type_uint32, L_set_sw, L_get_sw}, + { 'l', l_set, l_get, &ffi_type_sint32, l_set_sw, l_get_sw}, + { 'L', L_set, L_get, &ffi_type_uint32, L_set_sw, L_get_sw}, #elif SIZEOF_LONG == 8 - { 'l', l_set, l_get, &ffi_type_sint64, l_set_sw, l_get_sw}, - { 'L', L_set, L_get, &ffi_type_uint64, L_set_sw, L_get_sw}, + { 'l', l_set, l_get, &ffi_type_sint64, l_set_sw, l_get_sw}, + { 'L', L_set, L_get, &ffi_type_uint64, L_set_sw, L_get_sw}, #else # error #endif #ifdef HAVE_LONG_LONG #if SIZEOF_LONG_LONG == 8 - { 'q', q_set, q_get, &ffi_type_sint64, q_set_sw, q_get_sw}, - { 'Q', Q_set, Q_get, &ffi_type_uint64, Q_set_sw, Q_get_sw}, + { 'q', q_set, q_get, &ffi_type_sint64, q_set_sw, q_get_sw}, + { 'Q', Q_set, Q_get, &ffi_type_uint64, Q_set_sw, Q_get_sw}, #else # error #endif #endif - { 'P', P_set, P_get, &ffi_type_pointer}, - { 'z', z_set, z_get, &ffi_type_pointer}, + { 'P', P_set, P_get, &ffi_type_pointer}, + { 'z', z_set, z_get, &ffi_type_pointer}, #ifdef CTYPES_UNICODE - { 'u', u_set, u_get, NULL}, /* ffi_type set later */ - { 'U', U_set, U_get, &ffi_type_pointer}, - { 'Z', Z_set, Z_get, &ffi_type_pointer}, + { 'u', u_set, u_get, NULL}, /* ffi_type set later */ + { 'U', U_set, U_get, &ffi_type_pointer}, + { 'Z', Z_set, Z_get, &ffi_type_pointer}, #endif #ifdef MS_WIN32 - { 'X', BSTR_set, BSTR_get, &ffi_type_pointer}, - { 'v', vBOOL_set, vBOOL_get, &ffi_type_sshort}, + { 'X', BSTR_set, BSTR_get, &ffi_type_pointer}, + { 'v', vBOOL_set, vBOOL_get, &ffi_type_sshort}, #endif #if SIZEOF__BOOL == 1 - { '?', bool_set, bool_get, &ffi_type_uchar}, /* Also fallback for no native _Bool support */ + { '?', bool_set, bool_get, &ffi_type_uchar}, /* Also fallback for no native _Bool support */ #elif SIZEOF__BOOL == SIZEOF_SHORT - { '?', bool_set, bool_get, &ffi_type_ushort}, + { '?', bool_set, bool_get, &ffi_type_ushort}, #elif SIZEOF__BOOL == SIZEOF_INT - { '?', bool_set, bool_get, &ffi_type_uint, I_set_sw, I_get_sw}, + { '?', bool_set, bool_get, &ffi_type_uint, I_set_sw, I_get_sw}, #elif SIZEOF__BOOL == SIZEOF_LONG - { '?', bool_set, bool_get, &ffi_type_ulong, L_set_sw, L_get_sw}, + { '?', bool_set, bool_get, &ffi_type_ulong, L_set_sw, L_get_sw}, #elif SIZEOF__BOOL == SIZEOF_LONG_LONG - { '?', bool_set, bool_get, &ffi_type_ulong, Q_set_sw, Q_get_sw}, + { '?', bool_set, bool_get, &ffi_type_ulong, Q_set_sw, Q_get_sw}, #endif /* SIZEOF__BOOL */ - { 'O', O_set, O_get, &ffi_type_pointer}, - { 0, NULL, NULL, NULL}, + { 'O', O_set, O_get, &ffi_type_pointer}, + { 0, NULL, NULL, NULL}, }; /* @@ -1705,26 +1705,26 @@ struct fielddesc * _ctypes_get_fielddesc(const char *fmt) { - static int initialized = 0; - struct fielddesc *table = formattable; + static int initialized = 0; + struct fielddesc *table = formattable; - if (!initialized) { - initialized = 1; + if (!initialized) { + initialized = 1; #ifdef CTYPES_UNICODE - if (sizeof(wchar_t) == sizeof(short)) - _ctypes_get_fielddesc("u")->pffi_type = &ffi_type_sshort; - else if (sizeof(wchar_t) == sizeof(int)) - _ctypes_get_fielddesc("u")->pffi_type = &ffi_type_sint; - else if (sizeof(wchar_t) == sizeof(long)) - _ctypes_get_fielddesc("u")->pffi_type = &ffi_type_slong; -#endif - } - - for (; table->code; ++table) { - if (table->code == fmt[0]) - return table; - } - return NULL; + if (sizeof(wchar_t) == sizeof(short)) + _ctypes_get_fielddesc("u")->pffi_type = &ffi_type_sshort; + else if (sizeof(wchar_t) == sizeof(int)) + _ctypes_get_fielddesc("u")->pffi_type = &ffi_type_sint; + else if (sizeof(wchar_t) == sizeof(long)) + _ctypes_get_fielddesc("u")->pffi_type = &ffi_type_slong; +#endif + } + + for (; table->code; ++table) { + if (table->code == fmt[0]) + return table; + } + return NULL; } typedef struct { char c; char x; } s_char; @@ -1768,10 +1768,10 @@ /* from ffi.h: typedef struct _ffi_type { - size_t size; - unsigned short alignment; - unsigned short type; - struct _ffi_type **elements; + size_t size; + unsigned short alignment; + unsigned short type; + struct _ffi_type **elements; } ffi_type; */ @@ -1798,7 +1798,7 @@ #endif /* This is already defined on OSX */ ffi_type ffi_type_longdouble = { sizeof(long double), LONGDOUBLE_ALIGN, - FFI_TYPE_LONGDOUBLE }; + FFI_TYPE_LONGDOUBLE }; ffi_type ffi_type_pointer = { sizeof(void *), VOID_P_ALIGN, FFI_TYPE_POINTER }; Modified: python/branches/release31-maint/Modules/_ctypes/ctypes.h ============================================================================== --- python/branches/release31-maint/Modules/_ctypes/ctypes.h (original) +++ python/branches/release31-maint/Modules/_ctypes/ctypes.h Sun May 9 18:14:21 2010 @@ -21,16 +21,16 @@ difficult in the presence of PyCFuncPtrObject. Maybe later. */ union value { - char c[16]; - short s; - int i; - long l; - float f; - double d; + char c[16]; + short s; + int i; + long l; + float f; + double d; #ifdef HAVE_LONG_LONG - PY_LONG_LONG ll; + PY_LONG_LONG ll; #endif - long double D; + long double D; }; /* @@ -40,67 +40,67 @@ */ struct tagCDataObject { - PyObject_HEAD - char *b_ptr; /* pointer to memory block */ - int b_needsfree; /* need _we_ free the memory? */ - CDataObject *b_base; /* pointer to base object or NULL */ - Py_ssize_t b_size; /* size of memory block in bytes */ - Py_ssize_t b_length; /* number of references we need */ - Py_ssize_t b_index; /* index of this object into base's - b_object list */ - PyObject *b_objects; /* dictionary of references we need to keep, or Py_None */ - union value b_value; + PyObject_HEAD + char *b_ptr; /* pointer to memory block */ + int b_needsfree; /* need _we_ free the memory? */ + CDataObject *b_base; /* pointer to base object or NULL */ + Py_ssize_t b_size; /* size of memory block in bytes */ + Py_ssize_t b_length; /* number of references we need */ + Py_ssize_t b_index; /* index of this object into base's + b_object list */ + PyObject *b_objects; /* dictionary of references we need to keep, or Py_None */ + union value b_value; }; typedef struct { - PyObject_VAR_HEAD - ffi_closure *pcl; /* the C callable */ - ffi_cif cif; - int flags; - PyObject *converters; - PyObject *callable; - PyObject *restype; - SETFUNC setfunc; - ffi_type *ffi_restype; - ffi_type *atypes[1]; + PyObject_VAR_HEAD + ffi_closure *pcl; /* the C callable */ + ffi_cif cif; + int flags; + PyObject *converters; + PyObject *callable; + PyObject *restype; + SETFUNC setfunc; + ffi_type *ffi_restype; + ffi_type *atypes[1]; } CThunkObject; extern PyTypeObject PyCThunk_Type; -#define CThunk_CheckExact(v) ((v)->ob_type == &PyCThunk_Type) +#define CThunk_CheckExact(v) ((v)->ob_type == &PyCThunk_Type) typedef struct { - /* First part identical to tagCDataObject */ - PyObject_HEAD - char *b_ptr; /* pointer to memory block */ - int b_needsfree; /* need _we_ free the memory? */ - CDataObject *b_base; /* pointer to base object or NULL */ - Py_ssize_t b_size; /* size of memory block in bytes */ - Py_ssize_t b_length; /* number of references we need */ - Py_ssize_t b_index; /* index of this object into base's - b_object list */ - PyObject *b_objects; /* list of references we need to keep */ - union value b_value; - /* end of tagCDataObject, additional fields follow */ - - CThunkObject *thunk; - PyObject *callable; - - /* These two fields will override the ones in the type's stgdict if - they are set */ - PyObject *converters; - PyObject *argtypes; - PyObject *restype; - PyObject *checker; - PyObject *errcheck; + /* First part identical to tagCDataObject */ + PyObject_HEAD + char *b_ptr; /* pointer to memory block */ + int b_needsfree; /* need _we_ free the memory? */ + CDataObject *b_base; /* pointer to base object or NULL */ + Py_ssize_t b_size; /* size of memory block in bytes */ + Py_ssize_t b_length; /* number of references we need */ + Py_ssize_t b_index; /* index of this object into base's + b_object list */ + PyObject *b_objects; /* list of references we need to keep */ + union value b_value; + /* end of tagCDataObject, additional fields follow */ + + CThunkObject *thunk; + PyObject *callable; + + /* These two fields will override the ones in the type's stgdict if + they are set */ + PyObject *converters; + PyObject *argtypes; + PyObject *restype; + PyObject *checker; + PyObject *errcheck; #ifdef MS_WIN32 - int index; - GUID *iid; + int index; + GUID *iid; #endif - PyObject *paramflags; + PyObject *paramflags; } PyCFuncPtrObject; extern PyTypeObject PyCStgDict_Type; -#define PyCStgDict_CheckExact(v) ((v)->ob_type == &PyCStgDict_Type) -#define PyCStgDict_Check(v) PyObject_TypeCheck(v, &PyCStgDict_Type) +#define PyCStgDict_CheckExact(v) ((v)->ob_type == &PyCStgDict_Type) +#define PyCStgDict_Check(v) PyObject_TypeCheck(v, &PyCStgDict_Type) extern int PyCStructUnionType_update_stgdict(PyObject *fields, PyObject *type, int isStruct); extern int PyType_stginfo(PyTypeObject *self, Py_ssize_t *psize, Py_ssize_t *palign, Py_ssize_t *plength); @@ -109,12 +109,12 @@ extern PyTypeObject PyCData_Type; -#define CDataObject_CheckExact(v) ((v)->ob_type == &PyCData_Type) -#define CDataObject_Check(v) PyObject_TypeCheck(v, &PyCData_Type) +#define CDataObject_CheckExact(v) ((v)->ob_type == &PyCData_Type) +#define CDataObject_Check(v) PyObject_TypeCheck(v, &PyCData_Type) extern PyTypeObject PyCSimpleType_Type; -#define PyCSimpleTypeObject_CheckExact(v) ((v)->ob_type == &PyCSimpleType_Type) -#define PyCSimpleTypeObject_Check(v) PyObject_TypeCheck(v, &PyCSimpleType_Type) +#define PyCSimpleTypeObject_CheckExact(v) ((v)->ob_type == &PyCSimpleType_Type) +#define PyCSimpleTypeObject_Check(v) PyObject_TypeCheck(v, &PyCSimpleType_Type) extern PyTypeObject PyCField_Type; extern struct fielddesc *_ctypes_get_fielddesc(const char *fmt); @@ -122,9 +122,9 @@ extern PyObject * PyCField_FromDesc(PyObject *desc, Py_ssize_t index, - Py_ssize_t *pfield_size, int bitsize, int *pbitofs, - Py_ssize_t *psize, Py_ssize_t *poffset, Py_ssize_t *palign, - int pack, int is_big_endian); + Py_ssize_t *pfield_size, int bitsize, int *pbitofs, + Py_ssize_t *psize, Py_ssize_t *poffset, Py_ssize_t *palign, + int pack, int is_big_endian); extern PyObject *PyCData_AtAddress(PyObject *type, void *buf); extern PyObject *PyCData_FromBytes(PyObject *type, char *data, Py_ssize_t length); @@ -137,13 +137,13 @@ extern PyTypeObject PyCFuncPtrType_Type; extern PyTypeObject PyCStructType_Type; -#define PyCArrayTypeObject_Check(v) PyObject_TypeCheck(v, &PyCArrayType_Type) -#define ArrayObject_Check(v) PyObject_TypeCheck(v, &PyCArray_Type) -#define PointerObject_Check(v) PyObject_TypeCheck(v, &PyCPointer_Type) -#define PyCPointerTypeObject_Check(v) PyObject_TypeCheck(v, &PyCPointerType_Type) -#define PyCFuncPtrObject_Check(v) PyObject_TypeCheck(v, &PyCFuncPtr_Type) -#define PyCFuncPtrTypeObject_Check(v) PyObject_TypeCheck(v, &PyCFuncPtrType_Type) -#define PyCStructTypeObject_Check(v) PyObject_TypeCheck(v, &PyCStructType_Type) +#define PyCArrayTypeObject_Check(v) PyObject_TypeCheck(v, &PyCArrayType_Type) +#define ArrayObject_Check(v) PyObject_TypeCheck(v, &PyCArray_Type) +#define PointerObject_Check(v) PyObject_TypeCheck(v, &PyCPointer_Type) +#define PyCPointerTypeObject_Check(v) PyObject_TypeCheck(v, &PyCPointerType_Type) +#define PyCFuncPtrObject_Check(v) PyObject_TypeCheck(v, &PyCFuncPtr_Type) +#define PyCFuncPtrTypeObject_Check(v) PyObject_TypeCheck(v, &PyCFuncPtrType_Type) +#define PyCStructTypeObject_Check(v) PyObject_TypeCheck(v, &PyCStructType_Type) extern PyObject * PyCArrayType_from_ctype(PyObject *itemtype, Py_ssize_t length); @@ -151,35 +151,35 @@ extern PyMethodDef _ctypes_module_methods[]; extern CThunkObject *_ctypes_alloc_callback(PyObject *callable, - PyObject *converters, - PyObject *restype, - int flags); + PyObject *converters, + PyObject *restype, + int flags); /* a table entry describing a predefined ctypes type */ struct fielddesc { - char code; - SETFUNC setfunc; - GETFUNC getfunc; - ffi_type *pffi_type; /* always statically allocated */ - SETFUNC setfunc_swapped; - GETFUNC getfunc_swapped; + char code; + SETFUNC setfunc; + GETFUNC getfunc; + ffi_type *pffi_type; /* always statically allocated */ + SETFUNC setfunc_swapped; + GETFUNC getfunc_swapped; }; typedef struct { - PyObject_HEAD - Py_ssize_t offset; - Py_ssize_t size; - Py_ssize_t index; /* Index into CDataObject's - object array */ - PyObject *proto; /* a type or NULL */ - GETFUNC getfunc; /* getter function if proto is NULL */ - SETFUNC setfunc; /* setter function if proto is NULL */ - int anonymous; + PyObject_HEAD + Py_ssize_t offset; + Py_ssize_t size; + Py_ssize_t index; /* Index into CDataObject's + object array */ + PyObject *proto; /* a type or NULL */ + GETFUNC getfunc; /* getter function if proto is NULL */ + SETFUNC setfunc; /* setter function if proto is NULL */ + int anonymous; } CFieldObject; /* A subclass of PyDictObject, used as the instance dictionary of ctypes metatypes */ typedef struct { - PyDictObject dict; /* first part identical to PyDictObject */ + PyDictObject dict; /* first part identical to PyDictObject */ /* The size and align fields are unneeded, they are in ffi_type as well. As an experiment shows, it's trivial to get rid of them, the only thing to remember is that in PyCArrayType_new the ffi_type fields must be filled in - @@ -188,28 +188,28 @@ too much risk to change that now, and there are other fields which doen't belong into this structure anyway. Maybe in ctypes 2.0... (ctypes 2000?) */ - Py_ssize_t size; /* number of bytes */ - Py_ssize_t align; /* alignment requirements */ - Py_ssize_t length; /* number of fields */ - ffi_type ffi_type_pointer; - PyObject *proto; /* Only for Pointer/ArrayObject */ - SETFUNC setfunc; /* Only for simple objects */ - GETFUNC getfunc; /* Only for simple objects */ - PARAMFUNC paramfunc; - - /* Following fields only used by PyCFuncPtrType_Type instances */ - PyObject *argtypes; /* tuple of CDataObjects */ - PyObject *converters; /* tuple([t.from_param for t in argtypes]) */ - PyObject *restype; /* CDataObject or NULL */ - PyObject *checker; - int flags; /* calling convention and such */ - - /* pep3118 fields, pointers neeed PyMem_Free */ - char *format; - int ndim; - Py_ssize_t *shape; -/* Py_ssize_t *strides; */ /* unused in ctypes */ -/* Py_ssize_t *suboffsets; */ /* unused in ctypes */ + Py_ssize_t size; /* number of bytes */ + Py_ssize_t align; /* alignment requirements */ + Py_ssize_t length; /* number of fields */ + ffi_type ffi_type_pointer; + PyObject *proto; /* Only for Pointer/ArrayObject */ + SETFUNC setfunc; /* Only for simple objects */ + GETFUNC getfunc; /* Only for simple objects */ + PARAMFUNC paramfunc; + + /* Following fields only used by PyCFuncPtrType_Type instances */ + PyObject *argtypes; /* tuple of CDataObjects */ + PyObject *converters; /* tuple([t.from_param for t in argtypes]) */ + PyObject *restype; /* CDataObject or NULL */ + PyObject *checker; + int flags; /* calling convention and such */ + + /* pep3118 fields, pointers neeed PyMem_Free */ + char *format; + int ndim; + Py_ssize_t *shape; +/* Py_ssize_t *strides; */ /* unused in ctypes */ +/* Py_ssize_t *suboffsets; */ /* unused in ctypes */ } StgDictObject; @@ -264,16 +264,16 @@ typedef int(* PPROC)(void); PyObject *_ctypes_callproc(PPROC pProc, - PyObject *arguments, + PyObject *arguments, #ifdef MS_WIN32 - IUnknown *pIUnk, - GUID *iid, + IUnknown *pIUnk, + GUID *iid, #endif - int flags, - PyObject *argtypes, - PyObject *restype, - PyObject *checker); - + int flags, + PyObject *argtypes, + PyObject *restype, + PyObject *checker); + #define FUNCFLAG_STDCALL 0x0 #define FUNCFLAG_CDECL 0x1 @@ -288,45 +288,45 @@ #define DICTFLAG_FINAL 0x1000 struct tagPyCArgObject { - PyObject_HEAD - ffi_type *pffi_type; - char tag; - union { - char c; - char b; - short h; - int i; - long l; + PyObject_HEAD + ffi_type *pffi_type; + char tag; + union { + char c; + char b; + short h; + int i; + long l; #ifdef HAVE_LONG_LONG - PY_LONG_LONG q; + PY_LONG_LONG q; #endif - long double D; - double d; - float f; - void *p; - } value; - PyObject *obj; - Py_ssize_t size; /* for the 'V' tag */ + long double D; + double d; + float f; + void *p; + } value; + PyObject *obj; + Py_ssize_t size; /* for the 'V' tag */ }; extern PyTypeObject PyCArg_Type; -#define PyCArg_CheckExact(v) ((v)->ob_type == &PyCArg_Type) +#define PyCArg_CheckExact(v) ((v)->ob_type == &PyCArg_Type) extern PyCArgObject *PyCArgObject_new(void); extern PyObject * PyCData_get(PyObject *type, GETFUNC getfunc, PyObject *src, - Py_ssize_t index, Py_ssize_t size, char *ptr); + Py_ssize_t index, Py_ssize_t size, char *ptr); extern int PyCData_set(PyObject *dst, PyObject *type, SETFUNC setfunc, PyObject *value, - Py_ssize_t index, Py_ssize_t size, char *ptr); + Py_ssize_t index, Py_ssize_t size, char *ptr); extern void _ctypes_extend_error(PyObject *exc_class, char *fmt, ...); struct basespec { - CDataObject *base; - Py_ssize_t index; - char *adr; + CDataObject *base; + Py_ssize_t index; + char *adr; }; extern char basespec_string[]; Modified: python/branches/release31-maint/Modules/_ctypes/darwin/dlfcn_simple.c ============================================================================== --- python/branches/release31-maint/Modules/_ctypes/darwin/dlfcn_simple.c (original) +++ python/branches/release31-maint/Modules/_ctypes/darwin/dlfcn_simple.c Sun May 9 18:14:21 2010 @@ -81,167 +81,167 @@ /* Set and get the error string for use by dlerror */ static const char *error(int setget, const char *str, ...) { - static char errstr[ERR_STR_LEN]; - static int err_filled = 0; - const char *retval; - va_list arg; - if (setget == 0) - { - va_start(arg, str); - strncpy(errstr, "dlcompat: ", ERR_STR_LEN); - vsnprintf(errstr + 10, ERR_STR_LEN - 10, str, arg); - va_end(arg); - err_filled = 1; - retval = NULL; - } - else - { - if (!err_filled) - retval = NULL; - else - retval = errstr; - err_filled = 0; - } - return retval; + static char errstr[ERR_STR_LEN]; + static int err_filled = 0; + const char *retval; + va_list arg; + if (setget == 0) + { + va_start(arg, str); + strncpy(errstr, "dlcompat: ", ERR_STR_LEN); + vsnprintf(errstr + 10, ERR_STR_LEN - 10, str, arg); + va_end(arg); + err_filled = 1; + retval = NULL; + } + else + { + if (!err_filled) + retval = NULL; + else + retval = errstr; + err_filled = 0; + } + return retval; } /* darwin_dlopen */ static void *darwin_dlopen(const char *path, int mode) { - void *module = 0; - NSObjectFileImage ofi = 0; - NSObjectFileImageReturnCode ofirc; - - /* If we got no path, the app wants the global namespace, use -1 as the marker - in this case */ - if (!path) - return (void *)-1; - - /* Create the object file image, works for things linked with the -bundle arg to ld */ - ofirc = NSCreateObjectFileImageFromFile(path, &ofi); - switch (ofirc) - { - case NSObjectFileImageSuccess: - /* It was okay, so use NSLinkModule to link in the image */ - module = NSLinkModule(ofi, path, - NSLINKMODULE_OPTION_RETURN_ON_ERROR - | (mode & RTLD_GLOBAL) ? 0 : NSLINKMODULE_OPTION_PRIVATE - | (mode & RTLD_LAZY) ? 0 : NSLINKMODULE_OPTION_BINDNOW); - NSDestroyObjectFileImage(ofi); - break; - case NSObjectFileImageInappropriateFile: - /* It may have been a dynamic library rather than a bundle, try to load it */ - module = (void *)NSAddImage(path, NSADDIMAGE_OPTION_RETURN_ON_ERROR); - break; - default: - /* God knows what we got */ - error(0, "Can not open \"%s\"", path); - return 0; - } - if (!module) - error(0, "Can not open \"%s\"", path); - return module; + void *module = 0; + NSObjectFileImage ofi = 0; + NSObjectFileImageReturnCode ofirc; + + /* If we got no path, the app wants the global namespace, use -1 as the marker + in this case */ + if (!path) + return (void *)-1; + + /* Create the object file image, works for things linked with the -bundle arg to ld */ + ofirc = NSCreateObjectFileImageFromFile(path, &ofi); + switch (ofirc) + { + case NSObjectFileImageSuccess: + /* It was okay, so use NSLinkModule to link in the image */ + module = NSLinkModule(ofi, path, + NSLINKMODULE_OPTION_RETURN_ON_ERROR + | (mode & RTLD_GLOBAL) ? 0 : NSLINKMODULE_OPTION_PRIVATE + | (mode & RTLD_LAZY) ? 0 : NSLINKMODULE_OPTION_BINDNOW); + NSDestroyObjectFileImage(ofi); + break; + case NSObjectFileImageInappropriateFile: + /* It may have been a dynamic library rather than a bundle, try to load it */ + module = (void *)NSAddImage(path, NSADDIMAGE_OPTION_RETURN_ON_ERROR); + break; + default: + /* God knows what we got */ + error(0, "Can not open \"%s\"", path); + return 0; + } + if (!module) + error(0, "Can not open \"%s\"", path); + return module; } /* dlsymIntern is used by dlsym to find the symbol */ static void *dlsymIntern(void *handle, const char *symbol) { - NSSymbol nssym = 0; - /* If the handle is -1, if is the app global context */ - if (handle == (void *)-1) - { - /* Global context, use NSLookupAndBindSymbol */ - if (NSIsSymbolNameDefined(symbol)) - { - nssym = NSLookupAndBindSymbol(symbol); - } - - } - /* Now see if the handle is a struch mach_header* or not, use NSLookupSymbol in image - for libraries, and NSLookupSymbolInModule for bundles */ - else - { - /* Check for both possible magic numbers depending on x86/ppc byte order */ - if ((((struct mach_header *)handle)->magic == MH_MAGIC) || - (((struct mach_header *)handle)->magic == MH_CIGAM)) - { - if (NSIsSymbolNameDefinedInImage((struct mach_header *)handle, symbol)) - { - nssym = NSLookupSymbolInImage((struct mach_header *)handle, - symbol, - NSLOOKUPSYMBOLINIMAGE_OPTION_BIND - | NSLOOKUPSYMBOLINIMAGE_OPTION_RETURN_ON_ERROR); - } - - } - else - { - nssym = NSLookupSymbolInModule(handle, symbol); - } - } - if (!nssym) - { - error(0, "Symbol \"%s\" Not found", symbol); - return NULL; - } - return NSAddressOfSymbol(nssym); + NSSymbol nssym = 0; + /* If the handle is -1, if is the app global context */ + if (handle == (void *)-1) + { + /* Global context, use NSLookupAndBindSymbol */ + if (NSIsSymbolNameDefined(symbol)) + { + nssym = NSLookupAndBindSymbol(symbol); + } + + } + /* Now see if the handle is a struch mach_header* or not, use NSLookupSymbol in image + for libraries, and NSLookupSymbolInModule for bundles */ + else + { + /* Check for both possible magic numbers depending on x86/ppc byte order */ + if ((((struct mach_header *)handle)->magic == MH_MAGIC) || + (((struct mach_header *)handle)->magic == MH_CIGAM)) + { + if (NSIsSymbolNameDefinedInImage((struct mach_header *)handle, symbol)) + { + nssym = NSLookupSymbolInImage((struct mach_header *)handle, + symbol, + NSLOOKUPSYMBOLINIMAGE_OPTION_BIND + | NSLOOKUPSYMBOLINIMAGE_OPTION_RETURN_ON_ERROR); + } + + } + else + { + nssym = NSLookupSymbolInModule(handle, symbol); + } + } + if (!nssym) + { + error(0, "Symbol \"%s\" Not found", symbol); + return NULL; + } + return NSAddressOfSymbol(nssym); } static const char *darwin_dlerror(void) { - return error(1, (char *)NULL); + return error(1, (char *)NULL); } static int darwin_dlclose(void *handle) { - if ((((struct mach_header *)handle)->magic == MH_MAGIC) || - (((struct mach_header *)handle)->magic == MH_CIGAM)) - { - error(0, "Can't remove dynamic libraries on darwin"); - return 0; - } - if (!NSUnLinkModule(handle, 0)) - { - error(0, "unable to unlink module %s", NSNameOfModule(handle)); - return 1; - } - return 0; + if ((((struct mach_header *)handle)->magic == MH_MAGIC) || + (((struct mach_header *)handle)->magic == MH_CIGAM)) + { + error(0, "Can't remove dynamic libraries on darwin"); + return 0; + } + if (!NSUnLinkModule(handle, 0)) + { + error(0, "unable to unlink module %s", NSNameOfModule(handle)); + return 1; + } + return 0; } /* dlsym, prepend the underscore and call dlsymIntern */ static void *darwin_dlsym(void *handle, const char *symbol) { - static char undersym[257]; /* Saves calls to malloc(3) */ - int sym_len = strlen(symbol); - void *value = NULL; - char *malloc_sym = NULL; - - if (sym_len < 256) - { - snprintf(undersym, 256, "_%s", symbol); - value = dlsymIntern(handle, undersym); - } - else - { - malloc_sym = malloc(sym_len + 2); - if (malloc_sym) - { - sprintf(malloc_sym, "_%s", symbol); - value = dlsymIntern(handle, malloc_sym); - free(malloc_sym); - } - else - { - error(0, "Unable to allocate memory"); - } - } - return value; + static char undersym[257]; /* Saves calls to malloc(3) */ + int sym_len = strlen(symbol); + void *value = NULL; + char *malloc_sym = NULL; + + if (sym_len < 256) + { + snprintf(undersym, 256, "_%s", symbol); + value = dlsymIntern(handle, undersym); + } + else + { + malloc_sym = malloc(sym_len + 2); + if (malloc_sym) + { + sprintf(malloc_sym, "_%s", symbol); + value = dlsymIntern(handle, malloc_sym); + free(malloc_sym); + } + else + { + error(0, "Unable to allocate memory"); + } + } + return value; } static int darwin_dladdr(const void *handle, Dl_info *info) { - return 0; + return 0; } #endif /* MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_3 */ @@ -252,21 +252,21 @@ static #endif void ctypes_dlfcn_init(void) { - if (dlopen != NULL) { - ctypes_dlsym = dlsym; - ctypes_dlopen = dlopen; - ctypes_dlerror = dlerror; - ctypes_dlclose = dlclose; - ctypes_dladdr = dladdr; - } else { + if (dlopen != NULL) { + ctypes_dlsym = dlsym; + ctypes_dlopen = dlopen; + ctypes_dlerror = dlerror; + ctypes_dlclose = dlclose; + ctypes_dladdr = dladdr; + } else { #if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_3 - ctypes_dlsym = darwin_dlsym; - ctypes_dlopen = darwin_dlopen; - ctypes_dlerror = darwin_dlerror; - ctypes_dlclose = darwin_dlclose; - ctypes_dladdr = darwin_dladdr; + ctypes_dlsym = darwin_dlsym; + ctypes_dlopen = darwin_dlopen; + ctypes_dlerror = darwin_dlerror; + ctypes_dlclose = darwin_dlclose; + ctypes_dladdr = darwin_dladdr; #endif /* MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_3 */ - } + } } #endif /* CTYPES_DARWIN_DLFCN */ Modified: python/branches/release31-maint/Modules/_ctypes/malloc_closure.c ============================================================================== --- python/branches/release31-maint/Modules/_ctypes/malloc_closure.c (original) +++ python/branches/release31-maint/Modules/_ctypes/malloc_closure.c Sun May 9 18:14:21 2010 @@ -23,8 +23,8 @@ /******************************************************************/ typedef union _tagITEM { - ffi_closure closure; - union _tagITEM *next; + ffi_closure closure; + union _tagITEM *next; } ITEM; static ITEM *free_list; @@ -32,58 +32,58 @@ static void more_core(void) { - ITEM *item; - int count, i; + ITEM *item; + int count, i; /* determine the pagesize */ #ifdef MS_WIN32 - if (!_pagesize) { - SYSTEM_INFO systeminfo; - GetSystemInfo(&systeminfo); - _pagesize = systeminfo.dwPageSize; - } + if (!_pagesize) { + SYSTEM_INFO systeminfo; + GetSystemInfo(&systeminfo); + _pagesize = systeminfo.dwPageSize; + } #else - if (!_pagesize) { + if (!_pagesize) { #ifdef _SC_PAGESIZE - _pagesize = sysconf(_SC_PAGESIZE); + _pagesize = sysconf(_SC_PAGESIZE); #else - _pagesize = getpagesize(); + _pagesize = getpagesize(); #endif - } + } #endif - /* calculate the number of nodes to allocate */ - count = BLOCKSIZE / sizeof(ITEM); + /* calculate the number of nodes to allocate */ + count = BLOCKSIZE / sizeof(ITEM); - /* allocate a memory block */ + /* allocate a memory block */ #ifdef MS_WIN32 - item = (ITEM *)VirtualAlloc(NULL, - count * sizeof(ITEM), - MEM_COMMIT, - PAGE_EXECUTE_READWRITE); - if (item == NULL) - return; + item = (ITEM *)VirtualAlloc(NULL, + count * sizeof(ITEM), + MEM_COMMIT, + PAGE_EXECUTE_READWRITE); + if (item == NULL) + return; #else - item = (ITEM *)mmap(NULL, - count * sizeof(ITEM), - PROT_READ | PROT_WRITE | PROT_EXEC, - MAP_PRIVATE | MAP_ANONYMOUS, - -1, - 0); - if (item == (void *)MAP_FAILED) - return; + item = (ITEM *)mmap(NULL, + count * sizeof(ITEM), + PROT_READ | PROT_WRITE | PROT_EXEC, + MAP_PRIVATE | MAP_ANONYMOUS, + -1, + 0); + if (item == (void *)MAP_FAILED) + return; #endif #ifdef MALLOC_CLOSURE_DEBUG - printf("block at %p allocated (%d bytes), %d ITEMs\n", - item, count * sizeof(ITEM), count); + printf("block at %p allocated (%d bytes), %d ITEMs\n", + item, count * sizeof(ITEM), count); #endif - /* put them into the free list */ - for (i = 0; i < count; ++i) { - item->next = free_list; - free_list = item; - ++item; - } + /* put them into the free list */ + for (i = 0; i < count; ++i) { + item->next = free_list; + free_list = item; + ++item; + } } /******************************************************************/ @@ -91,20 +91,20 @@ /* put the item back into the free list */ void _ctypes_free_closure(void *p) { - ITEM *item = (ITEM *)p; - item->next = free_list; - free_list = item; + ITEM *item = (ITEM *)p; + item->next = free_list; + free_list = item; } /* return one item from the free list, allocating more if needed */ void *_ctypes_alloc_closure(void) { - ITEM *item; - if (!free_list) - more_core(); - if (!free_list) - return NULL; - item = free_list; - free_list = item->next; - return item; + ITEM *item; + if (!free_list) + more_core(); + if (!free_list) + return NULL; + item = free_list; + free_list = item->next; + return item; } Modified: python/branches/release31-maint/Modules/_ctypes/stgdict.c ============================================================================== --- python/branches/release31-maint/Modules/_ctypes/stgdict.c (original) +++ python/branches/release31-maint/Modules/_ctypes/stgdict.c Sun May 9 18:14:21 2010 @@ -19,143 +19,143 @@ static int PyCStgDict_init(StgDictObject *self, PyObject *args, PyObject *kwds) { - if (PyDict_Type.tp_init((PyObject *)self, args, kwds) < 0) - return -1; - self->format = NULL; - self->ndim = 0; - self->shape = NULL; - return 0; + if (PyDict_Type.tp_init((PyObject *)self, args, kwds) < 0) + return -1; + self->format = NULL; + self->ndim = 0; + self->shape = NULL; + return 0; } static int PyCStgDict_clear(StgDictObject *self) { - Py_CLEAR(self->proto); - Py_CLEAR(self->argtypes); - Py_CLEAR(self->converters); - Py_CLEAR(self->restype); - Py_CLEAR(self->checker); - return 0; + Py_CLEAR(self->proto); + Py_CLEAR(self->argtypes); + Py_CLEAR(self->converters); + Py_CLEAR(self->restype); + Py_CLEAR(self->checker); + return 0; } static void PyCStgDict_dealloc(StgDictObject *self) { - PyCStgDict_clear(self); - PyMem_Free(self->format); - PyMem_Free(self->shape); - PyMem_Free(self->ffi_type_pointer.elements); - PyDict_Type.tp_dealloc((PyObject *)self); + PyCStgDict_clear(self); + PyMem_Free(self->format); + PyMem_Free(self->shape); + PyMem_Free(self->ffi_type_pointer.elements); + PyDict_Type.tp_dealloc((PyObject *)self); } int PyCStgDict_clone(StgDictObject *dst, StgDictObject *src) { - char *d, *s; - Py_ssize_t size; + char *d, *s; + Py_ssize_t size; - PyCStgDict_clear(dst); - PyMem_Free(dst->ffi_type_pointer.elements); - PyMem_Free(dst->format); - dst->format = NULL; - PyMem_Free(dst->shape); - dst->shape = NULL; - dst->ffi_type_pointer.elements = NULL; - - d = (char *)dst; - s = (char *)src; - memcpy(d + sizeof(PyDictObject), - s + sizeof(PyDictObject), - sizeof(StgDictObject) - sizeof(PyDictObject)); - - Py_XINCREF(dst->proto); - Py_XINCREF(dst->argtypes); - Py_XINCREF(dst->converters); - Py_XINCREF(dst->restype); - Py_XINCREF(dst->checker); - - if (src->format) { - dst->format = PyMem_Malloc(strlen(src->format) + 1); - if (dst->format == NULL) - return -1; - strcpy(dst->format, src->format); - } - if (src->shape) { - dst->shape = PyMem_Malloc(sizeof(Py_ssize_t) * src->ndim); - if (dst->shape == NULL) - return -1; - memcpy(dst->shape, src->shape, - sizeof(Py_ssize_t) * src->ndim); - } - - if (src->ffi_type_pointer.elements == NULL) - return 0; - size = sizeof(ffi_type *) * (src->length + 1); - dst->ffi_type_pointer.elements = PyMem_Malloc(size); - if (dst->ffi_type_pointer.elements == NULL) { - PyErr_NoMemory(); - return -1; - } - memcpy(dst->ffi_type_pointer.elements, - src->ffi_type_pointer.elements, - size); - return 0; + PyCStgDict_clear(dst); + PyMem_Free(dst->ffi_type_pointer.elements); + PyMem_Free(dst->format); + dst->format = NULL; + PyMem_Free(dst->shape); + dst->shape = NULL; + dst->ffi_type_pointer.elements = NULL; + + d = (char *)dst; + s = (char *)src; + memcpy(d + sizeof(PyDictObject), + s + sizeof(PyDictObject), + sizeof(StgDictObject) - sizeof(PyDictObject)); + + Py_XINCREF(dst->proto); + Py_XINCREF(dst->argtypes); + Py_XINCREF(dst->converters); + Py_XINCREF(dst->restype); + Py_XINCREF(dst->checker); + + if (src->format) { + dst->format = PyMem_Malloc(strlen(src->format) + 1); + if (dst->format == NULL) + return -1; + strcpy(dst->format, src->format); + } + if (src->shape) { + dst->shape = PyMem_Malloc(sizeof(Py_ssize_t) * src->ndim); + if (dst->shape == NULL) + return -1; + memcpy(dst->shape, src->shape, + sizeof(Py_ssize_t) * src->ndim); + } + + if (src->ffi_type_pointer.elements == NULL) + return 0; + size = sizeof(ffi_type *) * (src->length + 1); + dst->ffi_type_pointer.elements = PyMem_Malloc(size); + if (dst->ffi_type_pointer.elements == NULL) { + PyErr_NoMemory(); + return -1; + } + memcpy(dst->ffi_type_pointer.elements, + src->ffi_type_pointer.elements, + size); + return 0; } PyTypeObject PyCStgDict_Type = { - PyVarObject_HEAD_INIT(NULL, 0) - "StgDict", - sizeof(StgDictObject), - 0, - (destructor)PyCStgDict_dealloc, /* tp_dealloc */ - 0, /* tp_print */ - 0, /* tp_getattr */ - 0, /* tp_setattr */ - 0, /* tp_reserved */ - 0, /* tp_repr */ - 0, /* tp_as_number */ - 0, /* tp_as_sequence */ - 0, /* tp_as_mapping */ - 0, /* tp_hash */ - 0, /* tp_call */ - 0, /* tp_str */ - 0, /* tp_getattro */ - 0, /* tp_setattro */ - 0, /* tp_as_buffer */ - Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */ - 0, /* tp_doc */ - 0, /* tp_traverse */ - 0, /* tp_clear */ - 0, /* tp_richcompare */ - 0, /* tp_weaklistoffset */ - 0, /* tp_iter */ - 0, /* tp_iternext */ - 0, /* tp_methods */ - 0, /* tp_members */ - 0, /* tp_getset */ - 0, /* tp_base */ - 0, /* tp_dict */ - 0, /* tp_descr_get */ - 0, /* tp_descr_set */ - 0, /* tp_dictoffset */ - (initproc)PyCStgDict_init, /* tp_init */ - 0, /* tp_alloc */ - 0, /* tp_new */ - 0, /* tp_free */ + PyVarObject_HEAD_INIT(NULL, 0) + "StgDict", + sizeof(StgDictObject), + 0, + (destructor)PyCStgDict_dealloc, /* tp_dealloc */ + 0, /* tp_print */ + 0, /* tp_getattr */ + 0, /* tp_setattr */ + 0, /* tp_reserved */ + 0, /* tp_repr */ + 0, /* tp_as_number */ + 0, /* tp_as_sequence */ + 0, /* tp_as_mapping */ + 0, /* tp_hash */ + 0, /* tp_call */ + 0, /* tp_str */ + 0, /* tp_getattro */ + 0, /* tp_setattro */ + 0, /* tp_as_buffer */ + Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */ + 0, /* tp_doc */ + 0, /* tp_traverse */ + 0, /* tp_clear */ + 0, /* tp_richcompare */ + 0, /* tp_weaklistoffset */ + 0, /* tp_iter */ + 0, /* tp_iternext */ + 0, /* tp_methods */ + 0, /* tp_members */ + 0, /* tp_getset */ + 0, /* tp_base */ + 0, /* tp_dict */ + 0, /* tp_descr_get */ + 0, /* tp_descr_set */ + 0, /* tp_dictoffset */ + (initproc)PyCStgDict_init, /* tp_init */ + 0, /* tp_alloc */ + 0, /* tp_new */ + 0, /* tp_free */ }; /* May return NULL, but does not set an exception! */ StgDictObject * PyType_stgdict(PyObject *obj) { - PyTypeObject *type; + PyTypeObject *type; - if (!PyType_Check(obj)) - return NULL; - type = (PyTypeObject *)obj; - if (!type->tp_dict || !PyCStgDict_CheckExact(type->tp_dict)) - return NULL; - return (StgDictObject *)type->tp_dict; + if (!PyType_Check(obj)) + return NULL; + type = (PyTypeObject *)obj; + if (!type->tp_dict || !PyCStgDict_CheckExact(type->tp_dict)) + return NULL; + return (StgDictObject *)type->tp_dict; } /* May return NULL, but does not set an exception! */ @@ -166,10 +166,10 @@ StgDictObject * PyObject_stgdict(PyObject *self) { - PyTypeObject *type = self->ob_type; - if (!type->tp_dict || !PyCStgDict_CheckExact(type->tp_dict)) - return NULL; - return (StgDictObject *)type->tp_dict; + PyTypeObject *type = self->ob_type; + if (!type->tp_dict || !PyCStgDict_CheckExact(type->tp_dict)) + return NULL; + return (StgDictObject *)type->tp_dict; } /* descr is the descriptor for a field marked as anonymous. Get all the @@ -178,78 +178,78 @@ */ static int MakeFields(PyObject *type, CFieldObject *descr, - Py_ssize_t index, Py_ssize_t offset) + Py_ssize_t index, Py_ssize_t offset) { - Py_ssize_t i; - PyObject *fields; - PyObject *fieldlist; - - fields = PyObject_GetAttrString(descr->proto, "_fields_"); - if (fields == NULL) - return -1; - fieldlist = PySequence_Fast(fields, "_fields_ must be a sequence"); - Py_DECREF(fields); - if (fieldlist == NULL) - return -1; - - for (i = 0; i < PySequence_Fast_GET_SIZE(fieldlist); ++i) { - PyObject *pair = PySequence_Fast_GET_ITEM(fieldlist, i); /* borrowed */ - PyObject *fname, *ftype, *bits; - CFieldObject *fdescr; - CFieldObject *new_descr; - /* Convert to PyArg_UnpackTuple... */ - if (!PyArg_ParseTuple(pair, "OO|O", &fname, &ftype, &bits)) { - Py_DECREF(fieldlist); - return -1; - } - fdescr = (CFieldObject *)PyObject_GetAttr(descr->proto, fname); - if (fdescr == NULL) { - Py_DECREF(fieldlist); - return -1; - } - if (Py_TYPE(fdescr) != &PyCField_Type) { - PyErr_SetString(PyExc_TypeError, "unexpected type"); - Py_DECREF(fdescr); - Py_DECREF(fieldlist); - return -1; - } - if (fdescr->anonymous) { - int rc = MakeFields(type, fdescr, - index + fdescr->index, - offset + fdescr->offset); - Py_DECREF(fdescr); - if (rc == -1) { - Py_DECREF(fieldlist); - return -1; - } - continue; - } - new_descr = (CFieldObject *)PyObject_CallObject((PyObject *)&PyCField_Type, NULL); - if (new_descr == NULL) { - Py_DECREF(fdescr); - Py_DECREF(fieldlist); - return -1; - } - assert(Py_TYPE(new_descr) == &PyCField_Type); - new_descr->size = fdescr->size; - new_descr->offset = fdescr->offset + offset; - new_descr->index = fdescr->index + index; - new_descr->proto = fdescr->proto; - Py_XINCREF(new_descr->proto); - new_descr->getfunc = fdescr->getfunc; - new_descr->setfunc = fdescr->setfunc; - - Py_DECREF(fdescr); - - if (-1 == PyObject_SetAttr(type, fname, (PyObject *)new_descr)) { - Py_DECREF(fieldlist); - Py_DECREF(new_descr); - return -1; - } - Py_DECREF(new_descr); - } - Py_DECREF(fieldlist); - return 0; + Py_ssize_t i; + PyObject *fields; + PyObject *fieldlist; + + fields = PyObject_GetAttrString(descr->proto, "_fields_"); + if (fields == NULL) + return -1; + fieldlist = PySequence_Fast(fields, "_fields_ must be a sequence"); + Py_DECREF(fields); + if (fieldlist == NULL) + return -1; + + for (i = 0; i < PySequence_Fast_GET_SIZE(fieldlist); ++i) { + PyObject *pair = PySequence_Fast_GET_ITEM(fieldlist, i); /* borrowed */ + PyObject *fname, *ftype, *bits; + CFieldObject *fdescr; + CFieldObject *new_descr; + /* Convert to PyArg_UnpackTuple... */ + if (!PyArg_ParseTuple(pair, "OO|O", &fname, &ftype, &bits)) { + Py_DECREF(fieldlist); + return -1; + } + fdescr = (CFieldObject *)PyObject_GetAttr(descr->proto, fname); + if (fdescr == NULL) { + Py_DECREF(fieldlist); + return -1; + } + if (Py_TYPE(fdescr) != &PyCField_Type) { + PyErr_SetString(PyExc_TypeError, "unexpected type"); + Py_DECREF(fdescr); + Py_DECREF(fieldlist); + return -1; + } + if (fdescr->anonymous) { + int rc = MakeFields(type, fdescr, + index + fdescr->index, + offset + fdescr->offset); + Py_DECREF(fdescr); + if (rc == -1) { + Py_DECREF(fieldlist); + return -1; + } + continue; + } + new_descr = (CFieldObject *)PyObject_CallObject((PyObject *)&PyCField_Type, NULL); + if (new_descr == NULL) { + Py_DECREF(fdescr); + Py_DECREF(fieldlist); + return -1; + } + assert(Py_TYPE(new_descr) == &PyCField_Type); + new_descr->size = fdescr->size; + new_descr->offset = fdescr->offset + offset; + new_descr->index = fdescr->index + index; + new_descr->proto = fdescr->proto; + Py_XINCREF(new_descr->proto); + new_descr->getfunc = fdescr->getfunc; + new_descr->setfunc = fdescr->setfunc; + + Py_DECREF(fdescr); + + if (-1 == PyObject_SetAttr(type, fname, (PyObject *)new_descr)) { + Py_DECREF(fieldlist); + Py_DECREF(new_descr); + return -1; + } + Py_DECREF(new_descr); + } + Py_DECREF(fieldlist); + return 0; } /* Iterate over the names in the type's _anonymous_ attribute, if present, @@ -257,43 +257,43 @@ static int MakeAnonFields(PyObject *type) { - PyObject *anon; - PyObject *anon_names; - Py_ssize_t i; - - anon = PyObject_GetAttrString(type, "_anonymous_"); - if (anon == NULL) { - PyErr_Clear(); - return 0; - } - anon_names = PySequence_Fast(anon, "_anonymous_ must be a sequence"); - Py_DECREF(anon); - if (anon_names == NULL) - return -1; - - for (i = 0; i < PySequence_Fast_GET_SIZE(anon_names); ++i) { - PyObject *fname = PySequence_Fast_GET_ITEM(anon_names, i); /* borrowed */ - CFieldObject *descr = (CFieldObject *)PyObject_GetAttr(type, fname); - if (descr == NULL) { - Py_DECREF(anon_names); - return -1; - } - assert(Py_TYPE(descr) == &PyCField_Type); - descr->anonymous = 1; - - /* descr is in the field descriptor. */ - if (-1 == MakeFields(type, (CFieldObject *)descr, - ((CFieldObject *)descr)->index, - ((CFieldObject *)descr)->offset)) { - Py_DECREF(descr); - Py_DECREF(anon_names); - return -1; - } - Py_DECREF(descr); - } + PyObject *anon; + PyObject *anon_names; + Py_ssize_t i; + + anon = PyObject_GetAttrString(type, "_anonymous_"); + if (anon == NULL) { + PyErr_Clear(); + return 0; + } + anon_names = PySequence_Fast(anon, "_anonymous_ must be a sequence"); + Py_DECREF(anon); + if (anon_names == NULL) + return -1; + + for (i = 0; i < PySequence_Fast_GET_SIZE(anon_names); ++i) { + PyObject *fname = PySequence_Fast_GET_ITEM(anon_names, i); /* borrowed */ + CFieldObject *descr = (CFieldObject *)PyObject_GetAttr(type, fname); + if (descr == NULL) { + Py_DECREF(anon_names); + return -1; + } + assert(Py_TYPE(descr) == &PyCField_Type); + descr->anonymous = 1; + + /* descr is in the field descriptor. */ + if (-1 == MakeFields(type, (CFieldObject *)descr, + ((CFieldObject *)descr)->index, + ((CFieldObject *)descr)->offset)) { + Py_DECREF(descr); + Py_DECREF(anon_names); + return -1; + } + Py_DECREF(descr); + } - Py_DECREF(anon_names); - return 0; + Py_DECREF(anon_names); + return 0; } /* @@ -303,261 +303,261 @@ int PyCStructUnionType_update_stgdict(PyObject *type, PyObject *fields, int isStruct) { - StgDictObject *stgdict, *basedict; - Py_ssize_t len, offset, size, align, i; - Py_ssize_t union_size, total_align; - Py_ssize_t field_size = 0; - int bitofs; - PyObject *isPacked; - int pack = 0; - Py_ssize_t ffi_ofs; - int big_endian; - - /* HACK Alert: I cannot be bothered to fix ctypes.com, so there has to - be a way to use the old, broken sematics: _fields_ are not extended - but replaced in subclasses. - - XXX Remove this in ctypes 1.0! - */ - int use_broken_old_ctypes_semantics; + StgDictObject *stgdict, *basedict; + Py_ssize_t len, offset, size, align, i; + Py_ssize_t union_size, total_align; + Py_ssize_t field_size = 0; + int bitofs; + PyObject *isPacked; + int pack = 0; + Py_ssize_t ffi_ofs; + int big_endian; + + /* HACK Alert: I cannot be bothered to fix ctypes.com, so there has to + be a way to use the old, broken sematics: _fields_ are not extended + but replaced in subclasses. + + XXX Remove this in ctypes 1.0! + */ + int use_broken_old_ctypes_semantics; - if (fields == NULL) - return 0; + if (fields == NULL) + return 0; #ifdef WORDS_BIGENDIAN - big_endian = PyObject_HasAttrString(type, "_swappedbytes_") ? 0 : 1; + big_endian = PyObject_HasAttrString(type, "_swappedbytes_") ? 0 : 1; #else - big_endian = PyObject_HasAttrString(type, "_swappedbytes_") ? 1 : 0; + big_endian = PyObject_HasAttrString(type, "_swappedbytes_") ? 1 : 0; #endif - use_broken_old_ctypes_semantics = \ - PyObject_HasAttrString(type, "_use_broken_old_ctypes_structure_semantics_"); + use_broken_old_ctypes_semantics = \ + PyObject_HasAttrString(type, "_use_broken_old_ctypes_structure_semantics_"); - isPacked = PyObject_GetAttrString(type, "_pack_"); - if (isPacked) { - pack = PyLong_AsLong(isPacked); - if (pack < 0 || PyErr_Occurred()) { - Py_XDECREF(isPacked); - PyErr_SetString(PyExc_ValueError, - "_pack_ must be a non-negative integer"); - return -1; - } - Py_DECREF(isPacked); - } else - PyErr_Clear(); - - len = PySequence_Length(fields); - if (len == -1) { - PyErr_SetString(PyExc_TypeError, - "'_fields_' must be a sequence of pairs"); - return -1; - } - - stgdict = PyType_stgdict(type); - if (!stgdict) - return -1; - /* If this structure/union is already marked final we cannot assign - _fields_ anymore. */ - - if (stgdict->flags & DICTFLAG_FINAL) {/* is final ? */ - PyErr_SetString(PyExc_AttributeError, - "_fields_ is final"); - return -1; - } - - if (stgdict->format) { - PyMem_Free(stgdict->format); - stgdict->format = NULL; - } - - if (stgdict->ffi_type_pointer.elements) - PyMem_Free(stgdict->ffi_type_pointer.elements); - - basedict = PyType_stgdict((PyObject *)((PyTypeObject *)type)->tp_base); - if (basedict && !use_broken_old_ctypes_semantics) { - size = offset = basedict->size; - align = basedict->align; - union_size = 0; - total_align = align ? align : 1; - stgdict->ffi_type_pointer.type = FFI_TYPE_STRUCT; - stgdict->ffi_type_pointer.elements = PyMem_Malloc(sizeof(ffi_type *) * (basedict->length + len + 1)); - if (stgdict->ffi_type_pointer.elements == NULL) { - PyErr_NoMemory(); - return -1; - } - memset(stgdict->ffi_type_pointer.elements, 0, - sizeof(ffi_type *) * (basedict->length + len + 1)); - memcpy(stgdict->ffi_type_pointer.elements, - basedict->ffi_type_pointer.elements, - sizeof(ffi_type *) * (basedict->length)); - ffi_ofs = basedict->length; - } else { - offset = 0; - size = 0; - align = 0; - union_size = 0; - total_align = 1; - stgdict->ffi_type_pointer.type = FFI_TYPE_STRUCT; - stgdict->ffi_type_pointer.elements = PyMem_Malloc(sizeof(ffi_type *) * (len + 1)); - if (stgdict->ffi_type_pointer.elements == NULL) { - PyErr_NoMemory(); - return -1; - } - memset(stgdict->ffi_type_pointer.elements, 0, - sizeof(ffi_type *) * (len + 1)); - ffi_ofs = 0; - } - - assert(stgdict->format == NULL); - if (isStruct && !isPacked) { - stgdict->format = _ctypes_alloc_format_string(NULL, "T{"); - } else { - /* PEP3118 doesn't support union, or packed structures (well, - only standard packing, but we dont support the pep for - that). Use 'B' for bytes. */ - stgdict->format = _ctypes_alloc_format_string(NULL, "B"); - } + isPacked = PyObject_GetAttrString(type, "_pack_"); + if (isPacked) { + pack = PyLong_AsLong(isPacked); + if (pack < 0 || PyErr_Occurred()) { + Py_XDECREF(isPacked); + PyErr_SetString(PyExc_ValueError, + "_pack_ must be a non-negative integer"); + return -1; + } + Py_DECREF(isPacked); + } else + PyErr_Clear(); + + len = PySequence_Length(fields); + if (len == -1) { + PyErr_SetString(PyExc_TypeError, + "'_fields_' must be a sequence of pairs"); + return -1; + } + + stgdict = PyType_stgdict(type); + if (!stgdict) + return -1; + /* If this structure/union is already marked final we cannot assign + _fields_ anymore. */ + + if (stgdict->flags & DICTFLAG_FINAL) {/* is final ? */ + PyErr_SetString(PyExc_AttributeError, + "_fields_ is final"); + return -1; + } + + if (stgdict->format) { + PyMem_Free(stgdict->format); + stgdict->format = NULL; + } + + if (stgdict->ffi_type_pointer.elements) + PyMem_Free(stgdict->ffi_type_pointer.elements); + + basedict = PyType_stgdict((PyObject *)((PyTypeObject *)type)->tp_base); + if (basedict && !use_broken_old_ctypes_semantics) { + size = offset = basedict->size; + align = basedict->align; + union_size = 0; + total_align = align ? align : 1; + stgdict->ffi_type_pointer.type = FFI_TYPE_STRUCT; + stgdict->ffi_type_pointer.elements = PyMem_Malloc(sizeof(ffi_type *) * (basedict->length + len + 1)); + if (stgdict->ffi_type_pointer.elements == NULL) { + PyErr_NoMemory(); + return -1; + } + memset(stgdict->ffi_type_pointer.elements, 0, + sizeof(ffi_type *) * (basedict->length + len + 1)); + memcpy(stgdict->ffi_type_pointer.elements, + basedict->ffi_type_pointer.elements, + sizeof(ffi_type *) * (basedict->length)); + ffi_ofs = basedict->length; + } else { + offset = 0; + size = 0; + align = 0; + union_size = 0; + total_align = 1; + stgdict->ffi_type_pointer.type = FFI_TYPE_STRUCT; + stgdict->ffi_type_pointer.elements = PyMem_Malloc(sizeof(ffi_type *) * (len + 1)); + if (stgdict->ffi_type_pointer.elements == NULL) { + PyErr_NoMemory(); + return -1; + } + memset(stgdict->ffi_type_pointer.elements, 0, + sizeof(ffi_type *) * (len + 1)); + ffi_ofs = 0; + } + + assert(stgdict->format == NULL); + if (isStruct && !isPacked) { + stgdict->format = _ctypes_alloc_format_string(NULL, "T{"); + } else { + /* PEP3118 doesn't support union, or packed structures (well, + only standard packing, but we dont support the pep for + that). Use 'B' for bytes. */ + stgdict->format = _ctypes_alloc_format_string(NULL, "B"); + } #define realdict ((PyObject *)&stgdict->dict) - for (i = 0; i < len; ++i) { - PyObject *name = NULL, *desc = NULL; - PyObject *pair = PySequence_GetItem(fields, i); - PyObject *prop; - StgDictObject *dict; - int bitsize = 0; - - if (!pair || !PyArg_ParseTuple(pair, "OO|i", &name, &desc, &bitsize)) { - PyErr_SetString(PyExc_AttributeError, - "'_fields_' must be a sequence of pairs"); - Py_XDECREF(pair); - return -1; - } - dict = PyType_stgdict(desc); - if (dict == NULL) { - Py_DECREF(pair); - PyErr_Format(PyExc_TypeError, - "second item in _fields_ tuple (index %zd) must be a C type", - i); - return -1; - } - stgdict->ffi_type_pointer.elements[ffi_ofs + i] = &dict->ffi_type_pointer; - if (dict->flags & (TYPEFLAG_ISPOINTER | TYPEFLAG_HASPOINTER)) - stgdict->flags |= TYPEFLAG_HASPOINTER; - dict->flags |= DICTFLAG_FINAL; /* mark field type final */ - if (PyTuple_Size(pair) == 3) { /* bits specified */ - switch(dict->ffi_type_pointer.type) { - case FFI_TYPE_UINT8: - case FFI_TYPE_UINT16: - case FFI_TYPE_UINT32: - case FFI_TYPE_SINT64: - case FFI_TYPE_UINT64: - break; - - case FFI_TYPE_SINT8: - case FFI_TYPE_SINT16: - case FFI_TYPE_SINT32: - if (dict->getfunc != _ctypes_get_fielddesc("c")->getfunc + for (i = 0; i < len; ++i) { + PyObject *name = NULL, *desc = NULL; + PyObject *pair = PySequence_GetItem(fields, i); + PyObject *prop; + StgDictObject *dict; + int bitsize = 0; + + if (!pair || !PyArg_ParseTuple(pair, "OO|i", &name, &desc, &bitsize)) { + PyErr_SetString(PyExc_AttributeError, + "'_fields_' must be a sequence of pairs"); + Py_XDECREF(pair); + return -1; + } + dict = PyType_stgdict(desc); + if (dict == NULL) { + Py_DECREF(pair); + PyErr_Format(PyExc_TypeError, + "second item in _fields_ tuple (index %zd) must be a C type", + i); + return -1; + } + stgdict->ffi_type_pointer.elements[ffi_ofs + i] = &dict->ffi_type_pointer; + if (dict->flags & (TYPEFLAG_ISPOINTER | TYPEFLAG_HASPOINTER)) + stgdict->flags |= TYPEFLAG_HASPOINTER; + dict->flags |= DICTFLAG_FINAL; /* mark field type final */ + if (PyTuple_Size(pair) == 3) { /* bits specified */ + switch(dict->ffi_type_pointer.type) { + case FFI_TYPE_UINT8: + case FFI_TYPE_UINT16: + case FFI_TYPE_UINT32: + case FFI_TYPE_SINT64: + case FFI_TYPE_UINT64: + break; + + case FFI_TYPE_SINT8: + case FFI_TYPE_SINT16: + case FFI_TYPE_SINT32: + if (dict->getfunc != _ctypes_get_fielddesc("c")->getfunc #ifdef CTYPES_UNICODE - && dict->getfunc != _ctypes_get_fielddesc("u")->getfunc + && dict->getfunc != _ctypes_get_fielddesc("u")->getfunc #endif - ) - break; - /* else fall through */ - default: - PyErr_Format(PyExc_TypeError, - "bit fields not allowed for type %s", - ((PyTypeObject *)desc)->tp_name); - Py_DECREF(pair); - return -1; - } - if (bitsize <= 0 || bitsize > dict->size * 8) { - PyErr_SetString(PyExc_ValueError, - "number of bits invalid for bit field"); - Py_DECREF(pair); - return -1; - } - } else - bitsize = 0; - if (isStruct && !isPacked) { - char *fieldfmt = dict->format ? dict->format : "B"; - char *fieldname = _PyUnicode_AsString(name); - char *ptr; - Py_ssize_t len = strlen(fieldname) + strlen(fieldfmt); - char *buf = alloca(len + 2 + 1); - - sprintf(buf, "%s:%s:", fieldfmt, fieldname); - - ptr = stgdict->format; - stgdict->format = _ctypes_alloc_format_string(stgdict->format, buf); - PyMem_Free(ptr); - - if (stgdict->format == NULL) { - Py_DECREF(pair); - return -1; - } - } - if (isStruct) { - prop = PyCField_FromDesc(desc, i, - &field_size, bitsize, &bitofs, - &size, &offset, &align, - pack, big_endian); - } else /* union */ { - size = 0; - offset = 0; - align = 0; - prop = PyCField_FromDesc(desc, i, - &field_size, bitsize, &bitofs, - &size, &offset, &align, - pack, big_endian); - union_size = max(size, union_size); - } - total_align = max(align, total_align); - - if (!prop) { - Py_DECREF(pair); - return -1; - } - if (-1 == PyObject_SetAttr(type, name, prop)) { - Py_DECREF(prop); - Py_DECREF(pair); - return -1; - } - Py_DECREF(pair); - Py_DECREF(prop); - } + ) + break; + /* else fall through */ + default: + PyErr_Format(PyExc_TypeError, + "bit fields not allowed for type %s", + ((PyTypeObject *)desc)->tp_name); + Py_DECREF(pair); + return -1; + } + if (bitsize <= 0 || bitsize > dict->size * 8) { + PyErr_SetString(PyExc_ValueError, + "number of bits invalid for bit field"); + Py_DECREF(pair); + return -1; + } + } else + bitsize = 0; + if (isStruct && !isPacked) { + char *fieldfmt = dict->format ? dict->format : "B"; + char *fieldname = _PyUnicode_AsString(name); + char *ptr; + Py_ssize_t len = strlen(fieldname) + strlen(fieldfmt); + char *buf = alloca(len + 2 + 1); + + sprintf(buf, "%s:%s:", fieldfmt, fieldname); + + ptr = stgdict->format; + stgdict->format = _ctypes_alloc_format_string(stgdict->format, buf); + PyMem_Free(ptr); + + if (stgdict->format == NULL) { + Py_DECREF(pair); + return -1; + } + } + if (isStruct) { + prop = PyCField_FromDesc(desc, i, + &field_size, bitsize, &bitofs, + &size, &offset, &align, + pack, big_endian); + } else /* union */ { + size = 0; + offset = 0; + align = 0; + prop = PyCField_FromDesc(desc, i, + &field_size, bitsize, &bitofs, + &size, &offset, &align, + pack, big_endian); + union_size = max(size, union_size); + } + total_align = max(align, total_align); + + if (!prop) { + Py_DECREF(pair); + return -1; + } + if (-1 == PyObject_SetAttr(type, name, prop)) { + Py_DECREF(prop); + Py_DECREF(pair); + return -1; + } + Py_DECREF(pair); + Py_DECREF(prop); + } #undef realdict - if (isStruct && !isPacked) { - char *ptr = stgdict->format; - stgdict->format = _ctypes_alloc_format_string(stgdict->format, "}"); - PyMem_Free(ptr); - if (stgdict->format == NULL) - return -1; - } - - if (!isStruct) - size = union_size; - - /* Adjust the size according to the alignment requirements */ - size = ((size + total_align - 1) / total_align) * total_align; - - stgdict->ffi_type_pointer.alignment = Py_SAFE_DOWNCAST(total_align, - Py_ssize_t, - unsigned short); - stgdict->ffi_type_pointer.size = size; - - stgdict->size = size; - stgdict->align = total_align; - stgdict->length = len; /* ADD ffi_ofs? */ - - /* We did check that this flag was NOT set above, it must not - have been set until now. */ - if (stgdict->flags & DICTFLAG_FINAL) { - PyErr_SetString(PyExc_AttributeError, - "Structure or union cannot contain itself"); - return -1; - } - stgdict->flags |= DICTFLAG_FINAL; + if (isStruct && !isPacked) { + char *ptr = stgdict->format; + stgdict->format = _ctypes_alloc_format_string(stgdict->format, "}"); + PyMem_Free(ptr); + if (stgdict->format == NULL) + return -1; + } + + if (!isStruct) + size = union_size; + + /* Adjust the size according to the alignment requirements */ + size = ((size + total_align - 1) / total_align) * total_align; + + stgdict->ffi_type_pointer.alignment = Py_SAFE_DOWNCAST(total_align, + Py_ssize_t, + unsigned short); + stgdict->ffi_type_pointer.size = size; + + stgdict->size = size; + stgdict->align = total_align; + stgdict->length = len; /* ADD ffi_ofs? */ + + /* We did check that this flag was NOT set above, it must not + have been set until now. */ + if (stgdict->flags & DICTFLAG_FINAL) { + PyErr_SetString(PyExc_AttributeError, + "Structure or union cannot contain itself"); + return -1; + } + stgdict->flags |= DICTFLAG_FINAL; - return MakeAnonFields(type); + return MakeAnonFields(type); } Modified: python/branches/release31-maint/Modules/_curses_panel.c ============================================================================== --- python/branches/release31-maint/Modules/_curses_panel.c (original) +++ python/branches/release31-maint/Modules/_curses_panel.c Sun May 9 18:14:21 2010 @@ -22,7 +22,7 @@ /* Utility Functions */ /* - * Check the return code from a curses function and return None + * Check the return code from a curses function and return None * or raise an exception as appropriate. */ @@ -30,15 +30,15 @@ PyCursesCheckERR(int code, char *fname) { if (code != ERR) { - Py_INCREF(Py_None); - return Py_None; + Py_INCREF(Py_None); + return Py_None; } else { - if (fname == NULL) { - PyErr_SetString(PyCursesError, catchall_ERR); - } else { - PyErr_Format(PyCursesError, "%s() returned ERR", fname); - } - return NULL; + if (fname == NULL) { + PyErr_SetString(PyCursesError, catchall_ERR); + } else { + PyErr_Format(PyCursesError, "%s() returned ERR", fname); + } + return NULL; } } @@ -51,12 +51,12 @@ typedef struct { PyObject_HEAD PANEL *pan; - PyCursesWindowObject *wo; /* for reference counts */ + PyCursesWindowObject *wo; /* for reference counts */ } PyCursesPanelObject; PyTypeObject PyCursesPanel_Type; -#define PyCursesPanel_Check(v) (Py_TYPE(v) == &PyCursesPanel_Type) +#define PyCursesPanel_Check(v) (Py_TYPE(v) == &PyCursesPanel_Type) /* Some helper functions. The problem is that there's always a window associated with a panel. To ensure that Python's GC doesn't pull @@ -88,10 +88,10 @@ insert_lop(PyCursesPanelObject *po) { list_of_panels *new; - + if ((new = (list_of_panels *)malloc(sizeof(list_of_panels))) == NULL) { - PyErr_NoMemory(); - return -1; + PyErr_NoMemory(); + return -1; } new->po = po; new->next = lop; @@ -107,17 +107,17 @@ temp = lop; if (temp->po == po) { - lop = temp->next; - free(temp); - return; + lop = temp->next; + free(temp); + return; } while (temp->next == NULL || temp->next->po != po) { - if (temp->next == NULL) { - PyErr_SetString(PyExc_RuntimeError, - "remove_lop: can't find Panel Object"); - return; - } - temp = temp->next; + if (temp->next == NULL) { + PyErr_SetString(PyExc_RuntimeError, + "remove_lop: can't find Panel Object"); + return; + } + temp = temp->next; } n = temp->next->next; free(temp->next); @@ -131,7 +131,7 @@ { list_of_panels *temp; for (temp = lop; temp->po->pan != pan; temp = temp->next) - if (temp->next == NULL) return NULL; /* not found!? */ + if (temp->next == NULL) return NULL; /* not found!? */ return temp->po; } @@ -179,9 +179,9 @@ if (po == NULL) return NULL; po->pan = pan; if (insert_lop(po) < 0) { - po->wo = NULL; - Py_DECREF(po); - return NULL; + po->wo = NULL; + Py_DECREF(po); + return NULL; } po->wo = wo; Py_INCREF(wo); @@ -193,8 +193,8 @@ { (void)del_panel(po->pan); if (po->wo != NULL) { - Py_DECREF(po->wo); - remove_lop(po); + Py_DECREF(po->wo); + remove_lop(po); } PyObject_DEL(po); } @@ -206,19 +206,19 @@ { PANEL *pan; PyCursesPanelObject *po; - + pan = panel_above(self->pan); - if (pan == NULL) { /* valid output, it means the calling panel - is on top of the stack */ - Py_INCREF(Py_None); - return Py_None; + if (pan == NULL) { /* valid output, it means the calling panel + is on top of the stack */ + Py_INCREF(Py_None); + return Py_None; } po = find_po(pan); if (po == NULL) { - PyErr_SetString(PyExc_RuntimeError, - "panel_above: can't find Panel Object"); - return NULL; + PyErr_SetString(PyExc_RuntimeError, + "panel_above: can't find Panel Object"); + return NULL; } Py_INCREF(po); return (PyObject *)po; @@ -231,19 +231,19 @@ { PANEL *pan; PyCursesPanelObject *po; - + pan = panel_below(self->pan); - - if (pan == NULL) { /* valid output, it means the calling panel - is on the bottom of the stack */ - Py_INCREF(Py_None); - return Py_None; + + if (pan == NULL) { /* valid output, it means the calling panel + is on the bottom of the stack */ + Py_INCREF(Py_None); + return Py_None; } po = find_po(pan); if (po == NULL) { - PyErr_SetString(PyExc_RuntimeError, - "panel_below: can't find Panel Object"); - return NULL; + PyErr_SetString(PyExc_RuntimeError, + "panel_below: can't find Panel Object"); + return NULL; } Py_INCREF(po); return (PyObject *)po; @@ -262,26 +262,26 @@ PyCursesPanelObject *po; PyCursesWindowObject *temp; int rtn; - + if (PyTuple_Size(args) != 1) { - PyErr_SetString(PyExc_TypeError, "replace requires one argument"); - return NULL; + PyErr_SetString(PyExc_TypeError, "replace requires one argument"); + return NULL; } if (!PyArg_ParseTuple(args, "O!;window object", - &PyCursesWindow_Type, &temp)) - return NULL; + &PyCursesWindow_Type, &temp)) + return NULL; po = find_po(self->pan); if (po == NULL) { - PyErr_SetString(PyExc_RuntimeError, - "replace_panel: can't find Panel Object"); - return NULL; + PyErr_SetString(PyExc_RuntimeError, + "replace_panel: can't find Panel Object"); + return NULL; } rtn = replace_panel(self->pan, temp->win); if (rtn == ERR) { - PyErr_SetString(PyCursesError, "replace_panel() returned ERR"); - return NULL; + PyErr_SetString(PyCursesError, "replace_panel() returned ERR"); + return NULL; } Py_DECREF(po->wo); po->wo = temp; @@ -302,11 +302,11 @@ PyCursesPanel_userptr(PyCursesPanelObject *self) { PyObject *obj; - PyCursesInitialised; + PyCursesInitialised; obj = (PyObject *) panel_userptr(self->pan); if (obj == NULL) { - PyErr_SetString(PyCursesError, "no userptr set"); - return NULL; + PyErr_SetString(PyCursesError, "no userptr set"); + return NULL; } Py_INCREF(obj); @@ -329,40 +329,40 @@ {"top", (PyCFunction)PyCursesPanel_top_panel, METH_NOARGS}, {"userptr", (PyCFunction)PyCursesPanel_userptr, METH_NOARGS}, {"window", (PyCFunction)PyCursesPanel_window, METH_NOARGS}, - {NULL, NULL} /* sentinel */ + {NULL, NULL} /* sentinel */ }; /* -------------------------------------------------------*/ PyTypeObject PyCursesPanel_Type = { PyVarObject_HEAD_INIT(NULL, 0) - "_curses_panel.curses panel", /*tp_name*/ - sizeof(PyCursesPanelObject), /*tp_basicsize*/ - 0, /*tp_itemsize*/ + "_curses_panel.curses panel", /*tp_name*/ + sizeof(PyCursesPanelObject), /*tp_basicsize*/ + 0, /*tp_itemsize*/ /* methods */ (destructor)PyCursesPanel_Dealloc, /*tp_dealloc*/ - 0, /*tp_print*/ - 0, /*tp_getattr*/ - 0, /*tp_setattr*/ - 0, /*tp_reserved*/ - 0, /*tp_repr*/ - 0, /*tp_as_number*/ - 0, /*tp_as_sequence*/ - 0, /*tp_as_mapping*/ - 0, /*tp_hash*/ - 0, /*tp_call*/ - 0, /*tp_str*/ - 0, /*tp_getattro*/ - 0, /*tp_setattro*/ - 0, /*tp_as_buffer*/ + 0, /*tp_print*/ + 0, /*tp_getattr*/ + 0, /*tp_setattr*/ + 0, /*tp_reserved*/ + 0, /*tp_repr*/ + 0, /*tp_as_number*/ + 0, /*tp_as_sequence*/ + 0, /*tp_as_mapping*/ + 0, /*tp_hash*/ + 0, /*tp_call*/ + 0, /*tp_str*/ + 0, /*tp_getattro*/ + 0, /*tp_setattro*/ + 0, /*tp_as_buffer*/ Py_TPFLAGS_DEFAULT, /*tp_flags*/ - 0, /*tp_doc*/ - 0, /*tp_traverse*/ - 0, /*tp_clear*/ - 0, /*tp_richcompare*/ - 0, /*tp_weaklistoffset*/ - 0, /*tp_iter*/ - 0, /*tp_iternext*/ + 0, /*tp_doc*/ + 0, /*tp_traverse*/ + 0, /*tp_clear*/ + 0, /*tp_richcompare*/ + 0, /*tp_weaklistoffset*/ + 0, /*tp_iter*/ + 0, /*tp_iternext*/ PyCursesPanel_Methods, /*tp_methods*/ }; @@ -380,16 +380,16 @@ pan = panel_above(NULL); - if (pan == NULL) { /* valid output, it means - there's no panel at all */ - Py_INCREF(Py_None); - return Py_None; + if (pan == NULL) { /* valid output, it means + there's no panel at all */ + Py_INCREF(Py_None); + return Py_None; } po = find_po(pan); if (po == NULL) { - PyErr_SetString(PyExc_RuntimeError, - "panel_above: can't find Panel Object"); - return NULL; + PyErr_SetString(PyExc_RuntimeError, + "panel_above: can't find Panel Object"); + return NULL; } Py_INCREF(po); return (PyObject *)po; @@ -405,8 +405,8 @@ return NULL; pan = new_panel(win->win); if (pan == NULL) { - PyErr_SetString(PyCursesError, catchall_NULL); - return NULL; + PyErr_SetString(PyCursesError, catchall_NULL); + return NULL; } return (PyObject *)PyCursesPanel_New(pan, win); } @@ -421,28 +421,28 @@ { PANEL *pan; PyCursesPanelObject *po; - + PyCursesInitialised; pan = panel_below(NULL); - if (pan == NULL) { /* valid output, it means - there's no panel at all */ - Py_INCREF(Py_None); - return Py_None; + if (pan == NULL) { /* valid output, it means + there's no panel at all */ + Py_INCREF(Py_None); + return Py_None; } po = find_po(pan); if (po == NULL) { - PyErr_SetString(PyExc_RuntimeError, - "panel_below: can't find Panel Object"); - return NULL; + PyErr_SetString(PyExc_RuntimeError, + "panel_below: can't find Panel Object"); + return NULL; } Py_INCREF(po); return (PyObject *)po; } static PyObject *PyCurses_update_panels(PyObject *self) -{ +{ PyCursesInitialised; update_panels(); Py_INCREF(Py_None); @@ -457,22 +457,22 @@ {"new_panel", (PyCFunction)PyCurses_new_panel, METH_VARARGS}, {"top_panel", (PyCFunction)PyCurses_top_panel, METH_NOARGS}, {"update_panels", (PyCFunction)PyCurses_update_panels, METH_NOARGS}, - {NULL, NULL} /* sentinel */ + {NULL, NULL} /* sentinel */ }; /* Initialization function for the module */ static struct PyModuleDef _curses_panelmodule = { - PyModuleDef_HEAD_INIT, - "_curses_panel", - NULL, - -1, - PyCurses_methods, - NULL, - NULL, - NULL, - NULL + PyModuleDef_HEAD_INIT, + "_curses_panel", + NULL, + -1, + PyCurses_methods, + NULL, + NULL, + NULL, + NULL }; PyMODINIT_FUNC @@ -489,7 +489,7 @@ /* Create the module and add the functions */ m = PyModule_Create(&_curses_panelmodule); if (m == NULL) - return NULL; + return NULL; d = PyModule_GetDict(m); /* For exception _curses_panel.error */ Modified: python/branches/release31-maint/Modules/_dbmmodule.c ============================================================================== --- python/branches/release31-maint/Modules/_dbmmodule.c (original) +++ python/branches/release31-maint/Modules/_dbmmodule.c Sun May 9 18:14:21 2010 @@ -33,9 +33,9 @@ #endif typedef struct { - PyObject_HEAD - int di_size; /* -1 means recompute */ - DBM *di_dbm; + PyObject_HEAD + int di_size; /* -1 means recompute */ + DBM *di_dbm; } dbmobject; static PyTypeObject Dbmtype; @@ -50,18 +50,18 @@ static PyObject * newdbmobject(char *file, int flags, int mode) { - dbmobject *dp; + dbmobject *dp; - dp = PyObject_New(dbmobject, &Dbmtype); - if (dp == NULL) - return NULL; - dp->di_size = -1; - if ( (dp->di_dbm = dbm_open(file, flags, mode)) == 0 ) { - PyErr_SetFromErrno(DbmError); - Py_DECREF(dp); - return NULL; - } - return (PyObject *)dp; + dp = PyObject_New(dbmobject, &Dbmtype); + if (dp == NULL) + return NULL; + dp->di_size = -1; + if ( (dp->di_dbm = dbm_open(file, flags, mode)) == 0 ) { + PyErr_SetFromErrno(DbmError); + Py_DECREF(dp); + return NULL; + } + return (PyObject *)dp; } /* Methods */ @@ -69,294 +69,294 @@ static void dbm_dealloc(register dbmobject *dp) { - if ( dp->di_dbm ) - dbm_close(dp->di_dbm); - PyObject_Del(dp); + if ( dp->di_dbm ) + dbm_close(dp->di_dbm); + PyObject_Del(dp); } static Py_ssize_t dbm_length(dbmobject *dp) { - if (dp->di_dbm == NULL) { - PyErr_SetString(DbmError, "DBM object has already been closed"); - return -1; - } - if ( dp->di_size < 0 ) { - datum key; - int size; - - size = 0; - for ( key=dbm_firstkey(dp->di_dbm); key.dptr; - key = dbm_nextkey(dp->di_dbm)) - size++; - dp->di_size = size; - } - return dp->di_size; + if (dp->di_dbm == NULL) { + PyErr_SetString(DbmError, "DBM object has already been closed"); + return -1; + } + if ( dp->di_size < 0 ) { + datum key; + int size; + + size = 0; + for ( key=dbm_firstkey(dp->di_dbm); key.dptr; + key = dbm_nextkey(dp->di_dbm)) + size++; + dp->di_size = size; + } + return dp->di_size; } static PyObject * dbm_subscript(dbmobject *dp, register PyObject *key) { - datum drec, krec; - Py_ssize_t tmp_size; - - if (!PyArg_Parse(key, "s#", &krec.dptr, &tmp_size) ) - return NULL; - - krec.dsize = tmp_size; - check_dbmobject_open(dp); - drec = dbm_fetch(dp->di_dbm, krec); - if ( drec.dptr == 0 ) { - PyErr_SetObject(PyExc_KeyError, key); - return NULL; - } - if ( dbm_error(dp->di_dbm) ) { - dbm_clearerr(dp->di_dbm); - PyErr_SetString(DbmError, ""); - return NULL; - } - return PyBytes_FromStringAndSize(drec.dptr, drec.dsize); + datum drec, krec; + Py_ssize_t tmp_size; + + if (!PyArg_Parse(key, "s#", &krec.dptr, &tmp_size) ) + return NULL; + + krec.dsize = tmp_size; + check_dbmobject_open(dp); + drec = dbm_fetch(dp->di_dbm, krec); + if ( drec.dptr == 0 ) { + PyErr_SetObject(PyExc_KeyError, key); + return NULL; + } + if ( dbm_error(dp->di_dbm) ) { + dbm_clearerr(dp->di_dbm); + PyErr_SetString(DbmError, ""); + return NULL; + } + return PyBytes_FromStringAndSize(drec.dptr, drec.dsize); } static int dbm_ass_sub(dbmobject *dp, PyObject *v, PyObject *w) { - datum krec, drec; - Py_ssize_t tmp_size; - - if ( !PyArg_Parse(v, "s#", &krec.dptr, &tmp_size) ) { - PyErr_SetString(PyExc_TypeError, - "dbm mappings have bytes or string keys only"); - return -1; - } - krec.dsize = tmp_size; - if (dp->di_dbm == NULL) { - PyErr_SetString(DbmError, "DBM object has already been closed"); - return -1; + datum krec, drec; + Py_ssize_t tmp_size; + + if ( !PyArg_Parse(v, "s#", &krec.dptr, &tmp_size) ) { + PyErr_SetString(PyExc_TypeError, + "dbm mappings have bytes or string keys only"); + return -1; + } + krec.dsize = tmp_size; + if (dp->di_dbm == NULL) { + PyErr_SetString(DbmError, "DBM object has already been closed"); + return -1; + } + dp->di_size = -1; + if (w == NULL) { + if ( dbm_delete(dp->di_dbm, krec) < 0 ) { + dbm_clearerr(dp->di_dbm); + PyErr_SetObject(PyExc_KeyError, v); + return -1; + } + } else { + if ( !PyArg_Parse(w, "s#", &drec.dptr, &tmp_size) ) { + PyErr_SetString(PyExc_TypeError, + "dbm mappings have byte or string elements only"); + return -1; } - dp->di_size = -1; - if (w == NULL) { - if ( dbm_delete(dp->di_dbm, krec) < 0 ) { - dbm_clearerr(dp->di_dbm); - PyErr_SetObject(PyExc_KeyError, v); - return -1; - } - } else { - if ( !PyArg_Parse(w, "s#", &drec.dptr, &tmp_size) ) { - PyErr_SetString(PyExc_TypeError, - "dbm mappings have byte or string elements only"); - return -1; - } - drec.dsize = tmp_size; - if ( dbm_store(dp->di_dbm, krec, drec, DBM_REPLACE) < 0 ) { - dbm_clearerr(dp->di_dbm); - PyErr_SetString(DbmError, - "cannot add item to database"); - return -1; - } - } - if ( dbm_error(dp->di_dbm) ) { - dbm_clearerr(dp->di_dbm); - PyErr_SetString(DbmError, ""); - return -1; - } - return 0; + drec.dsize = tmp_size; + if ( dbm_store(dp->di_dbm, krec, drec, DBM_REPLACE) < 0 ) { + dbm_clearerr(dp->di_dbm); + PyErr_SetString(DbmError, + "cannot add item to database"); + return -1; + } + } + if ( dbm_error(dp->di_dbm) ) { + dbm_clearerr(dp->di_dbm); + PyErr_SetString(DbmError, ""); + return -1; + } + return 0; } static PyMappingMethods dbm_as_mapping = { - (lenfunc)dbm_length, /*mp_length*/ - (binaryfunc)dbm_subscript, /*mp_subscript*/ - (objobjargproc)dbm_ass_sub, /*mp_ass_subscript*/ + (lenfunc)dbm_length, /*mp_length*/ + (binaryfunc)dbm_subscript, /*mp_subscript*/ + (objobjargproc)dbm_ass_sub, /*mp_ass_subscript*/ }; static PyObject * dbm__close(register dbmobject *dp, PyObject *unused) { - if (dp->di_dbm) - dbm_close(dp->di_dbm); - dp->di_dbm = NULL; - Py_INCREF(Py_None); - return Py_None; + if (dp->di_dbm) + dbm_close(dp->di_dbm); + dp->di_dbm = NULL; + Py_INCREF(Py_None); + return Py_None; } static PyObject * dbm_keys(register dbmobject *dp, PyObject *unused) { - register PyObject *v, *item; - datum key; - int err; - - check_dbmobject_open(dp); - v = PyList_New(0); - if (v == NULL) - return NULL; - for (key = dbm_firstkey(dp->di_dbm); key.dptr; - key = dbm_nextkey(dp->di_dbm)) { - item = PyBytes_FromStringAndSize(key.dptr, key.dsize); - if (item == NULL) { - Py_DECREF(v); - return NULL; - } - err = PyList_Append(v, item); - Py_DECREF(item); - if (err != 0) { - Py_DECREF(v); - return NULL; - } - } - return v; + register PyObject *v, *item; + datum key; + int err; + + check_dbmobject_open(dp); + v = PyList_New(0); + if (v == NULL) + return NULL; + for (key = dbm_firstkey(dp->di_dbm); key.dptr; + key = dbm_nextkey(dp->di_dbm)) { + item = PyBytes_FromStringAndSize(key.dptr, key.dsize); + if (item == NULL) { + Py_DECREF(v); + return NULL; + } + err = PyList_Append(v, item); + Py_DECREF(item); + if (err != 0) { + Py_DECREF(v); + return NULL; + } + } + return v; } static int dbm_contains(PyObject *self, PyObject *arg) { - dbmobject *dp = (dbmobject *)self; - datum key, val; + dbmobject *dp = (dbmobject *)self; + datum key, val; - if ((dp)->di_dbm == NULL) { - PyErr_SetString(DbmError, - "DBM object has already been closed"); - return -1; - } - if (PyUnicode_Check(arg)) { - arg = _PyUnicode_AsDefaultEncodedString(arg, NULL); - if (arg == NULL) - return -1; - } - if (!PyBytes_Check(arg)) { - PyErr_Format(PyExc_TypeError, - "dbm key must be string, not %.100s", - arg->ob_type->tp_name); - return -1; - } - key.dptr = PyBytes_AS_STRING(arg); - key.dsize = PyBytes_GET_SIZE(arg); - val = dbm_fetch(dp->di_dbm, key); - return val.dptr != NULL; + if ((dp)->di_dbm == NULL) { + PyErr_SetString(DbmError, + "DBM object has already been closed"); + return -1; + } + if (PyUnicode_Check(arg)) { + arg = _PyUnicode_AsDefaultEncodedString(arg, NULL); + if (arg == NULL) + return -1; + } + if (!PyBytes_Check(arg)) { + PyErr_Format(PyExc_TypeError, + "dbm key must be string, not %.100s", + arg->ob_type->tp_name); + return -1; + } + key.dptr = PyBytes_AS_STRING(arg); + key.dsize = PyBytes_GET_SIZE(arg); + val = dbm_fetch(dp->di_dbm, key); + return val.dptr != NULL; } static PySequenceMethods dbm_as_sequence = { - 0, /* sq_length */ - 0, /* sq_concat */ - 0, /* sq_repeat */ - 0, /* sq_item */ - 0, /* sq_slice */ - 0, /* sq_ass_item */ - 0, /* sq_ass_slice */ - dbm_contains, /* sq_contains */ - 0, /* sq_inplace_concat */ - 0, /* sq_inplace_repeat */ + 0, /* sq_length */ + 0, /* sq_concat */ + 0, /* sq_repeat */ + 0, /* sq_item */ + 0, /* sq_slice */ + 0, /* sq_ass_item */ + 0, /* sq_ass_slice */ + dbm_contains, /* sq_contains */ + 0, /* sq_inplace_concat */ + 0, /* sq_inplace_repeat */ }; static PyObject * dbm_get(register dbmobject *dp, PyObject *args) { - datum key, val; - PyObject *defvalue = Py_None; - char *tmp_ptr; - Py_ssize_t tmp_size; - - if (!PyArg_ParseTuple(args, "s#|O:get", - &tmp_ptr, &tmp_size, &defvalue)) - return NULL; - key.dptr = tmp_ptr; - key.dsize = tmp_size; - check_dbmobject_open(dp); - val = dbm_fetch(dp->di_dbm, key); - if (val.dptr != NULL) - return PyBytes_FromStringAndSize(val.dptr, val.dsize); - else { - Py_INCREF(defvalue); - return defvalue; - } + datum key, val; + PyObject *defvalue = Py_None; + char *tmp_ptr; + Py_ssize_t tmp_size; + + if (!PyArg_ParseTuple(args, "s#|O:get", + &tmp_ptr, &tmp_size, &defvalue)) + return NULL; + key.dptr = tmp_ptr; + key.dsize = tmp_size; + check_dbmobject_open(dp); + val = dbm_fetch(dp->di_dbm, key); + if (val.dptr != NULL) + return PyBytes_FromStringAndSize(val.dptr, val.dsize); + else { + Py_INCREF(defvalue); + return defvalue; + } } static PyObject * dbm_setdefault(register dbmobject *dp, PyObject *args) { - datum key, val; - PyObject *defvalue = NULL; - char *tmp_ptr; - Py_ssize_t tmp_size; - - if (!PyArg_ParseTuple(args, "s#|O:setdefault", - &tmp_ptr, &tmp_size, &defvalue)) - return NULL; - key.dptr = tmp_ptr; - key.dsize = tmp_size; - check_dbmobject_open(dp); - val = dbm_fetch(dp->di_dbm, key); - if (val.dptr != NULL) - return PyBytes_FromStringAndSize(val.dptr, val.dsize); - if (defvalue == NULL) { - defvalue = PyBytes_FromStringAndSize(NULL, 0); - if (defvalue == NULL) - return NULL; - val.dptr = NULL; - val.dsize = 0; - } - else { - if ( !PyArg_Parse(defvalue, "s#", &val.dptr, &tmp_size) ) { - PyErr_SetString(PyExc_TypeError, - "dbm mappings have byte string elements only"); - return NULL; - } - val.dsize = tmp_size; - Py_INCREF(defvalue); - } - if (dbm_store(dp->di_dbm, key, val, DBM_INSERT) < 0) { - dbm_clearerr(dp->di_dbm); - PyErr_SetString(DbmError, "cannot add item to database"); - Py_DECREF(defvalue); - return NULL; - } - return defvalue; + datum key, val; + PyObject *defvalue = NULL; + char *tmp_ptr; + Py_ssize_t tmp_size; + + if (!PyArg_ParseTuple(args, "s#|O:setdefault", + &tmp_ptr, &tmp_size, &defvalue)) + return NULL; + key.dptr = tmp_ptr; + key.dsize = tmp_size; + check_dbmobject_open(dp); + val = dbm_fetch(dp->di_dbm, key); + if (val.dptr != NULL) + return PyBytes_FromStringAndSize(val.dptr, val.dsize); + if (defvalue == NULL) { + defvalue = PyBytes_FromStringAndSize(NULL, 0); + if (defvalue == NULL) + return NULL; + val.dptr = NULL; + val.dsize = 0; + } + else { + if ( !PyArg_Parse(defvalue, "s#", &val.dptr, &tmp_size) ) { + PyErr_SetString(PyExc_TypeError, + "dbm mappings have byte string elements only"); + return NULL; + } + val.dsize = tmp_size; + Py_INCREF(defvalue); + } + if (dbm_store(dp->di_dbm, key, val, DBM_INSERT) < 0) { + dbm_clearerr(dp->di_dbm); + PyErr_SetString(DbmError, "cannot add item to database"); + Py_DECREF(defvalue); + return NULL; + } + return defvalue; } static PyMethodDef dbm_methods[] = { - {"close", (PyCFunction)dbm__close, METH_NOARGS, - "close()\nClose the database."}, - {"keys", (PyCFunction)dbm_keys, METH_NOARGS, - "keys() -> list\nReturn a list of all keys in the database."}, - {"get", (PyCFunction)dbm_get, METH_VARARGS, - "get(key[, default]) -> value\n" - "Return the value for key if present, otherwise default."}, - {"setdefault", (PyCFunction)dbm_setdefault, METH_VARARGS, - "setdefault(key[, default]) -> value\n" - "Return the value for key if present, otherwise default. If key\n" - "is not in the database, it is inserted with default as the value."}, - {NULL, NULL} /* sentinel */ + {"close", (PyCFunction)dbm__close, METH_NOARGS, + "close()\nClose the database."}, + {"keys", (PyCFunction)dbm_keys, METH_NOARGS, + "keys() -> list\nReturn a list of all keys in the database."}, + {"get", (PyCFunction)dbm_get, METH_VARARGS, + "get(key[, default]) -> value\n" + "Return the value for key if present, otherwise default."}, + {"setdefault", (PyCFunction)dbm_setdefault, METH_VARARGS, + "setdefault(key[, default]) -> value\n" + "Return the value for key if present, otherwise default. If key\n" + "is not in the database, it is inserted with default as the value."}, + {NULL, NULL} /* sentinel */ }; static PyTypeObject Dbmtype = { - PyVarObject_HEAD_INIT(NULL, 0) - "_dbm.dbm", - sizeof(dbmobject), - 0, - (destructor)dbm_dealloc, /*tp_dealloc*/ - 0, /*tp_print*/ - 0, /*tp_getattr*/ - 0, /*tp_setattr*/ - 0, /*tp_reserved*/ - 0, /*tp_repr*/ - 0, /*tp_as_number*/ - &dbm_as_sequence, /*tp_as_sequence*/ - &dbm_as_mapping, /*tp_as_mapping*/ - 0, /*tp_hash*/ - 0, /*tp_call*/ - 0, /*tp_str*/ - 0, /*tp_getattro*/ - 0, /*tp_setattro*/ - 0, /*tp_as_buffer*/ - Py_TPFLAGS_DEFAULT, /*tp_flags*/ - 0, /*tp_doc*/ - 0, /*tp_traverse*/ - 0, /*tp_clear*/ - 0, /*tp_richcompare*/ - 0, /*tp_weaklistoffset*/ - 0, /*tp_iter*/ - 0, /*tp_iternext*/ - dbm_methods, /*tp_methods*/ + PyVarObject_HEAD_INIT(NULL, 0) + "_dbm.dbm", + sizeof(dbmobject), + 0, + (destructor)dbm_dealloc, /*tp_dealloc*/ + 0, /*tp_print*/ + 0, /*tp_getattr*/ + 0, /*tp_setattr*/ + 0, /*tp_reserved*/ + 0, /*tp_repr*/ + 0, /*tp_as_number*/ + &dbm_as_sequence, /*tp_as_sequence*/ + &dbm_as_mapping, /*tp_as_mapping*/ + 0, /*tp_hash*/ + 0, /*tp_call*/ + 0, /*tp_str*/ + 0, /*tp_getattro*/ + 0, /*tp_setattro*/ + 0, /*tp_as_buffer*/ + Py_TPFLAGS_DEFAULT, /*tp_flags*/ + 0, /*tp_doc*/ + 0, /*tp_traverse*/ + 0, /*tp_clear*/ + 0, /*tp_richcompare*/ + 0, /*tp_weaklistoffset*/ + 0, /*tp_iter*/ + 0, /*tp_iternext*/ + dbm_methods, /*tp_methods*/ }; /* ----------------------------------------------------------------- */ @@ -364,74 +364,74 @@ static PyObject * dbmopen(PyObject *self, PyObject *args) { - char *name; - char *flags = "r"; - int iflags; - int mode = 0666; - - if ( !PyArg_ParseTuple(args, "s|si:open", &name, &flags, &mode) ) - return NULL; - if ( strcmp(flags, "r") == 0 ) - iflags = O_RDONLY; - else if ( strcmp(flags, "w") == 0 ) - iflags = O_RDWR; - else if ( strcmp(flags, "rw") == 0 ) /* B/W compat */ - iflags = O_RDWR|O_CREAT; - else if ( strcmp(flags, "c") == 0 ) - iflags = O_RDWR|O_CREAT; - else if ( strcmp(flags, "n") == 0 ) - iflags = O_RDWR|O_CREAT|O_TRUNC; - else { - PyErr_SetString(DbmError, - "arg 2 to open should be 'r', 'w', 'c', or 'n'"); - return NULL; - } - return newdbmobject(name, iflags, mode); + char *name; + char *flags = "r"; + int iflags; + int mode = 0666; + + if ( !PyArg_ParseTuple(args, "s|si:open", &name, &flags, &mode) ) + return NULL; + if ( strcmp(flags, "r") == 0 ) + iflags = O_RDONLY; + else if ( strcmp(flags, "w") == 0 ) + iflags = O_RDWR; + else if ( strcmp(flags, "rw") == 0 ) /* B/W compat */ + iflags = O_RDWR|O_CREAT; + else if ( strcmp(flags, "c") == 0 ) + iflags = O_RDWR|O_CREAT; + else if ( strcmp(flags, "n") == 0 ) + iflags = O_RDWR|O_CREAT|O_TRUNC; + else { + PyErr_SetString(DbmError, + "arg 2 to open should be 'r', 'w', 'c', or 'n'"); + return NULL; + } + return newdbmobject(name, iflags, mode); } static PyMethodDef dbmmodule_methods[] = { - { "open", (PyCFunction)dbmopen, METH_VARARGS, - "open(path[, flag[, mode]]) -> mapping\n" - "Return a database object."}, - { 0, 0 }, + { "open", (PyCFunction)dbmopen, METH_VARARGS, + "open(path[, flag[, mode]]) -> mapping\n" + "Return a database object."}, + { 0, 0 }, }; static struct PyModuleDef _dbmmodule = { - PyModuleDef_HEAD_INIT, - "_dbm", - NULL, - -1, - dbmmodule_methods, - NULL, - NULL, - NULL, - NULL + PyModuleDef_HEAD_INIT, + "_dbm", + NULL, + -1, + dbmmodule_methods, + NULL, + NULL, + NULL, + NULL }; PyMODINIT_FUNC PyInit__dbm(void) { - PyObject *m, *d, *s; + PyObject *m, *d, *s; - if (PyType_Ready(&Dbmtype) < 0) - return NULL; - m = PyModule_Create(&_dbmmodule); - if (m == NULL) - return NULL; - d = PyModule_GetDict(m); - if (DbmError == NULL) - DbmError = PyErr_NewException("_dbm.error", - PyExc_IOError, NULL); - s = PyUnicode_FromString(which_dbm); - if (s != NULL) { - PyDict_SetItemString(d, "library", s); - Py_DECREF(s); - } - if (DbmError != NULL) - PyDict_SetItemString(d, "error", DbmError); - if (PyErr_Occurred()) { - Py_DECREF(m); - m = NULL; - } - return m; + if (PyType_Ready(&Dbmtype) < 0) + return NULL; + m = PyModule_Create(&_dbmmodule); + if (m == NULL) + return NULL; + d = PyModule_GetDict(m); + if (DbmError == NULL) + DbmError = PyErr_NewException("_dbm.error", + PyExc_IOError, NULL); + s = PyUnicode_FromString(which_dbm); + if (s != NULL) { + PyDict_SetItemString(d, "library", s); + Py_DECREF(s); + } + if (DbmError != NULL) + PyDict_SetItemString(d, "error", DbmError); + if (PyErr_Occurred()) { + Py_DECREF(m); + m = NULL; + } + return m; } Modified: python/branches/release31-maint/Modules/_functoolsmodule.c ============================================================================== --- python/branches/release31-maint/Modules/_functoolsmodule.c (original) +++ python/branches/release31-maint/Modules/_functoolsmodule.c Sun May 9 18:14:21 2010 @@ -2,7 +2,7 @@ #include "Python.h" #include "structmember.h" -/* _functools module written and maintained +/* _functools module written and maintained by Hye-Shik Chang with adaptations by Raymond Hettinger Copyright (c) 2004, 2005, 2006 Python Software Foundation. @@ -12,12 +12,12 @@ /* partial object **********************************************************/ typedef struct { - PyObject_HEAD - PyObject *fn; - PyObject *args; - PyObject *kw; - PyObject *dict; - PyObject *weakreflist; /* List of weak references */ + PyObject_HEAD + PyObject *fn; + PyObject *args; + PyObject *kw; + PyObject *dict; + PyObject *weakreflist; /* List of weak references */ } partialobject; static PyTypeObject partial_type; @@ -25,175 +25,175 @@ static PyObject * partial_new(PyTypeObject *type, PyObject *args, PyObject *kw) { - PyObject *func; - partialobject *pto; + PyObject *func; + partialobject *pto; - if (PyTuple_GET_SIZE(args) < 1) { - PyErr_SetString(PyExc_TypeError, - "type 'partial' takes at least one argument"); - return NULL; - } - - func = PyTuple_GET_ITEM(args, 0); - if (!PyCallable_Check(func)) { - PyErr_SetString(PyExc_TypeError, - "the first argument must be callable"); - return NULL; - } - - /* create partialobject structure */ - pto = (partialobject *)type->tp_alloc(type, 0); - if (pto == NULL) - return NULL; - - pto->fn = func; - Py_INCREF(func); - pto->args = PyTuple_GetSlice(args, 1, PY_SSIZE_T_MAX); - if (pto->args == NULL) { - pto->kw = NULL; - Py_DECREF(pto); - return NULL; - } - if (kw != NULL) { - pto->kw = PyDict_Copy(kw); - if (pto->kw == NULL) { - Py_DECREF(pto); - return NULL; - } - } else { - pto->kw = Py_None; - Py_INCREF(Py_None); - } + if (PyTuple_GET_SIZE(args) < 1) { + PyErr_SetString(PyExc_TypeError, + "type 'partial' takes at least one argument"); + return NULL; + } + + func = PyTuple_GET_ITEM(args, 0); + if (!PyCallable_Check(func)) { + PyErr_SetString(PyExc_TypeError, + "the first argument must be callable"); + return NULL; + } + + /* create partialobject structure */ + pto = (partialobject *)type->tp_alloc(type, 0); + if (pto == NULL) + return NULL; + + pto->fn = func; + Py_INCREF(func); + pto->args = PyTuple_GetSlice(args, 1, PY_SSIZE_T_MAX); + if (pto->args == NULL) { + pto->kw = NULL; + Py_DECREF(pto); + return NULL; + } + if (kw != NULL) { + pto->kw = PyDict_Copy(kw); + if (pto->kw == NULL) { + Py_DECREF(pto); + return NULL; + } + } else { + pto->kw = Py_None; + Py_INCREF(Py_None); + } - pto->weakreflist = NULL; - pto->dict = NULL; + pto->weakreflist = NULL; + pto->dict = NULL; - return (PyObject *)pto; + return (PyObject *)pto; } static void partial_dealloc(partialobject *pto) { - PyObject_GC_UnTrack(pto); - if (pto->weakreflist != NULL) - PyObject_ClearWeakRefs((PyObject *) pto); - Py_XDECREF(pto->fn); - Py_XDECREF(pto->args); - Py_XDECREF(pto->kw); - Py_XDECREF(pto->dict); - Py_TYPE(pto)->tp_free(pto); + PyObject_GC_UnTrack(pto); + if (pto->weakreflist != NULL) + PyObject_ClearWeakRefs((PyObject *) pto); + Py_XDECREF(pto->fn); + Py_XDECREF(pto->args); + Py_XDECREF(pto->kw); + Py_XDECREF(pto->dict); + Py_TYPE(pto)->tp_free(pto); } static PyObject * partial_call(partialobject *pto, PyObject *args, PyObject *kw) { - PyObject *ret; - PyObject *argappl = NULL, *kwappl = NULL; + PyObject *ret; + PyObject *argappl = NULL, *kwappl = NULL; - assert (PyCallable_Check(pto->fn)); - assert (PyTuple_Check(pto->args)); - assert (pto->kw == Py_None || PyDict_Check(pto->kw)); - - if (PyTuple_GET_SIZE(pto->args) == 0) { - argappl = args; - Py_INCREF(args); - } else if (PyTuple_GET_SIZE(args) == 0) { - argappl = pto->args; - Py_INCREF(pto->args); - } else { - argappl = PySequence_Concat(pto->args, args); - if (argappl == NULL) - return NULL; - } - - if (pto->kw == Py_None) { - kwappl = kw; - Py_XINCREF(kw); - } else { - kwappl = PyDict_Copy(pto->kw); - if (kwappl == NULL) { - Py_DECREF(argappl); - return NULL; - } - if (kw != NULL) { - if (PyDict_Merge(kwappl, kw, 1) != 0) { - Py_DECREF(argappl); - Py_DECREF(kwappl); - return NULL; - } - } - } - - ret = PyObject_Call(pto->fn, argappl, kwappl); - Py_DECREF(argappl); - Py_XDECREF(kwappl); - return ret; + assert (PyCallable_Check(pto->fn)); + assert (PyTuple_Check(pto->args)); + assert (pto->kw == Py_None || PyDict_Check(pto->kw)); + + if (PyTuple_GET_SIZE(pto->args) == 0) { + argappl = args; + Py_INCREF(args); + } else if (PyTuple_GET_SIZE(args) == 0) { + argappl = pto->args; + Py_INCREF(pto->args); + } else { + argappl = PySequence_Concat(pto->args, args); + if (argappl == NULL) + return NULL; + } + + if (pto->kw == Py_None) { + kwappl = kw; + Py_XINCREF(kw); + } else { + kwappl = PyDict_Copy(pto->kw); + if (kwappl == NULL) { + Py_DECREF(argappl); + return NULL; + } + if (kw != NULL) { + if (PyDict_Merge(kwappl, kw, 1) != 0) { + Py_DECREF(argappl); + Py_DECREF(kwappl); + return NULL; + } + } + } + + ret = PyObject_Call(pto->fn, argappl, kwappl); + Py_DECREF(argappl); + Py_XDECREF(kwappl); + return ret; } static int partial_traverse(partialobject *pto, visitproc visit, void *arg) { - Py_VISIT(pto->fn); - Py_VISIT(pto->args); - Py_VISIT(pto->kw); - Py_VISIT(pto->dict); - return 0; + Py_VISIT(pto->fn); + Py_VISIT(pto->args); + Py_VISIT(pto->kw); + Py_VISIT(pto->dict); + return 0; } PyDoc_STRVAR(partial_doc, "partial(func, *args, **keywords) - new function with partial application\n\ - of the given arguments and keywords.\n"); + of the given arguments and keywords.\n"); #define OFF(x) offsetof(partialobject, x) static PyMemberDef partial_memberlist[] = { - {"func", T_OBJECT, OFF(fn), READONLY, - "function object to use in future partial calls"}, - {"args", T_OBJECT, OFF(args), READONLY, - "tuple of arguments to future partial calls"}, - {"keywords", T_OBJECT, OFF(kw), READONLY, - "dictionary of keyword arguments to future partial calls"}, - {NULL} /* Sentinel */ + {"func", T_OBJECT, OFF(fn), READONLY, + "function object to use in future partial calls"}, + {"args", T_OBJECT, OFF(args), READONLY, + "tuple of arguments to future partial calls"}, + {"keywords", T_OBJECT, OFF(kw), READONLY, + "dictionary of keyword arguments to future partial calls"}, + {NULL} /* Sentinel */ }; static PyObject * partial_get_dict(partialobject *pto) { - if (pto->dict == NULL) { - pto->dict = PyDict_New(); - if (pto->dict == NULL) - return NULL; - } - Py_INCREF(pto->dict); - return pto->dict; + if (pto->dict == NULL) { + pto->dict = PyDict_New(); + if (pto->dict == NULL) + return NULL; + } + Py_INCREF(pto->dict); + return pto->dict; } static int partial_set_dict(partialobject *pto, PyObject *value) { - PyObject *tmp; + PyObject *tmp; - /* It is illegal to del p.__dict__ */ - if (value == NULL) { - PyErr_SetString(PyExc_TypeError, - "a partial object's dictionary may not be deleted"); - return -1; - } - /* Can only set __dict__ to a dictionary */ - if (!PyDict_Check(value)) { - PyErr_SetString(PyExc_TypeError, - "setting partial object's dictionary to a non-dict"); - return -1; - } - tmp = pto->dict; - Py_INCREF(value); - pto->dict = value; - Py_XDECREF(tmp); - return 0; + /* It is illegal to del p.__dict__ */ + if (value == NULL) { + PyErr_SetString(PyExc_TypeError, + "a partial object's dictionary may not be deleted"); + return -1; + } + /* Can only set __dict__ to a dictionary */ + if (!PyDict_Check(value)) { + PyErr_SetString(PyExc_TypeError, + "setting partial object's dictionary to a non-dict"); + return -1; + } + tmp = pto->dict; + Py_INCREF(value); + pto->dict = value; + Py_XDECREF(tmp); + return 0; } static PyGetSetDef partial_getsetlist[] = { - {"__dict__", (getter)partial_get_dict, (setter)partial_set_dict}, - {NULL} /* Sentinel */ + {"__dict__", (getter)partial_get_dict, (setter)partial_set_dict}, + {NULL} /* Sentinel */ }; /* Pickle strategy: @@ -206,85 +206,85 @@ static PyObject * partial_reduce(partialobject *pto, PyObject *unused) { - return Py_BuildValue("O(O)(OOOO)", Py_TYPE(pto), pto->fn, pto->fn, - pto->args, pto->kw, - pto->dict ? pto->dict : Py_None); + return Py_BuildValue("O(O)(OOOO)", Py_TYPE(pto), pto->fn, pto->fn, + pto->args, pto->kw, + pto->dict ? pto->dict : Py_None); } static PyObject * partial_setstate(partialobject *pto, PyObject *args) { - PyObject *fn, *fnargs, *kw, *dict; - if (!PyArg_ParseTuple(args, "(OOOO):__setstate__", - &fn, &fnargs, &kw, &dict)) - return NULL; - Py_XDECREF(pto->fn); - Py_XDECREF(pto->args); - Py_XDECREF(pto->kw); - Py_XDECREF(pto->dict); - pto->fn = fn; - pto->args = fnargs; - pto->kw = kw; - if (dict != Py_None) { - pto->dict = dict; - Py_INCREF(dict); - } else { - pto->dict = NULL; - } - Py_INCREF(fn); - Py_INCREF(fnargs); - Py_INCREF(kw); - Py_RETURN_NONE; + PyObject *fn, *fnargs, *kw, *dict; + if (!PyArg_ParseTuple(args, "(OOOO):__setstate__", + &fn, &fnargs, &kw, &dict)) + return NULL; + Py_XDECREF(pto->fn); + Py_XDECREF(pto->args); + Py_XDECREF(pto->kw); + Py_XDECREF(pto->dict); + pto->fn = fn; + pto->args = fnargs; + pto->kw = kw; + if (dict != Py_None) { + pto->dict = dict; + Py_INCREF(dict); + } else { + pto->dict = NULL; + } + Py_INCREF(fn); + Py_INCREF(fnargs); + Py_INCREF(kw); + Py_RETURN_NONE; } static PyMethodDef partial_methods[] = { - {"__reduce__", (PyCFunction)partial_reduce, METH_NOARGS}, - {"__setstate__", (PyCFunction)partial_setstate, METH_VARARGS}, - {NULL, NULL} /* sentinel */ + {"__reduce__", (PyCFunction)partial_reduce, METH_NOARGS}, + {"__setstate__", (PyCFunction)partial_setstate, METH_VARARGS}, + {NULL, NULL} /* sentinel */ }; static PyTypeObject partial_type = { - PyVarObject_HEAD_INIT(NULL, 0) - "functools.partial", /* tp_name */ - sizeof(partialobject), /* tp_basicsize */ - 0, /* tp_itemsize */ - /* methods */ - (destructor)partial_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 */ - (ternaryfunc)partial_call, /* tp_call */ - 0, /* tp_str */ - PyObject_GenericGetAttr, /* tp_getattro */ - PyObject_GenericSetAttr, /* tp_setattro */ - 0, /* tp_as_buffer */ - Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC | - Py_TPFLAGS_BASETYPE, /* tp_flags */ - partial_doc, /* tp_doc */ - (traverseproc)partial_traverse, /* tp_traverse */ - 0, /* tp_clear */ - 0, /* tp_richcompare */ - offsetof(partialobject, weakreflist), /* tp_weaklistoffset */ - 0, /* tp_iter */ - 0, /* tp_iternext */ - partial_methods, /* tp_methods */ - partial_memberlist, /* tp_members */ - partial_getsetlist, /* tp_getset */ - 0, /* tp_base */ - 0, /* tp_dict */ - 0, /* tp_descr_get */ - 0, /* tp_descr_set */ - offsetof(partialobject, dict), /* tp_dictoffset */ - 0, /* tp_init */ - 0, /* tp_alloc */ - partial_new, /* tp_new */ - PyObject_GC_Del, /* tp_free */ + PyVarObject_HEAD_INIT(NULL, 0) + "functools.partial", /* tp_name */ + sizeof(partialobject), /* tp_basicsize */ + 0, /* tp_itemsize */ + /* methods */ + (destructor)partial_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 */ + (ternaryfunc)partial_call, /* tp_call */ + 0, /* tp_str */ + PyObject_GenericGetAttr, /* tp_getattro */ + PyObject_GenericSetAttr, /* tp_setattro */ + 0, /* tp_as_buffer */ + Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC | + Py_TPFLAGS_BASETYPE, /* tp_flags */ + partial_doc, /* tp_doc */ + (traverseproc)partial_traverse, /* tp_traverse */ + 0, /* tp_clear */ + 0, /* tp_richcompare */ + offsetof(partialobject, weakreflist), /* tp_weaklistoffset */ + 0, /* tp_iter */ + 0, /* tp_iternext */ + partial_methods, /* tp_methods */ + partial_memberlist, /* tp_members */ + partial_getsetlist, /* tp_getset */ + 0, /* tp_base */ + 0, /* tp_dict */ + 0, /* tp_descr_get */ + 0, /* tp_descr_set */ + offsetof(partialobject, dict), /* tp_dictoffset */ + 0, /* tp_init */ + 0, /* tp_alloc */ + partial_new, /* tp_new */ + PyObject_GC_Del, /* tp_free */ }; @@ -293,64 +293,64 @@ static PyObject * functools_reduce(PyObject *self, PyObject *args) { - PyObject *seq, *func, *result = NULL, *it; + PyObject *seq, *func, *result = NULL, *it; - if (!PyArg_UnpackTuple(args, "reduce", 2, 3, &func, &seq, &result)) - return NULL; - if (result != NULL) - Py_INCREF(result); - - it = PyObject_GetIter(seq); - if (it == NULL) { - PyErr_SetString(PyExc_TypeError, - "reduce() arg 2 must support iteration"); - Py_XDECREF(result); - return NULL; - } - - if ((args = PyTuple_New(2)) == NULL) - goto Fail; - - for (;;) { - PyObject *op2; - - if (args->ob_refcnt > 1) { - Py_DECREF(args); - if ((args = PyTuple_New(2)) == NULL) - goto Fail; - } - - op2 = PyIter_Next(it); - if (op2 == NULL) { - if (PyErr_Occurred()) - goto Fail; - break; - } - - if (result == NULL) - result = op2; - else { - PyTuple_SetItem(args, 0, result); - PyTuple_SetItem(args, 1, op2); - if ((result = PyEval_CallObject(func, args)) == NULL) - goto Fail; - } - } - - Py_DECREF(args); - - if (result == NULL) - PyErr_SetString(PyExc_TypeError, - "reduce() of empty sequence with no initial value"); + if (!PyArg_UnpackTuple(args, "reduce", 2, 3, &func, &seq, &result)) + return NULL; + if (result != NULL) + Py_INCREF(result); + + it = PyObject_GetIter(seq); + if (it == NULL) { + PyErr_SetString(PyExc_TypeError, + "reduce() arg 2 must support iteration"); + Py_XDECREF(result); + return NULL; + } + + if ((args = PyTuple_New(2)) == NULL) + goto Fail; + + for (;;) { + PyObject *op2; + + if (args->ob_refcnt > 1) { + Py_DECREF(args); + if ((args = PyTuple_New(2)) == NULL) + goto Fail; + } + + op2 = PyIter_Next(it); + if (op2 == NULL) { + if (PyErr_Occurred()) + goto Fail; + break; + } + + if (result == NULL) + result = op2; + else { + PyTuple_SetItem(args, 0, result); + PyTuple_SetItem(args, 1, op2); + if ((result = PyEval_CallObject(func, args)) == NULL) + goto Fail; + } + } + + Py_DECREF(args); + + if (result == NULL) + PyErr_SetString(PyExc_TypeError, + "reduce() of empty sequence with no initial value"); - Py_DECREF(it); - return result; + Py_DECREF(it); + return result; Fail: - Py_XDECREF(args); - Py_XDECREF(result); - Py_DECREF(it); - return NULL; + Py_XDECREF(args); + Py_XDECREF(result); + Py_DECREF(it); + return NULL; } PyDoc_STRVAR(functools_reduce_doc, @@ -369,47 +369,47 @@ "Tools that operate on functions."); static PyMethodDef module_methods[] = { - {"reduce", functools_reduce, METH_VARARGS, functools_reduce_doc}, - {NULL, NULL} /* sentinel */ + {"reduce", functools_reduce, METH_VARARGS, functools_reduce_doc}, + {NULL, NULL} /* sentinel */ }; static struct PyModuleDef _functoolsmodule = { - PyModuleDef_HEAD_INIT, - "_functools", - module_doc, - -1, - module_methods, - NULL, - NULL, - NULL, - NULL + PyModuleDef_HEAD_INIT, + "_functools", + module_doc, + -1, + module_methods, + NULL, + NULL, + NULL, + NULL }; PyMODINIT_FUNC PyInit__functools(void) { - int i; - PyObject *m; - char *name; - PyTypeObject *typelist[] = { - &partial_type, - NULL - }; - - m = PyModule_Create(&_functoolsmodule); - if (m == NULL) - return NULL; - - for (i=0 ; typelist[i] != NULL ; i++) { - if (PyType_Ready(typelist[i]) < 0) { - Py_DECREF(m); - return NULL; - } - name = strchr(typelist[i]->tp_name, '.'); - assert (name != NULL); - Py_INCREF(typelist[i]); - PyModule_AddObject(m, name+1, (PyObject *)typelist[i]); - } - return m; + int i; + PyObject *m; + char *name; + PyTypeObject *typelist[] = { + &partial_type, + NULL + }; + + m = PyModule_Create(&_functoolsmodule); + if (m == NULL) + return NULL; + + for (i=0 ; typelist[i] != NULL ; i++) { + if (PyType_Ready(typelist[i]) < 0) { + Py_DECREF(m); + return NULL; + } + name = strchr(typelist[i]->tp_name, '.'); + assert (name != NULL); + Py_INCREF(typelist[i]); + PyModule_AddObject(m, name+1, (PyObject *)typelist[i]); + } + return m; } Modified: python/branches/release31-maint/Modules/_gdbmmodule.c ============================================================================== --- python/branches/release31-maint/Modules/_gdbmmodule.c (original) +++ python/branches/release31-maint/Modules/_gdbmmodule.c Sun May 9 18:14:21 2010 @@ -30,7 +30,7 @@ typedef struct { PyObject_HEAD - int di_size; /* -1 means recompute */ + int di_size; /* -1 means recompute */ GDBM_FILE di_dbm; } dbmobject; @@ -177,7 +177,7 @@ } static PyMappingMethods dbm_as_mapping = { - (lenfunc)dbm_length, /*mp_length*/ + (lenfunc)dbm_length, /*mp_length*/ (binaryfunc)dbm_subscript, /*mp_subscript*/ (objobjargproc)dbm_ass_sub, /*mp_ass_subscript*/ }; @@ -247,15 +247,15 @@ datum key; if ((dp)->di_dbm == NULL) { - PyErr_SetString(DbmError, - "GDBM object has already been closed"); - return -1; + PyErr_SetString(DbmError, + "GDBM object has already been closed"); + return -1; } if (!PyBytes_Check(arg)) { - PyErr_Format(PyExc_TypeError, - "gdbm key must be bytes, not %.100s", - arg->ob_type->tp_name); - return -1; + PyErr_Format(PyExc_TypeError, + "gdbm key must be bytes, not %.100s", + arg->ob_type->tp_name); + return -1; } key.dptr = PyBytes_AS_STRING(arg); key.dsize = PyBytes_GET_SIZE(arg); @@ -263,16 +263,16 @@ } static PySequenceMethods dbm_as_sequence = { - 0, /* sq_length */ - 0, /* sq_concat */ - 0, /* sq_repeat */ - 0, /* sq_item */ - 0, /* sq_slice */ - 0, /* sq_ass_item */ - 0, /* sq_ass_slice */ - dbm_contains, /* sq_contains */ - 0, /* sq_inplace_concat */ - 0, /* sq_inplace_repeat */ + 0, /* sq_length */ + 0, /* sq_concat */ + 0, /* sq_repeat */ + 0, /* sq_item */ + 0, /* sq_slice */ + 0, /* sq_ass_item */ + 0, /* sq_ass_slice */ + dbm_contains, /* sq_contains */ + 0, /* sq_inplace_concat */ + 0, /* sq_inplace_repeat */ }; PyDoc_STRVAR(dbm_firstkey__doc__, @@ -372,13 +372,13 @@ } static PyMethodDef dbm_methods[] = { - {"close", (PyCFunction)dbm_close, METH_NOARGS, dbm_close__doc__}, - {"keys", (PyCFunction)dbm_keys, METH_NOARGS, dbm_keys__doc__}, + {"close", (PyCFunction)dbm_close, METH_NOARGS, dbm_close__doc__}, + {"keys", (PyCFunction)dbm_keys, METH_NOARGS, dbm_keys__doc__}, {"firstkey", (PyCFunction)dbm_firstkey,METH_NOARGS, dbm_firstkey__doc__}, - {"nextkey", (PyCFunction)dbm_nextkey, METH_VARARGS, dbm_nextkey__doc__}, + {"nextkey", (PyCFunction)dbm_nextkey, METH_VARARGS, dbm_nextkey__doc__}, {"reorganize",(PyCFunction)dbm_reorganize,METH_NOARGS, dbm_reorganize__doc__}, {"sync", (PyCFunction)dbm_sync, METH_NOARGS, dbm_sync__doc__}, - {NULL, NULL} /* sentinel */ + {NULL, NULL} /* sentinel */ }; static PyTypeObject Dbmtype = { @@ -486,7 +486,7 @@ #endif default: PyOS_snprintf(buf, sizeof(buf), "Flag '%c' is not supported.", - *flags); + *flags); PyErr_SetString(DbmError, buf); return NULL; } @@ -514,15 +514,15 @@ static struct PyModuleDef _gdbmmodule = { - PyModuleDef_HEAD_INIT, - "_gdbm", - gdbmmodule__doc__, - -1, - dbmmodule_methods, - NULL, - NULL, - NULL, - NULL + PyModuleDef_HEAD_INIT, + "_gdbm", + gdbmmodule__doc__, + -1, + dbmmodule_methods, + NULL, + NULL, + NULL, + NULL }; PyMODINIT_FUNC @@ -530,10 +530,10 @@ PyObject *m, *d, *s; if (PyType_Ready(&Dbmtype) < 0) - return NULL; + return NULL; m = PyModule_Create(&_gdbmmodule); if (m == NULL) - return NULL; + return NULL; d = PyModule_GetDict(m); DbmError = PyErr_NewException("_gdbm.error", PyExc_IOError, NULL); if (DbmError != NULL) { Modified: python/branches/release31-maint/Modules/_gestalt.c ============================================================================== --- python/branches/release31-maint/Modules/_gestalt.c (original) +++ python/branches/release31-maint/Modules/_gestalt.c Sun May 9 18:14:21 2010 @@ -4,10 +4,10 @@ All Rights Reserved -Permission to use, copy, modify, and distribute this software and its -documentation for any purpose and without fee is hereby granted, +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 +both that copyright notice and this permission notice appear in supporting documentation, and that the names of Stichting Mathematisch Centrum or CWI not be used in advertising or publicity pertaining to distribution of the software without specific, written prior permission. @@ -34,9 +34,9 @@ { uint32_t tmp; if (!PyUnicode_Check(v) || PyUnicode_GetSize(v) != 4) { - PyErr_SetString(PyExc_TypeError, - "OSType arg must be string of 4 chars"); - return 0; + PyErr_SetString(PyExc_TypeError, + "OSType arg must be string of 4 chars"); + return 0; } memcpy((char *)&tmp, _PyUnicode_AsString(v), 4); *pr = (OSType)ntohl(tmp); @@ -50,12 +50,12 @@ OSType selector; SInt32 response; if (!PyArg_ParseTuple(args, "O&", convert_to_OSType, &selector)) - return NULL; + return NULL; iErr = Gestalt(selector, &response); if (iErr != 0) { - PyErr_SetString(PyExc_OSError, - "non-zero exit code!"); - return NULL; + PyErr_SetString(PyExc_OSError, + "non-zero exit code!"); + return NULL; } return PyLong_FromLong(response); } @@ -66,19 +66,19 @@ }; static struct PyModuleDef gestaltmodule = { - PyModuleDef_HEAD_INIT, - "_gestalt", - NULL, - -1, - gestalt_methods, - NULL, - NULL, - NULL, - NULL + PyModuleDef_HEAD_INIT, + "_gestalt", + NULL, + -1, + gestalt_methods, + NULL, + NULL, + NULL, + NULL }; PyMODINIT_FUNC PyInit__gestalt(void) { - return PyModule_Create(&gestaltmodule); + return PyModule_Create(&gestaltmodule); } Modified: python/branches/release31-maint/Modules/_heapqmodule.c ============================================================================== --- python/branches/release31-maint/Modules/_heapqmodule.c (original) +++ python/branches/release31-maint/Modules/_heapqmodule.c Sun May 9 18:14:21 2010 @@ -1,4 +1,4 @@ -/* Drop in replacement for heapq.py +/* Drop in replacement for heapq.py C implementation derived directly from heapq.py in Py2.3 which was written by Kevin O'Connor, augmented by Tim Peters, @@ -11,115 +11,115 @@ static int cmp_lt(PyObject *x, PyObject *y) { - return PyObject_RichCompareBool(x, y, Py_LT); + return PyObject_RichCompareBool(x, y, Py_LT); } static int _siftdown(PyListObject *heap, Py_ssize_t startpos, Py_ssize_t pos) { - PyObject *newitem, *parent; - int cmp; - Py_ssize_t parentpos; - - assert(PyList_Check(heap)); - if (pos >= PyList_GET_SIZE(heap)) { - PyErr_SetString(PyExc_IndexError, "index out of range"); - return -1; - } - - newitem = PyList_GET_ITEM(heap, pos); - Py_INCREF(newitem); - /* Follow the path to the root, moving parents down until finding - a place newitem fits. */ - while (pos > startpos){ - parentpos = (pos - 1) >> 1; - parent = PyList_GET_ITEM(heap, parentpos); - cmp = cmp_lt(newitem, parent); - if (cmp == -1) { - Py_DECREF(newitem); - return -1; - } - if (cmp == 0) - break; - Py_INCREF(parent); - Py_DECREF(PyList_GET_ITEM(heap, pos)); - PyList_SET_ITEM(heap, pos, parent); - pos = parentpos; - } - Py_DECREF(PyList_GET_ITEM(heap, pos)); - PyList_SET_ITEM(heap, pos, newitem); - return 0; + PyObject *newitem, *parent; + int cmp; + Py_ssize_t parentpos; + + assert(PyList_Check(heap)); + if (pos >= PyList_GET_SIZE(heap)) { + PyErr_SetString(PyExc_IndexError, "index out of range"); + return -1; + } + + newitem = PyList_GET_ITEM(heap, pos); + Py_INCREF(newitem); + /* Follow the path to the root, moving parents down until finding + a place newitem fits. */ + while (pos > startpos){ + parentpos = (pos - 1) >> 1; + parent = PyList_GET_ITEM(heap, parentpos); + cmp = cmp_lt(newitem, parent); + if (cmp == -1) { + Py_DECREF(newitem); + return -1; + } + if (cmp == 0) + break; + Py_INCREF(parent); + Py_DECREF(PyList_GET_ITEM(heap, pos)); + PyList_SET_ITEM(heap, pos, parent); + pos = parentpos; + } + Py_DECREF(PyList_GET_ITEM(heap, pos)); + PyList_SET_ITEM(heap, pos, newitem); + return 0; } static int _siftup(PyListObject *heap, Py_ssize_t pos) { - Py_ssize_t startpos, endpos, childpos, rightpos; - int cmp; - PyObject *newitem, *tmp; - - assert(PyList_Check(heap)); - endpos = PyList_GET_SIZE(heap); - startpos = pos; - if (pos >= endpos) { - PyErr_SetString(PyExc_IndexError, "index out of range"); - return -1; - } - newitem = PyList_GET_ITEM(heap, pos); - Py_INCREF(newitem); - - /* Bubble up the smaller child until hitting a leaf. */ - childpos = 2*pos + 1; /* leftmost child position */ - while (childpos < endpos) { - /* Set childpos to index of smaller child. */ - rightpos = childpos + 1; - if (rightpos < endpos) { - cmp = cmp_lt( - PyList_GET_ITEM(heap, childpos), - PyList_GET_ITEM(heap, rightpos)); - if (cmp == -1) { - Py_DECREF(newitem); - return -1; - } - if (cmp == 0) - childpos = rightpos; - } - /* Move the smaller child up. */ - tmp = PyList_GET_ITEM(heap, childpos); - Py_INCREF(tmp); - Py_DECREF(PyList_GET_ITEM(heap, pos)); - PyList_SET_ITEM(heap, pos, tmp); - pos = childpos; - childpos = 2*pos + 1; - } - - /* The leaf at pos is empty now. Put newitem there, and and bubble - it up to its final resting place (by sifting its parents down). */ - Py_DECREF(PyList_GET_ITEM(heap, pos)); - PyList_SET_ITEM(heap, pos, newitem); - return _siftdown(heap, startpos, pos); + Py_ssize_t startpos, endpos, childpos, rightpos; + int cmp; + PyObject *newitem, *tmp; + + assert(PyList_Check(heap)); + endpos = PyList_GET_SIZE(heap); + startpos = pos; + if (pos >= endpos) { + PyErr_SetString(PyExc_IndexError, "index out of range"); + return -1; + } + newitem = PyList_GET_ITEM(heap, pos); + Py_INCREF(newitem); + + /* Bubble up the smaller child until hitting a leaf. */ + childpos = 2*pos + 1; /* leftmost child position */ + while (childpos < endpos) { + /* Set childpos to index of smaller child. */ + rightpos = childpos + 1; + if (rightpos < endpos) { + cmp = cmp_lt( + PyList_GET_ITEM(heap, childpos), + PyList_GET_ITEM(heap, rightpos)); + if (cmp == -1) { + Py_DECREF(newitem); + return -1; + } + if (cmp == 0) + childpos = rightpos; + } + /* Move the smaller child up. */ + tmp = PyList_GET_ITEM(heap, childpos); + Py_INCREF(tmp); + Py_DECREF(PyList_GET_ITEM(heap, pos)); + PyList_SET_ITEM(heap, pos, tmp); + pos = childpos; + childpos = 2*pos + 1; + } + + /* The leaf at pos is empty now. Put newitem there, and and bubble + it up to its final resting place (by sifting its parents down). */ + Py_DECREF(PyList_GET_ITEM(heap, pos)); + PyList_SET_ITEM(heap, pos, newitem); + return _siftdown(heap, startpos, pos); } static PyObject * heappush(PyObject *self, PyObject *args) { - PyObject *heap, *item; + PyObject *heap, *item; - if (!PyArg_UnpackTuple(args, "heappush", 2, 2, &heap, &item)) - return NULL; + if (!PyArg_UnpackTuple(args, "heappush", 2, 2, &heap, &item)) + return NULL; - if (!PyList_Check(heap)) { - PyErr_SetString(PyExc_TypeError, "heap argument must be a list"); - return NULL; - } - - if (PyList_Append(heap, item) == -1) - return NULL; - - if (_siftdown((PyListObject *)heap, 0, PyList_GET_SIZE(heap)-1) == -1) - return NULL; - Py_INCREF(Py_None); - return Py_None; + if (!PyList_Check(heap)) { + PyErr_SetString(PyExc_TypeError, "heap argument must be a list"); + return NULL; + } + + if (PyList_Append(heap, item) == -1) + return NULL; + + if (_siftdown((PyListObject *)heap, 0, PyList_GET_SIZE(heap)-1) == -1) + return NULL; + Py_INCREF(Py_None); + return Py_None; } PyDoc_STRVAR(heappush_doc, @@ -128,35 +128,35 @@ static PyObject * heappop(PyObject *self, PyObject *heap) { - PyObject *lastelt, *returnitem; - Py_ssize_t n; + PyObject *lastelt, *returnitem; + Py_ssize_t n; - if (!PyList_Check(heap)) { - PyErr_SetString(PyExc_TypeError, "heap argument must be a list"); - return NULL; - } - - /* # raises appropriate IndexError if heap is empty */ - n = PyList_GET_SIZE(heap); - if (n == 0) { - PyErr_SetString(PyExc_IndexError, "index out of range"); - return NULL; - } - - lastelt = PyList_GET_ITEM(heap, n-1) ; - Py_INCREF(lastelt); - PyList_SetSlice(heap, n-1, n, NULL); - n--; - - if (!n) - return lastelt; - returnitem = PyList_GET_ITEM(heap, 0); - PyList_SET_ITEM(heap, 0, lastelt); - if (_siftup((PyListObject *)heap, 0) == -1) { - Py_DECREF(returnitem); - return NULL; - } - return returnitem; + if (!PyList_Check(heap)) { + PyErr_SetString(PyExc_TypeError, "heap argument must be a list"); + return NULL; + } + + /* # raises appropriate IndexError if heap is empty */ + n = PyList_GET_SIZE(heap); + if (n == 0) { + PyErr_SetString(PyExc_IndexError, "index out of range"); + return NULL; + } + + lastelt = PyList_GET_ITEM(heap, n-1) ; + Py_INCREF(lastelt); + PyList_SetSlice(heap, n-1, n, NULL); + n--; + + if (!n) + return lastelt; + returnitem = PyList_GET_ITEM(heap, 0); + PyList_SET_ITEM(heap, 0, lastelt); + if (_siftup((PyListObject *)heap, 0) == -1) { + Py_DECREF(returnitem); + return NULL; + } + return returnitem; } PyDoc_STRVAR(heappop_doc, @@ -165,29 +165,29 @@ static PyObject * heapreplace(PyObject *self, PyObject *args) { - PyObject *heap, *item, *returnitem; + PyObject *heap, *item, *returnitem; - if (!PyArg_UnpackTuple(args, "heapreplace", 2, 2, &heap, &item)) - return NULL; + if (!PyArg_UnpackTuple(args, "heapreplace", 2, 2, &heap, &item)) + return NULL; - if (!PyList_Check(heap)) { - PyErr_SetString(PyExc_TypeError, "heap argument must be a list"); - return NULL; - } - - if (PyList_GET_SIZE(heap) < 1) { - PyErr_SetString(PyExc_IndexError, "index out of range"); - return NULL; - } - - returnitem = PyList_GET_ITEM(heap, 0); - Py_INCREF(item); - PyList_SET_ITEM(heap, 0, item); - if (_siftup((PyListObject *)heap, 0) == -1) { - Py_DECREF(returnitem); - return NULL; - } - return returnitem; + if (!PyList_Check(heap)) { + PyErr_SetString(PyExc_TypeError, "heap argument must be a list"); + return NULL; + } + + if (PyList_GET_SIZE(heap) < 1) { + PyErr_SetString(PyExc_IndexError, "index out of range"); + return NULL; + } + + returnitem = PyList_GET_ITEM(heap, 0); + Py_INCREF(item); + PyList_SET_ITEM(heap, 0, item); + if (_siftup((PyListObject *)heap, 0) == -1) { + Py_DECREF(returnitem); + return NULL; + } + return returnitem; } PyDoc_STRVAR(heapreplace_doc, @@ -197,44 +197,44 @@ more appropriate when using a fixed-size heap. Note that the value\n\ returned may be larger than item! That constrains reasonable uses of\n\ this routine unless written as part of a conditional replacement:\n\n\ - if item > heap[0]:\n\ - item = heapreplace(heap, item)\n"); + if item > heap[0]:\n\ + item = heapreplace(heap, item)\n"); static PyObject * heappushpop(PyObject *self, PyObject *args) { - PyObject *heap, *item, *returnitem; - int cmp; + PyObject *heap, *item, *returnitem; + int cmp; - if (!PyArg_UnpackTuple(args, "heappushpop", 2, 2, &heap, &item)) - return NULL; + if (!PyArg_UnpackTuple(args, "heappushpop", 2, 2, &heap, &item)) + return NULL; - if (!PyList_Check(heap)) { - PyErr_SetString(PyExc_TypeError, "heap argument must be a list"); - return NULL; - } - - if (PyList_GET_SIZE(heap) < 1) { - Py_INCREF(item); - return item; - } - - cmp = cmp_lt(PyList_GET_ITEM(heap, 0), item); - if (cmp == -1) - return NULL; - if (cmp == 0) { - Py_INCREF(item); - return item; - } - - returnitem = PyList_GET_ITEM(heap, 0); - Py_INCREF(item); - PyList_SET_ITEM(heap, 0, item); - if (_siftup((PyListObject *)heap, 0) == -1) { - Py_DECREF(returnitem); - return NULL; - } - return returnitem; + if (!PyList_Check(heap)) { + PyErr_SetString(PyExc_TypeError, "heap argument must be a list"); + return NULL; + } + + if (PyList_GET_SIZE(heap) < 1) { + Py_INCREF(item); + return item; + } + + cmp = cmp_lt(PyList_GET_ITEM(heap, 0), item); + if (cmp == -1) + return NULL; + if (cmp == 0) { + Py_INCREF(item); + return item; + } + + returnitem = PyList_GET_ITEM(heap, 0); + Py_INCREF(item); + PyList_SET_ITEM(heap, 0, item); + if (_siftup((PyListObject *)heap, 0) == -1) { + Py_DECREF(returnitem); + return NULL; + } + return returnitem; } PyDoc_STRVAR(heappushpop_doc, @@ -245,26 +245,26 @@ static PyObject * heapify(PyObject *self, PyObject *heap) { - Py_ssize_t i, n; + Py_ssize_t i, n; - if (!PyList_Check(heap)) { - PyErr_SetString(PyExc_TypeError, "heap argument must be a list"); - return NULL; - } - - n = PyList_GET_SIZE(heap); - /* Transform bottom-up. The largest index there's any point to - looking at is the largest with a child index in-range, so must - have 2*i + 1 < n, or i < (n-1)/2. If n is even = 2*j, this is - (2*j-1)/2 = j-1/2 so j-1 is the largest, which is n//2 - 1. If - n is odd = 2*j+1, this is (2*j+1-1)/2 = j so j-1 is the largest, - and that's again n//2-1. - */ - for (i=n/2-1 ; i>=0 ; i--) - if(_siftup((PyListObject *)heap, i) == -1) - return NULL; - Py_INCREF(Py_None); - return Py_None; + if (!PyList_Check(heap)) { + PyErr_SetString(PyExc_TypeError, "heap argument must be a list"); + return NULL; + } + + n = PyList_GET_SIZE(heap); + /* Transform bottom-up. The largest index there's any point to + looking at is the largest with a child index in-range, so must + have 2*i + 1 < n, or i < (n-1)/2. If n is even = 2*j, this is + (2*j-1)/2 = j-1/2 so j-1 is the largest, which is n//2 - 1. If + n is odd = 2*j+1, this is (2*j+1-1)/2 = j so j-1 is the largest, + and that's again n//2-1. + */ + for (i=n/2-1 ; i>=0 ; i--) + if(_siftup((PyListObject *)heap, i) == -1) + return NULL; + Py_INCREF(Py_None); + return Py_None; } PyDoc_STRVAR(heapify_doc, @@ -273,79 +273,79 @@ static PyObject * nlargest(PyObject *self, PyObject *args) { - PyObject *heap=NULL, *elem, *iterable, *sol, *it, *oldelem; - Py_ssize_t i, n; - int cmp; - - if (!PyArg_ParseTuple(args, "nO:nlargest", &n, &iterable)) - return NULL; - - it = PyObject_GetIter(iterable); - if (it == NULL) - return NULL; - - heap = PyList_New(0); - if (heap == NULL) - goto fail; - - for (i=0 ; i=0 ; i--) - if(_siftup((PyListObject *)heap, i) == -1) - goto fail; - - sol = PyList_GET_ITEM(heap, 0); - while (1) { - elem = PyIter_Next(it); - if (elem == NULL) { - if (PyErr_Occurred()) - goto fail; - else - goto sortit; - } - cmp = cmp_lt(sol, elem); - if (cmp == -1) { - Py_DECREF(elem); - goto fail; - } - if (cmp == 0) { - Py_DECREF(elem); - continue; - } - oldelem = PyList_GET_ITEM(heap, 0); - PyList_SET_ITEM(heap, 0, elem); - Py_DECREF(oldelem); - if (_siftup((PyListObject *)heap, 0) == -1) - goto fail; - sol = PyList_GET_ITEM(heap, 0); - } + PyObject *heap=NULL, *elem, *iterable, *sol, *it, *oldelem; + Py_ssize_t i, n; + int cmp; + + if (!PyArg_ParseTuple(args, "nO:nlargest", &n, &iterable)) + return NULL; + + it = PyObject_GetIter(iterable); + if (it == NULL) + return NULL; + + heap = PyList_New(0); + if (heap == NULL) + goto fail; + + for (i=0 ; i=0 ; i--) + if(_siftup((PyListObject *)heap, i) == -1) + goto fail; + + sol = PyList_GET_ITEM(heap, 0); + while (1) { + elem = PyIter_Next(it); + if (elem == NULL) { + if (PyErr_Occurred()) + goto fail; + else + goto sortit; + } + cmp = cmp_lt(sol, elem); + if (cmp == -1) { + Py_DECREF(elem); + goto fail; + } + if (cmp == 0) { + Py_DECREF(elem); + continue; + } + oldelem = PyList_GET_ITEM(heap, 0); + PyList_SET_ITEM(heap, 0, elem); + Py_DECREF(oldelem); + if (_siftup((PyListObject *)heap, 0) == -1) + goto fail; + sol = PyList_GET_ITEM(heap, 0); + } sortit: - if (PyList_Sort(heap) == -1) - goto fail; - if (PyList_Reverse(heap) == -1) - goto fail; - Py_DECREF(it); - return heap; + if (PyList_Sort(heap) == -1) + goto fail; + if (PyList_Reverse(heap) == -1) + goto fail; + Py_DECREF(it); + return heap; fail: - Py_DECREF(it); - Py_XDECREF(heap); - return NULL; + Py_DECREF(it); + Py_XDECREF(heap); + return NULL; } PyDoc_STRVAR(nlargest_doc, @@ -356,166 +356,166 @@ static int _siftdownmax(PyListObject *heap, Py_ssize_t startpos, Py_ssize_t pos) { - PyObject *newitem, *parent; - int cmp; - Py_ssize_t parentpos; - - assert(PyList_Check(heap)); - if (pos >= PyList_GET_SIZE(heap)) { - PyErr_SetString(PyExc_IndexError, "index out of range"); - return -1; - } - - newitem = PyList_GET_ITEM(heap, pos); - Py_INCREF(newitem); - /* Follow the path to the root, moving parents down until finding - a place newitem fits. */ - while (pos > startpos){ - parentpos = (pos - 1) >> 1; - parent = PyList_GET_ITEM(heap, parentpos); - cmp = cmp_lt(parent, newitem); - if (cmp == -1) { - Py_DECREF(newitem); - return -1; - } - if (cmp == 0) - break; - Py_INCREF(parent); - Py_DECREF(PyList_GET_ITEM(heap, pos)); - PyList_SET_ITEM(heap, pos, parent); - pos = parentpos; - } - Py_DECREF(PyList_GET_ITEM(heap, pos)); - PyList_SET_ITEM(heap, pos, newitem); - return 0; + PyObject *newitem, *parent; + int cmp; + Py_ssize_t parentpos; + + assert(PyList_Check(heap)); + if (pos >= PyList_GET_SIZE(heap)) { + PyErr_SetString(PyExc_IndexError, "index out of range"); + return -1; + } + + newitem = PyList_GET_ITEM(heap, pos); + Py_INCREF(newitem); + /* Follow the path to the root, moving parents down until finding + a place newitem fits. */ + while (pos > startpos){ + parentpos = (pos - 1) >> 1; + parent = PyList_GET_ITEM(heap, parentpos); + cmp = cmp_lt(parent, newitem); + if (cmp == -1) { + Py_DECREF(newitem); + return -1; + } + if (cmp == 0) + break; + Py_INCREF(parent); + Py_DECREF(PyList_GET_ITEM(heap, pos)); + PyList_SET_ITEM(heap, pos, parent); + pos = parentpos; + } + Py_DECREF(PyList_GET_ITEM(heap, pos)); + PyList_SET_ITEM(heap, pos, newitem); + return 0; } static int _siftupmax(PyListObject *heap, Py_ssize_t pos) { - Py_ssize_t startpos, endpos, childpos, rightpos; - int cmp; - PyObject *newitem, *tmp; - - assert(PyList_Check(heap)); - endpos = PyList_GET_SIZE(heap); - startpos = pos; - if (pos >= endpos) { - PyErr_SetString(PyExc_IndexError, "index out of range"); - return -1; - } - newitem = PyList_GET_ITEM(heap, pos); - Py_INCREF(newitem); - - /* Bubble up the smaller child until hitting a leaf. */ - childpos = 2*pos + 1; /* leftmost child position */ - while (childpos < endpos) { - /* Set childpos to index of smaller child. */ - rightpos = childpos + 1; - if (rightpos < endpos) { - cmp = cmp_lt( - PyList_GET_ITEM(heap, rightpos), - PyList_GET_ITEM(heap, childpos)); - if (cmp == -1) { - Py_DECREF(newitem); - return -1; - } - if (cmp == 0) - childpos = rightpos; - } - /* Move the smaller child up. */ - tmp = PyList_GET_ITEM(heap, childpos); - Py_INCREF(tmp); - Py_DECREF(PyList_GET_ITEM(heap, pos)); - PyList_SET_ITEM(heap, pos, tmp); - pos = childpos; - childpos = 2*pos + 1; - } - - /* The leaf at pos is empty now. Put newitem there, and and bubble - it up to its final resting place (by sifting its parents down). */ - Py_DECREF(PyList_GET_ITEM(heap, pos)); - PyList_SET_ITEM(heap, pos, newitem); - return _siftdownmax(heap, startpos, pos); + Py_ssize_t startpos, endpos, childpos, rightpos; + int cmp; + PyObject *newitem, *tmp; + + assert(PyList_Check(heap)); + endpos = PyList_GET_SIZE(heap); + startpos = pos; + if (pos >= endpos) { + PyErr_SetString(PyExc_IndexError, "index out of range"); + return -1; + } + newitem = PyList_GET_ITEM(heap, pos); + Py_INCREF(newitem); + + /* Bubble up the smaller child until hitting a leaf. */ + childpos = 2*pos + 1; /* leftmost child position */ + while (childpos < endpos) { + /* Set childpos to index of smaller child. */ + rightpos = childpos + 1; + if (rightpos < endpos) { + cmp = cmp_lt( + PyList_GET_ITEM(heap, rightpos), + PyList_GET_ITEM(heap, childpos)); + if (cmp == -1) { + Py_DECREF(newitem); + return -1; + } + if (cmp == 0) + childpos = rightpos; + } + /* Move the smaller child up. */ + tmp = PyList_GET_ITEM(heap, childpos); + Py_INCREF(tmp); + Py_DECREF(PyList_GET_ITEM(heap, pos)); + PyList_SET_ITEM(heap, pos, tmp); + pos = childpos; + childpos = 2*pos + 1; + } + + /* The leaf at pos is empty now. Put newitem there, and and bubble + it up to its final resting place (by sifting its parents down). */ + Py_DECREF(PyList_GET_ITEM(heap, pos)); + PyList_SET_ITEM(heap, pos, newitem); + return _siftdownmax(heap, startpos, pos); } static PyObject * nsmallest(PyObject *self, PyObject *args) { - PyObject *heap=NULL, *elem, *iterable, *los, *it, *oldelem; - Py_ssize_t i, n; - int cmp; - - if (!PyArg_ParseTuple(args, "nO:nsmallest", &n, &iterable)) - return NULL; - - it = PyObject_GetIter(iterable); - if (it == NULL) - return NULL; - - heap = PyList_New(0); - if (heap == NULL) - goto fail; - - for (i=0 ; i=0 ; i--) - if(_siftupmax((PyListObject *)heap, i) == -1) - goto fail; - - los = PyList_GET_ITEM(heap, 0); - while (1) { - elem = PyIter_Next(it); - if (elem == NULL) { - if (PyErr_Occurred()) - goto fail; - else - goto sortit; - } - cmp = cmp_lt(elem, los); - if (cmp == -1) { - Py_DECREF(elem); - goto fail; - } - if (cmp == 0) { - Py_DECREF(elem); - continue; - } - - oldelem = PyList_GET_ITEM(heap, 0); - PyList_SET_ITEM(heap, 0, elem); - Py_DECREF(oldelem); - if (_siftupmax((PyListObject *)heap, 0) == -1) - goto fail; - los = PyList_GET_ITEM(heap, 0); - } + PyObject *heap=NULL, *elem, *iterable, *los, *it, *oldelem; + Py_ssize_t i, n; + int cmp; + + if (!PyArg_ParseTuple(args, "nO:nsmallest", &n, &iterable)) + return NULL; + + it = PyObject_GetIter(iterable); + if (it == NULL) + return NULL; + + heap = PyList_New(0); + if (heap == NULL) + goto fail; + + for (i=0 ; i=0 ; i--) + if(_siftupmax((PyListObject *)heap, i) == -1) + goto fail; + + los = PyList_GET_ITEM(heap, 0); + while (1) { + elem = PyIter_Next(it); + if (elem == NULL) { + if (PyErr_Occurred()) + goto fail; + else + goto sortit; + } + cmp = cmp_lt(elem, los); + if (cmp == -1) { + Py_DECREF(elem); + goto fail; + } + if (cmp == 0) { + Py_DECREF(elem); + continue; + } + + oldelem = PyList_GET_ITEM(heap, 0); + PyList_SET_ITEM(heap, 0, elem); + Py_DECREF(oldelem); + if (_siftupmax((PyListObject *)heap, 0) == -1) + goto fail; + los = PyList_GET_ITEM(heap, 0); + } sortit: - if (PyList_Sort(heap) == -1) - goto fail; - Py_DECREF(it); - return heap; + if (PyList_Sort(heap) == -1) + goto fail; + Py_DECREF(it); + return heap; fail: - Py_DECREF(it); - Py_XDECREF(heap); - return NULL; + Py_DECREF(it); + Py_XDECREF(heap); + return NULL; } PyDoc_STRVAR(nsmallest_doc, @@ -524,21 +524,21 @@ Equivalent to: sorted(iterable)[:n]\n"); static PyMethodDef heapq_methods[] = { - {"heappush", (PyCFunction)heappush, - METH_VARARGS, heappush_doc}, - {"heappushpop", (PyCFunction)heappushpop, - METH_VARARGS, heappushpop_doc}, - {"heappop", (PyCFunction)heappop, - METH_O, heappop_doc}, - {"heapreplace", (PyCFunction)heapreplace, - METH_VARARGS, heapreplace_doc}, - {"heapify", (PyCFunction)heapify, - METH_O, heapify_doc}, - {"nlargest", (PyCFunction)nlargest, - METH_VARARGS, nlargest_doc}, - {"nsmallest", (PyCFunction)nsmallest, - METH_VARARGS, nsmallest_doc}, - {NULL, NULL} /* sentinel */ + {"heappush", (PyCFunction)heappush, + METH_VARARGS, heappush_doc}, + {"heappushpop", (PyCFunction)heappushpop, + METH_VARARGS, heappushpop_doc}, + {"heappop", (PyCFunction)heappop, + METH_O, heappop_doc}, + {"heapreplace", (PyCFunction)heapreplace, + METH_VARARGS, heapreplace_doc}, + {"heapify", (PyCFunction)heapify, + METH_O, heapify_doc}, + {"nlargest", (PyCFunction)nlargest, + METH_VARARGS, nlargest_doc}, + {"nsmallest", (PyCFunction)nsmallest, + METH_VARARGS, nsmallest_doc}, + {NULL, NULL} /* sentinel */ }; PyDoc_STRVAR(module_doc, @@ -668,27 +668,27 @@ static struct PyModuleDef _heapqmodule = { - PyModuleDef_HEAD_INIT, - "_heapq", - module_doc, - -1, - heapq_methods, - NULL, - NULL, - NULL, - NULL + PyModuleDef_HEAD_INIT, + "_heapq", + module_doc, + -1, + heapq_methods, + NULL, + NULL, + NULL, + NULL }; PyMODINIT_FUNC PyInit__heapq(void) { - PyObject *m, *about; + PyObject *m, *about; - m = PyModule_Create(&_heapqmodule); - if (m == NULL) - return NULL; - about = PyUnicode_DecodeUTF8(__about__, strlen(__about__), NULL); - PyModule_AddObject(m, "__about__", about); - return m; + m = PyModule_Create(&_heapqmodule); + if (m == NULL) + return NULL; + about = PyUnicode_DecodeUTF8(__about__, strlen(__about__), NULL); + PyModule_AddObject(m, "__about__", about); + return m; } Modified: python/branches/release31-maint/Modules/_json.c ============================================================================== --- python/branches/release31-maint/Modules/_json.c (original) +++ python/branches/release31-maint/Modules/_json.c Sun May 9 18:14:21 2010 @@ -511,7 +511,7 @@ rval = scanstring_unicode(pystr, end, strict, &next_end); } else { - PyErr_Format(PyExc_TypeError, + PyErr_Format(PyExc_TypeError, "first argument must be a string or bytes, not %.80s", Py_TYPE(pystr)->tp_name); return NULL; @@ -1394,7 +1394,7 @@ if (PyObject_IsTrue(s->sort_keys)) { if (code == NULL) { - code = Py_CompileString("sorted(d.items(), key=lambda kv: kv[0])", + code = Py_CompileString("sorted(d.items(), key=lambda kv: kv[0])", "_json.c", Py_eval_input); if (code == NULL) goto bail; @@ -1409,14 +1409,14 @@ } items = PyEval_EvalCode((PyCodeObject *)code, PyEval_GetGlobals(), mapping); Py_DECREF(mapping); - } else { + } else { items = PyMapping_Items(dct); - } - if (items == NULL) + } + if (items == NULL) goto bail; it = PyObject_GetIter(items); - Py_DECREF(items); - if (it == NULL) + Py_DECREF(items); + if (it == NULL) goto bail; skipkeys = PyObject_IsTrue(s->skipkeys); idx = 0; @@ -1437,8 +1437,8 @@ goto bail; } else if (key == Py_True || key == Py_False || key == Py_None) { - /* This must come before the PyLong_Check because - True and False are also 1 and 0.*/ + /* This must come before the PyLong_Check because + True and False are also 1 and 0.*/ kstr = _encoded_const(key); if (kstr == NULL) goto bail; @@ -1704,15 +1704,15 @@ "json speedups\n"); static struct PyModuleDef jsonmodule = { - PyModuleDef_HEAD_INIT, - "_json", - module_doc, - -1, - speedups_methods, - NULL, - NULL, - NULL, - NULL + PyModuleDef_HEAD_INIT, + "_json", + module_doc, + -1, + speedups_methods, + NULL, + NULL, + NULL, + NULL }; PyObject* Modified: python/branches/release31-maint/Modules/_localemodule.c ============================================================================== --- python/branches/release31-maint/Modules/_localemodule.c (original) +++ python/branches/release31-maint/Modules/_localemodule.c Sun May 9 18:14:21 2010 @@ -77,7 +77,7 @@ if (dest != smallbuf) PyMem_Free(dest); return res2; -} +} /* support functions for formatting floating point numbers */ @@ -243,7 +243,7 @@ PyObject *os1, *os2, *result = NULL; wchar_t *ws1 = NULL, *ws2 = NULL; Py_ssize_t len1, len2; - + if (!PyArg_ParseTuple(args, "UU:strcoll", &os1, &os2)) return NULL; /* Convert the unicode strings to wchar[]. */ @@ -373,9 +373,9 @@ #ifdef HAVE_LANGINFO_H #define LANGINFO(X) {#X, X} static struct langinfo_constant{ - char* name; - int value; -} langinfo_constants[] = + char* name; + int value; +} langinfo_constants[] = { /* These constants should exist on any langinfo implementation */ LANGINFO(DAY_1), @@ -514,10 +514,10 @@ static PyObject* PyIntl_gettext(PyObject* self, PyObject *args) { - char *in; - if (!PyArg_ParseTuple(args, "s", &in)) - return 0; - return str2uni(gettext(in)); + char *in; + if (!PyArg_ParseTuple(args, "s", &in)) + return 0; + return str2uni(gettext(in)); } PyDoc_STRVAR(dgettext__doc__, @@ -527,10 +527,10 @@ static PyObject* PyIntl_dgettext(PyObject* self, PyObject *args) { - char *domain, *in; - if (!PyArg_ParseTuple(args, "zs", &domain, &in)) - return 0; - return str2uni(dgettext(domain, in)); + char *domain, *in; + if (!PyArg_ParseTuple(args, "zs", &domain, &in)) + return 0; + return str2uni(dgettext(domain, in)); } PyDoc_STRVAR(dcgettext__doc__, @@ -540,11 +540,11 @@ static PyObject* PyIntl_dcgettext(PyObject *self, PyObject *args) { - char *domain, *msgid; - int category; - if (!PyArg_ParseTuple(args, "zsi", &domain, &msgid, &category)) - return 0; - return str2uni(dcgettext(domain,msgid,category)); + char *domain, *msgid; + int category; + if (!PyArg_ParseTuple(args, "zsi", &domain, &msgid, &category)) + return 0; + return str2uni(dcgettext(domain,msgid,category)); } PyDoc_STRVAR(textdomain__doc__, @@ -554,15 +554,15 @@ static PyObject* PyIntl_textdomain(PyObject* self, PyObject* args) { - char *domain; - if (!PyArg_ParseTuple(args, "z", &domain)) - return 0; - domain = textdomain(domain); - if (!domain) { - PyErr_SetFromErrno(PyExc_OSError); - return NULL; - } - return str2uni(domain); + char *domain; + if (!PyArg_ParseTuple(args, "z", &domain)) + return 0; + domain = textdomain(domain); + if (!domain) { + PyErr_SetFromErrno(PyExc_OSError); + return NULL; + } + return str2uni(domain); } PyDoc_STRVAR(bindtextdomain__doc__, @@ -572,19 +572,19 @@ static PyObject* PyIntl_bindtextdomain(PyObject* self,PyObject*args) { - char *domain, *dirname; - if (!PyArg_ParseTuple(args, "sz", &domain, &dirname)) - return 0; - if (!strlen(domain)) { - PyErr_SetString(Error, "domain must be a non-empty string"); - return 0; - } - dirname = bindtextdomain(domain, dirname); - if (!dirname) { - PyErr_SetFromErrno(PyExc_OSError); - return NULL; - } - return str2uni(dirname); + char *domain, *dirname; + if (!PyArg_ParseTuple(args, "sz", &domain, &dirname)) + return 0; + if (!strlen(domain)) { + PyErr_SetString(Error, "domain must be a non-empty string"); + return 0; + } + dirname = bindtextdomain(domain, dirname); + if (!dirname) { + PyErr_SetFromErrno(PyExc_OSError); + return NULL; + } + return str2uni(dirname); } #ifdef HAVE_BIND_TEXTDOMAIN_CODESET @@ -595,32 +595,32 @@ static PyObject* PyIntl_bind_textdomain_codeset(PyObject* self,PyObject*args) { - char *domain,*codeset; - if (!PyArg_ParseTuple(args, "sz", &domain, &codeset)) - return NULL; - codeset = bind_textdomain_codeset(domain, codeset); - if (codeset) - return str2uni(codeset); - Py_RETURN_NONE; + char *domain,*codeset; + if (!PyArg_ParseTuple(args, "sz", &domain, &codeset)) + return NULL; + codeset = bind_textdomain_codeset(domain, codeset); + if (codeset) + return str2uni(codeset); + Py_RETURN_NONE; } #endif #endif static struct PyMethodDef PyLocale_Methods[] = { - {"setlocale", (PyCFunction) PyLocale_setlocale, + {"setlocale", (PyCFunction) PyLocale_setlocale, METH_VARARGS, setlocale__doc__}, - {"localeconv", (PyCFunction) PyLocale_localeconv, + {"localeconv", (PyCFunction) PyLocale_localeconv, METH_NOARGS, localeconv__doc__}, #ifdef HAVE_WCSCOLL - {"strcoll", (PyCFunction) PyLocale_strcoll, + {"strcoll", (PyCFunction) PyLocale_strcoll, METH_VARARGS, strcoll__doc__}, #endif #ifdef HAVE_WCSXFRM - {"strxfrm", (PyCFunction) PyLocale_strxfrm, + {"strxfrm", (PyCFunction) PyLocale_strxfrm, METH_VARARGS, strxfrm__doc__}, #endif -#if defined(MS_WINDOWS) +#if defined(MS_WINDOWS) {"_getdefaultlocale", (PyCFunction) PyLocale_getdefaultlocale, METH_NOARGS}, #endif #ifdef HAVE_LANGINFO_H @@ -642,21 +642,21 @@ {"bind_textdomain_codeset",(PyCFunction)PyIntl_bind_textdomain_codeset, METH_VARARGS, bind_textdomain_codeset__doc__}, #endif -#endif +#endif {NULL, NULL} }; static struct PyModuleDef _localemodule = { - PyModuleDef_HEAD_INIT, - "_locale", - locale__doc__, - -1, - PyLocale_Methods, - NULL, - NULL, - NULL, - NULL + PyModuleDef_HEAD_INIT, + "_locale", + locale__doc__, + -1, + PyLocale_Methods, + NULL, + NULL, + NULL, + NULL }; PyMODINIT_FUNC @@ -669,7 +669,7 @@ m = PyModule_Create(&_localemodule); if (m == NULL) - return NULL; + return NULL; d = PyModule_GetDict(m); @@ -712,14 +712,14 @@ #ifdef HAVE_LANGINFO_H for (i = 0; langinfo_constants[i].name; i++) { - PyModule_AddIntConstant(m, langinfo_constants[i].name, - langinfo_constants[i].value); + PyModule_AddIntConstant(m, langinfo_constants[i].name, + langinfo_constants[i].value); } #endif return m; } -/* +/* Local variables: c-basic-offset: 4 indent-tabs-mode: nil Modified: python/branches/release31-maint/Modules/_lsprof.c ============================================================================== --- python/branches/release31-maint/Modules/_lsprof.c (original) +++ python/branches/release31-maint/Modules/_lsprof.c Sun May 9 18:14:21 2010 @@ -17,19 +17,19 @@ static PY_LONG_LONG hpTimer(void) { - LARGE_INTEGER li; - QueryPerformanceCounter(&li); - return li.QuadPart; + LARGE_INTEGER li; + QueryPerformanceCounter(&li); + return li.QuadPart; } static double hpTimerUnit(void) { - LARGE_INTEGER li; - if (QueryPerformanceFrequency(&li)) - return 1.0 / li.QuadPart; - else - return 0.000001; /* unlikely */ + LARGE_INTEGER li; + if (QueryPerformanceFrequency(&li)) + return 1.0 / li.QuadPart; + else + return 0.000001; /* unlikely */ } #else /* !MS_WINDOWS */ @@ -48,22 +48,22 @@ static PY_LONG_LONG hpTimer(void) { - struct timeval tv; - PY_LONG_LONG ret; + struct timeval tv; + PY_LONG_LONG ret; #ifdef GETTIMEOFDAY_NO_TZ - gettimeofday(&tv); + gettimeofday(&tv); #else - gettimeofday(&tv, (struct timezone *)NULL); + gettimeofday(&tv, (struct timezone *)NULL); #endif - ret = tv.tv_sec; - ret = ret * 1000000 + tv.tv_usec; - return ret; + ret = tv.tv_sec; + ret = ret * 1000000 + tv.tv_usec; + return ret; } static double hpTimerUnit(void) { - return 0.000001; + return 0.000001; } #endif /* MS_WINDOWS */ @@ -75,41 +75,41 @@ /* represents a function called from another function */ typedef struct _ProfilerSubEntry { - rotating_node_t header; - PY_LONG_LONG tt; - PY_LONG_LONG it; - long callcount; - long recursivecallcount; - long recursionLevel; + rotating_node_t header; + PY_LONG_LONG tt; + PY_LONG_LONG it; + long callcount; + long recursivecallcount; + long recursionLevel; } ProfilerSubEntry; /* represents a function or user defined block */ typedef struct _ProfilerEntry { - rotating_node_t header; - PyObject *userObj; /* PyCodeObject, or a descriptive str for builtins */ - PY_LONG_LONG tt; /* total time in this entry */ - PY_LONG_LONG it; /* inline time in this entry (not in subcalls) */ - long callcount; /* how many times this was called */ - long recursivecallcount; /* how many times called recursively */ - long recursionLevel; - rotating_node_t *calls; + rotating_node_t header; + PyObject *userObj; /* PyCodeObject, or a descriptive str for builtins */ + PY_LONG_LONG tt; /* total time in this entry */ + PY_LONG_LONG it; /* inline time in this entry (not in subcalls) */ + long callcount; /* how many times this was called */ + long recursivecallcount; /* how many times called recursively */ + long recursionLevel; + rotating_node_t *calls; } ProfilerEntry; typedef struct _ProfilerContext { - PY_LONG_LONG t0; - PY_LONG_LONG subt; - struct _ProfilerContext *previous; - ProfilerEntry *ctxEntry; + PY_LONG_LONG t0; + PY_LONG_LONG subt; + struct _ProfilerContext *previous; + ProfilerEntry *ctxEntry; } ProfilerContext; typedef struct { - PyObject_HEAD - rotating_node_t *profilerEntries; - ProfilerContext *currentProfilerContext; - ProfilerContext *freelistProfilerContext; - int flags; - PyObject *externalTimer; - double externalTimerUnit; + PyObject_HEAD + rotating_node_t *profilerEntries; + ProfilerContext *currentProfilerContext; + ProfilerContext *freelistProfilerContext; + int flags; + PyObject *externalTimer; + double externalTimerUnit; } ProfilerObject; #define POF_ENABLED 0x001 @@ -129,407 +129,407 @@ static PY_LONG_LONG CallExternalTimer(ProfilerObject *pObj) { - PY_LONG_LONG result; - PyObject *o = PyObject_Call(pObj->externalTimer, empty_tuple, NULL); - if (o == NULL) { - PyErr_WriteUnraisable(pObj->externalTimer); - return 0; - } - if (pObj->externalTimerUnit > 0.0) { - /* interpret the result as an integer that will be scaled - in profiler_getstats() */ - result = PyLong_AsLongLong(o); - } - else { - /* interpret the result as a double measured in seconds. - As the profiler works with PY_LONG_LONG internally - we convert it to a large integer */ - double val = PyFloat_AsDouble(o); - /* error handling delayed to the code below */ - result = (PY_LONG_LONG) (val * DOUBLE_TIMER_PRECISION); - } - Py_DECREF(o); - if (PyErr_Occurred()) { - PyErr_WriteUnraisable(pObj->externalTimer); - return 0; - } - return result; -} - -#define CALL_TIMER(pObj) ((pObj)->externalTimer ? \ - CallExternalTimer(pObj) : \ - hpTimer()) + PY_LONG_LONG result; + PyObject *o = PyObject_Call(pObj->externalTimer, empty_tuple, NULL); + if (o == NULL) { + PyErr_WriteUnraisable(pObj->externalTimer); + return 0; + } + if (pObj->externalTimerUnit > 0.0) { + /* interpret the result as an integer that will be scaled + in profiler_getstats() */ + result = PyLong_AsLongLong(o); + } + else { + /* interpret the result as a double measured in seconds. + As the profiler works with PY_LONG_LONG internally + we convert it to a large integer */ + double val = PyFloat_AsDouble(o); + /* error handling delayed to the code below */ + result = (PY_LONG_LONG) (val * DOUBLE_TIMER_PRECISION); + } + Py_DECREF(o); + if (PyErr_Occurred()) { + PyErr_WriteUnraisable(pObj->externalTimer); + return 0; + } + return result; +} + +#define CALL_TIMER(pObj) ((pObj)->externalTimer ? \ + CallExternalTimer(pObj) : \ + hpTimer()) /*** ProfilerObject ***/ static PyObject * normalizeUserObj(PyObject *obj) { - PyCFunctionObject *fn; - if (!PyCFunction_Check(obj)) { - Py_INCREF(obj); - return obj; - } - /* Replace built-in function objects with a descriptive string - because of built-in methods -- keeping a reference to - __self__ is probably not a good idea. */ - fn = (PyCFunctionObject *)obj; - - if (fn->m_self == NULL) { - /* built-in function: look up the module name */ - PyObject *mod = fn->m_module; - const char *modname; - if (mod && PyUnicode_Check(mod)) { - modname = _PyUnicode_AsString(mod); - } - else if (mod && PyModule_Check(mod)) { - modname = PyModule_GetName(mod); - if (modname == NULL) { - PyErr_Clear(); - modname = "builtins"; - } - } - else { - modname = "builtins"; - } - if (strcmp(modname, "builtins") != 0) - return PyUnicode_FromFormat("<%s.%s>", - modname, - fn->m_ml->ml_name); - else - return PyUnicode_FromFormat("<%s>", - fn->m_ml->ml_name); - } - else { - /* built-in method: try to return - repr(getattr(type(__self__), __name__)) - */ - PyObject *self = fn->m_self; - PyObject *name = PyUnicode_FromString(fn->m_ml->ml_name); - if (name != NULL) { - PyObject *mo = _PyType_Lookup(Py_TYPE(self), name); - Py_XINCREF(mo); - Py_DECREF(name); - if (mo != NULL) { - PyObject *res = PyObject_Repr(mo); - Py_DECREF(mo); - if (res != NULL) - return res; - } - } - PyErr_Clear(); - return PyUnicode_FromFormat("", - fn->m_ml->ml_name); - } + PyCFunctionObject *fn; + if (!PyCFunction_Check(obj)) { + Py_INCREF(obj); + return obj; + } + /* Replace built-in function objects with a descriptive string + because of built-in methods -- keeping a reference to + __self__ is probably not a good idea. */ + fn = (PyCFunctionObject *)obj; + + if (fn->m_self == NULL) { + /* built-in function: look up the module name */ + PyObject *mod = fn->m_module; + const char *modname; + if (mod && PyUnicode_Check(mod)) { + modname = _PyUnicode_AsString(mod); + } + else if (mod && PyModule_Check(mod)) { + modname = PyModule_GetName(mod); + if (modname == NULL) { + PyErr_Clear(); + modname = "builtins"; + } + } + else { + modname = "builtins"; + } + if (strcmp(modname, "builtins") != 0) + return PyUnicode_FromFormat("<%s.%s>", + modname, + fn->m_ml->ml_name); + else + return PyUnicode_FromFormat("<%s>", + fn->m_ml->ml_name); + } + else { + /* built-in method: try to return + repr(getattr(type(__self__), __name__)) + */ + PyObject *self = fn->m_self; + PyObject *name = PyUnicode_FromString(fn->m_ml->ml_name); + if (name != NULL) { + PyObject *mo = _PyType_Lookup(Py_TYPE(self), name); + Py_XINCREF(mo); + Py_DECREF(name); + if (mo != NULL) { + PyObject *res = PyObject_Repr(mo); + Py_DECREF(mo); + if (res != NULL) + return res; + } + } + PyErr_Clear(); + return PyUnicode_FromFormat("", + fn->m_ml->ml_name); + } } static ProfilerEntry* newProfilerEntry(ProfilerObject *pObj, void *key, PyObject *userObj) { - ProfilerEntry *self; - self = (ProfilerEntry*) malloc(sizeof(ProfilerEntry)); - if (self == NULL) { - pObj->flags |= POF_NOMEMORY; - return NULL; - } - userObj = normalizeUserObj(userObj); - if (userObj == NULL) { - PyErr_Clear(); - free(self); - pObj->flags |= POF_NOMEMORY; - return NULL; - } - self->header.key = key; - self->userObj = userObj; - self->tt = 0; - self->it = 0; - self->callcount = 0; - self->recursivecallcount = 0; - self->recursionLevel = 0; - self->calls = EMPTY_ROTATING_TREE; - RotatingTree_Add(&pObj->profilerEntries, &self->header); - return self; + ProfilerEntry *self; + self = (ProfilerEntry*) malloc(sizeof(ProfilerEntry)); + if (self == NULL) { + pObj->flags |= POF_NOMEMORY; + return NULL; + } + userObj = normalizeUserObj(userObj); + if (userObj == NULL) { + PyErr_Clear(); + free(self); + pObj->flags |= POF_NOMEMORY; + return NULL; + } + self->header.key = key; + self->userObj = userObj; + self->tt = 0; + self->it = 0; + self->callcount = 0; + self->recursivecallcount = 0; + self->recursionLevel = 0; + self->calls = EMPTY_ROTATING_TREE; + RotatingTree_Add(&pObj->profilerEntries, &self->header); + return self; } static ProfilerEntry* getEntry(ProfilerObject *pObj, void *key) { - return (ProfilerEntry*) RotatingTree_Get(&pObj->profilerEntries, key); + return (ProfilerEntry*) RotatingTree_Get(&pObj->profilerEntries, key); } -static ProfilerSubEntry * +static ProfilerSubEntry * getSubEntry(ProfilerObject *pObj, ProfilerEntry *caller, ProfilerEntry* entry) { - return (ProfilerSubEntry*) RotatingTree_Get(&caller->calls, - (void *)entry); + return (ProfilerSubEntry*) RotatingTree_Get(&caller->calls, + (void *)entry); } static ProfilerSubEntry * newSubEntry(ProfilerObject *pObj, ProfilerEntry *caller, ProfilerEntry* entry) { - ProfilerSubEntry *self; - self = (ProfilerSubEntry*) malloc(sizeof(ProfilerSubEntry)); - if (self == NULL) { - pObj->flags |= POF_NOMEMORY; - return NULL; - } - self->header.key = (void *)entry; - self->tt = 0; - self->it = 0; - self->callcount = 0; - self->recursivecallcount = 0; - self->recursionLevel = 0; - RotatingTree_Add(&caller->calls, &self->header); - return self; + ProfilerSubEntry *self; + self = (ProfilerSubEntry*) malloc(sizeof(ProfilerSubEntry)); + if (self == NULL) { + pObj->flags |= POF_NOMEMORY; + return NULL; + } + self->header.key = (void *)entry; + self->tt = 0; + self->it = 0; + self->callcount = 0; + self->recursivecallcount = 0; + self->recursionLevel = 0; + RotatingTree_Add(&caller->calls, &self->header); + return self; } static int freeSubEntry(rotating_node_t *header, void *arg) { - ProfilerSubEntry *subentry = (ProfilerSubEntry*) header; - free(subentry); - return 0; + ProfilerSubEntry *subentry = (ProfilerSubEntry*) header; + free(subentry); + return 0; } static int freeEntry(rotating_node_t *header, void *arg) { - ProfilerEntry *entry = (ProfilerEntry*) header; - RotatingTree_Enum(entry->calls, freeSubEntry, NULL); - Py_DECREF(entry->userObj); - free(entry); - return 0; + ProfilerEntry *entry = (ProfilerEntry*) header; + RotatingTree_Enum(entry->calls, freeSubEntry, NULL); + Py_DECREF(entry->userObj); + free(entry); + return 0; } static void clearEntries(ProfilerObject *pObj) { - RotatingTree_Enum(pObj->profilerEntries, freeEntry, NULL); - pObj->profilerEntries = EMPTY_ROTATING_TREE; - /* release the memory hold by the ProfilerContexts */ - if (pObj->currentProfilerContext) { - free(pObj->currentProfilerContext); - pObj->currentProfilerContext = NULL; - } - while (pObj->freelistProfilerContext) { - ProfilerContext *c = pObj->freelistProfilerContext; - pObj->freelistProfilerContext = c->previous; - free(c); - } - pObj->freelistProfilerContext = NULL; + RotatingTree_Enum(pObj->profilerEntries, freeEntry, NULL); + pObj->profilerEntries = EMPTY_ROTATING_TREE; + /* release the memory hold by the ProfilerContexts */ + if (pObj->currentProfilerContext) { + free(pObj->currentProfilerContext); + pObj->currentProfilerContext = NULL; + } + while (pObj->freelistProfilerContext) { + ProfilerContext *c = pObj->freelistProfilerContext; + pObj->freelistProfilerContext = c->previous; + free(c); + } + pObj->freelistProfilerContext = NULL; } static void initContext(ProfilerObject *pObj, ProfilerContext *self, ProfilerEntry *entry) { - self->ctxEntry = entry; - self->subt = 0; - self->previous = pObj->currentProfilerContext; - pObj->currentProfilerContext = self; - ++entry->recursionLevel; - if ((pObj->flags & POF_SUBCALLS) && self->previous) { - /* find or create an entry for me in my caller's entry */ - ProfilerEntry *caller = self->previous->ctxEntry; - ProfilerSubEntry *subentry = getSubEntry(pObj, caller, entry); - if (subentry == NULL) - subentry = newSubEntry(pObj, caller, entry); - if (subentry) - ++subentry->recursionLevel; - } - self->t0 = CALL_TIMER(pObj); + self->ctxEntry = entry; + self->subt = 0; + self->previous = pObj->currentProfilerContext; + pObj->currentProfilerContext = self; + ++entry->recursionLevel; + if ((pObj->flags & POF_SUBCALLS) && self->previous) { + /* find or create an entry for me in my caller's entry */ + ProfilerEntry *caller = self->previous->ctxEntry; + ProfilerSubEntry *subentry = getSubEntry(pObj, caller, entry); + if (subentry == NULL) + subentry = newSubEntry(pObj, caller, entry); + if (subentry) + ++subentry->recursionLevel; + } + self->t0 = CALL_TIMER(pObj); } static void Stop(ProfilerObject *pObj, ProfilerContext *self, ProfilerEntry *entry) { - PY_LONG_LONG tt = CALL_TIMER(pObj) - self->t0; - PY_LONG_LONG it = tt - self->subt; - if (self->previous) - self->previous->subt += tt; - pObj->currentProfilerContext = self->previous; - if (--entry->recursionLevel == 0) - entry->tt += tt; - else - ++entry->recursivecallcount; - entry->it += it; - entry->callcount++; - if ((pObj->flags & POF_SUBCALLS) && self->previous) { - /* find or create an entry for me in my caller's entry */ - ProfilerEntry *caller = self->previous->ctxEntry; - ProfilerSubEntry *subentry = getSubEntry(pObj, caller, entry); - if (subentry) { - if (--subentry->recursionLevel == 0) - subentry->tt += tt; - else - ++subentry->recursivecallcount; - subentry->it += it; - ++subentry->callcount; - } - } + PY_LONG_LONG tt = CALL_TIMER(pObj) - self->t0; + PY_LONG_LONG it = tt - self->subt; + if (self->previous) + self->previous->subt += tt; + pObj->currentProfilerContext = self->previous; + if (--entry->recursionLevel == 0) + entry->tt += tt; + else + ++entry->recursivecallcount; + entry->it += it; + entry->callcount++; + if ((pObj->flags & POF_SUBCALLS) && self->previous) { + /* find or create an entry for me in my caller's entry */ + ProfilerEntry *caller = self->previous->ctxEntry; + ProfilerSubEntry *subentry = getSubEntry(pObj, caller, entry); + if (subentry) { + if (--subentry->recursionLevel == 0) + subentry->tt += tt; + else + ++subentry->recursivecallcount; + subentry->it += it; + ++subentry->callcount; + } + } } static void ptrace_enter_call(PyObject *self, void *key, PyObject *userObj) { - /* entering a call to the function identified by 'key' - (which can be a PyCodeObject or a PyMethodDef pointer) */ - ProfilerObject *pObj = (ProfilerObject*)self; - ProfilerEntry *profEntry; - ProfilerContext *pContext; - - /* In the case of entering a generator expression frame via a - * throw (gen_send_ex(.., 1)), we may already have an - * Exception set here. We must not mess around with this - * exception, and some of the code under here assumes that - * PyErr_* is its own to mess around with, so we have to - * save and restore any current exception. */ - PyObject *last_type, *last_value, *last_tb; - PyErr_Fetch(&last_type, &last_value, &last_tb); - - profEntry = getEntry(pObj, key); - if (profEntry == NULL) { - profEntry = newProfilerEntry(pObj, key, userObj); - if (profEntry == NULL) - goto restorePyerr; - } - /* grab a ProfilerContext out of the free list */ - pContext = pObj->freelistProfilerContext; - if (pContext) { - pObj->freelistProfilerContext = pContext->previous; - } - else { - /* free list exhausted, allocate a new one */ - pContext = (ProfilerContext*) - malloc(sizeof(ProfilerContext)); - if (pContext == NULL) { - pObj->flags |= POF_NOMEMORY; - goto restorePyerr; - } - } - initContext(pObj, pContext, profEntry); + /* entering a call to the function identified by 'key' + (which can be a PyCodeObject or a PyMethodDef pointer) */ + ProfilerObject *pObj = (ProfilerObject*)self; + ProfilerEntry *profEntry; + ProfilerContext *pContext; + + /* In the case of entering a generator expression frame via a + * throw (gen_send_ex(.., 1)), we may already have an + * Exception set here. We must not mess around with this + * exception, and some of the code under here assumes that + * PyErr_* is its own to mess around with, so we have to + * save and restore any current exception. */ + PyObject *last_type, *last_value, *last_tb; + PyErr_Fetch(&last_type, &last_value, &last_tb); + + profEntry = getEntry(pObj, key); + if (profEntry == NULL) { + profEntry = newProfilerEntry(pObj, key, userObj); + if (profEntry == NULL) + goto restorePyerr; + } + /* grab a ProfilerContext out of the free list */ + pContext = pObj->freelistProfilerContext; + if (pContext) { + pObj->freelistProfilerContext = pContext->previous; + } + else { + /* free list exhausted, allocate a new one */ + pContext = (ProfilerContext*) + malloc(sizeof(ProfilerContext)); + if (pContext == NULL) { + pObj->flags |= POF_NOMEMORY; + goto restorePyerr; + } + } + initContext(pObj, pContext, profEntry); restorePyerr: - PyErr_Restore(last_type, last_value, last_tb); + PyErr_Restore(last_type, last_value, last_tb); } static void ptrace_leave_call(PyObject *self, void *key) { - /* leaving a call to the function identified by 'key' */ - ProfilerObject *pObj = (ProfilerObject*)self; - ProfilerEntry *profEntry; - ProfilerContext *pContext; - - pContext = pObj->currentProfilerContext; - if (pContext == NULL) - return; - profEntry = getEntry(pObj, key); - if (profEntry) { - Stop(pObj, pContext, profEntry); - } - else { - pObj->currentProfilerContext = pContext->previous; - } - /* put pContext into the free list */ - pContext->previous = pObj->freelistProfilerContext; - pObj->freelistProfilerContext = pContext; + /* leaving a call to the function identified by 'key' */ + ProfilerObject *pObj = (ProfilerObject*)self; + ProfilerEntry *profEntry; + ProfilerContext *pContext; + + pContext = pObj->currentProfilerContext; + if (pContext == NULL) + return; + profEntry = getEntry(pObj, key); + if (profEntry) { + Stop(pObj, pContext, profEntry); + } + else { + pObj->currentProfilerContext = pContext->previous; + } + /* put pContext into the free list */ + pContext->previous = pObj->freelistProfilerContext; + pObj->freelistProfilerContext = pContext; } static int profiler_callback(PyObject *self, PyFrameObject *frame, int what, - PyObject *arg) + PyObject *arg) { - switch (what) { + switch (what) { - /* the 'frame' of a called function is about to start its execution */ - case PyTrace_CALL: - ptrace_enter_call(self, (void *)frame->f_code, - (PyObject *)frame->f_code); - break; - - /* the 'frame' of a called function is about to finish - (either normally or with an exception) */ - case PyTrace_RETURN: - ptrace_leave_call(self, (void *)frame->f_code); - break; - - /* case PyTrace_EXCEPTION: - If the exception results in the function exiting, a - PyTrace_RETURN event will be generated, so we don't need to - handle it. */ - -#ifdef PyTrace_C_CALL /* not defined in Python <= 2.3 */ - /* the Python function 'frame' is issuing a call to the built-in - function 'arg' */ - case PyTrace_C_CALL: - if ((((ProfilerObject *)self)->flags & POF_BUILTINS) - && PyCFunction_Check(arg)) { - ptrace_enter_call(self, - ((PyCFunctionObject *)arg)->m_ml, - arg); - } - break; - - /* the call to the built-in function 'arg' is returning into its - caller 'frame' */ - case PyTrace_C_RETURN: /* ...normally */ - case PyTrace_C_EXCEPTION: /* ...with an exception set */ - if ((((ProfilerObject *)self)->flags & POF_BUILTINS) - && PyCFunction_Check(arg)) { - ptrace_leave_call(self, - ((PyCFunctionObject *)arg)->m_ml); - } - break; + /* the 'frame' of a called function is about to start its execution */ + case PyTrace_CALL: + ptrace_enter_call(self, (void *)frame->f_code, + (PyObject *)frame->f_code); + break; + + /* the 'frame' of a called function is about to finish + (either normally or with an exception) */ + case PyTrace_RETURN: + ptrace_leave_call(self, (void *)frame->f_code); + break; + + /* case PyTrace_EXCEPTION: + If the exception results in the function exiting, a + PyTrace_RETURN event will be generated, so we don't need to + handle it. */ + +#ifdef PyTrace_C_CALL /* not defined in Python <= 2.3 */ + /* the Python function 'frame' is issuing a call to the built-in + function 'arg' */ + case PyTrace_C_CALL: + if ((((ProfilerObject *)self)->flags & POF_BUILTINS) + && PyCFunction_Check(arg)) { + ptrace_enter_call(self, + ((PyCFunctionObject *)arg)->m_ml, + arg); + } + break; + + /* the call to the built-in function 'arg' is returning into its + caller 'frame' */ + case PyTrace_C_RETURN: /* ...normally */ + case PyTrace_C_EXCEPTION: /* ...with an exception set */ + if ((((ProfilerObject *)self)->flags & POF_BUILTINS) + && PyCFunction_Check(arg)) { + ptrace_leave_call(self, + ((PyCFunctionObject *)arg)->m_ml); + } + break; #endif - default: - break; - } - return 0; + default: + break; + } + return 0; } static int pending_exception(ProfilerObject *pObj) { - if (pObj->flags & POF_NOMEMORY) { - pObj->flags -= POF_NOMEMORY; - PyErr_SetString(PyExc_MemoryError, - "memory was exhausted while profiling"); - return -1; - } - return 0; + if (pObj->flags & POF_NOMEMORY) { + pObj->flags -= POF_NOMEMORY; + PyErr_SetString(PyExc_MemoryError, + "memory was exhausted while profiling"); + return -1; + } + return 0; } /************************************************************/ static PyStructSequence_Field profiler_entry_fields[] = { - {"code", "code object or built-in function name"}, - {"callcount", "how many times this was called"}, - {"reccallcount", "how many times called recursively"}, - {"totaltime", "total time in this entry"}, - {"inlinetime", "inline time in this entry (not in subcalls)"}, - {"calls", "details of the calls"}, - {0} + {"code", "code object or built-in function name"}, + {"callcount", "how many times this was called"}, + {"reccallcount", "how many times called recursively"}, + {"totaltime", "total time in this entry"}, + {"inlinetime", "inline time in this entry (not in subcalls)"}, + {"calls", "details of the calls"}, + {0} }; static PyStructSequence_Field profiler_subentry_fields[] = { - {"code", "called code object or built-in function name"}, - {"callcount", "how many times this is called"}, - {"reccallcount", "how many times this is called recursively"}, - {"totaltime", "total time spent in this call"}, - {"inlinetime", "inline time (not in further subcalls)"}, - {0} + {"code", "called code object or built-in function name"}, + {"callcount", "how many times this is called"}, + {"reccallcount", "how many times this is called recursively"}, + {"totaltime", "total time spent in this call"}, + {"inlinetime", "inline time (not in further subcalls)"}, + {0} }; static PyStructSequence_Desc profiler_entry_desc = { - "_lsprof.profiler_entry", /* name */ - NULL, /* doc */ - profiler_entry_fields, - 6 + "_lsprof.profiler_entry", /* name */ + NULL, /* doc */ + profiler_entry_fields, + 6 }; static PyStructSequence_Desc profiler_subentry_desc = { - "_lsprof.profiler_subentry", /* name */ - NULL, /* doc */ - profiler_subentry_fields, - 5 + "_lsprof.profiler_subentry", /* name */ + NULL, /* doc */ + profiler_subentry_fields, + 5 }; static int initialized; @@ -538,70 +538,70 @@ typedef struct { - PyObject *list; - PyObject *sublist; - double factor; + PyObject *list; + PyObject *sublist; + double factor; } statscollector_t; static int statsForSubEntry(rotating_node_t *node, void *arg) { - ProfilerSubEntry *sentry = (ProfilerSubEntry*) node; - statscollector_t *collect = (statscollector_t*) arg; - ProfilerEntry *entry = (ProfilerEntry*) sentry->header.key; - int err; - PyObject *sinfo; - sinfo = PyObject_CallFunction((PyObject*) &StatsSubEntryType, - "((Olldd))", - entry->userObj, - sentry->callcount, - sentry->recursivecallcount, - collect->factor * sentry->tt, - collect->factor * sentry->it); - if (sinfo == NULL) - return -1; - err = PyList_Append(collect->sublist, sinfo); - Py_DECREF(sinfo); - return err; + ProfilerSubEntry *sentry = (ProfilerSubEntry*) node; + statscollector_t *collect = (statscollector_t*) arg; + ProfilerEntry *entry = (ProfilerEntry*) sentry->header.key; + int err; + PyObject *sinfo; + sinfo = PyObject_CallFunction((PyObject*) &StatsSubEntryType, + "((Olldd))", + entry->userObj, + sentry->callcount, + sentry->recursivecallcount, + collect->factor * sentry->tt, + collect->factor * sentry->it); + if (sinfo == NULL) + return -1; + err = PyList_Append(collect->sublist, sinfo); + Py_DECREF(sinfo); + return err; } static int statsForEntry(rotating_node_t *node, void *arg) { - ProfilerEntry *entry = (ProfilerEntry*) node; - statscollector_t *collect = (statscollector_t*) arg; - PyObject *info; - int err; - if (entry->callcount == 0) - return 0; /* skip */ - - if (entry->calls != EMPTY_ROTATING_TREE) { - collect->sublist = PyList_New(0); - if (collect->sublist == NULL) - return -1; - if (RotatingTree_Enum(entry->calls, - statsForSubEntry, collect) != 0) { - Py_DECREF(collect->sublist); - return -1; - } - } - else { - Py_INCREF(Py_None); - collect->sublist = Py_None; - } - - info = PyObject_CallFunction((PyObject*) &StatsEntryType, - "((OllddO))", - entry->userObj, - entry->callcount, - entry->recursivecallcount, - collect->factor * entry->tt, - collect->factor * entry->it, - collect->sublist); - Py_DECREF(collect->sublist); - if (info == NULL) - return -1; - err = PyList_Append(collect->list, info); - Py_DECREF(info); - return err; + ProfilerEntry *entry = (ProfilerEntry*) node; + statscollector_t *collect = (statscollector_t*) arg; + PyObject *info; + int err; + if (entry->callcount == 0) + return 0; /* skip */ + + if (entry->calls != EMPTY_ROTATING_TREE) { + collect->sublist = PyList_New(0); + if (collect->sublist == NULL) + return -1; + if (RotatingTree_Enum(entry->calls, + statsForSubEntry, collect) != 0) { + Py_DECREF(collect->sublist); + return -1; + } + } + else { + Py_INCREF(Py_None); + collect->sublist = Py_None; + } + + info = PyObject_CallFunction((PyObject*) &StatsEntryType, + "((OllddO))", + entry->userObj, + entry->callcount, + entry->recursivecallcount, + collect->factor * entry->tt, + collect->factor * entry->it, + collect->sublist); + Py_DECREF(collect->sublist); + if (info == NULL) + return -1; + err = PyList_Append(collect->list, info); + Py_DECREF(info); + return err; } PyDoc_STRVAR(getstats_doc, "\ @@ -631,51 +631,51 @@ static PyObject* profiler_getstats(ProfilerObject *pObj, PyObject* noarg) { - statscollector_t collect; - if (pending_exception(pObj)) - return NULL; - if (!pObj->externalTimer) - collect.factor = hpTimerUnit(); - else if (pObj->externalTimerUnit > 0.0) - collect.factor = pObj->externalTimerUnit; - else - collect.factor = 1.0 / DOUBLE_TIMER_PRECISION; - collect.list = PyList_New(0); - if (collect.list == NULL) - return NULL; - if (RotatingTree_Enum(pObj->profilerEntries, statsForEntry, &collect) - != 0) { - Py_DECREF(collect.list); - return NULL; - } - return collect.list; + statscollector_t collect; + if (pending_exception(pObj)) + return NULL; + if (!pObj->externalTimer) + collect.factor = hpTimerUnit(); + else if (pObj->externalTimerUnit > 0.0) + collect.factor = pObj->externalTimerUnit; + else + collect.factor = 1.0 / DOUBLE_TIMER_PRECISION; + collect.list = PyList_New(0); + if (collect.list == NULL) + return NULL; + if (RotatingTree_Enum(pObj->profilerEntries, statsForEntry, &collect) + != 0) { + Py_DECREF(collect.list); + return NULL; + } + return collect.list; } static int setSubcalls(ProfilerObject *pObj, int nvalue) { - if (nvalue == 0) - pObj->flags &= ~POF_SUBCALLS; - else if (nvalue > 0) - pObj->flags |= POF_SUBCALLS; - return 0; + if (nvalue == 0) + pObj->flags &= ~POF_SUBCALLS; + else if (nvalue > 0) + pObj->flags |= POF_SUBCALLS; + return 0; } static int setBuiltins(ProfilerObject *pObj, int nvalue) { - if (nvalue == 0) - pObj->flags &= ~POF_BUILTINS; - else if (nvalue > 0) { + if (nvalue == 0) + pObj->flags &= ~POF_BUILTINS; + else if (nvalue > 0) { #ifndef PyTrace_C_CALL - PyErr_SetString(PyExc_ValueError, - "builtins=True requires Python >= 2.4"); - return -1; + PyErr_SetString(PyExc_ValueError, + "builtins=True requires Python >= 2.4"); + return -1; #else - pObj->flags |= POF_BUILTINS; + pObj->flags |= POF_BUILTINS; #endif - } - return 0; + } + return 0; } PyDoc_STRVAR(enable_doc, "\ @@ -691,33 +691,33 @@ static PyObject* profiler_enable(ProfilerObject *self, PyObject *args, PyObject *kwds) { - int subcalls = -1; - int builtins = -1; - static char *kwlist[] = {"subcalls", "builtins", 0}; - if (!PyArg_ParseTupleAndKeywords(args, kwds, "|ii:enable", - kwlist, &subcalls, &builtins)) - return NULL; - if (setSubcalls(self, subcalls) < 0 || setBuiltins(self, builtins) < 0) - return NULL; - PyEval_SetProfile(profiler_callback, (PyObject*)self); - self->flags |= POF_ENABLED; - Py_INCREF(Py_None); - return Py_None; + int subcalls = -1; + int builtins = -1; + static char *kwlist[] = {"subcalls", "builtins", 0}; + if (!PyArg_ParseTupleAndKeywords(args, kwds, "|ii:enable", + kwlist, &subcalls, &builtins)) + return NULL; + if (setSubcalls(self, subcalls) < 0 || setBuiltins(self, builtins) < 0) + return NULL; + PyEval_SetProfile(profiler_callback, (PyObject*)self); + self->flags |= POF_ENABLED; + Py_INCREF(Py_None); + return Py_None; } static void flush_unmatched(ProfilerObject *pObj) { - while (pObj->currentProfilerContext) { - ProfilerContext *pContext = pObj->currentProfilerContext; - ProfilerEntry *profEntry= pContext->ctxEntry; - if (profEntry) - Stop(pObj, pContext, profEntry); - else - pObj->currentProfilerContext = pContext->previous; - if (pContext) - free(pContext); - } + while (pObj->currentProfilerContext) { + ProfilerContext *pContext = pObj->currentProfilerContext; + ProfilerEntry *profEntry= pContext->ctxEntry; + if (profEntry) + Stop(pObj, pContext, profEntry); + else + pObj->currentProfilerContext = pContext->previous; + if (pContext) + free(pContext); + } } @@ -730,13 +730,13 @@ static PyObject* profiler_disable(ProfilerObject *self, PyObject* noarg) { - self->flags &= ~POF_ENABLED; - PyEval_SetProfile(NULL, NULL); - flush_unmatched(self); - if (pending_exception(self)) - return NULL; - Py_INCREF(Py_None); - return Py_None; + self->flags &= ~POF_ENABLED; + PyEval_SetProfile(NULL, NULL); + flush_unmatched(self); + if (pending_exception(self)) + return NULL; + Py_INCREF(Py_None); + return Py_None; } PyDoc_STRVAR(clear_doc, "\ @@ -748,62 +748,62 @@ static PyObject* profiler_clear(ProfilerObject *pObj, PyObject* noarg) { - clearEntries(pObj); - Py_INCREF(Py_None); - return Py_None; + clearEntries(pObj); + Py_INCREF(Py_None); + return Py_None; } static void profiler_dealloc(ProfilerObject *op) { - if (op->flags & POF_ENABLED) - PyEval_SetProfile(NULL, NULL); - flush_unmatched(op); - clearEntries(op); - Py_XDECREF(op->externalTimer); - Py_TYPE(op)->tp_free(op); + if (op->flags & POF_ENABLED) + PyEval_SetProfile(NULL, NULL); + flush_unmatched(op); + clearEntries(op); + Py_XDECREF(op->externalTimer); + Py_TYPE(op)->tp_free(op); } static int profiler_init(ProfilerObject *pObj, PyObject *args, PyObject *kw) { - PyObject *o; - PyObject *timer = NULL; - double timeunit = 0.0; - int subcalls = 1; + PyObject *o; + PyObject *timer = NULL; + double timeunit = 0.0; + int subcalls = 1; #ifdef PyTrace_C_CALL - int builtins = 1; + int builtins = 1; #else - int builtins = 0; + int builtins = 0; #endif - static char *kwlist[] = {"timer", "timeunit", - "subcalls", "builtins", 0}; + static char *kwlist[] = {"timer", "timeunit", + "subcalls", "builtins", 0}; - if (!PyArg_ParseTupleAndKeywords(args, kw, "|Odii:Profiler", kwlist, - &timer, &timeunit, - &subcalls, &builtins)) - return -1; - - if (setSubcalls(pObj, subcalls) < 0 || setBuiltins(pObj, builtins) < 0) - return -1; - o = pObj->externalTimer; - pObj->externalTimer = timer; - Py_XINCREF(timer); - Py_XDECREF(o); - pObj->externalTimerUnit = timeunit; - return 0; + if (!PyArg_ParseTupleAndKeywords(args, kw, "|Odii:Profiler", kwlist, + &timer, &timeunit, + &subcalls, &builtins)) + return -1; + + if (setSubcalls(pObj, subcalls) < 0 || setBuiltins(pObj, builtins) < 0) + return -1; + o = pObj->externalTimer; + pObj->externalTimer = timer; + Py_XINCREF(timer); + Py_XDECREF(o); + pObj->externalTimerUnit = timeunit; + return 0; } static PyMethodDef profiler_methods[] = { - {"getstats", (PyCFunction)profiler_getstats, - METH_NOARGS, getstats_doc}, - {"enable", (PyCFunction)profiler_enable, - METH_VARARGS | METH_KEYWORDS, enable_doc}, - {"disable", (PyCFunction)profiler_disable, - METH_NOARGS, disable_doc}, - {"clear", (PyCFunction)profiler_clear, - METH_NOARGS, clear_doc}, - {NULL, NULL} + {"getstats", (PyCFunction)profiler_getstats, + METH_NOARGS, getstats_doc}, + {"enable", (PyCFunction)profiler_enable, + METH_VARARGS | METH_KEYWORDS, enable_doc}, + {"disable", (PyCFunction)profiler_disable, + METH_NOARGS, disable_doc}, + {"clear", (PyCFunction)profiler_clear, + METH_NOARGS, clear_doc}, + {NULL, NULL} }; PyDoc_STRVAR(profiler_doc, "\ @@ -817,89 +817,89 @@ "); static PyTypeObject PyProfiler_Type = { - PyVarObject_HEAD_INIT(NULL, 0) - "_lsprof.Profiler", /* tp_name */ - sizeof(ProfilerObject), /* tp_basicsize */ - 0, /* tp_itemsize */ - (destructor)profiler_dealloc, /* tp_dealloc */ - 0, /* tp_print */ - 0, /* tp_getattr */ - 0, /* tp_setattr */ - 0, /* tp_reserved */ - 0, /* tp_repr */ - 0, /* tp_as_number */ - 0, /* tp_as_sequence */ - 0, /* tp_as_mapping */ - 0, /* tp_hash */ - 0, /* tp_call */ - 0, /* tp_str */ - 0, /* tp_getattro */ - 0, /* tp_setattro */ - 0, /* tp_as_buffer */ - Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */ - profiler_doc, /* tp_doc */ - 0, /* tp_traverse */ - 0, /* tp_clear */ - 0, /* tp_richcompare */ - 0, /* tp_weaklistoffset */ - 0, /* tp_iter */ - 0, /* tp_iternext */ - profiler_methods, /* tp_methods */ - 0, /* tp_members */ - 0, /* tp_getset */ - 0, /* tp_base */ - 0, /* tp_dict */ - 0, /* tp_descr_get */ - 0, /* tp_descr_set */ - 0, /* tp_dictoffset */ - (initproc)profiler_init, /* tp_init */ - PyType_GenericAlloc, /* tp_alloc */ - PyType_GenericNew, /* tp_new */ - PyObject_Del, /* tp_free */ + PyVarObject_HEAD_INIT(NULL, 0) + "_lsprof.Profiler", /* tp_name */ + sizeof(ProfilerObject), /* tp_basicsize */ + 0, /* tp_itemsize */ + (destructor)profiler_dealloc, /* tp_dealloc */ + 0, /* tp_print */ + 0, /* tp_getattr */ + 0, /* tp_setattr */ + 0, /* tp_reserved */ + 0, /* tp_repr */ + 0, /* tp_as_number */ + 0, /* tp_as_sequence */ + 0, /* tp_as_mapping */ + 0, /* tp_hash */ + 0, /* tp_call */ + 0, /* tp_str */ + 0, /* tp_getattro */ + 0, /* tp_setattro */ + 0, /* tp_as_buffer */ + Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */ + profiler_doc, /* tp_doc */ + 0, /* tp_traverse */ + 0, /* tp_clear */ + 0, /* tp_richcompare */ + 0, /* tp_weaklistoffset */ + 0, /* tp_iter */ + 0, /* tp_iternext */ + profiler_methods, /* tp_methods */ + 0, /* tp_members */ + 0, /* tp_getset */ + 0, /* tp_base */ + 0, /* tp_dict */ + 0, /* tp_descr_get */ + 0, /* tp_descr_set */ + 0, /* tp_dictoffset */ + (initproc)profiler_init, /* tp_init */ + PyType_GenericAlloc, /* tp_alloc */ + PyType_GenericNew, /* tp_new */ + PyObject_Del, /* tp_free */ }; static PyMethodDef moduleMethods[] = { - {NULL, NULL} + {NULL, NULL} }; static struct PyModuleDef _lsprofmodule = { - PyModuleDef_HEAD_INIT, - "_lsprof", - "Fast profiler", - -1, - moduleMethods, - NULL, - NULL, - NULL, - NULL + PyModuleDef_HEAD_INIT, + "_lsprof", + "Fast profiler", + -1, + moduleMethods, + NULL, + NULL, + NULL, + NULL }; PyMODINIT_FUNC PyInit__lsprof(void) { - PyObject *module, *d; - module = PyModule_Create(&_lsprofmodule); - if (module == NULL) - return NULL; - d = PyModule_GetDict(module); - if (PyType_Ready(&PyProfiler_Type) < 0) - return NULL; - PyDict_SetItemString(d, "Profiler", (PyObject *)&PyProfiler_Type); - - if (!initialized) { - PyStructSequence_InitType(&StatsEntryType, - &profiler_entry_desc); - PyStructSequence_InitType(&StatsSubEntryType, - &profiler_subentry_desc); - } - Py_INCREF((PyObject*) &StatsEntryType); - Py_INCREF((PyObject*) &StatsSubEntryType); - PyModule_AddObject(module, "profiler_entry", - (PyObject*) &StatsEntryType); - PyModule_AddObject(module, "profiler_subentry", - (PyObject*) &StatsSubEntryType); - empty_tuple = PyTuple_New(0); - initialized = 1; - return module; + PyObject *module, *d; + module = PyModule_Create(&_lsprofmodule); + if (module == NULL) + return NULL; + d = PyModule_GetDict(module); + if (PyType_Ready(&PyProfiler_Type) < 0) + return NULL; + PyDict_SetItemString(d, "Profiler", (PyObject *)&PyProfiler_Type); + + if (!initialized) { + PyStructSequence_InitType(&StatsEntryType, + &profiler_entry_desc); + PyStructSequence_InitType(&StatsSubEntryType, + &profiler_subentry_desc); + } + Py_INCREF((PyObject*) &StatsEntryType); + Py_INCREF((PyObject*) &StatsSubEntryType); + PyModule_AddObject(module, "profiler_entry", + (PyObject*) &StatsEntryType); + PyModule_AddObject(module, "profiler_subentry", + (PyObject*) &StatsSubEntryType); + empty_tuple = PyTuple_New(0); + initialized = 1; + return module; } Modified: python/branches/release31-maint/Modules/_multiprocessing/connection.h ============================================================================== --- python/branches/release31-maint/Modules/_multiprocessing/connection.h (original) +++ python/branches/release31-maint/Modules/_multiprocessing/connection.h Sun May 9 18:14:21 2010 @@ -1,5 +1,5 @@ /* - * Definition of a `Connection` type. + * Definition of a `Connection` type. * Used by `socket_connection.c` and `pipe_connection.c`. * * connection.h @@ -19,14 +19,14 @@ #define CHECK_READABLE(self) \ if (!(self->flags & READABLE)) { \ - PyErr_SetString(PyExc_IOError, "connection is write-only"); \ - return NULL; \ + PyErr_SetString(PyExc_IOError, "connection is write-only"); \ + return NULL; \ } #define CHECK_WRITABLE(self) \ if (!(self->flags & WRITABLE)) { \ - PyErr_SetString(PyExc_IOError, "connection is read-only"); \ - return NULL; \ + PyErr_SetString(PyExc_IOError, "connection is read-only"); \ + return NULL; \ } /* @@ -36,57 +36,57 @@ static PyObject * connection_new(PyTypeObject *type, PyObject *args, PyObject *kwds) { - ConnectionObject *self; - HANDLE handle; - BOOL readable = TRUE, writable = TRUE; - - static char *kwlist[] = {"handle", "readable", "writable", NULL}; - - if (!PyArg_ParseTupleAndKeywords(args, kwds, F_HANDLE "|ii", kwlist, - &handle, &readable, &writable)) - return NULL; - - if (handle == INVALID_HANDLE_VALUE || (Py_ssize_t)handle < 0) { - PyErr_Format(PyExc_IOError, "invalid handle %zd", - (Py_ssize_t)handle); - return NULL; - } - - if (!readable && !writable) { - PyErr_SetString(PyExc_ValueError, - "either readable or writable must be true"); - return NULL; - } - - self = PyObject_New(ConnectionObject, type); - if (self == NULL) - return NULL; - - self->weakreflist = NULL; - self->handle = handle; - self->flags = 0; - - if (readable) - self->flags |= READABLE; - if (writable) - self->flags |= WRITABLE; - assert(self->flags >= 1 && self->flags <= 3); + ConnectionObject *self; + HANDLE handle; + BOOL readable = TRUE, writable = TRUE; + + static char *kwlist[] = {"handle", "readable", "writable", NULL}; + + if (!PyArg_ParseTupleAndKeywords(args, kwds, F_HANDLE "|ii", kwlist, + &handle, &readable, &writable)) + return NULL; + + if (handle == INVALID_HANDLE_VALUE || (Py_ssize_t)handle < 0) { + PyErr_Format(PyExc_IOError, "invalid handle %zd", + (Py_ssize_t)handle); + return NULL; + } + + if (!readable && !writable) { + PyErr_SetString(PyExc_ValueError, + "either readable or writable must be true"); + return NULL; + } - return (PyObject*)self; + self = PyObject_New(ConnectionObject, type); + if (self == NULL) + return NULL; + + self->weakreflist = NULL; + self->handle = handle; + self->flags = 0; + + if (readable) + self->flags |= READABLE; + if (writable) + self->flags |= WRITABLE; + assert(self->flags >= 1 && self->flags <= 3); + + return (PyObject*)self; } static void connection_dealloc(ConnectionObject* self) { - if (self->weakreflist != NULL) - PyObject_ClearWeakRefs((PyObject*)self); + if (self->weakreflist != NULL) + PyObject_ClearWeakRefs((PyObject*)self); - if (self->handle != INVALID_HANDLE_VALUE) { - Py_BEGIN_ALLOW_THREADS - CLOSE(self->handle); - Py_END_ALLOW_THREADS - } - PyObject_Del(self); + if (self->handle != INVALID_HANDLE_VALUE) { + Py_BEGIN_ALLOW_THREADS + CLOSE(self->handle); + Py_END_ALLOW_THREADS + } + PyObject_Del(self); } /* @@ -96,168 +96,168 @@ static PyObject * connection_sendbytes(ConnectionObject *self, PyObject *args) { - Py_buffer pbuffer; - char *buffer; - Py_ssize_t length, offset=0, size=PY_SSIZE_T_MIN; - int res; - - if (!PyArg_ParseTuple(args, F_RBUFFER "*|" F_PY_SSIZE_T F_PY_SSIZE_T, - &pbuffer, &offset, &size)) - return NULL; - buffer = pbuffer.buf; - length = pbuffer.len; - - CHECK_WRITABLE(self); /* XXX release buffer in case of failure */ - - if (offset < 0) { - PyBuffer_Release(&pbuffer); - PyErr_SetString(PyExc_ValueError, "offset is negative"); - return NULL; - } - if (length < offset) { - PyBuffer_Release(&pbuffer); - PyErr_SetString(PyExc_ValueError, "buffer length < offset"); - return NULL; - } - - if (size == PY_SSIZE_T_MIN) { - size = length - offset; - } else { - if (size < 0) { - PyBuffer_Release(&pbuffer); - PyErr_SetString(PyExc_ValueError, "size is negative"); - return NULL; - } - if (offset + size > length) { - PyBuffer_Release(&pbuffer); - PyErr_SetString(PyExc_ValueError, - "buffer length < offset + size"); - return NULL; - } - } - - res = conn_send_string(self, buffer + offset, size); - - PyBuffer_Release(&pbuffer); - if (res < 0) { - if (PyErr_Occurred()) - return NULL; - else - return mp_SetError(PyExc_IOError, res); - } - - Py_RETURN_NONE; -} - -static PyObject * -connection_recvbytes(ConnectionObject *self, PyObject *args) -{ - char *freeme = NULL; - Py_ssize_t res, maxlength = PY_SSIZE_T_MAX; - PyObject *result = NULL; - - if (!PyArg_ParseTuple(args, "|" F_PY_SSIZE_T, &maxlength)) - return NULL; - - CHECK_READABLE(self); - - if (maxlength < 0) { - PyErr_SetString(PyExc_ValueError, "maxlength < 0"); - return NULL; - } - - res = conn_recv_string(self, self->buffer, CONNECTION_BUFFER_SIZE, - &freeme, maxlength); - - if (res < 0) { - if (res == MP_BAD_MESSAGE_LENGTH) { - if ((self->flags & WRITABLE) == 0) { - Py_BEGIN_ALLOW_THREADS - CLOSE(self->handle); - Py_END_ALLOW_THREADS - self->handle = INVALID_HANDLE_VALUE; - } else { - self->flags = WRITABLE; - } - } - mp_SetError(PyExc_IOError, res); - } else { - if (freeme == NULL) { - result = PyBytes_FromStringAndSize(self->buffer, res); - } else { - result = PyBytes_FromStringAndSize(freeme, res); - PyMem_Free(freeme); - } - } - - return result; -} - -static PyObject * -connection_recvbytes_into(ConnectionObject *self, PyObject *args) -{ - char *freeme = NULL, *buffer = NULL; - Py_ssize_t res, length, offset = 0; - PyObject *result = NULL; - Py_buffer pbuf; - - CHECK_READABLE(self); - - if (!PyArg_ParseTuple(args, "w*|" F_PY_SSIZE_T, - &pbuf, &offset)) - return NULL; - - buffer = pbuf.buf; - length = pbuf.len; - - if (offset < 0) { - PyErr_SetString(PyExc_ValueError, "negative offset"); - goto _error; - } - - if (offset > length) { - PyErr_SetString(PyExc_ValueError, "offset too large"); - goto _error; - } - - res = conn_recv_string(self, buffer+offset, length-offset, - &freeme, PY_SSIZE_T_MAX); - - if (res < 0) { - if (res == MP_BAD_MESSAGE_LENGTH) { - if ((self->flags & WRITABLE) == 0) { - Py_BEGIN_ALLOW_THREADS - CLOSE(self->handle); - Py_END_ALLOW_THREADS - self->handle = INVALID_HANDLE_VALUE; - } else { - self->flags = WRITABLE; - } - } - mp_SetError(PyExc_IOError, res); - } else { - if (freeme == NULL) { - result = PyInt_FromSsize_t(res); - } else { - result = PyObject_CallFunction(BufferTooShort, - F_RBUFFER "#", - freeme, res); - PyMem_Free(freeme); - if (result) { - PyErr_SetObject(BufferTooShort, result); - Py_DECREF(result); - } - goto _error; - } - } + Py_buffer pbuffer; + char *buffer; + Py_ssize_t length, offset=0, size=PY_SSIZE_T_MIN; + int res; + + if (!PyArg_ParseTuple(args, F_RBUFFER "*|" F_PY_SSIZE_T F_PY_SSIZE_T, + &pbuffer, &offset, &size)) + return NULL; + buffer = pbuffer.buf; + length = pbuffer.len; + + CHECK_WRITABLE(self); /* XXX release buffer in case of failure */ + + if (offset < 0) { + PyBuffer_Release(&pbuffer); + PyErr_SetString(PyExc_ValueError, "offset is negative"); + return NULL; + } + if (length < offset) { + PyBuffer_Release(&pbuffer); + PyErr_SetString(PyExc_ValueError, "buffer length < offset"); + return NULL; + } + + if (size == PY_SSIZE_T_MIN) { + size = length - offset; + } else { + if (size < 0) { + PyBuffer_Release(&pbuffer); + PyErr_SetString(PyExc_ValueError, "size is negative"); + return NULL; + } + if (offset + size > length) { + PyBuffer_Release(&pbuffer); + PyErr_SetString(PyExc_ValueError, + "buffer length < offset + size"); + return NULL; + } + } + + res = conn_send_string(self, buffer + offset, size); + + PyBuffer_Release(&pbuffer); + if (res < 0) { + if (PyErr_Occurred()) + return NULL; + else + return mp_SetError(PyExc_IOError, res); + } + + Py_RETURN_NONE; +} + +static PyObject * +connection_recvbytes(ConnectionObject *self, PyObject *args) +{ + char *freeme = NULL; + Py_ssize_t res, maxlength = PY_SSIZE_T_MAX; + PyObject *result = NULL; + + if (!PyArg_ParseTuple(args, "|" F_PY_SSIZE_T, &maxlength)) + return NULL; + + CHECK_READABLE(self); + + if (maxlength < 0) { + PyErr_SetString(PyExc_ValueError, "maxlength < 0"); + return NULL; + } + + res = conn_recv_string(self, self->buffer, CONNECTION_BUFFER_SIZE, + &freeme, maxlength); + + if (res < 0) { + if (res == MP_BAD_MESSAGE_LENGTH) { + if ((self->flags & WRITABLE) == 0) { + Py_BEGIN_ALLOW_THREADS + CLOSE(self->handle); + Py_END_ALLOW_THREADS + self->handle = INVALID_HANDLE_VALUE; + } else { + self->flags = WRITABLE; + } + } + mp_SetError(PyExc_IOError, res); + } else { + if (freeme == NULL) { + result = PyBytes_FromStringAndSize(self->buffer, res); + } else { + result = PyBytes_FromStringAndSize(freeme, res); + PyMem_Free(freeme); + } + } + + return result; +} + +static PyObject * +connection_recvbytes_into(ConnectionObject *self, PyObject *args) +{ + char *freeme = NULL, *buffer = NULL; + Py_ssize_t res, length, offset = 0; + PyObject *result = NULL; + Py_buffer pbuf; + + CHECK_READABLE(self); + + if (!PyArg_ParseTuple(args, "w*|" F_PY_SSIZE_T, + &pbuf, &offset)) + return NULL; + + buffer = pbuf.buf; + length = pbuf.len; + + if (offset < 0) { + PyErr_SetString(PyExc_ValueError, "negative offset"); + goto _error; + } + + if (offset > length) { + PyErr_SetString(PyExc_ValueError, "offset too large"); + goto _error; + } + + res = conn_recv_string(self, buffer+offset, length-offset, + &freeme, PY_SSIZE_T_MAX); + + if (res < 0) { + if (res == MP_BAD_MESSAGE_LENGTH) { + if ((self->flags & WRITABLE) == 0) { + Py_BEGIN_ALLOW_THREADS + CLOSE(self->handle); + Py_END_ALLOW_THREADS + self->handle = INVALID_HANDLE_VALUE; + } else { + self->flags = WRITABLE; + } + } + mp_SetError(PyExc_IOError, res); + } else { + if (freeme == NULL) { + result = PyInt_FromSsize_t(res); + } else { + result = PyObject_CallFunction(BufferTooShort, + F_RBUFFER "#", + freeme, res); + PyMem_Free(freeme); + if (result) { + PyErr_SetObject(BufferTooShort, result); + Py_DECREF(result); + } + goto _error; + } + } _cleanup: - PyBuffer_Release(&pbuf); - return result; + PyBuffer_Release(&pbuf); + return result; _error: - result = NULL; - goto _cleanup; + result = NULL; + goto _cleanup; } /* @@ -267,74 +267,74 @@ static PyObject * connection_send_obj(ConnectionObject *self, PyObject *obj) { - char *buffer; - int res; - Py_ssize_t length; - PyObject *pickled_string = NULL; - - CHECK_WRITABLE(self); - - pickled_string = PyObject_CallFunctionObjArgs(pickle_dumps, obj, - pickle_protocol, NULL); - if (!pickled_string) - goto failure; - - if (PyBytes_AsStringAndSize(pickled_string, &buffer, &length) < 0) - goto failure; - - res = conn_send_string(self, buffer, (int)length); - - if (res < 0) { - mp_SetError(PyExc_IOError, res); - goto failure; - } + char *buffer; + int res; + Py_ssize_t length; + PyObject *pickled_string = NULL; + + CHECK_WRITABLE(self); + + pickled_string = PyObject_CallFunctionObjArgs(pickle_dumps, obj, + pickle_protocol, NULL); + if (!pickled_string) + goto failure; + + if (PyBytes_AsStringAndSize(pickled_string, &buffer, &length) < 0) + goto failure; + + res = conn_send_string(self, buffer, (int)length); + + if (res < 0) { + mp_SetError(PyExc_IOError, res); + goto failure; + } - Py_XDECREF(pickled_string); - Py_RETURN_NONE; + Py_XDECREF(pickled_string); + Py_RETURN_NONE; failure: - Py_XDECREF(pickled_string); - return NULL; + Py_XDECREF(pickled_string); + return NULL; } static PyObject * connection_recv_obj(ConnectionObject *self) { - char *freeme = NULL; - Py_ssize_t res; - PyObject *temp = NULL, *result = NULL; - - CHECK_READABLE(self); - - res = conn_recv_string(self, self->buffer, CONNECTION_BUFFER_SIZE, - &freeme, PY_SSIZE_T_MAX); - - if (res < 0) { - if (res == MP_BAD_MESSAGE_LENGTH) { - if ((self->flags & WRITABLE) == 0) { - Py_BEGIN_ALLOW_THREADS - CLOSE(self->handle); - Py_END_ALLOW_THREADS - self->handle = INVALID_HANDLE_VALUE; - } else { - self->flags = WRITABLE; - } - } - mp_SetError(PyExc_IOError, res); - } else { - if (freeme == NULL) { - temp = PyBytes_FromStringAndSize(self->buffer, res); - } else { - temp = PyBytes_FromStringAndSize(freeme, res); - PyMem_Free(freeme); - } - } - - if (temp) - result = PyObject_CallFunctionObjArgs(pickle_loads, - temp, NULL); - Py_XDECREF(temp); - return result; + char *freeme = NULL; + Py_ssize_t res; + PyObject *temp = NULL, *result = NULL; + + CHECK_READABLE(self); + + res = conn_recv_string(self, self->buffer, CONNECTION_BUFFER_SIZE, + &freeme, PY_SSIZE_T_MAX); + + if (res < 0) { + if (res == MP_BAD_MESSAGE_LENGTH) { + if ((self->flags & WRITABLE) == 0) { + Py_BEGIN_ALLOW_THREADS + CLOSE(self->handle); + Py_END_ALLOW_THREADS + self->handle = INVALID_HANDLE_VALUE; + } else { + self->flags = WRITABLE; + } + } + mp_SetError(PyExc_IOError, res); + } else { + if (freeme == NULL) { + temp = PyBytes_FromStringAndSize(self->buffer, res); + } else { + temp = PyBytes_FromStringAndSize(freeme, res); + PyMem_Free(freeme); + } + } + + if (temp) + result = PyObject_CallFunctionObjArgs(pickle_loads, + temp, NULL); + Py_XDECREF(temp); + return result; } /* @@ -344,73 +344,73 @@ static PyObject * connection_poll(ConnectionObject *self, PyObject *args) { - PyObject *timeout_obj = NULL; - double timeout = 0.0; - int res; - - CHECK_READABLE(self); - - if (!PyArg_ParseTuple(args, "|O", &timeout_obj)) - return NULL; - - if (timeout_obj == NULL) { - timeout = 0.0; - } else if (timeout_obj == Py_None) { - timeout = -1.0; /* block forever */ - } else { - timeout = PyFloat_AsDouble(timeout_obj); - if (PyErr_Occurred()) - return NULL; - if (timeout < 0.0) - timeout = 0.0; - } - - Py_BEGIN_ALLOW_THREADS - res = conn_poll(self, timeout, _save); - Py_END_ALLOW_THREADS - - switch (res) { - case TRUE: - Py_RETURN_TRUE; - case FALSE: - Py_RETURN_FALSE; - default: - return mp_SetError(PyExc_IOError, res); - } + PyObject *timeout_obj = NULL; + double timeout = 0.0; + int res; + + CHECK_READABLE(self); + + if (!PyArg_ParseTuple(args, "|O", &timeout_obj)) + return NULL; + + if (timeout_obj == NULL) { + timeout = 0.0; + } else if (timeout_obj == Py_None) { + timeout = -1.0; /* block forever */ + } else { + timeout = PyFloat_AsDouble(timeout_obj); + if (PyErr_Occurred()) + return NULL; + if (timeout < 0.0) + timeout = 0.0; + } + + Py_BEGIN_ALLOW_THREADS + res = conn_poll(self, timeout, _save); + Py_END_ALLOW_THREADS + + switch (res) { + case TRUE: + Py_RETURN_TRUE; + case FALSE: + Py_RETURN_FALSE; + default: + return mp_SetError(PyExc_IOError, res); + } } static PyObject * connection_fileno(ConnectionObject* self) { - if (self->handle == INVALID_HANDLE_VALUE) { - PyErr_SetString(PyExc_IOError, "handle is invalid"); - return NULL; - } - return PyInt_FromLong((long)self->handle); + if (self->handle == INVALID_HANDLE_VALUE) { + PyErr_SetString(PyExc_IOError, "handle is invalid"); + return NULL; + } + return PyInt_FromLong((long)self->handle); } static PyObject * connection_close(ConnectionObject *self) { - if (self->handle != INVALID_HANDLE_VALUE) { - Py_BEGIN_ALLOW_THREADS - CLOSE(self->handle); - Py_END_ALLOW_THREADS - self->handle = INVALID_HANDLE_VALUE; - } + if (self->handle != INVALID_HANDLE_VALUE) { + Py_BEGIN_ALLOW_THREADS + CLOSE(self->handle); + Py_END_ALLOW_THREADS + self->handle = INVALID_HANDLE_VALUE; + } - Py_RETURN_NONE; + Py_RETURN_NONE; } static PyObject * connection_repr(ConnectionObject *self) { - static char *conn_type[] = {"read-only", "write-only", "read-write"}; + static char *conn_type[] = {"read-only", "write-only", "read-write"}; - assert(self->flags >= 1 && self->flags <= 3); - return FROM_FORMAT("<%s %s, handle %zd>", - conn_type[self->flags - 1], - CONNECTION_NAME, (Py_ssize_t)self->handle); + assert(self->flags >= 1 && self->flags <= 3); + return FROM_FORMAT("<%s %s, handle %zd>", + conn_type[self->flags - 1], + CONNECTION_NAME, (Py_ssize_t)self->handle); } /* @@ -420,19 +420,19 @@ static PyObject * connection_closed(ConnectionObject *self, void *closure) { - return PyBool_FromLong((long)(self->handle == INVALID_HANDLE_VALUE)); + return PyBool_FromLong((long)(self->handle == INVALID_HANDLE_VALUE)); } static PyObject * connection_readable(ConnectionObject *self, void *closure) { - return PyBool_FromLong((long)(self->flags & READABLE)); + return PyBool_FromLong((long)(self->flags & READABLE)); } static PyObject * connection_writable(ConnectionObject *self, void *closure) { - return PyBool_FromLong((long)(self->flags & WRITABLE)); + return PyBool_FromLong((long)(self->flags & WRITABLE)); } /* @@ -440,37 +440,37 @@ */ static PyMethodDef connection_methods[] = { - {"send_bytes", (PyCFunction)connection_sendbytes, METH_VARARGS, - "send the byte data from a readable buffer-like object"}, - {"recv_bytes", (PyCFunction)connection_recvbytes, METH_VARARGS, - "receive byte data as a string"}, - {"recv_bytes_into",(PyCFunction)connection_recvbytes_into,METH_VARARGS, - "receive byte data into a writeable buffer-like object\n" - "returns the number of bytes read"}, - - {"send", (PyCFunction)connection_send_obj, METH_O, - "send a (picklable) object"}, - {"recv", (PyCFunction)connection_recv_obj, METH_NOARGS, - "receive a (picklable) object"}, - - {"poll", (PyCFunction)connection_poll, METH_VARARGS, - "whether there is any input available to be read"}, - {"fileno", (PyCFunction)connection_fileno, METH_NOARGS, - "file descriptor or handle of the connection"}, - {"close", (PyCFunction)connection_close, METH_NOARGS, - "close the connection"}, + {"send_bytes", (PyCFunction)connection_sendbytes, METH_VARARGS, + "send the byte data from a readable buffer-like object"}, + {"recv_bytes", (PyCFunction)connection_recvbytes, METH_VARARGS, + "receive byte data as a string"}, + {"recv_bytes_into",(PyCFunction)connection_recvbytes_into,METH_VARARGS, + "receive byte data into a writeable buffer-like object\n" + "returns the number of bytes read"}, + + {"send", (PyCFunction)connection_send_obj, METH_O, + "send a (picklable) object"}, + {"recv", (PyCFunction)connection_recv_obj, METH_NOARGS, + "receive a (picklable) object"}, + + {"poll", (PyCFunction)connection_poll, METH_VARARGS, + "whether there is any input available to be read"}, + {"fileno", (PyCFunction)connection_fileno, METH_NOARGS, + "file descriptor or handle of the connection"}, + {"close", (PyCFunction)connection_close, METH_NOARGS, + "close the connection"}, - {NULL} /* Sentinel */ + {NULL} /* Sentinel */ }; static PyGetSetDef connection_getset[] = { - {"closed", (getter)connection_closed, NULL, - "True if the connection is closed", NULL}, - {"readable", (getter)connection_readable, NULL, - "True if the connection is readable", NULL}, - {"writable", (getter)connection_writable, NULL, - "True if the connection is writable", NULL}, - {NULL} + {"closed", (getter)connection_closed, NULL, + "True if the connection is closed", NULL}, + {"readable", (getter)connection_readable, NULL, + "True if the connection is readable", NULL}, + {"writable", (getter)connection_writable, NULL, + "True if the connection is writable", NULL}, + {NULL} }; /* @@ -478,50 +478,50 @@ */ PyDoc_STRVAR(connection_doc, - "Connection type whose constructor signature is\n\n" - " Connection(handle, readable=True, writable=True).\n\n" - "The constructor does *not* duplicate the handle."); + "Connection type whose constructor signature is\n\n" + " Connection(handle, readable=True, writable=True).\n\n" + "The constructor does *not* duplicate the handle."); PyTypeObject CONNECTION_TYPE = { - PyVarObject_HEAD_INIT(NULL, 0) - /* tp_name */ "_multiprocessing." CONNECTION_NAME, - /* tp_basicsize */ sizeof(ConnectionObject), - /* tp_itemsize */ 0, - /* tp_dealloc */ (destructor)connection_dealloc, - /* tp_print */ 0, - /* tp_getattr */ 0, - /* tp_setattr */ 0, - /* tp_reserved */ 0, - /* tp_repr */ (reprfunc)connection_repr, - /* tp_as_number */ 0, - /* tp_as_sequence */ 0, - /* tp_as_mapping */ 0, - /* tp_hash */ 0, - /* tp_call */ 0, - /* tp_str */ 0, - /* tp_getattro */ 0, - /* tp_setattro */ 0, - /* tp_as_buffer */ 0, - /* tp_flags */ Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | - Py_TPFLAGS_HAVE_WEAKREFS, - /* tp_doc */ connection_doc, - /* tp_traverse */ 0, - /* tp_clear */ 0, - /* tp_richcompare */ 0, - /* tp_weaklistoffset */ offsetof(ConnectionObject, weakreflist), - /* tp_iter */ 0, - /* tp_iternext */ 0, - /* tp_methods */ connection_methods, - /* tp_members */ 0, - /* tp_getset */ connection_getset, - /* tp_base */ 0, - /* tp_dict */ 0, - /* tp_descr_get */ 0, - /* tp_descr_set */ 0, - /* tp_dictoffset */ 0, - /* tp_init */ 0, - /* tp_alloc */ 0, - /* tp_new */ connection_new, + PyVarObject_HEAD_INIT(NULL, 0) + /* tp_name */ "_multiprocessing." CONNECTION_NAME, + /* tp_basicsize */ sizeof(ConnectionObject), + /* tp_itemsize */ 0, + /* tp_dealloc */ (destructor)connection_dealloc, + /* tp_print */ 0, + /* tp_getattr */ 0, + /* tp_setattr */ 0, + /* tp_reserved */ 0, + /* tp_repr */ (reprfunc)connection_repr, + /* tp_as_number */ 0, + /* tp_as_sequence */ 0, + /* tp_as_mapping */ 0, + /* tp_hash */ 0, + /* tp_call */ 0, + /* tp_str */ 0, + /* tp_getattro */ 0, + /* tp_setattro */ 0, + /* tp_as_buffer */ 0, + /* tp_flags */ Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | + Py_TPFLAGS_HAVE_WEAKREFS, + /* tp_doc */ connection_doc, + /* tp_traverse */ 0, + /* tp_clear */ 0, + /* tp_richcompare */ 0, + /* tp_weaklistoffset */ offsetof(ConnectionObject, weakreflist), + /* tp_iter */ 0, + /* tp_iternext */ 0, + /* tp_methods */ connection_methods, + /* tp_members */ 0, + /* tp_getset */ connection_getset, + /* tp_base */ 0, + /* tp_dict */ 0, + /* tp_descr_get */ 0, + /* tp_descr_set */ 0, + /* tp_dictoffset */ 0, + /* tp_init */ 0, + /* tp_alloc */ 0, + /* tp_new */ connection_new, }; #endif /* CONNECTION_H */ Modified: python/branches/release31-maint/Modules/_multiprocessing/multiprocessing.c ============================================================================== --- python/branches/release31-maint/Modules/_multiprocessing/multiprocessing.c (original) +++ python/branches/release31-maint/Modules/_multiprocessing/multiprocessing.c Sun May 9 18:14:21 2010 @@ -9,9 +9,9 @@ #include "multiprocessing.h" #ifdef SCM_RIGHTS - #define HAVE_FD_TRANSFER 1 + #define HAVE_FD_TRANSFER 1 #else - #define HAVE_FD_TRANSFER 0 + #define HAVE_FD_TRANSFER 0 #endif PyObject *create_win32_namespace(void); @@ -26,46 +26,46 @@ PyObject * mp_SetError(PyObject *Type, int num) { - switch (num) { + switch (num) { #ifdef MS_WINDOWS - case MP_STANDARD_ERROR: - if (Type == NULL) - Type = PyExc_WindowsError; - PyErr_SetExcFromWindowsErr(Type, 0); - break; - case MP_SOCKET_ERROR: - if (Type == NULL) - Type = PyExc_WindowsError; - PyErr_SetExcFromWindowsErr(Type, WSAGetLastError()); - break; + case MP_STANDARD_ERROR: + if (Type == NULL) + Type = PyExc_WindowsError; + PyErr_SetExcFromWindowsErr(Type, 0); + break; + case MP_SOCKET_ERROR: + if (Type == NULL) + Type = PyExc_WindowsError; + PyErr_SetExcFromWindowsErr(Type, WSAGetLastError()); + break; #else /* !MS_WINDOWS */ - case MP_STANDARD_ERROR: - case MP_SOCKET_ERROR: - if (Type == NULL) - Type = PyExc_OSError; - PyErr_SetFromErrno(Type); - break; + case MP_STANDARD_ERROR: + case MP_SOCKET_ERROR: + if (Type == NULL) + Type = PyExc_OSError; + PyErr_SetFromErrno(Type); + break; #endif /* !MS_WINDOWS */ - case MP_MEMORY_ERROR: - PyErr_NoMemory(); - break; - case MP_END_OF_FILE: - PyErr_SetNone(PyExc_EOFError); - break; - case MP_EARLY_END_OF_FILE: - PyErr_SetString(PyExc_IOError, - "got end of file during message"); - break; - case MP_BAD_MESSAGE_LENGTH: - PyErr_SetString(PyExc_IOError, "bad message length"); - break; - case MP_EXCEPTION_HAS_BEEN_SET: - break; - default: - PyErr_Format(PyExc_RuntimeError, - "unkown error number %d", num); - } - return NULL; + case MP_MEMORY_ERROR: + PyErr_NoMemory(); + break; + case MP_END_OF_FILE: + PyErr_SetNone(PyExc_EOFError); + break; + case MP_EARLY_END_OF_FILE: + PyErr_SetString(PyExc_IOError, + "got end of file during message"); + break; + case MP_BAD_MESSAGE_LENGTH: + PyErr_SetString(PyExc_IOError, "bad message length"); + break; + case MP_EXCEPTION_HAS_BEEN_SET: + break; + default: + PyErr_Format(PyExc_RuntimeError, + "unkown error number %d", num); + } + return NULL; } @@ -82,8 +82,8 @@ static BOOL WINAPI ProcessingCtrlHandler(DWORD dwCtrlType) { - SetEvent(sigint_event); - return FALSE; + SetEvent(sigint_event); + return FALSE; } /* @@ -101,72 +101,72 @@ static PyObject * multiprocessing_sendfd(PyObject *self, PyObject *args) { - int conn, fd, res; - char dummy_char; - char buf[CMSG_SPACE(sizeof(int))]; - struct msghdr msg = {0}; - struct iovec dummy_iov; - struct cmsghdr *cmsg; - - if (!PyArg_ParseTuple(args, "ii", &conn, &fd)) - return NULL; - - dummy_iov.iov_base = &dummy_char; - dummy_iov.iov_len = 1; - msg.msg_control = buf; - msg.msg_controllen = sizeof(buf); - msg.msg_iov = &dummy_iov; - msg.msg_iovlen = 1; - cmsg = CMSG_FIRSTHDR(&msg); - cmsg->cmsg_level = SOL_SOCKET; - cmsg->cmsg_type = SCM_RIGHTS; - cmsg->cmsg_len = CMSG_LEN(sizeof(int)); - msg.msg_controllen = cmsg->cmsg_len; - *(int*)CMSG_DATA(cmsg) = fd; - - Py_BEGIN_ALLOW_THREADS - res = sendmsg(conn, &msg, 0); - Py_END_ALLOW_THREADS - - if (res < 0) - return PyErr_SetFromErrno(PyExc_OSError); - Py_RETURN_NONE; + int conn, fd, res; + char dummy_char; + char buf[CMSG_SPACE(sizeof(int))]; + struct msghdr msg = {0}; + struct iovec dummy_iov; + struct cmsghdr *cmsg; + + if (!PyArg_ParseTuple(args, "ii", &conn, &fd)) + return NULL; + + dummy_iov.iov_base = &dummy_char; + dummy_iov.iov_len = 1; + msg.msg_control = buf; + msg.msg_controllen = sizeof(buf); + msg.msg_iov = &dummy_iov; + msg.msg_iovlen = 1; + cmsg = CMSG_FIRSTHDR(&msg); + cmsg->cmsg_level = SOL_SOCKET; + cmsg->cmsg_type = SCM_RIGHTS; + cmsg->cmsg_len = CMSG_LEN(sizeof(int)); + msg.msg_controllen = cmsg->cmsg_len; + *(int*)CMSG_DATA(cmsg) = fd; + + Py_BEGIN_ALLOW_THREADS + res = sendmsg(conn, &msg, 0); + Py_END_ALLOW_THREADS + + if (res < 0) + return PyErr_SetFromErrno(PyExc_OSError); + Py_RETURN_NONE; } static PyObject * multiprocessing_recvfd(PyObject *self, PyObject *args) { - int conn, fd, res; - char dummy_char; - char buf[CMSG_SPACE(sizeof(int))]; - struct msghdr msg = {0}; - struct iovec dummy_iov; - struct cmsghdr *cmsg; - - if (!PyArg_ParseTuple(args, "i", &conn)) - return NULL; - - dummy_iov.iov_base = &dummy_char; - dummy_iov.iov_len = 1; - msg.msg_control = buf; - msg.msg_controllen = sizeof(buf); - msg.msg_iov = &dummy_iov; - msg.msg_iovlen = 1; - cmsg = CMSG_FIRSTHDR(&msg); - cmsg->cmsg_level = SOL_SOCKET; - cmsg->cmsg_type = SCM_RIGHTS; - cmsg->cmsg_len = CMSG_LEN(sizeof(int)); - msg.msg_controllen = cmsg->cmsg_len; - - Py_BEGIN_ALLOW_THREADS - res = recvmsg(conn, &msg, 0); - Py_END_ALLOW_THREADS + int conn, fd, res; + char dummy_char; + char buf[CMSG_SPACE(sizeof(int))]; + struct msghdr msg = {0}; + struct iovec dummy_iov; + struct cmsghdr *cmsg; + + if (!PyArg_ParseTuple(args, "i", &conn)) + return NULL; + + dummy_iov.iov_base = &dummy_char; + dummy_iov.iov_len = 1; + msg.msg_control = buf; + msg.msg_controllen = sizeof(buf); + msg.msg_iov = &dummy_iov; + msg.msg_iovlen = 1; + cmsg = CMSG_FIRSTHDR(&msg); + cmsg->cmsg_level = SOL_SOCKET; + cmsg->cmsg_type = SCM_RIGHTS; + cmsg->cmsg_len = CMSG_LEN(sizeof(int)); + msg.msg_controllen = cmsg->cmsg_len; + + Py_BEGIN_ALLOW_THREADS + res = recvmsg(conn, &msg, 0); + Py_END_ALLOW_THREADS - if (res < 0) - return PyErr_SetFromErrno(PyExc_OSError); + if (res < 0) + return PyErr_SetFromErrno(PyExc_OSError); - fd = *(int*)CMSG_DATA(cmsg); - return Py_BuildValue("i", fd); + fd = *(int*)CMSG_DATA(cmsg); + return Py_BuildValue("i", fd); } #endif /* HAVE_FD_TRANSFER */ @@ -181,14 +181,14 @@ static PyObject* multiprocessing_address_of_buffer(PyObject *self, PyObject *obj) { - void *buffer; - Py_ssize_t buffer_len; + void *buffer; + Py_ssize_t buffer_len; - if (PyObject_AsWriteBuffer(obj, &buffer, &buffer_len) < 0) - return NULL; + if (PyObject_AsWriteBuffer(obj, &buffer, &buffer_len) < 0) + return NULL; - return Py_BuildValue("N" F_PY_SSIZE_T, - PyLong_FromVoidPtr(buffer), buffer_len); + return Py_BuildValue("N" F_PY_SSIZE_T, + PyLong_FromVoidPtr(buffer), buffer_len); } @@ -197,20 +197,20 @@ */ static PyMethodDef module_methods[] = { - {"address_of_buffer", multiprocessing_address_of_buffer, METH_O, - "address_of_buffer(obj) -> int\n" - "Return address of obj assuming obj supports buffer inteface"}, + {"address_of_buffer", multiprocessing_address_of_buffer, METH_O, + "address_of_buffer(obj) -> int\n" + "Return address of obj assuming obj supports buffer inteface"}, #if HAVE_FD_TRANSFER - {"sendfd", multiprocessing_sendfd, METH_VARARGS, - "sendfd(sockfd, fd) -> None\n" - "Send file descriptor given by fd over the unix domain socket\n" - "whose file decriptor is sockfd"}, - {"recvfd", multiprocessing_recvfd, METH_VARARGS, - "recvfd(sockfd) -> fd\n" - "Receive a file descriptor over a unix domain socket\n" - "whose file decriptor is sockfd"}, + {"sendfd", multiprocessing_sendfd, METH_VARARGS, + "sendfd(sockfd, fd) -> None\n" + "Send file descriptor given by fd over the unix domain socket\n" + "whose file decriptor is sockfd"}, + {"recvfd", multiprocessing_recvfd, METH_VARARGS, + "recvfd(sockfd) -> fd\n" + "Receive a file descriptor over a unix domain socket\n" + "whose file decriptor is sockfd"}, #endif - {NULL} + {NULL} }; @@ -219,117 +219,117 @@ */ static struct PyModuleDef multiprocessing_module = { - PyModuleDef_HEAD_INIT, - "_multiprocessing", - NULL, - -1, - module_methods, - NULL, - NULL, - NULL, - NULL + PyModuleDef_HEAD_INIT, + "_multiprocessing", + NULL, + -1, + module_methods, + NULL, + NULL, + NULL, + NULL }; -PyMODINIT_FUNC +PyMODINIT_FUNC PyInit__multiprocessing(void) { - PyObject *module, *temp, *value; + PyObject *module, *temp, *value; - /* Initialize module */ - module = PyModule_Create(&multiprocessing_module); - if (!module) - return NULL; - - /* Get copy of objects from pickle */ - temp = PyImport_ImportModule(PICKLE_MODULE); - if (!temp) - return NULL; - pickle_dumps = PyObject_GetAttrString(temp, "dumps"); - pickle_loads = PyObject_GetAttrString(temp, "loads"); - pickle_protocol = PyObject_GetAttrString(temp, "HIGHEST_PROTOCOL"); - Py_XDECREF(temp); - - /* Get copy of BufferTooShort */ - temp = PyImport_ImportModule("multiprocessing"); - if (!temp) - return NULL; - BufferTooShort = PyObject_GetAttrString(temp, "BufferTooShort"); - Py_XDECREF(temp); - - /* Add connection type to module */ - if (PyType_Ready(&ConnectionType) < 0) - return NULL; - Py_INCREF(&ConnectionType); - PyModule_AddObject(module, "Connection", (PyObject*)&ConnectionType); + /* Initialize module */ + module = PyModule_Create(&multiprocessing_module); + if (!module) + return NULL; + + /* Get copy of objects from pickle */ + temp = PyImport_ImportModule(PICKLE_MODULE); + if (!temp) + return NULL; + pickle_dumps = PyObject_GetAttrString(temp, "dumps"); + pickle_loads = PyObject_GetAttrString(temp, "loads"); + pickle_protocol = PyObject_GetAttrString(temp, "HIGHEST_PROTOCOL"); + Py_XDECREF(temp); + + /* Get copy of BufferTooShort */ + temp = PyImport_ImportModule("multiprocessing"); + if (!temp) + return NULL; + BufferTooShort = PyObject_GetAttrString(temp, "BufferTooShort"); + Py_XDECREF(temp); + + /* Add connection type to module */ + if (PyType_Ready(&ConnectionType) < 0) + return NULL; + Py_INCREF(&ConnectionType); + PyModule_AddObject(module, "Connection", (PyObject*)&ConnectionType); -#if defined(MS_WINDOWS) || \ +#if defined(MS_WINDOWS) || \ (defined(HAVE_SEM_OPEN) && !defined(POSIX_SEMAPHORES_NOT_ENABLED)) - /* Add SemLock type to module */ - if (PyType_Ready(&SemLockType) < 0) - return NULL; - Py_INCREF(&SemLockType); - PyDict_SetItemString(SemLockType.tp_dict, "SEM_VALUE_MAX", - Py_BuildValue("i", SEM_VALUE_MAX)); - PyModule_AddObject(module, "SemLock", (PyObject*)&SemLockType); + /* Add SemLock type to module */ + if (PyType_Ready(&SemLockType) < 0) + return NULL; + Py_INCREF(&SemLockType); + PyDict_SetItemString(SemLockType.tp_dict, "SEM_VALUE_MAX", + Py_BuildValue("i", SEM_VALUE_MAX)); + PyModule_AddObject(module, "SemLock", (PyObject*)&SemLockType); #endif #ifdef MS_WINDOWS - /* Add PipeConnection to module */ - if (PyType_Ready(&PipeConnectionType) < 0) - return NULL; - Py_INCREF(&PipeConnectionType); - PyModule_AddObject(module, "PipeConnection", - (PyObject*)&PipeConnectionType); - - /* Initialize win32 class and add to multiprocessing */ - temp = create_win32_namespace(); - if (!temp) - return NULL; - PyModule_AddObject(module, "win32", temp); - - /* Initialize the event handle used to signal Ctrl-C */ - sigint_event = CreateEvent(NULL, TRUE, FALSE, NULL); - if (!sigint_event) { - PyErr_SetFromWindowsErr(0); - return NULL; - } - if (!SetConsoleCtrlHandler(ProcessingCtrlHandler, TRUE)) { - PyErr_SetFromWindowsErr(0); - return NULL; - } + /* Add PipeConnection to module */ + if (PyType_Ready(&PipeConnectionType) < 0) + return NULL; + Py_INCREF(&PipeConnectionType); + PyModule_AddObject(module, "PipeConnection", + (PyObject*)&PipeConnectionType); + + /* Initialize win32 class and add to multiprocessing */ + temp = create_win32_namespace(); + if (!temp) + return NULL; + PyModule_AddObject(module, "win32", temp); + + /* Initialize the event handle used to signal Ctrl-C */ + sigint_event = CreateEvent(NULL, TRUE, FALSE, NULL); + if (!sigint_event) { + PyErr_SetFromWindowsErr(0); + return NULL; + } + if (!SetConsoleCtrlHandler(ProcessingCtrlHandler, TRUE)) { + PyErr_SetFromWindowsErr(0); + return NULL; + } #endif - /* Add configuration macros */ - temp = PyDict_New(); - if (!temp) - return NULL; - -#define ADD_FLAG(name) \ - value = Py_BuildValue("i", name); \ - if (value == NULL) { Py_DECREF(temp); return NULL; } \ - if (PyDict_SetItemString(temp, #name, value) < 0) { \ - Py_DECREF(temp); Py_DECREF(value); return NULL; } \ - Py_DECREF(value) - + /* Add configuration macros */ + temp = PyDict_New(); + if (!temp) + return NULL; + +#define ADD_FLAG(name) \ + value = Py_BuildValue("i", name); \ + if (value == NULL) { Py_DECREF(temp); return NULL; } \ + if (PyDict_SetItemString(temp, #name, value) < 0) { \ + Py_DECREF(temp); Py_DECREF(value); return NULL; } \ + Py_DECREF(value) + #if defined(HAVE_SEM_OPEN) && !defined(POSIX_SEMAPHORES_NOT_ENABLED) - ADD_FLAG(HAVE_SEM_OPEN); + ADD_FLAG(HAVE_SEM_OPEN); #endif #ifdef HAVE_SEM_TIMEDWAIT - ADD_FLAG(HAVE_SEM_TIMEDWAIT); + ADD_FLAG(HAVE_SEM_TIMEDWAIT); #endif #ifdef HAVE_FD_TRANSFER - ADD_FLAG(HAVE_FD_TRANSFER); + ADD_FLAG(HAVE_FD_TRANSFER); #endif #ifdef HAVE_BROKEN_SEM_GETVALUE - ADD_FLAG(HAVE_BROKEN_SEM_GETVALUE); + ADD_FLAG(HAVE_BROKEN_SEM_GETVALUE); #endif #ifdef HAVE_BROKEN_SEM_UNLINK - ADD_FLAG(HAVE_BROKEN_SEM_UNLINK); + ADD_FLAG(HAVE_BROKEN_SEM_UNLINK); #endif - if (PyModule_AddObject(module, "flags", temp) < 0) - return NULL; + if (PyModule_AddObject(module, "flags", temp) < 0) + return NULL; - return module; + return module; } Modified: python/branches/release31-maint/Modules/_multiprocessing/multiprocessing.h ============================================================================== --- python/branches/release31-maint/Modules/_multiprocessing/multiprocessing.h (original) +++ python/branches/release31-maint/Modules/_multiprocessing/multiprocessing.h Sun May 9 18:14:21 2010 @@ -15,7 +15,7 @@ # define WIN32_LEAN_AND_MEAN # include # include -# include /* getpid() */ +# include /* getpid() */ # ifdef Py_DEBUG # include # endif @@ -45,15 +45,15 @@ * Issue 3110 - Solaris does not define SEM_VALUE_MAX */ #ifndef SEM_VALUE_MAX - #if defined(HAVE_SYSCONF) && defined(_SC_SEM_VALUE_MAX) - # define SEM_VALUE_MAX sysconf(_SC_SEM_VALUE_MAX) - #elif defined(_SEM_VALUE_MAX) - # define SEM_VALUE_MAX _SEM_VALUE_MAX - #elif defined(_POSIX_SEM_VALUE_MAX) - # define SEM_VALUE_MAX _POSIX_SEM_VALUE_MAX - #else - # define SEM_VALUE_MAX INT_MAX - #endif + #if defined(HAVE_SYSCONF) && defined(_SC_SEM_VALUE_MAX) + # define SEM_VALUE_MAX sysconf(_SC_SEM_VALUE_MAX) + #elif defined(_SEM_VALUE_MAX) + # define SEM_VALUE_MAX _SEM_VALUE_MAX + #elif defined(_POSIX_SEM_VALUE_MAX) + # define SEM_VALUE_MAX _POSIX_SEM_VALUE_MAX + #else + # define SEM_VALUE_MAX INT_MAX + #endif #endif @@ -162,11 +162,11 @@ #define CONNECTION_BUFFER_SIZE 1024 typedef struct { - PyObject_HEAD - HANDLE handle; - int flags; - PyObject *weakreflist; - char buffer[CONNECTION_BUFFER_SIZE]; + PyObject_HEAD + HANDLE handle; + int flags; + PyObject *weakreflist; + char buffer[CONNECTION_BUFFER_SIZE]; } ConnectionObject; /* Modified: python/branches/release31-maint/Modules/_multiprocessing/pipe_connection.c ============================================================================== --- python/branches/release31-maint/Modules/_multiprocessing/pipe_connection.c (original) +++ python/branches/release31-maint/Modules/_multiprocessing/pipe_connection.c Sun May 9 18:14:21 2010 @@ -17,19 +17,19 @@ static Py_ssize_t conn_send_string(ConnectionObject *conn, char *string, size_t length) { - DWORD amount_written; - BOOL ret; + DWORD amount_written; + BOOL ret; - Py_BEGIN_ALLOW_THREADS - ret = WriteFile(conn->handle, string, length, &amount_written, NULL); - Py_END_ALLOW_THREADS - - if (ret == 0 && GetLastError() == ERROR_NO_SYSTEM_RESOURCES) { - PyErr_Format(PyExc_ValueError, "Cannnot send %" PY_FORMAT_SIZE_T "d bytes over connection", length); - return MP_STANDARD_ERROR; - } + Py_BEGIN_ALLOW_THREADS + ret = WriteFile(conn->handle, string, length, &amount_written, NULL); + Py_END_ALLOW_THREADS + + if (ret == 0 && GetLastError() == ERROR_NO_SYSTEM_RESOURCES) { + PyErr_Format(PyExc_ValueError, "Cannnot send %" PY_FORMAT_SIZE_T "d bytes over connection", length); + return MP_STANDARD_ERROR; + } - return ret ? MP_SUCCESS : MP_STANDARD_ERROR; + return ret ? MP_SUCCESS : MP_STANDARD_ERROR; } /* @@ -39,50 +39,50 @@ */ static Py_ssize_t -conn_recv_string(ConnectionObject *conn, char *buffer, - size_t buflength, char **newbuffer, size_t maxlength) +conn_recv_string(ConnectionObject *conn, char *buffer, + size_t buflength, char **newbuffer, size_t maxlength) { - DWORD left, length, full_length, err; - BOOL ret; - *newbuffer = NULL; - - Py_BEGIN_ALLOW_THREADS - ret = ReadFile(conn->handle, buffer, MIN(buflength, maxlength), - &length, NULL); - Py_END_ALLOW_THREADS - if (ret) - return length; - - err = GetLastError(); - if (err != ERROR_MORE_DATA) { - if (err == ERROR_BROKEN_PIPE) - return MP_END_OF_FILE; - return MP_STANDARD_ERROR; - } - - if (!PeekNamedPipe(conn->handle, NULL, 0, NULL, NULL, &left)) - return MP_STANDARD_ERROR; - - full_length = length + left; - if (full_length > maxlength) - return MP_BAD_MESSAGE_LENGTH; - - *newbuffer = PyMem_Malloc(full_length); - if (*newbuffer == NULL) - return MP_MEMORY_ERROR; - - memcpy(*newbuffer, buffer, length); - - Py_BEGIN_ALLOW_THREADS - ret = ReadFile(conn->handle, *newbuffer+length, left, &length, NULL); - Py_END_ALLOW_THREADS - if (ret) { - assert(length == left); - return full_length; - } else { - PyMem_Free(*newbuffer); - return MP_STANDARD_ERROR; - } + DWORD left, length, full_length, err; + BOOL ret; + *newbuffer = NULL; + + Py_BEGIN_ALLOW_THREADS + ret = ReadFile(conn->handle, buffer, MIN(buflength, maxlength), + &length, NULL); + Py_END_ALLOW_THREADS + if (ret) + return length; + + err = GetLastError(); + if (err != ERROR_MORE_DATA) { + if (err == ERROR_BROKEN_PIPE) + return MP_END_OF_FILE; + return MP_STANDARD_ERROR; + } + + if (!PeekNamedPipe(conn->handle, NULL, 0, NULL, NULL, &left)) + return MP_STANDARD_ERROR; + + full_length = length + left; + if (full_length > maxlength) + return MP_BAD_MESSAGE_LENGTH; + + *newbuffer = PyMem_Malloc(full_length); + if (*newbuffer == NULL) + return MP_MEMORY_ERROR; + + memcpy(*newbuffer, buffer, length); + + Py_BEGIN_ALLOW_THREADS + ret = ReadFile(conn->handle, *newbuffer+length, left, &length, NULL); + Py_END_ALLOW_THREADS + if (ret) { + assert(length == left); + return full_length; + } else { + PyMem_Free(*newbuffer); + return MP_STANDARD_ERROR; + } } /* @@ -92,51 +92,51 @@ static int conn_poll(ConnectionObject *conn, double timeout, PyThreadState *_save) { - DWORD bytes, deadline, delay; - int difference, res; - BOOL block = FALSE; - - if (!PeekNamedPipe(conn->handle, NULL, 0, NULL, &bytes, NULL)) - return MP_STANDARD_ERROR; - - if (timeout == 0.0) - return bytes > 0; - - if (timeout < 0.0) - block = TRUE; - else - /* XXX does not check for overflow */ - deadline = GetTickCount() + (DWORD)(1000 * timeout + 0.5); - - Sleep(0); - - for (delay = 1 ; ; delay += 1) { - if (!PeekNamedPipe(conn->handle, NULL, 0, NULL, &bytes, NULL)) - return MP_STANDARD_ERROR; - else if (bytes > 0) - return TRUE; - - if (!block) { - difference = deadline - GetTickCount(); - if (difference < 0) - return FALSE; - if ((int)delay > difference) - delay = difference; - } - - if (delay > 20) - delay = 20; - - Sleep(delay); - - /* check for signals */ - Py_BLOCK_THREADS - res = PyErr_CheckSignals(); - Py_UNBLOCK_THREADS - - if (res) - return MP_EXCEPTION_HAS_BEEN_SET; - } + DWORD bytes, deadline, delay; + int difference, res; + BOOL block = FALSE; + + if (!PeekNamedPipe(conn->handle, NULL, 0, NULL, &bytes, NULL)) + return MP_STANDARD_ERROR; + + if (timeout == 0.0) + return bytes > 0; + + if (timeout < 0.0) + block = TRUE; + else + /* XXX does not check for overflow */ + deadline = GetTickCount() + (DWORD)(1000 * timeout + 0.5); + + Sleep(0); + + for (delay = 1 ; ; delay += 1) { + if (!PeekNamedPipe(conn->handle, NULL, 0, NULL, &bytes, NULL)) + return MP_STANDARD_ERROR; + else if (bytes > 0) + return TRUE; + + if (!block) { + difference = deadline - GetTickCount(); + if (difference < 0) + return FALSE; + if ((int)delay > difference) + delay = difference; + } + + if (delay > 20) + delay = 20; + + Sleep(delay); + + /* check for signals */ + Py_BLOCK_THREADS + res = PyErr_CheckSignals(); + Py_UNBLOCK_THREADS + + if (res) + return MP_EXCEPTION_HAS_BEEN_SET; + } } /* Modified: python/branches/release31-maint/Modules/_multiprocessing/semaphore.c ============================================================================== --- python/branches/release31-maint/Modules/_multiprocessing/semaphore.c (original) +++ python/branches/release31-maint/Modules/_multiprocessing/semaphore.c Sun May 9 18:14:21 2010 @@ -11,12 +11,12 @@ enum { RECURSIVE_MUTEX, SEMAPHORE }; typedef struct { - PyObject_HEAD - SEM_HANDLE handle; - long last_tid; - int count; - int maxvalue; - int kind; + PyObject_HEAD + SEM_HANDLE handle; + long last_tid; + int count; + int maxvalue; + int kind; } SemLockObject; #define ISMINE(o) (o->count > 0 && PyThread_get_thread_ident() == o->last_tid) @@ -40,148 +40,148 @@ static int _GetSemaphoreValue(HANDLE handle, long *value) { - long previous; + long previous; - switch (WaitForSingleObject(handle, 0)) { - case WAIT_OBJECT_0: - if (!ReleaseSemaphore(handle, 1, &previous)) - return MP_STANDARD_ERROR; - *value = previous + 1; - return 0; - case WAIT_TIMEOUT: - *value = 0; - return 0; - default: - return MP_STANDARD_ERROR; - } + switch (WaitForSingleObject(handle, 0)) { + case WAIT_OBJECT_0: + if (!ReleaseSemaphore(handle, 1, &previous)) + return MP_STANDARD_ERROR; + *value = previous + 1; + return 0; + case WAIT_TIMEOUT: + *value = 0; + return 0; + default: + return MP_STANDARD_ERROR; + } } static PyObject * semlock_acquire(SemLockObject *self, PyObject *args, PyObject *kwds) { - int blocking = 1; - double timeout; - PyObject *timeout_obj = Py_None; - DWORD res, full_msecs, msecs, start, ticks; - - static char *kwlist[] = {"block", "timeout", NULL}; - - if (!PyArg_ParseTupleAndKeywords(args, kwds, "|iO", kwlist, - &blocking, &timeout_obj)) - return NULL; - - /* calculate timeout */ - if (!blocking) { - full_msecs = 0; - } else if (timeout_obj == Py_None) { - full_msecs = INFINITE; - } else { - timeout = PyFloat_AsDouble(timeout_obj); - if (PyErr_Occurred()) - return NULL; - timeout *= 1000.0; /* convert to millisecs */ - if (timeout < 0.0) { - timeout = 0.0; - } else if (timeout >= 0.5 * INFINITE) { /* 25 days */ - PyErr_SetString(PyExc_OverflowError, - "timeout is too large"); - return NULL; - } - full_msecs = (DWORD)(timeout + 0.5); - } - - /* check whether we already own the lock */ - if (self->kind == RECURSIVE_MUTEX && ISMINE(self)) { - ++self->count; - Py_RETURN_TRUE; - } - - /* check whether we can acquire without blocking */ - if (WaitForSingleObject(self->handle, 0) == WAIT_OBJECT_0) { - self->last_tid = GetCurrentThreadId(); - ++self->count; - Py_RETURN_TRUE; - } - - msecs = full_msecs; - start = GetTickCount(); - - for ( ; ; ) { - HANDLE handles[2] = {self->handle, sigint_event}; - - /* do the wait */ - Py_BEGIN_ALLOW_THREADS - ResetEvent(sigint_event); - res = WaitForMultipleObjects(2, handles, FALSE, msecs); - Py_END_ALLOW_THREADS - - /* handle result */ - if (res != WAIT_OBJECT_0 + 1) - break; - - /* got SIGINT so give signal handler a chance to run */ - Sleep(1); - - /* if this is main thread let KeyboardInterrupt be raised */ - if (PyErr_CheckSignals()) - return NULL; - - /* recalculate timeout */ - if (msecs != INFINITE) { - ticks = GetTickCount(); - if ((DWORD)(ticks - start) >= full_msecs) - Py_RETURN_FALSE; - msecs = full_msecs - (ticks - start); - } - } - - /* handle result */ - switch (res) { - case WAIT_TIMEOUT: - Py_RETURN_FALSE; - case WAIT_OBJECT_0: - self->last_tid = GetCurrentThreadId(); - ++self->count; - Py_RETURN_TRUE; - case WAIT_FAILED: - return PyErr_SetFromWindowsErr(0); - default: - PyErr_Format(PyExc_RuntimeError, "WaitForSingleObject() or " - "WaitForMultipleObjects() gave unrecognized " - "value %d", res); - return NULL; - } + int blocking = 1; + double timeout; + PyObject *timeout_obj = Py_None; + DWORD res, full_msecs, msecs, start, ticks; + + static char *kwlist[] = {"block", "timeout", NULL}; + + if (!PyArg_ParseTupleAndKeywords(args, kwds, "|iO", kwlist, + &blocking, &timeout_obj)) + return NULL; + + /* calculate timeout */ + if (!blocking) { + full_msecs = 0; + } else if (timeout_obj == Py_None) { + full_msecs = INFINITE; + } else { + timeout = PyFloat_AsDouble(timeout_obj); + if (PyErr_Occurred()) + return NULL; + timeout *= 1000.0; /* convert to millisecs */ + if (timeout < 0.0) { + timeout = 0.0; + } else if (timeout >= 0.5 * INFINITE) { /* 25 days */ + PyErr_SetString(PyExc_OverflowError, + "timeout is too large"); + return NULL; + } + full_msecs = (DWORD)(timeout + 0.5); + } + + /* check whether we already own the lock */ + if (self->kind == RECURSIVE_MUTEX && ISMINE(self)) { + ++self->count; + Py_RETURN_TRUE; + } + + /* check whether we can acquire without blocking */ + if (WaitForSingleObject(self->handle, 0) == WAIT_OBJECT_0) { + self->last_tid = GetCurrentThreadId(); + ++self->count; + Py_RETURN_TRUE; + } + + msecs = full_msecs; + start = GetTickCount(); + + for ( ; ; ) { + HANDLE handles[2] = {self->handle, sigint_event}; + + /* do the wait */ + Py_BEGIN_ALLOW_THREADS + ResetEvent(sigint_event); + res = WaitForMultipleObjects(2, handles, FALSE, msecs); + Py_END_ALLOW_THREADS + + /* handle result */ + if (res != WAIT_OBJECT_0 + 1) + break; + + /* got SIGINT so give signal handler a chance to run */ + Sleep(1); + + /* if this is main thread let KeyboardInterrupt be raised */ + if (PyErr_CheckSignals()) + return NULL; + + /* recalculate timeout */ + if (msecs != INFINITE) { + ticks = GetTickCount(); + if ((DWORD)(ticks - start) >= full_msecs) + Py_RETURN_FALSE; + msecs = full_msecs - (ticks - start); + } + } + + /* handle result */ + switch (res) { + case WAIT_TIMEOUT: + Py_RETURN_FALSE; + case WAIT_OBJECT_0: + self->last_tid = GetCurrentThreadId(); + ++self->count; + Py_RETURN_TRUE; + case WAIT_FAILED: + return PyErr_SetFromWindowsErr(0); + default: + PyErr_Format(PyExc_RuntimeError, "WaitForSingleObject() or " + "WaitForMultipleObjects() gave unrecognized " + "value %d", res); + return NULL; + } } static PyObject * semlock_release(SemLockObject *self, PyObject *args) { - if (self->kind == RECURSIVE_MUTEX) { - if (!ISMINE(self)) { - PyErr_SetString(PyExc_AssertionError, "attempt to " - "release recursive lock not owned " - "by thread"); - return NULL; - } - if (self->count > 1) { - --self->count; - Py_RETURN_NONE; - } - assert(self->count == 1); - } - - if (!ReleaseSemaphore(self->handle, 1, NULL)) { - if (GetLastError() == ERROR_TOO_MANY_POSTS) { - PyErr_SetString(PyExc_ValueError, "semaphore or lock " - "released too many times"); - return NULL; - } else { - return PyErr_SetFromWindowsErr(0); - } - } + if (self->kind == RECURSIVE_MUTEX) { + if (!ISMINE(self)) { + PyErr_SetString(PyExc_AssertionError, "attempt to " + "release recursive lock not owned " + "by thread"); + return NULL; + } + if (self->count > 1) { + --self->count; + Py_RETURN_NONE; + } + assert(self->count == 1); + } + + if (!ReleaseSemaphore(self->handle, 1, NULL)) { + if (GetLastError() == ERROR_TOO_MANY_POSTS) { + PyErr_SetString(PyExc_ValueError, "semaphore or lock " + "released too many times"); + return NULL; + } else { + return PyErr_SetFromWindowsErr(0); + } + } - --self->count; - Py_RETURN_NONE; + --self->count; + Py_RETURN_NONE; } #else /* !MS_WINDOWS */ @@ -207,59 +207,59 @@ int sem_timedwait_save(sem_t *sem, struct timespec *deadline, PyThreadState *_save) { - int res; - unsigned long delay, difference; - struct timeval now, tvdeadline, tvdelay; - - errno = 0; - tvdeadline.tv_sec = deadline->tv_sec; - tvdeadline.tv_usec = deadline->tv_nsec / 1000; - - for (delay = 0 ; ; delay += 1000) { - /* poll */ - if (sem_trywait(sem) == 0) - return 0; - else if (errno != EAGAIN) - return MP_STANDARD_ERROR; - - /* get current time */ - if (gettimeofday(&now, NULL) < 0) - return MP_STANDARD_ERROR; - - /* check for timeout */ - if (tvdeadline.tv_sec < now.tv_sec || - (tvdeadline.tv_sec == now.tv_sec && - tvdeadline.tv_usec <= now.tv_usec)) { - errno = ETIMEDOUT; - return MP_STANDARD_ERROR; - } - - /* calculate how much time is left */ - difference = (tvdeadline.tv_sec - now.tv_sec) * 1000000 + - (tvdeadline.tv_usec - now.tv_usec); - - /* check delay not too long -- maximum is 20 msecs */ - if (delay > 20000) - delay = 20000; - if (delay > difference) - delay = difference; - - /* sleep */ - tvdelay.tv_sec = delay / 1000000; - tvdelay.tv_usec = delay % 1000000; - if (select(0, NULL, NULL, NULL, &tvdelay) < 0) - return MP_STANDARD_ERROR; - - /* check for signals */ - Py_BLOCK_THREADS - res = PyErr_CheckSignals(); - Py_UNBLOCK_THREADS - - if (res) { - errno = EINTR; - return MP_EXCEPTION_HAS_BEEN_SET; - } - } + int res; + unsigned long delay, difference; + struct timeval now, tvdeadline, tvdelay; + + errno = 0; + tvdeadline.tv_sec = deadline->tv_sec; + tvdeadline.tv_usec = deadline->tv_nsec / 1000; + + for (delay = 0 ; ; delay += 1000) { + /* poll */ + if (sem_trywait(sem) == 0) + return 0; + else if (errno != EAGAIN) + return MP_STANDARD_ERROR; + + /* get current time */ + if (gettimeofday(&now, NULL) < 0) + return MP_STANDARD_ERROR; + + /* check for timeout */ + if (tvdeadline.tv_sec < now.tv_sec || + (tvdeadline.tv_sec == now.tv_sec && + tvdeadline.tv_usec <= now.tv_usec)) { + errno = ETIMEDOUT; + return MP_STANDARD_ERROR; + } + + /* calculate how much time is left */ + difference = (tvdeadline.tv_sec - now.tv_sec) * 1000000 + + (tvdeadline.tv_usec - now.tv_usec); + + /* check delay not too long -- maximum is 20 msecs */ + if (delay > 20000) + delay = 20000; + if (delay > difference) + delay = difference; + + /* sleep */ + tvdelay.tv_sec = delay / 1000000; + tvdelay.tv_usec = delay % 1000000; + if (select(0, NULL, NULL, NULL, &tvdelay) < 0) + return MP_STANDARD_ERROR; + + /* check for signals */ + Py_BLOCK_THREADS + res = PyErr_CheckSignals(); + Py_UNBLOCK_THREADS + + if (res) { + errno = EINTR; + return MP_EXCEPTION_HAS_BEEN_SET; + } + } } #endif /* !HAVE_SEM_TIMEDWAIT */ @@ -267,129 +267,129 @@ static PyObject * semlock_acquire(SemLockObject *self, PyObject *args, PyObject *kwds) { - int blocking = 1, res; - double timeout; - PyObject *timeout_obj = Py_None; - struct timespec deadline = {0}; - struct timeval now; - long sec, nsec; - - static char *kwlist[] = {"block", "timeout", NULL}; - - if (!PyArg_ParseTupleAndKeywords(args, kwds, "|iO", kwlist, - &blocking, &timeout_obj)) - return NULL; - - if (self->kind == RECURSIVE_MUTEX && ISMINE(self)) { - ++self->count; - Py_RETURN_TRUE; - } - - if (timeout_obj != Py_None) { - timeout = PyFloat_AsDouble(timeout_obj); - if (PyErr_Occurred()) - return NULL; - if (timeout < 0.0) - timeout = 0.0; - - if (gettimeofday(&now, NULL) < 0) { - PyErr_SetFromErrno(PyExc_OSError); - return NULL; - } - sec = (long) timeout; - nsec = (long) (1e9 * (timeout - sec) + 0.5); - deadline.tv_sec = now.tv_sec + sec; - deadline.tv_nsec = now.tv_usec * 1000 + nsec; - deadline.tv_sec += (deadline.tv_nsec / 1000000000); - deadline.tv_nsec %= 1000000000; - } - - do { - Py_BEGIN_ALLOW_THREADS - if (blocking && timeout_obj == Py_None) - res = sem_wait(self->handle); - else if (!blocking) - res = sem_trywait(self->handle); - else - res = sem_timedwait(self->handle, &deadline); - Py_END_ALLOW_THREADS - if (res == MP_EXCEPTION_HAS_BEEN_SET) - break; - } while (res < 0 && errno == EINTR && !PyErr_CheckSignals()); - - if (res < 0) { - if (errno == EAGAIN || errno == ETIMEDOUT) - Py_RETURN_FALSE; - else if (errno == EINTR) - return NULL; - else - return PyErr_SetFromErrno(PyExc_OSError); - } + int blocking = 1, res; + double timeout; + PyObject *timeout_obj = Py_None; + struct timespec deadline = {0}; + struct timeval now; + long sec, nsec; + + static char *kwlist[] = {"block", "timeout", NULL}; + + if (!PyArg_ParseTupleAndKeywords(args, kwds, "|iO", kwlist, + &blocking, &timeout_obj)) + return NULL; + + if (self->kind == RECURSIVE_MUTEX && ISMINE(self)) { + ++self->count; + Py_RETURN_TRUE; + } + + if (timeout_obj != Py_None) { + timeout = PyFloat_AsDouble(timeout_obj); + if (PyErr_Occurred()) + return NULL; + if (timeout < 0.0) + timeout = 0.0; + + if (gettimeofday(&now, NULL) < 0) { + PyErr_SetFromErrno(PyExc_OSError); + return NULL; + } + sec = (long) timeout; + nsec = (long) (1e9 * (timeout - sec) + 0.5); + deadline.tv_sec = now.tv_sec + sec; + deadline.tv_nsec = now.tv_usec * 1000 + nsec; + deadline.tv_sec += (deadline.tv_nsec / 1000000000); + deadline.tv_nsec %= 1000000000; + } + + do { + Py_BEGIN_ALLOW_THREADS + if (blocking && timeout_obj == Py_None) + res = sem_wait(self->handle); + else if (!blocking) + res = sem_trywait(self->handle); + else + res = sem_timedwait(self->handle, &deadline); + Py_END_ALLOW_THREADS + if (res == MP_EXCEPTION_HAS_BEEN_SET) + break; + } while (res < 0 && errno == EINTR && !PyErr_CheckSignals()); + + if (res < 0) { + if (errno == EAGAIN || errno == ETIMEDOUT) + Py_RETURN_FALSE; + else if (errno == EINTR) + return NULL; + else + return PyErr_SetFromErrno(PyExc_OSError); + } - ++self->count; - self->last_tid = PyThread_get_thread_ident(); + ++self->count; + self->last_tid = PyThread_get_thread_ident(); - Py_RETURN_TRUE; + Py_RETURN_TRUE; } static PyObject * semlock_release(SemLockObject *self, PyObject *args) { - if (self->kind == RECURSIVE_MUTEX) { - if (!ISMINE(self)) { - PyErr_SetString(PyExc_AssertionError, "attempt to " - "release recursive lock not owned " - "by thread"); - return NULL; - } - if (self->count > 1) { - --self->count; - Py_RETURN_NONE; - } - assert(self->count == 1); - } else { + if (self->kind == RECURSIVE_MUTEX) { + if (!ISMINE(self)) { + PyErr_SetString(PyExc_AssertionError, "attempt to " + "release recursive lock not owned " + "by thread"); + return NULL; + } + if (self->count > 1) { + --self->count; + Py_RETURN_NONE; + } + assert(self->count == 1); + } else { #ifdef HAVE_BROKEN_SEM_GETVALUE - /* We will only check properly the maxvalue == 1 case */ - if (self->maxvalue == 1) { - /* make sure that already locked */ - if (sem_trywait(self->handle) < 0) { - if (errno != EAGAIN) { - PyErr_SetFromErrno(PyExc_OSError); - return NULL; - } - /* it is already locked as expected */ - } else { - /* it was not locked so undo wait and raise */ - if (sem_post(self->handle) < 0) { - PyErr_SetFromErrno(PyExc_OSError); - return NULL; - } - PyErr_SetString(PyExc_ValueError, "semaphore " - "or lock released too many " - "times"); - return NULL; - } - } + /* We will only check properly the maxvalue == 1 case */ + if (self->maxvalue == 1) { + /* make sure that already locked */ + if (sem_trywait(self->handle) < 0) { + if (errno != EAGAIN) { + PyErr_SetFromErrno(PyExc_OSError); + return NULL; + } + /* it is already locked as expected */ + } else { + /* it was not locked so undo wait and raise */ + if (sem_post(self->handle) < 0) { + PyErr_SetFromErrno(PyExc_OSError); + return NULL; + } + PyErr_SetString(PyExc_ValueError, "semaphore " + "or lock released too many " + "times"); + return NULL; + } + } #else - int sval; + int sval; - /* This check is not an absolute guarantee that the semaphore - does not rise above maxvalue. */ - if (sem_getvalue(self->handle, &sval) < 0) { - return PyErr_SetFromErrno(PyExc_OSError); - } else if (sval >= self->maxvalue) { - PyErr_SetString(PyExc_ValueError, "semaphore or lock " - "released too many times"); - return NULL; - } + /* This check is not an absolute guarantee that the semaphore + does not rise above maxvalue. */ + if (sem_getvalue(self->handle, &sval) < 0) { + return PyErr_SetFromErrno(PyExc_OSError); + } else if (sval >= self->maxvalue) { + PyErr_SetString(PyExc_ValueError, "semaphore or lock " + "released too many times"); + return NULL; + } #endif - } + } - if (sem_post(self->handle) < 0) - return PyErr_SetFromErrno(PyExc_OSError); + if (sem_post(self->handle) < 0) + return PyErr_SetFromErrno(PyExc_OSError); - --self->count; - Py_RETURN_NONE; + --self->count; + Py_RETURN_NONE; } #endif /* !MS_WINDOWS */ @@ -401,111 +401,111 @@ static PyObject * newsemlockobject(PyTypeObject *type, SEM_HANDLE handle, int kind, int maxvalue) { - SemLockObject *self; + SemLockObject *self; - self = PyObject_New(SemLockObject, type); - if (!self) - return NULL; - self->handle = handle; - self->kind = kind; - self->count = 0; - self->last_tid = 0; - self->maxvalue = maxvalue; - return (PyObject*)self; + self = PyObject_New(SemLockObject, type); + if (!self) + return NULL; + self->handle = handle; + self->kind = kind; + self->count = 0; + self->last_tid = 0; + self->maxvalue = maxvalue; + return (PyObject*)self; } static PyObject * semlock_new(PyTypeObject *type, PyObject *args, PyObject *kwds) { - char buffer[256]; - SEM_HANDLE handle = SEM_FAILED; - int kind, maxvalue, value; - PyObject *result; - static char *kwlist[] = {"kind", "value", "maxvalue", NULL}; - static int counter = 0; - - if (!PyArg_ParseTupleAndKeywords(args, kwds, "iii", kwlist, - &kind, &value, &maxvalue)) - return NULL; - - if (kind != RECURSIVE_MUTEX && kind != SEMAPHORE) { - PyErr_SetString(PyExc_ValueError, "unrecognized kind"); - return NULL; - } - - PyOS_snprintf(buffer, sizeof(buffer), "/mp%d-%d", getpid(), counter++); - - SEM_CLEAR_ERROR(); - handle = SEM_CREATE(buffer, value, maxvalue); - /* On Windows we should fail if GetLastError()==ERROR_ALREADY_EXISTS */ - if (handle == SEM_FAILED || SEM_GET_LAST_ERROR() != 0) - goto failure; - - if (SEM_UNLINK(buffer) < 0) - goto failure; - - result = newsemlockobject(type, handle, kind, maxvalue); - if (!result) - goto failure; + char buffer[256]; + SEM_HANDLE handle = SEM_FAILED; + int kind, maxvalue, value; + PyObject *result; + static char *kwlist[] = {"kind", "value", "maxvalue", NULL}; + static int counter = 0; + + if (!PyArg_ParseTupleAndKeywords(args, kwds, "iii", kwlist, + &kind, &value, &maxvalue)) + return NULL; + + if (kind != RECURSIVE_MUTEX && kind != SEMAPHORE) { + PyErr_SetString(PyExc_ValueError, "unrecognized kind"); + return NULL; + } + + PyOS_snprintf(buffer, sizeof(buffer), "/mp%d-%d", getpid(), counter++); + + SEM_CLEAR_ERROR(); + handle = SEM_CREATE(buffer, value, maxvalue); + /* On Windows we should fail if GetLastError()==ERROR_ALREADY_EXISTS */ + if (handle == SEM_FAILED || SEM_GET_LAST_ERROR() != 0) + goto failure; + + if (SEM_UNLINK(buffer) < 0) + goto failure; + + result = newsemlockobject(type, handle, kind, maxvalue); + if (!result) + goto failure; - return result; + return result; failure: - if (handle != SEM_FAILED) - SEM_CLOSE(handle); - mp_SetError(NULL, MP_STANDARD_ERROR); - return NULL; + if (handle != SEM_FAILED) + SEM_CLOSE(handle); + mp_SetError(NULL, MP_STANDARD_ERROR); + return NULL; } static PyObject * semlock_rebuild(PyTypeObject *type, PyObject *args) { - SEM_HANDLE handle; - int kind, maxvalue; + SEM_HANDLE handle; + int kind, maxvalue; - if (!PyArg_ParseTuple(args, F_SEM_HANDLE "ii", - &handle, &kind, &maxvalue)) - return NULL; + if (!PyArg_ParseTuple(args, F_SEM_HANDLE "ii", + &handle, &kind, &maxvalue)) + return NULL; - return newsemlockobject(type, handle, kind, maxvalue); + return newsemlockobject(type, handle, kind, maxvalue); } static void semlock_dealloc(SemLockObject* self) { - if (self->handle != SEM_FAILED) - SEM_CLOSE(self->handle); - PyObject_Del(self); + if (self->handle != SEM_FAILED) + SEM_CLOSE(self->handle); + PyObject_Del(self); } static PyObject * semlock_count(SemLockObject *self) { - return PyInt_FromLong((long)self->count); + return PyInt_FromLong((long)self->count); } static PyObject * semlock_ismine(SemLockObject *self) { - /* only makes sense for a lock */ - return PyBool_FromLong(ISMINE(self)); + /* only makes sense for a lock */ + return PyBool_FromLong(ISMINE(self)); } static PyObject * semlock_getvalue(SemLockObject *self) { #ifdef HAVE_BROKEN_SEM_GETVALUE - PyErr_SetNone(PyExc_NotImplementedError); - return NULL; + PyErr_SetNone(PyExc_NotImplementedError); + return NULL; #else - int sval; - if (SEM_GETVALUE(self->handle, &sval) < 0) - return mp_SetError(NULL, MP_STANDARD_ERROR); - /* some posix implementations use negative numbers to indicate - the number of waiting threads */ - if (sval < 0) - sval = 0; - return PyInt_FromLong((long)sval); + int sval; + if (SEM_GETVALUE(self->handle, &sval) < 0) + return mp_SetError(NULL, MP_STANDARD_ERROR); + /* some posix implementations use negative numbers to indicate + the number of waiting threads */ + if (sval < 0) + sval = 0; + return PyInt_FromLong((long)sval); #endif } @@ -513,28 +513,28 @@ semlock_iszero(SemLockObject *self) { #ifdef HAVE_BROKEN_SEM_GETVALUE - if (sem_trywait(self->handle) < 0) { - if (errno == EAGAIN) - Py_RETURN_TRUE; - return mp_SetError(NULL, MP_STANDARD_ERROR); - } else { - if (sem_post(self->handle) < 0) - return mp_SetError(NULL, MP_STANDARD_ERROR); - Py_RETURN_FALSE; - } + if (sem_trywait(self->handle) < 0) { + if (errno == EAGAIN) + Py_RETURN_TRUE; + return mp_SetError(NULL, MP_STANDARD_ERROR); + } else { + if (sem_post(self->handle) < 0) + return mp_SetError(NULL, MP_STANDARD_ERROR); + Py_RETURN_FALSE; + } #else - int sval; - if (SEM_GETVALUE(self->handle, &sval) < 0) - return mp_SetError(NULL, MP_STANDARD_ERROR); - return PyBool_FromLong((long)sval == 0); + int sval; + if (SEM_GETVALUE(self->handle, &sval) < 0) + return mp_SetError(NULL, MP_STANDARD_ERROR); + return PyBool_FromLong((long)sval == 0); #endif } static PyObject * semlock_afterfork(SemLockObject *self) { - self->count = 0; - Py_RETURN_NONE; + self->count = 0; + Py_RETURN_NONE; } /* @@ -542,27 +542,27 @@ */ static PyMethodDef semlock_methods[] = { - {"acquire", (PyCFunction)semlock_acquire, METH_VARARGS | METH_KEYWORDS, - "acquire the semaphore/lock"}, - {"release", (PyCFunction)semlock_release, METH_NOARGS, - "release the semaphore/lock"}, + {"acquire", (PyCFunction)semlock_acquire, METH_VARARGS | METH_KEYWORDS, + "acquire the semaphore/lock"}, + {"release", (PyCFunction)semlock_release, METH_NOARGS, + "release the semaphore/lock"}, {"__enter__", (PyCFunction)semlock_acquire, METH_VARARGS | METH_KEYWORDS, - "enter the semaphore/lock"}, - {"__exit__", (PyCFunction)semlock_release, METH_VARARGS, - "exit the semaphore/lock"}, - {"_count", (PyCFunction)semlock_count, METH_NOARGS, - "num of `acquire()`s minus num of `release()`s for this process"}, - {"_is_mine", (PyCFunction)semlock_ismine, METH_NOARGS, - "whether the lock is owned by this thread"}, - {"_get_value", (PyCFunction)semlock_getvalue, METH_NOARGS, - "get the value of the semaphore"}, - {"_is_zero", (PyCFunction)semlock_iszero, METH_NOARGS, - "returns whether semaphore has value zero"}, - {"_rebuild", (PyCFunction)semlock_rebuild, METH_VARARGS | METH_CLASS, - ""}, - {"_after_fork", (PyCFunction)semlock_afterfork, METH_NOARGS, - "rezero the net acquisition count after fork()"}, - {NULL} + "enter the semaphore/lock"}, + {"__exit__", (PyCFunction)semlock_release, METH_VARARGS, + "exit the semaphore/lock"}, + {"_count", (PyCFunction)semlock_count, METH_NOARGS, + "num of `acquire()`s minus num of `release()`s for this process"}, + {"_is_mine", (PyCFunction)semlock_ismine, METH_NOARGS, + "whether the lock is owned by this thread"}, + {"_get_value", (PyCFunction)semlock_getvalue, METH_NOARGS, + "get the value of the semaphore"}, + {"_is_zero", (PyCFunction)semlock_iszero, METH_NOARGS, + "returns whether semaphore has value zero"}, + {"_rebuild", (PyCFunction)semlock_rebuild, METH_VARARGS | METH_CLASS, + ""}, + {"_after_fork", (PyCFunction)semlock_afterfork, METH_NOARGS, + "rezero the net acquisition count after fork()"}, + {NULL} }; /* @@ -570,13 +570,13 @@ */ static PyMemberDef semlock_members[] = { - {"handle", T_SEM_HANDLE, offsetof(SemLockObject, handle), READONLY, - ""}, - {"kind", T_INT, offsetof(SemLockObject, kind), READONLY, - ""}, - {"maxvalue", T_INT, offsetof(SemLockObject, maxvalue), READONLY, - ""}, - {NULL} + {"handle", T_SEM_HANDLE, offsetof(SemLockObject, handle), READONLY, + ""}, + {"kind", T_INT, offsetof(SemLockObject, kind), READONLY, + ""}, + {"maxvalue", T_INT, offsetof(SemLockObject, maxvalue), READONLY, + ""}, + {NULL} }; /* @@ -584,42 +584,42 @@ */ PyTypeObject SemLockType = { - PyVarObject_HEAD_INIT(NULL, 0) - /* tp_name */ "_multiprocessing.SemLock", - /* tp_basicsize */ sizeof(SemLockObject), - /* tp_itemsize */ 0, - /* tp_dealloc */ (destructor)semlock_dealloc, - /* tp_print */ 0, - /* tp_getattr */ 0, - /* tp_setattr */ 0, - /* tp_reserved */ 0, - /* tp_repr */ 0, - /* tp_as_number */ 0, - /* tp_as_sequence */ 0, - /* tp_as_mapping */ 0, - /* tp_hash */ 0, - /* tp_call */ 0, - /* tp_str */ 0, - /* tp_getattro */ 0, - /* tp_setattro */ 0, - /* tp_as_buffer */ 0, - /* tp_flags */ Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, - /* tp_doc */ "Semaphore/Mutex type", - /* tp_traverse */ 0, - /* tp_clear */ 0, - /* tp_richcompare */ 0, - /* tp_weaklistoffset */ 0, - /* tp_iter */ 0, - /* tp_iternext */ 0, - /* tp_methods */ semlock_methods, - /* tp_members */ semlock_members, - /* tp_getset */ 0, - /* tp_base */ 0, - /* tp_dict */ 0, - /* tp_descr_get */ 0, - /* tp_descr_set */ 0, - /* tp_dictoffset */ 0, - /* tp_init */ 0, - /* tp_alloc */ 0, - /* tp_new */ semlock_new, + PyVarObject_HEAD_INIT(NULL, 0) + /* tp_name */ "_multiprocessing.SemLock", + /* tp_basicsize */ sizeof(SemLockObject), + /* tp_itemsize */ 0, + /* tp_dealloc */ (destructor)semlock_dealloc, + /* tp_print */ 0, + /* tp_getattr */ 0, + /* tp_setattr */ 0, + /* tp_reserved */ 0, + /* tp_repr */ 0, + /* tp_as_number */ 0, + /* tp_as_sequence */ 0, + /* tp_as_mapping */ 0, + /* tp_hash */ 0, + /* tp_call */ 0, + /* tp_str */ 0, + /* tp_getattro */ 0, + /* tp_setattro */ 0, + /* tp_as_buffer */ 0, + /* tp_flags */ Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, + /* tp_doc */ "Semaphore/Mutex type", + /* tp_traverse */ 0, + /* tp_clear */ 0, + /* tp_richcompare */ 0, + /* tp_weaklistoffset */ 0, + /* tp_iter */ 0, + /* tp_iternext */ 0, + /* tp_methods */ semlock_methods, + /* tp_members */ semlock_members, + /* tp_getset */ 0, + /* tp_base */ 0, + /* tp_dict */ 0, + /* tp_descr_get */ 0, + /* tp_descr_set */ 0, + /* tp_dictoffset */ 0, + /* tp_init */ 0, + /* tp_alloc */ 0, + /* tp_new */ semlock_new, }; Modified: python/branches/release31-maint/Modules/_multiprocessing/socket_connection.c ============================================================================== --- python/branches/release31-maint/Modules/_multiprocessing/socket_connection.c (original) +++ python/branches/release31-maint/Modules/_multiprocessing/socket_connection.c Sun May 9 18:14:21 2010 @@ -25,45 +25,45 @@ static Py_ssize_t _conn_sendall(HANDLE h, char *string, size_t length) { - char *p = string; - Py_ssize_t res; + char *p = string; + Py_ssize_t res; - while (length > 0) { - res = WRITE(h, p, length); - if (res < 0) - return MP_SOCKET_ERROR; - length -= res; - p += res; - } + while (length > 0) { + res = WRITE(h, p, length); + if (res < 0) + return MP_SOCKET_ERROR; + length -= res; + p += res; + } - return MP_SUCCESS; + return MP_SUCCESS; } /* - * Receive string of exact length from file descriptor + * Receive string of exact length from file descriptor */ static Py_ssize_t _conn_recvall(HANDLE h, char *buffer, size_t length) { - size_t remaining = length; - Py_ssize_t temp; - char *p = buffer; - - while (remaining > 0) { - temp = READ(h, p, remaining); - if (temp <= 0) { - if (temp == 0) - return remaining == length ? - MP_END_OF_FILE : MP_EARLY_END_OF_FILE; - else - return temp; - } - remaining -= temp; - p += temp; - } + size_t remaining = length; + Py_ssize_t temp; + char *p = buffer; + + while (remaining > 0) { + temp = READ(h, p, remaining); + if (temp <= 0) { + if (temp == 0) + return remaining == length ? + MP_END_OF_FILE : MP_EARLY_END_OF_FILE; + else + return temp; + } + remaining -= temp; + p += temp; + } - return MP_SUCCESS; + return MP_SUCCESS; } /* @@ -73,38 +73,38 @@ static Py_ssize_t conn_send_string(ConnectionObject *conn, char *string, size_t length) { - Py_ssize_t res; - /* The "header" of the message is a 32 bit unsigned number (in - network order) which specifies the length of the "body". If - the message is shorter than about 16kb then it is quicker to - combine the "header" and the "body" of the message and send - them at once. */ - if (length < (16*1024)) { - char *message; - - message = PyMem_Malloc(length+4); - if (message == NULL) - return MP_MEMORY_ERROR; - - *(UINT32*)message = htonl((UINT32)length); - memcpy(message+4, string, length); - Py_BEGIN_ALLOW_THREADS - res = _conn_sendall(conn->handle, message, length+4); - Py_END_ALLOW_THREADS - PyMem_Free(message); - } else { - UINT32 lenbuff; - - if (length > MAX_MESSAGE_LENGTH) - return MP_BAD_MESSAGE_LENGTH; - - lenbuff = htonl((UINT32)length); - Py_BEGIN_ALLOW_THREADS - res = _conn_sendall(conn->handle, (char*)&lenbuff, 4) || - _conn_sendall(conn->handle, string, length); - Py_END_ALLOW_THREADS - } - return res; + Py_ssize_t res; + /* The "header" of the message is a 32 bit unsigned number (in + network order) which specifies the length of the "body". If + the message is shorter than about 16kb then it is quicker to + combine the "header" and the "body" of the message and send + them at once. */ + if (length < (16*1024)) { + char *message; + + message = PyMem_Malloc(length+4); + if (message == NULL) + return MP_MEMORY_ERROR; + + *(UINT32*)message = htonl((UINT32)length); + memcpy(message+4, string, length); + Py_BEGIN_ALLOW_THREADS + res = _conn_sendall(conn->handle, message, length+4); + Py_END_ALLOW_THREADS + PyMem_Free(message); + } else { + UINT32 lenbuff; + + if (length > MAX_MESSAGE_LENGTH) + return MP_BAD_MESSAGE_LENGTH; + + lenbuff = htonl((UINT32)length); + Py_BEGIN_ALLOW_THREADS + res = _conn_sendall(conn->handle, (char*)&lenbuff, 4) || + _conn_sendall(conn->handle, string, length); + Py_END_ALLOW_THREADS + } + return res; } /* @@ -114,38 +114,38 @@ */ static Py_ssize_t -conn_recv_string(ConnectionObject *conn, char *buffer, - size_t buflength, char **newbuffer, size_t maxlength) +conn_recv_string(ConnectionObject *conn, char *buffer, + size_t buflength, char **newbuffer, size_t maxlength) { - int res; - UINT32 ulength; + int res; + UINT32 ulength; - *newbuffer = NULL; + *newbuffer = NULL; - Py_BEGIN_ALLOW_THREADS - res = _conn_recvall(conn->handle, (char*)&ulength, 4); - Py_END_ALLOW_THREADS - if (res < 0) - return res; - - ulength = ntohl(ulength); - if (ulength > maxlength) - return MP_BAD_MESSAGE_LENGTH; - - if (ulength <= buflength) { - Py_BEGIN_ALLOW_THREADS - res = _conn_recvall(conn->handle, buffer, (size_t)ulength); - Py_END_ALLOW_THREADS - return res < 0 ? res : ulength; - } else { - *newbuffer = PyMem_Malloc((size_t)ulength); - if (*newbuffer == NULL) - return MP_MEMORY_ERROR; - Py_BEGIN_ALLOW_THREADS - res = _conn_recvall(conn->handle, *newbuffer, (size_t)ulength); - Py_END_ALLOW_THREADS - return res < 0 ? (Py_ssize_t)res : (Py_ssize_t)ulength; - } + Py_BEGIN_ALLOW_THREADS + res = _conn_recvall(conn->handle, (char*)&ulength, 4); + Py_END_ALLOW_THREADS + if (res < 0) + return res; + + ulength = ntohl(ulength); + if (ulength > maxlength) + return MP_BAD_MESSAGE_LENGTH; + + if (ulength <= buflength) { + Py_BEGIN_ALLOW_THREADS + res = _conn_recvall(conn->handle, buffer, (size_t)ulength); + Py_END_ALLOW_THREADS + return res < 0 ? res : ulength; + } else { + *newbuffer = PyMem_Malloc((size_t)ulength); + if (*newbuffer == NULL) + return MP_MEMORY_ERROR; + Py_BEGIN_ALLOW_THREADS + res = _conn_recvall(conn->handle, *newbuffer, (size_t)ulength); + Py_END_ALLOW_THREADS + return res < 0 ? (Py_ssize_t)res : (Py_ssize_t)ulength; + } } /* @@ -155,41 +155,41 @@ static int conn_poll(ConnectionObject *conn, double timeout, PyThreadState *_save) { - int res; - fd_set rfds; + int res; + fd_set rfds; - /* - * Verify the handle, issue 3321. Not required for windows. - */ - #ifndef MS_WINDOWS - if (((int)conn->handle) < 0 || ((int)conn->handle) >= FD_SETSIZE) { - Py_BLOCK_THREADS - PyErr_SetString(PyExc_IOError, "handle out of range in select()"); - Py_UNBLOCK_THREADS - return MP_EXCEPTION_HAS_BEEN_SET; - } - #endif - - FD_ZERO(&rfds); - FD_SET((SOCKET)conn->handle, &rfds); - - if (timeout < 0.0) { - res = select((int)conn->handle+1, &rfds, NULL, NULL, NULL); - } else { - struct timeval tv; - tv.tv_sec = (long)timeout; - tv.tv_usec = (long)((timeout - tv.tv_sec) * 1e6 + 0.5); - res = select((int)conn->handle+1, &rfds, NULL, NULL, &tv); - } - - if (res < 0) { - return MP_SOCKET_ERROR; - } else if (FD_ISSET(conn->handle, &rfds)) { - return TRUE; - } else { - assert(res == 0); - return FALSE; - } + /* + * Verify the handle, issue 3321. Not required for windows. + */ + #ifndef MS_WINDOWS + if (((int)conn->handle) < 0 || ((int)conn->handle) >= FD_SETSIZE) { + Py_BLOCK_THREADS + PyErr_SetString(PyExc_IOError, "handle out of range in select()"); + Py_UNBLOCK_THREADS + return MP_EXCEPTION_HAS_BEEN_SET; + } + #endif + + FD_ZERO(&rfds); + FD_SET((SOCKET)conn->handle, &rfds); + + if (timeout < 0.0) { + res = select((int)conn->handle+1, &rfds, NULL, NULL, NULL); + } else { + struct timeval tv; + tv.tv_sec = (long)timeout; + tv.tv_usec = (long)((timeout - tv.tv_sec) * 1e6 + 0.5); + res = select((int)conn->handle+1, &rfds, NULL, NULL, &tv); + } + + if (res < 0) { + return MP_SOCKET_ERROR; + } else if (FD_ISSET(conn->handle, &rfds)) { + return TRUE; + } else { + assert(res == 0); + return FALSE; + } } /* Modified: python/branches/release31-maint/Modules/_multiprocessing/win32_functions.c ============================================================================== --- python/branches/release31-maint/Modules/_multiprocessing/win32_functions.c (original) +++ python/branches/release31-maint/Modules/_multiprocessing/win32_functions.c Sun May 9 18:14:21 2010 @@ -19,248 +19,248 @@ static PyObject * win32_CloseHandle(PyObject *self, PyObject *args) { - HANDLE hObject; - BOOL success; + HANDLE hObject; + BOOL success; - if (!PyArg_ParseTuple(args, F_HANDLE, &hObject)) - return NULL; + if (!PyArg_ParseTuple(args, F_HANDLE, &hObject)) + return NULL; - Py_BEGIN_ALLOW_THREADS - success = CloseHandle(hObject); - Py_END_ALLOW_THREADS + Py_BEGIN_ALLOW_THREADS + success = CloseHandle(hObject); + Py_END_ALLOW_THREADS - if (!success) - return PyErr_SetFromWindowsErr(0); + if (!success) + return PyErr_SetFromWindowsErr(0); - Py_RETURN_NONE; + Py_RETURN_NONE; } static PyObject * win32_ConnectNamedPipe(PyObject *self, PyObject *args) { - HANDLE hNamedPipe; - LPOVERLAPPED lpOverlapped; - BOOL success; - - if (!PyArg_ParseTuple(args, F_HANDLE F_POINTER, - &hNamedPipe, &lpOverlapped)) - return NULL; - - Py_BEGIN_ALLOW_THREADS - success = ConnectNamedPipe(hNamedPipe, lpOverlapped); - Py_END_ALLOW_THREADS + HANDLE hNamedPipe; + LPOVERLAPPED lpOverlapped; + BOOL success; + + if (!PyArg_ParseTuple(args, F_HANDLE F_POINTER, + &hNamedPipe, &lpOverlapped)) + return NULL; + + Py_BEGIN_ALLOW_THREADS + success = ConnectNamedPipe(hNamedPipe, lpOverlapped); + Py_END_ALLOW_THREADS - if (!success) - return PyErr_SetFromWindowsErr(0); + if (!success) + return PyErr_SetFromWindowsErr(0); - Py_RETURN_NONE; + Py_RETURN_NONE; } static PyObject * win32_CreateFile(PyObject *self, PyObject *args) { - LPCTSTR lpFileName; - DWORD dwDesiredAccess; - DWORD dwShareMode; - LPSECURITY_ATTRIBUTES lpSecurityAttributes; - DWORD dwCreationDisposition; - DWORD dwFlagsAndAttributes; - HANDLE hTemplateFile; - HANDLE handle; - - if (!PyArg_ParseTuple(args, "s" F_DWORD F_DWORD F_POINTER - F_DWORD F_DWORD F_HANDLE, - &lpFileName, &dwDesiredAccess, &dwShareMode, - &lpSecurityAttributes, &dwCreationDisposition, - &dwFlagsAndAttributes, &hTemplateFile)) - return NULL; - - Py_BEGIN_ALLOW_THREADS - handle = CreateFile(lpFileName, dwDesiredAccess, - dwShareMode, lpSecurityAttributes, - dwCreationDisposition, - dwFlagsAndAttributes, hTemplateFile); - Py_END_ALLOW_THREADS + LPCTSTR lpFileName; + DWORD dwDesiredAccess; + DWORD dwShareMode; + LPSECURITY_ATTRIBUTES lpSecurityAttributes; + DWORD dwCreationDisposition; + DWORD dwFlagsAndAttributes; + HANDLE hTemplateFile; + HANDLE handle; + + if (!PyArg_ParseTuple(args, "s" F_DWORD F_DWORD F_POINTER + F_DWORD F_DWORD F_HANDLE, + &lpFileName, &dwDesiredAccess, &dwShareMode, + &lpSecurityAttributes, &dwCreationDisposition, + &dwFlagsAndAttributes, &hTemplateFile)) + return NULL; + + Py_BEGIN_ALLOW_THREADS + handle = CreateFile(lpFileName, dwDesiredAccess, + dwShareMode, lpSecurityAttributes, + dwCreationDisposition, + dwFlagsAndAttributes, hTemplateFile); + Py_END_ALLOW_THREADS - if (handle == INVALID_HANDLE_VALUE) - return PyErr_SetFromWindowsErr(0); + if (handle == INVALID_HANDLE_VALUE) + return PyErr_SetFromWindowsErr(0); - return Py_BuildValue(F_HANDLE, handle); + return Py_BuildValue(F_HANDLE, handle); } static PyObject * win32_CreateNamedPipe(PyObject *self, PyObject *args) { - LPCTSTR lpName; - DWORD dwOpenMode; - DWORD dwPipeMode; - DWORD nMaxInstances; - DWORD nOutBufferSize; - DWORD nInBufferSize; - DWORD nDefaultTimeOut; - LPSECURITY_ATTRIBUTES lpSecurityAttributes; - HANDLE handle; - - if (!PyArg_ParseTuple(args, "s" F_DWORD F_DWORD F_DWORD - F_DWORD F_DWORD F_DWORD F_POINTER, - &lpName, &dwOpenMode, &dwPipeMode, - &nMaxInstances, &nOutBufferSize, - &nInBufferSize, &nDefaultTimeOut, - &lpSecurityAttributes)) - return NULL; - - Py_BEGIN_ALLOW_THREADS - handle = CreateNamedPipe(lpName, dwOpenMode, dwPipeMode, - nMaxInstances, nOutBufferSize, - nInBufferSize, nDefaultTimeOut, - lpSecurityAttributes); - Py_END_ALLOW_THREADS + LPCTSTR lpName; + DWORD dwOpenMode; + DWORD dwPipeMode; + DWORD nMaxInstances; + DWORD nOutBufferSize; + DWORD nInBufferSize; + DWORD nDefaultTimeOut; + LPSECURITY_ATTRIBUTES lpSecurityAttributes; + HANDLE handle; + + if (!PyArg_ParseTuple(args, "s" F_DWORD F_DWORD F_DWORD + F_DWORD F_DWORD F_DWORD F_POINTER, + &lpName, &dwOpenMode, &dwPipeMode, + &nMaxInstances, &nOutBufferSize, + &nInBufferSize, &nDefaultTimeOut, + &lpSecurityAttributes)) + return NULL; + + Py_BEGIN_ALLOW_THREADS + handle = CreateNamedPipe(lpName, dwOpenMode, dwPipeMode, + nMaxInstances, nOutBufferSize, + nInBufferSize, nDefaultTimeOut, + lpSecurityAttributes); + Py_END_ALLOW_THREADS - if (handle == INVALID_HANDLE_VALUE) - return PyErr_SetFromWindowsErr(0); + if (handle == INVALID_HANDLE_VALUE) + return PyErr_SetFromWindowsErr(0); - return Py_BuildValue(F_HANDLE, handle); + return Py_BuildValue(F_HANDLE, handle); } static PyObject * win32_ExitProcess(PyObject *self, PyObject *args) { - UINT uExitCode; + UINT uExitCode; - if (!PyArg_ParseTuple(args, "I", &uExitCode)) - return NULL; + if (!PyArg_ParseTuple(args, "I", &uExitCode)) + return NULL; - #if defined(Py_DEBUG) - SetErrorMode(SEM_FAILCRITICALERRORS|SEM_NOALIGNMENTFAULTEXCEPT|SEM_NOGPFAULTERRORBOX|SEM_NOOPENFILEERRORBOX); - _CrtSetReportMode(_CRT_ASSERT, _CRTDBG_MODE_DEBUG); - #endif + #if defined(Py_DEBUG) + SetErrorMode(SEM_FAILCRITICALERRORS|SEM_NOALIGNMENTFAULTEXCEPT|SEM_NOGPFAULTERRORBOX|SEM_NOOPENFILEERRORBOX); + _CrtSetReportMode(_CRT_ASSERT, _CRTDBG_MODE_DEBUG); + #endif - ExitProcess(uExitCode); + ExitProcess(uExitCode); - return NULL; + return NULL; } static PyObject * win32_GetLastError(PyObject *self, PyObject *args) { - return Py_BuildValue(F_DWORD, GetLastError()); + return Py_BuildValue(F_DWORD, GetLastError()); } static PyObject * win32_OpenProcess(PyObject *self, PyObject *args) { - DWORD dwDesiredAccess; - BOOL bInheritHandle; - DWORD dwProcessId; - HANDLE handle; - - if (!PyArg_ParseTuple(args, F_DWORD "i" F_DWORD, - &dwDesiredAccess, &bInheritHandle, &dwProcessId)) - return NULL; - - handle = OpenProcess(dwDesiredAccess, bInheritHandle, dwProcessId); - if (handle == NULL) - return PyErr_SetFromWindowsErr(0); + DWORD dwDesiredAccess; + BOOL bInheritHandle; + DWORD dwProcessId; + HANDLE handle; + + if (!PyArg_ParseTuple(args, F_DWORD "i" F_DWORD, + &dwDesiredAccess, &bInheritHandle, &dwProcessId)) + return NULL; + + handle = OpenProcess(dwDesiredAccess, bInheritHandle, dwProcessId); + if (handle == NULL) + return PyErr_SetFromWindowsErr(0); - return Py_BuildValue(F_HANDLE, handle); + return Py_BuildValue(F_HANDLE, handle); } static PyObject * win32_SetNamedPipeHandleState(PyObject *self, PyObject *args) { - HANDLE hNamedPipe; - PyObject *oArgs[3]; - DWORD dwArgs[3], *pArgs[3] = {NULL, NULL, NULL}; - int i; - - if (!PyArg_ParseTuple(args, F_HANDLE "OOO", - &hNamedPipe, &oArgs[0], &oArgs[1], &oArgs[2])) - return NULL; - - PyErr_Clear(); - - for (i = 0 ; i < 3 ; i++) { - if (oArgs[i] != Py_None) { - dwArgs[i] = PyLong_AsUnsignedLongMask(oArgs[i]); - if (PyErr_Occurred()) - return NULL; - pArgs[i] = &dwArgs[i]; - } - } + HANDLE hNamedPipe; + PyObject *oArgs[3]; + DWORD dwArgs[3], *pArgs[3] = {NULL, NULL, NULL}; + int i; + + if (!PyArg_ParseTuple(args, F_HANDLE "OOO", + &hNamedPipe, &oArgs[0], &oArgs[1], &oArgs[2])) + return NULL; + + PyErr_Clear(); + + for (i = 0 ; i < 3 ; i++) { + if (oArgs[i] != Py_None) { + dwArgs[i] = PyLong_AsUnsignedLongMask(oArgs[i]); + if (PyErr_Occurred()) + return NULL; + pArgs[i] = &dwArgs[i]; + } + } - if (!SetNamedPipeHandleState(hNamedPipe, pArgs[0], pArgs[1], pArgs[2])) - return PyErr_SetFromWindowsErr(0); + if (!SetNamedPipeHandleState(hNamedPipe, pArgs[0], pArgs[1], pArgs[2])) + return PyErr_SetFromWindowsErr(0); - Py_RETURN_NONE; + Py_RETURN_NONE; } static PyObject * win32_WaitNamedPipe(PyObject *self, PyObject *args) { - LPCTSTR lpNamedPipeName; - DWORD nTimeOut; - BOOL success; + LPCTSTR lpNamedPipeName; + DWORD nTimeOut; + BOOL success; - if (!PyArg_ParseTuple(args, "s" F_DWORD, &lpNamedPipeName, &nTimeOut)) - return NULL; + if (!PyArg_ParseTuple(args, "s" F_DWORD, &lpNamedPipeName, &nTimeOut)) + return NULL; - Py_BEGIN_ALLOW_THREADS - success = WaitNamedPipe(lpNamedPipeName, nTimeOut); - Py_END_ALLOW_THREADS + Py_BEGIN_ALLOW_THREADS + success = WaitNamedPipe(lpNamedPipeName, nTimeOut); + Py_END_ALLOW_THREADS - if (!success) - return PyErr_SetFromWindowsErr(0); + if (!success) + return PyErr_SetFromWindowsErr(0); - Py_RETURN_NONE; + Py_RETURN_NONE; } static PyMethodDef win32_methods[] = { - WIN32_FUNCTION(CloseHandle), - WIN32_FUNCTION(GetLastError), - WIN32_FUNCTION(OpenProcess), - WIN32_FUNCTION(ExitProcess), - WIN32_FUNCTION(ConnectNamedPipe), - WIN32_FUNCTION(CreateFile), - WIN32_FUNCTION(CreateNamedPipe), - WIN32_FUNCTION(SetNamedPipeHandleState), - WIN32_FUNCTION(WaitNamedPipe), - {NULL} + WIN32_FUNCTION(CloseHandle), + WIN32_FUNCTION(GetLastError), + WIN32_FUNCTION(OpenProcess), + WIN32_FUNCTION(ExitProcess), + WIN32_FUNCTION(ConnectNamedPipe), + WIN32_FUNCTION(CreateFile), + WIN32_FUNCTION(CreateNamedPipe), + WIN32_FUNCTION(SetNamedPipeHandleState), + WIN32_FUNCTION(WaitNamedPipe), + {NULL} }; PyTypeObject Win32Type = { - PyVarObject_HEAD_INIT(NULL, 0) + PyVarObject_HEAD_INIT(NULL, 0) }; PyObject * create_win32_namespace(void) { - Win32Type.tp_name = "_multiprocessing.win32"; - Win32Type.tp_methods = win32_methods; - if (PyType_Ready(&Win32Type) < 0) - return NULL; - Py_INCREF(&Win32Type); - - WIN32_CONSTANT(F_DWORD, ERROR_ALREADY_EXISTS); - WIN32_CONSTANT(F_DWORD, ERROR_PIPE_BUSY); - WIN32_CONSTANT(F_DWORD, ERROR_PIPE_CONNECTED); - WIN32_CONSTANT(F_DWORD, ERROR_SEM_TIMEOUT); - WIN32_CONSTANT(F_DWORD, GENERIC_READ); - WIN32_CONSTANT(F_DWORD, GENERIC_WRITE); - WIN32_CONSTANT(F_DWORD, INFINITE); - WIN32_CONSTANT(F_DWORD, NMPWAIT_WAIT_FOREVER); - WIN32_CONSTANT(F_DWORD, OPEN_EXISTING); - WIN32_CONSTANT(F_DWORD, PIPE_ACCESS_DUPLEX); - WIN32_CONSTANT(F_DWORD, PIPE_ACCESS_INBOUND); - WIN32_CONSTANT(F_DWORD, PIPE_READMODE_MESSAGE); - WIN32_CONSTANT(F_DWORD, PIPE_TYPE_MESSAGE); - WIN32_CONSTANT(F_DWORD, PIPE_UNLIMITED_INSTANCES); - WIN32_CONSTANT(F_DWORD, PIPE_WAIT); - WIN32_CONSTANT(F_DWORD, PROCESS_ALL_ACCESS); + Win32Type.tp_name = "_multiprocessing.win32"; + Win32Type.tp_methods = win32_methods; + if (PyType_Ready(&Win32Type) < 0) + return NULL; + Py_INCREF(&Win32Type); + + WIN32_CONSTANT(F_DWORD, ERROR_ALREADY_EXISTS); + WIN32_CONSTANT(F_DWORD, ERROR_PIPE_BUSY); + WIN32_CONSTANT(F_DWORD, ERROR_PIPE_CONNECTED); + WIN32_CONSTANT(F_DWORD, ERROR_SEM_TIMEOUT); + WIN32_CONSTANT(F_DWORD, GENERIC_READ); + WIN32_CONSTANT(F_DWORD, GENERIC_WRITE); + WIN32_CONSTANT(F_DWORD, INFINITE); + WIN32_CONSTANT(F_DWORD, NMPWAIT_WAIT_FOREVER); + WIN32_CONSTANT(F_DWORD, OPEN_EXISTING); + WIN32_CONSTANT(F_DWORD, PIPE_ACCESS_DUPLEX); + WIN32_CONSTANT(F_DWORD, PIPE_ACCESS_INBOUND); + WIN32_CONSTANT(F_DWORD, PIPE_READMODE_MESSAGE); + WIN32_CONSTANT(F_DWORD, PIPE_TYPE_MESSAGE); + WIN32_CONSTANT(F_DWORD, PIPE_UNLIMITED_INSTANCES); + WIN32_CONSTANT(F_DWORD, PIPE_WAIT); + WIN32_CONSTANT(F_DWORD, PROCESS_ALL_ACCESS); - WIN32_CONSTANT("i", NULL); + WIN32_CONSTANT("i", NULL); - return (PyObject*)&Win32Type; + return (PyObject*)&Win32Type; } Modified: python/branches/release31-maint/Modules/_randommodule.c ============================================================================== --- python/branches/release31-maint/Modules/_randommodule.c (original) +++ python/branches/release31-maint/Modules/_randommodule.c Sun May 9 18:14:21 2010 @@ -2,23 +2,23 @@ /* ------------------------------------------------------------------ The code in this module was based on a download from: - http://www.math.keio.ac.jp/~matumoto/MT2002/emt19937ar.html + http://www.math.keio.ac.jp/~matumoto/MT2002/emt19937ar.html It was modified in 2002 by Raymond Hettinger as follows: - * the principal computational lines untouched except for tabbing. + * the principal computational lines untouched except for tabbing. - * renamed genrand_res53() to random_random() and wrapped - in python calling/return code. + * renamed genrand_res53() to random_random() and wrapped + in python calling/return code. - * genrand_int32() and the helper functions, init_genrand() - and init_by_array(), were declared static, wrapped in - Python calling/return code. also, their global data - references were replaced with structure references. - - * unused functions from the original were deleted. - new, original C python code was added to implement the - Random() interface. + * genrand_int32() and the helper functions, init_genrand() + and init_by_array(), were declared static, wrapped in + Python calling/return code. also, their global data + references were replaced with structure references. + + * unused functions from the original were deleted. + new, original C python code was added to implement the + Random() interface. The following are the verbatim comments from the original code: @@ -36,15 +36,15 @@ are met: 1. Redistributions of source code must retain the above copyright - notice, this list of conditions and the following disclaimer. + 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. + 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. + 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 @@ -67,24 +67,24 @@ /* ---------------------------------------------------------------*/ #include "Python.h" -#include /* for seeding to current time */ +#include /* for seeding to current time */ /* Period parameters -- These are all magic. Don't change. */ #define N 624 #define M 397 -#define MATRIX_A 0x9908b0dfUL /* constant vector a */ +#define MATRIX_A 0x9908b0dfUL /* constant vector a */ #define UPPER_MASK 0x80000000UL /* most significant w-r bits */ #define LOWER_MASK 0x7fffffffUL /* least significant r bits */ typedef struct { - PyObject_HEAD - unsigned long state[N]; - int index; + PyObject_HEAD + unsigned long state[N]; + int index; } RandomObject; static PyTypeObject Random_Type; -#define RandomObject_Check(v) (Py_TYPE(v) == &Random_Type) +#define RandomObject_Check(v) (Py_TYPE(v) == &Random_Type) /* Random methods */ @@ -94,28 +94,28 @@ static unsigned long genrand_int32(RandomObject *self) { - unsigned long y; - static unsigned long mag01[2]={0x0UL, MATRIX_A}; - /* mag01[x] = x * MATRIX_A for x=0,1 */ - unsigned long *mt; - - mt = self->state; - if (self->index >= N) { /* generate N words at one time */ - int kk; - - for (kk=0;kk> 1) ^ mag01[y & 0x1UL]; - } - for (;kk> 1) ^ mag01[y & 0x1UL]; - } - y = (mt[N-1]&UPPER_MASK)|(mt[0]&LOWER_MASK); - mt[N-1] = mt[M-1] ^ (y >> 1) ^ mag01[y & 0x1UL]; + unsigned long y; + static unsigned long mag01[2]={0x0UL, MATRIX_A}; + /* mag01[x] = x * MATRIX_A for x=0,1 */ + unsigned long *mt; + + mt = self->state; + if (self->index >= N) { /* generate N words at one time */ + int kk; + + for (kk=0;kk> 1) ^ mag01[y & 0x1UL]; + } + for (;kk> 1) ^ mag01[y & 0x1UL]; + } + y = (mt[N-1]&UPPER_MASK)|(mt[0]&LOWER_MASK); + mt[N-1] = mt[M-1] ^ (y >> 1) ^ mag01[y & 0x1UL]; - self->index = 0; - } + self->index = 0; + } y = mt[self->index++]; y ^= (y >> 11); @@ -137,31 +137,31 @@ static PyObject * random_random(RandomObject *self) { - unsigned long a=genrand_int32(self)>>5, b=genrand_int32(self)>>6; - return PyFloat_FromDouble((a*67108864.0+b)*(1.0/9007199254740992.0)); + unsigned long a=genrand_int32(self)>>5, b=genrand_int32(self)>>6; + return PyFloat_FromDouble((a*67108864.0+b)*(1.0/9007199254740992.0)); } /* initializes mt[N] with a seed */ static void init_genrand(RandomObject *self, unsigned long s) { - int mti; - unsigned long *mt; + int mti; + unsigned long *mt; - mt = self->state; - mt[0]= s & 0xffffffffUL; - for (mti=1; mti> 30)) + mti); - /* See Knuth TAOCP Vol2. 3rd Ed. P.106 for multiplier. */ - /* In the previous versions, MSBs of the seed affect */ - /* only MSBs of the array mt[]. */ - /* 2002/01/09 modified by Makoto Matsumoto */ - mt[mti] &= 0xffffffffUL; - /* for >32 bit machines */ - } - self->index = mti; - return; + mt = self->state; + mt[0]= s & 0xffffffffUL; + for (mti=1; mti> 30)) + mti); + /* See Knuth TAOCP Vol2. 3rd Ed. P.106 for multiplier. */ + /* In the previous versions, MSBs of the seed affect */ + /* only MSBs of the array mt[]. */ + /* 2002/01/09 modified by Makoto Matsumoto */ + mt[mti] &= 0xffffffffUL; + /* for >32 bit machines */ + } + self->index = mti; + return; } /* initialize by an array with array-length */ @@ -170,28 +170,28 @@ static PyObject * init_by_array(RandomObject *self, unsigned long init_key[], unsigned long key_length) { - unsigned int i, j, k; /* was signed in the original code. RDH 12/16/2002 */ - unsigned long *mt; + unsigned int i, j, k; /* was signed in the original code. RDH 12/16/2002 */ + unsigned long *mt; - mt = self->state; - init_genrand(self, 19650218UL); - i=1; j=0; - k = (N>key_length ? N : key_length); - for (; k; k--) { - mt[i] = (mt[i] ^ ((mt[i-1] ^ (mt[i-1] >> 30)) * 1664525UL)) - + init_key[j] + j; /* non linear */ - mt[i] &= 0xffffffffUL; /* for WORDSIZE > 32 machines */ - i++; j++; - if (i>=N) { mt[0] = mt[N-1]; i=1; } - if (j>=key_length) j=0; - } - for (k=N-1; k; k--) { - mt[i] = (mt[i] ^ ((mt[i-1] ^ (mt[i-1] >> 30)) * 1566083941UL)) - - i; /* non linear */ - mt[i] &= 0xffffffffUL; /* for WORDSIZE > 32 machines */ - i++; - if (i>=N) { mt[0] = mt[N-1]; i=1; } - } + mt = self->state; + init_genrand(self, 19650218UL); + i=1; j=0; + k = (N>key_length ? N : key_length); + for (; k; k--) { + mt[i] = (mt[i] ^ ((mt[i-1] ^ (mt[i-1] >> 30)) * 1664525UL)) + + init_key[j] + j; /* non linear */ + mt[i] &= 0xffffffffUL; /* for WORDSIZE > 32 machines */ + i++; j++; + if (i>=N) { mt[0] = mt[N-1]; i=1; } + if (j>=key_length) j=0; + } + for (k=N-1; k; k--) { + mt[i] = (mt[i] ^ ((mt[i-1] ^ (mt[i-1] >> 30)) * 1566083941UL)) + - i; /* non linear */ + mt[i] &= 0xffffffffUL; /* for WORDSIZE > 32 machines */ + i++; + if (i>=N) { mt[0] = mt[N-1]; i=1; } + } mt[0] = 0x80000000UL; /* MSB is 1; assuring non-zero initial array */ Py_INCREF(Py_None); @@ -206,291 +206,291 @@ static PyObject * random_seed(RandomObject *self, PyObject *args) { - PyObject *result = NULL; /* guilty until proved innocent */ - PyObject *masklower = NULL; - PyObject *thirtytwo = NULL; - PyObject *n = NULL; - unsigned long *key = NULL; - unsigned long keymax; /* # of allocated slots in key */ - unsigned long keyused; /* # of used slots in key */ - int err; - - PyObject *arg = NULL; - - if (!PyArg_UnpackTuple(args, "seed", 0, 1, &arg)) - return NULL; - - if (arg == NULL || arg == Py_None) { - time_t now; - - time(&now); - init_genrand(self, (unsigned long)now); - Py_INCREF(Py_None); - return Py_None; - } - /* If the arg is an int or long, use its absolute value; else use - * the absolute value of its hash code. - */ - if (PyLong_Check(arg)) - n = PyNumber_Absolute(arg); - else { - long hash = PyObject_Hash(arg); - if (hash == -1) - goto Done; - n = PyLong_FromUnsignedLong((unsigned long)hash); - } - if (n == NULL) - goto Done; - - /* Now split n into 32-bit chunks, from the right. Each piece is - * stored into key, which has a capacity of keymax chunks, of which - * keyused are filled. Alas, the repeated shifting makes this a - * quadratic-time algorithm; we'd really like to use - * _PyLong_AsByteArray here, but then we'd have to break into the - * long representation to figure out how big an array was needed - * in advance. - */ - keymax = 8; /* arbitrary; grows later if needed */ - keyused = 0; - key = (unsigned long *)PyMem_Malloc(keymax * sizeof(*key)); - if (key == NULL) - goto Done; - - masklower = PyLong_FromUnsignedLong(0xffffffffU); - if (masklower == NULL) - goto Done; - thirtytwo = PyLong_FromLong(32L); - if (thirtytwo == NULL) - goto Done; - while ((err=PyObject_IsTrue(n))) { - PyObject *newn; - PyObject *pychunk; - unsigned long chunk; - - if (err == -1) - goto Done; - pychunk = PyNumber_And(n, masklower); - if (pychunk == NULL) - goto Done; - chunk = PyLong_AsUnsignedLong(pychunk); - Py_DECREF(pychunk); - if (chunk == (unsigned long)-1 && PyErr_Occurred()) - goto Done; - newn = PyNumber_Rshift(n, thirtytwo); - if (newn == NULL) - goto Done; - Py_DECREF(n); - n = newn; - if (keyused >= keymax) { - unsigned long bigger = keymax << 1; - if ((bigger >> 1) != keymax) { - PyErr_NoMemory(); - goto Done; - } - key = (unsigned long *)PyMem_Realloc(key, - bigger * sizeof(*key)); - if (key == NULL) - goto Done; - keymax = bigger; - } - assert(keyused < keymax); - key[keyused++] = chunk; - } - - if (keyused == 0) - key[keyused++] = 0UL; - result = init_by_array(self, key, keyused); + PyObject *result = NULL; /* guilty until proved innocent */ + PyObject *masklower = NULL; + PyObject *thirtytwo = NULL; + PyObject *n = NULL; + unsigned long *key = NULL; + unsigned long keymax; /* # of allocated slots in key */ + unsigned long keyused; /* # of used slots in key */ + int err; + + PyObject *arg = NULL; + + if (!PyArg_UnpackTuple(args, "seed", 0, 1, &arg)) + return NULL; + + if (arg == NULL || arg == Py_None) { + time_t now; + + time(&now); + init_genrand(self, (unsigned long)now); + Py_INCREF(Py_None); + return Py_None; + } + /* If the arg is an int or long, use its absolute value; else use + * the absolute value of its hash code. + */ + if (PyLong_Check(arg)) + n = PyNumber_Absolute(arg); + else { + long hash = PyObject_Hash(arg); + if (hash == -1) + goto Done; + n = PyLong_FromUnsignedLong((unsigned long)hash); + } + if (n == NULL) + goto Done; + + /* Now split n into 32-bit chunks, from the right. Each piece is + * stored into key, which has a capacity of keymax chunks, of which + * keyused are filled. Alas, the repeated shifting makes this a + * quadratic-time algorithm; we'd really like to use + * _PyLong_AsByteArray here, but then we'd have to break into the + * long representation to figure out how big an array was needed + * in advance. + */ + keymax = 8; /* arbitrary; grows later if needed */ + keyused = 0; + key = (unsigned long *)PyMem_Malloc(keymax * sizeof(*key)); + if (key == NULL) + goto Done; + + masklower = PyLong_FromUnsignedLong(0xffffffffU); + if (masklower == NULL) + goto Done; + thirtytwo = PyLong_FromLong(32L); + if (thirtytwo == NULL) + goto Done; + while ((err=PyObject_IsTrue(n))) { + PyObject *newn; + PyObject *pychunk; + unsigned long chunk; + + if (err == -1) + goto Done; + pychunk = PyNumber_And(n, masklower); + if (pychunk == NULL) + goto Done; + chunk = PyLong_AsUnsignedLong(pychunk); + Py_DECREF(pychunk); + if (chunk == (unsigned long)-1 && PyErr_Occurred()) + goto Done; + newn = PyNumber_Rshift(n, thirtytwo); + if (newn == NULL) + goto Done; + Py_DECREF(n); + n = newn; + if (keyused >= keymax) { + unsigned long bigger = keymax << 1; + if ((bigger >> 1) != keymax) { + PyErr_NoMemory(); + goto Done; + } + key = (unsigned long *)PyMem_Realloc(key, + bigger * sizeof(*key)); + if (key == NULL) + goto Done; + keymax = bigger; + } + assert(keyused < keymax); + key[keyused++] = chunk; + } + + if (keyused == 0) + key[keyused++] = 0UL; + result = init_by_array(self, key, keyused); Done: - Py_XDECREF(masklower); - Py_XDECREF(thirtytwo); - Py_XDECREF(n); - PyMem_Free(key); - return result; + Py_XDECREF(masklower); + Py_XDECREF(thirtytwo); + Py_XDECREF(n); + PyMem_Free(key); + return result; } static PyObject * random_getstate(RandomObject *self) { - PyObject *state; - PyObject *element; - int i; - - state = PyTuple_New(N+1); - if (state == NULL) - return NULL; - for (i=0; istate[i]); - if (element == NULL) - goto Fail; - PyTuple_SET_ITEM(state, i, element); - } - element = PyLong_FromLong((long)(self->index)); - if (element == NULL) - goto Fail; - PyTuple_SET_ITEM(state, i, element); - return state; + PyObject *state; + PyObject *element; + int i; + + state = PyTuple_New(N+1); + if (state == NULL) + return NULL; + for (i=0; istate[i]); + if (element == NULL) + goto Fail; + PyTuple_SET_ITEM(state, i, element); + } + element = PyLong_FromLong((long)(self->index)); + if (element == NULL) + goto Fail; + PyTuple_SET_ITEM(state, i, element); + return state; Fail: - Py_DECREF(state); - return NULL; + Py_DECREF(state); + return NULL; } static PyObject * random_setstate(RandomObject *self, PyObject *state) { - int i; - unsigned long element; - long index; - - if (!PyTuple_Check(state)) { - PyErr_SetString(PyExc_TypeError, - "state vector must be a tuple"); - return NULL; - } - if (PyTuple_Size(state) != N+1) { - PyErr_SetString(PyExc_ValueError, - "state vector is the wrong size"); - return NULL; - } - - for (i=0; istate[i] = element & 0xffffffffUL; /* Make sure we get sane state */ - } - - index = PyLong_AsLong(PyTuple_GET_ITEM(state, i)); - if (index == -1 && PyErr_Occurred()) - return NULL; - self->index = (int)index; + int i; + unsigned long element; + long index; + + if (!PyTuple_Check(state)) { + PyErr_SetString(PyExc_TypeError, + "state vector must be a tuple"); + return NULL; + } + if (PyTuple_Size(state) != N+1) { + PyErr_SetString(PyExc_ValueError, + "state vector is the wrong size"); + return NULL; + } + + for (i=0; istate[i] = element & 0xffffffffUL; /* Make sure we get sane state */ + } + + index = PyLong_AsLong(PyTuple_GET_ITEM(state, i)); + if (index == -1 && PyErr_Occurred()) + return NULL; + self->index = (int)index; - Py_INCREF(Py_None); - return Py_None; + Py_INCREF(Py_None); + return Py_None; } static PyObject * random_getrandbits(RandomObject *self, PyObject *args) { - int k, i, bytes; - unsigned long r; - unsigned char *bytearray; - PyObject *result; - - if (!PyArg_ParseTuple(args, "i:getrandbits", &k)) - return NULL; - - if (k <= 0) { - PyErr_SetString(PyExc_ValueError, - "number of bits must be greater than zero"); - return NULL; - } - - bytes = ((k - 1) / 32 + 1) * 4; - bytearray = (unsigned char *)PyMem_Malloc(bytes); - if (bytearray == NULL) { - PyErr_NoMemory(); - return NULL; - } - - /* Fill-out whole words, byte-by-byte to avoid endianness issues */ - for (i=0 ; i>= (32 - k); - bytearray[i+0] = (unsigned char)r; - bytearray[i+1] = (unsigned char)(r >> 8); - bytearray[i+2] = (unsigned char)(r >> 16); - bytearray[i+3] = (unsigned char)(r >> 24); - } - - /* little endian order to match bytearray assignment order */ - result = _PyLong_FromByteArray(bytearray, bytes, 1, 0); - PyMem_Free(bytearray); - return result; + int k, i, bytes; + unsigned long r; + unsigned char *bytearray; + PyObject *result; + + if (!PyArg_ParseTuple(args, "i:getrandbits", &k)) + return NULL; + + if (k <= 0) { + PyErr_SetString(PyExc_ValueError, + "number of bits must be greater than zero"); + return NULL; + } + + bytes = ((k - 1) / 32 + 1) * 4; + bytearray = (unsigned char *)PyMem_Malloc(bytes); + if (bytearray == NULL) { + PyErr_NoMemory(); + return NULL; + } + + /* Fill-out whole words, byte-by-byte to avoid endianness issues */ + for (i=0 ; i>= (32 - k); + bytearray[i+0] = (unsigned char)r; + bytearray[i+1] = (unsigned char)(r >> 8); + bytearray[i+2] = (unsigned char)(r >> 16); + bytearray[i+3] = (unsigned char)(r >> 24); + } + + /* little endian order to match bytearray assignment order */ + result = _PyLong_FromByteArray(bytearray, bytes, 1, 0); + PyMem_Free(bytearray); + return result; } static PyObject * random_new(PyTypeObject *type, PyObject *args, PyObject *kwds) { - RandomObject *self; - PyObject *tmp; + RandomObject *self; + PyObject *tmp; - if (type == &Random_Type && !_PyArg_NoKeywords("Random()", kwds)) - return NULL; + if (type == &Random_Type && !_PyArg_NoKeywords("Random()", kwds)) + return NULL; - self = (RandomObject *)type->tp_alloc(type, 0); - if (self == NULL) - return NULL; - tmp = random_seed(self, args); - if (tmp == NULL) { - Py_DECREF(self); - return NULL; - } - Py_DECREF(tmp); - return (PyObject *)self; + self = (RandomObject *)type->tp_alloc(type, 0); + if (self == NULL) + return NULL; + tmp = random_seed(self, args); + if (tmp == NULL) { + Py_DECREF(self); + return NULL; + } + Py_DECREF(tmp); + return (PyObject *)self; } static PyMethodDef random_methods[] = { - {"random", (PyCFunction)random_random, METH_NOARGS, - PyDoc_STR("random() -> x in the interval [0, 1).")}, - {"seed", (PyCFunction)random_seed, METH_VARARGS, - PyDoc_STR("seed([n]) -> None. Defaults to current time.")}, - {"getstate", (PyCFunction)random_getstate, METH_NOARGS, - PyDoc_STR("getstate() -> tuple containing the current state.")}, - {"setstate", (PyCFunction)random_setstate, METH_O, - PyDoc_STR("setstate(state) -> None. Restores generator state.")}, - {"getrandbits", (PyCFunction)random_getrandbits, METH_VARARGS, - PyDoc_STR("getrandbits(k) -> x. Generates a long int with " - "k random bits.")}, - {NULL, NULL} /* sentinel */ + {"random", (PyCFunction)random_random, METH_NOARGS, + PyDoc_STR("random() -> x in the interval [0, 1).")}, + {"seed", (PyCFunction)random_seed, METH_VARARGS, + PyDoc_STR("seed([n]) -> None. Defaults to current time.")}, + {"getstate", (PyCFunction)random_getstate, METH_NOARGS, + PyDoc_STR("getstate() -> tuple containing the current state.")}, + {"setstate", (PyCFunction)random_setstate, METH_O, + PyDoc_STR("setstate(state) -> None. Restores generator state.")}, + {"getrandbits", (PyCFunction)random_getrandbits, METH_VARARGS, + PyDoc_STR("getrandbits(k) -> x. Generates a long int with " + "k random bits.")}, + {NULL, NULL} /* sentinel */ }; PyDoc_STRVAR(random_doc, "Random() -> create a random number generator with its own internal state."); static PyTypeObject Random_Type = { - PyVarObject_HEAD_INIT(NULL, 0) - "_random.Random", /*tp_name*/ - sizeof(RandomObject), /*tp_basicsize*/ - 0, /*tp_itemsize*/ - /* methods */ - 0, /*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_BASETYPE, /*tp_flags*/ - random_doc, /*tp_doc*/ - 0, /*tp_traverse*/ - 0, /*tp_clear*/ - 0, /*tp_richcompare*/ - 0, /*tp_weaklistoffset*/ - 0, /*tp_iter*/ - 0, /*tp_iternext*/ - random_methods, /*tp_methods*/ - 0, /*tp_members*/ - 0, /*tp_getset*/ - 0, /*tp_base*/ - 0, /*tp_dict*/ - 0, /*tp_descr_get*/ - 0, /*tp_descr_set*/ - 0, /*tp_dictoffset*/ - 0, /*tp_init*/ - 0, /*tp_alloc*/ - random_new, /*tp_new*/ - PyObject_Free, /*tp_free*/ - 0, /*tp_is_gc*/ + PyVarObject_HEAD_INIT(NULL, 0) + "_random.Random", /*tp_name*/ + sizeof(RandomObject), /*tp_basicsize*/ + 0, /*tp_itemsize*/ + /* methods */ + 0, /*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_BASETYPE, /*tp_flags*/ + random_doc, /*tp_doc*/ + 0, /*tp_traverse*/ + 0, /*tp_clear*/ + 0, /*tp_richcompare*/ + 0, /*tp_weaklistoffset*/ + 0, /*tp_iter*/ + 0, /*tp_iternext*/ + random_methods, /*tp_methods*/ + 0, /*tp_members*/ + 0, /*tp_getset*/ + 0, /*tp_base*/ + 0, /*tp_dict*/ + 0, /*tp_descr_get*/ + 0, /*tp_descr_set*/ + 0, /*tp_dictoffset*/ + 0, /*tp_init*/ + 0, /*tp_alloc*/ + random_new, /*tp_new*/ + PyObject_Free, /*tp_free*/ + 0, /*tp_is_gc*/ }; PyDoc_STRVAR(module_doc, @@ -498,28 +498,28 @@ static struct PyModuleDef _randommodule = { - PyModuleDef_HEAD_INIT, - "_random", - module_doc, - -1, - NULL, - NULL, - NULL, - NULL, - NULL + PyModuleDef_HEAD_INIT, + "_random", + module_doc, + -1, + NULL, + NULL, + NULL, + NULL, + NULL }; PyMODINIT_FUNC PyInit__random(void) { - PyObject *m; + PyObject *m; - if (PyType_Ready(&Random_Type) < 0) - return NULL; - m = PyModule_Create(&_randommodule); - if (m == NULL) - return NULL; - Py_INCREF(&Random_Type); - PyModule_AddObject(m, "Random", (PyObject *)&Random_Type); - return m; + if (PyType_Ready(&Random_Type) < 0) + return NULL; + m = PyModule_Create(&_randommodule); + if (m == NULL) + return NULL; + Py_INCREF(&Random_Type); + PyModule_AddObject(m, "Random", (PyObject *)&Random_Type); + return m; } Modified: python/branches/release31-maint/Modules/_scproxy.c ============================================================================== --- python/branches/release31-maint/Modules/_scproxy.c (original) +++ python/branches/release31-maint/Modules/_scproxy.c Sun May 9 18:14:21 2010 @@ -5,167 +5,167 @@ #include #include -static int32_t +static int32_t cfnum_to_int32(CFNumberRef num) { - int32_t result; + int32_t result; - CFNumberGetValue(num, kCFNumberSInt32Type, &result); - return result; + CFNumberGetValue(num, kCFNumberSInt32Type, &result); + return result; } static PyObject* cfstring_to_pystring(CFStringRef ref) { - const char* s; + const char* s; - s = CFStringGetCStringPtr(ref, kCFStringEncodingUTF8); - if (s) { - return PyUnicode_DecodeUTF8( - s, strlen(s), NULL); - - } else { - CFIndex len = CFStringGetLength(ref); - Boolean ok; - PyObject* result; - char* buf; - - buf = PyMem_Malloc(len*4); - if (buf == NULL) { - PyErr_NoMemory(); - return NULL; - } - - ok = CFStringGetCString(ref, - buf, len * 4, - kCFStringEncodingUTF8); - if (!ok) { - PyMem_Free(buf); - return NULL; - } else { - result = PyUnicode_DecodeUTF8( - buf, strlen(buf), NULL); - PyMem_Free(buf); - } - return result; - } + s = CFStringGetCStringPtr(ref, kCFStringEncodingUTF8); + if (s) { + return PyUnicode_DecodeUTF8( + s, strlen(s), NULL); + + } else { + CFIndex len = CFStringGetLength(ref); + Boolean ok; + PyObject* result; + char* buf; + + buf = PyMem_Malloc(len*4); + if (buf == NULL) { + PyErr_NoMemory(); + return NULL; + } + + ok = CFStringGetCString(ref, + buf, len * 4, + kCFStringEncodingUTF8); + if (!ok) { + PyMem_Free(buf); + return NULL; + } else { + result = PyUnicode_DecodeUTF8( + buf, strlen(buf), NULL); + PyMem_Free(buf); + } + return result; + } } static PyObject* get_proxy_settings(PyObject* mod __attribute__((__unused__))) { - CFDictionaryRef proxyDict = NULL; - CFNumberRef aNum = NULL; - CFArrayRef anArray = NULL; - PyObject* result = NULL; - PyObject* v; - int r; - - proxyDict = SCDynamicStoreCopyProxies(NULL); - if (!proxyDict) { - Py_INCREF(Py_None); - return Py_None; - } - - result = PyDict_New(); - if (result == NULL) goto error; - - if (&kSCPropNetProxiesExcludeSimpleHostnames != NULL) { - aNum = CFDictionaryGetValue(proxyDict, - kSCPropNetProxiesExcludeSimpleHostnames); - if (aNum == NULL) { - v = PyBool_FromLong(1); - } else { - v = PyBool_FromLong(cfnum_to_int32(aNum)); - } - } else { - v = PyBool_FromLong(1); - } - - if (v == NULL) goto error; - - r = PyDict_SetItemString(result, "exclude_simple", v); - Py_DECREF(v); v = NULL; - if (r == -1) goto error; - - anArray = CFDictionaryGetValue(proxyDict, - kSCPropNetProxiesExceptionsList); - if (anArray != NULL) { - CFIndex len = CFArrayGetCount(anArray); - CFIndex i; - v = PyTuple_New(len); - if (v == NULL) goto error; - - r = PyDict_SetItemString(result, "exceptions", v); - Py_DECREF(v); - if (r == -1) goto error; - - for (i = 0; i < len; i++) { - CFStringRef aString = NULL; - - aString = CFArrayGetValueAtIndex(anArray, i); - if (aString == NULL) { - PyTuple_SetItem(v, i, Py_None); - Py_INCREF(Py_None); - } else { - PyObject* t = cfstring_to_pystring(aString); - if (!t) { - PyTuple_SetItem(v, i, Py_None); - Py_INCREF(Py_None); - } else { - PyTuple_SetItem(v, i, t); - } - } - } - } + CFDictionaryRef proxyDict = NULL; + CFNumberRef aNum = NULL; + CFArrayRef anArray = NULL; + PyObject* result = NULL; + PyObject* v; + int r; + + proxyDict = SCDynamicStoreCopyProxies(NULL); + if (!proxyDict) { + Py_INCREF(Py_None); + return Py_None; + } + + result = PyDict_New(); + if (result == NULL) goto error; + + if (&kSCPropNetProxiesExcludeSimpleHostnames != NULL) { + aNum = CFDictionaryGetValue(proxyDict, + kSCPropNetProxiesExcludeSimpleHostnames); + if (aNum == NULL) { + v = PyBool_FromLong(1); + } else { + v = PyBool_FromLong(cfnum_to_int32(aNum)); + } + } else { + v = PyBool_FromLong(1); + } + + if (v == NULL) goto error; + + r = PyDict_SetItemString(result, "exclude_simple", v); + Py_DECREF(v); v = NULL; + if (r == -1) goto error; + + anArray = CFDictionaryGetValue(proxyDict, + kSCPropNetProxiesExceptionsList); + if (anArray != NULL) { + CFIndex len = CFArrayGetCount(anArray); + CFIndex i; + v = PyTuple_New(len); + if (v == NULL) goto error; + + r = PyDict_SetItemString(result, "exceptions", v); + Py_DECREF(v); + if (r == -1) goto error; + + for (i = 0; i < len; i++) { + CFStringRef aString = NULL; + + aString = CFArrayGetValueAtIndex(anArray, i); + if (aString == NULL) { + PyTuple_SetItem(v, i, Py_None); + Py_INCREF(Py_None); + } else { + PyObject* t = cfstring_to_pystring(aString); + if (!t) { + PyTuple_SetItem(v, i, Py_None); + Py_INCREF(Py_None); + } else { + PyTuple_SetItem(v, i, t); + } + } + } + } - CFRelease(proxyDict); - return result; + CFRelease(proxyDict); + return result; error: - if (proxyDict) CFRelease(proxyDict); - Py_XDECREF(result); - return NULL; + if (proxyDict) CFRelease(proxyDict); + Py_XDECREF(result); + return NULL; } static int set_proxy(PyObject* proxies, char* proto, CFDictionaryRef proxyDict, - CFStringRef enabledKey, - CFStringRef hostKey, CFStringRef portKey) + CFStringRef enabledKey, + CFStringRef hostKey, CFStringRef portKey) { - CFNumberRef aNum; + CFNumberRef aNum; - aNum = CFDictionaryGetValue(proxyDict, enabledKey); - if (aNum && cfnum_to_int32(aNum)) { - CFStringRef hostString; - - hostString = CFDictionaryGetValue(proxyDict, hostKey); - aNum = CFDictionaryGetValue(proxyDict, portKey); - - if (hostString) { - int r; - PyObject* h = cfstring_to_pystring(hostString); - PyObject* v; - if (h) { - if (aNum) { - int32_t port = cfnum_to_int32(aNum); - v = PyUnicode_FromFormat("http://%U:%ld", - h, (long)port); - } else { - v = PyUnicode_FromFormat("http://%U", h); - } - Py_DECREF(h); - if (!v) return -1; - r = PyDict_SetItemString(proxies, proto, - v); - Py_DECREF(v); - return r; - } - } + aNum = CFDictionaryGetValue(proxyDict, enabledKey); + if (aNum && cfnum_to_int32(aNum)) { + CFStringRef hostString; + + hostString = CFDictionaryGetValue(proxyDict, hostKey); + aNum = CFDictionaryGetValue(proxyDict, portKey); + + if (hostString) { + int r; + PyObject* h = cfstring_to_pystring(hostString); + PyObject* v; + if (h) { + if (aNum) { + int32_t port = cfnum_to_int32(aNum); + v = PyUnicode_FromFormat("http://%U:%ld", + h, (long)port); + } else { + v = PyUnicode_FromFormat("http://%U", h); + } + Py_DECREF(h); + if (!v) return -1; + r = PyDict_SetItemString(proxies, proto, + v); + Py_DECREF(v); + return r; + } + } - } - return 0; + } + return 0; } @@ -173,75 +173,75 @@ static PyObject* get_proxies(PyObject* mod __attribute__((__unused__))) { - PyObject* result = NULL; - int r; - CFDictionaryRef proxyDict = NULL; - - proxyDict = SCDynamicStoreCopyProxies(NULL); - if (proxyDict == NULL) { - return PyDict_New(); - } - - result = PyDict_New(); - if (result == NULL) goto error; - - r = set_proxy(result, "http", proxyDict, - kSCPropNetProxiesHTTPEnable, - kSCPropNetProxiesHTTPProxy, - kSCPropNetProxiesHTTPPort); - if (r == -1) goto error; - r = set_proxy(result, "https", proxyDict, - kSCPropNetProxiesHTTPSEnable, - kSCPropNetProxiesHTTPSProxy, - kSCPropNetProxiesHTTPSPort); - if (r == -1) goto error; - r = set_proxy(result, "ftp", proxyDict, - kSCPropNetProxiesFTPEnable, - kSCPropNetProxiesFTPProxy, - kSCPropNetProxiesFTPPort); - if (r == -1) goto error; - r = set_proxy(result, "gopher", proxyDict, - kSCPropNetProxiesGopherEnable, - kSCPropNetProxiesGopherProxy, - kSCPropNetProxiesGopherPort); - if (r == -1) goto error; + PyObject* result = NULL; + int r; + CFDictionaryRef proxyDict = NULL; + + proxyDict = SCDynamicStoreCopyProxies(NULL); + if (proxyDict == NULL) { + return PyDict_New(); + } + + result = PyDict_New(); + if (result == NULL) goto error; + + r = set_proxy(result, "http", proxyDict, + kSCPropNetProxiesHTTPEnable, + kSCPropNetProxiesHTTPProxy, + kSCPropNetProxiesHTTPPort); + if (r == -1) goto error; + r = set_proxy(result, "https", proxyDict, + kSCPropNetProxiesHTTPSEnable, + kSCPropNetProxiesHTTPSProxy, + kSCPropNetProxiesHTTPSPort); + if (r == -1) goto error; + r = set_proxy(result, "ftp", proxyDict, + kSCPropNetProxiesFTPEnable, + kSCPropNetProxiesFTPProxy, + kSCPropNetProxiesFTPPort); + if (r == -1) goto error; + r = set_proxy(result, "gopher", proxyDict, + kSCPropNetProxiesGopherEnable, + kSCPropNetProxiesGopherProxy, + kSCPropNetProxiesGopherPort); + if (r == -1) goto error; - CFRelease(proxyDict); - return result; + CFRelease(proxyDict); + return result; error: - if (proxyDict) CFRelease(proxyDict); - Py_XDECREF(result); - return NULL; + if (proxyDict) CFRelease(proxyDict); + Py_XDECREF(result); + return NULL; } static PyMethodDef mod_methods[] = { - { - "_get_proxy_settings", - (PyCFunction)get_proxy_settings, - METH_NOARGS, - NULL, - }, - { - "_get_proxies", - (PyCFunction)get_proxies, - METH_NOARGS, - NULL, - }, - { 0, 0, 0, 0 } + { + "_get_proxy_settings", + (PyCFunction)get_proxy_settings, + METH_NOARGS, + NULL, + }, + { + "_get_proxies", + (PyCFunction)get_proxies, + METH_NOARGS, + NULL, + }, + { 0, 0, 0, 0 } }; static struct PyModuleDef mod_module = { - PyModuleDef_HEAD_INIT, - "_scproxy", - NULL, - -1, - mod_methods, - NULL, - NULL, - NULL, - NULL + PyModuleDef_HEAD_INIT, + "_scproxy", + NULL, + -1, + mod_methods, + NULL, + NULL, + NULL, + NULL }; @@ -249,10 +249,10 @@ extern "C" { #endif -PyObject* +PyObject* PyInit__scproxy(void) { - return PyModule_Create(&mod_module); + return PyModule_Create(&mod_module); } #ifdef __cplusplus Modified: python/branches/release31-maint/Modules/_sqlite/module.c ============================================================================== --- python/branches/release31-maint/Modules/_sqlite/module.c (original) +++ python/branches/release31-maint/Modules/_sqlite/module.c Sun May 9 18:14:21 2010 @@ -64,7 +64,7 @@ if (!PyArg_ParseTupleAndKeywords(args, kwargs, "s|diOiOi", kwlist, &database, &timeout, &detect_types, &isolation_level, &check_same_thread, &factory, &cached_statements)) { - return NULL; + return NULL; } if (factory == NULL) { @@ -93,7 +93,7 @@ if (!PyArg_ParseTupleAndKeywords(args, kwargs, "s", kwlist, &statement)) { - return NULL; + return NULL; } if (sqlite3_complete(statement)) { @@ -122,7 +122,7 @@ if (!PyArg_ParseTupleAndKeywords(args, kwargs, "i", kwlist, &do_enable)) { - return NULL; + return NULL; } rc = sqlite3_enable_shared_cache(do_enable); @@ -302,15 +302,15 @@ static struct PyModuleDef _sqlite3module = { - PyModuleDef_HEAD_INIT, - "_sqlite3", - NULL, - -1, - module_methods, - NULL, - NULL, - NULL, - NULL + PyModuleDef_HEAD_INIT, + "_sqlite3", + NULL, + -1, + module_methods, + NULL, + NULL, + NULL, + NULL }; PyMODINIT_FUNC PyInit__sqlite3(void) @@ -329,7 +329,7 @@ (pysqlite_statement_setup_types() < 0) || (pysqlite_prepare_protocol_setup_types() < 0) ) { - Py_DECREF(module); + Py_DECREF(module); return NULL; } @@ -448,7 +448,7 @@ /* Original comment from _bsddb.c in the Python core. This is also still * needed nowadays for Python 2.3/2.4. - * + * * PyEval_InitThreads is called here due to a quirk in python 1.5 * - 2.2.1 (at least) according to Russell Williamson : * The global interpreter lock is not initialized until the first @@ -467,8 +467,8 @@ if (PyErr_Occurred()) { PyErr_SetString(PyExc_ImportError, MODULE_NAME ": init failed"); - Py_DECREF(module); - module = NULL; + Py_DECREF(module); + module = NULL; } return module; } Modified: python/branches/release31-maint/Modules/_struct.c ============================================================================== --- python/branches/release31-maint/Modules/_struct.c (original) +++ python/branches/release31-maint/Modules/_struct.c Sun May 9 18:14:21 2010 @@ -14,30 +14,30 @@ /* The translation function for each format character is table driven */ typedef struct _formatdef { - char format; - Py_ssize_t size; - Py_ssize_t alignment; - PyObject* (*unpack)(const char *, - const struct _formatdef *); - int (*pack)(char *, PyObject *, - const struct _formatdef *); + char format; + Py_ssize_t size; + Py_ssize_t alignment; + PyObject* (*unpack)(const char *, + const struct _formatdef *); + int (*pack)(char *, PyObject *, + const struct _formatdef *); } formatdef; typedef struct _formatcode { - const struct _formatdef *fmtdef; - Py_ssize_t offset; - Py_ssize_t size; + const struct _formatdef *fmtdef; + Py_ssize_t offset; + Py_ssize_t size; } formatcode; /* Struct object interface */ typedef struct { - PyObject_HEAD - Py_ssize_t s_size; - Py_ssize_t s_len; - formatcode *s_codes; - PyObject *s_format; - PyObject *weakreflist; /* List of weak references */ + PyObject_HEAD + Py_ssize_t s_size; + Py_ssize_t s_len; + formatcode *s_codes; + PyObject *s_format; + PyObject *weakreflist; /* List of weak references */ } PyStructObject; @@ -94,15 +94,15 @@ static PyObject * get_pylong(PyObject *v) { - assert(v != NULL); - if (!PyLong_Check(v)) { - PyErr_SetString(StructError, - "required argument is not an integer"); - return NULL; - } + assert(v != NULL); + if (!PyLong_Check(v)) { + PyErr_SetString(StructError, + "required argument is not an integer"); + return NULL; + } - Py_INCREF(v); - return v; + Py_INCREF(v); + return v; } /* Helper routine to get a C long and raise the appropriate error if it isn't @@ -111,22 +111,22 @@ static int get_long(PyObject *v, long *p) { - long x; + long x; - if (!PyLong_Check(v)) { - PyErr_SetString(StructError, - "required argument is not an integer"); - return -1; - } - x = PyLong_AsLong(v); - if (x == -1 && PyErr_Occurred()) { - if (PyErr_ExceptionMatches(PyExc_OverflowError)) - PyErr_SetString(StructError, - "argument out of range"); - return -1; - } - *p = x; - return 0; + if (!PyLong_Check(v)) { + PyErr_SetString(StructError, + "required argument is not an integer"); + return -1; + } + x = PyLong_AsLong(v); + if (x == -1 && PyErr_Occurred()) { + if (PyErr_ExceptionMatches(PyExc_OverflowError)) + PyErr_SetString(StructError, + "argument out of range"); + return -1; + } + *p = x; + return 0; } @@ -136,22 +136,22 @@ static int get_ulong(PyObject *v, unsigned long *p) { - unsigned long x; + unsigned long x; - if (!PyLong_Check(v)) { - PyErr_SetString(StructError, - "required argument is not an integer"); - return -1; - } - x = PyLong_AsUnsignedLong(v); - if (x == (unsigned long)-1 && PyErr_Occurred()) { - if (PyErr_ExceptionMatches(PyExc_OverflowError)) - PyErr_SetString(StructError, - "argument out of range"); - return -1; - } - *p = x; - return 0; + if (!PyLong_Check(v)) { + PyErr_SetString(StructError, + "required argument is not an integer"); + return -1; + } + x = PyLong_AsUnsignedLong(v); + if (x == (unsigned long)-1 && PyErr_Occurred()) { + if (PyErr_ExceptionMatches(PyExc_OverflowError)) + PyErr_SetString(StructError, + "argument out of range"); + return -1; + } + *p = x; + return 0; } #endif /* PY_STRUCT_OVERFLOW_MASKING */ @@ -162,21 +162,21 @@ static int get_longlong(PyObject *v, PY_LONG_LONG *p) { - PY_LONG_LONG x; - if (!PyLong_Check(v)) { - PyErr_SetString(StructError, - "required argument is not an integer"); - return -1; - } - x = PyLong_AsLongLong(v); - if (x == -1 && PyErr_Occurred()) { - if (PyErr_ExceptionMatches(PyExc_OverflowError)) - PyErr_SetString(StructError, - "argument out of range"); - return -1; - } - *p = x; - return 0; + PY_LONG_LONG x; + if (!PyLong_Check(v)) { + PyErr_SetString(StructError, + "required argument is not an integer"); + return -1; + } + x = PyLong_AsLongLong(v); + if (x == -1 && PyErr_Occurred()) { + if (PyErr_ExceptionMatches(PyExc_OverflowError)) + PyErr_SetString(StructError, + "argument out of range"); + return -1; + } + *p = x; + return 0; } /* Same, but handling native unsigned long long. */ @@ -184,21 +184,21 @@ static int get_ulonglong(PyObject *v, unsigned PY_LONG_LONG *p) { - unsigned PY_LONG_LONG x; - if (!PyLong_Check(v)) { - PyErr_SetString(StructError, - "required argument is not an integer"); - return -1; - } - x = PyLong_AsUnsignedLongLong(v); - if (x == -1 && PyErr_Occurred()) { - if (PyErr_ExceptionMatches(PyExc_OverflowError)) - PyErr_SetString(StructError, - "argument out of range"); - return -1; - } - *p = x; - return 0; + unsigned PY_LONG_LONG x; + if (!PyLong_Check(v)) { + PyErr_SetString(StructError, + "required argument is not an integer"); + return -1; + } + x = PyLong_AsUnsignedLongLong(v); + if (x == -1 && PyErr_Occurred()) { + if (PyErr_ExceptionMatches(PyExc_OverflowError)) + PyErr_SetString(StructError, + "argument out of range"); + return -1; + } + *p = x; + return 0; } #endif @@ -211,57 +211,57 @@ static PyObject * unpack_float(const char *p, /* start of 4-byte string */ - int le) /* true for little-endian, false for big-endian */ + int le) /* true for little-endian, false for big-endian */ { - double x; + double x; - x = _PyFloat_Unpack4((unsigned char *)p, le); - if (x == -1.0 && PyErr_Occurred()) - return NULL; - return PyFloat_FromDouble(x); + x = _PyFloat_Unpack4((unsigned char *)p, le); + if (x == -1.0 && PyErr_Occurred()) + return NULL; + return PyFloat_FromDouble(x); } static PyObject * unpack_double(const char *p, /* start of 8-byte string */ - int le) /* true for little-endian, false for big-endian */ + int le) /* true for little-endian, false for big-endian */ { - double x; + double x; - x = _PyFloat_Unpack8((unsigned char *)p, le); - if (x == -1.0 && PyErr_Occurred()) - return NULL; - return PyFloat_FromDouble(x); + x = _PyFloat_Unpack8((unsigned char *)p, le); + if (x == -1.0 && PyErr_Occurred()) + return NULL; + return PyFloat_FromDouble(x); } /* Helper to format the range error exceptions */ static int _range_error(const formatdef *f, int is_unsigned) { - /* ulargest is the largest unsigned value with f->size bytes. - * Note that the simpler: - * ((size_t)1 << (f->size * 8)) - 1 - * doesn't work when f->size == sizeof(size_t) because C doesn't - * define what happens when a left shift count is >= the number of - * bits in the integer being shifted; e.g., on some boxes it doesn't - * shift at all when they're equal. - */ - const size_t ulargest = (size_t)-1 >> ((SIZEOF_SIZE_T - f->size)*8); - assert(f->size >= 1 && f->size <= SIZEOF_SIZE_T); - if (is_unsigned) - PyErr_Format(StructError, - "'%c' format requires 0 <= number <= %zu", - f->format, - ulargest); - else { - const Py_ssize_t largest = (Py_ssize_t)(ulargest >> 1); - PyErr_Format(StructError, - "'%c' format requires %zd <= number <= %zd", - f->format, - ~ largest, - largest); - } + /* ulargest is the largest unsigned value with f->size bytes. + * Note that the simpler: + * ((size_t)1 << (f->size * 8)) - 1 + * doesn't work when f->size == sizeof(size_t) because C doesn't + * define what happens when a left shift count is >= the number of + * bits in the integer being shifted; e.g., on some boxes it doesn't + * shift at all when they're equal. + */ + const size_t ulargest = (size_t)-1 >> ((SIZEOF_SIZE_T - f->size)*8); + assert(f->size >= 1 && f->size <= SIZEOF_SIZE_T); + if (is_unsigned) + PyErr_Format(StructError, + "'%c' format requires 0 <= number <= %zu", + f->format, + ulargest); + else { + const Py_ssize_t largest = (Py_ssize_t)(ulargest >> 1); + PyErr_Format(StructError, + "'%c' format requires %zd <= number <= %zd", + f->format, + ~ largest, + largest); + } - return -1; + return -1; } @@ -288,75 +288,75 @@ static PyObject * nu_char(const char *p, const formatdef *f) { - return PyBytes_FromStringAndSize(p, 1); + return PyBytes_FromStringAndSize(p, 1); } static PyObject * nu_byte(const char *p, const formatdef *f) { - return PyLong_FromLong((long) *(signed char *)p); + return PyLong_FromLong((long) *(signed char *)p); } static PyObject * nu_ubyte(const char *p, const formatdef *f) { - return PyLong_FromLong((long) *(unsigned char *)p); + return PyLong_FromLong((long) *(unsigned char *)p); } static PyObject * nu_short(const char *p, const formatdef *f) { - short x; - memcpy((char *)&x, p, sizeof x); - return PyLong_FromLong((long)x); + short x; + memcpy((char *)&x, p, sizeof x); + return PyLong_FromLong((long)x); } static PyObject * nu_ushort(const char *p, const formatdef *f) { - unsigned short x; - memcpy((char *)&x, p, sizeof x); - return PyLong_FromLong((long)x); + unsigned short x; + memcpy((char *)&x, p, sizeof x); + return PyLong_FromLong((long)x); } static PyObject * nu_int(const char *p, const formatdef *f) { - int x; - memcpy((char *)&x, p, sizeof x); - return PyLong_FromLong((long)x); + int x; + memcpy((char *)&x, p, sizeof x); + return PyLong_FromLong((long)x); } static PyObject * nu_uint(const char *p, const formatdef *f) { - unsigned int x; - memcpy((char *)&x, p, sizeof x); + unsigned int x; + memcpy((char *)&x, p, sizeof x); #if (SIZEOF_LONG > SIZEOF_INT) - return PyLong_FromLong((long)x); + return PyLong_FromLong((long)x); #else - if (x <= ((unsigned int)LONG_MAX)) - return PyLong_FromLong((long)x); - return PyLong_FromUnsignedLong((unsigned long)x); + if (x <= ((unsigned int)LONG_MAX)) + return PyLong_FromLong((long)x); + return PyLong_FromUnsignedLong((unsigned long)x); #endif } static PyObject * nu_long(const char *p, const formatdef *f) { - long x; - memcpy((char *)&x, p, sizeof x); - return PyLong_FromLong(x); + long x; + memcpy((char *)&x, p, sizeof x); + return PyLong_FromLong(x); } static PyObject * nu_ulong(const char *p, const formatdef *f) { - unsigned long x; - memcpy((char *)&x, p, sizeof x); - if (x <= LONG_MAX) - return PyLong_FromLong((long)x); - return PyLong_FromUnsignedLong(x); + unsigned long x; + memcpy((char *)&x, p, sizeof x); + if (x <= LONG_MAX) + return PyLong_FromLong((long)x); + return PyLong_FromUnsignedLong(x); } /* Native mode doesn't support q or Q unless the platform C supports @@ -367,21 +367,21 @@ static PyObject * nu_longlong(const char *p, const formatdef *f) { - PY_LONG_LONG x; - memcpy((char *)&x, p, sizeof x); - if (x >= LONG_MIN && x <= LONG_MAX) - return PyLong_FromLong(Py_SAFE_DOWNCAST(x, PY_LONG_LONG, long)); - return PyLong_FromLongLong(x); + PY_LONG_LONG x; + memcpy((char *)&x, p, sizeof x); + if (x >= LONG_MIN && x <= LONG_MAX) + return PyLong_FromLong(Py_SAFE_DOWNCAST(x, PY_LONG_LONG, long)); + return PyLong_FromLongLong(x); } static PyObject * nu_ulonglong(const char *p, const formatdef *f) { - unsigned PY_LONG_LONG x; - memcpy((char *)&x, p, sizeof x); - if (x <= LONG_MAX) - return PyLong_FromLong(Py_SAFE_DOWNCAST(x, unsigned PY_LONG_LONG, long)); - return PyLong_FromUnsignedLongLong(x); + unsigned PY_LONG_LONG x; + memcpy((char *)&x, p, sizeof x); + if (x <= LONG_MAX) + return PyLong_FromLong(Py_SAFE_DOWNCAST(x, unsigned PY_LONG_LONG, long)); + return PyLong_FromUnsignedLongLong(x); } #endif @@ -389,168 +389,168 @@ static PyObject * nu_bool(const char *p, const formatdef *f) { - BOOL_TYPE x; - memcpy((char *)&x, p, sizeof x); - return PyBool_FromLong(x != 0); + BOOL_TYPE x; + memcpy((char *)&x, p, sizeof x); + return PyBool_FromLong(x != 0); } static PyObject * nu_float(const char *p, const formatdef *f) { - float x; - memcpy((char *)&x, p, sizeof x); - return PyFloat_FromDouble((double)x); + float x; + memcpy((char *)&x, p, sizeof x); + return PyFloat_FromDouble((double)x); } static PyObject * nu_double(const char *p, const formatdef *f) { - double x; - memcpy((char *)&x, p, sizeof x); - return PyFloat_FromDouble(x); + double x; + memcpy((char *)&x, p, sizeof x); + return PyFloat_FromDouble(x); } static PyObject * nu_void_p(const char *p, const formatdef *f) { - void *x; - memcpy((char *)&x, p, sizeof x); - return PyLong_FromVoidPtr(x); + void *x; + memcpy((char *)&x, p, sizeof x); + return PyLong_FromVoidPtr(x); } static int np_byte(char *p, PyObject *v, const formatdef *f) { - long x; - if (get_long(v, &x) < 0) - return -1; - if (x < -128 || x > 127){ - PyErr_SetString(StructError, - "byte format requires -128 <= number <= 127"); - return -1; - } - *p = (char)x; - return 0; + long x; + if (get_long(v, &x) < 0) + return -1; + if (x < -128 || x > 127){ + PyErr_SetString(StructError, + "byte format requires -128 <= number <= 127"); + return -1; + } + *p = (char)x; + return 0; } static int np_ubyte(char *p, PyObject *v, const formatdef *f) { - long x; - if (get_long(v, &x) < 0) - return -1; - if (x < 0 || x > 255){ - PyErr_SetString(StructError, - "ubyte format requires 0 <= number <= 255"); - return -1; - } - *p = (char)x; - return 0; + long x; + if (get_long(v, &x) < 0) + return -1; + if (x < 0 || x > 255){ + PyErr_SetString(StructError, + "ubyte format requires 0 <= number <= 255"); + return -1; + } + *p = (char)x; + return 0; } static int np_char(char *p, PyObject *v, const formatdef *f) { - if (PyUnicode_Check(v)) { - v = _PyUnicode_AsDefaultEncodedString(v, NULL); - if (v == NULL) - return -1; - } - if (!PyBytes_Check(v) || PyBytes_Size(v) != 1) { - PyErr_SetString(StructError, - "char format requires bytes or string of length 1"); - return -1; - } - *p = *PyBytes_AsString(v); - return 0; + if (PyUnicode_Check(v)) { + v = _PyUnicode_AsDefaultEncodedString(v, NULL); + if (v == NULL) + return -1; + } + if (!PyBytes_Check(v) || PyBytes_Size(v) != 1) { + PyErr_SetString(StructError, + "char format requires bytes or string of length 1"); + return -1; + } + *p = *PyBytes_AsString(v); + return 0; } static int np_short(char *p, PyObject *v, const formatdef *f) { - long x; - short y; - if (get_long(v, &x) < 0) - return -1; - if (x < SHRT_MIN || x > SHRT_MAX){ - PyErr_SetString(StructError, - "short format requires " STRINGIFY(SHRT_MIN) - " <= number <= " STRINGIFY(SHRT_MAX)); - return -1; - } - y = (short)x; - memcpy(p, (char *)&y, sizeof y); - return 0; + long x; + short y; + if (get_long(v, &x) < 0) + return -1; + if (x < SHRT_MIN || x > SHRT_MAX){ + PyErr_SetString(StructError, + "short format requires " STRINGIFY(SHRT_MIN) + " <= number <= " STRINGIFY(SHRT_MAX)); + return -1; + } + y = (short)x; + memcpy(p, (char *)&y, sizeof y); + return 0; } static int np_ushort(char *p, PyObject *v, const formatdef *f) { - long x; - unsigned short y; - if (get_long(v, &x) < 0) - return -1; - if (x < 0 || x > USHRT_MAX){ - PyErr_SetString(StructError, - "ushort format requires 0 <= number <= " STRINGIFY(USHRT_MAX)); - return -1; - } - y = (unsigned short)x; - memcpy(p, (char *)&y, sizeof y); - return 0; + long x; + unsigned short y; + if (get_long(v, &x) < 0) + return -1; + if (x < 0 || x > USHRT_MAX){ + PyErr_SetString(StructError, + "ushort format requires 0 <= number <= " STRINGIFY(USHRT_MAX)); + return -1; + } + y = (unsigned short)x; + memcpy(p, (char *)&y, sizeof y); + return 0; } static int np_int(char *p, PyObject *v, const formatdef *f) { - long x; - int y; - if (get_long(v, &x) < 0) - return -1; + long x; + int y; + if (get_long(v, &x) < 0) + return -1; #if (SIZEOF_LONG > SIZEOF_INT) - if ((x < ((long)INT_MIN)) || (x > ((long)INT_MAX))) - RANGE_ERROR(x, f, 0, -1); + if ((x < ((long)INT_MIN)) || (x > ((long)INT_MAX))) + RANGE_ERROR(x, f, 0, -1); #endif - y = (int)x; - memcpy(p, (char *)&y, sizeof y); - return 0; + y = (int)x; + memcpy(p, (char *)&y, sizeof y); + return 0; } static int np_uint(char *p, PyObject *v, const formatdef *f) { - unsigned long x; - unsigned int y; - if (get_ulong(v, &x) < 0) - return -1; - y = (unsigned int)x; + unsigned long x; + unsigned int y; + if (get_ulong(v, &x) < 0) + return -1; + y = (unsigned int)x; #if (SIZEOF_LONG > SIZEOF_INT) - if (x > ((unsigned long)UINT_MAX)) - RANGE_ERROR(y, f, 1, -1); + if (x > ((unsigned long)UINT_MAX)) + RANGE_ERROR(y, f, 1, -1); #endif - memcpy(p, (char *)&y, sizeof y); - return 0; + memcpy(p, (char *)&y, sizeof y); + return 0; } static int np_long(char *p, PyObject *v, const formatdef *f) { - long x; - if (get_long(v, &x) < 0) - return -1; - memcpy(p, (char *)&x, sizeof x); - return 0; + long x; + if (get_long(v, &x) < 0) + return -1; + memcpy(p, (char *)&x, sizeof x); + return 0; } static int np_ulong(char *p, PyObject *v, const formatdef *f) { - unsigned long x; - if (get_ulong(v, &x) < 0) - return -1; - memcpy(p, (char *)&x, sizeof x); - return 0; + unsigned long x; + if (get_ulong(v, &x) < 0) + return -1; + memcpy(p, (char *)&x, sizeof x); + return 0; } #ifdef HAVE_LONG_LONG @@ -558,21 +558,21 @@ static int np_longlong(char *p, PyObject *v, const formatdef *f) { - PY_LONG_LONG x; - if (get_longlong(v, &x) < 0) - return -1; - memcpy(p, (char *)&x, sizeof x); - return 0; + PY_LONG_LONG x; + if (get_longlong(v, &x) < 0) + return -1; + memcpy(p, (char *)&x, sizeof x); + return 0; } static int np_ulonglong(char *p, PyObject *v, const formatdef *f) { - unsigned PY_LONG_LONG x; - if (get_ulonglong(v, &x) < 0) - return -1; - memcpy(p, (char *)&x, sizeof x); - return 0; + unsigned PY_LONG_LONG x; + if (get_ulonglong(v, &x) < 0) + return -1; + memcpy(p, (char *)&x, sizeof x); + return 0; } #endif @@ -580,77 +580,77 @@ static int np_bool(char *p, PyObject *v, const formatdef *f) { - BOOL_TYPE y; - y = PyObject_IsTrue(v); - memcpy(p, (char *)&y, sizeof y); - return 0; + BOOL_TYPE y; + y = PyObject_IsTrue(v); + memcpy(p, (char *)&y, sizeof y); + return 0; } static int np_float(char *p, PyObject *v, const formatdef *f) { - float x = (float)PyFloat_AsDouble(v); - if (x == -1 && PyErr_Occurred()) { - PyErr_SetString(StructError, - "required argument is not a float"); - return -1; - } - memcpy(p, (char *)&x, sizeof x); - return 0; + float x = (float)PyFloat_AsDouble(v); + if (x == -1 && PyErr_Occurred()) { + PyErr_SetString(StructError, + "required argument is not a float"); + return -1; + } + memcpy(p, (char *)&x, sizeof x); + return 0; } static int np_double(char *p, PyObject *v, const formatdef *f) { - double x = PyFloat_AsDouble(v); - if (x == -1 && PyErr_Occurred()) { - PyErr_SetString(StructError, - "required argument is not a float"); - return -1; - } - memcpy(p, (char *)&x, sizeof(double)); - return 0; + double x = PyFloat_AsDouble(v); + if (x == -1 && PyErr_Occurred()) { + PyErr_SetString(StructError, + "required argument is not a float"); + return -1; + } + memcpy(p, (char *)&x, sizeof(double)); + return 0; } static int np_void_p(char *p, PyObject *v, const formatdef *f) { - void *x; + void *x; - v = get_pylong(v); - if (v == NULL) - return -1; - assert(PyLong_Check(v)); - x = PyLong_AsVoidPtr(v); - Py_DECREF(v); - if (x == NULL && PyErr_Occurred()) - return -1; - memcpy(p, (char *)&x, sizeof x); - return 0; + v = get_pylong(v); + if (v == NULL) + return -1; + assert(PyLong_Check(v)); + x = PyLong_AsVoidPtr(v); + Py_DECREF(v); + if (x == NULL && PyErr_Occurred()) + return -1; + memcpy(p, (char *)&x, sizeof x); + return 0; } static formatdef native_table[] = { - {'x', sizeof(char), 0, NULL}, - {'b', sizeof(char), 0, nu_byte, np_byte}, - {'B', sizeof(char), 0, nu_ubyte, np_ubyte}, - {'c', sizeof(char), 0, nu_char, np_char}, - {'s', sizeof(char), 0, NULL}, - {'p', sizeof(char), 0, NULL}, - {'h', sizeof(short), SHORT_ALIGN, nu_short, np_short}, - {'H', sizeof(short), SHORT_ALIGN, nu_ushort, np_ushort}, - {'i', sizeof(int), INT_ALIGN, nu_int, np_int}, - {'I', sizeof(int), INT_ALIGN, nu_uint, np_uint}, - {'l', sizeof(long), LONG_ALIGN, nu_long, np_long}, - {'L', sizeof(long), LONG_ALIGN, nu_ulong, np_ulong}, + {'x', sizeof(char), 0, NULL}, + {'b', sizeof(char), 0, nu_byte, np_byte}, + {'B', sizeof(char), 0, nu_ubyte, np_ubyte}, + {'c', sizeof(char), 0, nu_char, np_char}, + {'s', sizeof(char), 0, NULL}, + {'p', sizeof(char), 0, NULL}, + {'h', sizeof(short), SHORT_ALIGN, nu_short, np_short}, + {'H', sizeof(short), SHORT_ALIGN, nu_ushort, np_ushort}, + {'i', sizeof(int), INT_ALIGN, nu_int, np_int}, + {'I', sizeof(int), INT_ALIGN, nu_uint, np_uint}, + {'l', sizeof(long), LONG_ALIGN, nu_long, np_long}, + {'L', sizeof(long), LONG_ALIGN, nu_ulong, np_ulong}, #ifdef HAVE_LONG_LONG - {'q', sizeof(PY_LONG_LONG), LONG_LONG_ALIGN, nu_longlong, np_longlong}, - {'Q', sizeof(PY_LONG_LONG), LONG_LONG_ALIGN, nu_ulonglong,np_ulonglong}, + {'q', sizeof(PY_LONG_LONG), LONG_LONG_ALIGN, nu_longlong, np_longlong}, + {'Q', sizeof(PY_LONG_LONG), LONG_LONG_ALIGN, nu_ulonglong,np_ulonglong}, #endif - {'?', sizeof(BOOL_TYPE), BOOL_ALIGN, nu_bool, np_bool}, - {'f', sizeof(float), FLOAT_ALIGN, nu_float, np_float}, - {'d', sizeof(double), DOUBLE_ALIGN, nu_double, np_double}, - {'P', sizeof(void *), VOID_P_ALIGN, nu_void_p, np_void_p}, - {0} + {'?', sizeof(BOOL_TYPE), BOOL_ALIGN, nu_bool, np_bool}, + {'f', sizeof(float), FLOAT_ALIGN, nu_float, np_float}, + {'d', sizeof(double), DOUBLE_ALIGN, nu_double, np_double}, + {'P', sizeof(void *), VOID_P_ALIGN, nu_void_p, np_void_p}, + {0} }; /* Big-endian routines. *****************************************************/ @@ -658,53 +658,53 @@ static PyObject * bu_int(const char *p, const formatdef *f) { - long x = 0; - Py_ssize_t i = f->size; - const unsigned char *bytes = (const unsigned char *)p; - do { - x = (x<<8) | *bytes++; - } while (--i > 0); - /* Extend the sign bit. */ - if (SIZEOF_LONG > f->size) - x |= -(x & (1L << ((8 * f->size) - 1))); - return PyLong_FromLong(x); + long x = 0; + Py_ssize_t i = f->size; + const unsigned char *bytes = (const unsigned char *)p; + do { + x = (x<<8) | *bytes++; + } while (--i > 0); + /* Extend the sign bit. */ + if (SIZEOF_LONG > f->size) + x |= -(x & (1L << ((8 * f->size) - 1))); + return PyLong_FromLong(x); } static PyObject * bu_uint(const char *p, const formatdef *f) { - unsigned long x = 0; - Py_ssize_t i = f->size; - const unsigned char *bytes = (const unsigned char *)p; - do { - x = (x<<8) | *bytes++; - } while (--i > 0); - if (x <= LONG_MAX) - return PyLong_FromLong((long)x); - return PyLong_FromUnsignedLong(x); + unsigned long x = 0; + Py_ssize_t i = f->size; + const unsigned char *bytes = (const unsigned char *)p; + do { + x = (x<<8) | *bytes++; + } while (--i > 0); + if (x <= LONG_MAX) + return PyLong_FromLong((long)x); + return PyLong_FromUnsignedLong(x); } static PyObject * bu_longlong(const char *p, const formatdef *f) { #ifdef HAVE_LONG_LONG - PY_LONG_LONG x = 0; - Py_ssize_t i = f->size; - const unsigned char *bytes = (const unsigned char *)p; - do { - x = (x<<8) | *bytes++; - } while (--i > 0); - /* Extend the sign bit. */ - if (SIZEOF_LONG_LONG > f->size) - x |= -(x & ((PY_LONG_LONG)1 << ((8 * f->size) - 1))); - if (x >= LONG_MIN && x <= LONG_MAX) - return PyLong_FromLong(Py_SAFE_DOWNCAST(x, PY_LONG_LONG, long)); - return PyLong_FromLongLong(x); + PY_LONG_LONG x = 0; + Py_ssize_t i = f->size; + const unsigned char *bytes = (const unsigned char *)p; + do { + x = (x<<8) | *bytes++; + } while (--i > 0); + /* Extend the sign bit. */ + if (SIZEOF_LONG_LONG > f->size) + x |= -(x & ((PY_LONG_LONG)1 << ((8 * f->size) - 1))); + if (x >= LONG_MIN && x <= LONG_MAX) + return PyLong_FromLong(Py_SAFE_DOWNCAST(x, PY_LONG_LONG, long)); + return PyLong_FromLongLong(x); #else - return _PyLong_FromByteArray((const unsigned char *)p, - 8, - 0, /* little-endian */ - 1 /* signed */); + return _PyLong_FromByteArray((const unsigned char *)p, + 8, + 0, /* little-endian */ + 1 /* signed */); #endif } @@ -712,171 +712,171 @@ bu_ulonglong(const char *p, const formatdef *f) { #ifdef HAVE_LONG_LONG - unsigned PY_LONG_LONG x = 0; - Py_ssize_t i = f->size; - const unsigned char *bytes = (const unsigned char *)p; - do { - x = (x<<8) | *bytes++; - } while (--i > 0); - if (x <= LONG_MAX) - return PyLong_FromLong(Py_SAFE_DOWNCAST(x, unsigned PY_LONG_LONG, long)); - return PyLong_FromUnsignedLongLong(x); + unsigned PY_LONG_LONG x = 0; + Py_ssize_t i = f->size; + const unsigned char *bytes = (const unsigned char *)p; + do { + x = (x<<8) | *bytes++; + } while (--i > 0); + if (x <= LONG_MAX) + return PyLong_FromLong(Py_SAFE_DOWNCAST(x, unsigned PY_LONG_LONG, long)); + return PyLong_FromUnsignedLongLong(x); #else - return _PyLong_FromByteArray((const unsigned char *)p, - 8, - 0, /* little-endian */ - 0 /* signed */); + return _PyLong_FromByteArray((const unsigned char *)p, + 8, + 0, /* little-endian */ + 0 /* signed */); #endif } static PyObject * bu_float(const char *p, const formatdef *f) { - return unpack_float(p, 0); + return unpack_float(p, 0); } static PyObject * bu_double(const char *p, const formatdef *f) { - return unpack_double(p, 0); + return unpack_double(p, 0); } static PyObject * bu_bool(const char *p, const formatdef *f) { - char x; - memcpy((char *)&x, p, sizeof x); - return PyBool_FromLong(x != 0); + char x; + memcpy((char *)&x, p, sizeof x); + return PyBool_FromLong(x != 0); } static int bp_int(char *p, PyObject *v, const formatdef *f) { - long x; - Py_ssize_t i; - if (get_long(v, &x) < 0) - return -1; - i = f->size; - if (i != SIZEOF_LONG) { - if ((i == 2) && (x < -32768 || x > 32767)) - RANGE_ERROR(x, f, 0, 0xffffL); + long x; + Py_ssize_t i; + if (get_long(v, &x) < 0) + return -1; + i = f->size; + if (i != SIZEOF_LONG) { + if ((i == 2) && (x < -32768 || x > 32767)) + RANGE_ERROR(x, f, 0, 0xffffL); #if (SIZEOF_LONG != 4) - else if ((i == 4) && (x < -2147483648L || x > 2147483647L)) - RANGE_ERROR(x, f, 0, 0xffffffffL); + else if ((i == 4) && (x < -2147483648L || x > 2147483647L)) + RANGE_ERROR(x, f, 0, 0xffffffffL); #endif - } - do { - p[--i] = (char)x; - x >>= 8; - } while (i > 0); - return 0; + } + do { + p[--i] = (char)x; + x >>= 8; + } while (i > 0); + return 0; } static int bp_uint(char *p, PyObject *v, const formatdef *f) { - unsigned long x; - Py_ssize_t i; - if (get_ulong(v, &x) < 0) - return -1; - i = f->size; - if (i != SIZEOF_LONG) { - unsigned long maxint = 1; - maxint <<= (unsigned long)(i * 8); - if (x >= maxint) - RANGE_ERROR(x, f, 1, maxint - 1); - } - do { - p[--i] = (char)x; - x >>= 8; - } while (i > 0); - return 0; + unsigned long x; + Py_ssize_t i; + if (get_ulong(v, &x) < 0) + return -1; + i = f->size; + if (i != SIZEOF_LONG) { + unsigned long maxint = 1; + maxint <<= (unsigned long)(i * 8); + if (x >= maxint) + RANGE_ERROR(x, f, 1, maxint - 1); + } + do { + p[--i] = (char)x; + x >>= 8; + } while (i > 0); + return 0; } static int bp_longlong(char *p, PyObject *v, const formatdef *f) { - int res; - v = get_pylong(v); - if (v == NULL) - return -1; - res = _PyLong_AsByteArray((PyLongObject *)v, - (unsigned char *)p, - 8, - 0, /* little_endian */ - 1 /* signed */); - Py_DECREF(v); - return res; + int res; + v = get_pylong(v); + if (v == NULL) + return -1; + res = _PyLong_AsByteArray((PyLongObject *)v, + (unsigned char *)p, + 8, + 0, /* little_endian */ + 1 /* signed */); + Py_DECREF(v); + return res; } static int bp_ulonglong(char *p, PyObject *v, const formatdef *f) { - int res; - v = get_pylong(v); - if (v == NULL) - return -1; - res = _PyLong_AsByteArray((PyLongObject *)v, - (unsigned char *)p, - 8, - 0, /* little_endian */ - 0 /* signed */); - Py_DECREF(v); - return res; + int res; + v = get_pylong(v); + if (v == NULL) + return -1; + res = _PyLong_AsByteArray((PyLongObject *)v, + (unsigned char *)p, + 8, + 0, /* little_endian */ + 0 /* signed */); + Py_DECREF(v); + return res; } static int bp_float(char *p, PyObject *v, const formatdef *f) { - double x = PyFloat_AsDouble(v); - if (x == -1 && PyErr_Occurred()) { - PyErr_SetString(StructError, - "required argument is not a float"); - return -1; - } - return _PyFloat_Pack4(x, (unsigned char *)p, 0); + double x = PyFloat_AsDouble(v); + if (x == -1 && PyErr_Occurred()) { + PyErr_SetString(StructError, + "required argument is not a float"); + return -1; + } + return _PyFloat_Pack4(x, (unsigned char *)p, 0); } static int bp_double(char *p, PyObject *v, const formatdef *f) { - double x = PyFloat_AsDouble(v); - if (x == -1 && PyErr_Occurred()) { - PyErr_SetString(StructError, - "required argument is not a float"); - return -1; - } - return _PyFloat_Pack8(x, (unsigned char *)p, 0); + double x = PyFloat_AsDouble(v); + if (x == -1 && PyErr_Occurred()) { + PyErr_SetString(StructError, + "required argument is not a float"); + return -1; + } + return _PyFloat_Pack8(x, (unsigned char *)p, 0); } static int bp_bool(char *p, PyObject *v, const formatdef *f) { - char y; - y = PyObject_IsTrue(v); - memcpy(p, (char *)&y, sizeof y); - return 0; + char y; + y = PyObject_IsTrue(v); + memcpy(p, (char *)&y, sizeof y); + return 0; } static formatdef bigendian_table[] = { - {'x', 1, 0, NULL}, - {'b', 1, 0, nu_byte, np_byte}, - {'B', 1, 0, nu_ubyte, np_ubyte}, - {'c', 1, 0, nu_char, np_char}, - {'s', 1, 0, NULL}, - {'p', 1, 0, NULL}, - {'h', 2, 0, bu_int, bp_int}, - {'H', 2, 0, bu_uint, bp_uint}, - {'i', 4, 0, bu_int, bp_int}, - {'I', 4, 0, bu_uint, bp_uint}, - {'l', 4, 0, bu_int, bp_int}, - {'L', 4, 0, bu_uint, bp_uint}, - {'q', 8, 0, bu_longlong, bp_longlong}, - {'Q', 8, 0, bu_ulonglong, bp_ulonglong}, - {'?', 1, 0, bu_bool, bp_bool}, - {'f', 4, 0, bu_float, bp_float}, - {'d', 8, 0, bu_double, bp_double}, - {0} + {'x', 1, 0, NULL}, + {'b', 1, 0, nu_byte, np_byte}, + {'B', 1, 0, nu_ubyte, np_ubyte}, + {'c', 1, 0, nu_char, np_char}, + {'s', 1, 0, NULL}, + {'p', 1, 0, NULL}, + {'h', 2, 0, bu_int, bp_int}, + {'H', 2, 0, bu_uint, bp_uint}, + {'i', 4, 0, bu_int, bp_int}, + {'I', 4, 0, bu_uint, bp_uint}, + {'l', 4, 0, bu_int, bp_int}, + {'L', 4, 0, bu_uint, bp_uint}, + {'q', 8, 0, bu_longlong, bp_longlong}, + {'Q', 8, 0, bu_ulonglong, bp_ulonglong}, + {'?', 1, 0, bu_bool, bp_bool}, + {'f', 4, 0, bu_float, bp_float}, + {'d', 8, 0, bu_double, bp_double}, + {0} }; /* Little-endian routines. *****************************************************/ @@ -884,53 +884,53 @@ static PyObject * lu_int(const char *p, const formatdef *f) { - long x = 0; - Py_ssize_t i = f->size; - const unsigned char *bytes = (const unsigned char *)p; - do { - x = (x<<8) | bytes[--i]; - } while (i > 0); - /* Extend the sign bit. */ - if (SIZEOF_LONG > f->size) - x |= -(x & (1L << ((8 * f->size) - 1))); - return PyLong_FromLong(x); + long x = 0; + Py_ssize_t i = f->size; + const unsigned char *bytes = (const unsigned char *)p; + do { + x = (x<<8) | bytes[--i]; + } while (i > 0); + /* Extend the sign bit. */ + if (SIZEOF_LONG > f->size) + x |= -(x & (1L << ((8 * f->size) - 1))); + return PyLong_FromLong(x); } static PyObject * lu_uint(const char *p, const formatdef *f) { - unsigned long x = 0; - Py_ssize_t i = f->size; - const unsigned char *bytes = (const unsigned char *)p; - do { - x = (x<<8) | bytes[--i]; - } while (i > 0); - if (x <= LONG_MAX) - return PyLong_FromLong((long)x); - return PyLong_FromUnsignedLong((long)x); + unsigned long x = 0; + Py_ssize_t i = f->size; + const unsigned char *bytes = (const unsigned char *)p; + do { + x = (x<<8) | bytes[--i]; + } while (i > 0); + if (x <= LONG_MAX) + return PyLong_FromLong((long)x); + return PyLong_FromUnsignedLong((long)x); } static PyObject * lu_longlong(const char *p, const formatdef *f) { #ifdef HAVE_LONG_LONG - PY_LONG_LONG x = 0; - Py_ssize_t i = f->size; - const unsigned char *bytes = (const unsigned char *)p; - do { - x = (x<<8) | bytes[--i]; - } while (i > 0); - /* Extend the sign bit. */ - if (SIZEOF_LONG_LONG > f->size) - x |= -(x & ((PY_LONG_LONG)1 << ((8 * f->size) - 1))); - if (x >= LONG_MIN && x <= LONG_MAX) - return PyLong_FromLong(Py_SAFE_DOWNCAST(x, PY_LONG_LONG, long)); - return PyLong_FromLongLong(x); + PY_LONG_LONG x = 0; + Py_ssize_t i = f->size; + const unsigned char *bytes = (const unsigned char *)p; + do { + x = (x<<8) | bytes[--i]; + } while (i > 0); + /* Extend the sign bit. */ + if (SIZEOF_LONG_LONG > f->size) + x |= -(x & ((PY_LONG_LONG)1 << ((8 * f->size) - 1))); + if (x >= LONG_MIN && x <= LONG_MAX) + return PyLong_FromLong(Py_SAFE_DOWNCAST(x, PY_LONG_LONG, long)); + return PyLong_FromLongLong(x); #else - return _PyLong_FromByteArray((const unsigned char *)p, - 8, - 1, /* little-endian */ - 1 /* signed */); + return _PyLong_FromByteArray((const unsigned char *)p, + 8, + 1, /* little-endian */ + 1 /* signed */); #endif } @@ -938,182 +938,182 @@ lu_ulonglong(const char *p, const formatdef *f) { #ifdef HAVE_LONG_LONG - unsigned PY_LONG_LONG x = 0; - Py_ssize_t i = f->size; - const unsigned char *bytes = (const unsigned char *)p; - do { - x = (x<<8) | bytes[--i]; - } while (i > 0); - if (x <= LONG_MAX) - return PyLong_FromLong(Py_SAFE_DOWNCAST(x, unsigned PY_LONG_LONG, long)); - return PyLong_FromUnsignedLongLong(x); + unsigned PY_LONG_LONG x = 0; + Py_ssize_t i = f->size; + const unsigned char *bytes = (const unsigned char *)p; + do { + x = (x<<8) | bytes[--i]; + } while (i > 0); + if (x <= LONG_MAX) + return PyLong_FromLong(Py_SAFE_DOWNCAST(x, unsigned PY_LONG_LONG, long)); + return PyLong_FromUnsignedLongLong(x); #else - return _PyLong_FromByteArray((const unsigned char *)p, - 8, - 1, /* little-endian */ - 0 /* signed */); + return _PyLong_FromByteArray((const unsigned char *)p, + 8, + 1, /* little-endian */ + 0 /* signed */); #endif } static PyObject * lu_float(const char *p, const formatdef *f) { - return unpack_float(p, 1); + return unpack_float(p, 1); } static PyObject * lu_double(const char *p, const formatdef *f) { - return unpack_double(p, 1); + return unpack_double(p, 1); } static int lp_int(char *p, PyObject *v, const formatdef *f) { - long x; - Py_ssize_t i; - if (get_long(v, &x) < 0) - return -1; - i = f->size; - if (i != SIZEOF_LONG) { - if ((i == 2) && (x < -32768 || x > 32767)) - RANGE_ERROR(x, f, 0, 0xffffL); + long x; + Py_ssize_t i; + if (get_long(v, &x) < 0) + return -1; + i = f->size; + if (i != SIZEOF_LONG) { + if ((i == 2) && (x < -32768 || x > 32767)) + RANGE_ERROR(x, f, 0, 0xffffL); #if (SIZEOF_LONG != 4) - else if ((i == 4) && (x < -2147483648L || x > 2147483647L)) - RANGE_ERROR(x, f, 0, 0xffffffffL); + else if ((i == 4) && (x < -2147483648L || x > 2147483647L)) + RANGE_ERROR(x, f, 0, 0xffffffffL); #endif - } - do { - *p++ = (char)x; - x >>= 8; - } while (--i > 0); - return 0; + } + do { + *p++ = (char)x; + x >>= 8; + } while (--i > 0); + return 0; } static int lp_uint(char *p, PyObject *v, const formatdef *f) { - unsigned long x; - Py_ssize_t i; - if (get_ulong(v, &x) < 0) - return -1; - i = f->size; - if (i != SIZEOF_LONG) { - unsigned long maxint = 1; - maxint <<= (unsigned long)(i * 8); - if (x >= maxint) - RANGE_ERROR(x, f, 1, maxint - 1); - } - do { - *p++ = (char)x; - x >>= 8; - } while (--i > 0); - return 0; + unsigned long x; + Py_ssize_t i; + if (get_ulong(v, &x) < 0) + return -1; + i = f->size; + if (i != SIZEOF_LONG) { + unsigned long maxint = 1; + maxint <<= (unsigned long)(i * 8); + if (x >= maxint) + RANGE_ERROR(x, f, 1, maxint - 1); + } + do { + *p++ = (char)x; + x >>= 8; + } while (--i > 0); + return 0; } static int lp_longlong(char *p, PyObject *v, const formatdef *f) { - int res; - v = get_pylong(v); - if (v == NULL) - return -1; - res = _PyLong_AsByteArray((PyLongObject*)v, - (unsigned char *)p, - 8, - 1, /* little_endian */ - 1 /* signed */); - Py_DECREF(v); - return res; + int res; + v = get_pylong(v); + if (v == NULL) + return -1; + res = _PyLong_AsByteArray((PyLongObject*)v, + (unsigned char *)p, + 8, + 1, /* little_endian */ + 1 /* signed */); + Py_DECREF(v); + return res; } static int lp_ulonglong(char *p, PyObject *v, const formatdef *f) { - int res; - v = get_pylong(v); - if (v == NULL) - return -1; - res = _PyLong_AsByteArray((PyLongObject*)v, - (unsigned char *)p, - 8, - 1, /* little_endian */ - 0 /* signed */); - Py_DECREF(v); - return res; + int res; + v = get_pylong(v); + if (v == NULL) + return -1; + res = _PyLong_AsByteArray((PyLongObject*)v, + (unsigned char *)p, + 8, + 1, /* little_endian */ + 0 /* signed */); + Py_DECREF(v); + return res; } static int lp_float(char *p, PyObject *v, const formatdef *f) { - double x = PyFloat_AsDouble(v); - if (x == -1 && PyErr_Occurred()) { - PyErr_SetString(StructError, - "required argument is not a float"); - return -1; - } - return _PyFloat_Pack4(x, (unsigned char *)p, 1); + double x = PyFloat_AsDouble(v); + if (x == -1 && PyErr_Occurred()) { + PyErr_SetString(StructError, + "required argument is not a float"); + return -1; + } + return _PyFloat_Pack4(x, (unsigned char *)p, 1); } static int lp_double(char *p, PyObject *v, const formatdef *f) { - double x = PyFloat_AsDouble(v); - if (x == -1 && PyErr_Occurred()) { - PyErr_SetString(StructError, - "required argument is not a float"); - return -1; - } - return _PyFloat_Pack8(x, (unsigned char *)p, 1); + double x = PyFloat_AsDouble(v); + if (x == -1 && PyErr_Occurred()) { + PyErr_SetString(StructError, + "required argument is not a float"); + return -1; + } + return _PyFloat_Pack8(x, (unsigned char *)p, 1); } static formatdef lilendian_table[] = { - {'x', 1, 0, NULL}, - {'b', 1, 0, nu_byte, np_byte}, - {'B', 1, 0, nu_ubyte, np_ubyte}, - {'c', 1, 0, nu_char, np_char}, - {'s', 1, 0, NULL}, - {'p', 1, 0, NULL}, - {'h', 2, 0, lu_int, lp_int}, - {'H', 2, 0, lu_uint, lp_uint}, - {'i', 4, 0, lu_int, lp_int}, - {'I', 4, 0, lu_uint, lp_uint}, - {'l', 4, 0, lu_int, lp_int}, - {'L', 4, 0, lu_uint, lp_uint}, - {'q', 8, 0, lu_longlong, lp_longlong}, - {'Q', 8, 0, lu_ulonglong, lp_ulonglong}, - {'?', 1, 0, bu_bool, bp_bool}, /* Std rep not endian dep, - but potentially different from native rep -- reuse bx_bool funcs. */ - {'f', 4, 0, lu_float, lp_float}, - {'d', 8, 0, lu_double, lp_double}, - {0} + {'x', 1, 0, NULL}, + {'b', 1, 0, nu_byte, np_byte}, + {'B', 1, 0, nu_ubyte, np_ubyte}, + {'c', 1, 0, nu_char, np_char}, + {'s', 1, 0, NULL}, + {'p', 1, 0, NULL}, + {'h', 2, 0, lu_int, lp_int}, + {'H', 2, 0, lu_uint, lp_uint}, + {'i', 4, 0, lu_int, lp_int}, + {'I', 4, 0, lu_uint, lp_uint}, + {'l', 4, 0, lu_int, lp_int}, + {'L', 4, 0, lu_uint, lp_uint}, + {'q', 8, 0, lu_longlong, lp_longlong}, + {'Q', 8, 0, lu_ulonglong, lp_ulonglong}, + {'?', 1, 0, bu_bool, bp_bool}, /* Std rep not endian dep, + but potentially different from native rep -- reuse bx_bool funcs. */ + {'f', 4, 0, lu_float, lp_float}, + {'d', 8, 0, lu_double, lp_double}, + {0} }; static const formatdef * whichtable(char **pfmt) { - const char *fmt = (*pfmt)++; /* May be backed out of later */ - switch (*fmt) { - case '<': - return lilendian_table; - case '>': - case '!': /* Network byte order is big-endian */ - return bigendian_table; - case '=': { /* Host byte order -- different from native in aligment! */ - int n = 1; - char *p = (char *) &n; - if (*p == 1) - return lilendian_table; - else - return bigendian_table; - } - default: - --*pfmt; /* Back out of pointer increment */ - /* Fall through */ - case '@': - return native_table; - } + const char *fmt = (*pfmt)++; /* May be backed out of later */ + switch (*fmt) { + case '<': + return lilendian_table; + case '>': + case '!': /* Network byte order is big-endian */ + return bigendian_table; + case '=': { /* Host byte order -- different from native in aligment! */ + int n = 1; + char *p = (char *) &n; + if (*p == 1) + return lilendian_table; + else + return bigendian_table; + } + default: + --*pfmt; /* Back out of pointer increment */ + /* Fall through */ + case '@': + return native_table; + } } @@ -1122,13 +1122,13 @@ static const formatdef * getentry(int c, const formatdef *f) { - for (; f->format != '\0'; f++) { - if (f->format == c) { - return f; - } - } - PyErr_SetString(StructError, "bad char in struct format"); - return NULL; + for (; f->format != '\0'; f++) { + if (f->format == c) { + return f; + } + } + PyErr_SetString(StructError, "bad char in struct format"); + return NULL; } @@ -1137,14 +1137,14 @@ static int align(Py_ssize_t size, char c, const formatdef *e) { - if (e->format == c) { - if (e->alignment) { - size = ((size + e->alignment - 1) - / e->alignment) - * e->alignment; - } - } - return size; + if (e->format == c) { + if (e->alignment) { + size = ((size + e->alignment - 1) + / e->alignment) + * e->alignment; + } + } + return size; } @@ -1153,224 +1153,224 @@ static int prepare_s(PyStructObject *self) { - const formatdef *f; - const formatdef *e; - formatcode *codes; - - const char *s; - const char *fmt; - char c; - Py_ssize_t size, len, num, itemsize, x; - - fmt = PyBytes_AS_STRING(self->s_format); - - f = whichtable((char **)&fmt); - - s = fmt; - size = 0; - len = 0; - while ((c = *s++) != '\0') { - if (isspace(Py_CHARMASK(c))) - continue; - if ('0' <= c && c <= '9') { - num = c - '0'; - while ('0' <= (c = *s++) && c <= '9') { - x = num*10 + (c - '0'); - if (x/10 != num) { - PyErr_SetString( - StructError, - "overflow in item count"); - return -1; - } - num = x; - } - if (c == '\0') - break; - } - else - num = 1; - - e = getentry(c, f); - if (e == NULL) - return -1; - - switch (c) { - case 's': /* fall through */ - case 'p': len++; break; - case 'x': break; - default: len += num; break; - } - - itemsize = e->size; - size = align(size, c, e); - x = num * itemsize; - size += x; - if (x/itemsize != num || size < 0) { - PyErr_SetString(StructError, - "total struct size too long"); - return -1; - } - } - - /* check for overflow */ - if ((len + 1) > (PY_SSIZE_T_MAX / sizeof(formatcode))) { - PyErr_NoMemory(); - return -1; - } - - self->s_size = size; - self->s_len = len; - codes = PyMem_MALLOC((len + 1) * sizeof(formatcode)); - if (codes == NULL) { - PyErr_NoMemory(); - return -1; - } - self->s_codes = codes; - - s = fmt; - size = 0; - while ((c = *s++) != '\0') { - if (isspace(Py_CHARMASK(c))) - continue; - if ('0' <= c && c <= '9') { - num = c - '0'; - while ('0' <= (c = *s++) && c <= '9') - num = num*10 + (c - '0'); - if (c == '\0') - break; - } - else - num = 1; - - e = getentry(c, f); - - size = align(size, c, e); - if (c == 's' || c == 'p') { - codes->offset = size; - codes->size = num; - codes->fmtdef = e; - codes++; - size += num; - } else if (c == 'x') { - size += num; - } else { - while (--num >= 0) { - codes->offset = size; - codes->size = e->size; - codes->fmtdef = e; - codes++; - size += e->size; - } - } - } - codes->fmtdef = NULL; - codes->offset = size; - codes->size = 0; + const formatdef *f; + const formatdef *e; + formatcode *codes; + + const char *s; + const char *fmt; + char c; + Py_ssize_t size, len, num, itemsize, x; + + fmt = PyBytes_AS_STRING(self->s_format); + + f = whichtable((char **)&fmt); + + s = fmt; + size = 0; + len = 0; + while ((c = *s++) != '\0') { + if (isspace(Py_CHARMASK(c))) + continue; + if ('0' <= c && c <= '9') { + num = c - '0'; + while ('0' <= (c = *s++) && c <= '9') { + x = num*10 + (c - '0'); + if (x/10 != num) { + PyErr_SetString( + StructError, + "overflow in item count"); + return -1; + } + num = x; + } + if (c == '\0') + break; + } + else + num = 1; + + e = getentry(c, f); + if (e == NULL) + return -1; + + switch (c) { + case 's': /* fall through */ + case 'p': len++; break; + case 'x': break; + default: len += num; break; + } + + itemsize = e->size; + size = align(size, c, e); + x = num * itemsize; + size += x; + if (x/itemsize != num || size < 0) { + PyErr_SetString(StructError, + "total struct size too long"); + return -1; + } + } + + /* check for overflow */ + if ((len + 1) > (PY_SSIZE_T_MAX / sizeof(formatcode))) { + PyErr_NoMemory(); + return -1; + } + + self->s_size = size; + self->s_len = len; + codes = PyMem_MALLOC((len + 1) * sizeof(formatcode)); + if (codes == NULL) { + PyErr_NoMemory(); + return -1; + } + self->s_codes = codes; + + s = fmt; + size = 0; + while ((c = *s++) != '\0') { + if (isspace(Py_CHARMASK(c))) + continue; + if ('0' <= c && c <= '9') { + num = c - '0'; + while ('0' <= (c = *s++) && c <= '9') + num = num*10 + (c - '0'); + if (c == '\0') + break; + } + else + num = 1; + + e = getentry(c, f); + + size = align(size, c, e); + if (c == 's' || c == 'p') { + codes->offset = size; + codes->size = num; + codes->fmtdef = e; + codes++; + size += num; + } else if (c == 'x') { + size += num; + } else { + while (--num >= 0) { + codes->offset = size; + codes->size = e->size; + codes->fmtdef = e; + codes++; + size += e->size; + } + } + } + codes->fmtdef = NULL; + codes->offset = size; + codes->size = 0; - return 0; + return 0; } static PyObject * s_new(PyTypeObject *type, PyObject *args, PyObject *kwds) { - PyObject *self; + PyObject *self; - assert(type != NULL && type->tp_alloc != NULL); + assert(type != NULL && type->tp_alloc != NULL); - self = type->tp_alloc(type, 0); - if (self != NULL) { - PyStructObject *s = (PyStructObject*)self; - Py_INCREF(Py_None); - s->s_format = Py_None; - s->s_codes = NULL; - s->s_size = -1; - s->s_len = -1; - } - return self; + self = type->tp_alloc(type, 0); + if (self != NULL) { + PyStructObject *s = (PyStructObject*)self; + Py_INCREF(Py_None); + s->s_format = Py_None; + s->s_codes = NULL; + s->s_size = -1; + s->s_len = -1; + } + return self; } static int s_init(PyObject *self, PyObject *args, PyObject *kwds) { - PyStructObject *soself = (PyStructObject *)self; - PyObject *o_format = NULL; - int ret = 0; - static char *kwlist[] = {"format", 0}; - - assert(PyStruct_Check(self)); - - if (!PyArg_ParseTupleAndKeywords(args, kwds, "O:Struct", kwlist, - &o_format)) - return -1; - - if (PyUnicode_Check(o_format)) { - o_format = PyUnicode_AsASCIIString(o_format); - if (o_format == NULL) - return -1; - } - /* XXX support buffer interface, too */ - else { - Py_INCREF(o_format); - } - - if (!PyBytes_Check(o_format)) { - Py_DECREF(o_format); - PyErr_Format(PyExc_TypeError, - "Struct() argument 1 must be bytes, not %.200s", - Py_TYPE(o_format)->tp_name); - return -1; - } + PyStructObject *soself = (PyStructObject *)self; + PyObject *o_format = NULL; + int ret = 0; + static char *kwlist[] = {"format", 0}; + + assert(PyStruct_Check(self)); + + if (!PyArg_ParseTupleAndKeywords(args, kwds, "O:Struct", kwlist, + &o_format)) + return -1; + + if (PyUnicode_Check(o_format)) { + o_format = PyUnicode_AsASCIIString(o_format); + if (o_format == NULL) + return -1; + } + /* XXX support buffer interface, too */ + else { + Py_INCREF(o_format); + } + + if (!PyBytes_Check(o_format)) { + Py_DECREF(o_format); + PyErr_Format(PyExc_TypeError, + "Struct() argument 1 must be bytes, not %.200s", + Py_TYPE(o_format)->tp_name); + return -1; + } - Py_CLEAR(soself->s_format); - soself->s_format = o_format; + Py_CLEAR(soself->s_format); + soself->s_format = o_format; - ret = prepare_s(soself); - return ret; + ret = prepare_s(soself); + return ret; } static void s_dealloc(PyStructObject *s) { - if (s->weakreflist != NULL) - PyObject_ClearWeakRefs((PyObject *)s); - if (s->s_codes != NULL) { - PyMem_FREE(s->s_codes); - } - Py_XDECREF(s->s_format); - Py_TYPE(s)->tp_free((PyObject *)s); + if (s->weakreflist != NULL) + PyObject_ClearWeakRefs((PyObject *)s); + if (s->s_codes != NULL) { + PyMem_FREE(s->s_codes); + } + Py_XDECREF(s->s_format); + Py_TYPE(s)->tp_free((PyObject *)s); } static PyObject * s_unpack_internal(PyStructObject *soself, char *startfrom) { - formatcode *code; - Py_ssize_t i = 0; - PyObject *result = PyTuple_New(soself->s_len); - if (result == NULL) - return NULL; - - for (code = soself->s_codes; code->fmtdef != NULL; code++) { - PyObject *v; - const formatdef *e = code->fmtdef; - const char *res = startfrom + code->offset; - if (e->format == 's') { - v = PyBytes_FromStringAndSize(res, code->size); - } else if (e->format == 'p') { - Py_ssize_t n = *(unsigned char*)res; - if (n >= code->size) - n = code->size - 1; - v = PyBytes_FromStringAndSize(res + 1, n); - } else { - v = e->unpack(res, e); - } - if (v == NULL) - goto fail; - PyTuple_SET_ITEM(result, i++, v); - } + formatcode *code; + Py_ssize_t i = 0; + PyObject *result = PyTuple_New(soself->s_len); + if (result == NULL) + return NULL; + + for (code = soself->s_codes; code->fmtdef != NULL; code++) { + PyObject *v; + const formatdef *e = code->fmtdef; + const char *res = startfrom + code->offset; + if (e->format == 's') { + v = PyBytes_FromStringAndSize(res, code->size); + } else if (e->format == 'p') { + Py_ssize_t n = *(unsigned char*)res; + if (n >= code->size) + n = code->size - 1; + v = PyBytes_FromStringAndSize(res + 1, n); + } else { + v = e->unpack(res, e); + } + if (v == NULL) + goto fail; + PyTuple_SET_ITEM(result, i++, v); + } - return result; + return result; fail: - Py_DECREF(result); - return NULL; + Py_DECREF(result); + return NULL; } @@ -1384,24 +1384,24 @@ static PyObject * s_unpack(PyObject *self, PyObject *input) { - Py_buffer vbuf; - PyObject *result; - PyStructObject *soself = (PyStructObject *)self; - - assert(PyStruct_Check(self)); - assert(soself->s_codes != NULL); - if (PyObject_GetBuffer(input, &vbuf, PyBUF_SIMPLE) < 0) - return NULL; - if (vbuf.len != soself->s_size) { - PyErr_Format(StructError, - "unpack requires a bytes argument of length %zd", - soself->s_size); - PyBuffer_Release(&vbuf); - return NULL; - } - result = s_unpack_internal(soself, vbuf.buf); - PyBuffer_Release(&vbuf); - return result; + Py_buffer vbuf; + PyObject *result; + PyStructObject *soself = (PyStructObject *)self; + + assert(PyStruct_Check(self)); + assert(soself->s_codes != NULL); + if (PyObject_GetBuffer(input, &vbuf, PyBUF_SIMPLE) < 0) + return NULL; + if (vbuf.len != soself->s_size) { + PyErr_Format(StructError, + "unpack requires a bytes argument of length %zd", + soself->s_size); + PyBuffer_Release(&vbuf); + return NULL; + } + result = s_unpack_internal(soself, vbuf.buf); + PyBuffer_Release(&vbuf); + return result; } PyDoc_STRVAR(s_unpack_from__doc__, @@ -1415,35 +1415,35 @@ static PyObject * s_unpack_from(PyObject *self, PyObject *args, PyObject *kwds) { - static char *kwlist[] = {"buffer", "offset", 0}; + static char *kwlist[] = {"buffer", "offset", 0}; - PyObject *input; - Py_ssize_t offset = 0; - Py_buffer vbuf; - PyObject *result; - PyStructObject *soself = (PyStructObject *)self; - - assert(PyStruct_Check(self)); - assert(soself->s_codes != NULL); - - if (!PyArg_ParseTupleAndKeywords(args, kwds, - "O|n:unpack_from", kwlist, - &input, &offset)) - return NULL; - if (PyObject_GetBuffer(input, &vbuf, PyBUF_SIMPLE) < 0) - return NULL; - if (offset < 0) - offset += vbuf.len; - if (offset < 0 || vbuf.len - offset < soself->s_size) { - PyErr_Format(StructError, - "unpack_from requires a buffer of at least %zd bytes", - soself->s_size); - PyBuffer_Release(&vbuf); - return NULL; - } - result = s_unpack_internal(soself, (char*)vbuf.buf + offset); - PyBuffer_Release(&vbuf); - return result; + PyObject *input; + Py_ssize_t offset = 0; + Py_buffer vbuf; + PyObject *result; + PyStructObject *soself = (PyStructObject *)self; + + assert(PyStruct_Check(self)); + assert(soself->s_codes != NULL); + + if (!PyArg_ParseTupleAndKeywords(args, kwds, + "O|n:unpack_from", kwlist, + &input, &offset)) + return NULL; + if (PyObject_GetBuffer(input, &vbuf, PyBUF_SIMPLE) < 0) + return NULL; + if (offset < 0) + offset += vbuf.len; + if (offset < 0 || vbuf.len - offset < soself->s_size) { + PyErr_Format(StructError, + "unpack_from requires a buffer of at least %zd bytes", + soself->s_size); + PyBuffer_Release(&vbuf); + return NULL; + } + result = s_unpack_internal(soself, (char*)vbuf.buf + offset); + PyBuffer_Release(&vbuf); + return result; } @@ -1460,85 +1460,85 @@ static int s_pack_internal(PyStructObject *soself, PyObject *args, int offset, char* buf) { - formatcode *code; - /* XXX(nnorwitz): why does i need to be a local? can we use - the offset parameter or do we need the wider width? */ - Py_ssize_t i; - - memset(buf, '\0', soself->s_size); - i = offset; - for (code = soself->s_codes; code->fmtdef != NULL; code++) { - Py_ssize_t n; - PyObject *v = PyTuple_GET_ITEM(args, i++); - const formatdef *e = code->fmtdef; - char *res = buf + code->offset; - if (e->format == 's') { - int isstring; - void *p; - if (PyUnicode_Check(v)) { - v = _PyUnicode_AsDefaultEncodedString(v, NULL); - if (v == NULL) - return -1; - } - isstring = PyBytes_Check(v); - if (!isstring && !PyByteArray_Check(v)) { - PyErr_SetString(StructError, - "argument for 's' must be a bytes or string"); - return -1; - } - if (isstring) { - n = PyBytes_GET_SIZE(v); - p = PyBytes_AS_STRING(v); - } - else { - n = PyByteArray_GET_SIZE(v); - p = PyByteArray_AS_STRING(v); - } - if (n > code->size) - n = code->size; - if (n > 0) - memcpy(res, p, n); - } else if (e->format == 'p') { - int isstring; - void *p; - if (PyUnicode_Check(v)) { - v = _PyUnicode_AsDefaultEncodedString(v, NULL); - if (v == NULL) - return -1; - } - isstring = PyBytes_Check(v); - if (!isstring && !PyByteArray_Check(v)) { - PyErr_SetString(StructError, - "argument for 'p' must be a bytes or string"); - return -1; - } - if (isstring) { - n = PyBytes_GET_SIZE(v); - p = PyBytes_AS_STRING(v); - } - else { - n = PyByteArray_GET_SIZE(v); - p = PyByteArray_AS_STRING(v); - } - if (n > (code->size - 1)) - n = code->size - 1; - if (n > 0) - memcpy(res + 1, p, n); - if (n > 255) - n = 255; - *res = Py_SAFE_DOWNCAST(n, Py_ssize_t, unsigned char); - } else { - if (e->pack(res, v, e) < 0) { - if (PyLong_Check(v) && PyErr_ExceptionMatches(PyExc_OverflowError)) - PyErr_SetString(StructError, - "long too large to convert to int"); - return -1; - } - } - } + formatcode *code; + /* XXX(nnorwitz): why does i need to be a local? can we use + the offset parameter or do we need the wider width? */ + Py_ssize_t i; + + memset(buf, '\0', soself->s_size); + i = offset; + for (code = soself->s_codes; code->fmtdef != NULL; code++) { + Py_ssize_t n; + PyObject *v = PyTuple_GET_ITEM(args, i++); + const formatdef *e = code->fmtdef; + char *res = buf + code->offset; + if (e->format == 's') { + int isstring; + void *p; + if (PyUnicode_Check(v)) { + v = _PyUnicode_AsDefaultEncodedString(v, NULL); + if (v == NULL) + return -1; + } + isstring = PyBytes_Check(v); + if (!isstring && !PyByteArray_Check(v)) { + PyErr_SetString(StructError, + "argument for 's' must be a bytes or string"); + return -1; + } + if (isstring) { + n = PyBytes_GET_SIZE(v); + p = PyBytes_AS_STRING(v); + } + else { + n = PyByteArray_GET_SIZE(v); + p = PyByteArray_AS_STRING(v); + } + if (n > code->size) + n = code->size; + if (n > 0) + memcpy(res, p, n); + } else if (e->format == 'p') { + int isstring; + void *p; + if (PyUnicode_Check(v)) { + v = _PyUnicode_AsDefaultEncodedString(v, NULL); + if (v == NULL) + return -1; + } + isstring = PyBytes_Check(v); + if (!isstring && !PyByteArray_Check(v)) { + PyErr_SetString(StructError, + "argument for 'p' must be a bytes or string"); + return -1; + } + if (isstring) { + n = PyBytes_GET_SIZE(v); + p = PyBytes_AS_STRING(v); + } + else { + n = PyByteArray_GET_SIZE(v); + p = PyByteArray_AS_STRING(v); + } + if (n > (code->size - 1)) + n = code->size - 1; + if (n > 0) + memcpy(res + 1, p, n); + if (n > 255) + n = 255; + *res = Py_SAFE_DOWNCAST(n, Py_ssize_t, unsigned char); + } else { + if (e->pack(res, v, e) < 0) { + if (PyLong_Check(v) && PyErr_ExceptionMatches(PyExc_OverflowError)) + PyErr_SetString(StructError, + "long too large to convert to int"); + return -1; + } + } + } - /* Success */ - return 0; + /* Success */ + return 0; } @@ -1551,32 +1551,32 @@ static PyObject * s_pack(PyObject *self, PyObject *args) { - PyStructObject *soself; - PyObject *result; + PyStructObject *soself; + PyObject *result; - /* Validate arguments. */ - soself = (PyStructObject *)self; - assert(PyStruct_Check(self)); - assert(soself->s_codes != NULL); - if (PyTuple_GET_SIZE(args) != soself->s_len) - { - PyErr_Format(StructError, - "pack requires exactly %zd arguments", soself->s_len); - return NULL; - } - - /* Allocate a new string */ - result = PyBytes_FromStringAndSize((char *)NULL, soself->s_size); - if (result == NULL) - return NULL; - - /* Call the guts */ - if ( s_pack_internal(soself, args, 0, PyBytes_AS_STRING(result)) != 0 ) { - Py_DECREF(result); - return NULL; - } + /* Validate arguments. */ + soself = (PyStructObject *)self; + assert(PyStruct_Check(self)); + assert(soself->s_codes != NULL); + if (PyTuple_GET_SIZE(args) != soself->s_len) + { + PyErr_Format(StructError, + "pack requires exactly %zd arguments", soself->s_len); + return NULL; + } + + /* Allocate a new string */ + result = PyBytes_FromStringAndSize((char *)NULL, soself->s_size); + if (result == NULL) + return NULL; + + /* Call the guts */ + if ( s_pack_internal(soself, args, 0, PyBytes_AS_STRING(result)) != 0 ) { + Py_DECREF(result); + return NULL; + } - return result; + return result; } PyDoc_STRVAR(s_pack_into__doc__, @@ -1590,59 +1590,59 @@ static PyObject * s_pack_into(PyObject *self, PyObject *args) { - PyStructObject *soself; - char *buffer; - Py_ssize_t buffer_len, offset; - - /* Validate arguments. +1 is for the first arg as buffer. */ - soself = (PyStructObject *)self; - assert(PyStruct_Check(self)); - assert(soself->s_codes != NULL); - if (PyTuple_GET_SIZE(args) != (soself->s_len + 2)) - { - PyErr_Format(StructError, - "pack_into requires exactly %zd arguments", - (soself->s_len + 2)); - return NULL; - } - - /* Extract a writable memory buffer from the first argument */ - if ( PyObject_AsWriteBuffer(PyTuple_GET_ITEM(args, 0), - (void**)&buffer, &buffer_len) == -1 ) { - return NULL; - } - assert( buffer_len >= 0 ); - - /* Extract the offset from the first argument */ - offset = PyNumber_AsSsize_t(PyTuple_GET_ITEM(args, 1), PyExc_IndexError); - if (offset == -1 && PyErr_Occurred()) - return NULL; - - /* Support negative offsets. */ - if (offset < 0) - offset += buffer_len; - - /* Check boundaries */ - if (offset < 0 || (buffer_len - offset) < soself->s_size) { - PyErr_Format(StructError, - "pack_into requires a buffer of at least %zd bytes", - soself->s_size); - return NULL; - } - - /* Call the guts */ - if ( s_pack_internal(soself, args, 2, buffer + offset) != 0 ) { - return NULL; - } + PyStructObject *soself; + char *buffer; + Py_ssize_t buffer_len, offset; + + /* Validate arguments. +1 is for the first arg as buffer. */ + soself = (PyStructObject *)self; + assert(PyStruct_Check(self)); + assert(soself->s_codes != NULL); + if (PyTuple_GET_SIZE(args) != (soself->s_len + 2)) + { + PyErr_Format(StructError, + "pack_into requires exactly %zd arguments", + (soself->s_len + 2)); + return NULL; + } + + /* Extract a writable memory buffer from the first argument */ + if ( PyObject_AsWriteBuffer(PyTuple_GET_ITEM(args, 0), + (void**)&buffer, &buffer_len) == -1 ) { + return NULL; + } + assert( buffer_len >= 0 ); + + /* Extract the offset from the first argument */ + offset = PyNumber_AsSsize_t(PyTuple_GET_ITEM(args, 1), PyExc_IndexError); + if (offset == -1 && PyErr_Occurred()) + return NULL; + + /* Support negative offsets. */ + if (offset < 0) + offset += buffer_len; + + /* Check boundaries */ + if (offset < 0 || (buffer_len - offset) < soself->s_size) { + PyErr_Format(StructError, + "pack_into requires a buffer of at least %zd bytes", + soself->s_size); + return NULL; + } + + /* Call the guts */ + if ( s_pack_internal(soself, args, 2, buffer + offset) != 0 ) { + return NULL; + } - Py_RETURN_NONE; + Py_RETURN_NONE; } static PyObject * s_get_format(PyStructObject *self, void *unused) { - Py_INCREF(self->s_format); - return self->s_format; + Py_INCREF(self->s_format); + return self->s_format; } static PyObject * @@ -1654,12 +1654,12 @@ /* List of functions */ static struct PyMethodDef s_methods[] = { - {"pack", s_pack, METH_VARARGS, s_pack__doc__}, - {"pack_into", s_pack_into, METH_VARARGS, s_pack_into__doc__}, - {"unpack", s_unpack, METH_O, s_unpack__doc__}, - {"unpack_from", (PyCFunction)s_unpack_from, METH_VARARGS|METH_KEYWORDS, - s_unpack_from__doc__}, - {NULL, NULL} /* sentinel */ + {"pack", s_pack, METH_VARARGS, s_pack__doc__}, + {"pack_into", s_pack_into, METH_VARARGS, s_pack_into__doc__}, + {"unpack", s_unpack, METH_O, s_unpack__doc__}, + {"unpack_from", (PyCFunction)s_unpack_from, METH_VARARGS|METH_KEYWORDS, + s_unpack_from__doc__}, + {NULL, NULL} /* sentinel */ }; PyDoc_STRVAR(s__doc__, "Compiled struct object"); @@ -1667,52 +1667,52 @@ #define OFF(x) offsetof(PyStructObject, x) static PyGetSetDef s_getsetlist[] = { - {"format", (getter)s_get_format, (setter)NULL, "struct format string", NULL}, - {"size", (getter)s_get_size, (setter)NULL, "struct size in bytes", NULL}, - {NULL} /* sentinel */ + {"format", (getter)s_get_format, (setter)NULL, "struct format string", NULL}, + {"size", (getter)s_get_size, (setter)NULL, "struct size in bytes", NULL}, + {NULL} /* sentinel */ }; static PyTypeObject PyStructType = { - PyVarObject_HEAD_INIT(NULL, 0) - "Struct", - sizeof(PyStructObject), - 0, - (destructor)s_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 */ - PyObject_GenericSetAttr, /* tp_setattro */ - 0, /* tp_as_buffer */ - Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */ - s__doc__, /* tp_doc */ - 0, /* tp_traverse */ - 0, /* tp_clear */ - 0, /* tp_richcompare */ - offsetof(PyStructObject, weakreflist), /* tp_weaklistoffset */ - 0, /* tp_iter */ - 0, /* tp_iternext */ - s_methods, /* tp_methods */ - NULL, /* tp_members */ - s_getsetlist, /* tp_getset */ - 0, /* tp_base */ - 0, /* tp_dict */ - 0, /* tp_descr_get */ - 0, /* tp_descr_set */ - 0, /* tp_dictoffset */ - s_init, /* tp_init */ - PyType_GenericAlloc,/* tp_alloc */ - s_new, /* tp_new */ - PyObject_Del, /* tp_free */ + PyVarObject_HEAD_INIT(NULL, 0) + "Struct", + sizeof(PyStructObject), + 0, + (destructor)s_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 */ + PyObject_GenericSetAttr, /* tp_setattro */ + 0, /* tp_as_buffer */ + Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */ + s__doc__, /* tp_doc */ + 0, /* tp_traverse */ + 0, /* tp_clear */ + 0, /* tp_richcompare */ + offsetof(PyStructObject, weakreflist), /* tp_weaklistoffset */ + 0, /* tp_iter */ + 0, /* tp_iternext */ + s_methods, /* tp_methods */ + NULL, /* tp_members */ + s_getsetlist, /* tp_getset */ + 0, /* tp_base */ + 0, /* tp_dict */ + 0, /* tp_descr_get */ + 0, /* tp_descr_set */ + 0, /* tp_dictoffset */ + s_init, /* tp_init */ + PyType_GenericAlloc,/* tp_alloc */ + s_new, /* tp_new */ + PyObject_Del, /* tp_free */ }; @@ -1724,29 +1724,29 @@ static PyObject * cache_struct(PyObject *fmt) { - PyObject * s_object; + PyObject * s_object; - if (cache == NULL) { - cache = PyDict_New(); - if (cache == NULL) - return NULL; - } - - s_object = PyDict_GetItem(cache, fmt); - if (s_object != NULL) { - Py_INCREF(s_object); - return s_object; - } - - s_object = PyObject_CallFunctionObjArgs((PyObject *)(&PyStructType), fmt, NULL); - if (s_object != NULL) { - if (PyDict_Size(cache) >= MAXCACHE) - PyDict_Clear(cache); - /* Attempt to cache the result */ - if (PyDict_SetItem(cache, fmt, s_object) == -1) - PyErr_Clear(); - } - return s_object; + if (cache == NULL) { + cache = PyDict_New(); + if (cache == NULL) + return NULL; + } + + s_object = PyDict_GetItem(cache, fmt); + if (s_object != NULL) { + Py_INCREF(s_object); + return s_object; + } + + s_object = PyObject_CallFunctionObjArgs((PyObject *)(&PyStructType), fmt, NULL); + if (s_object != NULL) { + if (PyDict_Size(cache) >= MAXCACHE) + PyDict_Clear(cache); + /* Attempt to cache the result */ + if (PyDict_SetItem(cache, fmt, s_object) == -1) + PyErr_Clear(); + } + return s_object; } PyDoc_STRVAR(clearcache_doc, @@ -1755,8 +1755,8 @@ static PyObject * clearcache(PyObject *self) { - Py_CLEAR(cache); - Py_RETURN_NONE; + Py_CLEAR(cache); + Py_RETURN_NONE; } PyDoc_STRVAR(calcsize_doc, @@ -1765,13 +1765,13 @@ static PyObject * calcsize(PyObject *self, PyObject *fmt) { - Py_ssize_t n; - PyObject *s_object = cache_struct(fmt); - if (s_object == NULL) - return NULL; - n = ((PyStructObject *)s_object)->s_size; - Py_DECREF(s_object); - return PyLong_FromSsize_t(n); + Py_ssize_t n; + PyObject *s_object = cache_struct(fmt); + if (s_object == NULL) + return NULL; + n = ((PyStructObject *)s_object)->s_size; + Py_DECREF(s_object); + return PyLong_FromSsize_t(n); } PyDoc_STRVAR(pack_doc, @@ -1780,27 +1780,27 @@ static PyObject * pack(PyObject *self, PyObject *args) { - PyObject *s_object, *fmt, *newargs, *result; - Py_ssize_t n = PyTuple_GET_SIZE(args); + PyObject *s_object, *fmt, *newargs, *result; + Py_ssize_t n = PyTuple_GET_SIZE(args); - if (n == 0) { - PyErr_SetString(PyExc_TypeError, "missing format argument"); - return NULL; - } - fmt = PyTuple_GET_ITEM(args, 0); - newargs = PyTuple_GetSlice(args, 1, n); - if (newargs == NULL) - return NULL; - - s_object = cache_struct(fmt); - if (s_object == NULL) { - Py_DECREF(newargs); - return NULL; - } - result = s_pack(s_object, newargs); - Py_DECREF(newargs); - Py_DECREF(s_object); - return result; + if (n == 0) { + PyErr_SetString(PyExc_TypeError, "missing format argument"); + return NULL; + } + fmt = PyTuple_GET_ITEM(args, 0); + newargs = PyTuple_GetSlice(args, 1, n); + if (newargs == NULL) + return NULL; + + s_object = cache_struct(fmt); + if (s_object == NULL) { + Py_DECREF(newargs); + return NULL; + } + result = s_pack(s_object, newargs); + Py_DECREF(newargs); + Py_DECREF(s_object); + return result; } PyDoc_STRVAR(pack_into_doc, @@ -1810,27 +1810,27 @@ static PyObject * pack_into(PyObject *self, PyObject *args) { - PyObject *s_object, *fmt, *newargs, *result; - Py_ssize_t n = PyTuple_GET_SIZE(args); + PyObject *s_object, *fmt, *newargs, *result; + Py_ssize_t n = PyTuple_GET_SIZE(args); - if (n == 0) { - PyErr_SetString(PyExc_TypeError, "missing format argument"); - return NULL; - } - fmt = PyTuple_GET_ITEM(args, 0); - newargs = PyTuple_GetSlice(args, 1, n); - if (newargs == NULL) - return NULL; - - s_object = cache_struct(fmt); - if (s_object == NULL) { - Py_DECREF(newargs); - return NULL; - } - result = s_pack_into(s_object, newargs); - Py_DECREF(newargs); - Py_DECREF(s_object); - return result; + if (n == 0) { + PyErr_SetString(PyExc_TypeError, "missing format argument"); + return NULL; + } + fmt = PyTuple_GET_ITEM(args, 0); + newargs = PyTuple_GetSlice(args, 1, n); + if (newargs == NULL) + return NULL; + + s_object = cache_struct(fmt); + if (s_object == NULL) { + Py_DECREF(newargs); + return NULL; + } + result = s_pack_into(s_object, newargs); + Py_DECREF(newargs); + Py_DECREF(s_object); + return result; } PyDoc_STRVAR(unpack_doc, @@ -1840,17 +1840,17 @@ static PyObject * unpack(PyObject *self, PyObject *args) { - PyObject *s_object, *fmt, *inputstr, *result; + PyObject *s_object, *fmt, *inputstr, *result; - if (!PyArg_UnpackTuple(args, "unpack", 2, 2, &fmt, &inputstr)) - return NULL; + if (!PyArg_UnpackTuple(args, "unpack", 2, 2, &fmt, &inputstr)) + return NULL; - s_object = cache_struct(fmt); - if (s_object == NULL) - return NULL; - result = s_unpack(s_object, inputstr); - Py_DECREF(s_object); - return result; + s_object = cache_struct(fmt); + if (s_object == NULL) + return NULL; + result = s_unpack(s_object, inputstr); + Py_DECREF(s_object); + return result; } PyDoc_STRVAR(unpack_from_doc, @@ -1860,38 +1860,38 @@ static PyObject * unpack_from(PyObject *self, PyObject *args, PyObject *kwds) { - PyObject *s_object, *fmt, *newargs, *result; - Py_ssize_t n = PyTuple_GET_SIZE(args); + PyObject *s_object, *fmt, *newargs, *result; + Py_ssize_t n = PyTuple_GET_SIZE(args); - if (n == 0) { - PyErr_SetString(PyExc_TypeError, "missing format argument"); - return NULL; - } - fmt = PyTuple_GET_ITEM(args, 0); - newargs = PyTuple_GetSlice(args, 1, n); - if (newargs == NULL) - return NULL; - - s_object = cache_struct(fmt); - if (s_object == NULL) { - Py_DECREF(newargs); - return NULL; - } - result = s_unpack_from(s_object, newargs, kwds); - Py_DECREF(newargs); - Py_DECREF(s_object); - return result; + if (n == 0) { + PyErr_SetString(PyExc_TypeError, "missing format argument"); + return NULL; + } + fmt = PyTuple_GET_ITEM(args, 0); + newargs = PyTuple_GetSlice(args, 1, n); + if (newargs == NULL) + return NULL; + + s_object = cache_struct(fmt); + if (s_object == NULL) { + Py_DECREF(newargs); + return NULL; + } + result = s_unpack_from(s_object, newargs, kwds); + Py_DECREF(newargs); + Py_DECREF(s_object); + return result; } static struct PyMethodDef module_functions[] = { - {"_clearcache", (PyCFunction)clearcache, METH_NOARGS, clearcache_doc}, - {"calcsize", calcsize, METH_O, calcsize_doc}, - {"pack", pack, METH_VARARGS, pack_doc}, - {"pack_into", pack_into, METH_VARARGS, pack_into_doc}, - {"unpack", unpack, METH_VARARGS, unpack_doc}, - {"unpack_from", (PyCFunction)unpack_from, - METH_VARARGS|METH_KEYWORDS, unpack_from_doc}, - {NULL, NULL} /* sentinel */ + {"_clearcache", (PyCFunction)clearcache, METH_NOARGS, clearcache_doc}, + {"calcsize", calcsize, METH_O, calcsize_doc}, + {"pack", pack, METH_VARARGS, pack_doc}, + {"pack_into", pack_into, METH_VARARGS, pack_into_doc}, + {"unpack", unpack, METH_VARARGS, unpack_doc}, + {"unpack_from", (PyCFunction)unpack_from, + METH_VARARGS|METH_KEYWORDS, unpack_from_doc}, + {NULL, NULL} /* sentinel */ }; @@ -1928,87 +1928,87 @@ static struct PyModuleDef _structmodule = { - PyModuleDef_HEAD_INIT, - "_struct", - module_doc, - -1, - module_functions, - NULL, - NULL, - NULL, - NULL + PyModuleDef_HEAD_INIT, + "_struct", + module_doc, + -1, + module_functions, + NULL, + NULL, + NULL, + NULL }; PyMODINIT_FUNC PyInit__struct(void) { - PyObject *ver, *m; + PyObject *ver, *m; - ver = PyBytes_FromString("0.3"); - if (ver == NULL) - return NULL; - - m = PyModule_Create(&_structmodule); - if (m == NULL) - return NULL; - - Py_TYPE(&PyStructType) = &PyType_Type; - if (PyType_Ready(&PyStructType) < 0) - return NULL; - - /* Check endian and swap in faster functions */ - { - int one = 1; - formatdef *native = native_table; - formatdef *other, *ptr; - if ((int)*(unsigned char*)&one) - other = lilendian_table; - else - other = bigendian_table; - /* Scan through the native table, find a matching - entry in the endian table and swap in the - native implementations whenever possible - (64-bit platforms may not have "standard" sizes) */ - while (native->format != '\0' && other->format != '\0') { - ptr = other; - while (ptr->format != '\0') { - if (ptr->format == native->format) { - /* Match faster when formats are - listed in the same order */ - if (ptr == other) - other++; - /* Only use the trick if the - size matches */ - if (ptr->size != native->size) - break; - /* Skip float and double, could be - "unknown" float format */ - if (ptr->format == 'd' || ptr->format == 'f') - break; - ptr->pack = native->pack; - ptr->unpack = native->unpack; - break; - } - ptr++; - } - native++; - } - } - - /* Add some symbolic constants to the module */ - if (StructError == NULL) { - StructError = PyErr_NewException("struct.error", NULL, NULL); - if (StructError == NULL) - return NULL; - } - - Py_INCREF(StructError); - PyModule_AddObject(m, "error", StructError); + ver = PyBytes_FromString("0.3"); + if (ver == NULL) + return NULL; + + m = PyModule_Create(&_structmodule); + if (m == NULL) + return NULL; + + Py_TYPE(&PyStructType) = &PyType_Type; + if (PyType_Ready(&PyStructType) < 0) + return NULL; + + /* Check endian and swap in faster functions */ + { + int one = 1; + formatdef *native = native_table; + formatdef *other, *ptr; + if ((int)*(unsigned char*)&one) + other = lilendian_table; + else + other = bigendian_table; + /* Scan through the native table, find a matching + entry in the endian table and swap in the + native implementations whenever possible + (64-bit platforms may not have "standard" sizes) */ + while (native->format != '\0' && other->format != '\0') { + ptr = other; + while (ptr->format != '\0') { + if (ptr->format == native->format) { + /* Match faster when formats are + listed in the same order */ + if (ptr == other) + other++; + /* Only use the trick if the + size matches */ + if (ptr->size != native->size) + break; + /* Skip float and double, could be + "unknown" float format */ + if (ptr->format == 'd' || ptr->format == 'f') + break; + ptr->pack = native->pack; + ptr->unpack = native->unpack; + break; + } + ptr++; + } + native++; + } + } + + /* Add some symbolic constants to the module */ + if (StructError == NULL) { + StructError = PyErr_NewException("struct.error", NULL, NULL); + if (StructError == NULL) + return NULL; + } + + Py_INCREF(StructError); + PyModule_AddObject(m, "error", StructError); - Py_INCREF((PyObject*)&PyStructType); - PyModule_AddObject(m, "Struct", (PyObject*)&PyStructType); + Py_INCREF((PyObject*)&PyStructType); + PyModule_AddObject(m, "Struct", (PyObject*)&PyStructType); - PyModule_AddObject(m, "__version__", ver); + PyModule_AddObject(m, "__version__", ver); - return m; + return m; } Modified: python/branches/release31-maint/Modules/_testcapimodule.c ============================================================================== --- python/branches/release31-maint/Modules/_testcapimodule.c (original) +++ python/branches/release31-maint/Modules/_testcapimodule.c Sun May 9 18:14:21 2010 @@ -14,22 +14,22 @@ #ifdef WITH_THREAD #include "pythread.h" #endif /* WITH_THREAD */ -static PyObject *TestError; /* set to exception object in init */ +static PyObject *TestError; /* set to exception object in init */ /* Raise TestError with test_name + ": " + msg, and return NULL. */ static PyObject * raiseTestError(const char* test_name, const char* msg) { - char buf[2048]; + char buf[2048]; - if (strlen(test_name) + strlen(msg) > sizeof(buf) - 50) - PyErr_SetString(TestError, "internal error msg too large"); - else { - PyOS_snprintf(buf, sizeof(buf), "%s: %s", test_name, msg); - PyErr_SetString(TestError, buf); - } - return NULL; + if (strlen(test_name) + strlen(msg) > sizeof(buf) - 50) + PyErr_SetString(TestError, "internal error msg too large"); + else { + PyOS_snprintf(buf, sizeof(buf), "%s: %s", test_name, msg); + PyErr_SetString(TestError, buf); + } + return NULL; } /* Test #defines from pyconfig.h (particularly the SIZEOF_* defines). @@ -40,138 +40,138 @@ */ static PyObject* sizeof_error(const char* fatname, const char* typname, - int expected, int got) + int expected, int got) { - char buf[1024]; - PyOS_snprintf(buf, sizeof(buf), - "%.200s #define == %d but sizeof(%.200s) == %d", - fatname, expected, typname, got); - PyErr_SetString(TestError, buf); - return (PyObject*)NULL; + char buf[1024]; + PyOS_snprintf(buf, sizeof(buf), + "%.200s #define == %d but sizeof(%.200s) == %d", + fatname, expected, typname, got); + PyErr_SetString(TestError, buf); + return (PyObject*)NULL; } static PyObject* test_config(PyObject *self) { #define CHECK_SIZEOF(FATNAME, TYPE) \ - if (FATNAME != sizeof(TYPE)) \ - return sizeof_error(#FATNAME, #TYPE, FATNAME, sizeof(TYPE)) + if (FATNAME != sizeof(TYPE)) \ + return sizeof_error(#FATNAME, #TYPE, FATNAME, sizeof(TYPE)) - CHECK_SIZEOF(SIZEOF_SHORT, short); - CHECK_SIZEOF(SIZEOF_INT, int); - CHECK_SIZEOF(SIZEOF_LONG, long); - CHECK_SIZEOF(SIZEOF_VOID_P, void*); - CHECK_SIZEOF(SIZEOF_TIME_T, time_t); + CHECK_SIZEOF(SIZEOF_SHORT, short); + CHECK_SIZEOF(SIZEOF_INT, int); + CHECK_SIZEOF(SIZEOF_LONG, long); + CHECK_SIZEOF(SIZEOF_VOID_P, void*); + CHECK_SIZEOF(SIZEOF_TIME_T, time_t); #ifdef HAVE_LONG_LONG - CHECK_SIZEOF(SIZEOF_LONG_LONG, PY_LONG_LONG); + CHECK_SIZEOF(SIZEOF_LONG_LONG, PY_LONG_LONG); #endif #undef CHECK_SIZEOF - Py_INCREF(Py_None); - return Py_None; + Py_INCREF(Py_None); + return Py_None; } static PyObject* test_list_api(PyObject *self) { - PyObject* list; - int i; + PyObject* list; + int i; - /* SF bug 132008: PyList_Reverse segfaults */ + /* SF bug 132008: PyList_Reverse segfaults */ #define NLIST 30 - list = PyList_New(NLIST); - if (list == (PyObject*)NULL) - return (PyObject*)NULL; - /* list = range(NLIST) */ - for (i = 0; i < NLIST; ++i) { - PyObject* anint = PyLong_FromLong(i); - if (anint == (PyObject*)NULL) { - Py_DECREF(list); - return (PyObject*)NULL; - } - PyList_SET_ITEM(list, i, anint); - } - /* list.reverse(), via PyList_Reverse() */ - i = PyList_Reverse(list); /* should not blow up! */ - if (i != 0) { - Py_DECREF(list); - return (PyObject*)NULL; - } - /* Check that list == range(29, -1, -1) now */ - for (i = 0; i < NLIST; ++i) { - PyObject* anint = PyList_GET_ITEM(list, i); - if (PyLong_AS_LONG(anint) != NLIST-1-i) { - PyErr_SetString(TestError, - "test_list_api: reverse screwed up"); - Py_DECREF(list); - return (PyObject*)NULL; - } - } - Py_DECREF(list); + list = PyList_New(NLIST); + if (list == (PyObject*)NULL) + return (PyObject*)NULL; + /* list = range(NLIST) */ + for (i = 0; i < NLIST; ++i) { + PyObject* anint = PyLong_FromLong(i); + if (anint == (PyObject*)NULL) { + Py_DECREF(list); + return (PyObject*)NULL; + } + PyList_SET_ITEM(list, i, anint); + } + /* list.reverse(), via PyList_Reverse() */ + i = PyList_Reverse(list); /* should not blow up! */ + if (i != 0) { + Py_DECREF(list); + return (PyObject*)NULL; + } + /* Check that list == range(29, -1, -1) now */ + for (i = 0; i < NLIST; ++i) { + PyObject* anint = PyList_GET_ITEM(list, i); + if (PyLong_AS_LONG(anint) != NLIST-1-i) { + PyErr_SetString(TestError, + "test_list_api: reverse screwed up"); + Py_DECREF(list); + return (PyObject*)NULL; + } + } + Py_DECREF(list); #undef NLIST - Py_INCREF(Py_None); - return Py_None; + Py_INCREF(Py_None); + return Py_None; } static int test_dict_inner(int count) { - Py_ssize_t pos = 0, iterations = 0; - int i; - PyObject *dict = PyDict_New(); - PyObject *v, *k; - - if (dict == NULL) - return -1; - - for (i = 0; i < count; i++) { - v = PyLong_FromLong(i); - PyDict_SetItem(dict, v, v); - Py_DECREF(v); - } - - while (PyDict_Next(dict, &pos, &k, &v)) { - PyObject *o; - iterations++; - - i = PyLong_AS_LONG(v) + 1; - o = PyLong_FromLong(i); - if (o == NULL) - return -1; - if (PyDict_SetItem(dict, k, o) < 0) { - Py_DECREF(o); - return -1; - } - Py_DECREF(o); - } - - Py_DECREF(dict); - - if (iterations != count) { - PyErr_SetString( - TestError, - "test_dict_iteration: dict iteration went wrong "); - return -1; - } else { - return 0; - } + Py_ssize_t pos = 0, iterations = 0; + int i; + PyObject *dict = PyDict_New(); + PyObject *v, *k; + + if (dict == NULL) + return -1; + + for (i = 0; i < count; i++) { + v = PyLong_FromLong(i); + PyDict_SetItem(dict, v, v); + Py_DECREF(v); + } + + while (PyDict_Next(dict, &pos, &k, &v)) { + PyObject *o; + iterations++; + + i = PyLong_AS_LONG(v) + 1; + o = PyLong_FromLong(i); + if (o == NULL) + return -1; + if (PyDict_SetItem(dict, k, o) < 0) { + Py_DECREF(o); + return -1; + } + Py_DECREF(o); + } + + Py_DECREF(dict); + + if (iterations != count) { + PyErr_SetString( + TestError, + "test_dict_iteration: dict iteration went wrong "); + return -1; + } else { + return 0; + } } static PyObject* test_dict_iteration(PyObject* self) { - int i; + int i; - for (i = 0; i < 200; i++) { - if (test_dict_inner(i) < 0) { - return NULL; - } - } + for (i = 0; i < 200; i++) { + if (test_dict_inner(i) < 0) { + return NULL; + } + } - Py_INCREF(Py_None); - return Py_None; + Py_INCREF(Py_None); + return Py_None; } @@ -179,107 +179,107 @@ * PyType_Ready if it hasn't already been called */ static PyTypeObject _HashInheritanceTester_Type = { - PyVarObject_HEAD_INIT(NULL, 0) - "hashinheritancetester", /* Name of this type */ - sizeof(PyObject), /* Basic object size */ - 0, /* Item size for varobject */ - (destructor)PyObject_Del, /* 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, /* tp_flags */ - 0, /* tp_doc */ - 0, /* tp_traverse */ - 0, /* tp_clear */ - 0, /* tp_richcompare */ - 0, /* tp_weaklistoffset */ - 0, /* tp_iter */ - 0, /* tp_iternext */ - 0, /* tp_methods */ - 0, /* tp_members */ - 0, /* tp_getset */ - 0, /* tp_base */ - 0, /* tp_dict */ - 0, /* tp_descr_get */ - 0, /* tp_descr_set */ - 0, /* tp_dictoffset */ - 0, /* tp_init */ - 0, /* tp_alloc */ - PyType_GenericNew, /* tp_new */ + PyVarObject_HEAD_INIT(NULL, 0) + "hashinheritancetester", /* Name of this type */ + sizeof(PyObject), /* Basic object size */ + 0, /* Item size for varobject */ + (destructor)PyObject_Del, /* 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, /* tp_flags */ + 0, /* tp_doc */ + 0, /* tp_traverse */ + 0, /* tp_clear */ + 0, /* tp_richcompare */ + 0, /* tp_weaklistoffset */ + 0, /* tp_iter */ + 0, /* tp_iternext */ + 0, /* tp_methods */ + 0, /* tp_members */ + 0, /* tp_getset */ + 0, /* tp_base */ + 0, /* tp_dict */ + 0, /* tp_descr_get */ + 0, /* tp_descr_set */ + 0, /* tp_dictoffset */ + 0, /* tp_init */ + 0, /* tp_alloc */ + PyType_GenericNew, /* tp_new */ }; static PyObject* test_lazy_hash_inheritance(PyObject* self) { - PyTypeObject *type; - PyObject *obj; - long hash; - - type = &_HashInheritanceTester_Type; - - if (type->tp_dict != NULL) - /* The type has already been initialized. This probably means - -R is being used. */ - Py_RETURN_NONE; - - - obj = PyObject_New(PyObject, type); - if (obj == NULL) { - PyErr_Clear(); - PyErr_SetString( - TestError, - "test_lazy_hash_inheritance: failed to create object"); - return NULL; - } - - if (type->tp_dict != NULL) { - PyErr_SetString( - TestError, - "test_lazy_hash_inheritance: type initialised too soon"); - Py_DECREF(obj); - return NULL; - } - - hash = PyObject_Hash(obj); - if ((hash == -1) && PyErr_Occurred()) { - PyErr_Clear(); - PyErr_SetString( - TestError, - "test_lazy_hash_inheritance: could not hash object"); - Py_DECREF(obj); - return NULL; - } - - if (type->tp_dict == NULL) { - PyErr_SetString( - TestError, - "test_lazy_hash_inheritance: type not initialised by hash()"); - Py_DECREF(obj); - return NULL; - } - - if (type->tp_hash != PyType_Type.tp_hash) { - PyErr_SetString( - TestError, - "test_lazy_hash_inheritance: unexpected hash function"); - Py_DECREF(obj); - return NULL; - } + PyTypeObject *type; + PyObject *obj; + long hash; + + type = &_HashInheritanceTester_Type; + + if (type->tp_dict != NULL) + /* The type has already been initialized. This probably means + -R is being used. */ + Py_RETURN_NONE; + + + obj = PyObject_New(PyObject, type); + if (obj == NULL) { + PyErr_Clear(); + PyErr_SetString( + TestError, + "test_lazy_hash_inheritance: failed to create object"); + return NULL; + } + + if (type->tp_dict != NULL) { + PyErr_SetString( + TestError, + "test_lazy_hash_inheritance: type initialised too soon"); + Py_DECREF(obj); + return NULL; + } + + hash = PyObject_Hash(obj); + if ((hash == -1) && PyErr_Occurred()) { + PyErr_Clear(); + PyErr_SetString( + TestError, + "test_lazy_hash_inheritance: could not hash object"); + Py_DECREF(obj); + return NULL; + } + + if (type->tp_dict == NULL) { + PyErr_SetString( + TestError, + "test_lazy_hash_inheritance: type not initialised by hash()"); + Py_DECREF(obj); + return NULL; + } + + if (type->tp_hash != PyType_Type.tp_hash) { + PyErr_SetString( + TestError, + "test_lazy_hash_inheritance: unexpected hash function"); + Py_DECREF(obj); + return NULL; + } - Py_DECREF(obj); + Py_DECREF(obj); - Py_RETURN_NONE; + Py_RETURN_NONE; } @@ -290,85 +290,85 @@ static int broken_buffer_getbuffer(PyObject *self, Py_buffer *view, int flags) { - PyErr_SetString( - TestError, - "test_broken_memoryview: expected error in bf_getbuffer"); - return -1; + PyErr_SetString( + TestError, + "test_broken_memoryview: expected error in bf_getbuffer"); + return -1; } static PyBufferProcs memoryviewtester_as_buffer = { - (getbufferproc)broken_buffer_getbuffer, /* bf_getbuffer */ - 0, /* bf_releasebuffer */ + (getbufferproc)broken_buffer_getbuffer, /* bf_getbuffer */ + 0, /* bf_releasebuffer */ }; static PyTypeObject _MemoryViewTester_Type = { - PyVarObject_HEAD_INIT(NULL, 0) - "memoryviewtester", /* Name of this type */ - sizeof(PyObject), /* Basic object size */ - 0, /* Item size for varobject */ - (destructor)PyObject_Del, /* tp_dealloc */ - 0, /* tp_print */ - 0, /* tp_getattr */ - 0, /* tp_setattr */ - 0, /* tp_compare */ - 0, /* tp_repr */ - 0, /* tp_as_number */ - 0, /* tp_as_sequence */ - 0, /* tp_as_mapping */ - 0, /* tp_hash */ - 0, /* tp_call */ - 0, /* tp_str */ - PyObject_GenericGetAttr, /* tp_getattro */ - 0, /* tp_setattro */ - &memoryviewtester_as_buffer, /* tp_as_buffer */ - Py_TPFLAGS_DEFAULT, /* tp_flags */ - 0, /* tp_doc */ - 0, /* tp_traverse */ - 0, /* tp_clear */ - 0, /* tp_richcompare */ - 0, /* tp_weaklistoffset */ - 0, /* tp_iter */ - 0, /* tp_iternext */ - 0, /* tp_methods */ - 0, /* tp_members */ - 0, /* tp_getset */ - 0, /* tp_base */ - 0, /* tp_dict */ - 0, /* tp_descr_get */ - 0, /* tp_descr_set */ - 0, /* tp_dictoffset */ - 0, /* tp_init */ - 0, /* tp_alloc */ - PyType_GenericNew, /* tp_new */ + PyVarObject_HEAD_INIT(NULL, 0) + "memoryviewtester", /* Name of this type */ + sizeof(PyObject), /* Basic object size */ + 0, /* Item size for varobject */ + (destructor)PyObject_Del, /* tp_dealloc */ + 0, /* tp_print */ + 0, /* tp_getattr */ + 0, /* tp_setattr */ + 0, /* tp_compare */ + 0, /* tp_repr */ + 0, /* tp_as_number */ + 0, /* tp_as_sequence */ + 0, /* tp_as_mapping */ + 0, /* tp_hash */ + 0, /* tp_call */ + 0, /* tp_str */ + PyObject_GenericGetAttr, /* tp_getattro */ + 0, /* tp_setattro */ + &memoryviewtester_as_buffer, /* tp_as_buffer */ + Py_TPFLAGS_DEFAULT, /* tp_flags */ + 0, /* tp_doc */ + 0, /* tp_traverse */ + 0, /* tp_clear */ + 0, /* tp_richcompare */ + 0, /* tp_weaklistoffset */ + 0, /* tp_iter */ + 0, /* tp_iternext */ + 0, /* tp_methods */ + 0, /* tp_members */ + 0, /* tp_getset */ + 0, /* tp_base */ + 0, /* tp_dict */ + 0, /* tp_descr_get */ + 0, /* tp_descr_set */ + 0, /* tp_dictoffset */ + 0, /* tp_init */ + 0, /* tp_alloc */ + PyType_GenericNew, /* tp_new */ }; static PyObject* test_broken_memoryview(PyObject* self) { - PyObject *obj = PyObject_New(PyObject, &_MemoryViewTester_Type); - PyObject *res; + PyObject *obj = PyObject_New(PyObject, &_MemoryViewTester_Type); + PyObject *res; + + if (obj == NULL) { + PyErr_Clear(); + PyErr_SetString( + TestError, + "test_broken_memoryview: failed to create object"); + return NULL; + } - if (obj == NULL) { - PyErr_Clear(); - PyErr_SetString( - TestError, - "test_broken_memoryview: failed to create object"); - return NULL; - } - - res = PyMemoryView_FromObject(obj); - if (res || !PyErr_Occurred()){ - PyErr_SetString( - TestError, - "test_broken_memoryview: memoryview() didn't raise an Exception"); - Py_XDECREF(res); - Py_DECREF(obj); - return NULL; - } - - PyErr_Clear(); - Py_DECREF(obj); - Py_RETURN_NONE; + res = PyMemoryView_FromObject(obj); + if (res || !PyErr_Occurred()){ + PyErr_SetString( + TestError, + "test_broken_memoryview: memoryview() didn't raise an Exception"); + Py_XDECREF(res); + Py_DECREF(obj); + return NULL; + } + + PyErr_Clear(); + Py_DECREF(obj); + Py_RETURN_NONE; } @@ -392,22 +392,22 @@ static PyObject * raise_test_long_error(const char* msg) { - return raiseTestError("test_long_api", msg); + return raiseTestError("test_long_api", msg); } -#define TESTNAME test_long_api_inner -#define TYPENAME long -#define F_S_TO_PY PyLong_FromLong -#define F_PY_TO_S PyLong_AsLong -#define F_U_TO_PY PyLong_FromUnsignedLong -#define F_PY_TO_U PyLong_AsUnsignedLong +#define TESTNAME test_long_api_inner +#define TYPENAME long +#define F_S_TO_PY PyLong_FromLong +#define F_PY_TO_S PyLong_AsLong +#define F_U_TO_PY PyLong_FromUnsignedLong +#define F_PY_TO_U PyLong_AsUnsignedLong #include "testcapi_long.h" static PyObject * test_long_api(PyObject* self) { - return TESTNAME(raise_test_long_error); + return TESTNAME(raise_test_long_error); } #undef TESTNAME @@ -422,22 +422,22 @@ static PyObject * raise_test_longlong_error(const char* msg) { - return raiseTestError("test_longlong_api", msg); + return raiseTestError("test_longlong_api", msg); } -#define TESTNAME test_longlong_api_inner -#define TYPENAME PY_LONG_LONG -#define F_S_TO_PY PyLong_FromLongLong -#define F_PY_TO_S PyLong_AsLongLong -#define F_U_TO_PY PyLong_FromUnsignedLongLong -#define F_PY_TO_U PyLong_AsUnsignedLongLong +#define TESTNAME test_longlong_api_inner +#define TYPENAME PY_LONG_LONG +#define F_S_TO_PY PyLong_FromLongLong +#define F_PY_TO_S PyLong_AsLongLong +#define F_U_TO_PY PyLong_FromUnsignedLongLong +#define F_PY_TO_U PyLong_AsUnsignedLongLong #include "testcapi_long.h" static PyObject * test_longlong_api(PyObject* self, PyObject *args) { - return TESTNAME(raise_test_longlong_error); + return TESTNAME(raise_test_longlong_error); } #undef TESTNAME @@ -454,71 +454,71 @@ static PyObject * test_L_code(PyObject *self) { - PyObject *tuple, *num; - PY_LONG_LONG value; + PyObject *tuple, *num; + PY_LONG_LONG value; - tuple = PyTuple_New(1); - if (tuple == NULL) - return NULL; - - num = PyLong_FromLong(42); - if (num == NULL) - return NULL; - - PyTuple_SET_ITEM(tuple, 0, num); - - value = -1; - if (PyArg_ParseTuple(tuple, "L:test_L_code", &value) < 0) - return NULL; - if (value != 42) - return raiseTestError("test_L_code", - "L code returned wrong value for long 42"); - - Py_DECREF(num); - num = PyLong_FromLong(42); - if (num == NULL) - return NULL; - - PyTuple_SET_ITEM(tuple, 0, num); - - value = -1; - if (PyArg_ParseTuple(tuple, "L:test_L_code", &value) < 0) - return NULL; - if (value != 42) - return raiseTestError("test_L_code", - "L code returned wrong value for int 42"); - - Py_DECREF(tuple); - Py_INCREF(Py_None); - return Py_None; + tuple = PyTuple_New(1); + if (tuple == NULL) + return NULL; + + num = PyLong_FromLong(42); + if (num == NULL) + return NULL; + + PyTuple_SET_ITEM(tuple, 0, num); + + value = -1; + if (PyArg_ParseTuple(tuple, "L:test_L_code", &value) < 0) + return NULL; + if (value != 42) + return raiseTestError("test_L_code", + "L code returned wrong value for long 42"); + + Py_DECREF(num); + num = PyLong_FromLong(42); + if (num == NULL) + return NULL; + + PyTuple_SET_ITEM(tuple, 0, num); + + value = -1; + if (PyArg_ParseTuple(tuple, "L:test_L_code", &value) < 0) + return NULL; + if (value != 42) + return raiseTestError("test_L_code", + "L code returned wrong value for int 42"); + + Py_DECREF(tuple); + Py_INCREF(Py_None); + return Py_None; } -#endif /* ifdef HAVE_LONG_LONG */ +#endif /* ifdef HAVE_LONG_LONG */ /* Test tuple argument processing */ static PyObject * getargs_tuple(PyObject *self, PyObject *args) { - int a, b, c; - if (!PyArg_ParseTuple(args, "i(ii)", &a, &b, &c)) - return NULL; - return Py_BuildValue("iii", a, b, c); + int a, b, c; + if (!PyArg_ParseTuple(args, "i(ii)", &a, &b, &c)) + return NULL; + return Py_BuildValue("iii", a, b, c); } /* test PyArg_ParseTupleAndKeywords */ static PyObject *getargs_keywords(PyObject *self, PyObject *args, PyObject *kwargs) { - static char *keywords[] = {"arg1","arg2","arg3","arg4","arg5", NULL}; - static char *fmt="(ii)i|(i(ii))(iii)i"; - int int_args[10]={-1, -1, -1, -1, -1, -1, -1, -1, -1, -1}; - - if (!PyArg_ParseTupleAndKeywords(args, kwargs, fmt, keywords, - &int_args[0], &int_args[1], &int_args[2], &int_args[3], &int_args[4], - &int_args[5], &int_args[6], &int_args[7], &int_args[8], &int_args[9])) - return NULL; - return Py_BuildValue("iiiiiiiiii", - int_args[0], int_args[1], int_args[2], int_args[3], int_args[4], - int_args[5], int_args[6], int_args[7], int_args[8], int_args[9]); + static char *keywords[] = {"arg1","arg2","arg3","arg4","arg5", NULL}; + static char *fmt="(ii)i|(i(ii))(iii)i"; + int int_args[10]={-1, -1, -1, -1, -1, -1, -1, -1, -1, -1}; + + if (!PyArg_ParseTupleAndKeywords(args, kwargs, fmt, keywords, + &int_args[0], &int_args[1], &int_args[2], &int_args[3], &int_args[4], + &int_args[5], &int_args[6], &int_args[7], &int_args[8], &int_args[9])) + return NULL; + return Py_BuildValue("iiiiiiiiii", + int_args[0], int_args[1], int_args[2], int_args[3], int_args[4], + int_args[5], int_args[6], int_args[7], int_args[8], int_args[9]); } /* Functions to call PyArg_ParseTuple with integer format codes, @@ -527,92 +527,92 @@ static PyObject * getargs_b(PyObject *self, PyObject *args) { - unsigned char value; - if (!PyArg_ParseTuple(args, "b", &value)) - return NULL; - return PyLong_FromUnsignedLong((unsigned long)value); + unsigned char value; + if (!PyArg_ParseTuple(args, "b", &value)) + return NULL; + return PyLong_FromUnsignedLong((unsigned long)value); } static PyObject * getargs_B(PyObject *self, PyObject *args) { - unsigned char value; - if (!PyArg_ParseTuple(args, "B", &value)) - return NULL; - return PyLong_FromUnsignedLong((unsigned long)value); + unsigned char value; + if (!PyArg_ParseTuple(args, "B", &value)) + return NULL; + return PyLong_FromUnsignedLong((unsigned long)value); } static PyObject * getargs_H(PyObject *self, PyObject *args) { - unsigned short value; - if (!PyArg_ParseTuple(args, "H", &value)) - return NULL; - return PyLong_FromUnsignedLong((unsigned long)value); + unsigned short value; + if (!PyArg_ParseTuple(args, "H", &value)) + return NULL; + return PyLong_FromUnsignedLong((unsigned long)value); } static PyObject * getargs_I(PyObject *self, PyObject *args) { - unsigned int value; - if (!PyArg_ParseTuple(args, "I", &value)) - return NULL; - return PyLong_FromUnsignedLong((unsigned long)value); + unsigned int value; + if (!PyArg_ParseTuple(args, "I", &value)) + return NULL; + return PyLong_FromUnsignedLong((unsigned long)value); } static PyObject * getargs_k(PyObject *self, PyObject *args) { - unsigned long value; - if (!PyArg_ParseTuple(args, "k", &value)) - return NULL; - return PyLong_FromUnsignedLong(value); + unsigned long value; + if (!PyArg_ParseTuple(args, "k", &value)) + return NULL; + return PyLong_FromUnsignedLong(value); } static PyObject * getargs_i(PyObject *self, PyObject *args) { - int value; - if (!PyArg_ParseTuple(args, "i", &value)) - return NULL; - return PyLong_FromLong((long)value); + int value; + if (!PyArg_ParseTuple(args, "i", &value)) + return NULL; + return PyLong_FromLong((long)value); } static PyObject * getargs_l(PyObject *self, PyObject *args) { - long value; - if (!PyArg_ParseTuple(args, "l", &value)) - return NULL; - return PyLong_FromLong(value); + long value; + if (!PyArg_ParseTuple(args, "l", &value)) + return NULL; + return PyLong_FromLong(value); } static PyObject * getargs_n(PyObject *self, PyObject *args) { - Py_ssize_t value; - if (!PyArg_ParseTuple(args, "n", &value)) - return NULL; - return PyLong_FromSsize_t(value); + Py_ssize_t value; + if (!PyArg_ParseTuple(args, "n", &value)) + return NULL; + return PyLong_FromSsize_t(value); } #ifdef HAVE_LONG_LONG static PyObject * getargs_L(PyObject *self, PyObject *args) { - PY_LONG_LONG value; - if (!PyArg_ParseTuple(args, "L", &value)) - return NULL; - return PyLong_FromLongLong(value); + PY_LONG_LONG value; + if (!PyArg_ParseTuple(args, "L", &value)) + return NULL; + return PyLong_FromLongLong(value); } static PyObject * getargs_K(PyObject *self, PyObject *args) { - unsigned PY_LONG_LONG value; - if (!PyArg_ParseTuple(args, "K", &value)) - return NULL; - return PyLong_FromUnsignedLongLong(value); + unsigned PY_LONG_LONG value; + if (!PyArg_ParseTuple(args, "K", &value)) + return NULL; + return PyLong_FromUnsignedLongLong(value); } #endif @@ -621,54 +621,54 @@ static PyObject * test_k_code(PyObject *self) { - PyObject *tuple, *num; - unsigned long value; + PyObject *tuple, *num; + unsigned long value; + + tuple = PyTuple_New(1); + if (tuple == NULL) + return NULL; + + /* a number larger than ULONG_MAX even on 64-bit platforms */ + num = PyLong_FromString("FFFFFFFFFFFFFFFFFFFFFFFF", NULL, 16); + if (num == NULL) + return NULL; - tuple = PyTuple_New(1); - if (tuple == NULL) - return NULL; - - /* a number larger than ULONG_MAX even on 64-bit platforms */ - num = PyLong_FromString("FFFFFFFFFFFFFFFFFFFFFFFF", NULL, 16); - if (num == NULL) - return NULL; - - value = PyLong_AsUnsignedLongMask(num); - if (value != ULONG_MAX) - return raiseTestError("test_k_code", - "PyLong_AsUnsignedLongMask() returned wrong value for long 0xFFF...FFF"); - - PyTuple_SET_ITEM(tuple, 0, num); - - value = 0; - if (PyArg_ParseTuple(tuple, "k:test_k_code", &value) < 0) - return NULL; - if (value != ULONG_MAX) - return raiseTestError("test_k_code", - "k code returned wrong value for long 0xFFF...FFF"); - - Py_DECREF(num); - num = PyLong_FromString("-FFFFFFFF000000000000000042", NULL, 16); - if (num == NULL) - return NULL; - - value = PyLong_AsUnsignedLongMask(num); - if (value != (unsigned long)-0x42) - return raiseTestError("test_k_code", - "PyLong_AsUnsignedLongMask() returned wrong value for long 0xFFF...FFF"); - - PyTuple_SET_ITEM(tuple, 0, num); - - value = 0; - if (PyArg_ParseTuple(tuple, "k:test_k_code", &value) < 0) - return NULL; - if (value != (unsigned long)-0x42) - return raiseTestError("test_k_code", - "k code returned wrong value for long -0xFFF..000042"); - - Py_DECREF(tuple); - Py_INCREF(Py_None); - return Py_None; + value = PyLong_AsUnsignedLongMask(num); + if (value != ULONG_MAX) + return raiseTestError("test_k_code", + "PyLong_AsUnsignedLongMask() returned wrong value for long 0xFFF...FFF"); + + PyTuple_SET_ITEM(tuple, 0, num); + + value = 0; + if (PyArg_ParseTuple(tuple, "k:test_k_code", &value) < 0) + return NULL; + if (value != ULONG_MAX) + return raiseTestError("test_k_code", + "k code returned wrong value for long 0xFFF...FFF"); + + Py_DECREF(num); + num = PyLong_FromString("-FFFFFFFF000000000000000042", NULL, 16); + if (num == NULL) + return NULL; + + value = PyLong_AsUnsignedLongMask(num); + if (value != (unsigned long)-0x42) + return raiseTestError("test_k_code", + "PyLong_AsUnsignedLongMask() returned wrong value for long 0xFFF...FFF"); + + PyTuple_SET_ITEM(tuple, 0, num); + + value = 0; + if (PyArg_ParseTuple(tuple, "k:test_k_code", &value) < 0) + return NULL; + if (value != (unsigned long)-0x42) + return raiseTestError("test_k_code", + "k code returned wrong value for long -0xFFF..000042"); + + Py_DECREF(tuple); + Py_INCREF(Py_None); + return Py_None; } @@ -683,23 +683,23 @@ tuple = PyTuple_New(1); if (tuple == NULL) - return NULL; + return NULL; obj = PyUnicode_Decode("t\xeate", strlen("t\xeate"), - "latin-1", NULL); + "latin-1", NULL); if (obj == NULL) - return NULL; + return NULL; PyTuple_SET_ITEM(tuple, 0, obj); /* These two blocks used to raise a TypeError: - * "argument must be string without null bytes, not str" + * "argument must be string without null bytes, not str" */ if (PyArg_ParseTuple(tuple, "s:test_s_code1", &value) < 0) - return NULL; + return NULL; if (PyArg_ParseTuple(tuple, "z:test_s_code2", &value) < 0) - return NULL; + return NULL; Py_DECREF(tuple); Py_RETURN_NONE; @@ -708,46 +708,46 @@ static PyObject * test_bug_7414(PyObject *self) { - /* Issue #7414: for PyArg_ParseTupleAndKeywords, 'C' code wasn't being - skipped properly in skipitem() */ - int a = 0, b = 0, result; - char *kwlist[] = {"a", "b", NULL}; - PyObject *tuple = NULL, *dict = NULL, *b_str; - - tuple = PyTuple_New(0); - if (tuple == NULL) - goto failure; - dict = PyDict_New(); - if (dict == NULL) - goto failure; - b_str = PyUnicode_FromString("b"); - if (b_str == NULL) - goto failure; - result = PyDict_SetItemString(dict, "b", b_str); - Py_DECREF(b_str); - if (result < 0) - goto failure; - - result = PyArg_ParseTupleAndKeywords(tuple, dict, "|CC", - kwlist, &a, &b); - if (!result) - goto failure; - - if (a != 0) - return raiseTestError("test_bug_7414", - "C format code not skipped properly"); - if (b != 'b') - return raiseTestError("test_bug_7414", - "C format code returned wrong value"); - - Py_DECREF(dict); - Py_DECREF(tuple); - Py_RETURN_NONE; + /* Issue #7414: for PyArg_ParseTupleAndKeywords, 'C' code wasn't being + skipped properly in skipitem() */ + int a = 0, b = 0, result; + char *kwlist[] = {"a", "b", NULL}; + PyObject *tuple = NULL, *dict = NULL, *b_str; + + tuple = PyTuple_New(0); + if (tuple == NULL) + goto failure; + dict = PyDict_New(); + if (dict == NULL) + goto failure; + b_str = PyUnicode_FromString("b"); + if (b_str == NULL) + goto failure; + result = PyDict_SetItemString(dict, "b", b_str); + Py_DECREF(b_str); + if (result < 0) + goto failure; + + result = PyArg_ParseTupleAndKeywords(tuple, dict, "|CC", + kwlist, &a, &b); + if (!result) + goto failure; + + if (a != 0) + return raiseTestError("test_bug_7414", + "C format code not skipped properly"); + if (b != 'b') + return raiseTestError("test_bug_7414", + "C format code returned wrong value"); + + Py_DECREF(dict); + Py_DECREF(tuple); + Py_RETURN_NONE; failure: - Py_XDECREF(dict); - Py_XDECREF(tuple); - return NULL; + Py_XDECREF(dict); + Py_XDECREF(tuple); + return NULL; } @@ -759,186 +759,186 @@ static PyObject * test_u_code(PyObject *self) { - PyObject *tuple, *obj; - Py_UNICODE *value; - Py_ssize_t len; - int x; - - /* issue4122: Undefined reference to _Py_ascii_whitespace on Windows */ - /* Just use the macro and check that it compiles */ - x = Py_UNICODE_ISSPACE(25); - - tuple = PyTuple_New(1); - if (tuple == NULL) - return NULL; - - obj = PyUnicode_Decode("test", strlen("test"), - "ascii", NULL); - if (obj == NULL) - return NULL; - - PyTuple_SET_ITEM(tuple, 0, obj); - - value = 0; - if (PyArg_ParseTuple(tuple, "u:test_u_code", &value) < 0) - return NULL; - if (value != PyUnicode_AS_UNICODE(obj)) - return raiseTestError("test_u_code", - "u code returned wrong value for u'test'"); - value = 0; - if (PyArg_ParseTuple(tuple, "u#:test_u_code", &value, &len) < 0) - return NULL; - if (value != PyUnicode_AS_UNICODE(obj) || - len != PyUnicode_GET_SIZE(obj)) - return raiseTestError("test_u_code", - "u# code returned wrong values for u'test'"); - - Py_DECREF(tuple); - Py_INCREF(Py_None); - return Py_None; + PyObject *tuple, *obj; + Py_UNICODE *value; + Py_ssize_t len; + int x; + + /* issue4122: Undefined reference to _Py_ascii_whitespace on Windows */ + /* Just use the macro and check that it compiles */ + x = Py_UNICODE_ISSPACE(25); + + tuple = PyTuple_New(1); + if (tuple == NULL) + return NULL; + + obj = PyUnicode_Decode("test", strlen("test"), + "ascii", NULL); + if (obj == NULL) + return NULL; + + PyTuple_SET_ITEM(tuple, 0, obj); + + value = 0; + if (PyArg_ParseTuple(tuple, "u:test_u_code", &value) < 0) + return NULL; + if (value != PyUnicode_AS_UNICODE(obj)) + return raiseTestError("test_u_code", + "u code returned wrong value for u'test'"); + value = 0; + if (PyArg_ParseTuple(tuple, "u#:test_u_code", &value, &len) < 0) + return NULL; + if (value != PyUnicode_AS_UNICODE(obj) || + len != PyUnicode_GET_SIZE(obj)) + return raiseTestError("test_u_code", + "u# code returned wrong values for u'test'"); + + Py_DECREF(tuple); + Py_INCREF(Py_None); + return Py_None; } /* Test Z and Z# codes for PyArg_ParseTuple */ static PyObject * test_Z_code(PyObject *self) { - PyObject *tuple, *obj; - Py_UNICODE *value1, *value2; - Py_ssize_t len1, len2; - - tuple = PyTuple_New(2); - if (tuple == NULL) - return NULL; - - obj = PyUnicode_FromString("test"); - PyTuple_SET_ITEM(tuple, 0, obj); - Py_INCREF(Py_None); - PyTuple_SET_ITEM(tuple, 1, Py_None); - - /* swap values on purpose */ - value1 = NULL; - value2 = PyUnicode_AS_UNICODE(obj); - - /* Test Z for both values */ - if (PyArg_ParseTuple(tuple, "ZZ:test_Z_code", &value1, &value2) < 0) - return NULL; - if (value1 != PyUnicode_AS_UNICODE(obj)) - return raiseTestError("test_Z_code", - "Z code returned wrong value for 'test'"); - if (value2 != NULL) - return raiseTestError("test_Z_code", - "Z code returned wrong value for None"); - - value1 = NULL; - value2 = PyUnicode_AS_UNICODE(obj); - len1 = -1; - len2 = -1; - - /* Test Z# for both values */ - if (PyArg_ParseTuple(tuple, "Z#Z#:test_Z_code", &value1, &len1, - &value2, &len2) < 0) - return NULL; - if (value1 != PyUnicode_AS_UNICODE(obj) || - len1 != PyUnicode_GET_SIZE(obj)) - return raiseTestError("test_Z_code", - "Z# code returned wrong values for 'test'"); - if (value2 != NULL || - len2 != 0) - return raiseTestError("test_Z_code", - "Z# code returned wrong values for None'"); + PyObject *tuple, *obj; + Py_UNICODE *value1, *value2; + Py_ssize_t len1, len2; + + tuple = PyTuple_New(2); + if (tuple == NULL) + return NULL; - Py_DECREF(tuple); - Py_RETURN_NONE; + obj = PyUnicode_FromString("test"); + PyTuple_SET_ITEM(tuple, 0, obj); + Py_INCREF(Py_None); + PyTuple_SET_ITEM(tuple, 1, Py_None); + + /* swap values on purpose */ + value1 = NULL; + value2 = PyUnicode_AS_UNICODE(obj); + + /* Test Z for both values */ + if (PyArg_ParseTuple(tuple, "ZZ:test_Z_code", &value1, &value2) < 0) + return NULL; + if (value1 != PyUnicode_AS_UNICODE(obj)) + return raiseTestError("test_Z_code", + "Z code returned wrong value for 'test'"); + if (value2 != NULL) + return raiseTestError("test_Z_code", + "Z code returned wrong value for None"); + + value1 = NULL; + value2 = PyUnicode_AS_UNICODE(obj); + len1 = -1; + len2 = -1; + + /* Test Z# for both values */ + if (PyArg_ParseTuple(tuple, "Z#Z#:test_Z_code", &value1, &len1, + &value2, &len2) < 0) + return NULL; + if (value1 != PyUnicode_AS_UNICODE(obj) || + len1 != PyUnicode_GET_SIZE(obj)) + return raiseTestError("test_Z_code", + "Z# code returned wrong values for 'test'"); + if (value2 != NULL || + len2 != 0) + return raiseTestError("test_Z_code", + "Z# code returned wrong values for None'"); + + Py_DECREF(tuple); + Py_RETURN_NONE; } static PyObject * test_widechar(PyObject *self) { #if defined(SIZEOF_WCHAR_T) && (SIZEOF_WCHAR_T == 4) - const wchar_t wtext[2] = {(wchar_t)0x10ABCDu}; - size_t wtextlen = 1; + const wchar_t wtext[2] = {(wchar_t)0x10ABCDu}; + size_t wtextlen = 1; #else - const wchar_t wtext[3] = {(wchar_t)0xDBEAu, (wchar_t)0xDFCDu}; - size_t wtextlen = 2; + const wchar_t wtext[3] = {(wchar_t)0xDBEAu, (wchar_t)0xDFCDu}; + size_t wtextlen = 2; #endif - PyObject *wide, *utf8; + PyObject *wide, *utf8; + + wide = PyUnicode_FromWideChar(wtext, wtextlen); + if (wide == NULL) + return NULL; + + utf8 = PyUnicode_FromString("\xf4\x8a\xaf\x8d"); + if (utf8 == NULL) { + Py_DECREF(wide); + return NULL; + } + + if (PyUnicode_GET_SIZE(wide) != PyUnicode_GET_SIZE(utf8)) { + Py_DECREF(wide); + Py_DECREF(utf8); + return raiseTestError("test_widechar", + "wide string and utf8 string " + "have different length"); + } + if (PyUnicode_Compare(wide, utf8)) { + Py_DECREF(wide); + Py_DECREF(utf8); + if (PyErr_Occurred()) + return NULL; + return raiseTestError("test_widechar", + "wide string and utf8 string " + "are different"); + } - wide = PyUnicode_FromWideChar(wtext, wtextlen); - if (wide == NULL) - return NULL; - - utf8 = PyUnicode_FromString("\xf4\x8a\xaf\x8d"); - if (utf8 == NULL) { - Py_DECREF(wide); - return NULL; - } - - if (PyUnicode_GET_SIZE(wide) != PyUnicode_GET_SIZE(utf8)) { - Py_DECREF(wide); - Py_DECREF(utf8); - return raiseTestError("test_widechar", - "wide string and utf8 string " - "have different length"); - } - if (PyUnicode_Compare(wide, utf8)) { - Py_DECREF(wide); - Py_DECREF(utf8); - if (PyErr_Occurred()) - return NULL; - return raiseTestError("test_widechar", - "wide string and utf8 string " - "are different"); - } - - Py_DECREF(wide); - Py_DECREF(utf8); - Py_RETURN_NONE; + Py_DECREF(wide); + Py_DECREF(utf8); + Py_RETURN_NONE; } static PyObject * test_empty_argparse(PyObject *self) { - /* Test that formats can begin with '|'. See issue #4720. */ - PyObject *tuple, *dict = NULL; - static char *kwlist[] = {NULL}; - int result; - tuple = PyTuple_New(0); - if (!tuple) - return NULL; - if ((result = PyArg_ParseTuple(tuple, "|:test_empty_argparse")) < 0) - goto done; - dict = PyDict_New(); - if (!dict) - goto done; - result = PyArg_ParseTupleAndKeywords(tuple, dict, "|:test_empty_argparse", kwlist); + /* Test that formats can begin with '|'. See issue #4720. */ + PyObject *tuple, *dict = NULL; + static char *kwlist[] = {NULL}; + int result; + tuple = PyTuple_New(0); + if (!tuple) + return NULL; + if ((result = PyArg_ParseTuple(tuple, "|:test_empty_argparse")) < 0) + goto done; + dict = PyDict_New(); + if (!dict) + goto done; + result = PyArg_ParseTupleAndKeywords(tuple, dict, "|:test_empty_argparse", kwlist); done: - Py_DECREF(tuple); - Py_XDECREF(dict); - if (result < 0) - return NULL; - else { - Py_RETURN_NONE; - } + Py_DECREF(tuple); + Py_XDECREF(dict); + if (result < 0) + return NULL; + else { + Py_RETURN_NONE; + } } static PyObject * codec_incrementalencoder(PyObject *self, PyObject *args) { - const char *encoding, *errors = NULL; - if (!PyArg_ParseTuple(args, "s|s:test_incrementalencoder", - &encoding, &errors)) - return NULL; - return PyCodec_IncrementalEncoder(encoding, errors); + const char *encoding, *errors = NULL; + if (!PyArg_ParseTuple(args, "s|s:test_incrementalencoder", + &encoding, &errors)) + return NULL; + return PyCodec_IncrementalEncoder(encoding, errors); } static PyObject * codec_incrementaldecoder(PyObject *self, PyObject *args) { - const char *encoding, *errors = NULL; - if (!PyArg_ParseTuple(args, "s|s:test_incrementaldecoder", - &encoding, &errors)) - return NULL; - return PyCodec_IncrementalDecoder(encoding, errors); + const char *encoding, *errors = NULL; + if (!PyArg_ParseTuple(args, "s|s:test_incrementaldecoder", + &encoding, &errors)) + return NULL; + return PyCodec_IncrementalDecoder(encoding, errors); } @@ -946,42 +946,42 @@ static PyObject * test_long_numbits(PyObject *self) { - struct triple { - long input; - size_t nbits; - int sign; - } testcases[] = {{0, 0, 0}, - {1L, 1, 1}, - {-1L, 1, -1}, - {2L, 2, 1}, - {-2L, 2, -1}, - {3L, 2, 1}, - {-3L, 2, -1}, - {4L, 3, 1}, - {-4L, 3, -1}, - {0x7fffL, 15, 1}, /* one Python long digit */ - {-0x7fffL, 15, -1}, - {0xffffL, 16, 1}, - {-0xffffL, 16, -1}, - {0xfffffffL, 28, 1}, - {-0xfffffffL, 28, -1}}; - int i; - - for (i = 0; i < sizeof(testcases) / sizeof(struct triple); ++i) { - PyObject *plong = PyLong_FromLong(testcases[i].input); - size_t nbits = _PyLong_NumBits(plong); - int sign = _PyLong_Sign(plong); - - Py_DECREF(plong); - if (nbits != testcases[i].nbits) - return raiseTestError("test_long_numbits", - "wrong result for _PyLong_NumBits"); - if (sign != testcases[i].sign) - return raiseTestError("test_long_numbits", - "wrong result for _PyLong_Sign"); - } - Py_INCREF(Py_None); - return Py_None; + struct triple { + long input; + size_t nbits; + int sign; + } testcases[] = {{0, 0, 0}, + {1L, 1, 1}, + {-1L, 1, -1}, + {2L, 2, 1}, + {-2L, 2, -1}, + {3L, 2, 1}, + {-3L, 2, -1}, + {4L, 3, 1}, + {-4L, 3, -1}, + {0x7fffL, 15, 1}, /* one Python long digit */ + {-0x7fffL, 15, -1}, + {0xffffL, 16, 1}, + {-0xffffL, 16, -1}, + {0xfffffffL, 28, 1}, + {-0xfffffffL, 28, -1}}; + int i; + + for (i = 0; i < sizeof(testcases) / sizeof(struct triple); ++i) { + PyObject *plong = PyLong_FromLong(testcases[i].input); + size_t nbits = _PyLong_NumBits(plong); + int sign = _PyLong_Sign(plong); + + Py_DECREF(plong); + if (nbits != testcases[i].nbits) + return raiseTestError("test_long_numbits", + "wrong result for _PyLong_NumBits"); + if (sign != testcases[i].sign) + return raiseTestError("test_long_numbits", + "wrong result for _PyLong_Sign"); + } + Py_INCREF(Py_None); + return Py_None; } /* Example passing NULLs to PyObject_Str(NULL). */ @@ -989,38 +989,38 @@ static PyObject * test_null_strings(PyObject *self) { - PyObject *o1 = PyObject_Str(NULL), *o2 = PyObject_Str(NULL); - PyObject *tuple = PyTuple_Pack(2, o1, o2); - Py_XDECREF(o1); - Py_XDECREF(o2); - return tuple; + PyObject *o1 = PyObject_Str(NULL), *o2 = PyObject_Str(NULL); + PyObject *tuple = PyTuple_Pack(2, o1, o2); + Py_XDECREF(o1); + Py_XDECREF(o2); + return tuple; } static PyObject * raise_exception(PyObject *self, PyObject *args) { - PyObject *exc; - PyObject *exc_args, *v; - int num_args, i; - - if (!PyArg_ParseTuple(args, "Oi:raise_exception", - &exc, &num_args)) - return NULL; - - exc_args = PyTuple_New(num_args); - if (exc_args == NULL) - return NULL; - for (i = 0; i < num_args; ++i) { - v = PyLong_FromLong(i); - if (v == NULL) { - Py_DECREF(exc_args); - return NULL; - } - PyTuple_SET_ITEM(exc_args, i, v); - } - PyErr_SetObject(exc, exc_args); - Py_DECREF(exc_args); - return NULL; + PyObject *exc; + PyObject *exc_args, *v; + int num_args, i; + + if (!PyArg_ParseTuple(args, "Oi:raise_exception", + &exc, &num_args)) + return NULL; + + exc_args = PyTuple_New(num_args); + if (exc_args == NULL) + return NULL; + for (i = 0; i < num_args; ++i) { + v = PyLong_FromLong(i); + if (v == NULL) { + Py_DECREF(exc_args); + return NULL; + } + PyTuple_SET_ITEM(exc_args, i, v); + } + PyErr_SetObject(exc, exc_args); + Py_DECREF(exc_args); + return NULL; } #ifdef WITH_THREAD @@ -1037,14 +1037,14 @@ static int _make_call(void *callable) { - PyObject *rc; - int success; - PyGILState_STATE s = PyGILState_Ensure(); - rc = PyObject_CallFunction((PyObject *)callable, ""); - success = (rc != NULL); - Py_XDECREF(rc); - PyGILState_Release(s); - return success; + PyObject *rc; + int success; + PyGILState_STATE s = PyGILState_Ensure(); + rc = PyObject_CallFunction((PyObject *)callable, ""); + success = (rc != NULL); + Py_XDECREF(rc); + PyGILState_Release(s); + return success; } /* Same thing, but releases `thread_done` when it returns. This variant @@ -1053,70 +1053,70 @@ static void _make_call_from_thread(void *callable) { - _make_call(callable); - PyThread_release_lock(thread_done); + _make_call(callable); + PyThread_release_lock(thread_done); } static PyObject * test_thread_state(PyObject *self, PyObject *args) { - PyObject *fn; - int success = 1; + PyObject *fn; + int success = 1; - if (!PyArg_ParseTuple(args, "O:test_thread_state", &fn)) - return NULL; + if (!PyArg_ParseTuple(args, "O:test_thread_state", &fn)) + return NULL; + + if (!PyCallable_Check(fn)) { + PyErr_Format(PyExc_TypeError, "'%s' object is not callable", + fn->ob_type->tp_name); + return NULL; + } - if (!PyCallable_Check(fn)) { - PyErr_Format(PyExc_TypeError, "'%s' object is not callable", - fn->ob_type->tp_name); - return NULL; - } - - /* Ensure Python is set up for threading */ - PyEval_InitThreads(); - thread_done = PyThread_allocate_lock(); - if (thread_done == NULL) - return PyErr_NoMemory(); - PyThread_acquire_lock(thread_done, 1); - - /* Start a new thread with our callback. */ - PyThread_start_new_thread(_make_call_from_thread, fn); - /* Make the callback with the thread lock held by this thread */ - success &= _make_call(fn); - /* Do it all again, but this time with the thread-lock released */ - Py_BEGIN_ALLOW_THREADS - success &= _make_call(fn); - PyThread_acquire_lock(thread_done, 1); /* wait for thread to finish */ - Py_END_ALLOW_THREADS - - /* And once more with and without a thread - XXX - should use a lock and work out exactly what we are trying - to test - */ - Py_BEGIN_ALLOW_THREADS - PyThread_start_new_thread(_make_call_from_thread, fn); - success &= _make_call(fn); - PyThread_acquire_lock(thread_done, 1); /* wait for thread to finish */ - Py_END_ALLOW_THREADS - - /* Release lock we acquired above. This is required on HP-UX. */ - PyThread_release_lock(thread_done); - - PyThread_free_lock(thread_done); - if (!success) - return NULL; - Py_RETURN_NONE; + /* Ensure Python is set up for threading */ + PyEval_InitThreads(); + thread_done = PyThread_allocate_lock(); + if (thread_done == NULL) + return PyErr_NoMemory(); + PyThread_acquire_lock(thread_done, 1); + + /* Start a new thread with our callback. */ + PyThread_start_new_thread(_make_call_from_thread, fn); + /* Make the callback with the thread lock held by this thread */ + success &= _make_call(fn); + /* Do it all again, but this time with the thread-lock released */ + Py_BEGIN_ALLOW_THREADS + success &= _make_call(fn); + PyThread_acquire_lock(thread_done, 1); /* wait for thread to finish */ + Py_END_ALLOW_THREADS + + /* And once more with and without a thread + XXX - should use a lock and work out exactly what we are trying + to test + */ + Py_BEGIN_ALLOW_THREADS + PyThread_start_new_thread(_make_call_from_thread, fn); + success &= _make_call(fn); + PyThread_acquire_lock(thread_done, 1); /* wait for thread to finish */ + Py_END_ALLOW_THREADS + + /* Release lock we acquired above. This is required on HP-UX. */ + PyThread_release_lock(thread_done); + + PyThread_free_lock(thread_done); + if (!success) + return NULL; + Py_RETURN_NONE; } /* test Py_AddPendingCalls using threads */ static int _pending_callback(void *arg) { - /* we assume the argument is callable object to which we own a reference */ - PyObject *callable = (PyObject *)arg; - PyObject *r = PyObject_CallObject(callable, NULL); - Py_DECREF(callable); - Py_XDECREF(r); - return r != NULL ? 0 : -1; + /* we assume the argument is callable object to which we own a reference */ + PyObject *callable = (PyObject *)arg; + PyObject *r = PyObject_CallObject(callable, NULL); + Py_DECREF(callable); + Py_XDECREF(r); + return r != NULL ? 0 : -1; } /* The following requests n callbacks to _pending_callback. It can be @@ -1124,25 +1124,25 @@ */ PyObject *pending_threadfunc(PyObject *self, PyObject *arg) { - PyObject *callable; - int r; - if (PyArg_ParseTuple(arg, "O", &callable) == 0) - return NULL; - - /* create the reference for the callbackwhile we hold the lock */ - Py_INCREF(callable); - - Py_BEGIN_ALLOW_THREADS - r = Py_AddPendingCall(&_pending_callback, callable); - Py_END_ALLOW_THREADS - - if (r<0) { - Py_DECREF(callable); /* unsuccessful add, destroy the extra reference */ - Py_INCREF(Py_False); - return Py_False; - } - Py_INCREF(Py_True); - return Py_True; + PyObject *callable; + int r; + if (PyArg_ParseTuple(arg, "O", &callable) == 0) + return NULL; + + /* create the reference for the callbackwhile we hold the lock */ + Py_INCREF(callable); + + Py_BEGIN_ALLOW_THREADS + r = Py_AddPendingCall(&_pending_callback, callable); + Py_END_ALLOW_THREADS + + if (r<0) { + Py_DECREF(callable); /* unsuccessful add, destroy the extra reference */ + Py_INCREF(Py_False); + return Py_False; + } + Py_INCREF(Py_True); + return Py_True; } #endif @@ -1150,34 +1150,34 @@ static PyObject * test_string_from_format(PyObject *self, PyObject *args) { - PyObject *result; - char *msg; + PyObject *result; + char *msg; -#define CHECK_1_FORMAT(FORMAT, TYPE) \ - result = PyUnicode_FromFormat(FORMAT, (TYPE)1); \ - if (result == NULL) \ - return NULL; \ - if (strcmp(_PyUnicode_AsString(result), "1")) { \ - msg = FORMAT " failed at 1"; \ - goto Fail; \ - } \ - Py_DECREF(result) - - CHECK_1_FORMAT("%d", int); - CHECK_1_FORMAT("%ld", long); - /* The z width modifier was added in Python 2.5. */ - CHECK_1_FORMAT("%zd", Py_ssize_t); - - /* The u type code was added in Python 2.5. */ - CHECK_1_FORMAT("%u", unsigned int); - CHECK_1_FORMAT("%lu", unsigned long); - CHECK_1_FORMAT("%zu", size_t); +#define CHECK_1_FORMAT(FORMAT, TYPE) \ + result = PyUnicode_FromFormat(FORMAT, (TYPE)1); \ + if (result == NULL) \ + return NULL; \ + if (strcmp(_PyUnicode_AsString(result), "1")) { \ + msg = FORMAT " failed at 1"; \ + goto Fail; \ + } \ + Py_DECREF(result) + + CHECK_1_FORMAT("%d", int); + CHECK_1_FORMAT("%ld", long); + /* The z width modifier was added in Python 2.5. */ + CHECK_1_FORMAT("%zd", Py_ssize_t); + + /* The u type code was added in Python 2.5. */ + CHECK_1_FORMAT("%u", unsigned int); + CHECK_1_FORMAT("%lu", unsigned long); + CHECK_1_FORMAT("%zu", size_t); - Py_RETURN_NONE; + Py_RETURN_NONE; Fail: - Py_XDECREF(result); - return raiseTestError("test_string_from_format", msg); + Py_XDECREF(result); + return raiseTestError("test_string_from_format", msg); #undef CHECK_1_FORMAT } @@ -1185,70 +1185,70 @@ static PyObject * test_unicode_compare_with_ascii(PyObject *self) { - PyObject *py_s = PyUnicode_FromStringAndSize("str\0", 4); - int result; - if (py_s == NULL) - return NULL; - result = PyUnicode_CompareWithASCIIString(py_s, "str"); - Py_DECREF(py_s); - if (!result) { - PyErr_SetString(TestError, "Python string ending in NULL " - "should not compare equal to c string."); - return NULL; - } - Py_RETURN_NONE; + PyObject *py_s = PyUnicode_FromStringAndSize("str\0", 4); + int result; + if (py_s == NULL) + return NULL; + result = PyUnicode_CompareWithASCIIString(py_s, "str"); + Py_DECREF(py_s); + if (!result) { + PyErr_SetString(TestError, "Python string ending in NULL " + "should not compare equal to c string."); + return NULL; + } + Py_RETURN_NONE; }; /* This is here to provide a docstring for test_descr. */ static PyObject * test_with_docstring(PyObject *self) { - Py_RETURN_NONE; + Py_RETURN_NONE; } /* Test PyOS_string_to_double. */ static PyObject * test_string_to_double(PyObject *self) { - double result; - char *msg; + double result; + char *msg; -#define CHECK_STRING(STR, expected) \ - result = PyOS_string_to_double(STR, NULL, NULL); \ - if (result == -1.0 && PyErr_Occurred()) \ - return NULL; \ - if (result != expected) { \ - msg = "conversion of " STR " to float failed"; \ - goto fail; \ - } - -#define CHECK_INVALID(STR) \ - result = PyOS_string_to_double(STR, NULL, NULL); \ - if (result == -1.0 && PyErr_Occurred()) { \ - if (PyErr_ExceptionMatches(PyExc_ValueError)) \ - PyErr_Clear(); \ - else \ - return NULL; \ - } \ - else { \ - msg = "conversion of " STR " didn't raise ValueError"; \ - goto fail; \ - } - - CHECK_STRING("0.1", 0.1); - CHECK_STRING("1.234", 1.234); - CHECK_STRING("-1.35", -1.35); - CHECK_STRING(".1e01", 1.0); - CHECK_STRING("2.e-2", 0.02); - - CHECK_INVALID(" 0.1"); - CHECK_INVALID("\t\n-3"); - CHECK_INVALID(".123 "); - CHECK_INVALID("3\n"); - CHECK_INVALID("123abc"); +#define CHECK_STRING(STR, expected) \ + result = PyOS_string_to_double(STR, NULL, NULL); \ + if (result == -1.0 && PyErr_Occurred()) \ + return NULL; \ + if (result != expected) { \ + msg = "conversion of " STR " to float failed"; \ + goto fail; \ + } + +#define CHECK_INVALID(STR) \ + result = PyOS_string_to_double(STR, NULL, NULL); \ + if (result == -1.0 && PyErr_Occurred()) { \ + if (PyErr_ExceptionMatches(PyExc_ValueError)) \ + PyErr_Clear(); \ + else \ + return NULL; \ + } \ + else { \ + msg = "conversion of " STR " didn't raise ValueError"; \ + goto fail; \ + } + + CHECK_STRING("0.1", 0.1); + CHECK_STRING("1.234", 1.234); + CHECK_STRING("-1.35", -1.35); + CHECK_STRING(".1e01", 1.0); + CHECK_STRING("2.e-2", 0.02); + + CHECK_INVALID(" 0.1"); + CHECK_INVALID("\t\n-3"); + CHECK_INVALID(".123 "); + CHECK_INVALID("3\n"); + CHECK_INVALID("123abc"); - Py_RETURN_NONE; + Py_RETURN_NONE; fail: - return raiseTestError("test_string_to_double", msg); + return raiseTestError("test_string_to_double", msg); #undef CHECK_STRING #undef CHECK_INVALID } @@ -1265,143 +1265,143 @@ static void capsule_destructor(PyObject *o) { - capsule_destructor_call_count++; - if (PyCapsule_GetContext(o) != capsule_context) { - capsule_error = "context did not match in destructor!"; - } else if (PyCapsule_GetDestructor(o) != capsule_destructor) { - capsule_error = "destructor did not match in destructor! (woah!)"; - } else if (PyCapsule_GetName(o) != capsule_name) { - capsule_error = "name did not match in destructor!"; - } else if (PyCapsule_GetPointer(o, capsule_name) != capsule_pointer) { - capsule_error = "pointer did not match in destructor!"; - } + capsule_destructor_call_count++; + if (PyCapsule_GetContext(o) != capsule_context) { + capsule_error = "context did not match in destructor!"; + } else if (PyCapsule_GetDestructor(o) != capsule_destructor) { + capsule_error = "destructor did not match in destructor! (woah!)"; + } else if (PyCapsule_GetName(o) != capsule_name) { + capsule_error = "name did not match in destructor!"; + } else if (PyCapsule_GetPointer(o, capsule_name) != capsule_pointer) { + capsule_error = "pointer did not match in destructor!"; + } } typedef struct { - char *name; - char *module; - char *attribute; + char *name; + char *module; + char *attribute; } known_capsule; static PyObject * test_capsule(PyObject *self, PyObject *args) { - PyObject *object; - const char *error = NULL; - void *pointer; - void *pointer2; - known_capsule known_capsules[] = { - #define KNOWN_CAPSULE(module, name) { module "." name, module, name } - KNOWN_CAPSULE("_socket", "CAPI"), - KNOWN_CAPSULE("_curses", "_C_API"), - KNOWN_CAPSULE("datetime", "datetime_CAPI"), - { NULL, NULL }, - }; - known_capsule *known = &known_capsules[0]; + PyObject *object; + const char *error = NULL; + void *pointer; + void *pointer2; + known_capsule known_capsules[] = { + #define KNOWN_CAPSULE(module, name) { module "." name, module, name } + KNOWN_CAPSULE("_socket", "CAPI"), + KNOWN_CAPSULE("_curses", "_C_API"), + KNOWN_CAPSULE("datetime", "datetime_CAPI"), + { NULL, NULL }, + }; + known_capsule *known = &known_capsules[0]; #define FAIL(x) { error = (x); goto exit; } #define CHECK_DESTRUCTOR \ - if (capsule_error) { \ - FAIL(capsule_error); \ - } \ - else if (!capsule_destructor_call_count) { \ - FAIL("destructor not called!"); \ - } \ - capsule_destructor_call_count = 0; \ - - object = PyCapsule_New(capsule_pointer, capsule_name, capsule_destructor); - PyCapsule_SetContext(object, capsule_context); - capsule_destructor(object); - CHECK_DESTRUCTOR; - Py_DECREF(object); - CHECK_DESTRUCTOR; - - object = PyCapsule_New(known, "ignored", NULL); - PyCapsule_SetPointer(object, capsule_pointer); - PyCapsule_SetName(object, capsule_name); - PyCapsule_SetDestructor(object, capsule_destructor); - PyCapsule_SetContext(object, capsule_context); - capsule_destructor(object); - CHECK_DESTRUCTOR; - /* intentionally access using the wrong name */ - pointer2 = PyCapsule_GetPointer(object, "the wrong name"); - if (!PyErr_Occurred()) { - FAIL("PyCapsule_GetPointer should have failed but did not!"); - } - PyErr_Clear(); - if (pointer2) { - if (pointer2 == capsule_pointer) { - FAIL("PyCapsule_GetPointer should not have" - " returned the internal pointer!"); - } else { - FAIL("PyCapsule_GetPointer should have " - "returned NULL pointer but did not!"); - } - } - PyCapsule_SetDestructor(object, NULL); - Py_DECREF(object); - if (capsule_destructor_call_count) { - FAIL("destructor called when it should not have been!"); - } - - for (known = &known_capsules[0]; known->module != NULL; known++) { - /* yeah, ordinarily I wouldn't do this either, - but it's fine for this test harness. - */ - static char buffer[256]; + if (capsule_error) { \ + FAIL(capsule_error); \ + } \ + else if (!capsule_destructor_call_count) { \ + FAIL("destructor not called!"); \ + } \ + capsule_destructor_call_count = 0; \ + + object = PyCapsule_New(capsule_pointer, capsule_name, capsule_destructor); + PyCapsule_SetContext(object, capsule_context); + capsule_destructor(object); + CHECK_DESTRUCTOR; + Py_DECREF(object); + CHECK_DESTRUCTOR; + + object = PyCapsule_New(known, "ignored", NULL); + PyCapsule_SetPointer(object, capsule_pointer); + PyCapsule_SetName(object, capsule_name); + PyCapsule_SetDestructor(object, capsule_destructor); + PyCapsule_SetContext(object, capsule_context); + capsule_destructor(object); + CHECK_DESTRUCTOR; + /* intentionally access using the wrong name */ + pointer2 = PyCapsule_GetPointer(object, "the wrong name"); + if (!PyErr_Occurred()) { + FAIL("PyCapsule_GetPointer should have failed but did not!"); + } + PyErr_Clear(); + if (pointer2) { + if (pointer2 == capsule_pointer) { + FAIL("PyCapsule_GetPointer should not have" + " returned the internal pointer!"); + } else { + FAIL("PyCapsule_GetPointer should have " + "returned NULL pointer but did not!"); + } + } + PyCapsule_SetDestructor(object, NULL); + Py_DECREF(object); + if (capsule_destructor_call_count) { + FAIL("destructor called when it should not have been!"); + } + + for (known = &known_capsules[0]; known->module != NULL; known++) { + /* yeah, ordinarily I wouldn't do this either, + but it's fine for this test harness. + */ + static char buffer[256]; #undef FAIL #define FAIL(x) \ - { \ - sprintf(buffer, "%s module: \"%s\" attribute: \"%s\"", \ - x, known->module, known->attribute); \ - error = buffer; \ - goto exit; \ - } \ - - PyObject *module = PyImport_ImportModule(known->module); - if (module) { - pointer = PyCapsule_Import(known->name, 0); - if (!pointer) { - Py_DECREF(module); - FAIL("PyCapsule_GetPointer returned NULL unexpectedly!"); - } - object = PyObject_GetAttrString(module, known->attribute); - if (!object) { - Py_DECREF(module); - return NULL; - } - pointer2 = PyCapsule_GetPointer(object, - "weebles wobble but they don't fall down"); - if (!PyErr_Occurred()) { - Py_DECREF(object); - Py_DECREF(module); - FAIL("PyCapsule_GetPointer should have failed but did not!"); - } - PyErr_Clear(); - if (pointer2) { - Py_DECREF(module); - Py_DECREF(object); - if (pointer2 == pointer) { - FAIL("PyCapsule_GetPointer should not have" - " returned its internal pointer!"); - } else { - FAIL("PyCapsule_GetPointer should have" - " returned NULL pointer but did not!"); - } - } - Py_DECREF(object); - Py_DECREF(module); - } - else - PyErr_Clear(); - } + { \ + sprintf(buffer, "%s module: \"%s\" attribute: \"%s\"", \ + x, known->module, known->attribute); \ + error = buffer; \ + goto exit; \ + } \ + + PyObject *module = PyImport_ImportModule(known->module); + if (module) { + pointer = PyCapsule_Import(known->name, 0); + if (!pointer) { + Py_DECREF(module); + FAIL("PyCapsule_GetPointer returned NULL unexpectedly!"); + } + object = PyObject_GetAttrString(module, known->attribute); + if (!object) { + Py_DECREF(module); + return NULL; + } + pointer2 = PyCapsule_GetPointer(object, + "weebles wobble but they don't fall down"); + if (!PyErr_Occurred()) { + Py_DECREF(object); + Py_DECREF(module); + FAIL("PyCapsule_GetPointer should have failed but did not!"); + } + PyErr_Clear(); + if (pointer2) { + Py_DECREF(module); + Py_DECREF(object); + if (pointer2 == pointer) { + FAIL("PyCapsule_GetPointer should not have" + " returned its internal pointer!"); + } else { + FAIL("PyCapsule_GetPointer should have" + " returned NULL pointer but did not!"); + } + } + Py_DECREF(object); + Py_DECREF(module); + } + else + PyErr_Clear(); + } exit: - if (error) { - return raiseTestError("test_capsule", error); - } - Py_RETURN_NONE; + if (error) { + return raiseTestError("test_capsule", error); + } + Py_RETURN_NONE; #undef FAIL } @@ -1409,112 +1409,112 @@ /* Profiling of integer performance */ static void print_delta(int test, struct timeval *s, struct timeval *e) { - e->tv_sec -= s->tv_sec; - e->tv_usec -= s->tv_usec; - if (e->tv_usec < 0) { - e->tv_sec -=1; - e->tv_usec += 1000000; - } - printf("Test %d: %d.%06ds\n", test, (int)e->tv_sec, (int)e->tv_usec); + e->tv_sec -= s->tv_sec; + e->tv_usec -= s->tv_usec; + if (e->tv_usec < 0) { + e->tv_sec -=1; + e->tv_usec += 1000000; + } + printf("Test %d: %d.%06ds\n", test, (int)e->tv_sec, (int)e->tv_usec); } static PyObject * profile_int(PyObject *self, PyObject* args) { - int i, k; - struct timeval start, stop; - PyObject *single, **multiple, *op1, *result; - - /* Test 1: Allocate and immediately deallocate - many small integers */ - gettimeofday(&start, NULL); - for(k=0; k < 20000; k++) - for(i=0; i < 1000; i++) { - single = PyLong_FromLong(i); - Py_DECREF(single); - } - gettimeofday(&stop, NULL); - print_delta(1, &start, &stop); - - /* Test 2: Allocate and immediately deallocate - many large integers */ - gettimeofday(&start, NULL); - for(k=0; k < 20000; k++) - for(i=0; i < 1000; i++) { - single = PyLong_FromLong(i+1000000); - Py_DECREF(single); - } - gettimeofday(&stop, NULL); - print_delta(2, &start, &stop); - - /* Test 3: Allocate a few integers, then release - them all simultaneously. */ - multiple = malloc(sizeof(PyObject*) * 1000); - gettimeofday(&start, NULL); - for(k=0; k < 20000; k++) { - for(i=0; i < 1000; i++) { - multiple[i] = PyLong_FromLong(i+1000000); - } - for(i=0; i < 1000; i++) { - Py_DECREF(multiple[i]); - } - } - gettimeofday(&stop, NULL); - print_delta(3, &start, &stop); - - /* Test 4: Allocate many integers, then release - them all simultaneously. */ - multiple = malloc(sizeof(PyObject*) * 1000000); - gettimeofday(&start, NULL); - for(k=0; k < 20; k++) { - for(i=0; i < 1000000; i++) { - multiple[i] = PyLong_FromLong(i+1000000); - } - for(i=0; i < 1000000; i++) { - Py_DECREF(multiple[i]); - } - } - gettimeofday(&stop, NULL); - print_delta(4, &start, &stop); - - /* Test 5: Allocate many integers < 32000 */ - multiple = malloc(sizeof(PyObject*) * 1000000); - gettimeofday(&start, NULL); - for(k=0; k < 10; k++) { - for(i=0; i < 1000000; i++) { - multiple[i] = PyLong_FromLong(i+1000); - } - for(i=0; i < 1000000; i++) { - Py_DECREF(multiple[i]); - } - } - gettimeofday(&stop, NULL); - print_delta(5, &start, &stop); - - /* Test 6: Perform small int addition */ - op1 = PyLong_FromLong(1); - gettimeofday(&start, NULL); - for(i=0; i < 10000000; i++) { - result = PyNumber_Add(op1, op1); - Py_DECREF(result); - } - gettimeofday(&stop, NULL); - Py_DECREF(op1); - print_delta(6, &start, &stop); - - /* Test 7: Perform medium int addition */ - op1 = PyLong_FromLong(1000); - gettimeofday(&start, NULL); - for(i=0; i < 10000000; i++) { - result = PyNumber_Add(op1, op1); - Py_DECREF(result); - } - gettimeofday(&stop, NULL); - Py_DECREF(op1); - print_delta(7, &start, &stop); + int i, k; + struct timeval start, stop; + PyObject *single, **multiple, *op1, *result; + + /* Test 1: Allocate and immediately deallocate + many small integers */ + gettimeofday(&start, NULL); + for(k=0; k < 20000; k++) + for(i=0; i < 1000; i++) { + single = PyLong_FromLong(i); + Py_DECREF(single); + } + gettimeofday(&stop, NULL); + print_delta(1, &start, &stop); + + /* Test 2: Allocate and immediately deallocate + many large integers */ + gettimeofday(&start, NULL); + for(k=0; k < 20000; k++) + for(i=0; i < 1000; i++) { + single = PyLong_FromLong(i+1000000); + Py_DECREF(single); + } + gettimeofday(&stop, NULL); + print_delta(2, &start, &stop); + + /* Test 3: Allocate a few integers, then release + them all simultaneously. */ + multiple = malloc(sizeof(PyObject*) * 1000); + gettimeofday(&start, NULL); + for(k=0; k < 20000; k++) { + for(i=0; i < 1000; i++) { + multiple[i] = PyLong_FromLong(i+1000000); + } + for(i=0; i < 1000; i++) { + Py_DECREF(multiple[i]); + } + } + gettimeofday(&stop, NULL); + print_delta(3, &start, &stop); + + /* Test 4: Allocate many integers, then release + them all simultaneously. */ + multiple = malloc(sizeof(PyObject*) * 1000000); + gettimeofday(&start, NULL); + for(k=0; k < 20; k++) { + for(i=0; i < 1000000; i++) { + multiple[i] = PyLong_FromLong(i+1000000); + } + for(i=0; i < 1000000; i++) { + Py_DECREF(multiple[i]); + } + } + gettimeofday(&stop, NULL); + print_delta(4, &start, &stop); + + /* Test 5: Allocate many integers < 32000 */ + multiple = malloc(sizeof(PyObject*) * 1000000); + gettimeofday(&start, NULL); + for(k=0; k < 10; k++) { + for(i=0; i < 1000000; i++) { + multiple[i] = PyLong_FromLong(i+1000); + } + for(i=0; i < 1000000; i++) { + Py_DECREF(multiple[i]); + } + } + gettimeofday(&stop, NULL); + print_delta(5, &start, &stop); + + /* Test 6: Perform small int addition */ + op1 = PyLong_FromLong(1); + gettimeofday(&start, NULL); + for(i=0; i < 10000000; i++) { + result = PyNumber_Add(op1, op1); + Py_DECREF(result); + } + gettimeofday(&stop, NULL); + Py_DECREF(op1); + print_delta(6, &start, &stop); + + /* Test 7: Perform medium int addition */ + op1 = PyLong_FromLong(1000); + gettimeofday(&start, NULL); + for(i=0; i < 10000000; i++) { + result = PyNumber_Add(op1, op1); + Py_DECREF(result); + } + gettimeofday(&stop, NULL); + Py_DECREF(op1); + print_delta(7, &start, &stop); - Py_INCREF(Py_None); - return Py_None; + Py_INCREF(Py_None); + return Py_None; } #endif @@ -1522,40 +1522,40 @@ static PyObject * traceback_print(PyObject *self, PyObject *args) { - PyObject *file; - PyObject *traceback; - int result; - - if (!PyArg_ParseTuple(args, "OO:traceback_print", - &traceback, &file)) - return NULL; - - result = PyTraceBack_Print(traceback, file); - if (result < 0) - return NULL; - Py_RETURN_NONE; + PyObject *file; + PyObject *traceback; + int result; + + if (!PyArg_ParseTuple(args, "OO:traceback_print", + &traceback, &file)) + return NULL; + + result = PyTraceBack_Print(traceback, file); + if (result < 0) + return NULL; + Py_RETURN_NONE; } /* To test the format of exceptions as printed out. */ static PyObject * exception_print(PyObject *self, PyObject *args) { - PyObject *value; - PyObject *tb; + PyObject *value; + PyObject *tb; - if (!PyArg_ParseTuple(args, "O:exception_print", - &value)) - return NULL; - if (!PyExceptionInstance_Check(value)) { - PyErr_Format(PyExc_TypeError, "an exception instance is required"); - return NULL; - } - - tb = PyException_GetTraceback(value); - PyErr_Display((PyObject *) Py_TYPE(value), value, tb); - Py_XDECREF(tb); + if (!PyArg_ParseTuple(args, "O:exception_print", + &value)) + return NULL; + if (!PyExceptionInstance_Check(value)) { + PyErr_Format(PyExc_TypeError, "an exception instance is required"); + return NULL; + } - Py_RETURN_NONE; + tb = PyException_GetTraceback(value); + PyErr_Display((PyObject *) Py_TYPE(value), value, tb); + Py_XDECREF(tb); + + Py_RETURN_NONE; } @@ -1565,8 +1565,8 @@ static PyObject * raise_memoryerror(PyObject *self) { - PyErr_NoMemory(); - return NULL; + PyErr_NoMemory(); + return NULL; } /* Issue 6012 */ @@ -1574,304 +1574,304 @@ static int failing_converter(PyObject *obj, void *arg) { - /* Clone str1, then let the conversion fail. */ - assert(str1); - str2 = str1; - Py_INCREF(str2); - return 0; + /* Clone str1, then let the conversion fail. */ + assert(str1); + str2 = str1; + Py_INCREF(str2); + return 0; } static PyObject* argparsing(PyObject *o, PyObject *args) { - PyObject *res; - str1 = str2 = NULL; - if (!PyArg_ParseTuple(args, "O&O&", - PyUnicode_FSConverter, &str1, - failing_converter, &str2)) { - if (!str2) - /* argument converter not called? */ - return NULL; - /* Should be 1 */ - res = PyLong_FromLong(Py_REFCNT(str2)); - Py_DECREF(str2); - PyErr_Clear(); - return res; - } - Py_RETURN_NONE; + PyObject *res; + str1 = str2 = NULL; + if (!PyArg_ParseTuple(args, "O&O&", + PyUnicode_FSConverter, &str1, + failing_converter, &str2)) { + if (!str2) + /* argument converter not called? */ + return NULL; + /* Should be 1 */ + res = PyLong_FromLong(Py_REFCNT(str2)); + Py_DECREF(str2); + PyErr_Clear(); + return res; + } + Py_RETURN_NONE; } static PyMethodDef TestMethods[] = { - {"raise_exception", raise_exception, METH_VARARGS}, - {"raise_memoryerror", (PyCFunction)raise_memoryerror, METH_NOARGS}, - {"test_config", (PyCFunction)test_config, METH_NOARGS}, - {"test_list_api", (PyCFunction)test_list_api, METH_NOARGS}, - {"test_dict_iteration", (PyCFunction)test_dict_iteration,METH_NOARGS}, - {"test_lazy_hash_inheritance", (PyCFunction)test_lazy_hash_inheritance,METH_NOARGS}, - {"test_broken_memoryview", (PyCFunction)test_broken_memoryview,METH_NOARGS}, - {"test_long_api", (PyCFunction)test_long_api, METH_NOARGS}, - {"test_long_numbits", (PyCFunction)test_long_numbits, METH_NOARGS}, - {"test_k_code", (PyCFunction)test_k_code, METH_NOARGS}, - {"test_empty_argparse", (PyCFunction)test_empty_argparse,METH_NOARGS}, - {"test_bug_7414", (PyCFunction)test_bug_7414, METH_NOARGS}, - {"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, - PyDoc_STR("This is a pretty normal docstring.")}, - {"test_string_to_double", (PyCFunction)test_string_to_double, METH_NOARGS}, - {"test_unicode_compare_with_ascii", (PyCFunction)test_unicode_compare_with_ascii, METH_NOARGS}, - {"test_capsule", (PyCFunction)test_capsule, METH_NOARGS}, - {"getargs_tuple", getargs_tuple, METH_VARARGS}, - {"getargs_keywords", (PyCFunction)getargs_keywords, - METH_VARARGS|METH_KEYWORDS}, - {"getargs_b", getargs_b, METH_VARARGS}, - {"getargs_B", getargs_B, METH_VARARGS}, - {"getargs_H", getargs_H, METH_VARARGS}, - {"getargs_I", getargs_I, METH_VARARGS}, - {"getargs_k", getargs_k, METH_VARARGS}, - {"getargs_i", getargs_i, METH_VARARGS}, - {"getargs_l", getargs_l, METH_VARARGS}, - {"getargs_n", getargs_n, METH_VARARGS}, + {"raise_exception", raise_exception, METH_VARARGS}, + {"raise_memoryerror", (PyCFunction)raise_memoryerror, METH_NOARGS}, + {"test_config", (PyCFunction)test_config, METH_NOARGS}, + {"test_list_api", (PyCFunction)test_list_api, METH_NOARGS}, + {"test_dict_iteration", (PyCFunction)test_dict_iteration,METH_NOARGS}, + {"test_lazy_hash_inheritance", (PyCFunction)test_lazy_hash_inheritance,METH_NOARGS}, + {"test_broken_memoryview", (PyCFunction)test_broken_memoryview,METH_NOARGS}, + {"test_long_api", (PyCFunction)test_long_api, METH_NOARGS}, + {"test_long_numbits", (PyCFunction)test_long_numbits, METH_NOARGS}, + {"test_k_code", (PyCFunction)test_k_code, METH_NOARGS}, + {"test_empty_argparse", (PyCFunction)test_empty_argparse,METH_NOARGS}, + {"test_bug_7414", (PyCFunction)test_bug_7414, METH_NOARGS}, + {"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, + PyDoc_STR("This is a pretty normal docstring.")}, + {"test_string_to_double", (PyCFunction)test_string_to_double, METH_NOARGS}, + {"test_unicode_compare_with_ascii", (PyCFunction)test_unicode_compare_with_ascii, METH_NOARGS}, + {"test_capsule", (PyCFunction)test_capsule, METH_NOARGS}, + {"getargs_tuple", getargs_tuple, METH_VARARGS}, + {"getargs_keywords", (PyCFunction)getargs_keywords, + METH_VARARGS|METH_KEYWORDS}, + {"getargs_b", getargs_b, METH_VARARGS}, + {"getargs_B", getargs_B, METH_VARARGS}, + {"getargs_H", getargs_H, METH_VARARGS}, + {"getargs_I", getargs_I, METH_VARARGS}, + {"getargs_k", getargs_k, METH_VARARGS}, + {"getargs_i", getargs_i, METH_VARARGS}, + {"getargs_l", getargs_l, METH_VARARGS}, + {"getargs_n", getargs_n, METH_VARARGS}, #ifdef HAVE_LONG_LONG - {"getargs_L", getargs_L, METH_VARARGS}, - {"getargs_K", getargs_K, METH_VARARGS}, - {"test_longlong_api", test_longlong_api, METH_NOARGS}, - {"test_L_code", (PyCFunction)test_L_code, METH_NOARGS}, - {"codec_incrementalencoder", - (PyCFunction)codec_incrementalencoder, METH_VARARGS}, - {"codec_incrementaldecoder", - (PyCFunction)codec_incrementaldecoder, METH_VARARGS}, + {"getargs_L", getargs_L, METH_VARARGS}, + {"getargs_K", getargs_K, METH_VARARGS}, + {"test_longlong_api", test_longlong_api, METH_NOARGS}, + {"test_L_code", (PyCFunction)test_L_code, METH_NOARGS}, + {"codec_incrementalencoder", + (PyCFunction)codec_incrementalencoder, METH_VARARGS}, + {"codec_incrementaldecoder", + (PyCFunction)codec_incrementaldecoder, METH_VARARGS}, #endif - {"test_s_code", (PyCFunction)test_s_code, METH_NOARGS}, - {"test_u_code", (PyCFunction)test_u_code, METH_NOARGS}, - {"test_Z_code", (PyCFunction)test_Z_code, METH_NOARGS}, - {"test_widechar", (PyCFunction)test_widechar, METH_NOARGS}, + {"test_s_code", (PyCFunction)test_s_code, METH_NOARGS}, + {"test_u_code", (PyCFunction)test_u_code, METH_NOARGS}, + {"test_Z_code", (PyCFunction)test_Z_code, METH_NOARGS}, + {"test_widechar", (PyCFunction)test_widechar, METH_NOARGS}, #ifdef WITH_THREAD - {"_test_thread_state", test_thread_state, METH_VARARGS}, - {"_pending_threadfunc", pending_threadfunc, METH_VARARGS}, + {"_test_thread_state", test_thread_state, METH_VARARGS}, + {"_pending_threadfunc", pending_threadfunc, METH_VARARGS}, #endif #ifdef HAVE_GETTIMEOFDAY - {"profile_int", profile_int, METH_NOARGS}, + {"profile_int", profile_int, METH_NOARGS}, #endif - {"traceback_print", traceback_print, METH_VARARGS}, - {"exception_print", exception_print, METH_VARARGS}, - {"argparsing", argparsing, METH_VARARGS}, - {NULL, NULL} /* sentinel */ + {"traceback_print", traceback_print, METH_VARARGS}, + {"exception_print", exception_print, METH_VARARGS}, + {"argparsing", argparsing, METH_VARARGS}, + {NULL, NULL} /* sentinel */ }; #define AddSym(d, n, f, v) {PyObject *o = f(v); PyDict_SetItemString(d, n, o); Py_DECREF(o);} typedef struct { - char bool_member; - char byte_member; - unsigned char ubyte_member; - short short_member; - unsigned short ushort_member; - int int_member; - unsigned int uint_member; - long long_member; - unsigned long ulong_member; - Py_ssize_t pyssizet_member; - float float_member; - double double_member; - char inplace_member[6]; + char bool_member; + char byte_member; + unsigned char ubyte_member; + short short_member; + unsigned short ushort_member; + int int_member; + unsigned int uint_member; + long long_member; + unsigned long ulong_member; + Py_ssize_t pyssizet_member; + float float_member; + double double_member; + char inplace_member[6]; #ifdef HAVE_LONG_LONG - PY_LONG_LONG longlong_member; - unsigned PY_LONG_LONG ulonglong_member; + PY_LONG_LONG longlong_member; + unsigned PY_LONG_LONG ulonglong_member; #endif } all_structmembers; typedef struct { PyObject_HEAD - all_structmembers structmembers; + all_structmembers structmembers; } test_structmembers; static struct PyMemberDef test_members[] = { - {"T_BOOL", T_BOOL, offsetof(test_structmembers, structmembers.bool_member), 0, NULL}, - {"T_BYTE", T_BYTE, offsetof(test_structmembers, structmembers.byte_member), 0, NULL}, - {"T_UBYTE", T_UBYTE, offsetof(test_structmembers, structmembers.ubyte_member), 0, NULL}, - {"T_SHORT", T_SHORT, offsetof(test_structmembers, structmembers.short_member), 0, NULL}, - {"T_USHORT", T_USHORT, offsetof(test_structmembers, structmembers.ushort_member), 0, NULL}, - {"T_INT", T_INT, offsetof(test_structmembers, structmembers.int_member), 0, NULL}, - {"T_UINT", T_UINT, offsetof(test_structmembers, structmembers.uint_member), 0, NULL}, - {"T_LONG", T_LONG, offsetof(test_structmembers, structmembers.long_member), 0, NULL}, - {"T_ULONG", T_ULONG, offsetof(test_structmembers, structmembers.ulong_member), 0, NULL}, - {"T_PYSSIZET", T_PYSSIZET, offsetof(test_structmembers, structmembers.pyssizet_member), 0, NULL}, - {"T_FLOAT", T_FLOAT, offsetof(test_structmembers, structmembers.float_member), 0, NULL}, - {"T_DOUBLE", T_DOUBLE, offsetof(test_structmembers, structmembers.double_member), 0, NULL}, - {"T_STRING_INPLACE", T_STRING_INPLACE, offsetof(test_structmembers, structmembers.inplace_member), 0, NULL}, + {"T_BOOL", T_BOOL, offsetof(test_structmembers, structmembers.bool_member), 0, NULL}, + {"T_BYTE", T_BYTE, offsetof(test_structmembers, structmembers.byte_member), 0, NULL}, + {"T_UBYTE", T_UBYTE, offsetof(test_structmembers, structmembers.ubyte_member), 0, NULL}, + {"T_SHORT", T_SHORT, offsetof(test_structmembers, structmembers.short_member), 0, NULL}, + {"T_USHORT", T_USHORT, offsetof(test_structmembers, structmembers.ushort_member), 0, NULL}, + {"T_INT", T_INT, offsetof(test_structmembers, structmembers.int_member), 0, NULL}, + {"T_UINT", T_UINT, offsetof(test_structmembers, structmembers.uint_member), 0, NULL}, + {"T_LONG", T_LONG, offsetof(test_structmembers, structmembers.long_member), 0, NULL}, + {"T_ULONG", T_ULONG, offsetof(test_structmembers, structmembers.ulong_member), 0, NULL}, + {"T_PYSSIZET", T_PYSSIZET, offsetof(test_structmembers, structmembers.pyssizet_member), 0, NULL}, + {"T_FLOAT", T_FLOAT, offsetof(test_structmembers, structmembers.float_member), 0, NULL}, + {"T_DOUBLE", T_DOUBLE, offsetof(test_structmembers, structmembers.double_member), 0, NULL}, + {"T_STRING_INPLACE", T_STRING_INPLACE, offsetof(test_structmembers, structmembers.inplace_member), 0, NULL}, #ifdef HAVE_LONG_LONG - {"T_LONGLONG", T_LONGLONG, offsetof(test_structmembers, structmembers.longlong_member), 0, NULL}, - {"T_ULONGLONG", T_ULONGLONG, offsetof(test_structmembers, structmembers.ulonglong_member), 0, NULL}, + {"T_LONGLONG", T_LONGLONG, offsetof(test_structmembers, structmembers.longlong_member), 0, NULL}, + {"T_ULONGLONG", T_ULONGLONG, offsetof(test_structmembers, structmembers.ulonglong_member), 0, NULL}, #endif - {NULL} + {NULL} }; static PyObject * test_structmembers_new(PyTypeObject *type, PyObject *args, PyObject *kwargs) { - static char *keywords[] = { - "T_BOOL", "T_BYTE", "T_UBYTE", "T_SHORT", "T_USHORT", - "T_INT", "T_UINT", "T_LONG", "T_ULONG", "T_PYSSIZET", - "T_FLOAT", "T_DOUBLE", "T_STRING_INPLACE", + static char *keywords[] = { + "T_BOOL", "T_BYTE", "T_UBYTE", "T_SHORT", "T_USHORT", + "T_INT", "T_UINT", "T_LONG", "T_ULONG", "T_PYSSIZET", + "T_FLOAT", "T_DOUBLE", "T_STRING_INPLACE", #ifdef HAVE_LONG_LONG - "T_LONGLONG", "T_ULONGLONG", + "T_LONGLONG", "T_ULONGLONG", #endif - NULL}; - static char *fmt = "|bbBhHiIlknfds#" + NULL}; + static char *fmt = "|bbBhHiIlknfds#" #ifdef HAVE_LONG_LONG - "LK" + "LK" #endif - ; - test_structmembers *ob; - const char *s = NULL; - Py_ssize_t string_len = 0; - ob = PyObject_New(test_structmembers, type); - if (ob == NULL) - return NULL; - memset(&ob->structmembers, 0, sizeof(all_structmembers)); - if (!PyArg_ParseTupleAndKeywords(args, kwargs, fmt, keywords, - &ob->structmembers.bool_member, - &ob->structmembers.byte_member, - &ob->structmembers.ubyte_member, - &ob->structmembers.short_member, - &ob->structmembers.ushort_member, - &ob->structmembers.int_member, - &ob->structmembers.uint_member, - &ob->structmembers.long_member, - &ob->structmembers.ulong_member, - &ob->structmembers.pyssizet_member, - &ob->structmembers.float_member, - &ob->structmembers.double_member, - &s, &string_len + ; + test_structmembers *ob; + const char *s = NULL; + Py_ssize_t string_len = 0; + ob = PyObject_New(test_structmembers, type); + if (ob == NULL) + return NULL; + memset(&ob->structmembers, 0, sizeof(all_structmembers)); + if (!PyArg_ParseTupleAndKeywords(args, kwargs, fmt, keywords, + &ob->structmembers.bool_member, + &ob->structmembers.byte_member, + &ob->structmembers.ubyte_member, + &ob->structmembers.short_member, + &ob->structmembers.ushort_member, + &ob->structmembers.int_member, + &ob->structmembers.uint_member, + &ob->structmembers.long_member, + &ob->structmembers.ulong_member, + &ob->structmembers.pyssizet_member, + &ob->structmembers.float_member, + &ob->structmembers.double_member, + &s, &string_len #ifdef HAVE_LONG_LONG - , &ob->structmembers.longlong_member, - &ob->structmembers.ulonglong_member + , &ob->structmembers.longlong_member, + &ob->structmembers.ulonglong_member #endif - )) { - Py_DECREF(ob); - return NULL; - } - if (s != NULL) { - if (string_len > 5) { - Py_DECREF(ob); - PyErr_SetString(PyExc_ValueError, "string too long"); - return NULL; - } - strcpy(ob->structmembers.inplace_member, s); - } - else { - strcpy(ob->structmembers.inplace_member, ""); - } - return (PyObject *)ob; + )) { + Py_DECREF(ob); + return NULL; + } + if (s != NULL) { + if (string_len > 5) { + Py_DECREF(ob); + PyErr_SetString(PyExc_ValueError, "string too long"); + return NULL; + } + strcpy(ob->structmembers.inplace_member, s); + } + else { + strcpy(ob->structmembers.inplace_member, ""); + } + return (PyObject *)ob; } static void test_structmembers_free(PyObject *ob) { - PyObject_FREE(ob); + PyObject_FREE(ob); } static PyTypeObject test_structmembersType = { PyVarObject_HEAD_INIT(NULL, 0) - "test_structmembersType", - sizeof(test_structmembers), /* tp_basicsize */ - 0, /* tp_itemsize */ - test_structmembers_free, /* destructor 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 */ - PyObject_GenericSetAttr, /* tp_setattro */ - 0, /* tp_as_buffer */ - 0, /* tp_flags */ - "Type containing all structmember types", - 0, /* traverseproc tp_traverse */ - 0, /* tp_clear */ - 0, /* tp_richcompare */ - 0, /* tp_weaklistoffset */ - 0, /* tp_iter */ - 0, /* tp_iternext */ - 0, /* tp_methods */ - test_members, /* tp_members */ - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - test_structmembers_new, /* tp_new */ + "test_structmembersType", + sizeof(test_structmembers), /* tp_basicsize */ + 0, /* tp_itemsize */ + test_structmembers_free, /* destructor 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 */ + PyObject_GenericSetAttr, /* tp_setattro */ + 0, /* tp_as_buffer */ + 0, /* tp_flags */ + "Type containing all structmember types", + 0, /* traverseproc tp_traverse */ + 0, /* tp_clear */ + 0, /* tp_richcompare */ + 0, /* tp_weaklistoffset */ + 0, /* tp_iter */ + 0, /* tp_iternext */ + 0, /* tp_methods */ + test_members, /* tp_members */ + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + test_structmembers_new, /* tp_new */ }; static struct PyModuleDef _testcapimodule = { - PyModuleDef_HEAD_INIT, - "_testcapi", - NULL, - -1, - TestMethods, - NULL, - NULL, - NULL, - NULL + PyModuleDef_HEAD_INIT, + "_testcapi", + NULL, + -1, + TestMethods, + NULL, + NULL, + NULL, + NULL }; PyMODINIT_FUNC PyInit__testcapi(void) { - PyObject *m; + PyObject *m; + + m = PyModule_Create(&_testcapimodule); + if (m == NULL) + return NULL; + + Py_TYPE(&_HashInheritanceTester_Type)=&PyType_Type; + Py_TYPE(&_MemoryViewTester_Type)=&PyType_Type; - m = PyModule_Create(&_testcapimodule); - if (m == NULL) - return NULL; - - Py_TYPE(&_HashInheritanceTester_Type)=&PyType_Type; - Py_TYPE(&_MemoryViewTester_Type)=&PyType_Type; - - Py_TYPE(&test_structmembersType)=&PyType_Type; - Py_INCREF(&test_structmembersType); - /* don't use a name starting with "test", since we don't want - test_capi to automatically call this */ - PyModule_AddObject(m, "_test_structmembersType", (PyObject *)&test_structmembersType); - - PyModule_AddObject(m, "CHAR_MAX", PyLong_FromLong(CHAR_MAX)); - PyModule_AddObject(m, "CHAR_MIN", PyLong_FromLong(CHAR_MIN)); - PyModule_AddObject(m, "UCHAR_MAX", PyLong_FromLong(UCHAR_MAX)); - PyModule_AddObject(m, "SHRT_MAX", PyLong_FromLong(SHRT_MAX)); - PyModule_AddObject(m, "SHRT_MIN", PyLong_FromLong(SHRT_MIN)); - PyModule_AddObject(m, "USHRT_MAX", PyLong_FromLong(USHRT_MAX)); - PyModule_AddObject(m, "INT_MAX", PyLong_FromLong(INT_MAX)); - PyModule_AddObject(m, "INT_MIN", PyLong_FromLong(INT_MIN)); - PyModule_AddObject(m, "UINT_MAX", PyLong_FromUnsignedLong(UINT_MAX)); - PyModule_AddObject(m, "LONG_MAX", PyLong_FromLong(LONG_MAX)); - PyModule_AddObject(m, "LONG_MIN", PyLong_FromLong(LONG_MIN)); - PyModule_AddObject(m, "ULONG_MAX", PyLong_FromUnsignedLong(ULONG_MAX)); - PyModule_AddObject(m, "FLT_MAX", PyFloat_FromDouble(FLT_MAX)); - PyModule_AddObject(m, "FLT_MIN", PyFloat_FromDouble(FLT_MIN)); - PyModule_AddObject(m, "DBL_MAX", PyFloat_FromDouble(DBL_MAX)); - PyModule_AddObject(m, "DBL_MIN", PyFloat_FromDouble(DBL_MIN)); - PyModule_AddObject(m, "LLONG_MAX", PyLong_FromLongLong(PY_LLONG_MAX)); - PyModule_AddObject(m, "LLONG_MIN", PyLong_FromLongLong(PY_LLONG_MIN)); - PyModule_AddObject(m, "ULLONG_MAX", PyLong_FromUnsignedLongLong(PY_ULLONG_MAX)); - PyModule_AddObject(m, "PY_SSIZE_T_MAX", PyLong_FromSsize_t(PY_SSIZE_T_MAX)); - PyModule_AddObject(m, "PY_SSIZE_T_MIN", PyLong_FromSsize_t(PY_SSIZE_T_MIN)); - PyModule_AddObject(m, "SIZEOF_PYGC_HEAD", PyLong_FromSsize_t(sizeof(PyGC_Head))); - Py_INCREF(&PyInstanceMethod_Type); - PyModule_AddObject(m, "instancemethod", (PyObject *)&PyInstanceMethod_Type); - - TestError = PyErr_NewException("_testcapi.error", NULL, NULL); - Py_INCREF(TestError); - PyModule_AddObject(m, "error", TestError); - return m; + Py_TYPE(&test_structmembersType)=&PyType_Type; + Py_INCREF(&test_structmembersType); + /* don't use a name starting with "test", since we don't want + test_capi to automatically call this */ + PyModule_AddObject(m, "_test_structmembersType", (PyObject *)&test_structmembersType); + + PyModule_AddObject(m, "CHAR_MAX", PyLong_FromLong(CHAR_MAX)); + PyModule_AddObject(m, "CHAR_MIN", PyLong_FromLong(CHAR_MIN)); + PyModule_AddObject(m, "UCHAR_MAX", PyLong_FromLong(UCHAR_MAX)); + PyModule_AddObject(m, "SHRT_MAX", PyLong_FromLong(SHRT_MAX)); + PyModule_AddObject(m, "SHRT_MIN", PyLong_FromLong(SHRT_MIN)); + PyModule_AddObject(m, "USHRT_MAX", PyLong_FromLong(USHRT_MAX)); + PyModule_AddObject(m, "INT_MAX", PyLong_FromLong(INT_MAX)); + PyModule_AddObject(m, "INT_MIN", PyLong_FromLong(INT_MIN)); + PyModule_AddObject(m, "UINT_MAX", PyLong_FromUnsignedLong(UINT_MAX)); + PyModule_AddObject(m, "LONG_MAX", PyLong_FromLong(LONG_MAX)); + PyModule_AddObject(m, "LONG_MIN", PyLong_FromLong(LONG_MIN)); + PyModule_AddObject(m, "ULONG_MAX", PyLong_FromUnsignedLong(ULONG_MAX)); + PyModule_AddObject(m, "FLT_MAX", PyFloat_FromDouble(FLT_MAX)); + PyModule_AddObject(m, "FLT_MIN", PyFloat_FromDouble(FLT_MIN)); + PyModule_AddObject(m, "DBL_MAX", PyFloat_FromDouble(DBL_MAX)); + PyModule_AddObject(m, "DBL_MIN", PyFloat_FromDouble(DBL_MIN)); + PyModule_AddObject(m, "LLONG_MAX", PyLong_FromLongLong(PY_LLONG_MAX)); + PyModule_AddObject(m, "LLONG_MIN", PyLong_FromLongLong(PY_LLONG_MIN)); + PyModule_AddObject(m, "ULLONG_MAX", PyLong_FromUnsignedLongLong(PY_ULLONG_MAX)); + PyModule_AddObject(m, "PY_SSIZE_T_MAX", PyLong_FromSsize_t(PY_SSIZE_T_MAX)); + PyModule_AddObject(m, "PY_SSIZE_T_MIN", PyLong_FromSsize_t(PY_SSIZE_T_MIN)); + PyModule_AddObject(m, "SIZEOF_PYGC_HEAD", PyLong_FromSsize_t(sizeof(PyGC_Head))); + Py_INCREF(&PyInstanceMethod_Type); + PyModule_AddObject(m, "instancemethod", (PyObject *)&PyInstanceMethod_Type); + + TestError = PyErr_NewException("_testcapi.error", NULL, NULL); + Py_INCREF(TestError); + PyModule_AddObject(m, "error", TestError); + return m; } Modified: python/branches/release31-maint/Modules/_threadmodule.c ============================================================================== --- python/branches/release31-maint/Modules/_threadmodule.c (original) +++ python/branches/release31-maint/Modules/_threadmodule.c Sun May 9 18:14:21 2010 @@ -18,36 +18,36 @@ /* Lock objects */ typedef struct { - PyObject_HEAD - PyThread_type_lock lock_lock; + PyObject_HEAD + PyThread_type_lock lock_lock; } lockobject; static void lock_dealloc(lockobject *self) { - if (self->lock_lock != NULL) { - /* Unlock the lock so it's safe to free it */ - PyThread_acquire_lock(self->lock_lock, 0); - PyThread_release_lock(self->lock_lock); - - PyThread_free_lock(self->lock_lock); - } - PyObject_Del(self); + if (self->lock_lock != NULL) { + /* Unlock the lock so it's safe to free it */ + PyThread_acquire_lock(self->lock_lock, 0); + PyThread_release_lock(self->lock_lock); + + PyThread_free_lock(self->lock_lock); + } + PyObject_Del(self); } static PyObject * lock_PyThread_acquire_lock(lockobject *self, PyObject *args) { - int i = 1; + int i = 1; - if (!PyArg_ParseTuple(args, "|i:acquire", &i)) - return NULL; + if (!PyArg_ParseTuple(args, "|i:acquire", &i)) + return NULL; - Py_BEGIN_ALLOW_THREADS - i = PyThread_acquire_lock(self->lock_lock, i); - Py_END_ALLOW_THREADS + Py_BEGIN_ALLOW_THREADS + i = PyThread_acquire_lock(self->lock_lock, i); + Py_END_ALLOW_THREADS - return PyBool_FromLong((long)i); + return PyBool_FromLong((long)i); } PyDoc_STRVAR(acquire_doc, @@ -64,16 +64,16 @@ static PyObject * lock_PyThread_release_lock(lockobject *self) { - /* Sanity check: the lock must be locked */ - if (PyThread_acquire_lock(self->lock_lock, 0)) { - PyThread_release_lock(self->lock_lock); - PyErr_SetString(ThreadError, "release unlocked lock"); - return NULL; - } - - PyThread_release_lock(self->lock_lock); - Py_INCREF(Py_None); - return Py_None; + /* Sanity check: the lock must be locked */ + if (PyThread_acquire_lock(self->lock_lock, 0)) { + PyThread_release_lock(self->lock_lock); + PyErr_SetString(ThreadError, "release unlocked lock"); + return NULL; + } + + PyThread_release_lock(self->lock_lock); + Py_INCREF(Py_None); + return Py_None; } PyDoc_STRVAR(release_doc, @@ -87,11 +87,11 @@ static PyObject * lock_locked_lock(lockobject *self) { - if (PyThread_acquire_lock(self->lock_lock, 0)) { - PyThread_release_lock(self->lock_lock); - return PyBool_FromLong(0L); - } - return PyBool_FromLong(1L); + if (PyThread_acquire_lock(self->lock_lock, 0)) { + PyThread_release_lock(self->lock_lock); + return PyBool_FromLong(0L); + } + return PyBool_FromLong(1L); } PyDoc_STRVAR(locked_doc, @@ -101,71 +101,71 @@ Return whether the lock is in the locked state."); static PyMethodDef lock_methods[] = { - {"acquire_lock", (PyCFunction)lock_PyThread_acquire_lock, - METH_VARARGS, acquire_doc}, - {"acquire", (PyCFunction)lock_PyThread_acquire_lock, - METH_VARARGS, acquire_doc}, - {"release_lock", (PyCFunction)lock_PyThread_release_lock, - METH_NOARGS, release_doc}, - {"release", (PyCFunction)lock_PyThread_release_lock, - METH_NOARGS, release_doc}, - {"locked_lock", (PyCFunction)lock_locked_lock, - METH_NOARGS, locked_doc}, - {"locked", (PyCFunction)lock_locked_lock, - METH_NOARGS, locked_doc}, - {"__enter__", (PyCFunction)lock_PyThread_acquire_lock, - METH_VARARGS, acquire_doc}, - {"__exit__", (PyCFunction)lock_PyThread_release_lock, - METH_VARARGS, release_doc}, - {NULL, NULL} /* sentinel */ + {"acquire_lock", (PyCFunction)lock_PyThread_acquire_lock, + METH_VARARGS, acquire_doc}, + {"acquire", (PyCFunction)lock_PyThread_acquire_lock, + METH_VARARGS, acquire_doc}, + {"release_lock", (PyCFunction)lock_PyThread_release_lock, + METH_NOARGS, release_doc}, + {"release", (PyCFunction)lock_PyThread_release_lock, + METH_NOARGS, release_doc}, + {"locked_lock", (PyCFunction)lock_locked_lock, + METH_NOARGS, locked_doc}, + {"locked", (PyCFunction)lock_locked_lock, + METH_NOARGS, locked_doc}, + {"__enter__", (PyCFunction)lock_PyThread_acquire_lock, + METH_VARARGS, acquire_doc}, + {"__exit__", (PyCFunction)lock_PyThread_release_lock, + METH_VARARGS, release_doc}, + {NULL, NULL} /* sentinel */ }; static PyTypeObject Locktype = { - PyVarObject_HEAD_INIT(&PyType_Type, 0) - "_thread.lock", /*tp_name*/ - sizeof(lockobject), /*tp_size*/ - 0, /*tp_itemsize*/ - /* methods */ - (destructor)lock_dealloc, /*tp_dealloc*/ - 0, /*tp_print*/ - 0, /*tp_getattr*/ - 0, /*tp_setattr*/ - 0, /*tp_reserved*/ - 0, /*tp_repr*/ - 0, /*tp_as_number*/ - 0, /*tp_as_sequence*/ - 0, /*tp_as_mapping*/ - 0, /*tp_hash*/ - 0, /*tp_call*/ - 0, /*tp_str*/ - 0, /*tp_getattro*/ - 0, /*tp_setattro*/ - 0, /*tp_as_buffer*/ - Py_TPFLAGS_DEFAULT, /*tp_flags*/ - 0, /*tp_doc*/ - 0, /*tp_traverse*/ - 0, /*tp_clear*/ - 0, /*tp_richcompare*/ - 0, /*tp_weaklistoffset*/ - 0, /*tp_iter*/ - 0, /*tp_iternext*/ - lock_methods, /*tp_methods*/ + PyVarObject_HEAD_INIT(&PyType_Type, 0) + "_thread.lock", /*tp_name*/ + sizeof(lockobject), /*tp_size*/ + 0, /*tp_itemsize*/ + /* methods */ + (destructor)lock_dealloc, /*tp_dealloc*/ + 0, /*tp_print*/ + 0, /*tp_getattr*/ + 0, /*tp_setattr*/ + 0, /*tp_reserved*/ + 0, /*tp_repr*/ + 0, /*tp_as_number*/ + 0, /*tp_as_sequence*/ + 0, /*tp_as_mapping*/ + 0, /*tp_hash*/ + 0, /*tp_call*/ + 0, /*tp_str*/ + 0, /*tp_getattro*/ + 0, /*tp_setattro*/ + 0, /*tp_as_buffer*/ + Py_TPFLAGS_DEFAULT, /*tp_flags*/ + 0, /*tp_doc*/ + 0, /*tp_traverse*/ + 0, /*tp_clear*/ + 0, /*tp_richcompare*/ + 0, /*tp_weaklistoffset*/ + 0, /*tp_iter*/ + 0, /*tp_iternext*/ + lock_methods, /*tp_methods*/ }; static lockobject * newlockobject(void) { - lockobject *self; - self = PyObject_New(lockobject, &Locktype); - if (self == NULL) - return NULL; - self->lock_lock = PyThread_allocate_lock(); - if (self->lock_lock == NULL) { - Py_DECREF(self); - PyErr_SetString(ThreadError, "can't allocate lock"); - return NULL; - } - return self; + lockobject *self; + self = PyObject_New(lockobject, &Locktype); + if (self == NULL) + return NULL; + self->lock_lock = PyThread_allocate_lock(); + if (self->lock_lock == NULL) { + Py_DECREF(self); + PyErr_SetString(ThreadError, "can't allocate lock"); + return NULL; + } + return self; } /* Thread-local objects */ @@ -173,351 +173,351 @@ #include "structmember.h" typedef struct { - PyObject_HEAD - PyObject *key; - PyObject *args; - PyObject *kw; - PyObject *dict; + PyObject_HEAD + PyObject *key; + PyObject *args; + PyObject *kw; + PyObject *dict; } localobject; static PyObject * local_new(PyTypeObject *type, PyObject *args, PyObject *kw) { - localobject *self; - PyObject *tdict; + localobject *self; + PyObject *tdict; - if (type->tp_init == PyBaseObject_Type.tp_init - && ((args && PyObject_IsTrue(args)) - || (kw && PyObject_IsTrue(kw)))) { - PyErr_SetString(PyExc_TypeError, - "Initialization arguments are not supported"); - return NULL; - } - - self = (localobject *)type->tp_alloc(type, 0); - if (self == NULL) - return NULL; - - Py_XINCREF(args); - self->args = args; - Py_XINCREF(kw); - self->kw = kw; - self->dict = NULL; /* making sure */ - self->key = PyUnicode_FromFormat("thread.local.%p", self); - if (self->key == NULL) - goto err; - - self->dict = PyDict_New(); - if (self->dict == NULL) - goto err; - - tdict = PyThreadState_GetDict(); - if (tdict == NULL) { - PyErr_SetString(PyExc_SystemError, - "Couldn't get thread-state dictionary"); - goto err; - } + if (type->tp_init == PyBaseObject_Type.tp_init + && ((args && PyObject_IsTrue(args)) + || (kw && PyObject_IsTrue(kw)))) { + PyErr_SetString(PyExc_TypeError, + "Initialization arguments are not supported"); + return NULL; + } + + self = (localobject *)type->tp_alloc(type, 0); + if (self == NULL) + return NULL; + + Py_XINCREF(args); + self->args = args; + Py_XINCREF(kw); + self->kw = kw; + self->dict = NULL; /* making sure */ + self->key = PyUnicode_FromFormat("thread.local.%p", self); + if (self->key == NULL) + goto err; + + self->dict = PyDict_New(); + if (self->dict == NULL) + goto err; + + tdict = PyThreadState_GetDict(); + if (tdict == NULL) { + PyErr_SetString(PyExc_SystemError, + "Couldn't get thread-state dictionary"); + goto err; + } - if (PyDict_SetItem(tdict, self->key, self->dict) < 0) - goto err; + if (PyDict_SetItem(tdict, self->key, self->dict) < 0) + goto err; - return (PyObject *)self; + return (PyObject *)self; err: - Py_DECREF(self); - return NULL; + Py_DECREF(self); + return NULL; } static int local_traverse(localobject *self, visitproc visit, void *arg) { - Py_VISIT(self->args); - Py_VISIT(self->kw); - Py_VISIT(self->dict); - return 0; + Py_VISIT(self->args); + Py_VISIT(self->kw); + Py_VISIT(self->dict); + return 0; } static int local_clear(localobject *self) { - Py_CLEAR(self->args); - Py_CLEAR(self->kw); - Py_CLEAR(self->dict); - return 0; + Py_CLEAR(self->args); + Py_CLEAR(self->kw); + Py_CLEAR(self->dict); + return 0; } static void local_dealloc(localobject *self) { - PyThreadState *tstate; - if (self->key - && (tstate = PyThreadState_Get()) - && tstate->interp) { - for(tstate = PyInterpreterState_ThreadHead(tstate->interp); - tstate; - tstate = PyThreadState_Next(tstate)) - if (tstate->dict && - PyDict_GetItem(tstate->dict, self->key)) - PyDict_DelItem(tstate->dict, self->key); - } - - Py_XDECREF(self->key); - local_clear(self); - Py_TYPE(self)->tp_free((PyObject*)self); + PyThreadState *tstate; + if (self->key + && (tstate = PyThreadState_Get()) + && tstate->interp) { + for(tstate = PyInterpreterState_ThreadHead(tstate->interp); + tstate; + tstate = PyThreadState_Next(tstate)) + if (tstate->dict && + PyDict_GetItem(tstate->dict, self->key)) + PyDict_DelItem(tstate->dict, self->key); + } + + Py_XDECREF(self->key); + local_clear(self); + Py_TYPE(self)->tp_free((PyObject*)self); } static PyObject * _ldict(localobject *self) { - PyObject *tdict, *ldict; + PyObject *tdict, *ldict; - tdict = PyThreadState_GetDict(); - if (tdict == NULL) { - PyErr_SetString(PyExc_SystemError, - "Couldn't get thread-state dictionary"); - return NULL; - } - - ldict = PyDict_GetItem(tdict, self->key); - if (ldict == NULL) { - ldict = PyDict_New(); /* we own ldict */ - - if (ldict == NULL) - return NULL; - else { - int i = PyDict_SetItem(tdict, self->key, ldict); - Py_DECREF(ldict); /* now ldict is borrowed */ - if (i < 0) - return NULL; - } - - Py_CLEAR(self->dict); - Py_INCREF(ldict); - self->dict = ldict; /* still borrowed */ - - if (Py_TYPE(self)->tp_init != PyBaseObject_Type.tp_init && - Py_TYPE(self)->tp_init((PyObject*)self, - self->args, self->kw) < 0) { - /* we need to get rid of ldict from thread so - we create a new one the next time we do an attr - acces */ - PyDict_DelItem(tdict, self->key); - return NULL; - } - - } - - /* The call to tp_init above may have caused another thread to run. - Install our ldict again. */ - if (self->dict != ldict) { - Py_CLEAR(self->dict); - Py_INCREF(ldict); - self->dict = ldict; - } + tdict = PyThreadState_GetDict(); + if (tdict == NULL) { + PyErr_SetString(PyExc_SystemError, + "Couldn't get thread-state dictionary"); + return NULL; + } + + ldict = PyDict_GetItem(tdict, self->key); + if (ldict == NULL) { + ldict = PyDict_New(); /* we own ldict */ + + if (ldict == NULL) + return NULL; + else { + int i = PyDict_SetItem(tdict, self->key, ldict); + Py_DECREF(ldict); /* now ldict is borrowed */ + if (i < 0) + return NULL; + } + + Py_CLEAR(self->dict); + Py_INCREF(ldict); + self->dict = ldict; /* still borrowed */ + + if (Py_TYPE(self)->tp_init != PyBaseObject_Type.tp_init && + Py_TYPE(self)->tp_init((PyObject*)self, + self->args, self->kw) < 0) { + /* we need to get rid of ldict from thread so + we create a new one the next time we do an attr + acces */ + PyDict_DelItem(tdict, self->key); + return NULL; + } + + } + + /* The call to tp_init above may have caused another thread to run. + Install our ldict again. */ + if (self->dict != ldict) { + Py_CLEAR(self->dict); + Py_INCREF(ldict); + self->dict = ldict; + } - return ldict; + return ldict; } static int local_setattro(localobject *self, PyObject *name, PyObject *v) { - PyObject *ldict; - - ldict = _ldict(self); - if (ldict == NULL) - return -1; + PyObject *ldict; - return PyObject_GenericSetAttr((PyObject *)self, name, v); + ldict = _ldict(self); + if (ldict == NULL) + return -1; + + return PyObject_GenericSetAttr((PyObject *)self, name, v); } static PyObject * local_getdict(localobject *self, void *closure) { - if (self->dict == NULL) { - PyErr_SetString(PyExc_AttributeError, "__dict__"); - return NULL; - } + if (self->dict == NULL) { + PyErr_SetString(PyExc_AttributeError, "__dict__"); + return NULL; + } - Py_INCREF(self->dict); - return self->dict; + Py_INCREF(self->dict); + return self->dict; } static PyGetSetDef local_getset[] = { - {"__dict__", (getter)local_getdict, (setter)NULL, - "Local-data dictionary", NULL}, - {NULL} /* Sentinel */ + {"__dict__", (getter)local_getdict, (setter)NULL, + "Local-data dictionary", NULL}, + {NULL} /* Sentinel */ }; static PyObject *local_getattro(localobject *, PyObject *); static PyTypeObject localtype = { - PyVarObject_HEAD_INIT(NULL, 0) - /* tp_name */ "_thread._local", - /* tp_basicsize */ sizeof(localobject), - /* tp_itemsize */ 0, - /* tp_dealloc */ (destructor)local_dealloc, - /* tp_print */ 0, - /* tp_getattr */ 0, - /* tp_setattr */ 0, - /* tp_reserved */ 0, - /* tp_repr */ 0, - /* tp_as_number */ 0, - /* tp_as_sequence */ 0, - /* tp_as_mapping */ 0, - /* tp_hash */ 0, - /* tp_call */ 0, - /* tp_str */ 0, - /* tp_getattro */ (getattrofunc)local_getattro, - /* tp_setattro */ (setattrofunc)local_setattro, - /* tp_as_buffer */ 0, - /* tp_flags */ Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, - /* tp_doc */ "Thread-local data", - /* tp_traverse */ (traverseproc)local_traverse, - /* tp_clear */ (inquiry)local_clear, - /* tp_richcompare */ 0, - /* tp_weaklistoffset */ 0, - /* tp_iter */ 0, - /* tp_iternext */ 0, - /* tp_methods */ 0, - /* tp_members */ 0, - /* tp_getset */ local_getset, - /* tp_base */ 0, - /* tp_dict */ 0, /* internal use */ - /* tp_descr_get */ 0, - /* tp_descr_set */ 0, - /* tp_dictoffset */ offsetof(localobject, dict), - /* tp_init */ 0, - /* tp_alloc */ 0, - /* tp_new */ local_new, - /* tp_free */ 0, /* Low-level free-mem routine */ - /* tp_is_gc */ 0, /* For PyObject_IS_GC */ + PyVarObject_HEAD_INIT(NULL, 0) + /* tp_name */ "_thread._local", + /* tp_basicsize */ sizeof(localobject), + /* tp_itemsize */ 0, + /* tp_dealloc */ (destructor)local_dealloc, + /* tp_print */ 0, + /* tp_getattr */ 0, + /* tp_setattr */ 0, + /* tp_reserved */ 0, + /* tp_repr */ 0, + /* tp_as_number */ 0, + /* tp_as_sequence */ 0, + /* tp_as_mapping */ 0, + /* tp_hash */ 0, + /* tp_call */ 0, + /* tp_str */ 0, + /* tp_getattro */ (getattrofunc)local_getattro, + /* tp_setattro */ (setattrofunc)local_setattro, + /* tp_as_buffer */ 0, + /* tp_flags */ Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, + /* tp_doc */ "Thread-local data", + /* tp_traverse */ (traverseproc)local_traverse, + /* tp_clear */ (inquiry)local_clear, + /* tp_richcompare */ 0, + /* tp_weaklistoffset */ 0, + /* tp_iter */ 0, + /* tp_iternext */ 0, + /* tp_methods */ 0, + /* tp_members */ 0, + /* tp_getset */ local_getset, + /* tp_base */ 0, + /* tp_dict */ 0, /* internal use */ + /* tp_descr_get */ 0, + /* tp_descr_set */ 0, + /* tp_dictoffset */ offsetof(localobject, dict), + /* tp_init */ 0, + /* tp_alloc */ 0, + /* tp_new */ local_new, + /* tp_free */ 0, /* Low-level free-mem routine */ + /* tp_is_gc */ 0, /* For PyObject_IS_GC */ }; static PyObject * local_getattro(localobject *self, PyObject *name) { - PyObject *ldict, *value; + PyObject *ldict, *value; - ldict = _ldict(self); - if (ldict == NULL) - return NULL; - - if (Py_TYPE(self) != &localtype) - /* use generic lookup for subtypes */ - return PyObject_GenericGetAttr((PyObject *)self, name); - - /* Optimization: just look in dict ourselves */ - value = PyDict_GetItem(ldict, name); - if (value == NULL) - /* Fall back on generic to get __class__ and __dict__ */ - return PyObject_GenericGetAttr((PyObject *)self, name); + ldict = _ldict(self); + if (ldict == NULL) + return NULL; + + if (Py_TYPE(self) != &localtype) + /* use generic lookup for subtypes */ + return PyObject_GenericGetAttr((PyObject *)self, name); + + /* Optimization: just look in dict ourselves */ + value = PyDict_GetItem(ldict, name); + if (value == NULL) + /* Fall back on generic to get __class__ and __dict__ */ + return PyObject_GenericGetAttr((PyObject *)self, name); - Py_INCREF(value); - return value; + Py_INCREF(value); + return value; } /* Module functions */ struct bootstate { - PyInterpreterState *interp; - PyObject *func; - PyObject *args; - PyObject *keyw; - PyThreadState *tstate; + PyInterpreterState *interp; + PyObject *func; + PyObject *args; + PyObject *keyw; + PyThreadState *tstate; }; static void t_bootstrap(void *boot_raw) { - struct bootstate *boot = (struct bootstate *) boot_raw; - PyThreadState *tstate; - PyObject *res; - - tstate = boot->tstate; - tstate->thread_id = PyThread_get_thread_ident(); - _PyThreadState_Init(tstate); - PyEval_AcquireThread(tstate); - res = PyEval_CallObjectWithKeywords( - boot->func, boot->args, boot->keyw); - if (res == NULL) { - if (PyErr_ExceptionMatches(PyExc_SystemExit)) - PyErr_Clear(); - else { - PyObject *file; - PySys_WriteStderr( - "Unhandled exception in thread started by "); - file = PySys_GetObject("stderr"); - if (file != NULL && file != Py_None) - PyFile_WriteObject(boot->func, file, 0); - else - PyObject_Print(boot->func, stderr, 0); - PySys_WriteStderr("\n"); - PyErr_PrintEx(0); - } - } - else - Py_DECREF(res); - Py_DECREF(boot->func); - Py_DECREF(boot->args); - Py_XDECREF(boot->keyw); - PyMem_DEL(boot_raw); - PyThreadState_Clear(tstate); - PyThreadState_DeleteCurrent(); - PyThread_exit_thread(); + struct bootstate *boot = (struct bootstate *) boot_raw; + PyThreadState *tstate; + PyObject *res; + + tstate = boot->tstate; + tstate->thread_id = PyThread_get_thread_ident(); + _PyThreadState_Init(tstate); + PyEval_AcquireThread(tstate); + res = PyEval_CallObjectWithKeywords( + boot->func, boot->args, boot->keyw); + if (res == NULL) { + if (PyErr_ExceptionMatches(PyExc_SystemExit)) + PyErr_Clear(); + else { + PyObject *file; + PySys_WriteStderr( + "Unhandled exception in thread started by "); + file = PySys_GetObject("stderr"); + if (file != NULL && file != Py_None) + PyFile_WriteObject(boot->func, file, 0); + else + PyObject_Print(boot->func, stderr, 0); + PySys_WriteStderr("\n"); + PyErr_PrintEx(0); + } + } + else + Py_DECREF(res); + Py_DECREF(boot->func); + Py_DECREF(boot->args); + Py_XDECREF(boot->keyw); + PyMem_DEL(boot_raw); + PyThreadState_Clear(tstate); + PyThreadState_DeleteCurrent(); + PyThread_exit_thread(); } static PyObject * thread_PyThread_start_new_thread(PyObject *self, PyObject *fargs) { - PyObject *func, *args, *keyw = NULL; - struct bootstate *boot; - long ident; - - if (!PyArg_UnpackTuple(fargs, "start_new_thread", 2, 3, - &func, &args, &keyw)) - return NULL; - if (!PyCallable_Check(func)) { - PyErr_SetString(PyExc_TypeError, - "first arg must be callable"); - return NULL; - } - if (!PyTuple_Check(args)) { - PyErr_SetString(PyExc_TypeError, - "2nd arg must be a tuple"); - return NULL; - } - if (keyw != NULL && !PyDict_Check(keyw)) { - PyErr_SetString(PyExc_TypeError, - "optional 3rd arg must be a dictionary"); - return NULL; - } - boot = PyMem_NEW(struct bootstate, 1); - if (boot == NULL) - return PyErr_NoMemory(); - boot->interp = PyThreadState_GET()->interp; - boot->func = func; - boot->args = args; - boot->keyw = keyw; - boot->tstate = _PyThreadState_Prealloc(boot->interp); - if (boot->tstate == NULL) { - PyMem_DEL(boot); - return PyErr_NoMemory(); - } - Py_INCREF(func); - Py_INCREF(args); - Py_XINCREF(keyw); - PyEval_InitThreads(); /* Start the interpreter's thread-awareness */ - ident = PyThread_start_new_thread(t_bootstrap, (void*) boot); - if (ident == -1) { - PyErr_SetString(ThreadError, "can't start new thread"); - Py_DECREF(func); - Py_DECREF(args); - Py_XDECREF(keyw); - PyThreadState_Clear(boot->tstate); - PyMem_DEL(boot); - return NULL; - } - return PyLong_FromLong(ident); + PyObject *func, *args, *keyw = NULL; + struct bootstate *boot; + long ident; + + if (!PyArg_UnpackTuple(fargs, "start_new_thread", 2, 3, + &func, &args, &keyw)) + return NULL; + if (!PyCallable_Check(func)) { + PyErr_SetString(PyExc_TypeError, + "first arg must be callable"); + return NULL; + } + if (!PyTuple_Check(args)) { + PyErr_SetString(PyExc_TypeError, + "2nd arg must be a tuple"); + return NULL; + } + if (keyw != NULL && !PyDict_Check(keyw)) { + PyErr_SetString(PyExc_TypeError, + "optional 3rd arg must be a dictionary"); + return NULL; + } + boot = PyMem_NEW(struct bootstate, 1); + if (boot == NULL) + return PyErr_NoMemory(); + boot->interp = PyThreadState_GET()->interp; + boot->func = func; + boot->args = args; + boot->keyw = keyw; + boot->tstate = _PyThreadState_Prealloc(boot->interp); + if (boot->tstate == NULL) { + PyMem_DEL(boot); + return PyErr_NoMemory(); + } + Py_INCREF(func); + Py_INCREF(args); + Py_XINCREF(keyw); + PyEval_InitThreads(); /* Start the interpreter's thread-awareness */ + ident = PyThread_start_new_thread(t_bootstrap, (void*) boot); + if (ident == -1) { + PyErr_SetString(ThreadError, "can't start new thread"); + Py_DECREF(func); + Py_DECREF(args); + Py_XDECREF(keyw); + PyThreadState_Clear(boot->tstate); + PyMem_DEL(boot); + return NULL; + } + return PyLong_FromLong(ident); } PyDoc_STRVAR(start_new_doc, @@ -534,8 +534,8 @@ static PyObject * thread_PyThread_exit_thread(PyObject *self) { - PyErr_SetNone(PyExc_SystemExit); - return NULL; + PyErr_SetNone(PyExc_SystemExit); + return NULL; } PyDoc_STRVAR(exit_doc, @@ -548,9 +548,9 @@ static PyObject * thread_PyThread_interrupt_main(PyObject * self) { - PyErr_SetInterrupt(); - Py_INCREF(Py_None); - return Py_None; + PyErr_SetInterrupt(); + Py_INCREF(Py_None); + return Py_None; } PyDoc_STRVAR(interrupt_doc, @@ -564,11 +564,11 @@ static PyObject * thread_PyThread_exit_prog(PyObject *self, PyObject *args) { - int sts; - if (!PyArg_ParseTuple(args, "i:exit_prog", &sts)) - return NULL; - Py_Exit(sts); /* Calls PyThread_exit_prog(sts) or _PyThread_exit_prog(sts) */ - for (;;) { } /* Should not be reached */ + int sts; + if (!PyArg_ParseTuple(args, "i:exit_prog", &sts)) + return NULL; + Py_Exit(sts); /* Calls PyThread_exit_prog(sts) or _PyThread_exit_prog(sts) */ + for (;;) { } /* Should not be reached */ } #endif @@ -577,7 +577,7 @@ static PyObject * thread_PyThread_allocate_lock(PyObject *self) { - return (PyObject *) newlockobject(); + return (PyObject *) newlockobject(); } PyDoc_STRVAR(allocate_doc, @@ -589,13 +589,13 @@ static PyObject * thread_get_ident(PyObject *self) { - long ident; - ident = PyThread_get_thread_ident(); - if (ident == -1) { - PyErr_SetString(ThreadError, "no current thread ident"); - return NULL; - } - return PyLong_FromLong(ident); + long ident; + ident = PyThread_get_thread_ident(); + if (ident == -1) { + PyErr_SetString(ThreadError, "no current thread ident"); + return NULL; + } + return PyLong_FromLong(ident); } PyDoc_STRVAR(get_ident_doc, @@ -612,35 +612,35 @@ static PyObject * thread_stack_size(PyObject *self, PyObject *args) { - size_t old_size; - Py_ssize_t new_size = 0; - int rc; - - if (!PyArg_ParseTuple(args, "|n:stack_size", &new_size)) - return NULL; - - if (new_size < 0) { - PyErr_SetString(PyExc_ValueError, - "size must be 0 or a positive value"); - return NULL; - } - - old_size = PyThread_get_stacksize(); - - rc = PyThread_set_stacksize((size_t) new_size); - if (rc == -1) { - PyErr_Format(PyExc_ValueError, - "size not valid: %zd bytes", - new_size); - return NULL; - } - if (rc == -2) { - PyErr_SetString(ThreadError, - "setting stack size not supported"); - return NULL; - } + size_t old_size; + Py_ssize_t new_size = 0; + int rc; + + if (!PyArg_ParseTuple(args, "|n:stack_size", &new_size)) + return NULL; + + if (new_size < 0) { + PyErr_SetString(PyExc_ValueError, + "size must be 0 or a positive value"); + return NULL; + } + + old_size = PyThread_get_stacksize(); + + rc = PyThread_set_stacksize((size_t) new_size); + if (rc == -1) { + PyErr_Format(PyExc_ValueError, + "size not valid: %zd bytes", + new_size); + return NULL; + } + if (rc == -2) { + PyErr_SetString(ThreadError, + "setting stack size not supported"); + return NULL; + } - return PyLong_FromSsize_t((Py_ssize_t) old_size); + return PyLong_FromSsize_t((Py_ssize_t) old_size); } PyDoc_STRVAR(stack_size_doc, @@ -664,32 +664,32 @@ the suggested approach in the absence of more specific information)."); static PyMethodDef thread_methods[] = { - {"start_new_thread", (PyCFunction)thread_PyThread_start_new_thread, - METH_VARARGS, - start_new_doc}, - {"start_new", (PyCFunction)thread_PyThread_start_new_thread, - METH_VARARGS, - start_new_doc}, - {"allocate_lock", (PyCFunction)thread_PyThread_allocate_lock, - METH_NOARGS, allocate_doc}, - {"allocate", (PyCFunction)thread_PyThread_allocate_lock, - METH_NOARGS, allocate_doc}, - {"exit_thread", (PyCFunction)thread_PyThread_exit_thread, - METH_NOARGS, exit_doc}, - {"exit", (PyCFunction)thread_PyThread_exit_thread, - METH_NOARGS, exit_doc}, - {"interrupt_main", (PyCFunction)thread_PyThread_interrupt_main, - METH_NOARGS, interrupt_doc}, - {"get_ident", (PyCFunction)thread_get_ident, - METH_NOARGS, get_ident_doc}, - {"stack_size", (PyCFunction)thread_stack_size, - METH_VARARGS, - stack_size_doc}, + {"start_new_thread", (PyCFunction)thread_PyThread_start_new_thread, + METH_VARARGS, + start_new_doc}, + {"start_new", (PyCFunction)thread_PyThread_start_new_thread, + METH_VARARGS, + start_new_doc}, + {"allocate_lock", (PyCFunction)thread_PyThread_allocate_lock, + METH_NOARGS, allocate_doc}, + {"allocate", (PyCFunction)thread_PyThread_allocate_lock, + METH_NOARGS, allocate_doc}, + {"exit_thread", (PyCFunction)thread_PyThread_exit_thread, + METH_NOARGS, exit_doc}, + {"exit", (PyCFunction)thread_PyThread_exit_thread, + METH_NOARGS, exit_doc}, + {"interrupt_main", (PyCFunction)thread_PyThread_interrupt_main, + METH_NOARGS, interrupt_doc}, + {"get_ident", (PyCFunction)thread_get_ident, + METH_NOARGS, get_ident_doc}, + {"stack_size", (PyCFunction)thread_stack_size, + METH_VARARGS, + stack_size_doc}, #ifndef NO_EXIT_PROG - {"exit_prog", (PyCFunction)thread_PyThread_exit_prog, - METH_VARARGS}, + {"exit_prog", (PyCFunction)thread_PyThread_exit_prog, + METH_VARARGS}, #endif - {NULL, NULL} /* sentinel */ + {NULL, NULL} /* sentinel */ }; @@ -712,47 +712,47 @@ will block until another thread unlocks it. Deadlocks may ensue."); static struct PyModuleDef threadmodule = { - PyModuleDef_HEAD_INIT, - "_thread", - thread_doc, - -1, - thread_methods, - NULL, - NULL, - NULL, - NULL + PyModuleDef_HEAD_INIT, + "_thread", + thread_doc, + -1, + thread_methods, + NULL, + NULL, + NULL, + NULL }; PyMODINIT_FUNC PyInit__thread(void) { - PyObject *m, *d; - - /* Initialize types: */ - if (PyType_Ready(&localtype) < 0) - return NULL; - if (PyType_Ready(&Locktype) < 0) - return NULL; - - /* Create the module and add the functions */ - m = PyModule_Create(&threadmodule); - if (m == NULL) - return NULL; - - /* Add a symbolic constant */ - d = PyModule_GetDict(m); - ThreadError = PyErr_NewException("_thread.error", NULL, NULL); - PyDict_SetItemString(d, "error", ThreadError); - Locktype.tp_doc = lock_doc; - Py_INCREF(&Locktype); - PyDict_SetItemString(d, "LockType", (PyObject *)&Locktype); - - Py_INCREF(&localtype); - if (PyModule_AddObject(m, "_local", (PyObject *)&localtype) < 0) - return NULL; - - /* Initialize the C thread library */ - PyThread_init_thread(); - return m; + PyObject *m, *d; + + /* Initialize types: */ + if (PyType_Ready(&localtype) < 0) + return NULL; + if (PyType_Ready(&Locktype) < 0) + return NULL; + + /* Create the module and add the functions */ + m = PyModule_Create(&threadmodule); + if (m == NULL) + return NULL; + + /* Add a symbolic constant */ + d = PyModule_GetDict(m); + ThreadError = PyErr_NewException("_thread.error", NULL, NULL); + PyDict_SetItemString(d, "error", ThreadError); + Locktype.tp_doc = lock_doc; + Py_INCREF(&Locktype); + PyDict_SetItemString(d, "LockType", (PyObject *)&Locktype); + + Py_INCREF(&localtype); + if (PyModule_AddObject(m, "_local", (PyObject *)&localtype) < 0) + return NULL; + + /* Initialize the C thread library */ + PyThread_init_thread(); + return m; } Modified: python/branches/release31-maint/Modules/_tkinter.c ============================================================================== --- python/branches/release31-maint/Modules/_tkinter.c (original) +++ python/branches/release31-maint/Modules/_tkinter.c Sun May 9 18:14:21 2010 @@ -9,9 +9,9 @@ /* TCL/TK VERSION INFO: - Only Tcl/Tk 8.3.1 and later are supported. Older versions are not - supported. Use Python 2.6 or older if you cannot upgrade your - Tcl/Tk libraries. + Only Tcl/Tk 8.3.1 and later are supported. Older versions are not + supported. Use Python 2.6 or older if you cannot upgrade your + Tcl/Tk libraries. */ /* XXX Further speed-up ideas, involving Tcl 8.0 features: @@ -197,32 +197,32 @@ #endif #define ENTER_TCL \ - { PyThreadState *tstate = PyThreadState_Get(); Py_BEGIN_ALLOW_THREADS \ - if(tcl_lock)PyThread_acquire_lock(tcl_lock, 1); tcl_tstate = tstate; + { PyThreadState *tstate = PyThreadState_Get(); Py_BEGIN_ALLOW_THREADS \ + if(tcl_lock)PyThread_acquire_lock(tcl_lock, 1); tcl_tstate = tstate; #define LEAVE_TCL \ tcl_tstate = NULL; if(tcl_lock)PyThread_release_lock(tcl_lock); Py_END_ALLOW_THREADS} #define ENTER_OVERLAP \ - Py_END_ALLOW_THREADS + Py_END_ALLOW_THREADS #define LEAVE_OVERLAP_TCL \ - tcl_tstate = NULL; if(tcl_lock)PyThread_release_lock(tcl_lock); } + tcl_tstate = NULL; if(tcl_lock)PyThread_release_lock(tcl_lock); } #define ENTER_PYTHON \ - { PyThreadState *tstate = tcl_tstate; tcl_tstate = NULL; \ - if(tcl_lock)PyThread_release_lock(tcl_lock); PyEval_RestoreThread((tstate)); } + { PyThreadState *tstate = tcl_tstate; tcl_tstate = NULL; \ + if(tcl_lock)PyThread_release_lock(tcl_lock); PyEval_RestoreThread((tstate)); } #define LEAVE_PYTHON \ - { PyThreadState *tstate = PyEval_SaveThread(); \ - if(tcl_lock)PyThread_acquire_lock(tcl_lock, 1); tcl_tstate = tstate; } + { PyThreadState *tstate = PyEval_SaveThread(); \ + if(tcl_lock)PyThread_acquire_lock(tcl_lock, 1); tcl_tstate = tstate; } #define CHECK_TCL_APPARTMENT \ - if (((TkappObject *)self)->threaded && \ - ((TkappObject *)self)->thread_id != Tcl_GetCurrentThread()) { \ - PyErr_SetString(PyExc_RuntimeError, "Calling Tcl from different appartment"); \ - return 0; \ - } + if (((TkappObject *)self)->threaded && \ + ((TkappObject *)self)->thread_id != Tcl_GetCurrentThread()) { \ + PyErr_SetString(PyExc_RuntimeError, "Calling Tcl from different appartment"); \ + return 0; \ + } #else @@ -245,21 +245,21 @@ static PyTypeObject Tkapp_Type; typedef struct { - PyObject_HEAD - Tcl_Interp *interp; - int wantobjects; - int threaded; /* True if tcl_platform[threaded] */ - Tcl_ThreadId thread_id; - int dispatching; - /* We cannot include tclInt.h, as this is internal. - So we cache interesting types here. */ - Tcl_ObjType *BooleanType; - Tcl_ObjType *ByteArrayType; - Tcl_ObjType *DoubleType; - Tcl_ObjType *IntType; - Tcl_ObjType *ListType; - Tcl_ObjType *ProcBodyType; - Tcl_ObjType *StringType; + PyObject_HEAD + Tcl_Interp *interp; + int wantobjects; + int threaded; /* True if tcl_platform[threaded] */ + Tcl_ThreadId thread_id; + int dispatching; + /* We cannot include tclInt.h, as this is internal. + So we cache interesting types here. */ + Tcl_ObjType *BooleanType; + Tcl_ObjType *ByteArrayType; + Tcl_ObjType *DoubleType; + Tcl_ObjType *IntType; + Tcl_ObjType *ListType; + Tcl_ObjType *ProcBodyType; + Tcl_ObjType *StringType; } TkappObject; #define Tkapp_Check(v) (Py_TYPE(v) == &Tkapp_Type) @@ -270,7 +270,7 @@ (void *) v, Py_REFCNT(v))) - + /**** Error Handling ****/ static PyObject *Tkinter_TclError; @@ -284,16 +284,16 @@ static int tk_load_failed = 0; #endif - + static PyObject * Tkinter_Error(PyObject *v) { - PyErr_SetString(Tkinter_TclError, Tkapp_Result(v)); - return NULL; + PyErr_SetString(Tkinter_TclError, Tkapp_Result(v)); + return NULL; } - + /**** Utils ****/ static int Tkinter_busywaitinterval = 20; @@ -306,11 +306,11 @@ static void Sleep(int milli) { - /* XXX Too bad if you don't have select(). */ - struct timeval t; - t.tv_sec = milli/1000; - t.tv_usec = (milli%1000) * 1000; - select(0, (fd_set *)0, (fd_set *)0, (fd_set *)0, &t); + /* XXX Too bad if you don't have select(). */ + struct timeval t; + t.tv_sec = milli/1000; + t.tv_usec = (milli%1000) * 1000; + select(0, (fd_set *)0, (fd_set *)0, (fd_set *)0, &t); } #endif /* MS_WINDOWS */ @@ -319,172 +319,172 @@ static int WaitForMainloop(TkappObject* self) { - int i; - for (i = 0; i < 10; i++) { - if (self->dispatching) - return 1; - Py_BEGIN_ALLOW_THREADS - Sleep(100); - Py_END_ALLOW_THREADS - } - if (self->dispatching) - return 1; - PyErr_SetString(PyExc_RuntimeError, "main thread is not in main loop"); - return 0; + int i; + for (i = 0; i < 10; i++) { + if (self->dispatching) + return 1; + Py_BEGIN_ALLOW_THREADS + Sleep(100); + Py_END_ALLOW_THREADS + } + if (self->dispatching) + return 1; + PyErr_SetString(PyExc_RuntimeError, "main thread is not in main loop"); + return 0; } #endif /* WITH_THREAD */ - + static char * AsString(PyObject *value, PyObject *tmp) { - if (PyBytes_Check(value)) - return PyBytes_AsString(value); - else if (PyUnicode_Check(value)) { - PyObject *v = PyUnicode_AsUTF8String(value); - if (v == NULL) - return NULL; - if (PyList_Append(tmp, v) != 0) { - Py_DECREF(v); - return NULL; - } - Py_DECREF(v); - return PyBytes_AsString(v); - } - else { - PyObject *v = PyObject_Str(value); - if (v == NULL) - return NULL; - if (PyList_Append(tmp, v) != 0) { - Py_DECREF(v); - return NULL; - } - Py_DECREF(v); - return PyBytes_AsString(v); - } + if (PyBytes_Check(value)) + return PyBytes_AsString(value); + else if (PyUnicode_Check(value)) { + PyObject *v = PyUnicode_AsUTF8String(value); + if (v == NULL) + return NULL; + if (PyList_Append(tmp, v) != 0) { + Py_DECREF(v); + return NULL; + } + Py_DECREF(v); + return PyBytes_AsString(v); + } + else { + PyObject *v = PyObject_Str(value); + if (v == NULL) + return NULL; + if (PyList_Append(tmp, v) != 0) { + Py_DECREF(v); + return NULL; + } + Py_DECREF(v); + return PyBytes_AsString(v); + } } - + #define ARGSZ 64 static char * Merge(PyObject *args) { - PyObject *tmp = NULL; - char *argvStore[ARGSZ]; - char **argv = NULL; - int fvStore[ARGSZ]; - int *fv = NULL; - int argc = 0, fvc = 0, i; - char *res = NULL; - - if (!(tmp = PyList_New(0))) - return NULL; - - argv = argvStore; - fv = fvStore; - - if (args == NULL) - argc = 0; - - else if (!PyTuple_Check(args)) { - argc = 1; - fv[0] = 0; - if (!(argv[0] = AsString(args, tmp))) - goto finally; - } - else { - argc = PyTuple_Size(args); - - if (argc > ARGSZ) { - argv = (char **)ckalloc(argc * sizeof(char *)); - fv = (int *)ckalloc(argc * sizeof(int)); - if (argv == NULL || fv == NULL) { - PyErr_NoMemory(); - goto finally; - } - } - - for (i = 0; i < argc; i++) { - PyObject *v = PyTuple_GetItem(args, i); - if (PyTuple_Check(v)) { - fv[i] = 1; - if (!(argv[i] = Merge(v))) - goto finally; - fvc++; - } - else if (v == Py_None) { - argc = i; - break; - } - else { - fv[i] = 0; - if (!(argv[i] = AsString(v, tmp))) - goto finally; - fvc++; - } - } - } - res = Tcl_Merge(argc, argv); - if (res == NULL) - PyErr_SetString(Tkinter_TclError, "merge failed"); + PyObject *tmp = NULL; + char *argvStore[ARGSZ]; + char **argv = NULL; + int fvStore[ARGSZ]; + int *fv = NULL; + int argc = 0, fvc = 0, i; + char *res = NULL; + + if (!(tmp = PyList_New(0))) + return NULL; + + argv = argvStore; + fv = fvStore; + + if (args == NULL) + argc = 0; + + else if (!PyTuple_Check(args)) { + argc = 1; + fv[0] = 0; + if (!(argv[0] = AsString(args, tmp))) + goto finally; + } + else { + argc = PyTuple_Size(args); + + if (argc > ARGSZ) { + argv = (char **)ckalloc(argc * sizeof(char *)); + fv = (int *)ckalloc(argc * sizeof(int)); + if (argv == NULL || fv == NULL) { + PyErr_NoMemory(); + goto finally; + } + } + + for (i = 0; i < argc; i++) { + PyObject *v = PyTuple_GetItem(args, i); + if (PyTuple_Check(v)) { + fv[i] = 1; + if (!(argv[i] = Merge(v))) + goto finally; + fvc++; + } + else if (v == Py_None) { + argc = i; + break; + } + else { + fv[i] = 0; + if (!(argv[i] = AsString(v, tmp))) + goto finally; + fvc++; + } + } + } + res = Tcl_Merge(argc, argv); + if (res == NULL) + PyErr_SetString(Tkinter_TclError, "merge failed"); finally: - for (i = 0; i < fvc; i++) - if (fv[i]) { - ckfree(argv[i]); - } - if (argv != argvStore) - ckfree(FREECAST argv); - if (fv != fvStore) - ckfree(FREECAST fv); + for (i = 0; i < fvc; i++) + if (fv[i]) { + ckfree(argv[i]); + } + if (argv != argvStore) + ckfree(FREECAST argv); + if (fv != fvStore) + ckfree(FREECAST fv); - Py_DECREF(tmp); - return res; + Py_DECREF(tmp); + return res; } - + static PyObject * Split(char *list) { - int argc; - char **argv; - PyObject *v; - - if (list == NULL) { - Py_INCREF(Py_None); - return Py_None; - } - - if (Tcl_SplitList((Tcl_Interp *)NULL, list, &argc, &argv) != TCL_OK) { - /* Not a list. - * Could be a quoted string containing funnies, e.g. {"}. - * Return the string itself. - */ - return PyUnicode_FromString(list); - } - - if (argc == 0) - v = PyUnicode_FromString(""); - else if (argc == 1) - v = PyUnicode_FromString(argv[0]); - else if ((v = PyTuple_New(argc)) != NULL) { - int i; - PyObject *w; - - for (i = 0; i < argc; i++) { - if ((w = Split(argv[i])) == NULL) { - Py_DECREF(v); - v = NULL; - break; - } - PyTuple_SetItem(v, i, w); - } - } - Tcl_Free(FREECAST argv); - return v; + int argc; + char **argv; + PyObject *v; + + if (list == NULL) { + Py_INCREF(Py_None); + return Py_None; + } + + if (Tcl_SplitList((Tcl_Interp *)NULL, list, &argc, &argv) != TCL_OK) { + /* Not a list. + * Could be a quoted string containing funnies, e.g. {"}. + * Return the string itself. + */ + return PyUnicode_FromString(list); + } + + if (argc == 0) + v = PyUnicode_FromString(""); + else if (argc == 1) + v = PyUnicode_FromString(argv[0]); + else if ((v = PyTuple_New(argc)) != NULL) { + int i; + PyObject *w; + + for (i = 0; i < argc; i++) { + if ((w = Split(argv[i])) == NULL) { + Py_DECREF(v); + v = NULL; + break; + } + PyTuple_SetItem(v, i, w); + } + } + Tcl_Free(FREECAST argv); + return v; } /* In some cases, Tcl will still return strings that are supposed to be @@ -494,103 +494,103 @@ static PyObject * SplitObj(PyObject *arg) { - if (PyTuple_Check(arg)) { - int i, size; - PyObject *elem, *newelem, *result; - - size = PyTuple_Size(arg); - result = NULL; - /* Recursively invoke SplitObj for all tuple items. - If this does not return a new object, no action is - needed. */ - for(i = 0; i < size; i++) { - elem = PyTuple_GetItem(arg, i); - newelem = SplitObj(elem); - if (!newelem) { - Py_XDECREF(result); - return NULL; - } - if (!result) { - int k; - if (newelem == elem) { - Py_DECREF(newelem); - continue; - } - result = PyTuple_New(size); - if (!result) - return NULL; - for(k = 0; k < i; k++) { - elem = PyTuple_GetItem(arg, k); - Py_INCREF(elem); - PyTuple_SetItem(result, k, elem); - } - } - PyTuple_SetItem(result, i, newelem); - } - if (result) - return result; - /* Fall through, returning arg. */ - } - else if (PyBytes_Check(arg)) { - int argc; - char **argv; - char *list = PyBytes_AsString(arg); - - if (Tcl_SplitList((Tcl_Interp *)NULL, list, &argc, &argv) != TCL_OK) { - Py_INCREF(arg); - return arg; - } - Tcl_Free(FREECAST argv); - if (argc > 1) - return Split(PyBytes_AsString(arg)); - /* Fall through, returning arg. */ - } - Py_INCREF(arg); - return arg; + if (PyTuple_Check(arg)) { + int i, size; + PyObject *elem, *newelem, *result; + + size = PyTuple_Size(arg); + result = NULL; + /* Recursively invoke SplitObj for all tuple items. + If this does not return a new object, no action is + needed. */ + for(i = 0; i < size; i++) { + elem = PyTuple_GetItem(arg, i); + newelem = SplitObj(elem); + if (!newelem) { + Py_XDECREF(result); + return NULL; + } + if (!result) { + int k; + if (newelem == elem) { + Py_DECREF(newelem); + continue; + } + result = PyTuple_New(size); + if (!result) + return NULL; + for(k = 0; k < i; k++) { + elem = PyTuple_GetItem(arg, k); + Py_INCREF(elem); + PyTuple_SetItem(result, k, elem); + } + } + PyTuple_SetItem(result, i, newelem); + } + if (result) + return result; + /* Fall through, returning arg. */ + } + else if (PyBytes_Check(arg)) { + int argc; + char **argv; + char *list = PyBytes_AsString(arg); + + if (Tcl_SplitList((Tcl_Interp *)NULL, list, &argc, &argv) != TCL_OK) { + Py_INCREF(arg); + return arg; + } + Tcl_Free(FREECAST argv); + if (argc > 1) + return Split(PyBytes_AsString(arg)); + /* Fall through, returning arg. */ + } + Py_INCREF(arg); + return arg; } - + /**** Tkapp Object ****/ #ifndef WITH_APPINIT int Tcl_AppInit(Tcl_Interp *interp) { - const char * _tkinter_skip_tk_init; + const char * _tkinter_skip_tk_init; - if (Tcl_Init(interp) == TCL_ERROR) { - PySys_WriteStderr("Tcl_Init error: %s\n", Tcl_GetStringResult(interp)); - return TCL_ERROR; - } - - _tkinter_skip_tk_init = Tcl_GetVar(interp, - "_tkinter_skip_tk_init", TCL_GLOBAL_ONLY); - if (_tkinter_skip_tk_init != NULL && - strcmp(_tkinter_skip_tk_init, "1") == 0) { - return TCL_OK; - } + if (Tcl_Init(interp) == TCL_ERROR) { + PySys_WriteStderr("Tcl_Init error: %s\n", Tcl_GetStringResult(interp)); + return TCL_ERROR; + } + + _tkinter_skip_tk_init = Tcl_GetVar(interp, + "_tkinter_skip_tk_init", TCL_GLOBAL_ONLY); + if (_tkinter_skip_tk_init != NULL && + strcmp(_tkinter_skip_tk_init, "1") == 0) { + return TCL_OK; + } #ifdef TKINTER_PROTECT_LOADTK - if (tk_load_failed) { - PySys_WriteStderr("Tk_Init error: %s\n", TKINTER_LOADTK_ERRMSG); - return TCL_ERROR; - } + if (tk_load_failed) { + PySys_WriteStderr("Tk_Init error: %s\n", TKINTER_LOADTK_ERRMSG); + return TCL_ERROR; + } #endif - if (Tk_Init(interp) == TCL_ERROR) { + if (Tk_Init(interp) == TCL_ERROR) { #ifdef TKINTER_PROTECT_LOADTK - tk_load_failed = 1; + tk_load_failed = 1; #endif - PySys_WriteStderr("Tk_Init error: %s\n", Tcl_GetStringResult(interp)); - return TCL_ERROR; - } + PySys_WriteStderr("Tk_Init error: %s\n", Tcl_GetStringResult(interp)); + return TCL_ERROR; + } - return TCL_OK; + return TCL_OK; } #endif /* !WITH_APPINIT */ - + /* Initialize the Tk application; see the `main' function in * `tkMain.c'. @@ -601,189 +601,189 @@ static TkappObject * Tkapp_New(char *screenName, char *className, - int interactive, int wantobjects, int wantTk, int sync, char *use) + int interactive, int wantobjects, int wantTk, int sync, char *use) { - TkappObject *v; - char *argv0; + TkappObject *v; + char *argv0; - v = PyObject_New(TkappObject, &Tkapp_Type); - if (v == NULL) - return NULL; - - v->interp = Tcl_CreateInterp(); - v->wantobjects = wantobjects; - v->threaded = Tcl_GetVar2Ex(v->interp, "tcl_platform", "threaded", - TCL_GLOBAL_ONLY) != NULL; - v->thread_id = Tcl_GetCurrentThread(); - v->dispatching = 0; + v = PyObject_New(TkappObject, &Tkapp_Type); + if (v == NULL) + return NULL; + + v->interp = Tcl_CreateInterp(); + v->wantobjects = wantobjects; + v->threaded = Tcl_GetVar2Ex(v->interp, "tcl_platform", "threaded", + TCL_GLOBAL_ONLY) != NULL; + v->thread_id = Tcl_GetCurrentThread(); + v->dispatching = 0; #ifndef TCL_THREADS - if (v->threaded) { - PyErr_SetString(PyExc_RuntimeError, "Tcl is threaded but _tkinter is not"); - Py_DECREF(v); - return 0; - } -#endif -#ifdef WITH_THREAD - if (v->threaded && tcl_lock) { - /* If Tcl is threaded, we don't need the lock. */ - PyThread_free_lock(tcl_lock); - tcl_lock = NULL; - } -#endif - - v->BooleanType = Tcl_GetObjType("boolean"); - v->ByteArrayType = Tcl_GetObjType("bytearray"); - v->DoubleType = Tcl_GetObjType("double"); - v->IntType = Tcl_GetObjType("int"); - v->ListType = Tcl_GetObjType("list"); - v->ProcBodyType = Tcl_GetObjType("procbody"); - v->StringType = Tcl_GetObjType("string"); - - /* Delete the 'exit' command, which can screw things up */ - Tcl_DeleteCommand(v->interp, "exit"); - - if (screenName != NULL) - Tcl_SetVar2(v->interp, "env", "DISPLAY", - screenName, TCL_GLOBAL_ONLY); - - if (interactive) - Tcl_SetVar(v->interp, "tcl_interactive", "1", TCL_GLOBAL_ONLY); - else - Tcl_SetVar(v->interp, "tcl_interactive", "0", TCL_GLOBAL_ONLY); - - /* This is used to get the application class for Tk 4.1 and up */ - argv0 = (char*)ckalloc(strlen(className) + 1); - if (!argv0) { - PyErr_NoMemory(); - Py_DECREF(v); - return NULL; - } - - strcpy(argv0, className); - if (isupper(Py_CHARMASK(argv0[0]))) - argv0[0] = tolower(Py_CHARMASK(argv0[0])); - Tcl_SetVar(v->interp, "argv0", argv0, TCL_GLOBAL_ONLY); - ckfree(argv0); - - if (! wantTk) { - Tcl_SetVar(v->interp, - "_tkinter_skip_tk_init", "1", TCL_GLOBAL_ONLY); - } + if (v->threaded) { + PyErr_SetString(PyExc_RuntimeError, "Tcl is threaded but _tkinter is not"); + Py_DECREF(v); + return 0; + } +#endif +#ifdef WITH_THREAD + if (v->threaded && tcl_lock) { + /* If Tcl is threaded, we don't need the lock. */ + PyThread_free_lock(tcl_lock); + tcl_lock = NULL; + } +#endif + + v->BooleanType = Tcl_GetObjType("boolean"); + v->ByteArrayType = Tcl_GetObjType("bytearray"); + v->DoubleType = Tcl_GetObjType("double"); + v->IntType = Tcl_GetObjType("int"); + v->ListType = Tcl_GetObjType("list"); + v->ProcBodyType = Tcl_GetObjType("procbody"); + v->StringType = Tcl_GetObjType("string"); + + /* Delete the 'exit' command, which can screw things up */ + Tcl_DeleteCommand(v->interp, "exit"); + + if (screenName != NULL) + Tcl_SetVar2(v->interp, "env", "DISPLAY", + screenName, TCL_GLOBAL_ONLY); + + if (interactive) + Tcl_SetVar(v->interp, "tcl_interactive", "1", TCL_GLOBAL_ONLY); + else + Tcl_SetVar(v->interp, "tcl_interactive", "0", TCL_GLOBAL_ONLY); + + /* This is used to get the application class for Tk 4.1 and up */ + argv0 = (char*)ckalloc(strlen(className) + 1); + if (!argv0) { + PyErr_NoMemory(); + Py_DECREF(v); + return NULL; + } + + strcpy(argv0, className); + if (isupper(Py_CHARMASK(argv0[0]))) + argv0[0] = tolower(Py_CHARMASK(argv0[0])); + Tcl_SetVar(v->interp, "argv0", argv0, TCL_GLOBAL_ONLY); + ckfree(argv0); + + if (! wantTk) { + Tcl_SetVar(v->interp, + "_tkinter_skip_tk_init", "1", TCL_GLOBAL_ONLY); + } #ifdef TKINTER_PROTECT_LOADTK - else if (tk_load_failed) { - Tcl_SetVar(v->interp, - "_tkinter_tk_failed", "1", TCL_GLOBAL_ONLY); - } -#endif - - /* some initial arguments need to be in argv */ - if (sync || use) { - char *args; - int len = 0; - - if (sync) - len += sizeof "-sync"; - if (use) - len += strlen(use) + sizeof "-use "; - - args = (char*)ckalloc(len); - if (!args) { - PyErr_NoMemory(); - Py_DECREF(v); - return NULL; - } - - args[0] = '\0'; - if (sync) - strcat(args, "-sync"); - if (use) { - if (sync) - strcat(args, " "); - strcat(args, "-use "); - strcat(args, use); - } - - Tcl_SetVar(v->interp, "argv", args, TCL_GLOBAL_ONLY); - ckfree(args); - } + else if (tk_load_failed) { + Tcl_SetVar(v->interp, + "_tkinter_tk_failed", "1", TCL_GLOBAL_ONLY); + } +#endif + + /* some initial arguments need to be in argv */ + if (sync || use) { + char *args; + int len = 0; + + if (sync) + len += sizeof "-sync"; + if (use) + len += strlen(use) + sizeof "-use "; + + args = (char*)ckalloc(len); + if (!args) { + PyErr_NoMemory(); + Py_DECREF(v); + return NULL; + } + + args[0] = '\0'; + if (sync) + strcat(args, "-sync"); + if (use) { + if (sync) + strcat(args, " "); + strcat(args, "-use "); + strcat(args, use); + } + + Tcl_SetVar(v->interp, "argv", args, TCL_GLOBAL_ONLY); + ckfree(args); + } - if (Tcl_AppInit(v->interp) != TCL_OK) { - PyObject *result = Tkinter_Error((PyObject *)v); + if (Tcl_AppInit(v->interp) != TCL_OK) { + PyObject *result = Tkinter_Error((PyObject *)v); #ifdef TKINTER_PROTECT_LOADTK - if (wantTk) { - const char *_tkinter_tk_failed; - _tkinter_tk_failed = Tcl_GetVar(v->interp, - "_tkinter_tk_failed", TCL_GLOBAL_ONLY); - - if ( _tkinter_tk_failed != NULL && - strcmp(_tkinter_tk_failed, "1") == 0) { - tk_load_failed = 1; - } - } -#endif - Py_DECREF((PyObject *)v); - return (TkappObject *)result; - } + if (wantTk) { + const char *_tkinter_tk_failed; + _tkinter_tk_failed = Tcl_GetVar(v->interp, + "_tkinter_tk_failed", TCL_GLOBAL_ONLY); + + if ( _tkinter_tk_failed != NULL && + strcmp(_tkinter_tk_failed, "1") == 0) { + tk_load_failed = 1; + } + } +#endif + Py_DECREF((PyObject *)v); + return (TkappObject *)result; + } - EnableEventHook(); + EnableEventHook(); - return v; + return v; } #ifdef WITH_THREAD static void Tkapp_ThreadSend(TkappObject *self, Tcl_Event *ev, - Tcl_Condition *cond, Tcl_Mutex *mutex) + Tcl_Condition *cond, Tcl_Mutex *mutex) { - Py_BEGIN_ALLOW_THREADS; - Tcl_MutexLock(mutex); - Tcl_ThreadQueueEvent(self->thread_id, ev, TCL_QUEUE_TAIL); - Tcl_ThreadAlert(self->thread_id); - Tcl_ConditionWait(cond, mutex, NULL); - Tcl_MutexUnlock(mutex); - Py_END_ALLOW_THREADS + Py_BEGIN_ALLOW_THREADS; + Tcl_MutexLock(mutex); + Tcl_ThreadQueueEvent(self->thread_id, ev, TCL_QUEUE_TAIL); + Tcl_ThreadAlert(self->thread_id); + Tcl_ConditionWait(cond, mutex, NULL); + Tcl_MutexUnlock(mutex); + Py_END_ALLOW_THREADS } #endif - + /** Tcl Eval **/ typedef struct { - PyObject_HEAD - Tcl_Obj *value; - PyObject *string; /* This cannot cause cycles. */ + PyObject_HEAD + Tcl_Obj *value; + PyObject *string; /* This cannot cause cycles. */ } PyTclObject; static PyTypeObject PyTclObject_Type; -#define PyTclObject_Check(v) ((v)->ob_type == &PyTclObject_Type) +#define PyTclObject_Check(v) ((v)->ob_type == &PyTclObject_Type) static PyObject * newPyTclObject(Tcl_Obj *arg) { - PyTclObject *self; - self = PyObject_New(PyTclObject, &PyTclObject_Type); - if (self == NULL) - return NULL; - Tcl_IncrRefCount(arg); - self->value = arg; - self->string = NULL; - return (PyObject*)self; + PyTclObject *self; + self = PyObject_New(PyTclObject, &PyTclObject_Type); + if (self == NULL) + return NULL; + Tcl_IncrRefCount(arg); + self->value = arg; + self->string = NULL; + return (PyObject*)self; } static void PyTclObject_dealloc(PyTclObject *self) { - Tcl_DecrRefCount(self->value); - Py_XDECREF(self->string); - PyObject_Del(self); + Tcl_DecrRefCount(self->value); + Py_XDECREF(self->string); + PyObject_Del(self); } static char* PyTclObject_TclString(PyObject *self) { - return Tcl_GetString(((PyTclObject*)self)->value); + return Tcl_GetString(((PyTclObject*)self)->value); } /* Like _str, but create Unicode if necessary. */ @@ -793,37 +793,37 @@ static PyObject * PyTclObject_string(PyTclObject *self, void *ignored) { - char *s; - int len; - if (!self->string) { - s = Tcl_GetStringFromObj(self->value, &len); - self->string = PyUnicode_FromStringAndSize(s, len); - if (!self->string) - return NULL; - } - Py_INCREF(self->string); - return self->string; + char *s; + int len; + if (!self->string) { + s = Tcl_GetStringFromObj(self->value, &len); + self->string = PyUnicode_FromStringAndSize(s, len); + if (!self->string) + return NULL; + } + Py_INCREF(self->string); + return self->string; } static PyObject * PyTclObject_str(PyTclObject *self, void *ignored) { - char *s; - int len; - if (self->string && PyUnicode_Check(self->string)) { - Py_INCREF(self->string); - return self->string; - } - /* XXX Could chache result if it is non-ASCII. */ - s = Tcl_GetStringFromObj(self->value, &len); - return PyUnicode_DecodeUTF8(s, len, "strict"); + char *s; + int len; + if (self->string && PyUnicode_Check(self->string)) { + Py_INCREF(self->string); + return self->string; + } + /* XXX Could chache result if it is non-ASCII. */ + s = Tcl_GetStringFromObj(self->value, &len); + return PyUnicode_DecodeUTF8(s, len, "strict"); } static PyObject * PyTclObject_repr(PyTclObject *self) { - return PyUnicode_FromFormat("<%s object at %p>", - self->value->typePtr->name, self->value); + return PyUnicode_FromFormat("<%s object at %p>", + self->value->typePtr->name, self->value); } #define TEST_COND(cond) ((cond) ? Py_True : Py_False) @@ -831,54 +831,54 @@ static PyObject * PyTclObject_richcompare(PyObject *self, PyObject *other, int op) { - int result; - PyObject *v; + int result; + PyObject *v; - /* neither argument should be NULL, unless something's gone wrong */ - if (self == NULL || other == NULL) { - PyErr_BadInternalCall(); - return NULL; - } - - /* both arguments should be instances of PyTclObject */ - if (!PyTclObject_Check(self) || !PyTclObject_Check(other)) { - v = Py_NotImplemented; - goto finished; - } - - if (self == other) - /* fast path when self and other are identical */ - result = 0; - else - result = strcmp(Tcl_GetString(((PyTclObject *)self)->value), - Tcl_GetString(((PyTclObject *)other)->value)); - /* Convert return value to a Boolean */ - switch (op) { - case Py_EQ: - v = TEST_COND(result == 0); - break; - case Py_NE: - v = TEST_COND(result != 0); - break; - case Py_LE: - v = TEST_COND(result <= 0); - break; - case Py_GE: - v = TEST_COND(result >= 0); - break; - case Py_LT: - v = TEST_COND(result < 0); - break; - case Py_GT: - v = TEST_COND(result > 0); - break; - default: - PyErr_BadArgument(); - return NULL; - } + /* neither argument should be NULL, unless something's gone wrong */ + if (self == NULL || other == NULL) { + PyErr_BadInternalCall(); + return NULL; + } + + /* both arguments should be instances of PyTclObject */ + if (!PyTclObject_Check(self) || !PyTclObject_Check(other)) { + v = Py_NotImplemented; + goto finished; + } + + if (self == other) + /* fast path when self and other are identical */ + result = 0; + else + result = strcmp(Tcl_GetString(((PyTclObject *)self)->value), + Tcl_GetString(((PyTclObject *)other)->value)); + /* Convert return value to a Boolean */ + switch (op) { + case Py_EQ: + v = TEST_COND(result == 0); + break; + case Py_NE: + v = TEST_COND(result != 0); + break; + case Py_LE: + v = TEST_COND(result <= 0); + break; + case Py_GE: + v = TEST_COND(result >= 0); + break; + case Py_LT: + v = TEST_COND(result < 0); + break; + case Py_GT: + v = TEST_COND(result > 0); + break; + default: + PyErr_BadArgument(); + return NULL; + } finished: - Py_INCREF(v); - return v; + Py_INCREF(v); + return v; } PyDoc_STRVAR(get_typename__doc__, "name of the Tcl type"); @@ -886,230 +886,230 @@ static PyObject* get_typename(PyTclObject* obj, void* ignored) { - return PyUnicode_FromString(obj->value->typePtr->name); + return PyUnicode_FromString(obj->value->typePtr->name); } static PyGetSetDef PyTclObject_getsetlist[] = { - {"typename", (getter)get_typename, NULL, get_typename__doc__}, - {"string", (getter)PyTclObject_string, NULL, - PyTclObject_string__doc__}, - {0}, + {"typename", (getter)get_typename, NULL, get_typename__doc__}, + {"string", (getter)PyTclObject_string, NULL, + PyTclObject_string__doc__}, + {0}, }; static PyTypeObject PyTclObject_Type = { - PyVarObject_HEAD_INIT(NULL, 0) - "_tkinter.Tcl_Obj", /*tp_name*/ - sizeof(PyTclObject), /*tp_basicsize*/ - 0, /*tp_itemsize*/ - /* methods */ - (destructor)PyTclObject_dealloc,/*tp_dealloc*/ - 0, /*tp_print*/ - 0, /*tp_getattr*/ - 0, /*tp_setattr*/ - 0, /*tp_reserved*/ - (reprfunc)PyTclObject_repr, /*tp_repr*/ - 0, /*tp_as_number*/ - 0, /*tp_as_sequence*/ - 0, /*tp_as_mapping*/ - 0, /*tp_hash*/ - 0, /*tp_call*/ - (reprfunc)PyTclObject_str, /*tp_str*/ - PyObject_GenericGetAttr, /*tp_getattro*/ - 0, /*tp_setattro*/ - 0, /*tp_as_buffer*/ - Py_TPFLAGS_DEFAULT, /*tp_flags*/ - 0, /*tp_doc*/ - 0, /*tp_traverse*/ - 0, /*tp_clear*/ - PyTclObject_richcompare, /*tp_richcompare*/ - 0, /*tp_weaklistoffset*/ - 0, /*tp_iter*/ - 0, /*tp_iternext*/ - 0, /*tp_methods*/ - 0, /*tp_members*/ - PyTclObject_getsetlist, /*tp_getset*/ - 0, /*tp_base*/ - 0, /*tp_dict*/ - 0, /*tp_descr_get*/ - 0, /*tp_descr_set*/ - 0, /*tp_dictoffset*/ - 0, /*tp_init*/ - 0, /*tp_alloc*/ - 0, /*tp_new*/ - 0, /*tp_free*/ - 0, /*tp_is_gc*/ + PyVarObject_HEAD_INIT(NULL, 0) + "_tkinter.Tcl_Obj", /*tp_name*/ + sizeof(PyTclObject), /*tp_basicsize*/ + 0, /*tp_itemsize*/ + /* methods */ + (destructor)PyTclObject_dealloc,/*tp_dealloc*/ + 0, /*tp_print*/ + 0, /*tp_getattr*/ + 0, /*tp_setattr*/ + 0, /*tp_reserved*/ + (reprfunc)PyTclObject_repr, /*tp_repr*/ + 0, /*tp_as_number*/ + 0, /*tp_as_sequence*/ + 0, /*tp_as_mapping*/ + 0, /*tp_hash*/ + 0, /*tp_call*/ + (reprfunc)PyTclObject_str, /*tp_str*/ + PyObject_GenericGetAttr, /*tp_getattro*/ + 0, /*tp_setattro*/ + 0, /*tp_as_buffer*/ + Py_TPFLAGS_DEFAULT, /*tp_flags*/ + 0, /*tp_doc*/ + 0, /*tp_traverse*/ + 0, /*tp_clear*/ + PyTclObject_richcompare, /*tp_richcompare*/ + 0, /*tp_weaklistoffset*/ + 0, /*tp_iter*/ + 0, /*tp_iternext*/ + 0, /*tp_methods*/ + 0, /*tp_members*/ + PyTclObject_getsetlist, /*tp_getset*/ + 0, /*tp_base*/ + 0, /*tp_dict*/ + 0, /*tp_descr_get*/ + 0, /*tp_descr_set*/ + 0, /*tp_dictoffset*/ + 0, /*tp_init*/ + 0, /*tp_alloc*/ + 0, /*tp_new*/ + 0, /*tp_free*/ + 0, /*tp_is_gc*/ }; static Tcl_Obj* AsObj(PyObject *value) { - Tcl_Obj *result; - long longVal; - int overflow; - - if (PyBytes_Check(value)) - return Tcl_NewStringObj(PyBytes_AS_STRING(value), - PyBytes_GET_SIZE(value)); - else if (PyBool_Check(value)) - return Tcl_NewBooleanObj(PyObject_IsTrue(value)); - else if (PyLong_CheckExact(value) && - ((longVal = PyLong_AsLongAndOverflow(value, &overflow)), - !overflow)) { - /* If there is an overflow in the long conversion, - fall through to default object handling. */ - return Tcl_NewLongObj(longVal); - } - else if (PyFloat_Check(value)) - return Tcl_NewDoubleObj(PyFloat_AS_DOUBLE(value)); - else if (PyTuple_Check(value)) { - Tcl_Obj **argv = (Tcl_Obj**) - ckalloc(PyTuple_Size(value)*sizeof(Tcl_Obj*)); - int i; - if(!argv) - return 0; - for(i=0;i= size) - outbuf = (Tcl_UniChar*)ckalloc(allocsize); - /* Else overflow occurred, and we take the next exit */ - if (!outbuf) { - PyErr_NoMemory(); - return NULL; - } - for (i = 0; i < size; i++) { - if (inbuf[i] >= 0x10000) { - /* Tcl doesn't do UTF-16, yet. */ - PyErr_SetString(PyExc_ValueError, - "unsupported character"); - ckfree(FREECAST outbuf); - return NULL; - } - outbuf[i] = inbuf[i]; - } - result = Tcl_NewUnicodeObj(outbuf, size); - ckfree(FREECAST outbuf); - return result; + Tcl_UniChar *outbuf = NULL; + Py_ssize_t i; + size_t allocsize = ((size_t)size) * sizeof(Tcl_UniChar); + if (allocsize >= size) + outbuf = (Tcl_UniChar*)ckalloc(allocsize); + /* Else overflow occurred, and we take the next exit */ + if (!outbuf) { + PyErr_NoMemory(); + return NULL; + } + for (i = 0; i < size; i++) { + if (inbuf[i] >= 0x10000) { + /* Tcl doesn't do UTF-16, yet. */ + PyErr_SetString(PyExc_ValueError, + "unsupported character"); + ckfree(FREECAST outbuf); + return NULL; + } + outbuf[i] = inbuf[i]; + } + result = Tcl_NewUnicodeObj(outbuf, size); + ckfree(FREECAST outbuf); + return result; #else - return Tcl_NewUnicodeObj(inbuf, size); + return Tcl_NewUnicodeObj(inbuf, size); #endif - } - else if(PyTclObject_Check(value)) { - Tcl_Obj *v = ((PyTclObject*)value)->value; - Tcl_IncrRefCount(v); - return v; - } - else { - PyObject *v = PyObject_Str(value); - if (!v) - return 0; - result = AsObj(v); - Py_DECREF(v); - return result; - } + } + else if(PyTclObject_Check(value)) { + Tcl_Obj *v = ((PyTclObject*)value)->value; + Tcl_IncrRefCount(v); + return v; + } + else { + PyObject *v = PyObject_Str(value); + if (!v) + return 0; + result = AsObj(v); + Py_DECREF(v); + return result; + } } static PyObject* FromObj(PyObject* tkapp, Tcl_Obj *value) { - PyObject *result = NULL; - TkappObject *app = (TkappObject*)tkapp; + PyObject *result = NULL; + TkappObject *app = (TkappObject*)tkapp; - if (value->typePtr == NULL) { - return PyUnicode_FromStringAndSize(value->bytes, - value->length); - } - - if (value->typePtr == app->BooleanType) { - result = value->internalRep.longValue ? Py_True : Py_False; - Py_INCREF(result); - return result; - } - - if (value->typePtr == app->ByteArrayType) { - int size; - char *data = (char*)Tcl_GetByteArrayFromObj(value, &size); - return PyBytes_FromStringAndSize(data, size); - } - - if (value->typePtr == app->DoubleType) { - return PyFloat_FromDouble(value->internalRep.doubleValue); - } - - if (value->typePtr == app->IntType) { - return PyLong_FromLong(value->internalRep.longValue); - } - - if (value->typePtr == app->ListType) { - int size; - int i, status; - PyObject *elem; - Tcl_Obj *tcl_elem; - - status = Tcl_ListObjLength(Tkapp_Interp(tkapp), value, &size); - if (status == TCL_ERROR) - return Tkinter_Error(tkapp); - result = PyTuple_New(size); - if (!result) - return NULL; - for (i = 0; i < size; i++) { - status = Tcl_ListObjIndex(Tkapp_Interp(tkapp), - value, i, &tcl_elem); - if (status == TCL_ERROR) { - Py_DECREF(result); - return Tkinter_Error(tkapp); - } - elem = FromObj(tkapp, tcl_elem); - if (!elem) { - Py_DECREF(result); - return NULL; - } - PyTuple_SetItem(result, i, elem); - } - return result; - } - - if (value->typePtr == app->ProcBodyType) { - /* fall through: return tcl object. */ - } + if (value->typePtr == NULL) { + return PyUnicode_FromStringAndSize(value->bytes, + value->length); + } + + if (value->typePtr == app->BooleanType) { + result = value->internalRep.longValue ? Py_True : Py_False; + Py_INCREF(result); + return result; + } + + if (value->typePtr == app->ByteArrayType) { + int size; + char *data = (char*)Tcl_GetByteArrayFromObj(value, &size); + return PyBytes_FromStringAndSize(data, size); + } + + if (value->typePtr == app->DoubleType) { + return PyFloat_FromDouble(value->internalRep.doubleValue); + } + + if (value->typePtr == app->IntType) { + return PyLong_FromLong(value->internalRep.longValue); + } + + if (value->typePtr == app->ListType) { + int size; + int i, status; + PyObject *elem; + Tcl_Obj *tcl_elem; + + status = Tcl_ListObjLength(Tkapp_Interp(tkapp), value, &size); + if (status == TCL_ERROR) + return Tkinter_Error(tkapp); + result = PyTuple_New(size); + if (!result) + return NULL; + for (i = 0; i < size; i++) { + status = Tcl_ListObjIndex(Tkapp_Interp(tkapp), + value, i, &tcl_elem); + if (status == TCL_ERROR) { + Py_DECREF(result); + return Tkinter_Error(tkapp); + } + elem = FromObj(tkapp, tcl_elem); + if (!elem) { + Py_DECREF(result); + return NULL; + } + PyTuple_SetItem(result, i, elem); + } + return result; + } + + if (value->typePtr == app->ProcBodyType) { + /* fall through: return tcl object. */ + } - if (value->typePtr == app->StringType) { + if (value->typePtr == app->StringType) { #if defined(Py_UNICODE_WIDE) && TCL_UTF_MAX==3 - PyObject *result; - int size; - Tcl_UniChar *input; - Py_UNICODE *output; - - size = Tcl_GetCharLength(value); - result = PyUnicode_FromUnicode(NULL, size); - if (!result) - return NULL; - input = Tcl_GetUnicode(value); - output = PyUnicode_AS_UNICODE(result); - while (size--) - *output++ = *input++; - return result; + PyObject *result; + int size; + Tcl_UniChar *input; + Py_UNICODE *output; + + size = Tcl_GetCharLength(value); + result = PyUnicode_FromUnicode(NULL, size); + if (!result) + return NULL; + input = Tcl_GetUnicode(value); + output = PyUnicode_AS_UNICODE(result); + while (size--) + *output++ = *input++; + return result; #else - return PyUnicode_FromUnicode(Tcl_GetUnicode(value), - Tcl_GetCharLength(value)); + return PyUnicode_FromUnicode(Tcl_GetUnicode(value), + Tcl_GetCharLength(value)); #endif - } + } - return newPyTclObject(value); + return newPyTclObject(value); } #ifdef WITH_THREAD @@ -1117,24 +1117,24 @@ TCL_DECLARE_MUTEX(call_mutex) typedef struct Tkapp_CallEvent { - Tcl_Event ev; /* Must be first */ - TkappObject *self; - PyObject *args; - int flags; - PyObject **res; - PyObject **exc_type, **exc_value, **exc_tb; - Tcl_Condition *done; + Tcl_Event ev; /* Must be first */ + TkappObject *self; + PyObject *args; + int flags; + PyObject **res; + PyObject **exc_type, **exc_value, **exc_tb; + Tcl_Condition *done; } Tkapp_CallEvent; #endif void Tkapp_CallDeallocArgs(Tcl_Obj** objv, Tcl_Obj** objStore, int objc) { - int i; - for (i = 0; i < objc; i++) - Tcl_DecrRefCount(objv[i]); - if (objv != objStore) - ckfree(FREECAST objv); + int i; + for (i = 0; i < objc; i++) + Tcl_DecrRefCount(objv[i]); + if (objv != objStore) + ckfree(FREECAST objv); } /* Convert Python objects to Tcl objects. This must happen in the @@ -1143,51 +1143,51 @@ static Tcl_Obj** Tkapp_CallArgs(PyObject *args, Tcl_Obj** objStore, int *pobjc) { - Tcl_Obj **objv = objStore; - int objc = 0, i; - if (args == NULL) - /* do nothing */; - - else if (!PyTuple_Check(args)) { - objv[0] = AsObj(args); - if (objv[0] == 0) - goto finally; - objc = 1; - Tcl_IncrRefCount(objv[0]); - } - else { - objc = PyTuple_Size(args); - - if (objc > ARGSZ) { - objv = (Tcl_Obj **)ckalloc(objc * sizeof(char *)); - if (objv == NULL) { - PyErr_NoMemory(); - objc = 0; - goto finally; - } - } - - for (i = 0; i < objc; i++) { - PyObject *v = PyTuple_GetItem(args, i); - if (v == Py_None) { - objc = i; - break; - } - objv[i] = AsObj(v); - if (!objv[i]) { - /* Reset objc, so it attempts to clear - objects only up to i. */ - objc = i; - goto finally; - } - Tcl_IncrRefCount(objv[i]); - } - } - *pobjc = objc; - return objv; + Tcl_Obj **objv = objStore; + int objc = 0, i; + if (args == NULL) + /* do nothing */; + + else if (!PyTuple_Check(args)) { + objv[0] = AsObj(args); + if (objv[0] == 0) + goto finally; + objc = 1; + Tcl_IncrRefCount(objv[0]); + } + else { + objc = PyTuple_Size(args); + + if (objc > ARGSZ) { + objv = (Tcl_Obj **)ckalloc(objc * sizeof(char *)); + if (objv == NULL) { + PyErr_NoMemory(); + objc = 0; + goto finally; + } + } + + for (i = 0; i < objc; i++) { + PyObject *v = PyTuple_GetItem(args, i); + if (v == Py_None) { + objc = i; + break; + } + objv[i] = AsObj(v); + if (!objv[i]) { + /* Reset objc, so it attempts to clear + objects only up to i. */ + objc = i; + goto finally; + } + Tcl_IncrRefCount(objv[i]); + } + } + *pobjc = objc; + return objv; finally: - Tkapp_CallDeallocArgs(objv, objStore, objc); - return NULL; + Tkapp_CallDeallocArgs(objv, objStore, objc); + return NULL; } /* Convert the results of a command call into a Python objects. */ @@ -1195,22 +1195,22 @@ static PyObject* Tkapp_CallResult(TkappObject *self) { - PyObject *res = NULL; - if(self->wantobjects) { - Tcl_Obj *value = Tcl_GetObjResult(self->interp); - /* Not sure whether the IncrRef is necessary, but something - may overwrite the interpreter result while we are - converting it. */ - Tcl_IncrRefCount(value); - res = FromObj((PyObject*)self, value); - Tcl_DecrRefCount(value); - } else { - const char *s = Tcl_GetStringResult(self->interp); - const char *p = s; - - res = PyUnicode_FromStringAndSize(s, (int)(p-s)); - } - return res; + PyObject *res = NULL; + if(self->wantobjects) { + Tcl_Obj *value = Tcl_GetObjResult(self->interp); + /* Not sure whether the IncrRef is necessary, but something + may overwrite the interpreter result while we are + converting it. */ + Tcl_IncrRefCount(value); + res = FromObj((PyObject*)self, value); + Tcl_DecrRefCount(value); + } else { + const char *s = Tcl_GetStringResult(self->interp); + const char *p = s; + + res = PyUnicode_FromStringAndSize(s, (int)(p-s)); + } + return res; } #ifdef WITH_THREAD @@ -1222,41 +1222,41 @@ static int Tkapp_CallProc(Tkapp_CallEvent *e, int flags) { - Tcl_Obj *objStore[ARGSZ]; - Tcl_Obj **objv; - int objc; - int i; - ENTER_PYTHON - objv = Tkapp_CallArgs(e->args, objStore, &objc); - if (!objv) { - PyErr_Fetch(e->exc_type, e->exc_value, e->exc_tb); - *(e->res) = NULL; - } - LEAVE_PYTHON - if (!objv) - goto done; - i = Tcl_EvalObjv(e->self->interp, objc, objv, e->flags); - ENTER_PYTHON - if (i == TCL_ERROR) { - *(e->res) = NULL; - *(e->exc_type) = NULL; - *(e->exc_tb) = NULL; - *(e->exc_value) = PyObject_CallFunction( - Tkinter_TclError, "s", - Tcl_GetStringResult(e->self->interp)); - } - else { - *(e->res) = Tkapp_CallResult(e->self); - } - LEAVE_PYTHON + Tcl_Obj *objStore[ARGSZ]; + Tcl_Obj **objv; + int objc; + int i; + ENTER_PYTHON + objv = Tkapp_CallArgs(e->args, objStore, &objc); + if (!objv) { + PyErr_Fetch(e->exc_type, e->exc_value, e->exc_tb); + *(e->res) = NULL; + } + LEAVE_PYTHON + if (!objv) + goto done; + i = Tcl_EvalObjv(e->self->interp, objc, objv, e->flags); + ENTER_PYTHON + if (i == TCL_ERROR) { + *(e->res) = NULL; + *(e->exc_type) = NULL; + *(e->exc_tb) = NULL; + *(e->exc_value) = PyObject_CallFunction( + Tkinter_TclError, "s", + Tcl_GetStringResult(e->self->interp)); + } + else { + *(e->res) = Tkapp_CallResult(e->self); + } + LEAVE_PYTHON - Tkapp_CallDeallocArgs(objv, objStore, objc); + Tkapp_CallDeallocArgs(objv, objStore, objc); done: - /* Wake up calling thread. */ - Tcl_MutexLock(&call_mutex); - Tcl_ConditionNotify(e->done); - Tcl_MutexUnlock(&call_mutex); - return 1; + /* Wake up calling thread. */ + Tcl_MutexLock(&call_mutex); + Tcl_ConditionNotify(e->done); + Tcl_MutexUnlock(&call_mutex); + return 1; } #endif @@ -1276,218 +1276,218 @@ static PyObject * Tkapp_Call(PyObject *selfptr, PyObject *args) { - Tcl_Obj *objStore[ARGSZ]; - Tcl_Obj **objv = NULL; - int objc, i; - PyObject *res = NULL; - TkappObject *self = (TkappObject*)selfptr; - int flags = TCL_EVAL_DIRECT | TCL_EVAL_GLOBAL; - - /* If args is a single tuple, replace with contents of tuple */ - if (1 == PyTuple_Size(args)){ - PyObject* item = PyTuple_GetItem(args, 0); - if (PyTuple_Check(item)) - args = item; - } -#ifdef WITH_THREAD - if (self->threaded && self->thread_id != Tcl_GetCurrentThread()) { - /* We cannot call the command directly. Instead, we must - marshal the parameters to the interpreter thread. */ - Tkapp_CallEvent *ev; - Tcl_Condition cond = NULL; - PyObject *exc_type, *exc_value, *exc_tb; - if (!WaitForMainloop(self)) - return NULL; - ev = (Tkapp_CallEvent*)ckalloc(sizeof(Tkapp_CallEvent)); - ev->ev.proc = (Tcl_EventProc*)Tkapp_CallProc; - ev->self = self; - ev->args = args; - ev->res = &res; - ev->exc_type = &exc_type; - ev->exc_value = &exc_value; - ev->exc_tb = &exc_tb; - ev->done = &cond; - - Tkapp_ThreadSend(self, (Tcl_Event*)ev, &cond, &call_mutex); - - if (res == NULL) { - if (exc_type) - PyErr_Restore(exc_type, exc_value, exc_tb); - else - PyErr_SetObject(Tkinter_TclError, exc_value); - } - Tcl_ConditionFinalize(&cond); - } - else -#endif - { - - objv = Tkapp_CallArgs(args, objStore, &objc); - if (!objv) - return NULL; - - ENTER_TCL - - i = Tcl_EvalObjv(self->interp, objc, objv, flags); - - ENTER_OVERLAP - - if (i == TCL_ERROR) - Tkinter_Error(selfptr); - else - res = Tkapp_CallResult(self); - - LEAVE_OVERLAP_TCL - - Tkapp_CallDeallocArgs(objv, objStore, objc); - } - return res; + Tcl_Obj *objStore[ARGSZ]; + Tcl_Obj **objv = NULL; + int objc, i; + PyObject *res = NULL; + TkappObject *self = (TkappObject*)selfptr; + int flags = TCL_EVAL_DIRECT | TCL_EVAL_GLOBAL; + + /* If args is a single tuple, replace with contents of tuple */ + if (1 == PyTuple_Size(args)){ + PyObject* item = PyTuple_GetItem(args, 0); + if (PyTuple_Check(item)) + args = item; + } +#ifdef WITH_THREAD + if (self->threaded && self->thread_id != Tcl_GetCurrentThread()) { + /* We cannot call the command directly. Instead, we must + marshal the parameters to the interpreter thread. */ + Tkapp_CallEvent *ev; + Tcl_Condition cond = NULL; + PyObject *exc_type, *exc_value, *exc_tb; + if (!WaitForMainloop(self)) + return NULL; + ev = (Tkapp_CallEvent*)ckalloc(sizeof(Tkapp_CallEvent)); + ev->ev.proc = (Tcl_EventProc*)Tkapp_CallProc; + ev->self = self; + ev->args = args; + ev->res = &res; + ev->exc_type = &exc_type; + ev->exc_value = &exc_value; + ev->exc_tb = &exc_tb; + ev->done = &cond; + + Tkapp_ThreadSend(self, (Tcl_Event*)ev, &cond, &call_mutex); + + if (res == NULL) { + if (exc_type) + PyErr_Restore(exc_type, exc_value, exc_tb); + else + PyErr_SetObject(Tkinter_TclError, exc_value); + } + Tcl_ConditionFinalize(&cond); + } + else +#endif + { + + objv = Tkapp_CallArgs(args, objStore, &objc); + if (!objv) + return NULL; + + ENTER_TCL + + i = Tcl_EvalObjv(self->interp, objc, objv, flags); + + ENTER_OVERLAP + + if (i == TCL_ERROR) + Tkinter_Error(selfptr); + else + res = Tkapp_CallResult(self); + + LEAVE_OVERLAP_TCL + + Tkapp_CallDeallocArgs(objv, objStore, objc); + } + return res; } static PyObject * Tkapp_GlobalCall(PyObject *self, PyObject *args) { - /* Could do the same here as for Tkapp_Call(), but this is not used - much, so I can't be bothered. Unfortunately Tcl doesn't export a - way for the user to do what all its Global* variants do (save and - reset the scope pointer, call the local version, restore the saved - scope pointer). */ - - char *cmd; - PyObject *res = NULL; - - CHECK_TCL_APPARTMENT; - - cmd = Merge(args); - if (cmd) { - int err; - ENTER_TCL - err = Tcl_GlobalEval(Tkapp_Interp(self), cmd); - ENTER_OVERLAP - if (err == TCL_ERROR) - res = Tkinter_Error(self); - else - res = PyUnicode_FromString(Tkapp_Result(self)); - LEAVE_OVERLAP_TCL - ckfree(cmd); - } + /* Could do the same here as for Tkapp_Call(), but this is not used + much, so I can't be bothered. Unfortunately Tcl doesn't export a + way for the user to do what all its Global* variants do (save and + reset the scope pointer, call the local version, restore the saved + scope pointer). */ + + char *cmd; + PyObject *res = NULL; + + CHECK_TCL_APPARTMENT; + + cmd = Merge(args); + if (cmd) { + int err; + ENTER_TCL + err = Tcl_GlobalEval(Tkapp_Interp(self), cmd); + ENTER_OVERLAP + if (err == TCL_ERROR) + res = Tkinter_Error(self); + else + res = PyUnicode_FromString(Tkapp_Result(self)); + LEAVE_OVERLAP_TCL + ckfree(cmd); + } - return res; + return res; } static PyObject * Tkapp_Eval(PyObject *self, PyObject *args) { - char *script; - PyObject *res = NULL; - int err; - - if (!PyArg_ParseTuple(args, "s:eval", &script)) - return NULL; - - CHECK_TCL_APPARTMENT; - - ENTER_TCL - err = Tcl_Eval(Tkapp_Interp(self), script); - ENTER_OVERLAP - if (err == TCL_ERROR) - res = Tkinter_Error(self); - else - res = PyUnicode_FromString(Tkapp_Result(self)); - LEAVE_OVERLAP_TCL - return res; + char *script; + PyObject *res = NULL; + int err; + + if (!PyArg_ParseTuple(args, "s:eval", &script)) + return NULL; + + CHECK_TCL_APPARTMENT; + + ENTER_TCL + err = Tcl_Eval(Tkapp_Interp(self), script); + ENTER_OVERLAP + if (err == TCL_ERROR) + res = Tkinter_Error(self); + else + res = PyUnicode_FromString(Tkapp_Result(self)); + LEAVE_OVERLAP_TCL + return res; } static PyObject * Tkapp_GlobalEval(PyObject *self, PyObject *args) { - char *script; - PyObject *res = NULL; - int err; - - if (!PyArg_ParseTuple(args, "s:globaleval", &script)) - return NULL; - - CHECK_TCL_APPARTMENT; - - ENTER_TCL - err = Tcl_GlobalEval(Tkapp_Interp(self), script); - ENTER_OVERLAP - if (err == TCL_ERROR) - res = Tkinter_Error(self); - else - res = PyUnicode_FromString(Tkapp_Result(self)); - LEAVE_OVERLAP_TCL - return res; + char *script; + PyObject *res = NULL; + int err; + + if (!PyArg_ParseTuple(args, "s:globaleval", &script)) + return NULL; + + CHECK_TCL_APPARTMENT; + + ENTER_TCL + err = Tcl_GlobalEval(Tkapp_Interp(self), script); + ENTER_OVERLAP + if (err == TCL_ERROR) + res = Tkinter_Error(self); + else + res = PyUnicode_FromString(Tkapp_Result(self)); + LEAVE_OVERLAP_TCL + return res; } static PyObject * Tkapp_EvalFile(PyObject *self, PyObject *args) { - char *fileName; - PyObject *res = NULL; - int err; - - if (!PyArg_ParseTuple(args, "s:evalfile", &fileName)) - return NULL; - - CHECK_TCL_APPARTMENT; - - ENTER_TCL - err = Tcl_EvalFile(Tkapp_Interp(self), fileName); - ENTER_OVERLAP - if (err == TCL_ERROR) - res = Tkinter_Error(self); - - else - res = PyUnicode_FromString(Tkapp_Result(self)); - LEAVE_OVERLAP_TCL - return res; + char *fileName; + PyObject *res = NULL; + int err; + + if (!PyArg_ParseTuple(args, "s:evalfile", &fileName)) + return NULL; + + CHECK_TCL_APPARTMENT; + + ENTER_TCL + err = Tcl_EvalFile(Tkapp_Interp(self), fileName); + ENTER_OVERLAP + if (err == TCL_ERROR) + res = Tkinter_Error(self); + + else + res = PyUnicode_FromString(Tkapp_Result(self)); + LEAVE_OVERLAP_TCL + return res; } static PyObject * Tkapp_Record(PyObject *self, PyObject *args) { - char *script; - PyObject *res = NULL; - int err; - - if (!PyArg_ParseTuple(args, "s", &script)) - return NULL; - - CHECK_TCL_APPARTMENT; - - ENTER_TCL - err = Tcl_RecordAndEval(Tkapp_Interp(self), script, TCL_NO_EVAL); - ENTER_OVERLAP - if (err == TCL_ERROR) - res = Tkinter_Error(self); - else - res = PyUnicode_FromString(Tkapp_Result(self)); - LEAVE_OVERLAP_TCL - return res; + char *script; + PyObject *res = NULL; + int err; + + if (!PyArg_ParseTuple(args, "s", &script)) + return NULL; + + CHECK_TCL_APPARTMENT; + + ENTER_TCL + err = Tcl_RecordAndEval(Tkapp_Interp(self), script, TCL_NO_EVAL); + ENTER_OVERLAP + if (err == TCL_ERROR) + res = Tkinter_Error(self); + else + res = PyUnicode_FromString(Tkapp_Result(self)); + LEAVE_OVERLAP_TCL + return res; } static PyObject * Tkapp_AddErrorInfo(PyObject *self, PyObject *args) { - char *msg; - - if (!PyArg_ParseTuple(args, "s:adderrorinfo", &msg)) - return NULL; - CHECK_TCL_APPARTMENT; + char *msg; - ENTER_TCL - Tcl_AddErrorInfo(Tkapp_Interp(self), msg); - LEAVE_TCL + if (!PyArg_ParseTuple(args, "s:adderrorinfo", &msg)) + return NULL; + CHECK_TCL_APPARTMENT; + + ENTER_TCL + Tcl_AddErrorInfo(Tkapp_Interp(self), msg); + LEAVE_TCL - Py_INCREF(Py_None); - return Py_None; + Py_INCREF(Py_None); + return Py_None; } - + /** Tcl Variable **/ typedef PyObject* (*EventFunc)(PyObject*, PyObject *args, int flags); @@ -1496,36 +1496,36 @@ TCL_DECLARE_MUTEX(var_mutex) typedef struct VarEvent { - Tcl_Event ev; /* must be first */ - PyObject *self; - PyObject *args; - int flags; - EventFunc func; - PyObject **res; - PyObject **exc_type; - PyObject **exc_val; - Tcl_Condition *cond; + Tcl_Event ev; /* must be first */ + PyObject *self; + PyObject *args; + int flags; + EventFunc func; + PyObject **res; + PyObject **exc_type; + PyObject **exc_val; + Tcl_Condition *cond; } VarEvent; #endif static int varname_converter(PyObject *in, void *_out) { - char **out = (char**)_out; - if (PyBytes_Check(in)) { - *out = PyBytes_AsString(in); - return 1; - } - if (PyUnicode_Check(in)) { - *out = _PyUnicode_AsString(in); - return 1; - } - if (PyTclObject_Check(in)) { - *out = PyTclObject_TclString(in); - return 1; - } - /* XXX: Should give diagnostics. */ - return 0; + char **out = (char**)_out; + if (PyBytes_Check(in)) { + *out = PyBytes_AsString(in); + return 1; + } + if (PyUnicode_Check(in)) { + *out = _PyUnicode_AsString(in); + return 1; + } + if (PyTclObject_Check(in)) { + *out = PyTclObject_TclString(in); + return 1; + } + /* XXX: Should give diagnostics. */ + return 0; } #ifdef WITH_THREAD @@ -1533,28 +1533,28 @@ static void var_perform(VarEvent *ev) { - *(ev->res) = ev->func(ev->self, ev->args, ev->flags); - if (!*(ev->res)) { - PyObject *exc, *val, *tb; - PyErr_Fetch(&exc, &val, &tb); - PyErr_NormalizeException(&exc, &val, &tb); - *(ev->exc_type) = exc; - *(ev->exc_val) = val; - Py_DECREF(tb); - } + *(ev->res) = ev->func(ev->self, ev->args, ev->flags); + if (!*(ev->res)) { + PyObject *exc, *val, *tb; + PyErr_Fetch(&exc, &val, &tb); + PyErr_NormalizeException(&exc, &val, &tb); + *(ev->exc_type) = exc; + *(ev->exc_val) = val; + Py_DECREF(tb); + } } static int var_proc(VarEvent* ev, int flags) { - ENTER_PYTHON - var_perform(ev); - Tcl_MutexLock(&var_mutex); - Tcl_ConditionNotify(ev->cond); - Tcl_MutexUnlock(&var_mutex); - LEAVE_PYTHON - return 1; + ENTER_PYTHON + var_perform(ev); + Tcl_MutexLock(&var_mutex); + Tcl_ConditionNotify(ev->cond); + Tcl_MutexUnlock(&var_mutex); + LEAVE_PYTHON + return 1; } #endif @@ -1563,439 +1563,439 @@ var_invoke(EventFunc func, PyObject *selfptr, PyObject *args, int flags) { #ifdef WITH_THREAD - TkappObject *self = (TkappObject*)selfptr; - if (self->threaded && self->thread_id != Tcl_GetCurrentThread()) { - TkappObject *self = (TkappObject*)selfptr; - VarEvent *ev; - PyObject *res, *exc_type, *exc_val; - Tcl_Condition cond = NULL; - - /* The current thread is not the interpreter thread. Marshal - the call to the interpreter thread, then wait for - completion. */ - if (!WaitForMainloop(self)) - return NULL; - - ev = (VarEvent*)ckalloc(sizeof(VarEvent)); - - ev->self = selfptr; - ev->args = args; - ev->flags = flags; - ev->func = func; - ev->res = &res; - ev->exc_type = &exc_type; - ev->exc_val = &exc_val; - ev->cond = &cond; - ev->ev.proc = (Tcl_EventProc*)var_proc; - Tkapp_ThreadSend(self, (Tcl_Event*)ev, &cond, &var_mutex); - Tcl_ConditionFinalize(&cond); - if (!res) { - PyErr_SetObject(exc_type, exc_val); - Py_DECREF(exc_type); - Py_DECREF(exc_val); - return NULL; - } - return res; - } + TkappObject *self = (TkappObject*)selfptr; + if (self->threaded && self->thread_id != Tcl_GetCurrentThread()) { + TkappObject *self = (TkappObject*)selfptr; + VarEvent *ev; + PyObject *res, *exc_type, *exc_val; + Tcl_Condition cond = NULL; + + /* The current thread is not the interpreter thread. Marshal + the call to the interpreter thread, then wait for + completion. */ + if (!WaitForMainloop(self)) + return NULL; + + ev = (VarEvent*)ckalloc(sizeof(VarEvent)); + + ev->self = selfptr; + ev->args = args; + ev->flags = flags; + ev->func = func; + ev->res = &res; + ev->exc_type = &exc_type; + ev->exc_val = &exc_val; + ev->cond = &cond; + ev->ev.proc = (Tcl_EventProc*)var_proc; + Tkapp_ThreadSend(self, (Tcl_Event*)ev, &cond, &var_mutex); + Tcl_ConditionFinalize(&cond); + if (!res) { + PyErr_SetObject(exc_type, exc_val); + Py_DECREF(exc_type); + Py_DECREF(exc_val); + return NULL; + } + return res; + } #endif - /* Tcl is not threaded, or this is the interpreter thread. */ - return func(selfptr, args, flags); + /* Tcl is not threaded, or this is the interpreter thread. */ + return func(selfptr, args, flags); } static PyObject * SetVar(PyObject *self, PyObject *args, int flags) { - char *name1, *name2; - PyObject *newValue; - PyObject *res = NULL; - Tcl_Obj *newval, *ok; - - if (PyArg_ParseTuple(args, "O&O:setvar", - varname_converter, &name1, &newValue)) { - /* XXX Acquire tcl lock??? */ - newval = AsObj(newValue); - if (newval == NULL) - return NULL; - ENTER_TCL - ok = Tcl_SetVar2Ex(Tkapp_Interp(self), name1, NULL, - newval, flags); - ENTER_OVERLAP - if (!ok) - Tkinter_Error(self); - else { - res = Py_None; - Py_INCREF(res); - } - LEAVE_OVERLAP_TCL - } - else { - PyErr_Clear(); - if (PyArg_ParseTuple(args, "ssO:setvar", - &name1, &name2, &newValue)) { - /* XXX must hold tcl lock already??? */ - newval = AsObj(newValue); - ENTER_TCL - ok = Tcl_SetVar2Ex(Tkapp_Interp(self), name1, name2, newval, flags); - ENTER_OVERLAP - if (!ok) - Tkinter_Error(self); - else { - res = Py_None; - Py_INCREF(res); - } - LEAVE_OVERLAP_TCL - } - else { - return NULL; - } - } - return res; + char *name1, *name2; + PyObject *newValue; + PyObject *res = NULL; + Tcl_Obj *newval, *ok; + + if (PyArg_ParseTuple(args, "O&O:setvar", + varname_converter, &name1, &newValue)) { + /* XXX Acquire tcl lock??? */ + newval = AsObj(newValue); + if (newval == NULL) + return NULL; + ENTER_TCL + ok = Tcl_SetVar2Ex(Tkapp_Interp(self), name1, NULL, + newval, flags); + ENTER_OVERLAP + if (!ok) + Tkinter_Error(self); + else { + res = Py_None; + Py_INCREF(res); + } + LEAVE_OVERLAP_TCL + } + else { + PyErr_Clear(); + if (PyArg_ParseTuple(args, "ssO:setvar", + &name1, &name2, &newValue)) { + /* XXX must hold tcl lock already??? */ + newval = AsObj(newValue); + ENTER_TCL + ok = Tcl_SetVar2Ex(Tkapp_Interp(self), name1, name2, newval, flags); + ENTER_OVERLAP + if (!ok) + Tkinter_Error(self); + else { + res = Py_None; + Py_INCREF(res); + } + LEAVE_OVERLAP_TCL + } + else { + return NULL; + } + } + return res; } static PyObject * Tkapp_SetVar(PyObject *self, PyObject *args) { - return var_invoke(SetVar, self, args, TCL_LEAVE_ERR_MSG); + return var_invoke(SetVar, self, args, TCL_LEAVE_ERR_MSG); } static PyObject * Tkapp_GlobalSetVar(PyObject *self, PyObject *args) { - return var_invoke(SetVar, self, args, TCL_LEAVE_ERR_MSG | TCL_GLOBAL_ONLY); + return var_invoke(SetVar, self, args, TCL_LEAVE_ERR_MSG | TCL_GLOBAL_ONLY); } - + static PyObject * GetVar(PyObject *self, PyObject *args, int flags) { - char *name1, *name2=NULL; - PyObject *res = NULL; - Tcl_Obj *tres; - - if (!PyArg_ParseTuple(args, "O&|s:getvar", - varname_converter, &name1, &name2)) - return NULL; - - ENTER_TCL - tres = Tcl_GetVar2Ex(Tkapp_Interp(self), name1, name2, flags); - ENTER_OVERLAP - if (tres == NULL) { - PyErr_SetString(Tkinter_TclError, Tcl_GetStringResult(Tkapp_Interp(self))); - } else { - if (((TkappObject*)self)->wantobjects) { - res = FromObj(self, tres); - } - else { - res = PyUnicode_FromString(Tcl_GetString(tres)); - } - } - LEAVE_OVERLAP_TCL - return res; + char *name1, *name2=NULL; + PyObject *res = NULL; + Tcl_Obj *tres; + + if (!PyArg_ParseTuple(args, "O&|s:getvar", + varname_converter, &name1, &name2)) + return NULL; + + ENTER_TCL + tres = Tcl_GetVar2Ex(Tkapp_Interp(self), name1, name2, flags); + ENTER_OVERLAP + if (tres == NULL) { + PyErr_SetString(Tkinter_TclError, Tcl_GetStringResult(Tkapp_Interp(self))); + } else { + if (((TkappObject*)self)->wantobjects) { + res = FromObj(self, tres); + } + else { + res = PyUnicode_FromString(Tcl_GetString(tres)); + } + } + LEAVE_OVERLAP_TCL + return res; } static PyObject * Tkapp_GetVar(PyObject *self, PyObject *args) { - return var_invoke(GetVar, self, args, TCL_LEAVE_ERR_MSG); + return var_invoke(GetVar, self, args, TCL_LEAVE_ERR_MSG); } static PyObject * Tkapp_GlobalGetVar(PyObject *self, PyObject *args) { - return var_invoke(GetVar, self, args, TCL_LEAVE_ERR_MSG | TCL_GLOBAL_ONLY); + return var_invoke(GetVar, self, args, TCL_LEAVE_ERR_MSG | TCL_GLOBAL_ONLY); } - + static PyObject * UnsetVar(PyObject *self, PyObject *args, int flags) { - char *name1, *name2=NULL; - int code; - PyObject *res = NULL; - - if (!PyArg_ParseTuple(args, "s|s:unsetvar", &name1, &name2)) - return NULL; - - ENTER_TCL - code = Tcl_UnsetVar2(Tkapp_Interp(self), name1, name2, flags); - ENTER_OVERLAP - if (code == TCL_ERROR) - res = Tkinter_Error(self); - else { - Py_INCREF(Py_None); - res = Py_None; - } - LEAVE_OVERLAP_TCL - return res; + char *name1, *name2=NULL; + int code; + PyObject *res = NULL; + + if (!PyArg_ParseTuple(args, "s|s:unsetvar", &name1, &name2)) + return NULL; + + ENTER_TCL + code = Tcl_UnsetVar2(Tkapp_Interp(self), name1, name2, flags); + ENTER_OVERLAP + if (code == TCL_ERROR) + res = Tkinter_Error(self); + else { + Py_INCREF(Py_None); + res = Py_None; + } + LEAVE_OVERLAP_TCL + return res; } static PyObject * Tkapp_UnsetVar(PyObject *self, PyObject *args) { - return var_invoke(UnsetVar, self, args, TCL_LEAVE_ERR_MSG); + return var_invoke(UnsetVar, self, args, TCL_LEAVE_ERR_MSG); } static PyObject * Tkapp_GlobalUnsetVar(PyObject *self, PyObject *args) { - return var_invoke(UnsetVar, self, args, TCL_LEAVE_ERR_MSG | TCL_GLOBAL_ONLY); + return var_invoke(UnsetVar, self, args, TCL_LEAVE_ERR_MSG | TCL_GLOBAL_ONLY); } - + /** Tcl to Python **/ static PyObject * Tkapp_GetInt(PyObject *self, PyObject *args) { - char *s; - int v; + char *s; + int v; - if (PyTuple_Size(args) == 1) { - PyObject* o = PyTuple_GetItem(args, 0); - if (PyLong_Check(o)) { - Py_INCREF(o); - return o; - } - } - if (!PyArg_ParseTuple(args, "s:getint", &s)) - return NULL; - if (Tcl_GetInt(Tkapp_Interp(self), s, &v) == TCL_ERROR) - return Tkinter_Error(self); - return Py_BuildValue("i", v); + if (PyTuple_Size(args) == 1) { + PyObject* o = PyTuple_GetItem(args, 0); + if (PyLong_Check(o)) { + Py_INCREF(o); + return o; + } + } + if (!PyArg_ParseTuple(args, "s:getint", &s)) + return NULL; + if (Tcl_GetInt(Tkapp_Interp(self), s, &v) == TCL_ERROR) + return Tkinter_Error(self); + return Py_BuildValue("i", v); } static PyObject * Tkapp_GetDouble(PyObject *self, PyObject *args) { - char *s; - double v; + char *s; + double v; - if (PyTuple_Size(args) == 1) { - PyObject *o = PyTuple_GetItem(args, 0); - if (PyFloat_Check(o)) { - Py_INCREF(o); - return o; - } - } - if (!PyArg_ParseTuple(args, "s:getdouble", &s)) - return NULL; - if (Tcl_GetDouble(Tkapp_Interp(self), s, &v) == TCL_ERROR) - return Tkinter_Error(self); - return Py_BuildValue("d", v); + if (PyTuple_Size(args) == 1) { + PyObject *o = PyTuple_GetItem(args, 0); + if (PyFloat_Check(o)) { + Py_INCREF(o); + return o; + } + } + if (!PyArg_ParseTuple(args, "s:getdouble", &s)) + return NULL; + if (Tcl_GetDouble(Tkapp_Interp(self), s, &v) == TCL_ERROR) + return Tkinter_Error(self); + return Py_BuildValue("d", v); } static PyObject * Tkapp_GetBoolean(PyObject *self, PyObject *args) { - char *s; - int v; + char *s; + int v; - if (PyTuple_Size(args) == 1) { - PyObject *o = PyTuple_GetItem(args, 0); - if (PyLong_Check(o)) { - Py_INCREF(o); - return o; - } - } - if (!PyArg_ParseTuple(args, "s:getboolean", &s)) - return NULL; - if (Tcl_GetBoolean(Tkapp_Interp(self), s, &v) == TCL_ERROR) - return Tkinter_Error(self); - return PyBool_FromLong(v); + if (PyTuple_Size(args) == 1) { + PyObject *o = PyTuple_GetItem(args, 0); + if (PyLong_Check(o)) { + Py_INCREF(o); + return o; + } + } + if (!PyArg_ParseTuple(args, "s:getboolean", &s)) + return NULL; + if (Tcl_GetBoolean(Tkapp_Interp(self), s, &v) == TCL_ERROR) + return Tkinter_Error(self); + return PyBool_FromLong(v); } static PyObject * Tkapp_ExprString(PyObject *self, PyObject *args) { - char *s; - PyObject *res = NULL; - int retval; - - if (!PyArg_ParseTuple(args, "s:exprstring", &s)) - return NULL; - - CHECK_TCL_APPARTMENT; - - ENTER_TCL - retval = Tcl_ExprString(Tkapp_Interp(self), s); - ENTER_OVERLAP - if (retval == TCL_ERROR) - res = Tkinter_Error(self); - else - res = Py_BuildValue("s", Tkapp_Result(self)); - LEAVE_OVERLAP_TCL - return res; + char *s; + PyObject *res = NULL; + int retval; + + if (!PyArg_ParseTuple(args, "s:exprstring", &s)) + return NULL; + + CHECK_TCL_APPARTMENT; + + ENTER_TCL + retval = Tcl_ExprString(Tkapp_Interp(self), s); + ENTER_OVERLAP + if (retval == TCL_ERROR) + res = Tkinter_Error(self); + else + res = Py_BuildValue("s", Tkapp_Result(self)); + LEAVE_OVERLAP_TCL + return res; } static PyObject * Tkapp_ExprLong(PyObject *self, PyObject *args) { - char *s; - PyObject *res = NULL; - int retval; - long v; - - if (!PyArg_ParseTuple(args, "s:exprlong", &s)) - return NULL; - - CHECK_TCL_APPARTMENT; - - ENTER_TCL - retval = Tcl_ExprLong(Tkapp_Interp(self), s, &v); - ENTER_OVERLAP - if (retval == TCL_ERROR) - res = Tkinter_Error(self); - else - res = Py_BuildValue("l", v); - LEAVE_OVERLAP_TCL - return res; + char *s; + PyObject *res = NULL; + int retval; + long v; + + if (!PyArg_ParseTuple(args, "s:exprlong", &s)) + return NULL; + + CHECK_TCL_APPARTMENT; + + ENTER_TCL + retval = Tcl_ExprLong(Tkapp_Interp(self), s, &v); + ENTER_OVERLAP + if (retval == TCL_ERROR) + res = Tkinter_Error(self); + else + res = Py_BuildValue("l", v); + LEAVE_OVERLAP_TCL + return res; } static PyObject * Tkapp_ExprDouble(PyObject *self, PyObject *args) { - char *s; - PyObject *res = NULL; - double v; - int retval; - - if (!PyArg_ParseTuple(args, "s:exprdouble", &s)) - return NULL; - CHECK_TCL_APPARTMENT; - PyFPE_START_PROTECT("Tkapp_ExprDouble", return 0) - ENTER_TCL - retval = Tcl_ExprDouble(Tkapp_Interp(self), s, &v); - ENTER_OVERLAP - PyFPE_END_PROTECT(retval) - if (retval == TCL_ERROR) - res = Tkinter_Error(self); - else - res = Py_BuildValue("d", v); - LEAVE_OVERLAP_TCL - return res; + char *s; + PyObject *res = NULL; + double v; + int retval; + + if (!PyArg_ParseTuple(args, "s:exprdouble", &s)) + return NULL; + CHECK_TCL_APPARTMENT; + PyFPE_START_PROTECT("Tkapp_ExprDouble", return 0) + ENTER_TCL + retval = Tcl_ExprDouble(Tkapp_Interp(self), s, &v); + ENTER_OVERLAP + PyFPE_END_PROTECT(retval) + if (retval == TCL_ERROR) + res = Tkinter_Error(self); + else + res = Py_BuildValue("d", v); + LEAVE_OVERLAP_TCL + return res; } static PyObject * Tkapp_ExprBoolean(PyObject *self, PyObject *args) { - char *s; - PyObject *res = NULL; - int retval; - int v; - - if (!PyArg_ParseTuple(args, "s:exprboolean", &s)) - return NULL; - CHECK_TCL_APPARTMENT; - ENTER_TCL - retval = Tcl_ExprBoolean(Tkapp_Interp(self), s, &v); - ENTER_OVERLAP - if (retval == TCL_ERROR) - res = Tkinter_Error(self); - else - res = Py_BuildValue("i", v); - LEAVE_OVERLAP_TCL - return res; + char *s; + PyObject *res = NULL; + int retval; + int v; + + if (!PyArg_ParseTuple(args, "s:exprboolean", &s)) + return NULL; + CHECK_TCL_APPARTMENT; + ENTER_TCL + retval = Tcl_ExprBoolean(Tkapp_Interp(self), s, &v); + ENTER_OVERLAP + if (retval == TCL_ERROR) + res = Tkinter_Error(self); + else + res = Py_BuildValue("i", v); + LEAVE_OVERLAP_TCL + return res; } - + static PyObject * Tkapp_SplitList(PyObject *self, PyObject *args) { - char *list; - int argc; - char **argv; - PyObject *v; - int i; - - if (PyTuple_Size(args) == 1) { - v = PyTuple_GetItem(args, 0); - if (PyTuple_Check(v)) { - Py_INCREF(v); - return v; - } - } - if (!PyArg_ParseTuple(args, "et:splitlist", "utf-8", &list)) - return NULL; - - if (Tcl_SplitList(Tkapp_Interp(self), list, - &argc, &argv) == TCL_ERROR) { - PyMem_Free(list); - return Tkinter_Error(self); - } - - if (!(v = PyTuple_New(argc))) - goto finally; - - for (i = 0; i < argc; i++) { - PyObject *s = PyUnicode_FromString(argv[i]); - if (!s || PyTuple_SetItem(v, i, s)) { - Py_DECREF(v); - v = NULL; - goto finally; - } - } + char *list; + int argc; + char **argv; + PyObject *v; + int i; + + if (PyTuple_Size(args) == 1) { + v = PyTuple_GetItem(args, 0); + if (PyTuple_Check(v)) { + Py_INCREF(v); + return v; + } + } + if (!PyArg_ParseTuple(args, "et:splitlist", "utf-8", &list)) + return NULL; + + if (Tcl_SplitList(Tkapp_Interp(self), list, + &argc, &argv) == TCL_ERROR) { + PyMem_Free(list); + return Tkinter_Error(self); + } + + if (!(v = PyTuple_New(argc))) + goto finally; + + for (i = 0; i < argc; i++) { + PyObject *s = PyUnicode_FromString(argv[i]); + if (!s || PyTuple_SetItem(v, i, s)) { + Py_DECREF(v); + v = NULL; + goto finally; + } + } finally: - ckfree(FREECAST argv); - PyMem_Free(list); - return v; + ckfree(FREECAST argv); + PyMem_Free(list); + return v; } static PyObject * Tkapp_Split(PyObject *self, PyObject *args) { - PyObject *v; - char *list; + PyObject *v; + char *list; - if (PyTuple_Size(args) == 1) { - PyObject* o = PyTuple_GetItem(args, 0); - if (PyTuple_Check(o)) { - o = SplitObj(o); - return o; - } - } - if (!PyArg_ParseTuple(args, "et:split", "utf-8", &list)) - return NULL; - v = Split(list); - PyMem_Free(list); - return v; + if (PyTuple_Size(args) == 1) { + PyObject* o = PyTuple_GetItem(args, 0); + if (PyTuple_Check(o)) { + o = SplitObj(o); + return o; + } + } + if (!PyArg_ParseTuple(args, "et:split", "utf-8", &list)) + return NULL; + v = Split(list); + PyMem_Free(list); + return v; } static PyObject * Tkapp_Merge(PyObject *self, PyObject *args) { - char *s = Merge(args); - PyObject *res = NULL; + char *s = Merge(args); + PyObject *res = NULL; - if (s) { - res = PyUnicode_FromString(s); - ckfree(s); - } + if (s) { + res = PyUnicode_FromString(s); + ckfree(s); + } - return res; + return res; } - + /** Tcl Command **/ /* Client data struct */ typedef struct { - PyObject *self; - PyObject *func; + PyObject *self; + PyObject *func; } PythonCmd_ClientData; static int PythonCmd_Error(Tcl_Interp *interp) { - errorInCmd = 1; - PyErr_Fetch(&excInCmd, &valInCmd, &trbInCmd); - LEAVE_PYTHON - return TCL_ERROR; + errorInCmd = 1; + PyErr_Fetch(&excInCmd, &valInCmd, &trbInCmd); + LEAVE_PYTHON + return TCL_ERROR; } /* This is the Tcl command that acts as a wrapper for Python @@ -2004,211 +2004,211 @@ static int PythonCmd(ClientData clientData, Tcl_Interp *interp, int argc, char *argv[]) { - PythonCmd_ClientData *data = (PythonCmd_ClientData *)clientData; - PyObject *self, *func, *arg, *res; - int i, rv; - Tcl_Obj *obj_res; - - ENTER_PYTHON - - /* TBD: no error checking here since we know, via the - * Tkapp_CreateCommand() that the client data is a two-tuple - */ - self = data->self; - func = data->func; - - /* Create argument list (argv1, ..., argvN) */ - if (!(arg = PyTuple_New(argc - 1))) - return PythonCmd_Error(interp); - - for (i = 0; i < (argc - 1); i++) { - PyObject *s = PyUnicode_FromString(argv[i + 1]); - if (!s || PyTuple_SetItem(arg, i, s)) { - Py_DECREF(arg); - return PythonCmd_Error(interp); - } - } - res = PyEval_CallObject(func, arg); - Py_DECREF(arg); - - if (res == NULL) - return PythonCmd_Error(interp); - - obj_res = AsObj(res); - if (obj_res == NULL) { - Py_DECREF(res); - return PythonCmd_Error(interp); - } - else { - Tcl_SetObjResult(interp, obj_res); - rv = TCL_OK; - } + PythonCmd_ClientData *data = (PythonCmd_ClientData *)clientData; + PyObject *self, *func, *arg, *res; + int i, rv; + Tcl_Obj *obj_res; + + ENTER_PYTHON + + /* TBD: no error checking here since we know, via the + * Tkapp_CreateCommand() that the client data is a two-tuple + */ + self = data->self; + func = data->func; + + /* Create argument list (argv1, ..., argvN) */ + if (!(arg = PyTuple_New(argc - 1))) + return PythonCmd_Error(interp); + + for (i = 0; i < (argc - 1); i++) { + PyObject *s = PyUnicode_FromString(argv[i + 1]); + if (!s || PyTuple_SetItem(arg, i, s)) { + Py_DECREF(arg); + return PythonCmd_Error(interp); + } + } + res = PyEval_CallObject(func, arg); + Py_DECREF(arg); + + if (res == NULL) + return PythonCmd_Error(interp); + + obj_res = AsObj(res); + if (obj_res == NULL) { + Py_DECREF(res); + return PythonCmd_Error(interp); + } + else { + Tcl_SetObjResult(interp, obj_res); + rv = TCL_OK; + } - Py_DECREF(res); + Py_DECREF(res); - LEAVE_PYTHON + LEAVE_PYTHON - return rv; + return rv; } static void PythonCmdDelete(ClientData clientData) { - PythonCmd_ClientData *data = (PythonCmd_ClientData *)clientData; + PythonCmd_ClientData *data = (PythonCmd_ClientData *)clientData; - ENTER_PYTHON - Py_XDECREF(data->self); - Py_XDECREF(data->func); - PyMem_DEL(data); - LEAVE_PYTHON + ENTER_PYTHON + Py_XDECREF(data->self); + Py_XDECREF(data->func); + PyMem_DEL(data); + LEAVE_PYTHON } - + #ifdef WITH_THREAD TCL_DECLARE_MUTEX(command_mutex) typedef struct CommandEvent{ - Tcl_Event ev; - Tcl_Interp* interp; - char *name; - int create; - int *status; - ClientData *data; - Tcl_Condition *done; + Tcl_Event ev; + Tcl_Interp* interp; + char *name; + int create; + int *status; + ClientData *data; + Tcl_Condition *done; } CommandEvent; static int Tkapp_CommandProc(CommandEvent *ev, int flags) { - if (ev->create) - *ev->status = Tcl_CreateCommand( - ev->interp, ev->name, PythonCmd, - ev->data, PythonCmdDelete) == NULL; - else - *ev->status = Tcl_DeleteCommand(ev->interp, ev->name); - Tcl_MutexLock(&command_mutex); - Tcl_ConditionNotify(ev->done); - Tcl_MutexUnlock(&command_mutex); - return 1; + if (ev->create) + *ev->status = Tcl_CreateCommand( + ev->interp, ev->name, PythonCmd, + ev->data, PythonCmdDelete) == NULL; + else + *ev->status = Tcl_DeleteCommand(ev->interp, ev->name); + Tcl_MutexLock(&command_mutex); + Tcl_ConditionNotify(ev->done); + Tcl_MutexUnlock(&command_mutex); + return 1; } #endif static PyObject * Tkapp_CreateCommand(PyObject *selfptr, PyObject *args) { - TkappObject *self = (TkappObject*)selfptr; - PythonCmd_ClientData *data; - char *cmdName; - PyObject *func; - int err; - - if (!PyArg_ParseTuple(args, "sO:createcommand", &cmdName, &func)) - return NULL; - if (!PyCallable_Check(func)) { - PyErr_SetString(PyExc_TypeError, "command not callable"); - return NULL; - } - -#ifdef WITH_THREAD - if (self->threaded && self->thread_id != Tcl_GetCurrentThread() && - !WaitForMainloop(self)) - return NULL; -#endif - - data = PyMem_NEW(PythonCmd_ClientData, 1); - if (!data) - return PyErr_NoMemory(); - Py_INCREF(self); - Py_INCREF(func); - data->self = selfptr; - data->func = func; -#ifdef WITH_THREAD - if (self->threaded && self->thread_id != Tcl_GetCurrentThread()) { - Tcl_Condition cond = NULL; - CommandEvent *ev = (CommandEvent*)ckalloc(sizeof(CommandEvent)); - ev->ev.proc = (Tcl_EventProc*)Tkapp_CommandProc; - ev->interp = self->interp; - ev->create = 1; - ev->name = cmdName; - ev->data = (ClientData)data; - ev->status = &err; - ev->done = &cond; - Tkapp_ThreadSend(self, (Tcl_Event*)ev, &cond, &command_mutex); - Tcl_ConditionFinalize(&cond); - } - else -#endif - { - ENTER_TCL - err = Tcl_CreateCommand( - Tkapp_Interp(self), cmdName, PythonCmd, - (ClientData)data, PythonCmdDelete) == NULL; - LEAVE_TCL - } - if (err) { - PyErr_SetString(Tkinter_TclError, "can't create Tcl command"); - PyMem_DEL(data); - return NULL; - } + TkappObject *self = (TkappObject*)selfptr; + PythonCmd_ClientData *data; + char *cmdName; + PyObject *func; + int err; + + if (!PyArg_ParseTuple(args, "sO:createcommand", &cmdName, &func)) + return NULL; + if (!PyCallable_Check(func)) { + PyErr_SetString(PyExc_TypeError, "command not callable"); + return NULL; + } + +#ifdef WITH_THREAD + if (self->threaded && self->thread_id != Tcl_GetCurrentThread() && + !WaitForMainloop(self)) + return NULL; +#endif + + data = PyMem_NEW(PythonCmd_ClientData, 1); + if (!data) + return PyErr_NoMemory(); + Py_INCREF(self); + Py_INCREF(func); + data->self = selfptr; + data->func = func; +#ifdef WITH_THREAD + if (self->threaded && self->thread_id != Tcl_GetCurrentThread()) { + Tcl_Condition cond = NULL; + CommandEvent *ev = (CommandEvent*)ckalloc(sizeof(CommandEvent)); + ev->ev.proc = (Tcl_EventProc*)Tkapp_CommandProc; + ev->interp = self->interp; + ev->create = 1; + ev->name = cmdName; + ev->data = (ClientData)data; + ev->status = &err; + ev->done = &cond; + Tkapp_ThreadSend(self, (Tcl_Event*)ev, &cond, &command_mutex); + Tcl_ConditionFinalize(&cond); + } + else +#endif + { + ENTER_TCL + err = Tcl_CreateCommand( + Tkapp_Interp(self), cmdName, PythonCmd, + (ClientData)data, PythonCmdDelete) == NULL; + LEAVE_TCL + } + if (err) { + PyErr_SetString(Tkinter_TclError, "can't create Tcl command"); + PyMem_DEL(data); + return NULL; + } - Py_INCREF(Py_None); - return Py_None; + Py_INCREF(Py_None); + return Py_None; } - + static PyObject * Tkapp_DeleteCommand(PyObject *selfptr, PyObject *args) { - TkappObject *self = (TkappObject*)selfptr; - char *cmdName; - int err; - - if (!PyArg_ParseTuple(args, "s:deletecommand", &cmdName)) - return NULL; - -#ifdef WITH_THREAD - if (self->threaded && self->thread_id != Tcl_GetCurrentThread()) { - Tcl_Condition cond = NULL; - CommandEvent *ev; - ev = (CommandEvent*)ckalloc(sizeof(CommandEvent)); - ev->ev.proc = (Tcl_EventProc*)Tkapp_CommandProc; - ev->interp = self->interp; - ev->create = 0; - ev->name = cmdName; - ev->status = &err; - ev->done = &cond; - Tkapp_ThreadSend(self, (Tcl_Event*)ev, &cond, - &command_mutex); - Tcl_ConditionFinalize(&cond); - } - else -#endif - { - ENTER_TCL - err = Tcl_DeleteCommand(self->interp, cmdName); - LEAVE_TCL - } - if (err == -1) { - PyErr_SetString(Tkinter_TclError, "can't delete Tcl command"); - return NULL; - } - Py_INCREF(Py_None); - return Py_None; + TkappObject *self = (TkappObject*)selfptr; + char *cmdName; + int err; + + if (!PyArg_ParseTuple(args, "s:deletecommand", &cmdName)) + return NULL; + +#ifdef WITH_THREAD + if (self->threaded && self->thread_id != Tcl_GetCurrentThread()) { + Tcl_Condition cond = NULL; + CommandEvent *ev; + ev = (CommandEvent*)ckalloc(sizeof(CommandEvent)); + ev->ev.proc = (Tcl_EventProc*)Tkapp_CommandProc; + ev->interp = self->interp; + ev->create = 0; + ev->name = cmdName; + ev->status = &err; + ev->done = &cond; + Tkapp_ThreadSend(self, (Tcl_Event*)ev, &cond, + &command_mutex); + Tcl_ConditionFinalize(&cond); + } + else +#endif + { + ENTER_TCL + err = Tcl_DeleteCommand(self->interp, cmdName); + LEAVE_TCL + } + if (err == -1) { + PyErr_SetString(Tkinter_TclError, "can't delete Tcl command"); + return NULL; + } + Py_INCREF(Py_None); + return Py_None; } - + #ifdef HAVE_CREATEFILEHANDLER /** File Handler **/ typedef struct _fhcdata { - PyObject *func; - PyObject *file; - int id; - struct _fhcdata *next; + PyObject *func; + PyObject *file; + int id; + struct _fhcdata *next; } FileHandler_ClientData; static FileHandler_ClientData *HeadFHCD; @@ -2216,712 +2216,712 @@ static FileHandler_ClientData * NewFHCD(PyObject *func, PyObject *file, int id) { - FileHandler_ClientData *p; - p = PyMem_NEW(FileHandler_ClientData, 1); - if (p != NULL) { - Py_XINCREF(func); - Py_XINCREF(file); - p->func = func; - p->file = file; - p->id = id; - p->next = HeadFHCD; - HeadFHCD = p; - } - return p; + FileHandler_ClientData *p; + p = PyMem_NEW(FileHandler_ClientData, 1); + if (p != NULL) { + Py_XINCREF(func); + Py_XINCREF(file); + p->func = func; + p->file = file; + p->id = id; + p->next = HeadFHCD; + HeadFHCD = p; + } + return p; } static void DeleteFHCD(int id) { - FileHandler_ClientData *p, **pp; + FileHandler_ClientData *p, **pp; - pp = &HeadFHCD; - while ((p = *pp) != NULL) { - if (p->id == id) { - *pp = p->next; - Py_XDECREF(p->func); - Py_XDECREF(p->file); - PyMem_DEL(p); - } - else - pp = &p->next; - } + pp = &HeadFHCD; + while ((p = *pp) != NULL) { + if (p->id == id) { + *pp = p->next; + Py_XDECREF(p->func); + Py_XDECREF(p->file); + PyMem_DEL(p); + } + else + pp = &p->next; + } } static void FileHandler(ClientData clientData, int mask) { - FileHandler_ClientData *data = (FileHandler_ClientData *)clientData; - PyObject *func, *file, *arg, *res; + FileHandler_ClientData *data = (FileHandler_ClientData *)clientData; + PyObject *func, *file, *arg, *res; - ENTER_PYTHON - func = data->func; - file = data->file; - - arg = Py_BuildValue("(Oi)", file, (long) mask); - res = PyEval_CallObject(func, arg); - Py_DECREF(arg); - - if (res == NULL) { - errorInCmd = 1; - PyErr_Fetch(&excInCmd, &valInCmd, &trbInCmd); - } - Py_XDECREF(res); - LEAVE_PYTHON + ENTER_PYTHON + func = data->func; + file = data->file; + + arg = Py_BuildValue("(Oi)", file, (long) mask); + res = PyEval_CallObject(func, arg); + Py_DECREF(arg); + + if (res == NULL) { + errorInCmd = 1; + PyErr_Fetch(&excInCmd, &valInCmd, &trbInCmd); + } + Py_XDECREF(res); + LEAVE_PYTHON } static PyObject * Tkapp_CreateFileHandler(PyObject *self, PyObject *args) /* args is (file, mask, func) */ { - FileHandler_ClientData *data; - PyObject *file, *func; - int mask, tfile; - - if (!PyArg_ParseTuple(args, "OiO:createfilehandler", - &file, &mask, &func)) - return NULL; - - CHECK_TCL_APPARTMENT; - - tfile = PyObject_AsFileDescriptor(file); - if (tfile < 0) - return NULL; - if (!PyCallable_Check(func)) { - PyErr_SetString(PyExc_TypeError, "bad argument list"); - return NULL; - } - - data = NewFHCD(func, file, tfile); - if (data == NULL) - return NULL; - - /* Ought to check for null Tcl_File object... */ - ENTER_TCL - Tcl_CreateFileHandler(tfile, mask, FileHandler, (ClientData) data); - LEAVE_TCL - Py_INCREF(Py_None); - return Py_None; + FileHandler_ClientData *data; + PyObject *file, *func; + int mask, tfile; + + if (!PyArg_ParseTuple(args, "OiO:createfilehandler", + &file, &mask, &func)) + return NULL; + + CHECK_TCL_APPARTMENT; + + tfile = PyObject_AsFileDescriptor(file); + if (tfile < 0) + return NULL; + if (!PyCallable_Check(func)) { + PyErr_SetString(PyExc_TypeError, "bad argument list"); + return NULL; + } + + data = NewFHCD(func, file, tfile); + if (data == NULL) + return NULL; + + /* Ought to check for null Tcl_File object... */ + ENTER_TCL + Tcl_CreateFileHandler(tfile, mask, FileHandler, (ClientData) data); + LEAVE_TCL + Py_INCREF(Py_None); + return Py_None; } static PyObject * Tkapp_DeleteFileHandler(PyObject *self, PyObject *args) { - PyObject *file; - int tfile; + PyObject *file; + int tfile; - if (!PyArg_ParseTuple(args, "O:deletefilehandler", &file)) - return NULL; + if (!PyArg_ParseTuple(args, "O:deletefilehandler", &file)) + return NULL; - CHECK_TCL_APPARTMENT; + CHECK_TCL_APPARTMENT; - tfile = PyObject_AsFileDescriptor(file); - if (tfile < 0) - return NULL; - - DeleteFHCD(tfile); - - /* Ought to check for null Tcl_File object... */ - ENTER_TCL - Tcl_DeleteFileHandler(tfile); - LEAVE_TCL - Py_INCREF(Py_None); - return Py_None; + tfile = PyObject_AsFileDescriptor(file); + if (tfile < 0) + return NULL; + + DeleteFHCD(tfile); + + /* Ought to check for null Tcl_File object... */ + ENTER_TCL + Tcl_DeleteFileHandler(tfile); + LEAVE_TCL + Py_INCREF(Py_None); + return Py_None; } #endif /* HAVE_CREATEFILEHANDLER */ - + /**** Tktt Object (timer token) ****/ static PyTypeObject Tktt_Type; typedef struct { - PyObject_HEAD - Tcl_TimerToken token; - PyObject *func; + PyObject_HEAD + Tcl_TimerToken token; + PyObject *func; } TkttObject; static PyObject * Tktt_DeleteTimerHandler(PyObject *self, PyObject *args) { - TkttObject *v = (TkttObject *)self; - PyObject *func = v->func; + TkttObject *v = (TkttObject *)self; + PyObject *func = v->func; - if (!PyArg_ParseTuple(args, ":deletetimerhandler")) - return NULL; - if (v->token != NULL) { - Tcl_DeleteTimerHandler(v->token); - v->token = NULL; - } - if (func != NULL) { - v->func = NULL; - Py_DECREF(func); - Py_DECREF(v); /* See Tktt_New() */ - } - Py_INCREF(Py_None); - return Py_None; + if (!PyArg_ParseTuple(args, ":deletetimerhandler")) + return NULL; + if (v->token != NULL) { + Tcl_DeleteTimerHandler(v->token); + v->token = NULL; + } + if (func != NULL) { + v->func = NULL; + Py_DECREF(func); + Py_DECREF(v); /* See Tktt_New() */ + } + Py_INCREF(Py_None); + return Py_None; } static PyMethodDef Tktt_methods[] = { - {"deletetimerhandler", Tktt_DeleteTimerHandler, METH_VARARGS}, - {NULL, NULL} + {"deletetimerhandler", Tktt_DeleteTimerHandler, METH_VARARGS}, + {NULL, NULL} }; static TkttObject * Tktt_New(PyObject *func) { - TkttObject *v; + TkttObject *v; - v = PyObject_New(TkttObject, &Tktt_Type); - if (v == NULL) - return NULL; - - Py_INCREF(func); - v->token = NULL; - v->func = func; - - /* Extra reference, deleted when called or when handler is deleted */ - Py_INCREF(v); - return v; + v = PyObject_New(TkttObject, &Tktt_Type); + if (v == NULL) + return NULL; + + Py_INCREF(func); + v->token = NULL; + v->func = func; + + /* Extra reference, deleted when called or when handler is deleted */ + Py_INCREF(v); + return v; } static void Tktt_Dealloc(PyObject *self) { - TkttObject *v = (TkttObject *)self; - PyObject *func = v->func; + TkttObject *v = (TkttObject *)self; + PyObject *func = v->func; - Py_XDECREF(func); + Py_XDECREF(func); - PyObject_Del(self); + PyObject_Del(self); } static PyObject * Tktt_Repr(PyObject *self) { - TkttObject *v = (TkttObject *)self; - char buf[100]; + TkttObject *v = (TkttObject *)self; + char buf[100]; - PyOS_snprintf(buf, sizeof(buf), "", v, - v->func == NULL ? ", handler deleted" : ""); - return PyUnicode_FromString(buf); + PyOS_snprintf(buf, sizeof(buf), "", v, + v->func == NULL ? ", handler deleted" : ""); + return PyUnicode_FromString(buf); } static PyTypeObject Tktt_Type = { - PyVarObject_HEAD_INIT(NULL, 0) - "tktimertoken", /*tp_name */ - sizeof(TkttObject), /*tp_basicsize */ - 0, /*tp_itemsize */ - Tktt_Dealloc, /*tp_dealloc */ - 0, /*tp_print */ - 0, /*tp_getattr */ - 0, /*tp_setattr */ - 0, /*tp_reserved */ - Tktt_Repr, /*tp_repr */ - 0, /*tp_as_number */ - 0, /*tp_as_sequence */ - 0, /*tp_as_mapping */ - 0, /*tp_hash */ - 0, /*tp_call*/ - 0, /*tp_str*/ - 0, /*tp_getattro*/ - 0, /*tp_setattro*/ - 0, /*tp_as_buffer*/ - Py_TPFLAGS_DEFAULT, /*tp_flags*/ - 0, /*tp_doc*/ - 0, /*tp_traverse*/ - 0, /*tp_clear*/ - 0, /*tp_richcompare*/ - 0, /*tp_weaklistoffset*/ - 0, /*tp_iter*/ - 0, /*tp_iternext*/ - Tktt_methods, /*tp_methods*/ + PyVarObject_HEAD_INIT(NULL, 0) + "tktimertoken", /*tp_name */ + sizeof(TkttObject), /*tp_basicsize */ + 0, /*tp_itemsize */ + Tktt_Dealloc, /*tp_dealloc */ + 0, /*tp_print */ + 0, /*tp_getattr */ + 0, /*tp_setattr */ + 0, /*tp_reserved */ + Tktt_Repr, /*tp_repr */ + 0, /*tp_as_number */ + 0, /*tp_as_sequence */ + 0, /*tp_as_mapping */ + 0, /*tp_hash */ + 0, /*tp_call*/ + 0, /*tp_str*/ + 0, /*tp_getattro*/ + 0, /*tp_setattro*/ + 0, /*tp_as_buffer*/ + Py_TPFLAGS_DEFAULT, /*tp_flags*/ + 0, /*tp_doc*/ + 0, /*tp_traverse*/ + 0, /*tp_clear*/ + 0, /*tp_richcompare*/ + 0, /*tp_weaklistoffset*/ + 0, /*tp_iter*/ + 0, /*tp_iternext*/ + Tktt_methods, /*tp_methods*/ }; - + /** Timer Handler **/ static void TimerHandler(ClientData clientData) { - TkttObject *v = (TkttObject *)clientData; - PyObject *func = v->func; - PyObject *res; + TkttObject *v = (TkttObject *)clientData; + PyObject *func = v->func; + PyObject *res; - if (func == NULL) - return; + if (func == NULL) + return; - v->func = NULL; + v->func = NULL; - ENTER_PYTHON + ENTER_PYTHON - res = PyEval_CallObject(func, NULL); - Py_DECREF(func); - Py_DECREF(v); /* See Tktt_New() */ + res = PyEval_CallObject(func, NULL); + Py_DECREF(func); + Py_DECREF(v); /* See Tktt_New() */ - if (res == NULL) { - errorInCmd = 1; - PyErr_Fetch(&excInCmd, &valInCmd, &trbInCmd); - } - else - Py_DECREF(res); + if (res == NULL) { + errorInCmd = 1; + PyErr_Fetch(&excInCmd, &valInCmd, &trbInCmd); + } + else + Py_DECREF(res); - LEAVE_PYTHON + LEAVE_PYTHON } static PyObject * Tkapp_CreateTimerHandler(PyObject *self, PyObject *args) { - int milliseconds; - PyObject *func; - TkttObject *v; - - if (!PyArg_ParseTuple(args, "iO:createtimerhandler", - &milliseconds, &func)) - return NULL; - if (!PyCallable_Check(func)) { - PyErr_SetString(PyExc_TypeError, "bad argument list"); - return NULL; - } - - CHECK_TCL_APPARTMENT; - - v = Tktt_New(func); - if (v) { - v->token = Tcl_CreateTimerHandler(milliseconds, TimerHandler, - (ClientData)v); - } + int milliseconds; + PyObject *func; + TkttObject *v; + + if (!PyArg_ParseTuple(args, "iO:createtimerhandler", + &milliseconds, &func)) + return NULL; + if (!PyCallable_Check(func)) { + PyErr_SetString(PyExc_TypeError, "bad argument list"); + return NULL; + } + + CHECK_TCL_APPARTMENT; + + v = Tktt_New(func); + if (v) { + v->token = Tcl_CreateTimerHandler(milliseconds, TimerHandler, + (ClientData)v); + } - return (PyObject *) v; + return (PyObject *) v; } - + /** Event Loop **/ static PyObject * Tkapp_MainLoop(PyObject *selfptr, PyObject *args) { - int threshold = 0; - TkappObject *self = (TkappObject*)selfptr; + int threshold = 0; + TkappObject *self = (TkappObject*)selfptr; #ifdef WITH_THREAD - PyThreadState *tstate = PyThreadState_Get(); + PyThreadState *tstate = PyThreadState_Get(); #endif - if (!PyArg_ParseTuple(args, "|i:mainloop", &threshold)) - return NULL; + if (!PyArg_ParseTuple(args, "|i:mainloop", &threshold)) + return NULL; - CHECK_TCL_APPARTMENT; - self->dispatching = 1; - - quitMainLoop = 0; - while (Tk_GetNumMainWindows() > threshold && - !quitMainLoop && - !errorInCmd) - { - int result; - -#ifdef WITH_THREAD - if (self->threaded) { - /* Allow other Python threads to run. */ - ENTER_TCL - result = Tcl_DoOneEvent(0); - LEAVE_TCL - } - else { - Py_BEGIN_ALLOW_THREADS - if(tcl_lock)PyThread_acquire_lock(tcl_lock, 1); - tcl_tstate = tstate; - result = Tcl_DoOneEvent(TCL_DONT_WAIT); - tcl_tstate = NULL; - if(tcl_lock)PyThread_release_lock(tcl_lock); - if (result == 0) - Sleep(Tkinter_busywaitinterval); - Py_END_ALLOW_THREADS - } + CHECK_TCL_APPARTMENT; + self->dispatching = 1; + + quitMainLoop = 0; + while (Tk_GetNumMainWindows() > threshold && + !quitMainLoop && + !errorInCmd) + { + int result; + +#ifdef WITH_THREAD + if (self->threaded) { + /* Allow other Python threads to run. */ + ENTER_TCL + result = Tcl_DoOneEvent(0); + LEAVE_TCL + } + else { + Py_BEGIN_ALLOW_THREADS + if(tcl_lock)PyThread_acquire_lock(tcl_lock, 1); + tcl_tstate = tstate; + result = Tcl_DoOneEvent(TCL_DONT_WAIT); + tcl_tstate = NULL; + if(tcl_lock)PyThread_release_lock(tcl_lock); + if (result == 0) + Sleep(Tkinter_busywaitinterval); + Py_END_ALLOW_THREADS + } #else - result = Tcl_DoOneEvent(0); + result = Tcl_DoOneEvent(0); #endif - if (PyErr_CheckSignals() != 0) { - self->dispatching = 0; - return NULL; - } - if (result < 0) - break; - } - self->dispatching = 0; - quitMainLoop = 0; - - if (errorInCmd) { - errorInCmd = 0; - PyErr_Restore(excInCmd, valInCmd, trbInCmd); - excInCmd = valInCmd = trbInCmd = NULL; - return NULL; - } - Py_INCREF(Py_None); - return Py_None; + if (PyErr_CheckSignals() != 0) { + self->dispatching = 0; + return NULL; + } + if (result < 0) + break; + } + self->dispatching = 0; + quitMainLoop = 0; + + if (errorInCmd) { + errorInCmd = 0; + PyErr_Restore(excInCmd, valInCmd, trbInCmd); + excInCmd = valInCmd = trbInCmd = NULL; + return NULL; + } + Py_INCREF(Py_None); + return Py_None; } static PyObject * Tkapp_DoOneEvent(PyObject *self, PyObject *args) { - int flags = 0; - int rv; + int flags = 0; + int rv; - if (!PyArg_ParseTuple(args, "|i:dooneevent", &flags)) - return NULL; + if (!PyArg_ParseTuple(args, "|i:dooneevent", &flags)) + return NULL; - ENTER_TCL - rv = Tcl_DoOneEvent(flags); - LEAVE_TCL - return Py_BuildValue("i", rv); + ENTER_TCL + rv = Tcl_DoOneEvent(flags); + LEAVE_TCL + return Py_BuildValue("i", rv); } static PyObject * Tkapp_Quit(PyObject *self, PyObject *args) { - if (!PyArg_ParseTuple(args, ":quit")) - return NULL; + if (!PyArg_ParseTuple(args, ":quit")) + return NULL; - quitMainLoop = 1; - Py_INCREF(Py_None); - return Py_None; + quitMainLoop = 1; + Py_INCREF(Py_None); + return Py_None; } static PyObject * Tkapp_InterpAddr(PyObject *self, PyObject *args) { - if (!PyArg_ParseTuple(args, ":interpaddr")) - return NULL; + if (!PyArg_ParseTuple(args, ":interpaddr")) + return NULL; - return PyLong_FromLong((long)Tkapp_Interp(self)); + return PyLong_FromLong((long)Tkapp_Interp(self)); } -static PyObject * +static PyObject * Tkapp_TkInit(PyObject *self, PyObject *args) { - Tcl_Interp *interp = Tkapp_Interp(self); - const char * _tk_exists = NULL; - int err; + Tcl_Interp *interp = Tkapp_Interp(self); + const char * _tk_exists = NULL; + int err; #ifdef TKINTER_PROTECT_LOADTK - /* Up to Tk 8.4.13, Tk_Init deadlocks on the second call when the - * first call failed. - * To avoid the deadlock, we just refuse the second call through - * a static variable. - */ - if (tk_load_failed) { - PyErr_SetString(Tkinter_TclError, TKINTER_LOADTK_ERRMSG); - return NULL; - } -#endif - - /* We want to guard against calling Tk_Init() multiple times */ - CHECK_TCL_APPARTMENT; - ENTER_TCL - err = Tcl_Eval(Tkapp_Interp(self), "info exists tk_version"); - ENTER_OVERLAP - if (err == TCL_ERROR) { - /* This sets an exception, but we cannot return right - away because we need to exit the overlap first. */ - Tkinter_Error(self); - } else { - _tk_exists = Tkapp_Result(self); - } - LEAVE_OVERLAP_TCL - if (err == TCL_ERROR) { - return NULL; - } - if (_tk_exists == NULL || strcmp(_tk_exists, "1") != 0) { - if (Tk_Init(interp) == TCL_ERROR) { - PyErr_SetString(Tkinter_TclError, Tcl_GetStringResult(Tkapp_Interp(self))); + /* Up to Tk 8.4.13, Tk_Init deadlocks on the second call when the + * first call failed. + * To avoid the deadlock, we just refuse the second call through + * a static variable. + */ + if (tk_load_failed) { + PyErr_SetString(Tkinter_TclError, TKINTER_LOADTK_ERRMSG); + return NULL; + } +#endif + + /* We want to guard against calling Tk_Init() multiple times */ + CHECK_TCL_APPARTMENT; + ENTER_TCL + err = Tcl_Eval(Tkapp_Interp(self), "info exists tk_version"); + ENTER_OVERLAP + if (err == TCL_ERROR) { + /* This sets an exception, but we cannot return right + away because we need to exit the overlap first. */ + Tkinter_Error(self); + } else { + _tk_exists = Tkapp_Result(self); + } + LEAVE_OVERLAP_TCL + if (err == TCL_ERROR) { + return NULL; + } + if (_tk_exists == NULL || strcmp(_tk_exists, "1") != 0) { + if (Tk_Init(interp) == TCL_ERROR) { + PyErr_SetString(Tkinter_TclError, Tcl_GetStringResult(Tkapp_Interp(self))); #ifdef TKINTER_PROTECT_LOADTK - tk_load_failed = 1; + tk_load_failed = 1; #endif - return NULL; - } - } - Py_INCREF(Py_None); - return Py_None; + return NULL; + } + } + Py_INCREF(Py_None); + return Py_None; } static PyObject * Tkapp_WantObjects(PyObject *self, PyObject *args) { - int wantobjects = -1; - if (!PyArg_ParseTuple(args, "|i:wantobjects", &wantobjects)) - return NULL; - if (wantobjects == -1) - return PyBool_FromLong(((TkappObject*)self)->wantobjects); - ((TkappObject*)self)->wantobjects = wantobjects; + int wantobjects = -1; + if (!PyArg_ParseTuple(args, "|i:wantobjects", &wantobjects)) + return NULL; + if (wantobjects == -1) + return PyBool_FromLong(((TkappObject*)self)->wantobjects); + ((TkappObject*)self)->wantobjects = wantobjects; - Py_INCREF(Py_None); - return Py_None; + Py_INCREF(Py_None); + return Py_None; } static PyObject * Tkapp_WillDispatch(PyObject *self, PyObject *args) { - ((TkappObject*)self)->dispatching = 1; + ((TkappObject*)self)->dispatching = 1; - Py_INCREF(Py_None); - return Py_None; + Py_INCREF(Py_None); + return Py_None; } - + /**** Tkapp Method List ****/ static PyMethodDef Tkapp_methods[] = { - {"willdispatch", Tkapp_WillDispatch, METH_NOARGS}, - {"wantobjects", Tkapp_WantObjects, METH_VARARGS}, - {"call", Tkapp_Call, METH_VARARGS}, - {"globalcall", Tkapp_GlobalCall, METH_VARARGS}, - {"eval", Tkapp_Eval, METH_VARARGS}, - {"globaleval", Tkapp_GlobalEval, METH_VARARGS}, - {"evalfile", Tkapp_EvalFile, METH_VARARGS}, - {"record", Tkapp_Record, METH_VARARGS}, - {"adderrorinfo", Tkapp_AddErrorInfo, METH_VARARGS}, - {"setvar", Tkapp_SetVar, METH_VARARGS}, - {"globalsetvar", Tkapp_GlobalSetVar, METH_VARARGS}, - {"getvar", Tkapp_GetVar, METH_VARARGS}, - {"globalgetvar", Tkapp_GlobalGetVar, METH_VARARGS}, - {"unsetvar", Tkapp_UnsetVar, METH_VARARGS}, - {"globalunsetvar", Tkapp_GlobalUnsetVar, METH_VARARGS}, - {"getint", Tkapp_GetInt, METH_VARARGS}, - {"getdouble", Tkapp_GetDouble, METH_VARARGS}, - {"getboolean", Tkapp_GetBoolean, METH_VARARGS}, - {"exprstring", Tkapp_ExprString, METH_VARARGS}, - {"exprlong", Tkapp_ExprLong, METH_VARARGS}, - {"exprdouble", Tkapp_ExprDouble, METH_VARARGS}, - {"exprboolean", Tkapp_ExprBoolean, METH_VARARGS}, - {"splitlist", Tkapp_SplitList, METH_VARARGS}, - {"split", Tkapp_Split, METH_VARARGS}, - {"merge", Tkapp_Merge, METH_VARARGS}, - {"createcommand", Tkapp_CreateCommand, METH_VARARGS}, - {"deletecommand", Tkapp_DeleteCommand, METH_VARARGS}, + {"willdispatch", Tkapp_WillDispatch, METH_NOARGS}, + {"wantobjects", Tkapp_WantObjects, METH_VARARGS}, + {"call", Tkapp_Call, METH_VARARGS}, + {"globalcall", Tkapp_GlobalCall, METH_VARARGS}, + {"eval", Tkapp_Eval, METH_VARARGS}, + {"globaleval", Tkapp_GlobalEval, METH_VARARGS}, + {"evalfile", Tkapp_EvalFile, METH_VARARGS}, + {"record", Tkapp_Record, METH_VARARGS}, + {"adderrorinfo", Tkapp_AddErrorInfo, METH_VARARGS}, + {"setvar", Tkapp_SetVar, METH_VARARGS}, + {"globalsetvar", Tkapp_GlobalSetVar, METH_VARARGS}, + {"getvar", Tkapp_GetVar, METH_VARARGS}, + {"globalgetvar", Tkapp_GlobalGetVar, METH_VARARGS}, + {"unsetvar", Tkapp_UnsetVar, METH_VARARGS}, + {"globalunsetvar", Tkapp_GlobalUnsetVar, METH_VARARGS}, + {"getint", Tkapp_GetInt, METH_VARARGS}, + {"getdouble", Tkapp_GetDouble, METH_VARARGS}, + {"getboolean", Tkapp_GetBoolean, METH_VARARGS}, + {"exprstring", Tkapp_ExprString, METH_VARARGS}, + {"exprlong", Tkapp_ExprLong, METH_VARARGS}, + {"exprdouble", Tkapp_ExprDouble, METH_VARARGS}, + {"exprboolean", Tkapp_ExprBoolean, METH_VARARGS}, + {"splitlist", Tkapp_SplitList, METH_VARARGS}, + {"split", Tkapp_Split, METH_VARARGS}, + {"merge", Tkapp_Merge, METH_VARARGS}, + {"createcommand", Tkapp_CreateCommand, METH_VARARGS}, + {"deletecommand", Tkapp_DeleteCommand, METH_VARARGS}, #ifdef HAVE_CREATEFILEHANDLER - {"createfilehandler", Tkapp_CreateFileHandler, METH_VARARGS}, - {"deletefilehandler", Tkapp_DeleteFileHandler, METH_VARARGS}, + {"createfilehandler", Tkapp_CreateFileHandler, METH_VARARGS}, + {"deletefilehandler", Tkapp_DeleteFileHandler, METH_VARARGS}, #endif - {"createtimerhandler", Tkapp_CreateTimerHandler, METH_VARARGS}, - {"mainloop", Tkapp_MainLoop, METH_VARARGS}, - {"dooneevent", Tkapp_DoOneEvent, METH_VARARGS}, - {"quit", Tkapp_Quit, METH_VARARGS}, - {"interpaddr", Tkapp_InterpAddr, METH_VARARGS}, - {"loadtk", Tkapp_TkInit, METH_NOARGS}, - {NULL, NULL} + {"createtimerhandler", Tkapp_CreateTimerHandler, METH_VARARGS}, + {"mainloop", Tkapp_MainLoop, METH_VARARGS}, + {"dooneevent", Tkapp_DoOneEvent, METH_VARARGS}, + {"quit", Tkapp_Quit, METH_VARARGS}, + {"interpaddr", Tkapp_InterpAddr, METH_VARARGS}, + {"loadtk", Tkapp_TkInit, METH_NOARGS}, + {NULL, NULL} }; - + /**** Tkapp Type Methods ****/ static void Tkapp_Dealloc(PyObject *self) { - /*CHECK_TCL_APPARTMENT;*/ - ENTER_TCL - Tcl_DeleteInterp(Tkapp_Interp(self)); - LEAVE_TCL - PyObject_Del(self); - DisableEventHook(); + /*CHECK_TCL_APPARTMENT;*/ + ENTER_TCL + Tcl_DeleteInterp(Tkapp_Interp(self)); + LEAVE_TCL + PyObject_Del(self); + DisableEventHook(); } static PyTypeObject Tkapp_Type = { - PyVarObject_HEAD_INIT(NULL, 0) - "tkapp", /*tp_name */ - sizeof(TkappObject), /*tp_basicsize */ - 0, /*tp_itemsize */ - Tkapp_Dealloc, /*tp_dealloc */ - 0, /*tp_print */ - 0, /*tp_getattr */ - 0, /*tp_setattr */ - 0, /*tp_reserved */ - 0, /*tp_repr */ - 0, /*tp_as_number */ - 0, /*tp_as_sequence */ - 0, /*tp_as_mapping */ - 0, /*tp_hash */ - 0, /*tp_call*/ - 0, /*tp_str*/ - 0, /*tp_getattro*/ - 0, /*tp_setattro*/ - 0, /*tp_as_buffer*/ - Py_TPFLAGS_DEFAULT, /*tp_flags*/ - 0, /*tp_doc*/ - 0, /*tp_traverse*/ - 0, /*tp_clear*/ - 0, /*tp_richcompare*/ - 0, /*tp_weaklistoffset*/ - 0, /*tp_iter*/ - 0, /*tp_iternext*/ - Tkapp_methods, /*tp_methods*/ + PyVarObject_HEAD_INIT(NULL, 0) + "tkapp", /*tp_name */ + sizeof(TkappObject), /*tp_basicsize */ + 0, /*tp_itemsize */ + Tkapp_Dealloc, /*tp_dealloc */ + 0, /*tp_print */ + 0, /*tp_getattr */ + 0, /*tp_setattr */ + 0, /*tp_reserved */ + 0, /*tp_repr */ + 0, /*tp_as_number */ + 0, /*tp_as_sequence */ + 0, /*tp_as_mapping */ + 0, /*tp_hash */ + 0, /*tp_call*/ + 0, /*tp_str*/ + 0, /*tp_getattro*/ + 0, /*tp_setattro*/ + 0, /*tp_as_buffer*/ + Py_TPFLAGS_DEFAULT, /*tp_flags*/ + 0, /*tp_doc*/ + 0, /*tp_traverse*/ + 0, /*tp_clear*/ + 0, /*tp_richcompare*/ + 0, /*tp_weaklistoffset*/ + 0, /*tp_iter*/ + 0, /*tp_iternext*/ + Tkapp_methods, /*tp_methods*/ }; - + /**** Tkinter Module ****/ typedef struct { - PyObject* tuple; - int size; /* current size */ - int maxsize; /* allocated size */ + PyObject* tuple; + int size; /* current size */ + int maxsize; /* allocated size */ } FlattenContext; static int _bump(FlattenContext* context, int size) { - /* expand tuple to hold (at least) size new items. - return true if successful, false if an exception was raised */ + /* expand tuple to hold (at least) size new items. + return true if successful, false if an exception was raised */ - int maxsize = context->maxsize * 2; + int maxsize = context->maxsize * 2; - if (maxsize < context->size + size) - maxsize = context->size + size; + if (maxsize < context->size + size) + maxsize = context->size + size; - context->maxsize = maxsize; + context->maxsize = maxsize; - return _PyTuple_Resize(&context->tuple, maxsize) >= 0; + return _PyTuple_Resize(&context->tuple, maxsize) >= 0; } static int _flatten1(FlattenContext* context, PyObject* item, int depth) { - /* add tuple or list to argument tuple (recursively) */ + /* add tuple or list to argument tuple (recursively) */ - int i, size; + int i, size; - if (depth > 1000) { - PyErr_SetString(PyExc_ValueError, - "nesting too deep in _flatten"); - return 0; - } else if (PyList_Check(item)) { - size = PyList_GET_SIZE(item); - /* preallocate (assume no nesting) */ - if (context->size + size > context->maxsize && - !_bump(context, size)) - return 0; - /* copy items to output tuple */ - for (i = 0; i < size; i++) { - PyObject *o = PyList_GET_ITEM(item, i); - if (PyList_Check(o) || PyTuple_Check(o)) { - if (!_flatten1(context, o, depth + 1)) - return 0; - } else if (o != Py_None) { - if (context->size + 1 > context->maxsize && - !_bump(context, 1)) - return 0; - Py_INCREF(o); - PyTuple_SET_ITEM(context->tuple, - context->size++, o); - } - } - } else if (PyTuple_Check(item)) { - /* same, for tuples */ - size = PyTuple_GET_SIZE(item); - if (context->size + size > context->maxsize && - !_bump(context, size)) - return 0; - for (i = 0; i < size; i++) { - PyObject *o = PyTuple_GET_ITEM(item, i); - if (PyList_Check(o) || PyTuple_Check(o)) { - if (!_flatten1(context, o, depth + 1)) - return 0; - } else if (o != Py_None) { - if (context->size + 1 > context->maxsize && - !_bump(context, 1)) - return 0; - Py_INCREF(o); - PyTuple_SET_ITEM(context->tuple, - context->size++, o); - } - } - } else { - PyErr_SetString(PyExc_TypeError, "argument must be sequence"); - return 0; - } - return 1; + if (depth > 1000) { + PyErr_SetString(PyExc_ValueError, + "nesting too deep in _flatten"); + return 0; + } else if (PyList_Check(item)) { + size = PyList_GET_SIZE(item); + /* preallocate (assume no nesting) */ + if (context->size + size > context->maxsize && + !_bump(context, size)) + return 0; + /* copy items to output tuple */ + for (i = 0; i < size; i++) { + PyObject *o = PyList_GET_ITEM(item, i); + if (PyList_Check(o) || PyTuple_Check(o)) { + if (!_flatten1(context, o, depth + 1)) + return 0; + } else if (o != Py_None) { + if (context->size + 1 > context->maxsize && + !_bump(context, 1)) + return 0; + Py_INCREF(o); + PyTuple_SET_ITEM(context->tuple, + context->size++, o); + } + } + } else if (PyTuple_Check(item)) { + /* same, for tuples */ + size = PyTuple_GET_SIZE(item); + if (context->size + size > context->maxsize && + !_bump(context, size)) + return 0; + for (i = 0; i < size; i++) { + PyObject *o = PyTuple_GET_ITEM(item, i); + if (PyList_Check(o) || PyTuple_Check(o)) { + if (!_flatten1(context, o, depth + 1)) + return 0; + } else if (o != Py_None) { + if (context->size + 1 > context->maxsize && + !_bump(context, 1)) + return 0; + Py_INCREF(o); + PyTuple_SET_ITEM(context->tuple, + context->size++, o); + } + } + } else { + PyErr_SetString(PyExc_TypeError, "argument must be sequence"); + return 0; + } + return 1; } static PyObject * Tkinter_Flatten(PyObject* self, PyObject* args) { - FlattenContext context; - PyObject* item; + FlattenContext context; + PyObject* item; - if (!PyArg_ParseTuple(args, "O:_flatten", &item)) - return NULL; + if (!PyArg_ParseTuple(args, "O:_flatten", &item)) + return NULL; - context.maxsize = PySequence_Size(item); - if (context.maxsize < 0) - return NULL; - if (context.maxsize == 0) - return PyTuple_New(0); + context.maxsize = PySequence_Size(item); + if (context.maxsize < 0) + return NULL; + if (context.maxsize == 0) + return PyTuple_New(0); - context.tuple = PyTuple_New(context.maxsize); - if (!context.tuple) - return NULL; + context.tuple = PyTuple_New(context.maxsize); + if (!context.tuple) + return NULL; - context.size = 0; + context.size = 0; - if (!_flatten1(&context, item,0)) - return NULL; + if (!_flatten1(&context, item,0)) + return NULL; - if (_PyTuple_Resize(&context.tuple, context.size)) - return NULL; + if (_PyTuple_Resize(&context.tuple, context.size)) + return NULL; - return context.tuple; + return context.tuple; } static PyObject * Tkinter_Create(PyObject *self, PyObject *args) { - char *screenName = NULL; - char *baseName = NULL; /* XXX this is not used anymore; - try getting rid of it. */ - char *className = NULL; - int interactive = 0; - int wantobjects = 0; - int wantTk = 1; /* If false, then Tk_Init() doesn't get called */ - int sync = 0; /* pass -sync to wish */ - char *use = NULL; /* pass -use to wish */ - - className = "Tk"; - - if (!PyArg_ParseTuple(args, "|zssiiiiz:create", - &screenName, &baseName, &className, - &interactive, &wantobjects, &wantTk, - &sync, &use)) - return NULL; - - return (PyObject *) Tkapp_New(screenName, className, - interactive, wantobjects, wantTk, - sync, use); + char *screenName = NULL; + char *baseName = NULL; /* XXX this is not used anymore; + try getting rid of it. */ + char *className = NULL; + int interactive = 0; + int wantobjects = 0; + int wantTk = 1; /* If false, then Tk_Init() doesn't get called */ + int sync = 0; /* pass -sync to wish */ + char *use = NULL; /* pass -use to wish */ + + className = "Tk"; + + if (!PyArg_ParseTuple(args, "|zssiiiiz:create", + &screenName, &baseName, &className, + &interactive, &wantobjects, &wantTk, + &sync, &use)) + return NULL; + + return (PyObject *) Tkapp_New(screenName, className, + interactive, wantobjects, wantTk, + sync, use); } static PyObject * Tkinter_setbusywaitinterval(PyObject *self, PyObject *args) { - int new_val; - if (!PyArg_ParseTuple(args, "i:setbusywaitinterval", &new_val)) - return NULL; - if (new_val < 0) { - PyErr_SetString(PyExc_ValueError, - "busywaitinterval must be >= 0"); - return NULL; - } - Tkinter_busywaitinterval = new_val; - Py_INCREF(Py_None); - return Py_None; + int new_val; + if (!PyArg_ParseTuple(args, "i:setbusywaitinterval", &new_val)) + return NULL; + if (new_val < 0) { + PyErr_SetString(PyExc_ValueError, + "busywaitinterval must be >= 0"); + return NULL; + } + Tkinter_busywaitinterval = new_val; + Py_INCREF(Py_None); + return Py_None; } static char setbusywaitinterval_doc[] = @@ -2935,7 +2935,7 @@ static PyObject * Tkinter_getbusywaitinterval(PyObject *self, PyObject *args) { - return PyLong_FromLong(Tkinter_busywaitinterval); + return PyLong_FromLong(Tkinter_busywaitinterval); } static char getbusywaitinterval_doc[] = @@ -2946,13 +2946,13 @@ static PyMethodDef moduleMethods[] = { - {"_flatten", Tkinter_Flatten, METH_VARARGS}, - {"create", Tkinter_Create, METH_VARARGS}, - {"setbusywaitinterval",Tkinter_setbusywaitinterval, METH_VARARGS, - setbusywaitinterval_doc}, - {"getbusywaitinterval",(PyCFunction)Tkinter_getbusywaitinterval, - METH_NOARGS, getbusywaitinterval_doc}, - {NULL, NULL} + {"_flatten", Tkinter_Flatten, METH_VARARGS}, + {"create", Tkinter_Create, METH_VARARGS}, + {"setbusywaitinterval",Tkinter_setbusywaitinterval, METH_VARARGS, + setbusywaitinterval_doc}, + {"getbusywaitinterval",(PyCFunction)Tkinter_getbusywaitinterval, + METH_NOARGS, getbusywaitinterval_doc}, + {NULL, NULL} }; #ifdef WAIT_FOR_STDIN @@ -2963,7 +2963,7 @@ static void MyFileProc(void *clientData, int mask) { - stdin_ready = 1; + stdin_ready = 1; } #endif @@ -2975,57 +2975,57 @@ EventHook(void) { #ifndef MS_WINDOWS - int tfile; + int tfile; #endif #ifdef WITH_THREAD - PyEval_RestoreThread(event_tstate); + PyEval_RestoreThread(event_tstate); #endif - stdin_ready = 0; - errorInCmd = 0; + stdin_ready = 0; + errorInCmd = 0; #ifndef MS_WINDOWS - tfile = fileno(stdin); - Tcl_CreateFileHandler(tfile, TCL_READABLE, MyFileProc, NULL); + tfile = fileno(stdin); + Tcl_CreateFileHandler(tfile, TCL_READABLE, MyFileProc, NULL); #endif - while (!errorInCmd && !stdin_ready) { - int result; + while (!errorInCmd && !stdin_ready) { + int result; #ifdef MS_WINDOWS - if (_kbhit()) { - stdin_ready = 1; - break; - } + if (_kbhit()) { + stdin_ready = 1; + break; + } #endif #if defined(WITH_THREAD) || defined(MS_WINDOWS) - Py_BEGIN_ALLOW_THREADS - if(tcl_lock)PyThread_acquire_lock(tcl_lock, 1); - tcl_tstate = event_tstate; - - result = Tcl_DoOneEvent(TCL_DONT_WAIT); - - tcl_tstate = NULL; - if(tcl_lock)PyThread_release_lock(tcl_lock); - if (result == 0) - Sleep(Tkinter_busywaitinterval); - Py_END_ALLOW_THREADS + Py_BEGIN_ALLOW_THREADS + if(tcl_lock)PyThread_acquire_lock(tcl_lock, 1); + tcl_tstate = event_tstate; + + result = Tcl_DoOneEvent(TCL_DONT_WAIT); + + tcl_tstate = NULL; + if(tcl_lock)PyThread_release_lock(tcl_lock); + if (result == 0) + Sleep(Tkinter_busywaitinterval); + Py_END_ALLOW_THREADS #else - result = Tcl_DoOneEvent(0); + result = Tcl_DoOneEvent(0); #endif - if (result < 0) - break; - } + if (result < 0) + break; + } #ifndef MS_WINDOWS - Tcl_DeleteFileHandler(tfile); + Tcl_DeleteFileHandler(tfile); #endif - if (errorInCmd) { - errorInCmd = 0; - PyErr_Restore(excInCmd, valInCmd, trbInCmd); - excInCmd = valInCmd = trbInCmd = NULL; - PyErr_Print(); - } + if (errorInCmd) { + errorInCmd = 0; + PyErr_Restore(excInCmd, valInCmd, trbInCmd); + excInCmd = valInCmd = trbInCmd = NULL; + PyErr_Print(); + } #ifdef WITH_THREAD - PyEval_SaveThread(); + PyEval_SaveThread(); #endif - return 0; + return 0; } #endif @@ -3034,12 +3034,12 @@ EnableEventHook(void) { #ifdef WAIT_FOR_STDIN - if (PyOS_InputHook == NULL) { + if (PyOS_InputHook == NULL) { #ifdef WITH_THREAD - event_tstate = PyThreadState_Get(); + event_tstate = PyThreadState_Get(); #endif - PyOS_InputHook = EventHook; - } + PyOS_InputHook = EventHook; + } #endif } @@ -3047,9 +3047,9 @@ DisableEventHook(void) { #ifdef WAIT_FOR_STDIN - if (Tk_GetNumMainWindows() == 0 && PyOS_InputHook == EventHook) { - PyOS_InputHook = NULL; - } + if (Tk_GetNumMainWindows() == 0 && PyOS_InputHook == EventHook) { + PyOS_InputHook = NULL; + } #endif } @@ -3058,114 +3058,114 @@ static void ins_long(PyObject *d, char *name, long val) { - PyObject *v = PyLong_FromLong(val); - if (v) { - PyDict_SetItemString(d, name, v); - Py_DECREF(v); - } + PyObject *v = PyLong_FromLong(val); + if (v) { + PyDict_SetItemString(d, name, v); + Py_DECREF(v); + } } static void ins_string(PyObject *d, char *name, char *val) { - PyObject *v = PyUnicode_FromString(val); - if (v) { - PyDict_SetItemString(d, name, v); - Py_DECREF(v); - } + PyObject *v = PyUnicode_FromString(val); + if (v) { + PyDict_SetItemString(d, name, v); + Py_DECREF(v); + } } static struct PyModuleDef _tkintermodule = { - PyModuleDef_HEAD_INIT, - "_tkinter", - NULL, - -1, - moduleMethods, - NULL, - NULL, - NULL, - NULL + PyModuleDef_HEAD_INIT, + "_tkinter", + NULL, + -1, + moduleMethods, + NULL, + NULL, + NULL, + NULL }; PyMODINIT_FUNC PyInit__tkinter(void) { - PyObject *m, *d, *uexe, *cexe; + PyObject *m, *d, *uexe, *cexe; - if (PyType_Ready(&Tkapp_Type) < 0) - return NULL; + if (PyType_Ready(&Tkapp_Type) < 0) + return NULL; #ifdef WITH_THREAD - tcl_lock = PyThread_allocate_lock(); + tcl_lock = PyThread_allocate_lock(); #endif - m = PyModule_Create(&_tkintermodule); - if (m == NULL) - return NULL; + m = PyModule_Create(&_tkintermodule); + if (m == NULL) + return NULL; - d = PyModule_GetDict(m); - Tkinter_TclError = PyErr_NewException("_tkinter.TclError", NULL, NULL); - PyDict_SetItemString(d, "TclError", Tkinter_TclError); + d = PyModule_GetDict(m); + Tkinter_TclError = PyErr_NewException("_tkinter.TclError", NULL, NULL); + PyDict_SetItemString(d, "TclError", Tkinter_TclError); - ins_long(d, "READABLE", TCL_READABLE); - ins_long(d, "WRITABLE", TCL_WRITABLE); - ins_long(d, "EXCEPTION", TCL_EXCEPTION); - ins_long(d, "WINDOW_EVENTS", TCL_WINDOW_EVENTS); - ins_long(d, "FILE_EVENTS", TCL_FILE_EVENTS); - ins_long(d, "TIMER_EVENTS", TCL_TIMER_EVENTS); - ins_long(d, "IDLE_EVENTS", TCL_IDLE_EVENTS); - ins_long(d, "ALL_EVENTS", TCL_ALL_EVENTS); - ins_long(d, "DONT_WAIT", TCL_DONT_WAIT); - ins_string(d, "TK_VERSION", TK_VERSION); - ins_string(d, "TCL_VERSION", TCL_VERSION); + ins_long(d, "READABLE", TCL_READABLE); + ins_long(d, "WRITABLE", TCL_WRITABLE); + ins_long(d, "EXCEPTION", TCL_EXCEPTION); + ins_long(d, "WINDOW_EVENTS", TCL_WINDOW_EVENTS); + ins_long(d, "FILE_EVENTS", TCL_FILE_EVENTS); + ins_long(d, "TIMER_EVENTS", TCL_TIMER_EVENTS); + ins_long(d, "IDLE_EVENTS", TCL_IDLE_EVENTS); + ins_long(d, "ALL_EVENTS", TCL_ALL_EVENTS); + ins_long(d, "DONT_WAIT", TCL_DONT_WAIT); + ins_string(d, "TK_VERSION", TK_VERSION); + ins_string(d, "TCL_VERSION", TCL_VERSION); - PyDict_SetItemString(d, "TkappType", (PyObject *)&Tkapp_Type); + PyDict_SetItemString(d, "TkappType", (PyObject *)&Tkapp_Type); - if (PyType_Ready(&Tktt_Type) < 0) - return NULL; - PyDict_SetItemString(d, "TkttType", (PyObject *)&Tktt_Type); + if (PyType_Ready(&Tktt_Type) < 0) + return NULL; + PyDict_SetItemString(d, "TkttType", (PyObject *)&Tktt_Type); - Py_TYPE(&PyTclObject_Type) = &PyType_Type; - PyDict_SetItemString(d, "Tcl_Obj", (PyObject *)&PyTclObject_Type); + Py_TYPE(&PyTclObject_Type) = &PyType_Type; + PyDict_SetItemString(d, "Tcl_Obj", (PyObject *)&PyTclObject_Type); #ifdef TK_AQUA - /* Tk_MacOSXSetupTkNotifier must be called before Tcl's subsystems - * start waking up. Note that Tcl_FindExecutable will do this, this - * code must be above it! The original warning from - * tkMacOSXAppInit.c is copied below. - * - * NB - You have to swap in the Tk Notifier BEFORE you start up the - * Tcl interpreter for now. It probably should work to do this - * in the other order, but for now it doesn't seem to. - * - */ - Tk_MacOSXSetupTkNotifier(); + /* Tk_MacOSXSetupTkNotifier must be called before Tcl's subsystems + * start waking up. Note that Tcl_FindExecutable will do this, this + * code must be above it! The original warning from + * tkMacOSXAppInit.c is copied below. + * + * NB - You have to swap in the Tk Notifier BEFORE you start up the + * Tcl interpreter for now. It probably should work to do this + * in the other order, but for now it doesn't seem to. + * + */ + Tk_MacOSXSetupTkNotifier(); #endif - /* This helps the dynamic loader; in Unicode aware Tcl versions - it also helps Tcl find its encodings. */ - uexe = PyUnicode_FromWideChar(Py_GetProgramName(), -1); - if (uexe) { - cexe = PyUnicode_AsEncodedString(uexe, - Py_FileSystemDefaultEncoding, - NULL); - if (cexe) - Tcl_FindExecutable(PyBytes_AsString(cexe)); - Py_XDECREF(cexe); - Py_DECREF(uexe); - } - - if (PyErr_Occurred()) { - Py_DECREF(m); - return NULL; - } + /* This helps the dynamic loader; in Unicode aware Tcl versions + it also helps Tcl find its encodings. */ + uexe = PyUnicode_FromWideChar(Py_GetProgramName(), -1); + if (uexe) { + cexe = PyUnicode_AsEncodedString(uexe, + Py_FileSystemDefaultEncoding, + NULL); + if (cexe) + Tcl_FindExecutable(PyBytes_AsString(cexe)); + Py_XDECREF(cexe); + Py_DECREF(uexe); + } + + if (PyErr_Occurred()) { + Py_DECREF(m); + return NULL; + } #if 0 - /* This was not a good idea; through bindings, - Tcl_Finalize() may invoke Python code but at that point the - interpreter and thread state have already been destroyed! */ - Py_AtExit(Tcl_Finalize); + /* This was not a good idea; through bindings, + Tcl_Finalize() may invoke Python code but at that point the + interpreter and thread state have already been destroyed! */ + Py_AtExit(Tcl_Finalize); #endif - return m; + return m; } Modified: python/branches/release31-maint/Modules/addrinfo.h ============================================================================== --- python/branches/release31-maint/Modules/addrinfo.h (original) +++ python/branches/release31-maint/Modules/addrinfo.h Sun May 9 18:14:21 2010 @@ -1,7 +1,7 @@ /* * Copyright (C) 1995, 1996, 1997, 1998, and 1999 WIDE Project. * All rights reserved. - * + * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: @@ -13,7 +13,7 @@ * 3. Neither the name of the project nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. - * + * * THIS SOFTWARE IS PROVIDED BY THE PROJECT AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE @@ -55,20 +55,20 @@ #define getaddrinfo fake_getaddrinfo #endif /* EAI_ADDRFAMILY */ -#define EAI_ADDRFAMILY 1 /* address family for hostname not supported */ -#define EAI_AGAIN 2 /* temporary failure in name resolution */ -#define EAI_BADFLAGS 3 /* invalid value for ai_flags */ -#define EAI_FAIL 4 /* non-recoverable failure in name resolution */ -#define EAI_FAMILY 5 /* ai_family not supported */ -#define EAI_MEMORY 6 /* memory allocation failure */ -#define EAI_NODATA 7 /* no address associated with hostname */ -#define EAI_NONAME 8 /* hostname nor servname provided, or not known */ -#define EAI_SERVICE 9 /* servname not supported for ai_socktype */ -#define EAI_SOCKTYPE 10 /* ai_socktype not supported */ -#define EAI_SYSTEM 11 /* system error returned in errno */ -#define EAI_BADHINTS 12 -#define EAI_PROTOCOL 13 -#define EAI_MAX 14 +#define EAI_ADDRFAMILY 1 /* address family for hostname not supported */ +#define EAI_AGAIN 2 /* temporary failure in name resolution */ +#define EAI_BADFLAGS 3 /* invalid value for ai_flags */ +#define EAI_FAIL 4 /* non-recoverable failure in name resolution */ +#define EAI_FAMILY 5 /* ai_family not supported */ +#define EAI_MEMORY 6 /* memory allocation failure */ +#define EAI_NODATA 7 /* no address associated with hostname */ +#define EAI_NONAME 8 /* hostname nor servname provided, or not known */ +#define EAI_SERVICE 9 /* servname not supported for ai_socktype */ +#define EAI_SOCKTYPE 10 /* ai_socktype not supported */ +#define EAI_SYSTEM 11 /* system error returned in errno */ +#define EAI_BADHINTS 12 +#define EAI_PROTOCOL 13 +#define EAI_MAX 14 /* * Flag values for getaddrinfo() @@ -85,18 +85,18 @@ #undef AI_DEFAULT #endif /* AI_PASSIVE */ -#define AI_PASSIVE 0x00000001 /* get address to use bind() */ -#define AI_CANONNAME 0x00000002 /* fill ai_canonname */ -#define AI_NUMERICHOST 0x00000004 /* prevent name resolution */ +#define AI_PASSIVE 0x00000001 /* get address to use bind() */ +#define AI_CANONNAME 0x00000002 /* fill ai_canonname */ +#define AI_NUMERICHOST 0x00000004 /* prevent name resolution */ /* valid flags for addrinfo */ -#define AI_MASK (AI_PASSIVE | AI_CANONNAME | AI_NUMERICHOST) +#define AI_MASK (AI_PASSIVE | AI_CANONNAME | AI_NUMERICHOST) -#define AI_ALL 0x00000100 /* IPv6 and IPv4-mapped (with AI_V4MAPPED) */ -#define AI_V4MAPPED_CFG 0x00000200 /* accept IPv4-mapped if kernel supports */ -#define AI_ADDRCONFIG 0x00000400 /* only if any address is assigned */ -#define AI_V4MAPPED 0x00000800 /* accept IPv4-mapped IPv6 address */ +#define AI_ALL 0x00000100 /* IPv6 and IPv4-mapped (with AI_V4MAPPED) */ +#define AI_V4MAPPED_CFG 0x00000200 /* accept IPv4-mapped if kernel supports */ +#define AI_ADDRCONFIG 0x00000400 /* only if any address is assigned */ +#define AI_V4MAPPED 0x00000800 /* accept IPv4-mapped IPv6 address */ /* special recommended flags for getipnodebyname */ -#define AI_DEFAULT (AI_V4MAPPED_CFG | AI_ADDRCONFIG) +#define AI_DEFAULT (AI_V4MAPPED_CFG | AI_ADDRCONFIG) #endif /* !HAVE_GETADDRINFO */ @@ -106,33 +106,33 @@ * Constants for getnameinfo() */ #ifndef NI_MAXHOST -#define NI_MAXHOST 1025 -#define NI_MAXSERV 32 +#define NI_MAXHOST 1025 +#define NI_MAXSERV 32 #endif /* !NI_MAXHOST */ /* * Flag values for getnameinfo() */ #ifndef NI_NOFQDN -#define NI_NOFQDN 0x00000001 -#define NI_NUMERICHOST 0x00000002 -#define NI_NAMEREQD 0x00000004 -#define NI_NUMERICSERV 0x00000008 -#define NI_DGRAM 0x00000010 +#define NI_NOFQDN 0x00000001 +#define NI_NUMERICHOST 0x00000002 +#define NI_NAMEREQD 0x00000004 +#define NI_NUMERICSERV 0x00000008 +#define NI_DGRAM 0x00000010 #endif /* !NI_NOFQDN */ #endif /* !HAVE_GETNAMEINFO */ #ifndef HAVE_ADDRINFO struct addrinfo { - int ai_flags; /* AI_PASSIVE, AI_CANONNAME */ - int ai_family; /* PF_xxx */ - int ai_socktype; /* SOCK_xxx */ - int ai_protocol; /* 0 or IPPROTO_xxx for IPv4 and IPv6 */ - size_t ai_addrlen; /* length of ai_addr */ - char *ai_canonname; /* canonical name for hostname */ - struct sockaddr *ai_addr; /* binary address */ - struct addrinfo *ai_next; /* next structure in linked list */ + int ai_flags; /* AI_PASSIVE, AI_CANONNAME */ + int ai_family; /* PF_xxx */ + int ai_socktype; /* SOCK_xxx */ + int ai_protocol; /* 0 or IPPROTO_xxx for IPv4 and IPv6 */ + size_t ai_addrlen; /* length of ai_addr */ + char *ai_canonname; /* canonical name for hostname */ + struct sockaddr *ai_addr; /* binary address */ + struct addrinfo *ai_next; /* next structure in linked list */ }; #endif /* !HAVE_ADDRINFO */ @@ -140,30 +140,30 @@ /* * RFC 2553: protocol-independent placeholder for socket addresses */ -#define _SS_MAXSIZE 128 +#define _SS_MAXSIZE 128 #ifdef HAVE_LONG_LONG -#define _SS_ALIGNSIZE (sizeof(PY_LONG_LONG)) +#define _SS_ALIGNSIZE (sizeof(PY_LONG_LONG)) #else -#define _SS_ALIGNSIZE (sizeof(double)) +#define _SS_ALIGNSIZE (sizeof(double)) #endif /* HAVE_LONG_LONG */ -#define _SS_PAD1SIZE (_SS_ALIGNSIZE - sizeof(u_char) * 2) -#define _SS_PAD2SIZE (_SS_MAXSIZE - sizeof(u_char) * 2 - \ - _SS_PAD1SIZE - _SS_ALIGNSIZE) +#define _SS_PAD1SIZE (_SS_ALIGNSIZE - sizeof(u_char) * 2) +#define _SS_PAD2SIZE (_SS_MAXSIZE - sizeof(u_char) * 2 - \ + _SS_PAD1SIZE - _SS_ALIGNSIZE) struct sockaddr_storage { #ifdef HAVE_SOCKADDR_SA_LEN - unsigned char ss_len; /* address length */ - unsigned char ss_family; /* address family */ + unsigned char ss_len; /* address length */ + unsigned char ss_family; /* address family */ #else - unsigned short ss_family; /* address family */ + unsigned short ss_family; /* address family */ #endif /* HAVE_SOCKADDR_SA_LEN */ - char __ss_pad1[_SS_PAD1SIZE]; + char __ss_pad1[_SS_PAD1SIZE]; #ifdef HAVE_LONG_LONG - PY_LONG_LONG __ss_align; /* force desired structure storage alignment */ + PY_LONG_LONG __ss_align; /* force desired structure storage alignment */ #else - double __ss_align; /* force desired structure storage alignment */ + double __ss_align; /* force desired structure storage alignment */ #endif /* HAVE_LONG_LONG */ - char __ss_pad2[_SS_PAD2SIZE]; + char __ss_pad2[_SS_PAD2SIZE]; }; #endif /* !HAVE_SOCKADDR_STORAGE */ Modified: python/branches/release31-maint/Modules/arraymodule.c ============================================================================== --- python/branches/release31-maint/Modules/arraymodule.c (original) +++ python/branches/release31-maint/Modules/arraymodule.c Sun May 9 18:14:21 2010 @@ -11,7 +11,7 @@ #include #else /* !STDC_HEADERS */ #ifdef HAVE_SYS_TYPES_H -#include /* For size_t */ +#include /* For size_t */ #endif /* HAVE_SYS_TYPES_H */ #endif /* !STDC_HEADERS */ @@ -22,20 +22,20 @@ * functions aren't visible yet. */ struct arraydescr { - int typecode; - int itemsize; - PyObject * (*getitem)(struct arrayobject *, Py_ssize_t); - int (*setitem)(struct arrayobject *, Py_ssize_t, PyObject *); - char *formats; + int typecode; + int itemsize; + PyObject * (*getitem)(struct arrayobject *, Py_ssize_t); + int (*setitem)(struct arrayobject *, Py_ssize_t, PyObject *); + char *formats; }; typedef struct arrayobject { - PyObject_VAR_HEAD - char *ob_item; - Py_ssize_t allocated; - struct arraydescr *ob_descr; - PyObject *weakreflist; /* List of weak references */ - int ob_exports; /* Number of exported buffers */ + PyObject_VAR_HEAD + char *ob_item; + Py_ssize_t allocated; + struct arraydescr *ob_descr; + PyObject *weakreflist; /* List of weak references */ + int ob_exports; /* Number of exported buffers */ } arrayobject; static PyTypeObject Arraytype; @@ -46,63 +46,63 @@ static int array_resize(arrayobject *self, Py_ssize_t newsize) { - char *items; - size_t _new_size; + char *items; + size_t _new_size; - if (self->ob_exports > 0 && newsize != Py_SIZE(self)) { - PyErr_SetString(PyExc_BufferError, - "cannot resize an array that is exporting buffers"); - return -1; - } - - /* Bypass realloc() when a previous overallocation is large enough - to accommodate the newsize. If the newsize is 16 smaller than the - current size, then proceed with the realloc() to shrink the array. - */ - - if (self->allocated >= newsize && - Py_SIZE(self) < newsize + 16 && - self->ob_item != NULL) { - Py_SIZE(self) = newsize; - return 0; - } - - if (newsize == 0) { - PyMem_FREE(self->ob_item); - self->ob_item = NULL; - Py_SIZE(self) = 0; - self->allocated = 0; - return 0; - } - - /* This over-allocates proportional to the array size, making room - * for additional growth. The over-allocation is mild, but is - * enough to give linear-time amortized behavior over a long - * sequence of appends() in the presence of a poorly-performing - * system realloc(). - * The growth pattern is: 0, 4, 8, 16, 25, 34, 46, 56, 67, 79, ... - * Note, the pattern starts out the same as for lists but then - * grows at a smaller rate so that larger arrays only overallocate - * by about 1/16th -- this is done because arrays are presumed to be more - * memory critical. - */ - - _new_size = (newsize >> 4) + (Py_SIZE(self) < 8 ? 3 : 7) + newsize; - items = self->ob_item; - /* XXX The following multiplication and division does not optimize away - like it does for lists since the size is not known at compile time */ - if (_new_size <= ((~(size_t)0) / self->ob_descr->itemsize)) - PyMem_RESIZE(items, char, (_new_size * self->ob_descr->itemsize)); - else - items = NULL; - if (items == NULL) { - PyErr_NoMemory(); - return -1; - } - self->ob_item = items; - Py_SIZE(self) = newsize; - self->allocated = _new_size; - return 0; + if (self->ob_exports > 0 && newsize != Py_SIZE(self)) { + PyErr_SetString(PyExc_BufferError, + "cannot resize an array that is exporting buffers"); + return -1; + } + + /* Bypass realloc() when a previous overallocation is large enough + to accommodate the newsize. If the newsize is 16 smaller than the + current size, then proceed with the realloc() to shrink the array. + */ + + if (self->allocated >= newsize && + Py_SIZE(self) < newsize + 16 && + self->ob_item != NULL) { + Py_SIZE(self) = newsize; + return 0; + } + + if (newsize == 0) { + PyMem_FREE(self->ob_item); + self->ob_item = NULL; + Py_SIZE(self) = 0; + self->allocated = 0; + return 0; + } + + /* This over-allocates proportional to the array size, making room + * for additional growth. The over-allocation is mild, but is + * enough to give linear-time amortized behavior over a long + * sequence of appends() in the presence of a poorly-performing + * system realloc(). + * The growth pattern is: 0, 4, 8, 16, 25, 34, 46, 56, 67, 79, ... + * Note, the pattern starts out the same as for lists but then + * grows at a smaller rate so that larger arrays only overallocate + * by about 1/16th -- this is done because arrays are presumed to be more + * memory critical. + */ + + _new_size = (newsize >> 4) + (Py_SIZE(self) < 8 ? 3 : 7) + newsize; + items = self->ob_item; + /* XXX The following multiplication and division does not optimize away + like it does for lists since the size is not known at compile time */ + if (_new_size <= ((~(size_t)0) / self->ob_descr->itemsize)) + PyMem_RESIZE(items, char, (_new_size * self->ob_descr->itemsize)); + else + items = NULL; + if (items == NULL) { + PyErr_NoMemory(); + return -1; + } + self->ob_item = items; + Py_SIZE(self) = newsize; + self->allocated = _new_size; + return 0; } /**************************************************************************** @@ -120,289 +120,289 @@ static PyObject * b_getitem(arrayobject *ap, Py_ssize_t i) { - long x = ((char *)ap->ob_item)[i]; - if (x >= 128) - x -= 256; - return PyLong_FromLong(x); + long x = ((char *)ap->ob_item)[i]; + if (x >= 128) + x -= 256; + return PyLong_FromLong(x); } static int b_setitem(arrayobject *ap, Py_ssize_t i, PyObject *v) { - short x; - /* PyArg_Parse's 'b' formatter is for an unsigned char, therefore - must use the next size up that is signed ('h') and manually do - the overflow checking */ - if (!PyArg_Parse(v, "h;array item must be integer", &x)) - return -1; - else if (x < -128) { - PyErr_SetString(PyExc_OverflowError, - "signed char is less than minimum"); - return -1; - } - else if (x > 127) { - PyErr_SetString(PyExc_OverflowError, - "signed char is greater than maximum"); - return -1; - } - if (i >= 0) - ((char *)ap->ob_item)[i] = (char)x; - return 0; + short x; + /* PyArg_Parse's 'b' formatter is for an unsigned char, therefore + must use the next size up that is signed ('h') and manually do + the overflow checking */ + if (!PyArg_Parse(v, "h;array item must be integer", &x)) + return -1; + else if (x < -128) { + PyErr_SetString(PyExc_OverflowError, + "signed char is less than minimum"); + return -1; + } + else if (x > 127) { + PyErr_SetString(PyExc_OverflowError, + "signed char is greater than maximum"); + return -1; + } + if (i >= 0) + ((char *)ap->ob_item)[i] = (char)x; + return 0; } static PyObject * BB_getitem(arrayobject *ap, Py_ssize_t i) { - long x = ((unsigned char *)ap->ob_item)[i]; - return PyLong_FromLong(x); + long x = ((unsigned char *)ap->ob_item)[i]; + return PyLong_FromLong(x); } static int BB_setitem(arrayobject *ap, Py_ssize_t i, PyObject *v) { - unsigned char x; - /* 'B' == unsigned char, maps to PyArg_Parse's 'b' formatter */ - if (!PyArg_Parse(v, "b;array item must be integer", &x)) - return -1; - if (i >= 0) - ((char *)ap->ob_item)[i] = x; - return 0; + unsigned char x; + /* 'B' == unsigned char, maps to PyArg_Parse's 'b' formatter */ + if (!PyArg_Parse(v, "b;array item must be integer", &x)) + return -1; + if (i >= 0) + ((char *)ap->ob_item)[i] = x; + return 0; } static PyObject * u_getitem(arrayobject *ap, Py_ssize_t i) { - return PyUnicode_FromUnicode(&((Py_UNICODE *) ap->ob_item)[i], 1); + return PyUnicode_FromUnicode(&((Py_UNICODE *) ap->ob_item)[i], 1); } static int u_setitem(arrayobject *ap, Py_ssize_t i, PyObject *v) { - Py_UNICODE *p; - Py_ssize_t len; + Py_UNICODE *p; + Py_ssize_t len; - if (!PyArg_Parse(v, "u#;array item must be unicode character", &p, &len)) - return -1; - if (len != 1) { - PyErr_SetString(PyExc_TypeError, - "array item must be unicode character"); - return -1; - } - if (i >= 0) - ((Py_UNICODE *)ap->ob_item)[i] = p[0]; - return 0; + if (!PyArg_Parse(v, "u#;array item must be unicode character", &p, &len)) + return -1; + if (len != 1) { + PyErr_SetString(PyExc_TypeError, + "array item must be unicode character"); + return -1; + } + if (i >= 0) + ((Py_UNICODE *)ap->ob_item)[i] = p[0]; + return 0; } static PyObject * h_getitem(arrayobject *ap, Py_ssize_t i) { - return PyLong_FromLong((long) ((short *)ap->ob_item)[i]); + return PyLong_FromLong((long) ((short *)ap->ob_item)[i]); } static int h_setitem(arrayobject *ap, Py_ssize_t i, PyObject *v) { - short x; - /* 'h' == signed short, maps to PyArg_Parse's 'h' formatter */ - if (!PyArg_Parse(v, "h;array item must be integer", &x)) - return -1; - if (i >= 0) - ((short *)ap->ob_item)[i] = x; - return 0; + short x; + /* 'h' == signed short, maps to PyArg_Parse's 'h' formatter */ + if (!PyArg_Parse(v, "h;array item must be integer", &x)) + return -1; + if (i >= 0) + ((short *)ap->ob_item)[i] = x; + return 0; } static PyObject * HH_getitem(arrayobject *ap, Py_ssize_t i) { - return PyLong_FromLong((long) ((unsigned short *)ap->ob_item)[i]); + return PyLong_FromLong((long) ((unsigned short *)ap->ob_item)[i]); } static int HH_setitem(arrayobject *ap, Py_ssize_t i, PyObject *v) { - int x; - /* PyArg_Parse's 'h' formatter is for a signed short, therefore - must use the next size up and manually do the overflow checking */ - if (!PyArg_Parse(v, "i;array item must be integer", &x)) - return -1; - else if (x < 0) { - PyErr_SetString(PyExc_OverflowError, - "unsigned short is less than minimum"); - return -1; - } - else if (x > USHRT_MAX) { - PyErr_SetString(PyExc_OverflowError, - "unsigned short is greater than maximum"); - return -1; - } - if (i >= 0) - ((short *)ap->ob_item)[i] = (short)x; - return 0; + int x; + /* PyArg_Parse's 'h' formatter is for a signed short, therefore + must use the next size up and manually do the overflow checking */ + if (!PyArg_Parse(v, "i;array item must be integer", &x)) + return -1; + else if (x < 0) { + PyErr_SetString(PyExc_OverflowError, + "unsigned short is less than minimum"); + return -1; + } + else if (x > USHRT_MAX) { + PyErr_SetString(PyExc_OverflowError, + "unsigned short is greater than maximum"); + return -1; + } + if (i >= 0) + ((short *)ap->ob_item)[i] = (short)x; + return 0; } static PyObject * i_getitem(arrayobject *ap, Py_ssize_t i) { - return PyLong_FromLong((long) ((int *)ap->ob_item)[i]); + return PyLong_FromLong((long) ((int *)ap->ob_item)[i]); } static int i_setitem(arrayobject *ap, Py_ssize_t i, PyObject *v) { - int x; - /* 'i' == signed int, maps to PyArg_Parse's 'i' formatter */ - if (!PyArg_Parse(v, "i;array item must be integer", &x)) - return -1; - if (i >= 0) - ((int *)ap->ob_item)[i] = x; - return 0; + int x; + /* 'i' == signed int, maps to PyArg_Parse's 'i' formatter */ + if (!PyArg_Parse(v, "i;array item must be integer", &x)) + return -1; + if (i >= 0) + ((int *)ap->ob_item)[i] = x; + return 0; } static PyObject * II_getitem(arrayobject *ap, Py_ssize_t i) { - return PyLong_FromUnsignedLong( - (unsigned long) ((unsigned int *)ap->ob_item)[i]); + return PyLong_FromUnsignedLong( + (unsigned long) ((unsigned int *)ap->ob_item)[i]); } static int II_setitem(arrayobject *ap, Py_ssize_t i, PyObject *v) { - unsigned long x; - if (PyLong_Check(v)) { - x = PyLong_AsUnsignedLong(v); - if (x == (unsigned long) -1 && PyErr_Occurred()) - return -1; - } - else { - long y; - if (!PyArg_Parse(v, "l;array item must be integer", &y)) - return -1; - if (y < 0) { - PyErr_SetString(PyExc_OverflowError, - "unsigned int is less than minimum"); - return -1; - } - x = (unsigned long)y; - - } - if (x > UINT_MAX) { - PyErr_SetString(PyExc_OverflowError, - "unsigned int is greater than maximum"); - return -1; - } - - if (i >= 0) - ((unsigned int *)ap->ob_item)[i] = (unsigned int)x; - return 0; + unsigned long x; + if (PyLong_Check(v)) { + x = PyLong_AsUnsignedLong(v); + if (x == (unsigned long) -1 && PyErr_Occurred()) + return -1; + } + else { + long y; + if (!PyArg_Parse(v, "l;array item must be integer", &y)) + return -1; + if (y < 0) { + PyErr_SetString(PyExc_OverflowError, + "unsigned int is less than minimum"); + return -1; + } + x = (unsigned long)y; + + } + if (x > UINT_MAX) { + PyErr_SetString(PyExc_OverflowError, + "unsigned int is greater than maximum"); + return -1; + } + + if (i >= 0) + ((unsigned int *)ap->ob_item)[i] = (unsigned int)x; + return 0; } static PyObject * l_getitem(arrayobject *ap, Py_ssize_t i) { - return PyLong_FromLong(((long *)ap->ob_item)[i]); + return PyLong_FromLong(((long *)ap->ob_item)[i]); } static int l_setitem(arrayobject *ap, Py_ssize_t i, PyObject *v) { - long x; - if (!PyArg_Parse(v, "l;array item must be integer", &x)) - return -1; - if (i >= 0) - ((long *)ap->ob_item)[i] = x; - return 0; + long x; + if (!PyArg_Parse(v, "l;array item must be integer", &x)) + return -1; + if (i >= 0) + ((long *)ap->ob_item)[i] = x; + return 0; } static PyObject * LL_getitem(arrayobject *ap, Py_ssize_t i) { - return PyLong_FromUnsignedLong(((unsigned long *)ap->ob_item)[i]); + return PyLong_FromUnsignedLong(((unsigned long *)ap->ob_item)[i]); } static int LL_setitem(arrayobject *ap, Py_ssize_t i, PyObject *v) { - unsigned long x; - if (PyLong_Check(v)) { - x = PyLong_AsUnsignedLong(v); - if (x == (unsigned long) -1 && PyErr_Occurred()) - return -1; - } - else { - long y; - if (!PyArg_Parse(v, "l;array item must be integer", &y)) - return -1; - if (y < 0) { - PyErr_SetString(PyExc_OverflowError, - "unsigned long is less than minimum"); - return -1; - } - x = (unsigned long)y; - - } - if (x > ULONG_MAX) { - PyErr_SetString(PyExc_OverflowError, - "unsigned long is greater than maximum"); - return -1; - } - - if (i >= 0) - ((unsigned long *)ap->ob_item)[i] = x; - return 0; + unsigned long x; + if (PyLong_Check(v)) { + x = PyLong_AsUnsignedLong(v); + if (x == (unsigned long) -1 && PyErr_Occurred()) + return -1; + } + else { + long y; + if (!PyArg_Parse(v, "l;array item must be integer", &y)) + return -1; + if (y < 0) { + PyErr_SetString(PyExc_OverflowError, + "unsigned long is less than minimum"); + return -1; + } + x = (unsigned long)y; + + } + if (x > ULONG_MAX) { + PyErr_SetString(PyExc_OverflowError, + "unsigned long is greater than maximum"); + return -1; + } + + if (i >= 0) + ((unsigned long *)ap->ob_item)[i] = x; + return 0; } static PyObject * f_getitem(arrayobject *ap, Py_ssize_t i) { - return PyFloat_FromDouble((double) ((float *)ap->ob_item)[i]); + return PyFloat_FromDouble((double) ((float *)ap->ob_item)[i]); } static int f_setitem(arrayobject *ap, Py_ssize_t i, PyObject *v) { - float x; - if (!PyArg_Parse(v, "f;array item must be float", &x)) - return -1; - if (i >= 0) - ((float *)ap->ob_item)[i] = x; - return 0; + float x; + if (!PyArg_Parse(v, "f;array item must be float", &x)) + return -1; + if (i >= 0) + ((float *)ap->ob_item)[i] = x; + return 0; } static PyObject * d_getitem(arrayobject *ap, Py_ssize_t i) { - return PyFloat_FromDouble(((double *)ap->ob_item)[i]); + return PyFloat_FromDouble(((double *)ap->ob_item)[i]); } static int d_setitem(arrayobject *ap, Py_ssize_t i, PyObject *v) { - double x; - if (!PyArg_Parse(v, "d;array item must be float", &x)) - return -1; - if (i >= 0) - ((double *)ap->ob_item)[i] = x; - return 0; + double x; + if (!PyArg_Parse(v, "d;array item must be float", &x)) + return -1; + if (i >= 0) + ((double *)ap->ob_item)[i] = x; + return 0; } /* Description of types */ static struct arraydescr descriptors[] = { - {'b', 1, b_getitem, b_setitem, "b"}, - {'B', 1, BB_getitem, BB_setitem, "B"}, - {'u', sizeof(Py_UNICODE), u_getitem, u_setitem, "u"}, - {'h', sizeof(short), h_getitem, h_setitem, "h"}, - {'H', sizeof(short), HH_getitem, HH_setitem, "H"}, - {'i', sizeof(int), i_getitem, i_setitem, "i"}, - {'I', sizeof(int), II_getitem, II_setitem, "I"}, - {'l', sizeof(long), l_getitem, l_setitem, "l"}, - {'L', sizeof(long), LL_getitem, LL_setitem, "L"}, - {'f', sizeof(float), f_getitem, f_setitem, "f"}, - {'d', sizeof(double), d_getitem, d_setitem, "d"}, - {'\0', 0, 0, 0, 0} /* Sentinel */ + {'b', 1, b_getitem, b_setitem, "b"}, + {'B', 1, BB_getitem, BB_setitem, "B"}, + {'u', sizeof(Py_UNICODE), u_getitem, u_setitem, "u"}, + {'h', sizeof(short), h_getitem, h_setitem, "h"}, + {'H', sizeof(short), HH_getitem, HH_setitem, "H"}, + {'i', sizeof(int), i_getitem, i_setitem, "i"}, + {'I', sizeof(int), II_getitem, II_setitem, "I"}, + {'l', sizeof(long), l_getitem, l_setitem, "l"}, + {'L', sizeof(long), LL_getitem, LL_setitem, "L"}, + {'f', sizeof(float), f_getitem, f_setitem, "f"}, + {'d', sizeof(double), d_getitem, d_setitem, "d"}, + {'\0', 0, 0, 0, 0} /* Sentinel */ }; /**************************************************************************** @@ -412,79 +412,79 @@ static PyObject * newarrayobject(PyTypeObject *type, Py_ssize_t size, struct arraydescr *descr) { - arrayobject *op; - size_t nbytes; + arrayobject *op; + size_t nbytes; - if (size < 0) { - PyErr_BadInternalCall(); - return NULL; - } - - nbytes = size * descr->itemsize; - /* Check for overflow */ - if (nbytes / descr->itemsize != (size_t)size) { - return PyErr_NoMemory(); - } - op = (arrayobject *) type->tp_alloc(type, 0); - if (op == NULL) { - return NULL; - } - op->ob_descr = descr; - op->allocated = size; - op->weakreflist = NULL; - Py_SIZE(op) = size; - if (size <= 0) { - op->ob_item = NULL; - } - else { - op->ob_item = PyMem_NEW(char, nbytes); - if (op->ob_item == NULL) { - Py_DECREF(op); - return PyErr_NoMemory(); - } - } - op->ob_exports = 0; - return (PyObject *) op; + if (size < 0) { + PyErr_BadInternalCall(); + return NULL; + } + + nbytes = size * descr->itemsize; + /* Check for overflow */ + if (nbytes / descr->itemsize != (size_t)size) { + return PyErr_NoMemory(); + } + op = (arrayobject *) type->tp_alloc(type, 0); + if (op == NULL) { + return NULL; + } + op->ob_descr = descr; + op->allocated = size; + op->weakreflist = NULL; + Py_SIZE(op) = size; + if (size <= 0) { + op->ob_item = NULL; + } + else { + op->ob_item = PyMem_NEW(char, nbytes); + if (op->ob_item == NULL) { + Py_DECREF(op); + return PyErr_NoMemory(); + } + } + op->ob_exports = 0; + return (PyObject *) op; } static PyObject * getarrayitem(PyObject *op, Py_ssize_t i) { - register arrayobject *ap; - assert(array_Check(op)); - ap = (arrayobject *)op; - assert(i>=0 && iob_descr->getitem)(ap, i); + register arrayobject *ap; + assert(array_Check(op)); + ap = (arrayobject *)op; + assert(i>=0 && iob_descr->getitem)(ap, i); } static int ins1(arrayobject *self, Py_ssize_t where, PyObject *v) { - char *items; - Py_ssize_t n = Py_SIZE(self); - if (v == NULL) { - PyErr_BadInternalCall(); - return -1; - } - if ((*self->ob_descr->setitem)(self, -1, v) < 0) - return -1; - - if (array_resize(self, n+1) == -1) - return -1; - items = self->ob_item; - if (where < 0) { - where += n; - if (where < 0) - where = 0; - } - if (where > n) - where = n; - /* appends don't need to call memmove() */ - if (where != n) - memmove(items + (where+1)*self->ob_descr->itemsize, - items + where*self->ob_descr->itemsize, - (n-where)*self->ob_descr->itemsize); - return (*self->ob_descr->setitem)(self, where, v); + char *items; + Py_ssize_t n = Py_SIZE(self); + if (v == NULL) { + PyErr_BadInternalCall(); + return -1; + } + if ((*self->ob_descr->setitem)(self, -1, v) < 0) + return -1; + + if (array_resize(self, n+1) == -1) + return -1; + items = self->ob_item; + if (where < 0) { + where += n; + if (where < 0) + where = 0; + } + if (where > n) + where = n; + /* appends don't need to call memmove() */ + if (where != n) + memmove(items + (where+1)*self->ob_descr->itemsize, + items + where*self->ob_descr->itemsize, + (n-where)*self->ob_descr->itemsize); + return (*self->ob_descr->setitem)(self, where, v); } /* Methods */ @@ -492,141 +492,141 @@ static void array_dealloc(arrayobject *op) { - if (op->weakreflist != NULL) - PyObject_ClearWeakRefs((PyObject *) op); - if (op->ob_item != NULL) - PyMem_DEL(op->ob_item); - Py_TYPE(op)->tp_free((PyObject *)op); + if (op->weakreflist != NULL) + PyObject_ClearWeakRefs((PyObject *) op); + if (op->ob_item != NULL) + PyMem_DEL(op->ob_item); + Py_TYPE(op)->tp_free((PyObject *)op); } static PyObject * array_richcompare(PyObject *v, PyObject *w, int op) { - arrayobject *va, *wa; - PyObject *vi = NULL; - PyObject *wi = NULL; - Py_ssize_t i, k; - PyObject *res; - - if (!array_Check(v) || !array_Check(w)) { - Py_INCREF(Py_NotImplemented); - return Py_NotImplemented; - } - - va = (arrayobject *)v; - wa = (arrayobject *)w; - - if (Py_SIZE(va) != Py_SIZE(wa) && (op == Py_EQ || op == Py_NE)) { - /* Shortcut: if the lengths differ, the arrays differ */ - if (op == Py_EQ) - res = Py_False; - else - res = Py_True; - Py_INCREF(res); - return res; - } - - /* Search for the first index where items are different */ - k = 1; - for (i = 0; i < Py_SIZE(va) && i < Py_SIZE(wa); i++) { - vi = getarrayitem(v, i); - wi = getarrayitem(w, i); - if (vi == NULL || wi == NULL) { - Py_XDECREF(vi); - Py_XDECREF(wi); - return NULL; - } - k = PyObject_RichCompareBool(vi, wi, Py_EQ); - if (k == 0) - break; /* Keeping vi and wi alive! */ - Py_DECREF(vi); - Py_DECREF(wi); - if (k < 0) - return NULL; - } - - if (k) { - /* No more items to compare -- compare sizes */ - Py_ssize_t vs = Py_SIZE(va); - Py_ssize_t ws = Py_SIZE(wa); - int cmp; - switch (op) { - case Py_LT: cmp = vs < ws; break; - case Py_LE: cmp = vs <= ws; break; - case Py_EQ: cmp = vs == ws; break; - case Py_NE: cmp = vs != ws; break; - case Py_GT: cmp = vs > ws; break; - case Py_GE: cmp = vs >= ws; break; - default: return NULL; /* cannot happen */ - } - if (cmp) - res = Py_True; - else - res = Py_False; - Py_INCREF(res); - return res; - } - - /* We have an item that differs. First, shortcuts for EQ/NE */ - if (op == Py_EQ) { - Py_INCREF(Py_False); - res = Py_False; - } - else if (op == Py_NE) { - Py_INCREF(Py_True); - res = Py_True; - } - else { - /* Compare the final item again using the proper operator */ - res = PyObject_RichCompare(vi, wi, op); - } - Py_DECREF(vi); - Py_DECREF(wi); - return res; + arrayobject *va, *wa; + PyObject *vi = NULL; + PyObject *wi = NULL; + Py_ssize_t i, k; + PyObject *res; + + if (!array_Check(v) || !array_Check(w)) { + Py_INCREF(Py_NotImplemented); + return Py_NotImplemented; + } + + va = (arrayobject *)v; + wa = (arrayobject *)w; + + if (Py_SIZE(va) != Py_SIZE(wa) && (op == Py_EQ || op == Py_NE)) { + /* Shortcut: if the lengths differ, the arrays differ */ + if (op == Py_EQ) + res = Py_False; + else + res = Py_True; + Py_INCREF(res); + return res; + } + + /* Search for the first index where items are different */ + k = 1; + for (i = 0; i < Py_SIZE(va) && i < Py_SIZE(wa); i++) { + vi = getarrayitem(v, i); + wi = getarrayitem(w, i); + if (vi == NULL || wi == NULL) { + Py_XDECREF(vi); + Py_XDECREF(wi); + return NULL; + } + k = PyObject_RichCompareBool(vi, wi, Py_EQ); + if (k == 0) + break; /* Keeping vi and wi alive! */ + Py_DECREF(vi); + Py_DECREF(wi); + if (k < 0) + return NULL; + } + + if (k) { + /* No more items to compare -- compare sizes */ + Py_ssize_t vs = Py_SIZE(va); + Py_ssize_t ws = Py_SIZE(wa); + int cmp; + switch (op) { + case Py_LT: cmp = vs < ws; break; + case Py_LE: cmp = vs <= ws; break; + case Py_EQ: cmp = vs == ws; break; + case Py_NE: cmp = vs != ws; break; + case Py_GT: cmp = vs > ws; break; + case Py_GE: cmp = vs >= ws; break; + default: return NULL; /* cannot happen */ + } + if (cmp) + res = Py_True; + else + res = Py_False; + Py_INCREF(res); + return res; + } + + /* We have an item that differs. First, shortcuts for EQ/NE */ + if (op == Py_EQ) { + Py_INCREF(Py_False); + res = Py_False; + } + else if (op == Py_NE) { + Py_INCREF(Py_True); + res = Py_True; + } + else { + /* Compare the final item again using the proper operator */ + res = PyObject_RichCompare(vi, wi, op); + } + Py_DECREF(vi); + Py_DECREF(wi); + return res; } static Py_ssize_t array_length(arrayobject *a) { - return Py_SIZE(a); + return Py_SIZE(a); } static PyObject * array_item(arrayobject *a, Py_ssize_t i) { - if (i < 0 || i >= Py_SIZE(a)) { - PyErr_SetString(PyExc_IndexError, "array index out of range"); - return NULL; - } - return getarrayitem((PyObject *)a, i); + if (i < 0 || i >= Py_SIZE(a)) { + PyErr_SetString(PyExc_IndexError, "array index out of range"); + return NULL; + } + return getarrayitem((PyObject *)a, i); } static PyObject * array_slice(arrayobject *a, Py_ssize_t ilow, Py_ssize_t ihigh) { - arrayobject *np; - if (ilow < 0) - ilow = 0; - else if (ilow > Py_SIZE(a)) - ilow = Py_SIZE(a); - if (ihigh < 0) - ihigh = 0; - if (ihigh < ilow) - ihigh = ilow; - else if (ihigh > Py_SIZE(a)) - ihigh = Py_SIZE(a); - np = (arrayobject *) newarrayobject(&Arraytype, ihigh - ilow, a->ob_descr); - if (np == NULL) - return NULL; - memcpy(np->ob_item, a->ob_item + ilow * a->ob_descr->itemsize, - (ihigh-ilow) * a->ob_descr->itemsize); - return (PyObject *)np; + arrayobject *np; + if (ilow < 0) + ilow = 0; + else if (ilow > Py_SIZE(a)) + ilow = Py_SIZE(a); + if (ihigh < 0) + ihigh = 0; + if (ihigh < ilow) + ihigh = ilow; + else if (ihigh > Py_SIZE(a)) + ihigh = Py_SIZE(a); + np = (arrayobject *) newarrayobject(&Arraytype, ihigh - ilow, a->ob_descr); + if (np == NULL) + return NULL; + memcpy(np->ob_item, a->ob_item + ilow * a->ob_descr->itemsize, + (ihigh-ilow) * a->ob_descr->itemsize); + return (PyObject *)np; } static PyObject * array_copy(arrayobject *a, PyObject *unused) { - return array_slice(a, 0, Py_SIZE(a)); + return array_slice(a, 0, Py_SIZE(a)); } PyDoc_STRVAR(copy_doc, @@ -637,278 +637,278 @@ static PyObject * array_concat(arrayobject *a, PyObject *bb) { - Py_ssize_t size; - arrayobject *np; - if (!array_Check(bb)) { - PyErr_Format(PyExc_TypeError, - "can only append array (not \"%.200s\") to array", - Py_TYPE(bb)->tp_name); - return NULL; - } + Py_ssize_t size; + arrayobject *np; + if (!array_Check(bb)) { + PyErr_Format(PyExc_TypeError, + "can only append array (not \"%.200s\") to array", + Py_TYPE(bb)->tp_name); + return NULL; + } #define b ((arrayobject *)bb) - if (a->ob_descr != b->ob_descr) { - PyErr_BadArgument(); - return NULL; - } - if (Py_SIZE(a) > PY_SSIZE_T_MAX - Py_SIZE(b)) { - return PyErr_NoMemory(); - } - size = Py_SIZE(a) + Py_SIZE(b); - np = (arrayobject *) newarrayobject(&Arraytype, size, a->ob_descr); - if (np == NULL) { - return NULL; - } - memcpy(np->ob_item, a->ob_item, Py_SIZE(a)*a->ob_descr->itemsize); - memcpy(np->ob_item + Py_SIZE(a)*a->ob_descr->itemsize, - b->ob_item, Py_SIZE(b)*b->ob_descr->itemsize); - return (PyObject *)np; + if (a->ob_descr != b->ob_descr) { + PyErr_BadArgument(); + return NULL; + } + if (Py_SIZE(a) > PY_SSIZE_T_MAX - Py_SIZE(b)) { + return PyErr_NoMemory(); + } + size = Py_SIZE(a) + Py_SIZE(b); + np = (arrayobject *) newarrayobject(&Arraytype, size, a->ob_descr); + if (np == NULL) { + return NULL; + } + memcpy(np->ob_item, a->ob_item, Py_SIZE(a)*a->ob_descr->itemsize); + memcpy(np->ob_item + Py_SIZE(a)*a->ob_descr->itemsize, + b->ob_item, Py_SIZE(b)*b->ob_descr->itemsize); + return (PyObject *)np; #undef b } static PyObject * array_repeat(arrayobject *a, Py_ssize_t n) { - Py_ssize_t i; - Py_ssize_t size; - arrayobject *np; - char *p; - Py_ssize_t nbytes; - if (n < 0) - n = 0; - if ((Py_SIZE(a) != 0) && (n > PY_SSIZE_T_MAX / Py_SIZE(a))) { - return PyErr_NoMemory(); - } - size = Py_SIZE(a) * n; - np = (arrayobject *) newarrayobject(&Arraytype, size, a->ob_descr); - if (np == NULL) - return NULL; - p = np->ob_item; - nbytes = Py_SIZE(a) * a->ob_descr->itemsize; - for (i = 0; i < n; i++) { - memcpy(p, a->ob_item, nbytes); - p += nbytes; - } - return (PyObject *) np; + Py_ssize_t i; + Py_ssize_t size; + arrayobject *np; + char *p; + Py_ssize_t nbytes; + if (n < 0) + n = 0; + if ((Py_SIZE(a) != 0) && (n > PY_SSIZE_T_MAX / Py_SIZE(a))) { + return PyErr_NoMemory(); + } + size = Py_SIZE(a) * n; + np = (arrayobject *) newarrayobject(&Arraytype, size, a->ob_descr); + if (np == NULL) + return NULL; + p = np->ob_item; + nbytes = Py_SIZE(a) * a->ob_descr->itemsize; + for (i = 0; i < n; i++) { + memcpy(p, a->ob_item, nbytes); + p += nbytes; + } + return (PyObject *) np; } static int array_ass_slice(arrayobject *a, Py_ssize_t ilow, Py_ssize_t ihigh, PyObject *v) { - char *item; - Py_ssize_t n; /* Size of replacement array */ - Py_ssize_t d; /* Change in size */ + char *item; + Py_ssize_t n; /* Size of replacement array */ + Py_ssize_t d; /* Change in size */ #define b ((arrayobject *)v) - if (v == NULL) - n = 0; - else if (array_Check(v)) { - n = Py_SIZE(b); - if (a == b) { - /* Special case "a[i:j] = a" -- copy b first */ - int ret; - v = array_slice(b, 0, n); - if (!v) - return -1; - ret = array_ass_slice(a, ilow, ihigh, v); - Py_DECREF(v); - return ret; - } - if (b->ob_descr != a->ob_descr) { - PyErr_BadArgument(); - return -1; - } - } - else { - PyErr_Format(PyExc_TypeError, - "can only assign array (not \"%.200s\") to array slice", - Py_TYPE(v)->tp_name); - return -1; - } - if (ilow < 0) - ilow = 0; - else if (ilow > Py_SIZE(a)) - ilow = Py_SIZE(a); - if (ihigh < 0) - ihigh = 0; - if (ihigh < ilow) - ihigh = ilow; - else if (ihigh > Py_SIZE(a)) - ihigh = Py_SIZE(a); - item = a->ob_item; - d = n - (ihigh-ilow); - /* Issue #4509: If the array has exported buffers and the slice - assignment would change the size of the array, fail early to make - sure we don't modify it. */ - if (d != 0 && a->ob_exports > 0) { - PyErr_SetString(PyExc_BufferError, - "cannot resize an array that is exporting buffers"); - return -1; - } - if (d < 0) { /* Delete -d items */ - memmove(item + (ihigh+d)*a->ob_descr->itemsize, - item + ihigh*a->ob_descr->itemsize, - (Py_SIZE(a)-ihigh)*a->ob_descr->itemsize); - if (array_resize(a, Py_SIZE(a) + d) == -1) - return -1; - } - else if (d > 0) { /* Insert d items */ - if (array_resize(a, Py_SIZE(a) + d)) - return -1; - memmove(item + (ihigh+d)*a->ob_descr->itemsize, - item + ihigh*a->ob_descr->itemsize, - (Py_SIZE(a)-ihigh)*a->ob_descr->itemsize); - } - if (n > 0) - memcpy(item + ilow*a->ob_descr->itemsize, b->ob_item, - n*b->ob_descr->itemsize); - return 0; + if (v == NULL) + n = 0; + else if (array_Check(v)) { + n = Py_SIZE(b); + if (a == b) { + /* Special case "a[i:j] = a" -- copy b first */ + int ret; + v = array_slice(b, 0, n); + if (!v) + return -1; + ret = array_ass_slice(a, ilow, ihigh, v); + Py_DECREF(v); + return ret; + } + if (b->ob_descr != a->ob_descr) { + PyErr_BadArgument(); + return -1; + } + } + else { + PyErr_Format(PyExc_TypeError, + "can only assign array (not \"%.200s\") to array slice", + Py_TYPE(v)->tp_name); + return -1; + } + if (ilow < 0) + ilow = 0; + else if (ilow > Py_SIZE(a)) + ilow = Py_SIZE(a); + if (ihigh < 0) + ihigh = 0; + if (ihigh < ilow) + ihigh = ilow; + else if (ihigh > Py_SIZE(a)) + ihigh = Py_SIZE(a); + item = a->ob_item; + d = n - (ihigh-ilow); + /* Issue #4509: If the array has exported buffers and the slice + assignment would change the size of the array, fail early to make + sure we don't modify it. */ + if (d != 0 && a->ob_exports > 0) { + PyErr_SetString(PyExc_BufferError, + "cannot resize an array that is exporting buffers"); + return -1; + } + if (d < 0) { /* Delete -d items */ + memmove(item + (ihigh+d)*a->ob_descr->itemsize, + item + ihigh*a->ob_descr->itemsize, + (Py_SIZE(a)-ihigh)*a->ob_descr->itemsize); + if (array_resize(a, Py_SIZE(a) + d) == -1) + return -1; + } + else if (d > 0) { /* Insert d items */ + if (array_resize(a, Py_SIZE(a) + d)) + return -1; + memmove(item + (ihigh+d)*a->ob_descr->itemsize, + item + ihigh*a->ob_descr->itemsize, + (Py_SIZE(a)-ihigh)*a->ob_descr->itemsize); + } + if (n > 0) + memcpy(item + ilow*a->ob_descr->itemsize, b->ob_item, + n*b->ob_descr->itemsize); + return 0; #undef b } static int array_ass_item(arrayobject *a, Py_ssize_t i, PyObject *v) { - if (i < 0 || i >= Py_SIZE(a)) { - PyErr_SetString(PyExc_IndexError, - "array assignment index out of range"); - return -1; - } - if (v == NULL) - return array_ass_slice(a, i, i+1, v); - return (*a->ob_descr->setitem)(a, i, v); + if (i < 0 || i >= Py_SIZE(a)) { + PyErr_SetString(PyExc_IndexError, + "array assignment index out of range"); + return -1; + } + if (v == NULL) + return array_ass_slice(a, i, i+1, v); + return (*a->ob_descr->setitem)(a, i, v); } static int setarrayitem(PyObject *a, Py_ssize_t i, PyObject *v) { - assert(array_Check(a)); - return array_ass_item((arrayobject *)a, i, v); + assert(array_Check(a)); + return array_ass_item((arrayobject *)a, i, v); } static int array_iter_extend(arrayobject *self, PyObject *bb) { - PyObject *it, *v; + PyObject *it, *v; - it = PyObject_GetIter(bb); - if (it == NULL) - return -1; - - while ((v = PyIter_Next(it)) != NULL) { - if (ins1(self, (int) Py_SIZE(self), v) != 0) { - Py_DECREF(v); - Py_DECREF(it); - return -1; - } - Py_DECREF(v); - } - Py_DECREF(it); - if (PyErr_Occurred()) - return -1; - return 0; + it = PyObject_GetIter(bb); + if (it == NULL) + return -1; + + while ((v = PyIter_Next(it)) != NULL) { + if (ins1(self, (int) Py_SIZE(self), v) != 0) { + Py_DECREF(v); + Py_DECREF(it); + return -1; + } + Py_DECREF(v); + } + Py_DECREF(it); + if (PyErr_Occurred()) + return -1; + return 0; } static int array_do_extend(arrayobject *self, PyObject *bb) { - Py_ssize_t size, oldsize, bbsize; - - if (!array_Check(bb)) - return array_iter_extend(self, bb); + Py_ssize_t size, oldsize, bbsize; + + if (!array_Check(bb)) + return array_iter_extend(self, bb); #define b ((arrayobject *)bb) - if (self->ob_descr != b->ob_descr) { - PyErr_SetString(PyExc_TypeError, - "can only extend with array of same kind"); - return -1; - } - if ((Py_SIZE(self) > PY_SSIZE_T_MAX - Py_SIZE(b)) || - ((Py_SIZE(self) + Py_SIZE(b)) > PY_SSIZE_T_MAX / self->ob_descr->itemsize)) { - PyErr_NoMemory(); - return -1; - } - oldsize = Py_SIZE(self); - /* Get the size of bb before resizing the array since bb could be self. */ - bbsize = Py_SIZE(bb); - size = oldsize + Py_SIZE(b); - if (array_resize(self, size) == -1) - return -1; - memcpy(self->ob_item + oldsize * self->ob_descr->itemsize, - b->ob_item, bbsize * b->ob_descr->itemsize); + if (self->ob_descr != b->ob_descr) { + PyErr_SetString(PyExc_TypeError, + "can only extend with array of same kind"); + return -1; + } + if ((Py_SIZE(self) > PY_SSIZE_T_MAX - Py_SIZE(b)) || + ((Py_SIZE(self) + Py_SIZE(b)) > PY_SSIZE_T_MAX / self->ob_descr->itemsize)) { + PyErr_NoMemory(); + return -1; + } + oldsize = Py_SIZE(self); + /* Get the size of bb before resizing the array since bb could be self. */ + bbsize = Py_SIZE(bb); + size = oldsize + Py_SIZE(b); + if (array_resize(self, size) == -1) + return -1; + memcpy(self->ob_item + oldsize * self->ob_descr->itemsize, + b->ob_item, bbsize * b->ob_descr->itemsize); - return 0; + return 0; #undef b } static PyObject * array_inplace_concat(arrayobject *self, PyObject *bb) { - if (!array_Check(bb)) { - PyErr_Format(PyExc_TypeError, - "can only extend array with array (not \"%.200s\")", - Py_TYPE(bb)->tp_name); - return NULL; - } - if (array_do_extend(self, bb) == -1) - return NULL; - Py_INCREF(self); - return (PyObject *)self; + if (!array_Check(bb)) { + PyErr_Format(PyExc_TypeError, + "can only extend array with array (not \"%.200s\")", + Py_TYPE(bb)->tp_name); + return NULL; + } + if (array_do_extend(self, bb) == -1) + return NULL; + Py_INCREF(self); + return (PyObject *)self; } static PyObject * array_inplace_repeat(arrayobject *self, Py_ssize_t n) { - char *items, *p; - Py_ssize_t size, i; + char *items, *p; + Py_ssize_t size, i; - if (Py_SIZE(self) > 0) { - if (n < 0) - n = 0; - items = self->ob_item; - if ((self->ob_descr->itemsize != 0) && - (Py_SIZE(self) > PY_SSIZE_T_MAX / self->ob_descr->itemsize)) { - return PyErr_NoMemory(); - } - size = Py_SIZE(self) * self->ob_descr->itemsize; - if (n > 0 && size > PY_SSIZE_T_MAX / n) { - return PyErr_NoMemory(); - } - if (array_resize(self, n * Py_SIZE(self)) == -1) - return NULL; - items = p = self->ob_item; - for (i = 1; i < n; i++) { - p += size; - memcpy(p, items, size); - } - } - Py_INCREF(self); - return (PyObject *)self; + if (Py_SIZE(self) > 0) { + if (n < 0) + n = 0; + items = self->ob_item; + if ((self->ob_descr->itemsize != 0) && + (Py_SIZE(self) > PY_SSIZE_T_MAX / self->ob_descr->itemsize)) { + return PyErr_NoMemory(); + } + size = Py_SIZE(self) * self->ob_descr->itemsize; + if (n > 0 && size > PY_SSIZE_T_MAX / n) { + return PyErr_NoMemory(); + } + if (array_resize(self, n * Py_SIZE(self)) == -1) + return NULL; + items = p = self->ob_item; + for (i = 1; i < n; i++) { + p += size; + memcpy(p, items, size); + } + } + Py_INCREF(self); + return (PyObject *)self; } static PyObject * ins(arrayobject *self, Py_ssize_t where, PyObject *v) { - if (ins1(self, where, v) != 0) - return NULL; - Py_INCREF(Py_None); - return Py_None; + if (ins1(self, where, v) != 0) + return NULL; + Py_INCREF(Py_None); + return Py_None; } static PyObject * array_count(arrayobject *self, PyObject *v) { - Py_ssize_t count = 0; - Py_ssize_t i; + Py_ssize_t count = 0; + Py_ssize_t i; - for (i = 0; i < Py_SIZE(self); i++) { - PyObject *selfi = getarrayitem((PyObject *)self, i); - int cmp = PyObject_RichCompareBool(selfi, v, Py_EQ); - Py_DECREF(selfi); - if (cmp > 0) - count++; - else if (cmp < 0) - return NULL; - } - return PyLong_FromSsize_t(count); + for (i = 0; i < Py_SIZE(self); i++) { + PyObject *selfi = getarrayitem((PyObject *)self, i); + int cmp = PyObject_RichCompareBool(selfi, v, Py_EQ); + Py_DECREF(selfi); + if (cmp > 0) + count++; + else if (cmp < 0) + return NULL; + } + return PyLong_FromSsize_t(count); } PyDoc_STRVAR(count_doc, @@ -919,20 +919,20 @@ static PyObject * array_index(arrayobject *self, PyObject *v) { - Py_ssize_t i; + Py_ssize_t i; - for (i = 0; i < Py_SIZE(self); i++) { - PyObject *selfi = getarrayitem((PyObject *)self, i); - int cmp = PyObject_RichCompareBool(selfi, v, Py_EQ); - Py_DECREF(selfi); - if (cmp > 0) { - return PyLong_FromLong((long)i); - } - else if (cmp < 0) - return NULL; - } - PyErr_SetString(PyExc_ValueError, "array.index(x): x not in list"); - return NULL; + for (i = 0; i < Py_SIZE(self); i++) { + PyObject *selfi = getarrayitem((PyObject *)self, i); + int cmp = PyObject_RichCompareBool(selfi, v, Py_EQ); + Py_DECREF(selfi); + if (cmp > 0) { + return PyLong_FromLong((long)i); + } + else if (cmp < 0) + return NULL; + } + PyErr_SetString(PyExc_ValueError, "array.index(x): x not in list"); + return NULL; } PyDoc_STRVAR(index_doc, @@ -943,38 +943,38 @@ static int array_contains(arrayobject *self, PyObject *v) { - Py_ssize_t i; - int cmp; + Py_ssize_t i; + int cmp; - for (i = 0, cmp = 0 ; cmp == 0 && i < Py_SIZE(self); i++) { - PyObject *selfi = getarrayitem((PyObject *)self, i); - cmp = PyObject_RichCompareBool(selfi, v, Py_EQ); - Py_DECREF(selfi); - } - return cmp; + for (i = 0, cmp = 0 ; cmp == 0 && i < Py_SIZE(self); i++) { + PyObject *selfi = getarrayitem((PyObject *)self, i); + cmp = PyObject_RichCompareBool(selfi, v, Py_EQ); + Py_DECREF(selfi); + } + return cmp; } static PyObject * array_remove(arrayobject *self, PyObject *v) { - int i; + int i; - for (i = 0; i < Py_SIZE(self); i++) { - PyObject *selfi = getarrayitem((PyObject *)self,i); - int cmp = PyObject_RichCompareBool(selfi, v, Py_EQ); - Py_DECREF(selfi); - if (cmp > 0) { - if (array_ass_slice(self, i, i+1, - (PyObject *)NULL) != 0) - return NULL; - Py_INCREF(Py_None); - return Py_None; - } - else if (cmp < 0) - return NULL; - } - PyErr_SetString(PyExc_ValueError, "array.remove(x): x not in list"); - return NULL; + for (i = 0; i < Py_SIZE(self); i++) { + PyObject *selfi = getarrayitem((PyObject *)self,i); + int cmp = PyObject_RichCompareBool(selfi, v, Py_EQ); + Py_DECREF(selfi); + if (cmp > 0) { + if (array_ass_slice(self, i, i+1, + (PyObject *)NULL) != 0) + return NULL; + Py_INCREF(Py_None); + return Py_None; + } + else if (cmp < 0) + return NULL; + } + PyErr_SetString(PyExc_ValueError, "array.remove(x): x not in list"); + return NULL; } PyDoc_STRVAR(remove_doc, @@ -985,27 +985,27 @@ static PyObject * array_pop(arrayobject *self, PyObject *args) { - Py_ssize_t i = -1; - PyObject *v; - if (!PyArg_ParseTuple(args, "|n:pop", &i)) - return NULL; - if (Py_SIZE(self) == 0) { - /* Special-case most common failure cause */ - PyErr_SetString(PyExc_IndexError, "pop from empty array"); - return NULL; - } - if (i < 0) - i += Py_SIZE(self); - if (i < 0 || i >= Py_SIZE(self)) { - PyErr_SetString(PyExc_IndexError, "pop index out of range"); - return NULL; - } - v = getarrayitem((PyObject *)self,i); - if (array_ass_slice(self, i, i+1, (PyObject *)NULL) != 0) { - Py_DECREF(v); - return NULL; - } - return v; + Py_ssize_t i = -1; + PyObject *v; + if (!PyArg_ParseTuple(args, "|n:pop", &i)) + return NULL; + if (Py_SIZE(self) == 0) { + /* Special-case most common failure cause */ + PyErr_SetString(PyExc_IndexError, "pop from empty array"); + return NULL; + } + if (i < 0) + i += Py_SIZE(self); + if (i < 0 || i >= Py_SIZE(self)) { + PyErr_SetString(PyExc_IndexError, "pop index out of range"); + return NULL; + } + v = getarrayitem((PyObject *)self,i); + if (array_ass_slice(self, i, i+1, (PyObject *)NULL) != 0) { + Py_DECREF(v); + return NULL; + } + return v; } PyDoc_STRVAR(pop_doc, @@ -1016,10 +1016,10 @@ static PyObject * array_extend(arrayobject *self, PyObject *bb) { - if (array_do_extend(self, bb) == -1) - return NULL; - Py_INCREF(Py_None); - return Py_None; + if (array_do_extend(self, bb) == -1) + return NULL; + Py_INCREF(Py_None); + return Py_None; } PyDoc_STRVAR(extend_doc, @@ -1030,11 +1030,11 @@ static PyObject * array_insert(arrayobject *self, PyObject *args) { - Py_ssize_t i; - PyObject *v; - if (!PyArg_ParseTuple(args, "nO:insert", &i, &v)) - return NULL; - return ins(self, i, v); + Py_ssize_t i; + PyObject *v; + if (!PyArg_ParseTuple(args, "nO:insert", &i, &v)) + return NULL; + return ins(self, i, v); } PyDoc_STRVAR(insert_doc, @@ -1046,15 +1046,15 @@ static PyObject * array_buffer_info(arrayobject *self, PyObject *unused) { - PyObject* retval = NULL; - retval = PyTuple_New(2); - if (!retval) - return NULL; + PyObject* retval = NULL; + retval = PyTuple_New(2); + if (!retval) + return NULL; - PyTuple_SET_ITEM(retval, 0, PyLong_FromVoidPtr(self->ob_item)); - PyTuple_SET_ITEM(retval, 1, PyLong_FromLong((long)(Py_SIZE(self)))); + PyTuple_SET_ITEM(retval, 0, PyLong_FromVoidPtr(self->ob_item)); + PyTuple_SET_ITEM(retval, 1, PyLong_FromLong((long)(Py_SIZE(self)))); - return retval; + return retval; } PyDoc_STRVAR(buffer_info_doc, @@ -1069,7 +1069,7 @@ static PyObject * array_append(arrayobject *self, PyObject *v) { - return ins(self, (int) Py_SIZE(self), v); + return ins(self, (int) Py_SIZE(self), v); } PyDoc_STRVAR(append_doc, @@ -1081,52 +1081,52 @@ static PyObject * array_byteswap(arrayobject *self, PyObject *unused) { - char *p; - Py_ssize_t i; + char *p; + Py_ssize_t i; - switch (self->ob_descr->itemsize) { - case 1: - break; - case 2: - for (p = self->ob_item, i = Py_SIZE(self); --i >= 0; p += 2) { - char p0 = p[0]; - p[0] = p[1]; - p[1] = p0; - } - break; - case 4: - for (p = self->ob_item, i = Py_SIZE(self); --i >= 0; p += 4) { - char p0 = p[0]; - char p1 = p[1]; - p[0] = p[3]; - p[1] = p[2]; - p[2] = p1; - p[3] = p0; - } - break; - case 8: - for (p = self->ob_item, i = Py_SIZE(self); --i >= 0; p += 8) { - char p0 = p[0]; - char p1 = p[1]; - char p2 = p[2]; - char p3 = p[3]; - p[0] = p[7]; - p[1] = p[6]; - p[2] = p[5]; - p[3] = p[4]; - p[4] = p3; - p[5] = p2; - p[6] = p1; - p[7] = p0; - } - break; - default: - PyErr_SetString(PyExc_RuntimeError, - "don't know how to byteswap this array type"); - return NULL; - } - Py_INCREF(Py_None); - return Py_None; + switch (self->ob_descr->itemsize) { + case 1: + break; + case 2: + for (p = self->ob_item, i = Py_SIZE(self); --i >= 0; p += 2) { + char p0 = p[0]; + p[0] = p[1]; + p[1] = p0; + } + break; + case 4: + for (p = self->ob_item, i = Py_SIZE(self); --i >= 0; p += 4) { + char p0 = p[0]; + char p1 = p[1]; + p[0] = p[3]; + p[1] = p[2]; + p[2] = p1; + p[3] = p0; + } + break; + case 8: + for (p = self->ob_item, i = Py_SIZE(self); --i >= 0; p += 8) { + char p0 = p[0]; + char p1 = p[1]; + char p2 = p[2]; + char p3 = p[3]; + p[0] = p[7]; + p[1] = p[6]; + p[2] = p[5]; + p[3] = p[4]; + p[4] = p3; + p[5] = p2; + p[6] = p1; + p[7] = p0; + } + break; + default: + PyErr_SetString(PyExc_RuntimeError, + "don't know how to byteswap this array type"); + return NULL; + } + Py_INCREF(Py_None); + return Py_None; } PyDoc_STRVAR(byteswap_doc, @@ -1138,33 +1138,33 @@ static PyObject * array_reduce(arrayobject *array) { - PyObject *dict, *result; + PyObject *dict, *result; - dict = PyObject_GetAttrString((PyObject *)array, "__dict__"); - if (dict == NULL) { - PyErr_Clear(); - dict = Py_None; - Py_INCREF(dict); - } - if (Py_SIZE(array) > 0) { - if (array->ob_descr->itemsize - > PY_SSIZE_T_MAX / Py_SIZE(array)) { - return PyErr_NoMemory(); - } - result = Py_BuildValue("O(Cy#)O", - Py_TYPE(array), - array->ob_descr->typecode, - array->ob_item, - Py_SIZE(array) * array->ob_descr->itemsize, - dict); - } else { - result = Py_BuildValue("O(C)O", - Py_TYPE(array), - array->ob_descr->typecode, - dict); - } - Py_DECREF(dict); - return result; + dict = PyObject_GetAttrString((PyObject *)array, "__dict__"); + if (dict == NULL) { + PyErr_Clear(); + dict = Py_None; + Py_INCREF(dict); + } + if (Py_SIZE(array) > 0) { + if (array->ob_descr->itemsize + > PY_SSIZE_T_MAX / Py_SIZE(array)) { + return PyErr_NoMemory(); + } + result = Py_BuildValue("O(Cy#)O", + Py_TYPE(array), + array->ob_descr->typecode, + array->ob_item, + Py_SIZE(array) * array->ob_descr->itemsize, + dict); + } else { + result = Py_BuildValue("O(C)O", + Py_TYPE(array), + array->ob_descr->typecode, + dict); + } + Py_DECREF(dict); + return result; } PyDoc_STRVAR(array_doc, "Return state information for pickling."); @@ -1172,28 +1172,28 @@ static PyObject * array_reverse(arrayobject *self, PyObject *unused) { - register Py_ssize_t itemsize = self->ob_descr->itemsize; - register char *p, *q; - /* little buffer to hold items while swapping */ - char tmp[256]; /* 8 is probably enough -- but why skimp */ - assert((size_t)itemsize <= sizeof(tmp)); - - if (Py_SIZE(self) > 1) { - for (p = self->ob_item, - q = self->ob_item + (Py_SIZE(self) - 1)*itemsize; - p < q; - p += itemsize, q -= itemsize) { - /* memory areas guaranteed disjoint, so memcpy - * is safe (& memmove may be slower). - */ - memcpy(tmp, p, itemsize); - memcpy(p, q, itemsize); - memcpy(q, tmp, itemsize); - } - } + register Py_ssize_t itemsize = self->ob_descr->itemsize; + register char *p, *q; + /* little buffer to hold items while swapping */ + char tmp[256]; /* 8 is probably enough -- but why skimp */ + assert((size_t)itemsize <= sizeof(tmp)); + + if (Py_SIZE(self) > 1) { + for (p = self->ob_item, + q = self->ob_item + (Py_SIZE(self) - 1)*itemsize; + p < q; + p += itemsize, q -= itemsize) { + /* memory areas guaranteed disjoint, so memcpy + * is safe (& memmove may be slower). + */ + memcpy(tmp, p, itemsize); + memcpy(p, q, itemsize); + memcpy(q, tmp, itemsize); + } + } - Py_INCREF(Py_None); - return Py_None; + Py_INCREF(Py_None); + return Py_None; } PyDoc_STRVAR(reverse_doc, @@ -1208,51 +1208,51 @@ static PyObject * array_fromfile(arrayobject *self, PyObject *args) { - PyObject *f, *b, *res; - Py_ssize_t itemsize = self->ob_descr->itemsize; - Py_ssize_t n, nbytes; - int not_enough_bytes; - - if (!PyArg_ParseTuple(args, "On:fromfile", &f, &n)) - return NULL; - - nbytes = n * itemsize; - if (nbytes < 0 || nbytes/itemsize != n) { - PyErr_NoMemory(); - return NULL; - } - - b = PyObject_CallMethod(f, "read", "n", nbytes); - if (b == NULL) - return NULL; - - if (!PyBytes_Check(b)) { - PyErr_SetString(PyExc_TypeError, - "read() didn't return bytes"); - Py_DECREF(b); - return NULL; - } - - not_enough_bytes = (PyBytes_GET_SIZE(b) != nbytes); - - args = Py_BuildValue("(O)", b); - Py_DECREF(b); - if (args == NULL) - return NULL; - - res = array_fromstring(self, args); - Py_DECREF(args); - if (res == NULL) - return NULL; - - if (not_enough_bytes) { - PyErr_SetString(PyExc_EOFError, - "read() didn't return enough bytes"); - Py_DECREF(res); - return NULL; - } + PyObject *f, *b, *res; + Py_ssize_t itemsize = self->ob_descr->itemsize; + Py_ssize_t n, nbytes; + int not_enough_bytes; + + if (!PyArg_ParseTuple(args, "On:fromfile", &f, &n)) + return NULL; + + nbytes = n * itemsize; + if (nbytes < 0 || nbytes/itemsize != n) { + PyErr_NoMemory(); + return NULL; + } + + b = PyObject_CallMethod(f, "read", "n", nbytes); + if (b == NULL) + return NULL; + + if (!PyBytes_Check(b)) { + PyErr_SetString(PyExc_TypeError, + "read() didn't return bytes"); + Py_DECREF(b); + return NULL; + } + + not_enough_bytes = (PyBytes_GET_SIZE(b) != nbytes); + + args = Py_BuildValue("(O)", b); + Py_DECREF(b); + if (args == NULL) + return NULL; + + res = array_fromstring(self, args); + Py_DECREF(args); + if (res == NULL) + return NULL; + + if (not_enough_bytes) { + PyErr_SetString(PyExc_EOFError, + "read() didn't return enough bytes"); + Py_DECREF(res); + return NULL; + } - return res; + return res; } PyDoc_STRVAR(fromfile_doc, @@ -1265,35 +1265,35 @@ static PyObject * array_tofile(arrayobject *self, PyObject *f) { - Py_ssize_t nbytes = Py_SIZE(self) * self->ob_descr->itemsize; - /* Write 64K blocks at a time */ - /* XXX Make the block size settable */ - int BLOCKSIZE = 64*1024; - Py_ssize_t nblocks = (nbytes + BLOCKSIZE - 1) / BLOCKSIZE; - Py_ssize_t i; - - if (Py_SIZE(self) == 0) - goto done; - - for (i = 0; i < nblocks; i++) { - char* ptr = self->ob_item + i*BLOCKSIZE; - Py_ssize_t size = BLOCKSIZE; - PyObject *bytes, *res; - if (i*BLOCKSIZE + size > nbytes) - size = nbytes - i*BLOCKSIZE; - bytes = PyBytes_FromStringAndSize(ptr, size); - if (bytes == NULL) - return NULL; - res = PyObject_CallMethod(f, "write", "O", bytes); - Py_DECREF(bytes); - if (res == NULL) - return NULL; - Py_DECREF(res); /* drop write result */ - } + Py_ssize_t nbytes = Py_SIZE(self) * self->ob_descr->itemsize; + /* Write 64K blocks at a time */ + /* XXX Make the block size settable */ + int BLOCKSIZE = 64*1024; + Py_ssize_t nblocks = (nbytes + BLOCKSIZE - 1) / BLOCKSIZE; + Py_ssize_t i; + + if (Py_SIZE(self) == 0) + goto done; + + for (i = 0; i < nblocks; i++) { + char* ptr = self->ob_item + i*BLOCKSIZE; + Py_ssize_t size = BLOCKSIZE; + PyObject *bytes, *res; + if (i*BLOCKSIZE + size > nbytes) + size = nbytes - i*BLOCKSIZE; + bytes = PyBytes_FromStringAndSize(ptr, size); + if (bytes == NULL) + return NULL; + res = PyObject_CallMethod(f, "write", "O", bytes); + Py_DECREF(bytes); + if (res == NULL) + return NULL; + Py_DECREF(res); /* drop write result */ + } done: - Py_INCREF(Py_None); - return Py_None; + Py_INCREF(Py_None); + return Py_None; } PyDoc_STRVAR(tofile_doc, @@ -1305,29 +1305,29 @@ static PyObject * array_fromlist(arrayobject *self, PyObject *list) { - Py_ssize_t n; + Py_ssize_t n; - if (!PyList_Check(list)) { - PyErr_SetString(PyExc_TypeError, "arg must be list"); - return NULL; - } - n = PyList_Size(list); - if (n > 0) { - Py_ssize_t i, old_size; - old_size = Py_SIZE(self); - if (array_resize(self, old_size + n) == -1) - return NULL; - for (i = 0; i < n; i++) { - PyObject *v = PyList_GetItem(list, i); - if ((*self->ob_descr->setitem)(self, - Py_SIZE(self) - n + i, v) != 0) { - array_resize(self, old_size); - return NULL; - } - } - } - Py_INCREF(Py_None); - return Py_None; + if (!PyList_Check(list)) { + PyErr_SetString(PyExc_TypeError, "arg must be list"); + return NULL; + } + n = PyList_Size(list); + if (n > 0) { + Py_ssize_t i, old_size; + old_size = Py_SIZE(self); + if (array_resize(self, old_size + n) == -1) + return NULL; + for (i = 0; i < n; i++) { + PyObject *v = PyList_GetItem(list, i); + if ((*self->ob_descr->setitem)(self, + Py_SIZE(self) - n + i, v) != 0) { + array_resize(self, old_size); + return NULL; + } + } + } + Py_INCREF(Py_None); + return Py_None; } PyDoc_STRVAR(fromlist_doc, @@ -1338,20 +1338,20 @@ static PyObject * array_tolist(arrayobject *self, PyObject *unused) { - PyObject *list = PyList_New(Py_SIZE(self)); - Py_ssize_t i; + PyObject *list = PyList_New(Py_SIZE(self)); + Py_ssize_t i; - if (list == NULL) - return NULL; - for (i = 0; i < Py_SIZE(self); i++) { - PyObject *v = getarrayitem((PyObject *)self, i); - if (v == NULL) { - Py_DECREF(list); - return NULL; - } - PyList_SetItem(list, i, v); - } - return list; + if (list == NULL) + return NULL; + for (i = 0; i < Py_SIZE(self); i++) { + PyObject *v = getarrayitem((PyObject *)self, i); + if (v == NULL) { + Py_DECREF(list); + return NULL; + } + PyList_SetItem(list, i, v); + } + return list; } PyDoc_STRVAR(tolist_doc, @@ -1363,30 +1363,30 @@ static PyObject * array_fromstring(arrayobject *self, PyObject *args) { - char *str; - Py_ssize_t n; - int itemsize = self->ob_descr->itemsize; - if (!PyArg_ParseTuple(args, "s#:fromstring", &str, &n)) - return NULL; - if (n % itemsize != 0) { - PyErr_SetString(PyExc_ValueError, - "string length not a multiple of item size"); - return NULL; - } - n = n / itemsize; - if (n > 0) { - Py_ssize_t old_size = Py_SIZE(self); - if ((n > PY_SSIZE_T_MAX - old_size) || - ((old_size + n) > PY_SSIZE_T_MAX / itemsize)) { - return PyErr_NoMemory(); - } - if (array_resize(self, old_size + n) == -1) - return NULL; - memcpy(self->ob_item + old_size * itemsize, - str, n * itemsize); - } - Py_INCREF(Py_None); - return Py_None; + char *str; + Py_ssize_t n; + int itemsize = self->ob_descr->itemsize; + if (!PyArg_ParseTuple(args, "s#:fromstring", &str, &n)) + return NULL; + if (n % itemsize != 0) { + PyErr_SetString(PyExc_ValueError, + "string length not a multiple of item size"); + return NULL; + } + n = n / itemsize; + if (n > 0) { + Py_ssize_t old_size = Py_SIZE(self); + if ((n > PY_SSIZE_T_MAX - old_size) || + ((old_size + n) > PY_SSIZE_T_MAX / itemsize)) { + return PyErr_NoMemory(); + } + if (array_resize(self, old_size + n) == -1) + return NULL; + memcpy(self->ob_item + old_size * itemsize, + str, n * itemsize); + } + Py_INCREF(Py_None); + return Py_None; } PyDoc_STRVAR(fromstring_doc, @@ -1399,12 +1399,12 @@ static PyObject * array_tostring(arrayobject *self, PyObject *unused) { - if (Py_SIZE(self) <= PY_SSIZE_T_MAX / self->ob_descr->itemsize) { - return PyBytes_FromStringAndSize(self->ob_item, - Py_SIZE(self) * self->ob_descr->itemsize); - } else { - return PyErr_NoMemory(); - } + if (Py_SIZE(self) <= PY_SSIZE_T_MAX / self->ob_descr->itemsize) { + return PyBytes_FromStringAndSize(self->ob_item, + Py_SIZE(self) * self->ob_descr->itemsize); + } else { + return PyErr_NoMemory(); + } } PyDoc_STRVAR(tostring_doc, @@ -1418,29 +1418,29 @@ static PyObject * array_fromunicode(arrayobject *self, PyObject *args) { - Py_UNICODE *ustr; - Py_ssize_t n; - char typecode; - - if (!PyArg_ParseTuple(args, "u#:fromunicode", &ustr, &n)) - return NULL; - typecode = self->ob_descr->typecode; - if ((typecode != 'u')) { - PyErr_SetString(PyExc_ValueError, - "fromunicode() may only be called on " - "unicode type arrays"); - return NULL; - } - if (n > 0) { - Py_ssize_t old_size = Py_SIZE(self); - if (array_resize(self, old_size + n) == -1) - return NULL; - memcpy(self->ob_item + old_size * sizeof(Py_UNICODE), - ustr, n * sizeof(Py_UNICODE)); - } + Py_UNICODE *ustr; + Py_ssize_t n; + char typecode; + + if (!PyArg_ParseTuple(args, "u#:fromunicode", &ustr, &n)) + return NULL; + typecode = self->ob_descr->typecode; + if ((typecode != 'u')) { + PyErr_SetString(PyExc_ValueError, + "fromunicode() may only be called on " + "unicode type arrays"); + return NULL; + } + if (n > 0) { + Py_ssize_t old_size = Py_SIZE(self); + if (array_resize(self, old_size + n) == -1) + return NULL; + memcpy(self->ob_item + old_size * sizeof(Py_UNICODE), + ustr, n * sizeof(Py_UNICODE)); + } - Py_INCREF(Py_None); - return Py_None; + Py_INCREF(Py_None); + return Py_None; } PyDoc_STRVAR(fromunicode_doc, @@ -1455,14 +1455,14 @@ static PyObject * array_tounicode(arrayobject *self, PyObject *unused) { - char typecode; - typecode = self->ob_descr->typecode; - if ((typecode != 'u')) { - PyErr_SetString(PyExc_ValueError, - "tounicode() may only be called on unicode type arrays"); - return NULL; - } - return PyUnicode_FromUnicode((Py_UNICODE *) self->ob_item, Py_SIZE(self)); + char typecode; + typecode = self->ob_descr->typecode; + if ((typecode != 'u')) { + PyErr_SetString(PyExc_ValueError, + "tounicode() may only be called on unicode type arrays"); + return NULL; + } + return PyUnicode_FromUnicode((Py_UNICODE *) self->ob_item, Py_SIZE(self)); } PyDoc_STRVAR(tounicode_doc, @@ -1478,313 +1478,313 @@ static PyObject * array_get_typecode(arrayobject *a, void *closure) { - char tc = a->ob_descr->typecode; - return PyUnicode_FromStringAndSize(&tc, 1); + char tc = a->ob_descr->typecode; + return PyUnicode_FromStringAndSize(&tc, 1); } static PyObject * array_get_itemsize(arrayobject *a, void *closure) { - return PyLong_FromLong((long)a->ob_descr->itemsize); + return PyLong_FromLong((long)a->ob_descr->itemsize); } static PyGetSetDef array_getsets [] = { - {"typecode", (getter) array_get_typecode, NULL, - "the typecode character used to create the array"}, - {"itemsize", (getter) array_get_itemsize, NULL, - "the size, in bytes, of one array item"}, - {NULL} + {"typecode", (getter) array_get_typecode, NULL, + "the typecode character used to create the array"}, + {"itemsize", (getter) array_get_itemsize, NULL, + "the size, in bytes, of one array item"}, + {NULL} }; static PyMethodDef array_methods[] = { - {"append", (PyCFunction)array_append, METH_O, - append_doc}, - {"buffer_info", (PyCFunction)array_buffer_info, METH_NOARGS, - buffer_info_doc}, - {"byteswap", (PyCFunction)array_byteswap, METH_NOARGS, - byteswap_doc}, - {"__copy__", (PyCFunction)array_copy, METH_NOARGS, - copy_doc}, - {"count", (PyCFunction)array_count, METH_O, - count_doc}, - {"__deepcopy__",(PyCFunction)array_copy, METH_O, - copy_doc}, - {"extend", (PyCFunction)array_extend, METH_O, - extend_doc}, - {"fromfile", (PyCFunction)array_fromfile, METH_VARARGS, - fromfile_doc}, - {"fromlist", (PyCFunction)array_fromlist, METH_O, - fromlist_doc}, - {"fromstring", (PyCFunction)array_fromstring, METH_VARARGS, - fromstring_doc}, - {"fromunicode", (PyCFunction)array_fromunicode, METH_VARARGS, - fromunicode_doc}, - {"index", (PyCFunction)array_index, METH_O, - index_doc}, - {"insert", (PyCFunction)array_insert, METH_VARARGS, - insert_doc}, - {"pop", (PyCFunction)array_pop, METH_VARARGS, - pop_doc}, - {"__reduce__", (PyCFunction)array_reduce, METH_NOARGS, - array_doc}, - {"remove", (PyCFunction)array_remove, METH_O, - remove_doc}, - {"reverse", (PyCFunction)array_reverse, METH_NOARGS, - reverse_doc}, -/* {"sort", (PyCFunction)array_sort, METH_VARARGS, - sort_doc},*/ - {"tofile", (PyCFunction)array_tofile, METH_O, - tofile_doc}, - {"tolist", (PyCFunction)array_tolist, METH_NOARGS, - tolist_doc}, - {"tostring", (PyCFunction)array_tostring, METH_NOARGS, - tostring_doc}, - {"tounicode", (PyCFunction)array_tounicode, METH_NOARGS, - tounicode_doc}, - {NULL, NULL} /* sentinel */ + {"append", (PyCFunction)array_append, METH_O, + append_doc}, + {"buffer_info", (PyCFunction)array_buffer_info, METH_NOARGS, + buffer_info_doc}, + {"byteswap", (PyCFunction)array_byteswap, METH_NOARGS, + byteswap_doc}, + {"__copy__", (PyCFunction)array_copy, METH_NOARGS, + copy_doc}, + {"count", (PyCFunction)array_count, METH_O, + count_doc}, + {"__deepcopy__",(PyCFunction)array_copy, METH_O, + copy_doc}, + {"extend", (PyCFunction)array_extend, METH_O, + extend_doc}, + {"fromfile", (PyCFunction)array_fromfile, METH_VARARGS, + fromfile_doc}, + {"fromlist", (PyCFunction)array_fromlist, METH_O, + fromlist_doc}, + {"fromstring", (PyCFunction)array_fromstring, METH_VARARGS, + fromstring_doc}, + {"fromunicode", (PyCFunction)array_fromunicode, METH_VARARGS, + fromunicode_doc}, + {"index", (PyCFunction)array_index, METH_O, + index_doc}, + {"insert", (PyCFunction)array_insert, METH_VARARGS, + insert_doc}, + {"pop", (PyCFunction)array_pop, METH_VARARGS, + pop_doc}, + {"__reduce__", (PyCFunction)array_reduce, METH_NOARGS, + array_doc}, + {"remove", (PyCFunction)array_remove, METH_O, + remove_doc}, + {"reverse", (PyCFunction)array_reverse, METH_NOARGS, + reverse_doc}, +/* {"sort", (PyCFunction)array_sort, METH_VARARGS, + sort_doc},*/ + {"tofile", (PyCFunction)array_tofile, METH_O, + tofile_doc}, + {"tolist", (PyCFunction)array_tolist, METH_NOARGS, + tolist_doc}, + {"tostring", (PyCFunction)array_tostring, METH_NOARGS, + tostring_doc}, + {"tounicode", (PyCFunction)array_tounicode, METH_NOARGS, + tounicode_doc}, + {NULL, NULL} /* sentinel */ }; static PyObject * array_repr(arrayobject *a) { - char typecode; - PyObject *s, *v = NULL; - Py_ssize_t len; - - len = Py_SIZE(a); - typecode = a->ob_descr->typecode; - if (len == 0) { - return PyUnicode_FromFormat("array('%c')", typecode); - } - if ((typecode == 'u')) - v = array_tounicode(a, NULL); - else - v = array_tolist(a, NULL); - - s = PyUnicode_FromFormat("array('%c', %R)", typecode, v); - Py_DECREF(v); - return s; + char typecode; + PyObject *s, *v = NULL; + Py_ssize_t len; + + len = Py_SIZE(a); + typecode = a->ob_descr->typecode; + if (len == 0) { + return PyUnicode_FromFormat("array('%c')", typecode); + } + if ((typecode == 'u')) + v = array_tounicode(a, NULL); + else + v = array_tolist(a, NULL); + + s = PyUnicode_FromFormat("array('%c', %R)", typecode, v); + Py_DECREF(v); + return s; } static PyObject* array_subscr(arrayobject* 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 += Py_SIZE(self); - return array_item(self, i); - } - else if (PySlice_Check(item)) { - Py_ssize_t start, stop, step, slicelength, cur, i; - PyObject* result; - arrayobject* ar; - int itemsize = self->ob_descr->itemsize; - - if (PySlice_GetIndicesEx((PySliceObject*)item, Py_SIZE(self), - &start, &stop, &step, &slicelength) < 0) { - return NULL; - } - - if (slicelength <= 0) { - return newarrayobject(&Arraytype, 0, self->ob_descr); - } - else if (step == 1) { - PyObject *result = newarrayobject(&Arraytype, - slicelength, self->ob_descr); - if (result == NULL) - return NULL; - memcpy(((arrayobject *)result)->ob_item, - self->ob_item + start * itemsize, - slicelength * itemsize); - return result; - } - else { - result = newarrayobject(&Arraytype, slicelength, self->ob_descr); - if (!result) return NULL; - - ar = (arrayobject*)result; - - for (cur = start, i = 0; i < slicelength; - cur += step, i++) { - memcpy(ar->ob_item + i*itemsize, - self->ob_item + cur*itemsize, - itemsize); - } - - return result; - } - } - else { - PyErr_SetString(PyExc_TypeError, - "array indices must be integers"); - return NULL; - } + 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 += Py_SIZE(self); + return array_item(self, i); + } + else if (PySlice_Check(item)) { + Py_ssize_t start, stop, step, slicelength, cur, i; + PyObject* result; + arrayobject* ar; + int itemsize = self->ob_descr->itemsize; + + if (PySlice_GetIndicesEx((PySliceObject*)item, Py_SIZE(self), + &start, &stop, &step, &slicelength) < 0) { + return NULL; + } + + if (slicelength <= 0) { + return newarrayobject(&Arraytype, 0, self->ob_descr); + } + else if (step == 1) { + PyObject *result = newarrayobject(&Arraytype, + slicelength, self->ob_descr); + if (result == NULL) + return NULL; + memcpy(((arrayobject *)result)->ob_item, + self->ob_item + start * itemsize, + slicelength * itemsize); + return result; + } + else { + result = newarrayobject(&Arraytype, slicelength, self->ob_descr); + if (!result) return NULL; + + ar = (arrayobject*)result; + + for (cur = start, i = 0; i < slicelength; + cur += step, i++) { + memcpy(ar->ob_item + i*itemsize, + self->ob_item + cur*itemsize, + itemsize); + } + + return result; + } + } + else { + PyErr_SetString(PyExc_TypeError, + "array indices must be integers"); + return NULL; + } } static int array_ass_subscr(arrayobject* self, PyObject* item, PyObject* value) { - Py_ssize_t start, stop, step, slicelength, needed; - arrayobject* other; - int itemsize; - - if (PyIndex_Check(item)) { - Py_ssize_t i = PyNumber_AsSsize_t(item, PyExc_IndexError); - - if (i == -1 && PyErr_Occurred()) - return -1; - if (i < 0) - i += Py_SIZE(self); - if (i < 0 || i >= Py_SIZE(self)) { - PyErr_SetString(PyExc_IndexError, - "array assignment index out of range"); - return -1; - } - if (value == NULL) { - /* Fall through to slice assignment */ - start = i; - stop = i + 1; - step = 1; - slicelength = 1; - } - else - return (*self->ob_descr->setitem)(self, i, value); - } - else if (PySlice_Check(item)) { - if (PySlice_GetIndicesEx((PySliceObject *)item, - Py_SIZE(self), &start, &stop, - &step, &slicelength) < 0) { - return -1; - } - } - else { - PyErr_SetString(PyExc_TypeError, - "array indices must be integer"); - return -1; - } - if (value == NULL) { - other = NULL; - needed = 0; - } - else if (array_Check(value)) { - other = (arrayobject *)value; - needed = Py_SIZE(other); - if (self == other) { - /* Special case "self[i:j] = self" -- copy self first */ - int ret; - value = array_slice(other, 0, needed); - if (value == NULL) - return -1; - ret = array_ass_subscr(self, item, value); - Py_DECREF(value); - return ret; - } - if (other->ob_descr != self->ob_descr) { - PyErr_BadArgument(); - return -1; - } - } - else { - PyErr_Format(PyExc_TypeError, - "can only assign array (not \"%.200s\") to array slice", - Py_TYPE(value)->tp_name); - return -1; - } - itemsize = self->ob_descr->itemsize; - /* for 'a[2:1] = ...', the insertion point is 'start', not 'stop' */ - if ((step > 0 && stop < start) || - (step < 0 && stop > start)) - stop = start; - - /* Issue #4509: If the array has exported buffers and the slice - assignment would change the size of the array, fail early to make - sure we don't modify it. */ - if ((needed == 0 || slicelength != needed) && self->ob_exports > 0) { - PyErr_SetString(PyExc_BufferError, - "cannot resize an array that is exporting buffers"); - return -1; - } - - if (step == 1) { - if (slicelength > needed) { - memmove(self->ob_item + (start + needed) * itemsize, - self->ob_item + stop * itemsize, - (Py_SIZE(self) - stop) * itemsize); - if (array_resize(self, Py_SIZE(self) + - needed - slicelength) < 0) - return -1; - } - else if (slicelength < needed) { - if (array_resize(self, Py_SIZE(self) + - needed - slicelength) < 0) - return -1; - memmove(self->ob_item + (start + needed) * itemsize, - self->ob_item + stop * itemsize, - (Py_SIZE(self) - start - needed) * itemsize); - } - if (needed > 0) - memcpy(self->ob_item + start * itemsize, - other->ob_item, needed * itemsize); - return 0; - } - else if (needed == 0) { - /* Delete slice */ - size_t cur; - Py_ssize_t i; - - if (step < 0) { - stop = start + 1; - start = stop + step * (slicelength - 1) - 1; - step = -step; - } - for (cur = start, i = 0; i < slicelength; - cur += step, i++) { - Py_ssize_t lim = step - 1; - - if (cur + step >= (size_t)Py_SIZE(self)) - lim = Py_SIZE(self) - cur - 1; - memmove(self->ob_item + (cur - i) * itemsize, - self->ob_item + (cur + 1) * itemsize, - lim * itemsize); - } - cur = start + slicelength * step; - if (cur < (size_t)Py_SIZE(self)) { - memmove(self->ob_item + (cur-slicelength) * itemsize, - self->ob_item + cur * itemsize, - (Py_SIZE(self) - cur) * itemsize); - } - if (array_resize(self, Py_SIZE(self) - slicelength) < 0) - return -1; - return 0; - } - else { - Py_ssize_t cur, i; - - if (needed != slicelength) { - PyErr_Format(PyExc_ValueError, - "attempt to assign array of size %zd " - "to extended slice of size %zd", - needed, slicelength); - return -1; - } - for (cur = start, i = 0; i < slicelength; - cur += step, i++) { - memcpy(self->ob_item + cur * itemsize, - other->ob_item + i * itemsize, - itemsize); - } - return 0; - } + Py_ssize_t start, stop, step, slicelength, needed; + arrayobject* other; + int itemsize; + + if (PyIndex_Check(item)) { + Py_ssize_t i = PyNumber_AsSsize_t(item, PyExc_IndexError); + + if (i == -1 && PyErr_Occurred()) + return -1; + if (i < 0) + i += Py_SIZE(self); + if (i < 0 || i >= Py_SIZE(self)) { + PyErr_SetString(PyExc_IndexError, + "array assignment index out of range"); + return -1; + } + if (value == NULL) { + /* Fall through to slice assignment */ + start = i; + stop = i + 1; + step = 1; + slicelength = 1; + } + else + return (*self->ob_descr->setitem)(self, i, value); + } + else if (PySlice_Check(item)) { + if (PySlice_GetIndicesEx((PySliceObject *)item, + Py_SIZE(self), &start, &stop, + &step, &slicelength) < 0) { + return -1; + } + } + else { + PyErr_SetString(PyExc_TypeError, + "array indices must be integer"); + return -1; + } + if (value == NULL) { + other = NULL; + needed = 0; + } + else if (array_Check(value)) { + other = (arrayobject *)value; + needed = Py_SIZE(other); + if (self == other) { + /* Special case "self[i:j] = self" -- copy self first */ + int ret; + value = array_slice(other, 0, needed); + if (value == NULL) + return -1; + ret = array_ass_subscr(self, item, value); + Py_DECREF(value); + return ret; + } + if (other->ob_descr != self->ob_descr) { + PyErr_BadArgument(); + return -1; + } + } + else { + PyErr_Format(PyExc_TypeError, + "can only assign array (not \"%.200s\") to array slice", + Py_TYPE(value)->tp_name); + return -1; + } + itemsize = self->ob_descr->itemsize; + /* for 'a[2:1] = ...', the insertion point is 'start', not 'stop' */ + if ((step > 0 && stop < start) || + (step < 0 && stop > start)) + stop = start; + + /* Issue #4509: If the array has exported buffers and the slice + assignment would change the size of the array, fail early to make + sure we don't modify it. */ + if ((needed == 0 || slicelength != needed) && self->ob_exports > 0) { + PyErr_SetString(PyExc_BufferError, + "cannot resize an array that is exporting buffers"); + return -1; + } + + if (step == 1) { + if (slicelength > needed) { + memmove(self->ob_item + (start + needed) * itemsize, + self->ob_item + stop * itemsize, + (Py_SIZE(self) - stop) * itemsize); + if (array_resize(self, Py_SIZE(self) + + needed - slicelength) < 0) + return -1; + } + else if (slicelength < needed) { + if (array_resize(self, Py_SIZE(self) + + needed - slicelength) < 0) + return -1; + memmove(self->ob_item + (start + needed) * itemsize, + self->ob_item + stop * itemsize, + (Py_SIZE(self) - start - needed) * itemsize); + } + if (needed > 0) + memcpy(self->ob_item + start * itemsize, + other->ob_item, needed * itemsize); + return 0; + } + else if (needed == 0) { + /* Delete slice */ + size_t cur; + Py_ssize_t i; + + if (step < 0) { + stop = start + 1; + start = stop + step * (slicelength - 1) - 1; + step = -step; + } + for (cur = start, i = 0; i < slicelength; + cur += step, i++) { + Py_ssize_t lim = step - 1; + + if (cur + step >= (size_t)Py_SIZE(self)) + lim = Py_SIZE(self) - cur - 1; + memmove(self->ob_item + (cur - i) * itemsize, + self->ob_item + (cur + 1) * itemsize, + lim * itemsize); + } + cur = start + slicelength * step; + if (cur < (size_t)Py_SIZE(self)) { + memmove(self->ob_item + (cur-slicelength) * itemsize, + self->ob_item + cur * itemsize, + (Py_SIZE(self) - cur) * itemsize); + } + if (array_resize(self, Py_SIZE(self) - slicelength) < 0) + return -1; + return 0; + } + else { + Py_ssize_t cur, i; + + if (needed != slicelength) { + PyErr_Format(PyExc_ValueError, + "attempt to assign array of size %zd " + "to extended slice of size %zd", + needed, slicelength); + return -1; + } + for (cur = start, i = 0; i < slicelength; + cur += step, i++) { + memcpy(self->ob_item + cur * itemsize, + other->ob_item + i * itemsize, + itemsize); + } + return 0; + } } static PyMappingMethods array_as_mapping = { - (lenfunc)array_length, - (binaryfunc)array_subscr, - (objobjargproc)array_ass_subscr + (lenfunc)array_length, + (binaryfunc)array_subscr, + (objobjargproc)array_ass_subscr }; static const void *emptybuf = ""; @@ -1793,173 +1793,173 @@ static int array_buffer_getbuf(arrayobject *self, Py_buffer *view, int flags) { - if (view==NULL) goto finish; + if (view==NULL) goto finish; - view->buf = (void *)self->ob_item; - view->obj = (PyObject*)self; - Py_INCREF(self); - if (view->buf == NULL) - view->buf = (void *)emptybuf; - view->len = (Py_SIZE(self)) * self->ob_descr->itemsize; - view->readonly = 0; - view->ndim = 1; - view->itemsize = self->ob_descr->itemsize; - view->suboffsets = NULL; - view->shape = NULL; - if ((flags & PyBUF_ND)==PyBUF_ND) { - view->shape = &((Py_SIZE(self))); - } - view->strides = NULL; - if ((flags & PyBUF_STRIDES)==PyBUF_STRIDES) - view->strides = &(view->itemsize); - view->format = NULL; - view->internal = NULL; - if ((flags & PyBUF_FORMAT) == PyBUF_FORMAT) { - view->format = self->ob_descr->formats; + view->buf = (void *)self->ob_item; + view->obj = (PyObject*)self; + Py_INCREF(self); + if (view->buf == NULL) + view->buf = (void *)emptybuf; + view->len = (Py_SIZE(self)) * self->ob_descr->itemsize; + view->readonly = 0; + view->ndim = 1; + view->itemsize = self->ob_descr->itemsize; + view->suboffsets = NULL; + view->shape = NULL; + if ((flags & PyBUF_ND)==PyBUF_ND) { + view->shape = &((Py_SIZE(self))); + } + view->strides = NULL; + if ((flags & PyBUF_STRIDES)==PyBUF_STRIDES) + view->strides = &(view->itemsize); + view->format = NULL; + view->internal = NULL; + if ((flags & PyBUF_FORMAT) == PyBUF_FORMAT) { + view->format = self->ob_descr->formats; #ifdef Py_UNICODE_WIDE - if (self->ob_descr->typecode == 'u') { - view->format = "w"; - } -#endif + if (self->ob_descr->typecode == 'u') { + view->format = "w"; } +#endif + } finish: - self->ob_exports++; - return 0; + self->ob_exports++; + return 0; } static void array_buffer_relbuf(arrayobject *self, Py_buffer *view) { - self->ob_exports--; + self->ob_exports--; } static PySequenceMethods array_as_sequence = { - (lenfunc)array_length, /*sq_length*/ - (binaryfunc)array_concat, /*sq_concat*/ - (ssizeargfunc)array_repeat, /*sq_repeat*/ - (ssizeargfunc)array_item, /*sq_item*/ - 0, /*sq_slice*/ - (ssizeobjargproc)array_ass_item, /*sq_ass_item*/ - 0, /*sq_ass_slice*/ - (objobjproc)array_contains, /*sq_contains*/ - (binaryfunc)array_inplace_concat, /*sq_inplace_concat*/ - (ssizeargfunc)array_inplace_repeat /*sq_inplace_repeat*/ + (lenfunc)array_length, /*sq_length*/ + (binaryfunc)array_concat, /*sq_concat*/ + (ssizeargfunc)array_repeat, /*sq_repeat*/ + (ssizeargfunc)array_item, /*sq_item*/ + 0, /*sq_slice*/ + (ssizeobjargproc)array_ass_item, /*sq_ass_item*/ + 0, /*sq_ass_slice*/ + (objobjproc)array_contains, /*sq_contains*/ + (binaryfunc)array_inplace_concat, /*sq_inplace_concat*/ + (ssizeargfunc)array_inplace_repeat /*sq_inplace_repeat*/ }; static PyBufferProcs array_as_buffer = { - (getbufferproc)array_buffer_getbuf, - (releasebufferproc)array_buffer_relbuf + (getbufferproc)array_buffer_getbuf, + (releasebufferproc)array_buffer_relbuf }; static PyObject * array_new(PyTypeObject *type, PyObject *args, PyObject *kwds) { - int c; - PyObject *initial = NULL, *it = NULL; - struct arraydescr *descr; - - if (type == &Arraytype && !_PyArg_NoKeywords("array.array()", kwds)) - return NULL; - - if (!PyArg_ParseTuple(args, "C|O:array", &c, &initial)) - return NULL; - - if (!(initial == NULL || PyList_Check(initial) - || PyByteArray_Check(initial) - || PyBytes_Check(initial) - || PyTuple_Check(initial) - || ((c=='u') && PyUnicode_Check(initial)))) { - it = PyObject_GetIter(initial); - if (it == NULL) - return NULL; - /* We set initial to NULL so that the subsequent code - will create an empty array of the appropriate type - and afterwards we can use array_iter_extend to populate - the array. - */ - initial = NULL; - } - for (descr = descriptors; descr->typecode != '\0'; descr++) { - if (descr->typecode == c) { - PyObject *a; - Py_ssize_t len; - - if (initial == NULL || !(PyList_Check(initial) - || PyTuple_Check(initial))) - len = 0; - else - len = PySequence_Size(initial); - - a = newarrayobject(type, len, descr); - if (a == NULL) - return NULL; - - if (len > 0) { - Py_ssize_t i; - for (i = 0; i < len; i++) { - PyObject *v = - PySequence_GetItem(initial, i); - if (v == NULL) { - Py_DECREF(a); - return NULL; - } - if (setarrayitem(a, i, v) != 0) { - Py_DECREF(v); - Py_DECREF(a); - return NULL; - } - Py_DECREF(v); - } - } - else if (initial != NULL && (PyByteArray_Check(initial) || - PyBytes_Check(initial))) { - PyObject *t_initial, *v; - t_initial = PyTuple_Pack(1, initial); - if (t_initial == NULL) { - Py_DECREF(a); - return NULL; - } - v = array_fromstring((arrayobject *)a, - t_initial); - Py_DECREF(t_initial); - if (v == NULL) { - Py_DECREF(a); - return NULL; - } - Py_DECREF(v); - } - else if (initial != NULL && PyUnicode_Check(initial)) { - Py_ssize_t n = PyUnicode_GET_DATA_SIZE(initial); - if (n > 0) { - arrayobject *self = (arrayobject *)a; - char *item = self->ob_item; - item = (char *)PyMem_Realloc(item, n); - if (item == NULL) { - PyErr_NoMemory(); - Py_DECREF(a); - return NULL; - } - self->ob_item = item; - Py_SIZE(self) = n / sizeof(Py_UNICODE); - memcpy(item, PyUnicode_AS_DATA(initial), n); - self->allocated = Py_SIZE(self); - } - } - if (it != NULL) { - if (array_iter_extend((arrayobject *)a, it) == -1) { - Py_DECREF(it); - Py_DECREF(a); - return NULL; - } - Py_DECREF(it); - } - return a; - } - } - PyErr_SetString(PyExc_ValueError, - "bad typecode (must be b, B, u, h, H, i, I, l, L, f or d)"); - return NULL; + int c; + PyObject *initial = NULL, *it = NULL; + struct arraydescr *descr; + + if (type == &Arraytype && !_PyArg_NoKeywords("array.array()", kwds)) + return NULL; + + if (!PyArg_ParseTuple(args, "C|O:array", &c, &initial)) + return NULL; + + if (!(initial == NULL || PyList_Check(initial) + || PyByteArray_Check(initial) + || PyBytes_Check(initial) + || PyTuple_Check(initial) + || ((c=='u') && PyUnicode_Check(initial)))) { + it = PyObject_GetIter(initial); + if (it == NULL) + return NULL; + /* We set initial to NULL so that the subsequent code + will create an empty array of the appropriate type + and afterwards we can use array_iter_extend to populate + the array. + */ + initial = NULL; + } + for (descr = descriptors; descr->typecode != '\0'; descr++) { + if (descr->typecode == c) { + PyObject *a; + Py_ssize_t len; + + if (initial == NULL || !(PyList_Check(initial) + || PyTuple_Check(initial))) + len = 0; + else + len = PySequence_Size(initial); + + a = newarrayobject(type, len, descr); + if (a == NULL) + return NULL; + + if (len > 0) { + Py_ssize_t i; + for (i = 0; i < len; i++) { + PyObject *v = + PySequence_GetItem(initial, i); + if (v == NULL) { + Py_DECREF(a); + return NULL; + } + if (setarrayitem(a, i, v) != 0) { + Py_DECREF(v); + Py_DECREF(a); + return NULL; + } + Py_DECREF(v); + } + } + else if (initial != NULL && (PyByteArray_Check(initial) || + PyBytes_Check(initial))) { + PyObject *t_initial, *v; + t_initial = PyTuple_Pack(1, initial); + if (t_initial == NULL) { + Py_DECREF(a); + return NULL; + } + v = array_fromstring((arrayobject *)a, + t_initial); + Py_DECREF(t_initial); + if (v == NULL) { + Py_DECREF(a); + return NULL; + } + Py_DECREF(v); + } + else if (initial != NULL && PyUnicode_Check(initial)) { + Py_ssize_t n = PyUnicode_GET_DATA_SIZE(initial); + if (n > 0) { + arrayobject *self = (arrayobject *)a; + char *item = self->ob_item; + item = (char *)PyMem_Realloc(item, n); + if (item == NULL) { + PyErr_NoMemory(); + Py_DECREF(a); + return NULL; + } + self->ob_item = item; + Py_SIZE(self) = n / sizeof(Py_UNICODE); + memcpy(item, PyUnicode_AS_DATA(initial), n); + self->allocated = Py_SIZE(self); + } + } + if (it != NULL) { + if (array_iter_extend((arrayobject *)a, it) == -1) { + Py_DECREF(it); + Py_DECREF(a); + return NULL; + } + Py_DECREF(it); + } + return a; + } + } + PyErr_SetString(PyExc_ValueError, + "bad typecode (must be b, B, u, h, H, i, I, l, L, f or d)"); + return NULL; } @@ -2030,55 +2030,55 @@ static PyObject *array_iter(arrayobject *ao); static PyTypeObject Arraytype = { - PyVarObject_HEAD_INIT(NULL, 0) - "array.array", - sizeof(arrayobject), - 0, - (destructor)array_dealloc, /* tp_dealloc */ - 0, /* tp_print */ - 0, /* tp_getattr */ - 0, /* tp_setattr */ - 0, /* tp_reserved */ - (reprfunc)array_repr, /* tp_repr */ - 0, /* tp_as_number*/ - &array_as_sequence, /* tp_as_sequence*/ - &array_as_mapping, /* tp_as_mapping*/ - 0, /* tp_hash */ - 0, /* tp_call */ - 0, /* tp_str */ - PyObject_GenericGetAttr, /* tp_getattro */ - 0, /* tp_setattro */ - &array_as_buffer, /* tp_as_buffer*/ - Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */ - arraytype_doc, /* tp_doc */ - 0, /* tp_traverse */ - 0, /* tp_clear */ - array_richcompare, /* tp_richcompare */ - offsetof(arrayobject, weakreflist), /* tp_weaklistoffset */ - (getiterfunc)array_iter, /* tp_iter */ - 0, /* tp_iternext */ - array_methods, /* tp_methods */ - 0, /* tp_members */ - array_getsets, /* tp_getset */ - 0, /* tp_base */ - 0, /* tp_dict */ - 0, /* tp_descr_get */ - 0, /* tp_descr_set */ - 0, /* tp_dictoffset */ - 0, /* tp_init */ - PyType_GenericAlloc, /* tp_alloc */ - array_new, /* tp_new */ - PyObject_Del, /* tp_free */ + PyVarObject_HEAD_INIT(NULL, 0) + "array.array", + sizeof(arrayobject), + 0, + (destructor)array_dealloc, /* tp_dealloc */ + 0, /* tp_print */ + 0, /* tp_getattr */ + 0, /* tp_setattr */ + 0, /* tp_reserved */ + (reprfunc)array_repr, /* tp_repr */ + 0, /* tp_as_number*/ + &array_as_sequence, /* tp_as_sequence*/ + &array_as_mapping, /* tp_as_mapping*/ + 0, /* tp_hash */ + 0, /* tp_call */ + 0, /* tp_str */ + PyObject_GenericGetAttr, /* tp_getattro */ + 0, /* tp_setattro */ + &array_as_buffer, /* tp_as_buffer*/ + Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */ + arraytype_doc, /* tp_doc */ + 0, /* tp_traverse */ + 0, /* tp_clear */ + array_richcompare, /* tp_richcompare */ + offsetof(arrayobject, weakreflist), /* tp_weaklistoffset */ + (getiterfunc)array_iter, /* tp_iter */ + 0, /* tp_iternext */ + array_methods, /* tp_methods */ + 0, /* tp_members */ + array_getsets, /* tp_getset */ + 0, /* tp_base */ + 0, /* tp_dict */ + 0, /* tp_descr_get */ + 0, /* tp_descr_set */ + 0, /* tp_dictoffset */ + 0, /* tp_init */ + PyType_GenericAlloc, /* tp_alloc */ + array_new, /* tp_new */ + PyObject_Del, /* tp_free */ }; /*********************** Array Iterator **************************/ typedef struct { - PyObject_HEAD - Py_ssize_t index; - arrayobject *ao; - PyObject * (*getitem)(struct arrayobject *, Py_ssize_t); + PyObject_HEAD + Py_ssize_t index; + arrayobject *ao; + PyObject * (*getitem)(struct arrayobject *, Py_ssize_t); } arrayiterobject; static PyTypeObject PyArrayIter_Type; @@ -2088,79 +2088,79 @@ static PyObject * array_iter(arrayobject *ao) { - arrayiterobject *it; + arrayiterobject *it; - if (!array_Check(ao)) { - PyErr_BadInternalCall(); - return NULL; - } - - it = PyObject_GC_New(arrayiterobject, &PyArrayIter_Type); - if (it == NULL) - return NULL; - - Py_INCREF(ao); - it->ao = ao; - it->index = 0; - it->getitem = ao->ob_descr->getitem; - PyObject_GC_Track(it); - return (PyObject *)it; + if (!array_Check(ao)) { + PyErr_BadInternalCall(); + return NULL; + } + + it = PyObject_GC_New(arrayiterobject, &PyArrayIter_Type); + if (it == NULL) + return NULL; + + Py_INCREF(ao); + it->ao = ao; + it->index = 0; + it->getitem = ao->ob_descr->getitem; + PyObject_GC_Track(it); + return (PyObject *)it; } static PyObject * arrayiter_next(arrayiterobject *it) { - assert(PyArrayIter_Check(it)); - if (it->index < Py_SIZE(it->ao)) - return (*it->getitem)(it->ao, it->index++); - return NULL; + assert(PyArrayIter_Check(it)); + if (it->index < Py_SIZE(it->ao)) + return (*it->getitem)(it->ao, it->index++); + return NULL; } static void arrayiter_dealloc(arrayiterobject *it) { - PyObject_GC_UnTrack(it); - Py_XDECREF(it->ao); - PyObject_GC_Del(it); + PyObject_GC_UnTrack(it); + Py_XDECREF(it->ao); + PyObject_GC_Del(it); } static int arrayiter_traverse(arrayiterobject *it, visitproc visit, void *arg) { - Py_VISIT(it->ao); - return 0; + Py_VISIT(it->ao); + return 0; } static PyTypeObject PyArrayIter_Type = { - PyVarObject_HEAD_INIT(NULL, 0) - "arrayiterator", /* tp_name */ - sizeof(arrayiterobject), /* tp_basicsize */ - 0, /* tp_itemsize */ - /* methods */ - (destructor)arrayiter_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)arrayiter_traverse, /* tp_traverse */ - 0, /* tp_clear */ - 0, /* tp_richcompare */ - 0, /* tp_weaklistoffset */ - PyObject_SelfIter, /* tp_iter */ - (iternextfunc)arrayiter_next, /* tp_iternext */ - 0, /* tp_methods */ + PyVarObject_HEAD_INIT(NULL, 0) + "arrayiterator", /* tp_name */ + sizeof(arrayiterobject), /* tp_basicsize */ + 0, /* tp_itemsize */ + /* methods */ + (destructor)arrayiter_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)arrayiter_traverse, /* tp_traverse */ + 0, /* tp_clear */ + 0, /* tp_richcompare */ + 0, /* tp_weaklistoffset */ + PyObject_SelfIter, /* tp_iter */ + (iternextfunc)arrayiter_next, /* tp_iternext */ + 0, /* tp_methods */ }; @@ -2172,54 +2172,54 @@ }; static struct PyModuleDef arraymodule = { - PyModuleDef_HEAD_INIT, - "array", - module_doc, - -1, - a_methods, - NULL, - NULL, - NULL, - NULL + PyModuleDef_HEAD_INIT, + "array", + module_doc, + -1, + a_methods, + NULL, + NULL, + NULL, + NULL }; PyMODINIT_FUNC PyInit_array(void) { - PyObject *m; - PyObject *typecodes; - Py_ssize_t size = 0; - register Py_UNICODE *p; - struct arraydescr *descr; - - if (PyType_Ready(&Arraytype) < 0) - return NULL; - Py_TYPE(&PyArrayIter_Type) = &PyType_Type; - m = PyModule_Create(&arraymodule); - if (m == NULL) - return NULL; - - Py_INCREF((PyObject *)&Arraytype); - PyModule_AddObject(m, "ArrayType", (PyObject *)&Arraytype); - Py_INCREF((PyObject *)&Arraytype); - PyModule_AddObject(m, "array", (PyObject *)&Arraytype); - - for (descr=descriptors; descr->typecode != '\0'; descr++) { - size++; - } - - typecodes = PyUnicode_FromStringAndSize(NULL, size); - p = PyUnicode_AS_UNICODE(typecodes); - for (descr = descriptors; descr->typecode != '\0'; descr++) { - *p++ = (char)descr->typecode; - } - - PyModule_AddObject(m, "typecodes", (PyObject *)typecodes); - - if (PyErr_Occurred()) { - Py_DECREF(m); - m = NULL; - } - return m; + PyObject *m; + PyObject *typecodes; + Py_ssize_t size = 0; + register Py_UNICODE *p; + struct arraydescr *descr; + + if (PyType_Ready(&Arraytype) < 0) + return NULL; + Py_TYPE(&PyArrayIter_Type) = &PyType_Type; + m = PyModule_Create(&arraymodule); + if (m == NULL) + return NULL; + + Py_INCREF((PyObject *)&Arraytype); + PyModule_AddObject(m, "ArrayType", (PyObject *)&Arraytype); + Py_INCREF((PyObject *)&Arraytype); + PyModule_AddObject(m, "array", (PyObject *)&Arraytype); + + for (descr=descriptors; descr->typecode != '\0'; descr++) { + size++; + } + + typecodes = PyUnicode_FromStringAndSize(NULL, size); + p = PyUnicode_AS_UNICODE(typecodes); + for (descr = descriptors; descr->typecode != '\0'; descr++) { + *p++ = (char)descr->typecode; + } + + PyModule_AddObject(m, "typecodes", (PyObject *)typecodes); + + if (PyErr_Occurred()) { + Py_DECREF(m); + m = NULL; + } + return m; } Modified: python/branches/release31-maint/Modules/audioop.c ============================================================================== --- python/branches/release31-maint/Modules/audioop.c (original) +++ python/branches/release31-maint/Modules/audioop.c Sun May 9 18:14:21 2010 @@ -53,13 +53,13 @@ static PyInt16 search(PyInt16 val, PyInt16 *table, int size) { - int i; + int i; - for (i = 0; i < size; i++) { - if (val <= *table++) - return (i); - } - return (size); + for (i = 0; i < size; i++) { + if (val <= *table++) + return (i); + } + return (size); } #define st_ulaw2linear16(uc) (_st_ulaw2linear16[uc]) #define st_alaw2linear16(uc) (_st_alaw2linear16[uc]) @@ -83,7 +83,7 @@ -228, -212, -196, -180, -164, -148, -132, -120, -112, -104, -96, -88, -80, -72, -64, -56, -48, -40, -32, -24, -16, - -8, 0, 32124, 31100, 30076, 29052, 28028, + -8, 0, 32124, 31100, 30076, 29052, 28028, 27004, 25980, 24956, 23932, 22908, 21884, 20860, 19836, 18812, 17788, 16764, 15996, 15484, 14972, 14460, 13948, 13436, 12924, 12412, 11900, 11388, @@ -100,8 +100,8 @@ 372, 356, 340, 324, 308, 292, 276, 260, 244, 228, 212, 196, 180, 164, 148, 132, 120, 112, 104, 96, 88, - 80, 72, 64, 56, 48, 40, 32, - 24, 16, 8, 0 + 80, 72, 64, 56, 48, 40, 32, + 24, 16, 8, 0 }; /* @@ -137,39 +137,39 @@ * John Wiley & Sons, pps 98-111 and 472-476. */ static unsigned char -st_14linear2ulaw(PyInt16 pcm_val) /* 2's complement (14-bit range) */ +st_14linear2ulaw(PyInt16 pcm_val) /* 2's complement (14-bit range) */ { - PyInt16 mask; - PyInt16 seg; - unsigned char uval; - - /* The original sox code does this in the calling function, not here */ - pcm_val = pcm_val >> 2; - - /* u-law inverts all bits */ - /* Get the sign and the magnitude of the value. */ - if (pcm_val < 0) { - pcm_val = -pcm_val; - mask = 0x7F; - } else { - mask = 0xFF; - } - if ( pcm_val > CLIP ) pcm_val = CLIP; /* clip the magnitude */ - pcm_val += (BIAS >> 2); - - /* Convert the scaled magnitude to segment number. */ - seg = search(pcm_val, seg_uend, 8); - - /* - * Combine the sign, segment, quantization bits; - * and complement the code word. - */ - if (seg >= 8) /* out of range, return maximum value. */ - return (unsigned char) (0x7F ^ mask); - else { - uval = (unsigned char) (seg << 4) | ((pcm_val >> (seg + 1)) & 0xF); - return (uval ^ mask); - } + PyInt16 mask; + PyInt16 seg; + unsigned char uval; + + /* The original sox code does this in the calling function, not here */ + pcm_val = pcm_val >> 2; + + /* u-law inverts all bits */ + /* Get the sign and the magnitude of the value. */ + if (pcm_val < 0) { + pcm_val = -pcm_val; + mask = 0x7F; + } else { + mask = 0xFF; + } + if ( pcm_val > CLIP ) pcm_val = CLIP; /* clip the magnitude */ + pcm_val += (BIAS >> 2); + + /* Convert the scaled magnitude to segment number. */ + seg = search(pcm_val, seg_uend, 8); + + /* + * Combine the sign, segment, quantization bits; + * and complement the code word. + */ + if (seg >= 8) /* out of range, return maximum value. */ + return (unsigned char) (0x7F ^ mask); + else { + uval = (unsigned char) (seg << 4) | ((pcm_val >> (seg + 1)) & 0xF); + return (uval ^ mask); + } } @@ -234,59 +234,59 @@ * John Wiley & Sons, pps 98-111 and 472-476. */ static unsigned char -st_linear2alaw(PyInt16 pcm_val) /* 2's complement (13-bit range) */ +st_linear2alaw(PyInt16 pcm_val) /* 2's complement (13-bit range) */ { - PyInt16 mask; - short seg; - unsigned char aval; - - /* The original sox code does this in the calling function, not here */ - pcm_val = pcm_val >> 3; - - /* A-law using even bit inversion */ - if (pcm_val >= 0) { - mask = 0xD5; /* sign (7th) bit = 1 */ - } else { - mask = 0x55; /* sign bit = 0 */ - pcm_val = -pcm_val - 1; - } - - /* Convert the scaled magnitude to segment number. */ - seg = search(pcm_val, seg_aend, 8); - - /* Combine the sign, segment, and quantization bits. */ - - if (seg >= 8) /* out of range, return maximum value. */ - return (unsigned char) (0x7F ^ mask); - else { - aval = (unsigned char) seg << SEG_SHIFT; - if (seg < 2) - aval |= (pcm_val >> 1) & QUANT_MASK; - else - aval |= (pcm_val >> seg) & QUANT_MASK; - return (aval ^ mask); - } + PyInt16 mask; + short seg; + unsigned char aval; + + /* The original sox code does this in the calling function, not here */ + pcm_val = pcm_val >> 3; + + /* A-law using even bit inversion */ + if (pcm_val >= 0) { + mask = 0xD5; /* sign (7th) bit = 1 */ + } else { + mask = 0x55; /* sign bit = 0 */ + pcm_val = -pcm_val - 1; + } + + /* Convert the scaled magnitude to segment number. */ + seg = search(pcm_val, seg_aend, 8); + + /* Combine the sign, segment, and quantization bits. */ + + if (seg >= 8) /* out of range, return maximum value. */ + return (unsigned char) (0x7F ^ mask); + else { + aval = (unsigned char) seg << SEG_SHIFT; + if (seg < 2) + aval |= (pcm_val >> 1) & QUANT_MASK; + else + aval |= (pcm_val >> seg) & QUANT_MASK; + return (aval ^ mask); + } } /* End of code taken from sox */ /* Intel ADPCM step variation table */ static int indexTable[16] = { - -1, -1, -1, -1, 2, 4, 6, 8, - -1, -1, -1, -1, 2, 4, 6, 8, + -1, -1, -1, -1, 2, 4, 6, 8, + -1, -1, -1, -1, 2, 4, 6, 8, }; static int stepsizeTable[89] = { - 7, 8, 9, 10, 11, 12, 13, 14, 16, 17, - 19, 21, 23, 25, 28, 31, 34, 37, 41, 45, - 50, 55, 60, 66, 73, 80, 88, 97, 107, 118, - 130, 143, 157, 173, 190, 209, 230, 253, 279, 307, - 337, 371, 408, 449, 494, 544, 598, 658, 724, 796, - 876, 963, 1060, 1166, 1282, 1411, 1552, 1707, 1878, 2066, - 2272, 2499, 2749, 3024, 3327, 3660, 4026, 4428, 4871, 5358, - 5894, 6484, 7132, 7845, 8630, 9493, 10442, 11487, 12635, 13899, - 15289, 16818, 18500, 20350, 22385, 24623, 27086, 29794, 32767 + 7, 8, 9, 10, 11, 12, 13, 14, 16, 17, + 19, 21, 23, 25, 28, 31, 34, 37, 41, 45, + 50, 55, 60, 66, 73, 80, 88, 97, 107, 118, + 130, 143, 157, 173, 190, 209, 230, 253, 279, 307, + 337, 371, 408, 449, 494, 544, 598, 658, 724, 796, + 876, 963, 1060, 1166, 1282, 1411, 1552, 1707, 1878, 2066, + 2272, 2499, 2749, 3024, 3327, 3660, 4026, 4428, 4871, 5358, + 5894, 6484, 7132, 7845, 8630, 9493, 10442, 11487, 12635, 13899, + 15289, 16818, 18500, 20350, 22385, 24623, 27086, 29794, 32767 }; - + #define CHARP(cp, i) ((signed char *)(cp+i)) #define SHORTP(cp, i) ((short *)(cp+i)) #define LONGP(cp, i) ((Py_Int32 *)(cp+i)) @@ -298,137 +298,137 @@ static PyObject * audioop_getsample(PyObject *self, PyObject *args) { - signed char *cp; - int len, size, val = 0; - int i; - - if ( !PyArg_ParseTuple(args, "s#ii:getsample", &cp, &len, &size, &i) ) - return 0; - if ( size != 1 && size != 2 && size != 4 ) { - PyErr_SetString(AudioopError, "Size should be 1, 2 or 4"); - return 0; - } - if ( i < 0 || i >= len/size ) { - PyErr_SetString(AudioopError, "Index out of range"); - return 0; - } - if ( size == 1 ) val = (int)*CHARP(cp, i); - else if ( size == 2 ) val = (int)*SHORTP(cp, i*2); - else if ( size == 4 ) val = (int)*LONGP(cp, i*4); - return PyLong_FromLong(val); + signed char *cp; + int len, size, val = 0; + int i; + + if ( !PyArg_ParseTuple(args, "s#ii:getsample", &cp, &len, &size, &i) ) + return 0; + if ( size != 1 && size != 2 && size != 4 ) { + PyErr_SetString(AudioopError, "Size should be 1, 2 or 4"); + return 0; + } + if ( i < 0 || i >= len/size ) { + PyErr_SetString(AudioopError, "Index out of range"); + return 0; + } + if ( size == 1 ) val = (int)*CHARP(cp, i); + else if ( size == 2 ) val = (int)*SHORTP(cp, i*2); + else if ( size == 4 ) val = (int)*LONGP(cp, i*4); + return PyLong_FromLong(val); } static PyObject * audioop_max(PyObject *self, PyObject *args) { - signed char *cp; - int len, size, val = 0; - int i; - int max = 0; - - if ( !PyArg_ParseTuple(args, "s#i:max", &cp, &len, &size) ) - return 0; - if ( size != 1 && size != 2 && size != 4 ) { - PyErr_SetString(AudioopError, "Size should be 1, 2 or 4"); - return 0; - } - for ( i=0; i max ) max = val; - } - return PyLong_FromLong(max); + signed char *cp; + int len, size, val = 0; + int i; + int max = 0; + + if ( !PyArg_ParseTuple(args, "s#i:max", &cp, &len, &size) ) + return 0; + if ( size != 1 && size != 2 && size != 4 ) { + PyErr_SetString(AudioopError, "Size should be 1, 2 or 4"); + return 0; + } + for ( i=0; i max ) max = val; + } + return PyLong_FromLong(max); } static PyObject * audioop_minmax(PyObject *self, PyObject *args) { - signed char *cp; - int len, size, val = 0; - int i; - int min = 0x7fffffff, max = -0x7fffffff; - - if (!PyArg_ParseTuple(args, "s#i:minmax", &cp, &len, &size)) - return NULL; - if (size != 1 && size != 2 && size != 4) { - PyErr_SetString(AudioopError, "Size should be 1, 2 or 4"); - return NULL; - } - for (i = 0; i < len; i += size) { - 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); - if (val > max) max = val; - if (val < min) min = val; - } - return Py_BuildValue("(ii)", min, max); + signed char *cp; + int len, size, val = 0; + int i; + int min = 0x7fffffff, max = -0x7fffffff; + + if (!PyArg_ParseTuple(args, "s#i:minmax", &cp, &len, &size)) + return NULL; + if (size != 1 && size != 2 && size != 4) { + PyErr_SetString(AudioopError, "Size should be 1, 2 or 4"); + return NULL; + } + for (i = 0; i < len; i += size) { + 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); + if (val > max) max = val; + if (val < min) min = val; + } + return Py_BuildValue("(ii)", min, max); } static PyObject * audioop_avg(PyObject *self, PyObject *args) { - signed char *cp; - int len, size, val = 0; - int i; - double avg = 0.0; - - if ( !PyArg_ParseTuple(args, "s#i:avg", &cp, &len, &size) ) - return 0; - if ( size != 1 && size != 2 && size != 4 ) { - PyErr_SetString(AudioopError, "Size should be 1, 2 or 4"); - return 0; - } - for ( i=0; i>= 1; - len2 >>= 1; - - if ( len1 < len2 ) { - PyErr_SetString(AudioopError, "First sample should be longer"); - return 0; - } - sum_ri_2 = _sum2(cp2, cp2, len2); - sum_aij_2 = _sum2(cp1, cp1, len2); - sum_aij_ri = _sum2(cp1, cp2, len2); - - result = (sum_ri_2*sum_aij_2 - sum_aij_ri*sum_aij_ri) / sum_aij_2; - - best_result = result; - best_j = 0; - j = 0; - - for ( j=1; j<=len1-len2; j++) { - aj_m1 = (double)cp1[j-1]; - aj_lm1 = (double)cp1[j+len2-1]; - - sum_aij_2 = sum_aij_2 + aj_lm1*aj_lm1 - aj_m1*aj_m1; - sum_aij_ri = _sum2(cp1+j, cp2, len2); - - result = (sum_ri_2*sum_aij_2 - sum_aij_ri*sum_aij_ri) - / sum_aij_2; - - if ( result < best_result ) { - best_result = result; - best_j = j; - } - + short *cp1, *cp2; + int len1, len2; + int j, best_j; + double aj_m1, aj_lm1; + double sum_ri_2, sum_aij_2, sum_aij_ri, result, best_result, factor; + + /* Passing a short** for an 's' argument is correct only + if the string contents is aligned for interpretation + as short[]. Due to the definition of PyBytesObject, + this is currently (Python 2.6) the case. */ + if ( !PyArg_ParseTuple(args, "s#s#:findfit", + (char**)&cp1, &len1, (char**)&cp2, &len2) ) + return 0; + if ( len1 & 1 || len2 & 1 ) { + PyErr_SetString(AudioopError, "Strings should be even-sized"); + return 0; + } + len1 >>= 1; + len2 >>= 1; + + if ( len1 < len2 ) { + PyErr_SetString(AudioopError, "First sample should be longer"); + return 0; + } + sum_ri_2 = _sum2(cp2, cp2, len2); + sum_aij_2 = _sum2(cp1, cp1, len2); + sum_aij_ri = _sum2(cp1, cp2, len2); + + result = (sum_ri_2*sum_aij_2 - sum_aij_ri*sum_aij_ri) / sum_aij_2; + + best_result = result; + best_j = 0; + j = 0; + + for ( j=1; j<=len1-len2; j++) { + aj_m1 = (double)cp1[j-1]; + aj_lm1 = (double)cp1[j+len2-1]; + + sum_aij_2 = sum_aij_2 + aj_lm1*aj_lm1 - aj_m1*aj_m1; + sum_aij_ri = _sum2(cp1+j, cp2, len2); + + result = (sum_ri_2*sum_aij_2 - sum_aij_ri*sum_aij_ri) + / sum_aij_2; + + if ( result < best_result ) { + best_result = result; + best_j = j; } - factor = _sum2(cp1+best_j, cp2, len2) / sum_ri_2; - - return Py_BuildValue("(if)", best_j, factor); + } + + factor = _sum2(cp1+best_j, cp2, len2) / sum_ri_2; + + return Py_BuildValue("(if)", best_j, factor); } /* @@ -529,28 +529,28 @@ static PyObject * audioop_findfactor(PyObject *self, PyObject *args) { - short *cp1, *cp2; - int len1, len2; - double sum_ri_2, sum_aij_ri, result; - - if ( !PyArg_ParseTuple(args, "s#s#:findfactor", - (char**)&cp1, &len1, (char**)&cp2, &len2) ) - return 0; - if ( len1 & 1 || len2 & 1 ) { - PyErr_SetString(AudioopError, "Strings should be even-sized"); - return 0; - } - if ( len1 != len2 ) { - PyErr_SetString(AudioopError, "Samples should be same size"); - return 0; - } - len2 >>= 1; - sum_ri_2 = _sum2(cp2, cp2, len2); - sum_aij_ri = _sum2(cp1, cp2, len2); + short *cp1, *cp2; + int len1, len2; + double sum_ri_2, sum_aij_ri, result; + + if ( !PyArg_ParseTuple(args, "s#s#:findfactor", + (char**)&cp1, &len1, (char**)&cp2, &len2) ) + return 0; + if ( len1 & 1 || len2 & 1 ) { + PyErr_SetString(AudioopError, "Strings should be even-sized"); + return 0; + } + if ( len1 != len2 ) { + PyErr_SetString(AudioopError, "Samples should be same size"); + return 0; + } + len2 >>= 1; + sum_ri_2 = _sum2(cp2, cp2, len2); + sum_aij_ri = _sum2(cp1, cp2, len2); - result = sum_aij_ri / sum_ri_2; + result = sum_aij_ri / sum_ri_2; - return PyFloat_FromDouble(result); + return PyFloat_FromDouble(result); } /* @@ -560,1114 +560,1114 @@ static PyObject * audioop_findmax(PyObject *self, PyObject *args) { - short *cp1; - int len1, len2; - int j, best_j; - double aj_m1, aj_lm1; - double result, best_result; - - if ( !PyArg_ParseTuple(args, "s#i:findmax", - (char**)&cp1, &len1, &len2) ) - return 0; - if ( len1 & 1 ) { - PyErr_SetString(AudioopError, "Strings should be even-sized"); - return 0; + short *cp1; + int len1, len2; + int j, best_j; + double aj_m1, aj_lm1; + double result, best_result; + + if ( !PyArg_ParseTuple(args, "s#i:findmax", + (char**)&cp1, &len1, &len2) ) + return 0; + if ( len1 & 1 ) { + PyErr_SetString(AudioopError, "Strings should be even-sized"); + return 0; + } + len1 >>= 1; + + if ( len2 < 0 || len1 < len2 ) { + PyErr_SetString(AudioopError, "Input sample should be longer"); + return 0; + } + + result = _sum2(cp1, cp1, len2); + + best_result = result; + best_j = 0; + j = 0; + + for ( j=1; j<=len1-len2; j++) { + aj_m1 = (double)cp1[j-1]; + aj_lm1 = (double)cp1[j+len2-1]; + + result = result + aj_lm1*aj_lm1 - aj_m1*aj_m1; + + if ( result > best_result ) { + best_result = result; + best_j = j; } - len1 >>= 1; - - if ( len2 < 0 || len1 < len2 ) { - PyErr_SetString(AudioopError, "Input sample should be longer"); - return 0; - } - - result = _sum2(cp1, cp1, len2); - best_result = result; - best_j = 0; - j = 0; - - for ( j=1; j<=len1-len2; j++) { - aj_m1 = (double)cp1[j-1]; - aj_lm1 = (double)cp1[j+len2-1]; - - result = result + aj_lm1*aj_lm1 - aj_m1*aj_m1; - - if ( result > best_result ) { - best_result = result; - best_j = j; - } - - } + } - return PyLong_FromLong(best_j); + return PyLong_FromLong(best_j); } static PyObject * audioop_avgpp(PyObject *self, PyObject *args) { - signed char *cp; - int len, size, val = 0, prevval = 0, prevextremevalid = 0, - prevextreme = 0; - int i; - double avg = 0.0; - int diff, prevdiff, extremediff, nextreme = 0; - - if ( !PyArg_ParseTuple(args, "s#i:avgpp", &cp, &len, &size) ) - return 0; - if ( size != 1 && size != 2 && size != 4 ) { - PyErr_SetString(AudioopError, "Size should be 1, 2 or 4"); - return 0; - } - /* Compute first delta value ahead. Also automatically makes us - ** skip the first extreme value - */ - if ( size == 1 ) prevval = (int)*CHARP(cp, 0); - else if ( size == 2 ) prevval = (int)*SHORTP(cp, 0); - else if ( size == 4 ) prevval = (int)*LONGP(cp, 0); - if ( size == 1 ) val = (int)*CHARP(cp, size); - else if ( size == 2 ) val = (int)*SHORTP(cp, size); - else if ( size == 4 ) val = (int)*LONGP(cp, size); - prevdiff = val - prevval; - - for ( i=size; i max ) - max = extremediff; - } - prevextremevalid = 1; - prevextreme = prevval; - } - prevval = val; - if ( diff != 0 ) - prevdiff = diff; - } - return PyLong_FromLong(max); + signed char *cp; + int len, size, val = 0, prevval = 0, prevextremevalid = 0, + prevextreme = 0; + int i; + int max = 0; + int diff, prevdiff, extremediff; + + if ( !PyArg_ParseTuple(args, "s#i:maxpp", &cp, &len, &size) ) + return 0; + if ( size != 1 && size != 2 && size != 4 ) { + PyErr_SetString(AudioopError, "Size should be 1, 2 or 4"); + return 0; + } + /* Compute first delta value ahead. Also automatically makes us + ** skip the first extreme value + */ + if ( size == 1 ) prevval = (int)*CHARP(cp, 0); + else if ( size == 2 ) prevval = (int)*SHORTP(cp, 0); + else if ( size == 4 ) prevval = (int)*LONGP(cp, 0); + if ( size == 1 ) val = (int)*CHARP(cp, size); + else if ( size == 2 ) val = (int)*SHORTP(cp, size); + else if ( size == 4 ) val = (int)*LONGP(cp, size); + prevdiff = val - prevval; + + for ( i=size; i max ) + max = extremediff; + } + prevextremevalid = 1; + prevextreme = prevval; + } + prevval = val; + if ( diff != 0 ) + prevdiff = diff; + } + return PyLong_FromLong(max); } static PyObject * audioop_cross(PyObject *self, PyObject *args) { - signed char *cp; - int len, size, val = 0; - int i; - int prevval, ncross; - - if ( !PyArg_ParseTuple(args, "s#i:cross", &cp, &len, &size) ) - return 0; - if ( size != 1 && size != 2 && size != 4 ) { - PyErr_SetString(AudioopError, "Size should be 1, 2 or 4"); - return 0; - } - ncross = -1; - prevval = 17; /* Anything <> 0,1 */ - for ( i=0; i> 7; - else if ( size == 2 ) val = ((int)*SHORTP(cp, i)) >> 15; - else if ( size == 4 ) val = ((int)*LONGP(cp, i)) >> 31; - val = val & 1; - if ( val != prevval ) ncross++; - prevval = val; - } - return PyLong_FromLong(ncross); + signed char *cp; + int len, size, val = 0; + int i; + int prevval, ncross; + + if ( !PyArg_ParseTuple(args, "s#i:cross", &cp, &len, &size) ) + return 0; + if ( size != 1 && size != 2 && size != 4 ) { + PyErr_SetString(AudioopError, "Size should be 1, 2 or 4"); + return 0; + } + ncross = -1; + prevval = 17; /* Anything <> 0,1 */ + for ( i=0; i> 7; + else if ( size == 2 ) val = ((int)*SHORTP(cp, i)) >> 15; + else if ( size == 4 ) val = ((int)*LONGP(cp, i)) >> 31; + val = val & 1; + if ( val != prevval ) ncross++; + prevval = val; + } + return PyLong_FromLong(ncross); } static PyObject * audioop_mul(PyObject *self, PyObject *args) { - signed char *cp, *ncp; - int len, size, val = 0; - double factor, fval, maxval; - PyObject *rv; - int i; - - if ( !PyArg_ParseTuple(args, "s#id:mul", &cp, &len, &size, &factor ) ) - return 0; - - if ( size == 1 ) maxval = (double) 0x7f; - else if ( size == 2 ) maxval = (double) 0x7fff; - else if ( size == 4 ) maxval = (double) 0x7fffffff; - else { - PyErr_SetString(AudioopError, "Size should be 1, 2 or 4"); - return 0; - } - - rv = PyBytes_FromStringAndSize(NULL, len); - if ( rv == 0 ) - return 0; - ncp = (signed char *)PyBytes_AsString(rv); - - - for ( i=0; i < len; i += size ) { - 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; - if ( fval > maxval ) fval = maxval; - else if ( fval < -maxval ) fval = -maxval; - val = (int)fval; - 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; - } - return rv; + signed char *cp, *ncp; + int len, size, val = 0; + double factor, fval, maxval; + PyObject *rv; + int i; + + if ( !PyArg_ParseTuple(args, "s#id:mul", &cp, &len, &size, &factor ) ) + return 0; + + if ( size == 1 ) maxval = (double) 0x7f; + else if ( size == 2 ) maxval = (double) 0x7fff; + else if ( size == 4 ) maxval = (double) 0x7fffffff; + else { + PyErr_SetString(AudioopError, "Size should be 1, 2 or 4"); + return 0; + } + + rv = PyBytes_FromStringAndSize(NULL, len); + if ( rv == 0 ) + return 0; + ncp = (signed char *)PyBytes_AsString(rv); + + + for ( i=0; i < len; i += size ) { + 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; + if ( fval > maxval ) fval = maxval; + else if ( fval < -maxval ) fval = -maxval; + val = (int)fval; + 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; + } + return rv; } static PyObject * audioop_tomono(PyObject *self, PyObject *args) { - Py_buffer pcp; - signed char *cp, *ncp; - int len, size, val1 = 0, val2 = 0; - double fac1, fac2, fval, maxval; - PyObject *rv; - int i; - - if ( !PyArg_ParseTuple(args, "s*idd:tomono", - &pcp, &size, &fac1, &fac2 ) ) - return 0; - cp = pcp.buf; - len = pcp.len; - - if ( size == 1 ) maxval = (double) 0x7f; - else if ( size == 2 ) maxval = (double) 0x7fff; - else if ( size == 4 ) maxval = (double) 0x7fffffff; - else { - PyBuffer_Release(&pcp); - PyErr_SetString(AudioopError, "Size should be 1, 2 or 4"); - return 0; - } - - rv = PyBytes_FromStringAndSize(NULL, len/2); - if ( rv == 0 ) - return 0; - ncp = (signed char *)PyBytes_AsString(rv); - - - for ( i=0; i < len; i += size*2 ) { - if ( size == 1 ) val1 = (int)*CHARP(cp, i); - else if ( size == 2 ) val1 = (int)*SHORTP(cp, i); - else if ( size == 4 ) val1 = (int)*LONGP(cp, i); - 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; - if ( fval > maxval ) fval = maxval; - else if ( fval < -maxval ) fval = -maxval; - val1 = (int)fval; - 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; - } - PyBuffer_Release(&pcp); - return rv; + Py_buffer pcp; + signed char *cp, *ncp; + int len, size, val1 = 0, val2 = 0; + double fac1, fac2, fval, maxval; + PyObject *rv; + int i; + + if ( !PyArg_ParseTuple(args, "s*idd:tomono", + &pcp, &size, &fac1, &fac2 ) ) + return 0; + cp = pcp.buf; + len = pcp.len; + + if ( size == 1 ) maxval = (double) 0x7f; + else if ( size == 2 ) maxval = (double) 0x7fff; + else if ( size == 4 ) maxval = (double) 0x7fffffff; + else { + PyBuffer_Release(&pcp); + PyErr_SetString(AudioopError, "Size should be 1, 2 or 4"); + return 0; + } + + rv = PyBytes_FromStringAndSize(NULL, len/2); + if ( rv == 0 ) + return 0; + ncp = (signed char *)PyBytes_AsString(rv); + + + for ( i=0; i < len; i += size*2 ) { + if ( size == 1 ) val1 = (int)*CHARP(cp, i); + else if ( size == 2 ) val1 = (int)*SHORTP(cp, i); + else if ( size == 4 ) val1 = (int)*LONGP(cp, i); + 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; + if ( fval > maxval ) fval = maxval; + else if ( fval < -maxval ) fval = -maxval; + val1 = (int)fval; + 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; + } + PyBuffer_Release(&pcp); + return rv; } static PyObject * audioop_tostereo(PyObject *self, PyObject *args) { - signed char *cp, *ncp; - int len, new_len, size, val1, val2, val = 0; - double fac1, fac2, fval, maxval; - PyObject *rv; - int i; - - if ( !PyArg_ParseTuple(args, "s#idd:tostereo", - &cp, &len, &size, &fac1, &fac2 ) ) - return 0; - - if ( size == 1 ) maxval = (double) 0x7f; - else if ( size == 2 ) maxval = (double) 0x7fff; - else if ( size == 4 ) maxval = (double) 0x7fffffff; - else { - PyErr_SetString(AudioopError, "Size should be 1, 2 or 4"); - return 0; - } - - new_len = len*2; - if (new_len < 0) { - PyErr_SetString(PyExc_MemoryError, - "not enough memory for output buffer"); - return 0; - } + signed char *cp, *ncp; + int len, new_len, size, val1, val2, val = 0; + double fac1, fac2, fval, maxval; + PyObject *rv; + int i; + + if ( !PyArg_ParseTuple(args, "s#idd:tostereo", + &cp, &len, &size, &fac1, &fac2 ) ) + return 0; + + if ( size == 1 ) maxval = (double) 0x7f; + else if ( size == 2 ) maxval = (double) 0x7fff; + else if ( size == 4 ) maxval = (double) 0x7fffffff; + else { + PyErr_SetString(AudioopError, "Size should be 1, 2 or 4"); + return 0; + } + + new_len = len*2; + if (new_len < 0) { + PyErr_SetString(PyExc_MemoryError, + "not enough memory for output buffer"); + return 0; + } + + rv = PyBytes_FromStringAndSize(NULL, new_len); + if ( rv == 0 ) + return 0; + ncp = (signed char *)PyBytes_AsString(rv); - rv = PyBytes_FromStringAndSize(NULL, new_len); - if ( rv == 0 ) - return 0; - ncp = (signed char *)PyBytes_AsString(rv); - - - for ( i=0; i < len; i += size ) { - 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*fac1; - if ( fval > maxval ) fval = maxval; - else if ( fval < -maxval ) fval = -maxval; - val1 = (int)fval; - - fval = (double)val*fac2; - if ( fval > maxval ) fval = maxval; - else if ( fval < -maxval ) fval = -maxval; - val2 = (int)fval; - - 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; - - if ( size == 1 ) *CHARP(ncp, i*2+1) = (signed char)val2; - else if ( size == 2 ) *SHORTP(ncp, i*2+2) = (short)val2; - else if ( size == 4 ) *LONGP(ncp, i*2+4) = (Py_Int32)val2; - } - return rv; + + for ( i=0; i < len; i += size ) { + 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*fac1; + if ( fval > maxval ) fval = maxval; + else if ( fval < -maxval ) fval = -maxval; + val1 = (int)fval; + + fval = (double)val*fac2; + if ( fval > maxval ) fval = maxval; + else if ( fval < -maxval ) fval = -maxval; + val2 = (int)fval; + + 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; + + if ( size == 1 ) *CHARP(ncp, i*2+1) = (signed char)val2; + else if ( size == 2 ) *SHORTP(ncp, i*2+2) = (short)val2; + else if ( size == 4 ) *LONGP(ncp, i*2+4) = (Py_Int32)val2; + } + return rv; } static PyObject * audioop_add(PyObject *self, PyObject *args) { - signed char *cp1, *cp2, *ncp; - int len1, len2, size, val1 = 0, val2 = 0, maxval, newval; - PyObject *rv; - int i; - - if ( !PyArg_ParseTuple(args, "s#s#i:add", - &cp1, &len1, &cp2, &len2, &size ) ) - return 0; - - if ( len1 != len2 ) { - PyErr_SetString(AudioopError, "Lengths should be the same"); - return 0; - } - - if ( size == 1 ) maxval = 0x7f; - else if ( size == 2 ) maxval = 0x7fff; - else if ( size == 4 ) maxval = 0x7fffffff; - else { - PyErr_SetString(AudioopError, "Size should be 1, 2 or 4"); - return 0; - } - - rv = PyBytes_FromStringAndSize(NULL, len1); - if ( rv == 0 ) - return 0; - ncp = (signed char *)PyBytes_AsString(rv); - - for ( i=0; i < len1; i += size ) { - if ( size == 1 ) val1 = (int)*CHARP(cp1, i); - else if ( size == 2 ) val1 = (int)*SHORTP(cp1, i); - else if ( size == 4 ) val1 = (int)*LONGP(cp1, i); - - if ( size == 1 ) val2 = (int)*CHARP(cp2, i); - else if ( size == 2 ) val2 = (int)*SHORTP(cp2, i); - else if ( size == 4 ) val2 = (int)*LONGP(cp2, i); - - newval = val1 + val2; - /* truncate in case of overflow */ - if (newval > maxval) newval = maxval; - else if (newval < -maxval) newval = -maxval; - else if (size == 4 && (newval^val1) < 0 && (newval^val2) < 0) - newval = val1 > 0 ? maxval : - maxval; - - if ( size == 1 ) *CHARP(ncp, i) = (signed char)newval; - else if ( size == 2 ) *SHORTP(ncp, i) = (short)newval; - else if ( size == 4 ) *LONGP(ncp, i) = (Py_Int32)newval; - } - return rv; + signed char *cp1, *cp2, *ncp; + int len1, len2, size, val1 = 0, val2 = 0, maxval, newval; + PyObject *rv; + int i; + + if ( !PyArg_ParseTuple(args, "s#s#i:add", + &cp1, &len1, &cp2, &len2, &size ) ) + return 0; + + if ( len1 != len2 ) { + PyErr_SetString(AudioopError, "Lengths should be the same"); + return 0; + } + + if ( size == 1 ) maxval = 0x7f; + else if ( size == 2 ) maxval = 0x7fff; + else if ( size == 4 ) maxval = 0x7fffffff; + else { + PyErr_SetString(AudioopError, "Size should be 1, 2 or 4"); + return 0; + } + + rv = PyBytes_FromStringAndSize(NULL, len1); + if ( rv == 0 ) + return 0; + ncp = (signed char *)PyBytes_AsString(rv); + + for ( i=0; i < len1; i += size ) { + if ( size == 1 ) val1 = (int)*CHARP(cp1, i); + else if ( size == 2 ) val1 = (int)*SHORTP(cp1, i); + else if ( size == 4 ) val1 = (int)*LONGP(cp1, i); + + if ( size == 1 ) val2 = (int)*CHARP(cp2, i); + else if ( size == 2 ) val2 = (int)*SHORTP(cp2, i); + else if ( size == 4 ) val2 = (int)*LONGP(cp2, i); + + newval = val1 + val2; + /* truncate in case of overflow */ + if (newval > maxval) newval = maxval; + else if (newval < -maxval) newval = -maxval; + else if (size == 4 && (newval^val1) < 0 && (newval^val2) < 0) + newval = val1 > 0 ? maxval : - maxval; + + if ( size == 1 ) *CHARP(ncp, i) = (signed char)newval; + else if ( size == 2 ) *SHORTP(ncp, i) = (short)newval; + else if ( size == 4 ) *LONGP(ncp, i) = (Py_Int32)newval; + } + return rv; } static PyObject * audioop_bias(PyObject *self, PyObject *args) { - signed char *cp, *ncp; - int len, size, val = 0; - PyObject *rv; - int i; - int bias; - - if ( !PyArg_ParseTuple(args, "s#ii:bias", - &cp, &len, &size , &bias) ) - return 0; - - if ( size != 1 && size != 2 && size != 4) { - PyErr_SetString(AudioopError, "Size should be 1, 2 or 4"); - return 0; - } - - rv = PyBytes_FromStringAndSize(NULL, len); - if ( rv == 0 ) - return 0; - ncp = (signed char *)PyBytes_AsString(rv); - - - for ( i=0; i < len; i += size ) { - 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); - - if ( size == 1 ) *CHARP(ncp, i) = (signed char)(val+bias); - else if ( size == 2 ) *SHORTP(ncp, i) = (short)(val+bias); - else if ( size == 4 ) *LONGP(ncp, i) = (Py_Int32)(val+bias); - } - return rv; + signed char *cp, *ncp; + int len, size, val = 0; + PyObject *rv; + int i; + int bias; + + if ( !PyArg_ParseTuple(args, "s#ii:bias", + &cp, &len, &size , &bias) ) + return 0; + + if ( size != 1 && size != 2 && size != 4) { + PyErr_SetString(AudioopError, "Size should be 1, 2 or 4"); + return 0; + } + + rv = PyBytes_FromStringAndSize(NULL, len); + if ( rv == 0 ) + return 0; + ncp = (signed char *)PyBytes_AsString(rv); + + + for ( i=0; i < len; i += size ) { + 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); + + if ( size == 1 ) *CHARP(ncp, i) = (signed char)(val+bias); + else if ( size == 2 ) *SHORTP(ncp, i) = (short)(val+bias); + else if ( size == 4 ) *LONGP(ncp, i) = (Py_Int32)(val+bias); + } + return rv; } static PyObject * audioop_reverse(PyObject *self, PyObject *args) { - signed char *cp; - unsigned char *ncp; - int len, size, val = 0; - PyObject *rv; - int i, j; - - if ( !PyArg_ParseTuple(args, "s#i:reverse", - &cp, &len, &size) ) - return 0; - - if ( size != 1 && size != 2 && size != 4 ) { - PyErr_SetString(AudioopError, "Size should be 1, 2 or 4"); - return 0; - } - - rv = PyBytes_FromStringAndSize(NULL, len); - if ( rv == 0 ) - return 0; - ncp = (unsigned char *)PyBytes_AsString(rv); - - for ( i=0; i < len; i += size ) { - if ( size == 1 ) val = ((int)*CHARP(cp, i)) << 8; - else if ( size == 2 ) val = (int)*SHORTP(cp, i); - else if ( size == 4 ) val = ((int)*LONGP(cp, i)) >> 16; - - j = len - i - size; - - if ( size == 1 ) *CHARP(ncp, j) = (signed char)(val >> 8); - else if ( size == 2 ) *SHORTP(ncp, j) = (short)(val); - else if ( size == 4 ) *LONGP(ncp, j) = (Py_Int32)(val<<16); - } - return rv; + signed char *cp; + unsigned char *ncp; + int len, size, val = 0; + PyObject *rv; + int i, j; + + if ( !PyArg_ParseTuple(args, "s#i:reverse", + &cp, &len, &size) ) + return 0; + + if ( size != 1 && size != 2 && size != 4 ) { + PyErr_SetString(AudioopError, "Size should be 1, 2 or 4"); + return 0; + } + + rv = PyBytes_FromStringAndSize(NULL, len); + if ( rv == 0 ) + return 0; + ncp = (unsigned char *)PyBytes_AsString(rv); + + for ( i=0; i < len; i += size ) { + if ( size == 1 ) val = ((int)*CHARP(cp, i)) << 8; + else if ( size == 2 ) val = (int)*SHORTP(cp, i); + else if ( size == 4 ) val = ((int)*LONGP(cp, i)) >> 16; + + j = len - i - size; + + if ( size == 1 ) *CHARP(ncp, j) = (signed char)(val >> 8); + else if ( size == 2 ) *SHORTP(ncp, j) = (short)(val); + else if ( size == 4 ) *LONGP(ncp, j) = (Py_Int32)(val<<16); + } + return rv; } static PyObject * audioop_lin2lin(PyObject *self, PyObject *args) { - signed char *cp; - unsigned char *ncp; - int len, new_len, size, size2, val = 0; - PyObject *rv; - int i, j; - - if ( !PyArg_ParseTuple(args, "s#ii:lin2lin", - &cp, &len, &size, &size2) ) - return 0; - - if ( (size != 1 && size != 2 && size != 4) || - (size2 != 1 && size2 != 2 && size2 != 4)) { - PyErr_SetString(AudioopError, "Size should be 1, 2 or 4"); - return 0; - } - - new_len = (len/size)*size2; - if (new_len < 0) { - PyErr_SetString(PyExc_MemoryError, - "not enough memory for output buffer"); - return 0; - } - rv = PyBytes_FromStringAndSize(NULL, new_len); - if ( rv == 0 ) - return 0; - ncp = (unsigned char *)PyBytes_AsString(rv); - - for ( i=0, j=0; i < len; i += size, j += size2 ) { - if ( size == 1 ) val = ((int)*CHARP(cp, i)) << 8; - else if ( size == 2 ) val = (int)*SHORTP(cp, i); - else if ( size == 4 ) val = ((int)*LONGP(cp, i)) >> 16; - - if ( size2 == 1 ) *CHARP(ncp, j) = (signed char)(val >> 8); - else if ( size2 == 2 ) *SHORTP(ncp, j) = (short)(val); - else if ( size2 == 4 ) *LONGP(ncp, j) = (Py_Int32)(val<<16); - } - return rv; + signed char *cp; + unsigned char *ncp; + int len, new_len, size, size2, val = 0; + PyObject *rv; + int i, j; + + if ( !PyArg_ParseTuple(args, "s#ii:lin2lin", + &cp, &len, &size, &size2) ) + return 0; + + if ( (size != 1 && size != 2 && size != 4) || + (size2 != 1 && size2 != 2 && size2 != 4)) { + PyErr_SetString(AudioopError, "Size should be 1, 2 or 4"); + return 0; + } + + new_len = (len/size)*size2; + if (new_len < 0) { + PyErr_SetString(PyExc_MemoryError, + "not enough memory for output buffer"); + return 0; + } + rv = PyBytes_FromStringAndSize(NULL, new_len); + if ( rv == 0 ) + return 0; + ncp = (unsigned char *)PyBytes_AsString(rv); + + for ( i=0, j=0; i < len; i += size, j += size2 ) { + if ( size == 1 ) val = ((int)*CHARP(cp, i)) << 8; + else if ( size == 2 ) val = (int)*SHORTP(cp, i); + else if ( size == 4 ) val = ((int)*LONGP(cp, i)) >> 16; + + if ( size2 == 1 ) *CHARP(ncp, j) = (signed char)(val >> 8); + else if ( size2 == 2 ) *SHORTP(ncp, j) = (short)(val); + else if ( size2 == 4 ) *LONGP(ncp, j) = (Py_Int32)(val<<16); + } + return rv; } static int gcd(int a, int b) { - while (b > 0) { - int tmp = a % b; - a = b; - b = tmp; - } - return a; + while (b > 0) { + int tmp = a % b; + a = b; + b = tmp; + } + return a; } static PyObject * audioop_ratecv(PyObject *self, PyObject *args) { - char *cp, *ncp; - int len, size, nchannels, inrate, outrate, weightA, weightB; - int chan, d, *prev_i, *cur_i, cur_o; - PyObject *state, *samps, *str, *rv = NULL; - int bytes_per_frame; - size_t alloc_size; - - weightA = 1; - weightB = 0; - if (!PyArg_ParseTuple(args, "s#iiiiO|ii:ratecv", &cp, &len, &size, - &nchannels, &inrate, &outrate, &state, - &weightA, &weightB)) - return NULL; - if (size != 1 && size != 2 && size != 4) { - PyErr_SetString(AudioopError, "Size should be 1, 2 or 4"); - return NULL; - } - if (nchannels < 1) { - PyErr_SetString(AudioopError, "# of channels should be >= 1"); - return NULL; - } - bytes_per_frame = size * nchannels; - if (bytes_per_frame / nchannels != size) { - /* This overflow test is rigorously correct because - both multiplicands are >= 1. Use the argument names - from the docs for the error msg. */ - PyErr_SetString(PyExc_OverflowError, - "width * nchannels too big for a C int"); - return NULL; - } - if (weightA < 1 || weightB < 0) { - PyErr_SetString(AudioopError, - "weightA should be >= 1, weightB should be >= 0"); - return NULL; - } - if (len % bytes_per_frame != 0) { - PyErr_SetString(AudioopError, "not a whole number of frames"); - return NULL; - } - if (inrate <= 0 || outrate <= 0) { - PyErr_SetString(AudioopError, "sampling rate not > 0"); - return NULL; - } - /* divide inrate and outrate by their greatest common divisor */ - d = gcd(inrate, outrate); - inrate /= d; - outrate /= d; - - alloc_size = sizeof(int) * (unsigned)nchannels; - if (alloc_size < (unsigned)nchannels) { - PyErr_SetString(PyExc_MemoryError, - "not enough memory for output buffer"); - return 0; - } - prev_i = (int *) malloc(alloc_size); - cur_i = (int *) malloc(alloc_size); - if (prev_i == NULL || cur_i == NULL) { - (void) PyErr_NoMemory(); + char *cp, *ncp; + int len, size, nchannels, inrate, outrate, weightA, weightB; + int chan, d, *prev_i, *cur_i, cur_o; + PyObject *state, *samps, *str, *rv = NULL; + int bytes_per_frame; + size_t alloc_size; + + weightA = 1; + weightB = 0; + if (!PyArg_ParseTuple(args, "s#iiiiO|ii:ratecv", &cp, &len, &size, + &nchannels, &inrate, &outrate, &state, + &weightA, &weightB)) + return NULL; + if (size != 1 && size != 2 && size != 4) { + PyErr_SetString(AudioopError, "Size should be 1, 2 or 4"); + return NULL; + } + if (nchannels < 1) { + PyErr_SetString(AudioopError, "# of channels should be >= 1"); + return NULL; + } + bytes_per_frame = size * nchannels; + if (bytes_per_frame / nchannels != size) { + /* This overflow test is rigorously correct because + both multiplicands are >= 1. Use the argument names + from the docs for the error msg. */ + PyErr_SetString(PyExc_OverflowError, + "width * nchannels too big for a C int"); + return NULL; + } + if (weightA < 1 || weightB < 0) { + PyErr_SetString(AudioopError, + "weightA should be >= 1, weightB should be >= 0"); + return NULL; + } + if (len % bytes_per_frame != 0) { + PyErr_SetString(AudioopError, "not a whole number of frames"); + return NULL; + } + if (inrate <= 0 || outrate <= 0) { + PyErr_SetString(AudioopError, "sampling rate not > 0"); + return NULL; + } + /* divide inrate and outrate by their greatest common divisor */ + d = gcd(inrate, outrate); + inrate /= d; + outrate /= d; + + alloc_size = sizeof(int) * (unsigned)nchannels; + if (alloc_size < (unsigned)nchannels) { + PyErr_SetString(PyExc_MemoryError, + "not enough memory for output buffer"); + return 0; + } + prev_i = (int *) malloc(alloc_size); + cur_i = (int *) malloc(alloc_size); + if (prev_i == NULL || cur_i == NULL) { + (void) PyErr_NoMemory(); + goto exit; + } + + len /= bytes_per_frame; /* # of frames */ + + if (state == Py_None) { + d = -outrate; + for (chan = 0; chan < nchannels; chan++) + prev_i[chan] = cur_i[chan] = 0; + } + else { + if (!PyArg_ParseTuple(state, + "iO!;audioop.ratecv: illegal state argument", + &d, &PyTuple_Type, &samps)) + goto exit; + if (PyTuple_Size(samps) != nchannels) { + PyErr_SetString(AudioopError, + "illegal state argument"); + goto exit; + } + for (chan = 0; chan < nchannels; chan++) { + if (!PyArg_ParseTuple(PyTuple_GetItem(samps, chan), + "ii:ratecv", &prev_i[chan], + &cur_i[chan])) goto exit; } + } - len /= bytes_per_frame; /* # of frames */ + /* str <- Space for the output buffer. */ + { + /* There are len input frames, so we need (mathematically) + ceiling(len*outrate/inrate) output frames, and each frame + requires bytes_per_frame bytes. Computing this + without spurious overflow is the challenge; we can + settle for a reasonable upper bound, though. */ + int ceiling; /* the number of output frames */ + int nbytes; /* the number of output bytes needed */ + int q = len / inrate; + /* Now len = q * inrate + r exactly (with r = len % inrate), + and this is less than q * inrate + inrate = (q+1)*inrate. + So a reasonable upper bound on len*outrate/inrate is + ((q+1)*inrate)*outrate/inrate = + (q+1)*outrate. + */ + ceiling = (q+1) * outrate; + nbytes = ceiling * bytes_per_frame; + /* See whether anything overflowed; if not, get the space. */ + if (q+1 < 0 || + ceiling / outrate != q+1 || + nbytes / bytes_per_frame != ceiling) + str = NULL; + else + str = PyBytes_FromStringAndSize(NULL, nbytes); - if (state == Py_None) { - d = -outrate; + if (str == NULL) { + PyErr_SetString(PyExc_MemoryError, + "not enough memory for output buffer"); + goto exit; + } + } + ncp = PyBytes_AsString(str); + + for (;;) { + while (d < 0) { + if (len == 0) { + samps = PyTuple_New(nchannels); + if (samps == NULL) + goto exit; for (chan = 0; chan < nchannels; chan++) - prev_i[chan] = cur_i[chan] = 0; - } - else { - if (!PyArg_ParseTuple(state, - "iO!;audioop.ratecv: illegal state argument", - &d, &PyTuple_Type, &samps)) - goto exit; - if (PyTuple_Size(samps) != nchannels) { - PyErr_SetString(AudioopError, - "illegal state argument"); - goto exit; - } - for (chan = 0; chan < nchannels; chan++) { - if (!PyArg_ParseTuple(PyTuple_GetItem(samps, chan), - "ii:ratecv", &prev_i[chan], - &cur_i[chan])) - goto exit; - } - } - - /* str <- Space for the output buffer. */ - { - /* There are len input frames, so we need (mathematically) - ceiling(len*outrate/inrate) output frames, and each frame - requires bytes_per_frame bytes. Computing this - without spurious overflow is the challenge; we can - settle for a reasonable upper bound, though. */ - int ceiling; /* the number of output frames */ - int nbytes; /* the number of output bytes needed */ - int q = len / inrate; - /* Now len = q * inrate + r exactly (with r = len % inrate), - and this is less than q * inrate + inrate = (q+1)*inrate. - So a reasonable upper bound on len*outrate/inrate is - ((q+1)*inrate)*outrate/inrate = - (q+1)*outrate. - */ - ceiling = (q+1) * outrate; - nbytes = ceiling * bytes_per_frame; - /* See whether anything overflowed; if not, get the space. */ - if (q+1 < 0 || - ceiling / outrate != q+1 || - nbytes / bytes_per_frame != ceiling) - str = NULL; - else - str = PyBytes_FromStringAndSize(NULL, nbytes); - - if (str == NULL) { - PyErr_SetString(PyExc_MemoryError, - "not enough memory for output buffer"); - goto exit; - } - } - ncp = PyBytes_AsString(str); - - for (;;) { - while (d < 0) { - if (len == 0) { - samps = PyTuple_New(nchannels); - if (samps == NULL) - goto exit; - for (chan = 0; chan < nchannels; chan++) - PyTuple_SetItem(samps, chan, - Py_BuildValue("(ii)", - prev_i[chan], - cur_i[chan])); - if (PyErr_Occurred()) - goto exit; - /* We have checked before that the length - * of the string fits into int. */ - len = (int)(ncp - PyBytes_AsString(str)); - rv = PyBytes_FromStringAndSize - (PyBytes_AsString(str), len); - Py_DECREF(str); - str = rv; - if (str == NULL) - goto exit; - rv = Py_BuildValue("(O(iO))", str, d, samps); - Py_DECREF(samps); - Py_DECREF(str); - goto exit; /* return rv */ - } - for (chan = 0; chan < nchannels; chan++) { - prev_i[chan] = cur_i[chan]; - if (size == 1) - cur_i[chan] = ((int)*CHARP(cp, 0)) << 8; - else if (size == 2) - cur_i[chan] = (int)*SHORTP(cp, 0); - else if (size == 4) - cur_i[chan] = ((int)*LONGP(cp, 0)) >> 16; - cp += size; - /* implements a simple digital filter */ - cur_i[chan] = - (weightA * cur_i[chan] + - weightB * prev_i[chan]) / - (weightA + weightB); - } - len--; - d += outrate; - } - while (d >= 0) { - for (chan = 0; chan < nchannels; chan++) { - cur_o = (prev_i[chan] * d + - cur_i[chan] * (outrate - d)) / - outrate; - if (size == 1) - *CHARP(ncp, 0) = (signed char)(cur_o >> 8); - else if (size == 2) - *SHORTP(ncp, 0) = (short)(cur_o); - else if (size == 4) - *LONGP(ncp, 0) = (Py_Int32)(cur_o<<16); - ncp += size; - } - d -= inrate; - } + PyTuple_SetItem(samps, chan, + Py_BuildValue("(ii)", + prev_i[chan], + cur_i[chan])); + if (PyErr_Occurred()) + goto exit; + /* We have checked before that the length + * of the string fits into int. */ + len = (int)(ncp - PyBytes_AsString(str)); + rv = PyBytes_FromStringAndSize + (PyBytes_AsString(str), len); + Py_DECREF(str); + str = rv; + if (str == NULL) + goto exit; + rv = Py_BuildValue("(O(iO))", str, d, samps); + Py_DECREF(samps); + Py_DECREF(str); + goto exit; /* return rv */ + } + for (chan = 0; chan < nchannels; chan++) { + prev_i[chan] = cur_i[chan]; + if (size == 1) + cur_i[chan] = ((int)*CHARP(cp, 0)) << 8; + else if (size == 2) + cur_i[chan] = (int)*SHORTP(cp, 0); + else if (size == 4) + cur_i[chan] = ((int)*LONGP(cp, 0)) >> 16; + cp += size; + /* implements a simple digital filter */ + cur_i[chan] = + (weightA * cur_i[chan] + + weightB * prev_i[chan]) / + (weightA + weightB); + } + len--; + d += outrate; + } + while (d >= 0) { + for (chan = 0; chan < nchannels; chan++) { + cur_o = (prev_i[chan] * d + + cur_i[chan] * (outrate - d)) / + outrate; + if (size == 1) + *CHARP(ncp, 0) = (signed char)(cur_o >> 8); + else if (size == 2) + *SHORTP(ncp, 0) = (short)(cur_o); + else if (size == 4) + *LONGP(ncp, 0) = (Py_Int32)(cur_o<<16); + ncp += size; + } + d -= inrate; } + } exit: - if (prev_i != NULL) - free(prev_i); - if (cur_i != NULL) - free(cur_i); - return rv; + if (prev_i != NULL) + free(prev_i); + if (cur_i != NULL) + free(cur_i); + return rv; } static PyObject * audioop_lin2ulaw(PyObject *self, PyObject *args) { - signed char *cp; - unsigned char *ncp; - int len, size, val = 0; - PyObject *rv; - int i; - - if ( !PyArg_ParseTuple(args, "s#i:lin2ulaw", - &cp, &len, &size) ) - return 0 ; - - if ( size != 1 && size != 2 && size != 4) { - PyErr_SetString(AudioopError, "Size should be 1, 2 or 4"); - return 0; - } - - rv = PyBytes_FromStringAndSize(NULL, len/size); - if ( rv == 0 ) - return 0; - ncp = (unsigned char *)PyBytes_AsString(rv); - - for ( i=0; i < len; i += size ) { - if ( size == 1 ) val = ((int)*CHARP(cp, i)) << 8; - else if ( size == 2 ) val = (int)*SHORTP(cp, i); - else if ( size == 4 ) val = ((int)*LONGP(cp, i)) >> 16; - - *ncp++ = st_14linear2ulaw(val); - } - return rv; + signed char *cp; + unsigned char *ncp; + int len, size, val = 0; + PyObject *rv; + int i; + + if ( !PyArg_ParseTuple(args, "s#i:lin2ulaw", + &cp, &len, &size) ) + return 0 ; + + if ( size != 1 && size != 2 && size != 4) { + PyErr_SetString(AudioopError, "Size should be 1, 2 or 4"); + return 0; + } + + rv = PyBytes_FromStringAndSize(NULL, len/size); + if ( rv == 0 ) + return 0; + ncp = (unsigned char *)PyBytes_AsString(rv); + + for ( i=0; i < len; i += size ) { + if ( size == 1 ) val = ((int)*CHARP(cp, i)) << 8; + else if ( size == 2 ) val = (int)*SHORTP(cp, i); + else if ( size == 4 ) val = ((int)*LONGP(cp, i)) >> 16; + + *ncp++ = st_14linear2ulaw(val); + } + return rv; } static PyObject * audioop_ulaw2lin(PyObject *self, PyObject *args) { - unsigned char *cp; - unsigned char cval; - signed char *ncp; - int len, new_len, size, val; - PyObject *rv; - int i; - - if ( !PyArg_ParseTuple(args, "s#i:ulaw2lin", - &cp, &len, &size) ) - return 0; - - if ( size != 1 && size != 2 && size != 4) { - PyErr_SetString(AudioopError, "Size should be 1, 2 or 4"); - return 0; - } - - new_len = len*size; - if (new_len < 0) { - PyErr_SetString(PyExc_MemoryError, - "not enough memory for output buffer"); - return 0; - } - rv = PyBytes_FromStringAndSize(NULL, new_len); - if ( rv == 0 ) - return 0; - ncp = (signed char *)PyBytes_AsString(rv); - - for ( i=0; i < new_len; i += size ) { - cval = *cp++; - val = st_ulaw2linear16(cval); - - if ( size == 1 ) *CHARP(ncp, i) = (signed char)(val >> 8); - else if ( size == 2 ) *SHORTP(ncp, i) = (short)(val); - else if ( size == 4 ) *LONGP(ncp, i) = (Py_Int32)(val<<16); - } - return rv; + unsigned char *cp; + unsigned char cval; + signed char *ncp; + int len, new_len, size, val; + PyObject *rv; + int i; + + if ( !PyArg_ParseTuple(args, "s#i:ulaw2lin", + &cp, &len, &size) ) + return 0; + + if ( size != 1 && size != 2 && size != 4) { + PyErr_SetString(AudioopError, "Size should be 1, 2 or 4"); + return 0; + } + + new_len = len*size; + if (new_len < 0) { + PyErr_SetString(PyExc_MemoryError, + "not enough memory for output buffer"); + return 0; + } + rv = PyBytes_FromStringAndSize(NULL, new_len); + if ( rv == 0 ) + return 0; + ncp = (signed char *)PyBytes_AsString(rv); + + for ( i=0; i < new_len; i += size ) { + cval = *cp++; + val = st_ulaw2linear16(cval); + + if ( size == 1 ) *CHARP(ncp, i) = (signed char)(val >> 8); + else if ( size == 2 ) *SHORTP(ncp, i) = (short)(val); + else if ( size == 4 ) *LONGP(ncp, i) = (Py_Int32)(val<<16); + } + return rv; } static PyObject * audioop_lin2alaw(PyObject *self, PyObject *args) { - signed char *cp; - unsigned char *ncp; - int len, size, val = 0; - PyObject *rv; - int i; - - if ( !PyArg_ParseTuple(args, "s#i:lin2alaw", - &cp, &len, &size) ) - return 0; - - if ( size != 1 && size != 2 && size != 4) { - PyErr_SetString(AudioopError, "Size should be 1, 2 or 4"); - return 0; - } - - rv = PyBytes_FromStringAndSize(NULL, len/size); - if ( rv == 0 ) - return 0; - ncp = (unsigned char *)PyBytes_AsString(rv); - - for ( i=0; i < len; i += size ) { - if ( size == 1 ) val = ((int)*CHARP(cp, i)) << 8; - else if ( size == 2 ) val = (int)*SHORTP(cp, i); - else if ( size == 4 ) val = ((int)*LONGP(cp, i)) >> 16; - - *ncp++ = st_linear2alaw(val); - } - return rv; + signed char *cp; + unsigned char *ncp; + int len, size, val = 0; + PyObject *rv; + int i; + + if ( !PyArg_ParseTuple(args, "s#i:lin2alaw", + &cp, &len, &size) ) + return 0; + + if ( size != 1 && size != 2 && size != 4) { + PyErr_SetString(AudioopError, "Size should be 1, 2 or 4"); + return 0; + } + + rv = PyBytes_FromStringAndSize(NULL, len/size); + if ( rv == 0 ) + return 0; + ncp = (unsigned char *)PyBytes_AsString(rv); + + for ( i=0; i < len; i += size ) { + if ( size == 1 ) val = ((int)*CHARP(cp, i)) << 8; + else if ( size == 2 ) val = (int)*SHORTP(cp, i); + else if ( size == 4 ) val = ((int)*LONGP(cp, i)) >> 16; + + *ncp++ = st_linear2alaw(val); + } + return rv; } static PyObject * audioop_alaw2lin(PyObject *self, PyObject *args) { - unsigned char *cp; - unsigned char cval; - signed char *ncp; - int len, new_len, size, val; - PyObject *rv; - int i; - - if ( !PyArg_ParseTuple(args, "s#i:alaw2lin", - &cp, &len, &size) ) - return 0; - - if ( size != 1 && size != 2 && size != 4) { - PyErr_SetString(AudioopError, "Size should be 1, 2 or 4"); - return 0; - } - - new_len = len*size; - if (new_len < 0) { - PyErr_SetString(PyExc_MemoryError, - "not enough memory for output buffer"); - return 0; - } - rv = PyBytes_FromStringAndSize(NULL, new_len); - if ( rv == 0 ) - return 0; - ncp = (signed char *)PyBytes_AsString(rv); - - for ( i=0; i < new_len; i += size ) { - cval = *cp++; - val = st_alaw2linear16(cval); - - if ( size == 1 ) *CHARP(ncp, i) = (signed char)(val >> 8); - else if ( size == 2 ) *SHORTP(ncp, i) = (short)(val); - else if ( size == 4 ) *LONGP(ncp, i) = (Py_Int32)(val<<16); - } - return rv; + unsigned char *cp; + unsigned char cval; + signed char *ncp; + int len, new_len, size, val; + PyObject *rv; + int i; + + if ( !PyArg_ParseTuple(args, "s#i:alaw2lin", + &cp, &len, &size) ) + return 0; + + if ( size != 1 && size != 2 && size != 4) { + PyErr_SetString(AudioopError, "Size should be 1, 2 or 4"); + return 0; + } + + new_len = len*size; + if (new_len < 0) { + PyErr_SetString(PyExc_MemoryError, + "not enough memory for output buffer"); + return 0; + } + rv = PyBytes_FromStringAndSize(NULL, new_len); + if ( rv == 0 ) + return 0; + ncp = (signed char *)PyBytes_AsString(rv); + + for ( i=0; i < new_len; i += size ) { + cval = *cp++; + val = st_alaw2linear16(cval); + + if ( size == 1 ) *CHARP(ncp, i) = (signed char)(val >> 8); + else if ( size == 2 ) *SHORTP(ncp, i) = (short)(val); + else if ( size == 4 ) *LONGP(ncp, i) = (Py_Int32)(val<<16); + } + return rv; } static PyObject * audioop_lin2adpcm(PyObject *self, PyObject *args) { - signed char *cp; - signed char *ncp; - int len, size, val = 0, step, valpred, delta, - index, sign, vpdiff, diff; - PyObject *rv, *state, *str; - int i, outputbuffer = 0, bufferstep; - - if ( !PyArg_ParseTuple(args, "s#iO:lin2adpcm", - &cp, &len, &size, &state) ) - return 0; - - - if ( size != 1 && size != 2 && size != 4) { - PyErr_SetString(AudioopError, "Size should be 1, 2 or 4"); - return 0; - } - - str = PyBytes_FromStringAndSize(NULL, len/(size*2)); - if ( str == 0 ) - return 0; - ncp = (signed char *)PyBytes_AsString(str); - - /* Decode state, should have (value, step) */ - if ( state == Py_None ) { - /* First time, it seems. Set defaults */ - valpred = 0; - step = 7; - index = 0; - } else if ( !PyArg_ParseTuple(state, "ii", &valpred, &index) ) - return 0; + signed char *cp; + signed char *ncp; + int len, size, val = 0, step, valpred, delta, + index, sign, vpdiff, diff; + PyObject *rv, *state, *str; + int i, outputbuffer = 0, bufferstep; + + if ( !PyArg_ParseTuple(args, "s#iO:lin2adpcm", + &cp, &len, &size, &state) ) + return 0; + + + if ( size != 1 && size != 2 && size != 4) { + PyErr_SetString(AudioopError, "Size should be 1, 2 or 4"); + return 0; + } + + str = PyBytes_FromStringAndSize(NULL, len/(size*2)); + if ( str == 0 ) + return 0; + ncp = (signed char *)PyBytes_AsString(str); + + /* Decode state, should have (value, step) */ + if ( state == Py_None ) { + /* First time, it seems. Set defaults */ + valpred = 0; + step = 7; + index = 0; + } else if ( !PyArg_ParseTuple(state, "ii", &valpred, &index) ) + return 0; + + step = stepsizeTable[index]; + bufferstep = 1; + + for ( i=0; i < len; i += size ) { + if ( size == 1 ) val = ((int)*CHARP(cp, i)) << 8; + else if ( size == 2 ) val = (int)*SHORTP(cp, i); + else if ( size == 4 ) val = ((int)*LONGP(cp, i)) >> 16; + + /* Step 1 - compute difference with previous value */ + diff = val - valpred; + sign = (diff < 0) ? 8 : 0; + if ( sign ) diff = (-diff); + + /* Step 2 - Divide and clamp */ + /* Note: + ** This code *approximately* computes: + ** delta = diff*4/step; + ** vpdiff = (delta+0.5)*step/4; + ** but in shift step bits are dropped. The net result of this + ** is that even if you have fast mul/div hardware you cannot + ** put it to good use since the fixup would be too expensive. + */ + delta = 0; + vpdiff = (step >> 3); + if ( diff >= step ) { + delta = 4; + diff -= step; + vpdiff += step; + } + step >>= 1; + if ( diff >= step ) { + delta |= 2; + diff -= step; + vpdiff += step; + } + step >>= 1; + if ( diff >= step ) { + delta |= 1; + vpdiff += step; + } + + /* Step 3 - Update previous value */ + if ( sign ) + valpred -= vpdiff; + else + valpred += vpdiff; + + /* Step 4 - Clamp previous value to 16 bits */ + if ( valpred > 32767 ) + valpred = 32767; + else if ( valpred < -32768 ) + valpred = -32768; + + /* Step 5 - Assemble value, update index and step values */ + delta |= sign; + + index += indexTable[delta]; + if ( index < 0 ) index = 0; + if ( index > 88 ) index = 88; step = stepsizeTable[index]; - bufferstep = 1; - for ( i=0; i < len; i += size ) { - if ( size == 1 ) val = ((int)*CHARP(cp, i)) << 8; - else if ( size == 2 ) val = (int)*SHORTP(cp, i); - else if ( size == 4 ) val = ((int)*LONGP(cp, i)) >> 16; - - /* Step 1 - compute difference with previous value */ - diff = val - valpred; - sign = (diff < 0) ? 8 : 0; - if ( sign ) diff = (-diff); - - /* Step 2 - Divide and clamp */ - /* Note: - ** This code *approximately* computes: - ** delta = diff*4/step; - ** vpdiff = (delta+0.5)*step/4; - ** but in shift step bits are dropped. The net result of this - ** is that even if you have fast mul/div hardware you cannot - ** put it to good use since the fixup would be too expensive. - */ - delta = 0; - vpdiff = (step >> 3); - - if ( diff >= step ) { - delta = 4; - diff -= step; - vpdiff += step; - } - step >>= 1; - if ( diff >= step ) { - delta |= 2; - diff -= step; - vpdiff += step; - } - step >>= 1; - if ( diff >= step ) { - delta |= 1; - vpdiff += step; - } - - /* Step 3 - Update previous value */ - if ( sign ) - valpred -= vpdiff; - else - valpred += vpdiff; - - /* Step 4 - Clamp previous value to 16 bits */ - if ( valpred > 32767 ) - valpred = 32767; - else if ( valpred < -32768 ) - valpred = -32768; - - /* Step 5 - Assemble value, update index and step values */ - delta |= sign; - - index += indexTable[delta]; - if ( index < 0 ) index = 0; - if ( index > 88 ) index = 88; - step = stepsizeTable[index]; - - /* Step 6 - Output value */ - if ( bufferstep ) { - outputbuffer = (delta << 4) & 0xf0; - } else { - *ncp++ = (delta & 0x0f) | outputbuffer; - } - bufferstep = !bufferstep; + /* Step 6 - Output value */ + if ( bufferstep ) { + outputbuffer = (delta << 4) & 0xf0; + } else { + *ncp++ = (delta & 0x0f) | outputbuffer; } - rv = Py_BuildValue("(O(ii))", str, valpred, index); - Py_DECREF(str); - return rv; + bufferstep = !bufferstep; + } + rv = Py_BuildValue("(O(ii))", str, valpred, index); + Py_DECREF(str); + return rv; } static PyObject * audioop_adpcm2lin(PyObject *self, PyObject *args) { - signed char *cp; - signed char *ncp; - int len, new_len, size, valpred, step, delta, index, sign, vpdiff; - PyObject *rv, *str, *state; - int i, inputbuffer = 0, bufferstep; - - if ( !PyArg_ParseTuple(args, "s#iO:adpcm2lin", - &cp, &len, &size, &state) ) - return 0; - - if ( size != 1 && size != 2 && size != 4) { - PyErr_SetString(AudioopError, "Size should be 1, 2 or 4"); - return 0; - } - - /* Decode state, should have (value, step) */ - if ( state == Py_None ) { - /* First time, it seems. Set defaults */ - valpred = 0; - step = 7; - index = 0; - } else if ( !PyArg_ParseTuple(state, "ii", &valpred, &index) ) - return 0; - - new_len = len*size*2; - if (new_len < 0) { - PyErr_SetString(PyExc_MemoryError, - "not enough memory for output buffer"); - return 0; + signed char *cp; + signed char *ncp; + int len, new_len, size, valpred, step, delta, index, sign, vpdiff; + PyObject *rv, *str, *state; + int i, inputbuffer = 0, bufferstep; + + if ( !PyArg_ParseTuple(args, "s#iO:adpcm2lin", + &cp, &len, &size, &state) ) + return 0; + + if ( size != 1 && size != 2 && size != 4) { + PyErr_SetString(AudioopError, "Size should be 1, 2 or 4"); + return 0; + } + + /* Decode state, should have (value, step) */ + if ( state == Py_None ) { + /* First time, it seems. Set defaults */ + valpred = 0; + step = 7; + index = 0; + } else if ( !PyArg_ParseTuple(state, "ii", &valpred, &index) ) + return 0; + + new_len = len*size*2; + if (new_len < 0) { + PyErr_SetString(PyExc_MemoryError, + "not enough memory for output buffer"); + return 0; + } + str = PyBytes_FromStringAndSize(NULL, new_len); + if ( str == 0 ) + return 0; + ncp = (signed char *)PyBytes_AsString(str); + + step = stepsizeTable[index]; + bufferstep = 0; + + for ( i=0; i < new_len; i += size ) { + /* Step 1 - get the delta value and compute next index */ + if ( bufferstep ) { + delta = inputbuffer & 0xf; + } else { + inputbuffer = *cp++; + delta = (inputbuffer >> 4) & 0xf; } - str = PyBytes_FromStringAndSize(NULL, new_len); - if ( str == 0 ) - return 0; - ncp = (signed char *)PyBytes_AsString(str); + bufferstep = !bufferstep; + + /* Step 2 - Find new index value (for later) */ + index += indexTable[delta]; + if ( index < 0 ) index = 0; + if ( index > 88 ) index = 88; + + /* Step 3 - Separate sign and magnitude */ + sign = delta & 8; + delta = delta & 7; + + /* Step 4 - Compute difference and new predicted value */ + /* + ** Computes 'vpdiff = (delta+0.5)*step/4', but see comment + ** in adpcm_coder. + */ + vpdiff = step >> 3; + if ( delta & 4 ) vpdiff += step; + if ( delta & 2 ) vpdiff += step>>1; + if ( delta & 1 ) vpdiff += step>>2; + + if ( sign ) + valpred -= vpdiff; + else + valpred += vpdiff; + + /* Step 5 - clamp output value */ + if ( valpred > 32767 ) + valpred = 32767; + else if ( valpred < -32768 ) + valpred = -32768; + + /* Step 6 - Update step value */ step = stepsizeTable[index]; - bufferstep = 0; - - for ( i=0; i < new_len; i += size ) { - /* Step 1 - get the delta value and compute next index */ - if ( bufferstep ) { - delta = inputbuffer & 0xf; - } else { - inputbuffer = *cp++; - delta = (inputbuffer >> 4) & 0xf; - } - - bufferstep = !bufferstep; - - /* Step 2 - Find new index value (for later) */ - index += indexTable[delta]; - if ( index < 0 ) index = 0; - if ( index > 88 ) index = 88; - - /* Step 3 - Separate sign and magnitude */ - sign = delta & 8; - delta = delta & 7; - - /* Step 4 - Compute difference and new predicted value */ - /* - ** Computes 'vpdiff = (delta+0.5)*step/4', but see comment - ** in adpcm_coder. - */ - vpdiff = step >> 3; - if ( delta & 4 ) vpdiff += step; - if ( delta & 2 ) vpdiff += step>>1; - if ( delta & 1 ) vpdiff += step>>2; - - if ( sign ) - valpred -= vpdiff; - else - valpred += vpdiff; - - /* Step 5 - clamp output value */ - if ( valpred > 32767 ) - valpred = 32767; - else if ( valpred < -32768 ) - valpred = -32768; - - /* Step 6 - Update step value */ - step = stepsizeTable[index]; - - /* Step 6 - Output value */ - if ( size == 1 ) *CHARP(ncp, i) = (signed char)(valpred >> 8); - else if ( size == 2 ) *SHORTP(ncp, i) = (short)(valpred); - else if ( size == 4 ) *LONGP(ncp, i) = (Py_Int32)(valpred<<16); - } - rv = Py_BuildValue("(O(ii))", str, valpred, index); - Py_DECREF(str); - return rv; + /* Step 6 - Output value */ + if ( size == 1 ) *CHARP(ncp, i) = (signed char)(valpred >> 8); + else if ( size == 2 ) *SHORTP(ncp, i) = (short)(valpred); + else if ( size == 4 ) *LONGP(ncp, i) = (Py_Int32)(valpred<<16); + } + + rv = Py_BuildValue("(O(ii))", str, valpred, index); + Py_DECREF(str); + return rv; } static PyMethodDef audioop_methods[] = { - { "max", audioop_max, METH_VARARGS }, - { "minmax", audioop_minmax, METH_VARARGS }, - { "avg", audioop_avg, METH_VARARGS }, - { "maxpp", audioop_maxpp, METH_VARARGS }, - { "avgpp", audioop_avgpp, METH_VARARGS }, - { "rms", audioop_rms, METH_VARARGS }, - { "findfit", audioop_findfit, METH_VARARGS }, - { "findmax", audioop_findmax, METH_VARARGS }, - { "findfactor", audioop_findfactor, METH_VARARGS }, - { "cross", audioop_cross, METH_VARARGS }, - { "mul", audioop_mul, METH_VARARGS }, - { "add", audioop_add, METH_VARARGS }, - { "bias", audioop_bias, METH_VARARGS }, - { "ulaw2lin", audioop_ulaw2lin, METH_VARARGS }, - { "lin2ulaw", audioop_lin2ulaw, METH_VARARGS }, - { "alaw2lin", audioop_alaw2lin, METH_VARARGS }, - { "lin2alaw", audioop_lin2alaw, METH_VARARGS }, - { "lin2lin", audioop_lin2lin, METH_VARARGS }, - { "adpcm2lin", audioop_adpcm2lin, METH_VARARGS }, - { "lin2adpcm", audioop_lin2adpcm, METH_VARARGS }, - { "tomono", audioop_tomono, METH_VARARGS }, - { "tostereo", audioop_tostereo, METH_VARARGS }, - { "getsample", audioop_getsample, METH_VARARGS }, - { "reverse", audioop_reverse, METH_VARARGS }, - { "ratecv", audioop_ratecv, METH_VARARGS }, - { 0, 0 } + { "max", audioop_max, METH_VARARGS }, + { "minmax", audioop_minmax, METH_VARARGS }, + { "avg", audioop_avg, METH_VARARGS }, + { "maxpp", audioop_maxpp, METH_VARARGS }, + { "avgpp", audioop_avgpp, METH_VARARGS }, + { "rms", audioop_rms, METH_VARARGS }, + { "findfit", audioop_findfit, METH_VARARGS }, + { "findmax", audioop_findmax, METH_VARARGS }, + { "findfactor", audioop_findfactor, METH_VARARGS }, + { "cross", audioop_cross, METH_VARARGS }, + { "mul", audioop_mul, METH_VARARGS }, + { "add", audioop_add, METH_VARARGS }, + { "bias", audioop_bias, METH_VARARGS }, + { "ulaw2lin", audioop_ulaw2lin, METH_VARARGS }, + { "lin2ulaw", audioop_lin2ulaw, METH_VARARGS }, + { "alaw2lin", audioop_alaw2lin, METH_VARARGS }, + { "lin2alaw", audioop_lin2alaw, METH_VARARGS }, + { "lin2lin", audioop_lin2lin, METH_VARARGS }, + { "adpcm2lin", audioop_adpcm2lin, METH_VARARGS }, + { "lin2adpcm", audioop_lin2adpcm, METH_VARARGS }, + { "tomono", audioop_tomono, METH_VARARGS }, + { "tostereo", audioop_tostereo, METH_VARARGS }, + { "getsample", audioop_getsample, METH_VARARGS }, + { "reverse", audioop_reverse, METH_VARARGS }, + { "ratecv", audioop_ratecv, METH_VARARGS }, + { 0, 0 } }; static struct PyModuleDef audioopmodule = { - PyModuleDef_HEAD_INIT, - "audioop", - NULL, - -1, - audioop_methods, - NULL, - NULL, - NULL, - NULL + PyModuleDef_HEAD_INIT, + "audioop", + NULL, + -1, + audioop_methods, + NULL, + NULL, + NULL, + NULL }; PyMODINIT_FUNC PyInit_audioop(void) { - PyObject *m, *d; - m = PyModule_Create(&audioopmodule); - if (m == NULL) - return NULL; - d = PyModule_GetDict(m); - if (d == NULL) - return NULL; - AudioopError = PyErr_NewException("audioop.error", NULL, NULL); - if (AudioopError != NULL) - PyDict_SetItemString(d,"error",AudioopError); - return m; + PyObject *m, *d; + m = PyModule_Create(&audioopmodule); + if (m == NULL) + return NULL; + d = PyModule_GetDict(m); + if (d == NULL) + return NULL; + AudioopError = PyErr_NewException("audioop.error", NULL, NULL); + if (AudioopError != NULL) + PyDict_SetItemString(d,"error",AudioopError); + return m; } Modified: python/branches/release31-maint/Modules/binascii.c ============================================================================== --- python/branches/release31-maint/Modules/binascii.c (original) +++ python/branches/release31-maint/Modules/binascii.c Sun May 9 18:14:21 2010 @@ -3,40 +3,40 @@ ** ** This module currently supports the following encodings: ** uuencode: -** each line encodes 45 bytes (except possibly the last) -** First char encodes (binary) length, rest data -** each char encodes 6 bits, as follows: -** binary: 01234567 abcdefgh ijklmnop -** ascii: 012345 67abcd efghij klmnop -** ASCII encoding method is "excess-space": 000000 is encoded as ' ', etc. -** short binary data is zero-extended (so the bits are always in the -** right place), this does *not* reflect in the length. +** each line encodes 45 bytes (except possibly the last) +** First char encodes (binary) length, rest data +** each char encodes 6 bits, as follows: +** binary: 01234567 abcdefgh ijklmnop +** ascii: 012345 67abcd efghij klmnop +** ASCII encoding method is "excess-space": 000000 is encoded as ' ', etc. +** short binary data is zero-extended (so the bits are always in the +** right place), this does *not* reflect in the length. ** base64: ** Line breaks are insignificant, but lines are at most 76 chars ** each char encodes 6 bits, in similar order as uucode/hqx. Encoding ** is done via a table. ** Short binary data is filled (in ASCII) with '='. ** hqx: -** File starts with introductory text, real data starts and ends -** with colons. -** Data consists of three similar parts: info, datafork, resourcefork. -** Each part is protected (at the end) with a 16-bit crc -** The binary data is run-length encoded, and then ascii-fied: -** binary: 01234567 abcdefgh ijklmnop -** ascii: 012345 67abcd efghij klmnop -** ASCII encoding is table-driven, see the code. -** Short binary data results in the runt ascii-byte being output with -** the bits in the right place. +** File starts with introductory text, real data starts and ends +** with colons. +** Data consists of three similar parts: info, datafork, resourcefork. +** Each part is protected (at the end) with a 16-bit crc +** The binary data is run-length encoded, and then ascii-fied: +** binary: 01234567 abcdefgh ijklmnop +** ascii: 012345 67abcd efghij klmnop +** ASCII encoding is table-driven, see the code. +** Short binary data results in the runt ascii-byte being output with +** the bits in the right place. ** ** While I was reading dozens of programs that encode or decode the formats ** here (documentation? hihi:-) I have formulated Jansen's Observation: ** -** Programs that encode binary data in ASCII are written in -** such a style that they are as unreadable as possible. Devices used -** include unnecessary global variables, burying important tables -** in unrelated sourcefiles, putting functions in include files, -** using seemingly-descriptive variable names for different purposes, -** calls to empty subroutines and a host of others. +** Programs that encode binary data in ASCII are written in +** such a style that they are as unreadable as possible. Devices used +** include unnecessary global variables, burying important tables +** in unrelated sourcefiles, putting functions in include files, +** using seemingly-descriptive variable names for different purposes, +** calls to empty subroutines and a host of others. ** ** I have attempted to break with this tradition, but I guess that that ** does make the performance sub-optimal. Oh well, too bad... @@ -75,67 +75,67 @@ static unsigned char table_a2b_hqx[256] = { /* ^@ ^A ^B ^C ^D ^E ^F ^G */ -/* 0*/ FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, +/* 0*/ FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, /* \b \t \n ^K ^L \r ^N ^O */ -/* 1*/ FAIL, FAIL, SKIP, FAIL, FAIL, SKIP, FAIL, FAIL, +/* 1*/ FAIL, FAIL, SKIP, FAIL, FAIL, SKIP, FAIL, FAIL, /* ^P ^Q ^R ^S ^T ^U ^V ^W */ -/* 2*/ FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, +/* 2*/ FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, /* ^X ^Y ^Z ^[ ^\ ^] ^^ ^_ */ -/* 3*/ FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, +/* 3*/ FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, /* ! " # $ % & ' */ -/* 4*/ FAIL, 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, +/* 4*/ FAIL, 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, /* ( ) * + , - . / */ -/* 5*/ 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, FAIL, FAIL, +/* 5*/ 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, FAIL, FAIL, /* 0 1 2 3 4 5 6 7 */ -/* 6*/ 0x0D, 0x0E, 0x0F, 0x10, 0x11, 0x12, 0x13, FAIL, +/* 6*/ 0x0D, 0x0E, 0x0F, 0x10, 0x11, 0x12, 0x13, FAIL, /* 8 9 : ; < = > ? */ -/* 7*/ 0x14, 0x15, DONE, FAIL, FAIL, FAIL, FAIL, FAIL, +/* 7*/ 0x14, 0x15, DONE, FAIL, FAIL, FAIL, FAIL, FAIL, /* @ A B C D E F G */ -/* 8*/ 0x16, 0x17, 0x18, 0x19, 0x1A, 0x1B, 0x1C, 0x1D, +/* 8*/ 0x16, 0x17, 0x18, 0x19, 0x1A, 0x1B, 0x1C, 0x1D, /* H I J K L M N O */ -/* 9*/ 0x1E, 0x1F, 0x20, 0x21, 0x22, 0x23, 0x24, FAIL, +/* 9*/ 0x1E, 0x1F, 0x20, 0x21, 0x22, 0x23, 0x24, FAIL, /* P Q R S T U V W */ -/*10*/ 0x25, 0x26, 0x27, 0x28, 0x29, 0x2A, 0x2B, FAIL, +/*10*/ 0x25, 0x26, 0x27, 0x28, 0x29, 0x2A, 0x2B, FAIL, /* X Y Z [ \ ] ^ _ */ -/*11*/ 0x2C, 0x2D, 0x2E, 0x2F, FAIL, FAIL, FAIL, FAIL, +/*11*/ 0x2C, 0x2D, 0x2E, 0x2F, FAIL, FAIL, FAIL, FAIL, /* ` a b c d e f g */ -/*12*/ 0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, FAIL, +/*12*/ 0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, FAIL, /* h i j k l m n o */ -/*13*/ 0x37, 0x38, 0x39, 0x3A, 0x3B, 0x3C, FAIL, FAIL, +/*13*/ 0x37, 0x38, 0x39, 0x3A, 0x3B, 0x3C, FAIL, FAIL, /* p q r s t u v w */ -/*14*/ 0x3D, 0x3E, 0x3F, FAIL, FAIL, FAIL, FAIL, FAIL, +/*14*/ 0x3D, 0x3E, 0x3F, FAIL, FAIL, FAIL, FAIL, FAIL, /* x y z { | } ~ ^? */ -/*15*/ FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, -/*16*/ FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, - FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, - FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, - FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, - FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, - FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, - FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, - FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, - FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, - FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, - FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, - FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, - FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, - FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, - FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, - FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, +/*15*/ FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, +/*16*/ FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, + FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, + FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, + FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, + FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, + FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, + FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, + FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, + FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, + FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, + FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, + FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, + FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, + FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, + FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, + FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, }; static unsigned char table_b2a_hqx[] = "!\"#$%&'()*+,-012345689 at ABCDEFGHIJKLMNPQRSTUVXYZ[`abcdefhijklmpqr"; static char table_a2b_base64[] = { - -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1, - -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1, - -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,62, -1,-1,-1,63, - 52,53,54,55, 56,57,58,59, 60,61,-1,-1, -1, 0,-1,-1, /* Note PAD->0 */ - -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9,10, 11,12,13,14, - 15,16,17,18, 19,20,21,22, 23,24,25,-1, -1,-1,-1,-1, - -1,26,27,28, 29,30,31,32, 33,34,35,36, 37,38,39,40, - 41,42,43,44, 45,46,47,48, 49,50,51,-1, -1,-1,-1,-1 + -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1, + -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1, + -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,62, -1,-1,-1,63, + 52,53,54,55, 56,57,58,59, 60,61,-1,-1, -1, 0,-1,-1, /* Note PAD->0 */ + -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9,10, 11,12,13,14, + 15,16,17,18, 19,20,21,22, 23,24,25,-1, -1,-1,-1,-1, + -1,26,27,28, 29,30,31,32, 33,34,35,36, 37,38,39,40, + 41,42,43,44, 45,46,47,48, 49,50,51,-1, -1,-1,-1,-1 }; #define BASE64_PAD '=' @@ -149,38 +149,38 @@ static unsigned short crctab_hqx[256] = { - 0x0000, 0x1021, 0x2042, 0x3063, 0x4084, 0x50a5, 0x60c6, 0x70e7, - 0x8108, 0x9129, 0xa14a, 0xb16b, 0xc18c, 0xd1ad, 0xe1ce, 0xf1ef, - 0x1231, 0x0210, 0x3273, 0x2252, 0x52b5, 0x4294, 0x72f7, 0x62d6, - 0x9339, 0x8318, 0xb37b, 0xa35a, 0xd3bd, 0xc39c, 0xf3ff, 0xe3de, - 0x2462, 0x3443, 0x0420, 0x1401, 0x64e6, 0x74c7, 0x44a4, 0x5485, - 0xa56a, 0xb54b, 0x8528, 0x9509, 0xe5ee, 0xf5cf, 0xc5ac, 0xd58d, - 0x3653, 0x2672, 0x1611, 0x0630, 0x76d7, 0x66f6, 0x5695, 0x46b4, - 0xb75b, 0xa77a, 0x9719, 0x8738, 0xf7df, 0xe7fe, 0xd79d, 0xc7bc, - 0x48c4, 0x58e5, 0x6886, 0x78a7, 0x0840, 0x1861, 0x2802, 0x3823, - 0xc9cc, 0xd9ed, 0xe98e, 0xf9af, 0x8948, 0x9969, 0xa90a, 0xb92b, - 0x5af5, 0x4ad4, 0x7ab7, 0x6a96, 0x1a71, 0x0a50, 0x3a33, 0x2a12, - 0xdbfd, 0xcbdc, 0xfbbf, 0xeb9e, 0x9b79, 0x8b58, 0xbb3b, 0xab1a, - 0x6ca6, 0x7c87, 0x4ce4, 0x5cc5, 0x2c22, 0x3c03, 0x0c60, 0x1c41, - 0xedae, 0xfd8f, 0xcdec, 0xddcd, 0xad2a, 0xbd0b, 0x8d68, 0x9d49, - 0x7e97, 0x6eb6, 0x5ed5, 0x4ef4, 0x3e13, 0x2e32, 0x1e51, 0x0e70, - 0xff9f, 0xefbe, 0xdfdd, 0xcffc, 0xbf1b, 0xaf3a, 0x9f59, 0x8f78, - 0x9188, 0x81a9, 0xb1ca, 0xa1eb, 0xd10c, 0xc12d, 0xf14e, 0xe16f, - 0x1080, 0x00a1, 0x30c2, 0x20e3, 0x5004, 0x4025, 0x7046, 0x6067, - 0x83b9, 0x9398, 0xa3fb, 0xb3da, 0xc33d, 0xd31c, 0xe37f, 0xf35e, - 0x02b1, 0x1290, 0x22f3, 0x32d2, 0x4235, 0x5214, 0x6277, 0x7256, - 0xb5ea, 0xa5cb, 0x95a8, 0x8589, 0xf56e, 0xe54f, 0xd52c, 0xc50d, - 0x34e2, 0x24c3, 0x14a0, 0x0481, 0x7466, 0x6447, 0x5424, 0x4405, - 0xa7db, 0xb7fa, 0x8799, 0x97b8, 0xe75f, 0xf77e, 0xc71d, 0xd73c, - 0x26d3, 0x36f2, 0x0691, 0x16b0, 0x6657, 0x7676, 0x4615, 0x5634, - 0xd94c, 0xc96d, 0xf90e, 0xe92f, 0x99c8, 0x89e9, 0xb98a, 0xa9ab, - 0x5844, 0x4865, 0x7806, 0x6827, 0x18c0, 0x08e1, 0x3882, 0x28a3, - 0xcb7d, 0xdb5c, 0xeb3f, 0xfb1e, 0x8bf9, 0x9bd8, 0xabbb, 0xbb9a, - 0x4a75, 0x5a54, 0x6a37, 0x7a16, 0x0af1, 0x1ad0, 0x2ab3, 0x3a92, - 0xfd2e, 0xed0f, 0xdd6c, 0xcd4d, 0xbdaa, 0xad8b, 0x9de8, 0x8dc9, - 0x7c26, 0x6c07, 0x5c64, 0x4c45, 0x3ca2, 0x2c83, 0x1ce0, 0x0cc1, - 0xef1f, 0xff3e, 0xcf5d, 0xdf7c, 0xaf9b, 0xbfba, 0x8fd9, 0x9ff8, - 0x6e17, 0x7e36, 0x4e55, 0x5e74, 0x2e93, 0x3eb2, 0x0ed1, 0x1ef0, + 0x0000, 0x1021, 0x2042, 0x3063, 0x4084, 0x50a5, 0x60c6, 0x70e7, + 0x8108, 0x9129, 0xa14a, 0xb16b, 0xc18c, 0xd1ad, 0xe1ce, 0xf1ef, + 0x1231, 0x0210, 0x3273, 0x2252, 0x52b5, 0x4294, 0x72f7, 0x62d6, + 0x9339, 0x8318, 0xb37b, 0xa35a, 0xd3bd, 0xc39c, 0xf3ff, 0xe3de, + 0x2462, 0x3443, 0x0420, 0x1401, 0x64e6, 0x74c7, 0x44a4, 0x5485, + 0xa56a, 0xb54b, 0x8528, 0x9509, 0xe5ee, 0xf5cf, 0xc5ac, 0xd58d, + 0x3653, 0x2672, 0x1611, 0x0630, 0x76d7, 0x66f6, 0x5695, 0x46b4, + 0xb75b, 0xa77a, 0x9719, 0x8738, 0xf7df, 0xe7fe, 0xd79d, 0xc7bc, + 0x48c4, 0x58e5, 0x6886, 0x78a7, 0x0840, 0x1861, 0x2802, 0x3823, + 0xc9cc, 0xd9ed, 0xe98e, 0xf9af, 0x8948, 0x9969, 0xa90a, 0xb92b, + 0x5af5, 0x4ad4, 0x7ab7, 0x6a96, 0x1a71, 0x0a50, 0x3a33, 0x2a12, + 0xdbfd, 0xcbdc, 0xfbbf, 0xeb9e, 0x9b79, 0x8b58, 0xbb3b, 0xab1a, + 0x6ca6, 0x7c87, 0x4ce4, 0x5cc5, 0x2c22, 0x3c03, 0x0c60, 0x1c41, + 0xedae, 0xfd8f, 0xcdec, 0xddcd, 0xad2a, 0xbd0b, 0x8d68, 0x9d49, + 0x7e97, 0x6eb6, 0x5ed5, 0x4ef4, 0x3e13, 0x2e32, 0x1e51, 0x0e70, + 0xff9f, 0xefbe, 0xdfdd, 0xcffc, 0xbf1b, 0xaf3a, 0x9f59, 0x8f78, + 0x9188, 0x81a9, 0xb1ca, 0xa1eb, 0xd10c, 0xc12d, 0xf14e, 0xe16f, + 0x1080, 0x00a1, 0x30c2, 0x20e3, 0x5004, 0x4025, 0x7046, 0x6067, + 0x83b9, 0x9398, 0xa3fb, 0xb3da, 0xc33d, 0xd31c, 0xe37f, 0xf35e, + 0x02b1, 0x1290, 0x22f3, 0x32d2, 0x4235, 0x5214, 0x6277, 0x7256, + 0xb5ea, 0xa5cb, 0x95a8, 0x8589, 0xf56e, 0xe54f, 0xd52c, 0xc50d, + 0x34e2, 0x24c3, 0x14a0, 0x0481, 0x7466, 0x6447, 0x5424, 0x4405, + 0xa7db, 0xb7fa, 0x8799, 0x97b8, 0xe75f, 0xf77e, 0xc71d, 0xd73c, + 0x26d3, 0x36f2, 0x0691, 0x16b0, 0x6657, 0x7676, 0x4615, 0x5634, + 0xd94c, 0xc96d, 0xf90e, 0xe92f, 0x99c8, 0x89e9, 0xb98a, 0xa9ab, + 0x5844, 0x4865, 0x7806, 0x6827, 0x18c0, 0x08e1, 0x3882, 0x28a3, + 0xcb7d, 0xdb5c, 0xeb3f, 0xfb1e, 0x8bf9, 0x9bd8, 0xabbb, 0xbb9a, + 0x4a75, 0x5a54, 0x6a37, 0x7a16, 0x0af1, 0x1ad0, 0x2ab3, 0x3a92, + 0xfd2e, 0xed0f, 0xdd6c, 0xcd4d, 0xbdaa, 0xad8b, 0x9de8, 0x8dc9, + 0x7c26, 0x6c07, 0x5c64, 0x4c45, 0x3ca2, 0x2c83, 0x1ce0, 0x0cc1, + 0xef1f, 0xff3e, 0xcf5d, 0xdf7c, 0xaf9b, 0xbfba, 0x8fd9, 0x9ff8, + 0x6e17, 0x7e36, 0x4e55, 0x5e74, 0x2e93, 0x3eb2, 0x0ed1, 0x1ef0, }; PyDoc_STRVAR(doc_a2b_uu, "(ascii) -> bin. Decode a line of uuencoded data"); @@ -188,85 +188,85 @@ static PyObject * binascii_a2b_uu(PyObject *self, PyObject *args) { - Py_buffer pascii; - unsigned char *ascii_data, *bin_data; - int leftbits = 0; - unsigned char this_ch; - unsigned int leftchar = 0; - PyObject *rv; - Py_ssize_t ascii_len, bin_len; - - if ( !PyArg_ParseTuple(args, "y*:a2b_uu", &pascii) ) - return NULL; - ascii_data = pascii.buf; - ascii_len = pascii.len; - - assert(ascii_len >= 0); - - /* First byte: binary data length (in bytes) */ - bin_len = (*ascii_data++ - ' ') & 077; - ascii_len--; - - /* Allocate the buffer */ - if ( (rv=PyBytes_FromStringAndSize(NULL, bin_len)) == NULL ) { - PyBuffer_Release(&pascii); - return NULL; - } - bin_data = (unsigned char *)PyBytes_AS_STRING(rv); - - for( ; bin_len > 0 ; ascii_len--, ascii_data++ ) { - /* XXX is it really best to add NULs if there's no more data */ - this_ch = (ascii_len > 0) ? *ascii_data : 0; - if ( this_ch == '\n' || this_ch == '\r' || ascii_len <= 0) { - /* - ** Whitespace. Assume some spaces got eaten at - ** end-of-line. (We check this later) - */ - this_ch = 0; - } else { - /* Check the character for legality - ** The 64 in stead of the expected 63 is because - ** there are a few uuencodes out there that use - ** '`' as zero instead of space. - */ - if ( this_ch < ' ' || this_ch > (' ' + 64)) { - PyErr_SetString(Error, "Illegal char"); - PyBuffer_Release(&pascii); - Py_DECREF(rv); - return NULL; - } - this_ch = (this_ch - ' ') & 077; - } - /* - ** Shift it in on the low end, and see if there's - ** a byte ready for output. - */ - leftchar = (leftchar << 6) | (this_ch); - leftbits += 6; - if ( leftbits >= 8 ) { - leftbits -= 8; - *bin_data++ = (leftchar >> leftbits) & 0xff; - leftchar &= ((1 << leftbits) - 1); - bin_len--; - } - } - /* - ** Finally, check that if there's anything left on the line - ** that it's whitespace only. - */ - while( ascii_len-- > 0 ) { - this_ch = *ascii_data++; - /* Extra '`' may be written as padding in some cases */ - if ( this_ch != ' ' && this_ch != ' '+64 && - this_ch != '\n' && this_ch != '\r' ) { - PyErr_SetString(Error, "Trailing garbage"); - PyBuffer_Release(&pascii); - Py_DECREF(rv); - return NULL; - } - } - PyBuffer_Release(&pascii); - return rv; + Py_buffer pascii; + unsigned char *ascii_data, *bin_data; + int leftbits = 0; + unsigned char this_ch; + unsigned int leftchar = 0; + PyObject *rv; + Py_ssize_t ascii_len, bin_len; + + if ( !PyArg_ParseTuple(args, "y*:a2b_uu", &pascii) ) + return NULL; + ascii_data = pascii.buf; + ascii_len = pascii.len; + + assert(ascii_len >= 0); + + /* First byte: binary data length (in bytes) */ + bin_len = (*ascii_data++ - ' ') & 077; + ascii_len--; + + /* Allocate the buffer */ + if ( (rv=PyBytes_FromStringAndSize(NULL, bin_len)) == NULL ) { + PyBuffer_Release(&pascii); + return NULL; + } + bin_data = (unsigned char *)PyBytes_AS_STRING(rv); + + for( ; bin_len > 0 ; ascii_len--, ascii_data++ ) { + /* XXX is it really best to add NULs if there's no more data */ + this_ch = (ascii_len > 0) ? *ascii_data : 0; + if ( this_ch == '\n' || this_ch == '\r' || ascii_len <= 0) { + /* + ** Whitespace. Assume some spaces got eaten at + ** end-of-line. (We check this later) + */ + this_ch = 0; + } else { + /* Check the character for legality + ** The 64 in stead of the expected 63 is because + ** there are a few uuencodes out there that use + ** '`' as zero instead of space. + */ + if ( this_ch < ' ' || this_ch > (' ' + 64)) { + PyErr_SetString(Error, "Illegal char"); + PyBuffer_Release(&pascii); + Py_DECREF(rv); + return NULL; + } + this_ch = (this_ch - ' ') & 077; + } + /* + ** Shift it in on the low end, and see if there's + ** a byte ready for output. + */ + leftchar = (leftchar << 6) | (this_ch); + leftbits += 6; + if ( leftbits >= 8 ) { + leftbits -= 8; + *bin_data++ = (leftchar >> leftbits) & 0xff; + leftchar &= ((1 << leftbits) - 1); + bin_len--; + } + } + /* + ** Finally, check that if there's anything left on the line + ** that it's whitespace only. + */ + while( ascii_len-- > 0 ) { + this_ch = *ascii_data++; + /* Extra '`' may be written as padding in some cases */ + if ( this_ch != ' ' && this_ch != ' '+64 && + this_ch != '\n' && this_ch != '\r' ) { + PyErr_SetString(Error, "Trailing garbage"); + PyBuffer_Release(&pascii); + Py_DECREF(rv); + return NULL; + } + } + PyBuffer_Release(&pascii); + return rv; } PyDoc_STRVAR(doc_b2a_uu, "(bin) -> ascii. Uuencode line of data"); @@ -274,86 +274,86 @@ static PyObject * binascii_b2a_uu(PyObject *self, PyObject *args) { - Py_buffer pbin; - unsigned char *ascii_data, *bin_data; - int leftbits = 0; - unsigned char this_ch; - unsigned int leftchar = 0; - PyObject *rv; - Py_ssize_t bin_len; - - if ( !PyArg_ParseTuple(args, "y*:b2a_uu", &pbin) ) - return NULL; - bin_data = pbin.buf; - bin_len = pbin.len; - if ( bin_len > 45 ) { - /* The 45 is a limit that appears in all uuencode's */ - PyErr_SetString(Error, "At most 45 bytes at once"); - PyBuffer_Release(&pbin); - return NULL; - } - - /* We're lazy and allocate to much (fixed up later) */ - if ( (rv=PyBytes_FromStringAndSize(NULL, 2 + (bin_len+2)/3*4)) == NULL ) { - PyBuffer_Release(&pbin); - return NULL; - } - ascii_data = (unsigned char *)PyBytes_AS_STRING(rv); - - /* Store the length */ - *ascii_data++ = ' ' + (bin_len & 077); - - for( ; bin_len > 0 || leftbits != 0 ; bin_len--, bin_data++ ) { - /* Shift the data (or padding) into our buffer */ - if ( bin_len > 0 ) /* Data */ - leftchar = (leftchar << 8) | *bin_data; - else /* Padding */ - leftchar <<= 8; - leftbits += 8; - - /* See if there are 6-bit groups ready */ - while ( leftbits >= 6 ) { - this_ch = (leftchar >> (leftbits-6)) & 0x3f; - leftbits -= 6; - *ascii_data++ = this_ch + ' '; - } - } - *ascii_data++ = '\n'; /* Append a courtesy newline */ - - if (_PyBytes_Resize(&rv, - (ascii_data - - (unsigned char *)PyBytes_AS_STRING(rv))) < 0) { - Py_DECREF(rv); - rv = NULL; - } - PyBuffer_Release(&pbin); - return rv; + Py_buffer pbin; + unsigned char *ascii_data, *bin_data; + int leftbits = 0; + unsigned char this_ch; + unsigned int leftchar = 0; + PyObject *rv; + Py_ssize_t bin_len; + + if ( !PyArg_ParseTuple(args, "y*:b2a_uu", &pbin) ) + return NULL; + bin_data = pbin.buf; + bin_len = pbin.len; + if ( bin_len > 45 ) { + /* The 45 is a limit that appears in all uuencode's */ + PyErr_SetString(Error, "At most 45 bytes at once"); + PyBuffer_Release(&pbin); + return NULL; + } + + /* We're lazy and allocate to much (fixed up later) */ + if ( (rv=PyBytes_FromStringAndSize(NULL, 2 + (bin_len+2)/3*4)) == NULL ) { + PyBuffer_Release(&pbin); + return NULL; + } + ascii_data = (unsigned char *)PyBytes_AS_STRING(rv); + + /* Store the length */ + *ascii_data++ = ' ' + (bin_len & 077); + + for( ; bin_len > 0 || leftbits != 0 ; bin_len--, bin_data++ ) { + /* Shift the data (or padding) into our buffer */ + if ( bin_len > 0 ) /* Data */ + leftchar = (leftchar << 8) | *bin_data; + else /* Padding */ + leftchar <<= 8; + leftbits += 8; + + /* See if there are 6-bit groups ready */ + while ( leftbits >= 6 ) { + this_ch = (leftchar >> (leftbits-6)) & 0x3f; + leftbits -= 6; + *ascii_data++ = this_ch + ' '; + } + } + *ascii_data++ = '\n'; /* Append a courtesy newline */ + + if (_PyBytes_Resize(&rv, + (ascii_data - + (unsigned char *)PyBytes_AS_STRING(rv))) < 0) { + Py_DECREF(rv); + rv = NULL; + } + PyBuffer_Release(&pbin); + return rv; } static int binascii_find_valid(unsigned char *s, Py_ssize_t slen, int num) { - /* Finds & returns the (num+1)th - ** valid character for base64, or -1 if none. - */ - - int ret = -1; - unsigned char c, b64val; - - while ((slen > 0) && (ret == -1)) { - c = *s; - b64val = table_a2b_base64[c & 0x7f]; - if ( ((c <= 0x7f) && (b64val != (unsigned char)-1)) ) { - if (num == 0) - ret = *s; - num--; - } - - s++; - slen--; - } - return ret; + /* Finds & returns the (num+1)th + ** valid character for base64, or -1 if none. + */ + + int ret = -1; + unsigned char c, b64val; + + while ((slen > 0) && (ret == -1)) { + c = *s; + b64val = table_a2b_base64[c & 0x7f]; + if ( ((c <= 0x7f) && (b64val != (unsigned char)-1)) ) { + if (num == 0) + ret = *s; + num--; + } + + s++; + slen--; + } + return ret; } PyDoc_STRVAR(doc_a2b_base64, "(ascii) -> bin. Decode a line of base64 data"); @@ -361,108 +361,108 @@ static PyObject * binascii_a2b_base64(PyObject *self, PyObject *args) { - Py_buffer pascii; - unsigned char *ascii_data, *bin_data; - int leftbits = 0; - unsigned char this_ch; - unsigned int leftchar = 0; - PyObject *rv; - Py_ssize_t ascii_len, bin_len; - int quad_pos = 0; - - if ( !PyArg_ParseTuple(args, "y*:a2b_base64", &pascii) ) - return NULL; - ascii_data = pascii.buf; - ascii_len = pascii.len; - - assert(ascii_len >= 0); - - if (ascii_len > PY_SSIZE_T_MAX - 3) { - PyBuffer_Release(&pascii); - return PyErr_NoMemory(); - } - - bin_len = ((ascii_len+3)/4)*3; /* Upper bound, corrected later */ - - /* Allocate the buffer */ - if ( (rv=PyBytes_FromStringAndSize(NULL, bin_len)) == NULL ) { - PyBuffer_Release(&pascii); - return NULL; - } - bin_data = (unsigned char *)PyBytes_AS_STRING(rv); - bin_len = 0; - - for( ; ascii_len > 0; ascii_len--, ascii_data++) { - this_ch = *ascii_data; - - if (this_ch > 0x7f || - this_ch == '\r' || this_ch == '\n' || this_ch == ' ') - continue; - - /* Check for pad sequences and ignore - ** the invalid ones. - */ - if (this_ch == BASE64_PAD) { - if ( (quad_pos < 2) || - ((quad_pos == 2) && - (binascii_find_valid(ascii_data, ascii_len, 1) - != BASE64_PAD)) ) - { - continue; - } - else { - /* A pad sequence means no more input. - ** We've already interpreted the data - ** from the quad at this point. - */ - leftbits = 0; - break; - } - } - - this_ch = table_a2b_base64[*ascii_data]; - if ( this_ch == (unsigned char) -1 ) - continue; - - /* - ** Shift it in on the low end, and see if there's - ** a byte ready for output. - */ - quad_pos = (quad_pos + 1) & 0x03; - leftchar = (leftchar << 6) | (this_ch); - leftbits += 6; - - if ( leftbits >= 8 ) { - leftbits -= 8; - *bin_data++ = (leftchar >> leftbits) & 0xff; - bin_len++; - leftchar &= ((1 << leftbits) - 1); - } - } - - if (leftbits != 0) { - PyBuffer_Release(&pascii); - PyErr_SetString(Error, "Incorrect padding"); - Py_DECREF(rv); - return NULL; - } - - /* And set string size correctly. If the result string is empty - ** (because the input was all invalid) return the shared empty - ** string instead; _PyBytes_Resize() won't do this for us. - */ - if (bin_len > 0) { - if (_PyBytes_Resize(&rv, bin_len) < 0) { - Py_DECREF(rv); - rv = NULL; - } - } - else { - Py_DECREF(rv); - rv = PyBytes_FromStringAndSize("", 0); - } - PyBuffer_Release(&pascii); - return rv; + Py_buffer pascii; + unsigned char *ascii_data, *bin_data; + int leftbits = 0; + unsigned char this_ch; + unsigned int leftchar = 0; + PyObject *rv; + Py_ssize_t ascii_len, bin_len; + int quad_pos = 0; + + if ( !PyArg_ParseTuple(args, "y*:a2b_base64", &pascii) ) + return NULL; + ascii_data = pascii.buf; + ascii_len = pascii.len; + + assert(ascii_len >= 0); + + if (ascii_len > PY_SSIZE_T_MAX - 3) { + PyBuffer_Release(&pascii); + return PyErr_NoMemory(); + } + + bin_len = ((ascii_len+3)/4)*3; /* Upper bound, corrected later */ + + /* Allocate the buffer */ + if ( (rv=PyBytes_FromStringAndSize(NULL, bin_len)) == NULL ) { + PyBuffer_Release(&pascii); + return NULL; + } + bin_data = (unsigned char *)PyBytes_AS_STRING(rv); + bin_len = 0; + + for( ; ascii_len > 0; ascii_len--, ascii_data++) { + this_ch = *ascii_data; + + if (this_ch > 0x7f || + this_ch == '\r' || this_ch == '\n' || this_ch == ' ') + continue; + + /* Check for pad sequences and ignore + ** the invalid ones. + */ + if (this_ch == BASE64_PAD) { + if ( (quad_pos < 2) || + ((quad_pos == 2) && + (binascii_find_valid(ascii_data, ascii_len, 1) + != BASE64_PAD)) ) + { + continue; + } + else { + /* A pad sequence means no more input. + ** We've already interpreted the data + ** from the quad at this point. + */ + leftbits = 0; + break; + } + } + + this_ch = table_a2b_base64[*ascii_data]; + if ( this_ch == (unsigned char) -1 ) + continue; + + /* + ** Shift it in on the low end, and see if there's + ** a byte ready for output. + */ + quad_pos = (quad_pos + 1) & 0x03; + leftchar = (leftchar << 6) | (this_ch); + leftbits += 6; + + if ( leftbits >= 8 ) { + leftbits -= 8; + *bin_data++ = (leftchar >> leftbits) & 0xff; + bin_len++; + leftchar &= ((1 << leftbits) - 1); + } + } + + if (leftbits != 0) { + PyBuffer_Release(&pascii); + PyErr_SetString(Error, "Incorrect padding"); + Py_DECREF(rv); + return NULL; + } + + /* And set string size correctly. If the result string is empty + ** (because the input was all invalid) return the shared empty + ** string instead; _PyBytes_Resize() won't do this for us. + */ + if (bin_len > 0) { + if (_PyBytes_Resize(&rv, bin_len) < 0) { + Py_DECREF(rv); + rv = NULL; + } + } + else { + Py_DECREF(rv); + rv = PyBytes_FromStringAndSize("", 0); + } + PyBuffer_Release(&pascii); + return rv; } PyDoc_STRVAR(doc_b2a_base64, "(bin) -> ascii. Base64-code line of data"); @@ -470,66 +470,66 @@ static PyObject * binascii_b2a_base64(PyObject *self, PyObject *args) { - Py_buffer pbuf; - unsigned char *ascii_data, *bin_data; - int leftbits = 0; - unsigned char this_ch; - unsigned int leftchar = 0; - PyObject *rv; - Py_ssize_t bin_len; - - if ( !PyArg_ParseTuple(args, "y*:b2a_base64", &pbuf) ) - return NULL; - bin_data = pbuf.buf; - bin_len = pbuf.len; - - assert(bin_len >= 0); - - if ( bin_len > BASE64_MAXBIN ) { - PyErr_SetString(Error, "Too much data for base64 line"); - PyBuffer_Release(&pbuf); - return NULL; - } - - /* We're lazy and allocate too much (fixed up later). - "+3" leaves room for up to two pad characters and a trailing - newline. Note that 'b' gets encoded as 'Yg==\n' (1 in, 5 out). */ - if ( (rv=PyBytes_FromStringAndSize(NULL, bin_len*2 + 3)) == NULL ) { - PyBuffer_Release(&pbuf); - return NULL; - } - ascii_data = (unsigned char *)PyBytes_AS_STRING(rv); - - for( ; bin_len > 0 ; bin_len--, bin_data++ ) { - /* Shift the data into our buffer */ - leftchar = (leftchar << 8) | *bin_data; - leftbits += 8; - - /* See if there are 6-bit groups ready */ - while ( leftbits >= 6 ) { - this_ch = (leftchar >> (leftbits-6)) & 0x3f; - leftbits -= 6; - *ascii_data++ = table_b2a_base64[this_ch]; - } - } - if ( leftbits == 2 ) { - *ascii_data++ = table_b2a_base64[(leftchar&3) << 4]; - *ascii_data++ = BASE64_PAD; - *ascii_data++ = BASE64_PAD; - } else if ( leftbits == 4 ) { - *ascii_data++ = table_b2a_base64[(leftchar&0xf) << 2]; - *ascii_data++ = BASE64_PAD; - } - *ascii_data++ = '\n'; /* Append a courtesy newline */ - - if (_PyBytes_Resize(&rv, - (ascii_data - - (unsigned char *)PyBytes_AS_STRING(rv))) < 0) { - Py_DECREF(rv); - rv = NULL; - } - PyBuffer_Release(&pbuf); - return rv; + Py_buffer pbuf; + unsigned char *ascii_data, *bin_data; + int leftbits = 0; + unsigned char this_ch; + unsigned int leftchar = 0; + PyObject *rv; + Py_ssize_t bin_len; + + if ( !PyArg_ParseTuple(args, "y*:b2a_base64", &pbuf) ) + return NULL; + bin_data = pbuf.buf; + bin_len = pbuf.len; + + assert(bin_len >= 0); + + if ( bin_len > BASE64_MAXBIN ) { + PyErr_SetString(Error, "Too much data for base64 line"); + PyBuffer_Release(&pbuf); + return NULL; + } + + /* We're lazy and allocate too much (fixed up later). + "+3" leaves room for up to two pad characters and a trailing + newline. Note that 'b' gets encoded as 'Yg==\n' (1 in, 5 out). */ + if ( (rv=PyBytes_FromStringAndSize(NULL, bin_len*2 + 3)) == NULL ) { + PyBuffer_Release(&pbuf); + return NULL; + } + ascii_data = (unsigned char *)PyBytes_AS_STRING(rv); + + for( ; bin_len > 0 ; bin_len--, bin_data++ ) { + /* Shift the data into our buffer */ + leftchar = (leftchar << 8) | *bin_data; + leftbits += 8; + + /* See if there are 6-bit groups ready */ + while ( leftbits >= 6 ) { + this_ch = (leftchar >> (leftbits-6)) & 0x3f; + leftbits -= 6; + *ascii_data++ = table_b2a_base64[this_ch]; + } + } + if ( leftbits == 2 ) { + *ascii_data++ = table_b2a_base64[(leftchar&3) << 4]; + *ascii_data++ = BASE64_PAD; + *ascii_data++ = BASE64_PAD; + } else if ( leftbits == 4 ) { + *ascii_data++ = table_b2a_base64[(leftchar&0xf) << 2]; + *ascii_data++ = BASE64_PAD; + } + *ascii_data++ = '\n'; /* Append a courtesy newline */ + + if (_PyBytes_Resize(&rv, + (ascii_data - + (unsigned char *)PyBytes_AS_STRING(rv))) < 0) { + Py_DECREF(rv); + rv = NULL; + } + PyBuffer_Release(&pbuf); + return rv; } PyDoc_STRVAR(doc_a2b_hqx, "ascii -> bin, done. Decode .hqx coding"); @@ -537,74 +537,74 @@ static PyObject * binascii_a2b_hqx(PyObject *self, PyObject *args) { - unsigned char *ascii_data, *bin_data; - int leftbits = 0; - unsigned char this_ch; - unsigned int leftchar = 0; - PyObject *rv; - Py_ssize_t len; - int done = 0; - - if ( !PyArg_ParseTuple(args, "t#:a2b_hqx", &ascii_data, &len) ) - return NULL; - - assert(len >= 0); - - if (len > PY_SSIZE_T_MAX - 2) - return PyErr_NoMemory(); - - /* Allocate a string that is too big (fixed later) - Add two to the initial length to prevent interning which - would preclude subsequent resizing. */ - if ( (rv=PyBytes_FromStringAndSize(NULL, len+2)) == NULL ) - return NULL; - bin_data = (unsigned char *)PyBytes_AS_STRING(rv); - - for( ; len > 0 ; len--, ascii_data++ ) { - /* Get the byte and look it up */ - this_ch = table_a2b_hqx[*ascii_data]; - if ( this_ch == SKIP ) - continue; - if ( this_ch == FAIL ) { - PyErr_SetString(Error, "Illegal char"); - Py_DECREF(rv); - return NULL; - } - if ( this_ch == DONE ) { - /* The terminating colon */ - done = 1; - break; - } - - /* Shift it into the buffer and see if any bytes are ready */ - leftchar = (leftchar << 6) | (this_ch); - leftbits += 6; - if ( leftbits >= 8 ) { - leftbits -= 8; - *bin_data++ = (leftchar >> leftbits) & 0xff; - leftchar &= ((1 << leftbits) - 1); - } - } - - if ( leftbits && !done ) { - PyErr_SetString(Incomplete, - "String has incomplete number of bytes"); - Py_DECREF(rv); - return NULL; - } - if (_PyBytes_Resize(&rv, - (bin_data - - (unsigned char *)PyBytes_AS_STRING(rv))) < 0) { - Py_DECREF(rv); - rv = NULL; - } - if (rv) { - PyObject *rrv = Py_BuildValue("Oi", rv, done); - Py_DECREF(rv); - return rrv; - } + unsigned char *ascii_data, *bin_data; + int leftbits = 0; + unsigned char this_ch; + unsigned int leftchar = 0; + PyObject *rv; + Py_ssize_t len; + int done = 0; + + if ( !PyArg_ParseTuple(args, "t#:a2b_hqx", &ascii_data, &len) ) + return NULL; - return NULL; + assert(len >= 0); + + if (len > PY_SSIZE_T_MAX - 2) + return PyErr_NoMemory(); + + /* Allocate a string that is too big (fixed later) + Add two to the initial length to prevent interning which + would preclude subsequent resizing. */ + if ( (rv=PyBytes_FromStringAndSize(NULL, len+2)) == NULL ) + return NULL; + bin_data = (unsigned char *)PyBytes_AS_STRING(rv); + + for( ; len > 0 ; len--, ascii_data++ ) { + /* Get the byte and look it up */ + this_ch = table_a2b_hqx[*ascii_data]; + if ( this_ch == SKIP ) + continue; + if ( this_ch == FAIL ) { + PyErr_SetString(Error, "Illegal char"); + Py_DECREF(rv); + return NULL; + } + if ( this_ch == DONE ) { + /* The terminating colon */ + done = 1; + break; + } + + /* Shift it into the buffer and see if any bytes are ready */ + leftchar = (leftchar << 6) | (this_ch); + leftbits += 6; + if ( leftbits >= 8 ) { + leftbits -= 8; + *bin_data++ = (leftchar >> leftbits) & 0xff; + leftchar &= ((1 << leftbits) - 1); + } + } + + if ( leftbits && !done ) { + PyErr_SetString(Incomplete, + "String has incomplete number of bytes"); + Py_DECREF(rv); + return NULL; + } + if (_PyBytes_Resize(&rv, + (bin_data - + (unsigned char *)PyBytes_AS_STRING(rv))) < 0) { + Py_DECREF(rv); + rv = NULL; + } + if (rv) { + PyObject *rrv = Py_BuildValue("Oi", rv, done); + Py_DECREF(rv); + return rrv; + } + + return NULL; } PyDoc_STRVAR(doc_rlecode_hqx, "Binhex RLE-code binary data"); @@ -612,63 +612,63 @@ static PyObject * binascii_rlecode_hqx(PyObject *self, PyObject *args) { - Py_buffer pbuf; - unsigned char *in_data, *out_data; - PyObject *rv; - unsigned char ch; - Py_ssize_t in, inend, len; - - if ( !PyArg_ParseTuple(args, "y*:rlecode_hqx", &pbuf) ) - return NULL; - in_data = pbuf.buf; - len = pbuf.len; - - assert(len >= 0); - - if (len > PY_SSIZE_T_MAX / 2 - 2) { - PyBuffer_Release(&pbuf); - return PyErr_NoMemory(); - } - - /* Worst case: output is twice as big as input (fixed later) */ - if ( (rv=PyBytes_FromStringAndSize(NULL, len*2+2)) == NULL ) { - PyBuffer_Release(&pbuf); - return NULL; - } - out_data = (unsigned char *)PyBytes_AS_STRING(rv); - - for( in=0; in 3 ) { - /* More than 3 in a row. Output RLE. */ - *out_data++ = ch; - *out_data++ = RUNCHAR; - *out_data++ = inend-in; - in = inend-1; - } else { - /* Less than 3. Output the byte itself */ - *out_data++ = ch; - } - } - } - if (_PyBytes_Resize(&rv, - (out_data - - (unsigned char *)PyBytes_AS_STRING(rv))) < 0) { - Py_DECREF(rv); - rv = NULL; - } - PyBuffer_Release(&pbuf); - return rv; + Py_buffer pbuf; + unsigned char *in_data, *out_data; + PyObject *rv; + unsigned char ch; + Py_ssize_t in, inend, len; + + if ( !PyArg_ParseTuple(args, "y*:rlecode_hqx", &pbuf) ) + return NULL; + in_data = pbuf.buf; + len = pbuf.len; + + assert(len >= 0); + + if (len > PY_SSIZE_T_MAX / 2 - 2) { + PyBuffer_Release(&pbuf); + return PyErr_NoMemory(); + } + + /* Worst case: output is twice as big as input (fixed later) */ + if ( (rv=PyBytes_FromStringAndSize(NULL, len*2+2)) == NULL ) { + PyBuffer_Release(&pbuf); + return NULL; + } + out_data = (unsigned char *)PyBytes_AS_STRING(rv); + + for( in=0; in 3 ) { + /* More than 3 in a row. Output RLE. */ + *out_data++ = ch; + *out_data++ = RUNCHAR; + *out_data++ = inend-in; + in = inend-1; + } else { + /* Less than 3. Output the byte itself */ + *out_data++ = ch; + } + } + } + if (_PyBytes_Resize(&rv, + (out_data - + (unsigned char *)PyBytes_AS_STRING(rv))) < 0) { + Py_DECREF(rv); + rv = NULL; + } + PyBuffer_Release(&pbuf); + return rv; } PyDoc_STRVAR(doc_b2a_hqx, "Encode .hqx data"); @@ -676,56 +676,56 @@ static PyObject * binascii_b2a_hqx(PyObject *self, PyObject *args) { - Py_buffer pbin; - unsigned char *ascii_data, *bin_data; - int leftbits = 0; - unsigned char this_ch; - unsigned int leftchar = 0; - PyObject *rv; - Py_ssize_t len; - - if ( !PyArg_ParseTuple(args, "y*:b2a_hqx", &pbin) ) - return NULL; - bin_data = pbin.buf; - len = pbin.len; - - assert(len >= 0); - - if (len > PY_SSIZE_T_MAX / 2 - 2) { - PyBuffer_Release(&pbin); - return PyErr_NoMemory(); - } - - /* Allocate a buffer that is at least large enough */ - if ( (rv=PyBytes_FromStringAndSize(NULL, len*2+2)) == NULL ) { - PyBuffer_Release(&pbin); - return NULL; - } - ascii_data = (unsigned char *)PyBytes_AS_STRING(rv); - - for( ; len > 0 ; len--, bin_data++ ) { - /* Shift into our buffer, and output any 6bits ready */ - leftchar = (leftchar << 8) | *bin_data; - leftbits += 8; - while ( leftbits >= 6 ) { - this_ch = (leftchar >> (leftbits-6)) & 0x3f; - leftbits -= 6; - *ascii_data++ = table_b2a_hqx[this_ch]; - } - } - /* Output a possible runt byte */ - if ( leftbits ) { - leftchar <<= (6-leftbits); - *ascii_data++ = table_b2a_hqx[leftchar & 0x3f]; - } - if (_PyBytes_Resize(&rv, - (ascii_data - - (unsigned char *)PyBytes_AS_STRING(rv))) < 0) { - Py_DECREF(rv); - rv = NULL; - } - PyBuffer_Release(&pbin); - return rv; + Py_buffer pbin; + unsigned char *ascii_data, *bin_data; + int leftbits = 0; + unsigned char this_ch; + unsigned int leftchar = 0; + PyObject *rv; + Py_ssize_t len; + + if ( !PyArg_ParseTuple(args, "y*:b2a_hqx", &pbin) ) + return NULL; + bin_data = pbin.buf; + len = pbin.len; + + assert(len >= 0); + + if (len > PY_SSIZE_T_MAX / 2 - 2) { + PyBuffer_Release(&pbin); + return PyErr_NoMemory(); + } + + /* Allocate a buffer that is at least large enough */ + if ( (rv=PyBytes_FromStringAndSize(NULL, len*2+2)) == NULL ) { + PyBuffer_Release(&pbin); + return NULL; + } + ascii_data = (unsigned char *)PyBytes_AS_STRING(rv); + + for( ; len > 0 ; len--, bin_data++ ) { + /* Shift into our buffer, and output any 6bits ready */ + leftchar = (leftchar << 8) | *bin_data; + leftbits += 8; + while ( leftbits >= 6 ) { + this_ch = (leftchar >> (leftbits-6)) & 0x3f; + leftbits -= 6; + *ascii_data++ = table_b2a_hqx[this_ch]; + } + } + /* Output a possible runt byte */ + if ( leftbits ) { + leftchar <<= (6-leftbits); + *ascii_data++ = table_b2a_hqx[leftchar & 0x3f]; + } + if (_PyBytes_Resize(&rv, + (ascii_data - + (unsigned char *)PyBytes_AS_STRING(rv))) < 0) { + Py_DECREF(rv); + rv = NULL; + } + PyBuffer_Release(&pbin); + return rv; } PyDoc_STRVAR(doc_rledecode_hqx, "Decode hexbin RLE-coded string"); @@ -733,116 +733,116 @@ static PyObject * binascii_rledecode_hqx(PyObject *self, PyObject *args) { - Py_buffer pin; - unsigned char *in_data, *out_data; - unsigned char in_byte, in_repeat; - PyObject *rv; - Py_ssize_t in_len, out_len, out_len_left; - - if ( !PyArg_ParseTuple(args, "s*:rledecode_hqx", &pin) ) - return NULL; - in_data = pin.buf; - in_len = pin.len; - - assert(in_len >= 0); - - /* Empty string is a special case */ - if ( in_len == 0 ) { - PyBuffer_Release(&pin); - return PyBytes_FromStringAndSize("", 0); - } - else if (in_len > PY_SSIZE_T_MAX / 2) { - PyBuffer_Release(&pin); - return PyErr_NoMemory(); - } - - /* Allocate a buffer of reasonable size. Resized when needed */ - out_len = in_len*2; - if ( (rv=PyBytes_FromStringAndSize(NULL, out_len)) == NULL ) { - PyBuffer_Release(&pin); - return NULL; - } - out_len_left = out_len; - out_data = (unsigned char *)PyBytes_AS_STRING(rv); - - /* - ** We need two macros here to get/put bytes and handle - ** end-of-buffer for input and output strings. - */ + Py_buffer pin; + unsigned char *in_data, *out_data; + unsigned char in_byte, in_repeat; + PyObject *rv; + Py_ssize_t in_len, out_len, out_len_left; + + if ( !PyArg_ParseTuple(args, "s*:rledecode_hqx", &pin) ) + return NULL; + in_data = pin.buf; + in_len = pin.len; + + assert(in_len >= 0); + + /* Empty string is a special case */ + if ( in_len == 0 ) { + PyBuffer_Release(&pin); + return PyBytes_FromStringAndSize("", 0); + } + else if (in_len > PY_SSIZE_T_MAX / 2) { + PyBuffer_Release(&pin); + return PyErr_NoMemory(); + } + + /* Allocate a buffer of reasonable size. Resized when needed */ + out_len = in_len*2; + if ( (rv=PyBytes_FromStringAndSize(NULL, out_len)) == NULL ) { + PyBuffer_Release(&pin); + return NULL; + } + out_len_left = out_len; + out_data = (unsigned char *)PyBytes_AS_STRING(rv); + + /* + ** We need two macros here to get/put bytes and handle + ** end-of-buffer for input and output strings. + */ #define INBYTE(b) \ - do { \ - if ( --in_len < 0 ) { \ - PyErr_SetString(Incomplete, ""); \ - Py_DECREF(rv); \ - PyBuffer_Release(&pin); \ - return NULL; \ - } \ - b = *in_data++; \ - } while(0) + do { \ + if ( --in_len < 0 ) { \ + PyErr_SetString(Incomplete, ""); \ + Py_DECREF(rv); \ + PyBuffer_Release(&pin); \ + return NULL; \ + } \ + b = *in_data++; \ + } while(0) #define OUTBYTE(b) \ - do { \ - if ( --out_len_left < 0 ) { \ - if ( out_len > PY_SSIZE_T_MAX / 2) return PyErr_NoMemory(); \ - if (_PyBytes_Resize(&rv, 2*out_len) < 0) \ - { Py_DECREF(rv); PyBuffer_Release(&pin); return NULL; } \ - out_data = (unsigned char *)PyBytes_AS_STRING(rv) \ - + out_len; \ - out_len_left = out_len-1; \ - out_len = out_len * 2; \ - } \ - *out_data++ = b; \ - } while(0) - - /* - ** Handle first byte separately (since we have to get angry - ** in case of an orphaned RLE code). - */ - INBYTE(in_byte); - - if (in_byte == RUNCHAR) { - INBYTE(in_repeat); - if (in_repeat != 0) { - /* Note Error, not Incomplete (which is at the end - ** of the string only). This is a programmer error. - */ - PyErr_SetString(Error, "Orphaned RLE code at start"); - PyBuffer_Release(&pin); - Py_DECREF(rv); - return NULL; - } - OUTBYTE(RUNCHAR); - } else { - OUTBYTE(in_byte); - } - - while( in_len > 0 ) { - INBYTE(in_byte); - - if (in_byte == RUNCHAR) { - INBYTE(in_repeat); - if ( in_repeat == 0 ) { - /* Just an escaped RUNCHAR value */ - OUTBYTE(RUNCHAR); - } else { - /* Pick up value and output a sequence of it */ - in_byte = out_data[-1]; - while ( --in_repeat > 0 ) - OUTBYTE(in_byte); - } - } else { - /* Normal byte */ - OUTBYTE(in_byte); - } - } - if (_PyBytes_Resize(&rv, - (out_data - - (unsigned char *)PyBytes_AS_STRING(rv))) < 0) { - Py_DECREF(rv); - rv = NULL; - } - PyBuffer_Release(&pin); - return rv; + do { \ + if ( --out_len_left < 0 ) { \ + if ( out_len > PY_SSIZE_T_MAX / 2) return PyErr_NoMemory(); \ + if (_PyBytes_Resize(&rv, 2*out_len) < 0) \ + { Py_DECREF(rv); PyBuffer_Release(&pin); return NULL; } \ + out_data = (unsigned char *)PyBytes_AS_STRING(rv) \ + + out_len; \ + out_len_left = out_len-1; \ + out_len = out_len * 2; \ + } \ + *out_data++ = b; \ + } while(0) + + /* + ** Handle first byte separately (since we have to get angry + ** in case of an orphaned RLE code). + */ + INBYTE(in_byte); + + if (in_byte == RUNCHAR) { + INBYTE(in_repeat); + if (in_repeat != 0) { + /* Note Error, not Incomplete (which is at the end + ** of the string only). This is a programmer error. + */ + PyErr_SetString(Error, "Orphaned RLE code at start"); + PyBuffer_Release(&pin); + Py_DECREF(rv); + return NULL; + } + OUTBYTE(RUNCHAR); + } else { + OUTBYTE(in_byte); + } + + while( in_len > 0 ) { + INBYTE(in_byte); + + if (in_byte == RUNCHAR) { + INBYTE(in_repeat); + if ( in_repeat == 0 ) { + /* Just an escaped RUNCHAR value */ + OUTBYTE(RUNCHAR); + } else { + /* Pick up value and output a sequence of it */ + in_byte = out_data[-1]; + while ( --in_repeat > 0 ) + OUTBYTE(in_byte); + } + } else { + /* Normal byte */ + OUTBYTE(in_byte); + } + } + if (_PyBytes_Resize(&rv, + (out_data - + (unsigned char *)PyBytes_AS_STRING(rv))) < 0) { + Py_DECREF(rv); + rv = NULL; + } + PyBuffer_Release(&pin); + return rv; } PyDoc_STRVAR(doc_crc_hqx, @@ -851,22 +851,22 @@ static PyObject * binascii_crc_hqx(PyObject *self, PyObject *args) { - Py_buffer pin; - unsigned char *bin_data; - unsigned int crc; - Py_ssize_t len; - - if ( !PyArg_ParseTuple(args, "y*i:crc_hqx", &pin, &crc) ) - return NULL; - bin_data = pin.buf; - len = pin.len; - - while(len-- > 0) { - crc=((crc<<8)&0xff00)^crctab_hqx[((crc>>8)&0xff)^*bin_data++]; - } + Py_buffer pin; + unsigned char *bin_data; + unsigned int crc; + Py_ssize_t len; - PyBuffer_Release(&pin); - return Py_BuildValue("i", crc); + if ( !PyArg_ParseTuple(args, "y*i:crc_hqx", &pin, &crc) ) + return NULL; + bin_data = pin.buf; + len = pin.len; + + while(len-- > 0) { + crc=((crc<<8)&0xff00)^crctab_hqx[((crc>>8)&0xff)^*bin_data++]; + } + + PyBuffer_Release(&pin); + return Py_BuildValue("i", crc); } PyDoc_STRVAR(doc_crc32, @@ -884,7 +884,7 @@ int signed_val; if (!PyArg_ParseTuple(args, "y*|I:crc32", &pbuf, &crc32val)) - return NULL; + return NULL; buf = (Byte*)pbuf.buf; len = pbuf.len; signed_val = crc32(crc32val, buf, len); @@ -1013,26 +1013,26 @@ static PyObject * binascii_crc32(PyObject *self, PyObject *args) { /* By Jim Ahlstrom; All rights transferred to CNRI */ - Py_buffer pbin; - unsigned char *bin_data; - unsigned int crc = 0; /* initial value of CRC */ - Py_ssize_t len; - unsigned int result; - - if ( !PyArg_ParseTuple(args, "y*|I:crc32", &pbin, &crc) ) - return NULL; - bin_data = pbin.buf; - len = pbin.len; - - crc = ~ crc; - while (len-- > 0) { - crc = crc_32_tab[(crc ^ *bin_data++) & 0xff] ^ (crc >> 8); - /* Note: (crc >> 8) MUST zero fill on left */ - } - - result = (crc ^ 0xFFFFFFFF); - PyBuffer_Release(&pbin); - return PyLong_FromUnsignedLong(result & 0xffffffff); + Py_buffer pbin; + unsigned char *bin_data; + unsigned int crc = 0; /* initial value of CRC */ + Py_ssize_t len; + unsigned int result; + + if ( !PyArg_ParseTuple(args, "y*|I:crc32", &pbin, &crc) ) + return NULL; + bin_data = pbin.buf; + len = pbin.len; + + crc = ~ crc; + while (len-- > 0) { + crc = crc_32_tab[(crc ^ *bin_data++) & 0xff] ^ (crc >> 8); + /* Note: (crc >> 8) MUST zero fill on left */ + } + + result = (crc ^ 0xFFFFFFFF); + PyBuffer_Release(&pbin); + return PyLong_FromUnsignedLong(result & 0xffffffff); } #endif /* USE_ZLIB_CRC32 */ @@ -1040,43 +1040,43 @@ static PyObject * binascii_hexlify(PyObject *self, PyObject *args) { - Py_buffer parg; - char* argbuf; - Py_ssize_t arglen; - PyObject *retval; - char* retbuf; - Py_ssize_t i, j; - - if (!PyArg_ParseTuple(args, "y*:b2a_hex", &parg)) - return NULL; - argbuf = parg.buf; - arglen = parg.len; - - assert(arglen >= 0); - if (arglen > PY_SSIZE_T_MAX / 2) { - PyBuffer_Release(&parg); - return PyErr_NoMemory(); - } - - retval = PyBytes_FromStringAndSize(NULL, arglen*2); - if (!retval) { - PyBuffer_Release(&parg); - return NULL; - } - retbuf = PyBytes_AS_STRING(retval); - - /* make hex version of string, taken from shamodule.c */ - for (i=j=0; i < arglen; i++) { - char c; - c = (argbuf[i] >> 4) & 0xf; - c = (c>9) ? c+'a'-10 : c + '0'; - retbuf[j++] = c; - c = argbuf[i] & 0xf; - c = (c>9) ? c+'a'-10 : c + '0'; - retbuf[j++] = c; - } - PyBuffer_Release(&parg); - return retval; + Py_buffer parg; + char* argbuf; + Py_ssize_t arglen; + PyObject *retval; + char* retbuf; + Py_ssize_t i, j; + + if (!PyArg_ParseTuple(args, "y*:b2a_hex", &parg)) + return NULL; + argbuf = parg.buf; + arglen = parg.len; + + assert(arglen >= 0); + if (arglen > PY_SSIZE_T_MAX / 2) { + PyBuffer_Release(&parg); + return PyErr_NoMemory(); + } + + retval = PyBytes_FromStringAndSize(NULL, arglen*2); + if (!retval) { + PyBuffer_Release(&parg); + return NULL; + } + retbuf = PyBytes_AS_STRING(retval); + + /* make hex version of string, taken from shamodule.c */ + for (i=j=0; i < arglen; i++) { + char c; + c = (argbuf[i] >> 4) & 0xf; + c = (c>9) ? c+'a'-10 : c + '0'; + retbuf[j++] = c; + c = argbuf[i] & 0xf; + c = (c>9) ? c+'a'-10 : c + '0'; + retbuf[j++] = c; + } + PyBuffer_Release(&parg); + return retval; } PyDoc_STRVAR(doc_hexlify, @@ -1088,69 +1088,69 @@ static int to_int(int c) { - if (isdigit(c)) - return c - '0'; - else { - if (isupper(c)) - c = tolower(c); - if (c >= 'a' && c <= 'f') - return c - 'a' + 10; - } - return -1; + if (isdigit(c)) + return c - '0'; + else { + if (isupper(c)) + c = tolower(c); + if (c >= 'a' && c <= 'f') + return c - 'a' + 10; + } + return -1; } static PyObject * binascii_unhexlify(PyObject *self, PyObject *args) { - Py_buffer parg; - char* argbuf; - Py_ssize_t arglen; - PyObject *retval; - char* retbuf; - Py_ssize_t i, j; - - if (!PyArg_ParseTuple(args, "s*:a2b_hex", &parg)) - return NULL; - argbuf = parg.buf; - arglen = parg.len; - - assert(arglen >= 0); - - /* XXX What should we do about strings with an odd length? Should - * we add an implicit leading zero, or a trailing zero? For now, - * raise an exception. - */ - if (arglen % 2) { - PyBuffer_Release(&parg); - PyErr_SetString(Error, "Odd-length string"); - return NULL; - } - - retval = PyBytes_FromStringAndSize(NULL, (arglen/2)); - if (!retval) { - PyBuffer_Release(&parg); - return NULL; - } - retbuf = PyBytes_AS_STRING(retval); - - for (i=j=0; i < arglen; i += 2) { - int top = to_int(Py_CHARMASK(argbuf[i])); - int bot = to_int(Py_CHARMASK(argbuf[i+1])); - if (top == -1 || bot == -1) { - PyErr_SetString(Error, - "Non-hexadecimal digit found"); - goto finally; - } - retbuf[j++] = (top << 4) + bot; - } - PyBuffer_Release(&parg); - return retval; + Py_buffer parg; + char* argbuf; + Py_ssize_t arglen; + PyObject *retval; + char* retbuf; + Py_ssize_t i, j; + + if (!PyArg_ParseTuple(args, "s*:a2b_hex", &parg)) + return NULL; + argbuf = parg.buf; + arglen = parg.len; + + assert(arglen >= 0); + + /* XXX What should we do about strings with an odd length? Should + * we add an implicit leading zero, or a trailing zero? For now, + * raise an exception. + */ + if (arglen % 2) { + PyBuffer_Release(&parg); + PyErr_SetString(Error, "Odd-length string"); + return NULL; + } + + retval = PyBytes_FromStringAndSize(NULL, (arglen/2)); + if (!retval) { + PyBuffer_Release(&parg); + return NULL; + } + retbuf = PyBytes_AS_STRING(retval); + + for (i=j=0; i < arglen; i += 2) { + int top = to_int(Py_CHARMASK(argbuf[i])); + int bot = to_int(Py_CHARMASK(argbuf[i+1])); + if (top == -1 || bot == -1) { + PyErr_SetString(Error, + "Non-hexadecimal digit found"); + goto finally; + } + retbuf[j++] = (top << 4) + bot; + } + PyBuffer_Release(&parg); + return retval; finally: - PyBuffer_Release(&parg); - Py_DECREF(retval); - return NULL; + PyBuffer_Release(&parg); + Py_DECREF(retval); + return NULL; } PyDoc_STRVAR(doc_unhexlify, @@ -1179,96 +1179,96 @@ static PyObject* binascii_a2b_qp(PyObject *self, PyObject *args, PyObject *kwargs) { - Py_ssize_t in, out; - char ch; - Py_buffer pdata; - unsigned char *data, *odata; - Py_ssize_t datalen = 0; - PyObject *rv; - static char *kwlist[] = {"data", "header", NULL}; - int header = 0; - - if (!PyArg_ParseTupleAndKeywords(args, kwargs, "s*|i", kwlist, &pdata, - &header)) - return NULL; - data = pdata.buf; - datalen = pdata.len; - - /* We allocate the output same size as input, this is overkill. - * The previous implementation used calloc() so we'll zero out the - * memory here too, since PyMem_Malloc() does not guarantee that. - */ - odata = (unsigned char *) PyMem_Malloc(datalen); - if (odata == NULL) { - PyBuffer_Release(&pdata); - PyErr_NoMemory(); - return NULL; - } - memset(odata, 0, datalen); - - in = out = 0; - while (in < datalen) { - if (data[in] == '=') { - in++; - if (in >= datalen) break; - /* Soft line breaks */ - if ((data[in] == '\n') || (data[in] == '\r')) { - if (data[in] != '\n') { - while (in < datalen && data[in] != '\n') in++; - } - if (in < datalen) in++; - } - else if (data[in] == '=') { - /* broken case from broken python qp */ - odata[out++] = '='; - in++; - } - else if (((data[in] >= 'A' && data[in] <= 'F') || - (data[in] >= 'a' && data[in] <= 'f') || - (data[in] >= '0' && data[in] <= '9')) && - ((data[in+1] >= 'A' && data[in+1] <= 'F') || - (data[in+1] >= 'a' && data[in+1] <= 'f') || - (data[in+1] >= '0' && data[in+1] <= '9'))) { - /* hexval */ - ch = hexval(data[in]) << 4; - in++; - ch |= hexval(data[in]); - in++; - odata[out++] = ch; - } - else { - odata[out++] = '='; - } - } - else if (header && data[in] == '_') { - odata[out++] = ' '; - in++; - } - else { - odata[out] = data[in]; - in++; - out++; - } - } - if ((rv = PyBytes_FromStringAndSize((char *)odata, out)) == NULL) { - PyBuffer_Release(&pdata); - PyMem_Free(odata); - return NULL; - } - PyBuffer_Release(&pdata); - PyMem_Free(odata); - return rv; + Py_ssize_t in, out; + char ch; + Py_buffer pdata; + unsigned char *data, *odata; + Py_ssize_t datalen = 0; + PyObject *rv; + static char *kwlist[] = {"data", "header", NULL}; + int header = 0; + + if (!PyArg_ParseTupleAndKeywords(args, kwargs, "s*|i", kwlist, &pdata, + &header)) + return NULL; + data = pdata.buf; + datalen = pdata.len; + + /* We allocate the output same size as input, this is overkill. + * The previous implementation used calloc() so we'll zero out the + * memory here too, since PyMem_Malloc() does not guarantee that. + */ + odata = (unsigned char *) PyMem_Malloc(datalen); + if (odata == NULL) { + PyBuffer_Release(&pdata); + PyErr_NoMemory(); + return NULL; + } + memset(odata, 0, datalen); + + in = out = 0; + while (in < datalen) { + if (data[in] == '=') { + in++; + if (in >= datalen) break; + /* Soft line breaks */ + if ((data[in] == '\n') || (data[in] == '\r')) { + if (data[in] != '\n') { + while (in < datalen && data[in] != '\n') in++; + } + if (in < datalen) in++; + } + else if (data[in] == '=') { + /* broken case from broken python qp */ + odata[out++] = '='; + in++; + } + else if (((data[in] >= 'A' && data[in] <= 'F') || + (data[in] >= 'a' && data[in] <= 'f') || + (data[in] >= '0' && data[in] <= '9')) && + ((data[in+1] >= 'A' && data[in+1] <= 'F') || + (data[in+1] >= 'a' && data[in+1] <= 'f') || + (data[in+1] >= '0' && data[in+1] <= '9'))) { + /* hexval */ + ch = hexval(data[in]) << 4; + in++; + ch |= hexval(data[in]); + in++; + odata[out++] = ch; + } + else { + odata[out++] = '='; + } + } + else if (header && data[in] == '_') { + odata[out++] = ' '; + in++; + } + else { + odata[out] = data[in]; + in++; + out++; + } + } + if ((rv = PyBytes_FromStringAndSize((char *)odata, out)) == NULL) { + PyBuffer_Release(&pdata); + PyMem_Free(odata); + return NULL; + } + PyBuffer_Release(&pdata); + PyMem_Free(odata); + return rv; } static int to_hex (unsigned char ch, unsigned char *s) { - unsigned int uvalue = ch; + unsigned int uvalue = ch; - s[1] = "0123456789ABCDEF"[uvalue % 16]; - uvalue = (uvalue / 16); - s[0] = "0123456789ABCDEF"[uvalue % 16]; - return 0; + s[1] = "0123456789ABCDEF"[uvalue % 16]; + uvalue = (uvalue / 16); + s[0] = "0123456789ABCDEF"[uvalue % 16]; + return 0; } PyDoc_STRVAR(doc_b2a_qp, @@ -1285,210 +1285,210 @@ static PyObject* binascii_b2a_qp (PyObject *self, PyObject *args, PyObject *kwargs) { - Py_ssize_t in, out; - Py_buffer pdata; - unsigned char *data, *odata; - Py_ssize_t datalen = 0, odatalen = 0; - PyObject *rv; - unsigned int linelen = 0; - static char *kwlist[] = {"data", "quotetabs", "istext", - "header", NULL}; - int istext = 1; - int quotetabs = 0; - int header = 0; - unsigned char ch; - int crlf = 0; - unsigned char *p; - - if (!PyArg_ParseTupleAndKeywords(args, kwargs, "y*|iii", kwlist, &pdata, - "etabs, &istext, &header)) - return NULL; - data = pdata.buf; - datalen = pdata.len; - - /* See if this string is using CRLF line ends */ - /* XXX: this function has the side effect of converting all of - * the end of lines to be the same depending on this detection - * here */ - p = (unsigned char *) memchr(data, '\n', datalen); - if ((p != NULL) && (p > data) && (*(p-1) == '\r')) - crlf = 1; - - /* First, scan to see how many characters need to be encoded */ - in = 0; - while (in < datalen) { - if ((data[in] > 126) || - (data[in] == '=') || - (header && data[in] == '_') || - ((data[in] == '.') && (linelen == 0) && - (data[in+1] == '\n' || data[in+1] == '\r' || data[in+1] == 0)) || - (!istext && ((data[in] == '\r') || (data[in] == '\n'))) || - ((data[in] == '\t' || data[in] == ' ') && (in + 1 == datalen)) || - ((data[in] < 33) && - (data[in] != '\r') && (data[in] != '\n') && - (quotetabs || - (!quotetabs && ((data[in] != '\t') && (data[in] != ' ')))))) - { - if ((linelen + 3) >= MAXLINESIZE) { - linelen = 0; - if (crlf) - odatalen += 3; - else - odatalen += 2; - } - linelen += 3; - odatalen += 3; - in++; - } - else { - if (istext && - ((data[in] == '\n') || - ((in+1 < datalen) && (data[in] == '\r') && - (data[in+1] == '\n')))) - { - linelen = 0; - /* Protect against whitespace on end of line */ - if (in && ((data[in-1] == ' ') || (data[in-1] == '\t'))) - odatalen += 2; - if (crlf) - odatalen += 2; - else - odatalen += 1; - if (data[in] == '\r') - in += 2; - else - in++; - } - else { - if ((in + 1 != datalen) && - (data[in+1] != '\n') && - (linelen + 1) >= MAXLINESIZE) { - linelen = 0; - if (crlf) - odatalen += 3; - else - odatalen += 2; - } - linelen++; - odatalen++; - in++; - } - } - } - - /* We allocate the output same size as input, this is overkill. - * The previous implementation used calloc() so we'll zero out the - * memory here too, since PyMem_Malloc() does not guarantee that. - */ - odata = (unsigned char *) PyMem_Malloc(odatalen); - if (odata == NULL) { - PyBuffer_Release(&pdata); - PyErr_NoMemory(); - return NULL; - } - memset(odata, 0, odatalen); - - in = out = linelen = 0; - while (in < datalen) { - if ((data[in] > 126) || - (data[in] == '=') || - (header && data[in] == '_') || - ((data[in] == '.') && (linelen == 0) && - (data[in+1] == '\n' || data[in+1] == '\r' || data[in+1] == 0)) || - (!istext && ((data[in] == '\r') || (data[in] == '\n'))) || - ((data[in] == '\t' || data[in] == ' ') && (in + 1 == datalen)) || - ((data[in] < 33) && - (data[in] != '\r') && (data[in] != '\n') && - (quotetabs || - (!quotetabs && ((data[in] != '\t') && (data[in] != ' ')))))) - { - if ((linelen + 3 )>= MAXLINESIZE) { - odata[out++] = '='; - if (crlf) odata[out++] = '\r'; - odata[out++] = '\n'; - linelen = 0; - } - odata[out++] = '='; - to_hex(data[in], &odata[out]); - out += 2; - in++; - linelen += 3; - } - else { - if (istext && - ((data[in] == '\n') || - ((in+1 < datalen) && (data[in] == '\r') && - (data[in+1] == '\n')))) - { - linelen = 0; - /* Protect against whitespace on end of line */ - if (out && ((odata[out-1] == ' ') || (odata[out-1] == '\t'))) { - ch = odata[out-1]; - odata[out-1] = '='; - to_hex(ch, &odata[out]); - out += 2; - } - - if (crlf) odata[out++] = '\r'; - odata[out++] = '\n'; - if (data[in] == '\r') - in += 2; - else - in++; - } - else { - if ((in + 1 != datalen) && - (data[in+1] != '\n') && - (linelen + 1) >= MAXLINESIZE) { - odata[out++] = '='; - if (crlf) odata[out++] = '\r'; - odata[out++] = '\n'; - linelen = 0; - } - linelen++; - if (header && data[in] == ' ') { - odata[out++] = '_'; - in++; - } - else { - odata[out++] = data[in++]; - } - } - } - } - if ((rv = PyBytes_FromStringAndSize((char *)odata, out)) == NULL) { - PyBuffer_Release(&pdata); - PyMem_Free(odata); - return NULL; - } - PyBuffer_Release(&pdata); - PyMem_Free(odata); - return rv; + Py_ssize_t in, out; + Py_buffer pdata; + unsigned char *data, *odata; + Py_ssize_t datalen = 0, odatalen = 0; + PyObject *rv; + unsigned int linelen = 0; + static char *kwlist[] = {"data", "quotetabs", "istext", + "header", NULL}; + int istext = 1; + int quotetabs = 0; + int header = 0; + unsigned char ch; + int crlf = 0; + unsigned char *p; + + if (!PyArg_ParseTupleAndKeywords(args, kwargs, "y*|iii", kwlist, &pdata, + "etabs, &istext, &header)) + return NULL; + data = pdata.buf; + datalen = pdata.len; + + /* See if this string is using CRLF line ends */ + /* XXX: this function has the side effect of converting all of + * the end of lines to be the same depending on this detection + * here */ + p = (unsigned char *) memchr(data, '\n', datalen); + if ((p != NULL) && (p > data) && (*(p-1) == '\r')) + crlf = 1; + + /* First, scan to see how many characters need to be encoded */ + in = 0; + while (in < datalen) { + if ((data[in] > 126) || + (data[in] == '=') || + (header && data[in] == '_') || + ((data[in] == '.') && (linelen == 0) && + (data[in+1] == '\n' || data[in+1] == '\r' || data[in+1] == 0)) || + (!istext && ((data[in] == '\r') || (data[in] == '\n'))) || + ((data[in] == '\t' || data[in] == ' ') && (in + 1 == datalen)) || + ((data[in] < 33) && + (data[in] != '\r') && (data[in] != '\n') && + (quotetabs || + (!quotetabs && ((data[in] != '\t') && (data[in] != ' ')))))) + { + if ((linelen + 3) >= MAXLINESIZE) { + linelen = 0; + if (crlf) + odatalen += 3; + else + odatalen += 2; + } + linelen += 3; + odatalen += 3; + in++; + } + else { + if (istext && + ((data[in] == '\n') || + ((in+1 < datalen) && (data[in] == '\r') && + (data[in+1] == '\n')))) + { + linelen = 0; + /* Protect against whitespace on end of line */ + if (in && ((data[in-1] == ' ') || (data[in-1] == '\t'))) + odatalen += 2; + if (crlf) + odatalen += 2; + else + odatalen += 1; + if (data[in] == '\r') + in += 2; + else + in++; + } + else { + if ((in + 1 != datalen) && + (data[in+1] != '\n') && + (linelen + 1) >= MAXLINESIZE) { + linelen = 0; + if (crlf) + odatalen += 3; + else + odatalen += 2; + } + linelen++; + odatalen++; + in++; + } + } + } + + /* We allocate the output same size as input, this is overkill. + * The previous implementation used calloc() so we'll zero out the + * memory here too, since PyMem_Malloc() does not guarantee that. + */ + odata = (unsigned char *) PyMem_Malloc(odatalen); + if (odata == NULL) { + PyBuffer_Release(&pdata); + PyErr_NoMemory(); + return NULL; + } + memset(odata, 0, odatalen); + + in = out = linelen = 0; + while (in < datalen) { + if ((data[in] > 126) || + (data[in] == '=') || + (header && data[in] == '_') || + ((data[in] == '.') && (linelen == 0) && + (data[in+1] == '\n' || data[in+1] == '\r' || data[in+1] == 0)) || + (!istext && ((data[in] == '\r') || (data[in] == '\n'))) || + ((data[in] == '\t' || data[in] == ' ') && (in + 1 == datalen)) || + ((data[in] < 33) && + (data[in] != '\r') && (data[in] != '\n') && + (quotetabs || + (!quotetabs && ((data[in] != '\t') && (data[in] != ' ')))))) + { + if ((linelen + 3 )>= MAXLINESIZE) { + odata[out++] = '='; + if (crlf) odata[out++] = '\r'; + odata[out++] = '\n'; + linelen = 0; + } + odata[out++] = '='; + to_hex(data[in], &odata[out]); + out += 2; + in++; + linelen += 3; + } + else { + if (istext && + ((data[in] == '\n') || + ((in+1 < datalen) && (data[in] == '\r') && + (data[in+1] == '\n')))) + { + linelen = 0; + /* Protect against whitespace on end of line */ + if (out && ((odata[out-1] == ' ') || (odata[out-1] == '\t'))) { + ch = odata[out-1]; + odata[out-1] = '='; + to_hex(ch, &odata[out]); + out += 2; + } + + if (crlf) odata[out++] = '\r'; + odata[out++] = '\n'; + if (data[in] == '\r') + in += 2; + else + in++; + } + else { + if ((in + 1 != datalen) && + (data[in+1] != '\n') && + (linelen + 1) >= MAXLINESIZE) { + odata[out++] = '='; + if (crlf) odata[out++] = '\r'; + odata[out++] = '\n'; + linelen = 0; + } + linelen++; + if (header && data[in] == ' ') { + odata[out++] = '_'; + in++; + } + else { + odata[out++] = data[in++]; + } + } + } + } + if ((rv = PyBytes_FromStringAndSize((char *)odata, out)) == NULL) { + PyBuffer_Release(&pdata); + PyMem_Free(odata); + return NULL; + } + PyBuffer_Release(&pdata); + PyMem_Free(odata); + return rv; } /* List of functions defined in the module */ static struct PyMethodDef binascii_module_methods[] = { - {"a2b_uu", binascii_a2b_uu, METH_VARARGS, doc_a2b_uu}, - {"b2a_uu", binascii_b2a_uu, METH_VARARGS, doc_b2a_uu}, - {"a2b_base64", binascii_a2b_base64, METH_VARARGS, doc_a2b_base64}, - {"b2a_base64", binascii_b2a_base64, METH_VARARGS, doc_b2a_base64}, - {"a2b_hqx", binascii_a2b_hqx, METH_VARARGS, doc_a2b_hqx}, - {"b2a_hqx", binascii_b2a_hqx, METH_VARARGS, doc_b2a_hqx}, - {"b2a_hex", binascii_hexlify, METH_VARARGS, doc_hexlify}, - {"a2b_hex", binascii_unhexlify, METH_VARARGS, doc_unhexlify}, - {"hexlify", binascii_hexlify, METH_VARARGS, doc_hexlify}, - {"unhexlify", binascii_unhexlify, METH_VARARGS, doc_unhexlify}, - {"rlecode_hqx", binascii_rlecode_hqx, METH_VARARGS, doc_rlecode_hqx}, - {"rledecode_hqx", binascii_rledecode_hqx, METH_VARARGS, - doc_rledecode_hqx}, - {"crc_hqx", binascii_crc_hqx, METH_VARARGS, doc_crc_hqx}, - {"crc32", binascii_crc32, METH_VARARGS, doc_crc32}, - {"a2b_qp", (PyCFunction)binascii_a2b_qp, METH_VARARGS | METH_KEYWORDS, - doc_a2b_qp}, - {"b2a_qp", (PyCFunction)binascii_b2a_qp, METH_VARARGS | METH_KEYWORDS, - doc_b2a_qp}, - {NULL, NULL} /* sentinel */ + {"a2b_uu", binascii_a2b_uu, METH_VARARGS, doc_a2b_uu}, + {"b2a_uu", binascii_b2a_uu, METH_VARARGS, doc_b2a_uu}, + {"a2b_base64", binascii_a2b_base64, METH_VARARGS, doc_a2b_base64}, + {"b2a_base64", binascii_b2a_base64, METH_VARARGS, doc_b2a_base64}, + {"a2b_hqx", binascii_a2b_hqx, METH_VARARGS, doc_a2b_hqx}, + {"b2a_hqx", binascii_b2a_hqx, METH_VARARGS, doc_b2a_hqx}, + {"b2a_hex", binascii_hexlify, METH_VARARGS, doc_hexlify}, + {"a2b_hex", binascii_unhexlify, METH_VARARGS, doc_unhexlify}, + {"hexlify", binascii_hexlify, METH_VARARGS, doc_hexlify}, + {"unhexlify", binascii_unhexlify, METH_VARARGS, doc_unhexlify}, + {"rlecode_hqx", binascii_rlecode_hqx, METH_VARARGS, doc_rlecode_hqx}, + {"rledecode_hqx", binascii_rledecode_hqx, METH_VARARGS, + doc_rledecode_hqx}, + {"crc_hqx", binascii_crc_hqx, METH_VARARGS, doc_crc_hqx}, + {"crc32", binascii_crc32, METH_VARARGS, doc_crc32}, + {"a2b_qp", (PyCFunction)binascii_a2b_qp, METH_VARARGS | METH_KEYWORDS, + doc_a2b_qp}, + {"b2a_qp", (PyCFunction)binascii_b2a_qp, METH_VARARGS | METH_KEYWORDS, + doc_b2a_qp}, + {NULL, NULL} /* sentinel */ }; @@ -1497,36 +1497,36 @@ static struct PyModuleDef binasciimodule = { - PyModuleDef_HEAD_INIT, - "binascii", - doc_binascii, - -1, - binascii_module_methods, - NULL, - NULL, - NULL, - NULL + PyModuleDef_HEAD_INIT, + "binascii", + doc_binascii, + -1, + binascii_module_methods, + NULL, + NULL, + NULL, + NULL }; PyMODINIT_FUNC PyInit_binascii(void) { - PyObject *m, *d; + PyObject *m, *d; + + /* Create the module and add the functions */ + m = PyModule_Create(&binasciimodule); + if (m == NULL) + return NULL; + + d = PyModule_GetDict(m); - /* Create the module and add the functions */ - m = PyModule_Create(&binasciimodule); - if (m == NULL) - return NULL; - - d = PyModule_GetDict(m); - - Error = PyErr_NewException("binascii.Error", PyExc_ValueError, NULL); - PyDict_SetItemString(d, "Error", Error); - Incomplete = PyErr_NewException("binascii.Incomplete", NULL, NULL); - PyDict_SetItemString(d, "Incomplete", Incomplete); - if (PyErr_Occurred()) { - Py_DECREF(m); - m = NULL; - } - return m; + Error = PyErr_NewException("binascii.Error", PyExc_ValueError, NULL); + PyDict_SetItemString(d, "Error", Error); + Incomplete = PyErr_NewException("binascii.Incomplete", NULL, NULL); + PyDict_SetItemString(d, "Incomplete", Incomplete); + if (PyErr_Occurred()) { + Py_DECREF(m); + m = NULL; + } + return m; } Modified: python/branches/release31-maint/Modules/bz2module.c ============================================================================== --- python/branches/release31-maint/Modules/bz2module.c (original) +++ python/branches/release31-maint/Modules/bz2module.c Sun May 9 18:14:21 2010 @@ -41,20 +41,20 @@ #define MODE_READ_EOF 2 #define MODE_WRITE 3 -#define BZ2FileObject_Check(v) (Py_TYPE(v) == &BZ2File_Type) +#define BZ2FileObject_Check(v) (Py_TYPE(v) == &BZ2File_Type) #ifdef BZ_CONFIG_ERROR #if SIZEOF_LONG >= 8 #define BZS_TOTAL_OUT(bzs) \ - (((long)bzs->total_out_hi32 << 32) + bzs->total_out_lo32) + (((long)bzs->total_out_hi32 << 32) + bzs->total_out_lo32) #elif SIZEOF_LONG_LONG >= 8 #define BZS_TOTAL_OUT(bzs) \ - (((PY_LONG_LONG)bzs->total_out_hi32 << 32) + bzs->total_out_lo32) + (((PY_LONG_LONG)bzs->total_out_hi32 << 32) + bzs->total_out_lo32) #else #define BZS_TOTAL_OUT(bzs) \ - bzs->total_out_lo32 + bzs->total_out_lo32 #endif #else /* ! BZ_CONFIG_ERROR */ @@ -79,11 +79,11 @@ #ifdef WITH_THREAD #define ACQUIRE_LOCK(obj) do { \ - if (!PyThread_acquire_lock(obj->lock, 0)) { \ - Py_BEGIN_ALLOW_THREADS \ - PyThread_acquire_lock(obj->lock, 1); \ - Py_END_ALLOW_THREADS \ - } } while(0) + if (!PyThread_acquire_lock(obj->lock, 0)) { \ + Py_BEGIN_ALLOW_THREADS \ + PyThread_acquire_lock(obj->lock, 1); \ + Py_END_ALLOW_THREADS \ + } } while(0) #define RELEASE_LOCK(obj) PyThread_release_lock(obj->lock) #else #define ACQUIRE_LOCK(obj) @@ -91,47 +91,47 @@ #endif /* Bits in f_newlinetypes */ -#define NEWLINE_UNKNOWN 0 /* No newline seen, yet */ -#define NEWLINE_CR 1 /* \r newline seen */ -#define NEWLINE_LF 2 /* \n newline seen */ -#define NEWLINE_CRLF 4 /* \r\n newline seen */ +#define NEWLINE_UNKNOWN 0 /* No newline seen, yet */ +#define NEWLINE_CR 1 /* \r newline seen */ +#define NEWLINE_LF 2 /* \n newline seen */ +#define NEWLINE_CRLF 4 /* \r\n newline seen */ /* ===================================================================== */ /* Structure definitions. */ typedef struct { - PyObject_HEAD - FILE *rawfp; + PyObject_HEAD + FILE *rawfp; - char* f_buf; /* Allocated readahead buffer */ - char* f_bufend; /* Points after last occupied position */ - char* f_bufptr; /* Current buffer position */ - - BZFILE *fp; - int mode; - Py_off_t pos; - Py_off_t size; + char* f_buf; /* Allocated readahead buffer */ + char* f_bufend; /* Points after last occupied position */ + char* f_bufptr; /* Current buffer position */ + + BZFILE *fp; + int mode; + Py_off_t pos; + Py_off_t size; #ifdef WITH_THREAD - PyThread_type_lock lock; + PyThread_type_lock lock; #endif } BZ2FileObject; typedef struct { - PyObject_HEAD - bz_stream bzs; - int running; + PyObject_HEAD + bz_stream bzs; + int running; #ifdef WITH_THREAD - PyThread_type_lock lock; + PyThread_type_lock lock; #endif } BZ2CompObject; typedef struct { - PyObject_HEAD - bz_stream bzs; - int running; - PyObject *unused_data; + PyObject_HEAD + bz_stream bzs; + int running; + PyObject *unused_data; #ifdef WITH_THREAD - PyThread_type_lock lock; + PyThread_type_lock lock; #endif } BZ2DecompObject; @@ -141,59 +141,59 @@ static int Util_CatchBZ2Error(int bzerror) { - int ret = 0; - switch(bzerror) { - case BZ_OK: - case BZ_STREAM_END: - break; + int ret = 0; + switch(bzerror) { + case BZ_OK: + case BZ_STREAM_END: + break; #ifdef BZ_CONFIG_ERROR - case BZ_CONFIG_ERROR: - PyErr_SetString(PyExc_SystemError, - "the bz2 library was not compiled " - "correctly"); - ret = 1; - break; + case BZ_CONFIG_ERROR: + PyErr_SetString(PyExc_SystemError, + "the bz2 library was not compiled " + "correctly"); + ret = 1; + break; #endif - case BZ_PARAM_ERROR: - PyErr_SetString(PyExc_ValueError, - "the bz2 library has received wrong " - "parameters"); - ret = 1; - break; - - case BZ_MEM_ERROR: - PyErr_NoMemory(); - ret = 1; - break; - - case BZ_DATA_ERROR: - case BZ_DATA_ERROR_MAGIC: - PyErr_SetString(PyExc_IOError, "invalid data stream"); - ret = 1; - break; - - case BZ_IO_ERROR: - PyErr_SetString(PyExc_IOError, "unknown IO error"); - ret = 1; - break; - - case BZ_UNEXPECTED_EOF: - PyErr_SetString(PyExc_EOFError, - "compressed file ended before the " - "logical end-of-stream was detected"); - ret = 1; - break; - - case BZ_SEQUENCE_ERROR: - PyErr_SetString(PyExc_RuntimeError, - "wrong sequence of bz2 library " - "commands used"); - ret = 1; - break; - } - return ret; + case BZ_PARAM_ERROR: + PyErr_SetString(PyExc_ValueError, + "the bz2 library has received wrong " + "parameters"); + ret = 1; + break; + + case BZ_MEM_ERROR: + PyErr_NoMemory(); + ret = 1; + break; + + case BZ_DATA_ERROR: + case BZ_DATA_ERROR_MAGIC: + PyErr_SetString(PyExc_IOError, "invalid data stream"); + ret = 1; + break; + + case BZ_IO_ERROR: + PyErr_SetString(PyExc_IOError, "unknown IO error"); + ret = 1; + break; + + case BZ_UNEXPECTED_EOF: + PyErr_SetString(PyExc_EOFError, + "compressed file ended before the " + "logical end-of-stream was detected"); + ret = 1; + break; + + case BZ_SEQUENCE_ERROR: + PyErr_SetString(PyExc_RuntimeError, + "wrong sequence of bz2 library " + "commands used"); + ret = 1; + break; + } + return ret; } #if BUFSIZ < 8192 @@ -212,134 +212,134 @@ static size_t Util_NewBufferSize(size_t currentsize) { - if (currentsize > SMALLCHUNK) { - /* Keep doubling until we reach BIGCHUNK; - then keep adding BIGCHUNK. */ - if (currentsize <= BIGCHUNK) - return currentsize + currentsize; - else - return currentsize + BIGCHUNK; - } - return currentsize + SMALLCHUNK; + if (currentsize > SMALLCHUNK) { + /* Keep doubling until we reach BIGCHUNK; + then keep adding BIGCHUNK. */ + if (currentsize <= BIGCHUNK) + return currentsize + currentsize; + else + return currentsize + BIGCHUNK; + } + return currentsize + SMALLCHUNK; } /* This is a hacked version of Python's fileobject.c:get_line(). */ static PyObject * Util_GetLine(BZ2FileObject *f, int n) { - char c; - char *buf, *end; - size_t total_v_size; /* total # of slots in buffer */ - size_t used_v_size; /* # used slots in buffer */ - size_t increment; /* amount to increment the buffer */ - PyObject *v; - int bzerror; - int bytes_read; - - total_v_size = n > 0 ? n : 100; - v = PyBytes_FromStringAndSize((char *)NULL, total_v_size); - if (v == NULL) - return NULL; - - buf = BUF(v); - end = buf + total_v_size; - - for (;;) { - Py_BEGIN_ALLOW_THREADS - do { - bytes_read = BZ2_bzRead(&bzerror, f->fp, &c, 1); - f->pos++; - if (bytes_read == 0) - break; - *buf++ = c; - } while (bzerror == BZ_OK && c != '\n' && buf != end); - Py_END_ALLOW_THREADS - if (bzerror == BZ_STREAM_END) { - f->size = f->pos; - f->mode = MODE_READ_EOF; - break; - } else if (bzerror != BZ_OK) { - Util_CatchBZ2Error(bzerror); - Py_DECREF(v); - return NULL; - } - if (c == '\n') - break; - /* Must be because buf == end */ - if (n > 0) - break; - used_v_size = total_v_size; - increment = total_v_size >> 2; /* mild exponential growth */ - total_v_size += increment; - if (total_v_size > INT_MAX) { - PyErr_SetString(PyExc_OverflowError, - "line is longer than a Python string can hold"); - Py_DECREF(v); - return NULL; - } - if (_PyBytes_Resize(&v, total_v_size) < 0) { - return NULL; - } - buf = BUF(v) + used_v_size; - end = BUF(v) + total_v_size; - } - - used_v_size = buf - BUF(v); - if (used_v_size != total_v_size) { - if (_PyBytes_Resize(&v, used_v_size) < 0) { - v = NULL; - } - } - return v; + char c; + char *buf, *end; + size_t total_v_size; /* total # of slots in buffer */ + size_t used_v_size; /* # used slots in buffer */ + size_t increment; /* amount to increment the buffer */ + PyObject *v; + int bzerror; + int bytes_read; + + total_v_size = n > 0 ? n : 100; + v = PyBytes_FromStringAndSize((char *)NULL, total_v_size); + if (v == NULL) + return NULL; + + buf = BUF(v); + end = buf + total_v_size; + + for (;;) { + Py_BEGIN_ALLOW_THREADS + do { + bytes_read = BZ2_bzRead(&bzerror, f->fp, &c, 1); + f->pos++; + if (bytes_read == 0) + break; + *buf++ = c; + } while (bzerror == BZ_OK && c != '\n' && buf != end); + Py_END_ALLOW_THREADS + if (bzerror == BZ_STREAM_END) { + f->size = f->pos; + f->mode = MODE_READ_EOF; + break; + } else if (bzerror != BZ_OK) { + Util_CatchBZ2Error(bzerror); + Py_DECREF(v); + return NULL; + } + if (c == '\n') + break; + /* Must be because buf == end */ + if (n > 0) + break; + used_v_size = total_v_size; + increment = total_v_size >> 2; /* mild exponential growth */ + total_v_size += increment; + if (total_v_size > INT_MAX) { + PyErr_SetString(PyExc_OverflowError, + "line is longer than a Python string can hold"); + Py_DECREF(v); + return NULL; + } + if (_PyBytes_Resize(&v, total_v_size) < 0) { + return NULL; + } + buf = BUF(v) + used_v_size; + end = BUF(v) + total_v_size; + } + + used_v_size = buf - BUF(v); + if (used_v_size != total_v_size) { + if (_PyBytes_Resize(&v, used_v_size) < 0) { + v = NULL; + } + } + return v; } /* This is a hacked version of Python's fileobject.c:drop_readahead(). */ static void Util_DropReadAhead(BZ2FileObject *f) { - if (f->f_buf != NULL) { - PyMem_Free(f->f_buf); - f->f_buf = NULL; - } + if (f->f_buf != NULL) { + PyMem_Free(f->f_buf); + f->f_buf = NULL; + } } /* This is a hacked version of Python's fileobject.c:readahead(). */ static int Util_ReadAhead(BZ2FileObject *f, int bufsize) { - int chunksize; - int bzerror; + int chunksize; + int bzerror; - if (f->f_buf != NULL) { - if((f->f_bufend - f->f_bufptr) >= 1) - return 0; - else - Util_DropReadAhead(f); - } - if (f->mode == MODE_READ_EOF) { - f->f_bufptr = f->f_buf; - f->f_bufend = f->f_buf; - return 0; - } - if ((f->f_buf = PyMem_Malloc(bufsize)) == NULL) { - PyErr_NoMemory(); - return -1; - } - Py_BEGIN_ALLOW_THREADS - chunksize = BZ2_bzRead(&bzerror, f->fp, f->f_buf, bufsize); - Py_END_ALLOW_THREADS - f->pos += chunksize; - if (bzerror == BZ_STREAM_END) { - f->size = f->pos; - f->mode = MODE_READ_EOF; - } else if (bzerror != BZ_OK) { - Util_CatchBZ2Error(bzerror); - Util_DropReadAhead(f); - return -1; - } - f->f_bufptr = f->f_buf; - f->f_bufend = f->f_buf + chunksize; - return 0; + if (f->f_buf != NULL) { + if((f->f_bufend - f->f_bufptr) >= 1) + return 0; + else + Util_DropReadAhead(f); + } + if (f->mode == MODE_READ_EOF) { + f->f_bufptr = f->f_buf; + f->f_bufend = f->f_buf; + return 0; + } + if ((f->f_buf = PyMem_Malloc(bufsize)) == NULL) { + PyErr_NoMemory(); + return -1; + } + Py_BEGIN_ALLOW_THREADS + chunksize = BZ2_bzRead(&bzerror, f->fp, f->f_buf, bufsize); + Py_END_ALLOW_THREADS + f->pos += chunksize; + if (bzerror == BZ_STREAM_END) { + f->size = f->pos; + f->mode = MODE_READ_EOF; + } else if (bzerror != BZ_OK) { + Util_CatchBZ2Error(bzerror); + Util_DropReadAhead(f); + return -1; + } + f->f_bufptr = f->f_buf; + f->f_bufend = f->f_buf + chunksize; + return 0; } /* This is a hacked version of Python's @@ -347,45 +347,45 @@ static PyBytesObject * Util_ReadAheadGetLineSkip(BZ2FileObject *f, int skip, int bufsize) { - PyBytesObject* s; - char *bufptr; - char *buf; - int len; - - if (f->f_buf == NULL) - if (Util_ReadAhead(f, bufsize) < 0) - return NULL; - - len = f->f_bufend - f->f_bufptr; - if (len == 0) - return (PyBytesObject *) - PyBytes_FromStringAndSize(NULL, skip); - bufptr = memchr(f->f_bufptr, '\n', len); - if (bufptr != NULL) { - bufptr++; /* Count the '\n' */ - len = bufptr - f->f_bufptr; - s = (PyBytesObject *) - PyBytes_FromStringAndSize(NULL, skip+len); - if (s == NULL) - return NULL; - memcpy(PyBytes_AS_STRING(s)+skip, f->f_bufptr, len); - f->f_bufptr = bufptr; - if (bufptr == f->f_bufend) - Util_DropReadAhead(f); - } else { - bufptr = f->f_bufptr; - buf = f->f_buf; - f->f_buf = NULL; /* Force new readahead buffer */ - s = Util_ReadAheadGetLineSkip(f, skip+len, - bufsize + (bufsize>>2)); - if (s == NULL) { - PyMem_Free(buf); - return NULL; - } - memcpy(PyBytes_AS_STRING(s)+skip, bufptr, len); - PyMem_Free(buf); - } - return s; + PyBytesObject* s; + char *bufptr; + char *buf; + int len; + + if (f->f_buf == NULL) + if (Util_ReadAhead(f, bufsize) < 0) + return NULL; + + len = f->f_bufend - f->f_bufptr; + if (len == 0) + return (PyBytesObject *) + PyBytes_FromStringAndSize(NULL, skip); + bufptr = memchr(f->f_bufptr, '\n', len); + if (bufptr != NULL) { + bufptr++; /* Count the '\n' */ + len = bufptr - f->f_bufptr; + s = (PyBytesObject *) + PyBytes_FromStringAndSize(NULL, skip+len); + if (s == NULL) + return NULL; + memcpy(PyBytes_AS_STRING(s)+skip, f->f_bufptr, len); + f->f_bufptr = bufptr; + if (bufptr == f->f_bufend) + Util_DropReadAhead(f); + } else { + bufptr = f->f_bufptr; + buf = f->f_buf; + f->f_buf = NULL; /* Force new readahead buffer */ + s = Util_ReadAheadGetLineSkip(f, skip+len, + bufsize + (bufsize>>2)); + if (s == NULL) { + PyMem_Free(buf); + return NULL; + } + memcpy(PyBytes_AS_STRING(s)+skip, bufptr, len); + PyMem_Free(buf); + } + return s; } /* ===================================================================== */ @@ -402,83 +402,83 @@ static PyObject * BZ2File_read(BZ2FileObject *self, PyObject *args) { - long bytesrequested = -1; - size_t bytesread, buffersize, chunksize; - int bzerror; - PyObject *ret = NULL; - - if (!PyArg_ParseTuple(args, "|l:read", &bytesrequested)) - return NULL; - - ACQUIRE_LOCK(self); - switch (self->mode) { - case MODE_READ: - break; - case MODE_READ_EOF: - ret = PyBytes_FromStringAndSize("", 0); - goto cleanup; - case MODE_CLOSED: - PyErr_SetString(PyExc_ValueError, - "I/O operation on closed file"); - goto cleanup; - default: - PyErr_SetString(PyExc_IOError, - "file is not ready for reading"); - goto cleanup; - } - - if (bytesrequested < 0) - buffersize = Util_NewBufferSize((size_t)0); - else - buffersize = bytesrequested; - if (buffersize > INT_MAX) { - PyErr_SetString(PyExc_OverflowError, - "requested number of bytes is " - "more than a Python string can hold"); - goto cleanup; - } - ret = PyBytes_FromStringAndSize((char *)NULL, buffersize); - if (ret == NULL || buffersize == 0) - goto cleanup; - bytesread = 0; - - for (;;) { - Py_BEGIN_ALLOW_THREADS - chunksize = BZ2_bzRead(&bzerror, self->fp, - BUF(ret)+bytesread, - buffersize-bytesread); - self->pos += chunksize; - Py_END_ALLOW_THREADS - bytesread += chunksize; - if (bzerror == BZ_STREAM_END) { - self->size = self->pos; - self->mode = MODE_READ_EOF; - break; - } else if (bzerror != BZ_OK) { - Util_CatchBZ2Error(bzerror); - Py_DECREF(ret); - ret = NULL; - goto cleanup; - } - if (bytesrequested < 0) { - buffersize = Util_NewBufferSize(buffersize); - if (_PyBytes_Resize(&ret, buffersize) < 0) { - ret = NULL; - goto cleanup; - } - } else { - break; - } - } - if (bytesread != buffersize) { - if (_PyBytes_Resize(&ret, bytesread) < 0) { - ret = NULL; - } - } + long bytesrequested = -1; + size_t bytesread, buffersize, chunksize; + int bzerror; + PyObject *ret = NULL; + + if (!PyArg_ParseTuple(args, "|l:read", &bytesrequested)) + return NULL; + + ACQUIRE_LOCK(self); + switch (self->mode) { + case MODE_READ: + break; + case MODE_READ_EOF: + ret = PyBytes_FromStringAndSize("", 0); + goto cleanup; + case MODE_CLOSED: + PyErr_SetString(PyExc_ValueError, + "I/O operation on closed file"); + goto cleanup; + default: + PyErr_SetString(PyExc_IOError, + "file is not ready for reading"); + goto cleanup; + } + + if (bytesrequested < 0) + buffersize = Util_NewBufferSize((size_t)0); + else + buffersize = bytesrequested; + if (buffersize > INT_MAX) { + PyErr_SetString(PyExc_OverflowError, + "requested number of bytes is " + "more than a Python string can hold"); + goto cleanup; + } + ret = PyBytes_FromStringAndSize((char *)NULL, buffersize); + if (ret == NULL || buffersize == 0) + goto cleanup; + bytesread = 0; + + for (;;) { + Py_BEGIN_ALLOW_THREADS + chunksize = BZ2_bzRead(&bzerror, self->fp, + BUF(ret)+bytesread, + buffersize-bytesread); + self->pos += chunksize; + Py_END_ALLOW_THREADS + bytesread += chunksize; + if (bzerror == BZ_STREAM_END) { + self->size = self->pos; + self->mode = MODE_READ_EOF; + break; + } else if (bzerror != BZ_OK) { + Util_CatchBZ2Error(bzerror); + Py_DECREF(ret); + ret = NULL; + goto cleanup; + } + if (bytesrequested < 0) { + buffersize = Util_NewBufferSize(buffersize); + if (_PyBytes_Resize(&ret, buffersize) < 0) { + ret = NULL; + goto cleanup; + } + } else { + break; + } + } + if (bytesread != buffersize) { + if (_PyBytes_Resize(&ret, bytesread) < 0) { + ret = NULL; + } + } cleanup: - RELEASE_LOCK(self); - return ret; + RELEASE_LOCK(self); + return ret; } PyDoc_STRVAR(BZ2File_readline__doc__, @@ -493,37 +493,37 @@ static PyObject * BZ2File_readline(BZ2FileObject *self, PyObject *args) { - PyObject *ret = NULL; - int sizehint = -1; + PyObject *ret = NULL; + int sizehint = -1; - if (!PyArg_ParseTuple(args, "|i:readline", &sizehint)) - return NULL; + if (!PyArg_ParseTuple(args, "|i:readline", &sizehint)) + return NULL; - ACQUIRE_LOCK(self); - switch (self->mode) { - case MODE_READ: - break; - case MODE_READ_EOF: - ret = PyBytes_FromStringAndSize("", 0); - goto cleanup; - case MODE_CLOSED: - PyErr_SetString(PyExc_ValueError, - "I/O operation on closed file"); - goto cleanup; - default: - PyErr_SetString(PyExc_IOError, - "file is not ready for reading"); - goto cleanup; - } - - if (sizehint == 0) - ret = PyBytes_FromStringAndSize("", 0); - else - ret = Util_GetLine(self, (sizehint < 0) ? 0 : sizehint); + ACQUIRE_LOCK(self); + switch (self->mode) { + case MODE_READ: + break; + case MODE_READ_EOF: + ret = PyBytes_FromStringAndSize("", 0); + goto cleanup; + case MODE_CLOSED: + PyErr_SetString(PyExc_ValueError, + "I/O operation on closed file"); + goto cleanup; + default: + PyErr_SetString(PyExc_IOError, + "file is not ready for reading"); + goto cleanup; + } + + if (sizehint == 0) + ret = PyBytes_FromStringAndSize("", 0); + else + ret = Util_GetLine(self, (sizehint < 0) ? 0 : sizehint); cleanup: - RELEASE_LOCK(self); - return ret; + RELEASE_LOCK(self); + return ret; } PyDoc_STRVAR(BZ2File_readlines__doc__, @@ -538,150 +538,150 @@ static PyObject * BZ2File_readlines(BZ2FileObject *self, PyObject *args) { - long sizehint = 0; - PyObject *list = NULL; - PyObject *line; - char small_buffer[SMALLCHUNK]; - char *buffer = small_buffer; - size_t buffersize = SMALLCHUNK; - PyObject *big_buffer = NULL; - size_t nfilled = 0; - size_t nread; - size_t totalread = 0; - char *p, *q, *end; - int err; - int shortread = 0; - int bzerror; - - if (!PyArg_ParseTuple(args, "|l:readlines", &sizehint)) - return NULL; - - ACQUIRE_LOCK(self); - switch (self->mode) { - case MODE_READ: - break; - case MODE_READ_EOF: - list = PyList_New(0); - goto cleanup; - case MODE_CLOSED: - PyErr_SetString(PyExc_ValueError, - "I/O operation on closed file"); - goto cleanup; - default: - PyErr_SetString(PyExc_IOError, - "file is not ready for reading"); - goto cleanup; - } - - if ((list = PyList_New(0)) == NULL) - goto cleanup; - - for (;;) { - Py_BEGIN_ALLOW_THREADS - nread = BZ2_bzRead(&bzerror, self->fp, - buffer+nfilled, buffersize-nfilled); - self->pos += nread; - Py_END_ALLOW_THREADS - if (bzerror == BZ_STREAM_END) { - self->size = self->pos; - self->mode = MODE_READ_EOF; - if (nread == 0) { - sizehint = 0; - break; - } - shortread = 1; - } else if (bzerror != BZ_OK) { - Util_CatchBZ2Error(bzerror); - error: - Py_DECREF(list); - list = NULL; - goto cleanup; - } - totalread += nread; - p = memchr(buffer+nfilled, '\n', nread); - if (!shortread && p == NULL) { - /* Need a larger buffer to fit this line */ - nfilled += nread; - buffersize *= 2; - if (buffersize > INT_MAX) { - PyErr_SetString(PyExc_OverflowError, - "line is longer than a Python string can hold"); - goto error; - } - if (big_buffer == NULL) { - /* Create the big buffer */ - big_buffer = PyBytes_FromStringAndSize( - NULL, buffersize); - if (big_buffer == NULL) - goto error; - buffer = PyBytes_AS_STRING(big_buffer); - memcpy(buffer, small_buffer, nfilled); - } - else { - /* Grow the big buffer */ - if (_PyBytes_Resize(&big_buffer, buffersize) < 0){ - big_buffer = NULL; - goto error; - } - buffer = PyBytes_AS_STRING(big_buffer); - } - continue; - } - end = buffer+nfilled+nread; - q = buffer; - while (p != NULL) { - /* Process complete lines */ - p++; - line = PyBytes_FromStringAndSize(q, p-q); - if (line == NULL) - goto error; - err = PyList_Append(list, line); - Py_DECREF(line); - if (err != 0) - goto error; - q = p; - p = memchr(q, '\n', end-q); - } - /* Move the remaining incomplete line to the start */ - nfilled = end-q; - memmove(buffer, q, nfilled); - if (sizehint > 0) - if (totalread >= (size_t)sizehint) - break; - if (shortread) { - sizehint = 0; - break; - } - } - if (nfilled != 0) { - /* Partial last line */ - line = PyBytes_FromStringAndSize(buffer, nfilled); - if (line == NULL) - goto error; - if (sizehint > 0) { - /* Need to complete the last line */ - PyObject *rest = Util_GetLine(self, 0); - if (rest == NULL) { - Py_DECREF(line); - goto error; - } - PyBytes_Concat(&line, rest); - Py_DECREF(rest); - if (line == NULL) - goto error; - } - err = PyList_Append(list, line); - Py_DECREF(line); - if (err != 0) - goto error; - } + long sizehint = 0; + PyObject *list = NULL; + PyObject *line; + char small_buffer[SMALLCHUNK]; + char *buffer = small_buffer; + size_t buffersize = SMALLCHUNK; + PyObject *big_buffer = NULL; + size_t nfilled = 0; + size_t nread; + size_t totalread = 0; + char *p, *q, *end; + int err; + int shortread = 0; + int bzerror; + + if (!PyArg_ParseTuple(args, "|l:readlines", &sizehint)) + return NULL; + + ACQUIRE_LOCK(self); + switch (self->mode) { + case MODE_READ: + break; + case MODE_READ_EOF: + list = PyList_New(0); + goto cleanup; + case MODE_CLOSED: + PyErr_SetString(PyExc_ValueError, + "I/O operation on closed file"); + goto cleanup; + default: + PyErr_SetString(PyExc_IOError, + "file is not ready for reading"); + goto cleanup; + } + + if ((list = PyList_New(0)) == NULL) + goto cleanup; + + for (;;) { + Py_BEGIN_ALLOW_THREADS + nread = BZ2_bzRead(&bzerror, self->fp, + buffer+nfilled, buffersize-nfilled); + self->pos += nread; + Py_END_ALLOW_THREADS + if (bzerror == BZ_STREAM_END) { + self->size = self->pos; + self->mode = MODE_READ_EOF; + if (nread == 0) { + sizehint = 0; + break; + } + shortread = 1; + } else if (bzerror != BZ_OK) { + Util_CatchBZ2Error(bzerror); + error: + Py_DECREF(list); + list = NULL; + goto cleanup; + } + totalread += nread; + p = memchr(buffer+nfilled, '\n', nread); + if (!shortread && p == NULL) { + /* Need a larger buffer to fit this line */ + nfilled += nread; + buffersize *= 2; + if (buffersize > INT_MAX) { + PyErr_SetString(PyExc_OverflowError, + "line is longer than a Python string can hold"); + goto error; + } + if (big_buffer == NULL) { + /* Create the big buffer */ + big_buffer = PyBytes_FromStringAndSize( + NULL, buffersize); + if (big_buffer == NULL) + goto error; + buffer = PyBytes_AS_STRING(big_buffer); + memcpy(buffer, small_buffer, nfilled); + } + else { + /* Grow the big buffer */ + if (_PyBytes_Resize(&big_buffer, buffersize) < 0){ + big_buffer = NULL; + goto error; + } + buffer = PyBytes_AS_STRING(big_buffer); + } + continue; + } + end = buffer+nfilled+nread; + q = buffer; + while (p != NULL) { + /* Process complete lines */ + p++; + line = PyBytes_FromStringAndSize(q, p-q); + if (line == NULL) + goto error; + err = PyList_Append(list, line); + Py_DECREF(line); + if (err != 0) + goto error; + q = p; + p = memchr(q, '\n', end-q); + } + /* Move the remaining incomplete line to the start */ + nfilled = end-q; + memmove(buffer, q, nfilled); + if (sizehint > 0) + if (totalread >= (size_t)sizehint) + break; + if (shortread) { + sizehint = 0; + break; + } + } + if (nfilled != 0) { + /* Partial last line */ + line = PyBytes_FromStringAndSize(buffer, nfilled); + if (line == NULL) + goto error; + if (sizehint > 0) { + /* Need to complete the last line */ + PyObject *rest = Util_GetLine(self, 0); + if (rest == NULL) { + Py_DECREF(line); + goto error; + } + PyBytes_Concat(&line, rest); + Py_DECREF(rest); + if (line == NULL) + goto error; + } + err = PyList_Append(list, line); + Py_DECREF(line); + if (err != 0) + goto error; + } cleanup: - RELEASE_LOCK(self); - if (big_buffer) { - Py_DECREF(big_buffer); - } - return list; + RELEASE_LOCK(self); + if (big_buffer) { + Py_DECREF(big_buffer); + } + return list; } PyDoc_STRVAR(BZ2File_write__doc__, @@ -695,50 +695,50 @@ static PyObject * BZ2File_write(BZ2FileObject *self, PyObject *args) { - PyObject *ret = NULL; - Py_buffer pbuf; - char *buf; - int len; - int bzerror; - - if (!PyArg_ParseTuple(args, "y*:write", &pbuf)) - return NULL; - buf = pbuf.buf; - len = pbuf.len; - - ACQUIRE_LOCK(self); - switch (self->mode) { - case MODE_WRITE: - break; - - case MODE_CLOSED: - PyErr_SetString(PyExc_ValueError, - "I/O operation on closed file"); - goto cleanup; - - default: - PyErr_SetString(PyExc_IOError, - "file is not ready for writing"); - goto cleanup; - } - - Py_BEGIN_ALLOW_THREADS - BZ2_bzWrite (&bzerror, self->fp, buf, len); - self->pos += len; - Py_END_ALLOW_THREADS - - if (bzerror != BZ_OK) { - Util_CatchBZ2Error(bzerror); - goto cleanup; - } + PyObject *ret = NULL; + Py_buffer pbuf; + char *buf; + int len; + int bzerror; + + if (!PyArg_ParseTuple(args, "y*:write", &pbuf)) + return NULL; + buf = pbuf.buf; + len = pbuf.len; + + ACQUIRE_LOCK(self); + switch (self->mode) { + case MODE_WRITE: + break; + + case MODE_CLOSED: + PyErr_SetString(PyExc_ValueError, + "I/O operation on closed file"); + goto cleanup; + + default: + PyErr_SetString(PyExc_IOError, + "file is not ready for writing"); + goto cleanup; + } + + Py_BEGIN_ALLOW_THREADS + BZ2_bzWrite (&bzerror, self->fp, buf, len); + self->pos += len; + Py_END_ALLOW_THREADS + + if (bzerror != BZ_OK) { + Util_CatchBZ2Error(bzerror); + goto cleanup; + } - Py_INCREF(Py_None); - ret = Py_None; + Py_INCREF(Py_None); + ret = Py_None; cleanup: - PyBuffer_Release(&pbuf); - RELEASE_LOCK(self); - return ret; + PyBuffer_Release(&pbuf); + RELEASE_LOCK(self); + return ret; } PyDoc_STRVAR(BZ2File_writelines__doc__, @@ -754,122 +754,122 @@ BZ2File_writelines(BZ2FileObject *self, PyObject *seq) { #define CHUNKSIZE 1000 - PyObject *list = NULL; - PyObject *iter = NULL; - PyObject *ret = NULL; - PyObject *line; - int i, j, index, len, islist; - int bzerror; - - ACQUIRE_LOCK(self); - switch (self->mode) { - case MODE_WRITE: - break; - - case MODE_CLOSED: - PyErr_SetString(PyExc_ValueError, - "I/O operation on closed file"); - goto error; - - default: - PyErr_SetString(PyExc_IOError, - "file is not ready for writing"); - goto error; - } - - islist = PyList_Check(seq); - if (!islist) { - iter = PyObject_GetIter(seq); - if (iter == NULL) { - PyErr_SetString(PyExc_TypeError, - "writelines() requires an iterable argument"); - goto error; - } - list = PyList_New(CHUNKSIZE); - if (list == NULL) - goto error; - } - - /* Strategy: slurp CHUNKSIZE lines into a private list, - checking that they are all strings, then write that list - without holding the interpreter lock, then come back for more. */ - for (index = 0; ; index += CHUNKSIZE) { - if (islist) { - Py_XDECREF(list); - list = PyList_GetSlice(seq, index, index+CHUNKSIZE); - if (list == NULL) - goto error; - j = PyList_GET_SIZE(list); - } - else { - for (j = 0; j < CHUNKSIZE; j++) { - line = PyIter_Next(iter); - if (line == NULL) { - if (PyErr_Occurred()) - goto error; - break; - } - PyList_SetItem(list, j, line); - } - } - if (j == 0) - break; - - /* Check that all entries are indeed byte strings. If not, - apply the same rules as for file.write() and - convert the rets to strings. This is slow, but - seems to be the only way since all conversion APIs - could potentially execute Python code. */ - for (i = 0; i < j; i++) { - PyObject *v = PyList_GET_ITEM(list, i); - if (!PyBytes_Check(v)) { - const char *buffer; - Py_ssize_t len; - if (PyObject_AsCharBuffer(v, &buffer, &len)) { - PyErr_SetString(PyExc_TypeError, - "writelines() " - "argument must be " - "a sequence of " - "bytes objects"); - goto error; - } - line = PyBytes_FromStringAndSize(buffer, - len); - if (line == NULL) - goto error; - Py_DECREF(v); - PyList_SET_ITEM(list, i, line); - } - } - - /* Since we are releasing the global lock, the - following code may *not* execute Python code. */ - Py_BEGIN_ALLOW_THREADS - for (i = 0; i < j; i++) { - line = PyList_GET_ITEM(list, i); - len = PyBytes_GET_SIZE(line); - BZ2_bzWrite (&bzerror, self->fp, - PyBytes_AS_STRING(line), len); - if (bzerror != BZ_OK) { - Py_BLOCK_THREADS - Util_CatchBZ2Error(bzerror); - goto error; - } - } - Py_END_ALLOW_THREADS - - if (j < CHUNKSIZE) - break; - } + PyObject *list = NULL; + PyObject *iter = NULL; + PyObject *ret = NULL; + PyObject *line; + int i, j, index, len, islist; + int bzerror; + + ACQUIRE_LOCK(self); + switch (self->mode) { + case MODE_WRITE: + break; + + case MODE_CLOSED: + PyErr_SetString(PyExc_ValueError, + "I/O operation on closed file"); + goto error; + + default: + PyErr_SetString(PyExc_IOError, + "file is not ready for writing"); + goto error; + } + + islist = PyList_Check(seq); + if (!islist) { + iter = PyObject_GetIter(seq); + if (iter == NULL) { + PyErr_SetString(PyExc_TypeError, + "writelines() requires an iterable argument"); + goto error; + } + list = PyList_New(CHUNKSIZE); + if (list == NULL) + goto error; + } + + /* Strategy: slurp CHUNKSIZE lines into a private list, + checking that they are all strings, then write that list + without holding the interpreter lock, then come back for more. */ + for (index = 0; ; index += CHUNKSIZE) { + if (islist) { + Py_XDECREF(list); + list = PyList_GetSlice(seq, index, index+CHUNKSIZE); + if (list == NULL) + goto error; + j = PyList_GET_SIZE(list); + } + else { + for (j = 0; j < CHUNKSIZE; j++) { + line = PyIter_Next(iter); + if (line == NULL) { + if (PyErr_Occurred()) + goto error; + break; + } + PyList_SetItem(list, j, line); + } + } + if (j == 0) + break; + + /* Check that all entries are indeed byte strings. If not, + apply the same rules as for file.write() and + convert the rets to strings. This is slow, but + seems to be the only way since all conversion APIs + could potentially execute Python code. */ + for (i = 0; i < j; i++) { + PyObject *v = PyList_GET_ITEM(list, i); + if (!PyBytes_Check(v)) { + const char *buffer; + Py_ssize_t len; + if (PyObject_AsCharBuffer(v, &buffer, &len)) { + PyErr_SetString(PyExc_TypeError, + "writelines() " + "argument must be " + "a sequence of " + "bytes objects"); + goto error; + } + line = PyBytes_FromStringAndSize(buffer, + len); + if (line == NULL) + goto error; + Py_DECREF(v); + PyList_SET_ITEM(list, i, line); + } + } + + /* Since we are releasing the global lock, the + following code may *not* execute Python code. */ + Py_BEGIN_ALLOW_THREADS + for (i = 0; i < j; i++) { + line = PyList_GET_ITEM(list, i); + len = PyBytes_GET_SIZE(line); + BZ2_bzWrite (&bzerror, self->fp, + PyBytes_AS_STRING(line), len); + if (bzerror != BZ_OK) { + Py_BLOCK_THREADS + Util_CatchBZ2Error(bzerror); + goto error; + } + } + Py_END_ALLOW_THREADS + + if (j < CHUNKSIZE) + break; + } - Py_INCREF(Py_None); - ret = Py_None; + Py_INCREF(Py_None); + ret = Py_None; error: - RELEASE_LOCK(self); - Py_XDECREF(list); - Py_XDECREF(iter); - return ret; + RELEASE_LOCK(self); + Py_XDECREF(list); + Py_XDECREF(iter); + return ret; #undef CHUNKSIZE } @@ -889,135 +889,135 @@ static PyObject * BZ2File_seek(BZ2FileObject *self, PyObject *args) { - int where = 0; - PyObject *offobj; - Py_off_t offset; - char small_buffer[SMALLCHUNK]; - char *buffer = small_buffer; - size_t buffersize = SMALLCHUNK; - Py_off_t bytesread = 0; - size_t readsize; - int chunksize; - int bzerror; - PyObject *ret = NULL; + int where = 0; + PyObject *offobj; + Py_off_t offset; + char small_buffer[SMALLCHUNK]; + char *buffer = small_buffer; + size_t buffersize = SMALLCHUNK; + Py_off_t bytesread = 0; + size_t readsize; + int chunksize; + int bzerror; + PyObject *ret = NULL; - if (!PyArg_ParseTuple(args, "O|i:seek", &offobj, &where)) - return NULL; + if (!PyArg_ParseTuple(args, "O|i:seek", &offobj, &where)) + return NULL; #if !defined(HAVE_LARGEFILE_SUPPORT) - offset = PyLong_AsLong(offobj); + offset = PyLong_AsLong(offobj); #else - offset = PyLong_Check(offobj) ? - PyLong_AsLongLong(offobj) : PyLong_AsLong(offobj); + offset = PyLong_Check(offobj) ? + PyLong_AsLongLong(offobj) : PyLong_AsLong(offobj); #endif - if (PyErr_Occurred()) - return NULL; + if (PyErr_Occurred()) + return NULL; - ACQUIRE_LOCK(self); - Util_DropReadAhead(self); - switch (self->mode) { - case MODE_READ: - case MODE_READ_EOF: - break; - - case MODE_CLOSED: - PyErr_SetString(PyExc_ValueError, - "I/O operation on closed file"); - goto cleanup; - - default: - PyErr_SetString(PyExc_IOError, - "seek works only while reading"); - goto cleanup; - } - - if (where == 2) { - if (self->size == -1) { - assert(self->mode != MODE_READ_EOF); - for (;;) { - Py_BEGIN_ALLOW_THREADS - chunksize = BZ2_bzRead(&bzerror, self->fp, - buffer, buffersize); - self->pos += chunksize; - Py_END_ALLOW_THREADS - - bytesread += chunksize; - if (bzerror == BZ_STREAM_END) { - break; - } else if (bzerror != BZ_OK) { - Util_CatchBZ2Error(bzerror); - goto cleanup; - } - } - self->mode = MODE_READ_EOF; - self->size = self->pos; - bytesread = 0; - } - offset = self->size + offset; - } else if (where == 1) { - offset = self->pos + offset; - } - - /* Before getting here, offset must be the absolute position the file - * pointer should be set to. */ - - if (offset >= self->pos) { - /* we can move forward */ - offset -= self->pos; - } else { - /* we cannot move back, so rewind the stream */ - BZ2_bzReadClose(&bzerror, self->fp); - if (bzerror != BZ_OK) { - Util_CatchBZ2Error(bzerror); - goto cleanup; - } - rewind(self->rawfp); - self->pos = 0; - self->fp = BZ2_bzReadOpen(&bzerror, self->rawfp, - 0, 0, NULL, 0); - if (bzerror != BZ_OK) { - Util_CatchBZ2Error(bzerror); - goto cleanup; - } - self->mode = MODE_READ; - } - - if (offset <= 0 || self->mode == MODE_READ_EOF) - goto exit; - - /* Before getting here, offset must be set to the number of bytes - * to walk forward. */ - for (;;) { - if (offset-bytesread > buffersize) - readsize = buffersize; - else - /* offset might be wider that readsize, but the result - * of the subtraction is bound by buffersize (see the - * condition above). buffersize is 8192. */ - readsize = (size_t)(offset-bytesread); - Py_BEGIN_ALLOW_THREADS - chunksize = BZ2_bzRead(&bzerror, self->fp, buffer, readsize); - self->pos += chunksize; - Py_END_ALLOW_THREADS - bytesread += chunksize; - if (bzerror == BZ_STREAM_END) { - self->size = self->pos; - self->mode = MODE_READ_EOF; - break; - } else if (bzerror != BZ_OK) { - Util_CatchBZ2Error(bzerror); - goto cleanup; - } - if (bytesread == offset) - break; - } + ACQUIRE_LOCK(self); + Util_DropReadAhead(self); + switch (self->mode) { + case MODE_READ: + case MODE_READ_EOF: + break; + + case MODE_CLOSED: + PyErr_SetString(PyExc_ValueError, + "I/O operation on closed file"); + goto cleanup; + + default: + PyErr_SetString(PyExc_IOError, + "seek works only while reading"); + goto cleanup; + } + + if (where == 2) { + if (self->size == -1) { + assert(self->mode != MODE_READ_EOF); + for (;;) { + Py_BEGIN_ALLOW_THREADS + chunksize = BZ2_bzRead(&bzerror, self->fp, + buffer, buffersize); + self->pos += chunksize; + Py_END_ALLOW_THREADS + + bytesread += chunksize; + if (bzerror == BZ_STREAM_END) { + break; + } else if (bzerror != BZ_OK) { + Util_CatchBZ2Error(bzerror); + goto cleanup; + } + } + self->mode = MODE_READ_EOF; + self->size = self->pos; + bytesread = 0; + } + offset = self->size + offset; + } else if (where == 1) { + offset = self->pos + offset; + } + + /* Before getting here, offset must be the absolute position the file + * pointer should be set to. */ + + if (offset >= self->pos) { + /* we can move forward */ + offset -= self->pos; + } else { + /* we cannot move back, so rewind the stream */ + BZ2_bzReadClose(&bzerror, self->fp); + if (bzerror != BZ_OK) { + Util_CatchBZ2Error(bzerror); + goto cleanup; + } + rewind(self->rawfp); + self->pos = 0; + self->fp = BZ2_bzReadOpen(&bzerror, self->rawfp, + 0, 0, NULL, 0); + if (bzerror != BZ_OK) { + Util_CatchBZ2Error(bzerror); + goto cleanup; + } + self->mode = MODE_READ; + } + + if (offset <= 0 || self->mode == MODE_READ_EOF) + goto exit; + + /* Before getting here, offset must be set to the number of bytes + * to walk forward. */ + for (;;) { + if (offset-bytesread > buffersize) + readsize = buffersize; + else + /* offset might be wider that readsize, but the result + * of the subtraction is bound by buffersize (see the + * condition above). buffersize is 8192. */ + readsize = (size_t)(offset-bytesread); + Py_BEGIN_ALLOW_THREADS + chunksize = BZ2_bzRead(&bzerror, self->fp, buffer, readsize); + self->pos += chunksize; + Py_END_ALLOW_THREADS + bytesread += chunksize; + if (bzerror == BZ_STREAM_END) { + self->size = self->pos; + self->mode = MODE_READ_EOF; + break; + } else if (bzerror != BZ_OK) { + Util_CatchBZ2Error(bzerror); + goto cleanup; + } + if (bytesread == offset) + break; + } exit: - Py_INCREF(Py_None); - ret = Py_None; + Py_INCREF(Py_None); + ret = Py_None; cleanup: - RELEASE_LOCK(self); - return ret; + RELEASE_LOCK(self); + return ret; } PyDoc_STRVAR(BZ2File_tell__doc__, @@ -1029,22 +1029,22 @@ static PyObject * BZ2File_tell(BZ2FileObject *self, PyObject *args) { - PyObject *ret = NULL; + PyObject *ret = NULL; - if (self->mode == MODE_CLOSED) { - PyErr_SetString(PyExc_ValueError, - "I/O operation on closed file"); - goto cleanup; - } + if (self->mode == MODE_CLOSED) { + PyErr_SetString(PyExc_ValueError, + "I/O operation on closed file"); + goto cleanup; + } #if !defined(HAVE_LARGEFILE_SUPPORT) - ret = PyLong_FromLong(self->pos); + ret = PyLong_FromLong(self->pos); #else - ret = PyLong_FromLongLong(self->pos); + ret = PyLong_FromLongLong(self->pos); #endif cleanup: - return ret; + return ret; } PyDoc_STRVAR(BZ2File_close__doc__, @@ -1058,37 +1058,37 @@ static PyObject * BZ2File_close(BZ2FileObject *self) { - PyObject *ret = NULL; - int bzerror = BZ_OK; + PyObject *ret = NULL; + int bzerror = BZ_OK; - if (self->mode == MODE_CLOSED) { - Py_RETURN_NONE; - } - - ACQUIRE_LOCK(self); - switch (self->mode) { - case MODE_READ: - case MODE_READ_EOF: - BZ2_bzReadClose(&bzerror, self->fp); - break; - case MODE_WRITE: - BZ2_bzWriteClose(&bzerror, self->fp, - 0, NULL, NULL); - break; - } - self->mode = MODE_CLOSED; - fclose(self->rawfp); - self->rawfp = NULL; - if (bzerror == BZ_OK) { - Py_INCREF(Py_None); - ret = Py_None; - } - else { - Util_CatchBZ2Error(bzerror); - } + if (self->mode == MODE_CLOSED) { + Py_RETURN_NONE; + } + + ACQUIRE_LOCK(self); + switch (self->mode) { + case MODE_READ: + case MODE_READ_EOF: + BZ2_bzReadClose(&bzerror, self->fp); + break; + case MODE_WRITE: + BZ2_bzWriteClose(&bzerror, self->fp, + 0, NULL, NULL); + break; + } + self->mode = MODE_CLOSED; + fclose(self->rawfp); + self->rawfp = NULL; + if (bzerror == BZ_OK) { + Py_INCREF(Py_None); + ret = Py_None; + } + else { + Util_CatchBZ2Error(bzerror); + } - RELEASE_LOCK(self); - return ret; + RELEASE_LOCK(self); + return ret; } PyDoc_STRVAR(BZ2File_enter_doc, @@ -1097,13 +1097,13 @@ static PyObject * BZ2File_enter(BZ2FileObject *self) { - if (self->mode == MODE_CLOSED) { - PyErr_SetString(PyExc_ValueError, - "I/O operation on closed file"); - return NULL; - } - Py_INCREF(self); - return (PyObject *) self; + if (self->mode == MODE_CLOSED) { + PyErr_SetString(PyExc_ValueError, + "I/O operation on closed file"); + return NULL; + } + Py_INCREF(self); + return (PyObject *) self; } PyDoc_STRVAR(BZ2File_exit_doc, @@ -1112,29 +1112,29 @@ static PyObject * BZ2File_exit(BZ2FileObject *self, PyObject *args) { - PyObject *ret = PyObject_CallMethod((PyObject *) self, "close", NULL); - if (!ret) - /* If error occurred, pass through */ - return NULL; - Py_DECREF(ret); - Py_RETURN_NONE; + PyObject *ret = PyObject_CallMethod((PyObject *) self, "close", NULL); + if (!ret) + /* If error occurred, pass through */ + return NULL; + Py_DECREF(ret); + Py_RETURN_NONE; } static PyObject *BZ2File_getiter(BZ2FileObject *self); static PyMethodDef BZ2File_methods[] = { - {"read", (PyCFunction)BZ2File_read, METH_VARARGS, BZ2File_read__doc__}, - {"readline", (PyCFunction)BZ2File_readline, METH_VARARGS, BZ2File_readline__doc__}, - {"readlines", (PyCFunction)BZ2File_readlines, METH_VARARGS, BZ2File_readlines__doc__}, - {"write", (PyCFunction)BZ2File_write, METH_VARARGS, BZ2File_write__doc__}, - {"writelines", (PyCFunction)BZ2File_writelines, METH_O, BZ2File_writelines__doc__}, - {"seek", (PyCFunction)BZ2File_seek, METH_VARARGS, BZ2File_seek__doc__}, - {"tell", (PyCFunction)BZ2File_tell, METH_NOARGS, BZ2File_tell__doc__}, - {"close", (PyCFunction)BZ2File_close, METH_NOARGS, BZ2File_close__doc__}, - {"__enter__", (PyCFunction)BZ2File_enter, METH_NOARGS, BZ2File_enter_doc}, - {"__exit__", (PyCFunction)BZ2File_exit, METH_VARARGS, BZ2File_exit_doc}, - {NULL, NULL} /* sentinel */ + {"read", (PyCFunction)BZ2File_read, METH_VARARGS, BZ2File_read__doc__}, + {"readline", (PyCFunction)BZ2File_readline, METH_VARARGS, BZ2File_readline__doc__}, + {"readlines", (PyCFunction)BZ2File_readlines, METH_VARARGS, BZ2File_readlines__doc__}, + {"write", (PyCFunction)BZ2File_write, METH_VARARGS, BZ2File_write__doc__}, + {"writelines", (PyCFunction)BZ2File_writelines, METH_O, BZ2File_writelines__doc__}, + {"seek", (PyCFunction)BZ2File_seek, METH_VARARGS, BZ2File_seek__doc__}, + {"tell", (PyCFunction)BZ2File_tell, METH_NOARGS, BZ2File_tell__doc__}, + {"close", (PyCFunction)BZ2File_close, METH_NOARGS, BZ2File_close__doc__}, + {"__enter__", (PyCFunction)BZ2File_enter, METH_NOARGS, BZ2File_enter_doc}, + {"__exit__", (PyCFunction)BZ2File_exit, METH_VARARGS, BZ2File_exit_doc}, + {NULL, NULL} /* sentinel */ }; @@ -1144,13 +1144,13 @@ static PyObject * BZ2File_get_closed(BZ2FileObject *self, void *closure) { - return PyLong_FromLong(self->mode == MODE_CLOSED); + return PyLong_FromLong(self->mode == MODE_CLOSED); } static PyGetSetDef BZ2File_getset[] = { - {"closed", (getter)BZ2File_get_closed, NULL, - "True if the file is closed"}, - {NULL} /* Sentinel */ + {"closed", (getter)BZ2File_get_closed, NULL, + "True if the file is closed"}, + {NULL} /* Sentinel */ }; @@ -1160,151 +1160,151 @@ static int BZ2File_init(BZ2FileObject *self, PyObject *args, PyObject *kwargs) { - static char *kwlist[] = {"filename", "mode", "buffering", - "compresslevel", 0}; - PyObject *name_obj = NULL; - char *name; - char *mode = "r"; - int buffering = -1; - int compresslevel = 9; - int bzerror; - int mode_char = 0; - - self->size = -1; - - if (!PyArg_ParseTupleAndKeywords(args, kwargs, "O&|sii:BZ2File", - kwlist, PyUnicode_FSConverter, &name_obj, - &mode, &buffering, - &compresslevel)) - return -1; - - if (PyBytes_Check(name_obj)) - name = PyBytes_AsString(name_obj); - else - name = PyByteArray_AsString(name_obj); - if (compresslevel < 1 || compresslevel > 9) { - PyErr_SetString(PyExc_ValueError, - "compresslevel must be between 1 and 9"); - Py_DECREF(name_obj); - return -1; - } - - for (;;) { - int error = 0; - switch (*mode) { - case 'r': - case 'w': - if (mode_char) - error = 1; - mode_char = *mode; - break; - - case 'b': - break; - - default: - error = 1; - break; - } - if (error) { - PyErr_Format(PyExc_ValueError, - "invalid mode char %c", *mode); - Py_DECREF(name_obj); - return -1; - } - mode++; - if (*mode == '\0') - break; - } - - if (mode_char == 0) { - mode_char = 'r'; - } - - mode = (mode_char == 'r') ? "rb" : "wb"; - - self->rawfp = fopen(name, mode); - Py_DECREF(name_obj); - if (self->rawfp == NULL) { - PyErr_SetFromErrno(PyExc_IOError); - return -1; - } - /* XXX Ignore buffering */ + static char *kwlist[] = {"filename", "mode", "buffering", + "compresslevel", 0}; + PyObject *name_obj = NULL; + char *name; + char *mode = "r"; + int buffering = -1; + int compresslevel = 9; + int bzerror; + int mode_char = 0; + + self->size = -1; + + if (!PyArg_ParseTupleAndKeywords(args, kwargs, "O&|sii:BZ2File", + kwlist, PyUnicode_FSConverter, &name_obj, + &mode, &buffering, + &compresslevel)) + return -1; + + if (PyBytes_Check(name_obj)) + name = PyBytes_AsString(name_obj); + else + name = PyByteArray_AsString(name_obj); + if (compresslevel < 1 || compresslevel > 9) { + PyErr_SetString(PyExc_ValueError, + "compresslevel must be between 1 and 9"); + Py_DECREF(name_obj); + return -1; + } + + for (;;) { + int error = 0; + switch (*mode) { + case 'r': + case 'w': + if (mode_char) + error = 1; + mode_char = *mode; + break; + + case 'b': + break; + + default: + error = 1; + break; + } + if (error) { + PyErr_Format(PyExc_ValueError, + "invalid mode char %c", *mode); + Py_DECREF(name_obj); + return -1; + } + mode++; + if (*mode == '\0') + break; + } + + if (mode_char == 0) { + mode_char = 'r'; + } + + mode = (mode_char == 'r') ? "rb" : "wb"; + + self->rawfp = fopen(name, mode); + Py_DECREF(name_obj); + if (self->rawfp == NULL) { + PyErr_SetFromErrno(PyExc_IOError); + return -1; + } + /* XXX Ignore buffering */ - /* From now on, we have stuff to dealloc, so jump to error label - * instead of returning */ + /* From now on, we have stuff to dealloc, so jump to error label + * instead of returning */ #ifdef WITH_THREAD - self->lock = PyThread_allocate_lock(); - if (!self->lock) { - PyErr_SetString(PyExc_MemoryError, "unable to allocate lock"); - goto error; - } + self->lock = PyThread_allocate_lock(); + if (!self->lock) { + PyErr_SetString(PyExc_MemoryError, "unable to allocate lock"); + goto error; + } #endif - if (mode_char == 'r') - self->fp = BZ2_bzReadOpen(&bzerror, self->rawfp, - 0, 0, NULL, 0); - else - self->fp = BZ2_bzWriteOpen(&bzerror, self->rawfp, - compresslevel, 0, 0); - - if (bzerror != BZ_OK) { - Util_CatchBZ2Error(bzerror); - goto error; - } + if (mode_char == 'r') + self->fp = BZ2_bzReadOpen(&bzerror, self->rawfp, + 0, 0, NULL, 0); + else + self->fp = BZ2_bzWriteOpen(&bzerror, self->rawfp, + compresslevel, 0, 0); + + if (bzerror != BZ_OK) { + Util_CatchBZ2Error(bzerror); + goto error; + } - self->mode = (mode_char == 'r') ? MODE_READ : MODE_WRITE; + self->mode = (mode_char == 'r') ? MODE_READ : MODE_WRITE; - return 0; + return 0; error: - fclose(self->rawfp); - self->rawfp = NULL; + fclose(self->rawfp); + self->rawfp = NULL; #ifdef WITH_THREAD - if (self->lock) { - PyThread_free_lock(self->lock); - self->lock = NULL; - } + if (self->lock) { + PyThread_free_lock(self->lock); + self->lock = NULL; + } #endif - return -1; + return -1; } static void BZ2File_dealloc(BZ2FileObject *self) { - int bzerror; + int bzerror; #ifdef WITH_THREAD - if (self->lock) - PyThread_free_lock(self->lock); + if (self->lock) + PyThread_free_lock(self->lock); #endif - switch (self->mode) { - case MODE_READ: - case MODE_READ_EOF: - BZ2_bzReadClose(&bzerror, self->fp); - break; - case MODE_WRITE: - BZ2_bzWriteClose(&bzerror, self->fp, - 0, NULL, NULL); - break; - } - Util_DropReadAhead(self); - if (self->rawfp != NULL) - fclose(self->rawfp); - Py_TYPE(self)->tp_free((PyObject *)self); + switch (self->mode) { + case MODE_READ: + case MODE_READ_EOF: + BZ2_bzReadClose(&bzerror, self->fp); + break; + case MODE_WRITE: + BZ2_bzWriteClose(&bzerror, self->fp, + 0, NULL, NULL); + break; + } + Util_DropReadAhead(self); + if (self->rawfp != NULL) + fclose(self->rawfp); + Py_TYPE(self)->tp_free((PyObject *)self); } /* This is a hacked version of Python's fileobject.c:file_getiter(). */ static PyObject * BZ2File_getiter(BZ2FileObject *self) { - if (self->mode == MODE_CLOSED) { - PyErr_SetString(PyExc_ValueError, - "I/O operation on closed file"); - return NULL; - } - Py_INCREF((PyObject*)self); - return (PyObject *)self; + if (self->mode == MODE_CLOSED) { + PyErr_SetString(PyExc_ValueError, + "I/O operation on closed file"); + return NULL; + } + Py_INCREF((PyObject*)self); + return (PyObject *)self; } /* This is a hacked version of Python's fileobject.c:file_iternext(). */ @@ -1312,21 +1312,21 @@ static PyObject * BZ2File_iternext(BZ2FileObject *self) { - PyBytesObject* ret; - ACQUIRE_LOCK(self); - if (self->mode == MODE_CLOSED) { - RELEASE_LOCK(self); - PyErr_SetString(PyExc_ValueError, - "I/O operation on closed file"); - return NULL; - } - ret = Util_ReadAheadGetLineSkip(self, 0, READAHEAD_BUFSIZE); - RELEASE_LOCK(self); - if (ret == NULL || PyBytes_GET_SIZE(ret) == 0) { - Py_XDECREF(ret); - return NULL; - } - return (PyObject *)ret; + PyBytesObject* ret; + ACQUIRE_LOCK(self); + if (self->mode == MODE_CLOSED) { + RELEASE_LOCK(self); + PyErr_SetString(PyExc_ValueError, + "I/O operation on closed file"); + return NULL; + } + ret = Util_ReadAheadGetLineSkip(self, 0, READAHEAD_BUFSIZE); + RELEASE_LOCK(self); + if (ret == NULL || PyBytes_GET_SIZE(ret) == 0) { + Py_XDECREF(ret); + return NULL; + } + return (PyObject *)ret; } /* ===================================================================== */ @@ -1345,46 +1345,46 @@ "); static PyTypeObject BZ2File_Type = { - PyVarObject_HEAD_INIT(NULL, 0) - "bz2.BZ2File", /*tp_name*/ - sizeof(BZ2FileObject), /*tp_basicsize*/ - 0, /*tp_itemsize*/ - (destructor)BZ2File_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*/ - PyObject_GenericSetAttr,/*tp_setattro*/ - 0, /*tp_as_buffer*/ - Py_TPFLAGS_DEFAULT|Py_TPFLAGS_BASETYPE, /*tp_flags*/ - BZ2File__doc__, /*tp_doc*/ - 0, /*tp_traverse*/ - 0, /*tp_clear*/ - 0, /*tp_richcompare*/ - 0, /*tp_weaklistoffset*/ - (getiterfunc)BZ2File_getiter, /*tp_iter*/ - (iternextfunc)BZ2File_iternext, /*tp_iternext*/ - BZ2File_methods, /*tp_methods*/ - 0, /*tp_members*/ - BZ2File_getset, /*tp_getset*/ - 0, /*tp_base*/ - 0, /*tp_dict*/ - 0, /*tp_descr_get*/ - 0, /*tp_descr_set*/ - 0, /*tp_dictoffset*/ - (initproc)BZ2File_init, /*tp_init*/ - PyType_GenericAlloc, /*tp_alloc*/ - PyType_GenericNew, /*tp_new*/ - PyObject_Free, /*tp_free*/ - 0, /*tp_is_gc*/ + PyVarObject_HEAD_INIT(NULL, 0) + "bz2.BZ2File", /*tp_name*/ + sizeof(BZ2FileObject), /*tp_basicsize*/ + 0, /*tp_itemsize*/ + (destructor)BZ2File_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*/ + PyObject_GenericSetAttr,/*tp_setattro*/ + 0, /*tp_as_buffer*/ + Py_TPFLAGS_DEFAULT|Py_TPFLAGS_BASETYPE, /*tp_flags*/ + BZ2File__doc__, /*tp_doc*/ + 0, /*tp_traverse*/ + 0, /*tp_clear*/ + 0, /*tp_richcompare*/ + 0, /*tp_weaklistoffset*/ + (getiterfunc)BZ2File_getiter, /*tp_iter*/ + (iternextfunc)BZ2File_iternext, /*tp_iternext*/ + BZ2File_methods, /*tp_methods*/ + 0, /*tp_members*/ + BZ2File_getset, /*tp_getset*/ + 0, /*tp_base*/ + 0, /*tp_dict*/ + 0, /*tp_descr_get*/ + 0, /*tp_descr_set*/ + 0, /*tp_dictoffset*/ + (initproc)BZ2File_init, /*tp_init*/ + PyType_GenericAlloc, /*tp_alloc*/ + PyType_GenericNew, /*tp_new*/ + PyObject_Free, /*tp_free*/ + 0, /*tp_is_gc*/ }; @@ -1403,78 +1403,78 @@ static PyObject * BZ2Comp_compress(BZ2CompObject *self, PyObject *args) { - Py_buffer pdata; - char *data; - int datasize; - int bufsize = SMALLCHUNK; - PY_LONG_LONG totalout; - PyObject *ret = NULL; - bz_stream *bzs = &self->bzs; - int bzerror; - - if (!PyArg_ParseTuple(args, "y*:compress", &pdata)) - return NULL; - data = pdata.buf; - datasize = pdata.len; - - if (datasize == 0) { - PyBuffer_Release(&pdata); - return PyBytes_FromStringAndSize("", 0); - } - - ACQUIRE_LOCK(self); - if (!self->running) { - PyErr_SetString(PyExc_ValueError, - "this object was already flushed"); - goto error; - } - - ret = PyBytes_FromStringAndSize(NULL, bufsize); - if (!ret) - goto error; - - bzs->next_in = data; - bzs->avail_in = datasize; - bzs->next_out = BUF(ret); - bzs->avail_out = bufsize; - - totalout = BZS_TOTAL_OUT(bzs); - - for (;;) { - Py_BEGIN_ALLOW_THREADS - bzerror = BZ2_bzCompress(bzs, BZ_RUN); - Py_END_ALLOW_THREADS - if (bzerror != BZ_RUN_OK) { - Util_CatchBZ2Error(bzerror); - goto error; - } - if (bzs->avail_in == 0) - break; /* no more input data */ - if (bzs->avail_out == 0) { - bufsize = Util_NewBufferSize(bufsize); - if (_PyBytes_Resize(&ret, bufsize) < 0) { - BZ2_bzCompressEnd(bzs); - goto error; - } - bzs->next_out = BUF(ret) + (BZS_TOTAL_OUT(bzs) - - totalout); - bzs->avail_out = bufsize - (bzs->next_out - BUF(ret)); - } - } - - if (_PyBytes_Resize(&ret, - (Py_ssize_t)(BZS_TOTAL_OUT(bzs) - totalout)) < 0) - goto error; - - RELEASE_LOCK(self); - PyBuffer_Release(&pdata); - return ret; + Py_buffer pdata; + char *data; + int datasize; + int bufsize = SMALLCHUNK; + PY_LONG_LONG totalout; + PyObject *ret = NULL; + bz_stream *bzs = &self->bzs; + int bzerror; + + if (!PyArg_ParseTuple(args, "y*:compress", &pdata)) + return NULL; + data = pdata.buf; + datasize = pdata.len; + + if (datasize == 0) { + PyBuffer_Release(&pdata); + return PyBytes_FromStringAndSize("", 0); + } + + ACQUIRE_LOCK(self); + if (!self->running) { + PyErr_SetString(PyExc_ValueError, + "this object was already flushed"); + goto error; + } + + ret = PyBytes_FromStringAndSize(NULL, bufsize); + if (!ret) + goto error; + + bzs->next_in = data; + bzs->avail_in = datasize; + bzs->next_out = BUF(ret); + bzs->avail_out = bufsize; + + totalout = BZS_TOTAL_OUT(bzs); + + for (;;) { + Py_BEGIN_ALLOW_THREADS + bzerror = BZ2_bzCompress(bzs, BZ_RUN); + Py_END_ALLOW_THREADS + if (bzerror != BZ_RUN_OK) { + Util_CatchBZ2Error(bzerror); + goto error; + } + if (bzs->avail_in == 0) + break; /* no more input data */ + if (bzs->avail_out == 0) { + bufsize = Util_NewBufferSize(bufsize); + if (_PyBytes_Resize(&ret, bufsize) < 0) { + BZ2_bzCompressEnd(bzs); + goto error; + } + bzs->next_out = BUF(ret) + (BZS_TOTAL_OUT(bzs) + - totalout); + bzs->avail_out = bufsize - (bzs->next_out - BUF(ret)); + } + } + + if (_PyBytes_Resize(&ret, + (Py_ssize_t)(BZS_TOTAL_OUT(bzs) - totalout)) < 0) + goto error; + + RELEASE_LOCK(self); + PyBuffer_Release(&pdata); + return ret; error: - RELEASE_LOCK(self); - PyBuffer_Release(&pdata); - Py_XDECREF(ret); - return NULL; + RELEASE_LOCK(self); + PyBuffer_Release(&pdata); + Py_XDECREF(ret); + return NULL; } PyDoc_STRVAR(BZ2Comp_flush__doc__, @@ -1487,71 +1487,71 @@ static PyObject * BZ2Comp_flush(BZ2CompObject *self) { - int bufsize = SMALLCHUNK; - PyObject *ret = NULL; - bz_stream *bzs = &self->bzs; - PY_LONG_LONG totalout; - int bzerror; - - ACQUIRE_LOCK(self); - if (!self->running) { - PyErr_SetString(PyExc_ValueError, "object was already " - "flushed"); - goto error; - } - self->running = 0; - - ret = PyBytes_FromStringAndSize(NULL, bufsize); - if (!ret) - goto error; - - bzs->next_out = BUF(ret); - bzs->avail_out = bufsize; - - totalout = BZS_TOTAL_OUT(bzs); - - for (;;) { - Py_BEGIN_ALLOW_THREADS - bzerror = BZ2_bzCompress(bzs, BZ_FINISH); - Py_END_ALLOW_THREADS - if (bzerror == BZ_STREAM_END) { - break; - } else if (bzerror != BZ_FINISH_OK) { - Util_CatchBZ2Error(bzerror); - goto error; - } - if (bzs->avail_out == 0) { - bufsize = Util_NewBufferSize(bufsize); - if (_PyBytes_Resize(&ret, bufsize) < 0) - goto error; - bzs->next_out = BUF(ret); - bzs->next_out = BUF(ret) + (BZS_TOTAL_OUT(bzs) - - totalout); - bzs->avail_out = bufsize - (bzs->next_out - BUF(ret)); - } - } - - if (bzs->avail_out != 0) { - if (_PyBytes_Resize(&ret, - (Py_ssize_t)(BZS_TOTAL_OUT(bzs) - totalout)) < 0) - goto error; - } + int bufsize = SMALLCHUNK; + PyObject *ret = NULL; + bz_stream *bzs = &self->bzs; + PY_LONG_LONG totalout; + int bzerror; + + ACQUIRE_LOCK(self); + if (!self->running) { + PyErr_SetString(PyExc_ValueError, "object was already " + "flushed"); + goto error; + } + self->running = 0; + + ret = PyBytes_FromStringAndSize(NULL, bufsize); + if (!ret) + goto error; + + bzs->next_out = BUF(ret); + bzs->avail_out = bufsize; + + totalout = BZS_TOTAL_OUT(bzs); + + for (;;) { + Py_BEGIN_ALLOW_THREADS + bzerror = BZ2_bzCompress(bzs, BZ_FINISH); + Py_END_ALLOW_THREADS + if (bzerror == BZ_STREAM_END) { + break; + } else if (bzerror != BZ_FINISH_OK) { + Util_CatchBZ2Error(bzerror); + goto error; + } + if (bzs->avail_out == 0) { + bufsize = Util_NewBufferSize(bufsize); + if (_PyBytes_Resize(&ret, bufsize) < 0) + goto error; + bzs->next_out = BUF(ret); + bzs->next_out = BUF(ret) + (BZS_TOTAL_OUT(bzs) + - totalout); + bzs->avail_out = bufsize - (bzs->next_out - BUF(ret)); + } + } + + if (bzs->avail_out != 0) { + if (_PyBytes_Resize(&ret, + (Py_ssize_t)(BZS_TOTAL_OUT(bzs) - totalout)) < 0) + goto error; + } - RELEASE_LOCK(self); - return ret; + RELEASE_LOCK(self); + return ret; error: - RELEASE_LOCK(self); - Py_XDECREF(ret); - return NULL; + RELEASE_LOCK(self); + Py_XDECREF(ret); + return NULL; } static PyMethodDef BZ2Comp_methods[] = { - {"compress", (PyCFunction)BZ2Comp_compress, METH_VARARGS, - BZ2Comp_compress__doc__}, - {"flush", (PyCFunction)BZ2Comp_flush, METH_NOARGS, - BZ2Comp_flush__doc__}, - {NULL, NULL} /* sentinel */ + {"compress", (PyCFunction)BZ2Comp_compress, METH_VARARGS, + BZ2Comp_compress__doc__}, + {"flush", (PyCFunction)BZ2Comp_flush, METH_NOARGS, + BZ2Comp_flush__doc__}, + {NULL, NULL} /* sentinel */ }; @@ -1561,57 +1561,57 @@ static int BZ2Comp_init(BZ2CompObject *self, PyObject *args, PyObject *kwargs) { - int compresslevel = 9; - int bzerror; - static char *kwlist[] = {"compresslevel", 0}; - - if (!PyArg_ParseTupleAndKeywords(args, kwargs, "|i:BZ2Compressor", - kwlist, &compresslevel)) - return -1; - - if (compresslevel < 1 || compresslevel > 9) { - PyErr_SetString(PyExc_ValueError, - "compresslevel must be between 1 and 9"); - goto error; - } + int compresslevel = 9; + int bzerror; + static char *kwlist[] = {"compresslevel", 0}; + + if (!PyArg_ParseTupleAndKeywords(args, kwargs, "|i:BZ2Compressor", + kwlist, &compresslevel)) + return -1; + + if (compresslevel < 1 || compresslevel > 9) { + PyErr_SetString(PyExc_ValueError, + "compresslevel must be between 1 and 9"); + goto error; + } #ifdef WITH_THREAD - self->lock = PyThread_allocate_lock(); - if (!self->lock) { - PyErr_SetString(PyExc_MemoryError, "unable to allocate lock"); - goto error; - } + self->lock = PyThread_allocate_lock(); + if (!self->lock) { + PyErr_SetString(PyExc_MemoryError, "unable to allocate lock"); + goto error; + } #endif - memset(&self->bzs, 0, sizeof(bz_stream)); - bzerror = BZ2_bzCompressInit(&self->bzs, compresslevel, 0, 0); - if (bzerror != BZ_OK) { - Util_CatchBZ2Error(bzerror); - goto error; - } + memset(&self->bzs, 0, sizeof(bz_stream)); + bzerror = BZ2_bzCompressInit(&self->bzs, compresslevel, 0, 0); + if (bzerror != BZ_OK) { + Util_CatchBZ2Error(bzerror); + goto error; + } - self->running = 1; + self->running = 1; - return 0; + return 0; error: #ifdef WITH_THREAD - if (self->lock) { - PyThread_free_lock(self->lock); - self->lock = NULL; - } + if (self->lock) { + PyThread_free_lock(self->lock); + self->lock = NULL; + } #endif - return -1; + return -1; } static void BZ2Comp_dealloc(BZ2CompObject *self) { #ifdef WITH_THREAD - if (self->lock) - PyThread_free_lock(self->lock); + if (self->lock) + PyThread_free_lock(self->lock); #endif - BZ2_bzCompressEnd(&self->bzs); - Py_TYPE(self)->tp_free((PyObject *)self); + BZ2_bzCompressEnd(&self->bzs); + Py_TYPE(self)->tp_free((PyObject *)self); } @@ -1628,46 +1628,46 @@ "); static PyTypeObject BZ2Comp_Type = { - PyVarObject_HEAD_INIT(NULL, 0) - "bz2.BZ2Compressor", /*tp_name*/ - sizeof(BZ2CompObject), /*tp_basicsize*/ - 0, /*tp_itemsize*/ - (destructor)BZ2Comp_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*/ - PyObject_GenericSetAttr,/*tp_setattro*/ - 0, /*tp_as_buffer*/ - Py_TPFLAGS_DEFAULT|Py_TPFLAGS_BASETYPE, /*tp_flags*/ - BZ2Comp__doc__, /*tp_doc*/ - 0, /*tp_traverse*/ - 0, /*tp_clear*/ - 0, /*tp_richcompare*/ - 0, /*tp_weaklistoffset*/ - 0, /*tp_iter*/ - 0, /*tp_iternext*/ - BZ2Comp_methods, /*tp_methods*/ - 0, /*tp_members*/ - 0, /*tp_getset*/ - 0, /*tp_base*/ - 0, /*tp_dict*/ - 0, /*tp_descr_get*/ - 0, /*tp_descr_set*/ - 0, /*tp_dictoffset*/ - (initproc)BZ2Comp_init, /*tp_init*/ - PyType_GenericAlloc, /*tp_alloc*/ - PyType_GenericNew, /*tp_new*/ - PyObject_Free, /*tp_free*/ - 0, /*tp_is_gc*/ + PyVarObject_HEAD_INIT(NULL, 0) + "bz2.BZ2Compressor", /*tp_name*/ + sizeof(BZ2CompObject), /*tp_basicsize*/ + 0, /*tp_itemsize*/ + (destructor)BZ2Comp_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*/ + PyObject_GenericSetAttr,/*tp_setattro*/ + 0, /*tp_as_buffer*/ + Py_TPFLAGS_DEFAULT|Py_TPFLAGS_BASETYPE, /*tp_flags*/ + BZ2Comp__doc__, /*tp_doc*/ + 0, /*tp_traverse*/ + 0, /*tp_clear*/ + 0, /*tp_richcompare*/ + 0, /*tp_weaklistoffset*/ + 0, /*tp_iter*/ + 0, /*tp_iternext*/ + BZ2Comp_methods, /*tp_methods*/ + 0, /*tp_members*/ + 0, /*tp_getset*/ + 0, /*tp_base*/ + 0, /*tp_dict*/ + 0, /*tp_descr_get*/ + 0, /*tp_descr_set*/ + 0, /*tp_dictoffset*/ + (initproc)BZ2Comp_init, /*tp_init*/ + PyType_GenericAlloc, /*tp_alloc*/ + PyType_GenericNew, /*tp_new*/ + PyObject_Free, /*tp_free*/ + 0, /*tp_is_gc*/ }; @@ -1678,8 +1678,8 @@ #define OFF(x) offsetof(BZ2DecompObject, x) static PyMemberDef BZ2Decomp_members[] = { - {"unused_data", T_OBJECT, OFF(unused_data), READONLY}, - {NULL} /* Sentinel */ + {"unused_data", T_OBJECT, OFF(unused_data), READONLY}, + {NULL} /* Sentinel */ }; @@ -1699,91 +1699,91 @@ static PyObject * BZ2Decomp_decompress(BZ2DecompObject *self, PyObject *args) { - Py_buffer pdata; - char *data; - int datasize; - int bufsize = SMALLCHUNK; - PY_LONG_LONG totalout; - PyObject *ret = NULL; - bz_stream *bzs = &self->bzs; - int bzerror; - - if (!PyArg_ParseTuple(args, "y*:decompress", &pdata)) - return NULL; - data = pdata.buf; - datasize = pdata.len; - - ACQUIRE_LOCK(self); - if (!self->running) { - PyErr_SetString(PyExc_EOFError, "end of stream was " - "already found"); - goto error; - } - - ret = PyBytes_FromStringAndSize(NULL, bufsize); - if (!ret) - goto error; - - bzs->next_in = data; - bzs->avail_in = datasize; - bzs->next_out = BUF(ret); - bzs->avail_out = bufsize; - - totalout = BZS_TOTAL_OUT(bzs); - - for (;;) { - Py_BEGIN_ALLOW_THREADS - bzerror = BZ2_bzDecompress(bzs); - Py_END_ALLOW_THREADS - if (bzerror == BZ_STREAM_END) { - if (bzs->avail_in != 0) { - Py_DECREF(self->unused_data); - self->unused_data = - PyBytes_FromStringAndSize(bzs->next_in, - bzs->avail_in); - } - self->running = 0; - break; - } - if (bzerror != BZ_OK) { - Util_CatchBZ2Error(bzerror); - goto error; - } - if (bzs->avail_in == 0) - break; /* no more input data */ - if (bzs->avail_out == 0) { - bufsize = Util_NewBufferSize(bufsize); - if (_PyBytes_Resize(&ret, bufsize) < 0) { - BZ2_bzDecompressEnd(bzs); - goto error; - } - bzs->next_out = BUF(ret); - bzs->next_out = BUF(ret) + (BZS_TOTAL_OUT(bzs) - - totalout); - bzs->avail_out = bufsize - (bzs->next_out - BUF(ret)); - } - } - - if (bzs->avail_out != 0) { - if (_PyBytes_Resize(&ret, - (Py_ssize_t)(BZS_TOTAL_OUT(bzs) - totalout)) < 0) - goto error; - } - - RELEASE_LOCK(self); - PyBuffer_Release(&pdata); - return ret; + Py_buffer pdata; + char *data; + int datasize; + int bufsize = SMALLCHUNK; + PY_LONG_LONG totalout; + PyObject *ret = NULL; + bz_stream *bzs = &self->bzs; + int bzerror; + + if (!PyArg_ParseTuple(args, "y*:decompress", &pdata)) + return NULL; + data = pdata.buf; + datasize = pdata.len; + + ACQUIRE_LOCK(self); + if (!self->running) { + PyErr_SetString(PyExc_EOFError, "end of stream was " + "already found"); + goto error; + } + + ret = PyBytes_FromStringAndSize(NULL, bufsize); + if (!ret) + goto error; + + bzs->next_in = data; + bzs->avail_in = datasize; + bzs->next_out = BUF(ret); + bzs->avail_out = bufsize; + + totalout = BZS_TOTAL_OUT(bzs); + + for (;;) { + Py_BEGIN_ALLOW_THREADS + bzerror = BZ2_bzDecompress(bzs); + Py_END_ALLOW_THREADS + if (bzerror == BZ_STREAM_END) { + if (bzs->avail_in != 0) { + Py_DECREF(self->unused_data); + self->unused_data = + PyBytes_FromStringAndSize(bzs->next_in, + bzs->avail_in); + } + self->running = 0; + break; + } + if (bzerror != BZ_OK) { + Util_CatchBZ2Error(bzerror); + goto error; + } + if (bzs->avail_in == 0) + break; /* no more input data */ + if (bzs->avail_out == 0) { + bufsize = Util_NewBufferSize(bufsize); + if (_PyBytes_Resize(&ret, bufsize) < 0) { + BZ2_bzDecompressEnd(bzs); + goto error; + } + bzs->next_out = BUF(ret); + bzs->next_out = BUF(ret) + (BZS_TOTAL_OUT(bzs) + - totalout); + bzs->avail_out = bufsize - (bzs->next_out - BUF(ret)); + } + } + + if (bzs->avail_out != 0) { + if (_PyBytes_Resize(&ret, + (Py_ssize_t)(BZS_TOTAL_OUT(bzs) - totalout)) < 0) + goto error; + } + + RELEASE_LOCK(self); + PyBuffer_Release(&pdata); + return ret; error: - RELEASE_LOCK(self); - PyBuffer_Release(&pdata); - Py_XDECREF(ret); - return NULL; + RELEASE_LOCK(self); + PyBuffer_Release(&pdata); + Py_XDECREF(ret); + return NULL; } static PyMethodDef BZ2Decomp_methods[] = { - {"decompress", (PyCFunction)BZ2Decomp_decompress, METH_VARARGS, BZ2Decomp_decompress__doc__}, - {NULL, NULL} /* sentinel */ + {"decompress", (PyCFunction)BZ2Decomp_decompress, METH_VARARGS, BZ2Decomp_decompress__doc__}, + {NULL, NULL} /* sentinel */ }; @@ -1793,55 +1793,55 @@ static int BZ2Decomp_init(BZ2DecompObject *self, PyObject *args, PyObject *kwargs) { - int bzerror; + int bzerror; - if (!PyArg_ParseTuple(args, ":BZ2Decompressor")) - return -1; + if (!PyArg_ParseTuple(args, ":BZ2Decompressor")) + return -1; #ifdef WITH_THREAD - self->lock = PyThread_allocate_lock(); - if (!self->lock) { - PyErr_SetString(PyExc_MemoryError, "unable to allocate lock"); - goto error; - } + self->lock = PyThread_allocate_lock(); + if (!self->lock) { + PyErr_SetString(PyExc_MemoryError, "unable to allocate lock"); + goto error; + } #endif - self->unused_data = PyBytes_FromStringAndSize("", 0); - if (!self->unused_data) - goto error; - - memset(&self->bzs, 0, sizeof(bz_stream)); - bzerror = BZ2_bzDecompressInit(&self->bzs, 0, 0); - if (bzerror != BZ_OK) { - Util_CatchBZ2Error(bzerror); - goto error; - } + self->unused_data = PyBytes_FromStringAndSize("", 0); + if (!self->unused_data) + goto error; + + memset(&self->bzs, 0, sizeof(bz_stream)); + bzerror = BZ2_bzDecompressInit(&self->bzs, 0, 0); + if (bzerror != BZ_OK) { + Util_CatchBZ2Error(bzerror); + goto error; + } - self->running = 1; + self->running = 1; - return 0; + return 0; error: #ifdef WITH_THREAD - if (self->lock) { - PyThread_free_lock(self->lock); - self->lock = NULL; - } + if (self->lock) { + PyThread_free_lock(self->lock); + self->lock = NULL; + } #endif - Py_CLEAR(self->unused_data); - return -1; + Py_CLEAR(self->unused_data); + return -1; } static void BZ2Decomp_dealloc(BZ2DecompObject *self) { #ifdef WITH_THREAD - if (self->lock) - PyThread_free_lock(self->lock); + if (self->lock) + PyThread_free_lock(self->lock); #endif - Py_XDECREF(self->unused_data); - BZ2_bzDecompressEnd(&self->bzs); - Py_TYPE(self)->tp_free((PyObject *)self); + Py_XDECREF(self->unused_data); + BZ2_bzDecompressEnd(&self->bzs); + Py_TYPE(self)->tp_free((PyObject *)self); } @@ -1857,46 +1857,46 @@ "); static PyTypeObject BZ2Decomp_Type = { - PyVarObject_HEAD_INIT(NULL, 0) - "bz2.BZ2Decompressor", /*tp_name*/ - sizeof(BZ2DecompObject), /*tp_basicsize*/ - 0, /*tp_itemsize*/ - (destructor)BZ2Decomp_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*/ - PyObject_GenericSetAttr,/*tp_setattro*/ - 0, /*tp_as_buffer*/ - Py_TPFLAGS_DEFAULT|Py_TPFLAGS_BASETYPE, /*tp_flags*/ - BZ2Decomp__doc__, /*tp_doc*/ - 0, /*tp_traverse*/ - 0, /*tp_clear*/ - 0, /*tp_richcompare*/ - 0, /*tp_weaklistoffset*/ - 0, /*tp_iter*/ - 0, /*tp_iternext*/ - BZ2Decomp_methods, /*tp_methods*/ - BZ2Decomp_members, /*tp_members*/ - 0, /*tp_getset*/ - 0, /*tp_base*/ - 0, /*tp_dict*/ - 0, /*tp_descr_get*/ - 0, /*tp_descr_set*/ - 0, /*tp_dictoffset*/ - (initproc)BZ2Decomp_init, /*tp_init*/ - PyType_GenericAlloc, /*tp_alloc*/ - PyType_GenericNew, /*tp_new*/ - PyObject_Free, /*tp_free*/ - 0, /*tp_is_gc*/ + PyVarObject_HEAD_INIT(NULL, 0) + "bz2.BZ2Decompressor", /*tp_name*/ + sizeof(BZ2DecompObject), /*tp_basicsize*/ + 0, /*tp_itemsize*/ + (destructor)BZ2Decomp_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*/ + PyObject_GenericSetAttr,/*tp_setattro*/ + 0, /*tp_as_buffer*/ + Py_TPFLAGS_DEFAULT|Py_TPFLAGS_BASETYPE, /*tp_flags*/ + BZ2Decomp__doc__, /*tp_doc*/ + 0, /*tp_traverse*/ + 0, /*tp_clear*/ + 0, /*tp_richcompare*/ + 0, /*tp_weaklistoffset*/ + 0, /*tp_iter*/ + 0, /*tp_iternext*/ + BZ2Decomp_methods, /*tp_methods*/ + BZ2Decomp_members, /*tp_members*/ + 0, /*tp_getset*/ + 0, /*tp_base*/ + 0, /*tp_dict*/ + 0, /*tp_descr_get*/ + 0, /*tp_descr_set*/ + 0, /*tp_dictoffset*/ + (initproc)BZ2Decomp_init, /*tp_init*/ + PyType_GenericAlloc, /*tp_alloc*/ + PyType_GenericNew, /*tp_new*/ + PyObject_Free, /*tp_free*/ + 0, /*tp_is_gc*/ }; @@ -1914,90 +1914,90 @@ static PyObject * bz2_compress(PyObject *self, PyObject *args, PyObject *kwargs) { - int compresslevel=9; - Py_buffer pdata; - char *data; - int datasize; - int bufsize; - PyObject *ret = NULL; - bz_stream _bzs; - bz_stream *bzs = &_bzs; - int bzerror; - static char *kwlist[] = {"data", "compresslevel", 0}; - - if (!PyArg_ParseTupleAndKeywords(args, kwargs, "y*|i", - kwlist, &pdata, - &compresslevel)) - return NULL; - data = pdata.buf; - datasize = pdata.len; - - if (compresslevel < 1 || compresslevel > 9) { - PyErr_SetString(PyExc_ValueError, - "compresslevel must be between 1 and 9"); - PyBuffer_Release(&pdata); - return NULL; - } - - /* Conforming to bz2 manual, this is large enough to fit compressed - * data in one shot. We will check it later anyway. */ - bufsize = datasize + (datasize/100+1) + 600; - - ret = PyBytes_FromStringAndSize(NULL, bufsize); - if (!ret) { - PyBuffer_Release(&pdata); - return NULL; - } - - memset(bzs, 0, sizeof(bz_stream)); - - bzs->next_in = data; - bzs->avail_in = datasize; - bzs->next_out = BUF(ret); - bzs->avail_out = bufsize; - - bzerror = BZ2_bzCompressInit(bzs, compresslevel, 0, 0); - if (bzerror != BZ_OK) { - Util_CatchBZ2Error(bzerror); - PyBuffer_Release(&pdata); - Py_DECREF(ret); - return NULL; - } - - for (;;) { - Py_BEGIN_ALLOW_THREADS - bzerror = BZ2_bzCompress(bzs, BZ_FINISH); - Py_END_ALLOW_THREADS - if (bzerror == BZ_STREAM_END) { - break; - } else if (bzerror != BZ_FINISH_OK) { - BZ2_bzCompressEnd(bzs); - Util_CatchBZ2Error(bzerror); - PyBuffer_Release(&pdata); - Py_DECREF(ret); - return NULL; - } - if (bzs->avail_out == 0) { - bufsize = Util_NewBufferSize(bufsize); - if (_PyBytes_Resize(&ret, bufsize) < 0) { - BZ2_bzCompressEnd(bzs); - PyBuffer_Release(&pdata); - return NULL; - } - bzs->next_out = BUF(ret) + BZS_TOTAL_OUT(bzs); - bzs->avail_out = bufsize - (bzs->next_out - BUF(ret)); - } - } - - if (bzs->avail_out != 0) { - if (_PyBytes_Resize(&ret, (Py_ssize_t)BZS_TOTAL_OUT(bzs)) < 0) { - ret = NULL; - } - } - BZ2_bzCompressEnd(bzs); + int compresslevel=9; + Py_buffer pdata; + char *data; + int datasize; + int bufsize; + PyObject *ret = NULL; + bz_stream _bzs; + bz_stream *bzs = &_bzs; + int bzerror; + static char *kwlist[] = {"data", "compresslevel", 0}; + + if (!PyArg_ParseTupleAndKeywords(args, kwargs, "y*|i", + kwlist, &pdata, + &compresslevel)) + return NULL; + data = pdata.buf; + datasize = pdata.len; + + if (compresslevel < 1 || compresslevel > 9) { + PyErr_SetString(PyExc_ValueError, + "compresslevel must be between 1 and 9"); + PyBuffer_Release(&pdata); + return NULL; + } + + /* Conforming to bz2 manual, this is large enough to fit compressed + * data in one shot. We will check it later anyway. */ + bufsize = datasize + (datasize/100+1) + 600; + + ret = PyBytes_FromStringAndSize(NULL, bufsize); + if (!ret) { + PyBuffer_Release(&pdata); + return NULL; + } + + memset(bzs, 0, sizeof(bz_stream)); + + bzs->next_in = data; + bzs->avail_in = datasize; + bzs->next_out = BUF(ret); + bzs->avail_out = bufsize; + + bzerror = BZ2_bzCompressInit(bzs, compresslevel, 0, 0); + if (bzerror != BZ_OK) { + Util_CatchBZ2Error(bzerror); + PyBuffer_Release(&pdata); + Py_DECREF(ret); + return NULL; + } + + for (;;) { + Py_BEGIN_ALLOW_THREADS + bzerror = BZ2_bzCompress(bzs, BZ_FINISH); + Py_END_ALLOW_THREADS + if (bzerror == BZ_STREAM_END) { + break; + } else if (bzerror != BZ_FINISH_OK) { + BZ2_bzCompressEnd(bzs); + Util_CatchBZ2Error(bzerror); + PyBuffer_Release(&pdata); + Py_DECREF(ret); + return NULL; + } + if (bzs->avail_out == 0) { + bufsize = Util_NewBufferSize(bufsize); + if (_PyBytes_Resize(&ret, bufsize) < 0) { + BZ2_bzCompressEnd(bzs); + PyBuffer_Release(&pdata); + return NULL; + } + bzs->next_out = BUF(ret) + BZS_TOTAL_OUT(bzs); + bzs->avail_out = bufsize - (bzs->next_out - BUF(ret)); + } + } + + if (bzs->avail_out != 0) { + if (_PyBytes_Resize(&ret, (Py_ssize_t)BZS_TOTAL_OUT(bzs)) < 0) { + ret = NULL; + } + } + BZ2_bzCompressEnd(bzs); - PyBuffer_Release(&pdata); - return ret; + PyBuffer_Release(&pdata); + return ret; } PyDoc_STRVAR(bz2_decompress__doc__, @@ -2010,96 +2010,96 @@ static PyObject * bz2_decompress(PyObject *self, PyObject *args) { - Py_buffer pdata; - char *data; - int datasize; - int bufsize = SMALLCHUNK; - PyObject *ret; - bz_stream _bzs; - bz_stream *bzs = &_bzs; - int bzerror; - - if (!PyArg_ParseTuple(args, "y*:decompress", &pdata)) - return NULL; - data = pdata.buf; - datasize = pdata.len; - - if (datasize == 0) { - PyBuffer_Release(&pdata); - return PyBytes_FromStringAndSize("", 0); - } - - ret = PyBytes_FromStringAndSize(NULL, bufsize); - if (!ret) { - PyBuffer_Release(&pdata); - return NULL; - } - - memset(bzs, 0, sizeof(bz_stream)); - - bzs->next_in = data; - bzs->avail_in = datasize; - bzs->next_out = BUF(ret); - bzs->avail_out = bufsize; - - bzerror = BZ2_bzDecompressInit(bzs, 0, 0); - if (bzerror != BZ_OK) { - Util_CatchBZ2Error(bzerror); - Py_DECREF(ret); - PyBuffer_Release(&pdata); - return NULL; - } - - for (;;) { - Py_BEGIN_ALLOW_THREADS - bzerror = BZ2_bzDecompress(bzs); - Py_END_ALLOW_THREADS - if (bzerror == BZ_STREAM_END) { - break; - } else if (bzerror != BZ_OK) { - BZ2_bzDecompressEnd(bzs); - Util_CatchBZ2Error(bzerror); - PyBuffer_Release(&pdata); - Py_DECREF(ret); - return NULL; - } - if (bzs->avail_in == 0) { - BZ2_bzDecompressEnd(bzs); - PyErr_SetString(PyExc_ValueError, - "couldn't find end of stream"); - PyBuffer_Release(&pdata); - Py_DECREF(ret); - return NULL; - } - if (bzs->avail_out == 0) { - bufsize = Util_NewBufferSize(bufsize); - if (_PyBytes_Resize(&ret, bufsize) < 0) { - BZ2_bzDecompressEnd(bzs); - PyBuffer_Release(&pdata); - return NULL; - } - bzs->next_out = BUF(ret) + BZS_TOTAL_OUT(bzs); - bzs->avail_out = bufsize - (bzs->next_out - BUF(ret)); - } - } - - if (bzs->avail_out != 0) { - if (_PyBytes_Resize(&ret, (Py_ssize_t)BZS_TOTAL_OUT(bzs)) < 0) { - ret = NULL; - } - } - BZ2_bzDecompressEnd(bzs); - PyBuffer_Release(&pdata); + Py_buffer pdata; + char *data; + int datasize; + int bufsize = SMALLCHUNK; + PyObject *ret; + bz_stream _bzs; + bz_stream *bzs = &_bzs; + int bzerror; + + if (!PyArg_ParseTuple(args, "y*:decompress", &pdata)) + return NULL; + data = pdata.buf; + datasize = pdata.len; + + if (datasize == 0) { + PyBuffer_Release(&pdata); + return PyBytes_FromStringAndSize("", 0); + } + + ret = PyBytes_FromStringAndSize(NULL, bufsize); + if (!ret) { + PyBuffer_Release(&pdata); + return NULL; + } + + memset(bzs, 0, sizeof(bz_stream)); + + bzs->next_in = data; + bzs->avail_in = datasize; + bzs->next_out = BUF(ret); + bzs->avail_out = bufsize; + + bzerror = BZ2_bzDecompressInit(bzs, 0, 0); + if (bzerror != BZ_OK) { + Util_CatchBZ2Error(bzerror); + Py_DECREF(ret); + PyBuffer_Release(&pdata); + return NULL; + } + + for (;;) { + Py_BEGIN_ALLOW_THREADS + bzerror = BZ2_bzDecompress(bzs); + Py_END_ALLOW_THREADS + if (bzerror == BZ_STREAM_END) { + break; + } else if (bzerror != BZ_OK) { + BZ2_bzDecompressEnd(bzs); + Util_CatchBZ2Error(bzerror); + PyBuffer_Release(&pdata); + Py_DECREF(ret); + return NULL; + } + if (bzs->avail_in == 0) { + BZ2_bzDecompressEnd(bzs); + PyErr_SetString(PyExc_ValueError, + "couldn't find end of stream"); + PyBuffer_Release(&pdata); + Py_DECREF(ret); + return NULL; + } + if (bzs->avail_out == 0) { + bufsize = Util_NewBufferSize(bufsize); + if (_PyBytes_Resize(&ret, bufsize) < 0) { + BZ2_bzDecompressEnd(bzs); + PyBuffer_Release(&pdata); + return NULL; + } + bzs->next_out = BUF(ret) + BZS_TOTAL_OUT(bzs); + bzs->avail_out = bufsize - (bzs->next_out - BUF(ret)); + } + } + + if (bzs->avail_out != 0) { + if (_PyBytes_Resize(&ret, (Py_ssize_t)BZS_TOTAL_OUT(bzs)) < 0) { + ret = NULL; + } + } + BZ2_bzDecompressEnd(bzs); + PyBuffer_Release(&pdata); - return ret; + return ret; } static PyMethodDef bz2_methods[] = { - {"compress", (PyCFunction) bz2_compress, METH_VARARGS|METH_KEYWORDS, - bz2_compress__doc__}, - {"decompress", (PyCFunction) bz2_decompress, METH_VARARGS, - bz2_decompress__doc__}, - {NULL, NULL} /* sentinel */ + {"compress", (PyCFunction) bz2_compress, METH_VARARGS|METH_KEYWORDS, + bz2_compress__doc__}, + {"decompress", (PyCFunction) bz2_decompress, METH_VARARGS, + bz2_decompress__doc__}, + {NULL, NULL} /* sentinel */ }; /* ===================================================================== */ @@ -2114,39 +2114,39 @@ static struct PyModuleDef bz2module = { - PyModuleDef_HEAD_INIT, - "bz2", - bz2__doc__, - -1, - bz2_methods, - NULL, - NULL, - NULL, - NULL + PyModuleDef_HEAD_INIT, + "bz2", + bz2__doc__, + -1, + bz2_methods, + NULL, + NULL, + NULL, + NULL }; PyMODINIT_FUNC PyInit_bz2(void) { - PyObject *m; + PyObject *m; - Py_TYPE(&BZ2File_Type) = &PyType_Type; - Py_TYPE(&BZ2Comp_Type) = &PyType_Type; - Py_TYPE(&BZ2Decomp_Type) = &PyType_Type; + Py_TYPE(&BZ2File_Type) = &PyType_Type; + Py_TYPE(&BZ2Comp_Type) = &PyType_Type; + Py_TYPE(&BZ2Decomp_Type) = &PyType_Type; - m = PyModule_Create(&bz2module); - if (m == NULL) - return NULL; + m = PyModule_Create(&bz2module); + if (m == NULL) + return NULL; - PyModule_AddObject(m, "__author__", PyUnicode_FromString(__author__)); + PyModule_AddObject(m, "__author__", PyUnicode_FromString(__author__)); - Py_INCREF(&BZ2File_Type); - PyModule_AddObject(m, "BZ2File", (PyObject *)&BZ2File_Type); + Py_INCREF(&BZ2File_Type); + PyModule_AddObject(m, "BZ2File", (PyObject *)&BZ2File_Type); - Py_INCREF(&BZ2Comp_Type); - PyModule_AddObject(m, "BZ2Compressor", (PyObject *)&BZ2Comp_Type); + Py_INCREF(&BZ2Comp_Type); + PyModule_AddObject(m, "BZ2Compressor", (PyObject *)&BZ2Comp_Type); - Py_INCREF(&BZ2Decomp_Type); - PyModule_AddObject(m, "BZ2Decompressor", (PyObject *)&BZ2Decomp_Type); - return m; + Py_INCREF(&BZ2Decomp_Type); + PyModule_AddObject(m, "BZ2Decompressor", (PyObject *)&BZ2Decomp_Type); + return m; } Modified: python/branches/release31-maint/Modules/cjkcodecs/_codecs_cn.c ============================================================================== --- python/branches/release31-maint/Modules/cjkcodecs/_codecs_cn.c (original) +++ python/branches/release31-maint/Modules/cjkcodecs/_codecs_cn.c Sun May 9 18:14:21 2010 @@ -17,24 +17,24 @@ /* GBK and GB2312 map differently in few codepoints that are listed below: * - * gb2312 gbk - * A1A4 U+30FB KATAKANA MIDDLE DOT U+00B7 MIDDLE DOT - * A1AA U+2015 HORIZONTAL BAR U+2014 EM DASH - * A844 undefined U+2015 HORIZONTAL BAR + * gb2312 gbk + * A1A4 U+30FB KATAKANA MIDDLE DOT U+00B7 MIDDLE DOT + * A1AA U+2015 HORIZONTAL BAR U+2014 EM DASH + * A844 undefined U+2015 HORIZONTAL BAR */ #define GBK_DECODE(dc1, dc2, assi) \ - if ((dc1) == 0xa1 && (dc2) == 0xaa) (assi) = 0x2014; \ - else if ((dc1) == 0xa8 && (dc2) == 0x44) (assi) = 0x2015; \ - else if ((dc1) == 0xa1 && (dc2) == 0xa4) (assi) = 0x00b7; \ - else TRYMAP_DEC(gb2312, assi, dc1 ^ 0x80, dc2 ^ 0x80); \ - else TRYMAP_DEC(gbkext, assi, dc1, dc2); + if ((dc1) == 0xa1 && (dc2) == 0xaa) (assi) = 0x2014; \ + else if ((dc1) == 0xa8 && (dc2) == 0x44) (assi) = 0x2015; \ + else if ((dc1) == 0xa1 && (dc2) == 0xa4) (assi) = 0x00b7; \ + else TRYMAP_DEC(gb2312, assi, dc1 ^ 0x80, dc2 ^ 0x80); \ + else TRYMAP_DEC(gbkext, assi, dc1, dc2); #define GBK_ENCODE(code, assi) \ - if ((code) == 0x2014) (assi) = 0xa1aa; \ - else if ((code) == 0x2015) (assi) = 0xa844; \ - else if ((code) == 0x00b7) (assi) = 0xa1a4; \ - else if ((code) != 0x30fb && TRYMAP_ENC_COND(gbcommon, assi, code)); + if ((code) == 0x2014) (assi) = 0xa1aa; \ + else if ((code) == 0x2015) (assi) = 0xa844; \ + else if ((code) == 0x00b7) (assi) = 0xa1a4; \ + else if ((code) != 0x30fb && TRYMAP_ENC_COND(gbcommon, assi, code)); /* * GB2312 codec @@ -42,53 +42,53 @@ ENCODER(gb2312) { - while (inleft > 0) { - Py_UNICODE c = IN1; - DBCHAR code; - - if (c < 0x80) { - WRITE1((unsigned char)c) - NEXT(1, 1) - continue; - } - UCS4INVALID(c) - - REQUIRE_OUTBUF(2) - TRYMAP_ENC(gbcommon, code, c); - else return 1; - - if (code & 0x8000) /* MSB set: GBK */ - return 1; - - OUT1((code >> 8) | 0x80) - OUT2((code & 0xFF) | 0x80) - NEXT(1, 2) - } + while (inleft > 0) { + Py_UNICODE c = IN1; + DBCHAR code; + + if (c < 0x80) { + WRITE1((unsigned char)c) + NEXT(1, 1) + continue; + } + UCS4INVALID(c) + + REQUIRE_OUTBUF(2) + TRYMAP_ENC(gbcommon, code, c); + else return 1; + + if (code & 0x8000) /* MSB set: GBK */ + return 1; + + OUT1((code >> 8) | 0x80) + OUT2((code & 0xFF) | 0x80) + NEXT(1, 2) + } - return 0; + return 0; } DECODER(gb2312) { - while (inleft > 0) { - unsigned char c = **inbuf; + while (inleft > 0) { + unsigned char c = **inbuf; - REQUIRE_OUTBUF(1) + REQUIRE_OUTBUF(1) - if (c < 0x80) { - OUT1(c) - NEXT(1, 1) - continue; - } - - REQUIRE_INBUF(2) - TRYMAP_DEC(gb2312, **outbuf, c ^ 0x80, IN2 ^ 0x80) { - NEXT(2, 1) - } - else return 2; - } + if (c < 0x80) { + OUT1(c) + NEXT(1, 1) + continue; + } + + REQUIRE_INBUF(2) + TRYMAP_DEC(gb2312, **outbuf, c ^ 0x80, IN2 ^ 0x80) { + NEXT(2, 1) + } + else return 2; + } - return 0; + return 0; } @@ -98,55 +98,55 @@ ENCODER(gbk) { - while (inleft > 0) { - Py_UNICODE c = IN1; - DBCHAR code; - - if (c < 0x80) { - WRITE1((unsigned char)c) - NEXT(1, 1) - continue; - } - UCS4INVALID(c) - - REQUIRE_OUTBUF(2) - - GBK_ENCODE(c, code) - else return 1; - - OUT1((code >> 8) | 0x80) - if (code & 0x8000) - OUT2((code & 0xFF)) /* MSB set: GBK */ - else - OUT2((code & 0xFF) | 0x80) /* MSB unset: GB2312 */ - NEXT(1, 2) - } + while (inleft > 0) { + Py_UNICODE c = IN1; + DBCHAR code; + + if (c < 0x80) { + WRITE1((unsigned char)c) + NEXT(1, 1) + continue; + } + UCS4INVALID(c) + + REQUIRE_OUTBUF(2) + + GBK_ENCODE(c, code) + else return 1; + + OUT1((code >> 8) | 0x80) + if (code & 0x8000) + OUT2((code & 0xFF)) /* MSB set: GBK */ + else + OUT2((code & 0xFF) | 0x80) /* MSB unset: GB2312 */ + NEXT(1, 2) + } - return 0; + return 0; } DECODER(gbk) { - while (inleft > 0) { - unsigned char c = IN1; + while (inleft > 0) { + unsigned char c = IN1; - REQUIRE_OUTBUF(1) + REQUIRE_OUTBUF(1) - if (c < 0x80) { - OUT1(c) - NEXT(1, 1) - continue; - } + if (c < 0x80) { + OUT1(c) + NEXT(1, 1) + continue; + } - REQUIRE_INBUF(2) + REQUIRE_INBUF(2) - GBK_DECODE(c, IN2, **outbuf) - else return 2; + GBK_DECODE(c, IN2, **outbuf) + else return 2; - NEXT(2, 1) - } + NEXT(2, 1) + } - return 0; + return 0; } @@ -156,153 +156,153 @@ ENCODER(gb18030) { - while (inleft > 0) { - ucs4_t c = IN1; - DBCHAR code; - - if (c < 0x80) { - WRITE1(c) - NEXT(1, 1) - continue; - } + while (inleft > 0) { + ucs4_t c = IN1; + DBCHAR code; + + if (c < 0x80) { + WRITE1(c) + NEXT(1, 1) + continue; + } - DECODE_SURROGATE(c) - if (c > 0x10FFFF) + DECODE_SURROGATE(c) + if (c > 0x10FFFF) #if Py_UNICODE_SIZE == 2 - return 2; /* surrogates pair */ + return 2; /* surrogates pair */ #else - return 1; + return 1; #endif - else if (c >= 0x10000) { - ucs4_t tc = c - 0x10000; + else if (c >= 0x10000) { + ucs4_t tc = c - 0x10000; - REQUIRE_OUTBUF(4) + REQUIRE_OUTBUF(4) - OUT4((unsigned char)(tc % 10) + 0x30) - tc /= 10; - OUT3((unsigned char)(tc % 126) + 0x81) - tc /= 126; - OUT2((unsigned char)(tc % 10) + 0x30) - tc /= 10; - OUT1((unsigned char)(tc + 0x90)) + OUT4((unsigned char)(tc % 10) + 0x30) + tc /= 10; + OUT3((unsigned char)(tc % 126) + 0x81) + tc /= 126; + OUT2((unsigned char)(tc % 10) + 0x30) + tc /= 10; + OUT1((unsigned char)(tc + 0x90)) #if Py_UNICODE_SIZE == 2 - NEXT(2, 4) /* surrogates pair */ + NEXT(2, 4) /* surrogates pair */ #else - NEXT(1, 4) + NEXT(1, 4) #endif - continue; - } + continue; + } - REQUIRE_OUTBUF(2) + REQUIRE_OUTBUF(2) - GBK_ENCODE(c, code) - else TRYMAP_ENC(gb18030ext, code, c); - else { - const struct _gb18030_to_unibmp_ranges *utrrange; - - REQUIRE_OUTBUF(4) - - for (utrrange = gb18030_to_unibmp_ranges; - utrrange->first != 0; - utrrange++) - if (utrrange->first <= c && - c <= utrrange->last) { - Py_UNICODE tc; - - tc = c - utrrange->first + - utrrange->base; - - OUT4((unsigned char)(tc % 10) + 0x30) - tc /= 10; - OUT3((unsigned char)(tc % 126) + 0x81) - tc /= 126; - OUT2((unsigned char)(tc % 10) + 0x30) - tc /= 10; - OUT1((unsigned char)tc + 0x81) - - NEXT(1, 4) - break; - } - - if (utrrange->first == 0) - return 1; - continue; - } - - OUT1((code >> 8) | 0x80) - if (code & 0x8000) - OUT2((code & 0xFF)) /* MSB set: GBK or GB18030ext */ - else - OUT2((code & 0xFF) | 0x80) /* MSB unset: GB2312 */ + GBK_ENCODE(c, code) + else TRYMAP_ENC(gb18030ext, code, c); + else { + const struct _gb18030_to_unibmp_ranges *utrrange; + + REQUIRE_OUTBUF(4) + + for (utrrange = gb18030_to_unibmp_ranges; + utrrange->first != 0; + utrrange++) + if (utrrange->first <= c && + c <= utrrange->last) { + Py_UNICODE tc; + + tc = c - utrrange->first + + utrrange->base; + + OUT4((unsigned char)(tc % 10) + 0x30) + tc /= 10; + OUT3((unsigned char)(tc % 126) + 0x81) + tc /= 126; + OUT2((unsigned char)(tc % 10) + 0x30) + tc /= 10; + OUT1((unsigned char)tc + 0x81) + + NEXT(1, 4) + break; + } + + if (utrrange->first == 0) + return 1; + continue; + } + + OUT1((code >> 8) | 0x80) + if (code & 0x8000) + OUT2((code & 0xFF)) /* MSB set: GBK or GB18030ext */ + else + OUT2((code & 0xFF) | 0x80) /* MSB unset: GB2312 */ - NEXT(1, 2) - } + NEXT(1, 2) + } - return 0; + return 0; } DECODER(gb18030) { - while (inleft > 0) { - unsigned char c = IN1, c2; + while (inleft > 0) { + unsigned char c = IN1, c2; - REQUIRE_OUTBUF(1) + REQUIRE_OUTBUF(1) - if (c < 0x80) { - OUT1(c) - NEXT(1, 1) - continue; - } - - REQUIRE_INBUF(2) - - c2 = IN2; - if (c2 >= 0x30 && c2 <= 0x39) { /* 4 bytes seq */ - const struct _gb18030_to_unibmp_ranges *utr; - unsigned char c3, c4; - ucs4_t lseq; - - REQUIRE_INBUF(4) - c3 = IN3; - c4 = IN4; - if (c < 0x81 || c3 < 0x81 || c4 < 0x30 || c4 > 0x39) - return 4; - c -= 0x81; c2 -= 0x30; - c3 -= 0x81; c4 -= 0x30; - - if (c < 4) { /* U+0080 - U+FFFF */ - lseq = ((ucs4_t)c * 10 + c2) * 1260 + - (ucs4_t)c3 * 10 + c4; - if (lseq < 39420) { - for (utr = gb18030_to_unibmp_ranges; - lseq >= (utr + 1)->base; - utr++) ; - OUT1(utr->first - utr->base + lseq) - NEXT(4, 1) - continue; - } - } - else if (c >= 15) { /* U+10000 - U+10FFFF */ - lseq = 0x10000 + (((ucs4_t)c-15) * 10 + c2) - * 1260 + (ucs4_t)c3 * 10 + c4; - if (lseq <= 0x10FFFF) { - WRITEUCS4(lseq); - NEXT_IN(4) - continue; - } - } - return 4; - } - - GBK_DECODE(c, c2, **outbuf) - else TRYMAP_DEC(gb18030ext, **outbuf, c, c2); - else return 2; + if (c < 0x80) { + OUT1(c) + NEXT(1, 1) + continue; + } + + REQUIRE_INBUF(2) + + c2 = IN2; + if (c2 >= 0x30 && c2 <= 0x39) { /* 4 bytes seq */ + const struct _gb18030_to_unibmp_ranges *utr; + unsigned char c3, c4; + ucs4_t lseq; + + REQUIRE_INBUF(4) + c3 = IN3; + c4 = IN4; + if (c < 0x81 || c3 < 0x81 || c4 < 0x30 || c4 > 0x39) + return 4; + c -= 0x81; c2 -= 0x30; + c3 -= 0x81; c4 -= 0x30; + + if (c < 4) { /* U+0080 - U+FFFF */ + lseq = ((ucs4_t)c * 10 + c2) * 1260 + + (ucs4_t)c3 * 10 + c4; + if (lseq < 39420) { + for (utr = gb18030_to_unibmp_ranges; + lseq >= (utr + 1)->base; + utr++) ; + OUT1(utr->first - utr->base + lseq) + NEXT(4, 1) + continue; + } + } + else if (c >= 15) { /* U+10000 - U+10FFFF */ + lseq = 0x10000 + (((ucs4_t)c-15) * 10 + c2) + * 1260 + (ucs4_t)c3 * 10 + c4; + if (lseq <= 0x10FFFF) { + WRITEUCS4(lseq); + NEXT_IN(4) + continue; + } + } + return 4; + } + + GBK_DECODE(c, c2, **outbuf) + else TRYMAP_DEC(gb18030ext, **outbuf, c, c2); + else return 2; - NEXT(2, 1) - } + NEXT(2, 1) + } - return 0; + return 0; } @@ -312,118 +312,118 @@ ENCODER_INIT(hz) { - state->i = 0; - return 0; + state->i = 0; + return 0; } ENCODER_RESET(hz) { - if (state->i != 0) { - WRITE2('~', '}') - state->i = 0; - NEXT_OUT(2) - } - return 0; + if (state->i != 0) { + WRITE2('~', '}') + state->i = 0; + NEXT_OUT(2) + } + return 0; } ENCODER(hz) { - while (inleft > 0) { - Py_UNICODE c = IN1; - DBCHAR code; - - if (c < 0x80) { - if (state->i == 0) { - WRITE1((unsigned char)c) - NEXT(1, 1) - } - else { - WRITE3('~', '}', (unsigned char)c) - NEXT(1, 3) - state->i = 0; - } - continue; - } - - UCS4INVALID(c) - - TRYMAP_ENC(gbcommon, code, c); - else return 1; - - if (code & 0x8000) /* MSB set: GBK */ - return 1; - - if (state->i == 0) { - WRITE4('~', '{', code >> 8, code & 0xff) - NEXT(1, 4) - state->i = 1; - } - else { - WRITE2(code >> 8, code & 0xff) - NEXT(1, 2) - } - } + while (inleft > 0) { + Py_UNICODE c = IN1; + DBCHAR code; + + if (c < 0x80) { + if (state->i == 0) { + WRITE1((unsigned char)c) + NEXT(1, 1) + } + else { + WRITE3('~', '}', (unsigned char)c) + NEXT(1, 3) + state->i = 0; + } + continue; + } + + UCS4INVALID(c) + + TRYMAP_ENC(gbcommon, code, c); + else return 1; + + if (code & 0x8000) /* MSB set: GBK */ + return 1; + + if (state->i == 0) { + WRITE4('~', '{', code >> 8, code & 0xff) + NEXT(1, 4) + state->i = 1; + } + else { + WRITE2(code >> 8, code & 0xff) + NEXT(1, 2) + } + } - return 0; + return 0; } DECODER_INIT(hz) { - state->i = 0; - return 0; + state->i = 0; + return 0; } DECODER_RESET(hz) { - state->i = 0; - return 0; + state->i = 0; + return 0; } DECODER(hz) { - while (inleft > 0) { - unsigned char c = IN1; + while (inleft > 0) { + unsigned char c = IN1; - if (c == '~') { - unsigned char c2 = IN2; + if (c == '~') { + unsigned char c2 = IN2; - REQUIRE_INBUF(2) - if (c2 == '~') { - WRITE1('~') - NEXT(2, 1) - continue; - } - else if (c2 == '{' && state->i == 0) - state->i = 1; /* set GB */ - else if (c2 == '}' && state->i == 1) - state->i = 0; /* set ASCII */ - else if (c2 == '\n') - ; /* line-continuation */ - else - return 2; - NEXT(2, 0); - continue; - } - - if (c & 0x80) - return 1; - - if (state->i == 0) { /* ASCII mode */ - WRITE1(c) - NEXT(1, 1) - } - else { /* GB mode */ - REQUIRE_INBUF(2) - REQUIRE_OUTBUF(1) - TRYMAP_DEC(gb2312, **outbuf, c, IN2) { - NEXT(2, 1) - } - else - return 2; - } - } + REQUIRE_INBUF(2) + if (c2 == '~') { + WRITE1('~') + NEXT(2, 1) + continue; + } + else if (c2 == '{' && state->i == 0) + state->i = 1; /* set GB */ + else if (c2 == '}' && state->i == 1) + state->i = 0; /* set ASCII */ + else if (c2 == '\n') + ; /* line-continuation */ + else + return 2; + NEXT(2, 0); + continue; + } + + if (c & 0x80) + return 1; + + if (state->i == 0) { /* ASCII mode */ + WRITE1(c) + NEXT(1, 1) + } + else { /* GB mode */ + REQUIRE_INBUF(2) + REQUIRE_OUTBUF(1) + TRYMAP_DEC(gb2312, **outbuf, c, IN2) { + NEXT(2, 1) + } + else + return 2; + } + } - return 0; + return 0; } Modified: python/branches/release31-maint/Modules/cjkcodecs/_codecs_hk.c ============================================================================== --- python/branches/release31-maint/Modules/cjkcodecs/_codecs_hk.c (original) +++ python/branches/release31-maint/Modules/cjkcodecs/_codecs_hk.c Sun May 9 18:14:21 2010 @@ -18,12 +18,12 @@ CODEC_INIT(big5hkscs) { - static int initialized = 0; + static int initialized = 0; - if (!initialized && IMPORT_MAP(tw, big5, &big5_encmap, &big5_decmap)) - return -1; - initialized = 1; - return 0; + if (!initialized && IMPORT_MAP(tw, big5, &big5_encmap, &big5_decmap)) + return -1; + initialized = 1; + return 0; } /* @@ -38,135 +38,135 @@ ENCODER(big5hkscs) { - while (inleft > 0) { - ucs4_t c = **inbuf; - DBCHAR code; - Py_ssize_t insize; - - if (c < 0x80) { - REQUIRE_OUTBUF(1) - **outbuf = (unsigned char)c; - NEXT(1, 1) - continue; - } - - DECODE_SURROGATE(c) - insize = GET_INSIZE(c); - - REQUIRE_OUTBUF(2) - - if (c < 0x10000) { - TRYMAP_ENC(big5hkscs_bmp, code, c) { - if (code == MULTIC) { - if (inleft >= 2 && - ((c & 0xffdf) == 0x00ca) && - (((*inbuf)[1] & 0xfff7) == 0x0304)) { - code = big5hkscs_pairenc_table[ - ((c >> 4) | - ((*inbuf)[1] >> 3)) & 3]; - insize = 2; - } - else if (inleft < 2 && - !(flags & MBENC_FLUSH)) - return MBERR_TOOFEW; - else { - if (c == 0xca) - code = 0x8866; - else /* c == 0xea */ - code = 0x88a7; - } - } - } - else TRYMAP_ENC(big5, code, c); - else return 1; - } - else if (c < 0x20000) - return insize; - else if (c < 0x30000) { - TRYMAP_ENC(big5hkscs_nonbmp, code, c & 0xffff); - else return insize; - } - else - return insize; - - OUT1(code >> 8) - OUT2(code & 0xFF) - NEXT(insize, 2) - } + while (inleft > 0) { + ucs4_t c = **inbuf; + DBCHAR code; + Py_ssize_t insize; + + if (c < 0x80) { + REQUIRE_OUTBUF(1) + **outbuf = (unsigned char)c; + NEXT(1, 1) + continue; + } + + DECODE_SURROGATE(c) + insize = GET_INSIZE(c); + + REQUIRE_OUTBUF(2) + + if (c < 0x10000) { + TRYMAP_ENC(big5hkscs_bmp, code, c) { + if (code == MULTIC) { + if (inleft >= 2 && + ((c & 0xffdf) == 0x00ca) && + (((*inbuf)[1] & 0xfff7) == 0x0304)) { + code = big5hkscs_pairenc_table[ + ((c >> 4) | + ((*inbuf)[1] >> 3)) & 3]; + insize = 2; + } + else if (inleft < 2 && + !(flags & MBENC_FLUSH)) + return MBERR_TOOFEW; + else { + if (c == 0xca) + code = 0x8866; + else /* c == 0xea */ + code = 0x88a7; + } + } + } + else TRYMAP_ENC(big5, code, c); + else return 1; + } + else if (c < 0x20000) + return insize; + else if (c < 0x30000) { + TRYMAP_ENC(big5hkscs_nonbmp, code, c & 0xffff); + else return insize; + } + else + return insize; + + OUT1(code >> 8) + OUT2(code & 0xFF) + NEXT(insize, 2) + } - return 0; + return 0; } #define BH2S(c1, c2) (((c1) - 0x87) * (0xfe - 0x40 + 1) + ((c2) - 0x40)) DECODER(big5hkscs) { - while (inleft > 0) { - unsigned char c = IN1; - ucs4_t decoded; - - REQUIRE_OUTBUF(1) - - if (c < 0x80) { - OUT1(c) - NEXT(1, 1) - continue; - } - - REQUIRE_INBUF(2) - - if (0xc6 <= c && c <= 0xc8 && (c >= 0xc7 || IN2 >= 0xa1)) - goto hkscsdec; - - TRYMAP_DEC(big5, **outbuf, c, IN2) { - NEXT(2, 1) - } - else -hkscsdec: TRYMAP_DEC(big5hkscs, decoded, c, IN2) { - int s = BH2S(c, IN2); - const unsigned char *hintbase; - - assert(0x87 <= c && c <= 0xfe); - assert(0x40 <= IN2 && IN2 <= 0xfe); - - if (BH2S(0x87, 0x40) <= s && s <= BH2S(0xa0, 0xfe)) { - hintbase = big5hkscs_phint_0; - s -= BH2S(0x87, 0x40); - } - else if (BH2S(0xc6,0xa1) <= s && s <= BH2S(0xc8,0xfe)){ - hintbase = big5hkscs_phint_12130; - s -= BH2S(0xc6, 0xa1); - } - else if (BH2S(0xf9,0xd6) <= s && s <= BH2S(0xfe,0xfe)){ - hintbase = big5hkscs_phint_21924; - s -= BH2S(0xf9, 0xd6); - } - else - return MBERR_INTERNAL; - - if (hintbase[s >> 3] & (1 << (s & 7))) { - WRITEUCS4(decoded | 0x20000) - NEXT_IN(2) - } - else { - OUT1(decoded) - NEXT(2, 1) - } - } - else { - switch ((c << 8) | IN2) { - case 0x8862: WRITE2(0x00ca, 0x0304); break; - case 0x8864: WRITE2(0x00ca, 0x030c); break; - case 0x88a3: WRITE2(0x00ea, 0x0304); break; - case 0x88a5: WRITE2(0x00ea, 0x030c); break; - default: return 2; - } - - NEXT(2, 2) /* all decoded codepoints are pairs, above. */ - } - } + while (inleft > 0) { + unsigned char c = IN1; + ucs4_t decoded; + + REQUIRE_OUTBUF(1) + + if (c < 0x80) { + OUT1(c) + NEXT(1, 1) + continue; + } + + REQUIRE_INBUF(2) + + if (0xc6 <= c && c <= 0xc8 && (c >= 0xc7 || IN2 >= 0xa1)) + goto hkscsdec; + + TRYMAP_DEC(big5, **outbuf, c, IN2) { + NEXT(2, 1) + } + else +hkscsdec: TRYMAP_DEC(big5hkscs, decoded, c, IN2) { + int s = BH2S(c, IN2); + const unsigned char *hintbase; + + assert(0x87 <= c && c <= 0xfe); + assert(0x40 <= IN2 && IN2 <= 0xfe); + + if (BH2S(0x87, 0x40) <= s && s <= BH2S(0xa0, 0xfe)) { + hintbase = big5hkscs_phint_0; + s -= BH2S(0x87, 0x40); + } + else if (BH2S(0xc6,0xa1) <= s && s <= BH2S(0xc8,0xfe)){ + hintbase = big5hkscs_phint_12130; + s -= BH2S(0xc6, 0xa1); + } + else if (BH2S(0xf9,0xd6) <= s && s <= BH2S(0xfe,0xfe)){ + hintbase = big5hkscs_phint_21924; + s -= BH2S(0xf9, 0xd6); + } + else + return MBERR_INTERNAL; + + if (hintbase[s >> 3] & (1 << (s & 7))) { + WRITEUCS4(decoded | 0x20000) + NEXT_IN(2) + } + else { + OUT1(decoded) + NEXT(2, 1) + } + } + else { + switch ((c << 8) | IN2) { + case 0x8862: WRITE2(0x00ca, 0x0304); break; + case 0x8864: WRITE2(0x00ca, 0x030c); break; + case 0x88a3: WRITE2(0x00ea, 0x0304); break; + case 0x88a5: WRITE2(0x00ea, 0x030c); break; + default: return 2; + } + + NEXT(2, 2) /* all decoded codepoints are pairs, above. */ + } + } - return 0; + return 0; } Modified: python/branches/release31-maint/Modules/cjkcodecs/_codecs_iso2022.c ============================================================================== --- python/branches/release31-maint/Modules/cjkcodecs/_codecs_iso2022.c (original) +++ python/branches/release31-maint/Modules/cjkcodecs/_codecs_iso2022.c Sun May 9 18:14:21 2010 @@ -19,85 +19,85 @@ state->c[0-3] - 00000000 - ||^^^^^| - |+-----+---- G0-3 Character Set - +----------- Is G0-3 double byte? + 00000000 + ||^^^^^| + |+-----+---- G0-3 Character Set + +----------- Is G0-3 double byte? state->c[4] - 00000000 - || - |+---- Locked-Shift? - +----- ESC Throughout + 00000000 + || + |+---- Locked-Shift? + +----- ESC Throughout */ -#define ESC 0x1B -#define SO 0x0E -#define SI 0x0F -#define LF 0x0A - -#define MAX_ESCSEQLEN 16 - -#define CHARSET_ISO8859_1 'A' -#define CHARSET_ASCII 'B' -#define CHARSET_ISO8859_7 'F' -#define CHARSET_JISX0201_K 'I' -#define CHARSET_JISX0201_R 'J' - -#define CHARSET_GB2312 ('A'|CHARSET_DBCS) -#define CHARSET_JISX0208 ('B'|CHARSET_DBCS) -#define CHARSET_KSX1001 ('C'|CHARSET_DBCS) -#define CHARSET_JISX0212 ('D'|CHARSET_DBCS) -#define CHARSET_GB2312_8565 ('E'|CHARSET_DBCS) -#define CHARSET_CNS11643_1 ('G'|CHARSET_DBCS) -#define CHARSET_CNS11643_2 ('H'|CHARSET_DBCS) -#define CHARSET_JISX0213_2000_1 ('O'|CHARSET_DBCS) -#define CHARSET_JISX0213_2 ('P'|CHARSET_DBCS) -#define CHARSET_JISX0213_2004_1 ('Q'|CHARSET_DBCS) -#define CHARSET_JISX0208_O ('@'|CHARSET_DBCS) +#define ESC 0x1B +#define SO 0x0E +#define SI 0x0F +#define LF 0x0A + +#define MAX_ESCSEQLEN 16 + +#define CHARSET_ISO8859_1 'A' +#define CHARSET_ASCII 'B' +#define CHARSET_ISO8859_7 'F' +#define CHARSET_JISX0201_K 'I' +#define CHARSET_JISX0201_R 'J' + +#define CHARSET_GB2312 ('A'|CHARSET_DBCS) +#define CHARSET_JISX0208 ('B'|CHARSET_DBCS) +#define CHARSET_KSX1001 ('C'|CHARSET_DBCS) +#define CHARSET_JISX0212 ('D'|CHARSET_DBCS) +#define CHARSET_GB2312_8565 ('E'|CHARSET_DBCS) +#define CHARSET_CNS11643_1 ('G'|CHARSET_DBCS) +#define CHARSET_CNS11643_2 ('H'|CHARSET_DBCS) +#define CHARSET_JISX0213_2000_1 ('O'|CHARSET_DBCS) +#define CHARSET_JISX0213_2 ('P'|CHARSET_DBCS) +#define CHARSET_JISX0213_2004_1 ('Q'|CHARSET_DBCS) +#define CHARSET_JISX0208_O ('@'|CHARSET_DBCS) -#define CHARSET_DBCS 0x80 -#define ESCMARK(mark) ((mark) & 0x7f) +#define CHARSET_DBCS 0x80 +#define ESCMARK(mark) ((mark) & 0x7f) -#define IS_ESCEND(c) (((c) >= 'A' && (c) <= 'Z') || (c) == '@') +#define IS_ESCEND(c) (((c) >= 'A' && (c) <= 'Z') || (c) == '@') #define IS_ISO2022ESC(c2) \ - ((c2) == '(' || (c2) == ')' || (c2) == '$' || \ - (c2) == '.' || (c2) == '&') - /* this is not a complete list of ISO-2022 escape sequence headers. - * but, it's enough to implement CJK instances of iso-2022. */ - -#define MAP_UNMAPPABLE 0xFFFF -#define MAP_MULTIPLE_AVAIL 0xFFFE /* for JIS X 0213 */ - -#define F_SHIFTED 0x01 -#define F_ESCTHROUGHOUT 0x02 - -#define STATE_SETG(dn, v) ((state)->c[dn]) = (v); -#define STATE_GETG(dn) ((state)->c[dn]) - -#define STATE_G0 STATE_GETG(0) -#define STATE_G1 STATE_GETG(1) -#define STATE_G2 STATE_GETG(2) -#define STATE_G3 STATE_GETG(3) -#define STATE_SETG0(v) STATE_SETG(0, v) -#define STATE_SETG1(v) STATE_SETG(1, v) -#define STATE_SETG2(v) STATE_SETG(2, v) -#define STATE_SETG3(v) STATE_SETG(3, v) - -#define STATE_SETFLAG(f) ((state)->c[4]) |= (f); -#define STATE_GETFLAG(f) ((state)->c[4] & (f)) -#define STATE_CLEARFLAG(f) ((state)->c[4]) &= ~(f); -#define STATE_CLEARFLAGS() ((state)->c[4]) = 0; - -#define ISO2022_CONFIG ((const struct iso2022_config *)config) -#define CONFIG_ISSET(flag) (ISO2022_CONFIG->flags & (flag)) -#define CONFIG_DESIGNATIONS (ISO2022_CONFIG->designations) + ((c2) == '(' || (c2) == ')' || (c2) == '$' || \ + (c2) == '.' || (c2) == '&') + /* this is not a complete list of ISO-2022 escape sequence headers. + * but, it's enough to implement CJK instances of iso-2022. */ + +#define MAP_UNMAPPABLE 0xFFFF +#define MAP_MULTIPLE_AVAIL 0xFFFE /* for JIS X 0213 */ + +#define F_SHIFTED 0x01 +#define F_ESCTHROUGHOUT 0x02 + +#define STATE_SETG(dn, v) ((state)->c[dn]) = (v); +#define STATE_GETG(dn) ((state)->c[dn]) + +#define STATE_G0 STATE_GETG(0) +#define STATE_G1 STATE_GETG(1) +#define STATE_G2 STATE_GETG(2) +#define STATE_G3 STATE_GETG(3) +#define STATE_SETG0(v) STATE_SETG(0, v) +#define STATE_SETG1(v) STATE_SETG(1, v) +#define STATE_SETG2(v) STATE_SETG(2, v) +#define STATE_SETG3(v) STATE_SETG(3, v) + +#define STATE_SETFLAG(f) ((state)->c[4]) |= (f); +#define STATE_GETFLAG(f) ((state)->c[4] & (f)) +#define STATE_CLEARFLAG(f) ((state)->c[4]) &= ~(f); +#define STATE_CLEARFLAGS() ((state)->c[4]) = 0; + +#define ISO2022_CONFIG ((const struct iso2022_config *)config) +#define CONFIG_ISSET(flag) (ISO2022_CONFIG->flags & (flag)) +#define CONFIG_DESIGNATIONS (ISO2022_CONFIG->designations) /* iso2022_config.flags */ -#define NO_SHIFT 0x01 -#define USE_G2 0x02 -#define USE_JISX0208_EXT 0x04 +#define NO_SHIFT 0x01 +#define USE_G2 0x02 +#define USE_JISX0208_EXT 0x04 /*-*- internal data structures -*-*/ @@ -106,434 +106,434 @@ typedef DBCHAR (*iso2022_encode_func)(const ucs4_t *data, Py_ssize_t *length); struct iso2022_designation { - unsigned char mark; - unsigned char plane; - unsigned char width; - iso2022_init_func initializer; - iso2022_decode_func decoder; - iso2022_encode_func encoder; + unsigned char mark; + unsigned char plane; + unsigned char width; + iso2022_init_func initializer; + iso2022_decode_func decoder; + iso2022_encode_func encoder; }; struct iso2022_config { - int flags; - const struct iso2022_designation *designations; /* non-ascii desigs */ + int flags; + const struct iso2022_designation *designations; /* non-ascii desigs */ }; /*-*- iso-2022 codec implementation -*-*/ CODEC_INIT(iso2022) { - const struct iso2022_designation *desig = CONFIG_DESIGNATIONS; - for (desig = CONFIG_DESIGNATIONS; desig->mark; desig++) - if (desig->initializer != NULL && desig->initializer() != 0) - return -1; - return 0; + const struct iso2022_designation *desig = CONFIG_DESIGNATIONS; + for (desig = CONFIG_DESIGNATIONS; desig->mark; desig++) + if (desig->initializer != NULL && desig->initializer() != 0) + return -1; + return 0; } ENCODER_INIT(iso2022) { - STATE_CLEARFLAGS() - STATE_SETG0(CHARSET_ASCII) - STATE_SETG1(CHARSET_ASCII) - return 0; + STATE_CLEARFLAGS() + STATE_SETG0(CHARSET_ASCII) + STATE_SETG1(CHARSET_ASCII) + return 0; } ENCODER_RESET(iso2022) { - if (STATE_GETFLAG(F_SHIFTED)) { - WRITE1(SI) - NEXT_OUT(1) - STATE_CLEARFLAG(F_SHIFTED) - } - if (STATE_G0 != CHARSET_ASCII) { - WRITE3(ESC, '(', 'B') - NEXT_OUT(3) - STATE_SETG0(CHARSET_ASCII) - } - return 0; + if (STATE_GETFLAG(F_SHIFTED)) { + WRITE1(SI) + NEXT_OUT(1) + STATE_CLEARFLAG(F_SHIFTED) + } + if (STATE_G0 != CHARSET_ASCII) { + WRITE3(ESC, '(', 'B') + NEXT_OUT(3) + STATE_SETG0(CHARSET_ASCII) + } + return 0; } ENCODER(iso2022) { - while (inleft > 0) { - const struct iso2022_designation *dsg; - DBCHAR encoded; - ucs4_t c = **inbuf; - Py_ssize_t insize; - - if (c < 0x80) { - if (STATE_G0 != CHARSET_ASCII) { - WRITE3(ESC, '(', 'B') - STATE_SETG0(CHARSET_ASCII) - NEXT_OUT(3) - } - if (STATE_GETFLAG(F_SHIFTED)) { - WRITE1(SI) - STATE_CLEARFLAG(F_SHIFTED) - NEXT_OUT(1) - } - WRITE1((unsigned char)c) - NEXT(1, 1) - continue; - } - - DECODE_SURROGATE(c) - insize = GET_INSIZE(c); - - encoded = MAP_UNMAPPABLE; - for (dsg = CONFIG_DESIGNATIONS; dsg->mark; dsg++) { - Py_ssize_t length = 1; - encoded = dsg->encoder(&c, &length); - if (encoded == MAP_MULTIPLE_AVAIL) { - /* this implementation won't work for pair - * of non-bmp characters. */ - if (inleft < 2) { - if (!(flags & MBENC_FLUSH)) - return MBERR_TOOFEW; - length = -1; - } - else - length = 2; + while (inleft > 0) { + const struct iso2022_designation *dsg; + DBCHAR encoded; + ucs4_t c = **inbuf; + Py_ssize_t insize; + + if (c < 0x80) { + if (STATE_G0 != CHARSET_ASCII) { + WRITE3(ESC, '(', 'B') + STATE_SETG0(CHARSET_ASCII) + NEXT_OUT(3) + } + if (STATE_GETFLAG(F_SHIFTED)) { + WRITE1(SI) + STATE_CLEARFLAG(F_SHIFTED) + NEXT_OUT(1) + } + WRITE1((unsigned char)c) + NEXT(1, 1) + continue; + } + + DECODE_SURROGATE(c) + insize = GET_INSIZE(c); + + encoded = MAP_UNMAPPABLE; + for (dsg = CONFIG_DESIGNATIONS; dsg->mark; dsg++) { + Py_ssize_t length = 1; + encoded = dsg->encoder(&c, &length); + if (encoded == MAP_MULTIPLE_AVAIL) { + /* this implementation won't work for pair + * of non-bmp characters. */ + if (inleft < 2) { + if (!(flags & MBENC_FLUSH)) + return MBERR_TOOFEW; + length = -1; + } + else + length = 2; #if Py_UNICODE_SIZE == 2 - if (length == 2) { - ucs4_t u4in[2]; - u4in[0] = (ucs4_t)IN1; - u4in[1] = (ucs4_t)IN2; - encoded = dsg->encoder(u4in, &length); - } else - encoded = dsg->encoder(&c, &length); + if (length == 2) { + ucs4_t u4in[2]; + u4in[0] = (ucs4_t)IN1; + u4in[1] = (ucs4_t)IN2; + encoded = dsg->encoder(u4in, &length); + } else + encoded = dsg->encoder(&c, &length); #else - encoded = dsg->encoder(&c, &length); + encoded = dsg->encoder(&c, &length); #endif - if (encoded != MAP_UNMAPPABLE) { - insize = length; - break; - } - } - else if (encoded != MAP_UNMAPPABLE) - break; - } - - if (!dsg->mark) - return 1; - assert(dsg->width == 1 || dsg->width == 2); - - switch (dsg->plane) { - case 0: /* G0 */ - if (STATE_GETFLAG(F_SHIFTED)) { - WRITE1(SI) - STATE_CLEARFLAG(F_SHIFTED) - NEXT_OUT(1) - } - if (STATE_G0 != dsg->mark) { - if (dsg->width == 1) { - WRITE3(ESC, '(', ESCMARK(dsg->mark)) - STATE_SETG0(dsg->mark) - NEXT_OUT(3) - } - else if (dsg->mark == CHARSET_JISX0208) { - WRITE3(ESC, '$', ESCMARK(dsg->mark)) - STATE_SETG0(dsg->mark) - NEXT_OUT(3) - } - else { - WRITE4(ESC, '$', '(', - ESCMARK(dsg->mark)) - STATE_SETG0(dsg->mark) - NEXT_OUT(4) - } - } - break; - case 1: /* G1 */ - if (STATE_G1 != dsg->mark) { - if (dsg->width == 1) { - WRITE3(ESC, ')', ESCMARK(dsg->mark)) - STATE_SETG1(dsg->mark) - NEXT_OUT(3) - } - else { - WRITE4(ESC, '$', ')', - ESCMARK(dsg->mark)) - STATE_SETG1(dsg->mark) - NEXT_OUT(4) - } - } - if (!STATE_GETFLAG(F_SHIFTED)) { - WRITE1(SO) - STATE_SETFLAG(F_SHIFTED) - NEXT_OUT(1) - } - break; - default: /* G2 and G3 is not supported: no encoding in - * CJKCodecs are using them yet */ - return MBERR_INTERNAL; - } - - if (dsg->width == 1) { - WRITE1((unsigned char)encoded) - NEXT_OUT(1) - } - else { - WRITE2(encoded >> 8, encoded & 0xff) - NEXT_OUT(2) - } - NEXT_IN(insize) - } + if (encoded != MAP_UNMAPPABLE) { + insize = length; + break; + } + } + else if (encoded != MAP_UNMAPPABLE) + break; + } + + if (!dsg->mark) + return 1; + assert(dsg->width == 1 || dsg->width == 2); + + switch (dsg->plane) { + case 0: /* G0 */ + if (STATE_GETFLAG(F_SHIFTED)) { + WRITE1(SI) + STATE_CLEARFLAG(F_SHIFTED) + NEXT_OUT(1) + } + if (STATE_G0 != dsg->mark) { + if (dsg->width == 1) { + WRITE3(ESC, '(', ESCMARK(dsg->mark)) + STATE_SETG0(dsg->mark) + NEXT_OUT(3) + } + else if (dsg->mark == CHARSET_JISX0208) { + WRITE3(ESC, '$', ESCMARK(dsg->mark)) + STATE_SETG0(dsg->mark) + NEXT_OUT(3) + } + else { + WRITE4(ESC, '$', '(', + ESCMARK(dsg->mark)) + STATE_SETG0(dsg->mark) + NEXT_OUT(4) + } + } + break; + case 1: /* G1 */ + if (STATE_G1 != dsg->mark) { + if (dsg->width == 1) { + WRITE3(ESC, ')', ESCMARK(dsg->mark)) + STATE_SETG1(dsg->mark) + NEXT_OUT(3) + } + else { + WRITE4(ESC, '$', ')', + ESCMARK(dsg->mark)) + STATE_SETG1(dsg->mark) + NEXT_OUT(4) + } + } + if (!STATE_GETFLAG(F_SHIFTED)) { + WRITE1(SO) + STATE_SETFLAG(F_SHIFTED) + NEXT_OUT(1) + } + break; + default: /* G2 and G3 is not supported: no encoding in + * CJKCodecs are using them yet */ + return MBERR_INTERNAL; + } + + if (dsg->width == 1) { + WRITE1((unsigned char)encoded) + NEXT_OUT(1) + } + else { + WRITE2(encoded >> 8, encoded & 0xff) + NEXT_OUT(2) + } + NEXT_IN(insize) + } - return 0; + return 0; } DECODER_INIT(iso2022) { - STATE_CLEARFLAGS() - STATE_SETG0(CHARSET_ASCII) - STATE_SETG1(CHARSET_ASCII) - STATE_SETG2(CHARSET_ASCII) - return 0; + STATE_CLEARFLAGS() + STATE_SETG0(CHARSET_ASCII) + STATE_SETG1(CHARSET_ASCII) + STATE_SETG2(CHARSET_ASCII) + return 0; } DECODER_RESET(iso2022) { - STATE_SETG0(CHARSET_ASCII) - STATE_CLEARFLAG(F_SHIFTED) - return 0; + STATE_SETG0(CHARSET_ASCII) + STATE_CLEARFLAG(F_SHIFTED) + return 0; } static Py_ssize_t iso2022processesc(const void *config, MultibyteCodec_State *state, - const unsigned char **inbuf, Py_ssize_t *inleft) + const unsigned char **inbuf, Py_ssize_t *inleft) { - unsigned char charset, designation; - Py_ssize_t i, esclen; + unsigned char charset, designation; + Py_ssize_t i, esclen; - for (i = 1;i < MAX_ESCSEQLEN;i++) { - if (i >= *inleft) - return MBERR_TOOFEW; - if (IS_ESCEND((*inbuf)[i])) { - esclen = i + 1; - break; - } - else if (CONFIG_ISSET(USE_JISX0208_EXT) && i+1 < *inleft && - (*inbuf)[i] == '&' && (*inbuf)[i+1] == '@') - i += 2; - } - - if (i >= MAX_ESCSEQLEN) - return 1; /* unterminated escape sequence */ - - switch (esclen) { - case 3: - if (IN2 == '$') { - charset = IN3 | CHARSET_DBCS; - designation = 0; - } - else { - charset = IN3; - if (IN2 == '(') designation = 0; - else if (IN2 == ')') designation = 1; - else if (CONFIG_ISSET(USE_G2) && IN2 == '.') - designation = 2; - else return 3; - } - break; - case 4: - if (IN2 != '$') - return 4; - - charset = IN4 | CHARSET_DBCS; - if (IN3 == '(') designation = 0; - else if (IN3 == ')') designation = 1; - else return 4; - break; - case 6: /* designation with prefix */ - if (CONFIG_ISSET(USE_JISX0208_EXT) && - (*inbuf)[3] == ESC && (*inbuf)[4] == '$' && - (*inbuf)[5] == 'B') { - charset = 'B' | CHARSET_DBCS; - designation = 0; - } - else - return 6; - break; - default: - return esclen; - } - - /* raise error when the charset is not designated for this encoding */ - if (charset != CHARSET_ASCII) { - const struct iso2022_designation *dsg; - - for (dsg = CONFIG_DESIGNATIONS; dsg->mark; dsg++) - if (dsg->mark == charset) - break; - if (!dsg->mark) - return esclen; - } - - STATE_SETG(designation, charset) - *inleft -= esclen; - (*inbuf) += esclen; - return 0; -} - -#define ISO8859_7_DECODE(c, assi) \ - if ((c) < 0xa0) (assi) = (c); \ - else if ((c) < 0xc0 && (0x288f3bc9L & (1L << ((c)-0xa0)))) \ - (assi) = (c); \ - else if ((c) >= 0xb4 && (c) <= 0xfe && ((c) >= 0xd4 || \ - (0xbffffd77L & (1L << ((c)-0xb4))))) \ - (assi) = 0x02d0 + (c); \ - else if ((c) == 0xa1) (assi) = 0x2018; \ - else if ((c) == 0xa2) (assi) = 0x2019; \ - else if ((c) == 0xaf) (assi) = 0x2015; + for (i = 1;i < MAX_ESCSEQLEN;i++) { + if (i >= *inleft) + return MBERR_TOOFEW; + if (IS_ESCEND((*inbuf)[i])) { + esclen = i + 1; + break; + } + else if (CONFIG_ISSET(USE_JISX0208_EXT) && i+1 < *inleft && + (*inbuf)[i] == '&' && (*inbuf)[i+1] == '@') + i += 2; + } + + if (i >= MAX_ESCSEQLEN) + return 1; /* unterminated escape sequence */ + + switch (esclen) { + case 3: + if (IN2 == '$') { + charset = IN3 | CHARSET_DBCS; + designation = 0; + } + else { + charset = IN3; + if (IN2 == '(') designation = 0; + else if (IN2 == ')') designation = 1; + else if (CONFIG_ISSET(USE_G2) && IN2 == '.') + designation = 2; + else return 3; + } + break; + case 4: + if (IN2 != '$') + return 4; + + charset = IN4 | CHARSET_DBCS; + if (IN3 == '(') designation = 0; + else if (IN3 == ')') designation = 1; + else return 4; + break; + case 6: /* designation with prefix */ + if (CONFIG_ISSET(USE_JISX0208_EXT) && + (*inbuf)[3] == ESC && (*inbuf)[4] == '$' && + (*inbuf)[5] == 'B') { + charset = 'B' | CHARSET_DBCS; + designation = 0; + } + else + return 6; + break; + default: + return esclen; + } + + /* raise error when the charset is not designated for this encoding */ + if (charset != CHARSET_ASCII) { + const struct iso2022_designation *dsg; + + for (dsg = CONFIG_DESIGNATIONS; dsg->mark; dsg++) + if (dsg->mark == charset) + break; + if (!dsg->mark) + return esclen; + } + + STATE_SETG(designation, charset) + *inleft -= esclen; + (*inbuf) += esclen; + return 0; +} + +#define ISO8859_7_DECODE(c, assi) \ + if ((c) < 0xa0) (assi) = (c); \ + else if ((c) < 0xc0 && (0x288f3bc9L & (1L << ((c)-0xa0)))) \ + (assi) = (c); \ + else if ((c) >= 0xb4 && (c) <= 0xfe && ((c) >= 0xd4 || \ + (0xbffffd77L & (1L << ((c)-0xb4))))) \ + (assi) = 0x02d0 + (c); \ + else if ((c) == 0xa1) (assi) = 0x2018; \ + else if ((c) == 0xa2) (assi) = 0x2019; \ + else if ((c) == 0xaf) (assi) = 0x2015; static Py_ssize_t iso2022processg2(const void *config, MultibyteCodec_State *state, - const unsigned char **inbuf, Py_ssize_t *inleft, - Py_UNICODE **outbuf, Py_ssize_t *outleft) + const unsigned char **inbuf, Py_ssize_t *inleft, + Py_UNICODE **outbuf, Py_ssize_t *outleft) { - /* not written to use encoder, decoder functions because only few - * encodings use G2 designations in CJKCodecs */ - if (STATE_G2 == CHARSET_ISO8859_1) { - if (IN3 < 0x80) - OUT1(IN3 + 0x80) - else - return 3; - } - else if (STATE_G2 == CHARSET_ISO8859_7) { - ISO8859_7_DECODE(IN3 ^ 0x80, **outbuf) - else return 3; - } - else if (STATE_G2 == CHARSET_ASCII) { - if (IN3 & 0x80) return 3; - else **outbuf = IN3; - } - else - return MBERR_INTERNAL; - - (*inbuf) += 3; - *inleft -= 3; - (*outbuf) += 1; - *outleft -= 1; - return 0; + /* not written to use encoder, decoder functions because only few + * encodings use G2 designations in CJKCodecs */ + if (STATE_G2 == CHARSET_ISO8859_1) { + if (IN3 < 0x80) + OUT1(IN3 + 0x80) + else + return 3; + } + else if (STATE_G2 == CHARSET_ISO8859_7) { + ISO8859_7_DECODE(IN3 ^ 0x80, **outbuf) + else return 3; + } + else if (STATE_G2 == CHARSET_ASCII) { + if (IN3 & 0x80) return 3; + else **outbuf = IN3; + } + else + return MBERR_INTERNAL; + + (*inbuf) += 3; + *inleft -= 3; + (*outbuf) += 1; + *outleft -= 1; + return 0; } DECODER(iso2022) { - const struct iso2022_designation *dsgcache = NULL; + const struct iso2022_designation *dsgcache = NULL; - while (inleft > 0) { - unsigned char c = IN1; - Py_ssize_t err; - - if (STATE_GETFLAG(F_ESCTHROUGHOUT)) { - /* ESC throughout mode: - * for non-iso2022 escape sequences */ - WRITE1(c) /* assume as ISO-8859-1 */ - NEXT(1, 1) - if (IS_ESCEND(c)) { - STATE_CLEARFLAG(F_ESCTHROUGHOUT) - } - continue; - } - - switch (c) { - case ESC: - REQUIRE_INBUF(2) - if (IS_ISO2022ESC(IN2)) { - err = iso2022processesc(config, state, - inbuf, &inleft); - if (err != 0) - return err; - } - else if (CONFIG_ISSET(USE_G2) && IN2 == 'N') {/* SS2 */ - REQUIRE_INBUF(3) - err = iso2022processg2(config, state, - inbuf, &inleft, outbuf, &outleft); - if (err != 0) - return err; - } - else { - WRITE1(ESC) - STATE_SETFLAG(F_ESCTHROUGHOUT) - NEXT(1, 1) - } - break; - case SI: - if (CONFIG_ISSET(NO_SHIFT)) - goto bypass; - STATE_CLEARFLAG(F_SHIFTED) - NEXT_IN(1) - break; - case SO: - if (CONFIG_ISSET(NO_SHIFT)) - goto bypass; - STATE_SETFLAG(F_SHIFTED) - NEXT_IN(1) - break; - case LF: - STATE_CLEARFLAG(F_SHIFTED) - WRITE1(LF) - NEXT(1, 1) - break; - default: - if (c < 0x20) /* C0 */ - goto bypass; - else if (c >= 0x80) - return 1; - else { - const struct iso2022_designation *dsg; - unsigned char charset; - ucs4_t decoded; - - if (STATE_GETFLAG(F_SHIFTED)) - charset = STATE_G1; - else - charset = STATE_G0; - - if (charset == CHARSET_ASCII) { -bypass: WRITE1(c) - NEXT(1, 1) - break; - } - - if (dsgcache != NULL && - dsgcache->mark == charset) - dsg = dsgcache; - else { - for (dsg = CONFIG_DESIGNATIONS; - dsg->mark != charset + while (inleft > 0) { + unsigned char c = IN1; + Py_ssize_t err; + + if (STATE_GETFLAG(F_ESCTHROUGHOUT)) { + /* ESC throughout mode: + * for non-iso2022 escape sequences */ + WRITE1(c) /* assume as ISO-8859-1 */ + NEXT(1, 1) + if (IS_ESCEND(c)) { + STATE_CLEARFLAG(F_ESCTHROUGHOUT) + } + continue; + } + + switch (c) { + case ESC: + REQUIRE_INBUF(2) + if (IS_ISO2022ESC(IN2)) { + err = iso2022processesc(config, state, + inbuf, &inleft); + if (err != 0) + return err; + } + else if (CONFIG_ISSET(USE_G2) && IN2 == 'N') {/* SS2 */ + REQUIRE_INBUF(3) + err = iso2022processg2(config, state, + inbuf, &inleft, outbuf, &outleft); + if (err != 0) + return err; + } + else { + WRITE1(ESC) + STATE_SETFLAG(F_ESCTHROUGHOUT) + NEXT(1, 1) + } + break; + case SI: + if (CONFIG_ISSET(NO_SHIFT)) + goto bypass; + STATE_CLEARFLAG(F_SHIFTED) + NEXT_IN(1) + break; + case SO: + if (CONFIG_ISSET(NO_SHIFT)) + goto bypass; + STATE_SETFLAG(F_SHIFTED) + NEXT_IN(1) + break; + case LF: + STATE_CLEARFLAG(F_SHIFTED) + WRITE1(LF) + NEXT(1, 1) + break; + default: + if (c < 0x20) /* C0 */ + goto bypass; + else if (c >= 0x80) + return 1; + else { + const struct iso2022_designation *dsg; + unsigned char charset; + ucs4_t decoded; + + if (STATE_GETFLAG(F_SHIFTED)) + charset = STATE_G1; + else + charset = STATE_G0; + + if (charset == CHARSET_ASCII) { +bypass: WRITE1(c) + NEXT(1, 1) + break; + } + + if (dsgcache != NULL && + dsgcache->mark == charset) + dsg = dsgcache; + else { + for (dsg = CONFIG_DESIGNATIONS; + dsg->mark != charset #ifdef Py_DEBUG - && dsg->mark != '\0' + && dsg->mark != '\0' #endif - ;dsg++) - /* noop */; - assert(dsg->mark != '\0'); - dsgcache = dsg; - } - - REQUIRE_INBUF(dsg->width) - decoded = dsg->decoder(*inbuf); - if (decoded == MAP_UNMAPPABLE) - return dsg->width; - - if (decoded < 0x10000) { - WRITE1(decoded) - NEXT_OUT(1) - } - else if (decoded < 0x30000) { - WRITEUCS4(decoded) - } - else { /* JIS X 0213 pairs */ - WRITE2(decoded >> 16, decoded & 0xffff) - NEXT_OUT(2) - } - NEXT_IN(dsg->width) - } - break; - } - } - return 0; + ;dsg++) + /* noop */; + assert(dsg->mark != '\0'); + dsgcache = dsg; + } + + REQUIRE_INBUF(dsg->width) + decoded = dsg->decoder(*inbuf); + if (decoded == MAP_UNMAPPABLE) + return dsg->width; + + if (decoded < 0x10000) { + WRITE1(decoded) + NEXT_OUT(1) + } + else if (decoded < 0x30000) { + WRITEUCS4(decoded) + } + else { /* JIS X 0213 pairs */ + WRITE2(decoded >> 16, decoded & 0xffff) + NEXT_OUT(2) + } + NEXT_IN(dsg->width) + } + break; + } + } + return 0; } /*-*- mapping table holders -*-*/ @@ -567,542 +567,542 @@ static int ksx1001_init(void) { - static int initialized = 0; + static int initialized = 0; - if (!initialized && ( - IMPORT_MAP(kr, cp949, &cp949_encmap, NULL) || - IMPORT_MAP(kr, ksx1001, NULL, &ksx1001_decmap))) - return -1; - initialized = 1; - return 0; + if (!initialized && ( + IMPORT_MAP(kr, cp949, &cp949_encmap, NULL) || + IMPORT_MAP(kr, ksx1001, NULL, &ksx1001_decmap))) + return -1; + initialized = 1; + return 0; } static ucs4_t ksx1001_decoder(const unsigned char *data) { - ucs4_t u; - TRYMAP_DEC(ksx1001, u, data[0], data[1]) - return u; - else - return MAP_UNMAPPABLE; + ucs4_t u; + TRYMAP_DEC(ksx1001, u, data[0], data[1]) + return u; + else + return MAP_UNMAPPABLE; } static DBCHAR ksx1001_encoder(const ucs4_t *data, Py_ssize_t *length) { - DBCHAR coded; - assert(*length == 1); - if (*data < 0x10000) { - TRYMAP_ENC(cp949, coded, *data) - if (!(coded & 0x8000)) - return coded; - } - return MAP_UNMAPPABLE; + DBCHAR coded; + assert(*length == 1); + if (*data < 0x10000) { + TRYMAP_ENC(cp949, coded, *data) + if (!(coded & 0x8000)) + return coded; + } + return MAP_UNMAPPABLE; } static int jisx0208_init(void) { - static int initialized = 0; + static int initialized = 0; - if (!initialized && ( - IMPORT_MAP(jp, jisxcommon, &jisxcommon_encmap, NULL) || - IMPORT_MAP(jp, jisx0208, NULL, &jisx0208_decmap))) - return -1; - initialized = 1; - return 0; + if (!initialized && ( + IMPORT_MAP(jp, jisxcommon, &jisxcommon_encmap, NULL) || + IMPORT_MAP(jp, jisx0208, NULL, &jisx0208_decmap))) + return -1; + initialized = 1; + return 0; } static ucs4_t jisx0208_decoder(const unsigned char *data) { - ucs4_t u; - if (data[0] == 0x21 && data[1] == 0x40) /* F/W REVERSE SOLIDUS */ - return 0xff3c; - else TRYMAP_DEC(jisx0208, u, data[0], data[1]) - return u; - else - return MAP_UNMAPPABLE; + ucs4_t u; + if (data[0] == 0x21 && data[1] == 0x40) /* F/W REVERSE SOLIDUS */ + return 0xff3c; + else TRYMAP_DEC(jisx0208, u, data[0], data[1]) + return u; + else + return MAP_UNMAPPABLE; } static DBCHAR jisx0208_encoder(const ucs4_t *data, Py_ssize_t *length) { - DBCHAR coded; - assert(*length == 1); - if (*data < 0x10000) { - if (*data == 0xff3c) /* F/W REVERSE SOLIDUS */ - return 0x2140; - else TRYMAP_ENC(jisxcommon, coded, *data) { - if (!(coded & 0x8000)) - return coded; - } - } - return MAP_UNMAPPABLE; + DBCHAR coded; + assert(*length == 1); + if (*data < 0x10000) { + if (*data == 0xff3c) /* F/W REVERSE SOLIDUS */ + return 0x2140; + else TRYMAP_ENC(jisxcommon, coded, *data) { + if (!(coded & 0x8000)) + return coded; + } + } + return MAP_UNMAPPABLE; } static int jisx0212_init(void) { - static int initialized = 0; + static int initialized = 0; - if (!initialized && ( - IMPORT_MAP(jp, jisxcommon, &jisxcommon_encmap, NULL) || - IMPORT_MAP(jp, jisx0212, NULL, &jisx0212_decmap))) - return -1; - initialized = 1; - return 0; + if (!initialized && ( + IMPORT_MAP(jp, jisxcommon, &jisxcommon_encmap, NULL) || + IMPORT_MAP(jp, jisx0212, NULL, &jisx0212_decmap))) + return -1; + initialized = 1; + return 0; } static ucs4_t jisx0212_decoder(const unsigned char *data) { - ucs4_t u; - TRYMAP_DEC(jisx0212, u, data[0], data[1]) - return u; - else - return MAP_UNMAPPABLE; + ucs4_t u; + TRYMAP_DEC(jisx0212, u, data[0], data[1]) + return u; + else + return MAP_UNMAPPABLE; } static DBCHAR jisx0212_encoder(const ucs4_t *data, Py_ssize_t *length) { - DBCHAR coded; - assert(*length == 1); - if (*data < 0x10000) { - TRYMAP_ENC(jisxcommon, coded, *data) { - if (coded & 0x8000) - return coded & 0x7fff; - } - } - return MAP_UNMAPPABLE; + DBCHAR coded; + assert(*length == 1); + if (*data < 0x10000) { + TRYMAP_ENC(jisxcommon, coded, *data) { + if (coded & 0x8000) + return coded & 0x7fff; + } + } + return MAP_UNMAPPABLE; } static int jisx0213_init(void) { - static int initialized = 0; + static int initialized = 0; - if (!initialized && ( - jisx0208_init() || - IMPORT_MAP(jp, jisx0213_bmp, - &jisx0213_bmp_encmap, NULL) || - IMPORT_MAP(jp, jisx0213_1_bmp, - NULL, &jisx0213_1_bmp_decmap) || - IMPORT_MAP(jp, jisx0213_2_bmp, - NULL, &jisx0213_2_bmp_decmap) || - IMPORT_MAP(jp, jisx0213_emp, - &jisx0213_emp_encmap, NULL) || - IMPORT_MAP(jp, jisx0213_1_emp, - NULL, &jisx0213_1_emp_decmap) || - IMPORT_MAP(jp, jisx0213_2_emp, - NULL, &jisx0213_2_emp_decmap) || - IMPORT_MAP(jp, jisx0213_pair, &jisx0213_pair_encmap, - &jisx0213_pair_decmap))) - return -1; - initialized = 1; - return 0; + if (!initialized && ( + jisx0208_init() || + IMPORT_MAP(jp, jisx0213_bmp, + &jisx0213_bmp_encmap, NULL) || + IMPORT_MAP(jp, jisx0213_1_bmp, + NULL, &jisx0213_1_bmp_decmap) || + IMPORT_MAP(jp, jisx0213_2_bmp, + NULL, &jisx0213_2_bmp_decmap) || + IMPORT_MAP(jp, jisx0213_emp, + &jisx0213_emp_encmap, NULL) || + IMPORT_MAP(jp, jisx0213_1_emp, + NULL, &jisx0213_1_emp_decmap) || + IMPORT_MAP(jp, jisx0213_2_emp, + NULL, &jisx0213_2_emp_decmap) || + IMPORT_MAP(jp, jisx0213_pair, &jisx0213_pair_encmap, + &jisx0213_pair_decmap))) + return -1; + initialized = 1; + return 0; } #define config ((void *)2000) static ucs4_t jisx0213_2000_1_decoder(const unsigned char *data) { - ucs4_t u; - EMULATE_JISX0213_2000_DECODE_PLANE1(u, data[0], data[1]) - else if (data[0] == 0x21 && data[1] == 0x40) /* F/W REVERSE SOLIDUS */ - return 0xff3c; - else TRYMAP_DEC(jisx0208, u, data[0], data[1]); - else TRYMAP_DEC(jisx0213_1_bmp, u, data[0], data[1]); - else TRYMAP_DEC(jisx0213_1_emp, u, data[0], data[1]) - u |= 0x20000; - else TRYMAP_DEC(jisx0213_pair, u, data[0], data[1]); - else - return MAP_UNMAPPABLE; - return u; + ucs4_t u; + EMULATE_JISX0213_2000_DECODE_PLANE1(u, data[0], data[1]) + else if (data[0] == 0x21 && data[1] == 0x40) /* F/W REVERSE SOLIDUS */ + return 0xff3c; + else TRYMAP_DEC(jisx0208, u, data[0], data[1]); + else TRYMAP_DEC(jisx0213_1_bmp, u, data[0], data[1]); + else TRYMAP_DEC(jisx0213_1_emp, u, data[0], data[1]) + u |= 0x20000; + else TRYMAP_DEC(jisx0213_pair, u, data[0], data[1]); + else + return MAP_UNMAPPABLE; + return u; } static ucs4_t jisx0213_2000_2_decoder(const unsigned char *data) { - ucs4_t u; - EMULATE_JISX0213_2000_DECODE_PLANE2(u, data[0], data[1]) - TRYMAP_DEC(jisx0213_2_bmp, u, data[0], data[1]); - else TRYMAP_DEC(jisx0213_2_emp, u, data[0], data[1]) - u |= 0x20000; - else - return MAP_UNMAPPABLE; - return u; + ucs4_t u; + EMULATE_JISX0213_2000_DECODE_PLANE2(u, data[0], data[1]) + TRYMAP_DEC(jisx0213_2_bmp, u, data[0], data[1]); + else TRYMAP_DEC(jisx0213_2_emp, u, data[0], data[1]) + u |= 0x20000; + else + return MAP_UNMAPPABLE; + return u; } #undef config static ucs4_t jisx0213_2004_1_decoder(const unsigned char *data) { - ucs4_t u; - if (data[0] == 0x21 && data[1] == 0x40) /* F/W REVERSE SOLIDUS */ - return 0xff3c; - else TRYMAP_DEC(jisx0208, u, data[0], data[1]); - else TRYMAP_DEC(jisx0213_1_bmp, u, data[0], data[1]); - else TRYMAP_DEC(jisx0213_1_emp, u, data[0], data[1]) - u |= 0x20000; - else TRYMAP_DEC(jisx0213_pair, u, data[0], data[1]); - else - return MAP_UNMAPPABLE; - return u; + ucs4_t u; + if (data[0] == 0x21 && data[1] == 0x40) /* F/W REVERSE SOLIDUS */ + return 0xff3c; + else TRYMAP_DEC(jisx0208, u, data[0], data[1]); + else TRYMAP_DEC(jisx0213_1_bmp, u, data[0], data[1]); + else TRYMAP_DEC(jisx0213_1_emp, u, data[0], data[1]) + u |= 0x20000; + else TRYMAP_DEC(jisx0213_pair, u, data[0], data[1]); + else + return MAP_UNMAPPABLE; + return u; } static ucs4_t jisx0213_2004_2_decoder(const unsigned char *data) { - ucs4_t u; - TRYMAP_DEC(jisx0213_2_bmp, u, data[0], data[1]); - else TRYMAP_DEC(jisx0213_2_emp, u, data[0], data[1]) - u |= 0x20000; - else - return MAP_UNMAPPABLE; - return u; + ucs4_t u; + TRYMAP_DEC(jisx0213_2_bmp, u, data[0], data[1]); + else TRYMAP_DEC(jisx0213_2_emp, u, data[0], data[1]) + u |= 0x20000; + else + return MAP_UNMAPPABLE; + return u; } static DBCHAR jisx0213_encoder(const ucs4_t *data, Py_ssize_t *length, void *config) { - DBCHAR coded; + DBCHAR coded; - switch (*length) { - case 1: /* first character */ - if (*data >= 0x10000) { - if ((*data) >> 16 == 0x20000 >> 16) { - EMULATE_JISX0213_2000_ENCODE_EMP(coded, *data) - else TRYMAP_ENC(jisx0213_emp, coded, - (*data) & 0xffff) - return coded; - } - return MAP_UNMAPPABLE; - } - - EMULATE_JISX0213_2000_ENCODE_BMP(coded, *data) - else TRYMAP_ENC(jisx0213_bmp, coded, *data) { - if (coded == MULTIC) - return MAP_MULTIPLE_AVAIL; - } - else TRYMAP_ENC(jisxcommon, coded, *data) { - if (coded & 0x8000) - return MAP_UNMAPPABLE; - } - else - return MAP_UNMAPPABLE; - return coded; - case 2: /* second character of unicode pair */ - coded = find_pairencmap((ucs2_t)data[0], (ucs2_t)data[1], - jisx0213_pair_encmap, JISX0213_ENCPAIRS); - if (coded == DBCINV) { - *length = 1; - coded = find_pairencmap((ucs2_t)data[0], 0, - jisx0213_pair_encmap, JISX0213_ENCPAIRS); - if (coded == DBCINV) - return MAP_UNMAPPABLE; - } - else - return coded; - case -1: /* flush unterminated */ - *length = 1; - coded = find_pairencmap((ucs2_t)data[0], 0, - jisx0213_pair_encmap, JISX0213_ENCPAIRS); - if (coded == DBCINV) - return MAP_UNMAPPABLE; - else - return coded; - default: - return MAP_UNMAPPABLE; - } + switch (*length) { + case 1: /* first character */ + if (*data >= 0x10000) { + if ((*data) >> 16 == 0x20000 >> 16) { + EMULATE_JISX0213_2000_ENCODE_EMP(coded, *data) + else TRYMAP_ENC(jisx0213_emp, coded, + (*data) & 0xffff) + return coded; + } + return MAP_UNMAPPABLE; + } + + EMULATE_JISX0213_2000_ENCODE_BMP(coded, *data) + else TRYMAP_ENC(jisx0213_bmp, coded, *data) { + if (coded == MULTIC) + return MAP_MULTIPLE_AVAIL; + } + else TRYMAP_ENC(jisxcommon, coded, *data) { + if (coded & 0x8000) + return MAP_UNMAPPABLE; + } + else + return MAP_UNMAPPABLE; + return coded; + case 2: /* second character of unicode pair */ + coded = find_pairencmap((ucs2_t)data[0], (ucs2_t)data[1], + jisx0213_pair_encmap, JISX0213_ENCPAIRS); + if (coded == DBCINV) { + *length = 1; + coded = find_pairencmap((ucs2_t)data[0], 0, + jisx0213_pair_encmap, JISX0213_ENCPAIRS); + if (coded == DBCINV) + return MAP_UNMAPPABLE; + } + else + return coded; + case -1: /* flush unterminated */ + *length = 1; + coded = find_pairencmap((ucs2_t)data[0], 0, + jisx0213_pair_encmap, JISX0213_ENCPAIRS); + if (coded == DBCINV) + return MAP_UNMAPPABLE; + else + return coded; + default: + return MAP_UNMAPPABLE; + } } static DBCHAR jisx0213_2000_1_encoder(const ucs4_t *data, Py_ssize_t *length) { - DBCHAR coded = jisx0213_encoder(data, length, (void *)2000); - if (coded == MAP_UNMAPPABLE || coded == MAP_MULTIPLE_AVAIL) - return coded; - else if (coded & 0x8000) - return MAP_UNMAPPABLE; - else - return coded; + DBCHAR coded = jisx0213_encoder(data, length, (void *)2000); + if (coded == MAP_UNMAPPABLE || coded == MAP_MULTIPLE_AVAIL) + return coded; + else if (coded & 0x8000) + return MAP_UNMAPPABLE; + else + return coded; } static DBCHAR jisx0213_2000_1_encoder_paironly(const ucs4_t *data, Py_ssize_t *length) { - DBCHAR coded; - Py_ssize_t ilength = *length; + DBCHAR coded; + Py_ssize_t ilength = *length; - coded = jisx0213_encoder(data, length, (void *)2000); - switch (ilength) { - case 1: - if (coded == MAP_MULTIPLE_AVAIL) - return MAP_MULTIPLE_AVAIL; - else - return MAP_UNMAPPABLE; - case 2: - if (*length != 2) - return MAP_UNMAPPABLE; - else - return coded; - default: - return MAP_UNMAPPABLE; - } + coded = jisx0213_encoder(data, length, (void *)2000); + switch (ilength) { + case 1: + if (coded == MAP_MULTIPLE_AVAIL) + return MAP_MULTIPLE_AVAIL; + else + return MAP_UNMAPPABLE; + case 2: + if (*length != 2) + return MAP_UNMAPPABLE; + else + return coded; + default: + return MAP_UNMAPPABLE; + } } static DBCHAR jisx0213_2000_2_encoder(const ucs4_t *data, Py_ssize_t *length) { - DBCHAR coded = jisx0213_encoder(data, length, (void *)2000); - if (coded == MAP_UNMAPPABLE || coded == MAP_MULTIPLE_AVAIL) - return coded; - else if (coded & 0x8000) - return coded & 0x7fff; - else - return MAP_UNMAPPABLE; + DBCHAR coded = jisx0213_encoder(data, length, (void *)2000); + if (coded == MAP_UNMAPPABLE || coded == MAP_MULTIPLE_AVAIL) + return coded; + else if (coded & 0x8000) + return coded & 0x7fff; + else + return MAP_UNMAPPABLE; } static DBCHAR jisx0213_2004_1_encoder(const ucs4_t *data, Py_ssize_t *length) { - DBCHAR coded = jisx0213_encoder(data, length, NULL); - if (coded == MAP_UNMAPPABLE || coded == MAP_MULTIPLE_AVAIL) - return coded; - else if (coded & 0x8000) - return MAP_UNMAPPABLE; - else - return coded; + DBCHAR coded = jisx0213_encoder(data, length, NULL); + if (coded == MAP_UNMAPPABLE || coded == MAP_MULTIPLE_AVAIL) + return coded; + else if (coded & 0x8000) + return MAP_UNMAPPABLE; + else + return coded; } static DBCHAR jisx0213_2004_1_encoder_paironly(const ucs4_t *data, Py_ssize_t *length) { - DBCHAR coded; - Py_ssize_t ilength = *length; + DBCHAR coded; + Py_ssize_t ilength = *length; - coded = jisx0213_encoder(data, length, NULL); - switch (ilength) { - case 1: - if (coded == MAP_MULTIPLE_AVAIL) - return MAP_MULTIPLE_AVAIL; - else - return MAP_UNMAPPABLE; - case 2: - if (*length != 2) - return MAP_UNMAPPABLE; - else - return coded; - default: - return MAP_UNMAPPABLE; - } + coded = jisx0213_encoder(data, length, NULL); + switch (ilength) { + case 1: + if (coded == MAP_MULTIPLE_AVAIL) + return MAP_MULTIPLE_AVAIL; + else + return MAP_UNMAPPABLE; + case 2: + if (*length != 2) + return MAP_UNMAPPABLE; + else + return coded; + default: + return MAP_UNMAPPABLE; + } } static DBCHAR jisx0213_2004_2_encoder(const ucs4_t *data, Py_ssize_t *length) { - DBCHAR coded = jisx0213_encoder(data, length, NULL); - if (coded == MAP_UNMAPPABLE || coded == MAP_MULTIPLE_AVAIL) - return coded; - else if (coded & 0x8000) - return coded & 0x7fff; - else - return MAP_UNMAPPABLE; + DBCHAR coded = jisx0213_encoder(data, length, NULL); + if (coded == MAP_UNMAPPABLE || coded == MAP_MULTIPLE_AVAIL) + return coded; + else if (coded & 0x8000) + return coded & 0x7fff; + else + return MAP_UNMAPPABLE; } static ucs4_t jisx0201_r_decoder(const unsigned char *data) { - ucs4_t u; - JISX0201_R_DECODE(*data, u) - else return MAP_UNMAPPABLE; - return u; + ucs4_t u; + JISX0201_R_DECODE(*data, u) + else return MAP_UNMAPPABLE; + return u; } static DBCHAR jisx0201_r_encoder(const ucs4_t *data, Py_ssize_t *length) { - DBCHAR coded; - JISX0201_R_ENCODE(*data, coded) - else return MAP_UNMAPPABLE; - return coded; + DBCHAR coded; + JISX0201_R_ENCODE(*data, coded) + else return MAP_UNMAPPABLE; + return coded; } static ucs4_t jisx0201_k_decoder(const unsigned char *data) { - ucs4_t u; - JISX0201_K_DECODE(*data ^ 0x80, u) - else return MAP_UNMAPPABLE; - return u; + ucs4_t u; + JISX0201_K_DECODE(*data ^ 0x80, u) + else return MAP_UNMAPPABLE; + return u; } static DBCHAR jisx0201_k_encoder(const ucs4_t *data, Py_ssize_t *length) { - DBCHAR coded; - JISX0201_K_ENCODE(*data, coded) - else return MAP_UNMAPPABLE; - return coded - 0x80; + DBCHAR coded; + JISX0201_K_ENCODE(*data, coded) + else return MAP_UNMAPPABLE; + return coded - 0x80; } static int gb2312_init(void) { - static int initialized = 0; + static int initialized = 0; - if (!initialized && ( - IMPORT_MAP(cn, gbcommon, &gbcommon_encmap, NULL) || - IMPORT_MAP(cn, gb2312, NULL, &gb2312_decmap))) - return -1; - initialized = 1; - return 0; + if (!initialized && ( + IMPORT_MAP(cn, gbcommon, &gbcommon_encmap, NULL) || + IMPORT_MAP(cn, gb2312, NULL, &gb2312_decmap))) + return -1; + initialized = 1; + return 0; } static ucs4_t gb2312_decoder(const unsigned char *data) { - ucs4_t u; - TRYMAP_DEC(gb2312, u, data[0], data[1]) - return u; - else - return MAP_UNMAPPABLE; + ucs4_t u; + TRYMAP_DEC(gb2312, u, data[0], data[1]) + return u; + else + return MAP_UNMAPPABLE; } static DBCHAR gb2312_encoder(const ucs4_t *data, Py_ssize_t *length) { - DBCHAR coded; - assert(*length == 1); - if (*data < 0x10000) { - TRYMAP_ENC(gbcommon, coded, *data) { - if (!(coded & 0x8000)) - return coded; - } - } - return MAP_UNMAPPABLE; + DBCHAR coded; + assert(*length == 1); + if (*data < 0x10000) { + TRYMAP_ENC(gbcommon, coded, *data) { + if (!(coded & 0x8000)) + return coded; + } + } + return MAP_UNMAPPABLE; } static ucs4_t dummy_decoder(const unsigned char *data) { - return MAP_UNMAPPABLE; + return MAP_UNMAPPABLE; } static DBCHAR dummy_encoder(const ucs4_t *data, Py_ssize_t *length) { - return MAP_UNMAPPABLE; + return MAP_UNMAPPABLE; } /*-*- registry tables -*-*/ -#define REGISTRY_KSX1001_G0 { CHARSET_KSX1001, 0, 2, \ - ksx1001_init, \ - ksx1001_decoder, ksx1001_encoder } -#define REGISTRY_KSX1001_G1 { CHARSET_KSX1001, 1, 2, \ - ksx1001_init, \ - ksx1001_decoder, ksx1001_encoder } -#define REGISTRY_JISX0201_R { CHARSET_JISX0201_R, 0, 1, \ - NULL, \ - jisx0201_r_decoder, jisx0201_r_encoder } -#define REGISTRY_JISX0201_K { CHARSET_JISX0201_K, 0, 1, \ - NULL, \ - jisx0201_k_decoder, jisx0201_k_encoder } -#define REGISTRY_JISX0208 { CHARSET_JISX0208, 0, 2, \ - jisx0208_init, \ - jisx0208_decoder, jisx0208_encoder } -#define REGISTRY_JISX0208_O { CHARSET_JISX0208_O, 0, 2, \ - jisx0208_init, \ - jisx0208_decoder, jisx0208_encoder } -#define REGISTRY_JISX0212 { CHARSET_JISX0212, 0, 2, \ - jisx0212_init, \ - jisx0212_decoder, jisx0212_encoder } -#define REGISTRY_JISX0213_2000_1 { CHARSET_JISX0213_2000_1, 0, 2, \ - jisx0213_init, \ - jisx0213_2000_1_decoder, \ - jisx0213_2000_1_encoder } +#define REGISTRY_KSX1001_G0 { CHARSET_KSX1001, 0, 2, \ + ksx1001_init, \ + ksx1001_decoder, ksx1001_encoder } +#define REGISTRY_KSX1001_G1 { CHARSET_KSX1001, 1, 2, \ + ksx1001_init, \ + ksx1001_decoder, ksx1001_encoder } +#define REGISTRY_JISX0201_R { CHARSET_JISX0201_R, 0, 1, \ + NULL, \ + jisx0201_r_decoder, jisx0201_r_encoder } +#define REGISTRY_JISX0201_K { CHARSET_JISX0201_K, 0, 1, \ + NULL, \ + jisx0201_k_decoder, jisx0201_k_encoder } +#define REGISTRY_JISX0208 { CHARSET_JISX0208, 0, 2, \ + jisx0208_init, \ + jisx0208_decoder, jisx0208_encoder } +#define REGISTRY_JISX0208_O { CHARSET_JISX0208_O, 0, 2, \ + jisx0208_init, \ + jisx0208_decoder, jisx0208_encoder } +#define REGISTRY_JISX0212 { CHARSET_JISX0212, 0, 2, \ + jisx0212_init, \ + jisx0212_decoder, jisx0212_encoder } +#define REGISTRY_JISX0213_2000_1 { CHARSET_JISX0213_2000_1, 0, 2, \ + jisx0213_init, \ + jisx0213_2000_1_decoder, \ + jisx0213_2000_1_encoder } #define REGISTRY_JISX0213_2000_1_PAIRONLY { CHARSET_JISX0213_2000_1, 0, 2, \ - jisx0213_init, \ - jisx0213_2000_1_decoder, \ - jisx0213_2000_1_encoder_paironly } -#define REGISTRY_JISX0213_2000_2 { CHARSET_JISX0213_2, 0, 2, \ - jisx0213_init, \ - jisx0213_2000_2_decoder, \ - jisx0213_2000_2_encoder } -#define REGISTRY_JISX0213_2004_1 { CHARSET_JISX0213_2004_1, 0, 2, \ - jisx0213_init, \ - jisx0213_2004_1_decoder, \ - jisx0213_2004_1_encoder } + jisx0213_init, \ + jisx0213_2000_1_decoder, \ + jisx0213_2000_1_encoder_paironly } +#define REGISTRY_JISX0213_2000_2 { CHARSET_JISX0213_2, 0, 2, \ + jisx0213_init, \ + jisx0213_2000_2_decoder, \ + jisx0213_2000_2_encoder } +#define REGISTRY_JISX0213_2004_1 { CHARSET_JISX0213_2004_1, 0, 2, \ + jisx0213_init, \ + jisx0213_2004_1_decoder, \ + jisx0213_2004_1_encoder } #define REGISTRY_JISX0213_2004_1_PAIRONLY { CHARSET_JISX0213_2004_1, 0, 2, \ - jisx0213_init, \ - jisx0213_2004_1_decoder, \ - jisx0213_2004_1_encoder_paironly } -#define REGISTRY_JISX0213_2004_2 { CHARSET_JISX0213_2, 0, 2, \ - jisx0213_init, \ - jisx0213_2004_2_decoder, \ - jisx0213_2004_2_encoder } -#define REGISTRY_GB2312 { CHARSET_GB2312, 0, 2, \ - gb2312_init, \ - gb2312_decoder, gb2312_encoder } -#define REGISTRY_CNS11643_1 { CHARSET_CNS11643_1, 1, 2, \ - cns11643_init, \ - cns11643_1_decoder, cns11643_1_encoder } -#define REGISTRY_CNS11643_2 { CHARSET_CNS11643_2, 2, 2, \ - cns11643_init, \ - cns11643_2_decoder, cns11643_2_encoder } -#define REGISTRY_ISO8859_1 { CHARSET_ISO8859_1, 2, 1, \ - NULL, dummy_decoder, dummy_encoder } -#define REGISTRY_ISO8859_7 { CHARSET_ISO8859_7, 2, 1, \ - NULL, dummy_decoder, dummy_encoder } -#define REGISTRY_SENTINEL { 0, } -#define CONFIGDEF(var, attrs) \ - static const struct iso2022_config iso2022_##var##_config = { \ - attrs, iso2022_##var##_designations \ - }; + jisx0213_init, \ + jisx0213_2004_1_decoder, \ + jisx0213_2004_1_encoder_paironly } +#define REGISTRY_JISX0213_2004_2 { CHARSET_JISX0213_2, 0, 2, \ + jisx0213_init, \ + jisx0213_2004_2_decoder, \ + jisx0213_2004_2_encoder } +#define REGISTRY_GB2312 { CHARSET_GB2312, 0, 2, \ + gb2312_init, \ + gb2312_decoder, gb2312_encoder } +#define REGISTRY_CNS11643_1 { CHARSET_CNS11643_1, 1, 2, \ + cns11643_init, \ + cns11643_1_decoder, cns11643_1_encoder } +#define REGISTRY_CNS11643_2 { CHARSET_CNS11643_2, 2, 2, \ + cns11643_init, \ + cns11643_2_decoder, cns11643_2_encoder } +#define REGISTRY_ISO8859_1 { CHARSET_ISO8859_1, 2, 1, \ + NULL, dummy_decoder, dummy_encoder } +#define REGISTRY_ISO8859_7 { CHARSET_ISO8859_7, 2, 1, \ + NULL, dummy_decoder, dummy_encoder } +#define REGISTRY_SENTINEL { 0, } +#define CONFIGDEF(var, attrs) \ + static const struct iso2022_config iso2022_##var##_config = { \ + attrs, iso2022_##var##_designations \ + }; static const struct iso2022_designation iso2022_kr_designations[] = { - REGISTRY_KSX1001_G1, REGISTRY_SENTINEL + REGISTRY_KSX1001_G1, REGISTRY_SENTINEL }; CONFIGDEF(kr, 0) static const struct iso2022_designation iso2022_jp_designations[] = { - REGISTRY_JISX0208, REGISTRY_JISX0201_R, REGISTRY_JISX0208_O, - REGISTRY_SENTINEL + REGISTRY_JISX0208, REGISTRY_JISX0201_R, REGISTRY_JISX0208_O, + REGISTRY_SENTINEL }; CONFIGDEF(jp, NO_SHIFT | USE_JISX0208_EXT) static const struct iso2022_designation iso2022_jp_1_designations[] = { - REGISTRY_JISX0208, REGISTRY_JISX0212, REGISTRY_JISX0201_R, - REGISTRY_JISX0208_O, REGISTRY_SENTINEL + REGISTRY_JISX0208, REGISTRY_JISX0212, REGISTRY_JISX0201_R, + REGISTRY_JISX0208_O, REGISTRY_SENTINEL }; CONFIGDEF(jp_1, NO_SHIFT | USE_JISX0208_EXT) static const struct iso2022_designation iso2022_jp_2_designations[] = { - REGISTRY_JISX0208, REGISTRY_JISX0212, REGISTRY_KSX1001_G0, - REGISTRY_GB2312, REGISTRY_JISX0201_R, REGISTRY_JISX0208_O, - REGISTRY_ISO8859_1, REGISTRY_ISO8859_7, REGISTRY_SENTINEL + REGISTRY_JISX0208, REGISTRY_JISX0212, REGISTRY_KSX1001_G0, + REGISTRY_GB2312, REGISTRY_JISX0201_R, REGISTRY_JISX0208_O, + REGISTRY_ISO8859_1, REGISTRY_ISO8859_7, REGISTRY_SENTINEL }; CONFIGDEF(jp_2, NO_SHIFT | USE_G2 | USE_JISX0208_EXT) static const struct iso2022_designation iso2022_jp_2004_designations[] = { - REGISTRY_JISX0213_2004_1_PAIRONLY, REGISTRY_JISX0208, - REGISTRY_JISX0213_2004_1, REGISTRY_JISX0213_2004_2, REGISTRY_SENTINEL + REGISTRY_JISX0213_2004_1_PAIRONLY, REGISTRY_JISX0208, + REGISTRY_JISX0213_2004_1, REGISTRY_JISX0213_2004_2, REGISTRY_SENTINEL }; CONFIGDEF(jp_2004, NO_SHIFT | USE_JISX0208_EXT) static const struct iso2022_designation iso2022_jp_3_designations[] = { - REGISTRY_JISX0213_2000_1_PAIRONLY, REGISTRY_JISX0208, - REGISTRY_JISX0213_2000_1, REGISTRY_JISX0213_2000_2, REGISTRY_SENTINEL + REGISTRY_JISX0213_2000_1_PAIRONLY, REGISTRY_JISX0208, + REGISTRY_JISX0213_2000_1, REGISTRY_JISX0213_2000_2, REGISTRY_SENTINEL }; CONFIGDEF(jp_3, NO_SHIFT | USE_JISX0208_EXT) static const struct iso2022_designation iso2022_jp_ext_designations[] = { - REGISTRY_JISX0208, REGISTRY_JISX0212, REGISTRY_JISX0201_R, - REGISTRY_JISX0201_K, REGISTRY_JISX0208_O, REGISTRY_SENTINEL + REGISTRY_JISX0208, REGISTRY_JISX0212, REGISTRY_JISX0201_R, + REGISTRY_JISX0201_K, REGISTRY_JISX0208_O, REGISTRY_SENTINEL }; CONFIGDEF(jp_ext, NO_SHIFT | USE_JISX0208_EXT) @@ -1111,11 +1111,11 @@ /* no mapping table here */ END_MAPPINGS_LIST -#define ISO2022_CODEC(variation) { \ - "iso2022_" #variation, \ - &iso2022_##variation##_config, \ - iso2022_codec_init, \ - _STATEFUL_METHODS(iso2022) \ +#define ISO2022_CODEC(variation) { \ + "iso2022_" #variation, \ + &iso2022_##variation##_config, \ + iso2022_codec_init, \ + _STATEFUL_METHODS(iso2022) \ }, BEGIN_CODECS_LIST Modified: python/branches/release31-maint/Modules/cjkcodecs/_codecs_jp.c ============================================================================== --- python/branches/release31-maint/Modules/cjkcodecs/_codecs_jp.c (original) +++ python/branches/release31-maint/Modules/cjkcodecs/_codecs_jp.c Sun May 9 18:14:21 2010 @@ -19,124 +19,124 @@ ENCODER(cp932) { - while (inleft > 0) { - Py_UNICODE c = IN1; - DBCHAR code; - unsigned char c1, c2; - - if (c <= 0x80) { - WRITE1((unsigned char)c) - NEXT(1, 1) - continue; - } - else if (c >= 0xff61 && c <= 0xff9f) { - WRITE1(c - 0xfec0) - NEXT(1, 1) - continue; - } - else if (c >= 0xf8f0 && c <= 0xf8f3) { - /* Windows compatibility */ - REQUIRE_OUTBUF(1) - if (c == 0xf8f0) - OUT1(0xa0) - else - OUT1(c - 0xfef1 + 0xfd) - NEXT(1, 1) - continue; - } - - UCS4INVALID(c) - REQUIRE_OUTBUF(2) - - TRYMAP_ENC(cp932ext, code, c) { - OUT1(code >> 8) - OUT2(code & 0xff) - } - else TRYMAP_ENC(jisxcommon, code, c) { - if (code & 0x8000) /* MSB set: JIS X 0212 */ - return 1; - - /* JIS X 0208 */ - c1 = code >> 8; - c2 = code & 0xff; - c2 = (((c1 - 0x21) & 1) ? 0x5e : 0) + (c2 - 0x21); - c1 = (c1 - 0x21) >> 1; - OUT1(c1 < 0x1f ? c1 + 0x81 : c1 + 0xc1) - OUT2(c2 < 0x3f ? c2 + 0x40 : c2 + 0x41) - } - else if (c >= 0xe000 && c < 0xe758) { - /* User-defined area */ - c1 = (Py_UNICODE)(c - 0xe000) / 188; - c2 = (Py_UNICODE)(c - 0xe000) % 188; - OUT1(c1 + 0xf0) - OUT2(c2 < 0x3f ? c2 + 0x40 : c2 + 0x41) - } - else - return 1; + while (inleft > 0) { + Py_UNICODE c = IN1; + DBCHAR code; + unsigned char c1, c2; + + if (c <= 0x80) { + WRITE1((unsigned char)c) + NEXT(1, 1) + continue; + } + else if (c >= 0xff61 && c <= 0xff9f) { + WRITE1(c - 0xfec0) + NEXT(1, 1) + continue; + } + else if (c >= 0xf8f0 && c <= 0xf8f3) { + /* Windows compatibility */ + REQUIRE_OUTBUF(1) + if (c == 0xf8f0) + OUT1(0xa0) + else + OUT1(c - 0xfef1 + 0xfd) + NEXT(1, 1) + continue; + } + + UCS4INVALID(c) + REQUIRE_OUTBUF(2) + + TRYMAP_ENC(cp932ext, code, c) { + OUT1(code >> 8) + OUT2(code & 0xff) + } + else TRYMAP_ENC(jisxcommon, code, c) { + if (code & 0x8000) /* MSB set: JIS X 0212 */ + return 1; + + /* JIS X 0208 */ + c1 = code >> 8; + c2 = code & 0xff; + c2 = (((c1 - 0x21) & 1) ? 0x5e : 0) + (c2 - 0x21); + c1 = (c1 - 0x21) >> 1; + OUT1(c1 < 0x1f ? c1 + 0x81 : c1 + 0xc1) + OUT2(c2 < 0x3f ? c2 + 0x40 : c2 + 0x41) + } + else if (c >= 0xe000 && c < 0xe758) { + /* User-defined area */ + c1 = (Py_UNICODE)(c - 0xe000) / 188; + c2 = (Py_UNICODE)(c - 0xe000) % 188; + OUT1(c1 + 0xf0) + OUT2(c2 < 0x3f ? c2 + 0x40 : c2 + 0x41) + } + else + return 1; - NEXT(1, 2) - } + NEXT(1, 2) + } - return 0; + return 0; } DECODER(cp932) { - while (inleft > 0) { - unsigned char c = IN1, c2; + while (inleft > 0) { + unsigned char c = IN1, c2; - REQUIRE_OUTBUF(1) - if (c <= 0x80) { - OUT1(c) - NEXT(1, 1) - continue; - } - else if (c >= 0xa0 && c <= 0xdf) { - if (c == 0xa0) - OUT1(0xf8f0) /* half-width katakana */ - else - OUT1(0xfec0 + c) - NEXT(1, 1) - continue; - } - else if (c >= 0xfd/* && c <= 0xff*/) { - /* Windows compatibility */ - OUT1(0xf8f1 - 0xfd + c) - NEXT(1, 1) - continue; - } - - REQUIRE_INBUF(2) - c2 = IN2; - - TRYMAP_DEC(cp932ext, **outbuf, c, c2); - else if ((c >= 0x81 && c <= 0x9f) || (c >= 0xe0 && c <= 0xea)){ - if (c2 < 0x40 || (c2 > 0x7e && c2 < 0x80) || c2 > 0xfc) - return 2; - - c = (c < 0xe0 ? c - 0x81 : c - 0xc1); - c2 = (c2 < 0x80 ? c2 - 0x40 : c2 - 0x41); - c = (2 * c + (c2 < 0x5e ? 0 : 1) + 0x21); - c2 = (c2 < 0x5e ? c2 : c2 - 0x5e) + 0x21; - - TRYMAP_DEC(jisx0208, **outbuf, c, c2); - else return 2; - } - else if (c >= 0xf0 && c <= 0xf9) { - if ((c2 >= 0x40 && c2 <= 0x7e) || - (c2 >= 0x80 && c2 <= 0xfc)) - OUT1(0xe000 + 188 * (c - 0xf0) + - (c2 < 0x80 ? c2 - 0x40 : c2 - 0x41)) - else - return 2; - } - else - return 2; + REQUIRE_OUTBUF(1) + if (c <= 0x80) { + OUT1(c) + NEXT(1, 1) + continue; + } + else if (c >= 0xa0 && c <= 0xdf) { + if (c == 0xa0) + OUT1(0xf8f0) /* half-width katakana */ + else + OUT1(0xfec0 + c) + NEXT(1, 1) + continue; + } + else if (c >= 0xfd/* && c <= 0xff*/) { + /* Windows compatibility */ + OUT1(0xf8f1 - 0xfd + c) + NEXT(1, 1) + continue; + } + + REQUIRE_INBUF(2) + c2 = IN2; + + TRYMAP_DEC(cp932ext, **outbuf, c, c2); + else if ((c >= 0x81 && c <= 0x9f) || (c >= 0xe0 && c <= 0xea)){ + if (c2 < 0x40 || (c2 > 0x7e && c2 < 0x80) || c2 > 0xfc) + return 2; + + c = (c < 0xe0 ? c - 0x81 : c - 0xc1); + c2 = (c2 < 0x80 ? c2 - 0x40 : c2 - 0x41); + c = (2 * c + (c2 < 0x5e ? 0 : 1) + 0x21); + c2 = (c2 < 0x5e ? c2 : c2 - 0x5e) + 0x21; + + TRYMAP_DEC(jisx0208, **outbuf, c, c2); + else return 2; + } + else if (c >= 0xf0 && c <= 0xf9) { + if ((c2 >= 0x40 && c2 <= 0x7e) || + (c2 >= 0x80 && c2 <= 0xfc)) + OUT1(0xe000 + 188 * (c - 0xf0) + + (c2 < 0x80 ? c2 - 0x40 : c2 - 0x41)) + else + return 2; + } + else + return 2; - NEXT(2, 1) - } + NEXT(2, 1) + } - return 0; + return 0; } @@ -146,166 +146,166 @@ ENCODER(euc_jis_2004) { - while (inleft > 0) { - ucs4_t c = IN1; - DBCHAR code; - Py_ssize_t insize; - - if (c < 0x80) { - WRITE1(c) - NEXT(1, 1) - continue; - } - - DECODE_SURROGATE(c) - insize = GET_INSIZE(c); - - if (c <= 0xFFFF) { - EMULATE_JISX0213_2000_ENCODE_BMP(code, c) - else TRYMAP_ENC(jisx0213_bmp, code, c) { - if (code == MULTIC) { - if (inleft < 2) { - if (flags & MBENC_FLUSH) { - code = find_pairencmap( - (ucs2_t)c, 0, - jisx0213_pair_encmap, - JISX0213_ENCPAIRS); - if (code == DBCINV) - return 1; - } - else - return MBERR_TOOFEW; - } - else { - code = find_pairencmap( - (ucs2_t)c, (*inbuf)[1], - jisx0213_pair_encmap, - JISX0213_ENCPAIRS); - if (code == DBCINV) { - code = find_pairencmap( - (ucs2_t)c, 0, - jisx0213_pair_encmap, - JISX0213_ENCPAIRS); - if (code == DBCINV) - return 1; - } else - insize = 2; - } - } - } - else TRYMAP_ENC(jisxcommon, code, c); - else if (c >= 0xff61 && c <= 0xff9f) { - /* JIS X 0201 half-width katakana */ - WRITE2(0x8e, c - 0xfec0) - NEXT(1, 2) - continue; - } - else if (c == 0xff3c) - /* F/W REVERSE SOLIDUS (see NOTES) */ - code = 0x2140; - else if (c == 0xff5e) - /* F/W TILDE (see NOTES) */ - code = 0x2232; - else - return 1; - } - else if (c >> 16 == EMPBASE >> 16) { - EMULATE_JISX0213_2000_ENCODE_EMP(code, c) - else TRYMAP_ENC(jisx0213_emp, code, c & 0xffff); - else return insize; - } - else - return insize; - - if (code & 0x8000) { - /* Codeset 2 */ - WRITE3(0x8f, code >> 8, (code & 0xFF) | 0x80) - NEXT(insize, 3) - } else { - /* Codeset 1 */ - WRITE2((code >> 8) | 0x80, (code & 0xFF) | 0x80) - NEXT(insize, 2) - } - } + while (inleft > 0) { + ucs4_t c = IN1; + DBCHAR code; + Py_ssize_t insize; + + if (c < 0x80) { + WRITE1(c) + NEXT(1, 1) + continue; + } + + DECODE_SURROGATE(c) + insize = GET_INSIZE(c); + + if (c <= 0xFFFF) { + EMULATE_JISX0213_2000_ENCODE_BMP(code, c) + else TRYMAP_ENC(jisx0213_bmp, code, c) { + if (code == MULTIC) { + if (inleft < 2) { + if (flags & MBENC_FLUSH) { + code = find_pairencmap( + (ucs2_t)c, 0, + jisx0213_pair_encmap, + JISX0213_ENCPAIRS); + if (code == DBCINV) + return 1; + } + else + return MBERR_TOOFEW; + } + else { + code = find_pairencmap( + (ucs2_t)c, (*inbuf)[1], + jisx0213_pair_encmap, + JISX0213_ENCPAIRS); + if (code == DBCINV) { + code = find_pairencmap( + (ucs2_t)c, 0, + jisx0213_pair_encmap, + JISX0213_ENCPAIRS); + if (code == DBCINV) + return 1; + } else + insize = 2; + } + } + } + else TRYMAP_ENC(jisxcommon, code, c); + else if (c >= 0xff61 && c <= 0xff9f) { + /* JIS X 0201 half-width katakana */ + WRITE2(0x8e, c - 0xfec0) + NEXT(1, 2) + continue; + } + else if (c == 0xff3c) + /* F/W REVERSE SOLIDUS (see NOTES) */ + code = 0x2140; + else if (c == 0xff5e) + /* F/W TILDE (see NOTES) */ + code = 0x2232; + else + return 1; + } + else if (c >> 16 == EMPBASE >> 16) { + EMULATE_JISX0213_2000_ENCODE_EMP(code, c) + else TRYMAP_ENC(jisx0213_emp, code, c & 0xffff); + else return insize; + } + else + return insize; + + if (code & 0x8000) { + /* Codeset 2 */ + WRITE3(0x8f, code >> 8, (code & 0xFF) | 0x80) + NEXT(insize, 3) + } else { + /* Codeset 1 */ + WRITE2((code >> 8) | 0x80, (code & 0xFF) | 0x80) + NEXT(insize, 2) + } + } - return 0; + return 0; } DECODER(euc_jis_2004) { - while (inleft > 0) { - unsigned char c = IN1; - ucs4_t code; - - REQUIRE_OUTBUF(1) - - if (c < 0x80) { - OUT1(c) - NEXT(1, 1) - continue; - } - - if (c == 0x8e) { - /* JIS X 0201 half-width katakana */ - unsigned char c2; - - REQUIRE_INBUF(2) - c2 = IN2; - if (c2 >= 0xa1 && c2 <= 0xdf) { - OUT1(0xfec0 + c2) - NEXT(2, 1) - } - else - return 2; - } - else if (c == 0x8f) { - unsigned char c2, c3; - - REQUIRE_INBUF(3) - c2 = IN2 ^ 0x80; - c3 = IN3 ^ 0x80; - - /* JIS X 0213 Plane 2 or JIS X 0212 (see NOTES) */ - EMULATE_JISX0213_2000_DECODE_PLANE2(**outbuf, c2, c3) - else TRYMAP_DEC(jisx0213_2_bmp, **outbuf, c2, c3) ; - else TRYMAP_DEC(jisx0213_2_emp, code, c2, c3) { - WRITEUCS4(EMPBASE | code) - NEXT_IN(3) - continue; - } - else TRYMAP_DEC(jisx0212, **outbuf, c2, c3) ; - else return 3; - NEXT(3, 1) - } - else { - unsigned char c2; - - REQUIRE_INBUF(2) - c ^= 0x80; - c2 = IN2 ^ 0x80; - - /* JIS X 0213 Plane 1 */ - EMULATE_JISX0213_2000_DECODE_PLANE1(**outbuf, c, c2) - else if (c == 0x21 && c2 == 0x40) **outbuf = 0xff3c; - else if (c == 0x22 && c2 == 0x32) **outbuf = 0xff5e; - else TRYMAP_DEC(jisx0208, **outbuf, c, c2); - else TRYMAP_DEC(jisx0213_1_bmp, **outbuf, c, c2); - else TRYMAP_DEC(jisx0213_1_emp, code, c, c2) { - WRITEUCS4(EMPBASE | code) - NEXT_IN(2) - continue; - } - else TRYMAP_DEC(jisx0213_pair, code, c, c2) { - WRITE2(code >> 16, code & 0xffff) - NEXT(2, 2) - continue; - } - else return 2; - NEXT(2, 1) - } - } + while (inleft > 0) { + unsigned char c = IN1; + ucs4_t code; + + REQUIRE_OUTBUF(1) + + if (c < 0x80) { + OUT1(c) + NEXT(1, 1) + continue; + } + + if (c == 0x8e) { + /* JIS X 0201 half-width katakana */ + unsigned char c2; + + REQUIRE_INBUF(2) + c2 = IN2; + if (c2 >= 0xa1 && c2 <= 0xdf) { + OUT1(0xfec0 + c2) + NEXT(2, 1) + } + else + return 2; + } + else if (c == 0x8f) { + unsigned char c2, c3; + + REQUIRE_INBUF(3) + c2 = IN2 ^ 0x80; + c3 = IN3 ^ 0x80; + + /* JIS X 0213 Plane 2 or JIS X 0212 (see NOTES) */ + EMULATE_JISX0213_2000_DECODE_PLANE2(**outbuf, c2, c3) + else TRYMAP_DEC(jisx0213_2_bmp, **outbuf, c2, c3) ; + else TRYMAP_DEC(jisx0213_2_emp, code, c2, c3) { + WRITEUCS4(EMPBASE | code) + NEXT_IN(3) + continue; + } + else TRYMAP_DEC(jisx0212, **outbuf, c2, c3) ; + else return 3; + NEXT(3, 1) + } + else { + unsigned char c2; + + REQUIRE_INBUF(2) + c ^= 0x80; + c2 = IN2 ^ 0x80; + + /* JIS X 0213 Plane 1 */ + EMULATE_JISX0213_2000_DECODE_PLANE1(**outbuf, c, c2) + else if (c == 0x21 && c2 == 0x40) **outbuf = 0xff3c; + else if (c == 0x22 && c2 == 0x32) **outbuf = 0xff5e; + else TRYMAP_DEC(jisx0208, **outbuf, c, c2); + else TRYMAP_DEC(jisx0213_1_bmp, **outbuf, c, c2); + else TRYMAP_DEC(jisx0213_1_emp, code, c, c2) { + WRITEUCS4(EMPBASE | code) + NEXT_IN(2) + continue; + } + else TRYMAP_DEC(jisx0213_pair, code, c, c2) { + WRITE2(code >> 16, code & 0xffff) + NEXT(2, 2) + continue; + } + else return 2; + NEXT(2, 1) + } + } - return 0; + return 0; } @@ -315,114 +315,114 @@ ENCODER(euc_jp) { - while (inleft > 0) { - Py_UNICODE c = IN1; - DBCHAR code; - - if (c < 0x80) { - WRITE1((unsigned char)c) - NEXT(1, 1) - continue; - } - - UCS4INVALID(c) - - TRYMAP_ENC(jisxcommon, code, c); - else if (c >= 0xff61 && c <= 0xff9f) { - /* JIS X 0201 half-width katakana */ - WRITE2(0x8e, c - 0xfec0) - NEXT(1, 2) - continue; - } + while (inleft > 0) { + Py_UNICODE c = IN1; + DBCHAR code; + + if (c < 0x80) { + WRITE1((unsigned char)c) + NEXT(1, 1) + continue; + } + + UCS4INVALID(c) + + TRYMAP_ENC(jisxcommon, code, c); + else if (c >= 0xff61 && c <= 0xff9f) { + /* JIS X 0201 half-width katakana */ + WRITE2(0x8e, c - 0xfec0) + NEXT(1, 2) + continue; + } #ifndef STRICT_BUILD - else if (c == 0xff3c) /* FULL-WIDTH REVERSE SOLIDUS */ - code = 0x2140; - else if (c == 0xa5) { /* YEN SIGN */ - WRITE1(0x5c); - NEXT(1, 1) - continue; - } else if (c == 0x203e) { /* OVERLINE */ - WRITE1(0x7e); - NEXT(1, 1) - continue; - } + else if (c == 0xff3c) /* FULL-WIDTH REVERSE SOLIDUS */ + code = 0x2140; + else if (c == 0xa5) { /* YEN SIGN */ + WRITE1(0x5c); + NEXT(1, 1) + continue; + } else if (c == 0x203e) { /* OVERLINE */ + WRITE1(0x7e); + NEXT(1, 1) + continue; + } #endif - else - return 1; + else + return 1; - if (code & 0x8000) { - /* JIS X 0212 */ - WRITE3(0x8f, code >> 8, (code & 0xFF) | 0x80) - NEXT(1, 3) - } else { - /* JIS X 0208 */ - WRITE2((code >> 8) | 0x80, (code & 0xFF) | 0x80) - NEXT(1, 2) - } - } + if (code & 0x8000) { + /* JIS X 0212 */ + WRITE3(0x8f, code >> 8, (code & 0xFF) | 0x80) + NEXT(1, 3) + } else { + /* JIS X 0208 */ + WRITE2((code >> 8) | 0x80, (code & 0xFF) | 0x80) + NEXT(1, 2) + } + } - return 0; + return 0; } DECODER(euc_jp) { - while (inleft > 0) { - unsigned char c = IN1; + while (inleft > 0) { + unsigned char c = IN1; - REQUIRE_OUTBUF(1) + REQUIRE_OUTBUF(1) - if (c < 0x80) { - OUT1(c) - NEXT(1, 1) - continue; - } - - if (c == 0x8e) { - /* JIS X 0201 half-width katakana */ - unsigned char c2; - - REQUIRE_INBUF(2) - c2 = IN2; - if (c2 >= 0xa1 && c2 <= 0xdf) { - OUT1(0xfec0 + c2) - NEXT(2, 1) - } - else - return 2; - } - else if (c == 0x8f) { - unsigned char c2, c3; - - REQUIRE_INBUF(3) - c2 = IN2; - c3 = IN3; - /* JIS X 0212 */ - TRYMAP_DEC(jisx0212, **outbuf, c2 ^ 0x80, c3 ^ 0x80) { - NEXT(3, 1) - } - else - return 3; - } - else { - unsigned char c2; - - REQUIRE_INBUF(2) - c2 = IN2; - /* JIS X 0208 */ + if (c < 0x80) { + OUT1(c) + NEXT(1, 1) + continue; + } + + if (c == 0x8e) { + /* JIS X 0201 half-width katakana */ + unsigned char c2; + + REQUIRE_INBUF(2) + c2 = IN2; + if (c2 >= 0xa1 && c2 <= 0xdf) { + OUT1(0xfec0 + c2) + NEXT(2, 1) + } + else + return 2; + } + else if (c == 0x8f) { + unsigned char c2, c3; + + REQUIRE_INBUF(3) + c2 = IN2; + c3 = IN3; + /* JIS X 0212 */ + TRYMAP_DEC(jisx0212, **outbuf, c2 ^ 0x80, c3 ^ 0x80) { + NEXT(3, 1) + } + else + return 3; + } + else { + unsigned char c2; + + REQUIRE_INBUF(2) + c2 = IN2; + /* JIS X 0208 */ #ifndef STRICT_BUILD - if (c == 0xa1 && c2 == 0xc0) - /* FULL-WIDTH REVERSE SOLIDUS */ - **outbuf = 0xff3c; - else + if (c == 0xa1 && c2 == 0xc0) + /* FULL-WIDTH REVERSE SOLIDUS */ + **outbuf = 0xff3c; + else #endif - TRYMAP_DEC(jisx0208, **outbuf, - c ^ 0x80, c2 ^ 0x80) ; - else return 2; - NEXT(2, 1) - } - } + TRYMAP_DEC(jisx0208, **outbuf, + c ^ 0x80, c2 ^ 0x80) ; + else return 2; + NEXT(2, 1) + } + } - return 0; + return 0; } @@ -432,105 +432,105 @@ ENCODER(shift_jis) { - while (inleft > 0) { - Py_UNICODE c = IN1; - DBCHAR code; - unsigned char c1, c2; + while (inleft > 0) { + Py_UNICODE c = IN1; + DBCHAR code; + unsigned char c1, c2; #ifdef STRICT_BUILD - JISX0201_R_ENCODE(c, code) + JISX0201_R_ENCODE(c, code) #else - if (c < 0x80) code = c; - else if (c == 0x00a5) code = 0x5c; /* YEN SIGN */ - else if (c == 0x203e) code = 0x7e; /* OVERLINE */ + if (c < 0x80) code = c; + else if (c == 0x00a5) code = 0x5c; /* YEN SIGN */ + else if (c == 0x203e) code = 0x7e; /* OVERLINE */ #endif - else JISX0201_K_ENCODE(c, code) - else UCS4INVALID(c) - else code = NOCHAR; - - if (code < 0x80 || (code >= 0xa1 && code <= 0xdf)) { - REQUIRE_OUTBUF(1) - - OUT1((unsigned char)code) - NEXT(1, 1) - continue; - } + else JISX0201_K_ENCODE(c, code) + else UCS4INVALID(c) + else code = NOCHAR; + + if (code < 0x80 || (code >= 0xa1 && code <= 0xdf)) { + REQUIRE_OUTBUF(1) + + OUT1((unsigned char)code) + NEXT(1, 1) + continue; + } - REQUIRE_OUTBUF(2) + REQUIRE_OUTBUF(2) - if (code == NOCHAR) { - TRYMAP_ENC(jisxcommon, code, c); + if (code == NOCHAR) { + TRYMAP_ENC(jisxcommon, code, c); #ifndef STRICT_BUILD - else if (c == 0xff3c) - code = 0x2140; /* FULL-WIDTH REVERSE SOLIDUS */ + else if (c == 0xff3c) + code = 0x2140; /* FULL-WIDTH REVERSE SOLIDUS */ #endif - else - return 1; + else + return 1; - if (code & 0x8000) /* MSB set: JIS X 0212 */ - return 1; - } - - c1 = code >> 8; - c2 = code & 0xff; - c2 = (((c1 - 0x21) & 1) ? 0x5e : 0) + (c2 - 0x21); - c1 = (c1 - 0x21) >> 1; - OUT1(c1 < 0x1f ? c1 + 0x81 : c1 + 0xc1) - OUT2(c2 < 0x3f ? c2 + 0x40 : c2 + 0x41) - NEXT(1, 2) - } + if (code & 0x8000) /* MSB set: JIS X 0212 */ + return 1; + } + + c1 = code >> 8; + c2 = code & 0xff; + c2 = (((c1 - 0x21) & 1) ? 0x5e : 0) + (c2 - 0x21); + c1 = (c1 - 0x21) >> 1; + OUT1(c1 < 0x1f ? c1 + 0x81 : c1 + 0xc1) + OUT2(c2 < 0x3f ? c2 + 0x40 : c2 + 0x41) + NEXT(1, 2) + } - return 0; + return 0; } DECODER(shift_jis) { - while (inleft > 0) { - unsigned char c = IN1; + while (inleft > 0) { + unsigned char c = IN1; - REQUIRE_OUTBUF(1) + REQUIRE_OUTBUF(1) #ifdef STRICT_BUILD - JISX0201_R_DECODE(c, **outbuf) + JISX0201_R_DECODE(c, **outbuf) #else - if (c < 0x80) **outbuf = c; + if (c < 0x80) **outbuf = c; #endif - else JISX0201_K_DECODE(c, **outbuf) - else if ((c >= 0x81 && c <= 0x9f) || (c >= 0xe0 && c <= 0xea)){ - unsigned char c1, c2; - - REQUIRE_INBUF(2) - c2 = IN2; - if (c2 < 0x40 || (c2 > 0x7e && c2 < 0x80) || c2 > 0xfc) - return 2; - - c1 = (c < 0xe0 ? c - 0x81 : c - 0xc1); - c2 = (c2 < 0x80 ? c2 - 0x40 : c2 - 0x41); - c1 = (2 * c1 + (c2 < 0x5e ? 0 : 1) + 0x21); - c2 = (c2 < 0x5e ? c2 : c2 - 0x5e) + 0x21; + else JISX0201_K_DECODE(c, **outbuf) + else if ((c >= 0x81 && c <= 0x9f) || (c >= 0xe0 && c <= 0xea)){ + unsigned char c1, c2; + + REQUIRE_INBUF(2) + c2 = IN2; + if (c2 < 0x40 || (c2 > 0x7e && c2 < 0x80) || c2 > 0xfc) + return 2; + + c1 = (c < 0xe0 ? c - 0x81 : c - 0xc1); + c2 = (c2 < 0x80 ? c2 - 0x40 : c2 - 0x41); + c1 = (2 * c1 + (c2 < 0x5e ? 0 : 1) + 0x21); + c2 = (c2 < 0x5e ? c2 : c2 - 0x5e) + 0x21; #ifndef STRICT_BUILD - if (c1 == 0x21 && c2 == 0x40) { - /* FULL-WIDTH REVERSE SOLIDUS */ - OUT1(0xff3c) - NEXT(2, 1) - continue; - } + if (c1 == 0x21 && c2 == 0x40) { + /* FULL-WIDTH REVERSE SOLIDUS */ + OUT1(0xff3c) + NEXT(2, 1) + continue; + } #endif - TRYMAP_DEC(jisx0208, **outbuf, c1, c2) { - NEXT(2, 1) - continue; - } - else - return 2; - } - else - return 2; + TRYMAP_DEC(jisx0208, **outbuf, c1, c2) { + NEXT(2, 1) + continue; + } + else + return 2; + } + else + return 2; - NEXT(1, 1) /* JIS X 0201 */ - } + NEXT(1, 1) /* JIS X 0201 */ + } - return 0; + return 0; } @@ -540,167 +540,167 @@ ENCODER(shift_jis_2004) { - while (inleft > 0) { - ucs4_t c = IN1; - DBCHAR code = NOCHAR; - int c1, c2; - Py_ssize_t insize; - - JISX0201_ENCODE(c, code) - else DECODE_SURROGATE(c) - - if (code < 0x80 || (code >= 0xa1 && code <= 0xdf)) { - WRITE1((unsigned char)code) - NEXT(1, 1) - continue; - } - - REQUIRE_OUTBUF(2) - insize = GET_INSIZE(c); - - if (code == NOCHAR) { - if (c <= 0xffff) { - EMULATE_JISX0213_2000_ENCODE_BMP(code, c) - else TRYMAP_ENC(jisx0213_bmp, code, c) { - if (code == MULTIC) { - if (inleft < 2) { - if (flags & MBENC_FLUSH) { - code = find_pairencmap - ((ucs2_t)c, 0, - jisx0213_pair_encmap, - JISX0213_ENCPAIRS); - if (code == DBCINV) - return 1; - } - else - return MBERR_TOOFEW; - } - else { - code = find_pairencmap( - (ucs2_t)c, IN2, - jisx0213_pair_encmap, - JISX0213_ENCPAIRS); - if (code == DBCINV) { - code = find_pairencmap( - (ucs2_t)c, 0, - jisx0213_pair_encmap, - JISX0213_ENCPAIRS); - if (code == DBCINV) - return 1; - } - else - insize = 2; - } - } - } - else TRYMAP_ENC(jisxcommon, code, c) { - /* abandon JIS X 0212 codes */ - if (code & 0x8000) - return 1; - } - else return 1; - } - else if (c >> 16 == EMPBASE >> 16) { - EMULATE_JISX0213_2000_ENCODE_EMP(code, c) - else TRYMAP_ENC(jisx0213_emp, code, c&0xffff); - else return insize; - } - else - return insize; - } - - c1 = code >> 8; - c2 = (code & 0xff) - 0x21; - - if (c1 & 0x80) { /* Plane 2 */ - if (c1 >= 0xee) c1 -= 0x87; - else if (c1 >= 0xac || c1 == 0xa8) c1 -= 0x49; - else c1 -= 0x43; - } - else /* Plane 1 */ - c1 -= 0x21; - - if (c1 & 1) c2 += 0x5e; - c1 >>= 1; - OUT1(c1 + (c1 < 0x1f ? 0x81 : 0xc1)) - OUT2(c2 + (c2 < 0x3f ? 0x40 : 0x41)) + while (inleft > 0) { + ucs4_t c = IN1; + DBCHAR code = NOCHAR; + int c1, c2; + Py_ssize_t insize; + + JISX0201_ENCODE(c, code) + else DECODE_SURROGATE(c) + + if (code < 0x80 || (code >= 0xa1 && code <= 0xdf)) { + WRITE1((unsigned char)code) + NEXT(1, 1) + continue; + } + + REQUIRE_OUTBUF(2) + insize = GET_INSIZE(c); + + if (code == NOCHAR) { + if (c <= 0xffff) { + EMULATE_JISX0213_2000_ENCODE_BMP(code, c) + else TRYMAP_ENC(jisx0213_bmp, code, c) { + if (code == MULTIC) { + if (inleft < 2) { + if (flags & MBENC_FLUSH) { + code = find_pairencmap + ((ucs2_t)c, 0, + jisx0213_pair_encmap, + JISX0213_ENCPAIRS); + if (code == DBCINV) + return 1; + } + else + return MBERR_TOOFEW; + } + else { + code = find_pairencmap( + (ucs2_t)c, IN2, + jisx0213_pair_encmap, + JISX0213_ENCPAIRS); + if (code == DBCINV) { + code = find_pairencmap( + (ucs2_t)c, 0, + jisx0213_pair_encmap, + JISX0213_ENCPAIRS); + if (code == DBCINV) + return 1; + } + else + insize = 2; + } + } + } + else TRYMAP_ENC(jisxcommon, code, c) { + /* abandon JIS X 0212 codes */ + if (code & 0x8000) + return 1; + } + else return 1; + } + else if (c >> 16 == EMPBASE >> 16) { + EMULATE_JISX0213_2000_ENCODE_EMP(code, c) + else TRYMAP_ENC(jisx0213_emp, code, c&0xffff); + else return insize; + } + else + return insize; + } + + c1 = code >> 8; + c2 = (code & 0xff) - 0x21; + + if (c1 & 0x80) { /* Plane 2 */ + if (c1 >= 0xee) c1 -= 0x87; + else if (c1 >= 0xac || c1 == 0xa8) c1 -= 0x49; + else c1 -= 0x43; + } + else /* Plane 1 */ + c1 -= 0x21; + + if (c1 & 1) c2 += 0x5e; + c1 >>= 1; + OUT1(c1 + (c1 < 0x1f ? 0x81 : 0xc1)) + OUT2(c2 + (c2 < 0x3f ? 0x40 : 0x41)) - NEXT(insize, 2) - } + NEXT(insize, 2) + } - return 0; + return 0; } DECODER(shift_jis_2004) { - while (inleft > 0) { - unsigned char c = IN1; + while (inleft > 0) { + unsigned char c = IN1; - REQUIRE_OUTBUF(1) - JISX0201_DECODE(c, **outbuf) - else if ((c >= 0x81 && c <= 0x9f) || (c >= 0xe0 && c <= 0xfc)){ - unsigned char c1, c2; - ucs4_t code; - - REQUIRE_INBUF(2) - c2 = IN2; - if (c2 < 0x40 || (c2 > 0x7e && c2 < 0x80) || c2 > 0xfc) - return 2; - - c1 = (c < 0xe0 ? c - 0x81 : c - 0xc1); - c2 = (c2 < 0x80 ? c2 - 0x40 : c2 - 0x41); - c1 = (2 * c1 + (c2 < 0x5e ? 0 : 1)); - c2 = (c2 < 0x5e ? c2 : c2 - 0x5e) + 0x21; - - if (c1 < 0x5e) { /* Plane 1 */ - c1 += 0x21; - EMULATE_JISX0213_2000_DECODE_PLANE1(**outbuf, - c1, c2) - else TRYMAP_DEC(jisx0208, **outbuf, c1, c2) { - NEXT_OUT(1) - } - else TRYMAP_DEC(jisx0213_1_bmp, **outbuf, - c1, c2) { - NEXT_OUT(1) - } - else TRYMAP_DEC(jisx0213_1_emp, code, c1, c2) { - WRITEUCS4(EMPBASE | code) - } - else TRYMAP_DEC(jisx0213_pair, code, c1, c2) { - WRITE2(code >> 16, code & 0xffff) - NEXT_OUT(2) - } - else - return 2; - NEXT_IN(2) - } - else { /* Plane 2 */ - if (c1 >= 0x67) c1 += 0x07; - else if (c1 >= 0x63 || c1 == 0x5f) c1 -= 0x37; - else c1 -= 0x3d; - - EMULATE_JISX0213_2000_DECODE_PLANE2(**outbuf, - c1, c2) - else TRYMAP_DEC(jisx0213_2_bmp, **outbuf, - c1, c2) ; - else TRYMAP_DEC(jisx0213_2_emp, code, c1, c2) { - WRITEUCS4(EMPBASE | code) - NEXT_IN(2) - continue; - } - else - return 2; - NEXT(2, 1) - } - continue; - } - else - return 2; + REQUIRE_OUTBUF(1) + JISX0201_DECODE(c, **outbuf) + else if ((c >= 0x81 && c <= 0x9f) || (c >= 0xe0 && c <= 0xfc)){ + unsigned char c1, c2; + ucs4_t code; + + REQUIRE_INBUF(2) + c2 = IN2; + if (c2 < 0x40 || (c2 > 0x7e && c2 < 0x80) || c2 > 0xfc) + return 2; + + c1 = (c < 0xe0 ? c - 0x81 : c - 0xc1); + c2 = (c2 < 0x80 ? c2 - 0x40 : c2 - 0x41); + c1 = (2 * c1 + (c2 < 0x5e ? 0 : 1)); + c2 = (c2 < 0x5e ? c2 : c2 - 0x5e) + 0x21; + + if (c1 < 0x5e) { /* Plane 1 */ + c1 += 0x21; + EMULATE_JISX0213_2000_DECODE_PLANE1(**outbuf, + c1, c2) + else TRYMAP_DEC(jisx0208, **outbuf, c1, c2) { + NEXT_OUT(1) + } + else TRYMAP_DEC(jisx0213_1_bmp, **outbuf, + c1, c2) { + NEXT_OUT(1) + } + else TRYMAP_DEC(jisx0213_1_emp, code, c1, c2) { + WRITEUCS4(EMPBASE | code) + } + else TRYMAP_DEC(jisx0213_pair, code, c1, c2) { + WRITE2(code >> 16, code & 0xffff) + NEXT_OUT(2) + } + else + return 2; + NEXT_IN(2) + } + else { /* Plane 2 */ + if (c1 >= 0x67) c1 += 0x07; + else if (c1 >= 0x63 || c1 == 0x5f) c1 -= 0x37; + else c1 -= 0x3d; + + EMULATE_JISX0213_2000_DECODE_PLANE2(**outbuf, + c1, c2) + else TRYMAP_DEC(jisx0213_2_bmp, **outbuf, + c1, c2) ; + else TRYMAP_DEC(jisx0213_2_emp, code, c1, c2) { + WRITEUCS4(EMPBASE | code) + NEXT_IN(2) + continue; + } + else + return 2; + NEXT(2, 1) + } + continue; + } + else + return 2; - NEXT(1, 1) /* JIS X 0201 */ - } + NEXT(1, 1) /* JIS X 0201 */ + } - return 0; + return 0; } Modified: python/branches/release31-maint/Modules/cjkcodecs/_codecs_kr.c ============================================================================== --- python/branches/release31-maint/Modules/cjkcodecs/_codecs_kr.c (original) +++ python/branches/release31-maint/Modules/cjkcodecs/_codecs_kr.c Sun May 9 18:14:21 2010 @@ -11,151 +11,151 @@ * EUC-KR codec */ -#define EUCKR_JAMO_FIRSTBYTE 0xA4 -#define EUCKR_JAMO_FILLER 0xD4 +#define EUCKR_JAMO_FIRSTBYTE 0xA4 +#define EUCKR_JAMO_FILLER 0xD4 static const unsigned char u2cgk_choseong[19] = { - 0xa1, 0xa2, 0xa4, 0xa7, 0xa8, 0xa9, 0xb1, 0xb2, - 0xb3, 0xb5, 0xb6, 0xb7, 0xb8, 0xb9, 0xba, 0xbb, - 0xbc, 0xbd, 0xbe + 0xa1, 0xa2, 0xa4, 0xa7, 0xa8, 0xa9, 0xb1, 0xb2, + 0xb3, 0xb5, 0xb6, 0xb7, 0xb8, 0xb9, 0xba, 0xbb, + 0xbc, 0xbd, 0xbe }; static const unsigned char u2cgk_jungseong[21] = { - 0xbf, 0xc0, 0xc1, 0xc2, 0xc3, 0xc4, 0xc5, 0xc6, - 0xc7, 0xc8, 0xc9, 0xca, 0xcb, 0xcc, 0xcd, 0xce, - 0xcf, 0xd0, 0xd1, 0xd2, 0xd3 + 0xbf, 0xc0, 0xc1, 0xc2, 0xc3, 0xc4, 0xc5, 0xc6, + 0xc7, 0xc8, 0xc9, 0xca, 0xcb, 0xcc, 0xcd, 0xce, + 0xcf, 0xd0, 0xd1, 0xd2, 0xd3 }; static const unsigned char u2cgk_jongseong[28] = { - 0xd4, 0xa1, 0xa2, 0xa3, 0xa4, 0xa5, 0xa6, 0xa7, - 0xa9, 0xaa, 0xab, 0xac, 0xad, 0xae, 0xaf, 0xb0, - 0xb1, 0xb2, 0xb4, 0xb5, 0xb6, 0xb7, 0xb8, 0xba, - 0xbb, 0xbc, 0xbd, 0xbe + 0xd4, 0xa1, 0xa2, 0xa3, 0xa4, 0xa5, 0xa6, 0xa7, + 0xa9, 0xaa, 0xab, 0xac, 0xad, 0xae, 0xaf, 0xb0, + 0xb1, 0xb2, 0xb4, 0xb5, 0xb6, 0xb7, 0xb8, 0xba, + 0xbb, 0xbc, 0xbd, 0xbe }; ENCODER(euc_kr) { - while (inleft > 0) { - Py_UNICODE c = IN1; - DBCHAR code; - - if (c < 0x80) { - WRITE1((unsigned char)c) - NEXT(1, 1) - continue; - } - UCS4INVALID(c) - - REQUIRE_OUTBUF(2) - TRYMAP_ENC(cp949, code, c); - else return 1; - - if ((code & 0x8000) == 0) { - /* KS X 1001 coded character */ - OUT1((code >> 8) | 0x80) - OUT2((code & 0xFF) | 0x80) - NEXT(1, 2) - } - else { /* Mapping is found in CP949 extension, - * but we encode it in KS X 1001:1998 Annex 3, - * make-up sequence for EUC-KR. */ - - REQUIRE_OUTBUF(8) - - /* syllable composition precedence */ - OUT1(EUCKR_JAMO_FIRSTBYTE) - OUT2(EUCKR_JAMO_FILLER) - - /* All codepoints in CP949 extension are in unicode - * Hangul Syllable area. */ - assert(0xac00 <= c && c <= 0xd7a3); - c -= 0xac00; - - OUT3(EUCKR_JAMO_FIRSTBYTE) - OUT4(u2cgk_choseong[c / 588]) - NEXT_OUT(4) - - OUT1(EUCKR_JAMO_FIRSTBYTE) - OUT2(u2cgk_jungseong[(c / 28) % 21]) - OUT3(EUCKR_JAMO_FIRSTBYTE) - OUT4(u2cgk_jongseong[c % 28]) - NEXT(1, 4) - } - } + while (inleft > 0) { + Py_UNICODE c = IN1; + DBCHAR code; + + if (c < 0x80) { + WRITE1((unsigned char)c) + NEXT(1, 1) + continue; + } + UCS4INVALID(c) + + REQUIRE_OUTBUF(2) + TRYMAP_ENC(cp949, code, c); + else return 1; + + if ((code & 0x8000) == 0) { + /* KS X 1001 coded character */ + OUT1((code >> 8) | 0x80) + OUT2((code & 0xFF) | 0x80) + NEXT(1, 2) + } + else { /* Mapping is found in CP949 extension, + * but we encode it in KS X 1001:1998 Annex 3, + * make-up sequence for EUC-KR. */ + + REQUIRE_OUTBUF(8) + + /* syllable composition precedence */ + OUT1(EUCKR_JAMO_FIRSTBYTE) + OUT2(EUCKR_JAMO_FILLER) + + /* All codepoints in CP949 extension are in unicode + * Hangul Syllable area. */ + assert(0xac00 <= c && c <= 0xd7a3); + c -= 0xac00; + + OUT3(EUCKR_JAMO_FIRSTBYTE) + OUT4(u2cgk_choseong[c / 588]) + NEXT_OUT(4) + + OUT1(EUCKR_JAMO_FIRSTBYTE) + OUT2(u2cgk_jungseong[(c / 28) % 21]) + OUT3(EUCKR_JAMO_FIRSTBYTE) + OUT4(u2cgk_jongseong[c % 28]) + NEXT(1, 4) + } + } - return 0; + return 0; } -#define NONE 127 +#define NONE 127 static const unsigned char cgk2u_choseong[] = { /* [A1, BE] */ - 0, 1, NONE, 2, NONE, NONE, 3, 4, - 5, NONE, NONE, NONE, NONE, NONE, NONE, NONE, - 6, 7, 8, NONE, 9, 10, 11, 12, - 13, 14, 15, 16, 17, 18 + 0, 1, NONE, 2, NONE, NONE, 3, 4, + 5, NONE, NONE, NONE, NONE, NONE, NONE, NONE, + 6, 7, 8, NONE, 9, 10, 11, 12, + 13, 14, 15, 16, 17, 18 }; static const unsigned char cgk2u_jongseong[] = { /* [A1, BE] */ - 1, 2, 3, 4, 5, 6, 7, NONE, - 8, 9, 10, 11, 12, 13, 14, 15, - 16, 17, NONE, 18, 19, 20, 21, 22, - NONE, 23, 24, 25, 26, 27 + 1, 2, 3, 4, 5, 6, 7, NONE, + 8, 9, 10, 11, 12, 13, 14, 15, + 16, 17, NONE, 18, 19, 20, 21, 22, + NONE, 23, 24, 25, 26, 27 }; DECODER(euc_kr) { - while (inleft > 0) { - unsigned char c = IN1; + while (inleft > 0) { + unsigned char c = IN1; - REQUIRE_OUTBUF(1) + REQUIRE_OUTBUF(1) - if (c < 0x80) { - OUT1(c) - NEXT(1, 1) - continue; - } - - REQUIRE_INBUF(2) - - if (c == EUCKR_JAMO_FIRSTBYTE && - IN2 == EUCKR_JAMO_FILLER) { - /* KS X 1001:1998 Annex 3 make-up sequence */ - DBCHAR cho, jung, jong; - - REQUIRE_INBUF(8) - if ((*inbuf)[2] != EUCKR_JAMO_FIRSTBYTE || - (*inbuf)[4] != EUCKR_JAMO_FIRSTBYTE || - (*inbuf)[6] != EUCKR_JAMO_FIRSTBYTE) - return 8; - - c = (*inbuf)[3]; - if (0xa1 <= c && c <= 0xbe) - cho = cgk2u_choseong[c - 0xa1]; - else - cho = NONE; - - c = (*inbuf)[5]; - jung = (0xbf <= c && c <= 0xd3) ? c - 0xbf : NONE; - - c = (*inbuf)[7]; - if (c == EUCKR_JAMO_FILLER) - jong = 0; - else if (0xa1 <= c && c <= 0xbe) - jong = cgk2u_jongseong[c - 0xa1]; - else - jong = NONE; - - if (cho == NONE || jung == NONE || jong == NONE) - return 8; - - OUT1(0xac00 + cho*588 + jung*28 + jong); - NEXT(8, 1) - } - else TRYMAP_DEC(ksx1001, **outbuf, c ^ 0x80, IN2 ^ 0x80) { - NEXT(2, 1) - } - else - return 2; - } + if (c < 0x80) { + OUT1(c) + NEXT(1, 1) + continue; + } + + REQUIRE_INBUF(2) + + if (c == EUCKR_JAMO_FIRSTBYTE && + IN2 == EUCKR_JAMO_FILLER) { + /* KS X 1001:1998 Annex 3 make-up sequence */ + DBCHAR cho, jung, jong; + + REQUIRE_INBUF(8) + if ((*inbuf)[2] != EUCKR_JAMO_FIRSTBYTE || + (*inbuf)[4] != EUCKR_JAMO_FIRSTBYTE || + (*inbuf)[6] != EUCKR_JAMO_FIRSTBYTE) + return 8; + + c = (*inbuf)[3]; + if (0xa1 <= c && c <= 0xbe) + cho = cgk2u_choseong[c - 0xa1]; + else + cho = NONE; + + c = (*inbuf)[5]; + jung = (0xbf <= c && c <= 0xd3) ? c - 0xbf : NONE; + + c = (*inbuf)[7]; + if (c == EUCKR_JAMO_FILLER) + jong = 0; + else if (0xa1 <= c && c <= 0xbe) + jong = cgk2u_jongseong[c - 0xa1]; + else + jong = NONE; + + if (cho == NONE || jung == NONE || jong == NONE) + return 8; + + OUT1(0xac00 + cho*588 + jung*28 + jong); + NEXT(8, 1) + } + else TRYMAP_DEC(ksx1001, **outbuf, c ^ 0x80, IN2 ^ 0x80) { + NEXT(2, 1) + } + else + return 2; + } - return 0; + return 0; } #undef NONE @@ -166,54 +166,54 @@ ENCODER(cp949) { - while (inleft > 0) { - Py_UNICODE c = IN1; - DBCHAR code; - - if (c < 0x80) { - WRITE1((unsigned char)c) - NEXT(1, 1) - continue; - } - UCS4INVALID(c) - - REQUIRE_OUTBUF(2) - TRYMAP_ENC(cp949, code, c); - else return 1; - - OUT1((code >> 8) | 0x80) - if (code & 0x8000) - OUT2(code & 0xFF) /* MSB set: CP949 */ - else - OUT2((code & 0xFF) | 0x80) /* MSB unset: ks x 1001 */ - NEXT(1, 2) - } + while (inleft > 0) { + Py_UNICODE c = IN1; + DBCHAR code; + + if (c < 0x80) { + WRITE1((unsigned char)c) + NEXT(1, 1) + continue; + } + UCS4INVALID(c) + + REQUIRE_OUTBUF(2) + TRYMAP_ENC(cp949, code, c); + else return 1; + + OUT1((code >> 8) | 0x80) + if (code & 0x8000) + OUT2(code & 0xFF) /* MSB set: CP949 */ + else + OUT2((code & 0xFF) | 0x80) /* MSB unset: ks x 1001 */ + NEXT(1, 2) + } - return 0; + return 0; } DECODER(cp949) { - while (inleft > 0) { - unsigned char c = IN1; + while (inleft > 0) { + unsigned char c = IN1; - REQUIRE_OUTBUF(1) + REQUIRE_OUTBUF(1) - if (c < 0x80) { - OUT1(c) - NEXT(1, 1) - continue; - } - - REQUIRE_INBUF(2) - TRYMAP_DEC(ksx1001, **outbuf, c ^ 0x80, IN2 ^ 0x80); - else TRYMAP_DEC(cp949ext, **outbuf, c, IN2); - else return 2; + if (c < 0x80) { + OUT1(c) + NEXT(1, 1) + continue; + } + + REQUIRE_INBUF(2) + TRYMAP_DEC(ksx1001, **outbuf, c ^ 0x80, IN2 ^ 0x80); + else TRYMAP_DEC(cp949ext, **outbuf, c, IN2); + else return 2; - NEXT(2, 1) - } + NEXT(2, 1) + } - return 0; + return 0; } @@ -250,58 +250,58 @@ ENCODER(johab) { - while (inleft > 0) { - Py_UNICODE c = IN1; - DBCHAR code; - - if (c < 0x80) { - WRITE1((unsigned char)c) - NEXT(1, 1) - continue; - } - UCS4INVALID(c) - - REQUIRE_OUTBUF(2) - - if (c >= 0xac00 && c <= 0xd7a3) { - c -= 0xac00; - code = 0x8000 | - (u2johabidx_choseong[c / 588] << 10) | - (u2johabidx_jungseong[(c / 28) % 21] << 5) | - u2johabidx_jongseong[c % 28]; - } - else if (c >= 0x3131 && c <= 0x3163) - code = u2johabjamo[c - 0x3131]; - else TRYMAP_ENC(cp949, code, c) { - unsigned char c1, c2, t2; - unsigned short t1; - - assert((code & 0x8000) == 0); - c1 = code >> 8; - c2 = code & 0xff; - if (((c1 >= 0x21 && c1 <= 0x2c) || - (c1 >= 0x4a && c1 <= 0x7d)) && - (c2 >= 0x21 && c2 <= 0x7e)) { - t1 = (c1 < 0x4a ? (c1 - 0x21 + 0x1b2) : - (c1 - 0x21 + 0x197)); - t2 = ((t1 & 1) ? 0x5e : 0) + (c2 - 0x21); - OUT1(t1 >> 1) - OUT2(t2 < 0x4e ? t2 + 0x31 : t2 + 0x43) - NEXT(1, 2) - continue; - } - else - return 1; - } - else - return 1; - - OUT1(code >> 8) - OUT2(code & 0xff) - NEXT(1, 2) - } + while (inleft > 0) { + Py_UNICODE c = IN1; + DBCHAR code; + + if (c < 0x80) { + WRITE1((unsigned char)c) + NEXT(1, 1) + continue; + } + UCS4INVALID(c) + + REQUIRE_OUTBUF(2) + + if (c >= 0xac00 && c <= 0xd7a3) { + c -= 0xac00; + code = 0x8000 | + (u2johabidx_choseong[c / 588] << 10) | + (u2johabidx_jungseong[(c / 28) % 21] << 5) | + u2johabidx_jongseong[c % 28]; + } + else if (c >= 0x3131 && c <= 0x3163) + code = u2johabjamo[c - 0x3131]; + else TRYMAP_ENC(cp949, code, c) { + unsigned char c1, c2, t2; + unsigned short t1; + + assert((code & 0x8000) == 0); + c1 = code >> 8; + c2 = code & 0xff; + if (((c1 >= 0x21 && c1 <= 0x2c) || + (c1 >= 0x4a && c1 <= 0x7d)) && + (c2 >= 0x21 && c2 <= 0x7e)) { + t1 = (c1 < 0x4a ? (c1 - 0x21 + 0x1b2) : + (c1 - 0x21 + 0x197)); + t2 = ((t1 & 1) ? 0x5e : 0) + (c2 - 0x21); + OUT1(t1 >> 1) + OUT2(t2 < 0x4e ? t2 + 0x31 : t2 + 0x43) + NEXT(1, 2) + continue; + } + else + return 1; + } + else + return 1; + + OUT1(code >> 8) + OUT2(code & 0xff) + NEXT(1, 2) + } - return 0; + return 0; } #define FILL 0xfd @@ -347,91 +347,91 @@ DECODER(johab) { - while (inleft > 0) { - unsigned char c = IN1, c2; + while (inleft > 0) { + unsigned char c = IN1, c2; - REQUIRE_OUTBUF(1) + REQUIRE_OUTBUF(1) - if (c < 0x80) { - OUT1(c) - NEXT(1, 1) - continue; - } - - REQUIRE_INBUF(2) - c2 = IN2; - - if (c < 0xd8) { - /* johab hangul */ - unsigned char c_cho, c_jung, c_jong; - unsigned char i_cho, i_jung, i_jong; - - c_cho = (c >> 2) & 0x1f; - c_jung = ((c << 3) | c2 >> 5) & 0x1f; - c_jong = c2 & 0x1f; - - i_cho = johabidx_choseong[c_cho]; - i_jung = johabidx_jungseong[c_jung]; - i_jong = johabidx_jongseong[c_jong]; - - if (i_cho == NONE || i_jung == NONE || i_jong == NONE) - return 2; - - /* we don't use U+1100 hangul jamo yet. */ - if (i_cho == FILL) { - if (i_jung == FILL) { - if (i_jong == FILL) - OUT1(0x3000) - else - OUT1(0x3100 | - johabjamo_jongseong[c_jong]) - } - else { - if (i_jong == FILL) - OUT1(0x3100 | - johabjamo_jungseong[c_jung]) - else - return 2; - } - } else { - if (i_jung == FILL) { - if (i_jong == FILL) - OUT1(0x3100 | - johabjamo_choseong[c_cho]) - else - return 2; - } - else - OUT1(0xac00 + - i_cho * 588 + - i_jung * 28 + - (i_jong == FILL ? 0 : i_jong)) - } - NEXT(2, 1) - } else { - /* KS X 1001 except hangul jamos and syllables */ - if (c == 0xdf || c > 0xf9 || - c2 < 0x31 || (c2 >= 0x80 && c2 < 0x91) || - (c2 & 0x7f) == 0x7f || - (c == 0xda && (c2 >= 0xa1 && c2 <= 0xd3))) - return 2; - else { - unsigned char t1, t2; - - t1 = (c < 0xe0 ? 2 * (c - 0xd9) : - 2 * c - 0x197); - t2 = (c2 < 0x91 ? c2 - 0x31 : c2 - 0x43); - t1 = t1 + (t2 < 0x5e ? 0 : 1) + 0x21; - t2 = (t2 < 0x5e ? t2 : t2 - 0x5e) + 0x21; - - TRYMAP_DEC(ksx1001, **outbuf, t1, t2); - else return 2; - NEXT(2, 1) - } - } - } + if (c < 0x80) { + OUT1(c) + NEXT(1, 1) + continue; + } + + REQUIRE_INBUF(2) + c2 = IN2; + + if (c < 0xd8) { + /* johab hangul */ + unsigned char c_cho, c_jung, c_jong; + unsigned char i_cho, i_jung, i_jong; + + c_cho = (c >> 2) & 0x1f; + c_jung = ((c << 3) | c2 >> 5) & 0x1f; + c_jong = c2 & 0x1f; + + i_cho = johabidx_choseong[c_cho]; + i_jung = johabidx_jungseong[c_jung]; + i_jong = johabidx_jongseong[c_jong]; + + if (i_cho == NONE || i_jung == NONE || i_jong == NONE) + return 2; + + /* we don't use U+1100 hangul jamo yet. */ + if (i_cho == FILL) { + if (i_jung == FILL) { + if (i_jong == FILL) + OUT1(0x3000) + else + OUT1(0x3100 | + johabjamo_jongseong[c_jong]) + } + else { + if (i_jong == FILL) + OUT1(0x3100 | + johabjamo_jungseong[c_jung]) + else + return 2; + } + } else { + if (i_jung == FILL) { + if (i_jong == FILL) + OUT1(0x3100 | + johabjamo_choseong[c_cho]) + else + return 2; + } + else + OUT1(0xac00 + + i_cho * 588 + + i_jung * 28 + + (i_jong == FILL ? 0 : i_jong)) + } + NEXT(2, 1) + } else { + /* KS X 1001 except hangul jamos and syllables */ + if (c == 0xdf || c > 0xf9 || + c2 < 0x31 || (c2 >= 0x80 && c2 < 0x91) || + (c2 & 0x7f) == 0x7f || + (c == 0xda && (c2 >= 0xa1 && c2 <= 0xd3))) + return 2; + else { + unsigned char t1, t2; + + t1 = (c < 0xe0 ? 2 * (c - 0xd9) : + 2 * c - 0x197); + t2 = (c2 < 0x91 ? c2 - 0x31 : c2 - 0x43); + t1 = t1 + (t2 < 0x5e ? 0 : 1) + 0x21; + t2 = (t2 < 0x5e ? t2 : t2 - 0x5e) + 0x21; + + TRYMAP_DEC(ksx1001, **outbuf, t1, t2); + else return 2; + NEXT(2, 1) + } + } + } - return 0; + return 0; } #undef NONE #undef FILL Modified: python/branches/release31-maint/Modules/cjkcodecs/_codecs_tw.c ============================================================================== --- python/branches/release31-maint/Modules/cjkcodecs/_codecs_tw.c (original) +++ python/branches/release31-maint/Modules/cjkcodecs/_codecs_tw.c Sun May 9 18:14:21 2010 @@ -13,52 +13,52 @@ ENCODER(big5) { - while (inleft > 0) { - Py_UNICODE c = **inbuf; - DBCHAR code; - - if (c < 0x80) { - REQUIRE_OUTBUF(1) - **outbuf = (unsigned char)c; - NEXT(1, 1) - continue; - } - UCS4INVALID(c) - - REQUIRE_OUTBUF(2) - - TRYMAP_ENC(big5, code, c); - else return 1; - - OUT1(code >> 8) - OUT2(code & 0xFF) - NEXT(1, 2) - } + while (inleft > 0) { + Py_UNICODE c = **inbuf; + DBCHAR code; + + if (c < 0x80) { + REQUIRE_OUTBUF(1) + **outbuf = (unsigned char)c; + NEXT(1, 1) + continue; + } + UCS4INVALID(c) + + REQUIRE_OUTBUF(2) + + TRYMAP_ENC(big5, code, c); + else return 1; + + OUT1(code >> 8) + OUT2(code & 0xFF) + NEXT(1, 2) + } - return 0; + return 0; } DECODER(big5) { - while (inleft > 0) { - unsigned char c = IN1; + while (inleft > 0) { + unsigned char c = IN1; - REQUIRE_OUTBUF(1) + REQUIRE_OUTBUF(1) - if (c < 0x80) { - OUT1(c) - NEXT(1, 1) - continue; - } - - REQUIRE_INBUF(2) - TRYMAP_DEC(big5, **outbuf, c, IN2) { - NEXT(2, 1) - } - else return 2; - } + if (c < 0x80) { + OUT1(c) + NEXT(1, 1) + continue; + } + + REQUIRE_INBUF(2) + TRYMAP_DEC(big5, **outbuf, c, IN2) { + NEXT(2, 1) + } + else return 2; + } - return 0; + return 0; } @@ -68,53 +68,53 @@ ENCODER(cp950) { - while (inleft > 0) { - Py_UNICODE c = IN1; - DBCHAR code; - - if (c < 0x80) { - WRITE1((unsigned char)c) - NEXT(1, 1) - continue; - } - UCS4INVALID(c) - - REQUIRE_OUTBUF(2) - TRYMAP_ENC(cp950ext, code, c); - else TRYMAP_ENC(big5, code, c); - else return 1; - - OUT1(code >> 8) - OUT2(code & 0xFF) - NEXT(1, 2) - } + while (inleft > 0) { + Py_UNICODE c = IN1; + DBCHAR code; + + if (c < 0x80) { + WRITE1((unsigned char)c) + NEXT(1, 1) + continue; + } + UCS4INVALID(c) + + REQUIRE_OUTBUF(2) + TRYMAP_ENC(cp950ext, code, c); + else TRYMAP_ENC(big5, code, c); + else return 1; + + OUT1(code >> 8) + OUT2(code & 0xFF) + NEXT(1, 2) + } - return 0; + return 0; } DECODER(cp950) { - while (inleft > 0) { - unsigned char c = IN1; + while (inleft > 0) { + unsigned char c = IN1; - REQUIRE_OUTBUF(1) + REQUIRE_OUTBUF(1) - if (c < 0x80) { - OUT1(c) - NEXT(1, 1) - continue; - } + if (c < 0x80) { + OUT1(c) + NEXT(1, 1) + continue; + } - REQUIRE_INBUF(2) + REQUIRE_INBUF(2) - TRYMAP_DEC(cp950ext, **outbuf, c, IN2); - else TRYMAP_DEC(big5, **outbuf, c, IN2); - else return 2; + TRYMAP_DEC(cp950ext, **outbuf, c, IN2); + else TRYMAP_DEC(big5, **outbuf, c, IN2); + else return 2; - NEXT(2, 1) - } + NEXT(2, 1) + } - return 0; + return 0; } Modified: python/branches/release31-maint/Modules/cjkcodecs/alg_jisx0201.h ============================================================================== --- python/branches/release31-maint/Modules/cjkcodecs/alg_jisx0201.h (original) +++ python/branches/release31-maint/Modules/cjkcodecs/alg_jisx0201.h Sun May 9 18:14:21 2010 @@ -1,24 +1,24 @@ -#define JISX0201_R_ENCODE(c, assi) \ - if ((c) < 0x80 && (c) != 0x5c && (c) != 0x7e) \ - (assi) = (c); \ - else if ((c) == 0x00a5) (assi) = 0x5c; \ - else if ((c) == 0x203e) (assi) = 0x7e; -#define JISX0201_K_ENCODE(c, assi) \ - if ((c) >= 0xff61 && (c) <= 0xff9f) \ - (assi) = (c) - 0xfec0; -#define JISX0201_ENCODE(c, assi) \ - JISX0201_R_ENCODE(c, assi) \ - else JISX0201_K_ENCODE(c, assi) +#define JISX0201_R_ENCODE(c, assi) \ + if ((c) < 0x80 && (c) != 0x5c && (c) != 0x7e) \ + (assi) = (c); \ + else if ((c) == 0x00a5) (assi) = 0x5c; \ + else if ((c) == 0x203e) (assi) = 0x7e; +#define JISX0201_K_ENCODE(c, assi) \ + if ((c) >= 0xff61 && (c) <= 0xff9f) \ + (assi) = (c) - 0xfec0; +#define JISX0201_ENCODE(c, assi) \ + JISX0201_R_ENCODE(c, assi) \ + else JISX0201_K_ENCODE(c, assi) -#define JISX0201_R_DECODE(c, assi) \ - if ((c) < 0x5c) (assi) = (c); \ - else if ((c) == 0x5c) (assi) = 0x00a5; \ - else if ((c) < 0x7e) (assi) = (c); \ - else if ((c) == 0x7e) (assi) = 0x203e; \ - else if ((c) == 0x7f) (assi) = 0x7f; -#define JISX0201_K_DECODE(c, assi) \ - if ((c) >= 0xa1 && (c) <= 0xdf) \ - (assi) = 0xfec0 + (c); -#define JISX0201_DECODE(c, assi) \ - JISX0201_R_DECODE(c, assi) \ - else JISX0201_K_DECODE(c, assi) +#define JISX0201_R_DECODE(c, assi) \ + if ((c) < 0x5c) (assi) = (c); \ + else if ((c) == 0x5c) (assi) = 0x00a5; \ + else if ((c) < 0x7e) (assi) = (c); \ + else if ((c) == 0x7e) (assi) = 0x203e; \ + else if ((c) == 0x7f) (assi) = 0x7f; +#define JISX0201_K_DECODE(c, assi) \ + if ((c) >= 0xa1 && (c) <= 0xdf) \ + (assi) = 0xfec0 + (c); +#define JISX0201_DECODE(c, assi) \ + JISX0201_R_DECODE(c, assi) \ + else JISX0201_K_DECODE(c, assi) Modified: python/branches/release31-maint/Modules/cjkcodecs/cjkcodecs.h ============================================================================== --- python/branches/release31-maint/Modules/cjkcodecs/cjkcodecs.h (original) +++ python/branches/release31-maint/Modules/cjkcodecs/cjkcodecs.h Sun May 9 18:14:21 2010 @@ -13,12 +13,12 @@ /* a unicode "undefined" codepoint */ -#define UNIINV 0xFFFE +#define UNIINV 0xFFFE /* internal-use DBCS codepoints which aren't used by any charsets */ -#define NOCHAR 0xFFFF -#define MULTIC 0xFFFE -#define DBCINV 0xFFFD +#define NOCHAR 0xFFFF +#define MULTIC 0xFFFE +#define DBCINV 0xFFFD /* shorter macros to save source size of mapping tables */ #define U UNIINV @@ -27,94 +27,94 @@ #define D DBCINV struct dbcs_index { - const ucs2_t *map; - unsigned char bottom, top; + const ucs2_t *map; + unsigned char bottom, top; }; typedef struct dbcs_index decode_map; struct widedbcs_index { - const ucs4_t *map; - unsigned char bottom, top; + const ucs4_t *map; + unsigned char bottom, top; }; typedef struct widedbcs_index widedecode_map; struct unim_index { - const DBCHAR *map; - unsigned char bottom, top; + const DBCHAR *map; + unsigned char bottom, top; }; typedef struct unim_index encode_map; struct unim_index_bytebased { - const unsigned char *map; - unsigned char bottom, top; + const unsigned char *map; + unsigned char bottom, top; }; struct dbcs_map { - const char *charset; - const struct unim_index *encmap; - const struct dbcs_index *decmap; + const char *charset; + const struct unim_index *encmap; + const struct dbcs_index *decmap; }; struct pair_encodemap { - ucs4_t uniseq; - DBCHAR code; + ucs4_t uniseq; + DBCHAR code; }; static const MultibyteCodec *codec_list; static const struct dbcs_map *mapping_list; -#define CODEC_INIT(encoding) \ - static int encoding##_codec_init(const void *config) +#define CODEC_INIT(encoding) \ + static int encoding##_codec_init(const void *config) -#define ENCODER_INIT(encoding) \ - static int encoding##_encode_init( \ - MultibyteCodec_State *state, const void *config) -#define ENCODER(encoding) \ - static Py_ssize_t encoding##_encode( \ - MultibyteCodec_State *state, const void *config, \ - const Py_UNICODE **inbuf, Py_ssize_t inleft, \ - unsigned char **outbuf, Py_ssize_t outleft, int flags) -#define ENCODER_RESET(encoding) \ - static Py_ssize_t encoding##_encode_reset( \ - MultibyteCodec_State *state, const void *config, \ - unsigned char **outbuf, Py_ssize_t outleft) - -#define DECODER_INIT(encoding) \ - static int encoding##_decode_init( \ - MultibyteCodec_State *state, const void *config) -#define DECODER(encoding) \ - static Py_ssize_t encoding##_decode( \ - MultibyteCodec_State *state, const void *config, \ - const unsigned char **inbuf, Py_ssize_t inleft, \ - Py_UNICODE **outbuf, Py_ssize_t outleft) -#define DECODER_RESET(encoding) \ - static Py_ssize_t encoding##_decode_reset( \ - MultibyteCodec_State *state, const void *config) +#define ENCODER_INIT(encoding) \ + static int encoding##_encode_init( \ + MultibyteCodec_State *state, const void *config) +#define ENCODER(encoding) \ + static Py_ssize_t encoding##_encode( \ + MultibyteCodec_State *state, const void *config, \ + const Py_UNICODE **inbuf, Py_ssize_t inleft, \ + unsigned char **outbuf, Py_ssize_t outleft, int flags) +#define ENCODER_RESET(encoding) \ + static Py_ssize_t encoding##_encode_reset( \ + MultibyteCodec_State *state, const void *config, \ + unsigned char **outbuf, Py_ssize_t outleft) + +#define DECODER_INIT(encoding) \ + static int encoding##_decode_init( \ + MultibyteCodec_State *state, const void *config) +#define DECODER(encoding) \ + static Py_ssize_t encoding##_decode( \ + MultibyteCodec_State *state, const void *config, \ + const unsigned char **inbuf, Py_ssize_t inleft, \ + Py_UNICODE **outbuf, Py_ssize_t outleft) +#define DECODER_RESET(encoding) \ + static Py_ssize_t encoding##_decode_reset( \ + MultibyteCodec_State *state, const void *config) #if Py_UNICODE_SIZE == 4 -#define UCS4INVALID(code) \ - if ((code) > 0xFFFF) \ - return 1; +#define UCS4INVALID(code) \ + if ((code) > 0xFFFF) \ + return 1; #else -#define UCS4INVALID(code) \ - if (0) ; +#define UCS4INVALID(code) \ + if (0) ; #endif -#define NEXT_IN(i) \ - (*inbuf) += (i); \ - (inleft) -= (i); -#define NEXT_OUT(o) \ - (*outbuf) += (o); \ - (outleft) -= (o); -#define NEXT(i, o) \ - NEXT_IN(i) NEXT_OUT(o) - -#define REQUIRE_INBUF(n) \ - if (inleft < (n)) \ - return MBERR_TOOFEW; -#define REQUIRE_OUTBUF(n) \ - if (outleft < (n)) \ - return MBERR_TOOSMALL; +#define NEXT_IN(i) \ + (*inbuf) += (i); \ + (inleft) -= (i); +#define NEXT_OUT(o) \ + (*outbuf) += (o); \ + (outleft) -= (o); +#define NEXT(i, o) \ + NEXT_IN(i) NEXT_OUT(o) + +#define REQUIRE_INBUF(n) \ + if (inleft < (n)) \ + return MBERR_TOOFEW; +#define REQUIRE_OUTBUF(n) \ + if (outleft < (n)) \ + return MBERR_TOOSMALL; #define IN1 ((*inbuf)[0]) #define IN2 ((*inbuf)[1]) @@ -126,289 +126,289 @@ #define OUT3(c) ((*outbuf)[2]) = (c); #define OUT4(c) ((*outbuf)[3]) = (c); -#define WRITE1(c1) \ - REQUIRE_OUTBUF(1) \ - (*outbuf)[0] = (c1); -#define WRITE2(c1, c2) \ - REQUIRE_OUTBUF(2) \ - (*outbuf)[0] = (c1); \ - (*outbuf)[1] = (c2); -#define WRITE3(c1, c2, c3) \ - REQUIRE_OUTBUF(3) \ - (*outbuf)[0] = (c1); \ - (*outbuf)[1] = (c2); \ - (*outbuf)[2] = (c3); -#define WRITE4(c1, c2, c3, c4) \ - REQUIRE_OUTBUF(4) \ - (*outbuf)[0] = (c1); \ - (*outbuf)[1] = (c2); \ - (*outbuf)[2] = (c3); \ - (*outbuf)[3] = (c4); +#define WRITE1(c1) \ + REQUIRE_OUTBUF(1) \ + (*outbuf)[0] = (c1); +#define WRITE2(c1, c2) \ + REQUIRE_OUTBUF(2) \ + (*outbuf)[0] = (c1); \ + (*outbuf)[1] = (c2); +#define WRITE3(c1, c2, c3) \ + REQUIRE_OUTBUF(3) \ + (*outbuf)[0] = (c1); \ + (*outbuf)[1] = (c2); \ + (*outbuf)[2] = (c3); +#define WRITE4(c1, c2, c3, c4) \ + REQUIRE_OUTBUF(4) \ + (*outbuf)[0] = (c1); \ + (*outbuf)[1] = (c2); \ + (*outbuf)[2] = (c3); \ + (*outbuf)[3] = (c4); #if Py_UNICODE_SIZE == 2 -# define WRITEUCS4(c) \ - REQUIRE_OUTBUF(2) \ - (*outbuf)[0] = 0xd800 + (((c) - 0x10000) >> 10); \ - (*outbuf)[1] = 0xdc00 + (((c) - 0x10000) & 0x3ff); \ - NEXT_OUT(2) +# define WRITEUCS4(c) \ + REQUIRE_OUTBUF(2) \ + (*outbuf)[0] = 0xd800 + (((c) - 0x10000) >> 10); \ + (*outbuf)[1] = 0xdc00 + (((c) - 0x10000) & 0x3ff); \ + NEXT_OUT(2) #else -# define WRITEUCS4(c) \ - REQUIRE_OUTBUF(1) \ - **outbuf = (Py_UNICODE)(c); \ - NEXT_OUT(1) +# define WRITEUCS4(c) \ + REQUIRE_OUTBUF(1) \ + **outbuf = (Py_UNICODE)(c); \ + NEXT_OUT(1) #endif -#define _TRYMAP_ENC(m, assi, val) \ - ((m)->map != NULL && (val) >= (m)->bottom && \ - (val)<= (m)->top && ((assi) = (m)->map[(val) - \ - (m)->bottom]) != NOCHAR) -#define TRYMAP_ENC_COND(charset, assi, uni) \ - _TRYMAP_ENC(&charset##_encmap[(uni) >> 8], assi, (uni) & 0xff) -#define TRYMAP_ENC(charset, assi, uni) \ - if TRYMAP_ENC_COND(charset, assi, uni) - -#define _TRYMAP_DEC(m, assi, val) \ - ((m)->map != NULL && (val) >= (m)->bottom && \ - (val)<= (m)->top && ((assi) = (m)->map[(val) - \ - (m)->bottom]) != UNIINV) -#define TRYMAP_DEC(charset, assi, c1, c2) \ - if _TRYMAP_DEC(&charset##_decmap[c1], assi, c2) - -#define _TRYMAP_ENC_MPLANE(m, assplane, asshi, asslo, val) \ - ((m)->map != NULL && (val) >= (m)->bottom && \ - (val)<= (m)->top && \ - ((assplane) = (m)->map[((val) - (m)->bottom)*3]) != 0 && \ - (((asshi) = (m)->map[((val) - (m)->bottom)*3 + 1]), 1) && \ - (((asslo) = (m)->map[((val) - (m)->bottom)*3 + 2]), 1)) -#define TRYMAP_ENC_MPLANE(charset, assplane, asshi, asslo, uni) \ - if _TRYMAP_ENC_MPLANE(&charset##_encmap[(uni) >> 8], \ - assplane, asshi, asslo, (uni) & 0xff) -#define TRYMAP_DEC_MPLANE(charset, assi, plane, c1, c2) \ - if _TRYMAP_DEC(&charset##_decmap[plane][c1], assi, c2) +#define _TRYMAP_ENC(m, assi, val) \ + ((m)->map != NULL && (val) >= (m)->bottom && \ + (val)<= (m)->top && ((assi) = (m)->map[(val) - \ + (m)->bottom]) != NOCHAR) +#define TRYMAP_ENC_COND(charset, assi, uni) \ + _TRYMAP_ENC(&charset##_encmap[(uni) >> 8], assi, (uni) & 0xff) +#define TRYMAP_ENC(charset, assi, uni) \ + if TRYMAP_ENC_COND(charset, assi, uni) + +#define _TRYMAP_DEC(m, assi, val) \ + ((m)->map != NULL && (val) >= (m)->bottom && \ + (val)<= (m)->top && ((assi) = (m)->map[(val) - \ + (m)->bottom]) != UNIINV) +#define TRYMAP_DEC(charset, assi, c1, c2) \ + if _TRYMAP_DEC(&charset##_decmap[c1], assi, c2) + +#define _TRYMAP_ENC_MPLANE(m, assplane, asshi, asslo, val) \ + ((m)->map != NULL && (val) >= (m)->bottom && \ + (val)<= (m)->top && \ + ((assplane) = (m)->map[((val) - (m)->bottom)*3]) != 0 && \ + (((asshi) = (m)->map[((val) - (m)->bottom)*3 + 1]), 1) && \ + (((asslo) = (m)->map[((val) - (m)->bottom)*3 + 2]), 1)) +#define TRYMAP_ENC_MPLANE(charset, assplane, asshi, asslo, uni) \ + if _TRYMAP_ENC_MPLANE(&charset##_encmap[(uni) >> 8], \ + assplane, asshi, asslo, (uni) & 0xff) +#define TRYMAP_DEC_MPLANE(charset, assi, plane, c1, c2) \ + if _TRYMAP_DEC(&charset##_decmap[plane][c1], assi, c2) #if Py_UNICODE_SIZE == 2 -#define DECODE_SURROGATE(c) \ - if (c >> 10 == 0xd800 >> 10) { /* high surrogate */ \ - REQUIRE_INBUF(2) \ - if (IN2 >> 10 == 0xdc00 >> 10) { /* low surrogate */ \ - c = 0x10000 + ((ucs4_t)(c - 0xd800) << 10) + \ - ((ucs4_t)(IN2) - 0xdc00); \ - } \ - } -#define GET_INSIZE(c) ((c) > 0xffff ? 2 : 1) +#define DECODE_SURROGATE(c) \ + if (c >> 10 == 0xd800 >> 10) { /* high surrogate */ \ + REQUIRE_INBUF(2) \ + if (IN2 >> 10 == 0xdc00 >> 10) { /* low surrogate */ \ + c = 0x10000 + ((ucs4_t)(c - 0xd800) << 10) + \ + ((ucs4_t)(IN2) - 0xdc00); \ + } \ + } +#define GET_INSIZE(c) ((c) > 0xffff ? 2 : 1) #else #define DECODE_SURROGATE(c) {;} -#define GET_INSIZE(c) 1 +#define GET_INSIZE(c) 1 #endif #define BEGIN_MAPPINGS_LIST static const struct dbcs_map _mapping_list[] = { #define MAPPING_ENCONLY(enc) {#enc, (void*)enc##_encmap, NULL}, #define MAPPING_DECONLY(enc) {#enc, NULL, (void*)enc##_decmap}, #define MAPPING_ENCDEC(enc) {#enc, (void*)enc##_encmap, (void*)enc##_decmap}, -#define END_MAPPINGS_LIST \ - {"", NULL, NULL} }; \ - static const struct dbcs_map *mapping_list = \ - (const struct dbcs_map *)_mapping_list; +#define END_MAPPINGS_LIST \ + {"", NULL, NULL} }; \ + static const struct dbcs_map *mapping_list = \ + (const struct dbcs_map *)_mapping_list; #define BEGIN_CODECS_LIST static const MultibyteCodec _codec_list[] = { -#define _STATEFUL_METHODS(enc) \ - enc##_encode, \ - enc##_encode_init, \ - enc##_encode_reset, \ - enc##_decode, \ - enc##_decode_init, \ - enc##_decode_reset, -#define _STATELESS_METHODS(enc) \ - enc##_encode, NULL, NULL, \ - enc##_decode, NULL, NULL, -#define CODEC_STATEFUL(enc) { \ - #enc, NULL, NULL, \ - _STATEFUL_METHODS(enc) \ +#define _STATEFUL_METHODS(enc) \ + enc##_encode, \ + enc##_encode_init, \ + enc##_encode_reset, \ + enc##_decode, \ + enc##_decode_init, \ + enc##_decode_reset, +#define _STATELESS_METHODS(enc) \ + enc##_encode, NULL, NULL, \ + enc##_decode, NULL, NULL, +#define CODEC_STATEFUL(enc) { \ + #enc, NULL, NULL, \ + _STATEFUL_METHODS(enc) \ }, -#define CODEC_STATELESS(enc) { \ - #enc, NULL, NULL, \ - _STATELESS_METHODS(enc) \ +#define CODEC_STATELESS(enc) { \ + #enc, NULL, NULL, \ + _STATELESS_METHODS(enc) \ }, -#define CODEC_STATELESS_WINIT(enc) { \ - #enc, NULL, \ - enc##_codec_init, \ - _STATELESS_METHODS(enc) \ +#define CODEC_STATELESS_WINIT(enc) { \ + #enc, NULL, \ + enc##_codec_init, \ + _STATELESS_METHODS(enc) \ }, -#define END_CODECS_LIST \ - {"", NULL,} }; \ - static const MultibyteCodec *codec_list = \ - (const MultibyteCodec *)_codec_list; +#define END_CODECS_LIST \ + {"", NULL,} }; \ + static const MultibyteCodec *codec_list = \ + (const MultibyteCodec *)_codec_list; static PyObject * getmultibytecodec(void) { - static PyObject *cofunc = NULL; + static PyObject *cofunc = NULL; - if (cofunc == NULL) { - PyObject *mod = PyImport_ImportModuleNoBlock("_multibytecodec"); - if (mod == NULL) - return NULL; - cofunc = PyObject_GetAttrString(mod, "__create_codec"); - Py_DECREF(mod); - } - return cofunc; + if (cofunc == NULL) { + PyObject *mod = PyImport_ImportModuleNoBlock("_multibytecodec"); + if (mod == NULL) + return NULL; + cofunc = PyObject_GetAttrString(mod, "__create_codec"); + Py_DECREF(mod); + } + return cofunc; } static PyObject * getcodec(PyObject *self, PyObject *encoding) { - PyObject *codecobj, *r, *cofunc; - const MultibyteCodec *codec; - const char *enc; - - if (!PyUnicode_Check(encoding)) { - PyErr_SetString(PyExc_TypeError, - "encoding name must be a string."); - return NULL; - } - enc = _PyUnicode_AsString(encoding); - if (enc == NULL) - return NULL; - - cofunc = getmultibytecodec(); - if (cofunc == NULL) - return NULL; - - for (codec = codec_list; codec->encoding[0]; codec++) - if (strcmp(codec->encoding, enc) == 0) - break; - - if (codec->encoding[0] == '\0') { - PyErr_SetString(PyExc_LookupError, - "no such codec is supported."); - return NULL; - } - - codecobj = PyCapsule_New((void *)codec, PyMultibyteCodec_CAPSULE_NAME, NULL); - if (codecobj == NULL) - return NULL; + PyObject *codecobj, *r, *cofunc; + const MultibyteCodec *codec; + const char *enc; + + if (!PyUnicode_Check(encoding)) { + PyErr_SetString(PyExc_TypeError, + "encoding name must be a string."); + return NULL; + } + enc = _PyUnicode_AsString(encoding); + if (enc == NULL) + return NULL; + + cofunc = getmultibytecodec(); + if (cofunc == NULL) + return NULL; + + for (codec = codec_list; codec->encoding[0]; codec++) + if (strcmp(codec->encoding, enc) == 0) + break; + + if (codec->encoding[0] == '\0') { + PyErr_SetString(PyExc_LookupError, + "no such codec is supported."); + return NULL; + } + + codecobj = PyCapsule_New((void *)codec, PyMultibyteCodec_CAPSULE_NAME, NULL); + if (codecobj == NULL) + return NULL; - r = PyObject_CallFunctionObjArgs(cofunc, codecobj, NULL); - Py_DECREF(codecobj); + r = PyObject_CallFunctionObjArgs(cofunc, codecobj, NULL); + Py_DECREF(codecobj); - return r; + return r; } static struct PyMethodDef __methods[] = { - {"getcodec", (PyCFunction)getcodec, METH_O, ""}, - {NULL, NULL}, + {"getcodec", (PyCFunction)getcodec, METH_O, ""}, + {NULL, NULL}, }; static int register_maps(PyObject *module) { - const struct dbcs_map *h; + const struct dbcs_map *h; - for (h = mapping_list; h->charset[0] != '\0'; h++) { - char mhname[256] = "__map_"; - int r; - strcpy(mhname + sizeof("__map_") - 1, h->charset); - r = PyModule_AddObject(module, mhname, - PyCapsule_New((void *)h, PyMultibyteCodec_CAPSULE_NAME, NULL)); - if (r == -1) - return -1; - } - return 0; + for (h = mapping_list; h->charset[0] != '\0'; h++) { + char mhname[256] = "__map_"; + int r; + strcpy(mhname + sizeof("__map_") - 1, h->charset); + r = PyModule_AddObject(module, mhname, + PyCapsule_New((void *)h, PyMultibyteCodec_CAPSULE_NAME, NULL)); + if (r == -1) + return -1; + } + return 0; } #ifdef USING_BINARY_PAIR_SEARCH static DBCHAR find_pairencmap(ucs2_t body, ucs2_t modifier, - const struct pair_encodemap *haystack, int haystacksize) + const struct pair_encodemap *haystack, int haystacksize) { - int pos, min, max; - ucs4_t value = body << 16 | modifier; + int pos, min, max; + ucs4_t value = body << 16 | modifier; - min = 0; - max = haystacksize; + min = 0; + max = haystacksize; - for (pos = haystacksize >> 1; min != max; pos = (min + max) >> 1) - if (value < haystack[pos].uniseq) { - if (max == pos) break; - else max = pos; - } - else if (value > haystack[pos].uniseq) { - if (min == pos) break; - else min = pos; - } - else - break; - - if (value == haystack[pos].uniseq) - return haystack[pos].code; - else - return DBCINV; + for (pos = haystacksize >> 1; min != max; pos = (min + max) >> 1) + if (value < haystack[pos].uniseq) { + if (max == pos) break; + else max = pos; + } + else if (value > haystack[pos].uniseq) { + if (min == pos) break; + else min = pos; + } + else + break; + + if (value == haystack[pos].uniseq) + return haystack[pos].code; + else + return DBCINV; } #endif #ifdef USING_IMPORTED_MAPS #define IMPORT_MAP(locale, charset, encmap, decmap) \ - importmap("_codecs_" #locale, "__map_" #charset, \ - (const void**)encmap, (const void**)decmap) + importmap("_codecs_" #locale, "__map_" #charset, \ + (const void**)encmap, (const void**)decmap) static int importmap(const char *modname, const char *symbol, - const void **encmap, const void **decmap) + const void **encmap, const void **decmap) { - PyObject *o, *mod; + PyObject *o, *mod; - mod = PyImport_ImportModule((char *)modname); - if (mod == NULL) - return -1; - - o = PyObject_GetAttrString(mod, (char*)symbol); - if (o == NULL) - goto errorexit; - else if (!PyCapsule_IsValid(o, PyMultibyteCodec_CAPSULE_NAME)) { - PyErr_SetString(PyExc_ValueError, - "map data must be a Capsule."); - goto errorexit; - } - else { - struct dbcs_map *map; - map = PyCapsule_GetPointer(o, PyMultibyteCodec_CAPSULE_NAME); - if (encmap != NULL) - *encmap = map->encmap; - if (decmap != NULL) - *decmap = map->decmap; - Py_DECREF(o); - } + mod = PyImport_ImportModule((char *)modname); + if (mod == NULL) + return -1; + + o = PyObject_GetAttrString(mod, (char*)symbol); + if (o == NULL) + goto errorexit; + else if (!PyCapsule_IsValid(o, PyMultibyteCodec_CAPSULE_NAME)) { + PyErr_SetString(PyExc_ValueError, + "map data must be a Capsule."); + goto errorexit; + } + else { + struct dbcs_map *map; + map = PyCapsule_GetPointer(o, PyMultibyteCodec_CAPSULE_NAME); + if (encmap != NULL) + *encmap = map->encmap; + if (decmap != NULL) + *decmap = map->decmap; + Py_DECREF(o); + } - Py_DECREF(mod); - return 0; + Py_DECREF(mod); + return 0; errorexit: - Py_DECREF(mod); - return -1; + Py_DECREF(mod); + return -1; } #endif -#define I_AM_A_MODULE_FOR(loc) \ - static struct PyModuleDef __module = { \ - PyModuleDef_HEAD_INIT, \ - "_codecs_"#loc, \ - NULL, \ - 0, \ - __methods, \ - NULL, \ - NULL, \ - NULL, \ - NULL \ - }; \ - PyObject* \ - PyInit__codecs_##loc(void) \ - { \ - PyObject *m = PyModule_Create(&__module); \ - if (m != NULL) \ - (void)register_maps(m); \ - return m; \ - } +#define I_AM_A_MODULE_FOR(loc) \ + static struct PyModuleDef __module = { \ + PyModuleDef_HEAD_INIT, \ + "_codecs_"#loc, \ + NULL, \ + 0, \ + __methods, \ + NULL, \ + NULL, \ + NULL, \ + NULL \ + }; \ + PyObject* \ + PyInit__codecs_##loc(void) \ + { \ + PyObject *m = PyModule_Create(&__module); \ + if (m != NULL) \ + (void)register_maps(m); \ + return m; \ + } #endif Modified: python/branches/release31-maint/Modules/cjkcodecs/emu_jisx0213_2000.h ============================================================================== --- python/branches/release31-maint/Modules/cjkcodecs/emu_jisx0213_2000.h (original) +++ python/branches/release31-maint/Modules/cjkcodecs/emu_jisx0213_2000.h Sun May 9 18:14:21 2010 @@ -5,39 +5,39 @@ #define EMULATE_JISX0213_2000_ENCODE_INVALID 1 #endif -#define EMULATE_JISX0213_2000_ENCODE_BMP(assi, c) \ - if (config == (void *)2000 && ( \ - (c) == 0x9B1C || (c) == 0x4FF1 || \ - (c) == 0x525D || (c) == 0x541E || \ - (c) == 0x5653 || (c) == 0x59F8 || \ - (c) == 0x5C5B || (c) == 0x5E77 || \ - (c) == 0x7626 || (c) == 0x7E6B)) \ - return EMULATE_JISX0213_2000_ENCODE_INVALID; \ - else if (config == (void *)2000 && (c) == 0x9B1D) \ - (assi) = 0x8000 | 0x7d3b; \ +#define EMULATE_JISX0213_2000_ENCODE_BMP(assi, c) \ + if (config == (void *)2000 && ( \ + (c) == 0x9B1C || (c) == 0x4FF1 || \ + (c) == 0x525D || (c) == 0x541E || \ + (c) == 0x5653 || (c) == 0x59F8 || \ + (c) == 0x5C5B || (c) == 0x5E77 || \ + (c) == 0x7626 || (c) == 0x7E6B)) \ + return EMULATE_JISX0213_2000_ENCODE_INVALID; \ + else if (config == (void *)2000 && (c) == 0x9B1D) \ + (assi) = 0x8000 | 0x7d3b; \ -#define EMULATE_JISX0213_2000_ENCODE_EMP(assi, c) \ - if (config == (void *)2000 && (c) == 0x20B9F) \ - return EMULATE_JISX0213_2000_ENCODE_INVALID; +#define EMULATE_JISX0213_2000_ENCODE_EMP(assi, c) \ + if (config == (void *)2000 && (c) == 0x20B9F) \ + return EMULATE_JISX0213_2000_ENCODE_INVALID; #ifndef EMULATE_JISX0213_2000_DECODE_INVALID #define EMULATE_JISX0213_2000_DECODE_INVALID 2 #endif -#define EMULATE_JISX0213_2000_DECODE_PLANE1(assi, c1, c2) \ - if (config == (void *)2000 && \ - (((c1) == 0x2E && (c2) == 0x21) || \ - ((c1) == 0x2F && (c2) == 0x7E) || \ - ((c1) == 0x4F && (c2) == 0x54) || \ - ((c1) == 0x4F && (c2) == 0x7E) || \ - ((c1) == 0x74 && (c2) == 0x27) || \ - ((c1) == 0x7E && (c2) == 0x7A) || \ - ((c1) == 0x7E && (c2) == 0x7B) || \ - ((c1) == 0x7E && (c2) == 0x7C) || \ - ((c1) == 0x7E && (c2) == 0x7D) || \ - ((c1) == 0x7E && (c2) == 0x7E))) \ - return EMULATE_JISX0213_2000_DECODE_INVALID; +#define EMULATE_JISX0213_2000_DECODE_PLANE1(assi, c1, c2) \ + if (config == (void *)2000 && \ + (((c1) == 0x2E && (c2) == 0x21) || \ + ((c1) == 0x2F && (c2) == 0x7E) || \ + ((c1) == 0x4F && (c2) == 0x54) || \ + ((c1) == 0x4F && (c2) == 0x7E) || \ + ((c1) == 0x74 && (c2) == 0x27) || \ + ((c1) == 0x7E && (c2) == 0x7A) || \ + ((c1) == 0x7E && (c2) == 0x7B) || \ + ((c1) == 0x7E && (c2) == 0x7C) || \ + ((c1) == 0x7E && (c2) == 0x7D) || \ + ((c1) == 0x7E && (c2) == 0x7E))) \ + return EMULATE_JISX0213_2000_DECODE_INVALID; -#define EMULATE_JISX0213_2000_DECODE_PLANE2(assi, c1, c2) \ - if (config == (void *)2000 && (c1) == 0x7D && (c2) == 0x3B) \ - (assi) = 0x9B1D; +#define EMULATE_JISX0213_2000_DECODE_PLANE2(assi, c1, c2) \ + if (config == (void *)2000 && (c1) == 0x7D && (c2) == 0x3B) \ + (assi) = 0x9B1D; Modified: python/branches/release31-maint/Modules/cjkcodecs/multibytecodec.c ============================================================================== --- python/branches/release31-maint/Modules/cjkcodecs/multibytecodec.c (original) +++ python/branches/release31-maint/Modules/cjkcodecs/multibytecodec.c Sun May 9 18:14:21 2010 @@ -45,179 +45,179 @@ static char *streamkwarglist[] = {"stream", "errors", NULL}; static PyObject *multibytecodec_encode(MultibyteCodec *, - MultibyteCodec_State *, const Py_UNICODE **, Py_ssize_t, - PyObject *, int); + MultibyteCodec_State *, const Py_UNICODE **, Py_ssize_t, + PyObject *, int); -#define MBENC_RESET MBENC_MAX<<1 /* reset after an encoding session */ +#define MBENC_RESET MBENC_MAX<<1 /* reset after an encoding session */ static PyObject * make_tuple(PyObject *object, Py_ssize_t len) { - PyObject *v, *w; + PyObject *v, *w; - if (object == NULL) - return NULL; + if (object == NULL) + return NULL; - v = PyTuple_New(2); - if (v == NULL) { - Py_DECREF(object); - return NULL; - } - PyTuple_SET_ITEM(v, 0, object); - - w = PyLong_FromSsize_t(len); - if (w == NULL) { - Py_DECREF(v); - return NULL; - } - PyTuple_SET_ITEM(v, 1, w); + v = PyTuple_New(2); + if (v == NULL) { + Py_DECREF(object); + return NULL; + } + PyTuple_SET_ITEM(v, 0, object); + + w = PyLong_FromSsize_t(len); + if (w == NULL) { + Py_DECREF(v); + return NULL; + } + PyTuple_SET_ITEM(v, 1, w); - return v; + return v; } static PyObject * internal_error_callback(const char *errors) { - if (errors == NULL || strcmp(errors, "strict") == 0) - return ERROR_STRICT; - else if (strcmp(errors, "ignore") == 0) - return ERROR_IGNORE; - else if (strcmp(errors, "replace") == 0) - return ERROR_REPLACE; - else - return PyUnicode_FromString(errors); + if (errors == NULL || strcmp(errors, "strict") == 0) + return ERROR_STRICT; + else if (strcmp(errors, "ignore") == 0) + return ERROR_IGNORE; + else if (strcmp(errors, "replace") == 0) + return ERROR_REPLACE; + else + return PyUnicode_FromString(errors); } static PyObject * call_error_callback(PyObject *errors, PyObject *exc) { - PyObject *args, *cb, *r; - const char *str; + PyObject *args, *cb, *r; + const char *str; - assert(PyUnicode_Check(errors)); - str = _PyUnicode_AsString(errors); - if (str == NULL) - return NULL; - cb = PyCodec_LookupError(str); - if (cb == NULL) - return NULL; - - args = PyTuple_New(1); - if (args == NULL) { - Py_DECREF(cb); - return NULL; - } - - PyTuple_SET_ITEM(args, 0, exc); - Py_INCREF(exc); - - r = PyObject_CallObject(cb, args); - Py_DECREF(args); - Py_DECREF(cb); - return r; + assert(PyUnicode_Check(errors)); + str = _PyUnicode_AsString(errors); + if (str == NULL) + return NULL; + cb = PyCodec_LookupError(str); + if (cb == NULL) + return NULL; + + args = PyTuple_New(1); + if (args == NULL) { + Py_DECREF(cb); + return NULL; + } + + PyTuple_SET_ITEM(args, 0, exc); + Py_INCREF(exc); + + r = PyObject_CallObject(cb, args); + Py_DECREF(args); + Py_DECREF(cb); + return r; } static PyObject * codecctx_errors_get(MultibyteStatefulCodecContext *self) { - const char *errors; + const char *errors; - if (self->errors == ERROR_STRICT) - errors = "strict"; - else if (self->errors == ERROR_IGNORE) - errors = "ignore"; - else if (self->errors == ERROR_REPLACE) - errors = "replace"; - else { - Py_INCREF(self->errors); - return self->errors; - } + if (self->errors == ERROR_STRICT) + errors = "strict"; + else if (self->errors == ERROR_IGNORE) + errors = "ignore"; + else if (self->errors == ERROR_REPLACE) + errors = "replace"; + else { + Py_INCREF(self->errors); + return self->errors; + } - return PyUnicode_FromString(errors); + return PyUnicode_FromString(errors); } static int codecctx_errors_set(MultibyteStatefulCodecContext *self, PyObject *value, - void *closure) + void *closure) { - PyObject *cb; - const char *str; + PyObject *cb; + const char *str; - if (!PyUnicode_Check(value)) { - PyErr_SetString(PyExc_TypeError, "errors must be a string"); - return -1; - } - - str = _PyUnicode_AsString(value); - if (str == NULL) - return -1; - - cb = internal_error_callback(str); - if (cb == NULL) - return -1; - - ERROR_DECREF(self->errors); - self->errors = cb; - return 0; + if (!PyUnicode_Check(value)) { + PyErr_SetString(PyExc_TypeError, "errors must be a string"); + return -1; + } + + str = _PyUnicode_AsString(value); + if (str == NULL) + return -1; + + cb = internal_error_callback(str); + if (cb == NULL) + return -1; + + ERROR_DECREF(self->errors); + self->errors = cb; + return 0; } /* This getset handlers list is used by all the stateful codec objects */ static PyGetSetDef codecctx_getsets[] = { - {"errors", (getter)codecctx_errors_get, - (setter)codecctx_errors_set, - PyDoc_STR("how to treat errors")}, - {NULL,} + {"errors", (getter)codecctx_errors_get, + (setter)codecctx_errors_set, + PyDoc_STR("how to treat errors")}, + {NULL,} }; static int expand_encodebuffer(MultibyteEncodeBuffer *buf, Py_ssize_t esize) { - Py_ssize_t orgpos, orgsize, incsize; + Py_ssize_t orgpos, orgsize, incsize; - orgpos = (Py_ssize_t)((char *)buf->outbuf - - PyBytes_AS_STRING(buf->outobj)); - orgsize = PyBytes_GET_SIZE(buf->outobj); - incsize = (esize < (orgsize >> 1) ? (orgsize >> 1) | 1 : esize); + orgpos = (Py_ssize_t)((char *)buf->outbuf - + PyBytes_AS_STRING(buf->outobj)); + orgsize = PyBytes_GET_SIZE(buf->outobj); + incsize = (esize < (orgsize >> 1) ? (orgsize >> 1) | 1 : esize); - if (orgsize > PY_SSIZE_T_MAX - incsize) - return -1; + if (orgsize > PY_SSIZE_T_MAX - incsize) + return -1; - if (_PyBytes_Resize(&buf->outobj, orgsize + incsize) == -1) - return -1; + if (_PyBytes_Resize(&buf->outobj, orgsize + incsize) == -1) + return -1; - buf->outbuf = (unsigned char *)PyBytes_AS_STRING(buf->outobj) +orgpos; - buf->outbuf_end = (unsigned char *)PyBytes_AS_STRING(buf->outobj) - + PyBytes_GET_SIZE(buf->outobj); + buf->outbuf = (unsigned char *)PyBytes_AS_STRING(buf->outobj) +orgpos; + buf->outbuf_end = (unsigned char *)PyBytes_AS_STRING(buf->outobj) + + PyBytes_GET_SIZE(buf->outobj); - return 0; + return 0; } -#define REQUIRE_ENCODEBUFFER(buf, s) { \ - if ((s) < 1 || (buf)->outbuf + (s) > (buf)->outbuf_end) \ - if (expand_encodebuffer(buf, s) == -1) \ - goto errorexit; \ +#define REQUIRE_ENCODEBUFFER(buf, s) { \ + if ((s) < 1 || (buf)->outbuf + (s) > (buf)->outbuf_end) \ + if (expand_encodebuffer(buf, s) == -1) \ + goto errorexit; \ } static int expand_decodebuffer(MultibyteDecodeBuffer *buf, Py_ssize_t esize) { - Py_ssize_t orgpos, orgsize; + Py_ssize_t orgpos, orgsize; - orgpos = (Py_ssize_t)(buf->outbuf - PyUnicode_AS_UNICODE(buf->outobj)); - orgsize = PyUnicode_GET_SIZE(buf->outobj); - if (PyUnicode_Resize(&buf->outobj, orgsize + ( - esize < (orgsize >> 1) ? (orgsize >> 1) | 1 : esize)) == -1) - return -1; - - buf->outbuf = PyUnicode_AS_UNICODE(buf->outobj) + orgpos; - buf->outbuf_end = PyUnicode_AS_UNICODE(buf->outobj) - + PyUnicode_GET_SIZE(buf->outobj); - - return 0; -} -#define REQUIRE_DECODEBUFFER(buf, s) { \ - if ((s) < 1 || (buf)->outbuf + (s) > (buf)->outbuf_end) \ - if (expand_decodebuffer(buf, s) == -1) \ - goto errorexit; \ + orgpos = (Py_ssize_t)(buf->outbuf - PyUnicode_AS_UNICODE(buf->outobj)); + orgsize = PyUnicode_GET_SIZE(buf->outobj); + if (PyUnicode_Resize(&buf->outobj, orgsize + ( + esize < (orgsize >> 1) ? (orgsize >> 1) | 1 : esize)) == -1) + return -1; + + buf->outbuf = PyUnicode_AS_UNICODE(buf->outobj) + orgpos; + buf->outbuf_end = PyUnicode_AS_UNICODE(buf->outobj) + + PyUnicode_GET_SIZE(buf->outobj); + + return 0; +} +#define REQUIRE_DECODEBUFFER(buf, s) { \ + if ((s) < 1 || (buf)->outbuf + (s) > (buf)->outbuf_end) \ + if (expand_decodebuffer(buf, s) == -1) \ + goto errorexit; \ } @@ -227,504 +227,504 @@ static int multibytecodec_encerror(MultibyteCodec *codec, - MultibyteCodec_State *state, - MultibyteEncodeBuffer *buf, - PyObject *errors, Py_ssize_t e) -{ - PyObject *retobj = NULL, *retstr = NULL, *tobj; - Py_ssize_t retstrsize, newpos; - Py_ssize_t esize, start, end; - const char *reason; - - if (e > 0) { - reason = "illegal multibyte sequence"; - esize = e; - } - else { - switch (e) { - case MBERR_TOOSMALL: - REQUIRE_ENCODEBUFFER(buf, -1); - return 0; /* retry it */ - case MBERR_TOOFEW: - reason = "incomplete multibyte sequence"; - esize = (Py_ssize_t)(buf->inbuf_end - buf->inbuf); - break; - case MBERR_INTERNAL: - PyErr_SetString(PyExc_RuntimeError, - "internal codec error"); - return -1; - default: - PyErr_SetString(PyExc_RuntimeError, - "unknown runtime error"); - return -1; - } - } - - if (errors == ERROR_REPLACE) { - const Py_UNICODE replchar = '?', *inbuf = &replchar; - Py_ssize_t r; - - for (;;) { - Py_ssize_t outleft; - - outleft = (Py_ssize_t)(buf->outbuf_end - buf->outbuf); - r = codec->encode(state, codec->config, &inbuf, 1, - &buf->outbuf, outleft, 0); - if (r == MBERR_TOOSMALL) { - REQUIRE_ENCODEBUFFER(buf, -1); - continue; - } - else - break; - } - - if (r != 0) { - REQUIRE_ENCODEBUFFER(buf, 1); - *buf->outbuf++ = '?'; - } - } - if (errors == ERROR_IGNORE || errors == ERROR_REPLACE) { - buf->inbuf += esize; - return 0; - } - - start = (Py_ssize_t)(buf->inbuf - buf->inbuf_top); - end = start + esize; - - /* use cached exception object if available */ - if (buf->excobj == NULL) { - buf->excobj = PyUnicodeEncodeError_Create(codec->encoding, - buf->inbuf_top, - buf->inbuf_end - buf->inbuf_top, - start, end, reason); - if (buf->excobj == NULL) - goto errorexit; - } - else - if (PyUnicodeEncodeError_SetStart(buf->excobj, start) != 0 || - PyUnicodeEncodeError_SetEnd(buf->excobj, end) != 0 || - PyUnicodeEncodeError_SetReason(buf->excobj, reason) != 0) - goto errorexit; - - if (errors == ERROR_STRICT) { - PyCodec_StrictErrors(buf->excobj); - goto errorexit; - } - - retobj = call_error_callback(errors, buf->excobj); - if (retobj == NULL) - goto errorexit; - - if (!PyTuple_Check(retobj) || PyTuple_GET_SIZE(retobj) != 2 || - !PyUnicode_Check((tobj = PyTuple_GET_ITEM(retobj, 0))) || - !PyLong_Check(PyTuple_GET_ITEM(retobj, 1))) { - PyErr_SetString(PyExc_TypeError, - "encoding error handler must return " - "(unicode, int) tuple"); - goto errorexit; - } - - { - const Py_UNICODE *uraw = PyUnicode_AS_UNICODE(tobj); - - retstr = multibytecodec_encode(codec, state, &uraw, - PyUnicode_GET_SIZE(tobj), ERROR_STRICT, - MBENC_FLUSH); - if (retstr == NULL) - goto errorexit; - } - - assert(PyBytes_Check(retstr)); - retstrsize = PyBytes_GET_SIZE(retstr); - REQUIRE_ENCODEBUFFER(buf, retstrsize); - - memcpy(buf->outbuf, PyBytes_AS_STRING(retstr), retstrsize); - buf->outbuf += retstrsize; - - newpos = PyLong_AsSsize_t(PyTuple_GET_ITEM(retobj, 1)); - if (newpos < 0 && !PyErr_Occurred()) - newpos += (Py_ssize_t)(buf->inbuf_end - buf->inbuf_top); - if (newpos < 0 || buf->inbuf_top + newpos > buf->inbuf_end) { - PyErr_Clear(); - PyErr_Format(PyExc_IndexError, - "position %zd from error handler out of bounds", - newpos); - goto errorexit; - } - buf->inbuf = buf->inbuf_top + newpos; - - Py_DECREF(retobj); - Py_DECREF(retstr); - return 0; + MultibyteCodec_State *state, + MultibyteEncodeBuffer *buf, + PyObject *errors, Py_ssize_t e) +{ + PyObject *retobj = NULL, *retstr = NULL, *tobj; + Py_ssize_t retstrsize, newpos; + Py_ssize_t esize, start, end; + const char *reason; + + if (e > 0) { + reason = "illegal multibyte sequence"; + esize = e; + } + else { + switch (e) { + case MBERR_TOOSMALL: + REQUIRE_ENCODEBUFFER(buf, -1); + return 0; /* retry it */ + case MBERR_TOOFEW: + reason = "incomplete multibyte sequence"; + esize = (Py_ssize_t)(buf->inbuf_end - buf->inbuf); + break; + case MBERR_INTERNAL: + PyErr_SetString(PyExc_RuntimeError, + "internal codec error"); + return -1; + default: + PyErr_SetString(PyExc_RuntimeError, + "unknown runtime error"); + return -1; + } + } + + if (errors == ERROR_REPLACE) { + const Py_UNICODE replchar = '?', *inbuf = &replchar; + Py_ssize_t r; + + for (;;) { + Py_ssize_t outleft; + + outleft = (Py_ssize_t)(buf->outbuf_end - buf->outbuf); + r = codec->encode(state, codec->config, &inbuf, 1, + &buf->outbuf, outleft, 0); + if (r == MBERR_TOOSMALL) { + REQUIRE_ENCODEBUFFER(buf, -1); + continue; + } + else + break; + } + + if (r != 0) { + REQUIRE_ENCODEBUFFER(buf, 1); + *buf->outbuf++ = '?'; + } + } + if (errors == ERROR_IGNORE || errors == ERROR_REPLACE) { + buf->inbuf += esize; + return 0; + } + + start = (Py_ssize_t)(buf->inbuf - buf->inbuf_top); + end = start + esize; + + /* use cached exception object if available */ + if (buf->excobj == NULL) { + buf->excobj = PyUnicodeEncodeError_Create(codec->encoding, + buf->inbuf_top, + buf->inbuf_end - buf->inbuf_top, + start, end, reason); + if (buf->excobj == NULL) + goto errorexit; + } + else + if (PyUnicodeEncodeError_SetStart(buf->excobj, start) != 0 || + PyUnicodeEncodeError_SetEnd(buf->excobj, end) != 0 || + PyUnicodeEncodeError_SetReason(buf->excobj, reason) != 0) + goto errorexit; + + if (errors == ERROR_STRICT) { + PyCodec_StrictErrors(buf->excobj); + goto errorexit; + } + + retobj = call_error_callback(errors, buf->excobj); + if (retobj == NULL) + goto errorexit; + + if (!PyTuple_Check(retobj) || PyTuple_GET_SIZE(retobj) != 2 || + !PyUnicode_Check((tobj = PyTuple_GET_ITEM(retobj, 0))) || + !PyLong_Check(PyTuple_GET_ITEM(retobj, 1))) { + PyErr_SetString(PyExc_TypeError, + "encoding error handler must return " + "(unicode, int) tuple"); + goto errorexit; + } + + { + const Py_UNICODE *uraw = PyUnicode_AS_UNICODE(tobj); + + retstr = multibytecodec_encode(codec, state, &uraw, + PyUnicode_GET_SIZE(tobj), ERROR_STRICT, + MBENC_FLUSH); + if (retstr == NULL) + goto errorexit; + } + + assert(PyBytes_Check(retstr)); + retstrsize = PyBytes_GET_SIZE(retstr); + REQUIRE_ENCODEBUFFER(buf, retstrsize); + + memcpy(buf->outbuf, PyBytes_AS_STRING(retstr), retstrsize); + buf->outbuf += retstrsize; + + newpos = PyLong_AsSsize_t(PyTuple_GET_ITEM(retobj, 1)); + if (newpos < 0 && !PyErr_Occurred()) + newpos += (Py_ssize_t)(buf->inbuf_end - buf->inbuf_top); + if (newpos < 0 || buf->inbuf_top + newpos > buf->inbuf_end) { + PyErr_Clear(); + PyErr_Format(PyExc_IndexError, + "position %zd from error handler out of bounds", + newpos); + goto errorexit; + } + buf->inbuf = buf->inbuf_top + newpos; + + Py_DECREF(retobj); + Py_DECREF(retstr); + return 0; errorexit: - Py_XDECREF(retobj); - Py_XDECREF(retstr); - return -1; + Py_XDECREF(retobj); + Py_XDECREF(retstr); + return -1; } static int multibytecodec_decerror(MultibyteCodec *codec, - MultibyteCodec_State *state, - MultibyteDecodeBuffer *buf, - PyObject *errors, Py_ssize_t e) -{ - PyObject *retobj = NULL, *retuni = NULL; - Py_ssize_t retunisize, newpos; - const char *reason; - Py_ssize_t esize, start, end; - - if (e > 0) { - reason = "illegal multibyte sequence"; - esize = e; - } - else { - switch (e) { - case MBERR_TOOSMALL: - REQUIRE_DECODEBUFFER(buf, -1); - return 0; /* retry it */ - case MBERR_TOOFEW: - reason = "incomplete multibyte sequence"; - esize = (Py_ssize_t)(buf->inbuf_end - buf->inbuf); - break; - case MBERR_INTERNAL: - PyErr_SetString(PyExc_RuntimeError, - "internal codec error"); - return -1; - default: - PyErr_SetString(PyExc_RuntimeError, - "unknown runtime error"); - return -1; - } - } - - if (errors == ERROR_REPLACE) { - REQUIRE_DECODEBUFFER(buf, 1); - *buf->outbuf++ = Py_UNICODE_REPLACEMENT_CHARACTER; - } - if (errors == ERROR_IGNORE || errors == ERROR_REPLACE) { - buf->inbuf += esize; - return 0; - } - - start = (Py_ssize_t)(buf->inbuf - buf->inbuf_top); - end = start + esize; - - /* use cached exception object if available */ - if (buf->excobj == NULL) { - buf->excobj = PyUnicodeDecodeError_Create(codec->encoding, - (const char *)buf->inbuf_top, - (Py_ssize_t)(buf->inbuf_end - buf->inbuf_top), - start, end, reason); - if (buf->excobj == NULL) - goto errorexit; - } - else - if (PyUnicodeDecodeError_SetStart(buf->excobj, start) || - PyUnicodeDecodeError_SetEnd(buf->excobj, end) || - PyUnicodeDecodeError_SetReason(buf->excobj, reason)) - goto errorexit; - - if (errors == ERROR_STRICT) { - PyCodec_StrictErrors(buf->excobj); - goto errorexit; - } - - retobj = call_error_callback(errors, buf->excobj); - if (retobj == NULL) - goto errorexit; - - if (!PyTuple_Check(retobj) || PyTuple_GET_SIZE(retobj) != 2 || - !PyUnicode_Check((retuni = PyTuple_GET_ITEM(retobj, 0))) || - !PyLong_Check(PyTuple_GET_ITEM(retobj, 1))) { - PyErr_SetString(PyExc_TypeError, - "decoding error handler must return " - "(unicode, int) tuple"); - goto errorexit; - } - - retunisize = PyUnicode_GET_SIZE(retuni); - if (retunisize > 0) { - REQUIRE_DECODEBUFFER(buf, retunisize); - memcpy((char *)buf->outbuf, PyUnicode_AS_DATA(retuni), - retunisize * Py_UNICODE_SIZE); - buf->outbuf += retunisize; - } - - newpos = PyLong_AsSsize_t(PyTuple_GET_ITEM(retobj, 1)); - if (newpos < 0 && !PyErr_Occurred()) - newpos += (Py_ssize_t)(buf->inbuf_end - buf->inbuf_top); - if (newpos < 0 || buf->inbuf_top + newpos > buf->inbuf_end) { - PyErr_Clear(); - PyErr_Format(PyExc_IndexError, - "position %zd from error handler out of bounds", - newpos); - goto errorexit; - } - buf->inbuf = buf->inbuf_top + newpos; - Py_DECREF(retobj); - return 0; + MultibyteCodec_State *state, + MultibyteDecodeBuffer *buf, + PyObject *errors, Py_ssize_t e) +{ + PyObject *retobj = NULL, *retuni = NULL; + Py_ssize_t retunisize, newpos; + const char *reason; + Py_ssize_t esize, start, end; + + if (e > 0) { + reason = "illegal multibyte sequence"; + esize = e; + } + else { + switch (e) { + case MBERR_TOOSMALL: + REQUIRE_DECODEBUFFER(buf, -1); + return 0; /* retry it */ + case MBERR_TOOFEW: + reason = "incomplete multibyte sequence"; + esize = (Py_ssize_t)(buf->inbuf_end - buf->inbuf); + break; + case MBERR_INTERNAL: + PyErr_SetString(PyExc_RuntimeError, + "internal codec error"); + return -1; + default: + PyErr_SetString(PyExc_RuntimeError, + "unknown runtime error"); + return -1; + } + } + + if (errors == ERROR_REPLACE) { + REQUIRE_DECODEBUFFER(buf, 1); + *buf->outbuf++ = Py_UNICODE_REPLACEMENT_CHARACTER; + } + if (errors == ERROR_IGNORE || errors == ERROR_REPLACE) { + buf->inbuf += esize; + return 0; + } + + start = (Py_ssize_t)(buf->inbuf - buf->inbuf_top); + end = start + esize; + + /* use cached exception object if available */ + if (buf->excobj == NULL) { + buf->excobj = PyUnicodeDecodeError_Create(codec->encoding, + (const char *)buf->inbuf_top, + (Py_ssize_t)(buf->inbuf_end - buf->inbuf_top), + start, end, reason); + if (buf->excobj == NULL) + goto errorexit; + } + else + if (PyUnicodeDecodeError_SetStart(buf->excobj, start) || + PyUnicodeDecodeError_SetEnd(buf->excobj, end) || + PyUnicodeDecodeError_SetReason(buf->excobj, reason)) + goto errorexit; + + if (errors == ERROR_STRICT) { + PyCodec_StrictErrors(buf->excobj); + goto errorexit; + } + + retobj = call_error_callback(errors, buf->excobj); + if (retobj == NULL) + goto errorexit; + + if (!PyTuple_Check(retobj) || PyTuple_GET_SIZE(retobj) != 2 || + !PyUnicode_Check((retuni = PyTuple_GET_ITEM(retobj, 0))) || + !PyLong_Check(PyTuple_GET_ITEM(retobj, 1))) { + PyErr_SetString(PyExc_TypeError, + "decoding error handler must return " + "(unicode, int) tuple"); + goto errorexit; + } + + retunisize = PyUnicode_GET_SIZE(retuni); + if (retunisize > 0) { + REQUIRE_DECODEBUFFER(buf, retunisize); + memcpy((char *)buf->outbuf, PyUnicode_AS_DATA(retuni), + retunisize * Py_UNICODE_SIZE); + buf->outbuf += retunisize; + } + + newpos = PyLong_AsSsize_t(PyTuple_GET_ITEM(retobj, 1)); + if (newpos < 0 && !PyErr_Occurred()) + newpos += (Py_ssize_t)(buf->inbuf_end - buf->inbuf_top); + if (newpos < 0 || buf->inbuf_top + newpos > buf->inbuf_end) { + PyErr_Clear(); + PyErr_Format(PyExc_IndexError, + "position %zd from error handler out of bounds", + newpos); + goto errorexit; + } + buf->inbuf = buf->inbuf_top + newpos; + Py_DECREF(retobj); + return 0; errorexit: - Py_XDECREF(retobj); - return -1; + Py_XDECREF(retobj); + return -1; } static PyObject * multibytecodec_encode(MultibyteCodec *codec, - MultibyteCodec_State *state, - const Py_UNICODE **data, Py_ssize_t datalen, - PyObject *errors, int flags) -{ - MultibyteEncodeBuffer buf; - Py_ssize_t finalsize, r = 0; - - if (datalen == 0) - return PyBytes_FromStringAndSize(NULL, 0); - - buf.excobj = NULL; - buf.inbuf = buf.inbuf_top = *data; - buf.inbuf_end = buf.inbuf_top + datalen; - - if (datalen > (PY_SSIZE_T_MAX - 16) / 2) { - PyErr_NoMemory(); - goto errorexit; - } - - buf.outobj = PyBytes_FromStringAndSize(NULL, datalen * 2 + 16); - if (buf.outobj == NULL) - goto errorexit; - buf.outbuf = (unsigned char *)PyBytes_AS_STRING(buf.outobj); - buf.outbuf_end = buf.outbuf + PyBytes_GET_SIZE(buf.outobj); - - while (buf.inbuf < buf.inbuf_end) { - Py_ssize_t inleft, outleft; - - /* we don't reuse inleft and outleft here. - * error callbacks can relocate the cursor anywhere on buffer*/ - inleft = (Py_ssize_t)(buf.inbuf_end - buf.inbuf); - outleft = (Py_ssize_t)(buf.outbuf_end - buf.outbuf); - r = codec->encode(state, codec->config, &buf.inbuf, inleft, - &buf.outbuf, outleft, flags); - if ((r == 0) || (r == MBERR_TOOFEW && !(flags & MBENC_FLUSH))) - break; - else if (multibytecodec_encerror(codec, state, &buf, errors,r)) - goto errorexit; - else if (r == MBERR_TOOFEW) - break; - } - - if (codec->encreset != NULL) - for (;;) { - Py_ssize_t outleft; - - outleft = (Py_ssize_t)(buf.outbuf_end - buf.outbuf); - r = codec->encreset(state, codec->config, &buf.outbuf, - outleft); - if (r == 0) - break; - else if (multibytecodec_encerror(codec, state, - &buf, errors, r)) - goto errorexit; - } - - finalsize = (Py_ssize_t)((char *)buf.outbuf - - PyBytes_AS_STRING(buf.outobj)); - - if (finalsize != PyBytes_GET_SIZE(buf.outobj)) - if (_PyBytes_Resize(&buf.outobj, finalsize) == -1) - goto errorexit; - - *data = buf.inbuf; - Py_XDECREF(buf.excobj); - return buf.outobj; + MultibyteCodec_State *state, + const Py_UNICODE **data, Py_ssize_t datalen, + PyObject *errors, int flags) +{ + MultibyteEncodeBuffer buf; + Py_ssize_t finalsize, r = 0; + + if (datalen == 0) + return PyBytes_FromStringAndSize(NULL, 0); + + buf.excobj = NULL; + buf.inbuf = buf.inbuf_top = *data; + buf.inbuf_end = buf.inbuf_top + datalen; + + if (datalen > (PY_SSIZE_T_MAX - 16) / 2) { + PyErr_NoMemory(); + goto errorexit; + } + + buf.outobj = PyBytes_FromStringAndSize(NULL, datalen * 2 + 16); + if (buf.outobj == NULL) + goto errorexit; + buf.outbuf = (unsigned char *)PyBytes_AS_STRING(buf.outobj); + buf.outbuf_end = buf.outbuf + PyBytes_GET_SIZE(buf.outobj); + + while (buf.inbuf < buf.inbuf_end) { + Py_ssize_t inleft, outleft; + + /* we don't reuse inleft and outleft here. + * error callbacks can relocate the cursor anywhere on buffer*/ + inleft = (Py_ssize_t)(buf.inbuf_end - buf.inbuf); + outleft = (Py_ssize_t)(buf.outbuf_end - buf.outbuf); + r = codec->encode(state, codec->config, &buf.inbuf, inleft, + &buf.outbuf, outleft, flags); + if ((r == 0) || (r == MBERR_TOOFEW && !(flags & MBENC_FLUSH))) + break; + else if (multibytecodec_encerror(codec, state, &buf, errors,r)) + goto errorexit; + else if (r == MBERR_TOOFEW) + break; + } + + if (codec->encreset != NULL) + for (;;) { + Py_ssize_t outleft; + + outleft = (Py_ssize_t)(buf.outbuf_end - buf.outbuf); + r = codec->encreset(state, codec->config, &buf.outbuf, + outleft); + if (r == 0) + break; + else if (multibytecodec_encerror(codec, state, + &buf, errors, r)) + goto errorexit; + } + + finalsize = (Py_ssize_t)((char *)buf.outbuf - + PyBytes_AS_STRING(buf.outobj)); + + if (finalsize != PyBytes_GET_SIZE(buf.outobj)) + if (_PyBytes_Resize(&buf.outobj, finalsize) == -1) + goto errorexit; + + *data = buf.inbuf; + Py_XDECREF(buf.excobj); + return buf.outobj; errorexit: - Py_XDECREF(buf.excobj); - Py_XDECREF(buf.outobj); - return NULL; + Py_XDECREF(buf.excobj); + Py_XDECREF(buf.outobj); + return NULL; } static PyObject * MultibyteCodec_Encode(MultibyteCodecObject *self, - PyObject *args, PyObject *kwargs) + PyObject *args, PyObject *kwargs) { - MultibyteCodec_State state; - Py_UNICODE *data; - PyObject *errorcb, *r, *arg, *ucvt; - const char *errors = NULL; - Py_ssize_t datalen; - - if (!PyArg_ParseTupleAndKeywords(args, kwargs, "O|z:encode", - codeckwarglist, &arg, &errors)) - return NULL; - - if (PyUnicode_Check(arg)) - ucvt = NULL; - else { - arg = ucvt = PyObject_Str(arg); - if (arg == NULL) - return NULL; - else if (!PyUnicode_Check(arg)) { - PyErr_SetString(PyExc_TypeError, - "couldn't convert the object to unicode."); - Py_DECREF(ucvt); - return NULL; - } - } - - data = PyUnicode_AS_UNICODE(arg); - datalen = PyUnicode_GET_SIZE(arg); - - errorcb = internal_error_callback(errors); - if (errorcb == NULL) { - Py_XDECREF(ucvt); - return NULL; - } - - if (self->codec->encinit != NULL && - self->codec->encinit(&state, self->codec->config) != 0) - goto errorexit; - r = multibytecodec_encode(self->codec, &state, - (const Py_UNICODE **)&data, datalen, errorcb, - MBENC_FLUSH | MBENC_RESET); - if (r == NULL) - goto errorexit; - - ERROR_DECREF(errorcb); - Py_XDECREF(ucvt); - return make_tuple(r, datalen); + MultibyteCodec_State state; + Py_UNICODE *data; + PyObject *errorcb, *r, *arg, *ucvt; + const char *errors = NULL; + Py_ssize_t datalen; + + if (!PyArg_ParseTupleAndKeywords(args, kwargs, "O|z:encode", + codeckwarglist, &arg, &errors)) + return NULL; + + if (PyUnicode_Check(arg)) + ucvt = NULL; + else { + arg = ucvt = PyObject_Str(arg); + if (arg == NULL) + return NULL; + else if (!PyUnicode_Check(arg)) { + PyErr_SetString(PyExc_TypeError, + "couldn't convert the object to unicode."); + Py_DECREF(ucvt); + return NULL; + } + } + + data = PyUnicode_AS_UNICODE(arg); + datalen = PyUnicode_GET_SIZE(arg); + + errorcb = internal_error_callback(errors); + if (errorcb == NULL) { + Py_XDECREF(ucvt); + return NULL; + } + + if (self->codec->encinit != NULL && + self->codec->encinit(&state, self->codec->config) != 0) + goto errorexit; + r = multibytecodec_encode(self->codec, &state, + (const Py_UNICODE **)&data, datalen, errorcb, + MBENC_FLUSH | MBENC_RESET); + if (r == NULL) + goto errorexit; + + ERROR_DECREF(errorcb); + Py_XDECREF(ucvt); + return make_tuple(r, datalen); errorexit: - ERROR_DECREF(errorcb); - Py_XDECREF(ucvt); - return NULL; + ERROR_DECREF(errorcb); + Py_XDECREF(ucvt); + return NULL; } static PyObject * MultibyteCodec_Decode(MultibyteCodecObject *self, - PyObject *args, PyObject *kwargs) + PyObject *args, PyObject *kwargs) { - MultibyteCodec_State state; - MultibyteDecodeBuffer buf; - PyObject *errorcb; - Py_buffer pdata; - const char *data, *errors = NULL; - Py_ssize_t datalen, finalsize; - - if (!PyArg_ParseTupleAndKeywords(args, kwargs, "y*|z:decode", - codeckwarglist, &pdata, &errors)) - return NULL; - data = pdata.buf; - datalen = pdata.len; - - errorcb = internal_error_callback(errors); - if (errorcb == NULL) { - PyBuffer_Release(&pdata); - return NULL; - } - - if (datalen == 0) { - PyBuffer_Release(&pdata); - ERROR_DECREF(errorcb); - return make_tuple(PyUnicode_FromUnicode(NULL, 0), 0); - } - - buf.excobj = NULL; - buf.inbuf = buf.inbuf_top = (unsigned char *)data; - buf.inbuf_end = buf.inbuf_top + datalen; - buf.outobj = PyUnicode_FromUnicode(NULL, datalen); - if (buf.outobj == NULL) - goto errorexit; - buf.outbuf = PyUnicode_AS_UNICODE(buf.outobj); - buf.outbuf_end = buf.outbuf + PyUnicode_GET_SIZE(buf.outobj); - - if (self->codec->decinit != NULL && - self->codec->decinit(&state, self->codec->config) != 0) - goto errorexit; - - while (buf.inbuf < buf.inbuf_end) { - Py_ssize_t inleft, outleft, r; - - inleft = (Py_ssize_t)(buf.inbuf_end - buf.inbuf); - outleft = (Py_ssize_t)(buf.outbuf_end - buf.outbuf); - - r = self->codec->decode(&state, self->codec->config, - &buf.inbuf, inleft, &buf.outbuf, outleft); - if (r == 0) - break; - else if (multibytecodec_decerror(self->codec, &state, - &buf, errorcb, r)) - goto errorexit; - } - - finalsize = (Py_ssize_t)(buf.outbuf - - PyUnicode_AS_UNICODE(buf.outobj)); - - if (finalsize != PyUnicode_GET_SIZE(buf.outobj)) - if (PyUnicode_Resize(&buf.outobj, finalsize) == -1) - goto errorexit; - - PyBuffer_Release(&pdata); - Py_XDECREF(buf.excobj); - ERROR_DECREF(errorcb); - return make_tuple(buf.outobj, datalen); + MultibyteCodec_State state; + MultibyteDecodeBuffer buf; + PyObject *errorcb; + Py_buffer pdata; + const char *data, *errors = NULL; + Py_ssize_t datalen, finalsize; + + if (!PyArg_ParseTupleAndKeywords(args, kwargs, "y*|z:decode", + codeckwarglist, &pdata, &errors)) + return NULL; + data = pdata.buf; + datalen = pdata.len; + + errorcb = internal_error_callback(errors); + if (errorcb == NULL) { + PyBuffer_Release(&pdata); + return NULL; + } + + if (datalen == 0) { + PyBuffer_Release(&pdata); + ERROR_DECREF(errorcb); + return make_tuple(PyUnicode_FromUnicode(NULL, 0), 0); + } + + buf.excobj = NULL; + buf.inbuf = buf.inbuf_top = (unsigned char *)data; + buf.inbuf_end = buf.inbuf_top + datalen; + buf.outobj = PyUnicode_FromUnicode(NULL, datalen); + if (buf.outobj == NULL) + goto errorexit; + buf.outbuf = PyUnicode_AS_UNICODE(buf.outobj); + buf.outbuf_end = buf.outbuf + PyUnicode_GET_SIZE(buf.outobj); + + if (self->codec->decinit != NULL && + self->codec->decinit(&state, self->codec->config) != 0) + goto errorexit; + + while (buf.inbuf < buf.inbuf_end) { + Py_ssize_t inleft, outleft, r; + + inleft = (Py_ssize_t)(buf.inbuf_end - buf.inbuf); + outleft = (Py_ssize_t)(buf.outbuf_end - buf.outbuf); + + r = self->codec->decode(&state, self->codec->config, + &buf.inbuf, inleft, &buf.outbuf, outleft); + if (r == 0) + break; + else if (multibytecodec_decerror(self->codec, &state, + &buf, errorcb, r)) + goto errorexit; + } + + finalsize = (Py_ssize_t)(buf.outbuf - + PyUnicode_AS_UNICODE(buf.outobj)); + + if (finalsize != PyUnicode_GET_SIZE(buf.outobj)) + if (PyUnicode_Resize(&buf.outobj, finalsize) == -1) + goto errorexit; + + PyBuffer_Release(&pdata); + Py_XDECREF(buf.excobj); + ERROR_DECREF(errorcb); + return make_tuple(buf.outobj, datalen); errorexit: - PyBuffer_Release(&pdata); - ERROR_DECREF(errorcb); - Py_XDECREF(buf.excobj); - Py_XDECREF(buf.outobj); + PyBuffer_Release(&pdata); + ERROR_DECREF(errorcb); + Py_XDECREF(buf.excobj); + Py_XDECREF(buf.outobj); - return NULL; + return NULL; } static struct PyMethodDef multibytecodec_methods[] = { - {"encode", (PyCFunction)MultibyteCodec_Encode, - METH_VARARGS | METH_KEYWORDS, - MultibyteCodec_Encode__doc__}, - {"decode", (PyCFunction)MultibyteCodec_Decode, - METH_VARARGS | METH_KEYWORDS, - MultibyteCodec_Decode__doc__}, - {NULL, NULL}, + {"encode", (PyCFunction)MultibyteCodec_Encode, + METH_VARARGS | METH_KEYWORDS, + MultibyteCodec_Encode__doc__}, + {"decode", (PyCFunction)MultibyteCodec_Decode, + METH_VARARGS | METH_KEYWORDS, + MultibyteCodec_Decode__doc__}, + {NULL, NULL}, }; static void multibytecodec_dealloc(MultibyteCodecObject *self) { - PyObject_Del(self); + PyObject_Del(self); } static PyTypeObject MultibyteCodec_Type = { - PyVarObject_HEAD_INIT(NULL, 0) - "MultibyteCodec", /* tp_name */ - sizeof(MultibyteCodecObject), /* tp_basicsize */ - 0, /* tp_itemsize */ - /* methods */ - (destructor)multibytecodec_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, /* tp_flags */ - 0, /* tp_doc */ - 0, /* tp_traverse */ - 0, /* tp_clear */ - 0, /* tp_richcompare */ - 0, /* tp_weaklistoffset */ - 0, /* tp_iter */ - 0, /* tp_iterext */ - multibytecodec_methods, /* tp_methods */ + PyVarObject_HEAD_INIT(NULL, 0) + "MultibyteCodec", /* tp_name */ + sizeof(MultibyteCodecObject), /* tp_basicsize */ + 0, /* tp_itemsize */ + /* methods */ + (destructor)multibytecodec_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, /* tp_flags */ + 0, /* tp_doc */ + 0, /* tp_traverse */ + 0, /* tp_clear */ + 0, /* tp_richcompare */ + 0, /* tp_weaklistoffset */ + 0, /* tp_iter */ + 0, /* tp_iterext */ + multibytecodec_methods, /* tp_methods */ }; @@ -732,150 +732,150 @@ * Utility functions for stateful codec mechanism */ -#define STATEFUL_DCTX(o) ((MultibyteStatefulDecoderContext *)(o)) -#define STATEFUL_ECTX(o) ((MultibyteStatefulEncoderContext *)(o)) +#define STATEFUL_DCTX(o) ((MultibyteStatefulDecoderContext *)(o)) +#define STATEFUL_ECTX(o) ((MultibyteStatefulEncoderContext *)(o)) static PyObject * encoder_encode_stateful(MultibyteStatefulEncoderContext *ctx, - PyObject *unistr, int final) + PyObject *unistr, int final) { - PyObject *ucvt, *r = NULL; - Py_UNICODE *inbuf, *inbuf_end, *inbuf_tmp = NULL; - Py_ssize_t datalen, origpending; - - if (PyUnicode_Check(unistr)) - ucvt = NULL; - else { - unistr = ucvt = PyObject_Str(unistr); - if (unistr == NULL) - return NULL; - else if (!PyUnicode_Check(unistr)) { - PyErr_SetString(PyExc_TypeError, - "couldn't convert the object to unicode."); - Py_DECREF(ucvt); - return NULL; - } - } - - datalen = PyUnicode_GET_SIZE(unistr); - origpending = ctx->pendingsize; - - if (origpending > 0) { - if (datalen > PY_SSIZE_T_MAX - ctx->pendingsize) { - PyErr_NoMemory(); - /* inbuf_tmp == NULL */ - goto errorexit; - } - inbuf_tmp = PyMem_New(Py_UNICODE, datalen + ctx->pendingsize); - if (inbuf_tmp == NULL) - goto errorexit; - memcpy(inbuf_tmp, ctx->pending, - Py_UNICODE_SIZE * ctx->pendingsize); - memcpy(inbuf_tmp + ctx->pendingsize, - PyUnicode_AS_UNICODE(unistr), - Py_UNICODE_SIZE * datalen); - datalen += ctx->pendingsize; - ctx->pendingsize = 0; - inbuf = inbuf_tmp; - } - else - inbuf = (Py_UNICODE *)PyUnicode_AS_UNICODE(unistr); - - inbuf_end = inbuf + datalen; - - r = multibytecodec_encode(ctx->codec, &ctx->state, - (const Py_UNICODE **)&inbuf, - datalen, ctx->errors, final ? MBENC_FLUSH : 0); - if (r == NULL) { - /* recover the original pending buffer */ - if (origpending > 0) - memcpy(ctx->pending, inbuf_tmp, - Py_UNICODE_SIZE * origpending); - ctx->pendingsize = origpending; - goto errorexit; - } - - if (inbuf < inbuf_end) { - ctx->pendingsize = (Py_ssize_t)(inbuf_end - inbuf); - if (ctx->pendingsize > MAXENCPENDING) { - /* normal codecs can't reach here */ - ctx->pendingsize = 0; - PyErr_SetString(PyExc_UnicodeError, - "pending buffer overflow"); - goto errorexit; - } - memcpy(ctx->pending, inbuf, - ctx->pendingsize * Py_UNICODE_SIZE); - } - - if (inbuf_tmp != NULL) - PyMem_Del(inbuf_tmp); - Py_XDECREF(ucvt); - return r; + PyObject *ucvt, *r = NULL; + Py_UNICODE *inbuf, *inbuf_end, *inbuf_tmp = NULL; + Py_ssize_t datalen, origpending; + + if (PyUnicode_Check(unistr)) + ucvt = NULL; + else { + unistr = ucvt = PyObject_Str(unistr); + if (unistr == NULL) + return NULL; + else if (!PyUnicode_Check(unistr)) { + PyErr_SetString(PyExc_TypeError, + "couldn't convert the object to unicode."); + Py_DECREF(ucvt); + return NULL; + } + } + + datalen = PyUnicode_GET_SIZE(unistr); + origpending = ctx->pendingsize; + + if (origpending > 0) { + if (datalen > PY_SSIZE_T_MAX - ctx->pendingsize) { + PyErr_NoMemory(); + /* inbuf_tmp == NULL */ + goto errorexit; + } + inbuf_tmp = PyMem_New(Py_UNICODE, datalen + ctx->pendingsize); + if (inbuf_tmp == NULL) + goto errorexit; + memcpy(inbuf_tmp, ctx->pending, + Py_UNICODE_SIZE * ctx->pendingsize); + memcpy(inbuf_tmp + ctx->pendingsize, + PyUnicode_AS_UNICODE(unistr), + Py_UNICODE_SIZE * datalen); + datalen += ctx->pendingsize; + ctx->pendingsize = 0; + inbuf = inbuf_tmp; + } + else + inbuf = (Py_UNICODE *)PyUnicode_AS_UNICODE(unistr); + + inbuf_end = inbuf + datalen; + + r = multibytecodec_encode(ctx->codec, &ctx->state, + (const Py_UNICODE **)&inbuf, + datalen, ctx->errors, final ? MBENC_FLUSH : 0); + if (r == NULL) { + /* recover the original pending buffer */ + if (origpending > 0) + memcpy(ctx->pending, inbuf_tmp, + Py_UNICODE_SIZE * origpending); + ctx->pendingsize = origpending; + goto errorexit; + } + + if (inbuf < inbuf_end) { + ctx->pendingsize = (Py_ssize_t)(inbuf_end - inbuf); + if (ctx->pendingsize > MAXENCPENDING) { + /* normal codecs can't reach here */ + ctx->pendingsize = 0; + PyErr_SetString(PyExc_UnicodeError, + "pending buffer overflow"); + goto errorexit; + } + memcpy(ctx->pending, inbuf, + ctx->pendingsize * Py_UNICODE_SIZE); + } + + if (inbuf_tmp != NULL) + PyMem_Del(inbuf_tmp); + Py_XDECREF(ucvt); + return r; errorexit: - if (inbuf_tmp != NULL) - PyMem_Del(inbuf_tmp); - Py_XDECREF(r); - Py_XDECREF(ucvt); - return NULL; + if (inbuf_tmp != NULL) + PyMem_Del(inbuf_tmp); + Py_XDECREF(r); + Py_XDECREF(ucvt); + return NULL; } static int decoder_append_pending(MultibyteStatefulDecoderContext *ctx, - MultibyteDecodeBuffer *buf) + MultibyteDecodeBuffer *buf) { - Py_ssize_t npendings; + Py_ssize_t npendings; - npendings = (Py_ssize_t)(buf->inbuf_end - buf->inbuf); - if (npendings + ctx->pendingsize > MAXDECPENDING || - npendings > PY_SSIZE_T_MAX - ctx->pendingsize) { - PyErr_SetString(PyExc_UnicodeError, "pending buffer overflow"); - return -1; - } - memcpy(ctx->pending + ctx->pendingsize, buf->inbuf, npendings); - ctx->pendingsize += npendings; - return 0; + npendings = (Py_ssize_t)(buf->inbuf_end - buf->inbuf); + if (npendings + ctx->pendingsize > MAXDECPENDING || + npendings > PY_SSIZE_T_MAX - ctx->pendingsize) { + PyErr_SetString(PyExc_UnicodeError, "pending buffer overflow"); + return -1; + } + memcpy(ctx->pending + ctx->pendingsize, buf->inbuf, npendings); + ctx->pendingsize += npendings; + return 0; } static int decoder_prepare_buffer(MultibyteDecodeBuffer *buf, const char *data, - Py_ssize_t size) + Py_ssize_t size) { - buf->inbuf = buf->inbuf_top = (const unsigned char *)data; - buf->inbuf_end = buf->inbuf_top + size; - if (buf->outobj == NULL) { /* only if outobj is not allocated yet */ - buf->outobj = PyUnicode_FromUnicode(NULL, size); - if (buf->outobj == NULL) - return -1; - buf->outbuf = PyUnicode_AS_UNICODE(buf->outobj); - buf->outbuf_end = buf->outbuf + - PyUnicode_GET_SIZE(buf->outobj); - } + buf->inbuf = buf->inbuf_top = (const unsigned char *)data; + buf->inbuf_end = buf->inbuf_top + size; + if (buf->outobj == NULL) { /* only if outobj is not allocated yet */ + buf->outobj = PyUnicode_FromUnicode(NULL, size); + if (buf->outobj == NULL) + return -1; + buf->outbuf = PyUnicode_AS_UNICODE(buf->outobj); + buf->outbuf_end = buf->outbuf + + PyUnicode_GET_SIZE(buf->outobj); + } - return 0; + return 0; } static int decoder_feed_buffer(MultibyteStatefulDecoderContext *ctx, - MultibyteDecodeBuffer *buf) + MultibyteDecodeBuffer *buf) { - while (buf->inbuf < buf->inbuf_end) { - Py_ssize_t inleft, outleft; - Py_ssize_t r; - - inleft = (Py_ssize_t)(buf->inbuf_end - buf->inbuf); - outleft = (Py_ssize_t)(buf->outbuf_end - buf->outbuf); - - r = ctx->codec->decode(&ctx->state, ctx->codec->config, - &buf->inbuf, inleft, &buf->outbuf, outleft); - if (r == 0 || r == MBERR_TOOFEW) - break; - else if (multibytecodec_decerror(ctx->codec, &ctx->state, - buf, ctx->errors, r)) - return -1; - } - return 0; + while (buf->inbuf < buf->inbuf_end) { + Py_ssize_t inleft, outleft; + Py_ssize_t r; + + inleft = (Py_ssize_t)(buf->inbuf_end - buf->inbuf); + outleft = (Py_ssize_t)(buf->outbuf_end - buf->outbuf); + + r = ctx->codec->decode(&ctx->state, ctx->codec->config, + &buf->inbuf, inleft, &buf->outbuf, outleft); + if (r == 0 || r == MBERR_TOOFEW) + break; + else if (multibytecodec_decerror(ctx->codec, &ctx->state, + buf, ctx->errors, r)) + return -1; + } + return 0; } @@ -885,142 +885,142 @@ static PyObject * mbiencoder_encode(MultibyteIncrementalEncoderObject *self, - PyObject *args, PyObject *kwargs) + PyObject *args, PyObject *kwargs) { - PyObject *data; - int final = 0; + PyObject *data; + int final = 0; - if (!PyArg_ParseTupleAndKeywords(args, kwargs, "O|i:encode", - incrementalkwarglist, &data, &final)) - return NULL; + if (!PyArg_ParseTupleAndKeywords(args, kwargs, "O|i:encode", + incrementalkwarglist, &data, &final)) + return NULL; - return encoder_encode_stateful(STATEFUL_ECTX(self), data, final); + return encoder_encode_stateful(STATEFUL_ECTX(self), data, final); } static PyObject * mbiencoder_reset(MultibyteIncrementalEncoderObject *self) { - if (self->codec->decreset != NULL && - self->codec->decreset(&self->state, self->codec->config) != 0) - return NULL; - self->pendingsize = 0; + if (self->codec->decreset != NULL && + self->codec->decreset(&self->state, self->codec->config) != 0) + return NULL; + self->pendingsize = 0; - Py_RETURN_NONE; + Py_RETURN_NONE; } static struct PyMethodDef mbiencoder_methods[] = { - {"encode", (PyCFunction)mbiencoder_encode, - METH_VARARGS | METH_KEYWORDS, NULL}, - {"reset", (PyCFunction)mbiencoder_reset, - METH_NOARGS, NULL}, - {NULL, NULL}, + {"encode", (PyCFunction)mbiencoder_encode, + METH_VARARGS | METH_KEYWORDS, NULL}, + {"reset", (PyCFunction)mbiencoder_reset, + METH_NOARGS, NULL}, + {NULL, NULL}, }; static PyObject * mbiencoder_new(PyTypeObject *type, PyObject *args, PyObject *kwds) { - MultibyteIncrementalEncoderObject *self; - PyObject *codec = NULL; - char *errors = NULL; - - if (!PyArg_ParseTupleAndKeywords(args, kwds, "|s:IncrementalEncoder", - incnewkwarglist, &errors)) - return NULL; - - self = (MultibyteIncrementalEncoderObject *)type->tp_alloc(type, 0); - if (self == NULL) - return NULL; - - codec = PyObject_GetAttrString((PyObject *)type, "codec"); - if (codec == NULL) - goto errorexit; - if (!MultibyteCodec_Check(codec)) { - PyErr_SetString(PyExc_TypeError, "codec is unexpected type"); - goto errorexit; - } - - self->codec = ((MultibyteCodecObject *)codec)->codec; - self->pendingsize = 0; - self->errors = internal_error_callback(errors); - if (self->errors == NULL) - goto errorexit; - if (self->codec->encinit != NULL && - self->codec->encinit(&self->state, self->codec->config) != 0) - goto errorexit; + MultibyteIncrementalEncoderObject *self; + PyObject *codec = NULL; + char *errors = NULL; + + if (!PyArg_ParseTupleAndKeywords(args, kwds, "|s:IncrementalEncoder", + incnewkwarglist, &errors)) + return NULL; + + self = (MultibyteIncrementalEncoderObject *)type->tp_alloc(type, 0); + if (self == NULL) + return NULL; + + codec = PyObject_GetAttrString((PyObject *)type, "codec"); + if (codec == NULL) + goto errorexit; + if (!MultibyteCodec_Check(codec)) { + PyErr_SetString(PyExc_TypeError, "codec is unexpected type"); + goto errorexit; + } + + self->codec = ((MultibyteCodecObject *)codec)->codec; + self->pendingsize = 0; + self->errors = internal_error_callback(errors); + if (self->errors == NULL) + goto errorexit; + if (self->codec->encinit != NULL && + self->codec->encinit(&self->state, self->codec->config) != 0) + goto errorexit; - Py_DECREF(codec); - return (PyObject *)self; + Py_DECREF(codec); + return (PyObject *)self; errorexit: - Py_XDECREF(self); - Py_XDECREF(codec); - return NULL; + Py_XDECREF(self); + Py_XDECREF(codec); + return NULL; } static int mbiencoder_init(PyObject *self, PyObject *args, PyObject *kwds) { - return 0; + return 0; } static int mbiencoder_traverse(MultibyteIncrementalEncoderObject *self, - visitproc visit, void *arg) + visitproc visit, void *arg) { - if (ERROR_ISCUSTOM(self->errors)) - Py_VISIT(self->errors); - return 0; + if (ERROR_ISCUSTOM(self->errors)) + Py_VISIT(self->errors); + return 0; } static void mbiencoder_dealloc(MultibyteIncrementalEncoderObject *self) { - PyObject_GC_UnTrack(self); - ERROR_DECREF(self->errors); - Py_TYPE(self)->tp_free(self); + PyObject_GC_UnTrack(self); + ERROR_DECREF(self->errors); + Py_TYPE(self)->tp_free(self); } static PyTypeObject MultibyteIncrementalEncoder_Type = { - PyVarObject_HEAD_INIT(NULL, 0) - "MultibyteIncrementalEncoder", /* tp_name */ - sizeof(MultibyteIncrementalEncoderObject), /* tp_basicsize */ - 0, /* tp_itemsize */ - /* methods */ - (destructor)mbiencoder_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 - | Py_TPFLAGS_BASETYPE, /* tp_flags */ - 0, /* tp_doc */ - (traverseproc)mbiencoder_traverse, /* tp_traverse */ - 0, /* tp_clear */ - 0, /* tp_richcompare */ - 0, /* tp_weaklistoffset */ - 0, /* tp_iter */ - 0, /* tp_iterext */ - mbiencoder_methods, /* tp_methods */ - 0, /* tp_members */ - codecctx_getsets, /* tp_getset */ - 0, /* tp_base */ - 0, /* tp_dict */ - 0, /* tp_descr_get */ - 0, /* tp_descr_set */ - 0, /* tp_dictoffset */ - mbiencoder_init, /* tp_init */ - 0, /* tp_alloc */ - mbiencoder_new, /* tp_new */ + PyVarObject_HEAD_INIT(NULL, 0) + "MultibyteIncrementalEncoder", /* tp_name */ + sizeof(MultibyteIncrementalEncoderObject), /* tp_basicsize */ + 0, /* tp_itemsize */ + /* methods */ + (destructor)mbiencoder_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 + | Py_TPFLAGS_BASETYPE, /* tp_flags */ + 0, /* tp_doc */ + (traverseproc)mbiencoder_traverse, /* tp_traverse */ + 0, /* tp_clear */ + 0, /* tp_richcompare */ + 0, /* tp_weaklistoffset */ + 0, /* tp_iter */ + 0, /* tp_iterext */ + mbiencoder_methods, /* tp_methods */ + 0, /* tp_members */ + codecctx_getsets, /* tp_getset */ + 0, /* tp_base */ + 0, /* tp_dict */ + 0, /* tp_descr_get */ + 0, /* tp_descr_set */ + 0, /* tp_dictoffset */ + mbiencoder_init, /* tp_init */ + 0, /* tp_alloc */ + mbiencoder_new, /* tp_new */ }; @@ -1030,206 +1030,206 @@ static PyObject * mbidecoder_decode(MultibyteIncrementalDecoderObject *self, - PyObject *args, PyObject *kwargs) + PyObject *args, PyObject *kwargs) { - MultibyteDecodeBuffer buf; - char *data, *wdata = NULL; - Py_buffer pdata; - Py_ssize_t wsize, finalsize = 0, size, origpending; - int final = 0; - - if (!PyArg_ParseTupleAndKeywords(args, kwargs, "y*|i:decode", - incrementalkwarglist, &pdata, &final)) - return NULL; - data = pdata.buf; - size = pdata.len; - - buf.outobj = buf.excobj = NULL; - origpending = self->pendingsize; - - if (self->pendingsize == 0) { - wsize = size; - wdata = data; - } - else { - if (size > PY_SSIZE_T_MAX - self->pendingsize) { - PyErr_NoMemory(); - goto errorexit; - } - wsize = size + self->pendingsize; - wdata = PyMem_Malloc(wsize); - if (wdata == NULL) - goto errorexit; - memcpy(wdata, self->pending, self->pendingsize); - memcpy(wdata + self->pendingsize, data, size); - self->pendingsize = 0; - } - - if (decoder_prepare_buffer(&buf, wdata, wsize) != 0) - goto errorexit; - - if (decoder_feed_buffer(STATEFUL_DCTX(self), &buf)) - goto errorexit; - - if (final && buf.inbuf < buf.inbuf_end) { - if (multibytecodec_decerror(self->codec, &self->state, - &buf, self->errors, MBERR_TOOFEW)) { - /* recover the original pending buffer */ - memcpy(self->pending, wdata, origpending); - self->pendingsize = origpending; - goto errorexit; - } - } - - if (buf.inbuf < buf.inbuf_end) { /* pending sequence still exists */ - if (decoder_append_pending(STATEFUL_DCTX(self), &buf) != 0) - goto errorexit; - } - - finalsize = (Py_ssize_t)(buf.outbuf - PyUnicode_AS_UNICODE(buf.outobj)); - if (finalsize != PyUnicode_GET_SIZE(buf.outobj)) - if (PyUnicode_Resize(&buf.outobj, finalsize) == -1) - goto errorexit; - - PyBuffer_Release(&pdata); - if (wdata != data) - PyMem_Del(wdata); - Py_XDECREF(buf.excobj); - return buf.outobj; + MultibyteDecodeBuffer buf; + char *data, *wdata = NULL; + Py_buffer pdata; + Py_ssize_t wsize, finalsize = 0, size, origpending; + int final = 0; + + if (!PyArg_ParseTupleAndKeywords(args, kwargs, "y*|i:decode", + incrementalkwarglist, &pdata, &final)) + return NULL; + data = pdata.buf; + size = pdata.len; + + buf.outobj = buf.excobj = NULL; + origpending = self->pendingsize; + + if (self->pendingsize == 0) { + wsize = size; + wdata = data; + } + else { + if (size > PY_SSIZE_T_MAX - self->pendingsize) { + PyErr_NoMemory(); + goto errorexit; + } + wsize = size + self->pendingsize; + wdata = PyMem_Malloc(wsize); + if (wdata == NULL) + goto errorexit; + memcpy(wdata, self->pending, self->pendingsize); + memcpy(wdata + self->pendingsize, data, size); + self->pendingsize = 0; + } + + if (decoder_prepare_buffer(&buf, wdata, wsize) != 0) + goto errorexit; + + if (decoder_feed_buffer(STATEFUL_DCTX(self), &buf)) + goto errorexit; + + if (final && buf.inbuf < buf.inbuf_end) { + if (multibytecodec_decerror(self->codec, &self->state, + &buf, self->errors, MBERR_TOOFEW)) { + /* recover the original pending buffer */ + memcpy(self->pending, wdata, origpending); + self->pendingsize = origpending; + goto errorexit; + } + } + + if (buf.inbuf < buf.inbuf_end) { /* pending sequence still exists */ + if (decoder_append_pending(STATEFUL_DCTX(self), &buf) != 0) + goto errorexit; + } + + finalsize = (Py_ssize_t)(buf.outbuf - PyUnicode_AS_UNICODE(buf.outobj)); + if (finalsize != PyUnicode_GET_SIZE(buf.outobj)) + if (PyUnicode_Resize(&buf.outobj, finalsize) == -1) + goto errorexit; + + PyBuffer_Release(&pdata); + if (wdata != data) + PyMem_Del(wdata); + Py_XDECREF(buf.excobj); + return buf.outobj; errorexit: - PyBuffer_Release(&pdata); - if (wdata != NULL && wdata != data) - PyMem_Del(wdata); - Py_XDECREF(buf.excobj); - Py_XDECREF(buf.outobj); - return NULL; + PyBuffer_Release(&pdata); + if (wdata != NULL && wdata != data) + PyMem_Del(wdata); + Py_XDECREF(buf.excobj); + Py_XDECREF(buf.outobj); + return NULL; } static PyObject * mbidecoder_reset(MultibyteIncrementalDecoderObject *self) { - if (self->codec->decreset != NULL && - self->codec->decreset(&self->state, self->codec->config) != 0) - return NULL; - self->pendingsize = 0; + if (self->codec->decreset != NULL && + self->codec->decreset(&self->state, self->codec->config) != 0) + return NULL; + self->pendingsize = 0; - Py_RETURN_NONE; + Py_RETURN_NONE; } static struct PyMethodDef mbidecoder_methods[] = { - {"decode", (PyCFunction)mbidecoder_decode, - METH_VARARGS | METH_KEYWORDS, NULL}, - {"reset", (PyCFunction)mbidecoder_reset, - METH_NOARGS, NULL}, - {NULL, NULL}, + {"decode", (PyCFunction)mbidecoder_decode, + METH_VARARGS | METH_KEYWORDS, NULL}, + {"reset", (PyCFunction)mbidecoder_reset, + METH_NOARGS, NULL}, + {NULL, NULL}, }; static PyObject * mbidecoder_new(PyTypeObject *type, PyObject *args, PyObject *kwds) { - MultibyteIncrementalDecoderObject *self; - PyObject *codec = NULL; - char *errors = NULL; - - if (!PyArg_ParseTupleAndKeywords(args, kwds, "|s:IncrementalDecoder", - incnewkwarglist, &errors)) - return NULL; - - self = (MultibyteIncrementalDecoderObject *)type->tp_alloc(type, 0); - if (self == NULL) - return NULL; - - codec = PyObject_GetAttrString((PyObject *)type, "codec"); - if (codec == NULL) - goto errorexit; - if (!MultibyteCodec_Check(codec)) { - PyErr_SetString(PyExc_TypeError, "codec is unexpected type"); - goto errorexit; - } - - self->codec = ((MultibyteCodecObject *)codec)->codec; - self->pendingsize = 0; - self->errors = internal_error_callback(errors); - if (self->errors == NULL) - goto errorexit; - if (self->codec->decinit != NULL && - self->codec->decinit(&self->state, self->codec->config) != 0) - goto errorexit; + MultibyteIncrementalDecoderObject *self; + PyObject *codec = NULL; + char *errors = NULL; + + if (!PyArg_ParseTupleAndKeywords(args, kwds, "|s:IncrementalDecoder", + incnewkwarglist, &errors)) + return NULL; + + self = (MultibyteIncrementalDecoderObject *)type->tp_alloc(type, 0); + if (self == NULL) + return NULL; + + codec = PyObject_GetAttrString((PyObject *)type, "codec"); + if (codec == NULL) + goto errorexit; + if (!MultibyteCodec_Check(codec)) { + PyErr_SetString(PyExc_TypeError, "codec is unexpected type"); + goto errorexit; + } + + self->codec = ((MultibyteCodecObject *)codec)->codec; + self->pendingsize = 0; + self->errors = internal_error_callback(errors); + if (self->errors == NULL) + goto errorexit; + if (self->codec->decinit != NULL && + self->codec->decinit(&self->state, self->codec->config) != 0) + goto errorexit; - Py_DECREF(codec); - return (PyObject *)self; + Py_DECREF(codec); + return (PyObject *)self; errorexit: - Py_XDECREF(self); - Py_XDECREF(codec); - return NULL; + Py_XDECREF(self); + Py_XDECREF(codec); + return NULL; } static int mbidecoder_init(PyObject *self, PyObject *args, PyObject *kwds) { - return 0; + return 0; } static int mbidecoder_traverse(MultibyteIncrementalDecoderObject *self, - visitproc visit, void *arg) + visitproc visit, void *arg) { - if (ERROR_ISCUSTOM(self->errors)) - Py_VISIT(self->errors); - return 0; + if (ERROR_ISCUSTOM(self->errors)) + Py_VISIT(self->errors); + return 0; } static void mbidecoder_dealloc(MultibyteIncrementalDecoderObject *self) { - PyObject_GC_UnTrack(self); - ERROR_DECREF(self->errors); - Py_TYPE(self)->tp_free(self); + PyObject_GC_UnTrack(self); + ERROR_DECREF(self->errors); + Py_TYPE(self)->tp_free(self); } static PyTypeObject MultibyteIncrementalDecoder_Type = { - PyVarObject_HEAD_INIT(NULL, 0) - "MultibyteIncrementalDecoder", /* tp_name */ - sizeof(MultibyteIncrementalDecoderObject), /* tp_basicsize */ - 0, /* tp_itemsize */ - /* methods */ - (destructor)mbidecoder_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 - | Py_TPFLAGS_BASETYPE, /* tp_flags */ - 0, /* tp_doc */ - (traverseproc)mbidecoder_traverse, /* tp_traverse */ - 0, /* tp_clear */ - 0, /* tp_richcompare */ - 0, /* tp_weaklistoffset */ - 0, /* tp_iter */ - 0, /* tp_iterext */ - mbidecoder_methods, /* tp_methods */ - 0, /* tp_members */ - codecctx_getsets, /* tp_getset */ - 0, /* tp_base */ - 0, /* tp_dict */ - 0, /* tp_descr_get */ - 0, /* tp_descr_set */ - 0, /* tp_dictoffset */ - mbidecoder_init, /* tp_init */ - 0, /* tp_alloc */ - mbidecoder_new, /* tp_new */ + PyVarObject_HEAD_INIT(NULL, 0) + "MultibyteIncrementalDecoder", /* tp_name */ + sizeof(MultibyteIncrementalDecoderObject), /* tp_basicsize */ + 0, /* tp_itemsize */ + /* methods */ + (destructor)mbidecoder_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 + | Py_TPFLAGS_BASETYPE, /* tp_flags */ + 0, /* tp_doc */ + (traverseproc)mbidecoder_traverse, /* tp_traverse */ + 0, /* tp_clear */ + 0, /* tp_richcompare */ + 0, /* tp_weaklistoffset */ + 0, /* tp_iter */ + 0, /* tp_iterext */ + mbidecoder_methods, /* tp_methods */ + 0, /* tp_members */ + codecctx_getsets, /* tp_getset */ + 0, /* tp_base */ + 0, /* tp_dict */ + 0, /* tp_descr_get */ + 0, /* tp_descr_set */ + 0, /* tp_dictoffset */ + mbidecoder_init, /* tp_init */ + 0, /* tp_alloc */ + mbidecoder_new, /* tp_new */ }; @@ -1239,327 +1239,327 @@ static PyObject * mbstreamreader_iread(MultibyteStreamReaderObject *self, - const char *method, Py_ssize_t sizehint) + const char *method, Py_ssize_t sizehint) { - MultibyteDecodeBuffer buf; - PyObject *cres; - Py_ssize_t rsize, finalsize = 0; - - if (sizehint == 0) - return PyUnicode_FromUnicode(NULL, 0); - - buf.outobj = buf.excobj = NULL; - cres = NULL; - - for (;;) { - int endoffile; - - if (sizehint < 0) - cres = PyObject_CallMethod(self->stream, - (char *)method, NULL); - else - cres = PyObject_CallMethod(self->stream, - (char *)method, "i", sizehint); - if (cres == NULL) - goto errorexit; - - if (!PyBytes_Check(cres)) { - PyErr_Format(PyExc_TypeError, - "stream function returned a " - "non-bytes object (%.100s)", - cres->ob_type->tp_name); - goto errorexit; - } - - endoffile = (PyBytes_GET_SIZE(cres) == 0); - - if (self->pendingsize > 0) { - PyObject *ctr; - char *ctrdata; - - if (PyBytes_GET_SIZE(cres) > PY_SSIZE_T_MAX - self->pendingsize) { - PyErr_NoMemory(); - goto errorexit; - } - rsize = PyBytes_GET_SIZE(cres) + self->pendingsize; - ctr = PyBytes_FromStringAndSize(NULL, rsize); - if (ctr == NULL) - goto errorexit; - ctrdata = PyBytes_AS_STRING(ctr); - memcpy(ctrdata, self->pending, self->pendingsize); - memcpy(ctrdata + self->pendingsize, - PyBytes_AS_STRING(cres), - PyBytes_GET_SIZE(cres)); - Py_DECREF(cres); - cres = ctr; - self->pendingsize = 0; - } - - rsize = PyBytes_GET_SIZE(cres); - if (decoder_prepare_buffer(&buf, PyBytes_AS_STRING(cres), - rsize) != 0) - goto errorexit; - - if (rsize > 0 && decoder_feed_buffer( - (MultibyteStatefulDecoderContext *)self, &buf)) - goto errorexit; - - if (endoffile || sizehint < 0) { - if (buf.inbuf < buf.inbuf_end && - multibytecodec_decerror(self->codec, &self->state, - &buf, self->errors, MBERR_TOOFEW)) - goto errorexit; - } - - if (buf.inbuf < buf.inbuf_end) { /* pending sequence exists */ - if (decoder_append_pending(STATEFUL_DCTX(self), - &buf) != 0) - goto errorexit; - } - - finalsize = (Py_ssize_t)(buf.outbuf - - PyUnicode_AS_UNICODE(buf.outobj)); - Py_DECREF(cres); - cres = NULL; - - if (sizehint < 0 || finalsize != 0 || rsize == 0) - break; - - sizehint = 1; /* read 1 more byte and retry */ - } - - if (finalsize != PyUnicode_GET_SIZE(buf.outobj)) - if (PyUnicode_Resize(&buf.outobj, finalsize) == -1) - goto errorexit; - - Py_XDECREF(cres); - Py_XDECREF(buf.excobj); - return buf.outobj; + MultibyteDecodeBuffer buf; + PyObject *cres; + Py_ssize_t rsize, finalsize = 0; + + if (sizehint == 0) + return PyUnicode_FromUnicode(NULL, 0); + + buf.outobj = buf.excobj = NULL; + cres = NULL; + + for (;;) { + int endoffile; + + if (sizehint < 0) + cres = PyObject_CallMethod(self->stream, + (char *)method, NULL); + else + cres = PyObject_CallMethod(self->stream, + (char *)method, "i", sizehint); + if (cres == NULL) + goto errorexit; + + if (!PyBytes_Check(cres)) { + PyErr_Format(PyExc_TypeError, + "stream function returned a " + "non-bytes object (%.100s)", + cres->ob_type->tp_name); + goto errorexit; + } + + endoffile = (PyBytes_GET_SIZE(cres) == 0); + + if (self->pendingsize > 0) { + PyObject *ctr; + char *ctrdata; + + if (PyBytes_GET_SIZE(cres) > PY_SSIZE_T_MAX - self->pendingsize) { + PyErr_NoMemory(); + goto errorexit; + } + rsize = PyBytes_GET_SIZE(cres) + self->pendingsize; + ctr = PyBytes_FromStringAndSize(NULL, rsize); + if (ctr == NULL) + goto errorexit; + ctrdata = PyBytes_AS_STRING(ctr); + memcpy(ctrdata, self->pending, self->pendingsize); + memcpy(ctrdata + self->pendingsize, + PyBytes_AS_STRING(cres), + PyBytes_GET_SIZE(cres)); + Py_DECREF(cres); + cres = ctr; + self->pendingsize = 0; + } + + rsize = PyBytes_GET_SIZE(cres); + if (decoder_prepare_buffer(&buf, PyBytes_AS_STRING(cres), + rsize) != 0) + goto errorexit; + + if (rsize > 0 && decoder_feed_buffer( + (MultibyteStatefulDecoderContext *)self, &buf)) + goto errorexit; + + if (endoffile || sizehint < 0) { + if (buf.inbuf < buf.inbuf_end && + multibytecodec_decerror(self->codec, &self->state, + &buf, self->errors, MBERR_TOOFEW)) + goto errorexit; + } + + if (buf.inbuf < buf.inbuf_end) { /* pending sequence exists */ + if (decoder_append_pending(STATEFUL_DCTX(self), + &buf) != 0) + goto errorexit; + } + + finalsize = (Py_ssize_t)(buf.outbuf - + PyUnicode_AS_UNICODE(buf.outobj)); + Py_DECREF(cres); + cres = NULL; + + if (sizehint < 0 || finalsize != 0 || rsize == 0) + break; + + sizehint = 1; /* read 1 more byte and retry */ + } + + if (finalsize != PyUnicode_GET_SIZE(buf.outobj)) + if (PyUnicode_Resize(&buf.outobj, finalsize) == -1) + goto errorexit; + + Py_XDECREF(cres); + Py_XDECREF(buf.excobj); + return buf.outobj; errorexit: - Py_XDECREF(cres); - Py_XDECREF(buf.excobj); - Py_XDECREF(buf.outobj); - return NULL; + Py_XDECREF(cres); + Py_XDECREF(buf.excobj); + Py_XDECREF(buf.outobj); + return NULL; } static PyObject * mbstreamreader_read(MultibyteStreamReaderObject *self, PyObject *args) { - PyObject *sizeobj = NULL; - Py_ssize_t size; + PyObject *sizeobj = NULL; + Py_ssize_t size; - if (!PyArg_UnpackTuple(args, "read", 0, 1, &sizeobj)) - return NULL; + if (!PyArg_UnpackTuple(args, "read", 0, 1, &sizeobj)) + return NULL; - if (sizeobj == Py_None || sizeobj == NULL) - size = -1; - else if (PyLong_Check(sizeobj)) - size = PyLong_AsSsize_t(sizeobj); - else { - PyErr_SetString(PyExc_TypeError, "arg 1 must be an integer"); - return NULL; - } + if (sizeobj == Py_None || sizeobj == NULL) + size = -1; + else if (PyLong_Check(sizeobj)) + size = PyLong_AsSsize_t(sizeobj); + else { + PyErr_SetString(PyExc_TypeError, "arg 1 must be an integer"); + return NULL; + } - if (size == -1 && PyErr_Occurred()) - return NULL; + if (size == -1 && PyErr_Occurred()) + return NULL; - return mbstreamreader_iread(self, "read", size); + return mbstreamreader_iread(self, "read", size); } static PyObject * mbstreamreader_readline(MultibyteStreamReaderObject *self, PyObject *args) { - PyObject *sizeobj = NULL; - Py_ssize_t size; + PyObject *sizeobj = NULL; + Py_ssize_t size; - if (!PyArg_UnpackTuple(args, "readline", 0, 1, &sizeobj)) - return NULL; + if (!PyArg_UnpackTuple(args, "readline", 0, 1, &sizeobj)) + return NULL; - if (sizeobj == Py_None || sizeobj == NULL) - size = -1; - else if (PyLong_Check(sizeobj)) - size = PyLong_AsSsize_t(sizeobj); - else { - PyErr_SetString(PyExc_TypeError, "arg 1 must be an integer"); - return NULL; - } + if (sizeobj == Py_None || sizeobj == NULL) + size = -1; + else if (PyLong_Check(sizeobj)) + size = PyLong_AsSsize_t(sizeobj); + else { + PyErr_SetString(PyExc_TypeError, "arg 1 must be an integer"); + return NULL; + } - if (size == -1 && PyErr_Occurred()) - return NULL; + if (size == -1 && PyErr_Occurred()) + return NULL; - return mbstreamreader_iread(self, "readline", size); + return mbstreamreader_iread(self, "readline", size); } static PyObject * mbstreamreader_readlines(MultibyteStreamReaderObject *self, PyObject *args) { - PyObject *sizehintobj = NULL, *r, *sr; - Py_ssize_t sizehint; + PyObject *sizehintobj = NULL, *r, *sr; + Py_ssize_t sizehint; - if (!PyArg_UnpackTuple(args, "readlines", 0, 1, &sizehintobj)) - return NULL; + if (!PyArg_UnpackTuple(args, "readlines", 0, 1, &sizehintobj)) + return NULL; - if (sizehintobj == Py_None || sizehintobj == NULL) - sizehint = -1; - else if (PyLong_Check(sizehintobj)) - sizehint = PyLong_AsSsize_t(sizehintobj); - else { - PyErr_SetString(PyExc_TypeError, "arg 1 must be an integer"); - return NULL; - } - - if (sizehint == -1 && PyErr_Occurred()) - return NULL; - - r = mbstreamreader_iread(self, "read", sizehint); - if (r == NULL) - return NULL; - - sr = PyUnicode_Splitlines(r, 1); - Py_DECREF(r); - return sr; + if (sizehintobj == Py_None || sizehintobj == NULL) + sizehint = -1; + else if (PyLong_Check(sizehintobj)) + sizehint = PyLong_AsSsize_t(sizehintobj); + else { + PyErr_SetString(PyExc_TypeError, "arg 1 must be an integer"); + return NULL; + } + + if (sizehint == -1 && PyErr_Occurred()) + return NULL; + + r = mbstreamreader_iread(self, "read", sizehint); + if (r == NULL) + return NULL; + + sr = PyUnicode_Splitlines(r, 1); + Py_DECREF(r); + return sr; } static PyObject * mbstreamreader_reset(MultibyteStreamReaderObject *self) { - if (self->codec->decreset != NULL && - self->codec->decreset(&self->state, self->codec->config) != 0) - return NULL; - self->pendingsize = 0; + if (self->codec->decreset != NULL && + self->codec->decreset(&self->state, self->codec->config) != 0) + return NULL; + self->pendingsize = 0; - Py_RETURN_NONE; + Py_RETURN_NONE; } static struct PyMethodDef mbstreamreader_methods[] = { - {"read", (PyCFunction)mbstreamreader_read, - METH_VARARGS, NULL}, - {"readline", (PyCFunction)mbstreamreader_readline, - METH_VARARGS, NULL}, - {"readlines", (PyCFunction)mbstreamreader_readlines, - METH_VARARGS, NULL}, - {"reset", (PyCFunction)mbstreamreader_reset, - METH_NOARGS, NULL}, - {NULL, NULL}, + {"read", (PyCFunction)mbstreamreader_read, + METH_VARARGS, NULL}, + {"readline", (PyCFunction)mbstreamreader_readline, + METH_VARARGS, NULL}, + {"readlines", (PyCFunction)mbstreamreader_readlines, + METH_VARARGS, NULL}, + {"reset", (PyCFunction)mbstreamreader_reset, + METH_NOARGS, NULL}, + {NULL, NULL}, }; static PyMemberDef mbstreamreader_members[] = { - {"stream", T_OBJECT, - offsetof(MultibyteStreamReaderObject, stream), - READONLY, NULL}, - {NULL,} + {"stream", T_OBJECT, + offsetof(MultibyteStreamReaderObject, stream), + READONLY, NULL}, + {NULL,} }; static PyObject * mbstreamreader_new(PyTypeObject *type, PyObject *args, PyObject *kwds) { - MultibyteStreamReaderObject *self; - PyObject *stream, *codec = NULL; - char *errors = NULL; - - if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|s:StreamReader", - streamkwarglist, &stream, &errors)) - return NULL; - - self = (MultibyteStreamReaderObject *)type->tp_alloc(type, 0); - if (self == NULL) - return NULL; - - codec = PyObject_GetAttrString((PyObject *)type, "codec"); - if (codec == NULL) - goto errorexit; - if (!MultibyteCodec_Check(codec)) { - PyErr_SetString(PyExc_TypeError, "codec is unexpected type"); - goto errorexit; - } - - self->codec = ((MultibyteCodecObject *)codec)->codec; - self->stream = stream; - Py_INCREF(stream); - self->pendingsize = 0; - self->errors = internal_error_callback(errors); - if (self->errors == NULL) - goto errorexit; - if (self->codec->decinit != NULL && - self->codec->decinit(&self->state, self->codec->config) != 0) - goto errorexit; + MultibyteStreamReaderObject *self; + PyObject *stream, *codec = NULL; + char *errors = NULL; + + if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|s:StreamReader", + streamkwarglist, &stream, &errors)) + return NULL; + + self = (MultibyteStreamReaderObject *)type->tp_alloc(type, 0); + if (self == NULL) + return NULL; + + codec = PyObject_GetAttrString((PyObject *)type, "codec"); + if (codec == NULL) + goto errorexit; + if (!MultibyteCodec_Check(codec)) { + PyErr_SetString(PyExc_TypeError, "codec is unexpected type"); + goto errorexit; + } + + self->codec = ((MultibyteCodecObject *)codec)->codec; + self->stream = stream; + Py_INCREF(stream); + self->pendingsize = 0; + self->errors = internal_error_callback(errors); + if (self->errors == NULL) + goto errorexit; + if (self->codec->decinit != NULL && + self->codec->decinit(&self->state, self->codec->config) != 0) + goto errorexit; - Py_DECREF(codec); - return (PyObject *)self; + Py_DECREF(codec); + return (PyObject *)self; errorexit: - Py_XDECREF(self); - Py_XDECREF(codec); - return NULL; + Py_XDECREF(self); + Py_XDECREF(codec); + return NULL; } static int mbstreamreader_init(PyObject *self, PyObject *args, PyObject *kwds) { - return 0; + return 0; } static int mbstreamreader_traverse(MultibyteStreamReaderObject *self, - visitproc visit, void *arg) + visitproc visit, void *arg) { - if (ERROR_ISCUSTOM(self->errors)) - Py_VISIT(self->errors); - Py_VISIT(self->stream); - return 0; + if (ERROR_ISCUSTOM(self->errors)) + Py_VISIT(self->errors); + Py_VISIT(self->stream); + return 0; } static void mbstreamreader_dealloc(MultibyteStreamReaderObject *self) { - PyObject_GC_UnTrack(self); - ERROR_DECREF(self->errors); - Py_XDECREF(self->stream); - Py_TYPE(self)->tp_free(self); + PyObject_GC_UnTrack(self); + ERROR_DECREF(self->errors); + Py_XDECREF(self->stream); + Py_TYPE(self)->tp_free(self); } static PyTypeObject MultibyteStreamReader_Type = { - PyVarObject_HEAD_INIT(NULL, 0) - "MultibyteStreamReader", /* tp_name */ - sizeof(MultibyteStreamReaderObject), /* tp_basicsize */ - 0, /* tp_itemsize */ - /* methods */ - (destructor)mbstreamreader_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 - | Py_TPFLAGS_BASETYPE, /* tp_flags */ - 0, /* tp_doc */ - (traverseproc)mbstreamreader_traverse, /* tp_traverse */ - 0, /* tp_clear */ - 0, /* tp_richcompare */ - 0, /* tp_weaklistoffset */ - 0, /* tp_iter */ - 0, /* tp_iterext */ - mbstreamreader_methods, /* tp_methods */ - mbstreamreader_members, /* tp_members */ - codecctx_getsets, /* tp_getset */ - 0, /* tp_base */ - 0, /* tp_dict */ - 0, /* tp_descr_get */ - 0, /* tp_descr_set */ - 0, /* tp_dictoffset */ - mbstreamreader_init, /* tp_init */ - 0, /* tp_alloc */ - mbstreamreader_new, /* tp_new */ + PyVarObject_HEAD_INIT(NULL, 0) + "MultibyteStreamReader", /* tp_name */ + sizeof(MultibyteStreamReaderObject), /* tp_basicsize */ + 0, /* tp_itemsize */ + /* methods */ + (destructor)mbstreamreader_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 + | Py_TPFLAGS_BASETYPE, /* tp_flags */ + 0, /* tp_doc */ + (traverseproc)mbstreamreader_traverse, /* tp_traverse */ + 0, /* tp_clear */ + 0, /* tp_richcompare */ + 0, /* tp_weaklistoffset */ + 0, /* tp_iter */ + 0, /* tp_iterext */ + mbstreamreader_methods, /* tp_methods */ + mbstreamreader_members, /* tp_members */ + codecctx_getsets, /* tp_getset */ + 0, /* tp_base */ + 0, /* tp_dict */ + 0, /* tp_descr_get */ + 0, /* tp_descr_set */ + 0, /* tp_dictoffset */ + mbstreamreader_init, /* tp_init */ + 0, /* tp_alloc */ + mbstreamreader_new, /* tp_new */ }; @@ -1569,217 +1569,217 @@ static int mbstreamwriter_iwrite(MultibyteStreamWriterObject *self, - PyObject *unistr) + PyObject *unistr) { - PyObject *str, *wr; + PyObject *str, *wr; - str = encoder_encode_stateful(STATEFUL_ECTX(self), unistr, 0); - if (str == NULL) - return -1; + str = encoder_encode_stateful(STATEFUL_ECTX(self), unistr, 0); + if (str == NULL) + return -1; - wr = PyObject_CallMethod(self->stream, "write", "O", str); - Py_DECREF(str); - if (wr == NULL) - return -1; + wr = PyObject_CallMethod(self->stream, "write", "O", str); + Py_DECREF(str); + if (wr == NULL) + return -1; - Py_DECREF(wr); - return 0; + Py_DECREF(wr); + return 0; } static PyObject * mbstreamwriter_write(MultibyteStreamWriterObject *self, PyObject *strobj) { - if (mbstreamwriter_iwrite(self, strobj)) - return NULL; - else - Py_RETURN_NONE; + if (mbstreamwriter_iwrite(self, strobj)) + return NULL; + else + Py_RETURN_NONE; } static PyObject * mbstreamwriter_writelines(MultibyteStreamWriterObject *self, PyObject *lines) { - PyObject *strobj; - int i, r; + PyObject *strobj; + int i, r; - if (!PySequence_Check(lines)) { - PyErr_SetString(PyExc_TypeError, - "arg must be a sequence object"); - return NULL; - } - - for (i = 0; i < PySequence_Length(lines); i++) { - /* length can be changed even within this loop */ - strobj = PySequence_GetItem(lines, i); - if (strobj == NULL) - return NULL; - - r = mbstreamwriter_iwrite(self, strobj); - Py_DECREF(strobj); - if (r == -1) - return NULL; - } + if (!PySequence_Check(lines)) { + PyErr_SetString(PyExc_TypeError, + "arg must be a sequence object"); + return NULL; + } + + for (i = 0; i < PySequence_Length(lines); i++) { + /* length can be changed even within this loop */ + strobj = PySequence_GetItem(lines, i); + if (strobj == NULL) + return NULL; + + r = mbstreamwriter_iwrite(self, strobj); + Py_DECREF(strobj); + if (r == -1) + return NULL; + } - Py_RETURN_NONE; + Py_RETURN_NONE; } static PyObject * mbstreamwriter_reset(MultibyteStreamWriterObject *self) { - const Py_UNICODE *pending; - PyObject *pwrt; + const Py_UNICODE *pending; + PyObject *pwrt; - pending = self->pending; - pwrt = multibytecodec_encode(self->codec, &self->state, - &pending, self->pendingsize, self->errors, - MBENC_FLUSH | MBENC_RESET); - /* some pending buffer can be truncated when UnicodeEncodeError is - * raised on 'strict' mode. but, 'reset' method is designed to - * reset the pending buffer or states so failed string sequence - * ought to be missed */ - self->pendingsize = 0; - if (pwrt == NULL) - return NULL; - - assert(PyBytes_Check(pwrt)); - if (PyBytes_Size(pwrt) > 0) { - PyObject *wr; - wr = PyObject_CallMethod(self->stream, "write", "O", pwrt); - if (wr == NULL) { - Py_DECREF(pwrt); - return NULL; - } - } - Py_DECREF(pwrt); + pending = self->pending; + pwrt = multibytecodec_encode(self->codec, &self->state, + &pending, self->pendingsize, self->errors, + MBENC_FLUSH | MBENC_RESET); + /* some pending buffer can be truncated when UnicodeEncodeError is + * raised on 'strict' mode. but, 'reset' method is designed to + * reset the pending buffer or states so failed string sequence + * ought to be missed */ + self->pendingsize = 0; + if (pwrt == NULL) + return NULL; + + assert(PyBytes_Check(pwrt)); + if (PyBytes_Size(pwrt) > 0) { + PyObject *wr; + wr = PyObject_CallMethod(self->stream, "write", "O", pwrt); + if (wr == NULL) { + Py_DECREF(pwrt); + return NULL; + } + } + Py_DECREF(pwrt); - Py_RETURN_NONE; + Py_RETURN_NONE; } static PyObject * mbstreamwriter_new(PyTypeObject *type, PyObject *args, PyObject *kwds) { - MultibyteStreamWriterObject *self; - PyObject *stream, *codec = NULL; - char *errors = NULL; - - if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|s:StreamWriter", - streamkwarglist, &stream, &errors)) - return NULL; - - self = (MultibyteStreamWriterObject *)type->tp_alloc(type, 0); - if (self == NULL) - return NULL; - - codec = PyObject_GetAttrString((PyObject *)type, "codec"); - if (codec == NULL) - goto errorexit; - if (!MultibyteCodec_Check(codec)) { - PyErr_SetString(PyExc_TypeError, "codec is unexpected type"); - goto errorexit; - } - - self->codec = ((MultibyteCodecObject *)codec)->codec; - self->stream = stream; - Py_INCREF(stream); - self->pendingsize = 0; - self->errors = internal_error_callback(errors); - if (self->errors == NULL) - goto errorexit; - if (self->codec->encinit != NULL && - self->codec->encinit(&self->state, self->codec->config) != 0) - goto errorexit; + MultibyteStreamWriterObject *self; + PyObject *stream, *codec = NULL; + char *errors = NULL; + + if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|s:StreamWriter", + streamkwarglist, &stream, &errors)) + return NULL; + + self = (MultibyteStreamWriterObject *)type->tp_alloc(type, 0); + if (self == NULL) + return NULL; + + codec = PyObject_GetAttrString((PyObject *)type, "codec"); + if (codec == NULL) + goto errorexit; + if (!MultibyteCodec_Check(codec)) { + PyErr_SetString(PyExc_TypeError, "codec is unexpected type"); + goto errorexit; + } + + self->codec = ((MultibyteCodecObject *)codec)->codec; + self->stream = stream; + Py_INCREF(stream); + self->pendingsize = 0; + self->errors = internal_error_callback(errors); + if (self->errors == NULL) + goto errorexit; + if (self->codec->encinit != NULL && + self->codec->encinit(&self->state, self->codec->config) != 0) + goto errorexit; - Py_DECREF(codec); - return (PyObject *)self; + Py_DECREF(codec); + return (PyObject *)self; errorexit: - Py_XDECREF(self); - Py_XDECREF(codec); - return NULL; + Py_XDECREF(self); + Py_XDECREF(codec); + return NULL; } static int mbstreamwriter_init(PyObject *self, PyObject *args, PyObject *kwds) { - return 0; + return 0; } static int mbstreamwriter_traverse(MultibyteStreamWriterObject *self, - visitproc visit, void *arg) + visitproc visit, void *arg) { - if (ERROR_ISCUSTOM(self->errors)) - Py_VISIT(self->errors); - Py_VISIT(self->stream); - return 0; + if (ERROR_ISCUSTOM(self->errors)) + Py_VISIT(self->errors); + Py_VISIT(self->stream); + return 0; } static void mbstreamwriter_dealloc(MultibyteStreamWriterObject *self) { - PyObject_GC_UnTrack(self); - ERROR_DECREF(self->errors); - Py_XDECREF(self->stream); - Py_TYPE(self)->tp_free(self); + PyObject_GC_UnTrack(self); + ERROR_DECREF(self->errors); + Py_XDECREF(self->stream); + Py_TYPE(self)->tp_free(self); } static struct PyMethodDef mbstreamwriter_methods[] = { - {"write", (PyCFunction)mbstreamwriter_write, - METH_O, NULL}, - {"writelines", (PyCFunction)mbstreamwriter_writelines, - METH_O, NULL}, - {"reset", (PyCFunction)mbstreamwriter_reset, - METH_NOARGS, NULL}, - {NULL, NULL}, + {"write", (PyCFunction)mbstreamwriter_write, + METH_O, NULL}, + {"writelines", (PyCFunction)mbstreamwriter_writelines, + METH_O, NULL}, + {"reset", (PyCFunction)mbstreamwriter_reset, + METH_NOARGS, NULL}, + {NULL, NULL}, }; static PyMemberDef mbstreamwriter_members[] = { - {"stream", T_OBJECT, - offsetof(MultibyteStreamWriterObject, stream), - READONLY, NULL}, - {NULL,} + {"stream", T_OBJECT, + offsetof(MultibyteStreamWriterObject, stream), + READONLY, NULL}, + {NULL,} }; static PyTypeObject MultibyteStreamWriter_Type = { - PyVarObject_HEAD_INIT(NULL, 0) - "MultibyteStreamWriter", /* tp_name */ - sizeof(MultibyteStreamWriterObject), /* tp_basicsize */ - 0, /* tp_itemsize */ - /* methods */ - (destructor)mbstreamwriter_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 - | Py_TPFLAGS_BASETYPE, /* tp_flags */ - 0, /* tp_doc */ - (traverseproc)mbstreamwriter_traverse, /* tp_traverse */ - 0, /* tp_clear */ - 0, /* tp_richcompare */ - 0, /* tp_weaklistoffset */ - 0, /* tp_iter */ - 0, /* tp_iterext */ - mbstreamwriter_methods, /* tp_methods */ - mbstreamwriter_members, /* tp_members */ - codecctx_getsets, /* tp_getset */ - 0, /* tp_base */ - 0, /* tp_dict */ - 0, /* tp_descr_get */ - 0, /* tp_descr_set */ - 0, /* tp_dictoffset */ - mbstreamwriter_init, /* tp_init */ - 0, /* tp_alloc */ - mbstreamwriter_new, /* tp_new */ + PyVarObject_HEAD_INIT(NULL, 0) + "MultibyteStreamWriter", /* tp_name */ + sizeof(MultibyteStreamWriterObject), /* tp_basicsize */ + 0, /* tp_itemsize */ + /* methods */ + (destructor)mbstreamwriter_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 + | Py_TPFLAGS_BASETYPE, /* tp_flags */ + 0, /* tp_doc */ + (traverseproc)mbstreamwriter_traverse, /* tp_traverse */ + 0, /* tp_clear */ + 0, /* tp_richcompare */ + 0, /* tp_weaklistoffset */ + 0, /* tp_iter */ + 0, /* tp_iterext */ + mbstreamwriter_methods, /* tp_methods */ + mbstreamwriter_members, /* tp_members */ + codecctx_getsets, /* tp_getset */ + 0, /* tp_base */ + 0, /* tp_dict */ + 0, /* tp_descr_get */ + 0, /* tp_descr_set */ + 0, /* tp_dictoffset */ + mbstreamwriter_init, /* tp_init */ + 0, /* tp_alloc */ + mbstreamwriter_new, /* tp_new */ }; @@ -1790,76 +1790,76 @@ static PyObject * __create_codec(PyObject *ignore, PyObject *arg) { - MultibyteCodecObject *self; - MultibyteCodec *codec; + MultibyteCodecObject *self; + MultibyteCodec *codec; - if (!PyCapsule_IsValid(arg, PyMultibyteCodec_CAPSULE_NAME)) { - PyErr_SetString(PyExc_ValueError, "argument type invalid"); - return NULL; - } - - codec = PyCapsule_GetPointer(arg, PyMultibyteCodec_CAPSULE_NAME); - if (codec->codecinit != NULL && codec->codecinit(codec->config) != 0) - return NULL; - - self = PyObject_New(MultibyteCodecObject, &MultibyteCodec_Type); - if (self == NULL) - return NULL; - self->codec = codec; + if (!PyCapsule_IsValid(arg, PyMultibyteCodec_CAPSULE_NAME)) { + PyErr_SetString(PyExc_ValueError, "argument type invalid"); + return NULL; + } + + codec = PyCapsule_GetPointer(arg, PyMultibyteCodec_CAPSULE_NAME); + if (codec->codecinit != NULL && codec->codecinit(codec->config) != 0) + return NULL; + + self = PyObject_New(MultibyteCodecObject, &MultibyteCodec_Type); + if (self == NULL) + return NULL; + self->codec = codec; - return (PyObject *)self; + return (PyObject *)self; } static struct PyMethodDef __methods[] = { - {"__create_codec", (PyCFunction)__create_codec, METH_O}, - {NULL, NULL}, + {"__create_codec", (PyCFunction)__create_codec, METH_O}, + {NULL, NULL}, }; static struct PyModuleDef _multibytecodecmodule = { - PyModuleDef_HEAD_INIT, - "_multibytecodec", - NULL, - -1, - __methods, - NULL, - NULL, - NULL, - NULL + PyModuleDef_HEAD_INIT, + "_multibytecodec", + NULL, + -1, + __methods, + NULL, + NULL, + NULL, + NULL }; PyMODINIT_FUNC PyInit__multibytecodec(void) { - int i; - PyObject *m; - PyTypeObject *typelist[] = { - &MultibyteIncrementalEncoder_Type, - &MultibyteIncrementalDecoder_Type, - &MultibyteStreamReader_Type, - &MultibyteStreamWriter_Type, - NULL - }; - - if (PyType_Ready(&MultibyteCodec_Type) < 0) - return NULL; - - m = PyModule_Create(&_multibytecodecmodule); - if (m == NULL) - return NULL; - - for (i = 0; typelist[i] != NULL; i++) { - if (PyType_Ready(typelist[i]) < 0) - return NULL; - Py_INCREF(typelist[i]); - PyModule_AddObject(m, typelist[i]->tp_name, - (PyObject *)typelist[i]); - } - - if (PyErr_Occurred()) { - Py_FatalError("can't initialize the _multibytecodec module"); - Py_DECREF(m); - m = NULL; - } - return m; + int i; + PyObject *m; + PyTypeObject *typelist[] = { + &MultibyteIncrementalEncoder_Type, + &MultibyteIncrementalDecoder_Type, + &MultibyteStreamReader_Type, + &MultibyteStreamWriter_Type, + NULL + }; + + if (PyType_Ready(&MultibyteCodec_Type) < 0) + return NULL; + + m = PyModule_Create(&_multibytecodecmodule); + if (m == NULL) + return NULL; + + for (i = 0; typelist[i] != NULL; i++) { + if (PyType_Ready(typelist[i]) < 0) + return NULL; + Py_INCREF(typelist[i]); + PyModule_AddObject(m, typelist[i]->tp_name, + (PyObject *)typelist[i]); + } + + if (PyErr_Occurred()) { + Py_FatalError("can't initialize the _multibytecodec module"); + Py_DECREF(m); + m = NULL; + } + return m; } Modified: python/branches/release31-maint/Modules/cjkcodecs/multibytecodec.h ============================================================================== --- python/branches/release31-maint/Modules/cjkcodecs/multibytecodec.h (original) +++ python/branches/release31-maint/Modules/cjkcodecs/multibytecodec.h Sun May 9 18:14:21 2010 @@ -23,114 +23,114 @@ #endif typedef union { - void *p; - int i; - unsigned char c[8]; - ucs2_t u2[4]; - ucs4_t u4[2]; + void *p; + int i; + unsigned char c[8]; + ucs2_t u2[4]; + ucs4_t u4[2]; } MultibyteCodec_State; typedef int (*mbcodec_init)(const void *config); typedef Py_ssize_t (*mbencode_func)(MultibyteCodec_State *state, - const void *config, - const Py_UNICODE **inbuf, Py_ssize_t inleft, - unsigned char **outbuf, Py_ssize_t outleft, - int flags); + const void *config, + const Py_UNICODE **inbuf, Py_ssize_t inleft, + unsigned char **outbuf, Py_ssize_t outleft, + int flags); typedef int (*mbencodeinit_func)(MultibyteCodec_State *state, - const void *config); + const void *config); typedef Py_ssize_t (*mbencodereset_func)(MultibyteCodec_State *state, - const void *config, - unsigned char **outbuf, Py_ssize_t outleft); + const void *config, + unsigned char **outbuf, Py_ssize_t outleft); typedef Py_ssize_t (*mbdecode_func)(MultibyteCodec_State *state, - const void *config, - const unsigned char **inbuf, Py_ssize_t inleft, - Py_UNICODE **outbuf, Py_ssize_t outleft); + const void *config, + const unsigned char **inbuf, Py_ssize_t inleft, + Py_UNICODE **outbuf, Py_ssize_t outleft); typedef int (*mbdecodeinit_func)(MultibyteCodec_State *state, - const void *config); + const void *config); typedef Py_ssize_t (*mbdecodereset_func)(MultibyteCodec_State *state, - const void *config); + const void *config); typedef struct { - const char *encoding; - const void *config; - mbcodec_init codecinit; - mbencode_func encode; - mbencodeinit_func encinit; - mbencodereset_func encreset; - mbdecode_func decode; - mbdecodeinit_func decinit; - mbdecodereset_func decreset; + const char *encoding; + const void *config; + mbcodec_init codecinit; + mbencode_func encode; + mbencodeinit_func encinit; + mbencodereset_func encreset; + mbdecode_func decode; + mbdecodeinit_func decinit; + mbdecodereset_func decreset; } MultibyteCodec; typedef struct { - PyObject_HEAD - MultibyteCodec *codec; + PyObject_HEAD + MultibyteCodec *codec; } MultibyteCodecObject; #define MultibyteCodec_Check(op) ((op)->ob_type == &MultibyteCodec_Type) -#define _MultibyteStatefulCodec_HEAD \ - PyObject_HEAD \ - MultibyteCodec *codec; \ - MultibyteCodec_State state; \ - PyObject *errors; +#define _MultibyteStatefulCodec_HEAD \ + PyObject_HEAD \ + MultibyteCodec *codec; \ + MultibyteCodec_State state; \ + PyObject *errors; typedef struct { - _MultibyteStatefulCodec_HEAD + _MultibyteStatefulCodec_HEAD } MultibyteStatefulCodecContext; -#define MAXENCPENDING 2 -#define _MultibyteStatefulEncoder_HEAD \ - _MultibyteStatefulCodec_HEAD \ - Py_UNICODE pending[MAXENCPENDING]; \ - Py_ssize_t pendingsize; +#define MAXENCPENDING 2 +#define _MultibyteStatefulEncoder_HEAD \ + _MultibyteStatefulCodec_HEAD \ + Py_UNICODE pending[MAXENCPENDING]; \ + Py_ssize_t pendingsize; typedef struct { - _MultibyteStatefulEncoder_HEAD + _MultibyteStatefulEncoder_HEAD } MultibyteStatefulEncoderContext; -#define MAXDECPENDING 8 -#define _MultibyteStatefulDecoder_HEAD \ - _MultibyteStatefulCodec_HEAD \ - unsigned char pending[MAXDECPENDING]; \ - Py_ssize_t pendingsize; +#define MAXDECPENDING 8 +#define _MultibyteStatefulDecoder_HEAD \ + _MultibyteStatefulCodec_HEAD \ + unsigned char pending[MAXDECPENDING]; \ + Py_ssize_t pendingsize; typedef struct { - _MultibyteStatefulDecoder_HEAD + _MultibyteStatefulDecoder_HEAD } MultibyteStatefulDecoderContext; typedef struct { - _MultibyteStatefulEncoder_HEAD + _MultibyteStatefulEncoder_HEAD } MultibyteIncrementalEncoderObject; typedef struct { - _MultibyteStatefulDecoder_HEAD + _MultibyteStatefulDecoder_HEAD } MultibyteIncrementalDecoderObject; typedef struct { - _MultibyteStatefulDecoder_HEAD - PyObject *stream; + _MultibyteStatefulDecoder_HEAD + PyObject *stream; } MultibyteStreamReaderObject; typedef struct { - _MultibyteStatefulEncoder_HEAD - PyObject *stream; + _MultibyteStatefulEncoder_HEAD + PyObject *stream; } MultibyteStreamWriterObject; /* positive values for illegal sequences */ -#define MBERR_TOOSMALL (-1) /* insufficient output buffer space */ -#define MBERR_TOOFEW (-2) /* incomplete input buffer */ -#define MBERR_INTERNAL (-3) /* internal runtime error */ - -#define ERROR_STRICT (PyObject *)(1) -#define ERROR_IGNORE (PyObject *)(2) -#define ERROR_REPLACE (PyObject *)(3) -#define ERROR_ISCUSTOM(p) ((p) < ERROR_STRICT || ERROR_REPLACE < (p)) -#define ERROR_DECREF(p) do { \ - if (p != NULL && ERROR_ISCUSTOM(p)) { \ - Py_DECREF(p); \ - } \ +#define MBERR_TOOSMALL (-1) /* insufficient output buffer space */ +#define MBERR_TOOFEW (-2) /* incomplete input buffer */ +#define MBERR_INTERNAL (-3) /* internal runtime error */ + +#define ERROR_STRICT (PyObject *)(1) +#define ERROR_IGNORE (PyObject *)(2) +#define ERROR_REPLACE (PyObject *)(3) +#define ERROR_ISCUSTOM(p) ((p) < ERROR_STRICT || ERROR_REPLACE < (p)) +#define ERROR_DECREF(p) do { \ + if (p != NULL && ERROR_ISCUSTOM(p)) { \ + Py_DECREF(p); \ + } \ } while (0); -#define MBENC_FLUSH 0x0001 /* encode all characters encodable */ -#define MBENC_MAX MBENC_FLUSH +#define MBENC_FLUSH 0x0001 /* encode all characters encodable */ +#define MBENC_MAX MBENC_FLUSH #define PyMultibyteCodec_CAPSULE_NAME "multibytecodec.__map_*" Modified: python/branches/release31-maint/Modules/cmathmodule.c ============================================================================== --- python/branches/release31-maint/Modules/cmathmodule.c (original) +++ python/branches/release31-maint/Modules/cmathmodule.c Sun May 9 18:14:21 2010 @@ -31,7 +31,7 @@ #define CM_LOG_LARGE_DOUBLE (log(CM_LARGE_DOUBLE)) #define CM_SQRT_DBL_MIN (sqrt(DBL_MIN)) -/* +/* CM_SCALE_UP is an odd integer chosen such that multiplication by 2**CM_SCALE_UP is sufficient to turn a subnormal into a normal. CM_SCALE_DOWN is (-(CM_SCALE_UP+1)/2). These scalings are used to compute @@ -62,46 +62,46 @@ */ enum special_types { - ST_NINF, /* 0, negative infinity */ - ST_NEG, /* 1, negative finite number (nonzero) */ - ST_NZERO, /* 2, -0. */ - ST_PZERO, /* 3, +0. */ - ST_POS, /* 4, positive finite number (nonzero) */ - ST_PINF, /* 5, positive infinity */ - ST_NAN /* 6, Not a Number */ + ST_NINF, /* 0, negative infinity */ + ST_NEG, /* 1, negative finite number (nonzero) */ + ST_NZERO, /* 2, -0. */ + ST_PZERO, /* 3, +0. */ + ST_POS, /* 4, positive finite number (nonzero) */ + ST_PINF, /* 5, positive infinity */ + ST_NAN /* 6, Not a Number */ }; static enum special_types special_type(double d) { - if (Py_IS_FINITE(d)) { - if (d != 0) { - if (copysign(1., d) == 1.) - return ST_POS; - else - return ST_NEG; - } - else { - if (copysign(1., d) == 1.) - return ST_PZERO; - else - return ST_NZERO; - } - } - if (Py_IS_NAN(d)) - return ST_NAN; - if (copysign(1., d) == 1.) - return ST_PINF; - else - return ST_NINF; -} - -#define SPECIAL_VALUE(z, table) \ - if (!Py_IS_FINITE((z).real) || !Py_IS_FINITE((z).imag)) { \ - errno = 0; \ - return table[special_type((z).real)] \ - [special_type((z).imag)]; \ - } + if (Py_IS_FINITE(d)) { + if (d != 0) { + if (copysign(1., d) == 1.) + return ST_POS; + else + return ST_NEG; + } + else { + if (copysign(1., d) == 1.) + return ST_PZERO; + else + return ST_NZERO; + } + } + if (Py_IS_NAN(d)) + return ST_NAN; + if (copysign(1., d) == 1.) + return ST_PINF; + else + return ST_NINF; +} + +#define SPECIAL_VALUE(z, table) \ + if (!Py_IS_FINITE((z).real) || !Py_IS_FINITE((z).imag)) { \ + errno = 0; \ + return table[special_type((z).real)] \ + [special_type((z).imag)]; \ + } #define P Py_MATH_PI #define P14 0.25*Py_MATH_PI @@ -125,34 +125,34 @@ static Py_complex c_acos(Py_complex z) { - Py_complex s1, s2, r; + Py_complex s1, s2, r; - SPECIAL_VALUE(z, acos_special_values); + SPECIAL_VALUE(z, acos_special_values); - if (fabs(z.real) > CM_LARGE_DOUBLE || fabs(z.imag) > CM_LARGE_DOUBLE) { - /* avoid unnecessary overflow for large arguments */ - r.real = atan2(fabs(z.imag), z.real); - /* split into cases to make sure that the branch cut has the - correct continuity on systems with unsigned zeros */ - if (z.real < 0.) { - r.imag = -copysign(log(hypot(z.real/2., z.imag/2.)) + - M_LN2*2., z.imag); - } else { - r.imag = copysign(log(hypot(z.real/2., z.imag/2.)) + - M_LN2*2., -z.imag); - } - } else { - s1.real = 1.-z.real; - s1.imag = -z.imag; - s1 = c_sqrt(s1); - s2.real = 1.+z.real; - s2.imag = z.imag; - s2 = c_sqrt(s2); - r.real = 2.*atan2(s1.real, s2.real); - r.imag = asinh(s2.real*s1.imag - s2.imag*s1.real); - } - errno = 0; - return r; + if (fabs(z.real) > CM_LARGE_DOUBLE || fabs(z.imag) > CM_LARGE_DOUBLE) { + /* avoid unnecessary overflow for large arguments */ + r.real = atan2(fabs(z.imag), z.real); + /* split into cases to make sure that the branch cut has the + correct continuity on systems with unsigned zeros */ + if (z.real < 0.) { + r.imag = -copysign(log(hypot(z.real/2., z.imag/2.)) + + M_LN2*2., z.imag); + } else { + r.imag = copysign(log(hypot(z.real/2., z.imag/2.)) + + M_LN2*2., -z.imag); + } + } else { + s1.real = 1.-z.real; + s1.imag = -z.imag; + s1 = c_sqrt(s1); + s2.real = 1.+z.real; + s2.imag = z.imag; + s2 = c_sqrt(s2); + r.real = 2.*atan2(s1.real, s2.real); + r.imag = asinh(s2.real*s1.imag - s2.imag*s1.real); + } + errno = 0; + return r; } PyDoc_STRVAR(c_acos_doc, @@ -166,26 +166,26 @@ static Py_complex c_acosh(Py_complex z) { - Py_complex s1, s2, r; + Py_complex s1, s2, r; - SPECIAL_VALUE(z, acosh_special_values); + SPECIAL_VALUE(z, acosh_special_values); - if (fabs(z.real) > CM_LARGE_DOUBLE || fabs(z.imag) > CM_LARGE_DOUBLE) { - /* avoid unnecessary overflow for large arguments */ - r.real = log(hypot(z.real/2., z.imag/2.)) + M_LN2*2.; - r.imag = atan2(z.imag, z.real); - } else { - s1.real = z.real - 1.; - s1.imag = z.imag; - s1 = c_sqrt(s1); - s2.real = z.real + 1.; - s2.imag = z.imag; - s2 = c_sqrt(s2); - r.real = asinh(s1.real*s2.real + s1.imag*s2.imag); - r.imag = 2.*atan2(s1.imag, s2.real); - } - errno = 0; - return r; + if (fabs(z.real) > CM_LARGE_DOUBLE || fabs(z.imag) > CM_LARGE_DOUBLE) { + /* avoid unnecessary overflow for large arguments */ + r.real = log(hypot(z.real/2., z.imag/2.)) + M_LN2*2.; + r.imag = atan2(z.imag, z.real); + } else { + s1.real = z.real - 1.; + s1.imag = z.imag; + s1 = c_sqrt(s1); + s2.real = z.real + 1.; + s2.imag = z.imag; + s2 = c_sqrt(s2); + r.real = asinh(s1.real*s2.real + s1.imag*s2.imag); + r.imag = 2.*atan2(s1.imag, s2.real); + } + errno = 0; + return r; } PyDoc_STRVAR(c_acosh_doc, @@ -197,14 +197,14 @@ static Py_complex c_asin(Py_complex z) { - /* asin(z) = -i asinh(iz) */ - Py_complex s, r; - s.real = -z.imag; - s.imag = z.real; - s = c_asinh(s); - r.real = s.imag; - r.imag = -s.real; - return r; + /* asin(z) = -i asinh(iz) */ + Py_complex s, r; + s.real = -z.imag; + s.imag = z.real; + s = c_asinh(s); + r.real = s.imag; + r.imag = -s.real; + return r; } PyDoc_STRVAR(c_asin_doc, @@ -218,31 +218,31 @@ static Py_complex c_asinh(Py_complex z) { - Py_complex s1, s2, r; + Py_complex s1, s2, r; - SPECIAL_VALUE(z, asinh_special_values); + SPECIAL_VALUE(z, asinh_special_values); - if (fabs(z.real) > CM_LARGE_DOUBLE || fabs(z.imag) > CM_LARGE_DOUBLE) { - if (z.imag >= 0.) { - r.real = copysign(log(hypot(z.real/2., z.imag/2.)) + - M_LN2*2., z.real); - } else { - r.real = -copysign(log(hypot(z.real/2., z.imag/2.)) + - M_LN2*2., -z.real); - } - r.imag = atan2(z.imag, fabs(z.real)); - } else { - s1.real = 1.+z.imag; - s1.imag = -z.real; - s1 = c_sqrt(s1); - s2.real = 1.-z.imag; - s2.imag = z.real; - s2 = c_sqrt(s2); - r.real = asinh(s1.real*s2.imag-s2.real*s1.imag); - r.imag = atan2(z.imag, s1.real*s2.real-s1.imag*s2.imag); - } - errno = 0; - return r; + if (fabs(z.real) > CM_LARGE_DOUBLE || fabs(z.imag) > CM_LARGE_DOUBLE) { + if (z.imag >= 0.) { + r.real = copysign(log(hypot(z.real/2., z.imag/2.)) + + M_LN2*2., z.real); + } else { + r.real = -copysign(log(hypot(z.real/2., z.imag/2.)) + + M_LN2*2., -z.real); + } + r.imag = atan2(z.imag, fabs(z.real)); + } else { + s1.real = 1.+z.imag; + s1.imag = -z.real; + s1 = c_sqrt(s1); + s2.real = 1.-z.imag; + s2.imag = z.real; + s2 = c_sqrt(s2); + r.real = asinh(s1.real*s2.imag-s2.real*s1.imag); + r.imag = atan2(z.imag, s1.real*s2.real-s1.imag*s2.imag); + } + errno = 0; + return r; } PyDoc_STRVAR(c_asinh_doc, @@ -254,14 +254,14 @@ static Py_complex c_atan(Py_complex z) { - /* atan(z) = -i atanh(iz) */ - Py_complex s, r; - s.real = -z.imag; - s.imag = z.real; - s = c_atanh(s); - r.real = s.imag; - r.imag = -s.real; - return r; + /* atan(z) = -i atanh(iz) */ + Py_complex s, r; + s.real = -z.imag; + s.imag = z.real; + s = c_atanh(s); + r.real = s.imag; + r.imag = -s.real; + return r; } /* Windows screws up atan2 for inf and nan, and alpha Tru64 5.1 doesn't follow @@ -269,29 +269,29 @@ static double c_atan2(Py_complex z) { - if (Py_IS_NAN(z.real) || Py_IS_NAN(z.imag)) - return Py_NAN; - if (Py_IS_INFINITY(z.imag)) { - if (Py_IS_INFINITY(z.real)) { - if (copysign(1., z.real) == 1.) - /* atan2(+-inf, +inf) == +-pi/4 */ - return copysign(0.25*Py_MATH_PI, z.imag); - else - /* atan2(+-inf, -inf) == +-pi*3/4 */ - return copysign(0.75*Py_MATH_PI, z.imag); - } - /* atan2(+-inf, x) == +-pi/2 for finite x */ - return copysign(0.5*Py_MATH_PI, z.imag); - } - if (Py_IS_INFINITY(z.real) || z.imag == 0.) { - if (copysign(1., z.real) == 1.) - /* atan2(+-y, +inf) = atan2(+-0, +x) = +-0. */ - return copysign(0., z.imag); - else - /* atan2(+-y, -inf) = atan2(+-0., -x) = +-pi. */ - return copysign(Py_MATH_PI, z.imag); - } - return atan2(z.imag, z.real); + if (Py_IS_NAN(z.real) || Py_IS_NAN(z.imag)) + return Py_NAN; + if (Py_IS_INFINITY(z.imag)) { + if (Py_IS_INFINITY(z.real)) { + if (copysign(1., z.real) == 1.) + /* atan2(+-inf, +inf) == +-pi/4 */ + return copysign(0.25*Py_MATH_PI, z.imag); + else + /* atan2(+-inf, -inf) == +-pi*3/4 */ + return copysign(0.75*Py_MATH_PI, z.imag); + } + /* atan2(+-inf, x) == +-pi/2 for finite x */ + return copysign(0.5*Py_MATH_PI, z.imag); + } + if (Py_IS_INFINITY(z.real) || z.imag == 0.) { + if (copysign(1., z.real) == 1.) + /* atan2(+-y, +inf) = atan2(+-0, +x) = +-0. */ + return copysign(0., z.imag); + else + /* atan2(+-y, -inf) = atan2(+-0., -x) = +-pi. */ + return copysign(Py_MATH_PI, z.imag); + } + return atan2(z.imag, z.real); } PyDoc_STRVAR(c_atan_doc, @@ -305,48 +305,48 @@ static Py_complex c_atanh(Py_complex z) { - Py_complex r; - double ay, h; + Py_complex r; + double ay, h; - SPECIAL_VALUE(z, atanh_special_values); + SPECIAL_VALUE(z, atanh_special_values); - /* Reduce to case where z.real >= 0., using atanh(z) = -atanh(-z). */ - if (z.real < 0.) { - return c_neg(c_atanh(c_neg(z))); - } - - ay = fabs(z.imag); - if (z.real > CM_SQRT_LARGE_DOUBLE || ay > CM_SQRT_LARGE_DOUBLE) { - /* - if abs(z) is large then we use the approximation - atanh(z) ~ 1/z +/- i*pi/2 (+/- depending on the sign - of z.imag) - */ - h = hypot(z.real/2., z.imag/2.); /* safe from overflow */ - r.real = z.real/4./h/h; - /* the two negations in the next line cancel each other out - except when working with unsigned zeros: they're there to - ensure that the branch cut has the correct continuity on - systems that don't support signed zeros */ - r.imag = -copysign(Py_MATH_PI/2., -z.imag); - errno = 0; - } else if (z.real == 1. && ay < CM_SQRT_DBL_MIN) { - /* C99 standard says: atanh(1+/-0.) should be inf +/- 0i */ - if (ay == 0.) { - r.real = INF; - r.imag = z.imag; - errno = EDOM; - } else { - r.real = -log(sqrt(ay)/sqrt(hypot(ay, 2.))); - r.imag = copysign(atan2(2., -ay)/2, z.imag); - errno = 0; - } - } else { - r.real = log1p(4.*z.real/((1-z.real)*(1-z.real) + ay*ay))/4.; - r.imag = -atan2(-2.*z.imag, (1-z.real)*(1+z.real) - ay*ay)/2.; - errno = 0; - } - return r; + /* Reduce to case where z.real >= 0., using atanh(z) = -atanh(-z). */ + if (z.real < 0.) { + return c_neg(c_atanh(c_neg(z))); + } + + ay = fabs(z.imag); + if (z.real > CM_SQRT_LARGE_DOUBLE || ay > CM_SQRT_LARGE_DOUBLE) { + /* + if abs(z) is large then we use the approximation + atanh(z) ~ 1/z +/- i*pi/2 (+/- depending on the sign + of z.imag) + */ + h = hypot(z.real/2., z.imag/2.); /* safe from overflow */ + r.real = z.real/4./h/h; + /* the two negations in the next line cancel each other out + except when working with unsigned zeros: they're there to + ensure that the branch cut has the correct continuity on + systems that don't support signed zeros */ + r.imag = -copysign(Py_MATH_PI/2., -z.imag); + errno = 0; + } else if (z.real == 1. && ay < CM_SQRT_DBL_MIN) { + /* C99 standard says: atanh(1+/-0.) should be inf +/- 0i */ + if (ay == 0.) { + r.real = INF; + r.imag = z.imag; + errno = EDOM; + } else { + r.real = -log(sqrt(ay)/sqrt(hypot(ay, 2.))); + r.imag = copysign(atan2(2., -ay)/2, z.imag); + errno = 0; + } + } else { + r.real = log1p(4.*z.real/((1-z.real)*(1-z.real) + ay*ay))/4.; + r.imag = -atan2(-2.*z.imag, (1-z.real)*(1+z.real) - ay*ay)/2.; + errno = 0; + } + return r; } PyDoc_STRVAR(c_atanh_doc, @@ -358,12 +358,12 @@ static Py_complex c_cos(Py_complex z) { - /* cos(z) = cosh(iz) */ - Py_complex r; - r.real = -z.imag; - r.imag = z.real; - r = c_cosh(r); - return r; + /* cos(z) = cosh(iz) */ + Py_complex r; + r.real = -z.imag; + r.imag = z.real; + r = c_cosh(r); + return r; } PyDoc_STRVAR(c_cos_doc, @@ -378,51 +378,51 @@ static Py_complex c_cosh(Py_complex z) { - Py_complex r; - double x_minus_one; + Py_complex r; + double x_minus_one; - /* special treatment for cosh(+/-inf + iy) if y is not a NaN */ - if (!Py_IS_FINITE(z.real) || !Py_IS_FINITE(z.imag)) { - if (Py_IS_INFINITY(z.real) && Py_IS_FINITE(z.imag) && - (z.imag != 0.)) { - if (z.real > 0) { - r.real = copysign(INF, cos(z.imag)); - r.imag = copysign(INF, sin(z.imag)); - } - else { - r.real = copysign(INF, cos(z.imag)); - r.imag = -copysign(INF, sin(z.imag)); - } - } - else { - r = cosh_special_values[special_type(z.real)] - [special_type(z.imag)]; - } - /* need to set errno = EDOM if y is +/- infinity and x is not - a NaN */ - if (Py_IS_INFINITY(z.imag) && !Py_IS_NAN(z.real)) - errno = EDOM; - else - errno = 0; - return r; - } - - if (fabs(z.real) > CM_LOG_LARGE_DOUBLE) { - /* deal correctly with cases where cosh(z.real) overflows but - cosh(z) does not. */ - x_minus_one = z.real - copysign(1., z.real); - r.real = cos(z.imag) * cosh(x_minus_one) * Py_MATH_E; - r.imag = sin(z.imag) * sinh(x_minus_one) * Py_MATH_E; - } else { - r.real = cos(z.imag) * cosh(z.real); - r.imag = sin(z.imag) * sinh(z.real); - } - /* detect overflow, and set errno accordingly */ - if (Py_IS_INFINITY(r.real) || Py_IS_INFINITY(r.imag)) - errno = ERANGE; - else - errno = 0; - return r; + /* special treatment for cosh(+/-inf + iy) if y is not a NaN */ + if (!Py_IS_FINITE(z.real) || !Py_IS_FINITE(z.imag)) { + if (Py_IS_INFINITY(z.real) && Py_IS_FINITE(z.imag) && + (z.imag != 0.)) { + if (z.real > 0) { + r.real = copysign(INF, cos(z.imag)); + r.imag = copysign(INF, sin(z.imag)); + } + else { + r.real = copysign(INF, cos(z.imag)); + r.imag = -copysign(INF, sin(z.imag)); + } + } + else { + r = cosh_special_values[special_type(z.real)] + [special_type(z.imag)]; + } + /* need to set errno = EDOM if y is +/- infinity and x is not + a NaN */ + if (Py_IS_INFINITY(z.imag) && !Py_IS_NAN(z.real)) + errno = EDOM; + else + errno = 0; + return r; + } + + if (fabs(z.real) > CM_LOG_LARGE_DOUBLE) { + /* deal correctly with cases where cosh(z.real) overflows but + cosh(z) does not. */ + x_minus_one = z.real - copysign(1., z.real); + r.real = cos(z.imag) * cosh(x_minus_one) * Py_MATH_E; + r.imag = sin(z.imag) * sinh(x_minus_one) * Py_MATH_E; + } else { + r.real = cos(z.imag) * cosh(z.real); + r.imag = sin(z.imag) * sinh(z.real); + } + /* detect overflow, and set errno accordingly */ + if (Py_IS_INFINITY(r.real) || Py_IS_INFINITY(r.imag)) + errno = ERANGE; + else + errno = 0; + return r; } PyDoc_STRVAR(c_cosh_doc, @@ -438,51 +438,51 @@ static Py_complex c_exp(Py_complex z) { - Py_complex r; - double l; + Py_complex r; + double l; - if (!Py_IS_FINITE(z.real) || !Py_IS_FINITE(z.imag)) { - if (Py_IS_INFINITY(z.real) && Py_IS_FINITE(z.imag) - && (z.imag != 0.)) { - if (z.real > 0) { - r.real = copysign(INF, cos(z.imag)); - r.imag = copysign(INF, sin(z.imag)); - } - else { - r.real = copysign(0., cos(z.imag)); - r.imag = copysign(0., sin(z.imag)); - } - } - else { - r = exp_special_values[special_type(z.real)] - [special_type(z.imag)]; - } - /* need to set errno = EDOM if y is +/- infinity and x is not - a NaN and not -infinity */ - if (Py_IS_INFINITY(z.imag) && - (Py_IS_FINITE(z.real) || - (Py_IS_INFINITY(z.real) && z.real > 0))) - errno = EDOM; - else - errno = 0; - return r; - } - - if (z.real > CM_LOG_LARGE_DOUBLE) { - l = exp(z.real-1.); - r.real = l*cos(z.imag)*Py_MATH_E; - r.imag = l*sin(z.imag)*Py_MATH_E; - } else { - l = exp(z.real); - r.real = l*cos(z.imag); - r.imag = l*sin(z.imag); - } - /* detect overflow, and set errno accordingly */ - if (Py_IS_INFINITY(r.real) || Py_IS_INFINITY(r.imag)) - errno = ERANGE; - else - errno = 0; - return r; + if (!Py_IS_FINITE(z.real) || !Py_IS_FINITE(z.imag)) { + if (Py_IS_INFINITY(z.real) && Py_IS_FINITE(z.imag) + && (z.imag != 0.)) { + if (z.real > 0) { + r.real = copysign(INF, cos(z.imag)); + r.imag = copysign(INF, sin(z.imag)); + } + else { + r.real = copysign(0., cos(z.imag)); + r.imag = copysign(0., sin(z.imag)); + } + } + else { + r = exp_special_values[special_type(z.real)] + [special_type(z.imag)]; + } + /* need to set errno = EDOM if y is +/- infinity and x is not + a NaN and not -infinity */ + if (Py_IS_INFINITY(z.imag) && + (Py_IS_FINITE(z.real) || + (Py_IS_INFINITY(z.real) && z.real > 0))) + errno = EDOM; + else + errno = 0; + return r; + } + + if (z.real > CM_LOG_LARGE_DOUBLE) { + l = exp(z.real-1.); + r.real = l*cos(z.imag)*Py_MATH_E; + r.imag = l*sin(z.imag)*Py_MATH_E; + } else { + l = exp(z.real); + r.real = l*cos(z.imag); + r.imag = l*sin(z.imag); + } + /* detect overflow, and set errno accordingly */ + if (Py_IS_INFINITY(r.real) || Py_IS_INFINITY(r.imag)) + errno = ERANGE; + else + errno = 0; + return r; } PyDoc_STRVAR(c_exp_doc, @@ -496,85 +496,85 @@ static Py_complex c_log(Py_complex z) { - /* - The usual formula for the real part is log(hypot(z.real, z.imag)). - There are four situations where this formula is potentially - problematic: - - (1) the absolute value of z is subnormal. Then hypot is subnormal, - so has fewer than the usual number of bits of accuracy, hence may - have large relative error. This then gives a large absolute error - in the log. This can be solved by rescaling z by a suitable power - of 2. - - (2) the absolute value of z is greater than DBL_MAX (e.g. when both - z.real and z.imag are within a factor of 1/sqrt(2) of DBL_MAX) - Again, rescaling solves this. - - (3) the absolute value of z is close to 1. In this case it's - difficult to achieve good accuracy, at least in part because a - change of 1ulp in the real or imaginary part of z can result in a - change of billions of ulps in the correctly rounded answer. - - (4) z = 0. The simplest thing to do here is to call the - floating-point log with an argument of 0, and let its behaviour - (returning -infinity, signaling a floating-point exception, setting - errno, or whatever) determine that of c_log. So the usual formula - is fine here. - - */ - - Py_complex r; - double ax, ay, am, an, h; - - SPECIAL_VALUE(z, log_special_values); - - ax = fabs(z.real); - ay = fabs(z.imag); - - if (ax > CM_LARGE_DOUBLE || ay > CM_LARGE_DOUBLE) { - r.real = log(hypot(ax/2., ay/2.)) + M_LN2; - } else if (ax < DBL_MIN && ay < DBL_MIN) { - if (ax > 0. || ay > 0.) { - /* catch cases where hypot(ax, ay) is subnormal */ - r.real = log(hypot(ldexp(ax, DBL_MANT_DIG), - ldexp(ay, DBL_MANT_DIG))) - DBL_MANT_DIG*M_LN2; - } - else { - /* log(+/-0. +/- 0i) */ - r.real = -INF; - r.imag = atan2(z.imag, z.real); - errno = EDOM; - return r; - } - } else { - h = hypot(ax, ay); - if (0.71 <= h && h <= 1.73) { - am = ax > ay ? ax : ay; /* max(ax, ay) */ - an = ax > ay ? ay : ax; /* min(ax, ay) */ - r.real = log1p((am-1)*(am+1)+an*an)/2.; - } else { - r.real = log(h); - } - } - r.imag = atan2(z.imag, z.real); - errno = 0; - return r; + /* + The usual formula for the real part is log(hypot(z.real, z.imag)). + There are four situations where this formula is potentially + problematic: + + (1) the absolute value of z is subnormal. Then hypot is subnormal, + so has fewer than the usual number of bits of accuracy, hence may + have large relative error. This then gives a large absolute error + in the log. This can be solved by rescaling z by a suitable power + of 2. + + (2) the absolute value of z is greater than DBL_MAX (e.g. when both + z.real and z.imag are within a factor of 1/sqrt(2) of DBL_MAX) + Again, rescaling solves this. + + (3) the absolute value of z is close to 1. In this case it's + difficult to achieve good accuracy, at least in part because a + change of 1ulp in the real or imaginary part of z can result in a + change of billions of ulps in the correctly rounded answer. + + (4) z = 0. The simplest thing to do here is to call the + floating-point log with an argument of 0, and let its behaviour + (returning -infinity, signaling a floating-point exception, setting + errno, or whatever) determine that of c_log. So the usual formula + is fine here. + + */ + + Py_complex r; + double ax, ay, am, an, h; + + SPECIAL_VALUE(z, log_special_values); + + ax = fabs(z.real); + ay = fabs(z.imag); + + if (ax > CM_LARGE_DOUBLE || ay > CM_LARGE_DOUBLE) { + r.real = log(hypot(ax/2., ay/2.)) + M_LN2; + } else if (ax < DBL_MIN && ay < DBL_MIN) { + if (ax > 0. || ay > 0.) { + /* catch cases where hypot(ax, ay) is subnormal */ + r.real = log(hypot(ldexp(ax, DBL_MANT_DIG), + ldexp(ay, DBL_MANT_DIG))) - DBL_MANT_DIG*M_LN2; + } + else { + /* log(+/-0. +/- 0i) */ + r.real = -INF; + r.imag = atan2(z.imag, z.real); + errno = EDOM; + return r; + } + } else { + h = hypot(ax, ay); + if (0.71 <= h && h <= 1.73) { + am = ax > ay ? ax : ay; /* max(ax, ay) */ + an = ax > ay ? ay : ax; /* min(ax, ay) */ + r.real = log1p((am-1)*(am+1)+an*an)/2.; + } else { + r.real = log(h); + } + } + r.imag = atan2(z.imag, z.real); + errno = 0; + return r; } static Py_complex c_log10(Py_complex z) { - Py_complex r; - int errno_save; + Py_complex r; + int errno_save; - r = c_log(z); - errno_save = errno; /* just in case the divisions affect errno */ - r.real = r.real / M_LN10; - r.imag = r.imag / M_LN10; - errno = errno_save; - return r; + r = c_log(z); + errno_save = errno; /* just in case the divisions affect errno */ + r.real = r.real / M_LN10; + r.imag = r.imag / M_LN10; + errno = errno_save; + return r; } PyDoc_STRVAR(c_log10_doc, @@ -586,14 +586,14 @@ static Py_complex c_sin(Py_complex z) { - /* sin(z) = -i sin(iz) */ - Py_complex s, r; - s.real = -z.imag; - s.imag = z.real; - s = c_sinh(s); - r.real = s.imag; - r.imag = -s.real; - return r; + /* sin(z) = -i sin(iz) */ + Py_complex s, r; + s.real = -z.imag; + s.imag = z.real; + s = c_sinh(s); + r.real = s.imag; + r.imag = -s.real; + return r; } PyDoc_STRVAR(c_sin_doc, @@ -608,50 +608,50 @@ static Py_complex c_sinh(Py_complex z) { - Py_complex r; - double x_minus_one; + Py_complex r; + double x_minus_one; - /* special treatment for sinh(+/-inf + iy) if y is finite and - nonzero */ - if (!Py_IS_FINITE(z.real) || !Py_IS_FINITE(z.imag)) { - if (Py_IS_INFINITY(z.real) && Py_IS_FINITE(z.imag) - && (z.imag != 0.)) { - if (z.real > 0) { - r.real = copysign(INF, cos(z.imag)); - r.imag = copysign(INF, sin(z.imag)); - } - else { - r.real = -copysign(INF, cos(z.imag)); - r.imag = copysign(INF, sin(z.imag)); - } - } - else { - r = sinh_special_values[special_type(z.real)] - [special_type(z.imag)]; - } - /* need to set errno = EDOM if y is +/- infinity and x is not - a NaN */ - if (Py_IS_INFINITY(z.imag) && !Py_IS_NAN(z.real)) - errno = EDOM; - else - errno = 0; - return r; - } - - if (fabs(z.real) > CM_LOG_LARGE_DOUBLE) { - x_minus_one = z.real - copysign(1., z.real); - r.real = cos(z.imag) * sinh(x_minus_one) * Py_MATH_E; - r.imag = sin(z.imag) * cosh(x_minus_one) * Py_MATH_E; - } else { - r.real = cos(z.imag) * sinh(z.real); - r.imag = sin(z.imag) * cosh(z.real); - } - /* detect overflow, and set errno accordingly */ - if (Py_IS_INFINITY(r.real) || Py_IS_INFINITY(r.imag)) - errno = ERANGE; - else - errno = 0; - return r; + /* special treatment for sinh(+/-inf + iy) if y is finite and + nonzero */ + if (!Py_IS_FINITE(z.real) || !Py_IS_FINITE(z.imag)) { + if (Py_IS_INFINITY(z.real) && Py_IS_FINITE(z.imag) + && (z.imag != 0.)) { + if (z.real > 0) { + r.real = copysign(INF, cos(z.imag)); + r.imag = copysign(INF, sin(z.imag)); + } + else { + r.real = -copysign(INF, cos(z.imag)); + r.imag = copysign(INF, sin(z.imag)); + } + } + else { + r = sinh_special_values[special_type(z.real)] + [special_type(z.imag)]; + } + /* need to set errno = EDOM if y is +/- infinity and x is not + a NaN */ + if (Py_IS_INFINITY(z.imag) && !Py_IS_NAN(z.real)) + errno = EDOM; + else + errno = 0; + return r; + } + + if (fabs(z.real) > CM_LOG_LARGE_DOUBLE) { + x_minus_one = z.real - copysign(1., z.real); + r.real = cos(z.imag) * sinh(x_minus_one) * Py_MATH_E; + r.imag = sin(z.imag) * cosh(x_minus_one) * Py_MATH_E; + } else { + r.real = cos(z.imag) * sinh(z.real); + r.imag = sin(z.imag) * cosh(z.real); + } + /* detect overflow, and set errno accordingly */ + if (Py_IS_INFINITY(r.real) || Py_IS_INFINITY(r.imag)) + errno = ERANGE; + else + errno = 0; + return r; } PyDoc_STRVAR(c_sinh_doc, @@ -665,68 +665,68 @@ static Py_complex c_sqrt(Py_complex z) { - /* - Method: use symmetries to reduce to the case when x = z.real and y - = z.imag are nonnegative. Then the real part of the result is - given by - - s = sqrt((x + hypot(x, y))/2) - - and the imaginary part is - - d = (y/2)/s - - If either x or y is very large then there's a risk of overflow in - computation of the expression x + hypot(x, y). We can avoid this - by rewriting the formula for s as: - - s = 2*sqrt(x/8 + hypot(x/8, y/8)) - - This costs us two extra multiplications/divisions, but avoids the - overhead of checking for x and y large. - - If both x and y are subnormal then hypot(x, y) may also be - subnormal, so will lack full precision. We solve this by rescaling - x and y by a sufficiently large power of 2 to ensure that x and y - are normal. - */ - - - Py_complex r; - double s,d; - double ax, ay; - - SPECIAL_VALUE(z, sqrt_special_values); - - if (z.real == 0. && z.imag == 0.) { - r.real = 0.; - r.imag = z.imag; - return r; - } - - ax = fabs(z.real); - ay = fabs(z.imag); - - if (ax < DBL_MIN && ay < DBL_MIN && (ax > 0. || ay > 0.)) { - /* here we catch cases where hypot(ax, ay) is subnormal */ - ax = ldexp(ax, CM_SCALE_UP); - s = ldexp(sqrt(ax + hypot(ax, ldexp(ay, CM_SCALE_UP))), - CM_SCALE_DOWN); - } else { - ax /= 8.; - s = 2.*sqrt(ax + hypot(ax, ay/8.)); - } - d = ay/(2.*s); - - if (z.real >= 0.) { - r.real = s; - r.imag = copysign(d, z.imag); - } else { - r.real = d; - r.imag = copysign(s, z.imag); - } - errno = 0; - return r; + /* + Method: use symmetries to reduce to the case when x = z.real and y + = z.imag are nonnegative. Then the real part of the result is + given by + + s = sqrt((x + hypot(x, y))/2) + + and the imaginary part is + + d = (y/2)/s + + If either x or y is very large then there's a risk of overflow in + computation of the expression x + hypot(x, y). We can avoid this + by rewriting the formula for s as: + + s = 2*sqrt(x/8 + hypot(x/8, y/8)) + + This costs us two extra multiplications/divisions, but avoids the + overhead of checking for x and y large. + + If both x and y are subnormal then hypot(x, y) may also be + subnormal, so will lack full precision. We solve this by rescaling + x and y by a sufficiently large power of 2 to ensure that x and y + are normal. + */ + + + Py_complex r; + double s,d; + double ax, ay; + + SPECIAL_VALUE(z, sqrt_special_values); + + if (z.real == 0. && z.imag == 0.) { + r.real = 0.; + r.imag = z.imag; + return r; + } + + ax = fabs(z.real); + ay = fabs(z.imag); + + if (ax < DBL_MIN && ay < DBL_MIN && (ax > 0. || ay > 0.)) { + /* here we catch cases where hypot(ax, ay) is subnormal */ + ax = ldexp(ax, CM_SCALE_UP); + s = ldexp(sqrt(ax + hypot(ax, ldexp(ay, CM_SCALE_UP))), + CM_SCALE_DOWN); + } else { + ax /= 8.; + s = 2.*sqrt(ax + hypot(ax, ay/8.)); + } + d = ay/(2.*s); + + if (z.real >= 0.) { + r.real = s; + r.imag = copysign(d, z.imag); + } else { + r.real = d; + r.imag = copysign(s, z.imag); + } + errno = 0; + return r; } PyDoc_STRVAR(c_sqrt_doc, @@ -738,14 +738,14 @@ static Py_complex c_tan(Py_complex z) { - /* tan(z) = -i tanh(iz) */ - Py_complex s, r; - s.real = -z.imag; - s.imag = z.real; - s = c_tanh(s); - r.real = s.imag; - r.imag = -s.real; - return r; + /* tan(z) = -i tanh(iz) */ + Py_complex s, r; + s.real = -z.imag; + s.imag = z.real; + s = c_tanh(s); + r.real = s.imag; + r.imag = -s.real; + return r; } PyDoc_STRVAR(c_tan_doc, @@ -760,65 +760,65 @@ static Py_complex c_tanh(Py_complex z) { - /* Formula: + /* Formula: - tanh(x+iy) = (tanh(x)(1+tan(y)^2) + i tan(y)(1-tanh(x))^2) / - (1+tan(y)^2 tanh(x)^2) + tanh(x+iy) = (tanh(x)(1+tan(y)^2) + i tan(y)(1-tanh(x))^2) / + (1+tan(y)^2 tanh(x)^2) - To avoid excessive roundoff error, 1-tanh(x)^2 is better computed - as 1/cosh(x)^2. When abs(x) is large, we approximate 1-tanh(x)^2 - by 4 exp(-2*x) instead, to avoid possible overflow in the - computation of cosh(x). - - */ - - Py_complex r; - double tx, ty, cx, txty, denom; - - /* special treatment for tanh(+/-inf + iy) if y is finite and - nonzero */ - if (!Py_IS_FINITE(z.real) || !Py_IS_FINITE(z.imag)) { - if (Py_IS_INFINITY(z.real) && Py_IS_FINITE(z.imag) - && (z.imag != 0.)) { - if (z.real > 0) { - r.real = 1.0; - r.imag = copysign(0., - 2.*sin(z.imag)*cos(z.imag)); - } - else { - r.real = -1.0; - r.imag = copysign(0., - 2.*sin(z.imag)*cos(z.imag)); - } - } - else { - r = tanh_special_values[special_type(z.real)] - [special_type(z.imag)]; - } - /* need to set errno = EDOM if z.imag is +/-infinity and - z.real is finite */ - if (Py_IS_INFINITY(z.imag) && Py_IS_FINITE(z.real)) - errno = EDOM; - else - errno = 0; - return r; - } - - /* danger of overflow in 2.*z.imag !*/ - if (fabs(z.real) > CM_LOG_LARGE_DOUBLE) { - r.real = copysign(1., z.real); - r.imag = 4.*sin(z.imag)*cos(z.imag)*exp(-2.*fabs(z.real)); - } else { - tx = tanh(z.real); - ty = tan(z.imag); - cx = 1./cosh(z.real); - txty = tx*ty; - denom = 1. + txty*txty; - r.real = tx*(1.+ty*ty)/denom; - r.imag = ((ty/denom)*cx)*cx; - } - errno = 0; - return r; + To avoid excessive roundoff error, 1-tanh(x)^2 is better computed + as 1/cosh(x)^2. When abs(x) is large, we approximate 1-tanh(x)^2 + by 4 exp(-2*x) instead, to avoid possible overflow in the + computation of cosh(x). + + */ + + Py_complex r; + double tx, ty, cx, txty, denom; + + /* special treatment for tanh(+/-inf + iy) if y is finite and + nonzero */ + if (!Py_IS_FINITE(z.real) || !Py_IS_FINITE(z.imag)) { + if (Py_IS_INFINITY(z.real) && Py_IS_FINITE(z.imag) + && (z.imag != 0.)) { + if (z.real > 0) { + r.real = 1.0; + r.imag = copysign(0., + 2.*sin(z.imag)*cos(z.imag)); + } + else { + r.real = -1.0; + r.imag = copysign(0., + 2.*sin(z.imag)*cos(z.imag)); + } + } + else { + r = tanh_special_values[special_type(z.real)] + [special_type(z.imag)]; + } + /* need to set errno = EDOM if z.imag is +/-infinity and + z.real is finite */ + if (Py_IS_INFINITY(z.imag) && Py_IS_FINITE(z.real)) + errno = EDOM; + else + errno = 0; + return r; + } + + /* danger of overflow in 2.*z.imag !*/ + if (fabs(z.real) > CM_LOG_LARGE_DOUBLE) { + r.real = copysign(1., z.real); + r.imag = 4.*sin(z.imag)*cos(z.imag)*exp(-2.*fabs(z.real)); + } else { + tx = tanh(z.real); + ty = tan(z.imag); + cx = 1./cosh(z.real); + txty = tx*ty; + denom = 1. + txty*txty; + r.real = tx*(1.+ty*ty)/denom; + r.imag = ((ty/denom)*cx)*cx; + } + errno = 0; + return r; } PyDoc_STRVAR(c_tanh_doc, @@ -830,23 +830,23 @@ static PyObject * cmath_log(PyObject *self, PyObject *args) { - Py_complex x; - Py_complex y; + Py_complex x; + Py_complex y; - if (!PyArg_ParseTuple(args, "D|D", &x, &y)) - return NULL; + if (!PyArg_ParseTuple(args, "D|D", &x, &y)) + return NULL; - errno = 0; - PyFPE_START_PROTECT("complex function", return 0) - x = c_log(x); - if (PyTuple_GET_SIZE(args) == 2) { - y = c_log(y); - x = c_quot(x, y); - } - PyFPE_END_PROTECT(x) - if (errno != 0) - return math_error(); - return PyComplex_FromCComplex(x); + errno = 0; + PyFPE_START_PROTECT("complex function", return 0) + x = c_log(x); + if (PyTuple_GET_SIZE(args) == 2) { + y = c_log(y); + x = c_quot(x, y); + } + PyFPE_END_PROTECT(x) + if (errno != 0) + return math_error(); + return PyComplex_FromCComplex(x); } PyDoc_STRVAR(cmath_log_doc, @@ -859,42 +859,42 @@ static PyObject * math_error(void) { - if (errno == EDOM) - PyErr_SetString(PyExc_ValueError, "math domain error"); - else if (errno == ERANGE) - PyErr_SetString(PyExc_OverflowError, "math range error"); - else /* Unexpected math error */ - PyErr_SetFromErrno(PyExc_ValueError); - return NULL; + if (errno == EDOM) + PyErr_SetString(PyExc_ValueError, "math domain error"); + else if (errno == ERANGE) + PyErr_SetString(PyExc_OverflowError, "math range error"); + else /* Unexpected math error */ + PyErr_SetFromErrno(PyExc_ValueError); + return NULL; } static PyObject * math_1(PyObject *args, Py_complex (*func)(Py_complex)) { - Py_complex x,r ; - if (!PyArg_ParseTuple(args, "D", &x)) - return NULL; - errno = 0; - PyFPE_START_PROTECT("complex function", return 0); - r = (*func)(x); - PyFPE_END_PROTECT(r); - if (errno == EDOM) { - PyErr_SetString(PyExc_ValueError, "math domain error"); - return NULL; - } - else if (errno == ERANGE) { - PyErr_SetString(PyExc_OverflowError, "math range error"); - return NULL; - } - else { - return PyComplex_FromCComplex(r); - } + Py_complex x,r ; + if (!PyArg_ParseTuple(args, "D", &x)) + return NULL; + errno = 0; + PyFPE_START_PROTECT("complex function", return 0); + r = (*func)(x); + PyFPE_END_PROTECT(r); + if (errno == EDOM) { + PyErr_SetString(PyExc_ValueError, "math domain error"); + return NULL; + } + else if (errno == ERANGE) { + PyErr_SetString(PyExc_OverflowError, "math range error"); + return NULL; + } + else { + return PyComplex_FromCComplex(r); + } } #define FUNC1(stubname, func) \ - static PyObject * stubname(PyObject *self, PyObject *args) { \ - return math_1(args, func); \ - } + static PyObject * stubname(PyObject *self, PyObject *args) { \ + return math_1(args, func); \ + } FUNC1(cmath_acos, c_acos) FUNC1(cmath_acosh, c_acosh) @@ -915,18 +915,18 @@ static PyObject * cmath_phase(PyObject *self, PyObject *args) { - Py_complex z; - double phi; - if (!PyArg_ParseTuple(args, "D:phase", &z)) - return NULL; - errno = 0; - PyFPE_START_PROTECT("arg function", return 0) - phi = c_atan2(z); - PyFPE_END_PROTECT(phi) - if (errno != 0) - return math_error(); - else - return PyFloat_FromDouble(phi); + Py_complex z; + double phi; + if (!PyArg_ParseTuple(args, "D:phase", &z)) + return NULL; + errno = 0; + PyFPE_START_PROTECT("arg function", return 0) + phi = c_atan2(z); + PyFPE_END_PROTECT(phi) + if (errno != 0) + return math_error(); + else + return PyFloat_FromDouble(phi); } PyDoc_STRVAR(cmath_phase_doc, @@ -936,18 +936,18 @@ static PyObject * cmath_polar(PyObject *self, PyObject *args) { - Py_complex z; - double r, phi; - if (!PyArg_ParseTuple(args, "D:polar", &z)) - return NULL; - PyFPE_START_PROTECT("polar function", return 0) - phi = c_atan2(z); /* should not cause any exception */ - r = c_abs(z); /* sets errno to ERANGE on overflow; otherwise 0 */ - PyFPE_END_PROTECT(r) - if (errno != 0) - return math_error(); - else - return Py_BuildValue("dd", r, phi); + Py_complex z; + double r, phi; + if (!PyArg_ParseTuple(args, "D:polar", &z)) + return NULL; + PyFPE_START_PROTECT("polar function", return 0) + phi = c_atan2(z); /* should not cause any exception */ + r = c_abs(z); /* sets errno to ERANGE on overflow; otherwise 0 */ + PyFPE_END_PROTECT(r) + if (errno != 0) + return math_error(); + else + return Py_BuildValue("dd", r, phi); } PyDoc_STRVAR(cmath_polar_doc, @@ -971,51 +971,51 @@ static PyObject * cmath_rect(PyObject *self, PyObject *args) { - Py_complex z; - double r, phi; - if (!PyArg_ParseTuple(args, "dd:rect", &r, &phi)) - return NULL; - errno = 0; - PyFPE_START_PROTECT("rect function", return 0) - - /* deal with special values */ - if (!Py_IS_FINITE(r) || !Py_IS_FINITE(phi)) { - /* if r is +/-infinity and phi is finite but nonzero then - result is (+-INF +-INF i), but we need to compute cos(phi) - and sin(phi) to figure out the signs. */ - if (Py_IS_INFINITY(r) && (Py_IS_FINITE(phi) - && (phi != 0.))) { - if (r > 0) { - z.real = copysign(INF, cos(phi)); - z.imag = copysign(INF, sin(phi)); - } - else { - z.real = -copysign(INF, cos(phi)); - z.imag = -copysign(INF, sin(phi)); - } - } - else { - z = rect_special_values[special_type(r)] - [special_type(phi)]; - } - /* need to set errno = EDOM if r is a nonzero number and phi - is infinite */ - if (r != 0. && !Py_IS_NAN(r) && Py_IS_INFINITY(phi)) - errno = EDOM; - else - errno = 0; - } - else { - z.real = r * cos(phi); - z.imag = r * sin(phi); - errno = 0; - } - - PyFPE_END_PROTECT(z) - if (errno != 0) - return math_error(); - else - return PyComplex_FromCComplex(z); + Py_complex z; + double r, phi; + if (!PyArg_ParseTuple(args, "dd:rect", &r, &phi)) + return NULL; + errno = 0; + PyFPE_START_PROTECT("rect function", return 0) + + /* deal with special values */ + if (!Py_IS_FINITE(r) || !Py_IS_FINITE(phi)) { + /* if r is +/-infinity and phi is finite but nonzero then + result is (+-INF +-INF i), but we need to compute cos(phi) + and sin(phi) to figure out the signs. */ + if (Py_IS_INFINITY(r) && (Py_IS_FINITE(phi) + && (phi != 0.))) { + if (r > 0) { + z.real = copysign(INF, cos(phi)); + z.imag = copysign(INF, sin(phi)); + } + else { + z.real = -copysign(INF, cos(phi)); + z.imag = -copysign(INF, sin(phi)); + } + } + else { + z = rect_special_values[special_type(r)] + [special_type(phi)]; + } + /* need to set errno = EDOM if r is a nonzero number and phi + is infinite */ + if (r != 0. && !Py_IS_NAN(r) && Py_IS_INFINITY(phi)) + errno = EDOM; + else + errno = 0; + } + else { + z.real = r * cos(phi); + z.imag = r * sin(phi); + errno = 0; + } + + PyFPE_END_PROTECT(z) + if (errno != 0) + return math_error(); + else + return PyComplex_FromCComplex(z); } PyDoc_STRVAR(cmath_rect_doc, @@ -1025,10 +1025,10 @@ static PyObject * cmath_isnan(PyObject *self, PyObject *args) { - Py_complex z; - if (!PyArg_ParseTuple(args, "D:isnan", &z)) - return NULL; - return PyBool_FromLong(Py_IS_NAN(z.real) || Py_IS_NAN(z.imag)); + Py_complex z; + if (!PyArg_ParseTuple(args, "D:isnan", &z)) + return NULL; + return PyBool_FromLong(Py_IS_NAN(z.real) || Py_IS_NAN(z.imag)); } PyDoc_STRVAR(cmath_isnan_doc, @@ -1038,11 +1038,11 @@ static PyObject * cmath_isinf(PyObject *self, PyObject *args) { - Py_complex z; - if (!PyArg_ParseTuple(args, "D:isnan", &z)) - return NULL; - return PyBool_FromLong(Py_IS_INFINITY(z.real) || - Py_IS_INFINITY(z.imag)); + Py_complex z; + if (!PyArg_ParseTuple(args, "D:isnan", &z)) + return NULL; + return PyBool_FromLong(Py_IS_INFINITY(z.real) || + Py_IS_INFINITY(z.imag)); } PyDoc_STRVAR(cmath_isinf_doc, @@ -1055,169 +1055,169 @@ "functions for complex numbers."); static PyMethodDef cmath_methods[] = { - {"acos", cmath_acos, METH_VARARGS, c_acos_doc}, - {"acosh", cmath_acosh, METH_VARARGS, c_acosh_doc}, - {"asin", cmath_asin, METH_VARARGS, c_asin_doc}, - {"asinh", cmath_asinh, METH_VARARGS, c_asinh_doc}, - {"atan", cmath_atan, METH_VARARGS, c_atan_doc}, - {"atanh", cmath_atanh, METH_VARARGS, c_atanh_doc}, - {"cos", cmath_cos, METH_VARARGS, c_cos_doc}, - {"cosh", cmath_cosh, METH_VARARGS, c_cosh_doc}, - {"exp", cmath_exp, METH_VARARGS, c_exp_doc}, - {"isinf", cmath_isinf, METH_VARARGS, cmath_isinf_doc}, - {"isnan", cmath_isnan, METH_VARARGS, cmath_isnan_doc}, - {"log", cmath_log, METH_VARARGS, cmath_log_doc}, - {"log10", cmath_log10, METH_VARARGS, c_log10_doc}, - {"phase", cmath_phase, METH_VARARGS, cmath_phase_doc}, - {"polar", cmath_polar, METH_VARARGS, cmath_polar_doc}, - {"rect", cmath_rect, METH_VARARGS, cmath_rect_doc}, - {"sin", cmath_sin, METH_VARARGS, c_sin_doc}, - {"sinh", cmath_sinh, METH_VARARGS, c_sinh_doc}, - {"sqrt", cmath_sqrt, METH_VARARGS, c_sqrt_doc}, - {"tan", cmath_tan, METH_VARARGS, c_tan_doc}, - {"tanh", cmath_tanh, METH_VARARGS, c_tanh_doc}, - {NULL, NULL} /* sentinel */ + {"acos", cmath_acos, METH_VARARGS, c_acos_doc}, + {"acosh", cmath_acosh, METH_VARARGS, c_acosh_doc}, + {"asin", cmath_asin, METH_VARARGS, c_asin_doc}, + {"asinh", cmath_asinh, METH_VARARGS, c_asinh_doc}, + {"atan", cmath_atan, METH_VARARGS, c_atan_doc}, + {"atanh", cmath_atanh, METH_VARARGS, c_atanh_doc}, + {"cos", cmath_cos, METH_VARARGS, c_cos_doc}, + {"cosh", cmath_cosh, METH_VARARGS, c_cosh_doc}, + {"exp", cmath_exp, METH_VARARGS, c_exp_doc}, + {"isinf", cmath_isinf, METH_VARARGS, cmath_isinf_doc}, + {"isnan", cmath_isnan, METH_VARARGS, cmath_isnan_doc}, + {"log", cmath_log, METH_VARARGS, cmath_log_doc}, + {"log10", cmath_log10, METH_VARARGS, c_log10_doc}, + {"phase", cmath_phase, METH_VARARGS, cmath_phase_doc}, + {"polar", cmath_polar, METH_VARARGS, cmath_polar_doc}, + {"rect", cmath_rect, METH_VARARGS, cmath_rect_doc}, + {"sin", cmath_sin, METH_VARARGS, c_sin_doc}, + {"sinh", cmath_sinh, METH_VARARGS, c_sinh_doc}, + {"sqrt", cmath_sqrt, METH_VARARGS, c_sqrt_doc}, + {"tan", cmath_tan, METH_VARARGS, c_tan_doc}, + {"tanh", cmath_tanh, METH_VARARGS, c_tanh_doc}, + {NULL, NULL} /* sentinel */ }; static struct PyModuleDef cmathmodule = { - PyModuleDef_HEAD_INIT, - "cmath", - module_doc, - -1, - cmath_methods, - NULL, - NULL, - NULL, - NULL + PyModuleDef_HEAD_INIT, + "cmath", + module_doc, + -1, + cmath_methods, + NULL, + NULL, + NULL, + NULL }; PyMODINIT_FUNC PyInit_cmath(void) { - PyObject *m; + PyObject *m; - m = PyModule_Create(&cmathmodule); - if (m == NULL) - return NULL; + m = PyModule_Create(&cmathmodule); + if (m == NULL) + return NULL; - PyModule_AddObject(m, "pi", - PyFloat_FromDouble(Py_MATH_PI)); - PyModule_AddObject(m, "e", PyFloat_FromDouble(Py_MATH_E)); + PyModule_AddObject(m, "pi", + PyFloat_FromDouble(Py_MATH_PI)); + PyModule_AddObject(m, "e", PyFloat_FromDouble(Py_MATH_E)); - /* initialize special value tables */ + /* initialize special value tables */ #define INIT_SPECIAL_VALUES(NAME, BODY) { Py_complex* p = (Py_complex*)NAME; BODY } #define C(REAL, IMAG) p->real = REAL; p->imag = IMAG; ++p; - INIT_SPECIAL_VALUES(acos_special_values, { - C(P34,INF) C(P,INF) C(P,INF) C(P,-INF) C(P,-INF) C(P34,-INF) C(N,INF) - C(P12,INF) C(U,U) C(U,U) C(U,U) C(U,U) C(P12,-INF) C(N,N) - C(P12,INF) C(U,U) C(P12,0.) C(P12,-0.) C(U,U) C(P12,-INF) C(P12,N) - C(P12,INF) C(U,U) C(P12,0.) C(P12,-0.) C(U,U) C(P12,-INF) C(P12,N) - C(P12,INF) C(U,U) C(U,U) C(U,U) C(U,U) C(P12,-INF) C(N,N) - C(P14,INF) C(0.,INF) C(0.,INF) C(0.,-INF) C(0.,-INF) C(P14,-INF) C(N,INF) - C(N,INF) C(N,N) C(N,N) C(N,N) C(N,N) C(N,-INF) C(N,N) - }) - - INIT_SPECIAL_VALUES(acosh_special_values, { - C(INF,-P34) C(INF,-P) C(INF,-P) C(INF,P) C(INF,P) C(INF,P34) C(INF,N) - C(INF,-P12) C(U,U) C(U,U) C(U,U) C(U,U) C(INF,P12) C(N,N) - C(INF,-P12) C(U,U) C(0.,-P12) C(0.,P12) C(U,U) C(INF,P12) C(N,N) - C(INF,-P12) C(U,U) C(0.,-P12) C(0.,P12) C(U,U) C(INF,P12) C(N,N) - C(INF,-P12) C(U,U) C(U,U) C(U,U) C(U,U) C(INF,P12) C(N,N) - C(INF,-P14) C(INF,-0.) C(INF,-0.) C(INF,0.) C(INF,0.) C(INF,P14) C(INF,N) - C(INF,N) C(N,N) C(N,N) C(N,N) C(N,N) C(INF,N) C(N,N) - }) - - INIT_SPECIAL_VALUES(asinh_special_values, { - C(-INF,-P14) C(-INF,-0.) C(-INF,-0.) C(-INF,0.) C(-INF,0.) C(-INF,P14) C(-INF,N) - C(-INF,-P12) C(U,U) C(U,U) C(U,U) C(U,U) C(-INF,P12) C(N,N) - C(-INF,-P12) C(U,U) C(-0.,-0.) C(-0.,0.) C(U,U) C(-INF,P12) C(N,N) - C(INF,-P12) C(U,U) C(0.,-0.) C(0.,0.) C(U,U) C(INF,P12) C(N,N) - C(INF,-P12) C(U,U) C(U,U) C(U,U) C(U,U) C(INF,P12) C(N,N) - C(INF,-P14) C(INF,-0.) C(INF,-0.) C(INF,0.) C(INF,0.) C(INF,P14) C(INF,N) - C(INF,N) C(N,N) C(N,-0.) C(N,0.) C(N,N) C(INF,N) C(N,N) - }) - - INIT_SPECIAL_VALUES(atanh_special_values, { - C(-0.,-P12) C(-0.,-P12) C(-0.,-P12) C(-0.,P12) C(-0.,P12) C(-0.,P12) C(-0.,N) - C(-0.,-P12) C(U,U) C(U,U) C(U,U) C(U,U) C(-0.,P12) C(N,N) - C(-0.,-P12) C(U,U) C(-0.,-0.) C(-0.,0.) C(U,U) C(-0.,P12) C(-0.,N) - C(0.,-P12) C(U,U) C(0.,-0.) C(0.,0.) C(U,U) C(0.,P12) C(0.,N) - C(0.,-P12) C(U,U) C(U,U) C(U,U) C(U,U) C(0.,P12) C(N,N) - C(0.,-P12) C(0.,-P12) C(0.,-P12) C(0.,P12) C(0.,P12) C(0.,P12) C(0.,N) - C(0.,-P12) C(N,N) C(N,N) C(N,N) C(N,N) C(0.,P12) C(N,N) - }) - - INIT_SPECIAL_VALUES(cosh_special_values, { - C(INF,N) C(U,U) C(INF,0.) C(INF,-0.) C(U,U) C(INF,N) C(INF,N) - C(N,N) C(U,U) C(U,U) C(U,U) C(U,U) C(N,N) C(N,N) - C(N,0.) C(U,U) C(1.,0.) C(1.,-0.) C(U,U) C(N,0.) C(N,0.) - C(N,0.) C(U,U) C(1.,-0.) C(1.,0.) C(U,U) C(N,0.) C(N,0.) - C(N,N) C(U,U) C(U,U) C(U,U) C(U,U) C(N,N) C(N,N) - C(INF,N) C(U,U) C(INF,-0.) C(INF,0.) C(U,U) C(INF,N) C(INF,N) - C(N,N) C(N,N) C(N,0.) C(N,0.) C(N,N) C(N,N) C(N,N) - }) - - INIT_SPECIAL_VALUES(exp_special_values, { - C(0.,0.) C(U,U) C(0.,-0.) C(0.,0.) C(U,U) C(0.,0.) C(0.,0.) - C(N,N) C(U,U) C(U,U) C(U,U) C(U,U) C(N,N) C(N,N) - C(N,N) C(U,U) C(1.,-0.) C(1.,0.) C(U,U) C(N,N) C(N,N) - C(N,N) C(U,U) C(1.,-0.) C(1.,0.) C(U,U) C(N,N) C(N,N) - C(N,N) C(U,U) C(U,U) C(U,U) C(U,U) C(N,N) C(N,N) - C(INF,N) C(U,U) C(INF,-0.) C(INF,0.) C(U,U) C(INF,N) C(INF,N) - C(N,N) C(N,N) C(N,-0.) C(N,0.) C(N,N) C(N,N) C(N,N) - }) - - INIT_SPECIAL_VALUES(log_special_values, { - C(INF,-P34) C(INF,-P) C(INF,-P) C(INF,P) C(INF,P) C(INF,P34) C(INF,N) - C(INF,-P12) C(U,U) C(U,U) C(U,U) C(U,U) C(INF,P12) C(N,N) - C(INF,-P12) C(U,U) C(-INF,-P) C(-INF,P) C(U,U) C(INF,P12) C(N,N) - C(INF,-P12) C(U,U) C(-INF,-0.) C(-INF,0.) C(U,U) C(INF,P12) C(N,N) - C(INF,-P12) C(U,U) C(U,U) C(U,U) C(U,U) C(INF,P12) C(N,N) - C(INF,-P14) C(INF,-0.) C(INF,-0.) C(INF,0.) C(INF,0.) C(INF,P14) C(INF,N) - C(INF,N) C(N,N) C(N,N) C(N,N) C(N,N) C(INF,N) C(N,N) - }) - - INIT_SPECIAL_VALUES(sinh_special_values, { - C(INF,N) C(U,U) C(-INF,-0.) C(-INF,0.) C(U,U) C(INF,N) C(INF,N) - C(N,N) C(U,U) C(U,U) C(U,U) C(U,U) C(N,N) C(N,N) - C(0.,N) C(U,U) C(-0.,-0.) C(-0.,0.) C(U,U) C(0.,N) C(0.,N) - C(0.,N) C(U,U) C(0.,-0.) C(0.,0.) C(U,U) C(0.,N) C(0.,N) - C(N,N) C(U,U) C(U,U) C(U,U) C(U,U) C(N,N) C(N,N) - C(INF,N) C(U,U) C(INF,-0.) C(INF,0.) C(U,U) C(INF,N) C(INF,N) - C(N,N) C(N,N) C(N,-0.) C(N,0.) C(N,N) C(N,N) C(N,N) - }) - - INIT_SPECIAL_VALUES(sqrt_special_values, { - C(INF,-INF) C(0.,-INF) C(0.,-INF) C(0.,INF) C(0.,INF) C(INF,INF) C(N,INF) - C(INF,-INF) C(U,U) C(U,U) C(U,U) C(U,U) C(INF,INF) C(N,N) - C(INF,-INF) C(U,U) C(0.,-0.) C(0.,0.) C(U,U) C(INF,INF) C(N,N) - C(INF,-INF) C(U,U) C(0.,-0.) C(0.,0.) C(U,U) C(INF,INF) C(N,N) - C(INF,-INF) C(U,U) C(U,U) C(U,U) C(U,U) C(INF,INF) C(N,N) - C(INF,-INF) C(INF,-0.) C(INF,-0.) C(INF,0.) C(INF,0.) C(INF,INF) C(INF,N) - C(INF,-INF) C(N,N) C(N,N) C(N,N) C(N,N) C(INF,INF) C(N,N) - }) - - INIT_SPECIAL_VALUES(tanh_special_values, { - C(-1.,0.) C(U,U) C(-1.,-0.) C(-1.,0.) C(U,U) C(-1.,0.) C(-1.,0.) - C(N,N) C(U,U) C(U,U) C(U,U) C(U,U) C(N,N) C(N,N) - C(N,N) C(U,U) C(-0.,-0.) C(-0.,0.) C(U,U) C(N,N) C(N,N) - C(N,N) C(U,U) C(0.,-0.) C(0.,0.) C(U,U) C(N,N) C(N,N) - C(N,N) C(U,U) C(U,U) C(U,U) C(U,U) C(N,N) C(N,N) - C(1.,0.) C(U,U) C(1.,-0.) C(1.,0.) C(U,U) C(1.,0.) C(1.,0.) - C(N,N) C(N,N) C(N,-0.) C(N,0.) C(N,N) C(N,N) C(N,N) - }) - - INIT_SPECIAL_VALUES(rect_special_values, { - C(INF,N) C(U,U) C(-INF,0.) C(-INF,-0.) C(U,U) C(INF,N) C(INF,N) - C(N,N) C(U,U) C(U,U) C(U,U) C(U,U) C(N,N) C(N,N) - C(0.,0.) C(U,U) C(-0.,0.) C(-0.,-0.) C(U,U) C(0.,0.) C(0.,0.) - C(0.,0.) C(U,U) C(0.,-0.) C(0.,0.) C(U,U) C(0.,0.) C(0.,0.) - C(N,N) C(U,U) C(U,U) C(U,U) C(U,U) C(N,N) C(N,N) - C(INF,N) C(U,U) C(INF,-0.) C(INF,0.) C(U,U) C(INF,N) C(INF,N) - C(N,N) C(N,N) C(N,0.) C(N,0.) C(N,N) C(N,N) C(N,N) - }) - return m; + INIT_SPECIAL_VALUES(acos_special_values, { + C(P34,INF) C(P,INF) C(P,INF) C(P,-INF) C(P,-INF) C(P34,-INF) C(N,INF) + C(P12,INF) C(U,U) C(U,U) C(U,U) C(U,U) C(P12,-INF) C(N,N) + C(P12,INF) C(U,U) C(P12,0.) C(P12,-0.) C(U,U) C(P12,-INF) C(P12,N) + C(P12,INF) C(U,U) C(P12,0.) C(P12,-0.) C(U,U) C(P12,-INF) C(P12,N) + C(P12,INF) C(U,U) C(U,U) C(U,U) C(U,U) C(P12,-INF) C(N,N) + C(P14,INF) C(0.,INF) C(0.,INF) C(0.,-INF) C(0.,-INF) C(P14,-INF) C(N,INF) + C(N,INF) C(N,N) C(N,N) C(N,N) C(N,N) C(N,-INF) C(N,N) + }) + + INIT_SPECIAL_VALUES(acosh_special_values, { + C(INF,-P34) C(INF,-P) C(INF,-P) C(INF,P) C(INF,P) C(INF,P34) C(INF,N) + C(INF,-P12) C(U,U) C(U,U) C(U,U) C(U,U) C(INF,P12) C(N,N) + C(INF,-P12) C(U,U) C(0.,-P12) C(0.,P12) C(U,U) C(INF,P12) C(N,N) + C(INF,-P12) C(U,U) C(0.,-P12) C(0.,P12) C(U,U) C(INF,P12) C(N,N) + C(INF,-P12) C(U,U) C(U,U) C(U,U) C(U,U) C(INF,P12) C(N,N) + C(INF,-P14) C(INF,-0.) C(INF,-0.) C(INF,0.) C(INF,0.) C(INF,P14) C(INF,N) + C(INF,N) C(N,N) C(N,N) C(N,N) C(N,N) C(INF,N) C(N,N) + }) + + INIT_SPECIAL_VALUES(asinh_special_values, { + C(-INF,-P14) C(-INF,-0.) C(-INF,-0.) C(-INF,0.) C(-INF,0.) C(-INF,P14) C(-INF,N) + C(-INF,-P12) C(U,U) C(U,U) C(U,U) C(U,U) C(-INF,P12) C(N,N) + C(-INF,-P12) C(U,U) C(-0.,-0.) C(-0.,0.) C(U,U) C(-INF,P12) C(N,N) + C(INF,-P12) C(U,U) C(0.,-0.) C(0.,0.) C(U,U) C(INF,P12) C(N,N) + C(INF,-P12) C(U,U) C(U,U) C(U,U) C(U,U) C(INF,P12) C(N,N) + C(INF,-P14) C(INF,-0.) C(INF,-0.) C(INF,0.) C(INF,0.) C(INF,P14) C(INF,N) + C(INF,N) C(N,N) C(N,-0.) C(N,0.) C(N,N) C(INF,N) C(N,N) + }) + + INIT_SPECIAL_VALUES(atanh_special_values, { + C(-0.,-P12) C(-0.,-P12) C(-0.,-P12) C(-0.,P12) C(-0.,P12) C(-0.,P12) C(-0.,N) + C(-0.,-P12) C(U,U) C(U,U) C(U,U) C(U,U) C(-0.,P12) C(N,N) + C(-0.,-P12) C(U,U) C(-0.,-0.) C(-0.,0.) C(U,U) C(-0.,P12) C(-0.,N) + C(0.,-P12) C(U,U) C(0.,-0.) C(0.,0.) C(U,U) C(0.,P12) C(0.,N) + C(0.,-P12) C(U,U) C(U,U) C(U,U) C(U,U) C(0.,P12) C(N,N) + C(0.,-P12) C(0.,-P12) C(0.,-P12) C(0.,P12) C(0.,P12) C(0.,P12) C(0.,N) + C(0.,-P12) C(N,N) C(N,N) C(N,N) C(N,N) C(0.,P12) C(N,N) + }) + + INIT_SPECIAL_VALUES(cosh_special_values, { + C(INF,N) C(U,U) C(INF,0.) C(INF,-0.) C(U,U) C(INF,N) C(INF,N) + C(N,N) C(U,U) C(U,U) C(U,U) C(U,U) C(N,N) C(N,N) + C(N,0.) C(U,U) C(1.,0.) C(1.,-0.) C(U,U) C(N,0.) C(N,0.) + C(N,0.) C(U,U) C(1.,-0.) C(1.,0.) C(U,U) C(N,0.) C(N,0.) + C(N,N) C(U,U) C(U,U) C(U,U) C(U,U) C(N,N) C(N,N) + C(INF,N) C(U,U) C(INF,-0.) C(INF,0.) C(U,U) C(INF,N) C(INF,N) + C(N,N) C(N,N) C(N,0.) C(N,0.) C(N,N) C(N,N) C(N,N) + }) + + INIT_SPECIAL_VALUES(exp_special_values, { + C(0.,0.) C(U,U) C(0.,-0.) C(0.,0.) C(U,U) C(0.,0.) C(0.,0.) + C(N,N) C(U,U) C(U,U) C(U,U) C(U,U) C(N,N) C(N,N) + C(N,N) C(U,U) C(1.,-0.) C(1.,0.) C(U,U) C(N,N) C(N,N) + C(N,N) C(U,U) C(1.,-0.) C(1.,0.) C(U,U) C(N,N) C(N,N) + C(N,N) C(U,U) C(U,U) C(U,U) C(U,U) C(N,N) C(N,N) + C(INF,N) C(U,U) C(INF,-0.) C(INF,0.) C(U,U) C(INF,N) C(INF,N) + C(N,N) C(N,N) C(N,-0.) C(N,0.) C(N,N) C(N,N) C(N,N) + }) + + INIT_SPECIAL_VALUES(log_special_values, { + C(INF,-P34) C(INF,-P) C(INF,-P) C(INF,P) C(INF,P) C(INF,P34) C(INF,N) + C(INF,-P12) C(U,U) C(U,U) C(U,U) C(U,U) C(INF,P12) C(N,N) + C(INF,-P12) C(U,U) C(-INF,-P) C(-INF,P) C(U,U) C(INF,P12) C(N,N) + C(INF,-P12) C(U,U) C(-INF,-0.) C(-INF,0.) C(U,U) C(INF,P12) C(N,N) + C(INF,-P12) C(U,U) C(U,U) C(U,U) C(U,U) C(INF,P12) C(N,N) + C(INF,-P14) C(INF,-0.) C(INF,-0.) C(INF,0.) C(INF,0.) C(INF,P14) C(INF,N) + C(INF,N) C(N,N) C(N,N) C(N,N) C(N,N) C(INF,N) C(N,N) + }) + + INIT_SPECIAL_VALUES(sinh_special_values, { + C(INF,N) C(U,U) C(-INF,-0.) C(-INF,0.) C(U,U) C(INF,N) C(INF,N) + C(N,N) C(U,U) C(U,U) C(U,U) C(U,U) C(N,N) C(N,N) + C(0.,N) C(U,U) C(-0.,-0.) C(-0.,0.) C(U,U) C(0.,N) C(0.,N) + C(0.,N) C(U,U) C(0.,-0.) C(0.,0.) C(U,U) C(0.,N) C(0.,N) + C(N,N) C(U,U) C(U,U) C(U,U) C(U,U) C(N,N) C(N,N) + C(INF,N) C(U,U) C(INF,-0.) C(INF,0.) C(U,U) C(INF,N) C(INF,N) + C(N,N) C(N,N) C(N,-0.) C(N,0.) C(N,N) C(N,N) C(N,N) + }) + + INIT_SPECIAL_VALUES(sqrt_special_values, { + C(INF,-INF) C(0.,-INF) C(0.,-INF) C(0.,INF) C(0.,INF) C(INF,INF) C(N,INF) + C(INF,-INF) C(U,U) C(U,U) C(U,U) C(U,U) C(INF,INF) C(N,N) + C(INF,-INF) C(U,U) C(0.,-0.) C(0.,0.) C(U,U) C(INF,INF) C(N,N) + C(INF,-INF) C(U,U) C(0.,-0.) C(0.,0.) C(U,U) C(INF,INF) C(N,N) + C(INF,-INF) C(U,U) C(U,U) C(U,U) C(U,U) C(INF,INF) C(N,N) + C(INF,-INF) C(INF,-0.) C(INF,-0.) C(INF,0.) C(INF,0.) C(INF,INF) C(INF,N) + C(INF,-INF) C(N,N) C(N,N) C(N,N) C(N,N) C(INF,INF) C(N,N) + }) + + INIT_SPECIAL_VALUES(tanh_special_values, { + C(-1.,0.) C(U,U) C(-1.,-0.) C(-1.,0.) C(U,U) C(-1.,0.) C(-1.,0.) + C(N,N) C(U,U) C(U,U) C(U,U) C(U,U) C(N,N) C(N,N) + C(N,N) C(U,U) C(-0.,-0.) C(-0.,0.) C(U,U) C(N,N) C(N,N) + C(N,N) C(U,U) C(0.,-0.) C(0.,0.) C(U,U) C(N,N) C(N,N) + C(N,N) C(U,U) C(U,U) C(U,U) C(U,U) C(N,N) C(N,N) + C(1.,0.) C(U,U) C(1.,-0.) C(1.,0.) C(U,U) C(1.,0.) C(1.,0.) + C(N,N) C(N,N) C(N,-0.) C(N,0.) C(N,N) C(N,N) C(N,N) + }) + + INIT_SPECIAL_VALUES(rect_special_values, { + C(INF,N) C(U,U) C(-INF,0.) C(-INF,-0.) C(U,U) C(INF,N) C(INF,N) + C(N,N) C(U,U) C(U,U) C(U,U) C(U,U) C(N,N) C(N,N) + C(0.,0.) C(U,U) C(-0.,0.) C(-0.,-0.) C(U,U) C(0.,0.) C(0.,0.) + C(0.,0.) C(U,U) C(0.,-0.) C(0.,0.) C(U,U) C(0.,0.) C(0.,0.) + C(N,N) C(U,U) C(U,U) C(U,U) C(U,U) C(N,N) C(N,N) + C(INF,N) C(U,U) C(INF,-0.) C(INF,0.) C(U,U) C(INF,N) C(INF,N) + C(N,N) C(N,N) C(N,0.) C(N,0.) C(N,N) C(N,N) C(N,N) + }) + return m; } Modified: python/branches/release31-maint/Modules/cryptmodule.c ============================================================================== --- python/branches/release31-maint/Modules/cryptmodule.c (original) +++ python/branches/release31-maint/Modules/cryptmodule.c Sun May 9 18:14:21 2010 @@ -14,17 +14,17 @@ static PyObject *crypt_crypt(PyObject *self, PyObject *args) { - char *word, *salt; + char *word, *salt; #ifndef __VMS - extern char * crypt(const char *, const char *); + extern char * crypt(const char *, const char *); #endif - if (!PyArg_ParseTuple(args, "ss:crypt", &word, &salt)) { - return NULL; - } - /* On some platforms (AtheOS) crypt returns NULL for an invalid - salt. Return None in that case. XXX Maybe raise an exception? */ - return Py_BuildValue("s", crypt(word, salt)); + if (!PyArg_ParseTuple(args, "ss:crypt", &word, &salt)) { + return NULL; + } + /* On some platforms (AtheOS) crypt returns NULL for an invalid + salt. Return None in that case. XXX Maybe raise an exception? */ + return Py_BuildValue("s", crypt(word, salt)); } @@ -38,25 +38,25 @@ static PyMethodDef crypt_methods[] = { - {"crypt", crypt_crypt, METH_VARARGS, crypt_crypt__doc__}, - {NULL, NULL} /* sentinel */ + {"crypt", crypt_crypt, METH_VARARGS, crypt_crypt__doc__}, + {NULL, NULL} /* sentinel */ }; static struct PyModuleDef cryptmodule = { - PyModuleDef_HEAD_INIT, - "crypt", - NULL, - -1, - crypt_methods, - NULL, - NULL, - NULL, - NULL + PyModuleDef_HEAD_INIT, + "crypt", + NULL, + -1, + crypt_methods, + NULL, + NULL, + NULL, + NULL }; PyMODINIT_FUNC PyInit_crypt(void) { - return PyModule_Create(&cryptmodule); + return PyModule_Create(&cryptmodule); } Modified: python/branches/release31-maint/Modules/datetimemodule.c ============================================================================== --- python/branches/release31-maint/Modules/datetimemodule.c (original) +++ python/branches/release31-maint/Modules/datetimemodule.c Sun May 9 18:14:21 2010 @@ -25,7 +25,7 @@ * final result fits in a C int (this can be an issue on 64-bit boxes). */ #if SIZEOF_INT < 4 -# error "datetime.c requires that C int have at least 32 bits" +# error "datetime.c requires that C int have at least 32 bits" #endif #define MINYEAR 1 @@ -39,59 +39,59 @@ #define MAX_DELTA_DAYS 999999999 /* Rename the long macros in datetime.h to more reasonable short names. */ -#define GET_YEAR PyDateTime_GET_YEAR -#define GET_MONTH PyDateTime_GET_MONTH -#define GET_DAY PyDateTime_GET_DAY -#define DATE_GET_HOUR PyDateTime_DATE_GET_HOUR -#define DATE_GET_MINUTE PyDateTime_DATE_GET_MINUTE -#define DATE_GET_SECOND PyDateTime_DATE_GET_SECOND -#define DATE_GET_MICROSECOND PyDateTime_DATE_GET_MICROSECOND +#define GET_YEAR PyDateTime_GET_YEAR +#define GET_MONTH PyDateTime_GET_MONTH +#define GET_DAY PyDateTime_GET_DAY +#define DATE_GET_HOUR PyDateTime_DATE_GET_HOUR +#define DATE_GET_MINUTE PyDateTime_DATE_GET_MINUTE +#define DATE_GET_SECOND PyDateTime_DATE_GET_SECOND +#define DATE_GET_MICROSECOND PyDateTime_DATE_GET_MICROSECOND /* Date accessors for date and datetime. */ -#define SET_YEAR(o, v) (((o)->data[0] = ((v) & 0xff00) >> 8), \ - ((o)->data[1] = ((v) & 0x00ff))) -#define SET_MONTH(o, v) (PyDateTime_GET_MONTH(o) = (v)) -#define SET_DAY(o, v) (PyDateTime_GET_DAY(o) = (v)) +#define SET_YEAR(o, v) (((o)->data[0] = ((v) & 0xff00) >> 8), \ + ((o)->data[1] = ((v) & 0x00ff))) +#define SET_MONTH(o, v) (PyDateTime_GET_MONTH(o) = (v)) +#define SET_DAY(o, v) (PyDateTime_GET_DAY(o) = (v)) /* Date/Time accessors for datetime. */ -#define DATE_SET_HOUR(o, v) (PyDateTime_DATE_GET_HOUR(o) = (v)) -#define DATE_SET_MINUTE(o, v) (PyDateTime_DATE_GET_MINUTE(o) = (v)) -#define DATE_SET_SECOND(o, v) (PyDateTime_DATE_GET_SECOND(o) = (v)) -#define DATE_SET_MICROSECOND(o, v) \ - (((o)->data[7] = ((v) & 0xff0000) >> 16), \ - ((o)->data[8] = ((v) & 0x00ff00) >> 8), \ - ((o)->data[9] = ((v) & 0x0000ff))) +#define DATE_SET_HOUR(o, v) (PyDateTime_DATE_GET_HOUR(o) = (v)) +#define DATE_SET_MINUTE(o, v) (PyDateTime_DATE_GET_MINUTE(o) = (v)) +#define DATE_SET_SECOND(o, v) (PyDateTime_DATE_GET_SECOND(o) = (v)) +#define DATE_SET_MICROSECOND(o, v) \ + (((o)->data[7] = ((v) & 0xff0000) >> 16), \ + ((o)->data[8] = ((v) & 0x00ff00) >> 8), \ + ((o)->data[9] = ((v) & 0x0000ff))) /* Time accessors for time. */ -#define TIME_GET_HOUR PyDateTime_TIME_GET_HOUR -#define TIME_GET_MINUTE PyDateTime_TIME_GET_MINUTE -#define TIME_GET_SECOND PyDateTime_TIME_GET_SECOND -#define TIME_GET_MICROSECOND PyDateTime_TIME_GET_MICROSECOND -#define TIME_SET_HOUR(o, v) (PyDateTime_TIME_GET_HOUR(o) = (v)) -#define TIME_SET_MINUTE(o, v) (PyDateTime_TIME_GET_MINUTE(o) = (v)) -#define TIME_SET_SECOND(o, v) (PyDateTime_TIME_GET_SECOND(o) = (v)) -#define TIME_SET_MICROSECOND(o, v) \ - (((o)->data[3] = ((v) & 0xff0000) >> 16), \ - ((o)->data[4] = ((v) & 0x00ff00) >> 8), \ - ((o)->data[5] = ((v) & 0x0000ff))) +#define TIME_GET_HOUR PyDateTime_TIME_GET_HOUR +#define TIME_GET_MINUTE PyDateTime_TIME_GET_MINUTE +#define TIME_GET_SECOND PyDateTime_TIME_GET_SECOND +#define TIME_GET_MICROSECOND PyDateTime_TIME_GET_MICROSECOND +#define TIME_SET_HOUR(o, v) (PyDateTime_TIME_GET_HOUR(o) = (v)) +#define TIME_SET_MINUTE(o, v) (PyDateTime_TIME_GET_MINUTE(o) = (v)) +#define TIME_SET_SECOND(o, v) (PyDateTime_TIME_GET_SECOND(o) = (v)) +#define TIME_SET_MICROSECOND(o, v) \ + (((o)->data[3] = ((v) & 0xff0000) >> 16), \ + ((o)->data[4] = ((v) & 0x00ff00) >> 8), \ + ((o)->data[5] = ((v) & 0x0000ff))) /* Delta accessors for timedelta. */ -#define GET_TD_DAYS(o) (((PyDateTime_Delta *)(o))->days) -#define GET_TD_SECONDS(o) (((PyDateTime_Delta *)(o))->seconds) -#define GET_TD_MICROSECONDS(o) (((PyDateTime_Delta *)(o))->microseconds) +#define GET_TD_DAYS(o) (((PyDateTime_Delta *)(o))->days) +#define GET_TD_SECONDS(o) (((PyDateTime_Delta *)(o))->seconds) +#define GET_TD_MICROSECONDS(o) (((PyDateTime_Delta *)(o))->microseconds) -#define SET_TD_DAYS(o, v) ((o)->days = (v)) -#define SET_TD_SECONDS(o, v) ((o)->seconds = (v)) +#define SET_TD_DAYS(o, v) ((o)->days = (v)) +#define SET_TD_SECONDS(o, v) ((o)->seconds = (v)) #define SET_TD_MICROSECONDS(o, v) ((o)->microseconds = (v)) /* p is a pointer to a time or a datetime object; HASTZINFO(p) returns * p->hastzinfo. */ -#define HASTZINFO(p) (((_PyDateTime_BaseTZInfo *)(p))->hastzinfo) +#define HASTZINFO(p) (((_PyDateTime_BaseTZInfo *)(p))->hastzinfo) /* M is a char or int claiming to be a valid month. The macro is equivalent * to the two-sided Python test - * 1 <= M <= 12 + * 1 <= M <= 12 */ #define MONTH_IS_SANE(M) ((unsigned int)(M) - 1 < 12) @@ -111,7 +111,7 @@ * iff (k^i)&(k^j) has sign bit set. */ #define SIGNED_ADD_OVERFLOWED(RESULT, I, J) \ - ((((RESULT) ^ (I)) & ((RESULT) ^ (J))) < 0) + ((((RESULT) ^ (I)) & ((RESULT) ^ (J))) < 0) /* Compute Python divmod(x, y), returning the quotient and storing the * remainder into *r. The quotient is the floor of x/y, and that's @@ -125,17 +125,17 @@ static int divmod(int x, int y, int *r) { - int quo; + int quo; - assert(y > 0); - quo = x / y; - *r = x - quo * y; - if (*r < 0) { - --quo; - *r += y; - } - assert(0 <= *r && *r < y); - return quo; + assert(y > 0); + quo = x / y; + *r = x - quo * y; + if (*r < 0) { + --quo; + *r += y; + } + assert(0 <= *r && *r < y); + return quo; } /* Round a double to the nearest long. |x| must be small enough to fit @@ -144,11 +144,11 @@ static long round_to_long(double x) { - if (x >= 0.0) - x = floor(x + 0.5); - else - x = ceil(x - 0.5); - return (long)x; + if (x >= 0.0) + x = floor(x + 0.5); + else + x = ceil(x - 0.5); + return (long)x; } /* --------------------------------------------------------------------------- @@ -160,52 +160,52 @@ * are correct for non-leap years only. */ static int _days_in_month[] = { - 0, /* unused; this vector uses 1-based indexing */ - 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 + 0, /* unused; this vector uses 1-based indexing */ + 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 }; static int _days_before_month[] = { - 0, /* unused; this vector uses 1-based indexing */ - 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334 + 0, /* unused; this vector uses 1-based indexing */ + 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334 }; /* year -> 1 if leap year, else 0. */ static int is_leap(int year) { - /* Cast year to unsigned. The result is the same either way, but - * C can generate faster code for unsigned mod than for signed - * mod (especially for % 4 -- a good compiler should just grab - * the last 2 bits when the LHS is unsigned). - */ - const unsigned int ayear = (unsigned int)year; - return ayear % 4 == 0 && (ayear % 100 != 0 || ayear % 400 == 0); + /* Cast year to unsigned. The result is the same either way, but + * C can generate faster code for unsigned mod than for signed + * mod (especially for % 4 -- a good compiler should just grab + * the last 2 bits when the LHS is unsigned). + */ + const unsigned int ayear = (unsigned int)year; + return ayear % 4 == 0 && (ayear % 100 != 0 || ayear % 400 == 0); } /* year, month -> number of days in that month in that year */ static int days_in_month(int year, int month) { - assert(month >= 1); - assert(month <= 12); - if (month == 2 && is_leap(year)) - return 29; - else - return _days_in_month[month]; + assert(month >= 1); + assert(month <= 12); + if (month == 2 && is_leap(year)) + return 29; + else + return _days_in_month[month]; } /* year, month -> number of days in year preceeding first day of month */ static int days_before_month(int year, int month) { - int days; + int days; - assert(month >= 1); - assert(month <= 12); - days = _days_before_month[month]; - if (month > 2 && is_leap(year)) - ++days; - return days; + assert(month >= 1); + assert(month <= 12); + days = _days_before_month[month]; + if (month > 2 && is_leap(year)) + ++days; + return days; } /* year -> number of days before January 1st of year. Remember that we @@ -214,124 +214,124 @@ static int days_before_year(int year) { - int y = year - 1; - /* This is incorrect if year <= 0; we really want the floor - * here. But so long as MINYEAR is 1, the smallest year this - * can see is 0 (this can happen in some normalization endcases), - * so we'll just special-case that. - */ - assert (year >= 0); - if (y >= 0) - return y*365 + y/4 - y/100 + y/400; - else { - assert(y == -1); - return -366; - } + int y = year - 1; + /* This is incorrect if year <= 0; we really want the floor + * here. But so long as MINYEAR is 1, the smallest year this + * can see is 0 (this can happen in some normalization endcases), + * so we'll just special-case that. + */ + assert (year >= 0); + if (y >= 0) + return y*365 + y/4 - y/100 + y/400; + else { + assert(y == -1); + return -366; + } } /* Number of days in 4, 100, and 400 year cycles. That these have * the correct values is asserted in the module init function. */ -#define DI4Y 1461 /* days_before_year(5); days in 4 years */ -#define DI100Y 36524 /* days_before_year(101); days in 100 years */ -#define DI400Y 146097 /* days_before_year(401); days in 400 years */ +#define DI4Y 1461 /* days_before_year(5); days in 4 years */ +#define DI100Y 36524 /* days_before_year(101); days in 100 years */ +#define DI400Y 146097 /* days_before_year(401); days in 400 years */ /* ordinal -> year, month, day, considering 01-Jan-0001 as day 1. */ static void ord_to_ymd(int ordinal, int *year, int *month, int *day) { - int n, n1, n4, n100, n400, leapyear, preceding; + int n, n1, n4, n100, n400, leapyear, preceding; - /* ordinal is a 1-based index, starting at 1-Jan-1. The pattern of - * leap years repeats exactly every 400 years. The basic strategy is - * to find the closest 400-year boundary at or before ordinal, then - * work with the offset from that boundary to ordinal. Life is much - * clearer if we subtract 1 from ordinal first -- then the values - * of ordinal at 400-year boundaries are exactly those divisible - * by DI400Y: - * - * D M Y n n-1 - * -- --- ---- ---------- ---------------- - * 31 Dec -400 -DI400Y -DI400Y -1 - * 1 Jan -399 -DI400Y +1 -DI400Y 400-year boundary - * ... - * 30 Dec 000 -1 -2 - * 31 Dec 000 0 -1 - * 1 Jan 001 1 0 400-year boundary - * 2 Jan 001 2 1 - * 3 Jan 001 3 2 - * ... - * 31 Dec 400 DI400Y DI400Y -1 - * 1 Jan 401 DI400Y +1 DI400Y 400-year boundary - */ - assert(ordinal >= 1); - --ordinal; - n400 = ordinal / DI400Y; - n = ordinal % DI400Y; - *year = n400 * 400 + 1; - - /* Now n is the (non-negative) offset, in days, from January 1 of - * year, to the desired date. Now compute how many 100-year cycles - * precede n. - * Note that it's possible for n100 to equal 4! In that case 4 full - * 100-year cycles precede the desired day, which implies the - * desired day is December 31 at the end of a 400-year cycle. - */ - n100 = n / DI100Y; - n = n % DI100Y; - - /* Now compute how many 4-year cycles precede it. */ - n4 = n / DI4Y; - n = n % DI4Y; - - /* And now how many single years. Again n1 can be 4, and again - * meaning that the desired day is December 31 at the end of the - * 4-year cycle. - */ - n1 = n / 365; - n = n % 365; - - *year += n100 * 100 + n4 * 4 + n1; - if (n1 == 4 || n100 == 4) { - assert(n == 0); - *year -= 1; - *month = 12; - *day = 31; - return; - } - - /* Now the year is correct, and n is the offset from January 1. We - * find the month via an estimate that's either exact or one too - * large. - */ - leapyear = n1 == 3 && (n4 != 24 || n100 == 3); - assert(leapyear == is_leap(*year)); - *month = (n + 50) >> 5; - preceding = (_days_before_month[*month] + (*month > 2 && leapyear)); - if (preceding > n) { - /* estimate is too large */ - *month -= 1; - preceding -= days_in_month(*year, *month); - } - n -= preceding; - assert(0 <= n); - assert(n < days_in_month(*year, *month)); + /* ordinal is a 1-based index, starting at 1-Jan-1. The pattern of + * leap years repeats exactly every 400 years. The basic strategy is + * to find the closest 400-year boundary at or before ordinal, then + * work with the offset from that boundary to ordinal. Life is much + * clearer if we subtract 1 from ordinal first -- then the values + * of ordinal at 400-year boundaries are exactly those divisible + * by DI400Y: + * + * D M Y n n-1 + * -- --- ---- ---------- ---------------- + * 31 Dec -400 -DI400Y -DI400Y -1 + * 1 Jan -399 -DI400Y +1 -DI400Y 400-year boundary + * ... + * 30 Dec 000 -1 -2 + * 31 Dec 000 0 -1 + * 1 Jan 001 1 0 400-year boundary + * 2 Jan 001 2 1 + * 3 Jan 001 3 2 + * ... + * 31 Dec 400 DI400Y DI400Y -1 + * 1 Jan 401 DI400Y +1 DI400Y 400-year boundary + */ + assert(ordinal >= 1); + --ordinal; + n400 = ordinal / DI400Y; + n = ordinal % DI400Y; + *year = n400 * 400 + 1; + + /* Now n is the (non-negative) offset, in days, from January 1 of + * year, to the desired date. Now compute how many 100-year cycles + * precede n. + * Note that it's possible for n100 to equal 4! In that case 4 full + * 100-year cycles precede the desired day, which implies the + * desired day is December 31 at the end of a 400-year cycle. + */ + n100 = n / DI100Y; + n = n % DI100Y; + + /* Now compute how many 4-year cycles precede it. */ + n4 = n / DI4Y; + n = n % DI4Y; + + /* And now how many single years. Again n1 can be 4, and again + * meaning that the desired day is December 31 at the end of the + * 4-year cycle. + */ + n1 = n / 365; + n = n % 365; + + *year += n100 * 100 + n4 * 4 + n1; + if (n1 == 4 || n100 == 4) { + assert(n == 0); + *year -= 1; + *month = 12; + *day = 31; + return; + } + + /* Now the year is correct, and n is the offset from January 1. We + * find the month via an estimate that's either exact or one too + * large. + */ + leapyear = n1 == 3 && (n4 != 24 || n100 == 3); + assert(leapyear == is_leap(*year)); + *month = (n + 50) >> 5; + preceding = (_days_before_month[*month] + (*month > 2 && leapyear)); + if (preceding > n) { + /* estimate is too large */ + *month -= 1; + preceding -= days_in_month(*year, *month); + } + n -= preceding; + assert(0 <= n); + assert(n < days_in_month(*year, *month)); - *day = n + 1; + *day = n + 1; } /* year, month, day -> ordinal, considering 01-Jan-0001 as day 1. */ static int ymd_to_ord(int year, int month, int day) { - return days_before_year(year) + days_before_month(year, month) + day; + return days_before_year(year) + days_before_month(year, month) + day; } /* Day of week, where Monday==0, ..., Sunday==6. 1/1/1 was a Monday. */ static int weekday(int year, int month, int day) { - return (ymd_to_ord(year, month, day) + 6) % 7; + return (ymd_to_ord(year, month, day) + 6) % 7; } /* Ordinal of the Monday starting week 1 of the ISO year. Week 1 is the @@ -340,15 +340,15 @@ static int iso_week1_monday(int year) { - int first_day = ymd_to_ord(year, 1, 1); /* ord of 1/1 */ - /* 0 if 1/1 is a Monday, 1 if a Tue, etc. */ - int first_weekday = (first_day + 6) % 7; - /* ordinal of closest Monday at or before 1/1 */ - int week1_monday = first_day - first_weekday; - - if (first_weekday > 3) /* if 1/1 was Fri, Sat, Sun */ - week1_monday += 7; - return week1_monday; + int first_day = ymd_to_ord(year, 1, 1); /* ord of 1/1 */ + /* 0 if 1/1 is a Monday, 1 if a Tue, etc. */ + int first_weekday = (first_day + 6) % 7; + /* ordinal of closest Monday at or before 1/1 */ + int week1_monday = first_day - first_weekday; + + if (first_weekday > 3) /* if 1/1 was Fri, Sat, Sun */ + week1_monday += 7; + return week1_monday; } /* --------------------------------------------------------------------------- @@ -361,12 +361,12 @@ static int check_delta_day_range(int days) { - if (-MAX_DELTA_DAYS <= days && days <= MAX_DELTA_DAYS) - return 0; - PyErr_Format(PyExc_OverflowError, - "days=%d; must have magnitude <= %d", - days, MAX_DELTA_DAYS); - return -1; + if (-MAX_DELTA_DAYS <= days && days <= MAX_DELTA_DAYS) + return 0; + PyErr_Format(PyExc_OverflowError, + "days=%d; must have magnitude <= %d", + days, MAX_DELTA_DAYS); + return -1; } /* Check that date arguments are in range. Return 0 if they are. If they @@ -376,22 +376,22 @@ check_date_args(int year, int month, int day) { - if (year < MINYEAR || year > MAXYEAR) { - PyErr_SetString(PyExc_ValueError, - "year is out of range"); - return -1; - } - if (month < 1 || month > 12) { - PyErr_SetString(PyExc_ValueError, - "month must be in 1..12"); - return -1; - } - if (day < 1 || day > days_in_month(year, month)) { - PyErr_SetString(PyExc_ValueError, - "day is out of range for month"); - return -1; - } - return 0; + if (year < MINYEAR || year > MAXYEAR) { + PyErr_SetString(PyExc_ValueError, + "year is out of range"); + return -1; + } + if (month < 1 || month > 12) { + PyErr_SetString(PyExc_ValueError, + "month must be in 1..12"); + return -1; + } + if (day < 1 || day > days_in_month(year, month)) { + PyErr_SetString(PyExc_ValueError, + "day is out of range for month"); + return -1; + } + return 0; } /* Check that time arguments are in range. Return 0 if they are. If they @@ -400,27 +400,27 @@ static int check_time_args(int h, int m, int s, int us) { - if (h < 0 || h > 23) { - PyErr_SetString(PyExc_ValueError, - "hour must be in 0..23"); - return -1; - } - if (m < 0 || m > 59) { - PyErr_SetString(PyExc_ValueError, - "minute must be in 0..59"); - return -1; - } - if (s < 0 || s > 59) { - PyErr_SetString(PyExc_ValueError, - "second must be in 0..59"); - return -1; - } - if (us < 0 || us > 999999) { - PyErr_SetString(PyExc_ValueError, - "microsecond must be in 0..999999"); - return -1; - } - return 0; + if (h < 0 || h > 23) { + PyErr_SetString(PyExc_ValueError, + "hour must be in 0..23"); + return -1; + } + if (m < 0 || m > 59) { + PyErr_SetString(PyExc_ValueError, + "minute must be in 0..59"); + return -1; + } + if (s < 0 || s > 59) { + PyErr_SetString(PyExc_ValueError, + "second must be in 0..59"); + return -1; + } + if (us < 0 || us > 999999) { + PyErr_SetString(PyExc_ValueError, + "microsecond must be in 0..999999"); + return -1; + } + return 0; } /* --------------------------------------------------------------------------- @@ -436,109 +436,109 @@ static void normalize_pair(int *hi, int *lo, int factor) { - assert(factor > 0); - assert(lo != hi); - if (*lo < 0 || *lo >= factor) { - const int num_hi = divmod(*lo, factor, lo); - const int new_hi = *hi + num_hi; - assert(! SIGNED_ADD_OVERFLOWED(new_hi, *hi, num_hi)); - *hi = new_hi; - } - assert(0 <= *lo && *lo < factor); + assert(factor > 0); + assert(lo != hi); + if (*lo < 0 || *lo >= factor) { + const int num_hi = divmod(*lo, factor, lo); + const int new_hi = *hi + num_hi; + assert(! SIGNED_ADD_OVERFLOWED(new_hi, *hi, num_hi)); + *hi = new_hi; + } + assert(0 <= *lo && *lo < factor); } /* Fiddle days (d), seconds (s), and microseconds (us) so that - * 0 <= *s < 24*3600 - * 0 <= *us < 1000000 + * 0 <= *s < 24*3600 + * 0 <= *us < 1000000 * The input values must be such that the internals don't overflow. * The way this routine is used, we don't get close. */ static void normalize_d_s_us(int *d, int *s, int *us) { - if (*us < 0 || *us >= 1000000) { - normalize_pair(s, us, 1000000); - /* |s| can't be bigger than about - * |original s| + |original us|/1000000 now. - */ - - } - if (*s < 0 || *s >= 24*3600) { - normalize_pair(d, s, 24*3600); - /* |d| can't be bigger than about - * |original d| + - * (|original s| + |original us|/1000000) / (24*3600) now. - */ - } - assert(0 <= *s && *s < 24*3600); - assert(0 <= *us && *us < 1000000); + if (*us < 0 || *us >= 1000000) { + normalize_pair(s, us, 1000000); + /* |s| can't be bigger than about + * |original s| + |original us|/1000000 now. + */ + + } + if (*s < 0 || *s >= 24*3600) { + normalize_pair(d, s, 24*3600); + /* |d| can't be bigger than about + * |original d| + + * (|original s| + |original us|/1000000) / (24*3600) now. + */ + } + assert(0 <= *s && *s < 24*3600); + assert(0 <= *us && *us < 1000000); } /* Fiddle years (y), months (m), and days (d) so that - * 1 <= *m <= 12 - * 1 <= *d <= days_in_month(*y, *m) + * 1 <= *m <= 12 + * 1 <= *d <= days_in_month(*y, *m) * The input values must be such that the internals don't overflow. * The way this routine is used, we don't get close. */ static void normalize_y_m_d(int *y, int *m, int *d) { - int dim; /* # of days in month */ + int dim; /* # of days in month */ - /* This gets muddy: the proper range for day can't be determined - * without knowing the correct month and year, but if day is, e.g., - * plus or minus a million, the current month and year values make - * no sense (and may also be out of bounds themselves). - * Saying 12 months == 1 year should be non-controversial. - */ - if (*m < 1 || *m > 12) { - --*m; - normalize_pair(y, m, 12); - ++*m; - /* |y| can't be bigger than about - * |original y| + |original m|/12 now. - */ - } - assert(1 <= *m && *m <= 12); - - /* Now only day can be out of bounds (year may also be out of bounds - * for a datetime object, but we don't care about that here). - * If day is out of bounds, what to do is arguable, but at least the - * method here is principled and explainable. - */ - dim = days_in_month(*y, *m); - if (*d < 1 || *d > dim) { - /* Move day-1 days from the first of the month. First try to - * get off cheap if we're only one day out of range - * (adjustments for timezone alone can't be worse than that). - */ - if (*d == 0) { - --*m; - if (*m > 0) - *d = days_in_month(*y, *m); - else { - --*y; - *m = 12; - *d = 31; - } - } - else if (*d == dim + 1) { - /* move forward a day */ - ++*m; - *d = 1; - if (*m > 12) { - *m = 1; - ++*y; - } - } - else { - int ordinal = ymd_to_ord(*y, *m, 1) + - *d - 1; - ord_to_ymd(ordinal, y, m, d); - } - } - assert(*m > 0); - assert(*d > 0); + /* This gets muddy: the proper range for day can't be determined + * without knowing the correct month and year, but if day is, e.g., + * plus or minus a million, the current month and year values make + * no sense (and may also be out of bounds themselves). + * Saying 12 months == 1 year should be non-controversial. + */ + if (*m < 1 || *m > 12) { + --*m; + normalize_pair(y, m, 12); + ++*m; + /* |y| can't be bigger than about + * |original y| + |original m|/12 now. + */ + } + assert(1 <= *m && *m <= 12); + + /* Now only day can be out of bounds (year may also be out of bounds + * for a datetime object, but we don't care about that here). + * If day is out of bounds, what to do is arguable, but at least the + * method here is principled and explainable. + */ + dim = days_in_month(*y, *m); + if (*d < 1 || *d > dim) { + /* Move day-1 days from the first of the month. First try to + * get off cheap if we're only one day out of range + * (adjustments for timezone alone can't be worse than that). + */ + if (*d == 0) { + --*m; + if (*m > 0) + *d = days_in_month(*y, *m); + else { + --*y; + *m = 12; + *d = 31; + } + } + else if (*d == dim + 1) { + /* move forward a day */ + ++*m; + *d = 1; + if (*m > 12) { + *m = 1; + ++*y; + } + } + else { + int ordinal = ymd_to_ord(*y, *m, 1) + + *d - 1; + ord_to_ymd(ordinal, y, m, d); + } + } + assert(*m > 0); + assert(*d > 0); } /* Fiddle out-of-bounds months and days so that the result makes some kind @@ -548,17 +548,17 @@ static int normalize_date(int *year, int *month, int *day) { - int result; + int result; - normalize_y_m_d(year, month, day); - if (MINYEAR <= *year && *year <= MAXYEAR) - result = 0; - else { - PyErr_SetString(PyExc_OverflowError, - "date value out of range"); - result = -1; - } - return result; + normalize_y_m_d(year, month, day); + if (MINYEAR <= *year && *year <= MAXYEAR) + result = 0; + else { + PyErr_SetString(PyExc_OverflowError, + "date value out of range"); + result = -1; + } + return result; } /* Force all the datetime fields into range. The parameters are both @@ -569,11 +569,11 @@ int *hour, int *minute, int *second, int *microsecond) { - normalize_pair(second, microsecond, 1000000); - normalize_pair(minute, second, 60); - normalize_pair(hour, minute, 60); - normalize_pair(day, hour, 24); - return normalize_date(year, month, day); + normalize_pair(second, microsecond, 1000000); + normalize_pair(minute, second, 60); + normalize_pair(hour, minute, 60); + normalize_pair(day, hour, 24); + return normalize_date(year, month, day); } /* --------------------------------------------------------------------------- @@ -600,31 +600,31 @@ static PyObject * time_alloc(PyTypeObject *type, Py_ssize_t aware) { - PyObject *self; + PyObject *self; - self = (PyObject *) - PyObject_MALLOC(aware ? - sizeof(PyDateTime_Time) : - sizeof(_PyDateTime_BaseTime)); - if (self == NULL) - return (PyObject *)PyErr_NoMemory(); - PyObject_INIT(self, type); - return self; + self = (PyObject *) + PyObject_MALLOC(aware ? + sizeof(PyDateTime_Time) : + sizeof(_PyDateTime_BaseTime)); + if (self == NULL) + return (PyObject *)PyErr_NoMemory(); + PyObject_INIT(self, type); + return self; } static PyObject * datetime_alloc(PyTypeObject *type, Py_ssize_t aware) { - PyObject *self; + PyObject *self; - self = (PyObject *) - PyObject_MALLOC(aware ? - sizeof(PyDateTime_DateTime) : - sizeof(_PyDateTime_BaseDateTime)); - if (self == NULL) - return (PyObject *)PyErr_NoMemory(); - PyObject_INIT(self, type); - return self; + self = (PyObject *) + PyObject_MALLOC(aware ? + sizeof(PyDateTime_DateTime) : + sizeof(_PyDateTime_BaseDateTime)); + if (self == NULL) + return (PyObject *)PyErr_NoMemory(); + PyObject_INIT(self, type); + return self; } /* --------------------------------------------------------------------------- @@ -636,10 +636,10 @@ static void set_date_fields(PyDateTime_Date *self, int y, int m, int d) { - self->hashcode = -1; - SET_YEAR(self, y); - SET_MONTH(self, m); - SET_DAY(self, d); + self->hashcode = -1; + SET_YEAR(self, y); + SET_MONTH(self, m); + SET_DAY(self, d); } /* --------------------------------------------------------------------------- @@ -650,71 +650,71 @@ static PyObject * new_date_ex(int year, int month, int day, PyTypeObject *type) { - PyDateTime_Date *self; + PyDateTime_Date *self; - self = (PyDateTime_Date *) (type->tp_alloc(type, 0)); - if (self != NULL) - set_date_fields(self, year, month, day); - return (PyObject *) self; + self = (PyDateTime_Date *) (type->tp_alloc(type, 0)); + if (self != NULL) + set_date_fields(self, year, month, day); + return (PyObject *) self; } #define new_date(year, month, day) \ - new_date_ex(year, month, day, &PyDateTime_DateType) + new_date_ex(year, month, day, &PyDateTime_DateType) /* Create a datetime instance with no range checking. */ static PyObject * new_datetime_ex(int year, int month, int day, int hour, int minute, - int second, int usecond, PyObject *tzinfo, PyTypeObject *type) + int second, int usecond, PyObject *tzinfo, PyTypeObject *type) { - PyDateTime_DateTime *self; - char aware = tzinfo != Py_None; + PyDateTime_DateTime *self; + char aware = tzinfo != Py_None; - self = (PyDateTime_DateTime *) (type->tp_alloc(type, aware)); - if (self != NULL) { - self->hastzinfo = aware; - set_date_fields((PyDateTime_Date *)self, year, month, day); - DATE_SET_HOUR(self, hour); - DATE_SET_MINUTE(self, minute); - DATE_SET_SECOND(self, second); - DATE_SET_MICROSECOND(self, usecond); - if (aware) { - Py_INCREF(tzinfo); - self->tzinfo = tzinfo; - } - } - return (PyObject *)self; -} - -#define new_datetime(y, m, d, hh, mm, ss, us, tzinfo) \ - new_datetime_ex(y, m, d, hh, mm, ss, us, tzinfo, \ - &PyDateTime_DateTimeType) + self = (PyDateTime_DateTime *) (type->tp_alloc(type, aware)); + if (self != NULL) { + self->hastzinfo = aware; + set_date_fields((PyDateTime_Date *)self, year, month, day); + DATE_SET_HOUR(self, hour); + DATE_SET_MINUTE(self, minute); + DATE_SET_SECOND(self, second); + DATE_SET_MICROSECOND(self, usecond); + if (aware) { + Py_INCREF(tzinfo); + self->tzinfo = tzinfo; + } + } + return (PyObject *)self; +} + +#define new_datetime(y, m, d, hh, mm, ss, us, tzinfo) \ + new_datetime_ex(y, m, d, hh, mm, ss, us, tzinfo, \ + &PyDateTime_DateTimeType) /* Create a time instance with no range checking. */ static PyObject * new_time_ex(int hour, int minute, int second, int usecond, - PyObject *tzinfo, PyTypeObject *type) + PyObject *tzinfo, PyTypeObject *type) { - PyDateTime_Time *self; - char aware = tzinfo != Py_None; + PyDateTime_Time *self; + char aware = tzinfo != Py_None; - self = (PyDateTime_Time *) (type->tp_alloc(type, aware)); - if (self != NULL) { - self->hastzinfo = aware; - self->hashcode = -1; - TIME_SET_HOUR(self, hour); - TIME_SET_MINUTE(self, minute); - TIME_SET_SECOND(self, second); - TIME_SET_MICROSECOND(self, usecond); - if (aware) { - Py_INCREF(tzinfo); - self->tzinfo = tzinfo; - } - } - return (PyObject *)self; + self = (PyDateTime_Time *) (type->tp_alloc(type, aware)); + if (self != NULL) { + self->hastzinfo = aware; + self->hashcode = -1; + TIME_SET_HOUR(self, hour); + TIME_SET_MINUTE(self, minute); + TIME_SET_SECOND(self, second); + TIME_SET_MICROSECOND(self, usecond); + if (aware) { + Py_INCREF(tzinfo); + self->tzinfo = tzinfo; + } + } + return (PyObject *)self; } -#define new_time(hh, mm, ss, us, tzinfo) \ - new_time_ex(hh, mm, ss, us, tzinfo, &PyDateTime_TimeType) +#define new_time(hh, mm, ss, us, tzinfo) \ + new_time_ex(hh, mm, ss, us, tzinfo, &PyDateTime_TimeType) /* Create a timedelta instance. Normalize the members iff normalize is * true. Passing false is a speed optimization, if you know for sure @@ -724,30 +724,30 @@ */ static PyObject * new_delta_ex(int days, int seconds, int microseconds, int normalize, - PyTypeObject *type) + PyTypeObject *type) { - PyDateTime_Delta *self; + PyDateTime_Delta *self; - if (normalize) - normalize_d_s_us(&days, &seconds, µseconds); - assert(0 <= seconds && seconds < 24*3600); - assert(0 <= microseconds && microseconds < 1000000); - - if (check_delta_day_range(days) < 0) - return NULL; - - self = (PyDateTime_Delta *) (type->tp_alloc(type, 0)); - if (self != NULL) { - self->hashcode = -1; - SET_TD_DAYS(self, days); - SET_TD_SECONDS(self, seconds); - SET_TD_MICROSECONDS(self, microseconds); - } - return (PyObject *) self; + if (normalize) + normalize_d_s_us(&days, &seconds, µseconds); + assert(0 <= seconds && seconds < 24*3600); + assert(0 <= microseconds && microseconds < 1000000); + + if (check_delta_day_range(days) < 0) + return NULL; + + self = (PyDateTime_Delta *) (type->tp_alloc(type, 0)); + if (self != NULL) { + self->hashcode = -1; + SET_TD_DAYS(self, days); + SET_TD_SECONDS(self, seconds); + SET_TD_MICROSECONDS(self, microseconds); + } + return (PyObject *) self; } -#define new_delta(d, s, us, normalize) \ - new_delta_ex(d, s, us, normalize, &PyDateTime_DeltaType) +#define new_delta(d, s, us, normalize) \ + new_delta_ex(d, s, us, normalize, &PyDateTime_DeltaType) /* --------------------------------------------------------------------------- * tzinfo helpers. @@ -759,13 +759,13 @@ static int check_tzinfo_subclass(PyObject *p) { - if (p == Py_None || PyTZInfo_Check(p)) - return 0; - PyErr_Format(PyExc_TypeError, - "tzinfo argument must be None or of a tzinfo subclass, " - "not type '%s'", - Py_TYPE(p)->tp_name); - return -1; + if (p == Py_None || PyTZInfo_Check(p)) + return 0; + PyErr_Format(PyExc_TypeError, + "tzinfo argument must be None or of a tzinfo subclass, " + "not type '%s'", + Py_TYPE(p)->tp_name); + return -1; } /* Return tzinfo.methname(tzinfoarg), without any checking of results. @@ -774,17 +774,17 @@ static PyObject * call_tzinfo_method(PyObject *tzinfo, char *methname, PyObject *tzinfoarg) { - PyObject *result; + PyObject *result; - assert(tzinfo && methname && tzinfoarg); - assert(check_tzinfo_subclass(tzinfo) >= 0); - if (tzinfo == Py_None) { - result = Py_None; - Py_INCREF(result); - } - else - result = PyObject_CallMethod(tzinfo, methname, "O", tzinfoarg); - return result; + assert(tzinfo && methname && tzinfoarg); + assert(check_tzinfo_subclass(tzinfo) >= 0); + if (tzinfo == Py_None) { + result = Py_None; + Py_INCREF(result); + } + else + result = PyObject_CallMethod(tzinfo, methname, "O", tzinfoarg); + return result; } /* If self has a tzinfo member, return a BORROWED reference to it. Else @@ -794,14 +794,14 @@ static PyObject * get_tzinfo_member(PyObject *self) { - PyObject *tzinfo = NULL; + PyObject *tzinfo = NULL; - if (PyDateTime_Check(self) && HASTZINFO(self)) - tzinfo = ((PyDateTime_DateTime *)self)->tzinfo; - else if (PyTime_Check(self) && HASTZINFO(self)) - tzinfo = ((PyDateTime_Time *)self)->tzinfo; + if (PyDateTime_Check(self) && HASTZINFO(self)) + tzinfo = ((PyDateTime_DateTime *)self)->tzinfo; + else if (PyTime_Check(self) && HASTZINFO(self)) + tzinfo = ((PyDateTime_Time *)self)->tzinfo; - return tzinfo; + return tzinfo; } /* Call getattr(tzinfo, name)(tzinfoarg), and extract an int from the @@ -814,59 +814,59 @@ */ static int call_utc_tzinfo_method(PyObject *tzinfo, char *name, PyObject *tzinfoarg, - int *none) + int *none) { - PyObject *u; - int result = -1; + PyObject *u; + int result = -1; - assert(tzinfo != NULL); - assert(PyTZInfo_Check(tzinfo)); - assert(tzinfoarg != NULL); - - *none = 0; - u = call_tzinfo_method(tzinfo, name, tzinfoarg); - if (u == NULL) - return -1; - - else if (u == Py_None) { - result = 0; - *none = 1; - } - else if (PyDelta_Check(u)) { - const int days = GET_TD_DAYS(u); - if (days < -1 || days > 0) - result = 24*60; /* trigger ValueError below */ - else { - /* next line can't overflow because we know days - * is -1 or 0 now - */ - int ss = days * 24 * 3600 + GET_TD_SECONDS(u); - result = divmod(ss, 60, &ss); - if (ss || GET_TD_MICROSECONDS(u)) { - PyErr_Format(PyExc_ValueError, - "tzinfo.%s() must return a " - "whole number of minutes", - name); - result = -1; - } - } - } - else { - PyErr_Format(PyExc_TypeError, - "tzinfo.%s() must return None or " - "timedelta, not '%s'", - name, Py_TYPE(u)->tp_name); - } - - Py_DECREF(u); - if (result < -1439 || result > 1439) { - PyErr_Format(PyExc_ValueError, - "tzinfo.%s() returned %d; must be in " - "-1439 .. 1439", - name, result); - result = -1; - } - return result; + assert(tzinfo != NULL); + assert(PyTZInfo_Check(tzinfo)); + assert(tzinfoarg != NULL); + + *none = 0; + u = call_tzinfo_method(tzinfo, name, tzinfoarg); + if (u == NULL) + return -1; + + else if (u == Py_None) { + result = 0; + *none = 1; + } + else if (PyDelta_Check(u)) { + const int days = GET_TD_DAYS(u); + if (days < -1 || days > 0) + result = 24*60; /* trigger ValueError below */ + else { + /* next line can't overflow because we know days + * is -1 or 0 now + */ + int ss = days * 24 * 3600 + GET_TD_SECONDS(u); + result = divmod(ss, 60, &ss); + if (ss || GET_TD_MICROSECONDS(u)) { + PyErr_Format(PyExc_ValueError, + "tzinfo.%s() must return a " + "whole number of minutes", + name); + result = -1; + } + } + } + else { + PyErr_Format(PyExc_TypeError, + "tzinfo.%s() must return None or " + "timedelta, not '%s'", + name, Py_TYPE(u)->tp_name); + } + + Py_DECREF(u); + if (result < -1439 || result > 1439) { + PyErr_Format(PyExc_ValueError, + "tzinfo.%s() returned %d; must be in " + "-1439 .. 1439", + name, result); + result = -1; + } + return result; } /* Call tzinfo.utcoffset(tzinfoarg), and extract an integer from the @@ -880,34 +880,34 @@ static int call_utcoffset(PyObject *tzinfo, PyObject *tzinfoarg, int *none) { - return call_utc_tzinfo_method(tzinfo, "utcoffset", tzinfoarg, none); + return call_utc_tzinfo_method(tzinfo, "utcoffset", tzinfoarg, none); } /* Call tzinfo.name(tzinfoarg), and return the offset as a timedelta or None. */ static PyObject * offset_as_timedelta(PyObject *tzinfo, char *name, PyObject *tzinfoarg) { - PyObject *result; + PyObject *result; - assert(tzinfo && name && tzinfoarg); - if (tzinfo == Py_None) { - result = Py_None; - Py_INCREF(result); - } - else { - int none; - int offset = call_utc_tzinfo_method(tzinfo, name, tzinfoarg, - &none); - if (offset < 0 && PyErr_Occurred()) - return NULL; - if (none) { - result = Py_None; - Py_INCREF(result); - } - else - result = new_delta(0, offset * 60, 0, 1); - } - return result; + assert(tzinfo && name && tzinfoarg); + if (tzinfo == Py_None) { + result = Py_None; + Py_INCREF(result); + } + else { + int none; + int offset = call_utc_tzinfo_method(tzinfo, name, tzinfoarg, + &none); + if (offset < 0 && PyErr_Occurred()) + return NULL; + if (none) { + result = Py_None; + Py_INCREF(result); + } + else + result = new_delta(0, offset * 60, 0, 1); + } + return result; } /* Call tzinfo.dst(tzinfoarg), and extract an integer from the @@ -921,7 +921,7 @@ static int call_dst(PyObject *tzinfo, PyObject *tzinfoarg, int *none) { - return call_utc_tzinfo_method(tzinfo, "dst", tzinfoarg, none); + return call_utc_tzinfo_method(tzinfo, "dst", tzinfoarg, none); } /* Call tzinfo.tzname(tzinfoarg), and return the result. tzinfo must be @@ -933,55 +933,55 @@ static PyObject * call_tzname(PyObject *tzinfo, PyObject *tzinfoarg) { - PyObject *result; + PyObject *result; - assert(tzinfo != NULL); - assert(check_tzinfo_subclass(tzinfo) >= 0); - assert(tzinfoarg != NULL); - - if (tzinfo == Py_None) { - result = Py_None; - Py_INCREF(result); - } - else - result = PyObject_CallMethod(tzinfo, "tzname", "O", tzinfoarg); - - if (result != NULL && result != Py_None) { - if (!PyUnicode_Check(result)) { - PyErr_Format(PyExc_TypeError, "tzinfo.tzname() must " - "return None or a string, not '%s'", - Py_TYPE(result)->tp_name); - Py_DECREF(result); - result = NULL; - } - else if (!PyUnicode_Check(result)) { - PyObject *temp = PyUnicode_FromObject(result); - Py_DECREF(result); - result = temp; - } - } - return result; + assert(tzinfo != NULL); + assert(check_tzinfo_subclass(tzinfo) >= 0); + assert(tzinfoarg != NULL); + + if (tzinfo == Py_None) { + result = Py_None; + Py_INCREF(result); + } + else + result = PyObject_CallMethod(tzinfo, "tzname", "O", tzinfoarg); + + if (result != NULL && result != Py_None) { + if (!PyUnicode_Check(result)) { + PyErr_Format(PyExc_TypeError, "tzinfo.tzname() must " + "return None or a string, not '%s'", + Py_TYPE(result)->tp_name); + Py_DECREF(result); + result = NULL; + } + else if (!PyUnicode_Check(result)) { + PyObject *temp = PyUnicode_FromObject(result); + Py_DECREF(result); + result = temp; + } + } + return result; } typedef enum { - /* an exception has been set; the caller should pass it on */ - OFFSET_ERROR, + /* an exception has been set; the caller should pass it on */ + OFFSET_ERROR, - /* type isn't date, datetime, or time subclass */ - OFFSET_UNKNOWN, + /* type isn't date, datetime, or time subclass */ + OFFSET_UNKNOWN, - /* date, - * datetime with !hastzinfo - * datetime with None tzinfo, - * datetime where utcoffset() returns None - * time with !hastzinfo - * time with None tzinfo, - * time where utcoffset() returns None - */ - OFFSET_NAIVE, + /* date, + * datetime with !hastzinfo + * datetime with None tzinfo, + * datetime where utcoffset() returns None + * time with !hastzinfo + * time with None tzinfo, + * time where utcoffset() returns None + */ + OFFSET_NAIVE, - /* time or datetime where utcoffset() doesn't return None */ - OFFSET_AWARE + /* time or datetime where utcoffset() doesn't return None */ + OFFSET_AWARE } naivety; /* Classify an object as to whether it's naive or offset-aware. See @@ -993,23 +993,23 @@ static naivety classify_utcoffset(PyObject *op, PyObject *tzinfoarg, int *offset) { - int none; - PyObject *tzinfo; + int none; + PyObject *tzinfo; - assert(tzinfoarg != NULL); - *offset = 0; - tzinfo = get_tzinfo_member(op); /* NULL means no tzinfo, not error */ - if (tzinfo == Py_None) - return OFFSET_NAIVE; - if (tzinfo == NULL) { - /* note that a datetime passes the PyDate_Check test */ - return (PyTime_Check(op) || PyDate_Check(op)) ? - OFFSET_NAIVE : OFFSET_UNKNOWN; - } - *offset = call_utcoffset(tzinfo, tzinfoarg, &none); - if (*offset == -1 && PyErr_Occurred()) - return OFFSET_ERROR; - return none ? OFFSET_NAIVE : OFFSET_AWARE; + assert(tzinfoarg != NULL); + *offset = 0; + tzinfo = get_tzinfo_member(op); /* NULL means no tzinfo, not error */ + if (tzinfo == Py_None) + return OFFSET_NAIVE; + if (tzinfo == NULL) { + /* note that a datetime passes the PyDate_Check test */ + return (PyTime_Check(op) || PyDate_Check(op)) ? + OFFSET_NAIVE : OFFSET_UNKNOWN; + } + *offset = call_utcoffset(tzinfo, tzinfoarg, &none); + if (*offset == -1 && PyErr_Occurred()) + return OFFSET_ERROR; + return none ? OFFSET_NAIVE : OFFSET_AWARE; } /* Classify two objects as to whether they're naive or offset-aware. @@ -1023,23 +1023,23 @@ */ static int classify_two_utcoffsets(PyObject *o1, int *offset1, naivety *n1, - PyObject *tzinfoarg1, - PyObject *o2, int *offset2, naivety *n2, - PyObject *tzinfoarg2) -{ - if (get_tzinfo_member(o1) == get_tzinfo_member(o2)) { - *offset1 = *offset2 = 0; - *n1 = *n2 = OFFSET_NAIVE; - } - else { - *n1 = classify_utcoffset(o1, tzinfoarg1, offset1); - if (*n1 == OFFSET_ERROR) - return -1; - *n2 = classify_utcoffset(o2, tzinfoarg2, offset2); - if (*n2 == OFFSET_ERROR) - return -1; - } - return 0; + PyObject *tzinfoarg1, + PyObject *o2, int *offset2, naivety *n2, + PyObject *tzinfoarg2) +{ + if (get_tzinfo_member(o1) == get_tzinfo_member(o2)) { + *offset1 = *offset2 = 0; + *n1 = *n2 = OFFSET_NAIVE; + } + else { + *n1 = classify_utcoffset(o1, tzinfoarg1, offset1); + if (*n1 == OFFSET_ERROR) + return -1; + *n2 = classify_utcoffset(o2, tzinfoarg2, offset2); + if (*n2 == OFFSET_ERROR) + return -1; + } + return 0; } /* repr is like "someclass(arg1, arg2)". If tzinfo isn't None, @@ -1050,22 +1050,22 @@ static PyObject * append_keyword_tzinfo(PyObject *repr, PyObject *tzinfo) { - PyObject *temp; + PyObject *temp; - assert(PyUnicode_Check(repr)); - assert(tzinfo); - if (tzinfo == Py_None) - return repr; - /* Get rid of the trailing ')'. */ - assert(PyUnicode_AS_UNICODE(repr)[PyUnicode_GET_SIZE(repr)-1] == ')'); - temp = PyUnicode_FromUnicode(PyUnicode_AS_UNICODE(repr), - PyUnicode_GET_SIZE(repr) - 1); - Py_DECREF(repr); - if (temp == NULL) - return NULL; - repr = PyUnicode_FromFormat("%U, tzinfo=%R)", temp, tzinfo); - Py_DECREF(temp); - return repr; + assert(PyUnicode_Check(repr)); + assert(tzinfo); + if (tzinfo == Py_None) + return repr; + /* Get rid of the trailing ')'. */ + assert(PyUnicode_AS_UNICODE(repr)[PyUnicode_GET_SIZE(repr)-1] == ')'); + temp = PyUnicode_FromUnicode(PyUnicode_AS_UNICODE(repr), + PyUnicode_GET_SIZE(repr) - 1); + Py_DECREF(repr); + if (temp == NULL) + return NULL; + repr = PyUnicode_FromFormat("%U, tzinfo=%R)", temp, tzinfo); + Py_DECREF(temp); + return repr; } /* --------------------------------------------------------------------------- @@ -1075,20 +1075,20 @@ static PyObject * format_ctime(PyDateTime_Date *date, int hours, int minutes, int seconds) { - static const char *DayNames[] = { - "Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun" - }; - static const char *MonthNames[] = { - "Jan", "Feb", "Mar", "Apr", "May", "Jun", - "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" - }; - - int wday = weekday(GET_YEAR(date), GET_MONTH(date), GET_DAY(date)); - - return PyUnicode_FromFormat("%s %s %2d %02d:%02d:%02d %04d", - DayNames[wday], MonthNames[GET_MONTH(date)-1], - GET_DAY(date), hours, minutes, seconds, - GET_YEAR(date)); + static const char *DayNames[] = { + "Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun" + }; + static const char *MonthNames[] = { + "Jan", "Feb", "Mar", "Apr", "May", "Jun", + "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" + }; + + int wday = weekday(GET_YEAR(date), GET_MONTH(date), GET_DAY(date)); + + return PyUnicode_FromFormat("%s %s %2d %02d:%02d:%02d %04d", + DayNames[wday], MonthNames[GET_MONTH(date)-1], + GET_DAY(date), hours, minutes, seconds, + GET_YEAR(date)); } /* Add an hours & minutes UTC offset string to buf. buf has no more than @@ -1103,87 +1103,87 @@ */ static int format_utcoffset(char *buf, size_t buflen, const char *sep, - PyObject *tzinfo, PyObject *tzinfoarg) + PyObject *tzinfo, PyObject *tzinfoarg) { - int offset; - int hours; - int minutes; - char sign; - int none; - - assert(buflen >= 1); - - offset = call_utcoffset(tzinfo, tzinfoarg, &none); - if (offset == -1 && PyErr_Occurred()) - return -1; - if (none) { - *buf = '\0'; - return 0; - } - sign = '+'; - if (offset < 0) { - sign = '-'; - offset = - offset; - } - hours = divmod(offset, 60, &minutes); - PyOS_snprintf(buf, buflen, "%c%02d%s%02d", sign, hours, sep, minutes); - return 0; + int offset; + int hours; + int minutes; + char sign; + int none; + + assert(buflen >= 1); + + offset = call_utcoffset(tzinfo, tzinfoarg, &none); + if (offset == -1 && PyErr_Occurred()) + return -1; + if (none) { + *buf = '\0'; + return 0; + } + sign = '+'; + if (offset < 0) { + sign = '-'; + offset = - offset; + } + hours = divmod(offset, 60, &minutes); + PyOS_snprintf(buf, buflen, "%c%02d%s%02d", sign, hours, sep, minutes); + return 0; } static PyObject * make_Zreplacement(PyObject *object, PyObject *tzinfoarg) { - PyObject *temp; - PyObject *tzinfo = get_tzinfo_member(object); - PyObject *Zreplacement = PyUnicode_FromStringAndSize(NULL, 0); - if (Zreplacement == NULL) - return NULL; - if (tzinfo == Py_None || tzinfo == NULL) - return Zreplacement; - - assert(tzinfoarg != NULL); - temp = call_tzname(tzinfo, tzinfoarg); - if (temp == NULL) - goto Error; - if (temp == Py_None) { - Py_DECREF(temp); - return Zreplacement; - } - - assert(PyUnicode_Check(temp)); - /* Since the tzname is getting stuffed into the - * format, we have to double any % signs so that - * strftime doesn't treat them as format codes. - */ - Py_DECREF(Zreplacement); - Zreplacement = PyObject_CallMethod(temp, "replace", "ss", "%", "%%"); - Py_DECREF(temp); - if (Zreplacement == NULL) - return NULL; - if (!PyUnicode_Check(Zreplacement)) { - PyErr_SetString(PyExc_TypeError, - "tzname.replace() did not return a string"); - goto Error; - } - return Zreplacement; + PyObject *temp; + PyObject *tzinfo = get_tzinfo_member(object); + PyObject *Zreplacement = PyUnicode_FromStringAndSize(NULL, 0); + if (Zreplacement == NULL) + return NULL; + if (tzinfo == Py_None || tzinfo == NULL) + return Zreplacement; + + assert(tzinfoarg != NULL); + temp = call_tzname(tzinfo, tzinfoarg); + if (temp == NULL) + goto Error; + if (temp == Py_None) { + Py_DECREF(temp); + return Zreplacement; + } + + assert(PyUnicode_Check(temp)); + /* Since the tzname is getting stuffed into the + * format, we have to double any % signs so that + * strftime doesn't treat them as format codes. + */ + Py_DECREF(Zreplacement); + Zreplacement = PyObject_CallMethod(temp, "replace", "ss", "%", "%%"); + Py_DECREF(temp); + if (Zreplacement == NULL) + return NULL; + if (!PyUnicode_Check(Zreplacement)) { + PyErr_SetString(PyExc_TypeError, + "tzname.replace() did not return a string"); + goto Error; + } + return Zreplacement; Error: - Py_DECREF(Zreplacement); - return NULL; + Py_DECREF(Zreplacement); + return NULL; } static PyObject * make_freplacement(PyObject *object) { - char freplacement[64]; - if (PyTime_Check(object)) - sprintf(freplacement, "%06d", TIME_GET_MICROSECOND(object)); - else if (PyDateTime_Check(object)) - sprintf(freplacement, "%06d", DATE_GET_MICROSECOND(object)); - else - sprintf(freplacement, "%06d", 0); + char freplacement[64]; + if (PyTime_Check(object)) + sprintf(freplacement, "%06d", TIME_GET_MICROSECOND(object)); + else if (PyDateTime_Check(object)) + sprintf(freplacement, "%06d", DATE_GET_MICROSECOND(object)); + else + sprintf(freplacement, "%06d", 0); - return PyBytes_FromStringAndSize(freplacement, strlen(freplacement)); + return PyBytes_FromStringAndSize(freplacement, strlen(freplacement)); } /* I sure don't want to reproduce the strftime code from the time module, @@ -1195,190 +1195,190 @@ */ static PyObject * wrap_strftime(PyObject *object, PyObject *format, PyObject *timetuple, - PyObject *tzinfoarg) + PyObject *tzinfoarg) { - PyObject *result = NULL; /* guilty until proved innocent */ + PyObject *result = NULL; /* guilty until proved innocent */ + + PyObject *zreplacement = NULL; /* py string, replacement for %z */ + PyObject *Zreplacement = NULL; /* py string, replacement for %Z */ + PyObject *freplacement = NULL; /* py string, replacement for %f */ + + const char *pin; /* pointer to next char in input format */ + Py_ssize_t flen; /* length of input format */ + char ch; /* next char in input format */ + + PyObject *newfmt = NULL; /* py string, the output format */ + char *pnew; /* pointer to available byte in output format */ + size_t totalnew; /* number bytes total in output format buffer, + exclusive of trailing \0 */ + size_t usednew; /* number bytes used so far in output format buffer */ + + const char *ptoappend; /* ptr to string to append to output buffer */ + Py_ssize_t ntoappend; /* # of bytes to append to output buffer */ + + assert(object && format && timetuple); + assert(PyUnicode_Check(format)); + /* Convert the input format to a C string and size */ + pin = _PyUnicode_AsStringAndSize(format, &flen); + if (!pin) + return NULL; - PyObject *zreplacement = NULL; /* py string, replacement for %z */ - PyObject *Zreplacement = NULL; /* py string, replacement for %Z */ - PyObject *freplacement = NULL; /* py string, replacement for %f */ - - const char *pin; /* pointer to next char in input format */ - Py_ssize_t flen; /* length of input format */ - char ch; /* next char in input format */ - - PyObject *newfmt = NULL; /* py string, the output format */ - char *pnew; /* pointer to available byte in output format */ - size_t totalnew; /* number bytes total in output format buffer, - exclusive of trailing \0 */ - size_t usednew; /* number bytes used so far in output format buffer */ - - const char *ptoappend; /* ptr to string to append to output buffer */ - Py_ssize_t ntoappend; /* # of bytes to append to output buffer */ - - assert(object && format && timetuple); - assert(PyUnicode_Check(format)); - /* Convert the input format to a C string and size */ - pin = _PyUnicode_AsStringAndSize(format, &flen); - if (!pin) - return NULL; - - /* Give up if the year is before 1900. - * Python strftime() plays games with the year, and different - * games depending on whether envar PYTHON2K is set. This makes - * years before 1900 a nightmare, even if the platform strftime - * supports them (and not all do). - * We could get a lot farther here by avoiding Python's strftime - * wrapper and calling the C strftime() directly, but that isn't - * an option in the Python implementation of this module. - */ - { - long year; - PyObject *pyyear = PySequence_GetItem(timetuple, 0); - if (pyyear == NULL) return NULL; - assert(PyLong_Check(pyyear)); - year = PyLong_AsLong(pyyear); - Py_DECREF(pyyear); - if (year < 1900) { - PyErr_Format(PyExc_ValueError, "year=%ld is before " - "1900; the datetime strftime() " - "methods require year >= 1900", - year); - return NULL; - } - } - - /* Scan the input format, looking for %z/%Z/%f escapes, building - * a new format. Since computing the replacements for those codes - * is expensive, don't unless they're actually used. - */ - if (flen > INT_MAX - 1) { - PyErr_NoMemory(); - goto Done; - } - - totalnew = flen + 1; /* realistic if no %z/%Z */ - newfmt = PyBytes_FromStringAndSize(NULL, totalnew); - if (newfmt == NULL) goto Done; - pnew = PyBytes_AsString(newfmt); - usednew = 0; - - while ((ch = *pin++) != '\0') { - if (ch != '%') { - ptoappend = pin - 1; - ntoappend = 1; - } - else if ((ch = *pin++) == '\0') { - /* There's a lone trailing %; doesn't make sense. */ - PyErr_SetString(PyExc_ValueError, "strftime format " - "ends with raw %"); - goto Done; - } - /* A % has been seen and ch is the character after it. */ - else if (ch == 'z') { - if (zreplacement == NULL) { - /* format utcoffset */ - char buf[100]; - PyObject *tzinfo = get_tzinfo_member(object); - zreplacement = PyBytes_FromStringAndSize("", 0); - if (zreplacement == NULL) goto Done; - if (tzinfo != Py_None && tzinfo != NULL) { - assert(tzinfoarg != NULL); - if (format_utcoffset(buf, - sizeof(buf), - "", - tzinfo, - tzinfoarg) < 0) - goto Done; - Py_DECREF(zreplacement); - zreplacement = - PyBytes_FromStringAndSize(buf, - strlen(buf)); - if (zreplacement == NULL) - goto Done; - } - } - assert(zreplacement != NULL); - ptoappend = PyBytes_AS_STRING(zreplacement); - ntoappend = PyBytes_GET_SIZE(zreplacement); - } - else if (ch == 'Z') { - /* format tzname */ - if (Zreplacement == NULL) { - Zreplacement = make_Zreplacement(object, - tzinfoarg); - if (Zreplacement == NULL) - goto Done; - } - assert(Zreplacement != NULL); - assert(PyUnicode_Check(Zreplacement)); - ptoappend = _PyUnicode_AsStringAndSize(Zreplacement, - &ntoappend); - ntoappend = Py_SIZE(Zreplacement); - } - else if (ch == 'f') { - /* format microseconds */ - if (freplacement == NULL) { - freplacement = make_freplacement(object); - if (freplacement == NULL) - goto Done; - } - assert(freplacement != NULL); - assert(PyBytes_Check(freplacement)); - ptoappend = PyBytes_AS_STRING(freplacement); - ntoappend = PyBytes_GET_SIZE(freplacement); - } - else { - /* percent followed by neither z nor Z */ - ptoappend = pin - 2; - ntoappend = 2; - } - - /* Append the ntoappend chars starting at ptoappend to - * the new format. - */ - if (ntoappend == 0) - continue; - assert(ptoappend != NULL); - assert(ntoappend > 0); - while (usednew + ntoappend > totalnew) { - size_t bigger = totalnew << 1; - if ((bigger >> 1) != totalnew) { /* overflow */ - PyErr_NoMemory(); - goto Done; - } - if (_PyBytes_Resize(&newfmt, bigger) < 0) - goto Done; - totalnew = bigger; - pnew = PyBytes_AsString(newfmt) + usednew; - } - memcpy(pnew, ptoappend, ntoappend); - pnew += ntoappend; - usednew += ntoappend; - assert(usednew <= totalnew); - } /* end while() */ - - if (_PyBytes_Resize(&newfmt, usednew) < 0) - goto Done; - { - PyObject *format; - PyObject *time = PyImport_ImportModuleNoBlock("time"); - if (time == NULL) - goto Done; - format = PyUnicode_FromString(PyBytes_AS_STRING(newfmt)); - if (format != NULL) { - result = PyObject_CallMethod(time, "strftime", "OO", - format, timetuple); - Py_DECREF(format); - } - Py_DECREF(time); - } + /* Give up if the year is before 1900. + * Python strftime() plays games with the year, and different + * games depending on whether envar PYTHON2K is set. This makes + * years before 1900 a nightmare, even if the platform strftime + * supports them (and not all do). + * We could get a lot farther here by avoiding Python's strftime + * wrapper and calling the C strftime() directly, but that isn't + * an option in the Python implementation of this module. + */ + { + long year; + PyObject *pyyear = PySequence_GetItem(timetuple, 0); + if (pyyear == NULL) return NULL; + assert(PyLong_Check(pyyear)); + year = PyLong_AsLong(pyyear); + Py_DECREF(pyyear); + if (year < 1900) { + PyErr_Format(PyExc_ValueError, "year=%ld is before " + "1900; the datetime strftime() " + "methods require year >= 1900", + year); + return NULL; + } + } + + /* Scan the input format, looking for %z/%Z/%f escapes, building + * a new format. Since computing the replacements for those codes + * is expensive, don't unless they're actually used. + */ + if (flen > INT_MAX - 1) { + PyErr_NoMemory(); + goto Done; + } + + totalnew = flen + 1; /* realistic if no %z/%Z */ + newfmt = PyBytes_FromStringAndSize(NULL, totalnew); + if (newfmt == NULL) goto Done; + pnew = PyBytes_AsString(newfmt); + usednew = 0; + + while ((ch = *pin++) != '\0') { + if (ch != '%') { + ptoappend = pin - 1; + ntoappend = 1; + } + else if ((ch = *pin++) == '\0') { + /* There's a lone trailing %; doesn't make sense. */ + PyErr_SetString(PyExc_ValueError, "strftime format " + "ends with raw %"); + goto Done; + } + /* A % has been seen and ch is the character after it. */ + else if (ch == 'z') { + if (zreplacement == NULL) { + /* format utcoffset */ + char buf[100]; + PyObject *tzinfo = get_tzinfo_member(object); + zreplacement = PyBytes_FromStringAndSize("", 0); + if (zreplacement == NULL) goto Done; + if (tzinfo != Py_None && tzinfo != NULL) { + assert(tzinfoarg != NULL); + if (format_utcoffset(buf, + sizeof(buf), + "", + tzinfo, + tzinfoarg) < 0) + goto Done; + Py_DECREF(zreplacement); + zreplacement = + PyBytes_FromStringAndSize(buf, + strlen(buf)); + if (zreplacement == NULL) + goto Done; + } + } + assert(zreplacement != NULL); + ptoappend = PyBytes_AS_STRING(zreplacement); + ntoappend = PyBytes_GET_SIZE(zreplacement); + } + else if (ch == 'Z') { + /* format tzname */ + if (Zreplacement == NULL) { + Zreplacement = make_Zreplacement(object, + tzinfoarg); + if (Zreplacement == NULL) + goto Done; + } + assert(Zreplacement != NULL); + assert(PyUnicode_Check(Zreplacement)); + ptoappend = _PyUnicode_AsStringAndSize(Zreplacement, + &ntoappend); + ntoappend = Py_SIZE(Zreplacement); + } + else if (ch == 'f') { + /* format microseconds */ + if (freplacement == NULL) { + freplacement = make_freplacement(object); + if (freplacement == NULL) + goto Done; + } + assert(freplacement != NULL); + assert(PyBytes_Check(freplacement)); + ptoappend = PyBytes_AS_STRING(freplacement); + ntoappend = PyBytes_GET_SIZE(freplacement); + } + else { + /* percent followed by neither z nor Z */ + ptoappend = pin - 2; + ntoappend = 2; + } + + /* Append the ntoappend chars starting at ptoappend to + * the new format. + */ + if (ntoappend == 0) + continue; + assert(ptoappend != NULL); + assert(ntoappend > 0); + while (usednew + ntoappend > totalnew) { + size_t bigger = totalnew << 1; + if ((bigger >> 1) != totalnew) { /* overflow */ + PyErr_NoMemory(); + goto Done; + } + if (_PyBytes_Resize(&newfmt, bigger) < 0) + goto Done; + totalnew = bigger; + pnew = PyBytes_AsString(newfmt) + usednew; + } + memcpy(pnew, ptoappend, ntoappend); + pnew += ntoappend; + usednew += ntoappend; + assert(usednew <= totalnew); + } /* end while() */ + + if (_PyBytes_Resize(&newfmt, usednew) < 0) + goto Done; + { + PyObject *format; + PyObject *time = PyImport_ImportModuleNoBlock("time"); + if (time == NULL) + goto Done; + format = PyUnicode_FromString(PyBytes_AS_STRING(newfmt)); + if (format != NULL) { + result = PyObject_CallMethod(time, "strftime", "OO", + format, timetuple); + Py_DECREF(format); + } + Py_DECREF(time); + } Done: - Py_XDECREF(freplacement); - Py_XDECREF(zreplacement); - Py_XDECREF(Zreplacement); - Py_XDECREF(newfmt); - return result; + Py_XDECREF(freplacement); + Py_XDECREF(zreplacement); + Py_XDECREF(Zreplacement); + Py_XDECREF(newfmt); + return result; } /* --------------------------------------------------------------------------- @@ -1390,14 +1390,14 @@ static PyObject * time_time(void) { - PyObject *result = NULL; - PyObject *time = PyImport_ImportModuleNoBlock("time"); + PyObject *result = NULL; + PyObject *time = PyImport_ImportModuleNoBlock("time"); - if (time != NULL) { - result = PyObject_CallMethod(time, "time", "()"); - Py_DECREF(time); - } - return result; + if (time != NULL) { + result = PyObject_CallMethod(time, "time", "()"); + Py_DECREF(time); + } + return result; } /* Build a time.struct_time. The weekday and day number are automatically @@ -1406,21 +1406,21 @@ static PyObject * build_struct_time(int y, int m, int d, int hh, int mm, int ss, int dstflag) { - PyObject *time; - PyObject *result = NULL; + PyObject *time; + PyObject *result = NULL; - time = PyImport_ImportModuleNoBlock("time"); - if (time != NULL) { - result = PyObject_CallMethod(time, "struct_time", - "((iiiiiiiii))", - y, m, d, - hh, mm, ss, - weekday(y, m, d), - days_before_month(y, m) + d, - dstflag); - Py_DECREF(time); - } - return result; + time = PyImport_ImportModuleNoBlock("time"); + if (time != NULL) { + result = PyObject_CallMethod(time, "struct_time", + "((iiiiiiiii))", + y, m, d, + hh, mm, ss, + weekday(y, m, d), + days_before_month(y, m) + d, + dstflag); + Py_DECREF(time); + } + return result; } /* --------------------------------------------------------------------------- @@ -1434,33 +1434,33 @@ static PyObject * diff_to_bool(int diff, int op) { - PyObject *result; - int istrue; + PyObject *result; + int istrue; - switch (op) { - case Py_EQ: istrue = diff == 0; break; - case Py_NE: istrue = diff != 0; break; - case Py_LE: istrue = diff <= 0; break; - case Py_GE: istrue = diff >= 0; break; - case Py_LT: istrue = diff < 0; break; - case Py_GT: istrue = diff > 0; break; - default: - assert(! "op unknown"); - istrue = 0; /* To shut up compiler */ - } - result = istrue ? Py_True : Py_False; - Py_INCREF(result); - return result; + switch (op) { + case Py_EQ: istrue = diff == 0; break; + case Py_NE: istrue = diff != 0; break; + case Py_LE: istrue = diff <= 0; break; + case Py_GE: istrue = diff >= 0; break; + case Py_LT: istrue = diff < 0; break; + case Py_GT: istrue = diff > 0; break; + default: + assert(! "op unknown"); + istrue = 0; /* To shut up compiler */ + } + result = istrue ? Py_True : Py_False; + Py_INCREF(result); + return result; } /* Raises a "can't compare" TypeError and returns NULL. */ static PyObject * cmperror(PyObject *a, PyObject *b) { - PyErr_Format(PyExc_TypeError, - "can't compare %s to %s", - Py_TYPE(a)->tp_name, Py_TYPE(b)->tp_name); - return NULL; + PyErr_Format(PyExc_TypeError, + "can't compare %s to %s", + Py_TYPE(a)->tp_name, Py_TYPE(b)->tp_name); + return NULL; } /* --------------------------------------------------------------------------- @@ -1468,13 +1468,13 @@ */ /* Conversion factors. */ -static PyObject *us_per_us = NULL; /* 1 */ -static PyObject *us_per_ms = NULL; /* 1000 */ -static PyObject *us_per_second = NULL; /* 1000000 */ -static PyObject *us_per_minute = NULL; /* 1e6 * 60 as Python int */ -static PyObject *us_per_hour = NULL; /* 1e6 * 3600 as Python long */ -static PyObject *us_per_day = NULL; /* 1e6 * 3600 * 24 as Python long */ -static PyObject *us_per_week = NULL; /* 1e6*3600*24*7 as Python long */ +static PyObject *us_per_us = NULL; /* 1 */ +static PyObject *us_per_ms = NULL; /* 1000 */ +static PyObject *us_per_second = NULL; /* 1000000 */ +static PyObject *us_per_minute = NULL; /* 1e6 * 60 as Python int */ +static PyObject *us_per_hour = NULL; /* 1e6 * 3600 as Python long */ +static PyObject *us_per_day = NULL; /* 1e6 * 3600 * 24 as Python long */ +static PyObject *us_per_week = NULL; /* 1e6*3600*24*7 as Python long */ static PyObject *seconds_per_day = NULL; /* 3600*24 as Python int */ /* --------------------------------------------------------------------------- @@ -1486,7 +1486,7 @@ */ /* Convert a timedelta to a number of us, - * (24*3600*self.days + self.seconds)*1000000 + self.microseconds + * (24*3600*self.days + self.seconds)*1000000 + self.microseconds * as a Python int or long. * Doing mixed-radix arithmetic by hand instead is excruciating in C, * due to ubiquitous overflow possibilities. @@ -1494,49 +1494,49 @@ static PyObject * delta_to_microseconds(PyDateTime_Delta *self) { - PyObject *x1 = NULL; - PyObject *x2 = NULL; - PyObject *x3 = NULL; - PyObject *result = NULL; - - x1 = PyLong_FromLong(GET_TD_DAYS(self)); - if (x1 == NULL) - goto Done; - x2 = PyNumber_Multiply(x1, seconds_per_day); /* days in seconds */ - if (x2 == NULL) - goto Done; - Py_DECREF(x1); - x1 = NULL; - - /* x2 has days in seconds */ - x1 = PyLong_FromLong(GET_TD_SECONDS(self)); /* seconds */ - if (x1 == NULL) - goto Done; - x3 = PyNumber_Add(x1, x2); /* days and seconds in seconds */ - if (x3 == NULL) - goto Done; - Py_DECREF(x1); - Py_DECREF(x2); - x1 = x2 = NULL; - - /* x3 has days+seconds in seconds */ - x1 = PyNumber_Multiply(x3, us_per_second); /* us */ - if (x1 == NULL) - goto Done; - Py_DECREF(x3); - x3 = NULL; - - /* x1 has days+seconds in us */ - x2 = PyLong_FromLong(GET_TD_MICROSECONDS(self)); - if (x2 == NULL) - goto Done; - result = PyNumber_Add(x1, x2); + PyObject *x1 = NULL; + PyObject *x2 = NULL; + PyObject *x3 = NULL; + PyObject *result = NULL; + + x1 = PyLong_FromLong(GET_TD_DAYS(self)); + if (x1 == NULL) + goto Done; + x2 = PyNumber_Multiply(x1, seconds_per_day); /* days in seconds */ + if (x2 == NULL) + goto Done; + Py_DECREF(x1); + x1 = NULL; + + /* x2 has days in seconds */ + x1 = PyLong_FromLong(GET_TD_SECONDS(self)); /* seconds */ + if (x1 == NULL) + goto Done; + x3 = PyNumber_Add(x1, x2); /* days and seconds in seconds */ + if (x3 == NULL) + goto Done; + Py_DECREF(x1); + Py_DECREF(x2); + x1 = x2 = NULL; + + /* x3 has days+seconds in seconds */ + x1 = PyNumber_Multiply(x3, us_per_second); /* us */ + if (x1 == NULL) + goto Done; + Py_DECREF(x3); + x3 = NULL; + + /* x1 has days+seconds in us */ + x2 = PyLong_FromLong(GET_TD_MICROSECONDS(self)); + if (x2 == NULL) + goto Done; + result = PyNumber_Add(x1, x2); Done: - Py_XDECREF(x1); - Py_XDECREF(x2); - Py_XDECREF(x3); - return result; + Py_XDECREF(x1); + Py_XDECREF(x2); + Py_XDECREF(x3); + return result; } /* Convert a number of us (as a Python int or long) to a timedelta. @@ -1544,224 +1544,224 @@ static PyObject * microseconds_to_delta_ex(PyObject *pyus, PyTypeObject *type) { - int us; - int s; - int d; - long temp; - - PyObject *tuple = NULL; - PyObject *num = NULL; - PyObject *result = NULL; - - tuple = PyNumber_Divmod(pyus, us_per_second); - if (tuple == NULL) - goto Done; - - num = PyTuple_GetItem(tuple, 1); /* us */ - if (num == NULL) - goto Done; - temp = PyLong_AsLong(num); - num = NULL; - if (temp == -1 && PyErr_Occurred()) - goto Done; - assert(0 <= temp && temp < 1000000); - us = (int)temp; - if (us < 0) { - /* The divisor was positive, so this must be an error. */ - assert(PyErr_Occurred()); - goto Done; - } - - num = PyTuple_GetItem(tuple, 0); /* leftover seconds */ - if (num == NULL) - goto Done; - Py_INCREF(num); - Py_DECREF(tuple); - - tuple = PyNumber_Divmod(num, seconds_per_day); - if (tuple == NULL) - goto Done; - Py_DECREF(num); - - num = PyTuple_GetItem(tuple, 1); /* seconds */ - if (num == NULL) - goto Done; - temp = PyLong_AsLong(num); - num = NULL; - if (temp == -1 && PyErr_Occurred()) - goto Done; - assert(0 <= temp && temp < 24*3600); - s = (int)temp; - - if (s < 0) { - /* The divisor was positive, so this must be an error. */ - assert(PyErr_Occurred()); - goto Done; - } - - num = PyTuple_GetItem(tuple, 0); /* leftover days */ - if (num == NULL) - goto Done; - Py_INCREF(num); - temp = PyLong_AsLong(num); - if (temp == -1 && PyErr_Occurred()) - goto Done; - d = (int)temp; - if ((long)d != temp) { - PyErr_SetString(PyExc_OverflowError, "normalized days too " - "large to fit in a C int"); - goto Done; - } - result = new_delta_ex(d, s, us, 0, type); + int us; + int s; + int d; + long temp; + + PyObject *tuple = NULL; + PyObject *num = NULL; + PyObject *result = NULL; + + tuple = PyNumber_Divmod(pyus, us_per_second); + if (tuple == NULL) + goto Done; + + num = PyTuple_GetItem(tuple, 1); /* us */ + if (num == NULL) + goto Done; + temp = PyLong_AsLong(num); + num = NULL; + if (temp == -1 && PyErr_Occurred()) + goto Done; + assert(0 <= temp && temp < 1000000); + us = (int)temp; + if (us < 0) { + /* The divisor was positive, so this must be an error. */ + assert(PyErr_Occurred()); + goto Done; + } + + num = PyTuple_GetItem(tuple, 0); /* leftover seconds */ + if (num == NULL) + goto Done; + Py_INCREF(num); + Py_DECREF(tuple); + + tuple = PyNumber_Divmod(num, seconds_per_day); + if (tuple == NULL) + goto Done; + Py_DECREF(num); + + num = PyTuple_GetItem(tuple, 1); /* seconds */ + if (num == NULL) + goto Done; + temp = PyLong_AsLong(num); + num = NULL; + if (temp == -1 && PyErr_Occurred()) + goto Done; + assert(0 <= temp && temp < 24*3600); + s = (int)temp; + + if (s < 0) { + /* The divisor was positive, so this must be an error. */ + assert(PyErr_Occurred()); + goto Done; + } + + num = PyTuple_GetItem(tuple, 0); /* leftover days */ + if (num == NULL) + goto Done; + Py_INCREF(num); + temp = PyLong_AsLong(num); + if (temp == -1 && PyErr_Occurred()) + goto Done; + d = (int)temp; + if ((long)d != temp) { + PyErr_SetString(PyExc_OverflowError, "normalized days too " + "large to fit in a C int"); + goto Done; + } + result = new_delta_ex(d, s, us, 0, type); Done: - Py_XDECREF(tuple); - Py_XDECREF(num); - return result; + Py_XDECREF(tuple); + Py_XDECREF(num); + return result; } -#define microseconds_to_delta(pymicros) \ - microseconds_to_delta_ex(pymicros, &PyDateTime_DeltaType) +#define microseconds_to_delta(pymicros) \ + microseconds_to_delta_ex(pymicros, &PyDateTime_DeltaType) static PyObject * multiply_int_timedelta(PyObject *intobj, PyDateTime_Delta *delta) { - PyObject *pyus_in; - PyObject *pyus_out; - PyObject *result; - - pyus_in = delta_to_microseconds(delta); - if (pyus_in == NULL) - return NULL; - - pyus_out = PyNumber_Multiply(pyus_in, intobj); - Py_DECREF(pyus_in); - if (pyus_out == NULL) - return NULL; - - result = microseconds_to_delta(pyus_out); - Py_DECREF(pyus_out); - return result; + PyObject *pyus_in; + PyObject *pyus_out; + PyObject *result; + + pyus_in = delta_to_microseconds(delta); + if (pyus_in == NULL) + return NULL; + + pyus_out = PyNumber_Multiply(pyus_in, intobj); + Py_DECREF(pyus_in); + if (pyus_out == NULL) + return NULL; + + result = microseconds_to_delta(pyus_out); + Py_DECREF(pyus_out); + return result; } static PyObject * divide_timedelta_int(PyDateTime_Delta *delta, PyObject *intobj) { - PyObject *pyus_in; - PyObject *pyus_out; - PyObject *result; - - pyus_in = delta_to_microseconds(delta); - if (pyus_in == NULL) - return NULL; - - pyus_out = PyNumber_FloorDivide(pyus_in, intobj); - Py_DECREF(pyus_in); - if (pyus_out == NULL) - return NULL; - - result = microseconds_to_delta(pyus_out); - Py_DECREF(pyus_out); - return result; + PyObject *pyus_in; + PyObject *pyus_out; + PyObject *result; + + pyus_in = delta_to_microseconds(delta); + if (pyus_in == NULL) + return NULL; + + pyus_out = PyNumber_FloorDivide(pyus_in, intobj); + Py_DECREF(pyus_in); + if (pyus_out == NULL) + return NULL; + + result = microseconds_to_delta(pyus_out); + Py_DECREF(pyus_out); + return result; } static PyObject * delta_add(PyObject *left, PyObject *right) { - PyObject *result = Py_NotImplemented; + PyObject *result = Py_NotImplemented; - if (PyDelta_Check(left) && PyDelta_Check(right)) { - /* delta + delta */ - /* The C-level additions can't overflow because of the - * invariant bounds. - */ - int days = GET_TD_DAYS(left) + GET_TD_DAYS(right); - int seconds = GET_TD_SECONDS(left) + GET_TD_SECONDS(right); - int microseconds = GET_TD_MICROSECONDS(left) + - GET_TD_MICROSECONDS(right); - result = new_delta(days, seconds, microseconds, 1); - } - - if (result == Py_NotImplemented) - Py_INCREF(result); - return result; + if (PyDelta_Check(left) && PyDelta_Check(right)) { + /* delta + delta */ + /* The C-level additions can't overflow because of the + * invariant bounds. + */ + int days = GET_TD_DAYS(left) + GET_TD_DAYS(right); + int seconds = GET_TD_SECONDS(left) + GET_TD_SECONDS(right); + int microseconds = GET_TD_MICROSECONDS(left) + + GET_TD_MICROSECONDS(right); + result = new_delta(days, seconds, microseconds, 1); + } + + if (result == Py_NotImplemented) + Py_INCREF(result); + return result; } static PyObject * delta_negative(PyDateTime_Delta *self) { - return new_delta(-GET_TD_DAYS(self), - -GET_TD_SECONDS(self), - -GET_TD_MICROSECONDS(self), - 1); + return new_delta(-GET_TD_DAYS(self), + -GET_TD_SECONDS(self), + -GET_TD_MICROSECONDS(self), + 1); } static PyObject * delta_positive(PyDateTime_Delta *self) { - /* Could optimize this (by returning self) if this isn't a - * subclass -- but who uses unary + ? Approximately nobody. - */ - return new_delta(GET_TD_DAYS(self), - GET_TD_SECONDS(self), - GET_TD_MICROSECONDS(self), - 0); + /* Could optimize this (by returning self) if this isn't a + * subclass -- but who uses unary + ? Approximately nobody. + */ + return new_delta(GET_TD_DAYS(self), + GET_TD_SECONDS(self), + GET_TD_MICROSECONDS(self), + 0); } static PyObject * delta_abs(PyDateTime_Delta *self) { - PyObject *result; + PyObject *result; - assert(GET_TD_MICROSECONDS(self) >= 0); - assert(GET_TD_SECONDS(self) >= 0); + assert(GET_TD_MICROSECONDS(self) >= 0); + assert(GET_TD_SECONDS(self) >= 0); - if (GET_TD_DAYS(self) < 0) - result = delta_negative(self); - else - result = delta_positive(self); + if (GET_TD_DAYS(self) < 0) + result = delta_negative(self); + else + result = delta_positive(self); - return result; + return result; } static PyObject * delta_subtract(PyObject *left, PyObject *right) { - PyObject *result = Py_NotImplemented; + PyObject *result = Py_NotImplemented; - if (PyDelta_Check(left) && PyDelta_Check(right)) { - /* delta - delta */ - PyObject *minus_right = PyNumber_Negative(right); - if (minus_right) { - result = delta_add(left, minus_right); - Py_DECREF(minus_right); - } - else - result = NULL; - } - - if (result == Py_NotImplemented) - Py_INCREF(result); - return result; + if (PyDelta_Check(left) && PyDelta_Check(right)) { + /* delta - delta */ + PyObject *minus_right = PyNumber_Negative(right); + if (minus_right) { + result = delta_add(left, minus_right); + Py_DECREF(minus_right); + } + else + result = NULL; + } + + if (result == Py_NotImplemented) + Py_INCREF(result); + return result; } static PyObject * delta_richcompare(PyObject *self, PyObject *other, int op) { - if (PyDelta_Check(other)) { - int diff = GET_TD_DAYS(self) - GET_TD_DAYS(other); - if (diff == 0) { - diff = GET_TD_SECONDS(self) - GET_TD_SECONDS(other); - if (diff == 0) - diff = GET_TD_MICROSECONDS(self) - - GET_TD_MICROSECONDS(other); - } - return diff_to_bool(diff, op); - } - else { - Py_INCREF(Py_NotImplemented); - return Py_NotImplemented; - } + if (PyDelta_Check(other)) { + int diff = GET_TD_DAYS(self) - GET_TD_DAYS(other); + if (diff == 0) { + diff = GET_TD_SECONDS(self) - GET_TD_SECONDS(other); + if (diff == 0) + diff = GET_TD_MICROSECONDS(self) - + GET_TD_MICROSECONDS(other); + } + return diff_to_bool(diff, op); + } + else { + Py_INCREF(Py_NotImplemented); + return Py_NotImplemented; + } } static PyObject *delta_getstate(PyDateTime_Delta *self); @@ -1769,52 +1769,52 @@ static long delta_hash(PyDateTime_Delta *self) { - if (self->hashcode == -1) { - PyObject *temp = delta_getstate(self); - if (temp != NULL) { - self->hashcode = PyObject_Hash(temp); - Py_DECREF(temp); - } - } - return self->hashcode; + if (self->hashcode == -1) { + PyObject *temp = delta_getstate(self); + if (temp != NULL) { + self->hashcode = PyObject_Hash(temp); + Py_DECREF(temp); + } + } + return self->hashcode; } static PyObject * delta_multiply(PyObject *left, PyObject *right) { - PyObject *result = Py_NotImplemented; + PyObject *result = Py_NotImplemented; - if (PyDelta_Check(left)) { - /* delta * ??? */ - if (PyLong_Check(right)) - result = multiply_int_timedelta(right, - (PyDateTime_Delta *) left); - } - else if (PyLong_Check(left)) - result = multiply_int_timedelta(left, - (PyDateTime_Delta *) right); - - if (result == Py_NotImplemented) - Py_INCREF(result); - return result; + if (PyDelta_Check(left)) { + /* delta * ??? */ + if (PyLong_Check(right)) + result = multiply_int_timedelta(right, + (PyDateTime_Delta *) left); + } + else if (PyLong_Check(left)) + result = multiply_int_timedelta(left, + (PyDateTime_Delta *) right); + + if (result == Py_NotImplemented) + Py_INCREF(result); + return result; } static PyObject * delta_divide(PyObject *left, PyObject *right) { - PyObject *result = Py_NotImplemented; + PyObject *result = Py_NotImplemented; - if (PyDelta_Check(left)) { - /* delta * ??? */ - if (PyLong_Check(right)) - result = divide_timedelta_int( - (PyDateTime_Delta *)left, - right); - } - - if (result == Py_NotImplemented) - Py_INCREF(result); - return result; + if (PyDelta_Check(left)) { + /* delta * ??? */ + if (PyLong_Check(right)) + result = divide_timedelta_int( + (PyDateTime_Delta *)left, + right); + } + + if (result == Py_NotImplemented) + Py_INCREF(result); + return result; } /* Fold in the value of the tag ("seconds", "weeks", etc) component of a @@ -1830,166 +1830,166 @@ accum(const char* tag, PyObject *sofar, PyObject *num, PyObject *factor, double *leftover) { - PyObject *prod; - PyObject *sum; + PyObject *prod; + PyObject *sum; - assert(num != NULL); + assert(num != NULL); - if (PyLong_Check(num)) { - prod = PyNumber_Multiply(num, factor); - if (prod == NULL) - return NULL; - sum = PyNumber_Add(sofar, prod); - Py_DECREF(prod); - return sum; - } - - if (PyFloat_Check(num)) { - double dnum; - double fracpart; - double intpart; - PyObject *x; - PyObject *y; - - /* The Plan: decompose num into an integer part and a - * fractional part, num = intpart + fracpart. - * Then num * factor == - * intpart * factor + fracpart * factor - * and the LHS can be computed exactly in long arithmetic. - * The RHS is again broken into an int part and frac part. - * and the frac part is added into *leftover. - */ - dnum = PyFloat_AsDouble(num); - if (dnum == -1.0 && PyErr_Occurred()) - return NULL; - fracpart = modf(dnum, &intpart); - x = PyLong_FromDouble(intpart); - if (x == NULL) - return NULL; - - prod = PyNumber_Multiply(x, factor); - Py_DECREF(x); - if (prod == NULL) - return NULL; - - sum = PyNumber_Add(sofar, prod); - Py_DECREF(prod); - if (sum == NULL) - return NULL; - - if (fracpart == 0.0) - return sum; - /* So far we've lost no information. Dealing with the - * fractional part requires float arithmetic, and may - * lose a little info. - */ - assert(PyLong_Check(factor)); - dnum = PyLong_AsDouble(factor); - - dnum *= fracpart; - fracpart = modf(dnum, &intpart); - x = PyLong_FromDouble(intpart); - if (x == NULL) { - Py_DECREF(sum); - return NULL; - } - - y = PyNumber_Add(sum, x); - Py_DECREF(sum); - Py_DECREF(x); - *leftover += fracpart; - return y; - } - - PyErr_Format(PyExc_TypeError, - "unsupported type for timedelta %s component: %s", - tag, Py_TYPE(num)->tp_name); - return NULL; + if (PyLong_Check(num)) { + prod = PyNumber_Multiply(num, factor); + if (prod == NULL) + return NULL; + sum = PyNumber_Add(sofar, prod); + Py_DECREF(prod); + return sum; + } + + if (PyFloat_Check(num)) { + double dnum; + double fracpart; + double intpart; + PyObject *x; + PyObject *y; + + /* The Plan: decompose num into an integer part and a + * fractional part, num = intpart + fracpart. + * Then num * factor == + * intpart * factor + fracpart * factor + * and the LHS can be computed exactly in long arithmetic. + * The RHS is again broken into an int part and frac part. + * and the frac part is added into *leftover. + */ + dnum = PyFloat_AsDouble(num); + if (dnum == -1.0 && PyErr_Occurred()) + return NULL; + fracpart = modf(dnum, &intpart); + x = PyLong_FromDouble(intpart); + if (x == NULL) + return NULL; + + prod = PyNumber_Multiply(x, factor); + Py_DECREF(x); + if (prod == NULL) + return NULL; + + sum = PyNumber_Add(sofar, prod); + Py_DECREF(prod); + if (sum == NULL) + return NULL; + + if (fracpart == 0.0) + return sum; + /* So far we've lost no information. Dealing with the + * fractional part requires float arithmetic, and may + * lose a little info. + */ + assert(PyLong_Check(factor)); + dnum = PyLong_AsDouble(factor); + + dnum *= fracpart; + fracpart = modf(dnum, &intpart); + x = PyLong_FromDouble(intpart); + if (x == NULL) { + Py_DECREF(sum); + return NULL; + } + + y = PyNumber_Add(sum, x); + Py_DECREF(sum); + Py_DECREF(x); + *leftover += fracpart; + return y; + } + + PyErr_Format(PyExc_TypeError, + "unsupported type for timedelta %s component: %s", + tag, Py_TYPE(num)->tp_name); + return NULL; } static PyObject * delta_new(PyTypeObject *type, PyObject *args, PyObject *kw) { - PyObject *self = NULL; + PyObject *self = NULL; + + /* Argument objects. */ + PyObject *day = NULL; + PyObject *second = NULL; + PyObject *us = NULL; + PyObject *ms = NULL; + PyObject *minute = NULL; + PyObject *hour = NULL; + PyObject *week = NULL; + + PyObject *x = NULL; /* running sum of microseconds */ + PyObject *y = NULL; /* temp sum of microseconds */ + double leftover_us = 0.0; + + static char *keywords[] = { + "days", "seconds", "microseconds", "milliseconds", + "minutes", "hours", "weeks", NULL + }; + + if (PyArg_ParseTupleAndKeywords(args, kw, "|OOOOOOO:__new__", + keywords, + &day, &second, &us, + &ms, &minute, &hour, &week) == 0) + goto Done; - /* Argument objects. */ - PyObject *day = NULL; - PyObject *second = NULL; - PyObject *us = NULL; - PyObject *ms = NULL; - PyObject *minute = NULL; - PyObject *hour = NULL; - PyObject *week = NULL; - - PyObject *x = NULL; /* running sum of microseconds */ - PyObject *y = NULL; /* temp sum of microseconds */ - double leftover_us = 0.0; - - static char *keywords[] = { - "days", "seconds", "microseconds", "milliseconds", - "minutes", "hours", "weeks", NULL - }; - - if (PyArg_ParseTupleAndKeywords(args, kw, "|OOOOOOO:__new__", - keywords, - &day, &second, &us, - &ms, &minute, &hour, &week) == 0) - goto Done; - - x = PyLong_FromLong(0); - if (x == NULL) - goto Done; - -#define CLEANUP \ - Py_DECREF(x); \ - x = y; \ - if (x == NULL) \ - goto Done - - if (us) { - y = accum("microseconds", x, us, us_per_us, &leftover_us); - CLEANUP; - } - if (ms) { - y = accum("milliseconds", x, ms, us_per_ms, &leftover_us); - CLEANUP; - } - if (second) { - y = accum("seconds", x, second, us_per_second, &leftover_us); - CLEANUP; - } - if (minute) { - y = accum("minutes", x, minute, us_per_minute, &leftover_us); - CLEANUP; - } - if (hour) { - y = accum("hours", x, hour, us_per_hour, &leftover_us); - CLEANUP; - } - if (day) { - y = accum("days", x, day, us_per_day, &leftover_us); - CLEANUP; - } - if (week) { - y = accum("weeks", x, week, us_per_week, &leftover_us); - CLEANUP; - } - if (leftover_us) { - /* Round to nearest whole # of us, and add into x. */ - PyObject *temp = PyLong_FromLong(round_to_long(leftover_us)); - if (temp == NULL) { - Py_DECREF(x); - goto Done; - } - y = PyNumber_Add(x, temp); - Py_DECREF(temp); - CLEANUP; - } + x = PyLong_FromLong(0); + if (x == NULL) + goto Done; - self = microseconds_to_delta_ex(x, type); - Py_DECREF(x); +#define CLEANUP \ + Py_DECREF(x); \ + x = y; \ + if (x == NULL) \ + goto Done + + if (us) { + y = accum("microseconds", x, us, us_per_us, &leftover_us); + CLEANUP; + } + if (ms) { + y = accum("milliseconds", x, ms, us_per_ms, &leftover_us); + CLEANUP; + } + if (second) { + y = accum("seconds", x, second, us_per_second, &leftover_us); + CLEANUP; + } + if (minute) { + y = accum("minutes", x, minute, us_per_minute, &leftover_us); + CLEANUP; + } + if (hour) { + y = accum("hours", x, hour, us_per_hour, &leftover_us); + CLEANUP; + } + if (day) { + y = accum("days", x, day, us_per_day, &leftover_us); + CLEANUP; + } + if (week) { + y = accum("weeks", x, week, us_per_week, &leftover_us); + CLEANUP; + } + if (leftover_us) { + /* Round to nearest whole # of us, and add into x. */ + PyObject *temp = PyLong_FromLong(round_to_long(leftover_us)); + if (temp == NULL) { + Py_DECREF(x); + goto Done; + } + y = PyNumber_Add(x, temp); + Py_DECREF(temp); + CLEANUP; + } + + self = microseconds_to_delta_ex(x, type); + Py_DECREF(x); Done: - return self; + return self; #undef CLEANUP } @@ -1997,57 +1997,57 @@ static int delta_bool(PyDateTime_Delta *self) { - return (GET_TD_DAYS(self) != 0 - || GET_TD_SECONDS(self) != 0 - || GET_TD_MICROSECONDS(self) != 0); + return (GET_TD_DAYS(self) != 0 + || GET_TD_SECONDS(self) != 0 + || GET_TD_MICROSECONDS(self) != 0); } static PyObject * delta_repr(PyDateTime_Delta *self) { - if (GET_TD_MICROSECONDS(self) != 0) - return PyUnicode_FromFormat("%s(%d, %d, %d)", - Py_TYPE(self)->tp_name, - GET_TD_DAYS(self), - GET_TD_SECONDS(self), - GET_TD_MICROSECONDS(self)); - if (GET_TD_SECONDS(self) != 0) - return PyUnicode_FromFormat("%s(%d, %d)", - Py_TYPE(self)->tp_name, - GET_TD_DAYS(self), - GET_TD_SECONDS(self)); - - return PyUnicode_FromFormat("%s(%d)", - Py_TYPE(self)->tp_name, - GET_TD_DAYS(self)); + if (GET_TD_MICROSECONDS(self) != 0) + return PyUnicode_FromFormat("%s(%d, %d, %d)", + Py_TYPE(self)->tp_name, + GET_TD_DAYS(self), + GET_TD_SECONDS(self), + GET_TD_MICROSECONDS(self)); + if (GET_TD_SECONDS(self) != 0) + return PyUnicode_FromFormat("%s(%d, %d)", + Py_TYPE(self)->tp_name, + GET_TD_DAYS(self), + GET_TD_SECONDS(self)); + + return PyUnicode_FromFormat("%s(%d)", + Py_TYPE(self)->tp_name, + GET_TD_DAYS(self)); } static PyObject * delta_str(PyDateTime_Delta *self) { - int us = GET_TD_MICROSECONDS(self); - int seconds = GET_TD_SECONDS(self); - int minutes = divmod(seconds, 60, &seconds); - int hours = divmod(minutes, 60, &minutes); - int days = GET_TD_DAYS(self); - - if (days) { - if (us) - return PyUnicode_FromFormat("%d day%s, %d:%02d:%02d.%06d", - days, (days == 1 || days == -1) ? "" : "s", - hours, minutes, seconds, us); - else - return PyUnicode_FromFormat("%d day%s, %d:%02d:%02d", - days, (days == 1 || days == -1) ? "" : "s", - hours, minutes, seconds); - } else { - if (us) - return PyUnicode_FromFormat("%d:%02d:%02d.%06d", - hours, minutes, seconds, us); - else - return PyUnicode_FromFormat("%d:%02d:%02d", - hours, minutes, seconds); - } + int us = GET_TD_MICROSECONDS(self); + int seconds = GET_TD_SECONDS(self); + int minutes = divmod(seconds, 60, &seconds); + int hours = divmod(minutes, 60, &minutes); + int days = GET_TD_DAYS(self); + + if (days) { + if (us) + return PyUnicode_FromFormat("%d day%s, %d:%02d:%02d.%06d", + days, (days == 1 || days == -1) ? "" : "s", + hours, minutes, seconds, us); + else + return PyUnicode_FromFormat("%d day%s, %d:%02d:%02d", + days, (days == 1 || days == -1) ? "" : "s", + hours, minutes, seconds); + } else { + if (us) + return PyUnicode_FromFormat("%d:%02d:%02d.%06d", + hours, minutes, seconds, us); + else + return PyUnicode_FromFormat("%d:%02d:%02d", + hours, minutes, seconds); + } } @@ -2057,118 +2057,118 @@ static PyObject * delta_getstate(PyDateTime_Delta *self) { - return Py_BuildValue("iii", GET_TD_DAYS(self), - GET_TD_SECONDS(self), - GET_TD_MICROSECONDS(self)); + return Py_BuildValue("iii", GET_TD_DAYS(self), + GET_TD_SECONDS(self), + GET_TD_MICROSECONDS(self)); } static PyObject * delta_reduce(PyDateTime_Delta* self) { - return Py_BuildValue("ON", Py_TYPE(self), delta_getstate(self)); + return Py_BuildValue("ON", Py_TYPE(self), delta_getstate(self)); } #define OFFSET(field) offsetof(PyDateTime_Delta, field) static PyMemberDef delta_members[] = { - {"days", T_INT, OFFSET(days), READONLY, - PyDoc_STR("Number of days.")}, + {"days", T_INT, OFFSET(days), READONLY, + PyDoc_STR("Number of days.")}, - {"seconds", T_INT, OFFSET(seconds), READONLY, - PyDoc_STR("Number of seconds (>= 0 and less than 1 day).")}, + {"seconds", T_INT, OFFSET(seconds), READONLY, + PyDoc_STR("Number of seconds (>= 0 and less than 1 day).")}, - {"microseconds", T_INT, OFFSET(microseconds), READONLY, - PyDoc_STR("Number of microseconds (>= 0 and less than 1 second).")}, - {NULL} + {"microseconds", T_INT, OFFSET(microseconds), READONLY, + PyDoc_STR("Number of microseconds (>= 0 and less than 1 second).")}, + {NULL} }; static PyMethodDef delta_methods[] = { - {"__reduce__", (PyCFunction)delta_reduce, METH_NOARGS, - PyDoc_STR("__reduce__() -> (cls, state)")}, + {"__reduce__", (PyCFunction)delta_reduce, METH_NOARGS, + PyDoc_STR("__reduce__() -> (cls, state)")}, - {NULL, NULL}, + {NULL, NULL}, }; static char delta_doc[] = PyDoc_STR("Difference between two datetime values."); static PyNumberMethods delta_as_number = { - delta_add, /* nb_add */ - delta_subtract, /* nb_subtract */ - delta_multiply, /* nb_multiply */ - 0, /* nb_remainder */ - 0, /* nb_divmod */ - 0, /* nb_power */ - (unaryfunc)delta_negative, /* nb_negative */ - (unaryfunc)delta_positive, /* nb_positive */ - (unaryfunc)delta_abs, /* nb_absolute */ - (inquiry)delta_bool, /* nb_bool */ - 0, /*nb_invert*/ - 0, /*nb_lshift*/ - 0, /*nb_rshift*/ - 0, /*nb_and*/ - 0, /*nb_xor*/ - 0, /*nb_or*/ - 0, /*nb_int*/ - 0, /*nb_reserved*/ - 0, /*nb_float*/ - 0, /*nb_inplace_add*/ - 0, /*nb_inplace_subtract*/ - 0, /*nb_inplace_multiply*/ - 0, /*nb_inplace_remainder*/ - 0, /*nb_inplace_power*/ - 0, /*nb_inplace_lshift*/ - 0, /*nb_inplace_rshift*/ - 0, /*nb_inplace_and*/ - 0, /*nb_inplace_xor*/ - 0, /*nb_inplace_or*/ - delta_divide, /* nb_floor_divide */ - 0, /* nb_true_divide */ - 0, /* nb_inplace_floor_divide */ - 0, /* nb_inplace_true_divide */ + delta_add, /* nb_add */ + delta_subtract, /* nb_subtract */ + delta_multiply, /* nb_multiply */ + 0, /* nb_remainder */ + 0, /* nb_divmod */ + 0, /* nb_power */ + (unaryfunc)delta_negative, /* nb_negative */ + (unaryfunc)delta_positive, /* nb_positive */ + (unaryfunc)delta_abs, /* nb_absolute */ + (inquiry)delta_bool, /* nb_bool */ + 0, /*nb_invert*/ + 0, /*nb_lshift*/ + 0, /*nb_rshift*/ + 0, /*nb_and*/ + 0, /*nb_xor*/ + 0, /*nb_or*/ + 0, /*nb_int*/ + 0, /*nb_reserved*/ + 0, /*nb_float*/ + 0, /*nb_inplace_add*/ + 0, /*nb_inplace_subtract*/ + 0, /*nb_inplace_multiply*/ + 0, /*nb_inplace_remainder*/ + 0, /*nb_inplace_power*/ + 0, /*nb_inplace_lshift*/ + 0, /*nb_inplace_rshift*/ + 0, /*nb_inplace_and*/ + 0, /*nb_inplace_xor*/ + 0, /*nb_inplace_or*/ + delta_divide, /* nb_floor_divide */ + 0, /* nb_true_divide */ + 0, /* nb_inplace_floor_divide */ + 0, /* nb_inplace_true_divide */ }; static PyTypeObject PyDateTime_DeltaType = { - PyVarObject_HEAD_INIT(NULL, 0) - "datetime.timedelta", /* tp_name */ - sizeof(PyDateTime_Delta), /* tp_basicsize */ - 0, /* tp_itemsize */ - 0, /* tp_dealloc */ - 0, /* tp_print */ - 0, /* tp_getattr */ - 0, /* tp_setattr */ - 0, /* tp_reserved */ - (reprfunc)delta_repr, /* tp_repr */ - &delta_as_number, /* tp_as_number */ - 0, /* tp_as_sequence */ - 0, /* tp_as_mapping */ - (hashfunc)delta_hash, /* tp_hash */ - 0, /* tp_call */ - (reprfunc)delta_str, /* tp_str */ - PyObject_GenericGetAttr, /* tp_getattro */ - 0, /* tp_setattro */ - 0, /* tp_as_buffer */ - Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */ - delta_doc, /* tp_doc */ - 0, /* tp_traverse */ - 0, /* tp_clear */ - delta_richcompare, /* tp_richcompare */ - 0, /* tp_weaklistoffset */ - 0, /* tp_iter */ - 0, /* tp_iternext */ - delta_methods, /* tp_methods */ - delta_members, /* tp_members */ - 0, /* tp_getset */ - 0, /* tp_base */ - 0, /* tp_dict */ - 0, /* tp_descr_get */ - 0, /* tp_descr_set */ - 0, /* tp_dictoffset */ - 0, /* tp_init */ - 0, /* tp_alloc */ - delta_new, /* tp_new */ - 0, /* tp_free */ + PyVarObject_HEAD_INIT(NULL, 0) + "datetime.timedelta", /* tp_name */ + sizeof(PyDateTime_Delta), /* tp_basicsize */ + 0, /* tp_itemsize */ + 0, /* tp_dealloc */ + 0, /* tp_print */ + 0, /* tp_getattr */ + 0, /* tp_setattr */ + 0, /* tp_reserved */ + (reprfunc)delta_repr, /* tp_repr */ + &delta_as_number, /* tp_as_number */ + 0, /* tp_as_sequence */ + 0, /* tp_as_mapping */ + (hashfunc)delta_hash, /* tp_hash */ + 0, /* tp_call */ + (reprfunc)delta_str, /* tp_str */ + PyObject_GenericGetAttr, /* tp_getattro */ + 0, /* tp_setattro */ + 0, /* tp_as_buffer */ + Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */ + delta_doc, /* tp_doc */ + 0, /* tp_traverse */ + 0, /* tp_clear */ + delta_richcompare, /* tp_richcompare */ + 0, /* tp_weaklistoffset */ + 0, /* tp_iter */ + 0, /* tp_iternext */ + delta_methods, /* tp_methods */ + delta_members, /* tp_members */ + 0, /* tp_getset */ + 0, /* tp_base */ + 0, /* tp_dict */ + 0, /* tp_descr_get */ + 0, /* tp_descr_set */ + 0, /* tp_dictoffset */ + 0, /* tp_init */ + 0, /* tp_alloc */ + delta_new, /* tp_new */ + 0, /* tp_free */ }; /* @@ -2180,26 +2180,26 @@ static PyObject * date_year(PyDateTime_Date *self, void *unused) { - return PyLong_FromLong(GET_YEAR(self)); + return PyLong_FromLong(GET_YEAR(self)); } static PyObject * date_month(PyDateTime_Date *self, void *unused) { - return PyLong_FromLong(GET_MONTH(self)); + return PyLong_FromLong(GET_MONTH(self)); } static PyObject * date_day(PyDateTime_Date *self, void *unused) { - return PyLong_FromLong(GET_DAY(self)); + return PyLong_FromLong(GET_DAY(self)); } static PyGetSetDef date_getset[] = { - {"year", (getter)date_year}, - {"month", (getter)date_month}, - {"day", (getter)date_day}, - {NULL} + {"year", (getter)date_year}, + {"month", (getter)date_month}, + {"day", (getter)date_day}, + {NULL} }; /* Constructors. */ @@ -2209,60 +2209,60 @@ static PyObject * date_new(PyTypeObject *type, PyObject *args, PyObject *kw) { - PyObject *self = NULL; - PyObject *state; - int year; - int month; - int day; - - /* Check for invocation from pickle with __getstate__ state */ - if (PyTuple_GET_SIZE(args) == 1 && - PyBytes_Check(state = PyTuple_GET_ITEM(args, 0)) && - PyBytes_GET_SIZE(state) == _PyDateTime_DATE_DATASIZE && - MONTH_IS_SANE(PyBytes_AS_STRING(state)[2])) - { - PyDateTime_Date *me; - - me = (PyDateTime_Date *) (type->tp_alloc(type, 0)); - if (me != NULL) { - char *pdata = PyBytes_AS_STRING(state); - memcpy(me->data, pdata, _PyDateTime_DATE_DATASIZE); - me->hashcode = -1; - } - return (PyObject *)me; - } - - if (PyArg_ParseTupleAndKeywords(args, kw, "iii", date_kws, - &year, &month, &day)) { - if (check_date_args(year, month, day) < 0) - return NULL; - self = new_date_ex(year, month, day, type); - } - return self; + PyObject *self = NULL; + PyObject *state; + int year; + int month; + int day; + + /* Check for invocation from pickle with __getstate__ state */ + if (PyTuple_GET_SIZE(args) == 1 && + PyBytes_Check(state = PyTuple_GET_ITEM(args, 0)) && + PyBytes_GET_SIZE(state) == _PyDateTime_DATE_DATASIZE && + MONTH_IS_SANE(PyBytes_AS_STRING(state)[2])) + { + PyDateTime_Date *me; + + me = (PyDateTime_Date *) (type->tp_alloc(type, 0)); + if (me != NULL) { + char *pdata = PyBytes_AS_STRING(state); + memcpy(me->data, pdata, _PyDateTime_DATE_DATASIZE); + me->hashcode = -1; + } + return (PyObject *)me; + } + + if (PyArg_ParseTupleAndKeywords(args, kw, "iii", date_kws, + &year, &month, &day)) { + if (check_date_args(year, month, day) < 0) + return NULL; + self = new_date_ex(year, month, day, type); + } + return self; } /* Return new date from localtime(t). */ static PyObject * date_local_from_time_t(PyObject *cls, double ts) { - struct tm *tm; - time_t t; - PyObject *result = NULL; - - t = _PyTime_DoubleToTimet(ts); - if (t == (time_t)-1 && PyErr_Occurred()) - return NULL; - tm = localtime(&t); - if (tm) - result = PyObject_CallFunction(cls, "iii", - tm->tm_year + 1900, - tm->tm_mon + 1, - tm->tm_mday); - else - PyErr_SetString(PyExc_ValueError, - "timestamp out of range for " - "platform localtime() function"); - return result; + struct tm *tm; + time_t t; + PyObject *result = NULL; + + t = _PyTime_DoubleToTimet(ts); + if (t == (time_t)-1 && PyErr_Occurred()) + return NULL; + tm = localtime(&t); + if (tm) + result = PyObject_CallFunction(cls, "iii", + tm->tm_year + 1900, + tm->tm_mon + 1, + tm->tm_mday); + else + PyErr_SetString(PyExc_ValueError, + "timestamp out of range for " + "platform localtime() function"); + return result; } /* Return new date from current time. @@ -2273,34 +2273,34 @@ static PyObject * date_today(PyObject *cls, PyObject *dummy) { - PyObject *time; - PyObject *result; + PyObject *time; + PyObject *result; + + time = time_time(); + if (time == NULL) + return NULL; - time = time_time(); - if (time == NULL) - return NULL; - - /* Note well: today() is a class method, so this may not call - * date.fromtimestamp. For example, it may call - * datetime.fromtimestamp. That's why we need all the accuracy - * time.time() delivers; if someone were gonzo about optimization, - * date.today() could get away with plain C time(). - */ - result = PyObject_CallMethod(cls, "fromtimestamp", "O", time); - Py_DECREF(time); - return result; + /* Note well: today() is a class method, so this may not call + * date.fromtimestamp. For example, it may call + * datetime.fromtimestamp. That's why we need all the accuracy + * time.time() delivers; if someone were gonzo about optimization, + * date.today() could get away with plain C time(). + */ + result = PyObject_CallMethod(cls, "fromtimestamp", "O", time); + Py_DECREF(time); + return result; } /* Return new date from given timestamp (Python timestamp -- a double). */ static PyObject * date_fromtimestamp(PyObject *cls, PyObject *args) { - double timestamp; - PyObject *result = NULL; + double timestamp; + PyObject *result = NULL; - if (PyArg_ParseTuple(args, "d:fromtimestamp", ×tamp)) - result = date_local_from_time_t(cls, timestamp); - return result; + if (PyArg_ParseTuple(args, "d:fromtimestamp", ×tamp)) + result = date_local_from_time_t(cls, timestamp); + return result; } /* Return new date from proleptic Gregorian ordinal. Raises ValueError if @@ -2309,24 +2309,24 @@ static PyObject * date_fromordinal(PyObject *cls, PyObject *args) { - PyObject *result = NULL; - int ordinal; + PyObject *result = NULL; + int ordinal; - if (PyArg_ParseTuple(args, "i:fromordinal", &ordinal)) { - int year; - int month; - int day; - - if (ordinal < 1) - PyErr_SetString(PyExc_ValueError, "ordinal must be " - ">= 1"); - else { - ord_to_ymd(ordinal, &year, &month, &day); - result = PyObject_CallFunction(cls, "iii", - year, month, day); - } - } - return result; + if (PyArg_ParseTuple(args, "i:fromordinal", &ordinal)) { + int year; + int month; + int day; + + if (ordinal < 1) + PyErr_SetString(PyExc_ValueError, "ordinal must be " + ">= 1"); + else { + ord_to_ymd(ordinal, &year, &month, &day); + result = PyObject_CallFunction(cls, "iii", + year, month, day); + } + } + return result; } /* @@ -2339,74 +2339,74 @@ static PyObject * add_date_timedelta(PyDateTime_Date *date, PyDateTime_Delta *delta, int negate) { - PyObject *result = NULL; - int year = GET_YEAR(date); - int month = GET_MONTH(date); - int deltadays = GET_TD_DAYS(delta); - /* C-level overflow is impossible because |deltadays| < 1e9. */ - int day = GET_DAY(date) + (negate ? -deltadays : deltadays); - - if (normalize_date(&year, &month, &day) >= 0) - result = new_date(year, month, day); - return result; + PyObject *result = NULL; + int year = GET_YEAR(date); + int month = GET_MONTH(date); + int deltadays = GET_TD_DAYS(delta); + /* C-level overflow is impossible because |deltadays| < 1e9. */ + int day = GET_DAY(date) + (negate ? -deltadays : deltadays); + + if (normalize_date(&year, &month, &day) >= 0) + result = new_date(year, month, day); + return result; } static PyObject * date_add(PyObject *left, PyObject *right) { - if (PyDateTime_Check(left) || PyDateTime_Check(right)) { - Py_INCREF(Py_NotImplemented); - return Py_NotImplemented; - } - if (PyDate_Check(left)) { - /* date + ??? */ - if (PyDelta_Check(right)) - /* date + delta */ - return add_date_timedelta((PyDateTime_Date *) left, - (PyDateTime_Delta *) right, - 0); - } - else { - /* ??? + date - * 'right' must be one of us, or we wouldn't have been called - */ - if (PyDelta_Check(left)) - /* delta + date */ - return add_date_timedelta((PyDateTime_Date *) right, - (PyDateTime_Delta *) left, - 0); - } - Py_INCREF(Py_NotImplemented); - return Py_NotImplemented; + if (PyDateTime_Check(left) || PyDateTime_Check(right)) { + Py_INCREF(Py_NotImplemented); + return Py_NotImplemented; + } + if (PyDate_Check(left)) { + /* date + ??? */ + if (PyDelta_Check(right)) + /* date + delta */ + return add_date_timedelta((PyDateTime_Date *) left, + (PyDateTime_Delta *) right, + 0); + } + else { + /* ??? + date + * 'right' must be one of us, or we wouldn't have been called + */ + if (PyDelta_Check(left)) + /* delta + date */ + return add_date_timedelta((PyDateTime_Date *) right, + (PyDateTime_Delta *) left, + 0); + } + Py_INCREF(Py_NotImplemented); + return Py_NotImplemented; } static PyObject * date_subtract(PyObject *left, PyObject *right) { - if (PyDateTime_Check(left) || PyDateTime_Check(right)) { - Py_INCREF(Py_NotImplemented); - return Py_NotImplemented; - } - if (PyDate_Check(left)) { - if (PyDate_Check(right)) { - /* date - date */ - int left_ord = ymd_to_ord(GET_YEAR(left), - GET_MONTH(left), - GET_DAY(left)); - int right_ord = ymd_to_ord(GET_YEAR(right), - GET_MONTH(right), - GET_DAY(right)); - return new_delta(left_ord - right_ord, 0, 0, 0); - } - if (PyDelta_Check(right)) { - /* date - delta */ - return add_date_timedelta((PyDateTime_Date *) left, - (PyDateTime_Delta *) right, - 1); - } - } - Py_INCREF(Py_NotImplemented); - return Py_NotImplemented; + if (PyDateTime_Check(left) || PyDateTime_Check(right)) { + Py_INCREF(Py_NotImplemented); + return Py_NotImplemented; + } + if (PyDate_Check(left)) { + if (PyDate_Check(right)) { + /* date - date */ + int left_ord = ymd_to_ord(GET_YEAR(left), + GET_MONTH(left), + GET_DAY(left)); + int right_ord = ymd_to_ord(GET_YEAR(right), + GET_MONTH(right), + GET_DAY(right)); + return new_delta(left_ord - right_ord, 0, 0, 0); + } + if (PyDelta_Check(right)) { + /* date - delta */ + return add_date_timedelta((PyDateTime_Date *) left, + (PyDateTime_Delta *) right, + 1); + } + } + Py_INCREF(Py_NotImplemented); + return Py_NotImplemented; } @@ -2415,69 +2415,69 @@ static PyObject * date_repr(PyDateTime_Date *self) { - return PyUnicode_FromFormat("%s(%d, %d, %d)", - Py_TYPE(self)->tp_name, - GET_YEAR(self), GET_MONTH(self), GET_DAY(self)); + return PyUnicode_FromFormat("%s(%d, %d, %d)", + Py_TYPE(self)->tp_name, + GET_YEAR(self), GET_MONTH(self), GET_DAY(self)); } static PyObject * date_isoformat(PyDateTime_Date *self) { - return PyUnicode_FromFormat("%04d-%02d-%02d", - GET_YEAR(self), GET_MONTH(self), GET_DAY(self)); + return PyUnicode_FromFormat("%04d-%02d-%02d", + GET_YEAR(self), GET_MONTH(self), GET_DAY(self)); } /* str() calls the appropriate isoformat() method. */ static PyObject * date_str(PyDateTime_Date *self) { - return PyObject_CallMethod((PyObject *)self, "isoformat", "()"); + return PyObject_CallMethod((PyObject *)self, "isoformat", "()"); } static PyObject * date_ctime(PyDateTime_Date *self) { - return format_ctime(self, 0, 0, 0); + return format_ctime(self, 0, 0, 0); } static PyObject * date_strftime(PyDateTime_Date *self, PyObject *args, PyObject *kw) { - /* This method can be inherited, and needs to call the - * timetuple() method appropriate to self's class. - */ - PyObject *result; - PyObject *tuple; - PyObject *format; - static char *keywords[] = {"format", NULL}; - - if (! PyArg_ParseTupleAndKeywords(args, kw, "U:strftime", keywords, - &format)) - return NULL; - - tuple = PyObject_CallMethod((PyObject *)self, "timetuple", "()"); - if (tuple == NULL) - return NULL; - result = wrap_strftime((PyObject *)self, format, tuple, - (PyObject *)self); - Py_DECREF(tuple); - return result; + /* This method can be inherited, and needs to call the + * timetuple() method appropriate to self's class. + */ + PyObject *result; + PyObject *tuple; + PyObject *format; + static char *keywords[] = {"format", NULL}; + + if (! PyArg_ParseTupleAndKeywords(args, kw, "U:strftime", keywords, + &format)) + return NULL; + + tuple = PyObject_CallMethod((PyObject *)self, "timetuple", "()"); + if (tuple == NULL) + return NULL; + result = wrap_strftime((PyObject *)self, format, tuple, + (PyObject *)self); + Py_DECREF(tuple); + return result; } static PyObject * date_format(PyDateTime_Date *self, PyObject *args) { - PyObject *format; + PyObject *format; - if (!PyArg_ParseTuple(args, "U:__format__", &format)) - return NULL; + if (!PyArg_ParseTuple(args, "U:__format__", &format)) + return NULL; - /* if the format is zero length, return str(self) */ - if (PyUnicode_GetSize(format) == 0) - return PyObject_Str((PyObject *)self); + /* if the format is zero length, return str(self) */ + if (PyUnicode_GetSize(format) == 0) + return PyObject_Str((PyObject *)self); - return PyObject_CallMethod((PyObject *)self, "strftime", "O", format); + return PyObject_CallMethod((PyObject *)self, "strftime", "O", format); } /* ISO methods. */ @@ -2485,31 +2485,31 @@ static PyObject * date_isoweekday(PyDateTime_Date *self) { - int dow = weekday(GET_YEAR(self), GET_MONTH(self), GET_DAY(self)); + int dow = weekday(GET_YEAR(self), GET_MONTH(self), GET_DAY(self)); - return PyLong_FromLong(dow + 1); + return PyLong_FromLong(dow + 1); } static PyObject * date_isocalendar(PyDateTime_Date *self) { - int year = GET_YEAR(self); - int week1_monday = iso_week1_monday(year); - int today = ymd_to_ord(year, GET_MONTH(self), GET_DAY(self)); - int week; - int day; - - week = divmod(today - week1_monday, 7, &day); - if (week < 0) { - --year; - week1_monday = iso_week1_monday(year); - week = divmod(today - week1_monday, 7, &day); - } - else if (week >= 52 && today >= iso_week1_monday(year + 1)) { - ++year; - week = 0; - } - return Py_BuildValue("iii", year, week + 1, day + 1); + int year = GET_YEAR(self); + int week1_monday = iso_week1_monday(year); + int today = ymd_to_ord(year, GET_MONTH(self), GET_DAY(self)); + int week; + int day; + + week = divmod(today - week1_monday, 7, &day); + if (week < 0) { + --year; + week1_monday = iso_week1_monday(year); + week = divmod(today - week1_monday, 7, &day); + } + else if (week >= 52 && today >= iso_week1_monday(year + 1)) { + ++year; + week = 0; + } + return Py_BuildValue("iii", year, week + 1, day + 1); } /* Miscellaneous methods. */ @@ -2517,65 +2517,65 @@ static PyObject * date_richcompare(PyObject *self, PyObject *other, int op) { - if (PyDate_Check(other)) { - int diff = memcmp(((PyDateTime_Date *)self)->data, - ((PyDateTime_Date *)other)->data, - _PyDateTime_DATE_DATASIZE); - return diff_to_bool(diff, op); - } - else { - Py_INCREF(Py_NotImplemented); - return Py_NotImplemented; - } + if (PyDate_Check(other)) { + int diff = memcmp(((PyDateTime_Date *)self)->data, + ((PyDateTime_Date *)other)->data, + _PyDateTime_DATE_DATASIZE); + return diff_to_bool(diff, op); + } + else { + Py_INCREF(Py_NotImplemented); + return Py_NotImplemented; + } } static PyObject * date_timetuple(PyDateTime_Date *self) { - return build_struct_time(GET_YEAR(self), - GET_MONTH(self), - GET_DAY(self), - 0, 0, 0, -1); + return build_struct_time(GET_YEAR(self), + GET_MONTH(self), + GET_DAY(self), + 0, 0, 0, -1); } static PyObject * date_replace(PyDateTime_Date *self, PyObject *args, PyObject *kw) { - PyObject *clone; - PyObject *tuple; - int year = GET_YEAR(self); - int month = GET_MONTH(self); - int day = GET_DAY(self); - - if (! PyArg_ParseTupleAndKeywords(args, kw, "|iii:replace", date_kws, - &year, &month, &day)) - return NULL; - tuple = Py_BuildValue("iii", year, month, day); - if (tuple == NULL) - return NULL; - clone = date_new(Py_TYPE(self), tuple, NULL); - Py_DECREF(tuple); - return clone; + PyObject *clone; + PyObject *tuple; + int year = GET_YEAR(self); + int month = GET_MONTH(self); + int day = GET_DAY(self); + + if (! PyArg_ParseTupleAndKeywords(args, kw, "|iii:replace", date_kws, + &year, &month, &day)) + return NULL; + tuple = Py_BuildValue("iii", year, month, day); + if (tuple == NULL) + return NULL; + clone = date_new(Py_TYPE(self), tuple, NULL); + Py_DECREF(tuple); + return clone; } /* - Borrowed from stringobject.c, originally it was string_hash() + Borrowed from stringobject.c, originally it was string_hash() */ static long generic_hash(unsigned char *data, int len) { - register unsigned char *p; - register long x; + register unsigned char *p; + register long x; - p = (unsigned char *) data; - x = *p << 7; - while (--len >= 0) - x = (1000003*x) ^ *p++; - x ^= len; - if (x == -1) - x = -2; + p = (unsigned char *) data; + x = *p << 7; + while (--len >= 0) + x = (1000003*x) ^ *p++; + x ^= len; + if (x == -1) + x = -2; - return x; + return x; } @@ -2584,26 +2584,26 @@ static long date_hash(PyDateTime_Date *self) { - if (self->hashcode == -1) - self->hashcode = generic_hash( - (unsigned char *)self->data, _PyDateTime_DATE_DATASIZE); + if (self->hashcode == -1) + self->hashcode = generic_hash( + (unsigned char *)self->data, _PyDateTime_DATE_DATASIZE); - return self->hashcode; + return self->hashcode; } static PyObject * date_toordinal(PyDateTime_Date *self) { - return PyLong_FromLong(ymd_to_ord(GET_YEAR(self), GET_MONTH(self), - GET_DAY(self))); + return PyLong_FromLong(ymd_to_ord(GET_YEAR(self), GET_MONTH(self), + GET_DAY(self))); } static PyObject * date_weekday(PyDateTime_Date *self) { - int dow = weekday(GET_YEAR(self), GET_MONTH(self), GET_DAY(self)); + int dow = weekday(GET_YEAR(self), GET_MONTH(self), GET_DAY(self)); - return PyLong_FromLong(dow); + return PyLong_FromLong(dow); } /* Pickle support, a simple use of __reduce__. */ @@ -2612,134 +2612,134 @@ static PyObject * date_getstate(PyDateTime_Date *self) { - PyObject* field; - field = PyBytes_FromStringAndSize((char*)self->data, - _PyDateTime_DATE_DATASIZE); - return Py_BuildValue("(N)", field); + PyObject* field; + field = PyBytes_FromStringAndSize((char*)self->data, + _PyDateTime_DATE_DATASIZE); + return Py_BuildValue("(N)", field); } static PyObject * date_reduce(PyDateTime_Date *self, PyObject *arg) { - return Py_BuildValue("(ON)", Py_TYPE(self), date_getstate(self)); + return Py_BuildValue("(ON)", Py_TYPE(self), date_getstate(self)); } static PyMethodDef date_methods[] = { - /* Class methods: */ + /* Class methods: */ - {"fromtimestamp", (PyCFunction)date_fromtimestamp, METH_VARARGS | - METH_CLASS, - PyDoc_STR("timestamp -> local date from a POSIX timestamp (like " - "time.time()).")}, + {"fromtimestamp", (PyCFunction)date_fromtimestamp, METH_VARARGS | + METH_CLASS, + PyDoc_STR("timestamp -> local date from a POSIX timestamp (like " + "time.time()).")}, - {"fromordinal", (PyCFunction)date_fromordinal, METH_VARARGS | - METH_CLASS, - PyDoc_STR("int -> date corresponding to a proleptic Gregorian " - "ordinal.")}, + {"fromordinal", (PyCFunction)date_fromordinal, METH_VARARGS | + METH_CLASS, + PyDoc_STR("int -> date corresponding to a proleptic Gregorian " + "ordinal.")}, - {"today", (PyCFunction)date_today, METH_NOARGS | METH_CLASS, - PyDoc_STR("Current date or datetime: same as " - "self.__class__.fromtimestamp(time.time()).")}, + {"today", (PyCFunction)date_today, METH_NOARGS | METH_CLASS, + PyDoc_STR("Current date or datetime: same as " + "self.__class__.fromtimestamp(time.time()).")}, - /* Instance methods: */ + /* Instance methods: */ - {"ctime", (PyCFunction)date_ctime, METH_NOARGS, - PyDoc_STR("Return ctime() style string.")}, + {"ctime", (PyCFunction)date_ctime, METH_NOARGS, + PyDoc_STR("Return ctime() style string.")}, - {"strftime", (PyCFunction)date_strftime, METH_VARARGS | METH_KEYWORDS, - PyDoc_STR("format -> strftime() style string.")}, + {"strftime", (PyCFunction)date_strftime, METH_VARARGS | METH_KEYWORDS, + PyDoc_STR("format -> strftime() style string.")}, - {"__format__", (PyCFunction)date_format, METH_VARARGS, - PyDoc_STR("Formats self with strftime.")}, + {"__format__", (PyCFunction)date_format, METH_VARARGS, + PyDoc_STR("Formats self with strftime.")}, - {"timetuple", (PyCFunction)date_timetuple, METH_NOARGS, - PyDoc_STR("Return time tuple, compatible with time.localtime().")}, + {"timetuple", (PyCFunction)date_timetuple, METH_NOARGS, + PyDoc_STR("Return time tuple, compatible with time.localtime().")}, - {"isocalendar", (PyCFunction)date_isocalendar, METH_NOARGS, - PyDoc_STR("Return a 3-tuple containing ISO year, week number, and " - "weekday.")}, + {"isocalendar", (PyCFunction)date_isocalendar, METH_NOARGS, + PyDoc_STR("Return a 3-tuple containing ISO year, week number, and " + "weekday.")}, - {"isoformat", (PyCFunction)date_isoformat, METH_NOARGS, - PyDoc_STR("Return string in ISO 8601 format, YYYY-MM-DD.")}, + {"isoformat", (PyCFunction)date_isoformat, METH_NOARGS, + PyDoc_STR("Return string in ISO 8601 format, YYYY-MM-DD.")}, - {"isoweekday", (PyCFunction)date_isoweekday, METH_NOARGS, - PyDoc_STR("Return the day of the week represented by the date.\n" - "Monday == 1 ... Sunday == 7")}, + {"isoweekday", (PyCFunction)date_isoweekday, METH_NOARGS, + PyDoc_STR("Return the day of the week represented by the date.\n" + "Monday == 1 ... Sunday == 7")}, - {"toordinal", (PyCFunction)date_toordinal, METH_NOARGS, - PyDoc_STR("Return proleptic Gregorian ordinal. January 1 of year " - "1 is day 1.")}, + {"toordinal", (PyCFunction)date_toordinal, METH_NOARGS, + PyDoc_STR("Return proleptic Gregorian ordinal. January 1 of year " + "1 is day 1.")}, - {"weekday", (PyCFunction)date_weekday, METH_NOARGS, - PyDoc_STR("Return the day of the week represented by the date.\n" - "Monday == 0 ... Sunday == 6")}, + {"weekday", (PyCFunction)date_weekday, METH_NOARGS, + PyDoc_STR("Return the day of the week represented by the date.\n" + "Monday == 0 ... Sunday == 6")}, - {"replace", (PyCFunction)date_replace, METH_VARARGS | METH_KEYWORDS, - PyDoc_STR("Return date with new specified fields.")}, + {"replace", (PyCFunction)date_replace, METH_VARARGS | METH_KEYWORDS, + PyDoc_STR("Return date with new specified fields.")}, - {"__reduce__", (PyCFunction)date_reduce, METH_NOARGS, - PyDoc_STR("__reduce__() -> (cls, state)")}, + {"__reduce__", (PyCFunction)date_reduce, METH_NOARGS, + PyDoc_STR("__reduce__() -> (cls, state)")}, - {NULL, NULL} + {NULL, NULL} }; static char date_doc[] = PyDoc_STR("date(year, month, day) --> date object"); static PyNumberMethods date_as_number = { - date_add, /* nb_add */ - date_subtract, /* nb_subtract */ - 0, /* nb_multiply */ - 0, /* nb_remainder */ - 0, /* nb_divmod */ - 0, /* nb_power */ - 0, /* nb_negative */ - 0, /* nb_positive */ - 0, /* nb_absolute */ - 0, /* nb_bool */ + date_add, /* nb_add */ + date_subtract, /* nb_subtract */ + 0, /* nb_multiply */ + 0, /* nb_remainder */ + 0, /* nb_divmod */ + 0, /* nb_power */ + 0, /* nb_negative */ + 0, /* nb_positive */ + 0, /* nb_absolute */ + 0, /* nb_bool */ }; static PyTypeObject PyDateTime_DateType = { - PyVarObject_HEAD_INIT(NULL, 0) - "datetime.date", /* tp_name */ - sizeof(PyDateTime_Date), /* tp_basicsize */ - 0, /* tp_itemsize */ - 0, /* tp_dealloc */ - 0, /* tp_print */ - 0, /* tp_getattr */ - 0, /* tp_setattr */ - 0, /* tp_reserved */ - (reprfunc)date_repr, /* tp_repr */ - &date_as_number, /* tp_as_number */ - 0, /* tp_as_sequence */ - 0, /* tp_as_mapping */ - (hashfunc)date_hash, /* tp_hash */ - 0, /* tp_call */ - (reprfunc)date_str, /* tp_str */ - PyObject_GenericGetAttr, /* tp_getattro */ - 0, /* tp_setattro */ - 0, /* tp_as_buffer */ - Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */ - date_doc, /* tp_doc */ - 0, /* tp_traverse */ - 0, /* tp_clear */ - date_richcompare, /* tp_richcompare */ - 0, /* tp_weaklistoffset */ - 0, /* tp_iter */ - 0, /* tp_iternext */ - date_methods, /* tp_methods */ - 0, /* tp_members */ - date_getset, /* tp_getset */ - 0, /* tp_base */ - 0, /* tp_dict */ - 0, /* tp_descr_get */ - 0, /* tp_descr_set */ - 0, /* tp_dictoffset */ - 0, /* tp_init */ - 0, /* tp_alloc */ - date_new, /* tp_new */ - 0, /* tp_free */ + PyVarObject_HEAD_INIT(NULL, 0) + "datetime.date", /* tp_name */ + sizeof(PyDateTime_Date), /* tp_basicsize */ + 0, /* tp_itemsize */ + 0, /* tp_dealloc */ + 0, /* tp_print */ + 0, /* tp_getattr */ + 0, /* tp_setattr */ + 0, /* tp_reserved */ + (reprfunc)date_repr, /* tp_repr */ + &date_as_number, /* tp_as_number */ + 0, /* tp_as_sequence */ + 0, /* tp_as_mapping */ + (hashfunc)date_hash, /* tp_hash */ + 0, /* tp_call */ + (reprfunc)date_str, /* tp_str */ + PyObject_GenericGetAttr, /* tp_getattro */ + 0, /* tp_setattro */ + 0, /* tp_as_buffer */ + Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */ + date_doc, /* tp_doc */ + 0, /* tp_traverse */ + 0, /* tp_clear */ + date_richcompare, /* tp_richcompare */ + 0, /* tp_weaklistoffset */ + 0, /* tp_iter */ + 0, /* tp_iternext */ + date_methods, /* tp_methods */ + 0, /* tp_members */ + date_getset, /* tp_getset */ + 0, /* tp_base */ + 0, /* tp_dict */ + 0, /* tp_descr_get */ + 0, /* tp_descr_set */ + 0, /* tp_dictoffset */ + 0, /* tp_init */ + 0, /* tp_alloc */ + date_new, /* tp_new */ + 0, /* tp_free */ }; /* @@ -2762,10 +2762,10 @@ static PyObject * tzinfo_nogo(const char* methodname) { - PyErr_Format(PyExc_NotImplementedError, - "a tzinfo subclass must implement %s()", - methodname); - return NULL; + PyErr_Format(PyExc_NotImplementedError, + "a tzinfo subclass must implement %s()", + methodname); + return NULL; } /* Methods. A subclass must implement these. */ @@ -2773,101 +2773,101 @@ static PyObject * tzinfo_tzname(PyDateTime_TZInfo *self, PyObject *dt) { - return tzinfo_nogo("tzname"); + return tzinfo_nogo("tzname"); } static PyObject * tzinfo_utcoffset(PyDateTime_TZInfo *self, PyObject *dt) { - return tzinfo_nogo("utcoffset"); + return tzinfo_nogo("utcoffset"); } static PyObject * tzinfo_dst(PyDateTime_TZInfo *self, PyObject *dt) { - return tzinfo_nogo("dst"); + return tzinfo_nogo("dst"); } static PyObject * tzinfo_fromutc(PyDateTime_TZInfo *self, PyDateTime_DateTime *dt) { - int y, m, d, hh, mm, ss, us; + int y, m, d, hh, mm, ss, us; + + PyObject *result; + int off, dst; + int none; + int delta; + + if (! PyDateTime_Check(dt)) { + PyErr_SetString(PyExc_TypeError, + "fromutc: argument must be a datetime"); + return NULL; + } + if (! HASTZINFO(dt) || dt->tzinfo != (PyObject *)self) { + PyErr_SetString(PyExc_ValueError, "fromutc: dt.tzinfo " + "is not self"); + return NULL; + } + + off = call_utcoffset(dt->tzinfo, (PyObject *)dt, &none); + if (off == -1 && PyErr_Occurred()) + return NULL; + if (none) { + PyErr_SetString(PyExc_ValueError, "fromutc: non-None " + "utcoffset() result required"); + return NULL; + } - PyObject *result; - int off, dst; - int none; - int delta; - - if (! PyDateTime_Check(dt)) { - PyErr_SetString(PyExc_TypeError, - "fromutc: argument must be a datetime"); - return NULL; - } - if (! HASTZINFO(dt) || dt->tzinfo != (PyObject *)self) { - PyErr_SetString(PyExc_ValueError, "fromutc: dt.tzinfo " - "is not self"); - return NULL; - } - - off = call_utcoffset(dt->tzinfo, (PyObject *)dt, &none); - if (off == -1 && PyErr_Occurred()) - return NULL; - if (none) { - PyErr_SetString(PyExc_ValueError, "fromutc: non-None " - "utcoffset() result required"); - return NULL; - } - - dst = call_dst(dt->tzinfo, (PyObject *)dt, &none); - if (dst == -1 && PyErr_Occurred()) - return NULL; - if (none) { - PyErr_SetString(PyExc_ValueError, "fromutc: non-None " - "dst() result required"); - return NULL; - } - - y = GET_YEAR(dt); - m = GET_MONTH(dt); - d = GET_DAY(dt); - hh = DATE_GET_HOUR(dt); - mm = DATE_GET_MINUTE(dt); - ss = DATE_GET_SECOND(dt); - us = DATE_GET_MICROSECOND(dt); - - delta = off - dst; - mm += delta; - if ((mm < 0 || mm >= 60) && - normalize_datetime(&y, &m, &d, &hh, &mm, &ss, &us) < 0) - return NULL; - result = new_datetime(y, m, d, hh, mm, ss, us, dt->tzinfo); - if (result == NULL) - return result; - - dst = call_dst(dt->tzinfo, result, &none); - if (dst == -1 && PyErr_Occurred()) - goto Fail; - if (none) - goto Inconsistent; - if (dst == 0) - return result; - - mm += dst; - if ((mm < 0 || mm >= 60) && - normalize_datetime(&y, &m, &d, &hh, &mm, &ss, &us) < 0) - goto Fail; - Py_DECREF(result); - result = new_datetime(y, m, d, hh, mm, ss, us, dt->tzinfo); - return result; + dst = call_dst(dt->tzinfo, (PyObject *)dt, &none); + if (dst == -1 && PyErr_Occurred()) + return NULL; + if (none) { + PyErr_SetString(PyExc_ValueError, "fromutc: non-None " + "dst() result required"); + return NULL; + } + + y = GET_YEAR(dt); + m = GET_MONTH(dt); + d = GET_DAY(dt); + hh = DATE_GET_HOUR(dt); + mm = DATE_GET_MINUTE(dt); + ss = DATE_GET_SECOND(dt); + us = DATE_GET_MICROSECOND(dt); + + delta = off - dst; + mm += delta; + if ((mm < 0 || mm >= 60) && + normalize_datetime(&y, &m, &d, &hh, &mm, &ss, &us) < 0) + return NULL; + result = new_datetime(y, m, d, hh, mm, ss, us, dt->tzinfo); + if (result == NULL) + return result; + + dst = call_dst(dt->tzinfo, result, &none); + if (dst == -1 && PyErr_Occurred()) + goto Fail; + if (none) + goto Inconsistent; + if (dst == 0) + return result; + + mm += dst; + if ((mm < 0 || mm >= 60) && + normalize_datetime(&y, &m, &d, &hh, &mm, &ss, &us) < 0) + goto Fail; + Py_DECREF(result); + result = new_datetime(y, m, d, hh, mm, ss, us, dt->tzinfo); + return result; Inconsistent: - PyErr_SetString(PyExc_ValueError, "fromutc: tz.dst() gave" - "inconsistent results; cannot convert"); + PyErr_SetString(PyExc_ValueError, "fromutc: tz.dst() gave" + "inconsistent results; cannot convert"); - /* fall thru to failure */ + /* fall thru to failure */ Fail: - Py_DECREF(result); - return NULL; + Py_DECREF(result); + return NULL; } /* @@ -2878,122 +2878,122 @@ static PyObject * tzinfo_reduce(PyObject *self) { - PyObject *args, *state, *tmp; - PyObject *getinitargs, *getstate; + PyObject *args, *state, *tmp; + PyObject *getinitargs, *getstate; - tmp = PyTuple_New(0); - if (tmp == NULL) - return NULL; - - getinitargs = PyObject_GetAttrString(self, "__getinitargs__"); - if (getinitargs != NULL) { - args = PyObject_CallObject(getinitargs, tmp); - Py_DECREF(getinitargs); - if (args == NULL) { - Py_DECREF(tmp); - return NULL; - } - } - else { - PyErr_Clear(); - args = tmp; - Py_INCREF(args); - } - - getstate = PyObject_GetAttrString(self, "__getstate__"); - if (getstate != NULL) { - state = PyObject_CallObject(getstate, tmp); - Py_DECREF(getstate); - if (state == NULL) { - Py_DECREF(args); - Py_DECREF(tmp); - return NULL; - } - } - else { - PyObject **dictptr; - PyErr_Clear(); - state = Py_None; - dictptr = _PyObject_GetDictPtr(self); - if (dictptr && *dictptr && PyDict_Size(*dictptr)) - state = *dictptr; - Py_INCREF(state); - } - - Py_DECREF(tmp); - - if (state == Py_None) { - Py_DECREF(state); - return Py_BuildValue("(ON)", Py_TYPE(self), args); - } - else - return Py_BuildValue("(ONN)", Py_TYPE(self), args, state); + tmp = PyTuple_New(0); + if (tmp == NULL) + return NULL; + + getinitargs = PyObject_GetAttrString(self, "__getinitargs__"); + if (getinitargs != NULL) { + args = PyObject_CallObject(getinitargs, tmp); + Py_DECREF(getinitargs); + if (args == NULL) { + Py_DECREF(tmp); + return NULL; + } + } + else { + PyErr_Clear(); + args = tmp; + Py_INCREF(args); + } + + getstate = PyObject_GetAttrString(self, "__getstate__"); + if (getstate != NULL) { + state = PyObject_CallObject(getstate, tmp); + Py_DECREF(getstate); + if (state == NULL) { + Py_DECREF(args); + Py_DECREF(tmp); + return NULL; + } + } + else { + PyObject **dictptr; + PyErr_Clear(); + state = Py_None; + dictptr = _PyObject_GetDictPtr(self); + if (dictptr && *dictptr && PyDict_Size(*dictptr)) + state = *dictptr; + Py_INCREF(state); + } + + Py_DECREF(tmp); + + if (state == Py_None) { + Py_DECREF(state); + return Py_BuildValue("(ON)", Py_TYPE(self), args); + } + else + return Py_BuildValue("(ONN)", Py_TYPE(self), args, state); } static PyMethodDef tzinfo_methods[] = { - {"tzname", (PyCFunction)tzinfo_tzname, METH_O, - PyDoc_STR("datetime -> string name of time zone.")}, + {"tzname", (PyCFunction)tzinfo_tzname, METH_O, + PyDoc_STR("datetime -> string name of time zone.")}, - {"utcoffset", (PyCFunction)tzinfo_utcoffset, METH_O, - PyDoc_STR("datetime -> minutes east of UTC (negative for " - "west of UTC).")}, + {"utcoffset", (PyCFunction)tzinfo_utcoffset, METH_O, + PyDoc_STR("datetime -> minutes east of UTC (negative for " + "west of UTC).")}, - {"dst", (PyCFunction)tzinfo_dst, METH_O, - PyDoc_STR("datetime -> DST offset in minutes east of UTC.")}, + {"dst", (PyCFunction)tzinfo_dst, METH_O, + PyDoc_STR("datetime -> DST offset in minutes east of UTC.")}, - {"fromutc", (PyCFunction)tzinfo_fromutc, METH_O, - PyDoc_STR("datetime in UTC -> datetime in local time.")}, + {"fromutc", (PyCFunction)tzinfo_fromutc, METH_O, + PyDoc_STR("datetime in UTC -> datetime in local time.")}, - {"__reduce__", (PyCFunction)tzinfo_reduce, METH_NOARGS, - PyDoc_STR("-> (cls, state)")}, + {"__reduce__", (PyCFunction)tzinfo_reduce, METH_NOARGS, + PyDoc_STR("-> (cls, state)")}, - {NULL, NULL} + {NULL, NULL} }; static char tzinfo_doc[] = PyDoc_STR("Abstract base class for time zone info objects."); static PyTypeObject PyDateTime_TZInfoType = { - PyVarObject_HEAD_INIT(NULL, 0) - "datetime.tzinfo", /* tp_name */ - sizeof(PyDateTime_TZInfo), /* tp_basicsize */ - 0, /* tp_itemsize */ - 0, /* 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_BASETYPE, /* tp_flags */ - tzinfo_doc, /* tp_doc */ - 0, /* tp_traverse */ - 0, /* tp_clear */ - 0, /* tp_richcompare */ - 0, /* tp_weaklistoffset */ - 0, /* tp_iter */ - 0, /* tp_iternext */ - tzinfo_methods, /* tp_methods */ - 0, /* tp_members */ - 0, /* tp_getset */ - 0, /* tp_base */ - 0, /* tp_dict */ - 0, /* tp_descr_get */ - 0, /* tp_descr_set */ - 0, /* tp_dictoffset */ - 0, /* tp_init */ - 0, /* tp_alloc */ - PyType_GenericNew, /* tp_new */ - 0, /* tp_free */ + PyVarObject_HEAD_INIT(NULL, 0) + "datetime.tzinfo", /* tp_name */ + sizeof(PyDateTime_TZInfo), /* tp_basicsize */ + 0, /* tp_itemsize */ + 0, /* 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_BASETYPE, /* tp_flags */ + tzinfo_doc, /* tp_doc */ + 0, /* tp_traverse */ + 0, /* tp_clear */ + 0, /* tp_richcompare */ + 0, /* tp_weaklistoffset */ + 0, /* tp_iter */ + 0, /* tp_iternext */ + tzinfo_methods, /* tp_methods */ + 0, /* tp_members */ + 0, /* tp_getset */ + 0, /* tp_base */ + 0, /* tp_dict */ + 0, /* tp_descr_get */ + 0, /* tp_descr_set */ + 0, /* tp_dictoffset */ + 0, /* tp_init */ + 0, /* tp_alloc */ + PyType_GenericNew, /* tp_new */ + 0, /* tp_free */ }; /* @@ -3006,43 +3006,43 @@ static PyObject * time_hour(PyDateTime_Time *self, void *unused) { - return PyLong_FromLong(TIME_GET_HOUR(self)); + return PyLong_FromLong(TIME_GET_HOUR(self)); } static PyObject * time_minute(PyDateTime_Time *self, void *unused) { - return PyLong_FromLong(TIME_GET_MINUTE(self)); + return PyLong_FromLong(TIME_GET_MINUTE(self)); } /* The name time_second conflicted with some platform header file. */ static PyObject * py_time_second(PyDateTime_Time *self, void *unused) { - return PyLong_FromLong(TIME_GET_SECOND(self)); + return PyLong_FromLong(TIME_GET_SECOND(self)); } static PyObject * time_microsecond(PyDateTime_Time *self, void *unused) { - return PyLong_FromLong(TIME_GET_MICROSECOND(self)); + return PyLong_FromLong(TIME_GET_MICROSECOND(self)); } static PyObject * time_tzinfo(PyDateTime_Time *self, void *unused) { - PyObject *result = HASTZINFO(self) ? self->tzinfo : Py_None; - Py_INCREF(result); - return result; + PyObject *result = HASTZINFO(self) ? self->tzinfo : Py_None; + Py_INCREF(result); + return result; } static PyGetSetDef time_getset[] = { - {"hour", (getter)time_hour}, - {"minute", (getter)time_minute}, - {"second", (getter)py_time_second}, - {"microsecond", (getter)time_microsecond}, - {"tzinfo", (getter)time_tzinfo}, - {NULL} + {"hour", (getter)time_hour}, + {"minute", (getter)time_minute}, + {"second", (getter)py_time_second}, + {"microsecond", (getter)time_microsecond}, + {"tzinfo", (getter)time_tzinfo}, + {NULL} }; /* @@ -3050,64 +3050,64 @@ */ static char *time_kws[] = {"hour", "minute", "second", "microsecond", - "tzinfo", NULL}; + "tzinfo", NULL}; static PyObject * time_new(PyTypeObject *type, PyObject *args, PyObject *kw) { - PyObject *self = NULL; - PyObject *state; - int hour = 0; - int minute = 0; - int second = 0; - int usecond = 0; - PyObject *tzinfo = Py_None; - - /* Check for invocation from pickle with __getstate__ state */ - if (PyTuple_GET_SIZE(args) >= 1 && - PyTuple_GET_SIZE(args) <= 2 && - PyBytes_Check(state = PyTuple_GET_ITEM(args, 0)) && - PyBytes_GET_SIZE(state) == _PyDateTime_TIME_DATASIZE && - ((unsigned char) (PyBytes_AS_STRING(state)[0])) < 24) - { - PyDateTime_Time *me; - char aware; - - if (PyTuple_GET_SIZE(args) == 2) { - tzinfo = PyTuple_GET_ITEM(args, 1); - if (check_tzinfo_subclass(tzinfo) < 0) { - PyErr_SetString(PyExc_TypeError, "bad " - "tzinfo state arg"); - return NULL; - } - } - aware = (char)(tzinfo != Py_None); - me = (PyDateTime_Time *) (type->tp_alloc(type, aware)); - if (me != NULL) { - char *pdata = PyBytes_AS_STRING(state); - - memcpy(me->data, pdata, _PyDateTime_TIME_DATASIZE); - me->hashcode = -1; - me->hastzinfo = aware; - if (aware) { - Py_INCREF(tzinfo); - me->tzinfo = tzinfo; - } - } - return (PyObject *)me; - } - - if (PyArg_ParseTupleAndKeywords(args, kw, "|iiiiO", time_kws, - &hour, &minute, &second, &usecond, - &tzinfo)) { - if (check_time_args(hour, minute, second, usecond) < 0) - return NULL; - if (check_tzinfo_subclass(tzinfo) < 0) - return NULL; - self = new_time_ex(hour, minute, second, usecond, tzinfo, - type); - } - return self; + PyObject *self = NULL; + PyObject *state; + int hour = 0; + int minute = 0; + int second = 0; + int usecond = 0; + PyObject *tzinfo = Py_None; + + /* Check for invocation from pickle with __getstate__ state */ + if (PyTuple_GET_SIZE(args) >= 1 && + PyTuple_GET_SIZE(args) <= 2 && + PyBytes_Check(state = PyTuple_GET_ITEM(args, 0)) && + PyBytes_GET_SIZE(state) == _PyDateTime_TIME_DATASIZE && + ((unsigned char) (PyBytes_AS_STRING(state)[0])) < 24) + { + PyDateTime_Time *me; + char aware; + + if (PyTuple_GET_SIZE(args) == 2) { + tzinfo = PyTuple_GET_ITEM(args, 1); + if (check_tzinfo_subclass(tzinfo) < 0) { + PyErr_SetString(PyExc_TypeError, "bad " + "tzinfo state arg"); + return NULL; + } + } + aware = (char)(tzinfo != Py_None); + me = (PyDateTime_Time *) (type->tp_alloc(type, aware)); + if (me != NULL) { + char *pdata = PyBytes_AS_STRING(state); + + memcpy(me->data, pdata, _PyDateTime_TIME_DATASIZE); + me->hashcode = -1; + me->hastzinfo = aware; + if (aware) { + Py_INCREF(tzinfo); + me->tzinfo = tzinfo; + } + } + return (PyObject *)me; + } + + if (PyArg_ParseTupleAndKeywords(args, kw, "|iiiiO", time_kws, + &hour, &minute, &second, &usecond, + &tzinfo)) { + if (check_time_args(hour, minute, second, usecond) < 0) + return NULL; + if (check_tzinfo_subclass(tzinfo) < 0) + return NULL; + self = new_time_ex(hour, minute, second, usecond, tzinfo, + type); + } + return self; } /* @@ -3117,10 +3117,10 @@ static void time_dealloc(PyDateTime_Time *self) { - if (HASTZINFO(self)) { - Py_XDECREF(self->tzinfo); - } - Py_TYPE(self)->tp_free((PyObject *)self); + if (HASTZINFO(self)) { + Py_XDECREF(self->tzinfo); + } + Py_TYPE(self)->tp_free((PyObject *)self); } /* @@ -3130,20 +3130,20 @@ /* These are all METH_NOARGS, so don't need to check the arglist. */ static PyObject * time_utcoffset(PyDateTime_Time *self, PyObject *unused) { - return offset_as_timedelta(HASTZINFO(self) ? self->tzinfo : Py_None, - "utcoffset", Py_None); + return offset_as_timedelta(HASTZINFO(self) ? self->tzinfo : Py_None, + "utcoffset", Py_None); } static PyObject * time_dst(PyDateTime_Time *self, PyObject *unused) { - return offset_as_timedelta(HASTZINFO(self) ? self->tzinfo : Py_None, - "dst", Py_None); + return offset_as_timedelta(HASTZINFO(self) ? self->tzinfo : Py_None, + "dst", Py_None); } static PyObject * time_tzname(PyDateTime_Time *self, PyObject *unused) { - return call_tzname(HASTZINFO(self) ? self->tzinfo : Py_None, - Py_None); + return call_tzname(HASTZINFO(self) ? self->tzinfo : Py_None, + Py_None); } /* @@ -3153,93 +3153,93 @@ static PyObject * time_repr(PyDateTime_Time *self) { - const char *type_name = Py_TYPE(self)->tp_name; - int h = TIME_GET_HOUR(self); - int m = TIME_GET_MINUTE(self); - int s = TIME_GET_SECOND(self); - int us = TIME_GET_MICROSECOND(self); - PyObject *result = NULL; - - if (us) - result = PyUnicode_FromFormat("%s(%d, %d, %d, %d)", - type_name, h, m, s, us); - else if (s) - result = PyUnicode_FromFormat("%s(%d, %d, %d)", - type_name, h, m, s); - else - result = PyUnicode_FromFormat("%s(%d, %d)", type_name, h, m); - if (result != NULL && HASTZINFO(self)) - result = append_keyword_tzinfo(result, self->tzinfo); - return result; + const char *type_name = Py_TYPE(self)->tp_name; + int h = TIME_GET_HOUR(self); + int m = TIME_GET_MINUTE(self); + int s = TIME_GET_SECOND(self); + int us = TIME_GET_MICROSECOND(self); + PyObject *result = NULL; + + if (us) + result = PyUnicode_FromFormat("%s(%d, %d, %d, %d)", + type_name, h, m, s, us); + else if (s) + result = PyUnicode_FromFormat("%s(%d, %d, %d)", + type_name, h, m, s); + else + result = PyUnicode_FromFormat("%s(%d, %d)", type_name, h, m); + if (result != NULL && HASTZINFO(self)) + result = append_keyword_tzinfo(result, self->tzinfo); + return result; } static PyObject * time_str(PyDateTime_Time *self) { - return PyObject_CallMethod((PyObject *)self, "isoformat", "()"); + return PyObject_CallMethod((PyObject *)self, "isoformat", "()"); } static PyObject * time_isoformat(PyDateTime_Time *self, PyObject *unused) { - char buf[100]; - PyObject *result; - int us = TIME_GET_MICROSECOND(self);; - - if (us) - result = PyUnicode_FromFormat("%02d:%02d:%02d.%06d", - TIME_GET_HOUR(self), - TIME_GET_MINUTE(self), - TIME_GET_SECOND(self), - us); - else - result = PyUnicode_FromFormat("%02d:%02d:%02d", - TIME_GET_HOUR(self), - TIME_GET_MINUTE(self), - TIME_GET_SECOND(self)); - - if (result == NULL || ! HASTZINFO(self) || self->tzinfo == Py_None) - return result; - - /* We need to append the UTC offset. */ - if (format_utcoffset(buf, sizeof(buf), ":", self->tzinfo, - Py_None) < 0) { - Py_DECREF(result); - return NULL; - } - PyUnicode_AppendAndDel(&result, PyUnicode_FromString(buf)); - return result; + char buf[100]; + PyObject *result; + int us = TIME_GET_MICROSECOND(self);; + + if (us) + result = PyUnicode_FromFormat("%02d:%02d:%02d.%06d", + TIME_GET_HOUR(self), + TIME_GET_MINUTE(self), + TIME_GET_SECOND(self), + us); + else + result = PyUnicode_FromFormat("%02d:%02d:%02d", + TIME_GET_HOUR(self), + TIME_GET_MINUTE(self), + TIME_GET_SECOND(self)); + + if (result == NULL || ! HASTZINFO(self) || self->tzinfo == Py_None) + return result; + + /* We need to append the UTC offset. */ + if (format_utcoffset(buf, sizeof(buf), ":", self->tzinfo, + Py_None) < 0) { + Py_DECREF(result); + return NULL; + } + PyUnicode_AppendAndDel(&result, PyUnicode_FromString(buf)); + return result; } static PyObject * time_strftime(PyDateTime_Time *self, PyObject *args, PyObject *kw) { - PyObject *result; - PyObject *tuple; - PyObject *format; - static char *keywords[] = {"format", NULL}; - - if (! PyArg_ParseTupleAndKeywords(args, kw, "U:strftime", keywords, - &format)) - return NULL; - - /* Python's strftime does insane things with the year part of the - * timetuple. The year is forced to (the otherwise nonsensical) - * 1900 to worm around that. - */ - tuple = Py_BuildValue("iiiiiiiii", - 1900, 1, 1, /* year, month, day */ - TIME_GET_HOUR(self), - TIME_GET_MINUTE(self), - TIME_GET_SECOND(self), - 0, 1, -1); /* weekday, daynum, dst */ - if (tuple == NULL) - return NULL; - assert(PyTuple_Size(tuple) == 9); - result = wrap_strftime((PyObject *)self, format, tuple, - Py_None); - Py_DECREF(tuple); - return result; + PyObject *result; + PyObject *tuple; + PyObject *format; + static char *keywords[] = {"format", NULL}; + + if (! PyArg_ParseTupleAndKeywords(args, kw, "U:strftime", keywords, + &format)) + return NULL; + + /* Python's strftime does insane things with the year part of the + * timetuple. The year is forced to (the otherwise nonsensical) + * 1900 to worm around that. + */ + tuple = Py_BuildValue("iiiiiiiii", + 1900, 1, 1, /* year, month, day */ + TIME_GET_HOUR(self), + TIME_GET_MINUTE(self), + TIME_GET_SECOND(self), + 0, 1, -1); /* weekday, daynum, dst */ + if (tuple == NULL) + return NULL; + assert(PyTuple_Size(tuple) == 9); + result = wrap_strftime((PyObject *)self, format, tuple, + Py_None); + Py_DECREF(tuple); + return result; } /* @@ -3249,144 +3249,144 @@ static PyObject * time_richcompare(PyObject *self, PyObject *other, int op) { - int diff; - naivety n1, n2; - int offset1, offset2; - - if (! PyTime_Check(other)) { - Py_INCREF(Py_NotImplemented); - return Py_NotImplemented; - } - if (classify_two_utcoffsets(self, &offset1, &n1, Py_None, - other, &offset2, &n2, Py_None) < 0) - return NULL; - assert(n1 != OFFSET_UNKNOWN && n2 != OFFSET_UNKNOWN); - /* If they're both naive, or both aware and have the same offsets, - * we get off cheap. Note that if they're both naive, offset1 == - * offset2 == 0 at this point. - */ - if (n1 == n2 && offset1 == offset2) { - diff = memcmp(((PyDateTime_Time *)self)->data, - ((PyDateTime_Time *)other)->data, - _PyDateTime_TIME_DATASIZE); - return diff_to_bool(diff, op); - } - - if (n1 == OFFSET_AWARE && n2 == OFFSET_AWARE) { - assert(offset1 != offset2); /* else last "if" handled it */ - /* Convert everything except microseconds to seconds. These - * can't overflow (no more than the # of seconds in 2 days). - */ - offset1 = TIME_GET_HOUR(self) * 3600 + - (TIME_GET_MINUTE(self) - offset1) * 60 + - TIME_GET_SECOND(self); - offset2 = TIME_GET_HOUR(other) * 3600 + - (TIME_GET_MINUTE(other) - offset2) * 60 + - TIME_GET_SECOND(other); - diff = offset1 - offset2; - if (diff == 0) - diff = TIME_GET_MICROSECOND(self) - - TIME_GET_MICROSECOND(other); - return diff_to_bool(diff, op); - } - - assert(n1 != n2); - PyErr_SetString(PyExc_TypeError, - "can't compare offset-naive and " - "offset-aware times"); - return NULL; + int diff; + naivety n1, n2; + int offset1, offset2; + + if (! PyTime_Check(other)) { + Py_INCREF(Py_NotImplemented); + return Py_NotImplemented; + } + if (classify_two_utcoffsets(self, &offset1, &n1, Py_None, + other, &offset2, &n2, Py_None) < 0) + return NULL; + assert(n1 != OFFSET_UNKNOWN && n2 != OFFSET_UNKNOWN); + /* If they're both naive, or both aware and have the same offsets, + * we get off cheap. Note that if they're both naive, offset1 == + * offset2 == 0 at this point. + */ + if (n1 == n2 && offset1 == offset2) { + diff = memcmp(((PyDateTime_Time *)self)->data, + ((PyDateTime_Time *)other)->data, + _PyDateTime_TIME_DATASIZE); + return diff_to_bool(diff, op); + } + + if (n1 == OFFSET_AWARE && n2 == OFFSET_AWARE) { + assert(offset1 != offset2); /* else last "if" handled it */ + /* Convert everything except microseconds to seconds. These + * can't overflow (no more than the # of seconds in 2 days). + */ + offset1 = TIME_GET_HOUR(self) * 3600 + + (TIME_GET_MINUTE(self) - offset1) * 60 + + TIME_GET_SECOND(self); + offset2 = TIME_GET_HOUR(other) * 3600 + + (TIME_GET_MINUTE(other) - offset2) * 60 + + TIME_GET_SECOND(other); + diff = offset1 - offset2; + if (diff == 0) + diff = TIME_GET_MICROSECOND(self) - + TIME_GET_MICROSECOND(other); + return diff_to_bool(diff, op); + } + + assert(n1 != n2); + PyErr_SetString(PyExc_TypeError, + "can't compare offset-naive and " + "offset-aware times"); + return NULL; } static long time_hash(PyDateTime_Time *self) { - if (self->hashcode == -1) { - naivety n; - int offset; - PyObject *temp; - - n = classify_utcoffset((PyObject *)self, Py_None, &offset); - assert(n != OFFSET_UNKNOWN); - if (n == OFFSET_ERROR) - return -1; - - /* Reduce this to a hash of another object. */ - if (offset == 0) { - self->hashcode = generic_hash( - (unsigned char *)self->data, _PyDateTime_TIME_DATASIZE); - return self->hashcode; - } - else { - int hour; - int minute; - - assert(n == OFFSET_AWARE); - assert(HASTZINFO(self)); - hour = divmod(TIME_GET_HOUR(self) * 60 + - TIME_GET_MINUTE(self) - offset, - 60, - &minute); - if (0 <= hour && hour < 24) - temp = new_time(hour, minute, - TIME_GET_SECOND(self), - TIME_GET_MICROSECOND(self), - Py_None); - else - temp = Py_BuildValue("iiii", - hour, minute, - TIME_GET_SECOND(self), - TIME_GET_MICROSECOND(self)); - } - if (temp != NULL) { - self->hashcode = PyObject_Hash(temp); - Py_DECREF(temp); - } - } - return self->hashcode; + if (self->hashcode == -1) { + naivety n; + int offset; + PyObject *temp; + + n = classify_utcoffset((PyObject *)self, Py_None, &offset); + assert(n != OFFSET_UNKNOWN); + if (n == OFFSET_ERROR) + return -1; + + /* Reduce this to a hash of another object. */ + if (offset == 0) { + self->hashcode = generic_hash( + (unsigned char *)self->data, _PyDateTime_TIME_DATASIZE); + return self->hashcode; + } + else { + int hour; + int minute; + + assert(n == OFFSET_AWARE); + assert(HASTZINFO(self)); + hour = divmod(TIME_GET_HOUR(self) * 60 + + TIME_GET_MINUTE(self) - offset, + 60, + &minute); + if (0 <= hour && hour < 24) + temp = new_time(hour, minute, + TIME_GET_SECOND(self), + TIME_GET_MICROSECOND(self), + Py_None); + else + temp = Py_BuildValue("iiii", + hour, minute, + TIME_GET_SECOND(self), + TIME_GET_MICROSECOND(self)); + } + if (temp != NULL) { + self->hashcode = PyObject_Hash(temp); + Py_DECREF(temp); + } + } + return self->hashcode; } static PyObject * time_replace(PyDateTime_Time *self, PyObject *args, PyObject *kw) { - PyObject *clone; - PyObject *tuple; - int hh = TIME_GET_HOUR(self); - int mm = TIME_GET_MINUTE(self); - int ss = TIME_GET_SECOND(self); - int us = TIME_GET_MICROSECOND(self); - PyObject *tzinfo = HASTZINFO(self) ? self->tzinfo : Py_None; - - if (! PyArg_ParseTupleAndKeywords(args, kw, "|iiiiO:replace", - time_kws, - &hh, &mm, &ss, &us, &tzinfo)) - return NULL; - tuple = Py_BuildValue("iiiiO", hh, mm, ss, us, tzinfo); - if (tuple == NULL) - return NULL; - clone = time_new(Py_TYPE(self), tuple, NULL); - Py_DECREF(tuple); - return clone; + PyObject *clone; + PyObject *tuple; + int hh = TIME_GET_HOUR(self); + int mm = TIME_GET_MINUTE(self); + int ss = TIME_GET_SECOND(self); + int us = TIME_GET_MICROSECOND(self); + PyObject *tzinfo = HASTZINFO(self) ? self->tzinfo : Py_None; + + if (! PyArg_ParseTupleAndKeywords(args, kw, "|iiiiO:replace", + time_kws, + &hh, &mm, &ss, &us, &tzinfo)) + return NULL; + tuple = Py_BuildValue("iiiiO", hh, mm, ss, us, tzinfo); + if (tuple == NULL) + return NULL; + clone = time_new(Py_TYPE(self), tuple, NULL); + Py_DECREF(tuple); + return clone; } static int time_bool(PyDateTime_Time *self) { - int offset; - int none; + int offset; + int none; - if (TIME_GET_SECOND(self) || TIME_GET_MICROSECOND(self)) { - /* Since utcoffset is in whole minutes, nothing can - * alter the conclusion that this is nonzero. - */ - return 1; - } - offset = 0; - if (HASTZINFO(self) && self->tzinfo != Py_None) { - offset = call_utcoffset(self->tzinfo, Py_None, &none); - if (offset == -1 && PyErr_Occurred()) - return -1; - } - return (TIME_GET_MINUTE(self) - offset + TIME_GET_HOUR(self)*60) != 0; + if (TIME_GET_SECOND(self) || TIME_GET_MICROSECOND(self)) { + /* Since utcoffset is in whole minutes, nothing can + * alter the conclusion that this is nonzero. + */ + return 1; + } + offset = 0; + if (HASTZINFO(self) && self->tzinfo != Py_None) { + offset = call_utcoffset(self->tzinfo, Py_None, &none); + if (offset == -1 && PyErr_Occurred()) + return -1; + } + return (TIME_GET_MINUTE(self) - offset + TIME_GET_HOUR(self)*60) != 0; } /* Pickle support, a simple use of __reduce__. */ @@ -3399,55 +3399,55 @@ static PyObject * time_getstate(PyDateTime_Time *self) { - PyObject *basestate; - PyObject *result = NULL; + PyObject *basestate; + PyObject *result = NULL; - basestate = PyBytes_FromStringAndSize((char *)self->data, - _PyDateTime_TIME_DATASIZE); - if (basestate != NULL) { - if (! HASTZINFO(self) || self->tzinfo == Py_None) - result = PyTuple_Pack(1, basestate); - else - result = PyTuple_Pack(2, basestate, self->tzinfo); - Py_DECREF(basestate); - } - return result; + basestate = PyBytes_FromStringAndSize((char *)self->data, + _PyDateTime_TIME_DATASIZE); + if (basestate != NULL) { + if (! HASTZINFO(self) || self->tzinfo == Py_None) + result = PyTuple_Pack(1, basestate); + else + result = PyTuple_Pack(2, basestate, self->tzinfo); + Py_DECREF(basestate); + } + return result; } static PyObject * time_reduce(PyDateTime_Time *self, PyObject *arg) { - return Py_BuildValue("(ON)", Py_TYPE(self), time_getstate(self)); + return Py_BuildValue("(ON)", Py_TYPE(self), time_getstate(self)); } static PyMethodDef time_methods[] = { - {"isoformat", (PyCFunction)time_isoformat, METH_NOARGS, - PyDoc_STR("Return string in ISO 8601 format, HH:MM:SS[.mmmmmm]" - "[+HH:MM].")}, + {"isoformat", (PyCFunction)time_isoformat, METH_NOARGS, + PyDoc_STR("Return string in ISO 8601 format, HH:MM:SS[.mmmmmm]" + "[+HH:MM].")}, - {"strftime", (PyCFunction)time_strftime, METH_VARARGS | METH_KEYWORDS, - PyDoc_STR("format -> strftime() style string.")}, + {"strftime", (PyCFunction)time_strftime, METH_VARARGS | METH_KEYWORDS, + PyDoc_STR("format -> strftime() style string.")}, - {"__format__", (PyCFunction)date_format, METH_VARARGS, - PyDoc_STR("Formats self with strftime.")}, + {"__format__", (PyCFunction)date_format, METH_VARARGS, + PyDoc_STR("Formats self with strftime.")}, - {"utcoffset", (PyCFunction)time_utcoffset, METH_NOARGS, - PyDoc_STR("Return self.tzinfo.utcoffset(self).")}, + {"utcoffset", (PyCFunction)time_utcoffset, METH_NOARGS, + PyDoc_STR("Return self.tzinfo.utcoffset(self).")}, - {"tzname", (PyCFunction)time_tzname, METH_NOARGS, - PyDoc_STR("Return self.tzinfo.tzname(self).")}, + {"tzname", (PyCFunction)time_tzname, METH_NOARGS, + PyDoc_STR("Return self.tzinfo.tzname(self).")}, - {"dst", (PyCFunction)time_dst, METH_NOARGS, - PyDoc_STR("Return self.tzinfo.dst(self).")}, + {"dst", (PyCFunction)time_dst, METH_NOARGS, + PyDoc_STR("Return self.tzinfo.dst(self).")}, - {"replace", (PyCFunction)time_replace, METH_VARARGS | METH_KEYWORDS, - PyDoc_STR("Return time with new specified fields.")}, + {"replace", (PyCFunction)time_replace, METH_VARARGS | METH_KEYWORDS, + PyDoc_STR("Return time with new specified fields.")}, - {"__reduce__", (PyCFunction)time_reduce, METH_NOARGS, - PyDoc_STR("__reduce__() -> (cls, state)")}, + {"__reduce__", (PyCFunction)time_reduce, METH_NOARGS, + PyDoc_STR("__reduce__() -> (cls, state)")}, - {NULL, NULL} + {NULL, NULL} }; static char time_doc[] = @@ -3457,58 +3457,58 @@ a tzinfo subclass. The remaining arguments may be ints or longs.\n"); static PyNumberMethods time_as_number = { - 0, /* nb_add */ - 0, /* nb_subtract */ - 0, /* nb_multiply */ - 0, /* nb_remainder */ - 0, /* nb_divmod */ - 0, /* nb_power */ - 0, /* nb_negative */ - 0, /* nb_positive */ - 0, /* nb_absolute */ - (inquiry)time_bool, /* nb_bool */ + 0, /* nb_add */ + 0, /* nb_subtract */ + 0, /* nb_multiply */ + 0, /* nb_remainder */ + 0, /* nb_divmod */ + 0, /* nb_power */ + 0, /* nb_negative */ + 0, /* nb_positive */ + 0, /* nb_absolute */ + (inquiry)time_bool, /* nb_bool */ }; static PyTypeObject PyDateTime_TimeType = { - PyVarObject_HEAD_INIT(NULL, 0) - "datetime.time", /* tp_name */ - sizeof(PyDateTime_Time), /* tp_basicsize */ - 0, /* tp_itemsize */ - (destructor)time_dealloc, /* tp_dealloc */ - 0, /* tp_print */ - 0, /* tp_getattr */ - 0, /* tp_setattr */ - 0, /* tp_reserved */ - (reprfunc)time_repr, /* tp_repr */ - &time_as_number, /* tp_as_number */ - 0, /* tp_as_sequence */ - 0, /* tp_as_mapping */ - (hashfunc)time_hash, /* tp_hash */ - 0, /* tp_call */ - (reprfunc)time_str, /* tp_str */ - PyObject_GenericGetAttr, /* tp_getattro */ - 0, /* tp_setattro */ - 0, /* tp_as_buffer */ - Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */ - time_doc, /* tp_doc */ - 0, /* tp_traverse */ - 0, /* tp_clear */ - time_richcompare, /* tp_richcompare */ - 0, /* tp_weaklistoffset */ - 0, /* tp_iter */ - 0, /* tp_iternext */ - time_methods, /* tp_methods */ - 0, /* tp_members */ - time_getset, /* tp_getset */ - 0, /* tp_base */ - 0, /* tp_dict */ - 0, /* tp_descr_get */ - 0, /* tp_descr_set */ - 0, /* tp_dictoffset */ - 0, /* tp_init */ - time_alloc, /* tp_alloc */ - time_new, /* tp_new */ - 0, /* tp_free */ + PyVarObject_HEAD_INIT(NULL, 0) + "datetime.time", /* tp_name */ + sizeof(PyDateTime_Time), /* tp_basicsize */ + 0, /* tp_itemsize */ + (destructor)time_dealloc, /* tp_dealloc */ + 0, /* tp_print */ + 0, /* tp_getattr */ + 0, /* tp_setattr */ + 0, /* tp_reserved */ + (reprfunc)time_repr, /* tp_repr */ + &time_as_number, /* tp_as_number */ + 0, /* tp_as_sequence */ + 0, /* tp_as_mapping */ + (hashfunc)time_hash, /* tp_hash */ + 0, /* tp_call */ + (reprfunc)time_str, /* tp_str */ + PyObject_GenericGetAttr, /* tp_getattro */ + 0, /* tp_setattro */ + 0, /* tp_as_buffer */ + Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */ + time_doc, /* tp_doc */ + 0, /* tp_traverse */ + 0, /* tp_clear */ + time_richcompare, /* tp_richcompare */ + 0, /* tp_weaklistoffset */ + 0, /* tp_iter */ + 0, /* tp_iternext */ + time_methods, /* tp_methods */ + 0, /* tp_members */ + time_getset, /* tp_getset */ + 0, /* tp_base */ + 0, /* tp_dict */ + 0, /* tp_descr_get */ + 0, /* tp_descr_set */ + 0, /* tp_dictoffset */ + 0, /* tp_init */ + time_alloc, /* tp_alloc */ + time_new, /* tp_new */ + 0, /* tp_free */ }; /* @@ -3522,42 +3522,42 @@ static PyObject * datetime_hour(PyDateTime_DateTime *self, void *unused) { - return PyLong_FromLong(DATE_GET_HOUR(self)); + return PyLong_FromLong(DATE_GET_HOUR(self)); } static PyObject * datetime_minute(PyDateTime_DateTime *self, void *unused) { - return PyLong_FromLong(DATE_GET_MINUTE(self)); + return PyLong_FromLong(DATE_GET_MINUTE(self)); } static PyObject * datetime_second(PyDateTime_DateTime *self, void *unused) { - return PyLong_FromLong(DATE_GET_SECOND(self)); + return PyLong_FromLong(DATE_GET_SECOND(self)); } static PyObject * datetime_microsecond(PyDateTime_DateTime *self, void *unused) { - return PyLong_FromLong(DATE_GET_MICROSECOND(self)); + return PyLong_FromLong(DATE_GET_MICROSECOND(self)); } static PyObject * datetime_tzinfo(PyDateTime_DateTime *self, void *unused) { - PyObject *result = HASTZINFO(self) ? self->tzinfo : Py_None; - Py_INCREF(result); - return result; + PyObject *result = HASTZINFO(self) ? self->tzinfo : Py_None; + Py_INCREF(result); + return result; } static PyGetSetDef datetime_getset[] = { - {"hour", (getter)datetime_hour}, - {"minute", (getter)datetime_minute}, - {"second", (getter)datetime_second}, - {"microsecond", (getter)datetime_microsecond}, - {"tzinfo", (getter)datetime_tzinfo}, - {NULL} + {"hour", (getter)datetime_hour}, + {"minute", (getter)datetime_minute}, + {"second", (getter)datetime_second}, + {"microsecond", (getter)datetime_microsecond}, + {"tzinfo", (getter)datetime_tzinfo}, + {NULL} }; /* @@ -3565,72 +3565,72 @@ */ static char *datetime_kws[] = { - "year", "month", "day", "hour", "minute", "second", - "microsecond", "tzinfo", NULL + "year", "month", "day", "hour", "minute", "second", + "microsecond", "tzinfo", NULL }; static PyObject * datetime_new(PyTypeObject *type, PyObject *args, PyObject *kw) { - PyObject *self = NULL; - PyObject *state; - int year; - int month; - int day; - int hour = 0; - int minute = 0; - int second = 0; - int usecond = 0; - PyObject *tzinfo = Py_None; - - /* Check for invocation from pickle with __getstate__ state */ - if (PyTuple_GET_SIZE(args) >= 1 && - PyTuple_GET_SIZE(args) <= 2 && - PyBytes_Check(state = PyTuple_GET_ITEM(args, 0)) && - PyBytes_GET_SIZE(state) == _PyDateTime_DATETIME_DATASIZE && - MONTH_IS_SANE(PyBytes_AS_STRING(state)[2])) - { - PyDateTime_DateTime *me; - char aware; - - if (PyTuple_GET_SIZE(args) == 2) { - tzinfo = PyTuple_GET_ITEM(args, 1); - if (check_tzinfo_subclass(tzinfo) < 0) { - PyErr_SetString(PyExc_TypeError, "bad " - "tzinfo state arg"); - return NULL; - } - } - aware = (char)(tzinfo != Py_None); - me = (PyDateTime_DateTime *) (type->tp_alloc(type , aware)); - if (me != NULL) { - char *pdata = PyBytes_AS_STRING(state); - - memcpy(me->data, pdata, _PyDateTime_DATETIME_DATASIZE); - me->hashcode = -1; - me->hastzinfo = aware; - if (aware) { - Py_INCREF(tzinfo); - me->tzinfo = tzinfo; - } - } - return (PyObject *)me; - } - - if (PyArg_ParseTupleAndKeywords(args, kw, "iii|iiiiO", datetime_kws, - &year, &month, &day, &hour, &minute, - &second, &usecond, &tzinfo)) { - if (check_date_args(year, month, day) < 0) - return NULL; - if (check_time_args(hour, minute, second, usecond) < 0) - return NULL; - if (check_tzinfo_subclass(tzinfo) < 0) - return NULL; - self = new_datetime_ex(year, month, day, - hour, minute, second, usecond, - tzinfo, type); - } - return self; + PyObject *self = NULL; + PyObject *state; + int year; + int month; + int day; + int hour = 0; + int minute = 0; + int second = 0; + int usecond = 0; + PyObject *tzinfo = Py_None; + + /* Check for invocation from pickle with __getstate__ state */ + if (PyTuple_GET_SIZE(args) >= 1 && + PyTuple_GET_SIZE(args) <= 2 && + PyBytes_Check(state = PyTuple_GET_ITEM(args, 0)) && + PyBytes_GET_SIZE(state) == _PyDateTime_DATETIME_DATASIZE && + MONTH_IS_SANE(PyBytes_AS_STRING(state)[2])) + { + PyDateTime_DateTime *me; + char aware; + + if (PyTuple_GET_SIZE(args) == 2) { + tzinfo = PyTuple_GET_ITEM(args, 1); + if (check_tzinfo_subclass(tzinfo) < 0) { + PyErr_SetString(PyExc_TypeError, "bad " + "tzinfo state arg"); + return NULL; + } + } + aware = (char)(tzinfo != Py_None); + me = (PyDateTime_DateTime *) (type->tp_alloc(type , aware)); + if (me != NULL) { + char *pdata = PyBytes_AS_STRING(state); + + memcpy(me->data, pdata, _PyDateTime_DATETIME_DATASIZE); + me->hashcode = -1; + me->hastzinfo = aware; + if (aware) { + Py_INCREF(tzinfo); + me->tzinfo = tzinfo; + } + } + return (PyObject *)me; + } + + if (PyArg_ParseTupleAndKeywords(args, kw, "iii|iiiiO", datetime_kws, + &year, &month, &day, &hour, &minute, + &second, &usecond, &tzinfo)) { + if (check_date_args(year, month, day) < 0) + return NULL; + if (check_time_args(hour, minute, second, usecond) < 0) + return NULL; + if (check_tzinfo_subclass(tzinfo) < 0) + return NULL; + self = new_datetime_ex(year, month, day, + hour, minute, second, usecond, + tzinfo, type); + } + return self; } /* TM_FUNC is the shared type of localtime() and gmtime(). */ @@ -3642,36 +3642,36 @@ */ static PyObject * datetime_from_timet_and_us(PyObject *cls, TM_FUNC f, time_t timet, int us, - PyObject *tzinfo) + PyObject *tzinfo) { - struct tm *tm; - PyObject *result = NULL; + struct tm *tm; + PyObject *result = NULL; - tm = f(&timet); - if (tm) { - /* The platform localtime/gmtime may insert leap seconds, - * indicated by tm->tm_sec > 59. We don't care about them, - * except to the extent that passing them on to the datetime - * constructor would raise ValueError for a reason that - * made no sense to the user. - */ - if (tm->tm_sec > 59) - tm->tm_sec = 59; - result = PyObject_CallFunction(cls, "iiiiiiiO", - tm->tm_year + 1900, - tm->tm_mon + 1, - tm->tm_mday, - tm->tm_hour, - tm->tm_min, - tm->tm_sec, - us, - tzinfo); - } - else - PyErr_SetString(PyExc_ValueError, - "timestamp out of range for " - "platform localtime()/gmtime() function"); - return result; + tm = f(&timet); + if (tm) { + /* The platform localtime/gmtime may insert leap seconds, + * indicated by tm->tm_sec > 59. We don't care about them, + * except to the extent that passing them on to the datetime + * constructor would raise ValueError for a reason that + * made no sense to the user. + */ + if (tm->tm_sec > 59) + tm->tm_sec = 59; + result = PyObject_CallFunction(cls, "iiiiiiiO", + tm->tm_year + 1900, + tm->tm_mon + 1, + tm->tm_mday, + tm->tm_hour, + tm->tm_min, + tm->tm_sec, + us, + tzinfo); + } + else + PyErr_SetString(PyExc_ValueError, + "timestamp out of range for " + "platform localtime()/gmtime() function"); + return result; } /* Internal helper. @@ -3683,31 +3683,31 @@ */ static PyObject * datetime_from_timestamp(PyObject *cls, TM_FUNC f, double timestamp, - PyObject *tzinfo) + PyObject *tzinfo) { - time_t timet; - double fraction; - int us; - - timet = _PyTime_DoubleToTimet(timestamp); - if (timet == (time_t)-1 && PyErr_Occurred()) - return NULL; - fraction = timestamp - (double)timet; - us = (int)round_to_long(fraction * 1e6); - if (us < 0) { - /* Truncation towards zero is not what we wanted - for negative numbers (Python's mod semantics) */ - timet -= 1; - us += 1000000; - } - /* If timestamp is less than one microsecond smaller than a - * full second, round up. Otherwise, ValueErrors are raised - * for some floats. */ - if (us == 1000000) { - timet += 1; - us = 0; - } - return datetime_from_timet_and_us(cls, f, timet, us, tzinfo); + time_t timet; + double fraction; + int us; + + timet = _PyTime_DoubleToTimet(timestamp); + if (timet == (time_t)-1 && PyErr_Occurred()) + return NULL; + fraction = timestamp - (double)timet; + us = (int)round_to_long(fraction * 1e6); + if (us < 0) { + /* Truncation towards zero is not what we wanted + for negative numbers (Python's mod semantics) */ + timet -= 1; + us += 1000000; + } + /* If timestamp is less than one microsecond smaller than a + * full second, round up. Otherwise, ValueErrors are raised + * for some floats. */ + if (us == 1000000) { + timet += 1; + us = 0; + } + return datetime_from_timet_and_us(cls, f, timet, us, tzinfo); } /* Internal helper. @@ -3718,36 +3718,36 @@ datetime_best_possible(PyObject *cls, TM_FUNC f, PyObject *tzinfo) { #ifdef HAVE_GETTIMEOFDAY - struct timeval t; + struct timeval t; #ifdef GETTIMEOFDAY_NO_TZ - gettimeofday(&t); + gettimeofday(&t); #else - gettimeofday(&t, (struct timezone *)NULL); + gettimeofday(&t, (struct timezone *)NULL); #endif - return datetime_from_timet_and_us(cls, f, t.tv_sec, (int)t.tv_usec, - tzinfo); + return datetime_from_timet_and_us(cls, f, t.tv_sec, (int)t.tv_usec, + tzinfo); + +#else /* ! HAVE_GETTIMEOFDAY */ + /* No flavor of gettimeofday exists on this platform. Python's + * time.time() does a lot of other platform tricks to get the + * best time it can on the platform, and we're not going to do + * better than that (if we could, the better code would belong + * in time.time()!) We're limited by the precision of a double, + * though. + */ + PyObject *time; + double dtime; -#else /* ! HAVE_GETTIMEOFDAY */ - /* No flavor of gettimeofday exists on this platform. Python's - * time.time() does a lot of other platform tricks to get the - * best time it can on the platform, and we're not going to do - * better than that (if we could, the better code would belong - * in time.time()!) We're limited by the precision of a double, - * though. - */ - PyObject *time; - double dtime; - - time = time_time(); - if (time == NULL) - return NULL; - dtime = PyFloat_AsDouble(time); - Py_DECREF(time); - if (dtime == -1.0 && PyErr_Occurred()) - return NULL; - return datetime_from_timestamp(cls, f, dtime, tzinfo); -#endif /* ! HAVE_GETTIMEOFDAY */ + time = time_time(); + if (time == NULL) + return NULL; + dtime = PyFloat_AsDouble(time); + Py_DECREF(time); + if (dtime == -1.0 && PyErr_Occurred()) + return NULL; + return datetime_from_timestamp(cls, f, dtime, tzinfo); +#endif /* ! HAVE_GETTIMEOFDAY */ } /* Return best possible local time -- this isn't constrained by the @@ -3756,26 +3756,26 @@ static PyObject * datetime_now(PyObject *cls, PyObject *args, PyObject *kw) { - PyObject *self; - PyObject *tzinfo = Py_None; - static char *keywords[] = {"tz", NULL}; - - if (! PyArg_ParseTupleAndKeywords(args, kw, "|O:now", keywords, - &tzinfo)) - return NULL; - if (check_tzinfo_subclass(tzinfo) < 0) - return NULL; - - self = datetime_best_possible(cls, - tzinfo == Py_None ? localtime : gmtime, - tzinfo); - if (self != NULL && tzinfo != Py_None) { - /* Convert UTC to tzinfo's zone. */ - PyObject *temp = self; - self = PyObject_CallMethod(tzinfo, "fromutc", "O", self); - Py_DECREF(temp); - } - return self; + PyObject *self; + PyObject *tzinfo = Py_None; + static char *keywords[] = {"tz", NULL}; + + if (! PyArg_ParseTupleAndKeywords(args, kw, "|O:now", keywords, + &tzinfo)) + return NULL; + if (check_tzinfo_subclass(tzinfo) < 0) + return NULL; + + self = datetime_best_possible(cls, + tzinfo == Py_None ? localtime : gmtime, + tzinfo); + if (self != NULL && tzinfo != Py_None) { + /* Convert UTC to tzinfo's zone. */ + PyObject *temp = self; + self = PyObject_CallMethod(tzinfo, "fromutc", "O", self); + Py_DECREF(temp); + } + return self; } /* Return best possible UTC time -- this isn't constrained by the @@ -3784,155 +3784,155 @@ static PyObject * datetime_utcnow(PyObject *cls, PyObject *dummy) { - return datetime_best_possible(cls, gmtime, Py_None); + return datetime_best_possible(cls, gmtime, Py_None); } /* Return new local datetime from timestamp (Python timestamp -- a double). */ static PyObject * datetime_fromtimestamp(PyObject *cls, PyObject *args, PyObject *kw) { - PyObject *self; - double timestamp; - PyObject *tzinfo = Py_None; - static char *keywords[] = {"timestamp", "tz", NULL}; - - if (! PyArg_ParseTupleAndKeywords(args, kw, "d|O:fromtimestamp", - keywords, ×tamp, &tzinfo)) - return NULL; - if (check_tzinfo_subclass(tzinfo) < 0) - return NULL; - - self = datetime_from_timestamp(cls, - tzinfo == Py_None ? localtime : gmtime, - timestamp, - tzinfo); - if (self != NULL && tzinfo != Py_None) { - /* Convert UTC to tzinfo's zone. */ - PyObject *temp = self; - self = PyObject_CallMethod(tzinfo, "fromutc", "O", self); - Py_DECREF(temp); - } - return self; + PyObject *self; + double timestamp; + PyObject *tzinfo = Py_None; + static char *keywords[] = {"timestamp", "tz", NULL}; + + if (! PyArg_ParseTupleAndKeywords(args, kw, "d|O:fromtimestamp", + keywords, ×tamp, &tzinfo)) + return NULL; + if (check_tzinfo_subclass(tzinfo) < 0) + return NULL; + + self = datetime_from_timestamp(cls, + tzinfo == Py_None ? localtime : gmtime, + timestamp, + tzinfo); + if (self != NULL && tzinfo != Py_None) { + /* Convert UTC to tzinfo's zone. */ + PyObject *temp = self; + self = PyObject_CallMethod(tzinfo, "fromutc", "O", self); + Py_DECREF(temp); + } + return self; } /* Return new UTC datetime from timestamp (Python timestamp -- a double). */ static PyObject * datetime_utcfromtimestamp(PyObject *cls, PyObject *args) { - double timestamp; - PyObject *result = NULL; + double timestamp; + PyObject *result = NULL; - if (PyArg_ParseTuple(args, "d:utcfromtimestamp", ×tamp)) - result = datetime_from_timestamp(cls, gmtime, timestamp, - Py_None); - return result; + if (PyArg_ParseTuple(args, "d:utcfromtimestamp", ×tamp)) + result = datetime_from_timestamp(cls, gmtime, timestamp, + Py_None); + return result; } /* Return new datetime from time.strptime(). */ static PyObject * datetime_strptime(PyObject *cls, PyObject *args) { - static PyObject *module = NULL; - PyObject *result = NULL, *obj, *st = NULL, *frac = NULL; - const Py_UNICODE *string, *format; - - if (!PyArg_ParseTuple(args, "uu:strptime", &string, &format)) - return NULL; - - if (module == NULL && - (module = PyImport_ImportModuleNoBlock("_strptime")) == NULL) - return NULL; - - /* _strptime._strptime returns a two-element tuple. The first - element is a time.struct_time object. The second is the - microseconds (which are not defined for time.struct_time). */ - obj = PyObject_CallMethod(module, "_strptime", "uu", string, format); - if (obj != NULL) { - int i, good_timetuple = 1; - long int ia[7]; - if (PySequence_Check(obj) && PySequence_Size(obj) == 2) { - st = PySequence_GetItem(obj, 0); - frac = PySequence_GetItem(obj, 1); - if (st == NULL || frac == NULL) - good_timetuple = 0; - /* copy y/m/d/h/m/s values out of the - time.struct_time */ - if (good_timetuple && - PySequence_Check(st) && - PySequence_Size(st) >= 6) { - for (i=0; i < 6; i++) { - PyObject *p = PySequence_GetItem(st, i); - if (p == NULL) { - good_timetuple = 0; - break; - } - if (PyLong_Check(p)) - ia[i] = PyLong_AsLong(p); - else - good_timetuple = 0; - Py_DECREF(p); - } -/* if (PyLong_CheckExact(p)) { - ia[i] = PyLong_AsLongAndOverflow(p, &overflow); - if (overflow) - good_timetuple = 0; - } - else - good_timetuple = 0; - Py_DECREF(p); -*/ } - else - good_timetuple = 0; - /* follow that up with a little dose of microseconds */ - if (PyLong_Check(frac)) - ia[6] = PyLong_AsLong(frac); - else - good_timetuple = 0; - } - else - good_timetuple = 0; - if (good_timetuple) - result = PyObject_CallFunction(cls, "iiiiiii", - ia[0], ia[1], ia[2], - ia[3], ia[4], ia[5], - ia[6]); - else - PyErr_SetString(PyExc_ValueError, - "unexpected value from _strptime._strptime"); - } - Py_XDECREF(obj); - Py_XDECREF(st); - Py_XDECREF(frac); - return result; + static PyObject *module = NULL; + PyObject *result = NULL, *obj, *st = NULL, *frac = NULL; + const Py_UNICODE *string, *format; + + if (!PyArg_ParseTuple(args, "uu:strptime", &string, &format)) + return NULL; + + if (module == NULL && + (module = PyImport_ImportModuleNoBlock("_strptime")) == NULL) + return NULL; + + /* _strptime._strptime returns a two-element tuple. The first + element is a time.struct_time object. The second is the + microseconds (which are not defined for time.struct_time). */ + obj = PyObject_CallMethod(module, "_strptime", "uu", string, format); + if (obj != NULL) { + int i, good_timetuple = 1; + long int ia[7]; + if (PySequence_Check(obj) && PySequence_Size(obj) == 2) { + st = PySequence_GetItem(obj, 0); + frac = PySequence_GetItem(obj, 1); + if (st == NULL || frac == NULL) + good_timetuple = 0; + /* copy y/m/d/h/m/s values out of the + time.struct_time */ + if (good_timetuple && + PySequence_Check(st) && + PySequence_Size(st) >= 6) { + for (i=0; i < 6; i++) { + PyObject *p = PySequence_GetItem(st, i); + if (p == NULL) { + good_timetuple = 0; + break; + } + if (PyLong_Check(p)) + ia[i] = PyLong_AsLong(p); + else + good_timetuple = 0; + Py_DECREF(p); + } +/* if (PyLong_CheckExact(p)) { + ia[i] = PyLong_AsLongAndOverflow(p, &overflow); + if (overflow) + good_timetuple = 0; + } + else + good_timetuple = 0; + Py_DECREF(p); +*/ } + else + good_timetuple = 0; + /* follow that up with a little dose of microseconds */ + if (PyLong_Check(frac)) + ia[6] = PyLong_AsLong(frac); + else + good_timetuple = 0; + } + else + good_timetuple = 0; + if (good_timetuple) + result = PyObject_CallFunction(cls, "iiiiiii", + ia[0], ia[1], ia[2], + ia[3], ia[4], ia[5], + ia[6]); + else + PyErr_SetString(PyExc_ValueError, + "unexpected value from _strptime._strptime"); + } + Py_XDECREF(obj); + Py_XDECREF(st); + Py_XDECREF(frac); + return result; } /* Return new datetime from date/datetime and time arguments. */ static PyObject * datetime_combine(PyObject *cls, PyObject *args, PyObject *kw) { - static char *keywords[] = {"date", "time", NULL}; - PyObject *date; - PyObject *time; - PyObject *result = NULL; - - if (PyArg_ParseTupleAndKeywords(args, kw, "O!O!:combine", keywords, - &PyDateTime_DateType, &date, - &PyDateTime_TimeType, &time)) { - PyObject *tzinfo = Py_None; - - if (HASTZINFO(time)) - tzinfo = ((PyDateTime_Time *)time)->tzinfo; - result = PyObject_CallFunction(cls, "iiiiiiiO", - GET_YEAR(date), - GET_MONTH(date), - GET_DAY(date), - TIME_GET_HOUR(time), - TIME_GET_MINUTE(time), - TIME_GET_SECOND(time), - TIME_GET_MICROSECOND(time), - tzinfo); - } - return result; + static char *keywords[] = {"date", "time", NULL}; + PyObject *date; + PyObject *time; + PyObject *result = NULL; + + if (PyArg_ParseTupleAndKeywords(args, kw, "O!O!:combine", keywords, + &PyDateTime_DateType, &date, + &PyDateTime_TimeType, &time)) { + PyObject *tzinfo = Py_None; + + if (HASTZINFO(time)) + tzinfo = ((PyDateTime_Time *)time)->tzinfo; + result = PyObject_CallFunction(cls, "iiiiiiiO", + GET_YEAR(date), + GET_MONTH(date), + GET_DAY(date), + TIME_GET_HOUR(time), + TIME_GET_MINUTE(time), + TIME_GET_SECOND(time), + TIME_GET_MICROSECOND(time), + tzinfo); + } + return result; } /* @@ -3942,10 +3942,10 @@ static void datetime_dealloc(PyDateTime_DateTime *self) { - if (HASTZINFO(self)) { - Py_XDECREF(self->tzinfo); - } - Py_TYPE(self)->tp_free((PyObject *)self); + if (HASTZINFO(self)) { + Py_XDECREF(self->tzinfo); + } + Py_TYPE(self)->tp_free((PyObject *)self); } /* @@ -3955,20 +3955,20 @@ /* These are all METH_NOARGS, so don't need to check the arglist. */ static PyObject * datetime_utcoffset(PyDateTime_DateTime *self, PyObject *unused) { - return offset_as_timedelta(HASTZINFO(self) ? self->tzinfo : Py_None, - "utcoffset", (PyObject *)self); + return offset_as_timedelta(HASTZINFO(self) ? self->tzinfo : Py_None, + "utcoffset", (PyObject *)self); } static PyObject * datetime_dst(PyDateTime_DateTime *self, PyObject *unused) { - return offset_as_timedelta(HASTZINFO(self) ? self->tzinfo : Py_None, - "dst", (PyObject *)self); + return offset_as_timedelta(HASTZINFO(self) ? self->tzinfo : Py_None, + "dst", (PyObject *)self); } static PyObject * datetime_tzname(PyDateTime_DateTime *self, PyObject *unused) { - return call_tzname(HASTZINFO(self) ? self->tzinfo : Py_None, - (PyObject *)self); + return call_tzname(HASTZINFO(self) ? self->tzinfo : Py_None, + (PyObject *)self); } /* @@ -3980,112 +3980,112 @@ */ static PyObject * add_datetime_timedelta(PyDateTime_DateTime *date, PyDateTime_Delta *delta, - int factor) + int factor) { - /* Note that the C-level additions can't overflow, because of - * invariant bounds on the member values. - */ - int year = GET_YEAR(date); - int month = GET_MONTH(date); - int day = GET_DAY(date) + GET_TD_DAYS(delta) * factor; - int hour = DATE_GET_HOUR(date); - int minute = DATE_GET_MINUTE(date); - int second = DATE_GET_SECOND(date) + GET_TD_SECONDS(delta) * factor; - int microsecond = DATE_GET_MICROSECOND(date) + - GET_TD_MICROSECONDS(delta) * factor; - - assert(factor == 1 || factor == -1); - if (normalize_datetime(&year, &month, &day, - &hour, &minute, &second, µsecond) < 0) - return NULL; - else - return new_datetime(year, month, day, - hour, minute, second, microsecond, - HASTZINFO(date) ? date->tzinfo : Py_None); + /* Note that the C-level additions can't overflow, because of + * invariant bounds on the member values. + */ + int year = GET_YEAR(date); + int month = GET_MONTH(date); + int day = GET_DAY(date) + GET_TD_DAYS(delta) * factor; + int hour = DATE_GET_HOUR(date); + int minute = DATE_GET_MINUTE(date); + int second = DATE_GET_SECOND(date) + GET_TD_SECONDS(delta) * factor; + int microsecond = DATE_GET_MICROSECOND(date) + + GET_TD_MICROSECONDS(delta) * factor; + + assert(factor == 1 || factor == -1); + if (normalize_datetime(&year, &month, &day, + &hour, &minute, &second, µsecond) < 0) + return NULL; + else + return new_datetime(year, month, day, + hour, minute, second, microsecond, + HASTZINFO(date) ? date->tzinfo : Py_None); } static PyObject * datetime_add(PyObject *left, PyObject *right) { - if (PyDateTime_Check(left)) { - /* datetime + ??? */ - if (PyDelta_Check(right)) - /* datetime + delta */ - return add_datetime_timedelta( - (PyDateTime_DateTime *)left, - (PyDateTime_Delta *)right, - 1); - } - else if (PyDelta_Check(left)) { - /* delta + datetime */ - return add_datetime_timedelta((PyDateTime_DateTime *) right, - (PyDateTime_Delta *) left, - 1); - } - Py_INCREF(Py_NotImplemented); - return Py_NotImplemented; + if (PyDateTime_Check(left)) { + /* datetime + ??? */ + if (PyDelta_Check(right)) + /* datetime + delta */ + return add_datetime_timedelta( + (PyDateTime_DateTime *)left, + (PyDateTime_Delta *)right, + 1); + } + else if (PyDelta_Check(left)) { + /* delta + datetime */ + return add_datetime_timedelta((PyDateTime_DateTime *) right, + (PyDateTime_Delta *) left, + 1); + } + Py_INCREF(Py_NotImplemented); + return Py_NotImplemented; } static PyObject * datetime_subtract(PyObject *left, PyObject *right) { - PyObject *result = Py_NotImplemented; + PyObject *result = Py_NotImplemented; - if (PyDateTime_Check(left)) { - /* datetime - ??? */ - if (PyDateTime_Check(right)) { - /* datetime - datetime */ - naivety n1, n2; - int offset1, offset2; - int delta_d, delta_s, delta_us; - - if (classify_two_utcoffsets(left, &offset1, &n1, left, - right, &offset2, &n2, - right) < 0) - return NULL; - assert(n1 != OFFSET_UNKNOWN && n2 != OFFSET_UNKNOWN); - if (n1 != n2) { - PyErr_SetString(PyExc_TypeError, - "can't subtract offset-naive and " - "offset-aware datetimes"); - return NULL; - } - delta_d = ymd_to_ord(GET_YEAR(left), - GET_MONTH(left), - GET_DAY(left)) - - ymd_to_ord(GET_YEAR(right), - GET_MONTH(right), - GET_DAY(right)); - /* These can't overflow, since the values are - * normalized. At most this gives the number of - * seconds in one day. - */ - delta_s = (DATE_GET_HOUR(left) - - DATE_GET_HOUR(right)) * 3600 + - (DATE_GET_MINUTE(left) - - DATE_GET_MINUTE(right)) * 60 + - (DATE_GET_SECOND(left) - - DATE_GET_SECOND(right)); - delta_us = DATE_GET_MICROSECOND(left) - - DATE_GET_MICROSECOND(right); - /* (left - offset1) - (right - offset2) = - * (left - right) + (offset2 - offset1) - */ - delta_s += (offset2 - offset1) * 60; - result = new_delta(delta_d, delta_s, delta_us, 1); - } - else if (PyDelta_Check(right)) { - /* datetime - delta */ - result = add_datetime_timedelta( - (PyDateTime_DateTime *)left, - (PyDateTime_Delta *)right, - -1); - } - } - - if (result == Py_NotImplemented) - Py_INCREF(result); - return result; + if (PyDateTime_Check(left)) { + /* datetime - ??? */ + if (PyDateTime_Check(right)) { + /* datetime - datetime */ + naivety n1, n2; + int offset1, offset2; + int delta_d, delta_s, delta_us; + + if (classify_two_utcoffsets(left, &offset1, &n1, left, + right, &offset2, &n2, + right) < 0) + return NULL; + assert(n1 != OFFSET_UNKNOWN && n2 != OFFSET_UNKNOWN); + if (n1 != n2) { + PyErr_SetString(PyExc_TypeError, + "can't subtract offset-naive and " + "offset-aware datetimes"); + return NULL; + } + delta_d = ymd_to_ord(GET_YEAR(left), + GET_MONTH(left), + GET_DAY(left)) - + ymd_to_ord(GET_YEAR(right), + GET_MONTH(right), + GET_DAY(right)); + /* These can't overflow, since the values are + * normalized. At most this gives the number of + * seconds in one day. + */ + delta_s = (DATE_GET_HOUR(left) - + DATE_GET_HOUR(right)) * 3600 + + (DATE_GET_MINUTE(left) - + DATE_GET_MINUTE(right)) * 60 + + (DATE_GET_SECOND(left) - + DATE_GET_SECOND(right)); + delta_us = DATE_GET_MICROSECOND(left) - + DATE_GET_MICROSECOND(right); + /* (left - offset1) - (right - offset2) = + * (left - right) + (offset2 - offset1) + */ + delta_s += (offset2 - offset1) * 60; + result = new_delta(delta_d, delta_s, delta_us, 1); + } + else if (PyDelta_Check(right)) { + /* datetime - delta */ + result = add_datetime_timedelta( + (PyDateTime_DateTime *)left, + (PyDateTime_Delta *)right, + -1); + } + } + + if (result == Py_NotImplemented) + Py_INCREF(result); + return result; } /* Various ways to turn a datetime into a string. */ @@ -4093,88 +4093,88 @@ static PyObject * datetime_repr(PyDateTime_DateTime *self) { - const char *type_name = Py_TYPE(self)->tp_name; - PyObject *baserepr; + const char *type_name = Py_TYPE(self)->tp_name; + PyObject *baserepr; - if (DATE_GET_MICROSECOND(self)) { - baserepr = PyUnicode_FromFormat( - "%s(%d, %d, %d, %d, %d, %d, %d)", - type_name, - GET_YEAR(self), GET_MONTH(self), GET_DAY(self), - DATE_GET_HOUR(self), DATE_GET_MINUTE(self), - DATE_GET_SECOND(self), - DATE_GET_MICROSECOND(self)); - } - else if (DATE_GET_SECOND(self)) { - baserepr = PyUnicode_FromFormat( - "%s(%d, %d, %d, %d, %d, %d)", - type_name, - GET_YEAR(self), GET_MONTH(self), GET_DAY(self), - DATE_GET_HOUR(self), DATE_GET_MINUTE(self), - DATE_GET_SECOND(self)); - } - else { - baserepr = PyUnicode_FromFormat( - "%s(%d, %d, %d, %d, %d)", - type_name, - GET_YEAR(self), GET_MONTH(self), GET_DAY(self), - DATE_GET_HOUR(self), DATE_GET_MINUTE(self)); - } - if (baserepr == NULL || ! HASTZINFO(self)) - return baserepr; - return append_keyword_tzinfo(baserepr, self->tzinfo); + if (DATE_GET_MICROSECOND(self)) { + baserepr = PyUnicode_FromFormat( + "%s(%d, %d, %d, %d, %d, %d, %d)", + type_name, + GET_YEAR(self), GET_MONTH(self), GET_DAY(self), + DATE_GET_HOUR(self), DATE_GET_MINUTE(self), + DATE_GET_SECOND(self), + DATE_GET_MICROSECOND(self)); + } + else if (DATE_GET_SECOND(self)) { + baserepr = PyUnicode_FromFormat( + "%s(%d, %d, %d, %d, %d, %d)", + type_name, + GET_YEAR(self), GET_MONTH(self), GET_DAY(self), + DATE_GET_HOUR(self), DATE_GET_MINUTE(self), + DATE_GET_SECOND(self)); + } + else { + baserepr = PyUnicode_FromFormat( + "%s(%d, %d, %d, %d, %d)", + type_name, + GET_YEAR(self), GET_MONTH(self), GET_DAY(self), + DATE_GET_HOUR(self), DATE_GET_MINUTE(self)); + } + if (baserepr == NULL || ! HASTZINFO(self)) + return baserepr; + return append_keyword_tzinfo(baserepr, self->tzinfo); } static PyObject * datetime_str(PyDateTime_DateTime *self) { - return PyObject_CallMethod((PyObject *)self, "isoformat", "(s)", " "); + return PyObject_CallMethod((PyObject *)self, "isoformat", "(s)", " "); } static PyObject * datetime_isoformat(PyDateTime_DateTime *self, PyObject *args, PyObject *kw) { - int sep = 'T'; - static char *keywords[] = {"sep", NULL}; - char buffer[100]; - PyObject *result; - int us = DATE_GET_MICROSECOND(self); - - if (!PyArg_ParseTupleAndKeywords(args, kw, "|C:isoformat", keywords, &sep)) - return NULL; - if (us) - result = PyUnicode_FromFormat("%04d-%02d-%02d%c%02d:%02d:%02d.%06d", - GET_YEAR(self), GET_MONTH(self), - GET_DAY(self), (int)sep, - DATE_GET_HOUR(self), DATE_GET_MINUTE(self), - DATE_GET_SECOND(self), us); - else - result = PyUnicode_FromFormat("%04d-%02d-%02d%c%02d:%02d:%02d", - GET_YEAR(self), GET_MONTH(self), - GET_DAY(self), (int)sep, - DATE_GET_HOUR(self), DATE_GET_MINUTE(self), - DATE_GET_SECOND(self)); - - if (!result || !HASTZINFO(self)) - return result; - - /* We need to append the UTC offset. */ - if (format_utcoffset(buffer, sizeof(buffer), ":", self->tzinfo, - (PyObject *)self) < 0) { - Py_DECREF(result); - return NULL; - } - PyUnicode_AppendAndDel(&result, PyUnicode_FromString(buffer)); - return result; + int sep = 'T'; + static char *keywords[] = {"sep", NULL}; + char buffer[100]; + PyObject *result; + int us = DATE_GET_MICROSECOND(self); + + if (!PyArg_ParseTupleAndKeywords(args, kw, "|C:isoformat", keywords, &sep)) + return NULL; + if (us) + result = PyUnicode_FromFormat("%04d-%02d-%02d%c%02d:%02d:%02d.%06d", + GET_YEAR(self), GET_MONTH(self), + GET_DAY(self), (int)sep, + DATE_GET_HOUR(self), DATE_GET_MINUTE(self), + DATE_GET_SECOND(self), us); + else + result = PyUnicode_FromFormat("%04d-%02d-%02d%c%02d:%02d:%02d", + GET_YEAR(self), GET_MONTH(self), + GET_DAY(self), (int)sep, + DATE_GET_HOUR(self), DATE_GET_MINUTE(self), + DATE_GET_SECOND(self)); + + if (!result || !HASTZINFO(self)) + return result; + + /* We need to append the UTC offset. */ + if (format_utcoffset(buffer, sizeof(buffer), ":", self->tzinfo, + (PyObject *)self) < 0) { + Py_DECREF(result); + return NULL; + } + PyUnicode_AppendAndDel(&result, PyUnicode_FromString(buffer)); + return result; } static PyObject * datetime_ctime(PyDateTime_DateTime *self) { - return format_ctime((PyDateTime_Date *)self, - DATE_GET_HOUR(self), - DATE_GET_MINUTE(self), - DATE_GET_SECOND(self)); + return format_ctime((PyDateTime_Date *)self, + DATE_GET_HOUR(self), + DATE_GET_MINUTE(self), + DATE_GET_SECOND(self)); } /* Miscellaneous methods. */ @@ -4182,292 +4182,292 @@ static PyObject * datetime_richcompare(PyObject *self, PyObject *other, int op) { - int diff; - naivety n1, n2; - int offset1, offset2; - - if (! PyDateTime_Check(other)) { - if (PyDate_Check(other)) { - /* Prevent invocation of date_richcompare. We want to - return NotImplemented here to give the other object - a chance. But since DateTime is a subclass of - Date, if the other object is a Date, it would - compute an ordering based on the date part alone, - and we don't want that. So force unequal or - uncomparable here in that case. */ - if (op == Py_EQ) - Py_RETURN_FALSE; - if (op == Py_NE) - Py_RETURN_TRUE; - return cmperror(self, other); - } - Py_INCREF(Py_NotImplemented); - return Py_NotImplemented; - } - - if (classify_two_utcoffsets(self, &offset1, &n1, self, - other, &offset2, &n2, other) < 0) - return NULL; - assert(n1 != OFFSET_UNKNOWN && n2 != OFFSET_UNKNOWN); - /* If they're both naive, or both aware and have the same offsets, - * we get off cheap. Note that if they're both naive, offset1 == - * offset2 == 0 at this point. - */ - if (n1 == n2 && offset1 == offset2) { - diff = memcmp(((PyDateTime_DateTime *)self)->data, - ((PyDateTime_DateTime *)other)->data, - _PyDateTime_DATETIME_DATASIZE); - return diff_to_bool(diff, op); - } - - if (n1 == OFFSET_AWARE && n2 == OFFSET_AWARE) { - PyDateTime_Delta *delta; - - assert(offset1 != offset2); /* else last "if" handled it */ - delta = (PyDateTime_Delta *)datetime_subtract((PyObject *)self, - other); - if (delta == NULL) - return NULL; - diff = GET_TD_DAYS(delta); - if (diff == 0) - diff = GET_TD_SECONDS(delta) | - GET_TD_MICROSECONDS(delta); - Py_DECREF(delta); - return diff_to_bool(diff, op); - } - - assert(n1 != n2); - PyErr_SetString(PyExc_TypeError, - "can't compare offset-naive and " - "offset-aware datetimes"); - return NULL; + int diff; + naivety n1, n2; + int offset1, offset2; + + if (! PyDateTime_Check(other)) { + if (PyDate_Check(other)) { + /* Prevent invocation of date_richcompare. We want to + return NotImplemented here to give the other object + a chance. But since DateTime is a subclass of + Date, if the other object is a Date, it would + compute an ordering based on the date part alone, + and we don't want that. So force unequal or + uncomparable here in that case. */ + if (op == Py_EQ) + Py_RETURN_FALSE; + if (op == Py_NE) + Py_RETURN_TRUE; + return cmperror(self, other); + } + Py_INCREF(Py_NotImplemented); + return Py_NotImplemented; + } + + if (classify_two_utcoffsets(self, &offset1, &n1, self, + other, &offset2, &n2, other) < 0) + return NULL; + assert(n1 != OFFSET_UNKNOWN && n2 != OFFSET_UNKNOWN); + /* If they're both naive, or both aware and have the same offsets, + * we get off cheap. Note that if they're both naive, offset1 == + * offset2 == 0 at this point. + */ + if (n1 == n2 && offset1 == offset2) { + diff = memcmp(((PyDateTime_DateTime *)self)->data, + ((PyDateTime_DateTime *)other)->data, + _PyDateTime_DATETIME_DATASIZE); + return diff_to_bool(diff, op); + } + + if (n1 == OFFSET_AWARE && n2 == OFFSET_AWARE) { + PyDateTime_Delta *delta; + + assert(offset1 != offset2); /* else last "if" handled it */ + delta = (PyDateTime_Delta *)datetime_subtract((PyObject *)self, + other); + if (delta == NULL) + return NULL; + diff = GET_TD_DAYS(delta); + if (diff == 0) + diff = GET_TD_SECONDS(delta) | + GET_TD_MICROSECONDS(delta); + Py_DECREF(delta); + return diff_to_bool(diff, op); + } + + assert(n1 != n2); + PyErr_SetString(PyExc_TypeError, + "can't compare offset-naive and " + "offset-aware datetimes"); + return NULL; } static long datetime_hash(PyDateTime_DateTime *self) { - if (self->hashcode == -1) { - naivety n; - int offset; - PyObject *temp; - - n = classify_utcoffset((PyObject *)self, (PyObject *)self, - &offset); - assert(n != OFFSET_UNKNOWN); - if (n == OFFSET_ERROR) - return -1; - - /* Reduce this to a hash of another object. */ - if (n == OFFSET_NAIVE) { - self->hashcode = generic_hash( - (unsigned char *)self->data, _PyDateTime_DATETIME_DATASIZE); - return self->hashcode; - } - else { - int days; - int seconds; - - assert(n == OFFSET_AWARE); - assert(HASTZINFO(self)); - days = ymd_to_ord(GET_YEAR(self), - GET_MONTH(self), - GET_DAY(self)); - seconds = DATE_GET_HOUR(self) * 3600 + - (DATE_GET_MINUTE(self) - offset) * 60 + - DATE_GET_SECOND(self); - temp = new_delta(days, - seconds, - DATE_GET_MICROSECOND(self), - 1); - } - if (temp != NULL) { - self->hashcode = PyObject_Hash(temp); - Py_DECREF(temp); - } - } - return self->hashcode; + if (self->hashcode == -1) { + naivety n; + int offset; + PyObject *temp; + + n = classify_utcoffset((PyObject *)self, (PyObject *)self, + &offset); + assert(n != OFFSET_UNKNOWN); + if (n == OFFSET_ERROR) + return -1; + + /* Reduce this to a hash of another object. */ + if (n == OFFSET_NAIVE) { + self->hashcode = generic_hash( + (unsigned char *)self->data, _PyDateTime_DATETIME_DATASIZE); + return self->hashcode; + } + else { + int days; + int seconds; + + assert(n == OFFSET_AWARE); + assert(HASTZINFO(self)); + days = ymd_to_ord(GET_YEAR(self), + GET_MONTH(self), + GET_DAY(self)); + seconds = DATE_GET_HOUR(self) * 3600 + + (DATE_GET_MINUTE(self) - offset) * 60 + + DATE_GET_SECOND(self); + temp = new_delta(days, + seconds, + DATE_GET_MICROSECOND(self), + 1); + } + if (temp != NULL) { + self->hashcode = PyObject_Hash(temp); + Py_DECREF(temp); + } + } + return self->hashcode; } static PyObject * datetime_replace(PyDateTime_DateTime *self, PyObject *args, PyObject *kw) { - PyObject *clone; - PyObject *tuple; - int y = GET_YEAR(self); - int m = GET_MONTH(self); - int d = GET_DAY(self); - int hh = DATE_GET_HOUR(self); - int mm = DATE_GET_MINUTE(self); - int ss = DATE_GET_SECOND(self); - int us = DATE_GET_MICROSECOND(self); - PyObject *tzinfo = HASTZINFO(self) ? self->tzinfo : Py_None; - - if (! PyArg_ParseTupleAndKeywords(args, kw, "|iiiiiiiO:replace", - datetime_kws, - &y, &m, &d, &hh, &mm, &ss, &us, - &tzinfo)) - return NULL; - tuple = Py_BuildValue("iiiiiiiO", y, m, d, hh, mm, ss, us, tzinfo); - if (tuple == NULL) - return NULL; - clone = datetime_new(Py_TYPE(self), tuple, NULL); - Py_DECREF(tuple); - return clone; + PyObject *clone; + PyObject *tuple; + int y = GET_YEAR(self); + int m = GET_MONTH(self); + int d = GET_DAY(self); + int hh = DATE_GET_HOUR(self); + int mm = DATE_GET_MINUTE(self); + int ss = DATE_GET_SECOND(self); + int us = DATE_GET_MICROSECOND(self); + PyObject *tzinfo = HASTZINFO(self) ? self->tzinfo : Py_None; + + if (! PyArg_ParseTupleAndKeywords(args, kw, "|iiiiiiiO:replace", + datetime_kws, + &y, &m, &d, &hh, &mm, &ss, &us, + &tzinfo)) + return NULL; + tuple = Py_BuildValue("iiiiiiiO", y, m, d, hh, mm, ss, us, tzinfo); + if (tuple == NULL) + return NULL; + clone = datetime_new(Py_TYPE(self), tuple, NULL); + Py_DECREF(tuple); + return clone; } static PyObject * datetime_astimezone(PyDateTime_DateTime *self, PyObject *args, PyObject *kw) { - int y, m, d, hh, mm, ss, us; - PyObject *result; - int offset, none; - - PyObject *tzinfo; - static char *keywords[] = {"tz", NULL}; - - if (! PyArg_ParseTupleAndKeywords(args, kw, "O!:astimezone", keywords, - &PyDateTime_TZInfoType, &tzinfo)) - return NULL; - - if (!HASTZINFO(self) || self->tzinfo == Py_None) - goto NeedAware; - - /* Conversion to self's own time zone is a NOP. */ - if (self->tzinfo == tzinfo) { - Py_INCREF(self); - return (PyObject *)self; - } + int y, m, d, hh, mm, ss, us; + PyObject *result; + int offset, none; - /* Convert self to UTC. */ - offset = call_utcoffset(self->tzinfo, (PyObject *)self, &none); - if (offset == -1 && PyErr_Occurred()) - return NULL; - if (none) - goto NeedAware; + PyObject *tzinfo; + static char *keywords[] = {"tz", NULL}; - y = GET_YEAR(self); - m = GET_MONTH(self); - d = GET_DAY(self); - hh = DATE_GET_HOUR(self); - mm = DATE_GET_MINUTE(self); - ss = DATE_GET_SECOND(self); - us = DATE_GET_MICROSECOND(self); - - mm -= offset; - if ((mm < 0 || mm >= 60) && - normalize_datetime(&y, &m, &d, &hh, &mm, &ss, &us) < 0) - return NULL; - - /* Attach new tzinfo and let fromutc() do the rest. */ - result = new_datetime(y, m, d, hh, mm, ss, us, tzinfo); - if (result != NULL) { - PyObject *temp = result; - - result = PyObject_CallMethod(tzinfo, "fromutc", "O", temp); - Py_DECREF(temp); - } - return result; + if (! PyArg_ParseTupleAndKeywords(args, kw, "O!:astimezone", keywords, + &PyDateTime_TZInfoType, &tzinfo)) + return NULL; + + if (!HASTZINFO(self) || self->tzinfo == Py_None) + goto NeedAware; + + /* Conversion to self's own time zone is a NOP. */ + if (self->tzinfo == tzinfo) { + Py_INCREF(self); + return (PyObject *)self; + } + + /* Convert self to UTC. */ + offset = call_utcoffset(self->tzinfo, (PyObject *)self, &none); + if (offset == -1 && PyErr_Occurred()) + return NULL; + if (none) + goto NeedAware; + + y = GET_YEAR(self); + m = GET_MONTH(self); + d = GET_DAY(self); + hh = DATE_GET_HOUR(self); + mm = DATE_GET_MINUTE(self); + ss = DATE_GET_SECOND(self); + us = DATE_GET_MICROSECOND(self); + + mm -= offset; + if ((mm < 0 || mm >= 60) && + normalize_datetime(&y, &m, &d, &hh, &mm, &ss, &us) < 0) + return NULL; + + /* Attach new tzinfo and let fromutc() do the rest. */ + result = new_datetime(y, m, d, hh, mm, ss, us, tzinfo); + if (result != NULL) { + PyObject *temp = result; + + result = PyObject_CallMethod(tzinfo, "fromutc", "O", temp); + Py_DECREF(temp); + } + return result; NeedAware: - PyErr_SetString(PyExc_ValueError, "astimezone() cannot be applied to " - "a naive datetime"); - return NULL; + PyErr_SetString(PyExc_ValueError, "astimezone() cannot be applied to " + "a naive datetime"); + return NULL; } static PyObject * datetime_timetuple(PyDateTime_DateTime *self) { - int dstflag = -1; + int dstflag = -1; - if (HASTZINFO(self) && self->tzinfo != Py_None) { - int none; + if (HASTZINFO(self) && self->tzinfo != Py_None) { + int none; - dstflag = call_dst(self->tzinfo, (PyObject *)self, &none); - if (dstflag == -1 && PyErr_Occurred()) - return NULL; - - if (none) - dstflag = -1; - else if (dstflag != 0) - dstflag = 1; - - } - return build_struct_time(GET_YEAR(self), - GET_MONTH(self), - GET_DAY(self), - DATE_GET_HOUR(self), - DATE_GET_MINUTE(self), - DATE_GET_SECOND(self), - dstflag); + dstflag = call_dst(self->tzinfo, (PyObject *)self, &none); + if (dstflag == -1 && PyErr_Occurred()) + return NULL; + + if (none) + dstflag = -1; + else if (dstflag != 0) + dstflag = 1; + + } + return build_struct_time(GET_YEAR(self), + GET_MONTH(self), + GET_DAY(self), + DATE_GET_HOUR(self), + DATE_GET_MINUTE(self), + DATE_GET_SECOND(self), + dstflag); } static PyObject * datetime_getdate(PyDateTime_DateTime *self) { - return new_date(GET_YEAR(self), - GET_MONTH(self), - GET_DAY(self)); + return new_date(GET_YEAR(self), + GET_MONTH(self), + GET_DAY(self)); } static PyObject * datetime_gettime(PyDateTime_DateTime *self) { - return new_time(DATE_GET_HOUR(self), - DATE_GET_MINUTE(self), - DATE_GET_SECOND(self), - DATE_GET_MICROSECOND(self), - Py_None); + return new_time(DATE_GET_HOUR(self), + DATE_GET_MINUTE(self), + DATE_GET_SECOND(self), + DATE_GET_MICROSECOND(self), + Py_None); } static PyObject * datetime_gettimetz(PyDateTime_DateTime *self) { - return new_time(DATE_GET_HOUR(self), - DATE_GET_MINUTE(self), - DATE_GET_SECOND(self), - DATE_GET_MICROSECOND(self), - HASTZINFO(self) ? self->tzinfo : Py_None); + return new_time(DATE_GET_HOUR(self), + DATE_GET_MINUTE(self), + DATE_GET_SECOND(self), + DATE_GET_MICROSECOND(self), + HASTZINFO(self) ? self->tzinfo : Py_None); } static PyObject * datetime_utctimetuple(PyDateTime_DateTime *self) { - int y = GET_YEAR(self); - int m = GET_MONTH(self); - int d = GET_DAY(self); - int hh = DATE_GET_HOUR(self); - int mm = DATE_GET_MINUTE(self); - int ss = DATE_GET_SECOND(self); - int us = 0; /* microseconds are ignored in a timetuple */ - int offset = 0; - - if (HASTZINFO(self) && self->tzinfo != Py_None) { - int none; - - offset = call_utcoffset(self->tzinfo, (PyObject *)self, &none); - if (offset == -1 && PyErr_Occurred()) - return NULL; - } - /* Even if offset is 0, don't call timetuple() -- tm_isdst should be - * 0 in a UTC timetuple regardless of what dst() says. - */ - if (offset) { - /* Subtract offset minutes & normalize. */ - int stat; - - mm -= offset; - stat = normalize_datetime(&y, &m, &d, &hh, &mm, &ss, &us); - if (stat < 0) { - /* At the edges, it's possible we overflowed - * beyond MINYEAR or MAXYEAR. - */ - if (PyErr_ExceptionMatches(PyExc_OverflowError)) - PyErr_Clear(); - else - return NULL; - } - } - return build_struct_time(y, m, d, hh, mm, ss, 0); + int y = GET_YEAR(self); + int m = GET_MONTH(self); + int d = GET_DAY(self); + int hh = DATE_GET_HOUR(self); + int mm = DATE_GET_MINUTE(self); + int ss = DATE_GET_SECOND(self); + int us = 0; /* microseconds are ignored in a timetuple */ + int offset = 0; + + if (HASTZINFO(self) && self->tzinfo != Py_None) { + int none; + + offset = call_utcoffset(self->tzinfo, (PyObject *)self, &none); + if (offset == -1 && PyErr_Occurred()) + return NULL; + } + /* Even if offset is 0, don't call timetuple() -- tm_isdst should be + * 0 in a UTC timetuple regardless of what dst() says. + */ + if (offset) { + /* Subtract offset minutes & normalize. */ + int stat; + + mm -= offset; + stat = normalize_datetime(&y, &m, &d, &hh, &mm, &ss, &us); + if (stat < 0) { + /* At the edges, it's possible we overflowed + * beyond MINYEAR or MAXYEAR. + */ + if (PyErr_ExceptionMatches(PyExc_OverflowError)) + PyErr_Clear(); + else + return NULL; + } + } + return build_struct_time(y, m, d, hh, mm, ss, 0); } /* Pickle support, a simple use of __reduce__. */ @@ -4480,102 +4480,102 @@ static PyObject * datetime_getstate(PyDateTime_DateTime *self) { - PyObject *basestate; - PyObject *result = NULL; + PyObject *basestate; + PyObject *result = NULL; - basestate = PyBytes_FromStringAndSize((char *)self->data, - _PyDateTime_DATETIME_DATASIZE); - if (basestate != NULL) { - if (! HASTZINFO(self) || self->tzinfo == Py_None) - result = PyTuple_Pack(1, basestate); - else - result = PyTuple_Pack(2, basestate, self->tzinfo); - Py_DECREF(basestate); - } - return result; + basestate = PyBytes_FromStringAndSize((char *)self->data, + _PyDateTime_DATETIME_DATASIZE); + if (basestate != NULL) { + if (! HASTZINFO(self) || self->tzinfo == Py_None) + result = PyTuple_Pack(1, basestate); + else + result = PyTuple_Pack(2, basestate, self->tzinfo); + Py_DECREF(basestate); + } + return result; } static PyObject * datetime_reduce(PyDateTime_DateTime *self, PyObject *arg) { - return Py_BuildValue("(ON)", Py_TYPE(self), datetime_getstate(self)); + return Py_BuildValue("(ON)", Py_TYPE(self), datetime_getstate(self)); } static PyMethodDef datetime_methods[] = { - /* Class methods: */ + /* Class methods: */ - {"now", (PyCFunction)datetime_now, - METH_VARARGS | METH_KEYWORDS | METH_CLASS, - PyDoc_STR("[tz] -> new datetime with tz's local day and time.")}, + {"now", (PyCFunction)datetime_now, + METH_VARARGS | METH_KEYWORDS | METH_CLASS, + PyDoc_STR("[tz] -> new datetime with tz's local day and time.")}, - {"utcnow", (PyCFunction)datetime_utcnow, - METH_NOARGS | METH_CLASS, - PyDoc_STR("Return a new datetime representing UTC day and time.")}, + {"utcnow", (PyCFunction)datetime_utcnow, + METH_NOARGS | METH_CLASS, + PyDoc_STR("Return a new datetime representing UTC day and time.")}, - {"fromtimestamp", (PyCFunction)datetime_fromtimestamp, - METH_VARARGS | METH_KEYWORDS | METH_CLASS, - PyDoc_STR("timestamp[, tz] -> tz's local time from POSIX timestamp.")}, + {"fromtimestamp", (PyCFunction)datetime_fromtimestamp, + METH_VARARGS | METH_KEYWORDS | METH_CLASS, + PyDoc_STR("timestamp[, tz] -> tz's local time from POSIX timestamp.")}, - {"utcfromtimestamp", (PyCFunction)datetime_utcfromtimestamp, - METH_VARARGS | METH_CLASS, - PyDoc_STR("timestamp -> UTC datetime from a POSIX timestamp " - "(like time.time()).")}, + {"utcfromtimestamp", (PyCFunction)datetime_utcfromtimestamp, + METH_VARARGS | METH_CLASS, + PyDoc_STR("timestamp -> UTC datetime from a POSIX timestamp " + "(like time.time()).")}, - {"strptime", (PyCFunction)datetime_strptime, - METH_VARARGS | METH_CLASS, - PyDoc_STR("string, format -> new datetime parsed from a string " - "(like time.strptime()).")}, + {"strptime", (PyCFunction)datetime_strptime, + METH_VARARGS | METH_CLASS, + PyDoc_STR("string, format -> new datetime parsed from a string " + "(like time.strptime()).")}, - {"combine", (PyCFunction)datetime_combine, - METH_VARARGS | METH_KEYWORDS | METH_CLASS, - PyDoc_STR("date, time -> datetime with same date and time fields")}, + {"combine", (PyCFunction)datetime_combine, + METH_VARARGS | METH_KEYWORDS | METH_CLASS, + PyDoc_STR("date, time -> datetime with same date and time fields")}, - /* Instance methods: */ + /* Instance methods: */ - {"date", (PyCFunction)datetime_getdate, METH_NOARGS, - PyDoc_STR("Return date object with same year, month and day.")}, + {"date", (PyCFunction)datetime_getdate, METH_NOARGS, + PyDoc_STR("Return date object with same year, month and day.")}, - {"time", (PyCFunction)datetime_gettime, METH_NOARGS, - PyDoc_STR("Return time object with same time but with tzinfo=None.")}, + {"time", (PyCFunction)datetime_gettime, METH_NOARGS, + PyDoc_STR("Return time object with same time but with tzinfo=None.")}, - {"timetz", (PyCFunction)datetime_gettimetz, METH_NOARGS, - PyDoc_STR("Return time object with same time and tzinfo.")}, + {"timetz", (PyCFunction)datetime_gettimetz, METH_NOARGS, + PyDoc_STR("Return time object with same time and tzinfo.")}, - {"ctime", (PyCFunction)datetime_ctime, METH_NOARGS, - PyDoc_STR("Return ctime() style string.")}, + {"ctime", (PyCFunction)datetime_ctime, METH_NOARGS, + PyDoc_STR("Return ctime() style string.")}, - {"timetuple", (PyCFunction)datetime_timetuple, METH_NOARGS, - PyDoc_STR("Return time tuple, compatible with time.localtime().")}, + {"timetuple", (PyCFunction)datetime_timetuple, METH_NOARGS, + PyDoc_STR("Return time tuple, compatible with time.localtime().")}, - {"utctimetuple", (PyCFunction)datetime_utctimetuple, METH_NOARGS, - PyDoc_STR("Return UTC time tuple, compatible with time.localtime().")}, + {"utctimetuple", (PyCFunction)datetime_utctimetuple, METH_NOARGS, + PyDoc_STR("Return UTC time tuple, compatible with time.localtime().")}, - {"isoformat", (PyCFunction)datetime_isoformat, METH_VARARGS | METH_KEYWORDS, - PyDoc_STR("[sep] -> string in ISO 8601 format, " - "YYYY-MM-DDTHH:MM:SS[.mmmmmm][+HH:MM].\n\n" - "sep is used to separate the year from the time, and " - "defaults to 'T'.")}, + {"isoformat", (PyCFunction)datetime_isoformat, METH_VARARGS | METH_KEYWORDS, + PyDoc_STR("[sep] -> string in ISO 8601 format, " + "YYYY-MM-DDTHH:MM:SS[.mmmmmm][+HH:MM].\n\n" + "sep is used to separate the year from the time, and " + "defaults to 'T'.")}, - {"utcoffset", (PyCFunction)datetime_utcoffset, METH_NOARGS, - PyDoc_STR("Return self.tzinfo.utcoffset(self).")}, + {"utcoffset", (PyCFunction)datetime_utcoffset, METH_NOARGS, + PyDoc_STR("Return self.tzinfo.utcoffset(self).")}, - {"tzname", (PyCFunction)datetime_tzname, METH_NOARGS, - PyDoc_STR("Return self.tzinfo.tzname(self).")}, + {"tzname", (PyCFunction)datetime_tzname, METH_NOARGS, + PyDoc_STR("Return self.tzinfo.tzname(self).")}, - {"dst", (PyCFunction)datetime_dst, METH_NOARGS, - PyDoc_STR("Return self.tzinfo.dst(self).")}, + {"dst", (PyCFunction)datetime_dst, METH_NOARGS, + PyDoc_STR("Return self.tzinfo.dst(self).")}, - {"replace", (PyCFunction)datetime_replace, METH_VARARGS | METH_KEYWORDS, - PyDoc_STR("Return datetime with new specified fields.")}, + {"replace", (PyCFunction)datetime_replace, METH_VARARGS | METH_KEYWORDS, + PyDoc_STR("Return datetime with new specified fields.")}, - {"astimezone", (PyCFunction)datetime_astimezone, METH_VARARGS | METH_KEYWORDS, - PyDoc_STR("tz -> convert to local time in new timezone tz\n")}, + {"astimezone", (PyCFunction)datetime_astimezone, METH_VARARGS | METH_KEYWORDS, + PyDoc_STR("tz -> convert to local time in new timezone tz\n")}, - {"__reduce__", (PyCFunction)datetime_reduce, METH_NOARGS, - PyDoc_STR("__reduce__() -> (cls, state)")}, + {"__reduce__", (PyCFunction)datetime_reduce, METH_NOARGS, + PyDoc_STR("__reduce__() -> (cls, state)")}, - {NULL, NULL} + {NULL, NULL} }; static char datetime_doc[] = @@ -4585,58 +4585,58 @@ instance of a tzinfo subclass. The remaining arguments may be ints or longs.\n"); static PyNumberMethods datetime_as_number = { - datetime_add, /* nb_add */ - datetime_subtract, /* nb_subtract */ - 0, /* nb_multiply */ - 0, /* nb_remainder */ - 0, /* nb_divmod */ - 0, /* nb_power */ - 0, /* nb_negative */ - 0, /* nb_positive */ - 0, /* nb_absolute */ - 0, /* nb_bool */ + datetime_add, /* nb_add */ + datetime_subtract, /* nb_subtract */ + 0, /* nb_multiply */ + 0, /* nb_remainder */ + 0, /* nb_divmod */ + 0, /* nb_power */ + 0, /* nb_negative */ + 0, /* nb_positive */ + 0, /* nb_absolute */ + 0, /* nb_bool */ }; static PyTypeObject PyDateTime_DateTimeType = { - PyVarObject_HEAD_INIT(NULL, 0) - "datetime.datetime", /* tp_name */ - sizeof(PyDateTime_DateTime), /* tp_basicsize */ - 0, /* tp_itemsize */ - (destructor)datetime_dealloc, /* tp_dealloc */ - 0, /* tp_print */ - 0, /* tp_getattr */ - 0, /* tp_setattr */ - 0, /* tp_reserved */ - (reprfunc)datetime_repr, /* tp_repr */ - &datetime_as_number, /* tp_as_number */ - 0, /* tp_as_sequence */ - 0, /* tp_as_mapping */ - (hashfunc)datetime_hash, /* tp_hash */ - 0, /* tp_call */ - (reprfunc)datetime_str, /* tp_str */ - PyObject_GenericGetAttr, /* tp_getattro */ - 0, /* tp_setattro */ - 0, /* tp_as_buffer */ - Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */ - datetime_doc, /* tp_doc */ - 0, /* tp_traverse */ - 0, /* tp_clear */ - datetime_richcompare, /* tp_richcompare */ - 0, /* tp_weaklistoffset */ - 0, /* tp_iter */ - 0, /* tp_iternext */ - datetime_methods, /* tp_methods */ - 0, /* tp_members */ - datetime_getset, /* tp_getset */ - &PyDateTime_DateType, /* tp_base */ - 0, /* tp_dict */ - 0, /* tp_descr_get */ - 0, /* tp_descr_set */ - 0, /* tp_dictoffset */ - 0, /* tp_init */ - datetime_alloc, /* tp_alloc */ - datetime_new, /* tp_new */ - 0, /* tp_free */ + PyVarObject_HEAD_INIT(NULL, 0) + "datetime.datetime", /* tp_name */ + sizeof(PyDateTime_DateTime), /* tp_basicsize */ + 0, /* tp_itemsize */ + (destructor)datetime_dealloc, /* tp_dealloc */ + 0, /* tp_print */ + 0, /* tp_getattr */ + 0, /* tp_setattr */ + 0, /* tp_reserved */ + (reprfunc)datetime_repr, /* tp_repr */ + &datetime_as_number, /* tp_as_number */ + 0, /* tp_as_sequence */ + 0, /* tp_as_mapping */ + (hashfunc)datetime_hash, /* tp_hash */ + 0, /* tp_call */ + (reprfunc)datetime_str, /* tp_str */ + PyObject_GenericGetAttr, /* tp_getattro */ + 0, /* tp_setattro */ + 0, /* tp_as_buffer */ + Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */ + datetime_doc, /* tp_doc */ + 0, /* tp_traverse */ + 0, /* tp_clear */ + datetime_richcompare, /* tp_richcompare */ + 0, /* tp_weaklistoffset */ + 0, /* tp_iter */ + 0, /* tp_iternext */ + datetime_methods, /* tp_methods */ + 0, /* tp_members */ + datetime_getset, /* tp_getset */ + &PyDateTime_DateType, /* tp_base */ + 0, /* tp_dict */ + 0, /* tp_descr_get */ + 0, /* tp_descr_set */ + 0, /* tp_dictoffset */ + 0, /* tp_init */ + datetime_alloc, /* tp_alloc */ + datetime_new, /* tp_new */ + 0, /* tp_free */ }; /* --------------------------------------------------------------------------- @@ -4644,204 +4644,204 @@ */ static PyMethodDef module_methods[] = { - {NULL, NULL} + {NULL, NULL} }; /* C API. Clients get at this via PyDateTime_IMPORT, defined in * datetime.h. */ static PyDateTime_CAPI CAPI = { - &PyDateTime_DateType, - &PyDateTime_DateTimeType, - &PyDateTime_TimeType, - &PyDateTime_DeltaType, - &PyDateTime_TZInfoType, - new_date_ex, - new_datetime_ex, - new_time_ex, - new_delta_ex, - datetime_fromtimestamp, - date_fromtimestamp + &PyDateTime_DateType, + &PyDateTime_DateTimeType, + &PyDateTime_TimeType, + &PyDateTime_DeltaType, + &PyDateTime_TZInfoType, + new_date_ex, + new_datetime_ex, + new_time_ex, + new_delta_ex, + datetime_fromtimestamp, + date_fromtimestamp }; static struct PyModuleDef datetimemodule = { - PyModuleDef_HEAD_INIT, - "datetime", - "Fast implementation of the datetime type.", - -1, - module_methods, - NULL, - NULL, - NULL, - NULL + PyModuleDef_HEAD_INIT, + "datetime", + "Fast implementation of the datetime type.", + -1, + module_methods, + NULL, + NULL, + NULL, + NULL }; PyMODINIT_FUNC PyInit_datetime(void) { - PyObject *m; /* a module object */ - PyObject *d; /* its dict */ - PyObject *x; - - m = PyModule_Create(&datetimemodule); - if (m == NULL) - return NULL; - - if (PyType_Ready(&PyDateTime_DateType) < 0) - return NULL; - if (PyType_Ready(&PyDateTime_DateTimeType) < 0) - return NULL; - if (PyType_Ready(&PyDateTime_DeltaType) < 0) - return NULL; - if (PyType_Ready(&PyDateTime_TimeType) < 0) - return NULL; - if (PyType_Ready(&PyDateTime_TZInfoType) < 0) - return NULL; - - /* timedelta values */ - d = PyDateTime_DeltaType.tp_dict; - - x = new_delta(0, 0, 1, 0); - if (x == NULL || PyDict_SetItemString(d, "resolution", x) < 0) - return NULL; - Py_DECREF(x); - - x = new_delta(-MAX_DELTA_DAYS, 0, 0, 0); - if (x == NULL || PyDict_SetItemString(d, "min", x) < 0) - return NULL; - Py_DECREF(x); - - x = new_delta(MAX_DELTA_DAYS, 24*3600-1, 1000000-1, 0); - if (x == NULL || PyDict_SetItemString(d, "max", x) < 0) - return NULL; - Py_DECREF(x); - - /* date values */ - d = PyDateTime_DateType.tp_dict; - - x = new_date(1, 1, 1); - if (x == NULL || PyDict_SetItemString(d, "min", x) < 0) - return NULL; - Py_DECREF(x); - - x = new_date(MAXYEAR, 12, 31); - if (x == NULL || PyDict_SetItemString(d, "max", x) < 0) - return NULL; - Py_DECREF(x); - - x = new_delta(1, 0, 0, 0); - if (x == NULL || PyDict_SetItemString(d, "resolution", x) < 0) - return NULL; - Py_DECREF(x); - - /* time values */ - d = PyDateTime_TimeType.tp_dict; - - x = new_time(0, 0, 0, 0, Py_None); - if (x == NULL || PyDict_SetItemString(d, "min", x) < 0) - return NULL; - Py_DECREF(x); - - x = new_time(23, 59, 59, 999999, Py_None); - if (x == NULL || PyDict_SetItemString(d, "max", x) < 0) - return NULL; - Py_DECREF(x); - - x = new_delta(0, 0, 1, 0); - if (x == NULL || PyDict_SetItemString(d, "resolution", x) < 0) - return NULL; - Py_DECREF(x); - - /* datetime values */ - d = PyDateTime_DateTimeType.tp_dict; - - x = new_datetime(1, 1, 1, 0, 0, 0, 0, Py_None); - if (x == NULL || PyDict_SetItemString(d, "min", x) < 0) - return NULL; - Py_DECREF(x); - - x = new_datetime(MAXYEAR, 12, 31, 23, 59, 59, 999999, Py_None); - if (x == NULL || PyDict_SetItemString(d, "max", x) < 0) - return NULL; - Py_DECREF(x); - - x = new_delta(0, 0, 1, 0); - if (x == NULL || PyDict_SetItemString(d, "resolution", x) < 0) - return NULL; - Py_DECREF(x); - - /* module initialization */ - PyModule_AddIntConstant(m, "MINYEAR", MINYEAR); - PyModule_AddIntConstant(m, "MAXYEAR", MAXYEAR); - - Py_INCREF(&PyDateTime_DateType); - PyModule_AddObject(m, "date", (PyObject *) &PyDateTime_DateType); - - Py_INCREF(&PyDateTime_DateTimeType); - PyModule_AddObject(m, "datetime", - (PyObject *)&PyDateTime_DateTimeType); + PyObject *m; /* a module object */ + PyObject *d; /* its dict */ + PyObject *x; + + m = PyModule_Create(&datetimemodule); + if (m == NULL) + return NULL; + + if (PyType_Ready(&PyDateTime_DateType) < 0) + return NULL; + if (PyType_Ready(&PyDateTime_DateTimeType) < 0) + return NULL; + if (PyType_Ready(&PyDateTime_DeltaType) < 0) + return NULL; + if (PyType_Ready(&PyDateTime_TimeType) < 0) + return NULL; + if (PyType_Ready(&PyDateTime_TZInfoType) < 0) + return NULL; - Py_INCREF(&PyDateTime_TimeType); - PyModule_AddObject(m, "time", (PyObject *) &PyDateTime_TimeType); + /* timedelta values */ + d = PyDateTime_DeltaType.tp_dict; - Py_INCREF(&PyDateTime_DeltaType); - PyModule_AddObject(m, "timedelta", (PyObject *) &PyDateTime_DeltaType); + x = new_delta(0, 0, 1, 0); + if (x == NULL || PyDict_SetItemString(d, "resolution", x) < 0) + return NULL; + Py_DECREF(x); + + x = new_delta(-MAX_DELTA_DAYS, 0, 0, 0); + if (x == NULL || PyDict_SetItemString(d, "min", x) < 0) + return NULL; + Py_DECREF(x); + + x = new_delta(MAX_DELTA_DAYS, 24*3600-1, 1000000-1, 0); + if (x == NULL || PyDict_SetItemString(d, "max", x) < 0) + return NULL; + Py_DECREF(x); + + /* date values */ + d = PyDateTime_DateType.tp_dict; + + x = new_date(1, 1, 1); + if (x == NULL || PyDict_SetItemString(d, "min", x) < 0) + return NULL; + Py_DECREF(x); + + x = new_date(MAXYEAR, 12, 31); + if (x == NULL || PyDict_SetItemString(d, "max", x) < 0) + return NULL; + Py_DECREF(x); + + x = new_delta(1, 0, 0, 0); + if (x == NULL || PyDict_SetItemString(d, "resolution", x) < 0) + return NULL; + Py_DECREF(x); - Py_INCREF(&PyDateTime_TZInfoType); - PyModule_AddObject(m, "tzinfo", (PyObject *) &PyDateTime_TZInfoType); + /* time values */ + d = PyDateTime_TimeType.tp_dict; + + x = new_time(0, 0, 0, 0, Py_None); + if (x == NULL || PyDict_SetItemString(d, "min", x) < 0) + return NULL; + Py_DECREF(x); + + x = new_time(23, 59, 59, 999999, Py_None); + if (x == NULL || PyDict_SetItemString(d, "max", x) < 0) + return NULL; + Py_DECREF(x); + + x = new_delta(0, 0, 1, 0); + if (x == NULL || PyDict_SetItemString(d, "resolution", x) < 0) + return NULL; + Py_DECREF(x); + + /* datetime values */ + d = PyDateTime_DateTimeType.tp_dict; + + x = new_datetime(1, 1, 1, 0, 0, 0, 0, Py_None); + if (x == NULL || PyDict_SetItemString(d, "min", x) < 0) + return NULL; + Py_DECREF(x); + + x = new_datetime(MAXYEAR, 12, 31, 23, 59, 59, 999999, Py_None); + if (x == NULL || PyDict_SetItemString(d, "max", x) < 0) + return NULL; + Py_DECREF(x); + + x = new_delta(0, 0, 1, 0); + if (x == NULL || PyDict_SetItemString(d, "resolution", x) < 0) + return NULL; + Py_DECREF(x); + + /* module initialization */ + PyModule_AddIntConstant(m, "MINYEAR", MINYEAR); + PyModule_AddIntConstant(m, "MAXYEAR", MAXYEAR); + + Py_INCREF(&PyDateTime_DateType); + PyModule_AddObject(m, "date", (PyObject *) &PyDateTime_DateType); + + Py_INCREF(&PyDateTime_DateTimeType); + PyModule_AddObject(m, "datetime", + (PyObject *)&PyDateTime_DateTimeType); + + Py_INCREF(&PyDateTime_TimeType); + PyModule_AddObject(m, "time", (PyObject *) &PyDateTime_TimeType); + + Py_INCREF(&PyDateTime_DeltaType); + PyModule_AddObject(m, "timedelta", (PyObject *) &PyDateTime_DeltaType); + + Py_INCREF(&PyDateTime_TZInfoType); + PyModule_AddObject(m, "tzinfo", (PyObject *) &PyDateTime_TZInfoType); x = PyCapsule_New(&CAPI, PyDateTime_CAPSULE_NAME, NULL); if (x == NULL) - return NULL; + return NULL; PyModule_AddObject(m, "datetime_CAPI", x); - /* A 4-year cycle has an extra leap day over what we'd get from - * pasting together 4 single years. - */ - assert(DI4Y == 4 * 365 + 1); - assert(DI4Y == days_before_year(4+1)); - - /* Similarly, a 400-year cycle has an extra leap day over what we'd - * get from pasting together 4 100-year cycles. - */ - assert(DI400Y == 4 * DI100Y + 1); - assert(DI400Y == days_before_year(400+1)); - - /* OTOH, a 100-year cycle has one fewer leap day than we'd get from - * pasting together 25 4-year cycles. - */ - assert(DI100Y == 25 * DI4Y - 1); - assert(DI100Y == days_before_year(100+1)); - - us_per_us = PyLong_FromLong(1); - us_per_ms = PyLong_FromLong(1000); - us_per_second = PyLong_FromLong(1000000); - us_per_minute = PyLong_FromLong(60000000); - seconds_per_day = PyLong_FromLong(24 * 3600); - if (us_per_us == NULL || us_per_ms == NULL || us_per_second == NULL || - us_per_minute == NULL || seconds_per_day == NULL) - return NULL; - - /* The rest are too big for 32-bit ints, but even - * us_per_week fits in 40 bits, so doubles should be exact. - */ - us_per_hour = PyLong_FromDouble(3600000000.0); - us_per_day = PyLong_FromDouble(86400000000.0); - us_per_week = PyLong_FromDouble(604800000000.0); - if (us_per_hour == NULL || us_per_day == NULL || us_per_week == NULL) - return NULL; - return m; + /* A 4-year cycle has an extra leap day over what we'd get from + * pasting together 4 single years. + */ + assert(DI4Y == 4 * 365 + 1); + assert(DI4Y == days_before_year(4+1)); + + /* Similarly, a 400-year cycle has an extra leap day over what we'd + * get from pasting together 4 100-year cycles. + */ + assert(DI400Y == 4 * DI100Y + 1); + assert(DI400Y == days_before_year(400+1)); + + /* OTOH, a 100-year cycle has one fewer leap day than we'd get from + * pasting together 25 4-year cycles. + */ + assert(DI100Y == 25 * DI4Y - 1); + assert(DI100Y == days_before_year(100+1)); + + us_per_us = PyLong_FromLong(1); + us_per_ms = PyLong_FromLong(1000); + us_per_second = PyLong_FromLong(1000000); + us_per_minute = PyLong_FromLong(60000000); + seconds_per_day = PyLong_FromLong(24 * 3600); + if (us_per_us == NULL || us_per_ms == NULL || us_per_second == NULL || + us_per_minute == NULL || seconds_per_day == NULL) + return NULL; + + /* The rest are too big for 32-bit ints, but even + * us_per_week fits in 40 bits, so doubles should be exact. + */ + us_per_hour = PyLong_FromDouble(3600000000.0); + us_per_day = PyLong_FromDouble(86400000000.0); + us_per_week = PyLong_FromDouble(604800000000.0); + if (us_per_hour == NULL || us_per_day == NULL || us_per_week == NULL) + return NULL; + return m; } /* --------------------------------------------------------------------------- Some time zone algebra. For a datetime x, let x.n = x stripped of its timezone -- its naive time. x.o = x.utcoffset(), and assuming that doesn't raise an exception or - return None + return None x.d = x.dst(), and assuming that doesn't raise an exception or - return None + return None x.s = x's standard offset, x.o - x.d Now some derived rules, where k is a duration (timedelta). @@ -4963,13 +4963,13 @@ already): diff' = x.n - (z'.n - z'.o) = replacing z'.n via [7] - x.n - (z.n + diff - z'.o) = replacing diff via [6] - x.n - (z.n + x.n - (z.n - z.o) - z'.o) = - x.n - z.n - x.n + z.n - z.o + z'.o = cancel x.n - - z.n + z.n - z.o + z'.o = cancel z.n - - z.o + z'.o = #1 twice - -z.s - z.d + z'.s + z'.d = z and z' have same tzinfo - z'.d - z.d + x.n - (z.n + diff - z'.o) = replacing diff via [6] + x.n - (z.n + x.n - (z.n - z.o) - z'.o) = + x.n - z.n - x.n + z.n - z.o + z'.o = cancel x.n + - z.n + z.n - z.o + z'.o = cancel z.n + - z.o + z'.o = #1 twice + -z.s - z.d + z'.s + z'.d = z and z' have same tzinfo + z'.d - z.d So z' is UTC-equivalent to x iff z'.d = z.d at this point. If they are equal, we've found the UTC-equivalent so are done. In fact, we stop with [7] and Modified: python/branches/release31-maint/Modules/errnomodule.c ============================================================================== --- python/branches/release31-maint/Modules/errnomodule.c (original) +++ python/branches/release31-maint/Modules/errnomodule.c Sun May 9 18:14:21 2010 @@ -11,10 +11,10 @@ /* * Pull in the system error definitions - */ + */ static PyMethodDef errno_methods[] = { - {NULL, NULL} + {NULL, NULL} }; /* Helper function doing the dictionary inserting */ @@ -22,21 +22,21 @@ static void _inscode(PyObject *d, PyObject *de, const char *name, int code) { - PyObject *u = PyUnicode_FromString(name); - PyObject *v = PyLong_FromLong((long) code); + PyObject *u = PyUnicode_FromString(name); + PyObject *v = PyLong_FromLong((long) code); - /* Don't bother checking for errors; they'll be caught at the end - * of the module initialization function by the caller of - * initerrno(). - */ - if (u && v) { - /* insert in modules dict */ - PyDict_SetItem(d, u, v); - /* insert in errorcode dict */ - PyDict_SetItem(de, v, u); - } - Py_XDECREF(u); - Py_XDECREF(v); + /* Don't bother checking for errors; they'll be caught at the end + * of the module initialization function by the caller of + * initerrno(). + */ + if (u && v) { + /* insert in modules dict */ + PyDict_SetItem(d, u, v); + /* insert in errorcode dict */ + PyDict_SetItem(de, v, u); + } + Py_XDECREF(u); + Py_XDECREF(v); } PyDoc_STRVAR(errno__doc__, @@ -54,749 +54,749 @@ e.g. os.strerror(2) could return 'No such file or directory'."); static struct PyModuleDef errnomodule = { - PyModuleDef_HEAD_INIT, - "errno", - errno__doc__, - -1, - errno_methods, - NULL, - NULL, - NULL, - NULL + PyModuleDef_HEAD_INIT, + "errno", + errno__doc__, + -1, + errno_methods, + NULL, + NULL, + NULL, + NULL }; PyMODINIT_FUNC PyInit_errno(void) { - PyObject *m, *d, *de; - m = PyModule_Create(&errnomodule); - if (m == NULL) - return NULL; - d = PyModule_GetDict(m); - de = PyDict_New(); - if (!d || !de || PyDict_SetItemString(d, "errorcode", de) < 0) - return NULL; + PyObject *m, *d, *de; + m = PyModule_Create(&errnomodule); + if (m == NULL) + return NULL; + d = PyModule_GetDict(m); + de = PyDict_New(); + if (!d || !de || PyDict_SetItemString(d, "errorcode", de) < 0) + return NULL; /* Macro so I don't have to edit each and every line below... */ #define inscode(d, ds, de, name, code, comment) _inscode(d, de, name, code) - /* - * The names and comments are borrowed from linux/include/errno.h, - * which should be pretty all-inclusive - */ + /* + * The names and comments are borrowed from linux/include/errno.h, + * which should be pretty all-inclusive + */ #ifdef ENODEV - inscode(d, ds, de, "ENODEV", ENODEV, "No such device"); + inscode(d, ds, de, "ENODEV", ENODEV, "No such device"); #endif #ifdef ENOCSI - inscode(d, ds, de, "ENOCSI", ENOCSI, "No CSI structure available"); + inscode(d, ds, de, "ENOCSI", ENOCSI, "No CSI structure available"); #endif #ifdef EHOSTUNREACH - inscode(d, ds, de, "EHOSTUNREACH", EHOSTUNREACH, "No route to host"); + inscode(d, ds, de, "EHOSTUNREACH", EHOSTUNREACH, "No route to host"); #else #ifdef WSAEHOSTUNREACH - inscode(d, ds, de, "EHOSTUNREACH", WSAEHOSTUNREACH, "No route to host"); + inscode(d, ds, de, "EHOSTUNREACH", WSAEHOSTUNREACH, "No route to host"); #endif #endif #ifdef ENOMSG - inscode(d, ds, de, "ENOMSG", ENOMSG, "No message of desired type"); + inscode(d, ds, de, "ENOMSG", ENOMSG, "No message of desired type"); #endif #ifdef EUCLEAN - inscode(d, ds, de, "EUCLEAN", EUCLEAN, "Structure needs cleaning"); + inscode(d, ds, de, "EUCLEAN", EUCLEAN, "Structure needs cleaning"); #endif #ifdef EL2NSYNC - inscode(d, ds, de, "EL2NSYNC", EL2NSYNC, "Level 2 not synchronized"); + inscode(d, ds, de, "EL2NSYNC", EL2NSYNC, "Level 2 not synchronized"); #endif #ifdef EL2HLT - inscode(d, ds, de, "EL2HLT", EL2HLT, "Level 2 halted"); + inscode(d, ds, de, "EL2HLT", EL2HLT, "Level 2 halted"); #endif #ifdef ENODATA - inscode(d, ds, de, "ENODATA", ENODATA, "No data available"); + inscode(d, ds, de, "ENODATA", ENODATA, "No data available"); #endif #ifdef ENOTBLK - inscode(d, ds, de, "ENOTBLK", ENOTBLK, "Block device required"); + inscode(d, ds, de, "ENOTBLK", ENOTBLK, "Block device required"); #endif #ifdef ENOSYS - inscode(d, ds, de, "ENOSYS", ENOSYS, "Function not implemented"); + inscode(d, ds, de, "ENOSYS", ENOSYS, "Function not implemented"); #endif #ifdef EPIPE - inscode(d, ds, de, "EPIPE", EPIPE, "Broken pipe"); + inscode(d, ds, de, "EPIPE", EPIPE, "Broken pipe"); #endif #ifdef EINVAL - inscode(d, ds, de, "EINVAL", EINVAL, "Invalid argument"); + inscode(d, ds, de, "EINVAL", EINVAL, "Invalid argument"); #else #ifdef WSAEINVAL - inscode(d, ds, de, "EINVAL", WSAEINVAL, "Invalid argument"); + inscode(d, ds, de, "EINVAL", WSAEINVAL, "Invalid argument"); #endif #endif #ifdef EOVERFLOW - inscode(d, ds, de, "EOVERFLOW", EOVERFLOW, "Value too large for defined data type"); + inscode(d, ds, de, "EOVERFLOW", EOVERFLOW, "Value too large for defined data type"); #endif #ifdef EADV - inscode(d, ds, de, "EADV", EADV, "Advertise error"); + inscode(d, ds, de, "EADV", EADV, "Advertise error"); #endif #ifdef EINTR - inscode(d, ds, de, "EINTR", EINTR, "Interrupted system call"); + inscode(d, ds, de, "EINTR", EINTR, "Interrupted system call"); #else #ifdef WSAEINTR - inscode(d, ds, de, "EINTR", WSAEINTR, "Interrupted system call"); + inscode(d, ds, de, "EINTR", WSAEINTR, "Interrupted system call"); #endif #endif #ifdef EUSERS - inscode(d, ds, de, "EUSERS", EUSERS, "Too many users"); + inscode(d, ds, de, "EUSERS", EUSERS, "Too many users"); #else #ifdef WSAEUSERS - inscode(d, ds, de, "EUSERS", WSAEUSERS, "Too many users"); + inscode(d, ds, de, "EUSERS", WSAEUSERS, "Too many users"); #endif #endif #ifdef ENOTEMPTY - inscode(d, ds, de, "ENOTEMPTY", ENOTEMPTY, "Directory not empty"); + inscode(d, ds, de, "ENOTEMPTY", ENOTEMPTY, "Directory not empty"); #else #ifdef WSAENOTEMPTY - inscode(d, ds, de, "ENOTEMPTY", WSAENOTEMPTY, "Directory not empty"); + inscode(d, ds, de, "ENOTEMPTY", WSAENOTEMPTY, "Directory not empty"); #endif #endif #ifdef ENOBUFS - inscode(d, ds, de, "ENOBUFS", ENOBUFS, "No buffer space available"); + inscode(d, ds, de, "ENOBUFS", ENOBUFS, "No buffer space available"); #else #ifdef WSAENOBUFS - inscode(d, ds, de, "ENOBUFS", WSAENOBUFS, "No buffer space available"); + inscode(d, ds, de, "ENOBUFS", WSAENOBUFS, "No buffer space available"); #endif #endif #ifdef EPROTO - inscode(d, ds, de, "EPROTO", EPROTO, "Protocol error"); + inscode(d, ds, de, "EPROTO", EPROTO, "Protocol error"); #endif #ifdef EREMOTE - inscode(d, ds, de, "EREMOTE", EREMOTE, "Object is remote"); + inscode(d, ds, de, "EREMOTE", EREMOTE, "Object is remote"); #else #ifdef WSAEREMOTE - inscode(d, ds, de, "EREMOTE", WSAEREMOTE, "Object is remote"); + inscode(d, ds, de, "EREMOTE", WSAEREMOTE, "Object is remote"); #endif #endif #ifdef ENAVAIL - inscode(d, ds, de, "ENAVAIL", ENAVAIL, "No XENIX semaphores available"); + inscode(d, ds, de, "ENAVAIL", ENAVAIL, "No XENIX semaphores available"); #endif #ifdef ECHILD - inscode(d, ds, de, "ECHILD", ECHILD, "No child processes"); + inscode(d, ds, de, "ECHILD", ECHILD, "No child processes"); #endif #ifdef ELOOP - inscode(d, ds, de, "ELOOP", ELOOP, "Too many symbolic links encountered"); + inscode(d, ds, de, "ELOOP", ELOOP, "Too many symbolic links encountered"); #else #ifdef WSAELOOP - inscode(d, ds, de, "ELOOP", WSAELOOP, "Too many symbolic links encountered"); + inscode(d, ds, de, "ELOOP", WSAELOOP, "Too many symbolic links encountered"); #endif #endif #ifdef EXDEV - inscode(d, ds, de, "EXDEV", EXDEV, "Cross-device link"); + inscode(d, ds, de, "EXDEV", EXDEV, "Cross-device link"); #endif #ifdef E2BIG - inscode(d, ds, de, "E2BIG", E2BIG, "Arg list too long"); + inscode(d, ds, de, "E2BIG", E2BIG, "Arg list too long"); #endif #ifdef ESRCH - inscode(d, ds, de, "ESRCH", ESRCH, "No such process"); + inscode(d, ds, de, "ESRCH", ESRCH, "No such process"); #endif #ifdef EMSGSIZE - inscode(d, ds, de, "EMSGSIZE", EMSGSIZE, "Message too long"); + inscode(d, ds, de, "EMSGSIZE", EMSGSIZE, "Message too long"); #else #ifdef WSAEMSGSIZE - inscode(d, ds, de, "EMSGSIZE", WSAEMSGSIZE, "Message too long"); + inscode(d, ds, de, "EMSGSIZE", WSAEMSGSIZE, "Message too long"); #endif #endif #ifdef EAFNOSUPPORT - inscode(d, ds, de, "EAFNOSUPPORT", EAFNOSUPPORT, "Address family not supported by protocol"); + inscode(d, ds, de, "EAFNOSUPPORT", EAFNOSUPPORT, "Address family not supported by protocol"); #else #ifdef WSAEAFNOSUPPORT - inscode(d, ds, de, "EAFNOSUPPORT", WSAEAFNOSUPPORT, "Address family not supported by protocol"); + inscode(d, ds, de, "EAFNOSUPPORT", WSAEAFNOSUPPORT, "Address family not supported by protocol"); #endif #endif #ifdef EBADR - inscode(d, ds, de, "EBADR", EBADR, "Invalid request descriptor"); + inscode(d, ds, de, "EBADR", EBADR, "Invalid request descriptor"); #endif #ifdef EHOSTDOWN - inscode(d, ds, de, "EHOSTDOWN", EHOSTDOWN, "Host is down"); + inscode(d, ds, de, "EHOSTDOWN", EHOSTDOWN, "Host is down"); #else #ifdef WSAEHOSTDOWN - inscode(d, ds, de, "EHOSTDOWN", WSAEHOSTDOWN, "Host is down"); + inscode(d, ds, de, "EHOSTDOWN", WSAEHOSTDOWN, "Host is down"); #endif #endif #ifdef EPFNOSUPPORT - inscode(d, ds, de, "EPFNOSUPPORT", EPFNOSUPPORT, "Protocol family not supported"); + inscode(d, ds, de, "EPFNOSUPPORT", EPFNOSUPPORT, "Protocol family not supported"); #else #ifdef WSAEPFNOSUPPORT - inscode(d, ds, de, "EPFNOSUPPORT", WSAEPFNOSUPPORT, "Protocol family not supported"); + inscode(d, ds, de, "EPFNOSUPPORT", WSAEPFNOSUPPORT, "Protocol family not supported"); #endif #endif #ifdef ENOPROTOOPT - inscode(d, ds, de, "ENOPROTOOPT", ENOPROTOOPT, "Protocol not available"); + inscode(d, ds, de, "ENOPROTOOPT", ENOPROTOOPT, "Protocol not available"); #else #ifdef WSAENOPROTOOPT - inscode(d, ds, de, "ENOPROTOOPT", WSAENOPROTOOPT, "Protocol not available"); + inscode(d, ds, de, "ENOPROTOOPT", WSAENOPROTOOPT, "Protocol not available"); #endif #endif #ifdef EBUSY - inscode(d, ds, de, "EBUSY", EBUSY, "Device or resource busy"); + inscode(d, ds, de, "EBUSY", EBUSY, "Device or resource busy"); #endif #ifdef EWOULDBLOCK - inscode(d, ds, de, "EWOULDBLOCK", EWOULDBLOCK, "Operation would block"); + inscode(d, ds, de, "EWOULDBLOCK", EWOULDBLOCK, "Operation would block"); #else #ifdef WSAEWOULDBLOCK - inscode(d, ds, de, "EWOULDBLOCK", WSAEWOULDBLOCK, "Operation would block"); + inscode(d, ds, de, "EWOULDBLOCK", WSAEWOULDBLOCK, "Operation would block"); #endif #endif #ifdef EBADFD - inscode(d, ds, de, "EBADFD", EBADFD, "File descriptor in bad state"); + inscode(d, ds, de, "EBADFD", EBADFD, "File descriptor in bad state"); #endif #ifdef EDOTDOT - inscode(d, ds, de, "EDOTDOT", EDOTDOT, "RFS specific error"); + inscode(d, ds, de, "EDOTDOT", EDOTDOT, "RFS specific error"); #endif #ifdef EISCONN - inscode(d, ds, de, "EISCONN", EISCONN, "Transport endpoint is already connected"); + inscode(d, ds, de, "EISCONN", EISCONN, "Transport endpoint is already connected"); #else #ifdef WSAEISCONN - inscode(d, ds, de, "EISCONN", WSAEISCONN, "Transport endpoint is already connected"); + inscode(d, ds, de, "EISCONN", WSAEISCONN, "Transport endpoint is already connected"); #endif #endif #ifdef ENOANO - inscode(d, ds, de, "ENOANO", ENOANO, "No anode"); + inscode(d, ds, de, "ENOANO", ENOANO, "No anode"); #endif #ifdef ESHUTDOWN - inscode(d, ds, de, "ESHUTDOWN", ESHUTDOWN, "Cannot send after transport endpoint shutdown"); + inscode(d, ds, de, "ESHUTDOWN", ESHUTDOWN, "Cannot send after transport endpoint shutdown"); #else #ifdef WSAESHUTDOWN - inscode(d, ds, de, "ESHUTDOWN", WSAESHUTDOWN, "Cannot send after transport endpoint shutdown"); + inscode(d, ds, de, "ESHUTDOWN", WSAESHUTDOWN, "Cannot send after transport endpoint shutdown"); #endif #endif #ifdef ECHRNG - inscode(d, ds, de, "ECHRNG", ECHRNG, "Channel number out of range"); + inscode(d, ds, de, "ECHRNG", ECHRNG, "Channel number out of range"); #endif #ifdef ELIBBAD - inscode(d, ds, de, "ELIBBAD", ELIBBAD, "Accessing a corrupted shared library"); + inscode(d, ds, de, "ELIBBAD", ELIBBAD, "Accessing a corrupted shared library"); #endif #ifdef ENONET - inscode(d, ds, de, "ENONET", ENONET, "Machine is not on the network"); + inscode(d, ds, de, "ENONET", ENONET, "Machine is not on the network"); #endif #ifdef EBADE - inscode(d, ds, de, "EBADE", EBADE, "Invalid exchange"); + inscode(d, ds, de, "EBADE", EBADE, "Invalid exchange"); #endif #ifdef EBADF - inscode(d, ds, de, "EBADF", EBADF, "Bad file number"); + inscode(d, ds, de, "EBADF", EBADF, "Bad file number"); #else #ifdef WSAEBADF - inscode(d, ds, de, "EBADF", WSAEBADF, "Bad file number"); + inscode(d, ds, de, "EBADF", WSAEBADF, "Bad file number"); #endif #endif #ifdef EMULTIHOP - inscode(d, ds, de, "EMULTIHOP", EMULTIHOP, "Multihop attempted"); + inscode(d, ds, de, "EMULTIHOP", EMULTIHOP, "Multihop attempted"); #endif #ifdef EIO - inscode(d, ds, de, "EIO", EIO, "I/O error"); + inscode(d, ds, de, "EIO", EIO, "I/O error"); #endif #ifdef EUNATCH - inscode(d, ds, de, "EUNATCH", EUNATCH, "Protocol driver not attached"); + inscode(d, ds, de, "EUNATCH", EUNATCH, "Protocol driver not attached"); #endif #ifdef EPROTOTYPE - inscode(d, ds, de, "EPROTOTYPE", EPROTOTYPE, "Protocol wrong type for socket"); + inscode(d, ds, de, "EPROTOTYPE", EPROTOTYPE, "Protocol wrong type for socket"); #else #ifdef WSAEPROTOTYPE - inscode(d, ds, de, "EPROTOTYPE", WSAEPROTOTYPE, "Protocol wrong type for socket"); + inscode(d, ds, de, "EPROTOTYPE", WSAEPROTOTYPE, "Protocol wrong type for socket"); #endif #endif #ifdef ENOSPC - inscode(d, ds, de, "ENOSPC", ENOSPC, "No space left on device"); + inscode(d, ds, de, "ENOSPC", ENOSPC, "No space left on device"); #endif #ifdef ENOEXEC - inscode(d, ds, de, "ENOEXEC", ENOEXEC, "Exec format error"); + inscode(d, ds, de, "ENOEXEC", ENOEXEC, "Exec format error"); #endif #ifdef EALREADY - inscode(d, ds, de, "EALREADY", EALREADY, "Operation already in progress"); + inscode(d, ds, de, "EALREADY", EALREADY, "Operation already in progress"); #else #ifdef WSAEALREADY - inscode(d, ds, de, "EALREADY", WSAEALREADY, "Operation already in progress"); + inscode(d, ds, de, "EALREADY", WSAEALREADY, "Operation already in progress"); #endif #endif #ifdef ENETDOWN - inscode(d, ds, de, "ENETDOWN", ENETDOWN, "Network is down"); + inscode(d, ds, de, "ENETDOWN", ENETDOWN, "Network is down"); #else #ifdef WSAENETDOWN - inscode(d, ds, de, "ENETDOWN", WSAENETDOWN, "Network is down"); + inscode(d, ds, de, "ENETDOWN", WSAENETDOWN, "Network is down"); #endif #endif #ifdef ENOTNAM - inscode(d, ds, de, "ENOTNAM", ENOTNAM, "Not a XENIX named type file"); + inscode(d, ds, de, "ENOTNAM", ENOTNAM, "Not a XENIX named type file"); #endif #ifdef EACCES - inscode(d, ds, de, "EACCES", EACCES, "Permission denied"); + inscode(d, ds, de, "EACCES", EACCES, "Permission denied"); #else #ifdef WSAEACCES - inscode(d, ds, de, "EACCES", WSAEACCES, "Permission denied"); + inscode(d, ds, de, "EACCES", WSAEACCES, "Permission denied"); #endif #endif #ifdef ELNRNG - inscode(d, ds, de, "ELNRNG", ELNRNG, "Link number out of range"); + inscode(d, ds, de, "ELNRNG", ELNRNG, "Link number out of range"); #endif #ifdef EILSEQ - inscode(d, ds, de, "EILSEQ", EILSEQ, "Illegal byte sequence"); + inscode(d, ds, de, "EILSEQ", EILSEQ, "Illegal byte sequence"); #endif #ifdef ENOTDIR - inscode(d, ds, de, "ENOTDIR", ENOTDIR, "Not a directory"); + inscode(d, ds, de, "ENOTDIR", ENOTDIR, "Not a directory"); #endif #ifdef ENOTUNIQ - inscode(d, ds, de, "ENOTUNIQ", ENOTUNIQ, "Name not unique on network"); + inscode(d, ds, de, "ENOTUNIQ", ENOTUNIQ, "Name not unique on network"); #endif #ifdef EPERM - inscode(d, ds, de, "EPERM", EPERM, "Operation not permitted"); + inscode(d, ds, de, "EPERM", EPERM, "Operation not permitted"); #endif #ifdef EDOM - inscode(d, ds, de, "EDOM", EDOM, "Math argument out of domain of func"); + inscode(d, ds, de, "EDOM", EDOM, "Math argument out of domain of func"); #endif #ifdef EXFULL - inscode(d, ds, de, "EXFULL", EXFULL, "Exchange full"); + inscode(d, ds, de, "EXFULL", EXFULL, "Exchange full"); #endif #ifdef ECONNREFUSED - inscode(d, ds, de, "ECONNREFUSED", ECONNREFUSED, "Connection refused"); + inscode(d, ds, de, "ECONNREFUSED", ECONNREFUSED, "Connection refused"); #else #ifdef WSAECONNREFUSED - inscode(d, ds, de, "ECONNREFUSED", WSAECONNREFUSED, "Connection refused"); + inscode(d, ds, de, "ECONNREFUSED", WSAECONNREFUSED, "Connection refused"); #endif #endif #ifdef EISDIR - inscode(d, ds, de, "EISDIR", EISDIR, "Is a directory"); + inscode(d, ds, de, "EISDIR", EISDIR, "Is a directory"); #endif #ifdef EPROTONOSUPPORT - inscode(d, ds, de, "EPROTONOSUPPORT", EPROTONOSUPPORT, "Protocol not supported"); + inscode(d, ds, de, "EPROTONOSUPPORT", EPROTONOSUPPORT, "Protocol not supported"); #else #ifdef WSAEPROTONOSUPPORT - inscode(d, ds, de, "EPROTONOSUPPORT", WSAEPROTONOSUPPORT, "Protocol not supported"); + inscode(d, ds, de, "EPROTONOSUPPORT", WSAEPROTONOSUPPORT, "Protocol not supported"); #endif #endif #ifdef EROFS - inscode(d, ds, de, "EROFS", EROFS, "Read-only file system"); + inscode(d, ds, de, "EROFS", EROFS, "Read-only file system"); #endif #ifdef EADDRNOTAVAIL - inscode(d, ds, de, "EADDRNOTAVAIL", EADDRNOTAVAIL, "Cannot assign requested address"); + inscode(d, ds, de, "EADDRNOTAVAIL", EADDRNOTAVAIL, "Cannot assign requested address"); #else #ifdef WSAEADDRNOTAVAIL - inscode(d, ds, de, "EADDRNOTAVAIL", WSAEADDRNOTAVAIL, "Cannot assign requested address"); + inscode(d, ds, de, "EADDRNOTAVAIL", WSAEADDRNOTAVAIL, "Cannot assign requested address"); #endif #endif #ifdef EIDRM - inscode(d, ds, de, "EIDRM", EIDRM, "Identifier removed"); + inscode(d, ds, de, "EIDRM", EIDRM, "Identifier removed"); #endif #ifdef ECOMM - inscode(d, ds, de, "ECOMM", ECOMM, "Communication error on send"); + inscode(d, ds, de, "ECOMM", ECOMM, "Communication error on send"); #endif #ifdef ESRMNT - inscode(d, ds, de, "ESRMNT", ESRMNT, "Srmount error"); + inscode(d, ds, de, "ESRMNT", ESRMNT, "Srmount error"); #endif #ifdef EREMOTEIO - inscode(d, ds, de, "EREMOTEIO", EREMOTEIO, "Remote I/O error"); + inscode(d, ds, de, "EREMOTEIO", EREMOTEIO, "Remote I/O error"); #endif #ifdef EL3RST - inscode(d, ds, de, "EL3RST", EL3RST, "Level 3 reset"); + inscode(d, ds, de, "EL3RST", EL3RST, "Level 3 reset"); #endif #ifdef EBADMSG - inscode(d, ds, de, "EBADMSG", EBADMSG, "Not a data message"); + inscode(d, ds, de, "EBADMSG", EBADMSG, "Not a data message"); #endif #ifdef ENFILE - inscode(d, ds, de, "ENFILE", ENFILE, "File table overflow"); + inscode(d, ds, de, "ENFILE", ENFILE, "File table overflow"); #endif #ifdef ELIBMAX - inscode(d, ds, de, "ELIBMAX", ELIBMAX, "Attempting to link in too many shared libraries"); + inscode(d, ds, de, "ELIBMAX", ELIBMAX, "Attempting to link in too many shared libraries"); #endif #ifdef ESPIPE - inscode(d, ds, de, "ESPIPE", ESPIPE, "Illegal seek"); + inscode(d, ds, de, "ESPIPE", ESPIPE, "Illegal seek"); #endif #ifdef ENOLINK - inscode(d, ds, de, "ENOLINK", ENOLINK, "Link has been severed"); + inscode(d, ds, de, "ENOLINK", ENOLINK, "Link has been severed"); #endif #ifdef ENETRESET - inscode(d, ds, de, "ENETRESET", ENETRESET, "Network dropped connection because of reset"); + inscode(d, ds, de, "ENETRESET", ENETRESET, "Network dropped connection because of reset"); #else #ifdef WSAENETRESET - inscode(d, ds, de, "ENETRESET", WSAENETRESET, "Network dropped connection because of reset"); + inscode(d, ds, de, "ENETRESET", WSAENETRESET, "Network dropped connection because of reset"); #endif #endif #ifdef ETIMEDOUT - inscode(d, ds, de, "ETIMEDOUT", ETIMEDOUT, "Connection timed out"); + inscode(d, ds, de, "ETIMEDOUT", ETIMEDOUT, "Connection timed out"); #else #ifdef WSAETIMEDOUT - inscode(d, ds, de, "ETIMEDOUT", WSAETIMEDOUT, "Connection timed out"); + inscode(d, ds, de, "ETIMEDOUT", WSAETIMEDOUT, "Connection timed out"); #endif #endif #ifdef ENOENT - inscode(d, ds, de, "ENOENT", ENOENT, "No such file or directory"); + inscode(d, ds, de, "ENOENT", ENOENT, "No such file or directory"); #endif #ifdef EEXIST - inscode(d, ds, de, "EEXIST", EEXIST, "File exists"); + inscode(d, ds, de, "EEXIST", EEXIST, "File exists"); #endif #ifdef EDQUOT - inscode(d, ds, de, "EDQUOT", EDQUOT, "Quota exceeded"); + inscode(d, ds, de, "EDQUOT", EDQUOT, "Quota exceeded"); #else #ifdef WSAEDQUOT - inscode(d, ds, de, "EDQUOT", WSAEDQUOT, "Quota exceeded"); + inscode(d, ds, de, "EDQUOT", WSAEDQUOT, "Quota exceeded"); #endif #endif #ifdef ENOSTR - inscode(d, ds, de, "ENOSTR", ENOSTR, "Device not a stream"); + inscode(d, ds, de, "ENOSTR", ENOSTR, "Device not a stream"); #endif #ifdef EBADSLT - inscode(d, ds, de, "EBADSLT", EBADSLT, "Invalid slot"); + inscode(d, ds, de, "EBADSLT", EBADSLT, "Invalid slot"); #endif #ifdef EBADRQC - inscode(d, ds, de, "EBADRQC", EBADRQC, "Invalid request code"); + inscode(d, ds, de, "EBADRQC", EBADRQC, "Invalid request code"); #endif #ifdef ELIBACC - inscode(d, ds, de, "ELIBACC", ELIBACC, "Can not access a needed shared library"); + inscode(d, ds, de, "ELIBACC", ELIBACC, "Can not access a needed shared library"); #endif #ifdef EFAULT - inscode(d, ds, de, "EFAULT", EFAULT, "Bad address"); + inscode(d, ds, de, "EFAULT", EFAULT, "Bad address"); #else #ifdef WSAEFAULT - inscode(d, ds, de, "EFAULT", WSAEFAULT, "Bad address"); + inscode(d, ds, de, "EFAULT", WSAEFAULT, "Bad address"); #endif #endif #ifdef EFBIG - inscode(d, ds, de, "EFBIG", EFBIG, "File too large"); + inscode(d, ds, de, "EFBIG", EFBIG, "File too large"); #endif #ifdef EDEADLK - inscode(d, ds, de, "EDEADLK", EDEADLK, "Resource deadlock would occur"); + inscode(d, ds, de, "EDEADLK", EDEADLK, "Resource deadlock would occur"); #endif #ifdef ENOTCONN - inscode(d, ds, de, "ENOTCONN", ENOTCONN, "Transport endpoint is not connected"); + inscode(d, ds, de, "ENOTCONN", ENOTCONN, "Transport endpoint is not connected"); #else #ifdef WSAENOTCONN - inscode(d, ds, de, "ENOTCONN", WSAENOTCONN, "Transport endpoint is not connected"); + inscode(d, ds, de, "ENOTCONN", WSAENOTCONN, "Transport endpoint is not connected"); #endif #endif #ifdef EDESTADDRREQ - inscode(d, ds, de, "EDESTADDRREQ", EDESTADDRREQ, "Destination address required"); + inscode(d, ds, de, "EDESTADDRREQ", EDESTADDRREQ, "Destination address required"); #else #ifdef WSAEDESTADDRREQ - inscode(d, ds, de, "EDESTADDRREQ", WSAEDESTADDRREQ, "Destination address required"); + inscode(d, ds, de, "EDESTADDRREQ", WSAEDESTADDRREQ, "Destination address required"); #endif #endif #ifdef ELIBSCN - inscode(d, ds, de, "ELIBSCN", ELIBSCN, ".lib section in a.out corrupted"); + inscode(d, ds, de, "ELIBSCN", ELIBSCN, ".lib section in a.out corrupted"); #endif #ifdef ENOLCK - inscode(d, ds, de, "ENOLCK", ENOLCK, "No record locks available"); + inscode(d, ds, de, "ENOLCK", ENOLCK, "No record locks available"); #endif #ifdef EISNAM - inscode(d, ds, de, "EISNAM", EISNAM, "Is a named type file"); + inscode(d, ds, de, "EISNAM", EISNAM, "Is a named type file"); #endif #ifdef ECONNABORTED - inscode(d, ds, de, "ECONNABORTED", ECONNABORTED, "Software caused connection abort"); + inscode(d, ds, de, "ECONNABORTED", ECONNABORTED, "Software caused connection abort"); #else #ifdef WSAECONNABORTED - inscode(d, ds, de, "ECONNABORTED", WSAECONNABORTED, "Software caused connection abort"); + inscode(d, ds, de, "ECONNABORTED", WSAECONNABORTED, "Software caused connection abort"); #endif #endif #ifdef ENETUNREACH - inscode(d, ds, de, "ENETUNREACH", ENETUNREACH, "Network is unreachable"); + inscode(d, ds, de, "ENETUNREACH", ENETUNREACH, "Network is unreachable"); #else #ifdef WSAENETUNREACH - inscode(d, ds, de, "ENETUNREACH", WSAENETUNREACH, "Network is unreachable"); + inscode(d, ds, de, "ENETUNREACH", WSAENETUNREACH, "Network is unreachable"); #endif #endif #ifdef ESTALE - inscode(d, ds, de, "ESTALE", ESTALE, "Stale NFS file handle"); + inscode(d, ds, de, "ESTALE", ESTALE, "Stale NFS file handle"); #else #ifdef WSAESTALE - inscode(d, ds, de, "ESTALE", WSAESTALE, "Stale NFS file handle"); + inscode(d, ds, de, "ESTALE", WSAESTALE, "Stale NFS file handle"); #endif #endif #ifdef ENOSR - inscode(d, ds, de, "ENOSR", ENOSR, "Out of streams resources"); + inscode(d, ds, de, "ENOSR", ENOSR, "Out of streams resources"); #endif #ifdef ENOMEM - inscode(d, ds, de, "ENOMEM", ENOMEM, "Out of memory"); + inscode(d, ds, de, "ENOMEM", ENOMEM, "Out of memory"); #endif #ifdef ENOTSOCK - inscode(d, ds, de, "ENOTSOCK", ENOTSOCK, "Socket operation on non-socket"); + inscode(d, ds, de, "ENOTSOCK", ENOTSOCK, "Socket operation on non-socket"); #else #ifdef WSAENOTSOCK - inscode(d, ds, de, "ENOTSOCK", WSAENOTSOCK, "Socket operation on non-socket"); + inscode(d, ds, de, "ENOTSOCK", WSAENOTSOCK, "Socket operation on non-socket"); #endif #endif #ifdef ESTRPIPE - inscode(d, ds, de, "ESTRPIPE", ESTRPIPE, "Streams pipe error"); + inscode(d, ds, de, "ESTRPIPE", ESTRPIPE, "Streams pipe error"); #endif #ifdef EMLINK - inscode(d, ds, de, "EMLINK", EMLINK, "Too many links"); + inscode(d, ds, de, "EMLINK", EMLINK, "Too many links"); #endif #ifdef ERANGE - inscode(d, ds, de, "ERANGE", ERANGE, "Math result not representable"); + inscode(d, ds, de, "ERANGE", ERANGE, "Math result not representable"); #endif #ifdef ELIBEXEC - inscode(d, ds, de, "ELIBEXEC", ELIBEXEC, "Cannot exec a shared library directly"); + inscode(d, ds, de, "ELIBEXEC", ELIBEXEC, "Cannot exec a shared library directly"); #endif #ifdef EL3HLT - inscode(d, ds, de, "EL3HLT", EL3HLT, "Level 3 halted"); + inscode(d, ds, de, "EL3HLT", EL3HLT, "Level 3 halted"); #endif #ifdef ECONNRESET - inscode(d, ds, de, "ECONNRESET", ECONNRESET, "Connection reset by peer"); + inscode(d, ds, de, "ECONNRESET", ECONNRESET, "Connection reset by peer"); #else #ifdef WSAECONNRESET - inscode(d, ds, de, "ECONNRESET", WSAECONNRESET, "Connection reset by peer"); + inscode(d, ds, de, "ECONNRESET", WSAECONNRESET, "Connection reset by peer"); #endif #endif #ifdef EADDRINUSE - inscode(d, ds, de, "EADDRINUSE", EADDRINUSE, "Address already in use"); + inscode(d, ds, de, "EADDRINUSE", EADDRINUSE, "Address already in use"); #else #ifdef WSAEADDRINUSE - inscode(d, ds, de, "EADDRINUSE", WSAEADDRINUSE, "Address already in use"); + inscode(d, ds, de, "EADDRINUSE", WSAEADDRINUSE, "Address already in use"); #endif #endif #ifdef EOPNOTSUPP - inscode(d, ds, de, "EOPNOTSUPP", EOPNOTSUPP, "Operation not supported on transport endpoint"); + inscode(d, ds, de, "EOPNOTSUPP", EOPNOTSUPP, "Operation not supported on transport endpoint"); #else #ifdef WSAEOPNOTSUPP - inscode(d, ds, de, "EOPNOTSUPP", WSAEOPNOTSUPP, "Operation not supported on transport endpoint"); + inscode(d, ds, de, "EOPNOTSUPP", WSAEOPNOTSUPP, "Operation not supported on transport endpoint"); #endif #endif #ifdef EREMCHG - inscode(d, ds, de, "EREMCHG", EREMCHG, "Remote address changed"); + inscode(d, ds, de, "EREMCHG", EREMCHG, "Remote address changed"); #endif #ifdef EAGAIN - inscode(d, ds, de, "EAGAIN", EAGAIN, "Try again"); + inscode(d, ds, de, "EAGAIN", EAGAIN, "Try again"); #endif #ifdef ENAMETOOLONG - inscode(d, ds, de, "ENAMETOOLONG", ENAMETOOLONG, "File name too long"); + inscode(d, ds, de, "ENAMETOOLONG", ENAMETOOLONG, "File name too long"); #else #ifdef WSAENAMETOOLONG - inscode(d, ds, de, "ENAMETOOLONG", WSAENAMETOOLONG, "File name too long"); + inscode(d, ds, de, "ENAMETOOLONG", WSAENAMETOOLONG, "File name too long"); #endif #endif #ifdef ENOTTY - inscode(d, ds, de, "ENOTTY", ENOTTY, "Not a typewriter"); + inscode(d, ds, de, "ENOTTY", ENOTTY, "Not a typewriter"); #endif #ifdef ERESTART - inscode(d, ds, de, "ERESTART", ERESTART, "Interrupted system call should be restarted"); + inscode(d, ds, de, "ERESTART", ERESTART, "Interrupted system call should be restarted"); #endif #ifdef ESOCKTNOSUPPORT - inscode(d, ds, de, "ESOCKTNOSUPPORT", ESOCKTNOSUPPORT, "Socket type not supported"); + inscode(d, ds, de, "ESOCKTNOSUPPORT", ESOCKTNOSUPPORT, "Socket type not supported"); #else #ifdef WSAESOCKTNOSUPPORT - inscode(d, ds, de, "ESOCKTNOSUPPORT", WSAESOCKTNOSUPPORT, "Socket type not supported"); + inscode(d, ds, de, "ESOCKTNOSUPPORT", WSAESOCKTNOSUPPORT, "Socket type not supported"); #endif #endif #ifdef ETIME - inscode(d, ds, de, "ETIME", ETIME, "Timer expired"); + inscode(d, ds, de, "ETIME", ETIME, "Timer expired"); #endif #ifdef EBFONT - inscode(d, ds, de, "EBFONT", EBFONT, "Bad font file format"); + inscode(d, ds, de, "EBFONT", EBFONT, "Bad font file format"); #endif #ifdef EDEADLOCK - inscode(d, ds, de, "EDEADLOCK", EDEADLOCK, "Error EDEADLOCK"); + inscode(d, ds, de, "EDEADLOCK", EDEADLOCK, "Error EDEADLOCK"); #endif #ifdef ETOOMANYREFS - inscode(d, ds, de, "ETOOMANYREFS", ETOOMANYREFS, "Too many references: cannot splice"); + inscode(d, ds, de, "ETOOMANYREFS", ETOOMANYREFS, "Too many references: cannot splice"); #else #ifdef WSAETOOMANYREFS - inscode(d, ds, de, "ETOOMANYREFS", WSAETOOMANYREFS, "Too many references: cannot splice"); + inscode(d, ds, de, "ETOOMANYREFS", WSAETOOMANYREFS, "Too many references: cannot splice"); #endif #endif #ifdef EMFILE - inscode(d, ds, de, "EMFILE", EMFILE, "Too many open files"); + inscode(d, ds, de, "EMFILE", EMFILE, "Too many open files"); #else #ifdef WSAEMFILE - inscode(d, ds, de, "EMFILE", WSAEMFILE, "Too many open files"); + inscode(d, ds, de, "EMFILE", WSAEMFILE, "Too many open files"); #endif #endif #ifdef ETXTBSY - inscode(d, ds, de, "ETXTBSY", ETXTBSY, "Text file busy"); + inscode(d, ds, de, "ETXTBSY", ETXTBSY, "Text file busy"); #endif #ifdef EINPROGRESS - inscode(d, ds, de, "EINPROGRESS", EINPROGRESS, "Operation now in progress"); + inscode(d, ds, de, "EINPROGRESS", EINPROGRESS, "Operation now in progress"); #else #ifdef WSAEINPROGRESS - inscode(d, ds, de, "EINPROGRESS", WSAEINPROGRESS, "Operation now in progress"); + inscode(d, ds, de, "EINPROGRESS", WSAEINPROGRESS, "Operation now in progress"); #endif #endif #ifdef ENXIO - inscode(d, ds, de, "ENXIO", ENXIO, "No such device or address"); + inscode(d, ds, de, "ENXIO", ENXIO, "No such device or address"); #endif #ifdef ENOPKG - inscode(d, ds, de, "ENOPKG", ENOPKG, "Package not installed"); + inscode(d, ds, de, "ENOPKG", ENOPKG, "Package not installed"); #endif #ifdef WSASY - inscode(d, ds, de, "WSASY", WSASY, "Error WSASY"); + inscode(d, ds, de, "WSASY", WSASY, "Error WSASY"); #endif #ifdef WSAEHOSTDOWN - inscode(d, ds, de, "WSAEHOSTDOWN", WSAEHOSTDOWN, "Host is down"); + inscode(d, ds, de, "WSAEHOSTDOWN", WSAEHOSTDOWN, "Host is down"); #endif #ifdef WSAENETDOWN - inscode(d, ds, de, "WSAENETDOWN", WSAENETDOWN, "Network is down"); + inscode(d, ds, de, "WSAENETDOWN", WSAENETDOWN, "Network is down"); #endif #ifdef WSAENOTSOCK - inscode(d, ds, de, "WSAENOTSOCK", WSAENOTSOCK, "Socket operation on non-socket"); + inscode(d, ds, de, "WSAENOTSOCK", WSAENOTSOCK, "Socket operation on non-socket"); #endif #ifdef WSAEHOSTUNREACH - inscode(d, ds, de, "WSAEHOSTUNREACH", WSAEHOSTUNREACH, "No route to host"); + inscode(d, ds, de, "WSAEHOSTUNREACH", WSAEHOSTUNREACH, "No route to host"); #endif #ifdef WSAELOOP - inscode(d, ds, de, "WSAELOOP", WSAELOOP, "Too many symbolic links encountered"); + inscode(d, ds, de, "WSAELOOP", WSAELOOP, "Too many symbolic links encountered"); #endif #ifdef WSAEMFILE - inscode(d, ds, de, "WSAEMFILE", WSAEMFILE, "Too many open files"); + inscode(d, ds, de, "WSAEMFILE", WSAEMFILE, "Too many open files"); #endif #ifdef WSAESTALE - inscode(d, ds, de, "WSAESTALE", WSAESTALE, "Stale NFS file handle"); + inscode(d, ds, de, "WSAESTALE", WSAESTALE, "Stale NFS file handle"); #endif #ifdef WSAVERNOTSUPPORTED - inscode(d, ds, de, "WSAVERNOTSUPPORTED", WSAVERNOTSUPPORTED, "Error WSAVERNOTSUPPORTED"); + inscode(d, ds, de, "WSAVERNOTSUPPORTED", WSAVERNOTSUPPORTED, "Error WSAVERNOTSUPPORTED"); #endif #ifdef WSAENETUNREACH - inscode(d, ds, de, "WSAENETUNREACH", WSAENETUNREACH, "Network is unreachable"); + inscode(d, ds, de, "WSAENETUNREACH", WSAENETUNREACH, "Network is unreachable"); #endif #ifdef WSAEPROCLIM - inscode(d, ds, de, "WSAEPROCLIM", WSAEPROCLIM, "Error WSAEPROCLIM"); + inscode(d, ds, de, "WSAEPROCLIM", WSAEPROCLIM, "Error WSAEPROCLIM"); #endif #ifdef WSAEFAULT - inscode(d, ds, de, "WSAEFAULT", WSAEFAULT, "Bad address"); + inscode(d, ds, de, "WSAEFAULT", WSAEFAULT, "Bad address"); #endif #ifdef WSANOTINITIALISED - inscode(d, ds, de, "WSANOTINITIALISED", WSANOTINITIALISED, "Error WSANOTINITIALISED"); + inscode(d, ds, de, "WSANOTINITIALISED", WSANOTINITIALISED, "Error WSANOTINITIALISED"); #endif #ifdef WSAEUSERS - inscode(d, ds, de, "WSAEUSERS", WSAEUSERS, "Too many users"); + inscode(d, ds, de, "WSAEUSERS", WSAEUSERS, "Too many users"); #endif #ifdef WSAMAKEASYNCREPL - inscode(d, ds, de, "WSAMAKEASYNCREPL", WSAMAKEASYNCREPL, "Error WSAMAKEASYNCREPL"); + inscode(d, ds, de, "WSAMAKEASYNCREPL", WSAMAKEASYNCREPL, "Error WSAMAKEASYNCREPL"); #endif #ifdef WSAENOPROTOOPT - inscode(d, ds, de, "WSAENOPROTOOPT", WSAENOPROTOOPT, "Protocol not available"); + inscode(d, ds, de, "WSAENOPROTOOPT", WSAENOPROTOOPT, "Protocol not available"); #endif #ifdef WSAECONNABORTED - inscode(d, ds, de, "WSAECONNABORTED", WSAECONNABORTED, "Software caused connection abort"); + inscode(d, ds, de, "WSAECONNABORTED", WSAECONNABORTED, "Software caused connection abort"); #endif #ifdef WSAENAMETOOLONG - inscode(d, ds, de, "WSAENAMETOOLONG", WSAENAMETOOLONG, "File name too long"); + inscode(d, ds, de, "WSAENAMETOOLONG", WSAENAMETOOLONG, "File name too long"); #endif #ifdef WSAENOTEMPTY - inscode(d, ds, de, "WSAENOTEMPTY", WSAENOTEMPTY, "Directory not empty"); + inscode(d, ds, de, "WSAENOTEMPTY", WSAENOTEMPTY, "Directory not empty"); #endif #ifdef WSAESHUTDOWN - inscode(d, ds, de, "WSAESHUTDOWN", WSAESHUTDOWN, "Cannot send after transport endpoint shutdown"); + inscode(d, ds, de, "WSAESHUTDOWN", WSAESHUTDOWN, "Cannot send after transport endpoint shutdown"); #endif #ifdef WSAEAFNOSUPPORT - inscode(d, ds, de, "WSAEAFNOSUPPORT", WSAEAFNOSUPPORT, "Address family not supported by protocol"); + inscode(d, ds, de, "WSAEAFNOSUPPORT", WSAEAFNOSUPPORT, "Address family not supported by protocol"); #endif #ifdef WSAETOOMANYREFS - inscode(d, ds, de, "WSAETOOMANYREFS", WSAETOOMANYREFS, "Too many references: cannot splice"); + inscode(d, ds, de, "WSAETOOMANYREFS", WSAETOOMANYREFS, "Too many references: cannot splice"); #endif #ifdef WSAEACCES - inscode(d, ds, de, "WSAEACCES", WSAEACCES, "Permission denied"); + inscode(d, ds, de, "WSAEACCES", WSAEACCES, "Permission denied"); #endif #ifdef WSATR - inscode(d, ds, de, "WSATR", WSATR, "Error WSATR"); + inscode(d, ds, de, "WSATR", WSATR, "Error WSATR"); #endif #ifdef WSABASEERR - inscode(d, ds, de, "WSABASEERR", WSABASEERR, "Error WSABASEERR"); + inscode(d, ds, de, "WSABASEERR", WSABASEERR, "Error WSABASEERR"); #endif #ifdef WSADESCRIPTIO - inscode(d, ds, de, "WSADESCRIPTIO", WSADESCRIPTIO, "Error WSADESCRIPTIO"); + inscode(d, ds, de, "WSADESCRIPTIO", WSADESCRIPTIO, "Error WSADESCRIPTIO"); #endif #ifdef WSAEMSGSIZE - inscode(d, ds, de, "WSAEMSGSIZE", WSAEMSGSIZE, "Message too long"); + inscode(d, ds, de, "WSAEMSGSIZE", WSAEMSGSIZE, "Message too long"); #endif #ifdef WSAEBADF - inscode(d, ds, de, "WSAEBADF", WSAEBADF, "Bad file number"); + inscode(d, ds, de, "WSAEBADF", WSAEBADF, "Bad file number"); #endif #ifdef WSAECONNRESET - inscode(d, ds, de, "WSAECONNRESET", WSAECONNRESET, "Connection reset by peer"); + inscode(d, ds, de, "WSAECONNRESET", WSAECONNRESET, "Connection reset by peer"); #endif #ifdef WSAGETSELECTERRO - inscode(d, ds, de, "WSAGETSELECTERRO", WSAGETSELECTERRO, "Error WSAGETSELECTERRO"); + inscode(d, ds, de, "WSAGETSELECTERRO", WSAGETSELECTERRO, "Error WSAGETSELECTERRO"); #endif #ifdef WSAETIMEDOUT - inscode(d, ds, de, "WSAETIMEDOUT", WSAETIMEDOUT, "Connection timed out"); + inscode(d, ds, de, "WSAETIMEDOUT", WSAETIMEDOUT, "Connection timed out"); #endif #ifdef WSAENOBUFS - inscode(d, ds, de, "WSAENOBUFS", WSAENOBUFS, "No buffer space available"); + inscode(d, ds, de, "WSAENOBUFS", WSAENOBUFS, "No buffer space available"); #endif #ifdef WSAEDISCON - inscode(d, ds, de, "WSAEDISCON", WSAEDISCON, "Error WSAEDISCON"); + inscode(d, ds, de, "WSAEDISCON", WSAEDISCON, "Error WSAEDISCON"); #endif #ifdef WSAEINTR - inscode(d, ds, de, "WSAEINTR", WSAEINTR, "Interrupted system call"); + inscode(d, ds, de, "WSAEINTR", WSAEINTR, "Interrupted system call"); #endif #ifdef WSAEPROTOTYPE - inscode(d, ds, de, "WSAEPROTOTYPE", WSAEPROTOTYPE, "Protocol wrong type for socket"); + inscode(d, ds, de, "WSAEPROTOTYPE", WSAEPROTOTYPE, "Protocol wrong type for socket"); #endif #ifdef WSAHOS - inscode(d, ds, de, "WSAHOS", WSAHOS, "Error WSAHOS"); + inscode(d, ds, de, "WSAHOS", WSAHOS, "Error WSAHOS"); #endif #ifdef WSAEADDRINUSE - inscode(d, ds, de, "WSAEADDRINUSE", WSAEADDRINUSE, "Address already in use"); + inscode(d, ds, de, "WSAEADDRINUSE", WSAEADDRINUSE, "Address already in use"); #endif #ifdef WSAEADDRNOTAVAIL - inscode(d, ds, de, "WSAEADDRNOTAVAIL", WSAEADDRNOTAVAIL, "Cannot assign requested address"); + inscode(d, ds, de, "WSAEADDRNOTAVAIL", WSAEADDRNOTAVAIL, "Cannot assign requested address"); #endif #ifdef WSAEALREADY - inscode(d, ds, de, "WSAEALREADY", WSAEALREADY, "Operation already in progress"); + inscode(d, ds, de, "WSAEALREADY", WSAEALREADY, "Operation already in progress"); #endif #ifdef WSAEPROTONOSUPPORT - inscode(d, ds, de, "WSAEPROTONOSUPPORT", WSAEPROTONOSUPPORT, "Protocol not supported"); + inscode(d, ds, de, "WSAEPROTONOSUPPORT", WSAEPROTONOSUPPORT, "Protocol not supported"); #endif #ifdef WSASYSNOTREADY - inscode(d, ds, de, "WSASYSNOTREADY", WSASYSNOTREADY, "Error WSASYSNOTREADY"); + inscode(d, ds, de, "WSASYSNOTREADY", WSASYSNOTREADY, "Error WSASYSNOTREADY"); #endif #ifdef WSAEWOULDBLOCK - inscode(d, ds, de, "WSAEWOULDBLOCK", WSAEWOULDBLOCK, "Operation would block"); + inscode(d, ds, de, "WSAEWOULDBLOCK", WSAEWOULDBLOCK, "Operation would block"); #endif #ifdef WSAEPFNOSUPPORT - inscode(d, ds, de, "WSAEPFNOSUPPORT", WSAEPFNOSUPPORT, "Protocol family not supported"); + inscode(d, ds, de, "WSAEPFNOSUPPORT", WSAEPFNOSUPPORT, "Protocol family not supported"); #endif #ifdef WSAEOPNOTSUPP - inscode(d, ds, de, "WSAEOPNOTSUPP", WSAEOPNOTSUPP, "Operation not supported on transport endpoint"); + inscode(d, ds, de, "WSAEOPNOTSUPP", WSAEOPNOTSUPP, "Operation not supported on transport endpoint"); #endif #ifdef WSAEISCONN - inscode(d, ds, de, "WSAEISCONN", WSAEISCONN, "Transport endpoint is already connected"); + inscode(d, ds, de, "WSAEISCONN", WSAEISCONN, "Transport endpoint is already connected"); #endif #ifdef WSAEDQUOT - inscode(d, ds, de, "WSAEDQUOT", WSAEDQUOT, "Quota exceeded"); + inscode(d, ds, de, "WSAEDQUOT", WSAEDQUOT, "Quota exceeded"); #endif #ifdef WSAENOTCONN - inscode(d, ds, de, "WSAENOTCONN", WSAENOTCONN, "Transport endpoint is not connected"); + inscode(d, ds, de, "WSAENOTCONN", WSAENOTCONN, "Transport endpoint is not connected"); #endif #ifdef WSAEREMOTE - inscode(d, ds, de, "WSAEREMOTE", WSAEREMOTE, "Object is remote"); + inscode(d, ds, de, "WSAEREMOTE", WSAEREMOTE, "Object is remote"); #endif #ifdef WSAEINVAL - inscode(d, ds, de, "WSAEINVAL", WSAEINVAL, "Invalid argument"); + inscode(d, ds, de, "WSAEINVAL", WSAEINVAL, "Invalid argument"); #endif #ifdef WSAEINPROGRESS - inscode(d, ds, de, "WSAEINPROGRESS", WSAEINPROGRESS, "Operation now in progress"); + inscode(d, ds, de, "WSAEINPROGRESS", WSAEINPROGRESS, "Operation now in progress"); #endif #ifdef WSAGETSELECTEVEN - inscode(d, ds, de, "WSAGETSELECTEVEN", WSAGETSELECTEVEN, "Error WSAGETSELECTEVEN"); + inscode(d, ds, de, "WSAGETSELECTEVEN", WSAGETSELECTEVEN, "Error WSAGETSELECTEVEN"); #endif #ifdef WSAESOCKTNOSUPPORT - inscode(d, ds, de, "WSAESOCKTNOSUPPORT", WSAESOCKTNOSUPPORT, "Socket type not supported"); + inscode(d, ds, de, "WSAESOCKTNOSUPPORT", WSAESOCKTNOSUPPORT, "Socket type not supported"); #endif #ifdef WSAGETASYNCERRO - inscode(d, ds, de, "WSAGETASYNCERRO", WSAGETASYNCERRO, "Error WSAGETASYNCERRO"); + inscode(d, ds, de, "WSAGETASYNCERRO", WSAGETASYNCERRO, "Error WSAGETASYNCERRO"); #endif #ifdef WSAMAKESELECTREPL - inscode(d, ds, de, "WSAMAKESELECTREPL", WSAMAKESELECTREPL, "Error WSAMAKESELECTREPL"); + inscode(d, ds, de, "WSAMAKESELECTREPL", WSAMAKESELECTREPL, "Error WSAMAKESELECTREPL"); #endif #ifdef WSAGETASYNCBUFLE - inscode(d, ds, de, "WSAGETASYNCBUFLE", WSAGETASYNCBUFLE, "Error WSAGETASYNCBUFLE"); + inscode(d, ds, de, "WSAGETASYNCBUFLE", WSAGETASYNCBUFLE, "Error WSAGETASYNCBUFLE"); #endif #ifdef WSAEDESTADDRREQ - inscode(d, ds, de, "WSAEDESTADDRREQ", WSAEDESTADDRREQ, "Destination address required"); + inscode(d, ds, de, "WSAEDESTADDRREQ", WSAEDESTADDRREQ, "Destination address required"); #endif #ifdef WSAECONNREFUSED - inscode(d, ds, de, "WSAECONNREFUSED", WSAECONNREFUSED, "Connection refused"); + inscode(d, ds, de, "WSAECONNREFUSED", WSAECONNREFUSED, "Connection refused"); #endif #ifdef WSAENETRESET - inscode(d, ds, de, "WSAENETRESET", WSAENETRESET, "Network dropped connection because of reset"); + inscode(d, ds, de, "WSAENETRESET", WSAENETRESET, "Network dropped connection because of reset"); #endif #ifdef WSAN - inscode(d, ds, de, "WSAN", WSAN, "Error WSAN"); + inscode(d, ds, de, "WSAN", WSAN, "Error WSAN"); #endif - Py_DECREF(de); - return m; + Py_DECREF(de); + return m; } Modified: python/branches/release31-maint/Modules/fcntlmodule.c ============================================================================== --- python/branches/release31-maint/Modules/fcntlmodule.c (original) +++ python/branches/release31-maint/Modules/fcntlmodule.c Sun May 9 18:14:21 2010 @@ -21,7 +21,7 @@ int fd = PyObject_AsFileDescriptor(object); if (fd < 0) - return 0; + return 0; *target = fd; return 1; } @@ -32,48 +32,48 @@ static PyObject * fcntl_fcntl(PyObject *self, PyObject *args) { - int fd; - int code; - long arg; - int ret; - char *str; - Py_ssize_t len; - char buf[1024]; - - if (PyArg_ParseTuple(args, "O&is#:fcntl", - conv_descriptor, &fd, &code, &str, &len)) { - if (len > sizeof buf) { - PyErr_SetString(PyExc_ValueError, - "fcntl string arg too long"); - return NULL; - } - memcpy(buf, str, len); - Py_BEGIN_ALLOW_THREADS - ret = fcntl(fd, code, buf); - Py_END_ALLOW_THREADS - if (ret < 0) { - PyErr_SetFromErrno(PyExc_IOError); - return NULL; - } - return PyBytes_FromStringAndSize(buf, len); - } - - PyErr_Clear(); - arg = 0; - if (!PyArg_ParseTuple(args, - "O&i|l;fcntl requires a file or file descriptor," - " an integer and optionally a third integer or a string", - conv_descriptor, &fd, &code, &arg)) { - return NULL; - } - Py_BEGIN_ALLOW_THREADS - ret = fcntl(fd, code, arg); - Py_END_ALLOW_THREADS - if (ret < 0) { - PyErr_SetFromErrno(PyExc_IOError); - return NULL; - } - return PyLong_FromLong((long)ret); + int fd; + int code; + long arg; + int ret; + char *str; + Py_ssize_t len; + char buf[1024]; + + if (PyArg_ParseTuple(args, "O&is#:fcntl", + conv_descriptor, &fd, &code, &str, &len)) { + if (len > sizeof buf) { + PyErr_SetString(PyExc_ValueError, + "fcntl string arg too long"); + return NULL; + } + memcpy(buf, str, len); + Py_BEGIN_ALLOW_THREADS + ret = fcntl(fd, code, buf); + Py_END_ALLOW_THREADS + if (ret < 0) { + PyErr_SetFromErrno(PyExc_IOError); + return NULL; + } + return PyBytes_FromStringAndSize(buf, len); + } + + PyErr_Clear(); + arg = 0; + if (!PyArg_ParseTuple(args, + "O&i|l;fcntl requires a file or file descriptor," + " an integer and optionally a third integer or a string", + conv_descriptor, &fd, &code, &arg)) { + return NULL; + } + Py_BEGIN_ALLOW_THREADS + ret = fcntl(fd, code, arg); + Py_END_ALLOW_THREADS + if (ret < 0) { + PyErr_SetFromErrno(PyExc_IOError); + return NULL; + } + return PyLong_FromLong((long)ret); } PyDoc_STRVAR(fcntl_doc, @@ -96,128 +96,128 @@ fcntl_ioctl(PyObject *self, PyObject *args) { #define IOCTL_BUFSZ 1024 - int fd; - /* In PyArg_ParseTuple below, we use the unsigned non-checked 'I' - format for the 'code' parameter because Python turns 0x8000000 - into either a large positive number (PyLong or PyInt on 64-bit - platforms) or a negative number on others (32-bit PyInt) - whereas the system expects it to be a 32bit bit field value - regardless of it being passed as an int or unsigned long on - various platforms. See the termios.TIOCSWINSZ constant across - platforms for an example of thise. - - If any of the 64bit platforms ever decide to use more than 32bits - in their unsigned long ioctl codes this will break and need - special casing based on the platform being built on. - */ - unsigned int code; - int arg; - int ret; - Py_buffer pstr; - char *str; - Py_ssize_t len; - int mutate_arg = 1; - char buf[IOCTL_BUFSZ+1]; /* argument plus NUL byte */ - - if (PyArg_ParseTuple(args, "O&Iw*|i:ioctl", - conv_descriptor, &fd, &code, - &pstr, &mutate_arg)) { - char *arg; - str = pstr.buf; - len = pstr.len; - - if (mutate_arg) { - if (len <= IOCTL_BUFSZ) { - memcpy(buf, str, len); - buf[len] = '\0'; - arg = buf; - } - else { - arg = str; - } - } - else { - if (len > IOCTL_BUFSZ) { - PyBuffer_Release(&pstr); - PyErr_SetString(PyExc_ValueError, - "ioctl string arg too long"); - return NULL; - } - else { - memcpy(buf, str, len); - buf[len] = '\0'; - arg = buf; - } - } - if (buf == arg) { - Py_BEGIN_ALLOW_THREADS /* think array.resize() */ - ret = ioctl(fd, code, arg); - Py_END_ALLOW_THREADS - } - else { - ret = ioctl(fd, code, arg); - } - if (mutate_arg && (len < IOCTL_BUFSZ)) { - memcpy(str, buf, len); - } - PyBuffer_Release(&pstr); /* No further access to str below this point */ - if (ret < 0) { - PyErr_SetFromErrno(PyExc_IOError); - return NULL; - } - if (mutate_arg) { - return PyLong_FromLong(ret); - } - else { - return PyBytes_FromStringAndSize(buf, len); - } - } - - PyErr_Clear(); - if (PyArg_ParseTuple(args, "O&Is*:ioctl", - conv_descriptor, &fd, &code, &pstr)) { - str = pstr.buf; - len = pstr.len; - if (len > IOCTL_BUFSZ) { - PyBuffer_Release(&pstr); - PyErr_SetString(PyExc_ValueError, - "ioctl string arg too long"); - return NULL; - } - memcpy(buf, str, len); - buf[len] = '\0'; - Py_BEGIN_ALLOW_THREADS - ret = ioctl(fd, code, buf); - Py_END_ALLOW_THREADS - if (ret < 0) { - PyBuffer_Release(&pstr); - PyErr_SetFromErrno(PyExc_IOError); - return NULL; - } - PyBuffer_Release(&pstr); - return PyBytes_FromStringAndSize(buf, len); - } - - PyErr_Clear(); - arg = 0; - if (!PyArg_ParseTuple(args, - "O&I|i;ioctl requires a file or file descriptor," - " an integer and optionally an integer or buffer argument", - conv_descriptor, &fd, &code, &arg)) { - return NULL; - } - Py_BEGIN_ALLOW_THREADS + int fd; + /* In PyArg_ParseTuple below, we use the unsigned non-checked 'I' + format for the 'code' parameter because Python turns 0x8000000 + into either a large positive number (PyLong or PyInt on 64-bit + platforms) or a negative number on others (32-bit PyInt) + whereas the system expects it to be a 32bit bit field value + regardless of it being passed as an int or unsigned long on + various platforms. See the termios.TIOCSWINSZ constant across + platforms for an example of thise. + + If any of the 64bit platforms ever decide to use more than 32bits + in their unsigned long ioctl codes this will break and need + special casing based on the platform being built on. + */ + unsigned int code; + int arg; + int ret; + Py_buffer pstr; + char *str; + Py_ssize_t len; + int mutate_arg = 1; + char buf[IOCTL_BUFSZ+1]; /* argument plus NUL byte */ + + if (PyArg_ParseTuple(args, "O&Iw*|i:ioctl", + conv_descriptor, &fd, &code, + &pstr, &mutate_arg)) { + char *arg; + str = pstr.buf; + len = pstr.len; + + if (mutate_arg) { + if (len <= IOCTL_BUFSZ) { + memcpy(buf, str, len); + buf[len] = '\0'; + arg = buf; + } + else { + arg = str; + } + } + else { + if (len > IOCTL_BUFSZ) { + PyBuffer_Release(&pstr); + PyErr_SetString(PyExc_ValueError, + "ioctl string arg too long"); + return NULL; + } + else { + memcpy(buf, str, len); + buf[len] = '\0'; + arg = buf; + } + } + if (buf == arg) { + Py_BEGIN_ALLOW_THREADS /* think array.resize() */ + ret = ioctl(fd, code, arg); + Py_END_ALLOW_THREADS + } + else { + ret = ioctl(fd, code, arg); + } + if (mutate_arg && (len < IOCTL_BUFSZ)) { + memcpy(str, buf, len); + } + PyBuffer_Release(&pstr); /* No further access to str below this point */ + if (ret < 0) { + PyErr_SetFromErrno(PyExc_IOError); + return NULL; + } + if (mutate_arg) { + return PyLong_FromLong(ret); + } + else { + return PyBytes_FromStringAndSize(buf, len); + } + } + + PyErr_Clear(); + if (PyArg_ParseTuple(args, "O&Is*:ioctl", + conv_descriptor, &fd, &code, &pstr)) { + str = pstr.buf; + len = pstr.len; + if (len > IOCTL_BUFSZ) { + PyBuffer_Release(&pstr); + PyErr_SetString(PyExc_ValueError, + "ioctl string arg too long"); + return NULL; + } + memcpy(buf, str, len); + buf[len] = '\0'; + Py_BEGIN_ALLOW_THREADS + ret = ioctl(fd, code, buf); + Py_END_ALLOW_THREADS + if (ret < 0) { + PyBuffer_Release(&pstr); + PyErr_SetFromErrno(PyExc_IOError); + return NULL; + } + PyBuffer_Release(&pstr); + return PyBytes_FromStringAndSize(buf, len); + } + + PyErr_Clear(); + arg = 0; + if (!PyArg_ParseTuple(args, + "O&I|i;ioctl requires a file or file descriptor," + " an integer and optionally an integer or buffer argument", + conv_descriptor, &fd, &code, &arg)) { + return NULL; + } + Py_BEGIN_ALLOW_THREADS #ifdef __VMS - ret = ioctl(fd, code, (void *)arg); + ret = ioctl(fd, code, (void *)arg); #else - ret = ioctl(fd, code, arg); + ret = ioctl(fd, code, arg); #endif - Py_END_ALLOW_THREADS - if (ret < 0) { - PyErr_SetFromErrno(PyExc_IOError); - return NULL; - } - return PyLong_FromLong((long)ret); + Py_END_ALLOW_THREADS + if (ret < 0) { + PyErr_SetFromErrno(PyExc_IOError); + return NULL; + } + return PyLong_FromLong((long)ret); #undef IOCTL_BUFSZ } @@ -258,51 +258,51 @@ static PyObject * fcntl_flock(PyObject *self, PyObject *args) { - int fd; - int code; - int ret; - - if (!PyArg_ParseTuple(args, "O&i:flock", - conv_descriptor, &fd, &code)) - return NULL; + int fd; + int code; + int ret; + + if (!PyArg_ParseTuple(args, "O&i:flock", + conv_descriptor, &fd, &code)) + return NULL; #ifdef HAVE_FLOCK - Py_BEGIN_ALLOW_THREADS - ret = flock(fd, code); - Py_END_ALLOW_THREADS + Py_BEGIN_ALLOW_THREADS + ret = flock(fd, code); + Py_END_ALLOW_THREADS #else #ifndef LOCK_SH -#define LOCK_SH 1 /* shared lock */ -#define LOCK_EX 2 /* exclusive lock */ -#define LOCK_NB 4 /* don't block when locking */ -#define LOCK_UN 8 /* unlock */ -#endif - { - struct flock l; - if (code == LOCK_UN) - l.l_type = F_UNLCK; - else if (code & LOCK_SH) - l.l_type = F_RDLCK; - else if (code & LOCK_EX) - l.l_type = F_WRLCK; - else { - PyErr_SetString(PyExc_ValueError, - "unrecognized flock argument"); - return NULL; - } - l.l_whence = l.l_start = l.l_len = 0; - Py_BEGIN_ALLOW_THREADS - ret = fcntl(fd, (code & LOCK_NB) ? F_SETLK : F_SETLKW, &l); - Py_END_ALLOW_THREADS - } +#define LOCK_SH 1 /* shared lock */ +#define LOCK_EX 2 /* exclusive lock */ +#define LOCK_NB 4 /* don't block when locking */ +#define LOCK_UN 8 /* unlock */ +#endif + { + struct flock l; + if (code == LOCK_UN) + l.l_type = F_UNLCK; + else if (code & LOCK_SH) + l.l_type = F_RDLCK; + else if (code & LOCK_EX) + l.l_type = F_WRLCK; + else { + PyErr_SetString(PyExc_ValueError, + "unrecognized flock argument"); + return NULL; + } + l.l_whence = l.l_start = l.l_len = 0; + Py_BEGIN_ALLOW_THREADS + ret = fcntl(fd, (code & LOCK_NB) ? F_SETLK : F_SETLKW, &l); + Py_END_ALLOW_THREADS + } #endif /* HAVE_FLOCK */ - if (ret < 0) { - PyErr_SetFromErrno(PyExc_IOError); - return NULL; - } - Py_INCREF(Py_None); - return Py_None; + if (ret < 0) { + PyErr_SetFromErrno(PyExc_IOError); + return NULL; + } + Py_INCREF(Py_None); + return Py_None; } PyDoc_STRVAR(flock_doc, @@ -317,72 +317,72 @@ static PyObject * fcntl_lockf(PyObject *self, PyObject *args) { - int fd, code, ret, whence = 0; - PyObject *lenobj = NULL, *startobj = NULL; + int fd, code, ret, whence = 0; + PyObject *lenobj = NULL, *startobj = NULL; - if (!PyArg_ParseTuple(args, "O&i|OOi:lockf", - conv_descriptor, &fd, &code, - &lenobj, &startobj, &whence)) - return NULL; + if (!PyArg_ParseTuple(args, "O&i|OOi:lockf", + conv_descriptor, &fd, &code, + &lenobj, &startobj, &whence)) + return NULL; #if defined(PYOS_OS2) && defined(PYCC_GCC) - PyErr_SetString(PyExc_NotImplementedError, - "lockf not supported on OS/2 (EMX)"); - return NULL; + PyErr_SetString(PyExc_NotImplementedError, + "lockf not supported on OS/2 (EMX)"); + return NULL; #else #ifndef LOCK_SH -#define LOCK_SH 1 /* shared lock */ -#define LOCK_EX 2 /* exclusive lock */ -#define LOCK_NB 4 /* don't block when locking */ -#define LOCK_UN 8 /* unlock */ +#define LOCK_SH 1 /* shared lock */ +#define LOCK_EX 2 /* exclusive lock */ +#define LOCK_NB 4 /* don't block when locking */ +#define LOCK_UN 8 /* unlock */ #endif /* LOCK_SH */ - { - struct flock l; - if (code == LOCK_UN) - l.l_type = F_UNLCK; - else if (code & LOCK_SH) - l.l_type = F_RDLCK; - else if (code & LOCK_EX) - l.l_type = F_WRLCK; - else { - PyErr_SetString(PyExc_ValueError, - "unrecognized lockf argument"); - return NULL; - } - l.l_start = l.l_len = 0; - if (startobj != NULL) { + { + struct flock l; + if (code == LOCK_UN) + l.l_type = F_UNLCK; + else if (code & LOCK_SH) + l.l_type = F_RDLCK; + else if (code & LOCK_EX) + l.l_type = F_WRLCK; + else { + PyErr_SetString(PyExc_ValueError, + "unrecognized lockf argument"); + return NULL; + } + l.l_start = l.l_len = 0; + if (startobj != NULL) { #if !defined(HAVE_LARGEFILE_SUPPORT) - l.l_start = PyLong_AsLong(startobj); + l.l_start = PyLong_AsLong(startobj); #else - l.l_start = PyLong_Check(startobj) ? - PyLong_AsLongLong(startobj) : - PyLong_AsLong(startobj); -#endif - if (PyErr_Occurred()) - return NULL; - } - if (lenobj != NULL) { + l.l_start = PyLong_Check(startobj) ? + PyLong_AsLongLong(startobj) : + PyLong_AsLong(startobj); +#endif + if (PyErr_Occurred()) + return NULL; + } + if (lenobj != NULL) { #if !defined(HAVE_LARGEFILE_SUPPORT) - l.l_len = PyLong_AsLong(lenobj); + l.l_len = PyLong_AsLong(lenobj); #else - l.l_len = PyLong_Check(lenobj) ? - PyLong_AsLongLong(lenobj) : - PyLong_AsLong(lenobj); -#endif - if (PyErr_Occurred()) - return NULL; - } - l.l_whence = whence; - Py_BEGIN_ALLOW_THREADS - ret = fcntl(fd, (code & LOCK_NB) ? F_SETLK : F_SETLKW, &l); - Py_END_ALLOW_THREADS - } - if (ret < 0) { - PyErr_SetFromErrno(PyExc_IOError); - return NULL; - } - Py_INCREF(Py_None); - return Py_None; + l.l_len = PyLong_Check(lenobj) ? + PyLong_AsLongLong(lenobj) : + PyLong_AsLong(lenobj); +#endif + if (PyErr_Occurred()) + return NULL; + } + l.l_whence = whence; + Py_BEGIN_ALLOW_THREADS + ret = fcntl(fd, (code & LOCK_NB) ? F_SETLK : F_SETLKW, &l); + Py_END_ALLOW_THREADS + } + if (ret < 0) { + PyErr_SetFromErrno(PyExc_IOError); + return NULL; + } + Py_INCREF(Py_None); + return Py_None; #endif /* defined(PYOS_OS2) && defined(PYCC_GCC) */ } @@ -414,11 +414,11 @@ /* List of functions */ static PyMethodDef fcntl_methods[] = { - {"fcntl", fcntl_fcntl, METH_VARARGS, fcntl_doc}, - {"ioctl", fcntl_ioctl, METH_VARARGS, ioctl_doc}, - {"flock", fcntl_flock, METH_VARARGS, flock_doc}, - {"lockf", fcntl_lockf, METH_VARARGS, lockf_doc}, - {NULL, NULL} /* sentinel */ + {"fcntl", fcntl_fcntl, METH_VARARGS, fcntl_doc}, + {"ioctl", fcntl_ioctl, METH_VARARGS, ioctl_doc}, + {"flock", fcntl_flock, METH_VARARGS, flock_doc}, + {"lockf", fcntl_lockf, METH_VARARGS, lockf_doc}, + {NULL, NULL} /* sentinel */ }; @@ -433,12 +433,12 @@ static int ins(PyObject* d, char* symbol, long value) { - PyObject* v = PyLong_FromLong(value); - if (!v || PyDict_SetItemString(d, symbol, v) < 0) - return -1; + PyObject* v = PyLong_FromLong(value); + if (!v || PyDict_SetItemString(d, symbol, v) < 0) + return -1; - Py_DECREF(v); - return 0; + Py_DECREF(v); + return 0; } #define INS(x) if (ins(d, #x, (long)x)) return -1 @@ -446,199 +446,199 @@ static int all_ins(PyObject* d) { - if (ins(d, "LOCK_SH", (long)LOCK_SH)) return -1; - if (ins(d, "LOCK_EX", (long)LOCK_EX)) return -1; - if (ins(d, "LOCK_NB", (long)LOCK_NB)) return -1; - if (ins(d, "LOCK_UN", (long)LOCK_UN)) return -1; + if (ins(d, "LOCK_SH", (long)LOCK_SH)) return -1; + if (ins(d, "LOCK_EX", (long)LOCK_EX)) return -1; + if (ins(d, "LOCK_NB", (long)LOCK_NB)) return -1; + if (ins(d, "LOCK_UN", (long)LOCK_UN)) return -1; /* GNU extensions, as of glibc 2.2.4 */ #ifdef LOCK_MAND - if (ins(d, "LOCK_MAND", (long)LOCK_MAND)) return -1; + if (ins(d, "LOCK_MAND", (long)LOCK_MAND)) return -1; #endif #ifdef LOCK_READ - if (ins(d, "LOCK_READ", (long)LOCK_READ)) return -1; + if (ins(d, "LOCK_READ", (long)LOCK_READ)) return -1; #endif #ifdef LOCK_WRITE - if (ins(d, "LOCK_WRITE", (long)LOCK_WRITE)) return -1; + if (ins(d, "LOCK_WRITE", (long)LOCK_WRITE)) return -1; #endif #ifdef LOCK_RW - if (ins(d, "LOCK_RW", (long)LOCK_RW)) return -1; + if (ins(d, "LOCK_RW", (long)LOCK_RW)) return -1; #endif #ifdef F_DUPFD - if (ins(d, "F_DUPFD", (long)F_DUPFD)) return -1; + if (ins(d, "F_DUPFD", (long)F_DUPFD)) return -1; #endif #ifdef F_GETFD - if (ins(d, "F_GETFD", (long)F_GETFD)) return -1; + if (ins(d, "F_GETFD", (long)F_GETFD)) return -1; #endif #ifdef F_SETFD - if (ins(d, "F_SETFD", (long)F_SETFD)) return -1; + if (ins(d, "F_SETFD", (long)F_SETFD)) return -1; #endif #ifdef F_GETFL - if (ins(d, "F_GETFL", (long)F_GETFL)) return -1; + if (ins(d, "F_GETFL", (long)F_GETFL)) return -1; #endif #ifdef F_SETFL - if (ins(d, "F_SETFL", (long)F_SETFL)) return -1; + if (ins(d, "F_SETFL", (long)F_SETFL)) return -1; #endif #ifdef F_GETLK - if (ins(d, "F_GETLK", (long)F_GETLK)) return -1; + if (ins(d, "F_GETLK", (long)F_GETLK)) return -1; #endif #ifdef F_SETLK - if (ins(d, "F_SETLK", (long)F_SETLK)) return -1; + if (ins(d, "F_SETLK", (long)F_SETLK)) return -1; #endif #ifdef F_SETLKW - if (ins(d, "F_SETLKW", (long)F_SETLKW)) return -1; + if (ins(d, "F_SETLKW", (long)F_SETLKW)) return -1; #endif #ifdef F_GETOWN - if (ins(d, "F_GETOWN", (long)F_GETOWN)) return -1; + if (ins(d, "F_GETOWN", (long)F_GETOWN)) return -1; #endif #ifdef F_SETOWN - if (ins(d, "F_SETOWN", (long)F_SETOWN)) return -1; + if (ins(d, "F_SETOWN", (long)F_SETOWN)) return -1; #endif #ifdef F_GETSIG - if (ins(d, "F_GETSIG", (long)F_GETSIG)) return -1; + if (ins(d, "F_GETSIG", (long)F_GETSIG)) return -1; #endif #ifdef F_SETSIG - if (ins(d, "F_SETSIG", (long)F_SETSIG)) return -1; + if (ins(d, "F_SETSIG", (long)F_SETSIG)) return -1; #endif #ifdef F_RDLCK - if (ins(d, "F_RDLCK", (long)F_RDLCK)) return -1; + if (ins(d, "F_RDLCK", (long)F_RDLCK)) return -1; #endif #ifdef F_WRLCK - if (ins(d, "F_WRLCK", (long)F_WRLCK)) return -1; + if (ins(d, "F_WRLCK", (long)F_WRLCK)) return -1; #endif #ifdef F_UNLCK - if (ins(d, "F_UNLCK", (long)F_UNLCK)) return -1; + if (ins(d, "F_UNLCK", (long)F_UNLCK)) return -1; #endif /* LFS constants */ #ifdef F_GETLK64 - if (ins(d, "F_GETLK64", (long)F_GETLK64)) return -1; + if (ins(d, "F_GETLK64", (long)F_GETLK64)) return -1; #endif #ifdef F_SETLK64 - if (ins(d, "F_SETLK64", (long)F_SETLK64)) return -1; + if (ins(d, "F_SETLK64", (long)F_SETLK64)) return -1; #endif #ifdef F_SETLKW64 - if (ins(d, "F_SETLKW64", (long)F_SETLKW64)) return -1; + if (ins(d, "F_SETLKW64", (long)F_SETLKW64)) return -1; #endif /* GNU extensions, as of glibc 2.2.4. */ #ifdef FASYNC - if (ins(d, "FASYNC", (long)FASYNC)) return -1; + if (ins(d, "FASYNC", (long)FASYNC)) return -1; #endif #ifdef F_SETLEASE - if (ins(d, "F_SETLEASE", (long)F_SETLEASE)) return -1; + if (ins(d, "F_SETLEASE", (long)F_SETLEASE)) return -1; #endif #ifdef F_GETLEASE - if (ins(d, "F_GETLEASE", (long)F_GETLEASE)) return -1; + if (ins(d, "F_GETLEASE", (long)F_GETLEASE)) return -1; #endif #ifdef F_NOTIFY - if (ins(d, "F_NOTIFY", (long)F_NOTIFY)) return -1; + if (ins(d, "F_NOTIFY", (long)F_NOTIFY)) return -1; #endif /* Old BSD flock(). */ #ifdef F_EXLCK - if (ins(d, "F_EXLCK", (long)F_EXLCK)) return -1; + if (ins(d, "F_EXLCK", (long)F_EXLCK)) return -1; #endif #ifdef F_SHLCK - if (ins(d, "F_SHLCK", (long)F_SHLCK)) return -1; + if (ins(d, "F_SHLCK", (long)F_SHLCK)) return -1; #endif /* OS X (and maybe others) let you tell the storage device to flush to physical media */ #ifdef F_FULLFSYNC - if (ins(d, "F_FULLFSYNC", (long)F_FULLFSYNC)) return -1; + if (ins(d, "F_FULLFSYNC", (long)F_FULLFSYNC)) return -1; #endif /* For F_{GET|SET}FL */ #ifdef FD_CLOEXEC - if (ins(d, "FD_CLOEXEC", (long)FD_CLOEXEC)) return -1; + if (ins(d, "FD_CLOEXEC", (long)FD_CLOEXEC)) return -1; #endif /* For F_NOTIFY */ #ifdef DN_ACCESS - if (ins(d, "DN_ACCESS", (long)DN_ACCESS)) return -1; + if (ins(d, "DN_ACCESS", (long)DN_ACCESS)) return -1; #endif #ifdef DN_MODIFY - if (ins(d, "DN_MODIFY", (long)DN_MODIFY)) return -1; + if (ins(d, "DN_MODIFY", (long)DN_MODIFY)) return -1; #endif #ifdef DN_CREATE - if (ins(d, "DN_CREATE", (long)DN_CREATE)) return -1; + if (ins(d, "DN_CREATE", (long)DN_CREATE)) return -1; #endif #ifdef DN_DELETE - if (ins(d, "DN_DELETE", (long)DN_DELETE)) return -1; + if (ins(d, "DN_DELETE", (long)DN_DELETE)) return -1; #endif #ifdef DN_RENAME - if (ins(d, "DN_RENAME", (long)DN_RENAME)) return -1; + if (ins(d, "DN_RENAME", (long)DN_RENAME)) return -1; #endif #ifdef DN_ATTRIB - if (ins(d, "DN_ATTRIB", (long)DN_ATTRIB)) return -1; + if (ins(d, "DN_ATTRIB", (long)DN_ATTRIB)) return -1; #endif #ifdef DN_MULTISHOT - if (ins(d, "DN_MULTISHOT", (long)DN_MULTISHOT)) return -1; + if (ins(d, "DN_MULTISHOT", (long)DN_MULTISHOT)) return -1; #endif #ifdef HAVE_STROPTS_H - /* Unix 98 guarantees that these are in stropts.h. */ - INS(I_PUSH); - INS(I_POP); - INS(I_LOOK); - INS(I_FLUSH); - INS(I_FLUSHBAND); - INS(I_SETSIG); - INS(I_GETSIG); - INS(I_FIND); - INS(I_PEEK); - INS(I_SRDOPT); - INS(I_GRDOPT); - INS(I_NREAD); - INS(I_FDINSERT); - INS(I_STR); - INS(I_SWROPT); + /* Unix 98 guarantees that these are in stropts.h. */ + INS(I_PUSH); + INS(I_POP); + INS(I_LOOK); + INS(I_FLUSH); + INS(I_FLUSHBAND); + INS(I_SETSIG); + INS(I_GETSIG); + INS(I_FIND); + INS(I_PEEK); + INS(I_SRDOPT); + INS(I_GRDOPT); + INS(I_NREAD); + INS(I_FDINSERT); + INS(I_STR); + INS(I_SWROPT); #ifdef I_GWROPT - /* despite the comment above, old-ish glibcs miss a couple... */ - INS(I_GWROPT); + /* despite the comment above, old-ish glibcs miss a couple... */ + INS(I_GWROPT); #endif - INS(I_SENDFD); - INS(I_RECVFD); - INS(I_LIST); - INS(I_ATMARK); - INS(I_CKBAND); - INS(I_GETBAND); - INS(I_CANPUT); - INS(I_SETCLTIME); + INS(I_SENDFD); + INS(I_RECVFD); + INS(I_LIST); + INS(I_ATMARK); + INS(I_CKBAND); + INS(I_GETBAND); + INS(I_CANPUT); + INS(I_SETCLTIME); #ifdef I_GETCLTIME - INS(I_GETCLTIME); + INS(I_GETCLTIME); #endif - INS(I_LINK); - INS(I_UNLINK); - INS(I_PLINK); - INS(I_PUNLINK); + INS(I_LINK); + INS(I_UNLINK); + INS(I_PLINK); + INS(I_PUNLINK); #endif - - return 0; + + return 0; } static struct PyModuleDef fcntlmodule = { - PyModuleDef_HEAD_INIT, - "fcntl", - module_doc, - -1, - fcntl_methods, - NULL, - NULL, - NULL, - NULL + PyModuleDef_HEAD_INIT, + "fcntl", + module_doc, + -1, + fcntl_methods, + NULL, + NULL, + NULL, + NULL }; PyMODINIT_FUNC PyInit_fcntl(void) { - PyObject *m, *d; + PyObject *m, *d; - /* Create the module and add the functions and documentation */ - m = PyModule_Create(&fcntlmodule); - if (m == NULL) - return NULL; - - /* Add some symbolic constants to the module */ - d = PyModule_GetDict(m); - all_ins(d); - return m; + /* Create the module and add the functions and documentation */ + m = PyModule_Create(&fcntlmodule); + if (m == NULL) + return NULL; + + /* Add some symbolic constants to the module */ + d = PyModule_GetDict(m); + all_ins(d); + return m; } Modified: python/branches/release31-maint/Modules/fpectlmodule.c ============================================================================== --- python/branches/release31-maint/Modules/fpectlmodule.c (original) +++ python/branches/release31-maint/Modules/fpectlmodule.c Sun May 9 18:14:21 2010 @@ -1,6 +1,6 @@ /* - --------------------------------------------------------------------- - / Copyright (c) 1996. \ + --------------------------------------------------------------------- + / Copyright (c) 1996. \ | The Regents of the University of California. | | All rights reserved. | | | @@ -32,12 +32,12 @@ | 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. / - --------------------------------------------------------------------- + \ endorsement purposes. / + --------------------------------------------------------------------- */ /* - Floating point exception control module. + Floating point exception control module. This Python module provides bare-bones control over floating point units from several hardware manufacturers. Specifically, it allows @@ -96,8 +96,8 @@ static PyObject *turnoff_sigfpe (PyObject *self,PyObject *args); static PyMethodDef fpectl_methods[] = { - {"turnon_sigfpe", (PyCFunction) turnon_sigfpe, METH_VARARGS}, - {"turnoff_sigfpe", (PyCFunction) turnoff_sigfpe, METH_VARARGS}, + {"turnon_sigfpe", (PyCFunction) turnon_sigfpe, METH_VARARGS}, + {"turnoff_sigfpe", (PyCFunction) turnoff_sigfpe, METH_VARARGS}, {0,0} }; @@ -122,19 +122,19 @@ * My usage doesn't follow the man page exactly. Maybe somebody * else can explain handle_sigfpes to me.... * cc -c -I/usr/local/python/include fpectlmodule.c - * ld -shared -o fpectlmodule.so fpectlmodule.o -lfpe + * ld -shared -o fpectlmodule.so fpectlmodule.o -lfpe */ #include typedef void user_routine (unsigned[5], int[2]); typedef void abort_routine (unsigned long); handle_sigfpes(_OFF, 0, - (user_routine *)0, - _TURN_OFF_HANDLER_ON_ERROR, - NULL); + (user_routine *)0, + _TURN_OFF_HANDLER_ON_ERROR, + NULL); handle_sigfpes(_ON, _EN_OVERFL | _EN_DIVZERO | _EN_INVALID, - (user_routine *)0, - _ABORT_ON_ERROR, - NULL); + (user_routine *)0, + _ABORT_ON_ERROR, + NULL); PyOS_setsig(SIGFPE, handler); /*-- SunOS and Solaris ----------------------------------------------------*/ @@ -195,16 +195,16 @@ /*-- DEC ALPHA VMS --------------------------------------------------------*/ #elif defined(__ALPHA) && defined(__VMS) - IEEE clrmsk; - IEEE setmsk; - clrmsk.ieee$q_flags = - IEEE$M_TRAP_ENABLE_UNF | IEEE$M_TRAP_ENABLE_INE | - IEEE$M_MAP_UMZ; - setmsk.ieee$q_flags = - IEEE$M_TRAP_ENABLE_INV | IEEE$M_TRAP_ENABLE_DZE | - IEEE$M_TRAP_ENABLE_OVF; - sys$ieee_set_fp_control(&clrmsk, &setmsk, 0); - PyOS_setsig(SIGFPE, handler); + IEEE clrmsk; + IEEE setmsk; + clrmsk.ieee$q_flags = + IEEE$M_TRAP_ENABLE_UNF | IEEE$M_TRAP_ENABLE_INE | + IEEE$M_MAP_UMZ; + setmsk.ieee$q_flags = + IEEE$M_TRAP_ENABLE_INV | IEEE$M_TRAP_ENABLE_DZE | + IEEE$M_TRAP_ENABLE_OVF; + sys$ieee_set_fp_control(&clrmsk, &setmsk, 0); + PyOS_setsig(SIGFPE, handler); /*-- HP IA64 VMS --------------------------------------------------------*/ #elif defined(__ia64) && defined(__VMS) @@ -263,13 +263,13 @@ fpresetsticky(fpgetsticky()); fpsetmask(0); #elif defined(__VMS) - IEEE clrmsk; - clrmsk.ieee$q_flags = - IEEE$M_TRAP_ENABLE_UNF | IEEE$M_TRAP_ENABLE_INE | - IEEE$M_MAP_UMZ | IEEE$M_TRAP_ENABLE_INV | - IEEE$M_TRAP_ENABLE_DZE | IEEE$M_TRAP_ENABLE_OVF | - IEEE$M_INHERIT; - sys$ieee_set_fp_control(&clrmsk, 0, 0); + IEEE clrmsk; + clrmsk.ieee$q_flags = + IEEE$M_TRAP_ENABLE_UNF | IEEE$M_TRAP_ENABLE_INE | + IEEE$M_MAP_UMZ | IEEE$M_TRAP_ENABLE_INV | + IEEE$M_TRAP_ENABLE_DZE | IEEE$M_TRAP_ENABLE_OVF | + IEEE$M_INHERIT; + sys$ieee_set_fp_control(&clrmsk, 0, 0); #else fputs("Operation not implemented\n", stderr); #endif @@ -288,15 +288,15 @@ } static struct PyModuleDef fpectlmodule = { - PyModuleDef_HEAD_INIT, - "fpectl", - NULL, - -1, - fpectl_methods, - NULL, - NULL, - NULL, - NULL + PyModuleDef_HEAD_INIT, + "fpectl", + NULL, + -1, + fpectl_methods, + NULL, + NULL, + NULL, + NULL }; PyMODINIT_FUNC PyInit_fpectl(void) @@ -304,11 +304,11 @@ PyObject *m, *d; m = PyModule_Create(&fpectlmodule); if (m == NULL) - return NULL; + return NULL; d = PyModule_GetDict(m); fpe_error = PyErr_NewException("fpectl.error", NULL, NULL); if (fpe_error != NULL) - PyDict_SetItemString(d, "error", fpe_error); + PyDict_SetItemString(d, "error", fpe_error); return m; } Modified: python/branches/release31-maint/Modules/fpetestmodule.c ============================================================================== --- python/branches/release31-maint/Modules/fpetestmodule.c (original) +++ python/branches/release31-maint/Modules/fpetestmodule.c Sun May 9 18:14:21 2010 @@ -1,6 +1,6 @@ /* - --------------------------------------------------------------------- - / Copyright (c) 1996. \ + --------------------------------------------------------------------- + / Copyright (c) 1996. \ | The Regents of the University of California. | | All rights reserved. | | | @@ -32,12 +32,12 @@ | 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. / - --------------------------------------------------------------------- + \ endorsement purposes. / + --------------------------------------------------------------------- */ /* - Floating point exception test module. + Floating point exception test module. */ @@ -55,7 +55,7 @@ static void printerr(double); static PyMethodDef fpetest_methods[] = { - {"test", (PyCFunction) test, METH_VARARGS}, + {"test", (PyCFunction) test, METH_VARARGS}, {0,0} }; @@ -174,15 +174,15 @@ } static struct PyModuleDef fpetestmodule = { - PyModuleDef_HEAD_INIT, - "fpetest", - NULL, - -1, - fpetest_methods, - NULL, - NULL, - NULL, - NULL + PyModuleDef_HEAD_INIT, + "fpetest", + NULL, + -1, + fpetest_methods, + NULL, + NULL, + NULL, + NULL }; PyMODINIT_FUNC PyInit_fpetest(void) @@ -191,10 +191,10 @@ m = PyModule_Create(&fpetestmodule); if (m == NULL) - return NULL; + return NULL; d = PyModule_GetDict(m); fpe_error = PyErr_NewException("fpetest.error", NULL, NULL); if (fpe_error != NULL) - PyDict_SetItemString(d, "error", fpe_error); + PyDict_SetItemString(d, "error", fpe_error); return m; } Modified: python/branches/release31-maint/Modules/gcmodule.c ============================================================================== --- python/branches/release31-maint/Modules/gcmodule.c (original) +++ python/branches/release31-maint/Modules/gcmodule.c Sun May 9 18:14:21 2010 @@ -24,7 +24,7 @@ */ #include "Python.h" -#include "frameobject.h" /* for PyFrame_ClearFreeList */ +#include "frameobject.h" /* for PyFrame_ClearFreeList */ /* Get an object's GC head */ #define AS_GC(o) ((PyGC_Head *)(o)-1) @@ -35,10 +35,10 @@ /*** Global GC state ***/ struct gc_generation { - PyGC_Head head; - int threshold; /* collection threshold */ - int count; /* count of allocations or collections of younger - generations */ + PyGC_Head head; + int threshold; /* collection threshold */ + int count; /* count of allocations or collections of younger + generations */ }; #define NUM_GENERATIONS 3 @@ -46,10 +46,10 @@ /* linked lists of container objects */ static struct gc_generation generations[NUM_GENERATIONS] = { - /* PyGC_Head, threshold, count */ - {{{GEN_HEAD(0), GEN_HEAD(0), 0}}, 700, 0}, - {{{GEN_HEAD(1), GEN_HEAD(1), 0}}, 10, 0}, - {{{GEN_HEAD(2), GEN_HEAD(2), 0}}, 10, 0}, + /* PyGC_Head, threshold, count */ + {{{GEN_HEAD(0), GEN_HEAD(0), 0}}, 700, 0}, + {{{GEN_HEAD(1), GEN_HEAD(1), 0}}, 10, 0}, + {{{GEN_HEAD(2), GEN_HEAD(2), 0}}, 10, 0}, }; PyGC_Head *_PyGC_generation0 = GEN_HEAD(0); @@ -91,7 +91,7 @@ In addition to the various configurable thresholds, we only trigger a full collection if the ratio - long_lived_pending / long_lived_total + long_lived_pending / long_lived_total is above a given value (hardwired to 25%). The reason is that, while "non-full" collections (i.e., collections of @@ -113,18 +113,18 @@ This heuristic was suggested by Martin von L?wis on python-dev in June 2008. His original analysis and proposal can be found at: - http://mail.python.org/pipermail/python-dev/2008-June/080579.html + http://mail.python.org/pipermail/python-dev/2008-June/080579.html */ /* set for debugging information */ -#define DEBUG_STATS (1<<0) /* print collection statistics */ -#define DEBUG_COLLECTABLE (1<<1) /* print collectable objects */ -#define DEBUG_UNCOLLECTABLE (1<<2) /* print uncollectable objects */ -#define DEBUG_SAVEALL (1<<5) /* save all garbage in gc.garbage */ -#define DEBUG_LEAK DEBUG_COLLECTABLE | \ - DEBUG_UNCOLLECTABLE | \ - DEBUG_SAVEALL +#define DEBUG_STATS (1<<0) /* print collection statistics */ +#define DEBUG_COLLECTABLE (1<<1) /* print collectable objects */ +#define DEBUG_UNCOLLECTABLE (1<<2) /* print uncollectable objects */ +#define DEBUG_SAVEALL (1<<5) /* save all garbage in gc.garbage */ +#define DEBUG_LEAK DEBUG_COLLECTABLE | \ + DEBUG_UNCOLLECTABLE | \ + DEBUG_SAVEALL static int debug; static PyObject *tmod = NULL; @@ -167,28 +167,28 @@ it has a __del__ method), its gc_refs is restored to GC_REACHABLE again. ---------------------------------------------------------------------------- */ -#define GC_UNTRACKED _PyGC_REFS_UNTRACKED -#define GC_REACHABLE _PyGC_REFS_REACHABLE -#define GC_TENTATIVELY_UNREACHABLE _PyGC_REFS_TENTATIVELY_UNREACHABLE +#define GC_UNTRACKED _PyGC_REFS_UNTRACKED +#define GC_REACHABLE _PyGC_REFS_REACHABLE +#define GC_TENTATIVELY_UNREACHABLE _PyGC_REFS_TENTATIVELY_UNREACHABLE #define IS_TRACKED(o) ((AS_GC(o))->gc.gc_refs != GC_UNTRACKED) #define IS_REACHABLE(o) ((AS_GC(o))->gc.gc_refs == GC_REACHABLE) #define IS_TENTATIVELY_UNREACHABLE(o) ( \ - (AS_GC(o))->gc.gc_refs == GC_TENTATIVELY_UNREACHABLE) + (AS_GC(o))->gc.gc_refs == GC_TENTATIVELY_UNREACHABLE) /*** list functions ***/ static void gc_list_init(PyGC_Head *list) { - list->gc.gc_prev = list; - list->gc.gc_next = list; + list->gc.gc_prev = list; + list->gc.gc_next = list; } static int gc_list_is_empty(PyGC_Head *list) { - return (list->gc.gc_next == list); + return (list->gc.gc_next == list); } #if 0 @@ -197,10 +197,10 @@ static void gc_list_append(PyGC_Head *node, PyGC_Head *list) { - node->gc.gc_next = list; - node->gc.gc_prev = list->gc.gc_prev; - node->gc.gc_prev->gc.gc_next = node; - list->gc.gc_prev = node; + node->gc.gc_next = list; + node->gc.gc_prev = list->gc.gc_prev; + node->gc.gc_prev->gc.gc_next = node; + list->gc.gc_prev = node; } #endif @@ -208,9 +208,9 @@ static void gc_list_remove(PyGC_Head *node) { - node->gc.gc_prev->gc.gc_next = node->gc.gc_next; - node->gc.gc_next->gc.gc_prev = node->gc.gc_prev; - node->gc.gc_next = NULL; /* object is not currently tracked */ + node->gc.gc_prev->gc.gc_next = node->gc.gc_next; + node->gc.gc_next->gc.gc_prev = node->gc.gc_prev; + node->gc.gc_next = NULL; /* object is not currently tracked */ } /* Move `node` from the gc list it's currently in (which is not explicitly @@ -220,43 +220,43 @@ static void gc_list_move(PyGC_Head *node, PyGC_Head *list) { - PyGC_Head *new_prev; - PyGC_Head *current_prev = node->gc.gc_prev; - PyGC_Head *current_next = node->gc.gc_next; - /* Unlink from current list. */ - current_prev->gc.gc_next = current_next; - current_next->gc.gc_prev = current_prev; - /* Relink at end of new list. */ - new_prev = node->gc.gc_prev = list->gc.gc_prev; - new_prev->gc.gc_next = list->gc.gc_prev = node; - node->gc.gc_next = list; + PyGC_Head *new_prev; + PyGC_Head *current_prev = node->gc.gc_prev; + PyGC_Head *current_next = node->gc.gc_next; + /* Unlink from current list. */ + current_prev->gc.gc_next = current_next; + current_next->gc.gc_prev = current_prev; + /* Relink at end of new list. */ + new_prev = node->gc.gc_prev = list->gc.gc_prev; + new_prev->gc.gc_next = list->gc.gc_prev = node; + node->gc.gc_next = list; } /* append list `from` onto list `to`; `from` becomes an empty list */ static void gc_list_merge(PyGC_Head *from, PyGC_Head *to) { - PyGC_Head *tail; - assert(from != to); - if (!gc_list_is_empty(from)) { - tail = to->gc.gc_prev; - tail->gc.gc_next = from->gc.gc_next; - tail->gc.gc_next->gc.gc_prev = tail; - to->gc.gc_prev = from->gc.gc_prev; - to->gc.gc_prev->gc.gc_next = to; - } - gc_list_init(from); + PyGC_Head *tail; + assert(from != to); + if (!gc_list_is_empty(from)) { + tail = to->gc.gc_prev; + tail->gc.gc_next = from->gc.gc_next; + tail->gc.gc_next->gc.gc_prev = tail; + to->gc.gc_prev = from->gc.gc_prev; + to->gc.gc_prev->gc.gc_next = to; + } + gc_list_init(from); } static Py_ssize_t gc_list_size(PyGC_Head *list) { - PyGC_Head *gc; - Py_ssize_t n = 0; - for (gc = list->gc.gc_next; gc != list; gc = gc->gc.gc_next) { - n++; - } - return n; + PyGC_Head *gc; + Py_ssize_t n = 0; + for (gc = list->gc.gc_next; gc != list; gc = gc->gc.gc_next) { + n++; + } + return n; } /* Append objects in a GC list to a Python list. @@ -265,16 +265,16 @@ static int append_objects(PyObject *py_list, PyGC_Head *gc_list) { - PyGC_Head *gc; - for (gc = gc_list->gc.gc_next; gc != gc_list; gc = gc->gc.gc_next) { - PyObject *op = FROM_GC(gc); - if (op != py_list) { - if (PyList_Append(py_list, op)) { - return -1; /* exception */ - } - } - } - return 0; + PyGC_Head *gc; + for (gc = gc_list->gc.gc_next; gc != gc_list; gc = gc->gc.gc_next) { + PyObject *op = FROM_GC(gc); + if (op != py_list) { + if (PyList_Append(py_list, op)) { + return -1; /* exception */ + } + } + } + return 0; } /*** end of list stuff ***/ @@ -287,48 +287,48 @@ static void update_refs(PyGC_Head *containers) { - PyGC_Head *gc = containers->gc.gc_next; - for (; gc != containers; gc = gc->gc.gc_next) { - assert(gc->gc.gc_refs == GC_REACHABLE); - gc->gc.gc_refs = Py_REFCNT(FROM_GC(gc)); - /* Python's cyclic gc should never see an incoming refcount - * of 0: if something decref'ed to 0, it should have been - * deallocated immediately at that time. - * Possible cause (if the assert triggers): a tp_dealloc - * routine left a gc-aware object tracked during its teardown - * phase, and did something-- or allowed something to happen -- - * that called back into Python. gc can trigger then, and may - * see the still-tracked dying object. Before this assert - * was added, such mistakes went on to allow gc to try to - * delete the object again. In a debug build, that caused - * a mysterious segfault, when _Py_ForgetReference tried - * to remove the object from the doubly-linked list of all - * objects a second time. In a release build, an actual - * double deallocation occurred, which leads to corruption - * of the allocator's internal bookkeeping pointers. That's - * so serious that maybe this should be a release-build - * check instead of an assert? - */ - assert(gc->gc.gc_refs != 0); - } + PyGC_Head *gc = containers->gc.gc_next; + for (; gc != containers; gc = gc->gc.gc_next) { + assert(gc->gc.gc_refs == GC_REACHABLE); + gc->gc.gc_refs = Py_REFCNT(FROM_GC(gc)); + /* Python's cyclic gc should never see an incoming refcount + * of 0: if something decref'ed to 0, it should have been + * deallocated immediately at that time. + * Possible cause (if the assert triggers): a tp_dealloc + * routine left a gc-aware object tracked during its teardown + * phase, and did something-- or allowed something to happen -- + * that called back into Python. gc can trigger then, and may + * see the still-tracked dying object. Before this assert + * was added, such mistakes went on to allow gc to try to + * delete the object again. In a debug build, that caused + * a mysterious segfault, when _Py_ForgetReference tried + * to remove the object from the doubly-linked list of all + * objects a second time. In a release build, an actual + * double deallocation occurred, which leads to corruption + * of the allocator's internal bookkeeping pointers. That's + * so serious that maybe this should be a release-build + * check instead of an assert? + */ + assert(gc->gc.gc_refs != 0); + } } /* A traversal callback for subtract_refs. */ static int visit_decref(PyObject *op, void *data) { - assert(op != NULL); - if (PyObject_IS_GC(op)) { - PyGC_Head *gc = AS_GC(op); - /* We're only interested in gc_refs for objects in the - * generation being collected, which can be recognized - * because only they have positive gc_refs. - */ - assert(gc->gc.gc_refs != 0); /* else refcount was too small */ - if (gc->gc.gc_refs > 0) - gc->gc.gc_refs--; - } - return 0; + assert(op != NULL); + if (PyObject_IS_GC(op)) { + PyGC_Head *gc = AS_GC(op); + /* We're only interested in gc_refs for objects in the + * generation being collected, which can be recognized + * because only they have positive gc_refs. + */ + assert(gc->gc.gc_refs != 0); /* else refcount was too small */ + if (gc->gc.gc_refs > 0) + gc->gc.gc_refs--; + } + return 0; } /* Subtract internal references from gc_refs. After this, gc_refs is >= 0 @@ -339,57 +339,57 @@ static void subtract_refs(PyGC_Head *containers) { - traverseproc traverse; - PyGC_Head *gc = containers->gc.gc_next; - for (; gc != containers; gc=gc->gc.gc_next) { - traverse = Py_TYPE(FROM_GC(gc))->tp_traverse; - (void) traverse(FROM_GC(gc), - (visitproc)visit_decref, - NULL); - } + traverseproc traverse; + PyGC_Head *gc = containers->gc.gc_next; + for (; gc != containers; gc=gc->gc.gc_next) { + traverse = Py_TYPE(FROM_GC(gc))->tp_traverse; + (void) traverse(FROM_GC(gc), + (visitproc)visit_decref, + NULL); + } } /* A traversal callback for move_unreachable. */ static int visit_reachable(PyObject *op, PyGC_Head *reachable) { - if (PyObject_IS_GC(op)) { - PyGC_Head *gc = AS_GC(op); - const Py_ssize_t gc_refs = gc->gc.gc_refs; - - if (gc_refs == 0) { - /* This is in move_unreachable's 'young' list, but - * the traversal hasn't yet gotten to it. All - * we need to do is tell move_unreachable that it's - * reachable. - */ - gc->gc.gc_refs = 1; - } - else if (gc_refs == GC_TENTATIVELY_UNREACHABLE) { - /* This had gc_refs = 0 when move_unreachable got - * to it, but turns out it's reachable after all. - * Move it back to move_unreachable's 'young' list, - * and move_unreachable will eventually get to it - * again. - */ - gc_list_move(gc, reachable); - gc->gc.gc_refs = 1; - } - /* Else there's nothing to do. - * If gc_refs > 0, it must be in move_unreachable's 'young' - * list, and move_unreachable will eventually get to it. - * If gc_refs == GC_REACHABLE, it's either in some other - * generation so we don't care about it, or move_unreachable - * already dealt with it. - * If gc_refs == GC_UNTRACKED, it must be ignored. - */ - else { - assert(gc_refs > 0 - || gc_refs == GC_REACHABLE - || gc_refs == GC_UNTRACKED); - } - } - return 0; + if (PyObject_IS_GC(op)) { + PyGC_Head *gc = AS_GC(op); + const Py_ssize_t gc_refs = gc->gc.gc_refs; + + if (gc_refs == 0) { + /* This is in move_unreachable's 'young' list, but + * the traversal hasn't yet gotten to it. All + * we need to do is tell move_unreachable that it's + * reachable. + */ + gc->gc.gc_refs = 1; + } + else if (gc_refs == GC_TENTATIVELY_UNREACHABLE) { + /* This had gc_refs = 0 when move_unreachable got + * to it, but turns out it's reachable after all. + * Move it back to move_unreachable's 'young' list, + * and move_unreachable will eventually get to it + * again. + */ + gc_list_move(gc, reachable); + gc->gc.gc_refs = 1; + } + /* Else there's nothing to do. + * If gc_refs > 0, it must be in move_unreachable's 'young' + * list, and move_unreachable will eventually get to it. + * If gc_refs == GC_REACHABLE, it's either in some other + * generation so we don't care about it, or move_unreachable + * already dealt with it. + * If gc_refs == GC_UNTRACKED, it must be ignored. + */ + else { + assert(gc_refs > 0 + || gc_refs == GC_REACHABLE + || gc_refs == GC_UNTRACKED); + } + } + return 0; } /* Move the unreachable objects from young to unreachable. After this, @@ -403,68 +403,68 @@ static void move_unreachable(PyGC_Head *young, PyGC_Head *unreachable) { - PyGC_Head *gc = young->gc.gc_next; + PyGC_Head *gc = young->gc.gc_next; - /* Invariants: all objects "to the left" of us in young have gc_refs - * = GC_REACHABLE, and are indeed reachable (directly or indirectly) - * from outside the young list as it was at entry. All other objects - * from the original young "to the left" of us are in unreachable now, - * and have gc_refs = GC_TENTATIVELY_UNREACHABLE. All objects to the - * left of us in 'young' now have been scanned, and no objects here - * or to the right have been scanned yet. - */ - - while (gc != young) { - PyGC_Head *next; - - if (gc->gc.gc_refs) { - /* gc is definitely reachable from outside the - * original 'young'. Mark it as such, and traverse - * its pointers to find any other objects that may - * be directly reachable from it. Note that the - * call to tp_traverse may append objects to young, - * so we have to wait until it returns to determine - * the next object to visit. - */ - PyObject *op = FROM_GC(gc); - traverseproc traverse = Py_TYPE(op)->tp_traverse; - assert(gc->gc.gc_refs > 0); - gc->gc.gc_refs = GC_REACHABLE; - (void) traverse(op, - (visitproc)visit_reachable, - (void *)young); - next = gc->gc.gc_next; - if (PyTuple_CheckExact(op)) { - _PyTuple_MaybeUntrack(op); - } - else if (PyDict_CheckExact(op)) { - _PyDict_MaybeUntrack(op); - } - } - else { - /* This *may* be unreachable. To make progress, - * assume it is. gc isn't directly reachable from - * any object we've already traversed, but may be - * reachable from an object we haven't gotten to yet. - * visit_reachable will eventually move gc back into - * young if that's so, and we'll see it again. - */ - next = gc->gc.gc_next; - gc_list_move(gc, unreachable); - gc->gc.gc_refs = GC_TENTATIVELY_UNREACHABLE; - } - gc = next; - } + /* Invariants: all objects "to the left" of us in young have gc_refs + * = GC_REACHABLE, and are indeed reachable (directly or indirectly) + * from outside the young list as it was at entry. All other objects + * from the original young "to the left" of us are in unreachable now, + * and have gc_refs = GC_TENTATIVELY_UNREACHABLE. All objects to the + * left of us in 'young' now have been scanned, and no objects here + * or to the right have been scanned yet. + */ + + while (gc != young) { + PyGC_Head *next; + + if (gc->gc.gc_refs) { + /* gc is definitely reachable from outside the + * original 'young'. Mark it as such, and traverse + * its pointers to find any other objects that may + * be directly reachable from it. Note that the + * call to tp_traverse may append objects to young, + * so we have to wait until it returns to determine + * the next object to visit. + */ + PyObject *op = FROM_GC(gc); + traverseproc traverse = Py_TYPE(op)->tp_traverse; + assert(gc->gc.gc_refs > 0); + gc->gc.gc_refs = GC_REACHABLE; + (void) traverse(op, + (visitproc)visit_reachable, + (void *)young); + next = gc->gc.gc_next; + if (PyTuple_CheckExact(op)) { + _PyTuple_MaybeUntrack(op); + } + else if (PyDict_CheckExact(op)) { + _PyDict_MaybeUntrack(op); + } + } + else { + /* This *may* be unreachable. To make progress, + * assume it is. gc isn't directly reachable from + * any object we've already traversed, but may be + * reachable from an object we haven't gotten to yet. + * visit_reachable will eventually move gc back into + * young if that's so, and we'll see it again. + */ + next = gc->gc.gc_next; + gc_list_move(gc, unreachable); + gc->gc.gc_refs = GC_TENTATIVELY_UNREACHABLE; + } + gc = next; + } } /* Return true if object has a finalization method. */ static int has_finalizer(PyObject *op) { - if (PyGen_CheckExact(op)) - return PyGen_NeedsFinalizing((PyGenObject *)op); - else - return op->ob_type->tp_del != NULL; + if (PyGen_CheckExact(op)) + return PyGen_NeedsFinalizing((PyGenObject *)op); + else + return op->ob_type->tp_del != NULL; } /* Move the objects in unreachable with __del__ methods into `finalizers`. @@ -474,37 +474,37 @@ static void move_finalizers(PyGC_Head *unreachable, PyGC_Head *finalizers) { - PyGC_Head *gc; - PyGC_Head *next; + PyGC_Head *gc; + PyGC_Head *next; - /* March over unreachable. Move objects with finalizers into - * `finalizers`. - */ - for (gc = unreachable->gc.gc_next; gc != unreachable; gc = next) { - PyObject *op = FROM_GC(gc); - - assert(IS_TENTATIVELY_UNREACHABLE(op)); - next = gc->gc.gc_next; - - if (has_finalizer(op)) { - gc_list_move(gc, finalizers); - gc->gc.gc_refs = GC_REACHABLE; - } - } + /* March over unreachable. Move objects with finalizers into + * `finalizers`. + */ + for (gc = unreachable->gc.gc_next; gc != unreachable; gc = next) { + PyObject *op = FROM_GC(gc); + + assert(IS_TENTATIVELY_UNREACHABLE(op)); + next = gc->gc.gc_next; + + if (has_finalizer(op)) { + gc_list_move(gc, finalizers); + gc->gc.gc_refs = GC_REACHABLE; + } + } } /* A traversal callback for move_finalizer_reachable. */ static int visit_move(PyObject *op, PyGC_Head *tolist) { - if (PyObject_IS_GC(op)) { - if (IS_TENTATIVELY_UNREACHABLE(op)) { - PyGC_Head *gc = AS_GC(op); - gc_list_move(gc, tolist); - gc->gc.gc_refs = GC_REACHABLE; - } - } - return 0; + if (PyObject_IS_GC(op)) { + if (IS_TENTATIVELY_UNREACHABLE(op)) { + PyGC_Head *gc = AS_GC(op); + gc_list_move(gc, tolist); + gc->gc.gc_refs = GC_REACHABLE; + } + } + return 0; } /* Move objects that are reachable from finalizers, from the unreachable set @@ -513,15 +513,15 @@ static void move_finalizer_reachable(PyGC_Head *finalizers) { - traverseproc traverse; - PyGC_Head *gc = finalizers->gc.gc_next; - for (; gc != finalizers; gc = gc->gc.gc_next) { - /* Note that the finalizers list may grow during this. */ - traverse = Py_TYPE(FROM_GC(gc))->tp_traverse; - (void) traverse(FROM_GC(gc), - (visitproc)visit_move, - (void *)finalizers); - } + traverseproc traverse; + PyGC_Head *gc = finalizers->gc.gc_next; + for (; gc != finalizers; gc = gc->gc.gc_next) { + /* Note that the finalizers list may grow during this. */ + traverse = Py_TYPE(FROM_GC(gc))->tp_traverse; + (void) traverse(FROM_GC(gc), + (visitproc)visit_move, + (void *)finalizers); + } } /* Clear all weakrefs to unreachable objects, and if such a weakref has a @@ -538,150 +538,150 @@ static int handle_weakrefs(PyGC_Head *unreachable, PyGC_Head *old) { - PyGC_Head *gc; - PyObject *op; /* generally FROM_GC(gc) */ - PyWeakReference *wr; /* generally a cast of op */ - PyGC_Head wrcb_to_call; /* weakrefs with callbacks to call */ - PyGC_Head *next; - int num_freed = 0; - - gc_list_init(&wrcb_to_call); - - /* Clear all weakrefs to the objects in unreachable. If such a weakref - * also has a callback, move it into `wrcb_to_call` if the callback - * needs to be invoked. Note that we cannot invoke any callbacks until - * all weakrefs to unreachable objects are cleared, lest the callback - * resurrect an unreachable object via a still-active weakref. We - * make another pass over wrcb_to_call, invoking callbacks, after this - * pass completes. - */ - for (gc = unreachable->gc.gc_next; gc != unreachable; gc = next) { - PyWeakReference **wrlist; - - op = FROM_GC(gc); - assert(IS_TENTATIVELY_UNREACHABLE(op)); - next = gc->gc.gc_next; - - if (! PyType_SUPPORTS_WEAKREFS(Py_TYPE(op))) - continue; - - /* It supports weakrefs. Does it have any? */ - wrlist = (PyWeakReference **) - PyObject_GET_WEAKREFS_LISTPTR(op); - - /* `op` may have some weakrefs. March over the list, clear - * all the weakrefs, and move the weakrefs with callbacks - * that must be called into wrcb_to_call. - */ - for (wr = *wrlist; wr != NULL; wr = *wrlist) { - PyGC_Head *wrasgc; /* AS_GC(wr) */ - - /* _PyWeakref_ClearRef clears the weakref but leaves - * the callback pointer intact. Obscure: it also - * changes *wrlist. - */ - assert(wr->wr_object == op); - _PyWeakref_ClearRef(wr); - assert(wr->wr_object == Py_None); - if (wr->wr_callback == NULL) - continue; /* no callback */ - - /* Headache time. `op` is going away, and is weakly referenced by - * `wr`, which has a callback. Should the callback be invoked? If wr - * is also trash, no: - * - * 1. There's no need to call it. The object and the weakref are - * both going away, so it's legitimate to pretend the weakref is - * going away first. The user has to ensure a weakref outlives its - * referent if they want a guarantee that the wr callback will get - * invoked. - * - * 2. It may be catastrophic to call it. If the callback is also in - * cyclic trash (CT), then although the CT is unreachable from - * outside the current generation, CT may be reachable from the - * callback. Then the callback could resurrect insane objects. - * - * Since the callback is never needed and may be unsafe in this case, - * wr is simply left in the unreachable set. Note that because we - * already called _PyWeakref_ClearRef(wr), its callback will never - * trigger. - * - * OTOH, if wr isn't part of CT, we should invoke the callback: the - * weakref outlived the trash. Note that since wr isn't CT in this - * case, its callback can't be CT either -- wr acted as an external - * root to this generation, and therefore its callback did too. So - * nothing in CT is reachable from the callback either, so it's hard - * to imagine how calling it later could create a problem for us. wr - * is moved to wrcb_to_call in this case. - */ - if (IS_TENTATIVELY_UNREACHABLE(wr)) - continue; - assert(IS_REACHABLE(wr)); - - /* Create a new reference so that wr can't go away - * before we can process it again. - */ - Py_INCREF(wr); - - /* Move wr to wrcb_to_call, for the next pass. */ - wrasgc = AS_GC(wr); - assert(wrasgc != next); /* wrasgc is reachable, but - next isn't, so they can't - be the same */ - gc_list_move(wrasgc, &wrcb_to_call); - } - } - - /* Invoke the callbacks we decided to honor. It's safe to invoke them - * because they can't reference unreachable objects. - */ - while (! gc_list_is_empty(&wrcb_to_call)) { - PyObject *temp; - PyObject *callback; - - gc = wrcb_to_call.gc.gc_next; - op = FROM_GC(gc); - assert(IS_REACHABLE(op)); - assert(PyWeakref_Check(op)); - wr = (PyWeakReference *)op; - callback = wr->wr_callback; - assert(callback != NULL); - - /* copy-paste of weakrefobject.c's handle_callback() */ - temp = PyObject_CallFunctionObjArgs(callback, wr, NULL); - if (temp == NULL) - PyErr_WriteUnraisable(callback); - else - Py_DECREF(temp); - - /* Give up the reference we created in the first pass. When - * op's refcount hits 0 (which it may or may not do right now), - * op's tp_dealloc will decref op->wr_callback too. Note - * that the refcount probably will hit 0 now, and because this - * weakref was reachable to begin with, gc didn't already - * add it to its count of freed objects. Example: a reachable - * weak value dict maps some key to this reachable weakref. - * The callback removes this key->weakref mapping from the - * dict, leaving no other references to the weakref (excepting - * ours). - */ - Py_DECREF(op); - if (wrcb_to_call.gc.gc_next == gc) { - /* object is still alive -- move it */ - gc_list_move(gc, old); - } - else - ++num_freed; - } + PyGC_Head *gc; + PyObject *op; /* generally FROM_GC(gc) */ + PyWeakReference *wr; /* generally a cast of op */ + PyGC_Head wrcb_to_call; /* weakrefs with callbacks to call */ + PyGC_Head *next; + int num_freed = 0; + + gc_list_init(&wrcb_to_call); + + /* Clear all weakrefs to the objects in unreachable. If such a weakref + * also has a callback, move it into `wrcb_to_call` if the callback + * needs to be invoked. Note that we cannot invoke any callbacks until + * all weakrefs to unreachable objects are cleared, lest the callback + * resurrect an unreachable object via a still-active weakref. We + * make another pass over wrcb_to_call, invoking callbacks, after this + * pass completes. + */ + for (gc = unreachable->gc.gc_next; gc != unreachable; gc = next) { + PyWeakReference **wrlist; + + op = FROM_GC(gc); + assert(IS_TENTATIVELY_UNREACHABLE(op)); + next = gc->gc.gc_next; + + if (! PyType_SUPPORTS_WEAKREFS(Py_TYPE(op))) + continue; + + /* It supports weakrefs. Does it have any? */ + wrlist = (PyWeakReference **) + PyObject_GET_WEAKREFS_LISTPTR(op); + + /* `op` may have some weakrefs. March over the list, clear + * all the weakrefs, and move the weakrefs with callbacks + * that must be called into wrcb_to_call. + */ + for (wr = *wrlist; wr != NULL; wr = *wrlist) { + PyGC_Head *wrasgc; /* AS_GC(wr) */ + + /* _PyWeakref_ClearRef clears the weakref but leaves + * the callback pointer intact. Obscure: it also + * changes *wrlist. + */ + assert(wr->wr_object == op); + _PyWeakref_ClearRef(wr); + assert(wr->wr_object == Py_None); + if (wr->wr_callback == NULL) + continue; /* no callback */ + + /* Headache time. `op` is going away, and is weakly referenced by + * `wr`, which has a callback. Should the callback be invoked? If wr + * is also trash, no: + * + * 1. There's no need to call it. The object and the weakref are + * both going away, so it's legitimate to pretend the weakref is + * going away first. The user has to ensure a weakref outlives its + * referent if they want a guarantee that the wr callback will get + * invoked. + * + * 2. It may be catastrophic to call it. If the callback is also in + * cyclic trash (CT), then although the CT is unreachable from + * outside the current generation, CT may be reachable from the + * callback. Then the callback could resurrect insane objects. + * + * Since the callback is never needed and may be unsafe in this case, + * wr is simply left in the unreachable set. Note that because we + * already called _PyWeakref_ClearRef(wr), its callback will never + * trigger. + * + * OTOH, if wr isn't part of CT, we should invoke the callback: the + * weakref outlived the trash. Note that since wr isn't CT in this + * case, its callback can't be CT either -- wr acted as an external + * root to this generation, and therefore its callback did too. So + * nothing in CT is reachable from the callback either, so it's hard + * to imagine how calling it later could create a problem for us. wr + * is moved to wrcb_to_call in this case. + */ + if (IS_TENTATIVELY_UNREACHABLE(wr)) + continue; + assert(IS_REACHABLE(wr)); + + /* Create a new reference so that wr can't go away + * before we can process it again. + */ + Py_INCREF(wr); + + /* Move wr to wrcb_to_call, for the next pass. */ + wrasgc = AS_GC(wr); + assert(wrasgc != next); /* wrasgc is reachable, but + next isn't, so they can't + be the same */ + gc_list_move(wrasgc, &wrcb_to_call); + } + } + + /* Invoke the callbacks we decided to honor. It's safe to invoke them + * because they can't reference unreachable objects. + */ + while (! gc_list_is_empty(&wrcb_to_call)) { + PyObject *temp; + PyObject *callback; + + gc = wrcb_to_call.gc.gc_next; + op = FROM_GC(gc); + assert(IS_REACHABLE(op)); + assert(PyWeakref_Check(op)); + wr = (PyWeakReference *)op; + callback = wr->wr_callback; + assert(callback != NULL); + + /* copy-paste of weakrefobject.c's handle_callback() */ + temp = PyObject_CallFunctionObjArgs(callback, wr, NULL); + if (temp == NULL) + PyErr_WriteUnraisable(callback); + else + Py_DECREF(temp); + + /* Give up the reference we created in the first pass. When + * op's refcount hits 0 (which it may or may not do right now), + * op's tp_dealloc will decref op->wr_callback too. Note + * that the refcount probably will hit 0 now, and because this + * weakref was reachable to begin with, gc didn't already + * add it to its count of freed objects. Example: a reachable + * weak value dict maps some key to this reachable weakref. + * The callback removes this key->weakref mapping from the + * dict, leaving no other references to the weakref (excepting + * ours). + */ + Py_DECREF(op); + if (wrcb_to_call.gc.gc_next == gc) { + /* object is still alive -- move it */ + gc_list_move(gc, old); + } + else + ++num_freed; + } - return num_freed; + return num_freed; } static void debug_cycle(char *msg, PyObject *op) { - PySys_WriteStderr("gc: %.100s <%.100s %p>\n", - msg, Py_TYPE(op)->tp_name, op); + PySys_WriteStderr("gc: %.100s <%.100s %p>\n", + msg, Py_TYPE(op)->tp_name, op); } /* Handle uncollectable garbage (cycles with finalizers, and stuff reachable @@ -696,56 +696,56 @@ static int handle_finalizers(PyGC_Head *finalizers, PyGC_Head *old) { - PyGC_Head *gc = finalizers->gc.gc_next; + PyGC_Head *gc = finalizers->gc.gc_next; - if (garbage == NULL) { - garbage = PyList_New(0); - if (garbage == NULL) - Py_FatalError("gc couldn't create gc.garbage list"); - } - for (; gc != finalizers; gc = gc->gc.gc_next) { - PyObject *op = FROM_GC(gc); - - if ((debug & DEBUG_SAVEALL) || has_finalizer(op)) { - if (PyList_Append(garbage, op) < 0) - return -1; - } - } + if (garbage == NULL) { + garbage = PyList_New(0); + if (garbage == NULL) + Py_FatalError("gc couldn't create gc.garbage list"); + } + for (; gc != finalizers; gc = gc->gc.gc_next) { + PyObject *op = FROM_GC(gc); + + if ((debug & DEBUG_SAVEALL) || has_finalizer(op)) { + if (PyList_Append(garbage, op) < 0) + return -1; + } + } - gc_list_merge(finalizers, old); - return 0; + gc_list_merge(finalizers, old); + return 0; } -/* Break reference cycles by clearing the containers involved. This is +/* Break reference cycles by clearing the containers involved. This is * tricky business as the lists can be changing and we don't know which * objects may be freed. It is possible I screwed something up here. */ static void delete_garbage(PyGC_Head *collectable, PyGC_Head *old) { - inquiry clear; + inquiry clear; - while (!gc_list_is_empty(collectable)) { - PyGC_Head *gc = collectable->gc.gc_next; - PyObject *op = FROM_GC(gc); - - assert(IS_TENTATIVELY_UNREACHABLE(op)); - if (debug & DEBUG_SAVEALL) { - PyList_Append(garbage, op); - } - else { - if ((clear = Py_TYPE(op)->tp_clear) != NULL) { - Py_INCREF(op); - clear(op); - Py_DECREF(op); - } - } - if (collectable->gc.gc_next == gc) { - /* object is still alive, move it, it may die later */ - gc_list_move(gc, old); - gc->gc.gc_refs = GC_REACHABLE; - } - } + while (!gc_list_is_empty(collectable)) { + PyGC_Head *gc = collectable->gc.gc_next; + PyObject *op = FROM_GC(gc); + + assert(IS_TENTATIVELY_UNREACHABLE(op)); + if (debug & DEBUG_SAVEALL) { + PyList_Append(garbage, op); + } + else { + if ((clear = Py_TYPE(op)->tp_clear) != NULL) { + Py_INCREF(op); + clear(op); + Py_DECREF(op); + } + } + if (collectable->gc.gc_next == gc) { + /* object is still alive, move it, it may die later */ + gc_list_move(gc, old); + gc->gc.gc_refs = GC_REACHABLE; + } + } } /* Clear all free lists @@ -756,30 +756,30 @@ static void clear_freelists(void) { - (void)PyMethod_ClearFreeList(); - (void)PyFrame_ClearFreeList(); - (void)PyCFunction_ClearFreeList(); - (void)PyTuple_ClearFreeList(); - (void)PyUnicode_ClearFreeList(); - (void)PyFloat_ClearFreeList(); + (void)PyMethod_ClearFreeList(); + (void)PyFrame_ClearFreeList(); + (void)PyCFunction_ClearFreeList(); + (void)PyTuple_ClearFreeList(); + (void)PyUnicode_ClearFreeList(); + (void)PyFloat_ClearFreeList(); } static double get_time(void) { - double result = 0; - if (tmod != NULL) { - PyObject *f = PyObject_CallMethod(tmod, "time", NULL); - if (f == NULL) { - PyErr_Clear(); - } - else { - if (PyFloat_Check(f)) - result = PyFloat_AsDouble(f); - Py_DECREF(f); - } - } - return result; + double result = 0; + if (tmod != NULL) { + PyObject *f = PyObject_CallMethod(tmod, "time", NULL); + if (f == NULL) { + PyErr_Clear(); + } + else { + if (PyFloat_Check(f)) + result = PyFloat_AsDouble(f); + Py_DECREF(f); + } + } + return result; } /* This is the main function. Read this to understand how the @@ -787,184 +787,184 @@ static Py_ssize_t collect(int generation) { - int i; - Py_ssize_t m = 0; /* # objects collected */ - Py_ssize_t n = 0; /* # unreachable objects that couldn't be collected */ - PyGC_Head *young; /* the generation we are examining */ - PyGC_Head *old; /* next older generation */ - PyGC_Head unreachable; /* non-problematic unreachable trash */ - PyGC_Head finalizers; /* objects with, & reachable from, __del__ */ - PyGC_Head *gc; - double t1 = 0.0; - - if (delstr == NULL) { - delstr = PyUnicode_InternFromString("__del__"); - if (delstr == NULL) - Py_FatalError("gc couldn't allocate \"__del__\""); - } - - if (debug & DEBUG_STATS) { - PySys_WriteStderr("gc: collecting generation %d...\n", - generation); - PySys_WriteStderr("gc: objects in each generation:"); - for (i = 0; i < NUM_GENERATIONS; i++) - PySys_WriteStderr(" %" PY_FORMAT_SIZE_T "d", - gc_list_size(GEN_HEAD(i))); - t1 = get_time(); - PySys_WriteStderr("\n"); - } - - /* update collection and allocation counters */ - if (generation+1 < NUM_GENERATIONS) - generations[generation+1].count += 1; - for (i = 0; i <= generation; i++) - generations[i].count = 0; - - /* merge younger generations with one we are currently collecting */ - for (i = 0; i < generation; i++) { - gc_list_merge(GEN_HEAD(i), GEN_HEAD(generation)); - } - - /* handy references */ - young = GEN_HEAD(generation); - if (generation < NUM_GENERATIONS-1) - old = GEN_HEAD(generation+1); - else - old = young; - - /* Using ob_refcnt and gc_refs, calculate which objects in the - * container set are reachable from outside the set (i.e., have a - * refcount greater than 0 when all the references within the - * set are taken into account). - */ - update_refs(young); - subtract_refs(young); - - /* Leave everything reachable from outside young in young, and move - * everything else (in young) to unreachable. - * NOTE: This used to move the reachable objects into a reachable - * set instead. But most things usually turn out to be reachable, - * so it's more efficient to move the unreachable things. - */ - gc_list_init(&unreachable); - move_unreachable(young, &unreachable); - - /* Move reachable objects to next generation. */ - if (young != old) { - if (generation == NUM_GENERATIONS - 2) { - long_lived_pending += gc_list_size(young); - } - gc_list_merge(young, old); - } - else { - long_lived_pending = 0; - long_lived_total = gc_list_size(young); - } - - /* All objects in unreachable are trash, but objects reachable from - * finalizers can't safely be deleted. Python programmers should take - * care not to create such things. For Python, finalizers means - * instance objects with __del__ methods. Weakrefs with callbacks - * can also call arbitrary Python code but they will be dealt with by - * handle_weakrefs(). - */ - gc_list_init(&finalizers); - move_finalizers(&unreachable, &finalizers); - /* finalizers contains the unreachable objects with a finalizer; - * unreachable objects reachable *from* those are also uncollectable, - * and we move those into the finalizers list too. - */ - move_finalizer_reachable(&finalizers); - - /* Collect statistics on collectable objects found and print - * debugging information. - */ - for (gc = unreachable.gc.gc_next; gc != &unreachable; - gc = gc->gc.gc_next) { - m++; - if (debug & DEBUG_COLLECTABLE) { - debug_cycle("collectable", FROM_GC(gc)); - } - } - - /* Clear weakrefs and invoke callbacks as necessary. */ - m += handle_weakrefs(&unreachable, old); - - /* Call tp_clear on objects in the unreachable set. This will cause - * the reference cycles to be broken. It may also cause some objects - * in finalizers to be freed. - */ - delete_garbage(&unreachable, old); - - /* Collect statistics on uncollectable objects found and print - * debugging information. */ - for (gc = finalizers.gc.gc_next; - gc != &finalizers; - gc = gc->gc.gc_next) { - n++; - if (debug & DEBUG_UNCOLLECTABLE) - debug_cycle("uncollectable", FROM_GC(gc)); - } - if (debug & DEBUG_STATS) { - double t2 = get_time(); - if (m == 0 && n == 0) - PySys_WriteStderr("gc: done"); - else - PySys_WriteStderr( - "gc: done, " - "%" PY_FORMAT_SIZE_T "d unreachable, " - "%" PY_FORMAT_SIZE_T "d uncollectable", - n+m, n); - if (t1 && t2) { - PySys_WriteStderr(", %.4fs elapsed", t2-t1); - } - PySys_WriteStderr(".\n"); - } - - /* Append instances in the uncollectable set to a Python - * 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); - - /* Clear free list only during the collection of the highest - * generation */ - if (generation == NUM_GENERATIONS-1) { - clear_freelists(); - } - - if (PyErr_Occurred()) { - if (gc_str == NULL) - gc_str = PyUnicode_FromString("garbage collection"); - PyErr_WriteUnraisable(gc_str); - Py_FatalError("unexpected exception during garbage collection"); - } - return n+m; + int i; + Py_ssize_t m = 0; /* # objects collected */ + Py_ssize_t n = 0; /* # unreachable objects that couldn't be collected */ + PyGC_Head *young; /* the generation we are examining */ + PyGC_Head *old; /* next older generation */ + PyGC_Head unreachable; /* non-problematic unreachable trash */ + PyGC_Head finalizers; /* objects with, & reachable from, __del__ */ + PyGC_Head *gc; + double t1 = 0.0; + + if (delstr == NULL) { + delstr = PyUnicode_InternFromString("__del__"); + if (delstr == NULL) + Py_FatalError("gc couldn't allocate \"__del__\""); + } + + if (debug & DEBUG_STATS) { + PySys_WriteStderr("gc: collecting generation %d...\n", + generation); + PySys_WriteStderr("gc: objects in each generation:"); + for (i = 0; i < NUM_GENERATIONS; i++) + PySys_WriteStderr(" %" PY_FORMAT_SIZE_T "d", + gc_list_size(GEN_HEAD(i))); + t1 = get_time(); + PySys_WriteStderr("\n"); + } + + /* update collection and allocation counters */ + if (generation+1 < NUM_GENERATIONS) + generations[generation+1].count += 1; + for (i = 0; i <= generation; i++) + generations[i].count = 0; + + /* merge younger generations with one we are currently collecting */ + for (i = 0; i < generation; i++) { + gc_list_merge(GEN_HEAD(i), GEN_HEAD(generation)); + } + + /* handy references */ + young = GEN_HEAD(generation); + if (generation < NUM_GENERATIONS-1) + old = GEN_HEAD(generation+1); + else + old = young; + + /* Using ob_refcnt and gc_refs, calculate which objects in the + * container set are reachable from outside the set (i.e., have a + * refcount greater than 0 when all the references within the + * set are taken into account). + */ + update_refs(young); + subtract_refs(young); + + /* Leave everything reachable from outside young in young, and move + * everything else (in young) to unreachable. + * NOTE: This used to move the reachable objects into a reachable + * set instead. But most things usually turn out to be reachable, + * so it's more efficient to move the unreachable things. + */ + gc_list_init(&unreachable); + move_unreachable(young, &unreachable); + + /* Move reachable objects to next generation. */ + if (young != old) { + if (generation == NUM_GENERATIONS - 2) { + long_lived_pending += gc_list_size(young); + } + gc_list_merge(young, old); + } + else { + long_lived_pending = 0; + long_lived_total = gc_list_size(young); + } + + /* All objects in unreachable are trash, but objects reachable from + * finalizers can't safely be deleted. Python programmers should take + * care not to create such things. For Python, finalizers means + * instance objects with __del__ methods. Weakrefs with callbacks + * can also call arbitrary Python code but they will be dealt with by + * handle_weakrefs(). + */ + gc_list_init(&finalizers); + move_finalizers(&unreachable, &finalizers); + /* finalizers contains the unreachable objects with a finalizer; + * unreachable objects reachable *from* those are also uncollectable, + * and we move those into the finalizers list too. + */ + move_finalizer_reachable(&finalizers); + + /* Collect statistics on collectable objects found and print + * debugging information. + */ + for (gc = unreachable.gc.gc_next; gc != &unreachable; + gc = gc->gc.gc_next) { + m++; + if (debug & DEBUG_COLLECTABLE) { + debug_cycle("collectable", FROM_GC(gc)); + } + } + + /* Clear weakrefs and invoke callbacks as necessary. */ + m += handle_weakrefs(&unreachable, old); + + /* Call tp_clear on objects in the unreachable set. This will cause + * the reference cycles to be broken. It may also cause some objects + * in finalizers to be freed. + */ + delete_garbage(&unreachable, old); + + /* Collect statistics on uncollectable objects found and print + * debugging information. */ + for (gc = finalizers.gc.gc_next; + gc != &finalizers; + gc = gc->gc.gc_next) { + n++; + if (debug & DEBUG_UNCOLLECTABLE) + debug_cycle("uncollectable", FROM_GC(gc)); + } + if (debug & DEBUG_STATS) { + double t2 = get_time(); + if (m == 0 && n == 0) + PySys_WriteStderr("gc: done"); + else + PySys_WriteStderr( + "gc: done, " + "%" PY_FORMAT_SIZE_T "d unreachable, " + "%" PY_FORMAT_SIZE_T "d uncollectable", + n+m, n); + if (t1 && t2) { + PySys_WriteStderr(", %.4fs elapsed", t2-t1); + } + PySys_WriteStderr(".\n"); + } + + /* Append instances in the uncollectable set to a Python + * 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); + + /* Clear free list only during the collection of the highest + * generation */ + if (generation == NUM_GENERATIONS-1) { + clear_freelists(); + } + + if (PyErr_Occurred()) { + if (gc_str == NULL) + gc_str = PyUnicode_FromString("garbage collection"); + PyErr_WriteUnraisable(gc_str); + Py_FatalError("unexpected exception during garbage collection"); + } + return n+m; } static Py_ssize_t collect_generations(void) { - int i; - Py_ssize_t n = 0; + int i; + Py_ssize_t n = 0; - /* Find the oldest generation (highest numbered) where the count - * exceeds the threshold. Objects in the that generation and - * generations younger than it will be collected. */ - for (i = NUM_GENERATIONS-1; i >= 0; i--) { - if (generations[i].count > generations[i].threshold) { - /* Avoid quadratic performance degradation in number - of tracked objects. See comments at the beginning - of this file, and issue #4074. - */ - if (i == NUM_GENERATIONS - 1 - && long_lived_pending < long_lived_total / 4) - continue; - n = collect(i); - break; - } - } - return n; + /* Find the oldest generation (highest numbered) where the count + * exceeds the threshold. Objects in the that generation and + * generations younger than it will be collected. */ + for (i = NUM_GENERATIONS-1; i >= 0; i--) { + if (generations[i].count > generations[i].threshold) { + /* Avoid quadratic performance degradation in number + of tracked objects. See comments at the beginning + of this file, and issue #4074. + */ + if (i == NUM_GENERATIONS - 1 + && long_lived_pending < long_lived_total / 4) + continue; + n = collect(i); + break; + } + } + return n; } PyDoc_STRVAR(gc_enable__doc__, @@ -975,9 +975,9 @@ static PyObject * gc_enable(PyObject *self, PyObject *noargs) { - enabled = 1; - Py_INCREF(Py_None); - return Py_None; + enabled = 1; + Py_INCREF(Py_None); + return Py_None; } PyDoc_STRVAR(gc_disable__doc__, @@ -988,9 +988,9 @@ static PyObject * gc_disable(PyObject *self, PyObject *noargs) { - enabled = 0; - Py_INCREF(Py_None); - return Py_None; + enabled = 0; + Py_INCREF(Py_None); + return Py_None; } PyDoc_STRVAR(gc_isenabled__doc__, @@ -1001,7 +1001,7 @@ static PyObject * gc_isenabled(PyObject *self, PyObject *noargs) { - return PyBool_FromLong((long)enabled); + return PyBool_FromLong((long)enabled); } PyDoc_STRVAR(gc_collect__doc__, @@ -1015,27 +1015,27 @@ static PyObject * gc_collect(PyObject *self, PyObject *args, PyObject *kws) { - static char *keywords[] = {"generation", NULL}; - int genarg = NUM_GENERATIONS - 1; - Py_ssize_t n; - - if (!PyArg_ParseTupleAndKeywords(args, kws, "|i", keywords, &genarg)) - return NULL; - - else if (genarg < 0 || genarg >= NUM_GENERATIONS) { - PyErr_SetString(PyExc_ValueError, "invalid generation"); - return NULL; - } - - if (collecting) - n = 0; /* already collecting, don't do anything */ - else { - collecting = 1; - n = collect(genarg); - collecting = 0; - } + static char *keywords[] = {"generation", NULL}; + int genarg = NUM_GENERATIONS - 1; + Py_ssize_t n; + + if (!PyArg_ParseTupleAndKeywords(args, kws, "|i", keywords, &genarg)) + return NULL; + + else if (genarg < 0 || genarg >= NUM_GENERATIONS) { + PyErr_SetString(PyExc_ValueError, "invalid generation"); + return NULL; + } + + if (collecting) + n = 0; /* already collecting, don't do anything */ + else { + collecting = 1; + n = collect(genarg); + collecting = 0; + } - return PyLong_FromSsize_t(n); + return PyLong_FromSsize_t(n); } PyDoc_STRVAR(gc_set_debug__doc__, @@ -1055,11 +1055,11 @@ static PyObject * gc_set_debug(PyObject *self, PyObject *args) { - if (!PyArg_ParseTuple(args, "i:set_debug", &debug)) - return NULL; + if (!PyArg_ParseTuple(args, "i:set_debug", &debug)) + return NULL; - Py_INCREF(Py_None); - return Py_None; + Py_INCREF(Py_None); + return Py_None; } PyDoc_STRVAR(gc_get_debug__doc__, @@ -1070,7 +1070,7 @@ static PyObject * gc_get_debug(PyObject *self, PyObject *noargs) { - return Py_BuildValue("i", debug); + return Py_BuildValue("i", debug); } PyDoc_STRVAR(gc_set_thresh__doc__, @@ -1082,19 +1082,19 @@ static PyObject * gc_set_thresh(PyObject *self, PyObject *args) { - int i; - if (!PyArg_ParseTuple(args, "i|ii:set_threshold", - &generations[0].threshold, - &generations[1].threshold, - &generations[2].threshold)) - return NULL; - for (i = 2; i < NUM_GENERATIONS; i++) { - /* generations higher than 2 get the same threshold */ - generations[i].threshold = generations[2].threshold; - } + int i; + if (!PyArg_ParseTuple(args, "i|ii:set_threshold", + &generations[0].threshold, + &generations[1].threshold, + &generations[2].threshold)) + return NULL; + for (i = 2; i < NUM_GENERATIONS; i++) { + /* generations higher than 2 get the same threshold */ + generations[i].threshold = generations[2].threshold; + } - Py_INCREF(Py_None); - return Py_None; + Py_INCREF(Py_None); + return Py_None; } PyDoc_STRVAR(gc_get_thresh__doc__, @@ -1105,10 +1105,10 @@ static PyObject * gc_get_thresh(PyObject *self, PyObject *noargs) { - return Py_BuildValue("(iii)", - generations[0].threshold, - generations[1].threshold, - generations[2].threshold); + return Py_BuildValue("(iii)", + generations[0].threshold, + generations[1].threshold, + generations[2].threshold); } PyDoc_STRVAR(gc_get_count__doc__, @@ -1119,39 +1119,39 @@ static PyObject * gc_get_count(PyObject *self, PyObject *noargs) { - return Py_BuildValue("(iii)", - generations[0].count, - generations[1].count, - generations[2].count); + return Py_BuildValue("(iii)", + generations[0].count, + generations[1].count, + generations[2].count); } static int referrersvisit(PyObject* obj, PyObject *objs) { - Py_ssize_t i; - for (i = 0; i < PyTuple_GET_SIZE(objs); i++) - if (PyTuple_GET_ITEM(objs, i) == obj) - return 1; - return 0; + Py_ssize_t i; + for (i = 0; i < PyTuple_GET_SIZE(objs); i++) + if (PyTuple_GET_ITEM(objs, i) == obj) + return 1; + return 0; } static int gc_referrers_for(PyObject *objs, PyGC_Head *list, PyObject *resultlist) { - PyGC_Head *gc; - PyObject *obj; - traverseproc traverse; - for (gc = list->gc.gc_next; gc != list; gc = gc->gc.gc_next) { - obj = FROM_GC(gc); - traverse = Py_TYPE(obj)->tp_traverse; - if (obj == objs || obj == resultlist) - continue; - if (traverse(obj, (visitproc)referrersvisit, objs)) { - if (PyList_Append(resultlist, obj) < 0) - return 0; /* error */ - } - } - return 1; /* no error */ + PyGC_Head *gc; + PyObject *obj; + traverseproc traverse; + for (gc = list->gc.gc_next; gc != list; gc = gc->gc.gc_next) { + obj = FROM_GC(gc); + traverse = Py_TYPE(obj)->tp_traverse; + if (obj == objs || obj == resultlist) + continue; + if (traverse(obj, (visitproc)referrersvisit, objs)) { + if (PyList_Append(resultlist, obj) < 0) + return 0; /* error */ + } + } + return 1; /* no error */ } PyDoc_STRVAR(gc_get_referrers__doc__, @@ -1161,24 +1161,24 @@ static PyObject * gc_get_referrers(PyObject *self, PyObject *args) { - int i; - PyObject *result = PyList_New(0); - if (!result) return NULL; - - for (i = 0; i < NUM_GENERATIONS; i++) { - if (!(gc_referrers_for(args, GEN_HEAD(i), result))) { - Py_DECREF(result); - return NULL; - } - } - return result; + int i; + PyObject *result = PyList_New(0); + if (!result) return NULL; + + for (i = 0; i < NUM_GENERATIONS; i++) { + if (!(gc_referrers_for(args, GEN_HEAD(i), result))) { + Py_DECREF(result); + return NULL; + } + } + return result; } /* Append obj to list; return true if error (out of memory), false if OK. */ static int referentsvisit(PyObject *obj, PyObject *list) { - return PyList_Append(list, obj) < 0; + return PyList_Append(list, obj) < 0; } PyDoc_STRVAR(gc_get_referents__doc__, @@ -1188,27 +1188,27 @@ static PyObject * gc_get_referents(PyObject *self, PyObject *args) { - Py_ssize_t i; - PyObject *result = PyList_New(0); + Py_ssize_t i; + PyObject *result = PyList_New(0); - if (result == NULL) - return NULL; + if (result == NULL) + return NULL; - for (i = 0; i < PyTuple_GET_SIZE(args); i++) { - traverseproc traverse; - PyObject *obj = PyTuple_GET_ITEM(args, i); - - if (! PyObject_IS_GC(obj)) - continue; - traverse = Py_TYPE(obj)->tp_traverse; - if (! traverse) - continue; - if (traverse(obj, (visitproc)referentsvisit, result)) { - Py_DECREF(result); - return NULL; - } - } - return result; + for (i = 0; i < PyTuple_GET_SIZE(args); i++) { + traverseproc traverse; + PyObject *obj = PyTuple_GET_ITEM(args, i); + + if (! PyObject_IS_GC(obj)) + continue; + traverse = Py_TYPE(obj)->tp_traverse; + if (! traverse) + continue; + if (traverse(obj, (visitproc)referentsvisit, result)) { + Py_DECREF(result); + return NULL; + } + } + return result; } PyDoc_STRVAR(gc_get_objects__doc__, @@ -1220,19 +1220,19 @@ static PyObject * gc_get_objects(PyObject *self, PyObject *noargs) { - int i; - PyObject* result; + int i; + PyObject* result; - result = PyList_New(0); - if (result == NULL) - return NULL; - for (i = 0; i < NUM_GENERATIONS; i++) { - if (append_objects(result, GEN_HEAD(i))) { - Py_DECREF(result); - return NULL; - } - } - return result; + result = PyList_New(0); + if (result == NULL) + return NULL; + for (i = 0; i < NUM_GENERATIONS; i++) { + if (append_objects(result, GEN_HEAD(i))) { + Py_DECREF(result); + return NULL; + } + } + return result; } PyDoc_STRVAR(gc_is_tracked__doc__, @@ -1245,14 +1245,14 @@ static PyObject * gc_is_tracked(PyObject *self, PyObject *obj) { - PyObject *result; - - if (PyObject_IS_GC(obj) && IS_TRACKED(obj)) - result = Py_True; - else - result = Py_False; - Py_INCREF(result); - return result; + PyObject *result; + + if (PyObject_IS_GC(obj) && IS_TRACKED(obj)) + result = Py_True; + else + result = Py_False; + Py_INCREF(result); + return result; } @@ -1274,101 +1274,101 @@ "get_referents() -- Return the list of objects that an object refers to.\n"); static PyMethodDef GcMethods[] = { - {"enable", gc_enable, METH_NOARGS, gc_enable__doc__}, - {"disable", gc_disable, METH_NOARGS, gc_disable__doc__}, - {"isenabled", gc_isenabled, METH_NOARGS, gc_isenabled__doc__}, - {"set_debug", gc_set_debug, METH_VARARGS, gc_set_debug__doc__}, - {"get_debug", gc_get_debug, METH_NOARGS, gc_get_debug__doc__}, - {"get_count", gc_get_count, METH_NOARGS, gc_get_count__doc__}, - {"set_threshold", gc_set_thresh, METH_VARARGS, gc_set_thresh__doc__}, - {"get_threshold", gc_get_thresh, METH_NOARGS, gc_get_thresh__doc__}, - {"collect", (PyCFunction)gc_collect, - METH_VARARGS | METH_KEYWORDS, gc_collect__doc__}, - {"get_objects", gc_get_objects,METH_NOARGS, gc_get_objects__doc__}, - {"is_tracked", gc_is_tracked, METH_O, gc_is_tracked__doc__}, - {"get_referrers", gc_get_referrers, METH_VARARGS, - gc_get_referrers__doc__}, - {"get_referents", gc_get_referents, METH_VARARGS, - gc_get_referents__doc__}, - {NULL, NULL} /* Sentinel */ + {"enable", gc_enable, METH_NOARGS, gc_enable__doc__}, + {"disable", gc_disable, METH_NOARGS, gc_disable__doc__}, + {"isenabled", gc_isenabled, METH_NOARGS, gc_isenabled__doc__}, + {"set_debug", gc_set_debug, METH_VARARGS, gc_set_debug__doc__}, + {"get_debug", gc_get_debug, METH_NOARGS, gc_get_debug__doc__}, + {"get_count", gc_get_count, METH_NOARGS, gc_get_count__doc__}, + {"set_threshold", gc_set_thresh, METH_VARARGS, gc_set_thresh__doc__}, + {"get_threshold", gc_get_thresh, METH_NOARGS, gc_get_thresh__doc__}, + {"collect", (PyCFunction)gc_collect, + METH_VARARGS | METH_KEYWORDS, gc_collect__doc__}, + {"get_objects", gc_get_objects,METH_NOARGS, gc_get_objects__doc__}, + {"is_tracked", gc_is_tracked, METH_O, gc_is_tracked__doc__}, + {"get_referrers", gc_get_referrers, METH_VARARGS, + gc_get_referrers__doc__}, + {"get_referents", gc_get_referents, METH_VARARGS, + gc_get_referents__doc__}, + {NULL, NULL} /* Sentinel */ }; static struct PyModuleDef gcmodule = { - PyModuleDef_HEAD_INIT, - "gc", - gc__doc__, - -1, - GcMethods, - NULL, - NULL, - NULL, - NULL + PyModuleDef_HEAD_INIT, + "gc", + gc__doc__, + -1, + GcMethods, + NULL, + NULL, + NULL, + NULL }; PyMODINIT_FUNC PyInit_gc(void) { - PyObject *m; + PyObject *m; - m = PyModule_Create(&gcmodule); + m = PyModule_Create(&gcmodule); - if (m == NULL) - return NULL; + if (m == NULL) + return NULL; - if (garbage == NULL) { - garbage = PyList_New(0); - if (garbage == NULL) - return NULL; - } - Py_INCREF(garbage); - if (PyModule_AddObject(m, "garbage", garbage) < 0) - return NULL; - - /* Importing can't be done in collect() because collect() - * can be called via PyGC_Collect() in Py_Finalize(). - * This wouldn't be a problem, except that is - * reset to 0 before calling collect which trips up - * the import and triggers an assertion. - */ - if (tmod == NULL) { - tmod = PyImport_ImportModuleNoBlock("time"); - if (tmod == NULL) - PyErr_Clear(); - } + if (garbage == NULL) { + garbage = PyList_New(0); + if (garbage == NULL) + return NULL; + } + Py_INCREF(garbage); + if (PyModule_AddObject(m, "garbage", garbage) < 0) + return NULL; + + /* Importing can't be done in collect() because collect() + * can be called via PyGC_Collect() in Py_Finalize(). + * This wouldn't be a problem, except that is + * reset to 0 before calling collect which trips up + * the import and triggers an assertion. + */ + if (tmod == NULL) { + tmod = PyImport_ImportModuleNoBlock("time"); + if (tmod == NULL) + PyErr_Clear(); + } #define ADD_INT(NAME) if (PyModule_AddIntConstant(m, #NAME, NAME) < 0) return NULL - ADD_INT(DEBUG_STATS); - ADD_INT(DEBUG_COLLECTABLE); - ADD_INT(DEBUG_UNCOLLECTABLE); - ADD_INT(DEBUG_SAVEALL); - ADD_INT(DEBUG_LEAK); + ADD_INT(DEBUG_STATS); + ADD_INT(DEBUG_COLLECTABLE); + ADD_INT(DEBUG_UNCOLLECTABLE); + ADD_INT(DEBUG_SAVEALL); + ADD_INT(DEBUG_LEAK); #undef ADD_INT - return m; + return m; } /* API to invoke gc.collect() from C */ Py_ssize_t PyGC_Collect(void) { - Py_ssize_t n; + Py_ssize_t n; - if (collecting) - n = 0; /* already collecting, don't do anything */ - else { - collecting = 1; - n = collect(NUM_GENERATIONS - 1); - collecting = 0; - } + if (collecting) + n = 0; /* already collecting, don't do anything */ + else { + collecting = 1; + n = collect(NUM_GENERATIONS - 1); + collecting = 0; + } - return n; + return n; } /* for debugging */ void _PyGC_Dump(PyGC_Head *g) { - _PyObject_Dump(FROM_GC(g)); + _PyObject_Dump(FROM_GC(g)); } /* extension modules might be compiled with GC support so these @@ -1382,7 +1382,7 @@ void PyObject_GC_Track(void *op) { - _PyObject_GC_TRACK(op); + _PyObject_GC_TRACK(op); } /* for binary compatibility with 2.2 */ @@ -1395,11 +1395,11 @@ void PyObject_GC_UnTrack(void *op) { - /* Obscure: the Py_TRASHCAN mechanism requires that we be able to - * call PyObject_GC_UnTrack twice on an object. - */ - if (IS_TRACKED(op)) - _PyObject_GC_UNTRACK(op); + /* Obscure: the Py_TRASHCAN mechanism requires that we be able to + * call PyObject_GC_UnTrack twice on an object. + */ + if (IS_TRACKED(op)) + _PyObject_GC_UNTRACK(op); } /* for binary compatibility with 2.2 */ @@ -1412,73 +1412,73 @@ PyObject * _PyObject_GC_Malloc(size_t basicsize) { - PyObject *op; - PyGC_Head *g; - if (basicsize > PY_SSIZE_T_MAX - sizeof(PyGC_Head)) - return PyErr_NoMemory(); - g = (PyGC_Head *)PyObject_MALLOC( - sizeof(PyGC_Head) + basicsize); - if (g == NULL) - return PyErr_NoMemory(); - g->gc.gc_refs = GC_UNTRACKED; - generations[0].count++; /* number of allocated GC objects */ - if (generations[0].count > generations[0].threshold && - enabled && - generations[0].threshold && - !collecting && - !PyErr_Occurred()) { - collecting = 1; - collect_generations(); - collecting = 0; - } - op = FROM_GC(g); - return op; + PyObject *op; + PyGC_Head *g; + if (basicsize > PY_SSIZE_T_MAX - sizeof(PyGC_Head)) + return PyErr_NoMemory(); + g = (PyGC_Head *)PyObject_MALLOC( + sizeof(PyGC_Head) + basicsize); + if (g == NULL) + return PyErr_NoMemory(); + g->gc.gc_refs = GC_UNTRACKED; + generations[0].count++; /* number of allocated GC objects */ + if (generations[0].count > generations[0].threshold && + enabled && + generations[0].threshold && + !collecting && + !PyErr_Occurred()) { + collecting = 1; + collect_generations(); + collecting = 0; + } + op = FROM_GC(g); + return op; } PyObject * _PyObject_GC_New(PyTypeObject *tp) { - PyObject *op = _PyObject_GC_Malloc(_PyObject_SIZE(tp)); - if (op != NULL) - op = PyObject_INIT(op, tp); - return op; + PyObject *op = _PyObject_GC_Malloc(_PyObject_SIZE(tp)); + if (op != NULL) + op = PyObject_INIT(op, tp); + return op; } PyVarObject * _PyObject_GC_NewVar(PyTypeObject *tp, Py_ssize_t nitems) { - const size_t size = _PyObject_VAR_SIZE(tp, nitems); - PyVarObject *op = (PyVarObject *) _PyObject_GC_Malloc(size); - if (op != NULL) - op = PyObject_INIT_VAR(op, tp, nitems); - return op; + const size_t size = _PyObject_VAR_SIZE(tp, nitems); + PyVarObject *op = (PyVarObject *) _PyObject_GC_Malloc(size); + if (op != NULL) + op = PyObject_INIT_VAR(op, tp, nitems); + return op; } PyVarObject * _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); - if (basicsize > PY_SSIZE_T_MAX - sizeof(PyGC_Head)) - return (PyVarObject *)PyErr_NoMemory(); - g = (PyGC_Head *)PyObject_REALLOC(g, sizeof(PyGC_Head) + basicsize); - if (g == NULL) - return (PyVarObject *)PyErr_NoMemory(); - op = (PyVarObject *) FROM_GC(g); - Py_SIZE(op) = nitems; - return op; + const size_t basicsize = _PyObject_VAR_SIZE(Py_TYPE(op), nitems); + PyGC_Head *g = AS_GC(op); + if (basicsize > PY_SSIZE_T_MAX - sizeof(PyGC_Head)) + return (PyVarObject *)PyErr_NoMemory(); + g = (PyGC_Head *)PyObject_REALLOC(g, sizeof(PyGC_Head) + basicsize); + if (g == NULL) + return (PyVarObject *)PyErr_NoMemory(); + op = (PyVarObject *) FROM_GC(g); + Py_SIZE(op) = nitems; + return op; } void PyObject_GC_Del(void *op) { - PyGC_Head *g = AS_GC(op); - if (IS_TRACKED(op)) - gc_list_remove(g); - if (generations[0].count > 0) { - generations[0].count--; - } - PyObject_FREE(g); + PyGC_Head *g = AS_GC(op); + if (IS_TRACKED(op)) + gc_list_remove(g); + if (generations[0].count > 0) { + generations[0].count--; + } + PyObject_FREE(g); } /* for binary compatibility with 2.2 */ Modified: python/branches/release31-maint/Modules/getaddrinfo.c ============================================================================== --- python/branches/release31-maint/Modules/getaddrinfo.c (original) +++ python/branches/release31-maint/Modules/getaddrinfo.c Sun May 9 18:14:21 2010 @@ -1,7 +1,7 @@ /* * 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: @@ -13,7 +13,7 @@ * 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 @@ -73,52 +73,52 @@ static const char in_addrany[] = { 0, 0, 0, 0 }; static const char in6_addrany[] = { - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }; -static const char in_loopback[] = { 127, 0, 0, 1 }; +static const char in_loopback[] = { 127, 0, 0, 1 }; static const char in6_loopback[] = { - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1 + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1 }; struct sockinet { - u_char si_len; - u_char si_family; - u_short si_port; + u_char si_len; + u_char si_family; + u_short si_port; }; static struct gai_afd { - int a_af; - int a_addrlen; - int a_socklen; - int a_off; - const char *a_addrany; - const char *a_loopback; + int a_af; + int a_addrlen; + int a_socklen; + int a_off; + const char *a_addrany; + const char *a_loopback; } gai_afdl [] = { #ifdef ENABLE_IPV6 #define N_INET6 0 - {PF_INET6, sizeof(struct in6_addr), - sizeof(struct sockaddr_in6), - offsetof(struct sockaddr_in6, sin6_addr), - in6_addrany, in6_loopback}, + {PF_INET6, sizeof(struct in6_addr), + sizeof(struct sockaddr_in6), + offsetof(struct sockaddr_in6, sin6_addr), + in6_addrany, in6_loopback}, #define N_INET 1 #else #define N_INET 0 #endif - {PF_INET, sizeof(struct in_addr), - sizeof(struct sockaddr_in), - offsetof(struct sockaddr_in, sin_addr), - in_addrany, in_loopback}, - {0, 0, 0, 0, NULL, NULL}, + {PF_INET, sizeof(struct in_addr), + sizeof(struct sockaddr_in), + offsetof(struct sockaddr_in, sin_addr), + in_addrany, in_loopback}, + {0, 0, 0, 0, NULL, NULL}, }; #ifdef ENABLE_IPV6 -#define PTON_MAX 16 +#define PTON_MAX 16 #else -#define PTON_MAX 4 +#define PTON_MAX 4 #endif #ifndef IN_MULTICAST -#define IN_MULTICAST(i) (((i) & 0xf0000000U) == 0xe0000000U) +#define IN_MULTICAST(i) (((i) & 0xf0000000U) == 0xe0000000U) #endif #ifndef IN_EXPERIMENTAL @@ -126,73 +126,73 @@ #endif #ifndef IN_LOOPBACKNET -#define IN_LOOPBACKNET 127 +#define IN_LOOPBACKNET 127 #endif static int get_name(const char *, struct gai_afd *, - struct addrinfo **, char *, struct addrinfo *, - int); + struct addrinfo **, char *, struct addrinfo *, + int); static int get_addr(const char *, int, struct addrinfo **, - struct addrinfo *, int); + struct addrinfo *, int); static int str_isnumber(const char *); - + static char *ai_errlist[] = { - "success.", - "address family for hostname not supported.", /* EAI_ADDRFAMILY */ - "temporary failure in name resolution.", /* EAI_AGAIN */ - "invalid value for ai_flags.", /* EAI_BADFLAGS */ - "non-recoverable failure in name resolution.", /* EAI_FAIL */ - "ai_family not supported.", /* EAI_FAMILY */ - "memory allocation failure.", /* EAI_MEMORY */ - "no address associated with hostname.", /* EAI_NODATA */ - "hostname nor servname provided, or not known.",/* EAI_NONAME */ - "servname not supported for ai_socktype.", /* EAI_SERVICE */ - "ai_socktype not supported.", /* EAI_SOCKTYPE */ - "system error returned in errno.", /* EAI_SYSTEM */ - "invalid value for hints.", /* EAI_BADHINTS */ - "resolved protocol is unknown.", /* EAI_PROTOCOL */ - "unknown error.", /* EAI_MAX */ + "success.", + "address family for hostname not supported.", /* EAI_ADDRFAMILY */ + "temporary failure in name resolution.", /* EAI_AGAIN */ + "invalid value for ai_flags.", /* EAI_BADFLAGS */ + "non-recoverable failure in name resolution.", /* EAI_FAIL */ + "ai_family not supported.", /* EAI_FAMILY */ + "memory allocation failure.", /* EAI_MEMORY */ + "no address associated with hostname.", /* EAI_NODATA */ + "hostname nor servname provided, or not known.",/* EAI_NONAME */ + "servname not supported for ai_socktype.", /* EAI_SERVICE */ + "ai_socktype not supported.", /* EAI_SOCKTYPE */ + "system error returned in errno.", /* EAI_SYSTEM */ + "invalid value for hints.", /* EAI_BADHINTS */ + "resolved protocol is unknown.", /* EAI_PROTOCOL */ + "unknown error.", /* EAI_MAX */ }; #define GET_CANONNAME(ai, str) \ if (pai->ai_flags & AI_CANONNAME) {\ - if (((ai)->ai_canonname = (char *)malloc(strlen(str) + 1)) != NULL) {\ - strcpy((ai)->ai_canonname, (str));\ - } else {\ - error = EAI_MEMORY;\ - goto free;\ - }\ + if (((ai)->ai_canonname = (char *)malloc(strlen(str) + 1)) != NULL) {\ + strcpy((ai)->ai_canonname, (str));\ + } else {\ + error = EAI_MEMORY;\ + goto free;\ + }\ } #ifdef HAVE_SOCKADDR_SA_LEN #define GET_AI(ai, gai_afd, addr, port) {\ - char *p;\ - if (((ai) = (struct addrinfo *)malloc(sizeof(struct addrinfo) +\ - ((gai_afd)->a_socklen)))\ - == NULL) goto free;\ - memcpy(ai, pai, sizeof(struct addrinfo));\ - (ai)->ai_addr = (struct sockaddr *)((ai) + 1);\ - memset((ai)->ai_addr, 0, (gai_afd)->a_socklen);\ - (ai)->ai_addr->sa_len = (ai)->ai_addrlen = (gai_afd)->a_socklen;\ - (ai)->ai_addr->sa_family = (ai)->ai_family = (gai_afd)->a_af;\ - ((struct sockinet *)(ai)->ai_addr)->si_port = port;\ - p = (char *)((ai)->ai_addr);\ - memcpy(p + (gai_afd)->a_off, (addr), (gai_afd)->a_addrlen);\ + char *p;\ + if (((ai) = (struct addrinfo *)malloc(sizeof(struct addrinfo) +\ + ((gai_afd)->a_socklen)))\ + == NULL) goto free;\ + memcpy(ai, pai, sizeof(struct addrinfo));\ + (ai)->ai_addr = (struct sockaddr *)((ai) + 1);\ + memset((ai)->ai_addr, 0, (gai_afd)->a_socklen);\ + (ai)->ai_addr->sa_len = (ai)->ai_addrlen = (gai_afd)->a_socklen;\ + (ai)->ai_addr->sa_family = (ai)->ai_family = (gai_afd)->a_af;\ + ((struct sockinet *)(ai)->ai_addr)->si_port = port;\ + p = (char *)((ai)->ai_addr);\ + memcpy(p + (gai_afd)->a_off, (addr), (gai_afd)->a_addrlen);\ } #else #define GET_AI(ai, gai_afd, addr, port) {\ - char *p;\ - if (((ai) = (struct addrinfo *)malloc(sizeof(struct addrinfo) +\ - ((gai_afd)->a_socklen)))\ - == NULL) goto free;\ - memcpy(ai, pai, sizeof(struct addrinfo));\ - (ai)->ai_addr = (struct sockaddr *)((ai) + 1);\ - memset((ai)->ai_addr, 0, (gai_afd)->a_socklen);\ - (ai)->ai_addrlen = (gai_afd)->a_socklen;\ - (ai)->ai_addr->sa_family = (ai)->ai_family = (gai_afd)->a_af;\ - ((struct sockinet *)(ai)->ai_addr)->si_port = port;\ - p = (char *)((ai)->ai_addr);\ - memcpy(p + (gai_afd)->a_off, (addr), (gai_afd)->a_addrlen);\ + char *p;\ + if (((ai) = (struct addrinfo *)malloc(sizeof(struct addrinfo) +\ + ((gai_afd)->a_socklen)))\ + == NULL) goto free;\ + memcpy(ai, pai, sizeof(struct addrinfo));\ + (ai)->ai_addr = (struct sockaddr *)((ai) + 1);\ + memset((ai)->ai_addr, 0, (gai_afd)->a_socklen);\ + (ai)->ai_addrlen = (gai_afd)->a_socklen;\ + (ai)->ai_addr->sa_family = (ai)->ai_family = (gai_afd)->a_af;\ + ((struct sockinet *)(ai)->ai_addr)->si_port = port;\ + p = (char *)((ai)->ai_addr);\ + memcpy(p + (gai_afd)->a_off, (addr), (gai_afd)->a_addrlen);\ } #endif @@ -201,438 +201,438 @@ char * gai_strerror(int ecode) { - if (ecode < 0 || ecode > EAI_MAX) - ecode = EAI_MAX; - return ai_errlist[ecode]; + if (ecode < 0 || ecode > EAI_MAX) + ecode = EAI_MAX; + return ai_errlist[ecode]; } void freeaddrinfo(struct addrinfo *ai) { - struct addrinfo *next; + struct addrinfo *next; - do { - next = ai->ai_next; - if (ai->ai_canonname) - free(ai->ai_canonname); - /* no need to free(ai->ai_addr) */ - free(ai); - } while ((ai = next) != NULL); + do { + next = ai->ai_next; + if (ai->ai_canonname) + free(ai->ai_canonname); + /* no need to free(ai->ai_addr) */ + free(ai); + } while ((ai = next) != NULL); } static int str_isnumber(const char *p) { - unsigned char *q = (unsigned char *)p; - while (*q) { - if (! isdigit(*q)) - return NO; - q++; - } - return YES; + unsigned char *q = (unsigned char *)p; + while (*q) { + if (! isdigit(*q)) + return NO; + q++; + } + return YES; } int getaddrinfo(const char*hostname, const char*servname, const struct addrinfo *hints, struct addrinfo **res) { - struct addrinfo sentinel; - struct addrinfo *top = NULL; - struct addrinfo *cur; - int i, error = 0; - char pton[PTON_MAX]; - struct addrinfo ai; - struct addrinfo *pai; - u_short port; + struct addrinfo sentinel; + struct addrinfo *top = NULL; + struct addrinfo *cur; + int i, error = 0; + char pton[PTON_MAX]; + struct addrinfo ai; + struct addrinfo *pai; + u_short port; #ifdef FAITH - static int firsttime = 1; + static int firsttime = 1; - if (firsttime) { - /* translator hack */ - { - char *q = getenv("GAI"); - if (q && inet_pton(AF_INET6, q, &faith_prefix) == 1) - translate = YES; - } - firsttime = 0; - } -#endif - - /* initialize file static vars */ - sentinel.ai_next = NULL; - cur = &sentinel; - pai = &ai; - pai->ai_flags = 0; - pai->ai_family = PF_UNSPEC; - pai->ai_socktype = GAI_ANY; - pai->ai_protocol = GAI_ANY; - pai->ai_addrlen = 0; - pai->ai_canonname = NULL; - pai->ai_addr = NULL; - pai->ai_next = NULL; - port = GAI_ANY; - - if (hostname == NULL && servname == NULL) - return EAI_NONAME; - if (hints) { - /* error check for hints */ - if (hints->ai_addrlen || hints->ai_canonname || - hints->ai_addr || hints->ai_next) - ERR(EAI_BADHINTS); /* xxx */ - if (hints->ai_flags & ~AI_MASK) - ERR(EAI_BADFLAGS); - switch (hints->ai_family) { - case PF_UNSPEC: - case PF_INET: -#ifdef ENABLE_IPV6 - case PF_INET6: -#endif - break; - default: - ERR(EAI_FAMILY); - } - memcpy(pai, hints, sizeof(*pai)); - switch (pai->ai_socktype) { - case GAI_ANY: - switch (pai->ai_protocol) { - case GAI_ANY: - break; - case IPPROTO_UDP: - pai->ai_socktype = SOCK_DGRAM; - break; - case IPPROTO_TCP: - pai->ai_socktype = SOCK_STREAM; - break; - default: - pai->ai_socktype = SOCK_RAW; - break; - } - break; - case SOCK_RAW: - break; - case SOCK_DGRAM: - if (pai->ai_protocol != IPPROTO_UDP && - pai->ai_protocol != GAI_ANY) - ERR(EAI_BADHINTS); /*xxx*/ - pai->ai_protocol = IPPROTO_UDP; - break; - case SOCK_STREAM: - if (pai->ai_protocol != IPPROTO_TCP && - pai->ai_protocol != GAI_ANY) - ERR(EAI_BADHINTS); /*xxx*/ - pai->ai_protocol = IPPROTO_TCP; - break; - default: - ERR(EAI_SOCKTYPE); - /* unreachable */ - } - } - - /* - * service port - */ - if (servname) { - if (str_isnumber(servname)) { - if (pai->ai_socktype == GAI_ANY) { - /* caller accept *GAI_ANY* socktype */ - pai->ai_socktype = SOCK_DGRAM; - pai->ai_protocol = IPPROTO_UDP; - } - port = htons((u_short)atoi(servname)); - } else { - struct servent *sp; - char *proto; - - proto = NULL; - switch (pai->ai_socktype) { - case GAI_ANY: - proto = NULL; - break; - case SOCK_DGRAM: - proto = "udp"; - break; - case SOCK_STREAM: - proto = "tcp"; - break; - default: - fprintf(stderr, "panic!\n"); - break; - } - if ((sp = getservbyname(servname, proto)) == NULL) - ERR(EAI_SERVICE); - port = sp->s_port; - if (pai->ai_socktype == GAI_ANY) { - if (strcmp(sp->s_proto, "udp") == 0) { - pai->ai_socktype = SOCK_DGRAM; - pai->ai_protocol = IPPROTO_UDP; - } else if (strcmp(sp->s_proto, "tcp") == 0) { - pai->ai_socktype = SOCK_STREAM; - pai->ai_protocol = IPPROTO_TCP; - } else - ERR(EAI_PROTOCOL); /*xxx*/ - } - } - } - - /* - * hostname == NULL. - * passive socket -> anyaddr (0.0.0.0 or ::) - * non-passive socket -> localhost (127.0.0.1 or ::1) - */ - if (hostname == NULL) { - struct gai_afd *gai_afd; - - for (gai_afd = &gai_afdl[0]; gai_afd->a_af; gai_afd++) { - if (!(pai->ai_family == PF_UNSPEC - || pai->ai_family == gai_afd->a_af)) { - continue; - } - - if (pai->ai_flags & AI_PASSIVE) { - GET_AI(cur->ai_next, gai_afd, gai_afd->a_addrany, port); - /* xxx meaningless? - * GET_CANONNAME(cur->ai_next, "anyaddr"); - */ - } else { - GET_AI(cur->ai_next, gai_afd, gai_afd->a_loopback, - port); - /* xxx meaningless? - * GET_CANONNAME(cur->ai_next, "localhost"); - */ - } - cur = cur->ai_next; - } - top = sentinel.ai_next; - if (top) - goto good; - else - ERR(EAI_FAMILY); - } - - /* hostname as numeric name */ - for (i = 0; gai_afdl[i].a_af; i++) { - if (inet_pton(gai_afdl[i].a_af, hostname, pton)) { - u_long v4a; -#ifdef ENABLE_IPV6 - u_char pfx; -#endif - - switch (gai_afdl[i].a_af) { - case AF_INET: - v4a = ((struct in_addr *)pton)->s_addr; - v4a = ntohl(v4a); - if (IN_MULTICAST(v4a) || IN_EXPERIMENTAL(v4a)) - pai->ai_flags &= ~AI_CANONNAME; - v4a >>= IN_CLASSA_NSHIFT; - if (v4a == 0 || v4a == IN_LOOPBACKNET) - pai->ai_flags &= ~AI_CANONNAME; - break; -#ifdef ENABLE_IPV6 - case AF_INET6: - pfx = ((struct in6_addr *)pton)->s6_addr8[0]; - if (pfx == 0 || pfx == 0xfe || pfx == 0xff) - pai->ai_flags &= ~AI_CANONNAME; - break; -#endif - } - - if (pai->ai_family == gai_afdl[i].a_af || - pai->ai_family == PF_UNSPEC) { - if (! (pai->ai_flags & AI_CANONNAME)) { - GET_AI(top, &gai_afdl[i], pton, port); - goto good; - } - /* - * if AI_CANONNAME and if reverse lookup - * fail, return ai anyway to pacify - * calling application. - * - * XXX getaddrinfo() is a name->address - * translation function, and it looks strange - * that we do addr->name translation here. - */ - get_name(pton, &gai_afdl[i], &top, pton, pai, port); - goto good; - } else - ERR(EAI_FAMILY); /*xxx*/ - } - } - - if (pai->ai_flags & AI_NUMERICHOST) - ERR(EAI_NONAME); - - /* hostname as alphabetical name */ - error = get_addr(hostname, pai->ai_family, &top, pai, port); - if (error == 0) { - if (top) { + if (firsttime) { + /* translator hack */ + { + char *q = getenv("GAI"); + if (q && inet_pton(AF_INET6, q, &faith_prefix) == 1) + translate = YES; + } + firsttime = 0; + } +#endif + + /* initialize file static vars */ + sentinel.ai_next = NULL; + cur = &sentinel; + pai = &ai; + pai->ai_flags = 0; + pai->ai_family = PF_UNSPEC; + pai->ai_socktype = GAI_ANY; + pai->ai_protocol = GAI_ANY; + pai->ai_addrlen = 0; + pai->ai_canonname = NULL; + pai->ai_addr = NULL; + pai->ai_next = NULL; + port = GAI_ANY; + + if (hostname == NULL && servname == NULL) + return EAI_NONAME; + if (hints) { + /* error check for hints */ + if (hints->ai_addrlen || hints->ai_canonname || + hints->ai_addr || hints->ai_next) + ERR(EAI_BADHINTS); /* xxx */ + if (hints->ai_flags & ~AI_MASK) + ERR(EAI_BADFLAGS); + switch (hints->ai_family) { + case PF_UNSPEC: + case PF_INET: +#ifdef ENABLE_IPV6 + case PF_INET6: +#endif + break; + default: + ERR(EAI_FAMILY); + } + memcpy(pai, hints, sizeof(*pai)); + switch (pai->ai_socktype) { + case GAI_ANY: + switch (pai->ai_protocol) { + case GAI_ANY: + break; + case IPPROTO_UDP: + pai->ai_socktype = SOCK_DGRAM; + break; + case IPPROTO_TCP: + pai->ai_socktype = SOCK_STREAM; + break; + default: + pai->ai_socktype = SOCK_RAW; + break; + } + break; + case SOCK_RAW: + break; + case SOCK_DGRAM: + if (pai->ai_protocol != IPPROTO_UDP && + pai->ai_protocol != GAI_ANY) + ERR(EAI_BADHINTS); /*xxx*/ + pai->ai_protocol = IPPROTO_UDP; + break; + case SOCK_STREAM: + if (pai->ai_protocol != IPPROTO_TCP && + pai->ai_protocol != GAI_ANY) + ERR(EAI_BADHINTS); /*xxx*/ + pai->ai_protocol = IPPROTO_TCP; + break; + default: + ERR(EAI_SOCKTYPE); + /* unreachable */ + } + } + + /* + * service port + */ + if (servname) { + if (str_isnumber(servname)) { + if (pai->ai_socktype == GAI_ANY) { + /* caller accept *GAI_ANY* socktype */ + pai->ai_socktype = SOCK_DGRAM; + pai->ai_protocol = IPPROTO_UDP; + } + port = htons((u_short)atoi(servname)); + } else { + struct servent *sp; + char *proto; + + proto = NULL; + switch (pai->ai_socktype) { + case GAI_ANY: + proto = NULL; + break; + case SOCK_DGRAM: + proto = "udp"; + break; + case SOCK_STREAM: + proto = "tcp"; + break; + default: + fprintf(stderr, "panic!\n"); + break; + } + if ((sp = getservbyname(servname, proto)) == NULL) + ERR(EAI_SERVICE); + port = sp->s_port; + if (pai->ai_socktype == GAI_ANY) { + if (strcmp(sp->s_proto, "udp") == 0) { + pai->ai_socktype = SOCK_DGRAM; + pai->ai_protocol = IPPROTO_UDP; + } else if (strcmp(sp->s_proto, "tcp") == 0) { + pai->ai_socktype = SOCK_STREAM; + pai->ai_protocol = IPPROTO_TCP; + } else + ERR(EAI_PROTOCOL); /*xxx*/ + } + } + } + + /* + * hostname == NULL. + * passive socket -> anyaddr (0.0.0.0 or ::) + * non-passive socket -> localhost (127.0.0.1 or ::1) + */ + if (hostname == NULL) { + struct gai_afd *gai_afd; + + for (gai_afd = &gai_afdl[0]; gai_afd->a_af; gai_afd++) { + if (!(pai->ai_family == PF_UNSPEC + || pai->ai_family == gai_afd->a_af)) { + continue; + } + + if (pai->ai_flags & AI_PASSIVE) { + GET_AI(cur->ai_next, gai_afd, gai_afd->a_addrany, port); + /* xxx meaningless? + * GET_CANONNAME(cur->ai_next, "anyaddr"); + */ + } else { + GET_AI(cur->ai_next, gai_afd, gai_afd->a_loopback, + port); + /* xxx meaningless? + * GET_CANONNAME(cur->ai_next, "localhost"); + */ + } + cur = cur->ai_next; + } + top = sentinel.ai_next; + if (top) + goto good; + else + ERR(EAI_FAMILY); + } + + /* hostname as numeric name */ + for (i = 0; gai_afdl[i].a_af; i++) { + if (inet_pton(gai_afdl[i].a_af, hostname, pton)) { + u_long v4a; +#ifdef ENABLE_IPV6 + u_char pfx; +#endif + + switch (gai_afdl[i].a_af) { + case AF_INET: + v4a = ((struct in_addr *)pton)->s_addr; + v4a = ntohl(v4a); + if (IN_MULTICAST(v4a) || IN_EXPERIMENTAL(v4a)) + pai->ai_flags &= ~AI_CANONNAME; + v4a >>= IN_CLASSA_NSHIFT; + if (v4a == 0 || v4a == IN_LOOPBACKNET) + pai->ai_flags &= ~AI_CANONNAME; + break; +#ifdef ENABLE_IPV6 + case AF_INET6: + pfx = ((struct in6_addr *)pton)->s6_addr8[0]; + if (pfx == 0 || pfx == 0xfe || pfx == 0xff) + pai->ai_flags &= ~AI_CANONNAME; + break; +#endif + } + + if (pai->ai_family == gai_afdl[i].a_af || + pai->ai_family == PF_UNSPEC) { + if (! (pai->ai_flags & AI_CANONNAME)) { + GET_AI(top, &gai_afdl[i], pton, port); + goto good; + } + /* + * if AI_CANONNAME and if reverse lookup + * fail, return ai anyway to pacify + * calling application. + * + * XXX getaddrinfo() is a name->address + * translation function, and it looks strange + * that we do addr->name translation here. + */ + get_name(pton, &gai_afdl[i], &top, pton, pai, port); + goto good; + } else + ERR(EAI_FAMILY); /*xxx*/ + } + } + + if (pai->ai_flags & AI_NUMERICHOST) + ERR(EAI_NONAME); + + /* hostname as alphabetical name */ + error = get_addr(hostname, pai->ai_family, &top, pai, port); + if (error == 0) { + if (top) { good: - *res = top; - return SUCCESS; - } else - error = EAI_FAIL; - } + *res = top; + return SUCCESS; + } else + error = EAI_FAIL; + } free: - if (top) - freeaddrinfo(top); + if (top) + freeaddrinfo(top); bad: - *res = NULL; - return error; + *res = NULL; + return error; } static int get_name(addr, gai_afd, res, numaddr, pai, port0) - const char *addr; - struct gai_afd *gai_afd; - struct addrinfo **res; - char *numaddr; - struct addrinfo *pai; - int port0; + const char *addr; + struct gai_afd *gai_afd; + struct addrinfo **res; + char *numaddr; + struct addrinfo *pai; + int port0; { - u_short port = port0 & 0xffff; - struct hostent *hp; - struct addrinfo *cur; - int error = 0; + u_short port = port0 & 0xffff; + struct hostent *hp; + struct addrinfo *cur; + int error = 0; #ifdef ENABLE_IPV6 - int h_error; + int h_error; #endif - + #ifdef ENABLE_IPV6 - hp = getipnodebyaddr(addr, gai_afd->a_addrlen, gai_afd->a_af, &h_error); + hp = getipnodebyaddr(addr, gai_afd->a_addrlen, gai_afd->a_af, &h_error); #else - hp = gethostbyaddr(addr, gai_afd->a_addrlen, AF_INET); + hp = gethostbyaddr(addr, gai_afd->a_addrlen, AF_INET); #endif - if (hp && hp->h_name && hp->h_name[0] && hp->h_addr_list[0]) { - GET_AI(cur, gai_afd, hp->h_addr_list[0], port); - GET_CANONNAME(cur, hp->h_name); - } else - GET_AI(cur, gai_afd, numaddr, port); - + if (hp && hp->h_name && hp->h_name[0] && hp->h_addr_list[0]) { + GET_AI(cur, gai_afd, hp->h_addr_list[0], port); + GET_CANONNAME(cur, hp->h_name); + } else + GET_AI(cur, gai_afd, numaddr, port); + #ifdef ENABLE_IPV6 - if (hp) - freehostent(hp); + if (hp) + freehostent(hp); #endif - *res = cur; - return SUCCESS; + *res = cur; + return SUCCESS; free: - if (cur) - freeaddrinfo(cur); + if (cur) + freeaddrinfo(cur); #ifdef ENABLE_IPV6 - if (hp) - freehostent(hp); + if (hp) + freehostent(hp); #endif /* bad: */ - *res = NULL; - return error; + *res = NULL; + return error; } static int get_addr(hostname, af, res, pai, port0) - const char *hostname; - int af; - struct addrinfo **res; - struct addrinfo *pai; - int port0; + const char *hostname; + int af; + struct addrinfo **res; + struct addrinfo *pai; + int port0; { - u_short port = port0 & 0xffff; - struct addrinfo sentinel; - struct hostent *hp; - struct addrinfo *top, *cur; - struct gai_afd *gai_afd; - int i, error = 0, h_error; - char *ap; - - top = NULL; - sentinel.ai_next = NULL; - cur = &sentinel; -#ifdef ENABLE_IPV6 - if (af == AF_UNSPEC) { - hp = getipnodebyname(hostname, AF_INET6, - AI_ADDRCONFIG|AI_ALL|AI_V4MAPPED, &h_error); - } else - hp = getipnodebyname(hostname, af, AI_ADDRCONFIG, &h_error); + u_short port = port0 & 0xffff; + struct addrinfo sentinel; + struct hostent *hp; + struct addrinfo *top, *cur; + struct gai_afd *gai_afd; + int i, error = 0, h_error; + char *ap; + + top = NULL; + sentinel.ai_next = NULL; + cur = &sentinel; +#ifdef ENABLE_IPV6 + if (af == AF_UNSPEC) { + hp = getipnodebyname(hostname, AF_INET6, + AI_ADDRCONFIG|AI_ALL|AI_V4MAPPED, &h_error); + } else + hp = getipnodebyname(hostname, af, AI_ADDRCONFIG, &h_error); #else - hp = gethostbyname(hostname); - h_error = h_errno; + hp = gethostbyname(hostname); + h_error = h_errno; #endif - if (hp == NULL) { - switch (h_error) { - case HOST_NOT_FOUND: - case NO_DATA: - error = EAI_NODATA; - break; - case TRY_AGAIN: - error = EAI_AGAIN; - break; - case NO_RECOVERY: - default: - error = EAI_FAIL; - break; - } - goto free; - } - - if ((hp->h_name == NULL) || (hp->h_name[0] == 0) || - (hp->h_addr_list[0] == NULL)) { - error = EAI_FAIL; - goto free; - } - - for (i = 0; (ap = hp->h_addr_list[i]) != NULL; i++) { - switch (af) { -#ifdef ENABLE_IPV6 - case AF_INET6: - gai_afd = &gai_afdl[N_INET6]; - break; + if (hp == NULL) { + switch (h_error) { + case HOST_NOT_FOUND: + case NO_DATA: + error = EAI_NODATA; + break; + case TRY_AGAIN: + error = EAI_AGAIN; + break; + case NO_RECOVERY: + default: + error = EAI_FAIL; + break; + } + goto free; + } + + if ((hp->h_name == NULL) || (hp->h_name[0] == 0) || + (hp->h_addr_list[0] == NULL)) { + error = EAI_FAIL; + goto free; + } + + for (i = 0; (ap = hp->h_addr_list[i]) != NULL; i++) { + switch (af) { +#ifdef ENABLE_IPV6 + case AF_INET6: + gai_afd = &gai_afdl[N_INET6]; + break; #endif #ifndef ENABLE_IPV6 - default: /* AF_UNSPEC */ + default: /* AF_UNSPEC */ #endif - case AF_INET: - gai_afd = &gai_afdl[N_INET]; - break; -#ifdef ENABLE_IPV6 - default: /* AF_UNSPEC */ - if (IN6_IS_ADDR_V4MAPPED((struct in6_addr *)ap)) { - ap += sizeof(struct in6_addr) - - sizeof(struct in_addr); - gai_afd = &gai_afdl[N_INET]; - } else - gai_afd = &gai_afdl[N_INET6]; - break; + case AF_INET: + gai_afd = &gai_afdl[N_INET]; + break; +#ifdef ENABLE_IPV6 + default: /* AF_UNSPEC */ + if (IN6_IS_ADDR_V4MAPPED((struct in6_addr *)ap)) { + ap += sizeof(struct in6_addr) - + sizeof(struct in_addr); + gai_afd = &gai_afdl[N_INET]; + } else + gai_afd = &gai_afdl[N_INET6]; + break; #endif - } + } #ifdef FAITH - if (translate && gai_afd->a_af == AF_INET) { - struct in6_addr *in6; + if (translate && gai_afd->a_af == AF_INET) { + struct in6_addr *in6; - GET_AI(cur->ai_next, &gai_afdl[N_INET6], ap, port); - in6 = &((struct sockaddr_in6 *)cur->ai_next->ai_addr)->sin6_addr; - memcpy(&in6->s6_addr32[0], &faith_prefix, - sizeof(struct in6_addr) - sizeof(struct in_addr)); - memcpy(&in6->s6_addr32[3], ap, sizeof(struct in_addr)); - } else + GET_AI(cur->ai_next, &gai_afdl[N_INET6], ap, port); + in6 = &((struct sockaddr_in6 *)cur->ai_next->ai_addr)->sin6_addr; + memcpy(&in6->s6_addr32[0], &faith_prefix, + sizeof(struct in6_addr) - sizeof(struct in_addr)); + memcpy(&in6->s6_addr32[3], ap, sizeof(struct in_addr)); + } else #endif /* FAITH */ - GET_AI(cur->ai_next, gai_afd, ap, port); - if (cur == &sentinel) { - top = cur->ai_next; - GET_CANONNAME(top, hp->h_name); - } - cur = cur->ai_next; - } + GET_AI(cur->ai_next, gai_afd, ap, port); + if (cur == &sentinel) { + top = cur->ai_next; + GET_CANONNAME(top, hp->h_name); + } + cur = cur->ai_next; + } #ifdef ENABLE_IPV6 - freehostent(hp); + freehostent(hp); #endif - *res = top; - return SUCCESS; + *res = top; + return SUCCESS; free: - if (top) - freeaddrinfo(top); + if (top) + freeaddrinfo(top); #ifdef ENABLE_IPV6 - if (hp) - freehostent(hp); + if (hp) + freehostent(hp); #endif /* bad: */ - *res = NULL; - return error; + *res = NULL; + return error; } Modified: python/branches/release31-maint/Modules/getbuildinfo.c ============================================================================== --- python/branches/release31-maint/Modules/getbuildinfo.c (original) +++ python/branches/release31-maint/Modules/getbuildinfo.c Sun May 9 18:14:21 2010 @@ -31,22 +31,22 @@ const char * Py_GetBuildInfo(void) { - static char buildinfo[50]; - const char *revision = Py_SubversionRevision(); - const char *sep = *revision ? ":" : ""; - const char *branch = Py_SubversionShortBranch(); - PyOS_snprintf(buildinfo, sizeof(buildinfo), - "%s%s%s, %.20s, %.9s", branch, sep, revision, - DATE, TIME); - return buildinfo; + static char buildinfo[50]; + const char *revision = Py_SubversionRevision(); + const char *sep = *revision ? ":" : ""; + const char *branch = Py_SubversionShortBranch(); + PyOS_snprintf(buildinfo, sizeof(buildinfo), + "%s%s%s, %.20s, %.9s", branch, sep, revision, + DATE, TIME); + return buildinfo; } const char * _Py_svnversion(void) { - /* the following string can be modified by subwcrev.exe */ - static const char svnversion[] = SVNVERSION; - if (svnversion[0] != '$') - return svnversion; /* it was interpolated, or passed on command line */ - return "Unversioned directory"; + /* the following string can be modified by subwcrev.exe */ + static const char svnversion[] = SVNVERSION; + if (svnversion[0] != '$') + return svnversion; /* it was interpolated, or passed on command line */ + return "Unversioned directory"; } Modified: python/branches/release31-maint/Modules/getnameinfo.c ============================================================================== --- python/branches/release31-maint/Modules/getnameinfo.c (original) +++ python/branches/release31-maint/Modules/getnameinfo.c Sun May 9 18:14:21 2010 @@ -1,7 +1,7 @@ /* * 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: @@ -13,7 +13,7 @@ * 3. Neither the name of the project nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. - * + * * THIS SOFTWARE IS PROVIDED BY THE PROJECT AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE @@ -53,162 +53,162 @@ #define NO 0 static struct gni_afd { - int a_af; - int a_addrlen; - int a_socklen; - int a_off; + int a_af; + int a_addrlen; + int a_socklen; + int a_off; } gni_afdl [] = { #ifdef ENABLE_IPV6 - {PF_INET6, sizeof(struct in6_addr), sizeof(struct sockaddr_in6), - offsetof(struct sockaddr_in6, sin6_addr)}, + {PF_INET6, sizeof(struct in6_addr), sizeof(struct sockaddr_in6), + offsetof(struct sockaddr_in6, sin6_addr)}, #endif - {PF_INET, sizeof(struct in_addr), sizeof(struct sockaddr_in), - offsetof(struct sockaddr_in, sin_addr)}, - {0, 0, 0}, + {PF_INET, sizeof(struct in_addr), sizeof(struct sockaddr_in), + offsetof(struct sockaddr_in, sin_addr)}, + {0, 0, 0}, }; struct gni_sockinet { - u_char si_len; - u_char si_family; - u_short si_port; + u_char si_len; + u_char si_family; + u_short si_port; }; -#define ENI_NOSOCKET 0 -#define ENI_NOSERVNAME 1 -#define ENI_NOHOSTNAME 2 -#define ENI_MEMORY 3 -#define ENI_SYSTEM 4 -#define ENI_FAMILY 5 -#define ENI_SALEN 6 +#define ENI_NOSOCKET 0 +#define ENI_NOSERVNAME 1 +#define ENI_NOHOSTNAME 2 +#define ENI_MEMORY 3 +#define ENI_SYSTEM 4 +#define ENI_FAMILY 5 +#define ENI_SALEN 6 /* forward declaration to make gcc happy */ int getnameinfo(const struct sockaddr *, size_t, char *, size_t, - char *, size_t, int); + char *, size_t, int); int getnameinfo(sa, salen, host, hostlen, serv, servlen, flags) - const struct sockaddr *sa; - size_t salen; - char *host; - size_t hostlen; - char *serv; - size_t servlen; - int flags; + const struct sockaddr *sa; + size_t salen; + char *host; + size_t hostlen; + char *serv; + size_t servlen; + int flags; { - struct gni_afd *gni_afd; - struct servent *sp; - struct hostent *hp; - u_short port; - int family, len, i; - char *addr, *p; - u_long v4a; -#ifdef ENABLE_IPV6 - u_char pfx; -#endif - int h_error; - char numserv[512]; - char numaddr[512]; + struct gni_afd *gni_afd; + struct servent *sp; + struct hostent *hp; + u_short port; + int family, len, i; + char *addr, *p; + u_long v4a; +#ifdef ENABLE_IPV6 + u_char pfx; +#endif + int h_error; + char numserv[512]; + char numaddr[512]; - if (sa == NULL) - return ENI_NOSOCKET; + if (sa == NULL) + return ENI_NOSOCKET; #ifdef HAVE_SOCKADDR_SA_LEN - len = sa->sa_len; - if (len != salen) return ENI_SALEN; + len = sa->sa_len; + if (len != salen) return ENI_SALEN; #else - len = salen; + len = salen; #endif - - family = sa->sa_family; - for (i = 0; gni_afdl[i].a_af; i++) - if (gni_afdl[i].a_af == family) { - gni_afd = &gni_afdl[i]; - goto found; - } - return ENI_FAMILY; - + + family = sa->sa_family; + for (i = 0; gni_afdl[i].a_af; i++) + if (gni_afdl[i].a_af == family) { + gni_afd = &gni_afdl[i]; + goto found; + } + return ENI_FAMILY; + found: - if (len != gni_afd->a_socklen) return ENI_SALEN; - - port = ((struct gni_sockinet *)sa)->si_port; /* network byte order */ - addr = (char *)sa + gni_afd->a_off; - - if (serv == NULL || servlen == 0) { - /* what we should do? */ - } else if (flags & NI_NUMERICSERV) { - sprintf(numserv, "%d", ntohs(port)); - if (strlen(numserv) > servlen) - return ENI_MEMORY; - strcpy(serv, numserv); - } else { - sp = getservbyport(port, (flags & NI_DGRAM) ? "udp" : "tcp"); - if (sp) { - if (strlen(sp->s_name) > servlen) - return ENI_MEMORY; - strcpy(serv, sp->s_name); - } else - return ENI_NOSERVNAME; - } - - switch (sa->sa_family) { - case AF_INET: - v4a = ((struct sockaddr_in *)sa)->sin_addr.s_addr; - if (IN_MULTICAST(v4a) || IN_EXPERIMENTAL(v4a)) - flags |= NI_NUMERICHOST; - v4a >>= IN_CLASSA_NSHIFT; - if (v4a == 0 || v4a == IN_LOOPBACKNET) - flags |= NI_NUMERICHOST; - break; -#ifdef ENABLE_IPV6 - case AF_INET6: - pfx = ((struct sockaddr_in6 *)sa)->sin6_addr.s6_addr8[0]; - if (pfx == 0 || pfx == 0xfe || pfx == 0xff) - flags |= NI_NUMERICHOST; - break; -#endif - } - if (host == NULL || hostlen == 0) { - /* what should we do? */ - } else if (flags & NI_NUMERICHOST) { - if (inet_ntop(gni_afd->a_af, addr, numaddr, sizeof(numaddr)) - == NULL) - return ENI_SYSTEM; - if (strlen(numaddr) > hostlen) - return ENI_MEMORY; - strcpy(host, numaddr); - } else { + if (len != gni_afd->a_socklen) return ENI_SALEN; + + port = ((struct gni_sockinet *)sa)->si_port; /* network byte order */ + addr = (char *)sa + gni_afd->a_off; + + if (serv == NULL || servlen == 0) { + /* what we should do? */ + } else if (flags & NI_NUMERICSERV) { + sprintf(numserv, "%d", ntohs(port)); + if (strlen(numserv) > servlen) + return ENI_MEMORY; + strcpy(serv, numserv); + } else { + sp = getservbyport(port, (flags & NI_DGRAM) ? "udp" : "tcp"); + if (sp) { + if (strlen(sp->s_name) > servlen) + return ENI_MEMORY; + strcpy(serv, sp->s_name); + } else + return ENI_NOSERVNAME; + } + + switch (sa->sa_family) { + case AF_INET: + v4a = ((struct sockaddr_in *)sa)->sin_addr.s_addr; + if (IN_MULTICAST(v4a) || IN_EXPERIMENTAL(v4a)) + flags |= NI_NUMERICHOST; + v4a >>= IN_CLASSA_NSHIFT; + if (v4a == 0 || v4a == IN_LOOPBACKNET) + flags |= NI_NUMERICHOST; + break; +#ifdef ENABLE_IPV6 + case AF_INET6: + pfx = ((struct sockaddr_in6 *)sa)->sin6_addr.s6_addr8[0]; + if (pfx == 0 || pfx == 0xfe || pfx == 0xff) + flags |= NI_NUMERICHOST; + break; +#endif + } + if (host == NULL || hostlen == 0) { + /* what should we do? */ + } else if (flags & NI_NUMERICHOST) { + if (inet_ntop(gni_afd->a_af, addr, numaddr, sizeof(numaddr)) + == NULL) + return ENI_SYSTEM; + if (strlen(numaddr) > hostlen) + return ENI_MEMORY; + strcpy(host, numaddr); + } else { #ifdef ENABLE_IPV6 - hp = getipnodebyaddr(addr, gni_afd->a_addrlen, gni_afd->a_af, &h_error); + hp = getipnodebyaddr(addr, gni_afd->a_addrlen, gni_afd->a_af, &h_error); #else - hp = gethostbyaddr(addr, gni_afd->a_addrlen, gni_afd->a_af); - h_error = h_errno; + hp = gethostbyaddr(addr, gni_afd->a_addrlen, gni_afd->a_af); + h_error = h_errno; #endif - if (hp) { - if (flags & NI_NOFQDN) { - p = strchr(hp->h_name, '.'); - if (p) *p = '\0'; - } - if (strlen(hp->h_name) > hostlen) { -#ifdef ENABLE_IPV6 - freehostent(hp); -#endif - return ENI_MEMORY; - } - strcpy(host, hp->h_name); -#ifdef ENABLE_IPV6 - freehostent(hp); -#endif - } else { - if (flags & NI_NAMEREQD) - return ENI_NOHOSTNAME; - if (inet_ntop(gni_afd->a_af, addr, numaddr, sizeof(numaddr)) - == NULL) - return ENI_NOHOSTNAME; - if (strlen(numaddr) > hostlen) - return ENI_MEMORY; - strcpy(host, numaddr); - } - } - return SUCCESS; + if (hp) { + if (flags & NI_NOFQDN) { + p = strchr(hp->h_name, '.'); + if (p) *p = '\0'; + } + if (strlen(hp->h_name) > hostlen) { +#ifdef ENABLE_IPV6 + freehostent(hp); +#endif + return ENI_MEMORY; + } + strcpy(host, hp->h_name); +#ifdef ENABLE_IPV6 + freehostent(hp); +#endif + } else { + if (flags & NI_NAMEREQD) + return ENI_NOHOSTNAME; + if (inet_ntop(gni_afd->a_af, addr, numaddr, sizeof(numaddr)) + == NULL) + return ENI_NOHOSTNAME; + if (strlen(numaddr) > hostlen) + return ENI_MEMORY; + strcpy(host, numaddr); + } + } + return SUCCESS; } Modified: python/branches/release31-maint/Modules/getpath.c ============================================================================== --- python/branches/release31-maint/Modules/getpath.c (original) +++ python/branches/release31-maint/Modules/getpath.c Sun May 9 18:14:21 2010 @@ -142,8 +142,8 @@ char fname[PATH_MAX]; size_t res = wcstombs(fname, path, sizeof(fname)); if (res == (size_t)-1) { - errno = EINVAL; - return -1; + errno = EINVAL; + return -1; } return stat(fname, buf); } @@ -155,17 +155,17 @@ { char fname[PATH_MAX]; if (getcwd(fname, PATH_MAX) == NULL) - return NULL; + return NULL; if (mbstowcs(buf, fname, size) >= size) { - errno = ERANGE; - return NULL; + errno = ERANGE; + return NULL; } return buf; } #endif #ifdef HAVE_READLINK -int +int _Py_wreadlink(const wchar_t *path, wchar_t *buf, size_t bufsiz) { char cbuf[PATH_MAX]; @@ -173,24 +173,24 @@ int res; size_t r1 = wcstombs(cpath, path, PATH_MAX); if (r1 == (size_t)-1 || r1 >= PATH_MAX) { - errno = EINVAL; - return -1; + errno = EINVAL; + return -1; } res = (int)readlink(cpath, cbuf, PATH_MAX); if (res == -1) - return -1; + return -1; if (res == PATH_MAX) { - errno = EINVAL; - return -1; + errno = EINVAL; + return -1; } cbuf[res] = '\0'; /* buf will be null terminated */ r1 = mbstowcs(buf, cbuf, bufsiz); if (r1 == -1) { - errno = EINVAL; - return -1; + errno = EINVAL; + return -1; } return (int)r1; - + } #endif @@ -279,7 +279,7 @@ buffer[n++] = SEP; } if (n > MAXPATHLEN) - Py_FatalError("buffer overflow in getpath.c's joinpath()"); + Py_FatalError("buffer overflow in getpath.c's joinpath()"); k = wcslen(stuff); if (n + k > MAXPATHLEN) k = MAXPATHLEN - n; @@ -457,25 +457,25 @@ #else unsigned long nsexeclength = MAXPATHLEN; #endif - char execpath[MAXPATHLEN+1]; + char execpath[MAXPATHLEN+1]; #endif if (_path) { - size_t r = mbstowcs(wpath, _path, MAXPATHLEN+1); - path = wpath; - if (r == (size_t)-1 || r > MAXPATHLEN) { - /* Could not convert PATH, or it's too long. */ - path = NULL; - } + size_t r = mbstowcs(wpath, _path, MAXPATHLEN+1); + path = wpath; + if (r == (size_t)-1 || r > MAXPATHLEN) { + /* Could not convert PATH, or it's too long. */ + path = NULL; + } } - /* If there is no slash in the argv0 path, then we have to - * assume python is on the user's $PATH, since there's no - * other way to find a directory to start the search from. If - * $PATH isn't exported, you lose. - */ - if (wcschr(prog, SEP)) - wcsncpy(progpath, prog, MAXPATHLEN); + /* If there is no slash in the argv0 path, then we have to + * assume python is on the user's $PATH, since there's no + * other way to find a directory to start the search from. If + * $PATH isn't exported, you lose. + */ + if (wcschr(prog, SEP)) + wcsncpy(progpath, prog, MAXPATHLEN); #ifdef __APPLE__ /* On Mac OS X, if a script uses an interpreter of the form * "#!/opt/python2.3/bin/python", the kernel only passes "python" @@ -487,52 +487,52 @@ * will fail if a relative path was used. but in that case, * absolutize() should help us out below */ - else if(0 == _NSGetExecutablePath(execpath, &nsexeclength) && execpath[0] == SEP) { - size_t r = mbstowcs(progpath, execpath, MAXPATHLEN+1); - if (r == (size_t)-1 || r > MAXPATHLEN) { - /* Could not convert execpath, or it's too long. */ - progpath[0] = '\0'; - } - } + else if(0 == _NSGetExecutablePath(execpath, &nsexeclength) && execpath[0] == SEP) { + size_t r = mbstowcs(progpath, execpath, MAXPATHLEN+1); + if (r == (size_t)-1 || r > MAXPATHLEN) { + /* Could not convert execpath, or it's too long. */ + progpath[0] = '\0'; + } + } #endif /* __APPLE__ */ - else if (path) { - while (1) { - wchar_t *delim = wcschr(path, DELIM); - - if (delim) { - size_t len = delim - path; - if (len > MAXPATHLEN) - len = MAXPATHLEN; - wcsncpy(progpath, path, len); - *(progpath + len) = '\0'; - } - else - wcsncpy(progpath, path, MAXPATHLEN); - - joinpath(progpath, prog); - if (isxfile(progpath)) - break; - - if (!delim) { - progpath[0] = L'\0'; - break; - } - path = delim + 1; - } - } - else - progpath[0] = '\0'; - if (progpath[0] != SEP && progpath[0] != '\0') - absolutize(progpath); - wcsncpy(argv0_path, progpath, MAXPATHLEN); - argv0_path[MAXPATHLEN] = '\0'; + else if (path) { + while (1) { + wchar_t *delim = wcschr(path, DELIM); + + if (delim) { + size_t len = delim - path; + if (len > MAXPATHLEN) + len = MAXPATHLEN; + wcsncpy(progpath, path, len); + *(progpath + len) = '\0'; + } + else + wcsncpy(progpath, path, MAXPATHLEN); + + joinpath(progpath, prog); + if (isxfile(progpath)) + break; + + if (!delim) { + progpath[0] = L'\0'; + break; + } + path = delim + 1; + } + } + else + progpath[0] = '\0'; + if (progpath[0] != SEP && progpath[0] != '\0') + absolutize(progpath); + wcsncpy(argv0_path, progpath, MAXPATHLEN); + argv0_path[MAXPATHLEN] = '\0'; #ifdef WITH_NEXT_FRAMEWORK - /* On Mac OS X we have a special case if we're running from a framework. - ** This is because the python home should be set relative to the library, - ** which is in the framework, not relative to the executable, which may - ** be outside of the framework. Except when we're in the build directory... - */ + /* On Mac OS X we have a special case if we're running from a framework. + ** This is because the python home should be set relative to the library, + ** which is in the framework, not relative to the executable, which may + ** be outside of the framework. Except when we're in the build directory... + */ pythonModule = NSModuleForSymbol(NSLookupAndBindSymbol("_Py_Initialize")); /* Use dylib functions to find out where the framework was loaded from */ buf = (wchar_t *)NSLibraryNameForModule(pythonModule); @@ -604,7 +604,7 @@ else wcsncpy(zip_path, L"" PREFIX, MAXPATHLEN); joinpath(zip_path, L"lib/python00.zip"); - bufsz = wcslen(zip_path); /* Replace "00" with version */ + bufsz = wcslen(zip_path); /* Replace "00" with version */ zip_path[bufsz - 6] = VERSION[0]; zip_path[bufsz - 5] = VERSION[2]; @@ -626,12 +626,12 @@ bufsz = 0; if (_rtpypath) { - size_t s = mbstowcs(rtpypath, _rtpypath, sizeof(rtpypath)/sizeof(wchar_t)); - if (s == (size_t)-1 || s >=sizeof(rtpypath)) - /* XXX deal with errors more gracefully */ - _rtpypath = NULL; - if (_rtpypath) - bufsz += wcslen(rtpypath) + 1; + size_t s = mbstowcs(rtpypath, _rtpypath, sizeof(rtpypath)/sizeof(wchar_t)); + if (s == (size_t)-1 || s >=sizeof(rtpypath)) + /* XXX deal with errors more gracefully */ + _rtpypath = NULL; + if (_rtpypath) + bufsz += wcslen(rtpypath) + 1; } prefixsz = wcslen(prefix) + 1; @@ -718,10 +718,10 @@ if (pfound > 0) { reduce(prefix); reduce(prefix); - /* The prefix is the root directory, but reduce() chopped - * off the "/". */ - if (!prefix[0]) - wcscpy(prefix, separator); + /* The prefix is the root directory, but reduce() chopped + * off the "/". */ + if (!prefix[0]) + wcscpy(prefix, separator); } else wcsncpy(prefix, L"" PREFIX, MAXPATHLEN); @@ -730,8 +730,8 @@ reduce(exec_prefix); reduce(exec_prefix); reduce(exec_prefix); - if (!exec_prefix[0]) - wcscpy(exec_prefix, separator); + if (!exec_prefix[0]) + wcscpy(exec_prefix, separator); } else wcsncpy(exec_prefix, L"" EXEC_PREFIX, MAXPATHLEN); Modified: python/branches/release31-maint/Modules/grpmodule.c ============================================================================== --- python/branches/release31-maint/Modules/grpmodule.c (original) +++ python/branches/release31-maint/Modules/grpmodule.c Sun May 9 18:14:21 2010 @@ -10,8 +10,8 @@ static PyStructSequence_Field struct_group_type_fields[] = { {"gr_name", "group name"}, {"gr_passwd", "password"}, - {"gr_gid", "group id"}, - {"gr_mem", "group memebers"}, + {"gr_gid", "group id"}, + {"gr_mem", "group memebers"}, {0} }; @@ -67,10 +67,10 @@ Py_INCREF(Py_None); #else if (p->gr_passwd) - SET(setIndex++, FSDECODE(p->gr_passwd)); + SET(setIndex++, FSDECODE(p->gr_passwd)); else { - SET(setIndex++, Py_None); - Py_INCREF(Py_None); + SET(setIndex++, Py_None); + Py_INCREF(Py_None); } #endif SET(setIndex++, PyLong_FromLong((long) p->gr_gid)); @@ -94,12 +94,12 @@ py_int_id = PyNumber_Long(pyo_id); if (!py_int_id) - return NULL; + return NULL; gid = PyLong_AS_LONG(py_int_id); Py_DECREF(py_int_id); if ((p = getgrgid(gid)) == NULL) { - PyErr_Format(PyExc_KeyError, "getgrgid(): gid not found: %d", gid); + PyErr_Format(PyExc_KeyError, "getgrgid(): gid not found: %d", gid); return NULL; } return mkgrent(p); @@ -119,9 +119,9 @@ return NULL; if (PyBytes_AsStringAndSize(bytes, &name, NULL) == -1) goto out; - + if ((p = getgrnam(name)) == NULL) { - PyErr_Format(PyExc_KeyError, "getgrnam(): name not found: %s", name); + PyErr_Format(PyExc_KeyError, "getgrnam(): name not found: %s", name); goto out; } retval = mkgrent(p); @@ -154,18 +154,18 @@ } static PyMethodDef grp_methods[] = { - {"getgrgid", grp_getgrgid, METH_O, + {"getgrgid", grp_getgrgid, METH_O, "getgrgid(id) -> tuple\n\ Return the group database entry for the given numeric group ID. If\n\ id is not valid, raise KeyError."}, - {"getgrnam", grp_getgrnam, METH_VARARGS, + {"getgrnam", grp_getgrnam, METH_VARARGS, "getgrnam(name) -> tuple\n\ Return the group database entry for the given group name. If\n\ name is not valid, raise KeyError."}, - {"getgrall", grp_getgrall, METH_NOARGS, + {"getgrall", grp_getgrall, METH_NOARGS, "getgrall() -> list of tuples\n\ Return a list of all available group entries, in arbitrary order."}, - {NULL, NULL} /* sentinel */ + {NULL, NULL} /* sentinel */ }; PyDoc_STRVAR(grp__doc__, @@ -187,15 +187,15 @@ static struct PyModuleDef grpmodule = { - PyModuleDef_HEAD_INIT, - "grp", - grp__doc__, - -1, - grp_methods, - NULL, - NULL, - NULL, - NULL + PyModuleDef_HEAD_INIT, + "grp", + grp__doc__, + -1, + grp_methods, + NULL, + NULL, + NULL, + NULL }; PyMODINIT_FUNC @@ -207,7 +207,7 @@ return NULL; d = PyModule_GetDict(m); if (!initialized) - PyStructSequence_InitType(&StructGrpType, &struct_group_type_desc); + PyStructSequence_InitType(&StructGrpType, &struct_group_type_desc); PyDict_SetItemString(d, "struct_group", (PyObject *) &StructGrpType); initialized = 1; return m; Modified: python/branches/release31-maint/Modules/itertoolsmodule.c ============================================================================== --- python/branches/release31-maint/Modules/itertoolsmodule.c (original) +++ python/branches/release31-maint/Modules/itertoolsmodule.c Sun May 9 18:14:21 2010 @@ -2,7 +2,7 @@ #include "Python.h" #include "structmember.h" -/* Itertools module written and maintained +/* Itertools module written and maintained by Raymond D. Hettinger Copyright (c) 2003 Python Software Foundation. All rights reserved. @@ -12,12 +12,12 @@ /* groupby object ***********************************************************/ typedef struct { - PyObject_HEAD - PyObject *it; - PyObject *keyfunc; - PyObject *tgtkey; - PyObject *currkey; - PyObject *currvalue; + PyObject_HEAD + PyObject *it; + PyObject *keyfunc; + PyObject *tgtkey; + PyObject *currkey; + PyObject *currvalue; } groupbyobject; static PyTypeObject groupby_type; @@ -26,112 +26,112 @@ static PyObject * groupby_new(PyTypeObject *type, PyObject *args, PyObject *kwds) { - static char *kwargs[] = {"iterable", "key", NULL}; - groupbyobject *gbo; - PyObject *it, *keyfunc = Py_None; - - if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|O:groupby", kwargs, - &it, &keyfunc)) - return NULL; - - gbo = (groupbyobject *)type->tp_alloc(type, 0); - if (gbo == NULL) - return NULL; - gbo->tgtkey = NULL; - gbo->currkey = NULL; - gbo->currvalue = NULL; - gbo->keyfunc = keyfunc; - Py_INCREF(keyfunc); - gbo->it = PyObject_GetIter(it); - if (gbo->it == NULL) { - Py_DECREF(gbo); - return NULL; - } - return (PyObject *)gbo; + static char *kwargs[] = {"iterable", "key", NULL}; + groupbyobject *gbo; + PyObject *it, *keyfunc = Py_None; + + if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|O:groupby", kwargs, + &it, &keyfunc)) + return NULL; + + gbo = (groupbyobject *)type->tp_alloc(type, 0); + if (gbo == NULL) + return NULL; + gbo->tgtkey = NULL; + gbo->currkey = NULL; + gbo->currvalue = NULL; + gbo->keyfunc = keyfunc; + Py_INCREF(keyfunc); + gbo->it = PyObject_GetIter(it); + if (gbo->it == NULL) { + Py_DECREF(gbo); + return NULL; + } + return (PyObject *)gbo; } static void groupby_dealloc(groupbyobject *gbo) { - PyObject_GC_UnTrack(gbo); - Py_XDECREF(gbo->it); - Py_XDECREF(gbo->keyfunc); - Py_XDECREF(gbo->tgtkey); - Py_XDECREF(gbo->currkey); - Py_XDECREF(gbo->currvalue); - Py_TYPE(gbo)->tp_free(gbo); + PyObject_GC_UnTrack(gbo); + Py_XDECREF(gbo->it); + Py_XDECREF(gbo->keyfunc); + Py_XDECREF(gbo->tgtkey); + Py_XDECREF(gbo->currkey); + Py_XDECREF(gbo->currvalue); + Py_TYPE(gbo)->tp_free(gbo); } static int groupby_traverse(groupbyobject *gbo, visitproc visit, void *arg) { - Py_VISIT(gbo->it); - Py_VISIT(gbo->keyfunc); - Py_VISIT(gbo->tgtkey); - Py_VISIT(gbo->currkey); - Py_VISIT(gbo->currvalue); - return 0; + Py_VISIT(gbo->it); + Py_VISIT(gbo->keyfunc); + Py_VISIT(gbo->tgtkey); + Py_VISIT(gbo->currkey); + Py_VISIT(gbo->currvalue); + return 0; } static PyObject * groupby_next(groupbyobject *gbo) { - PyObject *newvalue, *newkey, *r, *grouper, *tmp; + PyObject *newvalue, *newkey, *r, *grouper, *tmp; - /* skip to next iteration group */ - for (;;) { - if (gbo->currkey == NULL) - /* pass */; - else if (gbo->tgtkey == NULL) - break; - else { - int rcmp; - - rcmp = PyObject_RichCompareBool(gbo->tgtkey, - gbo->currkey, Py_EQ); - if (rcmp == -1) - return NULL; - else if (rcmp == 0) - break; - } - - newvalue = PyIter_Next(gbo->it); - if (newvalue == NULL) - return NULL; - - if (gbo->keyfunc == Py_None) { - newkey = newvalue; - Py_INCREF(newvalue); - } else { - newkey = PyObject_CallFunctionObjArgs(gbo->keyfunc, - newvalue, NULL); - if (newkey == NULL) { - Py_DECREF(newvalue); - return NULL; - } - } - - tmp = gbo->currkey; - gbo->currkey = newkey; - Py_XDECREF(tmp); - - tmp = gbo->currvalue; - gbo->currvalue = newvalue; - Py_XDECREF(tmp); - } - - Py_INCREF(gbo->currkey); - tmp = gbo->tgtkey; - gbo->tgtkey = gbo->currkey; - Py_XDECREF(tmp); - - grouper = _grouper_create(gbo, gbo->tgtkey); - if (grouper == NULL) - return NULL; - - r = PyTuple_Pack(2, gbo->currkey, grouper); - Py_DECREF(grouper); - return r; + /* skip to next iteration group */ + for (;;) { + if (gbo->currkey == NULL) + /* pass */; + else if (gbo->tgtkey == NULL) + break; + else { + int rcmp; + + rcmp = PyObject_RichCompareBool(gbo->tgtkey, + gbo->currkey, Py_EQ); + if (rcmp == -1) + return NULL; + else if (rcmp == 0) + break; + } + + newvalue = PyIter_Next(gbo->it); + if (newvalue == NULL) + return NULL; + + if (gbo->keyfunc == Py_None) { + newkey = newvalue; + Py_INCREF(newvalue); + } else { + newkey = PyObject_CallFunctionObjArgs(gbo->keyfunc, + newvalue, NULL); + if (newkey == NULL) { + Py_DECREF(newvalue); + return NULL; + } + } + + tmp = gbo->currkey; + gbo->currkey = newkey; + Py_XDECREF(tmp); + + tmp = gbo->currvalue; + gbo->currvalue = newvalue; + Py_XDECREF(tmp); + } + + Py_INCREF(gbo->currkey); + tmp = gbo->tgtkey; + gbo->tgtkey = gbo->currkey; + Py_XDECREF(tmp); + + grouper = _grouper_create(gbo, gbo->tgtkey); + if (grouper == NULL) + return NULL; + + r = PyTuple_Pack(2, gbo->currkey, grouper); + Py_DECREF(grouper); + return r; } PyDoc_STRVAR(groupby_doc, @@ -139,56 +139,56 @@ (key, sub-iterator) grouped by each value of key(value).\n"); static PyTypeObject groupby_type = { - PyVarObject_HEAD_INIT(NULL, 0) - "itertools.groupby", /* tp_name */ - sizeof(groupbyobject), /* tp_basicsize */ - 0, /* tp_itemsize */ - /* methods */ - (destructor)groupby_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 | - Py_TPFLAGS_BASETYPE, /* tp_flags */ - groupby_doc, /* tp_doc */ - (traverseproc)groupby_traverse, /* tp_traverse */ - 0, /* tp_clear */ - 0, /* tp_richcompare */ - 0, /* tp_weaklistoffset */ - PyObject_SelfIter, /* tp_iter */ - (iternextfunc)groupby_next, /* tp_iternext */ - 0, /* tp_methods */ - 0, /* tp_members */ - 0, /* tp_getset */ - 0, /* tp_base */ - 0, /* tp_dict */ - 0, /* tp_descr_get */ - 0, /* tp_descr_set */ - 0, /* tp_dictoffset */ - 0, /* tp_init */ - 0, /* tp_alloc */ - groupby_new, /* tp_new */ - PyObject_GC_Del, /* tp_free */ + PyVarObject_HEAD_INIT(NULL, 0) + "itertools.groupby", /* tp_name */ + sizeof(groupbyobject), /* tp_basicsize */ + 0, /* tp_itemsize */ + /* methods */ + (destructor)groupby_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 | + Py_TPFLAGS_BASETYPE, /* tp_flags */ + groupby_doc, /* tp_doc */ + (traverseproc)groupby_traverse, /* tp_traverse */ + 0, /* tp_clear */ + 0, /* tp_richcompare */ + 0, /* tp_weaklistoffset */ + PyObject_SelfIter, /* tp_iter */ + (iternextfunc)groupby_next, /* tp_iternext */ + 0, /* tp_methods */ + 0, /* tp_members */ + 0, /* tp_getset */ + 0, /* tp_base */ + 0, /* tp_dict */ + 0, /* tp_descr_get */ + 0, /* tp_descr_set */ + 0, /* tp_dictoffset */ + 0, /* tp_init */ + 0, /* tp_alloc */ + groupby_new, /* tp_new */ + PyObject_GC_Del, /* tp_free */ }; /* _grouper object (internal) ************************************************/ typedef struct { - PyObject_HEAD - PyObject *parent; - PyObject *tgtkey; + PyObject_HEAD + PyObject *parent; + PyObject *tgtkey; } _grouperobject; static PyTypeObject _grouper_type; @@ -196,129 +196,129 @@ static PyObject * _grouper_create(groupbyobject *parent, PyObject *tgtkey) { - _grouperobject *igo; + _grouperobject *igo; - igo = PyObject_GC_New(_grouperobject, &_grouper_type); - if (igo == NULL) - return NULL; - igo->parent = (PyObject *)parent; - Py_INCREF(parent); - igo->tgtkey = tgtkey; - Py_INCREF(tgtkey); + igo = PyObject_GC_New(_grouperobject, &_grouper_type); + if (igo == NULL) + return NULL; + igo->parent = (PyObject *)parent; + Py_INCREF(parent); + igo->tgtkey = tgtkey; + Py_INCREF(tgtkey); - PyObject_GC_Track(igo); - return (PyObject *)igo; + PyObject_GC_Track(igo); + return (PyObject *)igo; } static void _grouper_dealloc(_grouperobject *igo) { - PyObject_GC_UnTrack(igo); - Py_DECREF(igo->parent); - Py_DECREF(igo->tgtkey); - PyObject_GC_Del(igo); + PyObject_GC_UnTrack(igo); + Py_DECREF(igo->parent); + Py_DECREF(igo->tgtkey); + PyObject_GC_Del(igo); } static int _grouper_traverse(_grouperobject *igo, visitproc visit, void *arg) { - Py_VISIT(igo->parent); - Py_VISIT(igo->tgtkey); - return 0; + Py_VISIT(igo->parent); + Py_VISIT(igo->tgtkey); + return 0; } static PyObject * _grouper_next(_grouperobject *igo) { - groupbyobject *gbo = (groupbyobject *)igo->parent; - PyObject *newvalue, *newkey, *r; - int rcmp; - - if (gbo->currvalue == NULL) { - newvalue = PyIter_Next(gbo->it); - if (newvalue == NULL) - return NULL; - - if (gbo->keyfunc == Py_None) { - newkey = newvalue; - Py_INCREF(newvalue); - } else { - newkey = PyObject_CallFunctionObjArgs(gbo->keyfunc, - newvalue, NULL); - if (newkey == NULL) { - Py_DECREF(newvalue); - return NULL; - } - } - - assert(gbo->currkey == NULL); - gbo->currkey = newkey; - gbo->currvalue = newvalue; - } - - assert(gbo->currkey != NULL); - rcmp = PyObject_RichCompareBool(igo->tgtkey, gbo->currkey, Py_EQ); - if (rcmp <= 0) - /* got any error or current group is end */ - return NULL; - - r = gbo->currvalue; - gbo->currvalue = NULL; - Py_CLEAR(gbo->currkey); + groupbyobject *gbo = (groupbyobject *)igo->parent; + PyObject *newvalue, *newkey, *r; + int rcmp; + + if (gbo->currvalue == NULL) { + newvalue = PyIter_Next(gbo->it); + if (newvalue == NULL) + return NULL; + + if (gbo->keyfunc == Py_None) { + newkey = newvalue; + Py_INCREF(newvalue); + } else { + newkey = PyObject_CallFunctionObjArgs(gbo->keyfunc, + newvalue, NULL); + if (newkey == NULL) { + Py_DECREF(newvalue); + return NULL; + } + } + + assert(gbo->currkey == NULL); + gbo->currkey = newkey; + gbo->currvalue = newvalue; + } + + assert(gbo->currkey != NULL); + rcmp = PyObject_RichCompareBool(igo->tgtkey, gbo->currkey, Py_EQ); + if (rcmp <= 0) + /* got any error or current group is end */ + return NULL; + + r = gbo->currvalue; + gbo->currvalue = NULL; + Py_CLEAR(gbo->currkey); - return r; + return r; } static PyTypeObject _grouper_type = { - PyVarObject_HEAD_INIT(NULL, 0) - "itertools._grouper", /* tp_name */ - sizeof(_grouperobject), /* tp_basicsize */ - 0, /* tp_itemsize */ - /* methods */ - (destructor)_grouper_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)_grouper_traverse,/* tp_traverse */ - 0, /* tp_clear */ - 0, /* tp_richcompare */ - 0, /* tp_weaklistoffset */ - PyObject_SelfIter, /* tp_iter */ - (iternextfunc)_grouper_next, /* tp_iternext */ - 0, /* tp_methods */ - 0, /* tp_members */ - 0, /* tp_getset */ - 0, /* tp_base */ - 0, /* tp_dict */ - 0, /* tp_descr_get */ - 0, /* tp_descr_set */ - 0, /* tp_dictoffset */ - 0, /* tp_init */ - 0, /* tp_alloc */ - 0, /* tp_new */ - PyObject_GC_Del, /* tp_free */ + PyVarObject_HEAD_INIT(NULL, 0) + "itertools._grouper", /* tp_name */ + sizeof(_grouperobject), /* tp_basicsize */ + 0, /* tp_itemsize */ + /* methods */ + (destructor)_grouper_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)_grouper_traverse,/* tp_traverse */ + 0, /* tp_clear */ + 0, /* tp_richcompare */ + 0, /* tp_weaklistoffset */ + PyObject_SelfIter, /* tp_iter */ + (iternextfunc)_grouper_next, /* tp_iternext */ + 0, /* tp_methods */ + 0, /* tp_members */ + 0, /* tp_getset */ + 0, /* tp_base */ + 0, /* tp_dict */ + 0, /* tp_descr_get */ + 0, /* tp_descr_set */ + 0, /* tp_dictoffset */ + 0, /* tp_init */ + 0, /* tp_alloc */ + 0, /* tp_new */ + PyObject_GC_Del, /* tp_free */ }; - + /* tee object and with supporting function and objects ***************/ /* The teedataobject pre-allocates space for LINKCELLS number of objects. To help the object fit neatly inside cache lines (space for 16 to 32 - pointers), the value should be a multiple of 16 minus space for + pointers), the value should be a multiple of 16 minus space for the other structure members including PyHEAD overhead. The larger the value, the less memory overhead per object and the less time spent allocating/deallocating new links. The smaller the number, the less @@ -327,18 +327,18 @@ #define LINKCELLS 57 typedef struct { - PyObject_HEAD - PyObject *it; - int numread; - PyObject *nextlink; - PyObject *(values[LINKCELLS]); + PyObject_HEAD + PyObject *it; + int numread; + PyObject *nextlink; + PyObject *(values[LINKCELLS]); } teedataobject; typedef struct { - PyObject_HEAD - teedataobject *dataobj; - int index; - PyObject *weakreflist; + PyObject_HEAD + teedataobject *dataobj; + int index; + PyObject *weakreflist; } teeobject; static PyTypeObject teedataobject_type; @@ -346,123 +346,123 @@ static PyObject * teedataobject_new(PyObject *it) { - teedataobject *tdo; + teedataobject *tdo; - tdo = PyObject_GC_New(teedataobject, &teedataobject_type); - if (tdo == NULL) - return NULL; - - tdo->numread = 0; - tdo->nextlink = NULL; - Py_INCREF(it); - tdo->it = it; - PyObject_GC_Track(tdo); - return (PyObject *)tdo; + tdo = PyObject_GC_New(teedataobject, &teedataobject_type); + if (tdo == NULL) + return NULL; + + tdo->numread = 0; + tdo->nextlink = NULL; + Py_INCREF(it); + tdo->it = it; + PyObject_GC_Track(tdo); + return (PyObject *)tdo; } static PyObject * teedataobject_jumplink(teedataobject *tdo) { - if (tdo->nextlink == NULL) - tdo->nextlink = teedataobject_new(tdo->it); - Py_XINCREF(tdo->nextlink); - return tdo->nextlink; + if (tdo->nextlink == NULL) + tdo->nextlink = teedataobject_new(tdo->it); + Py_XINCREF(tdo->nextlink); + return tdo->nextlink; } static PyObject * teedataobject_getitem(teedataobject *tdo, int i) { - PyObject *value; + PyObject *value; - assert(i < LINKCELLS); - if (i < tdo->numread) - value = tdo->values[i]; - else { - /* this is the lead iterator, so fetch more data */ - assert(i == tdo->numread); - value = PyIter_Next(tdo->it); - if (value == NULL) - return NULL; - tdo->numread++; - tdo->values[i] = value; - } - Py_INCREF(value); - return value; + assert(i < LINKCELLS); + if (i < tdo->numread) + value = tdo->values[i]; + else { + /* this is the lead iterator, so fetch more data */ + assert(i == tdo->numread); + value = PyIter_Next(tdo->it); + if (value == NULL) + return NULL; + tdo->numread++; + tdo->values[i] = value; + } + Py_INCREF(value); + return value; } static int teedataobject_traverse(teedataobject *tdo, visitproc visit, void * arg) { - int i; - Py_VISIT(tdo->it); - for (i = 0; i < tdo->numread; i++) - Py_VISIT(tdo->values[i]); - Py_VISIT(tdo->nextlink); - return 0; + int i; + Py_VISIT(tdo->it); + for (i = 0; i < tdo->numread; i++) + Py_VISIT(tdo->values[i]); + Py_VISIT(tdo->nextlink); + return 0; } static int teedataobject_clear(teedataobject *tdo) { - int i; - Py_CLEAR(tdo->it); - for (i=0 ; inumread ; i++) - Py_CLEAR(tdo->values[i]); - Py_CLEAR(tdo->nextlink); - return 0; + int i; + Py_CLEAR(tdo->it); + for (i=0 ; inumread ; i++) + Py_CLEAR(tdo->values[i]); + Py_CLEAR(tdo->nextlink); + return 0; } static void teedataobject_dealloc(teedataobject *tdo) { - PyObject_GC_UnTrack(tdo); - teedataobject_clear(tdo); - PyObject_GC_Del(tdo); + PyObject_GC_UnTrack(tdo); + teedataobject_clear(tdo); + PyObject_GC_Del(tdo); } PyDoc_STRVAR(teedataobject_doc, "Data container common to multiple tee objects."); static PyTypeObject teedataobject_type = { - PyVarObject_HEAD_INIT(0, 0) /* Must fill in type value later */ - "itertools.tee_dataobject", /* tp_name */ - sizeof(teedataobject), /* tp_basicsize */ - 0, /* tp_itemsize */ - /* methods */ - (destructor)teedataobject_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 */ - teedataobject_doc, /* tp_doc */ - (traverseproc)teedataobject_traverse, /* tp_traverse */ - (inquiry)teedataobject_clear, /* tp_clear */ - 0, /* tp_richcompare */ - 0, /* tp_weaklistoffset */ - 0, /* tp_iter */ - 0, /* tp_iternext */ - 0, /* tp_methods */ - 0, /* tp_members */ - 0, /* tp_getset */ - 0, /* tp_base */ - 0, /* tp_dict */ - 0, /* tp_descr_get */ - 0, /* tp_descr_set */ - 0, /* tp_dictoffset */ - 0, /* tp_init */ - 0, /* tp_alloc */ - 0, /* tp_new */ - PyObject_GC_Del, /* tp_free */ + PyVarObject_HEAD_INIT(0, 0) /* Must fill in type value later */ + "itertools.tee_dataobject", /* tp_name */ + sizeof(teedataobject), /* tp_basicsize */ + 0, /* tp_itemsize */ + /* methods */ + (destructor)teedataobject_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 */ + teedataobject_doc, /* tp_doc */ + (traverseproc)teedataobject_traverse, /* tp_traverse */ + (inquiry)teedataobject_clear, /* tp_clear */ + 0, /* tp_richcompare */ + 0, /* tp_weaklistoffset */ + 0, /* tp_iter */ + 0, /* tp_iternext */ + 0, /* tp_methods */ + 0, /* tp_members */ + 0, /* tp_getset */ + 0, /* tp_base */ + 0, /* tp_dict */ + 0, /* tp_descr_get */ + 0, /* tp_descr_set */ + 0, /* tp_dictoffset */ + 0, /* tp_init */ + 0, /* tp_alloc */ + 0, /* tp_new */ + PyObject_GC_Del, /* tp_free */ }; @@ -471,42 +471,42 @@ static PyObject * tee_next(teeobject *to) { - PyObject *value, *link; + PyObject *value, *link; - if (to->index >= LINKCELLS) { - link = teedataobject_jumplink(to->dataobj); - Py_DECREF(to->dataobj); - to->dataobj = (teedataobject *)link; - to->index = 0; - } - value = teedataobject_getitem(to->dataobj, to->index); - if (value == NULL) - return NULL; - to->index++; - return value; + if (to->index >= LINKCELLS) { + link = teedataobject_jumplink(to->dataobj); + Py_DECREF(to->dataobj); + to->dataobj = (teedataobject *)link; + to->index = 0; + } + value = teedataobject_getitem(to->dataobj, to->index); + if (value == NULL) + return NULL; + to->index++; + return value; } static int tee_traverse(teeobject *to, visitproc visit, void *arg) { - Py_VISIT((PyObject *)to->dataobj); - return 0; + Py_VISIT((PyObject *)to->dataobj); + return 0; } static PyObject * tee_copy(teeobject *to) { - teeobject *newto; + teeobject *newto; - newto = PyObject_GC_New(teeobject, &tee_type); - if (newto == NULL) - return NULL; - Py_INCREF(to->dataobj); - newto->dataobj = to->dataobj; - newto->index = to->index; - newto->weakreflist = NULL; - PyObject_GC_Track(newto); - return (PyObject *)newto; + newto = PyObject_GC_New(teeobject, &tee_type); + if (newto == NULL) + return NULL; + Py_INCREF(to->dataobj); + newto->dataobj = to->dataobj; + newto->index = to->index; + newto->weakreflist = NULL; + PyObject_GC_Track(newto); + return (PyObject *)newto; } PyDoc_STRVAR(teecopy_doc, "Returns an independent iterator."); @@ -514,154 +514,154 @@ static PyObject * tee_fromiterable(PyObject *iterable) { - teeobject *to; - PyObject *it = NULL; + teeobject *to; + PyObject *it = NULL; - it = PyObject_GetIter(iterable); - if (it == NULL) - return NULL; - if (PyObject_TypeCheck(it, &tee_type)) { - to = (teeobject *)tee_copy((teeobject *)it); - goto done; - } - - to = PyObject_GC_New(teeobject, &tee_type); - if (to == NULL) - goto done; - to->dataobj = (teedataobject *)teedataobject_new(it); - if (!to->dataobj) { - PyObject_GC_Del(to); - to = NULL; - goto done; - } - - to->index = 0; - to->weakreflist = NULL; - PyObject_GC_Track(to); + it = PyObject_GetIter(iterable); + if (it == NULL) + return NULL; + if (PyObject_TypeCheck(it, &tee_type)) { + to = (teeobject *)tee_copy((teeobject *)it); + goto done; + } + + to = PyObject_GC_New(teeobject, &tee_type); + if (to == NULL) + goto done; + to->dataobj = (teedataobject *)teedataobject_new(it); + if (!to->dataobj) { + PyObject_GC_Del(to); + to = NULL; + goto done; + } + + to->index = 0; + to->weakreflist = NULL; + PyObject_GC_Track(to); done: - Py_XDECREF(it); - return (PyObject *)to; + Py_XDECREF(it); + return (PyObject *)to; } static PyObject * tee_new(PyTypeObject *type, PyObject *args, PyObject *kw) { - PyObject *iterable; + PyObject *iterable; - if (!PyArg_UnpackTuple(args, "tee", 1, 1, &iterable)) - return NULL; - return tee_fromiterable(iterable); + if (!PyArg_UnpackTuple(args, "tee", 1, 1, &iterable)) + return NULL; + return tee_fromiterable(iterable); } static int tee_clear(teeobject *to) { - if (to->weakreflist != NULL) - PyObject_ClearWeakRefs((PyObject *) to); - Py_CLEAR(to->dataobj); - return 0; + if (to->weakreflist != NULL) + PyObject_ClearWeakRefs((PyObject *) to); + Py_CLEAR(to->dataobj); + return 0; } static void tee_dealloc(teeobject *to) { - PyObject_GC_UnTrack(to); - tee_clear(to); - PyObject_GC_Del(to); + PyObject_GC_UnTrack(to); + tee_clear(to); + PyObject_GC_Del(to); } PyDoc_STRVAR(teeobject_doc, "Iterator wrapped to make it copyable"); static PyMethodDef tee_methods[] = { - {"__copy__", (PyCFunction)tee_copy, METH_NOARGS, teecopy_doc}, - {NULL, NULL} /* sentinel */ + {"__copy__", (PyCFunction)tee_copy, METH_NOARGS, teecopy_doc}, + {NULL, NULL} /* sentinel */ }; static PyTypeObject tee_type = { - PyVarObject_HEAD_INIT(NULL, 0) - "itertools.tee", /* tp_name */ - sizeof(teeobject), /* tp_basicsize */ - 0, /* tp_itemsize */ - /* methods */ - (destructor)tee_dealloc, /* tp_dealloc */ - 0, /* tp_print */ - 0, /* tp_getattr */ - 0, /* tp_setattr */ - 0, /* tp_reserved */ - 0, /* tp_repr */ - 0, /* tp_as_number */ - 0, /* tp_as_sequence */ - 0, /* tp_as_mapping */ - 0, /* tp_hash */ - 0, /* tp_call */ - 0, /* tp_str */ - 0, /* tp_getattro */ - 0, /* tp_setattro */ - 0, /* tp_as_buffer */ - Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC, /* tp_flags */ - teeobject_doc, /* tp_doc */ - (traverseproc)tee_traverse, /* tp_traverse */ - (inquiry)tee_clear, /* tp_clear */ - 0, /* tp_richcompare */ - offsetof(teeobject, weakreflist), /* tp_weaklistoffset */ - PyObject_SelfIter, /* tp_iter */ - (iternextfunc)tee_next, /* tp_iternext */ - tee_methods, /* tp_methods */ - 0, /* tp_members */ - 0, /* tp_getset */ - 0, /* tp_base */ - 0, /* tp_dict */ - 0, /* tp_descr_get */ - 0, /* tp_descr_set */ - 0, /* tp_dictoffset */ - 0, /* tp_init */ - 0, /* tp_alloc */ - tee_new, /* tp_new */ - PyObject_GC_Del, /* tp_free */ + PyVarObject_HEAD_INIT(NULL, 0) + "itertools.tee", /* tp_name */ + sizeof(teeobject), /* tp_basicsize */ + 0, /* tp_itemsize */ + /* methods */ + (destructor)tee_dealloc, /* tp_dealloc */ + 0, /* tp_print */ + 0, /* tp_getattr */ + 0, /* tp_setattr */ + 0, /* tp_reserved */ + 0, /* tp_repr */ + 0, /* tp_as_number */ + 0, /* tp_as_sequence */ + 0, /* tp_as_mapping */ + 0, /* tp_hash */ + 0, /* tp_call */ + 0, /* tp_str */ + 0, /* tp_getattro */ + 0, /* tp_setattro */ + 0, /* tp_as_buffer */ + Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC, /* tp_flags */ + teeobject_doc, /* tp_doc */ + (traverseproc)tee_traverse, /* tp_traverse */ + (inquiry)tee_clear, /* tp_clear */ + 0, /* tp_richcompare */ + offsetof(teeobject, weakreflist), /* tp_weaklistoffset */ + PyObject_SelfIter, /* tp_iter */ + (iternextfunc)tee_next, /* tp_iternext */ + tee_methods, /* tp_methods */ + 0, /* tp_members */ + 0, /* tp_getset */ + 0, /* tp_base */ + 0, /* tp_dict */ + 0, /* tp_descr_get */ + 0, /* tp_descr_set */ + 0, /* tp_dictoffset */ + 0, /* tp_init */ + 0, /* tp_alloc */ + tee_new, /* tp_new */ + PyObject_GC_Del, /* tp_free */ }; static PyObject * tee(PyObject *self, PyObject *args) { - Py_ssize_t i, n=2; - PyObject *it, *iterable, *copyable, *result; + Py_ssize_t i, n=2; + PyObject *it, *iterable, *copyable, *result; - if (!PyArg_ParseTuple(args, "O|n", &iterable, &n)) - return NULL; - if (n < 0) { - PyErr_SetString(PyExc_ValueError, "n must be >= 0"); - return NULL; - } - result = PyTuple_New(n); - if (result == NULL) - return NULL; - if (n == 0) - return result; - it = PyObject_GetIter(iterable); - if (it == NULL) { - Py_DECREF(result); - return NULL; - } - if (!PyObject_HasAttrString(it, "__copy__")) { - copyable = tee_fromiterable(it); - Py_DECREF(it); - if (copyable == NULL) { - Py_DECREF(result); - return NULL; - } - } else - copyable = it; - PyTuple_SET_ITEM(result, 0, copyable); - for (i=1 ; i= 0"); + return NULL; + } + result = PyTuple_New(n); + if (result == NULL) + return NULL; + if (n == 0) + return result; + it = PyObject_GetIter(iterable); + if (it == NULL) { + Py_DECREF(result); + return NULL; + } + if (!PyObject_HasAttrString(it, "__copy__")) { + copyable = tee_fromiterable(it); + Py_DECREF(it); + if (copyable == NULL) { + Py_DECREF(result); + return NULL; + } + } else + copyable = it; + PyTuple_SET_ITEM(result, 0, copyable); + for (i=1 ; itp_alloc(type, 0); - if (lz == NULL) { - Py_DECREF(it); - Py_DECREF(saved); - return NULL; - } - lz->it = it; - lz->saved = saved; - lz->firstpass = 0; + PyObject *it; + PyObject *iterable; + PyObject *saved; + cycleobject *lz; + + if (type == &cycle_type && !_PyArg_NoKeywords("cycle()", kwds)) + return NULL; + + if (!PyArg_UnpackTuple(args, "cycle", 1, 1, &iterable)) + return NULL; + + /* Get iterator. */ + it = PyObject_GetIter(iterable); + if (it == NULL) + return NULL; + + saved = PyList_New(0); + if (saved == NULL) { + Py_DECREF(it); + return NULL; + } + + /* create cycleobject structure */ + lz = (cycleobject *)type->tp_alloc(type, 0); + if (lz == NULL) { + Py_DECREF(it); + Py_DECREF(saved); + return NULL; + } + lz->it = it; + lz->saved = saved; + lz->firstpass = 0; - return (PyObject *)lz; + return (PyObject *)lz; } static void cycle_dealloc(cycleobject *lz) { - PyObject_GC_UnTrack(lz); - Py_XDECREF(lz->saved); - Py_XDECREF(lz->it); - Py_TYPE(lz)->tp_free(lz); + PyObject_GC_UnTrack(lz); + Py_XDECREF(lz->saved); + Py_XDECREF(lz->it); + Py_TYPE(lz)->tp_free(lz); } static int cycle_traverse(cycleobject *lz, visitproc visit, void *arg) { - Py_VISIT(lz->it); - Py_VISIT(lz->saved); - return 0; + Py_VISIT(lz->it); + Py_VISIT(lz->saved); + return 0; } static PyObject * cycle_next(cycleobject *lz) { - PyObject *item; - PyObject *it; - PyObject *tmp; - - while (1) { - item = PyIter_Next(lz->it); - if (item != NULL) { - if (!lz->firstpass && PyList_Append(lz->saved, item)) { - Py_DECREF(item); - return NULL; - } - return item; - } - if (PyErr_Occurred()) { - if (PyErr_ExceptionMatches(PyExc_StopIteration)) - PyErr_Clear(); - else - return NULL; - } - if (PyList_Size(lz->saved) == 0) - return NULL; - it = PyObject_GetIter(lz->saved); - if (it == NULL) - return NULL; - tmp = lz->it; - lz->it = it; - lz->firstpass = 1; - Py_DECREF(tmp); - } + PyObject *item; + PyObject *it; + PyObject *tmp; + + while (1) { + item = PyIter_Next(lz->it); + if (item != NULL) { + if (!lz->firstpass && PyList_Append(lz->saved, item)) { + Py_DECREF(item); + return NULL; + } + return item; + } + if (PyErr_Occurred()) { + if (PyErr_ExceptionMatches(PyExc_StopIteration)) + PyErr_Clear(); + else + return NULL; + } + if (PyList_Size(lz->saved) == 0) + return NULL; + it = PyObject_GetIter(lz->saved); + if (it == NULL) + return NULL; + tmp = lz->it; + lz->it = it; + lz->firstpass = 1; + Py_DECREF(tmp); + } } PyDoc_STRVAR(cycle_doc, @@ -776,57 +776,57 @@ Then repeat the sequence indefinitely."); static PyTypeObject cycle_type = { - PyVarObject_HEAD_INIT(NULL, 0) - "itertools.cycle", /* tp_name */ - sizeof(cycleobject), /* tp_basicsize */ - 0, /* tp_itemsize */ - /* methods */ - (destructor)cycle_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 | - Py_TPFLAGS_BASETYPE, /* tp_flags */ - cycle_doc, /* tp_doc */ - (traverseproc)cycle_traverse, /* tp_traverse */ - 0, /* tp_clear */ - 0, /* tp_richcompare */ - 0, /* tp_weaklistoffset */ - PyObject_SelfIter, /* tp_iter */ - (iternextfunc)cycle_next, /* tp_iternext */ - 0, /* tp_methods */ - 0, /* tp_members */ - 0, /* tp_getset */ - 0, /* tp_base */ - 0, /* tp_dict */ - 0, /* tp_descr_get */ - 0, /* tp_descr_set */ - 0, /* tp_dictoffset */ - 0, /* tp_init */ - 0, /* tp_alloc */ - cycle_new, /* tp_new */ - PyObject_GC_Del, /* tp_free */ + PyVarObject_HEAD_INIT(NULL, 0) + "itertools.cycle", /* tp_name */ + sizeof(cycleobject), /* tp_basicsize */ + 0, /* tp_itemsize */ + /* methods */ + (destructor)cycle_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 | + Py_TPFLAGS_BASETYPE, /* tp_flags */ + cycle_doc, /* tp_doc */ + (traverseproc)cycle_traverse, /* tp_traverse */ + 0, /* tp_clear */ + 0, /* tp_richcompare */ + 0, /* tp_weaklistoffset */ + PyObject_SelfIter, /* tp_iter */ + (iternextfunc)cycle_next, /* tp_iternext */ + 0, /* tp_methods */ + 0, /* tp_members */ + 0, /* tp_getset */ + 0, /* tp_base */ + 0, /* tp_dict */ + 0, /* tp_descr_get */ + 0, /* tp_descr_set */ + 0, /* tp_dictoffset */ + 0, /* tp_init */ + 0, /* tp_alloc */ + cycle_new, /* tp_new */ + PyObject_GC_Del, /* tp_free */ }; /* dropwhile object **********************************************************/ typedef struct { - PyObject_HEAD - PyObject *func; - PyObject *it; - long start; + PyObject_HEAD + PyObject *func; + PyObject *it; + long start; } dropwhileobject; static PyTypeObject dropwhile_type; @@ -834,81 +834,81 @@ static PyObject * dropwhile_new(PyTypeObject *type, PyObject *args, PyObject *kwds) { - PyObject *func, *seq; - PyObject *it; - dropwhileobject *lz; - - if (type == &dropwhile_type && !_PyArg_NoKeywords("dropwhile()", kwds)) - return NULL; - - if (!PyArg_UnpackTuple(args, "dropwhile", 2, 2, &func, &seq)) - return NULL; - - /* Get iterator. */ - it = PyObject_GetIter(seq); - if (it == NULL) - return NULL; - - /* create dropwhileobject structure */ - lz = (dropwhileobject *)type->tp_alloc(type, 0); - if (lz == NULL) { - Py_DECREF(it); - return NULL; - } - Py_INCREF(func); - lz->func = func; - lz->it = it; - lz->start = 0; + PyObject *func, *seq; + PyObject *it; + dropwhileobject *lz; + + if (type == &dropwhile_type && !_PyArg_NoKeywords("dropwhile()", kwds)) + return NULL; + + if (!PyArg_UnpackTuple(args, "dropwhile", 2, 2, &func, &seq)) + return NULL; + + /* Get iterator. */ + it = PyObject_GetIter(seq); + if (it == NULL) + return NULL; + + /* create dropwhileobject structure */ + lz = (dropwhileobject *)type->tp_alloc(type, 0); + if (lz == NULL) { + Py_DECREF(it); + return NULL; + } + Py_INCREF(func); + lz->func = func; + lz->it = it; + lz->start = 0; - return (PyObject *)lz; + return (PyObject *)lz; } static void dropwhile_dealloc(dropwhileobject *lz) { - PyObject_GC_UnTrack(lz); - Py_XDECREF(lz->func); - Py_XDECREF(lz->it); - Py_TYPE(lz)->tp_free(lz); + PyObject_GC_UnTrack(lz); + Py_XDECREF(lz->func); + Py_XDECREF(lz->it); + Py_TYPE(lz)->tp_free(lz); } static int dropwhile_traverse(dropwhileobject *lz, visitproc visit, void *arg) { - Py_VISIT(lz->it); - Py_VISIT(lz->func); - return 0; + Py_VISIT(lz->it); + Py_VISIT(lz->func); + return 0; } static PyObject * dropwhile_next(dropwhileobject *lz) { - PyObject *item, *good; - PyObject *it = lz->it; - long ok; - PyObject *(*iternext)(PyObject *); - - iternext = *Py_TYPE(it)->tp_iternext; - for (;;) { - item = iternext(it); - if (item == NULL) - return NULL; - if (lz->start == 1) - return item; - - good = PyObject_CallFunctionObjArgs(lz->func, item, NULL); - if (good == NULL) { - Py_DECREF(item); - return NULL; - } - ok = PyObject_IsTrue(good); - Py_DECREF(good); - if (!ok) { - lz->start = 1; - return item; - } - Py_DECREF(item); - } + PyObject *item, *good; + PyObject *it = lz->it; + long ok; + PyObject *(*iternext)(PyObject *); + + iternext = *Py_TYPE(it)->tp_iternext; + for (;;) { + item = iternext(it); + if (item == NULL) + return NULL; + if (lz->start == 1) + return item; + + good = PyObject_CallFunctionObjArgs(lz->func, item, NULL); + if (good == NULL) { + Py_DECREF(item); + return NULL; + } + ok = PyObject_IsTrue(good); + Py_DECREF(good); + if (!ok) { + lz->start = 1; + return item; + } + Py_DECREF(item); + } } PyDoc_STRVAR(dropwhile_doc, @@ -918,57 +918,57 @@ Afterwards, return every element until the iterable is exhausted."); static PyTypeObject dropwhile_type = { - PyVarObject_HEAD_INIT(NULL, 0) - "itertools.dropwhile", /* tp_name */ - sizeof(dropwhileobject), /* tp_basicsize */ - 0, /* tp_itemsize */ - /* methods */ - (destructor)dropwhile_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 | - Py_TPFLAGS_BASETYPE, /* tp_flags */ - dropwhile_doc, /* tp_doc */ - (traverseproc)dropwhile_traverse, /* tp_traverse */ - 0, /* tp_clear */ - 0, /* tp_richcompare */ - 0, /* tp_weaklistoffset */ - PyObject_SelfIter, /* tp_iter */ - (iternextfunc)dropwhile_next, /* tp_iternext */ - 0, /* tp_methods */ - 0, /* tp_members */ - 0, /* tp_getset */ - 0, /* tp_base */ - 0, /* tp_dict */ - 0, /* tp_descr_get */ - 0, /* tp_descr_set */ - 0, /* tp_dictoffset */ - 0, /* tp_init */ - 0, /* tp_alloc */ - dropwhile_new, /* tp_new */ - PyObject_GC_Del, /* tp_free */ + PyVarObject_HEAD_INIT(NULL, 0) + "itertools.dropwhile", /* tp_name */ + sizeof(dropwhileobject), /* tp_basicsize */ + 0, /* tp_itemsize */ + /* methods */ + (destructor)dropwhile_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 | + Py_TPFLAGS_BASETYPE, /* tp_flags */ + dropwhile_doc, /* tp_doc */ + (traverseproc)dropwhile_traverse, /* tp_traverse */ + 0, /* tp_clear */ + 0, /* tp_richcompare */ + 0, /* tp_weaklistoffset */ + PyObject_SelfIter, /* tp_iter */ + (iternextfunc)dropwhile_next, /* tp_iternext */ + 0, /* tp_methods */ + 0, /* tp_members */ + 0, /* tp_getset */ + 0, /* tp_base */ + 0, /* tp_dict */ + 0, /* tp_descr_get */ + 0, /* tp_descr_set */ + 0, /* tp_dictoffset */ + 0, /* tp_init */ + 0, /* tp_alloc */ + dropwhile_new, /* tp_new */ + PyObject_GC_Del, /* tp_free */ }; /* takewhile object **********************************************************/ typedef struct { - PyObject_HEAD - PyObject *func; - PyObject *it; - long stop; + PyObject_HEAD + PyObject *func; + PyObject *it; + long stop; } takewhileobject; static PyTypeObject takewhile_type; @@ -976,78 +976,78 @@ static PyObject * takewhile_new(PyTypeObject *type, PyObject *args, PyObject *kwds) { - PyObject *func, *seq; - PyObject *it; - takewhileobject *lz; - - if (type == &takewhile_type && !_PyArg_NoKeywords("takewhile()", kwds)) - return NULL; - - if (!PyArg_UnpackTuple(args, "takewhile", 2, 2, &func, &seq)) - return NULL; - - /* Get iterator. */ - it = PyObject_GetIter(seq); - if (it == NULL) - return NULL; - - /* create takewhileobject structure */ - lz = (takewhileobject *)type->tp_alloc(type, 0); - if (lz == NULL) { - Py_DECREF(it); - return NULL; - } - Py_INCREF(func); - lz->func = func; - lz->it = it; - lz->stop = 0; + PyObject *func, *seq; + PyObject *it; + takewhileobject *lz; + + if (type == &takewhile_type && !_PyArg_NoKeywords("takewhile()", kwds)) + return NULL; + + if (!PyArg_UnpackTuple(args, "takewhile", 2, 2, &func, &seq)) + return NULL; + + /* Get iterator. */ + it = PyObject_GetIter(seq); + if (it == NULL) + return NULL; + + /* create takewhileobject structure */ + lz = (takewhileobject *)type->tp_alloc(type, 0); + if (lz == NULL) { + Py_DECREF(it); + return NULL; + } + Py_INCREF(func); + lz->func = func; + lz->it = it; + lz->stop = 0; - return (PyObject *)lz; + return (PyObject *)lz; } static void takewhile_dealloc(takewhileobject *lz) { - PyObject_GC_UnTrack(lz); - Py_XDECREF(lz->func); - Py_XDECREF(lz->it); - Py_TYPE(lz)->tp_free(lz); + PyObject_GC_UnTrack(lz); + Py_XDECREF(lz->func); + Py_XDECREF(lz->it); + Py_TYPE(lz)->tp_free(lz); } static int takewhile_traverse(takewhileobject *lz, visitproc visit, void *arg) { - Py_VISIT(lz->it); - Py_VISIT(lz->func); - return 0; + Py_VISIT(lz->it); + Py_VISIT(lz->func); + return 0; } static PyObject * takewhile_next(takewhileobject *lz) { - PyObject *item, *good; - PyObject *it = lz->it; - long ok; - - if (lz->stop == 1) - return NULL; - - item = (*Py_TYPE(it)->tp_iternext)(it); - if (item == NULL) - return NULL; - - good = PyObject_CallFunctionObjArgs(lz->func, item, NULL); - if (good == NULL) { - Py_DECREF(item); - return NULL; - } - ok = PyObject_IsTrue(good); - Py_DECREF(good); - if (ok) - return item; - Py_DECREF(item); - lz->stop = 1; - return NULL; + PyObject *item, *good; + PyObject *it = lz->it; + long ok; + + if (lz->stop == 1) + return NULL; + + item = (*Py_TYPE(it)->tp_iternext)(it); + if (item == NULL) + return NULL; + + good = PyObject_CallFunctionObjArgs(lz->func, item, NULL); + if (good == NULL) { + Py_DECREF(item); + return NULL; + } + ok = PyObject_IsTrue(good); + Py_DECREF(good); + if (ok) + return item; + Py_DECREF(item); + lz->stop = 1; + return NULL; } PyDoc_STRVAR(takewhile_doc, @@ -1057,59 +1057,59 @@ predicate evaluates to true for each entry."); static PyTypeObject takewhile_type = { - PyVarObject_HEAD_INIT(NULL, 0) - "itertools.takewhile", /* tp_name */ - sizeof(takewhileobject), /* tp_basicsize */ - 0, /* tp_itemsize */ - /* methods */ - (destructor)takewhile_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 | - Py_TPFLAGS_BASETYPE, /* tp_flags */ - takewhile_doc, /* tp_doc */ - (traverseproc)takewhile_traverse, /* tp_traverse */ - 0, /* tp_clear */ - 0, /* tp_richcompare */ - 0, /* tp_weaklistoffset */ - PyObject_SelfIter, /* tp_iter */ - (iternextfunc)takewhile_next, /* tp_iternext */ - 0, /* tp_methods */ - 0, /* tp_members */ - 0, /* tp_getset */ - 0, /* tp_base */ - 0, /* tp_dict */ - 0, /* tp_descr_get */ - 0, /* tp_descr_set */ - 0, /* tp_dictoffset */ - 0, /* tp_init */ - 0, /* tp_alloc */ - takewhile_new, /* tp_new */ - PyObject_GC_Del, /* tp_free */ + PyVarObject_HEAD_INIT(NULL, 0) + "itertools.takewhile", /* tp_name */ + sizeof(takewhileobject), /* tp_basicsize */ + 0, /* tp_itemsize */ + /* methods */ + (destructor)takewhile_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 | + Py_TPFLAGS_BASETYPE, /* tp_flags */ + takewhile_doc, /* tp_doc */ + (traverseproc)takewhile_traverse, /* tp_traverse */ + 0, /* tp_clear */ + 0, /* tp_richcompare */ + 0, /* tp_weaklistoffset */ + PyObject_SelfIter, /* tp_iter */ + (iternextfunc)takewhile_next, /* tp_iternext */ + 0, /* tp_methods */ + 0, /* tp_members */ + 0, /* tp_getset */ + 0, /* tp_base */ + 0, /* tp_dict */ + 0, /* tp_descr_get */ + 0, /* tp_descr_set */ + 0, /* tp_dictoffset */ + 0, /* tp_init */ + 0, /* tp_alloc */ + takewhile_new, /* tp_new */ + PyObject_GC_Del, /* tp_free */ }; /* islice object ************************************************************/ typedef struct { - PyObject_HEAD - PyObject *it; - Py_ssize_t next; - Py_ssize_t stop; - Py_ssize_t step; - Py_ssize_t cnt; + PyObject_HEAD + PyObject *it; + Py_ssize_t next; + Py_ssize_t stop; + Py_ssize_t step; + Py_ssize_t cnt; } isliceobject; static PyTypeObject islice_type; @@ -1117,126 +1117,126 @@ static PyObject * islice_new(PyTypeObject *type, PyObject *args, PyObject *kwds) { - PyObject *seq; - Py_ssize_t start=0, stop=-1, step=1; - PyObject *it, *a1=NULL, *a2=NULL, *a3=NULL; - Py_ssize_t numargs; - isliceobject *lz; - - if (type == &islice_type && !_PyArg_NoKeywords("islice()", kwds)) - return NULL; - - if (!PyArg_UnpackTuple(args, "islice", 2, 4, &seq, &a1, &a2, &a3)) - return NULL; - - numargs = PyTuple_Size(args); - if (numargs == 2) { - if (a1 != Py_None) { - stop = PyLong_AsSsize_t(a1); - if (stop == -1) { - if (PyErr_Occurred()) - PyErr_Clear(); - PyErr_SetString(PyExc_ValueError, - "Stop argument for islice() must be None or an integer: 0 <= x <= sys.maxsize."); - return NULL; - } - } - } else { - if (a1 != Py_None) - start = PyLong_AsSsize_t(a1); - if (start == -1 && PyErr_Occurred()) - PyErr_Clear(); - if (a2 != Py_None) { - stop = PyLong_AsSsize_t(a2); - if (stop == -1) { - if (PyErr_Occurred()) - PyErr_Clear(); - PyErr_SetString(PyExc_ValueError, - "Stop argument for islice() must be None or an integer: 0 <= x <= sys.maxsize."); - return NULL; - } - } - } - if (start<0 || stop<-1) { - PyErr_SetString(PyExc_ValueError, - "Indices for islice() must be None or an integer: 0 <= x <= sys.maxsize."); - return NULL; - } - - if (a3 != NULL) { - if (a3 != Py_None) - step = PyLong_AsSsize_t(a3); - if (step == -1 && PyErr_Occurred()) - PyErr_Clear(); - } - if (step<1) { - PyErr_SetString(PyExc_ValueError, - "Step for islice() must be a positive integer or None."); - return NULL; - } - - /* Get iterator. */ - it = PyObject_GetIter(seq); - if (it == NULL) - return NULL; - - /* create isliceobject structure */ - lz = (isliceobject *)type->tp_alloc(type, 0); - if (lz == NULL) { - Py_DECREF(it); - return NULL; - } - lz->it = it; - lz->next = start; - lz->stop = stop; - lz->step = step; - lz->cnt = 0L; + PyObject *seq; + Py_ssize_t start=0, stop=-1, step=1; + PyObject *it, *a1=NULL, *a2=NULL, *a3=NULL; + Py_ssize_t numargs; + isliceobject *lz; + + if (type == &islice_type && !_PyArg_NoKeywords("islice()", kwds)) + return NULL; + + if (!PyArg_UnpackTuple(args, "islice", 2, 4, &seq, &a1, &a2, &a3)) + return NULL; + + numargs = PyTuple_Size(args); + if (numargs == 2) { + if (a1 != Py_None) { + stop = PyLong_AsSsize_t(a1); + if (stop == -1) { + if (PyErr_Occurred()) + PyErr_Clear(); + PyErr_SetString(PyExc_ValueError, + "Stop argument for islice() must be None or an integer: 0 <= x <= sys.maxsize."); + return NULL; + } + } + } else { + if (a1 != Py_None) + start = PyLong_AsSsize_t(a1); + if (start == -1 && PyErr_Occurred()) + PyErr_Clear(); + if (a2 != Py_None) { + stop = PyLong_AsSsize_t(a2); + if (stop == -1) { + if (PyErr_Occurred()) + PyErr_Clear(); + PyErr_SetString(PyExc_ValueError, + "Stop argument for islice() must be None or an integer: 0 <= x <= sys.maxsize."); + return NULL; + } + } + } + if (start<0 || stop<-1) { + PyErr_SetString(PyExc_ValueError, + "Indices for islice() must be None or an integer: 0 <= x <= sys.maxsize."); + return NULL; + } + + if (a3 != NULL) { + if (a3 != Py_None) + step = PyLong_AsSsize_t(a3); + if (step == -1 && PyErr_Occurred()) + PyErr_Clear(); + } + if (step<1) { + PyErr_SetString(PyExc_ValueError, + "Step for islice() must be a positive integer or None."); + return NULL; + } + + /* Get iterator. */ + it = PyObject_GetIter(seq); + if (it == NULL) + return NULL; + + /* create isliceobject structure */ + lz = (isliceobject *)type->tp_alloc(type, 0); + if (lz == NULL) { + Py_DECREF(it); + return NULL; + } + lz->it = it; + lz->next = start; + lz->stop = stop; + lz->step = step; + lz->cnt = 0L; - return (PyObject *)lz; + return (PyObject *)lz; } static void islice_dealloc(isliceobject *lz) { - PyObject_GC_UnTrack(lz); - Py_XDECREF(lz->it); - Py_TYPE(lz)->tp_free(lz); + PyObject_GC_UnTrack(lz); + Py_XDECREF(lz->it); + Py_TYPE(lz)->tp_free(lz); } static int islice_traverse(isliceobject *lz, visitproc visit, void *arg) { - Py_VISIT(lz->it); - return 0; + Py_VISIT(lz->it); + return 0; } static PyObject * islice_next(isliceobject *lz) { - PyObject *item; - PyObject *it = lz->it; - Py_ssize_t oldnext; - PyObject *(*iternext)(PyObject *); - - iternext = *Py_TYPE(it)->tp_iternext; - while (lz->cnt < lz->next) { - item = iternext(it); - if (item == NULL) - return NULL; - Py_DECREF(item); - lz->cnt++; - } - if (lz->stop != -1 && lz->cnt >= lz->stop) - return NULL; - item = iternext(it); - if (item == NULL) - return NULL; - lz->cnt++; - oldnext = lz->next; - lz->next += lz->step; - if (lz->next < oldnext) /* Check for overflow */ - lz->next = lz->stop; - return item; + PyObject *item; + PyObject *it = lz->it; + Py_ssize_t oldnext; + PyObject *(*iternext)(PyObject *); + + iternext = *Py_TYPE(it)->tp_iternext; + while (lz->cnt < lz->next) { + item = iternext(it); + if (item == NULL) + return NULL; + Py_DECREF(item); + lz->cnt++; + } + if (lz->stop != -1 && lz->cnt >= lz->stop) + return NULL; + item = iternext(it); + if (item == NULL) + return NULL; + lz->cnt++; + oldnext = lz->next; + lz->next += lz->step; + if (lz->next < oldnext) /* Check for overflow */ + lz->next = lz->stop; + return item; } PyDoc_STRVAR(islice_doc, @@ -1250,56 +1250,56 @@ but returns an iterator."); static PyTypeObject islice_type = { - PyVarObject_HEAD_INIT(NULL, 0) - "itertools.islice", /* tp_name */ - sizeof(isliceobject), /* tp_basicsize */ - 0, /* tp_itemsize */ - /* methods */ - (destructor)islice_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 | - Py_TPFLAGS_BASETYPE, /* tp_flags */ - islice_doc, /* tp_doc */ - (traverseproc)islice_traverse, /* tp_traverse */ - 0, /* tp_clear */ - 0, /* tp_richcompare */ - 0, /* tp_weaklistoffset */ - PyObject_SelfIter, /* tp_iter */ - (iternextfunc)islice_next, /* tp_iternext */ - 0, /* tp_methods */ - 0, /* tp_members */ - 0, /* tp_getset */ - 0, /* tp_base */ - 0, /* tp_dict */ - 0, /* tp_descr_get */ - 0, /* tp_descr_set */ - 0, /* tp_dictoffset */ - 0, /* tp_init */ - 0, /* tp_alloc */ - islice_new, /* tp_new */ - PyObject_GC_Del, /* tp_free */ + PyVarObject_HEAD_INIT(NULL, 0) + "itertools.islice", /* tp_name */ + sizeof(isliceobject), /* tp_basicsize */ + 0, /* tp_itemsize */ + /* methods */ + (destructor)islice_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 | + Py_TPFLAGS_BASETYPE, /* tp_flags */ + islice_doc, /* tp_doc */ + (traverseproc)islice_traverse, /* tp_traverse */ + 0, /* tp_clear */ + 0, /* tp_richcompare */ + 0, /* tp_weaklistoffset */ + PyObject_SelfIter, /* tp_iter */ + (iternextfunc)islice_next, /* tp_iternext */ + 0, /* tp_methods */ + 0, /* tp_members */ + 0, /* tp_getset */ + 0, /* tp_base */ + 0, /* tp_dict */ + 0, /* tp_descr_get */ + 0, /* tp_descr_set */ + 0, /* tp_dictoffset */ + 0, /* tp_init */ + 0, /* tp_alloc */ + islice_new, /* tp_new */ + PyObject_GC_Del, /* tp_free */ }; /* starmap object ************************************************************/ typedef struct { - PyObject_HEAD - PyObject *func; - PyObject *it; + PyObject_HEAD + PyObject *func; + PyObject *it; } starmapobject; static PyTypeObject starmap_type; @@ -1307,71 +1307,71 @@ static PyObject * starmap_new(PyTypeObject *type, PyObject *args, PyObject *kwds) { - PyObject *func, *seq; - PyObject *it; - starmapobject *lz; - - if (type == &starmap_type && !_PyArg_NoKeywords("starmap()", kwds)) - return NULL; - - if (!PyArg_UnpackTuple(args, "starmap", 2, 2, &func, &seq)) - return NULL; - - /* Get iterator. */ - it = PyObject_GetIter(seq); - if (it == NULL) - return NULL; - - /* create starmapobject structure */ - lz = (starmapobject *)type->tp_alloc(type, 0); - if (lz == NULL) { - Py_DECREF(it); - return NULL; - } - Py_INCREF(func); - lz->func = func; - lz->it = it; + PyObject *func, *seq; + PyObject *it; + starmapobject *lz; + + if (type == &starmap_type && !_PyArg_NoKeywords("starmap()", kwds)) + return NULL; + + if (!PyArg_UnpackTuple(args, "starmap", 2, 2, &func, &seq)) + return NULL; + + /* Get iterator. */ + it = PyObject_GetIter(seq); + if (it == NULL) + return NULL; + + /* create starmapobject structure */ + lz = (starmapobject *)type->tp_alloc(type, 0); + if (lz == NULL) { + Py_DECREF(it); + return NULL; + } + Py_INCREF(func); + lz->func = func; + lz->it = it; - return (PyObject *)lz; + return (PyObject *)lz; } static void starmap_dealloc(starmapobject *lz) { - PyObject_GC_UnTrack(lz); - Py_XDECREF(lz->func); - Py_XDECREF(lz->it); - Py_TYPE(lz)->tp_free(lz); + PyObject_GC_UnTrack(lz); + Py_XDECREF(lz->func); + Py_XDECREF(lz->it); + Py_TYPE(lz)->tp_free(lz); } static int starmap_traverse(starmapobject *lz, visitproc visit, void *arg) { - Py_VISIT(lz->it); - Py_VISIT(lz->func); - return 0; + Py_VISIT(lz->it); + Py_VISIT(lz->func); + return 0; } static PyObject * starmap_next(starmapobject *lz) { - PyObject *args; - PyObject *result; - PyObject *it = lz->it; - - args = (*Py_TYPE(it)->tp_iternext)(it); - if (args == NULL) - return NULL; - if (!PyTuple_CheckExact(args)) { - PyObject *newargs = PySequence_Tuple(args); - Py_DECREF(args); - if (newargs == NULL) - return NULL; - args = newargs; - } - result = PyObject_Call(lz->func, args, NULL); - Py_DECREF(args); - return result; + PyObject *args; + PyObject *result; + PyObject *it = lz->it; + + args = (*Py_TYPE(it)->tp_iternext)(it); + if (args == NULL) + return NULL; + if (!PyTuple_CheckExact(args)) { + PyObject *newargs = PySequence_Tuple(args); + Py_DECREF(args); + if (newargs == NULL) + return NULL; + args = newargs; + } + result = PyObject_Call(lz->func, args, NULL); + Py_DECREF(args); + return result; } PyDoc_STRVAR(starmap_doc, @@ -1381,152 +1381,152 @@ with a argument tuple taken from the given sequence."); static PyTypeObject starmap_type = { - PyVarObject_HEAD_INIT(NULL, 0) - "itertools.starmap", /* tp_name */ - sizeof(starmapobject), /* tp_basicsize */ - 0, /* tp_itemsize */ - /* methods */ - (destructor)starmap_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 | - Py_TPFLAGS_BASETYPE, /* tp_flags */ - starmap_doc, /* tp_doc */ - (traverseproc)starmap_traverse, /* tp_traverse */ - 0, /* tp_clear */ - 0, /* tp_richcompare */ - 0, /* tp_weaklistoffset */ - PyObject_SelfIter, /* tp_iter */ - (iternextfunc)starmap_next, /* tp_iternext */ - 0, /* tp_methods */ - 0, /* tp_members */ - 0, /* tp_getset */ - 0, /* tp_base */ - 0, /* tp_dict */ - 0, /* tp_descr_get */ - 0, /* tp_descr_set */ - 0, /* tp_dictoffset */ - 0, /* tp_init */ - 0, /* tp_alloc */ - starmap_new, /* tp_new */ - PyObject_GC_Del, /* tp_free */ + PyVarObject_HEAD_INIT(NULL, 0) + "itertools.starmap", /* tp_name */ + sizeof(starmapobject), /* tp_basicsize */ + 0, /* tp_itemsize */ + /* methods */ + (destructor)starmap_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 | + Py_TPFLAGS_BASETYPE, /* tp_flags */ + starmap_doc, /* tp_doc */ + (traverseproc)starmap_traverse, /* tp_traverse */ + 0, /* tp_clear */ + 0, /* tp_richcompare */ + 0, /* tp_weaklistoffset */ + PyObject_SelfIter, /* tp_iter */ + (iternextfunc)starmap_next, /* tp_iternext */ + 0, /* tp_methods */ + 0, /* tp_members */ + 0, /* tp_getset */ + 0, /* tp_base */ + 0, /* tp_dict */ + 0, /* tp_descr_get */ + 0, /* tp_descr_set */ + 0, /* tp_dictoffset */ + 0, /* tp_init */ + 0, /* tp_alloc */ + starmap_new, /* tp_new */ + PyObject_GC_Del, /* tp_free */ }; /* chain object ************************************************************/ typedef struct { - PyObject_HEAD - PyObject *source; /* Iterator over input iterables */ - PyObject *active; /* Currently running input iterator */ + PyObject_HEAD + PyObject *source; /* Iterator over input iterables */ + PyObject *active; /* Currently running input iterator */ } chainobject; static PyTypeObject chain_type; -static PyObject * +static PyObject * chain_new_internal(PyTypeObject *type, PyObject *source) { - chainobject *lz; + chainobject *lz; - lz = (chainobject *)type->tp_alloc(type, 0); - if (lz == NULL) { - Py_DECREF(source); - return NULL; - } - - lz->source = source; - lz->active = NULL; - return (PyObject *)lz; + lz = (chainobject *)type->tp_alloc(type, 0); + if (lz == NULL) { + Py_DECREF(source); + return NULL; + } + + lz->source = source; + lz->active = NULL; + return (PyObject *)lz; } static PyObject * chain_new(PyTypeObject *type, PyObject *args, PyObject *kwds) { - PyObject *source; + PyObject *source; + + if (type == &chain_type && !_PyArg_NoKeywords("chain()", kwds)) + return NULL; - if (type == &chain_type && !_PyArg_NoKeywords("chain()", kwds)) - return NULL; - - source = PyObject_GetIter(args); - if (source == NULL) - return NULL; + source = PyObject_GetIter(args); + if (source == NULL) + return NULL; - return chain_new_internal(type, source); + return chain_new_internal(type, source); } static PyObject * chain_new_from_iterable(PyTypeObject *type, PyObject *arg) { - PyObject *source; - - source = PyObject_GetIter(arg); - if (source == NULL) - return NULL; + PyObject *source; + + source = PyObject_GetIter(arg); + if (source == NULL) + return NULL; - return chain_new_internal(type, source); + return chain_new_internal(type, source); } static void chain_dealloc(chainobject *lz) { - PyObject_GC_UnTrack(lz); - Py_XDECREF(lz->active); - Py_XDECREF(lz->source); - Py_TYPE(lz)->tp_free(lz); + PyObject_GC_UnTrack(lz); + Py_XDECREF(lz->active); + Py_XDECREF(lz->source); + Py_TYPE(lz)->tp_free(lz); } static int chain_traverse(chainobject *lz, visitproc visit, void *arg) { - Py_VISIT(lz->source); - Py_VISIT(lz->active); - return 0; + Py_VISIT(lz->source); + Py_VISIT(lz->active); + return 0; } static PyObject * chain_next(chainobject *lz) { - PyObject *item; + PyObject *item; - if (lz->source == NULL) - return NULL; /* already stopped */ + if (lz->source == NULL) + return NULL; /* already stopped */ - if (lz->active == NULL) { - PyObject *iterable = PyIter_Next(lz->source); - if (iterable == NULL) { - Py_CLEAR(lz->source); - return NULL; /* no more input sources */ - } - lz->active = PyObject_GetIter(iterable); - Py_DECREF(iterable); - if (lz->active == NULL) { - Py_CLEAR(lz->source); - return NULL; /* input not iterable */ - } - } - item = PyIter_Next(lz->active); - if (item != NULL) - return item; - if (PyErr_Occurred()) { - if (PyErr_ExceptionMatches(PyExc_StopIteration)) - PyErr_Clear(); - else - return NULL; /* input raised an exception */ - } - Py_CLEAR(lz->active); - return chain_next(lz); /* recurse and use next active */ + if (lz->active == NULL) { + PyObject *iterable = PyIter_Next(lz->source); + if (iterable == NULL) { + Py_CLEAR(lz->source); + return NULL; /* no more input sources */ + } + lz->active = PyObject_GetIter(iterable); + Py_DECREF(iterable); + if (lz->active == NULL) { + Py_CLEAR(lz->source); + return NULL; /* input not iterable */ + } + } + item = PyIter_Next(lz->active); + if (item != NULL) + return item; + if (PyErr_Occurred()) { + if (PyErr_ExceptionMatches(PyExc_StopIteration)) + PyErr_Clear(); + else + return NULL; /* input raised an exception */ + } + Py_CLEAR(lz->active); + return chain_next(lz); /* recurse and use next active */ } PyDoc_STRVAR(chain_doc, @@ -1543,64 +1543,64 @@ that evaluates lazily."); static PyMethodDef chain_methods[] = { - {"from_iterable", (PyCFunction) chain_new_from_iterable, METH_O | METH_CLASS, - chain_from_iterable_doc}, - {NULL, NULL} /* sentinel */ + {"from_iterable", (PyCFunction) chain_new_from_iterable, METH_O | METH_CLASS, + chain_from_iterable_doc}, + {NULL, NULL} /* sentinel */ }; static PyTypeObject chain_type = { - PyVarObject_HEAD_INIT(NULL, 0) - "itertools.chain", /* tp_name */ - sizeof(chainobject), /* tp_basicsize */ - 0, /* tp_itemsize */ - /* methods */ - (destructor)chain_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 | - Py_TPFLAGS_BASETYPE, /* tp_flags */ - chain_doc, /* tp_doc */ - (traverseproc)chain_traverse, /* tp_traverse */ - 0, /* tp_clear */ - 0, /* tp_richcompare */ - 0, /* tp_weaklistoffset */ - PyObject_SelfIter, /* tp_iter */ - (iternextfunc)chain_next, /* tp_iternext */ - chain_methods, /* tp_methods */ - 0, /* tp_members */ - 0, /* tp_getset */ - 0, /* tp_base */ - 0, /* tp_dict */ - 0, /* tp_descr_get */ - 0, /* tp_descr_set */ - 0, /* tp_dictoffset */ - 0, /* tp_init */ - 0, /* tp_alloc */ - chain_new, /* tp_new */ - PyObject_GC_Del, /* tp_free */ + PyVarObject_HEAD_INIT(NULL, 0) + "itertools.chain", /* tp_name */ + sizeof(chainobject), /* tp_basicsize */ + 0, /* tp_itemsize */ + /* methods */ + (destructor)chain_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 | + Py_TPFLAGS_BASETYPE, /* tp_flags */ + chain_doc, /* tp_doc */ + (traverseproc)chain_traverse, /* tp_traverse */ + 0, /* tp_clear */ + 0, /* tp_richcompare */ + 0, /* tp_weaklistoffset */ + PyObject_SelfIter, /* tp_iter */ + (iternextfunc)chain_next, /* tp_iternext */ + chain_methods, /* tp_methods */ + 0, /* tp_members */ + 0, /* tp_getset */ + 0, /* tp_base */ + 0, /* tp_dict */ + 0, /* tp_descr_get */ + 0, /* tp_descr_set */ + 0, /* tp_dictoffset */ + 0, /* tp_init */ + 0, /* tp_alloc */ + chain_new, /* tp_new */ + PyObject_GC_Del, /* tp_free */ }; /* product object ************************************************************/ typedef struct { - PyObject_HEAD - PyObject *pools; /* tuple of pool tuples */ - Py_ssize_t *indices; /* one index per pool */ - PyObject *result; /* most recently returned result tuple */ - int stopped; /* set to 1 when the product iterator is exhausted */ + PyObject_HEAD + PyObject *pools; /* tuple of pool tuples */ + Py_ssize_t *indices; /* one index per pool */ + PyObject *result; /* most recently returned result tuple */ + int stopped; /* set to 1 when the product iterator is exhausted */ } productobject; static PyTypeObject product_type; @@ -1608,181 +1608,181 @@ static PyObject * product_new(PyTypeObject *type, PyObject *args, PyObject *kwds) { - productobject *lz; - Py_ssize_t nargs, npools, repeat=1; - PyObject *pools = NULL; - Py_ssize_t *indices = NULL; - Py_ssize_t i; - - if (kwds != NULL) { - char *kwlist[] = {"repeat", 0}; - PyObject *tmpargs = PyTuple_New(0); - if (tmpargs == NULL) - return NULL; - if (!PyArg_ParseTupleAndKeywords(tmpargs, kwds, "|n:product", kwlist, &repeat)) { - Py_DECREF(tmpargs); - return NULL; - } - Py_DECREF(tmpargs); - if (repeat < 0) { - PyErr_SetString(PyExc_ValueError, - "repeat argument cannot be negative"); - return NULL; - } - } - - assert(PyTuple_Check(args)); - nargs = (repeat == 0) ? 0 : PyTuple_GET_SIZE(args); - npools = nargs * repeat; - - indices = PyMem_Malloc(npools * sizeof(Py_ssize_t)); - if (indices == NULL) { - PyErr_NoMemory(); - goto error; - } - - pools = PyTuple_New(npools); - if (pools == NULL) - goto error; - - for (i=0; i < nargs ; ++i) { - PyObject *item = PyTuple_GET_ITEM(args, i); - PyObject *pool = PySequence_Tuple(item); - if (pool == NULL) - goto error; - PyTuple_SET_ITEM(pools, i, pool); - indices[i] = 0; - } - for ( ; i < npools; ++i) { - PyObject *pool = PyTuple_GET_ITEM(pools, i - nargs); - Py_INCREF(pool); - PyTuple_SET_ITEM(pools, i, pool); - indices[i] = 0; - } - - /* create productobject structure */ - lz = (productobject *)type->tp_alloc(type, 0); - if (lz == NULL) - goto error; - - lz->pools = pools; - lz->indices = indices; - lz->result = NULL; - lz->stopped = 0; + productobject *lz; + Py_ssize_t nargs, npools, repeat=1; + PyObject *pools = NULL; + Py_ssize_t *indices = NULL; + Py_ssize_t i; + + if (kwds != NULL) { + char *kwlist[] = {"repeat", 0}; + PyObject *tmpargs = PyTuple_New(0); + if (tmpargs == NULL) + return NULL; + if (!PyArg_ParseTupleAndKeywords(tmpargs, kwds, "|n:product", kwlist, &repeat)) { + Py_DECREF(tmpargs); + return NULL; + } + Py_DECREF(tmpargs); + if (repeat < 0) { + PyErr_SetString(PyExc_ValueError, + "repeat argument cannot be negative"); + return NULL; + } + } + + assert(PyTuple_Check(args)); + nargs = (repeat == 0) ? 0 : PyTuple_GET_SIZE(args); + npools = nargs * repeat; + + indices = PyMem_Malloc(npools * sizeof(Py_ssize_t)); + if (indices == NULL) { + PyErr_NoMemory(); + goto error; + } + + pools = PyTuple_New(npools); + if (pools == NULL) + goto error; + + for (i=0; i < nargs ; ++i) { + PyObject *item = PyTuple_GET_ITEM(args, i); + PyObject *pool = PySequence_Tuple(item); + if (pool == NULL) + goto error; + PyTuple_SET_ITEM(pools, i, pool); + indices[i] = 0; + } + for ( ; i < npools; ++i) { + PyObject *pool = PyTuple_GET_ITEM(pools, i - nargs); + Py_INCREF(pool); + PyTuple_SET_ITEM(pools, i, pool); + indices[i] = 0; + } + + /* create productobject structure */ + lz = (productobject *)type->tp_alloc(type, 0); + if (lz == NULL) + goto error; + + lz->pools = pools; + lz->indices = indices; + lz->result = NULL; + lz->stopped = 0; - return (PyObject *)lz; + return (PyObject *)lz; error: - if (indices != NULL) - PyMem_Free(indices); - Py_XDECREF(pools); - return NULL; + if (indices != NULL) + PyMem_Free(indices); + Py_XDECREF(pools); + return NULL; } static void product_dealloc(productobject *lz) { - PyObject_GC_UnTrack(lz); - Py_XDECREF(lz->pools); - Py_XDECREF(lz->result); - if (lz->indices != NULL) - PyMem_Free(lz->indices); - Py_TYPE(lz)->tp_free(lz); + PyObject_GC_UnTrack(lz); + Py_XDECREF(lz->pools); + Py_XDECREF(lz->result); + if (lz->indices != NULL) + PyMem_Free(lz->indices); + Py_TYPE(lz)->tp_free(lz); } static int product_traverse(productobject *lz, visitproc visit, void *arg) { - Py_VISIT(lz->pools); - Py_VISIT(lz->result); - return 0; + Py_VISIT(lz->pools); + Py_VISIT(lz->result); + return 0; } static PyObject * product_next(productobject *lz) { - PyObject *pool; - PyObject *elem; - PyObject *oldelem; - PyObject *pools = lz->pools; - PyObject *result = lz->result; - Py_ssize_t npools = PyTuple_GET_SIZE(pools); - Py_ssize_t i; - - if (lz->stopped) - return NULL; - - if (result == NULL) { - /* On the first pass, return an initial tuple filled with the - first element from each pool. */ - result = PyTuple_New(npools); - if (result == NULL) - goto empty; - lz->result = result; - for (i=0; i < npools; i++) { - pool = PyTuple_GET_ITEM(pools, i); - if (PyTuple_GET_SIZE(pool) == 0) - goto empty; - elem = PyTuple_GET_ITEM(pool, 0); - Py_INCREF(elem); - PyTuple_SET_ITEM(result, i, elem); - } - } else { - Py_ssize_t *indices = lz->indices; - - /* Copy the previous result tuple or re-use it if available */ - if (Py_REFCNT(result) > 1) { - PyObject *old_result = result; - result = PyTuple_New(npools); - if (result == NULL) - goto empty; - lz->result = result; - for (i=0; i < npools; i++) { - elem = PyTuple_GET_ITEM(old_result, i); - Py_INCREF(elem); - PyTuple_SET_ITEM(result, i, elem); - } - Py_DECREF(old_result); - } - /* Now, we've got the only copy so we can update it in-place */ - assert (npools==0 || Py_REFCNT(result) == 1); - - /* Update the pool indices right-to-left. Only advance to the - next pool when the previous one rolls-over */ - for (i=npools-1 ; i >= 0 ; i--) { - pool = PyTuple_GET_ITEM(pools, i); - indices[i]++; - if (indices[i] == PyTuple_GET_SIZE(pool)) { - /* Roll-over and advance to next pool */ - indices[i] = 0; - elem = PyTuple_GET_ITEM(pool, 0); - Py_INCREF(elem); - oldelem = PyTuple_GET_ITEM(result, i); - PyTuple_SET_ITEM(result, i, elem); - Py_DECREF(oldelem); - } else { - /* No rollover. Just increment and stop here. */ - elem = PyTuple_GET_ITEM(pool, indices[i]); - Py_INCREF(elem); - oldelem = PyTuple_GET_ITEM(result, i); - PyTuple_SET_ITEM(result, i, elem); - Py_DECREF(oldelem); - break; - } - } - - /* If i is negative, then the indices have all rolled-over - and we're done. */ - if (i < 0) - goto empty; - } + PyObject *pool; + PyObject *elem; + PyObject *oldelem; + PyObject *pools = lz->pools; + PyObject *result = lz->result; + Py_ssize_t npools = PyTuple_GET_SIZE(pools); + Py_ssize_t i; + + if (lz->stopped) + return NULL; + + if (result == NULL) { + /* On the first pass, return an initial tuple filled with the + first element from each pool. */ + result = PyTuple_New(npools); + if (result == NULL) + goto empty; + lz->result = result; + for (i=0; i < npools; i++) { + pool = PyTuple_GET_ITEM(pools, i); + if (PyTuple_GET_SIZE(pool) == 0) + goto empty; + elem = PyTuple_GET_ITEM(pool, 0); + Py_INCREF(elem); + PyTuple_SET_ITEM(result, i, elem); + } + } else { + Py_ssize_t *indices = lz->indices; + + /* Copy the previous result tuple or re-use it if available */ + if (Py_REFCNT(result) > 1) { + PyObject *old_result = result; + result = PyTuple_New(npools); + if (result == NULL) + goto empty; + lz->result = result; + for (i=0; i < npools; i++) { + elem = PyTuple_GET_ITEM(old_result, i); + Py_INCREF(elem); + PyTuple_SET_ITEM(result, i, elem); + } + Py_DECREF(old_result); + } + /* Now, we've got the only copy so we can update it in-place */ + assert (npools==0 || Py_REFCNT(result) == 1); + + /* Update the pool indices right-to-left. Only advance to the + next pool when the previous one rolls-over */ + for (i=npools-1 ; i >= 0 ; i--) { + pool = PyTuple_GET_ITEM(pools, i); + indices[i]++; + if (indices[i] == PyTuple_GET_SIZE(pool)) { + /* Roll-over and advance to next pool */ + indices[i] = 0; + elem = PyTuple_GET_ITEM(pool, 0); + Py_INCREF(elem); + oldelem = PyTuple_GET_ITEM(result, i); + PyTuple_SET_ITEM(result, i, elem); + Py_DECREF(oldelem); + } else { + /* No rollover. Just increment and stop here. */ + elem = PyTuple_GET_ITEM(pool, indices[i]); + Py_INCREF(elem); + oldelem = PyTuple_GET_ITEM(result, i); + PyTuple_SET_ITEM(result, i, elem); + Py_DECREF(oldelem); + break; + } + } - Py_INCREF(result); - return result; + /* If i is negative, then the indices have all rolled-over + and we're done. */ + if (i < 0) + goto empty; + } + + Py_INCREF(result); + return result; empty: - lz->stopped = 1; - return NULL; + lz->stopped = 1; + return NULL; } PyDoc_STRVAR(product_doc, @@ -1800,59 +1800,59 @@ product((0,1), (0,1), (0,1)) --> (0,0,0) (0,0,1) (0,1,0) (0,1,1) (1,0,0) ..."); static PyTypeObject product_type = { - PyVarObject_HEAD_INIT(NULL, 0) - "itertools.product", /* tp_name */ - sizeof(productobject), /* tp_basicsize */ - 0, /* tp_itemsize */ - /* methods */ - (destructor)product_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 | - Py_TPFLAGS_BASETYPE, /* tp_flags */ - product_doc, /* tp_doc */ - (traverseproc)product_traverse, /* tp_traverse */ - 0, /* tp_clear */ - 0, /* tp_richcompare */ - 0, /* tp_weaklistoffset */ - PyObject_SelfIter, /* tp_iter */ - (iternextfunc)product_next, /* tp_iternext */ - 0, /* tp_methods */ - 0, /* tp_members */ - 0, /* tp_getset */ - 0, /* tp_base */ - 0, /* tp_dict */ - 0, /* tp_descr_get */ - 0, /* tp_descr_set */ - 0, /* tp_dictoffset */ - 0, /* tp_init */ - 0, /* tp_alloc */ - product_new, /* tp_new */ - PyObject_GC_Del, /* tp_free */ + PyVarObject_HEAD_INIT(NULL, 0) + "itertools.product", /* tp_name */ + sizeof(productobject), /* tp_basicsize */ + 0, /* tp_itemsize */ + /* methods */ + (destructor)product_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 | + Py_TPFLAGS_BASETYPE, /* tp_flags */ + product_doc, /* tp_doc */ + (traverseproc)product_traverse, /* tp_traverse */ + 0, /* tp_clear */ + 0, /* tp_richcompare */ + 0, /* tp_weaklistoffset */ + PyObject_SelfIter, /* tp_iter */ + (iternextfunc)product_next, /* tp_iternext */ + 0, /* tp_methods */ + 0, /* tp_members */ + 0, /* tp_getset */ + 0, /* tp_base */ + 0, /* tp_dict */ + 0, /* tp_descr_get */ + 0, /* tp_descr_set */ + 0, /* tp_dictoffset */ + 0, /* tp_init */ + 0, /* tp_alloc */ + product_new, /* tp_new */ + PyObject_GC_Del, /* tp_free */ }; /* combinations object ************************************************************/ typedef struct { - PyObject_HEAD - PyObject *pool; /* input converted to a tuple */ - Py_ssize_t *indices; /* one index per result element */ - PyObject *result; /* most recently returned result tuple */ - Py_ssize_t r; /* size of result tuple */ - int stopped; /* set to 1 when the combinations iterator is exhausted */ + PyObject_HEAD + PyObject *pool; /* input converted to a tuple */ + Py_ssize_t *indices; /* one index per result element */ + PyObject *result; /* most recently returned result tuple */ + Py_ssize_t r; /* size of result tuple */ + int stopped; /* set to 1 when the combinations iterator is exhausted */ } combinationsobject; static PyTypeObject combinations_type; @@ -1860,160 +1860,160 @@ static PyObject * combinations_new(PyTypeObject *type, PyObject *args, PyObject *kwds) { - combinationsobject *co; - Py_ssize_t n; - Py_ssize_t r; - PyObject *pool = NULL; - PyObject *iterable = NULL; - Py_ssize_t *indices = NULL; - Py_ssize_t i; - static char *kwargs[] = {"iterable", "r", NULL}; - - if (!PyArg_ParseTupleAndKeywords(args, kwds, "On:combinations", kwargs, - &iterable, &r)) - return NULL; - - pool = PySequence_Tuple(iterable); - if (pool == NULL) - goto error; - n = PyTuple_GET_SIZE(pool); - if (r < 0) { - PyErr_SetString(PyExc_ValueError, "r must be non-negative"); - goto error; - } - - indices = PyMem_Malloc(r * sizeof(Py_ssize_t)); - if (indices == NULL) { - PyErr_NoMemory(); - goto error; - } - - for (i=0 ; itp_alloc(type, 0); - if (co == NULL) - goto error; - - co->pool = pool; - co->indices = indices; - co->result = NULL; - co->r = r; - co->stopped = r > n ? 1 : 0; + combinationsobject *co; + Py_ssize_t n; + Py_ssize_t r; + PyObject *pool = NULL; + PyObject *iterable = NULL; + Py_ssize_t *indices = NULL; + Py_ssize_t i; + static char *kwargs[] = {"iterable", "r", NULL}; + + if (!PyArg_ParseTupleAndKeywords(args, kwds, "On:combinations", kwargs, + &iterable, &r)) + return NULL; + + pool = PySequence_Tuple(iterable); + if (pool == NULL) + goto error; + n = PyTuple_GET_SIZE(pool); + if (r < 0) { + PyErr_SetString(PyExc_ValueError, "r must be non-negative"); + goto error; + } + + indices = PyMem_Malloc(r * sizeof(Py_ssize_t)); + if (indices == NULL) { + PyErr_NoMemory(); + goto error; + } + + for (i=0 ; itp_alloc(type, 0); + if (co == NULL) + goto error; + + co->pool = pool; + co->indices = indices; + co->result = NULL; + co->r = r; + co->stopped = r > n ? 1 : 0; - return (PyObject *)co; + return (PyObject *)co; error: - if (indices != NULL) - PyMem_Free(indices); - Py_XDECREF(pool); - return NULL; + if (indices != NULL) + PyMem_Free(indices); + Py_XDECREF(pool); + return NULL; } static void combinations_dealloc(combinationsobject *co) { - PyObject_GC_UnTrack(co); - Py_XDECREF(co->pool); - Py_XDECREF(co->result); - if (co->indices != NULL) - PyMem_Free(co->indices); - Py_TYPE(co)->tp_free(co); + PyObject_GC_UnTrack(co); + Py_XDECREF(co->pool); + Py_XDECREF(co->result); + if (co->indices != NULL) + PyMem_Free(co->indices); + Py_TYPE(co)->tp_free(co); } static int combinations_traverse(combinationsobject *co, visitproc visit, void *arg) { - Py_VISIT(co->pool); - Py_VISIT(co->result); - return 0; + Py_VISIT(co->pool); + Py_VISIT(co->result); + return 0; } static PyObject * combinations_next(combinationsobject *co) { - PyObject *elem; - PyObject *oldelem; - PyObject *pool = co->pool; - Py_ssize_t *indices = co->indices; - PyObject *result = co->result; - Py_ssize_t n = PyTuple_GET_SIZE(pool); - Py_ssize_t r = co->r; - Py_ssize_t i, j, index; - - if (co->stopped) - return NULL; - - if (result == NULL) { - /* On the first pass, initialize result tuple using the indices */ - result = PyTuple_New(r); - if (result == NULL) - goto empty; - co->result = result; - for (i=0; i 1) { - PyObject *old_result = result; - result = PyTuple_New(r); - if (result == NULL) - goto empty; - co->result = result; - for (i=0; i= 0 && indices[i] == i+n-r ; i--) - ; - - /* If i is negative, then the indices are all at - their maximum value and we're done. */ - if (i < 0) - goto empty; - - /* Increment the current index which we know is not at its - maximum. Then move back to the right setting each index - to its lowest possible value (one higher than the index - to its left -- this maintains the sort order invariant). */ - indices[i]++; - for (j=i+1 ; jpool; + Py_ssize_t *indices = co->indices; + PyObject *result = co->result; + Py_ssize_t n = PyTuple_GET_SIZE(pool); + Py_ssize_t r = co->r; + Py_ssize_t i, j, index; + + if (co->stopped) + return NULL; + + if (result == NULL) { + /* On the first pass, initialize result tuple using the indices */ + result = PyTuple_New(r); + if (result == NULL) + goto empty; + co->result = result; + for (i=0; i 1) { + PyObject *old_result = result; + result = PyTuple_New(r); + if (result == NULL) + goto empty; + co->result = result; + for (i=0; i= 0 && indices[i] == i+n-r ; i--) + ; + + /* If i is negative, then the indices are all at + their maximum value and we're done. */ + if (i < 0) + goto empty; + + /* Increment the current index which we know is not at its + maximum. Then move back to the right setting each index + to its lowest possible value (one higher than the index + to its left -- this maintains the sort order invariant). */ + indices[i]++; + for (j=i+1 ; jstopped = 1; - return NULL; + co->stopped = 1; + return NULL; } PyDoc_STRVAR(combinations_doc, @@ -2023,47 +2023,47 @@ combinations(range(4), 3) --> (0,1,2), (0,1,3), (0,2,3), (1,2,3)"); static PyTypeObject combinations_type = { - PyVarObject_HEAD_INIT(NULL, 0) - "itertools.combinations", /* tp_name */ - sizeof(combinationsobject), /* tp_basicsize */ - 0, /* tp_itemsize */ - /* methods */ - (destructor)combinations_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 | - Py_TPFLAGS_BASETYPE, /* tp_flags */ - combinations_doc, /* tp_doc */ - (traverseproc)combinations_traverse, /* tp_traverse */ - 0, /* tp_clear */ - 0, /* tp_richcompare */ - 0, /* tp_weaklistoffset */ - PyObject_SelfIter, /* tp_iter */ - (iternextfunc)combinations_next, /* tp_iternext */ - 0, /* tp_methods */ - 0, /* tp_members */ - 0, /* tp_getset */ - 0, /* tp_base */ - 0, /* tp_dict */ - 0, /* tp_descr_get */ - 0, /* tp_descr_set */ - 0, /* tp_dictoffset */ - 0, /* tp_init */ - 0, /* tp_alloc */ - combinations_new, /* tp_new */ - PyObject_GC_Del, /* tp_free */ + PyVarObject_HEAD_INIT(NULL, 0) + "itertools.combinations", /* tp_name */ + sizeof(combinationsobject), /* tp_basicsize */ + 0, /* tp_itemsize */ + /* methods */ + (destructor)combinations_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 | + Py_TPFLAGS_BASETYPE, /* tp_flags */ + combinations_doc, /* tp_doc */ + (traverseproc)combinations_traverse, /* tp_traverse */ + 0, /* tp_clear */ + 0, /* tp_richcompare */ + 0, /* tp_weaklistoffset */ + PyObject_SelfIter, /* tp_iter */ + (iternextfunc)combinations_next, /* tp_iternext */ + 0, /* tp_methods */ + 0, /* tp_members */ + 0, /* tp_getset */ + 0, /* tp_base */ + 0, /* tp_dict */ + 0, /* tp_descr_get */ + 0, /* tp_descr_set */ + 0, /* tp_dictoffset */ + 0, /* tp_init */ + 0, /* tp_alloc */ + combinations_new, /* tp_new */ + PyObject_GC_Del, /* tp_free */ }; @@ -2071,37 +2071,37 @@ /* Equivalent to: - def combinations_with_replacement(iterable, r): - "combinations_with_replacement('ABC', 2) --> AA AB AC BB BC CC" - # number items returned: (n+r-1)! / r! / (n-1)! - pool = tuple(iterable) - n = len(pool) - indices = [0] * r - yield tuple(pool[i] for i in indices) - while 1: - for i in reversed(range(r)): - if indices[i] != n - 1: - break - else: - return - indices[i:] = [indices[i] + 1] * (r - i) - yield tuple(pool[i] for i in indices) - - def combinations_with_replacement2(iterable, r): - 'Alternate version that filters from product()' - pool = tuple(iterable) - n = len(pool) - for indices in product(range(n), repeat=r): - if sorted(indices) == list(indices): - yield tuple(pool[i] for i in indices) + def combinations_with_replacement(iterable, r): + "combinations_with_replacement('ABC', 2) --> AA AB AC BB BC CC" + # number items returned: (n+r-1)! / r! / (n-1)! + pool = tuple(iterable) + n = len(pool) + indices = [0] * r + yield tuple(pool[i] for i in indices) + while 1: + for i in reversed(range(r)): + if indices[i] != n - 1: + break + else: + return + indices[i:] = [indices[i] + 1] * (r - i) + yield tuple(pool[i] for i in indices) + + def combinations_with_replacement2(iterable, r): + 'Alternate version that filters from product()' + pool = tuple(iterable) + n = len(pool) + for indices in product(range(n), repeat=r): + if sorted(indices) == list(indices): + yield tuple(pool[i] for i in indices) */ typedef struct { - PyObject_HEAD - PyObject *pool; /* input converted to a tuple */ - Py_ssize_t *indices; /* one index per result element */ - PyObject *result; /* most recently returned result tuple */ - Py_ssize_t r; /* size of result tuple */ - int stopped; /* set to 1 when the cwr iterator is exhausted */ + PyObject_HEAD + PyObject *pool; /* input converted to a tuple */ + Py_ssize_t *indices; /* one index per result element */ + PyObject *result; /* most recently returned result tuple */ + Py_ssize_t r; /* size of result tuple */ + int stopped; /* set to 1 when the cwr iterator is exhausted */ } cwrobject; static PyTypeObject cwr_type; @@ -2109,156 +2109,156 @@ static PyObject * cwr_new(PyTypeObject *type, PyObject *args, PyObject *kwds) { - cwrobject *co; - Py_ssize_t n; - Py_ssize_t r; - PyObject *pool = NULL; - PyObject *iterable = NULL; - Py_ssize_t *indices = NULL; - Py_ssize_t i; - static char *kwargs[] = {"iterable", "r", NULL}; - - if (!PyArg_ParseTupleAndKeywords(args, kwds, "On:combinations_with_replacement", kwargs, - &iterable, &r)) - return NULL; - - pool = PySequence_Tuple(iterable); - if (pool == NULL) - goto error; - n = PyTuple_GET_SIZE(pool); - if (r < 0) { - PyErr_SetString(PyExc_ValueError, "r must be non-negative"); - goto error; - } - - indices = PyMem_Malloc(r * sizeof(Py_ssize_t)); - if (indices == NULL) { - PyErr_NoMemory(); - goto error; - } - - for (i=0 ; itp_alloc(type, 0); - if (co == NULL) - goto error; - - co->pool = pool; - co->indices = indices; - co->result = NULL; - co->r = r; - co->stopped = !n && r; + cwrobject *co; + Py_ssize_t n; + Py_ssize_t r; + PyObject *pool = NULL; + PyObject *iterable = NULL; + Py_ssize_t *indices = NULL; + Py_ssize_t i; + static char *kwargs[] = {"iterable", "r", NULL}; + + if (!PyArg_ParseTupleAndKeywords(args, kwds, "On:combinations_with_replacement", kwargs, + &iterable, &r)) + return NULL; + + pool = PySequence_Tuple(iterable); + if (pool == NULL) + goto error; + n = PyTuple_GET_SIZE(pool); + if (r < 0) { + PyErr_SetString(PyExc_ValueError, "r must be non-negative"); + goto error; + } + + indices = PyMem_Malloc(r * sizeof(Py_ssize_t)); + if (indices == NULL) { + PyErr_NoMemory(); + goto error; + } + + for (i=0 ; itp_alloc(type, 0); + if (co == NULL) + goto error; + + co->pool = pool; + co->indices = indices; + co->result = NULL; + co->r = r; + co->stopped = !n && r; - return (PyObject *)co; + return (PyObject *)co; error: - if (indices != NULL) - PyMem_Free(indices); - Py_XDECREF(pool); - return NULL; + if (indices != NULL) + PyMem_Free(indices); + Py_XDECREF(pool); + return NULL; } static void cwr_dealloc(cwrobject *co) { - PyObject_GC_UnTrack(co); - Py_XDECREF(co->pool); - Py_XDECREF(co->result); - if (co->indices != NULL) - PyMem_Free(co->indices); - Py_TYPE(co)->tp_free(co); + PyObject_GC_UnTrack(co); + Py_XDECREF(co->pool); + Py_XDECREF(co->result); + if (co->indices != NULL) + PyMem_Free(co->indices); + Py_TYPE(co)->tp_free(co); } static int cwr_traverse(cwrobject *co, visitproc visit, void *arg) { - Py_VISIT(co->pool); - Py_VISIT(co->result); - return 0; + Py_VISIT(co->pool); + Py_VISIT(co->result); + return 0; } static PyObject * cwr_next(cwrobject *co) { - PyObject *elem; - PyObject *oldelem; - PyObject *pool = co->pool; - Py_ssize_t *indices = co->indices; - PyObject *result = co->result; - Py_ssize_t n = PyTuple_GET_SIZE(pool); - Py_ssize_t r = co->r; - Py_ssize_t i, j, index; - - if (co->stopped) - return NULL; - - if (result == NULL) { - /* On the first pass, initialize result tuple using the indices */ - result = PyTuple_New(r); - if (result == NULL) - goto empty; - co->result = result; - for (i=0; i 1) { - PyObject *old_result = result; - result = PyTuple_New(r); - if (result == NULL) - goto empty; - co->result = result; - for (i=0; i= 0 && indices[i] == n-1; i--) - ; - - /* If i is negative, then the indices are all at - their maximum value and we're done. */ - if (i < 0) - goto empty; - - /* Increment the current index which we know is not at its - maximum. Then set all to the right to the same value. */ - indices[i]++; - for (j=i+1 ; jpool; + Py_ssize_t *indices = co->indices; + PyObject *result = co->result; + Py_ssize_t n = PyTuple_GET_SIZE(pool); + Py_ssize_t r = co->r; + Py_ssize_t i, j, index; + + if (co->stopped) + return NULL; + + if (result == NULL) { + /* On the first pass, initialize result tuple using the indices */ + result = PyTuple_New(r); + if (result == NULL) + goto empty; + co->result = result; + for (i=0; i 1) { + PyObject *old_result = result; + result = PyTuple_New(r); + if (result == NULL) + goto empty; + co->result = result; + for (i=0; i= 0 && indices[i] == n-1; i--) + ; + + /* If i is negative, then the indices are all at + their maximum value and we're done. */ + if (i < 0) + goto empty; + + /* Increment the current index which we know is not at its + maximum. Then set all to the right to the same value. */ + indices[i]++; + for (j=i+1 ; jstopped = 1; - return NULL; + co->stopped = 1; + return NULL; } PyDoc_STRVAR(cwr_doc, @@ -2269,52 +2269,52 @@ combinations_with_replacement('ABC', 2) --> AA AB AC BB BC CC"); static PyTypeObject cwr_type = { - PyVarObject_HEAD_INIT(NULL, 0) - "itertools.combinations_with_replacement", /* tp_name */ - sizeof(cwrobject), /* tp_basicsize */ - 0, /* tp_itemsize */ - /* methods */ - (destructor)cwr_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 | - Py_TPFLAGS_BASETYPE, /* tp_flags */ - cwr_doc, /* tp_doc */ - (traverseproc)cwr_traverse, /* tp_traverse */ - 0, /* tp_clear */ - 0, /* tp_richcompare */ - 0, /* tp_weaklistoffset */ - PyObject_SelfIter, /* tp_iter */ - (iternextfunc)cwr_next, /* tp_iternext */ - 0, /* tp_methods */ - 0, /* tp_members */ - 0, /* tp_getset */ - 0, /* tp_base */ - 0, /* tp_dict */ - 0, /* tp_descr_get */ - 0, /* tp_descr_set */ - 0, /* tp_dictoffset */ - 0, /* tp_init */ - 0, /* tp_alloc */ - cwr_new, /* tp_new */ - PyObject_GC_Del, /* tp_free */ + PyVarObject_HEAD_INIT(NULL, 0) + "itertools.combinations_with_replacement", /* tp_name */ + sizeof(cwrobject), /* tp_basicsize */ + 0, /* tp_itemsize */ + /* methods */ + (destructor)cwr_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 | + Py_TPFLAGS_BASETYPE, /* tp_flags */ + cwr_doc, /* tp_doc */ + (traverseproc)cwr_traverse, /* tp_traverse */ + 0, /* tp_clear */ + 0, /* tp_richcompare */ + 0, /* tp_weaklistoffset */ + PyObject_SelfIter, /* tp_iter */ + (iternextfunc)cwr_next, /* tp_iternext */ + 0, /* tp_methods */ + 0, /* tp_members */ + 0, /* tp_getset */ + 0, /* tp_base */ + 0, /* tp_dict */ + 0, /* tp_descr_get */ + 0, /* tp_descr_set */ + 0, /* tp_dictoffset */ + 0, /* tp_init */ + 0, /* tp_alloc */ + cwr_new, /* tp_new */ + PyObject_GC_Del, /* tp_free */ }; /* permutations object ************************************************************ - + def permutations(iterable, r=None): 'permutations(range(3), 2) --> (0,1) (0,2) (1,0) (1,2) (2,0) (2,1)' pool = tuple(iterable) @@ -2324,28 +2324,28 @@ cycles = range(n-r+1, n+1)[::-1] yield tuple(pool[i] for i in indices[:r]) while n: - for i in reversed(range(r)): - cycles[i] -= 1 - if cycles[i] == 0: - indices[i:] = indices[i+1:] + indices[i:i+1] - cycles[i] = n - i - else: - j = cycles[i] - indices[i], indices[-j] = indices[-j], indices[i] - yield tuple(pool[i] for i in indices[:r]) - break + for i in reversed(range(r)): + cycles[i] -= 1 + if cycles[i] == 0: + indices[i:] = indices[i+1:] + indices[i:i+1] + cycles[i] = n - i else: - return + j = cycles[i] + indices[i], indices[-j] = indices[-j], indices[i] + yield tuple(pool[i] for i in indices[:r]) + break + else: + return */ typedef struct { - PyObject_HEAD - PyObject *pool; /* input converted to a tuple */ - Py_ssize_t *indices; /* one index per element in the pool */ - Py_ssize_t *cycles; /* one rollover counter per element in the result */ - PyObject *result; /* most recently returned result tuple */ - Py_ssize_t r; /* size of result tuple */ - int stopped; /* set to 1 when the permutations iterator is exhausted */ + PyObject_HEAD + PyObject *pool; /* input converted to a tuple */ + Py_ssize_t *indices; /* one index per element in the pool */ + Py_ssize_t *cycles; /* one rollover counter per element in the result */ + PyObject *result; /* most recently returned result tuple */ + Py_ssize_t r; /* size of result tuple */ + int stopped; /* set to 1 when the permutations iterator is exhausted */ } permutationsobject; static PyTypeObject permutations_type; @@ -2353,184 +2353,184 @@ static PyObject * permutations_new(PyTypeObject *type, PyObject *args, PyObject *kwds) { - permutationsobject *po; - Py_ssize_t n; - Py_ssize_t r; - PyObject *robj = Py_None; - PyObject *pool = NULL; - PyObject *iterable = NULL; - Py_ssize_t *indices = NULL; - Py_ssize_t *cycles = NULL; - Py_ssize_t i; - static char *kwargs[] = {"iterable", "r", NULL}; - - if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|O:permutations", kwargs, - &iterable, &robj)) - return NULL; - - pool = PySequence_Tuple(iterable); - if (pool == NULL) - goto error; - n = PyTuple_GET_SIZE(pool); - - r = n; - if (robj != Py_None) { - if (!PyLong_Check(robj)) { - PyErr_SetString(PyExc_TypeError, "Expected int as r"); - goto error; - } - r = PyLong_AsSsize_t(robj); - if (r == -1 && PyErr_Occurred()) - goto error; - } - if (r < 0) { - PyErr_SetString(PyExc_ValueError, "r must be non-negative"); - goto error; - } - - indices = PyMem_Malloc(n * sizeof(Py_ssize_t)); - cycles = PyMem_Malloc(r * sizeof(Py_ssize_t)); - if (indices == NULL || cycles == NULL) { - PyErr_NoMemory(); - goto error; - } - - for (i=0 ; itp_alloc(type, 0); - if (po == NULL) - goto error; - - po->pool = pool; - po->indices = indices; - po->cycles = cycles; - po->result = NULL; - po->r = r; - po->stopped = r > n ? 1 : 0; + permutationsobject *po; + Py_ssize_t n; + Py_ssize_t r; + PyObject *robj = Py_None; + PyObject *pool = NULL; + PyObject *iterable = NULL; + Py_ssize_t *indices = NULL; + Py_ssize_t *cycles = NULL; + Py_ssize_t i; + static char *kwargs[] = {"iterable", "r", NULL}; + + if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|O:permutations", kwargs, + &iterable, &robj)) + return NULL; + + pool = PySequence_Tuple(iterable); + if (pool == NULL) + goto error; + n = PyTuple_GET_SIZE(pool); + + r = n; + if (robj != Py_None) { + if (!PyLong_Check(robj)) { + PyErr_SetString(PyExc_TypeError, "Expected int as r"); + goto error; + } + r = PyLong_AsSsize_t(robj); + if (r == -1 && PyErr_Occurred()) + goto error; + } + if (r < 0) { + PyErr_SetString(PyExc_ValueError, "r must be non-negative"); + goto error; + } + + indices = PyMem_Malloc(n * sizeof(Py_ssize_t)); + cycles = PyMem_Malloc(r * sizeof(Py_ssize_t)); + if (indices == NULL || cycles == NULL) { + PyErr_NoMemory(); + goto error; + } + + for (i=0 ; itp_alloc(type, 0); + if (po == NULL) + goto error; + + po->pool = pool; + po->indices = indices; + po->cycles = cycles; + po->result = NULL; + po->r = r; + po->stopped = r > n ? 1 : 0; - return (PyObject *)po; + return (PyObject *)po; error: - if (indices != NULL) - PyMem_Free(indices); - if (cycles != NULL) - PyMem_Free(cycles); - Py_XDECREF(pool); - return NULL; + if (indices != NULL) + PyMem_Free(indices); + if (cycles != NULL) + PyMem_Free(cycles); + Py_XDECREF(pool); + return NULL; } static void permutations_dealloc(permutationsobject *po) { - PyObject_GC_UnTrack(po); - Py_XDECREF(po->pool); - Py_XDECREF(po->result); - PyMem_Free(po->indices); - PyMem_Free(po->cycles); - Py_TYPE(po)->tp_free(po); + PyObject_GC_UnTrack(po); + Py_XDECREF(po->pool); + Py_XDECREF(po->result); + PyMem_Free(po->indices); + PyMem_Free(po->cycles); + Py_TYPE(po)->tp_free(po); } static int permutations_traverse(permutationsobject *po, visitproc visit, void *arg) { - Py_VISIT(po->pool); - Py_VISIT(po->result); - return 0; + Py_VISIT(po->pool); + Py_VISIT(po->result); + return 0; } static PyObject * permutations_next(permutationsobject *po) { - PyObject *elem; - PyObject *oldelem; - PyObject *pool = po->pool; - Py_ssize_t *indices = po->indices; - Py_ssize_t *cycles = po->cycles; - PyObject *result = po->result; - Py_ssize_t n = PyTuple_GET_SIZE(pool); - Py_ssize_t r = po->r; - Py_ssize_t i, j, k, index; - - if (po->stopped) - return NULL; - - if (result == NULL) { - /* On the first pass, initialize result tuple using the indices */ - result = PyTuple_New(r); - if (result == NULL) - goto empty; - po->result = result; - for (i=0; i 1) { - PyObject *old_result = result; - result = PyTuple_New(r); - if (result == NULL) - goto empty; - po->result = result; - for (i=0; i=0 ; i--) { - cycles[i] -= 1; - if (cycles[i] == 0) { - /* rotatation: indices[i:] = indices[i+1:] + indices[i:i+1] */ - index = indices[i]; - for (j=i ; jpool; + Py_ssize_t *indices = po->indices; + Py_ssize_t *cycles = po->cycles; + PyObject *result = po->result; + Py_ssize_t n = PyTuple_GET_SIZE(pool); + Py_ssize_t r = po->r; + Py_ssize_t i, j, k, index; + + if (po->stopped) + return NULL; + + if (result == NULL) { + /* On the first pass, initialize result tuple using the indices */ + result = PyTuple_New(r); + if (result == NULL) + goto empty; + po->result = result; + for (i=0; i 1) { + PyObject *old_result = result; + result = PyTuple_New(r); + if (result == NULL) + goto empty; + po->result = result; + for (i=0; i=0 ; i--) { + cycles[i] -= 1; + if (cycles[i] == 0) { + /* rotatation: indices[i:] = indices[i+1:] + indices[i:i+1] */ + index = indices[i]; + for (j=i ; jstopped = 1; - return NULL; + po->stopped = 1; + return NULL; } PyDoc_STRVAR(permutations_doc, @@ -2540,47 +2540,47 @@ permutations(range(3), 2) --> (0,1), (0,2), (1,0), (1,2), (2,0), (2,1)"); static PyTypeObject permutations_type = { - PyVarObject_HEAD_INIT(NULL, 0) - "itertools.permutations", /* tp_name */ - sizeof(permutationsobject), /* tp_basicsize */ - 0, /* tp_itemsize */ - /* methods */ - (destructor)permutations_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 | - Py_TPFLAGS_BASETYPE, /* tp_flags */ - permutations_doc, /* tp_doc */ - (traverseproc)permutations_traverse, /* tp_traverse */ - 0, /* tp_clear */ - 0, /* tp_richcompare */ - 0, /* tp_weaklistoffset */ - PyObject_SelfIter, /* tp_iter */ - (iternextfunc)permutations_next, /* tp_iternext */ - 0, /* tp_methods */ - 0, /* tp_members */ - 0, /* tp_getset */ - 0, /* tp_base */ - 0, /* tp_dict */ - 0, /* tp_descr_get */ - 0, /* tp_descr_set */ - 0, /* tp_dictoffset */ - 0, /* tp_init */ - 0, /* tp_alloc */ - permutations_new, /* tp_new */ - PyObject_GC_Del, /* tp_free */ + PyVarObject_HEAD_INIT(NULL, 0) + "itertools.permutations", /* tp_name */ + sizeof(permutationsobject), /* tp_basicsize */ + 0, /* tp_itemsize */ + /* methods */ + (destructor)permutations_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 | + Py_TPFLAGS_BASETYPE, /* tp_flags */ + permutations_doc, /* tp_doc */ + (traverseproc)permutations_traverse, /* tp_traverse */ + 0, /* tp_clear */ + 0, /* tp_richcompare */ + 0, /* tp_weaklistoffset */ + PyObject_SelfIter, /* tp_iter */ + (iternextfunc)permutations_next, /* tp_iternext */ + 0, /* tp_methods */ + 0, /* tp_members */ + 0, /* tp_getset */ + 0, /* tp_base */ + 0, /* tp_dict */ + 0, /* tp_descr_get */ + 0, /* tp_descr_set */ + 0, /* tp_dictoffset */ + 0, /* tp_init */ + 0, /* tp_alloc */ + permutations_new, /* tp_new */ + PyObject_GC_Del, /* tp_free */ }; @@ -2588,15 +2588,15 @@ /* Equivalent to: - def compress(data, selectors): - "compress('ABCDEF', [1,0,1,0,1,1]) --> A C E F" - return (d for d, s in zip(data, selectors) if s) + def compress(data, selectors): + "compress('ABCDEF', [1,0,1,0,1,1]) --> A C E F" + return (d for d, s in zip(data, selectors) if s) */ typedef struct { - PyObject_HEAD - PyObject *data; - PyObject *selectors; + PyObject_HEAD + PyObject *data; + PyObject *selectors; } compressobject; static PyTypeObject compress_type; @@ -2604,86 +2604,86 @@ static PyObject * compress_new(PyTypeObject *type, PyObject *args, PyObject *kwds) { - PyObject *seq1, *seq2; - PyObject *data=NULL, *selectors=NULL; - compressobject *lz; - static char *kwargs[] = {"data", "selectors", NULL}; - - if (!PyArg_ParseTupleAndKeywords(args, kwds, "OO:compress", kwargs, &seq1, &seq2)) - return NULL; - - data = PyObject_GetIter(seq1); - if (data == NULL) - goto fail; - selectors = PyObject_GetIter(seq2); - if (selectors == NULL) - goto fail; - - /* create compressobject structure */ - lz = (compressobject *)type->tp_alloc(type, 0); - if (lz == NULL) - goto fail; - lz->data = data; - lz->selectors = selectors; - return (PyObject *)lz; + PyObject *seq1, *seq2; + PyObject *data=NULL, *selectors=NULL; + compressobject *lz; + static char *kwargs[] = {"data", "selectors", NULL}; + + if (!PyArg_ParseTupleAndKeywords(args, kwds, "OO:compress", kwargs, &seq1, &seq2)) + return NULL; + + data = PyObject_GetIter(seq1); + if (data == NULL) + goto fail; + selectors = PyObject_GetIter(seq2); + if (selectors == NULL) + goto fail; + + /* create compressobject structure */ + lz = (compressobject *)type->tp_alloc(type, 0); + if (lz == NULL) + goto fail; + lz->data = data; + lz->selectors = selectors; + return (PyObject *)lz; fail: - Py_XDECREF(data); - Py_XDECREF(selectors); - return NULL; + Py_XDECREF(data); + Py_XDECREF(selectors); + return NULL; } static void compress_dealloc(compressobject *lz) { - PyObject_GC_UnTrack(lz); - Py_XDECREF(lz->data); - Py_XDECREF(lz->selectors); - Py_TYPE(lz)->tp_free(lz); + PyObject_GC_UnTrack(lz); + Py_XDECREF(lz->data); + Py_XDECREF(lz->selectors); + Py_TYPE(lz)->tp_free(lz); } static int compress_traverse(compressobject *lz, visitproc visit, void *arg) { - Py_VISIT(lz->data); - Py_VISIT(lz->selectors); - return 0; + Py_VISIT(lz->data); + Py_VISIT(lz->selectors); + return 0; } static PyObject * compress_next(compressobject *lz) { - PyObject *data = lz->data, *selectors = lz->selectors; - PyObject *datum, *selector; - PyObject *(*datanext)(PyObject *) = *Py_TYPE(data)->tp_iternext; - PyObject *(*selectornext)(PyObject *) = *Py_TYPE(selectors)->tp_iternext; - int ok; - - while (1) { - /* Steps: get datum, get selector, evaluate selector. - Order is important (to match the pure python version - in terms of which input gets a chance to raise an - exception first). - */ - - datum = datanext(data); - if (datum == NULL) - return NULL; - - selector = selectornext(selectors); - if (selector == NULL) { - Py_DECREF(datum); - return NULL; - } - - ok = PyObject_IsTrue(selector); - Py_DECREF(selector); - if (ok == 1) - return datum; - Py_DECREF(datum); - if (ok == -1) - return NULL; - } + PyObject *data = lz->data, *selectors = lz->selectors; + PyObject *datum, *selector; + PyObject *(*datanext)(PyObject *) = *Py_TYPE(data)->tp_iternext; + PyObject *(*selectornext)(PyObject *) = *Py_TYPE(selectors)->tp_iternext; + int ok; + + while (1) { + /* Steps: get datum, get selector, evaluate selector. + Order is important (to match the pure python version + in terms of which input gets a chance to raise an + exception first). + */ + + datum = datanext(data); + if (datum == NULL) + return NULL; + + selector = selectornext(selectors); + if (selector == NULL) { + Py_DECREF(datum); + return NULL; + } + + ok = PyObject_IsTrue(selector); + Py_DECREF(selector); + if (ok == 1) + return datum; + Py_DECREF(datum); + if (ok == -1) + return NULL; + } } PyDoc_STRVAR(compress_doc, @@ -2694,56 +2694,56 @@ selectors to choose the data elements."); static PyTypeObject compress_type = { - PyVarObject_HEAD_INIT(NULL, 0) - "itertools.compress", /* tp_name */ - sizeof(compressobject), /* tp_basicsize */ - 0, /* tp_itemsize */ - /* methods */ - (destructor)compress_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 | - Py_TPFLAGS_BASETYPE, /* tp_flags */ - compress_doc, /* tp_doc */ - (traverseproc)compress_traverse, /* tp_traverse */ - 0, /* tp_clear */ - 0, /* tp_richcompare */ - 0, /* tp_weaklistoffset */ - PyObject_SelfIter, /* tp_iter */ - (iternextfunc)compress_next, /* tp_iternext */ - 0, /* tp_methods */ - 0, /* tp_members */ - 0, /* tp_getset */ - 0, /* tp_base */ - 0, /* tp_dict */ - 0, /* tp_descr_get */ - 0, /* tp_descr_set */ - 0, /* tp_dictoffset */ - 0, /* tp_init */ - 0, /* tp_alloc */ - compress_new, /* tp_new */ - PyObject_GC_Del, /* tp_free */ + PyVarObject_HEAD_INIT(NULL, 0) + "itertools.compress", /* tp_name */ + sizeof(compressobject), /* tp_basicsize */ + 0, /* tp_itemsize */ + /* methods */ + (destructor)compress_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 | + Py_TPFLAGS_BASETYPE, /* tp_flags */ + compress_doc, /* tp_doc */ + (traverseproc)compress_traverse, /* tp_traverse */ + 0, /* tp_clear */ + 0, /* tp_richcompare */ + 0, /* tp_weaklistoffset */ + PyObject_SelfIter, /* tp_iter */ + (iternextfunc)compress_next, /* tp_iternext */ + 0, /* tp_methods */ + 0, /* tp_members */ + 0, /* tp_getset */ + 0, /* tp_base */ + 0, /* tp_dict */ + 0, /* tp_descr_get */ + 0, /* tp_descr_set */ + 0, /* tp_dictoffset */ + 0, /* tp_init */ + 0, /* tp_alloc */ + compress_new, /* tp_new */ + PyObject_GC_Del, /* tp_free */ }; /* filterfalse object ************************************************************/ typedef struct { - PyObject_HEAD - PyObject *func; - PyObject *it; + PyObject_HEAD + PyObject *func; + PyObject *it; } filterfalseobject; static PyTypeObject filterfalse_type; @@ -2751,83 +2751,83 @@ static PyObject * filterfalse_new(PyTypeObject *type, PyObject *args, PyObject *kwds) { - PyObject *func, *seq; - PyObject *it; - filterfalseobject *lz; - - if (type == &filterfalse_type && - !_PyArg_NoKeywords("filterfalse()", kwds)) - return NULL; - - if (!PyArg_UnpackTuple(args, "filterfalse", 2, 2, &func, &seq)) - return NULL; - - /* Get iterator. */ - it = PyObject_GetIter(seq); - if (it == NULL) - return NULL; - - /* create filterfalseobject structure */ - lz = (filterfalseobject *)type->tp_alloc(type, 0); - if (lz == NULL) { - Py_DECREF(it); - return NULL; - } - Py_INCREF(func); - lz->func = func; - lz->it = it; + PyObject *func, *seq; + PyObject *it; + filterfalseobject *lz; + + if (type == &filterfalse_type && + !_PyArg_NoKeywords("filterfalse()", kwds)) + return NULL; + + if (!PyArg_UnpackTuple(args, "filterfalse", 2, 2, &func, &seq)) + return NULL; + + /* Get iterator. */ + it = PyObject_GetIter(seq); + if (it == NULL) + return NULL; + + /* create filterfalseobject structure */ + lz = (filterfalseobject *)type->tp_alloc(type, 0); + if (lz == NULL) { + Py_DECREF(it); + return NULL; + } + Py_INCREF(func); + lz->func = func; + lz->it = it; - return (PyObject *)lz; + return (PyObject *)lz; } static void filterfalse_dealloc(filterfalseobject *lz) { - PyObject_GC_UnTrack(lz); - Py_XDECREF(lz->func); - Py_XDECREF(lz->it); - Py_TYPE(lz)->tp_free(lz); + PyObject_GC_UnTrack(lz); + Py_XDECREF(lz->func); + Py_XDECREF(lz->it); + Py_TYPE(lz)->tp_free(lz); } static int filterfalse_traverse(filterfalseobject *lz, visitproc visit, void *arg) { - Py_VISIT(lz->it); - Py_VISIT(lz->func); - return 0; + Py_VISIT(lz->it); + Py_VISIT(lz->func); + return 0; } static PyObject * filterfalse_next(filterfalseobject *lz) { - PyObject *item; - PyObject *it = lz->it; - long ok; - PyObject *(*iternext)(PyObject *); - - iternext = *Py_TYPE(it)->tp_iternext; - for (;;) { - item = iternext(it); - if (item == NULL) - return NULL; - - if (lz->func == Py_None || lz->func == (PyObject *)&PyBool_Type) { - ok = PyObject_IsTrue(item); - } else { - PyObject *good; - good = PyObject_CallFunctionObjArgs(lz->func, - item, NULL); - if (good == NULL) { - Py_DECREF(item); - return NULL; - } - ok = PyObject_IsTrue(good); - Py_DECREF(good); - } - if (!ok) - return item; - Py_DECREF(item); - } + PyObject *item; + PyObject *it = lz->it; + long ok; + PyObject *(*iternext)(PyObject *); + + iternext = *Py_TYPE(it)->tp_iternext; + for (;;) { + item = iternext(it); + if (item == NULL) + return NULL; + + if (lz->func == Py_None || lz->func == (PyObject *)&PyBool_Type) { + ok = PyObject_IsTrue(item); + } else { + PyObject *good; + good = PyObject_CallFunctionObjArgs(lz->func, + item, NULL); + if (good == NULL) { + Py_DECREF(item); + return NULL; + } + ok = PyObject_IsTrue(good); + Py_DECREF(good); + } + if (!ok) + return item; + Py_DECREF(item); + } } PyDoc_STRVAR(filterfalse_doc, @@ -2837,74 +2837,74 @@ If function is None, return the items that are false."); static PyTypeObject filterfalse_type = { - PyVarObject_HEAD_INIT(NULL, 0) - "itertools.filterfalse", /* tp_name */ - sizeof(filterfalseobject), /* tp_basicsize */ - 0, /* tp_itemsize */ - /* methods */ - (destructor)filterfalse_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 | - Py_TPFLAGS_BASETYPE, /* tp_flags */ - filterfalse_doc, /* tp_doc */ - (traverseproc)filterfalse_traverse, /* tp_traverse */ - 0, /* tp_clear */ - 0, /* tp_richcompare */ - 0, /* tp_weaklistoffset */ - PyObject_SelfIter, /* tp_iter */ - (iternextfunc)filterfalse_next, /* tp_iternext */ - 0, /* tp_methods */ - 0, /* tp_members */ - 0, /* tp_getset */ - 0, /* tp_base */ - 0, /* tp_dict */ - 0, /* tp_descr_get */ - 0, /* tp_descr_set */ - 0, /* tp_dictoffset */ - 0, /* tp_init */ - 0, /* tp_alloc */ - filterfalse_new, /* tp_new */ - PyObject_GC_Del, /* tp_free */ + PyVarObject_HEAD_INIT(NULL, 0) + "itertools.filterfalse", /* tp_name */ + sizeof(filterfalseobject), /* tp_basicsize */ + 0, /* tp_itemsize */ + /* methods */ + (destructor)filterfalse_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 | + Py_TPFLAGS_BASETYPE, /* tp_flags */ + filterfalse_doc, /* tp_doc */ + (traverseproc)filterfalse_traverse, /* tp_traverse */ + 0, /* tp_clear */ + 0, /* tp_richcompare */ + 0, /* tp_weaklistoffset */ + PyObject_SelfIter, /* tp_iter */ + (iternextfunc)filterfalse_next, /* tp_iternext */ + 0, /* tp_methods */ + 0, /* tp_members */ + 0, /* tp_getset */ + 0, /* tp_base */ + 0, /* tp_dict */ + 0, /* tp_descr_get */ + 0, /* tp_descr_set */ + 0, /* tp_dictoffset */ + 0, /* tp_init */ + 0, /* tp_alloc */ + filterfalse_new, /* tp_new */ + PyObject_GC_Del, /* tp_free */ }; /* count object ************************************************************/ typedef struct { - PyObject_HEAD - Py_ssize_t cnt; - PyObject *long_cnt; - PyObject *long_step; + PyObject_HEAD + Py_ssize_t cnt; + PyObject *long_cnt; + PyObject *long_step; } countobject; /* Counting logic and invariants: fast_mode: when cnt an integer < PY_SSIZE_T_MAX and no step is specified. - assert(cnt != PY_SSIZE_T_MAX && long_cnt == NULL && long_step==PyInt(1)); - Advances with: cnt += 1 - When count hits Y_SSIZE_T_MAX, switch to slow_mode. + assert(cnt != PY_SSIZE_T_MAX && long_cnt == NULL && long_step==PyInt(1)); + Advances with: cnt += 1 + When count hits Y_SSIZE_T_MAX, switch to slow_mode. slow_mode: when cnt == PY_SSIZE_T_MAX, step is not int(1), or cnt is a float. - assert(cnt == PY_SSIZE_T_MAX && long_cnt != NULL && long_step != NULL); - All counting is done with python objects (no overflows or underflows). - Advances with: long_cnt += long_step - Step may be zero -- effectively a slow version of repeat(cnt). - Either long_cnt or long_step may be a float, Fraction, or Decimal. + assert(cnt == PY_SSIZE_T_MAX && long_cnt != NULL && long_step != NULL); + All counting is done with python objects (no overflows or underflows). + Advances with: long_cnt += long_step + Step may be zero -- effectively a slow version of repeat(cnt). + Either long_cnt or long_step may be a float, Fraction, or Decimal. */ static PyTypeObject count_type; @@ -2912,221 +2912,221 @@ static PyObject * count_new(PyTypeObject *type, PyObject *args, PyObject *kwds) { - countobject *lz; - int slow_mode = 0; - Py_ssize_t cnt = 0; - PyObject *long_cnt = NULL; - PyObject *long_step = NULL; - static char *kwlist[] = {"start", "step", 0}; - - if (!PyArg_ParseTupleAndKeywords(args, kwds, "|OO:count", - kwlist, &long_cnt, &long_step)) - return NULL; - - if ((long_cnt != NULL && !PyNumber_Check(long_cnt)) || - (long_step != NULL && !PyNumber_Check(long_step))) { - PyErr_SetString(PyExc_TypeError, "a number is required"); - return NULL; - } - - if (long_cnt != NULL) { - cnt = PyLong_AsSsize_t(long_cnt); - if ((cnt == -1 && PyErr_Occurred()) || !PyLong_Check(long_cnt)) { - PyErr_Clear(); - slow_mode = 1; - } - Py_INCREF(long_cnt); - } else { - cnt = 0; - long_cnt = PyLong_FromLong(0); - } - - /* If not specified, step defaults to 1 */ - if (long_step == NULL) { - long_step = PyLong_FromLong(1); - if (long_step == NULL) { - Py_DECREF(long_cnt); - return NULL; - } - } else - Py_INCREF(long_step); - - assert(long_cnt != NULL && long_step != NULL); - - /* Fast mode only works when the step is 1 */ - if (!PyLong_Check(long_step) || - PyLong_AS_LONG(long_step) != 1) { - slow_mode = 1; - } - - if (slow_mode) - cnt = PY_SSIZE_T_MAX; - else - Py_CLEAR(long_cnt); - - assert((cnt != PY_SSIZE_T_MAX && long_cnt == NULL && !slow_mode) || - (cnt == PY_SSIZE_T_MAX && long_cnt != NULL && slow_mode)); - assert(slow_mode || - (PyLong_Check(long_step) && PyLong_AS_LONG(long_step) == 1)); - - /* create countobject structure */ - lz = (countobject *)type->tp_alloc(type, 0); - if (lz == NULL) { - Py_XDECREF(long_cnt); - return NULL; - } - lz->cnt = cnt; - lz->long_cnt = long_cnt; - lz->long_step = long_step; + countobject *lz; + int slow_mode = 0; + Py_ssize_t cnt = 0; + PyObject *long_cnt = NULL; + PyObject *long_step = NULL; + static char *kwlist[] = {"start", "step", 0}; + + if (!PyArg_ParseTupleAndKeywords(args, kwds, "|OO:count", + kwlist, &long_cnt, &long_step)) + return NULL; + + if ((long_cnt != NULL && !PyNumber_Check(long_cnt)) || + (long_step != NULL && !PyNumber_Check(long_step))) { + PyErr_SetString(PyExc_TypeError, "a number is required"); + return NULL; + } + + if (long_cnt != NULL) { + cnt = PyLong_AsSsize_t(long_cnt); + if ((cnt == -1 && PyErr_Occurred()) || !PyLong_Check(long_cnt)) { + PyErr_Clear(); + slow_mode = 1; + } + Py_INCREF(long_cnt); + } else { + cnt = 0; + long_cnt = PyLong_FromLong(0); + } + + /* If not specified, step defaults to 1 */ + if (long_step == NULL) { + long_step = PyLong_FromLong(1); + if (long_step == NULL) { + Py_DECREF(long_cnt); + return NULL; + } + } else + Py_INCREF(long_step); - return (PyObject *)lz; + assert(long_cnt != NULL && long_step != NULL); + + /* Fast mode only works when the step is 1 */ + if (!PyLong_Check(long_step) || + PyLong_AS_LONG(long_step) != 1) { + slow_mode = 1; + } + + if (slow_mode) + cnt = PY_SSIZE_T_MAX; + else + Py_CLEAR(long_cnt); + + assert((cnt != PY_SSIZE_T_MAX && long_cnt == NULL && !slow_mode) || + (cnt == PY_SSIZE_T_MAX && long_cnt != NULL && slow_mode)); + assert(slow_mode || + (PyLong_Check(long_step) && PyLong_AS_LONG(long_step) == 1)); + + /* create countobject structure */ + lz = (countobject *)type->tp_alloc(type, 0); + if (lz == NULL) { + Py_XDECREF(long_cnt); + return NULL; + } + lz->cnt = cnt; + lz->long_cnt = long_cnt; + lz->long_step = long_step; + + return (PyObject *)lz; } static void count_dealloc(countobject *lz) { - PyObject_GC_UnTrack(lz); - Py_XDECREF(lz->long_cnt); - Py_XDECREF(lz->long_step); - Py_TYPE(lz)->tp_free(lz); + PyObject_GC_UnTrack(lz); + Py_XDECREF(lz->long_cnt); + Py_XDECREF(lz->long_step); + Py_TYPE(lz)->tp_free(lz); } static int count_traverse(countobject *lz, visitproc visit, void *arg) { - Py_VISIT(lz->long_cnt); - Py_VISIT(lz->long_step); - return 0; + Py_VISIT(lz->long_cnt); + Py_VISIT(lz->long_step); + return 0; } static PyObject * count_nextlong(countobject *lz) { - PyObject *long_cnt; - PyObject *stepped_up; + PyObject *long_cnt; + PyObject *stepped_up; - long_cnt = lz->long_cnt; - if (long_cnt == NULL) { - /* Switch to slow_mode */ - long_cnt = PyLong_FromSsize_t(PY_SSIZE_T_MAX); - if (long_cnt == NULL) - return NULL; - } - assert(lz->cnt == PY_SSIZE_T_MAX && long_cnt != NULL); - - stepped_up = PyNumber_Add(long_cnt, lz->long_step); - if (stepped_up == NULL) - return NULL; - lz->long_cnt = stepped_up; - return long_cnt; + long_cnt = lz->long_cnt; + if (long_cnt == NULL) { + /* Switch to slow_mode */ + long_cnt = PyLong_FromSsize_t(PY_SSIZE_T_MAX); + if (long_cnt == NULL) + return NULL; + } + assert(lz->cnt == PY_SSIZE_T_MAX && long_cnt != NULL); + + stepped_up = PyNumber_Add(long_cnt, lz->long_step); + if (stepped_up == NULL) + return NULL; + lz->long_cnt = stepped_up; + return long_cnt; } static PyObject * count_next(countobject *lz) { - if (lz->cnt == PY_SSIZE_T_MAX) - return count_nextlong(lz); - return PyLong_FromSsize_t(lz->cnt++); + if (lz->cnt == PY_SSIZE_T_MAX) + return count_nextlong(lz); + return PyLong_FromSsize_t(lz->cnt++); } static PyObject * count_repr(countobject *lz) { - if (lz->cnt != PY_SSIZE_T_MAX) - return PyUnicode_FromFormat("count(%zd)", lz->cnt); + if (lz->cnt != PY_SSIZE_T_MAX) + return PyUnicode_FromFormat("count(%zd)", lz->cnt); - if (PyLong_Check(lz->long_step)) { - long step = PyLong_AsLong(lz->long_step); - if (step == -1 && PyErr_Occurred()) { - PyErr_Clear(); - } - if (step == 1) { - /* Don't display step when it is an integer equal to 1 */ - return PyUnicode_FromFormat("count(%R)", lz->long_cnt); - } - } - return PyUnicode_FromFormat("count(%R, %R)", - lz->long_cnt, lz->long_step); + if (PyLong_Check(lz->long_step)) { + long step = PyLong_AsLong(lz->long_step); + if (step == -1 && PyErr_Occurred()) { + PyErr_Clear(); + } + if (step == 1) { + /* Don't display step when it is an integer equal to 1 */ + return PyUnicode_FromFormat("count(%R)", lz->long_cnt); + } + } + return PyUnicode_FromFormat("count(%R, %R)", + lz->long_cnt, lz->long_step); } static PyObject * count_reduce(countobject *lz) { - if (lz->cnt == PY_SSIZE_T_MAX) - return Py_BuildValue("O(OO)", Py_TYPE(lz), lz->long_cnt, lz->long_step); - return Py_BuildValue("O(n)", Py_TYPE(lz), lz->cnt); + if (lz->cnt == PY_SSIZE_T_MAX) + return Py_BuildValue("O(OO)", Py_TYPE(lz), lz->long_cnt, lz->long_step); + return Py_BuildValue("O(n)", Py_TYPE(lz), lz->cnt); } PyDoc_STRVAR(count_reduce_doc, "Return state information for pickling."); static PyMethodDef count_methods[] = { - {"__reduce__", (PyCFunction)count_reduce, METH_NOARGS, - count_reduce_doc}, - {NULL, NULL} /* sentinel */ + {"__reduce__", (PyCFunction)count_reduce, METH_NOARGS, + count_reduce_doc}, + {NULL, NULL} /* sentinel */ }; PyDoc_STRVAR(count_doc, - "count(start=0, step=1]) --> count object\n\ + "count(start=0, step=1]) --> count object\n\ \n\ Return a count object whose .__next__() method returns consecutive values.\n\ Equivalent to:\n\n\ def count(firstval=0, step=1):\n\ - x = firstval\n\ - while 1:\n\ - yield x\n\ - x += step\n"); + x = firstval\n\ + while 1:\n\ + yield x\n\ + x += step\n"); static PyTypeObject count_type = { - PyVarObject_HEAD_INIT(NULL, 0) - "itertools.count", /* tp_name */ - sizeof(countobject), /* tp_basicsize */ - 0, /* tp_itemsize */ - /* methods */ - (destructor)count_dealloc, /* tp_dealloc */ - 0, /* tp_print */ - 0, /* tp_getattr */ - 0, /* tp_setattr */ - 0, /* tp_reserved */ - (reprfunc)count_repr, /* 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 | - Py_TPFLAGS_BASETYPE, /* tp_flags */ - count_doc, /* tp_doc */ - (traverseproc)count_traverse, /* tp_traverse */ - 0, /* tp_clear */ - 0, /* tp_richcompare */ - 0, /* tp_weaklistoffset */ - PyObject_SelfIter, /* tp_iter */ - (iternextfunc)count_next, /* tp_iternext */ - count_methods, /* tp_methods */ - 0, /* tp_members */ - 0, /* tp_getset */ - 0, /* tp_base */ - 0, /* tp_dict */ - 0, /* tp_descr_get */ - 0, /* tp_descr_set */ - 0, /* tp_dictoffset */ - 0, /* tp_init */ - 0, /* tp_alloc */ - count_new, /* tp_new */ - PyObject_GC_Del, /* tp_free */ + PyVarObject_HEAD_INIT(NULL, 0) + "itertools.count", /* tp_name */ + sizeof(countobject), /* tp_basicsize */ + 0, /* tp_itemsize */ + /* methods */ + (destructor)count_dealloc, /* tp_dealloc */ + 0, /* tp_print */ + 0, /* tp_getattr */ + 0, /* tp_setattr */ + 0, /* tp_reserved */ + (reprfunc)count_repr, /* 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 | + Py_TPFLAGS_BASETYPE, /* tp_flags */ + count_doc, /* tp_doc */ + (traverseproc)count_traverse, /* tp_traverse */ + 0, /* tp_clear */ + 0, /* tp_richcompare */ + 0, /* tp_weaklistoffset */ + PyObject_SelfIter, /* tp_iter */ + (iternextfunc)count_next, /* tp_iternext */ + count_methods, /* tp_methods */ + 0, /* tp_members */ + 0, /* tp_getset */ + 0, /* tp_base */ + 0, /* tp_dict */ + 0, /* tp_descr_get */ + 0, /* tp_descr_set */ + 0, /* tp_dictoffset */ + 0, /* tp_init */ + 0, /* tp_alloc */ + count_new, /* tp_new */ + PyObject_GC_Del, /* tp_free */ }; /* repeat object ************************************************************/ typedef struct { - PyObject_HEAD - PyObject *element; - Py_ssize_t cnt; + PyObject_HEAD + PyObject *element; + Py_ssize_t cnt; } repeatobject; static PyTypeObject repeat_type; @@ -3134,77 +3134,77 @@ static PyObject * repeat_new(PyTypeObject *type, PyObject *args, PyObject *kwds) { - repeatobject *ro; - PyObject *element; - Py_ssize_t cnt = -1; - static char *kwargs[] = {"object", "times", NULL}; - - if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|n:repeat", kwargs, - &element, &cnt)) - return NULL; - - if (PyTuple_Size(args) == 2 && cnt < 0) - cnt = 0; - - ro = (repeatobject *)type->tp_alloc(type, 0); - if (ro == NULL) - return NULL; - Py_INCREF(element); - ro->element = element; - ro->cnt = cnt; - return (PyObject *)ro; + repeatobject *ro; + PyObject *element; + Py_ssize_t cnt = -1; + static char *kwargs[] = {"object", "times", NULL}; + + if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|n:repeat", kwargs, + &element, &cnt)) + return NULL; + + if (PyTuple_Size(args) == 2 && cnt < 0) + cnt = 0; + + ro = (repeatobject *)type->tp_alloc(type, 0); + if (ro == NULL) + return NULL; + Py_INCREF(element); + ro->element = element; + ro->cnt = cnt; + return (PyObject *)ro; } static void repeat_dealloc(repeatobject *ro) { - PyObject_GC_UnTrack(ro); - Py_XDECREF(ro->element); - Py_TYPE(ro)->tp_free(ro); + PyObject_GC_UnTrack(ro); + Py_XDECREF(ro->element); + Py_TYPE(ro)->tp_free(ro); } static int repeat_traverse(repeatobject *ro, visitproc visit, void *arg) { - Py_VISIT(ro->element); - return 0; + Py_VISIT(ro->element); + return 0; } static PyObject * repeat_next(repeatobject *ro) { - if (ro->cnt == 0) - return NULL; - if (ro->cnt > 0) - ro->cnt--; - Py_INCREF(ro->element); - return ro->element; + if (ro->cnt == 0) + return NULL; + if (ro->cnt > 0) + ro->cnt--; + Py_INCREF(ro->element); + return ro->element; } static PyObject * repeat_repr(repeatobject *ro) { - if (ro->cnt == -1) - return PyUnicode_FromFormat("repeat(%R)", ro->element); - else - return PyUnicode_FromFormat("repeat(%R, %zd)", ro->element, ro->cnt); -} + if (ro->cnt == -1) + return PyUnicode_FromFormat("repeat(%R)", ro->element); + else + return PyUnicode_FromFormat("repeat(%R, %zd)", ro->element, ro->cnt); +} static PyObject * repeat_len(repeatobject *ro) { - if (ro->cnt == -1) { - PyErr_SetString(PyExc_TypeError, "len() of unsized object"); - return NULL; - } - return PyLong_FromSize_t(ro->cnt); + if (ro->cnt == -1) { + PyErr_SetString(PyExc_TypeError, "len() of unsized object"); + return NULL; + } + return PyLong_FromSize_t(ro->cnt); } PyDoc_STRVAR(length_hint_doc, "Private method returning an estimate of len(list(it))."); static PyMethodDef repeat_methods[] = { - {"__length_hint__", (PyCFunction)repeat_len, METH_NOARGS, length_hint_doc}, - {NULL, NULL} /* sentinel */ + {"__length_hint__", (PyCFunction)repeat_len, METH_NOARGS, length_hint_doc}, + {NULL, NULL} /* sentinel */ }; PyDoc_STRVAR(repeat_doc, @@ -3213,47 +3213,47 @@ endlessly."); static PyTypeObject repeat_type = { - PyVarObject_HEAD_INIT(NULL, 0) - "itertools.repeat", /* tp_name */ - sizeof(repeatobject), /* tp_basicsize */ - 0, /* tp_itemsize */ - /* methods */ - (destructor)repeat_dealloc, /* tp_dealloc */ - 0, /* tp_print */ - 0, /* tp_getattr */ - 0, /* tp_setattr */ - 0, /* tp_reserved */ - (reprfunc)repeat_repr, /* 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 | - Py_TPFLAGS_BASETYPE, /* tp_flags */ - repeat_doc, /* tp_doc */ - (traverseproc)repeat_traverse, /* tp_traverse */ - 0, /* tp_clear */ - 0, /* tp_richcompare */ - 0, /* tp_weaklistoffset */ - PyObject_SelfIter, /* tp_iter */ - (iternextfunc)repeat_next, /* tp_iternext */ - repeat_methods, /* tp_methods */ - 0, /* tp_members */ - 0, /* tp_getset */ - 0, /* tp_base */ - 0, /* tp_dict */ - 0, /* tp_descr_get */ - 0, /* tp_descr_set */ - 0, /* tp_dictoffset */ - 0, /* tp_init */ - 0, /* tp_alloc */ - repeat_new, /* tp_new */ - PyObject_GC_Del, /* tp_free */ + PyVarObject_HEAD_INIT(NULL, 0) + "itertools.repeat", /* tp_name */ + sizeof(repeatobject), /* tp_basicsize */ + 0, /* tp_itemsize */ + /* methods */ + (destructor)repeat_dealloc, /* tp_dealloc */ + 0, /* tp_print */ + 0, /* tp_getattr */ + 0, /* tp_setattr */ + 0, /* tp_reserved */ + (reprfunc)repeat_repr, /* 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 | + Py_TPFLAGS_BASETYPE, /* tp_flags */ + repeat_doc, /* tp_doc */ + (traverseproc)repeat_traverse, /* tp_traverse */ + 0, /* tp_clear */ + 0, /* tp_richcompare */ + 0, /* tp_weaklistoffset */ + PyObject_SelfIter, /* tp_iter */ + (iternextfunc)repeat_next, /* tp_iternext */ + repeat_methods, /* tp_methods */ + 0, /* tp_members */ + 0, /* tp_getset */ + 0, /* tp_base */ + 0, /* tp_dict */ + 0, /* tp_descr_get */ + 0, /* tp_descr_set */ + 0, /* tp_dictoffset */ + 0, /* tp_init */ + 0, /* tp_alloc */ + repeat_new, /* tp_new */ + PyObject_GC_Del, /* tp_free */ }; /* ziplongest object ************************************************************/ @@ -3261,12 +3261,12 @@ #include "Python.h" typedef struct { - PyObject_HEAD - Py_ssize_t tuplesize; - Py_ssize_t numactive; - PyObject *ittuple; /* tuple of iterators */ - PyObject *result; - PyObject *fillvalue; + PyObject_HEAD + Py_ssize_t tuplesize; + Py_ssize_t numactive; + PyObject *ittuple; /* tuple of iterators */ + PyObject *result; + PyObject *fillvalue; } ziplongestobject; static PyTypeObject ziplongest_type; @@ -3274,159 +3274,159 @@ static PyObject * zip_longest_new(PyTypeObject *type, PyObject *args, PyObject *kwds) { - ziplongestobject *lz; - Py_ssize_t i; - PyObject *ittuple; /* tuple of iterators */ - PyObject *result; - PyObject *fillvalue = Py_None; - Py_ssize_t tuplesize = PySequence_Length(args); - - if (kwds != NULL && PyDict_CheckExact(kwds) && PyDict_Size(kwds) > 0) { - fillvalue = PyDict_GetItemString(kwds, "fillvalue"); - if (fillvalue == NULL || PyDict_Size(kwds) > 1) { - PyErr_SetString(PyExc_TypeError, - "zip_longest() got an unexpected keyword argument"); - return NULL; - } + ziplongestobject *lz; + Py_ssize_t i; + PyObject *ittuple; /* tuple of iterators */ + PyObject *result; + PyObject *fillvalue = Py_None; + Py_ssize_t tuplesize = PySequence_Length(args); + + if (kwds != NULL && PyDict_CheckExact(kwds) && PyDict_Size(kwds) > 0) { + fillvalue = PyDict_GetItemString(kwds, "fillvalue"); + if (fillvalue == NULL || PyDict_Size(kwds) > 1) { + PyErr_SetString(PyExc_TypeError, + "zip_longest() got an unexpected keyword argument"); + return NULL; } + } + + /* args must be a tuple */ + assert(PyTuple_Check(args)); - /* args must be a tuple */ - assert(PyTuple_Check(args)); + /* obtain iterators */ + ittuple = PyTuple_New(tuplesize); + if (ittuple == NULL) + return NULL; + for (i=0; i < tuplesize; ++i) { + PyObject *item = PyTuple_GET_ITEM(args, i); + PyObject *it = PyObject_GetIter(item); + if (it == NULL) { + if (PyErr_ExceptionMatches(PyExc_TypeError)) + PyErr_Format(PyExc_TypeError, + "zip_longest argument #%zd must support iteration", + i+1); + Py_DECREF(ittuple); + return NULL; + } + PyTuple_SET_ITEM(ittuple, i, it); + } - /* obtain iterators */ - ittuple = PyTuple_New(tuplesize); - if (ittuple == NULL) - return NULL; - for (i=0; i < tuplesize; ++i) { - PyObject *item = PyTuple_GET_ITEM(args, i); - PyObject *it = PyObject_GetIter(item); - if (it == NULL) { - if (PyErr_ExceptionMatches(PyExc_TypeError)) - PyErr_Format(PyExc_TypeError, - "zip_longest argument #%zd must support iteration", - i+1); - Py_DECREF(ittuple); - return NULL; - } - PyTuple_SET_ITEM(ittuple, i, it); - } - - /* create a result holder */ - result = PyTuple_New(tuplesize); - if (result == NULL) { - Py_DECREF(ittuple); - return NULL; - } - for (i=0 ; i < tuplesize ; i++) { - Py_INCREF(Py_None); - PyTuple_SET_ITEM(result, i, Py_None); - } - - /* create ziplongestobject structure */ - lz = (ziplongestobject *)type->tp_alloc(type, 0); - if (lz == NULL) { - Py_DECREF(ittuple); - Py_DECREF(result); - return NULL; - } - lz->ittuple = ittuple; - lz->tuplesize = tuplesize; - lz->numactive = tuplesize; - lz->result = result; - Py_INCREF(fillvalue); - lz->fillvalue = fillvalue; - return (PyObject *)lz; + /* create a result holder */ + result = PyTuple_New(tuplesize); + if (result == NULL) { + Py_DECREF(ittuple); + return NULL; + } + for (i=0 ; i < tuplesize ; i++) { + Py_INCREF(Py_None); + PyTuple_SET_ITEM(result, i, Py_None); + } + + /* create ziplongestobject structure */ + lz = (ziplongestobject *)type->tp_alloc(type, 0); + if (lz == NULL) { + Py_DECREF(ittuple); + Py_DECREF(result); + return NULL; + } + lz->ittuple = ittuple; + lz->tuplesize = tuplesize; + lz->numactive = tuplesize; + lz->result = result; + Py_INCREF(fillvalue); + lz->fillvalue = fillvalue; + return (PyObject *)lz; } static void zip_longest_dealloc(ziplongestobject *lz) { - PyObject_GC_UnTrack(lz); - Py_XDECREF(lz->ittuple); - Py_XDECREF(lz->result); - Py_XDECREF(lz->fillvalue); - Py_TYPE(lz)->tp_free(lz); + PyObject_GC_UnTrack(lz); + Py_XDECREF(lz->ittuple); + Py_XDECREF(lz->result); + Py_XDECREF(lz->fillvalue); + Py_TYPE(lz)->tp_free(lz); } static int zip_longest_traverse(ziplongestobject *lz, visitproc visit, void *arg) { - Py_VISIT(lz->ittuple); - Py_VISIT(lz->result); - Py_VISIT(lz->fillvalue); - return 0; + Py_VISIT(lz->ittuple); + Py_VISIT(lz->result); + Py_VISIT(lz->fillvalue); + return 0; } static PyObject * zip_longest_next(ziplongestobject *lz) { - Py_ssize_t i; - Py_ssize_t tuplesize = lz->tuplesize; - PyObject *result = lz->result; - PyObject *it; - PyObject *item; - PyObject *olditem; - - if (tuplesize == 0) - return NULL; - if (lz->numactive == 0) - return NULL; - if (Py_REFCNT(result) == 1) { - Py_INCREF(result); - for (i=0 ; i < tuplesize ; i++) { - it = PyTuple_GET_ITEM(lz->ittuple, i); - if (it == NULL) { - Py_INCREF(lz->fillvalue); - item = lz->fillvalue; - } else { - item = PyIter_Next(it); - if (item == NULL) { - lz->numactive -= 1; - if (lz->numactive == 0 || PyErr_Occurred()) { - lz->numactive = 0; - Py_DECREF(result); - return NULL; - } else { - Py_INCREF(lz->fillvalue); - item = lz->fillvalue; - PyTuple_SET_ITEM(lz->ittuple, i, NULL); - Py_DECREF(it); - } - } - } - olditem = PyTuple_GET_ITEM(result, i); - PyTuple_SET_ITEM(result, i, item); - Py_DECREF(olditem); + Py_ssize_t i; + Py_ssize_t tuplesize = lz->tuplesize; + PyObject *result = lz->result; + PyObject *it; + PyObject *item; + PyObject *olditem; + + if (tuplesize == 0) + return NULL; + if (lz->numactive == 0) + return NULL; + if (Py_REFCNT(result) == 1) { + Py_INCREF(result); + for (i=0 ; i < tuplesize ; i++) { + it = PyTuple_GET_ITEM(lz->ittuple, i); + if (it == NULL) { + Py_INCREF(lz->fillvalue); + item = lz->fillvalue; + } else { + item = PyIter_Next(it); + if (item == NULL) { + lz->numactive -= 1; + if (lz->numactive == 0 || PyErr_Occurred()) { + lz->numactive = 0; + Py_DECREF(result); + return NULL; + } else { + Py_INCREF(lz->fillvalue); + item = lz->fillvalue; + PyTuple_SET_ITEM(lz->ittuple, i, NULL); + Py_DECREF(it); + } } - } else { - result = PyTuple_New(tuplesize); - if (result == NULL) + } + olditem = PyTuple_GET_ITEM(result, i); + PyTuple_SET_ITEM(result, i, item); + Py_DECREF(olditem); + } + } else { + result = PyTuple_New(tuplesize); + if (result == NULL) + return NULL; + for (i=0 ; i < tuplesize ; i++) { + it = PyTuple_GET_ITEM(lz->ittuple, i); + if (it == NULL) { + Py_INCREF(lz->fillvalue); + item = lz->fillvalue; + } else { + item = PyIter_Next(it); + if (item == NULL) { + lz->numactive -= 1; + if (lz->numactive == 0 || PyErr_Occurred()) { + lz->numactive = 0; + Py_DECREF(result); return NULL; - for (i=0 ; i < tuplesize ; i++) { - it = PyTuple_GET_ITEM(lz->ittuple, i); - if (it == NULL) { - Py_INCREF(lz->fillvalue); - item = lz->fillvalue; - } else { - item = PyIter_Next(it); - if (item == NULL) { - lz->numactive -= 1; - if (lz->numactive == 0 || PyErr_Occurred()) { - lz->numactive = 0; - Py_DECREF(result); - return NULL; - } else { - Py_INCREF(lz->fillvalue); - item = lz->fillvalue; - PyTuple_SET_ITEM(lz->ittuple, i, NULL); - Py_DECREF(it); - } - } - } - PyTuple_SET_ITEM(result, i, item); + } else { + Py_INCREF(lz->fillvalue); + item = lz->fillvalue; + PyTuple_SET_ITEM(lz->ittuple, i, NULL); + Py_DECREF(it); + } } + } + PyTuple_SET_ITEM(result, i, item); } - return result; + } + return result; } PyDoc_STRVAR(zip_longest_doc, @@ -3441,47 +3441,47 @@ "); static PyTypeObject ziplongest_type = { - PyVarObject_HEAD_INIT(NULL, 0) - "itertools.zip_longest", /* tp_name */ - sizeof(ziplongestobject), /* tp_basicsize */ - 0, /* tp_itemsize */ - /* methods */ - (destructor)zip_longest_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 | - Py_TPFLAGS_BASETYPE, /* tp_flags */ - zip_longest_doc, /* tp_doc */ - (traverseproc)zip_longest_traverse, /* tp_traverse */ - 0, /* tp_clear */ - 0, /* tp_richcompare */ - 0, /* tp_weaklistoffset */ - PyObject_SelfIter, /* tp_iter */ - (iternextfunc)zip_longest_next, /* tp_iternext */ - 0, /* tp_methods */ - 0, /* tp_members */ - 0, /* tp_getset */ - 0, /* tp_base */ - 0, /* tp_dict */ - 0, /* tp_descr_get */ - 0, /* tp_descr_set */ - 0, /* tp_dictoffset */ - 0, /* tp_init */ - 0, /* tp_alloc */ - zip_longest_new, /* tp_new */ - PyObject_GC_Del, /* tp_free */ + PyVarObject_HEAD_INIT(NULL, 0) + "itertools.zip_longest", /* tp_name */ + sizeof(ziplongestobject), /* tp_basicsize */ + 0, /* tp_itemsize */ + /* methods */ + (destructor)zip_longest_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 | + Py_TPFLAGS_BASETYPE, /* tp_flags */ + zip_longest_doc, /* tp_doc */ + (traverseproc)zip_longest_traverse, /* tp_traverse */ + 0, /* tp_clear */ + 0, /* tp_richcompare */ + 0, /* tp_weaklistoffset */ + PyObject_SelfIter, /* tp_iter */ + (iternextfunc)zip_longest_next, /* tp_iternext */ + 0, /* tp_methods */ + 0, /* tp_members */ + 0, /* tp_getset */ + 0, /* tp_base */ + 0, /* tp_dict */ + 0, /* tp_descr_get */ + 0, /* tp_descr_set */ + 0, /* tp_dictoffset */ + 0, /* tp_init */ + 0, /* tp_alloc */ + zip_longest_new, /* tp_new */ + PyObject_GC_Del, /* tp_free */ }; /* module level code ********************************************************/ @@ -3516,68 +3516,68 @@ static PyMethodDef module_methods[] = { - {"tee", (PyCFunction)tee, METH_VARARGS, tee_doc}, - {NULL, NULL} /* sentinel */ + {"tee", (PyCFunction)tee, METH_VARARGS, tee_doc}, + {NULL, NULL} /* sentinel */ }; static struct PyModuleDef itertoolsmodule = { - PyModuleDef_HEAD_INIT, - "itertools", - module_doc, - -1, - module_methods, - NULL, - NULL, - NULL, - NULL + PyModuleDef_HEAD_INIT, + "itertools", + module_doc, + -1, + module_methods, + NULL, + NULL, + NULL, + NULL }; PyMODINIT_FUNC PyInit_itertools(void) { - int i; - PyObject *m; - char *name; - PyTypeObject *typelist[] = { - &combinations_type, - &cwr_type, - &cycle_type, - &dropwhile_type, - &takewhile_type, - &islice_type, - &starmap_type, - &chain_type, - &compress_type, - &filterfalse_type, - &count_type, - &ziplongest_type, - &permutations_type, - &product_type, - &repeat_type, - &groupby_type, - NULL - }; - - Py_TYPE(&teedataobject_type) = &PyType_Type; - m = PyModule_Create(&itertoolsmodule); - if (m == NULL) - return NULL; - - for (i=0 ; typelist[i] != NULL ; i++) { - if (PyType_Ready(typelist[i]) < 0) - return NULL; - name = strchr(typelist[i]->tp_name, '.'); - assert (name != NULL); - Py_INCREF(typelist[i]); - PyModule_AddObject(m, name+1, (PyObject *)typelist[i]); - } - - if (PyType_Ready(&teedataobject_type) < 0) - return NULL; - if (PyType_Ready(&tee_type) < 0) - return NULL; - if (PyType_Ready(&_grouper_type) < 0) - return NULL; - return m; + int i; + PyObject *m; + char *name; + PyTypeObject *typelist[] = { + &combinations_type, + &cwr_type, + &cycle_type, + &dropwhile_type, + &takewhile_type, + &islice_type, + &starmap_type, + &chain_type, + &compress_type, + &filterfalse_type, + &count_type, + &ziplongest_type, + &permutations_type, + &product_type, + &repeat_type, + &groupby_type, + NULL + }; + + Py_TYPE(&teedataobject_type) = &PyType_Type; + m = PyModule_Create(&itertoolsmodule); + if (m == NULL) + return NULL; + + for (i=0 ; typelist[i] != NULL ; i++) { + if (PyType_Ready(typelist[i]) < 0) + return NULL; + name = strchr(typelist[i]->tp_name, '.'); + assert (name != NULL); + Py_INCREF(typelist[i]); + PyModule_AddObject(m, name+1, (PyObject *)typelist[i]); + } + + if (PyType_Ready(&teedataobject_type) < 0) + return NULL; + if (PyType_Ready(&tee_type) < 0) + return NULL; + if (PyType_Ready(&_grouper_type) < 0) + return NULL; + return m; } Modified: python/branches/release31-maint/Modules/main.c ============================================================================== --- python/branches/release31-maint/Modules/main.c (original) +++ python/branches/release31-maint/Modules/main.c Sun May 9 18:14:21 2010 @@ -104,20 +104,20 @@ static FILE* _wfopen(const wchar_t *path, const wchar_t *mode) { - char cpath[PATH_MAX]; - char cmode[10]; - size_t r; - r = wcstombs(cpath, path, PATH_MAX); - if (r == (size_t)-1 || r >= PATH_MAX) { - errno = EINVAL; - return NULL; - } - r = wcstombs(cmode, mode, 10); - if (r == (size_t)-1 || r >= 10) { - errno = EINVAL; - return NULL; - } - return fopen(cpath, cmode); + char cpath[PATH_MAX]; + char cmode[10]; + size_t r; + r = wcstombs(cpath, path, PATH_MAX); + if (r == (size_t)-1 || r >= PATH_MAX) { + errno = EINVAL; + return NULL; + } + r = wcstombs(cmode, mode, 10); + if (r == (size_t)-1 || r >= 10) { + errno = EINVAL; + return NULL; + } + return fopen(cpath, cmode); } #endif @@ -125,131 +125,131 @@ static int usage(int exitcode, wchar_t* program) { - FILE *f = exitcode ? stderr : stdout; + FILE *f = exitcode ? stderr : stdout; - fprintf(f, usage_line, program); - if (exitcode) - fprintf(f, "Try `python -h' for more information.\n"); - else { - fputs(usage_1, f); - fputs(usage_2, f); - fputs(usage_3, f); - fprintf(f, usage_4, DELIM); - fprintf(f, usage_5, DELIM, PYTHONHOMEHELP); - } + fprintf(f, usage_line, program); + if (exitcode) + fprintf(f, "Try `python -h' for more information.\n"); + else { + fputs(usage_1, f); + fputs(usage_2, f); + fputs(usage_3, f); + fprintf(f, usage_4, DELIM); + fprintf(f, usage_5, DELIM, PYTHONHOMEHELP); + } #if defined(__VMS) - if (exitcode == 0) { - /* suppress 'error' message */ - return 1; - } - else { - /* STS$M_INHIB_MSG + SS$_ABORT */ - return 0x1000002c; - } + if (exitcode == 0) { + /* suppress 'error' message */ + return 1; + } + else { + /* STS$M_INHIB_MSG + SS$_ABORT */ + return 0x1000002c; + } #else - return exitcode; + return exitcode; #endif - /*NOTREACHED*/ + /*NOTREACHED*/ } static void RunStartupFile(PyCompilerFlags *cf) { - char *startup = Py_GETENV("PYTHONSTARTUP"); - if (startup != NULL && startup[0] != '\0') { - FILE *fp = fopen(startup, "r"); - if (fp != NULL) { - (void) PyRun_SimpleFileExFlags(fp, startup, 0, cf); - PyErr_Clear(); - fclose(fp); - } else { - int save_errno; - - save_errno = errno; - PySys_WriteStderr("Could not open PYTHONSTARTUP\n"); - errno = save_errno; - PyErr_SetFromErrnoWithFilename(PyExc_IOError, - startup); - PyErr_Print(); - PyErr_Clear(); - } - } + char *startup = Py_GETENV("PYTHONSTARTUP"); + if (startup != NULL && startup[0] != '\0') { + FILE *fp = fopen(startup, "r"); + if (fp != NULL) { + (void) PyRun_SimpleFileExFlags(fp, startup, 0, cf); + PyErr_Clear(); + fclose(fp); + } else { + int save_errno; + + save_errno = errno; + PySys_WriteStderr("Could not open PYTHONSTARTUP\n"); + errno = save_errno; + PyErr_SetFromErrnoWithFilename(PyExc_IOError, + startup); + PyErr_Print(); + PyErr_Clear(); + } + } } static int RunModule(wchar_t *modname, int set_argv0) { - PyObject *module, *runpy, *runmodule, *runargs, *result; - runpy = PyImport_ImportModule("runpy"); - if (runpy == NULL) { - fprintf(stderr, "Could not import runpy module\n"); - return -1; - } - runmodule = PyObject_GetAttrString(runpy, "_run_module_as_main"); - if (runmodule == NULL) { - fprintf(stderr, "Could not access runpy._run_module_as_main\n"); - Py_DECREF(runpy); - return -1; - } - module = PyUnicode_FromWideChar(modname, wcslen(modname)); - if (module == NULL) { - fprintf(stderr, "Could not convert module name to unicode\n"); - Py_DECREF(runpy); - Py_DECREF(runmodule); - return -1; - } - runargs = Py_BuildValue("(Oi)", module, set_argv0); - if (runargs == NULL) { - fprintf(stderr, - "Could not create arguments for runpy._run_module_as_main\n"); - Py_DECREF(runpy); - Py_DECREF(runmodule); - Py_DECREF(module); - return -1; - } - result = PyObject_Call(runmodule, runargs, NULL); - if (result == NULL) { - PyErr_Print(); - } - Py_DECREF(runpy); - Py_DECREF(runmodule); - Py_DECREF(module); - Py_DECREF(runargs); - if (result == NULL) { - return -1; - } - Py_DECREF(result); - return 0; + PyObject *module, *runpy, *runmodule, *runargs, *result; + runpy = PyImport_ImportModule("runpy"); + if (runpy == NULL) { + fprintf(stderr, "Could not import runpy module\n"); + return -1; + } + runmodule = PyObject_GetAttrString(runpy, "_run_module_as_main"); + if (runmodule == NULL) { + fprintf(stderr, "Could not access runpy._run_module_as_main\n"); + Py_DECREF(runpy); + return -1; + } + module = PyUnicode_FromWideChar(modname, wcslen(modname)); + if (module == NULL) { + fprintf(stderr, "Could not convert module name to unicode\n"); + Py_DECREF(runpy); + Py_DECREF(runmodule); + return -1; + } + runargs = Py_BuildValue("(Oi)", module, set_argv0); + if (runargs == NULL) { + fprintf(stderr, + "Could not create arguments for runpy._run_module_as_main\n"); + Py_DECREF(runpy); + Py_DECREF(runmodule); + Py_DECREF(module); + return -1; + } + result = PyObject_Call(runmodule, runargs, NULL); + if (result == NULL) { + PyErr_Print(); + } + Py_DECREF(runpy); + Py_DECREF(runmodule); + Py_DECREF(module); + Py_DECREF(runargs); + if (result == NULL) { + return -1; + } + Py_DECREF(result); + return 0; } static int RunMainFromImporter(wchar_t *filename) { - PyObject *argv0 = NULL, *importer = NULL; + PyObject *argv0 = NULL, *importer = NULL; - if ((argv0 = PyUnicode_FromWideChar(filename,wcslen(filename))) && - (importer = PyImport_GetImporter(argv0)) && - (importer->ob_type != &PyNullImporter_Type)) - { - /* argv0 is usable as an import source, so - put it in sys.path[0] and import __main__ */ - PyObject *sys_path = NULL; - if ((sys_path = PySys_GetObject("path")) && - !PyList_SetItem(sys_path, 0, argv0)) - { - Py_INCREF(argv0); - Py_DECREF(importer); - sys_path = NULL; - return RunModule(L"__main__", 0) != 0; - } - } - Py_XDECREF(argv0); - Py_XDECREF(importer); - if (PyErr_Occurred()) { - PyErr_Print(); - return 1; - } - else { - return -1; - } + if ((argv0 = PyUnicode_FromWideChar(filename,wcslen(filename))) && + (importer = PyImport_GetImporter(argv0)) && + (importer->ob_type != &PyNullImporter_Type)) + { + /* argv0 is usable as an import source, so + put it in sys.path[0] and import __main__ */ + PyObject *sys_path = NULL; + if ((sys_path = PySys_GetObject("path")) && + !PyList_SetItem(sys_path, 0, argv0)) + { + Py_INCREF(argv0); + Py_DECREF(importer); + sys_path = NULL; + return RunModule(L"__main__", 0) != 0; + } + } + Py_XDECREF(argv0); + Py_XDECREF(importer); + if (PyErr_Occurred()) { + PyErr_Print(); + return 1; + } + else { + return -1; + } } @@ -258,391 +258,391 @@ int Py_Main(int argc, wchar_t **argv) { - int c; - int sts; - wchar_t *command = NULL; - wchar_t *filename = NULL; - wchar_t *module = NULL; - FILE *fp = stdin; - char *p; - int skipfirstline = 0; - int stdin_is_interactive = 0; - int help = 0; - int version = 0; - int saw_unbuffered_flag = 0; - PyCompilerFlags cf; - - cf.cf_flags = 0; - - orig_argc = argc; /* For Py_GetArgcArgv() */ - orig_argv = argv; - - PySys_ResetWarnOptions(); - - while ((c = _PyOS_GetOpt(argc, argv, PROGRAM_OPTS)) != EOF) { - if (c == 'c') { - size_t len; - /* -c is the last option; following arguments - that look like options are left for the - command to interpret. */ - - len = wcslen(_PyOS_optarg) + 1 + 1; - command = (wchar_t *)malloc(sizeof(wchar_t) * len); - if (command == NULL) - Py_FatalError( - "not enough memory to copy -c argument"); - wcscpy(command, _PyOS_optarg); - command[len - 2] = '\n'; - command[len - 1] = 0; - break; - } - - if (c == 'm') { - /* -m is the last option; following arguments - that look like options are left for the - module to interpret. */ - module = _PyOS_optarg; - break; - } - - switch (c) { - case 'b': - Py_BytesWarningFlag++; - break; - - case 'd': - Py_DebugFlag++; - break; - - case 'i': - Py_InspectFlag++; - Py_InteractiveFlag++; - break; - - /* case 'J': reserved for Jython */ - - case 'O': - Py_OptimizeFlag++; - break; - - case 'B': - Py_DontWriteBytecodeFlag++; - break; - - case 's': - Py_NoUserSiteDirectory++; - break; - - case 'S': - Py_NoSiteFlag++; - break; - - case 'E': - Py_IgnoreEnvironmentFlag++; - break; - - case 't': - /* ignored for backwards compatibility */ - break; - - case 'u': - Py_UnbufferedStdioFlag = 1; - saw_unbuffered_flag = 1; - break; - - case 'v': - Py_VerboseFlag++; - break; - - case 'x': - skipfirstline = 1; - break; - - /* case 'X': reserved for implementation-specific arguments */ - - case 'h': - case '?': - help++; - break; - - case 'V': - version++; - break; - - case 'W': - PySys_AddWarnOption(_PyOS_optarg); - break; - - /* This space reserved for other options */ - - default: - return usage(2, argv[0]); - /*NOTREACHED*/ - - } - } - - if (help) - return usage(0, argv[0]); - - if (version) { - fprintf(stderr, "Python %s\n", PY_VERSION); - return 0; - } - - if (!Py_InspectFlag && - (p = Py_GETENV("PYTHONINSPECT")) && *p != '\0') - Py_InspectFlag = 1; - if (!saw_unbuffered_flag && - (p = Py_GETENV("PYTHONUNBUFFERED")) && *p != '\0') - Py_UnbufferedStdioFlag = 1; - - if (!Py_NoUserSiteDirectory && - (p = Py_GETENV("PYTHONNOUSERSITE")) && *p != '\0') - Py_NoUserSiteDirectory = 1; - - if (command == NULL && module == NULL && _PyOS_optind < argc && - wcscmp(argv[_PyOS_optind], L"-") != 0) - { + int c; + int sts; + wchar_t *command = NULL; + wchar_t *filename = NULL; + wchar_t *module = NULL; + FILE *fp = stdin; + char *p; + int skipfirstline = 0; + int stdin_is_interactive = 0; + int help = 0; + int version = 0; + int saw_unbuffered_flag = 0; + PyCompilerFlags cf; + + cf.cf_flags = 0; + + orig_argc = argc; /* For Py_GetArgcArgv() */ + orig_argv = argv; + + PySys_ResetWarnOptions(); + + while ((c = _PyOS_GetOpt(argc, argv, PROGRAM_OPTS)) != EOF) { + if (c == 'c') { + size_t len; + /* -c is the last option; following arguments + that look like options are left for the + command to interpret. */ + + len = wcslen(_PyOS_optarg) + 1 + 1; + command = (wchar_t *)malloc(sizeof(wchar_t) * len); + if (command == NULL) + Py_FatalError( + "not enough memory to copy -c argument"); + wcscpy(command, _PyOS_optarg); + command[len - 2] = '\n'; + command[len - 1] = 0; + break; + } + + if (c == 'm') { + /* -m is the last option; following arguments + that look like options are left for the + module to interpret. */ + module = _PyOS_optarg; + break; + } + + switch (c) { + case 'b': + Py_BytesWarningFlag++; + break; + + case 'd': + Py_DebugFlag++; + break; + + case 'i': + Py_InspectFlag++; + Py_InteractiveFlag++; + break; + + /* case 'J': reserved for Jython */ + + case 'O': + Py_OptimizeFlag++; + break; + + case 'B': + Py_DontWriteBytecodeFlag++; + break; + + case 's': + Py_NoUserSiteDirectory++; + break; + + case 'S': + Py_NoSiteFlag++; + break; + + case 'E': + Py_IgnoreEnvironmentFlag++; + break; + + case 't': + /* ignored for backwards compatibility */ + break; + + case 'u': + Py_UnbufferedStdioFlag = 1; + saw_unbuffered_flag = 1; + break; + + case 'v': + Py_VerboseFlag++; + break; + + case 'x': + skipfirstline = 1; + break; + + /* case 'X': reserved for implementation-specific arguments */ + + case 'h': + case '?': + help++; + break; + + case 'V': + version++; + break; + + case 'W': + PySys_AddWarnOption(_PyOS_optarg); + break; + + /* This space reserved for other options */ + + default: + return usage(2, argv[0]); + /*NOTREACHED*/ + + } + } + + if (help) + return usage(0, argv[0]); + + if (version) { + fprintf(stderr, "Python %s\n", PY_VERSION); + return 0; + } + + if (!Py_InspectFlag && + (p = Py_GETENV("PYTHONINSPECT")) && *p != '\0') + Py_InspectFlag = 1; + if (!saw_unbuffered_flag && + (p = Py_GETENV("PYTHONUNBUFFERED")) && *p != '\0') + Py_UnbufferedStdioFlag = 1; + + if (!Py_NoUserSiteDirectory && + (p = Py_GETENV("PYTHONNOUSERSITE")) && *p != '\0') + Py_NoUserSiteDirectory = 1; + + if (command == NULL && module == NULL && _PyOS_optind < argc && + wcscmp(argv[_PyOS_optind], L"-") != 0) + { #ifdef __VMS - filename = decc$translate_vms(argv[_PyOS_optind]); - if (filename == (char *)0 || filename == (char *)-1) - filename = argv[_PyOS_optind]; + filename = decc$translate_vms(argv[_PyOS_optind]); + if (filename == (char *)0 || filename == (char *)-1) + filename = argv[_PyOS_optind]; #else - filename = argv[_PyOS_optind]; + filename = argv[_PyOS_optind]; #endif - } + } - stdin_is_interactive = Py_FdIsInteractive(stdin, (char *)0); + stdin_is_interactive = Py_FdIsInteractive(stdin, (char *)0); - if (Py_UnbufferedStdioFlag) { + if (Py_UnbufferedStdioFlag) { #if defined(MS_WINDOWS) || defined(__CYGWIN__) - _setmode(fileno(stdin), O_BINARY); - _setmode(fileno(stdout), O_BINARY); + _setmode(fileno(stdin), O_BINARY); + _setmode(fileno(stdout), O_BINARY); #endif #ifdef HAVE_SETVBUF - setvbuf(stdin, (char *)NULL, _IONBF, BUFSIZ); - setvbuf(stdout, (char *)NULL, _IONBF, BUFSIZ); - setvbuf(stderr, (char *)NULL, _IONBF, BUFSIZ); + setvbuf(stdin, (char *)NULL, _IONBF, BUFSIZ); + setvbuf(stdout, (char *)NULL, _IONBF, BUFSIZ); + setvbuf(stderr, (char *)NULL, _IONBF, BUFSIZ); #else /* !HAVE_SETVBUF */ - setbuf(stdin, (char *)NULL); - setbuf(stdout, (char *)NULL); - setbuf(stderr, (char *)NULL); + setbuf(stdin, (char *)NULL); + setbuf(stdout, (char *)NULL); + setbuf(stderr, (char *)NULL); #endif /* !HAVE_SETVBUF */ - } - else if (Py_InteractiveFlag) { + } + else if (Py_InteractiveFlag) { #ifdef MS_WINDOWS - /* Doesn't have to have line-buffered -- use unbuffered */ - /* Any set[v]buf(stdin, ...) screws up Tkinter :-( */ - setvbuf(stdout, (char *)NULL, _IONBF, BUFSIZ); + /* Doesn't have to have line-buffered -- use unbuffered */ + /* Any set[v]buf(stdin, ...) screws up Tkinter :-( */ + setvbuf(stdout, (char *)NULL, _IONBF, BUFSIZ); #else /* !MS_WINDOWS */ #ifdef HAVE_SETVBUF - setvbuf(stdin, (char *)NULL, _IOLBF, BUFSIZ); - setvbuf(stdout, (char *)NULL, _IOLBF, BUFSIZ); + setvbuf(stdin, (char *)NULL, _IOLBF, BUFSIZ); + setvbuf(stdout, (char *)NULL, _IOLBF, BUFSIZ); #endif /* HAVE_SETVBUF */ #endif /* !MS_WINDOWS */ - /* Leave stderr alone - it should be unbuffered anyway. */ - } + /* Leave stderr alone - it should be unbuffered anyway. */ + } #ifdef __VMS - else { - setvbuf (stdout, (char *)NULL, _IOLBF, BUFSIZ); - } + else { + setvbuf (stdout, (char *)NULL, _IOLBF, BUFSIZ); + } #endif /* __VMS */ #ifdef __APPLE__ - /* On MacOS X, when the Python interpreter is embedded in an - application bundle, it gets executed by a bootstrapping script - that does os.execve() with an argv[0] that's different from the - actual Python executable. This is needed to keep the Finder happy, - or rather, to work around Apple's overly strict requirements of - the process name. However, we still need a usable sys.executable, - so the actual executable path is passed in an environment variable. - See Lib/plat-mac/bundlebuiler.py for details about the bootstrap - script. */ - if ((p = Py_GETENV("PYTHONEXECUTABLE")) && *p != '\0') { - wchar_t* buffer; - size_t len = strlen(p); - size_t r; - - buffer = malloc(len * sizeof(wchar_t)); - if (buffer == NULL) { - Py_FatalError( - "not enough memory to copy PYTHONEXECUTABLE"); - } - - r = mbstowcs(buffer, p, len); - Py_SetProgramName(buffer); - /* buffer is now handed off - do not free */ - } else { - Py_SetProgramName(argv[0]); - } + /* On MacOS X, when the Python interpreter is embedded in an + application bundle, it gets executed by a bootstrapping script + that does os.execve() with an argv[0] that's different from the + actual Python executable. This is needed to keep the Finder happy, + or rather, to work around Apple's overly strict requirements of + the process name. However, we still need a usable sys.executable, + so the actual executable path is passed in an environment variable. + See Lib/plat-mac/bundlebuiler.py for details about the bootstrap + script. */ + if ((p = Py_GETENV("PYTHONEXECUTABLE")) && *p != '\0') { + wchar_t* buffer; + size_t len = strlen(p); + size_t r; + + buffer = malloc(len * sizeof(wchar_t)); + if (buffer == NULL) { + Py_FatalError( + "not enough memory to copy PYTHONEXECUTABLE"); + } + + r = mbstowcs(buffer, p, len); + Py_SetProgramName(buffer); + /* buffer is now handed off - do not free */ + } else { + Py_SetProgramName(argv[0]); + } #else - Py_SetProgramName(argv[0]); + Py_SetProgramName(argv[0]); #endif - Py_Initialize(); + Py_Initialize(); + + if (Py_VerboseFlag || + (command == NULL && filename == NULL && module == NULL && stdin_is_interactive)) { + fprintf(stderr, "Python %s on %s\n", + Py_GetVersion(), Py_GetPlatform()); + if (!Py_NoSiteFlag) + fprintf(stderr, "%s\n", COPYRIGHT); + } + + if (command != NULL) { + /* Backup _PyOS_optind and force sys.argv[0] = '-c' */ + _PyOS_optind--; + argv[_PyOS_optind] = L"-c"; + } + + if (module != NULL) { + /* Backup _PyOS_optind and force sys.argv[0] = '-c' + so that PySys_SetArgv correctly sets sys.path[0] to ''*/ + _PyOS_optind--; + argv[_PyOS_optind] = L"-c"; + } + + PySys_SetArgv(argc-_PyOS_optind, argv+_PyOS_optind); + + if ((Py_InspectFlag || (command == NULL && filename == NULL && module == NULL)) && + isatty(fileno(stdin))) { + PyObject *v; + v = PyImport_ImportModule("readline"); + if (v == NULL) + PyErr_Clear(); + else + Py_DECREF(v); + } + + if (command) { + PyObject *commandObj = PyUnicode_FromWideChar( + command, wcslen(command)); + free(command); + if (commandObj != NULL) { + sts = PyRun_SimpleStringFlags( + _PyUnicode_AsString(commandObj), &cf) != 0; + } + else { + PyErr_Print(); + sts = 1; + } + Py_DECREF(commandObj); + } else if (module) { + sts = RunModule(module, 1); + } + else { + + if (filename == NULL && stdin_is_interactive) { + Py_InspectFlag = 0; /* do exit on SystemExit */ + RunStartupFile(&cf); + } + /* XXX */ + + sts = -1; /* keep track of whether we've already run __main__ */ + + if (filename != NULL) { + sts = RunMainFromImporter(filename); + } + + if (sts==-1 && filename!=NULL) { + if ((fp = _wfopen(filename, L"r")) == NULL) { + char cfilename[PATH_MAX]; + size_t r = wcstombs(cfilename, filename, PATH_MAX); + if (r == PATH_MAX) + /* cfilename is not null-terminated; + * forcefully null-terminating it + * might break the shift state */ + strcpy(cfilename, ""); + if (r == ((size_t)-1)) + strcpy(cfilename, ""); + fprintf(stderr, "%ls: can't open file '%s': [Errno %d] %s\n", + argv[0], cfilename, errno, strerror(errno)); + + return 2; + } + else if (skipfirstline) { + int ch; + /* Push back first newline so line numbers + remain the same */ + while ((ch = getc(fp)) != EOF) { + if (ch == '\n') { + (void)ungetc(ch, fp); + break; + } + } + } + { + /* XXX: does this work on Win/Win64? (see posix_fstat) */ + struct stat sb; + if (fstat(fileno(fp), &sb) == 0 && + S_ISDIR(sb.st_mode)) { + fprintf(stderr, "%ls: '%ls' is a directory, cannot continue\n", argv[0], filename); + fclose(fp); + return 1; + } + } + } + + if (sts==-1) { + PyObject *filenameObj = NULL; + char *p_cfilename = ""; + if (filename) { + filenameObj = PyUnicode_FromWideChar( + filename, wcslen(filename)); + if (filenameObj != NULL) + p_cfilename = _PyUnicode_AsString(filenameObj); + else + p_cfilename = ""; + } + /* call pending calls like signal handlers (SIGINT) */ + if (Py_MakePendingCalls() == -1) { + PyErr_Print(); + sts = 1; + } else { + sts = PyRun_AnyFileExFlags( + fp, + p_cfilename, + filename != NULL, &cf) != 0; + } + Py_XDECREF(filenameObj); + } + + } - if (Py_VerboseFlag || - (command == NULL && filename == NULL && module == NULL && stdin_is_interactive)) { - fprintf(stderr, "Python %s on %s\n", - Py_GetVersion(), Py_GetPlatform()); - if (!Py_NoSiteFlag) - fprintf(stderr, "%s\n", COPYRIGHT); - } - - if (command != NULL) { - /* Backup _PyOS_optind and force sys.argv[0] = '-c' */ - _PyOS_optind--; - argv[_PyOS_optind] = L"-c"; - } - - if (module != NULL) { - /* Backup _PyOS_optind and force sys.argv[0] = '-c' - so that PySys_SetArgv correctly sets sys.path[0] to ''*/ - _PyOS_optind--; - argv[_PyOS_optind] = L"-c"; - } - - PySys_SetArgv(argc-_PyOS_optind, argv+_PyOS_optind); - - if ((Py_InspectFlag || (command == NULL && filename == NULL && module == NULL)) && - isatty(fileno(stdin))) { - PyObject *v; - v = PyImport_ImportModule("readline"); - if (v == NULL) - PyErr_Clear(); - else - Py_DECREF(v); - } - - if (command) { - PyObject *commandObj = PyUnicode_FromWideChar( - command, wcslen(command)); - free(command); - if (commandObj != NULL) { - sts = PyRun_SimpleStringFlags( - _PyUnicode_AsString(commandObj), &cf) != 0; - } - else { - PyErr_Print(); - sts = 1; - } - Py_DECREF(commandObj); - } else if (module) { - sts = RunModule(module, 1); - } - else { - - if (filename == NULL && stdin_is_interactive) { - Py_InspectFlag = 0; /* do exit on SystemExit */ - RunStartupFile(&cf); - } - /* XXX */ - - sts = -1; /* keep track of whether we've already run __main__ */ - - if (filename != NULL) { - sts = RunMainFromImporter(filename); - } - - if (sts==-1 && filename!=NULL) { - if ((fp = _wfopen(filename, L"r")) == NULL) { - char cfilename[PATH_MAX]; - size_t r = wcstombs(cfilename, filename, PATH_MAX); - if (r == PATH_MAX) - /* cfilename is not null-terminated; - * forcefully null-terminating it - * might break the shift state */ - strcpy(cfilename, ""); - if (r == ((size_t)-1)) - strcpy(cfilename, ""); - fprintf(stderr, "%ls: can't open file '%s': [Errno %d] %s\n", - argv[0], cfilename, errno, strerror(errno)); - - return 2; - } - else if (skipfirstline) { - int ch; - /* Push back first newline so line numbers - remain the same */ - while ((ch = getc(fp)) != EOF) { - if (ch == '\n') { - (void)ungetc(ch, fp); - break; - } - } - } - { - /* XXX: does this work on Win/Win64? (see posix_fstat) */ - struct stat sb; - if (fstat(fileno(fp), &sb) == 0 && - S_ISDIR(sb.st_mode)) { - fprintf(stderr, "%ls: '%ls' is a directory, cannot continue\n", argv[0], filename); - fclose(fp); - return 1; - } - } - } - - if (sts==-1) { - PyObject *filenameObj = NULL; - char *p_cfilename = ""; - if (filename) { - filenameObj = PyUnicode_FromWideChar( - filename, wcslen(filename)); - if (filenameObj != NULL) - p_cfilename = _PyUnicode_AsString(filenameObj); - else - p_cfilename = ""; - } - /* call pending calls like signal handlers (SIGINT) */ - if (Py_MakePendingCalls() == -1) { - PyErr_Print(); - sts = 1; - } else { - sts = PyRun_AnyFileExFlags( - fp, - p_cfilename, - filename != NULL, &cf) != 0; - } - Py_XDECREF(filenameObj); - } - - } - - /* Check this environment variable at the end, to give programs the - * opportunity to set it from Python. - */ - if (!Py_InspectFlag && - (p = Py_GETENV("PYTHONINSPECT")) && *p != '\0') - { - Py_InspectFlag = 1; - } - - if (Py_InspectFlag && stdin_is_interactive && - (filename != NULL || command != NULL || module != NULL)) { - Py_InspectFlag = 0; - /* XXX */ - sts = PyRun_AnyFileFlags(stdin, "", &cf) != 0; - } + /* Check this environment variable at the end, to give programs the + * opportunity to set it from Python. + */ + if (!Py_InspectFlag && + (p = Py_GETENV("PYTHONINSPECT")) && *p != '\0') + { + Py_InspectFlag = 1; + } + + if (Py_InspectFlag && stdin_is_interactive && + (filename != NULL || command != NULL || module != NULL)) { + Py_InspectFlag = 0; + /* XXX */ + sts = PyRun_AnyFileFlags(stdin, "", &cf) != 0; + } - Py_Finalize(); + Py_Finalize(); #ifdef __INSURE__ - /* Insure++ is a memory analysis tool that aids in discovering - * memory leaks and other memory problems. On Python exit, the - * interned string dictionaries are flagged as being in use at exit - * (which it is). Under normal circumstances, this is fine because - * the memory will be automatically reclaimed by the system. Under - * memory debugging, it's a huge source of useless noise, so we - * trade off slower shutdown for less distraction in the memory - * reports. -baw - */ - _Py_ReleaseInternedStrings(); - _Py_ReleaseInternedUnicodeStrings(); + /* Insure++ is a memory analysis tool that aids in discovering + * memory leaks and other memory problems. On Python exit, the + * interned string dictionaries are flagged as being in use at exit + * (which it is). Under normal circumstances, this is fine because + * the memory will be automatically reclaimed by the system. Under + * memory debugging, it's a huge source of useless noise, so we + * trade off slower shutdown for less distraction in the memory + * reports. -baw + */ + _Py_ReleaseInternedStrings(); + _Py_ReleaseInternedUnicodeStrings(); #endif /* __INSURE__ */ - return sts; + return sts; } /* this is gonna seem *real weird*, but if you put some other code between @@ -655,8 +655,8 @@ void Py_GetArgcArgv(int *argc, wchar_t ***argv) { - *argc = orig_argc; - *argv = orig_argv; + *argc = orig_argc; + *argv = orig_argv; } #ifdef __cplusplus Modified: python/branches/release31-maint/Modules/mathmodule.c ============================================================================== --- python/branches/release31-maint/Modules/mathmodule.c (original) +++ python/branches/release31-maint/Modules/mathmodule.c Sun May 9 18:14:21 2010 @@ -67,37 +67,37 @@ static int is_error(double x) { - int result = 1; /* presumption of guilt */ - assert(errno); /* non-zero errno is a precondition for calling */ - if (errno == EDOM) - PyErr_SetString(PyExc_ValueError, "math domain error"); - - else if (errno == ERANGE) { - /* ANSI C generally requires libm functions to set ERANGE - * on overflow, but also generally *allows* them to set - * ERANGE on underflow too. There's no consistency about - * the latter across platforms. - * Alas, C99 never requires that errno be set. - * Here we suppress the underflow errors (libm functions - * should return a zero on underflow, and +- HUGE_VAL on - * overflow, so testing the result for zero suffices to - * distinguish the cases). - * - * On some platforms (Ubuntu/ia64) it seems that errno can be - * set to ERANGE for subnormal results that do *not* underflow - * to zero. So to be safe, we'll ignore ERANGE whenever the - * function result is less than one in absolute value. - */ - if (fabs(x) < 1.0) - result = 0; - else - PyErr_SetString(PyExc_OverflowError, - "math range error"); - } - else - /* Unexpected math error */ - PyErr_SetFromErrno(PyExc_ValueError); - return result; + int result = 1; /* presumption of guilt */ + assert(errno); /* non-zero errno is a precondition for calling */ + if (errno == EDOM) + PyErr_SetString(PyExc_ValueError, "math domain error"); + + else if (errno == ERANGE) { + /* ANSI C generally requires libm functions to set ERANGE + * on overflow, but also generally *allows* them to set + * ERANGE on underflow too. There's no consistency about + * the latter across platforms. + * Alas, C99 never requires that errno be set. + * Here we suppress the underflow errors (libm functions + * should return a zero on underflow, and +- HUGE_VAL on + * overflow, so testing the result for zero suffices to + * distinguish the cases). + * + * On some platforms (Ubuntu/ia64) it seems that errno can be + * set to ERANGE for subnormal results that do *not* underflow + * to zero. So to be safe, we'll ignore ERANGE whenever the + * function result is less than one in absolute value. + */ + if (fabs(x) < 1.0) + result = 0; + else + PyErr_SetString(PyExc_OverflowError, + "math range error"); + } + else + /* Unexpected math error */ + PyErr_SetFromErrno(PyExc_ValueError); + return result; } /* @@ -111,29 +111,29 @@ static double m_atan2(double y, double x) { - if (Py_IS_NAN(x) || Py_IS_NAN(y)) - return Py_NAN; - if (Py_IS_INFINITY(y)) { - if (Py_IS_INFINITY(x)) { - if (copysign(1., x) == 1.) - /* atan2(+-inf, +inf) == +-pi/4 */ - return copysign(0.25*Py_MATH_PI, y); - else - /* atan2(+-inf, -inf) == +-pi*3/4 */ - return copysign(0.75*Py_MATH_PI, y); - } - /* atan2(+-inf, x) == +-pi/2 for finite x */ - return copysign(0.5*Py_MATH_PI, y); - } - if (Py_IS_INFINITY(x) || y == 0.) { - if (copysign(1., x) == 1.) - /* atan2(+-y, +inf) = atan2(+-0, +x) = +-0. */ - return copysign(0., y); - else - /* atan2(+-y, -inf) = atan2(+-0., -x) = +-pi. */ - return copysign(Py_MATH_PI, y); - } - return atan2(y, x); + if (Py_IS_NAN(x) || Py_IS_NAN(y)) + return Py_NAN; + if (Py_IS_INFINITY(y)) { + if (Py_IS_INFINITY(x)) { + if (copysign(1., x) == 1.) + /* atan2(+-inf, +inf) == +-pi/4 */ + return copysign(0.25*Py_MATH_PI, y); + else + /* atan2(+-inf, -inf) == +-pi*3/4 */ + return copysign(0.75*Py_MATH_PI, y); + } + /* atan2(+-inf, x) == +-pi/2 for finite x */ + return copysign(0.5*Py_MATH_PI, y); + } + if (Py_IS_INFINITY(x) || y == 0.) { + if (copysign(1., x) == 1.) + /* atan2(+-y, +inf) = atan2(+-0, +x) = +-0. */ + return copysign(0., y); + else + /* atan2(+-y, -inf) = atan2(+-0., -x) = +-pi. */ + return copysign(Py_MATH_PI, y); + } + return atan2(y, x); } /* @@ -146,45 +146,45 @@ static double m_log(double x) { - if (Py_IS_FINITE(x)) { - if (x > 0.0) - return log(x); - errno = EDOM; - if (x == 0.0) - return -Py_HUGE_VAL; /* log(0) = -inf */ - else - return Py_NAN; /* log(-ve) = nan */ - } - else if (Py_IS_NAN(x)) - return x; /* log(nan) = nan */ - else if (x > 0.0) - return x; /* log(inf) = inf */ - else { - errno = EDOM; - return Py_NAN; /* log(-inf) = nan */ - } + if (Py_IS_FINITE(x)) { + if (x > 0.0) + return log(x); + errno = EDOM; + if (x == 0.0) + return -Py_HUGE_VAL; /* log(0) = -inf */ + else + return Py_NAN; /* log(-ve) = nan */ + } + else if (Py_IS_NAN(x)) + return x; /* log(nan) = nan */ + else if (x > 0.0) + return x; /* log(inf) = inf */ + else { + errno = EDOM; + return Py_NAN; /* log(-inf) = nan */ + } } static double m_log10(double x) { - if (Py_IS_FINITE(x)) { - if (x > 0.0) - return log10(x); - errno = EDOM; - if (x == 0.0) - return -Py_HUGE_VAL; /* log10(0) = -inf */ - else - return Py_NAN; /* log10(-ve) = nan */ - } - else if (Py_IS_NAN(x)) - return x; /* log10(nan) = nan */ - else if (x > 0.0) - return x; /* log10(inf) = inf */ - else { - errno = EDOM; - return Py_NAN; /* log10(-inf) = nan */ - } + if (Py_IS_FINITE(x)) { + if (x > 0.0) + return log10(x); + errno = EDOM; + if (x == 0.0) + return -Py_HUGE_VAL; /* log10(0) = -inf */ + else + return Py_NAN; /* log10(-ve) = nan */ + } + else if (Py_IS_NAN(x)) + return x; /* log10(nan) = nan */ + else if (x > 0.0) + return x; /* log10(inf) = inf */ + else { + errno = EDOM; + return Py_NAN; /* log10(-inf) = nan */ + } } @@ -223,33 +223,33 @@ PyObject *(*from_double_func) (double), int can_overflow) { - double x, r; - x = PyFloat_AsDouble(arg); - if (x == -1.0 && PyErr_Occurred()) - return NULL; - errno = 0; - PyFPE_START_PROTECT("in math_1", return 0); - r = (*func)(x); - PyFPE_END_PROTECT(r); - if (Py_IS_NAN(r) && !Py_IS_NAN(x)) { - PyErr_SetString(PyExc_ValueError, - "math domain error"); /* invalid arg */ - return NULL; - } - if (Py_IS_INFINITY(r) && Py_IS_FINITE(x)) { - if (can_overflow) - PyErr_SetString(PyExc_OverflowError, - "math range error"); /* overflow */ - else - PyErr_SetString(PyExc_ValueError, - "math domain error"); /* singularity */ - return NULL; - } - if (Py_IS_FINITE(r) && errno && is_error(r)) - /* this branch unnecessary on most platforms */ - return NULL; + double x, r; + x = PyFloat_AsDouble(arg); + if (x == -1.0 && PyErr_Occurred()) + return NULL; + errno = 0; + PyFPE_START_PROTECT("in math_1", return 0); + r = (*func)(x); + PyFPE_END_PROTECT(r); + if (Py_IS_NAN(r) && !Py_IS_NAN(x)) { + PyErr_SetString(PyExc_ValueError, + "math domain error"); /* invalid arg */ + return NULL; + } + if (Py_IS_INFINITY(r) && Py_IS_FINITE(x)) { + if (can_overflow) + PyErr_SetString(PyExc_OverflowError, + "math range error"); /* overflow */ + else + PyErr_SetString(PyExc_ValueError, + "math domain error"); /* singularity */ + return NULL; + } + if (Py_IS_FINITE(r) && errno && is_error(r)) + /* this branch unnecessary on most platforms */ + return NULL; - return (*from_double_func)(r); + return (*from_double_func)(r); } /* @@ -282,59 +282,59 @@ static PyObject * math_1(PyObject *arg, double (*func) (double), int can_overflow) { - return math_1_to_whatever(arg, func, PyFloat_FromDouble, can_overflow); + return math_1_to_whatever(arg, func, PyFloat_FromDouble, can_overflow); } static PyObject * math_1_to_int(PyObject *arg, double (*func) (double), int can_overflow) { - return math_1_to_whatever(arg, func, PyLong_FromDouble, can_overflow); + return math_1_to_whatever(arg, func, PyLong_FromDouble, can_overflow); } static PyObject * math_2(PyObject *args, double (*func) (double, double), char *funcname) { - PyObject *ox, *oy; - double x, y, r; - if (! PyArg_UnpackTuple(args, funcname, 2, 2, &ox, &oy)) - return NULL; - x = PyFloat_AsDouble(ox); - y = PyFloat_AsDouble(oy); - if ((x == -1.0 || y == -1.0) && PyErr_Occurred()) - return NULL; - errno = 0; - PyFPE_START_PROTECT("in math_2", return 0); - r = (*func)(x, y); - PyFPE_END_PROTECT(r); - if (Py_IS_NAN(r)) { - if (!Py_IS_NAN(x) && !Py_IS_NAN(y)) - errno = EDOM; - else - errno = 0; - } - else if (Py_IS_INFINITY(r)) { - if (Py_IS_FINITE(x) && Py_IS_FINITE(y)) - errno = ERANGE; - else - errno = 0; - } - if (errno && is_error(r)) - return NULL; - else - return PyFloat_FromDouble(r); -} - -#define FUNC1(funcname, func, can_overflow, docstring) \ - static PyObject * math_##funcname(PyObject *self, PyObject *args) { \ - return math_1(args, func, can_overflow); \ - }\ - PyDoc_STRVAR(math_##funcname##_doc, docstring); + PyObject *ox, *oy; + double x, y, r; + if (! PyArg_UnpackTuple(args, funcname, 2, 2, &ox, &oy)) + return NULL; + x = PyFloat_AsDouble(ox); + y = PyFloat_AsDouble(oy); + if ((x == -1.0 || y == -1.0) && PyErr_Occurred()) + return NULL; + errno = 0; + PyFPE_START_PROTECT("in math_2", return 0); + r = (*func)(x, y); + PyFPE_END_PROTECT(r); + if (Py_IS_NAN(r)) { + if (!Py_IS_NAN(x) && !Py_IS_NAN(y)) + errno = EDOM; + else + errno = 0; + } + else if (Py_IS_INFINITY(r)) { + if (Py_IS_FINITE(x) && Py_IS_FINITE(y)) + errno = ERANGE; + else + errno = 0; + } + if (errno && is_error(r)) + return NULL; + else + return PyFloat_FromDouble(r); +} + +#define FUNC1(funcname, func, can_overflow, docstring) \ + static PyObject * math_##funcname(PyObject *self, PyObject *args) { \ + return math_1(args, func, can_overflow); \ + }\ + PyDoc_STRVAR(math_##funcname##_doc, docstring); #define FUNC2(funcname, func, docstring) \ - static PyObject * math_##funcname(PyObject *self, PyObject *args) { \ - return math_2(args, func, #funcname); \ - }\ - PyDoc_STRVAR(math_##funcname##_doc, docstring); + static PyObject * math_##funcname(PyObject *self, PyObject *args) { \ + return math_2(args, func, #funcname); \ + }\ + PyDoc_STRVAR(math_##funcname##_doc, docstring); FUNC1(acos, acos, 0, "acos(x)\n\nReturn the arc cosine (measured in radians) of x.") @@ -353,25 +353,25 @@ "atanh(x)\n\nReturn the hyperbolic arc tangent (measured in radians) of x.") static PyObject * math_ceil(PyObject *self, PyObject *number) { - static PyObject *ceil_str = NULL; - PyObject *method; + static PyObject *ceil_str = NULL; + PyObject *method; - if (ceil_str == NULL) { - ceil_str = PyUnicode_InternFromString("__ceil__"); - if (ceil_str == NULL) - return NULL; - } - - method = _PyType_Lookup(Py_TYPE(number), ceil_str); - if (method == NULL) - return math_1_to_int(number, ceil, 0); - else - return PyObject_CallFunction(method, "O", number); + if (ceil_str == NULL) { + ceil_str = PyUnicode_InternFromString("__ceil__"); + if (ceil_str == NULL) + return NULL; + } + + method = _PyType_Lookup(Py_TYPE(number), ceil_str); + if (method == NULL) + return math_1_to_int(number, ceil, 0); + else + return PyObject_CallFunction(method, "O", number); } PyDoc_STRVAR(math_ceil_doc, - "ceil(x)\n\nReturn the ceiling of x as an int.\n" - "This is the smallest integral value >= x."); + "ceil(x)\n\nReturn the ceiling of x as an int.\n" + "This is the smallest integral value >= x."); FUNC2(copysign, copysign, "copysign(x, y)\n\nReturn x with the sign of y.") @@ -385,25 +385,25 @@ "fabs(x)\n\nReturn the absolute value of the float x.") static PyObject * math_floor(PyObject *self, PyObject *number) { - static PyObject *floor_str = NULL; - PyObject *method; + static PyObject *floor_str = NULL; + PyObject *method; - if (floor_str == NULL) { - floor_str = PyUnicode_InternFromString("__floor__"); - if (floor_str == NULL) - return NULL; - } - - method = _PyType_Lookup(Py_TYPE(number), floor_str); - if (method == NULL) - return math_1_to_int(number, floor, 0); - else - return PyObject_CallFunction(method, "O", number); + if (floor_str == NULL) { + floor_str = PyUnicode_InternFromString("__floor__"); + if (floor_str == NULL) + return NULL; + } + + method = _PyType_Lookup(Py_TYPE(number), floor_str); + if (method == NULL) + return math_1_to_int(number, floor, 0); + else + return PyObject_CallFunction(method, "O", number); } PyDoc_STRVAR(math_floor_doc, - "floor(x)\n\nReturn the floor of x as an int.\n" - "This is the largest integral value <= x."); + "floor(x)\n\nReturn the floor of x as an int.\n" + "This is the largest integral value <= x."); FUNC1(log1p, log1p, 1, "log1p(x)\n\nReturn the natural logarithm of 1+x (base e).\n" @@ -439,7 +439,7 @@ Also, the volatile declaration forces the values to be stored in memory as regular doubles instead of extended long precision (80-bit) values. This prevents double rounding because any addition or subtraction of two doubles - can be resolved exactly into double-sized hi and lo values. As long as the + can be resolved exactly into double-sized hi and lo values. As long as the hi value gets forced into a double before yr and lo are computed, the extra bits in downstream extended precision operations (x87 for example) will be exactly zero and therefore can be losslessly stored back into a double, @@ -462,27 +462,27 @@ _fsum_realloc(double **p_ptr, Py_ssize_t n, double *ps, Py_ssize_t *m_ptr) { - void *v = NULL; - Py_ssize_t m = *m_ptr; + void *v = NULL; + Py_ssize_t m = *m_ptr; - m += m; /* double */ - if (n < m && m < (PY_SSIZE_T_MAX / sizeof(double))) { - double *p = *p_ptr; - if (p == ps) { - v = PyMem_Malloc(sizeof(double) * m); - if (v != NULL) - memcpy(v, ps, sizeof(double) * n); - } - else - v = PyMem_Realloc(p, sizeof(double) * m); - } - if (v == NULL) { /* size overflow or no memory */ - PyErr_SetString(PyExc_MemoryError, "math.fsum partials"); - return 1; - } - *p_ptr = (double*) v; - *m_ptr = m; - return 0; + m += m; /* double */ + if (n < m && m < (PY_SSIZE_T_MAX / sizeof(double))) { + double *p = *p_ptr; + if (p == ps) { + v = PyMem_Malloc(sizeof(double) * m); + if (v != NULL) + memcpy(v, ps, sizeof(double) * n); + } + else + v = PyMem_Realloc(p, sizeof(double) * m); + } + if (v == NULL) { /* size overflow or no memory */ + PyErr_SetString(PyExc_MemoryError, "math.fsum partials"); + return 1; + } + *p_ptr = (double*) v; + *m_ptr = m; + return 0; } /* Full precision summation of a sequence of floats. @@ -490,17 +490,17 @@ def msum(iterable): partials = [] # sorted, non-overlapping partial sums for x in iterable: - i = 0 - for y in partials: - if abs(x) < abs(y): - x, y = y, x - hi = x + y - lo = y - (hi - x) - if lo: - partials[i] = lo - i += 1 - x = hi - partials[i:] = [x] + i = 0 + for y in partials: + if abs(x) < abs(y): + x, y = y, x + hi = x + y + lo = y - (hi - x) + if lo: + partials[i] = lo + i += 1 + x = hi + partials[i:] = [x] return sum_exact(partials) Rounded x+y stored in hi with the roundoff stored in lo. Together hi+lo @@ -518,119 +518,119 @@ static PyObject* math_fsum(PyObject *self, PyObject *seq) { - PyObject *item, *iter, *sum = NULL; - Py_ssize_t i, j, n = 0, m = NUM_PARTIALS; - double x, y, t, ps[NUM_PARTIALS], *p = ps; - double xsave, special_sum = 0.0, inf_sum = 0.0; - volatile double hi, yr, lo; - - iter = PyObject_GetIter(seq); - if (iter == NULL) - return NULL; - - PyFPE_START_PROTECT("fsum", Py_DECREF(iter); return NULL) - - for(;;) { /* for x in iterable */ - assert(0 <= n && n <= m); - assert((m == NUM_PARTIALS && p == ps) || - (m > NUM_PARTIALS && p != NULL)); - - item = PyIter_Next(iter); - if (item == NULL) { - if (PyErr_Occurred()) - goto _fsum_error; - break; - } - x = PyFloat_AsDouble(item); - Py_DECREF(item); - if (PyErr_Occurred()) - goto _fsum_error; - - xsave = x; - for (i = j = 0; j < n; j++) { /* for y in partials */ - y = p[j]; - if (fabs(x) < fabs(y)) { - t = x; x = y; y = t; - } - hi = x + y; - yr = hi - x; - lo = y - yr; - if (lo != 0.0) - p[i++] = lo; - x = hi; - } - - n = i; /* ps[i:] = [x] */ - if (x != 0.0) { - if (! Py_IS_FINITE(x)) { - /* a nonfinite x could arise either as - a result of intermediate overflow, or - as a result of a nan or inf in the - summands */ - if (Py_IS_FINITE(xsave)) { - PyErr_SetString(PyExc_OverflowError, - "intermediate overflow in fsum"); - goto _fsum_error; - } - if (Py_IS_INFINITY(xsave)) - inf_sum += xsave; - special_sum += xsave; - /* reset partials */ - n = 0; - } - else if (n >= m && _fsum_realloc(&p, n, ps, &m)) - goto _fsum_error; - else - p[n++] = x; - } - } - - if (special_sum != 0.0) { - if (Py_IS_NAN(inf_sum)) - PyErr_SetString(PyExc_ValueError, - "-inf + inf in fsum"); - else - sum = PyFloat_FromDouble(special_sum); - goto _fsum_error; - } - - hi = 0.0; - if (n > 0) { - hi = p[--n]; - /* sum_exact(ps, hi) from the top, stop when the sum becomes - inexact. */ - while (n > 0) { - x = hi; - y = p[--n]; - assert(fabs(y) < fabs(x)); - hi = x + y; - yr = hi - x; - lo = y - yr; - if (lo != 0.0) - break; - } - /* Make half-even rounding work across multiple partials. - Needed so that sum([1e-16, 1, 1e16]) will round-up the last - digit to two instead of down to zero (the 1e-16 makes the 1 - slightly closer to two). With a potential 1 ULP rounding - error fixed-up, math.fsum() can guarantee commutativity. */ - if (n > 0 && ((lo < 0.0 && p[n-1] < 0.0) || - (lo > 0.0 && p[n-1] > 0.0))) { - y = lo * 2.0; - x = hi + y; - yr = x - hi; - if (y == yr) - hi = x; - } - } - sum = PyFloat_FromDouble(hi); + PyObject *item, *iter, *sum = NULL; + Py_ssize_t i, j, n = 0, m = NUM_PARTIALS; + double x, y, t, ps[NUM_PARTIALS], *p = ps; + double xsave, special_sum = 0.0, inf_sum = 0.0; + volatile double hi, yr, lo; + + iter = PyObject_GetIter(seq); + if (iter == NULL) + return NULL; + + PyFPE_START_PROTECT("fsum", Py_DECREF(iter); return NULL) + + for(;;) { /* for x in iterable */ + assert(0 <= n && n <= m); + assert((m == NUM_PARTIALS && p == ps) || + (m > NUM_PARTIALS && p != NULL)); + + item = PyIter_Next(iter); + if (item == NULL) { + if (PyErr_Occurred()) + goto _fsum_error; + break; + } + x = PyFloat_AsDouble(item); + Py_DECREF(item); + if (PyErr_Occurred()) + goto _fsum_error; + + xsave = x; + for (i = j = 0; j < n; j++) { /* for y in partials */ + y = p[j]; + if (fabs(x) < fabs(y)) { + t = x; x = y; y = t; + } + hi = x + y; + yr = hi - x; + lo = y - yr; + if (lo != 0.0) + p[i++] = lo; + x = hi; + } + + n = i; /* ps[i:] = [x] */ + if (x != 0.0) { + if (! Py_IS_FINITE(x)) { + /* a nonfinite x could arise either as + a result of intermediate overflow, or + as a result of a nan or inf in the + summands */ + if (Py_IS_FINITE(xsave)) { + PyErr_SetString(PyExc_OverflowError, + "intermediate overflow in fsum"); + goto _fsum_error; + } + if (Py_IS_INFINITY(xsave)) + inf_sum += xsave; + special_sum += xsave; + /* reset partials */ + n = 0; + } + else if (n >= m && _fsum_realloc(&p, n, ps, &m)) + goto _fsum_error; + else + p[n++] = x; + } + } + + if (special_sum != 0.0) { + if (Py_IS_NAN(inf_sum)) + PyErr_SetString(PyExc_ValueError, + "-inf + inf in fsum"); + else + sum = PyFloat_FromDouble(special_sum); + goto _fsum_error; + } + + hi = 0.0; + if (n > 0) { + hi = p[--n]; + /* sum_exact(ps, hi) from the top, stop when the sum becomes + inexact. */ + while (n > 0) { + x = hi; + y = p[--n]; + assert(fabs(y) < fabs(x)); + hi = x + y; + yr = hi - x; + lo = y - yr; + if (lo != 0.0) + break; + } + /* Make half-even rounding work across multiple partials. + Needed so that sum([1e-16, 1, 1e16]) will round-up the last + digit to two instead of down to zero (the 1e-16 makes the 1 + slightly closer to two). With a potential 1 ULP rounding + error fixed-up, math.fsum() can guarantee commutativity. */ + if (n > 0 && ((lo < 0.0 && p[n-1] < 0.0) || + (lo > 0.0 && p[n-1] > 0.0))) { + y = lo * 2.0; + x = hi + y; + yr = x - hi; + if (y == yr) + hi = x; + } + } + sum = PyFloat_FromDouble(hi); _fsum_error: - PyFPE_END_PROTECT(hi) - Py_DECREF(iter); - if (p != ps) - PyMem_Free(p); - return sum; + PyFPE_END_PROTECT(hi) + Py_DECREF(iter); + if (p != ps) + PyMem_Free(p); + return sum; } #undef NUM_PARTIALS @@ -643,46 +643,46 @@ static PyObject * math_factorial(PyObject *self, PyObject *arg) { - long i, x; - PyObject *result, *iobj, *newresult; + long i, x; + PyObject *result, *iobj, *newresult; - if (PyFloat_Check(arg)) { - double dx = PyFloat_AS_DOUBLE((PyFloatObject *)arg); - if (dx != floor(dx)) { - PyErr_SetString(PyExc_ValueError, - "factorial() only accepts integral values"); - return NULL; - } - } - - x = PyLong_AsLong(arg); - if (x == -1 && PyErr_Occurred()) - return NULL; - if (x < 0) { - PyErr_SetString(PyExc_ValueError, - "factorial() not defined for negative values"); - return NULL; - } - - result = (PyObject *)PyLong_FromLong(1); - if (result == NULL) - return NULL; - for (i=1 ; i<=x ; i++) { - iobj = (PyObject *)PyLong_FromLong(i); - if (iobj == NULL) - goto error; - newresult = PyNumber_Multiply(result, iobj); - Py_DECREF(iobj); - if (newresult == NULL) - goto error; - Py_DECREF(result); - result = newresult; - } - return result; + if (PyFloat_Check(arg)) { + double dx = PyFloat_AS_DOUBLE((PyFloatObject *)arg); + if (dx != floor(dx)) { + PyErr_SetString(PyExc_ValueError, + "factorial() only accepts integral values"); + return NULL; + } + } + + x = PyLong_AsLong(arg); + if (x == -1 && PyErr_Occurred()) + return NULL; + if (x < 0) { + PyErr_SetString(PyExc_ValueError, + "factorial() not defined for negative values"); + return NULL; + } + + result = (PyObject *)PyLong_FromLong(1); + if (result == NULL) + return NULL; + for (i=1 ; i<=x ; i++) { + iobj = (PyObject *)PyLong_FromLong(i); + if (iobj == NULL) + goto error; + newresult = PyNumber_Multiply(result, iobj); + Py_DECREF(iobj); + if (newresult == NULL) + goto error; + Py_DECREF(result); + result = newresult; + } + return result; error: - Py_DECREF(result); - return NULL; + Py_DECREF(result); + return NULL; } PyDoc_STRVAR(math_factorial_doc, @@ -693,28 +693,28 @@ static PyObject * math_trunc(PyObject *self, PyObject *number) { - static PyObject *trunc_str = NULL; - PyObject *trunc; + static PyObject *trunc_str = NULL; + PyObject *trunc; - if (Py_TYPE(number)->tp_dict == NULL) { - if (PyType_Ready(Py_TYPE(number)) < 0) - return NULL; - } - - if (trunc_str == NULL) { - trunc_str = PyUnicode_InternFromString("__trunc__"); - if (trunc_str == NULL) - return NULL; - } - - trunc = _PyType_Lookup(Py_TYPE(number), trunc_str); - if (trunc == NULL) { - PyErr_Format(PyExc_TypeError, - "type %.100s doesn't define __trunc__ method", - Py_TYPE(number)->tp_name); - return NULL; - } - return PyObject_CallFunctionObjArgs(trunc, number, NULL); + if (Py_TYPE(number)->tp_dict == NULL) { + if (PyType_Ready(Py_TYPE(number)) < 0) + return NULL; + } + + if (trunc_str == NULL) { + trunc_str = PyUnicode_InternFromString("__trunc__"); + if (trunc_str == NULL) + return NULL; + } + + trunc = _PyType_Lookup(Py_TYPE(number), trunc_str); + if (trunc == NULL) { + PyErr_Format(PyExc_TypeError, + "type %.100s doesn't define __trunc__ method", + Py_TYPE(number)->tp_name); + return NULL; + } + return PyObject_CallFunctionObjArgs(trunc, number, NULL); } PyDoc_STRVAR(math_trunc_doc, @@ -725,21 +725,21 @@ static PyObject * math_frexp(PyObject *self, PyObject *arg) { - int i; - double x = PyFloat_AsDouble(arg); - if (x == -1.0 && PyErr_Occurred()) - return NULL; - /* deal with special cases directly, to sidestep platform - differences */ - if (Py_IS_NAN(x) || Py_IS_INFINITY(x) || !x) { - i = 0; - } - else { - PyFPE_START_PROTECT("in math_frexp", return 0); - x = frexp(x, &i); - PyFPE_END_PROTECT(x); - } - return Py_BuildValue("(di)", x, i); + int i; + double x = PyFloat_AsDouble(arg); + if (x == -1.0 && PyErr_Occurred()) + return NULL; + /* deal with special cases directly, to sidestep platform + differences */ + if (Py_IS_NAN(x) || Py_IS_INFINITY(x) || !x) { + i = 0; + } + else { + PyFPE_START_PROTECT("in math_frexp", return 0); + x = frexp(x, &i); + PyFPE_END_PROTECT(x); + } + return Py_BuildValue("(di)", x, i); } PyDoc_STRVAR(math_frexp_doc, @@ -752,63 +752,63 @@ static PyObject * math_ldexp(PyObject *self, PyObject *args) { - double x, r; - PyObject *oexp; - long exp; - if (! PyArg_ParseTuple(args, "dO:ldexp", &x, &oexp)) - return NULL; - - if (PyLong_Check(oexp)) { - /* on overflow, replace exponent with either LONG_MAX - or LONG_MIN, depending on the sign. */ - exp = PyLong_AsLong(oexp); - if (exp == -1 && PyErr_Occurred()) { - if (PyErr_ExceptionMatches(PyExc_OverflowError)) { - if (Py_SIZE(oexp) < 0) { - exp = LONG_MIN; - } - else { - exp = LONG_MAX; - } - PyErr_Clear(); - } - else { - /* propagate any unexpected exception */ - return NULL; - } - } - } - else { - PyErr_SetString(PyExc_TypeError, - "Expected an int or long as second argument " - "to ldexp."); - return NULL; - } - - if (x == 0. || !Py_IS_FINITE(x)) { - /* NaNs, zeros and infinities are returned unchanged */ - r = x; - errno = 0; - } else if (exp > INT_MAX) { - /* overflow */ - r = copysign(Py_HUGE_VAL, x); - errno = ERANGE; - } else if (exp < INT_MIN) { - /* underflow to +-0 */ - r = copysign(0., x); - errno = 0; - } else { - errno = 0; - PyFPE_START_PROTECT("in math_ldexp", return 0); - r = ldexp(x, (int)exp); - PyFPE_END_PROTECT(r); - if (Py_IS_INFINITY(r)) - errno = ERANGE; - } - - if (errno && is_error(r)) - return NULL; - return PyFloat_FromDouble(r); + double x, r; + PyObject *oexp; + long exp; + if (! PyArg_ParseTuple(args, "dO:ldexp", &x, &oexp)) + return NULL; + + if (PyLong_Check(oexp)) { + /* on overflow, replace exponent with either LONG_MAX + or LONG_MIN, depending on the sign. */ + exp = PyLong_AsLong(oexp); + if (exp == -1 && PyErr_Occurred()) { + if (PyErr_ExceptionMatches(PyExc_OverflowError)) { + if (Py_SIZE(oexp) < 0) { + exp = LONG_MIN; + } + else { + exp = LONG_MAX; + } + PyErr_Clear(); + } + else { + /* propagate any unexpected exception */ + return NULL; + } + } + } + else { + PyErr_SetString(PyExc_TypeError, + "Expected an int or long as second argument " + "to ldexp."); + return NULL; + } + + if (x == 0. || !Py_IS_FINITE(x)) { + /* NaNs, zeros and infinities are returned unchanged */ + r = x; + errno = 0; + } else if (exp > INT_MAX) { + /* overflow */ + r = copysign(Py_HUGE_VAL, x); + errno = ERANGE; + } else if (exp < INT_MIN) { + /* underflow to +-0 */ + r = copysign(0., x); + errno = 0; + } else { + errno = 0; + PyFPE_START_PROTECT("in math_ldexp", return 0); + r = ldexp(x, (int)exp); + PyFPE_END_PROTECT(r); + if (Py_IS_INFINITY(r)) + errno = ERANGE; + } + + if (errno && is_error(r)) + return NULL; + return PyFloat_FromDouble(r); } PyDoc_STRVAR(math_ldexp_doc, @@ -818,23 +818,23 @@ static PyObject * math_modf(PyObject *self, PyObject *arg) { - double y, x = PyFloat_AsDouble(arg); - if (x == -1.0 && PyErr_Occurred()) - return NULL; - /* some platforms don't do the right thing for NaNs and - infinities, so we take care of special cases directly. */ - if (!Py_IS_FINITE(x)) { - if (Py_IS_INFINITY(x)) - return Py_BuildValue("(dd)", copysign(0., x), x); - else if (Py_IS_NAN(x)) - return Py_BuildValue("(dd)", x, x); - } - - errno = 0; - PyFPE_START_PROTECT("in math_modf", return 0); - x = modf(x, &y); - PyFPE_END_PROTECT(x); - return Py_BuildValue("(dd)", x, y); + double y, x = PyFloat_AsDouble(arg); + if (x == -1.0 && PyErr_Occurred()) + return NULL; + /* some platforms don't do the right thing for NaNs and + infinities, so we take care of special cases directly. */ + if (!Py_IS_FINITE(x)) { + if (Py_IS_INFINITY(x)) + return Py_BuildValue("(dd)", copysign(0., x), x); + else if (Py_IS_NAN(x)) + return Py_BuildValue("(dd)", x, x); + } + + errno = 0; + PyFPE_START_PROTECT("in math_modf", return 0); + x = modf(x, &y); + PyFPE_END_PROTECT(x); + return Py_BuildValue("(dd)", x, y); } PyDoc_STRVAR(math_modf_doc, @@ -854,53 +854,53 @@ static PyObject* loghelper(PyObject* arg, double (*func)(double), char *funcname) { - /* If it is long, do it ourselves. */ - if (PyLong_Check(arg)) { - double x; - int e; - x = _PyLong_AsScaledDouble(arg, &e); - if (x <= 0.0) { - PyErr_SetString(PyExc_ValueError, - "math domain error"); - return NULL; - } - /* Value is ~= x * 2**(e*PyLong_SHIFT), so the log ~= - log(x) + log(2) * e * PyLong_SHIFT. - CAUTION: e*PyLong_SHIFT may overflow using int arithmetic, - so force use of double. */ - x = func(x) + (e * (double)PyLong_SHIFT) * func(2.0); - return PyFloat_FromDouble(x); - } + /* If it is long, do it ourselves. */ + if (PyLong_Check(arg)) { + double x; + int e; + x = _PyLong_AsScaledDouble(arg, &e); + if (x <= 0.0) { + PyErr_SetString(PyExc_ValueError, + "math domain error"); + return NULL; + } + /* Value is ~= x * 2**(e*PyLong_SHIFT), so the log ~= + log(x) + log(2) * e * PyLong_SHIFT. + CAUTION: e*PyLong_SHIFT may overflow using int arithmetic, + so force use of double. */ + x = func(x) + (e * (double)PyLong_SHIFT) * func(2.0); + return PyFloat_FromDouble(x); + } - /* Else let libm handle it by itself. */ - return math_1(arg, func, 0); + /* Else let libm handle it by itself. */ + return math_1(arg, func, 0); } static PyObject * math_log(PyObject *self, PyObject *args) { - PyObject *arg; - PyObject *base = NULL; - PyObject *num, *den; - PyObject *ans; - - if (!PyArg_UnpackTuple(args, "log", 1, 2, &arg, &base)) - return NULL; - - num = loghelper(arg, m_log, "log"); - if (num == NULL || base == NULL) - return num; - - den = loghelper(base, m_log, "log"); - if (den == NULL) { - Py_DECREF(num); - return NULL; - } - - ans = PyNumber_TrueDivide(num, den); - Py_DECREF(num); - Py_DECREF(den); - return ans; + PyObject *arg; + PyObject *base = NULL; + PyObject *num, *den; + PyObject *ans; + + if (!PyArg_UnpackTuple(args, "log", 1, 2, &arg, &base)) + return NULL; + + num = loghelper(arg, m_log, "log"); + if (num == NULL || base == NULL) + return num; + + den = loghelper(base, m_log, "log"); + if (den == NULL) { + Py_DECREF(num); + return NULL; + } + + ans = PyNumber_TrueDivide(num, den); + Py_DECREF(num); + Py_DECREF(den); + return ans; } PyDoc_STRVAR(math_log_doc, @@ -911,7 +911,7 @@ static PyObject * math_log10(PyObject *self, PyObject *arg) { - return loghelper(arg, m_log10, "log10"); + return loghelper(arg, m_log10, "log10"); } PyDoc_STRVAR(math_log10_doc, @@ -920,31 +920,31 @@ static PyObject * math_fmod(PyObject *self, PyObject *args) { - PyObject *ox, *oy; - double r, x, y; - if (! PyArg_UnpackTuple(args, "fmod", 2, 2, &ox, &oy)) - return NULL; - x = PyFloat_AsDouble(ox); - y = PyFloat_AsDouble(oy); - if ((x == -1.0 || y == -1.0) && PyErr_Occurred()) - return NULL; - /* fmod(x, +/-Inf) returns x for finite x. */ - if (Py_IS_INFINITY(y) && Py_IS_FINITE(x)) - return PyFloat_FromDouble(x); - errno = 0; - PyFPE_START_PROTECT("in math_fmod", return 0); - r = fmod(x, y); - PyFPE_END_PROTECT(r); - if (Py_IS_NAN(r)) { - if (!Py_IS_NAN(x) && !Py_IS_NAN(y)) - errno = EDOM; - else - errno = 0; - } - if (errno && is_error(r)) - return NULL; - else - return PyFloat_FromDouble(r); + PyObject *ox, *oy; + double r, x, y; + if (! PyArg_UnpackTuple(args, "fmod", 2, 2, &ox, &oy)) + return NULL; + x = PyFloat_AsDouble(ox); + y = PyFloat_AsDouble(oy); + if ((x == -1.0 || y == -1.0) && PyErr_Occurred()) + return NULL; + /* fmod(x, +/-Inf) returns x for finite x. */ + if (Py_IS_INFINITY(y) && Py_IS_FINITE(x)) + return PyFloat_FromDouble(x); + errno = 0; + PyFPE_START_PROTECT("in math_fmod", return 0); + r = fmod(x, y); + PyFPE_END_PROTECT(r); + if (Py_IS_NAN(r)) { + if (!Py_IS_NAN(x) && !Py_IS_NAN(y)) + errno = EDOM; + else + errno = 0; + } + if (errno && is_error(r)) + return NULL; + else + return PyFloat_FromDouble(r); } PyDoc_STRVAR(math_fmod_doc, @@ -954,39 +954,39 @@ static PyObject * math_hypot(PyObject *self, PyObject *args) { - PyObject *ox, *oy; - double r, x, y; - if (! PyArg_UnpackTuple(args, "hypot", 2, 2, &ox, &oy)) - return NULL; - x = PyFloat_AsDouble(ox); - y = PyFloat_AsDouble(oy); - if ((x == -1.0 || y == -1.0) && PyErr_Occurred()) - return NULL; - /* hypot(x, +/-Inf) returns Inf, even if x is a NaN. */ - if (Py_IS_INFINITY(x)) - return PyFloat_FromDouble(fabs(x)); - if (Py_IS_INFINITY(y)) - return PyFloat_FromDouble(fabs(y)); - errno = 0; - PyFPE_START_PROTECT("in math_hypot", return 0); - r = hypot(x, y); - PyFPE_END_PROTECT(r); - if (Py_IS_NAN(r)) { - if (!Py_IS_NAN(x) && !Py_IS_NAN(y)) - errno = EDOM; - else - errno = 0; - } - else if (Py_IS_INFINITY(r)) { - if (Py_IS_FINITE(x) && Py_IS_FINITE(y)) - errno = ERANGE; - else - errno = 0; - } - if (errno && is_error(r)) - return NULL; - else - return PyFloat_FromDouble(r); + PyObject *ox, *oy; + double r, x, y; + if (! PyArg_UnpackTuple(args, "hypot", 2, 2, &ox, &oy)) + return NULL; + x = PyFloat_AsDouble(ox); + y = PyFloat_AsDouble(oy); + if ((x == -1.0 || y == -1.0) && PyErr_Occurred()) + return NULL; + /* hypot(x, +/-Inf) returns Inf, even if x is a NaN. */ + if (Py_IS_INFINITY(x)) + return PyFloat_FromDouble(fabs(x)); + if (Py_IS_INFINITY(y)) + return PyFloat_FromDouble(fabs(y)); + errno = 0; + PyFPE_START_PROTECT("in math_hypot", return 0); + r = hypot(x, y); + PyFPE_END_PROTECT(r); + if (Py_IS_NAN(r)) { + if (!Py_IS_NAN(x) && !Py_IS_NAN(y)) + errno = EDOM; + else + errno = 0; + } + else if (Py_IS_INFINITY(r)) { + if (Py_IS_FINITE(x) && Py_IS_FINITE(y)) + errno = ERANGE; + else + errno = 0; + } + if (errno && is_error(r)) + return NULL; + else + return PyFloat_FromDouble(r); } PyDoc_STRVAR(math_hypot_doc, @@ -1001,79 +1001,79 @@ static PyObject * math_pow(PyObject *self, PyObject *args) { - PyObject *ox, *oy; - double r, x, y; - int odd_y; - - if (! PyArg_UnpackTuple(args, "pow", 2, 2, &ox, &oy)) - return NULL; - x = PyFloat_AsDouble(ox); - y = PyFloat_AsDouble(oy); - if ((x == -1.0 || y == -1.0) && PyErr_Occurred()) - return NULL; - - /* deal directly with IEEE specials, to cope with problems on various - platforms whose semantics don't exactly match C99 */ - r = 0.; /* silence compiler warning */ - if (!Py_IS_FINITE(x) || !Py_IS_FINITE(y)) { - errno = 0; - if (Py_IS_NAN(x)) - r = y == 0. ? 1. : x; /* NaN**0 = 1 */ - else if (Py_IS_NAN(y)) - r = x == 1. ? 1. : y; /* 1**NaN = 1 */ - else if (Py_IS_INFINITY(x)) { - odd_y = Py_IS_FINITE(y) && fmod(fabs(y), 2.0) == 1.0; - if (y > 0.) - r = odd_y ? x : fabs(x); - else if (y == 0.) - r = 1.; - else /* y < 0. */ - r = odd_y ? copysign(0., x) : 0.; - } - else if (Py_IS_INFINITY(y)) { - if (fabs(x) == 1.0) - r = 1.; - else if (y > 0. && fabs(x) > 1.0) - r = y; - else if (y < 0. && fabs(x) < 1.0) { - r = -y; /* result is +inf */ - if (x == 0.) /* 0**-inf: divide-by-zero */ - errno = EDOM; - } - else - r = 0.; - } - } - else { - /* let libm handle finite**finite */ - errno = 0; - PyFPE_START_PROTECT("in math_pow", return 0); - r = pow(x, y); - PyFPE_END_PROTECT(r); - /* a NaN result should arise only from (-ve)**(finite - non-integer); in this case we want to raise ValueError. */ - if (!Py_IS_FINITE(r)) { - if (Py_IS_NAN(r)) { - errno = EDOM; - } - /* - an infinite result here arises either from: - (A) (+/-0.)**negative (-> divide-by-zero) - (B) overflow of x**y with x and y finite - */ - else if (Py_IS_INFINITY(r)) { - if (x == 0.) - errno = EDOM; - else - errno = ERANGE; - } - } - } - - if (errno && is_error(r)) - return NULL; - else - return PyFloat_FromDouble(r); + PyObject *ox, *oy; + double r, x, y; + int odd_y; + + if (! PyArg_UnpackTuple(args, "pow", 2, 2, &ox, &oy)) + return NULL; + x = PyFloat_AsDouble(ox); + y = PyFloat_AsDouble(oy); + if ((x == -1.0 || y == -1.0) && PyErr_Occurred()) + return NULL; + + /* deal directly with IEEE specials, to cope with problems on various + platforms whose semantics don't exactly match C99 */ + r = 0.; /* silence compiler warning */ + if (!Py_IS_FINITE(x) || !Py_IS_FINITE(y)) { + errno = 0; + if (Py_IS_NAN(x)) + r = y == 0. ? 1. : x; /* NaN**0 = 1 */ + else if (Py_IS_NAN(y)) + r = x == 1. ? 1. : y; /* 1**NaN = 1 */ + else if (Py_IS_INFINITY(x)) { + odd_y = Py_IS_FINITE(y) && fmod(fabs(y), 2.0) == 1.0; + if (y > 0.) + r = odd_y ? x : fabs(x); + else if (y == 0.) + r = 1.; + else /* y < 0. */ + r = odd_y ? copysign(0., x) : 0.; + } + else if (Py_IS_INFINITY(y)) { + if (fabs(x) == 1.0) + r = 1.; + else if (y > 0. && fabs(x) > 1.0) + r = y; + else if (y < 0. && fabs(x) < 1.0) { + r = -y; /* result is +inf */ + if (x == 0.) /* 0**-inf: divide-by-zero */ + errno = EDOM; + } + else + r = 0.; + } + } + else { + /* let libm handle finite**finite */ + errno = 0; + PyFPE_START_PROTECT("in math_pow", return 0); + r = pow(x, y); + PyFPE_END_PROTECT(r); + /* a NaN result should arise only from (-ve)**(finite + non-integer); in this case we want to raise ValueError. */ + if (!Py_IS_FINITE(r)) { + if (Py_IS_NAN(r)) { + errno = EDOM; + } + /* + an infinite result here arises either from: + (A) (+/-0.)**negative (-> divide-by-zero) + (B) overflow of x**y with x and y finite + */ + else if (Py_IS_INFINITY(r)) { + if (x == 0.) + errno = EDOM; + else + errno = ERANGE; + } + } + } + + if (errno && is_error(r)) + return NULL; + else + return PyFloat_FromDouble(r); } PyDoc_STRVAR(math_pow_doc, @@ -1085,10 +1085,10 @@ static PyObject * math_degrees(PyObject *self, PyObject *arg) { - double x = PyFloat_AsDouble(arg); - if (x == -1.0 && PyErr_Occurred()) - return NULL; - return PyFloat_FromDouble(x * radToDeg); + double x = PyFloat_AsDouble(arg); + if (x == -1.0 && PyErr_Occurred()) + return NULL; + return PyFloat_FromDouble(x * radToDeg); } PyDoc_STRVAR(math_degrees_doc, @@ -1098,10 +1098,10 @@ static PyObject * math_radians(PyObject *self, PyObject *arg) { - double x = PyFloat_AsDouble(arg); - if (x == -1.0 && PyErr_Occurred()) - return NULL; - return PyFloat_FromDouble(x * degToRad); + double x = PyFloat_AsDouble(arg); + if (x == -1.0 && PyErr_Occurred()) + return NULL; + return PyFloat_FromDouble(x * degToRad); } PyDoc_STRVAR(math_radians_doc, @@ -1111,10 +1111,10 @@ static PyObject * math_isnan(PyObject *self, PyObject *arg) { - double x = PyFloat_AsDouble(arg); - if (x == -1.0 && PyErr_Occurred()) - return NULL; - return PyBool_FromLong((long)Py_IS_NAN(x)); + double x = PyFloat_AsDouble(arg); + if (x == -1.0 && PyErr_Occurred()) + return NULL; + return PyBool_FromLong((long)Py_IS_NAN(x)); } PyDoc_STRVAR(math_isnan_doc, @@ -1124,10 +1124,10 @@ static PyObject * math_isinf(PyObject *self, PyObject *arg) { - double x = PyFloat_AsDouble(arg); - if (x == -1.0 && PyErr_Occurred()) - return NULL; - return PyBool_FromLong((long)Py_IS_INFINITY(x)); + double x = PyFloat_AsDouble(arg); + if (x == -1.0 && PyErr_Occurred()) + return NULL; + return PyBool_FromLong((long)Py_IS_INFINITY(x)); } PyDoc_STRVAR(math_isinf_doc, @@ -1135,42 +1135,42 @@ Check if float x is infinite (positive or negative)."); static PyMethodDef math_methods[] = { - {"acos", math_acos, METH_O, math_acos_doc}, - {"acosh", math_acosh, METH_O, math_acosh_doc}, - {"asin", math_asin, METH_O, math_asin_doc}, - {"asinh", math_asinh, METH_O, math_asinh_doc}, - {"atan", math_atan, METH_O, math_atan_doc}, - {"atan2", math_atan2, METH_VARARGS, math_atan2_doc}, - {"atanh", math_atanh, METH_O, math_atanh_doc}, - {"ceil", math_ceil, METH_O, math_ceil_doc}, - {"copysign", math_copysign, METH_VARARGS, math_copysign_doc}, - {"cos", math_cos, METH_O, math_cos_doc}, - {"cosh", math_cosh, METH_O, math_cosh_doc}, - {"degrees", math_degrees, METH_O, math_degrees_doc}, - {"exp", math_exp, METH_O, math_exp_doc}, - {"fabs", math_fabs, METH_O, math_fabs_doc}, - {"factorial", math_factorial, METH_O, math_factorial_doc}, - {"floor", math_floor, METH_O, math_floor_doc}, - {"fmod", math_fmod, METH_VARARGS, math_fmod_doc}, - {"frexp", math_frexp, METH_O, math_frexp_doc}, - {"fsum", math_fsum, METH_O, math_fsum_doc}, - {"hypot", math_hypot, METH_VARARGS, math_hypot_doc}, - {"isinf", math_isinf, METH_O, math_isinf_doc}, - {"isnan", math_isnan, METH_O, math_isnan_doc}, - {"ldexp", math_ldexp, METH_VARARGS, math_ldexp_doc}, - {"log", math_log, METH_VARARGS, math_log_doc}, - {"log1p", math_log1p, METH_O, math_log1p_doc}, - {"log10", math_log10, METH_O, math_log10_doc}, - {"modf", math_modf, METH_O, math_modf_doc}, - {"pow", math_pow, METH_VARARGS, math_pow_doc}, - {"radians", math_radians, METH_O, math_radians_doc}, - {"sin", math_sin, METH_O, math_sin_doc}, - {"sinh", math_sinh, METH_O, math_sinh_doc}, - {"sqrt", math_sqrt, METH_O, math_sqrt_doc}, - {"tan", math_tan, METH_O, math_tan_doc}, - {"tanh", math_tanh, METH_O, math_tanh_doc}, - {"trunc", math_trunc, METH_O, math_trunc_doc}, - {NULL, NULL} /* sentinel */ + {"acos", math_acos, METH_O, math_acos_doc}, + {"acosh", math_acosh, METH_O, math_acosh_doc}, + {"asin", math_asin, METH_O, math_asin_doc}, + {"asinh", math_asinh, METH_O, math_asinh_doc}, + {"atan", math_atan, METH_O, math_atan_doc}, + {"atan2", math_atan2, METH_VARARGS, math_atan2_doc}, + {"atanh", math_atanh, METH_O, math_atanh_doc}, + {"ceil", math_ceil, METH_O, math_ceil_doc}, + {"copysign", math_copysign, METH_VARARGS, math_copysign_doc}, + {"cos", math_cos, METH_O, math_cos_doc}, + {"cosh", math_cosh, METH_O, math_cosh_doc}, + {"degrees", math_degrees, METH_O, math_degrees_doc}, + {"exp", math_exp, METH_O, math_exp_doc}, + {"fabs", math_fabs, METH_O, math_fabs_doc}, + {"factorial", math_factorial, METH_O, math_factorial_doc}, + {"floor", math_floor, METH_O, math_floor_doc}, + {"fmod", math_fmod, METH_VARARGS, math_fmod_doc}, + {"frexp", math_frexp, METH_O, math_frexp_doc}, + {"fsum", math_fsum, METH_O, math_fsum_doc}, + {"hypot", math_hypot, METH_VARARGS, math_hypot_doc}, + {"isinf", math_isinf, METH_O, math_isinf_doc}, + {"isnan", math_isnan, METH_O, math_isnan_doc}, + {"ldexp", math_ldexp, METH_VARARGS, math_ldexp_doc}, + {"log", math_log, METH_VARARGS, math_log_doc}, + {"log1p", math_log1p, METH_O, math_log1p_doc}, + {"log10", math_log10, METH_O, math_log10_doc}, + {"modf", math_modf, METH_O, math_modf_doc}, + {"pow", math_pow, METH_VARARGS, math_pow_doc}, + {"radians", math_radians, METH_O, math_radians_doc}, + {"sin", math_sin, METH_O, math_sin_doc}, + {"sinh", math_sinh, METH_O, math_sinh_doc}, + {"sqrt", math_sqrt, METH_O, math_sqrt_doc}, + {"tan", math_tan, METH_O, math_tan_doc}, + {"tanh", math_tanh, METH_O, math_tanh_doc}, + {"trunc", math_trunc, METH_O, math_trunc_doc}, + {NULL, NULL} /* sentinel */ }; @@ -1180,29 +1180,29 @@ static struct PyModuleDef mathmodule = { - PyModuleDef_HEAD_INIT, - "math", - module_doc, - -1, - math_methods, - NULL, - NULL, - NULL, - NULL + PyModuleDef_HEAD_INIT, + "math", + module_doc, + -1, + math_methods, + NULL, + NULL, + NULL, + NULL }; PyMODINIT_FUNC PyInit_math(void) { - PyObject *m; + PyObject *m; - m = PyModule_Create(&mathmodule); - if (m == NULL) - goto finally; + m = PyModule_Create(&mathmodule); + if (m == NULL) + goto finally; - PyModule_AddObject(m, "pi", PyFloat_FromDouble(Py_MATH_PI)); - PyModule_AddObject(m, "e", PyFloat_FromDouble(Py_MATH_E)); + PyModule_AddObject(m, "pi", PyFloat_FromDouble(Py_MATH_PI)); + PyModule_AddObject(m, "e", PyFloat_FromDouble(Py_MATH_E)); finally: - return m; + return m; } Modified: python/branches/release31-maint/Modules/md5module.c ============================================================================== --- python/branches/release31-maint/Modules/md5module.c (original) +++ python/branches/release31-maint/Modules/md5module.c Sun May 9 18:14:21 2010 @@ -23,8 +23,8 @@ /* Some useful types */ #if SIZEOF_INT == 4 -typedef unsigned int MD5_INT32; /* 32-bit integer */ -typedef PY_LONG_LONG MD5_INT64; /* 64-bit integer */ +typedef unsigned int MD5_INT32; /* 32-bit integer */ +typedef PY_LONG_LONG MD5_INT64; /* 64-bit integer */ #else /* not defined. compilation will die. */ #endif @@ -127,7 +127,7 @@ for (i = 0; i < 16; i++) { LOAD32L(W[i], buf + (4*i)); } - + /* copy state */ a = md5->state[0]; b = md5->state[1]; @@ -386,21 +386,21 @@ /* Create a new string */ retval = PyUnicode_FromStringAndSize(NULL, MD5_DIGESTSIZE * 2); if (!retval) - return NULL; + return NULL; hex_digest = PyUnicode_AS_UNICODE(retval); if (!hex_digest) { - Py_DECREF(retval); - return NULL; + Py_DECREF(retval); + return NULL; } /* Make hex version of the digest */ for(i=j=0; i> 4) & 0xf; - c = (c>9) ? c+'a'-10 : c + '0'; + c = (c>9) ? c+'a'-10 : c + '0'; hex_digest[j++] = c; c = (digest[i] & 0xf); - c = (c>9) ? c+'a'-10 : c + '0'; + c = (c>9) ? c+'a'-10 : c + '0'; hex_digest[j++] = c; } return retval; @@ -414,7 +414,7 @@ { PyObject *obj; Py_buffer buf; - + if (!PyArg_ParseTuple(args, "O:update", &obj)) return NULL; @@ -428,11 +428,11 @@ } static PyMethodDef MD5_methods[] = { - {"copy", (PyCFunction)MD5_copy, METH_NOARGS, MD5_copy__doc__}, - {"digest", (PyCFunction)MD5_digest, METH_NOARGS, MD5_digest__doc__}, + {"copy", (PyCFunction)MD5_copy, METH_NOARGS, MD5_copy__doc__}, + {"digest", (PyCFunction)MD5_digest, METH_NOARGS, MD5_digest__doc__}, {"hexdigest", (PyCFunction)MD5_hexdigest, METH_NOARGS, MD5_hexdigest__doc__}, - {"update", (PyCFunction)MD5_update, METH_VARARGS, MD5_update__doc__}, - {NULL, NULL} /* sentinel */ + {"update", (PyCFunction)MD5_update, METH_VARARGS, MD5_update__doc__}, + {NULL, NULL} /* sentinel */ }; static PyObject * @@ -472,13 +472,13 @@ static PyTypeObject MD5type = { PyVarObject_HEAD_INIT(NULL, 0) - "_md5.md5", /*tp_name*/ - sizeof(MD5object), /*tp_size*/ - 0, /*tp_itemsize*/ + "_md5.md5", /*tp_name*/ + sizeof(MD5object), /*tp_size*/ + 0, /*tp_itemsize*/ /* methods */ - MD5_dealloc, /*tp_dealloc*/ - 0, /*tp_print*/ - 0, /*tp_getattr*/ + MD5_dealloc, /*tp_dealloc*/ + 0, /*tp_print*/ + 0, /*tp_getattr*/ 0, /*tp_setattr*/ 0, /*tp_reserved*/ 0, /*tp_repr*/ @@ -494,13 +494,13 @@ Py_TPFLAGS_DEFAULT, /*tp_flags*/ 0, /*tp_doc*/ 0, /*tp_traverse*/ - 0, /*tp_clear*/ - 0, /*tp_richcompare*/ - 0, /*tp_weaklistoffset*/ - 0, /*tp_iter*/ - 0, /*tp_iternext*/ - MD5_methods, /* tp_methods */ - NULL, /* tp_members */ + 0, /*tp_clear*/ + 0, /*tp_richcompare*/ + 0, /*tp_weaklistoffset*/ + 0, /*tp_iter*/ + 0, /*tp_iternext*/ + MD5_methods, /* tp_methods */ + NULL, /* tp_members */ MD5_getseters, /* tp_getset */ }; @@ -553,7 +553,7 @@ static struct PyMethodDef MD5_functions[] = { {"md5", (PyCFunction)MD5_new, METH_VARARGS|METH_KEYWORDS, MD5_new__doc__}, - {NULL, NULL} /* Sentinel */ + {NULL, NULL} /* Sentinel */ }; @@ -563,15 +563,15 @@ static struct PyModuleDef _md5module = { - PyModuleDef_HEAD_INIT, - "_md5", - NULL, - -1, - MD5_functions, - NULL, - NULL, - NULL, - NULL + PyModuleDef_HEAD_INIT, + "_md5", + NULL, + -1, + MD5_functions, + NULL, + NULL, + NULL, + NULL }; PyMODINIT_FUNC Modified: python/branches/release31-maint/Modules/mmapmodule.c ============================================================================== --- python/branches/release31-maint/Modules/mmapmodule.c (original) +++ python/branches/release31-maint/Modules/mmapmodule.c Sun May 9 18:14:21 2010 @@ -30,18 +30,18 @@ static int my_getpagesize(void) { - SYSTEM_INFO si; - GetSystemInfo(&si); - return si.dwPageSize; + SYSTEM_INFO si; + GetSystemInfo(&si); + return si.dwPageSize; } static int my_getallocationgranularity (void) { - SYSTEM_INFO si; - GetSystemInfo(&si); - return si.dwAllocationGranularity; + SYSTEM_INFO si; + GetSystemInfo(&si); + return si.dwAllocationGranularity; } #endif @@ -54,7 +54,7 @@ static int my_getpagesize(void) { - return sysconf(_SC_PAGESIZE); + return sysconf(_SC_PAGESIZE); } #define my_getallocationgranularity my_getpagesize @@ -79,31 +79,31 @@ typedef enum { - ACCESS_DEFAULT, - ACCESS_READ, - ACCESS_WRITE, - ACCESS_COPY + ACCESS_DEFAULT, + ACCESS_READ, + ACCESS_WRITE, + ACCESS_COPY } access_mode; typedef struct { - PyObject_HEAD - char * data; - size_t size; - size_t pos; /* relative to offset */ - size_t offset; - int exports; + PyObject_HEAD + char * data; + size_t size; + size_t pos; /* relative to offset */ + size_t offset; + int exports; #ifdef MS_WINDOWS - HANDLE map_handle; - HANDLE file_handle; - char * tagname; + HANDLE map_handle; + HANDLE file_handle; + char * tagname; #endif #ifdef UNIX - int fd; + int fd; #endif - access_mode access; + access_mode access; } mmap_object; @@ -111,331 +111,331 @@ mmap_object_dealloc(mmap_object *m_obj) { #ifdef MS_WINDOWS - if (m_obj->data != NULL) - UnmapViewOfFile (m_obj->data); - if (m_obj->map_handle != NULL) - CloseHandle (m_obj->map_handle); - if (m_obj->file_handle != INVALID_HANDLE_VALUE) - CloseHandle (m_obj->file_handle); - if (m_obj->tagname) - PyMem_Free(m_obj->tagname); + if (m_obj->data != NULL) + UnmapViewOfFile (m_obj->data); + if (m_obj->map_handle != NULL) + CloseHandle (m_obj->map_handle); + if (m_obj->file_handle != INVALID_HANDLE_VALUE) + CloseHandle (m_obj->file_handle); + if (m_obj->tagname) + PyMem_Free(m_obj->tagname); #endif /* MS_WINDOWS */ #ifdef UNIX - if (m_obj->fd >= 0) - (void) close(m_obj->fd); - if (m_obj->data!=NULL) { - msync(m_obj->data, m_obj->size, MS_SYNC); - munmap(m_obj->data, m_obj->size); - } + if (m_obj->fd >= 0) + (void) close(m_obj->fd); + if (m_obj->data!=NULL) { + msync(m_obj->data, m_obj->size, MS_SYNC); + munmap(m_obj->data, m_obj->size); + } #endif /* UNIX */ - Py_TYPE(m_obj)->tp_free((PyObject*)m_obj); + Py_TYPE(m_obj)->tp_free((PyObject*)m_obj); } static PyObject * mmap_close_method(mmap_object *self, PyObject *unused) { - if (self->exports > 0) { - PyErr_SetString(PyExc_BufferError, "cannot close "\ - "exported pointers exist"); - return NULL; - } + if (self->exports > 0) { + PyErr_SetString(PyExc_BufferError, "cannot close "\ + "exported pointers exist"); + return NULL; + } #ifdef MS_WINDOWS - /* For each resource we maintain, we need to check - the value is valid, and if so, free the resource - and set the member value to an invalid value so - the dealloc does not attempt to resource clearing - again. - TODO - should we check for errors in the close operations??? - */ - if (self->data != NULL) { - UnmapViewOfFile(self->data); - self->data = NULL; - } - if (self->map_handle != NULL) { - CloseHandle(self->map_handle); - self->map_handle = NULL; - } - if (self->file_handle != INVALID_HANDLE_VALUE) { - CloseHandle(self->file_handle); - self->file_handle = INVALID_HANDLE_VALUE; - } + /* For each resource we maintain, we need to check + the value is valid, and if so, free the resource + and set the member value to an invalid value so + the dealloc does not attempt to resource clearing + again. + TODO - should we check for errors in the close operations??? + */ + if (self->data != NULL) { + UnmapViewOfFile(self->data); + self->data = NULL; + } + if (self->map_handle != NULL) { + CloseHandle(self->map_handle); + self->map_handle = NULL; + } + if (self->file_handle != INVALID_HANDLE_VALUE) { + CloseHandle(self->file_handle); + self->file_handle = INVALID_HANDLE_VALUE; + } #endif /* MS_WINDOWS */ #ifdef UNIX - if (0 <= self->fd) - (void) close(self->fd); - self->fd = -1; - if (self->data != NULL) { - munmap(self->data, self->size); - self->data = NULL; - } + if (0 <= self->fd) + (void) close(self->fd); + self->fd = -1; + if (self->data != NULL) { + munmap(self->data, self->size); + self->data = NULL; + } #endif - Py_INCREF(Py_None); - return Py_None; + Py_INCREF(Py_None); + return Py_None; } #ifdef MS_WINDOWS -#define CHECK_VALID(err) \ -do { \ - if (self->map_handle == NULL) { \ - PyErr_SetString(PyExc_ValueError, "mmap closed or invalid"); \ - return err; \ - } \ +#define CHECK_VALID(err) \ +do { \ + if (self->map_handle == NULL) { \ + PyErr_SetString(PyExc_ValueError, "mmap closed or invalid"); \ + return err; \ + } \ } while (0) #endif /* MS_WINDOWS */ #ifdef UNIX -#define CHECK_VALID(err) \ -do { \ - if (self->data == NULL) { \ - PyErr_SetString(PyExc_ValueError, "mmap closed or invalid"); \ - return err; \ - } \ +#define CHECK_VALID(err) \ +do { \ + if (self->data == NULL) { \ + PyErr_SetString(PyExc_ValueError, "mmap closed or invalid"); \ + return err; \ + } \ } while (0) #endif /* UNIX */ static PyObject * mmap_read_byte_method(mmap_object *self, - PyObject *unused) + PyObject *unused) { - CHECK_VALID(NULL); - if (self->pos < self->size) { - char value = self->data[self->pos]; - self->pos += 1; - return Py_BuildValue("b", value); - } else { - PyErr_SetString(PyExc_ValueError, "read byte out of range"); - return NULL; - } + CHECK_VALID(NULL); + if (self->pos < self->size) { + char value = self->data[self->pos]; + self->pos += 1; + return Py_BuildValue("b", value); + } else { + PyErr_SetString(PyExc_ValueError, "read byte out of range"); + return NULL; + } } static PyObject * mmap_read_line_method(mmap_object *self, - PyObject *unused) + PyObject *unused) { - char *start = self->data+self->pos; - char *eof = self->data+self->size; - char *eol; - PyObject *result; - - CHECK_VALID(NULL); - - eol = memchr(start, '\n', self->size - self->pos); - if (!eol) - eol = eof; - else - ++eol; /* we're interested in the position after the - newline. */ - result = PyBytes_FromStringAndSize(start, (eol - start)); - self->pos += (eol - start); - return result; + char *start = self->data+self->pos; + char *eof = self->data+self->size; + char *eol; + PyObject *result; + + CHECK_VALID(NULL); + + eol = memchr(start, '\n', self->size - self->pos); + if (!eol) + eol = eof; + else + ++eol; /* we're interested in the position after the + newline. */ + result = PyBytes_FromStringAndSize(start, (eol - start)); + self->pos += (eol - start); + return result; } static PyObject * mmap_read_method(mmap_object *self, - PyObject *args) + PyObject *args) { - Py_ssize_t num_bytes, n; - PyObject *result; + Py_ssize_t num_bytes, n; + PyObject *result; - CHECK_VALID(NULL); - if (!PyArg_ParseTuple(args, "n:read", &num_bytes)) - return(NULL); - - /* silently 'adjust' out-of-range requests */ - assert(self->size >= self->pos); - n = self->size - self->pos; - /* The difference can overflow, only if self->size is greater than - * PY_SSIZE_T_MAX. But then the operation cannot possibly succeed, - * because the mapped area and the returned string each need more - * than half of the addressable memory. So we clip the size, and let - * the code below raise MemoryError. - */ - if (n < 0) - n = PY_SSIZE_T_MAX; - if (num_bytes < 0 || num_bytes > n) { - num_bytes = n; - } - result = PyBytes_FromStringAndSize(self->data+self->pos, num_bytes); - self->pos += num_bytes; - return result; + CHECK_VALID(NULL); + if (!PyArg_ParseTuple(args, "n:read", &num_bytes)) + return(NULL); + + /* silently 'adjust' out-of-range requests */ + assert(self->size >= self->pos); + n = self->size - self->pos; + /* The difference can overflow, only if self->size is greater than + * PY_SSIZE_T_MAX. But then the operation cannot possibly succeed, + * because the mapped area and the returned string each need more + * than half of the addressable memory. So we clip the size, and let + * the code below raise MemoryError. + */ + if (n < 0) + n = PY_SSIZE_T_MAX; + if (num_bytes < 0 || num_bytes > n) { + num_bytes = n; + } + result = PyBytes_FromStringAndSize(self->data+self->pos, num_bytes); + self->pos += num_bytes; + return result; } static PyObject * mmap_gfind(mmap_object *self, - PyObject *args, - int reverse) + PyObject *args, + int reverse) { - Py_ssize_t start = self->pos; - Py_ssize_t end = self->size; - const char *needle; - Py_ssize_t len; - - CHECK_VALID(NULL); - if (!PyArg_ParseTuple(args, reverse ? "y#|nn:rfind" : "y#|nn:find", - &needle, &len, &start, &end)) { - return NULL; - } else { - const char *p, *start_p, *end_p; - int sign = reverse ? -1 : 1; - - if (start < 0) - start += self->size; - if (start < 0) - start = 0; - else if ((size_t)start > self->size) - start = self->size; - - if (end < 0) - end += self->size; - if (end < 0) - end = 0; - else if ((size_t)end > self->size) - end = self->size; - - start_p = self->data + start; - end_p = self->data + end; - - for (p = (reverse ? end_p - len : start_p); - (p >= start_p) && (p + len <= end_p); p += sign) { - Py_ssize_t i; - for (i = 0; i < len && needle[i] == p[i]; ++i) - /* nothing */; - if (i == len) { - return PyLong_FromSsize_t(p - self->data); - } - } - return PyLong_FromLong(-1); - } + Py_ssize_t start = self->pos; + Py_ssize_t end = self->size; + const char *needle; + Py_ssize_t len; + + CHECK_VALID(NULL); + if (!PyArg_ParseTuple(args, reverse ? "y#|nn:rfind" : "y#|nn:find", + &needle, &len, &start, &end)) { + return NULL; + } else { + const char *p, *start_p, *end_p; + int sign = reverse ? -1 : 1; + + if (start < 0) + start += self->size; + if (start < 0) + start = 0; + else if ((size_t)start > self->size) + start = self->size; + + if (end < 0) + end += self->size; + if (end < 0) + end = 0; + else if ((size_t)end > self->size) + end = self->size; + + start_p = self->data + start; + end_p = self->data + end; + + for (p = (reverse ? end_p - len : start_p); + (p >= start_p) && (p + len <= end_p); p += sign) { + Py_ssize_t i; + for (i = 0; i < len && needle[i] == p[i]; ++i) + /* nothing */; + if (i == len) { + return PyLong_FromSsize_t(p - self->data); + } + } + return PyLong_FromLong(-1); + } } static PyObject * mmap_find_method(mmap_object *self, - PyObject *args) + PyObject *args) { - return mmap_gfind(self, args, 0); + return mmap_gfind(self, args, 0); } static PyObject * mmap_rfind_method(mmap_object *self, - PyObject *args) + PyObject *args) { - return mmap_gfind(self, args, 1); + return mmap_gfind(self, args, 1); } static int is_writable(mmap_object *self) { - if (self->access != ACCESS_READ) - return 1; - PyErr_Format(PyExc_TypeError, "mmap can't modify a readonly memory map."); - return 0; + if (self->access != ACCESS_READ) + return 1; + PyErr_Format(PyExc_TypeError, "mmap can't modify a readonly memory map."); + return 0; } static int is_resizeable(mmap_object *self) { - if (self->exports > 0) { - PyErr_SetString(PyExc_BufferError, - "mmap can't resize with extant buffers exported."); - return 0; - } - if ((self->access == ACCESS_WRITE) || (self->access == ACCESS_DEFAULT)) - return 1; - PyErr_Format(PyExc_TypeError, - "mmap can't resize a readonly or copy-on-write memory map."); - return 0; + if (self->exports > 0) { + PyErr_SetString(PyExc_BufferError, + "mmap can't resize with extant buffers exported."); + return 0; + } + if ((self->access == ACCESS_WRITE) || (self->access == ACCESS_DEFAULT)) + return 1; + PyErr_Format(PyExc_TypeError, + "mmap can't resize a readonly or copy-on-write memory map."); + return 0; } static PyObject * mmap_write_method(mmap_object *self, - PyObject *args) + PyObject *args) { - Py_ssize_t length; - char *data; + Py_ssize_t length; + char *data; - CHECK_VALID(NULL); - if (!PyArg_ParseTuple(args, "y#:write", &data, &length)) - return(NULL); - - if (!is_writable(self)) - return NULL; - - if ((self->pos + length) > self->size) { - PyErr_SetString(PyExc_ValueError, "data out of range"); - return NULL; - } - memcpy(self->data+self->pos, data, length); - self->pos = self->pos+length; - Py_INCREF(Py_None); - return Py_None; + CHECK_VALID(NULL); + if (!PyArg_ParseTuple(args, "y#:write", &data, &length)) + return(NULL); + + if (!is_writable(self)) + return NULL; + + if ((self->pos + length) > self->size) { + PyErr_SetString(PyExc_ValueError, "data out of range"); + return NULL; + } + memcpy(self->data+self->pos, data, length); + self->pos = self->pos+length; + Py_INCREF(Py_None); + return Py_None; } static PyObject * mmap_write_byte_method(mmap_object *self, - PyObject *args) + PyObject *args) { - char value; + char value; - CHECK_VALID(NULL); - if (!PyArg_ParseTuple(args, "b:write_byte", &value)) - return(NULL); - - if (!is_writable(self)) - return NULL; - - if (self->pos < self->size) { - *(self->data+self->pos) = value; - self->pos += 1; - Py_INCREF(Py_None); - return Py_None; - } - else { - PyErr_SetString(PyExc_ValueError, "write byte out of range"); - return NULL; - } + CHECK_VALID(NULL); + if (!PyArg_ParseTuple(args, "b:write_byte", &value)) + return(NULL); + + if (!is_writable(self)) + return NULL; + + if (self->pos < self->size) { + *(self->data+self->pos) = value; + self->pos += 1; + Py_INCREF(Py_None); + return Py_None; + } + else { + PyErr_SetString(PyExc_ValueError, "write byte out of range"); + return NULL; + } } static PyObject * mmap_size_method(mmap_object *self, - PyObject *unused) + PyObject *unused) { - CHECK_VALID(NULL); + CHECK_VALID(NULL); #ifdef MS_WINDOWS - if (self->file_handle != INVALID_HANDLE_VALUE) { - DWORD low,high; - PY_LONG_LONG size; - low = GetFileSize(self->file_handle, &high); - if (low == INVALID_FILE_SIZE) { - /* It might be that the function appears to have failed, - when indeed its size equals INVALID_FILE_SIZE */ - DWORD error = GetLastError(); - if (error != NO_ERROR) - return PyErr_SetFromWindowsErr(error); - } - if (!high && low < LONG_MAX) - return PyLong_FromLong((long)low); - size = (((PY_LONG_LONG)high)<<32) + low; - return PyLong_FromLongLong(size); - } else { - return PyLong_FromSsize_t(self->size); - } + if (self->file_handle != INVALID_HANDLE_VALUE) { + DWORD low,high; + PY_LONG_LONG size; + low = GetFileSize(self->file_handle, &high); + if (low == INVALID_FILE_SIZE) { + /* It might be that the function appears to have failed, + when indeed its size equals INVALID_FILE_SIZE */ + DWORD error = GetLastError(); + if (error != NO_ERROR) + return PyErr_SetFromWindowsErr(error); + } + if (!high && low < LONG_MAX) + return PyLong_FromLong((long)low); + size = (((PY_LONG_LONG)high)<<32) + low; + return PyLong_FromLongLong(size); + } else { + return PyLong_FromSsize_t(self->size); + } #endif /* MS_WINDOWS */ #ifdef UNIX - { - struct stat buf; - if (-1 == fstat(self->fd, &buf)) { - PyErr_SetFromErrno(mmap_module_error); - return NULL; - } - return PyLong_FromSsize_t(buf.st_size); - } + { + struct stat buf; + if (-1 == fstat(self->fd, &buf)) { + PyErr_SetFromErrno(mmap_module_error); + return NULL; + } + return PyLong_FromSsize_t(buf.st_size); + } #endif /* UNIX */ } @@ -450,223 +450,223 @@ static PyObject * mmap_resize_method(mmap_object *self, - PyObject *args) + PyObject *args) { - Py_ssize_t new_size; - CHECK_VALID(NULL); - if (!PyArg_ParseTuple(args, "n:resize", &new_size) || - !is_resizeable(self)) { - return NULL; + Py_ssize_t new_size; + CHECK_VALID(NULL); + if (!PyArg_ParseTuple(args, "n:resize", &new_size) || + !is_resizeable(self)) { + return NULL; #ifdef MS_WINDOWS - } else { - DWORD dwErrCode = 0; - DWORD off_hi, off_lo, newSizeLow, newSizeHigh; - /* First, unmap the file view */ - UnmapViewOfFile(self->data); - self->data = NULL; - /* Close the mapping object */ - CloseHandle(self->map_handle); - self->map_handle = NULL; - /* Move to the desired EOF position */ + } else { + DWORD dwErrCode = 0; + DWORD off_hi, off_lo, newSizeLow, newSizeHigh; + /* First, unmap the file view */ + UnmapViewOfFile(self->data); + self->data = NULL; + /* Close the mapping object */ + CloseHandle(self->map_handle); + self->map_handle = NULL; + /* Move to the desired EOF position */ #if SIZEOF_SIZE_T > 4 - newSizeHigh = (DWORD)((self->offset + new_size) >> 32); - newSizeLow = (DWORD)((self->offset + new_size) & 0xFFFFFFFF); - off_hi = (DWORD)(self->offset >> 32); - off_lo = (DWORD)(self->offset & 0xFFFFFFFF); + newSizeHigh = (DWORD)((self->offset + new_size) >> 32); + newSizeLow = (DWORD)((self->offset + new_size) & 0xFFFFFFFF); + off_hi = (DWORD)(self->offset >> 32); + off_lo = (DWORD)(self->offset & 0xFFFFFFFF); #else - newSizeHigh = 0; - newSizeLow = (DWORD)(self->offset + new_size); - off_hi = 0; - off_lo = (DWORD)self->offset; -#endif - SetFilePointer(self->file_handle, - newSizeLow, &newSizeHigh, FILE_BEGIN); - /* Change the size of the file */ - SetEndOfFile(self->file_handle); - /* Create another mapping object and remap the file view */ - self->map_handle = CreateFileMapping( - self->file_handle, - NULL, - PAGE_READWRITE, - 0, - 0, - self->tagname); - if (self->map_handle != NULL) { - self->data = (char *) MapViewOfFile(self->map_handle, - FILE_MAP_WRITE, - off_hi, - off_lo, - new_size); - if (self->data != NULL) { - self->size = new_size; - Py_INCREF(Py_None); - return Py_None; - } else { - dwErrCode = GetLastError(); - CloseHandle(self->map_handle); - self->map_handle = NULL; - } - } else { - dwErrCode = GetLastError(); - } - PyErr_SetFromWindowsErr(dwErrCode); - return NULL; + newSizeHigh = 0; + newSizeLow = (DWORD)(self->offset + new_size); + off_hi = 0; + off_lo = (DWORD)self->offset; +#endif + SetFilePointer(self->file_handle, + newSizeLow, &newSizeHigh, FILE_BEGIN); + /* Change the size of the file */ + SetEndOfFile(self->file_handle); + /* Create another mapping object and remap the file view */ + self->map_handle = CreateFileMapping( + self->file_handle, + NULL, + PAGE_READWRITE, + 0, + 0, + self->tagname); + if (self->map_handle != NULL) { + self->data = (char *) MapViewOfFile(self->map_handle, + FILE_MAP_WRITE, + off_hi, + off_lo, + new_size); + if (self->data != NULL) { + self->size = new_size; + Py_INCREF(Py_None); + return Py_None; + } else { + dwErrCode = GetLastError(); + CloseHandle(self->map_handle); + self->map_handle = NULL; + } + } else { + dwErrCode = GetLastError(); + } + PyErr_SetFromWindowsErr(dwErrCode); + return NULL; #endif /* MS_WINDOWS */ #ifdef UNIX #ifndef HAVE_MREMAP - } else { - PyErr_SetString(PyExc_SystemError, - "mmap: resizing not available--no mremap()"); - return NULL; + } else { + PyErr_SetString(PyExc_SystemError, + "mmap: resizing not available--no mremap()"); + return NULL; #else - } else { - void *newmap; + } else { + void *newmap; - if (ftruncate(self->fd, self->offset + new_size) == -1) { - PyErr_SetFromErrno(mmap_module_error); - return NULL; - } + if (ftruncate(self->fd, self->offset + new_size) == -1) { + PyErr_SetFromErrno(mmap_module_error); + return NULL; + } #ifdef MREMAP_MAYMOVE - newmap = mremap(self->data, self->size, new_size, MREMAP_MAYMOVE); + newmap = mremap(self->data, self->size, new_size, MREMAP_MAYMOVE); #else - #if defined(__NetBSD__) - newmap = mremap(self->data, self->size, self->data, new_size, 0); - #else - newmap = mremap(self->data, self->size, new_size, 0); - #endif /* __NetBSD__ */ -#endif - if (newmap == (void *)-1) - { - PyErr_SetFromErrno(mmap_module_error); - return NULL; - } - self->data = newmap; - self->size = new_size; - Py_INCREF(Py_None); - return Py_None; + #if defined(__NetBSD__) + newmap = mremap(self->data, self->size, self->data, new_size, 0); + #else + newmap = mremap(self->data, self->size, new_size, 0); + #endif /* __NetBSD__ */ +#endif + if (newmap == (void *)-1) + { + PyErr_SetFromErrno(mmap_module_error); + return NULL; + } + self->data = newmap; + self->size = new_size; + Py_INCREF(Py_None); + return Py_None; #endif /* HAVE_MREMAP */ #endif /* UNIX */ - } + } } static PyObject * mmap_tell_method(mmap_object *self, PyObject *unused) { - CHECK_VALID(NULL); - return PyLong_FromSize_t(self->pos); + CHECK_VALID(NULL); + return PyLong_FromSize_t(self->pos); } static PyObject * mmap_flush_method(mmap_object *self, PyObject *args) { - Py_ssize_t offset = 0; - Py_ssize_t size = self->size; - CHECK_VALID(NULL); - if (!PyArg_ParseTuple(args, "|nn:flush", &offset, &size)) - return NULL; - if ((size_t)(offset + size) > self->size) { - PyErr_SetString(PyExc_ValueError, "flush values out of range"); - return NULL; - } + Py_ssize_t offset = 0; + Py_ssize_t size = self->size; + CHECK_VALID(NULL); + if (!PyArg_ParseTuple(args, "|nn:flush", &offset, &size)) + return NULL; + if ((size_t)(offset + size) > self->size) { + PyErr_SetString(PyExc_ValueError, "flush values out of range"); + return NULL; + } #ifdef MS_WINDOWS - return PyLong_FromLong((long) FlushViewOfFile(self->data+offset, size)); + return PyLong_FromLong((long) FlushViewOfFile(self->data+offset, size)); #elif defined(UNIX) - /* XXX semantics of return value? */ - /* XXX flags for msync? */ - if (-1 == msync(self->data + offset, size, MS_SYNC)) { - PyErr_SetFromErrno(mmap_module_error); - return NULL; - } - return PyLong_FromLong(0); + /* XXX semantics of return value? */ + /* XXX flags for msync? */ + if (-1 == msync(self->data + offset, size, MS_SYNC)) { + PyErr_SetFromErrno(mmap_module_error); + return NULL; + } + return PyLong_FromLong(0); #else - PyErr_SetString(PyExc_ValueError, "flush not supported on this system"); - return NULL; + PyErr_SetString(PyExc_ValueError, "flush not supported on this system"); + return NULL; #endif } static PyObject * mmap_seek_method(mmap_object *self, PyObject *args) { - Py_ssize_t dist; - int how=0; - CHECK_VALID(NULL); - if (!PyArg_ParseTuple(args, "n|i:seek", &dist, &how)) - return NULL; - else { - size_t where; - switch (how) { - case 0: /* relative to start */ - if (dist < 0) - goto onoutofrange; - where = dist; - break; - case 1: /* relative to current position */ - if ((Py_ssize_t)self->pos + dist < 0) - goto onoutofrange; - where = self->pos + dist; - break; - case 2: /* relative to end */ - if ((Py_ssize_t)self->size + dist < 0) - goto onoutofrange; - where = self->size + dist; - break; - default: - PyErr_SetString(PyExc_ValueError, "unknown seek type"); - return NULL; - } - if (where > self->size) - goto onoutofrange; - self->pos = where; - Py_INCREF(Py_None); - return Py_None; - } + Py_ssize_t dist; + int how=0; + CHECK_VALID(NULL); + if (!PyArg_ParseTuple(args, "n|i:seek", &dist, &how)) + return NULL; + else { + size_t where; + switch (how) { + case 0: /* relative to start */ + if (dist < 0) + goto onoutofrange; + where = dist; + break; + case 1: /* relative to current position */ + if ((Py_ssize_t)self->pos + dist < 0) + goto onoutofrange; + where = self->pos + dist; + break; + case 2: /* relative to end */ + if ((Py_ssize_t)self->size + dist < 0) + goto onoutofrange; + where = self->size + dist; + break; + default: + PyErr_SetString(PyExc_ValueError, "unknown seek type"); + return NULL; + } + if (where > self->size) + goto onoutofrange; + self->pos = where; + Py_INCREF(Py_None); + return Py_None; + } onoutofrange: - PyErr_SetString(PyExc_ValueError, "seek out of range"); - return NULL; + PyErr_SetString(PyExc_ValueError, "seek out of range"); + return NULL; } static PyObject * mmap_move_method(mmap_object *self, PyObject *args) { - unsigned long dest, src, cnt; - CHECK_VALID(NULL); - if (!PyArg_ParseTuple(args, "kkk:move", &dest, &src, &cnt) || - !is_writable(self)) { - return NULL; - } else { - /* bounds check the values */ - if (cnt < 0 || (cnt + dest) < cnt || (cnt + src) < cnt || - src < 0 || src > self->size || (src + cnt) > self->size || - dest < 0 || dest > self->size || (dest + cnt) > self->size) { - PyErr_SetString(PyExc_ValueError, - "source, destination, or count out of range"); - return NULL; - } - memmove(self->data+dest, self->data+src, cnt); - Py_INCREF(Py_None); - return Py_None; - } + unsigned long dest, src, cnt; + CHECK_VALID(NULL); + if (!PyArg_ParseTuple(args, "kkk:move", &dest, &src, &cnt) || + !is_writable(self)) { + return NULL; + } else { + /* bounds check the values */ + if (cnt < 0 || (cnt + dest) < cnt || (cnt + src) < cnt || + src < 0 || src > self->size || (src + cnt) > self->size || + dest < 0 || dest > self->size || (dest + cnt) > self->size) { + PyErr_SetString(PyExc_ValueError, + "source, destination, or count out of range"); + return NULL; + } + memmove(self->data+dest, self->data+src, cnt); + Py_INCREF(Py_None); + return Py_None; + } } static struct PyMethodDef mmap_object_methods[] = { - {"close", (PyCFunction) mmap_close_method, METH_NOARGS}, - {"find", (PyCFunction) mmap_find_method, METH_VARARGS}, - {"rfind", (PyCFunction) mmap_rfind_method, METH_VARARGS}, - {"flush", (PyCFunction) mmap_flush_method, METH_VARARGS}, - {"move", (PyCFunction) mmap_move_method, METH_VARARGS}, - {"read", (PyCFunction) mmap_read_method, METH_VARARGS}, - {"read_byte", (PyCFunction) mmap_read_byte_method, METH_NOARGS}, - {"readline", (PyCFunction) mmap_read_line_method, METH_NOARGS}, - {"resize", (PyCFunction) mmap_resize_method, METH_VARARGS}, - {"seek", (PyCFunction) mmap_seek_method, METH_VARARGS}, - {"size", (PyCFunction) mmap_size_method, METH_NOARGS}, - {"tell", (PyCFunction) mmap_tell_method, METH_NOARGS}, - {"write", (PyCFunction) mmap_write_method, METH_VARARGS}, - {"write_byte", (PyCFunction) mmap_write_byte_method, METH_VARARGS}, - {NULL, NULL} /* sentinel */ + {"close", (PyCFunction) mmap_close_method, METH_NOARGS}, + {"find", (PyCFunction) mmap_find_method, METH_VARARGS}, + {"rfind", (PyCFunction) mmap_rfind_method, METH_VARARGS}, + {"flush", (PyCFunction) mmap_flush_method, METH_VARARGS}, + {"move", (PyCFunction) mmap_move_method, METH_VARARGS}, + {"read", (PyCFunction) mmap_read_method, METH_VARARGS}, + {"read_byte", (PyCFunction) mmap_read_byte_method, METH_NOARGS}, + {"readline", (PyCFunction) mmap_read_line_method, METH_NOARGS}, + {"resize", (PyCFunction) mmap_resize_method, METH_VARARGS}, + {"seek", (PyCFunction) mmap_seek_method, METH_VARARGS}, + {"size", (PyCFunction) mmap_size_method, METH_NOARGS}, + {"tell", (PyCFunction) mmap_tell_method, METH_NOARGS}, + {"write", (PyCFunction) mmap_write_method, METH_VARARGS}, + {"write_byte", (PyCFunction) mmap_write_byte_method, METH_VARARGS}, + {NULL, NULL} /* sentinel */ }; /* Functions for treating an mmap'ed file as a buffer */ @@ -674,247 +674,247 @@ static int mmap_buffer_getbuf(mmap_object *self, Py_buffer *view, int flags) { - CHECK_VALID(-1); - if (PyBuffer_FillInfo(view, (PyObject*)self, self->data, self->size, - (self->access == ACCESS_READ), flags) < 0) - return -1; - self->exports++; - return 0; + CHECK_VALID(-1); + if (PyBuffer_FillInfo(view, (PyObject*)self, self->data, self->size, + (self->access == ACCESS_READ), flags) < 0) + return -1; + self->exports++; + return 0; } static void mmap_buffer_releasebuf(mmap_object *self, Py_buffer *view) { - self->exports--; + self->exports--; } static Py_ssize_t mmap_length(mmap_object *self) { - CHECK_VALID(-1); - return self->size; + CHECK_VALID(-1); + return self->size; } static PyObject * mmap_item(mmap_object *self, Py_ssize_t i) { - CHECK_VALID(NULL); - if (i < 0 || (size_t)i >= self->size) { - PyErr_SetString(PyExc_IndexError, "mmap index out of range"); - return NULL; - } - return PyBytes_FromStringAndSize(self->data + i, 1); + CHECK_VALID(NULL); + if (i < 0 || (size_t)i >= self->size) { + PyErr_SetString(PyExc_IndexError, "mmap index out of range"); + return NULL; + } + return PyBytes_FromStringAndSize(self->data + i, 1); } static PyObject * mmap_subscript(mmap_object *self, PyObject *item) { - CHECK_VALID(NULL); - 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 += self->size; - if (i < 0 || (size_t)i >= self->size) { - PyErr_SetString(PyExc_IndexError, - "mmap index out of range"); - return NULL; - } - return PyLong_FromLong(Py_CHARMASK(self->data[i])); - } - else if (PySlice_Check(item)) { - Py_ssize_t start, stop, step, slicelen; - - if (PySlice_GetIndicesEx((PySliceObject *)item, self->size, - &start, &stop, &step, &slicelen) < 0) { - return NULL; - } - - if (slicelen <= 0) - return PyBytes_FromStringAndSize("", 0); - else if (step == 1) - return PyBytes_FromStringAndSize(self->data + start, - slicelen); - else { - char *result_buf = (char *)PyMem_Malloc(slicelen); - Py_ssize_t cur, i; - PyObject *result; - - if (result_buf == NULL) - return PyErr_NoMemory(); - for (cur = start, i = 0; i < slicelen; - cur += step, i++) { - result_buf[i] = self->data[cur]; - } - result = PyBytes_FromStringAndSize(result_buf, - slicelen); - PyMem_Free(result_buf); - return result; - } - } - else { - PyErr_SetString(PyExc_TypeError, - "mmap indices must be integers"); - return NULL; - } + CHECK_VALID(NULL); + 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 += self->size; + if (i < 0 || (size_t)i >= self->size) { + PyErr_SetString(PyExc_IndexError, + "mmap index out of range"); + return NULL; + } + return PyLong_FromLong(Py_CHARMASK(self->data[i])); + } + else if (PySlice_Check(item)) { + Py_ssize_t start, stop, step, slicelen; + + if (PySlice_GetIndicesEx((PySliceObject *)item, self->size, + &start, &stop, &step, &slicelen) < 0) { + return NULL; + } + + if (slicelen <= 0) + return PyBytes_FromStringAndSize("", 0); + else if (step == 1) + return PyBytes_FromStringAndSize(self->data + start, + slicelen); + else { + char *result_buf = (char *)PyMem_Malloc(slicelen); + Py_ssize_t cur, i; + PyObject *result; + + if (result_buf == NULL) + return PyErr_NoMemory(); + for (cur = start, i = 0; i < slicelen; + cur += step, i++) { + result_buf[i] = self->data[cur]; + } + result = PyBytes_FromStringAndSize(result_buf, + slicelen); + PyMem_Free(result_buf); + return result; + } + } + else { + PyErr_SetString(PyExc_TypeError, + "mmap indices must be integers"); + return NULL; + } } static PyObject * mmap_concat(mmap_object *self, PyObject *bb) { - CHECK_VALID(NULL); - PyErr_SetString(PyExc_SystemError, - "mmaps don't support concatenation"); - return NULL; + 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; + CHECK_VALID(NULL); + PyErr_SetString(PyExc_SystemError, + "mmaps don't support repeat operation"); + return NULL; } static int mmap_ass_item(mmap_object *self, Py_ssize_t i, PyObject *v) { - const char *buf; + const char *buf; - CHECK_VALID(-1); - if (i < 0 || (size_t)i >= self->size) { - PyErr_SetString(PyExc_IndexError, "mmap index out of range"); - return -1; - } - if (v == NULL) { - PyErr_SetString(PyExc_TypeError, - "mmap object doesn't support item deletion"); - return -1; - } - if (! (PyBytes_Check(v) && PyBytes_Size(v)==1) ) { - PyErr_SetString(PyExc_IndexError, - "mmap assignment must be length-1 bytes()"); - return -1; - } - if (!is_writable(self)) - return -1; - buf = PyBytes_AsString(v); - self->data[i] = buf[0]; - return 0; + CHECK_VALID(-1); + if (i < 0 || (size_t)i >= self->size) { + PyErr_SetString(PyExc_IndexError, "mmap index out of range"); + return -1; + } + if (v == NULL) { + PyErr_SetString(PyExc_TypeError, + "mmap object doesn't support item deletion"); + return -1; + } + if (! (PyBytes_Check(v) && PyBytes_Size(v)==1) ) { + PyErr_SetString(PyExc_IndexError, + "mmap assignment must be length-1 bytes()"); + return -1; + } + if (!is_writable(self)) + return -1; + buf = PyBytes_AsString(v); + self->data[i] = buf[0]; + return 0; } static int mmap_ass_subscript(mmap_object *self, PyObject *item, PyObject *value) { - CHECK_VALID(-1); + CHECK_VALID(-1); + + if (!is_writable(self)) + return -1; + + if (PyIndex_Check(item)) { + Py_ssize_t i = PyNumber_AsSsize_t(item, PyExc_IndexError); + Py_ssize_t v; + + if (i == -1 && PyErr_Occurred()) + return -1; + if (i < 0) + i += self->size; + if (i < 0 || (size_t)i >= self->size) { + PyErr_SetString(PyExc_IndexError, + "mmap index out of range"); + return -1; + } + if (value == NULL) { + PyErr_SetString(PyExc_TypeError, + "mmap doesn't support item deletion"); + return -1; + } + if (!PyIndex_Check(value)) { + PyErr_SetString(PyExc_TypeError, + "mmap item value must be an int"); + return -1; + } + v = PyNumber_AsSsize_t(value, PyExc_TypeError); + if (v == -1 && PyErr_Occurred()) + return -1; + if (v < 0 || v > 255) { + PyErr_SetString(PyExc_ValueError, + "mmap item value must be " + "in range(0, 256)"); + return -1; + } + self->data[i] = v; + return 0; + } + else if (PySlice_Check(item)) { + Py_ssize_t start, stop, step, slicelen; + Py_buffer vbuf; + + if (PySlice_GetIndicesEx((PySliceObject *)item, + self->size, &start, &stop, + &step, &slicelen) < 0) { + return -1; + } + if (value == NULL) { + PyErr_SetString(PyExc_TypeError, + "mmap object doesn't support slice deletion"); + return -1; + } + if (PyObject_GetBuffer(value, &vbuf, PyBUF_SIMPLE) < 0) + return -1; + if (vbuf.len != slicelen) { + PyErr_SetString(PyExc_IndexError, + "mmap slice assignment is wrong size"); + PyBuffer_Release(&vbuf); + return -1; + } - if (!is_writable(self)) - return -1; + if (slicelen == 0) { + } + else if (step == 1) { + memcpy(self->data + start, vbuf.buf, slicelen); + } + else { + Py_ssize_t cur, i; - if (PyIndex_Check(item)) { - Py_ssize_t i = PyNumber_AsSsize_t(item, PyExc_IndexError); - Py_ssize_t v; - - if (i == -1 && PyErr_Occurred()) - return -1; - if (i < 0) - i += self->size; - if (i < 0 || (size_t)i >= self->size) { - PyErr_SetString(PyExc_IndexError, - "mmap index out of range"); - return -1; - } - if (value == NULL) { - PyErr_SetString(PyExc_TypeError, - "mmap doesn't support item deletion"); - return -1; - } - if (!PyIndex_Check(value)) { - PyErr_SetString(PyExc_TypeError, - "mmap item value must be an int"); - return -1; - } - v = PyNumber_AsSsize_t(value, PyExc_TypeError); - if (v == -1 && PyErr_Occurred()) - return -1; - if (v < 0 || v > 255) { - PyErr_SetString(PyExc_ValueError, - "mmap item value must be " - "in range(0, 256)"); - return -1; - } - self->data[i] = v; - return 0; - } - else if (PySlice_Check(item)) { - Py_ssize_t start, stop, step, slicelen; - Py_buffer vbuf; - - if (PySlice_GetIndicesEx((PySliceObject *)item, - self->size, &start, &stop, - &step, &slicelen) < 0) { - return -1; - } - if (value == NULL) { - PyErr_SetString(PyExc_TypeError, - "mmap object doesn't support slice deletion"); - return -1; - } - if (PyObject_GetBuffer(value, &vbuf, PyBUF_SIMPLE) < 0) - return -1; - if (vbuf.len != slicelen) { - PyErr_SetString(PyExc_IndexError, - "mmap slice assignment is wrong size"); - PyBuffer_Release(&vbuf); - return -1; - } - - if (slicelen == 0) { - } - else if (step == 1) { - memcpy(self->data + start, vbuf.buf, slicelen); - } - else { - Py_ssize_t cur, i; - - for (cur = start, i = 0; - i < slicelen; - cur += step, i++) - { - self->data[cur] = ((char *)vbuf.buf)[i]; - } - } - PyBuffer_Release(&vbuf); - return 0; - } - else { - PyErr_SetString(PyExc_TypeError, - "mmap indices must be integer"); - return -1; - } + for (cur = start, i = 0; + i < slicelen; + cur += step, i++) + { + self->data[cur] = ((char *)vbuf.buf)[i]; + } + } + PyBuffer_Release(&vbuf); + return 0; + } + else { + PyErr_SetString(PyExc_TypeError, + "mmap indices must be integer"); + return -1; + } } 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_slice*/ - (ssizeobjargproc)mmap_ass_item, /*sq_ass_item*/ - 0, /*sq_ass_slice*/ + (lenfunc)mmap_length, /*sq_length*/ + (binaryfunc)mmap_concat, /*sq_concat*/ + (ssizeargfunc)mmap_repeat, /*sq_repeat*/ + (ssizeargfunc)mmap_item, /*sq_item*/ + 0, /*sq_slice*/ + (ssizeobjargproc)mmap_ass_item, /*sq_ass_item*/ + 0, /*sq_ass_slice*/ }; static PyMappingMethods mmap_as_mapping = { - (lenfunc)mmap_length, - (binaryfunc)mmap_subscript, - (objobjargproc)mmap_ass_subscript, + (lenfunc)mmap_length, + (binaryfunc)mmap_subscript, + (objobjargproc)mmap_ass_subscript, }; static PyBufferProcs mmap_as_buffer = { - (getbufferproc)mmap_buffer_getbuf, - (releasebufferproc)mmap_buffer_releasebuf, + (getbufferproc)mmap_buffer_getbuf, + (releasebufferproc)mmap_buffer_releasebuf, }; static PyObject * @@ -945,46 +945,46 @@ static PyTypeObject mmap_object_type = { - PyVarObject_HEAD_INIT(NULL, 0) - "mmap.mmap", /* tp_name */ - sizeof(mmap_object), /* tp_size */ - 0, /* tp_itemsize */ - /* methods */ - (destructor) mmap_object_dealloc, /* tp_dealloc */ - 0, /* tp_print */ - 0, /* tp_getattr */ - 0, /* tp_setattr */ - 0, /* tp_reserved */ - 0, /* tp_repr */ - 0, /* tp_as_number */ - &mmap_as_sequence, /*tp_as_sequence*/ - &mmap_as_mapping, /*tp_as_mapping*/ - 0, /*tp_hash*/ - 0, /*tp_call*/ - 0, /*tp_str*/ - PyObject_GenericGetAttr, /*tp_getattro*/ - 0, /*tp_setattro*/ - &mmap_as_buffer, /*tp_as_buffer*/ - Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /*tp_flags*/ - mmap_doc, /*tp_doc*/ - 0, /* tp_traverse */ - 0, /* tp_clear */ - 0, /* tp_richcompare */ - 0, /* tp_weaklistoffset */ - 0, /* tp_iter */ - 0, /* tp_iternext */ - mmap_object_methods, /* tp_methods */ - 0, /* tp_members */ - 0, /* tp_getset */ - 0, /* tp_base */ - 0, /* tp_dict */ - 0, /* tp_descr_get */ - 0, /* tp_descr_set */ - 0, /* tp_dictoffset */ - 0, /* tp_init */ - PyType_GenericAlloc, /* tp_alloc */ - new_mmap_object, /* tp_new */ - PyObject_Del, /* tp_free */ + PyVarObject_HEAD_INIT(NULL, 0) + "mmap.mmap", /* tp_name */ + sizeof(mmap_object), /* tp_size */ + 0, /* tp_itemsize */ + /* methods */ + (destructor) mmap_object_dealloc, /* tp_dealloc */ + 0, /* tp_print */ + 0, /* tp_getattr */ + 0, /* tp_setattr */ + 0, /* tp_reserved */ + 0, /* tp_repr */ + 0, /* tp_as_number */ + &mmap_as_sequence, /*tp_as_sequence*/ + &mmap_as_mapping, /*tp_as_mapping*/ + 0, /*tp_hash*/ + 0, /*tp_call*/ + 0, /*tp_str*/ + PyObject_GenericGetAttr, /*tp_getattro*/ + 0, /*tp_setattro*/ + &mmap_as_buffer, /*tp_as_buffer*/ + Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /*tp_flags*/ + mmap_doc, /*tp_doc*/ + 0, /* tp_traverse */ + 0, /* tp_clear */ + 0, /* tp_richcompare */ + 0, /* tp_weaklistoffset */ + 0, /* tp_iter */ + 0, /* tp_iternext */ + mmap_object_methods, /* tp_methods */ + 0, /* tp_members */ + 0, /* tp_getset */ + 0, /* tp_base */ + 0, /* tp_dict */ + 0, /* tp_descr_get */ + 0, /* tp_descr_set */ + 0, /* tp_dictoffset */ + 0, /* tp_init */ + PyType_GenericAlloc, /* tp_alloc */ + new_mmap_object, /* tp_new */ + PyObject_Del, /* tp_free */ }; @@ -995,23 +995,23 @@ static Py_ssize_t _GetMapSize(PyObject *o, const char* param) { - if (o == NULL) - return 0; - if (PyIndex_Check(o)) { - Py_ssize_t i = PyNumber_AsSsize_t(o, PyExc_OverflowError); - if (i==-1 && PyErr_Occurred()) - return -1; - if (i < 0) { - PyErr_Format(PyExc_OverflowError, - "memory mapped %s must be positive", - param); - return -1; - } - return i; - } + if (o == NULL) + return 0; + if (PyIndex_Check(o)) { + Py_ssize_t i = PyNumber_AsSsize_t(o, PyExc_OverflowError); + if (i==-1 && PyErr_Occurred()) + return -1; + if (i < 0) { + PyErr_Format(PyExc_OverflowError, + "memory mapped %s must be positive", + param); + return -1; + } + return i; + } - PyErr_SetString(PyExc_TypeError, "map size must be an integral value"); - return -1; + PyErr_SetString(PyExc_TypeError, "map size must be an integral value"); + return -1; } #ifdef UNIX @@ -1019,125 +1019,125 @@ new_mmap_object(PyTypeObject *type, PyObject *args, PyObject *kwdict) { #ifdef HAVE_FSTAT - struct stat st; + struct stat st; #endif - mmap_object *m_obj; - PyObject *map_size_obj = NULL, *offset_obj = NULL; - Py_ssize_t map_size, offset; - int fd, flags = MAP_SHARED, prot = PROT_WRITE | PROT_READ; - int devzero = -1; - int access = (int)ACCESS_DEFAULT; - static char *keywords[] = {"fileno", "length", - "flags", "prot", - "access", "offset", NULL}; - - if (!PyArg_ParseTupleAndKeywords(args, kwdict, "iO|iiiO", keywords, - &fd, &map_size_obj, &flags, &prot, - &access, &offset_obj)) - return NULL; - map_size = _GetMapSize(map_size_obj, "size"); - if (map_size < 0) - return NULL; - offset = _GetMapSize(offset_obj, "offset"); - if (offset < 0) - return NULL; - - if ((access != (int)ACCESS_DEFAULT) && - ((flags != MAP_SHARED) || (prot != (PROT_WRITE | PROT_READ)))) - return PyErr_Format(PyExc_ValueError, - "mmap can't specify both access and flags, prot."); - switch ((access_mode)access) { - case ACCESS_READ: - flags = MAP_SHARED; - prot = PROT_READ; - break; - case ACCESS_WRITE: - flags = MAP_SHARED; - prot = PROT_READ | PROT_WRITE; - break; - case ACCESS_COPY: - flags = MAP_PRIVATE; - prot = PROT_READ | PROT_WRITE; - break; - case ACCESS_DEFAULT: - /* use the specified or default values of flags and prot */ - break; - default: - return PyErr_Format(PyExc_ValueError, - "mmap invalid access parameter."); - } + mmap_object *m_obj; + PyObject *map_size_obj = NULL, *offset_obj = NULL; + Py_ssize_t map_size, offset; + int fd, flags = MAP_SHARED, prot = PROT_WRITE | PROT_READ; + int devzero = -1; + int access = (int)ACCESS_DEFAULT; + static char *keywords[] = {"fileno", "length", + "flags", "prot", + "access", "offset", NULL}; + + if (!PyArg_ParseTupleAndKeywords(args, kwdict, "iO|iiiO", keywords, + &fd, &map_size_obj, &flags, &prot, + &access, &offset_obj)) + return NULL; + map_size = _GetMapSize(map_size_obj, "size"); + if (map_size < 0) + return NULL; + offset = _GetMapSize(offset_obj, "offset"); + if (offset < 0) + return NULL; + + if ((access != (int)ACCESS_DEFAULT) && + ((flags != MAP_SHARED) || (prot != (PROT_WRITE | PROT_READ)))) + return PyErr_Format(PyExc_ValueError, + "mmap can't specify both access and flags, prot."); + switch ((access_mode)access) { + case ACCESS_READ: + flags = MAP_SHARED; + prot = PROT_READ; + break; + case ACCESS_WRITE: + flags = MAP_SHARED; + prot = PROT_READ | PROT_WRITE; + break; + case ACCESS_COPY: + flags = MAP_PRIVATE; + prot = PROT_READ | PROT_WRITE; + break; + case ACCESS_DEFAULT: + /* use the specified or default values of flags and prot */ + break; + default: + return PyErr_Format(PyExc_ValueError, + "mmap invalid access parameter."); + } if (prot == PROT_READ) { - access = ACCESS_READ; + access = ACCESS_READ; } #ifdef HAVE_FSTAT # ifdef __VMS - /* on OpenVMS we must ensure that all bytes are written to the file */ - if (fd != -1) { - fsync(fd); - } + /* on OpenVMS we must ensure that all bytes are written to the file */ + if (fd != -1) { + fsync(fd); + } # endif - if (fd != -1 && fstat(fd, &st) == 0 && S_ISREG(st.st_mode)) { - if (map_size == 0) { - map_size = st.st_size; - } else if ((size_t)offset + (size_t)map_size > st.st_size) { - PyErr_SetString(PyExc_ValueError, - "mmap length is greater than file size"); - return NULL; - } - } -#endif - m_obj = (mmap_object *)type->tp_alloc(type, 0); - if (m_obj == NULL) {return NULL;} - m_obj->data = NULL; - m_obj->size = (size_t) map_size; - m_obj->pos = (size_t) 0; - m_obj->exports = 0; - m_obj->offset = offset; - if (fd == -1) { - m_obj->fd = -1; - /* Assume the caller wants to map anonymous memory. - This is the same behaviour as Windows. mmap.mmap(-1, size) - on both Windows and Unix map anonymous memory. - */ + if (fd != -1 && fstat(fd, &st) == 0 && S_ISREG(st.st_mode)) { + if (map_size == 0) { + map_size = st.st_size; + } else if ((size_t)offset + (size_t)map_size > st.st_size) { + PyErr_SetString(PyExc_ValueError, + "mmap length is greater than file size"); + return NULL; + } + } +#endif + m_obj = (mmap_object *)type->tp_alloc(type, 0); + if (m_obj == NULL) {return NULL;} + m_obj->data = NULL; + m_obj->size = (size_t) map_size; + m_obj->pos = (size_t) 0; + m_obj->exports = 0; + m_obj->offset = offset; + if (fd == -1) { + m_obj->fd = -1; + /* Assume the caller wants to map anonymous memory. + This is the same behaviour as Windows. mmap.mmap(-1, size) + on both Windows and Unix map anonymous memory. + */ #ifdef MAP_ANONYMOUS - /* BSD way to map anonymous memory */ - flags |= MAP_ANONYMOUS; + /* BSD way to map anonymous memory */ + flags |= MAP_ANONYMOUS; #else - /* SVR4 method to map anonymous memory is to open /dev/zero */ - fd = devzero = open("/dev/zero", O_RDWR); - if (devzero == -1) { - Py_DECREF(m_obj); - PyErr_SetFromErrno(mmap_module_error); - return NULL; - } -#endif - } else { - m_obj->fd = dup(fd); - if (m_obj->fd == -1) { - Py_DECREF(m_obj); - PyErr_SetFromErrno(mmap_module_error); - return NULL; - } - } - - m_obj->data = mmap(NULL, map_size, - prot, flags, - fd, offset); - - if (devzero != -1) { - close(devzero); - } - - if (m_obj->data == (char *)-1) { - m_obj->data = NULL; - Py_DECREF(m_obj); - PyErr_SetFromErrno(mmap_module_error); - return NULL; - } - m_obj->access = (access_mode)access; - return (PyObject *)m_obj; + /* SVR4 method to map anonymous memory is to open /dev/zero */ + fd = devzero = open("/dev/zero", O_RDWR); + if (devzero == -1) { + Py_DECREF(m_obj); + PyErr_SetFromErrno(mmap_module_error); + return NULL; + } +#endif + } else { + m_obj->fd = dup(fd); + if (m_obj->fd == -1) { + Py_DECREF(m_obj); + PyErr_SetFromErrno(mmap_module_error); + return NULL; + } + } + + m_obj->data = mmap(NULL, map_size, + prot, flags, + fd, offset); + + if (devzero != -1) { + close(devzero); + } + + if (m_obj->data == (char *)-1) { + m_obj->data = NULL; + Py_DECREF(m_obj); + PyErr_SetFromErrno(mmap_module_error); + return NULL; + } + m_obj->access = (access_mode)access; + return (PyObject *)m_obj; } #endif /* UNIX */ @@ -1145,266 +1145,266 @@ static PyObject * new_mmap_object(PyTypeObject *type, PyObject *args, PyObject *kwdict) { - mmap_object *m_obj; - PyObject *map_size_obj = NULL, *offset_obj = NULL; - Py_ssize_t map_size, offset; - DWORD off_hi; /* upper 32 bits of offset */ - DWORD off_lo; /* lower 32 bits of offset */ - DWORD size_hi; /* upper 32 bits of size */ - DWORD size_lo; /* lower 32 bits of size */ - char *tagname = ""; - DWORD dwErr = 0; - int fileno; - HANDLE fh = 0; - int access = (access_mode)ACCESS_DEFAULT; - DWORD flProtect, dwDesiredAccess; - static char *keywords[] = { "fileno", "length", - "tagname", - "access", "offset", NULL }; - - if (!PyArg_ParseTupleAndKeywords(args, kwdict, "iO|ziO", keywords, - &fileno, &map_size_obj, - &tagname, &access, &offset_obj)) { - return NULL; - } - - switch((access_mode)access) { - case ACCESS_READ: - flProtect = PAGE_READONLY; - dwDesiredAccess = FILE_MAP_READ; - break; - case ACCESS_DEFAULT: case ACCESS_WRITE: - flProtect = PAGE_READWRITE; - dwDesiredAccess = FILE_MAP_WRITE; - break; - case ACCESS_COPY: - flProtect = PAGE_WRITECOPY; - dwDesiredAccess = FILE_MAP_COPY; - break; - default: - return PyErr_Format(PyExc_ValueError, - "mmap invalid access parameter."); - } - - map_size = _GetMapSize(map_size_obj, "size"); - if (map_size < 0) - return NULL; - offset = _GetMapSize(offset_obj, "offset"); - if (offset < 0) - return NULL; - - /* assume -1 and 0 both mean invalid filedescriptor - to 'anonymously' map memory. - XXX: fileno == 0 is a valid fd, but was accepted prior to 2.5. - XXX: Should this code be added? - if (fileno == 0) - PyErr_WarnEx(PyExc_DeprecationWarning, - "don't use 0 for anonymous memory", - 1); - */ - if (fileno != -1 && fileno != 0) { - fh = (HANDLE)_get_osfhandle(fileno); - if (fh==(HANDLE)-1) { - PyErr_SetFromErrno(mmap_module_error); - return NULL; - } - /* Win9x appears to need us seeked to zero */ - lseek(fileno, 0, SEEK_SET); - } - - m_obj = (mmap_object *)type->tp_alloc(type, 0); - if (m_obj == NULL) - return NULL; - /* Set every field to an invalid marker, so we can safely - destruct the object in the face of failure */ - m_obj->data = NULL; - m_obj->file_handle = INVALID_HANDLE_VALUE; - m_obj->map_handle = NULL; - m_obj->tagname = NULL; - m_obj->offset = offset; - - if (fh) { - /* It is necessary to duplicate the handle, so the - Python code can close it on us */ - if (!DuplicateHandle( - GetCurrentProcess(), /* source process handle */ - fh, /* handle to be duplicated */ - GetCurrentProcess(), /* target proc handle */ - (LPHANDLE)&m_obj->file_handle, /* result */ - 0, /* access - ignored due to options value */ - FALSE, /* inherited by child processes? */ - DUPLICATE_SAME_ACCESS)) { /* options */ - dwErr = GetLastError(); - Py_DECREF(m_obj); - PyErr_SetFromWindowsErr(dwErr); - return NULL; - } - if (!map_size) { - DWORD low,high; - low = GetFileSize(fh, &high); - /* low might just happen to have the value INVALID_FILE_SIZE; - so we need to check the last error also. */ - if (low == INVALID_FILE_SIZE && - (dwErr = GetLastError()) != NO_ERROR) { - Py_DECREF(m_obj); - return PyErr_SetFromWindowsErr(dwErr); - } + mmap_object *m_obj; + PyObject *map_size_obj = NULL, *offset_obj = NULL; + Py_ssize_t map_size, offset; + DWORD off_hi; /* upper 32 bits of offset */ + DWORD off_lo; /* lower 32 bits of offset */ + DWORD size_hi; /* upper 32 bits of size */ + DWORD size_lo; /* lower 32 bits of size */ + char *tagname = ""; + DWORD dwErr = 0; + int fileno; + HANDLE fh = 0; + int access = (access_mode)ACCESS_DEFAULT; + DWORD flProtect, dwDesiredAccess; + static char *keywords[] = { "fileno", "length", + "tagname", + "access", "offset", NULL }; + + if (!PyArg_ParseTupleAndKeywords(args, kwdict, "iO|ziO", keywords, + &fileno, &map_size_obj, + &tagname, &access, &offset_obj)) { + return NULL; + } + + switch((access_mode)access) { + case ACCESS_READ: + flProtect = PAGE_READONLY; + dwDesiredAccess = FILE_MAP_READ; + break; + case ACCESS_DEFAULT: case ACCESS_WRITE: + flProtect = PAGE_READWRITE; + dwDesiredAccess = FILE_MAP_WRITE; + break; + case ACCESS_COPY: + flProtect = PAGE_WRITECOPY; + dwDesiredAccess = FILE_MAP_COPY; + break; + default: + return PyErr_Format(PyExc_ValueError, + "mmap invalid access parameter."); + } + + map_size = _GetMapSize(map_size_obj, "size"); + if (map_size < 0) + return NULL; + offset = _GetMapSize(offset_obj, "offset"); + if (offset < 0) + return NULL; + + /* assume -1 and 0 both mean invalid filedescriptor + to 'anonymously' map memory. + XXX: fileno == 0 is a valid fd, but was accepted prior to 2.5. + XXX: Should this code be added? + if (fileno == 0) + PyErr_WarnEx(PyExc_DeprecationWarning, + "don't use 0 for anonymous memory", + 1); + */ + if (fileno != -1 && fileno != 0) { + fh = (HANDLE)_get_osfhandle(fileno); + if (fh==(HANDLE)-1) { + PyErr_SetFromErrno(mmap_module_error); + return NULL; + } + /* Win9x appears to need us seeked to zero */ + lseek(fileno, 0, SEEK_SET); + } + + m_obj = (mmap_object *)type->tp_alloc(type, 0); + if (m_obj == NULL) + return NULL; + /* Set every field to an invalid marker, so we can safely + destruct the object in the face of failure */ + m_obj->data = NULL; + m_obj->file_handle = INVALID_HANDLE_VALUE; + m_obj->map_handle = NULL; + m_obj->tagname = NULL; + m_obj->offset = offset; + + if (fh) { + /* It is necessary to duplicate the handle, so the + Python code can close it on us */ + if (!DuplicateHandle( + GetCurrentProcess(), /* source process handle */ + fh, /* handle to be duplicated */ + GetCurrentProcess(), /* target proc handle */ + (LPHANDLE)&m_obj->file_handle, /* result */ + 0, /* access - ignored due to options value */ + FALSE, /* inherited by child processes? */ + DUPLICATE_SAME_ACCESS)) { /* options */ + dwErr = GetLastError(); + Py_DECREF(m_obj); + PyErr_SetFromWindowsErr(dwErr); + return NULL; + } + if (!map_size) { + DWORD low,high; + low = GetFileSize(fh, &high); + /* low might just happen to have the value INVALID_FILE_SIZE; + so we need to check the last error also. */ + if (low == INVALID_FILE_SIZE && + (dwErr = GetLastError()) != NO_ERROR) { + Py_DECREF(m_obj); + return PyErr_SetFromWindowsErr(dwErr); + } #if SIZEOF_SIZE_T > 4 - m_obj->size = (((size_t)high)<<32) + low; + m_obj->size = (((size_t)high)<<32) + low; #else - if (high) - /* File is too large to map completely */ - m_obj->size = (size_t)-1; - else - m_obj->size = low; -#endif - } else { - m_obj->size = map_size; - } - } - else { - m_obj->size = map_size; - } - - /* set the initial position */ - m_obj->pos = (size_t) 0; - - m_obj->exports = 0; - /* set the tag name */ - if (tagname != NULL && *tagname != '\0') { - m_obj->tagname = PyMem_Malloc(strlen(tagname)+1); - if (m_obj->tagname == NULL) { - PyErr_NoMemory(); - Py_DECREF(m_obj); - return NULL; - } - strcpy(m_obj->tagname, tagname); - } - else - m_obj->tagname = NULL; - - m_obj->access = (access_mode)access; - /* DWORD is a 4-byte int. If we're on a box where size_t consumes - * more than 4 bytes, we need to break it apart. Else (size_t - * consumes 4 bytes), C doesn't define what happens if we shift - * right by 32, so we need different code. - */ + if (high) + /* File is too large to map completely */ + m_obj->size = (size_t)-1; + else + m_obj->size = low; +#endif + } else { + m_obj->size = map_size; + } + } + else { + m_obj->size = map_size; + } + + /* set the initial position */ + m_obj->pos = (size_t) 0; + + m_obj->exports = 0; + /* set the tag name */ + if (tagname != NULL && *tagname != '\0') { + m_obj->tagname = PyMem_Malloc(strlen(tagname)+1); + if (m_obj->tagname == NULL) { + PyErr_NoMemory(); + Py_DECREF(m_obj); + return NULL; + } + strcpy(m_obj->tagname, tagname); + } + else + m_obj->tagname = NULL; + + m_obj->access = (access_mode)access; + /* DWORD is a 4-byte int. If we're on a box where size_t consumes + * more than 4 bytes, we need to break it apart. Else (size_t + * consumes 4 bytes), C doesn't define what happens if we shift + * right by 32, so we need different code. + */ #if SIZEOF_SIZE_T > 4 - size_hi = (DWORD)((offset + m_obj->size) >> 32); - size_lo = (DWORD)((offset + m_obj->size) & 0xFFFFFFFF); - off_hi = (DWORD)(offset >> 32); - off_lo = (DWORD)(offset & 0xFFFFFFFF); + size_hi = (DWORD)((offset + m_obj->size) >> 32); + size_lo = (DWORD)((offset + m_obj->size) & 0xFFFFFFFF); + off_hi = (DWORD)(offset >> 32); + off_lo = (DWORD)(offset & 0xFFFFFFFF); #else - size_hi = 0; - size_lo = (DWORD)(offset + m_obj->size); - off_hi = 0; - off_lo = (DWORD)offset; -#endif - /* For files, it would be sufficient to pass 0 as size. - For anonymous maps, we have to pass the size explicitly. */ - m_obj->map_handle = CreateFileMapping(m_obj->file_handle, - NULL, - flProtect, - size_hi, - size_lo, - m_obj->tagname); - if (m_obj->map_handle != NULL) { - m_obj->data = (char *) MapViewOfFile(m_obj->map_handle, - dwDesiredAccess, - off_hi, - off_lo, - m_obj->size); - if (m_obj->data != NULL) - return (PyObject *)m_obj; - else { - dwErr = GetLastError(); - CloseHandle(m_obj->map_handle); - m_obj->map_handle = NULL; - } - } else - dwErr = GetLastError(); - Py_DECREF(m_obj); - PyErr_SetFromWindowsErr(dwErr); - return NULL; + size_hi = 0; + size_lo = (DWORD)(offset + m_obj->size); + off_hi = 0; + off_lo = (DWORD)offset; +#endif + /* For files, it would be sufficient to pass 0 as size. + For anonymous maps, we have to pass the size explicitly. */ + m_obj->map_handle = CreateFileMapping(m_obj->file_handle, + NULL, + flProtect, + size_hi, + size_lo, + m_obj->tagname); + if (m_obj->map_handle != NULL) { + m_obj->data = (char *) MapViewOfFile(m_obj->map_handle, + dwDesiredAccess, + off_hi, + off_lo, + m_obj->size); + if (m_obj->data != NULL) + return (PyObject *)m_obj; + else { + dwErr = GetLastError(); + CloseHandle(m_obj->map_handle); + m_obj->map_handle = NULL; + } + } else + dwErr = GetLastError(); + Py_DECREF(m_obj); + PyErr_SetFromWindowsErr(dwErr); + return NULL; } #endif /* MS_WINDOWS */ static void setint(PyObject *d, const char *name, long value) { - PyObject *o = PyLong_FromLong(value); - if (o && PyDict_SetItemString(d, name, o) == 0) { - Py_DECREF(o); - } + PyObject *o = PyLong_FromLong(value); + if (o && PyDict_SetItemString(d, name, o) == 0) { + Py_DECREF(o); + } } static struct PyModuleDef mmapmodule = { - PyModuleDef_HEAD_INIT, - "mmap", - NULL, - -1, - NULL, - NULL, - NULL, - NULL, - NULL + PyModuleDef_HEAD_INIT, + "mmap", + NULL, + -1, + NULL, + NULL, + NULL, + NULL, + NULL }; PyMODINIT_FUNC PyInit_mmap(void) { - PyObject *dict, *module; + PyObject *dict, *module; - if (PyType_Ready(&mmap_object_type) < 0) - return NULL; + if (PyType_Ready(&mmap_object_type) < 0) + return NULL; - module = PyModule_Create(&mmapmodule); - if (module == NULL) - return NULL; - dict = PyModule_GetDict(module); - if (!dict) - return NULL; - mmap_module_error = PyErr_NewException("mmap.error", - PyExc_EnvironmentError , NULL); - if (mmap_module_error == NULL) - return NULL; - PyDict_SetItemString(dict, "error", mmap_module_error); - PyDict_SetItemString(dict, "mmap", (PyObject*) &mmap_object_type); + module = PyModule_Create(&mmapmodule); + if (module == NULL) + return NULL; + dict = PyModule_GetDict(module); + if (!dict) + return NULL; + mmap_module_error = PyErr_NewException("mmap.error", + PyExc_EnvironmentError , NULL); + if (mmap_module_error == NULL) + return NULL; + PyDict_SetItemString(dict, "error", mmap_module_error); + PyDict_SetItemString(dict, "mmap", (PyObject*) &mmap_object_type); #ifdef PROT_EXEC - setint(dict, "PROT_EXEC", PROT_EXEC); + setint(dict, "PROT_EXEC", PROT_EXEC); #endif #ifdef PROT_READ - setint(dict, "PROT_READ", PROT_READ); + setint(dict, "PROT_READ", PROT_READ); #endif #ifdef PROT_WRITE - setint(dict, "PROT_WRITE", PROT_WRITE); + setint(dict, "PROT_WRITE", PROT_WRITE); #endif #ifdef MAP_SHARED - setint(dict, "MAP_SHARED", MAP_SHARED); + setint(dict, "MAP_SHARED", MAP_SHARED); #endif #ifdef MAP_PRIVATE - setint(dict, "MAP_PRIVATE", MAP_PRIVATE); + setint(dict, "MAP_PRIVATE", MAP_PRIVATE); #endif #ifdef MAP_DENYWRITE - setint(dict, "MAP_DENYWRITE", MAP_DENYWRITE); + setint(dict, "MAP_DENYWRITE", MAP_DENYWRITE); #endif #ifdef MAP_EXECUTABLE - setint(dict, "MAP_EXECUTABLE", MAP_EXECUTABLE); + setint(dict, "MAP_EXECUTABLE", MAP_EXECUTABLE); #endif #ifdef MAP_ANONYMOUS - setint(dict, "MAP_ANON", MAP_ANONYMOUS); - setint(dict, "MAP_ANONYMOUS", MAP_ANONYMOUS); + setint(dict, "MAP_ANON", MAP_ANONYMOUS); + setint(dict, "MAP_ANONYMOUS", MAP_ANONYMOUS); #endif - setint(dict, "PAGESIZE", (long)my_getpagesize()); + setint(dict, "PAGESIZE", (long)my_getpagesize()); - setint(dict, "ALLOCATIONGRANULARITY", (long)my_getallocationgranularity()); + setint(dict, "ALLOCATIONGRANULARITY", (long)my_getallocationgranularity()); - setint(dict, "ACCESS_READ", ACCESS_READ); - setint(dict, "ACCESS_WRITE", ACCESS_WRITE); - setint(dict, "ACCESS_COPY", ACCESS_COPY); - return module; + setint(dict, "ACCESS_READ", ACCESS_READ); + setint(dict, "ACCESS_WRITE", ACCESS_WRITE); + setint(dict, "ACCESS_COPY", ACCESS_COPY); + return module; } Modified: python/branches/release31-maint/Modules/nismodule.c ============================================================================== --- python/branches/release31-maint/Modules/nismodule.c (original) +++ python/branches/release31-maint/Modules/nismodule.c Sun May 9 18:14:21 2010 @@ -1,11 +1,11 @@ /*********************************************************** Written by: - Fred Gansevles - B&O group, - Faculteit der Informatica, - Universiteit Twente, - Enschede, - the Netherlands. + Fred Gansevles + B&O group, + Faculteit der Informatica, + Universiteit Twente, + Enschede, + the Netherlands. ******************************************************************/ /* NIS module implementation */ @@ -23,7 +23,7 @@ extern int yp_get_default_domain(char **); #endif -PyDoc_STRVAR(get_default_domain__doc__, +PyDoc_STRVAR(get_default_domain__doc__, "get_default_domain() -> str\n\ Corresponds to the C library yp_get_default_domain() call, returning\n\ the default NIS domain.\n"); @@ -49,44 +49,44 @@ static PyObject * nis_error (int err) { - PyErr_SetString(NisError, yperr_string(err)); - return NULL; + PyErr_SetString(NisError, yperr_string(err)); + return NULL; } static struct nis_map { - char *alias; - char *map; - int fix; + char *alias; + char *map; + int fix; } aliases [] = { - {"passwd", "passwd.byname", 0}, - {"group", "group.byname", 0}, - {"networks", "networks.byaddr", 0}, - {"hosts", "hosts.byname", 0}, - {"protocols", "protocols.bynumber", 0}, - {"services", "services.byname", 0}, - {"aliases", "mail.aliases", 1}, /* created with 'makedbm -a' */ - {"ethers", "ethers.byname", 0}, - {0L, 0L, 0} + {"passwd", "passwd.byname", 0}, + {"group", "group.byname", 0}, + {"networks", "networks.byaddr", 0}, + {"hosts", "hosts.byname", 0}, + {"protocols", "protocols.bynumber", 0}, + {"services", "services.byname", 0}, + {"aliases", "mail.aliases", 1}, /* created with 'makedbm -a' */ + {"ethers", "ethers.byname", 0}, + {0L, 0L, 0} }; static char * nis_mapname (char *map, int *pfix) { - int i; + int i; - *pfix = 0; - for (i=0; aliases[i].alias != 0L; i++) { - if (!strcmp (aliases[i].alias, map)) { - *pfix = aliases[i].fix; - return aliases[i].map; - } - if (!strcmp (aliases[i].map, map)) { - *pfix = aliases[i].fix; - return aliases[i].map; - } - } + *pfix = 0; + for (i=0; aliases[i].alias != 0L; i++) { + if (!strcmp (aliases[i].alias, map)) { + *pfix = aliases[i].fix; + return aliases[i].map; + } + if (!strcmp (aliases[i].map, map)) { + *pfix = aliases[i].fix; + return aliases[i].map; + } + } - return map; + return map; } #if defined(__APPLE__) || defined(__OpenBSD__) || defined(__FreeBSD__) @@ -96,168 +96,168 @@ #endif struct ypcallback_data { - PyObject *dict; - int fix; - PyThreadState *state; + PyObject *dict; + int fix; + PyThreadState *state; }; static int nis_foreach (int instatus, char *inkey, int inkeylen, char *inval, int invallen, struct ypcallback_data *indata) { - if (instatus == YP_TRUE) { - PyObject *key; - PyObject *val; - int err; - - PyEval_RestoreThread(indata->state); - if (indata->fix) { - if (inkeylen > 0 && inkey[inkeylen-1] == '\0') - inkeylen--; - if (invallen > 0 && inval[invallen-1] == '\0') - invallen--; - } - key = PyUnicode_FromStringAndSize(inkey, inkeylen); - val = PyUnicode_FromStringAndSize(inval, invallen); - if (key == NULL || val == NULL) { - /* XXX error -- don't know how to handle */ - PyErr_Clear(); - Py_XDECREF(key); - Py_XDECREF(val); - return 1; - } - err = PyDict_SetItem(indata->dict, key, val); - Py_DECREF(key); - Py_DECREF(val); - if (err != 0) - PyErr_Clear(); - indata->state = PyEval_SaveThread(); - if (err != 0) - return 1; - return 0; - } - return 1; + if (instatus == YP_TRUE) { + PyObject *key; + PyObject *val; + int err; + + PyEval_RestoreThread(indata->state); + if (indata->fix) { + if (inkeylen > 0 && inkey[inkeylen-1] == '\0') + inkeylen--; + if (invallen > 0 && inval[invallen-1] == '\0') + invallen--; + } + key = PyUnicode_FromStringAndSize(inkey, inkeylen); + val = PyUnicode_FromStringAndSize(inval, invallen); + if (key == NULL || val == NULL) { + /* XXX error -- don't know how to handle */ + PyErr_Clear(); + Py_XDECREF(key); + Py_XDECREF(val); + return 1; + } + err = PyDict_SetItem(indata->dict, key, val); + Py_DECREF(key); + Py_DECREF(val); + if (err != 0) + PyErr_Clear(); + indata->state = PyEval_SaveThread(); + if (err != 0) + return 1; + return 0; + } + return 1; } static PyObject * nis_get_default_domain (PyObject *self) { - char *domain; - int err; - PyObject *res; + char *domain; + int err; + PyObject *res; - if ((err = yp_get_default_domain(&domain)) != 0) - return nis_error(err); + if ((err = yp_get_default_domain(&domain)) != 0) + return nis_error(err); - res = PyUnicode_FromStringAndSize (domain, strlen(domain)); - return res; + res = PyUnicode_FromStringAndSize (domain, strlen(domain)); + return res; } static PyObject * nis_match (PyObject *self, PyObject *args, PyObject *kwdict) { - char *match; - char *domain = NULL; - int keylen, len; - char *key, *map; - int err; - PyObject *res; - int fix; - static char *kwlist[] = {"key", "map", "domain", NULL}; - - if (!PyArg_ParseTupleAndKeywords(args, kwdict, - "s#s|s:match", kwlist, - &key, &keylen, &map, &domain)) - return NULL; - if (!domain && ((err = yp_get_default_domain(&domain)) != 0)) - return nis_error(err); - map = nis_mapname (map, &fix); - if (fix) - keylen++; - Py_BEGIN_ALLOW_THREADS - err = yp_match (domain, map, key, keylen, &match, &len); - Py_END_ALLOW_THREADS - if (fix) - len--; - if (err != 0) - return nis_error(err); - res = PyUnicode_FromStringAndSize (match, len); - free (match); - return res; + char *match; + char *domain = NULL; + int keylen, len; + char *key, *map; + int err; + PyObject *res; + int fix; + static char *kwlist[] = {"key", "map", "domain", NULL}; + + if (!PyArg_ParseTupleAndKeywords(args, kwdict, + "s#s|s:match", kwlist, + &key, &keylen, &map, &domain)) + return NULL; + if (!domain && ((err = yp_get_default_domain(&domain)) != 0)) + return nis_error(err); + map = nis_mapname (map, &fix); + if (fix) + keylen++; + Py_BEGIN_ALLOW_THREADS + err = yp_match (domain, map, key, keylen, &match, &len); + Py_END_ALLOW_THREADS + if (fix) + len--; + if (err != 0) + return nis_error(err); + res = PyUnicode_FromStringAndSize (match, len); + free (match); + return res; } static PyObject * nis_cat (PyObject *self, PyObject *args, PyObject *kwdict) { - char *domain = NULL; - char *map; - struct ypall_callback cb; - struct ypcallback_data data; - PyObject *dict; - int err; - static char *kwlist[] = {"map", "domain", NULL}; - - if (!PyArg_ParseTupleAndKeywords(args, kwdict, "s|s:cat", - kwlist, &map, &domain)) - return NULL; - if (!domain && ((err = yp_get_default_domain(&domain)) != 0)) - return nis_error(err); - dict = PyDict_New (); - if (dict == NULL) - return NULL; - cb.foreach = (foreachfunc)nis_foreach; - data.dict = dict; - map = nis_mapname (map, &data.fix); - cb.data = (char *)&data; - data.state = PyEval_SaveThread(); - err = yp_all (domain, map, &cb); - PyEval_RestoreThread(data.state); - if (err != 0) { - Py_DECREF(dict); - return nis_error(err); - } - return dict; + char *domain = NULL; + char *map; + struct ypall_callback cb; + struct ypcallback_data data; + PyObject *dict; + int err; + static char *kwlist[] = {"map", "domain", NULL}; + + if (!PyArg_ParseTupleAndKeywords(args, kwdict, "s|s:cat", + kwlist, &map, &domain)) + return NULL; + if (!domain && ((err = yp_get_default_domain(&domain)) != 0)) + return nis_error(err); + dict = PyDict_New (); + if (dict == NULL) + return NULL; + cb.foreach = (foreachfunc)nis_foreach; + data.dict = dict; + map = nis_mapname (map, &data.fix); + cb.data = (char *)&data; + data.state = PyEval_SaveThread(); + err = yp_all (domain, map, &cb); + PyEval_RestoreThread(data.state); + if (err != 0) { + Py_DECREF(dict); + return nis_error(err); + } + return dict; } /* These should be u_long on Sun h/w but not on 64-bit h/w. This is not portable to machines with 16-bit ints and no prototypes */ #ifndef YPPROC_MAPLIST -#define YPPROC_MAPLIST 11 +#define YPPROC_MAPLIST 11 #endif #ifndef YPPROG -#define YPPROG 100004 +#define YPPROG 100004 #endif #ifndef YPVERS -#define YPVERS 2 +#define YPVERS 2 #endif typedef char *domainname; typedef char *mapname; enum nisstat { - NIS_TRUE = 1, - NIS_NOMORE = 2, - NIS_FALSE = 0, - NIS_NOMAP = -1, - NIS_NODOM = -2, - NIS_NOKEY = -3, - NIS_BADOP = -4, - NIS_BADDB = -5, - NIS_YPERR = -6, - NIS_BADARGS = -7, - NIS_VERS = -8 + NIS_TRUE = 1, + NIS_NOMORE = 2, + NIS_FALSE = 0, + NIS_NOMAP = -1, + NIS_NODOM = -2, + NIS_NOKEY = -3, + NIS_BADOP = -4, + NIS_BADDB = -5, + NIS_YPERR = -6, + NIS_BADARGS = -7, + NIS_VERS = -8 }; typedef enum nisstat nisstat; struct nismaplist { - mapname map; - struct nismaplist *next; + mapname map; + struct nismaplist *next; }; typedef struct nismaplist nismaplist; struct nisresp_maplist { - nisstat stat; - nismaplist *maps; + nisstat stat; + nismaplist *maps; }; typedef struct nisresp_maplist nisresp_maplist; @@ -267,45 +267,45 @@ bool_t nis_xdr_domainname(XDR *xdrs, domainname *objp) { - if (!xdr_string(xdrs, objp, YPMAXDOMAIN)) { - return (FALSE); - } - return (TRUE); + if (!xdr_string(xdrs, objp, YPMAXDOMAIN)) { + return (FALSE); + } + return (TRUE); } static bool_t nis_xdr_mapname(XDR *xdrs, mapname *objp) { - if (!xdr_string(xdrs, objp, YPMAXMAP)) { - return (FALSE); - } - return (TRUE); + if (!xdr_string(xdrs, objp, YPMAXMAP)) { + return (FALSE); + } + return (TRUE); } static bool_t nis_xdr_ypmaplist(XDR *xdrs, nismaplist *objp) { - if (!nis_xdr_mapname(xdrs, &objp->map)) { - return (FALSE); - } - if (!xdr_pointer(xdrs, (char **)&objp->next, - sizeof(nismaplist), (xdrproc_t)nis_xdr_ypmaplist)) - { - return (FALSE); - } - return (TRUE); + if (!nis_xdr_mapname(xdrs, &objp->map)) { + return (FALSE); + } + if (!xdr_pointer(xdrs, (char **)&objp->next, + sizeof(nismaplist), (xdrproc_t)nis_xdr_ypmaplist)) + { + return (FALSE); + } + return (TRUE); } static bool_t nis_xdr_ypstat(XDR *xdrs, nisstat *objp) { - if (!xdr_enum(xdrs, (enum_t *)objp)) { - return (FALSE); - } - return (TRUE); + if (!xdr_enum(xdrs, (enum_t *)objp)) { + return (FALSE); + } + return (TRUE); } @@ -313,15 +313,15 @@ bool_t nis_xdr_ypresp_maplist(XDR *xdrs, nisresp_maplist *objp) { - if (!nis_xdr_ypstat(xdrs, &objp->stat)) { - return (FALSE); - } - if (!xdr_pointer(xdrs, (char **)&objp->maps, - sizeof(nismaplist), (xdrproc_t)nis_xdr_ypmaplist)) - { - return (FALSE); - } - return (TRUE); + if (!nis_xdr_ypstat(xdrs, &objp->stat)) { + return (FALSE); + } + if (!xdr_pointer(xdrs, (char **)&objp->maps, + sizeof(nismaplist), (xdrproc_t)nis_xdr_ypmaplist)) + { + return (FALSE); + } + return (TRUE); } @@ -329,132 +329,132 @@ nisresp_maplist * nisproc_maplist_2(domainname *argp, CLIENT *clnt) { - static nisresp_maplist res; + static nisresp_maplist res; - memset(&res, 0, sizeof(res)); - if (clnt_call(clnt, YPPROC_MAPLIST, - (xdrproc_t)nis_xdr_domainname, (caddr_t)argp, - (xdrproc_t)nis_xdr_ypresp_maplist, (caddr_t)&res, - TIMEOUT) != RPC_SUCCESS) - { - return (NULL); - } - return (&res); + memset(&res, 0, sizeof(res)); + if (clnt_call(clnt, YPPROC_MAPLIST, + (xdrproc_t)nis_xdr_domainname, (caddr_t)argp, + (xdrproc_t)nis_xdr_ypresp_maplist, (caddr_t)&res, + TIMEOUT) != RPC_SUCCESS) + { + return (NULL); + } + return (&res); } static nismaplist * nis_maplist (char *dom) { - nisresp_maplist *list; - CLIENT *cl; - char *server = NULL; - int mapi = 0; - - while (!server && aliases[mapi].map != 0L) { - yp_master (dom, aliases[mapi].map, &server); - mapi++; - } - if (!server) { - PyErr_SetString(NisError, "No NIS master found for any map"); - return NULL; - } - cl = clnt_create(server, YPPROG, YPVERS, "tcp"); - if (cl == NULL) { - PyErr_SetString(NisError, clnt_spcreateerror(server)); - goto finally; - } - list = nisproc_maplist_2 (&dom, cl); - clnt_destroy(cl); - if (list == NULL) - goto finally; - if (list->stat != NIS_TRUE) - goto finally; + nisresp_maplist *list; + CLIENT *cl; + char *server = NULL; + int mapi = 0; + + while (!server && aliases[mapi].map != 0L) { + yp_master (dom, aliases[mapi].map, &server); + mapi++; + } + if (!server) { + PyErr_SetString(NisError, "No NIS master found for any map"); + return NULL; + } + cl = clnt_create(server, YPPROG, YPVERS, "tcp"); + if (cl == NULL) { + PyErr_SetString(NisError, clnt_spcreateerror(server)); + goto finally; + } + list = nisproc_maplist_2 (&dom, cl); + clnt_destroy(cl); + if (list == NULL) + goto finally; + if (list->stat != NIS_TRUE) + goto finally; - free(server); - return list->maps; + free(server); + return list->maps; finally: - free(server); - return NULL; + free(server); + return NULL; } static PyObject * nis_maps (PyObject *self, PyObject *args, PyObject *kwdict) { - char *domain = NULL; - nismaplist *maps; - PyObject *list; - int err; - static char *kwlist[] = {"domain", NULL}; - - if (!PyArg_ParseTupleAndKeywords(args, kwdict, - "|s:maps", kwlist, &domain)) - return NULL; - if (!domain && ((err = yp_get_default_domain (&domain)) != 0)) { - nis_error(err); - return NULL; - } - - if ((maps = nis_maplist (domain)) == NULL) - return NULL; - if ((list = PyList_New(0)) == NULL) - return NULL; - for (maps = maps; maps; maps = maps->next) { - PyObject *str = PyUnicode_FromString(maps->map); - if (!str || PyList_Append(list, str) < 0) - { - Py_DECREF(list); - list = NULL; - break; - } - Py_DECREF(str); - } - /* XXX Shouldn't we free the list of maps now? */ - return list; + char *domain = NULL; + nismaplist *maps; + PyObject *list; + int err; + static char *kwlist[] = {"domain", NULL}; + + if (!PyArg_ParseTupleAndKeywords(args, kwdict, + "|s:maps", kwlist, &domain)) + return NULL; + if (!domain && ((err = yp_get_default_domain (&domain)) != 0)) { + nis_error(err); + return NULL; + } + + if ((maps = nis_maplist (domain)) == NULL) + return NULL; + if ((list = PyList_New(0)) == NULL) + return NULL; + for (maps = maps; maps; maps = maps->next) { + PyObject *str = PyUnicode_FromString(maps->map); + if (!str || PyList_Append(list, str) < 0) + { + Py_DECREF(list); + list = NULL; + break; + } + Py_DECREF(str); + } + /* XXX Shouldn't we free the list of maps now? */ + return list; } static PyMethodDef nis_methods[] = { - {"match", (PyCFunction)nis_match, - METH_VARARGS | METH_KEYWORDS, - match__doc__}, - {"cat", (PyCFunction)nis_cat, - METH_VARARGS | METH_KEYWORDS, - cat__doc__}, - {"maps", (PyCFunction)nis_maps, - METH_VARARGS | METH_KEYWORDS, - maps__doc__}, - {"get_default_domain", (PyCFunction)nis_get_default_domain, - METH_NOARGS, - get_default_domain__doc__}, - {NULL, NULL} /* Sentinel */ + {"match", (PyCFunction)nis_match, + METH_VARARGS | METH_KEYWORDS, + match__doc__}, + {"cat", (PyCFunction)nis_cat, + METH_VARARGS | METH_KEYWORDS, + cat__doc__}, + {"maps", (PyCFunction)nis_maps, + METH_VARARGS | METH_KEYWORDS, + maps__doc__}, + {"get_default_domain", (PyCFunction)nis_get_default_domain, + METH_NOARGS, + get_default_domain__doc__}, + {NULL, NULL} /* Sentinel */ }; PyDoc_STRVAR(nis__doc__, "This module contains functions for accessing NIS maps.\n"); static struct PyModuleDef nismodule = { - PyModuleDef_HEAD_INIT, - "nis", - nis__doc__, - -1, - nis_methods, - NULL, - NULL, - NULL, - NULL + PyModuleDef_HEAD_INIT, + "nis", + nis__doc__, + -1, + nis_methods, + NULL, + NULL, + NULL, + NULL }; PyObject* PyInit_nis (void) { - PyObject *m, *d; - m = PyModule_Create(&nismodule); - if (m == NULL) - return NULL; - d = PyModule_GetDict(m); - NisError = PyErr_NewException("nis.error", NULL, NULL); - if (NisError != NULL) - PyDict_SetItemString(d, "error", NisError); - return m; + PyObject *m, *d; + m = PyModule_Create(&nismodule); + if (m == NULL) + return NULL; + d = PyModule_GetDict(m); + NisError = PyErr_NewException("nis.error", NULL, NULL); + if (NisError != NULL) + PyDict_SetItemString(d, "error", NisError); + return m; } Modified: python/branches/release31-maint/Modules/operator.c ============================================================================== --- python/branches/release31-maint/Modules/operator.c (original) +++ python/branches/release31-maint/Modules/operator.c Sun May 9 18:14:21 2010 @@ -112,47 +112,47 @@ static PyObject* op_pow(PyObject *s, PyObject *a) { - PyObject *a1, *a2; - if (PyArg_UnpackTuple(a,"pow", 2, 2, &a1, &a2)) - return PyNumber_Power(a1, a2, Py_None); - return NULL; + PyObject *a1, *a2; + if (PyArg_UnpackTuple(a,"pow", 2, 2, &a1, &a2)) + return PyNumber_Power(a1, a2, Py_None); + return NULL; } static PyObject* op_ipow(PyObject *s, PyObject *a) { - PyObject *a1, *a2; - if (PyArg_UnpackTuple(a,"ipow", 2, 2, &a1, &a2)) - return PyNumber_InPlacePower(a1, a2, Py_None); - return NULL; + PyObject *a1, *a2; + if (PyArg_UnpackTuple(a,"ipow", 2, 2, &a1, &a2)) + return PyNumber_InPlacePower(a1, a2, Py_None); + return NULL; } static PyObject * op_index(PyObject *s, PyObject *a) { - return PyNumber_Index(a); + return PyNumber_Index(a); } static PyObject* is_(PyObject *s, PyObject *a) { - PyObject *a1, *a2, *result = NULL; - if (PyArg_UnpackTuple(a,"is_", 2, 2, &a1, &a2)) { - result = (a1 == a2) ? Py_True : Py_False; - Py_INCREF(result); - } - return result; + PyObject *a1, *a2, *result = NULL; + if (PyArg_UnpackTuple(a,"is_", 2, 2, &a1, &a2)) { + result = (a1 == a2) ? Py_True : Py_False; + Py_INCREF(result); + } + return result; } static PyObject* is_not(PyObject *s, PyObject *a) { - PyObject *a1, *a2, *result = NULL; - if (PyArg_UnpackTuple(a,"is_not", 2, 2, &a1, &a2)) { - result = (a1 != a2) ? Py_True : Py_False; - Py_INCREF(result); - } - return result; + PyObject *a1, *a2, *result = NULL; + if (PyArg_UnpackTuple(a,"is_not", 2, 2, &a1, &a2)) { + result = (a1 != a2) ? Py_True : Py_False; + Py_INCREF(result); + } + return result; } #undef spam1 @@ -161,10 +161,10 @@ #undef spam1o #define spam1(OP,DOC) {#OP, OP, METH_VARARGS, PyDoc_STR(DOC)}, #define spam2(OP,ALTOP,DOC) {#OP, op_##OP, METH_VARARGS, PyDoc_STR(DOC)}, \ - {#ALTOP, op_##OP, METH_VARARGS, PyDoc_STR(DOC)}, + {#ALTOP, op_##OP, METH_VARARGS, PyDoc_STR(DOC)}, #define spam1o(OP,DOC) {#OP, OP, METH_O, PyDoc_STR(DOC)}, #define spam2o(OP,ALTOP,DOC) {#OP, op_##OP, METH_O, PyDoc_STR(DOC)}, \ - {#ALTOP, op_##OP, METH_O, PyDoc_STR(DOC)}, + {#ALTOP, op_##OP, METH_O, PyDoc_STR(DOC)}, static struct PyMethodDef operator_methods[] = { @@ -227,16 +227,16 @@ spam2(gt,__gt__, "gt(a, b) -- Same as a>b.") spam2(ge,__ge__, "ge(a, b) -- Same as a>=b.") - {NULL, NULL} /* sentinel */ + {NULL, NULL} /* sentinel */ }; /* itemgetter object **********************************************************/ typedef struct { - PyObject_HEAD - Py_ssize_t nitems; - PyObject *item; + PyObject_HEAD + Py_ssize_t nitems; + PyObject *item; } itemgetterobject; static PyTypeObject itemgetter_type; @@ -244,77 +244,77 @@ static PyObject * itemgetter_new(PyTypeObject *type, PyObject *args, PyObject *kwds) { - itemgetterobject *ig; - PyObject *item; - Py_ssize_t nitems; - - if (!_PyArg_NoKeywords("itemgetter()", kwds)) - return NULL; - - nitems = PyTuple_GET_SIZE(args); - if (nitems <= 1) { - if (!PyArg_UnpackTuple(args, "itemgetter", 1, 1, &item)) - return NULL; - } else - item = args; - - /* create itemgetterobject structure */ - ig = PyObject_GC_New(itemgetterobject, &itemgetter_type); - if (ig == NULL) - return NULL; - - Py_INCREF(item); - ig->item = item; - ig->nitems = nitems; + itemgetterobject *ig; + PyObject *item; + Py_ssize_t nitems; + + if (!_PyArg_NoKeywords("itemgetter()", kwds)) + return NULL; + + nitems = PyTuple_GET_SIZE(args); + if (nitems <= 1) { + if (!PyArg_UnpackTuple(args, "itemgetter", 1, 1, &item)) + return NULL; + } else + item = args; + + /* create itemgetterobject structure */ + ig = PyObject_GC_New(itemgetterobject, &itemgetter_type); + if (ig == NULL) + return NULL; + + Py_INCREF(item); + ig->item = item; + ig->nitems = nitems; - PyObject_GC_Track(ig); - return (PyObject *)ig; + PyObject_GC_Track(ig); + return (PyObject *)ig; } static void itemgetter_dealloc(itemgetterobject *ig) { - PyObject_GC_UnTrack(ig); - Py_XDECREF(ig->item); - PyObject_GC_Del(ig); + PyObject_GC_UnTrack(ig); + Py_XDECREF(ig->item); + PyObject_GC_Del(ig); } static int itemgetter_traverse(itemgetterobject *ig, visitproc visit, void *arg) { - Py_VISIT(ig->item); - return 0; + Py_VISIT(ig->item); + return 0; } static PyObject * itemgetter_call(itemgetterobject *ig, PyObject *args, PyObject *kw) { - PyObject *obj, *result; - Py_ssize_t i, nitems=ig->nitems; + PyObject *obj, *result; + Py_ssize_t i, nitems=ig->nitems; - if (!PyArg_UnpackTuple(args, "itemgetter", 1, 1, &obj)) - return NULL; - if (nitems == 1) - return PyObject_GetItem(obj, ig->item); - - assert(PyTuple_Check(ig->item)); - assert(PyTuple_GET_SIZE(ig->item) == nitems); - - result = PyTuple_New(nitems); - if (result == NULL) - return NULL; - - for (i=0 ; i < nitems ; i++) { - PyObject *item, *val; - item = PyTuple_GET_ITEM(ig->item, i); - val = PyObject_GetItem(obj, item); - if (val == NULL) { - Py_DECREF(result); - return NULL; - } - PyTuple_SET_ITEM(result, i, val); - } - return result; + if (!PyArg_UnpackTuple(args, "itemgetter", 1, 1, &obj)) + return NULL; + if (nitems == 1) + return PyObject_GetItem(obj, ig->item); + + assert(PyTuple_Check(ig->item)); + assert(PyTuple_GET_SIZE(ig->item) == nitems); + + result = PyTuple_New(nitems); + if (result == NULL) + return NULL; + + for (i=0 ; i < nitems ; i++) { + PyObject *item, *val; + item = PyTuple_GET_ITEM(ig->item, i); + val = PyObject_GetItem(obj, item); + if (val == NULL) { + Py_DECREF(result); + return NULL; + } + PyTuple_SET_ITEM(result, i, val); + } + return result; } PyDoc_STRVAR(itemgetter_doc, @@ -325,55 +325,55 @@ After, g=itemgetter(2,5,3), the call g(r) returns (r[2], r[5], r[3])"); static PyTypeObject itemgetter_type = { - PyVarObject_HEAD_INIT(NULL, 0) - "operator.itemgetter", /* tp_name */ - sizeof(itemgetterobject), /* tp_basicsize */ - 0, /* tp_itemsize */ - /* methods */ - (destructor)itemgetter_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 */ - (ternaryfunc)itemgetter_call, /* 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 */ - itemgetter_doc, /* tp_doc */ - (traverseproc)itemgetter_traverse, /* tp_traverse */ - 0, /* tp_clear */ - 0, /* tp_richcompare */ - 0, /* tp_weaklistoffset */ - 0, /* tp_iter */ - 0, /* tp_iternext */ - 0, /* tp_methods */ - 0, /* tp_members */ - 0, /* tp_getset */ - 0, /* tp_base */ - 0, /* tp_dict */ - 0, /* tp_descr_get */ - 0, /* tp_descr_set */ - 0, /* tp_dictoffset */ - 0, /* tp_init */ - 0, /* tp_alloc */ - itemgetter_new, /* tp_new */ - 0, /* tp_free */ + PyVarObject_HEAD_INIT(NULL, 0) + "operator.itemgetter", /* tp_name */ + sizeof(itemgetterobject), /* tp_basicsize */ + 0, /* tp_itemsize */ + /* methods */ + (destructor)itemgetter_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 */ + (ternaryfunc)itemgetter_call, /* 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 */ + itemgetter_doc, /* tp_doc */ + (traverseproc)itemgetter_traverse, /* tp_traverse */ + 0, /* tp_clear */ + 0, /* tp_richcompare */ + 0, /* tp_weaklistoffset */ + 0, /* tp_iter */ + 0, /* tp_iternext */ + 0, /* tp_methods */ + 0, /* tp_members */ + 0, /* tp_getset */ + 0, /* tp_base */ + 0, /* tp_dict */ + 0, /* tp_descr_get */ + 0, /* tp_descr_set */ + 0, /* tp_dictoffset */ + 0, /* tp_init */ + 0, /* tp_alloc */ + itemgetter_new, /* tp_new */ + 0, /* tp_free */ }; /* attrgetter object **********************************************************/ typedef struct { - PyObject_HEAD - Py_ssize_t nattrs; - PyObject *attr; + PyObject_HEAD + Py_ssize_t nattrs; + PyObject *attr; } attrgetterobject; static PyTypeObject attrgetter_type; @@ -381,112 +381,112 @@ static PyObject * attrgetter_new(PyTypeObject *type, PyObject *args, PyObject *kwds) { - attrgetterobject *ag; - PyObject *attr; - Py_ssize_t nattrs; - - if (!_PyArg_NoKeywords("attrgetter()", kwds)) - return NULL; - - nattrs = PyTuple_GET_SIZE(args); - if (nattrs <= 1) { - if (!PyArg_UnpackTuple(args, "attrgetter", 1, 1, &attr)) - return NULL; - } else - attr = args; - - /* create attrgetterobject structure */ - ag = PyObject_GC_New(attrgetterobject, &attrgetter_type); - if (ag == NULL) - return NULL; - - Py_INCREF(attr); - ag->attr = attr; - ag->nattrs = nattrs; + attrgetterobject *ag; + PyObject *attr; + Py_ssize_t nattrs; + + if (!_PyArg_NoKeywords("attrgetter()", kwds)) + return NULL; + + nattrs = PyTuple_GET_SIZE(args); + if (nattrs <= 1) { + if (!PyArg_UnpackTuple(args, "attrgetter", 1, 1, &attr)) + return NULL; + } else + attr = args; + + /* create attrgetterobject structure */ + ag = PyObject_GC_New(attrgetterobject, &attrgetter_type); + if (ag == NULL) + return NULL; + + Py_INCREF(attr); + ag->attr = attr; + ag->nattrs = nattrs; - PyObject_GC_Track(ag); - return (PyObject *)ag; + PyObject_GC_Track(ag); + return (PyObject *)ag; } static void attrgetter_dealloc(attrgetterobject *ag) { - PyObject_GC_UnTrack(ag); - Py_XDECREF(ag->attr); - PyObject_GC_Del(ag); + PyObject_GC_UnTrack(ag); + Py_XDECREF(ag->attr); + PyObject_GC_Del(ag); } static int attrgetter_traverse(attrgetterobject *ag, visitproc visit, void *arg) { - Py_VISIT(ag->attr); - return 0; + Py_VISIT(ag->attr); + return 0; } static PyObject * dotted_getattr(PyObject *obj, PyObject *attr) { - char *s, *p; + char *s, *p; - if (!PyUnicode_Check(attr)) { - PyErr_SetString(PyExc_TypeError, - "attribute name must be a string"); - return NULL; - } - - s = _PyUnicode_AsString(attr); - Py_INCREF(obj); - for (;;) { - PyObject *newobj, *str; - p = strchr(s, '.'); - str = p ? PyUnicode_FromStringAndSize(s, (p-s)) : - PyUnicode_FromString(s); - if (str == NULL) { - Py_DECREF(obj); - return NULL; - } - newobj = PyObject_GetAttr(obj, str); - Py_DECREF(str); - Py_DECREF(obj); - if (newobj == NULL) - return NULL; - obj = newobj; - if (p == NULL) break; - s = p+1; - } + if (!PyUnicode_Check(attr)) { + PyErr_SetString(PyExc_TypeError, + "attribute name must be a string"); + return NULL; + } + + s = _PyUnicode_AsString(attr); + Py_INCREF(obj); + for (;;) { + PyObject *newobj, *str; + p = strchr(s, '.'); + str = p ? PyUnicode_FromStringAndSize(s, (p-s)) : + PyUnicode_FromString(s); + if (str == NULL) { + Py_DECREF(obj); + return NULL; + } + newobj = PyObject_GetAttr(obj, str); + Py_DECREF(str); + Py_DECREF(obj); + if (newobj == NULL) + return NULL; + obj = newobj; + if (p == NULL) break; + s = p+1; + } - return obj; + return obj; } static PyObject * attrgetter_call(attrgetterobject *ag, PyObject *args, PyObject *kw) { - PyObject *obj, *result; - Py_ssize_t i, nattrs=ag->nattrs; + PyObject *obj, *result; + Py_ssize_t i, nattrs=ag->nattrs; - if (!PyArg_UnpackTuple(args, "attrgetter", 1, 1, &obj)) - return NULL; - if (ag->nattrs == 1) - return dotted_getattr(obj, ag->attr); - - assert(PyTuple_Check(ag->attr)); - assert(PyTuple_GET_SIZE(ag->attr) == nattrs); - - result = PyTuple_New(nattrs); - if (result == NULL) - return NULL; - - for (i=0 ; i < nattrs ; i++) { - PyObject *attr, *val; - attr = PyTuple_GET_ITEM(ag->attr, i); - val = dotted_getattr(obj, attr); - if (val == NULL) { - Py_DECREF(result); - return NULL; - } - PyTuple_SET_ITEM(result, i, val); - } - return result; + if (!PyArg_UnpackTuple(args, "attrgetter", 1, 1, &obj)) + return NULL; + if (ag->nattrs == 1) + return dotted_getattr(obj, ag->attr); + + assert(PyTuple_Check(ag->attr)); + assert(PyTuple_GET_SIZE(ag->attr) == nattrs); + + result = PyTuple_New(nattrs); + if (result == NULL) + return NULL; + + for (i=0 ; i < nattrs ; i++) { + PyObject *attr, *val; + attr = PyTuple_GET_ITEM(ag->attr, i); + val = dotted_getattr(obj, attr); + if (val == NULL) { + Py_DECREF(result); + return NULL; + } + PyTuple_SET_ITEM(result, i, val); + } + return result; } PyDoc_STRVAR(attrgetter_doc, @@ -499,56 +499,56 @@ (r.name.first, r.name.last)."); static PyTypeObject attrgetter_type = { - PyVarObject_HEAD_INIT(NULL, 0) - "operator.attrgetter", /* tp_name */ - sizeof(attrgetterobject), /* tp_basicsize */ - 0, /* tp_itemsize */ - /* methods */ - (destructor)attrgetter_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 */ - (ternaryfunc)attrgetter_call, /* 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 */ - attrgetter_doc, /* tp_doc */ - (traverseproc)attrgetter_traverse, /* tp_traverse */ - 0, /* tp_clear */ - 0, /* tp_richcompare */ - 0, /* tp_weaklistoffset */ - 0, /* tp_iter */ - 0, /* tp_iternext */ - 0, /* tp_methods */ - 0, /* tp_members */ - 0, /* tp_getset */ - 0, /* tp_base */ - 0, /* tp_dict */ - 0, /* tp_descr_get */ - 0, /* tp_descr_set */ - 0, /* tp_dictoffset */ - 0, /* tp_init */ - 0, /* tp_alloc */ - attrgetter_new, /* tp_new */ - 0, /* tp_free */ + PyVarObject_HEAD_INIT(NULL, 0) + "operator.attrgetter", /* tp_name */ + sizeof(attrgetterobject), /* tp_basicsize */ + 0, /* tp_itemsize */ + /* methods */ + (destructor)attrgetter_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 */ + (ternaryfunc)attrgetter_call, /* 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 */ + attrgetter_doc, /* tp_doc */ + (traverseproc)attrgetter_traverse, /* tp_traverse */ + 0, /* tp_clear */ + 0, /* tp_richcompare */ + 0, /* tp_weaklistoffset */ + 0, /* tp_iter */ + 0, /* tp_iternext */ + 0, /* tp_methods */ + 0, /* tp_members */ + 0, /* tp_getset */ + 0, /* tp_base */ + 0, /* tp_dict */ + 0, /* tp_descr_get */ + 0, /* tp_descr_set */ + 0, /* tp_dictoffset */ + 0, /* tp_init */ + 0, /* tp_alloc */ + attrgetter_new, /* tp_new */ + 0, /* tp_free */ }; /* methodcaller object **********************************************************/ typedef struct { - PyObject_HEAD - PyObject *name; - PyObject *args; - PyObject *kwds; + PyObject_HEAD + PyObject *name; + PyObject *args; + PyObject *kwds; } methodcallerobject; static PyTypeObject methodcaller_type; @@ -556,69 +556,69 @@ static PyObject * methodcaller_new(PyTypeObject *type, PyObject *args, PyObject *kwds) { - methodcallerobject *mc; - PyObject *name, *newargs; + methodcallerobject *mc; + PyObject *name, *newargs; - if (PyTuple_GET_SIZE(args) < 1) { - PyErr_SetString(PyExc_TypeError, "methodcaller needs at least " - "one argument, the method name"); - return NULL; - } - - /* create methodcallerobject structure */ - mc = PyObject_GC_New(methodcallerobject, &methodcaller_type); - if (mc == NULL) - return NULL; - - newargs = PyTuple_GetSlice(args, 1, PyTuple_GET_SIZE(args)); - if (newargs == NULL) { - Py_DECREF(mc); - return NULL; - } - mc->args = newargs; - - name = PyTuple_GET_ITEM(args, 0); - Py_INCREF(name); - mc->name = name; + if (PyTuple_GET_SIZE(args) < 1) { + PyErr_SetString(PyExc_TypeError, "methodcaller needs at least " + "one argument, the method name"); + return NULL; + } + + /* create methodcallerobject structure */ + mc = PyObject_GC_New(methodcallerobject, &methodcaller_type); + if (mc == NULL) + return NULL; + + newargs = PyTuple_GetSlice(args, 1, PyTuple_GET_SIZE(args)); + if (newargs == NULL) { + Py_DECREF(mc); + return NULL; + } + mc->args = newargs; + + name = PyTuple_GET_ITEM(args, 0); + Py_INCREF(name); + mc->name = name; - Py_XINCREF(kwds); - mc->kwds = kwds; + Py_XINCREF(kwds); + mc->kwds = kwds; - PyObject_GC_Track(mc); - return (PyObject *)mc; + PyObject_GC_Track(mc); + return (PyObject *)mc; } static void methodcaller_dealloc(methodcallerobject *mc) { - PyObject_GC_UnTrack(mc); - Py_XDECREF(mc->name); - Py_XDECREF(mc->args); - Py_XDECREF(mc->kwds); - PyObject_GC_Del(mc); + PyObject_GC_UnTrack(mc); + Py_XDECREF(mc->name); + Py_XDECREF(mc->args); + Py_XDECREF(mc->kwds); + PyObject_GC_Del(mc); } static int methodcaller_traverse(methodcallerobject *mc, visitproc visit, void *arg) { - Py_VISIT(mc->args); - Py_VISIT(mc->kwds); - return 0; + Py_VISIT(mc->args); + Py_VISIT(mc->kwds); + return 0; } static PyObject * methodcaller_call(methodcallerobject *mc, PyObject *args, PyObject *kw) { - PyObject *method, *obj, *result; + PyObject *method, *obj, *result; - if (!PyArg_UnpackTuple(args, "methodcaller", 1, 1, &obj)) - return NULL; - method = PyObject_GetAttr(obj, mc->name); - if (method == NULL) - return NULL; - result = PyObject_Call(method, mc->args, mc->kwds); - Py_DECREF(method); - return result; + if (!PyArg_UnpackTuple(args, "methodcaller", 1, 1, &obj)) + return NULL; + method = PyObject_GetAttr(obj, mc->name); + if (method == NULL) + return NULL; + result = PyObject_Call(method, mc->args, mc->kwds); + Py_DECREF(method); + return result; } PyDoc_STRVAR(methodcaller_doc, @@ -630,46 +630,46 @@ r.name('date', foo=1)."); static PyTypeObject methodcaller_type = { - PyVarObject_HEAD_INIT(NULL, 0) - "operator.methodcaller", /* tp_name */ - sizeof(methodcallerobject), /* tp_basicsize */ - 0, /* tp_itemsize */ - /* methods */ - (destructor)methodcaller_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 */ - (ternaryfunc)methodcaller_call, /* 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 */ - methodcaller_doc, /* tp_doc */ - (traverseproc)methodcaller_traverse, /* tp_traverse */ - 0, /* tp_clear */ - 0, /* tp_richcompare */ - 0, /* tp_weaklistoffset */ - 0, /* tp_iter */ - 0, /* tp_iternext */ - 0, /* tp_methods */ - 0, /* tp_members */ - 0, /* tp_getset */ - 0, /* tp_base */ - 0, /* tp_dict */ - 0, /* tp_descr_get */ - 0, /* tp_descr_set */ - 0, /* tp_dictoffset */ - 0, /* tp_init */ - 0, /* tp_alloc */ - methodcaller_new, /* tp_new */ - 0, /* tp_free */ + PyVarObject_HEAD_INIT(NULL, 0) + "operator.methodcaller", /* tp_name */ + sizeof(methodcallerobject), /* tp_basicsize */ + 0, /* tp_itemsize */ + /* methods */ + (destructor)methodcaller_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 */ + (ternaryfunc)methodcaller_call, /* 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 */ + methodcaller_doc, /* tp_doc */ + (traverseproc)methodcaller_traverse, /* tp_traverse */ + 0, /* tp_clear */ + 0, /* tp_richcompare */ + 0, /* tp_weaklistoffset */ + 0, /* tp_iter */ + 0, /* tp_iternext */ + 0, /* tp_methods */ + 0, /* tp_members */ + 0, /* tp_getset */ + 0, /* tp_base */ + 0, /* tp_dict */ + 0, /* tp_descr_get */ + 0, /* tp_descr_set */ + 0, /* tp_dictoffset */ + 0, /* tp_init */ + 0, /* tp_alloc */ + methodcaller_new, /* tp_new */ + 0, /* tp_free */ }; @@ -677,40 +677,40 @@ static struct PyModuleDef operatormodule = { - PyModuleDef_HEAD_INIT, - "operator", - operator_doc, - -1, - operator_methods, - NULL, - NULL, - NULL, - NULL + PyModuleDef_HEAD_INIT, + "operator", + operator_doc, + -1, + operator_methods, + NULL, + NULL, + NULL, + NULL }; PyMODINIT_FUNC PyInit_operator(void) { - PyObject *m; - - /* Create the module and add the functions */ - m = PyModule_Create(&operatormodule); - if (m == NULL) - return NULL; - - if (PyType_Ready(&itemgetter_type) < 0) - return NULL; - Py_INCREF(&itemgetter_type); - PyModule_AddObject(m, "itemgetter", (PyObject *)&itemgetter_type); - - if (PyType_Ready(&attrgetter_type) < 0) - return NULL; - Py_INCREF(&attrgetter_type); - PyModule_AddObject(m, "attrgetter", (PyObject *)&attrgetter_type); - - if (PyType_Ready(&methodcaller_type) < 0) - return NULL; - Py_INCREF(&methodcaller_type); - PyModule_AddObject(m, "methodcaller", (PyObject *)&methodcaller_type); - return m; + PyObject *m; + + /* Create the module and add the functions */ + m = PyModule_Create(&operatormodule); + if (m == NULL) + return NULL; + + if (PyType_Ready(&itemgetter_type) < 0) + return NULL; + Py_INCREF(&itemgetter_type); + PyModule_AddObject(m, "itemgetter", (PyObject *)&itemgetter_type); + + if (PyType_Ready(&attrgetter_type) < 0) + return NULL; + Py_INCREF(&attrgetter_type); + PyModule_AddObject(m, "attrgetter", (PyObject *)&attrgetter_type); + + if (PyType_Ready(&methodcaller_type) < 0) + return NULL; + Py_INCREF(&methodcaller_type); + PyModule_AddObject(m, "methodcaller", (PyObject *)&methodcaller_type); + return m; } Modified: python/branches/release31-maint/Modules/ossaudiodev.c ============================================================================== --- python/branches/release31-maint/Modules/ossaudiodev.c (original) +++ python/branches/release31-maint/Modules/ossaudiodev.c Sun May 9 18:14:21 2010 @@ -809,8 +809,8 @@ PyObject * rval = NULL; if (PyUnicode_Check(nameobj)) - name = _PyUnicode_AsString(nameobj); - + name = _PyUnicode_AsString(nameobj); + if (strcmp(name, "closed") == 0) { rval = (self->fd == -1) ? Py_True : Py_False; Py_INCREF(rval); @@ -975,15 +975,15 @@ static struct PyModuleDef ossaudiodevmodule = { - PyModuleDef_HEAD_INIT, - "ossaudiodev", - NULL, - -1, - ossaudiodev_methods, - NULL, - NULL, - NULL, - NULL + PyModuleDef_HEAD_INIT, + "ossaudiodev", + NULL, + -1, + ossaudiodev_methods, + NULL, + NULL, + NULL, + NULL }; PyMODINIT_FUNC @@ -999,10 +999,10 @@ m = PyModule_Create(&ossaudiodevmodule); if (m == NULL) - return NULL; + return NULL; OSSAudioError = PyErr_NewException("ossaudiodev.OSSAudioError", - NULL, NULL); + NULL, NULL); if (OSSAudioError) { /* Each call to PyModule_AddObject decrefs it; compensate: */ Py_INCREF(OSSAudioError); Modified: python/branches/release31-maint/Modules/parsermodule.c ============================================================================== --- python/branches/release31-maint/Modules/parsermodule.c (original) +++ python/branches/release31-maint/Modules/parsermodule.c Sun May 9 18:14:21 2010 @@ -578,8 +578,8 @@ ? eval_input : file_input, &err, &flags); - if (n) { - res = parser_newstobject(n, type); + if (n) { + res = parser_newstobject(n, type); if (res) ((PyST_Object *)res)->st_flags.cf_flags = flags & PyCF_MASK; } @@ -784,7 +784,7 @@ PyErr_Format(parser_error, "third item in terminal node must be an" " integer, found %s", - Py_TYPE(temp)->tp_name); + Py_TYPE(temp)->tp_name); Py_DECREF(o); Py_DECREF(temp); Py_DECREF(elem); @@ -1051,7 +1051,7 @@ { int nch = NCH(tree); int res = (validate_ntype(tree, classdef) && - ((nch == 4) || (nch == 6) || (nch == 7))); + ((nch == 4) || (nch == 6) || (nch == 7))); if (res) { res = (validate_name(CHILD(tree, 0), "class") @@ -1064,15 +1064,15 @@ } if (res) { - if (nch == 7) { - res = ((validate_lparen(CHILD(tree, 2)) && - validate_arglist(CHILD(tree, 3)) && - validate_rparen(CHILD(tree, 4)))); - } - else if (nch == 6) { - res = (validate_lparen(CHILD(tree,2)) && - validate_rparen(CHILD(tree,3))); - } + if (nch == 7) { + res = ((validate_lparen(CHILD(tree, 2)) && + validate_arglist(CHILD(tree, 3)) && + validate_rparen(CHILD(tree, 4)))); + } + else if (nch == 6) { + res = (validate_lparen(CHILD(tree,2)) && + validate_rparen(CHILD(tree,3))); + } } return (res); } @@ -1245,10 +1245,10 @@ else { /* skip over vfpdef (',' vfpdef ['=' test])* */ i = start + 1; - if (TYPE(CHILD(tree, i)) == vfpdef || - TYPE(CHILD(tree, i)) == tfpdef) { /* skip over vfpdef or tfpdef */ - i += 1; - } + if (TYPE(CHILD(tree, i)) == vfpdef || + TYPE(CHILD(tree, i)) == tfpdef) { /* skip over vfpdef or tfpdef */ + i += 1; + } while (res && i+1 < nch) { /* validate (',' vfpdef ['=' test])* */ res = validate_comma(CHILD(tree, i)); if (TYPE(CHILD(tree, i+1)) == DOUBLESTAR) @@ -1518,10 +1518,10 @@ static int validate_yield_or_testlist(node *tree) { - if (TYPE(tree) == yield_expr) - return validate_yield_expr(tree); - else - return validate_testlist(tree); + if (TYPE(tree) == yield_expr) + return validate_yield_expr(tree); + else + return validate_testlist(tree); } static int @@ -1536,7 +1536,7 @@ if (res && nch == 3 && TYPE(CHILD(tree, 1)) == augassign) { res = validate_numnodes(CHILD(tree, 1), 1, "augassign") - && validate_yield_or_testlist(CHILD(tree, 2)); + && validate_yield_or_testlist(CHILD(tree, 2)); if (res) { char *s = STR(CHILD(CHILD(tree, 1), 0)); @@ -1714,14 +1714,14 @@ static int validate_dotted_as_names(node *tree) { - int nch = NCH(tree); - int res = is_odd(nch) && validate_dotted_as_name(CHILD(tree, 0)); - int i; - - for (i = 1; res && (i < nch); i += 2) - res = (validate_comma(CHILD(tree, i)) - && validate_dotted_as_name(CHILD(tree, i + 1))); - return (res); + int nch = NCH(tree); + int res = is_odd(nch) && validate_dotted_as_name(CHILD(tree, 0)); + int i; + + for (i = 1; res && (i < nch); i += 2) + res = (validate_comma(CHILD(tree, i)) + && validate_dotted_as_name(CHILD(tree, i + 1))); + return (res); } @@ -1734,8 +1734,8 @@ int i; for (i = 1; res && (i + 1 < nch); i += 2) - res = (validate_comma(CHILD(tree, i)) - && validate_import_as_name(CHILD(tree, i + 1))); + res = (validate_comma(CHILD(tree, i)) + && validate_import_as_name(CHILD(tree, i + 1))); return (res); } @@ -1744,10 +1744,10 @@ static int validate_import_name(node *tree) { - return (validate_ntype(tree, import_name) - && validate_numnodes(tree, 2, "import_name") - && validate_name(CHILD(tree, 0), "import") - && validate_dotted_as_names(CHILD(tree, 1))); + return (validate_ntype(tree, import_name) + && validate_numnodes(tree, 2, "import_name") + && validate_name(CHILD(tree, 0), "import") + && validate_dotted_as_names(CHILD(tree, 1))); } /* Helper function to count the number of leading dots in @@ -1758,8 +1758,8 @@ { int i; for (i = 1; i < NCH(tree); i++) - if (TYPE(CHILD(tree, i)) != DOT) - break; + if (TYPE(CHILD(tree, i)) != DOT) + break; return i-1; } @@ -1769,24 +1769,24 @@ static int validate_import_from(node *tree) { - int nch = NCH(tree); - int ndots = count_from_dots(tree); - int havename = (TYPE(CHILD(tree, ndots + 1)) == dotted_name); - int offset = ndots + havename; - int res = validate_ntype(tree, import_from) - && (nch >= 4 + ndots) - && validate_name(CHILD(tree, 0), "from") - && (!havename || validate_dotted_name(CHILD(tree, ndots + 1))) - && validate_name(CHILD(tree, offset + 1), "import"); - - if (res && TYPE(CHILD(tree, offset + 2)) == LPAR) - res = ((nch == offset + 5) - && validate_lparen(CHILD(tree, offset + 2)) - && validate_import_as_names(CHILD(tree, offset + 3)) - && validate_rparen(CHILD(tree, offset + 4))); - else if (res && TYPE(CHILD(tree, offset + 2)) != STAR) - res = validate_import_as_names(CHILD(tree, offset + 2)); - return (res); + int nch = NCH(tree); + int ndots = count_from_dots(tree); + int havename = (TYPE(CHILD(tree, ndots + 1)) == dotted_name); + int offset = ndots + havename; + int res = validate_ntype(tree, import_from) + && (nch >= 4 + ndots) + && validate_name(CHILD(tree, 0), "from") + && (!havename || validate_dotted_name(CHILD(tree, ndots + 1))) + && validate_name(CHILD(tree, offset + 1), "import"); + + if (res && TYPE(CHILD(tree, offset + 2)) == LPAR) + res = ((nch == offset + 5) + && validate_lparen(CHILD(tree, offset + 2)) + && validate_import_as_names(CHILD(tree, offset + 3)) + && validate_rparen(CHILD(tree, offset + 4))); + else if (res && TYPE(CHILD(tree, offset + 2)) != STAR) + res = validate_import_as_names(CHILD(tree, offset + 2)); + return (res); } @@ -1798,9 +1798,9 @@ int res = validate_numnodes(tree, 1, "import_stmt"); if (res) { - int ntype = TYPE(CHILD(tree, 0)); + int ntype = TYPE(CHILD(tree, 0)); - if (ntype == import_name || ntype == import_from) + if (ntype == import_name || ntype == import_from) res = validate_node(CHILD(tree, 0)); else { res = 0; @@ -2321,11 +2321,11 @@ && (validate_rparen(CHILD(tree, nch - 1)))); if (res && (nch == 3)) { - if (TYPE(CHILD(tree, 1))==yield_expr) - res = validate_yield_expr(CHILD(tree, 1)); - else - res = validate_testlist_comp(CHILD(tree, 1)); - } + if (TYPE(CHILD(tree, 1))==yield_expr) + res = validate_yield_expr(CHILD(tree, 1)); + else + res = validate_testlist_comp(CHILD(tree, 1)); + } break; case LSQB: if (nch == 2) @@ -2353,11 +2353,11 @@ for (pos = 1; res && (pos < nch); ++pos) res = validate_ntype(CHILD(tree, pos), STRING); break; - case DOT: - res = (nch == 3 && - validate_ntype(CHILD(tree, 1), DOT) && - validate_ntype(CHILD(tree, 2), DOT)); - break; + case DOT: + res = (nch == 3 && + validate_ntype(CHILD(tree, 1), DOT) && + validate_ntype(CHILD(tree, 2), DOT)); + break; default: res = 0; break; @@ -2414,17 +2414,17 @@ int ok; int nch = NCH(tree); ok = (validate_ntype(tree, decorator) && - (nch == 3 || nch == 5 || nch == 6) && - validate_at(CHILD(tree, 0)) && - validate_dotted_name(CHILD(tree, 1)) && - validate_newline(RCHILD(tree, -1))); + (nch == 3 || nch == 5 || nch == 6) && + validate_at(CHILD(tree, 0)) && + validate_dotted_name(CHILD(tree, 1)) && + validate_newline(RCHILD(tree, -1))); if (ok && nch != 3) { - ok = (validate_lparen(CHILD(tree, 2)) && - validate_rparen(RCHILD(tree, -2))); + ok = (validate_lparen(CHILD(tree, 2)) && + validate_rparen(RCHILD(tree, -2))); - if (ok && nch == 6) - ok = validate_arglist(CHILD(tree, 3)); + if (ok && nch == 6) + ok = validate_arglist(CHILD(tree, 3)); } return ok; @@ -2441,7 +2441,7 @@ ok = validate_ntype(tree, decorators) && nch >= 1; for (i = 0; ok && i < nch; ++i) - ok = validate_decorator(CHILD(tree, i)); + ok = validate_decorator(CHILD(tree, i)); return ok; } @@ -2456,7 +2456,7 @@ int ok = (validate_ntype(tree, with_item) && (nch == 1 || nch == 3) && validate_test(CHILD(tree, 0))); - if (ok && nch == 3) + if (ok && nch == 3) ok = (validate_name(CHILD(tree, 1), "as") && validate_expr(CHILD(tree, 2))); return ok; @@ -2491,12 +2491,12 @@ { int nch = NCH(tree); int ok = (validate_ntype(tree, funcdef) - && (nch == 5) - && validate_name(RCHILD(tree, -5), "def") - && validate_ntype(RCHILD(tree, -4), NAME) - && validate_colon(RCHILD(tree, -2)) - && validate_parameters(RCHILD(tree, -3)) - && validate_suite(RCHILD(tree, -1))); + && (nch == 5) + && validate_name(RCHILD(tree, -5), "def") + && validate_ntype(RCHILD(tree, -4), NAME) + && validate_colon(RCHILD(tree, -2)) + && validate_parameters(RCHILD(tree, -3)) + && validate_suite(RCHILD(tree, -1))); return ok; } @@ -2509,11 +2509,11 @@ { int nch = NCH(tree); int ok = (validate_ntype(tree, decorated) - && (nch == 2) - && validate_decorators(RCHILD(tree, -2)) - && (validate_funcdef(RCHILD(tree, -1)) - || validate_class(RCHILD(tree, -1))) - ); + && (nch == 2) + && validate_decorators(RCHILD(tree, -2)) + && (validate_funcdef(RCHILD(tree, -1)) + || validate_class(RCHILD(tree, -1))) + ); return ok; } @@ -2863,9 +2863,9 @@ case classdef: res = validate_class(tree); break; - case decorated: - res = validate_decorated(tree); - break; + case decorated: + res = validate_decorated(tree); + break; /* * "Trivial" parse tree nodes. * (Why did I call these trivial?) @@ -2934,12 +2934,12 @@ case import_stmt: res = validate_import_stmt(tree); break; - case import_name: - res = validate_import_name(tree); - break; - case import_from: - res = validate_import_from(tree); - break; + case import_name: + res = validate_import_name(tree); + break; + case import_from: + res = validate_import_from(tree); + break; case global_stmt: res = validate_global_stmt(tree); break; @@ -3154,15 +3154,15 @@ static struct PyModuleDef parsermodule = { - PyModuleDef_HEAD_INIT, - "parser", - NULL, - -1, - parser_functions, - NULL, - NULL, - NULL, - NULL + PyModuleDef_HEAD_INIT, + "parser", + NULL, + -1, + parser_functions, + NULL, + NULL, + NULL, + NULL }; PyMODINIT_FUNC PyInit_parser(void); /* supply a prototype */ @@ -3176,7 +3176,7 @@ return NULL; module = PyModule_Create(&parsermodule); if (module == NULL) - return NULL; + return NULL; if (parser_error == 0) parser_error = PyErr_NewException("parser.ParserError", NULL, NULL); Modified: python/branches/release31-maint/Modules/pwdmodule.c ============================================================================== --- python/branches/release31-maint/Modules/pwdmodule.c (original) +++ python/branches/release31-maint/Modules/pwdmodule.c Sun May 9 18:14:21 2010 @@ -8,14 +8,14 @@ #include static PyStructSequence_Field struct_pwd_type_fields[] = { - {"pw_name", "user name"}, - {"pw_passwd", "password"}, - {"pw_uid", "user id"}, - {"pw_gid", "group id"}, - {"pw_gecos", "real name"}, - {"pw_dir", "home directory"}, - {"pw_shell", "shell program"}, - {0} + {"pw_name", "user name"}, + {"pw_passwd", "password"}, + {"pw_uid", "user id"}, + {"pw_gid", "group id"}, + {"pw_gecos", "real name"}, + {"pw_dir", "home directory"}, + {"pw_shell", "shell program"}, + {0} }; PyDoc_STRVAR(struct_passwd__doc__, @@ -25,10 +25,10 @@ or via the object attributes as named in the above tuple."); static PyStructSequence_Desc struct_pwd_type_desc = { - "pwd.struct_passwd", - struct_passwd__doc__, - struct_pwd_type_fields, - 7, + "pwd.struct_passwd", + struct_passwd__doc__, + struct_pwd_type_fields, + 7, }; PyDoc_STRVAR(pwd__doc__, @@ -41,7 +41,7 @@ The uid and gid items are integers, all others are strings. An\n\ exception is raised if the entry asked for cannot be found."); - + static int initialized; static PyTypeObject StructPwdType; @@ -49,53 +49,53 @@ sets(PyObject *v, int i, const char* val) { if (val) { - PyObject *o = PyUnicode_Decode(val, strlen(val), - Py_FileSystemDefaultEncoding, - "surrogateescape"); - PyStructSequence_SET_ITEM(v, i, o); + PyObject *o = PyUnicode_Decode(val, strlen(val), + Py_FileSystemDefaultEncoding, + "surrogateescape"); + PyStructSequence_SET_ITEM(v, i, o); } else { - PyStructSequence_SET_ITEM(v, i, Py_None); - Py_INCREF(Py_None); + PyStructSequence_SET_ITEM(v, i, Py_None); + Py_INCREF(Py_None); } } static PyObject * mkpwent(struct passwd *p) { - int setIndex = 0; - PyObject *v = PyStructSequence_New(&StructPwdType); - if (v == NULL) - return NULL; + int setIndex = 0; + PyObject *v = PyStructSequence_New(&StructPwdType); + if (v == NULL) + return NULL; #define SETI(i,val) PyStructSequence_SET_ITEM(v, i, PyLong_FromLong((long) val)) #define SETS(i,val) sets(v, i, val) - SETS(setIndex++, p->pw_name); + SETS(setIndex++, p->pw_name); #ifdef __VMS - SETS(setIndex++, ""); + SETS(setIndex++, ""); #else - SETS(setIndex++, p->pw_passwd); + SETS(setIndex++, p->pw_passwd); #endif - SETI(setIndex++, p->pw_uid); - SETI(setIndex++, p->pw_gid); + SETI(setIndex++, p->pw_uid); + SETI(setIndex++, p->pw_gid); #ifdef __VMS - SETS(setIndex++, ""); + SETS(setIndex++, ""); #else - SETS(setIndex++, p->pw_gecos); + SETS(setIndex++, p->pw_gecos); #endif - SETS(setIndex++, p->pw_dir); - SETS(setIndex++, p->pw_shell); + SETS(setIndex++, p->pw_dir); + SETS(setIndex++, p->pw_shell); #undef SETS #undef SETI - if (PyErr_Occurred()) { - Py_XDECREF(v); - return NULL; - } + if (PyErr_Occurred()) { + Py_XDECREF(v); + return NULL; + } - return v; + return v; } PyDoc_STRVAR(pwd_getpwuid__doc__, @@ -107,16 +107,16 @@ static PyObject * pwd_getpwuid(PyObject *self, PyObject *args) { - unsigned int uid; - struct passwd *p; - if (!PyArg_ParseTuple(args, "I:getpwuid", &uid)) - return NULL; - if ((p = getpwuid(uid)) == NULL) { - PyErr_Format(PyExc_KeyError, - "getpwuid(): uid not found: %d", uid); - return NULL; - } - return mkpwent(p); + unsigned int uid; + struct passwd *p; + if (!PyArg_ParseTuple(args, "I:getpwuid", &uid)) + return NULL; + if ((p = getpwuid(uid)) == NULL) { + PyErr_Format(PyExc_KeyError, + "getpwuid(): uid not found: %d", uid); + return NULL; + } + return mkpwent(p); } PyDoc_STRVAR(pwd_getpwnam__doc__, @@ -128,27 +128,27 @@ static PyObject * pwd_getpwnam(PyObject *self, PyObject *args) { - char *name; - struct passwd *p; - PyObject *arg, *bytes, *retval = NULL; - - if (!PyArg_ParseTuple(args, "U:getpwnam", &arg)) - return NULL; - if ((bytes = PyUnicode_AsEncodedString(arg, - Py_FileSystemDefaultEncoding, - "surrogateescape")) == NULL) - return NULL; - if (PyBytes_AsStringAndSize(bytes, &name, NULL) == -1) - goto out; - if ((p = getpwnam(name)) == NULL) { - PyErr_Format(PyExc_KeyError, - "getpwnam(): name not found: %s", name); - goto out; - } - retval = mkpwent(p); + char *name; + struct passwd *p; + PyObject *arg, *bytes, *retval = NULL; + + if (!PyArg_ParseTuple(args, "U:getpwnam", &arg)) + return NULL; + if ((bytes = PyUnicode_AsEncodedString(arg, + Py_FileSystemDefaultEncoding, + "surrogateescape")) == NULL) + return NULL; + if (PyBytes_AsStringAndSize(bytes, &name, NULL) == -1) + goto out; + if ((p = getpwnam(name)) == NULL) { + PyErr_Format(PyExc_KeyError, + "getpwnam(): name not found: %s", name); + goto out; + } + retval = mkpwent(p); out: - Py_DECREF(bytes); - return retval; + Py_DECREF(bytes); + return retval; } #ifdef HAVE_GETPWENT @@ -161,67 +161,67 @@ static PyObject * pwd_getpwall(PyObject *self) { - PyObject *d; - struct passwd *p; - if ((d = PyList_New(0)) == NULL) - return NULL; + PyObject *d; + struct passwd *p; + if ((d = PyList_New(0)) == NULL) + return NULL; #if defined(PYOS_OS2) && defined(PYCC_GCC) - if ((p = getpwuid(0)) != NULL) { + if ((p = getpwuid(0)) != NULL) { #else - setpwent(); - while ((p = getpwent()) != NULL) { + setpwent(); + while ((p = getpwent()) != NULL) { #endif - PyObject *v = mkpwent(p); - if (v == NULL || PyList_Append(d, v) != 0) { - Py_XDECREF(v); - Py_DECREF(d); - endpwent(); - return NULL; - } - Py_DECREF(v); - } - endpwent(); - return d; + PyObject *v = mkpwent(p); + if (v == NULL || PyList_Append(d, v) != 0) { + Py_XDECREF(v); + Py_DECREF(d); + endpwent(); + return NULL; + } + Py_DECREF(v); + } + endpwent(); + return d; } #endif static PyMethodDef pwd_methods[] = { - {"getpwuid", pwd_getpwuid, METH_VARARGS, pwd_getpwuid__doc__}, - {"getpwnam", pwd_getpwnam, METH_VARARGS, pwd_getpwnam__doc__}, + {"getpwuid", pwd_getpwuid, METH_VARARGS, pwd_getpwuid__doc__}, + {"getpwnam", pwd_getpwnam, METH_VARARGS, pwd_getpwnam__doc__}, #ifdef HAVE_GETPWENT - {"getpwall", (PyCFunction)pwd_getpwall, - METH_NOARGS, pwd_getpwall__doc__}, + {"getpwall", (PyCFunction)pwd_getpwall, + METH_NOARGS, pwd_getpwall__doc__}, #endif - {NULL, NULL} /* sentinel */ + {NULL, NULL} /* sentinel */ }; static struct PyModuleDef pwdmodule = { - PyModuleDef_HEAD_INIT, - "pwd", - pwd__doc__, - -1, - pwd_methods, - NULL, - NULL, - NULL, - NULL + PyModuleDef_HEAD_INIT, + "pwd", + pwd__doc__, + -1, + pwd_methods, + NULL, + NULL, + NULL, + NULL }; PyMODINIT_FUNC PyInit_pwd(void) { - PyObject *m; - m = PyModule_Create(&pwdmodule); - if (m == NULL) - return NULL; - - if (!initialized) { - PyStructSequence_InitType(&StructPwdType, - &struct_pwd_type_desc); - initialized = 1; - } - Py_INCREF((PyObject *) &StructPwdType); - PyModule_AddObject(m, "struct_passwd", (PyObject *) &StructPwdType); - return m; + PyObject *m; + m = PyModule_Create(&pwdmodule); + if (m == NULL) + return NULL; + + if (!initialized) { + PyStructSequence_InitType(&StructPwdType, + &struct_pwd_type_desc); + initialized = 1; + } + Py_INCREF((PyObject *) &StructPwdType); + PyModule_AddObject(m, "struct_passwd", (PyObject *) &StructPwdType); + return m; } Modified: python/branches/release31-maint/Modules/pyexpat.c ============================================================================== --- python/branches/release31-maint/Modules/pyexpat.c (original) +++ python/branches/release31-maint/Modules/pyexpat.c Sun May 9 18:14:21 2010 @@ -193,7 +193,7 @@ used only from the character data handler trampoline, and must be used right after `flag_error()` is called. */ static void -noop_character_data_handler(void *userData, const XML_Char *data, int len) +noop_character_data_handler(void *userData, const XML_Char *data, int len) { /* Do nothing. */ } @@ -226,23 +226,23 @@ goto failed; filename = PyUnicode_DecodeFSDefault(__FILE__); handler_info[slot].tb_code = - PyCode_New(0, /* argcount */ + PyCode_New(0, /* argcount */ 0, /* kwonlyargcount */ - 0, /* nlocals */ - 0, /* stacksize */ - 0, /* flags */ - code, /* code */ - nulltuple, /* consts */ - nulltuple, /* names */ - nulltuple, /* varnames */ + 0, /* nlocals */ + 0, /* stacksize */ + 0, /* flags */ + code, /* code */ + nulltuple, /* consts */ + nulltuple, /* names */ + nulltuple, /* varnames */ #if PYTHON_API_VERSION >= 1010 - nulltuple, /* freevars */ - nulltuple, /* cellvars */ + nulltuple, /* freevars */ + nulltuple, /* cellvars */ #endif - filename, /* filename */ - name, /* name */ - lineno, /* firstlineno */ - code /* lnotab */ + filename, /* filename */ + name, /* name */ + lineno, /* firstlineno */ + code /* lnotab */ ); if (handler_info[slot].tb_code == NULL) goto failed; @@ -264,25 +264,25 @@ { int result = 0; if (!tstate->use_tracing || tstate->tracing) - return 0; + return 0; if (tstate->c_profilefunc != NULL) { - tstate->tracing++; - result = tstate->c_profilefunc(tstate->c_profileobj, - f, code , val); - tstate->use_tracing = ((tstate->c_tracefunc != NULL) - || (tstate->c_profilefunc != NULL)); - tstate->tracing--; - if (result) - return result; + tstate->tracing++; + result = tstate->c_profilefunc(tstate->c_profileobj, + f, code , val); + tstate->use_tracing = ((tstate->c_tracefunc != NULL) + || (tstate->c_profilefunc != NULL)); + tstate->tracing--; + if (result) + return result; } if (tstate->c_tracefunc != NULL) { - tstate->tracing++; - result = tstate->c_tracefunc(tstate->c_traceobj, - f, code , val); - tstate->use_tracing = ((tstate->c_tracefunc != NULL) - || (tstate->c_profilefunc != NULL)); - tstate->tracing--; - } + tstate->tracing++; + result = tstate->c_tracefunc(tstate->c_traceobj, + f, code , val); + tstate->use_tracing = ((tstate->c_tracefunc != NULL) + || (tstate->c_profilefunc != NULL)); + tstate->tracing--; + } return result; } @@ -293,12 +293,12 @@ int err; if (tstate->c_tracefunc == NULL) - return 0; + return 0; PyErr_Fetch(&type, &value, &traceback); if (value == NULL) { - value = Py_None; - Py_INCREF(value); + value = Py_None; + Py_INCREF(value); } #if PY_VERSION_HEX < 0x02040000 arg = Py_BuildValue("(OOO)", type, value, traceback); @@ -306,17 +306,17 @@ arg = PyTuple_Pack(3, type, value, traceback); #endif if (arg == NULL) { - PyErr_Restore(type, value, traceback); - return 0; + PyErr_Restore(type, value, traceback); + return 0; } err = trace_frame(tstate, f, PyTrace_EXCEPTION, arg); Py_DECREF(arg); if (err == 0) - PyErr_Restore(type, value, traceback); + PyErr_Restore(type, value, traceback); else { - Py_XDECREF(type); - Py_XDECREF(value); - Py_XDECREF(traceback); + Py_XDECREF(type); + Py_XDECREF(value); + Py_XDECREF(traceback); } return err; } @@ -332,31 +332,31 @@ if (c == NULL) return NULL; - + f = PyFrame_New(tstate, c, PyEval_GetGlobals(), NULL); if (f == NULL) return NULL; tstate->frame = f; #ifdef FIX_TRACE if (trace_frame(tstate, f, PyTrace_CALL, Py_None) < 0) { - return NULL; + return NULL; } #endif res = PyEval_CallObject(func, args); if (res == NULL) { - if (tstate->curexc_traceback == NULL) - PyTraceBack_Here(f); + if (tstate->curexc_traceback == NULL) + PyTraceBack_Here(f); XML_StopParser(self->itself, XML_FALSE); #ifdef FIX_TRACE - if (trace_frame_exc(tstate, f) < 0) { - return NULL; - } + if (trace_frame_exc(tstate, f) < 0) { + return NULL; + } } else { - if (trace_frame(tstate, f, PyTrace_RETURN, res) < 0) { - Py_XDECREF(res); - res = NULL; - } + if (trace_frame(tstate, f, PyTrace_RETURN, res) < 0) { + Py_XDECREF(res); + res = NULL; + } } #else } @@ -373,12 +373,12 @@ PyObject *value; /* result can be NULL if the unicode conversion failed. */ if (!result) - return result; + return result; if (!self->intern) - return result; + return result; value = PyDict_GetItem(self->intern, result); if (!value) { - if (PyDict_SetItem(self->intern, result, result) == 0) + if (PyDict_SetItem(self->intern, result, result) == 0) return result; else return NULL; @@ -438,7 +438,7 @@ } static void -my_CharacterDataHandler(void *userData, const XML_Char *data, int len) +my_CharacterDataHandler(void *userData, const XML_Char *data, int len) { xmlparseobject *self = (xmlparseobject *) userData; if (self->buffer == NULL) @@ -578,13 +578,13 @@ } #define VOID_HANDLER(NAME, PARAMS, PARAM_FORMAT) \ - RC_HANDLER(void, NAME, PARAMS, ;, PARAM_FORMAT, ;, ;,\ - (xmlparseobject *)userData) + RC_HANDLER(void, NAME, PARAMS, ;, PARAM_FORMAT, ;, ;,\ + (xmlparseobject *)userData) #define INT_HANDLER(NAME, PARAMS, PARAM_FORMAT)\ - RC_HANDLER(int, NAME, PARAMS, int rc=0;, PARAM_FORMAT, \ - rc = PyLong_AsLong(rv);, rc, \ - (xmlparseobject *)userData) + RC_HANDLER(int, NAME, PARAMS, int rc=0;, PARAM_FORMAT, \ + rc = PyLong_AsLong(rv);, rc, \ + (xmlparseobject *)userData) VOID_HANDLER(EndElement, (void *userData, const XML_Char *name), @@ -729,25 +729,25 @@ #endif VOID_HANDLER(NotationDecl, - (void *userData, - const XML_Char *notationName, - const XML_Char *base, - const XML_Char *systemId, - const XML_Char *publicId), + (void *userData, + const XML_Char *notationName, + const XML_Char *base, + const XML_Char *systemId, + const XML_Char *publicId), ("(NNNN)", - string_intern(self, notationName), string_intern(self, base), - string_intern(self, systemId), string_intern(self, publicId))) + string_intern(self, notationName), string_intern(self, base), + string_intern(self, systemId), string_intern(self, publicId))) VOID_HANDLER(StartNamespaceDecl, - (void *userData, - const XML_Char *prefix, - const XML_Char *uri), + (void *userData, + const XML_Char *prefix, + const XML_Char *uri), ("(NN)", string_intern(self, prefix), string_intern(self, uri))) VOID_HANDLER(EndNamespaceDecl, - (void *userData, - const XML_Char *prefix), + (void *userData, + const XML_Char *prefix), ("(N)", string_intern(self, prefix))) VOID_HANDLER(Comment, @@ -756,36 +756,36 @@ VOID_HANDLER(StartCdataSection, (void *userData), - ("()")) + ("()")) VOID_HANDLER(EndCdataSection, (void *userData), - ("()")) + ("()")) VOID_HANDLER(Default, - (void *userData, const XML_Char *s, int len), - ("(N)", (conv_string_len_to_unicode(s,len)))) + (void *userData, const XML_Char *s, int len), + ("(N)", (conv_string_len_to_unicode(s,len)))) VOID_HANDLER(DefaultHandlerExpand, - (void *userData, const XML_Char *s, int len), - ("(N)", (conv_string_len_to_unicode(s,len)))) + (void *userData, const XML_Char *s, int len), + ("(N)", (conv_string_len_to_unicode(s,len)))) INT_HANDLER(NotStandalone, - (void *userData), - ("()")) + (void *userData), + ("()")) RC_HANDLER(int, ExternalEntityRef, - (XML_Parser parser, - const XML_Char *context, - const XML_Char *base, - const XML_Char *systemId, - const XML_Char *publicId), - int rc=0;, + (XML_Parser parser, + const XML_Char *context, + const XML_Char *base, + const XML_Char *systemId, + const XML_Char *publicId), + int rc=0;, ("(O&NNN)", - conv_string_to_unicode ,context, string_intern(self, base), - string_intern(self, systemId), string_intern(self, publicId)), - rc = PyLong_AsLong(rv);, rc, - XML_GetUserData(parser)) + conv_string_to_unicode ,context, string_intern(self, base), + string_intern(self, systemId), string_intern(self, publicId)), + rc = PyLong_AsLong(rv);, rc, + XML_GetUserData(parser)) /* XXX UnknownEncodingHandler */ @@ -957,7 +957,7 @@ if (!PyArg_ParseTuple(args, "s:SetBase", &base)) return NULL; if (!XML_SetBase(self->itself, base)) { - return PyErr_NoMemory(); + return PyErr_NoMemory(); } Py_INCREF(Py_None); return Py_None; @@ -1047,7 +1047,7 @@ new_parser->in_callback = 0; new_parser->ns_prefixes = self->ns_prefixes; new_parser->itself = XML_ExternalEntityParserCreate(self->itself, context, - encoding); + encoding); new_parser->handlers = 0; new_parser->intern = self->intern; Py_XINCREF(new_parser->intern); @@ -1138,26 +1138,26 @@ static PyObject *xmlparse_dir(PyObject *self, PyObject* noargs); static struct PyMethodDef xmlparse_methods[] = { - {"Parse", (PyCFunction)xmlparse_Parse, - METH_VARARGS, xmlparse_Parse__doc__}, + {"Parse", (PyCFunction)xmlparse_Parse, + METH_VARARGS, xmlparse_Parse__doc__}, {"ParseFile", (PyCFunction)xmlparse_ParseFile, - METH_O, xmlparse_ParseFile__doc__}, + METH_O, xmlparse_ParseFile__doc__}, {"SetBase", (PyCFunction)xmlparse_SetBase, - METH_VARARGS, xmlparse_SetBase__doc__}, + METH_VARARGS, xmlparse_SetBase__doc__}, {"GetBase", (PyCFunction)xmlparse_GetBase, - METH_NOARGS, xmlparse_GetBase__doc__}, + METH_NOARGS, xmlparse_GetBase__doc__}, {"ExternalEntityParserCreate", (PyCFunction)xmlparse_ExternalEntityParserCreate, - METH_VARARGS, xmlparse_ExternalEntityParserCreate__doc__}, + METH_VARARGS, xmlparse_ExternalEntityParserCreate__doc__}, {"SetParamEntityParsing", (PyCFunction)xmlparse_SetParamEntityParsing, - METH_VARARGS, xmlparse_SetParamEntityParsing__doc__}, + METH_VARARGS, xmlparse_SetParamEntityParsing__doc__}, {"GetInputContext", (PyCFunction)xmlparse_GetInputContext, - METH_NOARGS, xmlparse_GetInputContext__doc__}, + METH_NOARGS, xmlparse_GetInputContext__doc__}, #if XML_COMBINED_VERSION >= 19505 {"UseForeignDTD", (PyCFunction)xmlparse_UseForeignDTD, - METH_VARARGS, xmlparse_UseForeignDTD__doc__}, + METH_VARARGS, xmlparse_UseForeignDTD__doc__}, #endif {"__dir__", xmlparse_dir, METH_NOARGS}, - {NULL, NULL} /* sentinel */ + {NULL, NULL} /* sentinel */ }; /* ---------- */ @@ -1175,7 +1175,7 @@ { int i; for (i = 0; i < 256; i++) { - template_buffer[i] = i; + template_buffer[i] = i; } template_buffer[256] = 0; } @@ -1194,15 +1194,15 @@ PyUnicode_Decode(template_buffer, 256, name, "replace"); if (_u_string == NULL) - return result; + return result; for (i = 0; i < 256; i++) { - /* Stupid to access directly, but fast */ - Py_UNICODE c = _u_string->str[i]; - if (c == Py_UNICODE_REPLACEMENT_CHARACTER) - info->map[i] = -1; - else - info->map[i] = c; + /* Stupid to access directly, but fast */ + Py_UNICODE c = _u_string->str[i]; + if (c == Py_UNICODE_REPLACEMENT_CHARACTER) + info->map[i] = -1; + else + info->map[i] = c; } info->data = NULL; info->convert = NULL; @@ -1337,8 +1337,8 @@ int handlernum = -1; if (PyUnicode_Check(nameobj)) - name = _PyUnicode_AsString(nameobj); - + name = _PyUnicode_AsString(nameobj); + handlernum = handlername2int(name); if (handlernum != -1) { @@ -1404,18 +1404,18 @@ static PyObject * xmlparse_dir(PyObject *self, PyObject* noargs) { -#define APPEND(list, str) \ - do { \ - PyObject *o = PyUnicode_FromString(str); \ - if (o != NULL) \ - PyList_Append(list, o); \ - Py_XDECREF(o); \ +#define APPEND(list, str) \ + do { \ + PyObject *o = PyUnicode_FromString(str); \ + if (o != NULL) \ + PyList_Append(list, o); \ + Py_XDECREF(o); \ } while (0) int i; PyObject *rc = PyList_New(0); if (!rc) - return NULL; + return NULL; for (i = 0; handler_info[i].name != NULL; i++) { PyObject *o = get_handler_name(&handler_info[i]); if (o != NULL) @@ -1536,42 +1536,42 @@ if (strcmp(name, "buffer_size") == 0) { long new_buffer_size; if (!PyLong_Check(v)) { - PyErr_SetString(PyExc_TypeError, "buffer_size must be an integer"); - return -1; + PyErr_SetString(PyExc_TypeError, "buffer_size must be an integer"); + return -1; } new_buffer_size=PyLong_AS_LONG(v); /* trivial case -- no change */ if (new_buffer_size == self->buffer_size) { - return 0; + return 0; } if (new_buffer_size <= 0) { - PyErr_SetString(PyExc_ValueError, "buffer_size must be greater than zero"); - return -1; + PyErr_SetString(PyExc_ValueError, "buffer_size must be greater than zero"); + return -1; } /* check maximum */ if (new_buffer_size > INT_MAX) { - char errmsg[100]; - sprintf(errmsg, "buffer_size must not be greater than %i", INT_MAX); - PyErr_SetString(PyExc_ValueError, errmsg); - return -1; + char errmsg[100]; + sprintf(errmsg, "buffer_size must not be greater than %i", INT_MAX); + PyErr_SetString(PyExc_ValueError, errmsg); + return -1; } if (self->buffer != NULL) { - /* there is already a buffer */ - if (self->buffer_used != 0) { - flush_character_buffer(self); - } - /* free existing buffer */ - free(self->buffer); + /* there is already a buffer */ + if (self->buffer_used != 0) { + flush_character_buffer(self); + } + /* free existing buffer */ + free(self->buffer); } self->buffer = malloc(new_buffer_size); if (self->buffer == NULL) { - PyErr_NoMemory(); - return -1; - } + PyErr_NoMemory(); + return -1; + } self->buffer_size = new_buffer_size; return 0; } @@ -1612,39 +1612,39 @@ PyDoc_STRVAR(Xmlparsetype__doc__, "XML parser"); static PyTypeObject Xmlparsetype = { - PyVarObject_HEAD_INIT(NULL, 0) - "pyexpat.xmlparser", /*tp_name*/ - sizeof(xmlparseobject) + PyGC_HEAD_SIZE,/*tp_basicsize*/ - 0, /*tp_itemsize*/ - /* methods */ - (destructor)xmlparse_dealloc, /*tp_dealloc*/ - (printfunc)0, /*tp_print*/ - 0, /*tp_getattr*/ - (setattrfunc)xmlparse_setattr, /*tp_setattr*/ - 0, /*tp_reserved*/ - (reprfunc)0, /*tp_repr*/ - 0, /*tp_as_number*/ - 0, /*tp_as_sequence*/ - 0, /*tp_as_mapping*/ - (hashfunc)0, /*tp_hash*/ - (ternaryfunc)0, /*tp_call*/ - (reprfunc)0, /*tp_str*/ - (getattrofunc)xmlparse_getattro, /* tp_getattro */ - 0, /* tp_setattro */ - 0, /* tp_as_buffer */ + PyVarObject_HEAD_INIT(NULL, 0) + "pyexpat.xmlparser", /*tp_name*/ + sizeof(xmlparseobject) + PyGC_HEAD_SIZE,/*tp_basicsize*/ + 0, /*tp_itemsize*/ + /* methods */ + (destructor)xmlparse_dealloc, /*tp_dealloc*/ + (printfunc)0, /*tp_print*/ + 0, /*tp_getattr*/ + (setattrfunc)xmlparse_setattr, /*tp_setattr*/ + 0, /*tp_reserved*/ + (reprfunc)0, /*tp_repr*/ + 0, /*tp_as_number*/ + 0, /*tp_as_sequence*/ + 0, /*tp_as_mapping*/ + (hashfunc)0, /*tp_hash*/ + (ternaryfunc)0, /*tp_call*/ + (reprfunc)0, /*tp_str*/ + (getattrofunc)xmlparse_getattro, /* tp_getattro */ + 0, /* tp_setattro */ + 0, /* tp_as_buffer */ #ifdef Py_TPFLAGS_HAVE_GC - Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC, /*tp_flags*/ + Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC, /*tp_flags*/ #else - Py_TPFLAGS_DEFAULT | Py_TPFLAGS_GC, /*tp_flags*/ + Py_TPFLAGS_DEFAULT | Py_TPFLAGS_GC, /*tp_flags*/ #endif - Xmlparsetype__doc__, /* tp_doc - Documentation string */ - (traverseproc)xmlparse_traverse, /* tp_traverse */ - (inquiry)xmlparse_clear, /* tp_clear */ - 0, /* tp_richcompare */ - 0, /* tp_weaklistoffset */ - 0, /* tp_iter */ - 0, /* tp_iternext */ - xmlparse_methods, /* tp_methods */ + Xmlparsetype__doc__, /* tp_doc - Documentation string */ + (traverseproc)xmlparse_traverse, /* tp_traverse */ + (inquiry)xmlparse_clear, /* tp_clear */ + 0, /* tp_richcompare */ + 0, /* tp_weaklistoffset */ + 0, /* tp_iter */ + 0, /* tp_iternext */ + xmlparse_methods, /* tp_methods */ }; /* End of code for xmlparser objects */ @@ -1678,21 +1678,21 @@ /* Explicitly passing None means no interning is desired. Not passing anything means that a new dictionary is used. */ if (intern == Py_None) - intern = NULL; + intern = NULL; else if (intern == NULL) { - intern = PyDict_New(); - if (!intern) - return NULL; - intern_decref = 1; + intern = PyDict_New(); + if (!intern) + return NULL; + intern_decref = 1; } else if (!PyDict_Check(intern)) { - PyErr_SetString(PyExc_TypeError, "intern must be a dictionary"); - return NULL; + PyErr_SetString(PyExc_TypeError, "intern must be a dictionary"); + return NULL; } result = newxmlparseobject(encoding, namespace_separator, intern); if (intern_decref) { - Py_DECREF(intern); + Py_DECREF(intern); } return result; } @@ -1714,12 +1714,12 @@ /* List of methods defined in the module */ static struct PyMethodDef pyexpat_methods[] = { - {"ParserCreate", (PyCFunction)pyexpat_ParserCreate, + {"ParserCreate", (PyCFunction)pyexpat_ParserCreate, METH_VARARGS|METH_KEYWORDS, pyexpat_ParserCreate__doc__}, - {"ErrorString", (PyCFunction)pyexpat_ErrorString, - METH_VARARGS, pyexpat_ErrorString__doc__}, + {"ErrorString", (PyCFunction)pyexpat_ErrorString, + METH_VARARGS, pyexpat_ErrorString__doc__}, - {NULL, (PyCFunction)NULL, 0, NULL} /* sentinel */ + {NULL, (PyCFunction)NULL, 0, NULL} /* sentinel */ }; /* Module docstring */ @@ -1768,15 +1768,15 @@ PyMODINIT_FUNC MODULE_INITFUNC(void); /* avoid compiler warnings */ static struct PyModuleDef pyexpatmodule = { - PyModuleDef_HEAD_INIT, - MODULE_NAME, - pyexpat_module_documentation, - -1, - pyexpat_methods, - NULL, - NULL, - NULL, - NULL + PyModuleDef_HEAD_INIT, + MODULE_NAME, + pyexpat_module_documentation, + -1, + pyexpat_methods, + NULL, + NULL, + NULL, + NULL }; PyMODINIT_FUNC @@ -1798,12 +1798,12 @@ return NULL; if (PyType_Ready(&Xmlparsetype) < 0) - return NULL; + return NULL; /* Create the module and add the functions */ m = PyModule_Create(&pyexpatmodule); if (m == NULL) - return NULL; + return NULL; /* Add some symbolic constants to the module */ if (ErrorObject == NULL) { @@ -1860,7 +1860,7 @@ if (errors_module == NULL || model_module == NULL) /* Don't core dump later! */ return NULL; - + #if XML_COMBINED_VERSION > 19505 { const XML_Feature *features = XML_GetFeatureList(); @@ -1985,7 +1985,7 @@ capi.SetProcessingInstructionHandler = XML_SetProcessingInstructionHandler; capi.SetUnknownEncodingHandler = XML_SetUnknownEncodingHandler; capi.SetUserData = XML_SetUserData; - + /* export using capsule */ capi_object = PyCapsule_New(&capi, PyExpat_CAPSULE_NAME, NULL); if (capi_object) @@ -2001,12 +2001,12 @@ for (; handler_info[i].name != NULL; i++) { if (initial) - self->handlers[i] = NULL; - else { + self->handlers[i] = NULL; + else { temp = self->handlers[i]; self->handlers[i] = NULL; Py_XDECREF(temp); - handler_info[i].setter(self->itself, NULL); + handler_info[i].setter(self->itself, NULL); } } } Modified: python/branches/release31-maint/Modules/python.c ============================================================================== --- python/branches/release31-maint/Modules/python.c (original) +++ python/branches/release31-maint/Modules/python.c Sun May 9 18:14:21 2010 @@ -11,150 +11,150 @@ int wmain(int argc, wchar_t **argv) { - return Py_Main(argc, argv); + return Py_Main(argc, argv); } #else static wchar_t* char2wchar(char* arg) { - wchar_t *res; + wchar_t *res; #ifdef HAVE_BROKEN_MBSTOWCS - /* Some platforms have a broken implementation of - * mbstowcs which does not count the characters that - * would result from conversion. Use an upper bound. - */ - size_t argsize = strlen(arg); + /* Some platforms have a broken implementation of + * mbstowcs which does not count the characters that + * would result from conversion. Use an upper bound. + */ + size_t argsize = strlen(arg); #else - size_t argsize = mbstowcs(NULL, arg, 0); + size_t argsize = mbstowcs(NULL, arg, 0); #endif - size_t count; - unsigned char *in; - wchar_t *out; + size_t count; + unsigned char *in; + wchar_t *out; #ifdef HAVE_MBRTOWC - mbstate_t mbs; + mbstate_t mbs; #endif - if (argsize != (size_t)-1) { - res = (wchar_t *)PyMem_Malloc((argsize+1)*sizeof(wchar_t)); - if (!res) - goto oom; - count = mbstowcs(res, arg, argsize+1); - if (count != (size_t)-1) { - wchar_t *tmp; - /* Only use the result if it contains no - surrogate characters. */ - for (tmp = res; *tmp != 0 && - (*tmp < 0xd800 || *tmp > 0xdfff); tmp++) - ; - if (*tmp == 0) - return res; - } - PyMem_Free(res); - } - /* Conversion failed. Fall back to escaping with surrogateescape. */ + if (argsize != (size_t)-1) { + res = (wchar_t *)PyMem_Malloc((argsize+1)*sizeof(wchar_t)); + if (!res) + goto oom; + count = mbstowcs(res, arg, argsize+1); + if (count != (size_t)-1) { + wchar_t *tmp; + /* Only use the result if it contains no + surrogate characters. */ + for (tmp = res; *tmp != 0 && + (*tmp < 0xd800 || *tmp > 0xdfff); tmp++) + ; + if (*tmp == 0) + return res; + } + PyMem_Free(res); + } + /* Conversion failed. Fall back to escaping with surrogateescape. */ #ifdef HAVE_MBRTOWC - /* Try conversion with mbrtwoc (C99), and escape non-decodable bytes. */ - - /* Overallocate; as multi-byte characters are in the argument, the - actual output could use less memory. */ - argsize = strlen(arg) + 1; - res = PyMem_Malloc(argsize*sizeof(wchar_t)); - if (!res) goto oom; - in = (unsigned char*)arg; - out = res; - memset(&mbs, 0, sizeof mbs); - while (argsize) { - size_t converted = mbrtowc(out, (char*)in, argsize, &mbs); - if (converted == 0) - /* Reached end of string; null char stored. */ - break; - if (converted == (size_t)-2) { - /* Incomplete character. This should never happen, - since we provide everything that we have - - unless there is a bug in the C library, or I - misunderstood how mbrtowc works. */ - fprintf(stderr, "unexpected mbrtowc result -2\n"); - return NULL; - } - if (converted == (size_t)-1) { - /* Conversion error. Escape as UTF-8b, and start over - in the initial shift state. */ - *out++ = 0xdc00 + *in++; - argsize--; - memset(&mbs, 0, sizeof mbs); - continue; - } - if (*out >= 0xd800 && *out <= 0xdfff) { - /* Surrogate character. Escape the original - byte sequence with surrogateescape. */ - argsize -= converted; - while (converted--) - *out++ = 0xdc00 + *in++; - continue; - } - /* successfully converted some bytes */ - in += converted; - argsize -= converted; - out++; - } + /* Try conversion with mbrtwoc (C99), and escape non-decodable bytes. */ + + /* Overallocate; as multi-byte characters are in the argument, the + actual output could use less memory. */ + argsize = strlen(arg) + 1; + res = PyMem_Malloc(argsize*sizeof(wchar_t)); + if (!res) goto oom; + in = (unsigned char*)arg; + out = res; + memset(&mbs, 0, sizeof mbs); + while (argsize) { + size_t converted = mbrtowc(out, (char*)in, argsize, &mbs); + if (converted == 0) + /* Reached end of string; null char stored. */ + break; + if (converted == (size_t)-2) { + /* Incomplete character. This should never happen, + since we provide everything that we have - + unless there is a bug in the C library, or I + misunderstood how mbrtowc works. */ + fprintf(stderr, "unexpected mbrtowc result -2\n"); + return NULL; + } + if (converted == (size_t)-1) { + /* Conversion error. Escape as UTF-8b, and start over + in the initial shift state. */ + *out++ = 0xdc00 + *in++; + argsize--; + memset(&mbs, 0, sizeof mbs); + continue; + } + if (*out >= 0xd800 && *out <= 0xdfff) { + /* Surrogate character. Escape the original + byte sequence with surrogateescape. */ + argsize -= converted; + while (converted--) + *out++ = 0xdc00 + *in++; + continue; + } + /* successfully converted some bytes */ + in += converted; + argsize -= converted; + out++; + } #else - /* Cannot use C locale for escaping; manually escape as if charset - is ASCII (i.e. escape all bytes > 128. This will still roundtrip - correctly in the locale's charset, which must be an ASCII superset. */ - res = PyMem_Malloc((strlen(arg)+1)*sizeof(wchar_t)); - if (!res) goto oom; - in = (unsigned char*)arg; - out = res; - while(*in) - if(*in < 128) - *out++ = *in++; - else - *out++ = 0xdc00 + *in++; - *out = 0; + /* Cannot use C locale for escaping; manually escape as if charset + is ASCII (i.e. escape all bytes > 128. This will still roundtrip + correctly in the locale's charset, which must be an ASCII superset. */ + res = PyMem_Malloc((strlen(arg)+1)*sizeof(wchar_t)); + if (!res) goto oom; + in = (unsigned char*)arg; + out = res; + while(*in) + if(*in < 128) + *out++ = *in++; + else + *out++ = 0xdc00 + *in++; + *out = 0; #endif - return res; + return res; oom: - fprintf(stderr, "out of memory\n"); - return NULL; + fprintf(stderr, "out of memory\n"); + return NULL; } int main(int argc, char **argv) { - wchar_t **argv_copy = (wchar_t **)PyMem_Malloc(sizeof(wchar_t*)*argc); - /* We need a second copies, as Python might modify the first one. */ - wchar_t **argv_copy2 = (wchar_t **)PyMem_Malloc(sizeof(wchar_t*)*argc); - int i, res; - char *oldloc; - /* 754 requires that FP exceptions run in "no stop" mode by default, - * and until C vendors implement C99's ways to control FP exceptions, - * Python requires non-stop mode. Alas, some platforms enable FP - * exceptions by default. Here we disable them. - */ + wchar_t **argv_copy = (wchar_t **)PyMem_Malloc(sizeof(wchar_t*)*argc); + /* We need a second copies, as Python might modify the first one. */ + wchar_t **argv_copy2 = (wchar_t **)PyMem_Malloc(sizeof(wchar_t*)*argc); + int i, res; + char *oldloc; + /* 754 requires that FP exceptions run in "no stop" mode by default, + * and until C vendors implement C99's ways to control FP exceptions, + * Python requires non-stop mode. Alas, some platforms enable FP + * exceptions by default. Here we disable them. + */ #ifdef __FreeBSD__ - fp_except_t m; + fp_except_t m; - m = fpgetmask(); - fpsetmask(m & ~FP_X_OFL); + m = fpgetmask(); + fpsetmask(m & ~FP_X_OFL); #endif - if (!argv_copy || !argv_copy2) { - fprintf(stderr, "out of memory\n"); - return 1; - } - oldloc = strdup(setlocale(LC_ALL, NULL)); - setlocale(LC_ALL, ""); - for (i = 0; i < argc; i++) { - argv_copy2[i] = argv_copy[i] = char2wchar(argv[i]); - if (!argv_copy[i]) - return 1; - } - setlocale(LC_ALL, oldloc); - free(oldloc); - res = Py_Main(argc, argv_copy); - for (i = 0; i < argc; i++) { - PyMem_Free(argv_copy2[i]); - } - PyMem_Free(argv_copy); - PyMem_Free(argv_copy2); - return res; + if (!argv_copy || !argv_copy2) { + fprintf(stderr, "out of memory\n"); + return 1; + } + oldloc = strdup(setlocale(LC_ALL, NULL)); + setlocale(LC_ALL, ""); + for (i = 0; i < argc; i++) { + argv_copy2[i] = argv_copy[i] = char2wchar(argv[i]); + if (!argv_copy[i]) + return 1; + } + setlocale(LC_ALL, oldloc); + free(oldloc); + res = Py_Main(argc, argv_copy); + for (i = 0; i < argc; i++) { + PyMem_Free(argv_copy2[i]); + } + PyMem_Free(argv_copy); + PyMem_Free(argv_copy2); + return res; } #endif Modified: python/branches/release31-maint/Modules/readline.c ============================================================================== --- python/branches/release31-maint/Modules/readline.c (original) +++ python/branches/release31-maint/Modules/readline.c Sun May 9 18:14:21 2010 @@ -23,7 +23,7 @@ #ifdef SAVE_LOCALE # define RESTORE_LOCALE(sl) { setlocale(LC_CTYPE, sl); free(sl); } #else -# define RESTORE_LOCALE(sl) +# define RESTORE_LOCALE(sl) #endif /* GNU readline definitions */ @@ -33,7 +33,7 @@ #ifdef HAVE_RL_COMPLETION_MATCHES #define completion_matches(x, y) \ - rl_completion_matches((x), ((rl_compentry_func_t *)(y))) + rl_completion_matches((x), ((rl_compentry_func_t *)(y))) #else #if defined(_RL_FUNCTION_TYPEDEF) extern char **completion_matches(char *, rl_compentry_func_t *); @@ -44,7 +44,7 @@ static void on_completion_display_matches_hook(char **matches, - int num_matches, int max_length); + int num_matches, int max_length); /* Exported function to send one line to readline's init file parser */ @@ -52,18 +52,18 @@ static PyObject * parse_and_bind(PyObject *self, PyObject *args) { - char *s, *copy; - if (!PyArg_ParseTuple(args, "s:parse_and_bind", &s)) - return NULL; - /* Make a copy -- rl_parse_and_bind() modifies its argument */ - /* Bernard Herzog */ - copy = malloc(1 + strlen(s)); - if (copy == NULL) - return PyErr_NoMemory(); - strcpy(copy, s); - rl_parse_and_bind(copy); - free(copy); /* Free the copy */ - Py_RETURN_NONE; + char *s, *copy; + if (!PyArg_ParseTuple(args, "s:parse_and_bind", &s)) + return NULL; + /* Make a copy -- rl_parse_and_bind() modifies its argument */ + /* Bernard Herzog */ + copy = malloc(1 + strlen(s)); + if (copy == NULL) + return PyErr_NoMemory(); + strcpy(copy, s); + rl_parse_and_bind(copy); + free(copy); /* Free the copy */ + Py_RETURN_NONE; } PyDoc_STRVAR(doc_parse_and_bind, @@ -76,13 +76,13 @@ static PyObject * read_init_file(PyObject *self, PyObject *args) { - char *s = NULL; - if (!PyArg_ParseTuple(args, "|z:read_init_file", &s)) - return NULL; - errno = rl_read_init_file(s); - if (errno) - return PyErr_SetFromErrno(PyExc_IOError); - Py_RETURN_NONE; + char *s = NULL; + if (!PyArg_ParseTuple(args, "|z:read_init_file", &s)) + return NULL; + errno = rl_read_init_file(s); + if (errno) + return PyErr_SetFromErrno(PyExc_IOError); + Py_RETURN_NONE; } PyDoc_STRVAR(doc_read_init_file, @@ -96,13 +96,13 @@ static PyObject * read_history_file(PyObject *self, PyObject *args) { - char *s = NULL; - if (!PyArg_ParseTuple(args, "|z:read_history_file", &s)) - return NULL; - errno = read_history(s); - if (errno) - return PyErr_SetFromErrno(PyExc_IOError); - Py_RETURN_NONE; + char *s = NULL; + if (!PyArg_ParseTuple(args, "|z:read_history_file", &s)) + return NULL; + errno = read_history(s); + if (errno) + return PyErr_SetFromErrno(PyExc_IOError); + Py_RETURN_NONE; } static int _history_length = -1; /* do not truncate history by default */ @@ -117,15 +117,15 @@ static PyObject * write_history_file(PyObject *self, PyObject *args) { - char *s = NULL; - if (!PyArg_ParseTuple(args, "|z:write_history_file", &s)) - return NULL; - errno = write_history(s); - if (!errno && _history_length >= 0) - history_truncate_file(s, _history_length); - if (errno) - return PyErr_SetFromErrno(PyExc_IOError); - Py_RETURN_NONE; + char *s = NULL; + if (!PyArg_ParseTuple(args, "|z:write_history_file", &s)) + return NULL; + errno = write_history(s); + if (!errno && _history_length >= 0) + history_truncate_file(s, _history_length); + if (errno) + return PyErr_SetFromErrno(PyExc_IOError); + Py_RETURN_NONE; } PyDoc_STRVAR(doc_write_history_file, @@ -139,11 +139,11 @@ static PyObject* set_history_length(PyObject *self, PyObject *args) { - int length = _history_length; - if (!PyArg_ParseTuple(args, "i:set_history_length", &length)) - return NULL; - _history_length = length; - Py_RETURN_NONE; + int length = _history_length; + if (!PyArg_ParseTuple(args, "i:set_history_length", &length)) + return NULL; + _history_length = length; + Py_RETURN_NONE; } PyDoc_STRVAR(set_history_length_doc, @@ -158,7 +158,7 @@ static PyObject* get_history_length(PyObject *self, PyObject *noarg) { - return PyLong_FromLong(_history_length); + return PyLong_FromLong(_history_length); } PyDoc_STRVAR(get_history_length_doc, @@ -172,29 +172,29 @@ static PyObject * set_hook(const char *funcname, PyObject **hook_var, PyObject *args) { - PyObject *function = Py_None; - char buf[80]; - PyOS_snprintf(buf, sizeof(buf), "|O:set_%.50s", funcname); - if (!PyArg_ParseTuple(args, buf, &function)) - return NULL; - if (function == Py_None) { - Py_XDECREF(*hook_var); - *hook_var = NULL; - } - else if (PyCallable_Check(function)) { - PyObject *tmp = *hook_var; - Py_INCREF(function); - *hook_var = function; - Py_XDECREF(tmp); - } - else { - PyOS_snprintf(buf, sizeof(buf), - "set_%.50s(func): argument not callable", - funcname); - PyErr_SetString(PyExc_TypeError, buf); - return NULL; - } - Py_RETURN_NONE; + PyObject *function = Py_None; + char buf[80]; + PyOS_snprintf(buf, sizeof(buf), "|O:set_%.50s", funcname); + if (!PyArg_ParseTuple(args, buf, &function)) + return NULL; + if (function == Py_None) { + Py_XDECREF(*hook_var); + *hook_var = NULL; + } + else if (PyCallable_Check(function)) { + PyObject *tmp = *hook_var; + Py_INCREF(function); + *hook_var = function; + Py_XDECREF(tmp); + } + else { + PyOS_snprintf(buf, sizeof(buf), + "set_%.50s(func): argument not callable", + funcname); + PyErr_SetString(PyExc_TypeError, buf); + return NULL; + } + Py_RETURN_NONE; } @@ -210,20 +210,20 @@ static PyObject * set_completion_display_matches_hook(PyObject *self, PyObject *args) { - PyObject *result = set_hook("completion_display_matches_hook", - &completion_display_matches_hook, args); + PyObject *result = set_hook("completion_display_matches_hook", + &completion_display_matches_hook, args); #ifdef HAVE_RL_COMPLETION_DISPLAY_MATCHES_HOOK - /* We cannot set this hook globally, since it replaces the - default completion display. */ - rl_completion_display_matches_hook = - completion_display_matches_hook ? + /* We cannot set this hook globally, since it replaces the + default completion display. */ + rl_completion_display_matches_hook = + completion_display_matches_hook ? #if defined(_RL_FUNCTION_TYPEDEF) - (rl_compdisp_func_t *)on_completion_display_matches_hook : 0; + (rl_compdisp_func_t *)on_completion_display_matches_hook : 0; #else - (VFunction *)on_completion_display_matches_hook : 0; + (VFunction *)on_completion_display_matches_hook : 0; #endif #endif - return result; + return result; } @@ -237,7 +237,7 @@ static PyObject * set_startup_hook(PyObject *self, PyObject *args) { - return set_hook("startup_hook", &startup_hook, args); + return set_hook("startup_hook", &startup_hook, args); } PyDoc_STRVAR(doc_set_startup_hook, @@ -254,7 +254,7 @@ static PyObject * set_pre_input_hook(PyObject *self, PyObject *args) { - return set_hook("pre_input_hook", &pre_input_hook, args); + return set_hook("pre_input_hook", &pre_input_hook, args); } PyDoc_STRVAR(doc_set_pre_input_hook, @@ -292,8 +292,8 @@ static PyObject * get_begidx(PyObject *self, PyObject *noarg) { - Py_INCREF(begidx); - return begidx; + Py_INCREF(begidx); + return begidx; } PyDoc_STRVAR(doc_get_begidx, @@ -306,8 +306,8 @@ static PyObject * get_endidx(PyObject *self, PyObject *noarg) { - Py_INCREF(endidx); - return endidx; + Py_INCREF(endidx); + return endidx; } PyDoc_STRVAR(doc_get_endidx, @@ -320,14 +320,14 @@ static PyObject * set_completer_delims(PyObject *self, PyObject *args) { - char *break_chars; + char *break_chars; - if(!PyArg_ParseTuple(args, "s:set_completer_delims", &break_chars)) { - return NULL; - } - free((void*)rl_completer_word_break_characters); - rl_completer_word_break_characters = strdup(break_chars); - Py_RETURN_NONE; + if(!PyArg_ParseTuple(args, "s:set_completer_delims", &break_chars)) { + return NULL; + } + free((void*)rl_completer_word_break_characters); + rl_completer_word_break_characters = strdup(break_chars); + Py_RETURN_NONE; } PyDoc_STRVAR(doc_set_completer_delims, @@ -337,31 +337,31 @@ static PyObject * py_remove_history(PyObject *self, PyObject *args) { - int entry_number; - HIST_ENTRY *entry; + int entry_number; + HIST_ENTRY *entry; - if (!PyArg_ParseTuple(args, "i:remove_history", &entry_number)) - return NULL; - if (entry_number < 0) { - PyErr_SetString(PyExc_ValueError, - "History index cannot be negative"); - return NULL; - } - entry = remove_history(entry_number); - if (!entry) { - PyErr_Format(PyExc_ValueError, - "No history item at position %d", - entry_number); - return NULL; - } - /* free memory allocated for the history entry */ - if (entry->line) - free(entry->line); - if (entry->data) - free(entry->data); - free(entry); + if (!PyArg_ParseTuple(args, "i:remove_history", &entry_number)) + return NULL; + if (entry_number < 0) { + PyErr_SetString(PyExc_ValueError, + "History index cannot be negative"); + return NULL; + } + entry = remove_history(entry_number); + if (!entry) { + PyErr_Format(PyExc_ValueError, + "No history item at position %d", + entry_number); + return NULL; + } + /* free memory allocated for the history entry */ + if (entry->line) + free(entry->line); + if (entry->data) + free(entry->data); + free(entry); - Py_RETURN_NONE; + Py_RETURN_NONE; } PyDoc_STRVAR(doc_remove_history, @@ -371,34 +371,34 @@ static PyObject * py_replace_history(PyObject *self, PyObject *args) { - int entry_number; - char *line; - HIST_ENTRY *old_entry; - - if (!PyArg_ParseTuple(args, "is:replace_history", &entry_number, - &line)) { - return NULL; - } - if (entry_number < 0) { - PyErr_SetString(PyExc_ValueError, - "History index cannot be negative"); - return NULL; - } - old_entry = replace_history_entry(entry_number, line, (void *)NULL); - if (!old_entry) { - PyErr_Format(PyExc_ValueError, - "No history item at position %d", - entry_number); - return NULL; - } - /* free memory allocated for the old history entry */ - if (old_entry->line) - free(old_entry->line); - if (old_entry->data) - free(old_entry->data); - free(old_entry); + int entry_number; + char *line; + HIST_ENTRY *old_entry; + + if (!PyArg_ParseTuple(args, "is:replace_history", &entry_number, + &line)) { + return NULL; + } + if (entry_number < 0) { + PyErr_SetString(PyExc_ValueError, + "History index cannot be negative"); + return NULL; + } + old_entry = replace_history_entry(entry_number, line, (void *)NULL); + if (!old_entry) { + PyErr_Format(PyExc_ValueError, + "No history item at position %d", + entry_number); + return NULL; + } + /* free memory allocated for the old history entry */ + if (old_entry->line) + free(old_entry->line); + if (old_entry->data) + free(old_entry->data); + free(old_entry); - Py_RETURN_NONE; + Py_RETURN_NONE; } PyDoc_STRVAR(doc_replace_history, @@ -410,13 +410,13 @@ static PyObject * py_add_history(PyObject *self, PyObject *args) { - char *line; + char *line; - if(!PyArg_ParseTuple(args, "s:add_history", &line)) { - return NULL; - } - add_history(line); - Py_RETURN_NONE; + if(!PyArg_ParseTuple(args, "s:add_history", &line)) { + return NULL; + } + add_history(line); + Py_RETURN_NONE; } PyDoc_STRVAR(doc_add_history, @@ -429,7 +429,7 @@ static PyObject * get_completer_delims(PyObject *self, PyObject *noarg) { - return PyUnicode_FromString(rl_completer_word_break_characters); + return PyUnicode_FromString(rl_completer_word_break_characters); } PyDoc_STRVAR(doc_get_completer_delims, @@ -442,7 +442,7 @@ static PyObject * set_completer(PyObject *self, PyObject *args) { - return set_hook("completer", &completer, args); + return set_hook("completer", &completer, args); } PyDoc_STRVAR(doc_set_completer, @@ -456,11 +456,11 @@ static PyObject * get_completer(PyObject *self, PyObject *noargs) { - if (completer == NULL) { - Py_RETURN_NONE; - } - Py_INCREF(completer); - return completer; + if (completer == NULL) { + Py_RETURN_NONE; + } + Py_INCREF(completer); + return completer; } PyDoc_STRVAR(doc_get_completer, @@ -473,16 +473,16 @@ static PyObject * get_history_item(PyObject *self, PyObject *args) { - int idx = 0; - HIST_ENTRY *hist_ent; + int idx = 0; + HIST_ENTRY *hist_ent; - if (!PyArg_ParseTuple(args, "i:index", &idx)) - return NULL; - if ((hist_ent = history_get(idx))) - return PyUnicode_FromString(hist_ent->line); - else { - Py_RETURN_NONE; - } + if (!PyArg_ParseTuple(args, "i:index", &idx)) + return NULL; + if ((hist_ent = history_get(idx))) + return PyUnicode_FromString(hist_ent->line); + else { + Py_RETURN_NONE; + } } PyDoc_STRVAR(doc_get_history_item, @@ -495,10 +495,10 @@ static PyObject * get_current_history_length(PyObject *self, PyObject *noarg) { - HISTORY_STATE *hist_st; + HISTORY_STATE *hist_st; - hist_st = history_get_history_state(); - return PyLong_FromLong(hist_st ? (long) hist_st->length : (long) 0); + hist_st = history_get_history_state(); + return PyLong_FromLong(hist_st ? (long) hist_st->length : (long) 0); } PyDoc_STRVAR(doc_get_current_history_length, @@ -511,7 +511,7 @@ static PyObject * get_line_buffer(PyObject *self, PyObject *noarg) { - return PyUnicode_FromString(rl_line_buffer); + return PyUnicode_FromString(rl_line_buffer); } PyDoc_STRVAR(doc_get_line_buffer, @@ -526,8 +526,8 @@ static PyObject * py_clear_history(PyObject *self, PyObject *noarg) { - clear_history(); - Py_RETURN_NONE; + clear_history(); + Py_RETURN_NONE; } PyDoc_STRVAR(doc_clear_history, @@ -541,11 +541,11 @@ static PyObject * insert_text(PyObject *self, PyObject *args) { - char *s; - if (!PyArg_ParseTuple(args, "s:insert_text", &s)) - return NULL; - rl_insert_text(s); - Py_RETURN_NONE; + char *s; + if (!PyArg_ParseTuple(args, "s:insert_text", &s)) + return NULL; + rl_insert_text(s); + Py_RETURN_NONE; } PyDoc_STRVAR(doc_insert_text, @@ -558,8 +558,8 @@ static PyObject * redisplay(PyObject *self, PyObject *noarg) { - rl_redisplay(); - Py_RETURN_NONE; + rl_redisplay(); + Py_RETURN_NONE; } PyDoc_STRVAR(doc_redisplay, @@ -572,50 +572,50 @@ static struct PyMethodDef readline_methods[] = { - {"parse_and_bind", parse_and_bind, METH_VARARGS, doc_parse_and_bind}, - {"get_line_buffer", get_line_buffer, METH_NOARGS, doc_get_line_buffer}, - {"insert_text", insert_text, METH_VARARGS, doc_insert_text}, - {"redisplay", redisplay, METH_NOARGS, doc_redisplay}, - {"read_init_file", read_init_file, METH_VARARGS, doc_read_init_file}, - {"read_history_file", read_history_file, - METH_VARARGS, doc_read_history_file}, - {"write_history_file", write_history_file, - METH_VARARGS, doc_write_history_file}, - {"get_history_item", get_history_item, - METH_VARARGS, doc_get_history_item}, - {"get_current_history_length", (PyCFunction)get_current_history_length, - METH_NOARGS, doc_get_current_history_length}, - {"set_history_length", set_history_length, - METH_VARARGS, set_history_length_doc}, - {"get_history_length", get_history_length, - METH_NOARGS, get_history_length_doc}, - {"set_completer", set_completer, METH_VARARGS, doc_set_completer}, - {"get_completer", get_completer, METH_NOARGS, doc_get_completer}, - {"get_completion_type", get_completion_type, - METH_NOARGS, doc_get_completion_type}, - {"get_begidx", get_begidx, METH_NOARGS, doc_get_begidx}, - {"get_endidx", get_endidx, METH_NOARGS, doc_get_endidx}, - - {"set_completer_delims", set_completer_delims, - METH_VARARGS, doc_set_completer_delims}, - {"add_history", py_add_history, METH_VARARGS, doc_add_history}, - {"remove_history_item", py_remove_history, METH_VARARGS, doc_remove_history}, - {"replace_history_item", py_replace_history, METH_VARARGS, doc_replace_history}, - {"get_completer_delims", get_completer_delims, - METH_NOARGS, doc_get_completer_delims}, - - {"set_completion_display_matches_hook", set_completion_display_matches_hook, - METH_VARARGS, doc_set_completion_display_matches_hook}, - {"set_startup_hook", set_startup_hook, - METH_VARARGS, doc_set_startup_hook}, + {"parse_and_bind", parse_and_bind, METH_VARARGS, doc_parse_and_bind}, + {"get_line_buffer", get_line_buffer, METH_NOARGS, doc_get_line_buffer}, + {"insert_text", insert_text, METH_VARARGS, doc_insert_text}, + {"redisplay", redisplay, METH_NOARGS, doc_redisplay}, + {"read_init_file", read_init_file, METH_VARARGS, doc_read_init_file}, + {"read_history_file", read_history_file, + METH_VARARGS, doc_read_history_file}, + {"write_history_file", write_history_file, + METH_VARARGS, doc_write_history_file}, + {"get_history_item", get_history_item, + METH_VARARGS, doc_get_history_item}, + {"get_current_history_length", (PyCFunction)get_current_history_length, + METH_NOARGS, doc_get_current_history_length}, + {"set_history_length", set_history_length, + METH_VARARGS, set_history_length_doc}, + {"get_history_length", get_history_length, + METH_NOARGS, get_history_length_doc}, + {"set_completer", set_completer, METH_VARARGS, doc_set_completer}, + {"get_completer", get_completer, METH_NOARGS, doc_get_completer}, + {"get_completion_type", get_completion_type, + METH_NOARGS, doc_get_completion_type}, + {"get_begidx", get_begidx, METH_NOARGS, doc_get_begidx}, + {"get_endidx", get_endidx, METH_NOARGS, doc_get_endidx}, + + {"set_completer_delims", set_completer_delims, + METH_VARARGS, doc_set_completer_delims}, + {"add_history", py_add_history, METH_VARARGS, doc_add_history}, + {"remove_history_item", py_remove_history, METH_VARARGS, doc_remove_history}, + {"replace_history_item", py_replace_history, METH_VARARGS, doc_replace_history}, + {"get_completer_delims", get_completer_delims, + METH_NOARGS, doc_get_completer_delims}, + + {"set_completion_display_matches_hook", set_completion_display_matches_hook, + METH_VARARGS, doc_set_completion_display_matches_hook}, + {"set_startup_hook", set_startup_hook, + METH_VARARGS, doc_set_startup_hook}, #ifdef HAVE_RL_PRE_INPUT_HOOK - {"set_pre_input_hook", set_pre_input_hook, - METH_VARARGS, doc_set_pre_input_hook}, + {"set_pre_input_hook", set_pre_input_hook, + METH_VARARGS, doc_set_pre_input_hook}, #endif #ifdef HAVE_RL_COMPLETION_APPEND_CHARACTER - {"clear_history", py_clear_history, METH_NOARGS, doc_clear_history}, + {"clear_history", py_clear_history, METH_NOARGS, doc_clear_history}, #endif - {0, 0} + {0, 0} }; @@ -624,47 +624,47 @@ static int on_hook(PyObject *func) { - int result = 0; - if (func != NULL) { - PyObject *r; + int result = 0; + if (func != NULL) { + PyObject *r; #ifdef WITH_THREAD - PyGILState_STATE gilstate = PyGILState_Ensure(); + PyGILState_STATE gilstate = PyGILState_Ensure(); #endif - r = PyObject_CallFunction(func, NULL); - if (r == NULL) - goto error; - if (r == Py_None) - result = 0; - else { - result = PyLong_AsLong(r); - if (result == -1 && PyErr_Occurred()) - goto error; - } - Py_DECREF(r); - goto done; - error: - PyErr_Clear(); - Py_XDECREF(r); - done: + r = PyObject_CallFunction(func, NULL); + if (r == NULL) + goto error; + if (r == Py_None) + result = 0; + else { + result = PyLong_AsLong(r); + if (result == -1 && PyErr_Occurred()) + goto error; + } + Py_DECREF(r); + goto done; + error: + PyErr_Clear(); + Py_XDECREF(r); + done: #ifdef WITH_THREAD - PyGILState_Release(gilstate); + PyGILState_Release(gilstate); #endif - return result; - } - return result; + return result; + } + return result; } static int on_startup_hook(void) { - return on_hook(startup_hook); + return on_hook(startup_hook); } #ifdef HAVE_RL_PRE_INPUT_HOOK static int on_pre_input_hook(void) { - return on_hook(pre_input_hook); + return on_hook(pre_input_hook); } #endif @@ -673,42 +673,42 @@ static void on_completion_display_matches_hook(char **matches, - int num_matches, int max_length) + int num_matches, int max_length) { - int i; - PyObject *m=NULL, *s=NULL, *r=NULL; + int i; + PyObject *m=NULL, *s=NULL, *r=NULL; #ifdef WITH_THREAD - PyGILState_STATE gilstate = PyGILState_Ensure(); + PyGILState_STATE gilstate = PyGILState_Ensure(); #endif - m = PyList_New(num_matches); - if (m == NULL) - goto error; - for (i = 0; i < num_matches; i++) { - s = PyUnicode_FromString(matches[i+1]); - if (s == NULL) - goto error; - if (PyList_SetItem(m, i, s) == -1) - goto error; - } - r = PyObject_CallFunction(completion_display_matches_hook, - "sOi", matches[0], m, max_length); - - Py_DECREF(m); m=NULL; - - if (r == NULL || - (r != Py_None && PyLong_AsLong(r) == -1 && PyErr_Occurred())) { - goto error; - } - Py_XDECREF(r); r=NULL; - - if (0) { - error: - PyErr_Clear(); - Py_XDECREF(m); - Py_XDECREF(r); - } + m = PyList_New(num_matches); + if (m == NULL) + goto error; + for (i = 0; i < num_matches; i++) { + s = PyUnicode_FromString(matches[i+1]); + if (s == NULL) + goto error; + if (PyList_SetItem(m, i, s) == -1) + goto error; + } + r = PyObject_CallFunction(completion_display_matches_hook, + "sOi", matches[0], m, max_length); + + Py_DECREF(m); m=NULL; + + if (r == NULL || + (r != Py_None && PyLong_AsLong(r) == -1 && PyErr_Occurred())) { + goto error; + } + Py_XDECREF(r); r=NULL; + + if (0) { + error: + PyErr_Clear(); + Py_XDECREF(m); + Py_XDECREF(r); + } #ifdef WITH_THREAD - PyGILState_Release(gilstate); + PyGILState_Release(gilstate); #endif } @@ -718,37 +718,37 @@ static char * on_completion(const char *text, int state) { - char *result = NULL; - if (completer != NULL) { - PyObject *r; + char *result = NULL; + if (completer != NULL) { + PyObject *r; #ifdef WITH_THREAD - PyGILState_STATE gilstate = PyGILState_Ensure(); + PyGILState_STATE gilstate = PyGILState_Ensure(); #endif - rl_attempted_completion_over = 1; - r = PyObject_CallFunction(completer, "si", text, state); - if (r == NULL) - goto error; - if (r == Py_None) { - result = NULL; - } - else { - char *s = _PyUnicode_AsString(r); - if (s == NULL) - goto error; - result = strdup(s); - } - Py_DECREF(r); - goto done; - error: - PyErr_Clear(); - Py_XDECREF(r); - done: + rl_attempted_completion_over = 1; + r = PyObject_CallFunction(completer, "si", text, state); + if (r == NULL) + goto error; + if (r == Py_None) { + result = NULL; + } + else { + char *s = _PyUnicode_AsString(r); + if (s == NULL) + goto error; + result = strdup(s); + } + Py_DECREF(r); + goto done; + error: + PyErr_Clear(); + Py_XDECREF(r); + done: #ifdef WITH_THREAD - PyGILState_Release(gilstate); + PyGILState_Release(gilstate); #endif - return result; - } - return result; + return result; + } + return result; } @@ -759,16 +759,16 @@ flex_complete(char *text, int start, int end) { #ifdef HAVE_RL_COMPLETION_APPEND_CHARACTER - rl_completion_append_character ='\0'; + rl_completion_append_character ='\0'; #endif #ifdef HAVE_RL_COMPLETION_SUPPRESS_APPEND - rl_completion_suppress_append = 0; + rl_completion_suppress_append = 0; #endif - Py_XDECREF(begidx); - Py_XDECREF(endidx); - begidx = PyLong_FromLong((long) start); - endidx = PyLong_FromLong((long) end); - return completion_matches(text, *on_completion); + Py_XDECREF(begidx); + Py_XDECREF(endidx); + begidx = PyLong_FromLong((long) start); + endidx = PyLong_FromLong((long) end); + return completion_matches(text, *on_completion); } @@ -778,45 +778,45 @@ setup_readline(void) { #ifdef SAVE_LOCALE - char *saved_locale = strdup(setlocale(LC_CTYPE, NULL)); - if (!saved_locale) - Py_FatalError("not enough memory to save locale"); + char *saved_locale = strdup(setlocale(LC_CTYPE, NULL)); + if (!saved_locale) + Py_FatalError("not enough memory to save locale"); #endif - using_history(); + using_history(); - rl_readline_name = "python"; + rl_readline_name = "python"; #if defined(PYOS_OS2) && defined(PYCC_GCC) - /* Allow $if term= in .inputrc to work */ - rl_terminal_name = getenv("TERM"); + /* Allow $if term= in .inputrc to work */ + rl_terminal_name = getenv("TERM"); #endif - /* Force rebind of TAB to insert-tab */ - rl_bind_key('\t', rl_insert); - /* Bind both ESC-TAB and ESC-ESC to the completion function */ - rl_bind_key_in_map ('\t', rl_complete, emacs_meta_keymap); - rl_bind_key_in_map ('\033', rl_complete, emacs_meta_keymap); - /* Set our hook functions */ - rl_startup_hook = (Function *)on_startup_hook; + /* Force rebind of TAB to insert-tab */ + rl_bind_key('\t', rl_insert); + /* Bind both ESC-TAB and ESC-ESC to the completion function */ + rl_bind_key_in_map ('\t', rl_complete, emacs_meta_keymap); + rl_bind_key_in_map ('\033', rl_complete, emacs_meta_keymap); + /* Set our hook functions */ + rl_startup_hook = (Function *)on_startup_hook; #ifdef HAVE_RL_PRE_INPUT_HOOK - rl_pre_input_hook = (Function *)on_pre_input_hook; + rl_pre_input_hook = (Function *)on_pre_input_hook; #endif - /* Set our completion function */ - rl_attempted_completion_function = (CPPFunction *)flex_complete; - /* Set Python word break characters */ - rl_completer_word_break_characters = - strdup(" \t\n`~!@#$%^&*()-=+[{]}\\|;:'\",<>/?"); - /* All nonalphanums except '.' */ - - begidx = PyLong_FromLong(0L); - endidx = PyLong_FromLong(0L); - /* Initialize (allows .inputrc to override) - * - * XXX: A bug in the readline-2.2 library causes a memory leak - * inside this function. Nothing we can do about it. - */ - rl_initialize(); + /* Set our completion function */ + rl_attempted_completion_function = (CPPFunction *)flex_complete; + /* Set Python word break characters */ + rl_completer_word_break_characters = + strdup(" \t\n`~!@#$%^&*()-=+[{]}\\|;:'\",<>/?"); + /* All nonalphanums except '.' */ + + begidx = PyLong_FromLong(0L); + endidx = PyLong_FromLong(0L); + /* Initialize (allows .inputrc to override) + * + * XXX: A bug in the readline-2.2 library causes a memory leak + * inside this function. Nothing we can do about it. + */ + rl_initialize(); - RESTORE_LOCALE(saved_locale) + RESTORE_LOCALE(saved_locale) } /* Wrapper around GNU readline that handles signals differently. */ @@ -824,12 +824,12 @@ #if defined(HAVE_RL_CALLBACK) && defined(HAVE_SELECT) -static char *completed_input_string; +static char *completed_input_string; static void rlhandler(char *text) { - completed_input_string = text; - rl_callback_handler_remove(); + completed_input_string = text; + rl_callback_handler_remove(); } extern PyThreadState* _PyOS_ReadlineTState; @@ -837,60 +837,60 @@ static char * readline_until_enter_or_signal(char *prompt, int *signal) { - char * not_done_reading = ""; - fd_set selectset; + char * not_done_reading = ""; + fd_set selectset; - *signal = 0; + *signal = 0; #ifdef HAVE_RL_CATCH_SIGNAL - rl_catch_signals = 0; + rl_catch_signals = 0; #endif - rl_callback_handler_install (prompt, rlhandler); - FD_ZERO(&selectset); - - completed_input_string = not_done_reading; - - while (completed_input_string == not_done_reading) { - int has_input = 0; - - while (!has_input) - { struct timeval timeout = {0, 100000}; /* 0.1 seconds */ - - /* [Bug #1552726] Only limit the pause if an input hook has been - defined. */ - struct timeval *timeoutp = NULL; - if (PyOS_InputHook) - timeoutp = &timeout; - FD_SET(fileno(rl_instream), &selectset); - /* select resets selectset if no input was available */ - has_input = select(fileno(rl_instream) + 1, &selectset, - NULL, NULL, timeoutp); - if(PyOS_InputHook) PyOS_InputHook(); - } - - if(has_input > 0) { - rl_callback_read_char(); - } - else if (errno == EINTR) { - int s; + rl_callback_handler_install (prompt, rlhandler); + FD_ZERO(&selectset); + + completed_input_string = not_done_reading; + + while (completed_input_string == not_done_reading) { + int has_input = 0; + + while (!has_input) + { struct timeval timeout = {0, 100000}; /* 0.1 seconds */ + + /* [Bug #1552726] Only limit the pause if an input hook has been + defined. */ + struct timeval *timeoutp = NULL; + if (PyOS_InputHook) + timeoutp = &timeout; + FD_SET(fileno(rl_instream), &selectset); + /* select resets selectset if no input was available */ + has_input = select(fileno(rl_instream) + 1, &selectset, + NULL, NULL, timeoutp); + if(PyOS_InputHook) PyOS_InputHook(); + } + + if(has_input > 0) { + rl_callback_read_char(); + } + else if (errno == EINTR) { + int s; #ifdef WITH_THREAD - PyEval_RestoreThread(_PyOS_ReadlineTState); + PyEval_RestoreThread(_PyOS_ReadlineTState); #endif - s = PyErr_CheckSignals(); + s = PyErr_CheckSignals(); #ifdef WITH_THREAD - PyEval_SaveThread(); + PyEval_SaveThread(); #endif - if (s < 0) { - rl_free_line_state(); - rl_cleanup_after_signal(); - rl_callback_handler_remove(); - *signal = 1; - completed_input_string = NULL; - } - } - } + if (s < 0) { + rl_free_line_state(); + rl_cleanup_after_signal(); + rl_callback_handler_remove(); + *signal = 1; + completed_input_string = NULL; + } + } + } - return completed_input_string; + return completed_input_string; } @@ -904,31 +904,31 @@ static void onintr(int sig) { - longjmp(jbuf, 1); + longjmp(jbuf, 1); } static char * readline_until_enter_or_signal(char *prompt, int *signal) { - PyOS_sighandler_t old_inthandler; - char *p; - - *signal = 0; + PyOS_sighandler_t old_inthandler; + char *p; + + *signal = 0; - old_inthandler = PyOS_setsig(SIGINT, onintr); - if (setjmp(jbuf)) { + old_inthandler = PyOS_setsig(SIGINT, onintr); + if (setjmp(jbuf)) { #ifdef HAVE_SIGRELSE - /* This seems necessary on SunOS 4.1 (Rasmus Hahn) */ - sigrelse(SIGINT); + /* This seems necessary on SunOS 4.1 (Rasmus Hahn) */ + sigrelse(SIGINT); #endif - PyOS_setsig(SIGINT, old_inthandler); - *signal = 1; - return NULL; - } - rl_event_hook = PyOS_InputHook; - p = readline(prompt); - PyOS_setsig(SIGINT, old_inthandler); + PyOS_setsig(SIGINT, old_inthandler); + *signal = 1; + return NULL; + } + rl_event_hook = PyOS_InputHook; + p = readline(prompt); + PyOS_setsig(SIGINT, old_inthandler); return p; } @@ -938,73 +938,73 @@ static char * call_readline(FILE *sys_stdin, FILE *sys_stdout, char *prompt) { - size_t n; - char *p, *q; - int signal; + size_t n; + char *p, *q; + int signal; #ifdef SAVE_LOCALE - char *saved_locale = strdup(setlocale(LC_CTYPE, NULL)); - if (!saved_locale) - Py_FatalError("not enough memory to save locale"); - setlocale(LC_CTYPE, ""); + char *saved_locale = strdup(setlocale(LC_CTYPE, NULL)); + if (!saved_locale) + Py_FatalError("not enough memory to save locale"); + setlocale(LC_CTYPE, ""); #endif - if (sys_stdin != rl_instream || sys_stdout != rl_outstream) { - rl_instream = sys_stdin; - rl_outstream = sys_stdout; + if (sys_stdin != rl_instream || sys_stdout != rl_outstream) { + rl_instream = sys_stdin; + rl_outstream = sys_stdout; #ifdef HAVE_RL_COMPLETION_APPEND_CHARACTER - rl_prep_terminal (1); + rl_prep_terminal (1); #endif - } + } - p = readline_until_enter_or_signal(prompt, &signal); - - /* we got an interrupt signal */ - if (signal) { - RESTORE_LOCALE(saved_locale) - return NULL; - } - - /* We got an EOF, return a empty string. */ - if (p == NULL) { - p = PyMem_Malloc(1); - if (p != NULL) - *p = '\0'; - RESTORE_LOCALE(saved_locale) - return p; - } - - /* we have a valid line */ - n = strlen(p); - if (n > 0) { - char *line; - HISTORY_STATE *state = history_get_history_state(); - if (state->length > 0) - line = history_get(state->length)->line; - else - line = ""; - if (strcmp(p, line)) - add_history(p); - /* the history docs don't say so, but the address of state - changes each time history_get_history_state is called - which makes me think it's freshly malloc'd memory... - on the other hand, the address of the last line stays the - same as long as history isn't extended, so it appears to - be malloc'd but managed by the history package... */ - free(state); - } - /* Copy the malloc'ed buffer into a PyMem_Malloc'ed one and - release the original. */ - q = p; - p = PyMem_Malloc(n+2); - if (p != NULL) { - strncpy(p, q, n); - p[n] = '\n'; - p[n+1] = '\0'; - } - free(q); - RESTORE_LOCALE(saved_locale) - return p; + p = readline_until_enter_or_signal(prompt, &signal); + + /* we got an interrupt signal */ + if (signal) { + RESTORE_LOCALE(saved_locale) + return NULL; + } + + /* We got an EOF, return a empty string. */ + if (p == NULL) { + p = PyMem_Malloc(1); + if (p != NULL) + *p = '\0'; + RESTORE_LOCALE(saved_locale) + return p; + } + + /* we have a valid line */ + n = strlen(p); + if (n > 0) { + char *line; + HISTORY_STATE *state = history_get_history_state(); + if (state->length > 0) + line = history_get(state->length)->line; + else + line = ""; + if (strcmp(p, line)) + add_history(p); + /* the history docs don't say so, but the address of state + changes each time history_get_history_state is called + which makes me think it's freshly malloc'd memory... + on the other hand, the address of the last line stays the + same as long as history isn't extended, so it appears to + be malloc'd but managed by the history package... */ + free(state); + } + /* Copy the malloc'ed buffer into a PyMem_Malloc'ed one and + release the original. */ + q = p; + p = PyMem_Malloc(n+2); + if (p != NULL) { + strncpy(p, q, n); + p[n] = '\n'; + p[n+1] = '\0'; + } + free(q); + RESTORE_LOCALE(saved_locale) + return p; } @@ -1015,27 +1015,27 @@ static struct PyModuleDef readlinemodule = { - PyModuleDef_HEAD_INIT, - "readline", - doc_module, - -1, - readline_methods, - NULL, - NULL, - NULL, - NULL + PyModuleDef_HEAD_INIT, + "readline", + doc_module, + -1, + readline_methods, + NULL, + NULL, + NULL, + NULL }; PyMODINIT_FUNC PyInit_readline(void) { - PyObject *m; + PyObject *m; - m = PyModule_Create(&readlinemodule); - if (m == NULL) - return NULL; - - PyOS_ReadlineFunctionPointer = call_readline; - setup_readline(); - return m; + m = PyModule_Create(&readlinemodule); + if (m == NULL) + return NULL; + + PyOS_ReadlineFunctionPointer = call_readline; + setup_readline(); + return m; } Modified: python/branches/release31-maint/Modules/resource.c ============================================================================== --- python/branches/release31-maint/Modules/resource.c (original) +++ python/branches/release31-maint/Modules/resource.c Sun May 9 18:14:21 2010 @@ -29,30 +29,30 @@ "or via the attributes ru_utime, ru_stime, ru_maxrss, and so on."); static PyStructSequence_Field struct_rusage_fields[] = { - {"ru_utime", "user time used"}, - {"ru_stime", "system time used"}, - {"ru_maxrss", "max. resident set size"}, - {"ru_ixrss", "shared memory size"}, - {"ru_idrss", "unshared data size"}, - {"ru_isrss", "unshared stack size"}, - {"ru_minflt", "page faults not requiring I/O"}, - {"ru_majflt", "page faults requiring I/O"}, - {"ru_nswap", "number of swap outs"}, - {"ru_inblock", "block input operations"}, - {"ru_oublock", "block output operations"}, - {"ru_msgsnd", "IPC messages sent"}, - {"ru_msgrcv", "IPC messages received"}, - {"ru_nsignals", "signals received"}, - {"ru_nvcsw", "voluntary context switches"}, - {"ru_nivcsw", "involuntary context switches"}, - {0} + {"ru_utime", "user time used"}, + {"ru_stime", "system time used"}, + {"ru_maxrss", "max. resident set size"}, + {"ru_ixrss", "shared memory size"}, + {"ru_idrss", "unshared data size"}, + {"ru_isrss", "unshared stack size"}, + {"ru_minflt", "page faults not requiring I/O"}, + {"ru_majflt", "page faults requiring I/O"}, + {"ru_nswap", "number of swap outs"}, + {"ru_inblock", "block input operations"}, + {"ru_oublock", "block output operations"}, + {"ru_msgsnd", "IPC messages sent"}, + {"ru_msgrcv", "IPC messages received"}, + {"ru_nsignals", "signals received"}, + {"ru_nvcsw", "voluntary context switches"}, + {"ru_nivcsw", "involuntary context switches"}, + {0} }; static PyStructSequence_Desc struct_rusage_desc = { - "resource.struct_rusage", /* name */ - struct_rusage__doc__, /* doc */ - struct_rusage_fields, /* fields */ - 16 /* n_in_sequence */ + "resource.struct_rusage", /* name */ + struct_rusage__doc__, /* doc */ + struct_rusage_fields, /* fields */ + 16 /* n_in_sequence */ }; static int initialized; @@ -61,151 +61,151 @@ static PyObject * resource_getrusage(PyObject *self, PyObject *args) { - int who; - struct rusage ru; - PyObject *result; - - if (!PyArg_ParseTuple(args, "i:getrusage", &who)) - return NULL; - - if (getrusage(who, &ru) == -1) { - if (errno == EINVAL) { - PyErr_SetString(PyExc_ValueError, - "invalid who parameter"); - return NULL; - } - PyErr_SetFromErrno(ResourceError); - return NULL; - } - - result = PyStructSequence_New(&StructRUsageType); - if (!result) - return NULL; - - PyStructSequence_SET_ITEM(result, 0, - PyFloat_FromDouble(doubletime(ru.ru_utime))); - PyStructSequence_SET_ITEM(result, 1, - PyFloat_FromDouble(doubletime(ru.ru_stime))); - PyStructSequence_SET_ITEM(result, 2, PyLong_FromLong(ru.ru_maxrss)); - PyStructSequence_SET_ITEM(result, 3, PyLong_FromLong(ru.ru_ixrss)); - PyStructSequence_SET_ITEM(result, 4, PyLong_FromLong(ru.ru_idrss)); - PyStructSequence_SET_ITEM(result, 5, PyLong_FromLong(ru.ru_isrss)); - PyStructSequence_SET_ITEM(result, 6, PyLong_FromLong(ru.ru_minflt)); - PyStructSequence_SET_ITEM(result, 7, PyLong_FromLong(ru.ru_majflt)); - PyStructSequence_SET_ITEM(result, 8, PyLong_FromLong(ru.ru_nswap)); - PyStructSequence_SET_ITEM(result, 9, PyLong_FromLong(ru.ru_inblock)); - PyStructSequence_SET_ITEM(result, 10, PyLong_FromLong(ru.ru_oublock)); - PyStructSequence_SET_ITEM(result, 11, PyLong_FromLong(ru.ru_msgsnd)); - PyStructSequence_SET_ITEM(result, 12, PyLong_FromLong(ru.ru_msgrcv)); - PyStructSequence_SET_ITEM(result, 13, PyLong_FromLong(ru.ru_nsignals)); - PyStructSequence_SET_ITEM(result, 14, PyLong_FromLong(ru.ru_nvcsw)); - PyStructSequence_SET_ITEM(result, 15, PyLong_FromLong(ru.ru_nivcsw)); - - if (PyErr_Occurred()) { - Py_DECREF(result); - return NULL; - } + int who; + struct rusage ru; + PyObject *result; + + if (!PyArg_ParseTuple(args, "i:getrusage", &who)) + return NULL; + + if (getrusage(who, &ru) == -1) { + if (errno == EINVAL) { + PyErr_SetString(PyExc_ValueError, + "invalid who parameter"); + return NULL; + } + PyErr_SetFromErrno(ResourceError); + return NULL; + } + + result = PyStructSequence_New(&StructRUsageType); + if (!result) + return NULL; + + PyStructSequence_SET_ITEM(result, 0, + PyFloat_FromDouble(doubletime(ru.ru_utime))); + PyStructSequence_SET_ITEM(result, 1, + PyFloat_FromDouble(doubletime(ru.ru_stime))); + PyStructSequence_SET_ITEM(result, 2, PyLong_FromLong(ru.ru_maxrss)); + PyStructSequence_SET_ITEM(result, 3, PyLong_FromLong(ru.ru_ixrss)); + PyStructSequence_SET_ITEM(result, 4, PyLong_FromLong(ru.ru_idrss)); + PyStructSequence_SET_ITEM(result, 5, PyLong_FromLong(ru.ru_isrss)); + PyStructSequence_SET_ITEM(result, 6, PyLong_FromLong(ru.ru_minflt)); + PyStructSequence_SET_ITEM(result, 7, PyLong_FromLong(ru.ru_majflt)); + PyStructSequence_SET_ITEM(result, 8, PyLong_FromLong(ru.ru_nswap)); + PyStructSequence_SET_ITEM(result, 9, PyLong_FromLong(ru.ru_inblock)); + PyStructSequence_SET_ITEM(result, 10, PyLong_FromLong(ru.ru_oublock)); + PyStructSequence_SET_ITEM(result, 11, PyLong_FromLong(ru.ru_msgsnd)); + PyStructSequence_SET_ITEM(result, 12, PyLong_FromLong(ru.ru_msgrcv)); + PyStructSequence_SET_ITEM(result, 13, PyLong_FromLong(ru.ru_nsignals)); + PyStructSequence_SET_ITEM(result, 14, PyLong_FromLong(ru.ru_nvcsw)); + PyStructSequence_SET_ITEM(result, 15, PyLong_FromLong(ru.ru_nivcsw)); + + if (PyErr_Occurred()) { + Py_DECREF(result); + return NULL; + } - return result; + return result; } static PyObject * resource_getrlimit(PyObject *self, PyObject *args) { - struct rlimit rl; - int resource; + struct rlimit rl; + int resource; - if (!PyArg_ParseTuple(args, "i:getrlimit", &resource)) - return NULL; + if (!PyArg_ParseTuple(args, "i:getrlimit", &resource)) + return NULL; - if (resource < 0 || resource >= RLIM_NLIMITS) { - PyErr_SetString(PyExc_ValueError, - "invalid resource specified"); - return NULL; - } - - if (getrlimit(resource, &rl) == -1) { - PyErr_SetFromErrno(ResourceError); - return NULL; - } + if (resource < 0 || resource >= RLIM_NLIMITS) { + PyErr_SetString(PyExc_ValueError, + "invalid resource specified"); + return NULL; + } + + if (getrlimit(resource, &rl) == -1) { + PyErr_SetFromErrno(ResourceError); + return NULL; + } #if defined(HAVE_LONG_LONG) - if (sizeof(rl.rlim_cur) > sizeof(long)) { - return Py_BuildValue("LL", - (PY_LONG_LONG) rl.rlim_cur, - (PY_LONG_LONG) rl.rlim_max); - } + if (sizeof(rl.rlim_cur) > sizeof(long)) { + return Py_BuildValue("LL", + (PY_LONG_LONG) rl.rlim_cur, + (PY_LONG_LONG) rl.rlim_max); + } #endif - return Py_BuildValue("ll", (long) rl.rlim_cur, (long) rl.rlim_max); + return Py_BuildValue("ll", (long) rl.rlim_cur, (long) rl.rlim_max); } static PyObject * resource_setrlimit(PyObject *self, PyObject *args) { - struct rlimit rl; - int resource; - PyObject *curobj, *maxobj; - - if (!PyArg_ParseTuple(args, "i(OO):setrlimit", - &resource, &curobj, &maxobj)) - return NULL; - - if (resource < 0 || resource >= RLIM_NLIMITS) { - PyErr_SetString(PyExc_ValueError, - "invalid resource specified"); - return NULL; - } + struct rlimit rl; + int resource; + PyObject *curobj, *maxobj; + + if (!PyArg_ParseTuple(args, "i(OO):setrlimit", + &resource, &curobj, &maxobj)) + return NULL; + + if (resource < 0 || resource >= RLIM_NLIMITS) { + PyErr_SetString(PyExc_ValueError, + "invalid resource specified"); + return NULL; + } #if !defined(HAVE_LARGEFILE_SUPPORT) - rl.rlim_cur = PyLong_AsLong(curobj); - if (rl.rlim_cur == (rlim_t)-1 && PyErr_Occurred()) - return NULL; - rl.rlim_max = PyLong_AsLong(maxobj); - if (rl.rlim_max == (rlim_t)-1 && PyErr_Occurred()) - return NULL; + rl.rlim_cur = PyLong_AsLong(curobj); + if (rl.rlim_cur == (rlim_t)-1 && PyErr_Occurred()) + return NULL; + rl.rlim_max = PyLong_AsLong(maxobj); + if (rl.rlim_max == (rlim_t)-1 && PyErr_Occurred()) + return NULL; #else - /* The limits are probably bigger than a long */ - rl.rlim_cur = PyLong_AsLongLong(curobj); - if (rl.rlim_cur == (rlim_t)-1 && PyErr_Occurred()) - return NULL; - rl.rlim_max = PyLong_AsLongLong(maxobj); - if (rl.rlim_max == (rlim_t)-1 && PyErr_Occurred()) - return NULL; -#endif - - rl.rlim_cur = rl.rlim_cur & RLIM_INFINITY; - rl.rlim_max = rl.rlim_max & RLIM_INFINITY; - if (setrlimit(resource, &rl) == -1) { - if (errno == EINVAL) - PyErr_SetString(PyExc_ValueError, - "current limit exceeds maximum limit"); - else if (errno == EPERM) - PyErr_SetString(PyExc_ValueError, - "not allowed to raise maximum limit"); - else - PyErr_SetFromErrno(ResourceError); - return NULL; - } - Py_INCREF(Py_None); - return Py_None; + /* The limits are probably bigger than a long */ + rl.rlim_cur = PyLong_AsLongLong(curobj); + if (rl.rlim_cur == (rlim_t)-1 && PyErr_Occurred()) + return NULL; + rl.rlim_max = PyLong_AsLongLong(maxobj); + if (rl.rlim_max == (rlim_t)-1 && PyErr_Occurred()) + return NULL; +#endif + + rl.rlim_cur = rl.rlim_cur & RLIM_INFINITY; + rl.rlim_max = rl.rlim_max & RLIM_INFINITY; + if (setrlimit(resource, &rl) == -1) { + if (errno == EINVAL) + PyErr_SetString(PyExc_ValueError, + "current limit exceeds maximum limit"); + else if (errno == EPERM) + PyErr_SetString(PyExc_ValueError, + "not allowed to raise maximum limit"); + else + PyErr_SetFromErrno(ResourceError); + return NULL; + } + Py_INCREF(Py_None); + return Py_None; } static PyObject * resource_getpagesize(PyObject *self, PyObject *unused) { - long pagesize = 0; + long pagesize = 0; #if defined(HAVE_GETPAGESIZE) - pagesize = getpagesize(); + pagesize = getpagesize(); #elif defined(HAVE_SYSCONF) #if defined(_SC_PAGE_SIZE) - pagesize = sysconf(_SC_PAGE_SIZE); + pagesize = sysconf(_SC_PAGE_SIZE); #else - /* Irix 5.3 has _SC_PAGESIZE, but not _SC_PAGE_SIZE */ - pagesize = sysconf(_SC_PAGESIZE); + /* Irix 5.3 has _SC_PAGESIZE, but not _SC_PAGE_SIZE */ + pagesize = sysconf(_SC_PAGESIZE); #endif #endif - return Py_BuildValue("i", pagesize); + return Py_BuildValue("i", pagesize); } @@ -213,11 +213,11 @@ static struct PyMethodDef resource_methods[] = { - {"getrusage", resource_getrusage, METH_VARARGS}, - {"getrlimit", resource_getrlimit, METH_VARARGS}, - {"setrlimit", resource_setrlimit, METH_VARARGS}, - {"getpagesize", resource_getpagesize, METH_NOARGS}, - {NULL, NULL} /* sentinel */ + {"getrusage", resource_getrusage, METH_VARARGS}, + {"getrlimit", resource_getrlimit, METH_VARARGS}, + {"setrlimit", resource_setrlimit, METH_VARARGS}, + {"getpagesize", resource_getpagesize, METH_NOARGS}, + {NULL, NULL} /* sentinel */ }; @@ -225,117 +225,117 @@ static struct PyModuleDef resourcemodule = { - PyModuleDef_HEAD_INIT, - "resource", - NULL, - -1, - resource_methods, - NULL, - NULL, - NULL, - NULL + PyModuleDef_HEAD_INIT, + "resource", + NULL, + -1, + resource_methods, + NULL, + NULL, + NULL, + NULL }; PyMODINIT_FUNC PyInit_resource(void) { - PyObject *m, *v; + PyObject *m, *v; - /* Create the module and add the functions */ - m = PyModule_Create(&resourcemodule); - if (m == NULL) - return NULL; - - /* Add some symbolic constants to the module */ - if (ResourceError == NULL) { - ResourceError = PyErr_NewException("resource.error", - NULL, NULL); - } - Py_INCREF(ResourceError); - PyModule_AddObject(m, "error", ResourceError); - if (!initialized) - PyStructSequence_InitType(&StructRUsageType, - &struct_rusage_desc); - Py_INCREF(&StructRUsageType); - PyModule_AddObject(m, "struct_rusage", - (PyObject*) &StructRUsageType); + /* Create the module and add the functions */ + m = PyModule_Create(&resourcemodule); + if (m == NULL) + return NULL; + + /* Add some symbolic constants to the module */ + if (ResourceError == NULL) { + ResourceError = PyErr_NewException("resource.error", + NULL, NULL); + } + Py_INCREF(ResourceError); + PyModule_AddObject(m, "error", ResourceError); + if (!initialized) + PyStructSequence_InitType(&StructRUsageType, + &struct_rusage_desc); + Py_INCREF(&StructRUsageType); + PyModule_AddObject(m, "struct_rusage", + (PyObject*) &StructRUsageType); - /* insert constants */ + /* insert constants */ #ifdef RLIMIT_CPU - PyModule_AddIntConstant(m, "RLIMIT_CPU", RLIMIT_CPU); + PyModule_AddIntConstant(m, "RLIMIT_CPU", RLIMIT_CPU); #endif #ifdef RLIMIT_FSIZE - PyModule_AddIntConstant(m, "RLIMIT_FSIZE", RLIMIT_FSIZE); + PyModule_AddIntConstant(m, "RLIMIT_FSIZE", RLIMIT_FSIZE); #endif #ifdef RLIMIT_DATA - PyModule_AddIntConstant(m, "RLIMIT_DATA", RLIMIT_DATA); + PyModule_AddIntConstant(m, "RLIMIT_DATA", RLIMIT_DATA); #endif #ifdef RLIMIT_STACK - PyModule_AddIntConstant(m, "RLIMIT_STACK", RLIMIT_STACK); + PyModule_AddIntConstant(m, "RLIMIT_STACK", RLIMIT_STACK); #endif #ifdef RLIMIT_CORE - PyModule_AddIntConstant(m, "RLIMIT_CORE", RLIMIT_CORE); + PyModule_AddIntConstant(m, "RLIMIT_CORE", RLIMIT_CORE); #endif #ifdef RLIMIT_NOFILE - PyModule_AddIntConstant(m, "RLIMIT_NOFILE", RLIMIT_NOFILE); + PyModule_AddIntConstant(m, "RLIMIT_NOFILE", RLIMIT_NOFILE); #endif #ifdef RLIMIT_OFILE - PyModule_AddIntConstant(m, "RLIMIT_OFILE", RLIMIT_OFILE); + PyModule_AddIntConstant(m, "RLIMIT_OFILE", RLIMIT_OFILE); #endif #ifdef RLIMIT_VMEM - PyModule_AddIntConstant(m, "RLIMIT_VMEM", RLIMIT_VMEM); + PyModule_AddIntConstant(m, "RLIMIT_VMEM", RLIMIT_VMEM); #endif #ifdef RLIMIT_AS - PyModule_AddIntConstant(m, "RLIMIT_AS", RLIMIT_AS); + PyModule_AddIntConstant(m, "RLIMIT_AS", RLIMIT_AS); #endif #ifdef RLIMIT_RSS - PyModule_AddIntConstant(m, "RLIMIT_RSS", RLIMIT_RSS); + PyModule_AddIntConstant(m, "RLIMIT_RSS", RLIMIT_RSS); #endif #ifdef RLIMIT_NPROC - PyModule_AddIntConstant(m, "RLIMIT_NPROC", RLIMIT_NPROC); + PyModule_AddIntConstant(m, "RLIMIT_NPROC", RLIMIT_NPROC); #endif #ifdef RLIMIT_MEMLOCK - PyModule_AddIntConstant(m, "RLIMIT_MEMLOCK", RLIMIT_MEMLOCK); + PyModule_AddIntConstant(m, "RLIMIT_MEMLOCK", RLIMIT_MEMLOCK); #endif #ifdef RLIMIT_SBSIZE - PyModule_AddIntConstant(m, "RLIMIT_SBSIZE", RLIMIT_SBSIZE); + PyModule_AddIntConstant(m, "RLIMIT_SBSIZE", RLIMIT_SBSIZE); #endif #ifdef RUSAGE_SELF - PyModule_AddIntConstant(m, "RUSAGE_SELF", RUSAGE_SELF); + PyModule_AddIntConstant(m, "RUSAGE_SELF", RUSAGE_SELF); #endif #ifdef RUSAGE_CHILDREN - PyModule_AddIntConstant(m, "RUSAGE_CHILDREN", RUSAGE_CHILDREN); + PyModule_AddIntConstant(m, "RUSAGE_CHILDREN", RUSAGE_CHILDREN); #endif #ifdef RUSAGE_BOTH - PyModule_AddIntConstant(m, "RUSAGE_BOTH", RUSAGE_BOTH); + PyModule_AddIntConstant(m, "RUSAGE_BOTH", RUSAGE_BOTH); #endif #if defined(HAVE_LONG_LONG) - if (sizeof(RLIM_INFINITY) > sizeof(long)) { - v = PyLong_FromLongLong((PY_LONG_LONG) RLIM_INFINITY); - } else -#endif - { - v = PyLong_FromLong((long) RLIM_INFINITY); - } - if (v) { - PyModule_AddObject(m, "RLIM_INFINITY", v); - } - initialized = 1; - return m; + if (sizeof(RLIM_INFINITY) > sizeof(long)) { + v = PyLong_FromLongLong((PY_LONG_LONG) RLIM_INFINITY); + } else +#endif + { + v = PyLong_FromLong((long) RLIM_INFINITY); + } + if (v) { + PyModule_AddObject(m, "RLIM_INFINITY", v); + } + initialized = 1; + return m; } Modified: python/branches/release31-maint/Modules/rotatingtree.c ============================================================================== --- python/branches/release31-maint/Modules/rotatingtree.c (original) +++ python/branches/release31-maint/Modules/rotatingtree.c Sun May 9 18:14:21 2010 @@ -14,14 +14,14 @@ static int randombits(int bits) { - int result; - if (random_stream < (1U << bits)) { - random_value *= 1082527; - random_stream = random_value; - } - result = random_stream & ((1<>= bits; - return result; + int result; + if (random_stream < (1U << bits)) { + random_value *= 1082527; + random_stream = random_value; + } + result = random_stream & ((1<>= bits; + return result; } @@ -30,15 +30,15 @@ void RotatingTree_Add(rotating_node_t **root, rotating_node_t *node) { - while (*root != NULL) { - if (KEY_LOWER_THAN(node->key, (*root)->key)) - root = &((*root)->left); - else - root = &((*root)->right); - } - node->left = NULL; - node->right = NULL; - *root = node; + while (*root != NULL) { + if (KEY_LOWER_THAN(node->key, (*root)->key)) + root = &((*root)->left); + else + root = &((*root)->right); + } + node->left = NULL; + node->right = NULL; + *root = node; } /* Locate the node with the given key. This is the most complicated @@ -47,57 +47,57 @@ rotating_node_t * RotatingTree_Get(rotating_node_t **root, void *key) { - if (randombits(3) != 4) { - /* Fast path, no rebalancing */ - rotating_node_t *node = *root; - while (node != NULL) { - if (node->key == key) - return node; - if (KEY_LOWER_THAN(key, node->key)) - node = node->left; - else - node = node->right; - } - return NULL; - } - else { - rotating_node_t **pnode = root; - rotating_node_t *node = *pnode; - rotating_node_t *next; - int rotate; - if (node == NULL) - return NULL; - while (1) { - if (node->key == key) - return node; - rotate = !randombits(1); - if (KEY_LOWER_THAN(key, node->key)) { - next = node->left; - if (next == NULL) - return NULL; - if (rotate) { - node->left = next->right; - next->right = node; - *pnode = next; - } - else - pnode = &(node->left); - } - else { - next = node->right; - if (next == NULL) - return NULL; - if (rotate) { - node->right = next->left; - next->left = node; - *pnode = next; - } - else - pnode = &(node->right); - } - node = next; - } - } + if (randombits(3) != 4) { + /* Fast path, no rebalancing */ + rotating_node_t *node = *root; + while (node != NULL) { + if (node->key == key) + return node; + if (KEY_LOWER_THAN(key, node->key)) + node = node->left; + else + node = node->right; + } + return NULL; + } + else { + rotating_node_t **pnode = root; + rotating_node_t *node = *pnode; + rotating_node_t *next; + int rotate; + if (node == NULL) + return NULL; + while (1) { + if (node->key == key) + return node; + rotate = !randombits(1); + if (KEY_LOWER_THAN(key, node->key)) { + next = node->left; + if (next == NULL) + return NULL; + if (rotate) { + node->left = next->right; + next->right = node; + *pnode = next; + } + else + pnode = &(node->left); + } + else { + next = node->right; + if (next == NULL) + return NULL; + if (rotate) { + node->right = next->left; + next->left = node; + *pnode = next; + } + else + pnode = &(node->right); + } + node = next; + } + } } /* Enumerate all nodes in the tree. The callback enumfn() should return @@ -105,17 +105,17 @@ A non-zero value is directly returned by RotatingTree_Enum(). */ int RotatingTree_Enum(rotating_node_t *root, rotating_tree_enum_fn enumfn, - void *arg) + void *arg) { - int result; - rotating_node_t *node; - while (root != NULL) { - result = RotatingTree_Enum(root->left, enumfn, arg); - if (result != 0) return result; - node = root->right; - result = enumfn(root, arg); - if (result != 0) return result; - root = node; - } - return 0; + int result; + rotating_node_t *node; + while (root != NULL) { + result = RotatingTree_Enum(root->left, enumfn, arg); + if (result != 0) return result; + node = root->right; + result = enumfn(root, arg); + if (result != 0) return result; + root = node; + } + return 0; } Modified: python/branches/release31-maint/Modules/selectmodule.c ============================================================================== --- python/branches/release31-maint/Modules/selectmodule.c (original) +++ python/branches/release31-maint/Modules/selectmodule.c Sun May 9 18:14:21 2010 @@ -22,7 +22,7 @@ */ #if defined(MS_WINDOWS) && !defined(FD_SETSIZE) #define FD_SETSIZE 512 -#endif +#endif #if defined(HAVE_POLL_H) #include @@ -58,20 +58,20 @@ /* list of Python objects and their file descriptor */ typedef struct { - PyObject *obj; /* owned reference */ - SOCKET fd; - int sentinel; /* -1 == sentinel */ + PyObject *obj; /* owned reference */ + SOCKET fd; + int sentinel; /* -1 == sentinel */ } pylist; static void reap_obj(pylist fd2obj[FD_SETSIZE + 1]) { - int i; - for (i = 0; i < FD_SETSIZE + 1 && fd2obj[i].sentinel >= 0; i++) { - Py_XDECREF(fd2obj[i].obj); - fd2obj[i].obj = NULL; - } - fd2obj[0].sentinel = -1; + int i; + for (i = 0; i < FD_SETSIZE + 1 && fd2obj[i].sentinel >= 0; i++) { + Py_XDECREF(fd2obj[i].obj); + fd2obj[i].obj = NULL; + } + fd2obj[0].sentinel = -1; } @@ -81,106 +81,106 @@ static int seq2set(PyObject *seq, fd_set *set, pylist fd2obj[FD_SETSIZE + 1]) { - int i; - int max = -1; - int index = 0; - int len = -1; - PyObject* fast_seq = NULL; - PyObject* o = NULL; - - fd2obj[0].obj = (PyObject*)0; /* set list to zero size */ - FD_ZERO(set); + int i; + int max = -1; + int index = 0; + int len = -1; + PyObject* fast_seq = NULL; + PyObject* o = NULL; + + fd2obj[0].obj = (PyObject*)0; /* set list to zero size */ + FD_ZERO(set); + + fast_seq=PySequence_Fast(seq, "arguments 1-3 must be sequences"); + if (!fast_seq) + return -1; - fast_seq=PySequence_Fast(seq, "arguments 1-3 must be sequences"); - if (!fast_seq) - return -1; + len = PySequence_Fast_GET_SIZE(fast_seq); - len = PySequence_Fast_GET_SIZE(fast_seq); + for (i = 0; i < len; i++) { + SOCKET v; - for (i = 0; i < len; i++) { - SOCKET v; + /* any intervening fileno() calls could decr this refcnt */ + if (!(o = PySequence_Fast_GET_ITEM(fast_seq, i))) + return -1; - /* any intervening fileno() calls could decr this refcnt */ - if (!(o = PySequence_Fast_GET_ITEM(fast_seq, i))) - return -1; - - Py_INCREF(o); - v = PyObject_AsFileDescriptor( o ); - if (v == -1) goto finally; + Py_INCREF(o); + v = PyObject_AsFileDescriptor( o ); + if (v == -1) goto finally; #if defined(_MSC_VER) - max = 0; /* not used for Win32 */ + max = 0; /* not used for Win32 */ #else /* !_MSC_VER */ - if (v < 0 || v >= FD_SETSIZE) { - PyErr_SetString(PyExc_ValueError, - "filedescriptor out of range in select()"); - goto finally; - } - if (v > max) - max = v; + if (v < 0 || v >= FD_SETSIZE) { + PyErr_SetString(PyExc_ValueError, + "filedescriptor out of range in select()"); + goto finally; + } + if (v > max) + max = v; #endif /* _MSC_VER */ - FD_SET(v, set); + FD_SET(v, set); - /* add object and its file descriptor to the list */ - if (index >= FD_SETSIZE) { - PyErr_SetString(PyExc_ValueError, - "too many file descriptors in select()"); - goto finally; - } - fd2obj[index].obj = o; - fd2obj[index].fd = v; - fd2obj[index].sentinel = 0; - fd2obj[++index].sentinel = -1; - } - Py_DECREF(fast_seq); - return max+1; + /* add object and its file descriptor to the list */ + if (index >= FD_SETSIZE) { + PyErr_SetString(PyExc_ValueError, + "too many file descriptors in select()"); + goto finally; + } + fd2obj[index].obj = o; + fd2obj[index].fd = v; + fd2obj[index].sentinel = 0; + fd2obj[++index].sentinel = -1; + } + Py_DECREF(fast_seq); + return max+1; finally: - Py_XDECREF(o); - Py_DECREF(fast_seq); - return -1; + Py_XDECREF(o); + Py_DECREF(fast_seq); + return -1; } /* returns NULL and sets the Python exception if an error occurred */ static PyObject * set2list(fd_set *set, pylist fd2obj[FD_SETSIZE + 1]) { - int i, j, count=0; - PyObject *list, *o; - SOCKET fd; - - for (j = 0; fd2obj[j].sentinel >= 0; j++) { - if (FD_ISSET(fd2obj[j].fd, set)) - count++; - } - list = PyList_New(count); - if (!list) - return NULL; - - i = 0; - for (j = 0; fd2obj[j].sentinel >= 0; j++) { - fd = fd2obj[j].fd; - if (FD_ISSET(fd, set)) { + int i, j, count=0; + PyObject *list, *o; + SOCKET fd; + + for (j = 0; fd2obj[j].sentinel >= 0; j++) { + if (FD_ISSET(fd2obj[j].fd, set)) + count++; + } + list = PyList_New(count); + if (!list) + return NULL; + + i = 0; + for (j = 0; fd2obj[j].sentinel >= 0; j++) { + fd = fd2obj[j].fd; + if (FD_ISSET(fd, set)) { #ifndef _MSC_VER - if (fd > FD_SETSIZE) { - PyErr_SetString(PyExc_SystemError, - "filedescriptor out of range returned in select()"); - goto finally; - } + if (fd > FD_SETSIZE) { + PyErr_SetString(PyExc_SystemError, + "filedescriptor out of range returned in select()"); + goto finally; + } #endif - o = fd2obj[j].obj; - fd2obj[j].obj = NULL; - /* transfer ownership */ - if (PyList_SetItem(list, i, o) < 0) - goto finally; - - i++; - } - } - return list; + o = fd2obj[j].obj; + fd2obj[j].obj = NULL; + /* transfer ownership */ + if (PyList_SetItem(list, i, o) < 0) + goto finally; + + i++; + } + } + return list; finally: - Py_DECREF(list); - return NULL; + Py_DECREF(list); + return NULL; } #undef SELECT_USES_HEAP @@ -192,170 +192,170 @@ select_select(PyObject *self, PyObject *args) { #ifdef SELECT_USES_HEAP - pylist *rfd2obj, *wfd2obj, *efd2obj; + pylist *rfd2obj, *wfd2obj, *efd2obj; #else /* !SELECT_USES_HEAP */ - /* XXX: All this should probably be implemented as follows: - * - find the highest descriptor we're interested in - * - add one - * - that's the size - * See: Stevens, APitUE, $12.5.1 - */ - pylist rfd2obj[FD_SETSIZE + 1]; - pylist wfd2obj[FD_SETSIZE + 1]; - pylist efd2obj[FD_SETSIZE + 1]; + /* XXX: All this should probably be implemented as follows: + * - find the highest descriptor we're interested in + * - add one + * - that's the size + * See: Stevens, APitUE, $12.5.1 + */ + pylist rfd2obj[FD_SETSIZE + 1]; + pylist wfd2obj[FD_SETSIZE + 1]; + pylist efd2obj[FD_SETSIZE + 1]; #endif /* SELECT_USES_HEAP */ - PyObject *ifdlist, *ofdlist, *efdlist; - PyObject *ret = NULL; - PyObject *tout = Py_None; - fd_set ifdset, ofdset, efdset; - double timeout; - struct timeval tv, *tvp; - long seconds; - int imax, omax, emax, max; - int n; - - /* convert arguments */ - if (!PyArg_UnpackTuple(args, "select", 3, 4, - &ifdlist, &ofdlist, &efdlist, &tout)) - return NULL; - - if (tout == Py_None) - tvp = (struct timeval *)0; - else if (!PyNumber_Check(tout)) { - PyErr_SetString(PyExc_TypeError, - "timeout must be a float or None"); - return NULL; - } - else { - timeout = PyFloat_AsDouble(tout); - if (timeout == -1 && PyErr_Occurred()) - return NULL; - if (timeout > (double)LONG_MAX) { - PyErr_SetString(PyExc_OverflowError, - "timeout period too long"); - return NULL; - } - seconds = (long)timeout; - timeout = timeout - (double)seconds; - tv.tv_sec = seconds; - tv.tv_usec = (long)(timeout * 1E6); - tvp = &tv; - } + PyObject *ifdlist, *ofdlist, *efdlist; + PyObject *ret = NULL; + PyObject *tout = Py_None; + fd_set ifdset, ofdset, efdset; + double timeout; + struct timeval tv, *tvp; + long seconds; + int imax, omax, emax, max; + int n; + + /* convert arguments */ + if (!PyArg_UnpackTuple(args, "select", 3, 4, + &ifdlist, &ofdlist, &efdlist, &tout)) + return NULL; + + if (tout == Py_None) + tvp = (struct timeval *)0; + else if (!PyNumber_Check(tout)) { + PyErr_SetString(PyExc_TypeError, + "timeout must be a float or None"); + return NULL; + } + else { + timeout = PyFloat_AsDouble(tout); + if (timeout == -1 && PyErr_Occurred()) + return NULL; + if (timeout > (double)LONG_MAX) { + PyErr_SetString(PyExc_OverflowError, + "timeout period too long"); + return NULL; + } + seconds = (long)timeout; + timeout = timeout - (double)seconds; + tv.tv_sec = seconds; + tv.tv_usec = (long)(timeout * 1E6); + tvp = &tv; + } #ifdef SELECT_USES_HEAP - /* Allocate memory for the lists */ - rfd2obj = PyMem_NEW(pylist, FD_SETSIZE + 1); - wfd2obj = PyMem_NEW(pylist, FD_SETSIZE + 1); - efd2obj = PyMem_NEW(pylist, FD_SETSIZE + 1); - if (rfd2obj == NULL || wfd2obj == NULL || efd2obj == NULL) { - if (rfd2obj) PyMem_DEL(rfd2obj); - if (wfd2obj) PyMem_DEL(wfd2obj); - if (efd2obj) PyMem_DEL(efd2obj); - return PyErr_NoMemory(); - } + /* Allocate memory for the lists */ + rfd2obj = PyMem_NEW(pylist, FD_SETSIZE + 1); + wfd2obj = PyMem_NEW(pylist, FD_SETSIZE + 1); + efd2obj = PyMem_NEW(pylist, FD_SETSIZE + 1); + if (rfd2obj == NULL || wfd2obj == NULL || efd2obj == NULL) { + if (rfd2obj) PyMem_DEL(rfd2obj); + if (wfd2obj) PyMem_DEL(wfd2obj); + if (efd2obj) PyMem_DEL(efd2obj); + return PyErr_NoMemory(); + } #endif /* SELECT_USES_HEAP */ - /* Convert sequences to fd_sets, and get maximum fd number - * propagates the Python exception set in seq2set() - */ - rfd2obj[0].sentinel = -1; - wfd2obj[0].sentinel = -1; - efd2obj[0].sentinel = -1; - if ((imax=seq2set(ifdlist, &ifdset, rfd2obj)) < 0) - goto finally; - if ((omax=seq2set(ofdlist, &ofdset, wfd2obj)) < 0) - goto finally; - if ((emax=seq2set(efdlist, &efdset, efd2obj)) < 0) - goto finally; - max = imax; - if (omax > max) max = omax; - if (emax > max) max = emax; - - Py_BEGIN_ALLOW_THREADS - n = select(max, &ifdset, &ofdset, &efdset, tvp); - Py_END_ALLOW_THREADS + /* Convert sequences to fd_sets, and get maximum fd number + * propagates the Python exception set in seq2set() + */ + rfd2obj[0].sentinel = -1; + wfd2obj[0].sentinel = -1; + efd2obj[0].sentinel = -1; + if ((imax=seq2set(ifdlist, &ifdset, rfd2obj)) < 0) + goto finally; + if ((omax=seq2set(ofdlist, &ofdset, wfd2obj)) < 0) + goto finally; + if ((emax=seq2set(efdlist, &efdset, efd2obj)) < 0) + goto finally; + max = imax; + if (omax > max) max = omax; + if (emax > max) max = emax; + + Py_BEGIN_ALLOW_THREADS + n = select(max, &ifdset, &ofdset, &efdset, tvp); + Py_END_ALLOW_THREADS #ifdef MS_WINDOWS - if (n == SOCKET_ERROR) { - PyErr_SetExcFromWindowsErr(SelectError, WSAGetLastError()); - } + if (n == SOCKET_ERROR) { + PyErr_SetExcFromWindowsErr(SelectError, WSAGetLastError()); + } #else - if (n < 0) { - PyErr_SetFromErrno(SelectError); - } + if (n < 0) { + PyErr_SetFromErrno(SelectError); + } #endif - else { - /* any of these three calls can raise an exception. it's more - convenient to test for this after all three calls... but - is that acceptable? - */ - ifdlist = set2list(&ifdset, rfd2obj); - ofdlist = set2list(&ofdset, wfd2obj); - efdlist = set2list(&efdset, efd2obj); - if (PyErr_Occurred()) - ret = NULL; - else - ret = PyTuple_Pack(3, ifdlist, ofdlist, efdlist); - - Py_DECREF(ifdlist); - Py_DECREF(ofdlist); - Py_DECREF(efdlist); - } - + else { + /* any of these three calls can raise an exception. it's more + convenient to test for this after all three calls... but + is that acceptable? + */ + ifdlist = set2list(&ifdset, rfd2obj); + ofdlist = set2list(&ofdset, wfd2obj); + efdlist = set2list(&efdset, efd2obj); + if (PyErr_Occurred()) + ret = NULL; + else + ret = PyTuple_Pack(3, ifdlist, ofdlist, efdlist); + + Py_DECREF(ifdlist); + Py_DECREF(ofdlist); + Py_DECREF(efdlist); + } + finally: - reap_obj(rfd2obj); - reap_obj(wfd2obj); - reap_obj(efd2obj); + reap_obj(rfd2obj); + reap_obj(wfd2obj); + reap_obj(efd2obj); #ifdef SELECT_USES_HEAP - PyMem_DEL(rfd2obj); - PyMem_DEL(wfd2obj); - PyMem_DEL(efd2obj); + PyMem_DEL(rfd2obj); + PyMem_DEL(wfd2obj); + PyMem_DEL(efd2obj); #endif /* SELECT_USES_HEAP */ - return ret; + return ret; } #if defined(HAVE_POLL) && !defined(HAVE_BROKEN_POLL) -/* +/* * poll() support */ typedef struct { - PyObject_HEAD - PyObject *dict; - int ufd_uptodate; - int ufd_len; - struct pollfd *ufds; + PyObject_HEAD + PyObject *dict; + int ufd_uptodate; + int ufd_len; + struct pollfd *ufds; } pollObject; static PyTypeObject poll_Type; -/* Update the malloc'ed array of pollfds to match the dictionary +/* Update the malloc'ed array of pollfds to match the dictionary contained within a pollObject. Return 1 on success, 0 on an error. */ static int update_ufd_array(pollObject *self) { - Py_ssize_t i, pos; - PyObject *key, *value; - struct pollfd *old_ufds = self->ufds; - - self->ufd_len = PyDict_Size(self->dict); - PyMem_RESIZE(self->ufds, struct pollfd, self->ufd_len); - if (self->ufds == NULL) { - self->ufds = old_ufds; - PyErr_NoMemory(); - return 0; - } - - i = pos = 0; - while (PyDict_Next(self->dict, &pos, &key, &value)) { - self->ufds[i].fd = PyLong_AsLong(key); - self->ufds[i].events = (short)PyLong_AsLong(value); - i++; - } - self->ufd_uptodate = 1; - return 1; + Py_ssize_t i, pos; + PyObject *key, *value; + struct pollfd *old_ufds = self->ufds; + + self->ufd_len = PyDict_Size(self->dict); + PyMem_RESIZE(self->ufds, struct pollfd, self->ufd_len); + if (self->ufds == NULL) { + self->ufds = old_ufds; + PyErr_NoMemory(); + return 0; + } + + i = pos = 0; + while (PyDict_Next(self->dict, &pos, &key, &value)) { + self->ufds[i].fd = PyLong_AsLong(key); + self->ufds[i].events = (short)PyLong_AsLong(value); + i++; + } + self->ufd_uptodate = 1; + return 1; } PyDoc_STRVAR(poll_register_doc, @@ -366,39 +366,39 @@ events -- an optional bitmask describing the type of events to check for"); static PyObject * -poll_register(pollObject *self, PyObject *args) +poll_register(pollObject *self, PyObject *args) { - PyObject *o, *key, *value; - int fd, events = POLLIN | POLLPRI | POLLOUT; - int err; - - if (!PyArg_ParseTuple(args, "O|i:register", &o, &events)) { - return NULL; - } - - fd = PyObject_AsFileDescriptor(o); - if (fd == -1) return NULL; - - /* Add entry to the internal dictionary: the key is the - file descriptor, and the value is the event mask. */ - key = PyLong_FromLong(fd); - if (key == NULL) - return NULL; - value = PyLong_FromLong(events); - if (value == NULL) { - Py_DECREF(key); - return NULL; - } - err = PyDict_SetItem(self->dict, key, value); - Py_DECREF(key); - Py_DECREF(value); - if (err < 0) - return NULL; + PyObject *o, *key, *value; + int fd, events = POLLIN | POLLPRI | POLLOUT; + int err; + + if (!PyArg_ParseTuple(args, "O|i:register", &o, &events)) { + return NULL; + } + + fd = PyObject_AsFileDescriptor(o); + if (fd == -1) return NULL; + + /* Add entry to the internal dictionary: the key is the + file descriptor, and the value is the event mask. */ + key = PyLong_FromLong(fd); + if (key == NULL) + return NULL; + value = PyLong_FromLong(events); + if (value == NULL) { + Py_DECREF(key); + return NULL; + } + err = PyDict_SetItem(self->dict, key, value); + Py_DECREF(key); + Py_DECREF(value); + if (err < 0) + return NULL; - self->ufd_uptodate = 0; + self->ufd_uptodate = 0; - Py_INCREF(Py_None); - return Py_None; + Py_INCREF(Py_None); + return Py_None; } PyDoc_STRVAR(poll_modify_doc, @@ -411,41 +411,41 @@ static PyObject * poll_modify(pollObject *self, PyObject *args) { - PyObject *o, *key, *value; - int fd, events; - int err; - - if (!PyArg_ParseTuple(args, "Oi:modify", &o, &events)) { - return NULL; - } - - fd = PyObject_AsFileDescriptor(o); - if (fd == -1) return NULL; - - /* Modify registered fd */ - key = PyLong_FromLong(fd); - if (key == NULL) - return NULL; - if (PyDict_GetItem(self->dict, key) == NULL) { - errno = ENOENT; - PyErr_SetFromErrno(PyExc_IOError); - return NULL; - } - value = PyLong_FromLong(events); - if (value == NULL) { - Py_DECREF(key); - return NULL; - } - err = PyDict_SetItem(self->dict, key, value); - Py_DECREF(key); - Py_DECREF(value); - if (err < 0) - return NULL; + PyObject *o, *key, *value; + int fd, events; + int err; + + if (!PyArg_ParseTuple(args, "Oi:modify", &o, &events)) { + return NULL; + } + + fd = PyObject_AsFileDescriptor(o); + if (fd == -1) return NULL; + + /* Modify registered fd */ + key = PyLong_FromLong(fd); + if (key == NULL) + return NULL; + if (PyDict_GetItem(self->dict, key) == NULL) { + errno = ENOENT; + PyErr_SetFromErrno(PyExc_IOError); + return NULL; + } + value = PyLong_FromLong(events); + if (value == NULL) { + Py_DECREF(key); + return NULL; + } + err = PyDict_SetItem(self->dict, key, value); + Py_DECREF(key); + Py_DECREF(value); + if (err < 0) + return NULL; - self->ufd_uptodate = 0; + self->ufd_uptodate = 0; - Py_INCREF(Py_None); - return Py_None; + Py_INCREF(Py_None); + return Py_None; } @@ -454,32 +454,32 @@ Remove a file descriptor being tracked by the polling object."); static PyObject * -poll_unregister(pollObject *self, PyObject *o) +poll_unregister(pollObject *self, PyObject *o) { - PyObject *key; - int fd; + PyObject *key; + int fd; - fd = PyObject_AsFileDescriptor( o ); - if (fd == -1) - return NULL; - - /* Check whether the fd is already in the array */ - key = PyLong_FromLong(fd); - if (key == NULL) - return NULL; - - if (PyDict_DelItem(self->dict, key) == -1) { - Py_DECREF(key); - /* This will simply raise the KeyError set by PyDict_DelItem - if the file descriptor isn't registered. */ - return NULL; - } + fd = PyObject_AsFileDescriptor( o ); + if (fd == -1) + return NULL; + + /* Check whether the fd is already in the array */ + key = PyLong_FromLong(fd); + if (key == NULL) + return NULL; + + if (PyDict_DelItem(self->dict, key) == -1) { + Py_DECREF(key); + /* This will simply raise the KeyError set by PyDict_DelItem + if the file descriptor isn't registered. */ + return NULL; + } - Py_DECREF(key); - self->ufd_uptodate = 0; + Py_DECREF(key); + self->ufd_uptodate = 0; - Py_INCREF(Py_None); - return Py_None; + Py_INCREF(Py_None); + return Py_None; } PyDoc_STRVAR(poll_poll_doc, @@ -488,169 +488,169 @@ any descriptors that have events or errors to report."); static PyObject * -poll_poll(pollObject *self, PyObject *args) +poll_poll(pollObject *self, PyObject *args) { - PyObject *result_list = NULL, *tout = NULL; - int timeout = 0, poll_result, i, j; - PyObject *value = NULL, *num = NULL; - - if (!PyArg_UnpackTuple(args, "poll", 0, 1, &tout)) { - return NULL; - } - - /* Check values for timeout */ - if (tout == NULL || tout == Py_None) - timeout = -1; - else if (!PyNumber_Check(tout)) { - PyErr_SetString(PyExc_TypeError, - "timeout must be an integer or None"); - return NULL; - } - else { - tout = PyNumber_Long(tout); - if (!tout) - return NULL; - timeout = PyLong_AsLong(tout); - Py_DECREF(tout); - if (timeout == -1 && PyErr_Occurred()) - return NULL; - } - - /* Ensure the ufd array is up to date */ - if (!self->ufd_uptodate) - if (update_ufd_array(self) == 0) - return NULL; - - /* call poll() */ - Py_BEGIN_ALLOW_THREADS - poll_result = poll(self->ufds, self->ufd_len, timeout); - Py_END_ALLOW_THREADS - - if (poll_result < 0) { - PyErr_SetFromErrno(SelectError); - return NULL; - } - - /* build the result list */ - - result_list = PyList_New(poll_result); - if (!result_list) - return NULL; - else { - for (i = 0, j = 0; j < poll_result; j++) { - /* skip to the next fired descriptor */ - while (!self->ufds[i].revents) { - i++; - } - /* if we hit a NULL return, set value to NULL - and break out of loop; code at end will - clean up result_list */ - value = PyTuple_New(2); - if (value == NULL) - goto error; - num = PyLong_FromLong(self->ufds[i].fd); - if (num == NULL) { - Py_DECREF(value); - goto error; - } - PyTuple_SET_ITEM(value, 0, num); - - /* The &0xffff is a workaround for AIX. 'revents' - is a 16-bit short, and IBM assigned POLLNVAL - to be 0x8000, so the conversion to int results - in a negative number. See SF bug #923315. */ - num = PyLong_FromLong(self->ufds[i].revents & 0xffff); - if (num == NULL) { - Py_DECREF(value); - goto error; - } - PyTuple_SET_ITEM(value, 1, num); - if ((PyList_SetItem(result_list, j, value)) == -1) { - Py_DECREF(value); - goto error; - } - i++; - } - } - return result_list; + PyObject *result_list = NULL, *tout = NULL; + int timeout = 0, poll_result, i, j; + PyObject *value = NULL, *num = NULL; + + if (!PyArg_UnpackTuple(args, "poll", 0, 1, &tout)) { + return NULL; + } + + /* Check values for timeout */ + if (tout == NULL || tout == Py_None) + timeout = -1; + else if (!PyNumber_Check(tout)) { + PyErr_SetString(PyExc_TypeError, + "timeout must be an integer or None"); + return NULL; + } + else { + tout = PyNumber_Long(tout); + if (!tout) + return NULL; + timeout = PyLong_AsLong(tout); + Py_DECREF(tout); + if (timeout == -1 && PyErr_Occurred()) + return NULL; + } + + /* Ensure the ufd array is up to date */ + if (!self->ufd_uptodate) + if (update_ufd_array(self) == 0) + return NULL; + + /* call poll() */ + Py_BEGIN_ALLOW_THREADS + poll_result = poll(self->ufds, self->ufd_len, timeout); + Py_END_ALLOW_THREADS + + if (poll_result < 0) { + PyErr_SetFromErrno(SelectError); + return NULL; + } + + /* build the result list */ + + result_list = PyList_New(poll_result); + if (!result_list) + return NULL; + else { + for (i = 0, j = 0; j < poll_result; j++) { + /* skip to the next fired descriptor */ + while (!self->ufds[i].revents) { + i++; + } + /* if we hit a NULL return, set value to NULL + and break out of loop; code at end will + clean up result_list */ + value = PyTuple_New(2); + if (value == NULL) + goto error; + num = PyLong_FromLong(self->ufds[i].fd); + if (num == NULL) { + Py_DECREF(value); + goto error; + } + PyTuple_SET_ITEM(value, 0, num); + + /* The &0xffff is a workaround for AIX. 'revents' + is a 16-bit short, and IBM assigned POLLNVAL + to be 0x8000, so the conversion to int results + in a negative number. See SF bug #923315. */ + num = PyLong_FromLong(self->ufds[i].revents & 0xffff); + if (num == NULL) { + Py_DECREF(value); + goto error; + } + PyTuple_SET_ITEM(value, 1, num); + if ((PyList_SetItem(result_list, j, value)) == -1) { + Py_DECREF(value); + goto error; + } + i++; + } + } + return result_list; error: - Py_DECREF(result_list); - return NULL; + Py_DECREF(result_list); + return NULL; } static PyMethodDef poll_methods[] = { - {"register", (PyCFunction)poll_register, - METH_VARARGS, poll_register_doc}, - {"modify", (PyCFunction)poll_modify, - METH_VARARGS, poll_modify_doc}, - {"unregister", (PyCFunction)poll_unregister, - METH_O, poll_unregister_doc}, - {"poll", (PyCFunction)poll_poll, - METH_VARARGS, poll_poll_doc}, - {NULL, NULL} /* sentinel */ + {"register", (PyCFunction)poll_register, + METH_VARARGS, poll_register_doc}, + {"modify", (PyCFunction)poll_modify, + METH_VARARGS, poll_modify_doc}, + {"unregister", (PyCFunction)poll_unregister, + METH_O, poll_unregister_doc}, + {"poll", (PyCFunction)poll_poll, + METH_VARARGS, poll_poll_doc}, + {NULL, NULL} /* sentinel */ }; static pollObject * newPollObject(void) { - pollObject *self; - self = PyObject_New(pollObject, &poll_Type); - if (self == NULL) - return NULL; - /* ufd_uptodate is a Boolean, denoting whether the - array pointed to by ufds matches the contents of the dictionary. */ - self->ufd_uptodate = 0; - self->ufds = NULL; - self->dict = PyDict_New(); - if (self->dict == NULL) { - Py_DECREF(self); - return NULL; - } - return self; + pollObject *self; + self = PyObject_New(pollObject, &poll_Type); + if (self == NULL) + return NULL; + /* ufd_uptodate is a Boolean, denoting whether the + array pointed to by ufds matches the contents of the dictionary. */ + self->ufd_uptodate = 0; + self->ufds = NULL; + self->dict = PyDict_New(); + if (self->dict == NULL) { + Py_DECREF(self); + return NULL; + } + return self; } static void poll_dealloc(pollObject *self) { - if (self->ufds != NULL) - PyMem_DEL(self->ufds); - Py_XDECREF(self->dict); - PyObject_Del(self); + if (self->ufds != NULL) + PyMem_DEL(self->ufds); + Py_XDECREF(self->dict); + PyObject_Del(self); } static PyTypeObject poll_Type = { - /* The ob_type field must be initialized in the module init function - * to be portable to Windows without using C++. */ - PyVarObject_HEAD_INIT(NULL, 0) - "select.poll", /*tp_name*/ - sizeof(pollObject), /*tp_basicsize*/ - 0, /*tp_itemsize*/ - /* methods */ - (destructor)poll_dealloc, /*tp_dealloc*/ - 0, /*tp_print*/ - 0, /*tp_getattr*/ - 0, /*tp_setattr*/ - 0, /*tp_reserved*/ - 0, /*tp_repr*/ - 0, /*tp_as_number*/ - 0, /*tp_as_sequence*/ - 0, /*tp_as_mapping*/ - 0, /*tp_hash*/ - 0, /*tp_call*/ - 0, /*tp_str*/ - 0, /*tp_getattro*/ - 0, /*tp_setattro*/ - 0, /*tp_as_buffer*/ - Py_TPFLAGS_DEFAULT, /*tp_flags*/ - 0, /*tp_doc*/ - 0, /*tp_traverse*/ - 0, /*tp_clear*/ - 0, /*tp_richcompare*/ - 0, /*tp_weaklistoffset*/ - 0, /*tp_iter*/ - 0, /*tp_iternext*/ - poll_methods, /*tp_methods*/ + /* The ob_type field must be initialized in the module init function + * to be portable to Windows without using C++. */ + PyVarObject_HEAD_INIT(NULL, 0) + "select.poll", /*tp_name*/ + sizeof(pollObject), /*tp_basicsize*/ + 0, /*tp_itemsize*/ + /* methods */ + (destructor)poll_dealloc, /*tp_dealloc*/ + 0, /*tp_print*/ + 0, /*tp_getattr*/ + 0, /*tp_setattr*/ + 0, /*tp_reserved*/ + 0, /*tp_repr*/ + 0, /*tp_as_number*/ + 0, /*tp_as_sequence*/ + 0, /*tp_as_mapping*/ + 0, /*tp_hash*/ + 0, /*tp_call*/ + 0, /*tp_str*/ + 0, /*tp_getattro*/ + 0, /*tp_setattro*/ + 0, /*tp_as_buffer*/ + Py_TPFLAGS_DEFAULT, /*tp_flags*/ + 0, /*tp_doc*/ + 0, /*tp_traverse*/ + 0, /*tp_clear*/ + 0, /*tp_richcompare*/ + 0, /*tp_weaklistoffset*/ + 0, /*tp_iter*/ + 0, /*tp_iternext*/ + poll_methods, /*tp_methods*/ }; PyDoc_STRVAR(poll_doc, @@ -660,36 +660,36 @@ static PyObject * select_poll(PyObject *self, PyObject *unused) { - return (PyObject *)newPollObject(); + return (PyObject *)newPollObject(); } #ifdef __APPLE__ -/* +/* * On some systems poll() sets errno on invalid file descriptors. We test * for this at runtime because this bug may be fixed or introduced between * OS releases. */ static int select_have_broken_poll(void) { - int poll_test; - int filedes[2]; + int poll_test; + int filedes[2]; - struct pollfd poll_struct = { 0, POLLIN|POLLPRI|POLLOUT, 0 }; + struct pollfd poll_struct = { 0, POLLIN|POLLPRI|POLLOUT, 0 }; - /* Create a file descriptor to make invalid */ - if (pipe(filedes) < 0) { - return 1; - } - poll_struct.fd = filedes[0]; - close(filedes[0]); - close(filedes[1]); - poll_test = poll(&poll_struct, 1, 0); - if (poll_test < 0) { - return 1; - } else if (poll_test == 0 && poll_struct.revents != POLLNVAL) { - return 1; - } - return 0; + /* Create a file descriptor to make invalid */ + if (pipe(filedes) < 0) { + return 1; + } + poll_struct.fd = filedes[0]; + close(filedes[0]); + close(filedes[1]); + poll_test = poll(&poll_struct, 1, 0); + if (poll_test < 0) { + return 1; + } else if (poll_test == 0 && poll_struct.revents != POLLNVAL) { + return 1; + } + return 0; } #endif /* __APPLE__ */ @@ -708,8 +708,8 @@ #endif typedef struct { - PyObject_HEAD - SOCKET epfd; /* epoll control file descriptor */ + PyObject_HEAD + SOCKET epfd; /* epoll control file descriptor */ } pyEpoll_Object; static PyTypeObject pyEpoll_Type; @@ -718,92 +718,92 @@ static PyObject * pyepoll_err_closed(void) { - PyErr_SetString(PyExc_ValueError, "I/O operation on closed epoll fd"); - return NULL; + PyErr_SetString(PyExc_ValueError, "I/O operation on closed epoll fd"); + return NULL; } static int pyepoll_internal_close(pyEpoll_Object *self) { - int save_errno = 0; - if (self->epfd >= 0) { - int epfd = self->epfd; - self->epfd = -1; - Py_BEGIN_ALLOW_THREADS - if (close(epfd) < 0) - save_errno = errno; - Py_END_ALLOW_THREADS - } - return save_errno; + int save_errno = 0; + if (self->epfd >= 0) { + int epfd = self->epfd; + self->epfd = -1; + Py_BEGIN_ALLOW_THREADS + if (close(epfd) < 0) + save_errno = errno; + Py_END_ALLOW_THREADS + } + return save_errno; } static PyObject * newPyEpoll_Object(PyTypeObject *type, int sizehint, SOCKET fd) { - pyEpoll_Object *self; - - if (sizehint == -1) { - sizehint = FD_SETSIZE-1; - } - else if (sizehint < 1) { - PyErr_Format(PyExc_ValueError, - "sizehint must be greater zero, got %d", - sizehint); - return NULL; - } - - assert(type != NULL && type->tp_alloc != NULL); - self = (pyEpoll_Object *) type->tp_alloc(type, 0); - if (self == NULL) - return NULL; - - if (fd == -1) { - Py_BEGIN_ALLOW_THREADS - self->epfd = epoll_create(sizehint); - Py_END_ALLOW_THREADS - } - else { - self->epfd = fd; - } - if (self->epfd < 0) { - Py_DECREF(self); - PyErr_SetFromErrno(PyExc_IOError); - return NULL; - } - return (PyObject *)self; + pyEpoll_Object *self; + + if (sizehint == -1) { + sizehint = FD_SETSIZE-1; + } + else if (sizehint < 1) { + PyErr_Format(PyExc_ValueError, + "sizehint must be greater zero, got %d", + sizehint); + return NULL; + } + + assert(type != NULL && type->tp_alloc != NULL); + self = (pyEpoll_Object *) type->tp_alloc(type, 0); + if (self == NULL) + return NULL; + + if (fd == -1) { + Py_BEGIN_ALLOW_THREADS + self->epfd = epoll_create(sizehint); + Py_END_ALLOW_THREADS + } + else { + self->epfd = fd; + } + if (self->epfd < 0) { + Py_DECREF(self); + PyErr_SetFromErrno(PyExc_IOError); + return NULL; + } + return (PyObject *)self; } static PyObject * pyepoll_new(PyTypeObject *type, PyObject *args, PyObject *kwds) { - int sizehint = -1; - static char *kwlist[] = {"sizehint", NULL}; + int sizehint = -1; + static char *kwlist[] = {"sizehint", NULL}; - if (!PyArg_ParseTupleAndKeywords(args, kwds, "|i:epoll", kwlist, - &sizehint)) - return NULL; + if (!PyArg_ParseTupleAndKeywords(args, kwds, "|i:epoll", kwlist, + &sizehint)) + return NULL; - return newPyEpoll_Object(type, sizehint, -1); + return newPyEpoll_Object(type, sizehint, -1); } static void pyepoll_dealloc(pyEpoll_Object *self) { - (void)pyepoll_internal_close(self); - Py_TYPE(self)->tp_free(self); + (void)pyepoll_internal_close(self); + Py_TYPE(self)->tp_free(self); } static PyObject* pyepoll_close(pyEpoll_Object *self) { - errno = pyepoll_internal_close(self); - if (errno < 0) { - PyErr_SetFromErrno(PyExc_IOError); - return NULL; - } - Py_RETURN_NONE; + errno = pyepoll_internal_close(self); + if (errno < 0) { + PyErr_SetFromErrno(PyExc_IOError); + return NULL; + } + Py_RETURN_NONE; } PyDoc_STRVAR(pyepoll_close_doc, @@ -815,18 +815,18 @@ static PyObject* pyepoll_get_closed(pyEpoll_Object *self) { - if (self->epfd < 0) - Py_RETURN_TRUE; - else - Py_RETURN_FALSE; + if (self->epfd < 0) + Py_RETURN_TRUE; + else + Py_RETURN_FALSE; } static PyObject* pyepoll_fileno(pyEpoll_Object *self) { - if (self->epfd < 0) - return pyepoll_err_closed(); - return PyLong_FromLong(self->epfd); + if (self->epfd < 0) + return pyepoll_err_closed(); + return PyLong_FromLong(self->epfd); } PyDoc_STRVAR(pyepoll_fileno_doc, @@ -837,12 +837,12 @@ static PyObject* pyepoll_fromfd(PyObject *cls, PyObject *args) { - SOCKET fd; + SOCKET fd; - if (!PyArg_ParseTuple(args, "i:fromfd", &fd)) - return NULL; + if (!PyArg_ParseTuple(args, "i:fromfd", &fd)) + return NULL; - return newPyEpoll_Object((PyTypeObject*)cls, -1, fd); + return newPyEpoll_Object((PyTypeObject*)cls, -1, fd); } PyDoc_STRVAR(pyepoll_fromfd_doc, @@ -853,65 +853,65 @@ static PyObject * pyepoll_internal_ctl(int epfd, int op, PyObject *pfd, unsigned int events) { - struct epoll_event ev; - int result; - int fd; - - if (epfd < 0) - return pyepoll_err_closed(); - - fd = PyObject_AsFileDescriptor(pfd); - if (fd == -1) { - return NULL; - } - - switch(op) { - case EPOLL_CTL_ADD: - case EPOLL_CTL_MOD: - ev.events = events; - ev.data.fd = fd; - Py_BEGIN_ALLOW_THREADS - result = epoll_ctl(epfd, op, fd, &ev); - Py_END_ALLOW_THREADS - break; - case EPOLL_CTL_DEL: - /* In kernel versions before 2.6.9, the EPOLL_CTL_DEL - * operation required a non-NULL pointer in event, even - * though this argument is ignored. */ - Py_BEGIN_ALLOW_THREADS - result = epoll_ctl(epfd, op, fd, &ev); - if (errno == EBADF) { - /* fd already closed */ - result = 0; - errno = 0; - } - Py_END_ALLOW_THREADS - break; - default: - result = -1; - errno = EINVAL; - } - - if (result < 0) { - PyErr_SetFromErrno(PyExc_IOError); - return NULL; - } - Py_RETURN_NONE; + struct epoll_event ev; + int result; + int fd; + + if (epfd < 0) + return pyepoll_err_closed(); + + fd = PyObject_AsFileDescriptor(pfd); + if (fd == -1) { + return NULL; + } + + switch(op) { + case EPOLL_CTL_ADD: + case EPOLL_CTL_MOD: + ev.events = events; + ev.data.fd = fd; + Py_BEGIN_ALLOW_THREADS + result = epoll_ctl(epfd, op, fd, &ev); + Py_END_ALLOW_THREADS + break; + case EPOLL_CTL_DEL: + /* In kernel versions before 2.6.9, the EPOLL_CTL_DEL + * operation required a non-NULL pointer in event, even + * though this argument is ignored. */ + Py_BEGIN_ALLOW_THREADS + result = epoll_ctl(epfd, op, fd, &ev); + if (errno == EBADF) { + /* fd already closed */ + result = 0; + errno = 0; + } + Py_END_ALLOW_THREADS + break; + default: + result = -1; + errno = EINVAL; + } + + if (result < 0) { + PyErr_SetFromErrno(PyExc_IOError); + return NULL; + } + Py_RETURN_NONE; } static PyObject * pyepoll_register(pyEpoll_Object *self, PyObject *args, PyObject *kwds) { - PyObject *pfd; - unsigned int events = EPOLLIN | EPOLLOUT | EPOLLPRI; - static char *kwlist[] = {"fd", "eventmask", NULL}; - - if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|I:register", kwlist, - &pfd, &events)) { - return NULL; - } + PyObject *pfd; + unsigned int events = EPOLLIN | EPOLLOUT | EPOLLPRI; + static char *kwlist[] = {"fd", "eventmask", NULL}; + + if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|I:register", kwlist, + &pfd, &events)) { + return NULL; + } - return pyepoll_internal_ctl(self->epfd, EPOLL_CTL_ADD, pfd, events); + return pyepoll_internal_ctl(self->epfd, EPOLL_CTL_ADD, pfd, events); } PyDoc_STRVAR(pyepoll_register_doc, @@ -928,16 +928,16 @@ static PyObject * pyepoll_modify(pyEpoll_Object *self, PyObject *args, PyObject *kwds) { - PyObject *pfd; - unsigned int events; - static char *kwlist[] = {"fd", "eventmask", NULL}; - - if (!PyArg_ParseTupleAndKeywords(args, kwds, "OI:modify", kwlist, - &pfd, &events)) { - return NULL; - } + PyObject *pfd; + unsigned int events; + static char *kwlist[] = {"fd", "eventmask", NULL}; + + if (!PyArg_ParseTupleAndKeywords(args, kwds, "OI:modify", kwlist, + &pfd, &events)) { + return NULL; + } - return pyepoll_internal_ctl(self->epfd, EPOLL_CTL_MOD, pfd, events); + return pyepoll_internal_ctl(self->epfd, EPOLL_CTL_MOD, pfd, events); } PyDoc_STRVAR(pyepoll_modify_doc, @@ -949,15 +949,15 @@ static PyObject * pyepoll_unregister(pyEpoll_Object *self, PyObject *args, PyObject *kwds) { - PyObject *pfd; - static char *kwlist[] = {"fd", NULL}; + PyObject *pfd; + static char *kwlist[] = {"fd", NULL}; - if (!PyArg_ParseTupleAndKeywords(args, kwds, "O:unregister", kwlist, - &pfd)) { - return NULL; - } + if (!PyArg_ParseTupleAndKeywords(args, kwds, "O:unregister", kwlist, + &pfd)) { + return NULL; + } - return pyepoll_internal_ctl(self->epfd, EPOLL_CTL_DEL, pfd, 0); + return pyepoll_internal_ctl(self->epfd, EPOLL_CTL_DEL, pfd, 0); } PyDoc_STRVAR(pyepoll_unregister_doc, @@ -968,76 +968,76 @@ static PyObject * pyepoll_poll(pyEpoll_Object *self, PyObject *args, PyObject *kwds) { - double dtimeout = -1.; - int timeout; - int maxevents = -1; - int nfds, i; - PyObject *elist = NULL, *etuple = NULL; - struct epoll_event *evs = NULL; - static char *kwlist[] = {"timeout", "maxevents", NULL}; - - if (self->epfd < 0) - return pyepoll_err_closed(); - - if (!PyArg_ParseTupleAndKeywords(args, kwds, "|di:poll", kwlist, - &dtimeout, &maxevents)) { - return NULL; - } - - if (dtimeout < 0) { - timeout = -1; - } - else if (dtimeout * 1000.0 > INT_MAX) { - PyErr_SetString(PyExc_OverflowError, - "timeout is too large"); - return NULL; - } - else { - timeout = (int)(dtimeout * 1000.0); - } - - if (maxevents == -1) { - maxevents = FD_SETSIZE-1; - } - else if (maxevents < 1) { - PyErr_Format(PyExc_ValueError, - "maxevents must be greater than 0, got %d", - maxevents); - return NULL; - } - - evs = PyMem_New(struct epoll_event, maxevents); - if (evs == NULL) { - Py_DECREF(self); - PyErr_NoMemory(); - return NULL; - } - - Py_BEGIN_ALLOW_THREADS - nfds = epoll_wait(self->epfd, evs, maxevents, timeout); - Py_END_ALLOW_THREADS - if (nfds < 0) { - PyErr_SetFromErrno(PyExc_IOError); - goto error; - } - - elist = PyList_New(nfds); - if (elist == NULL) { - goto error; - } - - for (i = 0; i < nfds; i++) { - etuple = Py_BuildValue("iI", evs[i].data.fd, evs[i].events); - if (etuple == NULL) { - Py_CLEAR(elist); - goto error; - } - PyList_SET_ITEM(elist, i, etuple); - } + double dtimeout = -1.; + int timeout; + int maxevents = -1; + int nfds, i; + PyObject *elist = NULL, *etuple = NULL; + struct epoll_event *evs = NULL; + static char *kwlist[] = {"timeout", "maxevents", NULL}; + + if (self->epfd < 0) + return pyepoll_err_closed(); + + if (!PyArg_ParseTupleAndKeywords(args, kwds, "|di:poll", kwlist, + &dtimeout, &maxevents)) { + return NULL; + } + + if (dtimeout < 0) { + timeout = -1; + } + else if (dtimeout * 1000.0 > INT_MAX) { + PyErr_SetString(PyExc_OverflowError, + "timeout is too large"); + return NULL; + } + else { + timeout = (int)(dtimeout * 1000.0); + } + + if (maxevents == -1) { + maxevents = FD_SETSIZE-1; + } + else if (maxevents < 1) { + PyErr_Format(PyExc_ValueError, + "maxevents must be greater than 0, got %d", + maxevents); + return NULL; + } + + evs = PyMem_New(struct epoll_event, maxevents); + if (evs == NULL) { + Py_DECREF(self); + PyErr_NoMemory(); + return NULL; + } + + Py_BEGIN_ALLOW_THREADS + nfds = epoll_wait(self->epfd, evs, maxevents, timeout); + Py_END_ALLOW_THREADS + if (nfds < 0) { + PyErr_SetFromErrno(PyExc_IOError); + goto error; + } + + elist = PyList_New(nfds); + if (elist == NULL) { + goto error; + } + + for (i = 0; i < nfds; i++) { + etuple = Py_BuildValue("iI", evs[i].data.fd, evs[i].events); + if (etuple == NULL) { + Py_CLEAR(elist); + goto error; + } + PyList_SET_ITEM(elist, i, etuple); + } error: - PyMem_Free(evs); - return elist; + PyMem_Free(evs); + return elist; } PyDoc_STRVAR(pyepoll_poll_doc, @@ -1048,27 +1048,27 @@ Up to maxevents are returned to the caller."); static PyMethodDef pyepoll_methods[] = { - {"fromfd", (PyCFunction)pyepoll_fromfd, - METH_VARARGS | METH_CLASS, pyepoll_fromfd_doc}, - {"close", (PyCFunction)pyepoll_close, METH_NOARGS, - pyepoll_close_doc}, - {"fileno", (PyCFunction)pyepoll_fileno, METH_NOARGS, - pyepoll_fileno_doc}, - {"modify", (PyCFunction)pyepoll_modify, - METH_VARARGS | METH_KEYWORDS, pyepoll_modify_doc}, - {"register", (PyCFunction)pyepoll_register, - METH_VARARGS | METH_KEYWORDS, pyepoll_register_doc}, - {"unregister", (PyCFunction)pyepoll_unregister, - METH_VARARGS | METH_KEYWORDS, pyepoll_unregister_doc}, - {"poll", (PyCFunction)pyepoll_poll, - METH_VARARGS | METH_KEYWORDS, pyepoll_poll_doc}, - {NULL, NULL}, + {"fromfd", (PyCFunction)pyepoll_fromfd, + METH_VARARGS | METH_CLASS, pyepoll_fromfd_doc}, + {"close", (PyCFunction)pyepoll_close, METH_NOARGS, + pyepoll_close_doc}, + {"fileno", (PyCFunction)pyepoll_fileno, METH_NOARGS, + pyepoll_fileno_doc}, + {"modify", (PyCFunction)pyepoll_modify, + METH_VARARGS | METH_KEYWORDS, pyepoll_modify_doc}, + {"register", (PyCFunction)pyepoll_register, + METH_VARARGS | METH_KEYWORDS, pyepoll_register_doc}, + {"unregister", (PyCFunction)pyepoll_unregister, + METH_VARARGS | METH_KEYWORDS, pyepoll_unregister_doc}, + {"poll", (PyCFunction)pyepoll_poll, + METH_VARARGS | METH_KEYWORDS, pyepoll_poll_doc}, + {NULL, NULL}, }; static PyGetSetDef pyepoll_getsetlist[] = { - {"closed", (getter)pyepoll_get_closed, NULL, - "True if the epoll handler is closed"}, - {0}, + {"closed", (getter)pyepoll_get_closed, NULL, + "True if the epoll handler is closed"}, + {0}, }; PyDoc_STRVAR(pyepoll_doc, @@ -1081,45 +1081,45 @@ the maximum number of monitored events."); static PyTypeObject pyEpoll_Type = { - PyVarObject_HEAD_INIT(NULL, 0) - "select.epoll", /* tp_name */ - sizeof(pyEpoll_Object), /* tp_basicsize */ - 0, /* tp_itemsize */ - (destructor)pyepoll_dealloc, /* tp_dealloc */ - 0, /* tp_print */ - 0, /* tp_getattr */ - 0, /* tp_setattr */ - 0, /* tp_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, /* tp_flags */ - pyepoll_doc, /* tp_doc */ - 0, /* tp_traverse */ - 0, /* tp_clear */ - 0, /* tp_richcompare */ - 0, /* tp_weaklistoffset */ - 0, /* tp_iter */ - 0, /* tp_iternext */ - pyepoll_methods, /* tp_methods */ - 0, /* tp_members */ - pyepoll_getsetlist, /* tp_getset */ - 0, /* tp_base */ - 0, /* tp_dict */ - 0, /* tp_descr_get */ - 0, /* tp_descr_set */ - 0, /* tp_dictoffset */ - 0, /* tp_init */ - 0, /* tp_alloc */ - pyepoll_new, /* tp_new */ - 0, /* tp_free */ + PyVarObject_HEAD_INIT(NULL, 0) + "select.epoll", /* tp_name */ + sizeof(pyEpoll_Object), /* tp_basicsize */ + 0, /* tp_itemsize */ + (destructor)pyepoll_dealloc, /* tp_dealloc */ + 0, /* tp_print */ + 0, /* tp_getattr */ + 0, /* tp_setattr */ + 0, /* tp_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, /* tp_flags */ + pyepoll_doc, /* tp_doc */ + 0, /* tp_traverse */ + 0, /* tp_clear */ + 0, /* tp_richcompare */ + 0, /* tp_weaklistoffset */ + 0, /* tp_iter */ + 0, /* tp_iternext */ + pyepoll_methods, /* tp_methods */ + 0, /* tp_members */ + pyepoll_getsetlist, /* tp_getset */ + 0, /* tp_base */ + 0, /* tp_dict */ + 0, /* tp_descr_get */ + 0, /* tp_descr_set */ + 0, /* tp_dictoffset */ + 0, /* tp_init */ + 0, /* tp_alloc */ + pyepoll_new, /* tp_new */ + 0, /* tp_free */ }; #endif /* HAVE_EPOLL */ @@ -1174,8 +1174,8 @@ udata->object mapping."); typedef struct { - PyObject_HEAD - struct kevent e; + PyObject_HEAD + struct kevent e; } kqueue_event_Object; static PyTypeObject kqueue_event_Type; @@ -1183,8 +1183,8 @@ #define kqueue_event_Check(op) (PyObject_TypeCheck((op), &kqueue_event_Type)) typedef struct { - PyObject_HEAD - SOCKET kqfd; /* kqueue control fd */ + PyObject_HEAD + SOCKET kqfd; /* kqueue control fd */ } kqueue_queue_Object; static PyTypeObject kqueue_queue_Type; @@ -1198,221 +1198,221 @@ #define KQ_OFF(x) offsetof(kqueue_event_Object, x) static struct PyMemberDef kqueue_event_members[] = { - {"ident", T_UINT, KQ_OFF(e.ident)}, - {"filter", T_SHORT, KQ_OFF(e.filter)}, - {"flags", T_USHORT, KQ_OFF(e.flags)}, - {"fflags", T_UINT, KQ_OFF(e.fflags)}, - {"data", T_INT, KQ_OFF(e.data)}, - {"udata", T_INT, KQ_OFF(e.udata)}, - {NULL} /* Sentinel */ + {"ident", T_UINT, KQ_OFF(e.ident)}, + {"filter", T_SHORT, KQ_OFF(e.filter)}, + {"flags", T_USHORT, KQ_OFF(e.flags)}, + {"fflags", T_UINT, KQ_OFF(e.fflags)}, + {"data", T_INT, KQ_OFF(e.data)}, + {"udata", T_INT, KQ_OFF(e.udata)}, + {NULL} /* Sentinel */ }; #undef KQ_OFF static PyObject * kqueue_event_repr(kqueue_event_Object *s) { - char buf[1024]; - PyOS_snprintf( - buf, sizeof(buf), - "", - (unsigned long)(s->e.ident), s->e.filter, s->e.flags, - s->e.fflags, (long)(s->e.data), s->e.udata); - return PyBytes_FromString(buf); + char buf[1024]; + PyOS_snprintf( + buf, sizeof(buf), + "", + (unsigned long)(s->e.ident), s->e.filter, s->e.flags, + s->e.fflags, (long)(s->e.data), s->e.udata); + return PyBytes_FromString(buf); } static int kqueue_event_init(kqueue_event_Object *self, PyObject *args, PyObject *kwds) { - PyObject *pfd; - static char *kwlist[] = {"ident", "filter", "flags", "fflags", - "data", "udata", NULL}; - - EV_SET(&(self->e), 0, EVFILT_READ, EV_ADD, 0, 0, 0); /* defaults */ - - if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|hhiii:kevent", kwlist, - &pfd, &(self->e.filter), &(self->e.flags), - &(self->e.fflags), &(self->e.data), &(self->e.udata))) { - return -1; - } - - self->e.ident = PyObject_AsFileDescriptor(pfd); - if (self->e.ident == -1) { - return -1; - } - return 0; + PyObject *pfd; + static char *kwlist[] = {"ident", "filter", "flags", "fflags", + "data", "udata", NULL}; + + EV_SET(&(self->e), 0, EVFILT_READ, EV_ADD, 0, 0, 0); /* defaults */ + + if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|hhiii:kevent", kwlist, + &pfd, &(self->e.filter), &(self->e.flags), + &(self->e.fflags), &(self->e.data), &(self->e.udata))) { + return -1; + } + + self->e.ident = PyObject_AsFileDescriptor(pfd); + if (self->e.ident == -1) { + return -1; + } + return 0; } static PyObject * kqueue_event_richcompare(kqueue_event_Object *s, kqueue_event_Object *o, - int op) + int op) { - int result = 0; + int result = 0; - if (!kqueue_event_Check(o)) { - if (op == Py_EQ || op == Py_NE) { - PyObject *res = op == Py_EQ ? Py_False : Py_True; - Py_INCREF(res); - return res; - } - PyErr_Format(PyExc_TypeError, - "can't compare %.200s to %.200s", - Py_TYPE(s)->tp_name, Py_TYPE(o)->tp_name); - return NULL; - } - if (((result = s->e.ident - o->e.ident) == 0) && - ((result = s->e.filter - o->e.filter) == 0) && - ((result = s->e.flags - o->e.flags) == 0) && - ((result = s->e.fflags - o->e.fflags) == 0) && - ((result = s->e.data - o->e.data) == 0) && - ((result = s->e.udata - o->e.udata) == 0) - ) { - result = 0; - } - - switch (op) { - case Py_EQ: - result = (result == 0); - break; - case Py_NE: - result = (result != 0); - break; - case Py_LE: - result = (result <= 0); - break; - case Py_GE: - result = (result >= 0); - break; - case Py_LT: - result = (result < 0); - break; - case Py_GT: - result = (result > 0); - break; - } - return PyBool_FromLong(result); + if (!kqueue_event_Check(o)) { + if (op == Py_EQ || op == Py_NE) { + PyObject *res = op == Py_EQ ? Py_False : Py_True; + Py_INCREF(res); + return res; + } + PyErr_Format(PyExc_TypeError, + "can't compare %.200s to %.200s", + Py_TYPE(s)->tp_name, Py_TYPE(o)->tp_name); + return NULL; + } + if (((result = s->e.ident - o->e.ident) == 0) && + ((result = s->e.filter - o->e.filter) == 0) && + ((result = s->e.flags - o->e.flags) == 0) && + ((result = s->e.fflags - o->e.fflags) == 0) && + ((result = s->e.data - o->e.data) == 0) && + ((result = s->e.udata - o->e.udata) == 0) + ) { + result = 0; + } + + switch (op) { + case Py_EQ: + result = (result == 0); + break; + case Py_NE: + result = (result != 0); + break; + case Py_LE: + result = (result <= 0); + break; + case Py_GE: + result = (result >= 0); + break; + case Py_LT: + result = (result < 0); + break; + case Py_GT: + result = (result > 0); + break; + } + return PyBool_FromLong(result); } static PyTypeObject kqueue_event_Type = { - PyVarObject_HEAD_INIT(NULL, 0) - "select.kevent", /* tp_name */ - sizeof(kqueue_event_Object), /* tp_basicsize */ - 0, /* tp_itemsize */ - 0, /* tp_dealloc */ - 0, /* tp_print */ - 0, /* tp_getattr */ - 0, /* tp_setattr */ - 0, /* tp_reserved */ - (reprfunc)kqueue_event_repr, /* tp_repr */ - 0, /* tp_as_number */ - 0, /* tp_as_sequence */ - 0, /* tp_as_mapping */ - 0, /* tp_hash */ - 0, /* tp_call */ - 0, /* tp_str */ - 0, /* tp_getattro */ - 0, /* tp_setattro */ - 0, /* tp_as_buffer */ - Py_TPFLAGS_DEFAULT, /* tp_flags */ - kqueue_event_doc, /* tp_doc */ - 0, /* tp_traverse */ - 0, /* tp_clear */ - (richcmpfunc)kqueue_event_richcompare, /* tp_richcompare */ - 0, /* tp_weaklistoffset */ - 0, /* tp_iter */ - 0, /* tp_iternext */ - 0, /* tp_methods */ - kqueue_event_members, /* tp_members */ - 0, /* tp_getset */ - 0, /* tp_base */ - 0, /* tp_dict */ - 0, /* tp_descr_get */ - 0, /* tp_descr_set */ - 0, /* tp_dictoffset */ - (initproc)kqueue_event_init, /* tp_init */ - 0, /* tp_alloc */ - 0, /* tp_new */ - 0, /* tp_free */ + PyVarObject_HEAD_INIT(NULL, 0) + "select.kevent", /* tp_name */ + sizeof(kqueue_event_Object), /* tp_basicsize */ + 0, /* tp_itemsize */ + 0, /* tp_dealloc */ + 0, /* tp_print */ + 0, /* tp_getattr */ + 0, /* tp_setattr */ + 0, /* tp_reserved */ + (reprfunc)kqueue_event_repr, /* tp_repr */ + 0, /* tp_as_number */ + 0, /* tp_as_sequence */ + 0, /* tp_as_mapping */ + 0, /* tp_hash */ + 0, /* tp_call */ + 0, /* tp_str */ + 0, /* tp_getattro */ + 0, /* tp_setattro */ + 0, /* tp_as_buffer */ + Py_TPFLAGS_DEFAULT, /* tp_flags */ + kqueue_event_doc, /* tp_doc */ + 0, /* tp_traverse */ + 0, /* tp_clear */ + (richcmpfunc)kqueue_event_richcompare, /* tp_richcompare */ + 0, /* tp_weaklistoffset */ + 0, /* tp_iter */ + 0, /* tp_iternext */ + 0, /* tp_methods */ + kqueue_event_members, /* tp_members */ + 0, /* tp_getset */ + 0, /* tp_base */ + 0, /* tp_dict */ + 0, /* tp_descr_get */ + 0, /* tp_descr_set */ + 0, /* tp_dictoffset */ + (initproc)kqueue_event_init, /* tp_init */ + 0, /* tp_alloc */ + 0, /* tp_new */ + 0, /* tp_free */ }; static PyObject * kqueue_queue_err_closed(void) { - PyErr_SetString(PyExc_ValueError, "I/O operation on closed kqueue fd"); - return NULL; + PyErr_SetString(PyExc_ValueError, "I/O operation on closed kqueue fd"); + return NULL; } static int kqueue_queue_internal_close(kqueue_queue_Object *self) { - int save_errno = 0; - if (self->kqfd >= 0) { - int kqfd = self->kqfd; - self->kqfd = -1; - Py_BEGIN_ALLOW_THREADS - if (close(kqfd) < 0) - save_errno = errno; - Py_END_ALLOW_THREADS - } - return save_errno; + int save_errno = 0; + if (self->kqfd >= 0) { + int kqfd = self->kqfd; + self->kqfd = -1; + Py_BEGIN_ALLOW_THREADS + if (close(kqfd) < 0) + save_errno = errno; + Py_END_ALLOW_THREADS + } + return save_errno; } static PyObject * newKqueue_Object(PyTypeObject *type, SOCKET fd) { - kqueue_queue_Object *self; - assert(type != NULL && type->tp_alloc != NULL); - self = (kqueue_queue_Object *) type->tp_alloc(type, 0); - if (self == NULL) { - return NULL; - } - - if (fd == -1) { - Py_BEGIN_ALLOW_THREADS - self->kqfd = kqueue(); - Py_END_ALLOW_THREADS - } - else { - self->kqfd = fd; - } - if (self->kqfd < 0) { - Py_DECREF(self); - PyErr_SetFromErrno(PyExc_IOError); - return NULL; - } - return (PyObject *)self; + kqueue_queue_Object *self; + assert(type != NULL && type->tp_alloc != NULL); + self = (kqueue_queue_Object *) type->tp_alloc(type, 0); + if (self == NULL) { + return NULL; + } + + if (fd == -1) { + Py_BEGIN_ALLOW_THREADS + self->kqfd = kqueue(); + Py_END_ALLOW_THREADS + } + else { + self->kqfd = fd; + } + if (self->kqfd < 0) { + Py_DECREF(self); + PyErr_SetFromErrno(PyExc_IOError); + return NULL; + } + return (PyObject *)self; } static PyObject * kqueue_queue_new(PyTypeObject *type, PyObject *args, PyObject *kwds) { - if ((args != NULL && PyObject_Size(args)) || - (kwds != NULL && PyObject_Size(kwds))) { - PyErr_SetString(PyExc_ValueError, - "select.kqueue doesn't accept arguments"); - return NULL; - } + if ((args != NULL && PyObject_Size(args)) || + (kwds != NULL && PyObject_Size(kwds))) { + PyErr_SetString(PyExc_ValueError, + "select.kqueue doesn't accept arguments"); + return NULL; + } - return newKqueue_Object(type, -1); + return newKqueue_Object(type, -1); } static void kqueue_queue_dealloc(kqueue_queue_Object *self) { - kqueue_queue_internal_close(self); - Py_TYPE(self)->tp_free(self); + kqueue_queue_internal_close(self); + Py_TYPE(self)->tp_free(self); } static PyObject* kqueue_queue_close(kqueue_queue_Object *self) { - errno = kqueue_queue_internal_close(self); - if (errno < 0) { - PyErr_SetFromErrno(PyExc_IOError); - return NULL; - } - Py_RETURN_NONE; + errno = kqueue_queue_internal_close(self); + if (errno < 0) { + PyErr_SetFromErrno(PyExc_IOError); + return NULL; + } + Py_RETURN_NONE; } PyDoc_STRVAR(kqueue_queue_close_doc, @@ -1424,18 +1424,18 @@ static PyObject* kqueue_queue_get_closed(kqueue_queue_Object *self) { - if (self->kqfd < 0) - Py_RETURN_TRUE; - else - Py_RETURN_FALSE; + if (self->kqfd < 0) + Py_RETURN_TRUE; + else + Py_RETURN_FALSE; } static PyObject* kqueue_queue_fileno(kqueue_queue_Object *self) { - if (self->kqfd < 0) - return kqueue_queue_err_closed(); - return PyLong_FromLong(self->kqfd); + if (self->kqfd < 0) + return kqueue_queue_err_closed(); + return PyLong_FromLong(self->kqfd); } PyDoc_STRVAR(kqueue_queue_fileno_doc, @@ -1446,12 +1446,12 @@ static PyObject* kqueue_queue_fromfd(PyObject *cls, PyObject *args) { - SOCKET fd; + SOCKET fd; - if (!PyArg_ParseTuple(args, "i:fromfd", &fd)) - return NULL; + if (!PyArg_ParseTuple(args, "i:fromfd", &fd)) + return NULL; - return newKqueue_Object((PyTypeObject*)cls, fd); + return newKqueue_Object((PyTypeObject*)cls, fd); } PyDoc_STRVAR(kqueue_queue_fromfd_doc, @@ -1462,146 +1462,146 @@ static PyObject * kqueue_queue_control(kqueue_queue_Object *self, PyObject *args) { - int nevents = 0; - int gotevents = 0; - int nchanges = 0; - int i = 0; - PyObject *otimeout = NULL; - PyObject *ch = NULL; - PyObject *it = NULL, *ei = NULL; - PyObject *result = NULL; - struct kevent *evl = NULL; - struct kevent *chl = NULL; - struct timespec timeoutspec; - struct timespec *ptimeoutspec; - - if (self->kqfd < 0) - return kqueue_queue_err_closed(); - - if (!PyArg_ParseTuple(args, "Oi|O:control", &ch, &nevents, &otimeout)) - return NULL; - - if (nevents < 0) { - PyErr_Format(PyExc_ValueError, - "Length of eventlist must be 0 or positive, got %d", - nevents); - return NULL; - } - - if (ch != NULL && ch != Py_None) { - it = PyObject_GetIter(ch); - if (it == NULL) { - PyErr_SetString(PyExc_TypeError, - "changelist is not iterable"); - return NULL; - } - nchanges = PyObject_Size(ch); - if (nchanges < 0) { - return NULL; - } - } - - if (otimeout == Py_None || otimeout == NULL) { - ptimeoutspec = NULL; - } - else if (PyNumber_Check(otimeout)) { - double timeout; - long seconds; - - timeout = PyFloat_AsDouble(otimeout); - if (timeout == -1 && PyErr_Occurred()) - return NULL; - if (timeout > (double)LONG_MAX) { - PyErr_SetString(PyExc_OverflowError, - "timeout period too long"); - return NULL; - } - if (timeout < 0) { - PyErr_SetString(PyExc_ValueError, - "timeout must be positive or None"); - return NULL; - } - - seconds = (long)timeout; - timeout = timeout - (double)seconds; - timeoutspec.tv_sec = seconds; - timeoutspec.tv_nsec = (long)(timeout * 1E9); - ptimeoutspec = &timeoutspec; - } - else { - PyErr_Format(PyExc_TypeError, - "timeout argument must be an number " - "or None, got %.200s", - Py_TYPE(otimeout)->tp_name); - return NULL; - } - - if (nchanges) { - chl = PyMem_New(struct kevent, nchanges); - if (chl == NULL) { - PyErr_NoMemory(); - return NULL; - } - i = 0; - while ((ei = PyIter_Next(it)) != NULL) { - if (!kqueue_event_Check(ei)) { - Py_DECREF(ei); - PyErr_SetString(PyExc_TypeError, - "changelist must be an iterable of " - "select.kevent objects"); - goto error; - } else { - chl[i++] = ((kqueue_event_Object *)ei)->e; - } - Py_DECREF(ei); - } - } - Py_CLEAR(it); - - /* event list */ - if (nevents) { - evl = PyMem_New(struct kevent, nevents); - if (evl == NULL) { - PyErr_NoMemory(); - return NULL; - } - } - - Py_BEGIN_ALLOW_THREADS - gotevents = kevent(self->kqfd, chl, nchanges, - evl, nevents, ptimeoutspec); - Py_END_ALLOW_THREADS - - if (gotevents == -1) { - PyErr_SetFromErrno(PyExc_OSError); - goto error; - } - - result = PyList_New(gotevents); - if (result == NULL) { - goto error; - } - - for (i = 0; i < gotevents; i++) { - kqueue_event_Object *ch; - - ch = PyObject_New(kqueue_event_Object, &kqueue_event_Type); - if (ch == NULL) { - goto error; - } - ch->e = evl[i]; - PyList_SET_ITEM(result, i, (PyObject *)ch); - } - PyMem_Free(chl); - PyMem_Free(evl); - return result; + int nevents = 0; + int gotevents = 0; + int nchanges = 0; + int i = 0; + PyObject *otimeout = NULL; + PyObject *ch = NULL; + PyObject *it = NULL, *ei = NULL; + PyObject *result = NULL; + struct kevent *evl = NULL; + struct kevent *chl = NULL; + struct timespec timeoutspec; + struct timespec *ptimeoutspec; + + if (self->kqfd < 0) + return kqueue_queue_err_closed(); + + if (!PyArg_ParseTuple(args, "Oi|O:control", &ch, &nevents, &otimeout)) + return NULL; + + if (nevents < 0) { + PyErr_Format(PyExc_ValueError, + "Length of eventlist must be 0 or positive, got %d", + nevents); + return NULL; + } + + if (ch != NULL && ch != Py_None) { + it = PyObject_GetIter(ch); + if (it == NULL) { + PyErr_SetString(PyExc_TypeError, + "changelist is not iterable"); + return NULL; + } + nchanges = PyObject_Size(ch); + if (nchanges < 0) { + return NULL; + } + } + + if (otimeout == Py_None || otimeout == NULL) { + ptimeoutspec = NULL; + } + else if (PyNumber_Check(otimeout)) { + double timeout; + long seconds; + + timeout = PyFloat_AsDouble(otimeout); + if (timeout == -1 && PyErr_Occurred()) + return NULL; + if (timeout > (double)LONG_MAX) { + PyErr_SetString(PyExc_OverflowError, + "timeout period too long"); + return NULL; + } + if (timeout < 0) { + PyErr_SetString(PyExc_ValueError, + "timeout must be positive or None"); + return NULL; + } + + seconds = (long)timeout; + timeout = timeout - (double)seconds; + timeoutspec.tv_sec = seconds; + timeoutspec.tv_nsec = (long)(timeout * 1E9); + ptimeoutspec = &timeoutspec; + } + else { + PyErr_Format(PyExc_TypeError, + "timeout argument must be an number " + "or None, got %.200s", + Py_TYPE(otimeout)->tp_name); + return NULL; + } + + if (nchanges) { + chl = PyMem_New(struct kevent, nchanges); + if (chl == NULL) { + PyErr_NoMemory(); + return NULL; + } + i = 0; + while ((ei = PyIter_Next(it)) != NULL) { + if (!kqueue_event_Check(ei)) { + Py_DECREF(ei); + PyErr_SetString(PyExc_TypeError, + "changelist must be an iterable of " + "select.kevent objects"); + goto error; + } else { + chl[i++] = ((kqueue_event_Object *)ei)->e; + } + Py_DECREF(ei); + } + } + Py_CLEAR(it); + + /* event list */ + if (nevents) { + evl = PyMem_New(struct kevent, nevents); + if (evl == NULL) { + PyErr_NoMemory(); + return NULL; + } + } + + Py_BEGIN_ALLOW_THREADS + gotevents = kevent(self->kqfd, chl, nchanges, + evl, nevents, ptimeoutspec); + Py_END_ALLOW_THREADS + + if (gotevents == -1) { + PyErr_SetFromErrno(PyExc_OSError); + goto error; + } + + result = PyList_New(gotevents); + if (result == NULL) { + goto error; + } + + for (i = 0; i < gotevents; i++) { + kqueue_event_Object *ch; + + ch = PyObject_New(kqueue_event_Object, &kqueue_event_Type); + if (ch == NULL) { + goto error; + } + ch->e = evl[i]; + PyList_SET_ITEM(result, i, (PyObject *)ch); + } + PyMem_Free(chl); + PyMem_Free(evl); + return result; error: - PyMem_Free(chl); - PyMem_Free(evl); - Py_XDECREF(result); - Py_XDECREF(it); - return NULL; + PyMem_Free(chl); + PyMem_Free(evl); + Py_XDECREF(result); + Py_XDECREF(it); + return NULL; } PyDoc_STRVAR(kqueue_queue_control_doc, @@ -1617,21 +1617,21 @@ static PyMethodDef kqueue_queue_methods[] = { - {"fromfd", (PyCFunction)kqueue_queue_fromfd, - METH_VARARGS | METH_CLASS, kqueue_queue_fromfd_doc}, - {"close", (PyCFunction)kqueue_queue_close, METH_NOARGS, - kqueue_queue_close_doc}, - {"fileno", (PyCFunction)kqueue_queue_fileno, METH_NOARGS, - kqueue_queue_fileno_doc}, - {"control", (PyCFunction)kqueue_queue_control, - METH_VARARGS , kqueue_queue_control_doc}, - {NULL, NULL}, + {"fromfd", (PyCFunction)kqueue_queue_fromfd, + METH_VARARGS | METH_CLASS, kqueue_queue_fromfd_doc}, + {"close", (PyCFunction)kqueue_queue_close, METH_NOARGS, + kqueue_queue_close_doc}, + {"fileno", (PyCFunction)kqueue_queue_fileno, METH_NOARGS, + kqueue_queue_fileno_doc}, + {"control", (PyCFunction)kqueue_queue_control, + METH_VARARGS , kqueue_queue_control_doc}, + {NULL, NULL}, }; static PyGetSetDef kqueue_queue_getsetlist[] = { - {"closed", (getter)kqueue_queue_get_closed, NULL, - "True if the kqueue handler is closed"}, - {0}, + {"closed", (getter)kqueue_queue_get_closed, NULL, + "True if the kqueue handler is closed"}, + {0}, }; PyDoc_STRVAR(kqueue_queue_doc, @@ -1650,45 +1650,45 @@ >>> kq.control([kevent(sock, KQ_FILTER_WRITE, KQ_EV_DELETE)], 0)"); static PyTypeObject kqueue_queue_Type = { - PyVarObject_HEAD_INIT(NULL, 0) - "select.kqueue", /* tp_name */ - sizeof(kqueue_queue_Object), /* tp_basicsize */ - 0, /* tp_itemsize */ - (destructor)kqueue_queue_dealloc, /* tp_dealloc */ - 0, /* tp_print */ - 0, /* tp_getattr */ - 0, /* tp_setattr */ - 0, /* tp_reserved */ - 0, /* tp_repr */ - 0, /* tp_as_number */ - 0, /* tp_as_sequence */ - 0, /* tp_as_mapping */ - 0, /* tp_hash */ - 0, /* tp_call */ - 0, /* tp_str */ - 0, /* tp_getattro */ - 0, /* tp_setattro */ - 0, /* tp_as_buffer */ - Py_TPFLAGS_DEFAULT, /* tp_flags */ - kqueue_queue_doc, /* tp_doc */ - 0, /* tp_traverse */ - 0, /* tp_clear */ - 0, /* tp_richcompare */ - 0, /* tp_weaklistoffset */ - 0, /* tp_iter */ - 0, /* tp_iternext */ - kqueue_queue_methods, /* tp_methods */ - 0, /* tp_members */ - kqueue_queue_getsetlist, /* tp_getset */ - 0, /* tp_base */ - 0, /* tp_dict */ - 0, /* tp_descr_get */ - 0, /* tp_descr_set */ - 0, /* tp_dictoffset */ - 0, /* tp_init */ - 0, /* tp_alloc */ - kqueue_queue_new, /* tp_new */ - 0, /* tp_free */ + PyVarObject_HEAD_INIT(NULL, 0) + "select.kqueue", /* tp_name */ + sizeof(kqueue_queue_Object), /* tp_basicsize */ + 0, /* tp_itemsize */ + (destructor)kqueue_queue_dealloc, /* tp_dealloc */ + 0, /* tp_print */ + 0, /* tp_getattr */ + 0, /* tp_setattr */ + 0, /* tp_reserved */ + 0, /* tp_repr */ + 0, /* tp_as_number */ + 0, /* tp_as_sequence */ + 0, /* tp_as_mapping */ + 0, /* tp_hash */ + 0, /* tp_call */ + 0, /* tp_str */ + 0, /* tp_getattro */ + 0, /* tp_setattro */ + 0, /* tp_as_buffer */ + Py_TPFLAGS_DEFAULT, /* tp_flags */ + kqueue_queue_doc, /* tp_doc */ + 0, /* tp_traverse */ + 0, /* tp_clear */ + 0, /* tp_richcompare */ + 0, /* tp_weaklistoffset */ + 0, /* tp_iter */ + 0, /* tp_iternext */ + kqueue_queue_methods, /* tp_methods */ + 0, /* tp_members */ + kqueue_queue_getsetlist, /* tp_getset */ + 0, /* tp_base */ + 0, /* tp_dict */ + 0, /* tp_descr_get */ + 0, /* tp_descr_set */ + 0, /* tp_dictoffset */ + 0, /* tp_init */ + 0, /* tp_alloc */ + kqueue_queue_new, /* tp_new */ + 0, /* tp_free */ }; #endif /* HAVE_KQUEUE */ @@ -1719,11 +1719,11 @@ descriptors can be used."); static PyMethodDef select_methods[] = { - {"select", select_select, METH_VARARGS, select_doc}, + {"select", select_select, METH_VARARGS, select_doc}, #ifdef HAVE_POLL - {"poll", select_poll, METH_NOARGS, poll_doc}, + {"poll", select_poll, METH_NOARGS, poll_doc}, #endif /* HAVE_POLL */ - {0, 0}, /* sentinel */ + {0, 0}, /* sentinel */ }; PyDoc_STRVAR(module_doc, @@ -1734,163 +1734,163 @@ static struct PyModuleDef selectmodule = { - PyModuleDef_HEAD_INIT, - "select", - module_doc, - -1, - select_methods, - NULL, - NULL, - NULL, - NULL + PyModuleDef_HEAD_INIT, + "select", + module_doc, + -1, + select_methods, + NULL, + NULL, + NULL, + NULL }; PyMODINIT_FUNC PyInit_select(void) { - PyObject *m; - m = PyModule_Create(&selectmodule); - if (m == NULL) - return NULL; - - SelectError = PyErr_NewException("select.error", NULL, NULL); - Py_INCREF(SelectError); - PyModule_AddObject(m, "error", SelectError); + PyObject *m; + m = PyModule_Create(&selectmodule); + if (m == NULL) + return NULL; + + SelectError = PyErr_NewException("select.error", NULL, NULL); + Py_INCREF(SelectError); + PyModule_AddObject(m, "error", SelectError); #if defined(HAVE_POLL) #ifdef __APPLE__ - if (select_have_broken_poll()) { - if (PyObject_DelAttrString(m, "poll") == -1) { - PyErr_Clear(); - } - } else { + if (select_have_broken_poll()) { + if (PyObject_DelAttrString(m, "poll") == -1) { + PyErr_Clear(); + } + } else { #else - { + { #endif - if (PyType_Ready(&poll_Type) < 0) - return NULL; - PyModule_AddIntConstant(m, "POLLIN", POLLIN); - PyModule_AddIntConstant(m, "POLLPRI", POLLPRI); - PyModule_AddIntConstant(m, "POLLOUT", POLLOUT); - PyModule_AddIntConstant(m, "POLLERR", POLLERR); - PyModule_AddIntConstant(m, "POLLHUP", POLLHUP); - PyModule_AddIntConstant(m, "POLLNVAL", POLLNVAL); + if (PyType_Ready(&poll_Type) < 0) + return NULL; + PyModule_AddIntConstant(m, "POLLIN", POLLIN); + PyModule_AddIntConstant(m, "POLLPRI", POLLPRI); + PyModule_AddIntConstant(m, "POLLOUT", POLLOUT); + PyModule_AddIntConstant(m, "POLLERR", POLLERR); + PyModule_AddIntConstant(m, "POLLHUP", POLLHUP); + PyModule_AddIntConstant(m, "POLLNVAL", POLLNVAL); #ifdef POLLRDNORM - PyModule_AddIntConstant(m, "POLLRDNORM", POLLRDNORM); + PyModule_AddIntConstant(m, "POLLRDNORM", POLLRDNORM); #endif #ifdef POLLRDBAND - PyModule_AddIntConstant(m, "POLLRDBAND", POLLRDBAND); + PyModule_AddIntConstant(m, "POLLRDBAND", POLLRDBAND); #endif #ifdef POLLWRNORM - PyModule_AddIntConstant(m, "POLLWRNORM", POLLWRNORM); + PyModule_AddIntConstant(m, "POLLWRNORM", POLLWRNORM); #endif #ifdef POLLWRBAND - PyModule_AddIntConstant(m, "POLLWRBAND", POLLWRBAND); + PyModule_AddIntConstant(m, "POLLWRBAND", POLLWRBAND); #endif #ifdef POLLMSG - PyModule_AddIntConstant(m, "POLLMSG", POLLMSG); + PyModule_AddIntConstant(m, "POLLMSG", POLLMSG); #endif - } + } #endif /* HAVE_POLL */ #ifdef HAVE_EPOLL - Py_TYPE(&pyEpoll_Type) = &PyType_Type; - if (PyType_Ready(&pyEpoll_Type) < 0) - return NULL; - - Py_INCREF(&pyEpoll_Type); - PyModule_AddObject(m, "epoll", (PyObject *) &pyEpoll_Type); - - PyModule_AddIntConstant(m, "EPOLLIN", EPOLLIN); - PyModule_AddIntConstant(m, "EPOLLOUT", EPOLLOUT); - PyModule_AddIntConstant(m, "EPOLLPRI", EPOLLPRI); - PyModule_AddIntConstant(m, "EPOLLERR", EPOLLERR); - PyModule_AddIntConstant(m, "EPOLLHUP", EPOLLHUP); - PyModule_AddIntConstant(m, "EPOLLET", EPOLLET); + Py_TYPE(&pyEpoll_Type) = &PyType_Type; + if (PyType_Ready(&pyEpoll_Type) < 0) + return NULL; + + Py_INCREF(&pyEpoll_Type); + PyModule_AddObject(m, "epoll", (PyObject *) &pyEpoll_Type); + + PyModule_AddIntConstant(m, "EPOLLIN", EPOLLIN); + PyModule_AddIntConstant(m, "EPOLLOUT", EPOLLOUT); + PyModule_AddIntConstant(m, "EPOLLPRI", EPOLLPRI); + PyModule_AddIntConstant(m, "EPOLLERR", EPOLLERR); + PyModule_AddIntConstant(m, "EPOLLHUP", EPOLLHUP); + PyModule_AddIntConstant(m, "EPOLLET", EPOLLET); #ifdef EPOLLONESHOT - /* Kernel 2.6.2+ */ - PyModule_AddIntConstant(m, "EPOLLONESHOT", EPOLLONESHOT); + /* Kernel 2.6.2+ */ + PyModule_AddIntConstant(m, "EPOLLONESHOT", EPOLLONESHOT); #endif - /* PyModule_AddIntConstant(m, "EPOLL_RDHUP", EPOLLRDHUP); */ - PyModule_AddIntConstant(m, "EPOLLRDNORM", EPOLLRDNORM); - PyModule_AddIntConstant(m, "EPOLLRDBAND", EPOLLRDBAND); - PyModule_AddIntConstant(m, "EPOLLWRNORM", EPOLLWRNORM); - PyModule_AddIntConstant(m, "EPOLLWRBAND", EPOLLWRBAND); - PyModule_AddIntConstant(m, "EPOLLMSG", EPOLLMSG); + /* PyModule_AddIntConstant(m, "EPOLL_RDHUP", EPOLLRDHUP); */ + PyModule_AddIntConstant(m, "EPOLLRDNORM", EPOLLRDNORM); + PyModule_AddIntConstant(m, "EPOLLRDBAND", EPOLLRDBAND); + PyModule_AddIntConstant(m, "EPOLLWRNORM", EPOLLWRNORM); + PyModule_AddIntConstant(m, "EPOLLWRBAND", EPOLLWRBAND); + PyModule_AddIntConstant(m, "EPOLLMSG", EPOLLMSG); #endif /* HAVE_EPOLL */ #ifdef HAVE_KQUEUE - kqueue_event_Type.tp_new = PyType_GenericNew; - Py_TYPE(&kqueue_event_Type) = &PyType_Type; - if(PyType_Ready(&kqueue_event_Type) < 0) - return NULL; - - Py_INCREF(&kqueue_event_Type); - PyModule_AddObject(m, "kevent", (PyObject *)&kqueue_event_Type); - - Py_TYPE(&kqueue_queue_Type) = &PyType_Type; - if(PyType_Ready(&kqueue_queue_Type) < 0) - return NULL; - Py_INCREF(&kqueue_queue_Type); - PyModule_AddObject(m, "kqueue", (PyObject *)&kqueue_queue_Type); - - /* event filters */ - PyModule_AddIntConstant(m, "KQ_FILTER_READ", EVFILT_READ); - PyModule_AddIntConstant(m, "KQ_FILTER_WRITE", EVFILT_WRITE); - PyModule_AddIntConstant(m, "KQ_FILTER_AIO", EVFILT_AIO); - PyModule_AddIntConstant(m, "KQ_FILTER_VNODE", EVFILT_VNODE); - PyModule_AddIntConstant(m, "KQ_FILTER_PROC", EVFILT_PROC); + kqueue_event_Type.tp_new = PyType_GenericNew; + Py_TYPE(&kqueue_event_Type) = &PyType_Type; + if(PyType_Ready(&kqueue_event_Type) < 0) + return NULL; + + Py_INCREF(&kqueue_event_Type); + PyModule_AddObject(m, "kevent", (PyObject *)&kqueue_event_Type); + + Py_TYPE(&kqueue_queue_Type) = &PyType_Type; + if(PyType_Ready(&kqueue_queue_Type) < 0) + return NULL; + Py_INCREF(&kqueue_queue_Type); + PyModule_AddObject(m, "kqueue", (PyObject *)&kqueue_queue_Type); + + /* event filters */ + PyModule_AddIntConstant(m, "KQ_FILTER_READ", EVFILT_READ); + PyModule_AddIntConstant(m, "KQ_FILTER_WRITE", EVFILT_WRITE); + PyModule_AddIntConstant(m, "KQ_FILTER_AIO", EVFILT_AIO); + PyModule_AddIntConstant(m, "KQ_FILTER_VNODE", EVFILT_VNODE); + PyModule_AddIntConstant(m, "KQ_FILTER_PROC", EVFILT_PROC); #ifdef EVFILT_NETDEV - PyModule_AddIntConstant(m, "KQ_FILTER_NETDEV", EVFILT_NETDEV); + PyModule_AddIntConstant(m, "KQ_FILTER_NETDEV", EVFILT_NETDEV); #endif - PyModule_AddIntConstant(m, "KQ_FILTER_SIGNAL", EVFILT_SIGNAL); - PyModule_AddIntConstant(m, "KQ_FILTER_TIMER", EVFILT_TIMER); + PyModule_AddIntConstant(m, "KQ_FILTER_SIGNAL", EVFILT_SIGNAL); + PyModule_AddIntConstant(m, "KQ_FILTER_TIMER", EVFILT_TIMER); - /* event flags */ - PyModule_AddIntConstant(m, "KQ_EV_ADD", EV_ADD); - PyModule_AddIntConstant(m, "KQ_EV_DELETE", EV_DELETE); - PyModule_AddIntConstant(m, "KQ_EV_ENABLE", EV_ENABLE); - PyModule_AddIntConstant(m, "KQ_EV_DISABLE", EV_DISABLE); - PyModule_AddIntConstant(m, "KQ_EV_ONESHOT", EV_ONESHOT); - PyModule_AddIntConstant(m, "KQ_EV_CLEAR", EV_CLEAR); - - PyModule_AddIntConstant(m, "KQ_EV_SYSFLAGS", EV_SYSFLAGS); - PyModule_AddIntConstant(m, "KQ_EV_FLAG1", EV_FLAG1); - - PyModule_AddIntConstant(m, "KQ_EV_EOF", EV_EOF); - PyModule_AddIntConstant(m, "KQ_EV_ERROR", EV_ERROR); - - /* READ WRITE filter flag */ - PyModule_AddIntConstant(m, "KQ_NOTE_LOWAT", NOTE_LOWAT); - - /* VNODE filter flags */ - PyModule_AddIntConstant(m, "KQ_NOTE_DELETE", NOTE_DELETE); - PyModule_AddIntConstant(m, "KQ_NOTE_WRITE", NOTE_WRITE); - PyModule_AddIntConstant(m, "KQ_NOTE_EXTEND", NOTE_EXTEND); - PyModule_AddIntConstant(m, "KQ_NOTE_ATTRIB", NOTE_ATTRIB); - PyModule_AddIntConstant(m, "KQ_NOTE_LINK", NOTE_LINK); - PyModule_AddIntConstant(m, "KQ_NOTE_RENAME", NOTE_RENAME); - PyModule_AddIntConstant(m, "KQ_NOTE_REVOKE", NOTE_REVOKE); - - /* PROC filter flags */ - PyModule_AddIntConstant(m, "KQ_NOTE_EXIT", NOTE_EXIT); - PyModule_AddIntConstant(m, "KQ_NOTE_FORK", NOTE_FORK); - PyModule_AddIntConstant(m, "KQ_NOTE_EXEC", NOTE_EXEC); - PyModule_AddIntConstant(m, "KQ_NOTE_PCTRLMASK", NOTE_PCTRLMASK); - PyModule_AddIntConstant(m, "KQ_NOTE_PDATAMASK", NOTE_PDATAMASK); - - PyModule_AddIntConstant(m, "KQ_NOTE_TRACK", NOTE_TRACK); - PyModule_AddIntConstant(m, "KQ_NOTE_CHILD", NOTE_CHILD); - PyModule_AddIntConstant(m, "KQ_NOTE_TRACKERR", NOTE_TRACKERR); + /* event flags */ + PyModule_AddIntConstant(m, "KQ_EV_ADD", EV_ADD); + PyModule_AddIntConstant(m, "KQ_EV_DELETE", EV_DELETE); + PyModule_AddIntConstant(m, "KQ_EV_ENABLE", EV_ENABLE); + PyModule_AddIntConstant(m, "KQ_EV_DISABLE", EV_DISABLE); + PyModule_AddIntConstant(m, "KQ_EV_ONESHOT", EV_ONESHOT); + PyModule_AddIntConstant(m, "KQ_EV_CLEAR", EV_CLEAR); + + PyModule_AddIntConstant(m, "KQ_EV_SYSFLAGS", EV_SYSFLAGS); + PyModule_AddIntConstant(m, "KQ_EV_FLAG1", EV_FLAG1); + + PyModule_AddIntConstant(m, "KQ_EV_EOF", EV_EOF); + PyModule_AddIntConstant(m, "KQ_EV_ERROR", EV_ERROR); + + /* READ WRITE filter flag */ + PyModule_AddIntConstant(m, "KQ_NOTE_LOWAT", NOTE_LOWAT); + + /* VNODE filter flags */ + PyModule_AddIntConstant(m, "KQ_NOTE_DELETE", NOTE_DELETE); + PyModule_AddIntConstant(m, "KQ_NOTE_WRITE", NOTE_WRITE); + PyModule_AddIntConstant(m, "KQ_NOTE_EXTEND", NOTE_EXTEND); + PyModule_AddIntConstant(m, "KQ_NOTE_ATTRIB", NOTE_ATTRIB); + PyModule_AddIntConstant(m, "KQ_NOTE_LINK", NOTE_LINK); + PyModule_AddIntConstant(m, "KQ_NOTE_RENAME", NOTE_RENAME); + PyModule_AddIntConstant(m, "KQ_NOTE_REVOKE", NOTE_REVOKE); + + /* PROC filter flags */ + PyModule_AddIntConstant(m, "KQ_NOTE_EXIT", NOTE_EXIT); + PyModule_AddIntConstant(m, "KQ_NOTE_FORK", NOTE_FORK); + PyModule_AddIntConstant(m, "KQ_NOTE_EXEC", NOTE_EXEC); + PyModule_AddIntConstant(m, "KQ_NOTE_PCTRLMASK", NOTE_PCTRLMASK); + PyModule_AddIntConstant(m, "KQ_NOTE_PDATAMASK", NOTE_PDATAMASK); + + PyModule_AddIntConstant(m, "KQ_NOTE_TRACK", NOTE_TRACK); + PyModule_AddIntConstant(m, "KQ_NOTE_CHILD", NOTE_CHILD); + PyModule_AddIntConstant(m, "KQ_NOTE_TRACKERR", NOTE_TRACKERR); - /* NETDEV filter flags */ + /* NETDEV filter flags */ #ifdef EVFILT_NETDEV - PyModule_AddIntConstant(m, "KQ_NOTE_LINKUP", NOTE_LINKUP); - PyModule_AddIntConstant(m, "KQ_NOTE_LINKDOWN", NOTE_LINKDOWN); - PyModule_AddIntConstant(m, "KQ_NOTE_LINKINV", NOTE_LINKINV); + PyModule_AddIntConstant(m, "KQ_NOTE_LINKUP", NOTE_LINKUP); + PyModule_AddIntConstant(m, "KQ_NOTE_LINKDOWN", NOTE_LINKDOWN); + PyModule_AddIntConstant(m, "KQ_NOTE_LINKINV", NOTE_LINKINV); #endif #endif /* HAVE_KQUEUE */ - return m; + return m; } Modified: python/branches/release31-maint/Modules/sha1module.c ============================================================================== --- python/branches/release31-maint/Modules/sha1module.c (original) +++ python/branches/release31-maint/Modules/sha1module.c Sun May 9 18:14:21 2010 @@ -23,8 +23,8 @@ /* Some useful types */ #if SIZEOF_INT == 4 -typedef unsigned int SHA1_INT32; /* 32-bit integer */ -typedef PY_LONG_LONG SHA1_INT64; /* 64-bit integer */ +typedef unsigned int SHA1_INT32; /* 32-bit integer */ +typedef PY_LONG_LONG SHA1_INT64; /* 64-bit integer */ #else /* not defined. compilation will die. */ #endif @@ -122,7 +122,7 @@ /* expand it */ for (i = 16; i < 80; i++) { - W[i] = ROL(W[i-3] ^ W[i-8] ^ W[i-14] ^ W[i-16], 1); + W[i] = ROL(W[i-3] ^ W[i-8] ^ W[i-14] ^ W[i-16], 1); } /* compress */ @@ -131,7 +131,7 @@ #define FF1(a,b,c,d,e,i) e = (ROLc(a, 5) + F1(b,c,d) + e + W[i] + 0x6ed9eba1UL); b = ROLc(b, 30); #define FF2(a,b,c,d,e,i) e = (ROLc(a, 5) + F2(b,c,d) + e + W[i] + 0x8f1bbcdcUL); b = ROLc(b, 30); #define FF3(a,b,c,d,e,i) e = (ROLc(a, 5) + F3(b,c,d) + e + W[i] + 0xca62c1d6UL); b = ROLc(b, 30); - + for (i = 0; i < 20; ) { FF0(a,b,c,d,e,i++); FF0(e,a,b,c,d,i++); @@ -141,7 +141,7 @@ } /* round two */ - for (; i < 40; ) { + for (; i < 40; ) { FF1(a,b,c,d,e,i++); FF1(e,a,b,c,d,i++); FF1(d,e,a,b,c,i++); @@ -150,7 +150,7 @@ } /* round three */ - for (; i < 60; ) { + for (; i < 60; ) { FF2(a,b,c,d,e,i++); FF2(e,a,b,c,d,i++); FF2(d,e,a,b,c,i++); @@ -159,7 +159,7 @@ } /* round four */ - for (; i < 80; ) { + for (; i < 80; ) { FF3(a,b,c,d,e,i++); FF3(e,a,b,c,d,i++); FF3(d,e,a,b,c,i++); @@ -362,21 +362,21 @@ /* Create a new string */ retval = PyUnicode_FromStringAndSize(NULL, SHA1_DIGESTSIZE * 2); if (!retval) - return NULL; + return NULL; hex_digest = PyUnicode_AS_UNICODE(retval); if (!hex_digest) { - Py_DECREF(retval); - return NULL; + Py_DECREF(retval); + return NULL; } /* Make hex version of the digest */ for(i=j=0; i> 4) & 0xf; - c = (c>9) ? c+'a'-10 : c + '0'; + c = (c>9) ? c+'a'-10 : c + '0'; hex_digest[j++] = c; c = (digest[i] & 0xf); - c = (c>9) ? c+'a'-10 : c + '0'; + c = (c>9) ? c+'a'-10 : c + '0'; hex_digest[j++] = c; } return retval; @@ -404,11 +404,11 @@ } static PyMethodDef SHA1_methods[] = { - {"copy", (PyCFunction)SHA1_copy, METH_NOARGS, SHA1_copy__doc__}, - {"digest", (PyCFunction)SHA1_digest, METH_NOARGS, SHA1_digest__doc__}, + {"copy", (PyCFunction)SHA1_copy, METH_NOARGS, SHA1_copy__doc__}, + {"digest", (PyCFunction)SHA1_digest, METH_NOARGS, SHA1_digest__doc__}, {"hexdigest", (PyCFunction)SHA1_hexdigest, METH_NOARGS, SHA1_hexdigest__doc__}, - {"update", (PyCFunction)SHA1_update, METH_VARARGS, SHA1_update__doc__}, - {NULL, NULL} /* sentinel */ + {"update", (PyCFunction)SHA1_update, METH_VARARGS, SHA1_update__doc__}, + {NULL, NULL} /* sentinel */ }; static PyObject * @@ -448,13 +448,13 @@ static PyTypeObject SHA1type = { PyVarObject_HEAD_INIT(NULL, 0) - "_sha1.sha1", /*tp_name*/ - sizeof(SHA1object), /*tp_size*/ - 0, /*tp_itemsize*/ + "_sha1.sha1", /*tp_name*/ + sizeof(SHA1object), /*tp_size*/ + 0, /*tp_itemsize*/ /* methods */ - SHA1_dealloc, /*tp_dealloc*/ - 0, /*tp_print*/ - 0, /*tp_getattr*/ + SHA1_dealloc, /*tp_dealloc*/ + 0, /*tp_print*/ + 0, /*tp_getattr*/ 0, /*tp_setattr*/ 0, /*tp_reserved*/ 0, /*tp_repr*/ @@ -470,13 +470,13 @@ Py_TPFLAGS_DEFAULT, /*tp_flags*/ 0, /*tp_doc*/ 0, /*tp_traverse*/ - 0, /*tp_clear*/ - 0, /*tp_richcompare*/ - 0, /*tp_weaklistoffset*/ - 0, /*tp_iter*/ - 0, /*tp_iternext*/ - SHA1_methods, /* tp_methods */ - NULL, /* tp_members */ + 0, /*tp_clear*/ + 0, /*tp_richcompare*/ + 0, /*tp_weaklistoffset*/ + 0, /*tp_iter*/ + 0, /*tp_iternext*/ + SHA1_methods, /* tp_methods */ + NULL, /* tp_members */ SHA1_getseters, /* tp_getset */ }; @@ -529,7 +529,7 @@ static struct PyMethodDef SHA1_functions[] = { {"sha1",(PyCFunction)SHA1_new, METH_VARARGS|METH_KEYWORDS,SHA1_new__doc__}, - {NULL, NULL} /* Sentinel */ + {NULL, NULL} /* Sentinel */ }; @@ -539,15 +539,15 @@ static struct PyModuleDef _sha1module = { - PyModuleDef_HEAD_INIT, - "_sha1", - NULL, - -1, - SHA1_functions, - NULL, - NULL, - NULL, - NULL + PyModuleDef_HEAD_INIT, + "_sha1", + NULL, + -1, + SHA1_functions, + NULL, + NULL, + NULL, + NULL }; PyMODINIT_FUNC Modified: python/branches/release31-maint/Modules/sha256module.c ============================================================================== --- python/branches/release31-maint/Modules/sha256module.c (original) +++ python/branches/release31-maint/Modules/sha256module.c Sun May 9 18:14:21 2010 @@ -23,7 +23,7 @@ /* Endianness testing and definitions */ #define TestEndianness(variable) {int i=1; variable=PCT_BIG_ENDIAN;\ - if (*((char*)&i)==1) variable=PCT_LITTLE_ENDIAN;} + if (*((char*)&i)==1) variable=PCT_LITTLE_ENDIAN;} #define PCT_LITTLE_ENDIAN 1 #define PCT_BIG_ENDIAN 0 @@ -33,7 +33,7 @@ typedef unsigned char SHA_BYTE; #if SIZEOF_INT == 4 -typedef unsigned int SHA_INT32; /* 32-bit integer */ +typedef unsigned int SHA_INT32; /* 32-bit integer */ #else /* not defined. compilation will die. */ #endif @@ -47,11 +47,11 @@ typedef struct { PyObject_HEAD - SHA_INT32 digest[8]; /* Message digest */ - SHA_INT32 count_lo, count_hi; /* 64-bit bit count */ - SHA_BYTE data[SHA_BLOCKSIZE]; /* SHA data buffer */ + SHA_INT32 digest[8]; /* Message digest */ + SHA_INT32 count_lo, count_hi; /* 64-bit bit count */ + SHA_BYTE data[SHA_BLOCKSIZE]; /* SHA data buffer */ int Endianness; - int local; /* unprocessed amount in data */ + int local; /* unprocessed amount in data */ int digestsize; } SHAobject; @@ -63,7 +63,7 @@ SHA_INT32 value; if ( Endianness == PCT_BIG_ENDIAN ) - return; + return; byteCount /= sizeof(*buffer); while (byteCount--) { @@ -115,7 +115,7 @@ ( ((((unsigned long)(x)&0xFFFFFFFFUL)>>(unsigned long)((y)&31)) | \ ((unsigned long)(x)<<(unsigned long)(32-((y)&31)))) & 0xFFFFFFFFUL) #define Ch(x,y,z) (z ^ (x & (y ^ z))) -#define Maj(x,y,z) (((x | y) & z) | (x & y)) +#define Maj(x,y,z) (((x | y) & z) | (x & y)) #define S(x, n) ROR((x),(n)) #define R(x, n) (((x)&0xFFFFFFFFUL)>>(n)) #define Sigma0(x) (S(x, 2) ^ S(x, 13) ^ S(x, 22)) @@ -128,13 +128,13 @@ sha_transform(SHAobject *sha_info) { int i; - SHA_INT32 S[8], W[64], t0, t1; + SHA_INT32 S[8], W[64], t0, t1; memcpy(W, sha_info->data, sizeof(sha_info->data)); longReverse(W, (int)sizeof(sha_info->data), sha_info->Endianness); for (i = 16; i < 64; ++i) { - W[i] = Gamma1(W[i - 2]) + W[i - 7] + Gamma0(W[i - 15]) + W[i - 16]; + W[i] = Gamma1(W[i - 2]) + W[i - 7] + Gamma0(W[i - 15]) + W[i - 16]; } for (i = 0; i < 8; ++i) { S[i] = sha_info->digest[i]; @@ -212,8 +212,8 @@ RND(S[2],S[3],S[4],S[5],S[6],S[7],S[0],S[1],62,0xbef9a3f7); RND(S[1],S[2],S[3],S[4],S[5],S[6],S[7],S[0],63,0xc67178f2); -#undef RND - +#undef RND + /* feedback */ for (i = 0; i < 8; i++) { sha_info->digest[i] = sha_info->digest[i] + S[i]; @@ -315,14 +315,14 @@ count = (int) ((lo_bit_count >> 3) & 0x3f); ((SHA_BYTE *) sha_info->data)[count++] = 0x80; if (count > SHA_BLOCKSIZE - 8) { - memset(((SHA_BYTE *) sha_info->data) + count, 0, - SHA_BLOCKSIZE - count); - sha_transform(sha_info); - memset((SHA_BYTE *) sha_info->data, 0, SHA_BLOCKSIZE - 8); + memset(((SHA_BYTE *) sha_info->data) + count, 0, + SHA_BLOCKSIZE - count); + sha_transform(sha_info); + memset((SHA_BYTE *) sha_info->data, 0, SHA_BLOCKSIZE - 8); } else { - memset(((SHA_BYTE *) sha_info->data) + count, 0, - SHA_BLOCKSIZE - 8 - count); + memset(((SHA_BYTE *) sha_info->data) + count, 0, + SHA_BLOCKSIZE - 8 - count); } /* GJS: note that we add the hi/lo in big-endian. sha_transform will @@ -455,21 +455,21 @@ /* Create a new string */ retval = PyUnicode_FromStringAndSize(NULL, self->digestsize * 2); if (!retval) - return NULL; + return NULL; hex_digest = PyUnicode_AS_UNICODE(retval); if (!hex_digest) { - Py_DECREF(retval); - return NULL; + Py_DECREF(retval); + return NULL; } /* Make hex version of the digest */ for(i=j=0; idigestsize; i++) { char c; c = (digest[i] >> 4) & 0xf; - c = (c>9) ? c+'a'-10 : c + '0'; + c = (c>9) ? c+'a'-10 : c + '0'; hex_digest[j++] = c; c = (digest[i] & 0xf); - c = (c>9) ? c+'a'-10 : c + '0'; + c = (c>9) ? c+'a'-10 : c + '0'; hex_digest[j++] = c; } return retval; @@ -497,11 +497,11 @@ } static PyMethodDef SHA_methods[] = { - {"copy", (PyCFunction)SHA256_copy, METH_NOARGS, SHA256_copy__doc__}, - {"digest", (PyCFunction)SHA256_digest, METH_NOARGS, SHA256_digest__doc__}, + {"copy", (PyCFunction)SHA256_copy, METH_NOARGS, SHA256_copy__doc__}, + {"digest", (PyCFunction)SHA256_digest, METH_NOARGS, SHA256_digest__doc__}, {"hexdigest", (PyCFunction)SHA256_hexdigest, METH_NOARGS, SHA256_hexdigest__doc__}, - {"update", (PyCFunction)SHA256_update, METH_VARARGS, SHA256_update__doc__}, - {NULL, NULL} /* sentinel */ + {"update", (PyCFunction)SHA256_update, METH_VARARGS, SHA256_update__doc__}, + {NULL, NULL} /* sentinel */ }; static PyObject * @@ -538,13 +538,13 @@ static PyTypeObject SHA224type = { PyVarObject_HEAD_INIT(NULL, 0) - "_sha256.sha224", /*tp_name*/ - sizeof(SHAobject), /*tp_size*/ - 0, /*tp_itemsize*/ + "_sha256.sha224", /*tp_name*/ + sizeof(SHAobject), /*tp_size*/ + 0, /*tp_itemsize*/ /* methods */ - SHA_dealloc, /*tp_dealloc*/ - 0, /*tp_print*/ - 0, /*tp_getattr*/ + SHA_dealloc, /*tp_dealloc*/ + 0, /*tp_print*/ + 0, /*tp_getattr*/ 0, /*tp_setattr*/ 0, /*tp_reserved*/ 0, /*tp_repr*/ @@ -560,25 +560,25 @@ Py_TPFLAGS_DEFAULT, /*tp_flags*/ 0, /*tp_doc*/ 0, /*tp_traverse*/ - 0, /*tp_clear*/ - 0, /*tp_richcompare*/ - 0, /*tp_weaklistoffset*/ - 0, /*tp_iter*/ - 0, /*tp_iternext*/ - SHA_methods, /* tp_methods */ - SHA_members, /* tp_members */ + 0, /*tp_clear*/ + 0, /*tp_richcompare*/ + 0, /*tp_weaklistoffset*/ + 0, /*tp_iter*/ + 0, /*tp_iternext*/ + SHA_methods, /* tp_methods */ + SHA_members, /* tp_members */ SHA_getseters, /* tp_getset */ }; static PyTypeObject SHA256type = { PyVarObject_HEAD_INIT(NULL, 0) - "_sha256.sha256", /*tp_name*/ - sizeof(SHAobject), /*tp_size*/ - 0, /*tp_itemsize*/ + "_sha256.sha256", /*tp_name*/ + sizeof(SHAobject), /*tp_size*/ + 0, /*tp_itemsize*/ /* methods */ - SHA_dealloc, /*tp_dealloc*/ - 0, /*tp_print*/ - 0, /*tp_getattr*/ + SHA_dealloc, /*tp_dealloc*/ + 0, /*tp_print*/ + 0, /*tp_getattr*/ 0, /*tp_setattr*/ 0, /*tp_reserved*/ 0, /*tp_repr*/ @@ -594,13 +594,13 @@ Py_TPFLAGS_DEFAULT, /*tp_flags*/ 0, /*tp_doc*/ 0, /*tp_traverse*/ - 0, /*tp_clear*/ - 0, /*tp_richcompare*/ - 0, /*tp_weaklistoffset*/ - 0, /*tp_iter*/ - 0, /*tp_iternext*/ - SHA_methods, /* tp_methods */ - SHA_members, /* tp_members */ + 0, /*tp_clear*/ + 0, /*tp_richcompare*/ + 0, /*tp_weaklistoffset*/ + 0, /*tp_iter*/ + 0, /*tp_iternext*/ + SHA_methods, /* tp_methods */ + SHA_members, /* tp_members */ SHA_getseters, /* tp_getset */ }; @@ -695,7 +695,7 @@ static struct PyMethodDef SHA_functions[] = { {"sha256", (PyCFunction)SHA256_new, METH_VARARGS|METH_KEYWORDS, SHA256_new__doc__}, {"sha224", (PyCFunction)SHA224_new, METH_VARARGS|METH_KEYWORDS, SHA224_new__doc__}, - {NULL, NULL} /* Sentinel */ + {NULL, NULL} /* Sentinel */ }; @@ -705,15 +705,15 @@ static struct PyModuleDef _sha256module = { - PyModuleDef_HEAD_INIT, - "_sha256", - NULL, - -1, - SHA_functions, - NULL, - NULL, - NULL, - NULL + PyModuleDef_HEAD_INIT, + "_sha256", + NULL, + -1, + SHA_functions, + NULL, + NULL, + NULL, + NULL }; PyMODINIT_FUNC Modified: python/branches/release31-maint/Modules/sha512module.c ============================================================================== --- python/branches/release31-maint/Modules/sha512module.c (original) +++ python/branches/release31-maint/Modules/sha512module.c Sun May 9 18:14:21 2010 @@ -24,7 +24,7 @@ /* Endianness testing and definitions */ #define TestEndianness(variable) {int i=1; variable=PCT_BIG_ENDIAN;\ - if (*((char*)&i)==1) variable=PCT_LITTLE_ENDIAN;} + if (*((char*)&i)==1) variable=PCT_LITTLE_ENDIAN;} #define PCT_LITTLE_ENDIAN 1 #define PCT_BIG_ENDIAN 0 @@ -34,8 +34,8 @@ typedef unsigned char SHA_BYTE; #if SIZEOF_INT == 4 -typedef unsigned int SHA_INT32; /* 32-bit integer */ -typedef unsigned PY_LONG_LONG SHA_INT64; /* 64-bit integer */ +typedef unsigned int SHA_INT32; /* 32-bit integer */ +typedef unsigned PY_LONG_LONG SHA_INT64; /* 64-bit integer */ #else /* not defined. compilation will die. */ #endif @@ -49,11 +49,11 @@ typedef struct { PyObject_HEAD - SHA_INT64 digest[8]; /* Message digest */ - SHA_INT32 count_lo, count_hi; /* 64-bit bit count */ - SHA_BYTE data[SHA_BLOCKSIZE]; /* SHA data buffer */ + SHA_INT64 digest[8]; /* Message digest */ + SHA_INT32 count_lo, count_hi; /* 64-bit bit count */ + SHA_BYTE data[SHA_BLOCKSIZE]; /* SHA data buffer */ int Endianness; - int local; /* unprocessed amount in data */ + int local; /* unprocessed amount in data */ int digestsize; } SHAobject; @@ -65,22 +65,22 @@ SHA_INT64 value; if ( Endianness == PCT_BIG_ENDIAN ) - return; + return; byteCount /= sizeof(*buffer); while (byteCount--) { value = *buffer; - ((unsigned char*)buffer)[0] = (unsigned char)(value >> 56) & 0xff; - ((unsigned char*)buffer)[1] = (unsigned char)(value >> 48) & 0xff; - ((unsigned char*)buffer)[2] = (unsigned char)(value >> 40) & 0xff; - ((unsigned char*)buffer)[3] = (unsigned char)(value >> 32) & 0xff; - ((unsigned char*)buffer)[4] = (unsigned char)(value >> 24) & 0xff; - ((unsigned char*)buffer)[5] = (unsigned char)(value >> 16) & 0xff; - ((unsigned char*)buffer)[6] = (unsigned char)(value >> 8) & 0xff; - ((unsigned char*)buffer)[7] = (unsigned char)(value ) & 0xff; - - buffer++; + ((unsigned char*)buffer)[0] = (unsigned char)(value >> 56) & 0xff; + ((unsigned char*)buffer)[1] = (unsigned char)(value >> 48) & 0xff; + ((unsigned char*)buffer)[2] = (unsigned char)(value >> 40) & 0xff; + ((unsigned char*)buffer)[3] = (unsigned char)(value >> 32) & 0xff; + ((unsigned char*)buffer)[4] = (unsigned char)(value >> 24) & 0xff; + ((unsigned char*)buffer)[5] = (unsigned char)(value >> 16) & 0xff; + ((unsigned char*)buffer)[6] = (unsigned char)(value >> 8) & 0xff; + ((unsigned char*)buffer)[7] = (unsigned char)(value ) & 0xff; + + buffer++; } } @@ -125,7 +125,7 @@ ( ((((x) & Py_ULL(0xFFFFFFFFFFFFFFFF))>>((unsigned PY_LONG_LONG)(y) & 63)) | \ ((x)<<((unsigned PY_LONG_LONG)(64-((y) & 63))))) & Py_ULL(0xFFFFFFFFFFFFFFFF)) #define Ch(x,y,z) (z ^ (x & (y ^ z))) -#define Maj(x,y,z) (((x | y) & z) | (x & y)) +#define Maj(x,y,z) (((x | y) & z) | (x & y)) #define S(x, n) ROR64((x),(n)) #define R(x, n) (((x) & Py_ULL(0xFFFFFFFFFFFFFFFF)) >> ((unsigned PY_LONG_LONG)n)) #define Sigma0(x) (S(x, 28) ^ S(x, 34) ^ S(x, 39)) @@ -144,7 +144,7 @@ longReverse(W, (int)sizeof(sha_info->data), sha_info->Endianness); for (i = 16; i < 80; ++i) { - W[i] = Gamma1(W[i - 2]) + W[i - 7] + Gamma0(W[i - 15]) + W[i - 16]; + W[i] = Gamma1(W[i - 2]) + W[i - 7] + Gamma0(W[i - 15]) + W[i - 16]; } for (i = 0; i < 8; ++i) { S[i] = sha_info->digest[i]; @@ -238,8 +238,8 @@ RND(S[2],S[3],S[4],S[5],S[6],S[7],S[0],S[1],78,Py_ULL(0x5fcb6fab3ad6faec)); RND(S[1],S[2],S[3],S[4],S[5],S[6],S[7],S[0],79,Py_ULL(0x6c44198c4a475817)); -#undef RND - +#undef RND + /* feedback */ for (i = 0; i < 8; i++) { sha_info->digest[i] = sha_info->digest[i] + S[i]; @@ -341,14 +341,14 @@ count = (int) ((lo_bit_count >> 3) & 0x7f); ((SHA_BYTE *) sha_info->data)[count++] = 0x80; if (count > SHA_BLOCKSIZE - 16) { - memset(((SHA_BYTE *) sha_info->data) + count, 0, - SHA_BLOCKSIZE - count); - sha512_transform(sha_info); - memset((SHA_BYTE *) sha_info->data, 0, SHA_BLOCKSIZE - 16); + memset(((SHA_BYTE *) sha_info->data) + count, 0, + SHA_BLOCKSIZE - count); + sha512_transform(sha_info); + memset((SHA_BYTE *) sha_info->data, 0, SHA_BLOCKSIZE - 16); } else { - memset(((SHA_BYTE *) sha_info->data) + count, 0, - SHA_BLOCKSIZE - 16 - count); + memset(((SHA_BYTE *) sha_info->data) + count, 0, + SHA_BLOCKSIZE - 16 - count); } /* GJS: note that we add the hi/lo in big-endian. sha512_transform will @@ -521,21 +521,21 @@ /* Create a new string */ retval = PyUnicode_FromStringAndSize(NULL, self->digestsize * 2); if (!retval) - return NULL; + return NULL; hex_digest = PyUnicode_AS_UNICODE(retval); if (!hex_digest) { - Py_DECREF(retval); - return NULL; + Py_DECREF(retval); + return NULL; } /* Make hex version of the digest */ for (i=j=0; idigestsize; i++) { char c; c = (digest[i] >> 4) & 0xf; - c = (c>9) ? c+'a'-10 : c + '0'; + c = (c>9) ? c+'a'-10 : c + '0'; hex_digest[j++] = c; c = (digest[i] & 0xf); - c = (c>9) ? c+'a'-10 : c + '0'; + c = (c>9) ? c+'a'-10 : c + '0'; hex_digest[j++] = c; } return retval; @@ -563,11 +563,11 @@ } static PyMethodDef SHA_methods[] = { - {"copy", (PyCFunction)SHA512_copy, METH_NOARGS, SHA512_copy__doc__}, - {"digest", (PyCFunction)SHA512_digest, METH_NOARGS, SHA512_digest__doc__}, + {"copy", (PyCFunction)SHA512_copy, METH_NOARGS, SHA512_copy__doc__}, + {"digest", (PyCFunction)SHA512_digest, METH_NOARGS, SHA512_digest__doc__}, {"hexdigest", (PyCFunction)SHA512_hexdigest, METH_NOARGS, SHA512_hexdigest__doc__}, - {"update", (PyCFunction)SHA512_update, METH_VARARGS, SHA512_update__doc__}, - {NULL, NULL} /* sentinel */ + {"update", (PyCFunction)SHA512_update, METH_VARARGS, SHA512_update__doc__}, + {NULL, NULL} /* sentinel */ }; static PyObject * @@ -604,13 +604,13 @@ static PyTypeObject SHA384type = { PyVarObject_HEAD_INIT(NULL, 0) - "_sha512.sha384", /*tp_name*/ - sizeof(SHAobject), /*tp_size*/ - 0, /*tp_itemsize*/ + "_sha512.sha384", /*tp_name*/ + sizeof(SHAobject), /*tp_size*/ + 0, /*tp_itemsize*/ /* methods */ - SHA512_dealloc, /*tp_dealloc*/ - 0, /*tp_print*/ - 0, /*tp_getattr*/ + SHA512_dealloc, /*tp_dealloc*/ + 0, /*tp_print*/ + 0, /*tp_getattr*/ 0, /*tp_setattr*/ 0, /*tp_reserved*/ 0, /*tp_repr*/ @@ -626,25 +626,25 @@ Py_TPFLAGS_DEFAULT, /*tp_flags*/ 0, /*tp_doc*/ 0, /*tp_traverse*/ - 0, /*tp_clear*/ - 0, /*tp_richcompare*/ - 0, /*tp_weaklistoffset*/ - 0, /*tp_iter*/ - 0, /*tp_iternext*/ - SHA_methods, /* tp_methods */ - SHA_members, /* tp_members */ + 0, /*tp_clear*/ + 0, /*tp_richcompare*/ + 0, /*tp_weaklistoffset*/ + 0, /*tp_iter*/ + 0, /*tp_iternext*/ + SHA_methods, /* tp_methods */ + SHA_members, /* tp_members */ SHA_getseters, /* tp_getset */ }; static PyTypeObject SHA512type = { PyVarObject_HEAD_INIT(NULL, 0) - "_sha512.sha512", /*tp_name*/ - sizeof(SHAobject), /*tp_size*/ - 0, /*tp_itemsize*/ + "_sha512.sha512", /*tp_name*/ + sizeof(SHAobject), /*tp_size*/ + 0, /*tp_itemsize*/ /* methods */ - SHA512_dealloc, /*tp_dealloc*/ - 0, /*tp_print*/ - 0, /*tp_getattr*/ + SHA512_dealloc, /*tp_dealloc*/ + 0, /*tp_print*/ + 0, /*tp_getattr*/ 0, /*tp_setattr*/ 0, /*tp_reserved*/ 0, /*tp_repr*/ @@ -660,13 +660,13 @@ Py_TPFLAGS_DEFAULT, /*tp_flags*/ 0, /*tp_doc*/ 0, /*tp_traverse*/ - 0, /*tp_clear*/ - 0, /*tp_richcompare*/ - 0, /*tp_weaklistoffset*/ - 0, /*tp_iter*/ - 0, /*tp_iternext*/ - SHA_methods, /* tp_methods */ - SHA_members, /* tp_members */ + 0, /*tp_clear*/ + 0, /*tp_richcompare*/ + 0, /*tp_weaklistoffset*/ + 0, /*tp_iter*/ + 0, /*tp_iternext*/ + SHA_methods, /* tp_methods */ + SHA_members, /* tp_members */ SHA_getseters, /* tp_getset */ }; @@ -761,7 +761,7 @@ static struct PyMethodDef SHA_functions[] = { {"sha512", (PyCFunction)SHA512_new, METH_VARARGS|METH_KEYWORDS, SHA512_new__doc__}, {"sha384", (PyCFunction)SHA384_new, METH_VARARGS|METH_KEYWORDS, SHA384_new__doc__}, - {NULL, NULL} /* Sentinel */ + {NULL, NULL} /* Sentinel */ }; @@ -771,15 +771,15 @@ static struct PyModuleDef _sha512module = { - PyModuleDef_HEAD_INIT, - "_sha512", - NULL, - -1, - SHA_functions, - NULL, - NULL, - NULL, - NULL + PyModuleDef_HEAD_INIT, + "_sha512", + NULL, + -1, + SHA_functions, + NULL, + NULL, + NULL, + NULL }; PyMODINIT_FUNC Modified: python/branches/release31-maint/Modules/signalmodule.c ============================================================================== --- python/branches/release31-maint/Modules/signalmodule.c (original) +++ python/branches/release31-maint/Modules/signalmodule.c Sun May 9 18:14:21 2010 @@ -28,13 +28,13 @@ #ifndef NSIG # if defined(_NSIG) -# define NSIG _NSIG /* For BSD/SysV */ +# define NSIG _NSIG /* For BSD/SysV */ # elif defined(_SIGMAX) -# define NSIG (_SIGMAX + 1) /* For QNX */ +# define NSIG (_SIGMAX + 1) /* For QNX */ # elif defined(SIGMAX) -# define NSIG (SIGMAX + 1) /* For djgpp */ +# define NSIG (SIGMAX + 1) /* For djgpp */ # else -# define NSIG 64 /* Use a reasonable default value */ +# define NSIG 64 /* Use a reasonable default value */ # endif #endif @@ -76,8 +76,8 @@ #endif static struct { - int tripped; - PyObject *func; + int tripped; + PyObject *func; } Handlers[NSIG]; static sig_atomic_t wakeup_fd = -1; @@ -120,18 +120,18 @@ r = PyTuple_New(2); if (r == NULL) - return NULL; + return NULL; if(!(v = PyFloat_FromDouble(double_from_timeval(&iv->it_value)))) { - Py_DECREF(r); - return NULL; + Py_DECREF(r); + return NULL; } PyTuple_SET_ITEM(r, 0, v); if(!(v = PyFloat_FromDouble(double_from_timeval(&iv->it_interval)))) { - Py_DECREF(r); - return NULL; + Py_DECREF(r); + return NULL; } PyTuple_SET_ITEM(r, 1, v); @@ -143,8 +143,8 @@ static PyObject * signal_default_int_handler(PyObject *self, PyObject *args) { - PyErr_SetNone(PyExc_KeyboardInterrupt); - return NULL; + PyErr_SetNone(PyExc_KeyboardInterrupt); + return NULL; } PyDoc_STRVAR(default_int_handler_doc, @@ -157,7 +157,7 @@ static int checksignals_witharg(void * unused) { - return PyErr_CheckSignals(); + return PyErr_CheckSignals(); } static void @@ -165,38 +165,38 @@ { #ifdef WITH_THREAD #ifdef WITH_PTH - if (PyThread_get_thread_ident() != main_thread) { - pth_raise(*(pth_t *) main_thread, sig_num); - return; - } -#endif - /* See NOTES section above */ - if (getpid() == main_pid) { -#endif - Handlers[sig_num].tripped = 1; - /* Set is_tripped after setting .tripped, as it gets - cleared in PyErr_CheckSignals() before .tripped. */ - is_tripped = 1; - Py_AddPendingCall(checksignals_witharg, NULL); - if (wakeup_fd != -1) - write(wakeup_fd, "\0", 1); + if (PyThread_get_thread_ident() != main_thread) { + pth_raise(*(pth_t *) main_thread, sig_num); + return; + } +#endif + /* See NOTES section above */ + if (getpid() == main_pid) { +#endif + Handlers[sig_num].tripped = 1; + /* Set is_tripped after setting .tripped, as it gets + cleared in PyErr_CheckSignals() before .tripped. */ + is_tripped = 1; + Py_AddPendingCall(checksignals_witharg, NULL); + if (wakeup_fd != -1) + write(wakeup_fd, "\0", 1); #ifdef WITH_THREAD - } + } #endif #ifdef SIGCHLD - if (sig_num == SIGCHLD) { - /* To avoid infinite recursion, this signal remains - reset until explicit re-instated. - Don't clear the 'func' field as it is our pointer - to the Python handler... */ - return; - } + if (sig_num == SIGCHLD) { + /* To avoid infinite recursion, this signal remains + reset until explicit re-instated. + Don't clear the 'func' field as it is our pointer + to the Python handler... */ + return; + } #endif #ifndef HAVE_SIGACTION - /* If the handler was not set up with sigaction, reinstall it. See - * Python/pythonrun.c for the implementation of PyOS_setsig which - * makes this true. See also issue8354. */ - PyOS_setsig(sig_num, signal_handler); + /* If the handler was not set up with sigaction, reinstall it. See + * Python/pythonrun.c for the implementation of PyOS_setsig which + * makes this true. See also issue8354. */ + PyOS_setsig(sig_num, signal_handler); #endif } @@ -205,11 +205,11 @@ static PyObject * signal_alarm(PyObject *self, PyObject *args) { - int t; - if (!PyArg_ParseTuple(args, "i:alarm", &t)) - return NULL; - /* alarm() returns the number of seconds remaining */ - return PyLong_FromLong((long)alarm(t)); + int t; + if (!PyArg_ParseTuple(args, "i:alarm", &t)) + return NULL; + /* alarm() returns the number of seconds remaining */ + return PyLong_FromLong((long)alarm(t)); } PyDoc_STRVAR(alarm_doc, @@ -222,17 +222,17 @@ static PyObject * signal_pause(PyObject *self) { - Py_BEGIN_ALLOW_THREADS - (void)pause(); - Py_END_ALLOW_THREADS - /* make sure that any exceptions that got raised are propagated - * back into Python - */ - if (PyErr_CheckSignals()) - return NULL; + Py_BEGIN_ALLOW_THREADS + (void)pause(); + Py_END_ALLOW_THREADS + /* make sure that any exceptions that got raised are propagated + * back into Python + */ + if (PyErr_CheckSignals()) + return NULL; - Py_INCREF(Py_None); - return Py_None; + Py_INCREF(Py_None); + return Py_None; } PyDoc_STRVAR(pause_doc, "pause()\n\ @@ -245,44 +245,44 @@ static PyObject * signal_signal(PyObject *self, PyObject *args) { - PyObject *obj; - int sig_num; - PyObject *old_handler; - void (*func)(int); - if (!PyArg_ParseTuple(args, "iO:signal", &sig_num, &obj)) - return NULL; + PyObject *obj; + int sig_num; + PyObject *old_handler; + void (*func)(int); + if (!PyArg_ParseTuple(args, "iO:signal", &sig_num, &obj)) + return NULL; #ifdef WITH_THREAD - if (PyThread_get_thread_ident() != main_thread) { - PyErr_SetString(PyExc_ValueError, - "signal only works in main thread"); - return NULL; - } -#endif - if (sig_num < 1 || sig_num >= NSIG) { - PyErr_SetString(PyExc_ValueError, - "signal number out of range"); - return NULL; - } - if (obj == IgnoreHandler) - func = SIG_IGN; - else if (obj == DefaultHandler) - func = SIG_DFL; - else if (!PyCallable_Check(obj)) { - PyErr_SetString(PyExc_TypeError, + if (PyThread_get_thread_ident() != main_thread) { + PyErr_SetString(PyExc_ValueError, + "signal only works in main thread"); + return NULL; + } +#endif + if (sig_num < 1 || sig_num >= NSIG) { + PyErr_SetString(PyExc_ValueError, + "signal number out of range"); + return NULL; + } + if (obj == IgnoreHandler) + func = SIG_IGN; + else if (obj == DefaultHandler) + func = SIG_DFL; + else if (!PyCallable_Check(obj)) { + PyErr_SetString(PyExc_TypeError, "signal handler must be signal.SIG_IGN, signal.SIG_DFL, or a callable object"); - return NULL; - } - else - func = signal_handler; - if (PyOS_setsig(sig_num, func) == SIG_ERR) { - PyErr_SetFromErrno(PyExc_RuntimeError); - return NULL; - } - old_handler = Handlers[sig_num].func; - Handlers[sig_num].tripped = 0; - Py_INCREF(obj); - Handlers[sig_num].func = obj; - return old_handler; + return NULL; + } + else + func = signal_handler; + if (PyOS_setsig(sig_num, func) == SIG_ERR) { + PyErr_SetFromErrno(PyExc_RuntimeError); + return NULL; + } + old_handler = Handlers[sig_num].func; + Handlers[sig_num].tripped = 0; + Py_INCREF(obj); + Handlers[sig_num].func = obj; + return old_handler; } PyDoc_STRVAR(signal_doc, @@ -300,18 +300,18 @@ static PyObject * signal_getsignal(PyObject *self, PyObject *args) { - int sig_num; - PyObject *old_handler; - if (!PyArg_ParseTuple(args, "i:getsignal", &sig_num)) - return NULL; - if (sig_num < 1 || sig_num >= NSIG) { - PyErr_SetString(PyExc_ValueError, - "signal number out of range"); - return NULL; - } - old_handler = Handlers[sig_num].func; - Py_INCREF(old_handler); - return old_handler; + int sig_num; + PyObject *old_handler; + if (!PyArg_ParseTuple(args, "i:getsignal", &sig_num)) + return NULL; + if (sig_num < 1 || sig_num >= NSIG) { + PyErr_SetString(PyExc_ValueError, + "signal number out of range"); + return NULL; + } + old_handler = Handlers[sig_num].func; + Py_INCREF(old_handler); + return old_handler; } PyDoc_STRVAR(getsignal_doc, @@ -333,23 +333,23 @@ static PyObject * signal_siginterrupt(PyObject *self, PyObject *args) { - int sig_num; - int flag; + int sig_num; + int flag; - if (!PyArg_ParseTuple(args, "ii:siginterrupt", &sig_num, &flag)) - return NULL; - if (sig_num < 1 || sig_num >= NSIG) { - PyErr_SetString(PyExc_ValueError, - "signal number out of range"); - return NULL; - } - if (siginterrupt(sig_num, flag)<0) { - PyErr_SetFromErrno(PyExc_RuntimeError); - return NULL; - } + if (!PyArg_ParseTuple(args, "ii:siginterrupt", &sig_num, &flag)) + return NULL; + if (sig_num < 1 || sig_num >= NSIG) { + PyErr_SetString(PyExc_ValueError, + "signal number out of range"); + return NULL; + } + if (siginterrupt(sig_num, flag)<0) { + PyErr_SetFromErrno(PyExc_RuntimeError); + return NULL; + } - Py_INCREF(Py_None); - return Py_None; + Py_INCREF(Py_None); + return Py_None; } #endif @@ -357,24 +357,24 @@ static PyObject * signal_set_wakeup_fd(PyObject *self, PyObject *args) { - struct stat buf; - int fd, old_fd; - if (!PyArg_ParseTuple(args, "i:set_wakeup_fd", &fd)) - return NULL; + struct stat buf; + int fd, old_fd; + if (!PyArg_ParseTuple(args, "i:set_wakeup_fd", &fd)) + return NULL; #ifdef WITH_THREAD - if (PyThread_get_thread_ident() != main_thread) { - PyErr_SetString(PyExc_ValueError, - "set_wakeup_fd only works in main thread"); - return NULL; - } -#endif - if (fd != -1 && fstat(fd, &buf) != 0) { - PyErr_SetString(PyExc_ValueError, "invalid fd"); - return NULL; - } - old_fd = wakeup_fd; - wakeup_fd = fd; - return PyLong_FromLong(old_fd); + if (PyThread_get_thread_ident() != main_thread) { + PyErr_SetString(PyExc_ValueError, + "set_wakeup_fd only works in main thread"); + return NULL; + } +#endif + if (fd != -1 && fstat(fd, &buf) != 0) { + PyErr_SetString(PyExc_ValueError, "invalid fd"); + return NULL; + } + old_fd = wakeup_fd; + wakeup_fd = fd; + return PyLong_FromLong(old_fd); } PyDoc_STRVAR(set_wakeup_fd_doc, @@ -390,11 +390,11 @@ int PySignal_SetWakeupFd(int fd) { - int old_fd = wakeup_fd; - if (fd < 0) - fd = -1; - wakeup_fd = fd; - return old_fd; + int old_fd = wakeup_fd; + if (fd < 0) + fd = -1; + wakeup_fd = fd; + return old_fd; } @@ -408,14 +408,14 @@ struct itimerval new, old; if(!PyArg_ParseTuple(args, "id|d:setitimer", &which, &first, &interval)) - return NULL; + return NULL; timeval_from_double(first, &new.it_value); timeval_from_double(interval, &new.it_interval); /* Let OS check "which" value */ if (setitimer(which, &new, &old) != 0) { - PyErr_SetFromErrno(ItimerError); - return NULL; + PyErr_SetFromErrno(ItimerError); + return NULL; } return itimer_retval(&old); @@ -441,11 +441,11 @@ struct itimerval old; if (!PyArg_ParseTuple(args, "i:getitimer", &which)) - return NULL; + return NULL; if (getitimer(which, &old) != 0) { - PyErr_SetFromErrno(ItimerError); - return NULL; + PyErr_SetFromErrno(ItimerError); + return NULL; } return itimer_retval(&old); @@ -461,27 +461,27 @@ /* List of functions defined in the module */ static PyMethodDef signal_methods[] = { #ifdef HAVE_ALARM - {"alarm", signal_alarm, METH_VARARGS, alarm_doc}, + {"alarm", signal_alarm, METH_VARARGS, alarm_doc}, #endif #ifdef HAVE_SETITIMER {"setitimer", signal_setitimer, METH_VARARGS, setitimer_doc}, #endif #ifdef HAVE_GETITIMER - {"getitimer", signal_getitimer, METH_VARARGS, getitimer_doc}, + {"getitimer", signal_getitimer, METH_VARARGS, getitimer_doc}, #endif - {"signal", signal_signal, METH_VARARGS, signal_doc}, - {"getsignal", signal_getsignal, METH_VARARGS, getsignal_doc}, - {"set_wakeup_fd", signal_set_wakeup_fd, METH_VARARGS, set_wakeup_fd_doc}, + {"signal", signal_signal, METH_VARARGS, signal_doc}, + {"getsignal", signal_getsignal, METH_VARARGS, getsignal_doc}, + {"set_wakeup_fd", signal_set_wakeup_fd, METH_VARARGS, set_wakeup_fd_doc}, #ifdef HAVE_SIGINTERRUPT - {"siginterrupt", signal_siginterrupt, METH_VARARGS, siginterrupt_doc}, + {"siginterrupt", signal_siginterrupt, METH_VARARGS, siginterrupt_doc}, #endif #ifdef HAVE_PAUSE - {"pause", (PyCFunction)signal_pause, - METH_NOARGS,pause_doc}, + {"pause", (PyCFunction)signal_pause, + METH_NOARGS,pause_doc}, #endif - {"default_int_handler", signal_default_int_handler, - METH_VARARGS, default_int_handler_doc}, - {NULL, NULL} /* sentinel */ + {"default_int_handler", signal_default_int_handler, + METH_VARARGS, default_int_handler_doc}, + {NULL, NULL} /* sentinel */ }; @@ -522,264 +522,264 @@ the first is the signal number, the second is the interrupted stack frame."); static struct PyModuleDef signalmodule = { - PyModuleDef_HEAD_INIT, - "signal", - module_doc, - -1, - signal_methods, - NULL, - NULL, - NULL, - NULL + PyModuleDef_HEAD_INIT, + "signal", + module_doc, + -1, + signal_methods, + NULL, + NULL, + NULL, + NULL }; PyMODINIT_FUNC PyInit_signal(void) { - PyObject *m, *d, *x; - int i; + PyObject *m, *d, *x; + int i; #ifdef WITH_THREAD - main_thread = PyThread_get_thread_ident(); - main_pid = getpid(); + main_thread = PyThread_get_thread_ident(); + main_pid = getpid(); #endif - /* Create the module and add the functions */ - m = PyModule_Create(&signalmodule); - if (m == NULL) - return NULL; - - /* Add some symbolic constants to the module */ - d = PyModule_GetDict(m); - - x = DefaultHandler = PyLong_FromVoidPtr((void *)SIG_DFL); - if (!x || PyDict_SetItemString(d, "SIG_DFL", x) < 0) - goto finally; - - x = IgnoreHandler = PyLong_FromVoidPtr((void *)SIG_IGN); - if (!x || PyDict_SetItemString(d, "SIG_IGN", x) < 0) - goto finally; - - x = PyLong_FromLong((long)NSIG); - if (!x || PyDict_SetItemString(d, "NSIG", x) < 0) - goto finally; - Py_DECREF(x); - - x = IntHandler = PyDict_GetItemString(d, "default_int_handler"); - if (!x) - goto finally; - Py_INCREF(IntHandler); - - Handlers[0].tripped = 0; - for (i = 1; i < NSIG; i++) { - void (*t)(int); - t = PyOS_getsig(i); - Handlers[i].tripped = 0; - if (t == SIG_DFL) - Handlers[i].func = DefaultHandler; - else if (t == SIG_IGN) - Handlers[i].func = IgnoreHandler; - else - Handlers[i].func = Py_None; /* None of our business */ - Py_INCREF(Handlers[i].func); - } - if (Handlers[SIGINT].func == DefaultHandler) { - /* Install default int handler */ - Py_INCREF(IntHandler); - Py_DECREF(Handlers[SIGINT].func); - Handlers[SIGINT].func = IntHandler; - old_siginthandler = PyOS_setsig(SIGINT, signal_handler); - } + /* Create the module and add the functions */ + m = PyModule_Create(&signalmodule); + if (m == NULL) + return NULL; + + /* Add some symbolic constants to the module */ + d = PyModule_GetDict(m); + + x = DefaultHandler = PyLong_FromVoidPtr((void *)SIG_DFL); + if (!x || PyDict_SetItemString(d, "SIG_DFL", x) < 0) + goto finally; + + x = IgnoreHandler = PyLong_FromVoidPtr((void *)SIG_IGN); + if (!x || PyDict_SetItemString(d, "SIG_IGN", x) < 0) + goto finally; + + x = PyLong_FromLong((long)NSIG); + if (!x || PyDict_SetItemString(d, "NSIG", x) < 0) + goto finally; + Py_DECREF(x); + + x = IntHandler = PyDict_GetItemString(d, "default_int_handler"); + if (!x) + goto finally; + Py_INCREF(IntHandler); + + Handlers[0].tripped = 0; + for (i = 1; i < NSIG; i++) { + void (*t)(int); + t = PyOS_getsig(i); + Handlers[i].tripped = 0; + if (t == SIG_DFL) + Handlers[i].func = DefaultHandler; + else if (t == SIG_IGN) + Handlers[i].func = IgnoreHandler; + else + Handlers[i].func = Py_None; /* None of our business */ + Py_INCREF(Handlers[i].func); + } + if (Handlers[SIGINT].func == DefaultHandler) { + /* Install default int handler */ + Py_INCREF(IntHandler); + Py_DECREF(Handlers[SIGINT].func); + Handlers[SIGINT].func = IntHandler; + old_siginthandler = PyOS_setsig(SIGINT, signal_handler); + } #ifdef SIGHUP - x = PyLong_FromLong(SIGHUP); - PyDict_SetItemString(d, "SIGHUP", x); - Py_XDECREF(x); + x = PyLong_FromLong(SIGHUP); + PyDict_SetItemString(d, "SIGHUP", x); + Py_XDECREF(x); #endif #ifdef SIGINT - x = PyLong_FromLong(SIGINT); - PyDict_SetItemString(d, "SIGINT", x); - Py_XDECREF(x); + x = PyLong_FromLong(SIGINT); + PyDict_SetItemString(d, "SIGINT", x); + Py_XDECREF(x); #endif #ifdef SIGBREAK - x = PyLong_FromLong(SIGBREAK); - PyDict_SetItemString(d, "SIGBREAK", x); - Py_XDECREF(x); + x = PyLong_FromLong(SIGBREAK); + PyDict_SetItemString(d, "SIGBREAK", x); + Py_XDECREF(x); #endif #ifdef SIGQUIT - x = PyLong_FromLong(SIGQUIT); - PyDict_SetItemString(d, "SIGQUIT", x); - Py_XDECREF(x); + x = PyLong_FromLong(SIGQUIT); + PyDict_SetItemString(d, "SIGQUIT", x); + Py_XDECREF(x); #endif #ifdef SIGILL - x = PyLong_FromLong(SIGILL); - PyDict_SetItemString(d, "SIGILL", x); - Py_XDECREF(x); + x = PyLong_FromLong(SIGILL); + PyDict_SetItemString(d, "SIGILL", x); + Py_XDECREF(x); #endif #ifdef SIGTRAP - x = PyLong_FromLong(SIGTRAP); - PyDict_SetItemString(d, "SIGTRAP", x); - Py_XDECREF(x); + x = PyLong_FromLong(SIGTRAP); + PyDict_SetItemString(d, "SIGTRAP", x); + Py_XDECREF(x); #endif #ifdef SIGIOT - x = PyLong_FromLong(SIGIOT); - PyDict_SetItemString(d, "SIGIOT", x); - Py_XDECREF(x); + x = PyLong_FromLong(SIGIOT); + PyDict_SetItemString(d, "SIGIOT", x); + Py_XDECREF(x); #endif #ifdef SIGABRT - x = PyLong_FromLong(SIGABRT); - PyDict_SetItemString(d, "SIGABRT", x); - Py_XDECREF(x); + x = PyLong_FromLong(SIGABRT); + PyDict_SetItemString(d, "SIGABRT", x); + Py_XDECREF(x); #endif #ifdef SIGEMT - x = PyLong_FromLong(SIGEMT); - PyDict_SetItemString(d, "SIGEMT", x); - Py_XDECREF(x); + x = PyLong_FromLong(SIGEMT); + PyDict_SetItemString(d, "SIGEMT", x); + Py_XDECREF(x); #endif #ifdef SIGFPE - x = PyLong_FromLong(SIGFPE); - PyDict_SetItemString(d, "SIGFPE", x); - Py_XDECREF(x); + x = PyLong_FromLong(SIGFPE); + PyDict_SetItemString(d, "SIGFPE", x); + Py_XDECREF(x); #endif #ifdef SIGKILL - x = PyLong_FromLong(SIGKILL); - PyDict_SetItemString(d, "SIGKILL", x); - Py_XDECREF(x); + x = PyLong_FromLong(SIGKILL); + PyDict_SetItemString(d, "SIGKILL", x); + Py_XDECREF(x); #endif #ifdef SIGBUS - x = PyLong_FromLong(SIGBUS); - PyDict_SetItemString(d, "SIGBUS", x); - Py_XDECREF(x); + x = PyLong_FromLong(SIGBUS); + PyDict_SetItemString(d, "SIGBUS", x); + Py_XDECREF(x); #endif #ifdef SIGSEGV - x = PyLong_FromLong(SIGSEGV); - PyDict_SetItemString(d, "SIGSEGV", x); - Py_XDECREF(x); + x = PyLong_FromLong(SIGSEGV); + PyDict_SetItemString(d, "SIGSEGV", x); + Py_XDECREF(x); #endif #ifdef SIGSYS - x = PyLong_FromLong(SIGSYS); - PyDict_SetItemString(d, "SIGSYS", x); - Py_XDECREF(x); + x = PyLong_FromLong(SIGSYS); + PyDict_SetItemString(d, "SIGSYS", x); + Py_XDECREF(x); #endif #ifdef SIGPIPE - x = PyLong_FromLong(SIGPIPE); - PyDict_SetItemString(d, "SIGPIPE", x); - Py_XDECREF(x); + x = PyLong_FromLong(SIGPIPE); + PyDict_SetItemString(d, "SIGPIPE", x); + Py_XDECREF(x); #endif #ifdef SIGALRM - x = PyLong_FromLong(SIGALRM); - PyDict_SetItemString(d, "SIGALRM", x); - Py_XDECREF(x); + x = PyLong_FromLong(SIGALRM); + PyDict_SetItemString(d, "SIGALRM", x); + Py_XDECREF(x); #endif #ifdef SIGTERM - x = PyLong_FromLong(SIGTERM); - PyDict_SetItemString(d, "SIGTERM", x); - Py_XDECREF(x); + x = PyLong_FromLong(SIGTERM); + PyDict_SetItemString(d, "SIGTERM", x); + Py_XDECREF(x); #endif #ifdef SIGUSR1 - x = PyLong_FromLong(SIGUSR1); - PyDict_SetItemString(d, "SIGUSR1", x); - Py_XDECREF(x); + x = PyLong_FromLong(SIGUSR1); + PyDict_SetItemString(d, "SIGUSR1", x); + Py_XDECREF(x); #endif #ifdef SIGUSR2 - x = PyLong_FromLong(SIGUSR2); - PyDict_SetItemString(d, "SIGUSR2", x); - Py_XDECREF(x); + x = PyLong_FromLong(SIGUSR2); + PyDict_SetItemString(d, "SIGUSR2", x); + Py_XDECREF(x); #endif #ifdef SIGCLD - x = PyLong_FromLong(SIGCLD); - PyDict_SetItemString(d, "SIGCLD", x); - Py_XDECREF(x); + x = PyLong_FromLong(SIGCLD); + PyDict_SetItemString(d, "SIGCLD", x); + Py_XDECREF(x); #endif #ifdef SIGCHLD - x = PyLong_FromLong(SIGCHLD); - PyDict_SetItemString(d, "SIGCHLD", x); - Py_XDECREF(x); + x = PyLong_FromLong(SIGCHLD); + PyDict_SetItemString(d, "SIGCHLD", x); + Py_XDECREF(x); #endif #ifdef SIGPWR - x = PyLong_FromLong(SIGPWR); - PyDict_SetItemString(d, "SIGPWR", x); - Py_XDECREF(x); + x = PyLong_FromLong(SIGPWR); + PyDict_SetItemString(d, "SIGPWR", x); + Py_XDECREF(x); #endif #ifdef SIGIO - x = PyLong_FromLong(SIGIO); - PyDict_SetItemString(d, "SIGIO", x); - Py_XDECREF(x); + x = PyLong_FromLong(SIGIO); + PyDict_SetItemString(d, "SIGIO", x); + Py_XDECREF(x); #endif #ifdef SIGURG - x = PyLong_FromLong(SIGURG); - PyDict_SetItemString(d, "SIGURG", x); - Py_XDECREF(x); + x = PyLong_FromLong(SIGURG); + PyDict_SetItemString(d, "SIGURG", x); + Py_XDECREF(x); #endif #ifdef SIGWINCH - x = PyLong_FromLong(SIGWINCH); - PyDict_SetItemString(d, "SIGWINCH", x); - Py_XDECREF(x); + x = PyLong_FromLong(SIGWINCH); + PyDict_SetItemString(d, "SIGWINCH", x); + Py_XDECREF(x); #endif #ifdef SIGPOLL - x = PyLong_FromLong(SIGPOLL); - PyDict_SetItemString(d, "SIGPOLL", x); - Py_XDECREF(x); + x = PyLong_FromLong(SIGPOLL); + PyDict_SetItemString(d, "SIGPOLL", x); + Py_XDECREF(x); #endif #ifdef SIGSTOP - x = PyLong_FromLong(SIGSTOP); - PyDict_SetItemString(d, "SIGSTOP", x); - Py_XDECREF(x); + x = PyLong_FromLong(SIGSTOP); + PyDict_SetItemString(d, "SIGSTOP", x); + Py_XDECREF(x); #endif #ifdef SIGTSTP - x = PyLong_FromLong(SIGTSTP); - PyDict_SetItemString(d, "SIGTSTP", x); - Py_XDECREF(x); + x = PyLong_FromLong(SIGTSTP); + PyDict_SetItemString(d, "SIGTSTP", x); + Py_XDECREF(x); #endif #ifdef SIGCONT - x = PyLong_FromLong(SIGCONT); - PyDict_SetItemString(d, "SIGCONT", x); - Py_XDECREF(x); + x = PyLong_FromLong(SIGCONT); + PyDict_SetItemString(d, "SIGCONT", x); + Py_XDECREF(x); #endif #ifdef SIGTTIN - x = PyLong_FromLong(SIGTTIN); - PyDict_SetItemString(d, "SIGTTIN", x); - Py_XDECREF(x); + x = PyLong_FromLong(SIGTTIN); + PyDict_SetItemString(d, "SIGTTIN", x); + Py_XDECREF(x); #endif #ifdef SIGTTOU - x = PyLong_FromLong(SIGTTOU); - PyDict_SetItemString(d, "SIGTTOU", x); - Py_XDECREF(x); + x = PyLong_FromLong(SIGTTOU); + PyDict_SetItemString(d, "SIGTTOU", x); + Py_XDECREF(x); #endif #ifdef SIGVTALRM - x = PyLong_FromLong(SIGVTALRM); - PyDict_SetItemString(d, "SIGVTALRM", x); - Py_XDECREF(x); + x = PyLong_FromLong(SIGVTALRM); + PyDict_SetItemString(d, "SIGVTALRM", x); + Py_XDECREF(x); #endif #ifdef SIGPROF - x = PyLong_FromLong(SIGPROF); - PyDict_SetItemString(d, "SIGPROF", x); - Py_XDECREF(x); + x = PyLong_FromLong(SIGPROF); + PyDict_SetItemString(d, "SIGPROF", x); + Py_XDECREF(x); #endif #ifdef SIGXCPU - x = PyLong_FromLong(SIGXCPU); - PyDict_SetItemString(d, "SIGXCPU", x); - Py_XDECREF(x); + x = PyLong_FromLong(SIGXCPU); + PyDict_SetItemString(d, "SIGXCPU", x); + Py_XDECREF(x); #endif #ifdef SIGXFSZ - x = PyLong_FromLong(SIGXFSZ); - PyDict_SetItemString(d, "SIGXFSZ", x); - Py_XDECREF(x); + x = PyLong_FromLong(SIGXFSZ); + PyDict_SetItemString(d, "SIGXFSZ", x); + Py_XDECREF(x); #endif #ifdef SIGRTMIN - x = PyLong_FromLong(SIGRTMIN); - PyDict_SetItemString(d, "SIGRTMIN", x); - Py_XDECREF(x); + x = PyLong_FromLong(SIGRTMIN); + PyDict_SetItemString(d, "SIGRTMIN", x); + Py_XDECREF(x); #endif #ifdef SIGRTMAX - x = PyLong_FromLong(SIGRTMAX); - PyDict_SetItemString(d, "SIGRTMAX", x); - Py_XDECREF(x); + x = PyLong_FromLong(SIGRTMAX); + PyDict_SetItemString(d, "SIGRTMAX", x); + Py_XDECREF(x); #endif #ifdef SIGINFO - x = PyLong_FromLong(SIGINFO); - PyDict_SetItemString(d, "SIGINFO", x); - Py_XDECREF(x); + x = PyLong_FromLong(SIGINFO); + PyDict_SetItemString(d, "SIGINFO", x); + Py_XDECREF(x); #endif #ifdef ITIMER_REAL @@ -799,15 +799,15 @@ #endif #if defined (HAVE_SETITIMER) || defined (HAVE_GETITIMER) - ItimerError = PyErr_NewException("signal.ItimerError", - PyExc_IOError, NULL); + ItimerError = PyErr_NewException("signal.ItimerError", + PyExc_IOError, NULL); if (ItimerError != NULL) - PyDict_SetItemString(d, "ItimerError", ItimerError); + PyDict_SetItemString(d, "ItimerError", ItimerError); #endif if (PyErr_Occurred()) { - Py_DECREF(m); - m = NULL; + Py_DECREF(m); + m = NULL; } finally: @@ -817,28 +817,28 @@ static void finisignal(void) { - int i; - PyObject *func; + int i; + PyObject *func; - PyOS_setsig(SIGINT, old_siginthandler); - old_siginthandler = SIG_DFL; + 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 && - func != DefaultHandler && func != IgnoreHandler) - PyOS_setsig(i, SIG_DFL); - Py_XDECREF(func); - } - - Py_XDECREF(IntHandler); - IntHandler = NULL; - Py_XDECREF(DefaultHandler); - DefaultHandler = NULL; - Py_XDECREF(IgnoreHandler); - IgnoreHandler = NULL; + 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 && + func != DefaultHandler && func != IgnoreHandler) + PyOS_setsig(i, SIG_DFL); + Py_XDECREF(func); + } + + Py_XDECREF(IntHandler); + IntHandler = NULL; + Py_XDECREF(DefaultHandler); + DefaultHandler = NULL; + Py_XDECREF(IgnoreHandler); + IgnoreHandler = NULL; } @@ -846,55 +846,55 @@ int PyErr_CheckSignals(void) { - int i; - PyObject *f; + int i; + PyObject *f; - if (!is_tripped) - return 0; + if (!is_tripped) + return 0; #ifdef WITH_THREAD - if (PyThread_get_thread_ident() != main_thread) - return 0; + if (PyThread_get_thread_ident() != main_thread) + return 0; #endif - /* - * The is_tripped variable is meant to speed up the calls to - * PyErr_CheckSignals (both directly or via pending calls) when no - * signal has arrived. This variable is set to 1 when a signal arrives - * and it is set to 0 here, when we know some signals arrived. This way - * we can run the registered handlers with no signals blocked. - * - * NOTE: with this approach we can have a situation where is_tripped is - * 1 but we have no more signals to handle (Handlers[i].tripped - * is 0 for every signal i). This won't do us any harm (except - * we're gonna spent some cycles for nothing). This happens when - * we receive a signal i after we zero is_tripped and before we - * check Handlers[i].tripped. - */ - is_tripped = 0; - - if (!(f = (PyObject *)PyEval_GetFrame())) - f = Py_None; - - for (i = 1; i < NSIG; i++) { - if (Handlers[i].tripped) { - PyObject *result = NULL; - PyObject *arglist = Py_BuildValue("(iO)", i, f); - Handlers[i].tripped = 0; - - if (arglist) { - result = PyEval_CallObject(Handlers[i].func, - arglist); - Py_DECREF(arglist); - } - if (!result) - return -1; - - Py_DECREF(result); - } - } + /* + * The is_tripped variable is meant to speed up the calls to + * PyErr_CheckSignals (both directly or via pending calls) when no + * signal has arrived. This variable is set to 1 when a signal arrives + * and it is set to 0 here, when we know some signals arrived. This way + * we can run the registered handlers with no signals blocked. + * + * NOTE: with this approach we can have a situation where is_tripped is + * 1 but we have no more signals to handle (Handlers[i].tripped + * is 0 for every signal i). This won't do us any harm (except + * we're gonna spent some cycles for nothing). This happens when + * we receive a signal i after we zero is_tripped and before we + * check Handlers[i].tripped. + */ + is_tripped = 0; + + if (!(f = (PyObject *)PyEval_GetFrame())) + f = Py_None; + + for (i = 1; i < NSIG; i++) { + if (Handlers[i].tripped) { + PyObject *result = NULL; + PyObject *arglist = Py_BuildValue("(iO)", i, f); + Handlers[i].tripped = 0; + + if (arglist) { + result = PyEval_CallObject(Handlers[i].func, + arglist); + Py_DECREF(arglist); + } + if (!result) + return -1; + + Py_DECREF(result); + } + } - return 0; + return 0; } @@ -904,49 +904,49 @@ void PyErr_SetInterrupt(void) { - is_tripped = 1; - Handlers[SIGINT].tripped = 1; - Py_AddPendingCall((int (*)(void *))PyErr_CheckSignals, NULL); + is_tripped = 1; + Handlers[SIGINT].tripped = 1; + Py_AddPendingCall((int (*)(void *))PyErr_CheckSignals, NULL); } void PyOS_InitInterrupts(void) { - PyObject *m = PyInit_signal(); - if (m) { - _PyImport_FixupExtension(m, "signal", "signal"); - Py_DECREF(m); - } + PyObject *m = PyInit_signal(); + if (m) { + _PyImport_FixupExtension(m, "signal", "signal"); + Py_DECREF(m); + } } void PyOS_FiniInterrupts(void) { - finisignal(); + finisignal(); } int PyOS_InterruptOccurred(void) { - if (Handlers[SIGINT].tripped) { + if (Handlers[SIGINT].tripped) { #ifdef WITH_THREAD - if (PyThread_get_thread_ident() != main_thread) - return 0; + if (PyThread_get_thread_ident() != main_thread) + return 0; #endif - Handlers[SIGINT].tripped = 0; - return 1; - } - return 0; + Handlers[SIGINT].tripped = 0; + return 1; + } + return 0; } void PyOS_AfterFork(void) { #ifdef WITH_THREAD - PyEval_ReInitThreads(); - main_thread = PyThread_get_thread_ident(); - main_pid = getpid(); - _PyImport_ReInitLock(); - PyThread_ReInitTLS(); + PyEval_ReInitThreads(); + main_thread = PyThread_get_thread_ident(); + main_pid = getpid(); + _PyImport_ReInitLock(); + PyThread_ReInitTLS(); #endif } Modified: python/branches/release31-maint/Modules/socketmodule.c ============================================================================== --- python/branches/release31-maint/Modules/socketmodule.c (original) +++ python/branches/release31-maint/Modules/socketmodule.c Sun May 9 18:14:21 2010 @@ -17,9 +17,9 @@ - socket.error: exception raised for socket specific errors - socket.gaierror: exception raised for getaddrinfo/getnameinfo errors, - a subclass of socket.error + a subclass of socket.error - socket.herror: exception raised for gethostby* errors, - a subclass of socket.error + a subclass of socket.error - socket.gethostbyname(hostname) --> host IP address (string: 'dd.dd.dd.dd') - socket.gethostbyaddr(IP address) --> (hostname, [alias, ...], [IP addr, ...]) - socket.gethostname() --> host name (string: 'spam' or 'spam.domain.com') @@ -27,14 +27,14 @@ - socket.getservbyname(servicename[, protocolname]) --> port number - socket.getservbyport(portnumber[, protocolname]) --> service name - socket.socket([family[, type [, proto, fileno]]]) --> new socket object - (fileno specifies a pre-existing socket file descriptor) + (fileno specifies a pre-existing socket file descriptor) - socket.socketpair([family[, type [, proto]]]) --> (socket, socket) - socket.ntohs(16 bit value) --> new int object - socket.ntohl(32 bit value) --> new int object - socket.htons(16 bit value) --> new int object - socket.htonl(32 bit value) --> new int object - socket.getaddrinfo(host, port [, family, socktype, proto, flags]) - --> List of (family, socktype, proto, canonname, sockaddr) + --> List of (family, socktype, proto, canonname, sockaddr) - socket.getnameinfo(sockaddr, flags) --> (host, port) - socket.AF_INET, socket.SOCK_STREAM, etc.: constants from - socket.has_ipv6: boolean value indicating if IPv6 is supported @@ -54,22 +54,22 @@ specify packet-type and ha-type/addr. - an AF_TIPC socket address is expressed as (addr_type, v1, v2, v3 [, scope]); where addr_type can be one of: - TIPC_ADDR_NAMESEQ, TIPC_ADDR_NAME, and TIPC_ADDR_ID; + TIPC_ADDR_NAMESEQ, TIPC_ADDR_NAME, and TIPC_ADDR_ID; and scope can be one of: - TIPC_ZONE_SCOPE, TIPC_CLUSTER_SCOPE, and TIPC_NODE_SCOPE. + TIPC_ZONE_SCOPE, TIPC_CLUSTER_SCOPE, and TIPC_NODE_SCOPE. The meaning of v1, v2 and v3 depends on the value of addr_type: - if addr_type is TIPC_ADDR_NAME: - v1 is the server type - v2 is the port identifier - v3 is ignored - if addr_type is TIPC_ADDR_NAMESEQ: - v1 is the server type - v2 is the lower port number - v3 is the upper port number - if addr_type is TIPC_ADDR_ID: - v1 is the node - v2 is the ref - v3 is ignored + if addr_type is TIPC_ADDR_NAME: + v1 is the server type + v2 is the port identifier + v3 is ignored + if addr_type is TIPC_ADDR_NAMESEQ: + v1 is the server type + v2 is the lower port number + v3 is the upper port number + if addr_type is TIPC_ADDR_ID: + v1 is the node + v2 is the ref + v3 is ignored Local naming conventions: @@ -283,7 +283,7 @@ #include #ifndef offsetof -# define offsetof(type, member) ((size_t)(&((type *)0)->member)) +# define offsetof(type, member) ((size_t)(&((type *)0)->member)) #endif #ifndef O_NONBLOCK @@ -351,16 +351,16 @@ static SOCKET dup_socket(SOCKET handle) { - HANDLE newhandle; + HANDLE newhandle; - if (!DuplicateHandle(GetCurrentProcess(), (HANDLE)handle, - GetCurrentProcess(), &newhandle, - 0, FALSE, DUPLICATE_SAME_ACCESS)) - { - WSASetLastError(GetLastError()); - return INVALID_SOCKET; - } - return (SOCKET)newhandle; + if (!DuplicateHandle(GetCurrentProcess(), (HANDLE)handle, + GetCurrentProcess(), &newhandle, + 0, FALSE, DUPLICATE_SAME_ACCESS)) + { + WSASetLastError(GetLastError()); + return INVALID_SOCKET; + } + return (SOCKET)newhandle; } #define SOCKETCLOSE closesocket #else @@ -418,7 +418,7 @@ #define SEGMENT_SIZE (32 * 1024 -1) #endif -#define SAS2SA(x) ((struct sockaddr *)(x)) +#define SAS2SA(x) ((struct sockaddr *)(x)) /* * Constants for getnameinfo() @@ -473,8 +473,8 @@ static PyObject* select_error(void) { - PyErr_SetString(socket_error, "unable to select on socket"); - return NULL; + PyErr_SetString(socket_error, "unable to select on socket"); + return NULL; } /* Convenience function to raise an error according to errno @@ -484,95 +484,95 @@ set_error(void) { #ifdef MS_WINDOWS - int err_no = WSAGetLastError(); - /* PyErr_SetExcFromWindowsErr() invokes FormatMessage() which - recognizes the error codes used by both GetLastError() and - WSAGetLastError */ - if (err_no) - return PyErr_SetExcFromWindowsErr(socket_error, err_no); + int err_no = WSAGetLastError(); + /* PyErr_SetExcFromWindowsErr() invokes FormatMessage() which + recognizes the error codes used by both GetLastError() and + WSAGetLastError */ + if (err_no) + return PyErr_SetExcFromWindowsErr(socket_error, err_no); #endif #if defined(PYOS_OS2) && !defined(PYCC_GCC) - if (sock_errno() != NO_ERROR) { - APIRET rc; - ULONG msglen; - char outbuf[100]; - int myerrorcode = sock_errno(); - - /* Retrieve socket-related error message from MPTN.MSG file */ - rc = DosGetMessage(NULL, 0, outbuf, sizeof(outbuf), - myerrorcode - SOCBASEERR + 26, - "mptn.msg", - &msglen); - if (rc == NO_ERROR) { - PyObject *v; - - /* OS/2 doesn't guarantee a terminator */ - outbuf[msglen] = '\0'; - if (strlen(outbuf) > 0) { - /* If non-empty msg, trim CRLF */ - char *lastc = &outbuf[ strlen(outbuf)-1 ]; - while (lastc > outbuf && - isspace(Py_CHARMASK(*lastc))) { - /* Trim trailing whitespace (CRLF) */ - *lastc-- = '\0'; - } - } - v = Py_BuildValue("(is)", myerrorcode, outbuf); - if (v != NULL) { - PyErr_SetObject(socket_error, v); - Py_DECREF(v); - } - return NULL; - } - } + if (sock_errno() != NO_ERROR) { + APIRET rc; + ULONG msglen; + char outbuf[100]; + int myerrorcode = sock_errno(); + + /* Retrieve socket-related error message from MPTN.MSG file */ + rc = DosGetMessage(NULL, 0, outbuf, sizeof(outbuf), + myerrorcode - SOCBASEERR + 26, + "mptn.msg", + &msglen); + if (rc == NO_ERROR) { + PyObject *v; + + /* OS/2 doesn't guarantee a terminator */ + outbuf[msglen] = '\0'; + if (strlen(outbuf) > 0) { + /* If non-empty msg, trim CRLF */ + char *lastc = &outbuf[ strlen(outbuf)-1 ]; + while (lastc > outbuf && + isspace(Py_CHARMASK(*lastc))) { + /* Trim trailing whitespace (CRLF) */ + *lastc-- = '\0'; + } + } + v = Py_BuildValue("(is)", myerrorcode, outbuf); + if (v != NULL) { + PyErr_SetObject(socket_error, v); + Py_DECREF(v); + } + return NULL; + } + } #endif - return PyErr_SetFromErrno(socket_error); + return PyErr_SetFromErrno(socket_error); } static PyObject * set_herror(int h_error) { - PyObject *v; + PyObject *v; #ifdef HAVE_HSTRERROR - v = Py_BuildValue("(is)", h_error, (char *)hstrerror(h_error)); + v = Py_BuildValue("(is)", h_error, (char *)hstrerror(h_error)); #else - v = Py_BuildValue("(is)", h_error, "host not found"); + v = Py_BuildValue("(is)", h_error, "host not found"); #endif - if (v != NULL) { - PyErr_SetObject(socket_herror, v); - Py_DECREF(v); - } + if (v != NULL) { + PyErr_SetObject(socket_herror, v); + Py_DECREF(v); + } - return NULL; + return NULL; } static PyObject * set_gaierror(int error) { - PyObject *v; + PyObject *v; #ifdef EAI_SYSTEM - /* EAI_SYSTEM is not available on Windows XP. */ - if (error == EAI_SYSTEM) - return set_error(); + /* EAI_SYSTEM is not available on Windows XP. */ + if (error == EAI_SYSTEM) + return set_error(); #endif #ifdef HAVE_GAI_STRERROR - v = Py_BuildValue("(is)", error, gai_strerror(error)); + v = Py_BuildValue("(is)", error, gai_strerror(error)); #else - v = Py_BuildValue("(is)", error, "getaddrinfo failed"); + v = Py_BuildValue("(is)", error, "getaddrinfo failed"); #endif - if (v != NULL) { - PyErr_SetObject(socket_gaierror, v); - Py_DECREF(v); - } + if (v != NULL) { + PyErr_SetObject(socket_gaierror, v); + Py_DECREF(v); + } - return NULL; + return NULL; } #ifdef __VMS @@ -580,22 +580,22 @@ static int sendsegmented(int sock_fd, char *buf, int len, int flags) { - int n = 0; - int remaining = len; + int n = 0; + int remaining = len; - while (remaining > 0) { - unsigned int segment; + while (remaining > 0) { + unsigned int segment; - segment = (remaining >= SEGMENT_SIZE ? SEGMENT_SIZE : remaining); - n = send(sock_fd, buf, segment, flags); - if (n < 0) { - return n; - } - remaining -= segment; - buf += segment; - } /* end while */ + segment = (remaining >= SEGMENT_SIZE ? SEGMENT_SIZE : remaining); + n = send(sock_fd, buf, segment, flags); + if (n < 0) { + return n; + } + remaining -= segment; + buf += segment; + } /* end while */ - return len; + return len; } #endif @@ -605,33 +605,33 @@ internal_setblocking(PySocketSockObject *s, int block) { #ifndef MS_WINDOWS - int delay_flag; + int delay_flag; #endif - Py_BEGIN_ALLOW_THREADS + Py_BEGIN_ALLOW_THREADS #ifndef MS_WINDOWS #if defined(PYOS_OS2) && !defined(PYCC_GCC) - block = !block; - ioctl(s->sock_fd, FIONBIO, (caddr_t)&block, sizeof(block)); + block = !block; + ioctl(s->sock_fd, FIONBIO, (caddr_t)&block, sizeof(block)); #elif defined(__VMS) - block = !block; - ioctl(s->sock_fd, FIONBIO, (unsigned int *)&block); + block = !block; + ioctl(s->sock_fd, FIONBIO, (unsigned int *)&block); #else /* !PYOS_OS2 && !__VMS */ - delay_flag = fcntl(s->sock_fd, F_GETFL, 0); - if (block) - delay_flag &= (~O_NONBLOCK); - else - delay_flag |= O_NONBLOCK; - fcntl(s->sock_fd, F_SETFL, delay_flag); + delay_flag = fcntl(s->sock_fd, F_GETFL, 0); + if (block) + delay_flag &= (~O_NONBLOCK); + else + delay_flag |= O_NONBLOCK; + fcntl(s->sock_fd, F_SETFL, delay_flag); #endif /* !PYOS_OS2 */ #else /* MS_WINDOWS */ - block = !block; - ioctlsocket(s->sock_fd, FIONBIO, (u_long*)&block); + block = !block; + ioctlsocket(s->sock_fd, FIONBIO, (u_long*)&block); #endif /* MS_WINDOWS */ - Py_END_ALLOW_THREADS + Py_END_ALLOW_THREADS - /* Since these don't return anything */ - return 1; + /* Since these don't return anything */ + return 1; } /* Do a select()/poll() on the socket, if necessary (sock_timeout > 0). @@ -642,53 +642,53 @@ static int internal_select(PySocketSockObject *s, int writing) { - int n; + int n; - /* Nothing to do unless we're in timeout mode (not non-blocking) */ - if (s->sock_timeout <= 0.0) - return 0; - - /* Guard against closed socket */ - if (s->sock_fd < 0) - return 0; + /* Nothing to do unless we're in timeout mode (not non-blocking) */ + if (s->sock_timeout <= 0.0) + return 0; + + /* Guard against closed socket */ + if (s->sock_fd < 0) + return 0; - /* Prefer poll, if available, since you can poll() any fd - * which can't be done with select(). */ + /* Prefer poll, if available, since you can poll() any fd + * which can't be done with select(). */ #ifdef HAVE_POLL - { - struct pollfd pollfd; - int timeout; - - pollfd.fd = s->sock_fd; - pollfd.events = writing ? POLLOUT : POLLIN; - - /* s->sock_timeout is in seconds, timeout in ms */ - timeout = (int)(s->sock_timeout * 1000 + 0.5); - n = poll(&pollfd, 1, timeout); - } -#else - { - /* Construct the arguments to select */ - fd_set fds; - struct timeval tv; - tv.tv_sec = (int)s->sock_timeout; - tv.tv_usec = (int)((s->sock_timeout - tv.tv_sec) * 1e6); - FD_ZERO(&fds); - FD_SET(s->sock_fd, &fds); - - /* See if the socket is ready */ - if (writing) - n = select(s->sock_fd+1, NULL, &fds, NULL, &tv); - else - n = select(s->sock_fd+1, &fds, NULL, NULL, &tv); - } -#endif - - if (n < 0) - return -1; - if (n == 0) - return 1; - return 0; + { + struct pollfd pollfd; + int timeout; + + pollfd.fd = s->sock_fd; + pollfd.events = writing ? POLLOUT : POLLIN; + + /* s->sock_timeout is in seconds, timeout in ms */ + timeout = (int)(s->sock_timeout * 1000 + 0.5); + n = poll(&pollfd, 1, timeout); + } +#else + { + /* Construct the arguments to select */ + fd_set fds; + struct timeval tv; + tv.tv_sec = (int)s->sock_timeout; + tv.tv_usec = (int)((s->sock_timeout - tv.tv_sec) * 1e6); + FD_ZERO(&fds); + FD_SET(s->sock_fd, &fds); + + /* See if the socket is ready */ + if (writing) + n = select(s->sock_fd+1, NULL, &fds, NULL, &tv); + else + n = select(s->sock_fd+1, &fds, NULL, NULL, &tv); + } +#endif + + if (n < 0) + return -1; + if (n == 0) + return 1; + return 0; } /* Initialize a new socket object. */ @@ -697,18 +697,18 @@ static void init_sockobject(PySocketSockObject *s, - SOCKET_T fd, int family, int type, int proto) + SOCKET_T fd, int family, int type, int proto) { - s->sock_fd = fd; - s->sock_family = family; - s->sock_type = type; - s->sock_proto = proto; - s->sock_timeout = defaulttimeout; + s->sock_fd = fd; + s->sock_family = family; + s->sock_type = type; + s->sock_proto = proto; + s->sock_timeout = defaulttimeout; - s->errorhandler = &set_error; + s->errorhandler = &set_error; - if (defaulttimeout >= 0.0) - internal_setblocking(s, 0); + if (defaulttimeout >= 0.0) + internal_setblocking(s, 0); } @@ -721,12 +721,12 @@ static PySocketSockObject * new_sockobject(SOCKET_T fd, int family, int type, int proto) { - PySocketSockObject *s; - s = (PySocketSockObject *) - PyType_GenericNew(&sock_type, NULL, NULL); - if (s != NULL) - init_sockobject(s, fd, family, type, proto); - return s; + PySocketSockObject *s; + s = (PySocketSockObject *) + PyType_GenericNew(&sock_type, NULL, NULL); + if (s != NULL) + init_sockobject(s, fd, family, type, proto); + return s; } @@ -746,122 +746,122 @@ static int setipaddr(char *name, struct sockaddr *addr_ret, size_t addr_ret_size, int af) { - struct addrinfo hints, *res; - int error; - int d1, d2, d3, d4; - char ch; - - memset((void *) addr_ret, '\0', sizeof(*addr_ret)); - if (name[0] == '\0') { - int siz; - memset(&hints, 0, sizeof(hints)); - hints.ai_family = af; - hints.ai_socktype = SOCK_DGRAM; /*dummy*/ - hints.ai_flags = AI_PASSIVE; - Py_BEGIN_ALLOW_THREADS - ACQUIRE_GETADDRINFO_LOCK - error = getaddrinfo(NULL, "0", &hints, &res); - Py_END_ALLOW_THREADS - /* We assume that those thread-unsafe getaddrinfo() versions - *are* safe regarding their return value, ie. that a - subsequent call to getaddrinfo() does not destroy the - outcome of the first call. */ - RELEASE_GETADDRINFO_LOCK - if (error) { - set_gaierror(error); - return -1; - } - switch (res->ai_family) { - case AF_INET: - siz = 4; - break; + struct addrinfo hints, *res; + int error; + int d1, d2, d3, d4; + char ch; + + memset((void *) addr_ret, '\0', sizeof(*addr_ret)); + if (name[0] == '\0') { + int siz; + memset(&hints, 0, sizeof(hints)); + hints.ai_family = af; + hints.ai_socktype = SOCK_DGRAM; /*dummy*/ + hints.ai_flags = AI_PASSIVE; + Py_BEGIN_ALLOW_THREADS + ACQUIRE_GETADDRINFO_LOCK + error = getaddrinfo(NULL, "0", &hints, &res); + Py_END_ALLOW_THREADS + /* We assume that those thread-unsafe getaddrinfo() versions + *are* safe regarding their return value, ie. that a + subsequent call to getaddrinfo() does not destroy the + outcome of the first call. */ + RELEASE_GETADDRINFO_LOCK + if (error) { + set_gaierror(error); + return -1; + } + switch (res->ai_family) { + case AF_INET: + siz = 4; + break; #ifdef ENABLE_IPV6 - case AF_INET6: - siz = 16; - break; -#endif - default: - freeaddrinfo(res); - PyErr_SetString(socket_error, - "unsupported address family"); - return -1; - } - if (res->ai_next) { - freeaddrinfo(res); - PyErr_SetString(socket_error, - "wildcard resolved to multiple address"); - return -1; - } - if (res->ai_addrlen < addr_ret_size) - addr_ret_size = res->ai_addrlen; - memcpy(addr_ret, res->ai_addr, addr_ret_size); - freeaddrinfo(res); - return siz; - } - if (name[0] == '<' && strcmp(name, "") == 0) { - struct sockaddr_in *sin; - if (af != AF_INET && af != AF_UNSPEC) { - PyErr_SetString(socket_error, - "address family mismatched"); - return -1; - } - sin = (struct sockaddr_in *)addr_ret; - memset((void *) sin, '\0', sizeof(*sin)); - sin->sin_family = AF_INET; + case AF_INET6: + siz = 16; + break; +#endif + default: + freeaddrinfo(res); + PyErr_SetString(socket_error, + "unsupported address family"); + return -1; + } + if (res->ai_next) { + freeaddrinfo(res); + PyErr_SetString(socket_error, + "wildcard resolved to multiple address"); + return -1; + } + if (res->ai_addrlen < addr_ret_size) + addr_ret_size = res->ai_addrlen; + memcpy(addr_ret, res->ai_addr, addr_ret_size); + freeaddrinfo(res); + return siz; + } + if (name[0] == '<' && strcmp(name, "") == 0) { + struct sockaddr_in *sin; + if (af != AF_INET && af != AF_UNSPEC) { + PyErr_SetString(socket_error, + "address family mismatched"); + return -1; + } + sin = (struct sockaddr_in *)addr_ret; + memset((void *) sin, '\0', sizeof(*sin)); + sin->sin_family = AF_INET; #ifdef HAVE_SOCKADDR_SA_LEN - sin->sin_len = sizeof(*sin); + sin->sin_len = sizeof(*sin); #endif - sin->sin_addr.s_addr = INADDR_BROADCAST; - return sizeof(sin->sin_addr); - } - if (sscanf(name, "%d.%d.%d.%d%c", &d1, &d2, &d3, &d4, &ch) == 4 && - 0 <= d1 && d1 <= 255 && 0 <= d2 && d2 <= 255 && - 0 <= d3 && d3 <= 255 && 0 <= d4 && d4 <= 255) { - struct sockaddr_in *sin; - sin = (struct sockaddr_in *)addr_ret; - sin->sin_addr.s_addr = htonl( - ((long) d1 << 24) | ((long) d2 << 16) | - ((long) d3 << 8) | ((long) d4 << 0)); - sin->sin_family = AF_INET; + sin->sin_addr.s_addr = INADDR_BROADCAST; + return sizeof(sin->sin_addr); + } + if (sscanf(name, "%d.%d.%d.%d%c", &d1, &d2, &d3, &d4, &ch) == 4 && + 0 <= d1 && d1 <= 255 && 0 <= d2 && d2 <= 255 && + 0 <= d3 && d3 <= 255 && 0 <= d4 && d4 <= 255) { + struct sockaddr_in *sin; + sin = (struct sockaddr_in *)addr_ret; + sin->sin_addr.s_addr = htonl( + ((long) d1 << 24) | ((long) d2 << 16) | + ((long) d3 << 8) | ((long) d4 << 0)); + sin->sin_family = AF_INET; #ifdef HAVE_SOCKADDR_SA_LEN - sin->sin_len = sizeof(*sin); + sin->sin_len = sizeof(*sin); #endif - return 4; - } - memset(&hints, 0, sizeof(hints)); - hints.ai_family = af; - Py_BEGIN_ALLOW_THREADS - ACQUIRE_GETADDRINFO_LOCK - error = getaddrinfo(name, NULL, &hints, &res); + return 4; + } + memset(&hints, 0, sizeof(hints)); + hints.ai_family = af; + Py_BEGIN_ALLOW_THREADS + ACQUIRE_GETADDRINFO_LOCK + error = getaddrinfo(name, NULL, &hints, &res); #if defined(__digital__) && defined(__unix__) - if (error == EAI_NONAME && af == AF_UNSPEC) { - /* On Tru64 V5.1, numeric-to-addr conversion fails - if no address family is given. Assume IPv4 for now.*/ - hints.ai_family = AF_INET; - error = getaddrinfo(name, NULL, &hints, &res); - } -#endif - Py_END_ALLOW_THREADS - RELEASE_GETADDRINFO_LOCK /* see comment in setipaddr() */ - if (error) { - set_gaierror(error); - return -1; - } - if (res->ai_addrlen < addr_ret_size) - addr_ret_size = res->ai_addrlen; - memcpy((char *) addr_ret, res->ai_addr, addr_ret_size); - freeaddrinfo(res); - switch (addr_ret->sa_family) { - case AF_INET: - return 4; + if (error == EAI_NONAME && af == AF_UNSPEC) { + /* On Tru64 V5.1, numeric-to-addr conversion fails + if no address family is given. Assume IPv4 for now.*/ + hints.ai_family = AF_INET; + error = getaddrinfo(name, NULL, &hints, &res); + } +#endif + Py_END_ALLOW_THREADS + RELEASE_GETADDRINFO_LOCK /* see comment in setipaddr() */ + if (error) { + set_gaierror(error); + return -1; + } + if (res->ai_addrlen < addr_ret_size) + addr_ret_size = res->ai_addrlen; + memcpy((char *) addr_ret, res->ai_addr, addr_ret_size); + freeaddrinfo(res); + switch (addr_ret->sa_family) { + case AF_INET: + return 4; #ifdef ENABLE_IPV6 - case AF_INET6: - return 16; + case AF_INET6: + return 16; #endif - default: - PyErr_SetString(socket_error, "unknown address family"); - return -1; - } + default: + PyErr_SetString(socket_error, "unknown address family"); + return -1; + } } @@ -872,16 +872,16 @@ static PyObject * makeipaddr(struct sockaddr *addr, int addrlen) { - char buf[NI_MAXHOST]; - int error; + char buf[NI_MAXHOST]; + int error; - error = getnameinfo(addr, addrlen, buf, sizeof(buf), NULL, 0, - NI_NUMERICHOST); - if (error) { - set_gaierror(error); - return NULL; - } - return PyUnicode_FromString(buf); + error = getnameinfo(addr, addrlen, buf, sizeof(buf), NULL, 0, + NI_NUMERICHOST); + if (error) { + set_gaierror(error); + return NULL; + } + return PyUnicode_FromString(buf); } @@ -893,24 +893,24 @@ static int setbdaddr(char *name, bdaddr_t *bdaddr) { - unsigned int b0, b1, b2, b3, b4, b5; - char ch; - int n; - - n = sscanf(name, "%X:%X:%X:%X:%X:%X%c", - &b5, &b4, &b3, &b2, &b1, &b0, &ch); - if (n == 6 && (b0 | b1 | b2 | b3 | b4 | b5) < 256) { - bdaddr->b[0] = b0; - bdaddr->b[1] = b1; - bdaddr->b[2] = b2; - bdaddr->b[3] = b3; - bdaddr->b[4] = b4; - bdaddr->b[5] = b5; - return 6; - } else { - PyErr_SetString(socket_error, "bad bluetooth address"); - return -1; - } + unsigned int b0, b1, b2, b3, b4, b5; + char ch; + int n; + + n = sscanf(name, "%X:%X:%X:%X:%X:%X%c", + &b5, &b4, &b3, &b2, &b1, &b0, &ch); + if (n == 6 && (b0 | b1 | b2 | b3 | b4 | b5) < 256) { + bdaddr->b[0] = b0; + bdaddr->b[1] = b1; + bdaddr->b[2] = b2; + bdaddr->b[3] = b3; + bdaddr->b[4] = b4; + bdaddr->b[5] = b5; + return 6; + } else { + PyErr_SetString(socket_error, "bad bluetooth address"); + return -1; + } } /* Create a string representation of the Bluetooth address. This is always a @@ -920,12 +920,12 @@ static PyObject * makebdaddr(bdaddr_t *bdaddr) { - char buf[(6 * 2) + 5 + 1]; + char buf[(6 * 2) + 5 + 1]; - sprintf(buf, "%02X:%02X:%02X:%02X:%02X:%02X", - bdaddr->b[5], bdaddr->b[4], bdaddr->b[3], - bdaddr->b[2], bdaddr->b[1], bdaddr->b[0]); - return PyUnicode_FromString(buf); + sprintf(buf, "%02X:%02X:%02X:%02X:%02X:%02X", + bdaddr->b[5], bdaddr->b[4], bdaddr->b[3], + bdaddr->b[2], bdaddr->b[1], bdaddr->b[0]); + return PyUnicode_FromString(buf); } #endif @@ -939,193 +939,193 @@ static PyObject * makesockaddr(int sockfd, struct sockaddr *addr, int addrlen, int proto) { - if (addrlen == 0) { - /* No address -- may be recvfrom() from known socket */ - Py_INCREF(Py_None); - return Py_None; - } - - switch (addr->sa_family) { - - case AF_INET: - { - struct sockaddr_in *a; - PyObject *addrobj = makeipaddr(addr, sizeof(*a)); - PyObject *ret = NULL; - if (addrobj) { - a = (struct sockaddr_in *)addr; - ret = Py_BuildValue("Oi", addrobj, ntohs(a->sin_port)); - Py_DECREF(addrobj); - } - return ret; - } + if (addrlen == 0) { + /* No address -- may be recvfrom() from known socket */ + Py_INCREF(Py_None); + return Py_None; + } + + switch (addr->sa_family) { + + case AF_INET: + { + struct sockaddr_in *a; + PyObject *addrobj = makeipaddr(addr, sizeof(*a)); + PyObject *ret = NULL; + if (addrobj) { + a = (struct sockaddr_in *)addr; + ret = Py_BuildValue("Oi", addrobj, ntohs(a->sin_port)); + Py_DECREF(addrobj); + } + return ret; + } #if defined(AF_UNIX) - case AF_UNIX: - { - struct sockaddr_un *a = (struct sockaddr_un *) addr; + case AF_UNIX: + { + struct sockaddr_un *a = (struct sockaddr_un *) addr; #ifdef linux - if (a->sun_path[0] == 0) { /* Linux abstract namespace */ - addrlen -= offsetof(struct sockaddr_un, sun_path); - return PyBytes_FromStringAndSize(a->sun_path, addrlen); - } - else + if (a->sun_path[0] == 0) { /* Linux abstract namespace */ + addrlen -= offsetof(struct sockaddr_un, sun_path); + return PyBytes_FromStringAndSize(a->sun_path, addrlen); + } + else #endif /* linux */ - { - /* regular NULL-terminated string */ - return PyUnicode_FromString(a->sun_path); - } - } + { + /* regular NULL-terminated string */ + return PyUnicode_FromString(a->sun_path); + } + } #endif /* AF_UNIX */ #if defined(AF_NETLINK) case AF_NETLINK: { - struct sockaddr_nl *a = (struct sockaddr_nl *) addr; - return Py_BuildValue("II", a->nl_pid, a->nl_groups); + struct sockaddr_nl *a = (struct sockaddr_nl *) addr; + return Py_BuildValue("II", a->nl_pid, a->nl_groups); } #endif /* AF_NETLINK */ #ifdef ENABLE_IPV6 - case AF_INET6: - { - struct sockaddr_in6 *a; - PyObject *addrobj = makeipaddr(addr, sizeof(*a)); - PyObject *ret = NULL; - if (addrobj) { - a = (struct sockaddr_in6 *)addr; - ret = Py_BuildValue("Oiii", - addrobj, - ntohs(a->sin6_port), - a->sin6_flowinfo, - a->sin6_scope_id); - Py_DECREF(addrobj); - } - return ret; - } + case AF_INET6: + { + struct sockaddr_in6 *a; + PyObject *addrobj = makeipaddr(addr, sizeof(*a)); + PyObject *ret = NULL; + if (addrobj) { + a = (struct sockaddr_in6 *)addr; + ret = Py_BuildValue("Oiii", + addrobj, + ntohs(a->sin6_port), + a->sin6_flowinfo, + a->sin6_scope_id); + Py_DECREF(addrobj); + } + return ret; + } #endif #ifdef USE_BLUETOOTH - case AF_BLUETOOTH: - switch (proto) { + case AF_BLUETOOTH: + switch (proto) { - case BTPROTO_L2CAP: - { - struct sockaddr_l2 *a = (struct sockaddr_l2 *) addr; - PyObject *addrobj = makebdaddr(&_BT_L2_MEMB(a, bdaddr)); - PyObject *ret = NULL; - if (addrobj) { - ret = Py_BuildValue("Oi", - addrobj, - _BT_L2_MEMB(a, psm)); - Py_DECREF(addrobj); - } - return ret; - } - - case BTPROTO_RFCOMM: - { - struct sockaddr_rc *a = (struct sockaddr_rc *) addr; - PyObject *addrobj = makebdaddr(&_BT_RC_MEMB(a, bdaddr)); - PyObject *ret = NULL; - if (addrobj) { - ret = Py_BuildValue("Oi", - addrobj, - _BT_RC_MEMB(a, channel)); - Py_DECREF(addrobj); - } - return ret; - } - - case BTPROTO_HCI: - { - struct sockaddr_hci *a = (struct sockaddr_hci *) addr; - PyObject *ret = NULL; - ret = Py_BuildValue("i", _BT_HCI_MEMB(a, dev)); - return ret; - } + case BTPROTO_L2CAP: + { + struct sockaddr_l2 *a = (struct sockaddr_l2 *) addr; + PyObject *addrobj = makebdaddr(&_BT_L2_MEMB(a, bdaddr)); + PyObject *ret = NULL; + if (addrobj) { + ret = Py_BuildValue("Oi", + addrobj, + _BT_L2_MEMB(a, psm)); + Py_DECREF(addrobj); + } + return ret; + } + + case BTPROTO_RFCOMM: + { + struct sockaddr_rc *a = (struct sockaddr_rc *) addr; + PyObject *addrobj = makebdaddr(&_BT_RC_MEMB(a, bdaddr)); + PyObject *ret = NULL; + if (addrobj) { + ret = Py_BuildValue("Oi", + addrobj, + _BT_RC_MEMB(a, channel)); + Py_DECREF(addrobj); + } + return ret; + } + + case BTPROTO_HCI: + { + struct sockaddr_hci *a = (struct sockaddr_hci *) addr; + PyObject *ret = NULL; + ret = Py_BuildValue("i", _BT_HCI_MEMB(a, dev)); + return ret; + } #if !defined(__FreeBSD__) - case BTPROTO_SCO: - { - struct sockaddr_sco *a = (struct sockaddr_sco *) addr; - return makebdaddr(&_BT_SCO_MEMB(a, bdaddr)); - } + case BTPROTO_SCO: + { + struct sockaddr_sco *a = (struct sockaddr_sco *) addr; + return makebdaddr(&_BT_SCO_MEMB(a, bdaddr)); + } #endif - default: - PyErr_SetString(PyExc_ValueError, - "Unknown Bluetooth protocol"); - return NULL; - } + default: + PyErr_SetString(PyExc_ValueError, + "Unknown Bluetooth protocol"); + return NULL; + } #endif #ifdef HAVE_NETPACKET_PACKET_H - case AF_PACKET: - { - struct sockaddr_ll *a = (struct sockaddr_ll *)addr; - char *ifname = ""; - struct ifreq ifr; - /* need to look up interface name give index */ - if (a->sll_ifindex) { - ifr.ifr_ifindex = a->sll_ifindex; - if (ioctl(sockfd, SIOCGIFNAME, &ifr) == 0) - ifname = ifr.ifr_name; - } - return Py_BuildValue("shbhy#", - ifname, - ntohs(a->sll_protocol), - a->sll_pkttype, - a->sll_hatype, - a->sll_addr, - a->sll_halen); - } + case AF_PACKET: + { + struct sockaddr_ll *a = (struct sockaddr_ll *)addr; + char *ifname = ""; + struct ifreq ifr; + /* need to look up interface name give index */ + if (a->sll_ifindex) { + ifr.ifr_ifindex = a->sll_ifindex; + if (ioctl(sockfd, SIOCGIFNAME, &ifr) == 0) + ifname = ifr.ifr_name; + } + return Py_BuildValue("shbhy#", + ifname, + ntohs(a->sll_protocol), + a->sll_pkttype, + a->sll_hatype, + a->sll_addr, + a->sll_halen); + } #endif #ifdef HAVE_LINUX_TIPC_H - case AF_TIPC: - { - struct sockaddr_tipc *a = (struct sockaddr_tipc *) addr; - if (a->addrtype == TIPC_ADDR_NAMESEQ) { - return Py_BuildValue("IIIII", - a->addrtype, - a->addr.nameseq.type, - a->addr.nameseq.lower, - a->addr.nameseq.upper, - a->scope); - } else if (a->addrtype == TIPC_ADDR_NAME) { - return Py_BuildValue("IIIII", - a->addrtype, - a->addr.name.name.type, - a->addr.name.name.instance, - a->addr.name.name.instance, - a->scope); - } else if (a->addrtype == TIPC_ADDR_ID) { - return Py_BuildValue("IIIII", - a->addrtype, - a->addr.id.node, - a->addr.id.ref, - 0, - a->scope); - } else { - PyErr_SetString(PyExc_ValueError, - "Invalid address type"); - return NULL; - } - } -#endif - - /* More cases here... */ - - default: - /* If we don't know the address family, don't raise an - exception -- return it as an (int, bytes) tuple. */ - return Py_BuildValue("iy#", - addr->sa_family, - addr->sa_data, - sizeof(addr->sa_data)); + case AF_TIPC: + { + struct sockaddr_tipc *a = (struct sockaddr_tipc *) addr; + if (a->addrtype == TIPC_ADDR_NAMESEQ) { + return Py_BuildValue("IIIII", + a->addrtype, + a->addr.nameseq.type, + a->addr.nameseq.lower, + a->addr.nameseq.upper, + a->scope); + } else if (a->addrtype == TIPC_ADDR_NAME) { + return Py_BuildValue("IIIII", + a->addrtype, + a->addr.name.name.type, + a->addr.name.name.instance, + a->addr.name.name.instance, + a->scope); + } else if (a->addrtype == TIPC_ADDR_ID) { + return Py_BuildValue("IIIII", + a->addrtype, + a->addr.id.node, + a->addr.id.ref, + 0, + a->scope); + } else { + PyErr_SetString(PyExc_ValueError, + "Invalid address type"); + return NULL; + } + } +#endif + + /* More cases here... */ + + default: + /* If we don't know the address family, don't raise an + exception -- return it as an (int, bytes) tuple. */ + return Py_BuildValue("iy#", + addr->sa_family, + addr->sa_data, + sizeof(addr->sa_data)); - } + } } @@ -1136,346 +1136,346 @@ static int getsockaddrarg(PySocketSockObject *s, PyObject *args, - struct sockaddr *addr_ret, int *len_ret) + struct sockaddr *addr_ret, int *len_ret) { - switch (s->sock_family) { + switch (s->sock_family) { #if defined(AF_UNIX) - case AF_UNIX: - { - struct sockaddr_un* addr; - char *path; - int len; - if (!PyArg_Parse(args, "s#", &path, &len)) - return 0; + case AF_UNIX: + { + struct sockaddr_un* addr; + char *path; + int len; + if (!PyArg_Parse(args, "s#", &path, &len)) + return 0; - addr = (struct sockaddr_un*)addr_ret; + addr = (struct sockaddr_un*)addr_ret; #ifdef linux - if (len > 0 && path[0] == 0) { - /* Linux abstract namespace extension */ - if (len > sizeof addr->sun_path) { - PyErr_SetString(socket_error, - "AF_UNIX path too long"); - return 0; - } - } - else + if (len > 0 && path[0] == 0) { + /* Linux abstract namespace extension */ + if (len > sizeof addr->sun_path) { + PyErr_SetString(socket_error, + "AF_UNIX path too long"); + return 0; + } + } + else #endif /* linux */ - { - /* regular NULL-terminated string */ - if (len >= sizeof addr->sun_path) { - PyErr_SetString(socket_error, - "AF_UNIX path too long"); - return 0; - } - addr->sun_path[len] = 0; - } - addr->sun_family = s->sock_family; - memcpy(addr->sun_path, path, len); + { + /* regular NULL-terminated string */ + if (len >= sizeof addr->sun_path) { + PyErr_SetString(socket_error, + "AF_UNIX path too long"); + return 0; + } + addr->sun_path[len] = 0; + } + addr->sun_family = s->sock_family; + memcpy(addr->sun_path, path, len); #if defined(PYOS_OS2) - *len_ret = sizeof(*addr); + *len_ret = sizeof(*addr); #else - *len_ret = len + offsetof(struct sockaddr_un, sun_path); + *len_ret = len + offsetof(struct sockaddr_un, sun_path); #endif - return 1; - } + return 1; + } #endif /* AF_UNIX */ #if defined(AF_NETLINK) - case AF_NETLINK: - { - struct sockaddr_nl* addr; - int pid, groups; - addr = (struct sockaddr_nl *)addr_ret; - if (!PyTuple_Check(args)) { - PyErr_Format( - PyExc_TypeError, - "getsockaddrarg: " - "AF_NETLINK address must be tuple, not %.500s", - Py_TYPE(args)->tp_name); - return 0; - } - if (!PyArg_ParseTuple(args, "II:getsockaddrarg", &pid, &groups)) - return 0; - addr->nl_family = AF_NETLINK; - addr->nl_pid = pid; - addr->nl_groups = groups; - *len_ret = sizeof(*addr); - return 1; - } -#endif - - case AF_INET: - { - struct sockaddr_in* addr; - char *host; - int port, result; - if (!PyTuple_Check(args)) { - PyErr_Format( - PyExc_TypeError, - "getsockaddrarg: " - "AF_INET address must be tuple, not %.500s", - Py_TYPE(args)->tp_name); - return 0; - } - if (!PyArg_ParseTuple(args, "eti:getsockaddrarg", - "idna", &host, &port)) - return 0; - addr=(struct sockaddr_in*)addr_ret; - result = setipaddr(host, (struct sockaddr *)addr, - sizeof(*addr), AF_INET); - PyMem_Free(host); - if (result < 0) - return 0; - if (port < 0 || port > 0xffff) { - PyErr_SetString( - PyExc_OverflowError, - "getsockaddrarg: port must be 0-65535."); - return 0; - } - addr->sin_family = AF_INET; - addr->sin_port = htons((short)port); - *len_ret = sizeof *addr; - return 1; - } + case AF_NETLINK: + { + struct sockaddr_nl* addr; + int pid, groups; + addr = (struct sockaddr_nl *)addr_ret; + if (!PyTuple_Check(args)) { + PyErr_Format( + PyExc_TypeError, + "getsockaddrarg: " + "AF_NETLINK address must be tuple, not %.500s", + Py_TYPE(args)->tp_name); + return 0; + } + if (!PyArg_ParseTuple(args, "II:getsockaddrarg", &pid, &groups)) + return 0; + addr->nl_family = AF_NETLINK; + addr->nl_pid = pid; + addr->nl_groups = groups; + *len_ret = sizeof(*addr); + return 1; + } +#endif + + case AF_INET: + { + struct sockaddr_in* addr; + char *host; + int port, result; + if (!PyTuple_Check(args)) { + PyErr_Format( + PyExc_TypeError, + "getsockaddrarg: " + "AF_INET address must be tuple, not %.500s", + Py_TYPE(args)->tp_name); + return 0; + } + if (!PyArg_ParseTuple(args, "eti:getsockaddrarg", + "idna", &host, &port)) + return 0; + addr=(struct sockaddr_in*)addr_ret; + result = setipaddr(host, (struct sockaddr *)addr, + sizeof(*addr), AF_INET); + PyMem_Free(host); + if (result < 0) + return 0; + if (port < 0 || port > 0xffff) { + PyErr_SetString( + PyExc_OverflowError, + "getsockaddrarg: port must be 0-65535."); + return 0; + } + addr->sin_family = AF_INET; + addr->sin_port = htons((short)port); + *len_ret = sizeof *addr; + return 1; + } #ifdef ENABLE_IPV6 - case AF_INET6: - { - struct sockaddr_in6* addr; - char *host; - int port, flowinfo, scope_id, result; - flowinfo = scope_id = 0; - if (!PyTuple_Check(args)) { - PyErr_Format( - PyExc_TypeError, - "getsockaddrarg: " - "AF_INET6 address must be tuple, not %.500s", - Py_TYPE(args)->tp_name); - return 0; - } - if (!PyArg_ParseTuple(args, "eti|ii", - "idna", &host, &port, &flowinfo, - &scope_id)) { - return 0; - } - addr = (struct sockaddr_in6*)addr_ret; - result = setipaddr(host, (struct sockaddr *)addr, - sizeof(*addr), AF_INET6); - PyMem_Free(host); - if (result < 0) - return 0; - if (port < 0 || port > 0xffff) { - PyErr_SetString( - PyExc_OverflowError, - "getsockaddrarg: port must be 0-65535."); - return 0; - } - addr->sin6_family = s->sock_family; - addr->sin6_port = htons((short)port); - addr->sin6_flowinfo = flowinfo; - addr->sin6_scope_id = scope_id; - *len_ret = sizeof *addr; - return 1; - } + case AF_INET6: + { + struct sockaddr_in6* addr; + char *host; + int port, flowinfo, scope_id, result; + flowinfo = scope_id = 0; + if (!PyTuple_Check(args)) { + PyErr_Format( + PyExc_TypeError, + "getsockaddrarg: " + "AF_INET6 address must be tuple, not %.500s", + Py_TYPE(args)->tp_name); + return 0; + } + if (!PyArg_ParseTuple(args, "eti|ii", + "idna", &host, &port, &flowinfo, + &scope_id)) { + return 0; + } + addr = (struct sockaddr_in6*)addr_ret; + result = setipaddr(host, (struct sockaddr *)addr, + sizeof(*addr), AF_INET6); + PyMem_Free(host); + if (result < 0) + return 0; + if (port < 0 || port > 0xffff) { + PyErr_SetString( + PyExc_OverflowError, + "getsockaddrarg: port must be 0-65535."); + return 0; + } + addr->sin6_family = s->sock_family; + addr->sin6_port = htons((short)port); + addr->sin6_flowinfo = flowinfo; + addr->sin6_scope_id = scope_id; + *len_ret = sizeof *addr; + return 1; + } #endif #ifdef USE_BLUETOOTH - case AF_BLUETOOTH: - { - switch (s->sock_proto) { - case BTPROTO_L2CAP: - { - struct sockaddr_l2 *addr; - char *straddr; - - addr = (struct sockaddr_l2 *)addr_ret; - memset(addr, 0, sizeof(struct sockaddr_l2)); - _BT_L2_MEMB(addr, family) = AF_BLUETOOTH; - if (!PyArg_ParseTuple(args, "si", &straddr, - &_BT_L2_MEMB(addr, psm))) { - PyErr_SetString(socket_error, "getsockaddrarg: " - "wrong format"); - return 0; - } - if (setbdaddr(straddr, &_BT_L2_MEMB(addr, bdaddr)) < 0) - return 0; - - *len_ret = sizeof *addr; - return 1; - } - case BTPROTO_RFCOMM: - { - struct sockaddr_rc *addr; - char *straddr; - - addr = (struct sockaddr_rc *)addr_ret; - _BT_RC_MEMB(addr, family) = AF_BLUETOOTH; - if (!PyArg_ParseTuple(args, "si", &straddr, - &_BT_RC_MEMB(addr, channel))) { - PyErr_SetString(socket_error, "getsockaddrarg: " - "wrong format"); - return 0; - } - if (setbdaddr(straddr, &_BT_RC_MEMB(addr, bdaddr)) < 0) - return 0; - - *len_ret = sizeof *addr; - return 1; - } - case BTPROTO_HCI: - { - struct sockaddr_hci *addr = (struct sockaddr_hci *)addr_ret; - _BT_HCI_MEMB(addr, family) = AF_BLUETOOTH; - if (!PyArg_ParseTuple(args, "i", &_BT_HCI_MEMB(addr, dev))) { - PyErr_SetString(socket_error, "getsockaddrarg: " - "wrong format"); - return 0; - } - *len_ret = sizeof *addr; - return 1; - } + case AF_BLUETOOTH: + { + switch (s->sock_proto) { + case BTPROTO_L2CAP: + { + struct sockaddr_l2 *addr; + char *straddr; + + addr = (struct sockaddr_l2 *)addr_ret; + memset(addr, 0, sizeof(struct sockaddr_l2)); + _BT_L2_MEMB(addr, family) = AF_BLUETOOTH; + if (!PyArg_ParseTuple(args, "si", &straddr, + &_BT_L2_MEMB(addr, psm))) { + PyErr_SetString(socket_error, "getsockaddrarg: " + "wrong format"); + return 0; + } + if (setbdaddr(straddr, &_BT_L2_MEMB(addr, bdaddr)) < 0) + return 0; + + *len_ret = sizeof *addr; + return 1; + } + case BTPROTO_RFCOMM: + { + struct sockaddr_rc *addr; + char *straddr; + + addr = (struct sockaddr_rc *)addr_ret; + _BT_RC_MEMB(addr, family) = AF_BLUETOOTH; + if (!PyArg_ParseTuple(args, "si", &straddr, + &_BT_RC_MEMB(addr, channel))) { + PyErr_SetString(socket_error, "getsockaddrarg: " + "wrong format"); + return 0; + } + if (setbdaddr(straddr, &_BT_RC_MEMB(addr, bdaddr)) < 0) + return 0; + + *len_ret = sizeof *addr; + return 1; + } + case BTPROTO_HCI: + { + struct sockaddr_hci *addr = (struct sockaddr_hci *)addr_ret; + _BT_HCI_MEMB(addr, family) = AF_BLUETOOTH; + if (!PyArg_ParseTuple(args, "i", &_BT_HCI_MEMB(addr, dev))) { + PyErr_SetString(socket_error, "getsockaddrarg: " + "wrong format"); + return 0; + } + *len_ret = sizeof *addr; + return 1; + } #if !defined(__FreeBSD__) - case BTPROTO_SCO: - { - struct sockaddr_sco *addr; - char *straddr; - - addr = (struct sockaddr_sco *)addr_ret; - _BT_SCO_MEMB(addr, family) = AF_BLUETOOTH; - if (!PyBytes_Check(args)) { - PyErr_SetString(socket_error, "getsockaddrarg: " - "wrong format"); - return 0; - } - straddr = PyBytes_AS_STRING(args); - if (setbdaddr(straddr, &_BT_SCO_MEMB(addr, bdaddr)) < 0) - return 0; - - *len_ret = sizeof *addr; - return 1; - } -#endif - default: - PyErr_SetString(socket_error, "getsockaddrarg: unknown Bluetooth protocol"); - return 0; - } - } + case BTPROTO_SCO: + { + struct sockaddr_sco *addr; + char *straddr; + + addr = (struct sockaddr_sco *)addr_ret; + _BT_SCO_MEMB(addr, family) = AF_BLUETOOTH; + if (!PyBytes_Check(args)) { + PyErr_SetString(socket_error, "getsockaddrarg: " + "wrong format"); + return 0; + } + straddr = PyBytes_AS_STRING(args); + if (setbdaddr(straddr, &_BT_SCO_MEMB(addr, bdaddr)) < 0) + return 0; + + *len_ret = sizeof *addr; + return 1; + } +#endif + default: + PyErr_SetString(socket_error, "getsockaddrarg: unknown Bluetooth protocol"); + return 0; + } + } #endif #ifdef HAVE_NETPACKET_PACKET_H - case AF_PACKET: - { - struct sockaddr_ll* addr; - struct ifreq ifr; - char *interfaceName; - int protoNumber; - int hatype = 0; - int pkttype = 0; - char *haddr = NULL; - unsigned int halen = 0; - - if (!PyTuple_Check(args)) { - PyErr_Format( - PyExc_TypeError, - "getsockaddrarg: " - "AF_PACKET address must be tuple, not %.500s", - Py_TYPE(args)->tp_name); - return 0; - } - if (!PyArg_ParseTuple(args, "si|iiy#", &interfaceName, - &protoNumber, &pkttype, &hatype, - &haddr, &halen)) - return 0; - strncpy(ifr.ifr_name, interfaceName, sizeof(ifr.ifr_name)); - ifr.ifr_name[(sizeof(ifr.ifr_name))-1] = '\0'; - if (ioctl(s->sock_fd, SIOCGIFINDEX, &ifr) < 0) { - s->errorhandler(); - return 0; - } - if (halen > 8) { - PyErr_SetString(PyExc_ValueError, - "Hardware address must be 8 bytes or less"); - return 0; - } - if (protoNumber < 0 || protoNumber > 0xffff) { - PyErr_SetString( - PyExc_OverflowError, - "getsockaddrarg: protoNumber must be 0-65535."); - return 0; - } - addr = (struct sockaddr_ll*)addr_ret; - addr->sll_family = AF_PACKET; - addr->sll_protocol = htons((short)protoNumber); - addr->sll_ifindex = ifr.ifr_ifindex; - addr->sll_pkttype = pkttype; - addr->sll_hatype = hatype; - if (halen != 0) { - memcpy(&addr->sll_addr, haddr, halen); - } - addr->sll_halen = halen; - *len_ret = sizeof *addr; - return 1; - } + case AF_PACKET: + { + struct sockaddr_ll* addr; + struct ifreq ifr; + char *interfaceName; + int protoNumber; + int hatype = 0; + int pkttype = 0; + char *haddr = NULL; + unsigned int halen = 0; + + if (!PyTuple_Check(args)) { + PyErr_Format( + PyExc_TypeError, + "getsockaddrarg: " + "AF_PACKET address must be tuple, not %.500s", + Py_TYPE(args)->tp_name); + return 0; + } + if (!PyArg_ParseTuple(args, "si|iiy#", &interfaceName, + &protoNumber, &pkttype, &hatype, + &haddr, &halen)) + return 0; + strncpy(ifr.ifr_name, interfaceName, sizeof(ifr.ifr_name)); + ifr.ifr_name[(sizeof(ifr.ifr_name))-1] = '\0'; + if (ioctl(s->sock_fd, SIOCGIFINDEX, &ifr) < 0) { + s->errorhandler(); + return 0; + } + if (halen > 8) { + PyErr_SetString(PyExc_ValueError, + "Hardware address must be 8 bytes or less"); + return 0; + } + if (protoNumber < 0 || protoNumber > 0xffff) { + PyErr_SetString( + PyExc_OverflowError, + "getsockaddrarg: protoNumber must be 0-65535."); + return 0; + } + addr = (struct sockaddr_ll*)addr_ret; + addr->sll_family = AF_PACKET; + addr->sll_protocol = htons((short)protoNumber); + addr->sll_ifindex = ifr.ifr_ifindex; + addr->sll_pkttype = pkttype; + addr->sll_hatype = hatype; + if (halen != 0) { + memcpy(&addr->sll_addr, haddr, halen); + } + addr->sll_halen = halen; + *len_ret = sizeof *addr; + return 1; + } #endif #ifdef HAVE_LINUX_TIPC_H - case AF_TIPC: - { - unsigned int atype, v1, v2, v3; - unsigned int scope = TIPC_CLUSTER_SCOPE; - struct sockaddr_tipc *addr; - - if (!PyTuple_Check(args)) { - PyErr_Format( - PyExc_TypeError, - "getsockaddrarg: " - "AF_TIPC address must be tuple, not %.500s", - Py_TYPE(args)->tp_name); - return 0; - } - - if (!PyArg_ParseTuple(args, - "IIII|I;Invalid TIPC address format", - &atype, &v1, &v2, &v3, &scope)) - return 0; - - addr = (struct sockaddr_tipc *) addr_ret; - memset(addr, 0, sizeof(struct sockaddr_tipc)); - - addr->family = AF_TIPC; - addr->scope = scope; - addr->addrtype = atype; - - if (atype == TIPC_ADDR_NAMESEQ) { - addr->addr.nameseq.type = v1; - addr->addr.nameseq.lower = v2; - addr->addr.nameseq.upper = v3; - } else if (atype == TIPC_ADDR_NAME) { - addr->addr.name.name.type = v1; - addr->addr.name.name.instance = v2; - } else if (atype == TIPC_ADDR_ID) { - addr->addr.id.node = v1; - addr->addr.id.ref = v2; - } else { - /* Shouldn't happen */ - PyErr_SetString(PyExc_TypeError, "Invalid address type"); - return 0; - } - - *len_ret = sizeof(*addr); - - return 1; - } -#endif - - /* More cases here... */ - - default: - PyErr_SetString(socket_error, "getsockaddrarg: bad family"); - return 0; + case AF_TIPC: + { + unsigned int atype, v1, v2, v3; + unsigned int scope = TIPC_CLUSTER_SCOPE; + struct sockaddr_tipc *addr; + + if (!PyTuple_Check(args)) { + PyErr_Format( + PyExc_TypeError, + "getsockaddrarg: " + "AF_TIPC address must be tuple, not %.500s", + Py_TYPE(args)->tp_name); + return 0; + } + + if (!PyArg_ParseTuple(args, + "IIII|I;Invalid TIPC address format", + &atype, &v1, &v2, &v3, &scope)) + return 0; + + addr = (struct sockaddr_tipc *) addr_ret; + memset(addr, 0, sizeof(struct sockaddr_tipc)); + + addr->family = AF_TIPC; + addr->scope = scope; + addr->addrtype = atype; + + if (atype == TIPC_ADDR_NAMESEQ) { + addr->addr.nameseq.type = v1; + addr->addr.nameseq.lower = v2; + addr->addr.nameseq.upper = v3; + } else if (atype == TIPC_ADDR_NAME) { + addr->addr.name.name.type = v1; + addr->addr.name.name.instance = v2; + } else if (atype == TIPC_ADDR_ID) { + addr->addr.id.node = v1; + addr->addr.id.ref = v2; + } else { + /* Shouldn't happen */ + PyErr_SetString(PyExc_TypeError, "Invalid address type"); + return 0; + } + + *len_ret = sizeof(*addr); + + return 1; + } +#endif + + /* More cases here... */ + + default: + PyErr_SetString(socket_error, "getsockaddrarg: bad family"); + return 0; - } + } } @@ -1486,89 +1486,89 @@ static int getsockaddrlen(PySocketSockObject *s, socklen_t *len_ret) { - switch (s->sock_family) { + switch (s->sock_family) { #if defined(AF_UNIX) - case AF_UNIX: - { - *len_ret = sizeof (struct sockaddr_un); - return 1; - } + case AF_UNIX: + { + *len_ret = sizeof (struct sockaddr_un); + return 1; + } #endif /* AF_UNIX */ #if defined(AF_NETLINK) case AF_NETLINK: { - *len_ret = sizeof (struct sockaddr_nl); - return 1; + *len_ret = sizeof (struct sockaddr_nl); + return 1; } #endif - case AF_INET: - { - *len_ret = sizeof (struct sockaddr_in); - return 1; - } + case AF_INET: + { + *len_ret = sizeof (struct sockaddr_in); + return 1; + } #ifdef ENABLE_IPV6 - case AF_INET6: - { - *len_ret = sizeof (struct sockaddr_in6); - return 1; - } + case AF_INET6: + { + *len_ret = sizeof (struct sockaddr_in6); + return 1; + } #endif #ifdef USE_BLUETOOTH - case AF_BLUETOOTH: - { - switch(s->sock_proto) - { - - case BTPROTO_L2CAP: - *len_ret = sizeof (struct sockaddr_l2); - return 1; - case BTPROTO_RFCOMM: - *len_ret = sizeof (struct sockaddr_rc); - return 1; - case BTPROTO_HCI: - *len_ret = sizeof (struct sockaddr_hci); - return 1; + case AF_BLUETOOTH: + { + switch(s->sock_proto) + { + + case BTPROTO_L2CAP: + *len_ret = sizeof (struct sockaddr_l2); + return 1; + case BTPROTO_RFCOMM: + *len_ret = sizeof (struct sockaddr_rc); + return 1; + case BTPROTO_HCI: + *len_ret = sizeof (struct sockaddr_hci); + return 1; #if !defined(__FreeBSD__) - case BTPROTO_SCO: - *len_ret = sizeof (struct sockaddr_sco); - return 1; -#endif - default: - PyErr_SetString(socket_error, "getsockaddrlen: " - "unknown BT protocol"); - return 0; + case BTPROTO_SCO: + *len_ret = sizeof (struct sockaddr_sco); + return 1; +#endif + default: + PyErr_SetString(socket_error, "getsockaddrlen: " + "unknown BT protocol"); + return 0; - } - } + } + } #endif #ifdef HAVE_NETPACKET_PACKET_H - case AF_PACKET: - { - *len_ret = sizeof (struct sockaddr_ll); - return 1; - } + case AF_PACKET: + { + *len_ret = sizeof (struct sockaddr_ll); + return 1; + } #endif #ifdef HAVE_LINUX_TIPC_H - case AF_TIPC: - { - *len_ret = sizeof (struct sockaddr_tipc); - return 1; - } + case AF_TIPC: + { + *len_ret = sizeof (struct sockaddr_tipc); + return 1; + } #endif - /* More cases here... */ + /* More cases here... */ - default: - PyErr_SetString(socket_error, "getsockaddrlen: bad family"); - return 0; + default: + PyErr_SetString(socket_error, "getsockaddrlen: bad family"); + return 0; - } + } } @@ -1577,52 +1577,52 @@ static PyObject * sock_accept(PySocketSockObject *s) { - sock_addr_t addrbuf; - SOCKET_T newfd = INVALID_SOCKET; - socklen_t addrlen; - PyObject *sock = NULL; - PyObject *addr = NULL; - PyObject *res = NULL; - int timeout; - - if (!getsockaddrlen(s, &addrlen)) - return NULL; - memset(&addrbuf, 0, addrlen); - - if (!IS_SELECTABLE(s)) - return select_error(); - - Py_BEGIN_ALLOW_THREADS - timeout = internal_select(s, 0); - if (!timeout) - newfd = accept(s->sock_fd, SAS2SA(&addrbuf), &addrlen); - Py_END_ALLOW_THREADS - - if (timeout == 1) { - PyErr_SetString(socket_timeout, "timed out"); - return NULL; - } - - if (newfd == INVALID_SOCKET) - return s->errorhandler(); - - sock = PyLong_FromSocket_t(newfd); - if (sock == NULL) { - SOCKETCLOSE(newfd); - goto finally; - } - - addr = makesockaddr(s->sock_fd, SAS2SA(&addrbuf), - addrlen, s->sock_proto); - if (addr == NULL) - goto finally; + sock_addr_t addrbuf; + SOCKET_T newfd = INVALID_SOCKET; + socklen_t addrlen; + PyObject *sock = NULL; + PyObject *addr = NULL; + PyObject *res = NULL; + int timeout; + + if (!getsockaddrlen(s, &addrlen)) + return NULL; + memset(&addrbuf, 0, addrlen); + + if (!IS_SELECTABLE(s)) + return select_error(); + + Py_BEGIN_ALLOW_THREADS + timeout = internal_select(s, 0); + if (!timeout) + newfd = accept(s->sock_fd, SAS2SA(&addrbuf), &addrlen); + Py_END_ALLOW_THREADS + + if (timeout == 1) { + PyErr_SetString(socket_timeout, "timed out"); + return NULL; + } + + if (newfd == INVALID_SOCKET) + return s->errorhandler(); + + sock = PyLong_FromSocket_t(newfd); + if (sock == NULL) { + SOCKETCLOSE(newfd); + goto finally; + } + + addr = makesockaddr(s->sock_fd, SAS2SA(&addrbuf), + addrlen, s->sock_proto); + if (addr == NULL) + goto finally; - res = PyTuple_Pack(2, sock, addr); + res = PyTuple_Pack(2, sock, addr); finally: - Py_XDECREF(sock); - Py_XDECREF(addr); - return res; + Py_XDECREF(sock); + Py_XDECREF(addr); + return res; } PyDoc_STRVAR(accept_doc, @@ -1640,17 +1640,17 @@ static PyObject * sock_setblocking(PySocketSockObject *s, PyObject *arg) { - int block; + int block; - block = PyLong_AsLong(arg); - if (block == -1 && PyErr_Occurred()) - return NULL; + block = PyLong_AsLong(arg); + if (block == -1 && PyErr_Occurred()) + return NULL; - s->sock_timeout = block ? -1.0 : 0.0; - internal_setblocking(s, block); + s->sock_timeout = block ? -1.0 : 0.0; + internal_setblocking(s, block); - Py_INCREF(Py_None); - return Py_None; + Py_INCREF(Py_None); + return Py_None; } PyDoc_STRVAR(setblocking_doc, @@ -1669,25 +1669,25 @@ static PyObject * sock_settimeout(PySocketSockObject *s, PyObject *arg) { - double timeout; + double timeout; - if (arg == Py_None) - timeout = -1.0; - else { - timeout = PyFloat_AsDouble(arg); - if (timeout < 0.0) { - if (!PyErr_Occurred()) - PyErr_SetString(PyExc_ValueError, - "Timeout value out of range"); - return NULL; - } - } + if (arg == Py_None) + timeout = -1.0; + else { + timeout = PyFloat_AsDouble(arg); + if (timeout < 0.0) { + if (!PyErr_Occurred()) + PyErr_SetString(PyExc_ValueError, + "Timeout value out of range"); + return NULL; + } + } - s->sock_timeout = timeout; - internal_setblocking(s, timeout < 0.0); + s->sock_timeout = timeout; + internal_setblocking(s, timeout < 0.0); - Py_INCREF(Py_None); - return Py_None; + Py_INCREF(Py_None); + return Py_None; } PyDoc_STRVAR(settimeout_doc, @@ -1703,12 +1703,12 @@ static PyObject * sock_gettimeout(PySocketSockObject *s) { - if (s->sock_timeout < 0.0) { - Py_INCREF(Py_None); - return Py_None; - } - else - return PyFloat_FromDouble(s->sock_timeout); + if (s->sock_timeout < 0.0) { + Py_INCREF(Py_None); + return Py_None; + } + else + return PyFloat_FromDouble(s->sock_timeout); } PyDoc_STRVAR(gettimeout_doc, @@ -1726,29 +1726,29 @@ static PyObject * sock_setsockopt(PySocketSockObject *s, PyObject *args) { - int level; - int optname; - int res; - char *buf; - int buflen; - int flag; - - if (PyArg_ParseTuple(args, "iii:setsockopt", - &level, &optname, &flag)) { - buf = (char *) &flag; - buflen = sizeof flag; - } - else { - PyErr_Clear(); - if (!PyArg_ParseTuple(args, "iiy#:setsockopt", - &level, &optname, &buf, &buflen)) - return NULL; - } - res = setsockopt(s->sock_fd, level, optname, (void *)buf, buflen); - if (res < 0) - return s->errorhandler(); - Py_INCREF(Py_None); - return Py_None; + int level; + int optname; + int res; + char *buf; + int buflen; + int flag; + + if (PyArg_ParseTuple(args, "iii:setsockopt", + &level, &optname, &flag)) { + buf = (char *) &flag; + buflen = sizeof flag; + } + else { + PyErr_Clear(); + if (!PyArg_ParseTuple(args, "iiy#:setsockopt", + &level, &optname, &buf, &buflen)) + return NULL; + } + res = setsockopt(s->sock_fd, level, optname, (void *)buf, buflen); + if (res < 0) + return s->errorhandler(); + Py_INCREF(Py_None); + return Py_None; } PyDoc_STRVAR(setsockopt_doc, @@ -1766,47 +1766,47 @@ static PyObject * sock_getsockopt(PySocketSockObject *s, PyObject *args) { - int level; - int optname; - int res; - PyObject *buf; - socklen_t buflen = 0; - - if (!PyArg_ParseTuple(args, "ii|i:getsockopt", - &level, &optname, &buflen)) - return NULL; - - if (buflen == 0) { - int flag = 0; - socklen_t flagsize = sizeof flag; - res = getsockopt(s->sock_fd, level, optname, - (void *)&flag, &flagsize); - if (res < 0) - return s->errorhandler(); - return PyLong_FromLong(flag); - } + int level; + int optname; + int res; + PyObject *buf; + socklen_t buflen = 0; + + if (!PyArg_ParseTuple(args, "ii|i:getsockopt", + &level, &optname, &buflen)) + return NULL; + + if (buflen == 0) { + int flag = 0; + socklen_t flagsize = sizeof flag; + res = getsockopt(s->sock_fd, level, optname, + (void *)&flag, &flagsize); + if (res < 0) + return s->errorhandler(); + return PyLong_FromLong(flag); + } #ifdef __VMS - /* socklen_t is unsigned so no negative test is needed, - test buflen == 0 is previously done */ - if (buflen > 1024) { -#else - if (buflen <= 0 || buflen > 1024) { -#endif - PyErr_SetString(socket_error, - "getsockopt buflen out of range"); - return NULL; - } - buf = PyBytes_FromStringAndSize((char *)NULL, buflen); - if (buf == NULL) - return NULL; - res = getsockopt(s->sock_fd, level, optname, - (void *)PyBytes_AS_STRING(buf), &buflen); - if (res < 0) { - Py_DECREF(buf); - return s->errorhandler(); - } - _PyBytes_Resize(&buf, buflen); - return buf; + /* socklen_t is unsigned so no negative test is needed, + test buflen == 0 is previously done */ + if (buflen > 1024) { +#else + if (buflen <= 0 || buflen > 1024) { +#endif + PyErr_SetString(socket_error, + "getsockopt buflen out of range"); + return NULL; + } + buf = PyBytes_FromStringAndSize((char *)NULL, buflen); + if (buf == NULL) + return NULL; + res = getsockopt(s->sock_fd, level, optname, + (void *)PyBytes_AS_STRING(buf), &buflen); + if (res < 0) { + Py_DECREF(buf); + return s->errorhandler(); + } + _PyBytes_Resize(&buf, buflen); + return buf; } PyDoc_STRVAR(getsockopt_doc, @@ -1822,19 +1822,19 @@ static PyObject * sock_bind(PySocketSockObject *s, PyObject *addro) { - sock_addr_t addrbuf; - int addrlen; - int res; - - if (!getsockaddrarg(s, addro, SAS2SA(&addrbuf), &addrlen)) - return NULL; - Py_BEGIN_ALLOW_THREADS - res = bind(s->sock_fd, SAS2SA(&addrbuf), addrlen); - Py_END_ALLOW_THREADS - if (res < 0) - return s->errorhandler(); - Py_INCREF(Py_None); - return Py_None; + sock_addr_t addrbuf; + int addrlen; + int res; + + if (!getsockaddrarg(s, addro, SAS2SA(&addrbuf), &addrlen)) + return NULL; + Py_BEGIN_ALLOW_THREADS + res = bind(s->sock_fd, SAS2SA(&addrbuf), addrlen); + Py_END_ALLOW_THREADS + if (res < 0) + return s->errorhandler(); + Py_INCREF(Py_None); + return Py_None; } PyDoc_STRVAR(bind_doc, @@ -1852,16 +1852,16 @@ static PyObject * sock_close(PySocketSockObject *s) { - SOCKET_T fd; + SOCKET_T fd; - if ((fd = s->sock_fd) != -1) { - s->sock_fd = -1; - Py_BEGIN_ALLOW_THREADS - (void) SOCKETCLOSE(fd); - Py_END_ALLOW_THREADS - } - Py_INCREF(Py_None); - return Py_None; + if ((fd = s->sock_fd) != -1) { + s->sock_fd = -1; + Py_BEGIN_ALLOW_THREADS + (void) SOCKETCLOSE(fd); + Py_END_ALLOW_THREADS + } + Py_INCREF(Py_None); + return Py_None; } PyDoc_STRVAR(close_doc, @@ -1871,90 +1871,90 @@ static int internal_connect(PySocketSockObject *s, struct sockaddr *addr, int addrlen, - int *timeoutp) + int *timeoutp) { - int res, timeout; + int res, timeout; - timeout = 0; - res = connect(s->sock_fd, addr, addrlen); + timeout = 0; + res = connect(s->sock_fd, addr, addrlen); #ifdef MS_WINDOWS - if (s->sock_timeout > 0.0) { - if (res < 0 && WSAGetLastError() == WSAEWOULDBLOCK && - IS_SELECTABLE(s)) { - /* This is a mess. Best solution: trust select */ - fd_set fds; - fd_set fds_exc; - struct timeval tv; - tv.tv_sec = (int)s->sock_timeout; - tv.tv_usec = (int)((s->sock_timeout - tv.tv_sec) * 1e6); - FD_ZERO(&fds); - FD_SET(s->sock_fd, &fds); - FD_ZERO(&fds_exc); - FD_SET(s->sock_fd, &fds_exc); - res = select(s->sock_fd+1, NULL, &fds, &fds_exc, &tv); - if (res == 0) { - res = WSAEWOULDBLOCK; - timeout = 1; - } else if (res > 0) { - if (FD_ISSET(s->sock_fd, &fds)) - /* The socket is in the writable set - this - means connected */ - res = 0; - else { - /* As per MS docs, we need to call getsockopt() - to get the underlying error */ - int res_size = sizeof res; - /* It must be in the exception set */ - assert(FD_ISSET(s->sock_fd, &fds_exc)); - if (0 == getsockopt(s->sock_fd, SOL_SOCKET, SO_ERROR, - (char *)&res, &res_size)) - /* getsockopt also clears WSAGetLastError, - so reset it back. */ - WSASetLastError(res); - else - res = WSAGetLastError(); - } - } - /* else if (res < 0) an error occurred */ - } - } - - if (res < 0) - res = WSAGetLastError(); - -#else - - if (s->sock_timeout > 0.0) { - if (res < 0 && errno == EINPROGRESS && IS_SELECTABLE(s)) { - timeout = internal_select(s, 1); - if (timeout == 0) { - /* Bug #1019808: in case of an EINPROGRESS, - use getsockopt(SO_ERROR) to get the real - error. */ - socklen_t res_size = sizeof res; - (void)getsockopt(s->sock_fd, SOL_SOCKET, - SO_ERROR, &res, &res_size); - if (res == EISCONN) - res = 0; - errno = res; - } - else if (timeout == -1) { - res = errno; /* had error */ - } - else - res = EWOULDBLOCK; /* timed out */ - } - } + if (s->sock_timeout > 0.0) { + if (res < 0 && WSAGetLastError() == WSAEWOULDBLOCK && + IS_SELECTABLE(s)) { + /* This is a mess. Best solution: trust select */ + fd_set fds; + fd_set fds_exc; + struct timeval tv; + tv.tv_sec = (int)s->sock_timeout; + tv.tv_usec = (int)((s->sock_timeout - tv.tv_sec) * 1e6); + FD_ZERO(&fds); + FD_SET(s->sock_fd, &fds); + FD_ZERO(&fds_exc); + FD_SET(s->sock_fd, &fds_exc); + res = select(s->sock_fd+1, NULL, &fds, &fds_exc, &tv); + if (res == 0) { + res = WSAEWOULDBLOCK; + timeout = 1; + } else if (res > 0) { + if (FD_ISSET(s->sock_fd, &fds)) + /* The socket is in the writable set - this + means connected */ + res = 0; + else { + /* As per MS docs, we need to call getsockopt() + to get the underlying error */ + int res_size = sizeof res; + /* It must be in the exception set */ + assert(FD_ISSET(s->sock_fd, &fds_exc)); + if (0 == getsockopt(s->sock_fd, SOL_SOCKET, SO_ERROR, + (char *)&res, &res_size)) + /* getsockopt also clears WSAGetLastError, + so reset it back. */ + WSASetLastError(res); + else + res = WSAGetLastError(); + } + } + /* else if (res < 0) an error occurred */ + } + } + + if (res < 0) + res = WSAGetLastError(); + +#else + + if (s->sock_timeout > 0.0) { + if (res < 0 && errno == EINPROGRESS && IS_SELECTABLE(s)) { + timeout = internal_select(s, 1); + if (timeout == 0) { + /* Bug #1019808: in case of an EINPROGRESS, + use getsockopt(SO_ERROR) to get the real + error. */ + socklen_t res_size = sizeof res; + (void)getsockopt(s->sock_fd, SOL_SOCKET, + SO_ERROR, &res, &res_size); + if (res == EISCONN) + res = 0; + errno = res; + } + else if (timeout == -1) { + res = errno; /* had error */ + } + else + res = EWOULDBLOCK; /* timed out */ + } + } - if (res < 0) - res = errno; + if (res < 0) + res = errno; #endif - *timeoutp = timeout; + *timeoutp = timeout; - return res; + return res; } /* s.connect(sockaddr) method */ @@ -1962,26 +1962,26 @@ static PyObject * sock_connect(PySocketSockObject *s, PyObject *addro) { - sock_addr_t addrbuf; - int addrlen; - int res; - int timeout; - - if (!getsockaddrarg(s, addro, SAS2SA(&addrbuf), &addrlen)) - return NULL; - - Py_BEGIN_ALLOW_THREADS - res = internal_connect(s, SAS2SA(&addrbuf), addrlen, &timeout); - Py_END_ALLOW_THREADS - - if (timeout == 1) { - PyErr_SetString(socket_timeout, "timed out"); - return NULL; - } - if (res != 0) - return s->errorhandler(); - Py_INCREF(Py_None); - return Py_None; + sock_addr_t addrbuf; + int addrlen; + int res; + int timeout; + + if (!getsockaddrarg(s, addro, SAS2SA(&addrbuf), &addrlen)) + return NULL; + + Py_BEGIN_ALLOW_THREADS + res = internal_connect(s, SAS2SA(&addrbuf), addrlen, &timeout); + Py_END_ALLOW_THREADS + + if (timeout == 1) { + PyErr_SetString(socket_timeout, "timed out"); + return NULL; + } + if (res != 0) + return s->errorhandler(); + Py_INCREF(Py_None); + return Py_None; } PyDoc_STRVAR(connect_doc, @@ -1996,26 +1996,26 @@ static PyObject * sock_connect_ex(PySocketSockObject *s, PyObject *addro) { - sock_addr_t addrbuf; - int addrlen; - int res; - int timeout; - - if (!getsockaddrarg(s, addro, SAS2SA(&addrbuf), &addrlen)) - return NULL; - - Py_BEGIN_ALLOW_THREADS - res = internal_connect(s, SAS2SA(&addrbuf), addrlen, &timeout); - Py_END_ALLOW_THREADS + sock_addr_t addrbuf; + int addrlen; + int res; + int timeout; + + if (!getsockaddrarg(s, addro, SAS2SA(&addrbuf), &addrlen)) + return NULL; + + Py_BEGIN_ALLOW_THREADS + res = internal_connect(s, SAS2SA(&addrbuf), addrlen, &timeout); + Py_END_ALLOW_THREADS - /* Signals are not errors (though they may raise exceptions). Adapted - from PyErr_SetFromErrnoWithFilenameObject(). */ + /* Signals are not errors (though they may raise exceptions). Adapted + from PyErr_SetFromErrnoWithFilenameObject(). */ #ifdef EINTR - if (res == EINTR && PyErr_CheckSignals()) - return NULL; + if (res == EINTR && PyErr_CheckSignals()) + return NULL; #endif - return PyLong_FromLong((long) res); + return PyLong_FromLong((long) res); } PyDoc_STRVAR(connect_ex_doc, @@ -2030,7 +2030,7 @@ static PyObject * sock_fileno(PySocketSockObject *s) { - return PyLong_FromSocket_t(s->sock_fd); + return PyLong_FromSocket_t(s->sock_fd); } PyDoc_STRVAR(fileno_doc, @@ -2044,20 +2044,20 @@ static PyObject * sock_getsockname(PySocketSockObject *s) { - sock_addr_t addrbuf; - int res; - socklen_t addrlen; - - if (!getsockaddrlen(s, &addrlen)) - return NULL; - memset(&addrbuf, 0, addrlen); - Py_BEGIN_ALLOW_THREADS - res = getsockname(s->sock_fd, SAS2SA(&addrbuf), &addrlen); - Py_END_ALLOW_THREADS - if (res < 0) - return s->errorhandler(); - return makesockaddr(s->sock_fd, SAS2SA(&addrbuf), addrlen, - s->sock_proto); + sock_addr_t addrbuf; + int res; + socklen_t addrlen; + + if (!getsockaddrlen(s, &addrlen)) + return NULL; + memset(&addrbuf, 0, addrlen); + Py_BEGIN_ALLOW_THREADS + res = getsockname(s->sock_fd, SAS2SA(&addrbuf), &addrlen); + Py_END_ALLOW_THREADS + if (res < 0) + return s->errorhandler(); + return makesockaddr(s->sock_fd, SAS2SA(&addrbuf), addrlen, + s->sock_proto); } PyDoc_STRVAR(getsockname_doc, @@ -2067,26 +2067,26 @@ info is a pair (hostaddr, port)."); -#ifdef HAVE_GETPEERNAME /* Cray APP doesn't have this :-( */ +#ifdef HAVE_GETPEERNAME /* Cray APP doesn't have this :-( */ /* s.getpeername() method */ static PyObject * sock_getpeername(PySocketSockObject *s) { - sock_addr_t addrbuf; - int res; - socklen_t addrlen; - - if (!getsockaddrlen(s, &addrlen)) - return NULL; - memset(&addrbuf, 0, addrlen); - Py_BEGIN_ALLOW_THREADS - res = getpeername(s->sock_fd, SAS2SA(&addrbuf), &addrlen); - Py_END_ALLOW_THREADS - if (res < 0) - return s->errorhandler(); - return makesockaddr(s->sock_fd, SAS2SA(&addrbuf), addrlen, - s->sock_proto); + sock_addr_t addrbuf; + int res; + socklen_t addrlen; + + if (!getsockaddrlen(s, &addrlen)) + return NULL; + memset(&addrbuf, 0, addrlen); + Py_BEGIN_ALLOW_THREADS + res = getpeername(s->sock_fd, SAS2SA(&addrbuf), &addrlen); + Py_END_ALLOW_THREADS + if (res < 0) + return s->errorhandler(); + return makesockaddr(s->sock_fd, SAS2SA(&addrbuf), addrlen, + s->sock_proto); } PyDoc_STRVAR(getpeername_doc, @@ -2103,21 +2103,21 @@ static PyObject * sock_listen(PySocketSockObject *s, PyObject *arg) { - int backlog; - int res; + int backlog; + int res; - backlog = PyLong_AsLong(arg); - if (backlog == -1 && PyErr_Occurred()) - return NULL; - Py_BEGIN_ALLOW_THREADS - if (backlog < 1) - backlog = 1; - res = listen(s->sock_fd, backlog); - Py_END_ALLOW_THREADS - if (res < 0) - return s->errorhandler(); - Py_INCREF(Py_None); - return Py_None; + backlog = PyLong_AsLong(arg); + if (backlog == -1 && PyErr_Occurred()) + return NULL; + Py_BEGIN_ALLOW_THREADS + if (backlog < 1) + backlog = 1; + res = listen(s->sock_fd, backlog); + Py_END_ALLOW_THREADS + if (res < 0) + return s->errorhandler(); + Py_INCREF(Py_None); + return Py_None; } PyDoc_STRVAR(listen_doc, @@ -2139,80 +2139,80 @@ static ssize_t sock_recv_guts(PySocketSockObject *s, char* cbuf, int len, int flags) { - ssize_t outlen = -1; - int timeout; + ssize_t outlen = -1; + int timeout; #ifdef __VMS - int remaining; - char *read_buf; + int remaining; + char *read_buf; #endif - if (!IS_SELECTABLE(s)) { - select_error(); - return -1; - } - if (len == 0) { - /* If 0 bytes were requested, do nothing. */ - return 0; - } + if (!IS_SELECTABLE(s)) { + select_error(); + return -1; + } + if (len == 0) { + /* If 0 bytes were requested, do nothing. */ + return 0; + } #ifndef __VMS - Py_BEGIN_ALLOW_THREADS - timeout = internal_select(s, 0); - if (!timeout) - outlen = recv(s->sock_fd, cbuf, len, flags); - Py_END_ALLOW_THREADS - - if (timeout == 1) { - PyErr_SetString(socket_timeout, "timed out"); - return -1; - } - if (outlen < 0) { - /* Note: the call to errorhandler() ALWAYS indirectly returned - NULL, so ignore its return value */ - s->errorhandler(); - return -1; - } -#else - read_buf = cbuf; - remaining = len; - while (remaining != 0) { - unsigned int segment; - int nread = -1; - - segment = remaining /SEGMENT_SIZE; - if (segment != 0) { - segment = SEGMENT_SIZE; - } - else { - segment = remaining; - } - - Py_BEGIN_ALLOW_THREADS - timeout = internal_select(s, 0); - if (!timeout) - nread = recv(s->sock_fd, read_buf, segment, flags); - Py_END_ALLOW_THREADS - - if (timeout == 1) { - PyErr_SetString(socket_timeout, "timed out"); - return -1; - } - if (nread < 0) { - s->errorhandler(); - return -1; - } - if (nread != remaining) { - read_buf += nread; - break; - } - - remaining -= segment; - read_buf += segment; - } - outlen = read_buf - cbuf; + Py_BEGIN_ALLOW_THREADS + timeout = internal_select(s, 0); + if (!timeout) + outlen = recv(s->sock_fd, cbuf, len, flags); + Py_END_ALLOW_THREADS + + if (timeout == 1) { + PyErr_SetString(socket_timeout, "timed out"); + return -1; + } + if (outlen < 0) { + /* Note: the call to errorhandler() ALWAYS indirectly returned + NULL, so ignore its return value */ + s->errorhandler(); + return -1; + } +#else + read_buf = cbuf; + remaining = len; + while (remaining != 0) { + unsigned int segment; + int nread = -1; + + segment = remaining /SEGMENT_SIZE; + if (segment != 0) { + segment = SEGMENT_SIZE; + } + else { + segment = remaining; + } + + Py_BEGIN_ALLOW_THREADS + timeout = internal_select(s, 0); + if (!timeout) + nread = recv(s->sock_fd, read_buf, segment, flags); + Py_END_ALLOW_THREADS + + if (timeout == 1) { + PyErr_SetString(socket_timeout, "timed out"); + return -1; + } + if (nread < 0) { + s->errorhandler(); + return -1; + } + if (nread != remaining) { + read_buf += nread; + break; + } + + remaining -= segment; + read_buf += segment; + } + outlen = read_buf - cbuf; #endif /* !__VMS */ - return outlen; + return outlen; } @@ -2221,39 +2221,39 @@ static PyObject * sock_recv(PySocketSockObject *s, PyObject *args) { - int recvlen, flags = 0; - ssize_t outlen; - PyObject *buf; - - if (!PyArg_ParseTuple(args, "i|i:recv", &recvlen, &flags)) - return NULL; - - if (recvlen < 0) { - PyErr_SetString(PyExc_ValueError, - "negative buffersize in recv"); - return NULL; - } - - /* Allocate a new string. */ - buf = PyBytes_FromStringAndSize((char *) 0, recvlen); - if (buf == NULL) - return NULL; - - /* Call the guts */ - outlen = sock_recv_guts(s, PyBytes_AS_STRING(buf), recvlen, flags); - if (outlen < 0) { - /* An error occurred, release the string and return an - error. */ - Py_DECREF(buf); - return NULL; - } - if (outlen != recvlen) { - /* We did not read as many bytes as we anticipated, resize the - string if possible and be successful. */ - _PyBytes_Resize(&buf, outlen); - } + int recvlen, flags = 0; + ssize_t outlen; + PyObject *buf; + + if (!PyArg_ParseTuple(args, "i|i:recv", &recvlen, &flags)) + return NULL; + + if (recvlen < 0) { + PyErr_SetString(PyExc_ValueError, + "negative buffersize in recv"); + return NULL; + } + + /* Allocate a new string. */ + buf = PyBytes_FromStringAndSize((char *) 0, recvlen); + if (buf == NULL) + return NULL; + + /* Call the guts */ + outlen = sock_recv_guts(s, PyBytes_AS_STRING(buf), recvlen, flags); + if (outlen < 0) { + /* An error occurred, release the string and return an + error. */ + Py_DECREF(buf); + return NULL; + } + if (outlen != recvlen) { + /* We did not read as many bytes as we anticipated, resize the + string if possible and be successful. */ + _PyBytes_Resize(&buf, outlen); + } - return buf; + return buf; } PyDoc_STRVAR(recv_doc, @@ -2270,52 +2270,52 @@ static PyObject* sock_recv_into(PySocketSockObject *s, PyObject *args, PyObject *kwds) { - static char *kwlist[] = {"buffer", "nbytes", "flags", 0}; + static char *kwlist[] = {"buffer", "nbytes", "flags", 0}; - int recvlen = 0, flags = 0; - ssize_t readlen; - Py_buffer pbuf; - char *buf; - int buflen; - - /* Get the buffer's memory */ - if (!PyArg_ParseTupleAndKeywords(args, kwds, "w*|ii:recv_into", kwlist, - &pbuf, &recvlen, &flags)) - return NULL; - buf = pbuf.buf; - buflen = pbuf.len; - - if (recvlen < 0) { - PyBuffer_Release(&pbuf); - PyErr_SetString(PyExc_ValueError, - "negative buffersize in recv_into"); - return NULL; - } - if (recvlen == 0) { - /* If nbytes was not specified, use the buffer's length */ - recvlen = buflen; - } - - /* Check if the buffer is large enough */ - if (buflen < recvlen) { - PyBuffer_Release(&pbuf); - PyErr_SetString(PyExc_ValueError, - "buffer too small for requested bytes"); - return NULL; - } - - /* Call the guts */ - readlen = sock_recv_guts(s, buf, recvlen, flags); - if (readlen < 0) { - /* Return an error. */ - PyBuffer_Release(&pbuf); - return NULL; - } - - PyBuffer_Release(&pbuf); - /* Return the number of bytes read. Note that we do not do anything - special here in the case that readlen < recvlen. */ - return PyLong_FromSsize_t(readlen); + int recvlen = 0, flags = 0; + ssize_t readlen; + Py_buffer pbuf; + char *buf; + int buflen; + + /* Get the buffer's memory */ + if (!PyArg_ParseTupleAndKeywords(args, kwds, "w*|ii:recv_into", kwlist, + &pbuf, &recvlen, &flags)) + return NULL; + buf = pbuf.buf; + buflen = pbuf.len; + + if (recvlen < 0) { + PyBuffer_Release(&pbuf); + PyErr_SetString(PyExc_ValueError, + "negative buffersize in recv_into"); + return NULL; + } + if (recvlen == 0) { + /* If nbytes was not specified, use the buffer's length */ + recvlen = buflen; + } + + /* Check if the buffer is large enough */ + if (buflen < recvlen) { + PyBuffer_Release(&pbuf); + PyErr_SetString(PyExc_ValueError, + "buffer too small for requested bytes"); + return NULL; + } + + /* Call the guts */ + readlen = sock_recv_guts(s, buf, recvlen, flags); + if (readlen < 0) { + /* Return an error. */ + PyBuffer_Release(&pbuf); + return NULL; + } + + PyBuffer_Release(&pbuf); + /* Return the number of bytes read. Note that we do not do anything + special here in the case that readlen < recvlen. */ + return PyLong_FromSsize_t(readlen); } PyDoc_STRVAR(recv_into_doc, @@ -2341,56 +2341,56 @@ */ static ssize_t sock_recvfrom_guts(PySocketSockObject *s, char* cbuf, int len, int flags, - PyObject** addr) + PyObject** addr) { - sock_addr_t addrbuf; - int timeout; - ssize_t n = -1; - socklen_t addrlen; - - *addr = NULL; - - if (!getsockaddrlen(s, &addrlen)) - return -1; - - if (!IS_SELECTABLE(s)) { - select_error(); - return -1; - } - - Py_BEGIN_ALLOW_THREADS - memset(&addrbuf, 0, addrlen); - timeout = internal_select(s, 0); - if (!timeout) { + sock_addr_t addrbuf; + int timeout; + ssize_t n = -1; + socklen_t addrlen; + + *addr = NULL; + + if (!getsockaddrlen(s, &addrlen)) + return -1; + + if (!IS_SELECTABLE(s)) { + select_error(); + return -1; + } + + Py_BEGIN_ALLOW_THREADS + memset(&addrbuf, 0, addrlen); + timeout = internal_select(s, 0); + if (!timeout) { #ifndef MS_WINDOWS #if defined(PYOS_OS2) && !defined(PYCC_GCC) - n = recvfrom(s->sock_fd, cbuf, len, flags, - SAS2SA(&addrbuf), &addrlen); + n = recvfrom(s->sock_fd, cbuf, len, flags, + SAS2SA(&addrbuf), &addrlen); #else - n = recvfrom(s->sock_fd, cbuf, len, flags, - (void *) &addrbuf, &addrlen); + n = recvfrom(s->sock_fd, cbuf, len, flags, + (void *) &addrbuf, &addrlen); #endif #else - n = recvfrom(s->sock_fd, cbuf, len, flags, - SAS2SA(&addrbuf), &addrlen); + n = recvfrom(s->sock_fd, cbuf, len, flags, + SAS2SA(&addrbuf), &addrlen); #endif - } - Py_END_ALLOW_THREADS + } + Py_END_ALLOW_THREADS - if (timeout == 1) { - PyErr_SetString(socket_timeout, "timed out"); - return -1; - } - if (n < 0) { - s->errorhandler(); - return -1; - } + if (timeout == 1) { + PyErr_SetString(socket_timeout, "timed out"); + return -1; + } + if (n < 0) { + s->errorhandler(); + return -1; + } - if (!(*addr = makesockaddr(s->sock_fd, SAS2SA(&addrbuf), - addrlen, s->sock_proto))) - return -1; + if (!(*addr = makesockaddr(s->sock_fd, SAS2SA(&addrbuf), + addrlen, s->sock_proto))) + return -1; - return n; + return n; } /* s.recvfrom(nbytes [,flags]) method */ @@ -2398,45 +2398,45 @@ static PyObject * sock_recvfrom(PySocketSockObject *s, PyObject *args) { - PyObject *buf = NULL; - PyObject *addr = NULL; - PyObject *ret = NULL; - int recvlen, flags = 0; - ssize_t outlen; - - if (!PyArg_ParseTuple(args, "i|i:recvfrom", &recvlen, &flags)) - return NULL; - - if (recvlen < 0) { - PyErr_SetString(PyExc_ValueError, - "negative buffersize in recvfrom"); - return NULL; - } - - buf = PyBytes_FromStringAndSize((char *) 0, recvlen); - if (buf == NULL) - return NULL; - - outlen = sock_recvfrom_guts(s, PyBytes_AS_STRING(buf), - recvlen, flags, &addr); - if (outlen < 0) { - goto finally; - } - - if (outlen != recvlen) { - /* We did not read as many bytes as we anticipated, resize the - string if possible and be succesful. */ - if (_PyBytes_Resize(&buf, outlen) < 0) - /* Oopsy, not so succesful after all. */ - goto finally; - } + PyObject *buf = NULL; + PyObject *addr = NULL; + PyObject *ret = NULL; + int recvlen, flags = 0; + ssize_t outlen; + + if (!PyArg_ParseTuple(args, "i|i:recvfrom", &recvlen, &flags)) + return NULL; + + if (recvlen < 0) { + PyErr_SetString(PyExc_ValueError, + "negative buffersize in recvfrom"); + return NULL; + } + + buf = PyBytes_FromStringAndSize((char *) 0, recvlen); + if (buf == NULL) + return NULL; + + outlen = sock_recvfrom_guts(s, PyBytes_AS_STRING(buf), + recvlen, flags, &addr); + if (outlen < 0) { + goto finally; + } + + if (outlen != recvlen) { + /* We did not read as many bytes as we anticipated, resize the + string if possible and be succesful. */ + if (_PyBytes_Resize(&buf, outlen) < 0) + /* Oopsy, not so succesful after all. */ + goto finally; + } - ret = PyTuple_Pack(2, buf, addr); + ret = PyTuple_Pack(2, buf, addr); finally: - Py_XDECREF(buf); - Py_XDECREF(addr); - return ret; + Py_XDECREF(buf); + Py_XDECREF(addr); + return ret; } PyDoc_STRVAR(recvfrom_doc, @@ -2450,47 +2450,47 @@ static PyObject * sock_recvfrom_into(PySocketSockObject *s, PyObject *args, PyObject* kwds) { - static char *kwlist[] = {"buffer", "nbytes", "flags", 0}; + static char *kwlist[] = {"buffer", "nbytes", "flags", 0}; - int recvlen = 0, flags = 0; - ssize_t readlen; - Py_buffer pbuf; - char *buf; - int buflen; - - PyObject *addr = NULL; - - if (!PyArg_ParseTupleAndKeywords(args, kwds, "w*|ii:recvfrom_into", - kwlist, &pbuf, - &recvlen, &flags)) - return NULL; - buf = pbuf.buf; - buflen = pbuf.len; - assert(buf != 0 && buflen > 0); - - if (recvlen < 0) { - PyBuffer_Release(&pbuf); - PyErr_SetString(PyExc_ValueError, - "negative buffersize in recvfrom_into"); - return NULL; - } - if (recvlen == 0) { - /* If nbytes was not specified, use the buffer's length */ - recvlen = buflen; - } - - readlen = sock_recvfrom_guts(s, buf, recvlen, flags, &addr); - if (readlen < 0) { - PyBuffer_Release(&pbuf); - /* Return an error */ - Py_XDECREF(addr); - return NULL; - } - - PyBuffer_Release(&pbuf); - /* Return the number of bytes read and the address. Note that we do - not do anything special here in the case that readlen < recvlen. */ - return Py_BuildValue("lN", readlen, addr); + int recvlen = 0, flags = 0; + ssize_t readlen; + Py_buffer pbuf; + char *buf; + int buflen; + + PyObject *addr = NULL; + + if (!PyArg_ParseTupleAndKeywords(args, kwds, "w*|ii:recvfrom_into", + kwlist, &pbuf, + &recvlen, &flags)) + return NULL; + buf = pbuf.buf; + buflen = pbuf.len; + assert(buf != 0 && buflen > 0); + + if (recvlen < 0) { + PyBuffer_Release(&pbuf); + PyErr_SetString(PyExc_ValueError, + "negative buffersize in recvfrom_into"); + return NULL; + } + if (recvlen == 0) { + /* If nbytes was not specified, use the buffer's length */ + recvlen = buflen; + } + + readlen = sock_recvfrom_guts(s, buf, recvlen, flags, &addr); + if (readlen < 0) { + PyBuffer_Release(&pbuf); + /* Return an error */ + Py_XDECREF(addr); + return NULL; + } + + PyBuffer_Release(&pbuf); + /* Return the number of bytes read and the address. Note that we do + not do anything special here in the case that readlen < recvlen. */ + return Py_BuildValue("lN", readlen, addr); } PyDoc_STRVAR(recvfrom_into_doc, @@ -2504,39 +2504,39 @@ static PyObject * sock_send(PySocketSockObject *s, PyObject *args) { - char *buf; - int len, n = -1, flags = 0, timeout; - Py_buffer pbuf; - - if (!PyArg_ParseTuple(args, "y*|i:send", &pbuf, &flags)) - return NULL; - - if (!IS_SELECTABLE(s)) { - PyBuffer_Release(&pbuf); - return select_error(); - } - buf = pbuf.buf; - len = pbuf.len; - - Py_BEGIN_ALLOW_THREADS - timeout = internal_select(s, 1); - if (!timeout) + char *buf; + int len, n = -1, flags = 0, timeout; + Py_buffer pbuf; + + if (!PyArg_ParseTuple(args, "y*|i:send", &pbuf, &flags)) + return NULL; + + if (!IS_SELECTABLE(s)) { + PyBuffer_Release(&pbuf); + return select_error(); + } + buf = pbuf.buf; + len = pbuf.len; + + Py_BEGIN_ALLOW_THREADS + timeout = internal_select(s, 1); + if (!timeout) #ifdef __VMS - n = sendsegmented(s->sock_fd, buf, len, flags); + n = sendsegmented(s->sock_fd, buf, len, flags); #else - n = send(s->sock_fd, buf, len, flags); + n = send(s->sock_fd, buf, len, flags); #endif - Py_END_ALLOW_THREADS + Py_END_ALLOW_THREADS - PyBuffer_Release(&pbuf); + PyBuffer_Release(&pbuf); - if (timeout == 1) { - PyErr_SetString(socket_timeout, "timed out"); - return NULL; - } - if (n < 0) - return s->errorhandler(); - return PyLong_FromLong((long)n); + if (timeout == 1) { + PyErr_SetString(socket_timeout, "timed out"); + return NULL; + } + if (n < 0) + return s->errorhandler(); + return PyLong_FromLong((long)n); } PyDoc_STRVAR(send_doc, @@ -2552,48 +2552,48 @@ static PyObject * sock_sendall(PySocketSockObject *s, PyObject *args) { - char *buf; - int len, n = -1, flags = 0, timeout; - Py_buffer pbuf; - - if (!PyArg_ParseTuple(args, "y*|i:sendall", &pbuf, &flags)) - return NULL; - buf = pbuf.buf; - len = pbuf.len; - - if (!IS_SELECTABLE(s)) { - PyBuffer_Release(&pbuf); - return select_error(); - } - - Py_BEGIN_ALLOW_THREADS - do { - timeout = internal_select(s, 1); - n = -1; - if (timeout) - break; + char *buf; + int len, n = -1, flags = 0, timeout; + Py_buffer pbuf; + + if (!PyArg_ParseTuple(args, "y*|i:sendall", &pbuf, &flags)) + return NULL; + buf = pbuf.buf; + len = pbuf.len; + + if (!IS_SELECTABLE(s)) { + PyBuffer_Release(&pbuf); + return select_error(); + } + + Py_BEGIN_ALLOW_THREADS + do { + timeout = internal_select(s, 1); + n = -1; + if (timeout) + break; #ifdef __VMS - n = sendsegmented(s->sock_fd, buf, len, flags); + n = sendsegmented(s->sock_fd, buf, len, flags); #else - n = send(s->sock_fd, buf, len, flags); + n = send(s->sock_fd, buf, len, flags); #endif - if (n < 0) - break; - buf += n; - len -= n; - } while (len > 0); - Py_END_ALLOW_THREADS - PyBuffer_Release(&pbuf); - - if (timeout == 1) { - PyErr_SetString(socket_timeout, "timed out"); - return NULL; - } - if (n < 0) - return s->errorhandler(); + if (n < 0) + break; + buf += n; + len -= n; + } while (len > 0); + Py_END_ALLOW_THREADS + PyBuffer_Release(&pbuf); + + if (timeout == 1) { + PyErr_SetString(socket_timeout, "timed out"); + return NULL; + } + if (n < 0) + return s->errorhandler(); - Py_INCREF(Py_None); - return Py_None; + Py_INCREF(Py_None); + return Py_None; } PyDoc_STRVAR(sendall_doc, @@ -2610,47 +2610,47 @@ static PyObject * sock_sendto(PySocketSockObject *s, PyObject *args) { - Py_buffer pbuf; - PyObject *addro; - char *buf; - Py_ssize_t len; - sock_addr_t addrbuf; - int addrlen, n = -1, flags, timeout; - - flags = 0; - if (!PyArg_ParseTuple(args, "y*O:sendto", &pbuf, &addro)) { - PyErr_Clear(); - if (!PyArg_ParseTuple(args, "y*iO:sendto", - &pbuf, &flags, &addro)) - return NULL; - } - buf = pbuf.buf; - len = pbuf.len; - - if (!IS_SELECTABLE(s)) { - PyBuffer_Release(&pbuf); - return select_error(); - } - - if (!getsockaddrarg(s, addro, SAS2SA(&addrbuf), &addrlen)) { - PyBuffer_Release(&pbuf); - return NULL; - } - - Py_BEGIN_ALLOW_THREADS - timeout = internal_select(s, 1); - if (!timeout) - n = sendto(s->sock_fd, buf, len, flags, SAS2SA(&addrbuf), addrlen); - Py_END_ALLOW_THREADS - - PyBuffer_Release(&pbuf); - if (timeout == 1) { - PyErr_SetString(socket_timeout, "timed out"); - return NULL; - } - if (n < 0) - return s->errorhandler(); - return PyLong_FromLong((long)n); + Py_buffer pbuf; + PyObject *addro; + char *buf; + Py_ssize_t len; + sock_addr_t addrbuf; + int addrlen, n = -1, flags, timeout; + + flags = 0; + if (!PyArg_ParseTuple(args, "y*O:sendto", &pbuf, &addro)) { + PyErr_Clear(); + if (!PyArg_ParseTuple(args, "y*iO:sendto", + &pbuf, &flags, &addro)) + return NULL; + } + buf = pbuf.buf; + len = pbuf.len; + + if (!IS_SELECTABLE(s)) { + PyBuffer_Release(&pbuf); + return select_error(); + } + + if (!getsockaddrarg(s, addro, SAS2SA(&addrbuf), &addrlen)) { + PyBuffer_Release(&pbuf); + return NULL; + } + + Py_BEGIN_ALLOW_THREADS + timeout = internal_select(s, 1); + if (!timeout) + n = sendto(s->sock_fd, buf, len, flags, SAS2SA(&addrbuf), addrlen); + Py_END_ALLOW_THREADS + + PyBuffer_Release(&pbuf); + if (timeout == 1) { + PyErr_SetString(socket_timeout, "timed out"); + return NULL; + } + if (n < 0) + return s->errorhandler(); + return PyLong_FromLong((long)n); } PyDoc_STRVAR(sendto_doc, @@ -2665,19 +2665,19 @@ static PyObject * sock_shutdown(PySocketSockObject *s, PyObject *arg) { - int how; - int res; + int how; + int res; - how = PyLong_AsLong(arg); - if (how == -1 && PyErr_Occurred()) - return NULL; - Py_BEGIN_ALLOW_THREADS - res = shutdown(s->sock_fd, how); - Py_END_ALLOW_THREADS - if (res < 0) - return s->errorhandler(); - Py_INCREF(Py_None); - return Py_None; + how = PyLong_AsLong(arg); + if (how == -1 && PyErr_Occurred()) + return NULL; + Py_BEGIN_ALLOW_THREADS + res = shutdown(s->sock_fd, how); + Py_END_ALLOW_THREADS + if (res < 0) + return s->errorhandler(); + Py_INCREF(Py_None); + return Py_None; } PyDoc_STRVAR(shutdown_doc, @@ -2690,18 +2690,18 @@ static PyObject* sock_ioctl(PySocketSockObject *s, PyObject *arg) { - unsigned long cmd = SIO_RCVALL; - unsigned int option = RCVALL_ON; - DWORD recv; - - if (!PyArg_ParseTuple(arg, "kI:ioctl", &cmd, &option)) - return NULL; - - if (WSAIoctl(s->sock_fd, cmd, &option, sizeof(option), - NULL, 0, &recv, NULL, NULL) == SOCKET_ERROR) { - return set_error(); - } - return PyLong_FromUnsignedLong(recv); + unsigned long cmd = SIO_RCVALL; + unsigned int option = RCVALL_ON; + DWORD recv; + + if (!PyArg_ParseTuple(arg, "kI:ioctl", &cmd, &option)) + return NULL; + + if (WSAIoctl(s->sock_fd, cmd, &option, sizeof(option), + NULL, 0, &recv, NULL, NULL) == SOCKET_ERROR) { + return set_error(); + } + return PyLong_FromUnsignedLong(recv); } PyDoc_STRVAR(sock_ioctl_doc, "ioctl(cmd, option) -> long\n\ @@ -2715,57 +2715,57 @@ /* List of methods for socket objects */ static PyMethodDef sock_methods[] = { - {"_accept", (PyCFunction)sock_accept, METH_NOARGS, - accept_doc}, - {"bind", (PyCFunction)sock_bind, METH_O, - bind_doc}, - {"close", (PyCFunction)sock_close, METH_NOARGS, - close_doc}, - {"connect", (PyCFunction)sock_connect, METH_O, - connect_doc}, - {"connect_ex", (PyCFunction)sock_connect_ex, METH_O, - connect_ex_doc}, - {"fileno", (PyCFunction)sock_fileno, METH_NOARGS, - fileno_doc}, + {"_accept", (PyCFunction)sock_accept, METH_NOARGS, + accept_doc}, + {"bind", (PyCFunction)sock_bind, METH_O, + bind_doc}, + {"close", (PyCFunction)sock_close, METH_NOARGS, + close_doc}, + {"connect", (PyCFunction)sock_connect, METH_O, + connect_doc}, + {"connect_ex", (PyCFunction)sock_connect_ex, METH_O, + connect_ex_doc}, + {"fileno", (PyCFunction)sock_fileno, METH_NOARGS, + fileno_doc}, #ifdef HAVE_GETPEERNAME - {"getpeername", (PyCFunction)sock_getpeername, - METH_NOARGS, getpeername_doc}, + {"getpeername", (PyCFunction)sock_getpeername, + METH_NOARGS, getpeername_doc}, #endif - {"getsockname", (PyCFunction)sock_getsockname, - METH_NOARGS, getsockname_doc}, - {"getsockopt", (PyCFunction)sock_getsockopt, METH_VARARGS, - getsockopt_doc}, + {"getsockname", (PyCFunction)sock_getsockname, + METH_NOARGS, getsockname_doc}, + {"getsockopt", (PyCFunction)sock_getsockopt, METH_VARARGS, + getsockopt_doc}, #if defined(MS_WINDOWS) && defined(SIO_RCVALL) - {"ioctl", (PyCFunction)sock_ioctl, METH_VARARGS, - sock_ioctl_doc}, + {"ioctl", (PyCFunction)sock_ioctl, METH_VARARGS, + sock_ioctl_doc}, #endif - {"listen", (PyCFunction)sock_listen, METH_O, - listen_doc}, - {"recv", (PyCFunction)sock_recv, METH_VARARGS, - recv_doc}, - {"recv_into", (PyCFunction)sock_recv_into, METH_VARARGS | METH_KEYWORDS, - recv_into_doc}, - {"recvfrom", (PyCFunction)sock_recvfrom, METH_VARARGS, - recvfrom_doc}, - {"recvfrom_into", (PyCFunction)sock_recvfrom_into, METH_VARARGS | METH_KEYWORDS, - recvfrom_into_doc}, - {"send", (PyCFunction)sock_send, METH_VARARGS, - send_doc}, - {"sendall", (PyCFunction)sock_sendall, METH_VARARGS, - sendall_doc}, - {"sendto", (PyCFunction)sock_sendto, METH_VARARGS, - sendto_doc}, - {"setblocking", (PyCFunction)sock_setblocking, METH_O, - setblocking_doc}, - {"settimeout", (PyCFunction)sock_settimeout, METH_O, - settimeout_doc}, - {"gettimeout", (PyCFunction)sock_gettimeout, METH_NOARGS, - gettimeout_doc}, - {"setsockopt", (PyCFunction)sock_setsockopt, METH_VARARGS, - setsockopt_doc}, - {"shutdown", (PyCFunction)sock_shutdown, METH_O, - shutdown_doc}, - {NULL, NULL} /* sentinel */ + {"listen", (PyCFunction)sock_listen, METH_O, + listen_doc}, + {"recv", (PyCFunction)sock_recv, METH_VARARGS, + recv_doc}, + {"recv_into", (PyCFunction)sock_recv_into, METH_VARARGS | METH_KEYWORDS, + recv_into_doc}, + {"recvfrom", (PyCFunction)sock_recvfrom, METH_VARARGS, + recvfrom_doc}, + {"recvfrom_into", (PyCFunction)sock_recvfrom_into, METH_VARARGS | METH_KEYWORDS, + recvfrom_into_doc}, + {"send", (PyCFunction)sock_send, METH_VARARGS, + send_doc}, + {"sendall", (PyCFunction)sock_sendall, METH_VARARGS, + sendall_doc}, + {"sendto", (PyCFunction)sock_sendto, METH_VARARGS, + sendto_doc}, + {"setblocking", (PyCFunction)sock_setblocking, METH_O, + setblocking_doc}, + {"settimeout", (PyCFunction)sock_settimeout, METH_O, + settimeout_doc}, + {"gettimeout", (PyCFunction)sock_gettimeout, METH_NOARGS, + gettimeout_doc}, + {"setsockopt", (PyCFunction)sock_setsockopt, METH_VARARGS, + setsockopt_doc}, + {"shutdown", (PyCFunction)sock_shutdown, METH_O, + shutdown_doc}, + {NULL, NULL} /* sentinel */ }; /* SockObject members */ @@ -2783,9 +2783,9 @@ static void sock_dealloc(PySocketSockObject *s) { - if (s->sock_fd != -1) - (void) SOCKETCLOSE(s->sock_fd); - Py_TYPE(s)->tp_free((PyObject *)s); + if (s->sock_fd != -1) + (void) SOCKETCLOSE(s->sock_fd); + Py_TYPE(s)->tp_free((PyObject *)s); } @@ -2793,21 +2793,21 @@ sock_repr(PySocketSockObject *s) { #if SIZEOF_SOCKET_T > SIZEOF_LONG - if (s->sock_fd > LONG_MAX) { - /* this can occur on Win64, and actually there is a special - ugly printf formatter for decimal pointer length integer - printing, only bother if necessary*/ - PyErr_SetString(PyExc_OverflowError, - "no printf formatter to display " - "the socket descriptor in decimal"); - return NULL; - } -#endif - return PyUnicode_FromFormat( - "", - (long)s->sock_fd, s->sock_family, - s->sock_type, - s->sock_proto); + if (s->sock_fd > LONG_MAX) { + /* this can occur on Win64, and actually there is a special + ugly printf formatter for decimal pointer length integer + printing, only bother if necessary*/ + PyErr_SetString(PyExc_OverflowError, + "no printf formatter to display " + "the socket descriptor in decimal"); + return NULL; + } +#endif + return PyUnicode_FromFormat( + "", + (long)s->sock_fd, s->sock_family, + s->sock_type, + s->sock_proto); } @@ -2816,15 +2816,15 @@ static PyObject * sock_new(PyTypeObject *type, PyObject *args, PyObject *kwds) { - PyObject *new; + PyObject *new; - new = type->tp_alloc(type, 0); - if (new != NULL) { - ((PySocketSockObject *)new)->sock_fd = -1; - ((PySocketSockObject *)new)->sock_timeout = -1.0; - ((PySocketSockObject *)new)->errorhandler = &set_error; - } - return new; + new = type->tp_alloc(type, 0); + if (new != NULL) { + ((PySocketSockObject *)new)->sock_fd = -1; + ((PySocketSockObject *)new)->sock_timeout = -1.0; + ((PySocketSockObject *)new)->errorhandler = &set_error; + } + return new; } @@ -2834,40 +2834,40 @@ static int sock_initobj(PyObject *self, PyObject *args, PyObject *kwds) { - PySocketSockObject *s = (PySocketSockObject *)self; - PyObject *fdobj = NULL; - SOCKET_T fd = INVALID_SOCKET; - int family = AF_INET, type = SOCK_STREAM, proto = 0; - static char *keywords[] = {"family", "type", "proto", "fileno", 0}; - - if (!PyArg_ParseTupleAndKeywords(args, kwds, - "|iiiO:socket", keywords, - &family, &type, &proto, &fdobj)) - return -1; - - if (fdobj != NULL && fdobj != Py_None) { - fd = PyLong_AsSocket_t(fdobj); - if (fd == (SOCKET_T)(-1) && PyErr_Occurred()) - return -1; - if (fd == INVALID_SOCKET) { - PyErr_SetString(PyExc_ValueError, - "can't use invalid socket value"); - return -1; - } - } - else { - Py_BEGIN_ALLOW_THREADS - fd = socket(family, type, proto); - Py_END_ALLOW_THREADS - - if (fd == INVALID_SOCKET) { - set_error(); - return -1; - } - } - init_sockobject(s, fd, family, type, proto); + PySocketSockObject *s = (PySocketSockObject *)self; + PyObject *fdobj = NULL; + SOCKET_T fd = INVALID_SOCKET; + int family = AF_INET, type = SOCK_STREAM, proto = 0; + static char *keywords[] = {"family", "type", "proto", "fileno", 0}; + + if (!PyArg_ParseTupleAndKeywords(args, kwds, + "|iiiO:socket", keywords, + &family, &type, &proto, &fdobj)) + return -1; + + if (fdobj != NULL && fdobj != Py_None) { + fd = PyLong_AsSocket_t(fdobj); + if (fd == (SOCKET_T)(-1) && PyErr_Occurred()) + return -1; + if (fd == INVALID_SOCKET) { + PyErr_SetString(PyExc_ValueError, + "can't use invalid socket value"); + return -1; + } + } + else { + Py_BEGIN_ALLOW_THREADS + fd = socket(family, type, proto); + Py_END_ALLOW_THREADS + + if (fd == INVALID_SOCKET) { + set_error(); + return -1; + } + } + init_sockobject(s, fd, family, type, proto); - return 0; + return 0; } @@ -2875,45 +2875,45 @@ /* Type object for socket objects. */ static PyTypeObject sock_type = { - PyVarObject_HEAD_INIT(0, 0) /* Must fill in type value later */ - "_socket.socket", /* tp_name */ - sizeof(PySocketSockObject), /* tp_basicsize */ - 0, /* tp_itemsize */ - (destructor)sock_dealloc, /* tp_dealloc */ - 0, /* tp_print */ - 0, /* tp_getattr */ - 0, /* tp_setattr */ - 0, /* tp_reserved */ - (reprfunc)sock_repr, /* 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_BASETYPE, /* tp_flags */ - sock_doc, /* tp_doc */ - 0, /* tp_traverse */ - 0, /* tp_clear */ - 0, /* tp_richcompare */ - 0, /* tp_weaklistoffset */ - 0, /* tp_iter */ - 0, /* tp_iternext */ - sock_methods, /* tp_methods */ - sock_memberlist, /* tp_members */ - 0, /* tp_getset */ - 0, /* tp_base */ - 0, /* tp_dict */ - 0, /* tp_descr_get */ - 0, /* tp_descr_set */ - 0, /* tp_dictoffset */ - sock_initobj, /* tp_init */ - PyType_GenericAlloc, /* tp_alloc */ - sock_new, /* tp_new */ - PyObject_Del, /* tp_free */ + PyVarObject_HEAD_INIT(0, 0) /* Must fill in type value later */ + "_socket.socket", /* tp_name */ + sizeof(PySocketSockObject), /* tp_basicsize */ + 0, /* tp_itemsize */ + (destructor)sock_dealloc, /* tp_dealloc */ + 0, /* tp_print */ + 0, /* tp_getattr */ + 0, /* tp_setattr */ + 0, /* tp_reserved */ + (reprfunc)sock_repr, /* 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_BASETYPE, /* tp_flags */ + sock_doc, /* tp_doc */ + 0, /* tp_traverse */ + 0, /* tp_clear */ + 0, /* tp_richcompare */ + 0, /* tp_weaklistoffset */ + 0, /* tp_iter */ + 0, /* tp_iternext */ + sock_methods, /* tp_methods */ + sock_memberlist, /* tp_members */ + 0, /* tp_getset */ + 0, /* tp_base */ + 0, /* tp_dict */ + 0, /* tp_descr_get */ + 0, /* tp_descr_set */ + 0, /* tp_dictoffset */ + sock_initobj, /* tp_init */ + PyType_GenericAlloc, /* tp_alloc */ + sock_new, /* tp_new */ + PyObject_Del, /* tp_free */ }; @@ -2923,15 +2923,15 @@ static PyObject * socket_gethostname(PyObject *self, PyObject *unused) { - char buf[1024]; - int res; - Py_BEGIN_ALLOW_THREADS - res = gethostname(buf, (int) sizeof buf - 1); - Py_END_ALLOW_THREADS - if (res < 0) - return set_error(); - buf[sizeof buf - 1] = '\0'; - return PyUnicode_FromString(buf); + char buf[1024]; + int res; + Py_BEGIN_ALLOW_THREADS + res = gethostname(buf, (int) sizeof buf - 1); + Py_END_ALLOW_THREADS + if (res < 0) + return set_error(); + buf[sizeof buf - 1] = '\0'; + return PyUnicode_FromString(buf); } PyDoc_STRVAR(gethostname_doc, @@ -2946,14 +2946,14 @@ static PyObject * socket_gethostbyname(PyObject *self, PyObject *args) { - char *name; - sock_addr_t addrbuf; + char *name; + sock_addr_t addrbuf; - if (!PyArg_ParseTuple(args, "s:gethostbyname", &name)) - return NULL; - if (setipaddr(name, SAS2SA(&addrbuf), sizeof(addrbuf), AF_INET) < 0) - return NULL; - return makeipaddr(SAS2SA(&addrbuf), sizeof(struct sockaddr_in)); + if (!PyArg_ParseTuple(args, "s:gethostbyname", &name)) + return NULL; + if (setipaddr(name, SAS2SA(&addrbuf), sizeof(addrbuf), AF_INET) < 0) + return NULL; + return makeipaddr(SAS2SA(&addrbuf), sizeof(struct sockaddr_in)); } PyDoc_STRVAR(gethostbyname_doc, @@ -2967,126 +2967,126 @@ static PyObject * gethost_common(struct hostent *h, struct sockaddr *addr, int alen, int af) { - char **pch; - PyObject *rtn_tuple = (PyObject *)NULL; - PyObject *name_list = (PyObject *)NULL; - PyObject *addr_list = (PyObject *)NULL; - PyObject *tmp; - - if (h == NULL) { - /* Let's get real error message to return */ - set_herror(h_errno); - return NULL; - } - - if (h->h_addrtype != af) { - /* Let's get real error message to return */ - PyErr_SetString(socket_error, - (char *)strerror(EAFNOSUPPORT)); - - return NULL; - } - - switch (af) { - - case AF_INET: - if (alen < sizeof(struct sockaddr_in)) - return NULL; - break; + char **pch; + PyObject *rtn_tuple = (PyObject *)NULL; + PyObject *name_list = (PyObject *)NULL; + PyObject *addr_list = (PyObject *)NULL; + PyObject *tmp; + + if (h == NULL) { + /* Let's get real error message to return */ + set_herror(h_errno); + return NULL; + } + + if (h->h_addrtype != af) { + /* Let's get real error message to return */ + PyErr_SetString(socket_error, + (char *)strerror(EAFNOSUPPORT)); + + return NULL; + } + + switch (af) { + + case AF_INET: + if (alen < sizeof(struct sockaddr_in)) + return NULL; + break; #ifdef ENABLE_IPV6 - case AF_INET6: - if (alen < sizeof(struct sockaddr_in6)) - return NULL; - break; -#endif - - } - - if ((name_list = PyList_New(0)) == NULL) - goto err; - - if ((addr_list = PyList_New(0)) == NULL) - goto err; - - /* SF #1511317: h_aliases can be NULL */ - if (h->h_aliases) { - for (pch = h->h_aliases; *pch != NULL; pch++) { - int status; - tmp = PyUnicode_FromString(*pch); - if (tmp == NULL) - goto err; - - status = PyList_Append(name_list, tmp); - Py_DECREF(tmp); - - if (status) - goto err; - } - } - - for (pch = h->h_addr_list; *pch != NULL; pch++) { - int status; - - switch (af) { - - case AF_INET: - { - struct sockaddr_in sin; - memset(&sin, 0, sizeof(sin)); - sin.sin_family = af; + case AF_INET6: + if (alen < sizeof(struct sockaddr_in6)) + return NULL; + break; +#endif + + } + + if ((name_list = PyList_New(0)) == NULL) + goto err; + + if ((addr_list = PyList_New(0)) == NULL) + goto err; + + /* SF #1511317: h_aliases can be NULL */ + if (h->h_aliases) { + for (pch = h->h_aliases; *pch != NULL; pch++) { + int status; + tmp = PyUnicode_FromString(*pch); + if (tmp == NULL) + goto err; + + status = PyList_Append(name_list, tmp); + Py_DECREF(tmp); + + if (status) + goto err; + } + } + + for (pch = h->h_addr_list; *pch != NULL; pch++) { + int status; + + switch (af) { + + case AF_INET: + { + struct sockaddr_in sin; + memset(&sin, 0, sizeof(sin)); + sin.sin_family = af; #ifdef HAVE_SOCKADDR_SA_LEN - sin.sin_len = sizeof(sin); + sin.sin_len = sizeof(sin); #endif - memcpy(&sin.sin_addr, *pch, sizeof(sin.sin_addr)); - tmp = makeipaddr((struct sockaddr *)&sin, sizeof(sin)); + memcpy(&sin.sin_addr, *pch, sizeof(sin.sin_addr)); + tmp = makeipaddr((struct sockaddr *)&sin, sizeof(sin)); - if (pch == h->h_addr_list && alen >= sizeof(sin)) - memcpy((char *) addr, &sin, sizeof(sin)); - break; - } + if (pch == h->h_addr_list && alen >= sizeof(sin)) + memcpy((char *) addr, &sin, sizeof(sin)); + break; + } #ifdef ENABLE_IPV6 - case AF_INET6: - { - struct sockaddr_in6 sin6; - memset(&sin6, 0, sizeof(sin6)); - sin6.sin6_family = af; + case AF_INET6: + { + struct sockaddr_in6 sin6; + memset(&sin6, 0, sizeof(sin6)); + sin6.sin6_family = af; #ifdef HAVE_SOCKADDR_SA_LEN - sin6.sin6_len = sizeof(sin6); + sin6.sin6_len = sizeof(sin6); #endif - memcpy(&sin6.sin6_addr, *pch, sizeof(sin6.sin6_addr)); - tmp = makeipaddr((struct sockaddr *)&sin6, - sizeof(sin6)); + memcpy(&sin6.sin6_addr, *pch, sizeof(sin6.sin6_addr)); + tmp = makeipaddr((struct sockaddr *)&sin6, + sizeof(sin6)); - if (pch == h->h_addr_list && alen >= sizeof(sin6)) - memcpy((char *) addr, &sin6, sizeof(sin6)); - break; - } + if (pch == h->h_addr_list && alen >= sizeof(sin6)) + memcpy((char *) addr, &sin6, sizeof(sin6)); + break; + } #endif - default: /* can't happen */ - PyErr_SetString(socket_error, - "unsupported address family"); - return NULL; - } + default: /* can't happen */ + PyErr_SetString(socket_error, + "unsupported address family"); + return NULL; + } - if (tmp == NULL) - goto err; + if (tmp == NULL) + goto err; - status = PyList_Append(addr_list, tmp); - Py_DECREF(tmp); + status = PyList_Append(addr_list, tmp); + Py_DECREF(tmp); - if (status) - goto err; - } + if (status) + goto err; + } - rtn_tuple = Py_BuildValue("sOO", h->h_name, name_list, addr_list); + rtn_tuple = Py_BuildValue("sOO", h->h_name, name_list, addr_list); err: - Py_XDECREF(name_list); - Py_XDECREF(addr_list); - return rtn_tuple; + Py_XDECREF(name_list); + Py_XDECREF(addr_list); + return rtn_tuple; } @@ -3096,63 +3096,63 @@ static PyObject * socket_gethostbyname_ex(PyObject *self, PyObject *args) { - char *name; - struct hostent *h; + char *name; + struct hostent *h; #ifdef ENABLE_IPV6 - struct sockaddr_storage addr; + struct sockaddr_storage addr; #else - struct sockaddr_in addr; + struct sockaddr_in addr; #endif - struct sockaddr *sa; - PyObject *ret; + struct sockaddr *sa; + PyObject *ret; #ifdef HAVE_GETHOSTBYNAME_R - struct hostent hp_allocated; + struct hostent hp_allocated; #ifdef HAVE_GETHOSTBYNAME_R_3_ARG - struct hostent_data data; + struct hostent_data data; #else - char buf[16384]; - int buf_len = (sizeof buf) - 1; - int errnop; + char buf[16384]; + int buf_len = (sizeof buf) - 1; + int errnop; #endif #if defined(HAVE_GETHOSTBYNAME_R_3_ARG) || defined(HAVE_GETHOSTBYNAME_R_6_ARG) - int result; + int result; #endif #endif /* HAVE_GETHOSTBYNAME_R */ - if (!PyArg_ParseTuple(args, "s:gethostbyname_ex", &name)) - return NULL; - if (setipaddr(name, (struct sockaddr *)&addr, sizeof(addr), AF_INET) < 0) - return NULL; - Py_BEGIN_ALLOW_THREADS + if (!PyArg_ParseTuple(args, "s:gethostbyname_ex", &name)) + return NULL; + if (setipaddr(name, (struct sockaddr *)&addr, sizeof(addr), AF_INET) < 0) + return NULL; + Py_BEGIN_ALLOW_THREADS #ifdef HAVE_GETHOSTBYNAME_R #if defined(HAVE_GETHOSTBYNAME_R_6_ARG) - result = gethostbyname_r(name, &hp_allocated, buf, buf_len, - &h, &errnop); + result = gethostbyname_r(name, &hp_allocated, buf, buf_len, + &h, &errnop); #elif defined(HAVE_GETHOSTBYNAME_R_5_ARG) - h = gethostbyname_r(name, &hp_allocated, buf, buf_len, &errnop); + h = gethostbyname_r(name, &hp_allocated, buf, buf_len, &errnop); #else /* HAVE_GETHOSTBYNAME_R_3_ARG */ - memset((void *) &data, '\0', sizeof(data)); - result = gethostbyname_r(name, &hp_allocated, &data); - h = (result != 0) ? NULL : &hp_allocated; + memset((void *) &data, '\0', sizeof(data)); + result = gethostbyname_r(name, &hp_allocated, &data); + h = (result != 0) ? NULL : &hp_allocated; #endif #else /* not HAVE_GETHOSTBYNAME_R */ #ifdef USE_GETHOSTBYNAME_LOCK - PyThread_acquire_lock(netdb_lock, 1); + PyThread_acquire_lock(netdb_lock, 1); #endif - h = gethostbyname(name); + h = gethostbyname(name); #endif /* HAVE_GETHOSTBYNAME_R */ - Py_END_ALLOW_THREADS - /* Some C libraries would require addr.__ss_family instead of - addr.ss_family. - Therefore, we cast the sockaddr_storage into sockaddr to - access sa_family. */ - sa = (struct sockaddr*)&addr; - ret = gethost_common(h, (struct sockaddr *)&addr, sizeof(addr), - sa->sa_family); + Py_END_ALLOW_THREADS + /* Some C libraries would require addr.__ss_family instead of + addr.ss_family. + Therefore, we cast the sockaddr_storage into sockaddr to + access sa_family. */ + sa = (struct sockaddr*)&addr; + ret = gethost_common(h, (struct sockaddr *)&addr, sizeof(addr), + sa->sa_family); #ifdef USE_GETHOSTBYNAME_LOCK - PyThread_release_lock(netdb_lock); + PyThread_release_lock(netdb_lock); #endif - return ret; + return ret; } PyDoc_STRVAR(ghbn_ex_doc, @@ -3169,84 +3169,84 @@ socket_gethostbyaddr(PyObject *self, PyObject *args) { #ifdef ENABLE_IPV6 - struct sockaddr_storage addr; + struct sockaddr_storage addr; #else - struct sockaddr_in addr; + struct sockaddr_in addr; #endif - struct sockaddr *sa = (struct sockaddr *)&addr; - char *ip_num; - struct hostent *h; - PyObject *ret; + struct sockaddr *sa = (struct sockaddr *)&addr; + char *ip_num; + struct hostent *h; + PyObject *ret; #ifdef HAVE_GETHOSTBYNAME_R - struct hostent hp_allocated; + struct hostent hp_allocated; #ifdef HAVE_GETHOSTBYNAME_R_3_ARG - struct hostent_data data; + struct hostent_data data; #else - /* glibcs up to 2.10 assume that the buf argument to - gethostbyaddr_r is 8-byte aligned, which at least llvm-gcc - does not ensure. The attribute below instructs the compiler - to maintain this alignment. */ - char buf[16384] Py_ALIGNED(8); - int buf_len = (sizeof buf) - 1; - int errnop; + /* glibcs up to 2.10 assume that the buf argument to + gethostbyaddr_r is 8-byte aligned, which at least llvm-gcc + does not ensure. The attribute below instructs the compiler + to maintain this alignment. */ + char buf[16384] Py_ALIGNED(8); + int buf_len = (sizeof buf) - 1; + int errnop; #endif #if defined(HAVE_GETHOSTBYNAME_R_3_ARG) || defined(HAVE_GETHOSTBYNAME_R_6_ARG) - int result; + int result; #endif #endif /* HAVE_GETHOSTBYNAME_R */ - char *ap; - int al; - int af; - - if (!PyArg_ParseTuple(args, "s:gethostbyaddr", &ip_num)) - return NULL; - af = AF_UNSPEC; - if (setipaddr(ip_num, sa, sizeof(addr), af) < 0) - return NULL; - af = sa->sa_family; - ap = NULL; - al = 0; - switch (af) { - case AF_INET: - ap = (char *)&((struct sockaddr_in *)sa)->sin_addr; - al = sizeof(((struct sockaddr_in *)sa)->sin_addr); - break; + char *ap; + int al; + int af; + + if (!PyArg_ParseTuple(args, "s:gethostbyaddr", &ip_num)) + return NULL; + af = AF_UNSPEC; + if (setipaddr(ip_num, sa, sizeof(addr), af) < 0) + return NULL; + af = sa->sa_family; + ap = NULL; + al = 0; + switch (af) { + case AF_INET: + ap = (char *)&((struct sockaddr_in *)sa)->sin_addr; + al = sizeof(((struct sockaddr_in *)sa)->sin_addr); + break; #ifdef ENABLE_IPV6 - case AF_INET6: - ap = (char *)&((struct sockaddr_in6 *)sa)->sin6_addr; - al = sizeof(((struct sockaddr_in6 *)sa)->sin6_addr); - break; -#endif - default: - PyErr_SetString(socket_error, "unsupported address family"); - return NULL; - } - Py_BEGIN_ALLOW_THREADS + case AF_INET6: + ap = (char *)&((struct sockaddr_in6 *)sa)->sin6_addr; + al = sizeof(((struct sockaddr_in6 *)sa)->sin6_addr); + break; +#endif + default: + PyErr_SetString(socket_error, "unsupported address family"); + return NULL; + } + Py_BEGIN_ALLOW_THREADS #ifdef HAVE_GETHOSTBYNAME_R #if defined(HAVE_GETHOSTBYNAME_R_6_ARG) - result = gethostbyaddr_r(ap, al, af, - &hp_allocated, buf, buf_len, - &h, &errnop); + result = gethostbyaddr_r(ap, al, af, + &hp_allocated, buf, buf_len, + &h, &errnop); #elif defined(HAVE_GETHOSTBYNAME_R_5_ARG) - h = gethostbyaddr_r(ap, al, af, - &hp_allocated, buf, buf_len, &errnop); + h = gethostbyaddr_r(ap, al, af, + &hp_allocated, buf, buf_len, &errnop); #else /* HAVE_GETHOSTBYNAME_R_3_ARG */ - memset((void *) &data, '\0', sizeof(data)); - result = gethostbyaddr_r(ap, al, af, &hp_allocated, &data); - h = (result != 0) ? NULL : &hp_allocated; + memset((void *) &data, '\0', sizeof(data)); + result = gethostbyaddr_r(ap, al, af, &hp_allocated, &data); + h = (result != 0) ? NULL : &hp_allocated; #endif #else /* not HAVE_GETHOSTBYNAME_R */ #ifdef USE_GETHOSTBYNAME_LOCK - PyThread_acquire_lock(netdb_lock, 1); + PyThread_acquire_lock(netdb_lock, 1); #endif - h = gethostbyaddr(ap, al, af); + h = gethostbyaddr(ap, al, af); #endif /* HAVE_GETHOSTBYNAME_R */ - Py_END_ALLOW_THREADS - ret = gethost_common(h, (struct sockaddr *)&addr, sizeof(addr), af); + Py_END_ALLOW_THREADS + ret = gethost_common(h, (struct sockaddr *)&addr, sizeof(addr), af); #ifdef USE_GETHOSTBYNAME_LOCK - PyThread_release_lock(netdb_lock); + PyThread_release_lock(netdb_lock); #endif - return ret; + return ret; } PyDoc_STRVAR(gethostbyaddr_doc, @@ -3264,18 +3264,18 @@ static PyObject * socket_getservbyname(PyObject *self, PyObject *args) { - char *name, *proto=NULL; - struct servent *sp; - if (!PyArg_ParseTuple(args, "s|s:getservbyname", &name, &proto)) - return NULL; - Py_BEGIN_ALLOW_THREADS - sp = getservbyname(name, proto); - Py_END_ALLOW_THREADS - if (sp == NULL) { - PyErr_SetString(socket_error, "service/proto not found"); - return NULL; - } - return PyLong_FromLong((long) ntohs(sp->s_port)); + char *name, *proto=NULL; + struct servent *sp; + if (!PyArg_ParseTuple(args, "s|s:getservbyname", &name, &proto)) + return NULL; + Py_BEGIN_ALLOW_THREADS + sp = getservbyname(name, proto); + Py_END_ALLOW_THREADS + if (sp == NULL) { + PyErr_SetString(socket_error, "service/proto not found"); + return NULL; + } + return PyLong_FromLong((long) ntohs(sp->s_port)); } PyDoc_STRVAR(getservbyname_doc, @@ -3294,25 +3294,25 @@ static PyObject * socket_getservbyport(PyObject *self, PyObject *args) { - int port; - char *proto=NULL; - struct servent *sp; - if (!PyArg_ParseTuple(args, "i|s:getservbyport", &port, &proto)) - return NULL; - if (port < 0 || port > 0xffff) { - PyErr_SetString( - PyExc_OverflowError, - "getservbyport: port must be 0-65535."); - return NULL; - } - Py_BEGIN_ALLOW_THREADS - sp = getservbyport(htons((short)port), proto); - Py_END_ALLOW_THREADS - if (sp == NULL) { - PyErr_SetString(socket_error, "port/proto not found"); - return NULL; - } - return PyUnicode_FromString(sp->s_name); + int port; + char *proto=NULL; + struct servent *sp; + if (!PyArg_ParseTuple(args, "i|s:getservbyport", &port, &proto)) + return NULL; + if (port < 0 || port > 0xffff) { + PyErr_SetString( + PyExc_OverflowError, + "getservbyport: port must be 0-65535."); + return NULL; + } + Py_BEGIN_ALLOW_THREADS + sp = getservbyport(htons((short)port), proto); + Py_END_ALLOW_THREADS + if (sp == NULL) { + PyErr_SetString(socket_error, "port/proto not found"); + return NULL; + } + return PyUnicode_FromString(sp->s_name); } PyDoc_STRVAR(getservbyport_doc, @@ -3330,18 +3330,18 @@ static PyObject * socket_getprotobyname(PyObject *self, PyObject *args) { - char *name; - struct protoent *sp; - if (!PyArg_ParseTuple(args, "s:getprotobyname", &name)) - return NULL; - Py_BEGIN_ALLOW_THREADS - sp = getprotobyname(name); - Py_END_ALLOW_THREADS - if (sp == NULL) { - PyErr_SetString(socket_error, "protocol not found"); - return NULL; - } - return PyLong_FromLong((long) sp->p_proto); + char *name; + struct protoent *sp; + if (!PyArg_ParseTuple(args, "s:getprotobyname", &name)) + return NULL; + Py_BEGIN_ALLOW_THREADS + sp = getprotobyname(name); + Py_END_ALLOW_THREADS + if (sp == NULL) { + PyErr_SetString(socket_error, "protocol not found"); + return NULL; + } + return PyLong_FromLong((long) sp->p_proto); } PyDoc_STRVAR(getprotobyname_doc, @@ -3356,22 +3356,22 @@ static PyObject * socket_dup(PyObject *self, PyObject *fdobj) { - SOCKET_T fd, newfd; - PyObject *newfdobj; + SOCKET_T fd, newfd; + PyObject *newfdobj; - fd = PyLong_AsSocket_t(fdobj); - if (fd == (SOCKET_T)(-1) && PyErr_Occurred()) - return NULL; - - newfd = dup_socket(fd); - if (newfd == INVALID_SOCKET) - return set_error(); - - newfdobj = PyLong_FromSocket_t(newfd); - if (newfdobj == NULL) - SOCKETCLOSE(newfd); - return newfdobj; + fd = PyLong_AsSocket_t(fdobj); + if (fd == (SOCKET_T)(-1) && PyErr_Occurred()) + return NULL; + + newfd = dup_socket(fd); + if (newfd == INVALID_SOCKET) + return set_error(); + + newfdobj = PyLong_FromSocket_t(newfd); + if (newfdobj == NULL) + SOCKETCLOSE(newfd); + return newfdobj; } PyDoc_STRVAR(dup_doc, @@ -3391,40 +3391,40 @@ static PyObject * socket_socketpair(PyObject *self, PyObject *args) { - PySocketSockObject *s0 = NULL, *s1 = NULL; - SOCKET_T sv[2]; - int family, type = SOCK_STREAM, proto = 0; - PyObject *res = NULL; + PySocketSockObject *s0 = NULL, *s1 = NULL; + SOCKET_T sv[2]; + int family, type = SOCK_STREAM, proto = 0; + PyObject *res = NULL; #if defined(AF_UNIX) - family = AF_UNIX; + family = AF_UNIX; #else - family = AF_INET; + family = AF_INET; #endif - if (!PyArg_ParseTuple(args, "|iii:socketpair", - &family, &type, &proto)) - return NULL; - /* Create a pair of socket fds */ - if (socketpair(family, type, proto, sv) < 0) - return set_error(); - s0 = new_sockobject(sv[0], family, type, proto); - if (s0 == NULL) - goto finally; - s1 = new_sockobject(sv[1], family, type, proto); - if (s1 == NULL) - goto finally; - res = PyTuple_Pack(2, s0, s1); + if (!PyArg_ParseTuple(args, "|iii:socketpair", + &family, &type, &proto)) + return NULL; + /* Create a pair of socket fds */ + if (socketpair(family, type, proto, sv) < 0) + return set_error(); + s0 = new_sockobject(sv[0], family, type, proto); + if (s0 == NULL) + goto finally; + s1 = new_sockobject(sv[1], family, type, proto); + if (s1 == NULL) + goto finally; + res = PyTuple_Pack(2, s0, s1); finally: - if (res == NULL) { - if (s0 == NULL) - SOCKETCLOSE(sv[0]); - if (s1 == NULL) - SOCKETCLOSE(sv[1]); - } - Py_XDECREF(s0); - Py_XDECREF(s1); - return res; + if (res == NULL) { + if (s0 == NULL) + SOCKETCLOSE(sv[0]); + if (s1 == NULL) + SOCKETCLOSE(sv[1]); + } + Py_XDECREF(s0); + Py_XDECREF(s1); + return res; } PyDoc_STRVAR(socketpair_doc, @@ -3441,18 +3441,18 @@ static PyObject * socket_ntohs(PyObject *self, PyObject *args) { - int x1, x2; + int x1, x2; - if (!PyArg_ParseTuple(args, "i:ntohs", &x1)) { - return NULL; - } - if (x1 < 0) { - PyErr_SetString(PyExc_OverflowError, - "can't convert negative number to unsigned long"); - return NULL; - } - x2 = (unsigned int)ntohs((unsigned short)x1); - return PyLong_FromLong(x2); + if (!PyArg_ParseTuple(args, "i:ntohs", &x1)) { + return NULL; + } + if (x1 < 0) { + PyErr_SetString(PyExc_OverflowError, + "can't convert negative number to unsigned long"); + return NULL; + } + x2 = (unsigned int)ntohs((unsigned short)x1); + return PyLong_FromLong(x2); } PyDoc_STRVAR(ntohs_doc, @@ -3464,31 +3464,31 @@ static PyObject * socket_ntohl(PyObject *self, PyObject *arg) { - unsigned long x; + unsigned long x; - if (PyLong_Check(arg)) { - x = PyLong_AsUnsignedLong(arg); - if (x == (unsigned long) -1 && PyErr_Occurred()) - return NULL; + if (PyLong_Check(arg)) { + x = PyLong_AsUnsignedLong(arg); + if (x == (unsigned long) -1 && PyErr_Occurred()) + return NULL; #if SIZEOF_LONG > 4 - { - unsigned long y; - /* only want the trailing 32 bits */ - y = x & 0xFFFFFFFFUL; - if (y ^ x) - return PyErr_Format(PyExc_OverflowError, - "long int larger than 32 bits"); - x = y; - } -#endif - } - else - return PyErr_Format(PyExc_TypeError, - "expected int/long, %s found", - Py_TYPE(arg)->tp_name); - if (x == (unsigned long) -1 && PyErr_Occurred()) - return NULL; - return PyLong_FromUnsignedLong(ntohl(x)); + { + unsigned long y; + /* only want the trailing 32 bits */ + y = x & 0xFFFFFFFFUL; + if (y ^ x) + return PyErr_Format(PyExc_OverflowError, + "long int larger than 32 bits"); + x = y; + } +#endif + } + else + return PyErr_Format(PyExc_TypeError, + "expected int/long, %s found", + Py_TYPE(arg)->tp_name); + if (x == (unsigned long) -1 && PyErr_Occurred()) + return NULL; + return PyLong_FromUnsignedLong(ntohl(x)); } PyDoc_STRVAR(ntohl_doc, @@ -3500,18 +3500,18 @@ static PyObject * socket_htons(PyObject *self, PyObject *args) { - int x1, x2; + int x1, x2; - if (!PyArg_ParseTuple(args, "i:htons", &x1)) { - return NULL; - } - if (x1 < 0) { - PyErr_SetString(PyExc_OverflowError, - "can't convert negative number to unsigned long"); - return NULL; - } - x2 = (unsigned int)htons((unsigned short)x1); - return PyLong_FromLong(x2); + if (!PyArg_ParseTuple(args, "i:htons", &x1)) { + return NULL; + } + if (x1 < 0) { + PyErr_SetString(PyExc_OverflowError, + "can't convert negative number to unsigned long"); + return NULL; + } + x2 = (unsigned int)htons((unsigned short)x1); + return PyLong_FromLong(x2); } PyDoc_STRVAR(htons_doc, @@ -3523,29 +3523,29 @@ static PyObject * socket_htonl(PyObject *self, PyObject *arg) { - unsigned long x; + unsigned long x; - if (PyLong_Check(arg)) { - x = PyLong_AsUnsignedLong(arg); - if (x == (unsigned long) -1 && PyErr_Occurred()) - return NULL; + if (PyLong_Check(arg)) { + x = PyLong_AsUnsignedLong(arg); + if (x == (unsigned long) -1 && PyErr_Occurred()) + return NULL; #if SIZEOF_LONG > 4 - { - unsigned long y; - /* only want the trailing 32 bits */ - y = x & 0xFFFFFFFFUL; - if (y ^ x) - return PyErr_Format(PyExc_OverflowError, - "long int larger than 32 bits"); - x = y; - } -#endif - } - else - return PyErr_Format(PyExc_TypeError, - "expected int/long, %s found", - Py_TYPE(arg)->tp_name); - return PyLong_FromUnsignedLong(htonl((unsigned long)x)); + { + unsigned long y; + /* only want the trailing 32 bits */ + y = x & 0xFFFFFFFFUL; + if (y ^ x) + return PyErr_Format(PyExc_OverflowError, + "long int larger than 32 bits"); + x = y; + } +#endif + } + else + return PyErr_Format(PyExc_TypeError, + "expected int/long, %s found", + Py_TYPE(arg)->tp_name); + return PyLong_FromUnsignedLong(htonl((unsigned long)x)); } PyDoc_STRVAR(htonl_doc, @@ -3568,20 +3568,20 @@ #define INADDR_NONE (-1) #endif #ifdef HAVE_INET_ATON - struct in_addr buf; + struct in_addr buf; #endif #if !defined(HAVE_INET_ATON) || defined(USE_INET_ATON_WEAKLINK) #if (SIZEOF_INT != 4) #error "Not sure if in_addr_t exists and int is not 32-bits." #endif - /* Have to use inet_addr() instead */ - unsigned int packed_addr; + /* Have to use inet_addr() instead */ + unsigned int packed_addr; #endif - char *ip_addr; + char *ip_addr; - if (!PyArg_ParseTuple(args, "s:inet_aton", &ip_addr)) - return NULL; + if (!PyArg_ParseTuple(args, "s:inet_aton", &ip_addr)) + return NULL; #ifdef HAVE_INET_ATON @@ -3589,13 +3589,13 @@ #ifdef USE_INET_ATON_WEAKLINK if (inet_aton != NULL) { #endif - if (inet_aton(ip_addr, &buf)) - return PyBytes_FromStringAndSize((char *)(&buf), - sizeof(buf)); - - PyErr_SetString(socket_error, - "illegal IP address string passed to inet_aton"); - return NULL; + if (inet_aton(ip_addr, &buf)) + return PyBytes_FromStringAndSize((char *)(&buf), + sizeof(buf)); + + PyErr_SetString(socket_error, + "illegal IP address string passed to inet_aton"); + return NULL; #ifdef USE_INET_ATON_WEAKLINK } else { @@ -3605,22 +3605,22 @@ #if !defined(HAVE_INET_ATON) || defined(USE_INET_ATON_WEAKLINK) - /* special-case this address as inet_addr might return INADDR_NONE - * for this */ - if (strcmp(ip_addr, "255.255.255.255") == 0) { - packed_addr = 0xFFFFFFFF; - } else { - - packed_addr = inet_addr(ip_addr); - - if (packed_addr == INADDR_NONE) { /* invalid address */ - PyErr_SetString(socket_error, - "illegal IP address string passed to inet_aton"); - return NULL; - } - } - return PyBytes_FromStringAndSize((char *) &packed_addr, - sizeof(packed_addr)); + /* special-case this address as inet_addr might return INADDR_NONE + * for this */ + if (strcmp(ip_addr, "255.255.255.255") == 0) { + packed_addr = 0xFFFFFFFF; + } else { + + packed_addr = inet_addr(ip_addr); + + if (packed_addr == INADDR_NONE) { /* invalid address */ + PyErr_SetString(socket_error, + "illegal IP address string passed to inet_aton"); + return NULL; + } + } + return PyBytes_FromStringAndSize((char *) &packed_addr, + sizeof(packed_addr)); #ifdef USE_INET_ATON_WEAKLINK } @@ -3637,23 +3637,23 @@ static PyObject* socket_inet_ntoa(PyObject *self, PyObject *args) { - char *packed_str; - int addr_len; - struct in_addr packed_addr; - - if (!PyArg_ParseTuple(args, "y#:inet_ntoa", &packed_str, &addr_len)) { - return NULL; - } - - if (addr_len != sizeof(packed_addr)) { - PyErr_SetString(socket_error, - "packed IP wrong length for inet_ntoa"); - return NULL; - } + char *packed_str; + int addr_len; + struct in_addr packed_addr; + + if (!PyArg_ParseTuple(args, "y#:inet_ntoa", &packed_str, &addr_len)) { + return NULL; + } + + if (addr_len != sizeof(packed_addr)) { + PyErr_SetString(socket_error, + "packed IP wrong length for inet_ntoa"); + return NULL; + } - memcpy(&packed_addr, packed_str, addr_len); + memcpy(&packed_addr, packed_str, addr_len); - return PyUnicode_FromString(inet_ntoa(packed_addr)); + return PyUnicode_FromString(inet_ntoa(packed_addr)); } #ifdef HAVE_INET_PTON @@ -3667,46 +3667,46 @@ static PyObject * socket_inet_pton(PyObject *self, PyObject *args) { - int af; - char* ip; - int retval; + int af; + char* ip; + int retval; #ifdef ENABLE_IPV6 - char packed[MAX(sizeof(struct in_addr), sizeof(struct in6_addr))]; + char packed[MAX(sizeof(struct in_addr), sizeof(struct in6_addr))]; #else - char packed[sizeof(struct in_addr)]; + char packed[sizeof(struct in_addr)]; #endif - if (!PyArg_ParseTuple(args, "is:inet_pton", &af, &ip)) { - return NULL; - } + if (!PyArg_ParseTuple(args, "is:inet_pton", &af, &ip)) { + return NULL; + } #if !defined(ENABLE_IPV6) && defined(AF_INET6) - if(af == AF_INET6) { - PyErr_SetString(socket_error, - "can't use AF_INET6, IPv6 is disabled"); - return NULL; - } -#endif - - retval = inet_pton(af, ip, packed); - if (retval < 0) { - PyErr_SetFromErrno(socket_error); - return NULL; - } else if (retval == 0) { - PyErr_SetString(socket_error, - "illegal IP address string passed to inet_pton"); - return NULL; - } else if (af == AF_INET) { - return PyBytes_FromStringAndSize(packed, - sizeof(struct in_addr)); + if(af == AF_INET6) { + PyErr_SetString(socket_error, + "can't use AF_INET6, IPv6 is disabled"); + return NULL; + } +#endif + + retval = inet_pton(af, ip, packed); + if (retval < 0) { + PyErr_SetFromErrno(socket_error); + return NULL; + } else if (retval == 0) { + PyErr_SetString(socket_error, + "illegal IP address string passed to inet_pton"); + return NULL; + } else if (af == AF_INET) { + return PyBytes_FromStringAndSize(packed, + sizeof(struct in_addr)); #ifdef ENABLE_IPV6 - } else if (af == AF_INET6) { - return PyBytes_FromStringAndSize(packed, - sizeof(struct in6_addr)); -#endif - } else { - PyErr_SetString(socket_error, "unknown address family"); - return NULL; - } + } else if (af == AF_INET6) { + return PyBytes_FromStringAndSize(packed, + sizeof(struct in6_addr)); +#endif + } else { + PyErr_SetString(socket_error, "unknown address family"); + return NULL; + } } PyDoc_STRVAR(inet_ntop_doc, @@ -3717,54 +3717,54 @@ static PyObject * socket_inet_ntop(PyObject *self, PyObject *args) { - int af; - char* packed; - int len; - const char* retval; + int af; + char* packed; + int len; + const char* retval; #ifdef ENABLE_IPV6 - char ip[MAX(INET_ADDRSTRLEN, INET6_ADDRSTRLEN) + 1]; + char ip[MAX(INET_ADDRSTRLEN, INET6_ADDRSTRLEN) + 1]; #else - char ip[INET_ADDRSTRLEN + 1]; + char ip[INET_ADDRSTRLEN + 1]; #endif - /* Guarantee NUL-termination for PyUnicode_FromString() below */ - memset((void *) &ip[0], '\0', sizeof(ip)); + /* Guarantee NUL-termination for PyUnicode_FromString() below */ + memset((void *) &ip[0], '\0', sizeof(ip)); - if (!PyArg_ParseTuple(args, "iy#:inet_ntop", &af, &packed, &len)) { - return NULL; - } + if (!PyArg_ParseTuple(args, "iy#:inet_ntop", &af, &packed, &len)) { + return NULL; + } - if (af == AF_INET) { - if (len != sizeof(struct in_addr)) { - PyErr_SetString(PyExc_ValueError, - "invalid length of packed IP address string"); - return NULL; - } + if (af == AF_INET) { + if (len != sizeof(struct in_addr)) { + PyErr_SetString(PyExc_ValueError, + "invalid length of packed IP address string"); + return NULL; + } #ifdef ENABLE_IPV6 - } else if (af == AF_INET6) { - if (len != sizeof(struct in6_addr)) { - PyErr_SetString(PyExc_ValueError, - "invalid length of packed IP address string"); - return NULL; - } -#endif - } else { - PyErr_Format(PyExc_ValueError, - "unknown address family %d", af); - return NULL; - } - - retval = inet_ntop(af, packed, ip, sizeof(ip)); - if (!retval) { - PyErr_SetFromErrno(socket_error); - return NULL; - } else { - return PyUnicode_FromString(retval); - } - - /* NOTREACHED */ - PyErr_SetString(PyExc_RuntimeError, "invalid handling of inet_ntop"); - return NULL; + } else if (af == AF_INET6) { + if (len != sizeof(struct in6_addr)) { + PyErr_SetString(PyExc_ValueError, + "invalid length of packed IP address string"); + return NULL; + } +#endif + } else { + PyErr_Format(PyExc_ValueError, + "unknown address family %d", af); + return NULL; + } + + retval = inet_ntop(af, packed, ip, sizeof(ip)); + if (!retval) { + PyErr_SetFromErrno(socket_error); + return NULL; + } else { + return PyUnicode_FromString(retval); + } + + /* NOTREACHED */ + PyErr_SetString(PyExc_RuntimeError, "invalid handling of inet_ntop"); + return NULL; } #endif /* HAVE_INET_PTON */ @@ -3775,100 +3775,100 @@ static PyObject * socket_getaddrinfo(PyObject *self, PyObject *args) { - struct addrinfo hints, *res; - struct addrinfo *res0 = NULL; - PyObject *hobj = NULL; - PyObject *pobj = (PyObject *)NULL; - char pbuf[30]; - char *hptr, *pptr; - int family, socktype, protocol, flags; - int error; - PyObject *all = (PyObject *)NULL; - PyObject *idna = NULL; - - family = socktype = protocol = flags = 0; - family = AF_UNSPEC; - if (!PyArg_ParseTuple(args, "OO|iiii:getaddrinfo", - &hobj, &pobj, &family, &socktype, - &protocol, &flags)) { - return NULL; - } - if (hobj == Py_None) { - hptr = NULL; - } else if (PyUnicode_Check(hobj)) { - idna = PyObject_CallMethod(hobj, "encode", "s", "idna"); - if (!idna) - return NULL; - assert(PyBytes_Check(idna)); - hptr = PyBytes_AS_STRING(idna); - } else if (PyBytes_Check(hobj)) { - hptr = PyBytes_AsString(hobj); - } else { - PyErr_SetString(PyExc_TypeError, - "getaddrinfo() argument 1 must be string or None"); - return NULL; - } - if (PyLong_CheckExact(pobj)) { - long value = PyLong_AsLong(pobj); - if (value == -1 && PyErr_Occurred()) - goto err; - PyOS_snprintf(pbuf, sizeof(pbuf), "%ld", value); - pptr = pbuf; - } else if (PyUnicode_Check(pobj)) { - pptr = _PyUnicode_AsString(pobj); - } else if (PyBytes_Check(pobj)) { - pptr = PyBytes_AsString(pobj); - } else if (pobj == Py_None) { - pptr = (char *)NULL; - } else { - PyErr_SetString(socket_error, "Int or String expected"); - goto err; - } - memset(&hints, 0, sizeof(hints)); - hints.ai_family = family; - hints.ai_socktype = socktype; - hints.ai_protocol = protocol; - hints.ai_flags = flags; - Py_BEGIN_ALLOW_THREADS - ACQUIRE_GETADDRINFO_LOCK - error = getaddrinfo(hptr, pptr, &hints, &res0); - Py_END_ALLOW_THREADS - RELEASE_GETADDRINFO_LOCK /* see comment in setipaddr() */ - if (error) { - set_gaierror(error); - goto err; - } - - if ((all = PyList_New(0)) == NULL) - goto err; - for (res = res0; res; res = res->ai_next) { - PyObject *single; - PyObject *addr = - makesockaddr(-1, res->ai_addr, res->ai_addrlen, protocol); - if (addr == NULL) - goto err; - single = Py_BuildValue("iiisO", res->ai_family, - res->ai_socktype, res->ai_protocol, - res->ai_canonname ? res->ai_canonname : "", - addr); - Py_DECREF(addr); - if (single == NULL) - goto err; - - if (PyList_Append(all, single)) - goto err; - Py_XDECREF(single); - } - Py_XDECREF(idna); - if (res0) - freeaddrinfo(res0); - return all; + struct addrinfo hints, *res; + struct addrinfo *res0 = NULL; + PyObject *hobj = NULL; + PyObject *pobj = (PyObject *)NULL; + char pbuf[30]; + char *hptr, *pptr; + int family, socktype, protocol, flags; + int error; + PyObject *all = (PyObject *)NULL; + PyObject *idna = NULL; + + family = socktype = protocol = flags = 0; + family = AF_UNSPEC; + if (!PyArg_ParseTuple(args, "OO|iiii:getaddrinfo", + &hobj, &pobj, &family, &socktype, + &protocol, &flags)) { + return NULL; + } + if (hobj == Py_None) { + hptr = NULL; + } else if (PyUnicode_Check(hobj)) { + idna = PyObject_CallMethod(hobj, "encode", "s", "idna"); + if (!idna) + return NULL; + assert(PyBytes_Check(idna)); + hptr = PyBytes_AS_STRING(idna); + } else if (PyBytes_Check(hobj)) { + hptr = PyBytes_AsString(hobj); + } else { + PyErr_SetString(PyExc_TypeError, + "getaddrinfo() argument 1 must be string or None"); + return NULL; + } + if (PyLong_CheckExact(pobj)) { + long value = PyLong_AsLong(pobj); + if (value == -1 && PyErr_Occurred()) + goto err; + PyOS_snprintf(pbuf, sizeof(pbuf), "%ld", value); + pptr = pbuf; + } else if (PyUnicode_Check(pobj)) { + pptr = _PyUnicode_AsString(pobj); + } else if (PyBytes_Check(pobj)) { + pptr = PyBytes_AsString(pobj); + } else if (pobj == Py_None) { + pptr = (char *)NULL; + } else { + PyErr_SetString(socket_error, "Int or String expected"); + goto err; + } + memset(&hints, 0, sizeof(hints)); + hints.ai_family = family; + hints.ai_socktype = socktype; + hints.ai_protocol = protocol; + hints.ai_flags = flags; + Py_BEGIN_ALLOW_THREADS + ACQUIRE_GETADDRINFO_LOCK + error = getaddrinfo(hptr, pptr, &hints, &res0); + Py_END_ALLOW_THREADS + RELEASE_GETADDRINFO_LOCK /* see comment in setipaddr() */ + if (error) { + set_gaierror(error); + goto err; + } + + if ((all = PyList_New(0)) == NULL) + goto err; + for (res = res0; res; res = res->ai_next) { + PyObject *single; + PyObject *addr = + makesockaddr(-1, res->ai_addr, res->ai_addrlen, protocol); + if (addr == NULL) + goto err; + single = Py_BuildValue("iiisO", res->ai_family, + res->ai_socktype, res->ai_protocol, + res->ai_canonname ? res->ai_canonname : "", + addr); + Py_DECREF(addr); + if (single == NULL) + goto err; + + if (PyList_Append(all, single)) + goto err; + Py_XDECREF(single); + } + Py_XDECREF(idna); + if (res0) + freeaddrinfo(res0); + return all; err: - Py_XDECREF(all); - Py_XDECREF(idna); - if (res0) - freeaddrinfo(res0); - return (PyObject *)NULL; + Py_XDECREF(all); + Py_XDECREF(idna); + if (res0) + freeaddrinfo(res0); + return (PyObject *)NULL; } PyDoc_STRVAR(getaddrinfo_doc, @@ -3883,77 +3883,77 @@ static PyObject * socket_getnameinfo(PyObject *self, PyObject *args) { - PyObject *sa = (PyObject *)NULL; - int flags; - char *hostp; - int port, flowinfo, scope_id; - char hbuf[NI_MAXHOST], pbuf[NI_MAXSERV]; - struct addrinfo hints, *res = NULL; - int error; - PyObject *ret = (PyObject *)NULL; - - flags = flowinfo = scope_id = 0; - if (!PyArg_ParseTuple(args, "Oi:getnameinfo", &sa, &flags)) - return NULL; - if (!PyTuple_Check(sa)) { - PyErr_SetString(PyExc_TypeError, - "getnameinfo() argument 1 must be a tuple"); - return NULL; - } - if (!PyArg_ParseTuple(sa, "si|ii", - &hostp, &port, &flowinfo, &scope_id)) - return NULL; - PyOS_snprintf(pbuf, sizeof(pbuf), "%d", port); - memset(&hints, 0, sizeof(hints)); - hints.ai_family = AF_UNSPEC; - hints.ai_socktype = SOCK_DGRAM; /* make numeric port happy */ - Py_BEGIN_ALLOW_THREADS - ACQUIRE_GETADDRINFO_LOCK - error = getaddrinfo(hostp, pbuf, &hints, &res); - Py_END_ALLOW_THREADS - RELEASE_GETADDRINFO_LOCK /* see comment in setipaddr() */ - if (error) { - set_gaierror(error); - goto fail; - } - if (res->ai_next) { - PyErr_SetString(socket_error, - "sockaddr resolved to multiple addresses"); - goto fail; - } - switch (res->ai_family) { - case AF_INET: - { - if (PyTuple_GET_SIZE(sa) != 2) { - PyErr_SetString(socket_error, - "IPv4 sockaddr must be 2 tuple"); - goto fail; - } - break; - } + PyObject *sa = (PyObject *)NULL; + int flags; + char *hostp; + int port, flowinfo, scope_id; + char hbuf[NI_MAXHOST], pbuf[NI_MAXSERV]; + struct addrinfo hints, *res = NULL; + int error; + PyObject *ret = (PyObject *)NULL; + + flags = flowinfo = scope_id = 0; + if (!PyArg_ParseTuple(args, "Oi:getnameinfo", &sa, &flags)) + return NULL; + if (!PyTuple_Check(sa)) { + PyErr_SetString(PyExc_TypeError, + "getnameinfo() argument 1 must be a tuple"); + return NULL; + } + if (!PyArg_ParseTuple(sa, "si|ii", + &hostp, &port, &flowinfo, &scope_id)) + return NULL; + PyOS_snprintf(pbuf, sizeof(pbuf), "%d", port); + memset(&hints, 0, sizeof(hints)); + hints.ai_family = AF_UNSPEC; + hints.ai_socktype = SOCK_DGRAM; /* make numeric port happy */ + Py_BEGIN_ALLOW_THREADS + ACQUIRE_GETADDRINFO_LOCK + error = getaddrinfo(hostp, pbuf, &hints, &res); + Py_END_ALLOW_THREADS + RELEASE_GETADDRINFO_LOCK /* see comment in setipaddr() */ + if (error) { + set_gaierror(error); + goto fail; + } + if (res->ai_next) { + PyErr_SetString(socket_error, + "sockaddr resolved to multiple addresses"); + goto fail; + } + switch (res->ai_family) { + case AF_INET: + { + if (PyTuple_GET_SIZE(sa) != 2) { + PyErr_SetString(socket_error, + "IPv4 sockaddr must be 2 tuple"); + goto fail; + } + break; + } #ifdef ENABLE_IPV6 - case AF_INET6: - { - struct sockaddr_in6 *sin6; - sin6 = (struct sockaddr_in6 *)res->ai_addr; - sin6->sin6_flowinfo = flowinfo; - sin6->sin6_scope_id = scope_id; - break; - } -#endif - } - error = getnameinfo(res->ai_addr, res->ai_addrlen, - hbuf, sizeof(hbuf), pbuf, sizeof(pbuf), flags); - if (error) { - set_gaierror(error); - goto fail; - } - ret = Py_BuildValue("ss", hbuf, pbuf); + case AF_INET6: + { + struct sockaddr_in6 *sin6; + sin6 = (struct sockaddr_in6 *)res->ai_addr; + sin6->sin6_flowinfo = flowinfo; + sin6->sin6_scope_id = scope_id; + break; + } +#endif + } + error = getnameinfo(res->ai_addr, res->ai_addrlen, + hbuf, sizeof(hbuf), pbuf, sizeof(pbuf), flags); + if (error) { + set_gaierror(error); + goto fail; + } + ret = Py_BuildValue("ss", hbuf, pbuf); fail: - if (res) - freeaddrinfo(res); - return ret; + if (res) + freeaddrinfo(res); + return ret; } PyDoc_STRVAR(getnameinfo_doc, @@ -3967,12 +3967,12 @@ static PyObject * socket_getdefaulttimeout(PyObject *self) { - if (defaulttimeout < 0.0) { - Py_INCREF(Py_None); - return Py_None; - } - else - return PyFloat_FromDouble(defaulttimeout); + if (defaulttimeout < 0.0) { + Py_INCREF(Py_None); + return Py_None; + } + else + return PyFloat_FromDouble(defaulttimeout); } PyDoc_STRVAR(getdefaulttimeout_doc, @@ -3985,24 +3985,24 @@ static PyObject * socket_setdefaulttimeout(PyObject *self, PyObject *arg) { - double timeout; + double timeout; - if (arg == Py_None) - timeout = -1.0; - else { - timeout = PyFloat_AsDouble(arg); - if (timeout < 0.0) { - if (!PyErr_Occurred()) - PyErr_SetString(PyExc_ValueError, - "Timeout value out of range"); - return NULL; - } - } + if (arg == Py_None) + timeout = -1.0; + else { + timeout = PyFloat_AsDouble(arg); + if (timeout < 0.0) { + if (!PyErr_Occurred()) + PyErr_SetString(PyExc_ValueError, + "Timeout value out of range"); + return NULL; + } + } - defaulttimeout = timeout; + defaulttimeout = timeout; - Py_INCREF(Py_None); - return Py_None; + Py_INCREF(Py_None); + return Py_None; } PyDoc_STRVAR(setdefaulttimeout_doc, @@ -4016,55 +4016,55 @@ /* List of functions exported by this module. */ static PyMethodDef socket_methods[] = { - {"gethostbyname", socket_gethostbyname, - METH_VARARGS, gethostbyname_doc}, - {"gethostbyname_ex", socket_gethostbyname_ex, - METH_VARARGS, ghbn_ex_doc}, - {"gethostbyaddr", socket_gethostbyaddr, - METH_VARARGS, gethostbyaddr_doc}, - {"gethostname", socket_gethostname, - METH_NOARGS, gethostname_doc}, - {"getservbyname", socket_getservbyname, - METH_VARARGS, getservbyname_doc}, - {"getservbyport", socket_getservbyport, - METH_VARARGS, getservbyport_doc}, - {"getprotobyname", socket_getprotobyname, - METH_VARARGS, getprotobyname_doc}, + {"gethostbyname", socket_gethostbyname, + METH_VARARGS, gethostbyname_doc}, + {"gethostbyname_ex", socket_gethostbyname_ex, + METH_VARARGS, ghbn_ex_doc}, + {"gethostbyaddr", socket_gethostbyaddr, + METH_VARARGS, gethostbyaddr_doc}, + {"gethostname", socket_gethostname, + METH_NOARGS, gethostname_doc}, + {"getservbyname", socket_getservbyname, + METH_VARARGS, getservbyname_doc}, + {"getservbyport", socket_getservbyport, + METH_VARARGS, getservbyport_doc}, + {"getprotobyname", socket_getprotobyname, + METH_VARARGS, getprotobyname_doc}, #ifndef NO_DUP - {"dup", socket_dup, - METH_O, dup_doc}, + {"dup", socket_dup, + METH_O, dup_doc}, #endif #ifdef HAVE_SOCKETPAIR - {"socketpair", socket_socketpair, - METH_VARARGS, socketpair_doc}, + {"socketpair", socket_socketpair, + METH_VARARGS, socketpair_doc}, #endif - {"ntohs", socket_ntohs, - METH_VARARGS, ntohs_doc}, - {"ntohl", socket_ntohl, - METH_O, ntohl_doc}, - {"htons", socket_htons, - METH_VARARGS, htons_doc}, - {"htonl", socket_htonl, - METH_O, htonl_doc}, - {"inet_aton", socket_inet_aton, - METH_VARARGS, inet_aton_doc}, - {"inet_ntoa", socket_inet_ntoa, - METH_VARARGS, inet_ntoa_doc}, + {"ntohs", socket_ntohs, + METH_VARARGS, ntohs_doc}, + {"ntohl", socket_ntohl, + METH_O, ntohl_doc}, + {"htons", socket_htons, + METH_VARARGS, htons_doc}, + {"htonl", socket_htonl, + METH_O, htonl_doc}, + {"inet_aton", socket_inet_aton, + METH_VARARGS, inet_aton_doc}, + {"inet_ntoa", socket_inet_ntoa, + METH_VARARGS, inet_ntoa_doc}, #ifdef HAVE_INET_PTON - {"inet_pton", socket_inet_pton, - METH_VARARGS, inet_pton_doc}, - {"inet_ntop", socket_inet_ntop, - METH_VARARGS, inet_ntop_doc}, -#endif - {"getaddrinfo", socket_getaddrinfo, - METH_VARARGS, getaddrinfo_doc}, - {"getnameinfo", socket_getnameinfo, - METH_VARARGS, getnameinfo_doc}, - {"getdefaulttimeout", (PyCFunction)socket_getdefaulttimeout, - METH_NOARGS, getdefaulttimeout_doc}, - {"setdefaulttimeout", socket_setdefaulttimeout, - METH_O, setdefaulttimeout_doc}, - {NULL, NULL} /* Sentinel */ + {"inet_pton", socket_inet_pton, + METH_VARARGS, inet_pton_doc}, + {"inet_ntop", socket_inet_ntop, + METH_VARARGS, inet_ntop_doc}, +#endif + {"getaddrinfo", socket_getaddrinfo, + METH_VARARGS, getaddrinfo_doc}, + {"getnameinfo", socket_getnameinfo, + METH_VARARGS, getnameinfo_doc}, + {"getdefaulttimeout", (PyCFunction)socket_getdefaulttimeout, + METH_NOARGS, getdefaulttimeout_doc}, + {"setdefaulttimeout", socket_setdefaulttimeout, + METH_O, setdefaulttimeout_doc}, + {NULL, NULL} /* Sentinel */ }; @@ -4076,34 +4076,34 @@ static void os_cleanup(void) { - WSACleanup(); + WSACleanup(); } static int os_init(void) { - WSADATA WSAData; - int ret; - ret = WSAStartup(0x0101, &WSAData); - switch (ret) { - case 0: /* No error */ - Py_AtExit(os_cleanup); - return 1; /* Success */ - case WSASYSNOTREADY: - PyErr_SetString(PyExc_ImportError, - "WSAStartup failed: network not ready"); - break; - case WSAVERNOTSUPPORTED: - case WSAEINVAL: - PyErr_SetString( - PyExc_ImportError, - "WSAStartup failed: requested version not supported"); - break; - default: - PyErr_Format(PyExc_ImportError, "WSAStartup failed: error code %d", ret); - break; - } - return 0; /* Failure */ + WSADATA WSAData; + int ret; + ret = WSAStartup(0x0101, &WSAData); + switch (ret) { + case 0: /* No error */ + Py_AtExit(os_cleanup); + return 1; /* Success */ + case WSASYSNOTREADY: + PyErr_SetString(PyExc_ImportError, + "WSAStartup failed: network not ready"); + break; + case WSAVERNOTSUPPORTED: + case WSAEINVAL: + PyErr_SetString( + PyExc_ImportError, + "WSAStartup failed: requested version not supported"); + break; + default: + PyErr_Format(PyExc_ImportError, "WSAStartup failed: error code %d", ret); + break; + } + return 0; /* Failure */ } #endif /* MS_WINDOWS */ @@ -4118,18 +4118,18 @@ os_init(void) { #ifndef PYCC_GCC - int rc = sock_init(); + int rc = sock_init(); - if (rc == 0) { - return 1; /* Success */ - } + if (rc == 0) { + return 1; /* Success */ + } - PyErr_Format(PyExc_ImportError, "OS/2 TCP/IP Error# %d", sock_errno()); + PyErr_Format(PyExc_ImportError, "OS/2 TCP/IP Error# %d", sock_errno()); - return 0; /* Failure */ + return 0; /* Failure */ #else - /* No need to initialise sockets with GCC/EMX */ - return 1; /* Success */ + /* No need to initialise sockets with GCC/EMX */ + return 1; /* Success */ #endif } @@ -4140,7 +4140,7 @@ static int os_init(void) { - return 1; /* Success */ + return 1; /* Success */ } #endif @@ -4150,8 +4150,8 @@ static PySocketModule_APIObject PySocketModuleAPI = { - &sock_type, - NULL + &sock_type, + NULL }; @@ -4171,923 +4171,923 @@ See the socket module for documentation."); static struct PyModuleDef socketmodule = { - PyModuleDef_HEAD_INIT, - PySocket_MODULE_NAME, - socket_doc, - -1, - socket_methods, - NULL, - NULL, - NULL, - NULL + PyModuleDef_HEAD_INIT, + PySocket_MODULE_NAME, + socket_doc, + -1, + socket_methods, + NULL, + NULL, + NULL, + NULL }; PyMODINIT_FUNC PyInit__socket(void) { - PyObject *m, *has_ipv6; + PyObject *m, *has_ipv6; - if (!os_init()) - return NULL; + if (!os_init()) + return NULL; - Py_TYPE(&sock_type) = &PyType_Type; - m = PyModule_Create(&socketmodule); - if (m == NULL) - return NULL; - - socket_error = PyErr_NewException("socket.error", - PyExc_IOError, NULL); - if (socket_error == NULL) - return NULL; - PySocketModuleAPI.error = socket_error; - Py_INCREF(socket_error); - PyModule_AddObject(m, "error", socket_error); - socket_herror = PyErr_NewException("socket.herror", - socket_error, NULL); - if (socket_herror == NULL) - return NULL; - Py_INCREF(socket_herror); - PyModule_AddObject(m, "herror", socket_herror); - socket_gaierror = PyErr_NewException("socket.gaierror", socket_error, - NULL); - if (socket_gaierror == NULL) - return NULL; - Py_INCREF(socket_gaierror); - PyModule_AddObject(m, "gaierror", socket_gaierror); - socket_timeout = PyErr_NewException("socket.timeout", - socket_error, NULL); - if (socket_timeout == NULL) - return NULL; - Py_INCREF(socket_timeout); - PyModule_AddObject(m, "timeout", socket_timeout); - Py_INCREF((PyObject *)&sock_type); - if (PyModule_AddObject(m, "SocketType", - (PyObject *)&sock_type) != 0) - return NULL; - Py_INCREF((PyObject *)&sock_type); - if (PyModule_AddObject(m, "socket", - (PyObject *)&sock_type) != 0) - return NULL; + Py_TYPE(&sock_type) = &PyType_Type; + m = PyModule_Create(&socketmodule); + if (m == NULL) + return NULL; + + socket_error = PyErr_NewException("socket.error", + PyExc_IOError, NULL); + if (socket_error == NULL) + return NULL; + PySocketModuleAPI.error = socket_error; + Py_INCREF(socket_error); + PyModule_AddObject(m, "error", socket_error); + socket_herror = PyErr_NewException("socket.herror", + socket_error, NULL); + if (socket_herror == NULL) + return NULL; + Py_INCREF(socket_herror); + PyModule_AddObject(m, "herror", socket_herror); + socket_gaierror = PyErr_NewException("socket.gaierror", socket_error, + NULL); + if (socket_gaierror == NULL) + return NULL; + Py_INCREF(socket_gaierror); + PyModule_AddObject(m, "gaierror", socket_gaierror); + socket_timeout = PyErr_NewException("socket.timeout", + socket_error, NULL); + if (socket_timeout == NULL) + return NULL; + Py_INCREF(socket_timeout); + PyModule_AddObject(m, "timeout", socket_timeout); + Py_INCREF((PyObject *)&sock_type); + if (PyModule_AddObject(m, "SocketType", + (PyObject *)&sock_type) != 0) + return NULL; + Py_INCREF((PyObject *)&sock_type); + if (PyModule_AddObject(m, "socket", + (PyObject *)&sock_type) != 0) + return NULL; #ifdef ENABLE_IPV6 - has_ipv6 = Py_True; + has_ipv6 = Py_True; #else - has_ipv6 = Py_False; + has_ipv6 = Py_False; #endif - Py_INCREF(has_ipv6); - PyModule_AddObject(m, "has_ipv6", has_ipv6); + Py_INCREF(has_ipv6); + PyModule_AddObject(m, "has_ipv6", has_ipv6); - /* Export C API */ - if (PyModule_AddObject(m, PySocket_CAPI_NAME, - PyCapsule_New(&PySocketModuleAPI, PySocket_CAPSULE_NAME, NULL) - ) != 0) - return NULL; + /* Export C API */ + if (PyModule_AddObject(m, PySocket_CAPI_NAME, + PyCapsule_New(&PySocketModuleAPI, PySocket_CAPSULE_NAME, NULL) + ) != 0) + return NULL; - /* Address families (we only support AF_INET and AF_UNIX) */ + /* Address families (we only support AF_INET and AF_UNIX) */ #ifdef AF_UNSPEC - PyModule_AddIntConstant(m, "AF_UNSPEC", AF_UNSPEC); + PyModule_AddIntConstant(m, "AF_UNSPEC", AF_UNSPEC); #endif - PyModule_AddIntConstant(m, "AF_INET", AF_INET); + PyModule_AddIntConstant(m, "AF_INET", AF_INET); #ifdef AF_INET6 - PyModule_AddIntConstant(m, "AF_INET6", AF_INET6); + PyModule_AddIntConstant(m, "AF_INET6", AF_INET6); #endif /* AF_INET6 */ #if defined(AF_UNIX) - PyModule_AddIntConstant(m, "AF_UNIX", AF_UNIX); + PyModule_AddIntConstant(m, "AF_UNIX", AF_UNIX); #endif /* AF_UNIX */ #ifdef AF_AX25 - /* Amateur Radio AX.25 */ - PyModule_AddIntConstant(m, "AF_AX25", AF_AX25); + /* Amateur Radio AX.25 */ + PyModule_AddIntConstant(m, "AF_AX25", AF_AX25); #endif #ifdef AF_IPX - PyModule_AddIntConstant(m, "AF_IPX", AF_IPX); /* Novell IPX */ + PyModule_AddIntConstant(m, "AF_IPX", AF_IPX); /* Novell IPX */ #endif #ifdef AF_APPLETALK - /* Appletalk DDP */ - PyModule_AddIntConstant(m, "AF_APPLETALK", AF_APPLETALK); + /* Appletalk DDP */ + PyModule_AddIntConstant(m, "AF_APPLETALK", AF_APPLETALK); #endif #ifdef AF_NETROM - /* Amateur radio NetROM */ - PyModule_AddIntConstant(m, "AF_NETROM", AF_NETROM); + /* Amateur radio NetROM */ + PyModule_AddIntConstant(m, "AF_NETROM", AF_NETROM); #endif #ifdef AF_BRIDGE - /* Multiprotocol bridge */ - PyModule_AddIntConstant(m, "AF_BRIDGE", AF_BRIDGE); + /* Multiprotocol bridge */ + PyModule_AddIntConstant(m, "AF_BRIDGE", AF_BRIDGE); #endif #ifdef AF_ATMPVC - /* ATM PVCs */ - PyModule_AddIntConstant(m, "AF_ATMPVC", AF_ATMPVC); + /* ATM PVCs */ + PyModule_AddIntConstant(m, "AF_ATMPVC", AF_ATMPVC); #endif #ifdef AF_AAL5 - /* Reserved for Werner's ATM */ - PyModule_AddIntConstant(m, "AF_AAL5", AF_AAL5); + /* Reserved for Werner's ATM */ + PyModule_AddIntConstant(m, "AF_AAL5", AF_AAL5); #endif #ifdef AF_X25 - /* Reserved for X.25 project */ - PyModule_AddIntConstant(m, "AF_X25", AF_X25); + /* Reserved for X.25 project */ + PyModule_AddIntConstant(m, "AF_X25", AF_X25); #endif #ifdef AF_INET6 - PyModule_AddIntConstant(m, "AF_INET6", AF_INET6); /* IP version 6 */ + PyModule_AddIntConstant(m, "AF_INET6", AF_INET6); /* IP version 6 */ #endif #ifdef AF_ROSE - /* Amateur Radio X.25 PLP */ - PyModule_AddIntConstant(m, "AF_ROSE", AF_ROSE); + /* Amateur Radio X.25 PLP */ + PyModule_AddIntConstant(m, "AF_ROSE", AF_ROSE); #endif #ifdef AF_DECnet - /* Reserved for DECnet project */ - PyModule_AddIntConstant(m, "AF_DECnet", AF_DECnet); + /* Reserved for DECnet project */ + PyModule_AddIntConstant(m, "AF_DECnet", AF_DECnet); #endif #ifdef AF_NETBEUI - /* Reserved for 802.2LLC project */ - PyModule_AddIntConstant(m, "AF_NETBEUI", AF_NETBEUI); + /* Reserved for 802.2LLC project */ + PyModule_AddIntConstant(m, "AF_NETBEUI", AF_NETBEUI); #endif #ifdef AF_SECURITY - /* Security callback pseudo AF */ - PyModule_AddIntConstant(m, "AF_SECURITY", AF_SECURITY); + /* Security callback pseudo AF */ + PyModule_AddIntConstant(m, "AF_SECURITY", AF_SECURITY); #endif #ifdef AF_KEY - /* PF_KEY key management API */ - PyModule_AddIntConstant(m, "AF_KEY", AF_KEY); + /* PF_KEY key management API */ + PyModule_AddIntConstant(m, "AF_KEY", AF_KEY); #endif #ifdef AF_NETLINK - /* */ - PyModule_AddIntConstant(m, "AF_NETLINK", AF_NETLINK); - PyModule_AddIntConstant(m, "NETLINK_ROUTE", NETLINK_ROUTE); + /* */ + PyModule_AddIntConstant(m, "AF_NETLINK", AF_NETLINK); + PyModule_AddIntConstant(m, "NETLINK_ROUTE", NETLINK_ROUTE); #ifdef NETLINK_SKIP - PyModule_AddIntConstant(m, "NETLINK_SKIP", NETLINK_SKIP); + PyModule_AddIntConstant(m, "NETLINK_SKIP", NETLINK_SKIP); #endif #ifdef NETLINK_W1 - PyModule_AddIntConstant(m, "NETLINK_W1", NETLINK_W1); + PyModule_AddIntConstant(m, "NETLINK_W1", NETLINK_W1); #endif - PyModule_AddIntConstant(m, "NETLINK_USERSOCK", NETLINK_USERSOCK); - PyModule_AddIntConstant(m, "NETLINK_FIREWALL", NETLINK_FIREWALL); + PyModule_AddIntConstant(m, "NETLINK_USERSOCK", NETLINK_USERSOCK); + PyModule_AddIntConstant(m, "NETLINK_FIREWALL", NETLINK_FIREWALL); #ifdef NETLINK_TCPDIAG - PyModule_AddIntConstant(m, "NETLINK_TCPDIAG", NETLINK_TCPDIAG); + PyModule_AddIntConstant(m, "NETLINK_TCPDIAG", NETLINK_TCPDIAG); #endif #ifdef NETLINK_NFLOG - PyModule_AddIntConstant(m, "NETLINK_NFLOG", NETLINK_NFLOG); + PyModule_AddIntConstant(m, "NETLINK_NFLOG", NETLINK_NFLOG); #endif #ifdef NETLINK_XFRM - PyModule_AddIntConstant(m, "NETLINK_XFRM", NETLINK_XFRM); + PyModule_AddIntConstant(m, "NETLINK_XFRM", NETLINK_XFRM); #endif #ifdef NETLINK_ARPD - PyModule_AddIntConstant(m, "NETLINK_ARPD", NETLINK_ARPD); + PyModule_AddIntConstant(m, "NETLINK_ARPD", NETLINK_ARPD); #endif #ifdef NETLINK_ROUTE6 - PyModule_AddIntConstant(m, "NETLINK_ROUTE6", NETLINK_ROUTE6); + PyModule_AddIntConstant(m, "NETLINK_ROUTE6", NETLINK_ROUTE6); #endif - PyModule_AddIntConstant(m, "NETLINK_IP6_FW", NETLINK_IP6_FW); + PyModule_AddIntConstant(m, "NETLINK_IP6_FW", NETLINK_IP6_FW); #ifdef NETLINK_DNRTMSG - PyModule_AddIntConstant(m, "NETLINK_DNRTMSG", NETLINK_DNRTMSG); + PyModule_AddIntConstant(m, "NETLINK_DNRTMSG", NETLINK_DNRTMSG); #endif #ifdef NETLINK_TAPBASE - PyModule_AddIntConstant(m, "NETLINK_TAPBASE", NETLINK_TAPBASE); + PyModule_AddIntConstant(m, "NETLINK_TAPBASE", NETLINK_TAPBASE); #endif #endif /* AF_NETLINK */ #ifdef AF_ROUTE - /* Alias to emulate 4.4BSD */ - PyModule_AddIntConstant(m, "AF_ROUTE", AF_ROUTE); + /* Alias to emulate 4.4BSD */ + PyModule_AddIntConstant(m, "AF_ROUTE", AF_ROUTE); #endif #ifdef AF_ASH - /* Ash */ - PyModule_AddIntConstant(m, "AF_ASH", AF_ASH); + /* Ash */ + PyModule_AddIntConstant(m, "AF_ASH", AF_ASH); #endif #ifdef AF_ECONET - /* Acorn Econet */ - PyModule_AddIntConstant(m, "AF_ECONET", AF_ECONET); + /* Acorn Econet */ + PyModule_AddIntConstant(m, "AF_ECONET", AF_ECONET); #endif #ifdef AF_ATMSVC - /* ATM SVCs */ - PyModule_AddIntConstant(m, "AF_ATMSVC", AF_ATMSVC); + /* ATM SVCs */ + PyModule_AddIntConstant(m, "AF_ATMSVC", AF_ATMSVC); #endif #ifdef AF_SNA - /* Linux SNA Project (nutters!) */ - PyModule_AddIntConstant(m, "AF_SNA", AF_SNA); + /* Linux SNA Project (nutters!) */ + PyModule_AddIntConstant(m, "AF_SNA", AF_SNA); #endif #ifdef AF_IRDA - /* IRDA sockets */ - PyModule_AddIntConstant(m, "AF_IRDA", AF_IRDA); + /* IRDA sockets */ + PyModule_AddIntConstant(m, "AF_IRDA", AF_IRDA); #endif #ifdef AF_PPPOX - /* PPPoX sockets */ - PyModule_AddIntConstant(m, "AF_PPPOX", AF_PPPOX); + /* PPPoX sockets */ + PyModule_AddIntConstant(m, "AF_PPPOX", AF_PPPOX); #endif #ifdef AF_WANPIPE - /* Wanpipe API Sockets */ - PyModule_AddIntConstant(m, "AF_WANPIPE", AF_WANPIPE); + /* Wanpipe API Sockets */ + PyModule_AddIntConstant(m, "AF_WANPIPE", AF_WANPIPE); #endif #ifdef AF_LLC - /* Linux LLC */ - PyModule_AddIntConstant(m, "AF_LLC", AF_LLC); + /* Linux LLC */ + PyModule_AddIntConstant(m, "AF_LLC", AF_LLC); #endif #ifdef USE_BLUETOOTH - PyModule_AddIntConstant(m, "AF_BLUETOOTH", AF_BLUETOOTH); - PyModule_AddIntConstant(m, "BTPROTO_L2CAP", BTPROTO_L2CAP); - PyModule_AddIntConstant(m, "BTPROTO_HCI", BTPROTO_HCI); - PyModule_AddIntConstant(m, "SOL_HCI", SOL_HCI); - PyModule_AddIntConstant(m, "HCI_FILTER", HCI_FILTER); + PyModule_AddIntConstant(m, "AF_BLUETOOTH", AF_BLUETOOTH); + PyModule_AddIntConstant(m, "BTPROTO_L2CAP", BTPROTO_L2CAP); + PyModule_AddIntConstant(m, "BTPROTO_HCI", BTPROTO_HCI); + PyModule_AddIntConstant(m, "SOL_HCI", SOL_HCI); + PyModule_AddIntConstant(m, "HCI_FILTER", HCI_FILTER); #if !defined(__FreeBSD__) - PyModule_AddIntConstant(m, "HCI_TIME_STAMP", HCI_TIME_STAMP); - PyModule_AddIntConstant(m, "HCI_DATA_DIR", HCI_DATA_DIR); - PyModule_AddIntConstant(m, "BTPROTO_SCO", BTPROTO_SCO); -#endif - PyModule_AddIntConstant(m, "BTPROTO_RFCOMM", BTPROTO_RFCOMM); - PyModule_AddStringConstant(m, "BDADDR_ANY", "00:00:00:00:00:00"); - PyModule_AddStringConstant(m, "BDADDR_LOCAL", "00:00:00:FF:FF:FF"); + PyModule_AddIntConstant(m, "HCI_TIME_STAMP", HCI_TIME_STAMP); + PyModule_AddIntConstant(m, "HCI_DATA_DIR", HCI_DATA_DIR); + PyModule_AddIntConstant(m, "BTPROTO_SCO", BTPROTO_SCO); +#endif + PyModule_AddIntConstant(m, "BTPROTO_RFCOMM", BTPROTO_RFCOMM); + PyModule_AddStringConstant(m, "BDADDR_ANY", "00:00:00:00:00:00"); + PyModule_AddStringConstant(m, "BDADDR_LOCAL", "00:00:00:FF:FF:FF"); #endif #ifdef HAVE_NETPACKET_PACKET_H - PyModule_AddIntConstant(m, "AF_PACKET", AF_PACKET); - PyModule_AddIntConstant(m, "PF_PACKET", PF_PACKET); - PyModule_AddIntConstant(m, "PACKET_HOST", PACKET_HOST); - PyModule_AddIntConstant(m, "PACKET_BROADCAST", PACKET_BROADCAST); - PyModule_AddIntConstant(m, "PACKET_MULTICAST", PACKET_MULTICAST); - PyModule_AddIntConstant(m, "PACKET_OTHERHOST", PACKET_OTHERHOST); - PyModule_AddIntConstant(m, "PACKET_OUTGOING", PACKET_OUTGOING); - PyModule_AddIntConstant(m, "PACKET_LOOPBACK", PACKET_LOOPBACK); - PyModule_AddIntConstant(m, "PACKET_FASTROUTE", PACKET_FASTROUTE); + PyModule_AddIntConstant(m, "AF_PACKET", AF_PACKET); + PyModule_AddIntConstant(m, "PF_PACKET", PF_PACKET); + PyModule_AddIntConstant(m, "PACKET_HOST", PACKET_HOST); + PyModule_AddIntConstant(m, "PACKET_BROADCAST", PACKET_BROADCAST); + PyModule_AddIntConstant(m, "PACKET_MULTICAST", PACKET_MULTICAST); + PyModule_AddIntConstant(m, "PACKET_OTHERHOST", PACKET_OTHERHOST); + PyModule_AddIntConstant(m, "PACKET_OUTGOING", PACKET_OUTGOING); + PyModule_AddIntConstant(m, "PACKET_LOOPBACK", PACKET_LOOPBACK); + PyModule_AddIntConstant(m, "PACKET_FASTROUTE", PACKET_FASTROUTE); #endif #ifdef HAVE_LINUX_TIPC_H - PyModule_AddIntConstant(m, "AF_TIPC", AF_TIPC); + PyModule_AddIntConstant(m, "AF_TIPC", AF_TIPC); - /* for addresses */ - PyModule_AddIntConstant(m, "TIPC_ADDR_NAMESEQ", TIPC_ADDR_NAMESEQ); - PyModule_AddIntConstant(m, "TIPC_ADDR_NAME", TIPC_ADDR_NAME); - PyModule_AddIntConstant(m, "TIPC_ADDR_ID", TIPC_ADDR_ID); - - PyModule_AddIntConstant(m, "TIPC_ZONE_SCOPE", TIPC_ZONE_SCOPE); - PyModule_AddIntConstant(m, "TIPC_CLUSTER_SCOPE", TIPC_CLUSTER_SCOPE); - PyModule_AddIntConstant(m, "TIPC_NODE_SCOPE", TIPC_NODE_SCOPE); - - /* for setsockopt() */ - PyModule_AddIntConstant(m, "SOL_TIPC", SOL_TIPC); - PyModule_AddIntConstant(m, "TIPC_IMPORTANCE", TIPC_IMPORTANCE); - PyModule_AddIntConstant(m, "TIPC_SRC_DROPPABLE", TIPC_SRC_DROPPABLE); - PyModule_AddIntConstant(m, "TIPC_DEST_DROPPABLE", - TIPC_DEST_DROPPABLE); - PyModule_AddIntConstant(m, "TIPC_CONN_TIMEOUT", TIPC_CONN_TIMEOUT); - - PyModule_AddIntConstant(m, "TIPC_LOW_IMPORTANCE", - TIPC_LOW_IMPORTANCE); - PyModule_AddIntConstant(m, "TIPC_MEDIUM_IMPORTANCE", - TIPC_MEDIUM_IMPORTANCE); - PyModule_AddIntConstant(m, "TIPC_HIGH_IMPORTANCE", - TIPC_HIGH_IMPORTANCE); - PyModule_AddIntConstant(m, "TIPC_CRITICAL_IMPORTANCE", - TIPC_CRITICAL_IMPORTANCE); - - /* for subscriptions */ - PyModule_AddIntConstant(m, "TIPC_SUB_PORTS", TIPC_SUB_PORTS); - PyModule_AddIntConstant(m, "TIPC_SUB_SERVICE", TIPC_SUB_SERVICE); + /* for addresses */ + PyModule_AddIntConstant(m, "TIPC_ADDR_NAMESEQ", TIPC_ADDR_NAMESEQ); + PyModule_AddIntConstant(m, "TIPC_ADDR_NAME", TIPC_ADDR_NAME); + PyModule_AddIntConstant(m, "TIPC_ADDR_ID", TIPC_ADDR_ID); + + PyModule_AddIntConstant(m, "TIPC_ZONE_SCOPE", TIPC_ZONE_SCOPE); + PyModule_AddIntConstant(m, "TIPC_CLUSTER_SCOPE", TIPC_CLUSTER_SCOPE); + PyModule_AddIntConstant(m, "TIPC_NODE_SCOPE", TIPC_NODE_SCOPE); + + /* for setsockopt() */ + PyModule_AddIntConstant(m, "SOL_TIPC", SOL_TIPC); + PyModule_AddIntConstant(m, "TIPC_IMPORTANCE", TIPC_IMPORTANCE); + PyModule_AddIntConstant(m, "TIPC_SRC_DROPPABLE", TIPC_SRC_DROPPABLE); + PyModule_AddIntConstant(m, "TIPC_DEST_DROPPABLE", + TIPC_DEST_DROPPABLE); + PyModule_AddIntConstant(m, "TIPC_CONN_TIMEOUT", TIPC_CONN_TIMEOUT); + + PyModule_AddIntConstant(m, "TIPC_LOW_IMPORTANCE", + TIPC_LOW_IMPORTANCE); + PyModule_AddIntConstant(m, "TIPC_MEDIUM_IMPORTANCE", + TIPC_MEDIUM_IMPORTANCE); + PyModule_AddIntConstant(m, "TIPC_HIGH_IMPORTANCE", + TIPC_HIGH_IMPORTANCE); + PyModule_AddIntConstant(m, "TIPC_CRITICAL_IMPORTANCE", + TIPC_CRITICAL_IMPORTANCE); + + /* for subscriptions */ + PyModule_AddIntConstant(m, "TIPC_SUB_PORTS", TIPC_SUB_PORTS); + PyModule_AddIntConstant(m, "TIPC_SUB_SERVICE", TIPC_SUB_SERVICE); #ifdef TIPC_SUB_CANCEL - /* doesn't seem to be available everywhere */ - PyModule_AddIntConstant(m, "TIPC_SUB_CANCEL", TIPC_SUB_CANCEL); + /* doesn't seem to be available everywhere */ + PyModule_AddIntConstant(m, "TIPC_SUB_CANCEL", TIPC_SUB_CANCEL); #endif - PyModule_AddIntConstant(m, "TIPC_WAIT_FOREVER", TIPC_WAIT_FOREVER); - PyModule_AddIntConstant(m, "TIPC_PUBLISHED", TIPC_PUBLISHED); - PyModule_AddIntConstant(m, "TIPC_WITHDRAWN", TIPC_WITHDRAWN); - PyModule_AddIntConstant(m, "TIPC_SUBSCR_TIMEOUT", TIPC_SUBSCR_TIMEOUT); - PyModule_AddIntConstant(m, "TIPC_CFG_SRV", TIPC_CFG_SRV); - PyModule_AddIntConstant(m, "TIPC_TOP_SRV", TIPC_TOP_SRV); + PyModule_AddIntConstant(m, "TIPC_WAIT_FOREVER", TIPC_WAIT_FOREVER); + PyModule_AddIntConstant(m, "TIPC_PUBLISHED", TIPC_PUBLISHED); + PyModule_AddIntConstant(m, "TIPC_WITHDRAWN", TIPC_WITHDRAWN); + PyModule_AddIntConstant(m, "TIPC_SUBSCR_TIMEOUT", TIPC_SUBSCR_TIMEOUT); + PyModule_AddIntConstant(m, "TIPC_CFG_SRV", TIPC_CFG_SRV); + PyModule_AddIntConstant(m, "TIPC_TOP_SRV", TIPC_TOP_SRV); #endif - /* Socket types */ - PyModule_AddIntConstant(m, "SOCK_STREAM", SOCK_STREAM); - PyModule_AddIntConstant(m, "SOCK_DGRAM", SOCK_DGRAM); + /* Socket types */ + PyModule_AddIntConstant(m, "SOCK_STREAM", SOCK_STREAM); + PyModule_AddIntConstant(m, "SOCK_DGRAM", SOCK_DGRAM); /* We have incomplete socket support. */ - PyModule_AddIntConstant(m, "SOCK_RAW", SOCK_RAW); - PyModule_AddIntConstant(m, "SOCK_SEQPACKET", SOCK_SEQPACKET); + PyModule_AddIntConstant(m, "SOCK_RAW", SOCK_RAW); + PyModule_AddIntConstant(m, "SOCK_SEQPACKET", SOCK_SEQPACKET); #if defined(SOCK_RDM) - PyModule_AddIntConstant(m, "SOCK_RDM", SOCK_RDM); + PyModule_AddIntConstant(m, "SOCK_RDM", SOCK_RDM); #endif -#ifdef SO_DEBUG - PyModule_AddIntConstant(m, "SO_DEBUG", SO_DEBUG); +#ifdef SO_DEBUG + PyModule_AddIntConstant(m, "SO_DEBUG", SO_DEBUG); #endif -#ifdef SO_ACCEPTCONN - PyModule_AddIntConstant(m, "SO_ACCEPTCONN", SO_ACCEPTCONN); +#ifdef SO_ACCEPTCONN + PyModule_AddIntConstant(m, "SO_ACCEPTCONN", SO_ACCEPTCONN); #endif -#ifdef SO_REUSEADDR - PyModule_AddIntConstant(m, "SO_REUSEADDR", SO_REUSEADDR); +#ifdef SO_REUSEADDR + PyModule_AddIntConstant(m, "SO_REUSEADDR", SO_REUSEADDR); #endif #ifdef SO_EXCLUSIVEADDRUSE - PyModule_AddIntConstant(m, "SO_EXCLUSIVEADDRUSE", SO_EXCLUSIVEADDRUSE); + PyModule_AddIntConstant(m, "SO_EXCLUSIVEADDRUSE", SO_EXCLUSIVEADDRUSE); #endif -#ifdef SO_KEEPALIVE - PyModule_AddIntConstant(m, "SO_KEEPALIVE", SO_KEEPALIVE); +#ifdef SO_KEEPALIVE + PyModule_AddIntConstant(m, "SO_KEEPALIVE", SO_KEEPALIVE); #endif -#ifdef SO_DONTROUTE - PyModule_AddIntConstant(m, "SO_DONTROUTE", SO_DONTROUTE); +#ifdef SO_DONTROUTE + PyModule_AddIntConstant(m, "SO_DONTROUTE", SO_DONTROUTE); #endif -#ifdef SO_BROADCAST - PyModule_AddIntConstant(m, "SO_BROADCAST", SO_BROADCAST); +#ifdef SO_BROADCAST + PyModule_AddIntConstant(m, "SO_BROADCAST", SO_BROADCAST); #endif -#ifdef SO_USELOOPBACK - PyModule_AddIntConstant(m, "SO_USELOOPBACK", SO_USELOOPBACK); +#ifdef SO_USELOOPBACK + PyModule_AddIntConstant(m, "SO_USELOOPBACK", SO_USELOOPBACK); #endif -#ifdef SO_LINGER - PyModule_AddIntConstant(m, "SO_LINGER", SO_LINGER); +#ifdef SO_LINGER + PyModule_AddIntConstant(m, "SO_LINGER", SO_LINGER); #endif -#ifdef SO_OOBINLINE - PyModule_AddIntConstant(m, "SO_OOBINLINE", SO_OOBINLINE); +#ifdef SO_OOBINLINE + PyModule_AddIntConstant(m, "SO_OOBINLINE", SO_OOBINLINE); #endif -#ifdef SO_REUSEPORT - PyModule_AddIntConstant(m, "SO_REUSEPORT", SO_REUSEPORT); +#ifdef SO_REUSEPORT + PyModule_AddIntConstant(m, "SO_REUSEPORT", SO_REUSEPORT); #endif -#ifdef SO_SNDBUF - PyModule_AddIntConstant(m, "SO_SNDBUF", SO_SNDBUF); +#ifdef SO_SNDBUF + PyModule_AddIntConstant(m, "SO_SNDBUF", SO_SNDBUF); #endif -#ifdef SO_RCVBUF - PyModule_AddIntConstant(m, "SO_RCVBUF", SO_RCVBUF); +#ifdef SO_RCVBUF + PyModule_AddIntConstant(m, "SO_RCVBUF", SO_RCVBUF); #endif -#ifdef SO_SNDLOWAT - PyModule_AddIntConstant(m, "SO_SNDLOWAT", SO_SNDLOWAT); +#ifdef SO_SNDLOWAT + PyModule_AddIntConstant(m, "SO_SNDLOWAT", SO_SNDLOWAT); #endif -#ifdef SO_RCVLOWAT - PyModule_AddIntConstant(m, "SO_RCVLOWAT", SO_RCVLOWAT); +#ifdef SO_RCVLOWAT + PyModule_AddIntConstant(m, "SO_RCVLOWAT", SO_RCVLOWAT); #endif -#ifdef SO_SNDTIMEO - PyModule_AddIntConstant(m, "SO_SNDTIMEO", SO_SNDTIMEO); +#ifdef SO_SNDTIMEO + PyModule_AddIntConstant(m, "SO_SNDTIMEO", SO_SNDTIMEO); #endif -#ifdef SO_RCVTIMEO - PyModule_AddIntConstant(m, "SO_RCVTIMEO", SO_RCVTIMEO); +#ifdef SO_RCVTIMEO + PyModule_AddIntConstant(m, "SO_RCVTIMEO", SO_RCVTIMEO); #endif -#ifdef SO_ERROR - PyModule_AddIntConstant(m, "SO_ERROR", SO_ERROR); +#ifdef SO_ERROR + PyModule_AddIntConstant(m, "SO_ERROR", SO_ERROR); #endif -#ifdef SO_TYPE - PyModule_AddIntConstant(m, "SO_TYPE", SO_TYPE); +#ifdef SO_TYPE + PyModule_AddIntConstant(m, "SO_TYPE", SO_TYPE); #endif - /* Maximum number of connections for "listen" */ -#ifdef SOMAXCONN - PyModule_AddIntConstant(m, "SOMAXCONN", SOMAXCONN); + /* Maximum number of connections for "listen" */ +#ifdef SOMAXCONN + PyModule_AddIntConstant(m, "SOMAXCONN", SOMAXCONN); #else - PyModule_AddIntConstant(m, "SOMAXCONN", 5); /* Common value */ + PyModule_AddIntConstant(m, "SOMAXCONN", 5); /* Common value */ #endif - /* Flags for send, recv */ -#ifdef MSG_OOB - PyModule_AddIntConstant(m, "MSG_OOB", MSG_OOB); + /* Flags for send, recv */ +#ifdef MSG_OOB + PyModule_AddIntConstant(m, "MSG_OOB", MSG_OOB); #endif -#ifdef MSG_PEEK - PyModule_AddIntConstant(m, "MSG_PEEK", MSG_PEEK); +#ifdef MSG_PEEK + PyModule_AddIntConstant(m, "MSG_PEEK", MSG_PEEK); #endif -#ifdef MSG_DONTROUTE - PyModule_AddIntConstant(m, "MSG_DONTROUTE", MSG_DONTROUTE); +#ifdef MSG_DONTROUTE + PyModule_AddIntConstant(m, "MSG_DONTROUTE", MSG_DONTROUTE); #endif -#ifdef MSG_DONTWAIT - PyModule_AddIntConstant(m, "MSG_DONTWAIT", MSG_DONTWAIT); +#ifdef MSG_DONTWAIT + PyModule_AddIntConstant(m, "MSG_DONTWAIT", MSG_DONTWAIT); #endif -#ifdef MSG_EOR - PyModule_AddIntConstant(m, "MSG_EOR", MSG_EOR); +#ifdef MSG_EOR + PyModule_AddIntConstant(m, "MSG_EOR", MSG_EOR); #endif -#ifdef MSG_TRUNC - PyModule_AddIntConstant(m, "MSG_TRUNC", MSG_TRUNC); +#ifdef MSG_TRUNC + PyModule_AddIntConstant(m, "MSG_TRUNC", MSG_TRUNC); #endif -#ifdef MSG_CTRUNC - PyModule_AddIntConstant(m, "MSG_CTRUNC", MSG_CTRUNC); +#ifdef MSG_CTRUNC + PyModule_AddIntConstant(m, "MSG_CTRUNC", MSG_CTRUNC); #endif -#ifdef MSG_WAITALL - PyModule_AddIntConstant(m, "MSG_WAITALL", MSG_WAITALL); +#ifdef MSG_WAITALL + PyModule_AddIntConstant(m, "MSG_WAITALL", MSG_WAITALL); #endif -#ifdef MSG_BTAG - PyModule_AddIntConstant(m, "MSG_BTAG", MSG_BTAG); +#ifdef MSG_BTAG + PyModule_AddIntConstant(m, "MSG_BTAG", MSG_BTAG); #endif -#ifdef MSG_ETAG - PyModule_AddIntConstant(m, "MSG_ETAG", MSG_ETAG); +#ifdef MSG_ETAG + PyModule_AddIntConstant(m, "MSG_ETAG", MSG_ETAG); #endif - /* Protocol level and numbers, usable for [gs]etsockopt */ -#ifdef SOL_SOCKET - PyModule_AddIntConstant(m, "SOL_SOCKET", SOL_SOCKET); + /* Protocol level and numbers, usable for [gs]etsockopt */ +#ifdef SOL_SOCKET + PyModule_AddIntConstant(m, "SOL_SOCKET", SOL_SOCKET); #endif -#ifdef SOL_IP - PyModule_AddIntConstant(m, "SOL_IP", SOL_IP); +#ifdef SOL_IP + PyModule_AddIntConstant(m, "SOL_IP", SOL_IP); #else - PyModule_AddIntConstant(m, "SOL_IP", 0); + PyModule_AddIntConstant(m, "SOL_IP", 0); #endif -#ifdef SOL_IPX - PyModule_AddIntConstant(m, "SOL_IPX", SOL_IPX); +#ifdef SOL_IPX + PyModule_AddIntConstant(m, "SOL_IPX", SOL_IPX); #endif -#ifdef SOL_AX25 - PyModule_AddIntConstant(m, "SOL_AX25", SOL_AX25); +#ifdef SOL_AX25 + PyModule_AddIntConstant(m, "SOL_AX25", SOL_AX25); #endif -#ifdef SOL_ATALK - PyModule_AddIntConstant(m, "SOL_ATALK", SOL_ATALK); +#ifdef SOL_ATALK + PyModule_AddIntConstant(m, "SOL_ATALK", SOL_ATALK); #endif -#ifdef SOL_NETROM - PyModule_AddIntConstant(m, "SOL_NETROM", SOL_NETROM); +#ifdef SOL_NETROM + PyModule_AddIntConstant(m, "SOL_NETROM", SOL_NETROM); #endif -#ifdef SOL_ROSE - PyModule_AddIntConstant(m, "SOL_ROSE", SOL_ROSE); +#ifdef SOL_ROSE + PyModule_AddIntConstant(m, "SOL_ROSE", SOL_ROSE); #endif -#ifdef SOL_TCP - PyModule_AddIntConstant(m, "SOL_TCP", SOL_TCP); +#ifdef SOL_TCP + PyModule_AddIntConstant(m, "SOL_TCP", SOL_TCP); #else - PyModule_AddIntConstant(m, "SOL_TCP", 6); + PyModule_AddIntConstant(m, "SOL_TCP", 6); #endif -#ifdef SOL_UDP - PyModule_AddIntConstant(m, "SOL_UDP", SOL_UDP); +#ifdef SOL_UDP + PyModule_AddIntConstant(m, "SOL_UDP", SOL_UDP); #else - PyModule_AddIntConstant(m, "SOL_UDP", 17); + PyModule_AddIntConstant(m, "SOL_UDP", 17); #endif -#ifdef IPPROTO_IP - PyModule_AddIntConstant(m, "IPPROTO_IP", IPPROTO_IP); +#ifdef IPPROTO_IP + PyModule_AddIntConstant(m, "IPPROTO_IP", IPPROTO_IP); #else - PyModule_AddIntConstant(m, "IPPROTO_IP", 0); + PyModule_AddIntConstant(m, "IPPROTO_IP", 0); #endif -#ifdef IPPROTO_HOPOPTS - PyModule_AddIntConstant(m, "IPPROTO_HOPOPTS", IPPROTO_HOPOPTS); +#ifdef IPPROTO_HOPOPTS + PyModule_AddIntConstant(m, "IPPROTO_HOPOPTS", IPPROTO_HOPOPTS); #endif -#ifdef IPPROTO_ICMP - PyModule_AddIntConstant(m, "IPPROTO_ICMP", IPPROTO_ICMP); +#ifdef IPPROTO_ICMP + PyModule_AddIntConstant(m, "IPPROTO_ICMP", IPPROTO_ICMP); #else - PyModule_AddIntConstant(m, "IPPROTO_ICMP", 1); + PyModule_AddIntConstant(m, "IPPROTO_ICMP", 1); #endif -#ifdef IPPROTO_IGMP - PyModule_AddIntConstant(m, "IPPROTO_IGMP", IPPROTO_IGMP); +#ifdef IPPROTO_IGMP + PyModule_AddIntConstant(m, "IPPROTO_IGMP", IPPROTO_IGMP); #endif -#ifdef IPPROTO_GGP - PyModule_AddIntConstant(m, "IPPROTO_GGP", IPPROTO_GGP); +#ifdef IPPROTO_GGP + PyModule_AddIntConstant(m, "IPPROTO_GGP", IPPROTO_GGP); #endif -#ifdef IPPROTO_IPV4 - PyModule_AddIntConstant(m, "IPPROTO_IPV4", IPPROTO_IPV4); +#ifdef IPPROTO_IPV4 + PyModule_AddIntConstant(m, "IPPROTO_IPV4", IPPROTO_IPV4); #endif -#ifdef IPPROTO_IPV6 - PyModule_AddIntConstant(m, "IPPROTO_IPV6", IPPROTO_IPV6); +#ifdef IPPROTO_IPV6 + PyModule_AddIntConstant(m, "IPPROTO_IPV6", IPPROTO_IPV6); #endif -#ifdef IPPROTO_IPIP - PyModule_AddIntConstant(m, "IPPROTO_IPIP", IPPROTO_IPIP); +#ifdef IPPROTO_IPIP + PyModule_AddIntConstant(m, "IPPROTO_IPIP", IPPROTO_IPIP); #endif -#ifdef IPPROTO_TCP - PyModule_AddIntConstant(m, "IPPROTO_TCP", IPPROTO_TCP); +#ifdef IPPROTO_TCP + PyModule_AddIntConstant(m, "IPPROTO_TCP", IPPROTO_TCP); #else - PyModule_AddIntConstant(m, "IPPROTO_TCP", 6); + PyModule_AddIntConstant(m, "IPPROTO_TCP", 6); #endif -#ifdef IPPROTO_EGP - PyModule_AddIntConstant(m, "IPPROTO_EGP", IPPROTO_EGP); +#ifdef IPPROTO_EGP + PyModule_AddIntConstant(m, "IPPROTO_EGP", IPPROTO_EGP); #endif -#ifdef IPPROTO_PUP - PyModule_AddIntConstant(m, "IPPROTO_PUP", IPPROTO_PUP); +#ifdef IPPROTO_PUP + PyModule_AddIntConstant(m, "IPPROTO_PUP", IPPROTO_PUP); #endif -#ifdef IPPROTO_UDP - PyModule_AddIntConstant(m, "IPPROTO_UDP", IPPROTO_UDP); +#ifdef IPPROTO_UDP + PyModule_AddIntConstant(m, "IPPROTO_UDP", IPPROTO_UDP); #else - PyModule_AddIntConstant(m, "IPPROTO_UDP", 17); + PyModule_AddIntConstant(m, "IPPROTO_UDP", 17); #endif -#ifdef IPPROTO_IDP - PyModule_AddIntConstant(m, "IPPROTO_IDP", IPPROTO_IDP); +#ifdef IPPROTO_IDP + PyModule_AddIntConstant(m, "IPPROTO_IDP", IPPROTO_IDP); #endif -#ifdef IPPROTO_HELLO - PyModule_AddIntConstant(m, "IPPROTO_HELLO", IPPROTO_HELLO); +#ifdef IPPROTO_HELLO + PyModule_AddIntConstant(m, "IPPROTO_HELLO", IPPROTO_HELLO); #endif -#ifdef IPPROTO_ND - PyModule_AddIntConstant(m, "IPPROTO_ND", IPPROTO_ND); +#ifdef IPPROTO_ND + PyModule_AddIntConstant(m, "IPPROTO_ND", IPPROTO_ND); #endif -#ifdef IPPROTO_TP - PyModule_AddIntConstant(m, "IPPROTO_TP", IPPROTO_TP); +#ifdef IPPROTO_TP + PyModule_AddIntConstant(m, "IPPROTO_TP", IPPROTO_TP); #endif -#ifdef IPPROTO_IPV6 - PyModule_AddIntConstant(m, "IPPROTO_IPV6", IPPROTO_IPV6); +#ifdef IPPROTO_IPV6 + PyModule_AddIntConstant(m, "IPPROTO_IPV6", IPPROTO_IPV6); #endif -#ifdef IPPROTO_ROUTING - PyModule_AddIntConstant(m, "IPPROTO_ROUTING", IPPROTO_ROUTING); +#ifdef IPPROTO_ROUTING + PyModule_AddIntConstant(m, "IPPROTO_ROUTING", IPPROTO_ROUTING); #endif -#ifdef IPPROTO_FRAGMENT - PyModule_AddIntConstant(m, "IPPROTO_FRAGMENT", IPPROTO_FRAGMENT); +#ifdef IPPROTO_FRAGMENT + PyModule_AddIntConstant(m, "IPPROTO_FRAGMENT", IPPROTO_FRAGMENT); #endif -#ifdef IPPROTO_RSVP - PyModule_AddIntConstant(m, "IPPROTO_RSVP", IPPROTO_RSVP); +#ifdef IPPROTO_RSVP + PyModule_AddIntConstant(m, "IPPROTO_RSVP", IPPROTO_RSVP); #endif -#ifdef IPPROTO_GRE - PyModule_AddIntConstant(m, "IPPROTO_GRE", IPPROTO_GRE); +#ifdef IPPROTO_GRE + PyModule_AddIntConstant(m, "IPPROTO_GRE", IPPROTO_GRE); #endif -#ifdef IPPROTO_ESP - PyModule_AddIntConstant(m, "IPPROTO_ESP", IPPROTO_ESP); +#ifdef IPPROTO_ESP + PyModule_AddIntConstant(m, "IPPROTO_ESP", IPPROTO_ESP); #endif -#ifdef IPPROTO_AH - PyModule_AddIntConstant(m, "IPPROTO_AH", IPPROTO_AH); +#ifdef IPPROTO_AH + PyModule_AddIntConstant(m, "IPPROTO_AH", IPPROTO_AH); #endif -#ifdef IPPROTO_MOBILE - PyModule_AddIntConstant(m, "IPPROTO_MOBILE", IPPROTO_MOBILE); +#ifdef IPPROTO_MOBILE + PyModule_AddIntConstant(m, "IPPROTO_MOBILE", IPPROTO_MOBILE); #endif -#ifdef IPPROTO_ICMPV6 - PyModule_AddIntConstant(m, "IPPROTO_ICMPV6", IPPROTO_ICMPV6); +#ifdef IPPROTO_ICMPV6 + PyModule_AddIntConstant(m, "IPPROTO_ICMPV6", IPPROTO_ICMPV6); #endif -#ifdef IPPROTO_NONE - PyModule_AddIntConstant(m, "IPPROTO_NONE", IPPROTO_NONE); +#ifdef IPPROTO_NONE + PyModule_AddIntConstant(m, "IPPROTO_NONE", IPPROTO_NONE); #endif -#ifdef IPPROTO_DSTOPTS - PyModule_AddIntConstant(m, "IPPROTO_DSTOPTS", IPPROTO_DSTOPTS); +#ifdef IPPROTO_DSTOPTS + PyModule_AddIntConstant(m, "IPPROTO_DSTOPTS", IPPROTO_DSTOPTS); #endif -#ifdef IPPROTO_XTP - PyModule_AddIntConstant(m, "IPPROTO_XTP", IPPROTO_XTP); +#ifdef IPPROTO_XTP + PyModule_AddIntConstant(m, "IPPROTO_XTP", IPPROTO_XTP); #endif -#ifdef IPPROTO_EON - PyModule_AddIntConstant(m, "IPPROTO_EON", IPPROTO_EON); +#ifdef IPPROTO_EON + PyModule_AddIntConstant(m, "IPPROTO_EON", IPPROTO_EON); #endif -#ifdef IPPROTO_PIM - PyModule_AddIntConstant(m, "IPPROTO_PIM", IPPROTO_PIM); +#ifdef IPPROTO_PIM + PyModule_AddIntConstant(m, "IPPROTO_PIM", IPPROTO_PIM); #endif -#ifdef IPPROTO_IPCOMP - PyModule_AddIntConstant(m, "IPPROTO_IPCOMP", IPPROTO_IPCOMP); +#ifdef IPPROTO_IPCOMP + PyModule_AddIntConstant(m, "IPPROTO_IPCOMP", IPPROTO_IPCOMP); #endif -#ifdef IPPROTO_VRRP - PyModule_AddIntConstant(m, "IPPROTO_VRRP", IPPROTO_VRRP); +#ifdef IPPROTO_VRRP + PyModule_AddIntConstant(m, "IPPROTO_VRRP", IPPROTO_VRRP); #endif -#ifdef IPPROTO_BIP - PyModule_AddIntConstant(m, "IPPROTO_BIP", IPPROTO_BIP); +#ifdef IPPROTO_BIP + PyModule_AddIntConstant(m, "IPPROTO_BIP", IPPROTO_BIP); #endif /**/ -#ifdef IPPROTO_RAW - PyModule_AddIntConstant(m, "IPPROTO_RAW", IPPROTO_RAW); +#ifdef IPPROTO_RAW + PyModule_AddIntConstant(m, "IPPROTO_RAW", IPPROTO_RAW); #else - PyModule_AddIntConstant(m, "IPPROTO_RAW", 255); + PyModule_AddIntConstant(m, "IPPROTO_RAW", 255); #endif -#ifdef IPPROTO_MAX - PyModule_AddIntConstant(m, "IPPROTO_MAX", IPPROTO_MAX); +#ifdef IPPROTO_MAX + PyModule_AddIntConstant(m, "IPPROTO_MAX", IPPROTO_MAX); #endif - /* Some port configuration */ -#ifdef IPPORT_RESERVED - PyModule_AddIntConstant(m, "IPPORT_RESERVED", IPPORT_RESERVED); + /* Some port configuration */ +#ifdef IPPORT_RESERVED + PyModule_AddIntConstant(m, "IPPORT_RESERVED", IPPORT_RESERVED); #else - PyModule_AddIntConstant(m, "IPPORT_RESERVED", 1024); + PyModule_AddIntConstant(m, "IPPORT_RESERVED", 1024); #endif -#ifdef IPPORT_USERRESERVED - PyModule_AddIntConstant(m, "IPPORT_USERRESERVED", IPPORT_USERRESERVED); +#ifdef IPPORT_USERRESERVED + PyModule_AddIntConstant(m, "IPPORT_USERRESERVED", IPPORT_USERRESERVED); #else - PyModule_AddIntConstant(m, "IPPORT_USERRESERVED", 5000); + PyModule_AddIntConstant(m, "IPPORT_USERRESERVED", 5000); #endif - /* Some reserved IP v.4 addresses */ -#ifdef INADDR_ANY - PyModule_AddIntConstant(m, "INADDR_ANY", INADDR_ANY); + /* Some reserved IP v.4 addresses */ +#ifdef INADDR_ANY + PyModule_AddIntConstant(m, "INADDR_ANY", INADDR_ANY); #else - PyModule_AddIntConstant(m, "INADDR_ANY", 0x00000000); + PyModule_AddIntConstant(m, "INADDR_ANY", 0x00000000); #endif -#ifdef INADDR_BROADCAST - PyModule_AddIntConstant(m, "INADDR_BROADCAST", INADDR_BROADCAST); +#ifdef INADDR_BROADCAST + PyModule_AddIntConstant(m, "INADDR_BROADCAST", INADDR_BROADCAST); #else - PyModule_AddIntConstant(m, "INADDR_BROADCAST", 0xffffffff); + PyModule_AddIntConstant(m, "INADDR_BROADCAST", 0xffffffff); #endif -#ifdef INADDR_LOOPBACK - PyModule_AddIntConstant(m, "INADDR_LOOPBACK", INADDR_LOOPBACK); +#ifdef INADDR_LOOPBACK + PyModule_AddIntConstant(m, "INADDR_LOOPBACK", INADDR_LOOPBACK); #else - PyModule_AddIntConstant(m, "INADDR_LOOPBACK", 0x7F000001); + PyModule_AddIntConstant(m, "INADDR_LOOPBACK", 0x7F000001); #endif -#ifdef INADDR_UNSPEC_GROUP - PyModule_AddIntConstant(m, "INADDR_UNSPEC_GROUP", INADDR_UNSPEC_GROUP); +#ifdef INADDR_UNSPEC_GROUP + PyModule_AddIntConstant(m, "INADDR_UNSPEC_GROUP", INADDR_UNSPEC_GROUP); #else - PyModule_AddIntConstant(m, "INADDR_UNSPEC_GROUP", 0xe0000000); + PyModule_AddIntConstant(m, "INADDR_UNSPEC_GROUP", 0xe0000000); #endif -#ifdef INADDR_ALLHOSTS_GROUP - PyModule_AddIntConstant(m, "INADDR_ALLHOSTS_GROUP", - INADDR_ALLHOSTS_GROUP); +#ifdef INADDR_ALLHOSTS_GROUP + PyModule_AddIntConstant(m, "INADDR_ALLHOSTS_GROUP", + INADDR_ALLHOSTS_GROUP); #else - PyModule_AddIntConstant(m, "INADDR_ALLHOSTS_GROUP", 0xe0000001); + PyModule_AddIntConstant(m, "INADDR_ALLHOSTS_GROUP", 0xe0000001); #endif -#ifdef INADDR_MAX_LOCAL_GROUP - PyModule_AddIntConstant(m, "INADDR_MAX_LOCAL_GROUP", - INADDR_MAX_LOCAL_GROUP); +#ifdef INADDR_MAX_LOCAL_GROUP + PyModule_AddIntConstant(m, "INADDR_MAX_LOCAL_GROUP", + INADDR_MAX_LOCAL_GROUP); #else - PyModule_AddIntConstant(m, "INADDR_MAX_LOCAL_GROUP", 0xe00000ff); + PyModule_AddIntConstant(m, "INADDR_MAX_LOCAL_GROUP", 0xe00000ff); #endif -#ifdef INADDR_NONE - PyModule_AddIntConstant(m, "INADDR_NONE", INADDR_NONE); +#ifdef INADDR_NONE + PyModule_AddIntConstant(m, "INADDR_NONE", INADDR_NONE); #else - PyModule_AddIntConstant(m, "INADDR_NONE", 0xffffffff); + PyModule_AddIntConstant(m, "INADDR_NONE", 0xffffffff); #endif - /* IPv4 [gs]etsockopt options */ -#ifdef IP_OPTIONS - PyModule_AddIntConstant(m, "IP_OPTIONS", IP_OPTIONS); + /* IPv4 [gs]etsockopt options */ +#ifdef IP_OPTIONS + PyModule_AddIntConstant(m, "IP_OPTIONS", IP_OPTIONS); #endif -#ifdef IP_HDRINCL - PyModule_AddIntConstant(m, "IP_HDRINCL", IP_HDRINCL); +#ifdef IP_HDRINCL + PyModule_AddIntConstant(m, "IP_HDRINCL", IP_HDRINCL); #endif -#ifdef IP_TOS - PyModule_AddIntConstant(m, "IP_TOS", IP_TOS); +#ifdef IP_TOS + PyModule_AddIntConstant(m, "IP_TOS", IP_TOS); #endif -#ifdef IP_TTL - PyModule_AddIntConstant(m, "IP_TTL", IP_TTL); +#ifdef IP_TTL + PyModule_AddIntConstant(m, "IP_TTL", IP_TTL); #endif -#ifdef IP_RECVOPTS - PyModule_AddIntConstant(m, "IP_RECVOPTS", IP_RECVOPTS); +#ifdef IP_RECVOPTS + PyModule_AddIntConstant(m, "IP_RECVOPTS", IP_RECVOPTS); #endif -#ifdef IP_RECVRETOPTS - PyModule_AddIntConstant(m, "IP_RECVRETOPTS", IP_RECVRETOPTS); +#ifdef IP_RECVRETOPTS + PyModule_AddIntConstant(m, "IP_RECVRETOPTS", IP_RECVRETOPTS); #endif -#ifdef IP_RECVDSTADDR - PyModule_AddIntConstant(m, "IP_RECVDSTADDR", IP_RECVDSTADDR); +#ifdef IP_RECVDSTADDR + PyModule_AddIntConstant(m, "IP_RECVDSTADDR", IP_RECVDSTADDR); #endif -#ifdef IP_RETOPTS - PyModule_AddIntConstant(m, "IP_RETOPTS", IP_RETOPTS); +#ifdef IP_RETOPTS + PyModule_AddIntConstant(m, "IP_RETOPTS", IP_RETOPTS); #endif -#ifdef IP_MULTICAST_IF - PyModule_AddIntConstant(m, "IP_MULTICAST_IF", IP_MULTICAST_IF); +#ifdef IP_MULTICAST_IF + PyModule_AddIntConstant(m, "IP_MULTICAST_IF", IP_MULTICAST_IF); #endif -#ifdef IP_MULTICAST_TTL - PyModule_AddIntConstant(m, "IP_MULTICAST_TTL", IP_MULTICAST_TTL); +#ifdef IP_MULTICAST_TTL + PyModule_AddIntConstant(m, "IP_MULTICAST_TTL", IP_MULTICAST_TTL); #endif -#ifdef IP_MULTICAST_LOOP - PyModule_AddIntConstant(m, "IP_MULTICAST_LOOP", IP_MULTICAST_LOOP); +#ifdef IP_MULTICAST_LOOP + PyModule_AddIntConstant(m, "IP_MULTICAST_LOOP", IP_MULTICAST_LOOP); #endif -#ifdef IP_ADD_MEMBERSHIP - PyModule_AddIntConstant(m, "IP_ADD_MEMBERSHIP", IP_ADD_MEMBERSHIP); +#ifdef IP_ADD_MEMBERSHIP + PyModule_AddIntConstant(m, "IP_ADD_MEMBERSHIP", IP_ADD_MEMBERSHIP); #endif -#ifdef IP_DROP_MEMBERSHIP - PyModule_AddIntConstant(m, "IP_DROP_MEMBERSHIP", IP_DROP_MEMBERSHIP); +#ifdef IP_DROP_MEMBERSHIP + PyModule_AddIntConstant(m, "IP_DROP_MEMBERSHIP", IP_DROP_MEMBERSHIP); #endif -#ifdef IP_DEFAULT_MULTICAST_TTL - PyModule_AddIntConstant(m, "IP_DEFAULT_MULTICAST_TTL", - IP_DEFAULT_MULTICAST_TTL); +#ifdef IP_DEFAULT_MULTICAST_TTL + PyModule_AddIntConstant(m, "IP_DEFAULT_MULTICAST_TTL", + IP_DEFAULT_MULTICAST_TTL); #endif -#ifdef IP_DEFAULT_MULTICAST_LOOP - PyModule_AddIntConstant(m, "IP_DEFAULT_MULTICAST_LOOP", - IP_DEFAULT_MULTICAST_LOOP); +#ifdef IP_DEFAULT_MULTICAST_LOOP + PyModule_AddIntConstant(m, "IP_DEFAULT_MULTICAST_LOOP", + IP_DEFAULT_MULTICAST_LOOP); #endif -#ifdef IP_MAX_MEMBERSHIPS - PyModule_AddIntConstant(m, "IP_MAX_MEMBERSHIPS", IP_MAX_MEMBERSHIPS); +#ifdef IP_MAX_MEMBERSHIPS + PyModule_AddIntConstant(m, "IP_MAX_MEMBERSHIPS", IP_MAX_MEMBERSHIPS); #endif - /* IPv6 [gs]etsockopt options, defined in RFC2553 */ -#ifdef IPV6_JOIN_GROUP - PyModule_AddIntConstant(m, "IPV6_JOIN_GROUP", IPV6_JOIN_GROUP); + /* IPv6 [gs]etsockopt options, defined in RFC2553 */ +#ifdef IPV6_JOIN_GROUP + PyModule_AddIntConstant(m, "IPV6_JOIN_GROUP", IPV6_JOIN_GROUP); #endif -#ifdef IPV6_LEAVE_GROUP - PyModule_AddIntConstant(m, "IPV6_LEAVE_GROUP", IPV6_LEAVE_GROUP); +#ifdef IPV6_LEAVE_GROUP + PyModule_AddIntConstant(m, "IPV6_LEAVE_GROUP", IPV6_LEAVE_GROUP); #endif -#ifdef IPV6_MULTICAST_HOPS - PyModule_AddIntConstant(m, "IPV6_MULTICAST_HOPS", IPV6_MULTICAST_HOPS); +#ifdef IPV6_MULTICAST_HOPS + PyModule_AddIntConstant(m, "IPV6_MULTICAST_HOPS", IPV6_MULTICAST_HOPS); #endif -#ifdef IPV6_MULTICAST_IF - PyModule_AddIntConstant(m, "IPV6_MULTICAST_IF", IPV6_MULTICAST_IF); +#ifdef IPV6_MULTICAST_IF + PyModule_AddIntConstant(m, "IPV6_MULTICAST_IF", IPV6_MULTICAST_IF); #endif -#ifdef IPV6_MULTICAST_LOOP - PyModule_AddIntConstant(m, "IPV6_MULTICAST_LOOP", IPV6_MULTICAST_LOOP); +#ifdef IPV6_MULTICAST_LOOP + PyModule_AddIntConstant(m, "IPV6_MULTICAST_LOOP", IPV6_MULTICAST_LOOP); #endif -#ifdef IPV6_UNICAST_HOPS - PyModule_AddIntConstant(m, "IPV6_UNICAST_HOPS", IPV6_UNICAST_HOPS); +#ifdef IPV6_UNICAST_HOPS + PyModule_AddIntConstant(m, "IPV6_UNICAST_HOPS", IPV6_UNICAST_HOPS); #endif - /* Additional IPV6 socket options, defined in RFC 3493 */ + /* Additional IPV6 socket options, defined in RFC 3493 */ #ifdef IPV6_V6ONLY - PyModule_AddIntConstant(m, "IPV6_V6ONLY", IPV6_V6ONLY); + PyModule_AddIntConstant(m, "IPV6_V6ONLY", IPV6_V6ONLY); #endif - /* Advanced IPV6 socket options, from RFC 3542 */ + /* Advanced IPV6 socket options, from RFC 3542 */ #ifdef IPV6_CHECKSUM - PyModule_AddIntConstant(m, "IPV6_CHECKSUM", IPV6_CHECKSUM); + PyModule_AddIntConstant(m, "IPV6_CHECKSUM", IPV6_CHECKSUM); #endif #ifdef IPV6_DONTFRAG - PyModule_AddIntConstant(m, "IPV6_DONTFRAG", IPV6_DONTFRAG); + PyModule_AddIntConstant(m, "IPV6_DONTFRAG", IPV6_DONTFRAG); #endif #ifdef IPV6_DSTOPTS - PyModule_AddIntConstant(m, "IPV6_DSTOPTS", IPV6_DSTOPTS); + PyModule_AddIntConstant(m, "IPV6_DSTOPTS", IPV6_DSTOPTS); #endif #ifdef IPV6_HOPLIMIT - PyModule_AddIntConstant(m, "IPV6_HOPLIMIT", IPV6_HOPLIMIT); + PyModule_AddIntConstant(m, "IPV6_HOPLIMIT", IPV6_HOPLIMIT); #endif #ifdef IPV6_HOPOPTS - PyModule_AddIntConstant(m, "IPV6_HOPOPTS", IPV6_HOPOPTS); + PyModule_AddIntConstant(m, "IPV6_HOPOPTS", IPV6_HOPOPTS); #endif #ifdef IPV6_NEXTHOP - PyModule_AddIntConstant(m, "IPV6_NEXTHOP", IPV6_NEXTHOP); + PyModule_AddIntConstant(m, "IPV6_NEXTHOP", IPV6_NEXTHOP); #endif #ifdef IPV6_PATHMTU - PyModule_AddIntConstant(m, "IPV6_PATHMTU", IPV6_PATHMTU); + PyModule_AddIntConstant(m, "IPV6_PATHMTU", IPV6_PATHMTU); #endif #ifdef IPV6_PKTINFO - PyModule_AddIntConstant(m, "IPV6_PKTINFO", IPV6_PKTINFO); + PyModule_AddIntConstant(m, "IPV6_PKTINFO", IPV6_PKTINFO); #endif #ifdef IPV6_RECVDSTOPTS - PyModule_AddIntConstant(m, "IPV6_RECVDSTOPTS", IPV6_RECVDSTOPTS); + PyModule_AddIntConstant(m, "IPV6_RECVDSTOPTS", IPV6_RECVDSTOPTS); #endif #ifdef IPV6_RECVHOPLIMIT - PyModule_AddIntConstant(m, "IPV6_RECVHOPLIMIT", IPV6_RECVHOPLIMIT); + PyModule_AddIntConstant(m, "IPV6_RECVHOPLIMIT", IPV6_RECVHOPLIMIT); #endif #ifdef IPV6_RECVHOPOPTS - PyModule_AddIntConstant(m, "IPV6_RECVHOPOPTS", IPV6_RECVHOPOPTS); + PyModule_AddIntConstant(m, "IPV6_RECVHOPOPTS", IPV6_RECVHOPOPTS); #endif #ifdef IPV6_RECVPKTINFO - PyModule_AddIntConstant(m, "IPV6_RECVPKTINFO", IPV6_RECVPKTINFO); + PyModule_AddIntConstant(m, "IPV6_RECVPKTINFO", IPV6_RECVPKTINFO); #endif #ifdef IPV6_RECVRTHDR - PyModule_AddIntConstant(m, "IPV6_RECVRTHDR", IPV6_RECVRTHDR); + PyModule_AddIntConstant(m, "IPV6_RECVRTHDR", IPV6_RECVRTHDR); #endif #ifdef IPV6_RECVTCLASS - PyModule_AddIntConstant(m, "IPV6_RECVTCLASS", IPV6_RECVTCLASS); + PyModule_AddIntConstant(m, "IPV6_RECVTCLASS", IPV6_RECVTCLASS); #endif #ifdef IPV6_RTHDR - PyModule_AddIntConstant(m, "IPV6_RTHDR", IPV6_RTHDR); + PyModule_AddIntConstant(m, "IPV6_RTHDR", IPV6_RTHDR); #endif #ifdef IPV6_RTHDRDSTOPTS - PyModule_AddIntConstant(m, "IPV6_RTHDRDSTOPTS", IPV6_RTHDRDSTOPTS); + PyModule_AddIntConstant(m, "IPV6_RTHDRDSTOPTS", IPV6_RTHDRDSTOPTS); #endif #ifdef IPV6_RTHDR_TYPE_0 - PyModule_AddIntConstant(m, "IPV6_RTHDR_TYPE_0", IPV6_RTHDR_TYPE_0); + PyModule_AddIntConstant(m, "IPV6_RTHDR_TYPE_0", IPV6_RTHDR_TYPE_0); #endif #ifdef IPV6_RECVPATHMTU - PyModule_AddIntConstant(m, "IPV6_RECVPATHMTU", IPV6_RECVPATHMTU); + PyModule_AddIntConstant(m, "IPV6_RECVPATHMTU", IPV6_RECVPATHMTU); #endif #ifdef IPV6_TCLASS - PyModule_AddIntConstant(m, "IPV6_TCLASS", IPV6_TCLASS); + PyModule_AddIntConstant(m, "IPV6_TCLASS", IPV6_TCLASS); #endif #ifdef IPV6_USE_MIN_MTU - PyModule_AddIntConstant(m, "IPV6_USE_MIN_MTU", IPV6_USE_MIN_MTU); + PyModule_AddIntConstant(m, "IPV6_USE_MIN_MTU", IPV6_USE_MIN_MTU); #endif - /* TCP options */ -#ifdef TCP_NODELAY - PyModule_AddIntConstant(m, "TCP_NODELAY", TCP_NODELAY); + /* TCP options */ +#ifdef TCP_NODELAY + PyModule_AddIntConstant(m, "TCP_NODELAY", TCP_NODELAY); #endif -#ifdef TCP_MAXSEG - PyModule_AddIntConstant(m, "TCP_MAXSEG", TCP_MAXSEG); +#ifdef TCP_MAXSEG + PyModule_AddIntConstant(m, "TCP_MAXSEG", TCP_MAXSEG); #endif -#ifdef TCP_CORK - PyModule_AddIntConstant(m, "TCP_CORK", TCP_CORK); +#ifdef TCP_CORK + PyModule_AddIntConstant(m, "TCP_CORK", TCP_CORK); #endif -#ifdef TCP_KEEPIDLE - PyModule_AddIntConstant(m, "TCP_KEEPIDLE", TCP_KEEPIDLE); +#ifdef TCP_KEEPIDLE + PyModule_AddIntConstant(m, "TCP_KEEPIDLE", TCP_KEEPIDLE); #endif -#ifdef TCP_KEEPINTVL - PyModule_AddIntConstant(m, "TCP_KEEPINTVL", TCP_KEEPINTVL); +#ifdef TCP_KEEPINTVL + PyModule_AddIntConstant(m, "TCP_KEEPINTVL", TCP_KEEPINTVL); #endif -#ifdef TCP_KEEPCNT - PyModule_AddIntConstant(m, "TCP_KEEPCNT", TCP_KEEPCNT); +#ifdef TCP_KEEPCNT + PyModule_AddIntConstant(m, "TCP_KEEPCNT", TCP_KEEPCNT); #endif -#ifdef TCP_SYNCNT - PyModule_AddIntConstant(m, "TCP_SYNCNT", TCP_SYNCNT); +#ifdef TCP_SYNCNT + PyModule_AddIntConstant(m, "TCP_SYNCNT", TCP_SYNCNT); #endif -#ifdef TCP_LINGER2 - PyModule_AddIntConstant(m, "TCP_LINGER2", TCP_LINGER2); +#ifdef TCP_LINGER2 + PyModule_AddIntConstant(m, "TCP_LINGER2", TCP_LINGER2); #endif -#ifdef TCP_DEFER_ACCEPT - PyModule_AddIntConstant(m, "TCP_DEFER_ACCEPT", TCP_DEFER_ACCEPT); +#ifdef TCP_DEFER_ACCEPT + PyModule_AddIntConstant(m, "TCP_DEFER_ACCEPT", TCP_DEFER_ACCEPT); #endif -#ifdef TCP_WINDOW_CLAMP - PyModule_AddIntConstant(m, "TCP_WINDOW_CLAMP", TCP_WINDOW_CLAMP); +#ifdef TCP_WINDOW_CLAMP + PyModule_AddIntConstant(m, "TCP_WINDOW_CLAMP", TCP_WINDOW_CLAMP); #endif -#ifdef TCP_INFO - PyModule_AddIntConstant(m, "TCP_INFO", TCP_INFO); +#ifdef TCP_INFO + PyModule_AddIntConstant(m, "TCP_INFO", TCP_INFO); #endif -#ifdef TCP_QUICKACK - PyModule_AddIntConstant(m, "TCP_QUICKACK", TCP_QUICKACK); +#ifdef TCP_QUICKACK + PyModule_AddIntConstant(m, "TCP_QUICKACK", TCP_QUICKACK); #endif - /* IPX options */ -#ifdef IPX_TYPE - PyModule_AddIntConstant(m, "IPX_TYPE", IPX_TYPE); + /* IPX options */ +#ifdef IPX_TYPE + PyModule_AddIntConstant(m, "IPX_TYPE", IPX_TYPE); #endif - /* get{addr,name}info parameters */ + /* get{addr,name}info parameters */ #ifdef EAI_ADDRFAMILY - PyModule_AddIntConstant(m, "EAI_ADDRFAMILY", EAI_ADDRFAMILY); + PyModule_AddIntConstant(m, "EAI_ADDRFAMILY", EAI_ADDRFAMILY); #endif #ifdef EAI_AGAIN - PyModule_AddIntConstant(m, "EAI_AGAIN", EAI_AGAIN); + PyModule_AddIntConstant(m, "EAI_AGAIN", EAI_AGAIN); #endif #ifdef EAI_BADFLAGS - PyModule_AddIntConstant(m, "EAI_BADFLAGS", EAI_BADFLAGS); + PyModule_AddIntConstant(m, "EAI_BADFLAGS", EAI_BADFLAGS); #endif #ifdef EAI_FAIL - PyModule_AddIntConstant(m, "EAI_FAIL", EAI_FAIL); + PyModule_AddIntConstant(m, "EAI_FAIL", EAI_FAIL); #endif #ifdef EAI_FAMILY - PyModule_AddIntConstant(m, "EAI_FAMILY", EAI_FAMILY); + PyModule_AddIntConstant(m, "EAI_FAMILY", EAI_FAMILY); #endif #ifdef EAI_MEMORY - PyModule_AddIntConstant(m, "EAI_MEMORY", EAI_MEMORY); + PyModule_AddIntConstant(m, "EAI_MEMORY", EAI_MEMORY); #endif #ifdef EAI_NODATA - PyModule_AddIntConstant(m, "EAI_NODATA", EAI_NODATA); + PyModule_AddIntConstant(m, "EAI_NODATA", EAI_NODATA); #endif #ifdef EAI_NONAME - PyModule_AddIntConstant(m, "EAI_NONAME", EAI_NONAME); + PyModule_AddIntConstant(m, "EAI_NONAME", EAI_NONAME); #endif #ifdef EAI_OVERFLOW - PyModule_AddIntConstant(m, "EAI_OVERFLOW", EAI_OVERFLOW); + PyModule_AddIntConstant(m, "EAI_OVERFLOW", EAI_OVERFLOW); #endif #ifdef EAI_SERVICE - PyModule_AddIntConstant(m, "EAI_SERVICE", EAI_SERVICE); + PyModule_AddIntConstant(m, "EAI_SERVICE", EAI_SERVICE); #endif #ifdef EAI_SOCKTYPE - PyModule_AddIntConstant(m, "EAI_SOCKTYPE", EAI_SOCKTYPE); + PyModule_AddIntConstant(m, "EAI_SOCKTYPE", EAI_SOCKTYPE); #endif #ifdef EAI_SYSTEM - PyModule_AddIntConstant(m, "EAI_SYSTEM", EAI_SYSTEM); + PyModule_AddIntConstant(m, "EAI_SYSTEM", EAI_SYSTEM); #endif #ifdef EAI_BADHINTS - PyModule_AddIntConstant(m, "EAI_BADHINTS", EAI_BADHINTS); + PyModule_AddIntConstant(m, "EAI_BADHINTS", EAI_BADHINTS); #endif #ifdef EAI_PROTOCOL - PyModule_AddIntConstant(m, "EAI_PROTOCOL", EAI_PROTOCOL); + PyModule_AddIntConstant(m, "EAI_PROTOCOL", EAI_PROTOCOL); #endif #ifdef EAI_MAX - PyModule_AddIntConstant(m, "EAI_MAX", EAI_MAX); + PyModule_AddIntConstant(m, "EAI_MAX", EAI_MAX); #endif #ifdef AI_PASSIVE - PyModule_AddIntConstant(m, "AI_PASSIVE", AI_PASSIVE); + PyModule_AddIntConstant(m, "AI_PASSIVE", AI_PASSIVE); #endif #ifdef AI_CANONNAME - PyModule_AddIntConstant(m, "AI_CANONNAME", AI_CANONNAME); + PyModule_AddIntConstant(m, "AI_CANONNAME", AI_CANONNAME); #endif #ifdef AI_NUMERICHOST - PyModule_AddIntConstant(m, "AI_NUMERICHOST", AI_NUMERICHOST); + PyModule_AddIntConstant(m, "AI_NUMERICHOST", AI_NUMERICHOST); #endif #ifdef AI_NUMERICSERV - PyModule_AddIntConstant(m, "AI_NUMERICSERV", AI_NUMERICSERV); + PyModule_AddIntConstant(m, "AI_NUMERICSERV", AI_NUMERICSERV); #endif #ifdef AI_MASK - PyModule_AddIntConstant(m, "AI_MASK", AI_MASK); + PyModule_AddIntConstant(m, "AI_MASK", AI_MASK); #endif #ifdef AI_ALL - PyModule_AddIntConstant(m, "AI_ALL", AI_ALL); + PyModule_AddIntConstant(m, "AI_ALL", AI_ALL); #endif #ifdef AI_V4MAPPED_CFG - PyModule_AddIntConstant(m, "AI_V4MAPPED_CFG", AI_V4MAPPED_CFG); + PyModule_AddIntConstant(m, "AI_V4MAPPED_CFG", AI_V4MAPPED_CFG); #endif #ifdef AI_ADDRCONFIG - PyModule_AddIntConstant(m, "AI_ADDRCONFIG", AI_ADDRCONFIG); + PyModule_AddIntConstant(m, "AI_ADDRCONFIG", AI_ADDRCONFIG); #endif #ifdef AI_V4MAPPED - PyModule_AddIntConstant(m, "AI_V4MAPPED", AI_V4MAPPED); + PyModule_AddIntConstant(m, "AI_V4MAPPED", AI_V4MAPPED); #endif #ifdef AI_DEFAULT - PyModule_AddIntConstant(m, "AI_DEFAULT", AI_DEFAULT); + PyModule_AddIntConstant(m, "AI_DEFAULT", AI_DEFAULT); #endif #ifdef NI_MAXHOST - PyModule_AddIntConstant(m, "NI_MAXHOST", NI_MAXHOST); + PyModule_AddIntConstant(m, "NI_MAXHOST", NI_MAXHOST); #endif #ifdef NI_MAXSERV - PyModule_AddIntConstant(m, "NI_MAXSERV", NI_MAXSERV); + PyModule_AddIntConstant(m, "NI_MAXSERV", NI_MAXSERV); #endif #ifdef NI_NOFQDN - PyModule_AddIntConstant(m, "NI_NOFQDN", NI_NOFQDN); + PyModule_AddIntConstant(m, "NI_NOFQDN", NI_NOFQDN); #endif #ifdef NI_NUMERICHOST - PyModule_AddIntConstant(m, "NI_NUMERICHOST", NI_NUMERICHOST); + PyModule_AddIntConstant(m, "NI_NUMERICHOST", NI_NUMERICHOST); #endif #ifdef NI_NAMEREQD - PyModule_AddIntConstant(m, "NI_NAMEREQD", NI_NAMEREQD); + PyModule_AddIntConstant(m, "NI_NAMEREQD", NI_NAMEREQD); #endif #ifdef NI_NUMERICSERV - PyModule_AddIntConstant(m, "NI_NUMERICSERV", NI_NUMERICSERV); + PyModule_AddIntConstant(m, "NI_NUMERICSERV", NI_NUMERICSERV); #endif #ifdef NI_DGRAM - PyModule_AddIntConstant(m, "NI_DGRAM", NI_DGRAM); + PyModule_AddIntConstant(m, "NI_DGRAM", NI_DGRAM); #endif - /* shutdown() parameters */ + /* shutdown() parameters */ #ifdef SHUT_RD - PyModule_AddIntConstant(m, "SHUT_RD", SHUT_RD); + PyModule_AddIntConstant(m, "SHUT_RD", SHUT_RD); #elif defined(SD_RECEIVE) - PyModule_AddIntConstant(m, "SHUT_RD", SD_RECEIVE); + PyModule_AddIntConstant(m, "SHUT_RD", SD_RECEIVE); #else - PyModule_AddIntConstant(m, "SHUT_RD", 0); + PyModule_AddIntConstant(m, "SHUT_RD", 0); #endif #ifdef SHUT_WR - PyModule_AddIntConstant(m, "SHUT_WR", SHUT_WR); + PyModule_AddIntConstant(m, "SHUT_WR", SHUT_WR); #elif defined(SD_SEND) - PyModule_AddIntConstant(m, "SHUT_WR", SD_SEND); + PyModule_AddIntConstant(m, "SHUT_WR", SD_SEND); #else - PyModule_AddIntConstant(m, "SHUT_WR", 1); + PyModule_AddIntConstant(m, "SHUT_WR", 1); #endif #ifdef SHUT_RDWR - PyModule_AddIntConstant(m, "SHUT_RDWR", SHUT_RDWR); + PyModule_AddIntConstant(m, "SHUT_RDWR", SHUT_RDWR); #elif defined(SD_BOTH) - PyModule_AddIntConstant(m, "SHUT_RDWR", SD_BOTH); + PyModule_AddIntConstant(m, "SHUT_RDWR", SD_BOTH); #else - PyModule_AddIntConstant(m, "SHUT_RDWR", 2); + PyModule_AddIntConstant(m, "SHUT_RDWR", 2); #endif #ifdef SIO_RCVALL - { - PyObject *tmp; - tmp = PyLong_FromUnsignedLong(SIO_RCVALL); - if (tmp == NULL) - return NULL; - PyModule_AddObject(m, "SIO_RCVALL", tmp); - } - PyModule_AddIntConstant(m, "RCVALL_OFF", RCVALL_OFF); - PyModule_AddIntConstant(m, "RCVALL_ON", RCVALL_ON); - PyModule_AddIntConstant(m, "RCVALL_SOCKETLEVELONLY", RCVALL_SOCKETLEVELONLY); + { + PyObject *tmp; + tmp = PyLong_FromUnsignedLong(SIO_RCVALL); + if (tmp == NULL) + return NULL; + PyModule_AddObject(m, "SIO_RCVALL", tmp); + } + PyModule_AddIntConstant(m, "RCVALL_OFF", RCVALL_OFF); + PyModule_AddIntConstant(m, "RCVALL_ON", RCVALL_ON); + PyModule_AddIntConstant(m, "RCVALL_SOCKETLEVELONLY", RCVALL_SOCKETLEVELONLY); #ifdef RCVALL_IPLEVEL - PyModule_AddIntConstant(m, "RCVALL_IPLEVEL", RCVALL_IPLEVEL); + PyModule_AddIntConstant(m, "RCVALL_IPLEVEL", RCVALL_IPLEVEL); #endif #ifdef RCVALL_MAX - PyModule_AddIntConstant(m, "RCVALL_MAX", RCVALL_MAX); + PyModule_AddIntConstant(m, "RCVALL_MAX", RCVALL_MAX); #endif #endif /* _MSTCPIP_ */ - /* Initialize gethostbyname lock */ + /* Initialize gethostbyname lock */ #if defined(USE_GETHOSTBYNAME_LOCK) || defined(USE_GETADDRINFO_LOCK) - netdb_lock = PyThread_allocate_lock(); + netdb_lock = PyThread_allocate_lock(); #endif - return m; + return m; } @@ -5100,34 +5100,34 @@ int inet_pton(int af, const char *src, void *dst) { - if (af == AF_INET) { + if (af == AF_INET) { #if (SIZEOF_INT != 4) #error "Not sure if in_addr_t exists and int is not 32-bits." #endif - unsigned int packed_addr; - packed_addr = inet_addr(src); - if (packed_addr == INADDR_NONE) - return 0; - memcpy(dst, &packed_addr, 4); - return 1; - } - /* Should set errno to EAFNOSUPPORT */ - return -1; + unsigned int packed_addr; + packed_addr = inet_addr(src); + if (packed_addr == INADDR_NONE) + return 0; + memcpy(dst, &packed_addr, 4); + return 1; + } + /* Should set errno to EAFNOSUPPORT */ + return -1; } const char * inet_ntop(int af, const void *src, char *dst, socklen_t size) { - if (af == AF_INET) { - struct in_addr packed_addr; - if (size < 16) - /* Should set errno to ENOSPC. */ - return NULL; - memcpy(&packed_addr, src, sizeof(packed_addr)); - return strncpy(dst, inet_ntoa(packed_addr), size); - } - /* Should set errno to EAFNOSUPPORT */ - return NULL; + if (af == AF_INET) { + struct in_addr packed_addr; + if (size < 16) + /* Should set errno to ENOSPC. */ + return NULL; + memcpy(&packed_addr, src, sizeof(packed_addr)); + return strncpy(dst, inet_ntoa(packed_addr), size); + } + /* Should set errno to EAFNOSUPPORT */ + return NULL; } #endif Modified: python/branches/release31-maint/Modules/socketmodule.h ============================================================================== --- python/branches/release31-maint/Modules/socketmodule.h (original) +++ python/branches/release31-maint/Modules/socketmodule.h Sun May 9 18:14:21 2010 @@ -17,7 +17,7 @@ # include /* VC6 is shipped with old platform headers, and does not have MSTcpIP.h * Separate SDKs have all the functions we want, but older ones don't have - * any version information. + * any version information. * I use SIO_GET_MULTICAST_FILTER to detect a decent SDK. */ # ifdef SIO_GET_MULTICAST_FILTER @@ -76,44 +76,44 @@ #endif /* Python module and C API name */ -#define PySocket_MODULE_NAME "_socket" -#define PySocket_CAPI_NAME "CAPI" -#define PySocket_CAPSULE_NAME PySocket_MODULE_NAME "." PySocket_CAPI_NAME +#define PySocket_MODULE_NAME "_socket" +#define PySocket_CAPI_NAME "CAPI" +#define PySocket_CAPSULE_NAME PySocket_MODULE_NAME "." PySocket_CAPI_NAME /* Abstract the socket file descriptor type */ #ifdef MS_WINDOWS typedef SOCKET SOCKET_T; -# ifdef MS_WIN64 -# define SIZEOF_SOCKET_T 8 -# else -# define SIZEOF_SOCKET_T 4 -# endif +# ifdef MS_WIN64 +# define SIZEOF_SOCKET_T 8 +# else +# define SIZEOF_SOCKET_T 4 +# endif #else typedef int SOCKET_T; -# define SIZEOF_SOCKET_T SIZEOF_INT +# define SIZEOF_SOCKET_T SIZEOF_INT #endif /* Socket address */ typedef union sock_addr { - struct sockaddr_in in; + struct sockaddr_in in; #ifdef AF_UNIX - struct sockaddr_un un; + struct sockaddr_un un; #endif #ifdef AF_NETLINK - struct sockaddr_nl nl; + struct sockaddr_nl nl; #endif #ifdef ENABLE_IPV6 - struct sockaddr_in6 in6; - struct sockaddr_storage storage; + struct sockaddr_in6 in6; + struct sockaddr_storage storage; #endif #ifdef HAVE_BLUETOOTH_BLUETOOTH_H - struct sockaddr_l2 bt_l2; - struct sockaddr_rc bt_rc; - struct sockaddr_sco bt_sco; - struct sockaddr_hci bt_hci; + struct sockaddr_l2 bt_l2; + struct sockaddr_rc bt_rc; + struct sockaddr_sco bt_sco; + struct sockaddr_hci bt_hci; #endif #ifdef HAVE_NETPACKET_PACKET_H - struct sockaddr_ll ll; + struct sockaddr_ll ll; #endif } sock_addr_t; @@ -122,16 +122,16 @@ arguments properly. */ typedef struct { - PyObject_HEAD - SOCKET_T sock_fd; /* Socket file descriptor */ - int sock_family; /* Address family, e.g., AF_INET */ - int sock_type; /* Socket type, e.g., SOCK_STREAM */ - int sock_proto; /* Protocol type, usually 0 */ - PyObject *(*errorhandler)(void); /* Error handler; checks - errno, returns NULL and - sets a Python exception */ - double sock_timeout; /* Operation timeout in seconds; - 0.0 means non-blocking */ + PyObject_HEAD + SOCKET_T sock_fd; /* Socket file descriptor */ + int sock_family; /* Address family, e.g., AF_INET */ + int sock_type; /* Socket type, e.g., SOCK_STREAM */ + int sock_proto; /* Protocol type, usually 0 */ + PyObject *(*errorhandler)(void); /* Error handler; checks + errno, returns NULL and + sets a Python exception */ + double sock_timeout; /* Operation timeout in seconds; + 0.0 means non-blocking */ } PySocketSockObject; /* --- C API ----------------------------------------------------*/ @@ -139,7 +139,7 @@ /* Short explanation of what this C API export mechanism does and how it works: - The _ssl module needs access to the type object defined in + The _ssl module needs access to the type object defined in the _socket module. Since cross-DLL linking introduces a lot of problems on many platforms, the "trick" is to wrap the C API of a module in a struct which then gets exported to @@ -161,24 +161,24 @@ Load _socket module and its C API; this sets up the global PySocketModule: - - if (PySocketModule_ImportModuleAndAPI()) - return; + + if (PySocketModule_ImportModuleAndAPI()) + return; Now use the C API as if it were defined in the using module: - if (!PyArg_ParseTuple(args, "O!|zz:ssl", + if (!PyArg_ParseTuple(args, "O!|zz:ssl", - PySocketModule.Sock_Type, + PySocketModule.Sock_Type, - (PyObject*)&Sock, - &key_file, &cert_file)) - return NULL; + (PyObject*)&Sock, + &key_file, &cert_file)) + return NULL; Support could easily be extended to export more C APIs/symbols - this way. Currently, only the type object is exported, + this way. Currently, only the type object is exported, other candidates would be socket constructors and socket access functions. @@ -186,8 +186,8 @@ /* C API for usage by other Python modules */ typedef struct { - PyTypeObject *Sock_Type; - PyObject *error; + PyTypeObject *Sock_Type; + PyObject *error; } PySocketModule_APIObject; #define PySocketModule_ImportModuleAndAPI() PyCapsule_Import(PySocket_CAPSULE_NAME, 1) Modified: python/branches/release31-maint/Modules/spwdmodule.c ============================================================================== --- python/branches/release31-maint/Modules/spwdmodule.c (original) +++ python/branches/release31-maint/Modules/spwdmodule.c Sun May 9 18:14:21 2010 @@ -27,16 +27,16 @@ #if defined(HAVE_GETSPNAM) || defined(HAVE_GETSPENT) static PyStructSequence_Field struct_spwd_type_fields[] = { - {"sp_nam", "login name"}, - {"sp_pwd", "encrypted password"}, - {"sp_lstchg", "date of last change"}, - {"sp_min", "min #days between changes"}, - {"sp_max", "max #days between changes"}, - {"sp_warn", "#days before pw expires to warn user about it"}, - {"sp_inact", "#days after pw expires until account is blocked"}, - {"sp_expire", "#days since 1970-01-01 until account is disabled"}, - {"sp_flag", "reserved"}, - {0} + {"sp_nam", "login name"}, + {"sp_pwd", "encrypted password"}, + {"sp_lstchg", "date of last change"}, + {"sp_min", "min #days between changes"}, + {"sp_max", "max #days between changes"}, + {"sp_warn", "#days before pw expires to warn user about it"}, + {"sp_inact", "#days after pw expires until account is blocked"}, + {"sp_expire", "#days since 1970-01-01 until account is disabled"}, + {"sp_flag", "reserved"}, + {0} }; PyDoc_STRVAR(struct_spwd__doc__, @@ -46,10 +46,10 @@ or via the object attributes as named in the above tuple."); static PyStructSequence_Desc struct_spwd_type_desc = { - "spwd.struct_spwd", - struct_spwd__doc__, - struct_spwd_type_fields, - 9, + "spwd.struct_spwd", + struct_spwd__doc__, + struct_spwd_type_fields, + 9, }; static int initialized; @@ -60,45 +60,45 @@ sets(PyObject *v, int i, const char* val) { if (val) { - PyObject *o = PyUnicode_Decode(val, strlen(val), - Py_FileSystemDefaultEncoding, - "surrogateescape"); - PyStructSequence_SET_ITEM(v, i, o); + PyObject *o = PyUnicode_Decode(val, strlen(val), + Py_FileSystemDefaultEncoding, + "surrogateescape"); + PyStructSequence_SET_ITEM(v, i, o); } else { - PyStructSequence_SET_ITEM(v, i, Py_None); - Py_INCREF(Py_None); + PyStructSequence_SET_ITEM(v, i, Py_None); + Py_INCREF(Py_None); } } static PyObject *mkspent(struct spwd *p) { - int setIndex = 0; - PyObject *v = PyStructSequence_New(&StructSpwdType); - if (v == NULL) - return NULL; + int setIndex = 0; + PyObject *v = PyStructSequence_New(&StructSpwdType); + if (v == NULL) + return NULL; #define SETI(i,val) PyStructSequence_SET_ITEM(v, i, PyLong_FromLong((long) val)) #define SETS(i,val) sets(v, i, val) - SETS(setIndex++, p->sp_namp); - SETS(setIndex++, p->sp_pwdp); - SETI(setIndex++, p->sp_lstchg); - SETI(setIndex++, p->sp_min); - SETI(setIndex++, p->sp_max); - SETI(setIndex++, p->sp_warn); - SETI(setIndex++, p->sp_inact); - SETI(setIndex++, p->sp_expire); - SETI(setIndex++, p->sp_flag); + SETS(setIndex++, p->sp_namp); + SETS(setIndex++, p->sp_pwdp); + SETI(setIndex++, p->sp_lstchg); + SETI(setIndex++, p->sp_min); + SETI(setIndex++, p->sp_max); + SETI(setIndex++, p->sp_warn); + SETI(setIndex++, p->sp_inact); + SETI(setIndex++, p->sp_expire); + SETI(setIndex++, p->sp_flag); #undef SETS #undef SETI - if (PyErr_Occurred()) { - Py_DECREF(v); - return NULL; - } + if (PyErr_Occurred()) { + Py_DECREF(v); + return NULL; + } - return v; + return v; } #endif /* HAVE_GETSPNAM || HAVE_GETSPENT */ @@ -114,26 +114,26 @@ static PyObject* spwd_getspnam(PyObject *self, PyObject *args) { - char *name; - struct spwd *p; - PyObject *arg, *bytes, *retval = NULL; - - if (!PyArg_ParseTuple(args, "U:getspnam", &arg)) - return NULL; - if ((bytes = PyUnicode_AsEncodedString(arg, - Py_FileSystemDefaultEncoding, - "surrogateescape")) == NULL) - return NULL; - if (PyBytes_AsStringAndSize(bytes, &name, NULL) == -1) - goto out; - if ((p = getspnam(name)) == NULL) { - PyErr_SetString(PyExc_KeyError, "getspnam(): name not found"); - goto out; - } - retval = mkspent(p); + char *name; + struct spwd *p; + PyObject *arg, *bytes, *retval = NULL; + + if (!PyArg_ParseTuple(args, "U:getspnam", &arg)) + return NULL; + if ((bytes = PyUnicode_AsEncodedString(arg, + Py_FileSystemDefaultEncoding, + "surrogateescape")) == NULL) + return NULL; + if (PyBytes_AsStringAndSize(bytes, &name, NULL) == -1) + goto out; + if ((p = getspnam(name)) == NULL) { + PyErr_SetString(PyExc_KeyError, "getspnam(): name not found"); + goto out; + } + retval = mkspent(p); out: - Py_DECREF(bytes); - return retval; + Py_DECREF(bytes); + return retval; } #endif /* HAVE_GETSPNAM */ @@ -149,63 +149,63 @@ static PyObject * spwd_getspall(PyObject *self, PyObject *args) { - PyObject *d; - struct spwd *p; - if ((d = PyList_New(0)) == NULL) - return NULL; - setspent(); - while ((p = getspent()) != NULL) { - PyObject *v = mkspent(p); - if (v == NULL || PyList_Append(d, v) != 0) { - Py_XDECREF(v); - Py_DECREF(d); - endspent(); - return NULL; - } - Py_DECREF(v); - } - endspent(); - return d; + PyObject *d; + struct spwd *p; + if ((d = PyList_New(0)) == NULL) + return NULL; + setspent(); + while ((p = getspent()) != NULL) { + PyObject *v = mkspent(p); + if (v == NULL || PyList_Append(d, v) != 0) { + Py_XDECREF(v); + Py_DECREF(d); + endspent(); + return NULL; + } + Py_DECREF(v); + } + endspent(); + return d; } #endif /* HAVE_GETSPENT */ static PyMethodDef spwd_methods[] = { -#ifdef HAVE_GETSPNAM - {"getspnam", spwd_getspnam, METH_VARARGS, spwd_getspnam__doc__}, +#ifdef HAVE_GETSPNAM + {"getspnam", spwd_getspnam, METH_VARARGS, spwd_getspnam__doc__}, #endif #ifdef HAVE_GETSPENT - {"getspall", spwd_getspall, METH_NOARGS, spwd_getspall__doc__}, + {"getspall", spwd_getspall, METH_NOARGS, spwd_getspall__doc__}, #endif - {NULL, NULL} /* sentinel */ + {NULL, NULL} /* sentinel */ }; static struct PyModuleDef spwdmodule = { - PyModuleDef_HEAD_INIT, - "spwd", - spwd__doc__, - -1, - spwd_methods, - NULL, - NULL, - NULL, - NULL + PyModuleDef_HEAD_INIT, + "spwd", + spwd__doc__, + -1, + spwd_methods, + NULL, + NULL, + NULL, + NULL }; PyMODINIT_FUNC PyInit_spwd(void) { - PyObject *m; - m=PyModule_Create(&spwdmodule); - if (m == NULL) - return NULL; - if (!initialized) - PyStructSequence_InitType(&StructSpwdType, - &struct_spwd_type_desc); - Py_INCREF((PyObject *) &StructSpwdType); - PyModule_AddObject(m, "struct_spwd", (PyObject *) &StructSpwdType); - initialized = 1; - return m; + PyObject *m; + m=PyModule_Create(&spwdmodule); + if (m == NULL) + return NULL; + if (!initialized) + PyStructSequence_InitType(&StructSpwdType, + &struct_spwd_type_desc); + Py_INCREF((PyObject *) &StructSpwdType); + PyModule_AddObject(m, "struct_spwd", (PyObject *) &StructSpwdType); + initialized = 1; + return m; } Modified: python/branches/release31-maint/Modules/symtablemodule.c ============================================================================== --- python/branches/release31-maint/Modules/symtablemodule.c (original) +++ python/branches/release31-maint/Modules/symtablemodule.c Sun May 9 18:14:21 2010 @@ -8,97 +8,97 @@ static PyObject * symtable_symtable(PyObject *self, PyObject *args) { - struct symtable *st; - PyObject *t; + struct symtable *st; + PyObject *t; - char *str; - char *filename; - char *startstr; - int start; - - if (!PyArg_ParseTuple(args, "sss:symtable", &str, &filename, - &startstr)) - return NULL; - if (strcmp(startstr, "exec") == 0) - start = Py_file_input; - else if (strcmp(startstr, "eval") == 0) - start = Py_eval_input; - else if (strcmp(startstr, "single") == 0) - start = Py_single_input; - else { - PyErr_SetString(PyExc_ValueError, - "symtable() arg 3 must be 'exec' or 'eval' or 'single'"); - return NULL; - } - st = Py_SymtableString(str, filename, start); - if (st == NULL) - return NULL; - t = st->st_blocks; - Py_INCREF(t); - PyMem_Free((void *)st->st_future); - PySymtable_Free(st); - return t; + char *str; + char *filename; + char *startstr; + int start; + + if (!PyArg_ParseTuple(args, "sss:symtable", &str, &filename, + &startstr)) + return NULL; + if (strcmp(startstr, "exec") == 0) + start = Py_file_input; + else if (strcmp(startstr, "eval") == 0) + start = Py_eval_input; + else if (strcmp(startstr, "single") == 0) + start = Py_single_input; + else { + PyErr_SetString(PyExc_ValueError, + "symtable() arg 3 must be 'exec' or 'eval' or 'single'"); + return NULL; + } + st = Py_SymtableString(str, filename, start); + if (st == NULL) + return NULL; + t = st->st_blocks; + Py_INCREF(t); + PyMem_Free((void *)st->st_future); + PySymtable_Free(st); + return t; } static PyMethodDef symtable_methods[] = { - {"symtable", symtable_symtable, METH_VARARGS, - PyDoc_STR("Return symbol and scope dictionaries" - " used internally by compiler.")}, - {NULL, NULL} /* sentinel */ + {"symtable", symtable_symtable, METH_VARARGS, + PyDoc_STR("Return symbol and scope dictionaries" + " used internally by compiler.")}, + {NULL, NULL} /* sentinel */ }; static struct PyModuleDef symtablemodule = { - PyModuleDef_HEAD_INIT, - "_symtable", - NULL, - -1, - symtable_methods, - NULL, - NULL, - NULL, - NULL + PyModuleDef_HEAD_INIT, + "_symtable", + NULL, + -1, + symtable_methods, + NULL, + NULL, + NULL, + NULL }; PyMODINIT_FUNC PyInit__symtable(void) { - PyObject *m; + PyObject *m; - m = PyModule_Create(&symtablemodule); - if (m == NULL) - return NULL; - PyModule_AddIntConstant(m, "USE", USE); - PyModule_AddIntConstant(m, "DEF_GLOBAL", DEF_GLOBAL); - PyModule_AddIntConstant(m, "DEF_LOCAL", DEF_LOCAL); - PyModule_AddIntConstant(m, "DEF_PARAM", DEF_PARAM); - PyModule_AddIntConstant(m, "DEF_STAR", DEF_STAR); - PyModule_AddIntConstant(m, "DEF_DOUBLESTAR", DEF_DOUBLESTAR); - PyModule_AddIntConstant(m, "DEF_INTUPLE", DEF_INTUPLE); - PyModule_AddIntConstant(m, "DEF_FREE", DEF_FREE); - PyModule_AddIntConstant(m, "DEF_FREE_GLOBAL", DEF_FREE_GLOBAL); - PyModule_AddIntConstant(m, "DEF_FREE_CLASS", DEF_FREE_CLASS); - PyModule_AddIntConstant(m, "DEF_IMPORT", DEF_IMPORT); - PyModule_AddIntConstant(m, "DEF_BOUND", DEF_BOUND); - - PyModule_AddIntConstant(m, "TYPE_FUNCTION", FunctionBlock); - PyModule_AddIntConstant(m, "TYPE_CLASS", ClassBlock); - PyModule_AddIntConstant(m, "TYPE_MODULE", ModuleBlock); - - PyModule_AddIntConstant(m, "OPT_IMPORT_STAR", OPT_IMPORT_STAR); - PyModule_AddIntConstant(m, "OPT_TOPLEVEL", OPT_TOPLEVEL); - - PyModule_AddIntConstant(m, "LOCAL", LOCAL); - PyModule_AddIntConstant(m, "GLOBAL_EXPLICIT", GLOBAL_EXPLICIT); - PyModule_AddIntConstant(m, "GLOBAL_IMPLICIT", GLOBAL_IMPLICIT); - PyModule_AddIntConstant(m, "FREE", FREE); - PyModule_AddIntConstant(m, "CELL", CELL); - - PyModule_AddIntConstant(m, "SCOPE_OFF", SCOPE_OFFSET); - PyModule_AddIntConstant(m, "SCOPE_MASK", SCOPE_MASK); - - if (PyErr_Occurred()) { - Py_DECREF(m); - m = 0; - } - return m; + m = PyModule_Create(&symtablemodule); + if (m == NULL) + return NULL; + PyModule_AddIntConstant(m, "USE", USE); + PyModule_AddIntConstant(m, "DEF_GLOBAL", DEF_GLOBAL); + PyModule_AddIntConstant(m, "DEF_LOCAL", DEF_LOCAL); + PyModule_AddIntConstant(m, "DEF_PARAM", DEF_PARAM); + PyModule_AddIntConstant(m, "DEF_STAR", DEF_STAR); + PyModule_AddIntConstant(m, "DEF_DOUBLESTAR", DEF_DOUBLESTAR); + PyModule_AddIntConstant(m, "DEF_INTUPLE", DEF_INTUPLE); + PyModule_AddIntConstant(m, "DEF_FREE", DEF_FREE); + PyModule_AddIntConstant(m, "DEF_FREE_GLOBAL", DEF_FREE_GLOBAL); + PyModule_AddIntConstant(m, "DEF_FREE_CLASS", DEF_FREE_CLASS); + PyModule_AddIntConstant(m, "DEF_IMPORT", DEF_IMPORT); + PyModule_AddIntConstant(m, "DEF_BOUND", DEF_BOUND); + + PyModule_AddIntConstant(m, "TYPE_FUNCTION", FunctionBlock); + PyModule_AddIntConstant(m, "TYPE_CLASS", ClassBlock); + PyModule_AddIntConstant(m, "TYPE_MODULE", ModuleBlock); + + PyModule_AddIntConstant(m, "OPT_IMPORT_STAR", OPT_IMPORT_STAR); + PyModule_AddIntConstant(m, "OPT_TOPLEVEL", OPT_TOPLEVEL); + + PyModule_AddIntConstant(m, "LOCAL", LOCAL); + PyModule_AddIntConstant(m, "GLOBAL_EXPLICIT", GLOBAL_EXPLICIT); + PyModule_AddIntConstant(m, "GLOBAL_IMPLICIT", GLOBAL_IMPLICIT); + PyModule_AddIntConstant(m, "FREE", FREE); + PyModule_AddIntConstant(m, "CELL", CELL); + + PyModule_AddIntConstant(m, "SCOPE_OFF", SCOPE_OFFSET); + PyModule_AddIntConstant(m, "SCOPE_MASK", SCOPE_MASK); + + if (PyErr_Occurred()) { + Py_DECREF(m); + m = 0; + } + return m; } Modified: python/branches/release31-maint/Modules/syslogmodule.c ============================================================================== --- python/branches/release31-maint/Modules/syslogmodule.c (original) +++ python/branches/release31-maint/Modules/syslogmodule.c Sun May 9 18:14:21 2010 @@ -4,20 +4,20 @@ All Rights Reserved -Permission to use, copy, modify, and distribute this software and its -documentation for any purpose and without fee is hereby granted, +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 +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 +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 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 +FITNESS, IN NO EVENT SHALL LANCE ELLINGHOUSE 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. ******************************************************************/ @@ -49,198 +49,198 @@ #include /* only one instance, only one syslog, so globals should be ok */ -static PyObject *S_ident_o = NULL; /* identifier, held by openlog() */ +static PyObject *S_ident_o = NULL; /* identifier, held by openlog() */ -static PyObject * +static PyObject * syslog_openlog(PyObject * self, PyObject * args) { - long logopt = 0; - long facility = LOG_USER; - PyObject *new_S_ident_o; - const char *ident; - - if (!PyArg_ParseTuple(args, - "U|ll;ident string [, logoption [, facility]]", - &new_S_ident_o, &logopt, &facility)) - return NULL; - - /* This is needed because openlog() does NOT make a copy - * and syslog() later uses it.. cannot trash it. - */ - Py_XDECREF(S_ident_o); - S_ident_o = new_S_ident_o; - Py_INCREF(S_ident_o); - - ident = _PyUnicode_AsString(S_ident_o); - if (ident == NULL) - return NULL; - openlog(ident, logopt, facility); + long logopt = 0; + long facility = LOG_USER; + PyObject *new_S_ident_o; + const char *ident; + + if (!PyArg_ParseTuple(args, + "U|ll;ident string [, logoption [, facility]]", + &new_S_ident_o, &logopt, &facility)) + return NULL; + + /* This is needed because openlog() does NOT make a copy + * and syslog() later uses it.. cannot trash it. + */ + Py_XDECREF(S_ident_o); + S_ident_o = new_S_ident_o; + Py_INCREF(S_ident_o); + + ident = _PyUnicode_AsString(S_ident_o); + if (ident == NULL) + return NULL; + openlog(ident, logopt, facility); - Py_INCREF(Py_None); - return Py_None; + Py_INCREF(Py_None); + return Py_None; } -static PyObject * +static PyObject * syslog_syslog(PyObject * self, PyObject * args) { - PyObject *message_object; - const char *message; - int priority = LOG_INFO; - - if (!PyArg_ParseTuple(args, "iU;[priority,] message string", - &priority, &message_object)) { - PyErr_Clear(); - if (!PyArg_ParseTuple(args, "U;[priority,] message string", - &message_object)) - return NULL; - } - - message = _PyUnicode_AsString(message_object); - if (message == NULL) - return NULL; - Py_BEGIN_ALLOW_THREADS; - syslog(priority, "%s", message); - Py_END_ALLOW_THREADS; - Py_RETURN_NONE; + PyObject *message_object; + const char *message; + int priority = LOG_INFO; + + if (!PyArg_ParseTuple(args, "iU;[priority,] message string", + &priority, &message_object)) { + PyErr_Clear(); + if (!PyArg_ParseTuple(args, "U;[priority,] message string", + &message_object)) + return NULL; + } + + message = _PyUnicode_AsString(message_object); + if (message == NULL) + return NULL; + Py_BEGIN_ALLOW_THREADS; + syslog(priority, "%s", message); + Py_END_ALLOW_THREADS; + Py_RETURN_NONE; } -static PyObject * +static PyObject * syslog_closelog(PyObject *self, PyObject *unused) { - closelog(); - Py_XDECREF(S_ident_o); - S_ident_o = NULL; - Py_INCREF(Py_None); - return Py_None; + closelog(); + Py_XDECREF(S_ident_o); + S_ident_o = NULL; + Py_INCREF(Py_None); + return Py_None; } -static PyObject * +static PyObject * syslog_setlogmask(PyObject *self, PyObject *args) { - long maskpri, omaskpri; + long maskpri, omaskpri; - if (!PyArg_ParseTuple(args, "l;mask for priority", &maskpri)) - return NULL; - omaskpri = setlogmask(maskpri); - return PyLong_FromLong(omaskpri); + if (!PyArg_ParseTuple(args, "l;mask for priority", &maskpri)) + return NULL; + omaskpri = setlogmask(maskpri); + return PyLong_FromLong(omaskpri); } -static PyObject * +static PyObject * syslog_log_mask(PyObject *self, PyObject *args) { - long mask; - long pri; - if (!PyArg_ParseTuple(args, "l:LOG_MASK", &pri)) - return NULL; - mask = LOG_MASK(pri); - return PyLong_FromLong(mask); + long mask; + long pri; + if (!PyArg_ParseTuple(args, "l:LOG_MASK", &pri)) + return NULL; + mask = LOG_MASK(pri); + return PyLong_FromLong(mask); } -static PyObject * +static PyObject * syslog_log_upto(PyObject *self, PyObject *args) { - long mask; - long pri; - if (!PyArg_ParseTuple(args, "l:LOG_UPTO", &pri)) - return NULL; - mask = LOG_UPTO(pri); - return PyLong_FromLong(mask); + long mask; + long pri; + if (!PyArg_ParseTuple(args, "l:LOG_UPTO", &pri)) + return NULL; + mask = LOG_UPTO(pri); + return PyLong_FromLong(mask); } /* List of functions defined in the module */ static PyMethodDef syslog_methods[] = { - {"openlog", syslog_openlog, METH_VARARGS}, - {"closelog", syslog_closelog, METH_NOARGS}, - {"syslog", syslog_syslog, METH_VARARGS}, - {"setlogmask", syslog_setlogmask, METH_VARARGS}, - {"LOG_MASK", syslog_log_mask, METH_VARARGS}, - {"LOG_UPTO", syslog_log_upto, METH_VARARGS}, - {NULL, NULL, 0} + {"openlog", syslog_openlog, METH_VARARGS}, + {"closelog", syslog_closelog, METH_NOARGS}, + {"syslog", syslog_syslog, METH_VARARGS}, + {"setlogmask", syslog_setlogmask, METH_VARARGS}, + {"LOG_MASK", syslog_log_mask, METH_VARARGS}, + {"LOG_UPTO", syslog_log_upto, METH_VARARGS}, + {NULL, NULL, 0} }; /* Initialization function for the module */ static struct PyModuleDef syslogmodule = { - PyModuleDef_HEAD_INIT, - "syslog", - NULL, - -1, - syslog_methods, - NULL, - NULL, - NULL, - NULL + PyModuleDef_HEAD_INIT, + "syslog", + NULL, + -1, + syslog_methods, + NULL, + NULL, + NULL, + NULL }; PyMODINIT_FUNC PyInit_syslog(void) { - PyObject *m; + PyObject *m; - /* Create the module and add the functions */ - m = PyModule_Create(&syslogmodule); - if (m == NULL) - return NULL; - - /* Add some symbolic constants to the module */ - - /* Priorities */ - PyModule_AddIntConstant(m, "LOG_EMERG", LOG_EMERG); - PyModule_AddIntConstant(m, "LOG_ALERT", LOG_ALERT); - PyModule_AddIntConstant(m, "LOG_CRIT", LOG_CRIT); - PyModule_AddIntConstant(m, "LOG_ERR", LOG_ERR); - PyModule_AddIntConstant(m, "LOG_WARNING", LOG_WARNING); - PyModule_AddIntConstant(m, "LOG_NOTICE", LOG_NOTICE); - PyModule_AddIntConstant(m, "LOG_INFO", LOG_INFO); - PyModule_AddIntConstant(m, "LOG_DEBUG", LOG_DEBUG); - - /* openlog() option flags */ - PyModule_AddIntConstant(m, "LOG_PID", LOG_PID); - PyModule_AddIntConstant(m, "LOG_CONS", LOG_CONS); - PyModule_AddIntConstant(m, "LOG_NDELAY", LOG_NDELAY); + /* Create the module and add the functions */ + m = PyModule_Create(&syslogmodule); + if (m == NULL) + return NULL; + + /* Add some symbolic constants to the module */ + + /* Priorities */ + PyModule_AddIntConstant(m, "LOG_EMERG", LOG_EMERG); + PyModule_AddIntConstant(m, "LOG_ALERT", LOG_ALERT); + PyModule_AddIntConstant(m, "LOG_CRIT", LOG_CRIT); + PyModule_AddIntConstant(m, "LOG_ERR", LOG_ERR); + PyModule_AddIntConstant(m, "LOG_WARNING", LOG_WARNING); + PyModule_AddIntConstant(m, "LOG_NOTICE", LOG_NOTICE); + PyModule_AddIntConstant(m, "LOG_INFO", LOG_INFO); + PyModule_AddIntConstant(m, "LOG_DEBUG", LOG_DEBUG); + + /* openlog() option flags */ + PyModule_AddIntConstant(m, "LOG_PID", LOG_PID); + PyModule_AddIntConstant(m, "LOG_CONS", LOG_CONS); + PyModule_AddIntConstant(m, "LOG_NDELAY", LOG_NDELAY); #ifdef LOG_NOWAIT - PyModule_AddIntConstant(m, "LOG_NOWAIT", LOG_NOWAIT); + PyModule_AddIntConstant(m, "LOG_NOWAIT", LOG_NOWAIT); #endif #ifdef LOG_PERROR - PyModule_AddIntConstant(m, "LOG_PERROR", LOG_PERROR); + PyModule_AddIntConstant(m, "LOG_PERROR", LOG_PERROR); #endif - /* Facilities */ - PyModule_AddIntConstant(m, "LOG_KERN", LOG_KERN); - PyModule_AddIntConstant(m, "LOG_USER", LOG_USER); - PyModule_AddIntConstant(m, "LOG_MAIL", LOG_MAIL); - PyModule_AddIntConstant(m, "LOG_DAEMON", LOG_DAEMON); - PyModule_AddIntConstant(m, "LOG_AUTH", LOG_AUTH); - PyModule_AddIntConstant(m, "LOG_LPR", LOG_LPR); - PyModule_AddIntConstant(m, "LOG_LOCAL0", LOG_LOCAL0); - PyModule_AddIntConstant(m, "LOG_LOCAL1", LOG_LOCAL1); - PyModule_AddIntConstant(m, "LOG_LOCAL2", LOG_LOCAL2); - PyModule_AddIntConstant(m, "LOG_LOCAL3", LOG_LOCAL3); - PyModule_AddIntConstant(m, "LOG_LOCAL4", LOG_LOCAL4); - PyModule_AddIntConstant(m, "LOG_LOCAL5", LOG_LOCAL5); - PyModule_AddIntConstant(m, "LOG_LOCAL6", LOG_LOCAL6); - PyModule_AddIntConstant(m, "LOG_LOCAL7", LOG_LOCAL7); + /* Facilities */ + PyModule_AddIntConstant(m, "LOG_KERN", LOG_KERN); + PyModule_AddIntConstant(m, "LOG_USER", LOG_USER); + PyModule_AddIntConstant(m, "LOG_MAIL", LOG_MAIL); + PyModule_AddIntConstant(m, "LOG_DAEMON", LOG_DAEMON); + PyModule_AddIntConstant(m, "LOG_AUTH", LOG_AUTH); + PyModule_AddIntConstant(m, "LOG_LPR", LOG_LPR); + PyModule_AddIntConstant(m, "LOG_LOCAL0", LOG_LOCAL0); + PyModule_AddIntConstant(m, "LOG_LOCAL1", LOG_LOCAL1); + PyModule_AddIntConstant(m, "LOG_LOCAL2", LOG_LOCAL2); + PyModule_AddIntConstant(m, "LOG_LOCAL3", LOG_LOCAL3); + PyModule_AddIntConstant(m, "LOG_LOCAL4", LOG_LOCAL4); + PyModule_AddIntConstant(m, "LOG_LOCAL5", LOG_LOCAL5); + PyModule_AddIntConstant(m, "LOG_LOCAL6", LOG_LOCAL6); + PyModule_AddIntConstant(m, "LOG_LOCAL7", LOG_LOCAL7); #ifndef LOG_SYSLOG -#define LOG_SYSLOG LOG_DAEMON +#define LOG_SYSLOG LOG_DAEMON #endif #ifndef LOG_NEWS -#define LOG_NEWS LOG_MAIL +#define LOG_NEWS LOG_MAIL #endif #ifndef LOG_UUCP -#define LOG_UUCP LOG_MAIL +#define LOG_UUCP LOG_MAIL #endif #ifndef LOG_CRON -#define LOG_CRON LOG_DAEMON +#define LOG_CRON LOG_DAEMON #endif - PyModule_AddIntConstant(m, "LOG_SYSLOG", LOG_SYSLOG); - PyModule_AddIntConstant(m, "LOG_CRON", LOG_CRON); - PyModule_AddIntConstant(m, "LOG_UUCP", LOG_UUCP); - PyModule_AddIntConstant(m, "LOG_NEWS", LOG_NEWS); - return m; + PyModule_AddIntConstant(m, "LOG_SYSLOG", LOG_SYSLOG); + PyModule_AddIntConstant(m, "LOG_CRON", LOG_CRON); + PyModule_AddIntConstant(m, "LOG_UUCP", LOG_UUCP); + PyModule_AddIntConstant(m, "LOG_NEWS", LOG_NEWS); + return m; } Modified: python/branches/release31-maint/Modules/termios.c ============================================================================== --- python/branches/release31-maint/Modules/termios.c (original) +++ python/branches/release31-maint/Modules/termios.c Sun May 9 18:14:21 2010 @@ -42,14 +42,14 @@ static int fdconv(PyObject* obj, void* p) { - int fd; + int fd; - fd = PyObject_AsFileDescriptor(obj); - if (fd >= 0) { - *(int*)p = fd; - return 1; - } - return 0; + fd = PyObject_AsFileDescriptor(obj); + if (fd >= 0) { + *(int*)p = fd; + return 1; + } + return 0; } PyDoc_STRVAR(termios_tcgetattr__doc__, @@ -66,67 +66,67 @@ static PyObject * termios_tcgetattr(PyObject *self, PyObject *args) { - int fd; - struct termios mode; - PyObject *cc; - speed_t ispeed, ospeed; - PyObject *v; - int i; - char ch; - - if (!PyArg_ParseTuple(args, "O&:tcgetattr", - fdconv, (void*)&fd)) - return NULL; - - if (tcgetattr(fd, &mode) == -1) - return PyErr_SetFromErrno(TermiosError); - - ispeed = cfgetispeed(&mode); - ospeed = cfgetospeed(&mode); - - cc = PyList_New(NCCS); - if (cc == NULL) - return NULL; - for (i = 0; i < NCCS; i++) { - ch = (char)mode.c_cc[i]; - v = PyBytes_FromStringAndSize(&ch, 1); - if (v == NULL) - goto err; - PyList_SetItem(cc, i, v); - } - - /* Convert the MIN and TIME slots to integer. On some systems, the - MIN and TIME slots are the same as the EOF and EOL slots. So we - only do this in noncanonical input mode. */ - if ((mode.c_lflag & ICANON) == 0) { - v = PyLong_FromLong((long)mode.c_cc[VMIN]); - if (v == NULL) - goto err; - PyList_SetItem(cc, VMIN, v); - v = PyLong_FromLong((long)mode.c_cc[VTIME]); - if (v == NULL) - goto err; - PyList_SetItem(cc, VTIME, v); - } - - if (!(v = PyList_New(7))) - goto err; - - PyList_SetItem(v, 0, PyLong_FromLong((long)mode.c_iflag)); - PyList_SetItem(v, 1, PyLong_FromLong((long)mode.c_oflag)); - PyList_SetItem(v, 2, PyLong_FromLong((long)mode.c_cflag)); - PyList_SetItem(v, 3, PyLong_FromLong((long)mode.c_lflag)); - PyList_SetItem(v, 4, PyLong_FromLong((long)ispeed)); - PyList_SetItem(v, 5, PyLong_FromLong((long)ospeed)); - PyList_SetItem(v, 6, cc); - if (PyErr_Occurred()){ - Py_DECREF(v); - goto err; - } - return v; + int fd; + struct termios mode; + PyObject *cc; + speed_t ispeed, ospeed; + PyObject *v; + int i; + char ch; + + if (!PyArg_ParseTuple(args, "O&:tcgetattr", + fdconv, (void*)&fd)) + return NULL; + + if (tcgetattr(fd, &mode) == -1) + return PyErr_SetFromErrno(TermiosError); + + ispeed = cfgetispeed(&mode); + ospeed = cfgetospeed(&mode); + + cc = PyList_New(NCCS); + if (cc == NULL) + return NULL; + for (i = 0; i < NCCS; i++) { + ch = (char)mode.c_cc[i]; + v = PyBytes_FromStringAndSize(&ch, 1); + if (v == NULL) + goto err; + PyList_SetItem(cc, i, v); + } + + /* Convert the MIN and TIME slots to integer. On some systems, the + MIN and TIME slots are the same as the EOF and EOL slots. So we + only do this in noncanonical input mode. */ + if ((mode.c_lflag & ICANON) == 0) { + v = PyLong_FromLong((long)mode.c_cc[VMIN]); + if (v == NULL) + goto err; + PyList_SetItem(cc, VMIN, v); + v = PyLong_FromLong((long)mode.c_cc[VTIME]); + if (v == NULL) + goto err; + PyList_SetItem(cc, VTIME, v); + } + + if (!(v = PyList_New(7))) + goto err; + + PyList_SetItem(v, 0, PyLong_FromLong((long)mode.c_iflag)); + PyList_SetItem(v, 1, PyLong_FromLong((long)mode.c_oflag)); + PyList_SetItem(v, 2, PyLong_FromLong((long)mode.c_cflag)); + PyList_SetItem(v, 3, PyLong_FromLong((long)mode.c_lflag)); + PyList_SetItem(v, 4, PyLong_FromLong((long)ispeed)); + PyList_SetItem(v, 5, PyLong_FromLong((long)ospeed)); + PyList_SetItem(v, 6, cc); + if (PyErr_Occurred()){ + Py_DECREF(v); + goto err; + } + return v; err: - Py_DECREF(cc); - return NULL; + Py_DECREF(cc); + return NULL; } PyDoc_STRVAR(termios_tcsetattr__doc__, @@ -143,64 +143,64 @@ static PyObject * termios_tcsetattr(PyObject *self, PyObject *args) { - int fd, when; - struct termios mode; - speed_t ispeed, ospeed; - PyObject *term, *cc, *v; - int i; - - if (!PyArg_ParseTuple(args, "O&iO:tcsetattr", - fdconv, &fd, &when, &term)) - return NULL; - if (!PyList_Check(term) || PyList_Size(term) != 7) { - PyErr_SetString(PyExc_TypeError, - "tcsetattr, arg 3: must be 7 element list"); - return NULL; - } - - /* Get the old mode, in case there are any hidden fields... */ - if (tcgetattr(fd, &mode) == -1) - return PyErr_SetFromErrno(TermiosError); - mode.c_iflag = (tcflag_t) PyLong_AsLong(PyList_GetItem(term, 0)); - mode.c_oflag = (tcflag_t) PyLong_AsLong(PyList_GetItem(term, 1)); - mode.c_cflag = (tcflag_t) PyLong_AsLong(PyList_GetItem(term, 2)); - mode.c_lflag = (tcflag_t) PyLong_AsLong(PyList_GetItem(term, 3)); - ispeed = (speed_t) PyLong_AsLong(PyList_GetItem(term, 4)); - ospeed = (speed_t) PyLong_AsLong(PyList_GetItem(term, 5)); - cc = PyList_GetItem(term, 6); - if (PyErr_Occurred()) - return NULL; - - if (!PyList_Check(cc) || PyList_Size(cc) != NCCS) { - PyErr_Format(PyExc_TypeError, - "tcsetattr: attributes[6] must be %d element list", - NCCS); - return NULL; - } - - for (i = 0; i < NCCS; i++) { - v = PyList_GetItem(cc, i); - - if (PyBytes_Check(v) && PyBytes_Size(v) == 1) - mode.c_cc[i] = (cc_t) * PyBytes_AsString(v); - else if (PyLong_Check(v)) - mode.c_cc[i] = (cc_t) PyLong_AsLong(v); - else { - PyErr_SetString(PyExc_TypeError, + int fd, when; + struct termios mode; + speed_t ispeed, ospeed; + PyObject *term, *cc, *v; + int i; + + if (!PyArg_ParseTuple(args, "O&iO:tcsetattr", + fdconv, &fd, &when, &term)) + return NULL; + if (!PyList_Check(term) || PyList_Size(term) != 7) { + PyErr_SetString(PyExc_TypeError, + "tcsetattr, arg 3: must be 7 element list"); + return NULL; + } + + /* Get the old mode, in case there are any hidden fields... */ + if (tcgetattr(fd, &mode) == -1) + return PyErr_SetFromErrno(TermiosError); + mode.c_iflag = (tcflag_t) PyLong_AsLong(PyList_GetItem(term, 0)); + mode.c_oflag = (tcflag_t) PyLong_AsLong(PyList_GetItem(term, 1)); + mode.c_cflag = (tcflag_t) PyLong_AsLong(PyList_GetItem(term, 2)); + mode.c_lflag = (tcflag_t) PyLong_AsLong(PyList_GetItem(term, 3)); + ispeed = (speed_t) PyLong_AsLong(PyList_GetItem(term, 4)); + ospeed = (speed_t) PyLong_AsLong(PyList_GetItem(term, 5)); + cc = PyList_GetItem(term, 6); + if (PyErr_Occurred()) + return NULL; + + if (!PyList_Check(cc) || PyList_Size(cc) != NCCS) { + PyErr_Format(PyExc_TypeError, + "tcsetattr: attributes[6] must be %d element list", + NCCS); + return NULL; + } + + for (i = 0; i < NCCS; i++) { + v = PyList_GetItem(cc, i); + + if (PyBytes_Check(v) && PyBytes_Size(v) == 1) + mode.c_cc[i] = (cc_t) * PyBytes_AsString(v); + else if (PyLong_Check(v)) + mode.c_cc[i] = (cc_t) PyLong_AsLong(v); + else { + PyErr_SetString(PyExc_TypeError, "tcsetattr: elements of attributes must be characters or integers"); - return NULL; - } - } - - if (cfsetispeed(&mode, (speed_t) ispeed) == -1) - return PyErr_SetFromErrno(TermiosError); - if (cfsetospeed(&mode, (speed_t) ospeed) == -1) - return PyErr_SetFromErrno(TermiosError); - if (tcsetattr(fd, when, &mode) == -1) - return PyErr_SetFromErrno(TermiosError); + return NULL; + } + } + + if (cfsetispeed(&mode, (speed_t) ispeed) == -1) + return PyErr_SetFromErrno(TermiosError); + if (cfsetospeed(&mode, (speed_t) ospeed) == -1) + return PyErr_SetFromErrno(TermiosError); + if (tcsetattr(fd, when, &mode) == -1) + return PyErr_SetFromErrno(TermiosError); - Py_INCREF(Py_None); - return Py_None; + Py_INCREF(Py_None); + return Py_None; } PyDoc_STRVAR(termios_tcsendbreak__doc__, @@ -213,16 +213,16 @@ static PyObject * termios_tcsendbreak(PyObject *self, PyObject *args) { - int fd, duration; + int fd, duration; - if (!PyArg_ParseTuple(args, "O&i:tcsendbreak", - fdconv, &fd, &duration)) - return NULL; - if (tcsendbreak(fd, duration) == -1) - return PyErr_SetFromErrno(TermiosError); + if (!PyArg_ParseTuple(args, "O&i:tcsendbreak", + fdconv, &fd, &duration)) + return NULL; + if (tcsendbreak(fd, duration) == -1) + return PyErr_SetFromErrno(TermiosError); - Py_INCREF(Py_None); - return Py_None; + Py_INCREF(Py_None); + return Py_None; } PyDoc_STRVAR(termios_tcdrain__doc__, @@ -233,16 +233,16 @@ static PyObject * termios_tcdrain(PyObject *self, PyObject *args) { - int fd; + int fd; - if (!PyArg_ParseTuple(args, "O&:tcdrain", - fdconv, &fd)) - return NULL; - if (tcdrain(fd) == -1) - return PyErr_SetFromErrno(TermiosError); + if (!PyArg_ParseTuple(args, "O&:tcdrain", + fdconv, &fd)) + return NULL; + if (tcdrain(fd) == -1) + return PyErr_SetFromErrno(TermiosError); - Py_INCREF(Py_None); - return Py_None; + Py_INCREF(Py_None); + return Py_None; } PyDoc_STRVAR(termios_tcflush__doc__, @@ -256,16 +256,16 @@ static PyObject * termios_tcflush(PyObject *self, PyObject *args) { - int fd, queue; + int fd, queue; - if (!PyArg_ParseTuple(args, "O&i:tcflush", - fdconv, &fd, &queue)) - return NULL; - if (tcflush(fd, queue) == -1) - return PyErr_SetFromErrno(TermiosError); + if (!PyArg_ParseTuple(args, "O&i:tcflush", + fdconv, &fd, &queue)) + return NULL; + if (tcflush(fd, queue) == -1) + return PyErr_SetFromErrno(TermiosError); - Py_INCREF(Py_None); - return Py_None; + Py_INCREF(Py_None); + return Py_None; } PyDoc_STRVAR(termios_tcflow__doc__, @@ -279,33 +279,33 @@ static PyObject * termios_tcflow(PyObject *self, PyObject *args) { - int fd, action; + int fd, action; - if (!PyArg_ParseTuple(args, "O&i:tcflow", - fdconv, &fd, &action)) - return NULL; - if (tcflow(fd, action) == -1) - return PyErr_SetFromErrno(TermiosError); + if (!PyArg_ParseTuple(args, "O&i:tcflow", + fdconv, &fd, &action)) + return NULL; + if (tcflow(fd, action) == -1) + return PyErr_SetFromErrno(TermiosError); - Py_INCREF(Py_None); - return Py_None; + Py_INCREF(Py_None); + return Py_None; } static PyMethodDef termios_methods[] = { - {"tcgetattr", termios_tcgetattr, - METH_VARARGS, termios_tcgetattr__doc__}, - {"tcsetattr", termios_tcsetattr, - METH_VARARGS, termios_tcsetattr__doc__}, - {"tcsendbreak", termios_tcsendbreak, - METH_VARARGS, termios_tcsendbreak__doc__}, - {"tcdrain", termios_tcdrain, - METH_VARARGS, termios_tcdrain__doc__}, - {"tcflush", termios_tcflush, - METH_VARARGS, termios_tcflush__doc__}, - {"tcflow", termios_tcflow, - METH_VARARGS, termios_tcflow__doc__}, - {NULL, NULL} + {"tcgetattr", termios_tcgetattr, + METH_VARARGS, termios_tcgetattr__doc__}, + {"tcsetattr", termios_tcsetattr, + METH_VARARGS, termios_tcsetattr__doc__}, + {"tcsendbreak", termios_tcsendbreak, + METH_VARARGS, termios_tcsendbreak__doc__}, + {"tcdrain", termios_tcdrain, + METH_VARARGS, termios_tcdrain__doc__}, + {"tcflush", termios_tcflush, + METH_VARARGS, termios_tcflush__doc__}, + {"tcflow", termios_tcflow, + METH_VARARGS, termios_tcflow__doc__}, + {NULL, NULL} }; @@ -318,619 +318,619 @@ #endif static struct constant { - char *name; - long value; + char *name; + long value; } termios_constants[] = { - /* cfgetospeed(), cfsetospeed() constants */ - {"B0", B0}, - {"B50", B50}, - {"B75", B75}, - {"B110", B110}, - {"B134", B134}, - {"B150", B150}, - {"B200", B200}, - {"B300", B300}, - {"B600", B600}, - {"B1200", B1200}, - {"B1800", B1800}, - {"B2400", B2400}, - {"B4800", B4800}, - {"B9600", B9600}, - {"B19200", B19200}, - {"B38400", B38400}, + /* cfgetospeed(), cfsetospeed() constants */ + {"B0", B0}, + {"B50", B50}, + {"B75", B75}, + {"B110", B110}, + {"B134", B134}, + {"B150", B150}, + {"B200", B200}, + {"B300", B300}, + {"B600", B600}, + {"B1200", B1200}, + {"B1800", B1800}, + {"B2400", B2400}, + {"B4800", B4800}, + {"B9600", B9600}, + {"B19200", B19200}, + {"B38400", B38400}, #ifdef B57600 - {"B57600", B57600}, + {"B57600", B57600}, #endif #ifdef B115200 - {"B115200", B115200}, + {"B115200", B115200}, #endif #ifdef B230400 - {"B230400", B230400}, + {"B230400", B230400}, #endif #ifdef CBAUDEX - {"CBAUDEX", CBAUDEX}, + {"CBAUDEX", CBAUDEX}, #endif - /* tcsetattr() constants */ - {"TCSANOW", TCSANOW}, - {"TCSADRAIN", TCSADRAIN}, - {"TCSAFLUSH", TCSAFLUSH}, - - /* tcflush() constants */ - {"TCIFLUSH", TCIFLUSH}, - {"TCOFLUSH", TCOFLUSH}, - {"TCIOFLUSH", TCIOFLUSH}, - - /* tcflow() constants */ - {"TCOOFF", TCOOFF}, - {"TCOON", TCOON}, - {"TCIOFF", TCIOFF}, - {"TCION", TCION}, - - /* struct termios.c_iflag constants */ - {"IGNBRK", IGNBRK}, - {"BRKINT", BRKINT}, - {"IGNPAR", IGNPAR}, - {"PARMRK", PARMRK}, - {"INPCK", INPCK}, - {"ISTRIP", ISTRIP}, - {"INLCR", INLCR}, - {"IGNCR", IGNCR}, - {"ICRNL", ICRNL}, + /* tcsetattr() constants */ + {"TCSANOW", TCSANOW}, + {"TCSADRAIN", TCSADRAIN}, + {"TCSAFLUSH", TCSAFLUSH}, + + /* tcflush() constants */ + {"TCIFLUSH", TCIFLUSH}, + {"TCOFLUSH", TCOFLUSH}, + {"TCIOFLUSH", TCIOFLUSH}, + + /* tcflow() constants */ + {"TCOOFF", TCOOFF}, + {"TCOON", TCOON}, + {"TCIOFF", TCIOFF}, + {"TCION", TCION}, + + /* struct termios.c_iflag constants */ + {"IGNBRK", IGNBRK}, + {"BRKINT", BRKINT}, + {"IGNPAR", IGNPAR}, + {"PARMRK", PARMRK}, + {"INPCK", INPCK}, + {"ISTRIP", ISTRIP}, + {"INLCR", INLCR}, + {"IGNCR", IGNCR}, + {"ICRNL", ICRNL}, #ifdef IUCLC - {"IUCLC", IUCLC}, + {"IUCLC", IUCLC}, #endif - {"IXON", IXON}, - {"IXANY", IXANY}, - {"IXOFF", IXOFF}, + {"IXON", IXON}, + {"IXANY", IXANY}, + {"IXOFF", IXOFF}, #ifdef IMAXBEL - {"IMAXBEL", IMAXBEL}, + {"IMAXBEL", IMAXBEL}, #endif - /* struct termios.c_oflag constants */ - {"OPOST", OPOST}, + /* struct termios.c_oflag constants */ + {"OPOST", OPOST}, #ifdef OLCUC - {"OLCUC", OLCUC}, + {"OLCUC", OLCUC}, #endif #ifdef ONLCR - {"ONLCR", ONLCR}, + {"ONLCR", ONLCR}, #endif #ifdef OCRNL - {"OCRNL", OCRNL}, + {"OCRNL", OCRNL}, #endif #ifdef ONOCR - {"ONOCR", ONOCR}, + {"ONOCR", ONOCR}, #endif #ifdef ONLRET - {"ONLRET", ONLRET}, + {"ONLRET", ONLRET}, #endif #ifdef OFILL - {"OFILL", OFILL}, + {"OFILL", OFILL}, #endif #ifdef OFDEL - {"OFDEL", OFDEL}, + {"OFDEL", OFDEL}, #endif #ifdef NLDLY - {"NLDLY", NLDLY}, + {"NLDLY", NLDLY}, #endif #ifdef CRDLY - {"CRDLY", CRDLY}, + {"CRDLY", CRDLY}, #endif #ifdef TABDLY - {"TABDLY", TABDLY}, + {"TABDLY", TABDLY}, #endif #ifdef BSDLY - {"BSDLY", BSDLY}, + {"BSDLY", BSDLY}, #endif #ifdef VTDLY - {"VTDLY", VTDLY}, + {"VTDLY", VTDLY}, #endif #ifdef FFDLY - {"FFDLY", FFDLY}, + {"FFDLY", FFDLY}, #endif - /* struct termios.c_oflag-related values (delay mask) */ + /* struct termios.c_oflag-related values (delay mask) */ #ifdef NL0 - {"NL0", NL0}, + {"NL0", NL0}, #endif #ifdef NL1 - {"NL1", NL1}, + {"NL1", NL1}, #endif #ifdef CR0 - {"CR0", CR0}, + {"CR0", CR0}, #endif #ifdef CR1 - {"CR1", CR1}, + {"CR1", CR1}, #endif #ifdef CR2 - {"CR2", CR2}, + {"CR2", CR2}, #endif #ifdef CR3 - {"CR3", CR3}, + {"CR3", CR3}, #endif #ifdef TAB0 - {"TAB0", TAB0}, + {"TAB0", TAB0}, #endif #ifdef TAB1 - {"TAB1", TAB1}, + {"TAB1", TAB1}, #endif #ifdef TAB2 - {"TAB2", TAB2}, + {"TAB2", TAB2}, #endif #ifdef TAB3 - {"TAB3", TAB3}, + {"TAB3", TAB3}, #endif #ifdef XTABS - {"XTABS", XTABS}, + {"XTABS", XTABS}, #endif #ifdef BS0 - {"BS0", BS0}, + {"BS0", BS0}, #endif #ifdef BS1 - {"BS1", BS1}, + {"BS1", BS1}, #endif #ifdef VT0 - {"VT0", VT0}, + {"VT0", VT0}, #endif #ifdef VT1 - {"VT1", VT1}, + {"VT1", VT1}, #endif #ifdef FF0 - {"FF0", FF0}, + {"FF0", FF0}, #endif #ifdef FF1 - {"FF1", FF1}, + {"FF1", FF1}, #endif - /* struct termios.c_cflag constants */ - {"CSIZE", CSIZE}, - {"CSTOPB", CSTOPB}, - {"CREAD", CREAD}, - {"PARENB", PARENB}, - {"PARODD", PARODD}, - {"HUPCL", HUPCL}, - {"CLOCAL", CLOCAL}, + /* struct termios.c_cflag constants */ + {"CSIZE", CSIZE}, + {"CSTOPB", CSTOPB}, + {"CREAD", CREAD}, + {"PARENB", PARENB}, + {"PARODD", PARODD}, + {"HUPCL", HUPCL}, + {"CLOCAL", CLOCAL}, #ifdef CIBAUD - {"CIBAUD", CIBAUD}, + {"CIBAUD", CIBAUD}, #endif #ifdef CRTSCTS - {"CRTSCTS", (long)CRTSCTS}, + {"CRTSCTS", (long)CRTSCTS}, #endif - /* struct termios.c_cflag-related values (character size) */ - {"CS5", CS5}, - {"CS6", CS6}, - {"CS7", CS7}, - {"CS8", CS8}, - - /* struct termios.c_lflag constants */ - {"ISIG", ISIG}, - {"ICANON", ICANON}, + /* struct termios.c_cflag-related values (character size) */ + {"CS5", CS5}, + {"CS6", CS6}, + {"CS7", CS7}, + {"CS8", CS8}, + + /* struct termios.c_lflag constants */ + {"ISIG", ISIG}, + {"ICANON", ICANON}, #ifdef XCASE - {"XCASE", XCASE}, + {"XCASE", XCASE}, #endif - {"ECHO", ECHO}, - {"ECHOE", ECHOE}, - {"ECHOK", ECHOK}, - {"ECHONL", ECHONL}, + {"ECHO", ECHO}, + {"ECHOE", ECHOE}, + {"ECHOK", ECHOK}, + {"ECHONL", ECHONL}, #ifdef ECHOCTL - {"ECHOCTL", ECHOCTL}, + {"ECHOCTL", ECHOCTL}, #endif #ifdef ECHOPRT - {"ECHOPRT", ECHOPRT}, + {"ECHOPRT", ECHOPRT}, #endif #ifdef ECHOKE - {"ECHOKE", ECHOKE}, + {"ECHOKE", ECHOKE}, #endif #ifdef FLUSHO - {"FLUSHO", FLUSHO}, + {"FLUSHO", FLUSHO}, #endif - {"NOFLSH", NOFLSH}, - {"TOSTOP", TOSTOP}, + {"NOFLSH", NOFLSH}, + {"TOSTOP", TOSTOP}, #ifdef PENDIN - {"PENDIN", PENDIN}, + {"PENDIN", PENDIN}, #endif - {"IEXTEN", IEXTEN}, + {"IEXTEN", IEXTEN}, - /* indexes into the control chars array returned by tcgetattr() */ - {"VINTR", VINTR}, - {"VQUIT", VQUIT}, - {"VERASE", VERASE}, - {"VKILL", VKILL}, - {"VEOF", VEOF}, - {"VTIME", VTIME}, - {"VMIN", VMIN}, + /* indexes into the control chars array returned by tcgetattr() */ + {"VINTR", VINTR}, + {"VQUIT", VQUIT}, + {"VERASE", VERASE}, + {"VKILL", VKILL}, + {"VEOF", VEOF}, + {"VTIME", VTIME}, + {"VMIN", VMIN}, #ifdef VSWTC - /* The #defines above ensure that if either is defined, both are, - * but both may be omitted by the system headers. ;-( */ - {"VSWTC", VSWTC}, - {"VSWTCH", VSWTCH}, -#endif - {"VSTART", VSTART}, - {"VSTOP", VSTOP}, - {"VSUSP", VSUSP}, - {"VEOL", VEOL}, + /* The #defines above ensure that if either is defined, both are, + * but both may be omitted by the system headers. ;-( */ + {"VSWTC", VSWTC}, + {"VSWTCH", VSWTCH}, +#endif + {"VSTART", VSTART}, + {"VSTOP", VSTOP}, + {"VSUSP", VSUSP}, + {"VEOL", VEOL}, #ifdef VREPRINT - {"VREPRINT", VREPRINT}, + {"VREPRINT", VREPRINT}, #endif #ifdef VDISCARD - {"VDISCARD", VDISCARD}, + {"VDISCARD", VDISCARD}, #endif #ifdef VWERASE - {"VWERASE", VWERASE}, + {"VWERASE", VWERASE}, #endif #ifdef VLNEXT - {"VLNEXT", VLNEXT}, + {"VLNEXT", VLNEXT}, #endif #ifdef VEOL2 - {"VEOL2", VEOL2}, + {"VEOL2", VEOL2}, #endif #ifdef B460800 - {"B460800", B460800}, + {"B460800", B460800}, #endif #ifdef CBAUD - {"CBAUD", CBAUD}, + {"CBAUD", CBAUD}, #endif #ifdef CDEL - {"CDEL", CDEL}, + {"CDEL", CDEL}, #endif #ifdef CDSUSP - {"CDSUSP", CDSUSP}, + {"CDSUSP", CDSUSP}, #endif #ifdef CEOF - {"CEOF", CEOF}, + {"CEOF", CEOF}, #endif #ifdef CEOL - {"CEOL", CEOL}, + {"CEOL", CEOL}, #endif #ifdef CEOL2 - {"CEOL2", CEOL2}, + {"CEOL2", CEOL2}, #endif #ifdef CEOT - {"CEOT", CEOT}, + {"CEOT", CEOT}, #endif #ifdef CERASE - {"CERASE", CERASE}, + {"CERASE", CERASE}, #endif #ifdef CESC - {"CESC", CESC}, + {"CESC", CESC}, #endif #ifdef CFLUSH - {"CFLUSH", CFLUSH}, + {"CFLUSH", CFLUSH}, #endif #ifdef CINTR - {"CINTR", CINTR}, + {"CINTR", CINTR}, #endif #ifdef CKILL - {"CKILL", CKILL}, + {"CKILL", CKILL}, #endif #ifdef CLNEXT - {"CLNEXT", CLNEXT}, + {"CLNEXT", CLNEXT}, #endif #ifdef CNUL - {"CNUL", CNUL}, + {"CNUL", CNUL}, #endif #ifdef COMMON - {"COMMON", COMMON}, + {"COMMON", COMMON}, #endif #ifdef CQUIT - {"CQUIT", CQUIT}, + {"CQUIT", CQUIT}, #endif #ifdef CRPRNT - {"CRPRNT", CRPRNT}, + {"CRPRNT", CRPRNT}, #endif #ifdef CSTART - {"CSTART", CSTART}, + {"CSTART", CSTART}, #endif #ifdef CSTOP - {"CSTOP", CSTOP}, + {"CSTOP", CSTOP}, #endif #ifdef CSUSP - {"CSUSP", CSUSP}, + {"CSUSP", CSUSP}, #endif #ifdef CSWTCH - {"CSWTCH", CSWTCH}, + {"CSWTCH", CSWTCH}, #endif #ifdef CWERASE - {"CWERASE", CWERASE}, + {"CWERASE", CWERASE}, #endif #ifdef EXTA - {"EXTA", EXTA}, + {"EXTA", EXTA}, #endif #ifdef EXTB - {"EXTB", EXTB}, + {"EXTB", EXTB}, #endif #ifdef FIOASYNC - {"FIOASYNC", FIOASYNC}, + {"FIOASYNC", FIOASYNC}, #endif #ifdef FIOCLEX - {"FIOCLEX", FIOCLEX}, + {"FIOCLEX", FIOCLEX}, #endif #ifdef FIONBIO - {"FIONBIO", FIONBIO}, + {"FIONBIO", FIONBIO}, #endif #ifdef FIONCLEX - {"FIONCLEX", FIONCLEX}, + {"FIONCLEX", FIONCLEX}, #endif #ifdef FIONREAD - {"FIONREAD", FIONREAD}, + {"FIONREAD", FIONREAD}, #endif #ifdef IBSHIFT - {"IBSHIFT", IBSHIFT}, + {"IBSHIFT", IBSHIFT}, #endif #ifdef INIT_C_CC - {"INIT_C_CC", INIT_C_CC}, + {"INIT_C_CC", INIT_C_CC}, #endif #ifdef IOCSIZE_MASK - {"IOCSIZE_MASK", IOCSIZE_MASK}, + {"IOCSIZE_MASK", IOCSIZE_MASK}, #endif #ifdef IOCSIZE_SHIFT - {"IOCSIZE_SHIFT", IOCSIZE_SHIFT}, + {"IOCSIZE_SHIFT", IOCSIZE_SHIFT}, #endif #ifdef NCC - {"NCC", NCC}, + {"NCC", NCC}, #endif #ifdef NCCS - {"NCCS", NCCS}, + {"NCCS", NCCS}, #endif #ifdef NSWTCH - {"NSWTCH", NSWTCH}, + {"NSWTCH", NSWTCH}, #endif #ifdef N_MOUSE - {"N_MOUSE", N_MOUSE}, + {"N_MOUSE", N_MOUSE}, #endif #ifdef N_PPP - {"N_PPP", N_PPP}, + {"N_PPP", N_PPP}, #endif #ifdef N_SLIP - {"N_SLIP", N_SLIP}, + {"N_SLIP", N_SLIP}, #endif #ifdef N_STRIP - {"N_STRIP", N_STRIP}, + {"N_STRIP", N_STRIP}, #endif #ifdef N_TTY - {"N_TTY", N_TTY}, + {"N_TTY", N_TTY}, #endif #ifdef TCFLSH - {"TCFLSH", TCFLSH}, + {"TCFLSH", TCFLSH}, #endif #ifdef TCGETA - {"TCGETA", TCGETA}, + {"TCGETA", TCGETA}, #endif #ifdef TCGETS - {"TCGETS", TCGETS}, + {"TCGETS", TCGETS}, #endif #ifdef TCSBRK - {"TCSBRK", TCSBRK}, + {"TCSBRK", TCSBRK}, #endif #ifdef TCSBRKP - {"TCSBRKP", TCSBRKP}, + {"TCSBRKP", TCSBRKP}, #endif #ifdef TCSETA - {"TCSETA", TCSETA}, + {"TCSETA", TCSETA}, #endif #ifdef TCSETAF - {"TCSETAF", TCSETAF}, + {"TCSETAF", TCSETAF}, #endif #ifdef TCSETAW - {"TCSETAW", TCSETAW}, + {"TCSETAW", TCSETAW}, #endif #ifdef TCSETS - {"TCSETS", TCSETS}, + {"TCSETS", TCSETS}, #endif #ifdef TCSETSF - {"TCSETSF", TCSETSF}, + {"TCSETSF", TCSETSF}, #endif #ifdef TCSETSW - {"TCSETSW", TCSETSW}, + {"TCSETSW", TCSETSW}, #endif #ifdef TCXONC - {"TCXONC", TCXONC}, + {"TCXONC", TCXONC}, #endif #ifdef TIOCCONS - {"TIOCCONS", TIOCCONS}, + {"TIOCCONS", TIOCCONS}, #endif #ifdef TIOCEXCL - {"TIOCEXCL", TIOCEXCL}, + {"TIOCEXCL", TIOCEXCL}, #endif #ifdef TIOCGETD - {"TIOCGETD", TIOCGETD}, + {"TIOCGETD", TIOCGETD}, #endif #ifdef TIOCGICOUNT - {"TIOCGICOUNT", TIOCGICOUNT}, + {"TIOCGICOUNT", TIOCGICOUNT}, #endif #ifdef TIOCGLCKTRMIOS - {"TIOCGLCKTRMIOS", TIOCGLCKTRMIOS}, + {"TIOCGLCKTRMIOS", TIOCGLCKTRMIOS}, #endif #ifdef TIOCGPGRP - {"TIOCGPGRP", TIOCGPGRP}, + {"TIOCGPGRP", TIOCGPGRP}, #endif #ifdef TIOCGSERIAL - {"TIOCGSERIAL", TIOCGSERIAL}, + {"TIOCGSERIAL", TIOCGSERIAL}, #endif #ifdef TIOCGSOFTCAR - {"TIOCGSOFTCAR", TIOCGSOFTCAR}, + {"TIOCGSOFTCAR", TIOCGSOFTCAR}, #endif #ifdef TIOCGWINSZ - {"TIOCGWINSZ", TIOCGWINSZ}, + {"TIOCGWINSZ", TIOCGWINSZ}, #endif #ifdef TIOCINQ - {"TIOCINQ", TIOCINQ}, + {"TIOCINQ", TIOCINQ}, #endif #ifdef TIOCLINUX - {"TIOCLINUX", TIOCLINUX}, + {"TIOCLINUX", TIOCLINUX}, #endif #ifdef TIOCMBIC - {"TIOCMBIC", TIOCMBIC}, + {"TIOCMBIC", TIOCMBIC}, #endif #ifdef TIOCMBIS - {"TIOCMBIS", TIOCMBIS}, + {"TIOCMBIS", TIOCMBIS}, #endif #ifdef TIOCMGET - {"TIOCMGET", TIOCMGET}, + {"TIOCMGET", TIOCMGET}, #endif #ifdef TIOCMIWAIT - {"TIOCMIWAIT", TIOCMIWAIT}, + {"TIOCMIWAIT", TIOCMIWAIT}, #endif #ifdef TIOCMSET - {"TIOCMSET", TIOCMSET}, + {"TIOCMSET", TIOCMSET}, #endif #ifdef TIOCM_CAR - {"TIOCM_CAR", TIOCM_CAR}, + {"TIOCM_CAR", TIOCM_CAR}, #endif #ifdef TIOCM_CD - {"TIOCM_CD", TIOCM_CD}, + {"TIOCM_CD", TIOCM_CD}, #endif #ifdef TIOCM_CTS - {"TIOCM_CTS", TIOCM_CTS}, + {"TIOCM_CTS", TIOCM_CTS}, #endif #ifdef TIOCM_DSR - {"TIOCM_DSR", TIOCM_DSR}, + {"TIOCM_DSR", TIOCM_DSR}, #endif #ifdef TIOCM_DTR - {"TIOCM_DTR", TIOCM_DTR}, + {"TIOCM_DTR", TIOCM_DTR}, #endif #ifdef TIOCM_LE - {"TIOCM_LE", TIOCM_LE}, + {"TIOCM_LE", TIOCM_LE}, #endif #ifdef TIOCM_RI - {"TIOCM_RI", TIOCM_RI}, + {"TIOCM_RI", TIOCM_RI}, #endif #ifdef TIOCM_RNG - {"TIOCM_RNG", TIOCM_RNG}, + {"TIOCM_RNG", TIOCM_RNG}, #endif #ifdef TIOCM_RTS - {"TIOCM_RTS", TIOCM_RTS}, + {"TIOCM_RTS", TIOCM_RTS}, #endif #ifdef TIOCM_SR - {"TIOCM_SR", TIOCM_SR}, + {"TIOCM_SR", TIOCM_SR}, #endif #ifdef TIOCM_ST - {"TIOCM_ST", TIOCM_ST}, + {"TIOCM_ST", TIOCM_ST}, #endif #ifdef TIOCNOTTY - {"TIOCNOTTY", TIOCNOTTY}, + {"TIOCNOTTY", TIOCNOTTY}, #endif #ifdef TIOCNXCL - {"TIOCNXCL", TIOCNXCL}, + {"TIOCNXCL", TIOCNXCL}, #endif #ifdef TIOCOUTQ - {"TIOCOUTQ", TIOCOUTQ}, + {"TIOCOUTQ", TIOCOUTQ}, #endif #ifdef TIOCPKT - {"TIOCPKT", TIOCPKT}, + {"TIOCPKT", TIOCPKT}, #endif #ifdef TIOCPKT_DATA - {"TIOCPKT_DATA", TIOCPKT_DATA}, + {"TIOCPKT_DATA", TIOCPKT_DATA}, #endif #ifdef TIOCPKT_DOSTOP - {"TIOCPKT_DOSTOP", TIOCPKT_DOSTOP}, + {"TIOCPKT_DOSTOP", TIOCPKT_DOSTOP}, #endif #ifdef TIOCPKT_FLUSHREAD - {"TIOCPKT_FLUSHREAD", TIOCPKT_FLUSHREAD}, + {"TIOCPKT_FLUSHREAD", TIOCPKT_FLUSHREAD}, #endif #ifdef TIOCPKT_FLUSHWRITE - {"TIOCPKT_FLUSHWRITE", TIOCPKT_FLUSHWRITE}, + {"TIOCPKT_FLUSHWRITE", TIOCPKT_FLUSHWRITE}, #endif #ifdef TIOCPKT_NOSTOP - {"TIOCPKT_NOSTOP", TIOCPKT_NOSTOP}, + {"TIOCPKT_NOSTOP", TIOCPKT_NOSTOP}, #endif #ifdef TIOCPKT_START - {"TIOCPKT_START", TIOCPKT_START}, + {"TIOCPKT_START", TIOCPKT_START}, #endif #ifdef TIOCPKT_STOP - {"TIOCPKT_STOP", TIOCPKT_STOP}, + {"TIOCPKT_STOP", TIOCPKT_STOP}, #endif #ifdef TIOCSCTTY - {"TIOCSCTTY", TIOCSCTTY}, + {"TIOCSCTTY", TIOCSCTTY}, #endif #ifdef TIOCSERCONFIG - {"TIOCSERCONFIG", TIOCSERCONFIG}, + {"TIOCSERCONFIG", TIOCSERCONFIG}, #endif #ifdef TIOCSERGETLSR - {"TIOCSERGETLSR", TIOCSERGETLSR}, + {"TIOCSERGETLSR", TIOCSERGETLSR}, #endif #ifdef TIOCSERGETMULTI - {"TIOCSERGETMULTI", TIOCSERGETMULTI}, + {"TIOCSERGETMULTI", TIOCSERGETMULTI}, #endif #ifdef TIOCSERGSTRUCT - {"TIOCSERGSTRUCT", TIOCSERGSTRUCT}, + {"TIOCSERGSTRUCT", TIOCSERGSTRUCT}, #endif #ifdef TIOCSERGWILD - {"TIOCSERGWILD", TIOCSERGWILD}, + {"TIOCSERGWILD", TIOCSERGWILD}, #endif #ifdef TIOCSERSETMULTI - {"TIOCSERSETMULTI", TIOCSERSETMULTI}, + {"TIOCSERSETMULTI", TIOCSERSETMULTI}, #endif #ifdef TIOCSERSWILD - {"TIOCSERSWILD", TIOCSERSWILD}, + {"TIOCSERSWILD", TIOCSERSWILD}, #endif #ifdef TIOCSER_TEMT - {"TIOCSER_TEMT", TIOCSER_TEMT}, + {"TIOCSER_TEMT", TIOCSER_TEMT}, #endif #ifdef TIOCSETD - {"TIOCSETD", TIOCSETD}, + {"TIOCSETD", TIOCSETD}, #endif #ifdef TIOCSLCKTRMIOS - {"TIOCSLCKTRMIOS", TIOCSLCKTRMIOS}, + {"TIOCSLCKTRMIOS", TIOCSLCKTRMIOS}, #endif #ifdef TIOCSPGRP - {"TIOCSPGRP", TIOCSPGRP}, + {"TIOCSPGRP", TIOCSPGRP}, #endif #ifdef TIOCSSERIAL - {"TIOCSSERIAL", TIOCSSERIAL}, + {"TIOCSSERIAL", TIOCSSERIAL}, #endif #ifdef TIOCSSOFTCAR - {"TIOCSSOFTCAR", TIOCSSOFTCAR}, + {"TIOCSSOFTCAR", TIOCSSOFTCAR}, #endif #ifdef TIOCSTI - {"TIOCSTI", TIOCSTI}, + {"TIOCSTI", TIOCSTI}, #endif #ifdef TIOCSWINSZ - {"TIOCSWINSZ", TIOCSWINSZ}, + {"TIOCSWINSZ", TIOCSWINSZ}, #endif #ifdef TIOCTTYGSTRUCT - {"TIOCTTYGSTRUCT", TIOCTTYGSTRUCT}, + {"TIOCTTYGSTRUCT", TIOCTTYGSTRUCT}, #endif - /* sentinel */ - {NULL, 0} + /* sentinel */ + {NULL, 0} }; static struct PyModuleDef termiosmodule = { - PyModuleDef_HEAD_INIT, - "termios", - termios__doc__, - -1, - termios_methods, - NULL, - NULL, - NULL, - NULL + PyModuleDef_HEAD_INIT, + "termios", + termios__doc__, + -1, + termios_methods, + NULL, + NULL, + NULL, + NULL }; PyMODINIT_FUNC PyInit_termios(void) { - PyObject *m; - struct constant *constant = termios_constants; + PyObject *m; + struct constant *constant = termios_constants; - m = PyModule_Create(&termiosmodule); - if (m == NULL) - return NULL; - - if (TermiosError == NULL) { - TermiosError = PyErr_NewException("termios.error", NULL, NULL); - } - Py_INCREF(TermiosError); - PyModule_AddObject(m, "error", TermiosError); - - while (constant->name != NULL) { - PyModule_AddIntConstant(m, constant->name, constant->value); - ++constant; - } - return m; + m = PyModule_Create(&termiosmodule); + if (m == NULL) + return NULL; + + if (TermiosError == NULL) { + TermiosError = PyErr_NewException("termios.error", NULL, NULL); + } + Py_INCREF(TermiosError); + PyModule_AddObject(m, "error", TermiosError); + + while (constant->name != NULL) { + PyModule_AddIntConstant(m, constant->name, constant->value); + ++constant; + } + return m; } Modified: python/branches/release31-maint/Modules/testcapi_long.h ============================================================================== --- python/branches/release31-maint/Modules/testcapi_long.h (original) +++ python/branches/release31-maint/Modules/testcapi_long.h Sun May 9 18:14:21 2010 @@ -1,182 +1,182 @@ /* Poor-man's template. Macros used: - TESTNAME name of the test (like test_long_api_inner) - TYPENAME the signed type (like long) - F_S_TO_PY convert signed to pylong; TYPENAME -> PyObject* - F_PY_TO_S convert pylong to signed; PyObject* -> TYPENAME - F_U_TO_PY convert unsigned to pylong; unsigned TYPENAME -> PyObject* + TESTNAME name of the test (like test_long_api_inner) + TYPENAME the signed type (like long) + F_S_TO_PY convert signed to pylong; TYPENAME -> PyObject* + F_PY_TO_S convert pylong to signed; PyObject* -> TYPENAME + F_U_TO_PY convert unsigned to pylong; unsigned TYPENAME -> PyObject* F_PY_TO_U convert pylong to unsigned; PyObject* -> unsigned TYPENAME */ static PyObject * TESTNAME(PyObject *error(const char*)) { - const int NBITS = sizeof(TYPENAME) * 8; - unsigned TYPENAME base; - PyObject *pyresult; - int i; - - /* Note: This test lets PyObjects leak if an error is raised. Since - an error should never be raised, leaks are impossible . */ - - /* Test native -> PyLong -> native roundtrip identity. - * Generate all powers of 2, and test them and their negations, - * plus the numbers +-1 off from them. - */ - base = 1; - for (i = 0; - i < NBITS + 1; /* on last, base overflows to 0 */ - ++i, base <<= 1) - { - int j; - for (j = 0; j < 6; ++j) { - TYPENAME in, out; - unsigned TYPENAME uin, uout; - - /* For 0, 1, 2 use base; for 3, 4, 5 use -base */ - uin = j < 3 ? base - : (unsigned TYPENAME)(-(TYPENAME)base); - - /* For 0 & 3, subtract 1. - * For 1 & 4, leave alone. - * For 2 & 5, add 1. - */ - uin += (unsigned TYPENAME)(TYPENAME)(j % 3 - 1); - - pyresult = F_U_TO_PY(uin); - if (pyresult == NULL) - return error( - "unsigned unexpected null result"); - - uout = F_PY_TO_U(pyresult); - if (uout == (unsigned TYPENAME)-1 && PyErr_Occurred()) - return error( - "unsigned unexpected -1 result"); - if (uout != uin) - return error( - "unsigned output != input"); - UNBIND(pyresult); - - in = (TYPENAME)uin; - pyresult = F_S_TO_PY(in); - if (pyresult == NULL) - return error( - "signed unexpected null result"); - - out = F_PY_TO_S(pyresult); - if (out == (TYPENAME)-1 && PyErr_Occurred()) - return error( - "signed unexpected -1 result"); - if (out != in) - return error( - "signed output != input"); - UNBIND(pyresult); - } - } - - /* Overflow tests. The loop above ensured that all limit cases that - * should not overflow don't overflow, so all we need to do here is - * provoke one-over-the-limit cases (not exhaustive, but sharp). - */ - { - PyObject *one, *x, *y; - TYPENAME out; - unsigned TYPENAME uout; - - one = PyLong_FromLong(1); - if (one == NULL) - return error( - "unexpected NULL from PyLong_FromLong"); - - /* Unsigned complains about -1? */ - x = PyNumber_Negative(one); - if (x == NULL) - return error( - "unexpected NULL from PyNumber_Negative"); - - uout = F_PY_TO_U(x); - if (uout != (unsigned TYPENAME)-1 || !PyErr_Occurred()) - return error( - "PyLong_AsUnsignedXXX(-1) didn't complain"); - if (!PyErr_ExceptionMatches(PyExc_OverflowError)) - return error( - "PyLong_AsUnsignedXXX(-1) raised " - "something other than OverflowError"); - PyErr_Clear(); - UNBIND(x); - - /* Unsigned complains about 2**NBITS? */ - y = PyLong_FromLong((long)NBITS); - if (y == NULL) - return error( - "unexpected NULL from PyLong_FromLong"); - - x = PyNumber_Lshift(one, y); /* 1L << NBITS, == 2**NBITS */ - UNBIND(y); - if (x == NULL) - return error( - "unexpected NULL from PyNumber_Lshift"); - - uout = F_PY_TO_U(x); - if (uout != (unsigned TYPENAME)-1 || !PyErr_Occurred()) - return error( - "PyLong_AsUnsignedXXX(2**NBITS) didn't " - "complain"); - if (!PyErr_ExceptionMatches(PyExc_OverflowError)) - return error( - "PyLong_AsUnsignedXXX(2**NBITS) raised " - "something other than OverflowError"); - PyErr_Clear(); - - /* Signed complains about 2**(NBITS-1)? - x still has 2**NBITS. */ - y = PyNumber_Rshift(x, one); /* 2**(NBITS-1) */ - UNBIND(x); - if (y == NULL) - return error( - "unexpected NULL from PyNumber_Rshift"); - - out = F_PY_TO_S(y); - if (out != (TYPENAME)-1 || !PyErr_Occurred()) - return error( - "PyLong_AsXXX(2**(NBITS-1)) didn't " - "complain"); - if (!PyErr_ExceptionMatches(PyExc_OverflowError)) - return error( - "PyLong_AsXXX(2**(NBITS-1)) raised " - "something other than OverflowError"); - PyErr_Clear(); - - /* Signed complains about -2**(NBITS-1)-1?; - y still has 2**(NBITS-1). */ - x = PyNumber_Negative(y); /* -(2**(NBITS-1)) */ - UNBIND(y); - if (x == NULL) - return error( - "unexpected NULL from PyNumber_Negative"); - - y = PyNumber_Subtract(x, one); /* -(2**(NBITS-1))-1 */ - UNBIND(x); - if (y == NULL) - return error( - "unexpected NULL from PyNumber_Subtract"); - - out = F_PY_TO_S(y); - if (out != (TYPENAME)-1 || !PyErr_Occurred()) - return error( - "PyLong_AsXXX(-2**(NBITS-1)-1) didn't " - "complain"); - if (!PyErr_ExceptionMatches(PyExc_OverflowError)) - return error( - "PyLong_AsXXX(-2**(NBITS-1)-1) raised " - "something other than OverflowError"); - PyErr_Clear(); - UNBIND(y); - - Py_XDECREF(x); - Py_XDECREF(y); - Py_DECREF(one); - } + const int NBITS = sizeof(TYPENAME) * 8; + unsigned TYPENAME base; + PyObject *pyresult; + int i; + + /* Note: This test lets PyObjects leak if an error is raised. Since + an error should never be raised, leaks are impossible . */ + + /* Test native -> PyLong -> native roundtrip identity. + * Generate all powers of 2, and test them and their negations, + * plus the numbers +-1 off from them. + */ + base = 1; + for (i = 0; + i < NBITS + 1; /* on last, base overflows to 0 */ + ++i, base <<= 1) + { + int j; + for (j = 0; j < 6; ++j) { + TYPENAME in, out; + unsigned TYPENAME uin, uout; + + /* For 0, 1, 2 use base; for 3, 4, 5 use -base */ + uin = j < 3 ? base + : (unsigned TYPENAME)(-(TYPENAME)base); + + /* For 0 & 3, subtract 1. + * For 1 & 4, leave alone. + * For 2 & 5, add 1. + */ + uin += (unsigned TYPENAME)(TYPENAME)(j % 3 - 1); + + pyresult = F_U_TO_PY(uin); + if (pyresult == NULL) + return error( + "unsigned unexpected null result"); + + uout = F_PY_TO_U(pyresult); + if (uout == (unsigned TYPENAME)-1 && PyErr_Occurred()) + return error( + "unsigned unexpected -1 result"); + if (uout != uin) + return error( + "unsigned output != input"); + UNBIND(pyresult); + + in = (TYPENAME)uin; + pyresult = F_S_TO_PY(in); + if (pyresult == NULL) + return error( + "signed unexpected null result"); + + out = F_PY_TO_S(pyresult); + if (out == (TYPENAME)-1 && PyErr_Occurred()) + return error( + "signed unexpected -1 result"); + if (out != in) + return error( + "signed output != input"); + UNBIND(pyresult); + } + } + + /* Overflow tests. The loop above ensured that all limit cases that + * should not overflow don't overflow, so all we need to do here is + * provoke one-over-the-limit cases (not exhaustive, but sharp). + */ + { + PyObject *one, *x, *y; + TYPENAME out; + unsigned TYPENAME uout; + + one = PyLong_FromLong(1); + if (one == NULL) + return error( + "unexpected NULL from PyLong_FromLong"); + + /* Unsigned complains about -1? */ + x = PyNumber_Negative(one); + if (x == NULL) + return error( + "unexpected NULL from PyNumber_Negative"); + + uout = F_PY_TO_U(x); + if (uout != (unsigned TYPENAME)-1 || !PyErr_Occurred()) + return error( + "PyLong_AsUnsignedXXX(-1) didn't complain"); + if (!PyErr_ExceptionMatches(PyExc_OverflowError)) + return error( + "PyLong_AsUnsignedXXX(-1) raised " + "something other than OverflowError"); + PyErr_Clear(); + UNBIND(x); + + /* Unsigned complains about 2**NBITS? */ + y = PyLong_FromLong((long)NBITS); + if (y == NULL) + return error( + "unexpected NULL from PyLong_FromLong"); + + x = PyNumber_Lshift(one, y); /* 1L << NBITS, == 2**NBITS */ + UNBIND(y); + if (x == NULL) + return error( + "unexpected NULL from PyNumber_Lshift"); + + uout = F_PY_TO_U(x); + if (uout != (unsigned TYPENAME)-1 || !PyErr_Occurred()) + return error( + "PyLong_AsUnsignedXXX(2**NBITS) didn't " + "complain"); + if (!PyErr_ExceptionMatches(PyExc_OverflowError)) + return error( + "PyLong_AsUnsignedXXX(2**NBITS) raised " + "something other than OverflowError"); + PyErr_Clear(); + + /* Signed complains about 2**(NBITS-1)? + x still has 2**NBITS. */ + y = PyNumber_Rshift(x, one); /* 2**(NBITS-1) */ + UNBIND(x); + if (y == NULL) + return error( + "unexpected NULL from PyNumber_Rshift"); + + out = F_PY_TO_S(y); + if (out != (TYPENAME)-1 || !PyErr_Occurred()) + return error( + "PyLong_AsXXX(2**(NBITS-1)) didn't " + "complain"); + if (!PyErr_ExceptionMatches(PyExc_OverflowError)) + return error( + "PyLong_AsXXX(2**(NBITS-1)) raised " + "something other than OverflowError"); + PyErr_Clear(); + + /* Signed complains about -2**(NBITS-1)-1?; + y still has 2**(NBITS-1). */ + x = PyNumber_Negative(y); /* -(2**(NBITS-1)) */ + UNBIND(y); + if (x == NULL) + return error( + "unexpected NULL from PyNumber_Negative"); + + y = PyNumber_Subtract(x, one); /* -(2**(NBITS-1))-1 */ + UNBIND(x); + if (y == NULL) + return error( + "unexpected NULL from PyNumber_Subtract"); + + out = F_PY_TO_S(y); + if (out != (TYPENAME)-1 || !PyErr_Occurred()) + return error( + "PyLong_AsXXX(-2**(NBITS-1)-1) didn't " + "complain"); + if (!PyErr_ExceptionMatches(PyExc_OverflowError)) + return error( + "PyLong_AsXXX(-2**(NBITS-1)-1) raised " + "something other than OverflowError"); + PyErr_Clear(); + UNBIND(y); + + Py_XDECREF(x); + Py_XDECREF(y); + Py_DECREF(one); + } - Py_INCREF(Py_None); - return Py_None; + Py_INCREF(Py_None); + return Py_None; } Modified: python/branches/release31-maint/Modules/timemodule.c ============================================================================== --- python/branches/release31-maint/Modules/timemodule.c (original) +++ python/branches/release31-maint/Modules/timemodule.c Sun May 9 18:14:21 2010 @@ -48,12 +48,12 @@ static HANDLE hInterruptEvent = NULL; static BOOL WINAPI PyCtrlHandler(DWORD dwCtrlType) { - SetEvent(hInterruptEvent); - /* allow other default handlers to be called. - Default Python handler will setup the - KeyboardInterrupt exception. - */ - return FALSE; + SetEvent(hInterruptEvent); + /* allow other default handlers to be called. + Default Python handler will setup the + KeyboardInterrupt exception. + */ + return FALSE; } static long main_thread; @@ -94,38 +94,38 @@ time_t _PyTime_DoubleToTimet(double x) { - time_t result; - double diff; + time_t result; + double diff; - result = (time_t)x; - /* How much info did we lose? time_t may be an integral or - * floating type, and we don't know which. If it's integral, - * we don't know whether C truncates, rounds, returns the floor, - * etc. If we lost a second or more, the C rounding is - * unreasonable, or the input just doesn't fit in a time_t; - * call it an error regardless. Note that the original cast to - * time_t can cause a C error too, but nothing we can do to - * worm around that. - */ - diff = x - (double)result; - if (diff <= -1.0 || diff >= 1.0) { - PyErr_SetString(PyExc_ValueError, - "timestamp out of range for platform time_t"); - result = (time_t)-1; - } - return result; + result = (time_t)x; + /* How much info did we lose? time_t may be an integral or + * floating type, and we don't know which. If it's integral, + * we don't know whether C truncates, rounds, returns the floor, + * etc. If we lost a second or more, the C rounding is + * unreasonable, or the input just doesn't fit in a time_t; + * call it an error regardless. Note that the original cast to + * time_t can cause a C error too, but nothing we can do to + * worm around that. + */ + diff = x - (double)result; + if (diff <= -1.0 || diff >= 1.0) { + PyErr_SetString(PyExc_ValueError, + "timestamp out of range for platform time_t"); + result = (time_t)-1; + } + return result; } static PyObject * time_time(PyObject *self, PyObject *unused) { - double secs; - secs = floattime(); - if (secs == 0.0) { - PyErr_SetFromErrno(PyExc_IOError); - return NULL; - } - return PyFloat_FromDouble(secs); + double secs; + secs = floattime(); + if (secs == 0.0) { + PyErr_SetFromErrno(PyExc_IOError); + return NULL; + } + return PyFloat_FromDouble(secs); } PyDoc_STRVAR(time_doc, @@ -147,7 +147,7 @@ static PyObject * time_clock(PyObject *self, PyObject *unused) { - return PyFloat_FromDouble(((double)clock()) / CLOCKS_PER_SEC); + return PyFloat_FromDouble(((double)clock()) / CLOCKS_PER_SEC); } #endif /* HAVE_CLOCK */ @@ -156,25 +156,25 @@ static PyObject * time_clock(PyObject *self, PyObject *unused) { - static LARGE_INTEGER ctrStart; - static double divisor = 0.0; - LARGE_INTEGER now; - double diff; - - if (divisor == 0.0) { - LARGE_INTEGER freq; - QueryPerformanceCounter(&ctrStart); - if (!QueryPerformanceFrequency(&freq) || freq.QuadPart == 0) { - /* Unlikely to happen - this works on all intel - machines at least! Revert to clock() */ - return PyFloat_FromDouble(((double)clock()) / - CLOCKS_PER_SEC); - } - divisor = (double)freq.QuadPart; - } - QueryPerformanceCounter(&now); - diff = (double)(now.QuadPart - ctrStart.QuadPart); - return PyFloat_FromDouble(diff / divisor); + static LARGE_INTEGER ctrStart; + static double divisor = 0.0; + LARGE_INTEGER now; + double diff; + + if (divisor == 0.0) { + LARGE_INTEGER freq; + QueryPerformanceCounter(&ctrStart); + if (!QueryPerformanceFrequency(&freq) || freq.QuadPart == 0) { + /* Unlikely to happen - this works on all intel + machines at least! Revert to clock() */ + return PyFloat_FromDouble(((double)clock()) / + CLOCKS_PER_SEC); + } + divisor = (double)freq.QuadPart; + } + QueryPerformanceCounter(&now); + diff = (double)(now.QuadPart - ctrStart.QuadPart); + return PyFloat_FromDouble(diff / divisor); } #define HAVE_CLOCK /* So it gets included in the methods */ @@ -192,13 +192,13 @@ static PyObject * time_sleep(PyObject *self, PyObject *args) { - double secs; - if (!PyArg_ParseTuple(args, "d:sleep", &secs)) - return NULL; - if (floatsleep(secs) != 0) - return NULL; - Py_INCREF(Py_None); - return Py_None; + double secs; + if (!PyArg_ParseTuple(args, "d:sleep", &secs)) + return NULL; + if (floatsleep(secs) != 0) + return NULL; + Py_INCREF(Py_None); + return Py_None; } PyDoc_STRVAR(sleep_doc, @@ -208,23 +208,23 @@ a floating point number for subsecond precision."); static PyStructSequence_Field struct_time_type_fields[] = { - {"tm_year", NULL}, - {"tm_mon", NULL}, - {"tm_mday", NULL}, - {"tm_hour", NULL}, - {"tm_min", NULL}, - {"tm_sec", NULL}, - {"tm_wday", NULL}, - {"tm_yday", NULL}, - {"tm_isdst", NULL}, - {0} + {"tm_year", NULL}, + {"tm_mon", NULL}, + {"tm_mday", NULL}, + {"tm_hour", NULL}, + {"tm_min", NULL}, + {"tm_sec", NULL}, + {"tm_wday", NULL}, + {"tm_yday", NULL}, + {"tm_isdst", NULL}, + {0} }; static PyStructSequence_Desc struct_time_type_desc = { - "time.struct_time", - NULL, - struct_time_type_fields, - 9, + "time.struct_time", + NULL, + struct_time_type_fields, + 9, }; static int initialized; @@ -233,71 +233,71 @@ static PyObject * tmtotuple(struct tm *p) { - PyObject *v = PyStructSequence_New(&StructTimeType); - if (v == NULL) - return NULL; + PyObject *v = PyStructSequence_New(&StructTimeType); + if (v == NULL) + return NULL; #define SET(i,val) PyStructSequence_SET_ITEM(v, i, PyLong_FromLong((long) val)) - SET(0, p->tm_year + 1900); - SET(1, p->tm_mon + 1); /* Want January == 1 */ - SET(2, p->tm_mday); - SET(3, p->tm_hour); - SET(4, p->tm_min); - SET(5, p->tm_sec); - SET(6, (p->tm_wday + 6) % 7); /* Want Monday == 0 */ - SET(7, p->tm_yday + 1); /* Want January, 1 == 1 */ - SET(8, p->tm_isdst); + SET(0, p->tm_year + 1900); + SET(1, p->tm_mon + 1); /* Want January == 1 */ + SET(2, p->tm_mday); + SET(3, p->tm_hour); + SET(4, p->tm_min); + SET(5, p->tm_sec); + SET(6, (p->tm_wday + 6) % 7); /* Want Monday == 0 */ + SET(7, p->tm_yday + 1); /* Want January, 1 == 1 */ + SET(8, p->tm_isdst); #undef SET - if (PyErr_Occurred()) { - Py_XDECREF(v); - return NULL; - } + if (PyErr_Occurred()) { + Py_XDECREF(v); + return NULL; + } - return v; + return v; } static PyObject * structtime_totuple(PyObject *t) { - PyObject *x = NULL; - unsigned int i; - PyObject *v = PyTuple_New(9); - if (v == NULL) - return NULL; - - for (i=0; i<9; i++) { - x = PyStructSequence_GET_ITEM(t, i); - Py_INCREF(x); - PyTuple_SET_ITEM(v, i, x); - } - - if (PyErr_Occurred()) { - Py_XDECREF(v); - return NULL; - } + PyObject *x = NULL; + unsigned int i; + PyObject *v = PyTuple_New(9); + if (v == NULL) + return NULL; + + for (i=0; i<9; i++) { + x = PyStructSequence_GET_ITEM(t, i); + Py_INCREF(x); + PyTuple_SET_ITEM(v, i, x); + } - return v; + if (PyErr_Occurred()) { + Py_XDECREF(v); + return NULL; + } + + return v; } static PyObject * time_convert(double when, struct tm * (*function)(const time_t *)) { - struct tm *p; - time_t whent = _PyTime_DoubleToTimet(when); + struct tm *p; + time_t whent = _PyTime_DoubleToTimet(when); - if (whent == (time_t)-1 && PyErr_Occurred()) - return NULL; - errno = 0; - p = function(&whent); - if (p == NULL) { + if (whent == (time_t)-1 && PyErr_Occurred()) + return NULL; + errno = 0; + p = function(&whent); + if (p == NULL) { #ifdef EINVAL - if (errno == 0) - errno = EINVAL; + if (errno == 0) + errno = EINVAL; #endif - return PyErr_SetFromErrno(PyExc_ValueError); - } - return tmtotuple(p); + return PyErr_SetFromErrno(PyExc_ValueError); + } + return tmtotuple(p); } /* Parse arg tuple that can contain an optional float-or-None value; @@ -307,28 +307,28 @@ static int parse_time_double_args(PyObject *args, char *format, double *pwhen) { - PyObject *ot = NULL; + PyObject *ot = NULL; - if (!PyArg_ParseTuple(args, format, &ot)) - return 0; - if (ot == NULL || ot == Py_None) - *pwhen = floattime(); - else { - double when = PyFloat_AsDouble(ot); - if (PyErr_Occurred()) - return 0; - *pwhen = when; - } - return 1; + if (!PyArg_ParseTuple(args, format, &ot)) + return 0; + if (ot == NULL || ot == Py_None) + *pwhen = floattime(); + else { + double when = PyFloat_AsDouble(ot); + if (PyErr_Occurred()) + return 0; + *pwhen = when; + } + return 1; } static PyObject * time_gmtime(PyObject *self, PyObject *args) { - double when; - if (!parse_time_double_args(args, "|O:gmtime", &when)) - return NULL; - return time_convert(when, gmtime); + double when; + if (!parse_time_double_args(args, "|O:gmtime", &when)) + return NULL; + return time_convert(when, gmtime); } PyDoc_STRVAR(gmtime_doc, @@ -341,15 +341,15 @@ static PyObject * time_localtime(PyObject *self, PyObject *args) { - double when; - if (!parse_time_double_args(args, "|O:localtime", &when)) - return NULL; - return time_convert(when, localtime); + double when; + if (!parse_time_double_args(args, "|O:localtime", &when)) + return NULL; + return time_convert(when, localtime); } PyDoc_STRVAR(localtime_doc, "localtime([seconds]) -> (tm_year,tm_mon,tm_mday,tm_hour,tm_min,\n\ - tm_sec,tm_wday,tm_yday,tm_isdst)\n\ + tm_sec,tm_wday,tm_yday,tm_isdst)\n\ \n\ Convert seconds since the Epoch to a time tuple expressing local time.\n\ When 'seconds' is not passed in, convert the current time instead."); @@ -357,63 +357,63 @@ static int gettmarg(PyObject *args, struct tm *p) { - int y; - PyObject *t = NULL; + int y; + PyObject *t = NULL; - memset((void *) p, '\0', sizeof(struct tm)); + memset((void *) p, '\0', sizeof(struct tm)); - if (PyTuple_Check(args)) { - t = args; - Py_INCREF(t); - } - else if (Py_TYPE(args) == &StructTimeType) { - t = structtime_totuple(args); - } - else { - PyErr_SetString(PyExc_TypeError, - "Tuple or struct_time argument required"); - return 0; - } - - if (t == NULL || !PyArg_ParseTuple(t, "iiiiiiiii", - &y, - &p->tm_mon, - &p->tm_mday, - &p->tm_hour, - &p->tm_min, - &p->tm_sec, - &p->tm_wday, - &p->tm_yday, - &p->tm_isdst)) { - Py_XDECREF(t); - return 0; - } - Py_DECREF(t); - - if (y < 1900) { - PyObject *accept = PyDict_GetItemString(moddict, - "accept2dyear"); - if (accept == NULL || !PyLong_CheckExact(accept) || - !PyObject_IsTrue(accept)) { - PyErr_SetString(PyExc_ValueError, - "year >= 1900 required"); - return 0; - } - if (69 <= y && y <= 99) - y += 1900; - else if (0 <= y && y <= 68) - y += 2000; - else { - PyErr_SetString(PyExc_ValueError, - "year out of range"); - return 0; - } - } - p->tm_year = y - 1900; - p->tm_mon--; - p->tm_wday = (p->tm_wday + 1) % 7; - p->tm_yday--; - return 1; + if (PyTuple_Check(args)) { + t = args; + Py_INCREF(t); + } + else if (Py_TYPE(args) == &StructTimeType) { + t = structtime_totuple(args); + } + else { + PyErr_SetString(PyExc_TypeError, + "Tuple or struct_time argument required"); + return 0; + } + + if (t == NULL || !PyArg_ParseTuple(t, "iiiiiiiii", + &y, + &p->tm_mon, + &p->tm_mday, + &p->tm_hour, + &p->tm_min, + &p->tm_sec, + &p->tm_wday, + &p->tm_yday, + &p->tm_isdst)) { + Py_XDECREF(t); + return 0; + } + Py_DECREF(t); + + if (y < 1900) { + PyObject *accept = PyDict_GetItemString(moddict, + "accept2dyear"); + if (accept == NULL || !PyLong_CheckExact(accept) || + !PyObject_IsTrue(accept)) { + PyErr_SetString(PyExc_ValueError, + "year >= 1900 required"); + return 0; + } + if (69 <= y && y <= 99) + y += 1900; + else if (0 <= y && y <= 68) + y += 2000; + else { + PyErr_SetString(PyExc_ValueError, + "year out of range"); + return 0; + } + } + p->tm_year = y - 1900; + p->tm_mon--; + p->tm_wday = (p->tm_wday + 1) % 7; + p->tm_yday--; + return 1; } #ifdef HAVE_STRFTIME @@ -430,172 +430,172 @@ static PyObject * time_strftime(PyObject *self, PyObject *args) { - PyObject *tup = NULL; - struct tm buf; - const time_char *fmt; - PyObject *format, *tmpfmt; - size_t fmtlen, buflen; - time_char *outbuf = 0; - size_t i; - - memset((void *) &buf, '\0', sizeof(buf)); - - /* Will always expect a unicode string to be passed as format. - Given that there's no str type anymore in py3k this seems safe. - */ - if (!PyArg_ParseTuple(args, "U|O:strftime", &format, &tup)) - return NULL; - - if (tup == NULL) { - time_t tt = time(NULL); - buf = *localtime(&tt); - } else if (!gettmarg(tup, &buf)) - return NULL; - - /* Checks added to make sure strftime() does not crash Python by - indexing blindly into some array for a textual representation - by some bad index (fixes bug #897625). - - Also support values of zero from Python code for arguments in which - that is out of range by forcing that value to the lowest value that - is valid (fixed bug #1520914). - - Valid ranges based on what is allowed in struct tm: - - - tm_year: [0, max(int)] (1) - - tm_mon: [0, 11] (2) - - tm_mday: [1, 31] - - tm_hour: [0, 23] - - tm_min: [0, 59] - - tm_sec: [0, 60] - - tm_wday: [0, 6] (1) - - tm_yday: [0, 365] (2) - - tm_isdst: [-max(int), max(int)] - - (1) gettmarg() handles bounds-checking. - (2) Python's acceptable range is one greater than the range in C, - thus need to check against automatic decrement by gettmarg(). - */ - if (buf.tm_mon == -1) - buf.tm_mon = 0; - else if (buf.tm_mon < 0 || buf.tm_mon > 11) { - PyErr_SetString(PyExc_ValueError, "month out of range"); - return NULL; - } - if (buf.tm_mday == 0) - buf.tm_mday = 1; - else if (buf.tm_mday < 0 || buf.tm_mday > 31) { - PyErr_SetString(PyExc_ValueError, "day of month out of range"); - return NULL; - } - if (buf.tm_hour < 0 || buf.tm_hour > 23) { - PyErr_SetString(PyExc_ValueError, "hour out of range"); - return NULL; - } - if (buf.tm_min < 0 || buf.tm_min > 59) { - PyErr_SetString(PyExc_ValueError, "minute out of range"); - return NULL; - } - if (buf.tm_sec < 0 || buf.tm_sec > 61) { - PyErr_SetString(PyExc_ValueError, "seconds out of range"); - return NULL; - } - /* tm_wday does not need checking of its upper-bound since taking - ``% 7`` in gettmarg() automatically restricts the range. */ - if (buf.tm_wday < 0) { - PyErr_SetString(PyExc_ValueError, "day of week out of range"); - return NULL; - } - if (buf.tm_yday == -1) - buf.tm_yday = 0; - else if (buf.tm_yday < 0 || buf.tm_yday > 365) { - PyErr_SetString(PyExc_ValueError, "day of year out of range"); - return NULL; - } - if (buf.tm_isdst < -1 || buf.tm_isdst > 1) { - PyErr_SetString(PyExc_ValueError, - "daylight savings flag out of range"); - return NULL; - } + PyObject *tup = NULL; + struct tm buf; + const time_char *fmt; + PyObject *format, *tmpfmt; + size_t fmtlen, buflen; + time_char *outbuf = 0; + size_t i; + + memset((void *) &buf, '\0', sizeof(buf)); + + /* Will always expect a unicode string to be passed as format. + Given that there's no str type anymore in py3k this seems safe. + */ + if (!PyArg_ParseTuple(args, "U|O:strftime", &format, &tup)) + return NULL; + + if (tup == NULL) { + time_t tt = time(NULL); + buf = *localtime(&tt); + } else if (!gettmarg(tup, &buf)) + return NULL; + + /* Checks added to make sure strftime() does not crash Python by + indexing blindly into some array for a textual representation + by some bad index (fixes bug #897625). + + Also support values of zero from Python code for arguments in which + that is out of range by forcing that value to the lowest value that + is valid (fixed bug #1520914). + + Valid ranges based on what is allowed in struct tm: + + - tm_year: [0, max(int)] (1) + - tm_mon: [0, 11] (2) + - tm_mday: [1, 31] + - tm_hour: [0, 23] + - tm_min: [0, 59] + - tm_sec: [0, 60] + - tm_wday: [0, 6] (1) + - tm_yday: [0, 365] (2) + - tm_isdst: [-max(int), max(int)] + + (1) gettmarg() handles bounds-checking. + (2) Python's acceptable range is one greater than the range in C, + thus need to check against automatic decrement by gettmarg(). + */ + if (buf.tm_mon == -1) + buf.tm_mon = 0; + else if (buf.tm_mon < 0 || buf.tm_mon > 11) { + PyErr_SetString(PyExc_ValueError, "month out of range"); + return NULL; + } + if (buf.tm_mday == 0) + buf.tm_mday = 1; + else if (buf.tm_mday < 0 || buf.tm_mday > 31) { + PyErr_SetString(PyExc_ValueError, "day of month out of range"); + return NULL; + } + if (buf.tm_hour < 0 || buf.tm_hour > 23) { + PyErr_SetString(PyExc_ValueError, "hour out of range"); + return NULL; + } + if (buf.tm_min < 0 || buf.tm_min > 59) { + PyErr_SetString(PyExc_ValueError, "minute out of range"); + return NULL; + } + if (buf.tm_sec < 0 || buf.tm_sec > 61) { + PyErr_SetString(PyExc_ValueError, "seconds out of range"); + return NULL; + } + /* tm_wday does not need checking of its upper-bound since taking + ``% 7`` in gettmarg() automatically restricts the range. */ + if (buf.tm_wday < 0) { + PyErr_SetString(PyExc_ValueError, "day of week out of range"); + return NULL; + } + if (buf.tm_yday == -1) + buf.tm_yday = 0; + else if (buf.tm_yday < 0 || buf.tm_yday > 365) { + PyErr_SetString(PyExc_ValueError, "day of year out of range"); + return NULL; + } + if (buf.tm_isdst < -1 || buf.tm_isdst > 1) { + PyErr_SetString(PyExc_ValueError, + "daylight savings flag out of range"); + return NULL; + } #ifdef HAVE_WCSFTIME - tmpfmt = PyBytes_FromStringAndSize(NULL, - sizeof(wchar_t) * (PyUnicode_GetSize(format)+1)); - if (!tmpfmt) - return NULL; - /* This assumes that PyUnicode_AsWideChar doesn't do any UTF-16 - expansion. */ - if (PyUnicode_AsWideChar((PyUnicodeObject*)format, - (wchar_t*)PyBytes_AS_STRING(tmpfmt), - PyUnicode_GetSize(format)+1) == (size_t)-1) - /* This shouldn't fail. */ - Py_FatalError("PyUnicode_AsWideChar failed"); - format = tmpfmt; - fmt = (wchar_t*)PyBytes_AS_STRING(format); + tmpfmt = PyBytes_FromStringAndSize(NULL, + sizeof(wchar_t) * (PyUnicode_GetSize(format)+1)); + if (!tmpfmt) + return NULL; + /* This assumes that PyUnicode_AsWideChar doesn't do any UTF-16 + expansion. */ + if (PyUnicode_AsWideChar((PyUnicodeObject*)format, + (wchar_t*)PyBytes_AS_STRING(tmpfmt), + PyUnicode_GetSize(format)+1) == (size_t)-1) + /* This shouldn't fail. */ + Py_FatalError("PyUnicode_AsWideChar failed"); + format = tmpfmt; + fmt = (wchar_t*)PyBytes_AS_STRING(format); #else - /* Convert the unicode string to an ascii one */ - format = PyUnicode_AsEncodedString(format, TZNAME_ENCODING, NULL); - if (format == NULL) - return NULL; - fmt = PyBytes_AS_STRING(format); + /* Convert the unicode string to an ascii one */ + format = PyUnicode_AsEncodedString(format, TZNAME_ENCODING, NULL); + if (format == NULL) + return NULL; + fmt = PyBytes_AS_STRING(format); #endif #if defined(MS_WINDOWS) && defined(HAVE_WCSFTIME) - /* check that the format string contains only valid directives */ - for(outbuf = wcschr(fmt, L'%'); - outbuf != NULL; - outbuf = wcschr(outbuf+2, L'%')) - { - if (outbuf[1]=='#') - ++outbuf; /* not documented by python, */ - if (outbuf[1]=='\0' || - !wcschr(L"aAbBcdfHIjmMpSUwWxXyYzZ%", outbuf[1])) - { - PyErr_SetString(PyExc_ValueError, "Invalid format string"); - return 0; - } - } + /* check that the format string contains only valid directives */ + for(outbuf = wcschr(fmt, L'%'); + outbuf != NULL; + outbuf = wcschr(outbuf+2, L'%')) + { + if (outbuf[1]=='#') + ++outbuf; /* not documented by python, */ + if (outbuf[1]=='\0' || + !wcschr(L"aAbBcdfHIjmMpSUwWxXyYzZ%", outbuf[1])) + { + PyErr_SetString(PyExc_ValueError, "Invalid format string"); + return 0; + } + } #endif - fmtlen = time_strlen(fmt); + fmtlen = time_strlen(fmt); - /* I hate these functions that presume you know how big the output - * will be ahead of time... - */ - for (i = 1024; ; i += i) { - outbuf = (time_char *)PyMem_Malloc(i*sizeof(time_char)); - if (outbuf == NULL) { - Py_DECREF(format); - return PyErr_NoMemory(); - } - buflen = format_time(outbuf, i, fmt, &buf); - if (buflen > 0 || i >= 256 * fmtlen) { - /* If the buffer is 256 times as long as the format, - it's probably not failing for lack of room! - More likely, the format yields an empty result, - e.g. an empty format, or %Z when the timezone - is unknown. */ - PyObject *ret; + /* I hate these functions that presume you know how big the output + * will be ahead of time... + */ + for (i = 1024; ; i += i) { + outbuf = (time_char *)PyMem_Malloc(i*sizeof(time_char)); + if (outbuf == NULL) { + Py_DECREF(format); + return PyErr_NoMemory(); + } + buflen = format_time(outbuf, i, fmt, &buf); + if (buflen > 0 || i >= 256 * fmtlen) { + /* If the buffer is 256 times as long as the format, + it's probably not failing for lack of room! + More likely, the format yields an empty result, + e.g. an empty format, or %Z when the timezone + is unknown. */ + PyObject *ret; #ifdef HAVE_WCSFTIME - ret = PyUnicode_FromWideChar(outbuf, buflen); + ret = PyUnicode_FromWideChar(outbuf, buflen); #else - ret = PyUnicode_Decode(outbuf, buflen, - TZNAME_ENCODING, NULL); + ret = PyUnicode_Decode(outbuf, buflen, + TZNAME_ENCODING, NULL); #endif - PyMem_Free(outbuf); - Py_DECREF(format); - return ret; - } - PyMem_Free(outbuf); + PyMem_Free(outbuf); + Py_DECREF(format); + return ret; + } + PyMem_Free(outbuf); #if defined _MSC_VER && _MSC_VER >= 1400 && defined(__STDC_SECURE_LIB__) - /* VisualStudio .NET 2005 does this properly */ - if (buflen == 0 && errno == EINVAL) { - PyErr_SetString(PyExc_ValueError, "Invalid format string"); - Py_DECREF(format); - return 0; - } + /* VisualStudio .NET 2005 does this properly */ + if (buflen == 0 && errno == EINVAL) { + PyErr_SetString(PyExc_ValueError, "Invalid format string"); + Py_DECREF(format); + return 0; + } #endif - } + } } #undef time_char @@ -616,7 +616,7 @@ PyObject *strptime_result; if (!strptime_module) - return NULL; + return NULL; strptime_result = PyObject_CallMethod(strptime_module, "_strptime_time", "O", args); Py_DECREF(strptime_module); return strptime_result; @@ -632,20 +632,20 @@ static PyObject * time_asctime(PyObject *self, PyObject *args) { - PyObject *tup = NULL; - struct tm buf; - char *p; - if (!PyArg_UnpackTuple(args, "asctime", 0, 1, &tup)) - return NULL; - if (tup == NULL) { - time_t tt = time(NULL); - buf = *localtime(&tt); - } else if (!gettmarg(tup, &buf)) - return NULL; - p = asctime(&buf); - if (p[24] == '\n') - p[24] = '\0'; - return PyUnicode_FromString(p); + PyObject *tup = NULL; + struct tm buf; + char *p; + if (!PyArg_UnpackTuple(args, "asctime", 0, 1, &tup)) + return NULL; + if (tup == NULL) { + time_t tt = time(NULL); + buf = *localtime(&tt); + } else if (!gettmarg(tup, &buf)) + return NULL; + p = asctime(&buf); + if (p[24] == '\n') + p[24] = '\0'; + return PyUnicode_FromString(p); } PyDoc_STRVAR(asctime_doc, @@ -658,30 +658,30 @@ static PyObject * time_ctime(PyObject *self, PyObject *args) { - PyObject *ot = NULL; - time_t tt; - char *p; - - if (!PyArg_UnpackTuple(args, "ctime", 0, 1, &ot)) - return NULL; - if (ot == NULL || ot == Py_None) - tt = time(NULL); - else { - double dt = PyFloat_AsDouble(ot); - if (PyErr_Occurred()) - return NULL; - tt = _PyTime_DoubleToTimet(dt); - if (tt == (time_t)-1 && PyErr_Occurred()) - return NULL; - } - p = ctime(&tt); - if (p == NULL) { - PyErr_SetString(PyExc_ValueError, "unconvertible time"); - return NULL; - } - if (p[24] == '\n') - p[24] = '\0'; - return PyUnicode_FromString(p); + PyObject *ot = NULL; + time_t tt; + char *p; + + if (!PyArg_UnpackTuple(args, "ctime", 0, 1, &ot)) + return NULL; + if (ot == NULL || ot == Py_None) + tt = time(NULL); + else { + double dt = PyFloat_AsDouble(ot); + if (PyErr_Occurred()) + return NULL; + tt = _PyTime_DoubleToTimet(dt); + if (tt == (time_t)-1 && PyErr_Occurred()) + return NULL; + } + p = ctime(&tt); + if (p == NULL) { + PyErr_SetString(PyExc_ValueError, "unconvertible time"); + return NULL; + } + if (p[24] == '\n') + p[24] = '\0'; + return PyUnicode_FromString(p); } PyDoc_STRVAR(ctime_doc, @@ -695,17 +695,17 @@ static PyObject * time_mktime(PyObject *self, PyObject *tup) { - struct tm buf; - time_t tt; - if (!gettmarg(tup, &buf)) - return NULL; - tt = mktime(&buf); - if (tt == (time_t)(-1)) { - PyErr_SetString(PyExc_OverflowError, - "mktime argument out of range"); - return NULL; - } - return PyFloat_FromDouble((double)tt); + struct tm buf; + time_t tt; + if (!gettmarg(tup, &buf)) + return NULL; + tt = mktime(&buf); + if (tt == (time_t)(-1)) { + PyErr_SetString(PyExc_OverflowError, + "mktime argument out of range"); + return NULL; + } + return PyFloat_FromDouble((double)tt); } PyDoc_STRVAR(mktime_doc, @@ -720,21 +720,21 @@ static PyObject * time_tzset(PyObject *self, PyObject *unused) { - PyObject* m; + PyObject* m; - m = PyImport_ImportModuleNoBlock("time"); - if (m == NULL) { - return NULL; - } + m = PyImport_ImportModuleNoBlock("time"); + if (m == NULL) { + return NULL; + } - tzset(); + tzset(); - /* Reset timezone, altzone, daylight and tzname */ - PyInit_timezone(m); - Py_DECREF(m); + /* Reset timezone, altzone, daylight and tzname */ + PyInit_timezone(m); + Py_DECREF(m); - Py_INCREF(Py_None); - return Py_None; + Py_INCREF(Py_None); + return Py_None; } PyDoc_STRVAR(tzset_doc, @@ -754,115 +754,115 @@ static void PyInit_timezone(PyObject *m) { /* This code moved from PyInit_time wholesale to allow calling it from - time_tzset. In the future, some parts of it can be moved back - (for platforms that don't HAVE_WORKING_TZSET, when we know what they - are), and the extraneous calls to tzset(3) should be removed. - I haven't done this yet, as I don't want to change this code as - little as possible when introducing the time.tzset and time.tzsetwall - methods. This should simply be a method of doing the following once, - at the top of this function and removing the call to tzset() from - time_tzset(): - - #ifdef HAVE_TZSET - tzset() - #endif + time_tzset. In the future, some parts of it can be moved back + (for platforms that don't HAVE_WORKING_TZSET, when we know what they + are), and the extraneous calls to tzset(3) should be removed. + I haven't done this yet, as I don't want to change this code as + little as possible when introducing the time.tzset and time.tzsetwall + methods. This should simply be a method of doing the following once, + at the top of this function and removing the call to tzset() from + time_tzset(): + + #ifdef HAVE_TZSET + tzset() + #endif - And I'm lazy and hate C so nyer. + And I'm lazy and hate C so nyer. */ #if defined(HAVE_TZNAME) && !defined(__GLIBC__) && !defined(__CYGWIN__) - PyObject *otz0, *otz1; - tzset(); + PyObject *otz0, *otz1; + tzset(); #ifdef PYOS_OS2 - PyModule_AddIntConstant(m, "timezone", _timezone); + PyModule_AddIntConstant(m, "timezone", _timezone); #else /* !PYOS_OS2 */ - PyModule_AddIntConstant(m, "timezone", timezone); + PyModule_AddIntConstant(m, "timezone", timezone); #endif /* PYOS_OS2 */ #ifdef HAVE_ALTZONE - PyModule_AddIntConstant(m, "altzone", altzone); + PyModule_AddIntConstant(m, "altzone", altzone); #else #ifdef PYOS_OS2 - PyModule_AddIntConstant(m, "altzone", _timezone-3600); + PyModule_AddIntConstant(m, "altzone", _timezone-3600); #else /* !PYOS_OS2 */ - PyModule_AddIntConstant(m, "altzone", timezone-3600); + PyModule_AddIntConstant(m, "altzone", timezone-3600); #endif /* PYOS_OS2 */ #endif - PyModule_AddIntConstant(m, "daylight", daylight); - otz0 = PyUnicode_Decode(tzname[0], strlen(tzname[0]), TZNAME_ENCODING, NULL); - otz1 = PyUnicode_Decode(tzname[1], strlen(tzname[1]), TZNAME_ENCODING, NULL); - PyModule_AddObject(m, "tzname", Py_BuildValue("(NN)", otz0, otz1)); + PyModule_AddIntConstant(m, "daylight", daylight); + otz0 = PyUnicode_Decode(tzname[0], strlen(tzname[0]), TZNAME_ENCODING, NULL); + otz1 = PyUnicode_Decode(tzname[1], strlen(tzname[1]), TZNAME_ENCODING, NULL); + PyModule_AddObject(m, "tzname", Py_BuildValue("(NN)", otz0, otz1)); #else /* !HAVE_TZNAME || __GLIBC__ || __CYGWIN__*/ #ifdef HAVE_STRUCT_TM_TM_ZONE - { + { #define YEAR ((time_t)((365 * 24 + 6) * 3600)) - time_t t; - struct tm *p; - long janzone, julyzone; - char janname[10], julyname[10]; - t = (time((time_t *)0) / YEAR) * YEAR; - p = localtime(&t); - janzone = -p->tm_gmtoff; - strncpy(janname, p->tm_zone ? p->tm_zone : " ", 9); - janname[9] = '\0'; - t += YEAR/2; - p = localtime(&t); - julyzone = -p->tm_gmtoff; - strncpy(julyname, p->tm_zone ? p->tm_zone : " ", 9); - julyname[9] = '\0'; - - if( janzone < julyzone ) { - /* DST is reversed in the southern hemisphere */ - PyModule_AddIntConstant(m, "timezone", julyzone); - PyModule_AddIntConstant(m, "altzone", janzone); - PyModule_AddIntConstant(m, "daylight", - janzone != julyzone); - PyModule_AddObject(m, "tzname", - Py_BuildValue("(zz)", - julyname, janname)); - } else { - PyModule_AddIntConstant(m, "timezone", janzone); - PyModule_AddIntConstant(m, "altzone", julyzone); - PyModule_AddIntConstant(m, "daylight", - janzone != julyzone); - PyModule_AddObject(m, "tzname", - Py_BuildValue("(zz)", - janname, julyname)); - } - } + time_t t; + struct tm *p; + long janzone, julyzone; + char janname[10], julyname[10]; + t = (time((time_t *)0) / YEAR) * YEAR; + p = localtime(&t); + janzone = -p->tm_gmtoff; + strncpy(janname, p->tm_zone ? p->tm_zone : " ", 9); + janname[9] = '\0'; + t += YEAR/2; + p = localtime(&t); + julyzone = -p->tm_gmtoff; + strncpy(julyname, p->tm_zone ? p->tm_zone : " ", 9); + julyname[9] = '\0'; + + if( janzone < julyzone ) { + /* DST is reversed in the southern hemisphere */ + PyModule_AddIntConstant(m, "timezone", julyzone); + PyModule_AddIntConstant(m, "altzone", janzone); + PyModule_AddIntConstant(m, "daylight", + janzone != julyzone); + PyModule_AddObject(m, "tzname", + Py_BuildValue("(zz)", + julyname, janname)); + } else { + PyModule_AddIntConstant(m, "timezone", janzone); + PyModule_AddIntConstant(m, "altzone", julyzone); + PyModule_AddIntConstant(m, "daylight", + janzone != julyzone); + PyModule_AddObject(m, "tzname", + Py_BuildValue("(zz)", + janname, julyname)); + } + } #else #endif /* HAVE_STRUCT_TM_TM_ZONE */ #ifdef __CYGWIN__ - tzset(); - PyModule_AddIntConstant(m, "timezone", _timezone); - PyModule_AddIntConstant(m, "altzone", _timezone-3600); - PyModule_AddIntConstant(m, "daylight", _daylight); - PyModule_AddObject(m, "tzname", - Py_BuildValue("(zz)", _tzname[0], _tzname[1])); + tzset(); + PyModule_AddIntConstant(m, "timezone", _timezone); + PyModule_AddIntConstant(m, "altzone", _timezone-3600); + PyModule_AddIntConstant(m, "daylight", _daylight); + PyModule_AddObject(m, "tzname", + Py_BuildValue("(zz)", _tzname[0], _tzname[1])); #endif /* __CYGWIN__ */ #endif /* !HAVE_TZNAME || __GLIBC__ || __CYGWIN__*/ } static PyMethodDef time_methods[] = { - {"time", time_time, METH_NOARGS, time_doc}, + {"time", time_time, METH_NOARGS, time_doc}, #ifdef HAVE_CLOCK - {"clock", time_clock, METH_NOARGS, clock_doc}, + {"clock", time_clock, METH_NOARGS, clock_doc}, #endif - {"sleep", time_sleep, METH_VARARGS, sleep_doc}, - {"gmtime", time_gmtime, METH_VARARGS, gmtime_doc}, - {"localtime", time_localtime, METH_VARARGS, localtime_doc}, - {"asctime", time_asctime, METH_VARARGS, asctime_doc}, - {"ctime", time_ctime, METH_VARARGS, ctime_doc}, + {"sleep", time_sleep, METH_VARARGS, sleep_doc}, + {"gmtime", time_gmtime, METH_VARARGS, gmtime_doc}, + {"localtime", time_localtime, METH_VARARGS, localtime_doc}, + {"asctime", time_asctime, METH_VARARGS, asctime_doc}, + {"ctime", time_ctime, METH_VARARGS, ctime_doc}, #ifdef HAVE_MKTIME - {"mktime", time_mktime, METH_O, mktime_doc}, + {"mktime", time_mktime, METH_O, mktime_doc}, #endif #ifdef HAVE_STRFTIME - {"strftime", time_strftime, METH_VARARGS, strftime_doc}, + {"strftime", time_strftime, METH_VARARGS, strftime_doc}, #endif - {"strptime", time_strptime, METH_VARARGS, strptime_doc}, + {"strptime", time_strptime, METH_VARARGS, strptime_doc}, #ifdef HAVE_WORKING_TZSET - {"tzset", time_tzset, METH_NOARGS, tzset_doc}, + {"tzset", time_tzset, METH_NOARGS, tzset_doc}, #endif - {NULL, NULL} /* sentinel */ + {NULL, NULL} /* sentinel */ }; @@ -914,53 +914,53 @@ static struct PyModuleDef timemodule = { - PyModuleDef_HEAD_INIT, - "time", - module_doc, - -1, - time_methods, - NULL, - NULL, - NULL, - NULL + PyModuleDef_HEAD_INIT, + "time", + module_doc, + -1, + time_methods, + NULL, + NULL, + NULL, + NULL }; PyMODINIT_FUNC PyInit_time(void) { - PyObject *m; - char *p; - m = PyModule_Create(&timemodule); - if (m == NULL) - return NULL; - - /* Accept 2-digit dates unless PYTHONY2K is set and non-empty */ - p = Py_GETENV("PYTHONY2K"); - PyModule_AddIntConstant(m, "accept2dyear", (long) (!p || !*p)); - /* Squirrel away the module's dictionary for the y2k check */ - moddict = PyModule_GetDict(m); - Py_INCREF(moddict); + PyObject *m; + char *p; + m = PyModule_Create(&timemodule); + if (m == NULL) + return NULL; - /* Set, or reset, module variables like time.timezone */ - PyInit_timezone(m); + /* Accept 2-digit dates unless PYTHONY2K is set and non-empty */ + p = Py_GETENV("PYTHONY2K"); + PyModule_AddIntConstant(m, "accept2dyear", (long) (!p || !*p)); + /* Squirrel away the module's dictionary for the y2k check */ + moddict = PyModule_GetDict(m); + Py_INCREF(moddict); + + /* Set, or reset, module variables like time.timezone */ + PyInit_timezone(m); #ifdef MS_WINDOWS - /* Helper to allow interrupts for Windows. - If Ctrl+C event delivered while not sleeping - it will be ignored. - */ - main_thread = PyThread_get_thread_ident(); - hInterruptEvent = CreateEvent(NULL, TRUE, FALSE, NULL); - SetConsoleCtrlHandler( PyCtrlHandler, TRUE); + /* Helper to allow interrupts for Windows. + If Ctrl+C event delivered while not sleeping + it will be ignored. + */ + main_thread = PyThread_get_thread_ident(); + hInterruptEvent = CreateEvent(NULL, TRUE, FALSE, NULL); + SetConsoleCtrlHandler( PyCtrlHandler, TRUE); #endif /* MS_WINDOWS */ - if (!initialized) { - PyStructSequence_InitType(&StructTimeType, - &struct_time_type_desc); - } - Py_INCREF(&StructTimeType); - PyModule_AddObject(m, "struct_time", (PyObject*) &StructTimeType); - initialized = 1; - return m; + if (!initialized) { + PyStructSequence_InitType(&StructTimeType, + &struct_time_type_desc); + } + Py_INCREF(&StructTimeType); + PyModule_AddObject(m, "struct_time", (PyObject*) &StructTimeType); + initialized = 1; + return m; } @@ -969,38 +969,38 @@ static double floattime(void) { - /* There are three ways to get the time: - (1) gettimeofday() -- resolution in microseconds - (2) ftime() -- resolution in milliseconds - (3) time() -- resolution in seconds - In all cases the return value is a float in seconds. - Since on some systems (e.g. SCO ODT 3.0) gettimeofday() may - fail, so we fall back on ftime() or time(). - Note: clock resolution does not imply clock accuracy! */ + /* There are three ways to get the time: + (1) gettimeofday() -- resolution in microseconds + (2) ftime() -- resolution in milliseconds + (3) time() -- resolution in seconds + In all cases the return value is a float in seconds. + Since on some systems (e.g. SCO ODT 3.0) gettimeofday() may + fail, so we fall back on ftime() or time(). + Note: clock resolution does not imply clock accuracy! */ #ifdef HAVE_GETTIMEOFDAY - { - struct timeval t; + { + struct timeval t; #ifdef GETTIMEOFDAY_NO_TZ - if (gettimeofday(&t) == 0) - return (double)t.tv_sec + t.tv_usec*0.000001; + if (gettimeofday(&t) == 0) + return (double)t.tv_sec + t.tv_usec*0.000001; #else /* !GETTIMEOFDAY_NO_TZ */ - if (gettimeofday(&t, (struct timezone *)NULL) == 0) - return (double)t.tv_sec + t.tv_usec*0.000001; + if (gettimeofday(&t, (struct timezone *)NULL) == 0) + return (double)t.tv_sec + t.tv_usec*0.000001; #endif /* !GETTIMEOFDAY_NO_TZ */ - } + } #endif /* !HAVE_GETTIMEOFDAY */ - { + { #if defined(HAVE_FTIME) - struct timeb t; - ftime(&t); - return (double)t.time + (double)t.millitm * (double)0.001; + struct timeb t; + ftime(&t); + return (double)t.time + (double)t.millitm * (double)0.001; #else /* !HAVE_FTIME */ - time_t secs; - time(&secs); - return (double)secs; + time_t secs; + time(&secs); + return (double)secs; #endif /* !HAVE_FTIME */ - } + } } @@ -1013,96 +1013,96 @@ { /* XXX Should test for MS_WINDOWS first! */ #if defined(HAVE_SELECT) && !defined(__EMX__) - struct timeval t; - double frac; - frac = fmod(secs, 1.0); - secs = floor(secs); - t.tv_sec = (long)secs; - t.tv_usec = (long)(frac*1000000.0); - Py_BEGIN_ALLOW_THREADS - if (select(0, (fd_set *)0, (fd_set *)0, (fd_set *)0, &t) != 0) { + struct timeval t; + double frac; + frac = fmod(secs, 1.0); + secs = floor(secs); + t.tv_sec = (long)secs; + t.tv_usec = (long)(frac*1000000.0); + Py_BEGIN_ALLOW_THREADS + if (select(0, (fd_set *)0, (fd_set *)0, (fd_set *)0, &t) != 0) { #ifdef EINTR - if (errno != EINTR) { + if (errno != EINTR) { #else - if (1) { + if (1) { #endif - Py_BLOCK_THREADS - PyErr_SetFromErrno(PyExc_IOError); - return -1; - } - } - Py_END_ALLOW_THREADS + Py_BLOCK_THREADS + PyErr_SetFromErrno(PyExc_IOError); + return -1; + } + } + Py_END_ALLOW_THREADS #elif defined(__WATCOMC__) && !defined(__QNX__) - /* XXX Can't interrupt this sleep */ - Py_BEGIN_ALLOW_THREADS - delay((int)(secs * 1000 + 0.5)); /* delay() uses milliseconds */ - Py_END_ALLOW_THREADS + /* XXX Can't interrupt this sleep */ + Py_BEGIN_ALLOW_THREADS + delay((int)(secs * 1000 + 0.5)); /* delay() uses milliseconds */ + Py_END_ALLOW_THREADS #elif defined(MS_WINDOWS) - { - double millisecs = secs * 1000.0; - unsigned long ul_millis; - - if (millisecs > (double)ULONG_MAX) { - PyErr_SetString(PyExc_OverflowError, - "sleep length is too large"); - return -1; - } - Py_BEGIN_ALLOW_THREADS - /* Allow sleep(0) to maintain win32 semantics, and as decreed - * by Guido, only the main thread can be interrupted. - */ - ul_millis = (unsigned long)millisecs; - if (ul_millis == 0 || - main_thread != PyThread_get_thread_ident()) - Sleep(ul_millis); - else { - DWORD rc; - ResetEvent(hInterruptEvent); - rc = WaitForSingleObject(hInterruptEvent, ul_millis); - if (rc == WAIT_OBJECT_0) { - /* Yield to make sure real Python signal - * handler called. - */ - Sleep(1); - Py_BLOCK_THREADS - errno = EINTR; - PyErr_SetFromErrno(PyExc_IOError); - return -1; - } - } - Py_END_ALLOW_THREADS - } + { + double millisecs = secs * 1000.0; + unsigned long ul_millis; + + if (millisecs > (double)ULONG_MAX) { + PyErr_SetString(PyExc_OverflowError, + "sleep length is too large"); + return -1; + } + Py_BEGIN_ALLOW_THREADS + /* Allow sleep(0) to maintain win32 semantics, and as decreed + * by Guido, only the main thread can be interrupted. + */ + ul_millis = (unsigned long)millisecs; + if (ul_millis == 0 || + main_thread != PyThread_get_thread_ident()) + Sleep(ul_millis); + else { + DWORD rc; + ResetEvent(hInterruptEvent); + rc = WaitForSingleObject(hInterruptEvent, ul_millis); + if (rc == WAIT_OBJECT_0) { + /* Yield to make sure real Python signal + * handler called. + */ + Sleep(1); + Py_BLOCK_THREADS + errno = EINTR; + PyErr_SetFromErrno(PyExc_IOError); + return -1; + } + } + Py_END_ALLOW_THREADS + } #elif defined(PYOS_OS2) - /* This Sleep *IS* Interruptable by Exceptions */ - Py_BEGIN_ALLOW_THREADS - if (DosSleep(secs * 1000) != NO_ERROR) { - Py_BLOCK_THREADS - PyErr_SetFromErrno(PyExc_IOError); - return -1; - } - Py_END_ALLOW_THREADS + /* This Sleep *IS* Interruptable by Exceptions */ + Py_BEGIN_ALLOW_THREADS + if (DosSleep(secs * 1000) != NO_ERROR) { + Py_BLOCK_THREADS + PyErr_SetFromErrno(PyExc_IOError); + return -1; + } + Py_END_ALLOW_THREADS #elif defined(PLAN9) - { - double millisecs = secs * 1000.0; - if (millisecs > (double)LONG_MAX) { - PyErr_SetString(PyExc_OverflowError, "sleep length is too large"); - return -1; - } - /* This sleep *CAN BE* interrupted. */ - Py_BEGIN_ALLOW_THREADS - if(sleep((long)millisecs) < 0){ - Py_BLOCK_THREADS - PyErr_SetFromErrno(PyExc_IOError); - return -1; - } - Py_END_ALLOW_THREADS - } + { + double millisecs = secs * 1000.0; + if (millisecs > (double)LONG_MAX) { + PyErr_SetString(PyExc_OverflowError, "sleep length is too large"); + return -1; + } + /* This sleep *CAN BE* interrupted. */ + Py_BEGIN_ALLOW_THREADS + if(sleep((long)millisecs) < 0){ + Py_BLOCK_THREADS + PyErr_SetFromErrno(PyExc_IOError); + return -1; + } + Py_END_ALLOW_THREADS + } #else - /* XXX Can't interrupt this sleep */ - Py_BEGIN_ALLOW_THREADS - sleep((int)secs); - Py_END_ALLOW_THREADS + /* XXX Can't interrupt this sleep */ + Py_BEGIN_ALLOW_THREADS + sleep((int)secs); + Py_END_ALLOW_THREADS #endif - return 0; + return 0; } Modified: python/branches/release31-maint/Modules/tkappinit.c ============================================================================== --- python/branches/release31-maint/Modules/tkappinit.c (original) +++ python/branches/release31-maint/Modules/tkappinit.c Sun May 9 18:14:21 2010 @@ -26,154 +26,154 @@ int Tcl_AppInit(Tcl_Interp *interp) { - Tk_Window main_window; - const char *_tkinter_skip_tk_init; + Tk_Window main_window; + const char *_tkinter_skip_tk_init; #ifdef TKINTER_PROTECT_LOADTK - const char *_tkinter_tk_failed; + const char *_tkinter_tk_failed; #endif #ifdef TK_AQUA #ifndef MAX_PATH_LEN #define MAX_PATH_LEN 1024 #endif - char tclLibPath[MAX_PATH_LEN], tkLibPath[MAX_PATH_LEN]; - Tcl_Obj* pathPtr; + char tclLibPath[MAX_PATH_LEN], tkLibPath[MAX_PATH_LEN]; + Tcl_Obj* pathPtr; - /* pre- Tcl_Init code copied from tkMacOSXAppInit.c */ - Tk_MacOSXOpenBundleResources (interp, "com.tcltk.tcllibrary", - tclLibPath, MAX_PATH_LEN, 0); - - if (tclLibPath[0] != '\0') { - Tcl_SetVar(interp, "tcl_library", tclLibPath, TCL_GLOBAL_ONLY); - Tcl_SetVar(interp, "tclDefaultLibrary", tclLibPath, TCL_GLOBAL_ONLY); - Tcl_SetVar(interp, "tcl_pkgPath", tclLibPath, TCL_GLOBAL_ONLY); - } - - if (tclLibPath[0] != '\0') { - Tcl_SetVar(interp, "tcl_library", tclLibPath, TCL_GLOBAL_ONLY); - Tcl_SetVar(interp, "tclDefaultLibrary", tclLibPath, TCL_GLOBAL_ONLY); - Tcl_SetVar(interp, "tcl_pkgPath", tclLibPath, TCL_GLOBAL_ONLY); - } + /* pre- Tcl_Init code copied from tkMacOSXAppInit.c */ + Tk_MacOSXOpenBundleResources (interp, "com.tcltk.tcllibrary", + tclLibPath, MAX_PATH_LEN, 0); + + if (tclLibPath[0] != '\0') { + Tcl_SetVar(interp, "tcl_library", tclLibPath, TCL_GLOBAL_ONLY); + Tcl_SetVar(interp, "tclDefaultLibrary", tclLibPath, TCL_GLOBAL_ONLY); + Tcl_SetVar(interp, "tcl_pkgPath", tclLibPath, TCL_GLOBAL_ONLY); + } + + if (tclLibPath[0] != '\0') { + Tcl_SetVar(interp, "tcl_library", tclLibPath, TCL_GLOBAL_ONLY); + Tcl_SetVar(interp, "tclDefaultLibrary", tclLibPath, TCL_GLOBAL_ONLY); + Tcl_SetVar(interp, "tcl_pkgPath", tclLibPath, TCL_GLOBAL_ONLY); + } #endif - if (Tcl_Init (interp) == TCL_ERROR) - return TCL_ERROR; + if (Tcl_Init (interp) == TCL_ERROR) + return TCL_ERROR; #ifdef TK_AQUA - /* pre- Tk_Init code copied from tkMacOSXAppInit.c */ - Tk_MacOSXOpenBundleResources (interp, "com.tcltk.tklibrary", - tkLibPath, MAX_PATH_LEN, 1); - - if (tclLibPath[0] != '\0') { - pathPtr = Tcl_NewStringObj(tclLibPath, -1); - } else { - Tcl_Obj *pathPtr = TclGetLibraryPath(); - } - - if (tkLibPath[0] != '\0') { - Tcl_Obj *objPtr; - - Tcl_SetVar(interp, "tk_library", tkLibPath, TCL_GLOBAL_ONLY); - objPtr = Tcl_NewStringObj(tkLibPath, -1); - Tcl_ListObjAppendElement(NULL, pathPtr, objPtr); - } + /* pre- Tk_Init code copied from tkMacOSXAppInit.c */ + Tk_MacOSXOpenBundleResources (interp, "com.tcltk.tklibrary", + tkLibPath, MAX_PATH_LEN, 1); + + if (tclLibPath[0] != '\0') { + pathPtr = Tcl_NewStringObj(tclLibPath, -1); + } else { + Tcl_Obj *pathPtr = TclGetLibraryPath(); + } + + if (tkLibPath[0] != '\0') { + Tcl_Obj *objPtr; + + Tcl_SetVar(interp, "tk_library", tkLibPath, TCL_GLOBAL_ONLY); + objPtr = Tcl_NewStringObj(tkLibPath, -1); + Tcl_ListObjAppendElement(NULL, pathPtr, objPtr); + } - TclSetLibraryPath(pathPtr); + TclSetLibraryPath(pathPtr); #endif #ifdef WITH_XXX - /* Initialize modules that don't require Tk */ + /* Initialize modules that don't require Tk */ #endif - _tkinter_skip_tk_init = Tcl_GetVar(interp, - "_tkinter_skip_tk_init", TCL_GLOBAL_ONLY); - if (_tkinter_skip_tk_init != NULL && - strcmp(_tkinter_skip_tk_init, "1") == 0) { - return TCL_OK; - } + _tkinter_skip_tk_init = Tcl_GetVar(interp, + "_tkinter_skip_tk_init", TCL_GLOBAL_ONLY); + if (_tkinter_skip_tk_init != NULL && + strcmp(_tkinter_skip_tk_init, "1") == 0) { + return TCL_OK; + } #ifdef TKINTER_PROTECT_LOADTK - _tkinter_tk_failed = Tcl_GetVar(interp, - "_tkinter_tk_failed", TCL_GLOBAL_ONLY); + _tkinter_tk_failed = Tcl_GetVar(interp, + "_tkinter_tk_failed", TCL_GLOBAL_ONLY); - if (tk_load_failed || ( - _tkinter_tk_failed != NULL && - strcmp(_tkinter_tk_failed, "1") == 0)) { - Tcl_SetResult(interp, TKINTER_LOADTK_ERRMSG, TCL_STATIC); - return TCL_ERROR; - } + if (tk_load_failed || ( + _tkinter_tk_failed != NULL && + strcmp(_tkinter_tk_failed, "1") == 0)) { + Tcl_SetResult(interp, TKINTER_LOADTK_ERRMSG, TCL_STATIC); + return TCL_ERROR; + } #endif - if (Tk_Init(interp) == TCL_ERROR) { + if (Tk_Init(interp) == TCL_ERROR) { #ifdef TKINTER_PROTECT_LOADTK - tk_load_failed = 1; - Tcl_SetVar(interp, "_tkinter_tk_failed", "1", TCL_GLOBAL_ONLY); + tk_load_failed = 1; + Tcl_SetVar(interp, "_tkinter_tk_failed", "1", TCL_GLOBAL_ONLY); #endif - return TCL_ERROR; - } + return TCL_ERROR; + } - main_window = Tk_MainWindow(interp); + main_window = Tk_MainWindow(interp); #ifdef TK_AQUA - TkMacOSXInitAppleEvents(interp); - TkMacOSXInitMenus(interp); + TkMacOSXInitAppleEvents(interp); + TkMacOSXInitMenus(interp); #endif - + #ifdef WITH_MOREBUTTONS - { - extern Tcl_CmdProc studButtonCmd; - extern Tcl_CmdProc triButtonCmd; - - Tcl_CreateCommand(interp, "studbutton", studButtonCmd, - (ClientData) main_window, NULL); - Tcl_CreateCommand(interp, "tributton", triButtonCmd, - (ClientData) main_window, NULL); - } + { + extern Tcl_CmdProc studButtonCmd; + extern Tcl_CmdProc triButtonCmd; + + Tcl_CreateCommand(interp, "studbutton", studButtonCmd, + (ClientData) main_window, NULL); + Tcl_CreateCommand(interp, "tributton", triButtonCmd, + (ClientData) main_window, NULL); + } #endif #ifdef WITH_PIL /* 0.2b5 and later -- not yet released as of May 14 */ - { - extern void TkImaging_Init(Tcl_Interp *); - TkImaging_Init(interp); - /* XXX TkImaging_Init() doesn't have the right return type */ - /*Tcl_StaticPackage(interp, "Imaging", TkImaging_Init, NULL);*/ - } + { + extern void TkImaging_Init(Tcl_Interp *); + TkImaging_Init(interp); + /* XXX TkImaging_Init() doesn't have the right return type */ + /*Tcl_StaticPackage(interp, "Imaging", TkImaging_Init, NULL);*/ + } #endif #ifdef WITH_PIL_OLD /* 0.2b4 and earlier */ - { - extern void TkImaging_Init(void); - /* XXX TkImaging_Init() doesn't have the right prototype */ - /*Tcl_StaticPackage(interp, "Imaging", TkImaging_Init, NULL);*/ - } + { + extern void TkImaging_Init(void); + /* XXX TkImaging_Init() doesn't have the right prototype */ + /*Tcl_StaticPackage(interp, "Imaging", TkImaging_Init, NULL);*/ + } #endif #ifdef WITH_TIX - { - extern int Tix_Init(Tcl_Interp *interp); - extern int Tix_SafeInit(Tcl_Interp *interp); - Tcl_StaticPackage(NULL, "Tix", Tix_Init, Tix_SafeInit); - } + { + extern int Tix_Init(Tcl_Interp *interp); + extern int Tix_SafeInit(Tcl_Interp *interp); + Tcl_StaticPackage(NULL, "Tix", Tix_Init, Tix_SafeInit); + } #endif #ifdef WITH_BLT - { - extern int Blt_Init(Tcl_Interp *); - extern int Blt_SafeInit(Tcl_Interp *); - Tcl_StaticPackage(NULL, "Blt", Blt_Init, Blt_SafeInit); - } + { + extern int Blt_Init(Tcl_Interp *); + extern int Blt_SafeInit(Tcl_Interp *); + Tcl_StaticPackage(NULL, "Blt", Blt_Init, Blt_SafeInit); + } #endif #ifdef WITH_TOGL - { - /* XXX I've heard rumors that this doesn't work */ - extern int Togl_Init(Tcl_Interp *); - /* XXX Is there no Togl_SafeInit? */ - Tcl_StaticPackage(NULL, "Togl", Togl_Init, NULL); - } + { + /* XXX I've heard rumors that this doesn't work */ + extern int Togl_Init(Tcl_Interp *); + /* XXX Is there no Togl_SafeInit? */ + Tcl_StaticPackage(NULL, "Togl", Togl_Init, NULL); + } #endif #ifdef WITH_XXX #endif - return TCL_OK; + return TCL_OK; } Modified: python/branches/release31-maint/Modules/unicodedata.c ============================================================================== --- python/branches/release31-maint/Modules/unicodedata.c (original) +++ python/branches/release31-maint/Modules/unicodedata.c Sun May 9 18:14:21 2010 @@ -19,14 +19,14 @@ /* character properties */ typedef struct { - const unsigned char category; /* index into - _PyUnicode_CategoryNames */ - const unsigned char combining; /* combining class value 0 - 255 */ - const unsigned char bidirectional; /* index into - _PyUnicode_BidirectionalNames */ - const unsigned char mirrored; /* true if mirrored in bidir mode */ - const unsigned char east_asian_width; /* index into - _PyUnicode_EastAsianWidth */ + const unsigned char category; /* index into + _PyUnicode_CategoryNames */ + const unsigned char combining; /* combining class value 0 - 255 */ + const unsigned char bidirectional; /* index into + _PyUnicode_BidirectionalNames */ + const unsigned char mirrored; /* true if mirrored in bidir mode */ + const unsigned char east_asian_width; /* index into + _PyUnicode_EastAsianWidth */ const unsigned char normalization_quick_check; /* see is_normalized() */ } _PyUnicode_DatabaseRecord; @@ -67,7 +67,7 @@ #define get_old_record(self, v) ((((PreviousDBVersion*)self)->getrecord)(v)) static PyMemberDef DB_members[] = { - {"unidata_version", T_STRING, offsetof(PreviousDBVersion, name), READONLY}, + {"unidata_version", T_STRING, offsetof(PreviousDBVersion, name), READONLY}, {NULL} }; @@ -79,14 +79,14 @@ new_previous_version(const char*name, const change_record* (*getrecord)(Py_UCS4), Py_UCS4 (*normalization)(Py_UCS4)) { - PreviousDBVersion *self; - self = PyObject_New(PreviousDBVersion, &UCD_Type); - if (self == NULL) - return NULL; - self->name = name; - self->getrecord = getrecord; + PreviousDBVersion *self; + self = PyObject_New(PreviousDBVersion, &UCD_Type); + if (self == NULL) + return NULL; + self->name = name; + self->getrecord = getrecord; self->normalization = normalization; - return (PyObject*)self; + return (PyObject*)self; } @@ -95,12 +95,12 @@ Py_UNICODE *v = PyUnicode_AS_UNICODE(obj); if (PyUnicode_GET_SIZE(obj) == 1) - return *v; + return *v; #ifndef Py_UNICODE_WIDE else if ((PyUnicode_GET_SIZE(obj) == 2) && (0xD800 <= v[0] && v[0] <= 0xDBFF) && (0xDC00 <= v[1] && v[1] <= 0xDFFF)) - return (((v[0] & 0x3FF)<<10) | (v[1] & 0x3FF)) + 0x10000; + return (((v[0] & 0x3FF)<<10) | (v[1] & 0x3FF)) + 0x10000; #endif PyErr_SetString(PyExc_TypeError, "need a single Unicode character as parameter"); @@ -137,7 +137,7 @@ /* unassigned */ have_old = 1; rc = -1; - } + } else if (old->decimal_changed != 0xFF) { have_old = 1; rc = old->decimal_changed; @@ -147,15 +147,15 @@ if (!have_old) rc = Py_UNICODE_TODECIMAL(c); if (rc < 0) { - if (defobj == NULL) { - PyErr_SetString(PyExc_ValueError, - "not a decimal"); + if (defobj == NULL) { + PyErr_SetString(PyExc_ValueError, + "not a decimal"); return NULL; - } - else { - Py_INCREF(defobj); - return defobj; - } + } + else { + Py_INCREF(defobj); + return defobj; + } } return PyLong_FromLong(rc); } @@ -182,14 +182,14 @@ return NULL; rc = Py_UNICODE_TODIGIT(c); if (rc < 0) { - if (defobj == NULL) { - PyErr_SetString(PyExc_ValueError, "not a digit"); + if (defobj == NULL) { + PyErr_SetString(PyExc_ValueError, "not a digit"); return NULL; - } - else { - Py_INCREF(defobj); - return defobj; - } + } + else { + Py_INCREF(defobj); + return defobj; + } } return PyLong_FromLong(rc); } @@ -222,7 +222,7 @@ /* unassigned */ have_old = 1; rc = -1.0; - } + } else if (old->decimal_changed != 0xFF) { have_old = 1; rc = old->decimal_changed; @@ -232,14 +232,14 @@ if (!have_old) rc = Py_UNICODE_TONUMERIC(c); if (rc == -1.0) { - if (defobj == NULL) { - PyErr_SetString(PyExc_ValueError, "not a numeric character"); - return NULL; - } - else { - Py_INCREF(defobj); - return defobj; - } + if (defobj == NULL) { + PyErr_SetString(PyExc_ValueError, "not a numeric character"); + return NULL; + } + else { + Py_INCREF(defobj); + return defobj; + } } return PyFloat_FromDouble(rc); } @@ -258,8 +258,8 @@ Py_UCS4 c; if (!PyArg_ParseTuple(args, "O!:category", - &PyUnicode_Type, &v)) - return NULL; + &PyUnicode_Type, &v)) + return NULL; c = getuchar(v); if (c == (Py_UCS4)-1) return NULL; @@ -287,8 +287,8 @@ Py_UCS4 c; if (!PyArg_ParseTuple(args, "O!:bidirectional", - &PyUnicode_Type, &v)) - return NULL; + &PyUnicode_Type, &v)) + return NULL; c = getuchar(v); if (c == (Py_UCS4)-1) return NULL; @@ -318,8 +318,8 @@ Py_UCS4 c; if (!PyArg_ParseTuple(args, "O!:combining", - &PyUnicode_Type, &v)) - return NULL; + &PyUnicode_Type, &v)) + return NULL; c = getuchar(v); if (c == (Py_UCS4)-1) return NULL; @@ -347,8 +347,8 @@ Py_UCS4 c; if (!PyArg_ParseTuple(args, "O!:mirrored", - &PyUnicode_Type, &v)) - return NULL; + &PyUnicode_Type, &v)) + return NULL; c = getuchar(v); if (c == (Py_UCS4)-1) return NULL; @@ -377,8 +377,8 @@ Py_UCS4 c; if (!PyArg_ParseTuple(args, "O!:east_asian_width", - &PyUnicode_Type, &v)) - return NULL; + &PyUnicode_Type, &v)) + return NULL; c = getuchar(v); if (c == (Py_UCS4)-1) return NULL; @@ -408,8 +408,8 @@ Py_UCS4 c; if (!PyArg_ParseTuple(args, "O!:decomposition", - &PyUnicode_Type, &v)) - return NULL; + &PyUnicode_Type, &v)) + return NULL; c = getuchar(v); if (c == (Py_UCS4)-1) return NULL; @@ -455,7 +455,7 @@ decomp_data[++index]); i += strlen(decomp + i); } - + decomp[i] = '\0'; return PyUnicode_FromString(decomp); @@ -466,7 +466,7 @@ { if (code >= 0x110000) { *index = 0; - } else if (self && UCD_Check(self) && + } else if (self && UCD_Check(self) && get_old_record(self, code)->category_changed==0) { /* unassigned in old version */ *index = 0; @@ -476,7 +476,7 @@ *index = decomp_index2[(*index<> 8; @@ -501,11 +501,11 @@ PyObject *result; Py_UNICODE *i, *end, *o; /* Longest decomposition in Unicode 3.2: U+FDFA */ - Py_UNICODE stack[20]; + Py_UNICODE stack[20]; Py_ssize_t space, isize; int index, prefix, count, stackptr; unsigned char prev, cur; - + stackptr = 0; isize = PyUnicode_GET_SIZE(input); /* Overallocate atmost 10 characters. */ @@ -642,12 +642,12 @@ i = PyUnicode_AS_UNICODE(result); end = i + PyUnicode_GET_SIZE(result); o = PyUnicode_AS_UNICODE(result); - + again: while (i < end) { for (index = 0; index < cskipped; index++) { if (skipped[index] == i) { - /* *i character is skipped. + /* *i character is skipped. Remove from list. */ skipped[index] = skipped[cskipped-1]; cskipped--; @@ -658,7 +658,7 @@ /* Hangul Composition. We don't need to check for pairs, since we always have decomposed data. */ if (LBase <= *i && *i < (LBase+LCount) && - i + 1 < end && + i + 1 < end && VBase <= i[1] && i[1] <= (VBase+VCount)) { int LIndex, VIndex; LIndex = i[0] - LBase; @@ -707,7 +707,7 @@ (index&((1<category_changed == 0) { /* unassigned */ return 0; - } + } } if (SBase <= code && code < SBase+SCount) { - /* Hangul syllable. */ - int SIndex = code - SBase; - int L = SIndex / NCount; - int V = (SIndex % NCount) / TCount; - int T = SIndex % TCount; - - if (buflen < 27) - /* Worst case: HANGUL SYLLABLE <10chars>. */ - return 0; - strcpy(buffer, "HANGUL SYLLABLE "); - buffer += 16; - strcpy(buffer, hangul_syllables[L][0]); - buffer += strlen(hangul_syllables[L][0]); - strcpy(buffer, hangul_syllables[V][1]); - buffer += strlen(hangul_syllables[V][1]); - strcpy(buffer, hangul_syllables[T][2]); - buffer += strlen(hangul_syllables[T][2]); - *buffer = '\0'; - return 1; + /* Hangul syllable. */ + int SIndex = code - SBase; + int L = SIndex / NCount; + int V = (SIndex % NCount) / TCount; + int T = SIndex % TCount; + + if (buflen < 27) + /* Worst case: HANGUL SYLLABLE <10chars>. */ + return 0; + strcpy(buffer, "HANGUL SYLLABLE "); + buffer += 16; + strcpy(buffer, hangul_syllables[L][0]); + buffer += strlen(hangul_syllables[L][0]); + strcpy(buffer, hangul_syllables[V][1]); + buffer += strlen(hangul_syllables[V][1]); + strcpy(buffer, hangul_syllables[T][2]); + buffer += strlen(hangul_syllables[T][2]); + *buffer = '\0'; + return 1; } if (is_unified_ideograph(code)) { @@ -980,23 +980,23 @@ return buffer[namelen] == '\0'; } -static void +static void find_syllable(const char *str, int *len, int *pos, int count, int column) { int i, len1; *len = -1; for (i = 0; i < count; i++) { - char *s = hangul_syllables[i][column]; - len1 = strlen(s); - if (len1 <= *len) - continue; - if (strncmp(str, s, len1) == 0) { - *len = len1; - *pos = i; - } + char *s = hangul_syllables[i][column]; + len1 = strlen(s); + if (len1 <= *len) + continue; + if (strncmp(str, s, len1) == 0) { + *len = len1; + *pos = i; + } } if (*len == -1) { - *len = 0; + *len = 0; } } @@ -1009,18 +1009,18 @@ /* Check for hangul syllables. */ if (strncmp(name, "HANGUL SYLLABLE ", 16) == 0) { - int len, L = -1, V = -1, T = -1; - const char *pos = name + 16; - find_syllable(pos, &len, &L, LCount, 0); - pos += len; - find_syllable(pos, &len, &V, VCount, 1); - pos += len; - find_syllable(pos, &len, &T, TCount, 2); - pos += len; - if (L != -1 && V != -1 && T != -1 && pos-name == namelen) { - *code = SBase + (L*VCount+V)*TCount + T; - return 1; - } + int len, L = -1, V = -1, T = -1; + const char *pos = name + 16; + find_syllable(pos, &len, &L, LCount, 0); + pos += len; + find_syllable(pos, &len, &V, VCount, 1); + pos += len; + find_syllable(pos, &len, &T, TCount, 2); + pos += len; + if (L != -1 && V != -1 && T != -1 && pos-name == namelen) { + *code = SBase + (L*VCount+V)*TCount + T; + return 1; + } /* Otherwise, it's an illegal syllable name. */ return 0; } @@ -1080,7 +1080,7 @@ } } -static const _PyUnicode_Name_CAPI hashAPI = +static const _PyUnicode_Name_CAPI hashAPI = { sizeof(_PyUnicode_Name_CAPI), _getucname, @@ -1112,14 +1112,14 @@ return NULL; if (!_getucname(self, c, name, sizeof(name))) { - if (defobj == NULL) { - PyErr_SetString(PyExc_ValueError, "no such name"); + if (defobj == NULL) { + PyErr_SetString(PyExc_ValueError, "no such name"); return NULL; - } - else { - Py_INCREF(defobj); - return defobj; - } + } + else { + Py_INCREF(defobj); + return defobj; + } } return PyUnicode_FromString(name); @@ -1157,7 +1157,7 @@ } #endif str[0] = (Py_UNICODE) code; - return PyUnicode_FromUnicode(str, 1); + return PyUnicode_FromUnicode(str, 1); } /* XXX Add doc strings. */ @@ -1182,27 +1182,27 @@ {"lookup", unicodedata_lookup, METH_VARARGS, unicodedata_lookup__doc__}, {"normalize", unicodedata_normalize, METH_VARARGS, unicodedata_normalize__doc__}, - {NULL, NULL} /* sentinel */ + {NULL, NULL} /* sentinel */ }; static PyTypeObject UCD_Type = { - /* The ob_type field must be initialized in the module init function - * to be portable to Windows without using C++. */ - PyVarObject_HEAD_INIT(NULL, 0) - "unicodedata.UCD", /*tp_name*/ - sizeof(PreviousDBVersion), /*tp_basicsize*/ - 0, /*tp_itemsize*/ - /* methods */ - (destructor)PyObject_Del, /*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*/ + /* The ob_type field must be initialized in the module init function + * to be portable to Windows without using C++. */ + PyVarObject_HEAD_INIT(NULL, 0) + "unicodedata.UCD", /*tp_name*/ + sizeof(PreviousDBVersion), /*tp_basicsize*/ + 0, /*tp_itemsize*/ + /* methods */ + (destructor)PyObject_Del, /*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*/ @@ -1243,15 +1243,15 @@ static struct PyModuleDef unicodedatamodule = { - PyModuleDef_HEAD_INIT, - "unicodedata", - unicodedata_docstring, - -1, - unicodedata_functions, - NULL, - NULL, - NULL, - NULL + PyModuleDef_HEAD_INIT, + "unicodedata", + unicodedata_docstring, + -1, + unicodedata_functions, + NULL, + NULL, + NULL, + NULL }; PyMODINIT_FUNC @@ -1281,7 +1281,7 @@ return m; } -/* +/* Local variables: c-basic-offset: 4 indent-tabs-mode: nil Modified: python/branches/release31-maint/Modules/xxmodule.c ============================================================================== --- python/branches/release31-maint/Modules/xxmodule.c (original) +++ python/branches/release31-maint/Modules/xxmodule.c Sun May 9 18:14:21 2010 @@ -19,23 +19,23 @@ static PyObject *ErrorObject; typedef struct { - PyObject_HEAD - PyObject *x_attr; /* Attributes dictionary */ + PyObject_HEAD + PyObject *x_attr; /* Attributes dictionary */ } XxoObject; static PyTypeObject Xxo_Type; -#define XxoObject_Check(v) (Py_TYPE(v) == &Xxo_Type) +#define XxoObject_Check(v) (Py_TYPE(v) == &Xxo_Type) static XxoObject * newXxoObject(PyObject *arg) { - XxoObject *self; - self = PyObject_New(XxoObject, &Xxo_Type); - if (self == NULL) - return NULL; - self->x_attr = NULL; - return self; + XxoObject *self; + self = PyObject_New(XxoObject, &Xxo_Type); + if (self == NULL) + return NULL; + self->x_attr = NULL; + return self; } /* Xxo methods */ @@ -43,101 +43,101 @@ static void Xxo_dealloc(XxoObject *self) { - Py_XDECREF(self->x_attr); - PyObject_Del(self); + Py_XDECREF(self->x_attr); + PyObject_Del(self); } static PyObject * Xxo_demo(XxoObject *self, PyObject *args) { - if (!PyArg_ParseTuple(args, ":demo")) - return NULL; - Py_INCREF(Py_None); - return Py_None; + if (!PyArg_ParseTuple(args, ":demo")) + return NULL; + Py_INCREF(Py_None); + return Py_None; } static PyMethodDef Xxo_methods[] = { - {"demo", (PyCFunction)Xxo_demo, METH_VARARGS, - PyDoc_STR("demo() -> None")}, - {NULL, NULL} /* sentinel */ + {"demo", (PyCFunction)Xxo_demo, METH_VARARGS, + PyDoc_STR("demo() -> None")}, + {NULL, NULL} /* sentinel */ }; static PyObject * Xxo_getattro(XxoObject *self, PyObject *name) { - if (self->x_attr != NULL) { - PyObject *v = PyDict_GetItem(self->x_attr, name); - if (v != NULL) { - Py_INCREF(v); - return v; - } - } - return PyObject_GenericGetAttr((PyObject *)self, name); + if (self->x_attr != NULL) { + PyObject *v = PyDict_GetItem(self->x_attr, name); + if (v != NULL) { + Py_INCREF(v); + return v; + } + } + return PyObject_GenericGetAttr((PyObject *)self, name); } static int Xxo_setattr(XxoObject *self, char *name, PyObject *v) { - if (self->x_attr == NULL) { - self->x_attr = PyDict_New(); - if (self->x_attr == NULL) - return -1; - } - if (v == NULL) { - int rv = PyDict_DelItemString(self->x_attr, name); - if (rv < 0) - PyErr_SetString(PyExc_AttributeError, - "delete non-existing Xxo attribute"); - return rv; - } - else - return PyDict_SetItemString(self->x_attr, name, v); + if (self->x_attr == NULL) { + self->x_attr = PyDict_New(); + if (self->x_attr == NULL) + return -1; + } + if (v == NULL) { + int rv = PyDict_DelItemString(self->x_attr, name); + if (rv < 0) + PyErr_SetString(PyExc_AttributeError, + "delete non-existing Xxo attribute"); + return rv; + } + else + return PyDict_SetItemString(self->x_attr, name, v); } static PyTypeObject Xxo_Type = { - /* The ob_type field must be initialized in the module init function - * to be portable to Windows without using C++. */ - PyVarObject_HEAD_INIT(NULL, 0) - "xxmodule.Xxo", /*tp_name*/ - sizeof(XxoObject), /*tp_basicsize*/ - 0, /*tp_itemsize*/ - /* methods */ - (destructor)Xxo_dealloc, /*tp_dealloc*/ - 0, /*tp_print*/ - (getattrfunc)0, /*tp_getattr*/ - (setattrfunc)Xxo_setattr, /*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*/ - (getattrofunc)Xxo_getattro, /*tp_getattro*/ - 0, /*tp_setattro*/ - 0, /*tp_as_buffer*/ - Py_TPFLAGS_DEFAULT, /*tp_flags*/ - 0, /*tp_doc*/ - 0, /*tp_traverse*/ - 0, /*tp_clear*/ - 0, /*tp_richcompare*/ - 0, /*tp_weaklistoffset*/ - 0, /*tp_iter*/ - 0, /*tp_iternext*/ - Xxo_methods, /*tp_methods*/ - 0, /*tp_members*/ - 0, /*tp_getset*/ - 0, /*tp_base*/ - 0, /*tp_dict*/ - 0, /*tp_descr_get*/ - 0, /*tp_descr_set*/ - 0, /*tp_dictoffset*/ - 0, /*tp_init*/ - 0, /*tp_alloc*/ - 0, /*tp_new*/ - 0, /*tp_free*/ - 0, /*tp_is_gc*/ + /* The ob_type field must be initialized in the module init function + * to be portable to Windows without using C++. */ + PyVarObject_HEAD_INIT(NULL, 0) + "xxmodule.Xxo", /*tp_name*/ + sizeof(XxoObject), /*tp_basicsize*/ + 0, /*tp_itemsize*/ + /* methods */ + (destructor)Xxo_dealloc, /*tp_dealloc*/ + 0, /*tp_print*/ + (getattrfunc)0, /*tp_getattr*/ + (setattrfunc)Xxo_setattr, /*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*/ + (getattrofunc)Xxo_getattro, /*tp_getattro*/ + 0, /*tp_setattro*/ + 0, /*tp_as_buffer*/ + Py_TPFLAGS_DEFAULT, /*tp_flags*/ + 0, /*tp_doc*/ + 0, /*tp_traverse*/ + 0, /*tp_clear*/ + 0, /*tp_richcompare*/ + 0, /*tp_weaklistoffset*/ + 0, /*tp_iter*/ + 0, /*tp_iternext*/ + Xxo_methods, /*tp_methods*/ + 0, /*tp_members*/ + 0, /*tp_getset*/ + 0, /*tp_base*/ + 0, /*tp_dict*/ + 0, /*tp_descr_get*/ + 0, /*tp_descr_set*/ + 0, /*tp_dictoffset*/ + 0, /*tp_init*/ + 0, /*tp_alloc*/ + 0, /*tp_new*/ + 0, /*tp_free*/ + 0, /*tp_is_gc*/ }; /* --------------------------------------------------------------------- */ @@ -151,12 +151,12 @@ static PyObject * xx_foo(PyObject *self, PyObject *args) { - long i, j; - long res; - if (!PyArg_ParseTuple(args, "ll:foo", &i, &j)) - return NULL; - res = i+j; /* XXX Do something here */ - return PyLong_FromLong(res); + long i, j; + long res; + if (!PyArg_ParseTuple(args, "ll:foo", &i, &j)) + return NULL; + res = i+j; /* XXX Do something here */ + return PyLong_FromLong(res); } @@ -165,14 +165,14 @@ static PyObject * xx_new(PyObject *self, PyObject *args) { - XxoObject *rv; + XxoObject *rv; - if (!PyArg_ParseTuple(args, ":new")) - return NULL; - rv = newXxoObject(args); - if (rv == NULL) - return NULL; - return (PyObject *)rv; + if (!PyArg_ParseTuple(args, ":new")) + return NULL; + rv = newXxoObject(args); + if (rv == NULL) + return NULL; + return (PyObject *)rv; } /* Example with subtle bug from extensions manual ("Thin Ice"). */ @@ -180,20 +180,20 @@ static PyObject * xx_bug(PyObject *self, PyObject *args) { - PyObject *list, *item; + PyObject *list, *item; - if (!PyArg_ParseTuple(args, "O:bug", &list)) - return NULL; + if (!PyArg_ParseTuple(args, "O:bug", &list)) + return NULL; - item = PyList_GetItem(list, 0); - /* Py_INCREF(item); */ - PyList_SetItem(list, 1, PyLong_FromLong(0L)); - PyObject_Print(item, stdout, 0); - printf("\n"); - /* Py_DECREF(item); */ + item = PyList_GetItem(list, 0); + /* Py_INCREF(item); */ + PyList_SetItem(list, 1, PyLong_FromLong(0L)); + PyObject_Print(item, stdout, 0); + printf("\n"); + /* Py_DECREF(item); */ - Py_INCREF(Py_None); - return Py_None; + Py_INCREF(Py_None); + return Py_None; } /* Test bad format character */ @@ -201,61 +201,61 @@ static PyObject * xx_roj(PyObject *self, PyObject *args) { - PyObject *a; - long b; - if (!PyArg_ParseTuple(args, "O#:roj", &a, &b)) - return NULL; - Py_INCREF(Py_None); - return Py_None; + PyObject *a; + long b; + if (!PyArg_ParseTuple(args, "O#:roj", &a, &b)) + return NULL; + Py_INCREF(Py_None); + return Py_None; } /* ---------- */ static PyTypeObject Str_Type = { - /* The ob_type field must be initialized in the module init function - * to be portable to Windows without using C++. */ - PyVarObject_HEAD_INIT(NULL, 0) - "xxmodule.Str", /*tp_name*/ - 0, /*tp_basicsize*/ - 0, /*tp_itemsize*/ - /* methods */ - 0, /*tp_dealloc*/ - 0, /*tp_print*/ - 0, /*tp_getattr*/ - 0, /*tp_setattr*/ - 0, /*tp_reserved*/ - 0, /*tp_repr*/ - 0, /*tp_as_number*/ - 0, /*tp_as_sequence*/ - 0, /*tp_as_mapping*/ - 0, /*tp_hash*/ - 0, /*tp_call*/ - 0, /*tp_str*/ - 0, /*tp_getattro*/ - 0, /*tp_setattro*/ - 0, /*tp_as_buffer*/ - Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /*tp_flags*/ - 0, /*tp_doc*/ - 0, /*tp_traverse*/ - 0, /*tp_clear*/ - 0, /*tp_richcompare*/ - 0, /*tp_weaklistoffset*/ - 0, /*tp_iter*/ - 0, /*tp_iternext*/ - 0, /*tp_methods*/ - 0, /*tp_members*/ - 0, /*tp_getset*/ - 0, /* see PyInit_xx */ /*tp_base*/ - 0, /*tp_dict*/ - 0, /*tp_descr_get*/ - 0, /*tp_descr_set*/ - 0, /*tp_dictoffset*/ - 0, /*tp_init*/ - 0, /*tp_alloc*/ - 0, /*tp_new*/ - 0, /*tp_free*/ - 0, /*tp_is_gc*/ + /* The ob_type field must be initialized in the module init function + * to be portable to Windows without using C++. */ + PyVarObject_HEAD_INIT(NULL, 0) + "xxmodule.Str", /*tp_name*/ + 0, /*tp_basicsize*/ + 0, /*tp_itemsize*/ + /* methods */ + 0, /*tp_dealloc*/ + 0, /*tp_print*/ + 0, /*tp_getattr*/ + 0, /*tp_setattr*/ + 0, /*tp_reserved*/ + 0, /*tp_repr*/ + 0, /*tp_as_number*/ + 0, /*tp_as_sequence*/ + 0, /*tp_as_mapping*/ + 0, /*tp_hash*/ + 0, /*tp_call*/ + 0, /*tp_str*/ + 0, /*tp_getattro*/ + 0, /*tp_setattro*/ + 0, /*tp_as_buffer*/ + Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /*tp_flags*/ + 0, /*tp_doc*/ + 0, /*tp_traverse*/ + 0, /*tp_clear*/ + 0, /*tp_richcompare*/ + 0, /*tp_weaklistoffset*/ + 0, /*tp_iter*/ + 0, /*tp_iternext*/ + 0, /*tp_methods*/ + 0, /*tp_members*/ + 0, /*tp_getset*/ + 0, /* see PyInit_xx */ /*tp_base*/ + 0, /*tp_dict*/ + 0, /*tp_descr_get*/ + 0, /*tp_descr_set*/ + 0, /*tp_dictoffset*/ + 0, /*tp_init*/ + 0, /*tp_alloc*/ + 0, /*tp_new*/ + 0, /*tp_free*/ + 0, /*tp_is_gc*/ }; /* ---------- */ @@ -263,54 +263,54 @@ static PyObject * null_richcompare(PyObject *self, PyObject *other, int op) { - Py_INCREF(Py_NotImplemented); - return Py_NotImplemented; + Py_INCREF(Py_NotImplemented); + return Py_NotImplemented; } static PyTypeObject Null_Type = { - /* The ob_type field must be initialized in the module init function - * to be portable to Windows without using C++. */ - PyVarObject_HEAD_INIT(NULL, 0) - "xxmodule.Null", /*tp_name*/ - 0, /*tp_basicsize*/ - 0, /*tp_itemsize*/ - /* methods */ - 0, /*tp_dealloc*/ - 0, /*tp_print*/ - 0, /*tp_getattr*/ - 0, /*tp_setattr*/ - 0, /*tp_reserved*/ - 0, /*tp_repr*/ - 0, /*tp_as_number*/ - 0, /*tp_as_sequence*/ - 0, /*tp_as_mapping*/ - 0, /*tp_hash*/ - 0, /*tp_call*/ - 0, /*tp_str*/ - 0, /*tp_getattro*/ - 0, /*tp_setattro*/ - 0, /*tp_as_buffer*/ - Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /*tp_flags*/ - 0, /*tp_doc*/ - 0, /*tp_traverse*/ - 0, /*tp_clear*/ - null_richcompare, /*tp_richcompare*/ - 0, /*tp_weaklistoffset*/ - 0, /*tp_iter*/ - 0, /*tp_iternext*/ - 0, /*tp_methods*/ - 0, /*tp_members*/ - 0, /*tp_getset*/ - 0, /* see PyInit_xx */ /*tp_base*/ - 0, /*tp_dict*/ - 0, /*tp_descr_get*/ - 0, /*tp_descr_set*/ - 0, /*tp_dictoffset*/ - 0, /*tp_init*/ - 0, /*tp_alloc*/ - 0, /* see PyInit_xx */ /*tp_new*/ - 0, /*tp_free*/ - 0, /*tp_is_gc*/ + /* The ob_type field must be initialized in the module init function + * to be portable to Windows without using C++. */ + PyVarObject_HEAD_INIT(NULL, 0) + "xxmodule.Null", /*tp_name*/ + 0, /*tp_basicsize*/ + 0, /*tp_itemsize*/ + /* methods */ + 0, /*tp_dealloc*/ + 0, /*tp_print*/ + 0, /*tp_getattr*/ + 0, /*tp_setattr*/ + 0, /*tp_reserved*/ + 0, /*tp_repr*/ + 0, /*tp_as_number*/ + 0, /*tp_as_sequence*/ + 0, /*tp_as_mapping*/ + 0, /*tp_hash*/ + 0, /*tp_call*/ + 0, /*tp_str*/ + 0, /*tp_getattro*/ + 0, /*tp_setattro*/ + 0, /*tp_as_buffer*/ + Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /*tp_flags*/ + 0, /*tp_doc*/ + 0, /*tp_traverse*/ + 0, /*tp_clear*/ + null_richcompare, /*tp_richcompare*/ + 0, /*tp_weaklistoffset*/ + 0, /*tp_iter*/ + 0, /*tp_iternext*/ + 0, /*tp_methods*/ + 0, /*tp_members*/ + 0, /*tp_getset*/ + 0, /* see PyInit_xx */ /*tp_base*/ + 0, /*tp_dict*/ + 0, /*tp_descr_get*/ + 0, /*tp_descr_set*/ + 0, /*tp_dictoffset*/ + 0, /*tp_init*/ + 0, /*tp_alloc*/ + 0, /* see PyInit_xx */ /*tp_new*/ + 0, /*tp_free*/ + 0, /*tp_is_gc*/ }; @@ -320,15 +320,15 @@ /* List of functions defined in the module */ static PyMethodDef xx_methods[] = { - {"roj", xx_roj, METH_VARARGS, - PyDoc_STR("roj(a,b) -> None")}, - {"foo", xx_foo, METH_VARARGS, - xx_foo_doc}, - {"new", xx_new, METH_VARARGS, - PyDoc_STR("new() -> new Xx object")}, - {"bug", xx_bug, METH_VARARGS, - PyDoc_STR("bug(o) -> None")}, - {NULL, NULL} /* sentinel */ + {"roj", xx_roj, METH_VARARGS, + PyDoc_STR("roj(a,b) -> None")}, + {"foo", xx_foo, METH_VARARGS, + xx_foo_doc}, + {"new", xx_new, METH_VARARGS, + PyDoc_STR("new() -> new Xx object")}, + {"bug", xx_bug, METH_VARARGS, + PyDoc_STR("bug(o) -> None")}, + {NULL, NULL} /* sentinel */ }; PyDoc_STRVAR(module_doc, @@ -338,59 +338,59 @@ static struct PyModuleDef xxmodule = { - PyModuleDef_HEAD_INIT, - "xx", - module_doc, - -1, - xx_methods, - NULL, - NULL, - NULL, - NULL + PyModuleDef_HEAD_INIT, + "xx", + module_doc, + -1, + xx_methods, + NULL, + NULL, + NULL, + NULL }; PyMODINIT_FUNC PyInit_xx(void) { - PyObject *m = NULL; + PyObject *m = NULL; - /* Due to cross platform compiler issues the slots must be filled - * here. It's required for portability to Windows without requiring - * C++. */ - Null_Type.tp_base = &PyBaseObject_Type; - Null_Type.tp_new = PyType_GenericNew; - Str_Type.tp_base = &PyUnicode_Type; - - /* Finalize the type object including setting type of the new type - * object; doing it here is required for portability, too. */ - if (PyType_Ready(&Xxo_Type) < 0) - goto fail; - - /* Create the module and add the functions */ - m = PyModule_Create(&xxmodule); - if (m == NULL) - goto fail; - - /* Add some symbolic constants to the module */ - if (ErrorObject == NULL) { - ErrorObject = PyErr_NewException("xx.error", NULL, NULL); - if (ErrorObject == NULL) - goto fail; - } - Py_INCREF(ErrorObject); - PyModule_AddObject(m, "error", ErrorObject); - - /* Add Str */ - if (PyType_Ready(&Str_Type) < 0) - goto fail; - PyModule_AddObject(m, "Str", (PyObject *)&Str_Type); - - /* Add Null */ - if (PyType_Ready(&Null_Type) < 0) - goto fail; - PyModule_AddObject(m, "Null", (PyObject *)&Null_Type); - return m; + /* Due to cross platform compiler issues the slots must be filled + * here. It's required for portability to Windows without requiring + * C++. */ + Null_Type.tp_base = &PyBaseObject_Type; + Null_Type.tp_new = PyType_GenericNew; + Str_Type.tp_base = &PyUnicode_Type; + + /* Finalize the type object including setting type of the new type + * object; doing it here is required for portability, too. */ + if (PyType_Ready(&Xxo_Type) < 0) + goto fail; + + /* Create the module and add the functions */ + m = PyModule_Create(&xxmodule); + if (m == NULL) + goto fail; + + /* Add some symbolic constants to the module */ + if (ErrorObject == NULL) { + ErrorObject = PyErr_NewException("xx.error", NULL, NULL); + if (ErrorObject == NULL) + goto fail; + } + Py_INCREF(ErrorObject); + PyModule_AddObject(m, "error", ErrorObject); + + /* Add Str */ + if (PyType_Ready(&Str_Type) < 0) + goto fail; + PyModule_AddObject(m, "Str", (PyObject *)&Str_Type); + + /* Add Null */ + if (PyType_Ready(&Null_Type) < 0) + goto fail; + PyModule_AddObject(m, "Null", (PyObject *)&Null_Type); + return m; fail: - Py_XDECREF(m); - return NULL; + Py_XDECREF(m); + return NULL; } Modified: python/branches/release31-maint/Modules/xxsubtype.c ============================================================================== --- python/branches/release31-maint/Modules/xxsubtype.c (original) +++ python/branches/release31-maint/Modules/xxsubtype.c Sun May 9 18:14:21 2010 @@ -19,291 +19,291 @@ /* spamlist -- a list subtype */ typedef struct { - PyListObject list; - int state; + PyListObject list; + int state; } spamlistobject; static PyObject * spamlist_getstate(spamlistobject *self, PyObject *args) { - if (!PyArg_ParseTuple(args, ":getstate")) - return NULL; - return PyLong_FromLong(self->state); + if (!PyArg_ParseTuple(args, ":getstate")) + return NULL; + return PyLong_FromLong(self->state); } static PyObject * spamlist_setstate(spamlistobject *self, PyObject *args) { - int state; + int state; - if (!PyArg_ParseTuple(args, "i:setstate", &state)) - return NULL; - self->state = state; - Py_INCREF(Py_None); - return Py_None; + if (!PyArg_ParseTuple(args, "i:setstate", &state)) + return NULL; + self->state = state; + Py_INCREF(Py_None); + return Py_None; } static PyObject * spamlist_specialmeth(PyObject *self, PyObject *args, PyObject *kw) { - PyObject *result = PyTuple_New(3); + PyObject *result = PyTuple_New(3); - if (result != NULL) { - if (self == NULL) - self = Py_None; - if (kw == NULL) - kw = Py_None; - Py_INCREF(self); - PyTuple_SET_ITEM(result, 0, self); - Py_INCREF(args); - PyTuple_SET_ITEM(result, 1, args); - Py_INCREF(kw); - PyTuple_SET_ITEM(result, 2, kw); - } - return result; + if (result != NULL) { + if (self == NULL) + self = Py_None; + if (kw == NULL) + kw = Py_None; + Py_INCREF(self); + PyTuple_SET_ITEM(result, 0, self); + Py_INCREF(args); + PyTuple_SET_ITEM(result, 1, args); + Py_INCREF(kw); + PyTuple_SET_ITEM(result, 2, kw); + } + return result; } static PyMethodDef spamlist_methods[] = { - {"getstate", (PyCFunction)spamlist_getstate, METH_VARARGS, - PyDoc_STR("getstate() -> state")}, - {"setstate", (PyCFunction)spamlist_setstate, METH_VARARGS, - PyDoc_STR("setstate(state)")}, - /* These entries differ only in the flags; they are used by the tests - in test.test_descr. */ - {"classmeth", (PyCFunction)spamlist_specialmeth, - METH_VARARGS | METH_KEYWORDS | METH_CLASS, - PyDoc_STR("classmeth(*args, **kw)")}, - {"staticmeth", (PyCFunction)spamlist_specialmeth, - METH_VARARGS | METH_KEYWORDS | METH_STATIC, - PyDoc_STR("staticmeth(*args, **kw)")}, - {NULL, NULL}, + {"getstate", (PyCFunction)spamlist_getstate, METH_VARARGS, + PyDoc_STR("getstate() -> state")}, + {"setstate", (PyCFunction)spamlist_setstate, METH_VARARGS, + PyDoc_STR("setstate(state)")}, + /* These entries differ only in the flags; they are used by the tests + in test.test_descr. */ + {"classmeth", (PyCFunction)spamlist_specialmeth, + METH_VARARGS | METH_KEYWORDS | METH_CLASS, + PyDoc_STR("classmeth(*args, **kw)")}, + {"staticmeth", (PyCFunction)spamlist_specialmeth, + METH_VARARGS | METH_KEYWORDS | METH_STATIC, + PyDoc_STR("staticmeth(*args, **kw)")}, + {NULL, NULL}, }; static int spamlist_init(spamlistobject *self, PyObject *args, PyObject *kwds) { - if (PyList_Type.tp_init((PyObject *)self, args, kwds) < 0) - return -1; - self->state = 0; - return 0; + if (PyList_Type.tp_init((PyObject *)self, args, kwds) < 0) + return -1; + self->state = 0; + return 0; } static PyObject * spamlist_state_get(spamlistobject *self) { - return PyLong_FromLong(self->state); + return PyLong_FromLong(self->state); } static PyGetSetDef spamlist_getsets[] = { - {"state", (getter)spamlist_state_get, NULL, - PyDoc_STR("an int variable for demonstration purposes")}, - {0} + {"state", (getter)spamlist_state_get, NULL, + PyDoc_STR("an int variable for demonstration purposes")}, + {0} }; static PyTypeObject spamlist_type = { - PyVarObject_HEAD_INIT(DEFERRED_ADDRESS(&PyType_Type), 0) - "xxsubtype.spamlist", - sizeof(spamlistobject), - 0, - 0, /* tp_dealloc */ - 0, /* tp_print */ - 0, /* tp_getattr */ - 0, /* tp_setattr */ - 0, /* tp_reserved */ - 0, /* tp_repr */ - 0, /* tp_as_number */ - 0, /* tp_as_sequence */ - 0, /* tp_as_mapping */ - 0, /* tp_hash */ - 0, /* tp_call */ - 0, /* tp_str */ - 0, /* tp_getattro */ - 0, /* tp_setattro */ - 0, /* tp_as_buffer */ - Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */ - 0, /* tp_doc */ - 0, /* tp_traverse */ - 0, /* tp_clear */ - 0, /* tp_richcompare */ - 0, /* tp_weaklistoffset */ - 0, /* tp_iter */ - 0, /* tp_iternext */ - spamlist_methods, /* tp_methods */ - 0, /* tp_members */ - spamlist_getsets, /* tp_getset */ - DEFERRED_ADDRESS(&PyList_Type), /* tp_base */ - 0, /* tp_dict */ - 0, /* tp_descr_get */ - 0, /* tp_descr_set */ - 0, /* tp_dictoffset */ - (initproc)spamlist_init, /* tp_init */ - 0, /* tp_alloc */ - 0, /* tp_new */ + PyVarObject_HEAD_INIT(DEFERRED_ADDRESS(&PyType_Type), 0) + "xxsubtype.spamlist", + sizeof(spamlistobject), + 0, + 0, /* tp_dealloc */ + 0, /* tp_print */ + 0, /* tp_getattr */ + 0, /* tp_setattr */ + 0, /* tp_reserved */ + 0, /* tp_repr */ + 0, /* tp_as_number */ + 0, /* tp_as_sequence */ + 0, /* tp_as_mapping */ + 0, /* tp_hash */ + 0, /* tp_call */ + 0, /* tp_str */ + 0, /* tp_getattro */ + 0, /* tp_setattro */ + 0, /* tp_as_buffer */ + Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */ + 0, /* tp_doc */ + 0, /* tp_traverse */ + 0, /* tp_clear */ + 0, /* tp_richcompare */ + 0, /* tp_weaklistoffset */ + 0, /* tp_iter */ + 0, /* tp_iternext */ + spamlist_methods, /* tp_methods */ + 0, /* tp_members */ + spamlist_getsets, /* tp_getset */ + DEFERRED_ADDRESS(&PyList_Type), /* tp_base */ + 0, /* tp_dict */ + 0, /* tp_descr_get */ + 0, /* tp_descr_set */ + 0, /* tp_dictoffset */ + (initproc)spamlist_init, /* tp_init */ + 0, /* tp_alloc */ + 0, /* tp_new */ }; /* spamdict -- a dict subtype */ typedef struct { - PyDictObject dict; - int state; + PyDictObject dict; + int state; } spamdictobject; static PyObject * spamdict_getstate(spamdictobject *self, PyObject *args) { - if (!PyArg_ParseTuple(args, ":getstate")) - return NULL; - return PyLong_FromLong(self->state); + if (!PyArg_ParseTuple(args, ":getstate")) + return NULL; + return PyLong_FromLong(self->state); } static PyObject * spamdict_setstate(spamdictobject *self, PyObject *args) { - int state; + int state; - if (!PyArg_ParseTuple(args, "i:setstate", &state)) - return NULL; - self->state = state; - Py_INCREF(Py_None); - return Py_None; + if (!PyArg_ParseTuple(args, "i:setstate", &state)) + return NULL; + self->state = state; + Py_INCREF(Py_None); + return Py_None; } static PyMethodDef spamdict_methods[] = { - {"getstate", (PyCFunction)spamdict_getstate, METH_VARARGS, - PyDoc_STR("getstate() -> state")}, - {"setstate", (PyCFunction)spamdict_setstate, METH_VARARGS, - PyDoc_STR("setstate(state)")}, - {NULL, NULL}, + {"getstate", (PyCFunction)spamdict_getstate, METH_VARARGS, + PyDoc_STR("getstate() -> state")}, + {"setstate", (PyCFunction)spamdict_setstate, METH_VARARGS, + PyDoc_STR("setstate(state)")}, + {NULL, NULL}, }; static int spamdict_init(spamdictobject *self, PyObject *args, PyObject *kwds) { - if (PyDict_Type.tp_init((PyObject *)self, args, kwds) < 0) - return -1; - self->state = 0; - return 0; + if (PyDict_Type.tp_init((PyObject *)self, args, kwds) < 0) + return -1; + self->state = 0; + return 0; } static PyMemberDef spamdict_members[] = { - {"state", T_INT, offsetof(spamdictobject, state), READONLY, - PyDoc_STR("an int variable for demonstration purposes")}, - {0} + {"state", T_INT, offsetof(spamdictobject, state), READONLY, + PyDoc_STR("an int variable for demonstration purposes")}, + {0} }; static PyTypeObject spamdict_type = { - PyVarObject_HEAD_INIT(DEFERRED_ADDRESS(&PyType_Type), 0) - "xxsubtype.spamdict", - sizeof(spamdictobject), - 0, - 0, /* tp_dealloc */ - 0, /* tp_print */ - 0, /* tp_getattr */ - 0, /* tp_setattr */ - 0, /* tp_reserved */ - 0, /* tp_repr */ - 0, /* tp_as_number */ - 0, /* tp_as_sequence */ - 0, /* tp_as_mapping */ - 0, /* tp_hash */ - 0, /* tp_call */ - 0, /* tp_str */ - 0, /* tp_getattro */ - 0, /* tp_setattro */ - 0, /* tp_as_buffer */ - Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */ - 0, /* tp_doc */ - 0, /* tp_traverse */ - 0, /* tp_clear */ - 0, /* tp_richcompare */ - 0, /* tp_weaklistoffset */ - 0, /* tp_iter */ - 0, /* tp_iternext */ - spamdict_methods, /* tp_methods */ - spamdict_members, /* tp_members */ - 0, /* tp_getset */ - DEFERRED_ADDRESS(&PyDict_Type), /* tp_base */ - 0, /* tp_dict */ - 0, /* tp_descr_get */ - 0, /* tp_descr_set */ - 0, /* tp_dictoffset */ - (initproc)spamdict_init, /* tp_init */ - 0, /* tp_alloc */ - 0, /* tp_new */ + PyVarObject_HEAD_INIT(DEFERRED_ADDRESS(&PyType_Type), 0) + "xxsubtype.spamdict", + sizeof(spamdictobject), + 0, + 0, /* tp_dealloc */ + 0, /* tp_print */ + 0, /* tp_getattr */ + 0, /* tp_setattr */ + 0, /* tp_reserved */ + 0, /* tp_repr */ + 0, /* tp_as_number */ + 0, /* tp_as_sequence */ + 0, /* tp_as_mapping */ + 0, /* tp_hash */ + 0, /* tp_call */ + 0, /* tp_str */ + 0, /* tp_getattro */ + 0, /* tp_setattro */ + 0, /* tp_as_buffer */ + Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */ + 0, /* tp_doc */ + 0, /* tp_traverse */ + 0, /* tp_clear */ + 0, /* tp_richcompare */ + 0, /* tp_weaklistoffset */ + 0, /* tp_iter */ + 0, /* tp_iternext */ + spamdict_methods, /* tp_methods */ + spamdict_members, /* tp_members */ + 0, /* tp_getset */ + DEFERRED_ADDRESS(&PyDict_Type), /* tp_base */ + 0, /* tp_dict */ + 0, /* tp_descr_get */ + 0, /* tp_descr_set */ + 0, /* tp_dictoffset */ + (initproc)spamdict_init, /* tp_init */ + 0, /* tp_alloc */ + 0, /* tp_new */ }; static PyObject * spam_bench(PyObject *self, PyObject *args) { - PyObject *obj, *name, *res; - int n = 1000; - time_t t0, t1; - - if (!PyArg_ParseTuple(args, "OS|i", &obj, &name, &n)) - return NULL; - t0 = clock(); - while (--n >= 0) { - res = PyObject_GetAttr(obj, name); - if (res == NULL) - return NULL; - Py_DECREF(res); - } - t1 = clock(); - return PyFloat_FromDouble((double)(t1-t0) / CLOCKS_PER_SEC); + PyObject *obj, *name, *res; + int n = 1000; + time_t t0, t1; + + if (!PyArg_ParseTuple(args, "OS|i", &obj, &name, &n)) + return NULL; + t0 = clock(); + while (--n >= 0) { + res = PyObject_GetAttr(obj, name); + if (res == NULL) + return NULL; + Py_DECREF(res); + } + t1 = clock(); + return PyFloat_FromDouble((double)(t1-t0) / CLOCKS_PER_SEC); } static PyMethodDef xxsubtype_functions[] = { - {"bench", spam_bench, METH_VARARGS}, - {NULL, NULL} /* sentinel */ + {"bench", spam_bench, METH_VARARGS}, + {NULL, NULL} /* sentinel */ }; static struct PyModuleDef xxsubtypemodule = { - PyModuleDef_HEAD_INIT, - "xxsubtype", - xxsubtype__doc__, - -1, - xxsubtype_functions, - NULL, - NULL, - NULL, - NULL + PyModuleDef_HEAD_INIT, + "xxsubtype", + xxsubtype__doc__, + -1, + xxsubtype_functions, + NULL, + NULL, + NULL, + NULL }; PyMODINIT_FUNC PyInit_xxsubtype(void) { - PyObject *m; + PyObject *m; - /* Fill in deferred data addresses. This must be done before - PyType_Ready() is called. Note that PyType_Ready() automatically - initializes the ob.ob_type field to &PyType_Type if it's NULL, - so it's not necessary to fill in ob_type first. */ - spamdict_type.tp_base = &PyDict_Type; - if (PyType_Ready(&spamdict_type) < 0) - return NULL; - - spamlist_type.tp_base = &PyList_Type; - if (PyType_Ready(&spamlist_type) < 0) - return NULL; - - m = PyModule_Create(&xxsubtypemodule); - if (m == NULL) - return NULL; - - if (PyType_Ready(&spamlist_type) < 0) - return NULL; - if (PyType_Ready(&spamdict_type) < 0) - return NULL; - - Py_INCREF(&spamlist_type); - if (PyModule_AddObject(m, "spamlist", - (PyObject *) &spamlist_type) < 0) - return NULL; - - Py_INCREF(&spamdict_type); - if (PyModule_AddObject(m, "spamdict", - (PyObject *) &spamdict_type) < 0) - return NULL; - return m; + /* Fill in deferred data addresses. This must be done before + PyType_Ready() is called. Note that PyType_Ready() automatically + initializes the ob.ob_type field to &PyType_Type if it's NULL, + so it's not necessary to fill in ob_type first. */ + spamdict_type.tp_base = &PyDict_Type; + if (PyType_Ready(&spamdict_type) < 0) + return NULL; + + spamlist_type.tp_base = &PyList_Type; + if (PyType_Ready(&spamlist_type) < 0) + return NULL; + + m = PyModule_Create(&xxsubtypemodule); + if (m == NULL) + return NULL; + + if (PyType_Ready(&spamlist_type) < 0) + return NULL; + if (PyType_Ready(&spamdict_type) < 0) + return NULL; + + Py_INCREF(&spamlist_type); + if (PyModule_AddObject(m, "spamlist", + (PyObject *) &spamlist_type) < 0) + return NULL; + + Py_INCREF(&spamdict_type); + if (PyModule_AddObject(m, "spamdict", + (PyObject *) &spamdict_type) < 0) + return NULL; + return m; } Modified: python/branches/release31-maint/Modules/zipimport.c ============================================================================== --- python/branches/release31-maint/Modules/zipimport.c (original) +++ python/branches/release31-maint/Modules/zipimport.c Sun May 9 18:14:21 2010 @@ -10,8 +10,8 @@ #define IS_PACKAGE 0x2 struct st_zip_searchorder { - char suffix[14]; - int type; + char suffix[14]; + int type; }; /* zip_searchorder defines how we search for a module in the Zip @@ -20,13 +20,13 @@ are swapped by initzipimport() if we run in optimized mode. Also, '/' is replaced by SEP there. */ static struct st_zip_searchorder zip_searchorder[] = { - {"/__init__.pyc", IS_PACKAGE | IS_BYTECODE}, - {"/__init__.pyo", IS_PACKAGE | IS_BYTECODE}, - {"/__init__.py", IS_PACKAGE | IS_SOURCE}, - {".pyc", IS_BYTECODE}, - {".pyo", IS_BYTECODE}, - {".py", IS_SOURCE}, - {"", 0} + {"/__init__.pyc", IS_PACKAGE | IS_BYTECODE}, + {"/__init__.pyo", IS_PACKAGE | IS_BYTECODE}, + {"/__init__.py", IS_PACKAGE | IS_SOURCE}, + {".pyc", IS_BYTECODE}, + {".pyo", IS_BYTECODE}, + {".py", IS_SOURCE}, + {"", 0} }; /* zipimporter object definition and support */ @@ -34,10 +34,10 @@ typedef struct _zipimporter ZipImporter; struct _zipimporter { - PyObject_HEAD - PyObject *archive; /* pathname of the Zip archive */ - PyObject *prefix; /* file prefix: "a/sub/directory/" */ - PyObject *files; /* dict with file info {path: toc_entry} */ + PyObject_HEAD + PyObject *archive; /* pathname of the Zip archive */ + PyObject *prefix; /* file prefix: "a/sub/directory/" */ + PyObject *files; /* dict with file info {path: toc_entry} */ }; static PyObject *ZipImportError; @@ -47,7 +47,7 @@ static PyObject *read_directory(char *archive); static PyObject *get_data(char *archive, PyObject *toc_entry); static PyObject *get_module_code(ZipImporter *self, char *fullname, - int *p_ispackage, char **p_modpath); + int *p_ispackage, char **p_modpath); #define ZipImporter_Check(op) PyObject_TypeCheck(op, &ZipImporter_Type) @@ -60,147 +60,147 @@ static int zipimporter_init(ZipImporter *self, PyObject *args, PyObject *kwds) { - char *path, *p, *prefix, buf[MAXPATHLEN+2]; - size_t len; + char *path, *p, *prefix, buf[MAXPATHLEN+2]; + size_t len; - if (!_PyArg_NoKeywords("zipimporter()", kwds)) - return -1; + if (!_PyArg_NoKeywords("zipimporter()", kwds)) + return -1; - if (!PyArg_ParseTuple(args, "s:zipimporter", &path)) - return -1; + if (!PyArg_ParseTuple(args, "s:zipimporter", &path)) + return -1; - len = strlen(path); - if (len == 0) { - PyErr_SetString(ZipImportError, "archive path is empty"); - return -1; - } - if (len >= MAXPATHLEN) { - PyErr_SetString(ZipImportError, - "archive path too long"); - return -1; - } - strcpy(buf, path); + len = strlen(path); + if (len == 0) { + PyErr_SetString(ZipImportError, "archive path is empty"); + return -1; + } + if (len >= MAXPATHLEN) { + PyErr_SetString(ZipImportError, + "archive path too long"); + return -1; + } + strcpy(buf, path); #ifdef ALTSEP - for (p = buf; *p; p++) { - if (*p == ALTSEP) - *p = SEP; - } + for (p = buf; *p; p++) { + if (*p == ALTSEP) + *p = SEP; + } #endif - path = NULL; - prefix = NULL; - for (;;) { - struct stat statbuf; - int rv; - - rv = stat(buf, &statbuf); - if (rv == 0) { - /* it exists */ - if (S_ISREG(statbuf.st_mode)) - /* it's a file */ - path = buf; - break; - } - /* back up one path element */ - p = strrchr(buf, SEP); - if (prefix != NULL) - *prefix = SEP; - if (p == NULL) - break; - *p = '\0'; - prefix = p; - } - if (path != NULL) { - PyObject *files; - files = PyDict_GetItemString(zip_directory_cache, path); - if (files == NULL) { - files = read_directory(buf); - if (files == NULL) - return -1; - if (PyDict_SetItemString(zip_directory_cache, path, - files) != 0) - return -1; - } - else - Py_INCREF(files); - self->files = files; - } - else { - PyErr_SetString(ZipImportError, "not a Zip file"); - return -1; - } - - if (prefix == NULL) - prefix = ""; - else { - prefix++; - len = strlen(prefix); - if (prefix[len-1] != SEP) { - /* add trailing SEP */ - prefix[len] = SEP; - prefix[len + 1] = '\0'; - } - } - - self->archive = PyUnicode_FromString(buf); - if (self->archive == NULL) - return -1; - - self->prefix = PyUnicode_FromString(prefix); - if (self->prefix == NULL) - return -1; + path = NULL; + prefix = NULL; + for (;;) { + struct stat statbuf; + int rv; + + rv = stat(buf, &statbuf); + if (rv == 0) { + /* it exists */ + if (S_ISREG(statbuf.st_mode)) + /* it's a file */ + path = buf; + break; + } + /* back up one path element */ + p = strrchr(buf, SEP); + if (prefix != NULL) + *prefix = SEP; + if (p == NULL) + break; + *p = '\0'; + prefix = p; + } + if (path != NULL) { + PyObject *files; + files = PyDict_GetItemString(zip_directory_cache, path); + if (files == NULL) { + files = read_directory(buf); + if (files == NULL) + return -1; + if (PyDict_SetItemString(zip_directory_cache, path, + files) != 0) + return -1; + } + else + Py_INCREF(files); + self->files = files; + } + else { + PyErr_SetString(ZipImportError, "not a Zip file"); + return -1; + } + + if (prefix == NULL) + prefix = ""; + else { + prefix++; + len = strlen(prefix); + if (prefix[len-1] != SEP) { + /* add trailing SEP */ + prefix[len] = SEP; + prefix[len + 1] = '\0'; + } + } + + self->archive = PyUnicode_FromString(buf); + if (self->archive == NULL) + return -1; + + self->prefix = PyUnicode_FromString(prefix); + if (self->prefix == NULL) + return -1; - return 0; + return 0; } /* GC support. */ static int zipimporter_traverse(PyObject *obj, visitproc visit, void *arg) { - ZipImporter *self = (ZipImporter *)obj; - Py_VISIT(self->files); - return 0; + ZipImporter *self = (ZipImporter *)obj; + Py_VISIT(self->files); + return 0; } static void zipimporter_dealloc(ZipImporter *self) { - PyObject_GC_UnTrack(self); - Py_XDECREF(self->archive); - Py_XDECREF(self->prefix); - Py_XDECREF(self->files); - Py_TYPE(self)->tp_free((PyObject *)self); + PyObject_GC_UnTrack(self); + Py_XDECREF(self->archive); + Py_XDECREF(self->prefix); + Py_XDECREF(self->files); + Py_TYPE(self)->tp_free((PyObject *)self); } static PyObject * zipimporter_repr(ZipImporter *self) { - char *archive = "???"; - char *prefix = ""; + char *archive = "???"; + char *prefix = ""; - if (self->archive != NULL && PyUnicode_Check(self->archive)) - archive = _PyUnicode_AsString(self->archive); - if (self->prefix != NULL && PyUnicode_Check(self->prefix)) - prefix = _PyUnicode_AsString(self->prefix); - if (prefix != NULL && *prefix) - return PyUnicode_FromFormat("", - archive, SEP, prefix); - else - return PyUnicode_FromFormat("", - archive); + if (self->archive != NULL && PyUnicode_Check(self->archive)) + archive = _PyUnicode_AsString(self->archive); + if (self->prefix != NULL && PyUnicode_Check(self->prefix)) + prefix = _PyUnicode_AsString(self->prefix); + if (prefix != NULL && *prefix) + return PyUnicode_FromFormat("", + archive, SEP, prefix); + else + return PyUnicode_FromFormat("", + archive); } /* return fullname.split(".")[-1] */ static char * get_subname(char *fullname) { - char *subname = strrchr(fullname, '.'); - if (subname == NULL) - subname = fullname; - else - subname++; - return subname; + char *subname = strrchr(fullname, '.'); + if (subname == NULL) + subname = fullname; + else + subname++; + return subname; } /* Given a (sub)modulename, write the potential file path in the @@ -209,59 +209,59 @@ static int make_filename(char *prefix, char *name, char *path) { - size_t len; - char *p; + size_t len; + char *p; - len = strlen(prefix); + len = strlen(prefix); - /* self.prefix + name [+ SEP + "__init__"] + ".py[co]" */ - if (len + strlen(name) + 13 >= MAXPATHLEN) { - PyErr_SetString(ZipImportError, "path too long"); - return -1; - } - - strcpy(path, prefix); - strcpy(path + len, name); - for (p = path + len; *p; p++) { - if (*p == '.') - *p = SEP; - } - len += strlen(name); - assert(len < INT_MAX); - return (int)len; + /* self.prefix + name [+ SEP + "__init__"] + ".py[co]" */ + if (len + strlen(name) + 13 >= MAXPATHLEN) { + PyErr_SetString(ZipImportError, "path too long"); + return -1; + } + + strcpy(path, prefix); + strcpy(path + len, name); + for (p = path + len; *p; p++) { + if (*p == '.') + *p = SEP; + } + len += strlen(name); + assert(len < INT_MAX); + return (int)len; } enum zi_module_info { - MI_ERROR, - MI_NOT_FOUND, - MI_MODULE, - MI_PACKAGE + MI_ERROR, + MI_NOT_FOUND, + MI_MODULE, + MI_PACKAGE }; /* Return some information about a module. */ static enum zi_module_info get_module_info(ZipImporter *self, char *fullname) { - char *subname, path[MAXPATHLEN + 1]; - int len; - struct st_zip_searchorder *zso; - - subname = get_subname(fullname); - - len = make_filename(_PyUnicode_AsString(self->prefix), subname, path); - if (len < 0) - return MI_ERROR; - - for (zso = zip_searchorder; *zso->suffix; zso++) { - strcpy(path + len, zso->suffix); - if (PyDict_GetItemString(self->files, path) != NULL) { - if (zso->type & IS_PACKAGE) - return MI_PACKAGE; - else - return MI_MODULE; - } - } - return MI_NOT_FOUND; + char *subname, path[MAXPATHLEN + 1]; + int len; + struct st_zip_searchorder *zso; + + subname = get_subname(fullname); + + len = make_filename(_PyUnicode_AsString(self->prefix), subname, path); + if (len < 0) + return MI_ERROR; + + for (zso = zip_searchorder; *zso->suffix; zso++) { + strcpy(path + len, zso->suffix); + if (PyDict_GetItemString(self->files, path) != NULL) { + if (zso->type & IS_PACKAGE) + return MI_PACKAGE; + else + return MI_MODULE; + } + } + return MI_NOT_FOUND; } /* Check whether we can satisfy the import of the module named by @@ -269,86 +269,86 @@ static PyObject * zipimporter_find_module(PyObject *obj, PyObject *args) { - ZipImporter *self = (ZipImporter *)obj; - PyObject *path = NULL; - char *fullname; - enum zi_module_info mi; - - if (!PyArg_ParseTuple(args, "s|O:zipimporter.find_module", - &fullname, &path)) - return NULL; - - mi = get_module_info(self, fullname); - if (mi == MI_ERROR) - return NULL; - if (mi == MI_NOT_FOUND) { - Py_INCREF(Py_None); - return Py_None; - } - Py_INCREF(self); - return (PyObject *)self; + ZipImporter *self = (ZipImporter *)obj; + PyObject *path = NULL; + char *fullname; + enum zi_module_info mi; + + if (!PyArg_ParseTuple(args, "s|O:zipimporter.find_module", + &fullname, &path)) + return NULL; + + mi = get_module_info(self, fullname); + if (mi == MI_ERROR) + return NULL; + if (mi == MI_NOT_FOUND) { + Py_INCREF(Py_None); + return Py_None; + } + Py_INCREF(self); + return (PyObject *)self; } /* Load and return the module named by 'fullname'. */ static PyObject * zipimporter_load_module(PyObject *obj, PyObject *args) { - ZipImporter *self = (ZipImporter *)obj; - PyObject *code, *mod, *dict; - char *fullname, *modpath; - int ispackage; - - if (!PyArg_ParseTuple(args, "s:zipimporter.load_module", - &fullname)) - return NULL; - - code = get_module_code(self, fullname, &ispackage, &modpath); - if (code == NULL) - return NULL; - - mod = PyImport_AddModule(fullname); - if (mod == NULL) { - Py_DECREF(code); - return NULL; - } - dict = PyModule_GetDict(mod); - - /* mod.__loader__ = self */ - if (PyDict_SetItemString(dict, "__loader__", (PyObject *)self) != 0) - goto error; - - if (ispackage) { - /* add __path__ to the module *before* the code gets - executed */ - PyObject *pkgpath, *fullpath; - char *subname = get_subname(fullname); - int err; - - fullpath = PyUnicode_FromFormat("%U%c%U%s", - self->archive, SEP, - self->prefix, subname); - if (fullpath == NULL) - goto error; - - pkgpath = Py_BuildValue("[O]", fullpath); - Py_DECREF(fullpath); - if (pkgpath == NULL) - goto error; - err = PyDict_SetItemString(dict, "__path__", pkgpath); - Py_DECREF(pkgpath); - if (err != 0) - goto error; - } - mod = PyImport_ExecCodeModuleEx(fullname, code, modpath); - Py_DECREF(code); - if (Py_VerboseFlag) - PySys_WriteStderr("import %s # loaded from Zip %s\n", - fullname, modpath); - return mod; + ZipImporter *self = (ZipImporter *)obj; + PyObject *code, *mod, *dict; + char *fullname, *modpath; + int ispackage; + + if (!PyArg_ParseTuple(args, "s:zipimporter.load_module", + &fullname)) + return NULL; + + code = get_module_code(self, fullname, &ispackage, &modpath); + if (code == NULL) + return NULL; + + mod = PyImport_AddModule(fullname); + if (mod == NULL) { + Py_DECREF(code); + return NULL; + } + dict = PyModule_GetDict(mod); + + /* mod.__loader__ = self */ + if (PyDict_SetItemString(dict, "__loader__", (PyObject *)self) != 0) + goto error; + + if (ispackage) { + /* add __path__ to the module *before* the code gets + executed */ + PyObject *pkgpath, *fullpath; + char *subname = get_subname(fullname); + int err; + + fullpath = PyUnicode_FromFormat("%U%c%U%s", + self->archive, SEP, + self->prefix, subname); + if (fullpath == NULL) + goto error; + + pkgpath = Py_BuildValue("[O]", fullpath); + Py_DECREF(fullpath); + if (pkgpath == NULL) + goto error; + err = PyDict_SetItemString(dict, "__path__", pkgpath); + Py_DECREF(pkgpath); + if (err != 0) + goto error; + } + mod = PyImport_ExecCodeModuleEx(fullname, code, modpath); + Py_DECREF(code); + if (Py_VerboseFlag) + PySys_WriteStderr("import %s # loaded from Zip %s\n", + fullname, modpath); + return mod; error: - Py_DECREF(code); - Py_DECREF(mod); - return NULL; + Py_DECREF(code); + Py_DECREF(mod); + return NULL; } /* Return a string matching __file__ for the named module */ @@ -362,13 +362,13 @@ if (!PyArg_ParseTuple(args, "s:zipimporter.get_filename", &fullname)) - return NULL; + return NULL; /* Deciding the filename requires working out where the code would come from if the module was actually loaded */ code = get_module_code(self, fullname, &ispackage, &modpath); if (code == NULL) - return NULL; + return NULL; Py_DECREF(code); /* Only need the path info */ return PyUnicode_FromString(modpath); @@ -378,123 +378,123 @@ static PyObject * zipimporter_is_package(PyObject *obj, PyObject *args) { - ZipImporter *self = (ZipImporter *)obj; - char *fullname; - enum zi_module_info mi; - - if (!PyArg_ParseTuple(args, "s:zipimporter.is_package", - &fullname)) - return NULL; - - mi = get_module_info(self, fullname); - if (mi == MI_ERROR) - return NULL; - if (mi == MI_NOT_FOUND) { - PyErr_Format(ZipImportError, "can't find module '%.200s'", - fullname); - return NULL; - } - return PyBool_FromLong(mi == MI_PACKAGE); + ZipImporter *self = (ZipImporter *)obj; + char *fullname; + enum zi_module_info mi; + + if (!PyArg_ParseTuple(args, "s:zipimporter.is_package", + &fullname)) + return NULL; + + mi = get_module_info(self, fullname); + if (mi == MI_ERROR) + return NULL; + if (mi == MI_NOT_FOUND) { + PyErr_Format(ZipImportError, "can't find module '%.200s'", + fullname); + return NULL; + } + return PyBool_FromLong(mi == MI_PACKAGE); } static PyObject * zipimporter_get_data(PyObject *obj, PyObject *args) { - ZipImporter *self = (ZipImporter *)obj; - char *path; + ZipImporter *self = (ZipImporter *)obj; + char *path; #ifdef ALTSEP - char *p, buf[MAXPATHLEN + 1]; + char *p, buf[MAXPATHLEN + 1]; #endif - PyObject *toc_entry; - Py_ssize_t len; - char *archive_str; + PyObject *toc_entry; + Py_ssize_t len; + char *archive_str; - if (!PyArg_ParseTuple(args, "s:zipimporter.get_data", &path)) - return NULL; + if (!PyArg_ParseTuple(args, "s:zipimporter.get_data", &path)) + return NULL; #ifdef ALTSEP - if (strlen(path) >= MAXPATHLEN) { - PyErr_SetString(ZipImportError, "path too long"); - return NULL; - } - strcpy(buf, path); - for (p = buf; *p; p++) { - if (*p == ALTSEP) - *p = SEP; - } - path = buf; + if (strlen(path) >= MAXPATHLEN) { + PyErr_SetString(ZipImportError, "path too long"); + return NULL; + } + strcpy(buf, path); + for (p = buf; *p; p++) { + if (*p == ALTSEP) + *p = SEP; + } + path = buf; #endif - archive_str = _PyUnicode_AsStringAndSize(self->archive, &len); - if ((size_t)len < strlen(path) && - strncmp(path, archive_str, len) == 0 && - path[len] == SEP) { - path = path + len + 1; - } - - toc_entry = PyDict_GetItemString(self->files, path); - if (toc_entry == NULL) { - PyErr_SetFromErrnoWithFilename(PyExc_IOError, path); - return NULL; - } - return get_data(archive_str, toc_entry); + archive_str = _PyUnicode_AsStringAndSize(self->archive, &len); + if ((size_t)len < strlen(path) && + strncmp(path, archive_str, len) == 0 && + path[len] == SEP) { + path = path + len + 1; + } + + toc_entry = PyDict_GetItemString(self->files, path); + if (toc_entry == NULL) { + PyErr_SetFromErrnoWithFilename(PyExc_IOError, path); + return NULL; + } + return get_data(archive_str, toc_entry); } static PyObject * zipimporter_get_code(PyObject *obj, PyObject *args) { - ZipImporter *self = (ZipImporter *)obj; - char *fullname; + ZipImporter *self = (ZipImporter *)obj; + char *fullname; - if (!PyArg_ParseTuple(args, "s:zipimporter.get_code", &fullname)) - return NULL; + if (!PyArg_ParseTuple(args, "s:zipimporter.get_code", &fullname)) + return NULL; - return get_module_code(self, fullname, NULL, NULL); + return get_module_code(self, fullname, NULL, NULL); } static PyObject * zipimporter_get_source(PyObject *obj, PyObject *args) { - ZipImporter *self = (ZipImporter *)obj; - PyObject *toc_entry; - char *fullname, *subname, path[MAXPATHLEN+1]; - int len; - enum zi_module_info mi; - - if (!PyArg_ParseTuple(args, "s:zipimporter.get_source", &fullname)) - return NULL; - - mi = get_module_info(self, fullname); - if (mi == MI_ERROR) - return NULL; - if (mi == MI_NOT_FOUND) { - PyErr_Format(ZipImportError, "can't find module '%.200s'", - fullname); - return NULL; - } - subname = get_subname(fullname); - - len = make_filename(_PyUnicode_AsString(self->prefix), subname, path); - if (len < 0) - return NULL; - - if (mi == MI_PACKAGE) { - path[len] = SEP; - strcpy(path + len + 1, "__init__.py"); - } - else - strcpy(path + len, ".py"); - - toc_entry = PyDict_GetItemString(self->files, path); - if (toc_entry != NULL) { - PyObject *bytes = get_data(_PyUnicode_AsString(self->archive), toc_entry); - PyObject *res = PyUnicode_FromString(PyBytes_AsString(bytes)); - Py_XDECREF(bytes); - return res; - } - - /* we have the module, but no source */ - Py_INCREF(Py_None); - return Py_None; + ZipImporter *self = (ZipImporter *)obj; + PyObject *toc_entry; + char *fullname, *subname, path[MAXPATHLEN+1]; + int len; + enum zi_module_info mi; + + if (!PyArg_ParseTuple(args, "s:zipimporter.get_source", &fullname)) + return NULL; + + mi = get_module_info(self, fullname); + if (mi == MI_ERROR) + return NULL; + if (mi == MI_NOT_FOUND) { + PyErr_Format(ZipImportError, "can't find module '%.200s'", + fullname); + return NULL; + } + subname = get_subname(fullname); + + len = make_filename(_PyUnicode_AsString(self->prefix), subname, path); + if (len < 0) + return NULL; + + if (mi == MI_PACKAGE) { + path[len] = SEP; + strcpy(path + len + 1, "__init__.py"); + } + else + strcpy(path + len, ".py"); + + toc_entry = PyDict_GetItemString(self->files, path); + if (toc_entry != NULL) { + PyObject *bytes = get_data(_PyUnicode_AsString(self->archive), toc_entry); + PyObject *res = PyUnicode_FromString(PyBytes_AsString(bytes)); + Py_XDECREF(bytes); + return res; + } + + /* we have the module, but no source */ + Py_INCREF(Py_None); + return Py_None; } PyDoc_STRVAR(doc_find_module, @@ -545,28 +545,28 @@ Return the filename for the specified module."); static PyMethodDef zipimporter_methods[] = { - {"find_module", zipimporter_find_module, METH_VARARGS, - doc_find_module}, - {"load_module", zipimporter_load_module, METH_VARARGS, - doc_load_module}, - {"get_data", zipimporter_get_data, METH_VARARGS, - doc_get_data}, - {"get_code", zipimporter_get_code, METH_VARARGS, - doc_get_code}, - {"get_source", zipimporter_get_source, METH_VARARGS, - doc_get_source}, - {"get_filename", zipimporter_get_filename, METH_VARARGS, - doc_get_filename}, - {"is_package", zipimporter_is_package, METH_VARARGS, - doc_is_package}, - {NULL, NULL} /* sentinel */ + {"find_module", zipimporter_find_module, METH_VARARGS, + doc_find_module}, + {"load_module", zipimporter_load_module, METH_VARARGS, + doc_load_module}, + {"get_data", zipimporter_get_data, METH_VARARGS, + doc_get_data}, + {"get_code", zipimporter_get_code, METH_VARARGS, + doc_get_code}, + {"get_source", zipimporter_get_source, METH_VARARGS, + doc_get_source}, + {"get_filename", zipimporter_get_filename, METH_VARARGS, + doc_get_filename}, + {"is_package", zipimporter_is_package, METH_VARARGS, + doc_is_package}, + {NULL, NULL} /* sentinel */ }; static PyMemberDef zipimporter_members[] = { - {"archive", T_OBJECT, offsetof(ZipImporter, archive), READONLY}, - {"prefix", T_OBJECT, offsetof(ZipImporter, prefix), READONLY}, - {"_files", T_OBJECT, offsetof(ZipImporter, files), READONLY}, - {NULL} + {"archive", T_OBJECT, offsetof(ZipImporter, archive), READONLY}, + {"prefix", T_OBJECT, offsetof(ZipImporter, prefix), READONLY}, + {"_files", T_OBJECT, offsetof(ZipImporter, files), READONLY}, + {NULL} }; PyDoc_STRVAR(zipimporter_doc, @@ -586,46 +586,46 @@ #define DEFERRED_ADDRESS(ADDR) 0 static PyTypeObject ZipImporter_Type = { - PyVarObject_HEAD_INIT(DEFERRED_ADDRESS(&PyType_Type), 0) - "zipimport.zipimporter", - sizeof(ZipImporter), - 0, /* tp_itemsize */ - (destructor)zipimporter_dealloc, /* tp_dealloc */ - 0, /* tp_print */ - 0, /* tp_getattr */ - 0, /* tp_setattr */ - 0, /* tp_reserved */ - (reprfunc)zipimporter_repr, /* 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_BASETYPE | - Py_TPFLAGS_HAVE_GC, /* tp_flags */ - zipimporter_doc, /* tp_doc */ - zipimporter_traverse, /* tp_traverse */ - 0, /* tp_clear */ - 0, /* tp_richcompare */ - 0, /* tp_weaklistoffset */ - 0, /* tp_iter */ - 0, /* tp_iternext */ - zipimporter_methods, /* tp_methods */ - zipimporter_members, /* tp_members */ - 0, /* tp_getset */ - 0, /* tp_base */ - 0, /* tp_dict */ - 0, /* tp_descr_get */ - 0, /* tp_descr_set */ - 0, /* tp_dictoffset */ - (initproc)zipimporter_init, /* tp_init */ - PyType_GenericAlloc, /* tp_alloc */ - PyType_GenericNew, /* tp_new */ - PyObject_GC_Del, /* tp_free */ + PyVarObject_HEAD_INIT(DEFERRED_ADDRESS(&PyType_Type), 0) + "zipimport.zipimporter", + sizeof(ZipImporter), + 0, /* tp_itemsize */ + (destructor)zipimporter_dealloc, /* tp_dealloc */ + 0, /* tp_print */ + 0, /* tp_getattr */ + 0, /* tp_setattr */ + 0, /* tp_reserved */ + (reprfunc)zipimporter_repr, /* 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_BASETYPE | + Py_TPFLAGS_HAVE_GC, /* tp_flags */ + zipimporter_doc, /* tp_doc */ + zipimporter_traverse, /* tp_traverse */ + 0, /* tp_clear */ + 0, /* tp_richcompare */ + 0, /* tp_weaklistoffset */ + 0, /* tp_iter */ + 0, /* tp_iternext */ + zipimporter_methods, /* tp_methods */ + zipimporter_members, /* tp_members */ + 0, /* tp_getset */ + 0, /* tp_base */ + 0, /* tp_dict */ + 0, /* tp_descr_get */ + 0, /* tp_descr_set */ + 0, /* tp_dictoffset */ + (initproc)zipimporter_init, /* tp_init */ + PyType_GenericAlloc, /* tp_alloc */ + PyType_GenericNew, /* tp_new */ + PyObject_GC_Del, /* tp_free */ }; @@ -636,16 +636,16 @@ marshal.c:r_long() */ static long get_long(unsigned char *buf) { - long x; - x = buf[0]; - x |= (long)buf[1] << 8; - x |= (long)buf[2] << 16; - x |= (long)buf[3] << 24; + long x; + x = buf[0]; + x |= (long)buf[1] << 8; + x |= (long)buf[2] << 16; + x |= (long)buf[3] << 24; #if SIZEOF_LONG > 4 - /* Sign extension for 64-bit machines */ - x |= -(x & 0x80000000L); + /* Sign extension for 64-bit machines */ + x |= -(x & 0x80000000L); #endif - return x; + return x; } /* @@ -657,13 +657,13 @@ A toc_entry is a tuple: (__file__, # value to use for __file__, available for all files - compress, # compression kind; 0 for uncompressed - data_size, # size of compressed data on disk - file_size, # size of decompressed data - file_offset, # offset of file header from start of archive - time, # mod time of file (in dos format) - date, # mod data of file (in dos format) - crc, # crc checksum of the data + compress, # compression kind; 0 for uncompressed + data_size, # size of compressed data on disk + file_size, # size of decompressed data + file_offset, # offset of file header from start of archive + time, # mod time of file (in dos format) + date, # mod data of file (in dos format) + crc, # crc checksum of the data ) Directories can be recognized by the trailing SEP in the name, @@ -672,115 +672,115 @@ static PyObject * read_directory(char *archive) { - PyObject *files = NULL; - FILE *fp; - long compress, crc, data_size, file_size, file_offset, date, time; - long header_offset, name_size, header_size, header_position; - long i, l, count; - size_t length; - char path[MAXPATHLEN + 5]; - char name[MAXPATHLEN + 5]; - char *p, endof_central_dir[22]; - long arc_offset; /* offset from beginning of file to start of zip-archive */ - - if (strlen(archive) > MAXPATHLEN) { - PyErr_SetString(PyExc_OverflowError, - "Zip path name is too long"); - return NULL; - } - strcpy(path, archive); - - fp = fopen(archive, "rb"); - if (fp == NULL) { - PyErr_Format(ZipImportError, "can't open Zip file: " - "'%.200s'", archive); - return NULL; - } - fseek(fp, -22, SEEK_END); - header_position = ftell(fp); - if (fread(endof_central_dir, 1, 22, fp) != 22) { - fclose(fp); - PyErr_Format(ZipImportError, "can't read Zip file: " - "'%.200s'", archive); - return NULL; - } - if (get_long((unsigned char *)endof_central_dir) != 0x06054B50) { - /* Bad: End of Central Dir signature */ - fclose(fp); - PyErr_Format(ZipImportError, "not a Zip file: " - "'%.200s'", archive); - return NULL; - } - - header_size = get_long((unsigned char *)endof_central_dir + 12); - header_offset = get_long((unsigned char *)endof_central_dir + 16); - arc_offset = header_position - header_offset - header_size; - header_offset += arc_offset; - - files = PyDict_New(); - if (files == NULL) - goto error; - - length = (long)strlen(path); - path[length] = SEP; - - /* Start of Central Directory */ - count = 0; - for (;;) { - PyObject *t; - int err; - - fseek(fp, header_offset, 0); /* Start of file header */ - l = PyMarshal_ReadLongFromFile(fp); - if (l != 0x02014B50) - break; /* Bad: Central Dir File Header */ - fseek(fp, header_offset + 10, 0); - compress = PyMarshal_ReadShortFromFile(fp); - time = PyMarshal_ReadShortFromFile(fp); - date = PyMarshal_ReadShortFromFile(fp); - crc = PyMarshal_ReadLongFromFile(fp); - data_size = PyMarshal_ReadLongFromFile(fp); - file_size = PyMarshal_ReadLongFromFile(fp); - name_size = PyMarshal_ReadShortFromFile(fp); - header_size = 46 + name_size + - PyMarshal_ReadShortFromFile(fp) + - PyMarshal_ReadShortFromFile(fp); - fseek(fp, header_offset + 42, 0); - file_offset = PyMarshal_ReadLongFromFile(fp) + arc_offset; - if (name_size > MAXPATHLEN) - name_size = MAXPATHLEN; - - p = name; - for (i = 0; i < name_size; i++) { - *p = (char)getc(fp); - if (*p == '/') - *p = SEP; - p++; - } - *p = 0; /* Add terminating null byte */ - header_offset += header_size; - - strncpy(path + length + 1, name, MAXPATHLEN - length - 1); - - t = Py_BuildValue("siiiiiii", path, compress, data_size, - file_size, file_offset, time, date, crc); - if (t == NULL) - goto error; - err = PyDict_SetItemString(files, name, t); - Py_DECREF(t); - if (err != 0) - goto error; - count++; - } - fclose(fp); - if (Py_VerboseFlag) - PySys_WriteStderr("# zipimport: found %ld names in %s\n", - count, archive); - return files; + PyObject *files = NULL; + FILE *fp; + long compress, crc, data_size, file_size, file_offset, date, time; + long header_offset, name_size, header_size, header_position; + long i, l, count; + size_t length; + char path[MAXPATHLEN + 5]; + char name[MAXPATHLEN + 5]; + char *p, endof_central_dir[22]; + long arc_offset; /* offset from beginning of file to start of zip-archive */ + + if (strlen(archive) > MAXPATHLEN) { + PyErr_SetString(PyExc_OverflowError, + "Zip path name is too long"); + return NULL; + } + strcpy(path, archive); + + fp = fopen(archive, "rb"); + if (fp == NULL) { + PyErr_Format(ZipImportError, "can't open Zip file: " + "'%.200s'", archive); + return NULL; + } + fseek(fp, -22, SEEK_END); + header_position = ftell(fp); + if (fread(endof_central_dir, 1, 22, fp) != 22) { + fclose(fp); + PyErr_Format(ZipImportError, "can't read Zip file: " + "'%.200s'", archive); + return NULL; + } + if (get_long((unsigned char *)endof_central_dir) != 0x06054B50) { + /* Bad: End of Central Dir signature */ + fclose(fp); + PyErr_Format(ZipImportError, "not a Zip file: " + "'%.200s'", archive); + return NULL; + } + + header_size = get_long((unsigned char *)endof_central_dir + 12); + header_offset = get_long((unsigned char *)endof_central_dir + 16); + arc_offset = header_position - header_offset - header_size; + header_offset += arc_offset; + + files = PyDict_New(); + if (files == NULL) + goto error; + + length = (long)strlen(path); + path[length] = SEP; + + /* Start of Central Directory */ + count = 0; + for (;;) { + PyObject *t; + int err; + + fseek(fp, header_offset, 0); /* Start of file header */ + l = PyMarshal_ReadLongFromFile(fp); + if (l != 0x02014B50) + break; /* Bad: Central Dir File Header */ + fseek(fp, header_offset + 10, 0); + compress = PyMarshal_ReadShortFromFile(fp); + time = PyMarshal_ReadShortFromFile(fp); + date = PyMarshal_ReadShortFromFile(fp); + crc = PyMarshal_ReadLongFromFile(fp); + data_size = PyMarshal_ReadLongFromFile(fp); + file_size = PyMarshal_ReadLongFromFile(fp); + name_size = PyMarshal_ReadShortFromFile(fp); + header_size = 46 + name_size + + PyMarshal_ReadShortFromFile(fp) + + PyMarshal_ReadShortFromFile(fp); + fseek(fp, header_offset + 42, 0); + file_offset = PyMarshal_ReadLongFromFile(fp) + arc_offset; + if (name_size > MAXPATHLEN) + name_size = MAXPATHLEN; + + p = name; + for (i = 0; i < name_size; i++) { + *p = (char)getc(fp); + if (*p == '/') + *p = SEP; + p++; + } + *p = 0; /* Add terminating null byte */ + header_offset += header_size; + + strncpy(path + length + 1, name, MAXPATHLEN - length - 1); + + t = Py_BuildValue("siiiiiii", path, compress, data_size, + file_size, file_offset, time, date, crc); + if (t == NULL) + goto error; + err = PyDict_SetItemString(files, name, t); + Py_DECREF(t); + if (err != 0) + goto error; + count++; + } + fclose(fp); + if (Py_VerboseFlag) + PySys_WriteStderr("# zipimport: found %ld names in %s\n", + count, archive); + return files; error: - fclose(fp); - Py_XDECREF(files); - return NULL; + fclose(fp); + Py_XDECREF(files); + return NULL; } /* Return the zlib.decompress function object, or NULL if zlib couldn't @@ -790,31 +790,31 @@ static PyObject * get_decompress_func(void) { - static PyObject *decompress = NULL; + static PyObject *decompress = NULL; - if (decompress == NULL) { - PyObject *zlib; - static int importing_zlib = 0; - - if (importing_zlib != 0) - /* Someone has a zlib.py[co] in their Zip file; - let's avoid a stack overflow. */ - return NULL; - importing_zlib = 1; - zlib = PyImport_ImportModuleNoBlock("zlib"); - importing_zlib = 0; - if (zlib != NULL) { - decompress = PyObject_GetAttrString(zlib, - "decompress"); - Py_DECREF(zlib); - } - else - PyErr_Clear(); - if (Py_VerboseFlag) - PySys_WriteStderr("# zipimport: zlib %s\n", - zlib != NULL ? "available": "UNAVAILABLE"); - } - return decompress; + if (decompress == NULL) { + PyObject *zlib; + static int importing_zlib = 0; + + if (importing_zlib != 0) + /* Someone has a zlib.py[co] in their Zip file; + let's avoid a stack overflow. */ + return NULL; + importing_zlib = 1; + zlib = PyImport_ImportModuleNoBlock("zlib"); + importing_zlib = 0; + if (zlib != NULL) { + decompress = PyObject_GetAttrString(zlib, + "decompress"); + Py_DECREF(zlib); + } + else + PyErr_Clear(); + if (Py_VerboseFlag) + PySys_WriteStderr("# zipimport: zlib %s\n", + zlib != NULL ? "available": "UNAVAILABLE"); + } + return decompress; } /* Given a path to a Zip file and a toc_entry, return the (uncompressed) @@ -822,91 +822,91 @@ static PyObject * get_data(char *archive, PyObject *toc_entry) { - PyObject *raw_data, *data = NULL, *decompress; - char *buf; - FILE *fp; - int err; - Py_ssize_t bytes_read = 0; - long l; - char *datapath; - long compress, data_size, file_size, file_offset, bytes_size; - long time, date, crc; - - if (!PyArg_ParseTuple(toc_entry, "slllllll", &datapath, &compress, - &data_size, &file_size, &file_offset, &time, - &date, &crc)) { - return NULL; - } - - fp = fopen(archive, "rb"); - if (!fp) { - PyErr_Format(PyExc_IOError, - "zipimport: can not open file %s", archive); - return NULL; - } - - /* Check to make sure the local file header is correct */ - fseek(fp, file_offset, 0); - l = PyMarshal_ReadLongFromFile(fp); - if (l != 0x04034B50) { - /* Bad: Local File Header */ - PyErr_Format(ZipImportError, - "bad local file header in %s", - archive); - fclose(fp); - return NULL; - } - fseek(fp, file_offset + 26, 0); - l = 30 + PyMarshal_ReadShortFromFile(fp) + - PyMarshal_ReadShortFromFile(fp); /* local header size */ - file_offset += l; /* Start of file data */ - - bytes_size = compress == 0 ? data_size : data_size + 1; - if (bytes_size == 0) - bytes_size++; - raw_data = PyBytes_FromStringAndSize((char *)NULL, bytes_size); - - if (raw_data == NULL) { - fclose(fp); - return NULL; - } - buf = PyBytes_AsString(raw_data); - - err = fseek(fp, file_offset, 0); - if (err == 0) - bytes_read = fread(buf, 1, data_size, fp); - fclose(fp); - if (err || bytes_read != data_size) { - PyErr_SetString(PyExc_IOError, - "zipimport: can't read data"); - Py_DECREF(raw_data); - return NULL; - } - - if (compress != 0) { - buf[data_size] = 'Z'; /* saw this in zipfile.py */ - data_size++; - } - buf[data_size] = '\0'; - - if (compress == 0) { /* data is not compressed */ - data = PyBytes_FromStringAndSize(buf, data_size); - Py_DECREF(raw_data); - return data; - } - - /* Decompress with zlib */ - decompress = get_decompress_func(); - if (decompress == NULL) { - PyErr_SetString(ZipImportError, - "can't decompress data; " - "zlib not available"); - goto error; - } - data = PyObject_CallFunction(decompress, "Oi", raw_data, -15); + PyObject *raw_data, *data = NULL, *decompress; + char *buf; + FILE *fp; + int err; + Py_ssize_t bytes_read = 0; + long l; + char *datapath; + long compress, data_size, file_size, file_offset, bytes_size; + long time, date, crc; + + if (!PyArg_ParseTuple(toc_entry, "slllllll", &datapath, &compress, + &data_size, &file_size, &file_offset, &time, + &date, &crc)) { + return NULL; + } + + fp = fopen(archive, "rb"); + if (!fp) { + PyErr_Format(PyExc_IOError, + "zipimport: can not open file %s", archive); + return NULL; + } + + /* Check to make sure the local file header is correct */ + fseek(fp, file_offset, 0); + l = PyMarshal_ReadLongFromFile(fp); + if (l != 0x04034B50) { + /* Bad: Local File Header */ + PyErr_Format(ZipImportError, + "bad local file header in %s", + archive); + fclose(fp); + return NULL; + } + fseek(fp, file_offset + 26, 0); + l = 30 + PyMarshal_ReadShortFromFile(fp) + + PyMarshal_ReadShortFromFile(fp); /* local header size */ + file_offset += l; /* Start of file data */ + + bytes_size = compress == 0 ? data_size : data_size + 1; + if (bytes_size == 0) + bytes_size++; + raw_data = PyBytes_FromStringAndSize((char *)NULL, bytes_size); + + if (raw_data == NULL) { + fclose(fp); + return NULL; + } + buf = PyBytes_AsString(raw_data); + + err = fseek(fp, file_offset, 0); + if (err == 0) + bytes_read = fread(buf, 1, data_size, fp); + fclose(fp); + if (err || bytes_read != data_size) { + PyErr_SetString(PyExc_IOError, + "zipimport: can't read data"); + Py_DECREF(raw_data); + return NULL; + } + + if (compress != 0) { + buf[data_size] = 'Z'; /* saw this in zipfile.py */ + data_size++; + } + buf[data_size] = '\0'; + + if (compress == 0) { /* data is not compressed */ + data = PyBytes_FromStringAndSize(buf, data_size); + Py_DECREF(raw_data); + return data; + } + + /* Decompress with zlib */ + decompress = get_decompress_func(); + if (decompress == NULL) { + PyErr_SetString(ZipImportError, + "can't decompress data; " + "zlib not available"); + goto error; + } + data = PyObject_CallFunction(decompress, "Oi", raw_data, -15); error: - Py_DECREF(raw_data); - return data; + Py_DECREF(raw_data); + return data; } /* Lenient date/time comparison function. The precision of the mtime @@ -915,11 +915,11 @@ static int eq_mtime(time_t t1, time_t t2) { - time_t d = t1 - t2; - if (d < 0) - d = -d; - /* dostime only stores even seconds, so be lenient */ - return d <= 1; + time_t d = t1 - t2; + if (d < 0) + d = -d; + /* dostime only stores even seconds, so be lenient */ + return d <= 1; } /* Given the contents of a .py[co] file in a buffer, unmarshal the data @@ -930,44 +930,44 @@ static PyObject * unmarshal_code(char *pathname, PyObject *data, time_t mtime) { - PyObject *code; - char *buf = PyBytes_AsString(data); - Py_ssize_t size = PyBytes_Size(data); - - if (size <= 9) { - PyErr_SetString(ZipImportError, - "bad pyc data"); - return NULL; - } - - if (get_long((unsigned char *)buf) != PyImport_GetMagicNumber()) { - if (Py_VerboseFlag) - PySys_WriteStderr("# %s has bad magic\n", - pathname); - Py_INCREF(Py_None); - return Py_None; /* signal caller to try alternative */ - } - - if (mtime != 0 && !eq_mtime(get_long((unsigned char *)buf + 4), - mtime)) { - if (Py_VerboseFlag) - PySys_WriteStderr("# %s has bad mtime\n", - pathname); - Py_INCREF(Py_None); - return Py_None; /* signal caller to try alternative */ - } - - code = PyMarshal_ReadObjectFromString(buf + 8, size - 8); - if (code == NULL) - return NULL; - if (!PyCode_Check(code)) { - Py_DECREF(code); - PyErr_Format(PyExc_TypeError, - "compiled module %.200s is not a code object", - pathname); - return NULL; - } - return code; + PyObject *code; + char *buf = PyBytes_AsString(data); + Py_ssize_t size = PyBytes_Size(data); + + if (size <= 9) { + PyErr_SetString(ZipImportError, + "bad pyc data"); + return NULL; + } + + if (get_long((unsigned char *)buf) != PyImport_GetMagicNumber()) { + if (Py_VerboseFlag) + PySys_WriteStderr("# %s has bad magic\n", + pathname); + Py_INCREF(Py_None); + return Py_None; /* signal caller to try alternative */ + } + + if (mtime != 0 && !eq_mtime(get_long((unsigned char *)buf + 4), + mtime)) { + if (Py_VerboseFlag) + PySys_WriteStderr("# %s has bad mtime\n", + pathname); + Py_INCREF(Py_None); + return Py_None; /* signal caller to try alternative */ + } + + code = PyMarshal_ReadObjectFromString(buf + 8, size - 8); + if (code == NULL) + return NULL; + if (!PyCode_Check(code)) { + Py_DECREF(code); + PyErr_Format(PyExc_TypeError, + "compiled module %.200s is not a code object", + pathname); + return NULL; + } + return code; } /* Replace any occurances of "\r\n?" in the input string with "\n". @@ -977,38 +977,38 @@ static PyObject * normalize_line_endings(PyObject *source) { - char *buf, *q, *p = PyBytes_AsString(source); - PyObject *fixed_source; - int len = 0; - - if (!p) { - return PyBytes_FromStringAndSize("\n\0", 2); - } - - /* one char extra for trailing \n and one for terminating \0 */ - buf = (char *)PyMem_Malloc(PyBytes_Size(source) + 2); - if (buf == NULL) { - PyErr_SetString(PyExc_MemoryError, - "zipimport: no memory to allocate " - "source buffer"); - return NULL; - } - /* replace "\r\n?" by "\n" */ - for (q = buf; *p != '\0'; p++) { - if (*p == '\r') { - *q++ = '\n'; - if (*(p + 1) == '\n') - p++; - } - else - *q++ = *p; - len++; - } - *q++ = '\n'; /* add trailing \n */ - *q = '\0'; - fixed_source = PyBytes_FromStringAndSize(buf, len + 2); - PyMem_Free(buf); - return fixed_source; + char *buf, *q, *p = PyBytes_AsString(source); + PyObject *fixed_source; + int len = 0; + + if (!p) { + return PyBytes_FromStringAndSize("\n\0", 2); + } + + /* one char extra for trailing \n and one for terminating \0 */ + buf = (char *)PyMem_Malloc(PyBytes_Size(source) + 2); + if (buf == NULL) { + PyErr_SetString(PyExc_MemoryError, + "zipimport: no memory to allocate " + "source buffer"); + return NULL; + } + /* replace "\r\n?" by "\n" */ + for (q = buf; *p != '\0'; p++) { + if (*p == '\r') { + *q++ = '\n'; + if (*(p + 1) == '\n') + p++; + } + else + *q++ = *p; + len++; + } + *q++ = '\n'; /* add trailing \n */ + *q = '\0'; + fixed_source = PyBytes_FromStringAndSize(buf, len + 2); + PyMem_Free(buf); + return fixed_source; } /* Given a string buffer containing Python source code, compile it @@ -1016,16 +1016,16 @@ static PyObject * compile_source(char *pathname, PyObject *source) { - PyObject *code, *fixed_source; + PyObject *code, *fixed_source; - fixed_source = normalize_line_endings(source); - if (fixed_source == NULL) - return NULL; - - code = Py_CompileString(PyBytes_AsString(fixed_source), pathname, - Py_file_input); - Py_DECREF(fixed_source); - return code; + fixed_source = normalize_line_endings(source); + if (fixed_source == NULL) + return NULL; + + code = Py_CompileString(PyBytes_AsString(fixed_source), pathname, + Py_file_input); + Py_DECREF(fixed_source); + return code; } /* Convert the date/time values found in the Zip archive to a value @@ -1033,19 +1033,19 @@ static time_t parse_dostime(int dostime, int dosdate) { - struct tm stm; + struct tm stm; - memset((void *) &stm, '\0', sizeof(stm)); + memset((void *) &stm, '\0', sizeof(stm)); - stm.tm_sec = (dostime & 0x1f) * 2; - stm.tm_min = (dostime >> 5) & 0x3f; - stm.tm_hour = (dostime >> 11) & 0x1f; - stm.tm_mday = dosdate & 0x1f; - stm.tm_mon = ((dosdate >> 5) & 0x0f) - 1; - stm.tm_year = ((dosdate >> 9) & 0x7f) + 80; - stm.tm_isdst = -1; /* wday/yday is ignored */ + stm.tm_sec = (dostime & 0x1f) * 2; + stm.tm_min = (dostime >> 5) & 0x3f; + stm.tm_hour = (dostime >> 11) & 0x1f; + stm.tm_mday = dosdate & 0x1f; + stm.tm_mon = ((dosdate >> 5) & 0x0f) - 1; + stm.tm_year = ((dosdate >> 9) & 0x7f) + 80; + stm.tm_isdst = -1; /* wday/yday is ignored */ - return mktime(&stm); + return mktime(&stm); } /* Given a path to a .pyc or .pyo file in the archive, return the @@ -1054,106 +1054,106 @@ static time_t get_mtime_of_source(ZipImporter *self, char *path) { - PyObject *toc_entry; - time_t mtime = 0; - Py_ssize_t lastchar = strlen(path) - 1; - char savechar = path[lastchar]; - path[lastchar] = '\0'; /* strip 'c' or 'o' from *.py[co] */ - toc_entry = PyDict_GetItemString(self->files, path); - if (toc_entry != NULL && PyTuple_Check(toc_entry) && - PyTuple_Size(toc_entry) == 8) { - /* fetch the time stamp of the .py file for comparison - with an embedded pyc time stamp */ - int time, date; - time = PyLong_AsLong(PyTuple_GetItem(toc_entry, 5)); - date = PyLong_AsLong(PyTuple_GetItem(toc_entry, 6)); - mtime = parse_dostime(time, date); - } - path[lastchar] = savechar; - return mtime; + PyObject *toc_entry; + time_t mtime = 0; + Py_ssize_t lastchar = strlen(path) - 1; + char savechar = path[lastchar]; + path[lastchar] = '\0'; /* strip 'c' or 'o' from *.py[co] */ + toc_entry = PyDict_GetItemString(self->files, path); + if (toc_entry != NULL && PyTuple_Check(toc_entry) && + PyTuple_Size(toc_entry) == 8) { + /* fetch the time stamp of the .py file for comparison + with an embedded pyc time stamp */ + int time, date; + time = PyLong_AsLong(PyTuple_GetItem(toc_entry, 5)); + date = PyLong_AsLong(PyTuple_GetItem(toc_entry, 6)); + mtime = parse_dostime(time, date); + } + path[lastchar] = savechar; + return mtime; } /* Return the code object for the module named by 'fullname' from the Zip archive as a new reference. */ static PyObject * get_code_from_data(ZipImporter *self, int ispackage, int isbytecode, - time_t mtime, PyObject *toc_entry) + time_t mtime, PyObject *toc_entry) { - PyObject *data, *code; - char *modpath; - char *archive = _PyUnicode_AsString(self->archive); - - if (archive == NULL) - return NULL; - - data = get_data(archive, toc_entry); - if (data == NULL) - return NULL; - - modpath = _PyUnicode_AsString(PyTuple_GetItem(toc_entry, 0)); - - if (isbytecode) { - code = unmarshal_code(modpath, data, mtime); - } - else { - code = compile_source(modpath, data); - } - Py_DECREF(data); - return code; + PyObject *data, *code; + char *modpath; + char *archive = _PyUnicode_AsString(self->archive); + + if (archive == NULL) + return NULL; + + data = get_data(archive, toc_entry); + if (data == NULL) + return NULL; + + modpath = _PyUnicode_AsString(PyTuple_GetItem(toc_entry, 0)); + + if (isbytecode) { + code = unmarshal_code(modpath, data, mtime); + } + else { + code = compile_source(modpath, data); + } + Py_DECREF(data); + return code; } /* Get the code object assoiciated with the module specified by 'fullname'. */ static PyObject * get_module_code(ZipImporter *self, char *fullname, - int *p_ispackage, char **p_modpath) + int *p_ispackage, char **p_modpath) { - PyObject *toc_entry; - char *subname, path[MAXPATHLEN + 1]; - int len; - struct st_zip_searchorder *zso; - - subname = get_subname(fullname); - - len = make_filename(_PyUnicode_AsString(self->prefix), subname, path); - if (len < 0) - return NULL; - - for (zso = zip_searchorder; *zso->suffix; zso++) { - PyObject *code = NULL; - - strcpy(path + len, zso->suffix); - if (Py_VerboseFlag > 1) - PySys_WriteStderr("# trying %s%c%s\n", - _PyUnicode_AsString(self->archive), - (int)SEP, path); - toc_entry = PyDict_GetItemString(self->files, path); - if (toc_entry != NULL) { - time_t mtime = 0; - int ispackage = zso->type & IS_PACKAGE; - int isbytecode = zso->type & IS_BYTECODE; - - if (isbytecode) - mtime = get_mtime_of_source(self, path); - if (p_ispackage != NULL) - *p_ispackage = ispackage; - code = get_code_from_data(self, ispackage, - isbytecode, mtime, - toc_entry); - if (code == Py_None) { - /* bad magic number or non-matching mtime - in byte code, try next */ - Py_DECREF(code); - continue; - } - if (code != NULL && p_modpath != NULL) - *p_modpath = _PyUnicode_AsString( - PyTuple_GetItem(toc_entry, 0)); - return code; - } - } - PyErr_Format(ZipImportError, "can't find module '%.200s'", fullname); - return NULL; + PyObject *toc_entry; + char *subname, path[MAXPATHLEN + 1]; + int len; + struct st_zip_searchorder *zso; + + subname = get_subname(fullname); + + len = make_filename(_PyUnicode_AsString(self->prefix), subname, path); + if (len < 0) + return NULL; + + for (zso = zip_searchorder; *zso->suffix; zso++) { + PyObject *code = NULL; + + strcpy(path + len, zso->suffix); + if (Py_VerboseFlag > 1) + PySys_WriteStderr("# trying %s%c%s\n", + _PyUnicode_AsString(self->archive), + (int)SEP, path); + toc_entry = PyDict_GetItemString(self->files, path); + if (toc_entry != NULL) { + time_t mtime = 0; + int ispackage = zso->type & IS_PACKAGE; + int isbytecode = zso->type & IS_BYTECODE; + + if (isbytecode) + mtime = get_mtime_of_source(self, path); + if (p_ispackage != NULL) + *p_ispackage = ispackage; + code = get_code_from_data(self, ispackage, + isbytecode, mtime, + toc_entry); + if (code == Py_None) { + /* bad magic number or non-matching mtime + in byte code, try next */ + Py_DECREF(code); + continue; + } + if (code != NULL && p_modpath != NULL) + *p_modpath = _PyUnicode_AsString( + PyTuple_GetItem(toc_entry, 0)); + return code; + } + } + PyErr_Format(ZipImportError, "can't find module '%.200s'", fullname); + return NULL; } @@ -1174,65 +1174,65 @@ to Zip archives."); static struct PyModuleDef zipimportmodule = { - PyModuleDef_HEAD_INIT, - "zipimport", - zipimport_doc, - -1, - NULL, - NULL, - NULL, - NULL, - NULL + PyModuleDef_HEAD_INIT, + "zipimport", + zipimport_doc, + -1, + NULL, + NULL, + NULL, + NULL, + NULL }; PyMODINIT_FUNC PyInit_zipimport(void) { - PyObject *mod; + PyObject *mod; + + if (PyType_Ready(&ZipImporter_Type) < 0) + return NULL; + + /* Correct directory separator */ + zip_searchorder[0].suffix[0] = SEP; + zip_searchorder[1].suffix[0] = SEP; + zip_searchorder[2].suffix[0] = SEP; + if (Py_OptimizeFlag) { + /* Reverse *.pyc and *.pyo */ + struct st_zip_searchorder tmp; + tmp = zip_searchorder[0]; + zip_searchorder[0] = zip_searchorder[1]; + zip_searchorder[1] = tmp; + tmp = zip_searchorder[3]; + zip_searchorder[3] = zip_searchorder[4]; + zip_searchorder[4] = tmp; + } + + mod = PyModule_Create(&zipimportmodule); + if (mod == NULL) + return NULL; - if (PyType_Ready(&ZipImporter_Type) < 0) - return NULL; + ZipImportError = PyErr_NewException("zipimport.ZipImportError", + PyExc_ImportError, NULL); + if (ZipImportError == NULL) + return NULL; - /* Correct directory separator */ - zip_searchorder[0].suffix[0] = SEP; - zip_searchorder[1].suffix[0] = SEP; - zip_searchorder[2].suffix[0] = SEP; - if (Py_OptimizeFlag) { - /* Reverse *.pyc and *.pyo */ - struct st_zip_searchorder tmp; - tmp = zip_searchorder[0]; - zip_searchorder[0] = zip_searchorder[1]; - zip_searchorder[1] = tmp; - tmp = zip_searchorder[3]; - zip_searchorder[3] = zip_searchorder[4]; - zip_searchorder[4] = tmp; - } - - mod = PyModule_Create(&zipimportmodule); - if (mod == NULL) - return NULL; - - ZipImportError = PyErr_NewException("zipimport.ZipImportError", - PyExc_ImportError, NULL); - if (ZipImportError == NULL) - return NULL; - - Py_INCREF(ZipImportError); - if (PyModule_AddObject(mod, "ZipImportError", - ZipImportError) < 0) - return NULL; - - Py_INCREF(&ZipImporter_Type); - if (PyModule_AddObject(mod, "zipimporter", - (PyObject *)&ZipImporter_Type) < 0) - return NULL; - - zip_directory_cache = PyDict_New(); - if (zip_directory_cache == NULL) - return NULL; - Py_INCREF(zip_directory_cache); - if (PyModule_AddObject(mod, "_zip_directory_cache", - zip_directory_cache) < 0) - return NULL; - return mod; + Py_INCREF(ZipImportError); + if (PyModule_AddObject(mod, "ZipImportError", + ZipImportError) < 0) + return NULL; + + Py_INCREF(&ZipImporter_Type); + if (PyModule_AddObject(mod, "zipimporter", + (PyObject *)&ZipImporter_Type) < 0) + return NULL; + + zip_directory_cache = PyDict_New(); + if (zip_directory_cache == NULL) + return NULL; + Py_INCREF(zip_directory_cache); + if (PyModule_AddObject(mod, "_zip_directory_cache", + zip_directory_cache) < 0) + return NULL; + return mod; } Modified: python/branches/release31-maint/Modules/zlibmodule.c ============================================================================== --- python/branches/release31-maint/Modules/zlibmodule.c (original) +++ python/branches/release31-maint/Modules/zlibmodule.c Sun May 9 18:14:21 2010 @@ -53,9 +53,9 @@ zlib_error(z_stream zst, int err, char *msg) { if (zst.msg == Z_NULL) - PyErr_Format(ZlibError, "Error %d %s", err, msg); + PyErr_Format(ZlibError, "Error %d %s", err, msg); else - PyErr_Format(ZlibError, "Error %d %s: %.200s", err, msg, zst.msg); + PyErr_Format(ZlibError, "Error %d %s: %.200s", err, msg, zst.msg); } PyDoc_STRVAR(compressobj__doc__, @@ -74,17 +74,17 @@ compobject *self; self = PyObject_New(compobject, type); if (self == NULL) - return NULL; + return NULL; self->is_initialised = 0; self->unused_data = PyBytes_FromStringAndSize("", 0); if (self->unused_data == NULL) { - Py_DECREF(self); - return NULL; + Py_DECREF(self); + return NULL; } self->unconsumed_tail = PyBytes_FromStringAndSize("", 0); if (self->unconsumed_tail == NULL) { - Py_DECREF(self); - return NULL; + Py_DECREF(self); + return NULL; } #ifdef WITH_THREAD self->lock = PyThread_allocate_lock(); @@ -108,7 +108,7 @@ /* require Python string object, optional 'level' arg */ if (!PyArg_ParseTuple(args, "y*|i:compress", &pinput, &level)) - return NULL; + return NULL; input = pinput.buf; length = pinput.len; @@ -116,10 +116,10 @@ output = (Byte*)malloc(zst.avail_out); if (output == NULL) { - PyBuffer_Release(&pinput); - PyErr_SetString(PyExc_MemoryError, - "Can't allocate memory to compress data"); - return NULL; + PyBuffer_Release(&pinput); + PyErr_SetString(PyExc_MemoryError, + "Can't allocate memory to compress data"); + return NULL; } /* Past the point of no return. From here on out, we need to make sure @@ -134,19 +134,19 @@ switch(err) { case(Z_OK): - break; + break; case(Z_MEM_ERROR): - PyErr_SetString(PyExc_MemoryError, - "Out of memory while compressing data"); - goto error; + PyErr_SetString(PyExc_MemoryError, + "Out of memory while compressing data"); + goto error; case(Z_STREAM_ERROR): - PyErr_SetString(ZlibError, - "Bad compression level"); - goto error; + PyErr_SetString(ZlibError, + "Bad compression level"); + goto error; default: deflateEnd(&zst); - zlib_error(zst, err, "while compressing data"); - goto error; + zlib_error(zst, err, "while compressing data"); + goto error; } Py_BEGIN_ALLOW_THREADS; @@ -154,17 +154,17 @@ Py_END_ALLOW_THREADS; if (err != Z_STREAM_END) { - zlib_error(zst, err, "while compressing data"); - deflateEnd(&zst); - goto error; + zlib_error(zst, err, "while compressing data"); + deflateEnd(&zst); + goto error; } err=deflateEnd(&zst); if (err == Z_OK) - ReturnVal = PyBytes_FromStringAndSize((char *)output, + ReturnVal = PyBytes_FromStringAndSize((char *)output, zst.total_out); else - zlib_error(zst, err, "while finishing compression"); + zlib_error(zst, err, "while finishing compression"); error: PyBuffer_Release(&pinput); @@ -191,20 +191,20 @@ z_stream zst; if (!PyArg_ParseTuple(args, "y*|in:decompress", - &pinput, &wsize, &r_strlen)) - return NULL; + &pinput, &wsize, &r_strlen)) + return NULL; input = pinput.buf; length = pinput.len; if (r_strlen <= 0) - r_strlen = 1; + r_strlen = 1; zst.avail_in = length; zst.avail_out = r_strlen; if (!(result_str = PyBytes_FromStringAndSize(NULL, r_strlen))) { - PyBuffer_Release(&pinput); - return NULL; + PyBuffer_Release(&pinput); + return NULL; } zst.zalloc = (alloc_func)NULL; @@ -215,60 +215,60 @@ switch(err) { case(Z_OK): - break; + break; case(Z_MEM_ERROR): - PyErr_SetString(PyExc_MemoryError, - "Out of memory while decompressing data"); - goto error; + PyErr_SetString(PyExc_MemoryError, + "Out of memory while decompressing data"); + goto error; default: inflateEnd(&zst); - zlib_error(zst, err, "while preparing to decompress data"); - goto error; + zlib_error(zst, err, "while preparing to decompress data"); + goto error; } do { - Py_BEGIN_ALLOW_THREADS - err=inflate(&zst, Z_FINISH); - Py_END_ALLOW_THREADS - - switch(err) { - case(Z_STREAM_END): - break; - case(Z_BUF_ERROR): - /* - * If there is at least 1 byte of room according to zst.avail_out - * and we get this error, assume that it means zlib cannot - * process the inflate call() due to an error in the data. - */ - if (zst.avail_out > 0) { - PyErr_Format(ZlibError, "Error %i while decompressing data", - err); - inflateEnd(&zst); - goto error; - } - /* fall through */ - case(Z_OK): - /* need more memory */ - if (_PyBytes_Resize(&result_str, r_strlen << 1) < 0) { - inflateEnd(&zst); - goto error; - } - zst.next_out = + Py_BEGIN_ALLOW_THREADS + err=inflate(&zst, Z_FINISH); + Py_END_ALLOW_THREADS + + switch(err) { + case(Z_STREAM_END): + break; + case(Z_BUF_ERROR): + /* + * If there is at least 1 byte of room according to zst.avail_out + * and we get this error, assume that it means zlib cannot + * process the inflate call() due to an error in the data. + */ + if (zst.avail_out > 0) { + PyErr_Format(ZlibError, "Error %i while decompressing data", + err); + inflateEnd(&zst); + goto error; + } + /* fall through */ + case(Z_OK): + /* need more memory */ + if (_PyBytes_Resize(&result_str, r_strlen << 1) < 0) { + inflateEnd(&zst); + goto error; + } + zst.next_out = (unsigned char *)PyBytes_AS_STRING(result_str) + r_strlen; - zst.avail_out = r_strlen; - r_strlen = r_strlen << 1; - break; - default: - inflateEnd(&zst); - zlib_error(zst, err, "while decompressing data"); - goto error; - } + zst.avail_out = r_strlen; + r_strlen = r_strlen << 1; + break; + default: + inflateEnd(&zst); + zlib_error(zst, err, "while decompressing data"); + goto error; + } } while (err != Z_STREAM_END); err = inflateEnd(&zst); if (err != Z_OK) { - zlib_error(zst, err, "while finishing data decompression"); - goto error; + zlib_error(zst, err, "while finishing data decompression"); + goto error; } if (_PyBytes_Resize(&result_str, zst.total_out) < 0) @@ -291,12 +291,12 @@ int wbits=MAX_WBITS, memLevel=DEF_MEM_LEVEL, strategy=0, err; if (!PyArg_ParseTuple(args, "|iiiii:compressobj", &level, &method, &wbits, - &memLevel, &strategy)) - return NULL; + &memLevel, &strategy)) + return NULL; self = newcompobject(&Comptype); if (self==NULL) - return(NULL); + return(NULL); self->zst.zalloc = (alloc_func)NULL; self->zst.zfree = (free_func)Z_NULL; self->zst.next_in = NULL; @@ -304,21 +304,21 @@ err = deflateInit2(&self->zst, level, method, wbits, memLevel, strategy); switch(err) { case (Z_OK): - self->is_initialised = 1; - return (PyObject*)self; + self->is_initialised = 1; + return (PyObject*)self; case (Z_MEM_ERROR): - Py_DECREF(self); - PyErr_SetString(PyExc_MemoryError, - "Can't allocate memory for compression object"); - return NULL; + Py_DECREF(self); + PyErr_SetString(PyExc_MemoryError, + "Can't allocate memory for compression object"); + return NULL; case(Z_STREAM_ERROR): - Py_DECREF(self); - PyErr_SetString(PyExc_ValueError, "Invalid initialization option"); - return NULL; + Py_DECREF(self); + PyErr_SetString(PyExc_ValueError, "Invalid initialization option"); + return NULL; default: - zlib_error(self->zst, err, "while creating compression object"); + zlib_error(self->zst, err, "while creating compression object"); Py_DECREF(self); - return NULL; + return NULL; } } @@ -328,11 +328,11 @@ int wbits=DEF_WBITS, err; compobject *self; if (!PyArg_ParseTuple(args, "|i:decompressobj", &wbits)) - return NULL; + return NULL; self = newcompobject(&Decomptype); if (self == NULL) - return(NULL); + return(NULL); self->zst.zalloc = (alloc_func)NULL; self->zst.zfree = (free_func)Z_NULL; self->zst.next_in = NULL; @@ -340,21 +340,21 @@ err = inflateInit2(&self->zst, wbits); switch(err) { case (Z_OK): - self->is_initialised = 1; - return (PyObject*)self; + self->is_initialised = 1; + return (PyObject*)self; case(Z_STREAM_ERROR): - Py_DECREF(self); - PyErr_SetString(PyExc_ValueError, "Invalid initialization option"); - return NULL; + Py_DECREF(self); + PyErr_SetString(PyExc_ValueError, "Invalid initialization option"); + return NULL; case (Z_MEM_ERROR): - Py_DECREF(self); - PyErr_SetString(PyExc_MemoryError, - "Can't allocate memory for decompression object"); - return NULL; + Py_DECREF(self); + PyErr_SetString(PyExc_MemoryError, + "Can't allocate memory for decompression object"); + return NULL; default: - zlib_error(self->zst, err, "while creating decompression object"); + zlib_error(self->zst, err, "while creating decompression object"); Py_DECREF(self); - return NULL; + return NULL; } } @@ -404,13 +404,13 @@ unsigned long start_total_out; if (!PyArg_ParseTuple(args, "y*:compress", &pinput)) - return NULL; + return NULL; input = pinput.buf; inplen = pinput.len; if (!(RetVal = PyBytes_FromStringAndSize(NULL, length))) { - PyBuffer_Release(&pinput); - return NULL; + PyBuffer_Release(&pinput); + return NULL; } ENTER_ZLIB(self); @@ -428,19 +428,19 @@ /* while Z_OK and the output buffer is full, there might be more output, so extend the output buffer and try again */ while (err == Z_OK && self->zst.avail_out == 0) { - if (_PyBytes_Resize(&RetVal, length << 1) < 0) { + if (_PyBytes_Resize(&RetVal, length << 1) < 0) { Py_DECREF(RetVal); RetVal = NULL; - goto error; + goto error; } - self->zst.next_out = + self->zst.next_out = (unsigned char *)PyBytes_AS_STRING(RetVal) + length; - self->zst.avail_out = length; - length = length << 1; + self->zst.avail_out = length; + length = length << 1; - Py_BEGIN_ALLOW_THREADS - err = deflate(&(self->zst), Z_NO_FLUSH); - Py_END_ALLOW_THREADS + Py_BEGIN_ALLOW_THREADS + err = deflate(&(self->zst), Z_NO_FLUSH); + Py_END_ALLOW_THREADS } /* We will only get Z_BUF_ERROR if the output buffer was full but there wasn't more output when we tried again, so it is not an error @@ -448,10 +448,10 @@ */ if (err != Z_OK && err != Z_BUF_ERROR) { - zlib_error(self->zst, err, "while compressing"); - Py_DECREF(RetVal); - RetVal = NULL; - goto error; + zlib_error(self->zst, err, "while compressing"); + Py_DECREF(RetVal); + RetVal = NULL; + goto error; } if (_PyBytes_Resize(&RetVal, self->zst.total_out - start_total_out) < 0) { Py_DECREF(RetVal); @@ -486,23 +486,23 @@ unsigned long start_total_out; if (!PyArg_ParseTuple(args, "y*|i:decompress", &pinput, - &max_length)) - return NULL; + &max_length)) + return NULL; input = pinput.buf; inplen = pinput.len; if (max_length < 0) { - PyBuffer_Release(&pinput); - PyErr_SetString(PyExc_ValueError, - "max_length must be greater than zero"); - return NULL; + PyBuffer_Release(&pinput); + PyErr_SetString(PyExc_ValueError, + "max_length must be greater than zero"); + return NULL; } /* limit amount of data allocated to max_length */ if (max_length && length > max_length) - length = max_length; + length = max_length; if (!(RetVal = PyBytes_FromStringAndSize(NULL, length))) { - PyBuffer_Release(&pinput); - return NULL; + PyBuffer_Release(&pinput); + return NULL; } ENTER_ZLIB(self); @@ -521,43 +521,43 @@ So extend the output buffer and try again. */ while (err == Z_OK && self->zst.avail_out == 0) { - /* If max_length set, don't continue decompressing if we've already - reached the limit. - */ - if (max_length && length >= max_length) - break; - - /* otherwise, ... */ - old_length = length; - length = length << 1; - if (max_length && length > max_length) - length = max_length; + /* If max_length set, don't continue decompressing if we've already + reached the limit. + */ + if (max_length && length >= max_length) + break; + + /* otherwise, ... */ + old_length = length; + length = length << 1; + if (max_length && length > max_length) + length = max_length; - if (_PyBytes_Resize(&RetVal, length) < 0) { + if (_PyBytes_Resize(&RetVal, length) < 0) { Py_DECREF(RetVal); RetVal = NULL; - goto error; + goto error; } - self->zst.next_out = + self->zst.next_out = (unsigned char *)PyBytes_AS_STRING(RetVal) + old_length; - self->zst.avail_out = length - old_length; + self->zst.avail_out = length - old_length; - Py_BEGIN_ALLOW_THREADS - err = inflate(&(self->zst), Z_SYNC_FLUSH); - Py_END_ALLOW_THREADS + Py_BEGIN_ALLOW_THREADS + err = inflate(&(self->zst), Z_SYNC_FLUSH); + Py_END_ALLOW_THREADS } /* Not all of the compressed data could be accommodated in the output buffer of specified size. Return the unconsumed tail in an attribute.*/ if(max_length) { - Py_DECREF(self->unconsumed_tail); - self->unconsumed_tail = PyBytes_FromStringAndSize((char *)self->zst.next_in, - self->zst.avail_in); - if(!self->unconsumed_tail) { - Py_DECREF(RetVal); - RetVal = NULL; - goto error; - } + Py_DECREF(self->unconsumed_tail); + self->unconsumed_tail = PyBytes_FromStringAndSize((char *)self->zst.next_in, + self->zst.avail_in); + if(!self->unconsumed_tail) { + Py_DECREF(RetVal); + RetVal = NULL; + goto error; + } } /* The end of the compressed data has been reached, so set the @@ -567,22 +567,22 @@ preserved. */ if (err == Z_STREAM_END) { - Py_XDECREF(self->unused_data); /* Free original empty string */ - self->unused_data = PyBytes_FromStringAndSize( - (char *)self->zst.next_in, self->zst.avail_in); - if (self->unused_data == NULL) { - Py_DECREF(RetVal); - goto error; - } - /* We will only get Z_BUF_ERROR if the output buffer was full - but there wasn't more output when we tried again, so it is - not an error condition. - */ + Py_XDECREF(self->unused_data); /* Free original empty string */ + self->unused_data = PyBytes_FromStringAndSize( + (char *)self->zst.next_in, self->zst.avail_in); + if (self->unused_data == NULL) { + Py_DECREF(RetVal); + goto error; + } + /* We will only get Z_BUF_ERROR if the output buffer was full + but there wasn't more output when we tried again, so it is + not an error condition. + */ } else if (err != Z_OK && err != Z_BUF_ERROR) { - zlib_error(self->zst, err, "while decompressing"); - Py_DECREF(RetVal); - RetVal = NULL; - goto error; + zlib_error(self->zst, err, "while decompressing"); + Py_DECREF(RetVal); + RetVal = NULL; + goto error; } if (_PyBytes_Resize(&RetVal, self->zst.total_out - start_total_out) < 0) { @@ -613,16 +613,16 @@ unsigned long start_total_out; if (!PyArg_ParseTuple(args, "|i:flush", &flushmode)) - return NULL; + return NULL; /* Flushing with Z_NO_FLUSH is a no-op, so there's no point in doing any work at all; just return an empty string. */ if (flushmode == Z_NO_FLUSH) { - return PyBytes_FromStringAndSize(NULL, 0); + return PyBytes_FromStringAndSize(NULL, 0); } if (!(RetVal = PyBytes_FromStringAndSize(NULL, length))) - return NULL; + return NULL; ENTER_ZLIB(self); @@ -638,44 +638,44 @@ /* while Z_OK and the output buffer is full, there might be more output, so extend the output buffer and try again */ while (err == Z_OK && self->zst.avail_out == 0) { - if (_PyBytes_Resize(&RetVal, length << 1) < 0) { + if (_PyBytes_Resize(&RetVal, length << 1) < 0) { Py_DECREF(RetVal); RetVal = NULL; - goto error; + goto error; } - self->zst.next_out = + self->zst.next_out = (unsigned char *)PyBytes_AS_STRING(RetVal) + length; - self->zst.avail_out = length; - length = length << 1; + self->zst.avail_out = length; + length = length << 1; - Py_BEGIN_ALLOW_THREADS - err = deflate(&(self->zst), flushmode); - Py_END_ALLOW_THREADS + Py_BEGIN_ALLOW_THREADS + err = deflate(&(self->zst), flushmode); + Py_END_ALLOW_THREADS } /* If flushmode is Z_FINISH, we also have to call deflateEnd() to free various data structures. Note we should only get Z_STREAM_END when flushmode is Z_FINISH, but checking both for safety*/ if (err == Z_STREAM_END && flushmode == Z_FINISH) { - err = deflateEnd(&(self->zst)); - if (err != Z_OK) { - zlib_error(self->zst, err, "from deflateEnd()"); - Py_DECREF(RetVal); - RetVal = NULL; - goto error; - } - else - self->is_initialised = 0; - - /* We will only get Z_BUF_ERROR if the output buffer was full - but there wasn't more output when we tried again, so it is - not an error condition. - */ + err = deflateEnd(&(self->zst)); + if (err != Z_OK) { + zlib_error(self->zst, err, "from deflateEnd()"); + Py_DECREF(RetVal); + RetVal = NULL; + goto error; + } + else + self->is_initialised = 0; + + /* We will only get Z_BUF_ERROR if the output buffer was full + but there wasn't more output when we tried again, so it is + not an error condition. + */ } else if (err!=Z_OK && err!=Z_BUF_ERROR) { - zlib_error(self->zst, err, "while flushing"); - Py_DECREF(RetVal); - RetVal = NULL; - goto error; + zlib_error(self->zst, err, "while flushing"); + Py_DECREF(RetVal); + RetVal = NULL; + goto error; } if (_PyBytes_Resize(&RetVal, self->zst.total_out - start_total_out) < 0) { @@ -807,13 +807,13 @@ unsigned long start_total_out; if (!PyArg_ParseTuple(args, "|i:flush", &length)) - return NULL; + return NULL; if (length <= 0) { - PyErr_SetString(PyExc_ValueError, "length must be greater than zero"); - return NULL; + PyErr_SetString(PyExc_ValueError, "length must be greater than zero"); + return NULL; } if (!(retval = PyBytes_FromStringAndSize(NULL, length))) - return NULL; + return NULL; ENTER_ZLIB(self); @@ -829,32 +829,32 @@ /* while Z_OK and the output buffer is full, there might be more output, so extend the output buffer and try again */ while ((err == Z_OK || err == Z_BUF_ERROR) && self->zst.avail_out == 0) { - if (_PyBytes_Resize(&retval, length << 1) < 0) { + if (_PyBytes_Resize(&retval, length << 1) < 0) { Py_DECREF(retval); retval = NULL; - goto error; + goto error; } - self->zst.next_out = (Byte *)PyBytes_AS_STRING(retval) + length; - self->zst.avail_out = length; - length = length << 1; - - Py_BEGIN_ALLOW_THREADS - err = inflate(&(self->zst), Z_FINISH); - Py_END_ALLOW_THREADS + self->zst.next_out = (Byte *)PyBytes_AS_STRING(retval) + length; + self->zst.avail_out = length; + length = length << 1; + + Py_BEGIN_ALLOW_THREADS + err = inflate(&(self->zst), Z_FINISH); + Py_END_ALLOW_THREADS } /* If flushmode is Z_FINISH, we also have to call deflateEnd() to free various data structures. Note we should only get Z_STREAM_END when flushmode is Z_FINISH */ if (err == Z_STREAM_END) { - err = inflateEnd(&(self->zst)); + err = inflateEnd(&(self->zst)); self->is_initialised = 0; - if (err != Z_OK) { - zlib_error(self->zst, err, "from inflateEnd()"); - Py_DECREF(retval); - retval = NULL; - goto error; - } + if (err != Z_OK) { + zlib_error(self->zst, err, "from inflateEnd()"); + Py_DECREF(retval); + retval = NULL; + goto error; + } } if (_PyBytes_Resize(&retval, self->zst.total_out - start_total_out) < 0) { Py_DECREF(retval); @@ -942,7 +942,7 @@ int signed_val; if (!PyArg_ParseTuple(args, "y*|I:crc32", &pbuf, &crc32val)) - return NULL; + return NULL; /* Releasing the GIL for very small buffers is inefficient and may lower performance */ if (pbuf.len > 1024*5) { @@ -950,7 +950,7 @@ signed_val = crc32(crc32val, pbuf.buf, pbuf.len); Py_END_ALLOW_THREADS } else { - signed_val = crc32(crc32val, pbuf.buf, pbuf.len); + signed_val = crc32(crc32val, pbuf.buf, pbuf.len); } PyBuffer_Release(&pbuf); return PyLong_FromUnsignedLong(signed_val & 0xffffffffU); @@ -1053,15 +1053,15 @@ "objects support decompress() and flush()."); static struct PyModuleDef zlibmodule = { - PyModuleDef_HEAD_INIT, - "zlib", - zlib_module_documentation, - -1, - zlib_methods, - NULL, - NULL, - NULL, - NULL + PyModuleDef_HEAD_INIT, + "zlib", + zlib_module_documentation, + -1, + zlib_methods, + NULL, + NULL, + NULL, + NULL }; PyMODINIT_FUNC @@ -1069,17 +1069,17 @@ { PyObject *m, *ver; if (PyType_Ready(&Comptype) < 0) - return NULL; + return NULL; if (PyType_Ready(&Decomptype) < 0) - return NULL; + return NULL; m = PyModule_Create(&zlibmodule); if (m == NULL) - return NULL; + return NULL; ZlibError = PyErr_NewException("zlib.error", NULL, NULL); if (ZlibError != NULL) { Py_INCREF(ZlibError); - PyModule_AddObject(m, "error", ZlibError); + PyModule_AddObject(m, "error", ZlibError); } PyModule_AddIntConstant(m, "MAX_WBITS", MAX_WBITS); PyModule_AddIntConstant(m, "DEFLATED", DEFLATED); @@ -1098,7 +1098,7 @@ ver = PyUnicode_FromString(ZLIB_VERSION); if (ver != NULL) - PyModule_AddObject(m, "ZLIB_VERSION", ver); + PyModule_AddObject(m, "ZLIB_VERSION", ver); PyModule_AddStringConstant(m, "__version__", "1.0"); Modified: python/branches/release31-maint/Objects/abstract.c ============================================================================== --- python/branches/release31-maint/Objects/abstract.c (original) +++ python/branches/release31-maint/Objects/abstract.c Sun May 9 18:14:21 2010 @@ -12,17 +12,17 @@ static PyObject * type_error(const char *msg, PyObject *obj) { - PyErr_Format(PyExc_TypeError, msg, obj->ob_type->tp_name); - return NULL; + PyErr_Format(PyExc_TypeError, msg, obj->ob_type->tp_name); + return NULL; } static PyObject * null_error(void) { - if (!PyErr_Occurred()) - PyErr_SetString(PyExc_SystemError, - "null argument to internal routine"); - return NULL; + if (!PyErr_Occurred()) + PyErr_SetString(PyExc_SystemError, + "null argument to internal routine"); + return NULL; } /* Operations on any object */ @@ -30,37 +30,37 @@ PyObject * PyObject_Type(PyObject *o) { - PyObject *v; + PyObject *v; - if (o == NULL) - return null_error(); - v = (PyObject *)o->ob_type; - Py_INCREF(v); - return v; + if (o == NULL) + return null_error(); + v = (PyObject *)o->ob_type; + Py_INCREF(v); + return v; } Py_ssize_t PyObject_Size(PyObject *o) { - PySequenceMethods *m; + PySequenceMethods *m; - if (o == NULL) { - null_error(); - return -1; - } - - m = o->ob_type->tp_as_sequence; - if (m && m->sq_length) - return m->sq_length(o); + if (o == NULL) { + null_error(); + return -1; + } + + m = o->ob_type->tp_as_sequence; + if (m && m->sq_length) + return m->sq_length(o); - return PyMapping_Size(o); + return PyMapping_Size(o); } #undef PyObject_Length Py_ssize_t PyObject_Length(PyObject *o) { - return PyObject_Size(o); + return PyObject_Size(o); } #define PyObject_Length PyObject_Size @@ -74,149 +74,149 @@ Py_ssize_t _PyObject_LengthHint(PyObject *o, Py_ssize_t defaultvalue) { - static PyObject *hintstrobj = NULL; - PyObject *ro, *hintmeth; - Py_ssize_t rv; - - /* try o.__len__() */ - rv = PyObject_Size(o); - if (rv >= 0) - return rv; - if (PyErr_Occurred()) { - if (!PyErr_ExceptionMatches(PyExc_TypeError)) - return -1; - PyErr_Clear(); - } - - /* try o.__length_hint__() */ - hintmeth = _PyObject_LookupSpecial(o, "__length_hint__", &hintstrobj); - if (hintmeth == NULL) { - if (PyErr_Occurred()) - return -1; - else - return defaultvalue; - } - ro = PyObject_CallFunctionObjArgs(hintmeth, NULL); - Py_DECREF(hintmeth); - if (ro == NULL) { - if (!PyErr_ExceptionMatches(PyExc_TypeError)) - return -1; - PyErr_Clear(); - return defaultvalue; - } - rv = PyLong_Check(ro) ? PyLong_AsSsize_t(ro) : defaultvalue; - Py_DECREF(ro); - return rv; + static PyObject *hintstrobj = NULL; + PyObject *ro, *hintmeth; + Py_ssize_t rv; + + /* try o.__len__() */ + rv = PyObject_Size(o); + if (rv >= 0) + return rv; + if (PyErr_Occurred()) { + if (!PyErr_ExceptionMatches(PyExc_TypeError)) + return -1; + PyErr_Clear(); + } + + /* try o.__length_hint__() */ + hintmeth = _PyObject_LookupSpecial(o, "__length_hint__", &hintstrobj); + if (hintmeth == NULL) { + if (PyErr_Occurred()) + return -1; + else + return defaultvalue; + } + ro = PyObject_CallFunctionObjArgs(hintmeth, NULL); + Py_DECREF(hintmeth); + if (ro == NULL) { + if (!PyErr_ExceptionMatches(PyExc_TypeError)) + return -1; + PyErr_Clear(); + return defaultvalue; + } + rv = PyLong_Check(ro) ? PyLong_AsSsize_t(ro) : defaultvalue; + Py_DECREF(ro); + return rv; } PyObject * PyObject_GetItem(PyObject *o, PyObject *key) { - PyMappingMethods *m; + PyMappingMethods *m; - if (o == NULL || key == NULL) - return null_error(); + if (o == NULL || key == NULL) + return null_error(); - m = o->ob_type->tp_as_mapping; - if (m && m->mp_subscript) - return m->mp_subscript(o, key); - - if (o->ob_type->tp_as_sequence) { - if (PyIndex_Check(key)) { - Py_ssize_t key_value; - key_value = PyNumber_AsSsize_t(key, PyExc_IndexError); - if (key_value == -1 && PyErr_Occurred()) - return NULL; - return PySequence_GetItem(o, key_value); - } - else if (o->ob_type->tp_as_sequence->sq_item) - return type_error("sequence index must " - "be integer, not '%.200s'", key); - } + m = o->ob_type->tp_as_mapping; + if (m && m->mp_subscript) + return m->mp_subscript(o, key); + + if (o->ob_type->tp_as_sequence) { + if (PyIndex_Check(key)) { + Py_ssize_t key_value; + key_value = PyNumber_AsSsize_t(key, PyExc_IndexError); + if (key_value == -1 && PyErr_Occurred()) + return NULL; + return PySequence_GetItem(o, key_value); + } + else if (o->ob_type->tp_as_sequence->sq_item) + return type_error("sequence index must " + "be integer, not '%.200s'", key); + } - return type_error("'%.200s' object is not subscriptable", o); + return type_error("'%.200s' object is not subscriptable", o); } int PyObject_SetItem(PyObject *o, PyObject *key, PyObject *value) { - PyMappingMethods *m; + PyMappingMethods *m; - if (o == NULL || key == NULL || value == NULL) { - null_error(); - return -1; - } - m = o->ob_type->tp_as_mapping; - if (m && m->mp_ass_subscript) - return m->mp_ass_subscript(o, key, value); - - if (o->ob_type->tp_as_sequence) { - if (PyIndex_Check(key)) { - Py_ssize_t key_value; - key_value = PyNumber_AsSsize_t(key, PyExc_IndexError); - if (key_value == -1 && PyErr_Occurred()) - return -1; - return PySequence_SetItem(o, key_value, value); - } - else if (o->ob_type->tp_as_sequence->sq_ass_item) { - type_error("sequence index must be " - "integer, not '%.200s'", key); - return -1; - } - } + if (o == NULL || key == NULL || value == NULL) { + null_error(); + return -1; + } + m = o->ob_type->tp_as_mapping; + if (m && m->mp_ass_subscript) + return m->mp_ass_subscript(o, key, value); + + if (o->ob_type->tp_as_sequence) { + if (PyIndex_Check(key)) { + Py_ssize_t key_value; + key_value = PyNumber_AsSsize_t(key, PyExc_IndexError); + if (key_value == -1 && PyErr_Occurred()) + return -1; + return PySequence_SetItem(o, key_value, value); + } + else if (o->ob_type->tp_as_sequence->sq_ass_item) { + type_error("sequence index must be " + "integer, not '%.200s'", key); + return -1; + } + } - type_error("'%.200s' object does not support item assignment", o); - return -1; + type_error("'%.200s' object does not support item assignment", o); + return -1; } int PyObject_DelItem(PyObject *o, PyObject *key) { - PyMappingMethods *m; + PyMappingMethods *m; - if (o == NULL || key == NULL) { - null_error(); - return -1; - } - m = o->ob_type->tp_as_mapping; - if (m && m->mp_ass_subscript) - return m->mp_ass_subscript(o, key, (PyObject*)NULL); - - if (o->ob_type->tp_as_sequence) { - if (PyIndex_Check(key)) { - Py_ssize_t key_value; - key_value = PyNumber_AsSsize_t(key, PyExc_IndexError); - if (key_value == -1 && PyErr_Occurred()) - return -1; - return PySequence_DelItem(o, key_value); - } - else if (o->ob_type->tp_as_sequence->sq_ass_item) { - type_error("sequence index must be " - "integer, not '%.200s'", key); - return -1; - } - } + if (o == NULL || key == NULL) { + null_error(); + return -1; + } + m = o->ob_type->tp_as_mapping; + if (m && m->mp_ass_subscript) + return m->mp_ass_subscript(o, key, (PyObject*)NULL); + + if (o->ob_type->tp_as_sequence) { + if (PyIndex_Check(key)) { + Py_ssize_t key_value; + key_value = PyNumber_AsSsize_t(key, PyExc_IndexError); + if (key_value == -1 && PyErr_Occurred()) + return -1; + return PySequence_DelItem(o, key_value); + } + else if (o->ob_type->tp_as_sequence->sq_ass_item) { + type_error("sequence index must be " + "integer, not '%.200s'", key); + return -1; + } + } - type_error("'%.200s' object does not support item deletion", o); - return -1; + type_error("'%.200s' object does not support item deletion", o); + return -1; } int PyObject_DelItemString(PyObject *o, char *key) { - PyObject *okey; - int ret; + PyObject *okey; + int ret; - if (o == NULL || key == NULL) { - null_error(); - return -1; - } - okey = PyUnicode_FromString(key); - if (okey == NULL) - return -1; - ret = PyObject_DelItem(o, okey); - Py_DECREF(okey); - return ret; + if (o == NULL || key == NULL) { + null_error(); + return -1; + } + okey = PyUnicode_FromString(key); + if (okey == NULL) + return -1; + ret = PyObject_DelItem(o, okey); + Py_DECREF(okey); + return ret; } /* We release the buffer right after use of this function which could @@ -224,104 +224,104 @@ */ int PyObject_AsCharBuffer(PyObject *obj, - const char **buffer, - Py_ssize_t *buffer_len) + const char **buffer, + Py_ssize_t *buffer_len) { - PyBufferProcs *pb; - Py_buffer view; + PyBufferProcs *pb; + Py_buffer view; - if (obj == NULL || buffer == NULL || buffer_len == NULL) { - null_error(); - return -1; - } - pb = obj->ob_type->tp_as_buffer; - if (pb == NULL || pb->bf_getbuffer == NULL) { - PyErr_SetString(PyExc_TypeError, - "expected an object with the buffer interface"); - return -1; - } - if ((*pb->bf_getbuffer)(obj, &view, PyBUF_SIMPLE)) return -1; - - *buffer = view.buf; - *buffer_len = view.len; - if (pb->bf_releasebuffer != NULL) - (*pb->bf_releasebuffer)(obj, &view); - Py_XDECREF(view.obj); - return 0; + if (obj == NULL || buffer == NULL || buffer_len == NULL) { + null_error(); + return -1; + } + pb = obj->ob_type->tp_as_buffer; + if (pb == NULL || pb->bf_getbuffer == NULL) { + PyErr_SetString(PyExc_TypeError, + "expected an object with the buffer interface"); + return -1; + } + if ((*pb->bf_getbuffer)(obj, &view, PyBUF_SIMPLE)) return -1; + + *buffer = view.buf; + *buffer_len = view.len; + if (pb->bf_releasebuffer != NULL) + (*pb->bf_releasebuffer)(obj, &view); + Py_XDECREF(view.obj); + return 0; } int PyObject_CheckReadBuffer(PyObject *obj) { - PyBufferProcs *pb = obj->ob_type->tp_as_buffer; - Py_buffer view; + PyBufferProcs *pb = obj->ob_type->tp_as_buffer; + Py_buffer view; - if (pb == NULL || - pb->bf_getbuffer == NULL) - return 0; - if ((*pb->bf_getbuffer)(obj, &view, PyBUF_SIMPLE) == -1) { - PyErr_Clear(); - return 0; - } - PyBuffer_Release(&view); - return 1; + if (pb == NULL || + pb->bf_getbuffer == NULL) + return 0; + if ((*pb->bf_getbuffer)(obj, &view, PyBUF_SIMPLE) == -1) { + PyErr_Clear(); + return 0; + } + PyBuffer_Release(&view); + return 1; } int PyObject_AsReadBuffer(PyObject *obj, - const void **buffer, - Py_ssize_t *buffer_len) + const void **buffer, + Py_ssize_t *buffer_len) { - PyBufferProcs *pb; - Py_buffer view; + PyBufferProcs *pb; + Py_buffer view; + + if (obj == NULL || buffer == NULL || buffer_len == NULL) { + null_error(); + return -1; + } + pb = obj->ob_type->tp_as_buffer; + if (pb == NULL || + pb->bf_getbuffer == NULL) { + PyErr_SetString(PyExc_TypeError, + "expected an object with a buffer interface"); + return -1; + } + + if ((*pb->bf_getbuffer)(obj, &view, PyBUF_SIMPLE)) return -1; - if (obj == NULL || buffer == NULL || buffer_len == NULL) { - null_error(); - return -1; - } - pb = obj->ob_type->tp_as_buffer; - if (pb == NULL || - pb->bf_getbuffer == NULL) { - PyErr_SetString(PyExc_TypeError, - "expected an object with a buffer interface"); - return -1; - } - - if ((*pb->bf_getbuffer)(obj, &view, PyBUF_SIMPLE)) return -1; - - *buffer = view.buf; - *buffer_len = view.len; - if (pb->bf_releasebuffer != NULL) - (*pb->bf_releasebuffer)(obj, &view); - Py_XDECREF(view.obj); - return 0; + *buffer = view.buf; + *buffer_len = view.len; + if (pb->bf_releasebuffer != NULL) + (*pb->bf_releasebuffer)(obj, &view); + Py_XDECREF(view.obj); + return 0; } int PyObject_AsWriteBuffer(PyObject *obj, - void **buffer, - Py_ssize_t *buffer_len) + void **buffer, + Py_ssize_t *buffer_len) { - PyBufferProcs *pb; - Py_buffer view; + PyBufferProcs *pb; + Py_buffer view; - if (obj == NULL || buffer == NULL || buffer_len == NULL) { - null_error(); - return -1; - } - pb = obj->ob_type->tp_as_buffer; - if (pb == NULL || - pb->bf_getbuffer == NULL || - ((*pb->bf_getbuffer)(obj, &view, PyBUF_WRITABLE) != 0)) { - PyErr_SetString(PyExc_TypeError, - "expected an object with a writable buffer interface"); - return -1; - } - - *buffer = view.buf; - *buffer_len = view.len; - if (pb->bf_releasebuffer != NULL) - (*pb->bf_releasebuffer)(obj, &view); - Py_XDECREF(view.obj); - return 0; + if (obj == NULL || buffer == NULL || buffer_len == NULL) { + null_error(); + return -1; + } + pb = obj->ob_type->tp_as_buffer; + if (pb == NULL || + pb->bf_getbuffer == NULL || + ((*pb->bf_getbuffer)(obj, &view, PyBUF_WRITABLE) != 0)) { + PyErr_SetString(PyExc_TypeError, + "expected an object with a writable buffer interface"); + return -1; + } + + *buffer = view.buf; + *buffer_len = view.len; + if (pb->bf_releasebuffer != NULL) + (*pb->bf_releasebuffer)(obj, &view); + Py_XDECREF(view.obj); + return 0; } /* Buffer C-API for Python 3.0 */ @@ -329,119 +329,119 @@ int PyObject_GetBuffer(PyObject *obj, Py_buffer *view, int flags) { - if (!PyObject_CheckBuffer(obj)) { - PyErr_Format(PyExc_TypeError, - "'%100s' does not support the buffer interface", - Py_TYPE(obj)->tp_name); - return -1; - } - return (*(obj->ob_type->tp_as_buffer->bf_getbuffer))(obj, view, flags); + if (!PyObject_CheckBuffer(obj)) { + PyErr_Format(PyExc_TypeError, + "'%100s' does not support the buffer interface", + Py_TYPE(obj)->tp_name); + return -1; + } + return (*(obj->ob_type->tp_as_buffer->bf_getbuffer))(obj, view, flags); } static int _IsFortranContiguous(Py_buffer *view) { - Py_ssize_t sd, dim; - int i; + Py_ssize_t sd, dim; + int i; - if (view->ndim == 0) return 1; - if (view->strides == NULL) return (view->ndim == 1); + if (view->ndim == 0) return 1; + if (view->strides == NULL) return (view->ndim == 1); - sd = view->itemsize; - if (view->ndim == 1) return (view->shape[0] == 1 || - sd == view->strides[0]); - for (i=0; indim; i++) { - dim = view->shape[i]; - if (dim == 0) return 1; - if (view->strides[i] != sd) return 0; - sd *= dim; - } - return 1; + sd = view->itemsize; + if (view->ndim == 1) return (view->shape[0] == 1 || + sd == view->strides[0]); + for (i=0; indim; i++) { + dim = view->shape[i]; + if (dim == 0) return 1; + if (view->strides[i] != sd) return 0; + sd *= dim; + } + return 1; } static int _IsCContiguous(Py_buffer *view) { - Py_ssize_t sd, dim; - int i; + Py_ssize_t sd, dim; + int i; - if (view->ndim == 0) return 1; - if (view->strides == NULL) return 1; + if (view->ndim == 0) return 1; + if (view->strides == NULL) return 1; - sd = view->itemsize; - if (view->ndim == 1) return (view->shape[0] == 1 || - sd == view->strides[0]); - for (i=view->ndim-1; i>=0; i--) { - dim = view->shape[i]; - if (dim == 0) return 1; - if (view->strides[i] != sd) return 0; - sd *= dim; - } - return 1; + sd = view->itemsize; + if (view->ndim == 1) return (view->shape[0] == 1 || + sd == view->strides[0]); + for (i=view->ndim-1; i>=0; i--) { + dim = view->shape[i]; + if (dim == 0) return 1; + if (view->strides[i] != sd) return 0; + sd *= dim; + } + return 1; } int PyBuffer_IsContiguous(Py_buffer *view, char fort) { - if (view->suboffsets != NULL) return 0; + if (view->suboffsets != NULL) return 0; - if (fort == 'C') - return _IsCContiguous(view); - else if (fort == 'F') - return _IsFortranContiguous(view); - else if (fort == 'A') - return (_IsCContiguous(view) || _IsFortranContiguous(view)); - return 0; + if (fort == 'C') + return _IsCContiguous(view); + else if (fort == 'F') + return _IsFortranContiguous(view); + else if (fort == 'A') + return (_IsCContiguous(view) || _IsFortranContiguous(view)); + return 0; } void* PyBuffer_GetPointer(Py_buffer *view, Py_ssize_t *indices) { - char* pointer; - int i; - pointer = (char *)view->buf; - for (i = 0; i < view->ndim; i++) { - pointer += view->strides[i]*indices[i]; - if ((view->suboffsets != NULL) && (view->suboffsets[i] >= 0)) { - pointer = *((char**)pointer) + view->suboffsets[i]; - } - } - return (void*)pointer; + char* pointer; + int i; + pointer = (char *)view->buf; + for (i = 0; i < view->ndim; i++) { + pointer += view->strides[i]*indices[i]; + if ((view->suboffsets != NULL) && (view->suboffsets[i] >= 0)) { + pointer = *((char**)pointer) + view->suboffsets[i]; + } + } + return (void*)pointer; } void _add_one_to_index_F(int nd, Py_ssize_t *index, Py_ssize_t *shape) { - int k; + int k; - for (k=0; k=0; k--) { - if (index[k] < shape[k]-1) { - index[k]++; - break; - } - else { - index[k] = 0; - } - } + for (k=nd-1; k>=0; k--) { + if (index[k] < shape[k]-1) { + index[k]++; + break; + } + else { + index[k] = 0; + } + } } /* view is not checked for consistency in either of these. It is @@ -452,242 +452,242 @@ int PyBuffer_ToContiguous(void *buf, Py_buffer *view, Py_ssize_t len, char fort) { - int k; - void (*addone)(int, Py_ssize_t *, Py_ssize_t *); - Py_ssize_t *indices, elements; - char *dest, *ptr; - - if (len > view->len) { - len = view->len; - } - - if (PyBuffer_IsContiguous(view, fort)) { - /* simplest copy is all that is needed */ - memcpy(buf, view->buf, len); - return 0; - } - - /* Otherwise a more elaborate scheme is needed */ - - /* XXX(nnorwitz): need to check for overflow! */ - indices = (Py_ssize_t *)PyMem_Malloc(sizeof(Py_ssize_t)*(view->ndim)); - if (indices == NULL) { - PyErr_NoMemory(); - return -1; - } - for (k=0; kndim;k++) { - indices[k] = 0; - } - - if (fort == 'F') { - addone = _add_one_to_index_F; - } - else { - addone = _add_one_to_index_C; - } - dest = buf; - /* XXX : This is not going to be the fastest code in the world - several optimizations are possible. - */ - elements = len / view->itemsize; - while (elements--) { - addone(view->ndim, indices, view->shape); - ptr = PyBuffer_GetPointer(view, indices); - memcpy(dest, ptr, view->itemsize); - dest += view->itemsize; - } - PyMem_Free(indices); - return 0; + int k; + void (*addone)(int, Py_ssize_t *, Py_ssize_t *); + Py_ssize_t *indices, elements; + char *dest, *ptr; + + if (len > view->len) { + len = view->len; + } + + if (PyBuffer_IsContiguous(view, fort)) { + /* simplest copy is all that is needed */ + memcpy(buf, view->buf, len); + return 0; + } + + /* Otherwise a more elaborate scheme is needed */ + + /* XXX(nnorwitz): need to check for overflow! */ + indices = (Py_ssize_t *)PyMem_Malloc(sizeof(Py_ssize_t)*(view->ndim)); + if (indices == NULL) { + PyErr_NoMemory(); + return -1; + } + for (k=0; kndim;k++) { + indices[k] = 0; + } + + if (fort == 'F') { + addone = _add_one_to_index_F; + } + else { + addone = _add_one_to_index_C; + } + dest = buf; + /* XXX : This is not going to be the fastest code in the world + several optimizations are possible. + */ + elements = len / view->itemsize; + while (elements--) { + addone(view->ndim, indices, view->shape); + ptr = PyBuffer_GetPointer(view, indices); + memcpy(dest, ptr, view->itemsize); + dest += view->itemsize; + } + PyMem_Free(indices); + return 0; } int PyBuffer_FromContiguous(Py_buffer *view, void *buf, Py_ssize_t len, char fort) { - int k; - void (*addone)(int, Py_ssize_t *, Py_ssize_t *); - Py_ssize_t *indices, elements; - char *src, *ptr; - - if (len > view->len) { - len = view->len; - } - - if (PyBuffer_IsContiguous(view, fort)) { - /* simplest copy is all that is needed */ - memcpy(view->buf, buf, len); - return 0; - } - - /* Otherwise a more elaborate scheme is needed */ - - /* XXX(nnorwitz): need to check for overflow! */ - indices = (Py_ssize_t *)PyMem_Malloc(sizeof(Py_ssize_t)*(view->ndim)); - if (indices == NULL) { - PyErr_NoMemory(); - return -1; - } - for (k=0; kndim;k++) { - indices[k] = 0; - } - - if (fort == 'F') { - addone = _add_one_to_index_F; - } - else { - addone = _add_one_to_index_C; - } - src = buf; - /* XXX : This is not going to be the fastest code in the world - several optimizations are possible. - */ - elements = len / view->itemsize; - while (elements--) { - addone(view->ndim, indices, view->shape); - ptr = PyBuffer_GetPointer(view, indices); - memcpy(ptr, src, view->itemsize); - src += view->itemsize; - } + int k; + void (*addone)(int, Py_ssize_t *, Py_ssize_t *); + Py_ssize_t *indices, elements; + char *src, *ptr; + + if (len > view->len) { + len = view->len; + } + + if (PyBuffer_IsContiguous(view, fort)) { + /* simplest copy is all that is needed */ + memcpy(view->buf, buf, len); + return 0; + } + + /* Otherwise a more elaborate scheme is needed */ + + /* XXX(nnorwitz): need to check for overflow! */ + indices = (Py_ssize_t *)PyMem_Malloc(sizeof(Py_ssize_t)*(view->ndim)); + if (indices == NULL) { + PyErr_NoMemory(); + return -1; + } + for (k=0; kndim;k++) { + indices[k] = 0; + } + + if (fort == 'F') { + addone = _add_one_to_index_F; + } + else { + addone = _add_one_to_index_C; + } + src = buf; + /* XXX : This is not going to be the fastest code in the world + several optimizations are possible. + */ + elements = len / view->itemsize; + while (elements--) { + addone(view->ndim, indices, view->shape); + ptr = PyBuffer_GetPointer(view, indices); + memcpy(ptr, src, view->itemsize); + src += view->itemsize; + } - PyMem_Free(indices); - return 0; + PyMem_Free(indices); + return 0; } int PyObject_CopyData(PyObject *dest, PyObject *src) { - Py_buffer view_dest, view_src; - int k; - Py_ssize_t *indices, elements; - char *dptr, *sptr; - - if (!PyObject_CheckBuffer(dest) || - !PyObject_CheckBuffer(src)) { - PyErr_SetString(PyExc_TypeError, - "both destination and source must have the "\ - "buffer interface"); - return -1; - } - - if (PyObject_GetBuffer(dest, &view_dest, PyBUF_FULL) != 0) return -1; - if (PyObject_GetBuffer(src, &view_src, PyBUF_FULL_RO) != 0) { - PyBuffer_Release(&view_dest); - return -1; - } - - if (view_dest.len < view_src.len) { - PyErr_SetString(PyExc_BufferError, - "destination is too small to receive data from source"); - PyBuffer_Release(&view_dest); - PyBuffer_Release(&view_src); - return -1; - } - - if ((PyBuffer_IsContiguous(&view_dest, 'C') && - PyBuffer_IsContiguous(&view_src, 'C')) || - (PyBuffer_IsContiguous(&view_dest, 'F') && - PyBuffer_IsContiguous(&view_src, 'F'))) { - /* simplest copy is all that is needed */ - memcpy(view_dest.buf, view_src.buf, view_src.len); - PyBuffer_Release(&view_dest); - PyBuffer_Release(&view_src); - return 0; - } - - /* Otherwise a more elaborate copy scheme is needed */ - - /* XXX(nnorwitz): need to check for overflow! */ - indices = (Py_ssize_t *)PyMem_Malloc(sizeof(Py_ssize_t)*view_src.ndim); - if (indices == NULL) { - PyErr_NoMemory(); - PyBuffer_Release(&view_dest); - PyBuffer_Release(&view_src); - return -1; - } - for (k=0; k=0; k--) { - strides[k] = sd; - sd *= shape[k]; - } - } - return; + sd = itemsize; + if (fort == 'F') { + for (k=0; k=0; k--) { + strides[k] = sd; + sd *= shape[k]; + } + } + return; } int PyBuffer_FillInfo(Py_buffer *view, PyObject *obj, void *buf, Py_ssize_t len, - int readonly, int flags) + int readonly, int flags) { - if (view == NULL) return 0; - if (((flags & PyBUF_WRITABLE) == PyBUF_WRITABLE) && - (readonly == 1)) { - PyErr_SetString(PyExc_BufferError, - "Object is not writable."); - return -1; - } - - view->obj = obj; - if (obj) - Py_INCREF(obj); - view->buf = buf; - view->len = len; - view->readonly = readonly; - view->itemsize = 1; - view->format = NULL; - if ((flags & PyBUF_FORMAT) == PyBUF_FORMAT) - view->format = "B"; - view->ndim = 1; - view->shape = NULL; - if ((flags & PyBUF_ND) == PyBUF_ND) - view->shape = &(view->len); - view->strides = NULL; - if ((flags & PyBUF_STRIDES) == PyBUF_STRIDES) - view->strides = &(view->itemsize); - view->suboffsets = NULL; - view->internal = NULL; - return 0; + if (view == NULL) return 0; + if (((flags & PyBUF_WRITABLE) == PyBUF_WRITABLE) && + (readonly == 1)) { + PyErr_SetString(PyExc_BufferError, + "Object is not writable."); + return -1; + } + + view->obj = obj; + if (obj) + Py_INCREF(obj); + view->buf = buf; + view->len = len; + view->readonly = readonly; + view->itemsize = 1; + view->format = NULL; + if ((flags & PyBUF_FORMAT) == PyBUF_FORMAT) + view->format = "B"; + view->ndim = 1; + view->shape = NULL; + if ((flags & PyBUF_ND) == PyBUF_ND) + view->shape = &(view->len); + view->strides = NULL; + if ((flags & PyBUF_STRIDES) == PyBUF_STRIDES) + view->strides = &(view->itemsize); + view->suboffsets = NULL; + view->internal = NULL; + return 0; } void PyBuffer_Release(Py_buffer *view) { - PyObject *obj = view->obj; - if (obj && Py_TYPE(obj)->tp_as_buffer && Py_TYPE(obj)->tp_as_buffer->bf_releasebuffer) - Py_TYPE(obj)->tp_as_buffer->bf_releasebuffer(obj, view); - Py_XDECREF(obj); - view->obj = NULL; + PyObject *obj = view->obj; + if (obj && Py_TYPE(obj)->tp_as_buffer && Py_TYPE(obj)->tp_as_buffer->bf_releasebuffer) + Py_TYPE(obj)->tp_as_buffer->bf_releasebuffer(obj, view); + Py_XDECREF(obj); + view->obj = NULL; } PyObject * @@ -700,41 +700,41 @@ /* Initialize cached value */ if (str__format__ == NULL) { - /* Initialize static variable needed by _PyType_Lookup */ - str__format__ = PyUnicode_FromString("__format__"); - if (str__format__ == NULL) - goto done; + /* Initialize static variable needed by _PyType_Lookup */ + str__format__ = PyUnicode_FromString("__format__"); + if (str__format__ == NULL) + goto done; } /* If no format_spec is provided, use an empty string */ if (format_spec == NULL) { - empty = PyUnicode_FromUnicode(NULL, 0); - format_spec = empty; + empty = PyUnicode_FromUnicode(NULL, 0); + format_spec = empty; } /* Make sure the type is initialized. float gets initialized late */ if (Py_TYPE(obj)->tp_dict == NULL) - if (PyType_Ready(Py_TYPE(obj)) < 0) - goto done; + if (PyType_Ready(Py_TYPE(obj)) < 0) + goto done; /* Find the (unbound!) __format__ method (a borrowed reference) */ meth = _PyType_Lookup(Py_TYPE(obj), str__format__); if (meth == NULL) { - PyErr_Format(PyExc_TypeError, - "Type %.100s doesn't define __format__", - Py_TYPE(obj)->tp_name); - goto done; + PyErr_Format(PyExc_TypeError, + "Type %.100s doesn't define __format__", + Py_TYPE(obj)->tp_name); + goto done; } /* And call it, binding it to the value */ result = PyObject_CallFunctionObjArgs(meth, obj, format_spec, NULL); if (result && !PyUnicode_Check(result)) { - PyErr_SetString(PyExc_TypeError, - "__format__ method did not return string"); - Py_DECREF(result); - result = NULL; - goto done; + PyErr_SetString(PyExc_TypeError, + "__format__ method did not return string"); + Py_DECREF(result); + result = NULL; + goto done; } done: @@ -746,24 +746,24 @@ int PyNumber_Check(PyObject *o) { - return o && o->ob_type->tp_as_number && - (o->ob_type->tp_as_number->nb_int || - o->ob_type->tp_as_number->nb_float); + return o && o->ob_type->tp_as_number && + (o->ob_type->tp_as_number->nb_int || + o->ob_type->tp_as_number->nb_float); } /* Binary operators */ #define NB_SLOT(x) offsetof(PyNumberMethods, x) #define NB_BINOP(nb_methods, slot) \ - (*(binaryfunc*)(& ((char*)nb_methods)[slot])) + (*(binaryfunc*)(& ((char*)nb_methods)[slot])) #define NB_TERNOP(nb_methods, slot) \ - (*(ternaryfunc*)(& ((char*)nb_methods)[slot])) + (*(ternaryfunc*)(& ((char*)nb_methods)[slot])) /* Calling scheme used for binary operations: Order operations are tried until either a valid result or error: - w.op(v,w)[*], v.op(v,w), w.op(v,w) + w.op(v,w)[*], v.op(v,w), w.op(v,w) [*] only when v->ob_type != w->ob_type && w->ob_type is a subclass of v->ob_type @@ -772,62 +772,62 @@ static PyObject * binary_op1(PyObject *v, PyObject *w, const int op_slot) { - PyObject *x; - binaryfunc slotv = NULL; - binaryfunc slotw = NULL; - - if (v->ob_type->tp_as_number != NULL) - slotv = NB_BINOP(v->ob_type->tp_as_number, op_slot); - if (w->ob_type != v->ob_type && - w->ob_type->tp_as_number != NULL) { - slotw = NB_BINOP(w->ob_type->tp_as_number, op_slot); - if (slotw == slotv) - slotw = NULL; - } - if (slotv) { - if (slotw && PyType_IsSubtype(w->ob_type, v->ob_type)) { - x = slotw(v, w); - if (x != Py_NotImplemented) - return x; - Py_DECREF(x); /* can't do it */ - slotw = NULL; - } - x = slotv(v, w); - if (x != Py_NotImplemented) - return x; - Py_DECREF(x); /* can't do it */ - } - if (slotw) { - x = slotw(v, w); - if (x != Py_NotImplemented) - return x; - Py_DECREF(x); /* can't do it */ - } - Py_INCREF(Py_NotImplemented); - return Py_NotImplemented; + PyObject *x; + binaryfunc slotv = NULL; + binaryfunc slotw = NULL; + + if (v->ob_type->tp_as_number != NULL) + slotv = NB_BINOP(v->ob_type->tp_as_number, op_slot); + if (w->ob_type != v->ob_type && + w->ob_type->tp_as_number != NULL) { + slotw = NB_BINOP(w->ob_type->tp_as_number, op_slot); + if (slotw == slotv) + slotw = NULL; + } + if (slotv) { + if (slotw && PyType_IsSubtype(w->ob_type, v->ob_type)) { + x = slotw(v, w); + if (x != Py_NotImplemented) + return x; + Py_DECREF(x); /* can't do it */ + slotw = NULL; + } + x = slotv(v, w); + if (x != Py_NotImplemented) + return x; + Py_DECREF(x); /* can't do it */ + } + if (slotw) { + x = slotw(v, w); + if (x != Py_NotImplemented) + return x; + Py_DECREF(x); /* can't do it */ + } + Py_INCREF(Py_NotImplemented); + return Py_NotImplemented; } static PyObject * binop_type_error(PyObject *v, PyObject *w, const char *op_name) { - PyErr_Format(PyExc_TypeError, - "unsupported operand type(s) for %.100s: " - "'%.100s' and '%.100s'", - op_name, - v->ob_type->tp_name, - w->ob_type->tp_name); - return NULL; + PyErr_Format(PyExc_TypeError, + "unsupported operand type(s) for %.100s: " + "'%.100s' and '%.100s'", + op_name, + v->ob_type->tp_name, + w->ob_type->tp_name); + return NULL; } static PyObject * binary_op(PyObject *v, PyObject *w, const int op_slot, const char *op_name) { - PyObject *result = binary_op1(v, w, op_slot); - if (result == Py_NotImplemented) { - Py_DECREF(result); - return binop_type_error(v, w, op_name); - } - return result; + PyObject *result = binary_op1(v, w, op_slot); + if (result == Py_NotImplemented) { + Py_DECREF(result); + return binop_type_error(v, w, op_name); + } + return result; } @@ -835,86 +835,86 @@ Calling scheme used for ternary operations: Order operations are tried until either a valid result or error: - v.op(v,w,z), w.op(v,w,z), z.op(v,w,z) + v.op(v,w,z), w.op(v,w,z), z.op(v,w,z) */ static PyObject * ternary_op(PyObject *v, - PyObject *w, - PyObject *z, - const int op_slot, - const char *op_name) -{ - PyNumberMethods *mv, *mw, *mz; - PyObject *x = NULL; - ternaryfunc slotv = NULL; - ternaryfunc slotw = NULL; - ternaryfunc slotz = NULL; - - mv = v->ob_type->tp_as_number; - mw = w->ob_type->tp_as_number; - if (mv != NULL) - slotv = NB_TERNOP(mv, op_slot); - if (w->ob_type != v->ob_type && - mw != NULL) { - slotw = NB_TERNOP(mw, op_slot); - if (slotw == slotv) - slotw = NULL; - } - if (slotv) { - if (slotw && PyType_IsSubtype(w->ob_type, v->ob_type)) { - x = slotw(v, w, z); - if (x != Py_NotImplemented) - return x; - Py_DECREF(x); /* can't do it */ - slotw = NULL; - } - x = slotv(v, w, z); - if (x != Py_NotImplemented) - return x; - Py_DECREF(x); /* can't do it */ - } - if (slotw) { - x = slotw(v, w, z); - if (x != Py_NotImplemented) - return x; - Py_DECREF(x); /* can't do it */ - } - mz = z->ob_type->tp_as_number; - if (mz != NULL) { - slotz = NB_TERNOP(mz, op_slot); - if (slotz == slotv || slotz == slotw) - slotz = NULL; - if (slotz) { - x = slotz(v, w, z); - if (x != Py_NotImplemented) - return x; - Py_DECREF(x); /* can't do it */ - } - } - - if (z == Py_None) - PyErr_Format( - PyExc_TypeError, - "unsupported operand type(s) for ** or pow(): " - "'%.100s' and '%.100s'", - v->ob_type->tp_name, - w->ob_type->tp_name); - else - PyErr_Format( - PyExc_TypeError, - "unsupported operand type(s) for pow(): " - "'%.100s', '%.100s', '%.100s'", - v->ob_type->tp_name, - w->ob_type->tp_name, - z->ob_type->tp_name); - return NULL; + PyObject *w, + PyObject *z, + const int op_slot, + const char *op_name) +{ + PyNumberMethods *mv, *mw, *mz; + PyObject *x = NULL; + ternaryfunc slotv = NULL; + ternaryfunc slotw = NULL; + ternaryfunc slotz = NULL; + + mv = v->ob_type->tp_as_number; + mw = w->ob_type->tp_as_number; + if (mv != NULL) + slotv = NB_TERNOP(mv, op_slot); + if (w->ob_type != v->ob_type && + mw != NULL) { + slotw = NB_TERNOP(mw, op_slot); + if (slotw == slotv) + slotw = NULL; + } + if (slotv) { + if (slotw && PyType_IsSubtype(w->ob_type, v->ob_type)) { + x = slotw(v, w, z); + if (x != Py_NotImplemented) + return x; + Py_DECREF(x); /* can't do it */ + slotw = NULL; + } + x = slotv(v, w, z); + if (x != Py_NotImplemented) + return x; + Py_DECREF(x); /* can't do it */ + } + if (slotw) { + x = slotw(v, w, z); + if (x != Py_NotImplemented) + return x; + Py_DECREF(x); /* can't do it */ + } + mz = z->ob_type->tp_as_number; + if (mz != NULL) { + slotz = NB_TERNOP(mz, op_slot); + if (slotz == slotv || slotz == slotw) + slotz = NULL; + if (slotz) { + x = slotz(v, w, z); + if (x != Py_NotImplemented) + return x; + Py_DECREF(x); /* can't do it */ + } + } + + if (z == Py_None) + PyErr_Format( + PyExc_TypeError, + "unsupported operand type(s) for ** or pow(): " + "'%.100s' and '%.100s'", + v->ob_type->tp_name, + w->ob_type->tp_name); + else + PyErr_Format( + PyExc_TypeError, + "unsupported operand type(s) for pow(): " + "'%.100s', '%.100s', '%.100s'", + v->ob_type->tp_name, + w->ob_type->tp_name, + z->ob_type->tp_name); + return NULL; } #define BINARY_FUNC(func, op, op_name) \ PyObject * \ func(PyObject *v, PyObject *w) { \ - return binary_op(v, w, NB_SLOT(op), op_name); \ + return binary_op(v, w, NB_SLOT(op), op_name); \ } BINARY_FUNC(PyNumber_Or, nb_or, "|") @@ -928,75 +928,75 @@ PyObject * PyNumber_Add(PyObject *v, PyObject *w) { - PyObject *result = binary_op1(v, w, NB_SLOT(nb_add)); - if (result == Py_NotImplemented) { - PySequenceMethods *m = v->ob_type->tp_as_sequence; - Py_DECREF(result); - if (m && m->sq_concat) { - return (*m->sq_concat)(v, w); - } - result = binop_type_error(v, w, "+"); - } - return result; + PyObject *result = binary_op1(v, w, NB_SLOT(nb_add)); + if (result == Py_NotImplemented) { + PySequenceMethods *m = v->ob_type->tp_as_sequence; + Py_DECREF(result); + if (m && m->sq_concat) { + return (*m->sq_concat)(v, w); + } + result = binop_type_error(v, w, "+"); + } + return result; } static PyObject * sequence_repeat(ssizeargfunc repeatfunc, PyObject *seq, PyObject *n) { - Py_ssize_t count; - if (PyIndex_Check(n)) { - count = PyNumber_AsSsize_t(n, PyExc_OverflowError); - if (count == -1 && PyErr_Occurred()) - return NULL; - } - else { - return type_error("can't multiply sequence by " - "non-int of type '%.200s'", n); - } - return (*repeatfunc)(seq, count); + Py_ssize_t count; + if (PyIndex_Check(n)) { + count = PyNumber_AsSsize_t(n, PyExc_OverflowError); + if (count == -1 && PyErr_Occurred()) + return NULL; + } + else { + return type_error("can't multiply sequence by " + "non-int of type '%.200s'", n); + } + return (*repeatfunc)(seq, count); } PyObject * PyNumber_Multiply(PyObject *v, PyObject *w) { - PyObject *result = binary_op1(v, w, NB_SLOT(nb_multiply)); - if (result == Py_NotImplemented) { - PySequenceMethods *mv = v->ob_type->tp_as_sequence; - PySequenceMethods *mw = w->ob_type->tp_as_sequence; - Py_DECREF(result); - if (mv && mv->sq_repeat) { - return sequence_repeat(mv->sq_repeat, v, w); - } - else if (mw && mw->sq_repeat) { - return sequence_repeat(mw->sq_repeat, w, v); - } - result = binop_type_error(v, w, "*"); - } - return result; + PyObject *result = binary_op1(v, w, NB_SLOT(nb_multiply)); + if (result == Py_NotImplemented) { + PySequenceMethods *mv = v->ob_type->tp_as_sequence; + PySequenceMethods *mw = w->ob_type->tp_as_sequence; + Py_DECREF(result); + if (mv && mv->sq_repeat) { + return sequence_repeat(mv->sq_repeat, v, w); + } + else if (mw && mw->sq_repeat) { + return sequence_repeat(mw->sq_repeat, w, v); + } + result = binop_type_error(v, w, "*"); + } + return result; } PyObject * PyNumber_FloorDivide(PyObject *v, PyObject *w) { - return binary_op(v, w, NB_SLOT(nb_floor_divide), "//"); + return binary_op(v, w, NB_SLOT(nb_floor_divide), "//"); } PyObject * PyNumber_TrueDivide(PyObject *v, PyObject *w) { - return binary_op(v, w, NB_SLOT(nb_true_divide), "/"); + return binary_op(v, w, NB_SLOT(nb_true_divide), "/"); } PyObject * PyNumber_Remainder(PyObject *v, PyObject *w) { - return binary_op(v, w, NB_SLOT(nb_remainder), "%"); + return binary_op(v, w, NB_SLOT(nb_remainder), "%"); } PyObject * PyNumber_Power(PyObject *v, PyObject *w, PyObject *z) { - return ternary_op(v, w, z, NB_SLOT(nb_power), "** or pow()"); + return ternary_op(v, w, z, NB_SLOT(nb_power), "** or pow()"); } /* Binary in-place operators */ @@ -1018,37 +1018,37 @@ static PyObject * binary_iop1(PyObject *v, PyObject *w, const int iop_slot, const int op_slot) { - PyNumberMethods *mv = v->ob_type->tp_as_number; - if (mv != NULL) { - binaryfunc slot = NB_BINOP(mv, iop_slot); - if (slot) { - PyObject *x = (slot)(v, w); - if (x != Py_NotImplemented) { - return x; - } - Py_DECREF(x); - } - } - return binary_op1(v, w, op_slot); + PyNumberMethods *mv = v->ob_type->tp_as_number; + if (mv != NULL) { + binaryfunc slot = NB_BINOP(mv, iop_slot); + if (slot) { + PyObject *x = (slot)(v, w); + if (x != Py_NotImplemented) { + return x; + } + Py_DECREF(x); + } + } + return binary_op1(v, w, op_slot); } static PyObject * binary_iop(PyObject *v, PyObject *w, const int iop_slot, const int op_slot, - const char *op_name) + const char *op_name) { - PyObject *result = binary_iop1(v, w, iop_slot, op_slot); - if (result == Py_NotImplemented) { - Py_DECREF(result); - return binop_type_error(v, w, op_name); - } - return result; + PyObject *result = binary_iop1(v, w, iop_slot, op_slot); + if (result == Py_NotImplemented) { + Py_DECREF(result); + return binop_type_error(v, w, op_name); + } + return result; } #define INPLACE_BINOP(func, iop, op, op_name) \ - PyObject * \ - func(PyObject *v, PyObject *w) { \ - return binary_iop(v, w, NB_SLOT(iop), NB_SLOT(op), op_name); \ - } + PyObject * \ + func(PyObject *v, PyObject *w) { \ + return binary_iop(v, w, NB_SLOT(iop), NB_SLOT(op), op_name); \ + } INPLACE_BINOP(PyNumber_InPlaceOr, nb_inplace_or, nb_or, "|=") INPLACE_BINOP(PyNumber_InPlaceXor, nb_inplace_xor, nb_xor, "^=") @@ -1060,84 +1060,84 @@ PyObject * PyNumber_InPlaceFloorDivide(PyObject *v, PyObject *w) { - return binary_iop(v, w, NB_SLOT(nb_inplace_floor_divide), - NB_SLOT(nb_floor_divide), "//="); + return binary_iop(v, w, NB_SLOT(nb_inplace_floor_divide), + NB_SLOT(nb_floor_divide), "//="); } PyObject * PyNumber_InPlaceTrueDivide(PyObject *v, PyObject *w) { - return binary_iop(v, w, NB_SLOT(nb_inplace_true_divide), - NB_SLOT(nb_true_divide), "/="); + return binary_iop(v, w, NB_SLOT(nb_inplace_true_divide), + NB_SLOT(nb_true_divide), "/="); } PyObject * PyNumber_InPlaceAdd(PyObject *v, PyObject *w) { - PyObject *result = binary_iop1(v, w, NB_SLOT(nb_inplace_add), - NB_SLOT(nb_add)); - if (result == Py_NotImplemented) { - PySequenceMethods *m = v->ob_type->tp_as_sequence; - Py_DECREF(result); - if (m != NULL) { - binaryfunc f = NULL; - f = m->sq_inplace_concat; - if (f == NULL) - f = m->sq_concat; - if (f != NULL) - return (*f)(v, w); - } - result = binop_type_error(v, w, "+="); - } - return result; + PyObject *result = binary_iop1(v, w, NB_SLOT(nb_inplace_add), + NB_SLOT(nb_add)); + if (result == Py_NotImplemented) { + PySequenceMethods *m = v->ob_type->tp_as_sequence; + Py_DECREF(result); + if (m != NULL) { + binaryfunc f = NULL; + f = m->sq_inplace_concat; + if (f == NULL) + f = m->sq_concat; + if (f != NULL) + return (*f)(v, w); + } + result = binop_type_error(v, w, "+="); + } + return result; } PyObject * PyNumber_InPlaceMultiply(PyObject *v, PyObject *w) { - PyObject *result = binary_iop1(v, w, NB_SLOT(nb_inplace_multiply), - NB_SLOT(nb_multiply)); - if (result == Py_NotImplemented) { - ssizeargfunc f = NULL; - PySequenceMethods *mv = v->ob_type->tp_as_sequence; - PySequenceMethods *mw = w->ob_type->tp_as_sequence; - Py_DECREF(result); - if (mv != NULL) { - f = mv->sq_inplace_repeat; - if (f == NULL) - f = mv->sq_repeat; - if (f != NULL) - return sequence_repeat(f, v, w); - } - else if (mw != NULL) { - /* Note that the right hand operand should not be - * mutated in this case so sq_inplace_repeat is not - * used. */ - if (mw->sq_repeat) - return sequence_repeat(mw->sq_repeat, w, v); - } - result = binop_type_error(v, w, "*="); - } - return result; + PyObject *result = binary_iop1(v, w, NB_SLOT(nb_inplace_multiply), + NB_SLOT(nb_multiply)); + if (result == Py_NotImplemented) { + ssizeargfunc f = NULL; + PySequenceMethods *mv = v->ob_type->tp_as_sequence; + PySequenceMethods *mw = w->ob_type->tp_as_sequence; + Py_DECREF(result); + if (mv != NULL) { + f = mv->sq_inplace_repeat; + if (f == NULL) + f = mv->sq_repeat; + if (f != NULL) + return sequence_repeat(f, v, w); + } + else if (mw != NULL) { + /* Note that the right hand operand should not be + * mutated in this case so sq_inplace_repeat is not + * used. */ + if (mw->sq_repeat) + return sequence_repeat(mw->sq_repeat, w, v); + } + result = binop_type_error(v, w, "*="); + } + return result; } PyObject * PyNumber_InPlaceRemainder(PyObject *v, PyObject *w) { - return binary_iop(v, w, NB_SLOT(nb_inplace_remainder), - NB_SLOT(nb_remainder), "%="); + return binary_iop(v, w, NB_SLOT(nb_inplace_remainder), + NB_SLOT(nb_remainder), "%="); } PyObject * PyNumber_InPlacePower(PyObject *v, PyObject *w, PyObject *z) { - if (v->ob_type->tp_as_number && - v->ob_type->tp_as_number->nb_inplace_power != NULL) { - return ternary_op(v, w, z, NB_SLOT(nb_inplace_power), "**="); - } - else { - return ternary_op(v, w, z, NB_SLOT(nb_power), "**="); - } + if (v->ob_type->tp_as_number && + v->ob_type->tp_as_number->nb_inplace_power != NULL) { + return ternary_op(v, w, z, NB_SLOT(nb_inplace_power), "**="); + } + else { + return ternary_op(v, w, z, NB_SLOT(nb_power), "**="); + } } @@ -1146,57 +1146,57 @@ PyObject * PyNumber_Negative(PyObject *o) { - PyNumberMethods *m; + PyNumberMethods *m; - if (o == NULL) - return null_error(); - m = o->ob_type->tp_as_number; - if (m && m->nb_negative) - return (*m->nb_negative)(o); + if (o == NULL) + return null_error(); + m = o->ob_type->tp_as_number; + if (m && m->nb_negative) + return (*m->nb_negative)(o); - return type_error("bad operand type for unary -: '%.200s'", o); + return type_error("bad operand type for unary -: '%.200s'", o); } PyObject * PyNumber_Positive(PyObject *o) { - PyNumberMethods *m; + PyNumberMethods *m; - if (o == NULL) - return null_error(); - m = o->ob_type->tp_as_number; - if (m && m->nb_positive) - return (*m->nb_positive)(o); + if (o == NULL) + return null_error(); + m = o->ob_type->tp_as_number; + if (m && m->nb_positive) + return (*m->nb_positive)(o); - return type_error("bad operand type for unary +: '%.200s'", o); + return type_error("bad operand type for unary +: '%.200s'", o); } PyObject * PyNumber_Invert(PyObject *o) { - PyNumberMethods *m; + PyNumberMethods *m; - if (o == NULL) - return null_error(); - m = o->ob_type->tp_as_number; - if (m && m->nb_invert) - return (*m->nb_invert)(o); + if (o == NULL) + return null_error(); + m = o->ob_type->tp_as_number; + if (m && m->nb_invert) + return (*m->nb_invert)(o); - return type_error("bad operand type for unary ~: '%.200s'", o); + return type_error("bad operand type for unary ~: '%.200s'", o); } PyObject * PyNumber_Absolute(PyObject *o) { - PyNumberMethods *m; + PyNumberMethods *m; - if (o == NULL) - return null_error(); - m = o->ob_type->tp_as_number; - if (m && m->nb_absolute) - return m->nb_absolute(o); + if (o == NULL) + return null_error(); + m = o->ob_type->tp_as_number; + if (m && m->nb_absolute) + return m->nb_absolute(o); - return type_error("bad operand type for abs(): '%.200s'", o); + return type_error("bad operand type for abs(): '%.200s'", o); } /* Return a Python Int or Long from the object item @@ -1206,30 +1206,30 @@ PyObject * PyNumber_Index(PyObject *item) { - PyObject *result = NULL; - if (item == NULL) - return null_error(); - if (PyLong_Check(item)) { - Py_INCREF(item); - return item; - } - if (PyIndex_Check(item)) { - result = item->ob_type->tp_as_number->nb_index(item); - if (result && !PyLong_Check(result)) { - PyErr_Format(PyExc_TypeError, - "__index__ returned non-int " - "(type %.200s)", - result->ob_type->tp_name); - Py_DECREF(result); - return NULL; - } - } - else { - PyErr_Format(PyExc_TypeError, - "'%.200s' object cannot be interpreted " - "as an integer", item->ob_type->tp_name); - } - return result; + PyObject *result = NULL; + if (item == NULL) + return null_error(); + if (PyLong_Check(item)) { + Py_INCREF(item); + return item; + } + if (PyIndex_Check(item)) { + result = item->ob_type->tp_as_number->nb_index(item); + if (result && !PyLong_Check(result)) { + PyErr_Format(PyExc_TypeError, + "__index__ returned non-int " + "(type %.200s)", + result->ob_type->tp_name); + Py_DECREF(result); + return NULL; + } + } + else { + PyErr_Format(PyExc_TypeError, + "'%.200s' object cannot be interpreted " + "as an integer", item->ob_type->tp_name); + } + return result; } /* Return an error on Overflow only if err is not NULL*/ @@ -1237,79 +1237,79 @@ Py_ssize_t PyNumber_AsSsize_t(PyObject *item, PyObject *err) { - Py_ssize_t result; - PyObject *runerr; - PyObject *value = PyNumber_Index(item); - if (value == NULL) - return -1; - - /* We're done if PyLong_AsSsize_t() returns without error. */ - result = PyLong_AsSsize_t(value); - if (result != -1 || !(runerr = PyErr_Occurred())) - goto finish; - - /* Error handling code -- only manage OverflowError differently */ - if (!PyErr_GivenExceptionMatches(runerr, PyExc_OverflowError)) - goto finish; - - PyErr_Clear(); - /* If no error-handling desired then the default clipping - is sufficient. - */ - if (!err) { - assert(PyLong_Check(value)); - /* Whether or not it is less than or equal to - zero is determined by the sign of ob_size - */ - if (_PyLong_Sign(value) < 0) - result = PY_SSIZE_T_MIN; - else - result = PY_SSIZE_T_MAX; - } - else { - /* Otherwise replace the error with caller's error object. */ - PyErr_Format(err, - "cannot fit '%.200s' into an index-sized integer", - item->ob_type->tp_name); - } + Py_ssize_t result; + PyObject *runerr; + PyObject *value = PyNumber_Index(item); + if (value == NULL) + return -1; + + /* We're done if PyLong_AsSsize_t() returns without error. */ + result = PyLong_AsSsize_t(value); + if (result != -1 || !(runerr = PyErr_Occurred())) + goto finish; + + /* Error handling code -- only manage OverflowError differently */ + if (!PyErr_GivenExceptionMatches(runerr, PyExc_OverflowError)) + goto finish; + + PyErr_Clear(); + /* If no error-handling desired then the default clipping + is sufficient. + */ + if (!err) { + assert(PyLong_Check(value)); + /* Whether or not it is less than or equal to + zero is determined by the sign of ob_size + */ + if (_PyLong_Sign(value) < 0) + result = PY_SSIZE_T_MIN; + else + result = PY_SSIZE_T_MAX; + } + else { + /* Otherwise replace the error with caller's error object. */ + PyErr_Format(err, + "cannot fit '%.200s' into an index-sized integer", + item->ob_type->tp_name); + } finish: - Py_DECREF(value); - return result; + Py_DECREF(value); + return result; } PyObject * _PyNumber_ConvertIntegralToInt(PyObject *integral, const char* error_format) { - static PyObject *int_name = NULL; - if (int_name == NULL) { - int_name = PyUnicode_InternFromString("__int__"); - if (int_name == NULL) - return NULL; - } - - if (integral && !PyLong_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); - if (int_func == NULL) { - PyErr_Clear(); /* Raise a different error. */ - goto non_integral_error; - } - Py_DECREF(integral); - integral = PyEval_CallObject(int_func, NULL); - Py_DECREF(int_func); - if (integral && !PyLong_Check(integral)) { - goto non_integral_error; - } - } - return integral; + static PyObject *int_name = NULL; + if (int_name == NULL) { + int_name = PyUnicode_InternFromString("__int__"); + if (int_name == NULL) + return NULL; + } + + if (integral && !PyLong_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); + if (int_func == NULL) { + PyErr_Clear(); /* Raise a different error. */ + goto non_integral_error; + } + Py_DECREF(integral); + integral = PyEval_CallObject(int_func, NULL); + Py_DECREF(int_func); + if (integral && !PyLong_Check(integral)) { + goto non_integral_error; + } + } + return integral; non_integral_error: - PyErr_Format(PyExc_TypeError, error_format, Py_TYPE(integral)->tp_name); - Py_DECREF(integral); - return NULL; + PyErr_Format(PyExc_TypeError, error_format, Py_TYPE(integral)->tp_name); + Py_DECREF(integral); + return NULL; } @@ -1317,134 +1317,134 @@ static PyObject * long_from_string(const char *s, Py_ssize_t len) { - char *end; - PyObject *x; + char *end; + PyObject *x; - x = PyLong_FromString((char*)s, &end, 10); - if (x == NULL) - return NULL; - if (end != s + len) { - PyErr_SetString(PyExc_ValueError, - "null byte in argument for int()"); - Py_DECREF(x); - return NULL; - } - return x; + x = PyLong_FromString((char*)s, &end, 10); + if (x == NULL) + return NULL; + if (end != s + len) { + PyErr_SetString(PyExc_ValueError, + "null byte in argument for int()"); + Py_DECREF(x); + return NULL; + } + return x; } PyObject * PyNumber_Long(PyObject *o) { - PyNumberMethods *m; - static PyObject *trunc_name = NULL; - PyObject *trunc_func; - const char *buffer; - Py_ssize_t buffer_len; - - if (trunc_name == NULL) { - trunc_name = PyUnicode_InternFromString("__trunc__"); - if (trunc_name == NULL) - return NULL; - } - - if (o == NULL) - return null_error(); - if (PyLong_CheckExact(o)) { - Py_INCREF(o); - return o; - } - m = o->ob_type->tp_as_number; - if (m && m->nb_int) { /* This should include subclasses of int */ - PyObject *res = m->nb_int(o); - if (res && !PyLong_Check(res)) { - PyErr_Format(PyExc_TypeError, - "__int__ returned non-int (type %.200s)", - res->ob_type->tp_name); - Py_DECREF(res); - return NULL; - } - return res; - } - if (PyLong_Check(o)) /* An int subclass without nb_int */ - return _PyLong_Copy((PyLongObject *)o); - trunc_func = PyObject_GetAttr(o, trunc_name); - if (trunc_func) { - PyObject *truncated = PyEval_CallObject(trunc_func, NULL); - PyObject *int_instance; - Py_DECREF(trunc_func); - /* __trunc__ is specified to return an Integral type, - but long() needs to return a long. */ - int_instance = _PyNumber_ConvertIntegralToInt( - truncated, - "__trunc__ returned non-Integral (type %.200s)"); - return int_instance; - } - PyErr_Clear(); /* It's not an error if o.__trunc__ doesn't exist. */ - - if (PyBytes_Check(o)) - /* need to do extra error checking that PyLong_FromString() - * doesn't do. In particular long('9.5') must raise an - * exception, not truncate the float. - */ - return long_from_string(PyBytes_AS_STRING(o), - PyBytes_GET_SIZE(o)); - if (PyUnicode_Check(o)) - /* The above check is done in PyLong_FromUnicode(). */ - return PyLong_FromUnicode(PyUnicode_AS_UNICODE(o), - PyUnicode_GET_SIZE(o), - 10); - if (!PyObject_AsCharBuffer(o, &buffer, &buffer_len)) - return long_from_string(buffer, buffer_len); + PyNumberMethods *m; + static PyObject *trunc_name = NULL; + PyObject *trunc_func; + const char *buffer; + Py_ssize_t buffer_len; + + if (trunc_name == NULL) { + trunc_name = PyUnicode_InternFromString("__trunc__"); + if (trunc_name == NULL) + return NULL; + } + + if (o == NULL) + return null_error(); + if (PyLong_CheckExact(o)) { + Py_INCREF(o); + return o; + } + m = o->ob_type->tp_as_number; + if (m && m->nb_int) { /* This should include subclasses of int */ + PyObject *res = m->nb_int(o); + if (res && !PyLong_Check(res)) { + PyErr_Format(PyExc_TypeError, + "__int__ returned non-int (type %.200s)", + res->ob_type->tp_name); + Py_DECREF(res); + return NULL; + } + return res; + } + if (PyLong_Check(o)) /* An int subclass without nb_int */ + return _PyLong_Copy((PyLongObject *)o); + trunc_func = PyObject_GetAttr(o, trunc_name); + if (trunc_func) { + PyObject *truncated = PyEval_CallObject(trunc_func, NULL); + PyObject *int_instance; + Py_DECREF(trunc_func); + /* __trunc__ is specified to return an Integral type, + but long() needs to return a long. */ + int_instance = _PyNumber_ConvertIntegralToInt( + truncated, + "__trunc__ returned non-Integral (type %.200s)"); + return int_instance; + } + PyErr_Clear(); /* It's not an error if o.__trunc__ doesn't exist. */ - return type_error("int() argument must be a string or a " - "number, not '%.200s'", o); + if (PyBytes_Check(o)) + /* need to do extra error checking that PyLong_FromString() + * doesn't do. In particular long('9.5') must raise an + * exception, not truncate the float. + */ + return long_from_string(PyBytes_AS_STRING(o), + PyBytes_GET_SIZE(o)); + if (PyUnicode_Check(o)) + /* The above check is done in PyLong_FromUnicode(). */ + return PyLong_FromUnicode(PyUnicode_AS_UNICODE(o), + PyUnicode_GET_SIZE(o), + 10); + if (!PyObject_AsCharBuffer(o, &buffer, &buffer_len)) + return long_from_string(buffer, buffer_len); + + return type_error("int() argument must be a string or a " + "number, not '%.200s'", o); } PyObject * PyNumber_Float(PyObject *o) { - PyNumberMethods *m; + PyNumberMethods *m; - if (o == NULL) - return null_error(); - m = o->ob_type->tp_as_number; - if (m && m->nb_float) { /* This should include subclasses of float */ - PyObject *res = m->nb_float(o); - if (res && !PyFloat_Check(res)) { - PyErr_Format(PyExc_TypeError, - "__float__ returned non-float (type %.200s)", - res->ob_type->tp_name); - Py_DECREF(res); - return NULL; - } - return res; - } - if (PyFloat_Check(o)) { /* A float subclass with nb_float == NULL */ - PyFloatObject *po = (PyFloatObject *)o; - return PyFloat_FromDouble(po->ob_fval); - } - return PyFloat_FromString(o); + if (o == NULL) + return null_error(); + m = o->ob_type->tp_as_number; + if (m && m->nb_float) { /* This should include subclasses of float */ + PyObject *res = m->nb_float(o); + if (res && !PyFloat_Check(res)) { + PyErr_Format(PyExc_TypeError, + "__float__ returned non-float (type %.200s)", + res->ob_type->tp_name); + Py_DECREF(res); + return NULL; + } + return res; + } + if (PyFloat_Check(o)) { /* A float subclass with nb_float == NULL */ + PyFloatObject *po = (PyFloatObject *)o; + return PyFloat_FromDouble(po->ob_fval); + } + return PyFloat_FromString(o); } PyObject * PyNumber_ToBase(PyObject *n, int base) { - PyObject *res = NULL; - PyObject *index = PyNumber_Index(n); + PyObject *res = NULL; + PyObject *index = PyNumber_Index(n); - if (!index) - return NULL; - if (PyLong_Check(index)) - res = _PyLong_Format(index, base); - else - /* It should not be possible to get here, as - PyNumber_Index already has a check for the same - condition */ - PyErr_SetString(PyExc_ValueError, "PyNumber_ToBase: index not " - "int or long"); - Py_DECREF(index); - return res; + if (!index) + return NULL; + if (PyLong_Check(index)) + res = _PyLong_Format(index, base); + else + /* It should not be possible to get here, as + PyNumber_Index already has a check for the same + condition */ + PyErr_SetString(PyExc_ValueError, "PyNumber_ToBase: index not " + "int or long"); + Py_DECREF(index); + return res; } @@ -1453,507 +1453,507 @@ int PySequence_Check(PyObject *s) { - if (PyObject_IsInstance(s, (PyObject *)&PyDict_Type)) - return 0; - return s != NULL && s->ob_type->tp_as_sequence && - s->ob_type->tp_as_sequence->sq_item != NULL; + if (PyObject_IsInstance(s, (PyObject *)&PyDict_Type)) + return 0; + return s != NULL && s->ob_type->tp_as_sequence && + s->ob_type->tp_as_sequence->sq_item != NULL; } Py_ssize_t PySequence_Size(PyObject *s) { - PySequenceMethods *m; + PySequenceMethods *m; - if (s == NULL) { - null_error(); - return -1; - } - - m = s->ob_type->tp_as_sequence; - if (m && m->sq_length) - return m->sq_length(s); + if (s == NULL) { + null_error(); + return -1; + } - type_error("object of type '%.200s' has no len()", s); - return -1; + m = s->ob_type->tp_as_sequence; + if (m && m->sq_length) + return m->sq_length(s); + + type_error("object of type '%.200s' has no len()", s); + return -1; } #undef PySequence_Length Py_ssize_t PySequence_Length(PyObject *s) { - return PySequence_Size(s); + return PySequence_Size(s); } #define PySequence_Length PySequence_Size PyObject * PySequence_Concat(PyObject *s, PyObject *o) { - PySequenceMethods *m; + PySequenceMethods *m; - if (s == NULL || o == NULL) - return null_error(); + if (s == NULL || o == NULL) + return null_error(); - m = s->ob_type->tp_as_sequence; - if (m && m->sq_concat) - return m->sq_concat(s, o); - - /* Instances of user classes defining an __add__() method only - have an nb_add slot, not an sq_concat slot. So we fall back - to nb_add if both arguments appear to be sequences. */ - if (PySequence_Check(s) && PySequence_Check(o)) { - PyObject *result = binary_op1(s, o, NB_SLOT(nb_add)); - if (result != Py_NotImplemented) - return result; - Py_DECREF(result); - } - return type_error("'%.200s' object can't be concatenated", s); + m = s->ob_type->tp_as_sequence; + if (m && m->sq_concat) + return m->sq_concat(s, o); + + /* Instances of user classes defining an __add__() method only + have an nb_add slot, not an sq_concat slot. So we fall back + to nb_add if both arguments appear to be sequences. */ + if (PySequence_Check(s) && PySequence_Check(o)) { + PyObject *result = binary_op1(s, o, NB_SLOT(nb_add)); + if (result != Py_NotImplemented) + return result; + Py_DECREF(result); + } + return type_error("'%.200s' object can't be concatenated", s); } PyObject * PySequence_Repeat(PyObject *o, Py_ssize_t count) { - PySequenceMethods *m; + PySequenceMethods *m; - if (o == NULL) - return null_error(); + if (o == NULL) + return null_error(); - m = o->ob_type->tp_as_sequence; - if (m && m->sq_repeat) - return m->sq_repeat(o, count); - - /* Instances of user classes defining a __mul__() method only - have an nb_multiply slot, not an sq_repeat slot. so we fall back - to nb_multiply if o appears to be a sequence. */ - if (PySequence_Check(o)) { - PyObject *n, *result; - n = PyLong_FromSsize_t(count); - if (n == NULL) - return NULL; - result = binary_op1(o, n, NB_SLOT(nb_multiply)); - Py_DECREF(n); - if (result != Py_NotImplemented) - return result; - Py_DECREF(result); - } - return type_error("'%.200s' object can't be repeated", o); + m = o->ob_type->tp_as_sequence; + if (m && m->sq_repeat) + return m->sq_repeat(o, count); + + /* Instances of user classes defining a __mul__() method only + have an nb_multiply slot, not an sq_repeat slot. so we fall back + to nb_multiply if o appears to be a sequence. */ + if (PySequence_Check(o)) { + PyObject *n, *result; + n = PyLong_FromSsize_t(count); + if (n == NULL) + return NULL; + result = binary_op1(o, n, NB_SLOT(nb_multiply)); + Py_DECREF(n); + if (result != Py_NotImplemented) + return result; + Py_DECREF(result); + } + return type_error("'%.200s' object can't be repeated", o); } PyObject * PySequence_InPlaceConcat(PyObject *s, PyObject *o) { - PySequenceMethods *m; + PySequenceMethods *m; - if (s == NULL || o == NULL) - return null_error(); + if (s == NULL || o == NULL) + return null_error(); - m = s->ob_type->tp_as_sequence; - if (m && m->sq_inplace_concat) - return m->sq_inplace_concat(s, o); - if (m && m->sq_concat) - return m->sq_concat(s, o); - - if (PySequence_Check(s) && PySequence_Check(o)) { - PyObject *result = binary_iop1(s, o, NB_SLOT(nb_inplace_add), - NB_SLOT(nb_add)); - if (result != Py_NotImplemented) - return result; - Py_DECREF(result); - } - return type_error("'%.200s' object can't be concatenated", s); + m = s->ob_type->tp_as_sequence; + if (m && m->sq_inplace_concat) + return m->sq_inplace_concat(s, o); + if (m && m->sq_concat) + return m->sq_concat(s, o); + + if (PySequence_Check(s) && PySequence_Check(o)) { + PyObject *result = binary_iop1(s, o, NB_SLOT(nb_inplace_add), + NB_SLOT(nb_add)); + if (result != Py_NotImplemented) + return result; + Py_DECREF(result); + } + return type_error("'%.200s' object can't be concatenated", s); } PyObject * PySequence_InPlaceRepeat(PyObject *o, Py_ssize_t count) { - PySequenceMethods *m; + PySequenceMethods *m; - if (o == NULL) - return null_error(); + if (o == NULL) + return null_error(); - m = o->ob_type->tp_as_sequence; - if (m && m->sq_inplace_repeat) - return m->sq_inplace_repeat(o, count); - if (m && m->sq_repeat) - return m->sq_repeat(o, count); - - if (PySequence_Check(o)) { - PyObject *n, *result; - n = PyLong_FromSsize_t(count); - if (n == NULL) - return NULL; - result = binary_iop1(o, n, NB_SLOT(nb_inplace_multiply), - NB_SLOT(nb_multiply)); - Py_DECREF(n); - if (result != Py_NotImplemented) - return result; - Py_DECREF(result); - } - return type_error("'%.200s' object can't be repeated", o); + m = o->ob_type->tp_as_sequence; + if (m && m->sq_inplace_repeat) + return m->sq_inplace_repeat(o, count); + if (m && m->sq_repeat) + return m->sq_repeat(o, count); + + if (PySequence_Check(o)) { + PyObject *n, *result; + n = PyLong_FromSsize_t(count); + if (n == NULL) + return NULL; + result = binary_iop1(o, n, NB_SLOT(nb_inplace_multiply), + NB_SLOT(nb_multiply)); + Py_DECREF(n); + if (result != Py_NotImplemented) + return result; + Py_DECREF(result); + } + return type_error("'%.200s' object can't be repeated", o); } PyObject * PySequence_GetItem(PyObject *s, Py_ssize_t i) { - PySequenceMethods *m; + PySequenceMethods *m; - if (s == NULL) - return null_error(); + if (s == NULL) + return null_error(); - m = s->ob_type->tp_as_sequence; - if (m && m->sq_item) { - if (i < 0) { - if (m->sq_length) { - Py_ssize_t l = (*m->sq_length)(s); - if (l < 0) - return NULL; - i += l; - } - } - return m->sq_item(s, i); - } + m = s->ob_type->tp_as_sequence; + if (m && m->sq_item) { + if (i < 0) { + if (m->sq_length) { + Py_ssize_t l = (*m->sq_length)(s); + if (l < 0) + return NULL; + i += l; + } + } + return m->sq_item(s, i); + } - return type_error("'%.200s' object does not support indexing", s); + return type_error("'%.200s' object does not support indexing", s); } PyObject * PySequence_GetSlice(PyObject *s, Py_ssize_t i1, Py_ssize_t i2) { - PyMappingMethods *mp; + PyMappingMethods *mp; - if (!s) return null_error(); + if (!s) return null_error(); - mp = s->ob_type->tp_as_mapping; - if (mp->mp_subscript) { - PyObject *res; - PyObject *slice = _PySlice_FromIndices(i1, i2); - if (!slice) - return NULL; - res = mp->mp_subscript(s, slice); - Py_DECREF(slice); - return res; - } + mp = s->ob_type->tp_as_mapping; + if (mp->mp_subscript) { + PyObject *res; + PyObject *slice = _PySlice_FromIndices(i1, i2); + if (!slice) + return NULL; + res = mp->mp_subscript(s, slice); + Py_DECREF(slice); + return res; + } - return type_error("'%.200s' object is unsliceable", s); + return type_error("'%.200s' object is unsliceable", s); } int PySequence_SetItem(PyObject *s, Py_ssize_t i, PyObject *o) { - PySequenceMethods *m; + PySequenceMethods *m; + + if (s == NULL) { + null_error(); + return -1; + } - if (s == NULL) { - null_error(); - return -1; - } - - m = s->ob_type->tp_as_sequence; - if (m && m->sq_ass_item) { - if (i < 0) { - if (m->sq_length) { - Py_ssize_t l = (*m->sq_length)(s); - if (l < 0) - return -1; - i += l; - } - } - return m->sq_ass_item(s, i, o); - } + m = s->ob_type->tp_as_sequence; + if (m && m->sq_ass_item) { + if (i < 0) { + if (m->sq_length) { + Py_ssize_t l = (*m->sq_length)(s); + if (l < 0) + return -1; + i += l; + } + } + return m->sq_ass_item(s, i, o); + } - type_error("'%.200s' object does not support item assignment", s); - return -1; + type_error("'%.200s' object does not support item assignment", s); + return -1; } int PySequence_DelItem(PyObject *s, Py_ssize_t i) { - PySequenceMethods *m; + PySequenceMethods *m; - if (s == NULL) { - null_error(); - return -1; - } - - m = s->ob_type->tp_as_sequence; - if (m && m->sq_ass_item) { - if (i < 0) { - if (m->sq_length) { - Py_ssize_t l = (*m->sq_length)(s); - if (l < 0) - return -1; - i += l; - } - } - return m->sq_ass_item(s, i, (PyObject *)NULL); - } + if (s == NULL) { + null_error(); + return -1; + } + + m = s->ob_type->tp_as_sequence; + if (m && m->sq_ass_item) { + if (i < 0) { + if (m->sq_length) { + Py_ssize_t l = (*m->sq_length)(s); + if (l < 0) + return -1; + i += l; + } + } + return m->sq_ass_item(s, i, (PyObject *)NULL); + } - type_error("'%.200s' object doesn't support item deletion", s); - return -1; + type_error("'%.200s' object doesn't support item deletion", s); + return -1; } int PySequence_SetSlice(PyObject *s, Py_ssize_t i1, Py_ssize_t i2, PyObject *o) { - PyMappingMethods *mp; + PyMappingMethods *mp; - if (s == NULL) { - null_error(); - return -1; - } - - mp = s->ob_type->tp_as_mapping; - if (mp->mp_ass_subscript) { - int res; - PyObject *slice = _PySlice_FromIndices(i1, i2); - if (!slice) - return -1; - res = mp->mp_ass_subscript(s, slice, o); - Py_DECREF(slice); - return res; - } + if (s == NULL) { + null_error(); + return -1; + } + + mp = s->ob_type->tp_as_mapping; + if (mp->mp_ass_subscript) { + int res; + PyObject *slice = _PySlice_FromIndices(i1, i2); + if (!slice) + return -1; + res = mp->mp_ass_subscript(s, slice, o); + Py_DECREF(slice); + return res; + } - type_error("'%.200s' object doesn't support slice assignment", s); - return -1; + type_error("'%.200s' object doesn't support slice assignment", s); + return -1; } int PySequence_DelSlice(PyObject *s, Py_ssize_t i1, Py_ssize_t i2) { - PyMappingMethods *mp; + PyMappingMethods *mp; - if (s == NULL) { - null_error(); - return -1; - } - - mp = s->ob_type->tp_as_mapping; - if (mp->mp_ass_subscript) { - int res; - PyObject *slice = _PySlice_FromIndices(i1, i2); - if (!slice) - return -1; - res = mp->mp_ass_subscript(s, slice, NULL); - Py_DECREF(slice); - return res; - } - type_error("'%.200s' object doesn't support slice deletion", s); - return -1; + if (s == NULL) { + null_error(); + return -1; + } + + mp = s->ob_type->tp_as_mapping; + if (mp->mp_ass_subscript) { + int res; + PyObject *slice = _PySlice_FromIndices(i1, i2); + if (!slice) + return -1; + res = mp->mp_ass_subscript(s, slice, NULL); + Py_DECREF(slice); + return res; + } + type_error("'%.200s' object doesn't support slice deletion", s); + return -1; } PyObject * PySequence_Tuple(PyObject *v) { - PyObject *it; /* iter(v) */ - Py_ssize_t n; /* guess for result tuple size */ - PyObject *result = NULL; - Py_ssize_t j; - - if (v == NULL) - return null_error(); - - /* Special-case the common tuple and list cases, for efficiency. */ - if (PyTuple_CheckExact(v)) { - /* Note that we can't know whether it's safe to return - a tuple *subclass* instance as-is, hence the restriction - to exact tuples here. In contrast, lists always make - a copy, so there's no need for exactness below. */ - Py_INCREF(v); - return v; - } - if (PyList_Check(v)) - return PyList_AsTuple(v); - - /* Get iterator. */ - it = PyObject_GetIter(v); - if (it == NULL) - return NULL; - - /* Guess result size and allocate space. */ - n = _PyObject_LengthHint(v, 10); - if (n == -1) - goto Fail; - result = PyTuple_New(n); - if (result == NULL) - goto Fail; - - /* Fill the tuple. */ - for (j = 0; ; ++j) { - PyObject *item = PyIter_Next(it); - if (item == NULL) { - if (PyErr_Occurred()) - goto Fail; - break; - } - if (j >= n) { - Py_ssize_t oldn = n; - /* The over-allocation strategy can grow a bit faster - than for lists because unlike lists the - over-allocation isn't permanent -- we reclaim - the excess before the end of this routine. - So, grow by ten and then add 25%. - */ - n += 10; - n += n >> 2; - if (n < oldn) { - /* Check for overflow */ - PyErr_NoMemory(); - Py_DECREF(item); - goto Fail; - } - if (_PyTuple_Resize(&result, n) != 0) { - Py_DECREF(item); - goto Fail; - } - } - PyTuple_SET_ITEM(result, j, item); - } - - /* Cut tuple back if guess was too large. */ - if (j < n && - _PyTuple_Resize(&result, j) != 0) - goto Fail; + PyObject *it; /* iter(v) */ + Py_ssize_t n; /* guess for result tuple size */ + PyObject *result = NULL; + Py_ssize_t j; - Py_DECREF(it); - return result; + if (v == NULL) + return null_error(); + + /* Special-case the common tuple and list cases, for efficiency. */ + if (PyTuple_CheckExact(v)) { + /* Note that we can't know whether it's safe to return + a tuple *subclass* instance as-is, hence the restriction + to exact tuples here. In contrast, lists always make + a copy, so there's no need for exactness below. */ + Py_INCREF(v); + return v; + } + if (PyList_Check(v)) + return PyList_AsTuple(v); + + /* Get iterator. */ + it = PyObject_GetIter(v); + if (it == NULL) + return NULL; + + /* Guess result size and allocate space. */ + n = _PyObject_LengthHint(v, 10); + if (n == -1) + goto Fail; + result = PyTuple_New(n); + if (result == NULL) + goto Fail; + + /* Fill the tuple. */ + for (j = 0; ; ++j) { + PyObject *item = PyIter_Next(it); + if (item == NULL) { + if (PyErr_Occurred()) + goto Fail; + break; + } + if (j >= n) { + Py_ssize_t oldn = n; + /* The over-allocation strategy can grow a bit faster + than for lists because unlike lists the + over-allocation isn't permanent -- we reclaim + the excess before the end of this routine. + So, grow by ten and then add 25%. + */ + n += 10; + n += n >> 2; + if (n < oldn) { + /* Check for overflow */ + PyErr_NoMemory(); + Py_DECREF(item); + goto Fail; + } + if (_PyTuple_Resize(&result, n) != 0) { + Py_DECREF(item); + goto Fail; + } + } + PyTuple_SET_ITEM(result, j, item); + } + + /* Cut tuple back if guess was too large. */ + if (j < n && + _PyTuple_Resize(&result, j) != 0) + goto Fail; + + Py_DECREF(it); + return result; Fail: - Py_XDECREF(result); - Py_DECREF(it); - return NULL; + Py_XDECREF(result); + Py_DECREF(it); + return NULL; } PyObject * PySequence_List(PyObject *v) { - PyObject *result; /* result list */ - PyObject *rv; /* return value from PyList_Extend */ + PyObject *result; /* result list */ + PyObject *rv; /* return value from PyList_Extend */ - if (v == NULL) - return null_error(); + if (v == NULL) + return null_error(); - result = PyList_New(0); - if (result == NULL) - return NULL; - - rv = _PyList_Extend((PyListObject *)result, v); - if (rv == NULL) { - Py_DECREF(result); - return NULL; - } - Py_DECREF(rv); - return result; + result = PyList_New(0); + if (result == NULL) + return NULL; + + rv = _PyList_Extend((PyListObject *)result, v); + if (rv == NULL) { + Py_DECREF(result); + return NULL; + } + Py_DECREF(rv); + return result; } PyObject * PySequence_Fast(PyObject *v, const char *m) { - PyObject *it; + PyObject *it; - if (v == NULL) - return null_error(); + if (v == NULL) + return null_error(); - if (PyList_CheckExact(v) || PyTuple_CheckExact(v)) { - Py_INCREF(v); - return v; - } - - it = PyObject_GetIter(v); - if (it == NULL) { - if (PyErr_ExceptionMatches(PyExc_TypeError)) - PyErr_SetString(PyExc_TypeError, m); - return NULL; - } + if (PyList_CheckExact(v) || PyTuple_CheckExact(v)) { + Py_INCREF(v); + return v; + } + + it = PyObject_GetIter(v); + if (it == NULL) { + if (PyErr_ExceptionMatches(PyExc_TypeError)) + PyErr_SetString(PyExc_TypeError, m); + return NULL; + } - v = PySequence_List(it); - Py_DECREF(it); + v = PySequence_List(it); + Py_DECREF(it); - return v; + return v; } /* Iterate over seq. Result depends on the operation: - PY_ITERSEARCH_COUNT: -1 if error, else # of times obj appears in seq. - PY_ITERSEARCH_INDEX: 0-based index of first occurrence of obj in seq; - set ValueError and return -1 if none found; also return -1 on error. + PY_ITERSEARCH_COUNT: -1 if error, else # of times obj appears in seq. + PY_ITERSEARCH_INDEX: 0-based index of first occurrence of obj in seq; + set ValueError and return -1 if none found; also return -1 on error. Py_ITERSEARCH_CONTAINS: return 1 if obj in seq, else 0; -1 on error. */ Py_ssize_t _PySequence_IterSearch(PyObject *seq, PyObject *obj, int operation) { - Py_ssize_t n; - int wrapped; /* for PY_ITERSEARCH_INDEX, true iff n wrapped around */ - PyObject *it; /* iter(seq) */ - - if (seq == NULL || obj == NULL) { - null_error(); - return -1; - } - - it = PyObject_GetIter(seq); - if (it == NULL) { - type_error("argument of type '%.200s' is not iterable", seq); - return -1; - } - - n = wrapped = 0; - for (;;) { - int cmp; - PyObject *item = PyIter_Next(it); - if (item == NULL) { - if (PyErr_Occurred()) - goto Fail; - break; - } - - cmp = PyObject_RichCompareBool(obj, item, Py_EQ); - Py_DECREF(item); - if (cmp < 0) - goto Fail; - if (cmp > 0) { - switch (operation) { - case PY_ITERSEARCH_COUNT: - if (n == PY_SSIZE_T_MAX) { - PyErr_SetString(PyExc_OverflowError, - "count exceeds C integer size"); - goto Fail; - } - ++n; - break; - - case PY_ITERSEARCH_INDEX: - if (wrapped) { - PyErr_SetString(PyExc_OverflowError, - "index exceeds C integer size"); - goto Fail; - } - goto Done; - - case PY_ITERSEARCH_CONTAINS: - n = 1; - goto Done; - - default: - assert(!"unknown operation"); - } - } - - if (operation == PY_ITERSEARCH_INDEX) { - if (n == PY_SSIZE_T_MAX) - wrapped = 1; - ++n; - } - } - - if (operation != PY_ITERSEARCH_INDEX) - goto Done; - - PyErr_SetString(PyExc_ValueError, - "sequence.index(x): x not in sequence"); - /* fall into failure code */ + Py_ssize_t n; + int wrapped; /* for PY_ITERSEARCH_INDEX, true iff n wrapped around */ + PyObject *it; /* iter(seq) */ + + if (seq == NULL || obj == NULL) { + null_error(); + return -1; + } + + it = PyObject_GetIter(seq); + if (it == NULL) { + type_error("argument of type '%.200s' is not iterable", seq); + return -1; + } + + n = wrapped = 0; + for (;;) { + int cmp; + PyObject *item = PyIter_Next(it); + if (item == NULL) { + if (PyErr_Occurred()) + goto Fail; + break; + } + + cmp = PyObject_RichCompareBool(obj, item, Py_EQ); + Py_DECREF(item); + if (cmp < 0) + goto Fail; + if (cmp > 0) { + switch (operation) { + case PY_ITERSEARCH_COUNT: + if (n == PY_SSIZE_T_MAX) { + PyErr_SetString(PyExc_OverflowError, + "count exceeds C integer size"); + goto Fail; + } + ++n; + break; + + case PY_ITERSEARCH_INDEX: + if (wrapped) { + PyErr_SetString(PyExc_OverflowError, + "index exceeds C integer size"); + goto Fail; + } + goto Done; + + case PY_ITERSEARCH_CONTAINS: + n = 1; + goto Done; + + default: + assert(!"unknown operation"); + } + } + + if (operation == PY_ITERSEARCH_INDEX) { + if (n == PY_SSIZE_T_MAX) + wrapped = 1; + ++n; + } + } + + if (operation != PY_ITERSEARCH_INDEX) + goto Done; + + PyErr_SetString(PyExc_ValueError, + "sequence.index(x): x not in sequence"); + /* fall into failure code */ Fail: - n = -1; - /* fall through */ + n = -1; + /* fall through */ Done: - Py_DECREF(it); - return n; + Py_DECREF(it); + return n; } @@ -1961,7 +1961,7 @@ Py_ssize_t PySequence_Count(PyObject *s, PyObject *o) { - return _PySequence_IterSearch(s, o, PY_ITERSEARCH_COUNT); + return _PySequence_IterSearch(s, o, PY_ITERSEARCH_COUNT); } /* Return -1 if error; 1 if ob in seq; 0 if ob not in seq. @@ -1970,12 +1970,12 @@ int PySequence_Contains(PyObject *seq, PyObject *ob) { - Py_ssize_t result; - PySequenceMethods *sqm = seq->ob_type->tp_as_sequence; - if (sqm != NULL && sqm->sq_contains != NULL) - return (*sqm->sq_contains)(seq, ob); - result = _PySequence_IterSearch(seq, ob, PY_ITERSEARCH_CONTAINS); - return Py_SAFE_DOWNCAST(result, Py_ssize_t, int); + Py_ssize_t result; + PySequenceMethods *sqm = seq->ob_type->tp_as_sequence; + if (sqm != NULL && sqm->sq_contains != NULL) + return (*sqm->sq_contains)(seq, ob); + result = _PySequence_IterSearch(seq, ob, PY_ITERSEARCH_CONTAINS); + return Py_SAFE_DOWNCAST(result, Py_ssize_t, int); } /* Backwards compatibility */ @@ -1983,13 +1983,13 @@ int PySequence_In(PyObject *w, PyObject *v) { - return PySequence_Contains(w, v); + return PySequence_Contains(w, v); } Py_ssize_t PySequence_Index(PyObject *s, PyObject *o) { - return _PySequence_IterSearch(s, o, PY_ITERSEARCH_INDEX); + return _PySequence_IterSearch(s, o, PY_ITERSEARCH_INDEX); } /* Operations on mappings */ @@ -1997,145 +1997,145 @@ int PyMapping_Check(PyObject *o) { - return o && o->ob_type->tp_as_mapping && - o->ob_type->tp_as_mapping->mp_subscript; + return o && o->ob_type->tp_as_mapping && + o->ob_type->tp_as_mapping->mp_subscript; } Py_ssize_t PyMapping_Size(PyObject *o) { - PyMappingMethods *m; + PyMappingMethods *m; - if (o == NULL) { - null_error(); - return -1; - } - - m = o->ob_type->tp_as_mapping; - if (m && m->mp_length) - return m->mp_length(o); + if (o == NULL) { + null_error(); + return -1; + } + + m = o->ob_type->tp_as_mapping; + if (m && m->mp_length) + return m->mp_length(o); - type_error("object of type '%.200s' has no len()", o); - return -1; + type_error("object of type '%.200s' has no len()", o); + return -1; } #undef PyMapping_Length Py_ssize_t PyMapping_Length(PyObject *o) { - return PyMapping_Size(o); + return PyMapping_Size(o); } #define PyMapping_Length PyMapping_Size PyObject * PyMapping_GetItemString(PyObject *o, char *key) { - PyObject *okey, *r; + PyObject *okey, *r; - if (key == NULL) - return null_error(); + if (key == NULL) + return null_error(); - okey = PyUnicode_FromString(key); - if (okey == NULL) - return NULL; - r = PyObject_GetItem(o, okey); - Py_DECREF(okey); - return r; + okey = PyUnicode_FromString(key); + if (okey == NULL) + return NULL; + r = PyObject_GetItem(o, okey); + Py_DECREF(okey); + return r; } int PyMapping_SetItemString(PyObject *o, char *key, PyObject *value) { - PyObject *okey; - int r; + PyObject *okey; + int r; + + if (key == NULL) { + null_error(); + return -1; + } - if (key == NULL) { - null_error(); - return -1; - } - - okey = PyUnicode_FromString(key); - if (okey == NULL) - return -1; - r = PyObject_SetItem(o, okey, value); - Py_DECREF(okey); - return r; + okey = PyUnicode_FromString(key); + if (okey == NULL) + return -1; + r = PyObject_SetItem(o, okey, value); + Py_DECREF(okey); + return r; } int PyMapping_HasKeyString(PyObject *o, char *key) { - PyObject *v; + PyObject *v; - v = PyMapping_GetItemString(o, key); - if (v) { - Py_DECREF(v); - return 1; - } - PyErr_Clear(); - return 0; + v = PyMapping_GetItemString(o, key); + if (v) { + Py_DECREF(v); + return 1; + } + PyErr_Clear(); + return 0; } int PyMapping_HasKey(PyObject *o, PyObject *key) { - PyObject *v; + PyObject *v; - v = PyObject_GetItem(o, key); - if (v) { - Py_DECREF(v); - return 1; - } - PyErr_Clear(); - return 0; + v = PyObject_GetItem(o, key); + if (v) { + Py_DECREF(v); + return 1; + } + PyErr_Clear(); + return 0; } PyObject * PyMapping_Keys(PyObject *o) { - PyObject *keys; - PyObject *fast; + PyObject *keys; + PyObject *fast; - if (PyDict_CheckExact(o)) - return PyDict_Keys(o); - keys = PyObject_CallMethod(o, "keys", NULL); - if (keys == NULL) - return NULL; - fast = PySequence_Fast(keys, "o.keys() are not iterable"); - Py_DECREF(keys); - return fast; + if (PyDict_CheckExact(o)) + return PyDict_Keys(o); + keys = PyObject_CallMethod(o, "keys", NULL); + if (keys == NULL) + return NULL; + fast = PySequence_Fast(keys, "o.keys() are not iterable"); + Py_DECREF(keys); + return fast; } PyObject * PyMapping_Items(PyObject *o) { - PyObject *items; - PyObject *fast; + PyObject *items; + PyObject *fast; - if (PyDict_CheckExact(o)) - return PyDict_Items(o); - items = PyObject_CallMethod(o, "items", NULL); - if (items == NULL) - return NULL; - fast = PySequence_Fast(items, "o.items() are not iterable"); - Py_DECREF(items); - return fast; + if (PyDict_CheckExact(o)) + return PyDict_Items(o); + items = PyObject_CallMethod(o, "items", NULL); + if (items == NULL) + return NULL; + fast = PySequence_Fast(items, "o.items() are not iterable"); + Py_DECREF(items); + return fast; } PyObject * PyMapping_Values(PyObject *o) { - PyObject *values; - PyObject *fast; + PyObject *values; + PyObject *fast; - if (PyDict_CheckExact(o)) - return PyDict_Values(o); - values = PyObject_CallMethod(o, "values", NULL); - if (values == NULL) - return NULL; - fast = PySequence_Fast(values, "o.values() are not iterable"); - Py_DECREF(values); - return fast; + if (PyDict_CheckExact(o)) + return PyDict_Values(o); + values = PyObject_CallMethod(o, "values", NULL); + if (values == NULL) + return NULL; + fast = PySequence_Fast(values, "o.values() are not iterable"); + Py_DECREF(values); + return fast; } /* Operations on callable objects */ @@ -2145,253 +2145,253 @@ PyObject * PyObject_CallObject(PyObject *o, PyObject *a) { - return PyEval_CallObjectWithKeywords(o, a, NULL); + return PyEval_CallObjectWithKeywords(o, a, NULL); } PyObject * PyObject_Call(PyObject *func, PyObject *arg, PyObject *kw) { - ternaryfunc call; + ternaryfunc call; - if ((call = func->ob_type->tp_call) != NULL) { - PyObject *result; - if (Py_EnterRecursiveCall(" while calling a Python object")) - return NULL; - result = (*call)(func, arg, kw); - Py_LeaveRecursiveCall(); - if (result == NULL && !PyErr_Occurred()) - PyErr_SetString( - PyExc_SystemError, - "NULL result without error in PyObject_Call"); - return result; - } - PyErr_Format(PyExc_TypeError, "'%.200s' object is not callable", - func->ob_type->tp_name); - return NULL; + if ((call = func->ob_type->tp_call) != NULL) { + PyObject *result; + if (Py_EnterRecursiveCall(" while calling a Python object")) + return NULL; + result = (*call)(func, arg, kw); + Py_LeaveRecursiveCall(); + if (result == NULL && !PyErr_Occurred()) + PyErr_SetString( + PyExc_SystemError, + "NULL result without error in PyObject_Call"); + return result; + } + PyErr_Format(PyExc_TypeError, "'%.200s' object is not callable", + func->ob_type->tp_name); + return NULL; } static PyObject* call_function_tail(PyObject *callable, PyObject *args) { - PyObject *retval; + PyObject *retval; - if (args == NULL) - return NULL; + if (args == NULL) + return NULL; - if (!PyTuple_Check(args)) { - PyObject *a; + if (!PyTuple_Check(args)) { + PyObject *a; - a = PyTuple_New(1); - if (a == NULL) { - Py_DECREF(args); - return NULL; - } - PyTuple_SET_ITEM(a, 0, args); - args = a; - } - retval = PyObject_Call(callable, args, NULL); + a = PyTuple_New(1); + if (a == NULL) { + Py_DECREF(args); + return NULL; + } + PyTuple_SET_ITEM(a, 0, args); + args = a; + } + retval = PyObject_Call(callable, args, NULL); - Py_DECREF(args); + Py_DECREF(args); - return retval; + return retval; } PyObject * PyObject_CallFunction(PyObject *callable, char *format, ...) { - va_list va; - PyObject *args; + va_list va; + PyObject *args; - if (callable == NULL) - return null_error(); + if (callable == NULL) + return null_error(); - if (format && *format) { - va_start(va, format); - args = Py_VaBuildValue(format, va); - va_end(va); - } - else - args = PyTuple_New(0); + if (format && *format) { + va_start(va, format); + args = Py_VaBuildValue(format, va); + va_end(va); + } + else + args = PyTuple_New(0); - return call_function_tail(callable, args); + return call_function_tail(callable, args); } PyObject * _PyObject_CallFunction_SizeT(PyObject *callable, char *format, ...) { - va_list va; - PyObject *args; + va_list va; + PyObject *args; - if (callable == NULL) - return null_error(); + if (callable == NULL) + return null_error(); - if (format && *format) { - va_start(va, format); - args = _Py_VaBuildValue_SizeT(format, va); - va_end(va); - } - else - args = PyTuple_New(0); + if (format && *format) { + va_start(va, format); + args = _Py_VaBuildValue_SizeT(format, va); + va_end(va); + } + else + args = PyTuple_New(0); - return call_function_tail(callable, args); + return call_function_tail(callable, args); } PyObject * PyObject_CallMethod(PyObject *o, char *name, char *format, ...) { - va_list va; - PyObject *args; - PyObject *func = NULL; - PyObject *retval = NULL; - - if (o == NULL || name == NULL) - return null_error(); - - func = PyObject_GetAttrString(o, name); - if (func == NULL) { - PyErr_SetString(PyExc_AttributeError, name); - return 0; - } - - if (!PyCallable_Check(func)) { - type_error("attribute of type '%.200s' is not callable", func); - goto exit; - } - - if (format && *format) { - va_start(va, format); - args = Py_VaBuildValue(format, va); - va_end(va); - } - else - args = PyTuple_New(0); + va_list va; + PyObject *args; + PyObject *func = NULL; + PyObject *retval = NULL; + + if (o == NULL || name == NULL) + return null_error(); + + func = PyObject_GetAttrString(o, name); + if (func == NULL) { + PyErr_SetString(PyExc_AttributeError, name); + return 0; + } + + if (!PyCallable_Check(func)) { + type_error("attribute of type '%.200s' is not callable", func); + goto exit; + } + + if (format && *format) { + va_start(va, format); + args = Py_VaBuildValue(format, va); + va_end(va); + } + else + args = PyTuple_New(0); - retval = call_function_tail(func, args); + retval = call_function_tail(func, args); exit: - /* args gets consumed in call_function_tail */ - Py_XDECREF(func); + /* args gets consumed in call_function_tail */ + Py_XDECREF(func); - return retval; + return retval; } PyObject * _PyObject_CallMethod_SizeT(PyObject *o, char *name, char *format, ...) { - va_list va; - PyObject *args; - PyObject *func = NULL; - PyObject *retval = NULL; - - if (o == NULL || name == NULL) - return null_error(); - - func = PyObject_GetAttrString(o, name); - if (func == NULL) { - PyErr_SetString(PyExc_AttributeError, name); - return 0; - } - - if (!PyCallable_Check(func)) { - type_error("attribute of type '%.200s' is not callable", func); - goto exit; - } - - if (format && *format) { - va_start(va, format); - args = _Py_VaBuildValue_SizeT(format, va); - va_end(va); - } - else - args = PyTuple_New(0); + va_list va; + PyObject *args; + PyObject *func = NULL; + PyObject *retval = NULL; + + if (o == NULL || name == NULL) + return null_error(); + + func = PyObject_GetAttrString(o, name); + if (func == NULL) { + PyErr_SetString(PyExc_AttributeError, name); + return 0; + } - retval = call_function_tail(func, args); + if (!PyCallable_Check(func)) { + type_error("attribute of type '%.200s' is not callable", func); + goto exit; + } + + if (format && *format) { + va_start(va, format); + args = _Py_VaBuildValue_SizeT(format, va); + va_end(va); + } + else + args = PyTuple_New(0); + + retval = call_function_tail(func, args); exit: - /* args gets consumed in call_function_tail */ - Py_XDECREF(func); + /* args gets consumed in call_function_tail */ + Py_XDECREF(func); - return retval; + return retval; } static PyObject * objargs_mktuple(va_list va) { - int i, n = 0; - va_list countva; - PyObject *result, *tmp; + int i, n = 0; + va_list countva; + PyObject *result, *tmp; #ifdef VA_LIST_IS_ARRAY - memcpy(countva, va, sizeof(va_list)); + memcpy(countva, va, sizeof(va_list)); #else #ifdef __va_copy - __va_copy(countva, va); + __va_copy(countva, va); #else - countva = va; + countva = va; #endif #endif - while (((PyObject *)va_arg(countva, PyObject *)) != NULL) - ++n; - result = PyTuple_New(n); - if (result != NULL && n > 0) { - for (i = 0; i < n; ++i) { - tmp = (PyObject *)va_arg(va, PyObject *); - PyTuple_SET_ITEM(result, i, tmp); - Py_INCREF(tmp); - } - } - return result; + while (((PyObject *)va_arg(countva, PyObject *)) != NULL) + ++n; + result = PyTuple_New(n); + if (result != NULL && n > 0) { + for (i = 0; i < n; ++i) { + tmp = (PyObject *)va_arg(va, PyObject *); + PyTuple_SET_ITEM(result, i, tmp); + Py_INCREF(tmp); + } + } + return result; } PyObject * PyObject_CallMethodObjArgs(PyObject *callable, PyObject *name, ...) { - PyObject *args, *tmp; - va_list vargs; + PyObject *args, *tmp; + va_list vargs; - if (callable == NULL || name == NULL) - return null_error(); + if (callable == NULL || name == NULL) + return null_error(); - callable = PyObject_GetAttr(callable, name); - if (callable == NULL) - return NULL; - - /* count the args */ - va_start(vargs, name); - args = objargs_mktuple(vargs); - va_end(vargs); - if (args == NULL) { - Py_DECREF(callable); - return NULL; - } - tmp = PyObject_Call(callable, args, NULL); - Py_DECREF(args); - Py_DECREF(callable); + callable = PyObject_GetAttr(callable, name); + if (callable == NULL) + return NULL; + + /* count the args */ + va_start(vargs, name); + args = objargs_mktuple(vargs); + va_end(vargs); + if (args == NULL) { + Py_DECREF(callable); + return NULL; + } + tmp = PyObject_Call(callable, args, NULL); + Py_DECREF(args); + Py_DECREF(callable); - return tmp; + return tmp; } PyObject * PyObject_CallFunctionObjArgs(PyObject *callable, ...) { - PyObject *args, *tmp; - va_list vargs; + PyObject *args, *tmp; + va_list vargs; - if (callable == NULL) - return null_error(); + if (callable == NULL) + return null_error(); - /* count the args */ - va_start(vargs, callable); - args = objargs_mktuple(vargs); - va_end(vargs); - if (args == NULL) - return NULL; - tmp = PyObject_Call(callable, args, NULL); - Py_DECREF(args); + /* count the args */ + va_start(vargs, callable); + args = objargs_mktuple(vargs); + va_end(vargs); + if (args == NULL) + return NULL; + tmp = PyObject_Call(callable, args, NULL); + Py_DECREF(args); - return tmp; + return tmp; } @@ -2415,7 +2415,7 @@ * produce exactly the same results: NULL is returned and no error is set. * * If some exception other than AttributeError is raised, then NULL is also - * returned, but the exception is not cleared. That's because we want the + * returned, but the exception is not cleared. That's because we want the * exception to be propagated along. * * Callers are expected to test for PyErr_Occurred() when the return value @@ -2426,282 +2426,282 @@ static PyObject * abstract_get_bases(PyObject *cls) { - static PyObject *__bases__ = NULL; - PyObject *bases; + static PyObject *__bases__ = NULL; + PyObject *bases; - if (__bases__ == NULL) { - __bases__ = PyUnicode_InternFromString("__bases__"); - if (__bases__ == NULL) - return NULL; - } - Py_ALLOW_RECURSION - bases = PyObject_GetAttr(cls, __bases__); - Py_END_ALLOW_RECURSION - if (bases == NULL) { - if (PyErr_ExceptionMatches(PyExc_AttributeError)) - PyErr_Clear(); - return NULL; - } - if (!PyTuple_Check(bases)) { - Py_DECREF(bases); - return NULL; - } - return bases; + if (__bases__ == NULL) { + __bases__ = PyUnicode_InternFromString("__bases__"); + if (__bases__ == NULL) + return NULL; + } + Py_ALLOW_RECURSION + bases = PyObject_GetAttr(cls, __bases__); + Py_END_ALLOW_RECURSION + if (bases == NULL) { + if (PyErr_ExceptionMatches(PyExc_AttributeError)) + PyErr_Clear(); + return NULL; + } + if (!PyTuple_Check(bases)) { + Py_DECREF(bases); + return NULL; + } + return bases; } static int abstract_issubclass(PyObject *derived, PyObject *cls) { - PyObject *bases = NULL; - Py_ssize_t i, n; - int r = 0; - - while (1) { - if (derived == cls) - return 1; - bases = abstract_get_bases(derived); - if (bases == NULL) { - if (PyErr_Occurred()) - return -1; - return 0; - } - n = PyTuple_GET_SIZE(bases); - if (n == 0) { - Py_DECREF(bases); - return 0; - } - /* Avoid recursivity in the single inheritance case */ - if (n == 1) { - derived = PyTuple_GET_ITEM(bases, 0); - Py_DECREF(bases); - continue; - } - for (i = 0; i < n; i++) { - r = abstract_issubclass(PyTuple_GET_ITEM(bases, i), cls); - if (r != 0) - break; - } - Py_DECREF(bases); - return r; - } + PyObject *bases = NULL; + Py_ssize_t i, n; + int r = 0; + + while (1) { + if (derived == cls) + return 1; + bases = abstract_get_bases(derived); + if (bases == NULL) { + if (PyErr_Occurred()) + return -1; + return 0; + } + n = PyTuple_GET_SIZE(bases); + if (n == 0) { + Py_DECREF(bases); + return 0; + } + /* Avoid recursivity in the single inheritance case */ + if (n == 1) { + derived = PyTuple_GET_ITEM(bases, 0); + Py_DECREF(bases); + continue; + } + for (i = 0; i < n; i++) { + r = abstract_issubclass(PyTuple_GET_ITEM(bases, i), cls); + if (r != 0) + break; + } + Py_DECREF(bases); + return r; + } } static int check_class(PyObject *cls, const char *error) { - PyObject *bases = abstract_get_bases(cls); - if (bases == NULL) { - /* Do not mask errors. */ - if (!PyErr_Occurred()) - PyErr_SetString(PyExc_TypeError, error); - return 0; - } - Py_DECREF(bases); - return -1; + PyObject *bases = abstract_get_bases(cls); + if (bases == NULL) { + /* Do not mask errors. */ + if (!PyErr_Occurred()) + PyErr_SetString(PyExc_TypeError, error); + return 0; + } + Py_DECREF(bases); + return -1; } static int recursive_isinstance(PyObject *inst, PyObject *cls) { - PyObject *icls; - static PyObject *__class__ = NULL; - int retval = 0; - - if (__class__ == NULL) { - __class__ = PyUnicode_InternFromString("__class__"); - if (__class__ == NULL) - return -1; - } - - if (PyType_Check(cls)) { - retval = PyObject_TypeCheck(inst, (PyTypeObject *)cls); - if (retval == 0) { - PyObject *c = PyObject_GetAttr(inst, __class__); - if (c == NULL) { - PyErr_Clear(); - } - else { - if (c != (PyObject *)(inst->ob_type) && - PyType_Check(c)) - retval = PyType_IsSubtype( - (PyTypeObject *)c, - (PyTypeObject *)cls); - Py_DECREF(c); - } - } - } - else { - if (!check_class(cls, - "isinstance() arg 2 must be a class, type," - " or tuple of classes and types")) - return -1; - icls = PyObject_GetAttr(inst, __class__); - if (icls == NULL) { - PyErr_Clear(); - retval = 0; - } - else { - retval = abstract_issubclass(icls, cls); - Py_DECREF(icls); - } - } + PyObject *icls; + static PyObject *__class__ = NULL; + int retval = 0; + + if (__class__ == NULL) { + __class__ = PyUnicode_InternFromString("__class__"); + if (__class__ == NULL) + return -1; + } + + if (PyType_Check(cls)) { + retval = PyObject_TypeCheck(inst, (PyTypeObject *)cls); + if (retval == 0) { + PyObject *c = PyObject_GetAttr(inst, __class__); + if (c == NULL) { + PyErr_Clear(); + } + else { + if (c != (PyObject *)(inst->ob_type) && + PyType_Check(c)) + retval = PyType_IsSubtype( + (PyTypeObject *)c, + (PyTypeObject *)cls); + Py_DECREF(c); + } + } + } + else { + if (!check_class(cls, + "isinstance() arg 2 must be a class, type," + " or tuple of classes and types")) + return -1; + icls = PyObject_GetAttr(inst, __class__); + if (icls == NULL) { + PyErr_Clear(); + retval = 0; + } + else { + retval = abstract_issubclass(icls, cls); + Py_DECREF(icls); + } + } - return retval; + return retval; } int PyObject_IsInstance(PyObject *inst, PyObject *cls) { - static PyObject *name = NULL; - PyObject *checker; + static PyObject *name = NULL; + PyObject *checker; - /* Quick test for an exact match */ - if (Py_TYPE(inst) == (PyTypeObject *)cls) - return 1; - - if (PyTuple_Check(cls)) { - Py_ssize_t i; - Py_ssize_t n; - int r = 0; - - if (Py_EnterRecursiveCall(" in __instancecheck__")) - return -1; - n = PyTuple_GET_SIZE(cls); - for (i = 0; i < n; ++i) { - PyObject *item = PyTuple_GET_ITEM(cls, i); - r = PyObject_IsInstance(inst, item); - if (r != 0) - /* either found it, or got an error */ - break; - } - Py_LeaveRecursiveCall(); - return r; - } - - checker = _PyObject_LookupSpecial(cls, "__instancecheck__", &name); - if (checker != NULL) { - PyObject *res; - int ok = -1; - if (Py_EnterRecursiveCall(" in __instancecheck__")) { - Py_DECREF(checker); - return ok; - } - res = PyObject_CallFunctionObjArgs(checker, inst, NULL); - Py_LeaveRecursiveCall(); - Py_DECREF(checker); - if (res != NULL) { - ok = PyObject_IsTrue(res); - Py_DECREF(res); - } - return ok; - } - else if (PyErr_Occurred()) - return -1; - return recursive_isinstance(inst, cls); + /* Quick test for an exact match */ + if (Py_TYPE(inst) == (PyTypeObject *)cls) + return 1; + + if (PyTuple_Check(cls)) { + Py_ssize_t i; + Py_ssize_t n; + int r = 0; + + if (Py_EnterRecursiveCall(" in __instancecheck__")) + return -1; + n = PyTuple_GET_SIZE(cls); + for (i = 0; i < n; ++i) { + PyObject *item = PyTuple_GET_ITEM(cls, i); + r = PyObject_IsInstance(inst, item); + if (r != 0) + /* either found it, or got an error */ + break; + } + Py_LeaveRecursiveCall(); + return r; + } + + checker = _PyObject_LookupSpecial(cls, "__instancecheck__", &name); + if (checker != NULL) { + PyObject *res; + int ok = -1; + if (Py_EnterRecursiveCall(" in __instancecheck__")) { + Py_DECREF(checker); + return ok; + } + res = PyObject_CallFunctionObjArgs(checker, inst, NULL); + Py_LeaveRecursiveCall(); + Py_DECREF(checker); + if (res != NULL) { + ok = PyObject_IsTrue(res); + Py_DECREF(res); + } + return ok; + } + else if (PyErr_Occurred()) + return -1; + return recursive_isinstance(inst, cls); } -static int +static int recursive_issubclass(PyObject *derived, PyObject *cls) { - if (PyType_Check(cls) && PyType_Check(derived)) { - /* Fast path (non-recursive) */ - return PyType_IsSubtype((PyTypeObject *)derived, (PyTypeObject *)cls); - } - if (!check_class(derived, - "issubclass() arg 1 must be a class")) - return -1; - if (!check_class(cls, - "issubclass() arg 2 must be a class" - " or tuple of classes")) - return -1; + if (PyType_Check(cls) && PyType_Check(derived)) { + /* Fast path (non-recursive) */ + return PyType_IsSubtype((PyTypeObject *)derived, (PyTypeObject *)cls); + } + if (!check_class(derived, + "issubclass() arg 1 must be a class")) + return -1; + if (!check_class(cls, + "issubclass() arg 2 must be a class" + " or tuple of classes")) + return -1; - return abstract_issubclass(derived, cls); + return abstract_issubclass(derived, cls); } int PyObject_IsSubclass(PyObject *derived, PyObject *cls) { - static PyObject *name = NULL; - PyObject *checker; + static PyObject *name = NULL; + PyObject *checker; + + if (PyTuple_Check(cls)) { + Py_ssize_t i; + Py_ssize_t n; + int r = 0; + + if (Py_EnterRecursiveCall(" in __subclasscheck__")) + return -1; + n = PyTuple_GET_SIZE(cls); + for (i = 0; i < n; ++i) { + PyObject *item = PyTuple_GET_ITEM(cls, i); + r = PyObject_IsSubclass(derived, item); + if (r != 0) + /* either found it, or got an error */ + break; + } + Py_LeaveRecursiveCall(); + return r; + } - if (PyTuple_Check(cls)) { - Py_ssize_t i; - Py_ssize_t n; - int r = 0; - - if (Py_EnterRecursiveCall(" in __subclasscheck__")) - return -1; - n = PyTuple_GET_SIZE(cls); - for (i = 0; i < n; ++i) { - PyObject *item = PyTuple_GET_ITEM(cls, i); - r = PyObject_IsSubclass(derived, item); - if (r != 0) - /* either found it, or got an error */ - break; - } - Py_LeaveRecursiveCall(); - return r; - } - - checker = _PyObject_LookupSpecial(cls, "__subclasscheck__", &name); - if (checker != NULL) { - PyObject *res; - int ok = -1; - if (Py_EnterRecursiveCall(" in __subclasscheck__")) { - Py_DECREF(checker); - return ok; - } - res = PyObject_CallFunctionObjArgs(checker, derived, NULL); - Py_LeaveRecursiveCall(); - Py_DECREF(checker); - if (res != NULL) { - ok = PyObject_IsTrue(res); - Py_DECREF(res); - } - return ok; - } - else if (PyErr_Occurred()) - return -1; - return recursive_issubclass(derived, cls); + checker = _PyObject_LookupSpecial(cls, "__subclasscheck__", &name); + if (checker != NULL) { + PyObject *res; + int ok = -1; + if (Py_EnterRecursiveCall(" in __subclasscheck__")) { + Py_DECREF(checker); + return ok; + } + res = PyObject_CallFunctionObjArgs(checker, derived, NULL); + Py_LeaveRecursiveCall(); + Py_DECREF(checker); + if (res != NULL) { + ok = PyObject_IsTrue(res); + Py_DECREF(res); + } + return ok; + } + else if (PyErr_Occurred()) + return -1; + return recursive_issubclass(derived, cls); } int _PyObject_RealIsInstance(PyObject *inst, PyObject *cls) { - return recursive_isinstance(inst, cls); + return recursive_isinstance(inst, cls); } int _PyObject_RealIsSubclass(PyObject *derived, PyObject *cls) { - return recursive_issubclass(derived, cls); + return recursive_issubclass(derived, cls); } PyObject * PyObject_GetIter(PyObject *o) { - PyTypeObject *t = o->ob_type; - getiterfunc f = NULL; - f = t->tp_iter; - if (f == NULL) { - if (PySequence_Check(o)) - return PySeqIter_New(o); - return type_error("'%.200s' object is not iterable", o); - } - else { - PyObject *res = (*f)(o); - if (res != NULL && !PyIter_Check(res)) { - PyErr_Format(PyExc_TypeError, - "iter() returned non-iterator " - "of type '%.100s'", - res->ob_type->tp_name); - Py_DECREF(res); - res = NULL; - } - return res; - } + PyTypeObject *t = o->ob_type; + getiterfunc f = NULL; + f = t->tp_iter; + if (f == NULL) { + if (PySequence_Check(o)) + return PySeqIter_New(o); + return type_error("'%.200s' object is not iterable", o); + } + else { + PyObject *res = (*f)(o); + if (res != NULL && !PyIter_Check(res)) { + PyErr_Format(PyExc_TypeError, + "iter() returned non-iterator " + "of type '%.100s'", + res->ob_type->tp_name); + Py_DECREF(res); + res = NULL; + } + return res; + } } /* Return next item. @@ -2709,16 +2709,16 @@ * If the iteration terminates normally, return NULL and clear the * PyExc_StopIteration exception (if it was set). PyErr_Occurred() * will be false. - * Else return the next object. PyErr_Occurred() will be false. + * Else return the next object. PyErr_Occurred() will be false. */ PyObject * PyIter_Next(PyObject *iter) { - PyObject *result; - result = (*iter->ob_type->tp_iternext)(iter); - if (result == NULL && - PyErr_Occurred() && - PyErr_ExceptionMatches(PyExc_StopIteration)) - PyErr_Clear(); - return result; + PyObject *result; + result = (*iter->ob_type->tp_iternext)(iter); + if (result == NULL && + PyErr_Occurred() && + PyErr_ExceptionMatches(PyExc_StopIteration)) + PyErr_Clear(); + return result; } Modified: python/branches/release31-maint/Objects/boolobject.c ============================================================================== --- python/branches/release31-maint/Objects/boolobject.c (original) +++ python/branches/release31-maint/Objects/boolobject.c Sun May 9 18:14:21 2010 @@ -11,30 +11,30 @@ static PyObject * bool_repr(PyObject *self) { - PyObject *s; + PyObject *s; - if (self == Py_True) - s = true_str ? true_str : - (true_str = PyUnicode_InternFromString("True")); - else - s = false_str ? false_str : - (false_str = PyUnicode_InternFromString("False")); - Py_XINCREF(s); - return s; + if (self == Py_True) + s = true_str ? true_str : + (true_str = PyUnicode_InternFromString("True")); + else + s = false_str ? false_str : + (false_str = PyUnicode_InternFromString("False")); + Py_XINCREF(s); + return s; } /* Function to return a bool from a C long */ PyObject *PyBool_FromLong(long ok) { - PyObject *result; + PyObject *result; - if (ok) - result = Py_True; - else - result = Py_False; - Py_INCREF(result); - return result; + if (ok) + result = Py_True; + else + result = Py_False; + Py_INCREF(result); + return result; } /* We define bool_new to always return either Py_True or Py_False */ @@ -42,16 +42,16 @@ static PyObject * bool_new(PyTypeObject *type, PyObject *args, PyObject *kwds) { - static char *kwlist[] = {"x", 0}; - PyObject *x = Py_False; - long ok; - - if (!PyArg_ParseTupleAndKeywords(args, kwds, "|O:bool", kwlist, &x)) - return NULL; - ok = PyObject_IsTrue(x); - if (ok < 0) - return NULL; - return PyBool_FromLong(ok); + static char *kwlist[] = {"x", 0}; + PyObject *x = Py_False; + long ok; + + if (!PyArg_ParseTupleAndKeywords(args, kwds, "|O:bool", kwlist, &x)) + return NULL; + ok = PyObject_IsTrue(x); + if (ok < 0) + return NULL; + return PyBool_FromLong(ok); } /* Arithmetic operations redefined to return bool if both args are bool. */ @@ -59,25 +59,25 @@ static PyObject * bool_and(PyObject *a, PyObject *b) { - if (!PyBool_Check(a) || !PyBool_Check(b)) - return PyLong_Type.tp_as_number->nb_and(a, b); - return PyBool_FromLong((a == Py_True) & (b == Py_True)); + if (!PyBool_Check(a) || !PyBool_Check(b)) + return PyLong_Type.tp_as_number->nb_and(a, b); + return PyBool_FromLong((a == Py_True) & (b == Py_True)); } static PyObject * bool_or(PyObject *a, PyObject *b) { - if (!PyBool_Check(a) || !PyBool_Check(b)) - return PyLong_Type.tp_as_number->nb_or(a, b); - return PyBool_FromLong((a == Py_True) | (b == Py_True)); + if (!PyBool_Check(a) || !PyBool_Check(b)) + return PyLong_Type.tp_as_number->nb_or(a, b); + return PyBool_FromLong((a == Py_True) | (b == Py_True)); } static PyObject * bool_xor(PyObject *a, PyObject *b) { - if (!PyBool_Check(a) || !PyBool_Check(b)) - return PyLong_Type.tp_as_number->nb_xor(a, b); - return PyBool_FromLong((a == Py_True) ^ (b == Py_True)); + if (!PyBool_Check(a) || !PyBool_Check(b)) + return PyLong_Type.tp_as_number->nb_xor(a, b); + return PyBool_FromLong((a == Py_True) ^ (b == Py_True)); } /* Doc string */ @@ -92,93 +92,93 @@ /* Arithmetic methods -- only so we can override &, |, ^. */ static PyNumberMethods bool_as_number = { - 0, /* nb_add */ - 0, /* nb_subtract */ - 0, /* nb_multiply */ - 0, /* nb_remainder */ - 0, /* nb_divmod */ - 0, /* nb_power */ - 0, /* nb_negative */ - 0, /* nb_positive */ - 0, /* nb_absolute */ - 0, /* nb_bool */ - 0, /* nb_invert */ - 0, /* nb_lshift */ - 0, /* nb_rshift */ - bool_and, /* nb_and */ - bool_xor, /* nb_xor */ - bool_or, /* nb_or */ - 0, /* nb_int */ - 0, /* nb_reserved */ - 0, /* nb_float */ - 0, /* nb_inplace_add */ - 0, /* nb_inplace_subtract */ - 0, /* nb_inplace_multiply */ - 0, /* nb_inplace_remainder */ - 0, /* nb_inplace_power */ - 0, /* nb_inplace_lshift */ - 0, /* nb_inplace_rshift */ - 0, /* nb_inplace_and */ - 0, /* nb_inplace_xor */ - 0, /* nb_inplace_or */ - 0, /* nb_floor_divide */ - 0, /* nb_true_divide */ - 0, /* nb_inplace_floor_divide */ - 0, /* nb_inplace_true_divide */ - 0, /* nb_index */ + 0, /* nb_add */ + 0, /* nb_subtract */ + 0, /* nb_multiply */ + 0, /* nb_remainder */ + 0, /* nb_divmod */ + 0, /* nb_power */ + 0, /* nb_negative */ + 0, /* nb_positive */ + 0, /* nb_absolute */ + 0, /* nb_bool */ + 0, /* nb_invert */ + 0, /* nb_lshift */ + 0, /* nb_rshift */ + bool_and, /* nb_and */ + bool_xor, /* nb_xor */ + bool_or, /* nb_or */ + 0, /* nb_int */ + 0, /* nb_reserved */ + 0, /* nb_float */ + 0, /* nb_inplace_add */ + 0, /* nb_inplace_subtract */ + 0, /* nb_inplace_multiply */ + 0, /* nb_inplace_remainder */ + 0, /* nb_inplace_power */ + 0, /* nb_inplace_lshift */ + 0, /* nb_inplace_rshift */ + 0, /* nb_inplace_and */ + 0, /* nb_inplace_xor */ + 0, /* nb_inplace_or */ + 0, /* nb_floor_divide */ + 0, /* nb_true_divide */ + 0, /* nb_inplace_floor_divide */ + 0, /* nb_inplace_true_divide */ + 0, /* nb_index */ }; /* The type object for bool. Note that this cannot be subclassed! */ PyTypeObject PyBool_Type = { - PyVarObject_HEAD_INIT(&PyType_Type, 0) - "bool", - sizeof(struct _longobject), - 0, - 0, /* tp_dealloc */ - 0, /* tp_print */ - 0, /* tp_getattr */ - 0, /* tp_setattr */ - 0, /* tp_reserved */ - bool_repr, /* tp_repr */ - &bool_as_number, /* tp_as_number */ - 0, /* tp_as_sequence */ - 0, /* tp_as_mapping */ - 0, /* tp_hash */ - 0, /* tp_call */ - bool_repr, /* tp_str */ - 0, /* tp_getattro */ - 0, /* tp_setattro */ - 0, /* tp_as_buffer */ - Py_TPFLAGS_DEFAULT, /* tp_flags */ - bool_doc, /* tp_doc */ - 0, /* tp_traverse */ - 0, /* tp_clear */ - 0, /* tp_richcompare */ - 0, /* tp_weaklistoffset */ - 0, /* tp_iter */ - 0, /* tp_iternext */ - 0, /* tp_methods */ - 0, /* tp_members */ - 0, /* tp_getset */ - &PyLong_Type, /* tp_base */ - 0, /* tp_dict */ - 0, /* tp_descr_get */ - 0, /* tp_descr_set */ - 0, /* tp_dictoffset */ - 0, /* tp_init */ - 0, /* tp_alloc */ - bool_new, /* tp_new */ + PyVarObject_HEAD_INIT(&PyType_Type, 0) + "bool", + sizeof(struct _longobject), + 0, + 0, /* tp_dealloc */ + 0, /* tp_print */ + 0, /* tp_getattr */ + 0, /* tp_setattr */ + 0, /* tp_reserved */ + bool_repr, /* tp_repr */ + &bool_as_number, /* tp_as_number */ + 0, /* tp_as_sequence */ + 0, /* tp_as_mapping */ + 0, /* tp_hash */ + 0, /* tp_call */ + bool_repr, /* tp_str */ + 0, /* tp_getattro */ + 0, /* tp_setattro */ + 0, /* tp_as_buffer */ + Py_TPFLAGS_DEFAULT, /* tp_flags */ + bool_doc, /* tp_doc */ + 0, /* tp_traverse */ + 0, /* tp_clear */ + 0, /* tp_richcompare */ + 0, /* tp_weaklistoffset */ + 0, /* tp_iter */ + 0, /* tp_iternext */ + 0, /* tp_methods */ + 0, /* tp_members */ + 0, /* tp_getset */ + &PyLong_Type, /* tp_base */ + 0, /* tp_dict */ + 0, /* tp_descr_get */ + 0, /* tp_descr_set */ + 0, /* tp_dictoffset */ + 0, /* tp_init */ + 0, /* tp_alloc */ + bool_new, /* tp_new */ }; /* The objects representing bool values False and True */ struct _longobject _Py_FalseStruct = { - PyVarObject_HEAD_INIT(&PyBool_Type, 0) - { 0 } + PyVarObject_HEAD_INIT(&PyBool_Type, 0) + { 0 } }; struct _longobject _Py_TrueStruct = { - PyVarObject_HEAD_INIT(&PyBool_Type, 1) - { 1 } + PyVarObject_HEAD_INIT(&PyBool_Type, 1) + { 1 } }; Modified: python/branches/release31-maint/Objects/bytes_methods.c ============================================================================== --- python/branches/release31-maint/Objects/bytes_methods.c (original) +++ python/branches/release31-maint/Objects/bytes_methods.c Sun May 9 18:14:21 2010 @@ -24,7 +24,7 @@ e = p + len; for (; p < e; p++) { - if (!Py_ISSPACE(*p)) + if (!Py_ISSPACE(*p)) Py_RETURN_FALSE; } Py_RETURN_TRUE; @@ -46,16 +46,16 @@ /* Shortcut for single character strings */ if (len == 1 && Py_ISALPHA(*p)) - Py_RETURN_TRUE; + Py_RETURN_TRUE; /* Special case for empty strings */ if (len == 0) - Py_RETURN_FALSE; + Py_RETURN_FALSE; e = p + len; for (; p < e; p++) { - if (!Py_ISALPHA(*p)) - Py_RETURN_FALSE; + if (!Py_ISALPHA(*p)) + Py_RETURN_FALSE; } Py_RETURN_TRUE; } @@ -76,16 +76,16 @@ /* Shortcut for single character strings */ if (len == 1 && Py_ISALNUM(*p)) - Py_RETURN_TRUE; + Py_RETURN_TRUE; /* Special case for empty strings */ if (len == 0) - Py_RETURN_FALSE; + Py_RETURN_FALSE; e = p + len; for (; p < e; p++) { - if (!Py_ISALNUM(*p)) - Py_RETURN_FALSE; + if (!Py_ISALNUM(*p)) + Py_RETURN_FALSE; } Py_RETURN_TRUE; } @@ -106,16 +106,16 @@ /* Shortcut for single character strings */ if (len == 1 && Py_ISDIGIT(*p)) - Py_RETURN_TRUE; + Py_RETURN_TRUE; /* Special case for empty strings */ if (len == 0) - Py_RETURN_FALSE; + Py_RETURN_FALSE; e = p + len; for (; p < e; p++) { - if (!Py_ISDIGIT(*p)) - Py_RETURN_FALSE; + if (!Py_ISDIGIT(*p)) + Py_RETURN_FALSE; } Py_RETURN_TRUE; } @@ -137,19 +137,19 @@ /* Shortcut for single character strings */ if (len == 1) - return PyBool_FromLong(Py_ISLOWER(*p)); + return PyBool_FromLong(Py_ISLOWER(*p)); /* Special case for empty strings */ if (len == 0) - Py_RETURN_FALSE; + Py_RETURN_FALSE; e = p + len; cased = 0; for (; p < e; p++) { - if (Py_ISUPPER(*p)) - Py_RETURN_FALSE; - else if (!cased && Py_ISLOWER(*p)) - cased = 1; + if (Py_ISUPPER(*p)) + Py_RETURN_FALSE; + else if (!cased && Py_ISLOWER(*p)) + cased = 1; } return PyBool_FromLong(cased); } @@ -171,19 +171,19 @@ /* Shortcut for single character strings */ if (len == 1) - return PyBool_FromLong(Py_ISUPPER(*p)); + return PyBool_FromLong(Py_ISUPPER(*p)); /* Special case for empty strings */ if (len == 0) - Py_RETURN_FALSE; + Py_RETURN_FALSE; e = p + len; cased = 0; for (; p < e; p++) { - if (Py_ISLOWER(*p)) - Py_RETURN_FALSE; - else if (!cased && Py_ISUPPER(*p)) - cased = 1; + if (Py_ISLOWER(*p)) + Py_RETURN_FALSE; + else if (!cased && Py_ISUPPER(*p)) + cased = 1; } return PyBool_FromLong(cased); } @@ -207,32 +207,32 @@ /* Shortcut for single character strings */ if (len == 1) - return PyBool_FromLong(Py_ISUPPER(*p)); + return PyBool_FromLong(Py_ISUPPER(*p)); /* Special case for empty strings */ if (len == 0) - Py_RETURN_FALSE; + Py_RETURN_FALSE; e = p + len; cased = 0; previous_is_cased = 0; for (; p < e; p++) { - register const unsigned char ch = *p; + register const unsigned char ch = *p; - if (Py_ISUPPER(ch)) { - if (previous_is_cased) - Py_RETURN_FALSE; - previous_is_cased = 1; - cased = 1; - } - else if (Py_ISLOWER(ch)) { - if (!previous_is_cased) - Py_RETURN_FALSE; - previous_is_cased = 1; - cased = 1; - } - else - previous_is_cased = 0; + if (Py_ISUPPER(ch)) { + if (previous_is_cased) + Py_RETURN_FALSE; + previous_is_cased = 1; + cased = 1; + } + else if (Py_ISLOWER(ch)) { + if (!previous_is_cased) + Py_RETURN_FALSE; + previous_is_cased = 1; + cased = 1; + } + else + previous_is_cased = 0; } return PyBool_FromLong(cased); } @@ -246,23 +246,23 @@ void _Py_bytes_lower(char *result, const char *cptr, Py_ssize_t len) { - Py_ssize_t i; + Py_ssize_t i; /* - newobj = PyBytes_FromStringAndSize(NULL, len); - if (!newobj) - return NULL; + newobj = PyBytes_FromStringAndSize(NULL, len); + if (!newobj) + return NULL; - s = PyBytes_AS_STRING(newobj); + s = PyBytes_AS_STRING(newobj); */ - Py_MEMCPY(result, cptr, len); + Py_MEMCPY(result, cptr, len); - for (i = 0; i < len; i++) { - int c = Py_CHARMASK(result[i]); - if (Py_ISUPPER(c)) - result[i] = Py_TOLOWER(c); - } + for (i = 0; i < len; i++) { + int c = Py_CHARMASK(result[i]); + if (Py_ISUPPER(c)) + result[i] = Py_TOLOWER(c); + } } @@ -274,23 +274,23 @@ void _Py_bytes_upper(char *result, const char *cptr, Py_ssize_t len) { - Py_ssize_t i; + Py_ssize_t i; /* - newobj = PyBytes_FromStringAndSize(NULL, len); - if (!newobj) - return NULL; + newobj = PyBytes_FromStringAndSize(NULL, len); + if (!newobj) + return NULL; - s = PyBytes_AS_STRING(newobj); + s = PyBytes_AS_STRING(newobj); */ - Py_MEMCPY(result, cptr, len); + Py_MEMCPY(result, cptr, len); - for (i = 0; i < len; i++) { - int c = Py_CHARMASK(result[i]); - if (Py_ISLOWER(c)) - result[i] = Py_TOUPPER(c); - } + for (i = 0; i < len; i++) { + int c = Py_CHARMASK(result[i]); + if (Py_ISLOWER(c)) + result[i] = Py_TOUPPER(c); + } } @@ -303,29 +303,29 @@ void _Py_bytes_title(char *result, char *s, Py_ssize_t len) { - Py_ssize_t i; - int previous_is_cased = 0; + Py_ssize_t i; + int previous_is_cased = 0; /* - newobj = PyBytes_FromStringAndSize(NULL, len); - if (newobj == NULL) - return NULL; - s_new = PyBytes_AsString(newobj); + newobj = PyBytes_FromStringAndSize(NULL, len); + if (newobj == NULL) + return NULL; + s_new = PyBytes_AsString(newobj); */ - for (i = 0; i < len; i++) { - int c = Py_CHARMASK(*s++); - if (Py_ISLOWER(c)) { - if (!previous_is_cased) - c = Py_TOUPPER(c); - previous_is_cased = 1; - } else if (Py_ISUPPER(c)) { - if (previous_is_cased) - c = Py_TOLOWER(c); - previous_is_cased = 1; - } else - previous_is_cased = 0; - *result++ = c; - } + for (i = 0; i < len; i++) { + int c = Py_CHARMASK(*s++); + if (Py_ISLOWER(c)) { + if (!previous_is_cased) + c = Py_TOUPPER(c); + previous_is_cased = 1; + } else if (Py_ISUPPER(c)) { + if (previous_is_cased) + c = Py_TOLOWER(c); + previous_is_cased = 1; + } else + previous_is_cased = 0; + *result++ = c; + } } @@ -337,30 +337,30 @@ void _Py_bytes_capitalize(char *result, char *s, Py_ssize_t len) { - Py_ssize_t i; + Py_ssize_t i; /* - newobj = PyBytes_FromStringAndSize(NULL, len); - if (newobj == NULL) - return NULL; - s_new = PyBytes_AsString(newobj); + newobj = PyBytes_FromStringAndSize(NULL, len); + if (newobj == NULL) + return NULL; + s_new = PyBytes_AsString(newobj); */ - if (0 < len) { - int c = Py_CHARMASK(*s++); - if (Py_ISLOWER(c)) - *result = Py_TOUPPER(c); - else - *result = c; - result++; - } - for (i = 1; i < len; i++) { - int c = Py_CHARMASK(*s++); - if (Py_ISUPPER(c)) - *result = Py_TOLOWER(c); - else - *result = c; - result++; - } + if (0 < len) { + int c = Py_CHARMASK(*s++); + if (Py_ISLOWER(c)) + *result = Py_TOUPPER(c); + else + *result = c; + result++; + } + for (i = 1; i < len; i++) { + int c = Py_CHARMASK(*s++); + if (Py_ISUPPER(c)) + *result = Py_TOLOWER(c); + else + *result = c; + result++; + } } @@ -373,26 +373,26 @@ void _Py_bytes_swapcase(char *result, char *s, Py_ssize_t len) { - Py_ssize_t i; + Py_ssize_t i; /* - newobj = PyBytes_FromStringAndSize(NULL, len); - if (newobj == NULL) - return NULL; - s_new = PyBytes_AsString(newobj); + newobj = PyBytes_FromStringAndSize(NULL, len); + if (newobj == NULL) + return NULL; + s_new = PyBytes_AsString(newobj); */ - for (i = 0; i < len; i++) { - int c = Py_CHARMASK(*s++); - if (Py_ISLOWER(c)) { - *result = Py_TOUPPER(c); - } - else if (Py_ISUPPER(c)) { - *result = Py_TOLOWER(c); - } - else - *result = c; - result++; - } + for (i = 0; i < len; i++) { + int c = Py_CHARMASK(*s++); + if (Py_ISLOWER(c)) { + *result = Py_TOUPPER(c); + } + else if (Py_ISUPPER(c)) { + *result = Py_TOLOWER(c); + } + else + *result = c; + result++; + } } @@ -425,40 +425,40 @@ PyObject * _Py_bytes_maketrans(PyObject *args) { - PyObject *frm, *to, *res = NULL; - Py_buffer bfrm, bto; - Py_ssize_t i; - char *p; - - bfrm.len = -1; - bto.len = -1; - - if (!PyArg_ParseTuple(args, "OO:maketrans", &frm, &to)) - return NULL; - if (_getbuffer(frm, &bfrm) < 0) - return NULL; - if (_getbuffer(to, &bto) < 0) - goto done; - if (bfrm.len != bto.len) { - PyErr_Format(PyExc_ValueError, - "maketrans arguments must have same length"); - goto done; - } - res = PyBytes_FromStringAndSize(NULL, 256); - if (!res) { - goto done; - } - p = PyBytes_AS_STRING(res); - for (i = 0; i < 256; i++) - p[i] = i; - for (i = 0; i < bfrm.len; i++) { - p[((unsigned char *)bfrm.buf)[i]] = ((char *)bto.buf)[i]; - } + PyObject *frm, *to, *res = NULL; + Py_buffer bfrm, bto; + Py_ssize_t i; + char *p; + + bfrm.len = -1; + bto.len = -1; + + if (!PyArg_ParseTuple(args, "OO:maketrans", &frm, &to)) + return NULL; + if (_getbuffer(frm, &bfrm) < 0) + return NULL; + if (_getbuffer(to, &bto) < 0) + goto done; + if (bfrm.len != bto.len) { + PyErr_Format(PyExc_ValueError, + "maketrans arguments must have same length"); + goto done; + } + res = PyBytes_FromStringAndSize(NULL, 256); + if (!res) { + goto done; + } + p = PyBytes_AS_STRING(res); + for (i = 0; i < 256; i++) + p[i] = i; + for (i = 0; i < bfrm.len; i++) { + p[((unsigned char *)bfrm.buf)[i]] = ((char *)bto.buf)[i]; + } done: - if (bfrm.len != -1) - PyBuffer_Release(&bfrm); - if (bto.len != -1) - PyBuffer_Release(&bto); - return res; + if (bfrm.len != -1) + PyBuffer_Release(&bfrm); + if (bto.len != -1) + PyBuffer_Release(&bto); + return res; } Modified: python/branches/release31-maint/Objects/bytesobject.c ============================================================================== --- python/branches/release31-maint/Objects/bytesobject.c (original) +++ python/branches/release31-maint/Objects/bytesobject.c Sun May 9 18:14:21 2010 @@ -14,14 +14,14 @@ if (buffer == NULL || buffer->bf_getbuffer == NULL) { - PyErr_Format(PyExc_TypeError, - "Type %.100s doesn't support the buffer API", - Py_TYPE(obj)->tp_name); - return -1; + PyErr_Format(PyExc_TypeError, + "Type %.100s doesn't support the buffer API", + Py_TYPE(obj)->tp_name); + return -1; } if (buffer->bf_getbuffer(obj, view, PyBUF_SIMPLE) < 0) - return -1; + return -1; return view->len; } @@ -69,305 +69,305 @@ PyObject * PyBytes_FromStringAndSize(const char *str, Py_ssize_t size) { - register PyBytesObject *op; - if (size < 0) { - PyErr_SetString(PyExc_SystemError, - "Negative size passed to PyBytes_FromStringAndSize"); - return NULL; - } - if (size == 0 && (op = nullstring) != NULL) { + register PyBytesObject *op; + if (size < 0) { + PyErr_SetString(PyExc_SystemError, + "Negative size passed to PyBytes_FromStringAndSize"); + return NULL; + } + if (size == 0 && (op = nullstring) != NULL) { #ifdef COUNT_ALLOCS - null_strings++; + null_strings++; #endif - Py_INCREF(op); - return (PyObject *)op; - } - if (size == 1 && str != NULL && - (op = characters[*str & UCHAR_MAX]) != NULL) - { + Py_INCREF(op); + return (PyObject *)op; + } + if (size == 1 && str != NULL && + (op = characters[*str & UCHAR_MAX]) != NULL) + { #ifdef COUNT_ALLOCS - one_strings++; + one_strings++; #endif - Py_INCREF(op); - return (PyObject *)op; - } - - if (size > PY_SSIZE_T_MAX - PyBytesObject_SIZE) { - PyErr_SetString(PyExc_OverflowError, - "byte string is too large"); - return NULL; - } - - /* Inline PyObject_NewVar */ - op = (PyBytesObject *)PyObject_MALLOC(PyBytesObject_SIZE + size); - if (op == NULL) - return PyErr_NoMemory(); - PyObject_INIT_VAR(op, &PyBytes_Type, size); - op->ob_shash = -1; - if (str != NULL) - Py_MEMCPY(op->ob_sval, str, size); - op->ob_sval[size] = '\0'; - /* share short strings */ - if (size == 0) { - nullstring = op; - Py_INCREF(op); - } else if (size == 1 && str != NULL) { - characters[*str & UCHAR_MAX] = op; - Py_INCREF(op); - } - return (PyObject *) op; + Py_INCREF(op); + return (PyObject *)op; + } + + if (size > PY_SSIZE_T_MAX - PyBytesObject_SIZE) { + PyErr_SetString(PyExc_OverflowError, + "byte string is too large"); + return NULL; + } + + /* Inline PyObject_NewVar */ + op = (PyBytesObject *)PyObject_MALLOC(PyBytesObject_SIZE + size); + if (op == NULL) + return PyErr_NoMemory(); + PyObject_INIT_VAR(op, &PyBytes_Type, size); + op->ob_shash = -1; + if (str != NULL) + Py_MEMCPY(op->ob_sval, str, size); + op->ob_sval[size] = '\0'; + /* share short strings */ + if (size == 0) { + nullstring = op; + Py_INCREF(op); + } else if (size == 1 && str != NULL) { + characters[*str & UCHAR_MAX] = op; + Py_INCREF(op); + } + return (PyObject *) op; } PyObject * PyBytes_FromString(const char *str) { - register size_t size; - register PyBytesObject *op; + register size_t size; + register 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) { + 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++; + null_strings++; #endif - Py_INCREF(op); - return (PyObject *)op; - } - if (size == 1 && (op = characters[*str & UCHAR_MAX]) != NULL) { + Py_INCREF(op); + return (PyObject *)op; + } + if (size == 1 && (op = characters[*str & UCHAR_MAX]) != NULL) { #ifdef COUNT_ALLOCS - one_strings++; + 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(); - PyObject_INIT_VAR(op, &PyBytes_Type, size); - op->ob_shash = -1; - Py_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; + Py_INCREF(op); + return (PyObject *)op; + } + + /* Inline PyObject_NewVar */ + op = (PyBytesObject *)PyObject_MALLOC(PyBytesObject_SIZE + size); + if (op == NULL) + return PyErr_NoMemory(); + PyObject_INIT_VAR(op, &PyBytes_Type, size); + op->ob_shash = -1; + Py_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) { - va_list count; - Py_ssize_t n = 0; - const char* f; - char *s; - PyObject* string; + va_list count; + Py_ssize_t n = 0; + const char* f; + char *s; + PyObject* string; #ifdef VA_LIST_IS_ARRAY - Py_MEMCPY(count, vargs, sizeof(va_list)); + Py_MEMCPY(count, vargs, sizeof(va_list)); #else #ifdef __va_copy - __va_copy(count, vargs); + __va_copy(count, vargs); #else - count = vargs; + count = vargs; #endif #endif - /* step 1: figure out how large a buffer we need */ - for (f = format; *f; f++) { - if (*f == '%') { - const char* p = f; - while (*++f && *f != '%' && !ISALPHA(*f)) - ; - - /* skip the 'l' or 'z' in {%ld, %zd, %lu, %zu} since - * they don't affect the amount of space we reserve. - */ - if ((*f == 'l' || *f == 'z') && - (f[1] == 'd' || f[1] == 'u')) - ++f; - - switch (*f) { - case 'c': - (void)va_arg(count, int); - /* fall through... */ - case '%': - n++; - break; - case 'd': case 'u': case 'i': case 'x': - (void) va_arg(count, int); - /* 20 bytes is enough to hold a 64-bit - integer. Decimal takes the most space. - This isn't enough for octal. */ - n += 20; - break; - case 's': - s = va_arg(count, char*); - n += strlen(s); - break; - case 'p': - (void) va_arg(count, int); - /* maximum 64-bit pointer representation: - * 0xffffffffffffffff - * so 19 characters is enough. - * XXX I count 18 -- what's the extra for? - */ - n += 19; - break; - default: - /* if we stumble upon an unknown - formatting code, copy the rest of - the format string to the output - string. (we cannot just skip the - code, since there's no way to know - what's in the argument list) */ - n += strlen(p); - goto expand; - } - } else - n++; - } + /* step 1: figure out how large a buffer we need */ + for (f = format; *f; f++) { + if (*f == '%') { + const char* p = f; + while (*++f && *f != '%' && !ISALPHA(*f)) + ; + + /* skip the 'l' or 'z' in {%ld, %zd, %lu, %zu} since + * they don't affect the amount of space we reserve. + */ + if ((*f == 'l' || *f == 'z') && + (f[1] == 'd' || f[1] == 'u')) + ++f; + + switch (*f) { + case 'c': + (void)va_arg(count, int); + /* fall through... */ + case '%': + n++; + break; + case 'd': case 'u': case 'i': case 'x': + (void) va_arg(count, int); + /* 20 bytes is enough to hold a 64-bit + integer. Decimal takes the most space. + This isn't enough for octal. */ + n += 20; + break; + case 's': + s = va_arg(count, char*); + n += strlen(s); + break; + case 'p': + (void) va_arg(count, int); + /* maximum 64-bit pointer representation: + * 0xffffffffffffffff + * so 19 characters is enough. + * XXX I count 18 -- what's the extra for? + */ + n += 19; + break; + default: + /* if we stumble upon an unknown + formatting code, copy the rest of + the format string to the output + string. (we cannot just skip the + code, since there's no way to know + what's in the argument list) */ + n += strlen(p); + goto expand; + } + } else + n++; + } expand: - /* step 2: fill the buffer */ - /* Since we've analyzed how much space we need for the worst case, - use sprintf directly instead of the slower PyOS_snprintf. */ - string = PyBytes_FromStringAndSize(NULL, n); - if (!string) - return NULL; - - s = PyBytes_AsString(string); - - for (f = format; *f; f++) { - if (*f == '%') { - const char* p = f++; - Py_ssize_t i; - int longflag = 0; - int size_tflag = 0; - /* parse the width.precision part (we're only - interested in the precision value, if any) */ - n = 0; - while (ISDIGIT(*f)) - n = (n*10) + *f++ - '0'; - if (*f == '.') { - f++; - n = 0; - while (ISDIGIT(*f)) - n = (n*10) + *f++ - '0'; - } - while (*f && *f != '%' && !ISALPHA(*f)) - f++; - /* handle the long flag, but only for %ld and %lu. - others can be added when necessary. */ - if (*f == 'l' && (f[1] == 'd' || f[1] == 'u')) { - longflag = 1; - ++f; - } - /* handle the size_t flag. */ - if (*f == 'z' && (f[1] == 'd' || f[1] == 'u')) { - size_tflag = 1; - ++f; - } - - switch (*f) { - case 'c': - *s++ = va_arg(vargs, int); - break; - case 'd': - if (longflag) - sprintf(s, "%ld", va_arg(vargs, long)); - else if (size_tflag) - sprintf(s, "%" PY_FORMAT_SIZE_T "d", - va_arg(vargs, Py_ssize_t)); - else - sprintf(s, "%d", va_arg(vargs, int)); - s += strlen(s); - break; - case 'u': - if (longflag) - sprintf(s, "%lu", - va_arg(vargs, unsigned long)); - else if (size_tflag) - sprintf(s, "%" PY_FORMAT_SIZE_T "u", - va_arg(vargs, size_t)); - else - sprintf(s, "%u", - va_arg(vargs, unsigned int)); - s += strlen(s); - break; - case 'i': - sprintf(s, "%i", va_arg(vargs, int)); - s += strlen(s); - break; - case 'x': - sprintf(s, "%x", va_arg(vargs, int)); - s += strlen(s); - break; - case 's': - p = va_arg(vargs, char*); - i = strlen(p); - if (n > 0 && i > n) - i = n; - Py_MEMCPY(s, p, i); - s += i; - break; - case 'p': - sprintf(s, "%p", va_arg(vargs, void*)); - /* %p is ill-defined: ensure leading 0x. */ - if (s[1] == 'X') - s[1] = 'x'; - else if (s[1] != 'x') { - memmove(s+2, s, strlen(s)+1); - s[0] = '0'; - s[1] = 'x'; - } - s += strlen(s); - break; - case '%': - *s++ = '%'; - break; - default: - strcpy(s, p); - s += strlen(s); - goto end; - } - } else - *s++ = *f; - } + /* step 2: fill the buffer */ + /* Since we've analyzed how much space we need for the worst case, + use sprintf directly instead of the slower PyOS_snprintf. */ + string = PyBytes_FromStringAndSize(NULL, n); + if (!string) + return NULL; + + s = PyBytes_AsString(string); + + for (f = format; *f; f++) { + if (*f == '%') { + const char* p = f++; + Py_ssize_t i; + int longflag = 0; + int size_tflag = 0; + /* parse the width.precision part (we're only + interested in the precision value, if any) */ + n = 0; + while (ISDIGIT(*f)) + n = (n*10) + *f++ - '0'; + if (*f == '.') { + f++; + n = 0; + while (ISDIGIT(*f)) + n = (n*10) + *f++ - '0'; + } + while (*f && *f != '%' && !ISALPHA(*f)) + f++; + /* handle the long flag, but only for %ld and %lu. + others can be added when necessary. */ + if (*f == 'l' && (f[1] == 'd' || f[1] == 'u')) { + longflag = 1; + ++f; + } + /* handle the size_t flag. */ + if (*f == 'z' && (f[1] == 'd' || f[1] == 'u')) { + size_tflag = 1; + ++f; + } + + switch (*f) { + case 'c': + *s++ = va_arg(vargs, int); + break; + case 'd': + if (longflag) + sprintf(s, "%ld", va_arg(vargs, long)); + else if (size_tflag) + sprintf(s, "%" PY_FORMAT_SIZE_T "d", + va_arg(vargs, Py_ssize_t)); + else + sprintf(s, "%d", va_arg(vargs, int)); + s += strlen(s); + break; + case 'u': + if (longflag) + sprintf(s, "%lu", + va_arg(vargs, unsigned long)); + else if (size_tflag) + sprintf(s, "%" PY_FORMAT_SIZE_T "u", + va_arg(vargs, size_t)); + else + sprintf(s, "%u", + va_arg(vargs, unsigned int)); + s += strlen(s); + break; + case 'i': + sprintf(s, "%i", va_arg(vargs, int)); + s += strlen(s); + break; + case 'x': + sprintf(s, "%x", va_arg(vargs, int)); + s += strlen(s); + break; + case 's': + p = va_arg(vargs, char*); + i = strlen(p); + if (n > 0 && i > n) + i = n; + Py_MEMCPY(s, p, i); + s += i; + break; + case 'p': + sprintf(s, "%p", va_arg(vargs, void*)); + /* %p is ill-defined: ensure leading 0x. */ + if (s[1] == 'X') + s[1] = 'x'; + else if (s[1] != 'x') { + memmove(s+2, s, strlen(s)+1); + s[0] = '0'; + s[1] = 'x'; + } + s += strlen(s); + break; + case '%': + *s++ = '%'; + break; + default: + strcpy(s, p); + s += strlen(s); + goto end; + } + } else + *s++ = *f; + } end: - _PyBytes_Resize(&string, s - PyBytes_AS_STRING(string)); - return string; + _PyBytes_Resize(&string, s - PyBytes_AS_STRING(string)); + return string; } PyObject * PyBytes_FromFormat(const char *format, ...) { - PyObject* ret; - va_list vargs; + PyObject* ret; + va_list vargs; #ifdef HAVE_STDARG_PROTOTYPES - va_start(vargs, format); + va_start(vargs, format); #else - va_start(vargs); + va_start(vargs); #endif - ret = PyBytes_FromFormatV(format, vargs); - va_end(vargs); - return ret; + ret = PyBytes_FromFormatV(format, vargs); + va_end(vargs); + return ret; } static void bytes_dealloc(PyObject *op) { - Py_TYPE(op)->tp_free(op); + Py_TYPE(op)->tp_free(op); } /* Unescape a backslash-escaped string. If unicode is non-zero, @@ -376,135 +376,135 @@ specified encoding. */ PyObject *PyBytes_DecodeEscape(const char *s, - Py_ssize_t len, - const char *errors, - Py_ssize_t unicode, - const char *recode_encoding) -{ - int c; - char *p, *buf; - const char *end; - PyObject *v; - Py_ssize_t newlen = recode_encoding ? 4*len:len; - v = PyBytes_FromStringAndSize((char *)NULL, newlen); - if (v == NULL) - return NULL; - p = buf = PyBytes_AsString(v); - end = s + len; - while (s < end) { - if (*s != '\\') { - non_esc: - if (recode_encoding && (*s & 0x80)) { - PyObject *u, *w; - char *r; - const char* t; - Py_ssize_t rn; - t = s; - /* Decode non-ASCII bytes as UTF-8. */ - while (t < end && (*t & 0x80)) t++; - u = PyUnicode_DecodeUTF8(s, t - s, errors); - if(!u) goto failed; - - /* Recode them in target encoding. */ - w = PyUnicode_AsEncodedString( - u, recode_encoding, errors); - Py_DECREF(u); - if (!w) goto failed; - - /* Append bytes to output buffer. */ - assert(PyBytes_Check(w)); - r = PyBytes_AS_STRING(w); - rn = PyBytes_GET_SIZE(w); - Py_MEMCPY(p, r, rn); - p += rn; - Py_DECREF(w); - s = t; - } else { - *p++ = *s++; - } - 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 && ISXDIGIT(s[0]) && ISXDIGIT(s[1])) { - unsigned int x = 0; - c = Py_CHARMASK(*s); - s++; - if (ISDIGIT(c)) - x = c - '0'; - else if (ISLOWER(c)) - x = 10 + c - 'a'; - else - x = 10 + c - 'A'; - x = x << 4; - c = Py_CHARMASK(*s); - s++; - if (ISDIGIT(c)) - x += c - '0'; - else if (ISLOWER(c)) - x += 10 + c - 'a'; - else - x += 10 + c - 'A'; - *p++ = x; - break; - } - if (!errors || strcmp(errors, "strict") == 0) { - PyErr_SetString(PyExc_ValueError, - "invalid \\x escape"); - 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; - } - default: - *p++ = '\\'; - s--; - goto non_esc; /* an arbitry number of unescaped - UTF-8 bytes may follow. */ - } - } - if (p-buf < newlen) - _PyBytes_Resize(&v, p - buf); - return v; + Py_ssize_t len, + const char *errors, + Py_ssize_t unicode, + const char *recode_encoding) +{ + int c; + char *p, *buf; + const char *end; + PyObject *v; + Py_ssize_t newlen = recode_encoding ? 4*len:len; + v = PyBytes_FromStringAndSize((char *)NULL, newlen); + if (v == NULL) + return NULL; + p = buf = PyBytes_AsString(v); + end = s + len; + while (s < end) { + if (*s != '\\') { + non_esc: + if (recode_encoding && (*s & 0x80)) { + PyObject *u, *w; + char *r; + const char* t; + Py_ssize_t rn; + t = s; + /* Decode non-ASCII bytes as UTF-8. */ + while (t < end && (*t & 0x80)) t++; + u = PyUnicode_DecodeUTF8(s, t - s, errors); + if(!u) goto failed; + + /* Recode them in target encoding. */ + w = PyUnicode_AsEncodedString( + u, recode_encoding, errors); + Py_DECREF(u); + if (!w) goto failed; + + /* Append bytes to output buffer. */ + assert(PyBytes_Check(w)); + r = PyBytes_AS_STRING(w); + rn = PyBytes_GET_SIZE(w); + Py_MEMCPY(p, r, rn); + p += rn; + Py_DECREF(w); + s = t; + } else { + *p++ = *s++; + } + 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 && ISXDIGIT(s[0]) && ISXDIGIT(s[1])) { + unsigned int x = 0; + c = Py_CHARMASK(*s); + s++; + if (ISDIGIT(c)) + x = c - '0'; + else if (ISLOWER(c)) + x = 10 + c - 'a'; + else + x = 10 + c - 'A'; + x = x << 4; + c = Py_CHARMASK(*s); + s++; + if (ISDIGIT(c)) + x += c - '0'; + else if (ISLOWER(c)) + x += 10 + c - 'a'; + else + x += 10 + c - 'A'; + *p++ = x; + break; + } + if (!errors || strcmp(errors, "strict") == 0) { + PyErr_SetString(PyExc_ValueError, + "invalid \\x escape"); + 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; + } + default: + *p++ = '\\'; + s--; + goto non_esc; /* an arbitry number of unescaped + UTF-8 bytes may follow. */ + } + } + if (p-buf < newlen) + _PyBytes_Resize(&v, p - buf); + return v; failed: - Py_DECREF(v); - return NULL; + Py_DECREF(v); + return NULL; } /* -------------------------------------------------------------------- */ @@ -513,50 +513,50 @@ Py_ssize_t PyBytes_Size(register 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); + 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(register 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; + 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(register PyObject *obj, - register char **s, - register Py_ssize_t *len) + register char **s, + register 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_TypeError, - "expected bytes with no null"); - return -1; - } - return 0; + 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_TypeError, + "expected bytes with no null"); + return -1; + } + return 0; } /* -------------------------------------------------------------------- */ @@ -590,199 +590,199 @@ PyObject * PyBytes_Repr(PyObject *obj, int smartquotes) { - static const char *hexdigits = "0123456789abcdef"; - register PyBytesObject* op = (PyBytesObject*) obj; - Py_ssize_t length = Py_SIZE(op); - size_t newsize = 3 + 4 * length; - PyObject *v; - if (newsize > PY_SSIZE_T_MAX || (newsize-3) / 4 != length) { - PyErr_SetString(PyExc_OverflowError, - "bytes object is too large to make repr"); - return NULL; - } - v = PyUnicode_FromUnicode(NULL, newsize); - if (v == NULL) { - return NULL; - } - else { - register Py_ssize_t i; - register Py_UNICODE c; - register Py_UNICODE *p = PyUnicode_AS_UNICODE(v); - int quote; - - /* Figure out which quote to use; single is preferred */ - quote = '\''; - if (smartquotes) { - char *test, *start; - start = PyBytes_AS_STRING(op); - for (test = start; test < start+length; ++test) { - if (*test == '"') { - quote = '\''; /* back to single */ - goto decided; - } - else if (*test == '\'') - quote = '"'; - } - decided: - ; - } - - *p++ = 'b', *p++ = quote; - for (i = 0; i < length; i++) { - /* There's at least enough room for a hex escape - and a closing quote. */ - assert(newsize - (p - PyUnicode_AS_UNICODE(v)) >= 5); - 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++ = hexdigits[(c & 0xf0) >> 4]; - *p++ = hexdigits[c & 0xf]; - } - else - *p++ = c; - } - assert(newsize - (p - PyUnicode_AS_UNICODE(v)) >= 1); - *p++ = quote; - *p = '\0'; - if (PyUnicode_Resize(&v, (p - PyUnicode_AS_UNICODE(v)))) { - Py_DECREF(v); - return NULL; - } - return v; - } + static const char *hexdigits = "0123456789abcdef"; + register PyBytesObject* op = (PyBytesObject*) obj; + Py_ssize_t length = Py_SIZE(op); + size_t newsize = 3 + 4 * length; + PyObject *v; + if (newsize > PY_SSIZE_T_MAX || (newsize-3) / 4 != length) { + PyErr_SetString(PyExc_OverflowError, + "bytes object is too large to make repr"); + return NULL; + } + v = PyUnicode_FromUnicode(NULL, newsize); + if (v == NULL) { + return NULL; + } + else { + register Py_ssize_t i; + register Py_UNICODE c; + register Py_UNICODE *p = PyUnicode_AS_UNICODE(v); + int quote; + + /* Figure out which quote to use; single is preferred */ + quote = '\''; + if (smartquotes) { + char *test, *start; + start = PyBytes_AS_STRING(op); + for (test = start; test < start+length; ++test) { + if (*test == '"') { + quote = '\''; /* back to single */ + goto decided; + } + else if (*test == '\'') + quote = '"'; + } + decided: + ; + } + + *p++ = 'b', *p++ = quote; + for (i = 0; i < length; i++) { + /* There's at least enough room for a hex escape + and a closing quote. */ + assert(newsize - (p - PyUnicode_AS_UNICODE(v)) >= 5); + 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++ = hexdigits[(c & 0xf0) >> 4]; + *p++ = hexdigits[c & 0xf]; + } + else + *p++ = c; + } + assert(newsize - (p - PyUnicode_AS_UNICODE(v)) >= 1); + *p++ = quote; + *p = '\0'; + if (PyUnicode_Resize(&v, (p - PyUnicode_AS_UNICODE(v)))) { + Py_DECREF(v); + return NULL; + } + return v; + } } static PyObject * bytes_repr(PyObject *op) { - return PyBytes_Repr(op, 1); + 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); + 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); + return Py_SIZE(a); } /* This is also used by PyBytes_Concat() */ static PyObject * bytes_concat(PyObject *a, PyObject *b) { - Py_ssize_t size; - Py_buffer va, vb; - PyObject *result = NULL; - - va.len = -1; - vb.len = -1; - if (_getbuffer(a, &va) < 0 || - _getbuffer(b, &vb) < 0) { - PyErr_Format(PyExc_TypeError, "can't concat %.100s to %.100s", - Py_TYPE(a)->tp_name, Py_TYPE(b)->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; - } - - size = va.len + vb.len; - if (size < 0) { - PyErr_NoMemory(); - goto done; - } - - result = PyBytes_FromStringAndSize(NULL, size); - if (result != NULL) { - memcpy(PyBytes_AS_STRING(result), va.buf, va.len); - memcpy(PyBytes_AS_STRING(result) + va.len, vb.buf, vb.len); - } + Py_ssize_t size; + Py_buffer va, vb; + PyObject *result = NULL; + + va.len = -1; + vb.len = -1; + if (_getbuffer(a, &va) < 0 || + _getbuffer(b, &vb) < 0) { + PyErr_Format(PyExc_TypeError, "can't concat %.100s to %.100s", + Py_TYPE(a)->tp_name, Py_TYPE(b)->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; + } + + size = va.len + vb.len; + if (size < 0) { + PyErr_NoMemory(); + goto done; + } + + result = PyBytes_FromStringAndSize(NULL, size); + 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; + if (va.len != -1) + PyBuffer_Release(&va); + if (vb.len != -1) + PyBuffer_Release(&vb); + return result; } static PyObject * bytes_repeat(register PyBytesObject *a, register Py_ssize_t n) { - register Py_ssize_t i; - register Py_ssize_t j; - register Py_ssize_t size; - register 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 - */ - size = Py_SIZE(a) * n; - if (n && size / n != Py_SIZE(a)) { - PyErr_SetString(PyExc_OverflowError, - "repeated bytes are too long"); - return NULL; - } - 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(); - 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) { - Py_MEMCPY(op->ob_sval, a->ob_sval, Py_SIZE(a)); - i = Py_SIZE(a); - } - while (i < size) { - j = (i <= size-i) ? i : size-i; - Py_MEMCPY(op->ob_sval+i, op->ob_sval, j); - i += j; - } - return (PyObject *) op; + register Py_ssize_t i; + register Py_ssize_t j; + register Py_ssize_t size; + register 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 + */ + size = Py_SIZE(a) * n; + if (n && size / n != Py_SIZE(a)) { + PyErr_SetString(PyExc_OverflowError, + "repeated bytes are too long"); + return NULL; + } + 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(); + 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) { + Py_MEMCPY(op->ob_sval, a->ob_sval, Py_SIZE(a)); + i = Py_SIZE(a); + } + while (i < size) { + j = (i <= size-i) ? i : size-i; + Py_MEMCPY(op->ob_sval+i, op->ob_sval, j); + i += j; + } + return (PyObject *) op; } static int @@ -790,19 +790,19 @@ { Py_ssize_t ival = PyNumber_AsSsize_t(arg, PyExc_ValueError); if (ival == -1 && PyErr_Occurred()) { - Py_buffer varg; - int pos; - PyErr_Clear(); - if (_getbuffer(arg, &varg) < 0) - return -1; - pos = stringlib_find(PyBytes_AS_STRING(self), Py_SIZE(self), - varg.buf, varg.len, 0); - PyBuffer_Release(&varg); - return pos >= 0; + Py_buffer varg; + int pos; + PyErr_Clear(); + if (_getbuffer(arg, &varg) < 0) + return -1; + pos = stringlib_find(PyBytes_AS_STRING(self), Py_SIZE(self), + varg.buf, varg.len, 0); + PyBuffer_Release(&varg); + return pos >= 0; } if (ival < 0 || ival >= 256) { - PyErr_SetString(PyExc_ValueError, "byte must be in range(0, 256)"); - return -1; + PyErr_SetString(PyExc_ValueError, "byte must be in range(0, 256)"); + return -1; } return memchr(PyBytes_AS_STRING(self), ival, Py_SIZE(self)) != NULL; @@ -811,197 +811,197 @@ static PyObject * bytes_item(PyBytesObject *a, register 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]); + 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 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; - - /* Make sure both arguments are strings. */ - if (!(PyBytes_Check(a) && PyBytes_Check(b))) { - if (Py_BytesWarningFlag && (op == Py_EQ || op == Py_NE) && - (PyObject_IsInstance((PyObject*)a, - (PyObject*)&PyUnicode_Type) || - PyObject_IsInstance((PyObject*)b, - (PyObject*)&PyUnicode_Type))) { - if (PyErr_WarnEx(PyExc_BytesWarning, - "Comparison between bytes and string", 1)) - return NULL; - } - result = Py_NotImplemented; - goto out; - } - if (a == b) { - switch (op) { - case Py_EQ:case Py_LE:case Py_GE: - result = Py_True; - goto out; - case Py_NE:case Py_LT:case Py_GT: - result = Py_False; - goto out; - } - } - if (op == Py_EQ) { - /* Supporting Py_NE here as well does not save - much time, since Py_NE is rarely used. */ - if (Py_SIZE(a) == Py_SIZE(b) - && (a->ob_sval[0] == b->ob_sval[0] - && memcmp(a->ob_sval, b->ob_sval, Py_SIZE(a)) == 0)) { - result = Py_True; - } else { - result = Py_False; - } - goto out; - } - len_a = Py_SIZE(a); len_b = Py_SIZE(b); - min_len = (len_a < len_b) ? 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_EQ: assert(0); break; /* unreachable */ - case Py_NE: c = c != 0; break; - case Py_GT: c = c > 0; break; - case Py_GE: c = c >= 0; break; - default: - result = Py_NotImplemented; - goto out; - } - result = c ? Py_True : Py_False; + int c; + Py_ssize_t len_a, len_b; + Py_ssize_t min_len; + PyObject *result; + + /* Make sure both arguments are strings. */ + if (!(PyBytes_Check(a) && PyBytes_Check(b))) { + if (Py_BytesWarningFlag && (op == Py_EQ || op == Py_NE) && + (PyObject_IsInstance((PyObject*)a, + (PyObject*)&PyUnicode_Type) || + PyObject_IsInstance((PyObject*)b, + (PyObject*)&PyUnicode_Type))) { + if (PyErr_WarnEx(PyExc_BytesWarning, + "Comparison between bytes and string", 1)) + return NULL; + } + result = Py_NotImplemented; + goto out; + } + if (a == b) { + switch (op) { + case Py_EQ:case Py_LE:case Py_GE: + result = Py_True; + goto out; + case Py_NE:case Py_LT:case Py_GT: + result = Py_False; + goto out; + } + } + if (op == Py_EQ) { + /* Supporting Py_NE here as well does not save + much time, since Py_NE is rarely used. */ + if (Py_SIZE(a) == Py_SIZE(b) + && (a->ob_sval[0] == b->ob_sval[0] + && memcmp(a->ob_sval, b->ob_sval, Py_SIZE(a)) == 0)) { + result = Py_True; + } else { + result = Py_False; + } + goto out; + } + len_a = Py_SIZE(a); len_b = Py_SIZE(b); + min_len = (len_a < len_b) ? 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_EQ: assert(0); break; /* unreachable */ + case Py_NE: c = c != 0; break; + case Py_GT: c = c > 0; break; + case Py_GE: c = c >= 0; break; + default: + result = Py_NotImplemented; + goto out; + } + result = c ? Py_True : Py_False; out: - Py_INCREF(result); - return result; + Py_INCREF(result); + return result; } static long bytes_hash(PyBytesObject *a) { - register Py_ssize_t len; - register unsigned char *p; - register long x; - - if (a->ob_shash != -1) - return a->ob_shash; - len = Py_SIZE(a); - p = (unsigned char *) a->ob_sval; - x = *p << 7; - while (--len >= 0) - x = (1000003*x) ^ *p++; - x ^= Py_SIZE(a); - if (x == -1) - x = -2; - a->ob_shash = x; - return x; + register Py_ssize_t len; + register unsigned char *p; + register long x; + + if (a->ob_shash != -1) + return a->ob_shash; + len = Py_SIZE(a); + p = (unsigned char *) a->ob_sval; + x = *p << 7; + while (--len >= 0) + x = (1000003*x) ^ *p++; + x ^= Py_SIZE(a); + if (x == -1) + x = -2; + a->ob_shash = x; + return x; } 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_GetIndicesEx((PySliceObject*)item, - PyBytes_GET_SIZE(self), - &start, &stop, &step, &slicelength) < 0) { - return NULL; - } - - 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, not %.200s", - Py_TYPE(item)->tp_name); - return NULL; - } + 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_GetIndicesEx((PySliceObject*)item, + PyBytes_GET_SIZE(self), + &start, &stop, &step, &slicelength) < 0) { + return NULL; + } + + 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, 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); + 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*/ + (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, + (lenfunc)bytes_length, + (binaryfunc)bytes_subscript, + 0, }; static PyBufferProcs bytes_as_buffer = { - (getbufferproc)bytes_buffer_getbuffer, - NULL, + (getbufferproc)bytes_buffer_getbuffer, + NULL, }; @@ -1016,9 +1016,9 @@ /* Don't call if length < 2 */ -#define Py_STRING_MATCH(target, offset, pattern, length) \ - (target[offset] == pattern[0] && \ - target[offset+length-1] == pattern[length-1] && \ +#define Py_STRING_MATCH(target, offset, pattern, length) \ + (target[offset] == pattern[0] && \ + target[offset+length-1] == pattern[length-1] && \ !memcmp(target+offset+1, pattern+1, length-2) ) @@ -1033,24 +1033,24 @@ /* 5 splits gives 6 elements */ #define PREALLOC_SIZE(maxsplit) \ - (maxsplit >= MAX_PREALLOC ? MAX_PREALLOC : maxsplit+1) + (maxsplit >= MAX_PREALLOC ? MAX_PREALLOC : maxsplit+1) -#define SPLIT_ADD(data, left, right) { \ - str = PyBytes_FromStringAndSize((data) + (left), \ - (right) - (left)); \ - if (str == NULL) \ - goto onError; \ - if (count < MAX_PREALLOC) { \ - PyList_SET_ITEM(list, count, str); \ - } else { \ - if (PyList_Append(list, str)) { \ - Py_DECREF(str); \ - goto onError; \ - } \ - else \ - Py_DECREF(str); \ - } \ - count++; } +#define SPLIT_ADD(data, left, right) { \ + str = PyBytes_FromStringAndSize((data) + (left), \ + (right) - (left)); \ + if (str == NULL) \ + goto onError; \ + if (count < MAX_PREALLOC) { \ + PyList_SET_ITEM(list, count, str); \ + } else { \ + if (PyList_Append(list, str)) { \ + Py_DECREF(str); \ + goto onError; \ + } \ + else \ + Py_DECREF(str); \ + } \ + count++; } /* Always force the list to the expected size. */ #define FIX_PREALLOC_SIZE(list) Py_SIZE(list) = count @@ -1063,82 +1063,82 @@ Py_LOCAL_INLINE(PyObject *) split_whitespace(PyBytesObject *self, Py_ssize_t len, Py_ssize_t maxsplit) { - const char *s = PyBytes_AS_STRING(self); - Py_ssize_t i, j, count=0; - PyObject *str; - PyObject *list = PyList_New(PREALLOC_SIZE(maxsplit)); - - if (list == NULL) - return NULL; - - i = j = 0; - - while (maxsplit-- > 0) { - SKIP_SPACE(s, i, len); - if (i==len) break; - j = i; i++; - SKIP_NONSPACE(s, i, len); - if (j == 0 && i == len && PyBytes_CheckExact(self)) { - /* No whitespace in self, so just use it as list[0] */ - Py_INCREF(self); - PyList_SET_ITEM(list, 0, (PyObject *)self); - count++; - break; - } - SPLIT_ADD(s, j, i); - } - - if (i < len) { - /* Only occurs when maxsplit was reached */ - /* Skip any remaining whitespace and copy to end of string */ - SKIP_SPACE(s, i, len); - if (i != len) - SPLIT_ADD(s, i, len); - } - FIX_PREALLOC_SIZE(list); - return list; + const char *s = PyBytes_AS_STRING(self); + Py_ssize_t i, j, count=0; + PyObject *str; + PyObject *list = PyList_New(PREALLOC_SIZE(maxsplit)); + + if (list == NULL) + return NULL; + + i = j = 0; + + while (maxsplit-- > 0) { + SKIP_SPACE(s, i, len); + if (i==len) break; + j = i; i++; + SKIP_NONSPACE(s, i, len); + if (j == 0 && i == len && PyBytes_CheckExact(self)) { + /* No whitespace in self, so just use it as list[0] */ + Py_INCREF(self); + PyList_SET_ITEM(list, 0, (PyObject *)self); + count++; + break; + } + SPLIT_ADD(s, j, i); + } + + if (i < len) { + /* Only occurs when maxsplit was reached */ + /* Skip any remaining whitespace and copy to end of string */ + SKIP_SPACE(s, i, len); + if (i != len) + SPLIT_ADD(s, i, len); + } + FIX_PREALLOC_SIZE(list); + return list; onError: - Py_DECREF(list); - return NULL; + Py_DECREF(list); + return NULL; } Py_LOCAL_INLINE(PyObject *) split_char(PyBytesObject *self, Py_ssize_t len, char ch, Py_ssize_t maxcount) { - const char *s = PyBytes_AS_STRING(self); - register Py_ssize_t i, j, count=0; - PyObject *str; - PyObject *list = PyList_New(PREALLOC_SIZE(maxcount)); - - if (list == NULL) - return NULL; - - i = j = 0; - while ((j < len) && (maxcount-- > 0)) { - for(; j 0)) { + for(; j 0) { - pos = fastsearch(s+i, len-i, sub, n, FAST_SEARCH); - if (pos < 0) - break; - j = i+pos; - SPLIT_ADD(s, i, j); - i = j + n; - } + i = j = 0; + while (maxsplit-- > 0) { + pos = fastsearch(s+i, len-i, sub, n, FAST_SEARCH); + if (pos < 0) + break; + j = i+pos; + SPLIT_ADD(s, i, j); + i = j + n; + } #else - i = j = 0; - while ((j+n <= len) && (maxsplit-- > 0)) { - for (; j+n <= len; j++) { - if (Py_STRING_MATCH(s, j, sub, n)) { - SPLIT_ADD(s, i, j); - i = j = j + n; - break; - } - } - } + i = j = 0; + while ((j+n <= len) && (maxsplit-- > 0)) { + for (; j+n <= len; j++) { + if (Py_STRING_MATCH(s, j, sub, n)) { + SPLIT_ADD(s, i, j); + i = j = j + n; + break; + } + } + } #endif - SPLIT_ADD(s, i, len); - FIX_PREALLOC_SIZE(list); - PyBuffer_Release(&vsub); - return list; + SPLIT_ADD(s, i, len); + FIX_PREALLOC_SIZE(list); + PyBuffer_Release(&vsub); + return list; onError: - Py_DECREF(list); - PyBuffer_Release(&vsub); - return NULL; + Py_DECREF(list); + PyBuffer_Release(&vsub); + return NULL; } PyDoc_STRVAR(partition__doc__, @@ -1232,21 +1232,21 @@ static PyObject * bytes_partition(PyBytesObject *self, PyObject *sep_obj) { - const char *sep; - Py_ssize_t sep_len; + const char *sep; + Py_ssize_t sep_len; - if (PyBytes_Check(sep_obj)) { - sep = PyBytes_AS_STRING(sep_obj); - sep_len = PyBytes_GET_SIZE(sep_obj); - } - else if (PyObject_AsCharBuffer(sep_obj, &sep, &sep_len)) - return NULL; - - return stringlib_partition( - (PyObject*) self, - PyBytes_AS_STRING(self), PyBytes_GET_SIZE(self), - sep_obj, sep, sep_len - ); + if (PyBytes_Check(sep_obj)) { + sep = PyBytes_AS_STRING(sep_obj); + sep_len = PyBytes_GET_SIZE(sep_obj); + } + else if (PyObject_AsCharBuffer(sep_obj, &sep, &sep_len)) + return NULL; + + return stringlib_partition( + (PyObject*) self, + PyBytes_AS_STRING(self), PyBytes_GET_SIZE(self), + sep_obj, sep, sep_len + ); } PyDoc_STRVAR(rpartition__doc__, @@ -1260,105 +1260,105 @@ static PyObject * bytes_rpartition(PyBytesObject *self, PyObject *sep_obj) { - const char *sep; - Py_ssize_t sep_len; + const char *sep; + Py_ssize_t sep_len; + + if (PyBytes_Check(sep_obj)) { + sep = PyBytes_AS_STRING(sep_obj); + sep_len = PyBytes_GET_SIZE(sep_obj); + } + else if (PyObject_AsCharBuffer(sep_obj, &sep, &sep_len)) + return NULL; - if (PyBytes_Check(sep_obj)) { - sep = PyBytes_AS_STRING(sep_obj); - sep_len = PyBytes_GET_SIZE(sep_obj); - } - else if (PyObject_AsCharBuffer(sep_obj, &sep, &sep_len)) - return NULL; - - return stringlib_rpartition( - (PyObject*) self, - PyBytes_AS_STRING(self), PyBytes_GET_SIZE(self), - sep_obj, sep, sep_len - ); + return stringlib_rpartition( + (PyObject*) self, + PyBytes_AS_STRING(self), PyBytes_GET_SIZE(self), + sep_obj, sep, sep_len + ); } Py_LOCAL_INLINE(PyObject *) rsplit_whitespace(PyBytesObject *self, Py_ssize_t len, Py_ssize_t maxsplit) { - const char *s = PyBytes_AS_STRING(self); - Py_ssize_t i, j, count=0; - PyObject *str; - PyObject *list = PyList_New(PREALLOC_SIZE(maxsplit)); - - if (list == NULL) - return NULL; - - i = j = len-1; - - while (maxsplit-- > 0) { - RSKIP_SPACE(s, i); - if (i<0) break; - j = i; i--; - RSKIP_NONSPACE(s, i); - if (j == len-1 && i < 0 && PyBytes_CheckExact(self)) { - /* No whitespace in self, so just use it as list[0] */ - Py_INCREF(self); - PyList_SET_ITEM(list, 0, (PyObject *)self); - count++; - break; - } - SPLIT_ADD(s, i + 1, j + 1); - } - if (i >= 0) { - /* Only occurs when maxsplit was reached. Skip any remaining - whitespace and copy to beginning of string. */ - RSKIP_SPACE(s, i); - if (i >= 0) - SPLIT_ADD(s, 0, i + 1); - - } - FIX_PREALLOC_SIZE(list); - if (PyList_Reverse(list) < 0) - goto onError; - return list; + const char *s = PyBytes_AS_STRING(self); + Py_ssize_t i, j, count=0; + PyObject *str; + PyObject *list = PyList_New(PREALLOC_SIZE(maxsplit)); + + if (list == NULL) + return NULL; + + i = j = len-1; + + while (maxsplit-- > 0) { + RSKIP_SPACE(s, i); + if (i<0) break; + j = i; i--; + RSKIP_NONSPACE(s, i); + if (j == len-1 && i < 0 && PyBytes_CheckExact(self)) { + /* No whitespace in self, so just use it as list[0] */ + Py_INCREF(self); + PyList_SET_ITEM(list, 0, (PyObject *)self); + count++; + break; + } + SPLIT_ADD(s, i + 1, j + 1); + } + if (i >= 0) { + /* Only occurs when maxsplit was reached. Skip any remaining + whitespace and copy to beginning of string. */ + RSKIP_SPACE(s, i); + if (i >= 0) + SPLIT_ADD(s, 0, i + 1); + + } + FIX_PREALLOC_SIZE(list); + if (PyList_Reverse(list) < 0) + goto onError; + return list; onError: - Py_DECREF(list); - return NULL; + Py_DECREF(list); + return NULL; } Py_LOCAL_INLINE(PyObject *) rsplit_char(PyBytesObject *self, Py_ssize_t len, char ch, Py_ssize_t maxcount) { - const char *s = PyBytes_AS_STRING(self); - register Py_ssize_t i, j, count=0; - PyObject *str; - PyObject *list = PyList_New(PREALLOC_SIZE(maxcount)); - - if (list == NULL) - return NULL; - - i = j = len - 1; - while ((i >= 0) && (maxcount-- > 0)) { - for (; i >= 0; i--) { - if (s[i] == ch) { - SPLIT_ADD(s, i + 1, j + 1); - j = i = i - 1; - break; - } - } - } - if (i < 0 && count == 0 && PyBytes_CheckExact(self)) { - /* ch not in self, so just use self as list[0] */ - Py_INCREF(self); - PyList_SET_ITEM(list, 0, (PyObject *)self); - count++; - } - else if (j >= -1) { - SPLIT_ADD(s, 0, j + 1); - } - FIX_PREALLOC_SIZE(list); - if (PyList_Reverse(list) < 0) - goto onError; - return list; + const char *s = PyBytes_AS_STRING(self); + register Py_ssize_t i, j, count=0; + PyObject *str; + PyObject *list = PyList_New(PREALLOC_SIZE(maxcount)); + + if (list == NULL) + return NULL; + + i = j = len - 1; + while ((i >= 0) && (maxcount-- > 0)) { + for (; i >= 0; i--) { + if (s[i] == ch) { + SPLIT_ADD(s, i + 1, j + 1); + j = i = i - 1; + break; + } + } + } + if (i < 0 && count == 0 && PyBytes_CheckExact(self)) { + /* ch not in self, so just use self as list[0] */ + Py_INCREF(self); + PyList_SET_ITEM(list, 0, (PyObject *)self); + count++; + } + else if (j >= -1) { + SPLIT_ADD(s, 0, j + 1); + } + FIX_PREALLOC_SIZE(list); + if (PyList_Reverse(list) < 0) + goto onError; + return list; onError: - Py_DECREF(list); - return NULL; + Py_DECREF(list); + return NULL; } PyDoc_STRVAR(rsplit__doc__, @@ -1374,65 +1374,65 @@ static PyObject * bytes_rsplit(PyBytesObject *self, PyObject *args) { - Py_ssize_t len = PyBytes_GET_SIZE(self), n, i, j; - Py_ssize_t maxsplit = -1, count=0; - const char *s, *sub; - Py_buffer vsub; - PyObject *list, *str, *subobj = Py_None; - - if (!PyArg_ParseTuple(args, "|On:rsplit", &subobj, &maxsplit)) - return NULL; - if (maxsplit < 0) - maxsplit = PY_SSIZE_T_MAX; - if (subobj == Py_None) - return rsplit_whitespace(self, len, maxsplit); - if (_getbuffer(subobj, &vsub) < 0) - return NULL; - sub = vsub.buf; - n = vsub.len; - - if (n == 0) { - PyErr_SetString(PyExc_ValueError, "empty separator"); - PyBuffer_Release(&vsub); - return NULL; - } - else if (n == 1) { - list = rsplit_char(self, len, sub[0], maxsplit); - PyBuffer_Release(&vsub); - return list; - } - - list = PyList_New(PREALLOC_SIZE(maxsplit)); - if (list == NULL) { - PyBuffer_Release(&vsub); - return NULL; - } - - j = len; - i = j - n; - - s = PyBytes_AS_STRING(self); - while ( (i >= 0) && (maxsplit-- > 0) ) { - for (; i>=0; i--) { - if (Py_STRING_MATCH(s, i, sub, n)) { - SPLIT_ADD(s, i + n, j); - j = i; - i -= n; - break; - } - } - } - SPLIT_ADD(s, 0, j); - FIX_PREALLOC_SIZE(list); - if (PyList_Reverse(list) < 0) - goto onError; - PyBuffer_Release(&vsub); - return list; + Py_ssize_t len = PyBytes_GET_SIZE(self), n, i, j; + Py_ssize_t maxsplit = -1, count=0; + const char *s, *sub; + Py_buffer vsub; + PyObject *list, *str, *subobj = Py_None; + + if (!PyArg_ParseTuple(args, "|On:rsplit", &subobj, &maxsplit)) + return NULL; + if (maxsplit < 0) + maxsplit = PY_SSIZE_T_MAX; + if (subobj == Py_None) + return rsplit_whitespace(self, len, maxsplit); + if (_getbuffer(subobj, &vsub) < 0) + return NULL; + sub = vsub.buf; + n = vsub.len; + + if (n == 0) { + PyErr_SetString(PyExc_ValueError, "empty separator"); + PyBuffer_Release(&vsub); + return NULL; + } + else if (n == 1) { + list = rsplit_char(self, len, sub[0], maxsplit); + PyBuffer_Release(&vsub); + return list; + } + + list = PyList_New(PREALLOC_SIZE(maxsplit)); + if (list == NULL) { + PyBuffer_Release(&vsub); + return NULL; + } + + j = len; + i = j - n; + + s = PyBytes_AS_STRING(self); + while ( (i >= 0) && (maxsplit-- > 0) ) { + for (; i>=0; i--) { + if (Py_STRING_MATCH(s, i, sub, n)) { + SPLIT_ADD(s, i + n, j); + j = i; + i -= n; + break; + } + } + } + SPLIT_ADD(s, 0, j); + FIX_PREALLOC_SIZE(list); + if (PyList_Reverse(list) < 0) + goto onError; + PyBuffer_Release(&vsub); + return list; onError: - Py_DECREF(list); - PyBuffer_Release(&vsub); - return NULL; + Py_DECREF(list); + PyBuffer_Release(&vsub); + return NULL; } #undef SPLIT_ADD @@ -1449,156 +1449,156 @@ static PyObject * bytes_join(PyObject *self, PyObject *orig) { - char *sep = PyBytes_AS_STRING(self); - const Py_ssize_t seplen = PyBytes_GET_SIZE(self); - PyObject *res = NULL; - char *p; - Py_ssize_t seqlen = 0; - size_t sz = 0; - Py_ssize_t i; - PyObject *seq, *item; - - seq = PySequence_Fast(orig, ""); - if (seq == NULL) { - return NULL; - } - - seqlen = PySequence_Size(seq); - if (seqlen == 0) { - Py_DECREF(seq); - return PyBytes_FromString(""); - } - if (seqlen == 1) { - item = PySequence_Fast_GET_ITEM(seq, 0); - if (PyBytes_CheckExact(item)) { - Py_INCREF(item); - Py_DECREF(seq); - return item; - } - } - - /* There are at least two things to join, or else we have a subclass - * of the builtin types in the sequence. - * Do a pre-pass to figure out the total amount of space we'll - * need (sz), and see whether all argument are bytes. - */ - /* XXX Shouldn't we use _getbuffer() on these items instead? */ - for (i = 0; i < seqlen; i++) { - const size_t old_sz = sz; - item = PySequence_Fast_GET_ITEM(seq, i); - if (!PyBytes_Check(item) && !PyByteArray_Check(item)) { - PyErr_Format(PyExc_TypeError, - "sequence item %zd: expected bytes," - " %.80s found", - i, Py_TYPE(item)->tp_name); - Py_DECREF(seq); - return NULL; - } - sz += Py_SIZE(item); - if (i != 0) - sz += seplen; - if (sz < old_sz || sz > PY_SSIZE_T_MAX) { - PyErr_SetString(PyExc_OverflowError, - "join() result is too long for bytes"); - Py_DECREF(seq); - return NULL; - } - } - - /* Allocate result space. */ - res = PyBytes_FromStringAndSize((char*)NULL, sz); - if (res == NULL) { - Py_DECREF(seq); - return NULL; - } - - /* Catenate everything. */ - /* I'm not worried about a PyByteArray item growing because there's - nowhere in this function where we release the GIL. */ - p = PyBytes_AS_STRING(res); - for (i = 0; i < seqlen; ++i) { - size_t n; - char *q; - if (i) { - Py_MEMCPY(p, sep, seplen); - p += seplen; - } - item = PySequence_Fast_GET_ITEM(seq, i); - n = Py_SIZE(item); - if (PyBytes_Check(item)) - q = PyBytes_AS_STRING(item); - else - q = PyByteArray_AS_STRING(item); - Py_MEMCPY(p, q, n); - p += n; - } + char *sep = PyBytes_AS_STRING(self); + const Py_ssize_t seplen = PyBytes_GET_SIZE(self); + PyObject *res = NULL; + char *p; + Py_ssize_t seqlen = 0; + size_t sz = 0; + Py_ssize_t i; + PyObject *seq, *item; + + seq = PySequence_Fast(orig, ""); + if (seq == NULL) { + return NULL; + } + + seqlen = PySequence_Size(seq); + if (seqlen == 0) { + Py_DECREF(seq); + return PyBytes_FromString(""); + } + if (seqlen == 1) { + item = PySequence_Fast_GET_ITEM(seq, 0); + if (PyBytes_CheckExact(item)) { + Py_INCREF(item); + Py_DECREF(seq); + return item; + } + } + + /* There are at least two things to join, or else we have a subclass + * of the builtin types in the sequence. + * Do a pre-pass to figure out the total amount of space we'll + * need (sz), and see whether all argument are bytes. + */ + /* XXX Shouldn't we use _getbuffer() on these items instead? */ + for (i = 0; i < seqlen; i++) { + const size_t old_sz = sz; + item = PySequence_Fast_GET_ITEM(seq, i); + if (!PyBytes_Check(item) && !PyByteArray_Check(item)) { + PyErr_Format(PyExc_TypeError, + "sequence item %zd: expected bytes," + " %.80s found", + i, Py_TYPE(item)->tp_name); + Py_DECREF(seq); + return NULL; + } + sz += Py_SIZE(item); + if (i != 0) + sz += seplen; + if (sz < old_sz || sz > PY_SSIZE_T_MAX) { + PyErr_SetString(PyExc_OverflowError, + "join() result is too long for bytes"); + Py_DECREF(seq); + return NULL; + } + } + + /* Allocate result space. */ + res = PyBytes_FromStringAndSize((char*)NULL, sz); + if (res == NULL) { + Py_DECREF(seq); + return NULL; + } + + /* Catenate everything. */ + /* I'm not worried about a PyByteArray item growing because there's + nowhere in this function where we release the GIL. */ + p = PyBytes_AS_STRING(res); + for (i = 0; i < seqlen; ++i) { + size_t n; + char *q; + if (i) { + Py_MEMCPY(p, sep, seplen); + p += seplen; + } + item = PySequence_Fast_GET_ITEM(seq, i); + n = Py_SIZE(item); + if (PyBytes_Check(item)) + q = PyBytes_AS_STRING(item); + else + q = PyByteArray_AS_STRING(item); + Py_MEMCPY(p, q, n); + p += n; + } - Py_DECREF(seq); - return res; + Py_DECREF(seq); + return res; } PyObject * _PyBytes_Join(PyObject *sep, PyObject *x) { - assert(sep != NULL && PyBytes_Check(sep)); - assert(x != NULL); - return bytes_join(sep, x); + assert(sep != NULL && PyBytes_Check(sep)); + assert(x != NULL); + return bytes_join(sep, x); } Py_LOCAL_INLINE(void) bytes_adjust_indices(Py_ssize_t *start, Py_ssize_t *end, Py_ssize_t len) { - if (*end > len) - *end = len; - else if (*end < 0) - *end += len; - if (*end < 0) - *end = 0; - if (*start < 0) - *start += len; - if (*start < 0) - *start = 0; + if (*end > len) + *end = len; + else if (*end < 0) + *end += len; + if (*end < 0) + *end = 0; + if (*start < 0) + *start += len; + if (*start < 0) + *start = 0; } Py_LOCAL_INLINE(Py_ssize_t) bytes_find_internal(PyBytesObject *self, PyObject *args, int dir) { - PyObject *subobj; - const char *sub; - Py_ssize_t sub_len; - Py_ssize_t start=0, end=PY_SSIZE_T_MAX; - PyObject *obj_start=Py_None, *obj_end=Py_None; - - if (!PyArg_ParseTuple(args, "O|OO:find/rfind/index/rindex", &subobj, - &obj_start, &obj_end)) - return -2; - /* To support None in "start" and "end" arguments, meaning - the same as if they were not passed. - */ - if (obj_start != Py_None) - if (!_PyEval_SliceIndex(obj_start, &start)) - return -2; - if (obj_end != Py_None) - if (!_PyEval_SliceIndex(obj_end, &end)) - return -2; - - if (PyBytes_Check(subobj)) { - sub = PyBytes_AS_STRING(subobj); - sub_len = PyBytes_GET_SIZE(subobj); - } - else if (PyObject_AsCharBuffer(subobj, &sub, &sub_len)) - /* XXX - the "expected a character buffer object" is pretty - confusing for a non-expert. remap to something else ? */ - return -2; - - if (dir > 0) - return stringlib_find_slice( - PyBytes_AS_STRING(self), PyBytes_GET_SIZE(self), - sub, sub_len, start, end); - else - return stringlib_rfind_slice( - PyBytes_AS_STRING(self), PyBytes_GET_SIZE(self), - sub, sub_len, start, end); + PyObject *subobj; + const char *sub; + Py_ssize_t sub_len; + Py_ssize_t start=0, end=PY_SSIZE_T_MAX; + PyObject *obj_start=Py_None, *obj_end=Py_None; + + if (!PyArg_ParseTuple(args, "O|OO:find/rfind/index/rindex", &subobj, + &obj_start, &obj_end)) + return -2; + /* To support None in "start" and "end" arguments, meaning + the same as if they were not passed. + */ + if (obj_start != Py_None) + if (!_PyEval_SliceIndex(obj_start, &start)) + return -2; + if (obj_end != Py_None) + if (!_PyEval_SliceIndex(obj_end, &end)) + return -2; + + if (PyBytes_Check(subobj)) { + sub = PyBytes_AS_STRING(subobj); + sub_len = PyBytes_GET_SIZE(subobj); + } + else if (PyObject_AsCharBuffer(subobj, &sub, &sub_len)) + /* XXX - the "expected a character buffer object" is pretty + confusing for a non-expert. remap to something else ? */ + return -2; + + if (dir > 0) + return stringlib_find_slice( + PyBytes_AS_STRING(self), PyBytes_GET_SIZE(self), + sub, sub_len, start, end); + else + return stringlib_rfind_slice( + PyBytes_AS_STRING(self), PyBytes_GET_SIZE(self), + sub, sub_len, start, end); } @@ -1614,10 +1614,10 @@ static PyObject * bytes_find(PyBytesObject *self, PyObject *args) { - Py_ssize_t result = bytes_find_internal(self, args, +1); - if (result == -2) - return NULL; - return PyLong_FromSsize_t(result); + Py_ssize_t result = bytes_find_internal(self, args, +1); + if (result == -2) + return NULL; + return PyLong_FromSsize_t(result); } @@ -1629,15 +1629,15 @@ static PyObject * bytes_index(PyBytesObject *self, PyObject *args) { - Py_ssize_t result = bytes_find_internal(self, args, +1); - if (result == -2) - return NULL; - if (result == -1) { - PyErr_SetString(PyExc_ValueError, - "substring not found"); - return NULL; - } - return PyLong_FromSsize_t(result); + Py_ssize_t result = bytes_find_internal(self, args, +1); + if (result == -2) + return NULL; + if (result == -1) { + PyErr_SetString(PyExc_ValueError, + "substring not found"); + return NULL; + } + return PyLong_FromSsize_t(result); } @@ -1653,10 +1653,10 @@ static PyObject * bytes_rfind(PyBytesObject *self, PyObject *args) { - Py_ssize_t result = bytes_find_internal(self, args, -1); - if (result == -2) - return NULL; - return PyLong_FromSsize_t(result); + Py_ssize_t result = bytes_find_internal(self, args, -1); + if (result == -2) + return NULL; + return PyLong_FromSsize_t(result); } @@ -1668,101 +1668,101 @@ static PyObject * bytes_rindex(PyBytesObject *self, PyObject *args) { - Py_ssize_t result = bytes_find_internal(self, args, -1); - if (result == -2) - return NULL; - if (result == -1) { - PyErr_SetString(PyExc_ValueError, - "substring not found"); - return NULL; - } - return PyLong_FromSsize_t(result); + Py_ssize_t result = bytes_find_internal(self, args, -1); + if (result == -2) + return NULL; + if (result == -1) { + PyErr_SetString(PyExc_ValueError, + "substring not found"); + return NULL; + } + return PyLong_FromSsize_t(result); } 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 (_getbuffer(sepobj, &vsep) < 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_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 (_getbuffer(sepobj, &vsep) < 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; + char *s = PyBytes_AS_STRING(self); + Py_ssize_t len = PyBytes_GET_SIZE(self), i, j; + + i = 0; + if (striptype != RIGHTSTRIP) { + while (i < len && ISSPACE(s[i])) { + i++; + } + } + + j = len; + if (striptype != LEFTSTRIP) { + do { + j--; + } while (j >= i && ISSPACE(s[j])); + j++; + } - i = 0; - if (striptype != RIGHTSTRIP) { - while (i < len && ISSPACE(s[i])) { - i++; - } - } - - j = len; - if (striptype != LEFTSTRIP) { - do { - j--; - } while (j >= i && 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); + 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 *args) { - PyObject *sep = NULL; + PyObject *sep = NULL; - if (!PyArg_ParseTuple(args, (char *)stripformat[striptype], &sep)) - return NULL; + if (!PyArg_ParseTuple(args, (char *)stripformat[striptype], &sep)) + return NULL; - if (sep != NULL && sep != Py_None) { - return do_xstrip(self, striptype, sep); - } - return do_strip(self, striptype); + if (sep != NULL && sep != Py_None) { + return do_xstrip(self, striptype, sep); + } + return do_strip(self, striptype); } @@ -1774,10 +1774,10 @@ static PyObject * bytes_strip(PyBytesObject *self, PyObject *args) { - if (PyTuple_GET_SIZE(args) == 0) - return do_strip(self, BOTHSTRIP); /* Common case */ - else - return do_argstrip(self, BOTHSTRIP, args); + if (PyTuple_GET_SIZE(args) == 0) + return do_strip(self, BOTHSTRIP); /* Common case */ + else + return do_argstrip(self, BOTHSTRIP, args); } @@ -1789,10 +1789,10 @@ static PyObject * bytes_lstrip(PyBytesObject *self, PyObject *args) { - if (PyTuple_GET_SIZE(args) == 0) - return do_strip(self, LEFTSTRIP); /* Common case */ - else - return do_argstrip(self, LEFTSTRIP, args); + if (PyTuple_GET_SIZE(args) == 0) + return do_strip(self, LEFTSTRIP); /* Common case */ + else + return do_argstrip(self, LEFTSTRIP, args); } @@ -1804,10 +1804,10 @@ static PyObject * bytes_rstrip(PyBytesObject *self, PyObject *args) { - if (PyTuple_GET_SIZE(args) == 0) - return do_strip(self, RIGHTSTRIP); /* Common case */ - else - return do_argstrip(self, RIGHTSTRIP, args); + if (PyTuple_GET_SIZE(args) == 0) + return do_strip(self, RIGHTSTRIP); /* Common case */ + else + return do_argstrip(self, RIGHTSTRIP, args); } @@ -1821,27 +1821,27 @@ static PyObject * bytes_count(PyBytesObject *self, PyObject *args) { - PyObject *sub_obj; - const char *str = PyBytes_AS_STRING(self), *sub; - Py_ssize_t sub_len; - Py_ssize_t start = 0, end = PY_SSIZE_T_MAX; - - if (!PyArg_ParseTuple(args, "O|O&O&:count", &sub_obj, - _PyEval_SliceIndex, &start, _PyEval_SliceIndex, &end)) - return NULL; - - if (PyBytes_Check(sub_obj)) { - sub = PyBytes_AS_STRING(sub_obj); - sub_len = PyBytes_GET_SIZE(sub_obj); - } - else if (PyObject_AsCharBuffer(sub_obj, &sub, &sub_len)) - return NULL; - - bytes_adjust_indices(&start, &end, PyBytes_GET_SIZE(self)); - - return PyLong_FromSsize_t( - stringlib_count(str + start, end - start, sub, sub_len) - ); + PyObject *sub_obj; + const char *str = PyBytes_AS_STRING(self), *sub; + Py_ssize_t sub_len; + Py_ssize_t start = 0, end = PY_SSIZE_T_MAX; + + if (!PyArg_ParseTuple(args, "O|O&O&:count", &sub_obj, + _PyEval_SliceIndex, &start, _PyEval_SliceIndex, &end)) + return NULL; + + if (PyBytes_Check(sub_obj)) { + sub = PyBytes_AS_STRING(sub_obj); + sub_len = PyBytes_GET_SIZE(sub_obj); + } + else if (PyObject_AsCharBuffer(sub_obj, &sub, &sub_len)) + return NULL; + + bytes_adjust_indices(&start, &end, PyBytes_GET_SIZE(self)); + + return PyLong_FromSsize_t( + stringlib_count(str + start, end - start, sub, sub_len) + ); } @@ -1856,105 +1856,105 @@ static PyObject * bytes_translate(PyBytesObject *self, PyObject *args) { - register char *input, *output; - const char *table; - register Py_ssize_t i, c, changed = 0; - PyObject *input_obj = (PyObject*)self; - const char *output_start, *del_table=NULL; - Py_ssize_t inlen, tablen, dellen = 0; - PyObject *result; - int trans_table[256]; - PyObject *tableobj, *delobj = NULL; - - if (!PyArg_UnpackTuple(args, "translate", 1, 2, - &tableobj, &delobj)) - return NULL; - - if (PyBytes_Check(tableobj)) { - table = PyBytes_AS_STRING(tableobj); - tablen = PyBytes_GET_SIZE(tableobj); - } - else if (tableobj == Py_None) { - table = NULL; - tablen = 256; - } - else if (PyObject_AsCharBuffer(tableobj, &table, &tablen)) - return NULL; - - if (tablen != 256) { - PyErr_SetString(PyExc_ValueError, - "translation table must be 256 characters long"); - return NULL; - } - - if (delobj != NULL) { - if (PyBytes_Check(delobj)) { - del_table = PyBytes_AS_STRING(delobj); - dellen = PyBytes_GET_SIZE(delobj); - } - else if (PyObject_AsCharBuffer(delobj, &del_table, &dellen)) - return NULL; - } - else { - del_table = NULL; - dellen = 0; - } - - inlen = PyBytes_GET_SIZE(input_obj); - result = PyBytes_FromStringAndSize((char *)NULL, inlen); - if (result == NULL) - return NULL; - output_start = output = PyBytes_AsString(result); - input = PyBytes_AS_STRING(input_obj); - - if (dellen == 0 && table != NULL) { - /* If no deletions are required, use faster code */ - for (i = inlen; --i >= 0; ) { - c = Py_CHARMASK(*input++); - if (Py_CHARMASK((*output++ = table[c])) != c) - changed = 1; - } - if (changed || !PyBytes_CheckExact(input_obj)) - return result; - Py_DECREF(result); - Py_INCREF(input_obj); - return input_obj; - } - - if (table == 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[i]); - } - - for (i = 0; i < dellen; i++) - trans_table[(int) Py_CHARMASK(del_table[i])] = -1; - - 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; + register char *input, *output; + const char *table; + register Py_ssize_t i, c, changed = 0; + PyObject *input_obj = (PyObject*)self; + const char *output_start, *del_table=NULL; + Py_ssize_t inlen, tablen, dellen = 0; + PyObject *result; + int trans_table[256]; + PyObject *tableobj, *delobj = NULL; + + if (!PyArg_UnpackTuple(args, "translate", 1, 2, + &tableobj, &delobj)) + return NULL; + + if (PyBytes_Check(tableobj)) { + table = PyBytes_AS_STRING(tableobj); + tablen = PyBytes_GET_SIZE(tableobj); + } + else if (tableobj == Py_None) { + table = NULL; + tablen = 256; + } + else if (PyObject_AsCharBuffer(tableobj, &table, &tablen)) + return NULL; + + if (tablen != 256) { + PyErr_SetString(PyExc_ValueError, + "translation table must be 256 characters long"); + return NULL; + } + + if (delobj != NULL) { + if (PyBytes_Check(delobj)) { + del_table = PyBytes_AS_STRING(delobj); + dellen = PyBytes_GET_SIZE(delobj); + } + else if (PyObject_AsCharBuffer(delobj, &del_table, &dellen)) + return NULL; + } + else { + del_table = NULL; + dellen = 0; + } + + inlen = PyBytes_GET_SIZE(input_obj); + result = PyBytes_FromStringAndSize((char *)NULL, inlen); + if (result == NULL) + return NULL; + output_start = output = PyBytes_AsString(result); + input = PyBytes_AS_STRING(input_obj); + + if (dellen == 0 && table != NULL) { + /* If no deletions are required, use faster code */ + for (i = inlen; --i >= 0; ) { + c = Py_CHARMASK(*input++); + if (Py_CHARMASK((*output++ = table[c])) != c) + changed = 1; + } + if (changed || !PyBytes_CheckExact(input_obj)) + return result; + Py_DECREF(result); + Py_INCREF(input_obj); + return input_obj; + } + + if (table == 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[i]); + } + + for (i = 0; i < dellen; i++) + trans_table[(int) Py_CHARMASK(del_table[i])] = -1; + + 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; } static PyObject * bytes_maketrans(PyObject *null, PyObject *args) { - return _Py_bytes_maketrans(args); + return _Py_bytes_maketrans(args); } #define FORWARD 1 @@ -1962,7 +1962,7 @@ /* find and count characters and substrings */ -#define findchar(target, target_len, c) \ +#define findchar(target, target_len, c) \ ((char *)memchr((const void *)(target), c, target_len)) /* String ops must return a string. */ @@ -1970,117 +1970,117 @@ Py_LOCAL(PyBytesObject *) return_self(PyBytesObject *self) { - if (PyBytes_CheckExact(self)) { - Py_INCREF(self); - return self; - } - return (PyBytesObject *)PyBytes_FromStringAndSize( - PyBytes_AS_STRING(self), - PyBytes_GET_SIZE(self)); + if (PyBytes_CheckExact(self)) { + Py_INCREF(self); + return self; + } + return (PyBytesObject *)PyBytes_FromStringAndSize( + PyBytes_AS_STRING(self), + PyBytes_GET_SIZE(self)); } Py_LOCAL_INLINE(Py_ssize_t) countchar(const char *target, int target_len, char c, Py_ssize_t maxcount) { - Py_ssize_t count=0; - const char *start=target; - const char *end=target+target_len; - - while ( (start=findchar(start, end-start, c)) != NULL ) { - count++; - if (count >= maxcount) - break; - start += 1; - } - return count; + Py_ssize_t count=0; + const char *start=target; + const char *end=target+target_len; + + while ( (start=findchar(start, end-start, c)) != NULL ) { + count++; + if (count >= maxcount) + break; + start += 1; + } + return count; } Py_LOCAL(Py_ssize_t) findstring(const char *target, Py_ssize_t target_len, - const char *pattern, Py_ssize_t pattern_len, - Py_ssize_t start, - Py_ssize_t end, - int direction) -{ - if (start < 0) { - start += target_len; - if (start < 0) - start = 0; - } - if (end > target_len) { - end = target_len; - } else if (end < 0) { - end += target_len; - if (end < 0) - end = 0; - } - - /* zero-length substrings always match at the first attempt */ - if (pattern_len == 0) - return (direction > 0) ? start : end; - - end -= pattern_len; - - if (direction < 0) { - for (; end >= start; end--) - if (Py_STRING_MATCH(target, end, pattern, pattern_len)) - return end; - } else { - for (; start <= end; start++) - if (Py_STRING_MATCH(target, start,pattern,pattern_len)) - return start; - } - return -1; + const char *pattern, Py_ssize_t pattern_len, + Py_ssize_t start, + Py_ssize_t end, + int direction) +{ + if (start < 0) { + start += target_len; + if (start < 0) + start = 0; + } + if (end > target_len) { + end = target_len; + } else if (end < 0) { + end += target_len; + if (end < 0) + end = 0; + } + + /* zero-length substrings always match at the first attempt */ + if (pattern_len == 0) + return (direction > 0) ? start : end; + + end -= pattern_len; + + if (direction < 0) { + for (; end >= start; end--) + if (Py_STRING_MATCH(target, end, pattern, pattern_len)) + return end; + } else { + for (; start <= end; start++) + if (Py_STRING_MATCH(target, start,pattern,pattern_len)) + return start; + } + return -1; } Py_LOCAL_INLINE(Py_ssize_t) countstring(const char *target, Py_ssize_t target_len, - const char *pattern, Py_ssize_t pattern_len, - Py_ssize_t start, - Py_ssize_t end, - int direction, Py_ssize_t maxcount) -{ - Py_ssize_t count=0; - - if (start < 0) { - start += target_len; - if (start < 0) - start = 0; - } - if (end > target_len) { - end = target_len; - } else if (end < 0) { - end += target_len; - if (end < 0) - end = 0; - } - - /* zero-length substrings match everywhere */ - if (pattern_len == 0 || maxcount == 0) { - if (target_len+1 < maxcount) - return target_len+1; - return maxcount; - } - - end -= pattern_len; - if (direction < 0) { - for (; (end >= start); end--) - if (Py_STRING_MATCH(target, end,pattern,pattern_len)) { - count++; - if (--maxcount <= 0) break; - end -= pattern_len-1; - } - } else { - for (; (start <= end); start++) - if (Py_STRING_MATCH(target, start, - pattern, pattern_len)) { - count++; - if (--maxcount <= 0) - break; - start += pattern_len-1; - } - } - return count; + const char *pattern, Py_ssize_t pattern_len, + Py_ssize_t start, + Py_ssize_t end, + int direction, Py_ssize_t maxcount) +{ + Py_ssize_t count=0; + + if (start < 0) { + start += target_len; + if (start < 0) + start = 0; + } + if (end > target_len) { + end = target_len; + } else if (end < 0) { + end += target_len; + if (end < 0) + end = 0; + } + + /* zero-length substrings match everywhere */ + if (pattern_len == 0 || maxcount == 0) { + if (target_len+1 < maxcount) + return target_len+1; + return maxcount; + } + + end -= pattern_len; + if (direction < 0) { + for (; (end >= start); end--) + if (Py_STRING_MATCH(target, end,pattern,pattern_len)) { + count++; + if (--maxcount <= 0) break; + end -= pattern_len-1; + } + } else { + for (; (start <= end); start++) + if (Py_STRING_MATCH(target, start, + pattern, pattern_len)) { + count++; + if (--maxcount <= 0) + break; + start += pattern_len-1; + } + } + return count; } @@ -2089,467 +2089,467 @@ /* len(self)>=1, from="", len(to)>=1, maxcount>=1 */ Py_LOCAL(PyBytesObject *) replace_interleave(PyBytesObject *self, - const char *to_s, Py_ssize_t to_len, - Py_ssize_t maxcount) + const char *to_s, Py_ssize_t to_len, + Py_ssize_t maxcount) { - char *self_s, *result_s; - Py_ssize_t self_len, result_len; - Py_ssize_t count, i, product; - PyBytesObject *result; - - self_len = PyBytes_GET_SIZE(self); - - /* 1 at the end plus 1 after every character */ - count = self_len+1; - if (maxcount < count) - count = maxcount; - - /* Check for overflow */ - /* result_len = count * to_len + self_len; */ - product = count * to_len; - if (product / to_len != count) { - PyErr_SetString(PyExc_OverflowError, - "replacement bytes are too long"); - return NULL; - } - result_len = product + self_len; - if (result_len < 0) { - PyErr_SetString(PyExc_OverflowError, - "replacement bytes are too long"); - return NULL; - } - - if (! (result = (PyBytesObject *) - PyBytes_FromStringAndSize(NULL, result_len)) ) - return NULL; - - self_s = PyBytes_AS_STRING(self); - result_s = PyBytes_AS_STRING(result); - - /* TODO: special case single character, which doesn't need memcpy */ - - /* Lay the first one down (guaranteed this will occur) */ - Py_MEMCPY(result_s, to_s, to_len); - result_s += to_len; - count -= 1; - - for (i=0; i=1, len(from)==1, to="", maxcount>=1 */ Py_LOCAL(PyBytesObject *) replace_delete_single_character(PyBytesObject *self, - char from_c, Py_ssize_t maxcount) + char from_c, Py_ssize_t maxcount) { - char *self_s, *result_s; - char *start, *next, *end; - Py_ssize_t self_len, result_len; - Py_ssize_t count; - PyBytesObject *result; - - self_len = PyBytes_GET_SIZE(self); - self_s = PyBytes_AS_STRING(self); - - count = countchar(self_s, self_len, from_c, maxcount); - if (count == 0) { - return return_self(self); - } - - result_len = self_len - count; /* from_len == 1 */ - assert(result_len>=0); - - if ( (result = (PyBytesObject *) - PyBytes_FromStringAndSize(NULL, result_len)) == NULL) - return NULL; - result_s = PyBytes_AS_STRING(result); - - start = self_s; - end = self_s + self_len; - while (count-- > 0) { - next = findchar(start, end-start, from_c); - if (next == NULL) - break; - Py_MEMCPY(result_s, start, next-start); - result_s += (next-start); - start = next+1; - } - Py_MEMCPY(result_s, start, end-start); + char *self_s, *result_s; + char *start, *next, *end; + Py_ssize_t self_len, result_len; + Py_ssize_t count; + PyBytesObject *result; + + self_len = PyBytes_GET_SIZE(self); + self_s = PyBytes_AS_STRING(self); + + count = countchar(self_s, self_len, from_c, maxcount); + if (count == 0) { + return return_self(self); + } + + result_len = self_len - count; /* from_len == 1 */ + assert(result_len>=0); + + if ( (result = (PyBytesObject *) + PyBytes_FromStringAndSize(NULL, result_len)) == NULL) + return NULL; + result_s = PyBytes_AS_STRING(result); + + start = self_s; + end = self_s + self_len; + while (count-- > 0) { + next = findchar(start, end-start, from_c); + if (next == NULL) + break; + Py_MEMCPY(result_s, start, next-start); + result_s += (next-start); + start = next+1; + } + Py_MEMCPY(result_s, start, end-start); - return result; + return result; } /* len(self)>=1, len(from)>=2, to="", maxcount>=1 */ Py_LOCAL(PyBytesObject *) replace_delete_substring(PyBytesObject *self, - const char *from_s, Py_ssize_t from_len, - Py_ssize_t maxcount) { - char *self_s, *result_s; - char *start, *next, *end; - Py_ssize_t self_len, result_len; - Py_ssize_t count, offset; - PyBytesObject *result; - - self_len = PyBytes_GET_SIZE(self); - self_s = PyBytes_AS_STRING(self); - - count = countstring(self_s, self_len, - from_s, from_len, - 0, self_len, 1, - maxcount); - - if (count == 0) { - /* no matches */ - return return_self(self); - } - - result_len = self_len - (count * from_len); - assert (result_len>=0); - - if ( (result = (PyBytesObject *) - PyBytes_FromStringAndSize(NULL, result_len)) == NULL ) - return NULL; - - result_s = PyBytes_AS_STRING(result); - - start = self_s; - end = self_s + self_len; - while (count-- > 0) { - offset = findstring(start, end-start, - from_s, from_len, - 0, end-start, FORWARD); - if (offset == -1) - break; - next = start + offset; - - Py_MEMCPY(result_s, start, next-start); - - result_s += (next-start); - start = next+from_len; - } - Py_MEMCPY(result_s, start, end-start); - return result; + const char *from_s, Py_ssize_t from_len, + Py_ssize_t maxcount) { + char *self_s, *result_s; + char *start, *next, *end; + Py_ssize_t self_len, result_len; + Py_ssize_t count, offset; + PyBytesObject *result; + + self_len = PyBytes_GET_SIZE(self); + self_s = PyBytes_AS_STRING(self); + + count = countstring(self_s, self_len, + from_s, from_len, + 0, self_len, 1, + maxcount); + + if (count == 0) { + /* no matches */ + return return_self(self); + } + + result_len = self_len - (count * from_len); + assert (result_len>=0); + + if ( (result = (PyBytesObject *) + PyBytes_FromStringAndSize(NULL, result_len)) == NULL ) + return NULL; + + result_s = PyBytes_AS_STRING(result); + + start = self_s; + end = self_s + self_len; + while (count-- > 0) { + offset = findstring(start, end-start, + from_s, from_len, + 0, end-start, FORWARD); + if (offset == -1) + break; + next = start + offset; + + Py_MEMCPY(result_s, start, next-start); + + result_s += (next-start); + start = next+from_len; + } + Py_MEMCPY(result_s, start, end-start); + return result; } /* len(self)>=1, len(from)==len(to)==1, maxcount>=1 */ Py_LOCAL(PyBytesObject *) replace_single_character_in_place(PyBytesObject *self, - char from_c, char to_c, - Py_ssize_t maxcount) + char from_c, char to_c, + Py_ssize_t maxcount) { - char *self_s, *result_s, *start, *end, *next; - Py_ssize_t self_len; - PyBytesObject *result; - - /* The result string will be the same size */ - self_s = PyBytes_AS_STRING(self); - self_len = PyBytes_GET_SIZE(self); - - next = findchar(self_s, self_len, from_c); - - if (next == NULL) { - /* No matches; return the original string */ - return return_self(self); - } - - /* Need to make a new string */ - result = (PyBytesObject *) PyBytes_FromStringAndSize(NULL, self_len); - if (result == NULL) - return NULL; - result_s = PyBytes_AS_STRING(result); - Py_MEMCPY(result_s, self_s, self_len); - - /* change everything in-place, starting with this one */ - start = result_s + (next-self_s); - *start = to_c; - start++; - end = result_s + self_len; - - while (--maxcount > 0) { - next = findchar(start, end-start, from_c); - if (next == NULL) - break; - *next = to_c; - start = next+1; - } + char *self_s, *result_s, *start, *end, *next; + Py_ssize_t self_len; + PyBytesObject *result; + + /* The result string will be the same size */ + self_s = PyBytes_AS_STRING(self); + self_len = PyBytes_GET_SIZE(self); + + next = findchar(self_s, self_len, from_c); + + if (next == NULL) { + /* No matches; return the original string */ + return return_self(self); + } + + /* Need to make a new string */ + result = (PyBytesObject *) PyBytes_FromStringAndSize(NULL, self_len); + if (result == NULL) + return NULL; + result_s = PyBytes_AS_STRING(result); + Py_MEMCPY(result_s, self_s, self_len); + + /* change everything in-place, starting with this one */ + start = result_s + (next-self_s); + *start = to_c; + start++; + end = result_s + self_len; + + while (--maxcount > 0) { + next = findchar(start, end-start, from_c); + if (next == NULL) + break; + *next = to_c; + start = next+1; + } - return result; + return result; } /* len(self)>=1, len(from)==len(to)>=2, maxcount>=1 */ Py_LOCAL(PyBytesObject *) replace_substring_in_place(PyBytesObject *self, - const char *from_s, Py_ssize_t from_len, - const char *to_s, Py_ssize_t to_len, - Py_ssize_t maxcount) -{ - char *result_s, *start, *end; - char *self_s; - Py_ssize_t self_len, offset; - PyBytesObject *result; - - /* The result string will be the same size */ - - self_s = PyBytes_AS_STRING(self); - self_len = PyBytes_GET_SIZE(self); - - offset = findstring(self_s, self_len, - from_s, from_len, - 0, self_len, FORWARD); - if (offset == -1) { - /* No matches; return the original string */ - return return_self(self); - } - - /* Need to make a new string */ - result = (PyBytesObject *) PyBytes_FromStringAndSize(NULL, self_len); - if (result == NULL) - return NULL; - result_s = PyBytes_AS_STRING(result); - Py_MEMCPY(result_s, self_s, self_len); - - /* change everything in-place, starting with this one */ - start = result_s + offset; - Py_MEMCPY(start, to_s, from_len); - start += from_len; - end = result_s + self_len; - - while ( --maxcount > 0) { - offset = findstring(start, end-start, - from_s, from_len, - 0, end-start, FORWARD); - if (offset==-1) - break; - Py_MEMCPY(start+offset, to_s, from_len); - start += offset+from_len; - } + const char *from_s, Py_ssize_t from_len, + const char *to_s, Py_ssize_t to_len, + Py_ssize_t maxcount) +{ + char *result_s, *start, *end; + char *self_s; + Py_ssize_t self_len, offset; + PyBytesObject *result; + + /* The result string will be the same size */ + + self_s = PyBytes_AS_STRING(self); + self_len = PyBytes_GET_SIZE(self); + + offset = findstring(self_s, self_len, + from_s, from_len, + 0, self_len, FORWARD); + if (offset == -1) { + /* No matches; return the original string */ + return return_self(self); + } + + /* Need to make a new string */ + result = (PyBytesObject *) PyBytes_FromStringAndSize(NULL, self_len); + if (result == NULL) + return NULL; + result_s = PyBytes_AS_STRING(result); + Py_MEMCPY(result_s, self_s, self_len); + + /* change everything in-place, starting with this one */ + start = result_s + offset; + Py_MEMCPY(start, to_s, from_len); + start += from_len; + end = result_s + self_len; + + while ( --maxcount > 0) { + offset = findstring(start, end-start, + from_s, from_len, + 0, end-start, FORWARD); + if (offset==-1) + break; + Py_MEMCPY(start+offset, to_s, from_len); + start += offset+from_len; + } - return result; + return result; } /* len(self)>=1, len(from)==1, len(to)>=2, maxcount>=1 */ Py_LOCAL(PyBytesObject *) replace_single_character(PyBytesObject *self, - char from_c, - const char *to_s, Py_ssize_t to_len, - Py_ssize_t maxcount) -{ - char *self_s, *result_s; - char *start, *next, *end; - Py_ssize_t self_len, result_len; - Py_ssize_t count, product; - PyBytesObject *result; - - self_s = PyBytes_AS_STRING(self); - self_len = PyBytes_GET_SIZE(self); - - count = countchar(self_s, self_len, from_c, maxcount); - if (count == 0) { - /* no matches, return unchanged */ - return return_self(self); - } - - /* use the difference between current and new, hence the "-1" */ - /* result_len = self_len + count * (to_len-1) */ - product = count * (to_len-1); - if (product / (to_len-1) != count) { - PyErr_SetString(PyExc_OverflowError, - "replacement bytes are too long"); - return NULL; - } - result_len = self_len + product; - if (result_len < 0) { - PyErr_SetString(PyExc_OverflowError, - "replacment bytes are too long"); - return NULL; - } - - if ( (result = (PyBytesObject *) - PyBytes_FromStringAndSize(NULL, result_len)) == NULL) - return NULL; - result_s = PyBytes_AS_STRING(result); - - start = self_s; - end = self_s + self_len; - while (count-- > 0) { - next = findchar(start, end-start, from_c); - if (next == NULL) - break; - - if (next == start) { - /* replace with the 'to' */ - Py_MEMCPY(result_s, to_s, to_len); - result_s += to_len; - start += 1; - } else { - /* copy the unchanged old then the 'to' */ - Py_MEMCPY(result_s, start, next-start); - result_s += (next-start); - Py_MEMCPY(result_s, to_s, to_len); - result_s += to_len; - start = next+1; - } - } - /* Copy the remainder of the remaining string */ - Py_MEMCPY(result_s, start, end-start); + char from_c, + const char *to_s, Py_ssize_t to_len, + Py_ssize_t maxcount) +{ + char *self_s, *result_s; + char *start, *next, *end; + Py_ssize_t self_len, result_len; + Py_ssize_t count, product; + PyBytesObject *result; + + self_s = PyBytes_AS_STRING(self); + self_len = PyBytes_GET_SIZE(self); + + count = countchar(self_s, self_len, from_c, maxcount); + if (count == 0) { + /* no matches, return unchanged */ + return return_self(self); + } + + /* use the difference between current and new, hence the "-1" */ + /* result_len = self_len + count * (to_len-1) */ + product = count * (to_len-1); + if (product / (to_len-1) != count) { + PyErr_SetString(PyExc_OverflowError, + "replacement bytes are too long"); + return NULL; + } + result_len = self_len + product; + if (result_len < 0) { + PyErr_SetString(PyExc_OverflowError, + "replacment bytes are too long"); + return NULL; + } - return result; + if ( (result = (PyBytesObject *) + PyBytes_FromStringAndSize(NULL, result_len)) == NULL) + return NULL; + result_s = PyBytes_AS_STRING(result); + + start = self_s; + end = self_s + self_len; + while (count-- > 0) { + next = findchar(start, end-start, from_c); + if (next == NULL) + break; + + if (next == start) { + /* replace with the 'to' */ + Py_MEMCPY(result_s, to_s, to_len); + result_s += to_len; + start += 1; + } else { + /* copy the unchanged old then the 'to' */ + Py_MEMCPY(result_s, start, next-start); + result_s += (next-start); + Py_MEMCPY(result_s, to_s, to_len); + result_s += to_len; + start = next+1; + } + } + /* Copy the remainder of the remaining string */ + Py_MEMCPY(result_s, start, end-start); + + return result; } /* len(self)>=1, len(from)>=2, len(to)>=2, maxcount>=1 */ Py_LOCAL(PyBytesObject *) replace_substring(PyBytesObject *self, - const char *from_s, Py_ssize_t from_len, - const char *to_s, Py_ssize_t to_len, - Py_ssize_t maxcount) { - char *self_s, *result_s; - char *start, *next, *end; - Py_ssize_t self_len, result_len; - Py_ssize_t count, offset, product; - PyBytesObject *result; - - self_s = PyBytes_AS_STRING(self); - self_len = PyBytes_GET_SIZE(self); - - count = countstring(self_s, self_len, - from_s, from_len, - 0, self_len, FORWARD, maxcount); - if (count == 0) { - /* no matches, return unchanged */ - return return_self(self); - } - - /* Check for overflow */ - /* result_len = self_len + count * (to_len-from_len) */ - product = count * (to_len-from_len); - if (product / (to_len-from_len) != count) { - PyErr_SetString(PyExc_OverflowError, - "replacement bytes are too long"); - return NULL; - } - result_len = self_len + product; - if (result_len < 0) { - PyErr_SetString(PyExc_OverflowError, - "replacement bytes are too long"); - return NULL; - } - - if ( (result = (PyBytesObject *) - PyBytes_FromStringAndSize(NULL, result_len)) == NULL) - return NULL; - result_s = PyBytes_AS_STRING(result); - - start = self_s; - end = self_s + self_len; - while (count-- > 0) { - offset = findstring(start, end-start, - from_s, from_len, - 0, end-start, FORWARD); - if (offset == -1) - break; - next = start+offset; - if (next == start) { - /* replace with the 'to' */ - Py_MEMCPY(result_s, to_s, to_len); - result_s += to_len; - start += from_len; - } else { - /* copy the unchanged old then the 'to' */ - Py_MEMCPY(result_s, start, next-start); - result_s += (next-start); - Py_MEMCPY(result_s, to_s, to_len); - result_s += to_len; - start = next+from_len; - } - } - /* Copy the remainder of the remaining string */ - Py_MEMCPY(result_s, start, end-start); + const char *from_s, Py_ssize_t from_len, + const char *to_s, Py_ssize_t to_len, + Py_ssize_t maxcount) { + char *self_s, *result_s; + char *start, *next, *end; + Py_ssize_t self_len, result_len; + Py_ssize_t count, offset, product; + PyBytesObject *result; + + self_s = PyBytes_AS_STRING(self); + self_len = PyBytes_GET_SIZE(self); + + count = countstring(self_s, self_len, + from_s, from_len, + 0, self_len, FORWARD, maxcount); + if (count == 0) { + /* no matches, return unchanged */ + return return_self(self); + } + + /* Check for overflow */ + /* result_len = self_len + count * (to_len-from_len) */ + product = count * (to_len-from_len); + if (product / (to_len-from_len) != count) { + PyErr_SetString(PyExc_OverflowError, + "replacement bytes are too long"); + return NULL; + } + result_len = self_len + product; + if (result_len < 0) { + PyErr_SetString(PyExc_OverflowError, + "replacement bytes are too long"); + return NULL; + } + + if ( (result = (PyBytesObject *) + PyBytes_FromStringAndSize(NULL, result_len)) == NULL) + return NULL; + result_s = PyBytes_AS_STRING(result); + + start = self_s; + end = self_s + self_len; + while (count-- > 0) { + offset = findstring(start, end-start, + from_s, from_len, + 0, end-start, FORWARD); + if (offset == -1) + break; + next = start+offset; + if (next == start) { + /* replace with the 'to' */ + Py_MEMCPY(result_s, to_s, to_len); + result_s += to_len; + start += from_len; + } else { + /* copy the unchanged old then the 'to' */ + Py_MEMCPY(result_s, start, next-start); + result_s += (next-start); + Py_MEMCPY(result_s, to_s, to_len); + result_s += to_len; + start = next+from_len; + } + } + /* Copy the remainder of the remaining string */ + Py_MEMCPY(result_s, start, end-start); - return result; + return result; } Py_LOCAL(PyBytesObject *) replace(PyBytesObject *self, - const char *from_s, Py_ssize_t from_len, - const char *to_s, Py_ssize_t to_len, - Py_ssize_t maxcount) -{ - if (maxcount < 0) { - maxcount = PY_SSIZE_T_MAX; - } else if (maxcount == 0 || PyBytes_GET_SIZE(self) == 0) { - /* nothing to do; return the original string */ - return return_self(self); - } - - if (maxcount == 0 || - (from_len == 0 && to_len == 0)) { - /* nothing to do; return the original string */ - return return_self(self); - } - - /* Handle zero-length special cases */ - - if (from_len == 0) { - /* insert the 'to' string everywhere. */ - /* >>> "Python".replace("", ".") */ - /* '.P.y.t.h.o.n.' */ - return replace_interleave(self, to_s, to_len, maxcount); - } - - /* Except for "".replace("", "A") == "A" there is no way beyond this */ - /* point for an empty self string to generate a non-empty string */ - /* Special case so the remaining code always gets a non-empty string */ - if (PyBytes_GET_SIZE(self) == 0) { - return return_self(self); - } - - if (to_len == 0) { - /* delete all occurrences of 'from' string */ - if (from_len == 1) { - return replace_delete_single_character( - self, from_s[0], maxcount); - } else { - return replace_delete_substring(self, from_s, - from_len, maxcount); - } - } - - /* Handle special case where both strings have the same length */ - - if (from_len == to_len) { - if (from_len == 1) { - return replace_single_character_in_place( - self, - from_s[0], - to_s[0], - maxcount); - } else { - return replace_substring_in_place( - self, from_s, from_len, to_s, to_len, - maxcount); - } - } - - /* Otherwise use the more generic algorithms */ - if (from_len == 1) { - return replace_single_character(self, from_s[0], - to_s, to_len, maxcount); - } else { - /* len('from')>=2, len('to')>=1 */ - return replace_substring(self, from_s, from_len, to_s, to_len, - maxcount); - } + const char *from_s, Py_ssize_t from_len, + const char *to_s, Py_ssize_t to_len, + Py_ssize_t maxcount) +{ + if (maxcount < 0) { + maxcount = PY_SSIZE_T_MAX; + } else if (maxcount == 0 || PyBytes_GET_SIZE(self) == 0) { + /* nothing to do; return the original string */ + return return_self(self); + } + + if (maxcount == 0 || + (from_len == 0 && to_len == 0)) { + /* nothing to do; return the original string */ + return return_self(self); + } + + /* Handle zero-length special cases */ + + if (from_len == 0) { + /* insert the 'to' string everywhere. */ + /* >>> "Python".replace("", ".") */ + /* '.P.y.t.h.o.n.' */ + return replace_interleave(self, to_s, to_len, maxcount); + } + + /* Except for "".replace("", "A") == "A" there is no way beyond this */ + /* point for an empty self string to generate a non-empty string */ + /* Special case so the remaining code always gets a non-empty string */ + if (PyBytes_GET_SIZE(self) == 0) { + return return_self(self); + } + + if (to_len == 0) { + /* delete all occurrences of 'from' string */ + if (from_len == 1) { + return replace_delete_single_character( + self, from_s[0], maxcount); + } else { + return replace_delete_substring(self, from_s, + from_len, maxcount); + } + } + + /* Handle special case where both strings have the same length */ + + if (from_len == to_len) { + if (from_len == 1) { + return replace_single_character_in_place( + self, + from_s[0], + to_s[0], + maxcount); + } else { + return replace_substring_in_place( + self, from_s, from_len, to_s, to_len, + maxcount); + } + } + + /* Otherwise use the more generic algorithms */ + if (from_len == 1) { + return replace_single_character(self, from_s[0], + to_s, to_len, maxcount); + } else { + /* len('from')>=2, len('to')>=1 */ + return replace_substring(self, from_s, from_len, to_s, to_len, + maxcount); + } } PyDoc_STRVAR(replace__doc__, @@ -2562,31 +2562,31 @@ static PyObject * bytes_replace(PyBytesObject *self, PyObject *args) { - Py_ssize_t count = -1; - PyObject *from, *to; - const char *from_s, *to_s; - Py_ssize_t from_len, to_len; - - if (!PyArg_ParseTuple(args, "OO|n:replace", &from, &to, &count)) - return NULL; - - if (PyBytes_Check(from)) { - from_s = PyBytes_AS_STRING(from); - from_len = PyBytes_GET_SIZE(from); - } - else if (PyObject_AsCharBuffer(from, &from_s, &from_len)) - return NULL; - - if (PyBytes_Check(to)) { - to_s = PyBytes_AS_STRING(to); - to_len = PyBytes_GET_SIZE(to); - } - else if (PyObject_AsCharBuffer(to, &to_s, &to_len)) - return NULL; - - return (PyObject *)replace((PyBytesObject *) self, - from_s, from_len, - to_s, to_len, count); + Py_ssize_t count = -1; + PyObject *from, *to; + const char *from_s, *to_s; + Py_ssize_t from_len, to_len; + + if (!PyArg_ParseTuple(args, "OO|n:replace", &from, &to, &count)) + return NULL; + + if (PyBytes_Check(from)) { + from_s = PyBytes_AS_STRING(from); + from_len = PyBytes_GET_SIZE(from); + } + else if (PyObject_AsCharBuffer(from, &from_s, &from_len)) + return NULL; + + if (PyBytes_Check(to)) { + to_s = PyBytes_AS_STRING(to); + to_len = PyBytes_GET_SIZE(to); + } + else if (PyObject_AsCharBuffer(to, &to_s, &to_len)) + return NULL; + + return (PyObject *)replace((PyBytesObject *) self, + from_s, from_len, + to_s, to_len, count); } /** End DALKE **/ @@ -2597,38 +2597,38 @@ */ Py_LOCAL(int) _bytes_tailmatch(PyBytesObject *self, PyObject *substr, Py_ssize_t start, - Py_ssize_t end, int direction) + Py_ssize_t end, int direction) { - Py_ssize_t len = PyBytes_GET_SIZE(self); - Py_ssize_t slen; - const char* sub; - const char* str; - - if (PyBytes_Check(substr)) { - sub = PyBytes_AS_STRING(substr); - slen = PyBytes_GET_SIZE(substr); - } - else if (PyObject_AsCharBuffer(substr, &sub, &slen)) - return -1; - str = PyBytes_AS_STRING(self); - - bytes_adjust_indices(&start, &end, len); - - if (direction < 0) { - /* startswith */ - if (start+slen > len) - return 0; - } else { - /* endswith */ - if (end-start < slen || start > len) - return 0; - - if (end-slen > start) - start = end - slen; - } - if (end-start >= slen) - return ! memcmp(str+start, sub, slen); - return 0; + Py_ssize_t len = PyBytes_GET_SIZE(self); + Py_ssize_t slen; + const char* sub; + const char* str; + + if (PyBytes_Check(substr)) { + sub = PyBytes_AS_STRING(substr); + slen = PyBytes_GET_SIZE(substr); + } + else if (PyObject_AsCharBuffer(substr, &sub, &slen)) + return -1; + str = PyBytes_AS_STRING(self); + + bytes_adjust_indices(&start, &end, len); + + if (direction < 0) { + /* startswith */ + if (start+slen > len) + return 0; + } else { + /* endswith */ + if (end-start < slen || start > len) + return 0; + + if (end-slen > start) + start = end - slen; + } + if (end-start >= slen) + return ! memcmp(str+start, sub, slen); + return 0; } @@ -2643,33 +2643,33 @@ static PyObject * bytes_startswith(PyBytesObject *self, PyObject *args) { - Py_ssize_t start = 0; - Py_ssize_t end = PY_SSIZE_T_MAX; - PyObject *subobj; - int result; - - if (!PyArg_ParseTuple(args, "O|O&O&:startswith", &subobj, - _PyEval_SliceIndex, &start, _PyEval_SliceIndex, &end)) - return NULL; - if (PyTuple_Check(subobj)) { - Py_ssize_t i; - for (i = 0; i < PyTuple_GET_SIZE(subobj); i++) { - result = _bytes_tailmatch(self, - PyTuple_GET_ITEM(subobj, i), - start, end, -1); - if (result == -1) - return NULL; - else if (result) { - Py_RETURN_TRUE; - } - } - Py_RETURN_FALSE; - } - result = _bytes_tailmatch(self, subobj, start, end, -1); - if (result == -1) - return NULL; - else - return PyBool_FromLong(result); + Py_ssize_t start = 0; + Py_ssize_t end = PY_SSIZE_T_MAX; + PyObject *subobj; + int result; + + if (!PyArg_ParseTuple(args, "O|O&O&:startswith", &subobj, + _PyEval_SliceIndex, &start, _PyEval_SliceIndex, &end)) + return NULL; + if (PyTuple_Check(subobj)) { + Py_ssize_t i; + for (i = 0; i < PyTuple_GET_SIZE(subobj); i++) { + result = _bytes_tailmatch(self, + PyTuple_GET_ITEM(subobj, i), + start, end, -1); + if (result == -1) + return NULL; + else if (result) { + Py_RETURN_TRUE; + } + } + Py_RETURN_FALSE; + } + result = _bytes_tailmatch(self, subobj, start, end, -1); + if (result == -1) + return NULL; + else + return PyBool_FromLong(result); } @@ -2684,33 +2684,33 @@ static PyObject * bytes_endswith(PyBytesObject *self, PyObject *args) { - Py_ssize_t start = 0; - Py_ssize_t end = PY_SSIZE_T_MAX; - PyObject *subobj; - int result; - - if (!PyArg_ParseTuple(args, "O|O&O&:endswith", &subobj, - _PyEval_SliceIndex, &start, _PyEval_SliceIndex, &end)) - return NULL; - if (PyTuple_Check(subobj)) { - Py_ssize_t i; - for (i = 0; i < PyTuple_GET_SIZE(subobj); i++) { - result = _bytes_tailmatch(self, - PyTuple_GET_ITEM(subobj, i), - start, end, +1); - if (result == -1) - return NULL; - else if (result) { - Py_RETURN_TRUE; - } - } - Py_RETURN_FALSE; - } - result = _bytes_tailmatch(self, subobj, start, end, +1); - if (result == -1) - return NULL; - else - return PyBool_FromLong(result); + Py_ssize_t start = 0; + Py_ssize_t end = PY_SSIZE_T_MAX; + PyObject *subobj; + int result; + + if (!PyArg_ParseTuple(args, "O|O&O&:endswith", &subobj, + _PyEval_SliceIndex, &start, _PyEval_SliceIndex, &end)) + return NULL; + if (PyTuple_Check(subobj)) { + Py_ssize_t i; + for (i = 0; i < PyTuple_GET_SIZE(subobj); i++) { + result = _bytes_tailmatch(self, + PyTuple_GET_ITEM(subobj, i), + start, end, +1); + if (result == -1) + return NULL; + else if (result) { + Py_RETURN_TRUE; + } + } + Py_RETURN_FALSE; + } + result = _bytes_tailmatch(self, subobj, start, end, +1); + if (result == -1) + return NULL; + else + return PyBool_FromLong(result); } @@ -2727,14 +2727,14 @@ static PyObject * bytes_decode(PyObject *self, PyObject *args) { - const char *encoding = NULL; - const char *errors = NULL; + const char *encoding = NULL; + const char *errors = NULL; - if (!PyArg_ParseTuple(args, "|ss:decode", &encoding, &errors)) - return NULL; - if (encoding == NULL) - encoding = PyUnicode_GetDefaultEncoding(); - return PyUnicode_FromEncodedObject(self, encoding, errors); + if (!PyArg_ParseTuple(args, "|ss:decode", &encoding, &errors)) + return NULL; + if (encoding == NULL) + encoding = PyUnicode_GetDefaultEncoding(); + return PyUnicode_FromEncodedObject(self, encoding, errors); } @@ -2748,61 +2748,61 @@ static int hex_digit_to_int(Py_UNICODE c) { - if (c >= 128) - return -1; - if (ISDIGIT(c)) - return c - '0'; - else { - if (ISUPPER(c)) - c = TOLOWER(c); - if (c >= 'a' && c <= 'f') - return c - 'a' + 10; - } - return -1; + if (c >= 128) + return -1; + if (ISDIGIT(c)) + return c - '0'; + else { + if (ISUPPER(c)) + c = TOLOWER(c); + if (c >= 'a' && c <= 'f') + return c - 'a' + 10; + } + return -1; } static PyObject * bytes_fromhex(PyObject *cls, PyObject *args) { - PyObject *newstring, *hexobj; - char *buf; - Py_UNICODE *hex; - Py_ssize_t hexlen, byteslen, i, j; - int top, bot; - - if (!PyArg_ParseTuple(args, "U:fromhex", &hexobj)) - return NULL; - assert(PyUnicode_Check(hexobj)); - hexlen = PyUnicode_GET_SIZE(hexobj); - hex = PyUnicode_AS_UNICODE(hexobj); - byteslen = hexlen/2; /* This overestimates if there are spaces */ - newstring = PyBytes_FromStringAndSize(NULL, byteslen); - if (!newstring) - return NULL; - buf = PyBytes_AS_STRING(newstring); - for (i = j = 0; i < hexlen; i += 2) { - /* skip over spaces in the input */ - while (hex[i] == ' ') - i++; - if (i >= hexlen) - break; - top = hex_digit_to_int(hex[i]); - bot = hex_digit_to_int(hex[i+1]); - if (top == -1 || bot == -1) { - PyErr_Format(PyExc_ValueError, - "non-hexadecimal number found in " - "fromhex() arg at position %zd", i); - goto error; - } - buf[j++] = (top << 4) + bot; - } - if (j != byteslen && _PyBytes_Resize(&newstring, j) < 0) - goto error; - return newstring; + PyObject *newstring, *hexobj; + char *buf; + Py_UNICODE *hex; + Py_ssize_t hexlen, byteslen, i, j; + int top, bot; + + if (!PyArg_ParseTuple(args, "U:fromhex", &hexobj)) + return NULL; + assert(PyUnicode_Check(hexobj)); + hexlen = PyUnicode_GET_SIZE(hexobj); + hex = PyUnicode_AS_UNICODE(hexobj); + byteslen = hexlen/2; /* This overestimates if there are spaces */ + newstring = PyBytes_FromStringAndSize(NULL, byteslen); + if (!newstring) + return NULL; + buf = PyBytes_AS_STRING(newstring); + for (i = j = 0; i < hexlen; i += 2) { + /* skip over spaces in the input */ + while (hex[i] == ' ') + i++; + if (i >= hexlen) + break; + top = hex_digit_to_int(hex[i]); + bot = hex_digit_to_int(hex[i+1]); + if (top == -1 || bot == -1) { + PyErr_Format(PyExc_ValueError, + "non-hexadecimal number found in " + "fromhex() arg at position %zd", i); + goto error; + } + buf[j++] = (top << 4) + bot; + } + if (j != byteslen && _PyBytes_Resize(&newstring, j) < 0) + goto error; + return newstring; error: - Py_XDECREF(newstring); - return NULL; + Py_XDECREF(newstring); + return NULL; } PyDoc_STRVAR(sizeof__doc__, @@ -2811,80 +2811,80 @@ static PyObject * bytes_sizeof(PyBytesObject *v) { - Py_ssize_t res; - res = PyBytesObject_SIZE + Py_SIZE(v) * Py_TYPE(v)->tp_itemsize; - return PyLong_FromSsize_t(res); + Py_ssize_t res; + res = PyBytesObject_SIZE + Py_SIZE(v) * Py_TYPE(v)->tp_itemsize; + return PyLong_FromSsize_t(res); } static PyObject * bytes_getnewargs(PyBytesObject *v) { - return Py_BuildValue("(s#)", v->ob_sval, Py_SIZE(v)); + return Py_BuildValue("(s#)", 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, center__doc__}, - {"count", (PyCFunction)bytes_count, METH_VARARGS, count__doc__}, - {"decode", (PyCFunction)bytes_decode, METH_VARARGS, decode__doc__}, - {"endswith", (PyCFunction)bytes_endswith, METH_VARARGS, - endswith__doc__}, - {"expandtabs", (PyCFunction)stringlib_expandtabs, METH_VARARGS, - expandtabs__doc__}, - {"find", (PyCFunction)bytes_find, METH_VARARGS, find__doc__}, - {"fromhex", (PyCFunction)bytes_fromhex, METH_VARARGS|METH_CLASS, - fromhex_doc}, - {"index", (PyCFunction)bytes_index, METH_VARARGS, 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__}, - {"join", (PyCFunction)bytes_join, METH_O, join__doc__}, - {"ljust", (PyCFunction)stringlib_ljust, METH_VARARGS, ljust__doc__}, - {"lower", (PyCFunction)stringlib_lower, METH_NOARGS, _Py_lower__doc__}, - {"lstrip", (PyCFunction)bytes_lstrip, METH_VARARGS, lstrip__doc__}, - {"maketrans", (PyCFunction)bytes_maketrans, METH_VARARGS|METH_STATIC, - _Py_maketrans__doc__}, - {"partition", (PyCFunction)bytes_partition, METH_O, partition__doc__}, - {"replace", (PyCFunction)bytes_replace, METH_VARARGS, replace__doc__}, - {"rfind", (PyCFunction)bytes_rfind, METH_VARARGS, rfind__doc__}, - {"rindex", (PyCFunction)bytes_rindex, METH_VARARGS, rindex__doc__}, - {"rjust", (PyCFunction)stringlib_rjust, METH_VARARGS, rjust__doc__}, - {"rpartition", (PyCFunction)bytes_rpartition, METH_O, - rpartition__doc__}, - {"rsplit", (PyCFunction)bytes_rsplit, METH_VARARGS, rsplit__doc__}, - {"rstrip", (PyCFunction)bytes_rstrip, METH_VARARGS, rstrip__doc__}, - {"split", (PyCFunction)bytes_split, METH_VARARGS, split__doc__}, - {"splitlines", (PyCFunction)stringlib_splitlines, METH_VARARGS, - splitlines__doc__}, - {"startswith", (PyCFunction)bytes_startswith, METH_VARARGS, - startswith__doc__}, - {"strip", (PyCFunction)bytes_strip, METH_VARARGS, strip__doc__}, - {"swapcase", (PyCFunction)stringlib_swapcase, METH_NOARGS, - _Py_swapcase__doc__}, - {"title", (PyCFunction)stringlib_title, METH_NOARGS, _Py_title__doc__}, - {"translate", (PyCFunction)bytes_translate, METH_VARARGS, - translate__doc__}, - {"upper", (PyCFunction)stringlib_upper, METH_NOARGS, _Py_upper__doc__}, - {"zfill", (PyCFunction)stringlib_zfill, METH_VARARGS, zfill__doc__}, - {"__sizeof__", (PyCFunction)bytes_sizeof, METH_NOARGS, - sizeof__doc__}, - {NULL, NULL} /* sentinel */ + {"__getnewargs__", (PyCFunction)bytes_getnewargs, METH_NOARGS}, + {"capitalize", (PyCFunction)stringlib_capitalize, METH_NOARGS, + _Py_capitalize__doc__}, + {"center", (PyCFunction)stringlib_center, METH_VARARGS, center__doc__}, + {"count", (PyCFunction)bytes_count, METH_VARARGS, count__doc__}, + {"decode", (PyCFunction)bytes_decode, METH_VARARGS, decode__doc__}, + {"endswith", (PyCFunction)bytes_endswith, METH_VARARGS, + endswith__doc__}, + {"expandtabs", (PyCFunction)stringlib_expandtabs, METH_VARARGS, + expandtabs__doc__}, + {"find", (PyCFunction)bytes_find, METH_VARARGS, find__doc__}, + {"fromhex", (PyCFunction)bytes_fromhex, METH_VARARGS|METH_CLASS, + fromhex_doc}, + {"index", (PyCFunction)bytes_index, METH_VARARGS, 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__}, + {"join", (PyCFunction)bytes_join, METH_O, join__doc__}, + {"ljust", (PyCFunction)stringlib_ljust, METH_VARARGS, ljust__doc__}, + {"lower", (PyCFunction)stringlib_lower, METH_NOARGS, _Py_lower__doc__}, + {"lstrip", (PyCFunction)bytes_lstrip, METH_VARARGS, lstrip__doc__}, + {"maketrans", (PyCFunction)bytes_maketrans, METH_VARARGS|METH_STATIC, + _Py_maketrans__doc__}, + {"partition", (PyCFunction)bytes_partition, METH_O, partition__doc__}, + {"replace", (PyCFunction)bytes_replace, METH_VARARGS, replace__doc__}, + {"rfind", (PyCFunction)bytes_rfind, METH_VARARGS, rfind__doc__}, + {"rindex", (PyCFunction)bytes_rindex, METH_VARARGS, rindex__doc__}, + {"rjust", (PyCFunction)stringlib_rjust, METH_VARARGS, rjust__doc__}, + {"rpartition", (PyCFunction)bytes_rpartition, METH_O, + rpartition__doc__}, + {"rsplit", (PyCFunction)bytes_rsplit, METH_VARARGS, rsplit__doc__}, + {"rstrip", (PyCFunction)bytes_rstrip, METH_VARARGS, rstrip__doc__}, + {"split", (PyCFunction)bytes_split, METH_VARARGS, split__doc__}, + {"splitlines", (PyCFunction)stringlib_splitlines, METH_VARARGS, + splitlines__doc__}, + {"startswith", (PyCFunction)bytes_startswith, METH_VARARGS, + startswith__doc__}, + {"strip", (PyCFunction)bytes_strip, METH_VARARGS, strip__doc__}, + {"swapcase", (PyCFunction)stringlib_swapcase, METH_NOARGS, + _Py_swapcase__doc__}, + {"title", (PyCFunction)stringlib_title, METH_NOARGS, _Py_title__doc__}, + {"translate", (PyCFunction)bytes_translate, METH_VARARGS, + translate__doc__}, + {"upper", (PyCFunction)stringlib_upper, METH_NOARGS, _Py_upper__doc__}, + {"zfill", (PyCFunction)stringlib_zfill, METH_VARARGS, zfill__doc__}, + {"__sizeof__", (PyCFunction)bytes_sizeof, METH_NOARGS, + sizeof__doc__}, + {NULL, NULL} /* sentinel */ }; static PyObject * @@ -2893,187 +2893,187 @@ static PyObject * bytes_new(PyTypeObject *type, PyObject *args, PyObject *kwds) { - PyObject *x = NULL; - const char *encoding = NULL; - const char *errors = NULL; - PyObject *new = NULL; - static char *kwlist[] = {"source", "encoding", "errors", 0}; - - if (type != &PyBytes_Type) - return str_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_FromString(""); - } - - if (PyUnicode_Check(x)) { - /* Encode via the codec registry */ - if (encoding == NULL) { - PyErr_SetString(PyExc_TypeError, - "string argument without an encoding"); - return NULL; - } - new = PyUnicode_AsEncodedString(x, encoding, errors); - if (new == NULL) - return NULL; - assert(PyBytes_Check(new)); - return new; - } - - /* If it's not unicode, there can't be encoding or errors */ - if (encoding != NULL || errors != NULL) { - PyErr_SetString(PyExc_TypeError, - "encoding or errors without a string argument"); - return NULL; - } - return PyObject_Bytes(x); + PyObject *x = NULL; + const char *encoding = NULL; + const char *errors = NULL; + PyObject *new = NULL; + static char *kwlist[] = {"source", "encoding", "errors", 0}; + + if (type != &PyBytes_Type) + return str_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_FromString(""); + } + + if (PyUnicode_Check(x)) { + /* Encode via the codec registry */ + if (encoding == NULL) { + PyErr_SetString(PyExc_TypeError, + "string argument without an encoding"); + return NULL; + } + new = PyUnicode_AsEncodedString(x, encoding, errors); + if (new == NULL) + return NULL; + assert(PyBytes_Check(new)); + return new; + } + + /* If it's not unicode, there can't be encoding or errors */ + if (encoding != NULL || errors != NULL) { + PyErr_SetString(PyExc_TypeError, + "encoding or errors without a string argument"); + return NULL; + } + return PyObject_Bytes(x); } PyObject * PyBytes_FromObject(PyObject *x) { - PyObject *new, *it; - Py_ssize_t i, size; + PyObject *new, *it; + Py_ssize_t i, size; + + if (x == NULL) { + PyErr_BadInternalCall(); + return NULL; + } + + /* Is it an int? */ + size = PyNumber_AsSsize_t(x, PyExc_OverflowError); + if (size == -1 && PyErr_Occurred()) { + if (PyErr_ExceptionMatches(PyExc_OverflowError)) + return NULL; + PyErr_Clear(); + } + else if (size < 0) { + PyErr_SetString(PyExc_ValueError, "negative count"); + return NULL; + } + else { + new = PyBytes_FromStringAndSize(NULL, size); + if (new == NULL) { + return NULL; + } + if (size > 0) { + memset(((PyBytesObject*)new)->ob_sval, 0, size); + } + return new; + } + + /* Use the modern buffer interface */ + if (PyObject_CheckBuffer(x)) { + Py_buffer view; + if (PyObject_GetBuffer(x, &view, PyBUF_FULL_RO) < 0) + return NULL; + new = PyBytes_FromStringAndSize(NULL, view.len); + if (!new) + goto fail; + /* XXX(brett.cannon): Better way to get to internal buffer? */ + 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; + } + + /* For iterator version, create a string object and resize as needed */ + /* XXX(gb): is 64 a good value? also, optimize if length is known */ + /* XXX(guido): perhaps use Pysequence_Fast() -- I can't imagine the + input being a truly long iterator. */ + size = 64; + new = PyBytes_FromStringAndSize(NULL, size); + if (new == NULL) + return NULL; + + /* XXX Optimize this if the arguments is a list, tuple */ + + /* Get the iterator */ + it = PyObject_GetIter(x); + if (it == NULL) + goto error; + + /* 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, PyExc_ValueError); + 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) { + size *= 2; + if (_PyBytes_Resize(&new, size) < 0) + goto error; + } + ((PyBytesObject *)new)->ob_sval[i] = value; + } + _PyBytes_Resize(&new, i); - if (x == NULL) { - PyErr_BadInternalCall(); - return NULL; - } - - /* Is it an int? */ - size = PyNumber_AsSsize_t(x, PyExc_OverflowError); - if (size == -1 && PyErr_Occurred()) { - if (PyErr_ExceptionMatches(PyExc_OverflowError)) - return NULL; - PyErr_Clear(); - } - else if (size < 0) { - PyErr_SetString(PyExc_ValueError, "negative count"); - return NULL; - } - else { - new = PyBytes_FromStringAndSize(NULL, size); - if (new == NULL) { - return NULL; - } - if (size > 0) { - memset(((PyBytesObject*)new)->ob_sval, 0, size); - } - return new; - } - - /* Use the modern buffer interface */ - if (PyObject_CheckBuffer(x)) { - Py_buffer view; - if (PyObject_GetBuffer(x, &view, PyBUF_FULL_RO) < 0) - return NULL; - new = PyBytes_FromStringAndSize(NULL, view.len); - if (!new) - goto fail; - /* XXX(brett.cannon): Better way to get to internal buffer? */ - 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; - } - - /* For iterator version, create a string object and resize as needed */ - /* XXX(gb): is 64 a good value? also, optimize if length is known */ - /* XXX(guido): perhaps use Pysequence_Fast() -- I can't imagine the - input being a truly long iterator. */ - size = 64; - new = PyBytes_FromStringAndSize(NULL, size); - if (new == NULL) - return NULL; - - /* XXX Optimize this if the arguments is a list, tuple */ - - /* Get the iterator */ - it = PyObject_GetIter(x); - if (it == NULL) - goto error; - - /* 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, PyExc_ValueError); - 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) { - size *= 2; - if (_PyBytes_Resize(&new, size) < 0) - goto error; - } - ((PyBytesObject *)new)->ob_sval[i] = value; - } - _PyBytes_Resize(&new, i); - - /* Clean up and return success */ - Py_DECREF(it); - return new; + /* Clean up and return success */ + Py_DECREF(it); + return new; error: - /* Error handling when new != NULL */ - Py_XDECREF(it); - Py_DECREF(new); - return NULL; + /* Error handling when new != NULL */ + Py_XDECREF(it); + Py_DECREF(new); + return NULL; } static PyObject * str_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds) { - PyObject *tmp, *pnew; - Py_ssize_t n; + 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_CheckExact(tmp)); - n = PyBytes_GET_SIZE(tmp); - pnew = type->tp_alloc(type, n); - if (pnew != NULL) { - Py_MEMCPY(PyBytes_AS_STRING(pnew), - PyBytes_AS_STRING(tmp), n+1); - ((PyBytesObject *)pnew)->ob_shash = - ((PyBytesObject *)tmp)->ob_shash; - } - Py_DECREF(tmp); - return pnew; + assert(PyType_IsSubtype(type, &PyBytes_Type)); + tmp = bytes_new(&PyBytes_Type, args, kwds); + if (tmp == NULL) + return NULL; + assert(PyBytes_CheckExact(tmp)); + n = PyBytes_GET_SIZE(tmp); + pnew = type->tp_alloc(type, n); + if (pnew != NULL) { + Py_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, @@ -3091,70 +3091,70 @@ 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 */ - 0, /* 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 */ + 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 */ + 0, /* 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(register PyObject **pv, register PyObject *w) { - register PyObject *v; - assert(pv != NULL); - if (*pv == NULL) - return; - if (w == NULL) { - Py_DECREF(*pv); - *pv = NULL; - return; - } - v = bytes_concat(*pv, w); - Py_DECREF(*pv); - *pv = v; + register PyObject *v; + assert(pv != NULL); + if (*pv == NULL) + return; + if (w == NULL) { + Py_DECREF(*pv); + *pv = NULL; + return; + } + v = bytes_concat(*pv, w); + Py_DECREF(*pv); + *pv = v; } void PyBytes_ConcatAndDel(register PyObject **pv, register PyObject *w) { - PyBytes_Concat(pv, w); - Py_XDECREF(w); + PyBytes_Concat(pv, w); + Py_XDECREF(w); } @@ -3175,31 +3175,31 @@ int _PyBytes_Resize(PyObject **pv, Py_ssize_t newsize) { - register PyObject *v; - register PyBytesObject *sv; - v = *pv; - if (!PyBytes_Check(v) || Py_REFCNT(v) != 1 || newsize < 0) { - *pv = 0; - Py_DECREF(v); - PyErr_BadInternalCall(); - return -1; - } - /* XXX UNREF/NEWREF interface should be more symmetrical */ - _Py_DEC_REFTOTAL; - _Py_ForgetReference(v); - *pv = (PyObject *) - PyObject_REALLOC((char *)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; + register PyObject *v; + register PyBytesObject *sv; + v = *pv; + if (!PyBytes_Check(v) || Py_REFCNT(v) != 1 || newsize < 0) { + *pv = 0; + Py_DECREF(v); + PyErr_BadInternalCall(); + return -1; + } + /* XXX UNREF/NEWREF interface should be more symmetrical */ + _Py_DEC_REFTOTAL; + _Py_ForgetReference(v); + *pv = (PyObject *) + PyObject_REALLOC((char *)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; } /* _PyBytes_FormatLong emulates the format codes d, u, o, x and X, and @@ -3215,262 +3215,262 @@ * set in flags. The case of hex digits will be correct, * There will be at least prec digits, zero-filled on the left if * necessary to get that many. - * val object to be converted - * flags bitmask of format flags; only F_ALT is looked at - * prec minimum number of digits; 0-fill on left if needed - * type a character in [duoxX]; u acts the same as d + * val object to be converted + * flags bitmask of format flags; only F_ALT is looked at + * prec minimum number of digits; 0-fill on left if needed + * type a character in [duoxX]; u acts the same as d * * CAUTION: o, x and X conversions on regular ints can never * produce a '-' sign, but can for Python's unbounded ints. */ PyObject* _PyBytes_FormatLong(PyObject *val, int flags, int prec, int type, - char **pbuf, int *plen) + char **pbuf, int *plen) { - PyObject *result = NULL; - char *buf; - Py_ssize_t i; - int sign; /* 1 if '-', else 0 */ - int len; /* number of characters */ - Py_ssize_t llen; - int numdigits; /* len == numnondigits + numdigits */ - int numnondigits = 0; - - /* Avoid exceeding SSIZE_T_MAX */ - if (prec > INT_MAX-3) { - PyErr_SetString(PyExc_OverflowError, - "precision too large"); - return NULL; - } - - switch (type) { - case 'd': - case 'u': - /* Special-case boolean: we want 0/1 */ - if (PyBool_Check(val)) - result = PyNumber_ToBase(val, 10); - else - result = Py_TYPE(val)->tp_str(val); - break; - case 'o': - numnondigits = 2; - result = PyNumber_ToBase(val, 8); - break; - case 'x': - case 'X': - numnondigits = 2; - result = PyNumber_ToBase(val, 16); - break; - default: - assert(!"'type' not in [duoxX]"); - } - if (!result) - return NULL; - - buf = _PyUnicode_AsString(result); - if (!buf) { - Py_DECREF(result); - return NULL; - } - - /* To modify the string in-place, there can only be one reference. */ - if (Py_REFCNT(result) != 1) { - PyErr_BadInternalCall(); - return NULL; - } - llen = PyUnicode_GetSize(result); - if (llen > INT_MAX) { - PyErr_SetString(PyExc_ValueError, - "string too large in _PyBytes_FormatLong"); - return NULL; - } - len = (int)llen; - if (buf[len-1] == 'L') { - --len; - buf[len] = '\0'; - } - sign = buf[0] == '-'; - numnondigits += sign; - numdigits = len - numnondigits; - assert(numdigits > 0); - - /* Get rid of base marker unless F_ALT */ - if (((flags & F_ALT) == 0 && - (type == 'o' || type == 'x' || type == 'X'))) { - assert(buf[sign] == '0'); - assert(buf[sign+1] == 'x' || buf[sign+1] == 'X' || - buf[sign+1] == 'o'); - numnondigits -= 2; - buf += 2; - len -= 2; - if (sign) - buf[0] = '-'; - assert(len == numnondigits + numdigits); - assert(numdigits > 0); - } - - /* Fill with leading zeroes to meet minimum width. */ - if (prec > numdigits) { - PyObject *r1 = PyBytes_FromStringAndSize(NULL, - numnondigits + prec); - char *b1; - if (!r1) { - Py_DECREF(result); - return NULL; - } - b1 = PyBytes_AS_STRING(r1); - for (i = 0; i < numnondigits; ++i) - *b1++ = *buf++; - for (i = 0; i < prec - numdigits; i++) - *b1++ = '0'; - for (i = 0; i < numdigits; i++) - *b1++ = *buf++; - *b1 = '\0'; - Py_DECREF(result); - result = r1; - buf = PyBytes_AS_STRING(result); - len = numnondigits + prec; - } - - /* Fix up case for hex conversions. */ - if (type == 'X') { - /* Need to convert all lower case letters to upper case. - and need to convert 0x to 0X (and -0x to -0X). */ - for (i = 0; i < len; i++) - if (buf[i] >= 'a' && buf[i] <= 'x') - buf[i] -= 'a'-'A'; - } - *pbuf = buf; - *plen = len; - return result; + PyObject *result = NULL; + char *buf; + Py_ssize_t i; + int sign; /* 1 if '-', else 0 */ + int len; /* number of characters */ + Py_ssize_t llen; + int numdigits; /* len == numnondigits + numdigits */ + int numnondigits = 0; + + /* Avoid exceeding SSIZE_T_MAX */ + if (prec > INT_MAX-3) { + PyErr_SetString(PyExc_OverflowError, + "precision too large"); + return NULL; + } + + switch (type) { + case 'd': + case 'u': + /* Special-case boolean: we want 0/1 */ + if (PyBool_Check(val)) + result = PyNumber_ToBase(val, 10); + else + result = Py_TYPE(val)->tp_str(val); + break; + case 'o': + numnondigits = 2; + result = PyNumber_ToBase(val, 8); + break; + case 'x': + case 'X': + numnondigits = 2; + result = PyNumber_ToBase(val, 16); + break; + default: + assert(!"'type' not in [duoxX]"); + } + if (!result) + return NULL; + + buf = _PyUnicode_AsString(result); + if (!buf) { + Py_DECREF(result); + return NULL; + } + + /* To modify the string in-place, there can only be one reference. */ + if (Py_REFCNT(result) != 1) { + PyErr_BadInternalCall(); + return NULL; + } + llen = PyUnicode_GetSize(result); + if (llen > INT_MAX) { + PyErr_SetString(PyExc_ValueError, + "string too large in _PyBytes_FormatLong"); + return NULL; + } + len = (int)llen; + if (buf[len-1] == 'L') { + --len; + buf[len] = '\0'; + } + sign = buf[0] == '-'; + numnondigits += sign; + numdigits = len - numnondigits; + assert(numdigits > 0); + + /* Get rid of base marker unless F_ALT */ + if (((flags & F_ALT) == 0 && + (type == 'o' || type == 'x' || type == 'X'))) { + assert(buf[sign] == '0'); + assert(buf[sign+1] == 'x' || buf[sign+1] == 'X' || + buf[sign+1] == 'o'); + numnondigits -= 2; + buf += 2; + len -= 2; + if (sign) + buf[0] = '-'; + assert(len == numnondigits + numdigits); + assert(numdigits > 0); + } + + /* Fill with leading zeroes to meet minimum width. */ + if (prec > numdigits) { + PyObject *r1 = PyBytes_FromStringAndSize(NULL, + numnondigits + prec); + char *b1; + if (!r1) { + Py_DECREF(result); + return NULL; + } + b1 = PyBytes_AS_STRING(r1); + for (i = 0; i < numnondigits; ++i) + *b1++ = *buf++; + for (i = 0; i < prec - numdigits; i++) + *b1++ = '0'; + for (i = 0; i < numdigits; i++) + *b1++ = *buf++; + *b1 = '\0'; + Py_DECREF(result); + result = r1; + buf = PyBytes_AS_STRING(result); + len = numnondigits + prec; + } + + /* Fix up case for hex conversions. */ + if (type == 'X') { + /* Need to convert all lower case letters to upper case. + and need to convert 0x to 0X (and -0x to -0X). */ + for (i = 0; i < len; i++) + if (buf[i] >= 'a' && buf[i] <= 'x') + buf[i] -= 'a'-'A'; + } + *pbuf = buf; + *plen = len; + return result; } void PyBytes_Fini(void) { - int i; - for (i = 0; i < UCHAR_MAX + 1; i++) { - Py_XDECREF(characters[i]); - characters[i] = NULL; - } - Py_XDECREF(nullstring); - nullstring = NULL; + int i; + for (i = 0; i < UCHAR_MAX + 1; i++) { + Py_XDECREF(characters[i]); + characters[i] = NULL; + } + Py_XDECREF(nullstring); + nullstring = NULL; } /*********************** Bytes Iterator ****************************/ typedef struct { - PyObject_HEAD - Py_ssize_t it_index; - PyBytesObject *it_seq; /* Set to NULL when iterator is exhausted */ + 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); + _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; + Py_VISIT(it->it_seq); + return 0; } static PyObject * striter_next(striterobject *it) { - PyBytesObject *seq; - PyObject *item; + 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; + } - 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; - } - - Py_DECREF(seq); - it->it_seq = NULL; - return NULL; + Py_DECREF(seq); + it->it_seq = NULL; + 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); + 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))."); + "Private method returning an estimate of len(list(it))."); static PyMethodDef striter_methods[] = { - {"__length_hint__", (PyCFunction)striter_len, METH_NOARGS, - length_hint_doc}, - {NULL, NULL} /* sentinel */ + {"__length_hint__", (PyCFunction)striter_len, METH_NOARGS, + length_hint_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, + 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; + 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; + 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; } Modified: python/branches/release31-maint/Objects/cellobject.c ============================================================================== --- python/branches/release31-maint/Objects/cellobject.c (original) +++ python/branches/release31-maint/Objects/cellobject.c Sun May 9 18:14:21 2010 @@ -5,50 +5,50 @@ PyObject * PyCell_New(PyObject *obj) { - PyCellObject *op; + PyCellObject *op; - op = (PyCellObject *)PyObject_GC_New(PyCellObject, &PyCell_Type); - if (op == NULL) - return NULL; - op->ob_ref = obj; - Py_XINCREF(obj); + op = (PyCellObject *)PyObject_GC_New(PyCellObject, &PyCell_Type); + if (op == NULL) + return NULL; + op->ob_ref = obj; + Py_XINCREF(obj); - _PyObject_GC_TRACK(op); - return (PyObject *)op; + _PyObject_GC_TRACK(op); + return (PyObject *)op; } PyObject * PyCell_Get(PyObject *op) { - if (!PyCell_Check(op)) { - PyErr_BadInternalCall(); - return NULL; - } - Py_XINCREF(((PyCellObject*)op)->ob_ref); - return PyCell_GET(op); + if (!PyCell_Check(op)) { + PyErr_BadInternalCall(); + return NULL; + } + Py_XINCREF(((PyCellObject*)op)->ob_ref); + return PyCell_GET(op); } int PyCell_Set(PyObject *op, PyObject *obj) { - PyObject* oldobj; - if (!PyCell_Check(op)) { - PyErr_BadInternalCall(); - return -1; - } - oldobj = PyCell_GET(op); - Py_XINCREF(obj); - PyCell_SET(op, obj); - Py_XDECREF(oldobj); - return 0; + PyObject* oldobj; + if (!PyCell_Check(op)) { + PyErr_BadInternalCall(); + return -1; + } + oldobj = PyCell_GET(op); + Py_XINCREF(obj); + PyCell_SET(op, obj); + Py_XDECREF(oldobj); + return 0; } static void cell_dealloc(PyCellObject *op) { - _PyObject_GC_UNTRACK(op); - Py_XDECREF(op->ob_ref); - PyObject_GC_Del(op); + _PyObject_GC_UNTRACK(op); + Py_XDECREF(op->ob_ref); + PyObject_GC_Del(op); } #define TEST_COND(cond) ((cond) ? Py_True : Py_False) @@ -56,124 +56,124 @@ static PyObject * cell_richcompare(PyObject *a, PyObject *b, int op) { - int result; - PyObject *v; + int result; + PyObject *v; - /* neither argument should be NULL, unless something's gone wrong */ - assert(a != NULL && b != NULL); + /* neither argument should be NULL, unless something's gone wrong */ + assert(a != NULL && b != NULL); - /* both arguments should be instances of PyCellObject */ - if (!PyCell_Check(a) || !PyCell_Check(b)) { - v = Py_NotImplemented; - Py_INCREF(v); - return v; - } - - /* compare cells by contents; empty cells come before anything else */ - a = ((PyCellObject *)a)->ob_ref; - b = ((PyCellObject *)b)->ob_ref; - if (a != NULL && b != NULL) - return PyObject_RichCompare(a, b, op); - - result = (b == NULL) - (a == NULL); - switch (op) { - case Py_EQ: - v = TEST_COND(result == 0); - break; - case Py_NE: - v = TEST_COND(result != 0); - break; - case Py_LE: - v = TEST_COND(result <= 0); - break; - case Py_GE: - v = TEST_COND(result >= 0); - break; - case Py_LT: - v = TEST_COND(result < 0); - break; - case Py_GT: - v = TEST_COND(result > 0); - break; - default: - PyErr_BadArgument(); - return NULL; - } - Py_INCREF(v); - return v; + /* both arguments should be instances of PyCellObject */ + if (!PyCell_Check(a) || !PyCell_Check(b)) { + v = Py_NotImplemented; + Py_INCREF(v); + return v; + } + + /* compare cells by contents; empty cells come before anything else */ + a = ((PyCellObject *)a)->ob_ref; + b = ((PyCellObject *)b)->ob_ref; + if (a != NULL && b != NULL) + return PyObject_RichCompare(a, b, op); + + result = (b == NULL) - (a == NULL); + switch (op) { + case Py_EQ: + v = TEST_COND(result == 0); + break; + case Py_NE: + v = TEST_COND(result != 0); + break; + case Py_LE: + v = TEST_COND(result <= 0); + break; + case Py_GE: + v = TEST_COND(result >= 0); + break; + case Py_LT: + v = TEST_COND(result < 0); + break; + case Py_GT: + v = TEST_COND(result > 0); + break; + default: + PyErr_BadArgument(); + return NULL; + } + Py_INCREF(v); + return v; } static PyObject * cell_repr(PyCellObject *op) { - if (op->ob_ref == NULL) - return PyUnicode_FromFormat("", op); + if (op->ob_ref == NULL) + return PyUnicode_FromFormat("", op); - return PyUnicode_FromFormat("", - op, op->ob_ref->ob_type->tp_name, - op->ob_ref); + return PyUnicode_FromFormat("", + op, op->ob_ref->ob_type->tp_name, + op->ob_ref); } static int cell_traverse(PyCellObject *op, visitproc visit, void *arg) { - Py_VISIT(op->ob_ref); - return 0; + Py_VISIT(op->ob_ref); + return 0; } static int cell_clear(PyCellObject *op) { - Py_CLEAR(op->ob_ref); - return 0; + Py_CLEAR(op->ob_ref); + return 0; } static PyObject * cell_get_contents(PyCellObject *op, void *closure) { - if (op->ob_ref == NULL) - { - PyErr_SetString(PyExc_ValueError, "Cell is empty"); - return NULL; - } - Py_INCREF(op->ob_ref); - return op->ob_ref; + if (op->ob_ref == NULL) + { + PyErr_SetString(PyExc_ValueError, "Cell is empty"); + return NULL; + } + Py_INCREF(op->ob_ref); + return op->ob_ref; } static PyGetSetDef cell_getsetlist[] = { - {"cell_contents", (getter)cell_get_contents, NULL}, - {NULL} /* sentinel */ + {"cell_contents", (getter)cell_get_contents, NULL}, + {NULL} /* sentinel */ }; PyTypeObject PyCell_Type = { - PyVarObject_HEAD_INIT(&PyType_Type, 0) - "cell", - sizeof(PyCellObject), - 0, - (destructor)cell_dealloc, /* tp_dealloc */ - 0, /* tp_print */ - 0, /* tp_getattr */ - 0, /* tp_setattr */ - 0, /* tp_reserved */ - (reprfunc)cell_repr, /* 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)cell_traverse, /* tp_traverse */ - (inquiry)cell_clear, /* tp_clear */ - cell_richcompare, /* tp_richcompare */ - 0, /* tp_weaklistoffset */ - 0, /* tp_iter */ - 0, /* tp_iternext */ - 0, /* tp_methods */ - 0, /* tp_members */ - cell_getsetlist, /* tp_getset */ + PyVarObject_HEAD_INIT(&PyType_Type, 0) + "cell", + sizeof(PyCellObject), + 0, + (destructor)cell_dealloc, /* tp_dealloc */ + 0, /* tp_print */ + 0, /* tp_getattr */ + 0, /* tp_setattr */ + 0, /* tp_reserved */ + (reprfunc)cell_repr, /* 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)cell_traverse, /* tp_traverse */ + (inquiry)cell_clear, /* tp_clear */ + cell_richcompare, /* tp_richcompare */ + 0, /* tp_weaklistoffset */ + 0, /* tp_iter */ + 0, /* tp_iternext */ + 0, /* tp_methods */ + 0, /* tp_members */ + cell_getsetlist, /* tp_getset */ }; Modified: python/branches/release31-maint/Objects/classobject.c ============================================================================== --- python/branches/release31-maint/Objects/classobject.c (original) +++ python/branches/release31-maint/Objects/classobject.c Sun May 9 18:14:21 2010 @@ -17,21 +17,21 @@ PyObject * PyMethod_Function(PyObject *im) { - if (!PyMethod_Check(im)) { - PyErr_BadInternalCall(); - return NULL; - } - return ((PyMethodObject *)im)->im_func; + if (!PyMethod_Check(im)) { + PyErr_BadInternalCall(); + return NULL; + } + return ((PyMethodObject *)im)->im_func; } PyObject * PyMethod_Self(PyObject *im) { - if (!PyMethod_Check(im)) { - PyErr_BadInternalCall(); - return NULL; - } - return ((PyMethodObject *)im)->im_self; + if (!PyMethod_Check(im)) { + PyErr_BadInternalCall(); + return NULL; + } + return ((PyMethodObject *)im)->im_self; } /* Method objects are used for bound instance methods returned by @@ -42,29 +42,29 @@ PyObject * PyMethod_New(PyObject *func, PyObject *self) { - register PyMethodObject *im; - if (self == NULL) { - PyErr_BadInternalCall(); - return NULL; - } - im = free_list; - if (im != NULL) { - free_list = (PyMethodObject *)(im->im_self); - PyObject_INIT(im, &PyMethod_Type); - numfree--; - } - else { - im = PyObject_GC_New(PyMethodObject, &PyMethod_Type); - if (im == NULL) - return NULL; - } - im->im_weakreflist = NULL; - Py_INCREF(func); - im->im_func = func; - Py_XINCREF(self); - im->im_self = self; - _PyObject_GC_TRACK(im); - return (PyObject *)im; + register PyMethodObject *im; + if (self == NULL) { + PyErr_BadInternalCall(); + return NULL; + } + im = free_list; + if (im != NULL) { + free_list = (PyMethodObject *)(im->im_self); + PyObject_INIT(im, &PyMethod_Type); + numfree--; + } + else { + im = PyObject_GC_New(PyMethodObject, &PyMethod_Type); + if (im == NULL) + return NULL; + } + im->im_weakreflist = NULL; + Py_INCREF(func); + im->im_func = func; + Py_XINCREF(self); + im->im_self = self; + _PyObject_GC_TRACK(im); + return (PyObject *)im; } /* Descriptors for PyMethod attributes */ @@ -74,11 +74,11 @@ #define MO_OFF(x) offsetof(PyMethodObject, x) static PyMemberDef method_memberlist[] = { - {"__func__", T_OBJECT, MO_OFF(im_func), READONLY|RESTRICTED, - "the function (or other callable) implementing a method"}, - {"__self__", T_OBJECT, MO_OFF(im_self), READONLY|RESTRICTED, - "the instance to which a method is bound"}, - {NULL} /* Sentinel */ + {"__func__", T_OBJECT, MO_OFF(im_func), READONLY|RESTRICTED, + "the function (or other callable) implementing a method"}, + {"__self__", T_OBJECT, MO_OFF(im_self), READONLY|RESTRICTED, + "the instance to which a method is bound"}, + {NULL} /* Sentinel */ }; /* Christian Tismer argued convincingly that method attributes should @@ -89,46 +89,46 @@ static PyObject * method_get_doc(PyMethodObject *im, void *context) { - static PyObject *docstr; - if (docstr == NULL) { - docstr= PyUnicode_InternFromString("__doc__"); - if (docstr == NULL) - return NULL; - } - return PyObject_GetAttr(im->im_func, docstr); + static PyObject *docstr; + if (docstr == NULL) { + docstr= PyUnicode_InternFromString("__doc__"); + if (docstr == NULL) + return NULL; + } + return PyObject_GetAttr(im->im_func, docstr); } static PyGetSetDef method_getset[] = { - {"__doc__", (getter)method_get_doc, NULL, NULL}, - {0} + {"__doc__", (getter)method_get_doc, NULL, NULL}, + {0} }; static PyObject * method_getattro(PyObject *obj, PyObject *name) { - PyMethodObject *im = (PyMethodObject *)obj; - PyTypeObject *tp = obj->ob_type; - PyObject *descr = NULL; - - { - if (tp->tp_dict == NULL) { - if (PyType_Ready(tp) < 0) - return NULL; - } - descr = _PyType_Lookup(tp, name); - } - - if (descr != NULL) { - descrgetfunc f = TP_DESCR_GET(descr->ob_type); - if (f != NULL) - return f(descr, obj, (PyObject *)obj->ob_type); - else { - Py_INCREF(descr); - return descr; - } - } + PyMethodObject *im = (PyMethodObject *)obj; + PyTypeObject *tp = obj->ob_type; + PyObject *descr = NULL; + + { + if (tp->tp_dict == NULL) { + if (PyType_Ready(tp) < 0) + return NULL; + } + descr = _PyType_Lookup(tp, name); + } + + if (descr != NULL) { + descrgetfunc f = TP_DESCR_GET(descr->ob_type); + if (f != NULL) + return f(descr, obj, (PyObject *)obj->ob_type); + else { + Py_INCREF(descr); + return descr; + } + } - return PyObject_GetAttr(im->im_func, name); + return PyObject_GetAttr(im->im_func, name); } PyDoc_STRVAR(method_doc, @@ -139,241 +139,241 @@ static PyObject * method_new(PyTypeObject* type, PyObject* args, PyObject *kw) { - PyObject *func; - PyObject *self; + PyObject *func; + PyObject *self; - if (!_PyArg_NoKeywords("method", kw)) - return NULL; - if (!PyArg_UnpackTuple(args, "method", 2, 2, - &func, &self)) - return NULL; - if (!PyCallable_Check(func)) { - PyErr_SetString(PyExc_TypeError, - "first argument must be callable"); - return NULL; - } - if (self == NULL || self == Py_None) { - PyErr_SetString(PyExc_TypeError, - "self must not be None"); - return NULL; - } + if (!_PyArg_NoKeywords("method", kw)) + return NULL; + if (!PyArg_UnpackTuple(args, "method", 2, 2, + &func, &self)) + return NULL; + if (!PyCallable_Check(func)) { + PyErr_SetString(PyExc_TypeError, + "first argument must be callable"); + return NULL; + } + if (self == NULL || self == Py_None) { + PyErr_SetString(PyExc_TypeError, + "self must not be None"); + return NULL; + } - return PyMethod_New(func, self); + return PyMethod_New(func, self); } static void method_dealloc(register PyMethodObject *im) { - _PyObject_GC_UNTRACK(im); - if (im->im_weakreflist != NULL) - PyObject_ClearWeakRefs((PyObject *)im); - Py_DECREF(im->im_func); - Py_XDECREF(im->im_self); - if (numfree < PyMethod_MAXFREELIST) { - im->im_self = (PyObject *)free_list; - free_list = im; - numfree++; - } - else { - PyObject_GC_Del(im); - } + _PyObject_GC_UNTRACK(im); + if (im->im_weakreflist != NULL) + PyObject_ClearWeakRefs((PyObject *)im); + Py_DECREF(im->im_func); + Py_XDECREF(im->im_self); + if (numfree < PyMethod_MAXFREELIST) { + im->im_self = (PyObject *)free_list; + free_list = im; + numfree++; + } + else { + PyObject_GC_Del(im); + } } static PyObject * method_richcompare(PyObject *self, PyObject *other, int op) { - PyMethodObject *a, *b; - PyObject *res; - int eq; - - if ((op != Py_EQ && op != Py_NE) || - !PyMethod_Check(self) || - !PyMethod_Check(other)) - { - Py_INCREF(Py_NotImplemented); - return Py_NotImplemented; - } - a = (PyMethodObject *)self; - b = (PyMethodObject *)other; - eq = PyObject_RichCompareBool(a->im_func, b->im_func, Py_EQ); - if (eq == 1) { - if (a->im_self == NULL || b->im_self == NULL) - eq = a->im_self == b->im_self; - else - eq = PyObject_RichCompareBool(a->im_self, b->im_self, - Py_EQ); - } - if (eq < 0) - return NULL; - if (op == Py_EQ) - res = eq ? Py_True : Py_False; - else - res = eq ? Py_False : Py_True; - Py_INCREF(res); - return res; + PyMethodObject *a, *b; + PyObject *res; + int eq; + + if ((op != Py_EQ && op != Py_NE) || + !PyMethod_Check(self) || + !PyMethod_Check(other)) + { + Py_INCREF(Py_NotImplemented); + return Py_NotImplemented; + } + a = (PyMethodObject *)self; + b = (PyMethodObject *)other; + eq = PyObject_RichCompareBool(a->im_func, b->im_func, Py_EQ); + if (eq == 1) { + if (a->im_self == NULL || b->im_self == NULL) + eq = a->im_self == b->im_self; + else + eq = PyObject_RichCompareBool(a->im_self, b->im_self, + Py_EQ); + } + if (eq < 0) + return NULL; + if (op == Py_EQ) + res = eq ? Py_True : Py_False; + else + res = eq ? Py_False : Py_True; + Py_INCREF(res); + return res; } static PyObject * method_repr(PyMethodObject *a) { - PyObject *self = a->im_self; - PyObject *func = a->im_func; - PyObject *klass = (PyObject*)Py_TYPE(self); - PyObject *funcname = NULL ,*klassname = NULL, *result = NULL; - char *defname = "?"; - - if (self == NULL) { - PyErr_BadInternalCall(); - return NULL; - } - - funcname = PyObject_GetAttrString(func, "__name__"); - if (funcname == NULL) { - if (!PyErr_ExceptionMatches(PyExc_AttributeError)) - return NULL; - PyErr_Clear(); - } - else if (!PyUnicode_Check(funcname)) { - Py_DECREF(funcname); - funcname = NULL; - } - - if (klass == NULL) - klassname = NULL; - else { - klassname = PyObject_GetAttrString(klass, "__name__"); - if (klassname == NULL) { - if (!PyErr_ExceptionMatches(PyExc_AttributeError)) - return NULL; - PyErr_Clear(); - } - else if (!PyUnicode_Check(klassname)) { - Py_DECREF(klassname); - klassname = NULL; - } - } - - /* XXX Shouldn't use repr()/%R here! */ - result = PyUnicode_FromFormat("", - klassname, defname, - funcname, defname, self); - - Py_XDECREF(funcname); - Py_XDECREF(klassname); - return result; + PyObject *self = a->im_self; + PyObject *func = a->im_func; + PyObject *klass = (PyObject*)Py_TYPE(self); + PyObject *funcname = NULL ,*klassname = NULL, *result = NULL; + char *defname = "?"; + + if (self == NULL) { + PyErr_BadInternalCall(); + return NULL; + } + + funcname = PyObject_GetAttrString(func, "__name__"); + if (funcname == NULL) { + if (!PyErr_ExceptionMatches(PyExc_AttributeError)) + return NULL; + PyErr_Clear(); + } + else if (!PyUnicode_Check(funcname)) { + Py_DECREF(funcname); + funcname = NULL; + } + + if (klass == NULL) + klassname = NULL; + else { + klassname = PyObject_GetAttrString(klass, "__name__"); + if (klassname == NULL) { + if (!PyErr_ExceptionMatches(PyExc_AttributeError)) + return NULL; + PyErr_Clear(); + } + else if (!PyUnicode_Check(klassname)) { + Py_DECREF(klassname); + klassname = NULL; + } + } + + /* XXX Shouldn't use repr()/%R here! */ + result = PyUnicode_FromFormat("", + klassname, defname, + funcname, defname, self); + + Py_XDECREF(funcname); + Py_XDECREF(klassname); + return result; } static long method_hash(PyMethodObject *a) { - long x, y; - if (a->im_self == NULL) - x = PyObject_Hash(Py_None); - else - x = PyObject_Hash(a->im_self); - if (x == -1) - return -1; - y = PyObject_Hash(a->im_func); - if (y == -1) - return -1; - x = x ^ y; - if (x == -1) - x = -2; - return x; + long x, y; + if (a->im_self == NULL) + x = PyObject_Hash(Py_None); + else + x = PyObject_Hash(a->im_self); + if (x == -1) + return -1; + y = PyObject_Hash(a->im_func); + if (y == -1) + return -1; + x = x ^ y; + if (x == -1) + x = -2; + return x; } static int method_traverse(PyMethodObject *im, visitproc visit, void *arg) { - Py_VISIT(im->im_func); - Py_VISIT(im->im_self); - return 0; + Py_VISIT(im->im_func); + Py_VISIT(im->im_self); + return 0; } static PyObject * method_call(PyObject *func, PyObject *arg, PyObject *kw) { - PyObject *self = PyMethod_GET_SELF(func); - PyObject *result; + PyObject *self = PyMethod_GET_SELF(func); + PyObject *result; - func = PyMethod_GET_FUNCTION(func); - if (self == NULL) { - PyErr_BadInternalCall(); - return NULL; - } - else { - Py_ssize_t argcount = PyTuple_Size(arg); - PyObject *newarg = PyTuple_New(argcount + 1); - int i; - if (newarg == NULL) - return NULL; - Py_INCREF(self); - PyTuple_SET_ITEM(newarg, 0, self); - for (i = 0; i < argcount; i++) { - PyObject *v = PyTuple_GET_ITEM(arg, i); - Py_XINCREF(v); - PyTuple_SET_ITEM(newarg, i+1, v); - } - arg = newarg; - } - result = PyObject_Call((PyObject *)func, arg, kw); - Py_DECREF(arg); - return result; + func = PyMethod_GET_FUNCTION(func); + if (self == NULL) { + PyErr_BadInternalCall(); + return NULL; + } + else { + Py_ssize_t argcount = PyTuple_Size(arg); + PyObject *newarg = PyTuple_New(argcount + 1); + int i; + if (newarg == NULL) + return NULL; + Py_INCREF(self); + PyTuple_SET_ITEM(newarg, 0, self); + for (i = 0; i < argcount; i++) { + PyObject *v = PyTuple_GET_ITEM(arg, i); + Py_XINCREF(v); + PyTuple_SET_ITEM(newarg, i+1, v); + } + arg = newarg; + } + result = PyObject_Call((PyObject *)func, arg, kw); + Py_DECREF(arg); + return result; } static PyObject * method_descr_get(PyObject *meth, PyObject *obj, PyObject *cls) { - /* Don't rebind an already bound method of a class that's not a base - class of cls. */ - if (PyMethod_GET_SELF(meth) != NULL) { - /* Already bound */ - Py_INCREF(meth); - return meth; - } - /* Bind it to obj */ - return PyMethod_New(PyMethod_GET_FUNCTION(meth), obj); + /* Don't rebind an already bound method of a class that's not a base + class of cls. */ + if (PyMethod_GET_SELF(meth) != NULL) { + /* Already bound */ + Py_INCREF(meth); + return meth; + } + /* Bind it to obj */ + return PyMethod_New(PyMethod_GET_FUNCTION(meth), obj); } PyTypeObject PyMethod_Type = { - PyVarObject_HEAD_INIT(&PyType_Type, 0) - "method", - sizeof(PyMethodObject), - 0, - (destructor)method_dealloc, /* tp_dealloc */ - 0, /* tp_print */ - 0, /* tp_getattr */ - 0, /* tp_setattr */ - 0, /* tp_reserved */ - (reprfunc)method_repr, /* tp_repr */ - 0, /* tp_as_number */ - 0, /* tp_as_sequence */ - 0, /* tp_as_mapping */ - (hashfunc)method_hash, /* tp_hash */ - method_call, /* tp_call */ - 0, /* tp_str */ - method_getattro, /* tp_getattro */ - PyObject_GenericSetAttr, /* tp_setattro */ - 0, /* tp_as_buffer */ - Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC, /* tp_flags */ - method_doc, /* tp_doc */ - (traverseproc)method_traverse, /* tp_traverse */ - 0, /* tp_clear */ - method_richcompare, /* tp_richcompare */ - offsetof(PyMethodObject, im_weakreflist), /* tp_weaklistoffset */ - 0, /* tp_iter */ - 0, /* tp_iternext */ - 0, /* tp_methods */ - method_memberlist, /* tp_members */ - method_getset, /* tp_getset */ - 0, /* tp_base */ - 0, /* tp_dict */ - method_descr_get, /* tp_descr_get */ - 0, /* tp_descr_set */ - 0, /* tp_dictoffset */ - 0, /* tp_init */ - 0, /* tp_alloc */ - method_new, /* tp_new */ + PyVarObject_HEAD_INIT(&PyType_Type, 0) + "method", + sizeof(PyMethodObject), + 0, + (destructor)method_dealloc, /* tp_dealloc */ + 0, /* tp_print */ + 0, /* tp_getattr */ + 0, /* tp_setattr */ + 0, /* tp_reserved */ + (reprfunc)method_repr, /* tp_repr */ + 0, /* tp_as_number */ + 0, /* tp_as_sequence */ + 0, /* tp_as_mapping */ + (hashfunc)method_hash, /* tp_hash */ + method_call, /* tp_call */ + 0, /* tp_str */ + method_getattro, /* tp_getattro */ + PyObject_GenericSetAttr, /* tp_setattro */ + 0, /* tp_as_buffer */ + Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC, /* tp_flags */ + method_doc, /* tp_doc */ + (traverseproc)method_traverse, /* tp_traverse */ + 0, /* tp_clear */ + method_richcompare, /* tp_richcompare */ + offsetof(PyMethodObject, im_weakreflist), /* tp_weaklistoffset */ + 0, /* tp_iter */ + 0, /* tp_iternext */ + 0, /* tp_methods */ + method_memberlist, /* tp_members */ + method_getset, /* tp_getset */ + 0, /* tp_base */ + 0, /* tp_dict */ + method_descr_get, /* tp_descr_get */ + 0, /* tp_descr_set */ + 0, /* tp_dictoffset */ + 0, /* tp_init */ + 0, /* tp_alloc */ + method_new, /* tp_new */ }; /* Clear out the free list */ @@ -381,22 +381,22 @@ int PyMethod_ClearFreeList(void) { - int freelist_size = numfree; - - while (free_list) { - PyMethodObject *im = free_list; - free_list = (PyMethodObject *)(im->im_self); - PyObject_GC_Del(im); - numfree--; - } - assert(numfree == 0); - return freelist_size; + int freelist_size = numfree; + + while (free_list) { + PyMethodObject *im = free_list; + free_list = (PyMethodObject *)(im->im_self); + PyObject_GC_Del(im); + numfree--; + } + assert(numfree == 0); + return freelist_size; } void PyMethod_Fini(void) { - (void)PyMethod_ClearFreeList(); + (void)PyMethod_ClearFreeList(); } /* ------------------------------------------------------------------------ @@ -405,176 +405,176 @@ PyObject * PyInstanceMethod_New(PyObject *func) { - PyInstanceMethodObject *method; - method = PyObject_GC_New(PyInstanceMethodObject, - &PyInstanceMethod_Type); - if (method == NULL) return NULL; - Py_INCREF(func); - method->func = func; - _PyObject_GC_TRACK(method); - return (PyObject *)method; + PyInstanceMethodObject *method; + method = PyObject_GC_New(PyInstanceMethodObject, + &PyInstanceMethod_Type); + if (method == NULL) return NULL; + Py_INCREF(func); + method->func = func; + _PyObject_GC_TRACK(method); + return (PyObject *)method; } PyObject * PyInstanceMethod_Function(PyObject *im) { - if (!PyInstanceMethod_Check(im)) { - PyErr_BadInternalCall(); - return NULL; - } - return PyInstanceMethod_GET_FUNCTION(im); + if (!PyInstanceMethod_Check(im)) { + PyErr_BadInternalCall(); + return NULL; + } + return PyInstanceMethod_GET_FUNCTION(im); } #define IMO_OFF(x) offsetof(PyInstanceMethodObject, x) static PyMemberDef instancemethod_memberlist[] = { - {"__func__", T_OBJECT, IMO_OFF(func), READONLY|RESTRICTED, - "the function (or other callable) implementing a method"}, - {NULL} /* Sentinel */ + {"__func__", T_OBJECT, IMO_OFF(func), READONLY|RESTRICTED, + "the function (or other callable) implementing a method"}, + {NULL} /* Sentinel */ }; static PyObject * instancemethod_get_doc(PyObject *self, void *context) { - static PyObject *docstr; - if (docstr == NULL) { - docstr = PyUnicode_InternFromString("__doc__"); - if (docstr == NULL) - return NULL; - } - return PyObject_GetAttr(PyInstanceMethod_GET_FUNCTION(self), docstr); + static PyObject *docstr; + if (docstr == NULL) { + docstr = PyUnicode_InternFromString("__doc__"); + if (docstr == NULL) + return NULL; + } + return PyObject_GetAttr(PyInstanceMethod_GET_FUNCTION(self), docstr); } static PyGetSetDef instancemethod_getset[] = { - {"__doc__", (getter)instancemethod_get_doc, NULL, NULL}, - {0} + {"__doc__", (getter)instancemethod_get_doc, NULL, NULL}, + {0} }; static PyObject * instancemethod_getattro(PyObject *self, PyObject *name) { - PyTypeObject *tp = self->ob_type; - PyObject *descr = NULL; + PyTypeObject *tp = self->ob_type; + PyObject *descr = NULL; - if (tp->tp_dict == NULL) { - if (PyType_Ready(tp) < 0) - return NULL; - } - descr = _PyType_Lookup(tp, name); - - if (descr != NULL) { - descrgetfunc f = TP_DESCR_GET(descr->ob_type); - if (f != NULL) - return f(descr, self, (PyObject *)self->ob_type); - else { - Py_INCREF(descr); - return descr; - } - } + if (tp->tp_dict == NULL) { + if (PyType_Ready(tp) < 0) + return NULL; + } + descr = _PyType_Lookup(tp, name); + + if (descr != NULL) { + descrgetfunc f = TP_DESCR_GET(descr->ob_type); + if (f != NULL) + return f(descr, self, (PyObject *)self->ob_type); + else { + Py_INCREF(descr); + return descr; + } + } - return PyObject_GetAttr(PyInstanceMethod_GET_FUNCTION(self), name); + return PyObject_GetAttr(PyInstanceMethod_GET_FUNCTION(self), name); } static void instancemethod_dealloc(PyObject *self) { - _PyObject_GC_UNTRACK(self); - Py_DECREF(PyInstanceMethod_GET_FUNCTION(self)); - PyObject_GC_Del(self); + _PyObject_GC_UNTRACK(self); + Py_DECREF(PyInstanceMethod_GET_FUNCTION(self)); + PyObject_GC_Del(self); } static int instancemethod_traverse(PyObject *self, visitproc visit, void *arg) { - Py_VISIT(PyInstanceMethod_GET_FUNCTION(self)); - return 0; + Py_VISIT(PyInstanceMethod_GET_FUNCTION(self)); + return 0; } static PyObject * instancemethod_call(PyObject *self, PyObject *arg, PyObject *kw) { - return PyObject_Call(PyMethod_GET_FUNCTION(self), arg, kw); + return PyObject_Call(PyMethod_GET_FUNCTION(self), arg, kw); } static PyObject * instancemethod_descr_get(PyObject *descr, PyObject *obj, PyObject *type) { - register PyObject *func = PyInstanceMethod_GET_FUNCTION(descr); - if (obj == NULL) { - Py_INCREF(func); - return func; - } - else - return PyMethod_New(func, obj); + register PyObject *func = PyInstanceMethod_GET_FUNCTION(descr); + if (obj == NULL) { + Py_INCREF(func); + return func; + } + else + return PyMethod_New(func, obj); } static PyObject * instancemethod_richcompare(PyObject *self, PyObject *other, int op) { - PyInstanceMethodObject *a, *b; - PyObject *res; - int eq; - - if ((op != Py_EQ && op != Py_NE) || - !PyInstanceMethod_Check(self) || - !PyInstanceMethod_Check(other)) - { - Py_INCREF(Py_NotImplemented); - return Py_NotImplemented; - } - a = (PyInstanceMethodObject *)self; - b = (PyInstanceMethodObject *)other; - eq = PyObject_RichCompareBool(a->func, b->func, Py_EQ); - if (eq < 0) - return NULL; - if (op == Py_EQ) - res = eq ? Py_True : Py_False; - else - res = eq ? Py_False : Py_True; - Py_INCREF(res); - return res; + PyInstanceMethodObject *a, *b; + PyObject *res; + int eq; + + if ((op != Py_EQ && op != Py_NE) || + !PyInstanceMethod_Check(self) || + !PyInstanceMethod_Check(other)) + { + Py_INCREF(Py_NotImplemented); + return Py_NotImplemented; + } + a = (PyInstanceMethodObject *)self; + b = (PyInstanceMethodObject *)other; + eq = PyObject_RichCompareBool(a->func, b->func, Py_EQ); + if (eq < 0) + return NULL; + if (op == Py_EQ) + res = eq ? Py_True : Py_False; + else + res = eq ? Py_False : Py_True; + Py_INCREF(res); + return res; } static PyObject * instancemethod_repr(PyObject *self) { - PyObject *func = PyInstanceMethod_Function(self); - PyObject *funcname = NULL , *result = NULL; - char *defname = "?"; - - if (func == NULL) { - PyErr_BadInternalCall(); - return NULL; - } - - funcname = PyObject_GetAttrString(func, "__name__"); - if (funcname == NULL) { - if (!PyErr_ExceptionMatches(PyExc_AttributeError)) - return NULL; - PyErr_Clear(); - } - else if (!PyUnicode_Check(funcname)) { - Py_DECREF(funcname); - funcname = NULL; - } + PyObject *func = PyInstanceMethod_Function(self); + PyObject *funcname = NULL , *result = NULL; + char *defname = "?"; + + if (func == NULL) { + PyErr_BadInternalCall(); + return NULL; + } + + funcname = PyObject_GetAttrString(func, "__name__"); + if (funcname == NULL) { + if (!PyErr_ExceptionMatches(PyExc_AttributeError)) + return NULL; + PyErr_Clear(); + } + else if (!PyUnicode_Check(funcname)) { + Py_DECREF(funcname); + funcname = NULL; + } - result = PyUnicode_FromFormat("", - funcname, defname, self); + result = PyUnicode_FromFormat("", + funcname, defname, self); - Py_XDECREF(funcname); - return result; + Py_XDECREF(funcname); + return result; } /* static long instancemethod_hash(PyObject *self) { - long x, y; - x = (long)self; - y = PyObject_Hash(PyInstanceMethod_GET_FUNCTION(self)); - if (y == -1) - return -1; - x = x ^ y; - if (x == -1) - x = -2; - return x; + long x, y; + x = (long)self; + y = PyObject_Hash(PyInstanceMethod_GET_FUNCTION(self)); + if (y == -1) + return -1; + x = x ^ y; + if (x == -1) + x = -2; + return x; } */ @@ -586,59 +586,59 @@ static PyObject * instancemethod_new(PyTypeObject* type, PyObject* args, PyObject *kw) { - PyObject *func; + PyObject *func; - if (!_PyArg_NoKeywords("instancemethod", kw)) - return NULL; - if (!PyArg_UnpackTuple(args, "instancemethod", 1, 1, &func)) - return NULL; - if (!PyCallable_Check(func)) { - PyErr_SetString(PyExc_TypeError, - "first argument must be callable"); - return NULL; - } + if (!_PyArg_NoKeywords("instancemethod", kw)) + return NULL; + if (!PyArg_UnpackTuple(args, "instancemethod", 1, 1, &func)) + return NULL; + if (!PyCallable_Check(func)) { + PyErr_SetString(PyExc_TypeError, + "first argument must be callable"); + return NULL; + } - return PyInstanceMethod_New(func); + return PyInstanceMethod_New(func); } PyTypeObject PyInstanceMethod_Type = { - PyVarObject_HEAD_INIT(&PyType_Type, 0) - "instancemethod", /* tp_name */ - sizeof(PyInstanceMethodObject), /* tp_basicsize */ - 0, /* tp_itemsize */ - instancemethod_dealloc, /* tp_dealloc */ - 0, /* tp_print */ - 0, /* tp_getattr */ - 0, /* tp_setattr */ - 0, /* tp_reserved */ - (reprfunc)instancemethod_repr, /* tp_repr */ - 0, /* tp_as_number */ - 0, /* tp_as_sequence */ - 0, /* tp_as_mapping */ - 0, /*(hashfunc)instancemethod_hash, tp_hash */ - instancemethod_call, /* tp_call */ - 0, /* tp_str */ - instancemethod_getattro, /* tp_getattro */ - PyObject_GenericSetAttr, /* tp_setattro */ - 0, /* tp_as_buffer */ - Py_TPFLAGS_DEFAULT - | Py_TPFLAGS_HAVE_GC, /* tp_flags */ - instancemethod_doc, /* tp_doc */ - instancemethod_traverse, /* tp_traverse */ - 0, /* tp_clear */ - instancemethod_richcompare, /* tp_richcompare */ - 0, /* tp_weaklistoffset */ - 0, /* tp_iter */ - 0, /* tp_iternext */ - 0, /* tp_methods */ - instancemethod_memberlist, /* tp_members */ - instancemethod_getset, /* tp_getset */ - 0, /* tp_base */ - 0, /* tp_dict */ - instancemethod_descr_get, /* tp_descr_get */ - 0, /* tp_descr_set */ - 0, /* tp_dictoffset */ - 0, /* tp_init */ - 0, /* tp_alloc */ - instancemethod_new, /* tp_new */ + PyVarObject_HEAD_INIT(&PyType_Type, 0) + "instancemethod", /* tp_name */ + sizeof(PyInstanceMethodObject), /* tp_basicsize */ + 0, /* tp_itemsize */ + instancemethod_dealloc, /* tp_dealloc */ + 0, /* tp_print */ + 0, /* tp_getattr */ + 0, /* tp_setattr */ + 0, /* tp_reserved */ + (reprfunc)instancemethod_repr, /* tp_repr */ + 0, /* tp_as_number */ + 0, /* tp_as_sequence */ + 0, /* tp_as_mapping */ + 0, /*(hashfunc)instancemethod_hash, tp_hash */ + instancemethod_call, /* tp_call */ + 0, /* tp_str */ + instancemethod_getattro, /* tp_getattro */ + PyObject_GenericSetAttr, /* tp_setattro */ + 0, /* tp_as_buffer */ + Py_TPFLAGS_DEFAULT + | Py_TPFLAGS_HAVE_GC, /* tp_flags */ + instancemethod_doc, /* tp_doc */ + instancemethod_traverse, /* tp_traverse */ + 0, /* tp_clear */ + instancemethod_richcompare, /* tp_richcompare */ + 0, /* tp_weaklistoffset */ + 0, /* tp_iter */ + 0, /* tp_iternext */ + 0, /* tp_methods */ + instancemethod_memberlist, /* tp_members */ + instancemethod_getset, /* tp_getset */ + 0, /* tp_base */ + 0, /* tp_dict */ + instancemethod_descr_get, /* tp_descr_get */ + 0, /* tp_descr_set */ + 0, /* tp_dictoffset */ + 0, /* tp_init */ + 0, /* tp_alloc */ + instancemethod_new, /* tp_new */ }; Modified: python/branches/release31-maint/Objects/codeobject.c ============================================================================== --- python/branches/release31-maint/Objects/codeobject.c (original) +++ python/branches/release31-maint/Objects/codeobject.c Sun May 9 18:14:21 2010 @@ -3,135 +3,135 @@ #include "structmember.h" #define NAME_CHARS \ - "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ_abcdefghijklmnopqrstuvwxyz" + "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ_abcdefghijklmnopqrstuvwxyz" /* all_name_chars(s): true iff all chars in s are valid NAME_CHARS */ static int all_name_chars(Py_UNICODE *s) { - static char ok_name_char[256]; - static unsigned char *name_chars = (unsigned char *)NAME_CHARS; + static char ok_name_char[256]; + static unsigned char *name_chars = (unsigned char *)NAME_CHARS; - if (ok_name_char[*name_chars] == 0) { - unsigned char *p; - for (p = name_chars; *p; p++) - ok_name_char[*p] = 1; - } - while (*s) { - if (*s >= 128) - return 0; - if (ok_name_char[*s++] == 0) - return 0; - } - return 1; + if (ok_name_char[*name_chars] == 0) { + unsigned char *p; + for (p = name_chars; *p; p++) + ok_name_char[*p] = 1; + } + while (*s) { + if (*s >= 128) + return 0; + if (ok_name_char[*s++] == 0) + return 0; + } + return 1; } static void intern_strings(PyObject *tuple) { - Py_ssize_t i; + Py_ssize_t i; - for (i = PyTuple_GET_SIZE(tuple); --i >= 0; ) { - PyObject *v = PyTuple_GET_ITEM(tuple, i); - if (v == NULL || !PyUnicode_CheckExact(v)) { - Py_FatalError("non-string found in code slot"); - } - PyUnicode_InternInPlace(&PyTuple_GET_ITEM(tuple, i)); - } + for (i = PyTuple_GET_SIZE(tuple); --i >= 0; ) { + PyObject *v = PyTuple_GET_ITEM(tuple, i); + if (v == NULL || !PyUnicode_CheckExact(v)) { + Py_FatalError("non-string found in code slot"); + } + PyUnicode_InternInPlace(&PyTuple_GET_ITEM(tuple, i)); + } } PyCodeObject * PyCode_New(int argcount, int kwonlyargcount, - int nlocals, int stacksize, int flags, - PyObject *code, PyObject *consts, PyObject *names, - PyObject *varnames, PyObject *freevars, PyObject *cellvars, - PyObject *filename, PyObject *name, int firstlineno, - PyObject *lnotab) -{ - PyCodeObject *co; - Py_ssize_t i; - - /* Check argument types */ - if (argcount < 0 || nlocals < 0 || - code == NULL || - consts == NULL || !PyTuple_Check(consts) || - names == NULL || !PyTuple_Check(names) || - varnames == NULL || !PyTuple_Check(varnames) || - freevars == NULL || !PyTuple_Check(freevars) || - cellvars == NULL || !PyTuple_Check(cellvars) || - name == NULL || !PyUnicode_Check(name) || - filename == NULL || !PyUnicode_Check(filename) || - lnotab == NULL || !PyBytes_Check(lnotab) || - !PyObject_CheckReadBuffer(code)) { - PyErr_BadInternalCall(); - return NULL; - } - intern_strings(names); - intern_strings(varnames); - intern_strings(freevars); - intern_strings(cellvars); - /* Intern selected string constants */ - for (i = PyTuple_Size(consts); --i >= 0; ) { - PyObject *v = PyTuple_GetItem(consts, i); - if (!PyUnicode_Check(v)) - continue; - if (!all_name_chars(PyUnicode_AS_UNICODE(v))) - continue; - PyUnicode_InternInPlace(&PyTuple_GET_ITEM(consts, i)); - } - co = PyObject_NEW(PyCodeObject, &PyCode_Type); - if (co != NULL) { - co->co_argcount = argcount; - co->co_kwonlyargcount = kwonlyargcount; - co->co_nlocals = nlocals; - co->co_stacksize = stacksize; - co->co_flags = flags; - Py_INCREF(code); - co->co_code = code; - Py_INCREF(consts); - co->co_consts = consts; - Py_INCREF(names); - co->co_names = names; - Py_INCREF(varnames); - co->co_varnames = varnames; - Py_INCREF(freevars); - co->co_freevars = freevars; - Py_INCREF(cellvars); - co->co_cellvars = cellvars; - Py_INCREF(filename); - co->co_filename = filename; - Py_INCREF(name); - co->co_name = name; - co->co_firstlineno = firstlineno; - Py_INCREF(lnotab); - co->co_lnotab = lnotab; - co->co_zombieframe = NULL; - } - return co; + int nlocals, int stacksize, int flags, + PyObject *code, PyObject *consts, PyObject *names, + PyObject *varnames, PyObject *freevars, PyObject *cellvars, + PyObject *filename, PyObject *name, int firstlineno, + PyObject *lnotab) +{ + PyCodeObject *co; + Py_ssize_t i; + + /* Check argument types */ + if (argcount < 0 || nlocals < 0 || + code == NULL || + consts == NULL || !PyTuple_Check(consts) || + names == NULL || !PyTuple_Check(names) || + varnames == NULL || !PyTuple_Check(varnames) || + freevars == NULL || !PyTuple_Check(freevars) || + cellvars == NULL || !PyTuple_Check(cellvars) || + name == NULL || !PyUnicode_Check(name) || + filename == NULL || !PyUnicode_Check(filename) || + lnotab == NULL || !PyBytes_Check(lnotab) || + !PyObject_CheckReadBuffer(code)) { + PyErr_BadInternalCall(); + return NULL; + } + intern_strings(names); + intern_strings(varnames); + intern_strings(freevars); + intern_strings(cellvars); + /* Intern selected string constants */ + for (i = PyTuple_Size(consts); --i >= 0; ) { + PyObject *v = PyTuple_GetItem(consts, i); + if (!PyUnicode_Check(v)) + continue; + if (!all_name_chars(PyUnicode_AS_UNICODE(v))) + continue; + PyUnicode_InternInPlace(&PyTuple_GET_ITEM(consts, i)); + } + co = PyObject_NEW(PyCodeObject, &PyCode_Type); + if (co != NULL) { + co->co_argcount = argcount; + co->co_kwonlyargcount = kwonlyargcount; + co->co_nlocals = nlocals; + co->co_stacksize = stacksize; + co->co_flags = flags; + Py_INCREF(code); + co->co_code = code; + Py_INCREF(consts); + co->co_consts = consts; + Py_INCREF(names); + co->co_names = names; + Py_INCREF(varnames); + co->co_varnames = varnames; + Py_INCREF(freevars); + co->co_freevars = freevars; + Py_INCREF(cellvars); + co->co_cellvars = cellvars; + Py_INCREF(filename); + co->co_filename = filename; + Py_INCREF(name); + co->co_name = name; + co->co_firstlineno = firstlineno; + Py_INCREF(lnotab); + co->co_lnotab = lnotab; + co->co_zombieframe = NULL; + } + return co; } #define OFF(x) offsetof(PyCodeObject, x) static PyMemberDef code_memberlist[] = { - {"co_argcount", T_INT, OFF(co_argcount), READONLY}, - {"co_kwonlyargcount", T_INT, OFF(co_kwonlyargcount), READONLY}, - {"co_nlocals", T_INT, OFF(co_nlocals), READONLY}, - {"co_stacksize",T_INT, OFF(co_stacksize), READONLY}, - {"co_flags", T_INT, OFF(co_flags), READONLY}, - {"co_code", T_OBJECT, OFF(co_code), READONLY}, - {"co_consts", T_OBJECT, OFF(co_consts), READONLY}, - {"co_names", T_OBJECT, OFF(co_names), READONLY}, - {"co_varnames", T_OBJECT, OFF(co_varnames), READONLY}, - {"co_freevars", T_OBJECT, OFF(co_freevars), READONLY}, - {"co_cellvars", T_OBJECT, OFF(co_cellvars), READONLY}, - {"co_filename", T_OBJECT, OFF(co_filename), READONLY}, - {"co_name", T_OBJECT, OFF(co_name), READONLY}, - {"co_firstlineno", T_INT, OFF(co_firstlineno), READONLY}, - {"co_lnotab", T_OBJECT, OFF(co_lnotab), READONLY}, - {NULL} /* Sentinel */ + {"co_argcount", T_INT, OFF(co_argcount), READONLY}, + {"co_kwonlyargcount", T_INT, OFF(co_kwonlyargcount), READONLY}, + {"co_nlocals", T_INT, OFF(co_nlocals), READONLY}, + {"co_stacksize",T_INT, OFF(co_stacksize), READONLY}, + {"co_flags", T_INT, OFF(co_flags), READONLY}, + {"co_code", T_OBJECT, OFF(co_code), READONLY}, + {"co_consts", T_OBJECT, OFF(co_consts), READONLY}, + {"co_names", T_OBJECT, OFF(co_names), READONLY}, + {"co_varnames", T_OBJECT, OFF(co_varnames), READONLY}, + {"co_freevars", T_OBJECT, OFF(co_freevars), READONLY}, + {"co_cellvars", T_OBJECT, OFF(co_cellvars), READONLY}, + {"co_filename", T_OBJECT, OFF(co_filename), READONLY}, + {"co_name", T_OBJECT, OFF(co_name), READONLY}, + {"co_firstlineno", T_INT, OFF(co_firstlineno), READONLY}, + {"co_lnotab", T_OBJECT, OFF(co_lnotab), READONLY}, + {NULL} /* Sentinel */ }; /* Helper for code_new: return a shallow copy of a tuple that is @@ -140,42 +140,42 @@ static PyObject* validate_and_copy_tuple(PyObject *tup) { - PyObject *newtuple; - PyObject *item; - Py_ssize_t i, len; - - len = PyTuple_GET_SIZE(tup); - newtuple = PyTuple_New(len); - if (newtuple == NULL) - return NULL; - - for (i = 0; i < len; i++) { - item = PyTuple_GET_ITEM(tup, i); - if (PyUnicode_CheckExact(item)) { - Py_INCREF(item); - } - else if (!PyUnicode_Check(item)) { - PyErr_Format( - PyExc_TypeError, - "name tuples must contain only " - "strings, not '%.500s'", - item->ob_type->tp_name); - Py_DECREF(newtuple); - return NULL; - } - else { - item = PyUnicode_FromUnicode( - PyUnicode_AS_UNICODE(item), - PyUnicode_GET_SIZE(item)); - if (item == NULL) { - Py_DECREF(newtuple); - return NULL; - } - } - PyTuple_SET_ITEM(newtuple, i, item); - } + PyObject *newtuple; + PyObject *item; + Py_ssize_t i, len; + + len = PyTuple_GET_SIZE(tup); + newtuple = PyTuple_New(len); + if (newtuple == NULL) + return NULL; + + for (i = 0; i < len; i++) { + item = PyTuple_GET_ITEM(tup, i); + if (PyUnicode_CheckExact(item)) { + Py_INCREF(item); + } + else if (!PyUnicode_Check(item)) { + PyErr_Format( + PyExc_TypeError, + "name tuples must contain only " + "strings, not '%.500s'", + item->ob_type->tp_name); + Py_DECREF(newtuple); + return NULL; + } + else { + item = PyUnicode_FromUnicode( + PyUnicode_AS_UNICODE(item), + PyUnicode_GET_SIZE(item)); + if (item == NULL) { + Py_DECREF(newtuple); + return NULL; + } + } + PyTuple_SET_ITEM(newtuple, i, item); + } - return newtuple; + return newtuple; } PyDoc_STRVAR(code_doc, @@ -188,247 +188,247 @@ static PyObject * code_new(PyTypeObject *type, PyObject *args, PyObject *kw) { - int argcount; - int kwonlyargcount; - int nlocals; - int stacksize; - int flags; - PyObject *co = NULL; - PyObject *code; - PyObject *consts; - PyObject *names, *ournames = NULL; - PyObject *varnames, *ourvarnames = NULL; - PyObject *freevars = NULL, *ourfreevars = NULL; - PyObject *cellvars = NULL, *ourcellvars = NULL; - PyObject *filename; - PyObject *name; - int firstlineno; - PyObject *lnotab; - - if (!PyArg_ParseTuple(args, "iiiiiSO!O!O!UUiS|O!O!:code", - &argcount, &kwonlyargcount, - &nlocals, &stacksize, &flags, - &code, - &PyTuple_Type, &consts, - &PyTuple_Type, &names, - &PyTuple_Type, &varnames, - &filename, &name, - &firstlineno, &lnotab, - &PyTuple_Type, &freevars, - &PyTuple_Type, &cellvars)) - return NULL; - - if (argcount < 0) { - PyErr_SetString( - PyExc_ValueError, - "code: argcount must not be negative"); - goto cleanup; - } - - if (kwonlyargcount < 0) { - PyErr_SetString( - PyExc_ValueError, - "code: kwonlyargcount must not be negative"); - goto cleanup; - } - if (nlocals < 0) { - PyErr_SetString( - PyExc_ValueError, - "code: nlocals must not be negative"); - goto cleanup; - } - - ournames = validate_and_copy_tuple(names); - if (ournames == NULL) - goto cleanup; - ourvarnames = validate_and_copy_tuple(varnames); - if (ourvarnames == NULL) - goto cleanup; - if (freevars) - ourfreevars = validate_and_copy_tuple(freevars); - else - ourfreevars = PyTuple_New(0); - if (ourfreevars == NULL) - goto cleanup; - if (cellvars) - ourcellvars = validate_and_copy_tuple(cellvars); - else - ourcellvars = PyTuple_New(0); - if (ourcellvars == NULL) - goto cleanup; - - co = (PyObject *)PyCode_New(argcount, kwonlyargcount, - nlocals, stacksize, flags, - code, consts, ournames, ourvarnames, - ourfreevars, ourcellvars, filename, - name, firstlineno, lnotab); + int argcount; + int kwonlyargcount; + int nlocals; + int stacksize; + int flags; + PyObject *co = NULL; + PyObject *code; + PyObject *consts; + PyObject *names, *ournames = NULL; + PyObject *varnames, *ourvarnames = NULL; + PyObject *freevars = NULL, *ourfreevars = NULL; + PyObject *cellvars = NULL, *ourcellvars = NULL; + PyObject *filename; + PyObject *name; + int firstlineno; + PyObject *lnotab; + + if (!PyArg_ParseTuple(args, "iiiiiSO!O!O!UUiS|O!O!:code", + &argcount, &kwonlyargcount, + &nlocals, &stacksize, &flags, + &code, + &PyTuple_Type, &consts, + &PyTuple_Type, &names, + &PyTuple_Type, &varnames, + &filename, &name, + &firstlineno, &lnotab, + &PyTuple_Type, &freevars, + &PyTuple_Type, &cellvars)) + return NULL; + + if (argcount < 0) { + PyErr_SetString( + PyExc_ValueError, + "code: argcount must not be negative"); + goto cleanup; + } + + if (kwonlyargcount < 0) { + PyErr_SetString( + PyExc_ValueError, + "code: kwonlyargcount must not be negative"); + goto cleanup; + } + if (nlocals < 0) { + PyErr_SetString( + PyExc_ValueError, + "code: nlocals must not be negative"); + goto cleanup; + } + + ournames = validate_and_copy_tuple(names); + if (ournames == NULL) + goto cleanup; + ourvarnames = validate_and_copy_tuple(varnames); + if (ourvarnames == NULL) + goto cleanup; + if (freevars) + ourfreevars = validate_and_copy_tuple(freevars); + else + ourfreevars = PyTuple_New(0); + if (ourfreevars == NULL) + goto cleanup; + if (cellvars) + ourcellvars = validate_and_copy_tuple(cellvars); + else + ourcellvars = PyTuple_New(0); + if (ourcellvars == NULL) + goto cleanup; + + co = (PyObject *)PyCode_New(argcount, kwonlyargcount, + nlocals, stacksize, flags, + code, consts, ournames, ourvarnames, + ourfreevars, ourcellvars, filename, + name, firstlineno, lnotab); cleanup: - Py_XDECREF(ournames); - Py_XDECREF(ourvarnames); - Py_XDECREF(ourfreevars); - Py_XDECREF(ourcellvars); - return co; + Py_XDECREF(ournames); + Py_XDECREF(ourvarnames); + Py_XDECREF(ourfreevars); + Py_XDECREF(ourcellvars); + return co; } static void code_dealloc(PyCodeObject *co) { - Py_XDECREF(co->co_code); - Py_XDECREF(co->co_consts); - Py_XDECREF(co->co_names); - Py_XDECREF(co->co_varnames); - Py_XDECREF(co->co_freevars); - Py_XDECREF(co->co_cellvars); - Py_XDECREF(co->co_filename); - Py_XDECREF(co->co_name); - Py_XDECREF(co->co_lnotab); - if (co->co_zombieframe != NULL) - PyObject_GC_Del(co->co_zombieframe); - PyObject_DEL(co); + Py_XDECREF(co->co_code); + Py_XDECREF(co->co_consts); + Py_XDECREF(co->co_names); + Py_XDECREF(co->co_varnames); + Py_XDECREF(co->co_freevars); + Py_XDECREF(co->co_cellvars); + Py_XDECREF(co->co_filename); + Py_XDECREF(co->co_name); + Py_XDECREF(co->co_lnotab); + if (co->co_zombieframe != NULL) + PyObject_GC_Del(co->co_zombieframe); + PyObject_DEL(co); } static PyObject * code_repr(PyCodeObject *co) { - int lineno = -1; - char *filename = "???"; + int lineno = -1; + char *filename = "???"; - if (co->co_firstlineno != 0) - lineno = co->co_firstlineno; - if (co->co_filename && PyUnicode_Check(co->co_filename)) - filename = _PyUnicode_AsString(co->co_filename); - return PyUnicode_FromFormat( - "", - co->co_name, co, filename, lineno); + if (co->co_firstlineno != 0) + lineno = co->co_firstlineno; + if (co->co_filename && PyUnicode_Check(co->co_filename)) + filename = _PyUnicode_AsString(co->co_filename); + return PyUnicode_FromFormat( + "", + co->co_name, co, filename, lineno); } static PyObject * code_richcompare(PyObject *self, PyObject *other, int op) { - PyCodeObject *co, *cp; - int eq; - PyObject *res; - - if ((op != Py_EQ && op != Py_NE) || - !PyCode_Check(self) || - !PyCode_Check(other)) { - Py_INCREF(Py_NotImplemented); - return Py_NotImplemented; - } - - co = (PyCodeObject *)self; - cp = (PyCodeObject *)other; - - eq = PyObject_RichCompareBool(co->co_name, cp->co_name, Py_EQ); - if (eq <= 0) goto unequal; - eq = co->co_argcount == cp->co_argcount; - if (!eq) goto unequal; - eq = co->co_kwonlyargcount == cp->co_kwonlyargcount; - if (!eq) goto unequal; - eq = co->co_nlocals == cp->co_nlocals; - if (!eq) goto unequal; - eq = co->co_flags == cp->co_flags; - if (!eq) goto unequal; - eq = co->co_firstlineno == cp->co_firstlineno; - if (!eq) goto unequal; - eq = PyObject_RichCompareBool(co->co_code, cp->co_code, Py_EQ); - if (eq <= 0) goto unequal; - eq = PyObject_RichCompareBool(co->co_consts, cp->co_consts, Py_EQ); - if (eq <= 0) goto unequal; - eq = PyObject_RichCompareBool(co->co_names, cp->co_names, Py_EQ); - if (eq <= 0) goto unequal; - eq = PyObject_RichCompareBool(co->co_varnames, cp->co_varnames, Py_EQ); - if (eq <= 0) goto unequal; - eq = PyObject_RichCompareBool(co->co_freevars, cp->co_freevars, Py_EQ); - if (eq <= 0) goto unequal; - eq = PyObject_RichCompareBool(co->co_cellvars, cp->co_cellvars, Py_EQ); - if (eq <= 0) goto unequal; - - if (op == Py_EQ) - res = Py_True; - else - res = Py_False; - goto done; + PyCodeObject *co, *cp; + int eq; + PyObject *res; + + if ((op != Py_EQ && op != Py_NE) || + !PyCode_Check(self) || + !PyCode_Check(other)) { + Py_INCREF(Py_NotImplemented); + return Py_NotImplemented; + } + + co = (PyCodeObject *)self; + cp = (PyCodeObject *)other; + + eq = PyObject_RichCompareBool(co->co_name, cp->co_name, Py_EQ); + if (eq <= 0) goto unequal; + eq = co->co_argcount == cp->co_argcount; + if (!eq) goto unequal; + eq = co->co_kwonlyargcount == cp->co_kwonlyargcount; + if (!eq) goto unequal; + eq = co->co_nlocals == cp->co_nlocals; + if (!eq) goto unequal; + eq = co->co_flags == cp->co_flags; + if (!eq) goto unequal; + eq = co->co_firstlineno == cp->co_firstlineno; + if (!eq) goto unequal; + eq = PyObject_RichCompareBool(co->co_code, cp->co_code, Py_EQ); + if (eq <= 0) goto unequal; + eq = PyObject_RichCompareBool(co->co_consts, cp->co_consts, Py_EQ); + if (eq <= 0) goto unequal; + eq = PyObject_RichCompareBool(co->co_names, cp->co_names, Py_EQ); + if (eq <= 0) goto unequal; + eq = PyObject_RichCompareBool(co->co_varnames, cp->co_varnames, Py_EQ); + if (eq <= 0) goto unequal; + eq = PyObject_RichCompareBool(co->co_freevars, cp->co_freevars, Py_EQ); + if (eq <= 0) goto unequal; + eq = PyObject_RichCompareBool(co->co_cellvars, cp->co_cellvars, Py_EQ); + if (eq <= 0) goto unequal; + + if (op == Py_EQ) + res = Py_True; + else + res = Py_False; + goto done; unequal: - if (eq < 0) - return NULL; - if (op == Py_NE) - res = Py_True; - else - res = Py_False; + if (eq < 0) + return NULL; + if (op == Py_NE) + res = Py_True; + else + res = Py_False; done: - Py_INCREF(res); - return res; + Py_INCREF(res); + return res; } static long code_hash(PyCodeObject *co) { - long h, h0, h1, h2, h3, h4, h5, h6; - h0 = PyObject_Hash(co->co_name); - if (h0 == -1) return -1; - h1 = PyObject_Hash(co->co_code); - if (h1 == -1) return -1; - h2 = PyObject_Hash(co->co_consts); - if (h2 == -1) return -1; - h3 = PyObject_Hash(co->co_names); - if (h3 == -1) return -1; - h4 = PyObject_Hash(co->co_varnames); - if (h4 == -1) return -1; - h5 = PyObject_Hash(co->co_freevars); - if (h5 == -1) return -1; - h6 = PyObject_Hash(co->co_cellvars); - if (h6 == -1) return -1; - h = h0 ^ h1 ^ h2 ^ h3 ^ h4 ^ h5 ^ h6 ^ - co->co_argcount ^ co->co_kwonlyargcount ^ - co->co_nlocals ^ co->co_flags; - if (h == -1) h = -2; - return h; + long h, h0, h1, h2, h3, h4, h5, h6; + h0 = PyObject_Hash(co->co_name); + if (h0 == -1) return -1; + h1 = PyObject_Hash(co->co_code); + if (h1 == -1) return -1; + h2 = PyObject_Hash(co->co_consts); + if (h2 == -1) return -1; + h3 = PyObject_Hash(co->co_names); + if (h3 == -1) return -1; + h4 = PyObject_Hash(co->co_varnames); + if (h4 == -1) return -1; + h5 = PyObject_Hash(co->co_freevars); + if (h5 == -1) return -1; + h6 = PyObject_Hash(co->co_cellvars); + if (h6 == -1) return -1; + h = h0 ^ h1 ^ h2 ^ h3 ^ h4 ^ h5 ^ h6 ^ + co->co_argcount ^ co->co_kwonlyargcount ^ + co->co_nlocals ^ co->co_flags; + if (h == -1) h = -2; + return h; } /* XXX code objects need to participate in GC? */ PyTypeObject PyCode_Type = { - PyVarObject_HEAD_INIT(&PyType_Type, 0) - "code", - sizeof(PyCodeObject), - 0, - (destructor)code_dealloc, /* tp_dealloc */ - 0, /* tp_print */ - 0, /* tp_getattr */ - 0, /* tp_setattr */ - 0, /* tp_reserved */ - (reprfunc)code_repr, /* tp_repr */ - 0, /* tp_as_number */ - 0, /* tp_as_sequence */ - 0, /* tp_as_mapping */ - (hashfunc)code_hash, /* tp_hash */ - 0, /* tp_call */ - 0, /* tp_str */ - PyObject_GenericGetAttr, /* tp_getattro */ - 0, /* tp_setattro */ - 0, /* tp_as_buffer */ - Py_TPFLAGS_DEFAULT, /* tp_flags */ - code_doc, /* tp_doc */ - 0, /* tp_traverse */ - 0, /* tp_clear */ - code_richcompare, /* tp_richcompare */ - 0, /* tp_weaklistoffset */ - 0, /* tp_iter */ - 0, /* tp_iternext */ - 0, /* tp_methods */ - code_memberlist, /* tp_members */ - 0, /* tp_getset */ - 0, /* tp_base */ - 0, /* tp_dict */ - 0, /* tp_descr_get */ - 0, /* tp_descr_set */ - 0, /* tp_dictoffset */ - 0, /* tp_init */ - 0, /* tp_alloc */ - code_new, /* tp_new */ + PyVarObject_HEAD_INIT(&PyType_Type, 0) + "code", + sizeof(PyCodeObject), + 0, + (destructor)code_dealloc, /* tp_dealloc */ + 0, /* tp_print */ + 0, /* tp_getattr */ + 0, /* tp_setattr */ + 0, /* tp_reserved */ + (reprfunc)code_repr, /* tp_repr */ + 0, /* tp_as_number */ + 0, /* tp_as_sequence */ + 0, /* tp_as_mapping */ + (hashfunc)code_hash, /* tp_hash */ + 0, /* tp_call */ + 0, /* tp_str */ + PyObject_GenericGetAttr, /* tp_getattro */ + 0, /* tp_setattro */ + 0, /* tp_as_buffer */ + Py_TPFLAGS_DEFAULT, /* tp_flags */ + code_doc, /* tp_doc */ + 0, /* tp_traverse */ + 0, /* tp_clear */ + code_richcompare, /* tp_richcompare */ + 0, /* tp_weaklistoffset */ + 0, /* tp_iter */ + 0, /* tp_iternext */ + 0, /* tp_methods */ + code_memberlist, /* tp_members */ + 0, /* tp_getset */ + 0, /* tp_base */ + 0, /* tp_dict */ + 0, /* tp_descr_get */ + 0, /* tp_descr_set */ + 0, /* tp_dictoffset */ + 0, /* tp_init */ + 0, /* tp_alloc */ + code_new, /* tp_new */ }; /* All about c_lnotab. @@ -441,9 +441,9 @@ pairs. The details are important and delicate, best illustrated by example: byte code offset source code line number - 0 1 - 6 2 - 50 7 + 0 1 + 6 2 + 50 7 350 307 361 308 @@ -463,10 +463,10 @@ lineno = addr = 0 for addr_incr, line_incr in c_lnotab: - addr += addr_incr - if addr > A: - return lineno - lineno += line_incr + addr += addr_incr + if addr > A: + return lineno + lineno += line_incr In order for this to work, when the addr field increments by more than 255, the line # increment in each pair generated must be 0 until the remaining addr @@ -478,149 +478,149 @@ int PyCode_Addr2Line(PyCodeObject *co, int addrq) { - int size = PyBytes_Size(co->co_lnotab) / 2; - unsigned char *p = (unsigned char*)PyBytes_AsString(co->co_lnotab); - int line = co->co_firstlineno; - int addr = 0; - while (--size >= 0) { - addr += *p++; - if (addr > addrq) - break; - line += *p++; - } - return line; + int size = PyBytes_Size(co->co_lnotab) / 2; + unsigned char *p = (unsigned char*)PyBytes_AsString(co->co_lnotab); + int line = co->co_firstlineno; + int addr = 0; + while (--size >= 0) { + addr += *p++; + if (addr > addrq) + break; + line += *p++; + } + return line; } -/* +/* Check whether the current instruction is at the start of a line. */ - /* The theory of SET_LINENO-less tracing. + /* The theory of SET_LINENO-less tracing. - In a nutshell, we use the co_lnotab field of the code object - to tell when execution has moved onto a different line. + In a nutshell, we use the co_lnotab field of the code object + to tell when execution has moved onto a different line. - As mentioned above, the basic idea is so set things up so - that + As mentioned above, the basic idea is so set things up so + that - *instr_lb <= frame->f_lasti < *instr_ub - - is true so long as execution does not change lines. - - This is all fairly simple. Digging the information out of - co_lnotab takes some work, but is conceptually clear. - - Somewhat harder to explain is why we don't *always* call the - line trace function when the above test fails. - - Consider this code: - - 1: def f(a): - 2: if a: - 3: print 1 - 4: else: - 5: print 2 - - which compiles to this: - - 2 0 LOAD_FAST 0 (a) - 3 JUMP_IF_FALSE 9 (to 15) - 6 POP_TOP - - 3 7 LOAD_CONST 1 (1) - 10 PRINT_ITEM - 11 PRINT_NEWLINE - 12 JUMP_FORWARD 6 (to 21) - >> 15 POP_TOP - - 5 16 LOAD_CONST 2 (2) - 19 PRINT_ITEM - 20 PRINT_NEWLINE - >> 21 LOAD_CONST 0 (None) - 24 RETURN_VALUE - - If 'a' is false, execution will jump to instruction at offset - 15 and the co_lnotab will claim that execution has moved to - line 3. This is at best misleading. In this case we could - associate the POP_TOP with line 4, but that doesn't make - sense in all cases (I think). - - What we do is only call the line trace function if the co_lnotab - indicates we have jumped to the *start* of a line, i.e. if the - current instruction offset matches the offset given for the - start of a line by the co_lnotab. - - This also takes care of the situation where 'a' is true. - Execution will jump from instruction offset 12 to offset 21. - Then the co_lnotab would imply that execution has moved to line - 5, which is again misleading. - - Why do we set f_lineno when tracing? Well, consider the code - above when 'a' is true. If stepping through this with 'n' in - pdb, you would stop at line 1 with a "call" type event, then - line events on lines 2 and 3, then a "return" type event -- but - you would be shown line 5 during this event. This is a change - from the behaviour in 2.2 and before, and I've found it - confusing in practice. By setting and using f_lineno when - tracing, one can report a line number different from that - suggested by f_lasti on this one occasion where it's desirable. - */ + *instr_lb <= frame->f_lasti < *instr_ub + + is true so long as execution does not change lines. + + This is all fairly simple. Digging the information out of + co_lnotab takes some work, but is conceptually clear. + + Somewhat harder to explain is why we don't *always* call the + line trace function when the above test fails. + + Consider this code: + + 1: def f(a): + 2: if a: + 3: print 1 + 4: else: + 5: print 2 + + which compiles to this: + + 2 0 LOAD_FAST 0 (a) + 3 JUMP_IF_FALSE 9 (to 15) + 6 POP_TOP + + 3 7 LOAD_CONST 1 (1) + 10 PRINT_ITEM + 11 PRINT_NEWLINE + 12 JUMP_FORWARD 6 (to 21) + >> 15 POP_TOP + + 5 16 LOAD_CONST 2 (2) + 19 PRINT_ITEM + 20 PRINT_NEWLINE + >> 21 LOAD_CONST 0 (None) + 24 RETURN_VALUE + + If 'a' is false, execution will jump to instruction at offset + 15 and the co_lnotab will claim that execution has moved to + line 3. This is at best misleading. In this case we could + associate the POP_TOP with line 4, but that doesn't make + sense in all cases (I think). + + What we do is only call the line trace function if the co_lnotab + indicates we have jumped to the *start* of a line, i.e. if the + current instruction offset matches the offset given for the + start of a line by the co_lnotab. + + This also takes care of the situation where 'a' is true. + Execution will jump from instruction offset 12 to offset 21. + Then the co_lnotab would imply that execution has moved to line + 5, which is again misleading. + + Why do we set f_lineno when tracing? Well, consider the code + above when 'a' is true. If stepping through this with 'n' in + pdb, you would stop at line 1 with a "call" type event, then + line events on lines 2 and 3, then a "return" type event -- but + you would be shown line 5 during this event. This is a change + from the behaviour in 2.2 and before, and I've found it + confusing in practice. By setting and using f_lineno when + tracing, one can report a line number different from that + suggested by f_lasti on this one occasion where it's desirable. + */ -int +int PyCode_CheckLineNumber(PyCodeObject* co, int lasti, PyAddrPair *bounds) { - int size, addr, line; - unsigned char* p; - - p = (unsigned char*)PyBytes_AS_STRING(co->co_lnotab); - size = PyBytes_GET_SIZE(co->co_lnotab) / 2; + int size, addr, line; + unsigned char* p; - addr = 0; - line = co->co_firstlineno; - assert(line > 0); - - /* possible optimization: if f->f_lasti == instr_ub - (likely to be a common case) then we already know - instr_lb -- if we stored the matching value of p - somwhere we could skip the first while loop. */ - - /* see comments in compile.c for the description of - co_lnotab. A point to remember: increments to p - should come in pairs -- although we don't care about - the line increments here, treating them as byte - increments gets confusing, to say the least. */ - - bounds->ap_lower = 0; - while (size > 0) { - if (addr + *p > lasti) - break; - addr += *p++; - if (*p) - bounds->ap_lower = addr; - line += *p++; - --size; - } + p = (unsigned char*)PyBytes_AS_STRING(co->co_lnotab); + size = PyBytes_GET_SIZE(co->co_lnotab) / 2; - /* If lasti and addr don't match exactly, we don't want to - change the lineno slot on the frame or execute a trace - function. Return -1 instead. - */ - if (addr != lasti) - line = -1; - - if (size > 0) { - while (--size >= 0) { - addr += *p++; - if (*p++) - break; - } - bounds->ap_upper = addr; - } - else { - bounds->ap_upper = INT_MAX; + addr = 0; + line = co->co_firstlineno; + assert(line > 0); + + /* possible optimization: if f->f_lasti == instr_ub + (likely to be a common case) then we already know + instr_lb -- if we stored the matching value of p + somwhere we could skip the first while loop. */ + + /* see comments in compile.c for the description of + co_lnotab. A point to remember: increments to p + should come in pairs -- although we don't care about + the line increments here, treating them as byte + increments gets confusing, to say the least. */ + + bounds->ap_lower = 0; + while (size > 0) { + if (addr + *p > lasti) + break; + addr += *p++; + if (*p) + bounds->ap_lower = addr; + line += *p++; + --size; + } + + /* If lasti and addr don't match exactly, we don't want to + change the lineno slot on the frame or execute a trace + function. Return -1 instead. + */ + if (addr != lasti) + line = -1; + + if (size > 0) { + while (--size >= 0) { + addr += *p++; + if (*p++) + break; } + bounds->ap_upper = addr; + } + else { + bounds->ap_upper = INT_MAX; + } - return line; + return line; } Modified: python/branches/release31-maint/Objects/complexobject.c ============================================================================== --- python/branches/release31-maint/Objects/complexobject.c (original) +++ python/branches/release31-maint/Objects/complexobject.c Sun May 9 18:14:21 2010 @@ -21,375 +21,375 @@ Py_complex c_sum(Py_complex a, Py_complex b) { - Py_complex r; - r.real = a.real + b.real; - r.imag = a.imag + b.imag; - return r; + Py_complex r; + r.real = a.real + b.real; + r.imag = a.imag + b.imag; + return r; } Py_complex c_diff(Py_complex a, Py_complex b) { - Py_complex r; - r.real = a.real - b.real; - r.imag = a.imag - b.imag; - return r; + Py_complex r; + r.real = a.real - b.real; + r.imag = a.imag - b.imag; + return r; } Py_complex c_neg(Py_complex a) { - Py_complex r; - r.real = -a.real; - r.imag = -a.imag; - return r; + Py_complex r; + r.real = -a.real; + r.imag = -a.imag; + return r; } Py_complex c_prod(Py_complex a, Py_complex b) { - Py_complex r; - r.real = a.real*b.real - a.imag*b.imag; - r.imag = a.real*b.imag + a.imag*b.real; - return r; + Py_complex r; + r.real = a.real*b.real - a.imag*b.imag; + r.imag = a.real*b.imag + a.imag*b.real; + return r; } Py_complex c_quot(Py_complex a, Py_complex b) { - /****************************************************************** - This was the original algorithm. It's grossly prone to spurious - overflow and underflow errors. It also merrily divides by 0 despite - checking for that(!). The code still serves a doc purpose here, as - the algorithm following is a simple by-cases transformation of this - one: - - Py_complex r; - double d = b.real*b.real + b.imag*b.imag; - if (d == 0.) - errno = EDOM; - r.real = (a.real*b.real + a.imag*b.imag)/d; - r.imag = (a.imag*b.real - a.real*b.imag)/d; - return r; - ******************************************************************/ - - /* This algorithm is better, and is pretty obvious: first divide the - * numerators and denominator by whichever of {b.real, b.imag} has - * larger magnitude. The earliest reference I found was to CACM - * Algorithm 116 (Complex Division, Robert L. Smith, Stanford - * University). As usual, though, we're still ignoring all IEEE - * endcases. - */ - Py_complex r; /* the result */ - const double abs_breal = b.real < 0 ? -b.real : b.real; - const double abs_bimag = b.imag < 0 ? -b.imag : b.imag; - - if (abs_breal >= abs_bimag) { - /* divide tops and bottom by b.real */ - if (abs_breal == 0.0) { - errno = EDOM; - r.real = r.imag = 0.0; - } - else { - const double ratio = b.imag / b.real; - const double denom = b.real + b.imag * ratio; - r.real = (a.real + a.imag * ratio) / denom; - r.imag = (a.imag - a.real * ratio) / denom; - } - } - else { - /* divide tops and bottom by b.imag */ - const double ratio = b.real / b.imag; - const double denom = b.real * ratio + b.imag; - assert(b.imag != 0.0); - r.real = (a.real * ratio + a.imag) / denom; - r.imag = (a.imag * ratio - a.real) / denom; - } - return r; + /****************************************************************** + This was the original algorithm. It's grossly prone to spurious + overflow and underflow errors. It also merrily divides by 0 despite + checking for that(!). The code still serves a doc purpose here, as + the algorithm following is a simple by-cases transformation of this + one: + + Py_complex r; + double d = b.real*b.real + b.imag*b.imag; + if (d == 0.) + errno = EDOM; + r.real = (a.real*b.real + a.imag*b.imag)/d; + r.imag = (a.imag*b.real - a.real*b.imag)/d; + return r; + ******************************************************************/ + + /* This algorithm is better, and is pretty obvious: first divide the + * numerators and denominator by whichever of {b.real, b.imag} has + * larger magnitude. The earliest reference I found was to CACM + * Algorithm 116 (Complex Division, Robert L. Smith, Stanford + * University). As usual, though, we're still ignoring all IEEE + * endcases. + */ + Py_complex r; /* the result */ + const double abs_breal = b.real < 0 ? -b.real : b.real; + const double abs_bimag = b.imag < 0 ? -b.imag : b.imag; + + if (abs_breal >= abs_bimag) { + /* divide tops and bottom by b.real */ + if (abs_breal == 0.0) { + errno = EDOM; + r.real = r.imag = 0.0; + } + else { + const double ratio = b.imag / b.real; + const double denom = b.real + b.imag * ratio; + r.real = (a.real + a.imag * ratio) / denom; + r.imag = (a.imag - a.real * ratio) / denom; + } + } + else { + /* divide tops and bottom by b.imag */ + const double ratio = b.real / b.imag; + const double denom = b.real * ratio + b.imag; + assert(b.imag != 0.0); + r.real = (a.real * ratio + a.imag) / denom; + r.imag = (a.imag * ratio - a.real) / denom; + } + return r; } Py_complex c_pow(Py_complex a, Py_complex b) { - Py_complex r; - double vabs,len,at,phase; - if (b.real == 0. && b.imag == 0.) { - r.real = 1.; - r.imag = 0.; - } - else if (a.real == 0. && a.imag == 0.) { - if (b.imag != 0. || b.real < 0.) - errno = EDOM; - r.real = 0.; - r.imag = 0.; - } - else { - vabs = hypot(a.real,a.imag); - len = pow(vabs,b.real); - at = atan2(a.imag, a.real); - phase = at*b.real; - if (b.imag != 0.0) { - len /= exp(at*b.imag); - phase += b.imag*log(vabs); - } - r.real = len*cos(phase); - r.imag = len*sin(phase); - } - return r; + Py_complex r; + double vabs,len,at,phase; + if (b.real == 0. && b.imag == 0.) { + r.real = 1.; + r.imag = 0.; + } + else if (a.real == 0. && a.imag == 0.) { + if (b.imag != 0. || b.real < 0.) + errno = EDOM; + r.real = 0.; + r.imag = 0.; + } + else { + vabs = hypot(a.real,a.imag); + len = pow(vabs,b.real); + at = atan2(a.imag, a.real); + phase = at*b.real; + if (b.imag != 0.0) { + len /= exp(at*b.imag); + phase += b.imag*log(vabs); + } + r.real = len*cos(phase); + r.imag = len*sin(phase); + } + return r; } static Py_complex c_powu(Py_complex x, long n) { - Py_complex r, p; - long mask = 1; - r = c_1; - p = x; - while (mask > 0 && n >= mask) { - if (n & mask) - r = c_prod(r,p); - mask <<= 1; - p = c_prod(p,p); - } - return r; + Py_complex r, p; + long mask = 1; + r = c_1; + p = x; + while (mask > 0 && n >= mask) { + if (n & mask) + r = c_prod(r,p); + mask <<= 1; + p = c_prod(p,p); + } + return r; } static Py_complex c_powi(Py_complex x, long n) { - Py_complex cn; + Py_complex cn; - if (n > 100 || n < -100) { - cn.real = (double) n; - cn.imag = 0.; - return c_pow(x,cn); - } - else if (n > 0) - return c_powu(x,n); - else - return c_quot(c_1,c_powu(x,-n)); + if (n > 100 || n < -100) { + cn.real = (double) n; + cn.imag = 0.; + return c_pow(x,cn); + } + else if (n > 0) + return c_powu(x,n); + else + return c_quot(c_1,c_powu(x,-n)); } double c_abs(Py_complex z) { - /* sets errno = ERANGE on overflow; otherwise errno = 0 */ - double result; + /* sets errno = ERANGE on overflow; otherwise errno = 0 */ + double result; - if (!Py_IS_FINITE(z.real) || !Py_IS_FINITE(z.imag)) { - /* C99 rules: if either the real or the imaginary part is an - infinity, return infinity, even if the other part is a - NaN. */ - if (Py_IS_INFINITY(z.real)) { - result = fabs(z.real); - errno = 0; - return result; - } - if (Py_IS_INFINITY(z.imag)) { - result = fabs(z.imag); - errno = 0; - return result; - } - /* either the real or imaginary part is a NaN, - and neither is infinite. Result should be NaN. */ - return Py_NAN; - } - result = hypot(z.real, z.imag); - if (!Py_IS_FINITE(result)) - errno = ERANGE; - else - errno = 0; - return result; + if (!Py_IS_FINITE(z.real) || !Py_IS_FINITE(z.imag)) { + /* C99 rules: if either the real or the imaginary part is an + infinity, return infinity, even if the other part is a + NaN. */ + if (Py_IS_INFINITY(z.real)) { + result = fabs(z.real); + errno = 0; + return result; + } + if (Py_IS_INFINITY(z.imag)) { + result = fabs(z.imag); + errno = 0; + return result; + } + /* either the real or imaginary part is a NaN, + and neither is infinite. Result should be NaN. */ + return Py_NAN; + } + result = hypot(z.real, z.imag); + if (!Py_IS_FINITE(result)) + errno = ERANGE; + else + errno = 0; + return result; } static PyObject * complex_subtype_from_c_complex(PyTypeObject *type, Py_complex cval) { - PyObject *op; + PyObject *op; - op = type->tp_alloc(type, 0); - if (op != NULL) - ((PyComplexObject *)op)->cval = cval; - return op; + op = type->tp_alloc(type, 0); + if (op != NULL) + ((PyComplexObject *)op)->cval = cval; + return op; } PyObject * PyComplex_FromCComplex(Py_complex cval) { - register PyComplexObject *op; + register PyComplexObject *op; - /* Inline PyObject_New */ - op = (PyComplexObject *) PyObject_MALLOC(sizeof(PyComplexObject)); - if (op == NULL) - return PyErr_NoMemory(); - PyObject_INIT(op, &PyComplex_Type); - op->cval = cval; - return (PyObject *) op; + /* Inline PyObject_New */ + op = (PyComplexObject *) PyObject_MALLOC(sizeof(PyComplexObject)); + if (op == NULL) + return PyErr_NoMemory(); + PyObject_INIT(op, &PyComplex_Type); + op->cval = cval; + return (PyObject *) op; } static PyObject * complex_subtype_from_doubles(PyTypeObject *type, double real, double imag) { - Py_complex c; - c.real = real; - c.imag = imag; - return complex_subtype_from_c_complex(type, c); + Py_complex c; + c.real = real; + c.imag = imag; + return complex_subtype_from_c_complex(type, c); } PyObject * PyComplex_FromDoubles(double real, double imag) { - Py_complex c; - c.real = real; - c.imag = imag; - return PyComplex_FromCComplex(c); + Py_complex c; + c.real = real; + c.imag = imag; + return PyComplex_FromCComplex(c); } double PyComplex_RealAsDouble(PyObject *op) { - if (PyComplex_Check(op)) { - return ((PyComplexObject *)op)->cval.real; - } - else { - return PyFloat_AsDouble(op); - } + if (PyComplex_Check(op)) { + return ((PyComplexObject *)op)->cval.real; + } + else { + return PyFloat_AsDouble(op); + } } double PyComplex_ImagAsDouble(PyObject *op) { - if (PyComplex_Check(op)) { - return ((PyComplexObject *)op)->cval.imag; - } - else { - return 0.0; - } + if (PyComplex_Check(op)) { + return ((PyComplexObject *)op)->cval.imag; + } + else { + return 0.0; + } } Py_complex PyComplex_AsCComplex(PyObject *op) { - Py_complex cv; - PyObject *newop = NULL; - static PyObject *complex_str = NULL; - - assert(op); - /* If op is already of type PyComplex_Type, return its value */ - if (PyComplex_Check(op)) { - return ((PyComplexObject *)op)->cval; - } - /* If not, use op's __complex__ method, if it exists */ - - /* return -1 on failure */ - cv.real = -1.; - cv.imag = 0.; - - if (complex_str == NULL) { - if (!(complex_str = PyUnicode_FromString("__complex__"))) - return cv; - } - - { - PyObject *complexfunc; - complexfunc = _PyType_Lookup(op->ob_type, complex_str); - /* complexfunc is a borrowed reference */ - if (complexfunc) { - newop = PyObject_CallFunctionObjArgs(complexfunc, op, NULL); - if (!newop) - return cv; - } - } - - if (newop) { - if (!PyComplex_Check(newop)) { - PyErr_SetString(PyExc_TypeError, - "__complex__ should return a complex object"); - Py_DECREF(newop); - return cv; - } - cv = ((PyComplexObject *)newop)->cval; - Py_DECREF(newop); - return cv; - } - /* If neither of the above works, interpret op as a float giving the - real part of the result, and fill in the imaginary part as 0. */ - else { - /* PyFloat_AsDouble will return -1 on failure */ - cv.real = PyFloat_AsDouble(op); - return cv; - } + Py_complex cv; + PyObject *newop = NULL; + static PyObject *complex_str = NULL; + + assert(op); + /* If op is already of type PyComplex_Type, return its value */ + if (PyComplex_Check(op)) { + return ((PyComplexObject *)op)->cval; + } + /* If not, use op's __complex__ method, if it exists */ + + /* return -1 on failure */ + cv.real = -1.; + cv.imag = 0.; + + if (complex_str == NULL) { + if (!(complex_str = PyUnicode_FromString("__complex__"))) + return cv; + } + + { + PyObject *complexfunc; + complexfunc = _PyType_Lookup(op->ob_type, complex_str); + /* complexfunc is a borrowed reference */ + if (complexfunc) { + newop = PyObject_CallFunctionObjArgs(complexfunc, op, NULL); + if (!newop) + return cv; + } + } + + if (newop) { + if (!PyComplex_Check(newop)) { + PyErr_SetString(PyExc_TypeError, + "__complex__ should return a complex object"); + Py_DECREF(newop); + return cv; + } + cv = ((PyComplexObject *)newop)->cval; + Py_DECREF(newop); + return cv; + } + /* If neither of the above works, interpret op as a float giving the + real part of the result, and fill in the imaginary part as 0. */ + else { + /* PyFloat_AsDouble will return -1 on failure */ + cv.real = PyFloat_AsDouble(op); + return cv; + } } static void complex_dealloc(PyObject *op) { - op->ob_type->tp_free(op); + op->ob_type->tp_free(op); } static PyObject * complex_format(PyComplexObject *v, int precision, char format_code) { - PyObject *result = NULL; - Py_ssize_t len; + PyObject *result = NULL; + Py_ssize_t len; - /* If these are non-NULL, they'll need to be freed. */ - char *pre = NULL; - char *im = NULL; - char *buf = NULL; - - /* These do not need to be freed. re is either an alias - for pre or a pointer to a constant. lead and tail - are pointers to constants. */ - char *re = NULL; - char *lead = ""; - char *tail = ""; - - if (v->cval.real == 0. && copysign(1.0, v->cval.real)==1.0) { - re = ""; - im = PyOS_double_to_string(v->cval.imag, format_code, - precision, 0, NULL); - if (!im) { - PyErr_NoMemory(); - goto done; - } - } else { - /* Format imaginary part with sign, real part without */ - pre = PyOS_double_to_string(v->cval.real, format_code, - precision, 0, NULL); - if (!pre) { - PyErr_NoMemory(); - goto done; - } - re = pre; - - im = PyOS_double_to_string(v->cval.imag, format_code, - precision, Py_DTSF_SIGN, NULL); - if (!im) { - PyErr_NoMemory(); - goto done; - } - lead = "("; - tail = ")"; - } - /* Alloc the final buffer. Add one for the "j" in the format string, - and one for the trailing zero. */ - len = strlen(lead) + strlen(re) + strlen(im) + strlen(tail) + 2; - buf = PyMem_Malloc(len); - if (!buf) { - PyErr_NoMemory(); - goto done; - } - PyOS_snprintf(buf, len, "%s%s%sj%s", lead, re, im, tail); - result = PyUnicode_FromString(buf); + /* If these are non-NULL, they'll need to be freed. */ + char *pre = NULL; + char *im = NULL; + char *buf = NULL; + + /* These do not need to be freed. re is either an alias + for pre or a pointer to a constant. lead and tail + are pointers to constants. */ + char *re = NULL; + char *lead = ""; + char *tail = ""; + + if (v->cval.real == 0. && copysign(1.0, v->cval.real)==1.0) { + re = ""; + im = PyOS_double_to_string(v->cval.imag, format_code, + precision, 0, NULL); + if (!im) { + PyErr_NoMemory(); + goto done; + } + } else { + /* Format imaginary part with sign, real part without */ + pre = PyOS_double_to_string(v->cval.real, format_code, + precision, 0, NULL); + if (!pre) { + PyErr_NoMemory(); + goto done; + } + re = pre; + + im = PyOS_double_to_string(v->cval.imag, format_code, + precision, Py_DTSF_SIGN, NULL); + if (!im) { + PyErr_NoMemory(); + goto done; + } + lead = "("; + tail = ")"; + } + /* Alloc the final buffer. Add one for the "j" in the format string, + and one for the trailing zero. */ + len = strlen(lead) + strlen(re) + strlen(im) + strlen(tail) + 2; + buf = PyMem_Malloc(len); + if (!buf) { + PyErr_NoMemory(); + goto done; + } + PyOS_snprintf(buf, len, "%s%s%sj%s", lead, re, im, tail); + result = PyUnicode_FromString(buf); done: - PyMem_Free(im); - PyMem_Free(pre); - PyMem_Free(buf); + PyMem_Free(im); + PyMem_Free(pre); + PyMem_Free(buf); - return result; + return result; } static PyObject * @@ -407,266 +407,266 @@ static long complex_hash(PyComplexObject *v) { - long hashreal, hashimag, combined; - hashreal = _Py_HashDouble(v->cval.real); - if (hashreal == -1) - return -1; - hashimag = _Py_HashDouble(v->cval.imag); - if (hashimag == -1) - return -1; - /* Note: if the imaginary part is 0, hashimag is 0 now, - * so the following returns hashreal unchanged. This is - * important because numbers of different types that - * compare equal must have the same hash value, so that - * hash(x + 0*j) must equal hash(x). - */ - combined = hashreal + 1000003 * hashimag; - if (combined == -1) - combined = -2; - return combined; + long hashreal, hashimag, combined; + hashreal = _Py_HashDouble(v->cval.real); + if (hashreal == -1) + return -1; + hashimag = _Py_HashDouble(v->cval.imag); + if (hashimag == -1) + return -1; + /* Note: if the imaginary part is 0, hashimag is 0 now, + * so the following returns hashreal unchanged. This is + * important because numbers of different types that + * compare equal must have the same hash value, so that + * hash(x + 0*j) must equal hash(x). + */ + combined = hashreal + 1000003 * hashimag; + if (combined == -1) + combined = -2; + return combined; } /* This macro may return! */ #define TO_COMPLEX(obj, c) \ - if (PyComplex_Check(obj)) \ - c = ((PyComplexObject *)(obj))->cval; \ - else if (to_complex(&(obj), &(c)) < 0) \ - return (obj) + if (PyComplex_Check(obj)) \ + c = ((PyComplexObject *)(obj))->cval; \ + else if (to_complex(&(obj), &(c)) < 0) \ + return (obj) static int to_complex(PyObject **pobj, Py_complex *pc) { - PyObject *obj = *pobj; + PyObject *obj = *pobj; - pc->real = pc->imag = 0.0; - if (PyLong_Check(obj)) { - pc->real = PyLong_AsDouble(obj); - if (pc->real == -1.0 && PyErr_Occurred()) { - *pobj = NULL; - return -1; - } - return 0; - } - if (PyFloat_Check(obj)) { - pc->real = PyFloat_AsDouble(obj); - return 0; - } - Py_INCREF(Py_NotImplemented); - *pobj = Py_NotImplemented; - return -1; + pc->real = pc->imag = 0.0; + if (PyLong_Check(obj)) { + pc->real = PyLong_AsDouble(obj); + if (pc->real == -1.0 && PyErr_Occurred()) { + *pobj = NULL; + return -1; + } + return 0; + } + if (PyFloat_Check(obj)) { + pc->real = PyFloat_AsDouble(obj); + return 0; + } + Py_INCREF(Py_NotImplemented); + *pobj = Py_NotImplemented; + return -1; } - + static PyObject * complex_add(PyObject *v, PyObject *w) { - Py_complex result; - Py_complex a, b; - TO_COMPLEX(v, a); - TO_COMPLEX(w, b); - PyFPE_START_PROTECT("complex_add", return 0) - result = c_sum(a, b); - PyFPE_END_PROTECT(result) - return PyComplex_FromCComplex(result); + Py_complex result; + Py_complex a, b; + TO_COMPLEX(v, a); + TO_COMPLEX(w, b); + PyFPE_START_PROTECT("complex_add", return 0) + result = c_sum(a, b); + PyFPE_END_PROTECT(result) + return PyComplex_FromCComplex(result); } static PyObject * complex_sub(PyObject *v, PyObject *w) { - Py_complex result; - Py_complex a, b; - TO_COMPLEX(v, a); - TO_COMPLEX(w, b); - PyFPE_START_PROTECT("complex_sub", return 0) - result = c_diff(a, b); - PyFPE_END_PROTECT(result) - return PyComplex_FromCComplex(result); + Py_complex result; + Py_complex a, b; + TO_COMPLEX(v, a); + TO_COMPLEX(w, b); + PyFPE_START_PROTECT("complex_sub", return 0) + result = c_diff(a, b); + PyFPE_END_PROTECT(result) + return PyComplex_FromCComplex(result); } static PyObject * complex_mul(PyObject *v, PyObject *w) { - Py_complex result; - Py_complex a, b; - TO_COMPLEX(v, a); - TO_COMPLEX(w, b); - PyFPE_START_PROTECT("complex_mul", return 0) - result = c_prod(a, b); - PyFPE_END_PROTECT(result) - return PyComplex_FromCComplex(result); + Py_complex result; + Py_complex a, b; + TO_COMPLEX(v, a); + TO_COMPLEX(w, b); + PyFPE_START_PROTECT("complex_mul", return 0) + result = c_prod(a, b); + PyFPE_END_PROTECT(result) + return PyComplex_FromCComplex(result); } static PyObject * complex_div(PyObject *v, PyObject *w) { - Py_complex quot; - Py_complex a, b; - TO_COMPLEX(v, a); - TO_COMPLEX(w, b); - PyFPE_START_PROTECT("complex_div", return 0) - errno = 0; - quot = c_quot(a, b); - PyFPE_END_PROTECT(quot) - if (errno == EDOM) { - PyErr_SetString(PyExc_ZeroDivisionError, "complex division"); - return NULL; - } - return PyComplex_FromCComplex(quot); + Py_complex quot; + Py_complex a, b; + TO_COMPLEX(v, a); + TO_COMPLEX(w, b); + PyFPE_START_PROTECT("complex_div", return 0) + errno = 0; + quot = c_quot(a, b); + PyFPE_END_PROTECT(quot) + if (errno == EDOM) { + PyErr_SetString(PyExc_ZeroDivisionError, "complex division"); + return NULL; + } + return PyComplex_FromCComplex(quot); } static PyObject * complex_remainder(PyObject *v, PyObject *w) { - PyErr_SetString(PyExc_TypeError, - "can't mod complex numbers."); - return NULL; + PyErr_SetString(PyExc_TypeError, + "can't mod complex numbers."); + return NULL; } static PyObject * complex_divmod(PyObject *v, PyObject *w) { - PyErr_SetString(PyExc_TypeError, - "can't take floor or mod of complex number."); - return NULL; + PyErr_SetString(PyExc_TypeError, + "can't take floor or mod of complex number."); + return NULL; } static PyObject * complex_pow(PyObject *v, PyObject *w, PyObject *z) { - Py_complex p; - Py_complex exponent; - long int_exponent; - Py_complex a, b; - TO_COMPLEX(v, a); - TO_COMPLEX(w, b); - - if (z != Py_None) { - PyErr_SetString(PyExc_ValueError, "complex modulo"); - return NULL; - } - PyFPE_START_PROTECT("complex_pow", return 0) - errno = 0; - exponent = b; - int_exponent = (long)exponent.real; - if (exponent.imag == 0. && exponent.real == int_exponent) - p = c_powi(a, int_exponent); - else - p = c_pow(a, exponent); - - PyFPE_END_PROTECT(p) - Py_ADJUST_ERANGE2(p.real, p.imag); - if (errno == EDOM) { - PyErr_SetString(PyExc_ZeroDivisionError, - "0.0 to a negative or complex power"); - return NULL; - } - else if (errno == ERANGE) { - PyErr_SetString(PyExc_OverflowError, - "complex exponentiation"); - return NULL; - } - return PyComplex_FromCComplex(p); + Py_complex p; + Py_complex exponent; + long int_exponent; + Py_complex a, b; + TO_COMPLEX(v, a); + TO_COMPLEX(w, b); + + if (z != Py_None) { + PyErr_SetString(PyExc_ValueError, "complex modulo"); + return NULL; + } + PyFPE_START_PROTECT("complex_pow", return 0) + errno = 0; + exponent = b; + int_exponent = (long)exponent.real; + if (exponent.imag == 0. && exponent.real == int_exponent) + p = c_powi(a, int_exponent); + else + p = c_pow(a, exponent); + + PyFPE_END_PROTECT(p) + Py_ADJUST_ERANGE2(p.real, p.imag); + if (errno == EDOM) { + PyErr_SetString(PyExc_ZeroDivisionError, + "0.0 to a negative or complex power"); + return NULL; + } + else if (errno == ERANGE) { + PyErr_SetString(PyExc_OverflowError, + "complex exponentiation"); + return NULL; + } + return PyComplex_FromCComplex(p); } static PyObject * complex_int_div(PyObject *v, PyObject *w) { - PyErr_SetString(PyExc_TypeError, - "can't take floor of complex number."); - return NULL; + PyErr_SetString(PyExc_TypeError, + "can't take floor of complex number."); + return NULL; } static PyObject * complex_neg(PyComplexObject *v) { - Py_complex neg; - neg.real = -v->cval.real; - neg.imag = -v->cval.imag; - return PyComplex_FromCComplex(neg); + Py_complex neg; + neg.real = -v->cval.real; + neg.imag = -v->cval.imag; + return PyComplex_FromCComplex(neg); } static PyObject * complex_pos(PyComplexObject *v) { - if (PyComplex_CheckExact(v)) { - Py_INCREF(v); - return (PyObject *)v; - } - else - return PyComplex_FromCComplex(v->cval); + if (PyComplex_CheckExact(v)) { + Py_INCREF(v); + return (PyObject *)v; + } + else + return PyComplex_FromCComplex(v->cval); } static PyObject * complex_abs(PyComplexObject *v) { - double result; + double result; - PyFPE_START_PROTECT("complex_abs", return 0) - result = c_abs(v->cval); - PyFPE_END_PROTECT(result) - - if (errno == ERANGE) { - PyErr_SetString(PyExc_OverflowError, - "absolute value too large"); - return NULL; - } - return PyFloat_FromDouble(result); + PyFPE_START_PROTECT("complex_abs", return 0) + result = c_abs(v->cval); + PyFPE_END_PROTECT(result) + + if (errno == ERANGE) { + PyErr_SetString(PyExc_OverflowError, + "absolute value too large"); + return NULL; + } + return PyFloat_FromDouble(result); } static int complex_bool(PyComplexObject *v) { - return v->cval.real != 0.0 || v->cval.imag != 0.0; + return v->cval.real != 0.0 || v->cval.imag != 0.0; } static PyObject * complex_richcompare(PyObject *v, PyObject *w, int op) { - PyObject *res; - Py_complex i, j; - TO_COMPLEX(v, i); - TO_COMPLEX(w, j); - - if (op != Py_EQ && op != Py_NE) { - /* XXX Should eventually return NotImplemented */ - PyErr_SetString(PyExc_TypeError, - "no ordering relation is defined for complex numbers"); - return NULL; - } - - if ((i.real == j.real && i.imag == j.imag) == (op == Py_EQ)) - res = Py_True; - else - res = Py_False; + PyObject *res; + Py_complex i, j; + TO_COMPLEX(v, i); + TO_COMPLEX(w, j); + + if (op != Py_EQ && op != Py_NE) { + /* XXX Should eventually return NotImplemented */ + PyErr_SetString(PyExc_TypeError, + "no ordering relation is defined for complex numbers"); + return NULL; + } + + if ((i.real == j.real && i.imag == j.imag) == (op == Py_EQ)) + res = Py_True; + else + res = Py_False; - Py_INCREF(res); - return res; + Py_INCREF(res); + return res; } static PyObject * complex_int(PyObject *v) { - PyErr_SetString(PyExc_TypeError, - "can't convert complex to int"); - return NULL; + PyErr_SetString(PyExc_TypeError, + "can't convert complex to int"); + return NULL; } static PyObject * complex_float(PyObject *v) { - PyErr_SetString(PyExc_TypeError, - "can't convert complex to float"); - return NULL; + PyErr_SetString(PyExc_TypeError, + "can't convert complex to float"); + return NULL; } static PyObject * complex_conjugate(PyObject *self) { - Py_complex c; - c = ((PyComplexObject *)self)->cval; - c.imag = -c.imag; - return PyComplex_FromCComplex(c); + Py_complex c; + c = ((PyComplexObject *)self)->cval; + c.imag = -c.imag; + return PyComplex_FromCComplex(c); } PyDoc_STRVAR(complex_conjugate_doc, @@ -677,8 +677,8 @@ static PyObject * complex_getnewargs(PyComplexObject *v) { - Py_complex c = v->cval; - return Py_BuildValue("(dd)", c.real, c.imag); + Py_complex c = v->cval; + return Py_BuildValue("(dd)", c.real, c.imag); } PyDoc_STRVAR(complex__format__doc, @@ -692,7 +692,7 @@ PyObject *format_spec; if (!PyArg_ParseTuple(args, "U:__format__", &format_spec)) - return NULL; + return NULL; return _PyComplex_FormatAdvanced(self, PyUnicode_AS_UNICODE(format_spec), PyUnicode_GET_SIZE(format_spec)); @@ -702,10 +702,10 @@ static PyObject * complex_is_finite(PyObject *self) { - Py_complex c; - c = ((PyComplexObject *)self)->cval; - return PyBool_FromLong((long)(Py_IS_FINITE(c.real) && - Py_IS_FINITE(c.imag))); + Py_complex c; + c = ((PyComplexObject *)self)->cval; + return PyBool_FromLong((long)(Py_IS_FINITE(c.real) && + Py_IS_FINITE(c.imag))); } PyDoc_STRVAR(complex_is_finite_doc, @@ -715,314 +715,314 @@ #endif static PyMethodDef complex_methods[] = { - {"conjugate", (PyCFunction)complex_conjugate, METH_NOARGS, - complex_conjugate_doc}, + {"conjugate", (PyCFunction)complex_conjugate, METH_NOARGS, + complex_conjugate_doc}, #if 0 - {"is_finite", (PyCFunction)complex_is_finite, METH_NOARGS, - complex_is_finite_doc}, + {"is_finite", (PyCFunction)complex_is_finite, METH_NOARGS, + complex_is_finite_doc}, #endif - {"__getnewargs__", (PyCFunction)complex_getnewargs, METH_NOARGS}, - {"__format__", (PyCFunction)complex__format__, - METH_VARARGS, complex__format__doc}, - {NULL, NULL} /* sentinel */ + {"__getnewargs__", (PyCFunction)complex_getnewargs, METH_NOARGS}, + {"__format__", (PyCFunction)complex__format__, + METH_VARARGS, complex__format__doc}, + {NULL, NULL} /* sentinel */ }; static PyMemberDef complex_members[] = { - {"real", T_DOUBLE, offsetof(PyComplexObject, cval.real), READONLY, - "the real part of a complex number"}, - {"imag", T_DOUBLE, offsetof(PyComplexObject, cval.imag), READONLY, - "the imaginary part of a complex number"}, - {0}, + {"real", T_DOUBLE, offsetof(PyComplexObject, cval.real), READONLY, + "the real part of a complex number"}, + {"imag", T_DOUBLE, offsetof(PyComplexObject, cval.imag), READONLY, + "the imaginary part of a complex number"}, + {0}, }; static PyObject * complex_subtype_from_string(PyTypeObject *type, PyObject *v) { - const char *s, *start; - char *end; - double x=0.0, y=0.0, z; - int got_bracket=0; - char s_buffer[256]; - Py_ssize_t len; - - if (PyUnicode_Check(v)) { - if (PyUnicode_GET_SIZE(v) >= (Py_ssize_t)sizeof(s_buffer)) { - PyErr_SetString(PyExc_ValueError, - "complex() literal too large to convert"); - return NULL; - } - if (PyUnicode_EncodeDecimal(PyUnicode_AS_UNICODE(v), - PyUnicode_GET_SIZE(v), - s_buffer, - NULL)) - return NULL; - s = s_buffer; - len = strlen(s); - } - else if (PyObject_AsCharBuffer(v, &s, &len)) { - PyErr_SetString(PyExc_TypeError, - "complex() arg is not a string"); - return NULL; - } - - /* position on first nonblank */ - start = s; - while (Py_ISSPACE(*s)) - s++; - if (*s == '(') { - /* Skip over possible bracket from repr(). */ - got_bracket = 1; - s++; - while (Py_ISSPACE(*s)) - s++; - } - - /* a valid complex string usually takes one of the three forms: - - - real part only - j - imaginary part only - j - real and imaginary parts - - where represents any numeric string that's accepted by the - float constructor (including 'nan', 'inf', 'infinity', etc.), and - is any string of the form whose first - character is '+' or '-'. - - For backwards compatibility, the extra forms - - j - j - j - - are also accepted, though support for these forms may be removed from - a future version of Python. - */ - - /* first look for forms starting with */ - z = PyOS_string_to_double(s, &end, NULL); - if (z == -1.0 && PyErr_Occurred()) { - if (PyErr_ExceptionMatches(PyExc_ValueError)) - PyErr_Clear(); - else - return NULL; - } - if (end != s) { - /* all 4 forms starting with land here */ - s = end; - if (*s == '+' || *s == '-') { - /* j | j */ - x = z; - y = PyOS_string_to_double(s, &end, NULL); - if (y == -1.0 && PyErr_Occurred()) { - if (PyErr_ExceptionMatches(PyExc_ValueError)) - PyErr_Clear(); - else - return NULL; - } - if (end != s) - /* j */ - s = end; - else { - /* j */ - y = *s == '+' ? 1.0 : -1.0; - s++; - } - if (!(*s == 'j' || *s == 'J')) - goto parse_error; - s++; - } - else if (*s == 'j' || *s == 'J') { - /* j */ - s++; - y = z; - } - else - /* */ - x = z; - } - else { - /* not starting with ; must be j or j */ - if (*s == '+' || *s == '-') { - /* j */ - y = *s == '+' ? 1.0 : -1.0; - s++; - } - else - /* j */ - y = 1.0; - if (!(*s == 'j' || *s == 'J')) - goto parse_error; - s++; - } - - /* trailing whitespace and closing bracket */ - while (Py_ISSPACE(*s)) - s++; - if (got_bracket) { - /* if there was an opening parenthesis, then the corresponding - closing parenthesis should be right here */ - if (*s != ')') - goto parse_error; - s++; - while (Py_ISSPACE(*s)) - s++; - } - - /* we should now be at the end of the string */ - if (s-start != len) - goto parse_error; + const char *s, *start; + char *end; + double x=0.0, y=0.0, z; + int got_bracket=0; + char s_buffer[256]; + Py_ssize_t len; + + if (PyUnicode_Check(v)) { + if (PyUnicode_GET_SIZE(v) >= (Py_ssize_t)sizeof(s_buffer)) { + PyErr_SetString(PyExc_ValueError, + "complex() literal too large to convert"); + return NULL; + } + if (PyUnicode_EncodeDecimal(PyUnicode_AS_UNICODE(v), + PyUnicode_GET_SIZE(v), + s_buffer, + NULL)) + return NULL; + s = s_buffer; + len = strlen(s); + } + else if (PyObject_AsCharBuffer(v, &s, &len)) { + PyErr_SetString(PyExc_TypeError, + "complex() arg is not a string"); + return NULL; + } + + /* position on first nonblank */ + start = s; + while (Py_ISSPACE(*s)) + s++; + if (*s == '(') { + /* Skip over possible bracket from repr(). */ + got_bracket = 1; + s++; + while (Py_ISSPACE(*s)) + s++; + } + + /* a valid complex string usually takes one of the three forms: + + - real part only + j - imaginary part only + j - real and imaginary parts + + where represents any numeric string that's accepted by the + float constructor (including 'nan', 'inf', 'infinity', etc.), and + is any string of the form whose first + character is '+' or '-'. + + For backwards compatibility, the extra forms + + j + j + j + + are also accepted, though support for these forms may be removed from + a future version of Python. + */ + + /* first look for forms starting with */ + z = PyOS_string_to_double(s, &end, NULL); + if (z == -1.0 && PyErr_Occurred()) { + if (PyErr_ExceptionMatches(PyExc_ValueError)) + PyErr_Clear(); + else + return NULL; + } + if (end != s) { + /* all 4 forms starting with land here */ + s = end; + if (*s == '+' || *s == '-') { + /* j | j */ + x = z; + y = PyOS_string_to_double(s, &end, NULL); + if (y == -1.0 && PyErr_Occurred()) { + if (PyErr_ExceptionMatches(PyExc_ValueError)) + PyErr_Clear(); + else + return NULL; + } + if (end != s) + /* j */ + s = end; + else { + /* j */ + y = *s == '+' ? 1.0 : -1.0; + s++; + } + if (!(*s == 'j' || *s == 'J')) + goto parse_error; + s++; + } + else if (*s == 'j' || *s == 'J') { + /* j */ + s++; + y = z; + } + else + /* */ + x = z; + } + else { + /* not starting with ; must be j or j */ + if (*s == '+' || *s == '-') { + /* j */ + y = *s == '+' ? 1.0 : -1.0; + s++; + } + else + /* j */ + y = 1.0; + if (!(*s == 'j' || *s == 'J')) + goto parse_error; + s++; + } + + /* trailing whitespace and closing bracket */ + while (Py_ISSPACE(*s)) + s++; + if (got_bracket) { + /* if there was an opening parenthesis, then the corresponding + closing parenthesis should be right here */ + if (*s != ')') + goto parse_error; + s++; + while (Py_ISSPACE(*s)) + s++; + } + + /* we should now be at the end of the string */ + if (s-start != len) + goto parse_error; - return complex_subtype_from_doubles(type, x, y); + return complex_subtype_from_doubles(type, x, y); parse_error: - PyErr_SetString(PyExc_ValueError, - "complex() arg is a malformed string"); - return NULL; + PyErr_SetString(PyExc_ValueError, + "complex() arg is a malformed string"); + return NULL; } static PyObject * complex_new(PyTypeObject *type, PyObject *args, PyObject *kwds) { - PyObject *r, *i, *tmp, *f; - PyNumberMethods *nbr, *nbi = NULL; - Py_complex cr, ci; - int own_r = 0; - int cr_is_complex = 0; - int ci_is_complex = 0; - static PyObject *complexstr; - static char *kwlist[] = {"real", "imag", 0}; - - r = Py_False; - i = NULL; - if (!PyArg_ParseTupleAndKeywords(args, kwds, "|OO:complex", kwlist, - &r, &i)) - return NULL; - - /* Special-case for a single argument when type(arg) is complex. */ - if (PyComplex_CheckExact(r) && i == NULL && - type == &PyComplex_Type) { - /* Note that we can't know whether it's safe to return - a complex *subclass* instance as-is, hence the restriction - to exact complexes here. If either the input or the - output is a complex subclass, it will be handled below - as a non-orthogonal vector. */ - Py_INCREF(r); - return r; - } - if (PyUnicode_Check(r)) { - if (i != NULL) { - PyErr_SetString(PyExc_TypeError, - "complex() can't take second arg" - " if first is a string"); - return NULL; - } - return complex_subtype_from_string(type, r); - } - if (i != NULL && PyUnicode_Check(i)) { - PyErr_SetString(PyExc_TypeError, - "complex() second arg can't be a string"); - return NULL; - } - - /* XXX Hack to support classes with __complex__ method */ - if (complexstr == NULL) { - complexstr = PyUnicode_InternFromString("__complex__"); - if (complexstr == NULL) - return NULL; - } - f = PyObject_GetAttr(r, complexstr); - if (f == NULL) - PyErr_Clear(); - else { - PyObject *args = PyTuple_New(0); - if (args == NULL) - return NULL; - r = PyEval_CallObject(f, args); - Py_DECREF(args); - Py_DECREF(f); - if (r == NULL) - return NULL; - own_r = 1; - } - nbr = r->ob_type->tp_as_number; - if (i != NULL) - nbi = i->ob_type->tp_as_number; - if (nbr == NULL || nbr->nb_float == NULL || - ((i != NULL) && (nbi == NULL || nbi->nb_float == NULL))) { - PyErr_SetString(PyExc_TypeError, - "complex() argument must be a string or a number"); - if (own_r) { - Py_DECREF(r); - } - return NULL; - } - - /* If we get this far, then the "real" and "imag" parts should - both be treated as numbers, and the constructor should return a - complex number equal to (real + imag*1j). - - Note that we do NOT assume the input to already be in canonical - form; the "real" and "imag" parts might themselves be complex - numbers, which slightly complicates the code below. */ - if (PyComplex_Check(r)) { - /* Note that if r is of a complex subtype, we're only - retaining its real & imag parts here, and the return - value is (properly) of the builtin complex type. */ - cr = ((PyComplexObject*)r)->cval; - cr_is_complex = 1; - if (own_r) { - Py_DECREF(r); - } - } - else { - /* The "real" part really is entirely real, and contributes - nothing in the imaginary direction. - Just treat it as a double. */ - tmp = PyNumber_Float(r); - if (own_r) { - /* r was a newly created complex number, rather - than the original "real" argument. */ - Py_DECREF(r); - } - if (tmp == NULL) - return NULL; - if (!PyFloat_Check(tmp)) { - PyErr_SetString(PyExc_TypeError, - "float(r) didn't return a float"); - Py_DECREF(tmp); - return NULL; - } - cr.real = PyFloat_AsDouble(tmp); - cr.imag = 0.0; /* Shut up compiler warning */ - Py_DECREF(tmp); - } - if (i == NULL) { - ci.real = 0.0; - } - else if (PyComplex_Check(i)) { - ci = ((PyComplexObject*)i)->cval; - ci_is_complex = 1; - } else { - /* The "imag" part really is entirely imaginary, and - contributes nothing in the real direction. - Just treat it as a double. */ - tmp = (*nbi->nb_float)(i); - if (tmp == NULL) - return NULL; - ci.real = PyFloat_AsDouble(tmp); - Py_DECREF(tmp); - } - /* If the input was in canonical form, then the "real" and "imag" - parts are real numbers, so that ci.imag and cr.imag are zero. - We need this correction in case they were not real numbers. */ - - if (ci_is_complex) { - cr.real -= ci.imag; - } - if (cr_is_complex) { - ci.real += cr.imag; - } - return complex_subtype_from_doubles(type, cr.real, ci.real); + PyObject *r, *i, *tmp, *f; + PyNumberMethods *nbr, *nbi = NULL; + Py_complex cr, ci; + int own_r = 0; + int cr_is_complex = 0; + int ci_is_complex = 0; + static PyObject *complexstr; + static char *kwlist[] = {"real", "imag", 0}; + + r = Py_False; + i = NULL; + if (!PyArg_ParseTupleAndKeywords(args, kwds, "|OO:complex", kwlist, + &r, &i)) + return NULL; + + /* Special-case for a single argument when type(arg) is complex. */ + if (PyComplex_CheckExact(r) && i == NULL && + type == &PyComplex_Type) { + /* Note that we can't know whether it's safe to return + a complex *subclass* instance as-is, hence the restriction + to exact complexes here. If either the input or the + output is a complex subclass, it will be handled below + as a non-orthogonal vector. */ + Py_INCREF(r); + return r; + } + if (PyUnicode_Check(r)) { + if (i != NULL) { + PyErr_SetString(PyExc_TypeError, + "complex() can't take second arg" + " if first is a string"); + return NULL; + } + return complex_subtype_from_string(type, r); + } + if (i != NULL && PyUnicode_Check(i)) { + PyErr_SetString(PyExc_TypeError, + "complex() second arg can't be a string"); + return NULL; + } + + /* XXX Hack to support classes with __complex__ method */ + if (complexstr == NULL) { + complexstr = PyUnicode_InternFromString("__complex__"); + if (complexstr == NULL) + return NULL; + } + f = PyObject_GetAttr(r, complexstr); + if (f == NULL) + PyErr_Clear(); + else { + PyObject *args = PyTuple_New(0); + if (args == NULL) + return NULL; + r = PyEval_CallObject(f, args); + Py_DECREF(args); + Py_DECREF(f); + if (r == NULL) + return NULL; + own_r = 1; + } + nbr = r->ob_type->tp_as_number; + if (i != NULL) + nbi = i->ob_type->tp_as_number; + if (nbr == NULL || nbr->nb_float == NULL || + ((i != NULL) && (nbi == NULL || nbi->nb_float == NULL))) { + PyErr_SetString(PyExc_TypeError, + "complex() argument must be a string or a number"); + if (own_r) { + Py_DECREF(r); + } + return NULL; + } + + /* If we get this far, then the "real" and "imag" parts should + both be treated as numbers, and the constructor should return a + complex number equal to (real + imag*1j). + + Note that we do NOT assume the input to already be in canonical + form; the "real" and "imag" parts might themselves be complex + numbers, which slightly complicates the code below. */ + if (PyComplex_Check(r)) { + /* Note that if r is of a complex subtype, we're only + retaining its real & imag parts here, and the return + value is (properly) of the builtin complex type. */ + cr = ((PyComplexObject*)r)->cval; + cr_is_complex = 1; + if (own_r) { + Py_DECREF(r); + } + } + else { + /* The "real" part really is entirely real, and contributes + nothing in the imaginary direction. + Just treat it as a double. */ + tmp = PyNumber_Float(r); + if (own_r) { + /* r was a newly created complex number, rather + than the original "real" argument. */ + Py_DECREF(r); + } + if (tmp == NULL) + return NULL; + if (!PyFloat_Check(tmp)) { + PyErr_SetString(PyExc_TypeError, + "float(r) didn't return a float"); + Py_DECREF(tmp); + return NULL; + } + cr.real = PyFloat_AsDouble(tmp); + cr.imag = 0.0; /* Shut up compiler warning */ + Py_DECREF(tmp); + } + if (i == NULL) { + ci.real = 0.0; + } + else if (PyComplex_Check(i)) { + ci = ((PyComplexObject*)i)->cval; + ci_is_complex = 1; + } else { + /* The "imag" part really is entirely imaginary, and + contributes nothing in the real direction. + Just treat it as a double. */ + tmp = (*nbi->nb_float)(i); + if (tmp == NULL) + return NULL; + ci.real = PyFloat_AsDouble(tmp); + Py_DECREF(tmp); + } + /* If the input was in canonical form, then the "real" and "imag" + parts are real numbers, so that ci.imag and cr.imag are zero. + We need this correction in case they were not real numbers. */ + + if (ci_is_complex) { + cr.real -= ci.imag; + } + if (cr_is_complex) { + ci.real += cr.imag; + } + return complex_subtype_from_doubles(type, cr.real, ci.real); } PyDoc_STRVAR(complex_doc, @@ -1032,81 +1032,81 @@ "This is equivalent to (real + imag*1j) where imag defaults to 0."); static PyNumberMethods complex_as_number = { - (binaryfunc)complex_add, /* nb_add */ - (binaryfunc)complex_sub, /* nb_subtract */ - (binaryfunc)complex_mul, /* nb_multiply */ - (binaryfunc)complex_remainder, /* nb_remainder */ - (binaryfunc)complex_divmod, /* nb_divmod */ - (ternaryfunc)complex_pow, /* nb_power */ - (unaryfunc)complex_neg, /* nb_negative */ - (unaryfunc)complex_pos, /* nb_positive */ - (unaryfunc)complex_abs, /* nb_absolute */ - (inquiry)complex_bool, /* nb_bool */ - 0, /* nb_invert */ - 0, /* nb_lshift */ - 0, /* nb_rshift */ - 0, /* nb_and */ - 0, /* nb_xor */ - 0, /* nb_or */ - complex_int, /* nb_int */ - 0, /* nb_reserved */ - complex_float, /* nb_float */ - 0, /* nb_inplace_add */ - 0, /* nb_inplace_subtract */ - 0, /* nb_inplace_multiply*/ - 0, /* nb_inplace_remainder */ - 0, /* nb_inplace_power */ - 0, /* nb_inplace_lshift */ - 0, /* nb_inplace_rshift */ - 0, /* nb_inplace_and */ - 0, /* nb_inplace_xor */ - 0, /* nb_inplace_or */ - (binaryfunc)complex_int_div, /* nb_floor_divide */ - (binaryfunc)complex_div, /* nb_true_divide */ - 0, /* nb_inplace_floor_divide */ - 0, /* nb_inplace_true_divide */ + (binaryfunc)complex_add, /* nb_add */ + (binaryfunc)complex_sub, /* nb_subtract */ + (binaryfunc)complex_mul, /* nb_multiply */ + (binaryfunc)complex_remainder, /* nb_remainder */ + (binaryfunc)complex_divmod, /* nb_divmod */ + (ternaryfunc)complex_pow, /* nb_power */ + (unaryfunc)complex_neg, /* nb_negative */ + (unaryfunc)complex_pos, /* nb_positive */ + (unaryfunc)complex_abs, /* nb_absolute */ + (inquiry)complex_bool, /* nb_bool */ + 0, /* nb_invert */ + 0, /* nb_lshift */ + 0, /* nb_rshift */ + 0, /* nb_and */ + 0, /* nb_xor */ + 0, /* nb_or */ + complex_int, /* nb_int */ + 0, /* nb_reserved */ + complex_float, /* nb_float */ + 0, /* nb_inplace_add */ + 0, /* nb_inplace_subtract */ + 0, /* nb_inplace_multiply*/ + 0, /* nb_inplace_remainder */ + 0, /* nb_inplace_power */ + 0, /* nb_inplace_lshift */ + 0, /* nb_inplace_rshift */ + 0, /* nb_inplace_and */ + 0, /* nb_inplace_xor */ + 0, /* nb_inplace_or */ + (binaryfunc)complex_int_div, /* nb_floor_divide */ + (binaryfunc)complex_div, /* nb_true_divide */ + 0, /* nb_inplace_floor_divide */ + 0, /* nb_inplace_true_divide */ }; PyTypeObject PyComplex_Type = { - PyVarObject_HEAD_INIT(&PyType_Type, 0) - "complex", - sizeof(PyComplexObject), - 0, - complex_dealloc, /* tp_dealloc */ - 0, /* tp_print */ - 0, /* tp_getattr */ - 0, /* tp_setattr */ - 0, /* tp_reserved */ - (reprfunc)complex_repr, /* tp_repr */ - &complex_as_number, /* tp_as_number */ - 0, /* tp_as_sequence */ - 0, /* tp_as_mapping */ - (hashfunc)complex_hash, /* tp_hash */ - 0, /* tp_call */ - (reprfunc)complex_str, /* tp_str */ - PyObject_GenericGetAttr, /* tp_getattro */ - 0, /* tp_setattro */ - 0, /* tp_as_buffer */ - Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */ - complex_doc, /* tp_doc */ - 0, /* tp_traverse */ - 0, /* tp_clear */ - complex_richcompare, /* tp_richcompare */ - 0, /* tp_weaklistoffset */ - 0, /* tp_iter */ - 0, /* tp_iternext */ - complex_methods, /* tp_methods */ - complex_members, /* tp_members */ - 0, /* tp_getset */ - 0, /* tp_base */ - 0, /* tp_dict */ - 0, /* tp_descr_get */ - 0, /* tp_descr_set */ - 0, /* tp_dictoffset */ - 0, /* tp_init */ - PyType_GenericAlloc, /* tp_alloc */ - complex_new, /* tp_new */ - PyObject_Del, /* tp_free */ + PyVarObject_HEAD_INIT(&PyType_Type, 0) + "complex", + sizeof(PyComplexObject), + 0, + complex_dealloc, /* tp_dealloc */ + 0, /* tp_print */ + 0, /* tp_getattr */ + 0, /* tp_setattr */ + 0, /* tp_reserved */ + (reprfunc)complex_repr, /* tp_repr */ + &complex_as_number, /* tp_as_number */ + 0, /* tp_as_sequence */ + 0, /* tp_as_mapping */ + (hashfunc)complex_hash, /* tp_hash */ + 0, /* tp_call */ + (reprfunc)complex_str, /* tp_str */ + PyObject_GenericGetAttr, /* tp_getattro */ + 0, /* tp_setattro */ + 0, /* tp_as_buffer */ + Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */ + complex_doc, /* tp_doc */ + 0, /* tp_traverse */ + 0, /* tp_clear */ + complex_richcompare, /* tp_richcompare */ + 0, /* tp_weaklistoffset */ + 0, /* tp_iter */ + 0, /* tp_iternext */ + complex_methods, /* tp_methods */ + complex_members, /* tp_members */ + 0, /* tp_getset */ + 0, /* tp_base */ + 0, /* tp_dict */ + 0, /* tp_descr_get */ + 0, /* tp_descr_set */ + 0, /* tp_dictoffset */ + 0, /* tp_init */ + PyType_GenericAlloc, /* tp_alloc */ + complex_new, /* tp_new */ + PyObject_Del, /* tp_free */ }; #endif Modified: python/branches/release31-maint/Objects/descrobject.c ============================================================================== --- python/branches/release31-maint/Objects/descrobject.c (original) +++ python/branches/release31-maint/Objects/descrobject.c Sun May 9 18:14:21 2010 @@ -6,647 +6,647 @@ static void descr_dealloc(PyDescrObject *descr) { - _PyObject_GC_UNTRACK(descr); - Py_XDECREF(descr->d_type); - Py_XDECREF(descr->d_name); - PyObject_GC_Del(descr); + _PyObject_GC_UNTRACK(descr); + Py_XDECREF(descr->d_type); + Py_XDECREF(descr->d_name); + PyObject_GC_Del(descr); } static PyObject * descr_name(PyDescrObject *descr) { - if (descr->d_name != NULL && PyUnicode_Check(descr->d_name)) - return descr->d_name; - return NULL; + if (descr->d_name != NULL && PyUnicode_Check(descr->d_name)) + return descr->d_name; + return NULL; } static PyObject * descr_repr(PyDescrObject *descr, char *format) { - PyObject *name = NULL; - if (descr->d_name != NULL && PyUnicode_Check(descr->d_name)) - name = descr->d_name; + PyObject *name = NULL; + if (descr->d_name != NULL && PyUnicode_Check(descr->d_name)) + name = descr->d_name; - return PyUnicode_FromFormat(format, name, "?", descr->d_type->tp_name); + return PyUnicode_FromFormat(format, name, "?", descr->d_type->tp_name); } static PyObject * method_repr(PyMethodDescrObject *descr) { - return descr_repr((PyDescrObject *)descr, - ""); + return descr_repr((PyDescrObject *)descr, + ""); } static PyObject * member_repr(PyMemberDescrObject *descr) { - return descr_repr((PyDescrObject *)descr, - ""); + return descr_repr((PyDescrObject *)descr, + ""); } static PyObject * getset_repr(PyGetSetDescrObject *descr) { - return descr_repr((PyDescrObject *)descr, - ""); + return descr_repr((PyDescrObject *)descr, + ""); } static PyObject * wrapperdescr_repr(PyWrapperDescrObject *descr) { - return descr_repr((PyDescrObject *)descr, - ""); + return descr_repr((PyDescrObject *)descr, + ""); } static int descr_check(PyDescrObject *descr, PyObject *obj, PyObject **pres) { - if (obj == NULL) { - Py_INCREF(descr); - *pres = (PyObject *)descr; - return 1; - } - if (!PyObject_TypeCheck(obj, descr->d_type)) { - PyErr_Format(PyExc_TypeError, - "descriptor '%V' for '%s' objects " - "doesn't apply to '%s' object", - descr_name((PyDescrObject *)descr), "?", - descr->d_type->tp_name, - obj->ob_type->tp_name); - *pres = NULL; - return 1; - } - return 0; + if (obj == NULL) { + Py_INCREF(descr); + *pres = (PyObject *)descr; + return 1; + } + if (!PyObject_TypeCheck(obj, descr->d_type)) { + PyErr_Format(PyExc_TypeError, + "descriptor '%V' for '%s' objects " + "doesn't apply to '%s' object", + descr_name((PyDescrObject *)descr), "?", + descr->d_type->tp_name, + obj->ob_type->tp_name); + *pres = NULL; + return 1; + } + return 0; } static PyObject * classmethod_get(PyMethodDescrObject *descr, PyObject *obj, PyObject *type) { - /* Ensure a valid type. Class methods ignore obj. */ - if (type == NULL) { - if (obj != NULL) - type = (PyObject *)obj->ob_type; - else { - /* Wot - no type?! */ - PyErr_Format(PyExc_TypeError, - "descriptor '%V' for type '%s' " - "needs either an object or a type", - descr_name((PyDescrObject *)descr), "?", - descr->d_type->tp_name); - return NULL; - } - } - if (!PyType_Check(type)) { - PyErr_Format(PyExc_TypeError, - "descriptor '%V' for type '%s' " - "needs a type, not a '%s' as arg 2", - descr_name((PyDescrObject *)descr), "?", - descr->d_type->tp_name, - type->ob_type->tp_name); - return NULL; - } - if (!PyType_IsSubtype((PyTypeObject *)type, descr->d_type)) { - PyErr_Format(PyExc_TypeError, - "descriptor '%V' for type '%s' " - "doesn't apply to type '%s'", - descr_name((PyDescrObject *)descr), "?", - descr->d_type->tp_name, - ((PyTypeObject *)type)->tp_name); - return NULL; - } - return PyCFunction_New(descr->d_method, type); + /* Ensure a valid type. Class methods ignore obj. */ + if (type == NULL) { + if (obj != NULL) + type = (PyObject *)obj->ob_type; + else { + /* Wot - no type?! */ + PyErr_Format(PyExc_TypeError, + "descriptor '%V' for type '%s' " + "needs either an object or a type", + descr_name((PyDescrObject *)descr), "?", + descr->d_type->tp_name); + return NULL; + } + } + if (!PyType_Check(type)) { + PyErr_Format(PyExc_TypeError, + "descriptor '%V' for type '%s' " + "needs a type, not a '%s' as arg 2", + descr_name((PyDescrObject *)descr), "?", + descr->d_type->tp_name, + type->ob_type->tp_name); + return NULL; + } + if (!PyType_IsSubtype((PyTypeObject *)type, descr->d_type)) { + PyErr_Format(PyExc_TypeError, + "descriptor '%V' for type '%s' " + "doesn't apply to type '%s'", + descr_name((PyDescrObject *)descr), "?", + descr->d_type->tp_name, + ((PyTypeObject *)type)->tp_name); + return NULL; + } + return PyCFunction_New(descr->d_method, type); } static PyObject * method_get(PyMethodDescrObject *descr, PyObject *obj, PyObject *type) { - PyObject *res; + PyObject *res; - if (descr_check((PyDescrObject *)descr, obj, &res)) - return res; - return PyCFunction_New(descr->d_method, obj); + if (descr_check((PyDescrObject *)descr, obj, &res)) + return res; + return PyCFunction_New(descr->d_method, obj); } static PyObject * member_get(PyMemberDescrObject *descr, PyObject *obj, PyObject *type) { - PyObject *res; + PyObject *res; - if (descr_check((PyDescrObject *)descr, obj, &res)) - return res; - return PyMember_GetOne((char *)obj, descr->d_member); + if (descr_check((PyDescrObject *)descr, obj, &res)) + return res; + return PyMember_GetOne((char *)obj, descr->d_member); } static PyObject * getset_get(PyGetSetDescrObject *descr, PyObject *obj, PyObject *type) { - PyObject *res; + PyObject *res; - if (descr_check((PyDescrObject *)descr, obj, &res)) - return res; - if (descr->d_getset->get != NULL) - return descr->d_getset->get(obj, descr->d_getset->closure); - PyErr_Format(PyExc_AttributeError, - "attribute '%V' of '%.100s' objects is not readable", - descr_name((PyDescrObject *)descr), "?", - descr->d_type->tp_name); - return NULL; + if (descr_check((PyDescrObject *)descr, obj, &res)) + return res; + if (descr->d_getset->get != NULL) + return descr->d_getset->get(obj, descr->d_getset->closure); + PyErr_Format(PyExc_AttributeError, + "attribute '%V' of '%.100s' objects is not readable", + descr_name((PyDescrObject *)descr), "?", + descr->d_type->tp_name); + return NULL; } static PyObject * wrapperdescr_get(PyWrapperDescrObject *descr, PyObject *obj, PyObject *type) { - PyObject *res; + PyObject *res; - if (descr_check((PyDescrObject *)descr, obj, &res)) - return res; - return PyWrapper_New((PyObject *)descr, obj); + if (descr_check((PyDescrObject *)descr, obj, &res)) + return res; + return PyWrapper_New((PyObject *)descr, obj); } static int descr_setcheck(PyDescrObject *descr, PyObject *obj, PyObject *value, - int *pres) + int *pres) { - assert(obj != NULL); - if (!PyObject_TypeCheck(obj, descr->d_type)) { - PyErr_Format(PyExc_TypeError, - "descriptor '%V' for '%.100s' objects " - "doesn't apply to '%.100s' object", - descr_name(descr), "?", - descr->d_type->tp_name, - obj->ob_type->tp_name); - *pres = -1; - return 1; - } - return 0; + assert(obj != NULL); + if (!PyObject_TypeCheck(obj, descr->d_type)) { + PyErr_Format(PyExc_TypeError, + "descriptor '%V' for '%.100s' objects " + "doesn't apply to '%.100s' object", + descr_name(descr), "?", + descr->d_type->tp_name, + obj->ob_type->tp_name); + *pres = -1; + return 1; + } + return 0; } static int member_set(PyMemberDescrObject *descr, PyObject *obj, PyObject *value) { - int res; + int res; - if (descr_setcheck((PyDescrObject *)descr, obj, value, &res)) - return res; - return PyMember_SetOne((char *)obj, descr->d_member, value); + if (descr_setcheck((PyDescrObject *)descr, obj, value, &res)) + return res; + return PyMember_SetOne((char *)obj, descr->d_member, value); } static int getset_set(PyGetSetDescrObject *descr, PyObject *obj, PyObject *value) { - int res; + int res; - if (descr_setcheck((PyDescrObject *)descr, obj, value, &res)) - return res; - if (descr->d_getset->set != NULL) - return descr->d_getset->set(obj, value, - descr->d_getset->closure); - PyErr_Format(PyExc_AttributeError, - "attribute '%V' of '%.100s' objects is not writable", - descr_name((PyDescrObject *)descr), "?", - descr->d_type->tp_name); - return -1; + if (descr_setcheck((PyDescrObject *)descr, obj, value, &res)) + return res; + if (descr->d_getset->set != NULL) + return descr->d_getset->set(obj, value, + descr->d_getset->closure); + PyErr_Format(PyExc_AttributeError, + "attribute '%V' of '%.100s' objects is not writable", + descr_name((PyDescrObject *)descr), "?", + descr->d_type->tp_name); + return -1; } static PyObject * methoddescr_call(PyMethodDescrObject *descr, PyObject *args, PyObject *kwds) { - Py_ssize_t argc; - PyObject *self, *func, *result; + Py_ssize_t argc; + PyObject *self, *func, *result; - /* Make sure that the first argument is acceptable as 'self' */ - assert(PyTuple_Check(args)); - argc = PyTuple_GET_SIZE(args); - if (argc < 1) { - PyErr_Format(PyExc_TypeError, - "descriptor '%V' of '%.100s' " - "object needs an argument", - descr_name((PyDescrObject *)descr), "?", - descr->d_type->tp_name); - return NULL; - } - self = PyTuple_GET_ITEM(args, 0); - if (!PyObject_IsInstance(self, (PyObject *)(descr->d_type))) { - PyErr_Format(PyExc_TypeError, - "descriptor '%V' " - "requires a '%.100s' object " - "but received a '%.100s'", - descr_name((PyDescrObject *)descr), "?", - descr->d_type->tp_name, - self->ob_type->tp_name); - return NULL; - } - - func = PyCFunction_New(descr->d_method, self); - if (func == NULL) - return NULL; - args = PyTuple_GetSlice(args, 1, argc); - if (args == NULL) { - Py_DECREF(func); - return NULL; - } - result = PyEval_CallObjectWithKeywords(func, args, kwds); - Py_DECREF(args); - Py_DECREF(func); - return result; + /* Make sure that the first argument is acceptable as 'self' */ + assert(PyTuple_Check(args)); + argc = PyTuple_GET_SIZE(args); + if (argc < 1) { + PyErr_Format(PyExc_TypeError, + "descriptor '%V' of '%.100s' " + "object needs an argument", + descr_name((PyDescrObject *)descr), "?", + descr->d_type->tp_name); + return NULL; + } + self = PyTuple_GET_ITEM(args, 0); + if (!PyObject_IsInstance(self, (PyObject *)(descr->d_type))) { + PyErr_Format(PyExc_TypeError, + "descriptor '%V' " + "requires a '%.100s' object " + "but received a '%.100s'", + descr_name((PyDescrObject *)descr), "?", + descr->d_type->tp_name, + self->ob_type->tp_name); + return NULL; + } + + func = PyCFunction_New(descr->d_method, self); + if (func == NULL) + return NULL; + args = PyTuple_GetSlice(args, 1, argc); + if (args == NULL) { + Py_DECREF(func); + return NULL; + } + result = PyEval_CallObjectWithKeywords(func, args, kwds); + Py_DECREF(args); + Py_DECREF(func); + return result; } static PyObject * classmethoddescr_call(PyMethodDescrObject *descr, PyObject *args, - PyObject *kwds) + PyObject *kwds) { - PyObject *func, *result; + PyObject *func, *result; - func = PyCFunction_New(descr->d_method, (PyObject *)descr->d_type); - if (func == NULL) - return NULL; + func = PyCFunction_New(descr->d_method, (PyObject *)descr->d_type); + if (func == NULL) + return NULL; - result = PyEval_CallObjectWithKeywords(func, args, kwds); - Py_DECREF(func); - return result; + result = PyEval_CallObjectWithKeywords(func, args, kwds); + Py_DECREF(func); + return result; } static PyObject * wrapperdescr_call(PyWrapperDescrObject *descr, PyObject *args, PyObject *kwds) { - Py_ssize_t argc; - PyObject *self, *func, *result; + Py_ssize_t argc; + PyObject *self, *func, *result; - /* Make sure that the first argument is acceptable as 'self' */ - assert(PyTuple_Check(args)); - argc = PyTuple_GET_SIZE(args); - if (argc < 1) { - PyErr_Format(PyExc_TypeError, - "descriptor '%V' of '%.100s' " - "object needs an argument", - descr_name((PyDescrObject *)descr), "?", - descr->d_type->tp_name); - return NULL; - } - self = PyTuple_GET_ITEM(args, 0); - if (!PyObject_IsInstance(self, (PyObject *)(descr->d_type))) { - PyErr_Format(PyExc_TypeError, - "descriptor '%V' " - "requires a '%.100s' object " - "but received a '%.100s'", - descr_name((PyDescrObject *)descr), "?", - descr->d_type->tp_name, - self->ob_type->tp_name); - return NULL; - } - - func = PyWrapper_New((PyObject *)descr, self); - if (func == NULL) - return NULL; - args = PyTuple_GetSlice(args, 1, argc); - if (args == NULL) { - Py_DECREF(func); - return NULL; - } - result = PyEval_CallObjectWithKeywords(func, args, kwds); - Py_DECREF(args); - Py_DECREF(func); - return result; + /* Make sure that the first argument is acceptable as 'self' */ + assert(PyTuple_Check(args)); + argc = PyTuple_GET_SIZE(args); + if (argc < 1) { + PyErr_Format(PyExc_TypeError, + "descriptor '%V' of '%.100s' " + "object needs an argument", + descr_name((PyDescrObject *)descr), "?", + descr->d_type->tp_name); + return NULL; + } + self = PyTuple_GET_ITEM(args, 0); + if (!PyObject_IsInstance(self, (PyObject *)(descr->d_type))) { + PyErr_Format(PyExc_TypeError, + "descriptor '%V' " + "requires a '%.100s' object " + "but received a '%.100s'", + descr_name((PyDescrObject *)descr), "?", + descr->d_type->tp_name, + self->ob_type->tp_name); + return NULL; + } + + func = PyWrapper_New((PyObject *)descr, self); + if (func == NULL) + return NULL; + args = PyTuple_GetSlice(args, 1, argc); + if (args == NULL) { + Py_DECREF(func); + return NULL; + } + result = PyEval_CallObjectWithKeywords(func, args, kwds); + Py_DECREF(args); + Py_DECREF(func); + return result; } static PyObject * method_get_doc(PyMethodDescrObject *descr, void *closure) { - if (descr->d_method->ml_doc == NULL) { - Py_INCREF(Py_None); - return Py_None; - } - return PyUnicode_FromString(descr->d_method->ml_doc); + if (descr->d_method->ml_doc == NULL) { + Py_INCREF(Py_None); + return Py_None; + } + return PyUnicode_FromString(descr->d_method->ml_doc); } static PyMemberDef descr_members[] = { - {"__objclass__", T_OBJECT, offsetof(PyDescrObject, d_type), READONLY}, - {"__name__", T_OBJECT, offsetof(PyDescrObject, d_name), READONLY}, - {0} + {"__objclass__", T_OBJECT, offsetof(PyDescrObject, d_type), READONLY}, + {"__name__", T_OBJECT, offsetof(PyDescrObject, d_name), READONLY}, + {0} }; static PyGetSetDef method_getset[] = { - {"__doc__", (getter)method_get_doc}, - {0} + {"__doc__", (getter)method_get_doc}, + {0} }; static PyObject * member_get_doc(PyMemberDescrObject *descr, void *closure) { - if (descr->d_member->doc == NULL) { - Py_INCREF(Py_None); - return Py_None; - } - return PyUnicode_FromString(descr->d_member->doc); + if (descr->d_member->doc == NULL) { + Py_INCREF(Py_None); + return Py_None; + } + return PyUnicode_FromString(descr->d_member->doc); } static PyGetSetDef member_getset[] = { - {"__doc__", (getter)member_get_doc}, - {0} + {"__doc__", (getter)member_get_doc}, + {0} }; static PyObject * getset_get_doc(PyGetSetDescrObject *descr, void *closure) { - if (descr->d_getset->doc == NULL) { - Py_INCREF(Py_None); - return Py_None; - } - return PyUnicode_FromString(descr->d_getset->doc); + if (descr->d_getset->doc == NULL) { + Py_INCREF(Py_None); + return Py_None; + } + return PyUnicode_FromString(descr->d_getset->doc); } static PyGetSetDef getset_getset[] = { - {"__doc__", (getter)getset_get_doc}, - {0} + {"__doc__", (getter)getset_get_doc}, + {0} }; static PyObject * wrapperdescr_get_doc(PyWrapperDescrObject *descr, void *closure) { - if (descr->d_base->doc == NULL) { - Py_INCREF(Py_None); - return Py_None; - } - return PyUnicode_FromString(descr->d_base->doc); + if (descr->d_base->doc == NULL) { + Py_INCREF(Py_None); + return Py_None; + } + return PyUnicode_FromString(descr->d_base->doc); } static PyGetSetDef wrapperdescr_getset[] = { - {"__doc__", (getter)wrapperdescr_get_doc}, - {0} + {"__doc__", (getter)wrapperdescr_get_doc}, + {0} }; static int descr_traverse(PyObject *self, visitproc visit, void *arg) { - PyDescrObject *descr = (PyDescrObject *)self; - Py_VISIT(descr->d_type); - return 0; + PyDescrObject *descr = (PyDescrObject *)self; + Py_VISIT(descr->d_type); + return 0; } PyTypeObject PyMethodDescr_Type = { - PyVarObject_HEAD_INIT(&PyType_Type, 0) - "method_descriptor", - sizeof(PyMethodDescrObject), - 0, - (destructor)descr_dealloc, /* tp_dealloc */ - 0, /* tp_print */ - 0, /* tp_getattr */ - 0, /* tp_setattr */ - 0, /* tp_reserved */ - (reprfunc)method_repr, /* tp_repr */ - 0, /* tp_as_number */ - 0, /* tp_as_sequence */ - 0, /* tp_as_mapping */ - 0, /* tp_hash */ - (ternaryfunc)methoddescr_call, /* 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 */ - descr_traverse, /* tp_traverse */ - 0, /* tp_clear */ - 0, /* tp_richcompare */ - 0, /* tp_weaklistoffset */ - 0, /* tp_iter */ - 0, /* tp_iternext */ - 0, /* tp_methods */ - descr_members, /* tp_members */ - method_getset, /* tp_getset */ - 0, /* tp_base */ - 0, /* tp_dict */ - (descrgetfunc)method_get, /* tp_descr_get */ - 0, /* tp_descr_set */ + PyVarObject_HEAD_INIT(&PyType_Type, 0) + "method_descriptor", + sizeof(PyMethodDescrObject), + 0, + (destructor)descr_dealloc, /* tp_dealloc */ + 0, /* tp_print */ + 0, /* tp_getattr */ + 0, /* tp_setattr */ + 0, /* tp_reserved */ + (reprfunc)method_repr, /* tp_repr */ + 0, /* tp_as_number */ + 0, /* tp_as_sequence */ + 0, /* tp_as_mapping */ + 0, /* tp_hash */ + (ternaryfunc)methoddescr_call, /* 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 */ + descr_traverse, /* tp_traverse */ + 0, /* tp_clear */ + 0, /* tp_richcompare */ + 0, /* tp_weaklistoffset */ + 0, /* tp_iter */ + 0, /* tp_iternext */ + 0, /* tp_methods */ + descr_members, /* tp_members */ + method_getset, /* tp_getset */ + 0, /* tp_base */ + 0, /* tp_dict */ + (descrgetfunc)method_get, /* tp_descr_get */ + 0, /* tp_descr_set */ }; /* This is for METH_CLASS in C, not for "f = classmethod(f)" in Python! */ PyTypeObject PyClassMethodDescr_Type = { - PyVarObject_HEAD_INIT(&PyType_Type, 0) - "classmethod_descriptor", - sizeof(PyMethodDescrObject), - 0, - (destructor)descr_dealloc, /* tp_dealloc */ - 0, /* tp_print */ - 0, /* tp_getattr */ - 0, /* tp_setattr */ - 0, /* tp_reserved */ - (reprfunc)method_repr, /* tp_repr */ - 0, /* tp_as_number */ - 0, /* tp_as_sequence */ - 0, /* tp_as_mapping */ - 0, /* tp_hash */ - (ternaryfunc)classmethoddescr_call, /* 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 */ - descr_traverse, /* tp_traverse */ - 0, /* tp_clear */ - 0, /* tp_richcompare */ - 0, /* tp_weaklistoffset */ - 0, /* tp_iter */ - 0, /* tp_iternext */ - 0, /* tp_methods */ - descr_members, /* tp_members */ - method_getset, /* tp_getset */ - 0, /* tp_base */ - 0, /* tp_dict */ - (descrgetfunc)classmethod_get, /* tp_descr_get */ - 0, /* tp_descr_set */ + PyVarObject_HEAD_INIT(&PyType_Type, 0) + "classmethod_descriptor", + sizeof(PyMethodDescrObject), + 0, + (destructor)descr_dealloc, /* tp_dealloc */ + 0, /* tp_print */ + 0, /* tp_getattr */ + 0, /* tp_setattr */ + 0, /* tp_reserved */ + (reprfunc)method_repr, /* tp_repr */ + 0, /* tp_as_number */ + 0, /* tp_as_sequence */ + 0, /* tp_as_mapping */ + 0, /* tp_hash */ + (ternaryfunc)classmethoddescr_call, /* 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 */ + descr_traverse, /* tp_traverse */ + 0, /* tp_clear */ + 0, /* tp_richcompare */ + 0, /* tp_weaklistoffset */ + 0, /* tp_iter */ + 0, /* tp_iternext */ + 0, /* tp_methods */ + descr_members, /* tp_members */ + method_getset, /* tp_getset */ + 0, /* tp_base */ + 0, /* tp_dict */ + (descrgetfunc)classmethod_get, /* tp_descr_get */ + 0, /* tp_descr_set */ }; PyTypeObject PyMemberDescr_Type = { - PyVarObject_HEAD_INIT(&PyType_Type, 0) - "member_descriptor", - sizeof(PyMemberDescrObject), - 0, - (destructor)descr_dealloc, /* tp_dealloc */ - 0, /* tp_print */ - 0, /* tp_getattr */ - 0, /* tp_setattr */ - 0, /* tp_reserved */ - (reprfunc)member_repr, /* 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 */ - descr_traverse, /* tp_traverse */ - 0, /* tp_clear */ - 0, /* tp_richcompare */ - 0, /* tp_weaklistoffset */ - 0, /* tp_iter */ - 0, /* tp_iternext */ - 0, /* tp_methods */ - descr_members, /* tp_members */ - member_getset, /* tp_getset */ - 0, /* tp_base */ - 0, /* tp_dict */ - (descrgetfunc)member_get, /* tp_descr_get */ - (descrsetfunc)member_set, /* tp_descr_set */ + PyVarObject_HEAD_INIT(&PyType_Type, 0) + "member_descriptor", + sizeof(PyMemberDescrObject), + 0, + (destructor)descr_dealloc, /* tp_dealloc */ + 0, /* tp_print */ + 0, /* tp_getattr */ + 0, /* tp_setattr */ + 0, /* tp_reserved */ + (reprfunc)member_repr, /* 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 */ + descr_traverse, /* tp_traverse */ + 0, /* tp_clear */ + 0, /* tp_richcompare */ + 0, /* tp_weaklistoffset */ + 0, /* tp_iter */ + 0, /* tp_iternext */ + 0, /* tp_methods */ + descr_members, /* tp_members */ + member_getset, /* tp_getset */ + 0, /* tp_base */ + 0, /* tp_dict */ + (descrgetfunc)member_get, /* tp_descr_get */ + (descrsetfunc)member_set, /* tp_descr_set */ }; PyTypeObject PyGetSetDescr_Type = { - PyVarObject_HEAD_INIT(&PyType_Type, 0) - "getset_descriptor", - sizeof(PyGetSetDescrObject), - 0, - (destructor)descr_dealloc, /* tp_dealloc */ - 0, /* tp_print */ - 0, /* tp_getattr */ - 0, /* tp_setattr */ - 0, /* tp_reserved */ - (reprfunc)getset_repr, /* 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 */ - descr_traverse, /* tp_traverse */ - 0, /* tp_clear */ - 0, /* tp_richcompare */ - 0, /* tp_weaklistoffset */ - 0, /* tp_iter */ - 0, /* tp_iternext */ - 0, /* tp_methods */ - descr_members, /* tp_members */ - getset_getset, /* tp_getset */ - 0, /* tp_base */ - 0, /* tp_dict */ - (descrgetfunc)getset_get, /* tp_descr_get */ - (descrsetfunc)getset_set, /* tp_descr_set */ + PyVarObject_HEAD_INIT(&PyType_Type, 0) + "getset_descriptor", + sizeof(PyGetSetDescrObject), + 0, + (destructor)descr_dealloc, /* tp_dealloc */ + 0, /* tp_print */ + 0, /* tp_getattr */ + 0, /* tp_setattr */ + 0, /* tp_reserved */ + (reprfunc)getset_repr, /* 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 */ + descr_traverse, /* tp_traverse */ + 0, /* tp_clear */ + 0, /* tp_richcompare */ + 0, /* tp_weaklistoffset */ + 0, /* tp_iter */ + 0, /* tp_iternext */ + 0, /* tp_methods */ + descr_members, /* tp_members */ + getset_getset, /* tp_getset */ + 0, /* tp_base */ + 0, /* tp_dict */ + (descrgetfunc)getset_get, /* tp_descr_get */ + (descrsetfunc)getset_set, /* tp_descr_set */ }; PyTypeObject PyWrapperDescr_Type = { - PyVarObject_HEAD_INIT(&PyType_Type, 0) - "wrapper_descriptor", - sizeof(PyWrapperDescrObject), - 0, - (destructor)descr_dealloc, /* tp_dealloc */ - 0, /* tp_print */ - 0, /* tp_getattr */ - 0, /* tp_setattr */ - 0, /* tp_reserved */ - (reprfunc)wrapperdescr_repr, /* tp_repr */ - 0, /* tp_as_number */ - 0, /* tp_as_sequence */ - 0, /* tp_as_mapping */ - 0, /* tp_hash */ - (ternaryfunc)wrapperdescr_call, /* 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 */ - descr_traverse, /* tp_traverse */ - 0, /* tp_clear */ - 0, /* tp_richcompare */ - 0, /* tp_weaklistoffset */ - 0, /* tp_iter */ - 0, /* tp_iternext */ - 0, /* tp_methods */ - descr_members, /* tp_members */ - wrapperdescr_getset, /* tp_getset */ - 0, /* tp_base */ - 0, /* tp_dict */ - (descrgetfunc)wrapperdescr_get, /* tp_descr_get */ - 0, /* tp_descr_set */ + PyVarObject_HEAD_INIT(&PyType_Type, 0) + "wrapper_descriptor", + sizeof(PyWrapperDescrObject), + 0, + (destructor)descr_dealloc, /* tp_dealloc */ + 0, /* tp_print */ + 0, /* tp_getattr */ + 0, /* tp_setattr */ + 0, /* tp_reserved */ + (reprfunc)wrapperdescr_repr, /* tp_repr */ + 0, /* tp_as_number */ + 0, /* tp_as_sequence */ + 0, /* tp_as_mapping */ + 0, /* tp_hash */ + (ternaryfunc)wrapperdescr_call, /* 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 */ + descr_traverse, /* tp_traverse */ + 0, /* tp_clear */ + 0, /* tp_richcompare */ + 0, /* tp_weaklistoffset */ + 0, /* tp_iter */ + 0, /* tp_iternext */ + 0, /* tp_methods */ + descr_members, /* tp_members */ + wrapperdescr_getset, /* tp_getset */ + 0, /* tp_base */ + 0, /* tp_dict */ + (descrgetfunc)wrapperdescr_get, /* tp_descr_get */ + 0, /* tp_descr_set */ }; static PyDescrObject * descr_new(PyTypeObject *descrtype, PyTypeObject *type, const char *name) { - PyDescrObject *descr; + PyDescrObject *descr; - descr = (PyDescrObject *)PyType_GenericAlloc(descrtype, 0); - if (descr != NULL) { - Py_XINCREF(type); - descr->d_type = type; - descr->d_name = PyUnicode_InternFromString(name); - if (descr->d_name == NULL) { - Py_DECREF(descr); - descr = NULL; - } - } - return descr; + descr = (PyDescrObject *)PyType_GenericAlloc(descrtype, 0); + if (descr != NULL) { + Py_XINCREF(type); + descr->d_type = type; + descr->d_name = PyUnicode_InternFromString(name); + if (descr->d_name == NULL) { + Py_DECREF(descr); + descr = NULL; + } + } + return descr; } PyObject * PyDescr_NewMethod(PyTypeObject *type, PyMethodDef *method) { - PyMethodDescrObject *descr; + PyMethodDescrObject *descr; - descr = (PyMethodDescrObject *)descr_new(&PyMethodDescr_Type, - type, method->ml_name); - if (descr != NULL) - descr->d_method = method; - return (PyObject *)descr; + descr = (PyMethodDescrObject *)descr_new(&PyMethodDescr_Type, + type, method->ml_name); + if (descr != NULL) + descr->d_method = method; + return (PyObject *)descr; } PyObject * PyDescr_NewClassMethod(PyTypeObject *type, PyMethodDef *method) { - PyMethodDescrObject *descr; + PyMethodDescrObject *descr; - descr = (PyMethodDescrObject *)descr_new(&PyClassMethodDescr_Type, - type, method->ml_name); - if (descr != NULL) - descr->d_method = method; - return (PyObject *)descr; + descr = (PyMethodDescrObject *)descr_new(&PyClassMethodDescr_Type, + type, method->ml_name); + if (descr != NULL) + descr->d_method = method; + return (PyObject *)descr; } PyObject * PyDescr_NewMember(PyTypeObject *type, PyMemberDef *member) { - PyMemberDescrObject *descr; + PyMemberDescrObject *descr; - descr = (PyMemberDescrObject *)descr_new(&PyMemberDescr_Type, - type, member->name); - if (descr != NULL) - descr->d_member = member; - return (PyObject *)descr; + descr = (PyMemberDescrObject *)descr_new(&PyMemberDescr_Type, + type, member->name); + if (descr != NULL) + descr->d_member = member; + return (PyObject *)descr; } PyObject * PyDescr_NewGetSet(PyTypeObject *type, PyGetSetDef *getset) { - PyGetSetDescrObject *descr; + PyGetSetDescrObject *descr; - descr = (PyGetSetDescrObject *)descr_new(&PyGetSetDescr_Type, - type, getset->name); - if (descr != NULL) - descr->d_getset = getset; - return (PyObject *)descr; + descr = (PyGetSetDescrObject *)descr_new(&PyGetSetDescr_Type, + type, getset->name); + if (descr != NULL) + descr->d_getset = getset; + return (PyObject *)descr; } PyObject * PyDescr_NewWrapper(PyTypeObject *type, struct wrapperbase *base, void *wrapped) { - PyWrapperDescrObject *descr; + PyWrapperDescrObject *descr; - descr = (PyWrapperDescrObject *)descr_new(&PyWrapperDescr_Type, - type, base->name); - if (descr != NULL) { - descr->d_base = base; - descr->d_wrapped = wrapped; - } - return (PyObject *)descr; + descr = (PyWrapperDescrObject *)descr_new(&PyWrapperDescr_Type, + type, base->name); + if (descr != NULL) { + descr->d_base = base; + descr->d_wrapped = wrapped; + } + return (PyObject *)descr; } @@ -656,180 +656,180 @@ bit of a pain */ typedef struct { - PyObject_HEAD - PyObject *dict; + PyObject_HEAD + PyObject *dict; } proxyobject; static Py_ssize_t proxy_len(proxyobject *pp) { - return PyObject_Size(pp->dict); + return PyObject_Size(pp->dict); } static PyObject * proxy_getitem(proxyobject *pp, PyObject *key) { - return PyObject_GetItem(pp->dict, key); + return PyObject_GetItem(pp->dict, key); } static PyMappingMethods proxy_as_mapping = { - (lenfunc)proxy_len, /* mp_length */ - (binaryfunc)proxy_getitem, /* mp_subscript */ - 0, /* mp_ass_subscript */ + (lenfunc)proxy_len, /* mp_length */ + (binaryfunc)proxy_getitem, /* mp_subscript */ + 0, /* mp_ass_subscript */ }; static int proxy_contains(proxyobject *pp, PyObject *key) { - return PyDict_Contains(pp->dict, key); + return PyDict_Contains(pp->dict, key); } static PySequenceMethods proxy_as_sequence = { - 0, /* sq_length */ - 0, /* sq_concat */ - 0, /* sq_repeat */ - 0, /* sq_item */ - 0, /* sq_slice */ - 0, /* sq_ass_item */ - 0, /* sq_ass_slice */ - (objobjproc)proxy_contains, /* sq_contains */ - 0, /* sq_inplace_concat */ - 0, /* sq_inplace_repeat */ + 0, /* sq_length */ + 0, /* sq_concat */ + 0, /* sq_repeat */ + 0, /* sq_item */ + 0, /* sq_slice */ + 0, /* sq_ass_item */ + 0, /* sq_ass_slice */ + (objobjproc)proxy_contains, /* sq_contains */ + 0, /* sq_inplace_concat */ + 0, /* sq_inplace_repeat */ }; static PyObject * proxy_get(proxyobject *pp, PyObject *args) { - PyObject *key, *def = Py_None; + PyObject *key, *def = Py_None; - if (!PyArg_UnpackTuple(args, "get", 1, 2, &key, &def)) - return NULL; - return PyObject_CallMethod(pp->dict, "get", "(OO)", key, def); + if (!PyArg_UnpackTuple(args, "get", 1, 2, &key, &def)) + return NULL; + return PyObject_CallMethod(pp->dict, "get", "(OO)", key, def); } static PyObject * proxy_keys(proxyobject *pp) { - return PyMapping_Keys(pp->dict); + return PyMapping_Keys(pp->dict); } static PyObject * proxy_values(proxyobject *pp) { - return PyMapping_Values(pp->dict); + return PyMapping_Values(pp->dict); } static PyObject * proxy_items(proxyobject *pp) { - return PyMapping_Items(pp->dict); + return PyMapping_Items(pp->dict); } static PyObject * proxy_copy(proxyobject *pp) { - return PyObject_CallMethod(pp->dict, "copy", NULL); + return PyObject_CallMethod(pp->dict, "copy", NULL); } static PyMethodDef proxy_methods[] = { - {"get", (PyCFunction)proxy_get, METH_VARARGS, - PyDoc_STR("D.get(k[,d]) -> D[k] if k in D, else d." - " d defaults to None.")}, - {"keys", (PyCFunction)proxy_keys, METH_NOARGS, - PyDoc_STR("D.keys() -> list of D's keys")}, - {"values", (PyCFunction)proxy_values, METH_NOARGS, - PyDoc_STR("D.values() -> list of D's values")}, - {"items", (PyCFunction)proxy_items, METH_NOARGS, - PyDoc_STR("D.items() -> list of D's (key, value) pairs, as 2-tuples")}, - {"copy", (PyCFunction)proxy_copy, METH_NOARGS, - PyDoc_STR("D.copy() -> a shallow copy of D")}, - {0} + {"get", (PyCFunction)proxy_get, METH_VARARGS, + PyDoc_STR("D.get(k[,d]) -> D[k] if k in D, else d." + " d defaults to None.")}, + {"keys", (PyCFunction)proxy_keys, METH_NOARGS, + PyDoc_STR("D.keys() -> list of D's keys")}, + {"values", (PyCFunction)proxy_values, METH_NOARGS, + PyDoc_STR("D.values() -> list of D's values")}, + {"items", (PyCFunction)proxy_items, METH_NOARGS, + PyDoc_STR("D.items() -> list of D's (key, value) pairs, as 2-tuples")}, + {"copy", (PyCFunction)proxy_copy, METH_NOARGS, + PyDoc_STR("D.copy() -> a shallow copy of D")}, + {0} }; static void proxy_dealloc(proxyobject *pp) { - _PyObject_GC_UNTRACK(pp); - Py_DECREF(pp->dict); - PyObject_GC_Del(pp); + _PyObject_GC_UNTRACK(pp); + Py_DECREF(pp->dict); + PyObject_GC_Del(pp); } static PyObject * proxy_getiter(proxyobject *pp) { - return PyObject_GetIter(pp->dict); + return PyObject_GetIter(pp->dict); } static PyObject * proxy_str(proxyobject *pp) { - return PyObject_Str(pp->dict); + return PyObject_Str(pp->dict); } static int proxy_traverse(PyObject *self, visitproc visit, void *arg) { - proxyobject *pp = (proxyobject *)self; - Py_VISIT(pp->dict); - return 0; + proxyobject *pp = (proxyobject *)self; + Py_VISIT(pp->dict); + return 0; } static PyObject * proxy_richcompare(proxyobject *v, PyObject *w, int op) { - return PyObject_RichCompare(v->dict, w, op); + return PyObject_RichCompare(v->dict, w, op); } PyTypeObject PyDictProxy_Type = { - PyVarObject_HEAD_INIT(&PyType_Type, 0) - "dict_proxy", /* tp_name */ - sizeof(proxyobject), /* tp_basicsize */ - 0, /* tp_itemsize */ - /* methods */ - (destructor)proxy_dealloc, /* tp_dealloc */ - 0, /* tp_print */ - 0, /* tp_getattr */ - 0, /* tp_setattr */ - 0, /* tp_reserved */ - 0, /* tp_repr */ - 0, /* tp_as_number */ - &proxy_as_sequence, /* tp_as_sequence */ - &proxy_as_mapping, /* tp_as_mapping */ - 0, /* tp_hash */ - 0, /* tp_call */ - (reprfunc)proxy_str, /* 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 */ - proxy_traverse, /* tp_traverse */ - 0, /* tp_clear */ - (richcmpfunc)proxy_richcompare, /* tp_richcompare */ - 0, /* tp_weaklistoffset */ - (getiterfunc)proxy_getiter, /* tp_iter */ - 0, /* tp_iternext */ - proxy_methods, /* tp_methods */ - 0, /* tp_members */ - 0, /* tp_getset */ - 0, /* tp_base */ - 0, /* tp_dict */ - 0, /* tp_descr_get */ - 0, /* tp_descr_set */ + PyVarObject_HEAD_INIT(&PyType_Type, 0) + "dict_proxy", /* tp_name */ + sizeof(proxyobject), /* tp_basicsize */ + 0, /* tp_itemsize */ + /* methods */ + (destructor)proxy_dealloc, /* tp_dealloc */ + 0, /* tp_print */ + 0, /* tp_getattr */ + 0, /* tp_setattr */ + 0, /* tp_reserved */ + 0, /* tp_repr */ + 0, /* tp_as_number */ + &proxy_as_sequence, /* tp_as_sequence */ + &proxy_as_mapping, /* tp_as_mapping */ + 0, /* tp_hash */ + 0, /* tp_call */ + (reprfunc)proxy_str, /* 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 */ + proxy_traverse, /* tp_traverse */ + 0, /* tp_clear */ + (richcmpfunc)proxy_richcompare, /* tp_richcompare */ + 0, /* tp_weaklistoffset */ + (getiterfunc)proxy_getiter, /* tp_iter */ + 0, /* tp_iternext */ + proxy_methods, /* tp_methods */ + 0, /* tp_members */ + 0, /* tp_getset */ + 0, /* tp_base */ + 0, /* tp_dict */ + 0, /* tp_descr_get */ + 0, /* tp_descr_set */ }; PyObject * PyDictProxy_New(PyObject *dict) { - proxyobject *pp; + proxyobject *pp; - pp = PyObject_GC_New(proxyobject, &PyDictProxy_Type); - if (pp != NULL) { - Py_INCREF(dict); - pp->dict = dict; - _PyObject_GC_TRACK(pp); - } - return (PyObject *)pp; + pp = PyObject_GC_New(proxyobject, &PyDictProxy_Type); + if (pp != NULL) { + Py_INCREF(dict); + pp->dict = dict; + _PyObject_GC_TRACK(pp); + } + return (PyObject *)pp; } @@ -842,9 +842,9 @@ static PyTypeObject wrappertype; typedef struct { - PyObject_HEAD - PyWrapperDescrObject *descr; - PyObject *self; + PyObject_HEAD + PyWrapperDescrObject *descr; + PyObject *self; } wrapperobject; #define Wrapper_Check(v) (Py_TYPE(v) == &wrappertype) @@ -852,12 +852,12 @@ static void wrapper_dealloc(wrapperobject *wp) { - PyObject_GC_UnTrack(wp); - Py_TRASHCAN_SAFE_BEGIN(wp) - Py_XDECREF(wp->descr); - Py_XDECREF(wp->self); - PyObject_GC_Del(wp); - Py_TRASHCAN_SAFE_END(wp) + PyObject_GC_UnTrack(wp); + Py_TRASHCAN_SAFE_BEGIN(wp) + Py_XDECREF(wp->descr); + Py_XDECREF(wp->self); + PyObject_GC_Del(wp); + Py_TRASHCAN_SAFE_END(wp) } #define TEST_COND(cond) ((cond) ? Py_True : Py_False) @@ -865,211 +865,211 @@ static PyObject * wrapper_richcompare(PyObject *a, PyObject *b, int op) { - int result; - PyObject *v; - PyWrapperDescrObject *a_descr, *b_descr; - - assert(a != NULL && b != NULL); - - /* both arguments should be wrapperobjects */ - if (!Wrapper_Check(a) || !Wrapper_Check(b)) { - v = Py_NotImplemented; - Py_INCREF(v); - return v; - } - - /* compare by descriptor address; if the descriptors are the same, - compare by the objects they're bound to */ - a_descr = ((wrapperobject *)a)->descr; - b_descr = ((wrapperobject *)b)->descr; - if (a_descr == b_descr) { - a = ((wrapperobject *)a)->self; - b = ((wrapperobject *)b)->self; - return PyObject_RichCompare(a, b, op); - } - - result = a_descr - b_descr; - switch (op) { - case Py_EQ: - v = TEST_COND(result == 0); - break; - case Py_NE: - v = TEST_COND(result != 0); - break; - case Py_LE: - v = TEST_COND(result <= 0); - break; - case Py_GE: - v = TEST_COND(result >= 0); - break; - case Py_LT: - v = TEST_COND(result < 0); - break; - case Py_GT: - v = TEST_COND(result > 0); - break; - default: - PyErr_BadArgument(); - return NULL; - } - Py_INCREF(v); - return v; + int result; + PyObject *v; + PyWrapperDescrObject *a_descr, *b_descr; + + assert(a != NULL && b != NULL); + + /* both arguments should be wrapperobjects */ + if (!Wrapper_Check(a) || !Wrapper_Check(b)) { + v = Py_NotImplemented; + Py_INCREF(v); + return v; + } + + /* compare by descriptor address; if the descriptors are the same, + compare by the objects they're bound to */ + a_descr = ((wrapperobject *)a)->descr; + b_descr = ((wrapperobject *)b)->descr; + if (a_descr == b_descr) { + a = ((wrapperobject *)a)->self; + b = ((wrapperobject *)b)->self; + return PyObject_RichCompare(a, b, op); + } + + result = a_descr - b_descr; + switch (op) { + case Py_EQ: + v = TEST_COND(result == 0); + break; + case Py_NE: + v = TEST_COND(result != 0); + break; + case Py_LE: + v = TEST_COND(result <= 0); + break; + case Py_GE: + v = TEST_COND(result >= 0); + break; + case Py_LT: + v = TEST_COND(result < 0); + break; + case Py_GT: + v = TEST_COND(result > 0); + break; + default: + PyErr_BadArgument(); + return NULL; + } + Py_INCREF(v); + return v; } static long wrapper_hash(wrapperobject *wp) { - int x, y; - x = _Py_HashPointer(wp->descr); - if (x == -1) - return -1; - y = PyObject_Hash(wp->self); - if (y == -1) - return -1; - x = x ^ y; - if (x == -1) - x = -2; - return x; + int x, y; + x = _Py_HashPointer(wp->descr); + if (x == -1) + return -1; + y = PyObject_Hash(wp->self); + if (y == -1) + return -1; + x = x ^ y; + if (x == -1) + x = -2; + return x; } static PyObject * wrapper_repr(wrapperobject *wp) { - return PyUnicode_FromFormat("", - wp->descr->d_base->name, - wp->self->ob_type->tp_name, - wp->self); + return PyUnicode_FromFormat("", + wp->descr->d_base->name, + wp->self->ob_type->tp_name, + wp->self); } static PyMemberDef wrapper_members[] = { - {"__self__", T_OBJECT, offsetof(wrapperobject, self), READONLY}, - {0} + {"__self__", T_OBJECT, offsetof(wrapperobject, self), READONLY}, + {0} }; static PyObject * wrapper_objclass(wrapperobject *wp) { - PyObject *c = (PyObject *)wp->descr->d_type; + PyObject *c = (PyObject *)wp->descr->d_type; - Py_INCREF(c); - return c; + Py_INCREF(c); + return c; } static PyObject * wrapper_name(wrapperobject *wp) { - const char *s = wp->descr->d_base->name; + const char *s = wp->descr->d_base->name; - return PyUnicode_FromString(s); + return PyUnicode_FromString(s); } static PyObject * wrapper_doc(wrapperobject *wp) { - const char *s = wp->descr->d_base->doc; + const char *s = wp->descr->d_base->doc; - if (s == NULL) { - Py_INCREF(Py_None); - return Py_None; - } - else { - return PyUnicode_FromString(s); - } + if (s == NULL) { + Py_INCREF(Py_None); + return Py_None; + } + else { + return PyUnicode_FromString(s); + } } static PyGetSetDef wrapper_getsets[] = { - {"__objclass__", (getter)wrapper_objclass}, - {"__name__", (getter)wrapper_name}, - {"__doc__", (getter)wrapper_doc}, - {0} + {"__objclass__", (getter)wrapper_objclass}, + {"__name__", (getter)wrapper_name}, + {"__doc__", (getter)wrapper_doc}, + {0} }; static PyObject * wrapper_call(wrapperobject *wp, PyObject *args, PyObject *kwds) { - wrapperfunc wrapper = wp->descr->d_base->wrapper; - PyObject *self = wp->self; + wrapperfunc wrapper = wp->descr->d_base->wrapper; + PyObject *self = wp->self; - if (wp->descr->d_base->flags & PyWrapperFlag_KEYWORDS) { - wrapperfunc_kwds wk = (wrapperfunc_kwds)wrapper; - return (*wk)(self, args, wp->descr->d_wrapped, kwds); - } - - if (kwds != NULL && (!PyDict_Check(kwds) || PyDict_Size(kwds) != 0)) { - PyErr_Format(PyExc_TypeError, - "wrapper %s doesn't take keyword arguments", - wp->descr->d_base->name); - return NULL; - } - return (*wrapper)(self, args, wp->descr->d_wrapped); + if (wp->descr->d_base->flags & PyWrapperFlag_KEYWORDS) { + wrapperfunc_kwds wk = (wrapperfunc_kwds)wrapper; + return (*wk)(self, args, wp->descr->d_wrapped, kwds); + } + + if (kwds != NULL && (!PyDict_Check(kwds) || PyDict_Size(kwds) != 0)) { + PyErr_Format(PyExc_TypeError, + "wrapper %s doesn't take keyword arguments", + wp->descr->d_base->name); + return NULL; + } + return (*wrapper)(self, args, wp->descr->d_wrapped); } static int wrapper_traverse(PyObject *self, visitproc visit, void *arg) { - wrapperobject *wp = (wrapperobject *)self; - Py_VISIT(wp->descr); - Py_VISIT(wp->self); - return 0; + wrapperobject *wp = (wrapperobject *)self; + Py_VISIT(wp->descr); + Py_VISIT(wp->self); + return 0; } static PyTypeObject wrappertype = { - PyVarObject_HEAD_INIT(&PyType_Type, 0) - "method-wrapper", /* tp_name */ - sizeof(wrapperobject), /* tp_basicsize */ - 0, /* tp_itemsize */ - /* methods */ - (destructor)wrapper_dealloc, /* tp_dealloc */ - 0, /* tp_print */ - 0, /* tp_getattr */ - 0, /* tp_setattr */ - 0, /* tp_reserved */ - (reprfunc)wrapper_repr, /* tp_repr */ - 0, /* tp_as_number */ - 0, /* tp_as_sequence */ - 0, /* tp_as_mapping */ - (hashfunc)wrapper_hash, /* tp_hash */ - (ternaryfunc)wrapper_call, /* 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 */ - wrapper_traverse, /* tp_traverse */ - 0, /* tp_clear */ - wrapper_richcompare, /* tp_richcompare */ - 0, /* tp_weaklistoffset */ - 0, /* tp_iter */ - 0, /* tp_iternext */ - 0, /* tp_methods */ - wrapper_members, /* tp_members */ - wrapper_getsets, /* tp_getset */ - 0, /* tp_base */ - 0, /* tp_dict */ - 0, /* tp_descr_get */ - 0, /* tp_descr_set */ + PyVarObject_HEAD_INIT(&PyType_Type, 0) + "method-wrapper", /* tp_name */ + sizeof(wrapperobject), /* tp_basicsize */ + 0, /* tp_itemsize */ + /* methods */ + (destructor)wrapper_dealloc, /* tp_dealloc */ + 0, /* tp_print */ + 0, /* tp_getattr */ + 0, /* tp_setattr */ + 0, /* tp_reserved */ + (reprfunc)wrapper_repr, /* tp_repr */ + 0, /* tp_as_number */ + 0, /* tp_as_sequence */ + 0, /* tp_as_mapping */ + (hashfunc)wrapper_hash, /* tp_hash */ + (ternaryfunc)wrapper_call, /* 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 */ + wrapper_traverse, /* tp_traverse */ + 0, /* tp_clear */ + wrapper_richcompare, /* tp_richcompare */ + 0, /* tp_weaklistoffset */ + 0, /* tp_iter */ + 0, /* tp_iternext */ + 0, /* tp_methods */ + wrapper_members, /* tp_members */ + wrapper_getsets, /* tp_getset */ + 0, /* tp_base */ + 0, /* tp_dict */ + 0, /* tp_descr_get */ + 0, /* tp_descr_set */ }; PyObject * PyWrapper_New(PyObject *d, PyObject *self) { - wrapperobject *wp; - PyWrapperDescrObject *descr; + wrapperobject *wp; + PyWrapperDescrObject *descr; - assert(PyObject_TypeCheck(d, &PyWrapperDescr_Type)); - descr = (PyWrapperDescrObject *)d; - assert(PyObject_IsInstance(self, (PyObject *)(descr->d_type))); - - wp = PyObject_GC_New(wrapperobject, &wrappertype); - if (wp != NULL) { - Py_INCREF(descr); - wp->descr = descr; - Py_INCREF(self); - wp->self = self; - _PyObject_GC_TRACK(wp); - } - return (PyObject *)wp; + assert(PyObject_TypeCheck(d, &PyWrapperDescr_Type)); + descr = (PyWrapperDescrObject *)d; + assert(PyObject_IsInstance(self, (PyObject *)(descr->d_type))); + + wp = PyObject_GC_New(wrapperobject, &wrappertype); + if (wp != NULL) { + Py_INCREF(descr); + wp->descr = descr; + Py_INCREF(self); + wp->self = self; + _PyObject_GC_TRACK(wp); + } + return (PyObject *)wp; } @@ -1078,247 +1078,247 @@ /* class property(object): - def __init__(self, fget=None, fset=None, fdel=None, doc=None): - if doc is None and fget is not None and hasattr(fget, "__doc__"): - doc = fget.__doc__ - self.__get = fget - self.__set = fset - self.__del = fdel - self.__doc__ = doc - - def __get__(self, inst, type=None): - if inst is None: - return self - if self.__get is None: - raise AttributeError, "unreadable attribute" - return self.__get(inst) - - def __set__(self, inst, value): - if self.__set is None: - raise AttributeError, "can't set attribute" - return self.__set(inst, value) - - def __delete__(self, inst): - if self.__del is None: - raise AttributeError, "can't delete attribute" - return self.__del(inst) + def __init__(self, fget=None, fset=None, fdel=None, doc=None): + if doc is None and fget is not None and hasattr(fget, "__doc__"): + doc = fget.__doc__ + self.__get = fget + self.__set = fset + self.__del = fdel + self.__doc__ = doc + + def __get__(self, inst, type=None): + if inst is None: + return self + if self.__get is None: + raise AttributeError, "unreadable attribute" + return self.__get(inst) + + def __set__(self, inst, value): + if self.__set is None: + raise AttributeError, "can't set attribute" + return self.__set(inst, value) + + def __delete__(self, inst): + if self.__del is None: + raise AttributeError, "can't delete attribute" + return self.__del(inst) */ typedef struct { - PyObject_HEAD - PyObject *prop_get; - PyObject *prop_set; - PyObject *prop_del; - PyObject *prop_doc; - int getter_doc; + PyObject_HEAD + PyObject *prop_get; + PyObject *prop_set; + PyObject *prop_del; + PyObject *prop_doc; + int getter_doc; } propertyobject; static PyObject * property_copy(PyObject *, PyObject *, PyObject *, - PyObject *, PyObject *); + PyObject *, PyObject *); static PyMemberDef property_members[] = { - {"fget", T_OBJECT, offsetof(propertyobject, prop_get), READONLY}, - {"fset", T_OBJECT, offsetof(propertyobject, prop_set), READONLY}, - {"fdel", T_OBJECT, offsetof(propertyobject, prop_del), READONLY}, - {"__doc__", T_OBJECT, offsetof(propertyobject, prop_doc), READONLY}, - {0} + {"fget", T_OBJECT, offsetof(propertyobject, prop_get), READONLY}, + {"fset", T_OBJECT, offsetof(propertyobject, prop_set), READONLY}, + {"fdel", T_OBJECT, offsetof(propertyobject, prop_del), READONLY}, + {"__doc__", T_OBJECT, offsetof(propertyobject, prop_doc), READONLY}, + {0} }; PyDoc_STRVAR(getter_doc, - "Descriptor to change the getter on a property."); + "Descriptor to change the getter on a property."); static PyObject * property_getter(PyObject *self, PyObject *getter) { - return property_copy(self, getter, NULL, NULL, NULL); + return property_copy(self, getter, NULL, NULL, NULL); } PyDoc_STRVAR(setter_doc, - "Descriptor to change the setter on a property."); + "Descriptor to change the setter on a property."); static PyObject * property_setter(PyObject *self, PyObject *setter) { - return property_copy(self, NULL, setter, NULL, NULL); + return property_copy(self, NULL, setter, NULL, NULL); } PyDoc_STRVAR(deleter_doc, - "Descriptor to change the deleter on a property."); + "Descriptor to change the deleter on a property."); static PyObject * property_deleter(PyObject *self, PyObject *deleter) { - return property_copy(self, NULL, NULL, deleter, NULL); + return property_copy(self, NULL, NULL, deleter, NULL); } static PyMethodDef property_methods[] = { - {"getter", property_getter, METH_O, getter_doc}, - {"setter", property_setter, METH_O, setter_doc}, - {"deleter", property_deleter, METH_O, deleter_doc}, - {0} + {"getter", property_getter, METH_O, getter_doc}, + {"setter", property_setter, METH_O, setter_doc}, + {"deleter", property_deleter, METH_O, deleter_doc}, + {0} }; static void property_dealloc(PyObject *self) { - propertyobject *gs = (propertyobject *)self; + propertyobject *gs = (propertyobject *)self; - _PyObject_GC_UNTRACK(self); - Py_XDECREF(gs->prop_get); - Py_XDECREF(gs->prop_set); - Py_XDECREF(gs->prop_del); - Py_XDECREF(gs->prop_doc); - self->ob_type->tp_free(self); + _PyObject_GC_UNTRACK(self); + Py_XDECREF(gs->prop_get); + Py_XDECREF(gs->prop_set); + Py_XDECREF(gs->prop_del); + Py_XDECREF(gs->prop_doc); + self->ob_type->tp_free(self); } static PyObject * property_descr_get(PyObject *self, PyObject *obj, PyObject *type) { - propertyobject *gs = (propertyobject *)self; + propertyobject *gs = (propertyobject *)self; - if (obj == NULL || obj == Py_None) { - Py_INCREF(self); - return self; - } - if (gs->prop_get == NULL) { - PyErr_SetString(PyExc_AttributeError, "unreadable attribute"); - return NULL; - } - return PyObject_CallFunction(gs->prop_get, "(O)", obj); + if (obj == NULL || obj == Py_None) { + Py_INCREF(self); + return self; + } + if (gs->prop_get == NULL) { + PyErr_SetString(PyExc_AttributeError, "unreadable attribute"); + return NULL; + } + return PyObject_CallFunction(gs->prop_get, "(O)", obj); } static int property_descr_set(PyObject *self, PyObject *obj, PyObject *value) { - propertyobject *gs = (propertyobject *)self; - PyObject *func, *res; + propertyobject *gs = (propertyobject *)self; + PyObject *func, *res; - if (value == NULL) - func = gs->prop_del; - else - func = gs->prop_set; - if (func == NULL) { - PyErr_SetString(PyExc_AttributeError, - value == NULL ? - "can't delete attribute" : - "can't set attribute"); - return -1; - } - if (value == NULL) - res = PyObject_CallFunction(func, "(O)", obj); - else - res = PyObject_CallFunction(func, "(OO)", obj, value); - if (res == NULL) - return -1; - Py_DECREF(res); - return 0; + if (value == NULL) + func = gs->prop_del; + else + func = gs->prop_set; + if (func == NULL) { + PyErr_SetString(PyExc_AttributeError, + value == NULL ? + "can't delete attribute" : + "can't set attribute"); + return -1; + } + if (value == NULL) + res = PyObject_CallFunction(func, "(O)", obj); + else + res = PyObject_CallFunction(func, "(OO)", obj, value); + if (res == NULL) + return -1; + Py_DECREF(res); + return 0; } static PyObject * property_copy(PyObject *old, PyObject *get, PyObject *set, PyObject *del, - PyObject *doc) + PyObject *doc) { - propertyobject *pold = (propertyobject *)old; - PyObject *new, *type; + propertyobject *pold = (propertyobject *)old; + PyObject *new, *type; - type = PyObject_Type(old); - if (type == NULL) - return NULL; - - if (get == NULL || get == Py_None) { - Py_XDECREF(get); - get = pold->prop_get ? pold->prop_get : Py_None; - } - if (set == NULL || set == Py_None) { - Py_XDECREF(set); - set = pold->prop_set ? pold->prop_set : Py_None; - } - if (del == NULL || del == Py_None) { - Py_XDECREF(del); - del = pold->prop_del ? pold->prop_del : Py_None; - } - if (doc == NULL || doc == Py_None) { - Py_XDECREF(doc); - if (pold->getter_doc && get != Py_None) { - /* make _init use __doc__ from getter */ - doc = Py_None; - } - else { - doc = pold->prop_doc ? pold->prop_doc : Py_None; - } - } - - new = PyObject_CallFunction(type, "OOOO", get, set, del, doc); - Py_DECREF(type); - if (new == NULL) - return NULL; - return new; + type = PyObject_Type(old); + if (type == NULL) + return NULL; + + if (get == NULL || get == Py_None) { + Py_XDECREF(get); + get = pold->prop_get ? pold->prop_get : Py_None; + } + if (set == NULL || set == Py_None) { + Py_XDECREF(set); + set = pold->prop_set ? pold->prop_set : Py_None; + } + if (del == NULL || del == Py_None) { + Py_XDECREF(del); + del = pold->prop_del ? pold->prop_del : Py_None; + } + if (doc == NULL || doc == Py_None) { + Py_XDECREF(doc); + if (pold->getter_doc && get != Py_None) { + /* make _init use __doc__ from getter */ + doc = Py_None; + } + else { + doc = pold->prop_doc ? pold->prop_doc : Py_None; + } + } + + new = PyObject_CallFunction(type, "OOOO", get, set, del, doc); + Py_DECREF(type); + if (new == NULL) + return NULL; + return new; } static int property_init(PyObject *self, PyObject *args, PyObject *kwds) { - PyObject *get = NULL, *set = NULL, *del = NULL, *doc = NULL; - static char *kwlist[] = {"fget", "fset", "fdel", "doc", 0}; - propertyobject *prop = (propertyobject *)self; - - if (!PyArg_ParseTupleAndKeywords(args, kwds, "|OOOO:property", - kwlist, &get, &set, &del, &doc)) - return -1; - - if (get == Py_None) - get = NULL; - if (set == Py_None) - set = NULL; - if (del == Py_None) - del = NULL; - - Py_XINCREF(get); - Py_XINCREF(set); - Py_XINCREF(del); - Py_XINCREF(doc); - - prop->prop_get = get; - prop->prop_set = set; - prop->prop_del = del; - prop->prop_doc = doc; - prop->getter_doc = 0; - - /* if no docstring given and the getter has one, use that one */ - if ((doc == NULL || doc == Py_None) && get != NULL) { - PyObject *get_doc = PyObject_GetAttrString(get, "__doc__"); - if (get_doc) { - if (Py_TYPE(self) == &PyProperty_Type) { - Py_XDECREF(prop->prop_doc); - prop->prop_doc = get_doc; - } - else { - /* If this is a property subclass, put __doc__ - in dict of the subclass instance instead, - otherwise it gets shadowed by __doc__ in the - class's dict. */ - int err = PyObject_SetAttrString(self, "__doc__", get_doc); - Py_DECREF(get_doc); - if (err < 0) - return -1; - } - prop->getter_doc = 1; - } - else if (PyErr_ExceptionMatches(PyExc_Exception)) { - PyErr_Clear(); - } - else { - return -1; - } - } + PyObject *get = NULL, *set = NULL, *del = NULL, *doc = NULL; + static char *kwlist[] = {"fget", "fset", "fdel", "doc", 0}; + propertyobject *prop = (propertyobject *)self; + + if (!PyArg_ParseTupleAndKeywords(args, kwds, "|OOOO:property", + kwlist, &get, &set, &del, &doc)) + return -1; + + if (get == Py_None) + get = NULL; + if (set == Py_None) + set = NULL; + if (del == Py_None) + del = NULL; + + Py_XINCREF(get); + Py_XINCREF(set); + Py_XINCREF(del); + Py_XINCREF(doc); + + prop->prop_get = get; + prop->prop_set = set; + prop->prop_del = del; + prop->prop_doc = doc; + prop->getter_doc = 0; + + /* if no docstring given and the getter has one, use that one */ + if ((doc == NULL || doc == Py_None) && get != NULL) { + PyObject *get_doc = PyObject_GetAttrString(get, "__doc__"); + if (get_doc) { + if (Py_TYPE(self) == &PyProperty_Type) { + Py_XDECREF(prop->prop_doc); + prop->prop_doc = get_doc; + } + else { + /* If this is a property subclass, put __doc__ + in dict of the subclass instance instead, + otherwise it gets shadowed by __doc__ in the + class's dict. */ + int err = PyObject_SetAttrString(self, "__doc__", get_doc); + Py_DECREF(get_doc); + if (err < 0) + return -1; + } + prop->getter_doc = 1; + } + else if (PyErr_ExceptionMatches(PyExc_Exception)) { + PyErr_Clear(); + } + else { + return -1; + } + } - return 0; + return 0; } PyDoc_STRVAR(property_doc, @@ -1346,54 +1346,54 @@ static int property_traverse(PyObject *self, visitproc visit, void *arg) { - propertyobject *pp = (propertyobject *)self; - Py_VISIT(pp->prop_get); - Py_VISIT(pp->prop_set); - Py_VISIT(pp->prop_del); - Py_VISIT(pp->prop_doc); - return 0; + propertyobject *pp = (propertyobject *)self; + Py_VISIT(pp->prop_get); + Py_VISIT(pp->prop_set); + Py_VISIT(pp->prop_del); + Py_VISIT(pp->prop_doc); + return 0; } PyTypeObject PyProperty_Type = { - PyVarObject_HEAD_INIT(&PyType_Type, 0) - "property", /* tp_name */ - sizeof(propertyobject), /* tp_basicsize */ - 0, /* tp_itemsize */ - /* methods */ - property_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 | - Py_TPFLAGS_BASETYPE, /* tp_flags */ - property_doc, /* tp_doc */ - property_traverse, /* tp_traverse */ - 0, /* tp_clear */ - 0, /* tp_richcompare */ - 0, /* tp_weaklistoffset */ - 0, /* tp_iter */ - 0, /* tp_iternext */ - property_methods, /* tp_methods */ - property_members, /* tp_members */ - 0, /* tp_getset */ - 0, /* tp_base */ - 0, /* tp_dict */ - property_descr_get, /* tp_descr_get */ - property_descr_set, /* tp_descr_set */ - 0, /* tp_dictoffset */ - property_init, /* tp_init */ - PyType_GenericAlloc, /* tp_alloc */ - PyType_GenericNew, /* tp_new */ - PyObject_GC_Del, /* tp_free */ + PyVarObject_HEAD_INIT(&PyType_Type, 0) + "property", /* tp_name */ + sizeof(propertyobject), /* tp_basicsize */ + 0, /* tp_itemsize */ + /* methods */ + property_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 | + Py_TPFLAGS_BASETYPE, /* tp_flags */ + property_doc, /* tp_doc */ + property_traverse, /* tp_traverse */ + 0, /* tp_clear */ + 0, /* tp_richcompare */ + 0, /* tp_weaklistoffset */ + 0, /* tp_iter */ + 0, /* tp_iternext */ + property_methods, /* tp_methods */ + property_members, /* tp_members */ + 0, /* tp_getset */ + 0, /* tp_base */ + 0, /* tp_dict */ + property_descr_get, /* tp_descr_get */ + property_descr_set, /* tp_descr_set */ + 0, /* tp_dictoffset */ + property_init, /* tp_init */ + PyType_GenericAlloc, /* tp_alloc */ + PyType_GenericNew, /* tp_new */ + PyObject_GC_Del, /* tp_free */ }; Modified: python/branches/release31-maint/Objects/dictobject.c ============================================================================== --- python/branches/release31-maint/Objects/dictobject.c (original) +++ python/branches/release31-maint/Objects/dictobject.c Sun May 9 18:14:21 2010 @@ -17,12 +17,12 @@ static void set_key_error(PyObject *arg) { - PyObject *tup; - tup = PyTuple_Pack(1, arg); - if (!tup) - return; /* caller will expect error to be set anyway */ - PyErr_SetObject(PyExc_KeyError, tup); - Py_DECREF(tup); + PyObject *tup; + tup = PyTuple_Pack(1, arg); + if (!tup) + return; /* caller will expect error to be set anyway */ + PyErr_SetObject(PyExc_KeyError, tup); + Py_DECREF(tup); } /* Define this out if you don't want conversion statistics on exit. */ @@ -52,7 +52,7 @@ OTOH, when collisions occur, the tendency to fill contiguous slices of the hash table makes a good collision resolution strategy crucial. Taking only the last i bits of the hash code is also vulnerable: for example, consider -the list [i << 16 for i in range(20000)] as a set of keys. Since ints are +the list [i << 16 for i in range(20000)] as a set of keys. Since ints are their own hash codes, and this fits in a dict of size 2**15, the last 15 bits of every hash code are all 0: they *all* map to the same table index. @@ -142,7 +142,7 @@ PyObject * _PyDict_Dummy(void) { - return dummy; + return dummy; } #endif @@ -157,9 +157,9 @@ static void show_counts(void) { - fprintf(stderr, "created %ld string dicts\n", created); - fprintf(stderr, "converted %ld to normal dicts\n", converted); - fprintf(stderr, "%.2f%% conversion rate\n", (100.0*converted)/created); + fprintf(stderr, "created %ld string dicts\n", created); + fprintf(stderr, "converted %ld to normal dicts\n", converted); + fprintf(stderr, "%.2f%% conversion rate\n", (100.0*converted)/created); } #endif @@ -172,12 +172,12 @@ static void show_alloc(void) { - fprintf(stderr, "Dict allocations: %" PY_FORMAT_SIZE_T "d\n", - count_alloc); - fprintf(stderr, "Dict reuse through freelist: %" PY_FORMAT_SIZE_T - "d\n", count_reuse); - fprintf(stderr, "%.2f%% reuse rate\n\n", - (100.0*count_reuse/(count_alloc+count_reuse))); + fprintf(stderr, "Dict allocations: %" PY_FORMAT_SIZE_T "d\n", + count_alloc); + fprintf(stderr, "Dict reuse through freelist: %" PY_FORMAT_SIZE_T + "d\n", count_reuse); + fprintf(stderr, "%.2f%% reuse rate\n\n", + (100.0*count_reuse/(count_alloc+count_reuse))); } #endif @@ -189,12 +189,12 @@ static void show_track(void) { - fprintf(stderr, "Dicts created: %" PY_FORMAT_SIZE_T "d\n", - count_tracked + count_untracked); - fprintf(stderr, "Dicts tracked by the GC: %" PY_FORMAT_SIZE_T - "d\n", count_tracked); - fprintf(stderr, "%.2f%% dict tracking rate\n\n", - (100.0*count_tracked/(count_untracked+count_tracked))); + fprintf(stderr, "Dicts created: %" PY_FORMAT_SIZE_T "d\n", + count_tracked + count_untracked); + fprintf(stderr, "Dicts tracked by the GC: %" PY_FORMAT_SIZE_T + "d\n", count_tracked); + fprintf(stderr, "%.2f%% dict tracking rate\n\n", + (100.0*count_tracked/(count_untracked+count_tracked))); } #endif @@ -208,15 +208,15 @@ an excellent reason not to). */ -#define INIT_NONZERO_DICT_SLOTS(mp) do { \ - (mp)->ma_table = (mp)->ma_smalltable; \ - (mp)->ma_mask = PyDict_MINSIZE - 1; \ +#define INIT_NONZERO_DICT_SLOTS(mp) do { \ + (mp)->ma_table = (mp)->ma_smalltable; \ + (mp)->ma_mask = PyDict_MINSIZE - 1; \ } while(0) -#define EMPTY_TO_MINSIZE(mp) do { \ - memset((mp)->ma_smalltable, 0, sizeof((mp)->ma_smalltable)); \ - (mp)->ma_used = (mp)->ma_fill = 0; \ - INIT_NONZERO_DICT_SLOTS(mp); \ +#define EMPTY_TO_MINSIZE(mp) do { \ + memset((mp)->ma_smalltable, 0, sizeof((mp)->ma_smalltable)); \ + (mp)->ma_used = (mp)->ma_fill = 0; \ + INIT_NONZERO_DICT_SLOTS(mp); \ } while(0) /* Dictionary reuse scheme to save calls to malloc, free, and memset */ @@ -229,68 +229,68 @@ void PyDict_Fini(void) { - PyDictObject *op; + PyDictObject *op; - while (numfree) { - op = free_list[--numfree]; - assert(PyDict_CheckExact(op)); - PyObject_GC_Del(op); - } + while (numfree) { + op = free_list[--numfree]; + assert(PyDict_CheckExact(op)); + PyObject_GC_Del(op); + } } PyObject * PyDict_New(void) { - register PyDictObject *mp; - if (dummy == NULL) { /* Auto-initialize dummy */ - dummy = PyUnicode_FromString(""); - if (dummy == NULL) - return NULL; + register PyDictObject *mp; + if (dummy == NULL) { /* Auto-initialize dummy */ + dummy = PyUnicode_FromString(""); + if (dummy == NULL) + return NULL; #ifdef SHOW_CONVERSION_COUNTS - Py_AtExit(show_counts); + Py_AtExit(show_counts); #endif #ifdef SHOW_ALLOC_COUNT - Py_AtExit(show_alloc); + Py_AtExit(show_alloc); #endif #ifdef SHOW_TRACK_COUNT - Py_AtExit(show_track); + Py_AtExit(show_track); #endif - } - if (numfree) { - mp = free_list[--numfree]; - assert (mp != NULL); - assert (Py_TYPE(mp) == &PyDict_Type); - _Py_NewReference((PyObject *)mp); - if (mp->ma_fill) { - EMPTY_TO_MINSIZE(mp); - } else { - /* At least set ma_table and ma_mask; these are wrong - if an empty but presized dict is added to freelist */ - INIT_NONZERO_DICT_SLOTS(mp); - } - assert (mp->ma_used == 0); - assert (mp->ma_table == mp->ma_smalltable); - assert (mp->ma_mask == PyDict_MINSIZE - 1); + } + if (numfree) { + mp = free_list[--numfree]; + assert (mp != NULL); + assert (Py_TYPE(mp) == &PyDict_Type); + _Py_NewReference((PyObject *)mp); + if (mp->ma_fill) { + EMPTY_TO_MINSIZE(mp); + } else { + /* At least set ma_table and ma_mask; these are wrong + if an empty but presized dict is added to freelist */ + INIT_NONZERO_DICT_SLOTS(mp); + } + assert (mp->ma_used == 0); + assert (mp->ma_table == mp->ma_smalltable); + assert (mp->ma_mask == PyDict_MINSIZE - 1); #ifdef SHOW_ALLOC_COUNT - count_reuse++; + count_reuse++; #endif - } else { - mp = PyObject_GC_New(PyDictObject, &PyDict_Type); - if (mp == NULL) - return NULL; - EMPTY_TO_MINSIZE(mp); + } else { + mp = PyObject_GC_New(PyDictObject, &PyDict_Type); + if (mp == NULL) + return NULL; + EMPTY_TO_MINSIZE(mp); #ifdef SHOW_ALLOC_COUNT - count_alloc++; + count_alloc++; #endif - } - mp->ma_lookup = lookdict_unicode; + } + mp->ma_lookup = lookdict_unicode; #ifdef SHOW_TRACK_COUNT - count_untracked++; + count_untracked++; #endif #ifdef SHOW_CONVERSION_COUNTS - ++created; + ++created; #endif - return (PyObject *)mp; + return (PyObject *)mp; } /* @@ -320,80 +320,80 @@ static PyDictEntry * lookdict(PyDictObject *mp, PyObject *key, register long hash) { - register size_t i; - register size_t perturb; - register PyDictEntry *freeslot; - register size_t mask = (size_t)mp->ma_mask; - PyDictEntry *ep0 = mp->ma_table; - register PyDictEntry *ep; - register int cmp; - PyObject *startkey; - - i = (size_t)hash & mask; - ep = &ep0[i]; - if (ep->me_key == NULL || ep->me_key == key) - return ep; - - if (ep->me_key == dummy) - freeslot = ep; - else { - if (ep->me_hash == hash) { - startkey = ep->me_key; - Py_INCREF(startkey); - cmp = PyObject_RichCompareBool(startkey, key, Py_EQ); - Py_DECREF(startkey); - if (cmp < 0) - return NULL; - if (ep0 == mp->ma_table && ep->me_key == startkey) { - if (cmp > 0) - return ep; - } - else { - /* The compare did major nasty stuff to the - * dict: start over. - * XXX A clever adversary could prevent this - * XXX from terminating. - */ - return lookdict(mp, key, hash); - } - } - freeslot = NULL; - } - - /* In the loop, me_key == dummy is by far (factor of 100s) the - least likely outcome, so test for that last. */ - for (perturb = hash; ; perturb >>= PERTURB_SHIFT) { - i = (i << 2) + i + perturb + 1; - ep = &ep0[i & mask]; - if (ep->me_key == NULL) - return freeslot == NULL ? ep : freeslot; - if (ep->me_key == key) - return ep; - if (ep->me_hash == hash && ep->me_key != dummy) { - startkey = ep->me_key; - Py_INCREF(startkey); - cmp = PyObject_RichCompareBool(startkey, key, Py_EQ); - Py_DECREF(startkey); - if (cmp < 0) - return NULL; - if (ep0 == mp->ma_table && ep->me_key == startkey) { - if (cmp > 0) - return ep; - } - else { - /* The compare did major nasty stuff to the - * dict: start over. - * XXX A clever adversary could prevent this - * XXX from terminating. - */ - return lookdict(mp, key, hash); - } - } - else if (ep->me_key == dummy && freeslot == NULL) - freeslot = ep; - } - assert(0); /* NOT REACHED */ - return 0; + register size_t i; + register size_t perturb; + register PyDictEntry *freeslot; + register size_t mask = (size_t)mp->ma_mask; + PyDictEntry *ep0 = mp->ma_table; + register PyDictEntry *ep; + register int cmp; + PyObject *startkey; + + i = (size_t)hash & mask; + ep = &ep0[i]; + if (ep->me_key == NULL || ep->me_key == key) + return ep; + + if (ep->me_key == dummy) + freeslot = ep; + else { + if (ep->me_hash == hash) { + startkey = ep->me_key; + Py_INCREF(startkey); + cmp = PyObject_RichCompareBool(startkey, key, Py_EQ); + Py_DECREF(startkey); + if (cmp < 0) + return NULL; + if (ep0 == mp->ma_table && ep->me_key == startkey) { + if (cmp > 0) + return ep; + } + else { + /* The compare did major nasty stuff to the + * dict: start over. + * XXX A clever adversary could prevent this + * XXX from terminating. + */ + return lookdict(mp, key, hash); + } + } + freeslot = NULL; + } + + /* In the loop, me_key == dummy is by far (factor of 100s) the + least likely outcome, so test for that last. */ + for (perturb = hash; ; perturb >>= PERTURB_SHIFT) { + i = (i << 2) + i + perturb + 1; + ep = &ep0[i & mask]; + if (ep->me_key == NULL) + return freeslot == NULL ? ep : freeslot; + if (ep->me_key == key) + return ep; + if (ep->me_hash == hash && ep->me_key != dummy) { + startkey = ep->me_key; + Py_INCREF(startkey); + cmp = PyObject_RichCompareBool(startkey, key, Py_EQ); + Py_DECREF(startkey); + if (cmp < 0) + return NULL; + if (ep0 == mp->ma_table && ep->me_key == startkey) { + if (cmp > 0) + return ep; + } + else { + /* The compare did major nasty stuff to the + * dict: start over. + * XXX A clever adversary could prevent this + * XXX from terminating. + */ + return lookdict(mp, key, hash); + } + } + else if (ep->me_key == dummy && freeslot == NULL) + freeslot = ep; + } + assert(0); /* NOT REACHED */ + return 0; } /* @@ -409,99 +409,99 @@ static PyDictEntry * lookdict_unicode(PyDictObject *mp, PyObject *key, register long hash) { - register size_t i; - register size_t perturb; - register PyDictEntry *freeslot; - register size_t mask = (size_t)mp->ma_mask; - PyDictEntry *ep0 = mp->ma_table; - register PyDictEntry *ep; - - /* Make sure this function doesn't have to handle non-unicode keys, - including subclasses of str; e.g., one reason to subclass - unicodes is to override __eq__, and for speed we don't cater to - that here. */ - if (!PyUnicode_CheckExact(key)) { + register size_t i; + register size_t perturb; + register PyDictEntry *freeslot; + register size_t mask = (size_t)mp->ma_mask; + PyDictEntry *ep0 = mp->ma_table; + register PyDictEntry *ep; + + /* Make sure this function doesn't have to handle non-unicode keys, + including subclasses of str; e.g., one reason to subclass + unicodes is to override __eq__, and for speed we don't cater to + that here. */ + if (!PyUnicode_CheckExact(key)) { #ifdef SHOW_CONVERSION_COUNTS - ++converted; + ++converted; #endif - mp->ma_lookup = lookdict; - return lookdict(mp, key, hash); - } - i = hash & mask; - ep = &ep0[i]; - if (ep->me_key == NULL || ep->me_key == key) - return ep; - if (ep->me_key == dummy) - freeslot = ep; - else { - if (ep->me_hash == hash && unicode_eq(ep->me_key, key)) - return ep; - freeslot = NULL; - } - - /* In the loop, me_key == dummy is by far (factor of 100s) the - least likely outcome, so test for that last. */ - for (perturb = hash; ; perturb >>= PERTURB_SHIFT) { - i = (i << 2) + i + perturb + 1; - ep = &ep0[i & mask]; - if (ep->me_key == NULL) - return freeslot == NULL ? ep : freeslot; - if (ep->me_key == key - || (ep->me_hash == hash - && ep->me_key != dummy - && unicode_eq(ep->me_key, key))) - return ep; - if (ep->me_key == dummy && freeslot == NULL) - freeslot = ep; - } - assert(0); /* NOT REACHED */ - return 0; + mp->ma_lookup = lookdict; + return lookdict(mp, key, hash); + } + i = hash & mask; + ep = &ep0[i]; + if (ep->me_key == NULL || ep->me_key == key) + return ep; + if (ep->me_key == dummy) + freeslot = ep; + else { + if (ep->me_hash == hash && unicode_eq(ep->me_key, key)) + return ep; + freeslot = NULL; + } + + /* In the loop, me_key == dummy is by far (factor of 100s) the + least likely outcome, so test for that last. */ + for (perturb = hash; ; perturb >>= PERTURB_SHIFT) { + i = (i << 2) + i + perturb + 1; + ep = &ep0[i & mask]; + if (ep->me_key == NULL) + return freeslot == NULL ? ep : freeslot; + if (ep->me_key == key + || (ep->me_hash == hash + && ep->me_key != dummy + && unicode_eq(ep->me_key, key))) + return ep; + if (ep->me_key == dummy && freeslot == NULL) + freeslot = ep; + } + assert(0); /* NOT REACHED */ + return 0; } #ifdef SHOW_TRACK_COUNT #define INCREASE_TRACK_COUNT \ - (count_tracked++, count_untracked--); + (count_tracked++, count_untracked--); #define DECREASE_TRACK_COUNT \ - (count_tracked--, count_untracked++); + (count_tracked--, count_untracked++); #else #define INCREASE_TRACK_COUNT #define DECREASE_TRACK_COUNT #endif #define MAINTAIN_TRACKING(mp, key, value) \ - do { \ - if (!_PyObject_GC_IS_TRACKED(mp)) { \ - if (_PyObject_GC_MAY_BE_TRACKED(key) || \ - _PyObject_GC_MAY_BE_TRACKED(value)) { \ - _PyObject_GC_TRACK(mp); \ - INCREASE_TRACK_COUNT \ - } \ - } \ - } while(0) + do { \ + if (!_PyObject_GC_IS_TRACKED(mp)) { \ + if (_PyObject_GC_MAY_BE_TRACKED(key) || \ + _PyObject_GC_MAY_BE_TRACKED(value)) { \ + _PyObject_GC_TRACK(mp); \ + INCREASE_TRACK_COUNT \ + } \ + } \ + } while(0) void _PyDict_MaybeUntrack(PyObject *op) { - PyDictObject *mp; - PyObject *value; - Py_ssize_t mask, i; - PyDictEntry *ep; - - if (!PyDict_CheckExact(op) || !_PyObject_GC_IS_TRACKED(op)) - return; - - mp = (PyDictObject *) op; - ep = mp->ma_table; - mask = mp->ma_mask; - for (i = 0; i <= mask; i++) { - if ((value = ep[i].me_value) == NULL) - continue; - if (_PyObject_GC_MAY_BE_TRACKED(value) || - _PyObject_GC_MAY_BE_TRACKED(ep[i].me_key)) - return; - } - DECREASE_TRACK_COUNT - _PyObject_GC_UNTRACK(op); + PyDictObject *mp; + PyObject *value; + Py_ssize_t mask, i; + PyDictEntry *ep; + + if (!PyDict_CheckExact(op) || !_PyObject_GC_IS_TRACKED(op)) + return; + + mp = (PyDictObject *) op; + ep = mp->ma_table; + mask = mp->ma_mask; + for (i = 0; i <= mask; i++) { + if ((value = ep[i].me_value) == NULL) + continue; + if (_PyObject_GC_MAY_BE_TRACKED(value) || + _PyObject_GC_MAY_BE_TRACKED(ep[i].me_key)) + return; + } + DECREASE_TRACK_COUNT + _PyObject_GC_UNTRACK(op); } @@ -514,37 +514,37 @@ static int insertdict(register PyDictObject *mp, PyObject *key, long hash, PyObject *value) { - PyObject *old_value; - register PyDictEntry *ep; - typedef PyDictEntry *(*lookupfunc)(PyDictObject *, PyObject *, long); - - assert(mp->ma_lookup != NULL); - ep = mp->ma_lookup(mp, key, hash); - if (ep == NULL) { - Py_DECREF(key); - Py_DECREF(value); - return -1; - } - MAINTAIN_TRACKING(mp, key, value); - if (ep->me_value != NULL) { - old_value = ep->me_value; - ep->me_value = value; - Py_DECREF(old_value); /* which **CAN** re-enter */ - Py_DECREF(key); - } - else { - if (ep->me_key == NULL) - mp->ma_fill++; - else { - assert(ep->me_key == dummy); - Py_DECREF(dummy); - } - ep->me_key = key; - ep->me_hash = (Py_ssize_t)hash; - ep->me_value = value; - mp->ma_used++; - } - return 0; + PyObject *old_value; + register PyDictEntry *ep; + typedef PyDictEntry *(*lookupfunc)(PyDictObject *, PyObject *, long); + + assert(mp->ma_lookup != NULL); + ep = mp->ma_lookup(mp, key, hash); + if (ep == NULL) { + Py_DECREF(key); + Py_DECREF(value); + return -1; + } + MAINTAIN_TRACKING(mp, key, value); + if (ep->me_value != NULL) { + old_value = ep->me_value; + ep->me_value = value; + Py_DECREF(old_value); /* which **CAN** re-enter */ + Py_DECREF(key); + } + else { + if (ep->me_key == NULL) + mp->ma_fill++; + else { + assert(ep->me_key == dummy); + Py_DECREF(dummy); + } + ep->me_key = key; + ep->me_hash = (Py_ssize_t)hash; + ep->me_value = value; + mp->ma_used++; + } + return 0; } /* @@ -557,27 +557,27 @@ */ static void insertdict_clean(register PyDictObject *mp, PyObject *key, long hash, - PyObject *value) + PyObject *value) { - register size_t i; - register size_t perturb; - register size_t mask = (size_t)mp->ma_mask; - PyDictEntry *ep0 = mp->ma_table; - register PyDictEntry *ep; - - MAINTAIN_TRACKING(mp, key, value); - i = hash & mask; - ep = &ep0[i]; - for (perturb = hash; ep->me_key != NULL; perturb >>= PERTURB_SHIFT) { - i = (i << 2) + i + perturb + 1; - ep = &ep0[i & mask]; - } - assert(ep->me_value == NULL); - mp->ma_fill++; - ep->me_key = key; - ep->me_hash = (Py_ssize_t)hash; - ep->me_value = value; - mp->ma_used++; + register size_t i; + register size_t perturb; + register size_t mask = (size_t)mp->ma_mask; + PyDictEntry *ep0 = mp->ma_table; + register PyDictEntry *ep; + + MAINTAIN_TRACKING(mp, key, value); + i = hash & mask; + ep = &ep0[i]; + for (perturb = hash; ep->me_key != NULL; perturb >>= PERTURB_SHIFT) { + i = (i << 2) + i + perturb + 1; + ep = &ep0[i & mask]; + } + assert(ep->me_value == NULL); + mp->ma_fill++; + ep->me_key = key; + ep->me_hash = (Py_ssize_t)hash; + ep->me_value = value; + mp->ma_used++; } /* @@ -588,84 +588,84 @@ static int dictresize(PyDictObject *mp, Py_ssize_t minused) { - Py_ssize_t newsize; - PyDictEntry *oldtable, *newtable, *ep; - Py_ssize_t i; - int is_oldtable_malloced; - PyDictEntry small_copy[PyDict_MINSIZE]; - - assert(minused >= 0); - - /* Find the smallest table size > minused. */ - for (newsize = PyDict_MINSIZE; - newsize <= minused && newsize > 0; - newsize <<= 1) - ; - if (newsize <= 0) { - PyErr_NoMemory(); - return -1; - } - - /* Get space for a new table. */ - oldtable = mp->ma_table; - assert(oldtable != NULL); - is_oldtable_malloced = oldtable != mp->ma_smalltable; - - if (newsize == PyDict_MINSIZE) { - /* A large table is shrinking, or we can't get any smaller. */ - newtable = mp->ma_smalltable; - if (newtable == oldtable) { - if (mp->ma_fill == mp->ma_used) { - /* No dummies, so no point doing anything. */ - return 0; - } - /* We're not going to resize it, but rebuild the - table anyway to purge old dummy entries. - Subtle: This is *necessary* if fill==size, - as lookdict needs at least one virgin slot to - terminate failing searches. If fill < size, it's - merely desirable, as dummies slow searches. */ - assert(mp->ma_fill > mp->ma_used); - memcpy(small_copy, oldtable, sizeof(small_copy)); - oldtable = small_copy; - } - } - else { - newtable = PyMem_NEW(PyDictEntry, newsize); - if (newtable == NULL) { - PyErr_NoMemory(); - return -1; - } - } - - /* Make the dict empty, using the new table. */ - assert(newtable != oldtable); - mp->ma_table = newtable; - mp->ma_mask = newsize - 1; - memset(newtable, 0, sizeof(PyDictEntry) * newsize); - mp->ma_used = 0; - i = mp->ma_fill; - mp->ma_fill = 0; - - /* Copy the data over; this is refcount-neutral for active entries; - dummy entries aren't copied over, of course */ - for (ep = oldtable; i > 0; ep++) { - if (ep->me_value != NULL) { /* active entry */ - --i; - insertdict_clean(mp, ep->me_key, (long)ep->me_hash, - ep->me_value); - } - else if (ep->me_key != NULL) { /* dummy entry */ - --i; - assert(ep->me_key == dummy); - Py_DECREF(ep->me_key); - } - /* else key == value == NULL: nothing to do */ - } - - if (is_oldtable_malloced) - PyMem_DEL(oldtable); - return 0; + Py_ssize_t newsize; + PyDictEntry *oldtable, *newtable, *ep; + Py_ssize_t i; + int is_oldtable_malloced; + PyDictEntry small_copy[PyDict_MINSIZE]; + + assert(minused >= 0); + + /* Find the smallest table size > minused. */ + for (newsize = PyDict_MINSIZE; + newsize <= minused && newsize > 0; + newsize <<= 1) + ; + if (newsize <= 0) { + PyErr_NoMemory(); + return -1; + } + + /* Get space for a new table. */ + oldtable = mp->ma_table; + assert(oldtable != NULL); + is_oldtable_malloced = oldtable != mp->ma_smalltable; + + if (newsize == PyDict_MINSIZE) { + /* A large table is shrinking, or we can't get any smaller. */ + newtable = mp->ma_smalltable; + if (newtable == oldtable) { + if (mp->ma_fill == mp->ma_used) { + /* No dummies, so no point doing anything. */ + return 0; + } + /* We're not going to resize it, but rebuild the + table anyway to purge old dummy entries. + Subtle: This is *necessary* if fill==size, + as lookdict needs at least one virgin slot to + terminate failing searches. If fill < size, it's + merely desirable, as dummies slow searches. */ + assert(mp->ma_fill > mp->ma_used); + memcpy(small_copy, oldtable, sizeof(small_copy)); + oldtable = small_copy; + } + } + else { + newtable = PyMem_NEW(PyDictEntry, newsize); + if (newtable == NULL) { + PyErr_NoMemory(); + return -1; + } + } + + /* Make the dict empty, using the new table. */ + assert(newtable != oldtable); + mp->ma_table = newtable; + mp->ma_mask = newsize - 1; + memset(newtable, 0, sizeof(PyDictEntry) * newsize); + mp->ma_used = 0; + i = mp->ma_fill; + mp->ma_fill = 0; + + /* Copy the data over; this is refcount-neutral for active entries; + dummy entries aren't copied over, of course */ + for (ep = oldtable; i > 0; ep++) { + if (ep->me_value != NULL) { /* active entry */ + --i; + insertdict_clean(mp, ep->me_key, (long)ep->me_hash, + ep->me_value); + } + else if (ep->me_key != NULL) { /* dummy entry */ + --i; + assert(ep->me_key == dummy); + Py_DECREF(ep->me_key); + } + /* else key == value == NULL: nothing to do */ + } + + if (is_oldtable_malloced) + PyMem_DEL(oldtable); + return 0; } /* Create a new dictionary pre-sized to hold an estimated number of elements. @@ -676,13 +676,13 @@ PyObject * _PyDict_NewPresized(Py_ssize_t minused) { - PyObject *op = PyDict_New(); + PyObject *op = PyDict_New(); - if (minused>5 && op != NULL && dictresize((PyDictObject *)op, minused) == -1) { - Py_DECREF(op); - return NULL; - } - return op; + if (minused>5 && op != NULL && dictresize((PyDictObject *)op, minused) == -1) { + Py_DECREF(op); + return NULL; + } + return op; } /* Note that, for historical reasons, PyDict_GetItem() suppresses all errors @@ -698,46 +698,46 @@ PyObject * PyDict_GetItem(PyObject *op, PyObject *key) { - long hash; - PyDictObject *mp = (PyDictObject *)op; - PyDictEntry *ep; - PyThreadState *tstate; - if (!PyDict_Check(op)) - return NULL; - if (!PyUnicode_CheckExact(key) || - (hash = ((PyUnicodeObject *) key)->hash) == -1) - { - hash = PyObject_Hash(key); - if (hash == -1) { - PyErr_Clear(); - return NULL; - } - } - - /* We can arrive here with a NULL tstate during initialization: try - running "python -Wi" for an example related to string interning. - Let's just hope that no exception occurs then... This must be - _PyThreadState_Current and not PyThreadState_GET() because in debug - mode, the latter complains if tstate is NULL. */ - tstate = _PyThreadState_Current; - if (tstate != NULL && tstate->curexc_type != NULL) { - /* preserve the existing exception */ - PyObject *err_type, *err_value, *err_tb; - PyErr_Fetch(&err_type, &err_value, &err_tb); - ep = (mp->ma_lookup)(mp, key, hash); - /* ignore errors */ - PyErr_Restore(err_type, err_value, err_tb); - if (ep == NULL) - return NULL; - } - else { - ep = (mp->ma_lookup)(mp, key, hash); - if (ep == NULL) { - PyErr_Clear(); - return NULL; - } - } - return ep->me_value; + long hash; + PyDictObject *mp = (PyDictObject *)op; + PyDictEntry *ep; + PyThreadState *tstate; + if (!PyDict_Check(op)) + return NULL; + if (!PyUnicode_CheckExact(key) || + (hash = ((PyUnicodeObject *) key)->hash) == -1) + { + hash = PyObject_Hash(key); + if (hash == -1) { + PyErr_Clear(); + return NULL; + } + } + + /* We can arrive here with a NULL tstate during initialization: try + running "python -Wi" for an example related to string interning. + Let's just hope that no exception occurs then... This must be + _PyThreadState_Current and not PyThreadState_GET() because in debug + mode, the latter complains if tstate is NULL. */ + tstate = _PyThreadState_Current; + if (tstate != NULL && tstate->curexc_type != NULL) { + /* preserve the existing exception */ + PyObject *err_type, *err_value, *err_tb; + PyErr_Fetch(&err_type, &err_value, &err_tb); + ep = (mp->ma_lookup)(mp, key, hash); + /* ignore errors */ + PyErr_Restore(err_type, err_value, err_tb); + if (ep == NULL) + return NULL; + } + else { + ep = (mp->ma_lookup)(mp, key, hash); + if (ep == NULL) { + PyErr_Clear(); + return NULL; + } + } + return ep->me_value; } /* Variant of PyDict_GetItem() that doesn't suppress exceptions. @@ -747,27 +747,27 @@ PyObject * PyDict_GetItemWithError(PyObject *op, PyObject *key) { - long hash; - PyDictObject*mp = (PyDictObject *)op; - PyDictEntry *ep; - - if (!PyDict_Check(op)) { - PyErr_BadInternalCall(); - return NULL; - } - if (!PyUnicode_CheckExact(key) || - (hash = ((PyUnicodeObject *) key)->hash) == -1) - { - hash = PyObject_Hash(key); - if (hash == -1) { - return NULL; - } - } - - ep = (mp->ma_lookup)(mp, key, hash); - if (ep == NULL) - return NULL; - return ep->me_value; + long hash; + PyDictObject*mp = (PyDictObject *)op; + PyDictEntry *ep; + + if (!PyDict_Check(op)) { + PyErr_BadInternalCall(); + return NULL; + } + if (!PyUnicode_CheckExact(key) || + (hash = ((PyUnicodeObject *) key)->hash) == -1) + { + hash = PyObject_Hash(key); + if (hash == -1) { + return NULL; + } + } + + ep = (mp->ma_lookup)(mp, key, hash); + if (ep == NULL) + return NULL; + return ep->me_value; } /* CAUTION: PyDict_SetItem() must guarantee that it won't resize the @@ -779,154 +779,154 @@ int PyDict_SetItem(register PyObject *op, PyObject *key, PyObject *value) { - register PyDictObject *mp; - register long hash; - register Py_ssize_t n_used; - - if (!PyDict_Check(op)) { - PyErr_BadInternalCall(); - return -1; - } - assert(key); - assert(value); - mp = (PyDictObject *)op; - if (!PyUnicode_CheckExact(key) || - (hash = ((PyUnicodeObject *) key)->hash) == -1) - { - hash = PyObject_Hash(key); - if (hash == -1) - return -1; - } - assert(mp->ma_fill <= mp->ma_mask); /* at least one empty slot */ - n_used = mp->ma_used; - Py_INCREF(value); - Py_INCREF(key); - if (insertdict(mp, key, hash, value) != 0) - return -1; - /* If we added a key, we can safely resize. Otherwise just return! - * If fill >= 2/3 size, adjust size. Normally, this doubles or - * quaduples the size, but it's also possible for the dict to shrink - * (if ma_fill is much larger than ma_used, meaning a lot of dict - * keys have been * deleted). - * - * Quadrupling the size improves average dictionary sparseness - * (reducing collisions) at the cost of some memory and iteration - * speed (which loops over every possible entry). It also halves - * the number of expensive resize operations in a growing dictionary. - * - * Very large dictionaries (over 50K items) use doubling instead. - * This may help applications with severe memory constraints. - */ - if (!(mp->ma_used > n_used && mp->ma_fill*3 >= (mp->ma_mask+1)*2)) - return 0; - return dictresize(mp, (mp->ma_used > 50000 ? 2 : 4) * mp->ma_used); + register PyDictObject *mp; + register long hash; + register Py_ssize_t n_used; + + if (!PyDict_Check(op)) { + PyErr_BadInternalCall(); + return -1; + } + assert(key); + assert(value); + mp = (PyDictObject *)op; + if (!PyUnicode_CheckExact(key) || + (hash = ((PyUnicodeObject *) key)->hash) == -1) + { + hash = PyObject_Hash(key); + if (hash == -1) + return -1; + } + assert(mp->ma_fill <= mp->ma_mask); /* at least one empty slot */ + n_used = mp->ma_used; + Py_INCREF(value); + Py_INCREF(key); + if (insertdict(mp, key, hash, value) != 0) + return -1; + /* If we added a key, we can safely resize. Otherwise just return! + * If fill >= 2/3 size, adjust size. Normally, this doubles or + * quaduples the size, but it's also possible for the dict to shrink + * (if ma_fill is much larger than ma_used, meaning a lot of dict + * keys have been * deleted). + * + * Quadrupling the size improves average dictionary sparseness + * (reducing collisions) at the cost of some memory and iteration + * speed (which loops over every possible entry). It also halves + * the number of expensive resize operations in a growing dictionary. + * + * Very large dictionaries (over 50K items) use doubling instead. + * This may help applications with severe memory constraints. + */ + if (!(mp->ma_used > n_used && mp->ma_fill*3 >= (mp->ma_mask+1)*2)) + return 0; + return dictresize(mp, (mp->ma_used > 50000 ? 2 : 4) * mp->ma_used); } int PyDict_DelItem(PyObject *op, PyObject *key) { - register PyDictObject *mp; - register long hash; - register PyDictEntry *ep; - PyObject *old_value, *old_key; - - if (!PyDict_Check(op)) { - PyErr_BadInternalCall(); - return -1; - } - assert(key); - if (!PyUnicode_CheckExact(key) || - (hash = ((PyUnicodeObject *) key)->hash) == -1) { - hash = PyObject_Hash(key); - if (hash == -1) - return -1; - } - mp = (PyDictObject *)op; - ep = (mp->ma_lookup)(mp, key, hash); - if (ep == NULL) - return -1; - if (ep->me_value == NULL) { - set_key_error(key); - return -1; - } - old_key = ep->me_key; - Py_INCREF(dummy); - ep->me_key = dummy; - old_value = ep->me_value; - ep->me_value = NULL; - mp->ma_used--; - Py_DECREF(old_value); - Py_DECREF(old_key); - return 0; + register PyDictObject *mp; + register long hash; + register PyDictEntry *ep; + PyObject *old_value, *old_key; + + if (!PyDict_Check(op)) { + PyErr_BadInternalCall(); + return -1; + } + assert(key); + if (!PyUnicode_CheckExact(key) || + (hash = ((PyUnicodeObject *) key)->hash) == -1) { + hash = PyObject_Hash(key); + if (hash == -1) + return -1; + } + mp = (PyDictObject *)op; + ep = (mp->ma_lookup)(mp, key, hash); + if (ep == NULL) + return -1; + if (ep->me_value == NULL) { + set_key_error(key); + return -1; + } + old_key = ep->me_key; + Py_INCREF(dummy); + ep->me_key = dummy; + old_value = ep->me_value; + ep->me_value = NULL; + mp->ma_used--; + Py_DECREF(old_value); + Py_DECREF(old_key); + return 0; } void PyDict_Clear(PyObject *op) { - PyDictObject *mp; - PyDictEntry *ep, *table; - int table_is_malloced; - Py_ssize_t fill; - PyDictEntry small_copy[PyDict_MINSIZE]; + PyDictObject *mp; + PyDictEntry *ep, *table; + int table_is_malloced; + Py_ssize_t fill; + PyDictEntry small_copy[PyDict_MINSIZE]; #ifdef Py_DEBUG - Py_ssize_t i, n; + Py_ssize_t i, n; #endif - if (!PyDict_Check(op)) - return; - mp = (PyDictObject *)op; + if (!PyDict_Check(op)) + return; + mp = (PyDictObject *)op; #ifdef Py_DEBUG - n = mp->ma_mask + 1; - i = 0; + n = mp->ma_mask + 1; + i = 0; #endif - table = mp->ma_table; - assert(table != NULL); - table_is_malloced = table != mp->ma_smalltable; - - /* This is delicate. During the process of clearing the dict, - * decrefs can cause the dict to mutate. To avoid fatal confusion - * (voice of experience), we have to make the dict empty before - * clearing the slots, and never refer to anything via mp->xxx while - * clearing. - */ - fill = mp->ma_fill; - if (table_is_malloced) - EMPTY_TO_MINSIZE(mp); - - else if (fill > 0) { - /* It's a small table with something that needs to be cleared. - * Afraid the only safe way is to copy the dict entries into - * another small table first. - */ - memcpy(small_copy, table, sizeof(small_copy)); - table = small_copy; - EMPTY_TO_MINSIZE(mp); - } - /* else it's a small table that's already empty */ - - /* Now we can finally clear things. If C had refcounts, we could - * assert that the refcount on table is 1 now, i.e. that this function - * has unique access to it, so decref side-effects can't alter it. - */ - for (ep = table; fill > 0; ++ep) { + table = mp->ma_table; + assert(table != NULL); + table_is_malloced = table != mp->ma_smalltable; + + /* This is delicate. During the process of clearing the dict, + * decrefs can cause the dict to mutate. To avoid fatal confusion + * (voice of experience), we have to make the dict empty before + * clearing the slots, and never refer to anything via mp->xxx while + * clearing. + */ + fill = mp->ma_fill; + if (table_is_malloced) + EMPTY_TO_MINSIZE(mp); + + else if (fill > 0) { + /* It's a small table with something that needs to be cleared. + * Afraid the only safe way is to copy the dict entries into + * another small table first. + */ + memcpy(small_copy, table, sizeof(small_copy)); + table = small_copy; + EMPTY_TO_MINSIZE(mp); + } + /* else it's a small table that's already empty */ + + /* Now we can finally clear things. If C had refcounts, we could + * assert that the refcount on table is 1 now, i.e. that this function + * has unique access to it, so decref side-effects can't alter it. + */ + for (ep = table; fill > 0; ++ep) { #ifdef Py_DEBUG - assert(i < n); - ++i; + assert(i < n); + ++i; #endif - if (ep->me_key) { - --fill; - Py_DECREF(ep->me_key); - Py_XDECREF(ep->me_value); - } + if (ep->me_key) { + --fill; + Py_DECREF(ep->me_key); + Py_XDECREF(ep->me_value); + } #ifdef Py_DEBUG - else - assert(ep->me_value == NULL); + else + assert(ep->me_value == NULL); #endif - } + } - if (table_is_malloced) - PyMem_DEL(table); + if (table_is_malloced) + PyMem_DEL(table); } /* @@ -947,55 +947,55 @@ int PyDict_Next(PyObject *op, Py_ssize_t *ppos, PyObject **pkey, PyObject **pvalue) { - register Py_ssize_t i; - register Py_ssize_t mask; - register PyDictEntry *ep; - - if (!PyDict_Check(op)) - return 0; - i = *ppos; - if (i < 0) - return 0; - ep = ((PyDictObject *)op)->ma_table; - mask = ((PyDictObject *)op)->ma_mask; - while (i <= mask && ep[i].me_value == NULL) - i++; - *ppos = i+1; - if (i > mask) - return 0; - if (pkey) - *pkey = ep[i].me_key; - if (pvalue) - *pvalue = ep[i].me_value; - return 1; + register Py_ssize_t i; + register Py_ssize_t mask; + register PyDictEntry *ep; + + if (!PyDict_Check(op)) + return 0; + i = *ppos; + if (i < 0) + return 0; + ep = ((PyDictObject *)op)->ma_table; + mask = ((PyDictObject *)op)->ma_mask; + while (i <= mask && ep[i].me_value == NULL) + i++; + *ppos = i+1; + if (i > mask) + return 0; + if (pkey) + *pkey = ep[i].me_key; + if (pvalue) + *pvalue = ep[i].me_value; + return 1; } /* Internal version of PyDict_Next that returns a hash value in addition to the key and value.*/ int _PyDict_Next(PyObject *op, Py_ssize_t *ppos, PyObject **pkey, PyObject **pvalue, long *phash) { - register Py_ssize_t i; - register Py_ssize_t mask; - register PyDictEntry *ep; - - if (!PyDict_Check(op)) - return 0; - i = *ppos; - if (i < 0) - return 0; - ep = ((PyDictObject *)op)->ma_table; - mask = ((PyDictObject *)op)->ma_mask; - while (i <= mask && ep[i].me_value == NULL) - i++; - *ppos = i+1; - if (i > mask) - return 0; - *phash = (long)(ep[i].me_hash); - if (pkey) - *pkey = ep[i].me_key; - if (pvalue) - *pvalue = ep[i].me_value; - return 1; + register Py_ssize_t i; + register Py_ssize_t mask; + register PyDictEntry *ep; + + if (!PyDict_Check(op)) + return 0; + i = *ppos; + if (i < 0) + return 0; + ep = ((PyDictObject *)op)->ma_table; + mask = ((PyDictObject *)op)->ma_mask; + while (i <= mask && ep[i].me_value == NULL) + i++; + *ppos = i+1; + if (i > mask) + return 0; + *phash = (long)(ep[i].me_hash); + if (pkey) + *pkey = ep[i].me_key; + if (pvalue) + *pvalue = ep[i].me_value; + return 1; } /* Methods */ @@ -1003,400 +1003,400 @@ static void dict_dealloc(register PyDictObject *mp) { - register PyDictEntry *ep; - Py_ssize_t fill = mp->ma_fill; - PyObject_GC_UnTrack(mp); - Py_TRASHCAN_SAFE_BEGIN(mp) - for (ep = mp->ma_table; fill > 0; ep++) { - if (ep->me_key) { - --fill; - Py_DECREF(ep->me_key); - Py_XDECREF(ep->me_value); - } - } - if (mp->ma_table != mp->ma_smalltable) - PyMem_DEL(mp->ma_table); - if (numfree < PyDict_MAXFREELIST && Py_TYPE(mp) == &PyDict_Type) - free_list[numfree++] = mp; - else - Py_TYPE(mp)->tp_free((PyObject *)mp); - Py_TRASHCAN_SAFE_END(mp) + register PyDictEntry *ep; + Py_ssize_t fill = mp->ma_fill; + PyObject_GC_UnTrack(mp); + Py_TRASHCAN_SAFE_BEGIN(mp) + for (ep = mp->ma_table; fill > 0; ep++) { + if (ep->me_key) { + --fill; + Py_DECREF(ep->me_key); + Py_XDECREF(ep->me_value); + } + } + if (mp->ma_table != mp->ma_smalltable) + PyMem_DEL(mp->ma_table); + if (numfree < PyDict_MAXFREELIST && Py_TYPE(mp) == &PyDict_Type) + free_list[numfree++] = mp; + else + Py_TYPE(mp)->tp_free((PyObject *)mp); + Py_TRASHCAN_SAFE_END(mp) } static PyObject * dict_repr(PyDictObject *mp) { - Py_ssize_t i; - PyObject *s, *temp, *colon = NULL; - PyObject *pieces = NULL, *result = NULL; - PyObject *key, *value; - - i = Py_ReprEnter((PyObject *)mp); - if (i != 0) { - return i > 0 ? PyUnicode_FromString("{...}") : NULL; - } - - if (mp->ma_used == 0) { - result = PyUnicode_FromString("{}"); - goto Done; - } - - pieces = PyList_New(0); - if (pieces == NULL) - goto Done; - - colon = PyUnicode_FromString(": "); - if (colon == NULL) - goto Done; - - /* Do repr() on each key+value pair, and insert ": " between them. - Note that repr may mutate the dict. */ - i = 0; - while (PyDict_Next((PyObject *)mp, &i, &key, &value)) { - int status; - /* Prevent repr from deleting value during key format. */ - Py_INCREF(value); - s = PyObject_Repr(key); - PyUnicode_Append(&s, colon); - PyUnicode_AppendAndDel(&s, PyObject_Repr(value)); - Py_DECREF(value); - if (s == NULL) - goto Done; - status = PyList_Append(pieces, s); - Py_DECREF(s); /* append created a new ref */ - if (status < 0) - goto Done; - } - - /* Add "{}" decorations to the first and last items. */ - assert(PyList_GET_SIZE(pieces) > 0); - s = PyUnicode_FromString("{"); - if (s == NULL) - goto Done; - temp = PyList_GET_ITEM(pieces, 0); - PyUnicode_AppendAndDel(&s, temp); - PyList_SET_ITEM(pieces, 0, s); - if (s == NULL) - goto Done; - - s = PyUnicode_FromString("}"); - if (s == NULL) - goto Done; - temp = PyList_GET_ITEM(pieces, PyList_GET_SIZE(pieces) - 1); - PyUnicode_AppendAndDel(&temp, s); - PyList_SET_ITEM(pieces, PyList_GET_SIZE(pieces) - 1, temp); - if (temp == NULL) - goto Done; - - /* Paste them all together with ", " between. */ - s = PyUnicode_FromString(", "); - if (s == NULL) - goto Done; - result = PyUnicode_Join(s, pieces); - Py_DECREF(s); + Py_ssize_t i; + PyObject *s, *temp, *colon = NULL; + PyObject *pieces = NULL, *result = NULL; + PyObject *key, *value; + + i = Py_ReprEnter((PyObject *)mp); + if (i != 0) { + return i > 0 ? PyUnicode_FromString("{...}") : NULL; + } + + if (mp->ma_used == 0) { + result = PyUnicode_FromString("{}"); + goto Done; + } + + pieces = PyList_New(0); + if (pieces == NULL) + goto Done; + + colon = PyUnicode_FromString(": "); + if (colon == NULL) + goto Done; + + /* Do repr() on each key+value pair, and insert ": " between them. + Note that repr may mutate the dict. */ + i = 0; + while (PyDict_Next((PyObject *)mp, &i, &key, &value)) { + int status; + /* Prevent repr from deleting value during key format. */ + Py_INCREF(value); + s = PyObject_Repr(key); + PyUnicode_Append(&s, colon); + PyUnicode_AppendAndDel(&s, PyObject_Repr(value)); + Py_DECREF(value); + if (s == NULL) + goto Done; + status = PyList_Append(pieces, s); + Py_DECREF(s); /* append created a new ref */ + if (status < 0) + goto Done; + } + + /* Add "{}" decorations to the first and last items. */ + assert(PyList_GET_SIZE(pieces) > 0); + s = PyUnicode_FromString("{"); + if (s == NULL) + goto Done; + temp = PyList_GET_ITEM(pieces, 0); + PyUnicode_AppendAndDel(&s, temp); + PyList_SET_ITEM(pieces, 0, s); + if (s == NULL) + goto Done; + + s = PyUnicode_FromString("}"); + if (s == NULL) + goto Done; + temp = PyList_GET_ITEM(pieces, PyList_GET_SIZE(pieces) - 1); + PyUnicode_AppendAndDel(&temp, s); + PyList_SET_ITEM(pieces, PyList_GET_SIZE(pieces) - 1, temp); + if (temp == NULL) + goto Done; + + /* Paste them all together with ", " between. */ + s = PyUnicode_FromString(", "); + if (s == NULL) + goto Done; + result = PyUnicode_Join(s, pieces); + Py_DECREF(s); Done: - Py_XDECREF(pieces); - Py_XDECREF(colon); - Py_ReprLeave((PyObject *)mp); - return result; + Py_XDECREF(pieces); + Py_XDECREF(colon); + Py_ReprLeave((PyObject *)mp); + return result; } static Py_ssize_t dict_length(PyDictObject *mp) { - return mp->ma_used; + return mp->ma_used; } static PyObject * dict_subscript(PyDictObject *mp, register PyObject *key) { - PyObject *v; - long hash; - PyDictEntry *ep; - assert(mp->ma_table != NULL); - if (!PyUnicode_CheckExact(key) || - (hash = ((PyUnicodeObject *) key)->hash) == -1) { - hash = PyObject_Hash(key); - if (hash == -1) - return NULL; - } - ep = (mp->ma_lookup)(mp, key, hash); - if (ep == NULL) - return NULL; - v = ep->me_value; - if (v == NULL) { - if (!PyDict_CheckExact(mp)) { - /* Look up __missing__ method if we're a subclass. */ - PyObject *missing, *res; - static PyObject *missing_str = NULL; - missing = _PyObject_LookupSpecial((PyObject *)mp, - "__missing__", - &missing_str); - if (missing != NULL) { - res = PyObject_CallFunctionObjArgs(missing, - key, NULL); - Py_DECREF(missing); - return res; - } - else if (PyErr_Occurred()) - return NULL; - } - set_key_error(key); - return NULL; - } - else - Py_INCREF(v); - return v; + PyObject *v; + long hash; + PyDictEntry *ep; + assert(mp->ma_table != NULL); + if (!PyUnicode_CheckExact(key) || + (hash = ((PyUnicodeObject *) key)->hash) == -1) { + hash = PyObject_Hash(key); + if (hash == -1) + return NULL; + } + ep = (mp->ma_lookup)(mp, key, hash); + if (ep == NULL) + return NULL; + v = ep->me_value; + if (v == NULL) { + if (!PyDict_CheckExact(mp)) { + /* Look up __missing__ method if we're a subclass. */ + PyObject *missing, *res; + static PyObject *missing_str = NULL; + missing = _PyObject_LookupSpecial((PyObject *)mp, + "__missing__", + &missing_str); + if (missing != NULL) { + res = PyObject_CallFunctionObjArgs(missing, + key, NULL); + Py_DECREF(missing); + return res; + } + else if (PyErr_Occurred()) + return NULL; + } + set_key_error(key); + return NULL; + } + else + Py_INCREF(v); + return v; } static int dict_ass_sub(PyDictObject *mp, PyObject *v, PyObject *w) { - if (w == NULL) - return PyDict_DelItem((PyObject *)mp, v); - else - return PyDict_SetItem((PyObject *)mp, v, w); + if (w == NULL) + return PyDict_DelItem((PyObject *)mp, v); + else + return PyDict_SetItem((PyObject *)mp, v, w); } static PyMappingMethods dict_as_mapping = { - (lenfunc)dict_length, /*mp_length*/ - (binaryfunc)dict_subscript, /*mp_subscript*/ - (objobjargproc)dict_ass_sub, /*mp_ass_subscript*/ + (lenfunc)dict_length, /*mp_length*/ + (binaryfunc)dict_subscript, /*mp_subscript*/ + (objobjargproc)dict_ass_sub, /*mp_ass_subscript*/ }; static PyObject * dict_keys(register PyDictObject *mp) { - register PyObject *v; - register Py_ssize_t i, j; - PyDictEntry *ep; - Py_ssize_t mask, n; + register PyObject *v; + register Py_ssize_t i, j; + PyDictEntry *ep; + Py_ssize_t mask, n; again: - n = mp->ma_used; - v = PyList_New(n); - if (v == NULL) - return NULL; - if (n != mp->ma_used) { - /* Durnit. The allocations caused the dict to resize. - * Just start over, this shouldn't normally happen. - */ - Py_DECREF(v); - goto again; - } - ep = mp->ma_table; - mask = mp->ma_mask; - for (i = 0, j = 0; i <= mask; i++) { - if (ep[i].me_value != NULL) { - PyObject *key = ep[i].me_key; - Py_INCREF(key); - PyList_SET_ITEM(v, j, key); - j++; - } - } - assert(j == n); - return v; + n = mp->ma_used; + v = PyList_New(n); + if (v == NULL) + return NULL; + if (n != mp->ma_used) { + /* Durnit. The allocations caused the dict to resize. + * Just start over, this shouldn't normally happen. + */ + Py_DECREF(v); + goto again; + } + ep = mp->ma_table; + mask = mp->ma_mask; + for (i = 0, j = 0; i <= mask; i++) { + if (ep[i].me_value != NULL) { + PyObject *key = ep[i].me_key; + Py_INCREF(key); + PyList_SET_ITEM(v, j, key); + j++; + } + } + assert(j == n); + return v; } static PyObject * dict_values(register PyDictObject *mp) { - register PyObject *v; - register Py_ssize_t i, j; - PyDictEntry *ep; - Py_ssize_t mask, n; + register PyObject *v; + register Py_ssize_t i, j; + PyDictEntry *ep; + Py_ssize_t mask, n; again: - n = mp->ma_used; - v = PyList_New(n); - if (v == NULL) - return NULL; - if (n != mp->ma_used) { - /* Durnit. The allocations caused the dict to resize. - * Just start over, this shouldn't normally happen. - */ - Py_DECREF(v); - goto again; - } - ep = mp->ma_table; - mask = mp->ma_mask; - for (i = 0, j = 0; i <= mask; i++) { - if (ep[i].me_value != NULL) { - PyObject *value = ep[i].me_value; - Py_INCREF(value); - PyList_SET_ITEM(v, j, value); - j++; - } - } - assert(j == n); - return v; + n = mp->ma_used; + v = PyList_New(n); + if (v == NULL) + return NULL; + if (n != mp->ma_used) { + /* Durnit. The allocations caused the dict to resize. + * Just start over, this shouldn't normally happen. + */ + Py_DECREF(v); + goto again; + } + ep = mp->ma_table; + mask = mp->ma_mask; + for (i = 0, j = 0; i <= mask; i++) { + if (ep[i].me_value != NULL) { + PyObject *value = ep[i].me_value; + Py_INCREF(value); + PyList_SET_ITEM(v, j, value); + j++; + } + } + assert(j == n); + return v; } static PyObject * dict_items(register PyDictObject *mp) { - register PyObject *v; - register Py_ssize_t i, j, n; - Py_ssize_t mask; - PyObject *item, *key, *value; - PyDictEntry *ep; - - /* Preallocate the list of tuples, to avoid allocations during - * the loop over the items, which could trigger GC, which - * could resize the dict. :-( - */ + register PyObject *v; + register Py_ssize_t i, j, n; + Py_ssize_t mask; + PyObject *item, *key, *value; + PyDictEntry *ep; + + /* Preallocate the list of tuples, to avoid allocations during + * the loop over the items, which could trigger GC, which + * could resize the dict. :-( + */ again: - n = mp->ma_used; - v = PyList_New(n); - if (v == NULL) - return NULL; - for (i = 0; i < n; i++) { - item = PyTuple_New(2); - if (item == NULL) { - Py_DECREF(v); - return NULL; - } - PyList_SET_ITEM(v, i, item); - } - if (n != mp->ma_used) { - /* Durnit. The allocations caused the dict to resize. - * Just start over, this shouldn't normally happen. - */ - Py_DECREF(v); - goto again; - } - /* Nothing we do below makes any function calls. */ - ep = mp->ma_table; - mask = mp->ma_mask; - for (i = 0, j = 0; i <= mask; i++) { - if ((value=ep[i].me_value) != NULL) { - key = ep[i].me_key; - item = PyList_GET_ITEM(v, j); - Py_INCREF(key); - PyTuple_SET_ITEM(item, 0, key); - Py_INCREF(value); - PyTuple_SET_ITEM(item, 1, value); - j++; - } - } - assert(j == n); - return v; + n = mp->ma_used; + v = PyList_New(n); + if (v == NULL) + return NULL; + for (i = 0; i < n; i++) { + item = PyTuple_New(2); + if (item == NULL) { + Py_DECREF(v); + return NULL; + } + PyList_SET_ITEM(v, i, item); + } + if (n != mp->ma_used) { + /* Durnit. The allocations caused the dict to resize. + * Just start over, this shouldn't normally happen. + */ + Py_DECREF(v); + goto again; + } + /* Nothing we do below makes any function calls. */ + ep = mp->ma_table; + mask = mp->ma_mask; + for (i = 0, j = 0; i <= mask; i++) { + if ((value=ep[i].me_value) != NULL) { + key = ep[i].me_key; + item = PyList_GET_ITEM(v, j); + Py_INCREF(key); + PyTuple_SET_ITEM(item, 0, key); + Py_INCREF(value); + PyTuple_SET_ITEM(item, 1, value); + j++; + } + } + assert(j == n); + return v; } static PyObject * dict_fromkeys(PyObject *cls, PyObject *args) { - PyObject *seq; - PyObject *value = Py_None; - PyObject *it; /* iter(seq) */ - PyObject *key; - PyObject *d; - int status; - - if (!PyArg_UnpackTuple(args, "fromkeys", 1, 2, &seq, &value)) - return NULL; - - d = PyObject_CallObject(cls, NULL); - if (d == NULL) - return NULL; - - if (PyDict_CheckExact(d) && PyDict_CheckExact(seq)) { - PyDictObject *mp = (PyDictObject *)d; - PyObject *oldvalue; - Py_ssize_t pos = 0; - PyObject *key; - long hash; - - if (dictresize(mp, Py_SIZE(seq))) - return NULL; - - while (_PyDict_Next(seq, &pos, &key, &oldvalue, &hash)) { - Py_INCREF(key); - Py_INCREF(value); - if (insertdict(mp, key, hash, value)) - return NULL; - } - return d; - } - - if (PyDict_CheckExact(d) && PyAnySet_CheckExact(seq)) { - PyDictObject *mp = (PyDictObject *)d; - Py_ssize_t pos = 0; - PyObject *key; - long hash; - - if (dictresize(mp, PySet_GET_SIZE(seq))) - return NULL; - - while (_PySet_NextEntry(seq, &pos, &key, &hash)) { - Py_INCREF(key); - Py_INCREF(value); - if (insertdict(mp, key, hash, value)) - return NULL; - } - return d; - } - - it = PyObject_GetIter(seq); - if (it == NULL){ - Py_DECREF(d); - return NULL; - } - - if (PyDict_CheckExact(d)) { - while ((key = PyIter_Next(it)) != NULL) { - status = PyDict_SetItem(d, key, value); - Py_DECREF(key); - if (status < 0) - goto Fail; - } - } else { - while ((key = PyIter_Next(it)) != NULL) { - status = PyObject_SetItem(d, key, value); - Py_DECREF(key); - if (status < 0) - goto Fail; - } - } - - if (PyErr_Occurred()) - goto Fail; - Py_DECREF(it); - return d; + PyObject *seq; + PyObject *value = Py_None; + PyObject *it; /* iter(seq) */ + PyObject *key; + PyObject *d; + int status; + + if (!PyArg_UnpackTuple(args, "fromkeys", 1, 2, &seq, &value)) + return NULL; + + d = PyObject_CallObject(cls, NULL); + if (d == NULL) + return NULL; + + if (PyDict_CheckExact(d) && PyDict_CheckExact(seq)) { + PyDictObject *mp = (PyDictObject *)d; + PyObject *oldvalue; + Py_ssize_t pos = 0; + PyObject *key; + long hash; + + if (dictresize(mp, Py_SIZE(seq))) + return NULL; + + while (_PyDict_Next(seq, &pos, &key, &oldvalue, &hash)) { + Py_INCREF(key); + Py_INCREF(value); + if (insertdict(mp, key, hash, value)) + return NULL; + } + return d; + } + + if (PyDict_CheckExact(d) && PyAnySet_CheckExact(seq)) { + PyDictObject *mp = (PyDictObject *)d; + Py_ssize_t pos = 0; + PyObject *key; + long hash; + + if (dictresize(mp, PySet_GET_SIZE(seq))) + return NULL; + + while (_PySet_NextEntry(seq, &pos, &key, &hash)) { + Py_INCREF(key); + Py_INCREF(value); + if (insertdict(mp, key, hash, value)) + return NULL; + } + return d; + } + + it = PyObject_GetIter(seq); + if (it == NULL){ + Py_DECREF(d); + return NULL; + } + + if (PyDict_CheckExact(d)) { + while ((key = PyIter_Next(it)) != NULL) { + status = PyDict_SetItem(d, key, value); + Py_DECREF(key); + if (status < 0) + goto Fail; + } + } else { + while ((key = PyIter_Next(it)) != NULL) { + status = PyObject_SetItem(d, key, value); + Py_DECREF(key); + if (status < 0) + goto Fail; + } + } + + if (PyErr_Occurred()) + goto Fail; + Py_DECREF(it); + return d; Fail: - Py_DECREF(it); - Py_DECREF(d); - return NULL; + Py_DECREF(it); + Py_DECREF(d); + return NULL; } static int dict_update_common(PyObject *self, PyObject *args, PyObject *kwds, char *methname) { - PyObject *arg = NULL; - int result = 0; + PyObject *arg = NULL; + int result = 0; - if (!PyArg_UnpackTuple(args, methname, 0, 1, &arg)) - result = -1; + if (!PyArg_UnpackTuple(args, methname, 0, 1, &arg)) + result = -1; - else if (arg != NULL) { - if (PyObject_HasAttrString(arg, "keys")) - result = PyDict_Merge(self, arg, 1); - else - result = PyDict_MergeFromSeq2(self, arg, 1); - } - if (result == 0 && kwds != NULL) - result = PyDict_Merge(self, kwds, 1); - return result; + else if (arg != NULL) { + if (PyObject_HasAttrString(arg, "keys")) + result = PyDict_Merge(self, arg, 1); + else + result = PyDict_MergeFromSeq2(self, arg, 1); + } + if (result == 0 && kwds != NULL) + result = PyDict_Merge(self, kwds, 1); + return result; } static PyObject * dict_update(PyObject *self, PyObject *args, PyObject *kwds) { - if (dict_update_common(self, args, kwds, "update") != -1) - Py_RETURN_NONE; - return NULL; + if (dict_update_common(self, args, kwds, "update") != -1) + Py_RETURN_NONE; + return NULL; } /* Update unconditionally replaces existing items. @@ -1412,238 +1412,238 @@ int PyDict_MergeFromSeq2(PyObject *d, PyObject *seq2, int override) { - PyObject *it; /* iter(seq2) */ - Py_ssize_t i; /* index into seq2 of current element */ - PyObject *item; /* seq2[i] */ - PyObject *fast; /* item as a 2-tuple or 2-list */ - - assert(d != NULL); - assert(PyDict_Check(d)); - assert(seq2 != NULL); - - it = PyObject_GetIter(seq2); - if (it == NULL) - return -1; - - for (i = 0; ; ++i) { - PyObject *key, *value; - Py_ssize_t n; - - fast = NULL; - item = PyIter_Next(it); - if (item == NULL) { - if (PyErr_Occurred()) - goto Fail; - break; - } - - /* Convert item to sequence, and verify length 2. */ - fast = PySequence_Fast(item, ""); - if (fast == NULL) { - if (PyErr_ExceptionMatches(PyExc_TypeError)) - PyErr_Format(PyExc_TypeError, - "cannot convert dictionary update " - "sequence element #%zd to a sequence", - i); - goto Fail; - } - n = PySequence_Fast_GET_SIZE(fast); - if (n != 2) { - PyErr_Format(PyExc_ValueError, - "dictionary update sequence element #%zd " - "has length %zd; 2 is required", - i, n); - goto Fail; - } - - /* Update/merge with this (key, value) pair. */ - key = PySequence_Fast_GET_ITEM(fast, 0); - value = PySequence_Fast_GET_ITEM(fast, 1); - if (override || PyDict_GetItem(d, key) == NULL) { - int status = PyDict_SetItem(d, key, value); - if (status < 0) - goto Fail; - } - Py_DECREF(fast); - Py_DECREF(item); - } + PyObject *it; /* iter(seq2) */ + Py_ssize_t i; /* index into seq2 of current element */ + PyObject *item; /* seq2[i] */ + PyObject *fast; /* item as a 2-tuple or 2-list */ + + assert(d != NULL); + assert(PyDict_Check(d)); + assert(seq2 != NULL); + + it = PyObject_GetIter(seq2); + if (it == NULL) + return -1; + + for (i = 0; ; ++i) { + PyObject *key, *value; + Py_ssize_t n; + + fast = NULL; + item = PyIter_Next(it); + if (item == NULL) { + if (PyErr_Occurred()) + goto Fail; + break; + } + + /* Convert item to sequence, and verify length 2. */ + fast = PySequence_Fast(item, ""); + if (fast == NULL) { + if (PyErr_ExceptionMatches(PyExc_TypeError)) + PyErr_Format(PyExc_TypeError, + "cannot convert dictionary update " + "sequence element #%zd to a sequence", + i); + goto Fail; + } + n = PySequence_Fast_GET_SIZE(fast); + if (n != 2) { + PyErr_Format(PyExc_ValueError, + "dictionary update sequence element #%zd " + "has length %zd; 2 is required", + i, n); + goto Fail; + } + + /* Update/merge with this (key, value) pair. */ + key = PySequence_Fast_GET_ITEM(fast, 0); + value = PySequence_Fast_GET_ITEM(fast, 1); + if (override || PyDict_GetItem(d, key) == NULL) { + int status = PyDict_SetItem(d, key, value); + if (status < 0) + goto Fail; + } + Py_DECREF(fast); + Py_DECREF(item); + } - i = 0; - goto Return; + i = 0; + goto Return; Fail: - Py_XDECREF(item); - Py_XDECREF(fast); - i = -1; + Py_XDECREF(item); + Py_XDECREF(fast); + i = -1; Return: - Py_DECREF(it); - return Py_SAFE_DOWNCAST(i, Py_ssize_t, int); + Py_DECREF(it); + return Py_SAFE_DOWNCAST(i, Py_ssize_t, int); } int PyDict_Update(PyObject *a, PyObject *b) { - return PyDict_Merge(a, b, 1); + return PyDict_Merge(a, b, 1); } int PyDict_Merge(PyObject *a, PyObject *b, int override) { - register PyDictObject *mp, *other; - register Py_ssize_t i; - PyDictEntry *entry; - - /* We accept for the argument either a concrete dictionary object, - * or an abstract "mapping" object. For the former, we can do - * things quite efficiently. For the latter, we only require that - * PyMapping_Keys() and PyObject_GetItem() be supported. - */ - if (a == NULL || !PyDict_Check(a) || b == NULL) { - PyErr_BadInternalCall(); - return -1; - } - mp = (PyDictObject*)a; - if (PyDict_Check(b)) { - other = (PyDictObject*)b; - if (other == mp || other->ma_used == 0) - /* a.update(a) or a.update({}); nothing to do */ - return 0; - if (mp->ma_used == 0) - /* Since the target dict is empty, PyDict_GetItem() - * always returns NULL. Setting override to 1 - * skips the unnecessary test. - */ - override = 1; - /* Do one big resize at the start, rather than - * incrementally resizing as we insert new items. Expect - * that there will be no (or few) overlapping keys. - */ - if ((mp->ma_fill + other->ma_used)*3 >= (mp->ma_mask+1)*2) { - if (dictresize(mp, (mp->ma_used + other->ma_used)*2) != 0) - return -1; - } - for (i = 0; i <= other->ma_mask; i++) { - entry = &other->ma_table[i]; - if (entry->me_value != NULL && - (override || - PyDict_GetItem(a, entry->me_key) == NULL)) { - Py_INCREF(entry->me_key); - Py_INCREF(entry->me_value); - if (insertdict(mp, entry->me_key, - (long)entry->me_hash, - entry->me_value) != 0) - return -1; - } - } - } - else { - /* Do it the generic, slower way */ - PyObject *keys = PyMapping_Keys(b); - PyObject *iter; - PyObject *key, *value; - int status; - - if (keys == NULL) - /* Docstring says this is equivalent to E.keys() so - * if E doesn't have a .keys() method we want - * AttributeError to percolate up. Might as well - * do the same for any other error. - */ - return -1; - - iter = PyObject_GetIter(keys); - Py_DECREF(keys); - if (iter == NULL) - return -1; - - for (key = PyIter_Next(iter); key; key = PyIter_Next(iter)) { - if (!override && PyDict_GetItem(a, key) != NULL) { - Py_DECREF(key); - continue; - } - value = PyObject_GetItem(b, key); - if (value == NULL) { - Py_DECREF(iter); - Py_DECREF(key); - return -1; - } - status = PyDict_SetItem(a, key, value); - Py_DECREF(key); - Py_DECREF(value); - if (status < 0) { - Py_DECREF(iter); - return -1; - } - } - Py_DECREF(iter); - if (PyErr_Occurred()) - /* Iterator completed, via error */ - return -1; - } - return 0; + register PyDictObject *mp, *other; + register Py_ssize_t i; + PyDictEntry *entry; + + /* We accept for the argument either a concrete dictionary object, + * or an abstract "mapping" object. For the former, we can do + * things quite efficiently. For the latter, we only require that + * PyMapping_Keys() and PyObject_GetItem() be supported. + */ + if (a == NULL || !PyDict_Check(a) || b == NULL) { + PyErr_BadInternalCall(); + return -1; + } + mp = (PyDictObject*)a; + if (PyDict_Check(b)) { + other = (PyDictObject*)b; + if (other == mp || other->ma_used == 0) + /* a.update(a) or a.update({}); nothing to do */ + return 0; + if (mp->ma_used == 0) + /* Since the target dict is empty, PyDict_GetItem() + * always returns NULL. Setting override to 1 + * skips the unnecessary test. + */ + override = 1; + /* Do one big resize at the start, rather than + * incrementally resizing as we insert new items. Expect + * that there will be no (or few) overlapping keys. + */ + if ((mp->ma_fill + other->ma_used)*3 >= (mp->ma_mask+1)*2) { + if (dictresize(mp, (mp->ma_used + other->ma_used)*2) != 0) + return -1; + } + for (i = 0; i <= other->ma_mask; i++) { + entry = &other->ma_table[i]; + if (entry->me_value != NULL && + (override || + PyDict_GetItem(a, entry->me_key) == NULL)) { + Py_INCREF(entry->me_key); + Py_INCREF(entry->me_value); + if (insertdict(mp, entry->me_key, + (long)entry->me_hash, + entry->me_value) != 0) + return -1; + } + } + } + else { + /* Do it the generic, slower way */ + PyObject *keys = PyMapping_Keys(b); + PyObject *iter; + PyObject *key, *value; + int status; + + if (keys == NULL) + /* Docstring says this is equivalent to E.keys() so + * if E doesn't have a .keys() method we want + * AttributeError to percolate up. Might as well + * do the same for any other error. + */ + return -1; + + iter = PyObject_GetIter(keys); + Py_DECREF(keys); + if (iter == NULL) + return -1; + + for (key = PyIter_Next(iter); key; key = PyIter_Next(iter)) { + if (!override && PyDict_GetItem(a, key) != NULL) { + Py_DECREF(key); + continue; + } + value = PyObject_GetItem(b, key); + if (value == NULL) { + Py_DECREF(iter); + Py_DECREF(key); + return -1; + } + status = PyDict_SetItem(a, key, value); + Py_DECREF(key); + Py_DECREF(value); + if (status < 0) { + Py_DECREF(iter); + return -1; + } + } + Py_DECREF(iter); + if (PyErr_Occurred()) + /* Iterator completed, via error */ + return -1; + } + return 0; } static PyObject * dict_copy(register PyDictObject *mp) { - return PyDict_Copy((PyObject*)mp); + return PyDict_Copy((PyObject*)mp); } PyObject * PyDict_Copy(PyObject *o) { - PyObject *copy; + PyObject *copy; - if (o == NULL || !PyDict_Check(o)) { - PyErr_BadInternalCall(); - return NULL; - } - copy = PyDict_New(); - if (copy == NULL) - return NULL; - if (PyDict_Merge(copy, o, 1) == 0) - return copy; - Py_DECREF(copy); - return NULL; + if (o == NULL || !PyDict_Check(o)) { + PyErr_BadInternalCall(); + return NULL; + } + copy = PyDict_New(); + if (copy == NULL) + return NULL; + if (PyDict_Merge(copy, o, 1) == 0) + return copy; + Py_DECREF(copy); + return NULL; } Py_ssize_t PyDict_Size(PyObject *mp) { - if (mp == NULL || !PyDict_Check(mp)) { - PyErr_BadInternalCall(); - return -1; - } - return ((PyDictObject *)mp)->ma_used; + if (mp == NULL || !PyDict_Check(mp)) { + PyErr_BadInternalCall(); + return -1; + } + return ((PyDictObject *)mp)->ma_used; } PyObject * PyDict_Keys(PyObject *mp) { - if (mp == NULL || !PyDict_Check(mp)) { - PyErr_BadInternalCall(); - return NULL; - } - return dict_keys((PyDictObject *)mp); + if (mp == NULL || !PyDict_Check(mp)) { + PyErr_BadInternalCall(); + return NULL; + } + return dict_keys((PyDictObject *)mp); } PyObject * PyDict_Values(PyObject *mp) { - if (mp == NULL || !PyDict_Check(mp)) { - PyErr_BadInternalCall(); - return NULL; - } - return dict_values((PyDictObject *)mp); + if (mp == NULL || !PyDict_Check(mp)) { + PyErr_BadInternalCall(); + return NULL; + } + return dict_values((PyDictObject *)mp); } PyObject * PyDict_Items(PyObject *mp) { - if (mp == NULL || !PyDict_Check(mp)) { - PyErr_BadInternalCall(); - return NULL; - } - return dict_items((PyDictObject *)mp); + if (mp == NULL || !PyDict_Check(mp)) { + PyErr_BadInternalCall(); + return NULL; + } + return dict_items((PyDictObject *)mp); } /* Return 1 if dicts equal, 0 if not, -1 if error. @@ -1653,271 +1653,271 @@ static int dict_equal(PyDictObject *a, PyDictObject *b) { - Py_ssize_t i; + Py_ssize_t i; - if (a->ma_used != b->ma_used) - /* can't be equal if # of entries differ */ - return 0; - - /* Same # of entries -- check all of 'em. Exit early on any diff. */ - for (i = 0; i <= a->ma_mask; i++) { - PyObject *aval = a->ma_table[i].me_value; - if (aval != NULL) { - int cmp; - PyObject *bval; - PyObject *key = a->ma_table[i].me_key; - /* temporarily bump aval's refcount to ensure it stays - alive until we're done with it */ - Py_INCREF(aval); - /* ditto for key */ - Py_INCREF(key); - bval = PyDict_GetItemWithError((PyObject *)b, key); - Py_DECREF(key); - if (bval == NULL) { - Py_DECREF(aval); - if (PyErr_Occurred()) - return -1; - return 0; - } - cmp = PyObject_RichCompareBool(aval, bval, Py_EQ); - Py_DECREF(aval); - if (cmp <= 0) /* error or not equal */ - return cmp; - } - } - return 1; + if (a->ma_used != b->ma_used) + /* can't be equal if # of entries differ */ + return 0; + + /* Same # of entries -- check all of 'em. Exit early on any diff. */ + for (i = 0; i <= a->ma_mask; i++) { + PyObject *aval = a->ma_table[i].me_value; + if (aval != NULL) { + int cmp; + PyObject *bval; + PyObject *key = a->ma_table[i].me_key; + /* temporarily bump aval's refcount to ensure it stays + alive until we're done with it */ + Py_INCREF(aval); + /* ditto for key */ + Py_INCREF(key); + bval = PyDict_GetItemWithError((PyObject *)b, key); + Py_DECREF(key); + if (bval == NULL) { + Py_DECREF(aval); + if (PyErr_Occurred()) + return -1; + return 0; + } + cmp = PyObject_RichCompareBool(aval, bval, Py_EQ); + Py_DECREF(aval); + if (cmp <= 0) /* error or not equal */ + return cmp; + } + } + return 1; } static PyObject * dict_richcompare(PyObject *v, PyObject *w, int op) { - int cmp; - PyObject *res; + int cmp; + PyObject *res; - if (!PyDict_Check(v) || !PyDict_Check(w)) { - res = Py_NotImplemented; - } - else if (op == Py_EQ || op == Py_NE) { - cmp = dict_equal((PyDictObject *)v, (PyDictObject *)w); - if (cmp < 0) - return NULL; - res = (cmp == (op == Py_EQ)) ? Py_True : Py_False; - } - else - res = Py_NotImplemented; - Py_INCREF(res); - return res; + if (!PyDict_Check(v) || !PyDict_Check(w)) { + res = Py_NotImplemented; + } + else if (op == Py_EQ || op == Py_NE) { + cmp = dict_equal((PyDictObject *)v, (PyDictObject *)w); + if (cmp < 0) + return NULL; + res = (cmp == (op == Py_EQ)) ? Py_True : Py_False; + } + else + res = Py_NotImplemented; + Py_INCREF(res); + return res; } static PyObject * dict_contains(register PyDictObject *mp, PyObject *key) { - long hash; - PyDictEntry *ep; + long hash; + PyDictEntry *ep; - if (!PyUnicode_CheckExact(key) || - (hash = ((PyUnicodeObject *) key)->hash) == -1) { - hash = PyObject_Hash(key); - if (hash == -1) - return NULL; - } - ep = (mp->ma_lookup)(mp, key, hash); - if (ep == NULL) - return NULL; - return PyBool_FromLong(ep->me_value != NULL); + if (!PyUnicode_CheckExact(key) || + (hash = ((PyUnicodeObject *) key)->hash) == -1) { + hash = PyObject_Hash(key); + if (hash == -1) + return NULL; + } + ep = (mp->ma_lookup)(mp, key, hash); + if (ep == NULL) + return NULL; + return PyBool_FromLong(ep->me_value != NULL); } static PyObject * dict_get(register PyDictObject *mp, PyObject *args) { - PyObject *key; - PyObject *failobj = Py_None; - PyObject *val = NULL; - long hash; - PyDictEntry *ep; - - if (!PyArg_UnpackTuple(args, "get", 1, 2, &key, &failobj)) - return NULL; - - if (!PyUnicode_CheckExact(key) || - (hash = ((PyUnicodeObject *) key)->hash) == -1) { - hash = PyObject_Hash(key); - if (hash == -1) - return NULL; - } - ep = (mp->ma_lookup)(mp, key, hash); - if (ep == NULL) - return NULL; - val = ep->me_value; - if (val == NULL) - val = failobj; - Py_INCREF(val); - return val; + PyObject *key; + PyObject *failobj = Py_None; + PyObject *val = NULL; + long hash; + PyDictEntry *ep; + + if (!PyArg_UnpackTuple(args, "get", 1, 2, &key, &failobj)) + return NULL; + + if (!PyUnicode_CheckExact(key) || + (hash = ((PyUnicodeObject *) key)->hash) == -1) { + hash = PyObject_Hash(key); + if (hash == -1) + return NULL; + } + ep = (mp->ma_lookup)(mp, key, hash); + if (ep == NULL) + return NULL; + val = ep->me_value; + if (val == NULL) + val = failobj; + Py_INCREF(val); + return val; } static PyObject * dict_setdefault(register PyDictObject *mp, PyObject *args) { - PyObject *key; - PyObject *failobj = Py_None; - PyObject *val = NULL; - long hash; - PyDictEntry *ep; - - if (!PyArg_UnpackTuple(args, "setdefault", 1, 2, &key, &failobj)) - return NULL; - - if (!PyUnicode_CheckExact(key) || - (hash = ((PyUnicodeObject *) key)->hash) == -1) { - hash = PyObject_Hash(key); - if (hash == -1) - return NULL; - } - ep = (mp->ma_lookup)(mp, key, hash); - if (ep == NULL) - return NULL; - val = ep->me_value; - if (val == NULL) { - val = failobj; - if (PyDict_SetItem((PyObject*)mp, key, failobj)) - val = NULL; - } - Py_XINCREF(val); - return val; + PyObject *key; + PyObject *failobj = Py_None; + PyObject *val = NULL; + long hash; + PyDictEntry *ep; + + if (!PyArg_UnpackTuple(args, "setdefault", 1, 2, &key, &failobj)) + return NULL; + + if (!PyUnicode_CheckExact(key) || + (hash = ((PyUnicodeObject *) key)->hash) == -1) { + hash = PyObject_Hash(key); + if (hash == -1) + return NULL; + } + ep = (mp->ma_lookup)(mp, key, hash); + if (ep == NULL) + return NULL; + val = ep->me_value; + if (val == NULL) { + val = failobj; + if (PyDict_SetItem((PyObject*)mp, key, failobj)) + val = NULL; + } + Py_XINCREF(val); + return val; } static PyObject * dict_clear(register PyDictObject *mp) { - PyDict_Clear((PyObject *)mp); - Py_RETURN_NONE; + PyDict_Clear((PyObject *)mp); + Py_RETURN_NONE; } static PyObject * dict_pop(PyDictObject *mp, PyObject *args) { - long hash; - PyDictEntry *ep; - PyObject *old_value, *old_key; - PyObject *key, *deflt = NULL; - - if(!PyArg_UnpackTuple(args, "pop", 1, 2, &key, &deflt)) - return NULL; - if (mp->ma_used == 0) { - if (deflt) { - Py_INCREF(deflt); - return deflt; - } - PyErr_SetString(PyExc_KeyError, - "pop(): dictionary is empty"); - return NULL; - } - if (!PyUnicode_CheckExact(key) || - (hash = ((PyUnicodeObject *) key)->hash) == -1) { - hash = PyObject_Hash(key); - if (hash == -1) - return NULL; - } - ep = (mp->ma_lookup)(mp, key, hash); - if (ep == NULL) - return NULL; - if (ep->me_value == NULL) { - if (deflt) { - Py_INCREF(deflt); - return deflt; - } - set_key_error(key); - return NULL; - } - old_key = ep->me_key; - Py_INCREF(dummy); - ep->me_key = dummy; - old_value = ep->me_value; - ep->me_value = NULL; - mp->ma_used--; - Py_DECREF(old_key); - return old_value; + long hash; + PyDictEntry *ep; + PyObject *old_value, *old_key; + PyObject *key, *deflt = NULL; + + if(!PyArg_UnpackTuple(args, "pop", 1, 2, &key, &deflt)) + return NULL; + if (mp->ma_used == 0) { + if (deflt) { + Py_INCREF(deflt); + return deflt; + } + PyErr_SetString(PyExc_KeyError, + "pop(): dictionary is empty"); + return NULL; + } + if (!PyUnicode_CheckExact(key) || + (hash = ((PyUnicodeObject *) key)->hash) == -1) { + hash = PyObject_Hash(key); + if (hash == -1) + return NULL; + } + ep = (mp->ma_lookup)(mp, key, hash); + if (ep == NULL) + return NULL; + if (ep->me_value == NULL) { + if (deflt) { + Py_INCREF(deflt); + return deflt; + } + set_key_error(key); + return NULL; + } + old_key = ep->me_key; + Py_INCREF(dummy); + ep->me_key = dummy; + old_value = ep->me_value; + ep->me_value = NULL; + mp->ma_used--; + Py_DECREF(old_key); + return old_value; } static PyObject * dict_popitem(PyDictObject *mp) { - Py_ssize_t i = 0; - PyDictEntry *ep; - PyObject *res; - - /* Allocate the result tuple before checking the size. Believe it - * or not, this allocation could trigger a garbage collection which - * could empty the dict, so if we checked the size first and that - * happened, the result would be an infinite loop (searching for an - * entry that no longer exists). Note that the usual popitem() - * idiom is "while d: k, v = d.popitem()". so needing to throw the - * tuple away if the dict *is* empty isn't a significant - * inefficiency -- possible, but unlikely in practice. - */ - res = PyTuple_New(2); - if (res == NULL) - return NULL; - if (mp->ma_used == 0) { - Py_DECREF(res); - PyErr_SetString(PyExc_KeyError, - "popitem(): dictionary is empty"); - return NULL; - } - /* Set ep to "the first" dict entry with a value. We abuse the hash - * field of slot 0 to hold a search finger: - * If slot 0 has a value, use slot 0. - * Else slot 0 is being used to hold a search finger, - * and we use its hash value as the first index to look. - */ - ep = &mp->ma_table[0]; - if (ep->me_value == NULL) { - i = ep->me_hash; - /* The hash field may be a real hash value, or it may be a - * legit search finger, or it may be a once-legit search - * finger that's out of bounds now because it wrapped around - * or the table shrunk -- simply make sure it's in bounds now. - */ - if (i > mp->ma_mask || i < 1) - i = 1; /* skip slot 0 */ - while ((ep = &mp->ma_table[i])->me_value == NULL) { - i++; - if (i > mp->ma_mask) - i = 1; - } - } - PyTuple_SET_ITEM(res, 0, ep->me_key); - PyTuple_SET_ITEM(res, 1, ep->me_value); - Py_INCREF(dummy); - ep->me_key = dummy; - ep->me_value = NULL; - mp->ma_used--; - assert(mp->ma_table[0].me_value == NULL); - mp->ma_table[0].me_hash = i + 1; /* next place to start */ - return res; + Py_ssize_t i = 0; + PyDictEntry *ep; + PyObject *res; + + /* Allocate the result tuple before checking the size. Believe it + * or not, this allocation could trigger a garbage collection which + * could empty the dict, so if we checked the size first and that + * happened, the result would be an infinite loop (searching for an + * entry that no longer exists). Note that the usual popitem() + * idiom is "while d: k, v = d.popitem()". so needing to throw the + * tuple away if the dict *is* empty isn't a significant + * inefficiency -- possible, but unlikely in practice. + */ + res = PyTuple_New(2); + if (res == NULL) + return NULL; + if (mp->ma_used == 0) { + Py_DECREF(res); + PyErr_SetString(PyExc_KeyError, + "popitem(): dictionary is empty"); + return NULL; + } + /* Set ep to "the first" dict entry with a value. We abuse the hash + * field of slot 0 to hold a search finger: + * If slot 0 has a value, use slot 0. + * Else slot 0 is being used to hold a search finger, + * and we use its hash value as the first index to look. + */ + ep = &mp->ma_table[0]; + if (ep->me_value == NULL) { + i = ep->me_hash; + /* The hash field may be a real hash value, or it may be a + * legit search finger, or it may be a once-legit search + * finger that's out of bounds now because it wrapped around + * or the table shrunk -- simply make sure it's in bounds now. + */ + if (i > mp->ma_mask || i < 1) + i = 1; /* skip slot 0 */ + while ((ep = &mp->ma_table[i])->me_value == NULL) { + i++; + if (i > mp->ma_mask) + i = 1; + } + } + PyTuple_SET_ITEM(res, 0, ep->me_key); + PyTuple_SET_ITEM(res, 1, ep->me_value); + Py_INCREF(dummy); + ep->me_key = dummy; + ep->me_value = NULL; + mp->ma_used--; + assert(mp->ma_table[0].me_value == NULL); + mp->ma_table[0].me_hash = i + 1; /* next place to start */ + return res; } static int dict_traverse(PyObject *op, visitproc visit, void *arg) { - Py_ssize_t i = 0; - PyObject *pk; - PyObject *pv; - - while (PyDict_Next(op, &i, &pk, &pv)) { - Py_VISIT(pk); - Py_VISIT(pv); - } - return 0; + Py_ssize_t i = 0; + PyObject *pk; + PyObject *pv; + + while (PyDict_Next(op, &i, &pk, &pv)) { + Py_VISIT(pk); + Py_VISIT(pv); + } + return 0; } static int dict_tp_clear(PyObject *op) { - PyDict_Clear(op); - return 0; + PyDict_Clear(op); + return 0; } static PyObject *dictiter_new(PyDictObject *, PyTypeObject *); @@ -1925,12 +1925,12 @@ static PyObject * dict_sizeof(PyDictObject *mp) { - Py_ssize_t res; + Py_ssize_t res; - res = sizeof(PyDictObject); - if (mp->ma_table != mp->ma_smalltable) - res = res + (mp->ma_mask + 1) * sizeof(PyDictEntry); - return PyLong_FromSsize_t(res); + res = sizeof(PyDictObject); + if (mp->ma_table != mp->ma_smalltable) + res = res + (mp->ma_mask + 1) * sizeof(PyDictEntry); + return PyLong_FromSsize_t(res); } PyDoc_STRVAR(contains__doc__, @@ -1977,126 +1977,126 @@ static PyObject *dictvalues_new(PyObject *); PyDoc_STRVAR(keys__doc__, - "D.keys() -> a set-like object providing a view on D's keys"); + "D.keys() -> a set-like object providing a view on D's keys"); PyDoc_STRVAR(items__doc__, - "D.items() -> a set-like object providing a view on D's items"); + "D.items() -> a set-like object providing a view on D's items"); PyDoc_STRVAR(values__doc__, - "D.values() -> an object providing a view on D's values"); + "D.values() -> an object providing a view on D's values"); static PyMethodDef mapp_methods[] = { - {"__contains__",(PyCFunction)dict_contains, METH_O | METH_COEXIST, - contains__doc__}, - {"__getitem__", (PyCFunction)dict_subscript, METH_O | METH_COEXIST, - getitem__doc__}, - {"__sizeof__", (PyCFunction)dict_sizeof, METH_NOARGS, - sizeof__doc__}, - {"get", (PyCFunction)dict_get, METH_VARARGS, - get__doc__}, - {"setdefault", (PyCFunction)dict_setdefault, METH_VARARGS, - setdefault_doc__}, - {"pop", (PyCFunction)dict_pop, METH_VARARGS, - pop__doc__}, - {"popitem", (PyCFunction)dict_popitem, METH_NOARGS, - popitem__doc__}, - {"keys", (PyCFunction)dictkeys_new, METH_NOARGS, - keys__doc__}, - {"items", (PyCFunction)dictitems_new, METH_NOARGS, - items__doc__}, - {"values", (PyCFunction)dictvalues_new, METH_NOARGS, - values__doc__}, - {"update", (PyCFunction)dict_update, METH_VARARGS | METH_KEYWORDS, - update__doc__}, - {"fromkeys", (PyCFunction)dict_fromkeys, METH_VARARGS | METH_CLASS, - fromkeys__doc__}, - {"clear", (PyCFunction)dict_clear, METH_NOARGS, - clear__doc__}, - {"copy", (PyCFunction)dict_copy, METH_NOARGS, - copy__doc__}, - {NULL, NULL} /* sentinel */ + {"__contains__",(PyCFunction)dict_contains, METH_O | METH_COEXIST, + contains__doc__}, + {"__getitem__", (PyCFunction)dict_subscript, METH_O | METH_COEXIST, + getitem__doc__}, + {"__sizeof__", (PyCFunction)dict_sizeof, METH_NOARGS, + sizeof__doc__}, + {"get", (PyCFunction)dict_get, METH_VARARGS, + get__doc__}, + {"setdefault", (PyCFunction)dict_setdefault, METH_VARARGS, + setdefault_doc__}, + {"pop", (PyCFunction)dict_pop, METH_VARARGS, + pop__doc__}, + {"popitem", (PyCFunction)dict_popitem, METH_NOARGS, + popitem__doc__}, + {"keys", (PyCFunction)dictkeys_new, METH_NOARGS, + keys__doc__}, + {"items", (PyCFunction)dictitems_new, METH_NOARGS, + items__doc__}, + {"values", (PyCFunction)dictvalues_new, METH_NOARGS, + values__doc__}, + {"update", (PyCFunction)dict_update, METH_VARARGS | METH_KEYWORDS, + update__doc__}, + {"fromkeys", (PyCFunction)dict_fromkeys, METH_VARARGS | METH_CLASS, + fromkeys__doc__}, + {"clear", (PyCFunction)dict_clear, METH_NOARGS, + clear__doc__}, + {"copy", (PyCFunction)dict_copy, METH_NOARGS, + copy__doc__}, + {NULL, NULL} /* sentinel */ }; /* Return 1 if `key` is in dict `op`, 0 if not, and -1 on error. */ int PyDict_Contains(PyObject *op, PyObject *key) { - long hash; - PyDictObject *mp = (PyDictObject *)op; - PyDictEntry *ep; - - if (!PyUnicode_CheckExact(key) || - (hash = ((PyUnicodeObject *) key)->hash) == -1) { - hash = PyObject_Hash(key); - if (hash == -1) - return -1; - } - ep = (mp->ma_lookup)(mp, key, hash); - return ep == NULL ? -1 : (ep->me_value != NULL); + long hash; + PyDictObject *mp = (PyDictObject *)op; + PyDictEntry *ep; + + if (!PyUnicode_CheckExact(key) || + (hash = ((PyUnicodeObject *) key)->hash) == -1) { + hash = PyObject_Hash(key); + if (hash == -1) + return -1; + } + ep = (mp->ma_lookup)(mp, key, hash); + return ep == NULL ? -1 : (ep->me_value != NULL); } /* Internal version of PyDict_Contains used when the hash value is already known */ int _PyDict_Contains(PyObject *op, PyObject *key, long hash) { - PyDictObject *mp = (PyDictObject *)op; - PyDictEntry *ep; + PyDictObject *mp = (PyDictObject *)op; + PyDictEntry *ep; - ep = (mp->ma_lookup)(mp, key, hash); - return ep == NULL ? -1 : (ep->me_value != NULL); + ep = (mp->ma_lookup)(mp, key, hash); + return ep == NULL ? -1 : (ep->me_value != NULL); } /* Hack to implement "key in dict" */ static PySequenceMethods dict_as_sequence = { - 0, /* sq_length */ - 0, /* sq_concat */ - 0, /* sq_repeat */ - 0, /* sq_item */ - 0, /* sq_slice */ - 0, /* sq_ass_item */ - 0, /* sq_ass_slice */ - PyDict_Contains, /* sq_contains */ - 0, /* sq_inplace_concat */ - 0, /* sq_inplace_repeat */ + 0, /* sq_length */ + 0, /* sq_concat */ + 0, /* sq_repeat */ + 0, /* sq_item */ + 0, /* sq_slice */ + 0, /* sq_ass_item */ + 0, /* sq_ass_slice */ + PyDict_Contains, /* sq_contains */ + 0, /* sq_inplace_concat */ + 0, /* sq_inplace_repeat */ }; static PyObject * dict_new(PyTypeObject *type, PyObject *args, PyObject *kwds) { - PyObject *self; + PyObject *self; - assert(type != NULL && type->tp_alloc != NULL); - self = type->tp_alloc(type, 0); - if (self != NULL) { - PyDictObject *d = (PyDictObject *)self; - /* It's guaranteed that tp->alloc zeroed out the struct. */ - assert(d->ma_table == NULL && d->ma_fill == 0 && d->ma_used == 0); - INIT_NONZERO_DICT_SLOTS(d); - d->ma_lookup = lookdict_unicode; - /* The object has been implicitely tracked by tp_alloc */ - if (type == &PyDict_Type) - _PyObject_GC_UNTRACK(d); + assert(type != NULL && type->tp_alloc != NULL); + self = type->tp_alloc(type, 0); + if (self != NULL) { + PyDictObject *d = (PyDictObject *)self; + /* It's guaranteed that tp->alloc zeroed out the struct. */ + assert(d->ma_table == NULL && d->ma_fill == 0 && d->ma_used == 0); + INIT_NONZERO_DICT_SLOTS(d); + d->ma_lookup = lookdict_unicode; + /* The object has been implicitely tracked by tp_alloc */ + if (type == &PyDict_Type) + _PyObject_GC_UNTRACK(d); #ifdef SHOW_CONVERSION_COUNTS - ++created; + ++created; #endif #ifdef SHOW_TRACK_COUNT - if (_PyObject_GC_IS_TRACKED(d)) - count_tracked++; - else - count_untracked++; + if (_PyObject_GC_IS_TRACKED(d)) + count_tracked++; + else + count_untracked++; #endif - } - return self; + } + return self; } static int dict_init(PyObject *self, PyObject *args, PyObject *kwds) { - return dict_update_common(self, args, kwds, "dict"); + return dict_update_common(self, args, kwds, "dict"); } static PyObject * dict_iter(PyDictObject *dict) { - return dictiter_new(dict, &PyDictIterKey_Type); + return dictiter_new(dict, &PyDictIterKey_Type); } PyDoc_STRVAR(dictionary_doc, @@ -2111,46 +2111,46 @@ " in the keyword argument list. For example: dict(one=1, two=2)"); PyTypeObject PyDict_Type = { - PyVarObject_HEAD_INIT(&PyType_Type, 0) - "dict", - sizeof(PyDictObject), - 0, - (destructor)dict_dealloc, /* tp_dealloc */ - 0, /* tp_print */ - 0, /* tp_getattr */ - 0, /* tp_setattr */ - 0, /* tp_reserved */ - (reprfunc)dict_repr, /* tp_repr */ - 0, /* tp_as_number */ - &dict_as_sequence, /* tp_as_sequence */ - &dict_as_mapping, /* tp_as_mapping */ - (hashfunc)PyObject_HashNotImplemented, /* 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 | - Py_TPFLAGS_BASETYPE | Py_TPFLAGS_DICT_SUBCLASS, /* tp_flags */ - dictionary_doc, /* tp_doc */ - dict_traverse, /* tp_traverse */ - dict_tp_clear, /* tp_clear */ - dict_richcompare, /* tp_richcompare */ - 0, /* tp_weaklistoffset */ - (getiterfunc)dict_iter, /* tp_iter */ - 0, /* tp_iternext */ - mapp_methods, /* tp_methods */ - 0, /* tp_members */ - 0, /* tp_getset */ - 0, /* tp_base */ - 0, /* tp_dict */ - 0, /* tp_descr_get */ - 0, /* tp_descr_set */ - 0, /* tp_dictoffset */ - dict_init, /* tp_init */ - PyType_GenericAlloc, /* tp_alloc */ - dict_new, /* tp_new */ - PyObject_GC_Del, /* tp_free */ + PyVarObject_HEAD_INIT(&PyType_Type, 0) + "dict", + sizeof(PyDictObject), + 0, + (destructor)dict_dealloc, /* tp_dealloc */ + 0, /* tp_print */ + 0, /* tp_getattr */ + 0, /* tp_setattr */ + 0, /* tp_reserved */ + (reprfunc)dict_repr, /* tp_repr */ + 0, /* tp_as_number */ + &dict_as_sequence, /* tp_as_sequence */ + &dict_as_mapping, /* tp_as_mapping */ + (hashfunc)PyObject_HashNotImplemented, /* 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 | + Py_TPFLAGS_BASETYPE | Py_TPFLAGS_DICT_SUBCLASS, /* tp_flags */ + dictionary_doc, /* tp_doc */ + dict_traverse, /* tp_traverse */ + dict_tp_clear, /* tp_clear */ + dict_richcompare, /* tp_richcompare */ + 0, /* tp_weaklistoffset */ + (getiterfunc)dict_iter, /* tp_iter */ + 0, /* tp_iternext */ + mapp_methods, /* tp_methods */ + 0, /* tp_members */ + 0, /* tp_getset */ + 0, /* tp_base */ + 0, /* tp_dict */ + 0, /* tp_descr_get */ + 0, /* tp_descr_set */ + 0, /* tp_dictoffset */ + dict_init, /* tp_init */ + PyType_GenericAlloc, /* tp_alloc */ + dict_new, /* tp_new */ + PyObject_GC_Del, /* tp_free */ }; /* For backward compatibility with old dictionary interface */ @@ -2158,340 +2158,340 @@ PyObject * PyDict_GetItemString(PyObject *v, const char *key) { - PyObject *kv, *rv; - kv = PyUnicode_FromString(key); - if (kv == NULL) - return NULL; - rv = PyDict_GetItem(v, kv); - Py_DECREF(kv); - return rv; + PyObject *kv, *rv; + kv = PyUnicode_FromString(key); + if (kv == NULL) + return NULL; + rv = PyDict_GetItem(v, kv); + Py_DECREF(kv); + return rv; } int PyDict_SetItemString(PyObject *v, const char *key, PyObject *item) { - PyObject *kv; - int err; - kv = PyUnicode_FromString(key); - if (kv == NULL) - return -1; - PyUnicode_InternInPlace(&kv); /* XXX Should we really? */ - err = PyDict_SetItem(v, kv, item); - Py_DECREF(kv); - return err; + PyObject *kv; + int err; + kv = PyUnicode_FromString(key); + if (kv == NULL) + return -1; + PyUnicode_InternInPlace(&kv); /* XXX Should we really? */ + err = PyDict_SetItem(v, kv, item); + Py_DECREF(kv); + return err; } int PyDict_DelItemString(PyObject *v, const char *key) { - PyObject *kv; - int err; - kv = PyUnicode_FromString(key); - if (kv == NULL) - return -1; - err = PyDict_DelItem(v, kv); - Py_DECREF(kv); - return err; + PyObject *kv; + int err; + kv = PyUnicode_FromString(key); + if (kv == NULL) + return -1; + err = PyDict_DelItem(v, kv); + Py_DECREF(kv); + return err; } /* Dictionary iterator types */ typedef struct { - PyObject_HEAD - PyDictObject *di_dict; /* Set to NULL when iterator is exhausted */ - Py_ssize_t di_used; - Py_ssize_t di_pos; - PyObject* di_result; /* reusable result tuple for iteritems */ - Py_ssize_t len; + PyObject_HEAD + PyDictObject *di_dict; /* Set to NULL when iterator is exhausted */ + Py_ssize_t di_used; + Py_ssize_t di_pos; + PyObject* di_result; /* reusable result tuple for iteritems */ + Py_ssize_t len; } dictiterobject; static PyObject * dictiter_new(PyDictObject *dict, PyTypeObject *itertype) { - dictiterobject *di; - di = PyObject_GC_New(dictiterobject, itertype); - if (di == NULL) - return NULL; - Py_INCREF(dict); - di->di_dict = dict; - di->di_used = dict->ma_used; - di->di_pos = 0; - di->len = dict->ma_used; - if (itertype == &PyDictIterItem_Type) { - di->di_result = PyTuple_Pack(2, Py_None, Py_None); - if (di->di_result == NULL) { - Py_DECREF(di); - return NULL; - } - } - else - di->di_result = NULL; - _PyObject_GC_TRACK(di); - return (PyObject *)di; + dictiterobject *di; + di = PyObject_GC_New(dictiterobject, itertype); + if (di == NULL) + return NULL; + Py_INCREF(dict); + di->di_dict = dict; + di->di_used = dict->ma_used; + di->di_pos = 0; + di->len = dict->ma_used; + if (itertype == &PyDictIterItem_Type) { + di->di_result = PyTuple_Pack(2, Py_None, Py_None); + if (di->di_result == NULL) { + Py_DECREF(di); + return NULL; + } + } + else + di->di_result = NULL; + _PyObject_GC_TRACK(di); + return (PyObject *)di; } static void dictiter_dealloc(dictiterobject *di) { - Py_XDECREF(di->di_dict); - Py_XDECREF(di->di_result); - PyObject_GC_Del(di); + Py_XDECREF(di->di_dict); + Py_XDECREF(di->di_result); + PyObject_GC_Del(di); } static int dictiter_traverse(dictiterobject *di, visitproc visit, void *arg) { - Py_VISIT(di->di_dict); - Py_VISIT(di->di_result); - return 0; + Py_VISIT(di->di_dict); + Py_VISIT(di->di_result); + return 0; } static PyObject * dictiter_len(dictiterobject *di) { - Py_ssize_t len = 0; - if (di->di_dict != NULL && di->di_used == di->di_dict->ma_used) - len = di->len; - return PyLong_FromSize_t(len); + Py_ssize_t len = 0; + if (di->di_dict != NULL && di->di_used == di->di_dict->ma_used) + len = di->len; + return PyLong_FromSize_t(len); } PyDoc_STRVAR(length_hint_doc, "Private method returning an estimate of len(list(it))."); static PyMethodDef dictiter_methods[] = { - {"__length_hint__", (PyCFunction)dictiter_len, METH_NOARGS, - length_hint_doc}, - {NULL, NULL} /* sentinel */ + {"__length_hint__", (PyCFunction)dictiter_len, METH_NOARGS, + length_hint_doc}, + {NULL, NULL} /* sentinel */ }; static PyObject *dictiter_iternextkey(dictiterobject *di) { - PyObject *key; - register Py_ssize_t i, mask; - register PyDictEntry *ep; - PyDictObject *d = di->di_dict; - - if (d == NULL) - return NULL; - assert (PyDict_Check(d)); - - if (di->di_used != d->ma_used) { - PyErr_SetString(PyExc_RuntimeError, - "dictionary changed size during iteration"); - di->di_used = -1; /* Make this state sticky */ - return NULL; - } - - i = di->di_pos; - if (i < 0) - goto fail; - ep = d->ma_table; - mask = d->ma_mask; - while (i <= mask && ep[i].me_value == NULL) - i++; - di->di_pos = i+1; - if (i > mask) - goto fail; - di->len--; - key = ep[i].me_key; - Py_INCREF(key); - return key; + PyObject *key; + register Py_ssize_t i, mask; + register PyDictEntry *ep; + PyDictObject *d = di->di_dict; + + if (d == NULL) + return NULL; + assert (PyDict_Check(d)); + + if (di->di_used != d->ma_used) { + PyErr_SetString(PyExc_RuntimeError, + "dictionary changed size during iteration"); + di->di_used = -1; /* Make this state sticky */ + return NULL; + } + + i = di->di_pos; + if (i < 0) + goto fail; + ep = d->ma_table; + mask = d->ma_mask; + while (i <= mask && ep[i].me_value == NULL) + i++; + di->di_pos = i+1; + if (i > mask) + goto fail; + di->len--; + key = ep[i].me_key; + Py_INCREF(key); + return key; fail: - Py_DECREF(d); - di->di_dict = NULL; - return NULL; + Py_DECREF(d); + di->di_dict = NULL; + return NULL; } PyTypeObject PyDictIterKey_Type = { - PyVarObject_HEAD_INIT(&PyType_Type, 0) - "dict_keyiterator", /* tp_name */ - sizeof(dictiterobject), /* tp_basicsize */ - 0, /* tp_itemsize */ - /* methods */ - (destructor)dictiter_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)dictiter_traverse, /* tp_traverse */ - 0, /* tp_clear */ - 0, /* tp_richcompare */ - 0, /* tp_weaklistoffset */ - PyObject_SelfIter, /* tp_iter */ - (iternextfunc)dictiter_iternextkey, /* tp_iternext */ - dictiter_methods, /* tp_methods */ - 0, + PyVarObject_HEAD_INIT(&PyType_Type, 0) + "dict_keyiterator", /* tp_name */ + sizeof(dictiterobject), /* tp_basicsize */ + 0, /* tp_itemsize */ + /* methods */ + (destructor)dictiter_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)dictiter_traverse, /* tp_traverse */ + 0, /* tp_clear */ + 0, /* tp_richcompare */ + 0, /* tp_weaklistoffset */ + PyObject_SelfIter, /* tp_iter */ + (iternextfunc)dictiter_iternextkey, /* tp_iternext */ + dictiter_methods, /* tp_methods */ + 0, }; static PyObject *dictiter_iternextvalue(dictiterobject *di) { - PyObject *value; - register Py_ssize_t i, mask; - register PyDictEntry *ep; - PyDictObject *d = di->di_dict; - - if (d == NULL) - return NULL; - assert (PyDict_Check(d)); - - if (di->di_used != d->ma_used) { - PyErr_SetString(PyExc_RuntimeError, - "dictionary changed size during iteration"); - di->di_used = -1; /* Make this state sticky */ - return NULL; - } - - i = di->di_pos; - mask = d->ma_mask; - if (i < 0 || i > mask) - goto fail; - ep = d->ma_table; - while ((value=ep[i].me_value) == NULL) { - i++; - if (i > mask) - goto fail; - } - di->di_pos = i+1; - di->len--; - Py_INCREF(value); - return value; + PyObject *value; + register Py_ssize_t i, mask; + register PyDictEntry *ep; + PyDictObject *d = di->di_dict; + + if (d == NULL) + return NULL; + assert (PyDict_Check(d)); + + if (di->di_used != d->ma_used) { + PyErr_SetString(PyExc_RuntimeError, + "dictionary changed size during iteration"); + di->di_used = -1; /* Make this state sticky */ + return NULL; + } + + i = di->di_pos; + mask = d->ma_mask; + if (i < 0 || i > mask) + goto fail; + ep = d->ma_table; + while ((value=ep[i].me_value) == NULL) { + i++; + if (i > mask) + goto fail; + } + di->di_pos = i+1; + di->len--; + Py_INCREF(value); + return value; fail: - Py_DECREF(d); - di->di_dict = NULL; - return NULL; + Py_DECREF(d); + di->di_dict = NULL; + return NULL; } PyTypeObject PyDictIterValue_Type = { - PyVarObject_HEAD_INIT(&PyType_Type, 0) - "dict_valueiterator", /* tp_name */ - sizeof(dictiterobject), /* tp_basicsize */ - 0, /* tp_itemsize */ - /* methods */ - (destructor)dictiter_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)dictiter_traverse, /* tp_traverse */ - 0, /* tp_clear */ - 0, /* tp_richcompare */ - 0, /* tp_weaklistoffset */ - PyObject_SelfIter, /* tp_iter */ - (iternextfunc)dictiter_iternextvalue, /* tp_iternext */ - dictiter_methods, /* tp_methods */ - 0, + PyVarObject_HEAD_INIT(&PyType_Type, 0) + "dict_valueiterator", /* tp_name */ + sizeof(dictiterobject), /* tp_basicsize */ + 0, /* tp_itemsize */ + /* methods */ + (destructor)dictiter_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)dictiter_traverse, /* tp_traverse */ + 0, /* tp_clear */ + 0, /* tp_richcompare */ + 0, /* tp_weaklistoffset */ + PyObject_SelfIter, /* tp_iter */ + (iternextfunc)dictiter_iternextvalue, /* tp_iternext */ + dictiter_methods, /* tp_methods */ + 0, }; static PyObject *dictiter_iternextitem(dictiterobject *di) { - PyObject *key, *value, *result = di->di_result; - register Py_ssize_t i, mask; - register PyDictEntry *ep; - PyDictObject *d = di->di_dict; - - if (d == NULL) - return NULL; - assert (PyDict_Check(d)); - - if (di->di_used != d->ma_used) { - PyErr_SetString(PyExc_RuntimeError, - "dictionary changed size during iteration"); - di->di_used = -1; /* Make this state sticky */ - return NULL; - } - - i = di->di_pos; - if (i < 0) - goto fail; - ep = d->ma_table; - mask = d->ma_mask; - while (i <= mask && ep[i].me_value == NULL) - i++; - di->di_pos = i+1; - if (i > mask) - goto fail; - - if (result->ob_refcnt == 1) { - Py_INCREF(result); - Py_DECREF(PyTuple_GET_ITEM(result, 0)); - Py_DECREF(PyTuple_GET_ITEM(result, 1)); - } else { - result = PyTuple_New(2); - if (result == NULL) - return NULL; - } - di->len--; - key = ep[i].me_key; - value = ep[i].me_value; - Py_INCREF(key); - Py_INCREF(value); - PyTuple_SET_ITEM(result, 0, key); - PyTuple_SET_ITEM(result, 1, value); - return result; + PyObject *key, *value, *result = di->di_result; + register Py_ssize_t i, mask; + register PyDictEntry *ep; + PyDictObject *d = di->di_dict; + + if (d == NULL) + return NULL; + assert (PyDict_Check(d)); + + if (di->di_used != d->ma_used) { + PyErr_SetString(PyExc_RuntimeError, + "dictionary changed size during iteration"); + di->di_used = -1; /* Make this state sticky */ + return NULL; + } + + i = di->di_pos; + if (i < 0) + goto fail; + ep = d->ma_table; + mask = d->ma_mask; + while (i <= mask && ep[i].me_value == NULL) + i++; + di->di_pos = i+1; + if (i > mask) + goto fail; + + if (result->ob_refcnt == 1) { + Py_INCREF(result); + Py_DECREF(PyTuple_GET_ITEM(result, 0)); + Py_DECREF(PyTuple_GET_ITEM(result, 1)); + } else { + result = PyTuple_New(2); + if (result == NULL) + return NULL; + } + di->len--; + key = ep[i].me_key; + value = ep[i].me_value; + Py_INCREF(key); + Py_INCREF(value); + PyTuple_SET_ITEM(result, 0, key); + PyTuple_SET_ITEM(result, 1, value); + return result; fail: - Py_DECREF(d); - di->di_dict = NULL; - return NULL; + Py_DECREF(d); + di->di_dict = NULL; + return NULL; } PyTypeObject PyDictIterItem_Type = { - PyVarObject_HEAD_INIT(&PyType_Type, 0) - "dict_itemiterator", /* tp_name */ - sizeof(dictiterobject), /* tp_basicsize */ - 0, /* tp_itemsize */ - /* methods */ - (destructor)dictiter_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)dictiter_traverse, /* tp_traverse */ - 0, /* tp_clear */ - 0, /* tp_richcompare */ - 0, /* tp_weaklistoffset */ - PyObject_SelfIter, /* tp_iter */ - (iternextfunc)dictiter_iternextitem, /* tp_iternext */ - dictiter_methods, /* tp_methods */ - 0, + PyVarObject_HEAD_INIT(&PyType_Type, 0) + "dict_itemiterator", /* tp_name */ + sizeof(dictiterobject), /* tp_basicsize */ + 0, /* tp_itemsize */ + /* methods */ + (destructor)dictiter_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)dictiter_traverse, /* tp_traverse */ + 0, /* tp_clear */ + 0, /* tp_richcompare */ + 0, /* tp_weaklistoffset */ + PyObject_SelfIter, /* tp_iter */ + (iternextfunc)dictiter_iternextitem, /* tp_iternext */ + dictiter_methods, /* tp_methods */ + 0, }; @@ -2502,56 +2502,56 @@ /* The instance lay-out is the same for all three; but the type differs. */ typedef struct { - PyObject_HEAD - PyDictObject *dv_dict; + PyObject_HEAD + PyDictObject *dv_dict; } dictviewobject; static void dictview_dealloc(dictviewobject *dv) { - Py_XDECREF(dv->dv_dict); - PyObject_GC_Del(dv); + Py_XDECREF(dv->dv_dict); + PyObject_GC_Del(dv); } static int dictview_traverse(dictviewobject *dv, visitproc visit, void *arg) { - Py_VISIT(dv->dv_dict); - return 0; + Py_VISIT(dv->dv_dict); + return 0; } static Py_ssize_t dictview_len(dictviewobject *dv) { - Py_ssize_t len = 0; - if (dv->dv_dict != NULL) - len = dv->dv_dict->ma_used; - return len; + Py_ssize_t len = 0; + if (dv->dv_dict != NULL) + len = dv->dv_dict->ma_used; + return len; } static PyObject * dictview_new(PyObject *dict, PyTypeObject *type) { - dictviewobject *dv; - if (dict == NULL) { - PyErr_BadInternalCall(); - return NULL; - } - if (!PyDict_Check(dict)) { - /* XXX Get rid of this restriction later */ - PyErr_Format(PyExc_TypeError, - "%s() requires a dict argument, not '%s'", - type->tp_name, dict->ob_type->tp_name); - return NULL; - } - dv = PyObject_GC_New(dictviewobject, type); - if (dv == NULL) - return NULL; - Py_INCREF(dict); - dv->dv_dict = (PyDictObject *)dict; - _PyObject_GC_TRACK(dv); - return (PyObject *)dv; + dictviewobject *dv; + if (dict == NULL) { + PyErr_BadInternalCall(); + return NULL; + } + if (!PyDict_Check(dict)) { + /* XXX Get rid of this restriction later */ + PyErr_Format(PyExc_TypeError, + "%s() requires a dict argument, not '%s'", + type->tp_name, dict->ob_type->tp_name); + return NULL; + } + dv = PyObject_GC_New(dictviewobject, type); + if (dv == NULL) + return NULL; + Py_INCREF(dict); + dv->dv_dict = (PyDictObject *)dict; + _PyObject_GC_TRACK(dv); + return (PyObject *)dv; } /* TODO(guido): The views objects are not complete: @@ -2567,102 +2567,102 @@ static int all_contained_in(PyObject *self, PyObject *other) { - PyObject *iter = PyObject_GetIter(self); - int ok = 1; + PyObject *iter = PyObject_GetIter(self); + int ok = 1; - if (iter == NULL) - return -1; - for (;;) { - PyObject *next = PyIter_Next(iter); - if (next == NULL) { - if (PyErr_Occurred()) - ok = -1; - break; - } - ok = PySequence_Contains(other, next); - Py_DECREF(next); - if (ok <= 0) - break; - } - Py_DECREF(iter); - return ok; + if (iter == NULL) + return -1; + for (;;) { + PyObject *next = PyIter_Next(iter); + if (next == NULL) { + if (PyErr_Occurred()) + ok = -1; + break; + } + ok = PySequence_Contains(other, next); + Py_DECREF(next); + if (ok <= 0) + break; + } + Py_DECREF(iter); + return ok; } static PyObject * dictview_richcompare(PyObject *self, PyObject *other, int op) { - Py_ssize_t len_self, len_other; - int ok; - PyObject *result; - - assert(self != NULL); - assert(PyDictViewSet_Check(self)); - assert(other != NULL); - - if (!PyAnySet_Check(other) && !PyDictViewSet_Check(other)) { - Py_INCREF(Py_NotImplemented); - return Py_NotImplemented; - } - - len_self = PyObject_Size(self); - if (len_self < 0) - return NULL; - len_other = PyObject_Size(other); - if (len_other < 0) - return NULL; - - ok = 0; - switch(op) { - - case Py_NE: - case Py_EQ: - if (len_self == len_other) - ok = all_contained_in(self, other); - if (op == Py_NE && ok >= 0) - ok = !ok; - break; - - case Py_LT: - if (len_self < len_other) - ok = all_contained_in(self, other); - break; - - case Py_LE: - if (len_self <= len_other) - ok = all_contained_in(self, other); - break; - - case Py_GT: - if (len_self > len_other) - ok = all_contained_in(other, self); - break; - - case Py_GE: - if (len_self >= len_other) - ok = all_contained_in(other, self); - break; - - } - if (ok < 0) - return NULL; - result = ok ? Py_True : Py_False; - Py_INCREF(result); - return result; + Py_ssize_t len_self, len_other; + int ok; + PyObject *result; + + assert(self != NULL); + assert(PyDictViewSet_Check(self)); + assert(other != NULL); + + if (!PyAnySet_Check(other) && !PyDictViewSet_Check(other)) { + Py_INCREF(Py_NotImplemented); + return Py_NotImplemented; + } + + len_self = PyObject_Size(self); + if (len_self < 0) + return NULL; + len_other = PyObject_Size(other); + if (len_other < 0) + return NULL; + + ok = 0; + switch(op) { + + case Py_NE: + case Py_EQ: + if (len_self == len_other) + ok = all_contained_in(self, other); + if (op == Py_NE && ok >= 0) + ok = !ok; + break; + + case Py_LT: + if (len_self < len_other) + ok = all_contained_in(self, other); + break; + + case Py_LE: + if (len_self <= len_other) + ok = all_contained_in(self, other); + break; + + case Py_GT: + if (len_self > len_other) + ok = all_contained_in(other, self); + break; + + case Py_GE: + if (len_self >= len_other) + ok = all_contained_in(other, self); + break; + + } + if (ok < 0) + return NULL; + result = ok ? Py_True : Py_False; + Py_INCREF(result); + return result; } static PyObject * dictview_repr(dictviewobject *dv) { - PyObject *seq; - PyObject *result; - - seq = PySequence_List((PyObject *)dv); - if (seq == NULL) - return NULL; - - result = PyUnicode_FromFormat("%s(%R)", Py_TYPE(dv)->tp_name, seq); - Py_DECREF(seq); - return result; + PyObject *seq; + PyObject *result; + + seq = PySequence_List((PyObject *)dv); + if (seq == NULL) + return NULL; + + result = PyUnicode_FromFormat("%s(%R)", Py_TYPE(dv)->tp_name, seq); + Py_DECREF(seq); + return result; } /*** dict_keys ***/ @@ -2670,164 +2670,164 @@ static PyObject * dictkeys_iter(dictviewobject *dv) { - if (dv->dv_dict == NULL) { - Py_RETURN_NONE; - } - return dictiter_new(dv->dv_dict, &PyDictIterKey_Type); + if (dv->dv_dict == NULL) { + Py_RETURN_NONE; + } + return dictiter_new(dv->dv_dict, &PyDictIterKey_Type); } static int dictkeys_contains(dictviewobject *dv, PyObject *obj) { - if (dv->dv_dict == NULL) - return 0; - return PyDict_Contains((PyObject *)dv->dv_dict, obj); + if (dv->dv_dict == NULL) + return 0; + return PyDict_Contains((PyObject *)dv->dv_dict, obj); } static PySequenceMethods dictkeys_as_sequence = { - (lenfunc)dictview_len, /* sq_length */ - 0, /* sq_concat */ - 0, /* sq_repeat */ - 0, /* sq_item */ - 0, /* sq_slice */ - 0, /* sq_ass_item */ - 0, /* sq_ass_slice */ - (objobjproc)dictkeys_contains, /* sq_contains */ + (lenfunc)dictview_len, /* sq_length */ + 0, /* sq_concat */ + 0, /* sq_repeat */ + 0, /* sq_item */ + 0, /* sq_slice */ + 0, /* sq_ass_item */ + 0, /* sq_ass_slice */ + (objobjproc)dictkeys_contains, /* sq_contains */ }; static PyObject* dictviews_sub(PyObject* self, PyObject *other) { - PyObject *result = PySet_New(self); - PyObject *tmp; - if (result == NULL) - return NULL; - - tmp = PyObject_CallMethod(result, "difference_update", "O", other); - if (tmp == NULL) { - Py_DECREF(result); - return NULL; - } + PyObject *result = PySet_New(self); + PyObject *tmp; + if (result == NULL) + return NULL; + + tmp = PyObject_CallMethod(result, "difference_update", "O", other); + if (tmp == NULL) { + Py_DECREF(result); + return NULL; + } - Py_DECREF(tmp); - return result; + Py_DECREF(tmp); + return result; } static PyObject* dictviews_and(PyObject* self, PyObject *other) { - PyObject *result = PySet_New(self); - PyObject *tmp; - if (result == NULL) - return NULL; - - tmp = PyObject_CallMethod(result, "intersection_update", "O", other); - if (tmp == NULL) { - Py_DECREF(result); - return NULL; - } + PyObject *result = PySet_New(self); + PyObject *tmp; + if (result == NULL) + return NULL; + + tmp = PyObject_CallMethod(result, "intersection_update", "O", other); + if (tmp == NULL) { + Py_DECREF(result); + return NULL; + } - Py_DECREF(tmp); - return result; + Py_DECREF(tmp); + return result; } static PyObject* dictviews_or(PyObject* self, PyObject *other) { - PyObject *result = PySet_New(self); - PyObject *tmp; - if (result == NULL) - return NULL; - - tmp = PyObject_CallMethod(result, "update", "O", other); - if (tmp == NULL) { - Py_DECREF(result); - return NULL; - } + PyObject *result = PySet_New(self); + PyObject *tmp; + if (result == NULL) + return NULL; + + tmp = PyObject_CallMethod(result, "update", "O", other); + if (tmp == NULL) { + Py_DECREF(result); + return NULL; + } - Py_DECREF(tmp); - return result; + Py_DECREF(tmp); + return result; } static PyObject* dictviews_xor(PyObject* self, PyObject *other) { - PyObject *result = PySet_New(self); - PyObject *tmp; - if (result == NULL) - return NULL; - - tmp = PyObject_CallMethod(result, "symmetric_difference_update", "O", - other); - if (tmp == NULL) { - Py_DECREF(result); - return NULL; - } + PyObject *result = PySet_New(self); + PyObject *tmp; + if (result == NULL) + return NULL; + + tmp = PyObject_CallMethod(result, "symmetric_difference_update", "O", + other); + if (tmp == NULL) { + Py_DECREF(result); + return NULL; + } - Py_DECREF(tmp); - return result; + Py_DECREF(tmp); + return result; } static PyNumberMethods dictviews_as_number = { - 0, /*nb_add*/ - (binaryfunc)dictviews_sub, /*nb_subtract*/ - 0, /*nb_multiply*/ - 0, /*nb_remainder*/ - 0, /*nb_divmod*/ - 0, /*nb_power*/ - 0, /*nb_negative*/ - 0, /*nb_positive*/ - 0, /*nb_absolute*/ - 0, /*nb_bool*/ - 0, /*nb_invert*/ - 0, /*nb_lshift*/ - 0, /*nb_rshift*/ - (binaryfunc)dictviews_and, /*nb_and*/ - (binaryfunc)dictviews_xor, /*nb_xor*/ - (binaryfunc)dictviews_or, /*nb_or*/ + 0, /*nb_add*/ + (binaryfunc)dictviews_sub, /*nb_subtract*/ + 0, /*nb_multiply*/ + 0, /*nb_remainder*/ + 0, /*nb_divmod*/ + 0, /*nb_power*/ + 0, /*nb_negative*/ + 0, /*nb_positive*/ + 0, /*nb_absolute*/ + 0, /*nb_bool*/ + 0, /*nb_invert*/ + 0, /*nb_lshift*/ + 0, /*nb_rshift*/ + (binaryfunc)dictviews_and, /*nb_and*/ + (binaryfunc)dictviews_xor, /*nb_xor*/ + (binaryfunc)dictviews_or, /*nb_or*/ }; static PyMethodDef dictkeys_methods[] = { - {NULL, NULL} /* sentinel */ + {NULL, NULL} /* sentinel */ }; PyTypeObject PyDictKeys_Type = { - PyVarObject_HEAD_INIT(&PyType_Type, 0) - "dict_keys", /* tp_name */ - sizeof(dictviewobject), /* tp_basicsize */ - 0, /* tp_itemsize */ - /* methods */ - (destructor)dictview_dealloc, /* tp_dealloc */ - 0, /* tp_print */ - 0, /* tp_getattr */ - 0, /* tp_setattr */ - 0, /* tp_reserved */ - (reprfunc)dictview_repr, /* tp_repr */ - &dictviews_as_number, /* tp_as_number */ - &dictkeys_as_sequence, /* 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)dictview_traverse, /* tp_traverse */ - 0, /* tp_clear */ - dictview_richcompare, /* tp_richcompare */ - 0, /* tp_weaklistoffset */ - (getiterfunc)dictkeys_iter, /* tp_iter */ - 0, /* tp_iternext */ - dictkeys_methods, /* tp_methods */ - 0, + PyVarObject_HEAD_INIT(&PyType_Type, 0) + "dict_keys", /* tp_name */ + sizeof(dictviewobject), /* tp_basicsize */ + 0, /* tp_itemsize */ + /* methods */ + (destructor)dictview_dealloc, /* tp_dealloc */ + 0, /* tp_print */ + 0, /* tp_getattr */ + 0, /* tp_setattr */ + 0, /* tp_reserved */ + (reprfunc)dictview_repr, /* tp_repr */ + &dictviews_as_number, /* tp_as_number */ + &dictkeys_as_sequence, /* 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)dictview_traverse, /* tp_traverse */ + 0, /* tp_clear */ + dictview_richcompare, /* tp_richcompare */ + 0, /* tp_weaklistoffset */ + (getiterfunc)dictkeys_iter, /* tp_iter */ + 0, /* tp_iternext */ + dictkeys_methods, /* tp_methods */ + 0, }; static PyObject * dictkeys_new(PyObject *dict) { - return dictview_new(dict, &PyDictKeys_Type); + return dictview_new(dict, &PyDictKeys_Type); } /*** dict_items ***/ @@ -2835,83 +2835,83 @@ static PyObject * dictitems_iter(dictviewobject *dv) { - if (dv->dv_dict == NULL) { - Py_RETURN_NONE; - } - return dictiter_new(dv->dv_dict, &PyDictIterItem_Type); + if (dv->dv_dict == NULL) { + Py_RETURN_NONE; + } + return dictiter_new(dv->dv_dict, &PyDictIterItem_Type); } static int dictitems_contains(dictviewobject *dv, PyObject *obj) { - PyObject *key, *value, *found; - if (dv->dv_dict == NULL) - return 0; - if (!PyTuple_Check(obj) || PyTuple_GET_SIZE(obj) != 2) - return 0; - key = PyTuple_GET_ITEM(obj, 0); - value = PyTuple_GET_ITEM(obj, 1); - found = PyDict_GetItem((PyObject *)dv->dv_dict, key); - if (found == NULL) { - if (PyErr_Occurred()) - return -1; - return 0; - } - return PyObject_RichCompareBool(value, found, Py_EQ); + PyObject *key, *value, *found; + if (dv->dv_dict == NULL) + return 0; + if (!PyTuple_Check(obj) || PyTuple_GET_SIZE(obj) != 2) + return 0; + key = PyTuple_GET_ITEM(obj, 0); + value = PyTuple_GET_ITEM(obj, 1); + found = PyDict_GetItem((PyObject *)dv->dv_dict, key); + if (found == NULL) { + if (PyErr_Occurred()) + return -1; + return 0; + } + return PyObject_RichCompareBool(value, found, Py_EQ); } static PySequenceMethods dictitems_as_sequence = { - (lenfunc)dictview_len, /* sq_length */ - 0, /* sq_concat */ - 0, /* sq_repeat */ - 0, /* sq_item */ - 0, /* sq_slice */ - 0, /* sq_ass_item */ - 0, /* sq_ass_slice */ - (objobjproc)dictitems_contains, /* sq_contains */ + (lenfunc)dictview_len, /* sq_length */ + 0, /* sq_concat */ + 0, /* sq_repeat */ + 0, /* sq_item */ + 0, /* sq_slice */ + 0, /* sq_ass_item */ + 0, /* sq_ass_slice */ + (objobjproc)dictitems_contains, /* sq_contains */ }; static PyMethodDef dictitems_methods[] = { - {NULL, NULL} /* sentinel */ + {NULL, NULL} /* sentinel */ }; PyTypeObject PyDictItems_Type = { - PyVarObject_HEAD_INIT(&PyType_Type, 0) - "dict_items", /* tp_name */ - sizeof(dictviewobject), /* tp_basicsize */ - 0, /* tp_itemsize */ - /* methods */ - (destructor)dictview_dealloc, /* tp_dealloc */ - 0, /* tp_print */ - 0, /* tp_getattr */ - 0, /* tp_setattr */ - 0, /* tp_reserved */ - (reprfunc)dictview_repr, /* tp_repr */ - &dictviews_as_number, /* tp_as_number */ - &dictitems_as_sequence, /* 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)dictview_traverse, /* tp_traverse */ - 0, /* tp_clear */ - dictview_richcompare, /* tp_richcompare */ - 0, /* tp_weaklistoffset */ - (getiterfunc)dictitems_iter, /* tp_iter */ - 0, /* tp_iternext */ - dictitems_methods, /* tp_methods */ - 0, + PyVarObject_HEAD_INIT(&PyType_Type, 0) + "dict_items", /* tp_name */ + sizeof(dictviewobject), /* tp_basicsize */ + 0, /* tp_itemsize */ + /* methods */ + (destructor)dictview_dealloc, /* tp_dealloc */ + 0, /* tp_print */ + 0, /* tp_getattr */ + 0, /* tp_setattr */ + 0, /* tp_reserved */ + (reprfunc)dictview_repr, /* tp_repr */ + &dictviews_as_number, /* tp_as_number */ + &dictitems_as_sequence, /* 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)dictview_traverse, /* tp_traverse */ + 0, /* tp_clear */ + dictview_richcompare, /* tp_richcompare */ + 0, /* tp_weaklistoffset */ + (getiterfunc)dictitems_iter, /* tp_iter */ + 0, /* tp_iternext */ + dictitems_methods, /* tp_methods */ + 0, }; static PyObject * dictitems_new(PyObject *dict) { - return dictview_new(dict, &PyDictItems_Type); + return dictview_new(dict, &PyDictItems_Type); } /*** dict_values ***/ @@ -2919,62 +2919,62 @@ static PyObject * dictvalues_iter(dictviewobject *dv) { - if (dv->dv_dict == NULL) { - Py_RETURN_NONE; - } - return dictiter_new(dv->dv_dict, &PyDictIterValue_Type); + if (dv->dv_dict == NULL) { + Py_RETURN_NONE; + } + return dictiter_new(dv->dv_dict, &PyDictIterValue_Type); } static PySequenceMethods dictvalues_as_sequence = { - (lenfunc)dictview_len, /* sq_length */ - 0, /* sq_concat */ - 0, /* sq_repeat */ - 0, /* sq_item */ - 0, /* sq_slice */ - 0, /* sq_ass_item */ - 0, /* sq_ass_slice */ - (objobjproc)0, /* sq_contains */ + (lenfunc)dictview_len, /* sq_length */ + 0, /* sq_concat */ + 0, /* sq_repeat */ + 0, /* sq_item */ + 0, /* sq_slice */ + 0, /* sq_ass_item */ + 0, /* sq_ass_slice */ + (objobjproc)0, /* sq_contains */ }; static PyMethodDef dictvalues_methods[] = { - {NULL, NULL} /* sentinel */ + {NULL, NULL} /* sentinel */ }; PyTypeObject PyDictValues_Type = { - PyVarObject_HEAD_INIT(&PyType_Type, 0) - "dict_values", /* tp_name */ - sizeof(dictviewobject), /* tp_basicsize */ - 0, /* tp_itemsize */ - /* methods */ - (destructor)dictview_dealloc, /* tp_dealloc */ - 0, /* tp_print */ - 0, /* tp_getattr */ - 0, /* tp_setattr */ - 0, /* tp_reserved */ - (reprfunc)dictview_repr, /* tp_repr */ - 0, /* tp_as_number */ - &dictvalues_as_sequence, /* 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)dictview_traverse, /* tp_traverse */ - 0, /* tp_clear */ - 0, /* tp_richcompare */ - 0, /* tp_weaklistoffset */ - (getiterfunc)dictvalues_iter, /* tp_iter */ - 0, /* tp_iternext */ - dictvalues_methods, /* tp_methods */ - 0, + PyVarObject_HEAD_INIT(&PyType_Type, 0) + "dict_values", /* tp_name */ + sizeof(dictviewobject), /* tp_basicsize */ + 0, /* tp_itemsize */ + /* methods */ + (destructor)dictview_dealloc, /* tp_dealloc */ + 0, /* tp_print */ + 0, /* tp_getattr */ + 0, /* tp_setattr */ + 0, /* tp_reserved */ + (reprfunc)dictview_repr, /* tp_repr */ + 0, /* tp_as_number */ + &dictvalues_as_sequence, /* 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)dictview_traverse, /* tp_traverse */ + 0, /* tp_clear */ + 0, /* tp_richcompare */ + 0, /* tp_weaklistoffset */ + (getiterfunc)dictvalues_iter, /* tp_iter */ + 0, /* tp_iternext */ + dictvalues_methods, /* tp_methods */ + 0, }; static PyObject * dictvalues_new(PyObject *dict) { - return dictview_new(dict, &PyDictValues_Type); + return dictview_new(dict, &PyDictValues_Type); } Modified: python/branches/release31-maint/Objects/enumobject.c ============================================================================== --- python/branches/release31-maint/Objects/enumobject.c (original) +++ python/branches/release31-maint/Objects/enumobject.c Sun May 9 18:14:21 2010 @@ -3,159 +3,159 @@ #include "Python.h" typedef struct { - PyObject_HEAD - Py_ssize_t en_index; /* current index of enumeration */ - PyObject* en_sit; /* secondary iterator of enumeration */ - PyObject* en_result; /* result tuple */ - PyObject* en_longindex; /* index for sequences >= PY_SSIZE_T_MAX */ + PyObject_HEAD + Py_ssize_t en_index; /* current index of enumeration */ + PyObject* en_sit; /* secondary iterator of enumeration */ + PyObject* en_result; /* result tuple */ + PyObject* en_longindex; /* index for sequences >= PY_SSIZE_T_MAX */ } enumobject; static PyObject * enum_new(PyTypeObject *type, PyObject *args, PyObject *kwds) { - enumobject *en; - PyObject *seq = NULL; - PyObject *start = NULL; - static char *kwlist[] = {"iterable", "start", 0}; - - if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|O:enumerate", kwlist, - &seq, &start)) - return NULL; - - en = (enumobject *)type->tp_alloc(type, 0); - if (en == NULL) - return NULL; - if (start != NULL) { - start = PyNumber_Index(start); - if (start == NULL) { - Py_DECREF(en); - return NULL; - } - assert(PyLong_Check(start)); - en->en_index = PyLong_AsSsize_t(start); - if (en->en_index == -1 && PyErr_Occurred()) { - PyErr_Clear(); - en->en_index = PY_SSIZE_T_MAX; - en->en_longindex = start; - } else { - en->en_longindex = NULL; - Py_DECREF(start); - } - } else { - en->en_index = 0; - en->en_longindex = NULL; - } - en->en_sit = PyObject_GetIter(seq); - if (en->en_sit == NULL) { - Py_DECREF(en); - return NULL; - } - en->en_result = PyTuple_Pack(2, Py_None, Py_None); - if (en->en_result == NULL) { - Py_DECREF(en); - return NULL; - } - return (PyObject *)en; + enumobject *en; + PyObject *seq = NULL; + PyObject *start = NULL; + static char *kwlist[] = {"iterable", "start", 0}; + + if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|O:enumerate", kwlist, + &seq, &start)) + return NULL; + + en = (enumobject *)type->tp_alloc(type, 0); + if (en == NULL) + return NULL; + if (start != NULL) { + start = PyNumber_Index(start); + if (start == NULL) { + Py_DECREF(en); + return NULL; + } + assert(PyLong_Check(start)); + en->en_index = PyLong_AsSsize_t(start); + if (en->en_index == -1 && PyErr_Occurred()) { + PyErr_Clear(); + en->en_index = PY_SSIZE_T_MAX; + en->en_longindex = start; + } else { + en->en_longindex = NULL; + Py_DECREF(start); + } + } else { + en->en_index = 0; + en->en_longindex = NULL; + } + en->en_sit = PyObject_GetIter(seq); + if (en->en_sit == NULL) { + Py_DECREF(en); + return NULL; + } + en->en_result = PyTuple_Pack(2, Py_None, Py_None); + if (en->en_result == NULL) { + Py_DECREF(en); + return NULL; + } + return (PyObject *)en; } static void enum_dealloc(enumobject *en) { - PyObject_GC_UnTrack(en); - Py_XDECREF(en->en_sit); - Py_XDECREF(en->en_result); - Py_XDECREF(en->en_longindex); - Py_TYPE(en)->tp_free(en); + PyObject_GC_UnTrack(en); + Py_XDECREF(en->en_sit); + Py_XDECREF(en->en_result); + Py_XDECREF(en->en_longindex); + Py_TYPE(en)->tp_free(en); } static int enum_traverse(enumobject *en, visitproc visit, void *arg) { - Py_VISIT(en->en_sit); - Py_VISIT(en->en_result); - Py_VISIT(en->en_longindex); - return 0; + Py_VISIT(en->en_sit); + Py_VISIT(en->en_result); + Py_VISIT(en->en_longindex); + return 0; } static PyObject * enum_next_long(enumobject *en, PyObject* next_item) { - static PyObject *one = NULL; - PyObject *result = en->en_result; - PyObject *next_index; - PyObject *stepped_up; - - if (en->en_longindex == NULL) { - en->en_longindex = PyLong_FromSsize_t(PY_SSIZE_T_MAX); - if (en->en_longindex == NULL) - return NULL; - } - if (one == NULL) { - one = PyLong_FromLong(1); - if (one == NULL) - return NULL; - } - next_index = en->en_longindex; - assert(next_index != NULL); - stepped_up = PyNumber_Add(next_index, one); - if (stepped_up == NULL) - return NULL; - en->en_longindex = stepped_up; - - if (result->ob_refcnt == 1) { - Py_INCREF(result); - Py_DECREF(PyTuple_GET_ITEM(result, 0)); - Py_DECREF(PyTuple_GET_ITEM(result, 1)); - } else { - result = PyTuple_New(2); - if (result == NULL) { - Py_DECREF(next_index); - Py_DECREF(next_item); - return NULL; - } - } - PyTuple_SET_ITEM(result, 0, next_index); - PyTuple_SET_ITEM(result, 1, next_item); - return result; + static PyObject *one = NULL; + PyObject *result = en->en_result; + PyObject *next_index; + PyObject *stepped_up; + + if (en->en_longindex == NULL) { + en->en_longindex = PyLong_FromSsize_t(PY_SSIZE_T_MAX); + if (en->en_longindex == NULL) + return NULL; + } + if (one == NULL) { + one = PyLong_FromLong(1); + if (one == NULL) + return NULL; + } + next_index = en->en_longindex; + assert(next_index != NULL); + stepped_up = PyNumber_Add(next_index, one); + if (stepped_up == NULL) + return NULL; + en->en_longindex = stepped_up; + + if (result->ob_refcnt == 1) { + Py_INCREF(result); + Py_DECREF(PyTuple_GET_ITEM(result, 0)); + Py_DECREF(PyTuple_GET_ITEM(result, 1)); + } else { + result = PyTuple_New(2); + if (result == NULL) { + Py_DECREF(next_index); + Py_DECREF(next_item); + return NULL; + } + } + PyTuple_SET_ITEM(result, 0, next_index); + PyTuple_SET_ITEM(result, 1, next_item); + return result; } static PyObject * enum_next(enumobject *en) { - PyObject *next_index; - PyObject *next_item; - PyObject *result = en->en_result; - PyObject *it = en->en_sit; - - next_item = (*Py_TYPE(it)->tp_iternext)(it); - if (next_item == NULL) - return NULL; - - if (en->en_index == PY_SSIZE_T_MAX) - return enum_next_long(en, next_item); - - next_index = PyLong_FromSsize_t(en->en_index); - if (next_index == NULL) { - Py_DECREF(next_item); - return NULL; - } - en->en_index++; - - if (result->ob_refcnt == 1) { - Py_INCREF(result); - Py_DECREF(PyTuple_GET_ITEM(result, 0)); - Py_DECREF(PyTuple_GET_ITEM(result, 1)); - } else { - result = PyTuple_New(2); - if (result == NULL) { - Py_DECREF(next_index); - Py_DECREF(next_item); - return NULL; - } - } - PyTuple_SET_ITEM(result, 0, next_index); - PyTuple_SET_ITEM(result, 1, next_item); - return result; + PyObject *next_index; + PyObject *next_item; + PyObject *result = en->en_result; + PyObject *it = en->en_sit; + + next_item = (*Py_TYPE(it)->tp_iternext)(it); + if (next_item == NULL) + return NULL; + + if (en->en_index == PY_SSIZE_T_MAX) + return enum_next_long(en, next_item); + + next_index = PyLong_FromSsize_t(en->en_index); + if (next_index == NULL) { + Py_DECREF(next_item); + return NULL; + } + en->en_index++; + + if (result->ob_refcnt == 1) { + Py_INCREF(result); + Py_DECREF(PyTuple_GET_ITEM(result, 0)); + Py_DECREF(PyTuple_GET_ITEM(result, 1)); + } else { + result = PyTuple_New(2); + if (result == NULL) { + Py_DECREF(next_index); + Py_DECREF(next_item); + return NULL; + } + } + PyTuple_SET_ITEM(result, 0, next_index); + PyTuple_SET_ITEM(result, 1, next_item); + return result; } PyDoc_STRVAR(enum_doc, @@ -167,134 +167,134 @@ "for obtaining an indexed list: (0, seq[0]), (1, seq[1]), (2, seq[2]), ..."); PyTypeObject PyEnum_Type = { - PyVarObject_HEAD_INIT(&PyType_Type, 0) - "enumerate", /* tp_name */ - sizeof(enumobject), /* tp_basicsize */ - 0, /* tp_itemsize */ - /* methods */ - (destructor)enum_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 | - Py_TPFLAGS_BASETYPE, /* tp_flags */ - enum_doc, /* tp_doc */ - (traverseproc)enum_traverse, /* tp_traverse */ - 0, /* tp_clear */ - 0, /* tp_richcompare */ - 0, /* tp_weaklistoffset */ - PyObject_SelfIter, /* tp_iter */ - (iternextfunc)enum_next, /* tp_iternext */ - 0, /* tp_methods */ - 0, /* tp_members */ - 0, /* tp_getset */ - 0, /* tp_base */ - 0, /* tp_dict */ - 0, /* tp_descr_get */ - 0, /* tp_descr_set */ - 0, /* tp_dictoffset */ - 0, /* tp_init */ - PyType_GenericAlloc, /* tp_alloc */ - enum_new, /* tp_new */ - PyObject_GC_Del, /* tp_free */ + PyVarObject_HEAD_INIT(&PyType_Type, 0) + "enumerate", /* tp_name */ + sizeof(enumobject), /* tp_basicsize */ + 0, /* tp_itemsize */ + /* methods */ + (destructor)enum_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 | + Py_TPFLAGS_BASETYPE, /* tp_flags */ + enum_doc, /* tp_doc */ + (traverseproc)enum_traverse, /* tp_traverse */ + 0, /* tp_clear */ + 0, /* tp_richcompare */ + 0, /* tp_weaklistoffset */ + PyObject_SelfIter, /* tp_iter */ + (iternextfunc)enum_next, /* tp_iternext */ + 0, /* tp_methods */ + 0, /* tp_members */ + 0, /* tp_getset */ + 0, /* tp_base */ + 0, /* tp_dict */ + 0, /* tp_descr_get */ + 0, /* tp_descr_set */ + 0, /* tp_dictoffset */ + 0, /* tp_init */ + PyType_GenericAlloc, /* tp_alloc */ + enum_new, /* tp_new */ + PyObject_GC_Del, /* tp_free */ }; /* Reversed Object ***************************************************************/ typedef struct { - PyObject_HEAD - Py_ssize_t index; - PyObject* seq; + PyObject_HEAD + Py_ssize_t index; + PyObject* seq; } reversedobject; static PyObject * reversed_new(PyTypeObject *type, PyObject *args, PyObject *kwds) { - Py_ssize_t n; - PyObject *seq, *reversed_meth; - static PyObject *reversed_cache = NULL; - reversedobject *ro; - - if (type == &PyReversed_Type && !_PyArg_NoKeywords("reversed()", kwds)) - return NULL; - - if (!PyArg_UnpackTuple(args, "reversed", 1, 1, &seq) ) - return NULL; - - reversed_meth = _PyObject_LookupSpecial(seq, "__reversed__", &reversed_cache); - if (reversed_meth != NULL) { - PyObject *res = PyObject_CallFunctionObjArgs(reversed_meth, NULL); - Py_DECREF(reversed_meth); - return res; - } - else if (PyErr_Occurred()) - return NULL; - - if (!PySequence_Check(seq)) { - PyErr_SetString(PyExc_TypeError, - "argument to reversed() must be a sequence"); - return NULL; - } - - n = PySequence_Size(seq); - if (n == -1) - return NULL; - - ro = (reversedobject *)type->tp_alloc(type, 0); - if (ro == NULL) - return NULL; - - ro->index = n-1; - Py_INCREF(seq); - ro->seq = seq; - return (PyObject *)ro; + Py_ssize_t n; + PyObject *seq, *reversed_meth; + static PyObject *reversed_cache = NULL; + reversedobject *ro; + + if (type == &PyReversed_Type && !_PyArg_NoKeywords("reversed()", kwds)) + return NULL; + + if (!PyArg_UnpackTuple(args, "reversed", 1, 1, &seq) ) + return NULL; + + reversed_meth = _PyObject_LookupSpecial(seq, "__reversed__", &reversed_cache); + if (reversed_meth != NULL) { + PyObject *res = PyObject_CallFunctionObjArgs(reversed_meth, NULL); + Py_DECREF(reversed_meth); + return res; + } + else if (PyErr_Occurred()) + return NULL; + + if (!PySequence_Check(seq)) { + PyErr_SetString(PyExc_TypeError, + "argument to reversed() must be a sequence"); + return NULL; + } + + n = PySequence_Size(seq); + if (n == -1) + return NULL; + + ro = (reversedobject *)type->tp_alloc(type, 0); + if (ro == NULL) + return NULL; + + ro->index = n-1; + Py_INCREF(seq); + ro->seq = seq; + return (PyObject *)ro; } static void reversed_dealloc(reversedobject *ro) { - PyObject_GC_UnTrack(ro); - Py_XDECREF(ro->seq); - Py_TYPE(ro)->tp_free(ro); + PyObject_GC_UnTrack(ro); + Py_XDECREF(ro->seq); + Py_TYPE(ro)->tp_free(ro); } static int reversed_traverse(reversedobject *ro, visitproc visit, void *arg) { - Py_VISIT(ro->seq); - return 0; + Py_VISIT(ro->seq); + return 0; } static PyObject * reversed_next(reversedobject *ro) { - PyObject *item; - Py_ssize_t index = ro->index; + PyObject *item; + Py_ssize_t index = ro->index; - if (index >= 0) { - item = PySequence_GetItem(ro->seq, index); - if (item != NULL) { - ro->index--; - return item; - } - if (PyErr_ExceptionMatches(PyExc_IndexError) || - PyErr_ExceptionMatches(PyExc_StopIteration)) - PyErr_Clear(); - } - ro->index = -1; - Py_CLEAR(ro->seq); - return NULL; + if (index >= 0) { + item = PySequence_GetItem(ro->seq, index); + if (item != NULL) { + ro->index--; + return item; + } + if (PyErr_ExceptionMatches(PyExc_IndexError) || + PyErr_ExceptionMatches(PyExc_StopIteration)) + PyErr_Clear(); + } + ro->index = -1; + Py_CLEAR(ro->seq); + return NULL; } PyDoc_STRVAR(reversed_doc, @@ -305,64 +305,64 @@ static PyObject * reversed_len(reversedobject *ro) { - Py_ssize_t position, seqsize; + Py_ssize_t position, seqsize; - if (ro->seq == NULL) - return PyLong_FromLong(0); - seqsize = PySequence_Size(ro->seq); - if (seqsize == -1) - return NULL; - position = ro->index + 1; - return PyLong_FromSsize_t((seqsize < position) ? 0 : position); + if (ro->seq == NULL) + return PyLong_FromLong(0); + seqsize = PySequence_Size(ro->seq); + if (seqsize == -1) + return NULL; + position = ro->index + 1; + return PyLong_FromSsize_t((seqsize < position) ? 0 : position); } PyDoc_STRVAR(length_hint_doc, "Private method returning an estimate of len(list(it))."); static PyMethodDef reversediter_methods[] = { - {"__length_hint__", (PyCFunction)reversed_len, METH_NOARGS, length_hint_doc}, - {NULL, NULL} /* sentinel */ + {"__length_hint__", (PyCFunction)reversed_len, METH_NOARGS, length_hint_doc}, + {NULL, NULL} /* sentinel */ }; PyTypeObject PyReversed_Type = { - PyVarObject_HEAD_INIT(&PyType_Type, 0) - "reversed", /* tp_name */ - sizeof(reversedobject), /* tp_basicsize */ - 0, /* tp_itemsize */ - /* methods */ - (destructor)reversed_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 | - Py_TPFLAGS_BASETYPE, /* tp_flags */ - reversed_doc, /* tp_doc */ - (traverseproc)reversed_traverse,/* tp_traverse */ - 0, /* tp_clear */ - 0, /* tp_richcompare */ - 0, /* tp_weaklistoffset */ - PyObject_SelfIter, /* tp_iter */ - (iternextfunc)reversed_next, /* tp_iternext */ - reversediter_methods, /* tp_methods */ - 0, /* tp_members */ - 0, /* tp_getset */ - 0, /* tp_base */ - 0, /* tp_dict */ - 0, /* tp_descr_get */ - 0, /* tp_descr_set */ - 0, /* tp_dictoffset */ - 0, /* tp_init */ - PyType_GenericAlloc, /* tp_alloc */ - reversed_new, /* tp_new */ - PyObject_GC_Del, /* tp_free */ + PyVarObject_HEAD_INIT(&PyType_Type, 0) + "reversed", /* tp_name */ + sizeof(reversedobject), /* tp_basicsize */ + 0, /* tp_itemsize */ + /* methods */ + (destructor)reversed_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 | + Py_TPFLAGS_BASETYPE, /* tp_flags */ + reversed_doc, /* tp_doc */ + (traverseproc)reversed_traverse,/* tp_traverse */ + 0, /* tp_clear */ + 0, /* tp_richcompare */ + 0, /* tp_weaklistoffset */ + PyObject_SelfIter, /* tp_iter */ + (iternextfunc)reversed_next, /* tp_iternext */ + reversediter_methods, /* tp_methods */ + 0, /* tp_members */ + 0, /* tp_getset */ + 0, /* tp_base */ + 0, /* tp_dict */ + 0, /* tp_descr_get */ + 0, /* tp_descr_set */ + 0, /* tp_dictoffset */ + 0, /* tp_init */ + PyType_GenericAlloc, /* tp_alloc */ + reversed_new, /* tp_new */ + PyObject_GC_Del, /* tp_free */ }; Modified: python/branches/release31-maint/Objects/exceptions.c ============================================================================== --- python/branches/release31-maint/Objects/exceptions.c (original) +++ python/branches/release31-maint/Objects/exceptions.c Sun May 9 18:14:21 2010 @@ -270,7 +270,7 @@ } else { /* PyException_SetContext steals this reference */ Py_INCREF(arg); - } + } PyException_SetContext(self, arg); return 0; } @@ -296,7 +296,7 @@ } else { /* PyException_SetCause steals this reference */ Py_INCREF(arg); - } + } PyException_SetCause(self, arg); return 0; } @@ -379,7 +379,7 @@ PyObject_GenericSetAttr, /*tp_setattro*/ 0, /*tp_as_buffer*/ Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC | - Py_TPFLAGS_BASE_EXC_SUBCLASS, /*tp_flags*/ + Py_TPFLAGS_BASE_EXC_SUBCLASS, /*tp_flags*/ PyDoc_STR("Common base class for all exceptions"), /* tp_doc */ (traverseproc)BaseException_traverse, /* tp_traverse */ (inquiry)BaseException_clear, /* tp_clear */ @@ -990,7 +990,7 @@ lineno here */ if (self->filename && PyUnicode_Check(self->filename)) { - filename = _PyUnicode_AsString(self->filename); + filename = _PyUnicode_AsString(self->filename); } have_lineno = (self->lineno != NULL) && PyLong_CheckExact(self->lineno); @@ -1001,7 +1001,7 @@ return PyUnicode_FromFormat("%S (%s, line %ld)", self->msg ? self->msg : Py_None, my_basename(filename), - PyLong_AsLongAndOverflow(self->lineno, &overflow)); + PyLong_AsLongAndOverflow(self->lineno, &overflow)); else if (filename) return PyUnicode_FromFormat("%S (%s)", self->msg ? self->msg : Py_None, @@ -1997,25 +1997,25 @@ PyExc_RecursionErrorInst = BaseException_new(&_PyExc_RuntimeError, NULL, NULL); if (!PyExc_RecursionErrorInst) - Py_FatalError("Cannot pre-allocate RuntimeError instance for " - "recursion errors"); + Py_FatalError("Cannot pre-allocate RuntimeError instance for " + "recursion errors"); else { - PyBaseExceptionObject *err_inst = - (PyBaseExceptionObject *)PyExc_RecursionErrorInst; - PyObject *args_tuple; - PyObject *exc_message; - exc_message = PyUnicode_FromString("maximum recursion depth exceeded"); - if (!exc_message) - Py_FatalError("cannot allocate argument for RuntimeError " - "pre-allocation"); - args_tuple = PyTuple_Pack(1, exc_message); - if (!args_tuple) - Py_FatalError("cannot allocate tuple for RuntimeError " - "pre-allocation"); - Py_DECREF(exc_message); - if (BaseException_init(err_inst, args_tuple, NULL)) - Py_FatalError("init of pre-allocated RuntimeError failed"); - Py_DECREF(args_tuple); + PyBaseExceptionObject *err_inst = + (PyBaseExceptionObject *)PyExc_RecursionErrorInst; + PyObject *args_tuple; + PyObject *exc_message; + exc_message = PyUnicode_FromString("maximum recursion depth exceeded"); + if (!exc_message) + Py_FatalError("cannot allocate argument for RuntimeError " + "pre-allocation"); + args_tuple = PyTuple_Pack(1, exc_message); + if (!args_tuple) + Py_FatalError("cannot allocate tuple for RuntimeError " + "pre-allocation"); + Py_DECREF(exc_message); + if (BaseException_init(err_inst, args_tuple, NULL)) + Py_FatalError("init of pre-allocated RuntimeError failed"); + Py_DECREF(args_tuple); } Py_DECREF(bltinmod); Modified: python/branches/release31-maint/Objects/fileobject.c ============================================================================== --- python/branches/release31-maint/Objects/fileobject.c (original) +++ python/branches/release31-maint/Objects/fileobject.c Sun May 9 18:14:21 2010 @@ -14,10 +14,10 @@ #endif /* Newline flags */ -#define NEWLINE_UNKNOWN 0 /* No newline seen, yet */ -#define NEWLINE_CR 1 /* \r newline seen */ -#define NEWLINE_LF 2 /* \n newline seen */ -#define NEWLINE_CRLF 4 /* \r\n newline seen */ +#define NEWLINE_UNKNOWN 0 /* No newline seen, yet */ +#define NEWLINE_CR 1 /* \r newline seen */ +#define NEWLINE_LF 2 /* \n newline seen */ +#define NEWLINE_CRLF 4 /* \r\n newline seen */ #ifdef __cplusplus extern "C" { @@ -27,110 +27,110 @@ PyObject * PyFile_FromFd(int fd, char *name, char *mode, int buffering, char *encoding, - char *errors, char *newline, int closefd) + char *errors, char *newline, int closefd) { - PyObject *io, *stream, *nameobj = NULL; + PyObject *io, *stream, *nameobj = NULL; - io = PyImport_ImportModule("io"); - if (io == NULL) - return NULL; - stream = PyObject_CallMethod(io, "open", "isisssi", fd, mode, - buffering, encoding, errors, - newline, closefd); - Py_DECREF(io); - if (stream == NULL) - return NULL; - if (name != NULL) { - nameobj = PyUnicode_FromString(name); - if (nameobj == NULL) - PyErr_Clear(); - else { - if (PyObject_SetAttrString(stream, "name", nameobj) < 0) - PyErr_Clear(); - Py_DECREF(nameobj); - } - } - return stream; + io = PyImport_ImportModule("io"); + if (io == NULL) + return NULL; + stream = PyObject_CallMethod(io, "open", "isisssi", fd, mode, + buffering, encoding, errors, + newline, closefd); + Py_DECREF(io); + if (stream == NULL) + return NULL; + if (name != NULL) { + nameobj = PyUnicode_FromString(name); + if (nameobj == NULL) + PyErr_Clear(); + else { + if (PyObject_SetAttrString(stream, "name", nameobj) < 0) + PyErr_Clear(); + Py_DECREF(nameobj); + } + } + return stream; } PyObject * PyFile_GetLine(PyObject *f, int n) { - PyObject *result; + PyObject *result; - if (f == NULL) { - PyErr_BadInternalCall(); - return NULL; - } - - { - PyObject *reader; - PyObject *args; - - reader = PyObject_GetAttrString(f, "readline"); - if (reader == NULL) - return NULL; - if (n <= 0) - args = PyTuple_New(0); - else - args = Py_BuildValue("(i)", n); - if (args == NULL) { - Py_DECREF(reader); - return NULL; - } - result = PyEval_CallObject(reader, args); - Py_DECREF(reader); - Py_DECREF(args); - if (result != NULL && !PyBytes_Check(result) && - !PyUnicode_Check(result)) { - Py_DECREF(result); - result = NULL; - PyErr_SetString(PyExc_TypeError, - "object.readline() returned non-string"); - } - } - - if (n < 0 && result != NULL && PyBytes_Check(result)) { - char *s = PyBytes_AS_STRING(result); - Py_ssize_t len = PyBytes_GET_SIZE(result); - if (len == 0) { - Py_DECREF(result); - result = NULL; - PyErr_SetString(PyExc_EOFError, - "EOF when reading a line"); - } - else if (s[len-1] == '\n') { - if (result->ob_refcnt == 1) - _PyBytes_Resize(&result, len-1); - else { - PyObject *v; - v = PyBytes_FromStringAndSize(s, len-1); - Py_DECREF(result); - result = v; - } - } - } - if (n < 0 && result != NULL && PyUnicode_Check(result)) { - Py_UNICODE *s = PyUnicode_AS_UNICODE(result); - Py_ssize_t len = PyUnicode_GET_SIZE(result); - if (len == 0) { - Py_DECREF(result); - result = NULL; - PyErr_SetString(PyExc_EOFError, - "EOF when reading a line"); - } - else if (s[len-1] == '\n') { - if (result->ob_refcnt == 1) - PyUnicode_Resize(&result, len-1); - else { - PyObject *v; - v = PyUnicode_FromUnicode(s, len-1); - Py_DECREF(result); - result = v; - } - } - } - return result; + if (f == NULL) { + PyErr_BadInternalCall(); + return NULL; + } + + { + PyObject *reader; + PyObject *args; + + reader = PyObject_GetAttrString(f, "readline"); + if (reader == NULL) + return NULL; + if (n <= 0) + args = PyTuple_New(0); + else + args = Py_BuildValue("(i)", n); + if (args == NULL) { + Py_DECREF(reader); + return NULL; + } + result = PyEval_CallObject(reader, args); + Py_DECREF(reader); + Py_DECREF(args); + if (result != NULL && !PyBytes_Check(result) && + !PyUnicode_Check(result)) { + Py_DECREF(result); + result = NULL; + PyErr_SetString(PyExc_TypeError, + "object.readline() returned non-string"); + } + } + + if (n < 0 && result != NULL && PyBytes_Check(result)) { + char *s = PyBytes_AS_STRING(result); + Py_ssize_t len = PyBytes_GET_SIZE(result); + if (len == 0) { + Py_DECREF(result); + result = NULL; + PyErr_SetString(PyExc_EOFError, + "EOF when reading a line"); + } + else if (s[len-1] == '\n') { + if (result->ob_refcnt == 1) + _PyBytes_Resize(&result, len-1); + else { + PyObject *v; + v = PyBytes_FromStringAndSize(s, len-1); + Py_DECREF(result); + result = v; + } + } + } + if (n < 0 && result != NULL && PyUnicode_Check(result)) { + Py_UNICODE *s = PyUnicode_AS_UNICODE(result); + Py_ssize_t len = PyUnicode_GET_SIZE(result); + if (len == 0) { + Py_DECREF(result); + result = NULL; + PyErr_SetString(PyExc_EOFError, + "EOF when reading a line"); + } + else if (s[len-1] == '\n') { + if (result->ob_refcnt == 1) + PyUnicode_Resize(&result, len-1); + else { + PyObject *v; + v = PyUnicode_FromUnicode(s, len-1); + Py_DECREF(result); + result = v; + } + } + } + return result; } /* Interfaces to write objects/strings to file-like objects */ @@ -138,60 +138,60 @@ int PyFile_WriteObject(PyObject *v, PyObject *f, int flags) { - PyObject *writer, *value, *args, *result; - if (f == NULL) { - PyErr_SetString(PyExc_TypeError, "writeobject with NULL file"); - return -1; - } - writer = PyObject_GetAttrString(f, "write"); - if (writer == NULL) - return -1; - if (flags & Py_PRINT_RAW) { - value = PyObject_Str(v); - } - else - value = PyObject_Repr(v); - if (value == NULL) { - Py_DECREF(writer); - return -1; - } - args = PyTuple_Pack(1, value); - if (args == NULL) { - Py_DECREF(value); - Py_DECREF(writer); - return -1; - } - result = PyEval_CallObject(writer, args); - Py_DECREF(args); - Py_DECREF(value); - Py_DECREF(writer); - if (result == NULL) - return -1; - Py_DECREF(result); - return 0; + PyObject *writer, *value, *args, *result; + if (f == NULL) { + PyErr_SetString(PyExc_TypeError, "writeobject with NULL file"); + return -1; + } + writer = PyObject_GetAttrString(f, "write"); + if (writer == NULL) + return -1; + if (flags & Py_PRINT_RAW) { + value = PyObject_Str(v); + } + else + value = PyObject_Repr(v); + if (value == NULL) { + Py_DECREF(writer); + return -1; + } + args = PyTuple_Pack(1, value); + if (args == NULL) { + Py_DECREF(value); + Py_DECREF(writer); + return -1; + } + result = PyEval_CallObject(writer, args); + Py_DECREF(args); + Py_DECREF(value); + Py_DECREF(writer); + if (result == NULL) + return -1; + Py_DECREF(result); + return 0; } int PyFile_WriteString(const char *s, PyObject *f) { - if (f == NULL) { - /* Should be caused by a pre-existing error */ - if (!PyErr_Occurred()) - PyErr_SetString(PyExc_SystemError, - "null file for PyFile_WriteString"); - return -1; - } - else if (!PyErr_Occurred()) { - PyObject *v = PyUnicode_FromString(s); - int err; - if (v == NULL) - return -1; - err = PyFile_WriteObject(v, f, Py_PRINT_RAW); - Py_DECREF(v); - return err; - } - else - return -1; + if (f == NULL) { + /* Should be caused by a pre-existing error */ + if (!PyErr_Occurred()) + PyErr_SetString(PyExc_SystemError, + "null file for PyFile_WriteString"); + return -1; + } + else if (!PyErr_Occurred()) { + PyObject *v = PyUnicode_FromString(s); + int err; + if (v == NULL) + return -1; + err = PyFile_WriteObject(v, f, Py_PRINT_RAW); + Py_DECREF(v); + return err; + } + else + return -1; } /* Try to get a file-descriptor from a Python object. If the object @@ -204,45 +204,45 @@ int PyObject_AsFileDescriptor(PyObject *o) { - int fd; - PyObject *meth; + int fd; + PyObject *meth; - if (PyLong_Check(o)) { - fd = PyLong_AsLong(o); - } - else if ((meth = PyObject_GetAttrString(o, "fileno")) != NULL) - { - PyObject *fno = PyEval_CallObject(meth, NULL); - Py_DECREF(meth); - if (fno == NULL) - return -1; - - if (PyLong_Check(fno)) { - fd = PyLong_AsLong(fno); - Py_DECREF(fno); - } - else { - PyErr_SetString(PyExc_TypeError, - "fileno() returned a non-integer"); - Py_DECREF(fno); - return -1; - } - } - else { - PyErr_SetString(PyExc_TypeError, - "argument must be an int, or have a fileno() method."); - return -1; - } - - if (fd == -1 && PyErr_Occurred()) - return -1; - if (fd < 0) { - PyErr_Format(PyExc_ValueError, - "file descriptor cannot be a negative integer (%i)", - fd); - return -1; - } - return fd; + if (PyLong_Check(o)) { + fd = PyLong_AsLong(o); + } + else if ((meth = PyObject_GetAttrString(o, "fileno")) != NULL) + { + PyObject *fno = PyEval_CallObject(meth, NULL); + Py_DECREF(meth); + if (fno == NULL) + return -1; + + if (PyLong_Check(fno)) { + fd = PyLong_AsLong(fno); + Py_DECREF(fno); + } + else { + PyErr_SetString(PyExc_TypeError, + "fileno() returned a non-integer"); + Py_DECREF(fno); + return -1; + } + } + else { + PyErr_SetString(PyExc_TypeError, + "argument must be an int, or have a fileno() method."); + return -1; + } + + if (fd == -1 && PyErr_Occurred()) + return -1; + if (fd < 0) { + PyErr_Format(PyExc_ValueError, + "file descriptor cannot be a negative integer (%i)", + fd); + return -1; + } + return fd; } /* @@ -262,68 +262,68 @@ char * Py_UniversalNewlineFgets(char *buf, int n, FILE *stream, PyObject *fobj) { - char *p = buf; - int c; - int newlinetypes = 0; - int skipnextlf = 0; - - if (fobj) { - errno = ENXIO; /* What can you do... */ - return NULL; - } - FLOCKFILE(stream); - c = 'x'; /* Shut up gcc warning */ - while (--n > 0 && (c = GETC(stream)) != EOF ) { - if (skipnextlf ) { - skipnextlf = 0; - if (c == '\n') { - /* Seeing a \n here with skipnextlf true - ** means we saw a \r before. - */ - newlinetypes |= NEWLINE_CRLF; - c = GETC(stream); - if (c == EOF) break; - } else { - /* - ** Note that c == EOF also brings us here, - ** so we're okay if the last char in the file - ** is a CR. - */ - newlinetypes |= NEWLINE_CR; - } - } - if (c == '\r') { - /* A \r is translated into a \n, and we skip - ** an adjacent \n, if any. We don't set the - ** newlinetypes flag until we've seen the next char. - */ - skipnextlf = 1; - c = '\n'; - } else if ( c == '\n') { - newlinetypes |= NEWLINE_LF; - } - *p++ = c; - if (c == '\n') break; - } - if ( c == EOF && skipnextlf ) - newlinetypes |= NEWLINE_CR; - FUNLOCKFILE(stream); - *p = '\0'; - if ( skipnextlf ) { - /* If we have no file object we cannot save the - ** skipnextlf flag. We have to readahead, which - ** will cause a pause if we're reading from an - ** interactive stream, but that is very unlikely - ** unless we're doing something silly like - ** exec(open("/dev/tty").read()). - */ - c = GETC(stream); - if ( c != '\n' ) - ungetc(c, stream); - } - if (p == buf) - return NULL; - return buf; + char *p = buf; + int c; + int newlinetypes = 0; + int skipnextlf = 0; + + if (fobj) { + errno = ENXIO; /* What can you do... */ + return NULL; + } + FLOCKFILE(stream); + c = 'x'; /* Shut up gcc warning */ + while (--n > 0 && (c = GETC(stream)) != EOF ) { + if (skipnextlf ) { + skipnextlf = 0; + if (c == '\n') { + /* Seeing a \n here with skipnextlf true + ** means we saw a \r before. + */ + newlinetypes |= NEWLINE_CRLF; + c = GETC(stream); + if (c == EOF) break; + } else { + /* + ** Note that c == EOF also brings us here, + ** so we're okay if the last char in the file + ** is a CR. + */ + newlinetypes |= NEWLINE_CR; + } + } + if (c == '\r') { + /* A \r is translated into a \n, and we skip + ** an adjacent \n, if any. We don't set the + ** newlinetypes flag until we've seen the next char. + */ + skipnextlf = 1; + c = '\n'; + } else if ( c == '\n') { + newlinetypes |= NEWLINE_LF; + } + *p++ = c; + if (c == '\n') break; + } + if ( c == EOF && skipnextlf ) + newlinetypes |= NEWLINE_CR; + FUNLOCKFILE(stream); + *p = '\0'; + if ( skipnextlf ) { + /* If we have no file object we cannot save the + ** skipnextlf flag. We have to readahead, which + ** will cause a pause if we're reading from an + ** interactive stream, but that is very unlikely + ** unless we're doing something silly like + ** exec(open("/dev/tty").read()). + */ + c = GETC(stream); + if ( c != '\n' ) + ungetc(c, stream); + } + if (p == buf) + return NULL; + return buf; } /* **************************** std printer **************************** @@ -332,195 +332,195 @@ */ typedef struct { - PyObject_HEAD - int fd; + PyObject_HEAD + int fd; } PyStdPrinter_Object; static PyObject * stdprinter_new(PyTypeObject *type, PyObject *args, PyObject *kews) { - PyStdPrinter_Object *self; + PyStdPrinter_Object *self; - assert(type != NULL && type->tp_alloc != NULL); + assert(type != NULL && type->tp_alloc != NULL); - self = (PyStdPrinter_Object *) type->tp_alloc(type, 0); - if (self != NULL) { - self->fd = -1; - } + self = (PyStdPrinter_Object *) type->tp_alloc(type, 0); + if (self != NULL) { + self->fd = -1; + } - return (PyObject *) self; + return (PyObject *) self; } static int fileio_init(PyObject *self, PyObject *args, PyObject *kwds) { - PyErr_SetString(PyExc_TypeError, - "cannot create 'stderrprinter' instances"); - return -1; + PyErr_SetString(PyExc_TypeError, + "cannot create 'stderrprinter' instances"); + return -1; } PyObject * PyFile_NewStdPrinter(int fd) { - PyStdPrinter_Object *self; + PyStdPrinter_Object *self; - if (fd != fileno(stdout) && fd != fileno(stderr)) { - /* not enough infrastructure for PyErr_BadInternalCall() */ - return NULL; - } - - self = PyObject_New(PyStdPrinter_Object, - &PyStdPrinter_Type); - if (self != NULL) { - self->fd = fd; - } - return (PyObject*)self; + if (fd != fileno(stdout) && fd != fileno(stderr)) { + /* not enough infrastructure for PyErr_BadInternalCall() */ + return NULL; + } + + self = PyObject_New(PyStdPrinter_Object, + &PyStdPrinter_Type); + if (self != NULL) { + self->fd = fd; + } + return (PyObject*)self; } static PyObject * stdprinter_write(PyStdPrinter_Object *self, PyObject *args) { - char *c; - Py_ssize_t n; + char *c; + Py_ssize_t n; - if (self->fd < 0) { - /* fd might be invalid on Windows - * I can't raise an exception here. It may lead to an - * unlimited recursion in the case stderr is invalid. - */ - Py_RETURN_NONE; - } - - if (!PyArg_ParseTuple(args, "s", &c)) { - return NULL; - } - n = strlen(c); - - Py_BEGIN_ALLOW_THREADS - errno = 0; - n = write(self->fd, c, n); - Py_END_ALLOW_THREADS - - if (n < 0) { - if (errno == EAGAIN) - Py_RETURN_NONE; - PyErr_SetFromErrno(PyExc_IOError); - return NULL; - } + if (self->fd < 0) { + /* fd might be invalid on Windows + * I can't raise an exception here. It may lead to an + * unlimited recursion in the case stderr is invalid. + */ + Py_RETURN_NONE; + } + + if (!PyArg_ParseTuple(args, "s", &c)) { + return NULL; + } + n = strlen(c); + + Py_BEGIN_ALLOW_THREADS + errno = 0; + n = write(self->fd, c, n); + Py_END_ALLOW_THREADS + + if (n < 0) { + if (errno == EAGAIN) + Py_RETURN_NONE; + PyErr_SetFromErrno(PyExc_IOError); + return NULL; + } - return PyLong_FromSsize_t(n); + return PyLong_FromSsize_t(n); } static PyObject * stdprinter_fileno(PyStdPrinter_Object *self) { - return PyLong_FromLong((long) self->fd); + return PyLong_FromLong((long) self->fd); } static PyObject * stdprinter_repr(PyStdPrinter_Object *self) { - return PyUnicode_FromFormat("", - self->fd, self); + return PyUnicode_FromFormat("", + self->fd, self); } static PyObject * stdprinter_noop(PyStdPrinter_Object *self) { - Py_RETURN_NONE; + Py_RETURN_NONE; } static PyObject * stdprinter_isatty(PyStdPrinter_Object *self) { - long res; - if (self->fd < 0) { - Py_RETURN_FALSE; - } - - Py_BEGIN_ALLOW_THREADS - res = isatty(self->fd); - Py_END_ALLOW_THREADS + long res; + if (self->fd < 0) { + Py_RETURN_FALSE; + } + + Py_BEGIN_ALLOW_THREADS + res = isatty(self->fd); + Py_END_ALLOW_THREADS - return PyBool_FromLong(res); + return PyBool_FromLong(res); } static PyMethodDef stdprinter_methods[] = { - {"close", (PyCFunction)stdprinter_noop, METH_NOARGS, ""}, - {"flush", (PyCFunction)stdprinter_noop, METH_NOARGS, ""}, - {"fileno", (PyCFunction)stdprinter_fileno, METH_NOARGS, ""}, - {"isatty", (PyCFunction)stdprinter_isatty, METH_NOARGS, ""}, - {"write", (PyCFunction)stdprinter_write, METH_VARARGS, ""}, - {NULL, NULL} /*sentinel */ + {"close", (PyCFunction)stdprinter_noop, METH_NOARGS, ""}, + {"flush", (PyCFunction)stdprinter_noop, METH_NOARGS, ""}, + {"fileno", (PyCFunction)stdprinter_fileno, METH_NOARGS, ""}, + {"isatty", (PyCFunction)stdprinter_isatty, METH_NOARGS, ""}, + {"write", (PyCFunction)stdprinter_write, METH_VARARGS, ""}, + {NULL, NULL} /*sentinel */ }; static PyObject * get_closed(PyStdPrinter_Object *self, void *closure) { - Py_INCREF(Py_False); - return Py_False; + Py_INCREF(Py_False); + return Py_False; } static PyObject * get_mode(PyStdPrinter_Object *self, void *closure) { - return PyUnicode_FromString("w"); + return PyUnicode_FromString("w"); } static PyObject * get_encoding(PyStdPrinter_Object *self, void *closure) { - Py_RETURN_NONE; + Py_RETURN_NONE; } static PyGetSetDef stdprinter_getsetlist[] = { - {"closed", (getter)get_closed, NULL, "True if the file is closed"}, - {"encoding", (getter)get_encoding, NULL, "Encoding of the file"}, - {"mode", (getter)get_mode, NULL, "String giving the file mode"}, - {0}, + {"closed", (getter)get_closed, NULL, "True if the file is closed"}, + {"encoding", (getter)get_encoding, NULL, "Encoding of the file"}, + {"mode", (getter)get_mode, NULL, "String giving the file mode"}, + {0}, }; PyTypeObject PyStdPrinter_Type = { - PyVarObject_HEAD_INIT(&PyType_Type, 0) - "stderrprinter", /* tp_name */ - sizeof(PyStdPrinter_Object), /* tp_basicsize */ - 0, /* tp_itemsize */ - /* methods */ - 0, /* tp_dealloc */ - 0, /* tp_print */ - 0, /* tp_getattr */ - 0, /* tp_setattr */ - 0, /* tp_reserved */ - (reprfunc)stdprinter_repr, /* tp_repr */ - 0, /* tp_as_number */ - 0, /* tp_as_sequence */ - 0, /* tp_as_mapping */ - 0, /* tp_hash */ - 0, /* tp_call */ - 0, /* tp_str */ - PyObject_GenericGetAttr, /* tp_getattro */ - 0, /* tp_setattro */ - 0, /* tp_as_buffer */ - Py_TPFLAGS_DEFAULT, /* tp_flags */ - 0, /* tp_doc */ - 0, /* tp_traverse */ - 0, /* tp_clear */ - 0, /* tp_richcompare */ - 0, /* tp_weaklistoffset */ - 0, /* tp_iter */ - 0, /* tp_iternext */ - stdprinter_methods, /* tp_methods */ - 0, /* tp_members */ - stdprinter_getsetlist, /* tp_getset */ - 0, /* tp_base */ - 0, /* tp_dict */ - 0, /* tp_descr_get */ - 0, /* tp_descr_set */ - 0, /* tp_dictoffset */ - fileio_init, /* tp_init */ - PyType_GenericAlloc, /* tp_alloc */ - stdprinter_new, /* tp_new */ - PyObject_Del, /* tp_free */ + PyVarObject_HEAD_INIT(&PyType_Type, 0) + "stderrprinter", /* tp_name */ + sizeof(PyStdPrinter_Object), /* tp_basicsize */ + 0, /* tp_itemsize */ + /* methods */ + 0, /* tp_dealloc */ + 0, /* tp_print */ + 0, /* tp_getattr */ + 0, /* tp_setattr */ + 0, /* tp_reserved */ + (reprfunc)stdprinter_repr, /* tp_repr */ + 0, /* tp_as_number */ + 0, /* tp_as_sequence */ + 0, /* tp_as_mapping */ + 0, /* tp_hash */ + 0, /* tp_call */ + 0, /* tp_str */ + PyObject_GenericGetAttr, /* tp_getattro */ + 0, /* tp_setattro */ + 0, /* tp_as_buffer */ + Py_TPFLAGS_DEFAULT, /* tp_flags */ + 0, /* tp_doc */ + 0, /* tp_traverse */ + 0, /* tp_clear */ + 0, /* tp_richcompare */ + 0, /* tp_weaklistoffset */ + 0, /* tp_iter */ + 0, /* tp_iternext */ + stdprinter_methods, /* tp_methods */ + 0, /* tp_members */ + stdprinter_getsetlist, /* tp_getset */ + 0, /* tp_base */ + 0, /* tp_dict */ + 0, /* tp_descr_get */ + 0, /* tp_descr_set */ + 0, /* tp_dictoffset */ + fileio_init, /* tp_init */ + PyType_GenericAlloc, /* tp_alloc */ + stdprinter_new, /* tp_new */ + PyObject_Del, /* tp_free */ }; Modified: python/branches/release31-maint/Objects/floatobject.c ============================================================================== --- python/branches/release31-maint/Objects/floatobject.c (original) +++ python/branches/release31-maint/Objects/floatobject.c Sun May 9 18:14:21 2010 @@ -26,13 +26,13 @@ #endif /* Special free list -- see comments for same code in intobject.c. */ -#define BLOCK_SIZE 1000 /* 1K less typical malloc overhead */ -#define BHEAD_SIZE 8 /* Enough for a 64-bit pointer */ -#define N_FLOATOBJECTS ((BLOCK_SIZE - BHEAD_SIZE) / sizeof(PyFloatObject)) +#define BLOCK_SIZE 1000 /* 1K less typical malloc overhead */ +#define BHEAD_SIZE 8 /* Enough for a 64-bit pointer */ +#define N_FLOATOBJECTS ((BLOCK_SIZE - BHEAD_SIZE) / sizeof(PyFloatObject)) struct _floatblock { - struct _floatblock *next; - PyFloatObject objects[N_FLOATOBJECTS]; + struct _floatblock *next; + PyFloatObject objects[N_FLOATOBJECTS]; }; typedef struct _floatblock PyFloatBlock; @@ -43,31 +43,31 @@ static PyFloatObject * fill_free_list(void) { - PyFloatObject *p, *q; - /* XXX Float blocks escape the object heap. Use PyObject_MALLOC ??? */ - p = (PyFloatObject *) PyMem_MALLOC(sizeof(PyFloatBlock)); - if (p == NULL) - return (PyFloatObject *) PyErr_NoMemory(); - ((PyFloatBlock *)p)->next = block_list; - block_list = (PyFloatBlock *)p; - p = &((PyFloatBlock *)p)->objects[0]; - q = p + N_FLOATOBJECTS; - while (--q > p) - Py_TYPE(q) = (struct _typeobject *)(q-1); - Py_TYPE(q) = NULL; - return p + N_FLOATOBJECTS - 1; + PyFloatObject *p, *q; + /* XXX Float blocks escape the object heap. Use PyObject_MALLOC ??? */ + p = (PyFloatObject *) PyMem_MALLOC(sizeof(PyFloatBlock)); + if (p == NULL) + return (PyFloatObject *) PyErr_NoMemory(); + ((PyFloatBlock *)p)->next = block_list; + block_list = (PyFloatBlock *)p; + p = &((PyFloatBlock *)p)->objects[0]; + q = p + N_FLOATOBJECTS; + while (--q > p) + Py_TYPE(q) = (struct _typeobject *)(q-1); + Py_TYPE(q) = NULL; + return p + N_FLOATOBJECTS - 1; } double PyFloat_GetMax(void) { - return DBL_MAX; + return DBL_MAX; } double PyFloat_GetMin(void) { - return DBL_MIN; + return DBL_MIN; } static PyTypeObject FloatInfoType; @@ -80,183 +80,183 @@ your system's :file:`float.h` for more information."); static PyStructSequence_Field floatinfo_fields[] = { - {"max", "DBL_MAX -- maximum representable finite float"}, - {"max_exp", "DBL_MAX_EXP -- maximum int e such that radix**(e-1) " - "is representable"}, - {"max_10_exp", "DBL_MAX_10_EXP -- maximum int e such that 10**e " - "is representable"}, - {"min", "DBL_MIN -- Minimum positive normalizer float"}, - {"min_exp", "DBL_MIN_EXP -- minimum int e such that radix**(e-1) " - "is a normalized float"}, - {"min_10_exp", "DBL_MIN_10_EXP -- minimum int e such that 10**e is " - "a normalized"}, - {"dig", "DBL_DIG -- digits"}, - {"mant_dig", "DBL_MANT_DIG -- mantissa digits"}, - {"epsilon", "DBL_EPSILON -- Difference between 1 and the next " - "representable float"}, - {"radix", "FLT_RADIX -- radix of exponent"}, - {"rounds", "FLT_ROUNDS -- addition rounds"}, - {0} + {"max", "DBL_MAX -- maximum representable finite float"}, + {"max_exp", "DBL_MAX_EXP -- maximum int e such that radix**(e-1) " + "is representable"}, + {"max_10_exp", "DBL_MAX_10_EXP -- maximum int e such that 10**e " + "is representable"}, + {"min", "DBL_MIN -- Minimum positive normalizer float"}, + {"min_exp", "DBL_MIN_EXP -- minimum int e such that radix**(e-1) " + "is a normalized float"}, + {"min_10_exp", "DBL_MIN_10_EXP -- minimum int e such that 10**e is " + "a normalized"}, + {"dig", "DBL_DIG -- digits"}, + {"mant_dig", "DBL_MANT_DIG -- mantissa digits"}, + {"epsilon", "DBL_EPSILON -- Difference between 1 and the next " + "representable float"}, + {"radix", "FLT_RADIX -- radix of exponent"}, + {"rounds", "FLT_ROUNDS -- addition rounds"}, + {0} }; static PyStructSequence_Desc floatinfo_desc = { - "sys.floatinfo", /* name */ - floatinfo__doc__, /* doc */ - floatinfo_fields, /* fields */ - 11 + "sys.floatinfo", /* name */ + floatinfo__doc__, /* doc */ + floatinfo_fields, /* fields */ + 11 }; PyObject * PyFloat_GetInfo(void) { - PyObject* floatinfo; - int pos = 0; + PyObject* floatinfo; + int pos = 0; - floatinfo = PyStructSequence_New(&FloatInfoType); - if (floatinfo == NULL) { - return NULL; - } + floatinfo = PyStructSequence_New(&FloatInfoType); + if (floatinfo == NULL) { + return NULL; + } #define SetIntFlag(flag) \ - PyStructSequence_SET_ITEM(floatinfo, pos++, PyLong_FromLong(flag)) + PyStructSequence_SET_ITEM(floatinfo, pos++, PyLong_FromLong(flag)) #define SetDblFlag(flag) \ - PyStructSequence_SET_ITEM(floatinfo, pos++, PyFloat_FromDouble(flag)) + PyStructSequence_SET_ITEM(floatinfo, pos++, PyFloat_FromDouble(flag)) - SetDblFlag(DBL_MAX); - SetIntFlag(DBL_MAX_EXP); - SetIntFlag(DBL_MAX_10_EXP); - SetDblFlag(DBL_MIN); - SetIntFlag(DBL_MIN_EXP); - SetIntFlag(DBL_MIN_10_EXP); - SetIntFlag(DBL_DIG); - SetIntFlag(DBL_MANT_DIG); - SetDblFlag(DBL_EPSILON); - SetIntFlag(FLT_RADIX); - SetIntFlag(FLT_ROUNDS); + SetDblFlag(DBL_MAX); + SetIntFlag(DBL_MAX_EXP); + SetIntFlag(DBL_MAX_10_EXP); + SetDblFlag(DBL_MIN); + SetIntFlag(DBL_MIN_EXP); + SetIntFlag(DBL_MIN_10_EXP); + SetIntFlag(DBL_DIG); + SetIntFlag(DBL_MANT_DIG); + SetDblFlag(DBL_EPSILON); + SetIntFlag(FLT_RADIX); + SetIntFlag(FLT_ROUNDS); #undef SetIntFlag #undef SetDblFlag - - if (PyErr_Occurred()) { - Py_CLEAR(floatinfo); - return NULL; - } - return floatinfo; + + if (PyErr_Occurred()) { + Py_CLEAR(floatinfo); + return NULL; + } + return floatinfo; } PyObject * PyFloat_FromDouble(double fval) { - register PyFloatObject *op; - if (free_list == NULL) { - if ((free_list = fill_free_list()) == NULL) - return NULL; - } - /* Inline PyObject_New */ - op = free_list; - free_list = (PyFloatObject *)Py_TYPE(op); - PyObject_INIT(op, &PyFloat_Type); - op->ob_fval = fval; - return (PyObject *) op; + register PyFloatObject *op; + if (free_list == NULL) { + if ((free_list = fill_free_list()) == NULL) + return NULL; + } + /* Inline PyObject_New */ + op = free_list; + free_list = (PyFloatObject *)Py_TYPE(op); + PyObject_INIT(op, &PyFloat_Type); + op->ob_fval = fval; + return (PyObject *) op; } PyObject * PyFloat_FromString(PyObject *v) { - const char *s, *last, *end; - double x; - char buffer[256]; /* for errors */ - char *s_buffer = NULL; - Py_ssize_t len; - PyObject *result = NULL; - - if (PyUnicode_Check(v)) { - s_buffer = (char *)PyMem_MALLOC(PyUnicode_GET_SIZE(v)+1); - if (s_buffer == NULL) - return PyErr_NoMemory(); - if (PyUnicode_EncodeDecimal(PyUnicode_AS_UNICODE(v), - PyUnicode_GET_SIZE(v), - s_buffer, - NULL)) - goto error; - s = s_buffer; - len = strlen(s); - } - else if (PyObject_AsCharBuffer(v, &s, &len)) { - PyErr_SetString(PyExc_TypeError, - "float() argument must be a string or a number"); - return NULL; - } - last = s + len; - - while (Py_ISSPACE(*s)) - s++; - /* We don't care about overflow or underflow. If the platform - * supports them, infinities and signed zeroes (on underflow) are - * fine. */ - x = PyOS_string_to_double(s, (char **)&end, NULL); - if (x == -1.0 && PyErr_Occurred()) - goto error; - while (Py_ISSPACE(*end)) - end++; - if (end == last) - result = PyFloat_FromDouble(x); - else { - PyOS_snprintf(buffer, sizeof(buffer), - "invalid literal for float(): %.200s", s); - PyErr_SetString(PyExc_ValueError, buffer); - result = NULL; - } + const char *s, *last, *end; + double x; + char buffer[256]; /* for errors */ + char *s_buffer = NULL; + Py_ssize_t len; + PyObject *result = NULL; + + if (PyUnicode_Check(v)) { + s_buffer = (char *)PyMem_MALLOC(PyUnicode_GET_SIZE(v)+1); + if (s_buffer == NULL) + return PyErr_NoMemory(); + if (PyUnicode_EncodeDecimal(PyUnicode_AS_UNICODE(v), + PyUnicode_GET_SIZE(v), + s_buffer, + NULL)) + goto error; + s = s_buffer; + len = strlen(s); + } + else if (PyObject_AsCharBuffer(v, &s, &len)) { + PyErr_SetString(PyExc_TypeError, + "float() argument must be a string or a number"); + return NULL; + } + last = s + len; + + while (Py_ISSPACE(*s)) + s++; + /* We don't care about overflow or underflow. If the platform + * supports them, infinities and signed zeroes (on underflow) are + * fine. */ + x = PyOS_string_to_double(s, (char **)&end, NULL); + if (x == -1.0 && PyErr_Occurred()) + goto error; + while (Py_ISSPACE(*end)) + end++; + if (end == last) + result = PyFloat_FromDouble(x); + else { + PyOS_snprintf(buffer, sizeof(buffer), + "invalid literal for float(): %.200s", s); + PyErr_SetString(PyExc_ValueError, buffer); + result = NULL; + } error: - if (s_buffer) - PyMem_FREE(s_buffer); - return result; + if (s_buffer) + PyMem_FREE(s_buffer); + return result; } static void float_dealloc(PyFloatObject *op) { - if (PyFloat_CheckExact(op)) { - Py_TYPE(op) = (struct _typeobject *)free_list; - free_list = op; - } - else - Py_TYPE(op)->tp_free((PyObject *)op); + if (PyFloat_CheckExact(op)) { + Py_TYPE(op) = (struct _typeobject *)free_list; + free_list = op; + } + else + Py_TYPE(op)->tp_free((PyObject *)op); } double PyFloat_AsDouble(PyObject *op) { - PyNumberMethods *nb; - PyFloatObject *fo; - double val; - - if (op && PyFloat_Check(op)) - return PyFloat_AS_DOUBLE((PyFloatObject*) op); - - if (op == NULL) { - PyErr_BadArgument(); - return -1; - } - - if ((nb = Py_TYPE(op)->tp_as_number) == NULL || nb->nb_float == NULL) { - PyErr_SetString(PyExc_TypeError, "a float is required"); - return -1; - } - - fo = (PyFloatObject*) (*nb->nb_float) (op); - if (fo == NULL) - return -1; - if (!PyFloat_Check(fo)) { - PyErr_SetString(PyExc_TypeError, - "nb_float should return float object"); - return -1; - } + PyNumberMethods *nb; + PyFloatObject *fo; + double val; + + if (op && PyFloat_Check(op)) + return PyFloat_AS_DOUBLE((PyFloatObject*) op); + + if (op == NULL) { + PyErr_BadArgument(); + return -1; + } + + if ((nb = Py_TYPE(op)->tp_as_number) == NULL || nb->nb_float == NULL) { + PyErr_SetString(PyExc_TypeError, "a float is required"); + return -1; + } + + fo = (PyFloatObject*) (*nb->nb_float) (op); + if (fo == NULL) + return -1; + if (!PyFloat_Check(fo)) { + PyErr_SetString(PyExc_TypeError, + "nb_float should return float object"); + return -1; + } - val = PyFloat_AS_DOUBLE(fo); - Py_DECREF(fo); + val = PyFloat_AS_DOUBLE(fo); + Py_DECREF(fo); - return val; + return val; } /* Macro and helper that convert PyObject obj to a C double and store @@ -265,32 +265,32 @@ obj is not of float, int or long type, Py_NotImplemented is incref'ed, stored in obj, and returned from the function invoking this macro. */ -#define CONVERT_TO_DOUBLE(obj, dbl) \ - if (PyFloat_Check(obj)) \ - dbl = PyFloat_AS_DOUBLE(obj); \ - else if (convert_to_double(&(obj), &(dbl)) < 0) \ - return obj; +#define CONVERT_TO_DOUBLE(obj, dbl) \ + if (PyFloat_Check(obj)) \ + dbl = PyFloat_AS_DOUBLE(obj); \ + else if (convert_to_double(&(obj), &(dbl)) < 0) \ + return obj; /* Methods */ static int convert_to_double(PyObject **v, double *dbl) { - register PyObject *obj = *v; + register PyObject *obj = *v; - if (PyLong_Check(obj)) { - *dbl = PyLong_AsDouble(obj); - if (*dbl == -1.0 && PyErr_Occurred()) { - *v = NULL; - return -1; - } - } - else { - Py_INCREF(Py_NotImplemented); - *v = Py_NotImplemented; - return -1; - } - return 0; + if (PyLong_Check(obj)) { + *dbl = PyLong_AsDouble(obj); + if (*dbl == -1.0 && PyErr_Occurred()) { + *v = NULL; + return -1; + } + } + else { + Py_INCREF(Py_NotImplemented); + *v = Py_NotImplemented; + return -1; + } + return 0; } static PyObject * @@ -302,7 +302,7 @@ Py_DTSF_ADD_DOT_0, NULL); if (!buf) - return PyErr_NoMemory(); + return PyErr_NoMemory(); result = PyUnicode_FromString(buf); PyMem_Free(buf); return result; @@ -338,514 +338,514 @@ static PyObject* float_richcompare(PyObject *v, PyObject *w, int op) { - double i, j; - int r = 0; + double i, j; + int r = 0; - assert(PyFloat_Check(v)); - i = PyFloat_AS_DOUBLE(v); + assert(PyFloat_Check(v)); + i = PyFloat_AS_DOUBLE(v); - /* Switch on the type of w. Set i and j to doubles to be compared, - * and op to the richcomp to use. - */ - if (PyFloat_Check(w)) - j = PyFloat_AS_DOUBLE(w); - - else if (!Py_IS_FINITE(i)) { - if (PyLong_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. - */ - j = 0.0; - else - goto Unimplemented; - } - - else if (PyLong_Check(w)) { - int vsign = i == 0.0 ? 0 : i < 0.0 ? -1 : 1; - int wsign = _PyLong_Sign(w); - size_t nbits; - int exponent; - - if (vsign != wsign) { - /* Magnitudes are irrelevant -- the signs alone - * determine the outcome. - */ - i = (double)vsign; - j = (double)wsign; - goto Compare; - } - /* The signs are the same. */ - /* Convert w to a double if it fits. In particular, 0 fits. */ - nbits = _PyLong_NumBits(w); - if (nbits == (size_t)-1 && PyErr_Occurred()) { - /* This long is so large that size_t isn't big enough - * to hold the # of bits. Replace with little doubles - * that give the same outcome -- w is so large that - * its magnitude must exceed the magnitude of any - * finite float. - */ - PyErr_Clear(); - i = (double)vsign; - assert(wsign != 0); - j = wsign * 2.0; - goto Compare; - } - if (nbits <= 48) { - j = PyLong_AsDouble(w); - /* It's impossible that <= 48 bits overflowed. */ - assert(j != -1.0 || ! PyErr_Occurred()); - goto Compare; - } - assert(wsign != 0); /* else nbits was 0 */ - assert(vsign != 0); /* if vsign were 0, then since wsign is - * not 0, we would have taken the - * vsign != wsign branch at the start */ - /* We want to work with non-negative numbers. */ - if (vsign < 0) { - /* "Multiply both sides" by -1; this also swaps the - * comparator. - */ - i = -i; - op = _Py_SwappedOp[op]; - } - assert(i > 0.0); - (void) frexp(i, &exponent); - /* exponent is the # of bits in v before the radix point; - * we know that nbits (the # of bits in w) > 48 at this point - */ - if (exponent < 0 || (size_t)exponent < nbits) { - i = 1.0; - j = 2.0; - goto Compare; - } - if ((size_t)exponent > nbits) { - i = 2.0; - j = 1.0; - goto Compare; - } - /* v and w have the same number of bits before the radix - * point. Construct two longs that have the same comparison - * outcome. - */ - { - double fracpart; - double intpart; - PyObject *result = NULL; - PyObject *one = NULL; - PyObject *vv = NULL; - PyObject *ww = w; - - if (wsign < 0) { - ww = PyNumber_Negative(w); - if (ww == NULL) - goto Error; - } - else - Py_INCREF(ww); - - fracpart = modf(i, &intpart); - vv = PyLong_FromDouble(intpart); - if (vv == NULL) - goto Error; - - if (fracpart != 0.0) { - /* Shift left, and or a 1 bit into vv - * to represent the lost fraction. - */ - PyObject *temp; - - one = PyLong_FromLong(1); - if (one == NULL) - goto Error; - - temp = PyNumber_Lshift(ww, one); - if (temp == NULL) - goto Error; - Py_DECREF(ww); - ww = temp; - - temp = PyNumber_Lshift(vv, one); - if (temp == NULL) - goto Error; - Py_DECREF(vv); - vv = temp; - - temp = PyNumber_Or(vv, one); - if (temp == NULL) - goto Error; - Py_DECREF(vv); - vv = temp; - } - - r = PyObject_RichCompareBool(vv, ww, op); - if (r < 0) - goto Error; - result = PyBool_FromLong(r); - Error: - Py_XDECREF(vv); - Py_XDECREF(ww); - Py_XDECREF(one); - return result; - } - } /* else if (PyLong_Check(w)) */ + /* Switch on the type of w. Set i and j to doubles to be compared, + * and op to the richcomp to use. + */ + if (PyFloat_Check(w)) + j = PyFloat_AS_DOUBLE(w); + + else if (!Py_IS_FINITE(i)) { + if (PyLong_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. + */ + j = 0.0; + else + goto Unimplemented; + } + + else if (PyLong_Check(w)) { + int vsign = i == 0.0 ? 0 : i < 0.0 ? -1 : 1; + int wsign = _PyLong_Sign(w); + size_t nbits; + int exponent; + + if (vsign != wsign) { + /* Magnitudes are irrelevant -- the signs alone + * determine the outcome. + */ + i = (double)vsign; + j = (double)wsign; + goto Compare; + } + /* The signs are the same. */ + /* Convert w to a double if it fits. In particular, 0 fits. */ + nbits = _PyLong_NumBits(w); + if (nbits == (size_t)-1 && PyErr_Occurred()) { + /* This long is so large that size_t isn't big enough + * to hold the # of bits. Replace with little doubles + * that give the same outcome -- w is so large that + * its magnitude must exceed the magnitude of any + * finite float. + */ + PyErr_Clear(); + i = (double)vsign; + assert(wsign != 0); + j = wsign * 2.0; + goto Compare; + } + if (nbits <= 48) { + j = PyLong_AsDouble(w); + /* It's impossible that <= 48 bits overflowed. */ + assert(j != -1.0 || ! PyErr_Occurred()); + goto Compare; + } + assert(wsign != 0); /* else nbits was 0 */ + assert(vsign != 0); /* if vsign were 0, then since wsign is + * not 0, we would have taken the + * vsign != wsign branch at the start */ + /* We want to work with non-negative numbers. */ + if (vsign < 0) { + /* "Multiply both sides" by -1; this also swaps the + * comparator. + */ + i = -i; + op = _Py_SwappedOp[op]; + } + assert(i > 0.0); + (void) frexp(i, &exponent); + /* exponent is the # of bits in v before the radix point; + * we know that nbits (the # of bits in w) > 48 at this point + */ + if (exponent < 0 || (size_t)exponent < nbits) { + i = 1.0; + j = 2.0; + goto Compare; + } + if ((size_t)exponent > nbits) { + i = 2.0; + j = 1.0; + goto Compare; + } + /* v and w have the same number of bits before the radix + * point. Construct two longs that have the same comparison + * outcome. + */ + { + double fracpart; + double intpart; + PyObject *result = NULL; + PyObject *one = NULL; + PyObject *vv = NULL; + PyObject *ww = w; + + if (wsign < 0) { + ww = PyNumber_Negative(w); + if (ww == NULL) + goto Error; + } + else + Py_INCREF(ww); + + fracpart = modf(i, &intpart); + vv = PyLong_FromDouble(intpart); + if (vv == NULL) + goto Error; + + if (fracpart != 0.0) { + /* Shift left, and or a 1 bit into vv + * to represent the lost fraction. + */ + PyObject *temp; + + one = PyLong_FromLong(1); + if (one == NULL) + goto Error; + + temp = PyNumber_Lshift(ww, one); + if (temp == NULL) + goto Error; + Py_DECREF(ww); + ww = temp; + + temp = PyNumber_Lshift(vv, one); + if (temp == NULL) + goto Error; + Py_DECREF(vv); + vv = temp; + + temp = PyNumber_Or(vv, one); + if (temp == NULL) + goto Error; + Py_DECREF(vv); + vv = temp; + } + + r = PyObject_RichCompareBool(vv, ww, op); + if (r < 0) + goto Error; + result = PyBool_FromLong(r); + Error: + Py_XDECREF(vv); + Py_XDECREF(ww); + Py_XDECREF(one); + return result; + } + } /* else if (PyLong_Check(w)) */ - else /* w isn't float, int, or long */ - goto Unimplemented; + else /* w isn't float, int, or long */ + goto Unimplemented; Compare: - PyFPE_START_PROTECT("richcompare", return NULL) - switch (op) { - case Py_EQ: - r = i == j; - break; - case Py_NE: - r = i != j; - break; - case Py_LE: - r = i <= j; - break; - case Py_GE: - r = i >= j; - break; - case Py_LT: - r = i < j; - break; - case Py_GT: - r = i > j; - break; - } - PyFPE_END_PROTECT(r) - return PyBool_FromLong(r); + PyFPE_START_PROTECT("richcompare", return NULL) + switch (op) { + case Py_EQ: + r = i == j; + break; + case Py_NE: + r = i != j; + break; + case Py_LE: + r = i <= j; + break; + case Py_GE: + r = i >= j; + break; + case Py_LT: + r = i < j; + break; + case Py_GT: + r = i > j; + break; + } + PyFPE_END_PROTECT(r) + return PyBool_FromLong(r); Unimplemented: - Py_INCREF(Py_NotImplemented); - return Py_NotImplemented; + Py_INCREF(Py_NotImplemented); + return Py_NotImplemented; } static long float_hash(PyFloatObject *v) { - return _Py_HashDouble(v->ob_fval); + return _Py_HashDouble(v->ob_fval); } static PyObject * float_add(PyObject *v, PyObject *w) { - double a,b; - CONVERT_TO_DOUBLE(v, a); - CONVERT_TO_DOUBLE(w, b); - PyFPE_START_PROTECT("add", return 0) - a = a + b; - PyFPE_END_PROTECT(a) - return PyFloat_FromDouble(a); + double a,b; + CONVERT_TO_DOUBLE(v, a); + CONVERT_TO_DOUBLE(w, b); + PyFPE_START_PROTECT("add", return 0) + a = a + b; + PyFPE_END_PROTECT(a) + return PyFloat_FromDouble(a); } static PyObject * float_sub(PyObject *v, PyObject *w) { - double a,b; - CONVERT_TO_DOUBLE(v, a); - CONVERT_TO_DOUBLE(w, b); - PyFPE_START_PROTECT("subtract", return 0) - a = a - b; - PyFPE_END_PROTECT(a) - return PyFloat_FromDouble(a); + double a,b; + CONVERT_TO_DOUBLE(v, a); + CONVERT_TO_DOUBLE(w, b); + PyFPE_START_PROTECT("subtract", return 0) + a = a - b; + PyFPE_END_PROTECT(a) + return PyFloat_FromDouble(a); } static PyObject * float_mul(PyObject *v, PyObject *w) { - double a,b; - CONVERT_TO_DOUBLE(v, a); - CONVERT_TO_DOUBLE(w, b); - PyFPE_START_PROTECT("multiply", return 0) - a = a * b; - PyFPE_END_PROTECT(a) - return PyFloat_FromDouble(a); + double a,b; + CONVERT_TO_DOUBLE(v, a); + CONVERT_TO_DOUBLE(w, b); + PyFPE_START_PROTECT("multiply", return 0) + a = a * b; + PyFPE_END_PROTECT(a) + return PyFloat_FromDouble(a); } static PyObject * float_div(PyObject *v, PyObject *w) { - double a,b; - CONVERT_TO_DOUBLE(v, a); - CONVERT_TO_DOUBLE(w, b); + double a,b; + CONVERT_TO_DOUBLE(v, a); + CONVERT_TO_DOUBLE(w, b); #ifdef Py_NAN - if (b == 0.0) { - PyErr_SetString(PyExc_ZeroDivisionError, - "float division"); - return NULL; - } + if (b == 0.0) { + PyErr_SetString(PyExc_ZeroDivisionError, + "float division"); + return NULL; + } #endif - PyFPE_START_PROTECT("divide", return 0) - a = a / b; - PyFPE_END_PROTECT(a) - return PyFloat_FromDouble(a); + PyFPE_START_PROTECT("divide", return 0) + a = a / b; + PyFPE_END_PROTECT(a) + return PyFloat_FromDouble(a); } static PyObject * float_rem(PyObject *v, PyObject *w) { - double vx, wx; - double mod; - CONVERT_TO_DOUBLE(v, vx); - CONVERT_TO_DOUBLE(w, wx); + double vx, wx; + double mod; + CONVERT_TO_DOUBLE(v, vx); + CONVERT_TO_DOUBLE(w, wx); #ifdef Py_NAN - if (wx == 0.0) { - PyErr_SetString(PyExc_ZeroDivisionError, - "float modulo"); - return NULL; - } + if (wx == 0.0) { + PyErr_SetString(PyExc_ZeroDivisionError, + "float modulo"); + return NULL; + } #endif - PyFPE_START_PROTECT("modulo", return 0) - mod = fmod(vx, wx); - /* note: checking mod*wx < 0 is incorrect -- underflows to - 0 if wx < sqrt(smallest nonzero double) */ - if (mod && ((wx < 0) != (mod < 0))) { - mod += wx; - } - PyFPE_END_PROTECT(mod) - return PyFloat_FromDouble(mod); + PyFPE_START_PROTECT("modulo", return 0) + mod = fmod(vx, wx); + /* note: checking mod*wx < 0 is incorrect -- underflows to + 0 if wx < sqrt(smallest nonzero double) */ + if (mod && ((wx < 0) != (mod < 0))) { + mod += wx; + } + PyFPE_END_PROTECT(mod) + return PyFloat_FromDouble(mod); } static PyObject * float_divmod(PyObject *v, PyObject *w) { - double vx, wx; - double div, mod, floordiv; - CONVERT_TO_DOUBLE(v, vx); - CONVERT_TO_DOUBLE(w, wx); - if (wx == 0.0) { - PyErr_SetString(PyExc_ZeroDivisionError, "float divmod()"); - return NULL; - } - PyFPE_START_PROTECT("divmod", return 0) - mod = fmod(vx, wx); - /* fmod is typically exact, so vx-mod is *mathematically* an - exact multiple of wx. But this is fp arithmetic, and fp - vx - mod is an approximation; the result is that div may - not be an exact integral value after the division, although - it will always be very close to one. - */ - div = (vx - mod) / wx; - if (mod) { - /* ensure the remainder has the same sign as the denominator */ - if ((wx < 0) != (mod < 0)) { - mod += wx; - div -= 1.0; - } - } - else { - /* the remainder is zero, and in the presence of signed zeroes - fmod returns different results across platforms; ensure - it has the same sign as the denominator; we'd like to do - "mod = wx * 0.0", but that may get optimized away */ - mod *= mod; /* hide "mod = +0" from optimizer */ - if (wx < 0.0) - mod = -mod; - } - /* snap quotient to nearest integral value */ - if (div) { - floordiv = floor(div); - if (div - floordiv > 0.5) - floordiv += 1.0; - } - else { - /* div is zero - get the same sign as the true quotient */ - div *= div; /* hide "div = +0" from optimizers */ - floordiv = div * vx / wx; /* zero w/ sign of vx/wx */ - } - PyFPE_END_PROTECT(floordiv) - return Py_BuildValue("(dd)", floordiv, mod); + double vx, wx; + double div, mod, floordiv; + CONVERT_TO_DOUBLE(v, vx); + CONVERT_TO_DOUBLE(w, wx); + if (wx == 0.0) { + PyErr_SetString(PyExc_ZeroDivisionError, "float divmod()"); + return NULL; + } + PyFPE_START_PROTECT("divmod", return 0) + mod = fmod(vx, wx); + /* fmod is typically exact, so vx-mod is *mathematically* an + exact multiple of wx. But this is fp arithmetic, and fp + vx - mod is an approximation; the result is that div may + not be an exact integral value after the division, although + it will always be very close to one. + */ + div = (vx - mod) / wx; + if (mod) { + /* ensure the remainder has the same sign as the denominator */ + if ((wx < 0) != (mod < 0)) { + mod += wx; + div -= 1.0; + } + } + else { + /* the remainder is zero, and in the presence of signed zeroes + fmod returns different results across platforms; ensure + it has the same sign as the denominator; we'd like to do + "mod = wx * 0.0", but that may get optimized away */ + mod *= mod; /* hide "mod = +0" from optimizer */ + if (wx < 0.0) + mod = -mod; + } + /* snap quotient to nearest integral value */ + if (div) { + floordiv = floor(div); + if (div - floordiv > 0.5) + floordiv += 1.0; + } + else { + /* div is zero - get the same sign as the true quotient */ + div *= div; /* hide "div = +0" from optimizers */ + floordiv = div * vx / wx; /* zero w/ sign of vx/wx */ + } + PyFPE_END_PROTECT(floordiv) + return Py_BuildValue("(dd)", floordiv, mod); } static PyObject * float_floor_div(PyObject *v, PyObject *w) { - PyObject *t, *r; + PyObject *t, *r; - t = float_divmod(v, w); - if (t == NULL || t == Py_NotImplemented) - return t; - assert(PyTuple_CheckExact(t)); - r = PyTuple_GET_ITEM(t, 0); - Py_INCREF(r); - Py_DECREF(t); - return r; + t = float_divmod(v, w); + if (t == NULL || t == Py_NotImplemented) + return t; + assert(PyTuple_CheckExact(t)); + r = PyTuple_GET_ITEM(t, 0); + Py_INCREF(r); + Py_DECREF(t); + return r; } static PyObject * float_pow(PyObject *v, PyObject *w, PyObject *z) { - double iv, iw, ix; + double iv, iw, ix; - if ((PyObject *)z != Py_None) { - PyErr_SetString(PyExc_TypeError, "pow() 3rd argument not " - "allowed unless all arguments are integers"); - return NULL; - } - - CONVERT_TO_DOUBLE(v, iv); - CONVERT_TO_DOUBLE(w, iw); - - /* Sort out special cases here instead of relying on pow() */ - if (iw == 0) { /* v**0 is 1, even 0**0 */ - return PyFloat_FromDouble(1.0); - } - if (iv == 0.0) { /* 0**w is error if w<0, else 1 */ - if (iw < 0.0) { - PyErr_SetString(PyExc_ZeroDivisionError, - "0.0 cannot be raised to a negative power"); - return NULL; - } - return PyFloat_FromDouble(0.0); - } - if (iv == 1.0) { /* 1**w is 1, even 1**inf and 1**nan */ - return PyFloat_FromDouble(1.0); - } - if (iv < 0.0) { - /* Whether this is an error is a mess, and bumps into libm - * bugs so we have to figure it out ourselves. - */ - if (iw != floor(iw)) { - /* Negative numbers raised to fractional powers - * become complex. - */ - return PyComplex_Type.tp_as_number->nb_power(v, w, z); - } - /* iw is an exact integer, albeit perhaps a very large one. - * -1 raised to an exact integer should never be exceptional. - * Alas, some libms (chiefly glibc as of early 2003) return - * NaN and set EDOM on pow(-1, large_int) if the int doesn't - * happen to be representable in a *C* integer. That's a - * bug; we let that slide in math.pow() (which currently - * reflects all platform accidents), but not for Python's **. - */ - if (iv == -1.0 && Py_IS_FINITE(iw)) { - /* Return 1 if iw is even, -1 if iw is odd; there's - * no guarantee that any C integral type is big - * enough to hold iw, so we have to check this - * indirectly. - */ - ix = floor(iw * 0.5) * 2.0; - return PyFloat_FromDouble(ix == iw ? 1.0 : -1.0); - } - /* Else iv != -1.0, and overflow or underflow are possible. - * Unless we're to write pow() ourselves, we have to trust - * the platform to do this correctly. - */ - } - errno = 0; - PyFPE_START_PROTECT("pow", return NULL) - ix = pow(iv, iw); - PyFPE_END_PROTECT(ix) - Py_ADJUST_ERANGE1(ix); - if (errno != 0) { - /* We don't expect any errno value other than ERANGE, but - * the range of libm bugs appears unbounded. - */ - PyErr_SetFromErrno(errno == ERANGE ? PyExc_OverflowError : - PyExc_ValueError); - return NULL; - } - return PyFloat_FromDouble(ix); + if ((PyObject *)z != Py_None) { + PyErr_SetString(PyExc_TypeError, "pow() 3rd argument not " + "allowed unless all arguments are integers"); + return NULL; + } + + CONVERT_TO_DOUBLE(v, iv); + CONVERT_TO_DOUBLE(w, iw); + + /* Sort out special cases here instead of relying on pow() */ + if (iw == 0) { /* v**0 is 1, even 0**0 */ + return PyFloat_FromDouble(1.0); + } + if (iv == 0.0) { /* 0**w is error if w<0, else 1 */ + if (iw < 0.0) { + PyErr_SetString(PyExc_ZeroDivisionError, + "0.0 cannot be raised to a negative power"); + return NULL; + } + return PyFloat_FromDouble(0.0); + } + if (iv == 1.0) { /* 1**w is 1, even 1**inf and 1**nan */ + return PyFloat_FromDouble(1.0); + } + if (iv < 0.0) { + /* Whether this is an error is a mess, and bumps into libm + * bugs so we have to figure it out ourselves. + */ + if (iw != floor(iw)) { + /* Negative numbers raised to fractional powers + * become complex. + */ + return PyComplex_Type.tp_as_number->nb_power(v, w, z); + } + /* iw is an exact integer, albeit perhaps a very large one. + * -1 raised to an exact integer should never be exceptional. + * Alas, some libms (chiefly glibc as of early 2003) return + * NaN and set EDOM on pow(-1, large_int) if the int doesn't + * happen to be representable in a *C* integer. That's a + * bug; we let that slide in math.pow() (which currently + * reflects all platform accidents), but not for Python's **. + */ + if (iv == -1.0 && Py_IS_FINITE(iw)) { + /* Return 1 if iw is even, -1 if iw is odd; there's + * no guarantee that any C integral type is big + * enough to hold iw, so we have to check this + * indirectly. + */ + ix = floor(iw * 0.5) * 2.0; + return PyFloat_FromDouble(ix == iw ? 1.0 : -1.0); + } + /* Else iv != -1.0, and overflow or underflow are possible. + * Unless we're to write pow() ourselves, we have to trust + * the platform to do this correctly. + */ + } + errno = 0; + PyFPE_START_PROTECT("pow", return NULL) + ix = pow(iv, iw); + PyFPE_END_PROTECT(ix) + Py_ADJUST_ERANGE1(ix); + if (errno != 0) { + /* We don't expect any errno value other than ERANGE, but + * the range of libm bugs appears unbounded. + */ + PyErr_SetFromErrno(errno == ERANGE ? PyExc_OverflowError : + PyExc_ValueError); + return NULL; + } + return PyFloat_FromDouble(ix); } static PyObject * float_neg(PyFloatObject *v) { - return PyFloat_FromDouble(-v->ob_fval); + return PyFloat_FromDouble(-v->ob_fval); } static PyObject * float_abs(PyFloatObject *v) { - return PyFloat_FromDouble(fabs(v->ob_fval)); + return PyFloat_FromDouble(fabs(v->ob_fval)); } static int float_bool(PyFloatObject *v) { - return v->ob_fval != 0.0; + return v->ob_fval != 0.0; } static PyObject * float_is_integer(PyObject *v) { - double x = PyFloat_AsDouble(v); - PyObject *o; - - if (x == -1.0 && PyErr_Occurred()) - return NULL; - if (!Py_IS_FINITE(x)) - Py_RETURN_FALSE; - errno = 0; - PyFPE_START_PROTECT("is_integer", return NULL) - o = (floor(x) == x) ? Py_True : Py_False; - PyFPE_END_PROTECT(x) - if (errno != 0) { - PyErr_SetFromErrno(errno == ERANGE ? PyExc_OverflowError : - PyExc_ValueError); - return NULL; - } - Py_INCREF(o); - return o; + double x = PyFloat_AsDouble(v); + PyObject *o; + + if (x == -1.0 && PyErr_Occurred()) + return NULL; + if (!Py_IS_FINITE(x)) + Py_RETURN_FALSE; + errno = 0; + PyFPE_START_PROTECT("is_integer", return NULL) + o = (floor(x) == x) ? Py_True : Py_False; + PyFPE_END_PROTECT(x) + if (errno != 0) { + PyErr_SetFromErrno(errno == ERANGE ? PyExc_OverflowError : + PyExc_ValueError); + return NULL; + } + Py_INCREF(o); + return o; } #if 0 static PyObject * float_is_inf(PyObject *v) { - double x = PyFloat_AsDouble(v); - if (x == -1.0 && PyErr_Occurred()) - return NULL; - return PyBool_FromLong((long)Py_IS_INFINITY(x)); + double x = PyFloat_AsDouble(v); + if (x == -1.0 && PyErr_Occurred()) + return NULL; + return PyBool_FromLong((long)Py_IS_INFINITY(x)); } static PyObject * float_is_nan(PyObject *v) { - double x = PyFloat_AsDouble(v); - if (x == -1.0 && PyErr_Occurred()) - return NULL; - return PyBool_FromLong((long)Py_IS_NAN(x)); + double x = PyFloat_AsDouble(v); + if (x == -1.0 && PyErr_Occurred()) + return NULL; + return PyBool_FromLong((long)Py_IS_NAN(x)); } static PyObject * float_is_finite(PyObject *v) { - double x = PyFloat_AsDouble(v); - if (x == -1.0 && PyErr_Occurred()) - return NULL; - return PyBool_FromLong((long)Py_IS_FINITE(x)); + double x = PyFloat_AsDouble(v); + if (x == -1.0 && PyErr_Occurred()) + return NULL; + return PyBool_FromLong((long)Py_IS_FINITE(x)); } #endif static PyObject * float_trunc(PyObject *v) { - double x = PyFloat_AsDouble(v); - double wholepart; /* integral portion of x, rounded toward 0 */ + double x = PyFloat_AsDouble(v); + double wholepart; /* integral portion of x, rounded toward 0 */ - (void)modf(x, &wholepart); - /* Try to get out cheap if this fits in a Python int. The attempt - * to cast to long must be protected, as C doesn't define what - * happens if the double is too big to fit in a long. Some rare - * systems raise an exception then (RISCOS was mentioned as one, - * and someone using a non-default option on Sun also bumped into - * that). Note that checking for >= and <= LONG_{MIN,MAX} would - * still be vulnerable: if a long has more bits of precision than - * a double, casting MIN/MAX to double may yield an approximation, - * and if that's rounded up, then, e.g., wholepart=LONG_MAX+1 would - * yield true from the C expression wholepart<=LONG_MAX, despite - * that wholepart is actually greater than LONG_MAX. - */ - if (LONG_MIN < wholepart && wholepart < LONG_MAX) { - const long aslong = (long)wholepart; - return PyLong_FromLong(aslong); - } - return PyLong_FromDouble(wholepart); + (void)modf(x, &wholepart); + /* Try to get out cheap if this fits in a Python int. The attempt + * to cast to long must be protected, as C doesn't define what + * happens if the double is too big to fit in a long. Some rare + * systems raise an exception then (RISCOS was mentioned as one, + * and someone using a non-default option on Sun also bumped into + * that). Note that checking for >= and <= LONG_{MIN,MAX} would + * still be vulnerable: if a long has more bits of precision than + * a double, casting MIN/MAX to double may yield an approximation, + * and if that's rounded up, then, e.g., wholepart=LONG_MAX+1 would + * yield true from the C expression wholepart<=LONG_MAX, despite + * that wholepart is actually greater than LONG_MAX. + */ + if (LONG_MIN < wholepart && wholepart < LONG_MAX) { + const long aslong = (long)wholepart; + return PyLong_FromLong(aslong); + } + return PyLong_FromDouble(wholepart); } /* double_round: rounds a finite double to the closest multiple of @@ -860,49 +860,49 @@ static PyObject * double_round(double x, int ndigits) { - double rounded; - Py_ssize_t buflen, mybuflen=100; - char *buf, *buf_end, shortbuf[100], *mybuf=shortbuf; - int decpt, sign; - PyObject *result = NULL; - - /* round to a decimal string */ - buf = _Py_dg_dtoa(x, 3, ndigits, &decpt, &sign, &buf_end); - if (buf == NULL) { - PyErr_NoMemory(); - return NULL; - } - - /* Get new buffer if shortbuf is too small. Space needed <= buf_end - - buf + 8: (1 extra for '0', 1 for sign, 5 for exp, 1 for '\0'). */ - buflen = buf_end - buf; - if (buflen + 8 > mybuflen) { - mybuflen = buflen+8; - mybuf = (char *)PyMem_Malloc(mybuflen); - if (mybuf == NULL) { - PyErr_NoMemory(); - goto exit; - } - } - /* copy buf to mybuf, adding exponent, sign and leading 0 */ - PyOS_snprintf(mybuf, mybuflen, "%s0%se%d", (sign ? "-" : ""), - buf, decpt - (int)buflen); - - /* and convert the resulting string back to a double */ - errno = 0; - rounded = _Py_dg_strtod(mybuf, NULL); - if (errno == ERANGE && fabs(rounded) >= 1.) - PyErr_SetString(PyExc_OverflowError, - "rounded value too large to represent"); - else - result = PyFloat_FromDouble(rounded); - - /* done computing value; now clean up */ - if (mybuf != shortbuf) - PyMem_Free(mybuf); + double rounded; + Py_ssize_t buflen, mybuflen=100; + char *buf, *buf_end, shortbuf[100], *mybuf=shortbuf; + int decpt, sign; + PyObject *result = NULL; + + /* round to a decimal string */ + buf = _Py_dg_dtoa(x, 3, ndigits, &decpt, &sign, &buf_end); + if (buf == NULL) { + PyErr_NoMemory(); + return NULL; + } + + /* Get new buffer if shortbuf is too small. Space needed <= buf_end - + buf + 8: (1 extra for '0', 1 for sign, 5 for exp, 1 for '\0'). */ + buflen = buf_end - buf; + if (buflen + 8 > mybuflen) { + mybuflen = buflen+8; + mybuf = (char *)PyMem_Malloc(mybuflen); + if (mybuf == NULL) { + PyErr_NoMemory(); + goto exit; + } + } + /* copy buf to mybuf, adding exponent, sign and leading 0 */ + PyOS_snprintf(mybuf, mybuflen, "%s0%se%d", (sign ? "-" : ""), + buf, decpt - (int)buflen); + + /* and convert the resulting string back to a double */ + errno = 0; + rounded = _Py_dg_strtod(mybuf, NULL); + if (errno == ERANGE && fabs(rounded) >= 1.) + PyErr_SetString(PyExc_OverflowError, + "rounded value too large to represent"); + else + result = PyFloat_FromDouble(rounded); + + /* done computing value; now clean up */ + if (mybuf != shortbuf) + PyMem_Free(mybuf); exit: - _Py_dg_freedtoa(buf); - return result; + _Py_dg_freedtoa(buf); + return result; } #else /* PY_NO_SHORT_FLOAT_REPR */ @@ -912,47 +912,47 @@ static PyObject * double_round(double x, int ndigits) { - double pow1, pow2, y, z; - if (ndigits >= 0) { - if (ndigits > 22) { - /* pow1 and pow2 are each safe from overflow, but - pow1*pow2 ~= pow(10.0, ndigits) might overflow */ - pow1 = pow(10.0, (double)(ndigits-22)); - pow2 = 1e22; - } - else { - pow1 = pow(10.0, (double)ndigits); - pow2 = 1.0; - } - y = (x*pow1)*pow2; - /* if y overflows, then rounded value is exactly x */ - if (!Py_IS_FINITE(y)) - return PyFloat_FromDouble(x); - } - else { - pow1 = pow(10.0, (double)-ndigits); - pow2 = 1.0; /* unused; silences a gcc compiler warning */ - y = x / pow1; - } - - z = round(y); - if (fabs(y-z) == 0.5) - /* halfway between two integers; use round-half-even */ - z = 2.0*round(y/2.0); - - if (ndigits >= 0) - z = (z / pow2) / pow1; - else - z *= pow1; - - /* if computation resulted in overflow, raise OverflowError */ - if (!Py_IS_FINITE(z)) { - PyErr_SetString(PyExc_OverflowError, - "overflow occurred during round"); - return NULL; - } + double pow1, pow2, y, z; + if (ndigits >= 0) { + if (ndigits > 22) { + /* pow1 and pow2 are each safe from overflow, but + pow1*pow2 ~= pow(10.0, ndigits) might overflow */ + pow1 = pow(10.0, (double)(ndigits-22)); + pow2 = 1e22; + } + else { + pow1 = pow(10.0, (double)ndigits); + pow2 = 1.0; + } + y = (x*pow1)*pow2; + /* if y overflows, then rounded value is exactly x */ + if (!Py_IS_FINITE(y)) + return PyFloat_FromDouble(x); + } + else { + pow1 = pow(10.0, (double)-ndigits); + pow2 = 1.0; /* unused; silences a gcc compiler warning */ + y = x / pow1; + } + + z = round(y); + if (fabs(y-z) == 0.5) + /* halfway between two integers; use round-half-even */ + z = 2.0*round(y/2.0); + + if (ndigits >= 0) + z = (z / pow2) / pow1; + else + z *= pow1; + + /* if computation resulted in overflow, raise OverflowError */ + if (!Py_IS_FINITE(z)) { + PyErr_SetString(PyExc_OverflowError, + "overflow occurred during round"); + return NULL; + } - return PyFloat_FromDouble(z); + return PyFloat_FromDouble(z); } #endif /* PY_NO_SHORT_FLOAT_REPR */ @@ -962,45 +962,45 @@ static PyObject * float_round(PyObject *v, PyObject *args) { - double x, rounded; - PyObject *o_ndigits = NULL; - Py_ssize_t ndigits; - - x = PyFloat_AsDouble(v); - if (!PyArg_ParseTuple(args, "|O", &o_ndigits)) - return NULL; - if (o_ndigits == NULL) { - /* single-argument round: round to nearest integer */ - rounded = round(x); - if (fabs(x-rounded) == 0.5) - /* halfway case: round to even */ - rounded = 2.0*round(x/2.0); - return PyLong_FromDouble(rounded); - } - - /* interpret second argument as a Py_ssize_t; clips on overflow */ - ndigits = PyNumber_AsSsize_t(o_ndigits, NULL); - if (ndigits == -1 && PyErr_Occurred()) - return NULL; - - /* nans and infinities round to themselves */ - if (!Py_IS_FINITE(x)) - return PyFloat_FromDouble(x); - - /* Deal with extreme values for ndigits. For ndigits > NDIGITS_MAX, x - always rounds to itself. For ndigits < NDIGITS_MIN, x always - rounds to +-0.0. Here 0.30103 is an upper bound for log10(2). */ + double x, rounded; + PyObject *o_ndigits = NULL; + Py_ssize_t ndigits; + + x = PyFloat_AsDouble(v); + if (!PyArg_ParseTuple(args, "|O", &o_ndigits)) + return NULL; + if (o_ndigits == NULL) { + /* single-argument round: round to nearest integer */ + rounded = round(x); + if (fabs(x-rounded) == 0.5) + /* halfway case: round to even */ + rounded = 2.0*round(x/2.0); + return PyLong_FromDouble(rounded); + } + + /* interpret second argument as a Py_ssize_t; clips on overflow */ + ndigits = PyNumber_AsSsize_t(o_ndigits, NULL); + if (ndigits == -1 && PyErr_Occurred()) + return NULL; + + /* nans and infinities round to themselves */ + if (!Py_IS_FINITE(x)) + return PyFloat_FromDouble(x); + + /* Deal with extreme values for ndigits. For ndigits > NDIGITS_MAX, x + always rounds to itself. For ndigits < NDIGITS_MIN, x always + rounds to +-0.0. Here 0.30103 is an upper bound for log10(2). */ #define NDIGITS_MAX ((int)((DBL_MANT_DIG-DBL_MIN_EXP) * 0.30103)) #define NDIGITS_MIN (-(int)((DBL_MAX_EXP + 1) * 0.30103)) - if (ndigits > NDIGITS_MAX) - /* return x */ - return PyFloat_FromDouble(x); - else if (ndigits < NDIGITS_MIN) - /* return 0.0, but with sign of x */ - return PyFloat_FromDouble(0.0*x); - else - /* finite x, and ndigits is not unreasonably large */ - return double_round(x, (int)ndigits); + if (ndigits > NDIGITS_MAX) + /* return x */ + return PyFloat_FromDouble(x); + else if (ndigits < NDIGITS_MIN) + /* return 0.0, but with sign of x */ + return PyFloat_FromDouble(0.0*x); + else + /* finite x, and ndigits is not unreasonably large */ + return double_round(x, (int)ndigits); #undef NDIGITS_MAX #undef NDIGITS_MIN } @@ -1008,11 +1008,11 @@ static PyObject * float_float(PyObject *v) { - if (PyFloat_CheckExact(v)) - Py_INCREF(v); - else - v = PyFloat_FromDouble(((PyFloatObject *)v)->ob_fval); - return v; + if (PyFloat_CheckExact(v)) + Py_INCREF(v); + else + v = PyFloat_FromDouble(((PyFloatObject *)v)->ob_fval); + return v; } /* turn ASCII hex characters into integer values and vice versa */ @@ -1020,73 +1020,73 @@ static char char_from_hex(int x) { - assert(0 <= x && x < 16); - return "0123456789abcdef"[x]; + assert(0 <= x && x < 16); + return "0123456789abcdef"[x]; } static int hex_from_char(char c) { - int x; - switch(c) { - case '0': - x = 0; - break; - case '1': - x = 1; - break; - case '2': - x = 2; - break; - case '3': - x = 3; - break; - case '4': - x = 4; - break; - case '5': - x = 5; - break; - case '6': - x = 6; - break; - case '7': - x = 7; - break; - case '8': - x = 8; - break; - case '9': - x = 9; - break; - case 'a': - case 'A': - x = 10; - break; - case 'b': - case 'B': - x = 11; - break; - case 'c': - case 'C': - x = 12; - break; - case 'd': - case 'D': - x = 13; - break; - case 'e': - case 'E': - x = 14; - break; - case 'f': - case 'F': - x = 15; - break; - default: - x = -1; - break; - } - return x; + int x; + switch(c) { + case '0': + x = 0; + break; + case '1': + x = 1; + break; + case '2': + x = 2; + break; + case '3': + x = 3; + break; + case '4': + x = 4; + break; + case '5': + x = 5; + break; + case '6': + x = 6; + break; + case '7': + x = 7; + break; + case '8': + x = 8; + break; + case '9': + x = 9; + break; + case 'a': + case 'A': + x = 10; + break; + case 'b': + case 'B': + x = 11; + break; + case 'c': + case 'C': + x = 12; + break; + case 'd': + case 'D': + x = 13; + break; + case 'e': + case 'E': + x = 14; + break; + case 'f': + case 'F': + x = 15; + break; + default: + x = -1; + break; + } + return x; } /* convert a float to a hexadecimal string */ @@ -1098,54 +1098,54 @@ static PyObject * float_hex(PyObject *v) { - double x, m; - int e, shift, i, si, esign; - /* Space for 1+(TOHEX_NBITS-1)/4 digits, a decimal point, and the - trailing NUL byte. */ - char s[(TOHEX_NBITS-1)/4+3]; - - CONVERT_TO_DOUBLE(v, x); - - if (Py_IS_NAN(x) || Py_IS_INFINITY(x)) - return float_str((PyFloatObject *)v); - - if (x == 0.0) { - if(copysign(1.0, x) == -1.0) - return PyUnicode_FromString("-0x0.0p+0"); - else - return PyUnicode_FromString("0x0.0p+0"); - } - - m = frexp(fabs(x), &e); - shift = 1 - MAX(DBL_MIN_EXP - e, 0); - m = ldexp(m, shift); - e -= shift; - - si = 0; - s[si] = char_from_hex((int)m); - si++; - m -= (int)m; - s[si] = '.'; - si++; - for (i=0; i < (TOHEX_NBITS-1)/4; i++) { - m *= 16.0; - s[si] = char_from_hex((int)m); - si++; - m -= (int)m; - } - s[si] = '\0'; - - if (e < 0) { - esign = (int)'-'; - e = -e; - } - else - esign = (int)'+'; - - if (x < 0.0) - return PyUnicode_FromFormat("-0x%sp%c%d", s, esign, e); - else - return PyUnicode_FromFormat("0x%sp%c%d", s, esign, e); + double x, m; + int e, shift, i, si, esign; + /* Space for 1+(TOHEX_NBITS-1)/4 digits, a decimal point, and the + trailing NUL byte. */ + char s[(TOHEX_NBITS-1)/4+3]; + + CONVERT_TO_DOUBLE(v, x); + + if (Py_IS_NAN(x) || Py_IS_INFINITY(x)) + return float_str((PyFloatObject *)v); + + if (x == 0.0) { + if(copysign(1.0, x) == -1.0) + return PyUnicode_FromString("-0x0.0p+0"); + else + return PyUnicode_FromString("0x0.0p+0"); + } + + m = frexp(fabs(x), &e); + shift = 1 - MAX(DBL_MIN_EXP - e, 0); + m = ldexp(m, shift); + e -= shift; + + si = 0; + s[si] = char_from_hex((int)m); + si++; + m -= (int)m; + s[si] = '.'; + si++; + for (i=0; i < (TOHEX_NBITS-1)/4; i++) { + m *= 16.0; + s[si] = char_from_hex((int)m); + si++; + m -= (int)m; + } + s[si] = '\0'; + + if (e < 0) { + esign = (int)'-'; + e = -e; + } + else + esign = (int)'+'; + + if (x < 0.0) + return PyUnicode_FromFormat("-0x%sp%c%d", s, esign, e); + else + return PyUnicode_FromFormat("0x%sp%c%d", s, esign, e); } PyDoc_STRVAR(float_hex_doc, @@ -1162,242 +1162,242 @@ static PyObject * float_fromhex(PyObject *cls, PyObject *arg) { - PyObject *result_as_float, *result; - double x; - long exp, top_exp, lsb, key_digit; - char *s, *coeff_start, *s_store, *coeff_end, *exp_start, *s_end; - int half_eps, digit, round_up, negate=0; - Py_ssize_t length, ndigits, fdigits, i; - - /* - * For the sake of simplicity and correctness, we impose an artificial - * limit on ndigits, the total number of hex digits in the coefficient - * The limit is chosen to ensure that, writing exp for the exponent, - * - * (1) if exp > LONG_MAX/2 then the value of the hex string is - * guaranteed to overflow (provided it's nonzero) - * - * (2) if exp < LONG_MIN/2 then the value of the hex string is - * guaranteed to underflow to 0. - * - * (3) if LONG_MIN/2 <= exp <= LONG_MAX/2 then there's no danger of - * overflow in the calculation of exp and top_exp below. - * - * More specifically, ndigits is assumed to satisfy the following - * inequalities: - * - * 4*ndigits <= DBL_MIN_EXP - DBL_MANT_DIG - LONG_MIN/2 - * 4*ndigits <= LONG_MAX/2 + 1 - DBL_MAX_EXP - * - * If either of these inequalities is not satisfied, a ValueError is - * raised. Otherwise, write x for the value of the hex string, and - * assume x is nonzero. Then - * - * 2**(exp-4*ndigits) <= |x| < 2**(exp+4*ndigits). - * - * Now if exp > LONG_MAX/2 then: - * - * exp - 4*ndigits >= LONG_MAX/2 + 1 - (LONG_MAX/2 + 1 - DBL_MAX_EXP) - * = DBL_MAX_EXP - * - * so |x| >= 2**DBL_MAX_EXP, which is too large to be stored in C - * double, so overflows. If exp < LONG_MIN/2, then - * - * exp + 4*ndigits <= LONG_MIN/2 - 1 + ( - * DBL_MIN_EXP - DBL_MANT_DIG - LONG_MIN/2) - * = DBL_MIN_EXP - DBL_MANT_DIG - 1 - * - * and so |x| < 2**(DBL_MIN_EXP-DBL_MANT_DIG-1), hence underflows to 0 - * when converted to a C double. - * - * It's easy to show that if LONG_MIN/2 <= exp <= LONG_MAX/2 then both - * exp+4*ndigits and exp-4*ndigits are within the range of a long. - */ - - s = _PyUnicode_AsStringAndSize(arg, &length); - if (s == NULL) - return NULL; - s_end = s + length; - - /******************** - * Parse the string * - ********************/ - - /* leading whitespace */ - while (Py_ISSPACE(*s)) - s++; - - /* infinities and nans */ - x = _Py_parse_inf_or_nan(s, &coeff_end); - if (coeff_end != s) { - s = coeff_end; - goto finished; - } - - /* optional sign */ - if (*s == '-') { - s++; - negate = 1; - } - else if (*s == '+') - s++; - - /* [0x] */ - s_store = s; - if (*s == '0') { - s++; - if (*s == 'x' || *s == 'X') - s++; - else - s = s_store; - } - - /* coefficient: [. ] */ - coeff_start = s; - while (hex_from_char(*s) >= 0) - s++; - s_store = s; - if (*s == '.') { - s++; - while (hex_from_char(*s) >= 0) - s++; - coeff_end = s-1; - } - else - coeff_end = s; - - /* ndigits = total # of hex digits; fdigits = # after point */ - ndigits = coeff_end - coeff_start; - fdigits = coeff_end - s_store; - if (ndigits == 0) - goto parse_error; - if (ndigits > MIN(DBL_MIN_EXP - DBL_MANT_DIG - LONG_MIN/2, - LONG_MAX/2 + 1 - DBL_MAX_EXP)/4) - goto insane_length_error; - - /* [p ] */ - if (*s == 'p' || *s == 'P') { - s++; - exp_start = s; - if (*s == '-' || *s == '+') - s++; - if (!('0' <= *s && *s <= '9')) - goto parse_error; - s++; - while ('0' <= *s && *s <= '9') - s++; - exp = strtol(exp_start, NULL, 10); - } - else - exp = 0; + PyObject *result_as_float, *result; + double x; + long exp, top_exp, lsb, key_digit; + char *s, *coeff_start, *s_store, *coeff_end, *exp_start, *s_end; + int half_eps, digit, round_up, negate=0; + Py_ssize_t length, ndigits, fdigits, i; + + /* + * For the sake of simplicity and correctness, we impose an artificial + * limit on ndigits, the total number of hex digits in the coefficient + * The limit is chosen to ensure that, writing exp for the exponent, + * + * (1) if exp > LONG_MAX/2 then the value of the hex string is + * guaranteed to overflow (provided it's nonzero) + * + * (2) if exp < LONG_MIN/2 then the value of the hex string is + * guaranteed to underflow to 0. + * + * (3) if LONG_MIN/2 <= exp <= LONG_MAX/2 then there's no danger of + * overflow in the calculation of exp and top_exp below. + * + * More specifically, ndigits is assumed to satisfy the following + * inequalities: + * + * 4*ndigits <= DBL_MIN_EXP - DBL_MANT_DIG - LONG_MIN/2 + * 4*ndigits <= LONG_MAX/2 + 1 - DBL_MAX_EXP + * + * If either of these inequalities is not satisfied, a ValueError is + * raised. Otherwise, write x for the value of the hex string, and + * assume x is nonzero. Then + * + * 2**(exp-4*ndigits) <= |x| < 2**(exp+4*ndigits). + * + * Now if exp > LONG_MAX/2 then: + * + * exp - 4*ndigits >= LONG_MAX/2 + 1 - (LONG_MAX/2 + 1 - DBL_MAX_EXP) + * = DBL_MAX_EXP + * + * so |x| >= 2**DBL_MAX_EXP, which is too large to be stored in C + * double, so overflows. If exp < LONG_MIN/2, then + * + * exp + 4*ndigits <= LONG_MIN/2 - 1 + ( + * DBL_MIN_EXP - DBL_MANT_DIG - LONG_MIN/2) + * = DBL_MIN_EXP - DBL_MANT_DIG - 1 + * + * and so |x| < 2**(DBL_MIN_EXP-DBL_MANT_DIG-1), hence underflows to 0 + * when converted to a C double. + * + * It's easy to show that if LONG_MIN/2 <= exp <= LONG_MAX/2 then both + * exp+4*ndigits and exp-4*ndigits are within the range of a long. + */ + + s = _PyUnicode_AsStringAndSize(arg, &length); + if (s == NULL) + return NULL; + s_end = s + length; + + /******************** + * Parse the string * + ********************/ + + /* leading whitespace */ + while (Py_ISSPACE(*s)) + s++; + + /* infinities and nans */ + x = _Py_parse_inf_or_nan(s, &coeff_end); + if (coeff_end != s) { + s = coeff_end; + goto finished; + } + + /* optional sign */ + if (*s == '-') { + s++; + negate = 1; + } + else if (*s == '+') + s++; + + /* [0x] */ + s_store = s; + if (*s == '0') { + s++; + if (*s == 'x' || *s == 'X') + s++; + else + s = s_store; + } + + /* coefficient: [. ] */ + coeff_start = s; + while (hex_from_char(*s) >= 0) + s++; + s_store = s; + if (*s == '.') { + s++; + while (hex_from_char(*s) >= 0) + s++; + coeff_end = s-1; + } + else + coeff_end = s; + + /* ndigits = total # of hex digits; fdigits = # after point */ + ndigits = coeff_end - coeff_start; + fdigits = coeff_end - s_store; + if (ndigits == 0) + goto parse_error; + if (ndigits > MIN(DBL_MIN_EXP - DBL_MANT_DIG - LONG_MIN/2, + LONG_MAX/2 + 1 - DBL_MAX_EXP)/4) + goto insane_length_error; + + /* [p ] */ + if (*s == 'p' || *s == 'P') { + s++; + exp_start = s; + if (*s == '-' || *s == '+') + s++; + if (!('0' <= *s && *s <= '9')) + goto parse_error; + s++; + while ('0' <= *s && *s <= '9') + s++; + exp = strtol(exp_start, NULL, 10); + } + else + exp = 0; /* for 0 <= j < ndigits, HEX_DIGIT(j) gives the jth most significant digit */ -#define HEX_DIGIT(j) hex_from_char(*((j) < fdigits ? \ - coeff_end-(j) : \ - coeff_end-1-(j))) - - /******************************************* - * Compute rounded value of the hex string * - *******************************************/ - - /* Discard leading zeros, and catch extreme overflow and underflow */ - while (ndigits > 0 && HEX_DIGIT(ndigits-1) == 0) - ndigits--; - if (ndigits == 0 || exp < LONG_MIN/2) { - x = 0.0; - goto finished; - } - if (exp > LONG_MAX/2) - goto overflow_error; - - /* Adjust exponent for fractional part. */ - exp = exp - 4*((long)fdigits); - - /* top_exp = 1 more than exponent of most sig. bit of coefficient */ - top_exp = exp + 4*((long)ndigits - 1); - for (digit = HEX_DIGIT(ndigits-1); digit != 0; digit /= 2) - top_exp++; - - /* catch almost all nonextreme cases of overflow and underflow here */ - if (top_exp < DBL_MIN_EXP - DBL_MANT_DIG) { - x = 0.0; - goto finished; - } - if (top_exp > DBL_MAX_EXP) - goto overflow_error; - - /* lsb = exponent of least significant bit of the *rounded* value. - This is top_exp - DBL_MANT_DIG unless result is subnormal. */ - lsb = MAX(top_exp, (long)DBL_MIN_EXP) - DBL_MANT_DIG; - - x = 0.0; - if (exp >= lsb) { - /* no rounding required */ - for (i = ndigits-1; i >= 0; i--) - x = 16.0*x + HEX_DIGIT(i); - x = ldexp(x, (int)(exp)); - goto finished; - } - /* rounding required. key_digit is the index of the hex digit - containing the first bit to be rounded away. */ - half_eps = 1 << (int)((lsb - exp - 1) % 4); - key_digit = (lsb - exp - 1) / 4; - for (i = ndigits-1; i > key_digit; i--) - x = 16.0*x + HEX_DIGIT(i); - digit = HEX_DIGIT(key_digit); - x = 16.0*x + (double)(digit & (16-2*half_eps)); - - /* round-half-even: round up if bit lsb-1 is 1 and at least one of - bits lsb, lsb-2, lsb-3, lsb-4, ... is 1. */ - if ((digit & half_eps) != 0) { - round_up = 0; - if ((digit & (3*half_eps-1)) != 0 || - (half_eps == 8 && (HEX_DIGIT(key_digit+1) & 1) != 0)) - round_up = 1; - else - for (i = key_digit-1; i >= 0; i--) - if (HEX_DIGIT(i) != 0) { - round_up = 1; - break; - } - if (round_up == 1) { - x += 2*half_eps; - if (top_exp == DBL_MAX_EXP && - x == ldexp((double)(2*half_eps), DBL_MANT_DIG)) - /* overflow corner case: pre-rounded value < - 2**DBL_MAX_EXP; rounded=2**DBL_MAX_EXP. */ - goto overflow_error; - } - } - x = ldexp(x, (int)(exp+4*key_digit)); +#define HEX_DIGIT(j) hex_from_char(*((j) < fdigits ? \ + coeff_end-(j) : \ + coeff_end-1-(j))) + + /******************************************* + * Compute rounded value of the hex string * + *******************************************/ + + /* Discard leading zeros, and catch extreme overflow and underflow */ + while (ndigits > 0 && HEX_DIGIT(ndigits-1) == 0) + ndigits--; + if (ndigits == 0 || exp < LONG_MIN/2) { + x = 0.0; + goto finished; + } + if (exp > LONG_MAX/2) + goto overflow_error; + + /* Adjust exponent for fractional part. */ + exp = exp - 4*((long)fdigits); + + /* top_exp = 1 more than exponent of most sig. bit of coefficient */ + top_exp = exp + 4*((long)ndigits - 1); + for (digit = HEX_DIGIT(ndigits-1); digit != 0; digit /= 2) + top_exp++; + + /* catch almost all nonextreme cases of overflow and underflow here */ + if (top_exp < DBL_MIN_EXP - DBL_MANT_DIG) { + x = 0.0; + goto finished; + } + if (top_exp > DBL_MAX_EXP) + goto overflow_error; + + /* lsb = exponent of least significant bit of the *rounded* value. + This is top_exp - DBL_MANT_DIG unless result is subnormal. */ + lsb = MAX(top_exp, (long)DBL_MIN_EXP) - DBL_MANT_DIG; + + x = 0.0; + if (exp >= lsb) { + /* no rounding required */ + for (i = ndigits-1; i >= 0; i--) + x = 16.0*x + HEX_DIGIT(i); + x = ldexp(x, (int)(exp)); + goto finished; + } + /* rounding required. key_digit is the index of the hex digit + containing the first bit to be rounded away. */ + half_eps = 1 << (int)((lsb - exp - 1) % 4); + key_digit = (lsb - exp - 1) / 4; + for (i = ndigits-1; i > key_digit; i--) + x = 16.0*x + HEX_DIGIT(i); + digit = HEX_DIGIT(key_digit); + x = 16.0*x + (double)(digit & (16-2*half_eps)); + + /* round-half-even: round up if bit lsb-1 is 1 and at least one of + bits lsb, lsb-2, lsb-3, lsb-4, ... is 1. */ + if ((digit & half_eps) != 0) { + round_up = 0; + if ((digit & (3*half_eps-1)) != 0 || + (half_eps == 8 && (HEX_DIGIT(key_digit+1) & 1) != 0)) + round_up = 1; + else + for (i = key_digit-1; i >= 0; i--) + if (HEX_DIGIT(i) != 0) { + round_up = 1; + break; + } + if (round_up == 1) { + x += 2*half_eps; + if (top_exp == DBL_MAX_EXP && + x == ldexp((double)(2*half_eps), DBL_MANT_DIG)) + /* overflow corner case: pre-rounded value < + 2**DBL_MAX_EXP; rounded=2**DBL_MAX_EXP. */ + goto overflow_error; + } + } + x = ldexp(x, (int)(exp+4*key_digit)); finished: - /* optional trailing whitespace leading to the end of the string */ - while (Py_ISSPACE(*s)) - s++; - if (s != s_end) - goto parse_error; - result_as_float = Py_BuildValue("(d)", negate ? -x : x); - if (result_as_float == NULL) - return NULL; - result = PyObject_CallObject(cls, result_as_float); - Py_DECREF(result_as_float); - return result; + /* optional trailing whitespace leading to the end of the string */ + while (Py_ISSPACE(*s)) + s++; + if (s != s_end) + goto parse_error; + result_as_float = Py_BuildValue("(d)", negate ? -x : x); + if (result_as_float == NULL) + return NULL; + result = PyObject_CallObject(cls, result_as_float); + Py_DECREF(result_as_float); + return result; overflow_error: - PyErr_SetString(PyExc_OverflowError, - "hexadecimal value too large to represent as a float"); - return NULL; + PyErr_SetString(PyExc_OverflowError, + "hexadecimal value too large to represent as a float"); + return NULL; parse_error: - PyErr_SetString(PyExc_ValueError, - "invalid hexadecimal floating-point string"); - return NULL; + PyErr_SetString(PyExc_ValueError, + "invalid hexadecimal floating-point string"); + return NULL; insane_length_error: - PyErr_SetString(PyExc_ValueError, - "hexadecimal string too long to convert"); - return NULL; + PyErr_SetString(PyExc_ValueError, + "hexadecimal string too long to convert"); + return NULL; } PyDoc_STRVAR(float_fromhex_doc, @@ -1413,79 +1413,79 @@ static PyObject * float_as_integer_ratio(PyObject *v, PyObject *unused) { - double self; - double float_part; - int exponent; - int i; - - PyObject *prev; - PyObject *py_exponent = NULL; - PyObject *numerator = NULL; - PyObject *denominator = NULL; - PyObject *result_pair = NULL; - PyNumberMethods *long_methods = PyLong_Type.tp_as_number; + double self; + double float_part; + int exponent; + int i; + + PyObject *prev; + PyObject *py_exponent = NULL; + PyObject *numerator = NULL; + PyObject *denominator = NULL; + PyObject *result_pair = NULL; + PyNumberMethods *long_methods = PyLong_Type.tp_as_number; #define INPLACE_UPDATE(obj, call) \ - prev = obj; \ - obj = call; \ - Py_DECREF(prev); \ - - CONVERT_TO_DOUBLE(v, self); - - if (Py_IS_INFINITY(self)) { - PyErr_SetString(PyExc_OverflowError, - "Cannot pass infinity to float.as_integer_ratio."); - return NULL; - } + prev = obj; \ + obj = call; \ + Py_DECREF(prev); \ + + CONVERT_TO_DOUBLE(v, self); + + if (Py_IS_INFINITY(self)) { + PyErr_SetString(PyExc_OverflowError, + "Cannot pass infinity to float.as_integer_ratio."); + return NULL; + } #ifdef Py_NAN - if (Py_IS_NAN(self)) { - PyErr_SetString(PyExc_ValueError, - "Cannot pass NaN to float.as_integer_ratio."); - return NULL; - } + if (Py_IS_NAN(self)) { + PyErr_SetString(PyExc_ValueError, + "Cannot pass NaN to float.as_integer_ratio."); + return NULL; + } #endif - PyFPE_START_PROTECT("as_integer_ratio", goto error); - float_part = frexp(self, &exponent); /* self == float_part * 2**exponent exactly */ - PyFPE_END_PROTECT(float_part); - - for (i=0; i<300 && float_part != floor(float_part) ; i++) { - float_part *= 2.0; - exponent--; - } - /* self == float_part * 2**exponent exactly and float_part is integral. - If FLT_RADIX != 2, the 300 steps may leave a tiny fractional part - to be truncated by PyLong_FromDouble(). */ - - numerator = PyLong_FromDouble(float_part); - if (numerator == NULL) goto error; - - /* fold in 2**exponent */ - denominator = PyLong_FromLong(1); - py_exponent = PyLong_FromLong(labs((long)exponent)); - if (py_exponent == NULL) goto error; - INPLACE_UPDATE(py_exponent, - long_methods->nb_lshift(denominator, py_exponent)); - if (py_exponent == NULL) goto error; - if (exponent > 0) { - INPLACE_UPDATE(numerator, - long_methods->nb_multiply(numerator, py_exponent)); - if (numerator == NULL) goto error; - } - else { - Py_DECREF(denominator); - denominator = py_exponent; - py_exponent = NULL; - } + PyFPE_START_PROTECT("as_integer_ratio", goto error); + float_part = frexp(self, &exponent); /* self == float_part * 2**exponent exactly */ + PyFPE_END_PROTECT(float_part); + + for (i=0; i<300 && float_part != floor(float_part) ; i++) { + float_part *= 2.0; + exponent--; + } + /* self == float_part * 2**exponent exactly and float_part is integral. + If FLT_RADIX != 2, the 300 steps may leave a tiny fractional part + to be truncated by PyLong_FromDouble(). */ + + numerator = PyLong_FromDouble(float_part); + if (numerator == NULL) goto error; + + /* fold in 2**exponent */ + denominator = PyLong_FromLong(1); + py_exponent = PyLong_FromLong(labs((long)exponent)); + if (py_exponent == NULL) goto error; + INPLACE_UPDATE(py_exponent, + long_methods->nb_lshift(denominator, py_exponent)); + if (py_exponent == NULL) goto error; + if (exponent > 0) { + INPLACE_UPDATE(numerator, + long_methods->nb_multiply(numerator, py_exponent)); + if (numerator == NULL) goto error; + } + else { + Py_DECREF(denominator); + denominator = py_exponent; + py_exponent = NULL; + } - result_pair = PyTuple_Pack(2, numerator, denominator); + result_pair = PyTuple_Pack(2, numerator, denominator); #undef INPLACE_UPDATE error: - Py_XDECREF(py_exponent); - Py_XDECREF(denominator); - Py_XDECREF(numerator); - return result_pair; + Py_XDECREF(py_exponent); + Py_XDECREF(denominator); + Py_XDECREF(numerator); + return result_pair; } PyDoc_STRVAR(float_as_integer_ratio_doc, @@ -1509,18 +1509,18 @@ static PyObject * float_new(PyTypeObject *type, PyObject *args, PyObject *kwds) { - PyObject *x = Py_False; /* Integer zero */ - static char *kwlist[] = {"x", 0}; + PyObject *x = Py_False; /* Integer zero */ + static char *kwlist[] = {"x", 0}; - if (type != &PyFloat_Type) - return float_subtype_new(type, args, kwds); /* Wimp out */ - if (!PyArg_ParseTupleAndKeywords(args, kwds, "|O:float", kwlist, &x)) - return NULL; - /* If it's a string, but not a string subclass, use - PyFloat_FromString. */ - if (PyUnicode_CheckExact(x)) - return PyFloat_FromString(x); - return PyNumber_Float(x); + if (type != &PyFloat_Type) + return float_subtype_new(type, args, kwds); /* Wimp out */ + if (!PyArg_ParseTupleAndKeywords(args, kwds, "|O:float", kwlist, &x)) + return NULL; + /* If it's a string, but not a string subclass, use + PyFloat_FromString. */ + if (PyUnicode_CheckExact(x)) + return PyFloat_FromString(x); + return PyNumber_Float(x); } /* Wimpy, slow approach to tp_new calls for subtypes of float: @@ -1531,33 +1531,33 @@ static PyObject * float_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds) { - PyObject *tmp, *newobj; + PyObject *tmp, *newobj; - assert(PyType_IsSubtype(type, &PyFloat_Type)); - tmp = float_new(&PyFloat_Type, args, kwds); - if (tmp == NULL) - return NULL; - assert(PyFloat_CheckExact(tmp)); - newobj = type->tp_alloc(type, 0); - if (newobj == NULL) { - Py_DECREF(tmp); - return NULL; - } - ((PyFloatObject *)newobj)->ob_fval = ((PyFloatObject *)tmp)->ob_fval; - Py_DECREF(tmp); - return newobj; + assert(PyType_IsSubtype(type, &PyFloat_Type)); + tmp = float_new(&PyFloat_Type, args, kwds); + if (tmp == NULL) + return NULL; + assert(PyFloat_CheckExact(tmp)); + newobj = type->tp_alloc(type, 0); + if (newobj == NULL) { + Py_DECREF(tmp); + return NULL; + } + ((PyFloatObject *)newobj)->ob_fval = ((PyFloatObject *)tmp)->ob_fval; + Py_DECREF(tmp); + return newobj; } static PyObject * float_getnewargs(PyFloatObject *v) { - return Py_BuildValue("(d)", v->ob_fval); + return Py_BuildValue("(d)", v->ob_fval); } /* this is for the benefit of the pack/unpack routines below */ typedef enum { - unknown_format, ieee_big_endian_format, ieee_little_endian_format + unknown_format, ieee_big_endian_format, ieee_little_endian_format } float_format_type; static float_format_type double_format, float_format; @@ -1566,42 +1566,42 @@ static PyObject * float_getformat(PyTypeObject *v, PyObject* arg) { - char* s; - float_format_type r; + char* s; + float_format_type r; - if (!PyUnicode_Check(arg)) { - PyErr_Format(PyExc_TypeError, - "__getformat__() argument must be string, not %.500s", - Py_TYPE(arg)->tp_name); - return NULL; - } - s = _PyUnicode_AsString(arg); - if (s == NULL) - return NULL; - if (strcmp(s, "double") == 0) { - r = double_format; - } - else if (strcmp(s, "float") == 0) { - r = float_format; - } - else { - PyErr_SetString(PyExc_ValueError, - "__getformat__() argument 1 must be " - "'double' or 'float'"); - return NULL; - } - - switch (r) { - case unknown_format: - return PyUnicode_FromString("unknown"); - case ieee_little_endian_format: - return PyUnicode_FromString("IEEE, little-endian"); - case ieee_big_endian_format: - return PyUnicode_FromString("IEEE, big-endian"); - default: - Py_FatalError("insane float_format or double_format"); - return NULL; - } + if (!PyUnicode_Check(arg)) { + PyErr_Format(PyExc_TypeError, + "__getformat__() argument must be string, not %.500s", + Py_TYPE(arg)->tp_name); + return NULL; + } + s = _PyUnicode_AsString(arg); + if (s == NULL) + return NULL; + if (strcmp(s, "double") == 0) { + r = double_format; + } + else if (strcmp(s, "float") == 0) { + r = float_format; + } + else { + PyErr_SetString(PyExc_ValueError, + "__getformat__() argument 1 must be " + "'double' or 'float'"); + return NULL; + } + + switch (r) { + case unknown_format: + return PyUnicode_FromString("unknown"); + case ieee_little_endian_format: + return PyUnicode_FromString("IEEE, little-endian"); + case ieee_big_endian_format: + return PyUnicode_FromString("IEEE, big-endian"); + default: + Py_FatalError("insane float_format or double_format"); + return NULL; + } } PyDoc_STRVAR(float_getformat_doc, @@ -1617,57 +1617,57 @@ static PyObject * float_setformat(PyTypeObject *v, PyObject* args) { - char* typestr; - char* format; - float_format_type f; - float_format_type detected; - float_format_type *p; - - if (!PyArg_ParseTuple(args, "ss:__setformat__", &typestr, &format)) - return NULL; - - if (strcmp(typestr, "double") == 0) { - p = &double_format; - detected = detected_double_format; - } - else if (strcmp(typestr, "float") == 0) { - p = &float_format; - detected = detected_float_format; - } - else { - PyErr_SetString(PyExc_ValueError, - "__setformat__() argument 1 must " - "be 'double' or 'float'"); - return NULL; - } - - if (strcmp(format, "unknown") == 0) { - f = unknown_format; - } - else if (strcmp(format, "IEEE, little-endian") == 0) { - f = ieee_little_endian_format; - } - else if (strcmp(format, "IEEE, big-endian") == 0) { - f = ieee_big_endian_format; - } - else { - PyErr_SetString(PyExc_ValueError, - "__setformat__() argument 2 must be " - "'unknown', 'IEEE, little-endian' or " - "'IEEE, big-endian'"); - return NULL; - - } - - if (f != unknown_format && f != detected) { - PyErr_Format(PyExc_ValueError, - "can only set %s format to 'unknown' or the " - "detected platform value", typestr); - return NULL; - } + char* typestr; + char* format; + float_format_type f; + float_format_type detected; + float_format_type *p; + + if (!PyArg_ParseTuple(args, "ss:__setformat__", &typestr, &format)) + return NULL; + + if (strcmp(typestr, "double") == 0) { + p = &double_format; + detected = detected_double_format; + } + else if (strcmp(typestr, "float") == 0) { + p = &float_format; + detected = detected_float_format; + } + else { + PyErr_SetString(PyExc_ValueError, + "__setformat__() argument 1 must " + "be 'double' or 'float'"); + return NULL; + } + + if (strcmp(format, "unknown") == 0) { + f = unknown_format; + } + else if (strcmp(format, "IEEE, little-endian") == 0) { + f = ieee_little_endian_format; + } + else if (strcmp(format, "IEEE, big-endian") == 0) { + f = ieee_big_endian_format; + } + else { + PyErr_SetString(PyExc_ValueError, + "__setformat__() argument 2 must be " + "'unknown', 'IEEE, little-endian' or " + "'IEEE, big-endian'"); + return NULL; + + } + + if (f != unknown_format && f != detected) { + PyErr_Format(PyExc_ValueError, + "can only set %s format to 'unknown' or the " + "detected platform value", typestr); + return NULL; + } - *p = f; - Py_RETURN_NONE; + *p = f; + Py_RETURN_NONE; } PyDoc_STRVAR(float_setformat_doc, @@ -1686,19 +1686,19 @@ static PyObject * float_getzero(PyObject *v, void *closure) { - return PyFloat_FromDouble(0.0); + return PyFloat_FromDouble(0.0); } static PyObject * float__format__(PyObject *self, PyObject *args) { - PyObject *format_spec; + PyObject *format_spec; - if (!PyArg_ParseTuple(args, "U:__format__", &format_spec)) - return NULL; - return _PyFloat_FormatAdvanced(self, - PyUnicode_AS_UNICODE(format_spec), - PyUnicode_GET_SIZE(format_spec)); + if (!PyArg_ParseTuple(args, "U:__format__", &format_spec)) + return NULL; + return _PyFloat_FormatAdvanced(self, + PyUnicode_AS_UNICODE(format_spec), + PyUnicode_GET_SIZE(format_spec)); } PyDoc_STRVAR(float__format__doc, @@ -1708,45 +1708,45 @@ static PyMethodDef float_methods[] = { - {"conjugate", (PyCFunction)float_float, METH_NOARGS, - "Returns self, the complex conjugate of any float."}, - {"__trunc__", (PyCFunction)float_trunc, METH_NOARGS, - "Returns the Integral closest to x between 0 and x."}, - {"__round__", (PyCFunction)float_round, METH_VARARGS, - "Returns the Integral closest to x, rounding half toward even.\n" - "When an argument is passed, works like built-in round(x, ndigits)."}, - {"as_integer_ratio", (PyCFunction)float_as_integer_ratio, METH_NOARGS, - float_as_integer_ratio_doc}, - {"fromhex", (PyCFunction)float_fromhex, - METH_O|METH_CLASS, float_fromhex_doc}, - {"hex", (PyCFunction)float_hex, - METH_NOARGS, float_hex_doc}, - {"is_integer", (PyCFunction)float_is_integer, METH_NOARGS, - "Returns True if the float is an integer."}, + {"conjugate", (PyCFunction)float_float, METH_NOARGS, + "Returns self, the complex conjugate of any float."}, + {"__trunc__", (PyCFunction)float_trunc, METH_NOARGS, + "Returns the Integral closest to x between 0 and x."}, + {"__round__", (PyCFunction)float_round, METH_VARARGS, + "Returns the Integral closest to x, rounding half toward even.\n" + "When an argument is passed, works like built-in round(x, ndigits)."}, + {"as_integer_ratio", (PyCFunction)float_as_integer_ratio, METH_NOARGS, + float_as_integer_ratio_doc}, + {"fromhex", (PyCFunction)float_fromhex, + METH_O|METH_CLASS, float_fromhex_doc}, + {"hex", (PyCFunction)float_hex, + METH_NOARGS, float_hex_doc}, + {"is_integer", (PyCFunction)float_is_integer, METH_NOARGS, + "Returns True if the float is an integer."}, #if 0 - {"is_inf", (PyCFunction)float_is_inf, METH_NOARGS, - "Returns True if the float is positive or negative infinite."}, - {"is_finite", (PyCFunction)float_is_finite, METH_NOARGS, - "Returns True if the float is finite, neither infinite nor NaN."}, - {"is_nan", (PyCFunction)float_is_nan, METH_NOARGS, - "Returns True if the float is not a number (NaN)."}, + {"is_inf", (PyCFunction)float_is_inf, METH_NOARGS, + "Returns True if the float is positive or negative infinite."}, + {"is_finite", (PyCFunction)float_is_finite, METH_NOARGS, + "Returns True if the float is finite, neither infinite nor NaN."}, + {"is_nan", (PyCFunction)float_is_nan, METH_NOARGS, + "Returns True if the float is not a number (NaN)."}, #endif - {"__getnewargs__", (PyCFunction)float_getnewargs, METH_NOARGS}, - {"__getformat__", (PyCFunction)float_getformat, - METH_O|METH_CLASS, float_getformat_doc}, - {"__setformat__", (PyCFunction)float_setformat, - METH_VARARGS|METH_CLASS, float_setformat_doc}, - {"__format__", (PyCFunction)float__format__, - METH_VARARGS, float__format__doc}, - {NULL, NULL} /* sentinel */ + {"__getnewargs__", (PyCFunction)float_getnewargs, METH_NOARGS}, + {"__getformat__", (PyCFunction)float_getformat, + METH_O|METH_CLASS, float_getformat_doc}, + {"__setformat__", (PyCFunction)float_setformat, + METH_VARARGS|METH_CLASS, float_setformat_doc}, + {"__format__", (PyCFunction)float__format__, + METH_VARARGS, float__format__doc}, + {NULL, NULL} /* sentinel */ }; static PyGetSetDef float_getset[] = { - {"real", + {"real", (getter)float_float, (setter)NULL, "the real part of a complex number", NULL}, - {"imag", + {"imag", (getter)float_getzero, (setter)NULL, "the imaginary part of a complex number", NULL}, @@ -1760,229 +1760,229 @@ static PyNumberMethods float_as_number = { - float_add, /*nb_add*/ - float_sub, /*nb_subtract*/ - float_mul, /*nb_multiply*/ - float_rem, /*nb_remainder*/ - float_divmod, /*nb_divmod*/ - float_pow, /*nb_power*/ - (unaryfunc)float_neg, /*nb_negative*/ - (unaryfunc)float_float, /*nb_positive*/ - (unaryfunc)float_abs, /*nb_absolute*/ - (inquiry)float_bool, /*nb_bool*/ - 0, /*nb_invert*/ - 0, /*nb_lshift*/ - 0, /*nb_rshift*/ - 0, /*nb_and*/ - 0, /*nb_xor*/ - 0, /*nb_or*/ - float_trunc, /*nb_int*/ - 0, /*nb_reserved*/ - float_float, /*nb_float*/ - 0, /* nb_inplace_add */ - 0, /* nb_inplace_subtract */ - 0, /* nb_inplace_multiply */ - 0, /* nb_inplace_remainder */ - 0, /* nb_inplace_power */ - 0, /* nb_inplace_lshift */ - 0, /* nb_inplace_rshift */ - 0, /* nb_inplace_and */ - 0, /* nb_inplace_xor */ - 0, /* nb_inplace_or */ - float_floor_div, /* nb_floor_divide */ - float_div, /* nb_true_divide */ - 0, /* nb_inplace_floor_divide */ - 0, /* nb_inplace_true_divide */ + float_add, /*nb_add*/ + float_sub, /*nb_subtract*/ + float_mul, /*nb_multiply*/ + float_rem, /*nb_remainder*/ + float_divmod, /*nb_divmod*/ + float_pow, /*nb_power*/ + (unaryfunc)float_neg, /*nb_negative*/ + (unaryfunc)float_float, /*nb_positive*/ + (unaryfunc)float_abs, /*nb_absolute*/ + (inquiry)float_bool, /*nb_bool*/ + 0, /*nb_invert*/ + 0, /*nb_lshift*/ + 0, /*nb_rshift*/ + 0, /*nb_and*/ + 0, /*nb_xor*/ + 0, /*nb_or*/ + float_trunc, /*nb_int*/ + 0, /*nb_reserved*/ + float_float, /*nb_float*/ + 0, /* nb_inplace_add */ + 0, /* nb_inplace_subtract */ + 0, /* nb_inplace_multiply */ + 0, /* nb_inplace_remainder */ + 0, /* nb_inplace_power */ + 0, /* nb_inplace_lshift */ + 0, /* nb_inplace_rshift */ + 0, /* nb_inplace_and */ + 0, /* nb_inplace_xor */ + 0, /* nb_inplace_or */ + float_floor_div, /* nb_floor_divide */ + float_div, /* nb_true_divide */ + 0, /* nb_inplace_floor_divide */ + 0, /* nb_inplace_true_divide */ }; PyTypeObject PyFloat_Type = { - PyVarObject_HEAD_INIT(&PyType_Type, 0) - "float", - sizeof(PyFloatObject), - 0, - (destructor)float_dealloc, /* tp_dealloc */ - 0, /* tp_print */ - 0, /* tp_getattr */ - 0, /* tp_setattr */ - 0, /* tp_reserved */ - (reprfunc)float_repr, /* tp_repr */ - &float_as_number, /* tp_as_number */ - 0, /* tp_as_sequence */ - 0, /* tp_as_mapping */ - (hashfunc)float_hash, /* tp_hash */ - 0, /* tp_call */ - (reprfunc)float_str, /* tp_str */ - PyObject_GenericGetAttr, /* tp_getattro */ - 0, /* tp_setattro */ - 0, /* tp_as_buffer */ - Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */ - float_doc, /* tp_doc */ - 0, /* tp_traverse */ - 0, /* tp_clear */ - float_richcompare, /* tp_richcompare */ - 0, /* tp_weaklistoffset */ - 0, /* tp_iter */ - 0, /* tp_iternext */ - float_methods, /* tp_methods */ - 0, /* tp_members */ - float_getset, /* tp_getset */ - 0, /* tp_base */ - 0, /* tp_dict */ - 0, /* tp_descr_get */ - 0, /* tp_descr_set */ - 0, /* tp_dictoffset */ - 0, /* tp_init */ - 0, /* tp_alloc */ - float_new, /* tp_new */ + PyVarObject_HEAD_INIT(&PyType_Type, 0) + "float", + sizeof(PyFloatObject), + 0, + (destructor)float_dealloc, /* tp_dealloc */ + 0, /* tp_print */ + 0, /* tp_getattr */ + 0, /* tp_setattr */ + 0, /* tp_reserved */ + (reprfunc)float_repr, /* tp_repr */ + &float_as_number, /* tp_as_number */ + 0, /* tp_as_sequence */ + 0, /* tp_as_mapping */ + (hashfunc)float_hash, /* tp_hash */ + 0, /* tp_call */ + (reprfunc)float_str, /* tp_str */ + PyObject_GenericGetAttr, /* tp_getattro */ + 0, /* tp_setattro */ + 0, /* tp_as_buffer */ + Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */ + float_doc, /* tp_doc */ + 0, /* tp_traverse */ + 0, /* tp_clear */ + float_richcompare, /* tp_richcompare */ + 0, /* tp_weaklistoffset */ + 0, /* tp_iter */ + 0, /* tp_iternext */ + float_methods, /* tp_methods */ + 0, /* tp_members */ + float_getset, /* tp_getset */ + 0, /* tp_base */ + 0, /* tp_dict */ + 0, /* tp_descr_get */ + 0, /* tp_descr_set */ + 0, /* tp_dictoffset */ + 0, /* tp_init */ + 0, /* tp_alloc */ + float_new, /* tp_new */ }; void _PyFloat_Init(void) { - /* We attempt to determine if this machine is using IEEE - floating point formats by peering at the bits of some - carefully chosen values. If it looks like we are on an - IEEE platform, the float packing/unpacking routines can - just copy bits, if not they resort to arithmetic & shifts - and masks. The shifts & masks approach works on all finite - values, but what happens to infinities, NaNs and signed - zeroes on packing is an accident, and attempting to unpack - a NaN or an infinity will raise an exception. - - Note that if we're on some whacked-out platform which uses - IEEE formats but isn't strictly little-endian or big- - endian, we will fall back to the portable shifts & masks - method. */ + /* We attempt to determine if this machine is using IEEE + floating point formats by peering at the bits of some + carefully chosen values. If it looks like we are on an + IEEE platform, the float packing/unpacking routines can + just copy bits, if not they resort to arithmetic & shifts + and masks. The shifts & masks approach works on all finite + values, but what happens to infinities, NaNs and signed + zeroes on packing is an accident, and attempting to unpack + a NaN or an infinity will raise an exception. + + Note that if we're on some whacked-out platform which uses + IEEE formats but isn't strictly little-endian or big- + endian, we will fall back to the portable shifts & masks + method. */ #if SIZEOF_DOUBLE == 8 - { - double x = 9006104071832581.0; - if (memcmp(&x, "\x43\x3f\xff\x01\x02\x03\x04\x05", 8) == 0) - detected_double_format = ieee_big_endian_format; - else if (memcmp(&x, "\x05\x04\x03\x02\x01\xff\x3f\x43", 8) == 0) - detected_double_format = ieee_little_endian_format; - else - detected_double_format = unknown_format; - } + { + double x = 9006104071832581.0; + if (memcmp(&x, "\x43\x3f\xff\x01\x02\x03\x04\x05", 8) == 0) + detected_double_format = ieee_big_endian_format; + else if (memcmp(&x, "\x05\x04\x03\x02\x01\xff\x3f\x43", 8) == 0) + detected_double_format = ieee_little_endian_format; + else + detected_double_format = unknown_format; + } #else - detected_double_format = unknown_format; + detected_double_format = unknown_format; #endif #if SIZEOF_FLOAT == 4 - { - float y = 16711938.0; - if (memcmp(&y, "\x4b\x7f\x01\x02", 4) == 0) - detected_float_format = ieee_big_endian_format; - else if (memcmp(&y, "\x02\x01\x7f\x4b", 4) == 0) - detected_float_format = ieee_little_endian_format; - else - detected_float_format = unknown_format; - } + { + float y = 16711938.0; + if (memcmp(&y, "\x4b\x7f\x01\x02", 4) == 0) + detected_float_format = ieee_big_endian_format; + else if (memcmp(&y, "\x02\x01\x7f\x4b", 4) == 0) + detected_float_format = ieee_little_endian_format; + else + detected_float_format = unknown_format; + } #else - detected_float_format = unknown_format; + detected_float_format = unknown_format; #endif - double_format = detected_double_format; - float_format = detected_float_format; + double_format = detected_double_format; + float_format = detected_float_format; - /* Init float info */ - if (FloatInfoType.tp_name == 0) - PyStructSequence_InitType(&FloatInfoType, &floatinfo_desc); + /* Init float info */ + if (FloatInfoType.tp_name == 0) + PyStructSequence_InitType(&FloatInfoType, &floatinfo_desc); } int PyFloat_ClearFreeList(void) { - PyFloatObject *p; - PyFloatBlock *list, *next; - int i; - int u; /* remaining unfreed floats per block */ - int freelist_size = 0; - - list = block_list; - block_list = NULL; - free_list = NULL; - while (list != NULL) { - u = 0; - for (i = 0, p = &list->objects[0]; - i < N_FLOATOBJECTS; - i++, p++) { - if (PyFloat_CheckExact(p) && Py_REFCNT(p) != 0) - u++; - } - next = list->next; - if (u) { - list->next = block_list; - block_list = list; - for (i = 0, p = &list->objects[0]; - i < N_FLOATOBJECTS; - i++, p++) { - if (!PyFloat_CheckExact(p) || - Py_REFCNT(p) == 0) { - Py_TYPE(p) = (struct _typeobject *) - free_list; - free_list = p; - } - } - } - else { - PyMem_FREE(list); - } - freelist_size += u; - list = next; - } - return freelist_size; + PyFloatObject *p; + PyFloatBlock *list, *next; + int i; + int u; /* remaining unfreed floats per block */ + int freelist_size = 0; + + list = block_list; + block_list = NULL; + free_list = NULL; + while (list != NULL) { + u = 0; + for (i = 0, p = &list->objects[0]; + i < N_FLOATOBJECTS; + i++, p++) { + if (PyFloat_CheckExact(p) && Py_REFCNT(p) != 0) + u++; + } + next = list->next; + if (u) { + list->next = block_list; + block_list = list; + for (i = 0, p = &list->objects[0]; + i < N_FLOATOBJECTS; + i++, p++) { + if (!PyFloat_CheckExact(p) || + Py_REFCNT(p) == 0) { + Py_TYPE(p) = (struct _typeobject *) + free_list; + free_list = p; + } + } + } + else { + PyMem_FREE(list); + } + freelist_size += u; + list = next; + } + return freelist_size; } void PyFloat_Fini(void) { - PyFloatObject *p; - PyFloatBlock *list; - int i; - int u; /* total unfreed floats per block */ - - u = PyFloat_ClearFreeList(); - - if (!Py_VerboseFlag) - return; - fprintf(stderr, "# cleanup floats"); - if (!u) { - fprintf(stderr, "\n"); - } - else { - fprintf(stderr, - ": %d unfreed float%s\n", - u, u == 1 ? "" : "s"); - } - if (Py_VerboseFlag > 1) { - list = block_list; - while (list != NULL) { - for (i = 0, p = &list->objects[0]; - i < N_FLOATOBJECTS; - i++, p++) { - if (PyFloat_CheckExact(p) && - Py_REFCNT(p) != 0) { - char *buf = PyOS_double_to_string( - PyFloat_AS_DOUBLE(p), 'r', - 0, 0, NULL); - if (buf) { - /* XXX(twouters) cast - refcount to long - until %zd is - universally - available - */ - fprintf(stderr, - "# \n", - p, (long)Py_REFCNT(p), buf); - PyMem_Free(buf); - } - } - } - list = list->next; - } - } + PyFloatObject *p; + PyFloatBlock *list; + int i; + int u; /* total unfreed floats per block */ + + u = PyFloat_ClearFreeList(); + + if (!Py_VerboseFlag) + return; + fprintf(stderr, "# cleanup floats"); + if (!u) { + fprintf(stderr, "\n"); + } + else { + fprintf(stderr, + ": %d unfreed float%s\n", + u, u == 1 ? "" : "s"); + } + if (Py_VerboseFlag > 1) { + list = block_list; + while (list != NULL) { + for (i = 0, p = &list->objects[0]; + i < N_FLOATOBJECTS; + i++, p++) { + if (PyFloat_CheckExact(p) && + Py_REFCNT(p) != 0) { + char *buf = PyOS_double_to_string( + PyFloat_AS_DOUBLE(p), 'r', + 0, 0, NULL); + if (buf) { + /* XXX(twouters) cast + refcount to long + until %zd is + universally + available + */ + fprintf(stderr, + "# \n", + p, (long)Py_REFCNT(p), buf); + PyMem_Free(buf); + } + } + } + list = list->next; + } + } } /*---------------------------------------------------------------------------- @@ -1991,406 +1991,406 @@ int _PyFloat_Pack4(double x, unsigned char *p, int le) { - if (float_format == unknown_format) { - unsigned char sign; - int e; - double f; - unsigned int fbits; - int incr = 1; - - if (le) { - p += 3; - incr = -1; - } - - if (x < 0) { - sign = 1; - x = -x; - } - else - sign = 0; - - f = frexp(x, &e); - - /* Normalize f to be in the range [1.0, 2.0) */ - if (0.5 <= f && f < 1.0) { - f *= 2.0; - e--; - } - else if (f == 0.0) - e = 0; - else { - PyErr_SetString(PyExc_SystemError, - "frexp() result out of range"); - return -1; - } - - if (e >= 128) - goto Overflow; - else if (e < -126) { - /* Gradual underflow */ - f = ldexp(f, 126 + e); - e = 0; - } - else if (!(e == 0 && f == 0.0)) { - e += 127; - f -= 1.0; /* Get rid of leading 1 */ - } - - f *= 8388608.0; /* 2**23 */ - fbits = (unsigned int)(f + 0.5); /* Round */ - assert(fbits <= 8388608); - if (fbits >> 23) { - /* The carry propagated out of a string of 23 1 bits. */ - fbits = 0; - ++e; - if (e >= 255) - goto Overflow; - } - - /* First byte */ - *p = (sign << 7) | (e >> 1); - p += incr; - - /* Second byte */ - *p = (char) (((e & 1) << 7) | (fbits >> 16)); - p += incr; - - /* Third byte */ - *p = (fbits >> 8) & 0xFF; - p += incr; - - /* Fourth byte */ - *p = fbits & 0xFF; - - /* Done */ - return 0; - - } - else { - float y = (float)x; - const char *s = (char*)&y; - int i, incr = 1; - - if (Py_IS_INFINITY(y) && !Py_IS_INFINITY(x)) - goto Overflow; - - if ((float_format == ieee_little_endian_format && !le) - || (float_format == ieee_big_endian_format && le)) { - p += 3; - incr = -1; - } - - for (i = 0; i < 4; i++) { - *p = *s++; - p += incr; - } - return 0; - } + if (float_format == unknown_format) { + unsigned char sign; + int e; + double f; + unsigned int fbits; + int incr = 1; + + if (le) { + p += 3; + incr = -1; + } + + if (x < 0) { + sign = 1; + x = -x; + } + else + sign = 0; + + f = frexp(x, &e); + + /* Normalize f to be in the range [1.0, 2.0) */ + if (0.5 <= f && f < 1.0) { + f *= 2.0; + e--; + } + else if (f == 0.0) + e = 0; + else { + PyErr_SetString(PyExc_SystemError, + "frexp() result out of range"); + return -1; + } + + if (e >= 128) + goto Overflow; + else if (e < -126) { + /* Gradual underflow */ + f = ldexp(f, 126 + e); + e = 0; + } + else if (!(e == 0 && f == 0.0)) { + e += 127; + f -= 1.0; /* Get rid of leading 1 */ + } + + f *= 8388608.0; /* 2**23 */ + fbits = (unsigned int)(f + 0.5); /* Round */ + assert(fbits <= 8388608); + if (fbits >> 23) { + /* The carry propagated out of a string of 23 1 bits. */ + fbits = 0; + ++e; + if (e >= 255) + goto Overflow; + } + + /* First byte */ + *p = (sign << 7) | (e >> 1); + p += incr; + + /* Second byte */ + *p = (char) (((e & 1) << 7) | (fbits >> 16)); + p += incr; + + /* Third byte */ + *p = (fbits >> 8) & 0xFF; + p += incr; + + /* Fourth byte */ + *p = fbits & 0xFF; + + /* Done */ + return 0; + + } + else { + float y = (float)x; + const char *s = (char*)&y; + int i, incr = 1; + + if (Py_IS_INFINITY(y) && !Py_IS_INFINITY(x)) + goto Overflow; + + if ((float_format == ieee_little_endian_format && !le) + || (float_format == ieee_big_endian_format && le)) { + p += 3; + incr = -1; + } + + for (i = 0; i < 4; i++) { + *p = *s++; + p += incr; + } + return 0; + } Overflow: - PyErr_SetString(PyExc_OverflowError, - "float too large to pack with f format"); - return -1; + PyErr_SetString(PyExc_OverflowError, + "float too large to pack with f format"); + return -1; } int _PyFloat_Pack8(double x, unsigned char *p, int le) { - if (double_format == unknown_format) { - unsigned char sign; - int e; - double f; - unsigned int fhi, flo; - int incr = 1; - - if (le) { - p += 7; - incr = -1; - } - - if (x < 0) { - sign = 1; - x = -x; - } - else - sign = 0; - - f = frexp(x, &e); - - /* Normalize f to be in the range [1.0, 2.0) */ - if (0.5 <= f && f < 1.0) { - f *= 2.0; - e--; - } - else if (f == 0.0) - e = 0; - else { - PyErr_SetString(PyExc_SystemError, - "frexp() result out of range"); - return -1; - } - - if (e >= 1024) - goto Overflow; - else if (e < -1022) { - /* Gradual underflow */ - f = ldexp(f, 1022 + e); - e = 0; - } - else if (!(e == 0 && f == 0.0)) { - e += 1023; - f -= 1.0; /* Get rid of leading 1 */ - } - - /* fhi receives the high 28 bits; flo the low 24 bits (== 52 bits) */ - f *= 268435456.0; /* 2**28 */ - fhi = (unsigned int)f; /* Truncate */ - assert(fhi < 268435456); - - f -= (double)fhi; - f *= 16777216.0; /* 2**24 */ - flo = (unsigned int)(f + 0.5); /* Round */ - assert(flo <= 16777216); - if (flo >> 24) { - /* The carry propagated out of a string of 24 1 bits. */ - flo = 0; - ++fhi; - if (fhi >> 28) { - /* And it also progagated out of the next 28 bits. */ - fhi = 0; - ++e; - if (e >= 2047) - goto Overflow; - } - } - - /* First byte */ - *p = (sign << 7) | (e >> 4); - p += incr; - - /* Second byte */ - *p = (unsigned char) (((e & 0xF) << 4) | (fhi >> 24)); - p += incr; - - /* Third byte */ - *p = (fhi >> 16) & 0xFF; - p += incr; - - /* Fourth byte */ - *p = (fhi >> 8) & 0xFF; - p += incr; - - /* Fifth byte */ - *p = fhi & 0xFF; - p += incr; - - /* Sixth byte */ - *p = (flo >> 16) & 0xFF; - p += incr; - - /* Seventh byte */ - *p = (flo >> 8) & 0xFF; - p += incr; - - /* Eighth byte */ - *p = flo & 0xFF; - p += incr; - - /* Done */ - return 0; - - Overflow: - PyErr_SetString(PyExc_OverflowError, - "float too large to pack with d format"); - return -1; - } - else { - const char *s = (char*)&x; - int i, incr = 1; - - if ((double_format == ieee_little_endian_format && !le) - || (double_format == ieee_big_endian_format && le)) { - p += 7; - incr = -1; - } - - for (i = 0; i < 8; i++) { - *p = *s++; - p += incr; - } - return 0; - } + if (double_format == unknown_format) { + unsigned char sign; + int e; + double f; + unsigned int fhi, flo; + int incr = 1; + + if (le) { + p += 7; + incr = -1; + } + + if (x < 0) { + sign = 1; + x = -x; + } + else + sign = 0; + + f = frexp(x, &e); + + /* Normalize f to be in the range [1.0, 2.0) */ + if (0.5 <= f && f < 1.0) { + f *= 2.0; + e--; + } + else if (f == 0.0) + e = 0; + else { + PyErr_SetString(PyExc_SystemError, + "frexp() result out of range"); + return -1; + } + + if (e >= 1024) + goto Overflow; + else if (e < -1022) { + /* Gradual underflow */ + f = ldexp(f, 1022 + e); + e = 0; + } + else if (!(e == 0 && f == 0.0)) { + e += 1023; + f -= 1.0; /* Get rid of leading 1 */ + } + + /* fhi receives the high 28 bits; flo the low 24 bits (== 52 bits) */ + f *= 268435456.0; /* 2**28 */ + fhi = (unsigned int)f; /* Truncate */ + assert(fhi < 268435456); + + f -= (double)fhi; + f *= 16777216.0; /* 2**24 */ + flo = (unsigned int)(f + 0.5); /* Round */ + assert(flo <= 16777216); + if (flo >> 24) { + /* The carry propagated out of a string of 24 1 bits. */ + flo = 0; + ++fhi; + if (fhi >> 28) { + /* And it also progagated out of the next 28 bits. */ + fhi = 0; + ++e; + if (e >= 2047) + goto Overflow; + } + } + + /* First byte */ + *p = (sign << 7) | (e >> 4); + p += incr; + + /* Second byte */ + *p = (unsigned char) (((e & 0xF) << 4) | (fhi >> 24)); + p += incr; + + /* Third byte */ + *p = (fhi >> 16) & 0xFF; + p += incr; + + /* Fourth byte */ + *p = (fhi >> 8) & 0xFF; + p += incr; + + /* Fifth byte */ + *p = fhi & 0xFF; + p += incr; + + /* Sixth byte */ + *p = (flo >> 16) & 0xFF; + p += incr; + + /* Seventh byte */ + *p = (flo >> 8) & 0xFF; + p += incr; + + /* Eighth byte */ + *p = flo & 0xFF; + p += incr; + + /* Done */ + return 0; + + Overflow: + PyErr_SetString(PyExc_OverflowError, + "float too large to pack with d format"); + return -1; + } + else { + const char *s = (char*)&x; + int i, incr = 1; + + if ((double_format == ieee_little_endian_format && !le) + || (double_format == ieee_big_endian_format && le)) { + p += 7; + incr = -1; + } + + for (i = 0; i < 8; i++) { + *p = *s++; + p += incr; + } + return 0; + } } double _PyFloat_Unpack4(const unsigned char *p, int le) { - if (float_format == unknown_format) { - unsigned char sign; - int e; - unsigned int f; - double x; - int incr = 1; - - if (le) { - p += 3; - incr = -1; - } - - /* First byte */ - sign = (*p >> 7) & 1; - e = (*p & 0x7F) << 1; - p += incr; - - /* Second byte */ - e |= (*p >> 7) & 1; - f = (*p & 0x7F) << 16; - p += incr; - - if (e == 255) { - PyErr_SetString( - PyExc_ValueError, - "can't unpack IEEE 754 special value " - "on non-IEEE platform"); - return -1; - } - - /* Third byte */ - f |= *p << 8; - p += incr; - - /* Fourth byte */ - f |= *p; - - x = (double)f / 8388608.0; - - /* XXX This sadly ignores Inf/NaN issues */ - if (e == 0) - e = -126; - else { - x += 1.0; - e -= 127; - } - x = ldexp(x, e); - - if (sign) - x = -x; - - return x; - } - else { - float x; - - if ((float_format == ieee_little_endian_format && !le) - || (float_format == ieee_big_endian_format && le)) { - char buf[4]; - char *d = &buf[3]; - int i; - - for (i = 0; i < 4; i++) { - *d-- = *p++; - } - memcpy(&x, buf, 4); - } - else { - memcpy(&x, p, 4); - } + if (float_format == unknown_format) { + unsigned char sign; + int e; + unsigned int f; + double x; + int incr = 1; + + if (le) { + p += 3; + incr = -1; + } + + /* First byte */ + sign = (*p >> 7) & 1; + e = (*p & 0x7F) << 1; + p += incr; + + /* Second byte */ + e |= (*p >> 7) & 1; + f = (*p & 0x7F) << 16; + p += incr; + + if (e == 255) { + PyErr_SetString( + PyExc_ValueError, + "can't unpack IEEE 754 special value " + "on non-IEEE platform"); + return -1; + } + + /* Third byte */ + f |= *p << 8; + p += incr; + + /* Fourth byte */ + f |= *p; + + x = (double)f / 8388608.0; + + /* XXX This sadly ignores Inf/NaN issues */ + if (e == 0) + e = -126; + else { + x += 1.0; + e -= 127; + } + x = ldexp(x, e); + + if (sign) + x = -x; + + return x; + } + else { + float x; + + if ((float_format == ieee_little_endian_format && !le) + || (float_format == ieee_big_endian_format && le)) { + char buf[4]; + char *d = &buf[3]; + int i; + + for (i = 0; i < 4; i++) { + *d-- = *p++; + } + memcpy(&x, buf, 4); + } + else { + memcpy(&x, p, 4); + } - return x; - } + return x; + } } double _PyFloat_Unpack8(const unsigned char *p, int le) { - if (double_format == unknown_format) { - unsigned char sign; - int e; - unsigned int fhi, flo; - double x; - int incr = 1; - - if (le) { - p += 7; - incr = -1; - } - - /* First byte */ - sign = (*p >> 7) & 1; - e = (*p & 0x7F) << 4; - - p += incr; - - /* Second byte */ - e |= (*p >> 4) & 0xF; - fhi = (*p & 0xF) << 24; - p += incr; - - if (e == 2047) { - PyErr_SetString( - PyExc_ValueError, - "can't unpack IEEE 754 special value " - "on non-IEEE platform"); - return -1.0; - } - - /* Third byte */ - fhi |= *p << 16; - p += incr; - - /* Fourth byte */ - fhi |= *p << 8; - p += incr; - - /* Fifth byte */ - fhi |= *p; - p += incr; - - /* Sixth byte */ - flo = *p << 16; - p += incr; - - /* Seventh byte */ - flo |= *p << 8; - p += incr; - - /* Eighth byte */ - flo |= *p; - - x = (double)fhi + (double)flo / 16777216.0; /* 2**24 */ - x /= 268435456.0; /* 2**28 */ - - if (e == 0) - e = -1022; - else { - x += 1.0; - e -= 1023; - } - x = ldexp(x, e); - - if (sign) - x = -x; - - return x; - } - else { - double x; - - if ((double_format == ieee_little_endian_format && !le) - || (double_format == ieee_big_endian_format && le)) { - char buf[8]; - char *d = &buf[7]; - int i; - - for (i = 0; i < 8; i++) { - *d-- = *p++; - } - memcpy(&x, buf, 8); - } - else { - memcpy(&x, p, 8); - } + if (double_format == unknown_format) { + unsigned char sign; + int e; + unsigned int fhi, flo; + double x; + int incr = 1; + + if (le) { + p += 7; + incr = -1; + } + + /* First byte */ + sign = (*p >> 7) & 1; + e = (*p & 0x7F) << 4; + + p += incr; + + /* Second byte */ + e |= (*p >> 4) & 0xF; + fhi = (*p & 0xF) << 24; + p += incr; + + if (e == 2047) { + PyErr_SetString( + PyExc_ValueError, + "can't unpack IEEE 754 special value " + "on non-IEEE platform"); + return -1.0; + } + + /* Third byte */ + fhi |= *p << 16; + p += incr; + + /* Fourth byte */ + fhi |= *p << 8; + p += incr; + + /* Fifth byte */ + fhi |= *p; + p += incr; + + /* Sixth byte */ + flo = *p << 16; + p += incr; + + /* Seventh byte */ + flo |= *p << 8; + p += incr; + + /* Eighth byte */ + flo |= *p; + + x = (double)fhi + (double)flo / 16777216.0; /* 2**24 */ + x /= 268435456.0; /* 2**28 */ + + if (e == 0) + e = -1022; + else { + x += 1.0; + e -= 1023; + } + x = ldexp(x, e); + + if (sign) + x = -x; + + return x; + } + else { + double x; + + if ((double_format == ieee_little_endian_format && !le) + || (double_format == ieee_big_endian_format && le)) { + char buf[8]; + char *d = &buf[7]; + int i; + + for (i = 0; i < 8; i++) { + *d-- = *p++; + } + memcpy(&x, buf, 8); + } + else { + memcpy(&x, p, 8); + } - return x; - } + return x; + } } Modified: python/branches/release31-maint/Objects/frameobject.c ============================================================================== --- python/branches/release31-maint/Objects/frameobject.c (original) +++ python/branches/release31-maint/Objects/frameobject.c Sun May 9 18:14:21 2010 @@ -15,37 +15,37 @@ #define OFF(x) offsetof(PyFrameObject, x) static PyMemberDef frame_memberlist[] = { - {"f_back", T_OBJECT, OFF(f_back), READONLY}, - {"f_code", T_OBJECT, OFF(f_code), READONLY}, - {"f_builtins", T_OBJECT, OFF(f_builtins),READONLY}, - {"f_globals", T_OBJECT, OFF(f_globals), READONLY}, - {"f_lasti", T_INT, OFF(f_lasti), READONLY}, - {NULL} /* Sentinel */ + {"f_back", T_OBJECT, OFF(f_back), READONLY}, + {"f_code", T_OBJECT, OFF(f_code), READONLY}, + {"f_builtins", T_OBJECT, OFF(f_builtins),READONLY}, + {"f_globals", T_OBJECT, OFF(f_globals), READONLY}, + {"f_lasti", T_INT, OFF(f_lasti), READONLY}, + {NULL} /* Sentinel */ }; static PyObject * frame_getlocals(PyFrameObject *f, void *closure) { - PyFrame_FastToLocals(f); - Py_INCREF(f->f_locals); - return f->f_locals; + PyFrame_FastToLocals(f); + Py_INCREF(f->f_locals); + return f->f_locals; } static PyObject * frame_getlineno(PyFrameObject *f, void *closure) { - int lineno; + int lineno; - if (f->f_trace) - lineno = f->f_lineno; - else - lineno = PyCode_Addr2Line(f->f_code, f->f_lasti); + if (f->f_trace) + lineno = f->f_lineno; + else + lineno = PyCode_Addr2Line(f->f_code, f->f_lasti); - return PyLong_FromLong(lineno); + return PyLong_FromLong(lineno); } /* Setter for f_lineno - you can set f_lineno from within a trace function in - * order to jump to a given line of code, subject to some restrictions. Most + * order to jump to a given line of code, subject to some restrictions. Most * lines are OK to jump to because they don't make any assumptions about the * state of the stack (obvious because you could remove the line and the code * would still work without any stack errors), but there are some constructs @@ -62,311 +62,311 @@ static int frame_setlineno(PyFrameObject *f, PyObject* p_new_lineno) { - int new_lineno = 0; /* The new value of f_lineno */ - long l_new_lineno; - int overflow; - int new_lasti = 0; /* The new value of f_lasti */ - int new_iblock = 0; /* The new value of f_iblock */ - unsigned char *code = NULL; /* The bytecode for the frame... */ - Py_ssize_t code_len = 0; /* ...and its length */ - unsigned char *lnotab = NULL; /* Iterating over co_lnotab */ - Py_ssize_t lnotab_len = 0; /* (ditto) */ - int offset = 0; /* (ditto) */ - int line = 0; /* (ditto) */ - int addr = 0; /* (ditto) */ - int min_addr = 0; /* Scanning the SETUPs and POPs */ - int max_addr = 0; /* (ditto) */ - int delta_iblock = 0; /* (ditto) */ - int min_delta_iblock = 0; /* (ditto) */ - int min_iblock = 0; /* (ditto) */ - int f_lasti_setup_addr = 0; /* Policing no-jump-into-finally */ - int new_lasti_setup_addr = 0; /* (ditto) */ - int blockstack[CO_MAXBLOCKS]; /* Walking the 'finally' blocks */ - int in_finally[CO_MAXBLOCKS]; /* (ditto) */ - int blockstack_top = 0; /* (ditto) */ - unsigned char setup_op = 0; /* (ditto) */ - - /* f_lineno must be an integer. */ - if (!PyLong_CheckExact(p_new_lineno)) { - PyErr_SetString(PyExc_ValueError, - "lineno must be an integer"); - return -1; - } - - /* You can only do this from within a trace function, not via - * _getframe or similar hackery. */ - if (!f->f_trace) - { - PyErr_Format(PyExc_ValueError, - "f_lineno can only be set by a" - " line trace function"); - return -1; - } - - /* Fail if the line comes before the start of the code block. */ - l_new_lineno = PyLong_AsLongAndOverflow(p_new_lineno, &overflow); - if (overflow + int new_lineno = 0; /* The new value of f_lineno */ + long l_new_lineno; + int overflow; + int new_lasti = 0; /* The new value of f_lasti */ + int new_iblock = 0; /* The new value of f_iblock */ + unsigned char *code = NULL; /* The bytecode for the frame... */ + Py_ssize_t code_len = 0; /* ...and its length */ + unsigned char *lnotab = NULL; /* Iterating over co_lnotab */ + Py_ssize_t lnotab_len = 0; /* (ditto) */ + int offset = 0; /* (ditto) */ + int line = 0; /* (ditto) */ + int addr = 0; /* (ditto) */ + int min_addr = 0; /* Scanning the SETUPs and POPs */ + int max_addr = 0; /* (ditto) */ + int delta_iblock = 0; /* (ditto) */ + int min_delta_iblock = 0; /* (ditto) */ + int min_iblock = 0; /* (ditto) */ + int f_lasti_setup_addr = 0; /* Policing no-jump-into-finally */ + int new_lasti_setup_addr = 0; /* (ditto) */ + int blockstack[CO_MAXBLOCKS]; /* Walking the 'finally' blocks */ + int in_finally[CO_MAXBLOCKS]; /* (ditto) */ + int blockstack_top = 0; /* (ditto) */ + unsigned char setup_op = 0; /* (ditto) */ + + /* f_lineno must be an integer. */ + if (!PyLong_CheckExact(p_new_lineno)) { + PyErr_SetString(PyExc_ValueError, + "lineno must be an integer"); + return -1; + } + + /* You can only do this from within a trace function, not via + * _getframe or similar hackery. */ + if (!f->f_trace) + { + PyErr_Format(PyExc_ValueError, + "f_lineno can only be set by a" + " line trace function"); + return -1; + } + + /* Fail if the line comes before the start of the code block. */ + l_new_lineno = PyLong_AsLongAndOverflow(p_new_lineno, &overflow); + if (overflow #if SIZEOF_LONG > SIZEOF_INT - || l_new_lineno > INT_MAX - || l_new_lineno < INT_MIN + || l_new_lineno > INT_MAX + || l_new_lineno < INT_MIN #endif - ) { - PyErr_SetString(PyExc_ValueError, - "lineno out of range"); - return -1; - } - new_lineno = (int)l_new_lineno; - - if (new_lineno < f->f_code->co_firstlineno) { - PyErr_Format(PyExc_ValueError, - "line %d comes before the current code block", - new_lineno); - return -1; - } - else if (new_lineno == f->f_code->co_firstlineno) { - new_lasti = 0; - new_lineno = f->f_code->co_firstlineno; - } - else { - /* Find the bytecode offset for the start of the given - * line, or the first code-owning line after it. */ - char *tmp; - PyBytes_AsStringAndSize(f->f_code->co_lnotab, - &tmp, &lnotab_len); - lnotab = (unsigned char *) tmp; - addr = 0; - line = f->f_code->co_firstlineno; - new_lasti = -1; - for (offset = 0; offset < lnotab_len; offset += 2) { - addr += lnotab[offset]; - line += lnotab[offset+1]; - if (line >= new_lineno) { - new_lasti = addr; - new_lineno = line; - break; - } - } - } - - /* If we didn't reach the requested line, return an error. */ - if (new_lasti == -1) { - PyErr_Format(PyExc_ValueError, - "line %d comes after the current code block", - new_lineno); - return -1; - } - - /* We're now ready to look at the bytecode. */ - PyBytes_AsStringAndSize(f->f_code->co_code, (char **)&code, &code_len); - min_addr = MIN(new_lasti, f->f_lasti); - max_addr = MAX(new_lasti, f->f_lasti); - - /* You can't jump onto a line with an 'except' statement on it - - * they expect to have an exception on the top of the stack, which - * won't be true if you jump to them. They always start with code - * that either pops the exception using POP_TOP (plain 'except:' - * lines do this) or duplicates the exception on the stack using - * DUP_TOP (if there's an exception type specified). See compile.c, - * 'com_try_except' for the full details. There aren't any other - * cases (AFAIK) where a line's code can start with DUP_TOP or - * POP_TOP, but if any ever appear, they'll be subject to the same - * restriction (but with a different error message). */ - if (code[new_lasti] == DUP_TOP || code[new_lasti] == POP_TOP) { - PyErr_SetString(PyExc_ValueError, - "can't jump to 'except' line as there's no exception"); - return -1; - } - - /* You can't jump into or out of a 'finally' block because the 'try' - * block leaves something on the stack for the END_FINALLY to clean - * up. So we walk the bytecode, maintaining a simulated blockstack. - * When we reach the old or new address and it's in a 'finally' block - * we note the address of the corresponding SETUP_FINALLY. The jump - * is only legal if neither address is in a 'finally' block or - * they're both in the same one. 'blockstack' is a stack of the - * bytecode addresses of the SETUP_X opcodes, and 'in_finally' tracks - * whether we're in a 'finally' block at each blockstack level. */ - f_lasti_setup_addr = -1; - new_lasti_setup_addr = -1; - memset(blockstack, '\0', sizeof(blockstack)); - memset(in_finally, '\0', sizeof(in_finally)); - blockstack_top = 0; - for (addr = 0; addr < code_len; addr++) { - unsigned char op = code[addr]; - switch (op) { - case SETUP_LOOP: - case SETUP_EXCEPT: - case SETUP_FINALLY: - blockstack[blockstack_top++] = addr; - in_finally[blockstack_top-1] = 0; - break; - - case POP_BLOCK: - assert(blockstack_top > 0); - setup_op = code[blockstack[blockstack_top-1]]; - if (setup_op == SETUP_FINALLY) { - in_finally[blockstack_top-1] = 1; - } - else { - blockstack_top--; - } - break; - - case END_FINALLY: - /* Ignore END_FINALLYs for SETUP_EXCEPTs - they exist - * in the bytecode but don't correspond to an actual - * 'finally' block. (If blockstack_top is 0, we must - * be seeing such an END_FINALLY.) */ - if (blockstack_top > 0) { - setup_op = code[blockstack[blockstack_top-1]]; - if (setup_op == SETUP_FINALLY) { - blockstack_top--; - } - } - break; - } - - /* For the addresses we're interested in, see whether they're - * within a 'finally' block and if so, remember the address - * of the SETUP_FINALLY. */ - if (addr == new_lasti || addr == f->f_lasti) { - int i = 0; - int setup_addr = -1; - for (i = blockstack_top-1; i >= 0; i--) { - if (in_finally[i]) { - setup_addr = blockstack[i]; - break; - } - } - - if (setup_addr != -1) { - if (addr == new_lasti) { - new_lasti_setup_addr = setup_addr; - } - - if (addr == f->f_lasti) { - f_lasti_setup_addr = setup_addr; - } - } - } - - if (op >= HAVE_ARGUMENT) { - addr += 2; - } - } - - /* Verify that the blockstack tracking code didn't get lost. */ - assert(blockstack_top == 0); - - /* After all that, are we jumping into / out of a 'finally' block? */ - if (new_lasti_setup_addr != f_lasti_setup_addr) { - PyErr_SetString(PyExc_ValueError, - "can't jump into or out of a 'finally' block"); - return -1; - } - - - /* Police block-jumping (you can't jump into the middle of a block) - * and ensure that the blockstack finishes up in a sensible state (by - * popping any blocks we're jumping out of). We look at all the - * blockstack operations between the current position and the new - * one, and keep track of how many blocks we drop out of on the way. - * By also keeping track of the lowest blockstack position we see, we - * can tell whether the jump goes into any blocks without coming out - * again - in that case we raise an exception below. */ - delta_iblock = 0; - for (addr = min_addr; addr < max_addr; addr++) { - unsigned char op = code[addr]; - switch (op) { - case SETUP_LOOP: - case SETUP_EXCEPT: - case SETUP_FINALLY: - delta_iblock++; - break; - - case POP_BLOCK: - delta_iblock--; - break; - } - - min_delta_iblock = MIN(min_delta_iblock, delta_iblock); - - if (op >= HAVE_ARGUMENT) { - addr += 2; - } - } - - /* Derive the absolute iblock values from the deltas. */ - min_iblock = f->f_iblock + min_delta_iblock; - if (new_lasti > f->f_lasti) { - /* Forwards jump. */ - new_iblock = f->f_iblock + delta_iblock; - } - else { - /* Backwards jump. */ - new_iblock = f->f_iblock - delta_iblock; - } - - /* Are we jumping into a block? */ - if (new_iblock > min_iblock) { - PyErr_SetString(PyExc_ValueError, - "can't jump into the middle of a block"); - return -1; - } - - /* Pop any blocks that we're jumping out of. */ - while (f->f_iblock > new_iblock) { - PyTryBlock *b = &f->f_blockstack[--f->f_iblock]; - while ((f->f_stacktop - f->f_valuestack) > b->b_level) { - PyObject *v = (*--f->f_stacktop); - Py_DECREF(v); - } - } - - /* Finally set the new f_lineno and f_lasti and return OK. */ - f->f_lineno = new_lineno; - f->f_lasti = new_lasti; - return 0; + ) { + PyErr_SetString(PyExc_ValueError, + "lineno out of range"); + return -1; + } + new_lineno = (int)l_new_lineno; + + if (new_lineno < f->f_code->co_firstlineno) { + PyErr_Format(PyExc_ValueError, + "line %d comes before the current code block", + new_lineno); + return -1; + } + else if (new_lineno == f->f_code->co_firstlineno) { + new_lasti = 0; + new_lineno = f->f_code->co_firstlineno; + } + else { + /* Find the bytecode offset for the start of the given + * line, or the first code-owning line after it. */ + char *tmp; + PyBytes_AsStringAndSize(f->f_code->co_lnotab, + &tmp, &lnotab_len); + lnotab = (unsigned char *) tmp; + addr = 0; + line = f->f_code->co_firstlineno; + new_lasti = -1; + for (offset = 0; offset < lnotab_len; offset += 2) { + addr += lnotab[offset]; + line += lnotab[offset+1]; + if (line >= new_lineno) { + new_lasti = addr; + new_lineno = line; + break; + } + } + } + + /* If we didn't reach the requested line, return an error. */ + if (new_lasti == -1) { + PyErr_Format(PyExc_ValueError, + "line %d comes after the current code block", + new_lineno); + return -1; + } + + /* We're now ready to look at the bytecode. */ + PyBytes_AsStringAndSize(f->f_code->co_code, (char **)&code, &code_len); + min_addr = MIN(new_lasti, f->f_lasti); + max_addr = MAX(new_lasti, f->f_lasti); + + /* You can't jump onto a line with an 'except' statement on it - + * they expect to have an exception on the top of the stack, which + * won't be true if you jump to them. They always start with code + * that either pops the exception using POP_TOP (plain 'except:' + * lines do this) or duplicates the exception on the stack using + * DUP_TOP (if there's an exception type specified). See compile.c, + * 'com_try_except' for the full details. There aren't any other + * cases (AFAIK) where a line's code can start with DUP_TOP or + * POP_TOP, but if any ever appear, they'll be subject to the same + * restriction (but with a different error message). */ + if (code[new_lasti] == DUP_TOP || code[new_lasti] == POP_TOP) { + PyErr_SetString(PyExc_ValueError, + "can't jump to 'except' line as there's no exception"); + return -1; + } + + /* You can't jump into or out of a 'finally' block because the 'try' + * block leaves something on the stack for the END_FINALLY to clean + * up. So we walk the bytecode, maintaining a simulated blockstack. + * When we reach the old or new address and it's in a 'finally' block + * we note the address of the corresponding SETUP_FINALLY. The jump + * is only legal if neither address is in a 'finally' block or + * they're both in the same one. 'blockstack' is a stack of the + * bytecode addresses of the SETUP_X opcodes, and 'in_finally' tracks + * whether we're in a 'finally' block at each blockstack level. */ + f_lasti_setup_addr = -1; + new_lasti_setup_addr = -1; + memset(blockstack, '\0', sizeof(blockstack)); + memset(in_finally, '\0', sizeof(in_finally)); + blockstack_top = 0; + for (addr = 0; addr < code_len; addr++) { + unsigned char op = code[addr]; + switch (op) { + case SETUP_LOOP: + case SETUP_EXCEPT: + case SETUP_FINALLY: + blockstack[blockstack_top++] = addr; + in_finally[blockstack_top-1] = 0; + break; + + case POP_BLOCK: + assert(blockstack_top > 0); + setup_op = code[blockstack[blockstack_top-1]]; + if (setup_op == SETUP_FINALLY) { + in_finally[blockstack_top-1] = 1; + } + else { + blockstack_top--; + } + break; + + case END_FINALLY: + /* Ignore END_FINALLYs for SETUP_EXCEPTs - they exist + * in the bytecode but don't correspond to an actual + * 'finally' block. (If blockstack_top is 0, we must + * be seeing such an END_FINALLY.) */ + if (blockstack_top > 0) { + setup_op = code[blockstack[blockstack_top-1]]; + if (setup_op == SETUP_FINALLY) { + blockstack_top--; + } + } + break; + } + + /* For the addresses we're interested in, see whether they're + * within a 'finally' block and if so, remember the address + * of the SETUP_FINALLY. */ + if (addr == new_lasti || addr == f->f_lasti) { + int i = 0; + int setup_addr = -1; + for (i = blockstack_top-1; i >= 0; i--) { + if (in_finally[i]) { + setup_addr = blockstack[i]; + break; + } + } + + if (setup_addr != -1) { + if (addr == new_lasti) { + new_lasti_setup_addr = setup_addr; + } + + if (addr == f->f_lasti) { + f_lasti_setup_addr = setup_addr; + } + } + } + + if (op >= HAVE_ARGUMENT) { + addr += 2; + } + } + + /* Verify that the blockstack tracking code didn't get lost. */ + assert(blockstack_top == 0); + + /* After all that, are we jumping into / out of a 'finally' block? */ + if (new_lasti_setup_addr != f_lasti_setup_addr) { + PyErr_SetString(PyExc_ValueError, + "can't jump into or out of a 'finally' block"); + return -1; + } + + + /* Police block-jumping (you can't jump into the middle of a block) + * and ensure that the blockstack finishes up in a sensible state (by + * popping any blocks we're jumping out of). We look at all the + * blockstack operations between the current position and the new + * one, and keep track of how many blocks we drop out of on the way. + * By also keeping track of the lowest blockstack position we see, we + * can tell whether the jump goes into any blocks without coming out + * again - in that case we raise an exception below. */ + delta_iblock = 0; + for (addr = min_addr; addr < max_addr; addr++) { + unsigned char op = code[addr]; + switch (op) { + case SETUP_LOOP: + case SETUP_EXCEPT: + case SETUP_FINALLY: + delta_iblock++; + break; + + case POP_BLOCK: + delta_iblock--; + break; + } + + min_delta_iblock = MIN(min_delta_iblock, delta_iblock); + + if (op >= HAVE_ARGUMENT) { + addr += 2; + } + } + + /* Derive the absolute iblock values from the deltas. */ + min_iblock = f->f_iblock + min_delta_iblock; + if (new_lasti > f->f_lasti) { + /* Forwards jump. */ + new_iblock = f->f_iblock + delta_iblock; + } + else { + /* Backwards jump. */ + new_iblock = f->f_iblock - delta_iblock; + } + + /* Are we jumping into a block? */ + if (new_iblock > min_iblock) { + PyErr_SetString(PyExc_ValueError, + "can't jump into the middle of a block"); + return -1; + } + + /* Pop any blocks that we're jumping out of. */ + while (f->f_iblock > new_iblock) { + PyTryBlock *b = &f->f_blockstack[--f->f_iblock]; + while ((f->f_stacktop - f->f_valuestack) > b->b_level) { + PyObject *v = (*--f->f_stacktop); + Py_DECREF(v); + } + } + + /* Finally set the new f_lineno and f_lasti and return OK. */ + f->f_lineno = new_lineno; + f->f_lasti = new_lasti; + return 0; } static PyObject * frame_gettrace(PyFrameObject *f, void *closure) { - PyObject* trace = f->f_trace; + PyObject* trace = f->f_trace; - if (trace == NULL) - trace = Py_None; + if (trace == NULL) + trace = Py_None; - Py_INCREF(trace); + Py_INCREF(trace); - return trace; + return trace; } static int frame_settrace(PyFrameObject *f, PyObject* v, void *closure) { - /* We rely on f_lineno being accurate when f_trace is set. */ + /* We rely on f_lineno being accurate when f_trace is set. */ - PyObject* old_value = f->f_trace; + PyObject* old_value = f->f_trace; - Py_XINCREF(v); - f->f_trace = v; + Py_XINCREF(v); + f->f_trace = v; - if (v != NULL) - f->f_lineno = PyCode_Addr2Line(f->f_code, f->f_lasti); + if (v != NULL) + f->f_lineno = PyCode_Addr2Line(f->f_code, f->f_lasti); - Py_XDECREF(old_value); + Py_XDECREF(old_value); - return 0; + return 0; } static PyGetSetDef frame_getsetlist[] = { - {"f_locals", (getter)frame_getlocals, NULL, NULL}, - {"f_lineno", (getter)frame_getlineno, - (setter)frame_setlineno, NULL}, - {"f_trace", (getter)frame_gettrace, (setter)frame_settrace, NULL}, - {0} + {"f_locals", (getter)frame_getlocals, NULL, NULL}, + {"f_lineno", (getter)frame_getlineno, + (setter)frame_setlineno, NULL}, + {"f_trace", (getter)frame_gettrace, (setter)frame_settrace, NULL}, + {0} }; /* Stack frames are allocated and deallocated at a considerable rate. @@ -383,7 +383,7 @@ the following fields are still valid: * ob_type, ob_size, f_code, f_valuestack; - + * f_locals, f_trace, f_exc_type, f_exc_value, f_exc_traceback are NULL; @@ -394,10 +394,10 @@ integers are allocated in a special way -- see intobject.c). When a stack frame is on the free list, only the following members have a meaning: - ob_type == &Frametype - f_back next item on free list, or NULL - f_stacksize size of value stack - ob_size size of localsplus + ob_type == &Frametype + f_back next item on free list, or NULL + f_stacksize size of value stack + ob_size size of localsplus Note that the value and block stacks are preserved -- this can save another malloc() call or two (and two free() calls as well!). Also note that, unlike for integers, each frame object is a @@ -413,307 +413,307 @@ */ static PyFrameObject *free_list = NULL; -static int numfree = 0; /* number of frames currently in free_list */ +static int numfree = 0; /* number of frames currently in free_list */ /* max value for numfree */ -#define PyFrame_MAXFREELIST 200 +#define PyFrame_MAXFREELIST 200 static void frame_dealloc(PyFrameObject *f) { - PyObject **p, **valuestack; - PyCodeObject *co; + PyObject **p, **valuestack; + PyCodeObject *co; - PyObject_GC_UnTrack(f); - Py_TRASHCAN_SAFE_BEGIN(f) - /* Kill all local variables */ - valuestack = f->f_valuestack; - for (p = f->f_localsplus; p < valuestack; p++) - Py_CLEAR(*p); - - /* Free stack */ - if (f->f_stacktop != NULL) { - for (p = valuestack; p < f->f_stacktop; p++) - Py_XDECREF(*p); - } - - Py_XDECREF(f->f_back); - Py_DECREF(f->f_builtins); - Py_DECREF(f->f_globals); - Py_CLEAR(f->f_locals); - Py_CLEAR(f->f_trace); - Py_CLEAR(f->f_exc_type); - Py_CLEAR(f->f_exc_value); - Py_CLEAR(f->f_exc_traceback); - - co = f->f_code; - if (co->co_zombieframe == NULL) - co->co_zombieframe = f; - else if (numfree < PyFrame_MAXFREELIST) { - ++numfree; - f->f_back = free_list; - free_list = f; - } - else - PyObject_GC_Del(f); + PyObject_GC_UnTrack(f); + Py_TRASHCAN_SAFE_BEGIN(f) + /* Kill all local variables */ + valuestack = f->f_valuestack; + for (p = f->f_localsplus; p < valuestack; p++) + Py_CLEAR(*p); + + /* Free stack */ + if (f->f_stacktop != NULL) { + for (p = valuestack; p < f->f_stacktop; p++) + Py_XDECREF(*p); + } + + Py_XDECREF(f->f_back); + Py_DECREF(f->f_builtins); + Py_DECREF(f->f_globals); + Py_CLEAR(f->f_locals); + Py_CLEAR(f->f_trace); + Py_CLEAR(f->f_exc_type); + Py_CLEAR(f->f_exc_value); + Py_CLEAR(f->f_exc_traceback); + + co = f->f_code; + if (co->co_zombieframe == NULL) + co->co_zombieframe = f; + else if (numfree < PyFrame_MAXFREELIST) { + ++numfree; + f->f_back = free_list; + free_list = f; + } + else + PyObject_GC_Del(f); - Py_DECREF(co); - Py_TRASHCAN_SAFE_END(f) + Py_DECREF(co); + Py_TRASHCAN_SAFE_END(f) } static int frame_traverse(PyFrameObject *f, visitproc visit, void *arg) { - PyObject **fastlocals, **p; - int i, slots; + PyObject **fastlocals, **p; + int i, slots; - Py_VISIT(f->f_back); - Py_VISIT(f->f_code); - Py_VISIT(f->f_builtins); - Py_VISIT(f->f_globals); - Py_VISIT(f->f_locals); - Py_VISIT(f->f_trace); - Py_VISIT(f->f_exc_type); - Py_VISIT(f->f_exc_value); - Py_VISIT(f->f_exc_traceback); - - /* locals */ - slots = f->f_code->co_nlocals + PyTuple_GET_SIZE(f->f_code->co_cellvars) + PyTuple_GET_SIZE(f->f_code->co_freevars); - fastlocals = f->f_localsplus; - for (i = slots; --i >= 0; ++fastlocals) - Py_VISIT(*fastlocals); - - /* stack */ - if (f->f_stacktop != NULL) { - for (p = f->f_valuestack; p < f->f_stacktop; p++) - Py_VISIT(*p); - } - return 0; + Py_VISIT(f->f_back); + Py_VISIT(f->f_code); + Py_VISIT(f->f_builtins); + Py_VISIT(f->f_globals); + Py_VISIT(f->f_locals); + Py_VISIT(f->f_trace); + Py_VISIT(f->f_exc_type); + Py_VISIT(f->f_exc_value); + Py_VISIT(f->f_exc_traceback); + + /* locals */ + slots = f->f_code->co_nlocals + PyTuple_GET_SIZE(f->f_code->co_cellvars) + PyTuple_GET_SIZE(f->f_code->co_freevars); + fastlocals = f->f_localsplus; + for (i = slots; --i >= 0; ++fastlocals) + Py_VISIT(*fastlocals); + + /* stack */ + if (f->f_stacktop != NULL) { + for (p = f->f_valuestack; p < f->f_stacktop; p++) + Py_VISIT(*p); + } + return 0; } static void frame_clear(PyFrameObject *f) { - PyObject **fastlocals, **p, **oldtop; - int i, slots; + PyObject **fastlocals, **p, **oldtop; + int i, slots; - /* Before anything else, make sure that this frame is clearly marked - * as being defunct! Else, e.g., a generator reachable from this - * frame may also point to this frame, believe itself to still be - * active, and try cleaning up this frame again. - */ - oldtop = f->f_stacktop; - f->f_stacktop = NULL; - - Py_CLEAR(f->f_exc_type); - Py_CLEAR(f->f_exc_value); - Py_CLEAR(f->f_exc_traceback); - Py_CLEAR(f->f_trace); - - /* locals */ - slots = f->f_code->co_nlocals + PyTuple_GET_SIZE(f->f_code->co_cellvars) + PyTuple_GET_SIZE(f->f_code->co_freevars); - fastlocals = f->f_localsplus; - for (i = slots; --i >= 0; ++fastlocals) - Py_CLEAR(*fastlocals); - - /* stack */ - if (oldtop != NULL) { - for (p = f->f_valuestack; p < oldtop; p++) - Py_CLEAR(*p); - } + /* Before anything else, make sure that this frame is clearly marked + * as being defunct! Else, e.g., a generator reachable from this + * frame may also point to this frame, believe itself to still be + * active, and try cleaning up this frame again. + */ + oldtop = f->f_stacktop; + f->f_stacktop = NULL; + + Py_CLEAR(f->f_exc_type); + Py_CLEAR(f->f_exc_value); + Py_CLEAR(f->f_exc_traceback); + Py_CLEAR(f->f_trace); + + /* locals */ + slots = f->f_code->co_nlocals + PyTuple_GET_SIZE(f->f_code->co_cellvars) + PyTuple_GET_SIZE(f->f_code->co_freevars); + fastlocals = f->f_localsplus; + for (i = slots; --i >= 0; ++fastlocals) + Py_CLEAR(*fastlocals); + + /* stack */ + if (oldtop != NULL) { + for (p = f->f_valuestack; p < oldtop; p++) + Py_CLEAR(*p); + } } static PyObject * frame_sizeof(PyFrameObject *f) { - Py_ssize_t res, extras, ncells, nfrees; + Py_ssize_t res, extras, ncells, nfrees; - ncells = PyTuple_GET_SIZE(f->f_code->co_cellvars); - nfrees = PyTuple_GET_SIZE(f->f_code->co_freevars); - extras = f->f_code->co_stacksize + f->f_code->co_nlocals + - ncells + nfrees; - /* subtract one as it is already included in PyFrameObject */ - res = sizeof(PyFrameObject) + (extras-1) * sizeof(PyObject *); + ncells = PyTuple_GET_SIZE(f->f_code->co_cellvars); + nfrees = PyTuple_GET_SIZE(f->f_code->co_freevars); + extras = f->f_code->co_stacksize + f->f_code->co_nlocals + + ncells + nfrees; + /* subtract one as it is already included in PyFrameObject */ + res = sizeof(PyFrameObject) + (extras-1) * sizeof(PyObject *); - return PyLong_FromSsize_t(res); + return PyLong_FromSsize_t(res); } PyDoc_STRVAR(sizeof__doc__, "F.__sizeof__() -> size of F in memory, in bytes"); static PyMethodDef frame_methods[] = { - {"__sizeof__", (PyCFunction)frame_sizeof, METH_NOARGS, - sizeof__doc__}, - {NULL, NULL} /* sentinel */ + {"__sizeof__", (PyCFunction)frame_sizeof, METH_NOARGS, + sizeof__doc__}, + {NULL, NULL} /* sentinel */ }; PyTypeObject PyFrame_Type = { - PyVarObject_HEAD_INIT(&PyType_Type, 0) - "frame", - sizeof(PyFrameObject), - sizeof(PyObject *), - (destructor)frame_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 */ - PyObject_GenericSetAttr, /* tp_setattro */ - 0, /* tp_as_buffer */ - Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */ - 0, /* tp_doc */ - (traverseproc)frame_traverse, /* tp_traverse */ - (inquiry)frame_clear, /* tp_clear */ - 0, /* tp_richcompare */ - 0, /* tp_weaklistoffset */ - 0, /* tp_iter */ - 0, /* tp_iternext */ - frame_methods, /* tp_methods */ - frame_memberlist, /* tp_members */ - frame_getsetlist, /* tp_getset */ - 0, /* tp_base */ - 0, /* tp_dict */ + PyVarObject_HEAD_INIT(&PyType_Type, 0) + "frame", + sizeof(PyFrameObject), + sizeof(PyObject *), + (destructor)frame_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 */ + PyObject_GenericSetAttr, /* tp_setattro */ + 0, /* tp_as_buffer */ + Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */ + 0, /* tp_doc */ + (traverseproc)frame_traverse, /* tp_traverse */ + (inquiry)frame_clear, /* tp_clear */ + 0, /* tp_richcompare */ + 0, /* tp_weaklistoffset */ + 0, /* tp_iter */ + 0, /* tp_iternext */ + frame_methods, /* tp_methods */ + frame_memberlist, /* tp_members */ + frame_getsetlist, /* tp_getset */ + 0, /* tp_base */ + 0, /* tp_dict */ }; static PyObject *builtin_object; int _PyFrame_Init() { - builtin_object = PyUnicode_InternFromString("__builtins__"); - if (builtin_object == NULL) - return 0; - return 1; + builtin_object = PyUnicode_InternFromString("__builtins__"); + if (builtin_object == NULL) + return 0; + return 1; } PyFrameObject * PyFrame_New(PyThreadState *tstate, PyCodeObject *code, PyObject *globals, - PyObject *locals) + PyObject *locals) { - PyFrameObject *back = tstate->frame; - PyFrameObject *f; - PyObject *builtins; - Py_ssize_t i; + PyFrameObject *back = tstate->frame; + PyFrameObject *f; + PyObject *builtins; + Py_ssize_t i; #ifdef Py_DEBUG - if (code == NULL || globals == NULL || !PyDict_Check(globals) || - (locals != NULL && !PyMapping_Check(locals))) { - PyErr_BadInternalCall(); - return NULL; - } + if (code == NULL || globals == NULL || !PyDict_Check(globals) || + (locals != NULL && !PyMapping_Check(locals))) { + PyErr_BadInternalCall(); + return NULL; + } #endif - if (back == NULL || back->f_globals != globals) { - builtins = PyDict_GetItem(globals, builtin_object); - if (builtins) { - if (PyModule_Check(builtins)) { - builtins = PyModule_GetDict(builtins); - assert(!builtins || PyDict_Check(builtins)); - } - else if (!PyDict_Check(builtins)) - builtins = NULL; - } - if (builtins == NULL) { - /* No builtins! Make up a minimal one - Give them 'None', at least. */ - builtins = PyDict_New(); - if (builtins == NULL || - PyDict_SetItemString( - builtins, "None", Py_None) < 0) - return NULL; - } - else - Py_INCREF(builtins); - - } - else { - /* If we share the globals, we share the builtins. - Save a lookup and a call. */ - builtins = back->f_builtins; - assert(builtins != NULL && PyDict_Check(builtins)); - Py_INCREF(builtins); - } - if (code->co_zombieframe != NULL) { - f = code->co_zombieframe; - code->co_zombieframe = NULL; - _Py_NewReference((PyObject *)f); - assert(f->f_code == code); - } - else { - Py_ssize_t extras, ncells, nfrees; - ncells = PyTuple_GET_SIZE(code->co_cellvars); - nfrees = PyTuple_GET_SIZE(code->co_freevars); - extras = code->co_stacksize + code->co_nlocals + ncells + - nfrees; - if (free_list == NULL) { - f = PyObject_GC_NewVar(PyFrameObject, &PyFrame_Type, - extras); - if (f == NULL) { - Py_DECREF(builtins); - return NULL; - } - } - else { - assert(numfree > 0); - --numfree; - f = free_list; - free_list = free_list->f_back; - if (Py_SIZE(f) < extras) { - f = PyObject_GC_Resize(PyFrameObject, f, extras); - if (f == NULL) { - Py_DECREF(builtins); - return NULL; - } - } - _Py_NewReference((PyObject *)f); - } - - f->f_code = code; - extras = code->co_nlocals + ncells + nfrees; - f->f_valuestack = f->f_localsplus + extras; - for (i=0; if_localsplus[i] = NULL; - f->f_locals = NULL; - f->f_trace = NULL; - f->f_exc_type = f->f_exc_value = f->f_exc_traceback = NULL; - } - f->f_stacktop = f->f_valuestack; - f->f_builtins = builtins; - Py_XINCREF(back); - f->f_back = back; - Py_INCREF(code); - Py_INCREF(globals); - f->f_globals = globals; - /* Most functions have CO_NEWLOCALS and CO_OPTIMIZED set. */ - if ((code->co_flags & (CO_NEWLOCALS | CO_OPTIMIZED)) == - (CO_NEWLOCALS | CO_OPTIMIZED)) - ; /* f_locals = NULL; will be set by PyFrame_FastToLocals() */ - else if (code->co_flags & CO_NEWLOCALS) { - locals = PyDict_New(); - if (locals == NULL) { - Py_DECREF(f); - return NULL; - } - f->f_locals = locals; - } - else { - if (locals == NULL) - locals = globals; - Py_INCREF(locals); - f->f_locals = locals; - } - f->f_tstate = tstate; - - f->f_lasti = -1; - f->f_lineno = code->co_firstlineno; - f->f_iblock = 0; + if (back == NULL || back->f_globals != globals) { + builtins = PyDict_GetItem(globals, builtin_object); + if (builtins) { + if (PyModule_Check(builtins)) { + builtins = PyModule_GetDict(builtins); + assert(!builtins || PyDict_Check(builtins)); + } + else if (!PyDict_Check(builtins)) + builtins = NULL; + } + if (builtins == NULL) { + /* No builtins! Make up a minimal one + Give them 'None', at least. */ + builtins = PyDict_New(); + if (builtins == NULL || + PyDict_SetItemString( + builtins, "None", Py_None) < 0) + return NULL; + } + else + Py_INCREF(builtins); + + } + else { + /* If we share the globals, we share the builtins. + Save a lookup and a call. */ + builtins = back->f_builtins; + assert(builtins != NULL && PyDict_Check(builtins)); + Py_INCREF(builtins); + } + if (code->co_zombieframe != NULL) { + f = code->co_zombieframe; + code->co_zombieframe = NULL; + _Py_NewReference((PyObject *)f); + assert(f->f_code == code); + } + else { + Py_ssize_t extras, ncells, nfrees; + ncells = PyTuple_GET_SIZE(code->co_cellvars); + nfrees = PyTuple_GET_SIZE(code->co_freevars); + extras = code->co_stacksize + code->co_nlocals + ncells + + nfrees; + if (free_list == NULL) { + f = PyObject_GC_NewVar(PyFrameObject, &PyFrame_Type, + extras); + if (f == NULL) { + Py_DECREF(builtins); + return NULL; + } + } + else { + assert(numfree > 0); + --numfree; + f = free_list; + free_list = free_list->f_back; + if (Py_SIZE(f) < extras) { + f = PyObject_GC_Resize(PyFrameObject, f, extras); + if (f == NULL) { + Py_DECREF(builtins); + return NULL; + } + } + _Py_NewReference((PyObject *)f); + } + + f->f_code = code; + extras = code->co_nlocals + ncells + nfrees; + f->f_valuestack = f->f_localsplus + extras; + for (i=0; if_localsplus[i] = NULL; + f->f_locals = NULL; + f->f_trace = NULL; + f->f_exc_type = f->f_exc_value = f->f_exc_traceback = NULL; + } + f->f_stacktop = f->f_valuestack; + f->f_builtins = builtins; + Py_XINCREF(back); + f->f_back = back; + Py_INCREF(code); + Py_INCREF(globals); + f->f_globals = globals; + /* Most functions have CO_NEWLOCALS and CO_OPTIMIZED set. */ + if ((code->co_flags & (CO_NEWLOCALS | CO_OPTIMIZED)) == + (CO_NEWLOCALS | CO_OPTIMIZED)) + ; /* f_locals = NULL; will be set by PyFrame_FastToLocals() */ + else if (code->co_flags & CO_NEWLOCALS) { + locals = PyDict_New(); + if (locals == NULL) { + Py_DECREF(f); + return NULL; + } + f->f_locals = locals; + } + else { + if (locals == NULL) + locals = globals; + Py_INCREF(locals); + f->f_locals = locals; + } + f->f_tstate = tstate; + + f->f_lasti = -1; + f->f_lineno = code->co_firstlineno; + f->f_iblock = 0; - _PyObject_GC_TRACK(f); - return f; + _PyObject_GC_TRACK(f); + return f; } /* Block management */ @@ -721,28 +721,28 @@ void PyFrame_BlockSetup(PyFrameObject *f, int type, int handler, int level) { - PyTryBlock *b; - if (f->f_iblock >= CO_MAXBLOCKS) - Py_FatalError("XXX block stack overflow"); - b = &f->f_blockstack[f->f_iblock++]; - b->b_type = type; - b->b_level = level; - b->b_handler = handler; + PyTryBlock *b; + if (f->f_iblock >= CO_MAXBLOCKS) + Py_FatalError("XXX block stack overflow"); + b = &f->f_blockstack[f->f_iblock++]; + b->b_type = type; + b->b_level = level; + b->b_handler = handler; } PyTryBlock * PyFrame_BlockPop(PyFrameObject *f) { - PyTryBlock *b; - if (f->f_iblock <= 0) - Py_FatalError("XXX block stack underflow"); - b = &f->f_blockstack[--f->f_iblock]; - return b; + PyTryBlock *b; + if (f->f_iblock <= 0) + Py_FatalError("XXX block stack underflow"); + b = &f->f_blockstack[--f->f_iblock]; + return b; } /* Convert between "fast" version of locals and dictionary version. - - map and values are input arguments. map is a tuple of strings. + + map and values are input arguments. map is a tuple of strings. values is an array of PyObject*. At index i, map[i] is the name of the variable with value values[i]. The function copies the first nmap variable from map/values into dict. If values[i] is NULL, @@ -758,29 +758,29 @@ static void map_to_dict(PyObject *map, Py_ssize_t nmap, PyObject *dict, PyObject **values, - int deref) + int deref) { - Py_ssize_t j; - assert(PyTuple_Check(map)); - assert(PyDict_Check(dict)); - assert(PyTuple_Size(map) >= nmap); - for (j = nmap; --j >= 0; ) { - PyObject *key = PyTuple_GET_ITEM(map, j); - PyObject *value = values[j]; - assert(PyUnicode_Check(key)); - if (deref) { - assert(PyCell_Check(value)); - value = PyCell_GET(value); - } - if (value == NULL) { - if (PyObject_DelItem(dict, key) != 0) - PyErr_Clear(); - } - else { - if (PyObject_SetItem(dict, key, value) != 0) - PyErr_Clear(); - } - } + Py_ssize_t j; + assert(PyTuple_Check(map)); + assert(PyDict_Check(dict)); + assert(PyTuple_Size(map) >= nmap); + for (j = nmap; --j >= 0; ) { + PyObject *key = PyTuple_GET_ITEM(map, j); + PyObject *value = values[j]; + assert(PyUnicode_Check(key)); + if (deref) { + assert(PyCell_Check(value)); + value = PyCell_GET(value); + } + if (value == NULL) { + if (PyObject_DelItem(dict, key) != 0) + PyErr_Clear(); + } + else { + if (PyObject_SetItem(dict, key, value) != 0) + PyErr_Clear(); + } + } } /* Copy values from the "locals" dict into the fast locals. @@ -788,7 +788,7 @@ dict is an input argument containing string keys representing variables names and arbitrary PyObject* as values. - map and values are input arguments. map is a tuple of strings. + map and values are input arguments. map is a tuple of strings. values is an array of PyObject*. At index i, map[i] is the name of the variable with value values[i]. The function copies the first nmap variable from map/values into dict. If values[i] is NULL, @@ -806,150 +806,150 @@ static void dict_to_map(PyObject *map, Py_ssize_t nmap, PyObject *dict, PyObject **values, - int deref, int clear) + int deref, int clear) { - Py_ssize_t j; - assert(PyTuple_Check(map)); - assert(PyDict_Check(dict)); - assert(PyTuple_Size(map) >= nmap); - for (j = nmap; --j >= 0; ) { - PyObject *key = PyTuple_GET_ITEM(map, j); - PyObject *value = PyObject_GetItem(dict, key); - assert(PyUnicode_Check(key)); - /* We only care about NULLs if clear is true. */ - if (value == NULL) { - PyErr_Clear(); - if (!clear) - continue; - } - if (deref) { - assert(PyCell_Check(values[j])); - if (PyCell_GET(values[j]) != value) { - if (PyCell_Set(values[j], value) < 0) - PyErr_Clear(); - } - } else if (values[j] != value) { - Py_XINCREF(value); - Py_XDECREF(values[j]); - values[j] = value; - } - Py_XDECREF(value); - } + Py_ssize_t j; + assert(PyTuple_Check(map)); + assert(PyDict_Check(dict)); + assert(PyTuple_Size(map) >= nmap); + for (j = nmap; --j >= 0; ) { + PyObject *key = PyTuple_GET_ITEM(map, j); + PyObject *value = PyObject_GetItem(dict, key); + assert(PyUnicode_Check(key)); + /* We only care about NULLs if clear is true. */ + if (value == NULL) { + PyErr_Clear(); + if (!clear) + continue; + } + if (deref) { + assert(PyCell_Check(values[j])); + if (PyCell_GET(values[j]) != value) { + if (PyCell_Set(values[j], value) < 0) + PyErr_Clear(); + } + } else if (values[j] != value) { + Py_XINCREF(value); + Py_XDECREF(values[j]); + values[j] = value; + } + Py_XDECREF(value); + } } void PyFrame_FastToLocals(PyFrameObject *f) { - /* Merge fast locals into f->f_locals */ - PyObject *locals, *map; - PyObject **fast; - PyObject *error_type, *error_value, *error_traceback; - PyCodeObject *co; - Py_ssize_t j; - int ncells, nfreevars; - if (f == NULL) - return; - locals = f->f_locals; - if (locals == NULL) { - locals = f->f_locals = PyDict_New(); - if (locals == NULL) { - PyErr_Clear(); /* Can't report it :-( */ - return; - } - } - co = f->f_code; - map = co->co_varnames; - if (!PyTuple_Check(map)) - return; - PyErr_Fetch(&error_type, &error_value, &error_traceback); - fast = f->f_localsplus; - j = PyTuple_GET_SIZE(map); - if (j > co->co_nlocals) - j = co->co_nlocals; - if (co->co_nlocals) - map_to_dict(map, j, locals, fast, 0); - ncells = PyTuple_GET_SIZE(co->co_cellvars); - nfreevars = PyTuple_GET_SIZE(co->co_freevars); - if (ncells || nfreevars) { - map_to_dict(co->co_cellvars, ncells, - locals, fast + co->co_nlocals, 1); - /* If the namespace is unoptimized, then one of the - following cases applies: - 1. It does not contain free variables, because it - uses import * or is a top-level namespace. - 2. It is a class namespace. - We don't want to accidentally copy free variables - into the locals dict used by the class. - */ - if (co->co_flags & CO_OPTIMIZED) { - map_to_dict(co->co_freevars, nfreevars, - locals, fast + co->co_nlocals + ncells, 1); - } - } - PyErr_Restore(error_type, error_value, error_traceback); + /* Merge fast locals into f->f_locals */ + PyObject *locals, *map; + PyObject **fast; + PyObject *error_type, *error_value, *error_traceback; + PyCodeObject *co; + Py_ssize_t j; + int ncells, nfreevars; + if (f == NULL) + return; + locals = f->f_locals; + if (locals == NULL) { + locals = f->f_locals = PyDict_New(); + if (locals == NULL) { + PyErr_Clear(); /* Can't report it :-( */ + return; + } + } + co = f->f_code; + map = co->co_varnames; + if (!PyTuple_Check(map)) + return; + PyErr_Fetch(&error_type, &error_value, &error_traceback); + fast = f->f_localsplus; + j = PyTuple_GET_SIZE(map); + if (j > co->co_nlocals) + j = co->co_nlocals; + if (co->co_nlocals) + map_to_dict(map, j, locals, fast, 0); + ncells = PyTuple_GET_SIZE(co->co_cellvars); + nfreevars = PyTuple_GET_SIZE(co->co_freevars); + if (ncells || nfreevars) { + map_to_dict(co->co_cellvars, ncells, + locals, fast + co->co_nlocals, 1); + /* If the namespace is unoptimized, then one of the + following cases applies: + 1. It does not contain free variables, because it + uses import * or is a top-level namespace. + 2. It is a class namespace. + We don't want to accidentally copy free variables + into the locals dict used by the class. + */ + if (co->co_flags & CO_OPTIMIZED) { + map_to_dict(co->co_freevars, nfreevars, + locals, fast + co->co_nlocals + ncells, 1); + } + } + PyErr_Restore(error_type, error_value, error_traceback); } void PyFrame_LocalsToFast(PyFrameObject *f, int clear) { - /* Merge f->f_locals into fast locals */ - PyObject *locals, *map; - PyObject **fast; - PyObject *error_type, *error_value, *error_traceback; - PyCodeObject *co; - Py_ssize_t j; - int ncells, nfreevars; - if (f == NULL) - return; - locals = f->f_locals; - co = f->f_code; - map = co->co_varnames; - if (locals == NULL) - return; - if (!PyTuple_Check(map)) - return; - PyErr_Fetch(&error_type, &error_value, &error_traceback); - fast = f->f_localsplus; - j = PyTuple_GET_SIZE(map); - if (j > co->co_nlocals) - j = co->co_nlocals; - if (co->co_nlocals) - dict_to_map(co->co_varnames, j, locals, fast, 0, clear); - ncells = PyTuple_GET_SIZE(co->co_cellvars); - nfreevars = PyTuple_GET_SIZE(co->co_freevars); - if (ncells || nfreevars) { - dict_to_map(co->co_cellvars, ncells, - locals, fast + co->co_nlocals, 1, clear); - /* Same test as in PyFrame_FastToLocals() above. */ - if (co->co_flags & CO_OPTIMIZED) { - dict_to_map(co->co_freevars, nfreevars, - locals, fast + co->co_nlocals + ncells, 1, - clear); - } - } - PyErr_Restore(error_type, error_value, error_traceback); + /* Merge f->f_locals into fast locals */ + PyObject *locals, *map; + PyObject **fast; + PyObject *error_type, *error_value, *error_traceback; + PyCodeObject *co; + Py_ssize_t j; + int ncells, nfreevars; + if (f == NULL) + return; + locals = f->f_locals; + co = f->f_code; + map = co->co_varnames; + if (locals == NULL) + return; + if (!PyTuple_Check(map)) + return; + PyErr_Fetch(&error_type, &error_value, &error_traceback); + fast = f->f_localsplus; + j = PyTuple_GET_SIZE(map); + if (j > co->co_nlocals) + j = co->co_nlocals; + if (co->co_nlocals) + dict_to_map(co->co_varnames, j, locals, fast, 0, clear); + ncells = PyTuple_GET_SIZE(co->co_cellvars); + nfreevars = PyTuple_GET_SIZE(co->co_freevars); + if (ncells || nfreevars) { + dict_to_map(co->co_cellvars, ncells, + locals, fast + co->co_nlocals, 1, clear); + /* Same test as in PyFrame_FastToLocals() above. */ + if (co->co_flags & CO_OPTIMIZED) { + dict_to_map(co->co_freevars, nfreevars, + locals, fast + co->co_nlocals + ncells, 1, + clear); + } + } + PyErr_Restore(error_type, error_value, error_traceback); } /* Clear out the free list */ int PyFrame_ClearFreeList(void) { - int freelist_size = numfree; - - while (free_list != NULL) { - PyFrameObject *f = free_list; - free_list = free_list->f_back; - PyObject_GC_Del(f); - --numfree; - } - assert(numfree == 0); - return freelist_size; + int freelist_size = numfree; + + while (free_list != NULL) { + PyFrameObject *f = free_list; + free_list = free_list->f_back; + PyObject_GC_Del(f); + --numfree; + } + assert(numfree == 0); + return freelist_size; } void PyFrame_Fini(void) { - (void)PyFrame_ClearFreeList(); - Py_XDECREF(builtin_object); - builtin_object = NULL; + (void)PyFrame_ClearFreeList(); + Py_XDECREF(builtin_object); + builtin_object = NULL; } Modified: python/branches/release31-maint/Objects/funcobject.c ============================================================================== --- python/branches/release31-maint/Objects/funcobject.c (original) +++ python/branches/release31-maint/Objects/funcobject.c Sun May 9 18:14:21 2010 @@ -9,215 +9,215 @@ PyObject * PyFunction_New(PyObject *code, PyObject *globals) { - PyFunctionObject *op = PyObject_GC_New(PyFunctionObject, - &PyFunction_Type); - static PyObject *__name__ = 0; - if (op != NULL) { - PyObject *doc; - PyObject *consts; - PyObject *module; - op->func_weakreflist = NULL; - Py_INCREF(code); - op->func_code = code; - Py_INCREF(globals); - op->func_globals = globals; - op->func_name = ((PyCodeObject *)code)->co_name; - Py_INCREF(op->func_name); - op->func_defaults = NULL; /* No default arguments */ - op->func_kwdefaults = NULL; /* No keyword only defaults */ - op->func_closure = NULL; - consts = ((PyCodeObject *)code)->co_consts; - if (PyTuple_Size(consts) >= 1) { - doc = PyTuple_GetItem(consts, 0); - if (!PyUnicode_Check(doc)) - doc = Py_None; - } - else - doc = Py_None; - Py_INCREF(doc); - op->func_doc = doc; - op->func_dict = NULL; - op->func_module = NULL; - op->func_annotations = NULL; - - /* __module__: If module name is in globals, use it. - Otherwise, use None. - */ - if (!__name__) { - __name__ = PyUnicode_InternFromString("__name__"); - if (!__name__) { - Py_DECREF(op); - return NULL; - } - } - module = PyDict_GetItem(globals, __name__); - if (module) { - Py_INCREF(module); - op->func_module = module; - } - } - else - return NULL; - _PyObject_GC_TRACK(op); - return (PyObject *)op; + PyFunctionObject *op = PyObject_GC_New(PyFunctionObject, + &PyFunction_Type); + static PyObject *__name__ = 0; + if (op != NULL) { + PyObject *doc; + PyObject *consts; + PyObject *module; + op->func_weakreflist = NULL; + Py_INCREF(code); + op->func_code = code; + Py_INCREF(globals); + op->func_globals = globals; + op->func_name = ((PyCodeObject *)code)->co_name; + Py_INCREF(op->func_name); + op->func_defaults = NULL; /* No default arguments */ + op->func_kwdefaults = NULL; /* No keyword only defaults */ + op->func_closure = NULL; + consts = ((PyCodeObject *)code)->co_consts; + if (PyTuple_Size(consts) >= 1) { + doc = PyTuple_GetItem(consts, 0); + if (!PyUnicode_Check(doc)) + doc = Py_None; + } + else + doc = Py_None; + Py_INCREF(doc); + op->func_doc = doc; + op->func_dict = NULL; + op->func_module = NULL; + op->func_annotations = NULL; + + /* __module__: If module name is in globals, use it. + Otherwise, use None. + */ + if (!__name__) { + __name__ = PyUnicode_InternFromString("__name__"); + if (!__name__) { + Py_DECREF(op); + return NULL; + } + } + module = PyDict_GetItem(globals, __name__); + if (module) { + Py_INCREF(module); + op->func_module = module; + } + } + else + return NULL; + _PyObject_GC_TRACK(op); + return (PyObject *)op; } PyObject * PyFunction_GetCode(PyObject *op) { - if (!PyFunction_Check(op)) { - PyErr_BadInternalCall(); - return NULL; - } - return ((PyFunctionObject *) op) -> func_code; + if (!PyFunction_Check(op)) { + PyErr_BadInternalCall(); + return NULL; + } + return ((PyFunctionObject *) op) -> func_code; } PyObject * PyFunction_GetGlobals(PyObject *op) { - if (!PyFunction_Check(op)) { - PyErr_BadInternalCall(); - return NULL; - } - return ((PyFunctionObject *) op) -> func_globals; + if (!PyFunction_Check(op)) { + PyErr_BadInternalCall(); + return NULL; + } + return ((PyFunctionObject *) op) -> func_globals; } PyObject * PyFunction_GetModule(PyObject *op) { - if (!PyFunction_Check(op)) { - PyErr_BadInternalCall(); - return NULL; - } - return ((PyFunctionObject *) op) -> func_module; + if (!PyFunction_Check(op)) { + PyErr_BadInternalCall(); + return NULL; + } + return ((PyFunctionObject *) op) -> func_module; } PyObject * PyFunction_GetDefaults(PyObject *op) { - if (!PyFunction_Check(op)) { - PyErr_BadInternalCall(); - return NULL; - } - return ((PyFunctionObject *) op) -> func_defaults; + if (!PyFunction_Check(op)) { + PyErr_BadInternalCall(); + return NULL; + } + return ((PyFunctionObject *) op) -> func_defaults; } int PyFunction_SetDefaults(PyObject *op, PyObject *defaults) { - if (!PyFunction_Check(op)) { - PyErr_BadInternalCall(); - return -1; - } - if (defaults == Py_None) - defaults = NULL; - else if (defaults && PyTuple_Check(defaults)) { - Py_INCREF(defaults); - } - else { - PyErr_SetString(PyExc_SystemError, "non-tuple default args"); - return -1; - } - Py_XDECREF(((PyFunctionObject *) op) -> func_defaults); - ((PyFunctionObject *) op) -> func_defaults = defaults; - return 0; + if (!PyFunction_Check(op)) { + PyErr_BadInternalCall(); + return -1; + } + if (defaults == Py_None) + defaults = NULL; + else if (defaults && PyTuple_Check(defaults)) { + Py_INCREF(defaults); + } + else { + PyErr_SetString(PyExc_SystemError, "non-tuple default args"); + return -1; + } + Py_XDECREF(((PyFunctionObject *) op) -> func_defaults); + ((PyFunctionObject *) op) -> func_defaults = defaults; + return 0; } PyObject * PyFunction_GetKwDefaults(PyObject *op) { - if (!PyFunction_Check(op)) { - PyErr_BadInternalCall(); - return NULL; - } - return ((PyFunctionObject *) op) -> func_kwdefaults; + if (!PyFunction_Check(op)) { + PyErr_BadInternalCall(); + return NULL; + } + return ((PyFunctionObject *) op) -> func_kwdefaults; } int PyFunction_SetKwDefaults(PyObject *op, PyObject *defaults) { - if (!PyFunction_Check(op)) { - PyErr_BadInternalCall(); - return -1; - } - if (defaults == Py_None) - defaults = NULL; - else if (defaults && PyDict_Check(defaults)) { - Py_INCREF(defaults); - } - else { - PyErr_SetString(PyExc_SystemError, - "non-dict keyword only default args"); - return -1; - } - Py_XDECREF(((PyFunctionObject *)op) -> func_kwdefaults); - ((PyFunctionObject *) op) -> func_kwdefaults = defaults; - return 0; + if (!PyFunction_Check(op)) { + PyErr_BadInternalCall(); + return -1; + } + if (defaults == Py_None) + defaults = NULL; + else if (defaults && PyDict_Check(defaults)) { + Py_INCREF(defaults); + } + else { + PyErr_SetString(PyExc_SystemError, + "non-dict keyword only default args"); + return -1; + } + Py_XDECREF(((PyFunctionObject *)op) -> func_kwdefaults); + ((PyFunctionObject *) op) -> func_kwdefaults = defaults; + return 0; } PyObject * PyFunction_GetClosure(PyObject *op) { - if (!PyFunction_Check(op)) { - PyErr_BadInternalCall(); - return NULL; - } - return ((PyFunctionObject *) op) -> func_closure; + if (!PyFunction_Check(op)) { + PyErr_BadInternalCall(); + return NULL; + } + return ((PyFunctionObject *) op) -> func_closure; } int PyFunction_SetClosure(PyObject *op, PyObject *closure) { - if (!PyFunction_Check(op)) { - PyErr_BadInternalCall(); - return -1; - } - if (closure == Py_None) - closure = NULL; - else if (PyTuple_Check(closure)) { - Py_INCREF(closure); - } - else { - PyErr_Format(PyExc_SystemError, - "expected tuple for closure, got '%.100s'", - closure->ob_type->tp_name); - return -1; - } - Py_XDECREF(((PyFunctionObject *) op) -> func_closure); - ((PyFunctionObject *) op) -> func_closure = closure; - return 0; + if (!PyFunction_Check(op)) { + PyErr_BadInternalCall(); + return -1; + } + if (closure == Py_None) + closure = NULL; + else if (PyTuple_Check(closure)) { + Py_INCREF(closure); + } + else { + PyErr_Format(PyExc_SystemError, + "expected tuple for closure, got '%.100s'", + closure->ob_type->tp_name); + return -1; + } + Py_XDECREF(((PyFunctionObject *) op) -> func_closure); + ((PyFunctionObject *) op) -> func_closure = closure; + return 0; } PyObject * PyFunction_GetAnnotations(PyObject *op) { - if (!PyFunction_Check(op)) { - PyErr_BadInternalCall(); - return NULL; - } - return ((PyFunctionObject *) op) -> func_annotations; + if (!PyFunction_Check(op)) { + PyErr_BadInternalCall(); + return NULL; + } + return ((PyFunctionObject *) op) -> func_annotations; } int PyFunction_SetAnnotations(PyObject *op, PyObject *annotations) { - if (!PyFunction_Check(op)) { - PyErr_BadInternalCall(); - return -1; - } - if (annotations == Py_None) - annotations = NULL; - else if (annotations && PyDict_Check(annotations)) { - Py_INCREF(annotations); - } - else { - PyErr_SetString(PyExc_SystemError, - "non-dict annotations"); - return -1; - } - Py_XDECREF(((PyFunctionObject *)op) -> func_annotations); - ((PyFunctionObject *) op) -> func_annotations = annotations; - return 0; + if (!PyFunction_Check(op)) { + PyErr_BadInternalCall(); + return -1; + } + if (annotations == Py_None) + annotations = NULL; + else if (annotations && PyDict_Check(annotations)) { + Py_INCREF(annotations); + } + else { + PyErr_SetString(PyExc_SystemError, + "non-dict annotations"); + return -1; + } + Py_XDECREF(((PyFunctionObject *)op) -> func_annotations); + ((PyFunctionObject *) op) -> func_annotations = annotations; + return 0; } /* Methods */ @@ -225,224 +225,224 @@ #define OFF(x) offsetof(PyFunctionObject, x) static PyMemberDef func_memberlist[] = { - {"__closure__", T_OBJECT, OFF(func_closure), - RESTRICTED|READONLY}, - {"__doc__", T_OBJECT, OFF(func_doc), PY_WRITE_RESTRICTED}, - {"__globals__", T_OBJECT, OFF(func_globals), - RESTRICTED|READONLY}, - {"__module__", T_OBJECT, OFF(func_module), PY_WRITE_RESTRICTED}, - {NULL} /* Sentinel */ + {"__closure__", T_OBJECT, OFF(func_closure), + RESTRICTED|READONLY}, + {"__doc__", T_OBJECT, OFF(func_doc), PY_WRITE_RESTRICTED}, + {"__globals__", T_OBJECT, OFF(func_globals), + RESTRICTED|READONLY}, + {"__module__", T_OBJECT, OFF(func_module), PY_WRITE_RESTRICTED}, + {NULL} /* Sentinel */ }; static PyObject * func_get_dict(PyFunctionObject *op) { - if (op->func_dict == NULL) { - op->func_dict = PyDict_New(); - if (op->func_dict == NULL) - return NULL; - } - Py_INCREF(op->func_dict); - return op->func_dict; + if (op->func_dict == NULL) { + op->func_dict = PyDict_New(); + if (op->func_dict == NULL) + return NULL; + } + Py_INCREF(op->func_dict); + return op->func_dict; } static int func_set_dict(PyFunctionObject *op, PyObject *value) { - PyObject *tmp; + PyObject *tmp; - /* It is illegal to del f.func_dict */ - if (value == NULL) { - PyErr_SetString(PyExc_TypeError, - "function's dictionary may not be deleted"); - return -1; - } - /* Can only set func_dict to a dictionary */ - if (!PyDict_Check(value)) { - PyErr_SetString(PyExc_TypeError, - "setting function's dictionary to a non-dict"); - return -1; - } - tmp = op->func_dict; - Py_INCREF(value); - op->func_dict = value; - Py_XDECREF(tmp); - return 0; + /* It is illegal to del f.func_dict */ + if (value == NULL) { + PyErr_SetString(PyExc_TypeError, + "function's dictionary may not be deleted"); + return -1; + } + /* Can only set func_dict to a dictionary */ + if (!PyDict_Check(value)) { + PyErr_SetString(PyExc_TypeError, + "setting function's dictionary to a non-dict"); + return -1; + } + tmp = op->func_dict; + Py_INCREF(value); + op->func_dict = value; + Py_XDECREF(tmp); + return 0; } static PyObject * func_get_code(PyFunctionObject *op) { - Py_INCREF(op->func_code); - return op->func_code; + Py_INCREF(op->func_code); + return op->func_code; } static int func_set_code(PyFunctionObject *op, PyObject *value) { - PyObject *tmp; - Py_ssize_t nfree, nclosure; + PyObject *tmp; + Py_ssize_t nfree, nclosure; - /* Not legal to del f.func_code or to set it to anything - * other than a code object. */ - if (value == NULL || !PyCode_Check(value)) { - PyErr_SetString(PyExc_TypeError, - "__code__ must be set to a code object"); - return -1; - } - nfree = PyCode_GetNumFree((PyCodeObject *)value); - nclosure = (op->func_closure == NULL ? 0 : - PyTuple_GET_SIZE(op->func_closure)); - if (nclosure != nfree) { - PyErr_Format(PyExc_ValueError, - "%U() requires a code object with %zd free vars," - " not %zd", - op->func_name, - nclosure, nfree); - return -1; - } - tmp = op->func_code; - Py_INCREF(value); - op->func_code = value; - Py_DECREF(tmp); - return 0; + /* Not legal to del f.func_code or to set it to anything + * other than a code object. */ + if (value == NULL || !PyCode_Check(value)) { + PyErr_SetString(PyExc_TypeError, + "__code__ must be set to a code object"); + return -1; + } + nfree = PyCode_GetNumFree((PyCodeObject *)value); + nclosure = (op->func_closure == NULL ? 0 : + PyTuple_GET_SIZE(op->func_closure)); + if (nclosure != nfree) { + PyErr_Format(PyExc_ValueError, + "%U() requires a code object with %zd free vars," + " not %zd", + op->func_name, + nclosure, nfree); + return -1; + } + tmp = op->func_code; + Py_INCREF(value); + op->func_code = value; + Py_DECREF(tmp); + return 0; } static PyObject * func_get_name(PyFunctionObject *op) { - Py_INCREF(op->func_name); - return op->func_name; + Py_INCREF(op->func_name); + return op->func_name; } static int func_set_name(PyFunctionObject *op, PyObject *value) { - PyObject *tmp; + PyObject *tmp; - /* Not legal to del f.func_name or to set it to anything - * other than a string object. */ - if (value == NULL || !PyUnicode_Check(value)) { - PyErr_SetString(PyExc_TypeError, - "__name__ must be set to a string object"); - return -1; - } - tmp = op->func_name; - Py_INCREF(value); - op->func_name = value; - Py_DECREF(tmp); - return 0; + /* Not legal to del f.func_name or to set it to anything + * other than a string object. */ + if (value == NULL || !PyUnicode_Check(value)) { + PyErr_SetString(PyExc_TypeError, + "__name__ must be set to a string object"); + return -1; + } + tmp = op->func_name; + Py_INCREF(value); + op->func_name = value; + Py_DECREF(tmp); + return 0; } static PyObject * func_get_defaults(PyFunctionObject *op) { - if (op->func_defaults == NULL) { - Py_INCREF(Py_None); - return Py_None; - } - Py_INCREF(op->func_defaults); - return op->func_defaults; + if (op->func_defaults == NULL) { + Py_INCREF(Py_None); + return Py_None; + } + Py_INCREF(op->func_defaults); + return op->func_defaults; } static int func_set_defaults(PyFunctionObject *op, PyObject *value) { - PyObject *tmp; + PyObject *tmp; - /* Legal to del f.func_defaults. - * Can only set func_defaults to NULL or a tuple. */ - if (value == Py_None) - value = NULL; - if (value != NULL && !PyTuple_Check(value)) { - PyErr_SetString(PyExc_TypeError, - "__defaults__ must be set to a tuple object"); - return -1; - } - tmp = op->func_defaults; - Py_XINCREF(value); - op->func_defaults = value; - Py_XDECREF(tmp); - return 0; + /* Legal to del f.func_defaults. + * Can only set func_defaults to NULL or a tuple. */ + if (value == Py_None) + value = NULL; + if (value != NULL && !PyTuple_Check(value)) { + PyErr_SetString(PyExc_TypeError, + "__defaults__ must be set to a tuple object"); + return -1; + } + tmp = op->func_defaults; + Py_XINCREF(value); + op->func_defaults = value; + Py_XDECREF(tmp); + return 0; } static PyObject * func_get_kwdefaults(PyFunctionObject *op) { - if (op->func_kwdefaults == NULL) { - Py_INCREF(Py_None); - return Py_None; - } - Py_INCREF(op->func_kwdefaults); - return op->func_kwdefaults; + if (op->func_kwdefaults == NULL) { + Py_INCREF(Py_None); + return Py_None; + } + Py_INCREF(op->func_kwdefaults); + return op->func_kwdefaults; } static int func_set_kwdefaults(PyFunctionObject *op, PyObject *value) { - PyObject *tmp; + PyObject *tmp; - if (value == Py_None) - value = NULL; - /* Legal to del f.func_kwdefaults. - * Can only set func_kwdefaults to NULL or a dict. */ - if (value != NULL && !PyDict_Check(value)) { - PyErr_SetString(PyExc_TypeError, - "__kwdefaults__ must be set to a dict object"); - return -1; - } - tmp = op->func_kwdefaults; - Py_XINCREF(value); - op->func_kwdefaults = value; - Py_XDECREF(tmp); - return 0; + if (value == Py_None) + value = NULL; + /* Legal to del f.func_kwdefaults. + * Can only set func_kwdefaults to NULL or a dict. */ + if (value != NULL && !PyDict_Check(value)) { + PyErr_SetString(PyExc_TypeError, + "__kwdefaults__ must be set to a dict object"); + return -1; + } + tmp = op->func_kwdefaults; + Py_XINCREF(value); + op->func_kwdefaults = value; + Py_XDECREF(tmp); + return 0; } static PyObject * func_get_annotations(PyFunctionObject *op) { - if (op->func_annotations == NULL) { - op->func_annotations = PyDict_New(); - if (op->func_annotations == NULL) - return NULL; - } - Py_INCREF(op->func_annotations); - return op->func_annotations; + if (op->func_annotations == NULL) { + op->func_annotations = PyDict_New(); + if (op->func_annotations == NULL) + return NULL; + } + Py_INCREF(op->func_annotations); + return op->func_annotations; } static int func_set_annotations(PyFunctionObject *op, PyObject *value) { - PyObject *tmp; + PyObject *tmp; - if (value == Py_None) - value = NULL; - /* Legal to del f.func_annotations. - * Can only set func_annotations to NULL (through C api) - * or a dict. */ - if (value != NULL && !PyDict_Check(value)) { - PyErr_SetString(PyExc_TypeError, - "__annotations__ must be set to a dict object"); - return -1; - } - tmp = op->func_annotations; - Py_XINCREF(value); - op->func_annotations = value; - Py_XDECREF(tmp); - return 0; + if (value == Py_None) + value = NULL; + /* Legal to del f.func_annotations. + * Can only set func_annotations to NULL (through C api) + * or a dict. */ + if (value != NULL && !PyDict_Check(value)) { + PyErr_SetString(PyExc_TypeError, + "__annotations__ must be set to a dict object"); + return -1; + } + tmp = op->func_annotations; + Py_XINCREF(value); + op->func_annotations = value; + Py_XDECREF(tmp); + return 0; } static PyGetSetDef func_getsetlist[] = { - {"__code__", (getter)func_get_code, (setter)func_set_code}, - {"__defaults__", (getter)func_get_defaults, - (setter)func_set_defaults}, - {"__kwdefaults__", (getter)func_get_kwdefaults, - (setter)func_set_kwdefaults}, - {"__annotations__", (getter)func_get_annotations, - (setter)func_set_annotations}, - {"__dict__", (getter)func_get_dict, (setter)func_set_dict}, - {"__name__", (getter)func_get_name, (setter)func_set_name}, - {NULL} /* Sentinel */ + {"__code__", (getter)func_get_code, (setter)func_set_code}, + {"__defaults__", (getter)func_get_defaults, + (setter)func_set_defaults}, + {"__kwdefaults__", (getter)func_get_kwdefaults, + (setter)func_set_kwdefaults}, + {"__annotations__", (getter)func_get_annotations, + (setter)func_set_annotations}, + {"__dict__", (getter)func_get_dict, (setter)func_set_dict}, + {"__name__", (getter)func_get_name, (setter)func_set_name}, + {NULL} /* Sentinel */ }; PyDoc_STRVAR(func_doc, @@ -455,241 +455,241 @@ /* func_new() maintains the following invariants for closures. The closure must correspond to the free variables of the code object. - - if len(code.co_freevars) == 0: - closure = NULL + + if len(code.co_freevars) == 0: + closure = NULL else: - len(closure) == len(code.co_freevars) + len(closure) == len(code.co_freevars) for every elt in closure, type(elt) == cell */ static PyObject * func_new(PyTypeObject* type, PyObject* args, PyObject* kw) { - PyCodeObject *code; - PyObject *globals; - PyObject *name = Py_None; - PyObject *defaults = Py_None; - PyObject *closure = Py_None; - PyFunctionObject *newfunc; - Py_ssize_t nfree, nclosure; - static char *kwlist[] = {"code", "globals", "name", - "argdefs", "closure", 0}; - - if (!PyArg_ParseTupleAndKeywords(args, kw, "O!O!|OOO:function", - kwlist, - &PyCode_Type, &code, - &PyDict_Type, &globals, - &name, &defaults, &closure)) - return NULL; - if (name != Py_None && !PyUnicode_Check(name)) { - PyErr_SetString(PyExc_TypeError, - "arg 3 (name) must be None or string"); - return NULL; - } - if (defaults != Py_None && !PyTuple_Check(defaults)) { - PyErr_SetString(PyExc_TypeError, - "arg 4 (defaults) must be None or tuple"); - return NULL; - } - nfree = PyTuple_GET_SIZE(code->co_freevars); - if (!PyTuple_Check(closure)) { - if (nfree && closure == Py_None) { - PyErr_SetString(PyExc_TypeError, - "arg 5 (closure) must be tuple"); - return NULL; - } - else if (closure != Py_None) { - PyErr_SetString(PyExc_TypeError, - "arg 5 (closure) must be None or tuple"); - return NULL; - } - } - - /* check that the closure is well-formed */ - nclosure = closure == Py_None ? 0 : PyTuple_GET_SIZE(closure); - if (nfree != nclosure) - return PyErr_Format(PyExc_ValueError, - "%U requires closure of length %zd, not %zd", - code->co_name, nfree, nclosure); - if (nclosure) { - Py_ssize_t i; - for (i = 0; i < nclosure; i++) { - PyObject *o = PyTuple_GET_ITEM(closure, i); - if (!PyCell_Check(o)) { - return PyErr_Format(PyExc_TypeError, - "arg 5 (closure) expected cell, found %s", - o->ob_type->tp_name); - } - } - } - - newfunc = (PyFunctionObject *)PyFunction_New((PyObject *)code, - globals); - if (newfunc == NULL) - return NULL; - - if (name != Py_None) { - Py_INCREF(name); - Py_DECREF(newfunc->func_name); - newfunc->func_name = name; - } - if (defaults != Py_None) { - Py_INCREF(defaults); - newfunc->func_defaults = defaults; - } - if (closure != Py_None) { - Py_INCREF(closure); - newfunc->func_closure = closure; - } + PyCodeObject *code; + PyObject *globals; + PyObject *name = Py_None; + PyObject *defaults = Py_None; + PyObject *closure = Py_None; + PyFunctionObject *newfunc; + Py_ssize_t nfree, nclosure; + static char *kwlist[] = {"code", "globals", "name", + "argdefs", "closure", 0}; + + if (!PyArg_ParseTupleAndKeywords(args, kw, "O!O!|OOO:function", + kwlist, + &PyCode_Type, &code, + &PyDict_Type, &globals, + &name, &defaults, &closure)) + return NULL; + if (name != Py_None && !PyUnicode_Check(name)) { + PyErr_SetString(PyExc_TypeError, + "arg 3 (name) must be None or string"); + return NULL; + } + if (defaults != Py_None && !PyTuple_Check(defaults)) { + PyErr_SetString(PyExc_TypeError, + "arg 4 (defaults) must be None or tuple"); + return NULL; + } + nfree = PyTuple_GET_SIZE(code->co_freevars); + if (!PyTuple_Check(closure)) { + if (nfree && closure == Py_None) { + PyErr_SetString(PyExc_TypeError, + "arg 5 (closure) must be tuple"); + return NULL; + } + else if (closure != Py_None) { + PyErr_SetString(PyExc_TypeError, + "arg 5 (closure) must be None or tuple"); + return NULL; + } + } + + /* check that the closure is well-formed */ + nclosure = closure == Py_None ? 0 : PyTuple_GET_SIZE(closure); + if (nfree != nclosure) + return PyErr_Format(PyExc_ValueError, + "%U requires closure of length %zd, not %zd", + code->co_name, nfree, nclosure); + if (nclosure) { + Py_ssize_t i; + for (i = 0; i < nclosure; i++) { + PyObject *o = PyTuple_GET_ITEM(closure, i); + if (!PyCell_Check(o)) { + return PyErr_Format(PyExc_TypeError, + "arg 5 (closure) expected cell, found %s", + o->ob_type->tp_name); + } + } + } + + newfunc = (PyFunctionObject *)PyFunction_New((PyObject *)code, + globals); + if (newfunc == NULL) + return NULL; + + if (name != Py_None) { + Py_INCREF(name); + Py_DECREF(newfunc->func_name); + newfunc->func_name = name; + } + if (defaults != Py_None) { + Py_INCREF(defaults); + newfunc->func_defaults = defaults; + } + if (closure != Py_None) { + Py_INCREF(closure); + newfunc->func_closure = closure; + } - return (PyObject *)newfunc; + return (PyObject *)newfunc; } static void func_dealloc(PyFunctionObject *op) { - _PyObject_GC_UNTRACK(op); - if (op->func_weakreflist != NULL) - PyObject_ClearWeakRefs((PyObject *) op); - Py_DECREF(op->func_code); - Py_DECREF(op->func_globals); - Py_XDECREF(op->func_module); - Py_DECREF(op->func_name); - Py_XDECREF(op->func_defaults); - Py_XDECREF(op->func_kwdefaults); - Py_XDECREF(op->func_doc); - Py_XDECREF(op->func_dict); - Py_XDECREF(op->func_closure); - Py_XDECREF(op->func_annotations); - PyObject_GC_Del(op); + _PyObject_GC_UNTRACK(op); + if (op->func_weakreflist != NULL) + PyObject_ClearWeakRefs((PyObject *) op); + Py_DECREF(op->func_code); + Py_DECREF(op->func_globals); + Py_XDECREF(op->func_module); + Py_DECREF(op->func_name); + Py_XDECREF(op->func_defaults); + Py_XDECREF(op->func_kwdefaults); + Py_XDECREF(op->func_doc); + Py_XDECREF(op->func_dict); + Py_XDECREF(op->func_closure); + Py_XDECREF(op->func_annotations); + PyObject_GC_Del(op); } static PyObject* func_repr(PyFunctionObject *op) { - return PyUnicode_FromFormat("", - op->func_name, op); + return PyUnicode_FromFormat("", + op->func_name, op); } static int func_traverse(PyFunctionObject *f, visitproc visit, void *arg) { - Py_VISIT(f->func_code); - Py_VISIT(f->func_globals); - Py_VISIT(f->func_module); - Py_VISIT(f->func_defaults); - Py_VISIT(f->func_kwdefaults); - Py_VISIT(f->func_doc); - Py_VISIT(f->func_name); - Py_VISIT(f->func_dict); - Py_VISIT(f->func_closure); - Py_VISIT(f->func_annotations); - return 0; + Py_VISIT(f->func_code); + Py_VISIT(f->func_globals); + Py_VISIT(f->func_module); + Py_VISIT(f->func_defaults); + Py_VISIT(f->func_kwdefaults); + Py_VISIT(f->func_doc); + Py_VISIT(f->func_name); + Py_VISIT(f->func_dict); + Py_VISIT(f->func_closure); + Py_VISIT(f->func_annotations); + return 0; } static PyObject * function_call(PyObject *func, PyObject *arg, PyObject *kw) { - PyObject *result; - PyObject *argdefs; - PyObject *kwtuple = NULL; - PyObject **d, **k; - Py_ssize_t nk, nd; - - argdefs = PyFunction_GET_DEFAULTS(func); - if (argdefs != NULL && PyTuple_Check(argdefs)) { - d = &PyTuple_GET_ITEM((PyTupleObject *)argdefs, 0); - nd = PyTuple_GET_SIZE(argdefs); - } - else { - d = NULL; - nd = 0; - } - - if (kw != NULL && PyDict_Check(kw)) { - Py_ssize_t pos, i; - nk = PyDict_Size(kw); - kwtuple = PyTuple_New(2*nk); - if (kwtuple == NULL) - return NULL; - k = &PyTuple_GET_ITEM(kwtuple, 0); - pos = i = 0; - while (PyDict_Next(kw, &pos, &k[i], &k[i+1])) { - Py_INCREF(k[i]); - Py_INCREF(k[i+1]); - i += 2; - } - nk = i/2; - } - else { - k = NULL; - nk = 0; - } - - result = PyEval_EvalCodeEx( - (PyCodeObject *)PyFunction_GET_CODE(func), - PyFunction_GET_GLOBALS(func), (PyObject *)NULL, - &PyTuple_GET_ITEM(arg, 0), PyTuple_GET_SIZE(arg), - k, nk, d, nd, - PyFunction_GET_KW_DEFAULTS(func), - PyFunction_GET_CLOSURE(func)); + PyObject *result; + PyObject *argdefs; + PyObject *kwtuple = NULL; + PyObject **d, **k; + Py_ssize_t nk, nd; + + argdefs = PyFunction_GET_DEFAULTS(func); + if (argdefs != NULL && PyTuple_Check(argdefs)) { + d = &PyTuple_GET_ITEM((PyTupleObject *)argdefs, 0); + nd = PyTuple_GET_SIZE(argdefs); + } + else { + d = NULL; + nd = 0; + } + + if (kw != NULL && PyDict_Check(kw)) { + Py_ssize_t pos, i; + nk = PyDict_Size(kw); + kwtuple = PyTuple_New(2*nk); + if (kwtuple == NULL) + return NULL; + k = &PyTuple_GET_ITEM(kwtuple, 0); + pos = i = 0; + while (PyDict_Next(kw, &pos, &k[i], &k[i+1])) { + Py_INCREF(k[i]); + Py_INCREF(k[i+1]); + i += 2; + } + nk = i/2; + } + else { + k = NULL; + nk = 0; + } + + result = PyEval_EvalCodeEx( + (PyCodeObject *)PyFunction_GET_CODE(func), + PyFunction_GET_GLOBALS(func), (PyObject *)NULL, + &PyTuple_GET_ITEM(arg, 0), PyTuple_GET_SIZE(arg), + k, nk, d, nd, + PyFunction_GET_KW_DEFAULTS(func), + PyFunction_GET_CLOSURE(func)); - Py_XDECREF(kwtuple); + Py_XDECREF(kwtuple); - return result; + return result; } /* Bind a function to an object */ static PyObject * func_descr_get(PyObject *func, PyObject *obj, PyObject *type) { - if (obj == Py_None || obj == NULL) { - Py_INCREF(func); - return func; - } - return PyMethod_New(func, obj); + if (obj == Py_None || obj == NULL) { + Py_INCREF(func); + return func; + } + return PyMethod_New(func, obj); } PyTypeObject PyFunction_Type = { - PyVarObject_HEAD_INIT(&PyType_Type, 0) - "function", - sizeof(PyFunctionObject), - 0, - (destructor)func_dealloc, /* tp_dealloc */ - 0, /* tp_print */ - 0, /* tp_getattr */ - 0, /* tp_setattr */ - 0, /* tp_reserved */ - (reprfunc)func_repr, /* tp_repr */ - 0, /* tp_as_number */ - 0, /* tp_as_sequence */ - 0, /* tp_as_mapping */ - 0, /* tp_hash */ - function_call, /* tp_call */ - 0, /* tp_str */ - PyObject_GenericGetAttr, /* tp_getattro */ - PyObject_GenericSetAttr, /* tp_setattro */ - 0, /* tp_as_buffer */ - Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */ - func_doc, /* tp_doc */ - (traverseproc)func_traverse, /* tp_traverse */ - 0, /* tp_clear */ - 0, /* tp_richcompare */ - offsetof(PyFunctionObject, func_weakreflist), /* tp_weaklistoffset */ - 0, /* tp_iter */ - 0, /* tp_iternext */ - 0, /* tp_methods */ - func_memberlist, /* tp_members */ - func_getsetlist, /* tp_getset */ - 0, /* tp_base */ - 0, /* tp_dict */ - func_descr_get, /* tp_descr_get */ - 0, /* tp_descr_set */ - offsetof(PyFunctionObject, func_dict), /* tp_dictoffset */ - 0, /* tp_init */ - 0, /* tp_alloc */ - func_new, /* tp_new */ + PyVarObject_HEAD_INIT(&PyType_Type, 0) + "function", + sizeof(PyFunctionObject), + 0, + (destructor)func_dealloc, /* tp_dealloc */ + 0, /* tp_print */ + 0, /* tp_getattr */ + 0, /* tp_setattr */ + 0, /* tp_reserved */ + (reprfunc)func_repr, /* tp_repr */ + 0, /* tp_as_number */ + 0, /* tp_as_sequence */ + 0, /* tp_as_mapping */ + 0, /* tp_hash */ + function_call, /* tp_call */ + 0, /* tp_str */ + PyObject_GenericGetAttr, /* tp_getattro */ + PyObject_GenericSetAttr, /* tp_setattro */ + 0, /* tp_as_buffer */ + Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */ + func_doc, /* tp_doc */ + (traverseproc)func_traverse, /* tp_traverse */ + 0, /* tp_clear */ + 0, /* tp_richcompare */ + offsetof(PyFunctionObject, func_weakreflist), /* tp_weaklistoffset */ + 0, /* tp_iter */ + 0, /* tp_iternext */ + 0, /* tp_methods */ + func_memberlist, /* tp_members */ + func_getsetlist, /* tp_getset */ + 0, /* tp_base */ + 0, /* tp_dict */ + func_descr_get, /* tp_descr_get */ + 0, /* tp_descr_set */ + offsetof(PyFunctionObject, func_dict), /* tp_dictoffset */ + 0, /* tp_init */ + 0, /* tp_alloc */ + func_new, /* tp_new */ }; @@ -700,9 +700,9 @@ To declare a class method, use this idiom: class C: - def f(cls, arg1, arg2, ...): ... - f = classmethod(f) - + def f(cls, arg1, arg2, ...): ... + f = classmethod(f) + It can be called either on the class (e.g. C.f()) or on an instance (e.g. C().f()); the instance is ignored except for its class. If a class method is called for a derived class, the derived class @@ -713,66 +713,66 @@ */ typedef struct { - PyObject_HEAD - PyObject *cm_callable; + PyObject_HEAD + PyObject *cm_callable; } classmethod; static void cm_dealloc(classmethod *cm) { - _PyObject_GC_UNTRACK((PyObject *)cm); - Py_XDECREF(cm->cm_callable); - Py_TYPE(cm)->tp_free((PyObject *)cm); + _PyObject_GC_UNTRACK((PyObject *)cm); + Py_XDECREF(cm->cm_callable); + Py_TYPE(cm)->tp_free((PyObject *)cm); } static int cm_traverse(classmethod *cm, visitproc visit, void *arg) { - Py_VISIT(cm->cm_callable); - return 0; + Py_VISIT(cm->cm_callable); + return 0; } static int cm_clear(classmethod *cm) { - Py_CLEAR(cm->cm_callable); - return 0; + Py_CLEAR(cm->cm_callable); + return 0; } static PyObject * cm_descr_get(PyObject *self, PyObject *obj, PyObject *type) { - classmethod *cm = (classmethod *)self; + classmethod *cm = (classmethod *)self; - if (cm->cm_callable == NULL) { - PyErr_SetString(PyExc_RuntimeError, - "uninitialized classmethod object"); - return NULL; - } - if (type == NULL) - type = (PyObject *)(Py_TYPE(obj)); - return PyMethod_New(cm->cm_callable, type); + if (cm->cm_callable == NULL) { + PyErr_SetString(PyExc_RuntimeError, + "uninitialized classmethod object"); + return NULL; + } + if (type == NULL) + type = (PyObject *)(Py_TYPE(obj)); + return PyMethod_New(cm->cm_callable, type); } static int cm_init(PyObject *self, PyObject *args, PyObject *kwds) { - classmethod *cm = (classmethod *)self; - PyObject *callable; + classmethod *cm = (classmethod *)self; + PyObject *callable; - if (!PyArg_UnpackTuple(args, "classmethod", 1, 1, &callable)) - return -1; - if (!_PyArg_NoKeywords("classmethod", kwds)) - return -1; - Py_INCREF(callable); - cm->cm_callable = callable; - return 0; + if (!PyArg_UnpackTuple(args, "classmethod", 1, 1, &callable)) + return -1; + if (!_PyArg_NoKeywords("classmethod", kwds)) + return -1; + Py_INCREF(callable); + cm->cm_callable = callable; + return 0; } static PyMemberDef cm_memberlist[] = { - {"__func__", T_OBJECT, offsetof(classmethod, cm_callable), READONLY}, - {NULL} /* Sentinel */ + {"__func__", T_OBJECT, offsetof(classmethod, cm_callable), READONLY}, + {NULL} /* Sentinel */ }; PyDoc_STRVAR(classmethod_doc, @@ -797,57 +797,57 @@ If you want those, see the staticmethod builtin."); PyTypeObject PyClassMethod_Type = { - PyVarObject_HEAD_INIT(&PyType_Type, 0) - "classmethod", - sizeof(classmethod), - 0, - (destructor)cm_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_BASETYPE | Py_TPFLAGS_HAVE_GC, - classmethod_doc, /* tp_doc */ - (traverseproc)cm_traverse, /* tp_traverse */ - (inquiry)cm_clear, /* tp_clear */ - 0, /* tp_richcompare */ - 0, /* tp_weaklistoffset */ - 0, /* tp_iter */ - 0, /* tp_iternext */ - 0, /* tp_methods */ - cm_memberlist, /* tp_members */ - 0, /* tp_getset */ - 0, /* tp_base */ - 0, /* tp_dict */ - cm_descr_get, /* tp_descr_get */ - 0, /* tp_descr_set */ - 0, /* tp_dictoffset */ - cm_init, /* tp_init */ - PyType_GenericAlloc, /* tp_alloc */ - PyType_GenericNew, /* tp_new */ - PyObject_GC_Del, /* tp_free */ + PyVarObject_HEAD_INIT(&PyType_Type, 0) + "classmethod", + sizeof(classmethod), + 0, + (destructor)cm_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_BASETYPE | Py_TPFLAGS_HAVE_GC, + classmethod_doc, /* tp_doc */ + (traverseproc)cm_traverse, /* tp_traverse */ + (inquiry)cm_clear, /* tp_clear */ + 0, /* tp_richcompare */ + 0, /* tp_weaklistoffset */ + 0, /* tp_iter */ + 0, /* tp_iternext */ + 0, /* tp_methods */ + cm_memberlist, /* tp_members */ + 0, /* tp_getset */ + 0, /* tp_base */ + 0, /* tp_dict */ + cm_descr_get, /* tp_descr_get */ + 0, /* tp_descr_set */ + 0, /* tp_dictoffset */ + cm_init, /* tp_init */ + PyType_GenericAlloc, /* tp_alloc */ + PyType_GenericNew, /* tp_new */ + PyObject_GC_Del, /* tp_free */ }; PyObject * PyClassMethod_New(PyObject *callable) { - classmethod *cm = (classmethod *) - PyType_GenericAlloc(&PyClassMethod_Type, 0); - if (cm != NULL) { - Py_INCREF(callable); - cm->cm_callable = callable; - } - return (PyObject *)cm; + classmethod *cm = (classmethod *) + PyType_GenericAlloc(&PyClassMethod_Type, 0); + if (cm != NULL) { + Py_INCREF(callable); + cm->cm_callable = callable; + } + return (PyObject *)cm; } @@ -857,8 +857,8 @@ To declare a static method, use this idiom: class C: - def f(arg1, arg2, ...): ... - f = staticmethod(f) + def f(arg1, arg2, ...): ... + f = staticmethod(f) It can be called either on the class (e.g. C.f()) or on an instance (e.g. C().f()); the instance is ignored except for its class. @@ -868,66 +868,66 @@ */ typedef struct { - PyObject_HEAD - PyObject *sm_callable; + PyObject_HEAD + PyObject *sm_callable; } staticmethod; static void sm_dealloc(staticmethod *sm) { - _PyObject_GC_UNTRACK((PyObject *)sm); - Py_XDECREF(sm->sm_callable); - Py_TYPE(sm)->tp_free((PyObject *)sm); + _PyObject_GC_UNTRACK((PyObject *)sm); + Py_XDECREF(sm->sm_callable); + Py_TYPE(sm)->tp_free((PyObject *)sm); } static int sm_traverse(staticmethod *sm, visitproc visit, void *arg) { - Py_VISIT(sm->sm_callable); - return 0; + Py_VISIT(sm->sm_callable); + return 0; } static int sm_clear(staticmethod *sm) { - Py_XDECREF(sm->sm_callable); - sm->sm_callable = NULL; + Py_XDECREF(sm->sm_callable); + sm->sm_callable = NULL; - return 0; + return 0; } static PyObject * sm_descr_get(PyObject *self, PyObject *obj, PyObject *type) { - staticmethod *sm = (staticmethod *)self; + staticmethod *sm = (staticmethod *)self; - if (sm->sm_callable == NULL) { - PyErr_SetString(PyExc_RuntimeError, - "uninitialized staticmethod object"); - return NULL; - } - Py_INCREF(sm->sm_callable); - return sm->sm_callable; + if (sm->sm_callable == NULL) { + PyErr_SetString(PyExc_RuntimeError, + "uninitialized staticmethod object"); + return NULL; + } + Py_INCREF(sm->sm_callable); + return sm->sm_callable; } static int sm_init(PyObject *self, PyObject *args, PyObject *kwds) { - staticmethod *sm = (staticmethod *)self; - PyObject *callable; + staticmethod *sm = (staticmethod *)self; + PyObject *callable; - if (!PyArg_UnpackTuple(args, "staticmethod", 1, 1, &callable)) - return -1; - if (!_PyArg_NoKeywords("staticmethod", kwds)) - return -1; - Py_INCREF(callable); - sm->sm_callable = callable; - return 0; + if (!PyArg_UnpackTuple(args, "staticmethod", 1, 1, &callable)) + return -1; + if (!_PyArg_NoKeywords("staticmethod", kwds)) + return -1; + Py_INCREF(callable); + sm->sm_callable = callable; + return 0; } static PyMemberDef sm_memberlist[] = { - {"__func__", T_OBJECT, offsetof(staticmethod, sm_callable), READONLY}, - {NULL} /* Sentinel */ + {"__func__", T_OBJECT, offsetof(staticmethod, sm_callable), READONLY}, + {NULL} /* Sentinel */ }; PyDoc_STRVAR(staticmethod_doc, @@ -939,8 +939,8 @@ To declare a static method, use this idiom:\n\ \n\ class C:\n\ - def f(arg1, arg2, ...): ...\n\ - f = staticmethod(f)\n\ + def f(arg1, arg2, ...): ...\n\ + f = staticmethod(f)\n\ \n\ It can be called either on the class (e.g. C.f()) or on an instance\n\ (e.g. C().f()). The instance is ignored except for its class.\n\ @@ -949,55 +949,55 @@ For a more advanced concept, see the classmethod builtin."); PyTypeObject PyStaticMethod_Type = { - PyVarObject_HEAD_INIT(&PyType_Type, 0) - "staticmethod", - sizeof(staticmethod), - 0, - (destructor)sm_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_BASETYPE | Py_TPFLAGS_HAVE_GC, - staticmethod_doc, /* tp_doc */ - (traverseproc)sm_traverse, /* tp_traverse */ - (inquiry)sm_clear, /* tp_clear */ - 0, /* tp_richcompare */ - 0, /* tp_weaklistoffset */ - 0, /* tp_iter */ - 0, /* tp_iternext */ - 0, /* tp_methods */ - sm_memberlist, /* tp_members */ - 0, /* tp_getset */ - 0, /* tp_base */ - 0, /* tp_dict */ - sm_descr_get, /* tp_descr_get */ - 0, /* tp_descr_set */ - 0, /* tp_dictoffset */ - sm_init, /* tp_init */ - PyType_GenericAlloc, /* tp_alloc */ - PyType_GenericNew, /* tp_new */ - PyObject_GC_Del, /* tp_free */ + PyVarObject_HEAD_INIT(&PyType_Type, 0) + "staticmethod", + sizeof(staticmethod), + 0, + (destructor)sm_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_BASETYPE | Py_TPFLAGS_HAVE_GC, + staticmethod_doc, /* tp_doc */ + (traverseproc)sm_traverse, /* tp_traverse */ + (inquiry)sm_clear, /* tp_clear */ + 0, /* tp_richcompare */ + 0, /* tp_weaklistoffset */ + 0, /* tp_iter */ + 0, /* tp_iternext */ + 0, /* tp_methods */ + sm_memberlist, /* tp_members */ + 0, /* tp_getset */ + 0, /* tp_base */ + 0, /* tp_dict */ + sm_descr_get, /* tp_descr_get */ + 0, /* tp_descr_set */ + 0, /* tp_dictoffset */ + sm_init, /* tp_init */ + PyType_GenericAlloc, /* tp_alloc */ + PyType_GenericNew, /* tp_new */ + PyObject_GC_Del, /* tp_free */ }; PyObject * PyStaticMethod_New(PyObject *callable) { - staticmethod *sm = (staticmethod *) - PyType_GenericAlloc(&PyStaticMethod_Type, 0); - if (sm != NULL) { - Py_INCREF(callable); - sm->sm_callable = callable; - } - return (PyObject *)sm; + staticmethod *sm = (staticmethod *) + PyType_GenericAlloc(&PyStaticMethod_Type, 0); + if (sm != NULL) { + Py_INCREF(callable); + sm->sm_callable = callable; + } + return (PyObject *)sm; } Modified: python/branches/release31-maint/Objects/genobject.c ============================================================================== --- python/branches/release31-maint/Objects/genobject.c (original) +++ python/branches/release31-maint/Objects/genobject.c Sun May 9 18:14:21 2010 @@ -10,103 +10,103 @@ static int gen_traverse(PyGenObject *gen, visitproc visit, void *arg) { - Py_VISIT((PyObject *)gen->gi_frame); - Py_VISIT(gen->gi_code); - return 0; + Py_VISIT((PyObject *)gen->gi_frame); + Py_VISIT(gen->gi_code); + return 0; } static void gen_dealloc(PyGenObject *gen) { - PyObject *self = (PyObject *) gen; + PyObject *self = (PyObject *) gen; - _PyObject_GC_UNTRACK(gen); + _PyObject_GC_UNTRACK(gen); - if (gen->gi_weakreflist != NULL) - PyObject_ClearWeakRefs(self); + if (gen->gi_weakreflist != NULL) + PyObject_ClearWeakRefs(self); - _PyObject_GC_TRACK(self); + _PyObject_GC_TRACK(self); - if (gen->gi_frame != NULL && gen->gi_frame->f_stacktop != NULL) { - /* Generator is paused, so we need to close */ - Py_TYPE(gen)->tp_del(self); - if (self->ob_refcnt > 0) - return; /* resurrected. :( */ - } - - _PyObject_GC_UNTRACK(self); - Py_CLEAR(gen->gi_frame); - Py_CLEAR(gen->gi_code); - PyObject_GC_Del(gen); + if (gen->gi_frame != NULL && gen->gi_frame->f_stacktop != NULL) { + /* Generator is paused, so we need to close */ + Py_TYPE(gen)->tp_del(self); + if (self->ob_refcnt > 0) + return; /* resurrected. :( */ + } + + _PyObject_GC_UNTRACK(self); + Py_CLEAR(gen->gi_frame); + Py_CLEAR(gen->gi_code); + PyObject_GC_Del(gen); } static PyObject * gen_send_ex(PyGenObject *gen, PyObject *arg, int exc) { - PyThreadState *tstate = PyThreadState_GET(); - PyFrameObject *f = gen->gi_frame; - PyObject *result; - - if (gen->gi_running) { - PyErr_SetString(PyExc_ValueError, - "generator already executing"); - return NULL; - } - if (f==NULL || f->f_stacktop == NULL) { - /* Only set exception if called from send() */ - if (arg && !exc) - PyErr_SetNone(PyExc_StopIteration); - return NULL; - } - - if (f->f_lasti == -1) { - if (arg && arg != Py_None) { - PyErr_SetString(PyExc_TypeError, - "can't send non-None value to a " - "just-started generator"); - return NULL; - } - } else { - /* Push arg onto the frame's value stack */ - result = arg ? arg : Py_None; - Py_INCREF(result); - *(f->f_stacktop++) = result; - } - - /* Generators always return to their most recent caller, not - * necessarily their creator. */ - Py_XINCREF(tstate->frame); - assert(f->f_back == NULL); - f->f_back = tstate->frame; - - gen->gi_running = 1; - result = PyEval_EvalFrameEx(f, exc); - gen->gi_running = 0; - - /* Don't keep the reference to f_back any longer than necessary. It - * may keep a chain of frames alive or it could create a reference - * cycle. */ - assert(f->f_back == tstate->frame); - Py_CLEAR(f->f_back); - - /* If the generator just returned (as opposed to yielding), signal - * that the generator is exhausted. */ - if (result == Py_None && f->f_stacktop == NULL) { - Py_DECREF(result); - result = NULL; - /* Set exception if not called by gen_iternext() */ - if (arg) - PyErr_SetNone(PyExc_StopIteration); - } - - if (!result || f->f_stacktop == NULL) { - /* generator can't be rerun, so release the frame */ - Py_DECREF(f); - gen->gi_frame = NULL; - } + PyThreadState *tstate = PyThreadState_GET(); + PyFrameObject *f = gen->gi_frame; + PyObject *result; + + if (gen->gi_running) { + PyErr_SetString(PyExc_ValueError, + "generator already executing"); + return NULL; + } + if (f==NULL || f->f_stacktop == NULL) { + /* Only set exception if called from send() */ + if (arg && !exc) + PyErr_SetNone(PyExc_StopIteration); + return NULL; + } + + if (f->f_lasti == -1) { + if (arg && arg != Py_None) { + PyErr_SetString(PyExc_TypeError, + "can't send non-None value to a " + "just-started generator"); + return NULL; + } + } else { + /* Push arg onto the frame's value stack */ + result = arg ? arg : Py_None; + Py_INCREF(result); + *(f->f_stacktop++) = result; + } + + /* Generators always return to their most recent caller, not + * necessarily their creator. */ + Py_XINCREF(tstate->frame); + assert(f->f_back == NULL); + f->f_back = tstate->frame; + + gen->gi_running = 1; + result = PyEval_EvalFrameEx(f, exc); + gen->gi_running = 0; + + /* Don't keep the reference to f_back any longer than necessary. It + * may keep a chain of frames alive or it could create a reference + * cycle. */ + assert(f->f_back == tstate->frame); + Py_CLEAR(f->f_back); + + /* If the generator just returned (as opposed to yielding), signal + * that the generator is exhausted. */ + if (result == Py_None && f->f_stacktop == NULL) { + Py_DECREF(result); + result = NULL; + /* Set exception if not called by gen_iternext() */ + if (arg) + PyErr_SetNone(PyExc_StopIteration); + } + + if (!result || f->f_stacktop == NULL) { + /* generator can't be rerun, so release the frame */ + Py_DECREF(f); + gen->gi_frame = NULL; + } - return result; + return result; } PyDoc_STRVAR(send_doc, @@ -116,7 +116,7 @@ static PyObject * gen_send(PyGenObject *gen, PyObject *arg) { - return gen_send_ex(gen, arg, 0); + return gen_send_ex(gen, arg, 0); } PyDoc_STRVAR(close_doc, @@ -125,83 +125,83 @@ static PyObject * gen_close(PyGenObject *gen, PyObject *args) { - PyObject *retval; - PyErr_SetNone(PyExc_GeneratorExit); - retval = gen_send_ex(gen, Py_None, 1); - if (retval) { - Py_DECREF(retval); - PyErr_SetString(PyExc_RuntimeError, - "generator ignored GeneratorExit"); - return NULL; - } - if (PyErr_ExceptionMatches(PyExc_StopIteration) - || PyErr_ExceptionMatches(PyExc_GeneratorExit)) - { - PyErr_Clear(); /* ignore these errors */ - Py_INCREF(Py_None); - return Py_None; - } - return NULL; + PyObject *retval; + PyErr_SetNone(PyExc_GeneratorExit); + retval = gen_send_ex(gen, Py_None, 1); + if (retval) { + Py_DECREF(retval); + PyErr_SetString(PyExc_RuntimeError, + "generator ignored GeneratorExit"); + return NULL; + } + if (PyErr_ExceptionMatches(PyExc_StopIteration) + || PyErr_ExceptionMatches(PyExc_GeneratorExit)) + { + PyErr_Clear(); /* ignore these errors */ + Py_INCREF(Py_None); + return Py_None; + } + return NULL; } static void gen_del(PyObject *self) { - PyObject *res; - PyObject *error_type, *error_value, *error_traceback; - PyGenObject *gen = (PyGenObject *)self; - - if (gen->gi_frame == NULL || gen->gi_frame->f_stacktop == NULL) - /* Generator isn't paused, so no need to close */ - return; - - /* Temporarily resurrect the object. */ - assert(self->ob_refcnt == 0); - self->ob_refcnt = 1; - - /* Save the current exception, if any. */ - PyErr_Fetch(&error_type, &error_value, &error_traceback); - - res = gen_close(gen, NULL); - - if (res == NULL) - PyErr_WriteUnraisable(self); - else - Py_DECREF(res); - - /* Restore the saved exception. */ - PyErr_Restore(error_type, error_value, error_traceback); - - /* Undo the temporary resurrection; can't use DECREF here, it would - * cause a recursive call. - */ - assert(self->ob_refcnt > 0); - if (--self->ob_refcnt == 0) - return; /* this is the normal path out */ - - /* close() resurrected it! Make it look like the original Py_DECREF - * never happened. - */ - { - Py_ssize_t refcnt = self->ob_refcnt; - _Py_NewReference(self); - self->ob_refcnt = refcnt; - } - assert(PyType_IS_GC(self->ob_type) && - _Py_AS_GC(self)->gc.gc_refs != _PyGC_REFS_UNTRACKED); - - /* If Py_REF_DEBUG, _Py_NewReference bumped _Py_RefTotal, so - * we need to undo that. */ - _Py_DEC_REFTOTAL; - /* If Py_TRACE_REFS, _Py_NewReference re-added self to the object - * chain, so no more to do there. - * If COUNT_ALLOCS, the original decref bumped tp_frees, and - * _Py_NewReference bumped tp_allocs: both of those need to be - * undone. - */ + PyObject *res; + PyObject *error_type, *error_value, *error_traceback; + PyGenObject *gen = (PyGenObject *)self; + + if (gen->gi_frame == NULL || gen->gi_frame->f_stacktop == NULL) + /* Generator isn't paused, so no need to close */ + return; + + /* Temporarily resurrect the object. */ + assert(self->ob_refcnt == 0); + self->ob_refcnt = 1; + + /* Save the current exception, if any. */ + PyErr_Fetch(&error_type, &error_value, &error_traceback); + + res = gen_close(gen, NULL); + + if (res == NULL) + PyErr_WriteUnraisable(self); + else + Py_DECREF(res); + + /* Restore the saved exception. */ + PyErr_Restore(error_type, error_value, error_traceback); + + /* Undo the temporary resurrection; can't use DECREF here, it would + * cause a recursive call. + */ + assert(self->ob_refcnt > 0); + if (--self->ob_refcnt == 0) + return; /* this is the normal path out */ + + /* close() resurrected it! Make it look like the original Py_DECREF + * never happened. + */ + { + Py_ssize_t refcnt = self->ob_refcnt; + _Py_NewReference(self); + self->ob_refcnt = refcnt; + } + assert(PyType_IS_GC(self->ob_type) && + _Py_AS_GC(self)->gc.gc_refs != _PyGC_REFS_UNTRACKED); + + /* If Py_REF_DEBUG, _Py_NewReference bumped _Py_RefTotal, so + * we need to undo that. */ + _Py_DEC_REFTOTAL; + /* If Py_TRACE_REFS, _Py_NewReference re-added self to the object + * chain, so no more to do there. + * If COUNT_ALLOCS, the original decref bumped tp_frees, and + * _Py_NewReference bumped tp_allocs: both of those need to be + * undone. + */ #ifdef COUNT_ALLOCS - --self->ob_type->tp_frees; - --self->ob_type->tp_allocs; + --self->ob_type->tp_frees; + --self->ob_type->tp_allocs; #endif } @@ -214,89 +214,89 @@ static PyObject * gen_throw(PyGenObject *gen, PyObject *args) { - PyObject *typ; - PyObject *tb = NULL; - PyObject *val = NULL; - - if (!PyArg_UnpackTuple(args, "throw", 1, 3, &typ, &val, &tb)) - return NULL; - - /* First, check the traceback argument, replacing None with - NULL. */ - if (tb == Py_None) - tb = NULL; - else if (tb != NULL && !PyTraceBack_Check(tb)) { - PyErr_SetString(PyExc_TypeError, - "throw() third argument must be a traceback object"); - return NULL; - } - - Py_INCREF(typ); - Py_XINCREF(val); - Py_XINCREF(tb); - - if (PyExceptionClass_Check(typ)) { - PyErr_NormalizeException(&typ, &val, &tb); - } - - else if (PyExceptionInstance_Check(typ)) { - /* Raising an instance. The value should be a dummy. */ - if (val && val != Py_None) { - PyErr_SetString(PyExc_TypeError, - "instance exception may not have a separate value"); - goto failed_throw; - } - else { - /* Normalize to raise , */ - Py_XDECREF(val); - val = typ; - typ = PyExceptionInstance_Class(typ); - Py_INCREF(typ); - } - } - else { - /* Not something you can raise. throw() fails. */ - PyErr_Format(PyExc_TypeError, - "exceptions must be classes or instances " - "deriving from BaseException, not %s", - typ->ob_type->tp_name); - goto failed_throw; - } + PyObject *typ; + PyObject *tb = NULL; + PyObject *val = NULL; + + if (!PyArg_UnpackTuple(args, "throw", 1, 3, &typ, &val, &tb)) + return NULL; + + /* First, check the traceback argument, replacing None with + NULL. */ + if (tb == Py_None) + tb = NULL; + else if (tb != NULL && !PyTraceBack_Check(tb)) { + PyErr_SetString(PyExc_TypeError, + "throw() third argument must be a traceback object"); + return NULL; + } + + Py_INCREF(typ); + Py_XINCREF(val); + Py_XINCREF(tb); + + if (PyExceptionClass_Check(typ)) { + PyErr_NormalizeException(&typ, &val, &tb); + } + + else if (PyExceptionInstance_Check(typ)) { + /* Raising an instance. The value should be a dummy. */ + if (val && val != Py_None) { + PyErr_SetString(PyExc_TypeError, + "instance exception may not have a separate value"); + goto failed_throw; + } + else { + /* Normalize to raise , */ + Py_XDECREF(val); + val = typ; + typ = PyExceptionInstance_Class(typ); + Py_INCREF(typ); + } + } + else { + /* Not something you can raise. throw() fails. */ + PyErr_Format(PyExc_TypeError, + "exceptions must be classes or instances " + "deriving from BaseException, not %s", + typ->ob_type->tp_name); + goto failed_throw; + } - PyErr_Restore(typ, val, tb); - return gen_send_ex(gen, Py_None, 1); + PyErr_Restore(typ, val, tb); + return gen_send_ex(gen, Py_None, 1); failed_throw: - /* Didn't use our arguments, so restore their original refcounts */ - Py_DECREF(typ); - Py_XDECREF(val); - Py_XDECREF(tb); - return NULL; + /* Didn't use our arguments, so restore their original refcounts */ + Py_DECREF(typ); + Py_XDECREF(val); + Py_XDECREF(tb); + return NULL; } static PyObject * gen_iternext(PyGenObject *gen) { - return gen_send_ex(gen, NULL, 0); + return gen_send_ex(gen, NULL, 0); } static PyObject * gen_repr(PyGenObject *gen) { - return PyUnicode_FromFormat("", - ((PyCodeObject *)gen->gi_code)->co_name, - gen); + return PyUnicode_FromFormat("", + ((PyCodeObject *)gen->gi_code)->co_name, + gen); } static PyObject * gen_get_name(PyGenObject *gen) { - PyObject *name = ((PyCodeObject *)gen->gi_code)->co_name; - Py_INCREF(name); - return name; + PyObject *name = ((PyCodeObject *)gen->gi_code)->co_name; + Py_INCREF(name); + return name; } @@ -304,109 +304,109 @@ "Return the name of the generator's associated code object."); static PyGetSetDef gen_getsetlist[] = { - {"__name__", (getter)gen_get_name, NULL, gen__name__doc__}, - {NULL} + {"__name__", (getter)gen_get_name, NULL, gen__name__doc__}, + {NULL} }; static PyMemberDef gen_memberlist[] = { - {"gi_frame", T_OBJECT, offsetof(PyGenObject, gi_frame), READONLY}, - {"gi_running", T_INT, offsetof(PyGenObject, gi_running), READONLY}, - {"gi_code", T_OBJECT, offsetof(PyGenObject, gi_code), READONLY}, - {NULL} /* Sentinel */ + {"gi_frame", T_OBJECT, offsetof(PyGenObject, gi_frame), READONLY}, + {"gi_running", T_INT, offsetof(PyGenObject, gi_running), READONLY}, + {"gi_code", T_OBJECT, offsetof(PyGenObject, gi_code), READONLY}, + {NULL} /* Sentinel */ }; static PyMethodDef gen_methods[] = { - {"send",(PyCFunction)gen_send, METH_O, send_doc}, - {"throw",(PyCFunction)gen_throw, METH_VARARGS, throw_doc}, - {"close",(PyCFunction)gen_close, METH_NOARGS, close_doc}, - {NULL, NULL} /* Sentinel */ + {"send",(PyCFunction)gen_send, METH_O, send_doc}, + {"throw",(PyCFunction)gen_throw, METH_VARARGS, throw_doc}, + {"close",(PyCFunction)gen_close, METH_NOARGS, close_doc}, + {NULL, NULL} /* Sentinel */ }; PyTypeObject PyGen_Type = { - PyVarObject_HEAD_INIT(&PyType_Type, 0) - "generator", /* tp_name */ - sizeof(PyGenObject), /* tp_basicsize */ - 0, /* tp_itemsize */ - /* methods */ - (destructor)gen_dealloc, /* tp_dealloc */ - 0, /* tp_print */ - 0, /* tp_getattr */ - 0, /* tp_setattr */ - 0, /* tp_reserved */ - (reprfunc)gen_repr, /* 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)gen_traverse, /* tp_traverse */ - 0, /* tp_clear */ - 0, /* tp_richcompare */ - offsetof(PyGenObject, gi_weakreflist), /* tp_weaklistoffset */ - PyObject_SelfIter, /* tp_iter */ - (iternextfunc)gen_iternext, /* tp_iternext */ - gen_methods, /* tp_methods */ - gen_memberlist, /* tp_members */ - gen_getsetlist, /* tp_getset */ - 0, /* tp_base */ - 0, /* tp_dict */ - - 0, /* tp_descr_get */ - 0, /* tp_descr_set */ - 0, /* tp_dictoffset */ - 0, /* tp_init */ - 0, /* tp_alloc */ - 0, /* tp_new */ - 0, /* tp_free */ - 0, /* tp_is_gc */ - 0, /* tp_bases */ - 0, /* tp_mro */ - 0, /* tp_cache */ - 0, /* tp_subclasses */ - 0, /* tp_weaklist */ - gen_del, /* tp_del */ + PyVarObject_HEAD_INIT(&PyType_Type, 0) + "generator", /* tp_name */ + sizeof(PyGenObject), /* tp_basicsize */ + 0, /* tp_itemsize */ + /* methods */ + (destructor)gen_dealloc, /* tp_dealloc */ + 0, /* tp_print */ + 0, /* tp_getattr */ + 0, /* tp_setattr */ + 0, /* tp_reserved */ + (reprfunc)gen_repr, /* 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)gen_traverse, /* tp_traverse */ + 0, /* tp_clear */ + 0, /* tp_richcompare */ + offsetof(PyGenObject, gi_weakreflist), /* tp_weaklistoffset */ + PyObject_SelfIter, /* tp_iter */ + (iternextfunc)gen_iternext, /* tp_iternext */ + gen_methods, /* tp_methods */ + gen_memberlist, /* tp_members */ + gen_getsetlist, /* tp_getset */ + 0, /* tp_base */ + 0, /* tp_dict */ + + 0, /* tp_descr_get */ + 0, /* tp_descr_set */ + 0, /* tp_dictoffset */ + 0, /* tp_init */ + 0, /* tp_alloc */ + 0, /* tp_new */ + 0, /* tp_free */ + 0, /* tp_is_gc */ + 0, /* tp_bases */ + 0, /* tp_mro */ + 0, /* tp_cache */ + 0, /* tp_subclasses */ + 0, /* tp_weaklist */ + gen_del, /* tp_del */ }; PyObject * PyGen_New(PyFrameObject *f) { - PyGenObject *gen = PyObject_GC_New(PyGenObject, &PyGen_Type); - if (gen == NULL) { - Py_DECREF(f); - return NULL; - } - gen->gi_frame = f; - Py_INCREF(f->f_code); - gen->gi_code = (PyObject *)(f->f_code); - gen->gi_running = 0; - gen->gi_weakreflist = NULL; - _PyObject_GC_TRACK(gen); - return (PyObject *)gen; + PyGenObject *gen = PyObject_GC_New(PyGenObject, &PyGen_Type); + if (gen == NULL) { + Py_DECREF(f); + return NULL; + } + gen->gi_frame = f; + Py_INCREF(f->f_code); + gen->gi_code = (PyObject *)(f->f_code); + gen->gi_running = 0; + gen->gi_weakreflist = NULL; + _PyObject_GC_TRACK(gen); + return (PyObject *)gen; } int PyGen_NeedsFinalizing(PyGenObject *gen) { - int i; - PyFrameObject *f = gen->gi_frame; + int i; + PyFrameObject *f = gen->gi_frame; - if (f == NULL || f->f_stacktop == NULL || f->f_iblock <= 0) - return 0; /* no frame or empty blockstack == no finalization */ + if (f == NULL || f->f_stacktop == NULL || f->f_iblock <= 0) + return 0; /* no frame or empty blockstack == no finalization */ - /* Any block type besides a loop requires cleanup. */ - i = f->f_iblock; - while (--i >= 0) { - if (f->f_blockstack[i].b_type != SETUP_LOOP) - return 1; - } + /* Any block type besides a loop requires cleanup. */ + i = f->f_iblock; + while (--i >= 0) { + if (f->f_blockstack[i].b_type != SETUP_LOOP) + return 1; + } - /* No blocks except loops, it's safe to skip finalization. */ - return 0; + /* No blocks except loops, it's safe to skip finalization. */ + return 0; } Modified: python/branches/release31-maint/Objects/iterobject.c ============================================================================== --- python/branches/release31-maint/Objects/iterobject.c (original) +++ python/branches/release31-maint/Objects/iterobject.c Sun May 9 18:14:21 2010 @@ -3,230 +3,230 @@ #include "Python.h" typedef struct { - PyObject_HEAD - long it_index; - PyObject *it_seq; /* Set to NULL when iterator is exhausted */ + PyObject_HEAD + long it_index; + PyObject *it_seq; /* Set to NULL when iterator is exhausted */ } seqiterobject; PyObject * PySeqIter_New(PyObject *seq) { - seqiterobject *it; + seqiterobject *it; - if (!PySequence_Check(seq)) { - PyErr_BadInternalCall(); - return NULL; - } - it = PyObject_GC_New(seqiterobject, &PySeqIter_Type); - if (it == NULL) - return NULL; - it->it_index = 0; - Py_INCREF(seq); - it->it_seq = seq; - _PyObject_GC_TRACK(it); - return (PyObject *)it; + if (!PySequence_Check(seq)) { + PyErr_BadInternalCall(); + return NULL; + } + it = PyObject_GC_New(seqiterobject, &PySeqIter_Type); + if (it == NULL) + return NULL; + it->it_index = 0; + Py_INCREF(seq); + it->it_seq = seq; + _PyObject_GC_TRACK(it); + return (PyObject *)it; } static void iter_dealloc(seqiterobject *it) { - _PyObject_GC_UNTRACK(it); - Py_XDECREF(it->it_seq); - PyObject_GC_Del(it); + _PyObject_GC_UNTRACK(it); + Py_XDECREF(it->it_seq); + PyObject_GC_Del(it); } static int iter_traverse(seqiterobject *it, visitproc visit, void *arg) { - Py_VISIT(it->it_seq); - return 0; + Py_VISIT(it->it_seq); + return 0; } static PyObject * iter_iternext(PyObject *iterator) { - seqiterobject *it; - PyObject *seq; - PyObject *result; - - assert(PySeqIter_Check(iterator)); - it = (seqiterobject *)iterator; - seq = it->it_seq; - if (seq == NULL) - return NULL; - - result = PySequence_GetItem(seq, it->it_index); - if (result != NULL) { - it->it_index++; - return result; - } - if (PyErr_ExceptionMatches(PyExc_IndexError) || - PyErr_ExceptionMatches(PyExc_StopIteration)) - { - PyErr_Clear(); - Py_DECREF(seq); - it->it_seq = NULL; - } - return NULL; + seqiterobject *it; + PyObject *seq; + PyObject *result; + + assert(PySeqIter_Check(iterator)); + it = (seqiterobject *)iterator; + seq = it->it_seq; + if (seq == NULL) + return NULL; + + result = PySequence_GetItem(seq, it->it_index); + if (result != NULL) { + it->it_index++; + return result; + } + if (PyErr_ExceptionMatches(PyExc_IndexError) || + PyErr_ExceptionMatches(PyExc_StopIteration)) + { + PyErr_Clear(); + Py_DECREF(seq); + it->it_seq = NULL; + } + return NULL; } static PyObject * iter_len(seqiterobject *it) { - Py_ssize_t seqsize, len; + Py_ssize_t seqsize, len; - if (it->it_seq) { - seqsize = PySequence_Size(it->it_seq); - if (seqsize == -1) - return NULL; - len = seqsize - it->it_index; - if (len >= 0) - return PyLong_FromSsize_t(len); - } - return PyLong_FromLong(0); + if (it->it_seq) { + seqsize = PySequence_Size(it->it_seq); + if (seqsize == -1) + return NULL; + len = seqsize - it->it_index; + if (len >= 0) + return PyLong_FromSsize_t(len); + } + return PyLong_FromLong(0); } PyDoc_STRVAR(length_hint_doc, "Private method returning an estimate of len(list(it))."); static PyMethodDef seqiter_methods[] = { - {"__length_hint__", (PyCFunction)iter_len, METH_NOARGS, length_hint_doc}, - {NULL, NULL} /* sentinel */ + {"__length_hint__", (PyCFunction)iter_len, METH_NOARGS, length_hint_doc}, + {NULL, NULL} /* sentinel */ }; PyTypeObject PySeqIter_Type = { - PyVarObject_HEAD_INIT(&PyType_Type, 0) - "iterator", /* tp_name */ - sizeof(seqiterobject), /* tp_basicsize */ - 0, /* tp_itemsize */ - /* methods */ - (destructor)iter_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)iter_traverse, /* tp_traverse */ - 0, /* tp_clear */ - 0, /* tp_richcompare */ - 0, /* tp_weaklistoffset */ - PyObject_SelfIter, /* tp_iter */ - iter_iternext, /* tp_iternext */ - seqiter_methods, /* tp_methods */ - 0, /* tp_members */ + PyVarObject_HEAD_INIT(&PyType_Type, 0) + "iterator", /* tp_name */ + sizeof(seqiterobject), /* tp_basicsize */ + 0, /* tp_itemsize */ + /* methods */ + (destructor)iter_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)iter_traverse, /* tp_traverse */ + 0, /* tp_clear */ + 0, /* tp_richcompare */ + 0, /* tp_weaklistoffset */ + PyObject_SelfIter, /* tp_iter */ + iter_iternext, /* tp_iternext */ + seqiter_methods, /* tp_methods */ + 0, /* tp_members */ }; /* -------------------------------------- */ typedef struct { - PyObject_HEAD - PyObject *it_callable; /* Set to NULL when iterator is exhausted */ - PyObject *it_sentinel; /* Set to NULL when iterator is exhausted */ + PyObject_HEAD + PyObject *it_callable; /* Set to NULL when iterator is exhausted */ + PyObject *it_sentinel; /* Set to NULL when iterator is exhausted */ } calliterobject; PyObject * PyCallIter_New(PyObject *callable, PyObject *sentinel) { - calliterobject *it; - it = PyObject_GC_New(calliterobject, &PyCallIter_Type); - if (it == NULL) - return NULL; - Py_INCREF(callable); - it->it_callable = callable; - Py_INCREF(sentinel); - it->it_sentinel = sentinel; - _PyObject_GC_TRACK(it); - return (PyObject *)it; + calliterobject *it; + it = PyObject_GC_New(calliterobject, &PyCallIter_Type); + if (it == NULL) + return NULL; + Py_INCREF(callable); + it->it_callable = callable; + Py_INCREF(sentinel); + it->it_sentinel = sentinel; + _PyObject_GC_TRACK(it); + return (PyObject *)it; } static void calliter_dealloc(calliterobject *it) { - _PyObject_GC_UNTRACK(it); - Py_XDECREF(it->it_callable); - Py_XDECREF(it->it_sentinel); - PyObject_GC_Del(it); + _PyObject_GC_UNTRACK(it); + Py_XDECREF(it->it_callable); + Py_XDECREF(it->it_sentinel); + PyObject_GC_Del(it); } static int calliter_traverse(calliterobject *it, visitproc visit, void *arg) { - Py_VISIT(it->it_callable); - Py_VISIT(it->it_sentinel); - return 0; + Py_VISIT(it->it_callable); + Py_VISIT(it->it_sentinel); + return 0; } static PyObject * calliter_iternext(calliterobject *it) { - if (it->it_callable != NULL) { - PyObject *args = PyTuple_New(0); - PyObject *result; - if (args == NULL) - return NULL; - result = PyObject_Call(it->it_callable, args, NULL); - Py_DECREF(args); - if (result != NULL) { - int ok; - ok = PyObject_RichCompareBool(result, - it->it_sentinel, - Py_EQ); - if (ok == 0) - return result; /* Common case, fast path */ - Py_DECREF(result); - if (ok > 0) { - Py_CLEAR(it->it_callable); - Py_CLEAR(it->it_sentinel); - } - } - else if (PyErr_ExceptionMatches(PyExc_StopIteration)) { - PyErr_Clear(); - Py_CLEAR(it->it_callable); - Py_CLEAR(it->it_sentinel); - } - } - return NULL; + if (it->it_callable != NULL) { + PyObject *args = PyTuple_New(0); + PyObject *result; + if (args == NULL) + return NULL; + result = PyObject_Call(it->it_callable, args, NULL); + Py_DECREF(args); + if (result != NULL) { + int ok; + ok = PyObject_RichCompareBool(result, + it->it_sentinel, + Py_EQ); + if (ok == 0) + return result; /* Common case, fast path */ + Py_DECREF(result); + if (ok > 0) { + Py_CLEAR(it->it_callable); + Py_CLEAR(it->it_sentinel); + } + } + else if (PyErr_ExceptionMatches(PyExc_StopIteration)) { + PyErr_Clear(); + Py_CLEAR(it->it_callable); + Py_CLEAR(it->it_sentinel); + } + } + return NULL; } PyTypeObject PyCallIter_Type = { - PyVarObject_HEAD_INIT(&PyType_Type, 0) - "callable_iterator", /* tp_name */ - sizeof(calliterobject), /* tp_basicsize */ - 0, /* tp_itemsize */ - /* methods */ - (destructor)calliter_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)calliter_traverse, /* tp_traverse */ - 0, /* tp_clear */ - 0, /* tp_richcompare */ - 0, /* tp_weaklistoffset */ - PyObject_SelfIter, /* tp_iter */ - (iternextfunc)calliter_iternext, /* tp_iternext */ - 0, /* tp_methods */ + PyVarObject_HEAD_INIT(&PyType_Type, 0) + "callable_iterator", /* tp_name */ + sizeof(calliterobject), /* tp_basicsize */ + 0, /* tp_itemsize */ + /* methods */ + (destructor)calliter_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)calliter_traverse, /* tp_traverse */ + 0, /* tp_clear */ + 0, /* tp_richcompare */ + 0, /* tp_weaklistoffset */ + PyObject_SelfIter, /* tp_iter */ + (iternextfunc)calliter_iternext, /* tp_iternext */ + 0, /* tp_methods */ }; Modified: python/branches/release31-maint/Objects/listobject.c ============================================================================== --- python/branches/release31-maint/Objects/listobject.c (original) +++ python/branches/release31-maint/Objects/listobject.c Sun May 9 18:14:21 2010 @@ -5,7 +5,7 @@ #ifdef STDC_HEADERS #include #else -#include /* For size_t */ +#include /* For size_t */ #endif /* Ensure ob_item has room for at least newsize elements, and set @@ -24,52 +24,52 @@ static int list_resize(PyListObject *self, Py_ssize_t newsize) { - PyObject **items; - size_t new_allocated; - Py_ssize_t allocated = self->allocated; - - /* Bypass realloc() when a previous overallocation is large enough - to accommodate the newsize. If the newsize falls lower than half - the allocated size, then proceed with the realloc() to shrink the list. - */ - if (allocated >= newsize && newsize >= (allocated >> 1)) { - assert(self->ob_item != NULL || newsize == 0); - Py_SIZE(self) = newsize; - return 0; - } - - /* This over-allocates proportional to the list size, making room - * for additional growth. The over-allocation is mild, but is - * enough to give linear-time amortized behavior over a long - * sequence of appends() in the presence of a poorly-performing - * system realloc(). - * The growth pattern is: 0, 4, 8, 16, 25, 35, 46, 58, 72, 88, ... - */ - new_allocated = (newsize >> 3) + (newsize < 9 ? 3 : 6); - - /* check for integer overflow */ - if (new_allocated > PY_SIZE_MAX - newsize) { - PyErr_NoMemory(); - return -1; - } else { - new_allocated += newsize; - } - - if (newsize == 0) - new_allocated = 0; - items = self->ob_item; - if (new_allocated <= ((~(size_t)0) / sizeof(PyObject *))) - PyMem_RESIZE(items, PyObject *, new_allocated); - else - items = NULL; - if (items == NULL) { - PyErr_NoMemory(); - return -1; - } - self->ob_item = items; - Py_SIZE(self) = newsize; - self->allocated = new_allocated; - return 0; + PyObject **items; + size_t new_allocated; + Py_ssize_t allocated = self->allocated; + + /* Bypass realloc() when a previous overallocation is large enough + to accommodate the newsize. If the newsize falls lower than half + the allocated size, then proceed with the realloc() to shrink the list. + */ + if (allocated >= newsize && newsize >= (allocated >> 1)) { + assert(self->ob_item != NULL || newsize == 0); + Py_SIZE(self) = newsize; + return 0; + } + + /* This over-allocates proportional to the list size, making room + * for additional growth. The over-allocation is mild, but is + * enough to give linear-time amortized behavior over a long + * sequence of appends() in the presence of a poorly-performing + * system realloc(). + * The growth pattern is: 0, 4, 8, 16, 25, 35, 46, 58, 72, 88, ... + */ + new_allocated = (newsize >> 3) + (newsize < 9 ? 3 : 6); + + /* check for integer overflow */ + if (new_allocated > PY_SIZE_MAX - newsize) { + PyErr_NoMemory(); + return -1; + } else { + new_allocated += newsize; + } + + if (newsize == 0) + new_allocated = 0; + items = self->ob_item; + if (new_allocated <= ((~(size_t)0) / sizeof(PyObject *))) + PyMem_RESIZE(items, PyObject *, new_allocated); + else + items = NULL; + if (items == NULL) { + PyErr_NoMemory(); + return -1; + } + self->ob_item = items; + Py_SIZE(self) = newsize; + self->allocated = new_allocated; + return 0; } /* Debug statistic to compare allocations with reuse through the free list */ @@ -81,12 +81,12 @@ static void show_alloc(void) { - fprintf(stderr, "List allocations: %" PY_FORMAT_SIZE_T "d\n", - count_alloc); - fprintf(stderr, "List reuse through freelist: %" PY_FORMAT_SIZE_T - "d\n", count_reuse); - fprintf(stderr, "%.2f%% reuse rate\n\n", - (100.0*count_reuse/(count_alloc+count_reuse))); + fprintf(stderr, "List allocations: %" PY_FORMAT_SIZE_T "d\n", + count_alloc); + fprintf(stderr, "List reuse through freelist: %" PY_FORMAT_SIZE_T + "d\n", count_reuse); + fprintf(stderr, "%.2f%% reuse rate\n\n", + (100.0*count_reuse/(count_alloc+count_reuse))); } #endif @@ -100,77 +100,77 @@ void PyList_Fini(void) { - PyListObject *op; + PyListObject *op; - while (numfree) { - op = free_list[--numfree]; - assert(PyList_CheckExact(op)); - PyObject_GC_Del(op); - } + while (numfree) { + op = free_list[--numfree]; + assert(PyList_CheckExact(op)); + PyObject_GC_Del(op); + } } PyObject * PyList_New(Py_ssize_t size) { - PyListObject *op; - size_t nbytes; + PyListObject *op; + size_t nbytes; #ifdef SHOW_ALLOC_COUNT - static int initialized = 0; - if (!initialized) { - Py_AtExit(show_alloc); - initialized = 1; - } + static int initialized = 0; + if (!initialized) { + Py_AtExit(show_alloc); + initialized = 1; + } #endif - if (size < 0) { - PyErr_BadInternalCall(); - return NULL; - } - /* Check for overflow without an actual overflow, - * which can cause compiler to optimise out */ - if ((size_t)size > PY_SIZE_MAX / sizeof(PyObject *)) - return PyErr_NoMemory(); - nbytes = size * sizeof(PyObject *); - if (numfree) { - numfree--; - op = free_list[numfree]; - _Py_NewReference((PyObject *)op); + if (size < 0) { + PyErr_BadInternalCall(); + return NULL; + } + /* Check for overflow without an actual overflow, + * which can cause compiler to optimise out */ + if ((size_t)size > PY_SIZE_MAX / sizeof(PyObject *)) + return PyErr_NoMemory(); + nbytes = size * sizeof(PyObject *); + if (numfree) { + numfree--; + op = free_list[numfree]; + _Py_NewReference((PyObject *)op); #ifdef SHOW_ALLOC_COUNT - count_reuse++; + count_reuse++; #endif - } else { - op = PyObject_GC_New(PyListObject, &PyList_Type); - if (op == NULL) - return NULL; + } else { + op = PyObject_GC_New(PyListObject, &PyList_Type); + if (op == NULL) + return NULL; #ifdef SHOW_ALLOC_COUNT - count_alloc++; + count_alloc++; #endif - } - if (size <= 0) - op->ob_item = NULL; - else { - op->ob_item = (PyObject **) PyMem_MALLOC(nbytes); - if (op->ob_item == NULL) { - Py_DECREF(op); - return PyErr_NoMemory(); - } - memset(op->ob_item, 0, nbytes); - } - Py_SIZE(op) = size; - op->allocated = size; - _PyObject_GC_TRACK(op); - return (PyObject *) op; + } + if (size <= 0) + op->ob_item = NULL; + else { + op->ob_item = (PyObject **) PyMem_MALLOC(nbytes); + if (op->ob_item == NULL) { + Py_DECREF(op); + return PyErr_NoMemory(); + } + memset(op->ob_item, 0, nbytes); + } + Py_SIZE(op) = size; + op->allocated = size; + _PyObject_GC_TRACK(op); + return (PyObject *) op; } Py_ssize_t PyList_Size(PyObject *op) { - if (!PyList_Check(op)) { - PyErr_BadInternalCall(); - return -1; - } - else - return Py_SIZE(op); + if (!PyList_Check(op)) { + PyErr_BadInternalCall(); + return -1; + } + else + return Py_SIZE(op); } static PyObject *indexerr = NULL; @@ -178,117 +178,117 @@ PyObject * PyList_GetItem(PyObject *op, Py_ssize_t i) { - if (!PyList_Check(op)) { - PyErr_BadInternalCall(); - return NULL; - } - if (i < 0 || i >= Py_SIZE(op)) { - if (indexerr == NULL) { - indexerr = PyUnicode_FromString( - "list index out of range"); - if (indexerr == NULL) - return NULL; - } - PyErr_SetObject(PyExc_IndexError, indexerr); - return NULL; - } - return ((PyListObject *)op) -> ob_item[i]; + if (!PyList_Check(op)) { + PyErr_BadInternalCall(); + return NULL; + } + if (i < 0 || i >= Py_SIZE(op)) { + if (indexerr == NULL) { + indexerr = PyUnicode_FromString( + "list index out of range"); + if (indexerr == NULL) + return NULL; + } + PyErr_SetObject(PyExc_IndexError, indexerr); + return NULL; + } + return ((PyListObject *)op) -> ob_item[i]; } int PyList_SetItem(register PyObject *op, register Py_ssize_t i, register PyObject *newitem) { - register PyObject *olditem; - register PyObject **p; - if (!PyList_Check(op)) { - Py_XDECREF(newitem); - PyErr_BadInternalCall(); - return -1; - } - if (i < 0 || i >= Py_SIZE(op)) { - Py_XDECREF(newitem); - PyErr_SetString(PyExc_IndexError, - "list assignment index out of range"); - return -1; - } - p = ((PyListObject *)op) -> ob_item + i; - olditem = *p; - *p = newitem; - Py_XDECREF(olditem); - return 0; + register PyObject *olditem; + register PyObject **p; + if (!PyList_Check(op)) { + Py_XDECREF(newitem); + PyErr_BadInternalCall(); + return -1; + } + if (i < 0 || i >= Py_SIZE(op)) { + Py_XDECREF(newitem); + PyErr_SetString(PyExc_IndexError, + "list assignment index out of range"); + return -1; + } + p = ((PyListObject *)op) -> ob_item + i; + olditem = *p; + *p = newitem; + Py_XDECREF(olditem); + return 0; } static int ins1(PyListObject *self, Py_ssize_t where, PyObject *v) { - Py_ssize_t i, n = Py_SIZE(self); - PyObject **items; - if (v == NULL) { - PyErr_BadInternalCall(); - return -1; - } - if (n == PY_SSIZE_T_MAX) { - PyErr_SetString(PyExc_OverflowError, - "cannot add more objects to list"); - return -1; - } - - if (list_resize(self, n+1) == -1) - return -1; - - if (where < 0) { - where += n; - if (where < 0) - where = 0; - } - if (where > n) - where = n; - items = self->ob_item; - for (i = n; --i >= where; ) - items[i+1] = items[i]; - Py_INCREF(v); - items[where] = v; - return 0; + Py_ssize_t i, n = Py_SIZE(self); + PyObject **items; + if (v == NULL) { + PyErr_BadInternalCall(); + return -1; + } + if (n == PY_SSIZE_T_MAX) { + PyErr_SetString(PyExc_OverflowError, + "cannot add more objects to list"); + return -1; + } + + if (list_resize(self, n+1) == -1) + return -1; + + if (where < 0) { + where += n; + if (where < 0) + where = 0; + } + if (where > n) + where = n; + items = self->ob_item; + for (i = n; --i >= where; ) + items[i+1] = items[i]; + Py_INCREF(v); + items[where] = v; + return 0; } int PyList_Insert(PyObject *op, Py_ssize_t where, PyObject *newitem) { - if (!PyList_Check(op)) { - PyErr_BadInternalCall(); - return -1; - } - return ins1((PyListObject *)op, where, newitem); + if (!PyList_Check(op)) { + PyErr_BadInternalCall(); + return -1; + } + return ins1((PyListObject *)op, where, newitem); } static int app1(PyListObject *self, PyObject *v) { - Py_ssize_t n = PyList_GET_SIZE(self); + Py_ssize_t n = PyList_GET_SIZE(self); - assert (v != NULL); - if (n == PY_SSIZE_T_MAX) { - PyErr_SetString(PyExc_OverflowError, - "cannot add more objects to list"); - return -1; - } - - if (list_resize(self, n+1) == -1) - return -1; - - Py_INCREF(v); - PyList_SET_ITEM(self, n, v); - return 0; + assert (v != NULL); + if (n == PY_SSIZE_T_MAX) { + PyErr_SetString(PyExc_OverflowError, + "cannot add more objects to list"); + return -1; + } + + if (list_resize(self, n+1) == -1) + return -1; + + Py_INCREF(v); + PyList_SET_ITEM(self, n, v); + return 0; } int PyList_Append(PyObject *op, PyObject *newitem) { - if (PyList_Check(op) && (newitem != NULL)) - return app1((PyListObject *)op, newitem); - PyErr_BadInternalCall(); - return -1; + if (PyList_Check(op) && (newitem != NULL)) + return app1((PyListObject *)op, newitem); + PyErr_BadInternalCall(); + return -1; } /* Methods */ @@ -296,271 +296,271 @@ static void list_dealloc(PyListObject *op) { - Py_ssize_t i; - PyObject_GC_UnTrack(op); - Py_TRASHCAN_SAFE_BEGIN(op) - if (op->ob_item != NULL) { - /* Do it backwards, for Christian Tismer. - There's a simple test case where somehow this reduces - thrashing when a *very* large list is created and - immediately deleted. */ - i = Py_SIZE(op); - while (--i >= 0) { - Py_XDECREF(op->ob_item[i]); - } - PyMem_FREE(op->ob_item); - } - if (numfree < PyList_MAXFREELIST && PyList_CheckExact(op)) - free_list[numfree++] = op; - else - Py_TYPE(op)->tp_free((PyObject *)op); - Py_TRASHCAN_SAFE_END(op) + Py_ssize_t i; + PyObject_GC_UnTrack(op); + Py_TRASHCAN_SAFE_BEGIN(op) + if (op->ob_item != NULL) { + /* Do it backwards, for Christian Tismer. + There's a simple test case where somehow this reduces + thrashing when a *very* large list is created and + immediately deleted. */ + i = Py_SIZE(op); + while (--i >= 0) { + Py_XDECREF(op->ob_item[i]); + } + PyMem_FREE(op->ob_item); + } + if (numfree < PyList_MAXFREELIST && PyList_CheckExact(op)) + free_list[numfree++] = op; + else + Py_TYPE(op)->tp_free((PyObject *)op); + Py_TRASHCAN_SAFE_END(op) } static PyObject * list_repr(PyListObject *v) { - Py_ssize_t i; - PyObject *s, *temp; - PyObject *pieces = NULL, *result = NULL; - - i = Py_ReprEnter((PyObject*)v); - if (i != 0) { - return i > 0 ? PyUnicode_FromString("[...]") : NULL; - } - - if (Py_SIZE(v) == 0) { - result = PyUnicode_FromString("[]"); - goto Done; - } - - pieces = PyList_New(0); - if (pieces == NULL) - goto Done; - - /* Do repr() on each element. Note that this may mutate the list, - so must refetch the list size on each iteration. */ - for (i = 0; i < Py_SIZE(v); ++i) { - int status; - if (Py_EnterRecursiveCall(" while getting the repr of a list")) - goto Done; - s = PyObject_Repr(v->ob_item[i]); - Py_LeaveRecursiveCall(); - if (s == NULL) - goto Done; - status = PyList_Append(pieces, s); - Py_DECREF(s); /* append created a new ref */ - if (status < 0) - goto Done; - } - - /* Add "[]" decorations to the first and last items. */ - assert(PyList_GET_SIZE(pieces) > 0); - s = PyUnicode_FromString("["); - if (s == NULL) - goto Done; - temp = PyList_GET_ITEM(pieces, 0); - PyUnicode_AppendAndDel(&s, temp); - PyList_SET_ITEM(pieces, 0, s); - if (s == NULL) - goto Done; - - s = PyUnicode_FromString("]"); - if (s == NULL) - goto Done; - temp = PyList_GET_ITEM(pieces, PyList_GET_SIZE(pieces) - 1); - PyUnicode_AppendAndDel(&temp, s); - PyList_SET_ITEM(pieces, PyList_GET_SIZE(pieces) - 1, temp); - if (temp == NULL) - goto Done; - - /* Paste them all together with ", " between. */ - s = PyUnicode_FromString(", "); - if (s == NULL) - goto Done; - result = PyUnicode_Join(s, pieces); - Py_DECREF(s); + Py_ssize_t i; + PyObject *s, *temp; + PyObject *pieces = NULL, *result = NULL; + + i = Py_ReprEnter((PyObject*)v); + if (i != 0) { + return i > 0 ? PyUnicode_FromString("[...]") : NULL; + } + + if (Py_SIZE(v) == 0) { + result = PyUnicode_FromString("[]"); + goto Done; + } + + pieces = PyList_New(0); + if (pieces == NULL) + goto Done; + + /* Do repr() on each element. Note that this may mutate the list, + so must refetch the list size on each iteration. */ + for (i = 0; i < Py_SIZE(v); ++i) { + int status; + if (Py_EnterRecursiveCall(" while getting the repr of a list")) + goto Done; + s = PyObject_Repr(v->ob_item[i]); + Py_LeaveRecursiveCall(); + if (s == NULL) + goto Done; + status = PyList_Append(pieces, s); + Py_DECREF(s); /* append created a new ref */ + if (status < 0) + goto Done; + } + + /* Add "[]" decorations to the first and last items. */ + assert(PyList_GET_SIZE(pieces) > 0); + s = PyUnicode_FromString("["); + if (s == NULL) + goto Done; + temp = PyList_GET_ITEM(pieces, 0); + PyUnicode_AppendAndDel(&s, temp); + PyList_SET_ITEM(pieces, 0, s); + if (s == NULL) + goto Done; + + s = PyUnicode_FromString("]"); + if (s == NULL) + goto Done; + temp = PyList_GET_ITEM(pieces, PyList_GET_SIZE(pieces) - 1); + PyUnicode_AppendAndDel(&temp, s); + PyList_SET_ITEM(pieces, PyList_GET_SIZE(pieces) - 1, temp); + if (temp == NULL) + goto Done; + + /* Paste them all together with ", " between. */ + s = PyUnicode_FromString(", "); + if (s == NULL) + goto Done; + result = PyUnicode_Join(s, pieces); + Py_DECREF(s); Done: - Py_XDECREF(pieces); - Py_ReprLeave((PyObject *)v); - return result; + Py_XDECREF(pieces); + Py_ReprLeave((PyObject *)v); + return result; } static Py_ssize_t list_length(PyListObject *a) { - return Py_SIZE(a); + return Py_SIZE(a); } static int list_contains(PyListObject *a, PyObject *el) { - Py_ssize_t i; - int cmp; + Py_ssize_t i; + int cmp; - for (i = 0, cmp = 0 ; cmp == 0 && i < Py_SIZE(a); ++i) - cmp = PyObject_RichCompareBool(el, PyList_GET_ITEM(a, i), - Py_EQ); - return cmp; + for (i = 0, cmp = 0 ; cmp == 0 && i < Py_SIZE(a); ++i) + cmp = PyObject_RichCompareBool(el, PyList_GET_ITEM(a, i), + Py_EQ); + return cmp; } static PyObject * list_item(PyListObject *a, Py_ssize_t i) { - if (i < 0 || i >= Py_SIZE(a)) { - if (indexerr == NULL) { - indexerr = PyUnicode_FromString( - "list index out of range"); - if (indexerr == NULL) - return NULL; - } - PyErr_SetObject(PyExc_IndexError, indexerr); - return NULL; - } - Py_INCREF(a->ob_item[i]); - return a->ob_item[i]; + if (i < 0 || i >= Py_SIZE(a)) { + if (indexerr == NULL) { + indexerr = PyUnicode_FromString( + "list index out of range"); + if (indexerr == NULL) + return NULL; + } + PyErr_SetObject(PyExc_IndexError, indexerr); + return NULL; + } + Py_INCREF(a->ob_item[i]); + return a->ob_item[i]; } static PyObject * list_slice(PyListObject *a, Py_ssize_t ilow, Py_ssize_t ihigh) { - PyListObject *np; - PyObject **src, **dest; - Py_ssize_t i, len; - if (ilow < 0) - ilow = 0; - else if (ilow > Py_SIZE(a)) - ilow = Py_SIZE(a); - if (ihigh < ilow) - ihigh = ilow; - else if (ihigh > Py_SIZE(a)) - ihigh = Py_SIZE(a); - len = ihigh - ilow; - np = (PyListObject *) PyList_New(len); - if (np == NULL) - return NULL; - - src = a->ob_item + ilow; - dest = np->ob_item; - for (i = 0; i < len; i++) { - PyObject *v = src[i]; - Py_INCREF(v); - dest[i] = v; - } - return (PyObject *)np; + PyListObject *np; + PyObject **src, **dest; + Py_ssize_t i, len; + if (ilow < 0) + ilow = 0; + else if (ilow > Py_SIZE(a)) + ilow = Py_SIZE(a); + if (ihigh < ilow) + ihigh = ilow; + else if (ihigh > Py_SIZE(a)) + ihigh = Py_SIZE(a); + len = ihigh - ilow; + np = (PyListObject *) PyList_New(len); + if (np == NULL) + return NULL; + + src = a->ob_item + ilow; + dest = np->ob_item; + for (i = 0; i < len; i++) { + PyObject *v = src[i]; + Py_INCREF(v); + dest[i] = v; + } + return (PyObject *)np; } PyObject * PyList_GetSlice(PyObject *a, Py_ssize_t ilow, Py_ssize_t ihigh) { - if (!PyList_Check(a)) { - PyErr_BadInternalCall(); - return NULL; - } - return list_slice((PyListObject *)a, ilow, ihigh); + if (!PyList_Check(a)) { + PyErr_BadInternalCall(); + return NULL; + } + return list_slice((PyListObject *)a, ilow, ihigh); } static PyObject * list_concat(PyListObject *a, PyObject *bb) { - Py_ssize_t size; - Py_ssize_t i; - PyObject **src, **dest; - PyListObject *np; - if (!PyList_Check(bb)) { - PyErr_Format(PyExc_TypeError, - "can only concatenate list (not \"%.200s\") to list", - bb->ob_type->tp_name); - return NULL; - } + Py_ssize_t size; + Py_ssize_t i; + PyObject **src, **dest; + PyListObject *np; + if (!PyList_Check(bb)) { + PyErr_Format(PyExc_TypeError, + "can only concatenate list (not \"%.200s\") to list", + bb->ob_type->tp_name); + return NULL; + } #define b ((PyListObject *)bb) - size = Py_SIZE(a) + Py_SIZE(b); - if (size < 0) - return PyErr_NoMemory(); - np = (PyListObject *) PyList_New(size); - if (np == NULL) { - return NULL; - } - src = a->ob_item; - dest = np->ob_item; - for (i = 0; i < Py_SIZE(a); i++) { - PyObject *v = src[i]; - Py_INCREF(v); - dest[i] = v; - } - src = b->ob_item; - dest = np->ob_item + Py_SIZE(a); - for (i = 0; i < Py_SIZE(b); i++) { - PyObject *v = src[i]; - Py_INCREF(v); - dest[i] = v; - } - return (PyObject *)np; + size = Py_SIZE(a) + Py_SIZE(b); + if (size < 0) + return PyErr_NoMemory(); + np = (PyListObject *) PyList_New(size); + if (np == NULL) { + return NULL; + } + src = a->ob_item; + dest = np->ob_item; + for (i = 0; i < Py_SIZE(a); i++) { + PyObject *v = src[i]; + Py_INCREF(v); + dest[i] = v; + } + src = b->ob_item; + dest = np->ob_item + Py_SIZE(a); + for (i = 0; i < Py_SIZE(b); i++) { + PyObject *v = src[i]; + Py_INCREF(v); + dest[i] = v; + } + return (PyObject *)np; #undef b } static PyObject * list_repeat(PyListObject *a, Py_ssize_t n) { - Py_ssize_t i, j; - Py_ssize_t size; - PyListObject *np; - PyObject **p, **items; - PyObject *elem; - if (n < 0) - n = 0; - size = Py_SIZE(a) * n; - if (n && size/n != Py_SIZE(a)) - return PyErr_NoMemory(); - if (size == 0) - return PyList_New(0); - np = (PyListObject *) PyList_New(size); - if (np == NULL) - return NULL; - - items = np->ob_item; - if (Py_SIZE(a) == 1) { - elem = a->ob_item[0]; - for (i = 0; i < n; i++) { - items[i] = elem; - Py_INCREF(elem); - } - return (PyObject *) np; - } - p = np->ob_item; - items = a->ob_item; - for (i = 0; i < n; i++) { - for (j = 0; j < Py_SIZE(a); j++) { - *p = items[j]; - Py_INCREF(*p); - p++; - } - } - return (PyObject *) np; + Py_ssize_t i, j; + Py_ssize_t size; + PyListObject *np; + PyObject **p, **items; + PyObject *elem; + if (n < 0) + n = 0; + size = Py_SIZE(a) * n; + if (n && size/n != Py_SIZE(a)) + return PyErr_NoMemory(); + if (size == 0) + return PyList_New(0); + np = (PyListObject *) PyList_New(size); + if (np == NULL) + return NULL; + + items = np->ob_item; + if (Py_SIZE(a) == 1) { + elem = a->ob_item[0]; + for (i = 0; i < n; i++) { + items[i] = elem; + Py_INCREF(elem); + } + return (PyObject *) np; + } + p = np->ob_item; + items = a->ob_item; + for (i = 0; i < n; i++) { + for (j = 0; j < Py_SIZE(a); j++) { + *p = items[j]; + Py_INCREF(*p); + p++; + } + } + return (PyObject *) np; } static int list_clear(PyListObject *a) { - Py_ssize_t i; - PyObject **item = a->ob_item; - if (item != NULL) { - /* Because XDECREF can recursively invoke operations on - this list, we make it empty first. */ - i = Py_SIZE(a); - Py_SIZE(a) = 0; - a->ob_item = NULL; - a->allocated = 0; - while (--i >= 0) { - Py_XDECREF(item[i]); - } - PyMem_FREE(item); - } - /* Never fails; the return value can be ignored. - Note that there is no guarantee that the list is actually empty - at this point, because XDECREF may have populated it again! */ - return 0; + Py_ssize_t i; + PyObject **item = a->ob_item; + if (item != NULL) { + /* Because XDECREF can recursively invoke operations on + this list, we make it empty first. */ + i = Py_SIZE(a); + Py_SIZE(a) = 0; + a->ob_item = NULL; + a->allocated = 0; + while (--i >= 0) { + Py_XDECREF(item[i]); + } + PyMem_FREE(item); + } + /* Never fails; the return value can be ignored. + Note that there is no guarantee that the list is actually empty + at this point, because XDECREF may have populated it again! */ + return 0; } /* a[ilow:ihigh] = v if v != NULL. @@ -572,368 +572,368 @@ static int list_ass_slice(PyListObject *a, Py_ssize_t ilow, Py_ssize_t ihigh, PyObject *v) { - /* Because [X]DECREF can recursively invoke list operations on - this list, we must postpone all [X]DECREF activity until - after the list is back in its canonical shape. Therefore - we must allocate an additional array, 'recycle', into which - we temporarily copy the items that are deleted from the - list. :-( */ - PyObject *recycle_on_stack[8]; - PyObject **recycle = recycle_on_stack; /* will allocate more if needed */ - PyObject **item; - PyObject **vitem = NULL; - PyObject *v_as_SF = NULL; /* PySequence_Fast(v) */ - Py_ssize_t n; /* # of elements in replacement list */ - Py_ssize_t norig; /* # of elements in list getting replaced */ - Py_ssize_t d; /* Change in size */ - Py_ssize_t k; - size_t s; - int result = -1; /* guilty until proved innocent */ + /* Because [X]DECREF can recursively invoke list operations on + this list, we must postpone all [X]DECREF activity until + after the list is back in its canonical shape. Therefore + we must allocate an additional array, 'recycle', into which + we temporarily copy the items that are deleted from the + list. :-( */ + PyObject *recycle_on_stack[8]; + PyObject **recycle = recycle_on_stack; /* will allocate more if needed */ + PyObject **item; + PyObject **vitem = NULL; + PyObject *v_as_SF = NULL; /* PySequence_Fast(v) */ + Py_ssize_t n; /* # of elements in replacement list */ + Py_ssize_t norig; /* # of elements in list getting replaced */ + Py_ssize_t d; /* Change in size */ + Py_ssize_t k; + size_t s; + int result = -1; /* guilty until proved innocent */ #define b ((PyListObject *)v) - if (v == NULL) - n = 0; - else { - if (a == b) { - /* Special case "a[i:j] = a" -- copy b first */ - v = list_slice(b, 0, Py_SIZE(b)); - if (v == NULL) - return result; - result = list_ass_slice(a, ilow, ihigh, v); - Py_DECREF(v); - return result; - } - v_as_SF = PySequence_Fast(v, "can only assign an iterable"); - if(v_as_SF == NULL) - goto Error; - n = PySequence_Fast_GET_SIZE(v_as_SF); - vitem = PySequence_Fast_ITEMS(v_as_SF); - } - if (ilow < 0) - ilow = 0; - else if (ilow > Py_SIZE(a)) - ilow = Py_SIZE(a); - - if (ihigh < ilow) - ihigh = ilow; - else if (ihigh > Py_SIZE(a)) - ihigh = Py_SIZE(a); - - norig = ihigh - ilow; - assert(norig >= 0); - d = n - norig; - if (Py_SIZE(a) + d == 0) { - Py_XDECREF(v_as_SF); - return list_clear(a); - } - item = a->ob_item; - /* recycle the items that we are about to remove */ - s = norig * sizeof(PyObject *); - if (s > sizeof(recycle_on_stack)) { - recycle = (PyObject **)PyMem_MALLOC(s); - if (recycle == NULL) { - PyErr_NoMemory(); - goto Error; - } - } - memcpy(recycle, &item[ilow], s); - - if (d < 0) { /* Delete -d items */ - memmove(&item[ihigh+d], &item[ihigh], - (Py_SIZE(a) - ihigh)*sizeof(PyObject *)); - list_resize(a, Py_SIZE(a) + d); - item = a->ob_item; - } - else if (d > 0) { /* Insert d items */ - k = Py_SIZE(a); - if (list_resize(a, k+d) < 0) - goto Error; - item = a->ob_item; - memmove(&item[ihigh+d], &item[ihigh], - (k - ihigh)*sizeof(PyObject *)); - } - for (k = 0; k < n; k++, ilow++) { - PyObject *w = vitem[k]; - Py_XINCREF(w); - item[ilow] = w; - } - for (k = norig - 1; k >= 0; --k) - Py_XDECREF(recycle[k]); - result = 0; + if (v == NULL) + n = 0; + else { + if (a == b) { + /* Special case "a[i:j] = a" -- copy b first */ + v = list_slice(b, 0, Py_SIZE(b)); + if (v == NULL) + return result; + result = list_ass_slice(a, ilow, ihigh, v); + Py_DECREF(v); + return result; + } + v_as_SF = PySequence_Fast(v, "can only assign an iterable"); + if(v_as_SF == NULL) + goto Error; + n = PySequence_Fast_GET_SIZE(v_as_SF); + vitem = PySequence_Fast_ITEMS(v_as_SF); + } + if (ilow < 0) + ilow = 0; + else if (ilow > Py_SIZE(a)) + ilow = Py_SIZE(a); + + if (ihigh < ilow) + ihigh = ilow; + else if (ihigh > Py_SIZE(a)) + ihigh = Py_SIZE(a); + + norig = ihigh - ilow; + assert(norig >= 0); + d = n - norig; + if (Py_SIZE(a) + d == 0) { + Py_XDECREF(v_as_SF); + return list_clear(a); + } + item = a->ob_item; + /* recycle the items that we are about to remove */ + s = norig * sizeof(PyObject *); + if (s > sizeof(recycle_on_stack)) { + recycle = (PyObject **)PyMem_MALLOC(s); + if (recycle == NULL) { + PyErr_NoMemory(); + goto Error; + } + } + memcpy(recycle, &item[ilow], s); + + if (d < 0) { /* Delete -d items */ + memmove(&item[ihigh+d], &item[ihigh], + (Py_SIZE(a) - ihigh)*sizeof(PyObject *)); + list_resize(a, Py_SIZE(a) + d); + item = a->ob_item; + } + else if (d > 0) { /* Insert d items */ + k = Py_SIZE(a); + if (list_resize(a, k+d) < 0) + goto Error; + item = a->ob_item; + memmove(&item[ihigh+d], &item[ihigh], + (k - ihigh)*sizeof(PyObject *)); + } + for (k = 0; k < n; k++, ilow++) { + PyObject *w = vitem[k]; + Py_XINCREF(w); + item[ilow] = w; + } + for (k = norig - 1; k >= 0; --k) + Py_XDECREF(recycle[k]); + result = 0; Error: - if (recycle != recycle_on_stack) - PyMem_FREE(recycle); - Py_XDECREF(v_as_SF); - return result; + if (recycle != recycle_on_stack) + PyMem_FREE(recycle); + Py_XDECREF(v_as_SF); + return result; #undef b } int PyList_SetSlice(PyObject *a, Py_ssize_t ilow, Py_ssize_t ihigh, PyObject *v) { - if (!PyList_Check(a)) { - PyErr_BadInternalCall(); - return -1; - } - return list_ass_slice((PyListObject *)a, ilow, ihigh, v); + if (!PyList_Check(a)) { + PyErr_BadInternalCall(); + return -1; + } + return list_ass_slice((PyListObject *)a, ilow, ihigh, v); } static PyObject * list_inplace_repeat(PyListObject *self, Py_ssize_t n) { - PyObject **items; - Py_ssize_t size, i, j, p; + PyObject **items; + Py_ssize_t size, i, j, p; - size = PyList_GET_SIZE(self); - if (size == 0 || n == 1) { - Py_INCREF(self); - return (PyObject *)self; - } - - if (n < 1) { - (void)list_clear(self); - Py_INCREF(self); - return (PyObject *)self; - } - - if (size > PY_SSIZE_T_MAX / n) { - return PyErr_NoMemory(); - } - - if (list_resize(self, size*n) == -1) - return NULL; - - p = size; - items = self->ob_item; - for (i = 1; i < n; i++) { /* Start counting at 1, not 0 */ - for (j = 0; j < size; j++) { - PyObject *o = items[j]; - Py_INCREF(o); - items[p++] = o; - } - } - Py_INCREF(self); - return (PyObject *)self; + size = PyList_GET_SIZE(self); + if (size == 0 || n == 1) { + Py_INCREF(self); + return (PyObject *)self; + } + + if (n < 1) { + (void)list_clear(self); + Py_INCREF(self); + return (PyObject *)self; + } + + if (size > PY_SSIZE_T_MAX / n) { + return PyErr_NoMemory(); + } + + if (list_resize(self, size*n) == -1) + return NULL; + + p = size; + items = self->ob_item; + for (i = 1; i < n; i++) { /* Start counting at 1, not 0 */ + for (j = 0; j < size; j++) { + PyObject *o = items[j]; + Py_INCREF(o); + items[p++] = o; + } + } + Py_INCREF(self); + return (PyObject *)self; } static int list_ass_item(PyListObject *a, Py_ssize_t i, PyObject *v) { - PyObject *old_value; - if (i < 0 || i >= Py_SIZE(a)) { - PyErr_SetString(PyExc_IndexError, - "list assignment index out of range"); - return -1; - } - if (v == NULL) - return list_ass_slice(a, i, i+1, v); - Py_INCREF(v); - old_value = a->ob_item[i]; - a->ob_item[i] = v; - Py_DECREF(old_value); - return 0; + PyObject *old_value; + if (i < 0 || i >= Py_SIZE(a)) { + PyErr_SetString(PyExc_IndexError, + "list assignment index out of range"); + return -1; + } + if (v == NULL) + return list_ass_slice(a, i, i+1, v); + Py_INCREF(v); + old_value = a->ob_item[i]; + a->ob_item[i] = v; + Py_DECREF(old_value); + return 0; } static PyObject * listinsert(PyListObject *self, PyObject *args) { - Py_ssize_t i; - PyObject *v; - if (!PyArg_ParseTuple(args, "nO:insert", &i, &v)) - return NULL; - if (ins1(self, i, v) == 0) - Py_RETURN_NONE; - return NULL; + Py_ssize_t i; + PyObject *v; + if (!PyArg_ParseTuple(args, "nO:insert", &i, &v)) + return NULL; + if (ins1(self, i, v) == 0) + Py_RETURN_NONE; + return NULL; } static PyObject * listappend(PyListObject *self, PyObject *v) { - if (app1(self, v) == 0) - Py_RETURN_NONE; - return NULL; + if (app1(self, v) == 0) + Py_RETURN_NONE; + return NULL; } static PyObject * listextend(PyListObject *self, PyObject *b) { - PyObject *it; /* iter(v) */ - Py_ssize_t m; /* size of self */ - Py_ssize_t n; /* guess for size of b */ - Py_ssize_t mn; /* m + n */ - Py_ssize_t i; - PyObject *(*iternext)(PyObject *); - - /* Special cases: - 1) lists and tuples which can use PySequence_Fast ops - 2) extending self to self requires making a copy first - */ - if (PyList_CheckExact(b) || PyTuple_CheckExact(b) || (PyObject *)self == b) { - PyObject **src, **dest; - b = PySequence_Fast(b, "argument must be iterable"); - if (!b) - return NULL; - n = PySequence_Fast_GET_SIZE(b); - if (n == 0) { - /* short circuit when b is empty */ - Py_DECREF(b); - Py_RETURN_NONE; - } - m = Py_SIZE(self); - if (list_resize(self, m + n) == -1) { - Py_DECREF(b); - return NULL; - } - /* note that we may still have self == b here for the - * situation a.extend(a), but the following code works - * in that case too. Just make sure to resize self - * before calling PySequence_Fast_ITEMS. - */ - /* populate the end of self with b's items */ - src = PySequence_Fast_ITEMS(b); - dest = self->ob_item + m; - for (i = 0; i < n; i++) { - PyObject *o = src[i]; - Py_INCREF(o); - dest[i] = o; - } - Py_DECREF(b); - Py_RETURN_NONE; - } - - it = PyObject_GetIter(b); - if (it == NULL) - return NULL; - iternext = *it->ob_type->tp_iternext; - - /* Guess a result list size. */ - n = _PyObject_LengthHint(b, 8); - if (n == -1) { - Py_DECREF(it); - return NULL; - } - m = Py_SIZE(self); - mn = m + n; - if (mn >= m) { - /* Make room. */ - if (list_resize(self, mn) == -1) - goto error; - /* Make the list sane again. */ - Py_SIZE(self) = m; - } - /* Else m + n overflowed; on the chance that n lied, and there really - * is enough room, ignore it. If n was telling the truth, we'll - * eventually run out of memory during the loop. - */ - - /* Run iterator to exhaustion. */ - for (;;) { - PyObject *item = iternext(it); - if (item == NULL) { - if (PyErr_Occurred()) { - if (PyErr_ExceptionMatches(PyExc_StopIteration)) - PyErr_Clear(); - else - goto error; - } - break; - } - if (Py_SIZE(self) < self->allocated) { - /* steals ref */ - PyList_SET_ITEM(self, Py_SIZE(self), item); - ++Py_SIZE(self); - } - else { - int status = app1(self, item); - Py_DECREF(item); /* append creates a new ref */ - if (status < 0) - goto error; - } - } - - /* Cut back result list if initial guess was too large. */ - if (Py_SIZE(self) < self->allocated) - list_resize(self, Py_SIZE(self)); /* shrinking can't fail */ + PyObject *it; /* iter(v) */ + Py_ssize_t m; /* size of self */ + Py_ssize_t n; /* guess for size of b */ + Py_ssize_t mn; /* m + n */ + Py_ssize_t i; + PyObject *(*iternext)(PyObject *); + + /* Special cases: + 1) lists and tuples which can use PySequence_Fast ops + 2) extending self to self requires making a copy first + */ + if (PyList_CheckExact(b) || PyTuple_CheckExact(b) || (PyObject *)self == b) { + PyObject **src, **dest; + b = PySequence_Fast(b, "argument must be iterable"); + if (!b) + return NULL; + n = PySequence_Fast_GET_SIZE(b); + if (n == 0) { + /* short circuit when b is empty */ + Py_DECREF(b); + Py_RETURN_NONE; + } + m = Py_SIZE(self); + if (list_resize(self, m + n) == -1) { + Py_DECREF(b); + return NULL; + } + /* note that we may still have self == b here for the + * situation a.extend(a), but the following code works + * in that case too. Just make sure to resize self + * before calling PySequence_Fast_ITEMS. + */ + /* populate the end of self with b's items */ + src = PySequence_Fast_ITEMS(b); + dest = self->ob_item + m; + for (i = 0; i < n; i++) { + PyObject *o = src[i]; + Py_INCREF(o); + dest[i] = o; + } + Py_DECREF(b); + Py_RETURN_NONE; + } + + it = PyObject_GetIter(b); + if (it == NULL) + return NULL; + iternext = *it->ob_type->tp_iternext; + + /* Guess a result list size. */ + n = _PyObject_LengthHint(b, 8); + if (n == -1) { + Py_DECREF(it); + return NULL; + } + m = Py_SIZE(self); + mn = m + n; + if (mn >= m) { + /* Make room. */ + if (list_resize(self, mn) == -1) + goto error; + /* Make the list sane again. */ + Py_SIZE(self) = m; + } + /* Else m + n overflowed; on the chance that n lied, and there really + * is enough room, ignore it. If n was telling the truth, we'll + * eventually run out of memory during the loop. + */ + + /* Run iterator to exhaustion. */ + for (;;) { + PyObject *item = iternext(it); + if (item == NULL) { + if (PyErr_Occurred()) { + if (PyErr_ExceptionMatches(PyExc_StopIteration)) + PyErr_Clear(); + else + goto error; + } + break; + } + if (Py_SIZE(self) < self->allocated) { + /* steals ref */ + PyList_SET_ITEM(self, Py_SIZE(self), item); + ++Py_SIZE(self); + } + else { + int status = app1(self, item); + Py_DECREF(item); /* append creates a new ref */ + if (status < 0) + goto error; + } + } + + /* Cut back result list if initial guess was too large. */ + if (Py_SIZE(self) < self->allocated) + list_resize(self, Py_SIZE(self)); /* shrinking can't fail */ - Py_DECREF(it); - Py_RETURN_NONE; + Py_DECREF(it); + Py_RETURN_NONE; error: - Py_DECREF(it); - return NULL; + Py_DECREF(it); + return NULL; } PyObject * _PyList_Extend(PyListObject *self, PyObject *b) { - return listextend(self, b); + return listextend(self, b); } static PyObject * list_inplace_concat(PyListObject *self, PyObject *other) { - PyObject *result; + PyObject *result; - result = listextend(self, other); - if (result == NULL) - return result; - Py_DECREF(result); - Py_INCREF(self); - return (PyObject *)self; + result = listextend(self, other); + if (result == NULL) + return result; + Py_DECREF(result); + Py_INCREF(self); + return (PyObject *)self; } static PyObject * listpop(PyListObject *self, PyObject *args) { - Py_ssize_t i = -1; - PyObject *v; - int status; - - if (!PyArg_ParseTuple(args, "|n:pop", &i)) - return NULL; - - if (Py_SIZE(self) == 0) { - /* Special-case most common failure cause */ - PyErr_SetString(PyExc_IndexError, "pop from empty list"); - return NULL; - } - if (i < 0) - i += Py_SIZE(self); - if (i < 0 || i >= Py_SIZE(self)) { - PyErr_SetString(PyExc_IndexError, "pop index out of range"); - return NULL; - } - v = self->ob_item[i]; - if (i == Py_SIZE(self) - 1) { - status = list_resize(self, Py_SIZE(self) - 1); - assert(status >= 0); - return v; /* and v now owns the reference the list had */ - } - Py_INCREF(v); - status = list_ass_slice(self, i, i+1, (PyObject *)NULL); - assert(status >= 0); - /* Use status, so that in a release build compilers don't - * complain about the unused name. - */ - (void) status; + Py_ssize_t i = -1; + PyObject *v; + int status; + + if (!PyArg_ParseTuple(args, "|n:pop", &i)) + return NULL; + + if (Py_SIZE(self) == 0) { + /* Special-case most common failure cause */ + PyErr_SetString(PyExc_IndexError, "pop from empty list"); + return NULL; + } + if (i < 0) + i += Py_SIZE(self); + if (i < 0 || i >= Py_SIZE(self)) { + PyErr_SetString(PyExc_IndexError, "pop index out of range"); + return NULL; + } + v = self->ob_item[i]; + if (i == Py_SIZE(self) - 1) { + status = list_resize(self, Py_SIZE(self) - 1); + assert(status >= 0); + return v; /* and v now owns the reference the list had */ + } + Py_INCREF(v); + status = list_ass_slice(self, i, i+1, (PyObject *)NULL); + assert(status >= 0); + /* Use status, so that in a release build compilers don't + * complain about the unused name. + */ + (void) status; - return v; + return v; } /* Reverse a slice of a list in place, from lo up to (exclusive) hi. */ static void reverse_slice(PyObject **lo, PyObject **hi) { - assert(lo && hi); + assert(lo && hi); - --hi; - while (lo < hi) { - PyObject *t = *lo; - *lo = *hi; - *hi = t; - ++lo; - --hi; - } + --hi; + while (lo < hi) { + PyObject *t = *lo; + *lo = *hi; + *hi = t; + ++lo; + --hi; + } } /* Lots of code for an adaptive, stable, natural mergesort. There are many @@ -951,7 +951,7 @@ started. It makes more sense in context . X and Y are PyObject*s. */ #define IFLT(X, Y) if ((k = ISLT(X, Y)) < 0) goto fail; \ - if (k) + if (k) /* binarysort is the best method for sorting small arrays: it does few compares, but can do data movement quadratic in the number of @@ -967,48 +967,48 @@ static int binarysort(PyObject **lo, PyObject **hi, PyObject **start) { - register Py_ssize_t k; - register PyObject **l, **p, **r; - register PyObject *pivot; - - assert(lo <= start && start <= hi); - /* assert [lo, start) is sorted */ - if (lo == start) - ++start; - for (; start < hi; ++start) { - /* set l to where *start belongs */ - l = lo; - r = start; - pivot = *r; - /* Invariants: - * pivot >= all in [lo, l). - * pivot < all in [r, start). - * The second is vacuously true at the start. - */ - assert(l < r); - do { - p = l + ((r - l) >> 1); - IFLT(pivot, *p) - r = p; - else - l = p+1; - } while (l < r); - assert(l == r); - /* The invariants still hold, so pivot >= all in [lo, l) and - pivot < all in [l, start), so pivot belongs at l. Note - that if there are elements equal to pivot, l points to the - first slot after them -- that's why this sort is stable. - Slide over to make room. - Caution: using memmove is much slower under MSVC 5; - we're not usually moving many slots. */ - for (p = start; p > l; --p) - *p = *(p-1); - *l = pivot; - } - return 0; + register Py_ssize_t k; + register PyObject **l, **p, **r; + register PyObject *pivot; + + assert(lo <= start && start <= hi); + /* assert [lo, start) is sorted */ + if (lo == start) + ++start; + for (; start < hi; ++start) { + /* set l to where *start belongs */ + l = lo; + r = start; + pivot = *r; + /* Invariants: + * pivot >= all in [lo, l). + * pivot < all in [r, start). + * The second is vacuously true at the start. + */ + assert(l < r); + do { + p = l + ((r - l) >> 1); + IFLT(pivot, *p) + r = p; + else + l = p+1; + } while (l < r); + assert(l == r); + /* The invariants still hold, so pivot >= all in [lo, l) and + pivot < all in [l, start), so pivot belongs at l. Note + that if there are elements equal to pivot, l points to the + first slot after them -- that's why this sort is stable. + Slide over to make room. + Caution: using memmove is much slower under MSVC 5; + we're not usually moving many slots. */ + for (p = start; p > l; --p) + *p = *(p-1); + *l = pivot; + } + return 0; fail: - return -1; + return -1; } /* @@ -1032,35 +1032,35 @@ static Py_ssize_t count_run(PyObject **lo, PyObject **hi, int *descending) { - Py_ssize_t k; - Py_ssize_t n; + Py_ssize_t k; + Py_ssize_t n; - assert(lo < hi); - *descending = 0; - ++lo; - if (lo == hi) - return 1; - - n = 2; - IFLT(*lo, *(lo-1)) { - *descending = 1; - for (lo = lo+1; lo < hi; ++lo, ++n) { - IFLT(*lo, *(lo-1)) - ; - else - break; - } - } - else { - for (lo = lo+1; lo < hi; ++lo, ++n) { - IFLT(*lo, *(lo-1)) - break; - } - } + assert(lo < hi); + *descending = 0; + ++lo; + if (lo == hi) + return 1; + + n = 2; + IFLT(*lo, *(lo-1)) { + *descending = 1; + for (lo = lo+1; lo < hi; ++lo, ++n) { + IFLT(*lo, *(lo-1)) + ; + else + break; + } + } + else { + for (lo = lo+1; lo < hi; ++lo, ++n) { + IFLT(*lo, *(lo-1)) + break; + } + } - return n; + return n; fail: - return -1; + return -1; } /* @@ -1087,78 +1087,78 @@ static Py_ssize_t gallop_left(PyObject *key, PyObject **a, Py_ssize_t n, Py_ssize_t hint) { - Py_ssize_t ofs; - Py_ssize_t lastofs; - Py_ssize_t k; - - assert(key && a && n > 0 && hint >= 0 && hint < n); - - a += hint; - lastofs = 0; - ofs = 1; - IFLT(*a, key) { - /* a[hint] < key -- gallop right, until - * a[hint + lastofs] < key <= a[hint + ofs] - */ - const Py_ssize_t maxofs = n - hint; /* &a[n-1] is highest */ - while (ofs < maxofs) { - IFLT(a[ofs], key) { - lastofs = ofs; - ofs = (ofs << 1) + 1; - if (ofs <= 0) /* int overflow */ - ofs = maxofs; - } - else /* key <= a[hint + ofs] */ - break; - } - if (ofs > maxofs) - ofs = maxofs; - /* Translate back to offsets relative to &a[0]. */ - lastofs += hint; - ofs += hint; - } - else { - /* key <= a[hint] -- gallop left, until - * a[hint - ofs] < key <= a[hint - lastofs] - */ - const Py_ssize_t maxofs = hint + 1; /* &a[0] is lowest */ - while (ofs < maxofs) { - IFLT(*(a-ofs), key) - break; - /* key <= a[hint - ofs] */ - lastofs = ofs; - ofs = (ofs << 1) + 1; - if (ofs <= 0) /* int overflow */ - ofs = maxofs; - } - if (ofs > maxofs) - ofs = maxofs; - /* Translate back to positive offsets relative to &a[0]. */ - k = lastofs; - lastofs = hint - ofs; - ofs = hint - k; - } - a -= hint; - - assert(-1 <= lastofs && lastofs < ofs && ofs <= n); - /* Now a[lastofs] < key <= a[ofs], so key belongs somewhere to the - * right of lastofs but no farther right than ofs. Do a binary - * search, with invariant a[lastofs-1] < key <= a[ofs]. - */ - ++lastofs; - while (lastofs < ofs) { - Py_ssize_t m = lastofs + ((ofs - lastofs) >> 1); - - IFLT(a[m], key) - lastofs = m+1; /* a[m] < key */ - else - ofs = m; /* key <= a[m] */ - } - assert(lastofs == ofs); /* so a[ofs-1] < key <= a[ofs] */ - return ofs; + Py_ssize_t ofs; + Py_ssize_t lastofs; + Py_ssize_t k; + + assert(key && a && n > 0 && hint >= 0 && hint < n); + + a += hint; + lastofs = 0; + ofs = 1; + IFLT(*a, key) { + /* a[hint] < key -- gallop right, until + * a[hint + lastofs] < key <= a[hint + ofs] + */ + const Py_ssize_t maxofs = n - hint; /* &a[n-1] is highest */ + while (ofs < maxofs) { + IFLT(a[ofs], key) { + lastofs = ofs; + ofs = (ofs << 1) + 1; + if (ofs <= 0) /* int overflow */ + ofs = maxofs; + } + else /* key <= a[hint + ofs] */ + break; + } + if (ofs > maxofs) + ofs = maxofs; + /* Translate back to offsets relative to &a[0]. */ + lastofs += hint; + ofs += hint; + } + else { + /* key <= a[hint] -- gallop left, until + * a[hint - ofs] < key <= a[hint - lastofs] + */ + const Py_ssize_t maxofs = hint + 1; /* &a[0] is lowest */ + while (ofs < maxofs) { + IFLT(*(a-ofs), key) + break; + /* key <= a[hint - ofs] */ + lastofs = ofs; + ofs = (ofs << 1) + 1; + if (ofs <= 0) /* int overflow */ + ofs = maxofs; + } + if (ofs > maxofs) + ofs = maxofs; + /* Translate back to positive offsets relative to &a[0]. */ + k = lastofs; + lastofs = hint - ofs; + ofs = hint - k; + } + a -= hint; + + assert(-1 <= lastofs && lastofs < ofs && ofs <= n); + /* Now a[lastofs] < key <= a[ofs], so key belongs somewhere to the + * right of lastofs but no farther right than ofs. Do a binary + * search, with invariant a[lastofs-1] < key <= a[ofs]. + */ + ++lastofs; + while (lastofs < ofs) { + Py_ssize_t m = lastofs + ((ofs - lastofs) >> 1); + + IFLT(a[m], key) + lastofs = m+1; /* a[m] < key */ + else + ofs = m; /* key <= a[m] */ + } + assert(lastofs == ofs); /* so a[ofs-1] < key <= a[ofs] */ + return ofs; fail: - return -1; + return -1; } /* @@ -1178,78 +1178,78 @@ static Py_ssize_t gallop_right(PyObject *key, PyObject **a, Py_ssize_t n, Py_ssize_t hint) { - Py_ssize_t ofs; - Py_ssize_t lastofs; - Py_ssize_t k; - - assert(key && a && n > 0 && hint >= 0 && hint < n); - - a += hint; - lastofs = 0; - ofs = 1; - IFLT(key, *a) { - /* key < a[hint] -- gallop left, until - * a[hint - ofs] <= key < a[hint - lastofs] - */ - const Py_ssize_t maxofs = hint + 1; /* &a[0] is lowest */ - while (ofs < maxofs) { - IFLT(key, *(a-ofs)) { - lastofs = ofs; - ofs = (ofs << 1) + 1; - if (ofs <= 0) /* int overflow */ - ofs = maxofs; - } - else /* a[hint - ofs] <= key */ - break; - } - if (ofs > maxofs) - ofs = maxofs; - /* Translate back to positive offsets relative to &a[0]. */ - k = lastofs; - lastofs = hint - ofs; - ofs = hint - k; - } - else { - /* a[hint] <= key -- gallop right, until - * a[hint + lastofs] <= key < a[hint + ofs] - */ - const Py_ssize_t maxofs = n - hint; /* &a[n-1] is highest */ - while (ofs < maxofs) { - IFLT(key, a[ofs]) - break; - /* a[hint + ofs] <= key */ - lastofs = ofs; - ofs = (ofs << 1) + 1; - if (ofs <= 0) /* int overflow */ - ofs = maxofs; - } - if (ofs > maxofs) - ofs = maxofs; - /* Translate back to offsets relative to &a[0]. */ - lastofs += hint; - ofs += hint; - } - a -= hint; - - assert(-1 <= lastofs && lastofs < ofs && ofs <= n); - /* Now a[lastofs] <= key < a[ofs], so key belongs somewhere to the - * right of lastofs but no farther right than ofs. Do a binary - * search, with invariant a[lastofs-1] <= key < a[ofs]. - */ - ++lastofs; - while (lastofs < ofs) { - Py_ssize_t m = lastofs + ((ofs - lastofs) >> 1); - - IFLT(key, a[m]) - ofs = m; /* key < a[m] */ - else - lastofs = m+1; /* a[m] <= key */ - } - assert(lastofs == ofs); /* so a[ofs-1] <= key < a[ofs] */ - return ofs; + Py_ssize_t ofs; + Py_ssize_t lastofs; + Py_ssize_t k; + + assert(key && a && n > 0 && hint >= 0 && hint < n); + + a += hint; + lastofs = 0; + ofs = 1; + IFLT(key, *a) { + /* key < a[hint] -- gallop left, until + * a[hint - ofs] <= key < a[hint - lastofs] + */ + const Py_ssize_t maxofs = hint + 1; /* &a[0] is lowest */ + while (ofs < maxofs) { + IFLT(key, *(a-ofs)) { + lastofs = ofs; + ofs = (ofs << 1) + 1; + if (ofs <= 0) /* int overflow */ + ofs = maxofs; + } + else /* a[hint - ofs] <= key */ + break; + } + if (ofs > maxofs) + ofs = maxofs; + /* Translate back to positive offsets relative to &a[0]. */ + k = lastofs; + lastofs = hint - ofs; + ofs = hint - k; + } + else { + /* a[hint] <= key -- gallop right, until + * a[hint + lastofs] <= key < a[hint + ofs] + */ + const Py_ssize_t maxofs = n - hint; /* &a[n-1] is highest */ + while (ofs < maxofs) { + IFLT(key, a[ofs]) + break; + /* a[hint + ofs] <= key */ + lastofs = ofs; + ofs = (ofs << 1) + 1; + if (ofs <= 0) /* int overflow */ + ofs = maxofs; + } + if (ofs > maxofs) + ofs = maxofs; + /* Translate back to offsets relative to &a[0]. */ + lastofs += hint; + ofs += hint; + } + a -= hint; + + assert(-1 <= lastofs && lastofs < ofs && ofs <= n); + /* Now a[lastofs] <= key < a[ofs], so key belongs somewhere to the + * right of lastofs but no farther right than ofs. Do a binary + * search, with invariant a[lastofs-1] <= key < a[ofs]. + */ + ++lastofs; + while (lastofs < ofs) { + Py_ssize_t m = lastofs + ((ofs - lastofs) >> 1); + + IFLT(key, a[m]) + ofs = m; /* key < a[m] */ + else + lastofs = m+1; /* a[m] <= key */ + } + assert(lastofs == ofs); /* so a[ofs-1] <= key < a[ofs] */ + return ofs; fail: - return -1; + return -1; } /* The maximum number of entries in a MergeState's pending-runs stack. @@ -1272,48 +1272,48 @@ * a convenient way to pass state around among the helper functions. */ struct s_slice { - PyObject **base; - Py_ssize_t len; + PyObject **base; + Py_ssize_t len; }; typedef struct s_MergeState { - /* This controls when we get *into* galloping mode. It's initialized - * to MIN_GALLOP. merge_lo and merge_hi tend to nudge it higher for - * random data, and lower for highly structured data. - */ - Py_ssize_t min_gallop; - - /* 'a' is temp storage to help with merges. It contains room for - * alloced entries. - */ - PyObject **a; /* may point to temparray below */ - Py_ssize_t alloced; - - /* A stack of n pending runs yet to be merged. Run #i starts at - * address base[i] and extends for len[i] elements. It's always - * true (so long as the indices are in bounds) that - * - * pending[i].base + pending[i].len == pending[i+1].base - * - * so we could cut the storage for this, but it's a minor amount, - * and keeping all the info explicit simplifies the code. - */ - int n; - struct s_slice pending[MAX_MERGE_PENDING]; + /* This controls when we get *into* galloping mode. It's initialized + * to MIN_GALLOP. merge_lo and merge_hi tend to nudge it higher for + * random data, and lower for highly structured data. + */ + Py_ssize_t min_gallop; + + /* 'a' is temp storage to help with merges. It contains room for + * alloced entries. + */ + PyObject **a; /* may point to temparray below */ + Py_ssize_t alloced; + + /* A stack of n pending runs yet to be merged. Run #i starts at + * address base[i] and extends for len[i] elements. It's always + * true (so long as the indices are in bounds) that + * + * pending[i].base + pending[i].len == pending[i+1].base + * + * so we could cut the storage for this, but it's a minor amount, + * and keeping all the info explicit simplifies the code. + */ + int n; + struct s_slice pending[MAX_MERGE_PENDING]; - /* 'a' points to this when possible, rather than muck with malloc. */ - PyObject *temparray[MERGESTATE_TEMP_SIZE]; + /* 'a' points to this when possible, rather than muck with malloc. */ + PyObject *temparray[MERGESTATE_TEMP_SIZE]; } MergeState; /* Conceptually a MergeState's constructor. */ static void merge_init(MergeState *ms) { - assert(ms != NULL); - ms->a = ms->temparray; - ms->alloced = MERGESTATE_TEMP_SIZE; - ms->n = 0; - ms->min_gallop = MIN_GALLOP; + assert(ms != NULL); + ms->a = ms->temparray; + ms->alloced = MERGESTATE_TEMP_SIZE; + ms->n = 0; + ms->min_gallop = MIN_GALLOP; } /* Free all the temp memory owned by the MergeState. This must be called @@ -1323,11 +1323,11 @@ static void merge_freemem(MergeState *ms) { - assert(ms != NULL); - if (ms->a != ms->temparray) - PyMem_Free(ms->a); - ms->a = ms->temparray; - ms->alloced = MERGESTATE_TEMP_SIZE; + assert(ms != NULL); + if (ms->a != ms->temparray) + PyMem_Free(ms->a); + ms->a = ms->temparray; + ms->alloced = MERGESTATE_TEMP_SIZE; } /* Ensure enough temp memory for 'need' array slots is available. @@ -1336,28 +1336,28 @@ static int merge_getmem(MergeState *ms, Py_ssize_t need) { - assert(ms != NULL); - if (need <= ms->alloced) - return 0; - /* Don't realloc! That can cost cycles to copy the old data, but - * we don't care what's in the block. - */ - merge_freemem(ms); - if ((size_t)need > PY_SSIZE_T_MAX / sizeof(PyObject*)) { - PyErr_NoMemory(); - return -1; - } - ms->a = (PyObject **)PyMem_Malloc(need * sizeof(PyObject*)); - if (ms->a) { - ms->alloced = need; - return 0; - } - PyErr_NoMemory(); - merge_freemem(ms); /* reset to sane state */ - return -1; + assert(ms != NULL); + if (need <= ms->alloced) + return 0; + /* Don't realloc! That can cost cycles to copy the old data, but + * we don't care what's in the block. + */ + merge_freemem(ms); + if ((size_t)need > PY_SSIZE_T_MAX / sizeof(PyObject*)) { + PyErr_NoMemory(); + return -1; + } + ms->a = (PyObject **)PyMem_Malloc(need * sizeof(PyObject*)); + if (ms->a) { + ms->alloced = need; + return 0; + } + PyErr_NoMemory(); + merge_freemem(ms); /* reset to sane state */ + return -1; } -#define MERGE_GETMEM(MS, NEED) ((NEED) <= (MS)->alloced ? 0 : \ - merge_getmem(MS, NEED)) +#define MERGE_GETMEM(MS, NEED) ((NEED) <= (MS)->alloced ? 0 : \ + merge_getmem(MS, NEED)) /* Merge the na elements starting at pa with the nb elements starting at pb * in a stable way, in-place. na and nb must be > 0, and pa + na == pb. @@ -1369,125 +1369,125 @@ merge_lo(MergeState *ms, PyObject **pa, Py_ssize_t na, PyObject **pb, Py_ssize_t nb) { - Py_ssize_t k; - PyObject **dest; - int result = -1; /* guilty until proved innocent */ - Py_ssize_t min_gallop; - - assert(ms && pa && pb && na > 0 && nb > 0 && pa + na == pb); - if (MERGE_GETMEM(ms, na) < 0) - return -1; - memcpy(ms->a, pa, na * sizeof(PyObject*)); - dest = pa; - pa = ms->a; - - *dest++ = *pb++; - --nb; - if (nb == 0) - goto Succeed; - if (na == 1) - goto CopyB; - - min_gallop = ms->min_gallop; - for (;;) { - Py_ssize_t acount = 0; /* # of times A won in a row */ - Py_ssize_t bcount = 0; /* # of times B won in a row */ - - /* Do the straightforward thing until (if ever) one run - * appears to win consistently. - */ - for (;;) { - assert(na > 1 && nb > 0); - k = ISLT(*pb, *pa); - if (k) { - if (k < 0) - goto Fail; - *dest++ = *pb++; - ++bcount; - acount = 0; - --nb; - if (nb == 0) - goto Succeed; - if (bcount >= min_gallop) - break; - } - else { - *dest++ = *pa++; - ++acount; - bcount = 0; - --na; - if (na == 1) - goto CopyB; - if (acount >= min_gallop) - break; - } - } - - /* One run is winning so consistently that galloping may - * be a huge win. So try that, and continue galloping until - * (if ever) neither run appears to be winning consistently - * anymore. - */ - ++min_gallop; - do { - assert(na > 1 && nb > 0); - min_gallop -= min_gallop > 1; - ms->min_gallop = min_gallop; - k = gallop_right(*pb, pa, na, 0); - acount = k; - if (k) { - if (k < 0) - goto Fail; - memcpy(dest, pa, k * sizeof(PyObject *)); - dest += k; - pa += k; - na -= k; - if (na == 1) - goto CopyB; - /* na==0 is impossible now if the comparison - * function is consistent, but we can't assume - * that it is. - */ - if (na == 0) - goto Succeed; - } - *dest++ = *pb++; - --nb; - if (nb == 0) - goto Succeed; - - k = gallop_left(*pa, pb, nb, 0); - bcount = k; - if (k) { - if (k < 0) - goto Fail; - memmove(dest, pb, k * sizeof(PyObject *)); - dest += k; - pb += k; - nb -= k; - if (nb == 0) - goto Succeed; - } - *dest++ = *pa++; - --na; - if (na == 1) - goto CopyB; - } while (acount >= MIN_GALLOP || bcount >= MIN_GALLOP); - ++min_gallop; /* penalize it for leaving galloping mode */ - ms->min_gallop = min_gallop; - } + Py_ssize_t k; + PyObject **dest; + int result = -1; /* guilty until proved innocent */ + Py_ssize_t min_gallop; + + assert(ms && pa && pb && na > 0 && nb > 0 && pa + na == pb); + if (MERGE_GETMEM(ms, na) < 0) + return -1; + memcpy(ms->a, pa, na * sizeof(PyObject*)); + dest = pa; + pa = ms->a; + + *dest++ = *pb++; + --nb; + if (nb == 0) + goto Succeed; + if (na == 1) + goto CopyB; + + min_gallop = ms->min_gallop; + for (;;) { + Py_ssize_t acount = 0; /* # of times A won in a row */ + Py_ssize_t bcount = 0; /* # of times B won in a row */ + + /* Do the straightforward thing until (if ever) one run + * appears to win consistently. + */ + for (;;) { + assert(na > 1 && nb > 0); + k = ISLT(*pb, *pa); + if (k) { + if (k < 0) + goto Fail; + *dest++ = *pb++; + ++bcount; + acount = 0; + --nb; + if (nb == 0) + goto Succeed; + if (bcount >= min_gallop) + break; + } + else { + *dest++ = *pa++; + ++acount; + bcount = 0; + --na; + if (na == 1) + goto CopyB; + if (acount >= min_gallop) + break; + } + } + + /* One run is winning so consistently that galloping may + * be a huge win. So try that, and continue galloping until + * (if ever) neither run appears to be winning consistently + * anymore. + */ + ++min_gallop; + do { + assert(na > 1 && nb > 0); + min_gallop -= min_gallop > 1; + ms->min_gallop = min_gallop; + k = gallop_right(*pb, pa, na, 0); + acount = k; + if (k) { + if (k < 0) + goto Fail; + memcpy(dest, pa, k * sizeof(PyObject *)); + dest += k; + pa += k; + na -= k; + if (na == 1) + goto CopyB; + /* na==0 is impossible now if the comparison + * function is consistent, but we can't assume + * that it is. + */ + if (na == 0) + goto Succeed; + } + *dest++ = *pb++; + --nb; + if (nb == 0) + goto Succeed; + + k = gallop_left(*pa, pb, nb, 0); + bcount = k; + if (k) { + if (k < 0) + goto Fail; + memmove(dest, pb, k * sizeof(PyObject *)); + dest += k; + pb += k; + nb -= k; + if (nb == 0) + goto Succeed; + } + *dest++ = *pa++; + --na; + if (na == 1) + goto CopyB; + } while (acount >= MIN_GALLOP || bcount >= MIN_GALLOP); + ++min_gallop; /* penalize it for leaving galloping mode */ + ms->min_gallop = min_gallop; + } Succeed: - result = 0; + result = 0; Fail: - if (na) - memcpy(dest, pa, na * sizeof(PyObject*)); - return result; + if (na) + memcpy(dest, pa, na * sizeof(PyObject*)); + return result; CopyB: - assert(na == 1 && nb > 0); - /* The last element of pa belongs at the end of the merge. */ - memmove(dest, pb, nb * sizeof(PyObject *)); - dest[nb] = *pa; - return 0; + assert(na == 1 && nb > 0); + /* The last element of pa belongs at the end of the merge. */ + memmove(dest, pb, nb * sizeof(PyObject *)); + dest[nb] = *pa; + return 0; } /* Merge the na elements starting at pa with the nb elements starting at pb @@ -1499,134 +1499,134 @@ static Py_ssize_t merge_hi(MergeState *ms, PyObject **pa, Py_ssize_t na, PyObject **pb, Py_ssize_t nb) { - Py_ssize_t k; - PyObject **dest; - int result = -1; /* guilty until proved innocent */ - PyObject **basea; - PyObject **baseb; - Py_ssize_t min_gallop; - - assert(ms && pa && pb && na > 0 && nb > 0 && pa + na == pb); - if (MERGE_GETMEM(ms, nb) < 0) - return -1; - dest = pb + nb - 1; - memcpy(ms->a, pb, nb * sizeof(PyObject*)); - basea = pa; - baseb = ms->a; - pb = ms->a + nb - 1; - pa += na - 1; - - *dest-- = *pa--; - --na; - if (na == 0) - goto Succeed; - if (nb == 1) - goto CopyA; - - min_gallop = ms->min_gallop; - for (;;) { - Py_ssize_t acount = 0; /* # of times A won in a row */ - Py_ssize_t bcount = 0; /* # of times B won in a row */ - - /* Do the straightforward thing until (if ever) one run - * appears to win consistently. - */ - for (;;) { - assert(na > 0 && nb > 1); - k = ISLT(*pb, *pa); - if (k) { - if (k < 0) - goto Fail; - *dest-- = *pa--; - ++acount; - bcount = 0; - --na; - if (na == 0) - goto Succeed; - if (acount >= min_gallop) - break; - } - else { - *dest-- = *pb--; - ++bcount; - acount = 0; - --nb; - if (nb == 1) - goto CopyA; - if (bcount >= min_gallop) - break; - } - } - - /* One run is winning so consistently that galloping may - * be a huge win. So try that, and continue galloping until - * (if ever) neither run appears to be winning consistently - * anymore. - */ - ++min_gallop; - do { - assert(na > 0 && nb > 1); - min_gallop -= min_gallop > 1; - ms->min_gallop = min_gallop; - k = gallop_right(*pb, basea, na, na-1); - if (k < 0) - goto Fail; - k = na - k; - acount = k; - if (k) { - dest -= k; - pa -= k; - memmove(dest+1, pa+1, k * sizeof(PyObject *)); - na -= k; - if (na == 0) - goto Succeed; - } - *dest-- = *pb--; - --nb; - if (nb == 1) - goto CopyA; - - k = gallop_left(*pa, baseb, nb, nb-1); - if (k < 0) - goto Fail; - k = nb - k; - bcount = k; - if (k) { - dest -= k; - pb -= k; - memcpy(dest+1, pb+1, k * sizeof(PyObject *)); - nb -= k; - if (nb == 1) - goto CopyA; - /* nb==0 is impossible now if the comparison - * function is consistent, but we can't assume - * that it is. - */ - if (nb == 0) - goto Succeed; - } - *dest-- = *pa--; - --na; - if (na == 0) - goto Succeed; - } while (acount >= MIN_GALLOP || bcount >= MIN_GALLOP); - ++min_gallop; /* penalize it for leaving galloping mode */ - ms->min_gallop = min_gallop; - } + Py_ssize_t k; + PyObject **dest; + int result = -1; /* guilty until proved innocent */ + PyObject **basea; + PyObject **baseb; + Py_ssize_t min_gallop; + + assert(ms && pa && pb && na > 0 && nb > 0 && pa + na == pb); + if (MERGE_GETMEM(ms, nb) < 0) + return -1; + dest = pb + nb - 1; + memcpy(ms->a, pb, nb * sizeof(PyObject*)); + basea = pa; + baseb = ms->a; + pb = ms->a + nb - 1; + pa += na - 1; + + *dest-- = *pa--; + --na; + if (na == 0) + goto Succeed; + if (nb == 1) + goto CopyA; + + min_gallop = ms->min_gallop; + for (;;) { + Py_ssize_t acount = 0; /* # of times A won in a row */ + Py_ssize_t bcount = 0; /* # of times B won in a row */ + + /* Do the straightforward thing until (if ever) one run + * appears to win consistently. + */ + for (;;) { + assert(na > 0 && nb > 1); + k = ISLT(*pb, *pa); + if (k) { + if (k < 0) + goto Fail; + *dest-- = *pa--; + ++acount; + bcount = 0; + --na; + if (na == 0) + goto Succeed; + if (acount >= min_gallop) + break; + } + else { + *dest-- = *pb--; + ++bcount; + acount = 0; + --nb; + if (nb == 1) + goto CopyA; + if (bcount >= min_gallop) + break; + } + } + + /* One run is winning so consistently that galloping may + * be a huge win. So try that, and continue galloping until + * (if ever) neither run appears to be winning consistently + * anymore. + */ + ++min_gallop; + do { + assert(na > 0 && nb > 1); + min_gallop -= min_gallop > 1; + ms->min_gallop = min_gallop; + k = gallop_right(*pb, basea, na, na-1); + if (k < 0) + goto Fail; + k = na - k; + acount = k; + if (k) { + dest -= k; + pa -= k; + memmove(dest+1, pa+1, k * sizeof(PyObject *)); + na -= k; + if (na == 0) + goto Succeed; + } + *dest-- = *pb--; + --nb; + if (nb == 1) + goto CopyA; + + k = gallop_left(*pa, baseb, nb, nb-1); + if (k < 0) + goto Fail; + k = nb - k; + bcount = k; + if (k) { + dest -= k; + pb -= k; + memcpy(dest+1, pb+1, k * sizeof(PyObject *)); + nb -= k; + if (nb == 1) + goto CopyA; + /* nb==0 is impossible now if the comparison + * function is consistent, but we can't assume + * that it is. + */ + if (nb == 0) + goto Succeed; + } + *dest-- = *pa--; + --na; + if (na == 0) + goto Succeed; + } while (acount >= MIN_GALLOP || bcount >= MIN_GALLOP); + ++min_gallop; /* penalize it for leaving galloping mode */ + ms->min_gallop = min_gallop; + } Succeed: - result = 0; + result = 0; Fail: - if (nb) - memcpy(dest-(nb-1), baseb, nb * sizeof(PyObject*)); - return result; + if (nb) + memcpy(dest-(nb-1), baseb, nb * sizeof(PyObject*)); + return result; CopyA: - assert(nb == 1 && na > 0); - /* The first element of pb belongs at the front of the merge. */ - dest -= na; - pa -= na; - memmove(dest+1, pa+1, na * sizeof(PyObject *)); - *dest = *pb; - return 0; + assert(nb == 1 && na > 0); + /* The first element of pb belongs at the front of the merge. */ + dest -= na; + pa -= na; + memmove(dest+1, pa+1, na * sizeof(PyObject *)); + *dest = *pb; + return 0; } /* Merge the two runs at stack indices i and i+1. @@ -1635,56 +1635,56 @@ static Py_ssize_t merge_at(MergeState *ms, Py_ssize_t i) { - PyObject **pa, **pb; - Py_ssize_t na, nb; - Py_ssize_t k; - - assert(ms != NULL); - assert(ms->n >= 2); - assert(i >= 0); - assert(i == ms->n - 2 || i == ms->n - 3); - - pa = ms->pending[i].base; - na = ms->pending[i].len; - pb = ms->pending[i+1].base; - nb = ms->pending[i+1].len; - assert(na > 0 && nb > 0); - assert(pa + na == pb); - - /* Record the length of the combined runs; if i is the 3rd-last - * run now, also slide over the last run (which isn't involved - * in this merge). The current run i+1 goes away in any case. - */ - ms->pending[i].len = na + nb; - if (i == ms->n - 3) - ms->pending[i+1] = ms->pending[i+2]; - --ms->n; - - /* Where does b start in a? Elements in a before that can be - * ignored (already in place). - */ - k = gallop_right(*pb, pa, na, 0); - if (k < 0) - return -1; - pa += k; - na -= k; - if (na == 0) - return 0; - - /* Where does a end in b? Elements in b after that can be - * ignored (already in place). - */ - nb = gallop_left(pa[na-1], pb, nb, nb-1); - if (nb <= 0) - return nb; - - /* Merge what remains of the runs, using a temp array with - * min(na, nb) elements. - */ - if (na <= nb) - return merge_lo(ms, pa, na, pb, nb); - else - return merge_hi(ms, pa, na, pb, nb); + PyObject **pa, **pb; + Py_ssize_t na, nb; + Py_ssize_t k; + + assert(ms != NULL); + assert(ms->n >= 2); + assert(i >= 0); + assert(i == ms->n - 2 || i == ms->n - 3); + + pa = ms->pending[i].base; + na = ms->pending[i].len; + pb = ms->pending[i+1].base; + nb = ms->pending[i+1].len; + assert(na > 0 && nb > 0); + assert(pa + na == pb); + + /* Record the length of the combined runs; if i is the 3rd-last + * run now, also slide over the last run (which isn't involved + * in this merge). The current run i+1 goes away in any case. + */ + ms->pending[i].len = na + nb; + if (i == ms->n - 3) + ms->pending[i+1] = ms->pending[i+2]; + --ms->n; + + /* Where does b start in a? Elements in a before that can be + * ignored (already in place). + */ + k = gallop_right(*pb, pa, na, 0); + if (k < 0) + return -1; + pa += k; + na -= k; + if (na == 0) + return 0; + + /* Where does a end in b? Elements in b after that can be + * ignored (already in place). + */ + nb = gallop_left(pa[na-1], pb, nb, nb-1); + if (nb <= 0) + return nb; + + /* Merge what remains of the runs, using a temp array with + * min(na, nb) elements. + */ + if (na <= nb) + return merge_lo(ms, pa, na, pb, nb); + else + return merge_hi(ms, pa, na, pb, nb); } /* Examine the stack of runs waiting to be merged, merging adjacent runs @@ -1700,25 +1700,25 @@ static int merge_collapse(MergeState *ms) { - struct s_slice *p = ms->pending; + struct s_slice *p = ms->pending; - assert(ms); - while (ms->n > 1) { - Py_ssize_t n = ms->n - 2; - if (n > 0 && p[n-1].len <= p[n].len + p[n+1].len) { - if (p[n-1].len < p[n+1].len) - --n; - if (merge_at(ms, n) < 0) - return -1; - } - else if (p[n].len <= p[n+1].len) { - if (merge_at(ms, n) < 0) - return -1; - } - else - break; - } - return 0; + assert(ms); + while (ms->n > 1) { + Py_ssize_t n = ms->n - 2; + if (n > 0 && p[n-1].len <= p[n].len + p[n+1].len) { + if (p[n-1].len < p[n+1].len) + --n; + if (merge_at(ms, n) < 0) + return -1; + } + else if (p[n].len <= p[n+1].len) { + if (merge_at(ms, n) < 0) + return -1; + } + else + break; + } + return 0; } /* Regardless of invariants, merge all runs on the stack until only one @@ -1729,17 +1729,17 @@ static int merge_force_collapse(MergeState *ms) { - struct s_slice *p = ms->pending; + struct s_slice *p = ms->pending; - assert(ms); - while (ms->n > 1) { - Py_ssize_t n = ms->n - 2; - if (n > 0 && p[n-1].len < p[n+1].len) - --n; - if (merge_at(ms, n) < 0) - return -1; - } - return 0; + assert(ms); + while (ms->n > 1) { + Py_ssize_t n = ms->n - 2; + if (n > 0 && p[n-1].len < p[n+1].len) + --n; + if (merge_at(ms, n) < 0) + return -1; + } + return 0; } /* Compute a good value for the minimum run length; natural runs shorter @@ -1755,14 +1755,14 @@ static Py_ssize_t merge_compute_minrun(Py_ssize_t n) { - Py_ssize_t r = 0; /* becomes 1 if any 1 bits are shifted off */ + Py_ssize_t r = 0; /* becomes 1 if any 1 bits are shifted off */ - assert(n >= 0); - while (n >= 64) { - r |= n & 1; - n >>= 1; - } - return n + r; + assert(n >= 0); + while (n >= 64) { + r |= n & 1; + n >>= 1; + } + return n + r; } /* Special wrapper to support stable sorting using the decorate-sort-undecorate @@ -1773,9 +1773,9 @@ a full record. */ typedef struct { - PyObject_HEAD - PyObject *key; - PyObject *value; + PyObject_HEAD + PyObject *key; + PyObject *value; } sortwrapperobject; PyDoc_STRVAR(sortwrapper_doc, "Object wrapper with a custom sort key."); @@ -1785,51 +1785,51 @@ sortwrapper_dealloc(sortwrapperobject *); PyTypeObject PySortWrapper_Type = { - PyVarObject_HEAD_INIT(&PyType_Type, 0) - "sortwrapper", /* tp_name */ - sizeof(sortwrapperobject), /* tp_basicsize */ - 0, /* tp_itemsize */ - /* methods */ - (destructor)sortwrapper_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, /* tp_flags */ - sortwrapper_doc, /* tp_doc */ - 0, /* tp_traverse */ - 0, /* tp_clear */ - (richcmpfunc)sortwrapper_richcompare, /* tp_richcompare */ + PyVarObject_HEAD_INIT(&PyType_Type, 0) + "sortwrapper", /* tp_name */ + sizeof(sortwrapperobject), /* tp_basicsize */ + 0, /* tp_itemsize */ + /* methods */ + (destructor)sortwrapper_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, /* tp_flags */ + sortwrapper_doc, /* tp_doc */ + 0, /* tp_traverse */ + 0, /* tp_clear */ + (richcmpfunc)sortwrapper_richcompare, /* tp_richcompare */ }; static PyObject * sortwrapper_richcompare(sortwrapperobject *a, sortwrapperobject *b, int op) { - if (!PyObject_TypeCheck(b, &PySortWrapper_Type)) { - PyErr_SetString(PyExc_TypeError, - "expected a sortwrapperobject"); - return NULL; - } - return PyObject_RichCompare(a->key, b->key, op); + if (!PyObject_TypeCheck(b, &PySortWrapper_Type)) { + PyErr_SetString(PyExc_TypeError, + "expected a sortwrapperobject"); + return NULL; + } + return PyObject_RichCompare(a->key, b->key, op); } static void sortwrapper_dealloc(sortwrapperobject *so) { - Py_XDECREF(so->key); - Py_XDECREF(so->value); - PyObject_Del(so); + Py_XDECREF(so->key); + Py_XDECREF(so->value); + PyObject_Del(so); } /* Returns a new reference to a sortwrapper. @@ -1838,30 +1838,30 @@ static PyObject * build_sortwrapper(PyObject *key, PyObject *value) { - sortwrapperobject *so; + sortwrapperobject *so; - so = PyObject_New(sortwrapperobject, &PySortWrapper_Type); - if (so == NULL) - return NULL; - so->key = key; - so->value = value; - return (PyObject *)so; + so = PyObject_New(sortwrapperobject, &PySortWrapper_Type); + if (so == NULL) + return NULL; + so->key = key; + so->value = value; + return (PyObject *)so; } /* Returns a new reference to the value underlying the wrapper. */ static PyObject * sortwrapper_getvalue(PyObject *so) { - PyObject *value; + PyObject *value; - if (!PyObject_TypeCheck(so, &PySortWrapper_Type)) { - PyErr_SetString(PyExc_TypeError, - "expected a sortwrapperobject"); - return NULL; - } - value = ((sortwrapperobject *)so)->value; - Py_INCREF(value); - return value; + if (!PyObject_TypeCheck(so, &PySortWrapper_Type)) { + PyErr_SetString(PyExc_TypeError, + "expected a sortwrapperobject"); + return NULL; + } + value = ((sortwrapperobject *)so)->value; + Py_INCREF(value); + return value; } /* An adaptive, stable, natural mergesort. See listsort.txt. @@ -1872,163 +1872,163 @@ static PyObject * listsort(PyListObject *self, PyObject *args, PyObject *kwds) { - MergeState ms; - PyObject **lo, **hi; - Py_ssize_t nremaining; - Py_ssize_t minrun; - Py_ssize_t saved_ob_size, saved_allocated; - PyObject **saved_ob_item; - PyObject **final_ob_item; - PyObject *result = NULL; /* guilty until proved innocent */ - int reverse = 0; - PyObject *keyfunc = NULL; - Py_ssize_t i; - PyObject *key, *value, *kvpair; - static char *kwlist[] = {"key", "reverse", 0}; - - assert(self != NULL); - assert (PyList_Check(self)); - if (args != NULL) { - if (!PyArg_ParseTupleAndKeywords(args, kwds, "|Oi:sort", - kwlist, &keyfunc, &reverse)) - return NULL; - if (Py_SIZE(args) > 0) { - PyErr_SetString(PyExc_TypeError, - "must use keyword argument for key function"); - return NULL; - } - } - if (keyfunc == Py_None) - keyfunc = NULL; - - /* The list is temporarily made empty, so that mutations performed - * by comparison functions can't affect the slice of memory we're - * sorting (allowing mutations during sorting is a core-dump - * factory, since ob_item may change). - */ - saved_ob_size = Py_SIZE(self); - saved_ob_item = self->ob_item; - saved_allocated = self->allocated; - Py_SIZE(self) = 0; - self->ob_item = NULL; - self->allocated = -1; /* any operation will reset it to >= 0 */ - - if (keyfunc != NULL) { - for (i=0 ; i < saved_ob_size ; i++) { - value = saved_ob_item[i]; - key = PyObject_CallFunctionObjArgs(keyfunc, value, - NULL); - if (key == NULL) { - for (i=i-1 ; i>=0 ; i--) { - kvpair = saved_ob_item[i]; - value = sortwrapper_getvalue(kvpair); - saved_ob_item[i] = value; - Py_DECREF(kvpair); - } - goto dsu_fail; - } - kvpair = build_sortwrapper(key, value); - if (kvpair == NULL) - goto dsu_fail; - saved_ob_item[i] = kvpair; - } - } - - /* Reverse sort stability achieved by initially reversing the list, - applying a stable forward sort, then reversing the final result. */ - if (reverse && saved_ob_size > 1) - reverse_slice(saved_ob_item, saved_ob_item + saved_ob_size); - - merge_init(&ms); - - nremaining = saved_ob_size; - if (nremaining < 2) - goto succeed; - - /* March over the array once, left to right, finding natural runs, - * and extending short natural runs to minrun elements. - */ - lo = saved_ob_item; - hi = lo + nremaining; - minrun = merge_compute_minrun(nremaining); - do { - int descending; - Py_ssize_t n; - - /* Identify next run. */ - n = count_run(lo, hi, &descending); - if (n < 0) - goto fail; - if (descending) - reverse_slice(lo, lo + n); - /* If short, extend to min(minrun, nremaining). */ - if (n < minrun) { - const Py_ssize_t force = nremaining <= minrun ? - nremaining : minrun; - if (binarysort(lo, lo + force, lo + n) < 0) - goto fail; - n = force; - } - /* Push run onto pending-runs stack, and maybe merge. */ - assert(ms.n < MAX_MERGE_PENDING); - ms.pending[ms.n].base = lo; - ms.pending[ms.n].len = n; - ++ms.n; - if (merge_collapse(&ms) < 0) - goto fail; - /* Advance to find next run. */ - lo += n; - nremaining -= n; - } while (nremaining); - assert(lo == hi); - - if (merge_force_collapse(&ms) < 0) - goto fail; - assert(ms.n == 1); - assert(ms.pending[0].base == saved_ob_item); - assert(ms.pending[0].len == saved_ob_size); + MergeState ms; + PyObject **lo, **hi; + Py_ssize_t nremaining; + Py_ssize_t minrun; + Py_ssize_t saved_ob_size, saved_allocated; + PyObject **saved_ob_item; + PyObject **final_ob_item; + PyObject *result = NULL; /* guilty until proved innocent */ + int reverse = 0; + PyObject *keyfunc = NULL; + Py_ssize_t i; + PyObject *key, *value, *kvpair; + static char *kwlist[] = {"key", "reverse", 0}; + + assert(self != NULL); + assert (PyList_Check(self)); + if (args != NULL) { + if (!PyArg_ParseTupleAndKeywords(args, kwds, "|Oi:sort", + kwlist, &keyfunc, &reverse)) + return NULL; + if (Py_SIZE(args) > 0) { + PyErr_SetString(PyExc_TypeError, + "must use keyword argument for key function"); + return NULL; + } + } + if (keyfunc == Py_None) + keyfunc = NULL; + + /* The list is temporarily made empty, so that mutations performed + * by comparison functions can't affect the slice of memory we're + * sorting (allowing mutations during sorting is a core-dump + * factory, since ob_item may change). + */ + saved_ob_size = Py_SIZE(self); + saved_ob_item = self->ob_item; + saved_allocated = self->allocated; + Py_SIZE(self) = 0; + self->ob_item = NULL; + self->allocated = -1; /* any operation will reset it to >= 0 */ + + if (keyfunc != NULL) { + for (i=0 ; i < saved_ob_size ; i++) { + value = saved_ob_item[i]; + key = PyObject_CallFunctionObjArgs(keyfunc, value, + NULL); + if (key == NULL) { + for (i=i-1 ; i>=0 ; i--) { + kvpair = saved_ob_item[i]; + value = sortwrapper_getvalue(kvpair); + saved_ob_item[i] = value; + Py_DECREF(kvpair); + } + goto dsu_fail; + } + kvpair = build_sortwrapper(key, value); + if (kvpair == NULL) + goto dsu_fail; + saved_ob_item[i] = kvpair; + } + } + + /* Reverse sort stability achieved by initially reversing the list, + applying a stable forward sort, then reversing the final result. */ + if (reverse && saved_ob_size > 1) + reverse_slice(saved_ob_item, saved_ob_item + saved_ob_size); + + merge_init(&ms); + + nremaining = saved_ob_size; + if (nremaining < 2) + goto succeed; + + /* March over the array once, left to right, finding natural runs, + * and extending short natural runs to minrun elements. + */ + lo = saved_ob_item; + hi = lo + nremaining; + minrun = merge_compute_minrun(nremaining); + do { + int descending; + Py_ssize_t n; + + /* Identify next run. */ + n = count_run(lo, hi, &descending); + if (n < 0) + goto fail; + if (descending) + reverse_slice(lo, lo + n); + /* If short, extend to min(minrun, nremaining). */ + if (n < minrun) { + const Py_ssize_t force = nremaining <= minrun ? + nremaining : minrun; + if (binarysort(lo, lo + force, lo + n) < 0) + goto fail; + n = force; + } + /* Push run onto pending-runs stack, and maybe merge. */ + assert(ms.n < MAX_MERGE_PENDING); + ms.pending[ms.n].base = lo; + ms.pending[ms.n].len = n; + ++ms.n; + if (merge_collapse(&ms) < 0) + goto fail; + /* Advance to find next run. */ + lo += n; + nremaining -= n; + } while (nremaining); + assert(lo == hi); + + if (merge_force_collapse(&ms) < 0) + goto fail; + assert(ms.n == 1); + assert(ms.pending[0].base == saved_ob_item); + assert(ms.pending[0].len == saved_ob_size); succeed: - result = Py_None; + result = Py_None; fail: - if (keyfunc != NULL) { - for (i=0 ; i < saved_ob_size ; i++) { - kvpair = saved_ob_item[i]; - value = sortwrapper_getvalue(kvpair); - saved_ob_item[i] = value; - Py_DECREF(kvpair); - } - } - - if (self->allocated != -1 && result != NULL) { - /* The user mucked with the list during the sort, - * and we don't already have another error to report. - */ - PyErr_SetString(PyExc_ValueError, "list modified during sort"); - result = NULL; - } + if (keyfunc != NULL) { + for (i=0 ; i < saved_ob_size ; i++) { + kvpair = saved_ob_item[i]; + value = sortwrapper_getvalue(kvpair); + saved_ob_item[i] = value; + Py_DECREF(kvpair); + } + } + + if (self->allocated != -1 && result != NULL) { + /* The user mucked with the list during the sort, + * and we don't already have another error to report. + */ + PyErr_SetString(PyExc_ValueError, "list modified during sort"); + result = NULL; + } - if (reverse && saved_ob_size > 1) - reverse_slice(saved_ob_item, saved_ob_item + saved_ob_size); + if (reverse && saved_ob_size > 1) + reverse_slice(saved_ob_item, saved_ob_item + saved_ob_size); - merge_freemem(&ms); + merge_freemem(&ms); dsu_fail: - final_ob_item = self->ob_item; - i = Py_SIZE(self); - Py_SIZE(self) = saved_ob_size; - self->ob_item = saved_ob_item; - self->allocated = saved_allocated; - if (final_ob_item != NULL) { - /* we cannot use list_clear() for this because it does not - guarantee that the list is really empty when it returns */ - while (--i >= 0) { - Py_XDECREF(final_ob_item[i]); - } - PyMem_FREE(final_ob_item); - } - Py_XINCREF(result); - return result; + final_ob_item = self->ob_item; + i = Py_SIZE(self); + Py_SIZE(self) = saved_ob_size; + self->ob_item = saved_ob_item; + self->allocated = saved_allocated; + if (final_ob_item != NULL) { + /* we cannot use list_clear() for this because it does not + guarantee that the list is really empty when it returns */ + while (--i >= 0) { + Py_XDECREF(final_ob_item[i]); + } + PyMem_FREE(final_ob_item); + } + Py_XINCREF(result); + return result; } #undef IFLT #undef ISLT @@ -2036,248 +2036,248 @@ int PyList_Sort(PyObject *v) { - if (v == NULL || !PyList_Check(v)) { - PyErr_BadInternalCall(); - return -1; - } - v = listsort((PyListObject *)v, (PyObject *)NULL, (PyObject *)NULL); - if (v == NULL) - return -1; - Py_DECREF(v); - return 0; + if (v == NULL || !PyList_Check(v)) { + PyErr_BadInternalCall(); + return -1; + } + v = listsort((PyListObject *)v, (PyObject *)NULL, (PyObject *)NULL); + if (v == NULL) + return -1; + Py_DECREF(v); + return 0; } static PyObject * listreverse(PyListObject *self) { - if (Py_SIZE(self) > 1) - reverse_slice(self->ob_item, self->ob_item + Py_SIZE(self)); - Py_RETURN_NONE; + if (Py_SIZE(self) > 1) + reverse_slice(self->ob_item, self->ob_item + Py_SIZE(self)); + Py_RETURN_NONE; } int PyList_Reverse(PyObject *v) { - PyListObject *self = (PyListObject *)v; + PyListObject *self = (PyListObject *)v; - if (v == NULL || !PyList_Check(v)) { - PyErr_BadInternalCall(); - return -1; - } - if (Py_SIZE(self) > 1) - reverse_slice(self->ob_item, self->ob_item + Py_SIZE(self)); - return 0; + if (v == NULL || !PyList_Check(v)) { + PyErr_BadInternalCall(); + return -1; + } + if (Py_SIZE(self) > 1) + reverse_slice(self->ob_item, self->ob_item + Py_SIZE(self)); + return 0; } PyObject * PyList_AsTuple(PyObject *v) { - PyObject *w; - PyObject **p, **q; - Py_ssize_t n; - if (v == NULL || !PyList_Check(v)) { - PyErr_BadInternalCall(); - return NULL; - } - n = Py_SIZE(v); - w = PyTuple_New(n); - if (w == NULL) - return NULL; - p = ((PyTupleObject *)w)->ob_item; - q = ((PyListObject *)v)->ob_item; - while (--n >= 0) { - Py_INCREF(*q); - *p = *q; - p++; - q++; - } - return w; + PyObject *w; + PyObject **p, **q; + Py_ssize_t n; + if (v == NULL || !PyList_Check(v)) { + PyErr_BadInternalCall(); + return NULL; + } + n = Py_SIZE(v); + w = PyTuple_New(n); + if (w == NULL) + return NULL; + p = ((PyTupleObject *)w)->ob_item; + q = ((PyListObject *)v)->ob_item; + while (--n >= 0) { + Py_INCREF(*q); + *p = *q; + p++; + q++; + } + return w; } static PyObject * listindex(PyListObject *self, PyObject *args) { - Py_ssize_t i, start=0, stop=Py_SIZE(self); - PyObject *v; + Py_ssize_t i, start=0, stop=Py_SIZE(self); + PyObject *v; - if (!PyArg_ParseTuple(args, "O|O&O&:index", &v, - _PyEval_SliceIndex, &start, - _PyEval_SliceIndex, &stop)) - return NULL; - if (start < 0) { - start += Py_SIZE(self); - if (start < 0) - start = 0; - } - if (stop < 0) { - stop += Py_SIZE(self); - if (stop < 0) - stop = 0; - } - for (i = start; i < stop && i < Py_SIZE(self); i++) { - int cmp = PyObject_RichCompareBool(self->ob_item[i], v, Py_EQ); - if (cmp > 0) - return PyLong_FromSsize_t(i); - else if (cmp < 0) - return NULL; - } - PyErr_SetString(PyExc_ValueError, "list.index(x): x not in list"); - return NULL; + if (!PyArg_ParseTuple(args, "O|O&O&:index", &v, + _PyEval_SliceIndex, &start, + _PyEval_SliceIndex, &stop)) + return NULL; + if (start < 0) { + start += Py_SIZE(self); + if (start < 0) + start = 0; + } + if (stop < 0) { + stop += Py_SIZE(self); + if (stop < 0) + stop = 0; + } + for (i = start; i < stop && i < Py_SIZE(self); i++) { + int cmp = PyObject_RichCompareBool(self->ob_item[i], v, Py_EQ); + if (cmp > 0) + return PyLong_FromSsize_t(i); + else if (cmp < 0) + return NULL; + } + PyErr_SetString(PyExc_ValueError, "list.index(x): x not in list"); + return NULL; } static PyObject * listcount(PyListObject *self, PyObject *v) { - Py_ssize_t count = 0; - Py_ssize_t i; + Py_ssize_t count = 0; + Py_ssize_t i; - for (i = 0; i < Py_SIZE(self); i++) { - int cmp = PyObject_RichCompareBool(self->ob_item[i], v, Py_EQ); - if (cmp > 0) - count++; - else if (cmp < 0) - return NULL; - } - return PyLong_FromSsize_t(count); + for (i = 0; i < Py_SIZE(self); i++) { + int cmp = PyObject_RichCompareBool(self->ob_item[i], v, Py_EQ); + if (cmp > 0) + count++; + else if (cmp < 0) + return NULL; + } + return PyLong_FromSsize_t(count); } static PyObject * listremove(PyListObject *self, PyObject *v) { - Py_ssize_t i; + Py_ssize_t i; - for (i = 0; i < Py_SIZE(self); i++) { - int cmp = PyObject_RichCompareBool(self->ob_item[i], v, Py_EQ); - if (cmp > 0) { - if (list_ass_slice(self, i, i+1, - (PyObject *)NULL) == 0) - Py_RETURN_NONE; - return NULL; - } - else if (cmp < 0) - return NULL; - } - PyErr_SetString(PyExc_ValueError, "list.remove(x): x not in list"); - return NULL; + for (i = 0; i < Py_SIZE(self); i++) { + int cmp = PyObject_RichCompareBool(self->ob_item[i], v, Py_EQ); + if (cmp > 0) { + if (list_ass_slice(self, i, i+1, + (PyObject *)NULL) == 0) + Py_RETURN_NONE; + return NULL; + } + else if (cmp < 0) + return NULL; + } + PyErr_SetString(PyExc_ValueError, "list.remove(x): x not in list"); + return NULL; } static int list_traverse(PyListObject *o, visitproc visit, void *arg) { - Py_ssize_t i; + Py_ssize_t i; - for (i = Py_SIZE(o); --i >= 0; ) - Py_VISIT(o->ob_item[i]); - return 0; + for (i = Py_SIZE(o); --i >= 0; ) + Py_VISIT(o->ob_item[i]); + return 0; } static PyObject * list_richcompare(PyObject *v, PyObject *w, int op) { - PyListObject *vl, *wl; - Py_ssize_t i; + PyListObject *vl, *wl; + Py_ssize_t i; - if (!PyList_Check(v) || !PyList_Check(w)) { - Py_INCREF(Py_NotImplemented); - return Py_NotImplemented; - } - - vl = (PyListObject *)v; - wl = (PyListObject *)w; - - if (Py_SIZE(vl) != Py_SIZE(wl) && (op == Py_EQ || op == Py_NE)) { - /* Shortcut: if the lengths differ, the lists differ */ - PyObject *res; - if (op == Py_EQ) - res = Py_False; - else - res = Py_True; - Py_INCREF(res); - return res; - } - - /* Search for the first index where items are different */ - for (i = 0; i < Py_SIZE(vl) && i < Py_SIZE(wl); i++) { - int k = PyObject_RichCompareBool(vl->ob_item[i], - wl->ob_item[i], Py_EQ); - if (k < 0) - return NULL; - if (!k) - break; - } - - if (i >= Py_SIZE(vl) || i >= Py_SIZE(wl)) { - /* No more items to compare -- compare sizes */ - Py_ssize_t vs = Py_SIZE(vl); - Py_ssize_t ws = Py_SIZE(wl); - int cmp; - PyObject *res; - switch (op) { - case Py_LT: cmp = vs < ws; break; - case Py_LE: cmp = vs <= ws; break; - case Py_EQ: cmp = vs == ws; break; - case Py_NE: cmp = vs != ws; break; - case Py_GT: cmp = vs > ws; break; - case Py_GE: cmp = vs >= ws; break; - default: return NULL; /* cannot happen */ - } - if (cmp) - res = Py_True; - else - res = Py_False; - Py_INCREF(res); - return res; - } - - /* We have an item that differs -- shortcuts for EQ/NE */ - if (op == Py_EQ) { - Py_INCREF(Py_False); - return Py_False; - } - if (op == Py_NE) { - Py_INCREF(Py_True); - return Py_True; - } + if (!PyList_Check(v) || !PyList_Check(w)) { + Py_INCREF(Py_NotImplemented); + return Py_NotImplemented; + } + + vl = (PyListObject *)v; + wl = (PyListObject *)w; + + if (Py_SIZE(vl) != Py_SIZE(wl) && (op == Py_EQ || op == Py_NE)) { + /* Shortcut: if the lengths differ, the lists differ */ + PyObject *res; + if (op == Py_EQ) + res = Py_False; + else + res = Py_True; + Py_INCREF(res); + return res; + } + + /* Search for the first index where items are different */ + for (i = 0; i < Py_SIZE(vl) && i < Py_SIZE(wl); i++) { + int k = PyObject_RichCompareBool(vl->ob_item[i], + wl->ob_item[i], Py_EQ); + if (k < 0) + return NULL; + if (!k) + break; + } + + if (i >= Py_SIZE(vl) || i >= Py_SIZE(wl)) { + /* No more items to compare -- compare sizes */ + Py_ssize_t vs = Py_SIZE(vl); + Py_ssize_t ws = Py_SIZE(wl); + int cmp; + PyObject *res; + switch (op) { + case Py_LT: cmp = vs < ws; break; + case Py_LE: cmp = vs <= ws; break; + case Py_EQ: cmp = vs == ws; break; + case Py_NE: cmp = vs != ws; break; + case Py_GT: cmp = vs > ws; break; + case Py_GE: cmp = vs >= ws; break; + default: return NULL; /* cannot happen */ + } + if (cmp) + res = Py_True; + else + res = Py_False; + Py_INCREF(res); + return res; + } + + /* We have an item that differs -- shortcuts for EQ/NE */ + if (op == Py_EQ) { + Py_INCREF(Py_False); + return Py_False; + } + if (op == Py_NE) { + Py_INCREF(Py_True); + return Py_True; + } - /* Compare the final item again using the proper operator */ - return PyObject_RichCompare(vl->ob_item[i], wl->ob_item[i], op); + /* Compare the final item again using the proper operator */ + return PyObject_RichCompare(vl->ob_item[i], wl->ob_item[i], op); } static int list_init(PyListObject *self, PyObject *args, PyObject *kw) { - PyObject *arg = NULL; - static char *kwlist[] = {"sequence", 0}; + PyObject *arg = NULL; + static char *kwlist[] = {"sequence", 0}; - if (!PyArg_ParseTupleAndKeywords(args, kw, "|O:list", kwlist, &arg)) - return -1; + if (!PyArg_ParseTupleAndKeywords(args, kw, "|O:list", kwlist, &arg)) + return -1; - /* Verify list invariants established by PyType_GenericAlloc() */ - assert(0 <= Py_SIZE(self)); - assert(Py_SIZE(self) <= self->allocated || self->allocated == -1); - assert(self->ob_item != NULL || - self->allocated == 0 || self->allocated == -1); - - /* Empty previous contents */ - if (self->ob_item != NULL) { - (void)list_clear(self); - } - if (arg != NULL) { - PyObject *rv = listextend(self, arg); - if (rv == NULL) - return -1; - Py_DECREF(rv); - } - return 0; + /* Verify list invariants established by PyType_GenericAlloc() */ + assert(0 <= Py_SIZE(self)); + assert(Py_SIZE(self) <= self->allocated || self->allocated == -1); + assert(self->ob_item != NULL || + self->allocated == 0 || self->allocated == -1); + + /* Empty previous contents */ + if (self->ob_item != NULL) { + (void)list_clear(self); + } + if (arg != NULL) { + PyObject *rv = listextend(self, arg); + if (rv == NULL) + return -1; + Py_DECREF(rv); + } + return 0; } static PyObject * list_sizeof(PyListObject *self) { - Py_ssize_t res; + Py_ssize_t res; - res = sizeof(PyListObject) + self->allocated * sizeof(void*); - return PyLong_FromSsize_t(res); + res = sizeof(PyListObject) + self->allocated * sizeof(void*); + return PyLong_FromSsize_t(res); } static PyObject *list_iter(PyObject *seq); @@ -2314,32 +2314,32 @@ static PyObject *list_subscript(PyListObject*, PyObject*); static PyMethodDef list_methods[] = { - {"__getitem__", (PyCFunction)list_subscript, METH_O|METH_COEXIST, getitem_doc}, - {"__reversed__",(PyCFunction)list_reversed, METH_NOARGS, reversed_doc}, - {"__sizeof__", (PyCFunction)list_sizeof, METH_NOARGS, sizeof_doc}, - {"append", (PyCFunction)listappend, METH_O, append_doc}, - {"insert", (PyCFunction)listinsert, METH_VARARGS, insert_doc}, - {"extend", (PyCFunction)listextend, METH_O, extend_doc}, - {"pop", (PyCFunction)listpop, METH_VARARGS, pop_doc}, - {"remove", (PyCFunction)listremove, METH_O, remove_doc}, - {"index", (PyCFunction)listindex, METH_VARARGS, index_doc}, - {"count", (PyCFunction)listcount, METH_O, count_doc}, - {"reverse", (PyCFunction)listreverse, METH_NOARGS, reverse_doc}, - {"sort", (PyCFunction)listsort, METH_VARARGS | METH_KEYWORDS, sort_doc}, - {NULL, NULL} /* sentinel */ + {"__getitem__", (PyCFunction)list_subscript, METH_O|METH_COEXIST, getitem_doc}, + {"__reversed__",(PyCFunction)list_reversed, METH_NOARGS, reversed_doc}, + {"__sizeof__", (PyCFunction)list_sizeof, METH_NOARGS, sizeof_doc}, + {"append", (PyCFunction)listappend, METH_O, append_doc}, + {"insert", (PyCFunction)listinsert, METH_VARARGS, insert_doc}, + {"extend", (PyCFunction)listextend, METH_O, extend_doc}, + {"pop", (PyCFunction)listpop, METH_VARARGS, pop_doc}, + {"remove", (PyCFunction)listremove, METH_O, remove_doc}, + {"index", (PyCFunction)listindex, METH_VARARGS, index_doc}, + {"count", (PyCFunction)listcount, METH_O, count_doc}, + {"reverse", (PyCFunction)listreverse, METH_NOARGS, reverse_doc}, + {"sort", (PyCFunction)listsort, METH_VARARGS | METH_KEYWORDS, sort_doc}, + {NULL, NULL} /* sentinel */ }; static PySequenceMethods list_as_sequence = { - (lenfunc)list_length, /* sq_length */ - (binaryfunc)list_concat, /* sq_concat */ - (ssizeargfunc)list_repeat, /* sq_repeat */ - (ssizeargfunc)list_item, /* sq_item */ - 0, /* sq_slice */ - (ssizeobjargproc)list_ass_item, /* sq_ass_item */ - 0, /* sq_ass_slice */ - (objobjproc)list_contains, /* sq_contains */ - (binaryfunc)list_inplace_concat, /* sq_inplace_concat */ - (ssizeargfunc)list_inplace_repeat, /* sq_inplace_repeat */ + (lenfunc)list_length, /* sq_length */ + (binaryfunc)list_concat, /* sq_concat */ + (ssizeargfunc)list_repeat, /* sq_repeat */ + (ssizeargfunc)list_item, /* sq_item */ + 0, /* sq_slice */ + (ssizeobjargproc)list_ass_item, /* sq_ass_item */ + 0, /* sq_ass_slice */ + (objobjproc)list_contains, /* sq_contains */ + (binaryfunc)list_inplace_concat, /* sq_inplace_concat */ + (ssizeargfunc)list_inplace_repeat, /* sq_inplace_repeat */ }; PyDoc_STRVAR(list_doc, @@ -2349,275 +2349,275 @@ static PyObject * list_subscript(PyListObject* self, PyObject* item) { - if (PyIndex_Check(item)) { - Py_ssize_t i; - i = PyNumber_AsSsize_t(item, PyExc_IndexError); - if (i == -1 && PyErr_Occurred()) - return NULL; - if (i < 0) - i += PyList_GET_SIZE(self); - return list_item(self, i); - } - else if (PySlice_Check(item)) { - Py_ssize_t start, stop, step, slicelength, cur, i; - PyObject* result; - PyObject* it; - PyObject **src, **dest; - - if (PySlice_GetIndicesEx((PySliceObject*)item, Py_SIZE(self), - &start, &stop, &step, &slicelength) < 0) { - return NULL; - } - - if (slicelength <= 0) { - return PyList_New(0); - } - else if (step == 1) { - return list_slice(self, start, stop); - } - else { - result = PyList_New(slicelength); - if (!result) return NULL; - - src = self->ob_item; - dest = ((PyListObject *)result)->ob_item; - for (cur = start, i = 0; i < slicelength; - cur += step, i++) { - it = src[cur]; - Py_INCREF(it); - dest[i] = it; - } - - return result; - } - } - else { - PyErr_Format(PyExc_TypeError, - "list indices must be integers, not %.200s", - item->ob_type->tp_name); - return NULL; - } + if (PyIndex_Check(item)) { + Py_ssize_t i; + i = PyNumber_AsSsize_t(item, PyExc_IndexError); + if (i == -1 && PyErr_Occurred()) + return NULL; + if (i < 0) + i += PyList_GET_SIZE(self); + return list_item(self, i); + } + else if (PySlice_Check(item)) { + Py_ssize_t start, stop, step, slicelength, cur, i; + PyObject* result; + PyObject* it; + PyObject **src, **dest; + + if (PySlice_GetIndicesEx((PySliceObject*)item, Py_SIZE(self), + &start, &stop, &step, &slicelength) < 0) { + return NULL; + } + + if (slicelength <= 0) { + return PyList_New(0); + } + else if (step == 1) { + return list_slice(self, start, stop); + } + else { + result = PyList_New(slicelength); + if (!result) return NULL; + + src = self->ob_item; + dest = ((PyListObject *)result)->ob_item; + for (cur = start, i = 0; i < slicelength; + cur += step, i++) { + it = src[cur]; + Py_INCREF(it); + dest[i] = it; + } + + return result; + } + } + else { + PyErr_Format(PyExc_TypeError, + "list indices must be integers, not %.200s", + item->ob_type->tp_name); + return NULL; + } } static int list_ass_subscript(PyListObject* self, PyObject* item, PyObject* value) { - if (PyIndex_Check(item)) { - Py_ssize_t i = PyNumber_AsSsize_t(item, PyExc_IndexError); - if (i == -1 && PyErr_Occurred()) - return -1; - if (i < 0) - i += PyList_GET_SIZE(self); - return list_ass_item(self, i, value); - } - else if (PySlice_Check(item)) { - Py_ssize_t start, stop, step, slicelength; - - if (PySlice_GetIndicesEx((PySliceObject*)item, Py_SIZE(self), - &start, &stop, &step, &slicelength) < 0) { - return -1; - } - - if (step == 1) - return list_ass_slice(self, start, stop, value); - - /* Make sure s[5:2] = [..] inserts at the right place: - before 5, not before 2. */ - if ((step < 0 && start < stop) || - (step > 0 && start > stop)) - stop = start; - - if (value == NULL) { - /* delete slice */ - PyObject **garbage; - size_t cur; - Py_ssize_t i; - - if (slicelength <= 0) - return 0; - - if (step < 0) { - stop = start + 1; - start = stop + step*(slicelength - 1) - 1; - step = -step; - } - - assert((size_t)slicelength <= - PY_SIZE_MAX / sizeof(PyObject*)); - - garbage = (PyObject**) - PyMem_MALLOC(slicelength*sizeof(PyObject*)); - if (!garbage) { - PyErr_NoMemory(); - return -1; - } - - /* drawing pictures might help understand these for - loops. Basically, we memmove the parts of the - list that are *not* part of the slice: step-1 - items for each item that is part of the slice, - and then tail end of the list that was not - covered by the slice */ - for (cur = start, i = 0; - cur < (size_t)stop; - cur += step, i++) { - Py_ssize_t lim = step - 1; - - garbage[i] = PyList_GET_ITEM(self, cur); - - if (cur + step >= (size_t)Py_SIZE(self)) { - lim = Py_SIZE(self) - cur - 1; - } - - memmove(self->ob_item + cur - i, - self->ob_item + cur + 1, - lim * sizeof(PyObject *)); - } - cur = start + slicelength*step; - if (cur < (size_t)Py_SIZE(self)) { - memmove(self->ob_item + cur - slicelength, - self->ob_item + cur, - (Py_SIZE(self) - cur) * - sizeof(PyObject *)); - } - - Py_SIZE(self) -= slicelength; - list_resize(self, Py_SIZE(self)); - - for (i = 0; i < slicelength; i++) { - Py_DECREF(garbage[i]); - } - PyMem_FREE(garbage); - - return 0; - } - else { - /* assign slice */ - PyObject *ins, *seq; - PyObject **garbage, **seqitems, **selfitems; - Py_ssize_t cur, i; - - /* protect against a[::-1] = a */ - if (self == (PyListObject*)value) { - seq = list_slice((PyListObject*)value, 0, - PyList_GET_SIZE(value)); - } - else { - seq = PySequence_Fast(value, - "must assign iterable " - "to extended slice"); - } - if (!seq) - return -1; - - if (PySequence_Fast_GET_SIZE(seq) != slicelength) { - PyErr_Format(PyExc_ValueError, - "attempt to assign sequence of " - "size %zd to extended slice of " - "size %zd", - PySequence_Fast_GET_SIZE(seq), - slicelength); - Py_DECREF(seq); - return -1; - } - - if (!slicelength) { - Py_DECREF(seq); - return 0; - } - - garbage = (PyObject**) - PyMem_MALLOC(slicelength*sizeof(PyObject*)); - if (!garbage) { - Py_DECREF(seq); - PyErr_NoMemory(); - return -1; - } - - selfitems = self->ob_item; - seqitems = PySequence_Fast_ITEMS(seq); - for (cur = start, i = 0; i < slicelength; - cur += step, i++) { - garbage[i] = selfitems[cur]; - ins = seqitems[i]; - Py_INCREF(ins); - selfitems[cur] = ins; - } - - for (i = 0; i < slicelength; i++) { - Py_DECREF(garbage[i]); - } - - PyMem_FREE(garbage); - Py_DECREF(seq); - - return 0; - } - } - else { - PyErr_Format(PyExc_TypeError, - "list indices must be integers, not %.200s", - item->ob_type->tp_name); - return -1; - } + if (PyIndex_Check(item)) { + Py_ssize_t i = PyNumber_AsSsize_t(item, PyExc_IndexError); + if (i == -1 && PyErr_Occurred()) + return -1; + if (i < 0) + i += PyList_GET_SIZE(self); + return list_ass_item(self, i, value); + } + else if (PySlice_Check(item)) { + Py_ssize_t start, stop, step, slicelength; + + if (PySlice_GetIndicesEx((PySliceObject*)item, Py_SIZE(self), + &start, &stop, &step, &slicelength) < 0) { + return -1; + } + + if (step == 1) + return list_ass_slice(self, start, stop, value); + + /* Make sure s[5:2] = [..] inserts at the right place: + before 5, not before 2. */ + if ((step < 0 && start < stop) || + (step > 0 && start > stop)) + stop = start; + + if (value == NULL) { + /* delete slice */ + PyObject **garbage; + size_t cur; + Py_ssize_t i; + + if (slicelength <= 0) + return 0; + + if (step < 0) { + stop = start + 1; + start = stop + step*(slicelength - 1) - 1; + step = -step; + } + + assert((size_t)slicelength <= + PY_SIZE_MAX / sizeof(PyObject*)); + + garbage = (PyObject**) + PyMem_MALLOC(slicelength*sizeof(PyObject*)); + if (!garbage) { + PyErr_NoMemory(); + return -1; + } + + /* drawing pictures might help understand these for + loops. Basically, we memmove the parts of the + list that are *not* part of the slice: step-1 + items for each item that is part of the slice, + and then tail end of the list that was not + covered by the slice */ + for (cur = start, i = 0; + cur < (size_t)stop; + cur += step, i++) { + Py_ssize_t lim = step - 1; + + garbage[i] = PyList_GET_ITEM(self, cur); + + if (cur + step >= (size_t)Py_SIZE(self)) { + lim = Py_SIZE(self) - cur - 1; + } + + memmove(self->ob_item + cur - i, + self->ob_item + cur + 1, + lim * sizeof(PyObject *)); + } + cur = start + slicelength*step; + if (cur < (size_t)Py_SIZE(self)) { + memmove(self->ob_item + cur - slicelength, + self->ob_item + cur, + (Py_SIZE(self) - cur) * + sizeof(PyObject *)); + } + + Py_SIZE(self) -= slicelength; + list_resize(self, Py_SIZE(self)); + + for (i = 0; i < slicelength; i++) { + Py_DECREF(garbage[i]); + } + PyMem_FREE(garbage); + + return 0; + } + else { + /* assign slice */ + PyObject *ins, *seq; + PyObject **garbage, **seqitems, **selfitems; + Py_ssize_t cur, i; + + /* protect against a[::-1] = a */ + if (self == (PyListObject*)value) { + seq = list_slice((PyListObject*)value, 0, + PyList_GET_SIZE(value)); + } + else { + seq = PySequence_Fast(value, + "must assign iterable " + "to extended slice"); + } + if (!seq) + return -1; + + if (PySequence_Fast_GET_SIZE(seq) != slicelength) { + PyErr_Format(PyExc_ValueError, + "attempt to assign sequence of " + "size %zd to extended slice of " + "size %zd", + PySequence_Fast_GET_SIZE(seq), + slicelength); + Py_DECREF(seq); + return -1; + } + + if (!slicelength) { + Py_DECREF(seq); + return 0; + } + + garbage = (PyObject**) + PyMem_MALLOC(slicelength*sizeof(PyObject*)); + if (!garbage) { + Py_DECREF(seq); + PyErr_NoMemory(); + return -1; + } + + selfitems = self->ob_item; + seqitems = PySequence_Fast_ITEMS(seq); + for (cur = start, i = 0; i < slicelength; + cur += step, i++) { + garbage[i] = selfitems[cur]; + ins = seqitems[i]; + Py_INCREF(ins); + selfitems[cur] = ins; + } + + for (i = 0; i < slicelength; i++) { + Py_DECREF(garbage[i]); + } + + PyMem_FREE(garbage); + Py_DECREF(seq); + + return 0; + } + } + else { + PyErr_Format(PyExc_TypeError, + "list indices must be integers, not %.200s", + item->ob_type->tp_name); + return -1; + } } static PyMappingMethods list_as_mapping = { - (lenfunc)list_length, - (binaryfunc)list_subscript, - (objobjargproc)list_ass_subscript + (lenfunc)list_length, + (binaryfunc)list_subscript, + (objobjargproc)list_ass_subscript }; PyTypeObject PyList_Type = { - PyVarObject_HEAD_INIT(&PyType_Type, 0) - "list", - sizeof(PyListObject), - 0, - (destructor)list_dealloc, /* tp_dealloc */ - 0, /* tp_print */ - 0, /* tp_getattr */ - 0, /* tp_setattr */ - 0, /* tp_reserved */ - (reprfunc)list_repr, /* tp_repr */ - 0, /* tp_as_number */ - &list_as_sequence, /* tp_as_sequence */ - &list_as_mapping, /* tp_as_mapping */ - (hashfunc)PyObject_HashNotImplemented, /* 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 | - Py_TPFLAGS_BASETYPE | Py_TPFLAGS_LIST_SUBCLASS, /* tp_flags */ - list_doc, /* tp_doc */ - (traverseproc)list_traverse, /* tp_traverse */ - (inquiry)list_clear, /* tp_clear */ - list_richcompare, /* tp_richcompare */ - 0, /* tp_weaklistoffset */ - list_iter, /* tp_iter */ - 0, /* tp_iternext */ - list_methods, /* tp_methods */ - 0, /* tp_members */ - 0, /* tp_getset */ - 0, /* tp_base */ - 0, /* tp_dict */ - 0, /* tp_descr_get */ - 0, /* tp_descr_set */ - 0, /* tp_dictoffset */ - (initproc)list_init, /* tp_init */ - PyType_GenericAlloc, /* tp_alloc */ - PyType_GenericNew, /* tp_new */ - PyObject_GC_Del, /* tp_free */ + PyVarObject_HEAD_INIT(&PyType_Type, 0) + "list", + sizeof(PyListObject), + 0, + (destructor)list_dealloc, /* tp_dealloc */ + 0, /* tp_print */ + 0, /* tp_getattr */ + 0, /* tp_setattr */ + 0, /* tp_reserved */ + (reprfunc)list_repr, /* tp_repr */ + 0, /* tp_as_number */ + &list_as_sequence, /* tp_as_sequence */ + &list_as_mapping, /* tp_as_mapping */ + (hashfunc)PyObject_HashNotImplemented, /* 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 | + Py_TPFLAGS_BASETYPE | Py_TPFLAGS_LIST_SUBCLASS, /* tp_flags */ + list_doc, /* tp_doc */ + (traverseproc)list_traverse, /* tp_traverse */ + (inquiry)list_clear, /* tp_clear */ + list_richcompare, /* tp_richcompare */ + 0, /* tp_weaklistoffset */ + list_iter, /* tp_iter */ + 0, /* tp_iternext */ + list_methods, /* tp_methods */ + 0, /* tp_members */ + 0, /* tp_getset */ + 0, /* tp_base */ + 0, /* tp_dict */ + 0, /* tp_descr_get */ + 0, /* tp_descr_set */ + 0, /* tp_dictoffset */ + (initproc)list_init, /* tp_init */ + PyType_GenericAlloc, /* tp_alloc */ + PyType_GenericNew, /* tp_new */ + PyObject_GC_Del, /* tp_free */ }; /*********************** List Iterator **************************/ typedef struct { - PyObject_HEAD - long it_index; - PyListObject *it_seq; /* Set to NULL when iterator is exhausted */ + PyObject_HEAD + long it_index; + PyListObject *it_seq; /* Set to NULL when iterator is exhausted */ } listiterobject; static PyObject *list_iter(PyObject *); @@ -2629,119 +2629,119 @@ PyDoc_STRVAR(length_hint_doc, "Private method returning an estimate of len(list(it))."); static PyMethodDef listiter_methods[] = { - {"__length_hint__", (PyCFunction)listiter_len, METH_NOARGS, length_hint_doc}, - {NULL, NULL} /* sentinel */ + {"__length_hint__", (PyCFunction)listiter_len, METH_NOARGS, length_hint_doc}, + {NULL, NULL} /* sentinel */ }; PyTypeObject PyListIter_Type = { - PyVarObject_HEAD_INIT(&PyType_Type, 0) - "list_iterator", /* tp_name */ - sizeof(listiterobject), /* tp_basicsize */ - 0, /* tp_itemsize */ - /* methods */ - (destructor)listiter_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)listiter_traverse, /* tp_traverse */ - 0, /* tp_clear */ - 0, /* tp_richcompare */ - 0, /* tp_weaklistoffset */ - PyObject_SelfIter, /* tp_iter */ - (iternextfunc)listiter_next, /* tp_iternext */ - listiter_methods, /* tp_methods */ - 0, /* tp_members */ + PyVarObject_HEAD_INIT(&PyType_Type, 0) + "list_iterator", /* tp_name */ + sizeof(listiterobject), /* tp_basicsize */ + 0, /* tp_itemsize */ + /* methods */ + (destructor)listiter_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)listiter_traverse, /* tp_traverse */ + 0, /* tp_clear */ + 0, /* tp_richcompare */ + 0, /* tp_weaklistoffset */ + PyObject_SelfIter, /* tp_iter */ + (iternextfunc)listiter_next, /* tp_iternext */ + listiter_methods, /* tp_methods */ + 0, /* tp_members */ }; static PyObject * list_iter(PyObject *seq) { - listiterobject *it; + listiterobject *it; - if (!PyList_Check(seq)) { - PyErr_BadInternalCall(); - return NULL; - } - it = PyObject_GC_New(listiterobject, &PyListIter_Type); - if (it == NULL) - return NULL; - it->it_index = 0; - Py_INCREF(seq); - it->it_seq = (PyListObject *)seq; - _PyObject_GC_TRACK(it); - return (PyObject *)it; + if (!PyList_Check(seq)) { + PyErr_BadInternalCall(); + return NULL; + } + it = PyObject_GC_New(listiterobject, &PyListIter_Type); + if (it == NULL) + return NULL; + it->it_index = 0; + Py_INCREF(seq); + it->it_seq = (PyListObject *)seq; + _PyObject_GC_TRACK(it); + return (PyObject *)it; } static void listiter_dealloc(listiterobject *it) { - _PyObject_GC_UNTRACK(it); - Py_XDECREF(it->it_seq); - PyObject_GC_Del(it); + _PyObject_GC_UNTRACK(it); + Py_XDECREF(it->it_seq); + PyObject_GC_Del(it); } static int listiter_traverse(listiterobject *it, visitproc visit, void *arg) { - Py_VISIT(it->it_seq); - return 0; + Py_VISIT(it->it_seq); + return 0; } static PyObject * listiter_next(listiterobject *it) { - PyListObject *seq; - PyObject *item; + PyListObject *seq; + PyObject *item; - assert(it != NULL); - seq = it->it_seq; - if (seq == NULL) - return NULL; - assert(PyList_Check(seq)); - - if (it->it_index < PyList_GET_SIZE(seq)) { - item = PyList_GET_ITEM(seq, it->it_index); - ++it->it_index; - Py_INCREF(item); - return item; - } - - Py_DECREF(seq); - it->it_seq = NULL; - return NULL; + assert(it != NULL); + seq = it->it_seq; + if (seq == NULL) + return NULL; + assert(PyList_Check(seq)); + + if (it->it_index < PyList_GET_SIZE(seq)) { + item = PyList_GET_ITEM(seq, it->it_index); + ++it->it_index; + Py_INCREF(item); + return item; + } + + Py_DECREF(seq); + it->it_seq = NULL; + return NULL; } static PyObject * listiter_len(listiterobject *it) { - Py_ssize_t len; - if (it->it_seq) { - len = PyList_GET_SIZE(it->it_seq) - it->it_index; - if (len >= 0) - return PyLong_FromSsize_t(len); - } - return PyLong_FromLong(0); + Py_ssize_t len; + if (it->it_seq) { + len = PyList_GET_SIZE(it->it_seq) - it->it_index; + if (len >= 0) + return PyLong_FromSsize_t(len); + } + return PyLong_FromLong(0); } /*********************** List Reverse Iterator **************************/ typedef struct { - PyObject_HEAD - Py_ssize_t it_index; - PyListObject *it_seq; /* Set to NULL when iterator is exhausted */ + PyObject_HEAD + Py_ssize_t it_index; + PyListObject *it_seq; /* Set to NULL when iterator is exhausted */ } listreviterobject; static PyObject *list_reversed(PyListObject *, PyObject *); @@ -2751,101 +2751,101 @@ static PyObject *listreviter_len(listreviterobject *); static PyMethodDef listreviter_methods[] = { - {"__length_hint__", (PyCFunction)listreviter_len, METH_NOARGS, length_hint_doc}, - {NULL, NULL} /* sentinel */ + {"__length_hint__", (PyCFunction)listreviter_len, METH_NOARGS, length_hint_doc}, + {NULL, NULL} /* sentinel */ }; PyTypeObject PyListRevIter_Type = { - PyVarObject_HEAD_INIT(&PyType_Type, 0) - "list_reverseiterator", /* tp_name */ - sizeof(listreviterobject), /* tp_basicsize */ - 0, /* tp_itemsize */ - /* methods */ - (destructor)listreviter_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)listreviter_traverse, /* tp_traverse */ - 0, /* tp_clear */ - 0, /* tp_richcompare */ - 0, /* tp_weaklistoffset */ - PyObject_SelfIter, /* tp_iter */ - (iternextfunc)listreviter_next, /* tp_iternext */ - listreviter_methods, /* tp_methods */ - 0, + PyVarObject_HEAD_INIT(&PyType_Type, 0) + "list_reverseiterator", /* tp_name */ + sizeof(listreviterobject), /* tp_basicsize */ + 0, /* tp_itemsize */ + /* methods */ + (destructor)listreviter_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)listreviter_traverse, /* tp_traverse */ + 0, /* tp_clear */ + 0, /* tp_richcompare */ + 0, /* tp_weaklistoffset */ + PyObject_SelfIter, /* tp_iter */ + (iternextfunc)listreviter_next, /* tp_iternext */ + listreviter_methods, /* tp_methods */ + 0, }; static PyObject * list_reversed(PyListObject *seq, PyObject *unused) { - listreviterobject *it; + listreviterobject *it; - it = PyObject_GC_New(listreviterobject, &PyListRevIter_Type); - if (it == NULL) - return NULL; - assert(PyList_Check(seq)); - it->it_index = PyList_GET_SIZE(seq) - 1; - Py_INCREF(seq); - it->it_seq = seq; - PyObject_GC_Track(it); - return (PyObject *)it; + it = PyObject_GC_New(listreviterobject, &PyListRevIter_Type); + if (it == NULL) + return NULL; + assert(PyList_Check(seq)); + it->it_index = PyList_GET_SIZE(seq) - 1; + Py_INCREF(seq); + it->it_seq = seq; + PyObject_GC_Track(it); + return (PyObject *)it; } static void listreviter_dealloc(listreviterobject *it) { - PyObject_GC_UnTrack(it); - Py_XDECREF(it->it_seq); - PyObject_GC_Del(it); + PyObject_GC_UnTrack(it); + Py_XDECREF(it->it_seq); + PyObject_GC_Del(it); } static int listreviter_traverse(listreviterobject *it, visitproc visit, void *arg) { - Py_VISIT(it->it_seq); - return 0; + Py_VISIT(it->it_seq); + return 0; } static PyObject * listreviter_next(listreviterobject *it) { - PyObject *item; - Py_ssize_t index = it->it_index; - PyListObject *seq = it->it_seq; - - if (index>=0 && index < PyList_GET_SIZE(seq)) { - item = PyList_GET_ITEM(seq, index); - it->it_index--; - Py_INCREF(item); - return item; - } - it->it_index = -1; - if (seq != NULL) { - it->it_seq = NULL; - Py_DECREF(seq); - } - return NULL; + PyObject *item; + Py_ssize_t index = it->it_index; + PyListObject *seq = it->it_seq; + + if (index>=0 && index < PyList_GET_SIZE(seq)) { + item = PyList_GET_ITEM(seq, index); + it->it_index--; + Py_INCREF(item); + return item; + } + it->it_index = -1; + if (seq != NULL) { + it->it_seq = NULL; + Py_DECREF(seq); + } + return NULL; } static PyObject * listreviter_len(listreviterobject *it) { - Py_ssize_t len = it->it_index + 1; - if (it->it_seq == NULL || PyList_GET_SIZE(it->it_seq) < len) - len = 0; - return PyLong_FromSsize_t(len); + Py_ssize_t len = it->it_index + 1; + if (it->it_seq == NULL || PyList_GET_SIZE(it->it_seq) < len) + len = 0; + return PyLong_FromSsize_t(len); } Modified: python/branches/release31-maint/Objects/longobject.c ============================================================================== --- python/branches/release31-maint/Objects/longobject.c (original) +++ python/branches/release31-maint/Objects/longobject.c Sun May 9 18:14:21 2010 @@ -11,16 +11,16 @@ #include #ifndef NSMALLPOSINTS -#define NSMALLPOSINTS 257 +#define NSMALLPOSINTS 257 #endif #ifndef NSMALLNEGINTS -#define NSMALLNEGINTS 5 +#define NSMALLNEGINTS 5 #endif /* convert a PyLong of size 1, 0 or -1 to an sdigit */ -#define MEDIUM_VALUE(x) (Py_SIZE(x) < 0 ? -(sdigit)(x)->ob_digit[0] : \ - (Py_SIZE(x) == 0 ? (sdigit)0 : \ - (sdigit)(x)->ob_digit[0])) +#define MEDIUM_VALUE(x) (Py_SIZE(x) < 0 ? -(sdigit)(x)->ob_digit[0] : \ + (Py_SIZE(x) == 0 ? (sdigit)0 : \ + (sdigit)(x)->ob_digit[0])) #define ABS(x) ((x) < 0 ? -(x) : (x)) #if NSMALLNEGINTS + NSMALLPOSINTS > 0 @@ -37,32 +37,32 @@ static PyObject * get_small_int(sdigit ival) { - PyObject *v = (PyObject*)(small_ints + ival + NSMALLNEGINTS); - Py_INCREF(v); + PyObject *v = (PyObject*)(small_ints + ival + NSMALLNEGINTS); + Py_INCREF(v); #ifdef COUNT_ALLOCS - if (ival >= 0) - quick_int_allocs++; - else - quick_neg_int_allocs++; + if (ival >= 0) + quick_int_allocs++; + else + quick_neg_int_allocs++; #endif - return v; + return v; } #define CHECK_SMALL_INT(ival) \ - do if (-NSMALLNEGINTS <= ival && ival < NSMALLPOSINTS) { \ - return get_small_int((sdigit)ival); \ - } while(0) + do if (-NSMALLNEGINTS <= ival && ival < NSMALLPOSINTS) { \ + return get_small_int((sdigit)ival); \ + } while(0) -static PyLongObject * +static PyLongObject * maybe_small_long(PyLongObject *v) { - if (v && ABS(Py_SIZE(v)) <= 1) { - sdigit ival = MEDIUM_VALUE(v); - if (-NSMALLNEGINTS <= ival && ival < NSMALLPOSINTS) { - Py_DECREF(v); - return (PyLongObject *)get_small_int(ival); - } - } - return v; + if (v && ABS(Py_SIZE(v)) <= 1) { + sdigit ival = MEDIUM_VALUE(v); + if (-NSMALLNEGINTS <= ival && ival < NSMALLPOSINTS) { + Py_DECREF(v); + return (PyLongObject *)get_small_int(ival); + } + } + return v; } #else #define CHECK_SMALL_INT(ival) @@ -72,10 +72,10 @@ /* If a freshly-allocated long is already shared, it must be a small integer, so negating it must go to PyLong_FromLong */ #define NEGATE(x) \ - do if (Py_REFCNT(x) == 1) Py_SIZE(x) = -Py_SIZE(x); \ - else { PyObject* tmp=PyLong_FromLong(-MEDIUM_VALUE(x)); \ - Py_DECREF(x); (x) = (PyLongObject*)tmp; } \ - while(0) + do if (Py_REFCNT(x) == 1) Py_SIZE(x) = -Py_SIZE(x); \ + else { PyObject* tmp=PyLong_FromLong(-MEDIUM_VALUE(x)); \ + Py_DECREF(x); (x) = (PyLongObject*)tmp; } \ + while(0) /* For long multiplication, use the O(N**2) school algorithm unless * both operands contain more than KARATSUBA_CUTOFF digits (this * being an internal Python long digit, in base BASE). @@ -96,10 +96,10 @@ #define MIN(x, y) ((x) > (y) ? (y) : (x)) #define SIGCHECK(PyTryBlock) \ - if (--_Py_Ticker < 0) { \ - _Py_Ticker = _Py_CheckInterval; \ - if (PyErr_CheckSignals()) PyTryBlock \ - } + if (--_Py_Ticker < 0) { \ + _Py_Ticker = _Py_CheckInterval; \ + if (PyErr_CheckSignals()) PyTryBlock \ + } /* forward declaration */ static int bits_in_digit(digit d); @@ -111,68 +111,68 @@ static PyLongObject * long_normalize(register PyLongObject *v) { - Py_ssize_t j = ABS(Py_SIZE(v)); - Py_ssize_t i = j; + Py_ssize_t j = ABS(Py_SIZE(v)); + Py_ssize_t i = j; - while (i > 0 && v->ob_digit[i-1] == 0) - --i; - if (i != j) - Py_SIZE(v) = (Py_SIZE(v) < 0) ? -(i) : i; - return v; + while (i > 0 && v->ob_digit[i-1] == 0) + --i; + if (i != j) + Py_SIZE(v) = (Py_SIZE(v) < 0) ? -(i) : i; + return v; } /* Allocate a new long int object with size digits. Return NULL and set exception if we run out of memory. */ #define MAX_LONG_DIGITS \ - ((PY_SSIZE_T_MAX - offsetof(PyLongObject, ob_digit))/sizeof(digit)) + ((PY_SSIZE_T_MAX - offsetof(PyLongObject, ob_digit))/sizeof(digit)) PyLongObject * _PyLong_New(Py_ssize_t size) { - PyLongObject *result; - /* Number of bytes needed is: offsetof(PyLongObject, ob_digit) + - sizeof(digit)*size. Previous incarnations of this code used - sizeof(PyVarObject) instead of the offsetof, but this risks being - incorrect in the presence of padding between the PyVarObject header - and the digits. */ - if (size > (Py_ssize_t)MAX_LONG_DIGITS) { - PyErr_SetString(PyExc_OverflowError, - "too many digits in integer"); - return NULL; - } - result = PyObject_MALLOC(offsetof(PyLongObject, ob_digit) + - size*sizeof(digit)); - if (!result) { - PyErr_NoMemory(); - return NULL; - } - return (PyLongObject*)PyObject_INIT_VAR(result, &PyLong_Type, size); + PyLongObject *result; + /* Number of bytes needed is: offsetof(PyLongObject, ob_digit) + + sizeof(digit)*size. Previous incarnations of this code used + sizeof(PyVarObject) instead of the offsetof, but this risks being + incorrect in the presence of padding between the PyVarObject header + and the digits. */ + if (size > (Py_ssize_t)MAX_LONG_DIGITS) { + PyErr_SetString(PyExc_OverflowError, + "too many digits in integer"); + return NULL; + } + result = PyObject_MALLOC(offsetof(PyLongObject, ob_digit) + + size*sizeof(digit)); + if (!result) { + PyErr_NoMemory(); + return NULL; + } + return (PyLongObject*)PyObject_INIT_VAR(result, &PyLong_Type, size); } PyObject * _PyLong_Copy(PyLongObject *src) { - PyLongObject *result; - Py_ssize_t i; + PyLongObject *result; + Py_ssize_t i; - assert(src != NULL); - i = Py_SIZE(src); - if (i < 0) - i = -(i); - if (i < 2) { - sdigit ival = src->ob_digit[0]; - if (Py_SIZE(src) < 0) - ival = -ival; - CHECK_SMALL_INT(ival); - } - result = _PyLong_New(i); - if (result != NULL) { - Py_SIZE(result) = Py_SIZE(src); - while (--i >= 0) - result->ob_digit[i] = src->ob_digit[i]; - } - return (PyObject *)result; + assert(src != NULL); + i = Py_SIZE(src); + if (i < 0) + i = -(i); + if (i < 2) { + sdigit ival = src->ob_digit[0]; + if (Py_SIZE(src) < 0) + ival = -ival; + CHECK_SMALL_INT(ival); + } + result = _PyLong_New(i); + if (result != NULL) { + Py_SIZE(result) = Py_SIZE(src); + while (--i >= 0) + result->ob_digit[i] = src->ob_digit[i]; + } + return (PyObject *)result; } /* Create a new long int object from a C long int */ @@ -180,68 +180,68 @@ PyObject * PyLong_FromLong(long ival) { - PyLongObject *v; - unsigned long abs_ival; - unsigned long t; /* unsigned so >> doesn't propagate sign bit */ - int ndigits = 0; - int sign = 1; - - CHECK_SMALL_INT(ival); - - if (ival < 0) { - /* negate: can't write this as abs_ival = -ival since that - invokes undefined behaviour when ival is LONG_MIN */ - abs_ival = 0U-(unsigned long)ival; - sign = -1; - } - else { - abs_ival = (unsigned long)ival; - } - - /* Fast path for single-digit ints */ - if (!(abs_ival >> PyLong_SHIFT)) { - v = _PyLong_New(1); - if (v) { - Py_SIZE(v) = sign; - v->ob_digit[0] = Py_SAFE_DOWNCAST( - abs_ival, unsigned long, digit); - } - return (PyObject*)v; - } + PyLongObject *v; + unsigned long abs_ival; + unsigned long t; /* unsigned so >> doesn't propagate sign bit */ + int ndigits = 0; + int sign = 1; + + CHECK_SMALL_INT(ival); + + if (ival < 0) { + /* negate: can't write this as abs_ival = -ival since that + invokes undefined behaviour when ival is LONG_MIN */ + abs_ival = 0U-(unsigned long)ival; + sign = -1; + } + else { + abs_ival = (unsigned long)ival; + } + + /* Fast path for single-digit ints */ + if (!(abs_ival >> PyLong_SHIFT)) { + v = _PyLong_New(1); + if (v) { + Py_SIZE(v) = sign; + v->ob_digit[0] = Py_SAFE_DOWNCAST( + abs_ival, unsigned long, digit); + } + return (PyObject*)v; + } #if PyLong_SHIFT==15 - /* 2 digits */ - if (!(abs_ival >> 2*PyLong_SHIFT)) { - v = _PyLong_New(2); - if (v) { - Py_SIZE(v) = 2*sign; - v->ob_digit[0] = Py_SAFE_DOWNCAST( - abs_ival & PyLong_MASK, unsigned long, digit); - v->ob_digit[1] = Py_SAFE_DOWNCAST( - abs_ival >> PyLong_SHIFT, unsigned long, digit); - } - return (PyObject*)v; - } + /* 2 digits */ + if (!(abs_ival >> 2*PyLong_SHIFT)) { + v = _PyLong_New(2); + if (v) { + Py_SIZE(v) = 2*sign; + v->ob_digit[0] = Py_SAFE_DOWNCAST( + abs_ival & PyLong_MASK, unsigned long, digit); + v->ob_digit[1] = Py_SAFE_DOWNCAST( + abs_ival >> PyLong_SHIFT, unsigned long, digit); + } + return (PyObject*)v; + } #endif - /* Larger numbers: loop to determine number of digits */ - t = abs_ival; - while (t) { - ++ndigits; - t >>= PyLong_SHIFT; - } - v = _PyLong_New(ndigits); - if (v != NULL) { - digit *p = v->ob_digit; - Py_SIZE(v) = ndigits*sign; - t = abs_ival; - while (t) { - *p++ = Py_SAFE_DOWNCAST( - t & PyLong_MASK, unsigned long, digit); - t >>= PyLong_SHIFT; - } - } - return (PyObject *)v; + /* Larger numbers: loop to determine number of digits */ + t = abs_ival; + while (t) { + ++ndigits; + t >>= PyLong_SHIFT; + } + v = _PyLong_New(ndigits); + if (v != NULL) { + digit *p = v->ob_digit; + Py_SIZE(v) = ndigits*sign; + t = abs_ival; + while (t) { + *p++ = Py_SAFE_DOWNCAST( + t & PyLong_MASK, unsigned long, digit); + t >>= PyLong_SHIFT; + } + } + return (PyObject *)v; } /* Create a new long int object from a C unsigned long int */ @@ -249,28 +249,28 @@ PyObject * PyLong_FromUnsignedLong(unsigned long ival) { - PyLongObject *v; - unsigned long t; - int ndigits = 0; - - if (ival < PyLong_BASE) - return PyLong_FromLong(ival); - /* Count the number of Python digits. */ - t = (unsigned long)ival; - while (t) { - ++ndigits; - t >>= PyLong_SHIFT; - } - v = _PyLong_New(ndigits); - if (v != NULL) { - digit *p = v->ob_digit; - Py_SIZE(v) = ndigits; - while (ival) { - *p++ = (digit)(ival & PyLong_MASK); - ival >>= PyLong_SHIFT; - } - } - return (PyObject *)v; + PyLongObject *v; + unsigned long t; + int ndigits = 0; + + if (ival < PyLong_BASE) + return PyLong_FromLong(ival); + /* Count the number of Python digits. */ + t = (unsigned long)ival; + while (t) { + ++ndigits; + t >>= PyLong_SHIFT; + } + v = _PyLong_New(ndigits); + if (v != NULL) { + digit *p = v->ob_digit; + Py_SIZE(v) = ndigits; + while (ival) { + *p++ = (digit)(ival & PyLong_MASK); + ival >>= PyLong_SHIFT; + } + } + return (PyObject *)v; } /* Create a new long int object from a C double */ @@ -278,41 +278,41 @@ PyObject * PyLong_FromDouble(double dval) { - PyLongObject *v; - double frac; - int i, ndig, expo, neg; - neg = 0; - if (Py_IS_INFINITY(dval)) { - PyErr_SetString(PyExc_OverflowError, - "cannot convert float infinity to integer"); - return NULL; - } - if (Py_IS_NAN(dval)) { - PyErr_SetString(PyExc_ValueError, - "cannot convert float NaN to integer"); - return NULL; - } - if (dval < 0.0) { - neg = 1; - dval = -dval; - } - frac = frexp(dval, &expo); /* dval = frac*2**expo; 0.0 <= frac < 1.0 */ - if (expo <= 0) - return PyLong_FromLong(0L); - ndig = (expo-1) / PyLong_SHIFT + 1; /* Number of 'digits' in result */ - v = _PyLong_New(ndig); - if (v == NULL) - return NULL; - frac = ldexp(frac, (expo-1) % PyLong_SHIFT + 1); - for (i = ndig; --i >= 0; ) { - digit bits = (digit)frac; - v->ob_digit[i] = bits; - frac = frac - (double)bits; - frac = ldexp(frac, PyLong_SHIFT); - } - if (neg) - Py_SIZE(v) = -(Py_SIZE(v)); - return (PyObject *)v; + PyLongObject *v; + double frac; + int i, ndig, expo, neg; + neg = 0; + if (Py_IS_INFINITY(dval)) { + PyErr_SetString(PyExc_OverflowError, + "cannot convert float infinity to integer"); + return NULL; + } + if (Py_IS_NAN(dval)) { + PyErr_SetString(PyExc_ValueError, + "cannot convert float NaN to integer"); + return NULL; + } + if (dval < 0.0) { + neg = 1; + dval = -dval; + } + frac = frexp(dval, &expo); /* dval = frac*2**expo; 0.0 <= frac < 1.0 */ + if (expo <= 0) + return PyLong_FromLong(0L); + ndig = (expo-1) / PyLong_SHIFT + 1; /* Number of 'digits' in result */ + v = _PyLong_New(ndig); + if (v == NULL) + return NULL; + frac = ldexp(frac, (expo-1) % PyLong_SHIFT + 1); + for (i = ndig; --i >= 0; ) { + digit bits = (digit)frac; + v->ob_digit[i] = bits; + frac = frac - (double)bits; + frac = ldexp(frac, PyLong_SHIFT); + } + if (neg) + Py_SIZE(v) = -(Py_SIZE(v)); + return (PyObject *)v; } /* Checking for overflow in PyLong_AsLong is a PITA since C doesn't define @@ -324,8 +324,8 @@ * However, some other compilers warn about applying unary minus to an * unsigned operand. Hence the weird "0-". */ -#define PY_ABS_LONG_MIN (0-(unsigned long)LONG_MIN) -#define PY_ABS_SSIZE_T_MIN (0-(size_t)PY_SSIZE_T_MIN) +#define PY_ABS_LONG_MIN (0-(unsigned long)LONG_MIN) +#define PY_ABS_SSIZE_T_MIN (0-(size_t)PY_SSIZE_T_MIN) /* Get a C long int from a long int object. Returns -1 and sets an error condition if overflow occurs. */ @@ -333,101 +333,101 @@ long PyLong_AsLongAndOverflow(PyObject *vv, int *overflow) { - /* This version by Tim Peters */ - register PyLongObject *v; - unsigned long x, prev; - long res; - Py_ssize_t i; - int sign; - int do_decref = 0; /* if nb_int was called */ - - *overflow = 0; - if (vv == NULL) { - PyErr_BadInternalCall(); - return -1; - } - - if (!PyLong_Check(vv)) { - PyNumberMethods *nb; - if ((nb = vv->ob_type->tp_as_number) == NULL || - nb->nb_int == NULL) { - PyErr_SetString(PyExc_TypeError, "an integer is required"); - return -1; - } - vv = (*nb->nb_int) (vv); - if (vv == NULL) - return -1; - do_decref = 1; - if (!PyLong_Check(vv)) { - Py_DECREF(vv); - PyErr_SetString(PyExc_TypeError, - "nb_int should return int object"); - return -1; - } - } - - res = -1; - v = (PyLongObject *)vv; - i = Py_SIZE(v); - - switch (i) { - case -1: - res = -(sdigit)v->ob_digit[0]; - break; - case 0: - res = 0; - break; - case 1: - res = v->ob_digit[0]; - break; - default: - sign = 1; - x = 0; - if (i < 0) { - sign = -1; - i = -(i); - } - while (--i >= 0) { - prev = x; - x = (x << PyLong_SHIFT) + v->ob_digit[i]; - if ((x >> PyLong_SHIFT) != prev) { - *overflow = Py_SIZE(v) > 0 ? 1 : -1; - goto exit; - } - } - /* Haven't lost any bits, but casting to long requires extra care - * (see comment above). - */ - if (x <= (unsigned long)LONG_MAX) { - res = (long)x * sign; - } - else if (sign < 0 && x == PY_ABS_LONG_MIN) { - res = LONG_MIN; - } - else { - *overflow = Py_SIZE(v) > 0 ? 1 : -1; - /* res is already set to -1 */ - } - } + /* This version by Tim Peters */ + register PyLongObject *v; + unsigned long x, prev; + long res; + Py_ssize_t i; + int sign; + int do_decref = 0; /* if nb_int was called */ + + *overflow = 0; + if (vv == NULL) { + PyErr_BadInternalCall(); + return -1; + } + + if (!PyLong_Check(vv)) { + PyNumberMethods *nb; + if ((nb = vv->ob_type->tp_as_number) == NULL || + nb->nb_int == NULL) { + PyErr_SetString(PyExc_TypeError, "an integer is required"); + return -1; + } + vv = (*nb->nb_int) (vv); + if (vv == NULL) + return -1; + do_decref = 1; + if (!PyLong_Check(vv)) { + Py_DECREF(vv); + PyErr_SetString(PyExc_TypeError, + "nb_int should return int object"); + return -1; + } + } + + res = -1; + v = (PyLongObject *)vv; + i = Py_SIZE(v); + + switch (i) { + case -1: + res = -(sdigit)v->ob_digit[0]; + break; + case 0: + res = 0; + break; + case 1: + res = v->ob_digit[0]; + break; + default: + sign = 1; + x = 0; + if (i < 0) { + sign = -1; + i = -(i); + } + while (--i >= 0) { + prev = x; + x = (x << PyLong_SHIFT) + v->ob_digit[i]; + if ((x >> PyLong_SHIFT) != prev) { + *overflow = Py_SIZE(v) > 0 ? 1 : -1; + goto exit; + } + } + /* Haven't lost any bits, but casting to long requires extra care + * (see comment above). + */ + if (x <= (unsigned long)LONG_MAX) { + res = (long)x * sign; + } + else if (sign < 0 && x == PY_ABS_LONG_MIN) { + res = LONG_MIN; + } + else { + *overflow = Py_SIZE(v) > 0 ? 1 : -1; + /* res is already set to -1 */ + } + } exit: - if (do_decref) { - Py_DECREF(vv); - } - return res; + if (do_decref) { + Py_DECREF(vv); + } + return res; } -long +long PyLong_AsLong(PyObject *obj) { - int overflow; - long result = PyLong_AsLongAndOverflow(obj, &overflow); - if (overflow) { - /* XXX: could be cute and give a different - message for overflow == -1 */ - PyErr_SetString(PyExc_OverflowError, - "Python int too large to convert to C long"); - } - return result; + int overflow; + long result = PyLong_AsLongAndOverflow(obj, &overflow); + if (overflow) { + /* XXX: could be cute and give a different + message for overflow == -1 */ + PyErr_SetString(PyExc_OverflowError, + "Python int too large to convert to C long"); + } + return result; } /* Get a Py_ssize_t from a long int object. @@ -435,54 +435,54 @@ Py_ssize_t PyLong_AsSsize_t(PyObject *vv) { - register PyLongObject *v; - size_t x, prev; - Py_ssize_t i; - int sign; - - if (vv == NULL) { - PyErr_BadInternalCall(); - return -1; - } - if (!PyLong_Check(vv)) { - PyErr_SetString(PyExc_TypeError, "an integer is required"); - return -1; - } - - v = (PyLongObject *)vv; - i = Py_SIZE(v); - switch (i) { - case -1: return -(sdigit)v->ob_digit[0]; - case 0: return 0; - case 1: return v->ob_digit[0]; - } - sign = 1; - x = 0; - if (i < 0) { - sign = -1; - i = -(i); - } - while (--i >= 0) { - prev = x; - x = (x << PyLong_SHIFT) + v->ob_digit[i]; - if ((x >> PyLong_SHIFT) != prev) - goto overflow; - } - /* Haven't lost any bits, but casting to a signed type requires - * extra care (see comment above). - */ - if (x <= (size_t)PY_SSIZE_T_MAX) { - return (Py_ssize_t)x * sign; - } - else if (sign < 0 && x == PY_ABS_SSIZE_T_MIN) { - return PY_SSIZE_T_MIN; - } - /* else overflow */ + register PyLongObject *v; + size_t x, prev; + Py_ssize_t i; + int sign; + + if (vv == NULL) { + PyErr_BadInternalCall(); + return -1; + } + if (!PyLong_Check(vv)) { + PyErr_SetString(PyExc_TypeError, "an integer is required"); + return -1; + } + + v = (PyLongObject *)vv; + i = Py_SIZE(v); + switch (i) { + case -1: return -(sdigit)v->ob_digit[0]; + case 0: return 0; + case 1: return v->ob_digit[0]; + } + sign = 1; + x = 0; + if (i < 0) { + sign = -1; + i = -(i); + } + while (--i >= 0) { + prev = x; + x = (x << PyLong_SHIFT) + v->ob_digit[i]; + if ((x >> PyLong_SHIFT) != prev) + goto overflow; + } + /* Haven't lost any bits, but casting to a signed type requires + * extra care (see comment above). + */ + if (x <= (size_t)PY_SSIZE_T_MAX) { + return (Py_ssize_t)x * sign; + } + else if (sign < 0 && x == PY_ABS_SSIZE_T_MIN) { + return PY_SSIZE_T_MIN; + } + /* else overflow */ overflow: - PyErr_SetString(PyExc_OverflowError, - "Python int too large to convert to C ssize_t"); - return -1; + PyErr_SetString(PyExc_OverflowError, + "Python int too large to convert to C ssize_t"); + return -1; } /* Get a C unsigned long int from a long int object. @@ -491,41 +491,41 @@ unsigned long PyLong_AsUnsignedLong(PyObject *vv) { - register PyLongObject *v; - unsigned long x, prev; - Py_ssize_t i; - - if (vv == NULL) { - PyErr_BadInternalCall(); - return (unsigned long)-1; - } - if (!PyLong_Check(vv)) { - PyErr_SetString(PyExc_TypeError, "an integer is required"); - return (unsigned long)-1; - } - - v = (PyLongObject *)vv; - i = Py_SIZE(v); - x = 0; - if (i < 0) { - PyErr_SetString(PyExc_OverflowError, - "can't convert negative value to unsigned int"); - return (unsigned long) -1; - } - switch (i) { - case 0: return 0; - case 1: return v->ob_digit[0]; - } - while (--i >= 0) { - prev = x; - x = (x << PyLong_SHIFT) + v->ob_digit[i]; - if ((x >> PyLong_SHIFT) != prev) { - PyErr_SetString(PyExc_OverflowError, - "python int too large to convert to C unsigned long"); - return (unsigned long) -1; - } - } - return x; + register PyLongObject *v; + unsigned long x, prev; + Py_ssize_t i; + + if (vv == NULL) { + PyErr_BadInternalCall(); + return (unsigned long)-1; + } + if (!PyLong_Check(vv)) { + PyErr_SetString(PyExc_TypeError, "an integer is required"); + return (unsigned long)-1; + } + + v = (PyLongObject *)vv; + i = Py_SIZE(v); + x = 0; + if (i < 0) { + PyErr_SetString(PyExc_OverflowError, + "can't convert negative value to unsigned int"); + return (unsigned long) -1; + } + switch (i) { + case 0: return 0; + case 1: return v->ob_digit[0]; + } + while (--i >= 0) { + prev = x; + x = (x << PyLong_SHIFT) + v->ob_digit[i]; + if ((x >> PyLong_SHIFT) != prev) { + PyErr_SetString(PyExc_OverflowError, + "python int too large to convert to C unsigned long"); + return (unsigned long) -1; + } + } + return x; } /* Get a C unsigned long int from a long int object. @@ -534,41 +534,41 @@ size_t PyLong_AsSize_t(PyObject *vv) { - register PyLongObject *v; - size_t x, prev; - Py_ssize_t i; - - if (vv == NULL) { - PyErr_BadInternalCall(); - return (size_t) -1; - } - if (!PyLong_Check(vv)) { - PyErr_SetString(PyExc_TypeError, "an integer is required"); - return (size_t)-1; - } - - v = (PyLongObject *)vv; - i = Py_SIZE(v); - x = 0; - if (i < 0) { - PyErr_SetString(PyExc_OverflowError, - "can't convert negative value to size_t"); - return (size_t) -1; - } - switch (i) { - case 0: return 0; - case 1: return v->ob_digit[0]; - } - while (--i >= 0) { - prev = x; - x = (x << PyLong_SHIFT) + v->ob_digit[i]; - if ((x >> PyLong_SHIFT) != prev) { - PyErr_SetString(PyExc_OverflowError, - "Python int too large to convert to C size_t"); - return (unsigned long) -1; - } - } - return x; + register PyLongObject *v; + size_t x, prev; + Py_ssize_t i; + + if (vv == NULL) { + PyErr_BadInternalCall(); + return (size_t) -1; + } + if (!PyLong_Check(vv)) { + PyErr_SetString(PyExc_TypeError, "an integer is required"); + return (size_t)-1; + } + + v = (PyLongObject *)vv; + i = Py_SIZE(v); + x = 0; + if (i < 0) { + PyErr_SetString(PyExc_OverflowError, + "can't convert negative value to size_t"); + return (size_t) -1; + } + switch (i) { + case 0: return 0; + case 1: return v->ob_digit[0]; + } + while (--i >= 0) { + prev = x; + x = (x << PyLong_SHIFT) + v->ob_digit[i]; + if ((x >> PyLong_SHIFT) != prev) { + PyErr_SetString(PyExc_OverflowError, + "Python int too large to convert to C size_t"); + return (unsigned long) -1; + } + } + return x; } /* Get a C unsigned long int from a long int object, ignoring the high bits. @@ -577,354 +577,354 @@ static unsigned long _PyLong_AsUnsignedLongMask(PyObject *vv) { - register PyLongObject *v; - unsigned long x; - Py_ssize_t i; - int sign; - - if (vv == NULL || !PyLong_Check(vv)) { - PyErr_BadInternalCall(); - return (unsigned long) -1; - } - v = (PyLongObject *)vv; - i = Py_SIZE(v); - switch (i) { - case 0: return 0; - case 1: return v->ob_digit[0]; - } - sign = 1; - x = 0; - if (i < 0) { - sign = -1; - i = -i; - } - while (--i >= 0) { - x = (x << PyLong_SHIFT) + v->ob_digit[i]; - } - return x * sign; + register PyLongObject *v; + unsigned long x; + Py_ssize_t i; + int sign; + + if (vv == NULL || !PyLong_Check(vv)) { + PyErr_BadInternalCall(); + return (unsigned long) -1; + } + v = (PyLongObject *)vv; + i = Py_SIZE(v); + switch (i) { + case 0: return 0; + case 1: return v->ob_digit[0]; + } + sign = 1; + x = 0; + if (i < 0) { + sign = -1; + i = -i; + } + while (--i >= 0) { + x = (x << PyLong_SHIFT) + v->ob_digit[i]; + } + return x * sign; } unsigned long PyLong_AsUnsignedLongMask(register PyObject *op) { - PyNumberMethods *nb; - PyLongObject *lo; - unsigned long val; - - if (op && PyLong_Check(op)) - return _PyLong_AsUnsignedLongMask(op); - - if (op == NULL || (nb = op->ob_type->tp_as_number) == NULL || - nb->nb_int == NULL) { - PyErr_SetString(PyExc_TypeError, "an integer is required"); - return (unsigned long)-1; - } - - lo = (PyLongObject*) (*nb->nb_int) (op); - if (lo == NULL) - return (unsigned long)-1; - if (PyLong_Check(lo)) { - val = _PyLong_AsUnsignedLongMask((PyObject *)lo); - Py_DECREF(lo); - if (PyErr_Occurred()) - return (unsigned long)-1; - return val; - } - else - { - Py_DECREF(lo); - PyErr_SetString(PyExc_TypeError, - "nb_int should return int object"); - return (unsigned long)-1; - } + PyNumberMethods *nb; + PyLongObject *lo; + unsigned long val; + + if (op && PyLong_Check(op)) + return _PyLong_AsUnsignedLongMask(op); + + if (op == NULL || (nb = op->ob_type->tp_as_number) == NULL || + nb->nb_int == NULL) { + PyErr_SetString(PyExc_TypeError, "an integer is required"); + return (unsigned long)-1; + } + + lo = (PyLongObject*) (*nb->nb_int) (op); + if (lo == NULL) + return (unsigned long)-1; + if (PyLong_Check(lo)) { + val = _PyLong_AsUnsignedLongMask((PyObject *)lo); + Py_DECREF(lo); + if (PyErr_Occurred()) + return (unsigned long)-1; + return val; + } + else + { + Py_DECREF(lo); + PyErr_SetString(PyExc_TypeError, + "nb_int should return int object"); + return (unsigned long)-1; + } } int _PyLong_Sign(PyObject *vv) { - PyLongObject *v = (PyLongObject *)vv; + PyLongObject *v = (PyLongObject *)vv; - assert(v != NULL); - assert(PyLong_Check(v)); + assert(v != NULL); + assert(PyLong_Check(v)); - return Py_SIZE(v) == 0 ? 0 : (Py_SIZE(v) < 0 ? -1 : 1); + return Py_SIZE(v) == 0 ? 0 : (Py_SIZE(v) < 0 ? -1 : 1); } size_t _PyLong_NumBits(PyObject *vv) { - PyLongObject *v = (PyLongObject *)vv; - size_t result = 0; - Py_ssize_t ndigits; - - assert(v != NULL); - assert(PyLong_Check(v)); - ndigits = ABS(Py_SIZE(v)); - assert(ndigits == 0 || v->ob_digit[ndigits - 1] != 0); - if (ndigits > 0) { - digit msd = v->ob_digit[ndigits - 1]; - - result = (ndigits - 1) * PyLong_SHIFT; - if (result / PyLong_SHIFT != (size_t)(ndigits - 1)) - goto Overflow; - do { - ++result; - if (result == 0) - goto Overflow; - msd >>= 1; - } while (msd); - } - return result; + PyLongObject *v = (PyLongObject *)vv; + size_t result = 0; + Py_ssize_t ndigits; + + assert(v != NULL); + assert(PyLong_Check(v)); + ndigits = ABS(Py_SIZE(v)); + assert(ndigits == 0 || v->ob_digit[ndigits - 1] != 0); + if (ndigits > 0) { + digit msd = v->ob_digit[ndigits - 1]; + + result = (ndigits - 1) * PyLong_SHIFT; + if (result / PyLong_SHIFT != (size_t)(ndigits - 1)) + goto Overflow; + do { + ++result; + if (result == 0) + goto Overflow; + msd >>= 1; + } while (msd); + } + return result; Overflow: - PyErr_SetString(PyExc_OverflowError, "int has too many bits " - "to express in a platform size_t"); - return (size_t)-1; + PyErr_SetString(PyExc_OverflowError, "int has too many bits " + "to express in a platform size_t"); + return (size_t)-1; } PyObject * _PyLong_FromByteArray(const unsigned char* bytes, size_t n, - int little_endian, int is_signed) + int little_endian, int is_signed) { - const unsigned char* pstartbyte;/* LSB of bytes */ - int incr; /* direction to move pstartbyte */ - const unsigned char* pendbyte; /* MSB of bytes */ - size_t numsignificantbytes; /* number of bytes that matter */ - Py_ssize_t ndigits; /* number of Python long digits */ - PyLongObject* v; /* result */ - Py_ssize_t idigit = 0; /* next free index in v->ob_digit */ - - if (n == 0) - return PyLong_FromLong(0L); - - if (little_endian) { - pstartbyte = bytes; - pendbyte = bytes + n - 1; - incr = 1; - } - else { - pstartbyte = bytes + n - 1; - pendbyte = bytes; - incr = -1; - } - - if (is_signed) - is_signed = *pendbyte >= 0x80; - - /* Compute numsignificantbytes. This consists of finding the most - significant byte. Leading 0 bytes are insignficant if the number - is positive, and leading 0xff bytes if negative. */ - { - size_t i; - const unsigned char* p = pendbyte; - const int pincr = -incr; /* search MSB to LSB */ - const unsigned char insignficant = is_signed ? 0xff : 0x00; - - for (i = 0; i < n; ++i, p += pincr) { - if (*p != insignficant) - break; - } - numsignificantbytes = n - i; - /* 2's-comp is a bit tricky here, e.g. 0xff00 == -0x0100, so - actually has 2 significant bytes. OTOH, 0xff0001 == - -0x00ffff, so we wouldn't *need* to bump it there; but we - do for 0xffff = -0x0001. To be safe without bothering to - check every case, bump it regardless. */ - if (is_signed && numsignificantbytes < n) - ++numsignificantbytes; - } - - /* How many Python long digits do we need? We have - 8*numsignificantbytes bits, and each Python long digit has - PyLong_SHIFT bits, so it's the ceiling of the quotient. */ - /* catch overflow before it happens */ - if (numsignificantbytes > (PY_SSIZE_T_MAX - PyLong_SHIFT) / 8) { - PyErr_SetString(PyExc_OverflowError, - "byte array too long to convert to int"); - return NULL; - } - ndigits = (numsignificantbytes * 8 + PyLong_SHIFT - 1) / PyLong_SHIFT; - v = _PyLong_New(ndigits); - if (v == NULL) - return NULL; - - /* Copy the bits over. The tricky parts are computing 2's-comp on - the fly for signed numbers, and dealing with the mismatch between - 8-bit bytes and (probably) 15-bit Python digits.*/ - { - size_t i; - twodigits carry = 1; /* for 2's-comp calculation */ - twodigits accum = 0; /* sliding register */ - unsigned int accumbits = 0; /* number of bits in accum */ - const unsigned char* p = pstartbyte; - - for (i = 0; i < numsignificantbytes; ++i, p += incr) { - twodigits thisbyte = *p; - /* Compute correction for 2's comp, if needed. */ - if (is_signed) { - thisbyte = (0xff ^ thisbyte) + carry; - carry = thisbyte >> 8; - thisbyte &= 0xff; - } - /* Because we're going LSB to MSB, thisbyte is - more significant than what's already in accum, - so needs to be prepended to accum. */ - accum |= (twodigits)thisbyte << accumbits; - accumbits += 8; - if (accumbits >= PyLong_SHIFT) { - /* There's enough to fill a Python digit. */ - assert(idigit < ndigits); - v->ob_digit[idigit] = (digit)(accum & - PyLong_MASK); - ++idigit; - accum >>= PyLong_SHIFT; - accumbits -= PyLong_SHIFT; - assert(accumbits < PyLong_SHIFT); - } - } - assert(accumbits < PyLong_SHIFT); - if (accumbits) { - assert(idigit < ndigits); - v->ob_digit[idigit] = (digit)accum; - ++idigit; - } - } + const unsigned char* pstartbyte;/* LSB of bytes */ + int incr; /* direction to move pstartbyte */ + const unsigned char* pendbyte; /* MSB of bytes */ + size_t numsignificantbytes; /* number of bytes that matter */ + Py_ssize_t ndigits; /* number of Python long digits */ + PyLongObject* v; /* result */ + Py_ssize_t idigit = 0; /* next free index in v->ob_digit */ + + if (n == 0) + return PyLong_FromLong(0L); + + if (little_endian) { + pstartbyte = bytes; + pendbyte = bytes + n - 1; + incr = 1; + } + else { + pstartbyte = bytes + n - 1; + pendbyte = bytes; + incr = -1; + } + + if (is_signed) + is_signed = *pendbyte >= 0x80; + + /* Compute numsignificantbytes. This consists of finding the most + significant byte. Leading 0 bytes are insignficant if the number + is positive, and leading 0xff bytes if negative. */ + { + size_t i; + const unsigned char* p = pendbyte; + const int pincr = -incr; /* search MSB to LSB */ + const unsigned char insignficant = is_signed ? 0xff : 0x00; + + for (i = 0; i < n; ++i, p += pincr) { + if (*p != insignficant) + break; + } + numsignificantbytes = n - i; + /* 2's-comp is a bit tricky here, e.g. 0xff00 == -0x0100, so + actually has 2 significant bytes. OTOH, 0xff0001 == + -0x00ffff, so we wouldn't *need* to bump it there; but we + do for 0xffff = -0x0001. To be safe without bothering to + check every case, bump it regardless. */ + if (is_signed && numsignificantbytes < n) + ++numsignificantbytes; + } + + /* How many Python long digits do we need? We have + 8*numsignificantbytes bits, and each Python long digit has + PyLong_SHIFT bits, so it's the ceiling of the quotient. */ + /* catch overflow before it happens */ + if (numsignificantbytes > (PY_SSIZE_T_MAX - PyLong_SHIFT) / 8) { + PyErr_SetString(PyExc_OverflowError, + "byte array too long to convert to int"); + return NULL; + } + ndigits = (numsignificantbytes * 8 + PyLong_SHIFT - 1) / PyLong_SHIFT; + v = _PyLong_New(ndigits); + if (v == NULL) + return NULL; + + /* Copy the bits over. The tricky parts are computing 2's-comp on + the fly for signed numbers, and dealing with the mismatch between + 8-bit bytes and (probably) 15-bit Python digits.*/ + { + size_t i; + twodigits carry = 1; /* for 2's-comp calculation */ + twodigits accum = 0; /* sliding register */ + unsigned int accumbits = 0; /* number of bits in accum */ + const unsigned char* p = pstartbyte; + + for (i = 0; i < numsignificantbytes; ++i, p += incr) { + twodigits thisbyte = *p; + /* Compute correction for 2's comp, if needed. */ + if (is_signed) { + thisbyte = (0xff ^ thisbyte) + carry; + carry = thisbyte >> 8; + thisbyte &= 0xff; + } + /* Because we're going LSB to MSB, thisbyte is + more significant than what's already in accum, + so needs to be prepended to accum. */ + accum |= (twodigits)thisbyte << accumbits; + accumbits += 8; + if (accumbits >= PyLong_SHIFT) { + /* There's enough to fill a Python digit. */ + assert(idigit < ndigits); + v->ob_digit[idigit] = (digit)(accum & + PyLong_MASK); + ++idigit; + accum >>= PyLong_SHIFT; + accumbits -= PyLong_SHIFT; + assert(accumbits < PyLong_SHIFT); + } + } + assert(accumbits < PyLong_SHIFT); + if (accumbits) { + assert(idigit < ndigits); + v->ob_digit[idigit] = (digit)accum; + ++idigit; + } + } - Py_SIZE(v) = is_signed ? -idigit : idigit; - return (PyObject *)long_normalize(v); + Py_SIZE(v) = is_signed ? -idigit : idigit; + return (PyObject *)long_normalize(v); } int _PyLong_AsByteArray(PyLongObject* v, - unsigned char* bytes, size_t n, - int little_endian, int is_signed) + unsigned char* bytes, size_t n, + int little_endian, int is_signed) { - Py_ssize_t i; /* index into v->ob_digit */ - Py_ssize_t ndigits; /* |v->ob_size| */ - twodigits accum; /* sliding register */ - unsigned int accumbits; /* # bits in accum */ - int do_twos_comp; /* store 2's-comp? is_signed and v < 0 */ - digit carry; /* for computing 2's-comp */ - size_t j; /* # bytes filled */ - unsigned char* p; /* pointer to next byte in bytes */ - int pincr; /* direction to move p */ - - assert(v != NULL && PyLong_Check(v)); - - if (Py_SIZE(v) < 0) { - ndigits = -(Py_SIZE(v)); - if (!is_signed) { - PyErr_SetString(PyExc_OverflowError, - "can't convert negative int to unsigned"); - return -1; - } - do_twos_comp = 1; - } - else { - ndigits = Py_SIZE(v); - do_twos_comp = 0; - } - - if (little_endian) { - p = bytes; - pincr = 1; - } - else { - p = bytes + n - 1; - pincr = -1; - } - - /* Copy over all the Python digits. - It's crucial that every Python digit except for the MSD contribute - exactly PyLong_SHIFT bits to the total, so first assert that the long is - normalized. */ - assert(ndigits == 0 || v->ob_digit[ndigits - 1] != 0); - j = 0; - accum = 0; - accumbits = 0; - carry = do_twos_comp ? 1 : 0; - for (i = 0; i < ndigits; ++i) { - digit thisdigit = v->ob_digit[i]; - if (do_twos_comp) { - thisdigit = (thisdigit ^ PyLong_MASK) + carry; - carry = thisdigit >> PyLong_SHIFT; - thisdigit &= PyLong_MASK; - } - /* Because we're going LSB to MSB, thisdigit is more - significant than what's already in accum, so needs to be - prepended to accum. */ - accum |= (twodigits)thisdigit << accumbits; - - /* The most-significant digit may be (probably is) at least - partly empty. */ - if (i == ndigits - 1) { - /* Count # of sign bits -- they needn't be stored, - * although for signed conversion we need later to - * make sure at least one sign bit gets stored. */ - digit s = do_twos_comp ? thisdigit ^ PyLong_MASK : - thisdigit; - while (s != 0) { - s >>= 1; - accumbits++; - } - } - else - accumbits += PyLong_SHIFT; - - /* Store as many bytes as possible. */ - while (accumbits >= 8) { - if (j >= n) - goto Overflow; - ++j; - *p = (unsigned char)(accum & 0xff); - p += pincr; - accumbits -= 8; - accum >>= 8; - } - } - - /* Store the straggler (if any). */ - assert(accumbits < 8); - assert(carry == 0); /* else do_twos_comp and *every* digit was 0 */ - if (accumbits > 0) { - if (j >= n) - goto Overflow; - ++j; - if (do_twos_comp) { - /* Fill leading bits of the byte with sign bits - (appropriately pretending that the long had an - infinite supply of sign bits). */ - accum |= (~(twodigits)0) << accumbits; - } - *p = (unsigned char)(accum & 0xff); - p += pincr; - } - else if (j == n && n > 0 && is_signed) { - /* The main loop filled the byte array exactly, so the code - just above didn't get to ensure there's a sign bit, and the - loop below wouldn't add one either. Make sure a sign bit - exists. */ - unsigned char msb = *(p - pincr); - int sign_bit_set = msb >= 0x80; - assert(accumbits == 0); - if (sign_bit_set == do_twos_comp) - return 0; - else - goto Overflow; - } - - /* Fill remaining bytes with copies of the sign bit. */ - { - unsigned char signbyte = do_twos_comp ? 0xffU : 0U; - for ( ; j < n; ++j, p += pincr) - *p = signbyte; - } + Py_ssize_t i; /* index into v->ob_digit */ + Py_ssize_t ndigits; /* |v->ob_size| */ + twodigits accum; /* sliding register */ + unsigned int accumbits; /* # bits in accum */ + int do_twos_comp; /* store 2's-comp? is_signed and v < 0 */ + digit carry; /* for computing 2's-comp */ + size_t j; /* # bytes filled */ + unsigned char* p; /* pointer to next byte in bytes */ + int pincr; /* direction to move p */ + + assert(v != NULL && PyLong_Check(v)); + + if (Py_SIZE(v) < 0) { + ndigits = -(Py_SIZE(v)); + if (!is_signed) { + PyErr_SetString(PyExc_OverflowError, + "can't convert negative int to unsigned"); + return -1; + } + do_twos_comp = 1; + } + else { + ndigits = Py_SIZE(v); + do_twos_comp = 0; + } + + if (little_endian) { + p = bytes; + pincr = 1; + } + else { + p = bytes + n - 1; + pincr = -1; + } + + /* Copy over all the Python digits. + It's crucial that every Python digit except for the MSD contribute + exactly PyLong_SHIFT bits to the total, so first assert that the long is + normalized. */ + assert(ndigits == 0 || v->ob_digit[ndigits - 1] != 0); + j = 0; + accum = 0; + accumbits = 0; + carry = do_twos_comp ? 1 : 0; + for (i = 0; i < ndigits; ++i) { + digit thisdigit = v->ob_digit[i]; + if (do_twos_comp) { + thisdigit = (thisdigit ^ PyLong_MASK) + carry; + carry = thisdigit >> PyLong_SHIFT; + thisdigit &= PyLong_MASK; + } + /* Because we're going LSB to MSB, thisdigit is more + significant than what's already in accum, so needs to be + prepended to accum. */ + accum |= (twodigits)thisdigit << accumbits; + + /* The most-significant digit may be (probably is) at least + partly empty. */ + if (i == ndigits - 1) { + /* Count # of sign bits -- they needn't be stored, + * although for signed conversion we need later to + * make sure at least one sign bit gets stored. */ + digit s = do_twos_comp ? thisdigit ^ PyLong_MASK : + thisdigit; + while (s != 0) { + s >>= 1; + accumbits++; + } + } + else + accumbits += PyLong_SHIFT; + + /* Store as many bytes as possible. */ + while (accumbits >= 8) { + if (j >= n) + goto Overflow; + ++j; + *p = (unsigned char)(accum & 0xff); + p += pincr; + accumbits -= 8; + accum >>= 8; + } + } + + /* Store the straggler (if any). */ + assert(accumbits < 8); + assert(carry == 0); /* else do_twos_comp and *every* digit was 0 */ + if (accumbits > 0) { + if (j >= n) + goto Overflow; + ++j; + if (do_twos_comp) { + /* Fill leading bits of the byte with sign bits + (appropriately pretending that the long had an + infinite supply of sign bits). */ + accum |= (~(twodigits)0) << accumbits; + } + *p = (unsigned char)(accum & 0xff); + p += pincr; + } + else if (j == n && n > 0 && is_signed) { + /* The main loop filled the byte array exactly, so the code + just above didn't get to ensure there's a sign bit, and the + loop below wouldn't add one either. Make sure a sign bit + exists. */ + unsigned char msb = *(p - pincr); + int sign_bit_set = msb >= 0x80; + assert(accumbits == 0); + if (sign_bit_set == do_twos_comp) + return 0; + else + goto Overflow; + } + + /* Fill remaining bytes with copies of the sign bit. */ + { + unsigned char signbyte = do_twos_comp ? 0xffU : 0U; + for ( ; j < n; ++j, p += pincr) + *p = signbyte; + } - return 0; + return 0; Overflow: - PyErr_SetString(PyExc_OverflowError, "int too big to convert"); - return -1; + PyErr_SetString(PyExc_OverflowError, "int too big to convert"); + return -1; } @@ -942,42 +942,42 @@ least one round bit to stand in for the ignored least-significant bits. */ #define NBITS_WANTED 57 - PyLongObject *v; - double x; - const double multiplier = (double)(1L << PyLong_SHIFT); - Py_ssize_t i; - int sign; - int nbitsneeded; - - if (vv == NULL || !PyLong_Check(vv)) { - PyErr_BadInternalCall(); - return -1; - } - v = (PyLongObject *)vv; - i = Py_SIZE(v); - sign = 1; - if (i < 0) { - sign = -1; - i = -(i); - } - else if (i == 0) { - *exponent = 0; - return 0.0; - } - --i; - x = (double)v->ob_digit[i]; - nbitsneeded = NBITS_WANTED - 1; - /* Invariant: i Python digits remain unaccounted for. */ - while (i > 0 && nbitsneeded > 0) { - --i; - x = x * multiplier + (double)v->ob_digit[i]; - nbitsneeded -= PyLong_SHIFT; - } - /* There are i digits we didn't shift in. Pretending they're all - zeroes, the true value is x * 2**(i*PyLong_SHIFT). */ - *exponent = i; - assert(x > 0.0); - return x * sign; + PyLongObject *v; + double x; + const double multiplier = (double)(1L << PyLong_SHIFT); + Py_ssize_t i; + int sign; + int nbitsneeded; + + if (vv == NULL || !PyLong_Check(vv)) { + PyErr_BadInternalCall(); + return -1; + } + v = (PyLongObject *)vv; + i = Py_SIZE(v); + sign = 1; + if (i < 0) { + sign = -1; + i = -(i); + } + else if (i == 0) { + *exponent = 0; + return 0.0; + } + --i; + x = (double)v->ob_digit[i]; + nbitsneeded = NBITS_WANTED - 1; + /* Invariant: i Python digits remain unaccounted for. */ + while (i > 0 && nbitsneeded > 0) { + --i; + x = x * multiplier + (double)v->ob_digit[i]; + nbitsneeded -= PyLong_SHIFT; + } + /* There are i digits we didn't shift in. Pretending they're all + zeroes, the true value is x * 2**(i*PyLong_SHIFT). */ + *exponent = i; + assert(x > 0.0); + return x * sign; #undef NBITS_WANTED } @@ -987,163 +987,163 @@ double PyLong_AsDouble(PyObject *vv) { - PyLongObject *v = (PyLongObject *)vv; - Py_ssize_t rnd_digit, rnd_bit, m, n; - digit lsb, *d; - int round_up = 0; - double x; - - if (vv == NULL || !PyLong_Check(vv)) { - PyErr_BadInternalCall(); - return -1.0; - } - - /* Notes on the method: for simplicity, assume v is positive and >= - 2**DBL_MANT_DIG. (For negative v we just ignore the sign until the - end; for small v no rounding is necessary.) Write n for the number - of bits in v, so that 2**(n-1) <= v < 2**n, and n > DBL_MANT_DIG. - - Some terminology: the *rounding bit* of v is the 1st bit of v that - will be rounded away (bit n - DBL_MANT_DIG - 1); the *parity bit* - is the bit immediately above. The round-half-to-even rule says - that we round up if the rounding bit is set, unless v is exactly - halfway between two floats and the parity bit is zero. - - Write d[0] ... d[m] for the digits of v, least to most significant. - Let rnd_bit be the index of the rounding bit, and rnd_digit the - index of the PyLong digit containing the rounding bit. Then the - bits of the digit d[rnd_digit] look something like: - - rounding bit - | - v - msb -> sssssrttttttttt <- lsb - ^ - | - parity bit - - where 's' represents a 'significant bit' that will be included in - the mantissa of the result, 'r' is the rounding bit, and 't' - represents a 'trailing bit' following the rounding bit. Note that - if the rounding bit is at the top of d[rnd_digit] then the parity - bit will be the lsb of d[rnd_digit+1]. If we set - - lsb = 1 << (rnd_bit % PyLong_SHIFT) - - then d[rnd_digit] & (PyLong_BASE - 2*lsb) selects just the - significant bits of d[rnd_digit], d[rnd_digit] & (lsb-1) gets the - trailing bits, and d[rnd_digit] & lsb gives the rounding bit. - - We initialize the double x to the integer given by digits - d[rnd_digit:m-1], but with the rounding bit and trailing bits of - d[rnd_digit] masked out. So the value of x comes from the top - DBL_MANT_DIG bits of v, multiplied by 2*lsb. Note that in the loop - that produces x, all floating-point operations are exact (assuming - that FLT_RADIX==2). Now if we're rounding down, the value we want - to return is simply - - x * 2**(PyLong_SHIFT * rnd_digit). - - and if we're rounding up, it's - - (x + 2*lsb) * 2**(PyLong_SHIFT * rnd_digit). - - Under the round-half-to-even rule, we round up if, and only - if, the rounding bit is set *and* at least one of the - following three conditions is satisfied: - - (1) the parity bit is set, or - (2) at least one of the trailing bits of d[rnd_digit] is set, or - (3) at least one of the digits d[i], 0 <= i < rnd_digit - is nonzero. - - Finally, we have to worry about overflow. If v >= 2**DBL_MAX_EXP, - or equivalently n > DBL_MAX_EXP, then overflow occurs. If v < - 2**DBL_MAX_EXP then we're usually safe, but there's a corner case - to consider: if v is very close to 2**DBL_MAX_EXP then it's - possible that v is rounded up to exactly 2**DBL_MAX_EXP, and then - again overflow occurs. - */ - - if (Py_SIZE(v) == 0) - return 0.0; - m = ABS(Py_SIZE(v)) - 1; - d = v->ob_digit; - assert(d[m]); /* v should be normalized */ - - /* fast path for case where 0 < abs(v) < 2**DBL_MANT_DIG */ - if (m < DBL_MANT_DIG / PyLong_SHIFT || - (m == DBL_MANT_DIG / PyLong_SHIFT && - d[m] < (digit)1 << DBL_MANT_DIG%PyLong_SHIFT)) { - x = d[m]; - while (--m >= 0) - x = x*PyLong_BASE + d[m]; - return Py_SIZE(v) < 0 ? -x : x; - } - - /* if m is huge then overflow immediately; otherwise, compute the - number of bits n in v. The condition below implies n (= #bits) >= - m * PyLong_SHIFT + 1 > DBL_MAX_EXP, hence v >= 2**DBL_MAX_EXP. */ - if (m > (DBL_MAX_EXP-1)/PyLong_SHIFT) - goto overflow; - n = m * PyLong_SHIFT + bits_in_digit(d[m]); - if (n > DBL_MAX_EXP) - goto overflow; - - /* find location of rounding bit */ - assert(n > DBL_MANT_DIG); /* dealt with |v| < 2**DBL_MANT_DIG above */ - rnd_bit = n - DBL_MANT_DIG - 1; - rnd_digit = rnd_bit/PyLong_SHIFT; - lsb = (digit)1 << (rnd_bit%PyLong_SHIFT); - - /* Get top DBL_MANT_DIG bits of v. Assumes PyLong_SHIFT < - DBL_MANT_DIG, so we'll need bits from at least 2 digits of v. */ - x = d[m]; - assert(m > rnd_digit); - while (--m > rnd_digit) - x = x*PyLong_BASE + d[m]; - x = x*PyLong_BASE + (d[m] & (PyLong_BASE-2*lsb)); - - /* decide whether to round up, using round-half-to-even */ - assert(m == rnd_digit); - if (d[m] & lsb) { /* if (rounding bit is set) */ - digit parity_bit; - if (lsb == PyLong_BASE/2) - parity_bit = d[m+1] & 1; - else - parity_bit = d[m] & 2*lsb; - if (parity_bit) - round_up = 1; - else if (d[m] & (lsb-1)) - round_up = 1; - else { - while (--m >= 0) { - if (d[m]) { - round_up = 1; - break; - } - } - } - } - - /* and round up if necessary */ - if (round_up) { - x += 2*lsb; - if (n == DBL_MAX_EXP && - x == ldexp((double)(2*lsb), DBL_MANT_DIG)) { - /* overflow corner case */ - goto overflow; - } - } - - /* shift, adjust for sign, and return */ - x = ldexp(x, rnd_digit*PyLong_SHIFT); - return Py_SIZE(v) < 0 ? -x : x; + PyLongObject *v = (PyLongObject *)vv; + Py_ssize_t rnd_digit, rnd_bit, m, n; + digit lsb, *d; + int round_up = 0; + double x; + + if (vv == NULL || !PyLong_Check(vv)) { + PyErr_BadInternalCall(); + return -1.0; + } + + /* Notes on the method: for simplicity, assume v is positive and >= + 2**DBL_MANT_DIG. (For negative v we just ignore the sign until the + end; for small v no rounding is necessary.) Write n for the number + of bits in v, so that 2**(n-1) <= v < 2**n, and n > DBL_MANT_DIG. + + Some terminology: the *rounding bit* of v is the 1st bit of v that + will be rounded away (bit n - DBL_MANT_DIG - 1); the *parity bit* + is the bit immediately above. The round-half-to-even rule says + that we round up if the rounding bit is set, unless v is exactly + halfway between two floats and the parity bit is zero. + + Write d[0] ... d[m] for the digits of v, least to most significant. + Let rnd_bit be the index of the rounding bit, and rnd_digit the + index of the PyLong digit containing the rounding bit. Then the + bits of the digit d[rnd_digit] look something like: + + rounding bit + | + v + msb -> sssssrttttttttt <- lsb + ^ + | + parity bit + + where 's' represents a 'significant bit' that will be included in + the mantissa of the result, 'r' is the rounding bit, and 't' + represents a 'trailing bit' following the rounding bit. Note that + if the rounding bit is at the top of d[rnd_digit] then the parity + bit will be the lsb of d[rnd_digit+1]. If we set + + lsb = 1 << (rnd_bit % PyLong_SHIFT) + + then d[rnd_digit] & (PyLong_BASE - 2*lsb) selects just the + significant bits of d[rnd_digit], d[rnd_digit] & (lsb-1) gets the + trailing bits, and d[rnd_digit] & lsb gives the rounding bit. + + We initialize the double x to the integer given by digits + d[rnd_digit:m-1], but with the rounding bit and trailing bits of + d[rnd_digit] masked out. So the value of x comes from the top + DBL_MANT_DIG bits of v, multiplied by 2*lsb. Note that in the loop + that produces x, all floating-point operations are exact (assuming + that FLT_RADIX==2). Now if we're rounding down, the value we want + to return is simply + + x * 2**(PyLong_SHIFT * rnd_digit). + + and if we're rounding up, it's + + (x + 2*lsb) * 2**(PyLong_SHIFT * rnd_digit). + + Under the round-half-to-even rule, we round up if, and only + if, the rounding bit is set *and* at least one of the + following three conditions is satisfied: + + (1) the parity bit is set, or + (2) at least one of the trailing bits of d[rnd_digit] is set, or + (3) at least one of the digits d[i], 0 <= i < rnd_digit + is nonzero. + + Finally, we have to worry about overflow. If v >= 2**DBL_MAX_EXP, + or equivalently n > DBL_MAX_EXP, then overflow occurs. If v < + 2**DBL_MAX_EXP then we're usually safe, but there's a corner case + to consider: if v is very close to 2**DBL_MAX_EXP then it's + possible that v is rounded up to exactly 2**DBL_MAX_EXP, and then + again overflow occurs. + */ + + if (Py_SIZE(v) == 0) + return 0.0; + m = ABS(Py_SIZE(v)) - 1; + d = v->ob_digit; + assert(d[m]); /* v should be normalized */ + + /* fast path for case where 0 < abs(v) < 2**DBL_MANT_DIG */ + if (m < DBL_MANT_DIG / PyLong_SHIFT || + (m == DBL_MANT_DIG / PyLong_SHIFT && + d[m] < (digit)1 << DBL_MANT_DIG%PyLong_SHIFT)) { + x = d[m]; + while (--m >= 0) + x = x*PyLong_BASE + d[m]; + return Py_SIZE(v) < 0 ? -x : x; + } + + /* if m is huge then overflow immediately; otherwise, compute the + number of bits n in v. The condition below implies n (= #bits) >= + m * PyLong_SHIFT + 1 > DBL_MAX_EXP, hence v >= 2**DBL_MAX_EXP. */ + if (m > (DBL_MAX_EXP-1)/PyLong_SHIFT) + goto overflow; + n = m * PyLong_SHIFT + bits_in_digit(d[m]); + if (n > DBL_MAX_EXP) + goto overflow; + + /* find location of rounding bit */ + assert(n > DBL_MANT_DIG); /* dealt with |v| < 2**DBL_MANT_DIG above */ + rnd_bit = n - DBL_MANT_DIG - 1; + rnd_digit = rnd_bit/PyLong_SHIFT; + lsb = (digit)1 << (rnd_bit%PyLong_SHIFT); + + /* Get top DBL_MANT_DIG bits of v. Assumes PyLong_SHIFT < + DBL_MANT_DIG, so we'll need bits from at least 2 digits of v. */ + x = d[m]; + assert(m > rnd_digit); + while (--m > rnd_digit) + x = x*PyLong_BASE + d[m]; + x = x*PyLong_BASE + (d[m] & (PyLong_BASE-2*lsb)); + + /* decide whether to round up, using round-half-to-even */ + assert(m == rnd_digit); + if (d[m] & lsb) { /* if (rounding bit is set) */ + digit parity_bit; + if (lsb == PyLong_BASE/2) + parity_bit = d[m+1] & 1; + else + parity_bit = d[m] & 2*lsb; + if (parity_bit) + round_up = 1; + else if (d[m] & (lsb-1)) + round_up = 1; + else { + while (--m >= 0) { + if (d[m]) { + round_up = 1; + break; + } + } + } + } + + /* and round up if necessary */ + if (round_up) { + x += 2*lsb; + if (n == DBL_MAX_EXP && + x == ldexp((double)(2*lsb), DBL_MANT_DIG)) { + /* overflow corner case */ + goto overflow; + } + } + + /* shift, adjust for sign, and return */ + x = ldexp(x, rnd_digit*PyLong_SHIFT); + return Py_SIZE(v) < 0 ? -x : x; overflow: - PyErr_SetString(PyExc_OverflowError, - "Python int too large to convert to C double"); - return -1.0; + PyErr_SetString(PyExc_OverflowError, + "Python int too large to convert to C double"); + return -1.0; } /* Create a new long (or int) object from a C pointer */ @@ -1157,10 +1157,10 @@ #if SIZEOF_LONG_LONG < SIZEOF_VOID_P # error "PyLong_FromVoidPtr: sizeof(PY_LONG_LONG) < sizeof(void*)" #endif - /* special-case null pointer */ - if (!p) - return PyLong_FromLong(0); - return PyLong_FromUnsignedLongLong((unsigned PY_LONG_LONG)(Py_uintptr_t)p); + /* special-case null pointer */ + if (!p) + return PyLong_FromLong(0); + return PyLong_FromUnsignedLongLong((unsigned PY_LONG_LONG)(Py_uintptr_t)p); } @@ -1169,17 +1169,17 @@ void * PyLong_AsVoidPtr(PyObject *vv) { - /* This function will allow int or long objects. If vv is neither, - then the PyLong_AsLong*() functions will raise the exception: - PyExc_SystemError, "bad argument to internal function" - */ + /* This function will allow int or long objects. If vv is neither, + then the PyLong_AsLong*() functions will raise the exception: + PyExc_SystemError, "bad argument to internal function" + */ #if SIZEOF_VOID_P <= SIZEOF_LONG - long x; + long x; - if (PyLong_Check(vv) && _PyLong_Sign(vv) < 0) - x = PyLong_AsLong(vv); - else - x = PyLong_AsUnsignedLong(vv); + if (PyLong_Check(vv) && _PyLong_Sign(vv) < 0) + x = PyLong_AsLong(vv); + else + x = PyLong_AsUnsignedLong(vv); #else #ifndef HAVE_LONG_LONG @@ -1188,18 +1188,18 @@ #if SIZEOF_LONG_LONG < SIZEOF_VOID_P # error "PyLong_AsVoidPtr: sizeof(PY_LONG_LONG) < sizeof(void*)" #endif - PY_LONG_LONG x; + PY_LONG_LONG x; - if (PyLong_Check(vv) && _PyLong_Sign(vv) < 0) - x = PyLong_AsLongLong(vv); - else - x = PyLong_AsUnsignedLongLong(vv); + if (PyLong_Check(vv) && _PyLong_Sign(vv) < 0) + x = PyLong_AsLongLong(vv); + else + x = PyLong_AsUnsignedLongLong(vv); #endif /* SIZEOF_VOID_P <= SIZEOF_LONG */ - if (x == -1 && PyErr_Occurred()) - return NULL; - return (void *)x; + if (x == -1 && PyErr_Occurred()) + return NULL; + return (void *)x; } #ifdef HAVE_LONG_LONG @@ -1215,43 +1215,43 @@ PyObject * PyLong_FromLongLong(PY_LONG_LONG ival) { - PyLongObject *v; - unsigned PY_LONG_LONG abs_ival; - unsigned PY_LONG_LONG t; /* unsigned so >> doesn't propagate sign bit */ - int ndigits = 0; - int negative = 0; - - CHECK_SMALL_INT(ival); - if (ival < 0) { - /* avoid signed overflow on negation; see comments - in PyLong_FromLong above. */ - abs_ival = (unsigned PY_LONG_LONG)(-1-ival) + 1; - negative = 1; - } - else { - abs_ival = (unsigned PY_LONG_LONG)ival; - } - - /* Count the number of Python digits. - We used to pick 5 ("big enough for anything"), but that's a - waste of time and space given that 5*15 = 75 bits are rarely - needed. */ - t = abs_ival; - while (t) { - ++ndigits; - t >>= PyLong_SHIFT; - } - v = _PyLong_New(ndigits); - if (v != NULL) { - digit *p = v->ob_digit; - Py_SIZE(v) = negative ? -ndigits : ndigits; - t = abs_ival; - while (t) { - *p++ = (digit)(t & PyLong_MASK); - t >>= PyLong_SHIFT; - } - } - return (PyObject *)v; + PyLongObject *v; + unsigned PY_LONG_LONG abs_ival; + unsigned PY_LONG_LONG t; /* unsigned so >> doesn't propagate sign bit */ + int ndigits = 0; + int negative = 0; + + CHECK_SMALL_INT(ival); + if (ival < 0) { + /* avoid signed overflow on negation; see comments + in PyLong_FromLong above. */ + abs_ival = (unsigned PY_LONG_LONG)(-1-ival) + 1; + negative = 1; + } + else { + abs_ival = (unsigned PY_LONG_LONG)ival; + } + + /* Count the number of Python digits. + We used to pick 5 ("big enough for anything"), but that's a + waste of time and space given that 5*15 = 75 bits are rarely + needed. */ + t = abs_ival; + while (t) { + ++ndigits; + t >>= PyLong_SHIFT; + } + v = _PyLong_New(ndigits); + if (v != NULL) { + digit *p = v->ob_digit; + Py_SIZE(v) = negative ? -ndigits : ndigits; + t = abs_ival; + while (t) { + *p++ = (digit)(t & PyLong_MASK); + t >>= PyLong_SHIFT; + } + } + return (PyObject *)v; } /* Create a new long int object from a C unsigned PY_LONG_LONG int. */ @@ -1259,28 +1259,28 @@ PyObject * PyLong_FromUnsignedLongLong(unsigned PY_LONG_LONG ival) { - PyLongObject *v; - unsigned PY_LONG_LONG t; - int ndigits = 0; - - if (ival < PyLong_BASE) - return PyLong_FromLong((long)ival); - /* Count the number of Python digits. */ - t = (unsigned PY_LONG_LONG)ival; - while (t) { - ++ndigits; - t >>= PyLong_SHIFT; - } - v = _PyLong_New(ndigits); - if (v != NULL) { - digit *p = v->ob_digit; - Py_SIZE(v) = ndigits; - while (ival) { - *p++ = (digit)(ival & PyLong_MASK); - ival >>= PyLong_SHIFT; - } - } - return (PyObject *)v; + PyLongObject *v; + unsigned PY_LONG_LONG t; + int ndigits = 0; + + if (ival < PyLong_BASE) + return PyLong_FromLong((long)ival); + /* Count the number of Python digits. */ + t = (unsigned PY_LONG_LONG)ival; + while (t) { + ++ndigits; + t >>= PyLong_SHIFT; + } + v = _PyLong_New(ndigits); + if (v != NULL) { + digit *p = v->ob_digit; + Py_SIZE(v) = ndigits; + while (ival) { + *p++ = (digit)(ival & PyLong_MASK); + ival >>= PyLong_SHIFT; + } + } + return (PyObject *)v; } /* Create a new long int object from a C Py_ssize_t. */ @@ -1288,39 +1288,39 @@ PyObject * PyLong_FromSsize_t(Py_ssize_t ival) { - PyLongObject *v; - size_t abs_ival; - size_t t; /* unsigned so >> doesn't propagate sign bit */ - int ndigits = 0; - int negative = 0; - - CHECK_SMALL_INT(ival); - if (ival < 0) { - /* avoid signed overflow when ival = SIZE_T_MIN */ - abs_ival = (size_t)(-1-ival)+1; - negative = 1; - } - else { - abs_ival = (size_t)ival; - } - - /* Count the number of Python digits. */ - t = abs_ival; - while (t) { - ++ndigits; - t >>= PyLong_SHIFT; - } - v = _PyLong_New(ndigits); - if (v != NULL) { - digit *p = v->ob_digit; - Py_SIZE(v) = negative ? -ndigits : ndigits; - t = abs_ival; - while (t) { - *p++ = (digit)(t & PyLong_MASK); - t >>= PyLong_SHIFT; - } - } - return (PyObject *)v; + PyLongObject *v; + size_t abs_ival; + size_t t; /* unsigned so >> doesn't propagate sign bit */ + int ndigits = 0; + int negative = 0; + + CHECK_SMALL_INT(ival); + if (ival < 0) { + /* avoid signed overflow when ival = SIZE_T_MIN */ + abs_ival = (size_t)(-1-ival)+1; + negative = 1; + } + else { + abs_ival = (size_t)ival; + } + + /* Count the number of Python digits. */ + t = abs_ival; + while (t) { + ++ndigits; + t >>= PyLong_SHIFT; + } + v = _PyLong_New(ndigits); + if (v != NULL) { + digit *p = v->ob_digit; + Py_SIZE(v) = negative ? -ndigits : ndigits; + t = abs_ival; + while (t) { + *p++ = (digit)(t & PyLong_MASK); + t >>= PyLong_SHIFT; + } + } + return (PyObject *)v; } /* Create a new long int object from a C size_t. */ @@ -1328,28 +1328,28 @@ PyObject * PyLong_FromSize_t(size_t ival) { - PyLongObject *v; - size_t t; - int ndigits = 0; - - if (ival < PyLong_BASE) - return PyLong_FromLong((long)ival); - /* Count the number of Python digits. */ - t = ival; - while (t) { - ++ndigits; - t >>= PyLong_SHIFT; - } - v = _PyLong_New(ndigits); - if (v != NULL) { - digit *p = v->ob_digit; - Py_SIZE(v) = ndigits; - while (ival) { - *p++ = (digit)(ival & PyLong_MASK); - ival >>= PyLong_SHIFT; - } - } - return (PyObject *)v; + PyLongObject *v; + size_t t; + int ndigits = 0; + + if (ival < PyLong_BASE) + return PyLong_FromLong((long)ival); + /* Count the number of Python digits. */ + t = ival; + while (t) { + ++ndigits; + t >>= PyLong_SHIFT; + } + v = _PyLong_New(ndigits); + if (v != NULL) { + digit *p = v->ob_digit; + Py_SIZE(v) = ndigits; + while (ival) { + *p++ = (digit)(ival & PyLong_MASK); + ival >>= PyLong_SHIFT; + } + } + return (PyObject *)v; } /* Get a C PY_LONG_LONG int from a long int object. @@ -1358,51 +1358,51 @@ PY_LONG_LONG PyLong_AsLongLong(PyObject *vv) { - PyLongObject *v; - PY_LONG_LONG bytes; - int one = 1; - int res; - - if (vv == NULL) { - PyErr_BadInternalCall(); - return -1; - } - if (!PyLong_Check(vv)) { - PyNumberMethods *nb; - PyObject *io; - if ((nb = vv->ob_type->tp_as_number) == NULL || - nb->nb_int == NULL) { - PyErr_SetString(PyExc_TypeError, "an integer is required"); - return -1; - } - io = (*nb->nb_int) (vv); - if (io == NULL) - return -1; - if (PyLong_Check(io)) { - bytes = PyLong_AsLongLong(io); - Py_DECREF(io); - return bytes; - } - Py_DECREF(io); - PyErr_SetString(PyExc_TypeError, "integer conversion failed"); - return -1; - } - - v = (PyLongObject*)vv; - switch(Py_SIZE(v)) { - case -1: return -(sdigit)v->ob_digit[0]; - case 0: return 0; - case 1: return v->ob_digit[0]; - } - res = _PyLong_AsByteArray( - (PyLongObject *)vv, (unsigned char *)&bytes, - SIZEOF_LONG_LONG, IS_LITTLE_ENDIAN, 1); - - /* Plan 9 can't handle PY_LONG_LONG in ? : expressions */ - if (res < 0) - return (PY_LONG_LONG)-1; - else - return bytes; + PyLongObject *v; + PY_LONG_LONG bytes; + int one = 1; + int res; + + if (vv == NULL) { + PyErr_BadInternalCall(); + return -1; + } + if (!PyLong_Check(vv)) { + PyNumberMethods *nb; + PyObject *io; + if ((nb = vv->ob_type->tp_as_number) == NULL || + nb->nb_int == NULL) { + PyErr_SetString(PyExc_TypeError, "an integer is required"); + return -1; + } + io = (*nb->nb_int) (vv); + if (io == NULL) + return -1; + if (PyLong_Check(io)) { + bytes = PyLong_AsLongLong(io); + Py_DECREF(io); + return bytes; + } + Py_DECREF(io); + PyErr_SetString(PyExc_TypeError, "integer conversion failed"); + return -1; + } + + v = (PyLongObject*)vv; + switch(Py_SIZE(v)) { + case -1: return -(sdigit)v->ob_digit[0]; + case 0: return 0; + case 1: return v->ob_digit[0]; + } + res = _PyLong_AsByteArray( + (PyLongObject *)vv, (unsigned char *)&bytes, + SIZEOF_LONG_LONG, IS_LITTLE_ENDIAN, 1); + + /* Plan 9 can't handle PY_LONG_LONG in ? : expressions */ + if (res < 0) + return (PY_LONG_LONG)-1; + else + return bytes; } /* Get a C unsigned PY_LONG_LONG int from a long int object. @@ -1411,31 +1411,31 @@ unsigned PY_LONG_LONG PyLong_AsUnsignedLongLong(PyObject *vv) { - PyLongObject *v; - unsigned PY_LONG_LONG bytes; - int one = 1; - int res; - - if (vv == NULL || !PyLong_Check(vv)) { - PyErr_BadInternalCall(); - return (unsigned PY_LONG_LONG)-1; - } - - v = (PyLongObject*)vv; - switch(Py_SIZE(v)) { - case 0: return 0; - case 1: return v->ob_digit[0]; - } - - res = _PyLong_AsByteArray( - (PyLongObject *)vv, (unsigned char *)&bytes, - SIZEOF_LONG_LONG, IS_LITTLE_ENDIAN, 0); - - /* Plan 9 can't handle PY_LONG_LONG in ? : expressions */ - if (res < 0) - return (unsigned PY_LONG_LONG)res; - else - return bytes; + PyLongObject *v; + unsigned PY_LONG_LONG bytes; + int one = 1; + int res; + + if (vv == NULL || !PyLong_Check(vv)) { + PyErr_BadInternalCall(); + return (unsigned PY_LONG_LONG)-1; + } + + v = (PyLongObject*)vv; + switch(Py_SIZE(v)) { + case 0: return 0; + case 1: return v->ob_digit[0]; + } + + res = _PyLong_AsByteArray( + (PyLongObject *)vv, (unsigned char *)&bytes, + SIZEOF_LONG_LONG, IS_LITTLE_ENDIAN, 0); + + /* Plan 9 can't handle PY_LONG_LONG in ? : expressions */ + if (res < 0) + return (unsigned PY_LONG_LONG)res; + else + return bytes; } /* Get a C unsigned long int from a long int object, ignoring the high bits. @@ -1444,95 +1444,95 @@ static unsigned PY_LONG_LONG _PyLong_AsUnsignedLongLongMask(PyObject *vv) { - register PyLongObject *v; - unsigned PY_LONG_LONG x; - Py_ssize_t i; - int sign; - - if (vv == NULL || !PyLong_Check(vv)) { - PyErr_BadInternalCall(); - return (unsigned long) -1; - } - v = (PyLongObject *)vv; - switch(Py_SIZE(v)) { - case 0: return 0; - case 1: return v->ob_digit[0]; - } - i = Py_SIZE(v); - sign = 1; - x = 0; - if (i < 0) { - sign = -1; - i = -i; - } - while (--i >= 0) { - x = (x << PyLong_SHIFT) + v->ob_digit[i]; - } - return x * sign; + register PyLongObject *v; + unsigned PY_LONG_LONG x; + Py_ssize_t i; + int sign; + + if (vv == NULL || !PyLong_Check(vv)) { + PyErr_BadInternalCall(); + return (unsigned long) -1; + } + v = (PyLongObject *)vv; + switch(Py_SIZE(v)) { + case 0: return 0; + case 1: return v->ob_digit[0]; + } + i = Py_SIZE(v); + sign = 1; + x = 0; + if (i < 0) { + sign = -1; + i = -i; + } + while (--i >= 0) { + x = (x << PyLong_SHIFT) + v->ob_digit[i]; + } + return x * sign; } unsigned PY_LONG_LONG PyLong_AsUnsignedLongLongMask(register PyObject *op) { - PyNumberMethods *nb; - PyLongObject *lo; - unsigned PY_LONG_LONG val; - - if (op && PyLong_Check(op)) - return _PyLong_AsUnsignedLongLongMask(op); - - if (op == NULL || (nb = op->ob_type->tp_as_number) == NULL || - nb->nb_int == NULL) { - PyErr_SetString(PyExc_TypeError, "an integer is required"); - return (unsigned PY_LONG_LONG)-1; - } - - lo = (PyLongObject*) (*nb->nb_int) (op); - if (lo == NULL) - return (unsigned PY_LONG_LONG)-1; - if (PyLong_Check(lo)) { - val = _PyLong_AsUnsignedLongLongMask((PyObject *)lo); - Py_DECREF(lo); - if (PyErr_Occurred()) - return (unsigned PY_LONG_LONG)-1; - return val; - } - else - { - Py_DECREF(lo); - PyErr_SetString(PyExc_TypeError, - "nb_int should return int object"); - return (unsigned PY_LONG_LONG)-1; - } + PyNumberMethods *nb; + PyLongObject *lo; + unsigned PY_LONG_LONG val; + + if (op && PyLong_Check(op)) + return _PyLong_AsUnsignedLongLongMask(op); + + if (op == NULL || (nb = op->ob_type->tp_as_number) == NULL || + nb->nb_int == NULL) { + PyErr_SetString(PyExc_TypeError, "an integer is required"); + return (unsigned PY_LONG_LONG)-1; + } + + lo = (PyLongObject*) (*nb->nb_int) (op); + if (lo == NULL) + return (unsigned PY_LONG_LONG)-1; + if (PyLong_Check(lo)) { + val = _PyLong_AsUnsignedLongLongMask((PyObject *)lo); + Py_DECREF(lo); + if (PyErr_Occurred()) + return (unsigned PY_LONG_LONG)-1; + return val; + } + else + { + Py_DECREF(lo); + PyErr_SetString(PyExc_TypeError, + "nb_int should return int object"); + return (unsigned PY_LONG_LONG)-1; + } } #undef IS_LITTLE_ENDIAN #endif /* HAVE_LONG_LONG */ #define CHECK_BINOP(v,w) \ - if (!PyLong_Check(v) || !PyLong_Check(w)) { \ - Py_INCREF(Py_NotImplemented); \ - return Py_NotImplemented; \ - } + if (!PyLong_Check(v) || !PyLong_Check(w)) { \ + Py_INCREF(Py_NotImplemented); \ + return Py_NotImplemented; \ + } /* bits_in_digit(d) returns the unique integer k such that 2**(k-1) <= d < 2**k if d is nonzero, else 0. */ static const unsigned char BitLengthTable[32] = { - 0, 1, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 4, 4, 4, 4, - 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5 + 0, 1, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 4, 4, 4, 4, + 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5 }; static int bits_in_digit(digit d) { - int d_bits = 0; - while (d >= 32) { - d_bits += 6; - d >>= 6; - } - d_bits += (int)BitLengthTable[d]; - return d_bits; + int d_bits = 0; + while (d >= 32) { + d_bits += 6; + d >>= 6; + } + d_bits += (int)BitLengthTable[d]; + return d_bits; } /* x[0:m] and y[0:n] are digit vectors, LSD first, m >= n required. x[0:n] @@ -1542,23 +1542,23 @@ static digit v_iadd(digit *x, Py_ssize_t m, digit *y, Py_ssize_t n) { - Py_ssize_t i; - digit carry = 0; + Py_ssize_t i; + digit carry = 0; - assert(m >= n); - for (i = 0; i < n; ++i) { - carry += x[i] + y[i]; - x[i] = carry & PyLong_MASK; - carry >>= PyLong_SHIFT; - assert((carry & 1) == carry); - } - for (; carry && i < m; ++i) { - carry += x[i]; - x[i] = carry & PyLong_MASK; - carry >>= PyLong_SHIFT; - assert((carry & 1) == carry); - } - return carry; + assert(m >= n); + for (i = 0; i < n; ++i) { + carry += x[i] + y[i]; + x[i] = carry & PyLong_MASK; + carry >>= PyLong_SHIFT; + assert((carry & 1) == carry); + } + for (; carry && i < m; ++i) { + carry += x[i]; + x[i] = carry & PyLong_MASK; + carry >>= PyLong_SHIFT; + assert((carry & 1) == carry); + } + return carry; } /* x[0:m] and y[0:n] are digit vectors, LSD first, m >= n required. x[0:n] @@ -1568,23 +1568,23 @@ static digit v_isub(digit *x, Py_ssize_t m, digit *y, Py_ssize_t n) { - Py_ssize_t i; - digit borrow = 0; + Py_ssize_t i; + digit borrow = 0; - assert(m >= n); - for (i = 0; i < n; ++i) { - borrow = x[i] - y[i] - borrow; - x[i] = borrow & PyLong_MASK; - borrow >>= PyLong_SHIFT; - borrow &= 1; /* keep only 1 sign bit */ - } - for (; borrow && i < m; ++i) { - borrow = x[i] - borrow; - x[i] = borrow & PyLong_MASK; - borrow >>= PyLong_SHIFT; - borrow &= 1; - } - return borrow; + assert(m >= n); + for (i = 0; i < n; ++i) { + borrow = x[i] - y[i] - borrow; + x[i] = borrow & PyLong_MASK; + borrow >>= PyLong_SHIFT; + borrow &= 1; /* keep only 1 sign bit */ + } + for (; borrow && i < m; ++i) { + borrow = x[i] - borrow; + x[i] = borrow & PyLong_MASK; + borrow >>= PyLong_SHIFT; + borrow &= 1; + } + return borrow; } /* Shift digit vector a[0:m] d bits left, with 0 <= d < PyLong_SHIFT. Put @@ -1593,16 +1593,16 @@ static digit v_lshift(digit *z, digit *a, Py_ssize_t m, int d) { - Py_ssize_t i; - digit carry = 0; + Py_ssize_t i; + digit carry = 0; - assert(0 <= d && d < PyLong_SHIFT); - for (i=0; i < m; i++) { - twodigits acc = (twodigits)a[i] << d | carry; - z[i] = (digit)acc & PyLong_MASK; - carry = (digit)(acc >> PyLong_SHIFT); - } - return carry; + assert(0 <= d && d < PyLong_SHIFT); + for (i=0; i < m; i++) { + twodigits acc = (twodigits)a[i] << d | carry; + z[i] = (digit)acc & PyLong_MASK; + carry = (digit)(acc >> PyLong_SHIFT); + } + return carry; } /* Shift digit vector a[0:m] d bits right, with 0 <= d < PyLong_SHIFT. Put @@ -1611,17 +1611,17 @@ static digit v_rshift(digit *z, digit *a, Py_ssize_t m, int d) { - Py_ssize_t i; - digit carry = 0; - digit mask = ((digit)1 << d) - 1U; - - assert(0 <= d && d < PyLong_SHIFT); - for (i=m; i-- > 0;) { - twodigits acc = (twodigits)carry << PyLong_SHIFT | a[i]; - carry = (digit)acc & mask; - z[i] = (digit)(acc >> d); - } - return carry; + Py_ssize_t i; + digit carry = 0; + digit mask = ((digit)1 << d) - 1U; + + assert(0 <= d && d < PyLong_SHIFT); + for (i=m; i-- > 0;) { + twodigits acc = (twodigits)carry << PyLong_SHIFT | a[i]; + carry = (digit)acc & mask; + z[i] = (digit)(acc >> d); + } + return carry; } /* Divide long pin, w/ size digits, by non-zero digit n, storing quotient @@ -1633,18 +1633,18 @@ static digit inplace_divrem1(digit *pout, digit *pin, Py_ssize_t size, digit n) { - twodigits rem = 0; + twodigits rem = 0; - assert(n > 0 && n <= PyLong_MASK); - pin += size; - pout += size; - while (--size >= 0) { - digit hi; - rem = (rem << PyLong_SHIFT) + *--pin; - *--pout = hi = (digit)(rem / n); - rem -= (twodigits)hi * n; - } - return (digit)rem; + assert(n > 0 && n <= PyLong_MASK); + pin += size; + pout += size; + while (--size >= 0) { + digit hi; + rem = (rem << PyLong_SHIFT) + *--pin; + *--pout = hi = (digit)(rem / n); + rem -= (twodigits)hi * n; + } + return (digit)rem; } /* Divide a long integer by a digit, returning both the quotient @@ -1654,15 +1654,15 @@ static PyLongObject * divrem1(PyLongObject *a, digit n, digit *prem) { - const Py_ssize_t size = ABS(Py_SIZE(a)); - PyLongObject *z; + const Py_ssize_t size = ABS(Py_SIZE(a)); + PyLongObject *z; - assert(n > 0 && n <= PyLong_MASK); - z = _PyLong_New(size); - if (z == NULL) - return NULL; - *prem = inplace_divrem1(z->ob_digit, a->ob_digit, size, n); - return long_normalize(z); + assert(n > 0 && n <= PyLong_MASK); + z = _PyLong_New(size); + if (z == NULL) + return NULL; + *prem = inplace_divrem1(z->ob_digit, a->ob_digit, size, n); + return long_normalize(z); } /* Convert a long int object to a string, using a given conversion base. @@ -1672,163 +1672,163 @@ PyObject * _PyLong_Format(PyObject *aa, int base) { - register PyLongObject *a = (PyLongObject *)aa; - PyObject *str; - Py_ssize_t i, sz; - Py_ssize_t size_a; - Py_UNICODE *p; - int bits; - char sign = '\0'; - - if (a == NULL || !PyLong_Check(a)) { - PyErr_BadInternalCall(); - return NULL; - } - assert(base >= 2 && base <= 36); - size_a = ABS(Py_SIZE(a)); - - /* Compute a rough upper bound for the length of the string */ - i = base; - bits = 0; - while (i > 1) { - ++bits; - i >>= 1; - } - i = 5; - /* ensure we don't get signed overflow in sz calculation */ - if (size_a > (PY_SSIZE_T_MAX - i) / PyLong_SHIFT) { - PyErr_SetString(PyExc_OverflowError, - "int is too large to format"); - return NULL; - } - sz = i + 1 + (size_a * PyLong_SHIFT - 1) / bits; - assert(sz >= 0); - str = PyUnicode_FromUnicode(NULL, sz); - if (str == NULL) - return NULL; - p = PyUnicode_AS_UNICODE(str) + sz; - *p = '\0'; - if (Py_SIZE(a) < 0) - sign = '-'; - - if (Py_SIZE(a) == 0) { - *--p = '0'; - } - else if ((base & (base - 1)) == 0) { - /* JRH: special case for power-of-2 bases */ - twodigits accum = 0; - int accumbits = 0; /* # of bits in accum */ - int basebits = 1; /* # of bits in base-1 */ - i = base; - while ((i >>= 1) > 1) - ++basebits; - - for (i = 0; i < size_a; ++i) { - accum |= (twodigits)a->ob_digit[i] << accumbits; - accumbits += PyLong_SHIFT; - assert(accumbits >= basebits); - do { - char cdigit = (char)(accum & (base - 1)); - cdigit += (cdigit < 10) ? '0' : 'a'-10; - assert(p > PyUnicode_AS_UNICODE(str)); - *--p = cdigit; - accumbits -= basebits; - accum >>= basebits; - } while (i < size_a-1 ? accumbits >= basebits : - accum > 0); - } - } - else { - /* Not 0, and base not a power of 2. Divide repeatedly by - base, but for speed use the highest power of base that - fits in a digit. */ - Py_ssize_t size = size_a; - digit *pin = a->ob_digit; - PyLongObject *scratch; - /* powbasw <- largest power of base that fits in a digit. */ - digit powbase = base; /* powbase == base ** power */ - int power = 1; - for (;;) { - twodigits newpow = powbase * (twodigits)base; - if (newpow >> PyLong_SHIFT) - /* doesn't fit in a digit */ - break; - powbase = (digit)newpow; - ++power; - } - - /* Get a scratch area for repeated division. */ - scratch = _PyLong_New(size); - if (scratch == NULL) { - Py_DECREF(str); - return NULL; - } - - /* Repeatedly divide by powbase. */ - do { - int ntostore = power; - digit rem = inplace_divrem1(scratch->ob_digit, - pin, size, powbase); - pin = scratch->ob_digit; /* no need to use a again */ - if (pin[size - 1] == 0) - --size; - SIGCHECK({ - Py_DECREF(scratch); - Py_DECREF(str); - return NULL; - }) - - /* Break rem into digits. */ - assert(ntostore > 0); - do { - digit nextrem = (digit)(rem / base); - char c = (char)(rem - nextrem * base); - assert(p > PyUnicode_AS_UNICODE(str)); - c += (c < 10) ? '0' : 'a'-10; - *--p = c; - rem = nextrem; - --ntostore; - /* Termination is a bit delicate: must not - store leading zeroes, so must get out if - remaining quotient and rem are both 0. */ - } while (ntostore && (size || rem)); - } while (size != 0); - Py_DECREF(scratch); - } - - if (base == 16) { - *--p = 'x'; - *--p = '0'; - } - else if (base == 8) { - *--p = 'o'; - *--p = '0'; - } - else if (base == 2) { - *--p = 'b'; - *--p = '0'; - } - else if (base != 10) { - *--p = '#'; - *--p = '0' + base%10; - if (base > 10) - *--p = '0' + base/10; - } - if (sign) - *--p = sign; - if (p != PyUnicode_AS_UNICODE(str)) { - Py_UNICODE *q = PyUnicode_AS_UNICODE(str); - assert(p > q); - do { - } while ((*q++ = *p++) != '\0'); - q--; - if (PyUnicode_Resize(&str,(Py_ssize_t) (q - - PyUnicode_AS_UNICODE(str)))) { - Py_DECREF(str); - return NULL; - } - } - return (PyObject *)str; + register PyLongObject *a = (PyLongObject *)aa; + PyObject *str; + Py_ssize_t i, sz; + Py_ssize_t size_a; + Py_UNICODE *p; + int bits; + char sign = '\0'; + + if (a == NULL || !PyLong_Check(a)) { + PyErr_BadInternalCall(); + return NULL; + } + assert(base >= 2 && base <= 36); + size_a = ABS(Py_SIZE(a)); + + /* Compute a rough upper bound for the length of the string */ + i = base; + bits = 0; + while (i > 1) { + ++bits; + i >>= 1; + } + i = 5; + /* ensure we don't get signed overflow in sz calculation */ + if (size_a > (PY_SSIZE_T_MAX - i) / PyLong_SHIFT) { + PyErr_SetString(PyExc_OverflowError, + "int is too large to format"); + return NULL; + } + sz = i + 1 + (size_a * PyLong_SHIFT - 1) / bits; + assert(sz >= 0); + str = PyUnicode_FromUnicode(NULL, sz); + if (str == NULL) + return NULL; + p = PyUnicode_AS_UNICODE(str) + sz; + *p = '\0'; + if (Py_SIZE(a) < 0) + sign = '-'; + + if (Py_SIZE(a) == 0) { + *--p = '0'; + } + else if ((base & (base - 1)) == 0) { + /* JRH: special case for power-of-2 bases */ + twodigits accum = 0; + int accumbits = 0; /* # of bits in accum */ + int basebits = 1; /* # of bits in base-1 */ + i = base; + while ((i >>= 1) > 1) + ++basebits; + + for (i = 0; i < size_a; ++i) { + accum |= (twodigits)a->ob_digit[i] << accumbits; + accumbits += PyLong_SHIFT; + assert(accumbits >= basebits); + do { + char cdigit = (char)(accum & (base - 1)); + cdigit += (cdigit < 10) ? '0' : 'a'-10; + assert(p > PyUnicode_AS_UNICODE(str)); + *--p = cdigit; + accumbits -= basebits; + accum >>= basebits; + } while (i < size_a-1 ? accumbits >= basebits : + accum > 0); + } + } + else { + /* Not 0, and base not a power of 2. Divide repeatedly by + base, but for speed use the highest power of base that + fits in a digit. */ + Py_ssize_t size = size_a; + digit *pin = a->ob_digit; + PyLongObject *scratch; + /* powbasw <- largest power of base that fits in a digit. */ + digit powbase = base; /* powbase == base ** power */ + int power = 1; + for (;;) { + twodigits newpow = powbase * (twodigits)base; + if (newpow >> PyLong_SHIFT) + /* doesn't fit in a digit */ + break; + powbase = (digit)newpow; + ++power; + } + + /* Get a scratch area for repeated division. */ + scratch = _PyLong_New(size); + if (scratch == NULL) { + Py_DECREF(str); + return NULL; + } + + /* Repeatedly divide by powbase. */ + do { + int ntostore = power; + digit rem = inplace_divrem1(scratch->ob_digit, + pin, size, powbase); + pin = scratch->ob_digit; /* no need to use a again */ + if (pin[size - 1] == 0) + --size; + SIGCHECK({ + Py_DECREF(scratch); + Py_DECREF(str); + return NULL; + }) + + /* Break rem into digits. */ + assert(ntostore > 0); + do { + digit nextrem = (digit)(rem / base); + char c = (char)(rem - nextrem * base); + assert(p > PyUnicode_AS_UNICODE(str)); + c += (c < 10) ? '0' : 'a'-10; + *--p = c; + rem = nextrem; + --ntostore; + /* Termination is a bit delicate: must not + store leading zeroes, so must get out if + remaining quotient and rem are both 0. */ + } while (ntostore && (size || rem)); + } while (size != 0); + Py_DECREF(scratch); + } + + if (base == 16) { + *--p = 'x'; + *--p = '0'; + } + else if (base == 8) { + *--p = 'o'; + *--p = '0'; + } + else if (base == 2) { + *--p = 'b'; + *--p = '0'; + } + else if (base != 10) { + *--p = '#'; + *--p = '0' + base%10; + if (base > 10) + *--p = '0' + base/10; + } + if (sign) + *--p = sign; + if (p != PyUnicode_AS_UNICODE(str)) { + Py_UNICODE *q = PyUnicode_AS_UNICODE(str); + assert(p > q); + do { + } while ((*q++ = *p++) != '\0'); + q--; + if (PyUnicode_Resize(&str,(Py_ssize_t) (q - + PyUnicode_AS_UNICODE(str)))) { + Py_DECREF(str); + return NULL; + } + } + return (PyObject *)str; } /* Table of digit values for 8-bit string -> integer conversion. @@ -1839,22 +1839,22 @@ * base B digit iff _PyLong_DigitValue[Py_CHARPyLong_MASK(c)] < B. */ unsigned char _PyLong_DigitValue[256] = { - 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, - 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, - 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, - 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 37, 37, 37, 37, 37, 37, - 37, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, - 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 37, 37, 37, 37, 37, - 37, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, - 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 37, 37, 37, 37, 37, - 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, - 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, - 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, - 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, - 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, - 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, - 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, - 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, + 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, + 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, + 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, + 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 37, 37, 37, 37, 37, 37, + 37, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, + 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 37, 37, 37, 37, 37, + 37, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, + 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 37, 37, 37, 37, 37, + 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, + 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, + 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, + 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, + 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, + 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, + 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, + 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, }; /* *str points to the first digit in a string of base `base` digits. base @@ -1866,111 +1866,111 @@ static PyLongObject * long_from_binary_base(char **str, int base) { - char *p = *str; - char *start = p; - int bits_per_char; - Py_ssize_t n; - PyLongObject *z; - twodigits accum; - int bits_in_accum; - digit *pdigit; - - assert(base >= 2 && base <= 32 && (base & (base - 1)) == 0); - n = base; - for (bits_per_char = -1; n; ++bits_per_char) - n >>= 1; - /* n <- total # of bits needed, while setting p to end-of-string */ - while (_PyLong_DigitValue[Py_CHARMASK(*p)] < base) - ++p; - *str = p; - /* n <- # of Python digits needed, = ceiling(n/PyLong_SHIFT). */ - n = (p - start) * bits_per_char + PyLong_SHIFT - 1; - if (n / bits_per_char < p - start) { - PyErr_SetString(PyExc_ValueError, - "int string too large to convert"); - return NULL; - } - n = n / PyLong_SHIFT; - z = _PyLong_New(n); - if (z == NULL) - return NULL; - /* Read string from right, and fill in long from left; i.e., - * from least to most significant in both. - */ - accum = 0; - bits_in_accum = 0; - pdigit = z->ob_digit; - while (--p >= start) { - int k = (int)_PyLong_DigitValue[Py_CHARMASK(*p)]; - assert(k >= 0 && k < base); - accum |= (twodigits)k << bits_in_accum; - bits_in_accum += bits_per_char; - if (bits_in_accum >= PyLong_SHIFT) { - *pdigit++ = (digit)(accum & PyLong_MASK); - assert(pdigit - z->ob_digit <= n); - accum >>= PyLong_SHIFT; - bits_in_accum -= PyLong_SHIFT; - assert(bits_in_accum < PyLong_SHIFT); - } - } - if (bits_in_accum) { - assert(bits_in_accum <= PyLong_SHIFT); - *pdigit++ = (digit)accum; - assert(pdigit - z->ob_digit <= n); - } - while (pdigit - z->ob_digit < n) - *pdigit++ = 0; - return long_normalize(z); + char *p = *str; + char *start = p; + int bits_per_char; + Py_ssize_t n; + PyLongObject *z; + twodigits accum; + int bits_in_accum; + digit *pdigit; + + assert(base >= 2 && base <= 32 && (base & (base - 1)) == 0); + n = base; + for (bits_per_char = -1; n; ++bits_per_char) + n >>= 1; + /* n <- total # of bits needed, while setting p to end-of-string */ + while (_PyLong_DigitValue[Py_CHARMASK(*p)] < base) + ++p; + *str = p; + /* n <- # of Python digits needed, = ceiling(n/PyLong_SHIFT). */ + n = (p - start) * bits_per_char + PyLong_SHIFT - 1; + if (n / bits_per_char < p - start) { + PyErr_SetString(PyExc_ValueError, + "int string too large to convert"); + return NULL; + } + n = n / PyLong_SHIFT; + z = _PyLong_New(n); + if (z == NULL) + return NULL; + /* Read string from right, and fill in long from left; i.e., + * from least to most significant in both. + */ + accum = 0; + bits_in_accum = 0; + pdigit = z->ob_digit; + while (--p >= start) { + int k = (int)_PyLong_DigitValue[Py_CHARMASK(*p)]; + assert(k >= 0 && k < base); + accum |= (twodigits)k << bits_in_accum; + bits_in_accum += bits_per_char; + if (bits_in_accum >= PyLong_SHIFT) { + *pdigit++ = (digit)(accum & PyLong_MASK); + assert(pdigit - z->ob_digit <= n); + accum >>= PyLong_SHIFT; + bits_in_accum -= PyLong_SHIFT; + assert(bits_in_accum < PyLong_SHIFT); + } + } + if (bits_in_accum) { + assert(bits_in_accum <= PyLong_SHIFT); + *pdigit++ = (digit)accum; + assert(pdigit - z->ob_digit <= n); + } + while (pdigit - z->ob_digit < n) + *pdigit++ = 0; + return long_normalize(z); } PyObject * PyLong_FromString(char *str, char **pend, int base) { - int sign = 1, error_if_nonzero = 0; - char *start, *orig_str = str; - PyLongObject *z = NULL; - PyObject *strobj; - Py_ssize_t slen; - - if ((base != 0 && base < 2) || base > 36) { - PyErr_SetString(PyExc_ValueError, - "int() arg 2 must be >= 2 and <= 36"); - return NULL; - } - while (*str != '\0' && isspace(Py_CHARMASK(*str))) - str++; - if (*str == '+') - ++str; - else if (*str == '-') { - ++str; - sign = -1; - } - if (base == 0) { - if (str[0] != '0') - base = 10; - else if (str[1] == 'x' || str[1] == 'X') - base = 16; - else if (str[1] == 'o' || str[1] == 'O') - base = 8; - else if (str[1] == 'b' || str[1] == 'B') - base = 2; - else { - /* "old" (C-style) octal literal, now invalid. - it might still be zero though */ - error_if_nonzero = 1; - base = 10; - } - } - if (str[0] == '0' && - ((base == 16 && (str[1] == 'x' || str[1] == 'X')) || - (base == 8 && (str[1] == 'o' || str[1] == 'O')) || - (base == 2 && (str[1] == 'b' || str[1] == 'B')))) - str += 2; - - start = str; - if ((base & (base - 1)) == 0) - z = long_from_binary_base(&str, base); - else { + int sign = 1, error_if_nonzero = 0; + char *start, *orig_str = str; + PyLongObject *z = NULL; + PyObject *strobj; + Py_ssize_t slen; + + if ((base != 0 && base < 2) || base > 36) { + PyErr_SetString(PyExc_ValueError, + "int() arg 2 must be >= 2 and <= 36"); + return NULL; + } + while (*str != '\0' && isspace(Py_CHARMASK(*str))) + str++; + if (*str == '+') + ++str; + else if (*str == '-') { + ++str; + sign = -1; + } + if (base == 0) { + if (str[0] != '0') + base = 10; + else if (str[1] == 'x' || str[1] == 'X') + base = 16; + else if (str[1] == 'o' || str[1] == 'O') + base = 8; + else if (str[1] == 'b' || str[1] == 'B') + base = 2; + else { + /* "old" (C-style) octal literal, now invalid. + it might still be zero though */ + error_if_nonzero = 1; + base = 10; + } + } + if (str[0] == '0' && + ((base == 16 && (str[1] == 'x' || str[1] == 'X')) || + (base == 8 && (str[1] == 'o' || str[1] == 'O')) || + (base == 2 && (str[1] == 'b' || str[1] == 'B')))) + str += 2; + + start = str; + if ((base & (base - 1)) == 0) + z = long_from_binary_base(&str, base); + else { /*** Binary bases can be converted in time linear in the number of digits, because Python's representation base is binary. Other bases (including decimal!) use @@ -2056,227 +2056,227 @@ just 1 digit at the start, so that the copying code was exercised for every digit beyond the first. ***/ - register twodigits c; /* current input character */ - Py_ssize_t size_z; - int i; - int convwidth; - twodigits convmultmax, convmult; - digit *pz, *pzstop; - char* scan; - - static double log_base_BASE[37] = {0.0e0,}; - static int convwidth_base[37] = {0,}; - static twodigits convmultmax_base[37] = {0,}; - - if (log_base_BASE[base] == 0.0) { - twodigits convmax = base; - int i = 1; - - log_base_BASE[base] = log((double)base) / - log((double)PyLong_BASE); - for (;;) { - twodigits next = convmax * base; - if (next > PyLong_BASE) - break; - convmax = next; - ++i; - } - convmultmax_base[base] = convmax; - assert(i > 0); - convwidth_base[base] = i; - } - - /* Find length of the string of numeric characters. */ - scan = str; - while (_PyLong_DigitValue[Py_CHARMASK(*scan)] < base) - ++scan; - - /* Create a long object that can contain the largest possible - * integer with this base and length. Note that there's no - * need to initialize z->ob_digit -- no slot is read up before - * being stored into. - */ - size_z = (Py_ssize_t)((scan - str) * log_base_BASE[base]) + 1; - /* Uncomment next line to test exceedingly rare copy code */ - /* size_z = 1; */ - assert(size_z > 0); - z = _PyLong_New(size_z); - if (z == NULL) - return NULL; - Py_SIZE(z) = 0; - - /* `convwidth` consecutive input digits are treated as a single - * digit in base `convmultmax`. - */ - convwidth = convwidth_base[base]; - convmultmax = convmultmax_base[base]; - - /* Work ;-) */ - while (str < scan) { - /* grab up to convwidth digits from the input string */ - c = (digit)_PyLong_DigitValue[Py_CHARMASK(*str++)]; - for (i = 1; i < convwidth && str != scan; ++i, ++str) { - c = (twodigits)(c * base + - (int)_PyLong_DigitValue[Py_CHARMASK(*str)]); - assert(c < PyLong_BASE); - } - - convmult = convmultmax; - /* Calculate the shift only if we couldn't get - * convwidth digits. - */ - if (i != convwidth) { - convmult = base; - for ( ; i > 1; --i) - convmult *= base; - } - - /* Multiply z by convmult, and add c. */ - pz = z->ob_digit; - pzstop = pz + Py_SIZE(z); - for (; pz < pzstop; ++pz) { - c += (twodigits)*pz * convmult; - *pz = (digit)(c & PyLong_MASK); - c >>= PyLong_SHIFT; - } - /* carry off the current end? */ - if (c) { - assert(c < PyLong_BASE); - if (Py_SIZE(z) < size_z) { - *pz = (digit)c; - ++Py_SIZE(z); - } - else { - PyLongObject *tmp; - /* Extremely rare. Get more space. */ - assert(Py_SIZE(z) == size_z); - tmp = _PyLong_New(size_z + 1); - if (tmp == NULL) { - Py_DECREF(z); - return NULL; - } - memcpy(tmp->ob_digit, - z->ob_digit, - sizeof(digit) * size_z); - Py_DECREF(z); - z = tmp; - z->ob_digit[size_z] = (digit)c; - ++size_z; - } - } - } - } - if (z == NULL) - return NULL; - if (error_if_nonzero) { - /* reset the base to 0, else the exception message - doesn't make too much sense */ - base = 0; - if (Py_SIZE(z) != 0) - goto onError; - /* there might still be other problems, therefore base - remains zero here for the same reason */ - } - if (str == start) - goto onError; - if (sign < 0) - Py_SIZE(z) = -(Py_SIZE(z)); - while (*str && isspace(Py_CHARMASK(*str))) - str++; - if (*str != '\0') - goto onError; - if (pend) - *pend = str; - long_normalize(z); - return (PyObject *) maybe_small_long(z); + register twodigits c; /* current input character */ + Py_ssize_t size_z; + int i; + int convwidth; + twodigits convmultmax, convmult; + digit *pz, *pzstop; + char* scan; + + static double log_base_BASE[37] = {0.0e0,}; + static int convwidth_base[37] = {0,}; + static twodigits convmultmax_base[37] = {0,}; + + if (log_base_BASE[base] == 0.0) { + twodigits convmax = base; + int i = 1; + + log_base_BASE[base] = log((double)base) / + log((double)PyLong_BASE); + for (;;) { + twodigits next = convmax * base; + if (next > PyLong_BASE) + break; + convmax = next; + ++i; + } + convmultmax_base[base] = convmax; + assert(i > 0); + convwidth_base[base] = i; + } + + /* Find length of the string of numeric characters. */ + scan = str; + while (_PyLong_DigitValue[Py_CHARMASK(*scan)] < base) + ++scan; + + /* Create a long object that can contain the largest possible + * integer with this base and length. Note that there's no + * need to initialize z->ob_digit -- no slot is read up before + * being stored into. + */ + size_z = (Py_ssize_t)((scan - str) * log_base_BASE[base]) + 1; + /* Uncomment next line to test exceedingly rare copy code */ + /* size_z = 1; */ + assert(size_z > 0); + z = _PyLong_New(size_z); + if (z == NULL) + return NULL; + Py_SIZE(z) = 0; + + /* `convwidth` consecutive input digits are treated as a single + * digit in base `convmultmax`. + */ + convwidth = convwidth_base[base]; + convmultmax = convmultmax_base[base]; + + /* Work ;-) */ + while (str < scan) { + /* grab up to convwidth digits from the input string */ + c = (digit)_PyLong_DigitValue[Py_CHARMASK(*str++)]; + for (i = 1; i < convwidth && str != scan; ++i, ++str) { + c = (twodigits)(c * base + + (int)_PyLong_DigitValue[Py_CHARMASK(*str)]); + assert(c < PyLong_BASE); + } + + convmult = convmultmax; + /* Calculate the shift only if we couldn't get + * convwidth digits. + */ + if (i != convwidth) { + convmult = base; + for ( ; i > 1; --i) + convmult *= base; + } + + /* Multiply z by convmult, and add c. */ + pz = z->ob_digit; + pzstop = pz + Py_SIZE(z); + for (; pz < pzstop; ++pz) { + c += (twodigits)*pz * convmult; + *pz = (digit)(c & PyLong_MASK); + c >>= PyLong_SHIFT; + } + /* carry off the current end? */ + if (c) { + assert(c < PyLong_BASE); + if (Py_SIZE(z) < size_z) { + *pz = (digit)c; + ++Py_SIZE(z); + } + else { + PyLongObject *tmp; + /* Extremely rare. Get more space. */ + assert(Py_SIZE(z) == size_z); + tmp = _PyLong_New(size_z + 1); + if (tmp == NULL) { + Py_DECREF(z); + return NULL; + } + memcpy(tmp->ob_digit, + z->ob_digit, + sizeof(digit) * size_z); + Py_DECREF(z); + z = tmp; + z->ob_digit[size_z] = (digit)c; + ++size_z; + } + } + } + } + if (z == NULL) + return NULL; + if (error_if_nonzero) { + /* reset the base to 0, else the exception message + doesn't make too much sense */ + base = 0; + if (Py_SIZE(z) != 0) + goto onError; + /* there might still be other problems, therefore base + remains zero here for the same reason */ + } + if (str == start) + goto onError; + if (sign < 0) + Py_SIZE(z) = -(Py_SIZE(z)); + while (*str && isspace(Py_CHARMASK(*str))) + str++; + if (*str != '\0') + goto onError; + if (pend) + *pend = str; + long_normalize(z); + return (PyObject *) maybe_small_long(z); onError: - Py_XDECREF(z); - slen = strlen(orig_str) < 200 ? strlen(orig_str) : 200; - strobj = PyUnicode_FromStringAndSize(orig_str, slen); - if (strobj == NULL) - return NULL; - PyErr_Format(PyExc_ValueError, - "invalid literal for int() with base %d: %R", - base, strobj); - Py_DECREF(strobj); - return NULL; + Py_XDECREF(z); + slen = strlen(orig_str) < 200 ? strlen(orig_str) : 200; + strobj = PyUnicode_FromStringAndSize(orig_str, slen); + if (strobj == NULL) + return NULL; + PyErr_Format(PyExc_ValueError, + "invalid literal for int() with base %d: %R", + base, strobj); + Py_DECREF(strobj); + return NULL; } PyObject * PyLong_FromUnicode(Py_UNICODE *u, Py_ssize_t length, int base) { - PyObject *result; - char *buffer = (char *)PyMem_MALLOC(length+1); + PyObject *result; + char *buffer = (char *)PyMem_MALLOC(length+1); - if (buffer == NULL) - return NULL; + if (buffer == NULL) + return NULL; - if (PyUnicode_EncodeDecimal(u, length, buffer, NULL)) { - PyMem_FREE(buffer); - return NULL; - } - result = PyLong_FromString(buffer, NULL, base); - PyMem_FREE(buffer); - return result; + if (PyUnicode_EncodeDecimal(u, length, buffer, NULL)) { + PyMem_FREE(buffer); + return NULL; + } + result = PyLong_FromString(buffer, NULL, base); + PyMem_FREE(buffer); + return result; } /* forward */ static PyLongObject *x_divrem - (PyLongObject *, PyLongObject *, PyLongObject **); + (PyLongObject *, PyLongObject *, PyLongObject **); static PyObject *long_long(PyObject *v); /* Long division with remainder, top-level routine */ static int long_divrem(PyLongObject *a, PyLongObject *b, - PyLongObject **pdiv, PyLongObject **prem) + PyLongObject **pdiv, PyLongObject **prem) { - Py_ssize_t size_a = ABS(Py_SIZE(a)), size_b = ABS(Py_SIZE(b)); - PyLongObject *z; + Py_ssize_t size_a = ABS(Py_SIZE(a)), size_b = ABS(Py_SIZE(b)); + PyLongObject *z; - if (size_b == 0) { - PyErr_SetString(PyExc_ZeroDivisionError, - "integer division or modulo by zero"); - return -1; - } - if (size_a < size_b || - (size_a == size_b && - a->ob_digit[size_a-1] < b->ob_digit[size_b-1])) { - /* |a| < |b|. */ - *pdiv = (PyLongObject*)PyLong_FromLong(0); - if (*pdiv == NULL) - return -1; - Py_INCREF(a); - *prem = (PyLongObject *) a; - return 0; - } - if (size_b == 1) { - digit rem = 0; - z = divrem1(a, b->ob_digit[0], &rem); - if (z == NULL) - return -1; - *prem = (PyLongObject *) PyLong_FromLong((long)rem); - if (*prem == NULL) { - Py_DECREF(z); - return -1; - } - } - else { - z = x_divrem(a, b, prem); - if (z == NULL) - return -1; - } - /* Set the signs. - The quotient z has the sign of a*b; - the remainder r has the sign of a, - so a = b*z + r. */ - if ((Py_SIZE(a) < 0) != (Py_SIZE(b) < 0)) - NEGATE(z); - if (Py_SIZE(a) < 0 && Py_SIZE(*prem) != 0) - NEGATE(*prem); - *pdiv = maybe_small_long(z); - return 0; + if (size_b == 0) { + PyErr_SetString(PyExc_ZeroDivisionError, + "integer division or modulo by zero"); + return -1; + } + if (size_a < size_b || + (size_a == size_b && + a->ob_digit[size_a-1] < b->ob_digit[size_b-1])) { + /* |a| < |b|. */ + *pdiv = (PyLongObject*)PyLong_FromLong(0); + if (*pdiv == NULL) + return -1; + Py_INCREF(a); + *prem = (PyLongObject *) a; + return 0; + } + if (size_b == 1) { + digit rem = 0; + z = divrem1(a, b->ob_digit[0], &rem); + if (z == NULL) + return -1; + *prem = (PyLongObject *) PyLong_FromLong((long)rem); + if (*prem == NULL) { + Py_DECREF(z); + return -1; + } + } + else { + z = x_divrem(a, b, prem); + if (z == NULL) + return -1; + } + /* Set the signs. + The quotient z has the sign of a*b; + the remainder r has the sign of a, + so a = b*z + r. */ + if ((Py_SIZE(a) < 0) != (Py_SIZE(b) < 0)) + NEGATE(z); + if (Py_SIZE(a) < 0 && Py_SIZE(*prem) != 0) + NEGATE(*prem); + *pdiv = maybe_small_long(z); + return 0; } /* Unsigned long division with remainder -- the algorithm. The arguments v1 @@ -2285,125 +2285,125 @@ static PyLongObject * x_divrem(PyLongObject *v1, PyLongObject *w1, PyLongObject **prem) { - PyLongObject *v, *w, *a; - Py_ssize_t i, k, size_v, size_w; - int d; - digit wm1, wm2, carry, q, r, vtop, *v0, *vk, *w0, *ak; - twodigits vv; - sdigit zhi; - stwodigits z; - - /* We follow Knuth [The Art of Computer Programming, Vol. 2 (3rd - edn.), section 4.3.1, Algorithm D], except that we don't explicitly - handle the special case when the initial estimate q for a quotient - digit is >= PyLong_BASE: the max value for q is PyLong_BASE+1, and - that won't overflow a digit. */ - - /* allocate space; w will also be used to hold the final remainder */ - size_v = ABS(Py_SIZE(v1)); - size_w = ABS(Py_SIZE(w1)); - assert(size_v >= size_w && size_w >= 2); /* Assert checks by div() */ - v = _PyLong_New(size_v+1); - if (v == NULL) { - *prem = NULL; - return NULL; - } - w = _PyLong_New(size_w); - if (w == NULL) { - Py_DECREF(v); - *prem = NULL; - return NULL; - } - - /* normalize: shift w1 left so that its top digit is >= PyLong_BASE/2. - shift v1 left by the same amount. Results go into w and v. */ - d = PyLong_SHIFT - bits_in_digit(w1->ob_digit[size_w-1]); - carry = v_lshift(w->ob_digit, w1->ob_digit, size_w, d); - assert(carry == 0); - carry = v_lshift(v->ob_digit, v1->ob_digit, size_v, d); - if (carry != 0 || v->ob_digit[size_v-1] >= w->ob_digit[size_w-1]) { - v->ob_digit[size_v] = carry; - size_v++; - } - - /* Now v->ob_digit[size_v-1] < w->ob_digit[size_w-1], so quotient has - at most (and usually exactly) k = size_v - size_w digits. */ - k = size_v - size_w; - assert(k >= 0); - a = _PyLong_New(k); - if (a == NULL) { - Py_DECREF(w); - Py_DECREF(v); - *prem = NULL; - return NULL; - } - v0 = v->ob_digit; - w0 = w->ob_digit; - wm1 = w0[size_w-1]; - wm2 = w0[size_w-2]; - for (vk = v0+k, ak = a->ob_digit + k; vk-- > v0;) { - /* inner loop: divide vk[0:size_w+1] by w0[0:size_w], giving - single-digit quotient q, remainder in vk[0:size_w]. */ - - SIGCHECK({ - Py_DECREF(a); - Py_DECREF(w); - Py_DECREF(v); - *prem = NULL; - return NULL; - }) - - /* estimate quotient digit q; may overestimate by 1 (rare) */ - vtop = vk[size_w]; - assert(vtop <= wm1); - vv = ((twodigits)vtop << PyLong_SHIFT) | vk[size_w-1]; - q = (digit)(vv / wm1); - r = (digit)(vv - (twodigits)wm1 * q); /* r = vv % wm1 */ - while ((twodigits)wm2 * q > (((twodigits)r << PyLong_SHIFT) - | vk[size_w-2])) { - --q; - r += wm1; - if (r >= PyLong_BASE) - break; - } - assert(q <= PyLong_BASE); - - /* subtract q*w0[0:size_w] from vk[0:size_w+1] */ - zhi = 0; - for (i = 0; i < size_w; ++i) { - /* invariants: -PyLong_BASE <= -q <= zhi <= 0; - -PyLong_BASE * q <= z < PyLong_BASE */ - z = (sdigit)vk[i] + zhi - - (stwodigits)q * (stwodigits)w0[i]; - vk[i] = (digit)z & PyLong_MASK; - zhi = (sdigit)Py_ARITHMETIC_RIGHT_SHIFT(stwodigits, - z, PyLong_SHIFT); - } - - /* add w back if q was too large (this branch taken rarely) */ - assert((sdigit)vtop + zhi == -1 || (sdigit)vtop + zhi == 0); - if ((sdigit)vtop + zhi < 0) { - carry = 0; - for (i = 0; i < size_w; ++i) { - carry += vk[i] + w0[i]; - vk[i] = carry & PyLong_MASK; - carry >>= PyLong_SHIFT; - } - --q; - } - - /* store quotient digit */ - assert(q < PyLong_BASE); - *--ak = q; - } - - /* unshift remainder; we reuse w to store the result */ - carry = v_rshift(w0, v0, size_w, d); - assert(carry==0); - Py_DECREF(v); + PyLongObject *v, *w, *a; + Py_ssize_t i, k, size_v, size_w; + int d; + digit wm1, wm2, carry, q, r, vtop, *v0, *vk, *w0, *ak; + twodigits vv; + sdigit zhi; + stwodigits z; + + /* We follow Knuth [The Art of Computer Programming, Vol. 2 (3rd + edn.), section 4.3.1, Algorithm D], except that we don't explicitly + handle the special case when the initial estimate q for a quotient + digit is >= PyLong_BASE: the max value for q is PyLong_BASE+1, and + that won't overflow a digit. */ + + /* allocate space; w will also be used to hold the final remainder */ + size_v = ABS(Py_SIZE(v1)); + size_w = ABS(Py_SIZE(w1)); + assert(size_v >= size_w && size_w >= 2); /* Assert checks by div() */ + v = _PyLong_New(size_v+1); + if (v == NULL) { + *prem = NULL; + return NULL; + } + w = _PyLong_New(size_w); + if (w == NULL) { + Py_DECREF(v); + *prem = NULL; + return NULL; + } + + /* normalize: shift w1 left so that its top digit is >= PyLong_BASE/2. + shift v1 left by the same amount. Results go into w and v. */ + d = PyLong_SHIFT - bits_in_digit(w1->ob_digit[size_w-1]); + carry = v_lshift(w->ob_digit, w1->ob_digit, size_w, d); + assert(carry == 0); + carry = v_lshift(v->ob_digit, v1->ob_digit, size_v, d); + if (carry != 0 || v->ob_digit[size_v-1] >= w->ob_digit[size_w-1]) { + v->ob_digit[size_v] = carry; + size_v++; + } + + /* Now v->ob_digit[size_v-1] < w->ob_digit[size_w-1], so quotient has + at most (and usually exactly) k = size_v - size_w digits. */ + k = size_v - size_w; + assert(k >= 0); + a = _PyLong_New(k); + if (a == NULL) { + Py_DECREF(w); + Py_DECREF(v); + *prem = NULL; + return NULL; + } + v0 = v->ob_digit; + w0 = w->ob_digit; + wm1 = w0[size_w-1]; + wm2 = w0[size_w-2]; + for (vk = v0+k, ak = a->ob_digit + k; vk-- > v0;) { + /* inner loop: divide vk[0:size_w+1] by w0[0:size_w], giving + single-digit quotient q, remainder in vk[0:size_w]. */ + + SIGCHECK({ + Py_DECREF(a); + Py_DECREF(w); + Py_DECREF(v); + *prem = NULL; + return NULL; + }) + + /* estimate quotient digit q; may overestimate by 1 (rare) */ + vtop = vk[size_w]; + assert(vtop <= wm1); + vv = ((twodigits)vtop << PyLong_SHIFT) | vk[size_w-1]; + q = (digit)(vv / wm1); + r = (digit)(vv - (twodigits)wm1 * q); /* r = vv % wm1 */ + while ((twodigits)wm2 * q > (((twodigits)r << PyLong_SHIFT) + | vk[size_w-2])) { + --q; + r += wm1; + if (r >= PyLong_BASE) + break; + } + assert(q <= PyLong_BASE); + + /* subtract q*w0[0:size_w] from vk[0:size_w+1] */ + zhi = 0; + for (i = 0; i < size_w; ++i) { + /* invariants: -PyLong_BASE <= -q <= zhi <= 0; + -PyLong_BASE * q <= z < PyLong_BASE */ + z = (sdigit)vk[i] + zhi - + (stwodigits)q * (stwodigits)w0[i]; + vk[i] = (digit)z & PyLong_MASK; + zhi = (sdigit)Py_ARITHMETIC_RIGHT_SHIFT(stwodigits, + z, PyLong_SHIFT); + } + + /* add w back if q was too large (this branch taken rarely) */ + assert((sdigit)vtop + zhi == -1 || (sdigit)vtop + zhi == 0); + if ((sdigit)vtop + zhi < 0) { + carry = 0; + for (i = 0; i < size_w; ++i) { + carry += vk[i] + w0[i]; + vk[i] = carry & PyLong_MASK; + carry >>= PyLong_SHIFT; + } + --q; + } + + /* store quotient digit */ + assert(q < PyLong_BASE); + *--ak = q; + } + + /* unshift remainder; we reuse w to store the result */ + carry = v_rshift(w0, v0, size_w, d); + assert(carry==0); + Py_DECREF(v); - *prem = long_normalize(w); - return long_normalize(a); + *prem = long_normalize(w); + return long_normalize(a); } /* Methods */ @@ -2411,121 +2411,121 @@ static void long_dealloc(PyObject *v) { - Py_TYPE(v)->tp_free(v); + Py_TYPE(v)->tp_free(v); } static PyObject * long_repr(PyObject *v) { - return _PyLong_Format(v, 10); + return _PyLong_Format(v, 10); } static int long_compare(PyLongObject *a, PyLongObject *b) { - Py_ssize_t sign; + Py_ssize_t sign; - if (Py_SIZE(a) != Py_SIZE(b)) { - if (ABS(Py_SIZE(a)) == 0 && ABS(Py_SIZE(b)) == 0) - sign = 0; - else - sign = Py_SIZE(a) - Py_SIZE(b); - } - else { - Py_ssize_t i = ABS(Py_SIZE(a)); - while (--i >= 0 && a->ob_digit[i] == b->ob_digit[i]) - ; - if (i < 0) - sign = 0; - else { - sign = (sdigit)a->ob_digit[i] - (sdigit)b->ob_digit[i]; - if (Py_SIZE(a) < 0) - sign = -sign; - } - } - return sign < 0 ? -1 : sign > 0 ? 1 : 0; + if (Py_SIZE(a) != Py_SIZE(b)) { + if (ABS(Py_SIZE(a)) == 0 && ABS(Py_SIZE(b)) == 0) + sign = 0; + else + sign = Py_SIZE(a) - Py_SIZE(b); + } + else { + Py_ssize_t i = ABS(Py_SIZE(a)); + while (--i >= 0 && a->ob_digit[i] == b->ob_digit[i]) + ; + if (i < 0) + sign = 0; + else { + sign = (sdigit)a->ob_digit[i] - (sdigit)b->ob_digit[i]; + if (Py_SIZE(a) < 0) + sign = -sign; + } + } + return sign < 0 ? -1 : sign > 0 ? 1 : 0; } #define TEST_COND(cond) \ - ((cond) ? Py_True : Py_False) + ((cond) ? Py_True : Py_False) static PyObject * long_richcompare(PyObject *self, PyObject *other, int op) { - int result; - PyObject *v; - CHECK_BINOP(self, other); - if (self == other) - result = 0; - else - result = long_compare((PyLongObject*)self, (PyLongObject*)other); - /* Convert the return value to a Boolean */ - switch (op) { - case Py_EQ: - v = TEST_COND(result == 0); - break; - case Py_NE: - v = TEST_COND(result != 0); - break; - case Py_LE: - v = TEST_COND(result <= 0); - break; - case Py_GE: - v = TEST_COND(result >= 0); - break; - case Py_LT: - v = TEST_COND(result == -1); - break; - case Py_GT: - v = TEST_COND(result == 1); - break; - default: - PyErr_BadArgument(); - return NULL; - } - Py_INCREF(v); - return v; + int result; + PyObject *v; + CHECK_BINOP(self, other); + if (self == other) + result = 0; + else + result = long_compare((PyLongObject*)self, (PyLongObject*)other); + /* Convert the return value to a Boolean */ + switch (op) { + case Py_EQ: + v = TEST_COND(result == 0); + break; + case Py_NE: + v = TEST_COND(result != 0); + break; + case Py_LE: + v = TEST_COND(result <= 0); + break; + case Py_GE: + v = TEST_COND(result >= 0); + break; + case Py_LT: + v = TEST_COND(result == -1); + break; + case Py_GT: + v = TEST_COND(result == 1); + break; + default: + PyErr_BadArgument(); + return NULL; + } + Py_INCREF(v); + return v; } static long long_hash(PyLongObject *v) { - unsigned long x; - Py_ssize_t i; - int sign; - - /* This is designed so that Python ints and longs with the - same value hash to the same value, otherwise comparisons - of mapping keys will turn out weird */ - i = Py_SIZE(v); - switch(i) { - case -1: return v->ob_digit[0]==1 ? -2 : -(sdigit)v->ob_digit[0]; - case 0: return 0; - case 1: return v->ob_digit[0]; - } - sign = 1; - x = 0; - if (i < 0) { - sign = -1; - i = -(i); - } - /* The following loop produces a C unsigned long x such that x is - congruent to the absolute value of v modulo ULONG_MAX. The - resulting x is nonzero if and only if v is. */ - while (--i >= 0) { - /* Force a native long #-bits (32 or 64) circular shift */ - x = (x >> (8*SIZEOF_LONG-PyLong_SHIFT)) | (x << PyLong_SHIFT); - x += v->ob_digit[i]; - /* If the addition above overflowed we compensate by - incrementing. This preserves the value modulo - ULONG_MAX. */ - if (x < v->ob_digit[i]) - x++; - } - x = x * sign; - if (x == (unsigned long)-1) - x = (unsigned long)-2; - return (long)x; + unsigned long x; + Py_ssize_t i; + int sign; + + /* This is designed so that Python ints and longs with the + same value hash to the same value, otherwise comparisons + of mapping keys will turn out weird */ + i = Py_SIZE(v); + switch(i) { + case -1: return v->ob_digit[0]==1 ? -2 : -(sdigit)v->ob_digit[0]; + case 0: return 0; + case 1: return v->ob_digit[0]; + } + sign = 1; + x = 0; + if (i < 0) { + sign = -1; + i = -(i); + } + /* The following loop produces a C unsigned long x such that x is + congruent to the absolute value of v modulo ULONG_MAX. The + resulting x is nonzero if and only if v is. */ + while (--i >= 0) { + /* Force a native long #-bits (32 or 64) circular shift */ + x = (x >> (8*SIZEOF_LONG-PyLong_SHIFT)) | (x << PyLong_SHIFT); + x += v->ob_digit[i]; + /* If the addition above overflowed we compensate by + incrementing. This preserves the value modulo + ULONG_MAX. */ + if (x < v->ob_digit[i]) + x++; + } + x = x * sign; + if (x == (unsigned long)-1) + x = (unsigned long)-2; + return (long)x; } @@ -2534,33 +2534,33 @@ static PyLongObject * x_add(PyLongObject *a, PyLongObject *b) { - Py_ssize_t size_a = ABS(Py_SIZE(a)), size_b = ABS(Py_SIZE(b)); - PyLongObject *z; - Py_ssize_t i; - digit carry = 0; - - /* Ensure a is the larger of the two: */ - if (size_a < size_b) { - { PyLongObject *temp = a; a = b; b = temp; } - { Py_ssize_t size_temp = size_a; - size_a = size_b; - size_b = size_temp; } - } - z = _PyLong_New(size_a+1); - if (z == NULL) - return NULL; - for (i = 0; i < size_b; ++i) { - carry += a->ob_digit[i] + b->ob_digit[i]; - z->ob_digit[i] = carry & PyLong_MASK; - carry >>= PyLong_SHIFT; - } - for (; i < size_a; ++i) { - carry += a->ob_digit[i]; - z->ob_digit[i] = carry & PyLong_MASK; - carry >>= PyLong_SHIFT; - } - z->ob_digit[i] = carry; - return long_normalize(z); + Py_ssize_t size_a = ABS(Py_SIZE(a)), size_b = ABS(Py_SIZE(b)); + PyLongObject *z; + Py_ssize_t i; + digit carry = 0; + + /* Ensure a is the larger of the two: */ + if (size_a < size_b) { + { PyLongObject *temp = a; a = b; b = temp; } + { Py_ssize_t size_temp = size_a; + size_a = size_b; + size_b = size_temp; } + } + z = _PyLong_New(size_a+1); + if (z == NULL) + return NULL; + for (i = 0; i < size_b; ++i) { + carry += a->ob_digit[i] + b->ob_digit[i]; + z->ob_digit[i] = carry & PyLong_MASK; + carry >>= PyLong_SHIFT; + } + for (; i < size_a; ++i) { + carry += a->ob_digit[i]; + z->ob_digit[i] = carry & PyLong_MASK; + carry >>= PyLong_SHIFT; + } + z->ob_digit[i] = carry; + return long_normalize(z); } /* Subtract the absolute values of two integers. */ @@ -2568,113 +2568,113 @@ static PyLongObject * x_sub(PyLongObject *a, PyLongObject *b) { - Py_ssize_t size_a = ABS(Py_SIZE(a)), size_b = ABS(Py_SIZE(b)); - PyLongObject *z; - Py_ssize_t i; - int sign = 1; - digit borrow = 0; - - /* Ensure a is the larger of the two: */ - if (size_a < size_b) { - sign = -1; - { PyLongObject *temp = a; a = b; b = temp; } - { Py_ssize_t size_temp = size_a; - size_a = size_b; - size_b = size_temp; } - } - else if (size_a == size_b) { - /* Find highest digit where a and b differ: */ - i = size_a; - while (--i >= 0 && a->ob_digit[i] == b->ob_digit[i]) - ; - if (i < 0) - return (PyLongObject *)PyLong_FromLong(0); - if (a->ob_digit[i] < b->ob_digit[i]) { - sign = -1; - { PyLongObject *temp = a; a = b; b = temp; } - } - size_a = size_b = i+1; - } - z = _PyLong_New(size_a); - if (z == NULL) - return NULL; - for (i = 0; i < size_b; ++i) { - /* The following assumes unsigned arithmetic - works module 2**N for some N>PyLong_SHIFT. */ - borrow = a->ob_digit[i] - b->ob_digit[i] - borrow; - z->ob_digit[i] = borrow & PyLong_MASK; - borrow >>= PyLong_SHIFT; - borrow &= 1; /* Keep only one sign bit */ - } - for (; i < size_a; ++i) { - borrow = a->ob_digit[i] - borrow; - z->ob_digit[i] = borrow & PyLong_MASK; - borrow >>= PyLong_SHIFT; - borrow &= 1; /* Keep only one sign bit */ - } - assert(borrow == 0); - if (sign < 0) - NEGATE(z); - return long_normalize(z); + Py_ssize_t size_a = ABS(Py_SIZE(a)), size_b = ABS(Py_SIZE(b)); + PyLongObject *z; + Py_ssize_t i; + int sign = 1; + digit borrow = 0; + + /* Ensure a is the larger of the two: */ + if (size_a < size_b) { + sign = -1; + { PyLongObject *temp = a; a = b; b = temp; } + { Py_ssize_t size_temp = size_a; + size_a = size_b; + size_b = size_temp; } + } + else if (size_a == size_b) { + /* Find highest digit where a and b differ: */ + i = size_a; + while (--i >= 0 && a->ob_digit[i] == b->ob_digit[i]) + ; + if (i < 0) + return (PyLongObject *)PyLong_FromLong(0); + if (a->ob_digit[i] < b->ob_digit[i]) { + sign = -1; + { PyLongObject *temp = a; a = b; b = temp; } + } + size_a = size_b = i+1; + } + z = _PyLong_New(size_a); + if (z == NULL) + return NULL; + for (i = 0; i < size_b; ++i) { + /* The following assumes unsigned arithmetic + works module 2**N for some N>PyLong_SHIFT. */ + borrow = a->ob_digit[i] - b->ob_digit[i] - borrow; + z->ob_digit[i] = borrow & PyLong_MASK; + borrow >>= PyLong_SHIFT; + borrow &= 1; /* Keep only one sign bit */ + } + for (; i < size_a; ++i) { + borrow = a->ob_digit[i] - borrow; + z->ob_digit[i] = borrow & PyLong_MASK; + borrow >>= PyLong_SHIFT; + borrow &= 1; /* Keep only one sign bit */ + } + assert(borrow == 0); + if (sign < 0) + NEGATE(z); + return long_normalize(z); } static PyObject * long_add(PyLongObject *a, PyLongObject *b) { - PyLongObject *z; + PyLongObject *z; - CHECK_BINOP(a, b); + CHECK_BINOP(a, b); - if (ABS(Py_SIZE(a)) <= 1 && ABS(Py_SIZE(b)) <= 1) { - PyObject *result = PyLong_FromLong(MEDIUM_VALUE(a) + - MEDIUM_VALUE(b)); - return result; - } - if (Py_SIZE(a) < 0) { - if (Py_SIZE(b) < 0) { - z = x_add(a, b); - if (z != NULL && Py_SIZE(z) != 0) - Py_SIZE(z) = -(Py_SIZE(z)); - } - else - z = x_sub(b, a); - } - else { - if (Py_SIZE(b) < 0) - z = x_sub(a, b); - else - z = x_add(a, b); - } - return (PyObject *)z; + if (ABS(Py_SIZE(a)) <= 1 && ABS(Py_SIZE(b)) <= 1) { + PyObject *result = PyLong_FromLong(MEDIUM_VALUE(a) + + MEDIUM_VALUE(b)); + return result; + } + if (Py_SIZE(a) < 0) { + if (Py_SIZE(b) < 0) { + z = x_add(a, b); + if (z != NULL && Py_SIZE(z) != 0) + Py_SIZE(z) = -(Py_SIZE(z)); + } + else + z = x_sub(b, a); + } + else { + if (Py_SIZE(b) < 0) + z = x_sub(a, b); + else + z = x_add(a, b); + } + return (PyObject *)z; } static PyObject * long_sub(PyLongObject *a, PyLongObject *b) { - PyLongObject *z; + PyLongObject *z; - CHECK_BINOP(a, b); + CHECK_BINOP(a, b); - if (ABS(Py_SIZE(a)) <= 1 && ABS(Py_SIZE(b)) <= 1) { - PyObject* r; - r = PyLong_FromLong(MEDIUM_VALUE(a)-MEDIUM_VALUE(b)); - return r; - } - if (Py_SIZE(a) < 0) { - if (Py_SIZE(b) < 0) - z = x_sub(a, b); - else - z = x_add(a, b); - if (z != NULL && Py_SIZE(z) != 0) - Py_SIZE(z) = -(Py_SIZE(z)); - } - else { - if (Py_SIZE(b) < 0) - z = x_add(a, b); - else - z = x_sub(a, b); - } - return (PyObject *)z; + if (ABS(Py_SIZE(a)) <= 1 && ABS(Py_SIZE(b)) <= 1) { + PyObject* r; + r = PyLong_FromLong(MEDIUM_VALUE(a)-MEDIUM_VALUE(b)); + return r; + } + if (Py_SIZE(a) < 0) { + if (Py_SIZE(b) < 0) + z = x_sub(a, b); + else + z = x_add(a, b); + if (z != NULL && Py_SIZE(z) != 0) + Py_SIZE(z) = -(Py_SIZE(z)); + } + else { + if (Py_SIZE(b) < 0) + z = x_add(a, b); + else + z = x_sub(a, b); + } + return (PyObject *)z; } /* Grade school multiplication, ignoring the signs. @@ -2683,85 +2683,85 @@ static PyLongObject * x_mul(PyLongObject *a, PyLongObject *b) { - PyLongObject *z; - Py_ssize_t size_a = ABS(Py_SIZE(a)); - Py_ssize_t size_b = ABS(Py_SIZE(b)); - Py_ssize_t i; - - z = _PyLong_New(size_a + size_b); - if (z == NULL) - return NULL; - - memset(z->ob_digit, 0, Py_SIZE(z) * sizeof(digit)); - if (a == b) { - /* Efficient squaring per HAC, Algorithm 14.16: - * http://www.cacr.math.uwaterloo.ca/hac/about/chap14.pdf - * Gives slightly less than a 2x speedup when a == b, - * via exploiting that each entry in the multiplication - * pyramid appears twice (except for the size_a squares). - */ - for (i = 0; i < size_a; ++i) { - twodigits carry; - twodigits f = a->ob_digit[i]; - digit *pz = z->ob_digit + (i << 1); - digit *pa = a->ob_digit + i + 1; - digit *paend = a->ob_digit + size_a; - - SIGCHECK({ - Py_DECREF(z); - return NULL; - }) - - carry = *pz + f * f; - *pz++ = (digit)(carry & PyLong_MASK); - carry >>= PyLong_SHIFT; - assert(carry <= PyLong_MASK); - - /* Now f is added in twice in each column of the - * pyramid it appears. Same as adding f<<1 once. - */ - f <<= 1; - while (pa < paend) { - carry += *pz + *pa++ * f; - *pz++ = (digit)(carry & PyLong_MASK); - carry >>= PyLong_SHIFT; - assert(carry <= (PyLong_MASK << 1)); - } - if (carry) { - carry += *pz; - *pz++ = (digit)(carry & PyLong_MASK); - carry >>= PyLong_SHIFT; - } - if (carry) - *pz += (digit)(carry & PyLong_MASK); - assert((carry >> PyLong_SHIFT) == 0); - } - } - else { /* a is not the same as b -- gradeschool long mult */ - for (i = 0; i < size_a; ++i) { - twodigits carry = 0; - twodigits f = a->ob_digit[i]; - digit *pz = z->ob_digit + i; - digit *pb = b->ob_digit; - digit *pbend = b->ob_digit + size_b; - - SIGCHECK({ - Py_DECREF(z); - return NULL; - }) - - while (pb < pbend) { - carry += *pz + *pb++ * f; - *pz++ = (digit)(carry & PyLong_MASK); - carry >>= PyLong_SHIFT; - assert(carry <= PyLong_MASK); - } - if (carry) - *pz += (digit)(carry & PyLong_MASK); - assert((carry >> PyLong_SHIFT) == 0); - } - } - return long_normalize(z); + PyLongObject *z; + Py_ssize_t size_a = ABS(Py_SIZE(a)); + Py_ssize_t size_b = ABS(Py_SIZE(b)); + Py_ssize_t i; + + z = _PyLong_New(size_a + size_b); + if (z == NULL) + return NULL; + + memset(z->ob_digit, 0, Py_SIZE(z) * sizeof(digit)); + if (a == b) { + /* Efficient squaring per HAC, Algorithm 14.16: + * http://www.cacr.math.uwaterloo.ca/hac/about/chap14.pdf + * Gives slightly less than a 2x speedup when a == b, + * via exploiting that each entry in the multiplication + * pyramid appears twice (except for the size_a squares). + */ + for (i = 0; i < size_a; ++i) { + twodigits carry; + twodigits f = a->ob_digit[i]; + digit *pz = z->ob_digit + (i << 1); + digit *pa = a->ob_digit + i + 1; + digit *paend = a->ob_digit + size_a; + + SIGCHECK({ + Py_DECREF(z); + return NULL; + }) + + carry = *pz + f * f; + *pz++ = (digit)(carry & PyLong_MASK); + carry >>= PyLong_SHIFT; + assert(carry <= PyLong_MASK); + + /* Now f is added in twice in each column of the + * pyramid it appears. Same as adding f<<1 once. + */ + f <<= 1; + while (pa < paend) { + carry += *pz + *pa++ * f; + *pz++ = (digit)(carry & PyLong_MASK); + carry >>= PyLong_SHIFT; + assert(carry <= (PyLong_MASK << 1)); + } + if (carry) { + carry += *pz; + *pz++ = (digit)(carry & PyLong_MASK); + carry >>= PyLong_SHIFT; + } + if (carry) + *pz += (digit)(carry & PyLong_MASK); + assert((carry >> PyLong_SHIFT) == 0); + } + } + else { /* a is not the same as b -- gradeschool long mult */ + for (i = 0; i < size_a; ++i) { + twodigits carry = 0; + twodigits f = a->ob_digit[i]; + digit *pz = z->ob_digit + i; + digit *pb = b->ob_digit; + digit *pbend = b->ob_digit + size_b; + + SIGCHECK({ + Py_DECREF(z); + return NULL; + }) + + while (pb < pbend) { + carry += *pz + *pb++ * f; + *pz++ = (digit)(carry & PyLong_MASK); + carry >>= PyLong_SHIFT; + assert(carry <= PyLong_MASK); + } + if (carry) + *pz += (digit)(carry & PyLong_MASK); + assert((carry >> PyLong_SHIFT) == 0); + } + } + return long_normalize(z); } /* A helper for Karatsuba multiplication (k_mul). @@ -2774,26 +2774,26 @@ static int kmul_split(PyLongObject *n, Py_ssize_t size, PyLongObject **high, PyLongObject **low) { - PyLongObject *hi, *lo; - Py_ssize_t size_lo, size_hi; - const Py_ssize_t size_n = ABS(Py_SIZE(n)); - - size_lo = MIN(size_n, size); - size_hi = size_n - size_lo; - - if ((hi = _PyLong_New(size_hi)) == NULL) - return -1; - if ((lo = _PyLong_New(size_lo)) == NULL) { - Py_DECREF(hi); - return -1; - } - - memcpy(lo->ob_digit, n->ob_digit, size_lo * sizeof(digit)); - memcpy(hi->ob_digit, n->ob_digit + size_lo, size_hi * sizeof(digit)); - - *high = long_normalize(hi); - *low = long_normalize(lo); - return 0; + PyLongObject *hi, *lo; + Py_ssize_t size_lo, size_hi; + const Py_ssize_t size_n = ABS(Py_SIZE(n)); + + size_lo = MIN(size_n, size); + size_hi = size_n - size_lo; + + if ((hi = _PyLong_New(size_hi)) == NULL) + return -1; + if ((lo = _PyLong_New(size_lo)) == NULL) { + Py_DECREF(hi); + return -1; + } + + memcpy(lo->ob_digit, n->ob_digit, size_lo * sizeof(digit)); + memcpy(hi->ob_digit, n->ob_digit + size_lo, size_hi * sizeof(digit)); + + *high = long_normalize(hi); + *low = long_normalize(lo); + return 0; } static PyLongObject *k_lopsided_mul(PyLongObject *a, PyLongObject *b); @@ -2805,169 +2805,169 @@ static PyLongObject * k_mul(PyLongObject *a, PyLongObject *b) { - Py_ssize_t asize = ABS(Py_SIZE(a)); - Py_ssize_t bsize = ABS(Py_SIZE(b)); - PyLongObject *ah = NULL; - PyLongObject *al = NULL; - PyLongObject *bh = NULL; - PyLongObject *bl = NULL; - PyLongObject *ret = NULL; - PyLongObject *t1, *t2, *t3; - Py_ssize_t shift; /* the number of digits we split off */ - Py_ssize_t i; - - /* (ah*X+al)(bh*X+bl) = ah*bh*X*X + (ah*bl + al*bh)*X + al*bl - * Let k = (ah+al)*(bh+bl) = ah*bl + al*bh + ah*bh + al*bl - * Then the original product is - * ah*bh*X*X + (k - ah*bh - al*bl)*X + al*bl - * By picking X to be a power of 2, "*X" is just shifting, and it's - * been reduced to 3 multiplies on numbers half the size. - */ - - /* We want to split based on the larger number; fiddle so that b - * is largest. - */ - if (asize > bsize) { - t1 = a; - a = b; - b = t1; - - i = asize; - asize = bsize; - bsize = i; - } - - /* Use gradeschool math when either number is too small. */ - i = a == b ? KARATSUBA_SQUARE_CUTOFF : KARATSUBA_CUTOFF; - if (asize <= i) { - if (asize == 0) - return (PyLongObject *)PyLong_FromLong(0); - else - return x_mul(a, b); - } - - /* If a is small compared to b, splitting on b gives a degenerate - * case with ah==0, and Karatsuba may be (even much) less efficient - * than "grade school" then. However, we can still win, by viewing - * b as a string of "big digits", each of width a->ob_size. That - * leads to a sequence of balanced calls to k_mul. - */ - if (2 * asize <= bsize) - return k_lopsided_mul(a, b); - - /* Split a & b into hi & lo pieces. */ - shift = bsize >> 1; - if (kmul_split(a, shift, &ah, &al) < 0) goto fail; - assert(Py_SIZE(ah) > 0); /* the split isn't degenerate */ - - if (a == b) { - bh = ah; - bl = al; - Py_INCREF(bh); - Py_INCREF(bl); - } - else if (kmul_split(b, shift, &bh, &bl) < 0) goto fail; - - /* The plan: - * 1. Allocate result space (asize + bsize digits: that's always - * enough). - * 2. Compute ah*bh, and copy into result at 2*shift. - * 3. Compute al*bl, and copy into result at 0. Note that this - * can't overlap with #2. - * 4. Subtract al*bl from the result, starting at shift. This may - * underflow (borrow out of the high digit), but we don't care: - * we're effectively doing unsigned arithmetic mod - * BASE**(sizea + sizeb), and so long as the *final* result fits, - * borrows and carries out of the high digit can be ignored. - * 5. Subtract ah*bh from the result, starting at shift. - * 6. Compute (ah+al)*(bh+bl), and add it into the result starting - * at shift. - */ - - /* 1. Allocate result space. */ - ret = _PyLong_New(asize + bsize); - if (ret == NULL) goto fail; + Py_ssize_t asize = ABS(Py_SIZE(a)); + Py_ssize_t bsize = ABS(Py_SIZE(b)); + PyLongObject *ah = NULL; + PyLongObject *al = NULL; + PyLongObject *bh = NULL; + PyLongObject *bl = NULL; + PyLongObject *ret = NULL; + PyLongObject *t1, *t2, *t3; + Py_ssize_t shift; /* the number of digits we split off */ + Py_ssize_t i; + + /* (ah*X+al)(bh*X+bl) = ah*bh*X*X + (ah*bl + al*bh)*X + al*bl + * Let k = (ah+al)*(bh+bl) = ah*bl + al*bh + ah*bh + al*bl + * Then the original product is + * ah*bh*X*X + (k - ah*bh - al*bl)*X + al*bl + * By picking X to be a power of 2, "*X" is just shifting, and it's + * been reduced to 3 multiplies on numbers half the size. + */ + + /* We want to split based on the larger number; fiddle so that b + * is largest. + */ + if (asize > bsize) { + t1 = a; + a = b; + b = t1; + + i = asize; + asize = bsize; + bsize = i; + } + + /* Use gradeschool math when either number is too small. */ + i = a == b ? KARATSUBA_SQUARE_CUTOFF : KARATSUBA_CUTOFF; + if (asize <= i) { + if (asize == 0) + return (PyLongObject *)PyLong_FromLong(0); + else + return x_mul(a, b); + } + + /* If a is small compared to b, splitting on b gives a degenerate + * case with ah==0, and Karatsuba may be (even much) less efficient + * than "grade school" then. However, we can still win, by viewing + * b as a string of "big digits", each of width a->ob_size. That + * leads to a sequence of balanced calls to k_mul. + */ + if (2 * asize <= bsize) + return k_lopsided_mul(a, b); + + /* Split a & b into hi & lo pieces. */ + shift = bsize >> 1; + if (kmul_split(a, shift, &ah, &al) < 0) goto fail; + assert(Py_SIZE(ah) > 0); /* the split isn't degenerate */ + + if (a == b) { + bh = ah; + bl = al; + Py_INCREF(bh); + Py_INCREF(bl); + } + else if (kmul_split(b, shift, &bh, &bl) < 0) goto fail; + + /* The plan: + * 1. Allocate result space (asize + bsize digits: that's always + * enough). + * 2. Compute ah*bh, and copy into result at 2*shift. + * 3. Compute al*bl, and copy into result at 0. Note that this + * can't overlap with #2. + * 4. Subtract al*bl from the result, starting at shift. This may + * underflow (borrow out of the high digit), but we don't care: + * we're effectively doing unsigned arithmetic mod + * BASE**(sizea + sizeb), and so long as the *final* result fits, + * borrows and carries out of the high digit can be ignored. + * 5. Subtract ah*bh from the result, starting at shift. + * 6. Compute (ah+al)*(bh+bl), and add it into the result starting + * at shift. + */ + + /* 1. Allocate result space. */ + ret = _PyLong_New(asize + bsize); + if (ret == NULL) goto fail; #ifdef Py_DEBUG - /* Fill with trash, to catch reference to uninitialized digits. */ - memset(ret->ob_digit, 0xDF, Py_SIZE(ret) * sizeof(digit)); + /* Fill with trash, to catch reference to uninitialized digits. */ + memset(ret->ob_digit, 0xDF, Py_SIZE(ret) * sizeof(digit)); #endif - /* 2. t1 <- ah*bh, and copy into high digits of result. */ - if ((t1 = k_mul(ah, bh)) == NULL) goto fail; - assert(Py_SIZE(t1) >= 0); - assert(2*shift + Py_SIZE(t1) <= Py_SIZE(ret)); - memcpy(ret->ob_digit + 2*shift, t1->ob_digit, - Py_SIZE(t1) * sizeof(digit)); - - /* Zero-out the digits higher than the ah*bh copy. */ - i = Py_SIZE(ret) - 2*shift - Py_SIZE(t1); - if (i) - memset(ret->ob_digit + 2*shift + Py_SIZE(t1), 0, - i * sizeof(digit)); - - /* 3. t2 <- al*bl, and copy into the low digits. */ - if ((t2 = k_mul(al, bl)) == NULL) { - Py_DECREF(t1); - goto fail; - } - assert(Py_SIZE(t2) >= 0); - assert(Py_SIZE(t2) <= 2*shift); /* no overlap with high digits */ - memcpy(ret->ob_digit, t2->ob_digit, Py_SIZE(t2) * sizeof(digit)); - - /* Zero out remaining digits. */ - i = 2*shift - Py_SIZE(t2); /* number of uninitialized digits */ - if (i) - memset(ret->ob_digit + Py_SIZE(t2), 0, i * sizeof(digit)); - - /* 4 & 5. Subtract ah*bh (t1) and al*bl (t2). We do al*bl first - * because it's fresher in cache. - */ - i = Py_SIZE(ret) - shift; /* # digits after shift */ - (void)v_isub(ret->ob_digit + shift, i, t2->ob_digit, Py_SIZE(t2)); - Py_DECREF(t2); - - (void)v_isub(ret->ob_digit + shift, i, t1->ob_digit, Py_SIZE(t1)); - Py_DECREF(t1); - - /* 6. t3 <- (ah+al)(bh+bl), and add into result. */ - if ((t1 = x_add(ah, al)) == NULL) goto fail; - Py_DECREF(ah); - Py_DECREF(al); - ah = al = NULL; - - if (a == b) { - t2 = t1; - Py_INCREF(t2); - } - else if ((t2 = x_add(bh, bl)) == NULL) { - Py_DECREF(t1); - goto fail; - } - Py_DECREF(bh); - Py_DECREF(bl); - bh = bl = NULL; - - t3 = k_mul(t1, t2); - Py_DECREF(t1); - Py_DECREF(t2); - if (t3 == NULL) goto fail; - assert(Py_SIZE(t3) >= 0); - - /* Add t3. It's not obvious why we can't run out of room here. - * See the (*) comment after this function. - */ - (void)v_iadd(ret->ob_digit + shift, i, t3->ob_digit, Py_SIZE(t3)); - Py_DECREF(t3); + /* 2. t1 <- ah*bh, and copy into high digits of result. */ + if ((t1 = k_mul(ah, bh)) == NULL) goto fail; + assert(Py_SIZE(t1) >= 0); + assert(2*shift + Py_SIZE(t1) <= Py_SIZE(ret)); + memcpy(ret->ob_digit + 2*shift, t1->ob_digit, + Py_SIZE(t1) * sizeof(digit)); + + /* Zero-out the digits higher than the ah*bh copy. */ + i = Py_SIZE(ret) - 2*shift - Py_SIZE(t1); + if (i) + memset(ret->ob_digit + 2*shift + Py_SIZE(t1), 0, + i * sizeof(digit)); + + /* 3. t2 <- al*bl, and copy into the low digits. */ + if ((t2 = k_mul(al, bl)) == NULL) { + Py_DECREF(t1); + goto fail; + } + assert(Py_SIZE(t2) >= 0); + assert(Py_SIZE(t2) <= 2*shift); /* no overlap with high digits */ + memcpy(ret->ob_digit, t2->ob_digit, Py_SIZE(t2) * sizeof(digit)); + + /* Zero out remaining digits. */ + i = 2*shift - Py_SIZE(t2); /* number of uninitialized digits */ + if (i) + memset(ret->ob_digit + Py_SIZE(t2), 0, i * sizeof(digit)); + + /* 4 & 5. Subtract ah*bh (t1) and al*bl (t2). We do al*bl first + * because it's fresher in cache. + */ + i = Py_SIZE(ret) - shift; /* # digits after shift */ + (void)v_isub(ret->ob_digit + shift, i, t2->ob_digit, Py_SIZE(t2)); + Py_DECREF(t2); + + (void)v_isub(ret->ob_digit + shift, i, t1->ob_digit, Py_SIZE(t1)); + Py_DECREF(t1); + + /* 6. t3 <- (ah+al)(bh+bl), and add into result. */ + if ((t1 = x_add(ah, al)) == NULL) goto fail; + Py_DECREF(ah); + Py_DECREF(al); + ah = al = NULL; + + if (a == b) { + t2 = t1; + Py_INCREF(t2); + } + else if ((t2 = x_add(bh, bl)) == NULL) { + Py_DECREF(t1); + goto fail; + } + Py_DECREF(bh); + Py_DECREF(bl); + bh = bl = NULL; + + t3 = k_mul(t1, t2); + Py_DECREF(t1); + Py_DECREF(t2); + if (t3 == NULL) goto fail; + assert(Py_SIZE(t3) >= 0); + + /* Add t3. It's not obvious why we can't run out of room here. + * See the (*) comment after this function. + */ + (void)v_iadd(ret->ob_digit + shift, i, t3->ob_digit, Py_SIZE(t3)); + Py_DECREF(t3); - return long_normalize(ret); + return long_normalize(ret); fail: - Py_XDECREF(ret); - Py_XDECREF(ah); - Py_XDECREF(al); - Py_XDECREF(bh); - Py_XDECREF(bl); - return NULL; + Py_XDECREF(ret); + Py_XDECREF(ah); + Py_XDECREF(al); + Py_XDECREF(bh); + Py_XDECREF(bl); + return NULL; } /* (*) Why adding t3 can't "run out of room" above. @@ -3026,85 +3026,85 @@ static PyLongObject * k_lopsided_mul(PyLongObject *a, PyLongObject *b) { - const Py_ssize_t asize = ABS(Py_SIZE(a)); - Py_ssize_t bsize = ABS(Py_SIZE(b)); - Py_ssize_t nbdone; /* # of b digits already multiplied */ - PyLongObject *ret; - PyLongObject *bslice = NULL; - - assert(asize > KARATSUBA_CUTOFF); - assert(2 * asize <= bsize); - - /* Allocate result space, and zero it out. */ - ret = _PyLong_New(asize + bsize); - if (ret == NULL) - return NULL; - memset(ret->ob_digit, 0, Py_SIZE(ret) * sizeof(digit)); - - /* Successive slices of b are copied into bslice. */ - bslice = _PyLong_New(asize); - if (bslice == NULL) - goto fail; - - nbdone = 0; - while (bsize > 0) { - PyLongObject *product; - const Py_ssize_t nbtouse = MIN(bsize, asize); - - /* Multiply the next slice of b by a. */ - memcpy(bslice->ob_digit, b->ob_digit + nbdone, - nbtouse * sizeof(digit)); - Py_SIZE(bslice) = nbtouse; - product = k_mul(a, bslice); - if (product == NULL) - goto fail; - - /* Add into result. */ - (void)v_iadd(ret->ob_digit + nbdone, Py_SIZE(ret) - nbdone, - product->ob_digit, Py_SIZE(product)); - Py_DECREF(product); - - bsize -= nbtouse; - nbdone += nbtouse; - } + const Py_ssize_t asize = ABS(Py_SIZE(a)); + Py_ssize_t bsize = ABS(Py_SIZE(b)); + Py_ssize_t nbdone; /* # of b digits already multiplied */ + PyLongObject *ret; + PyLongObject *bslice = NULL; + + assert(asize > KARATSUBA_CUTOFF); + assert(2 * asize <= bsize); + + /* Allocate result space, and zero it out. */ + ret = _PyLong_New(asize + bsize); + if (ret == NULL) + return NULL; + memset(ret->ob_digit, 0, Py_SIZE(ret) * sizeof(digit)); + + /* Successive slices of b are copied into bslice. */ + bslice = _PyLong_New(asize); + if (bslice == NULL) + goto fail; + + nbdone = 0; + while (bsize > 0) { + PyLongObject *product; + const Py_ssize_t nbtouse = MIN(bsize, asize); + + /* Multiply the next slice of b by a. */ + memcpy(bslice->ob_digit, b->ob_digit + nbdone, + nbtouse * sizeof(digit)); + Py_SIZE(bslice) = nbtouse; + product = k_mul(a, bslice); + if (product == NULL) + goto fail; + + /* Add into result. */ + (void)v_iadd(ret->ob_digit + nbdone, Py_SIZE(ret) - nbdone, + product->ob_digit, Py_SIZE(product)); + Py_DECREF(product); + + bsize -= nbtouse; + nbdone += nbtouse; + } - Py_DECREF(bslice); - return long_normalize(ret); + Py_DECREF(bslice); + return long_normalize(ret); fail: - Py_DECREF(ret); - Py_XDECREF(bslice); - return NULL; + Py_DECREF(ret); + Py_XDECREF(bslice); + return NULL; } static PyObject * long_mul(PyLongObject *a, PyLongObject *b) { - PyLongObject *z; + PyLongObject *z; - CHECK_BINOP(a, b); + CHECK_BINOP(a, b); - /* fast path for single-digit multiplication */ - if (ABS(Py_SIZE(a)) <= 1 && ABS(Py_SIZE(b)) <= 1) { - stwodigits v = (stwodigits)(MEDIUM_VALUE(a)) * MEDIUM_VALUE(b); + /* fast path for single-digit multiplication */ + if (ABS(Py_SIZE(a)) <= 1 && ABS(Py_SIZE(b)) <= 1) { + stwodigits v = (stwodigits)(MEDIUM_VALUE(a)) * MEDIUM_VALUE(b); #ifdef HAVE_LONG_LONG - return PyLong_FromLongLong((PY_LONG_LONG)v); + return PyLong_FromLongLong((PY_LONG_LONG)v); #else - /* if we don't have long long then we're almost certainly - using 15-bit digits, so v will fit in a long. In the - unlikely event that we're using 30-bit digits on a platform - without long long, a large v will just cause us to fall - through to the general multiplication code below. */ - if (v >= LONG_MIN && v <= LONG_MAX) - return PyLong_FromLong((long)v); + /* if we don't have long long then we're almost certainly + using 15-bit digits, so v will fit in a long. In the + unlikely event that we're using 30-bit digits on a platform + without long long, a large v will just cause us to fall + through to the general multiplication code below. */ + if (v >= LONG_MIN && v <= LONG_MAX) + return PyLong_FromLong((long)v); #endif - } + } - z = k_mul(a, b); - /* Negate if exactly one of the inputs is negative. */ - if (((Py_SIZE(a) ^ Py_SIZE(b)) < 0) && z) - NEGATE(z); - return (PyObject *)z; + z = k_mul(a, b); + /* Negate if exactly one of the inputs is negative. */ + if (((Py_SIZE(a) ^ Py_SIZE(b)) < 0) && z) + NEGATE(z); + return (PyObject *)z; } /* The / and % operators are now defined in terms of divmod(). @@ -3113,11 +3113,11 @@ |a| by |b|, with the sign of a. This is also expressed as a - b*trunc(a/b), if trunc truncates towards zero. Some examples: - a b a rem b a mod b - 13 10 3 3 - -13 10 -3 7 - 13 -10 3 -7 - -13 -10 -3 -3 + a b a rem b a mod b + 13 10 3 3 + -13 10 -3 7 + 13 -10 3 -7 + -13 -10 -3 -3 So, to get from rem to mod, we have to add b if a and b have different signs. We then subtract one from the 'div' part of the outcome to keep the invariant intact. */ @@ -3130,480 +3130,480 @@ */ static int l_divmod(PyLongObject *v, PyLongObject *w, - PyLongObject **pdiv, PyLongObject **pmod) + PyLongObject **pdiv, PyLongObject **pmod) { - PyLongObject *div, *mod; + PyLongObject *div, *mod; - if (long_divrem(v, w, &div, &mod) < 0) - return -1; - if ((Py_SIZE(mod) < 0 && Py_SIZE(w) > 0) || - (Py_SIZE(mod) > 0 && Py_SIZE(w) < 0)) { - PyLongObject *temp; - PyLongObject *one; - temp = (PyLongObject *) long_add(mod, w); - Py_DECREF(mod); - mod = temp; - if (mod == NULL) { - Py_DECREF(div); - return -1; - } - one = (PyLongObject *) PyLong_FromLong(1L); - if (one == NULL || - (temp = (PyLongObject *) long_sub(div, one)) == NULL) { - Py_DECREF(mod); - Py_DECREF(div); - Py_XDECREF(one); - return -1; - } - Py_DECREF(one); - Py_DECREF(div); - div = temp; - } - if (pdiv != NULL) - *pdiv = div; - else - Py_DECREF(div); - - if (pmod != NULL) - *pmod = mod; - else - Py_DECREF(mod); + if (long_divrem(v, w, &div, &mod) < 0) + return -1; + if ((Py_SIZE(mod) < 0 && Py_SIZE(w) > 0) || + (Py_SIZE(mod) > 0 && Py_SIZE(w) < 0)) { + PyLongObject *temp; + PyLongObject *one; + temp = (PyLongObject *) long_add(mod, w); + Py_DECREF(mod); + mod = temp; + if (mod == NULL) { + Py_DECREF(div); + return -1; + } + one = (PyLongObject *) PyLong_FromLong(1L); + if (one == NULL || + (temp = (PyLongObject *) long_sub(div, one)) == NULL) { + Py_DECREF(mod); + Py_DECREF(div); + Py_XDECREF(one); + return -1; + } + Py_DECREF(one); + Py_DECREF(div); + div = temp; + } + if (pdiv != NULL) + *pdiv = div; + else + Py_DECREF(div); + + if (pmod != NULL) + *pmod = mod; + else + Py_DECREF(mod); - return 0; + return 0; } static PyObject * long_div(PyObject *a, PyObject *b) { - PyLongObject *div; + PyLongObject *div; - CHECK_BINOP(a, b); - if (l_divmod((PyLongObject*)a, (PyLongObject*)b, &div, NULL) < 0) - div = NULL; - return (PyObject *)div; + CHECK_BINOP(a, b); + if (l_divmod((PyLongObject*)a, (PyLongObject*)b, &div, NULL) < 0) + div = NULL; + return (PyObject *)div; } static PyObject * long_true_divide(PyObject *a, PyObject *b) { - double ad, bd; - int failed, aexp = -1, bexp = -1; + double ad, bd; + int failed, aexp = -1, bexp = -1; - CHECK_BINOP(a, b); - ad = _PyLong_AsScaledDouble((PyObject *)a, &aexp); - bd = _PyLong_AsScaledDouble((PyObject *)b, &bexp); - failed = (ad == -1.0 || bd == -1.0) && PyErr_Occurred(); - if (failed) - return NULL; - /* 'aexp' and 'bexp' were initialized to -1 to silence gcc-4.0.x, - but should really be set correctly after sucessful calls to - _PyLong_AsScaledDouble() */ - assert(aexp >= 0 && bexp >= 0); - - if (bd == 0.0) { - PyErr_SetString(PyExc_ZeroDivisionError, - "int division or modulo by zero"); - return NULL; - } - - /* True value is very close to ad/bd * 2**(PyLong_SHIFT*(aexp-bexp)) */ - ad /= bd; /* overflow/underflow impossible here */ - aexp -= bexp; - if (aexp > INT_MAX / PyLong_SHIFT) - goto overflow; - else if (aexp < -(INT_MAX / PyLong_SHIFT)) - return PyFloat_FromDouble(0.0); /* underflow to 0 */ - errno = 0; - ad = ldexp(ad, aexp * PyLong_SHIFT); - if (Py_OVERFLOWED(ad)) /* ignore underflow to 0.0 */ - goto overflow; - return PyFloat_FromDouble(ad); + CHECK_BINOP(a, b); + ad = _PyLong_AsScaledDouble((PyObject *)a, &aexp); + bd = _PyLong_AsScaledDouble((PyObject *)b, &bexp); + failed = (ad == -1.0 || bd == -1.0) && PyErr_Occurred(); + if (failed) + return NULL; + /* 'aexp' and 'bexp' were initialized to -1 to silence gcc-4.0.x, + but should really be set correctly after sucessful calls to + _PyLong_AsScaledDouble() */ + assert(aexp >= 0 && bexp >= 0); + + if (bd == 0.0) { + PyErr_SetString(PyExc_ZeroDivisionError, + "int division or modulo by zero"); + return NULL; + } + + /* True value is very close to ad/bd * 2**(PyLong_SHIFT*(aexp-bexp)) */ + ad /= bd; /* overflow/underflow impossible here */ + aexp -= bexp; + if (aexp > INT_MAX / PyLong_SHIFT) + goto overflow; + else if (aexp < -(INT_MAX / PyLong_SHIFT)) + return PyFloat_FromDouble(0.0); /* underflow to 0 */ + errno = 0; + ad = ldexp(ad, aexp * PyLong_SHIFT); + if (Py_OVERFLOWED(ad)) /* ignore underflow to 0.0 */ + goto overflow; + return PyFloat_FromDouble(ad); overflow: - PyErr_SetString(PyExc_OverflowError, - "int/int too large for a float"); - return NULL; + PyErr_SetString(PyExc_OverflowError, + "int/int too large for a float"); + return NULL; } static PyObject * long_mod(PyObject *a, PyObject *b) { - PyLongObject *mod; - - CHECK_BINOP(a, b); - - if (l_divmod((PyLongObject*)a, (PyLongObject*)b, NULL, &mod) < 0) - mod = NULL; - return (PyObject *)mod; + PyLongObject *mod; + + CHECK_BINOP(a, b); + + if (l_divmod((PyLongObject*)a, (PyLongObject*)b, NULL, &mod) < 0) + mod = NULL; + return (PyObject *)mod; } static PyObject * long_divmod(PyObject *a, PyObject *b) { - PyLongObject *div, *mod; - PyObject *z; + PyLongObject *div, *mod; + PyObject *z; - CHECK_BINOP(a, b); + CHECK_BINOP(a, b); - if (l_divmod((PyLongObject*)a, (PyLongObject*)b, &div, &mod) < 0) { - return NULL; - } - z = PyTuple_New(2); - if (z != NULL) { - PyTuple_SetItem(z, 0, (PyObject *) div); - PyTuple_SetItem(z, 1, (PyObject *) mod); - } - else { - Py_DECREF(div); - Py_DECREF(mod); - } - return z; + if (l_divmod((PyLongObject*)a, (PyLongObject*)b, &div, &mod) < 0) { + return NULL; + } + z = PyTuple_New(2); + if (z != NULL) { + PyTuple_SetItem(z, 0, (PyObject *) div); + PyTuple_SetItem(z, 1, (PyObject *) mod); + } + else { + Py_DECREF(div); + Py_DECREF(mod); + } + return z; } /* pow(v, w, x) */ static PyObject * long_pow(PyObject *v, PyObject *w, PyObject *x) { - PyLongObject *a, *b, *c; /* a,b,c = v,w,x */ - int negativeOutput = 0; /* if x<0 return negative output */ + PyLongObject *a, *b, *c; /* a,b,c = v,w,x */ + int negativeOutput = 0; /* if x<0 return negative output */ - PyLongObject *z = NULL; /* accumulated result */ - Py_ssize_t i, j, k; /* counters */ - PyLongObject *temp = NULL; - - /* 5-ary values. If the exponent is large enough, table is - * precomputed so that table[i] == a**i % c for i in range(32). - */ - PyLongObject *table[32] = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, - 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0}; - - /* a, b, c = v, w, x */ - CHECK_BINOP(v, w); - a = (PyLongObject*)v; Py_INCREF(a); - b = (PyLongObject*)w; Py_INCREF(b); - if (PyLong_Check(x)) { - c = (PyLongObject *)x; - Py_INCREF(x); - } - else if (x == Py_None) - c = NULL; - else { - Py_DECREF(a); - Py_DECREF(b); - Py_INCREF(Py_NotImplemented); - return Py_NotImplemented; - } - - if (Py_SIZE(b) < 0) { /* if exponent is negative */ - if (c) { - PyErr_SetString(PyExc_TypeError, "pow() 2nd argument " - "cannot be negative when 3rd argument specified"); - goto Error; - } - else { - /* else return a float. This works because we know - that this calls float_pow() which converts its - arguments to double. */ - Py_DECREF(a); - Py_DECREF(b); - return PyFloat_Type.tp_as_number->nb_power(v, w, x); - } - } - - if (c) { - /* if modulus == 0: - raise ValueError() */ - if (Py_SIZE(c) == 0) { - PyErr_SetString(PyExc_ValueError, - "pow() 3rd argument cannot be 0"); - goto Error; - } - - /* if modulus < 0: - negativeOutput = True - modulus = -modulus */ - if (Py_SIZE(c) < 0) { - negativeOutput = 1; - temp = (PyLongObject *)_PyLong_Copy(c); - if (temp == NULL) - goto Error; - Py_DECREF(c); - c = temp; - temp = NULL; - NEGATE(c); - } - - /* if modulus == 1: - return 0 */ - if ((Py_SIZE(c) == 1) && (c->ob_digit[0] == 1)) { - z = (PyLongObject *)PyLong_FromLong(0L); - goto Done; - } - - /* if base < 0: - base = base % modulus - Having the base positive just makes things easier. */ - if (Py_SIZE(a) < 0) { - if (l_divmod(a, c, NULL, &temp) < 0) - goto Error; - Py_DECREF(a); - a = temp; - temp = NULL; - } - } - - /* At this point a, b, and c are guaranteed non-negative UNLESS - c is NULL, in which case a may be negative. */ - - z = (PyLongObject *)PyLong_FromLong(1L); - if (z == NULL) - goto Error; - - /* Perform a modular reduction, X = X % c, but leave X alone if c - * is NULL. - */ -#define REDUCE(X) \ - if (c != NULL) { \ - if (l_divmod(X, c, NULL, &temp) < 0) \ - goto Error; \ - Py_XDECREF(X); \ - X = temp; \ - temp = NULL; \ - } - - /* Multiply two values, then reduce the result: - result = X*Y % c. If c is NULL, skip the mod. */ -#define MULT(X, Y, result) \ -{ \ - temp = (PyLongObject *)long_mul(X, Y); \ - if (temp == NULL) \ - goto Error; \ - Py_XDECREF(result); \ - result = temp; \ - temp = NULL; \ - REDUCE(result) \ -} - - if (Py_SIZE(b) <= FIVEARY_CUTOFF) { - /* Left-to-right binary exponentiation (HAC Algorithm 14.79) */ - /* http://www.cacr.math.uwaterloo.ca/hac/about/chap14.pdf */ - for (i = Py_SIZE(b) - 1; i >= 0; --i) { - digit bi = b->ob_digit[i]; - - for (j = (digit)1 << (PyLong_SHIFT-1); j != 0; j >>= 1) { - MULT(z, z, z) - if (bi & j) - MULT(z, a, z) - } - } - } - else { - /* Left-to-right 5-ary exponentiation (HAC Algorithm 14.82) */ - Py_INCREF(z); /* still holds 1L */ - table[0] = z; - for (i = 1; i < 32; ++i) - MULT(table[i-1], a, table[i]) - - for (i = Py_SIZE(b) - 1; i >= 0; --i) { - const digit bi = b->ob_digit[i]; - - for (j = PyLong_SHIFT - 5; j >= 0; j -= 5) { - const int index = (bi >> j) & 0x1f; - for (k = 0; k < 5; ++k) - MULT(z, z, z) - if (index) - MULT(z, table[index], z) - } - } - } - - if (negativeOutput && (Py_SIZE(z) != 0)) { - temp = (PyLongObject *)long_sub(z, c); - if (temp == NULL) - goto Error; - Py_DECREF(z); - z = temp; - temp = NULL; - } - goto Done; + PyLongObject *z = NULL; /* accumulated result */ + Py_ssize_t i, j, k; /* counters */ + PyLongObject *temp = NULL; + + /* 5-ary values. If the exponent is large enough, table is + * precomputed so that table[i] == a**i % c for i in range(32). + */ + PyLongObject *table[32] = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, + 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0}; + + /* a, b, c = v, w, x */ + CHECK_BINOP(v, w); + a = (PyLongObject*)v; Py_INCREF(a); + b = (PyLongObject*)w; Py_INCREF(b); + if (PyLong_Check(x)) { + c = (PyLongObject *)x; + Py_INCREF(x); + } + else if (x == Py_None) + c = NULL; + else { + Py_DECREF(a); + Py_DECREF(b); + Py_INCREF(Py_NotImplemented); + return Py_NotImplemented; + } + + if (Py_SIZE(b) < 0) { /* if exponent is negative */ + if (c) { + PyErr_SetString(PyExc_TypeError, "pow() 2nd argument " + "cannot be negative when 3rd argument specified"); + goto Error; + } + else { + /* else return a float. This works because we know + that this calls float_pow() which converts its + arguments to double. */ + Py_DECREF(a); + Py_DECREF(b); + return PyFloat_Type.tp_as_number->nb_power(v, w, x); + } + } + + if (c) { + /* if modulus == 0: + raise ValueError() */ + if (Py_SIZE(c) == 0) { + PyErr_SetString(PyExc_ValueError, + "pow() 3rd argument cannot be 0"); + goto Error; + } + + /* if modulus < 0: + negativeOutput = True + modulus = -modulus */ + if (Py_SIZE(c) < 0) { + negativeOutput = 1; + temp = (PyLongObject *)_PyLong_Copy(c); + if (temp == NULL) + goto Error; + Py_DECREF(c); + c = temp; + temp = NULL; + NEGATE(c); + } + + /* if modulus == 1: + return 0 */ + if ((Py_SIZE(c) == 1) && (c->ob_digit[0] == 1)) { + z = (PyLongObject *)PyLong_FromLong(0L); + goto Done; + } + + /* if base < 0: + base = base % modulus + Having the base positive just makes things easier. */ + if (Py_SIZE(a) < 0) { + if (l_divmod(a, c, NULL, &temp) < 0) + goto Error; + Py_DECREF(a); + a = temp; + temp = NULL; + } + } + + /* At this point a, b, and c are guaranteed non-negative UNLESS + c is NULL, in which case a may be negative. */ + + z = (PyLongObject *)PyLong_FromLong(1L); + if (z == NULL) + goto Error; + + /* Perform a modular reduction, X = X % c, but leave X alone if c + * is NULL. + */ +#define REDUCE(X) \ + if (c != NULL) { \ + if (l_divmod(X, c, NULL, &temp) < 0) \ + goto Error; \ + Py_XDECREF(X); \ + X = temp; \ + temp = NULL; \ + } + + /* Multiply two values, then reduce the result: + result = X*Y % c. If c is NULL, skip the mod. */ +#define MULT(X, Y, result) \ +{ \ + temp = (PyLongObject *)long_mul(X, Y); \ + if (temp == NULL) \ + goto Error; \ + Py_XDECREF(result); \ + result = temp; \ + temp = NULL; \ + REDUCE(result) \ +} + + if (Py_SIZE(b) <= FIVEARY_CUTOFF) { + /* Left-to-right binary exponentiation (HAC Algorithm 14.79) */ + /* http://www.cacr.math.uwaterloo.ca/hac/about/chap14.pdf */ + for (i = Py_SIZE(b) - 1; i >= 0; --i) { + digit bi = b->ob_digit[i]; + + for (j = (digit)1 << (PyLong_SHIFT-1); j != 0; j >>= 1) { + MULT(z, z, z) + if (bi & j) + MULT(z, a, z) + } + } + } + else { + /* Left-to-right 5-ary exponentiation (HAC Algorithm 14.82) */ + Py_INCREF(z); /* still holds 1L */ + table[0] = z; + for (i = 1; i < 32; ++i) + MULT(table[i-1], a, table[i]) + + for (i = Py_SIZE(b) - 1; i >= 0; --i) { + const digit bi = b->ob_digit[i]; + + for (j = PyLong_SHIFT - 5; j >= 0; j -= 5) { + const int index = (bi >> j) & 0x1f; + for (k = 0; k < 5; ++k) + MULT(z, z, z) + if (index) + MULT(z, table[index], z) + } + } + } + + if (negativeOutput && (Py_SIZE(z) != 0)) { + temp = (PyLongObject *)long_sub(z, c); + if (temp == NULL) + goto Error; + Py_DECREF(z); + z = temp; + temp = NULL; + } + goto Done; Error: - if (z != NULL) { - Py_DECREF(z); - z = NULL; - } - /* fall through */ + if (z != NULL) { + Py_DECREF(z); + z = NULL; + } + /* fall through */ Done: - if (Py_SIZE(b) > FIVEARY_CUTOFF) { - for (i = 0; i < 32; ++i) - Py_XDECREF(table[i]); - } - Py_DECREF(a); - Py_DECREF(b); - Py_XDECREF(c); - Py_XDECREF(temp); - return (PyObject *)z; + if (Py_SIZE(b) > FIVEARY_CUTOFF) { + for (i = 0; i < 32; ++i) + Py_XDECREF(table[i]); + } + Py_DECREF(a); + Py_DECREF(b); + Py_XDECREF(c); + Py_XDECREF(temp); + return (PyObject *)z; } static PyObject * long_invert(PyLongObject *v) { - /* Implement ~x as -(x+1) */ - PyLongObject *x; - PyLongObject *w; - if (ABS(Py_SIZE(v)) <=1) - return PyLong_FromLong(-(MEDIUM_VALUE(v)+1)); - w = (PyLongObject *)PyLong_FromLong(1L); - if (w == NULL) - return NULL; - x = (PyLongObject *) long_add(v, w); - Py_DECREF(w); - if (x == NULL) - return NULL; - Py_SIZE(x) = -(Py_SIZE(x)); - return (PyObject *)maybe_small_long(x); + /* Implement ~x as -(x+1) */ + PyLongObject *x; + PyLongObject *w; + if (ABS(Py_SIZE(v)) <=1) + return PyLong_FromLong(-(MEDIUM_VALUE(v)+1)); + w = (PyLongObject *)PyLong_FromLong(1L); + if (w == NULL) + return NULL; + x = (PyLongObject *) long_add(v, w); + Py_DECREF(w); + if (x == NULL) + return NULL; + Py_SIZE(x) = -(Py_SIZE(x)); + return (PyObject *)maybe_small_long(x); } static PyObject * long_neg(PyLongObject *v) { - PyLongObject *z; - if (ABS(Py_SIZE(v)) <= 1) - return PyLong_FromLong(-MEDIUM_VALUE(v)); - z = (PyLongObject *)_PyLong_Copy(v); - if (z != NULL) - Py_SIZE(z) = -(Py_SIZE(v)); - return (PyObject *)z; + PyLongObject *z; + if (ABS(Py_SIZE(v)) <= 1) + return PyLong_FromLong(-MEDIUM_VALUE(v)); + z = (PyLongObject *)_PyLong_Copy(v); + if (z != NULL) + Py_SIZE(z) = -(Py_SIZE(v)); + return (PyObject *)z; } static PyObject * long_abs(PyLongObject *v) { - if (Py_SIZE(v) < 0) - return long_neg(v); - else - return long_long((PyObject *)v); + if (Py_SIZE(v) < 0) + return long_neg(v); + else + return long_long((PyObject *)v); } static int long_bool(PyLongObject *v) { - return ABS(Py_SIZE(v)) != 0; + return ABS(Py_SIZE(v)) != 0; } static PyObject * long_rshift(PyLongObject *a, PyLongObject *b) { - PyLongObject *z = NULL; - long shiftby; - Py_ssize_t newsize, wordshift, loshift, hishift, i, j; - digit lomask, himask; - - CHECK_BINOP(a, b); - - if (Py_SIZE(a) < 0) { - /* Right shifting negative numbers is harder */ - PyLongObject *a1, *a2; - a1 = (PyLongObject *) long_invert(a); - if (a1 == NULL) - goto rshift_error; - a2 = (PyLongObject *) long_rshift(a1, b); - Py_DECREF(a1); - if (a2 == NULL) - goto rshift_error; - z = (PyLongObject *) long_invert(a2); - Py_DECREF(a2); - } - else { - - shiftby = PyLong_AsLong((PyObject *)b); - if (shiftby == -1L && PyErr_Occurred()) - goto rshift_error; - if (shiftby < 0) { - PyErr_SetString(PyExc_ValueError, - "negative shift count"); - goto rshift_error; - } - wordshift = shiftby / PyLong_SHIFT; - newsize = ABS(Py_SIZE(a)) - wordshift; - if (newsize <= 0) - return PyLong_FromLong(0); - loshift = shiftby % PyLong_SHIFT; - hishift = PyLong_SHIFT - loshift; - lomask = ((digit)1 << hishift) - 1; - himask = PyLong_MASK ^ lomask; - z = _PyLong_New(newsize); - if (z == NULL) - goto rshift_error; - if (Py_SIZE(a) < 0) - Py_SIZE(z) = -(Py_SIZE(z)); - for (i = 0, j = wordshift; i < newsize; i++, j++) { - z->ob_digit[i] = (a->ob_digit[j] >> loshift) & lomask; - if (i+1 < newsize) - z->ob_digit[i] |= - (a->ob_digit[j+1] << hishift) & himask; - } - z = long_normalize(z); - } + PyLongObject *z = NULL; + long shiftby; + Py_ssize_t newsize, wordshift, loshift, hishift, i, j; + digit lomask, himask; + + CHECK_BINOP(a, b); + + if (Py_SIZE(a) < 0) { + /* Right shifting negative numbers is harder */ + PyLongObject *a1, *a2; + a1 = (PyLongObject *) long_invert(a); + if (a1 == NULL) + goto rshift_error; + a2 = (PyLongObject *) long_rshift(a1, b); + Py_DECREF(a1); + if (a2 == NULL) + goto rshift_error; + z = (PyLongObject *) long_invert(a2); + Py_DECREF(a2); + } + else { + + shiftby = PyLong_AsLong((PyObject *)b); + if (shiftby == -1L && PyErr_Occurred()) + goto rshift_error; + if (shiftby < 0) { + PyErr_SetString(PyExc_ValueError, + "negative shift count"); + goto rshift_error; + } + wordshift = shiftby / PyLong_SHIFT; + newsize = ABS(Py_SIZE(a)) - wordshift; + if (newsize <= 0) + return PyLong_FromLong(0); + loshift = shiftby % PyLong_SHIFT; + hishift = PyLong_SHIFT - loshift; + lomask = ((digit)1 << hishift) - 1; + himask = PyLong_MASK ^ lomask; + z = _PyLong_New(newsize); + if (z == NULL) + goto rshift_error; + if (Py_SIZE(a) < 0) + Py_SIZE(z) = -(Py_SIZE(z)); + for (i = 0, j = wordshift; i < newsize; i++, j++) { + z->ob_digit[i] = (a->ob_digit[j] >> loshift) & lomask; + if (i+1 < newsize) + z->ob_digit[i] |= + (a->ob_digit[j+1] << hishift) & himask; + } + z = long_normalize(z); + } rshift_error: - return (PyObject *) maybe_small_long(z); + return (PyObject *) maybe_small_long(z); } static PyObject * long_lshift(PyObject *v, PyObject *w) { - /* This version due to Tim Peters */ - PyLongObject *a = (PyLongObject*)v; - PyLongObject *b = (PyLongObject*)w; - PyLongObject *z = NULL; - long shiftby; - Py_ssize_t oldsize, newsize, wordshift, remshift, i, j; - twodigits accum; - - CHECK_BINOP(a, b); - - shiftby = PyLong_AsLong((PyObject *)b); - if (shiftby == -1L && PyErr_Occurred()) - goto lshift_error; - if (shiftby < 0) { - PyErr_SetString(PyExc_ValueError, "negative shift count"); - goto lshift_error; - } - if ((long)(int)shiftby != shiftby) { - PyErr_SetString(PyExc_ValueError, - "outrageous left shift count"); - goto lshift_error; - } - /* wordshift, remshift = divmod(shiftby, PyLong_SHIFT) */ - wordshift = (int)shiftby / PyLong_SHIFT; - remshift = (int)shiftby - wordshift * PyLong_SHIFT; - - oldsize = ABS(Py_SIZE(a)); - newsize = oldsize + wordshift; - if (remshift) - ++newsize; - z = _PyLong_New(newsize); - if (z == NULL) - goto lshift_error; - if (Py_SIZE(a) < 0) - NEGATE(z); - for (i = 0; i < wordshift; i++) - z->ob_digit[i] = 0; - accum = 0; - for (i = wordshift, j = 0; j < oldsize; i++, j++) { - accum |= (twodigits)a->ob_digit[j] << remshift; - z->ob_digit[i] = (digit)(accum & PyLong_MASK); - accum >>= PyLong_SHIFT; - } - if (remshift) - z->ob_digit[newsize-1] = (digit)accum; - else - assert(!accum); - z = long_normalize(z); + /* This version due to Tim Peters */ + PyLongObject *a = (PyLongObject*)v; + PyLongObject *b = (PyLongObject*)w; + PyLongObject *z = NULL; + long shiftby; + Py_ssize_t oldsize, newsize, wordshift, remshift, i, j; + twodigits accum; + + CHECK_BINOP(a, b); + + shiftby = PyLong_AsLong((PyObject *)b); + if (shiftby == -1L && PyErr_Occurred()) + goto lshift_error; + if (shiftby < 0) { + PyErr_SetString(PyExc_ValueError, "negative shift count"); + goto lshift_error; + } + if ((long)(int)shiftby != shiftby) { + PyErr_SetString(PyExc_ValueError, + "outrageous left shift count"); + goto lshift_error; + } + /* wordshift, remshift = divmod(shiftby, PyLong_SHIFT) */ + wordshift = (int)shiftby / PyLong_SHIFT; + remshift = (int)shiftby - wordshift * PyLong_SHIFT; + + oldsize = ABS(Py_SIZE(a)); + newsize = oldsize + wordshift; + if (remshift) + ++newsize; + z = _PyLong_New(newsize); + if (z == NULL) + goto lshift_error; + if (Py_SIZE(a) < 0) + NEGATE(z); + for (i = 0; i < wordshift; i++) + z->ob_digit[i] = 0; + accum = 0; + for (i = wordshift, j = 0; j < oldsize; i++, j++) { + accum |= (twodigits)a->ob_digit[j] << remshift; + z->ob_digit[i] = (digit)(accum & PyLong_MASK); + accum >>= PyLong_SHIFT; + } + if (remshift) + z->ob_digit[newsize-1] = (digit)accum; + else + assert(!accum); + z = long_normalize(z); lshift_error: - return (PyObject *) maybe_small_long(z); + return (PyObject *) maybe_small_long(z); } @@ -3611,154 +3611,154 @@ static PyObject * long_bitwise(PyLongObject *a, - int op, /* '&', '|', '^' */ - PyLongObject *b) + int op, /* '&', '|', '^' */ + PyLongObject *b) { - digit maska, maskb; /* 0 or PyLong_MASK */ - int negz; - Py_ssize_t size_a, size_b, size_z, i; - PyLongObject *z; - digit diga, digb; - PyObject *v; - - if (Py_SIZE(a) < 0) { - a = (PyLongObject *) long_invert(a); - if (a == NULL) - return NULL; - maska = PyLong_MASK; - } - else { - Py_INCREF(a); - maska = 0; - } - if (Py_SIZE(b) < 0) { - b = (PyLongObject *) long_invert(b); - if (b == NULL) { - Py_DECREF(a); - return NULL; - } - maskb = PyLong_MASK; - } - else { - Py_INCREF(b); - maskb = 0; - } - - negz = 0; - switch (op) { - case '^': - if (maska != maskb) { - maska ^= PyLong_MASK; - negz = -1; - } - break; - case '&': - if (maska && maskb) { - op = '|'; - maska ^= PyLong_MASK; - maskb ^= PyLong_MASK; - negz = -1; - } - break; - case '|': - if (maska || maskb) { - op = '&'; - maska ^= PyLong_MASK; - maskb ^= PyLong_MASK; - negz = -1; - } - break; - } - - /* JRH: The original logic here was to allocate the result value (z) - as the longer of the two operands. However, there are some cases - where the result is guaranteed to be shorter than that: AND of two - positives, OR of two negatives: use the shorter number. AND with - mixed signs: use the positive number. OR with mixed signs: use the - negative number. After the transformations above, op will be '&' - iff one of these cases applies, and mask will be non-0 for operands - whose length should be ignored. - */ - - size_a = Py_SIZE(a); - size_b = Py_SIZE(b); - size_z = op == '&' - ? (maska - ? size_b - : (maskb ? size_a : MIN(size_a, size_b))) - : MAX(size_a, size_b); - z = _PyLong_New(size_z); - if (z == NULL) { - Py_DECREF(a); - Py_DECREF(b); - return NULL; - } - - for (i = 0; i < size_z; ++i) { - diga = (i < size_a ? a->ob_digit[i] : 0) ^ maska; - digb = (i < size_b ? b->ob_digit[i] : 0) ^ maskb; - switch (op) { - case '&': z->ob_digit[i] = diga & digb; break; - case '|': z->ob_digit[i] = diga | digb; break; - case '^': z->ob_digit[i] = diga ^ digb; break; - } - } - - Py_DECREF(a); - Py_DECREF(b); - z = long_normalize(z); - if (negz == 0) - return (PyObject *) maybe_small_long(z); - v = long_invert(z); - Py_DECREF(z); - return v; + digit maska, maskb; /* 0 or PyLong_MASK */ + int negz; + Py_ssize_t size_a, size_b, size_z, i; + PyLongObject *z; + digit diga, digb; + PyObject *v; + + if (Py_SIZE(a) < 0) { + a = (PyLongObject *) long_invert(a); + if (a == NULL) + return NULL; + maska = PyLong_MASK; + } + else { + Py_INCREF(a); + maska = 0; + } + if (Py_SIZE(b) < 0) { + b = (PyLongObject *) long_invert(b); + if (b == NULL) { + Py_DECREF(a); + return NULL; + } + maskb = PyLong_MASK; + } + else { + Py_INCREF(b); + maskb = 0; + } + + negz = 0; + switch (op) { + case '^': + if (maska != maskb) { + maska ^= PyLong_MASK; + negz = -1; + } + break; + case '&': + if (maska && maskb) { + op = '|'; + maska ^= PyLong_MASK; + maskb ^= PyLong_MASK; + negz = -1; + } + break; + case '|': + if (maska || maskb) { + op = '&'; + maska ^= PyLong_MASK; + maskb ^= PyLong_MASK; + negz = -1; + } + break; + } + + /* JRH: The original logic here was to allocate the result value (z) + as the longer of the two operands. However, there are some cases + where the result is guaranteed to be shorter than that: AND of two + positives, OR of two negatives: use the shorter number. AND with + mixed signs: use the positive number. OR with mixed signs: use the + negative number. After the transformations above, op will be '&' + iff one of these cases applies, and mask will be non-0 for operands + whose length should be ignored. + */ + + size_a = Py_SIZE(a); + size_b = Py_SIZE(b); + size_z = op == '&' + ? (maska + ? size_b + : (maskb ? size_a : MIN(size_a, size_b))) + : MAX(size_a, size_b); + z = _PyLong_New(size_z); + if (z == NULL) { + Py_DECREF(a); + Py_DECREF(b); + return NULL; + } + + for (i = 0; i < size_z; ++i) { + diga = (i < size_a ? a->ob_digit[i] : 0) ^ maska; + digb = (i < size_b ? b->ob_digit[i] : 0) ^ maskb; + switch (op) { + case '&': z->ob_digit[i] = diga & digb; break; + case '|': z->ob_digit[i] = diga | digb; break; + case '^': z->ob_digit[i] = diga ^ digb; break; + } + } + + Py_DECREF(a); + Py_DECREF(b); + z = long_normalize(z); + if (negz == 0) + return (PyObject *) maybe_small_long(z); + v = long_invert(z); + Py_DECREF(z); + return v; } static PyObject * long_and(PyObject *a, PyObject *b) { - PyObject *c; - CHECK_BINOP(a, b); - c = long_bitwise((PyLongObject*)a, '&', (PyLongObject*)b); - return c; + PyObject *c; + CHECK_BINOP(a, b); + c = long_bitwise((PyLongObject*)a, '&', (PyLongObject*)b); + return c; } static PyObject * long_xor(PyObject *a, PyObject *b) { - PyObject *c; - CHECK_BINOP(a, b); - c = long_bitwise((PyLongObject*)a, '^', (PyLongObject*)b); - return c; + PyObject *c; + CHECK_BINOP(a, b); + c = long_bitwise((PyLongObject*)a, '^', (PyLongObject*)b); + return c; } static PyObject * long_or(PyObject *a, PyObject *b) { - PyObject *c; - CHECK_BINOP(a, b); - c = long_bitwise((PyLongObject*)a, '|', (PyLongObject*)b); - return c; + PyObject *c; + CHECK_BINOP(a, b); + c = long_bitwise((PyLongObject*)a, '|', (PyLongObject*)b); + return c; } static PyObject * long_long(PyObject *v) { - if (PyLong_CheckExact(v)) - Py_INCREF(v); - else - v = _PyLong_Copy((PyLongObject *)v); - return v; + if (PyLong_CheckExact(v)) + Py_INCREF(v); + else + v = _PyLong_Copy((PyLongObject *)v); + return v; } static PyObject * long_float(PyObject *v) { - double result; - result = PyLong_AsDouble(v); - if (result == -1.0 && PyErr_Occurred()) - return NULL; - return PyFloat_FromDouble(result); + double result; + result = PyLong_AsDouble(v); + if (result == -1.0 && PyErr_Occurred()) + return NULL; + return PyFloat_FromDouble(result); } static PyObject * @@ -3767,47 +3767,47 @@ static PyObject * long_new(PyTypeObject *type, PyObject *args, PyObject *kwds) { - PyObject *x = NULL; - int base = -909; /* unlikely! */ - static char *kwlist[] = {"x", "base", 0}; - - if (type != &PyLong_Type) - return long_subtype_new(type, args, kwds); /* Wimp out */ - if (!PyArg_ParseTupleAndKeywords(args, kwds, "|Oi:int", kwlist, - &x, &base)) - return NULL; - if (x == NULL) - return PyLong_FromLong(0L); - if (base == -909) - return PyNumber_Long(x); - else if (PyUnicode_Check(x)) - return PyLong_FromUnicode(PyUnicode_AS_UNICODE(x), - PyUnicode_GET_SIZE(x), - base); - else if (PyByteArray_Check(x) || PyBytes_Check(x)) { - /* Since PyLong_FromString doesn't have a length parameter, - * check here for possible NULs in the string. */ - char *string; - Py_ssize_t size = Py_SIZE(x); - if (PyByteArray_Check(x)) - string = PyByteArray_AS_STRING(x); - else - string = PyBytes_AS_STRING(x); - if (strlen(string) != (size_t)size) { - /* We only see this if there's a null byte in x, - x is a bytes or buffer, *and* a base is given. */ - PyErr_Format(PyExc_ValueError, - "invalid literal for int() with base %d: %R", - base, x); - return NULL; - } - return PyLong_FromString(string, NULL, base); - } - else { - PyErr_SetString(PyExc_TypeError, - "int() can't convert non-string with explicit base"); - return NULL; - } + PyObject *x = NULL; + int base = -909; /* unlikely! */ + static char *kwlist[] = {"x", "base", 0}; + + if (type != &PyLong_Type) + return long_subtype_new(type, args, kwds); /* Wimp out */ + if (!PyArg_ParseTupleAndKeywords(args, kwds, "|Oi:int", kwlist, + &x, &base)) + return NULL; + if (x == NULL) + return PyLong_FromLong(0L); + if (base == -909) + return PyNumber_Long(x); + else if (PyUnicode_Check(x)) + return PyLong_FromUnicode(PyUnicode_AS_UNICODE(x), + PyUnicode_GET_SIZE(x), + base); + else if (PyByteArray_Check(x) || PyBytes_Check(x)) { + /* Since PyLong_FromString doesn't have a length parameter, + * check here for possible NULs in the string. */ + char *string; + Py_ssize_t size = Py_SIZE(x); + if (PyByteArray_Check(x)) + string = PyByteArray_AS_STRING(x); + else + string = PyBytes_AS_STRING(x); + if (strlen(string) != (size_t)size) { + /* We only see this if there's a null byte in x, + x is a bytes or buffer, *and* a base is given. */ + PyErr_Format(PyExc_ValueError, + "invalid literal for int() with base %d: %R", + base, x); + return NULL; + } + return PyLong_FromString(string, NULL, base); + } + else { + PyErr_SetString(PyExc_TypeError, + "int() can't convert non-string with explicit base"); + return NULL; + } } /* Wimpy, slow approach to tp_new calls for subtypes of long: @@ -3818,256 +3818,256 @@ static PyObject * long_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds) { - PyLongObject *tmp, *newobj; - Py_ssize_t i, n; + PyLongObject *tmp, *newobj; + Py_ssize_t i, n; - assert(PyType_IsSubtype(type, &PyLong_Type)); - tmp = (PyLongObject *)long_new(&PyLong_Type, args, kwds); - if (tmp == NULL) - return NULL; - assert(PyLong_CheckExact(tmp)); - n = Py_SIZE(tmp); - if (n < 0) - n = -n; - newobj = (PyLongObject *)type->tp_alloc(type, n); - if (newobj == NULL) { - Py_DECREF(tmp); - return NULL; - } - assert(PyLong_Check(newobj)); - Py_SIZE(newobj) = Py_SIZE(tmp); - for (i = 0; i < n; i++) - newobj->ob_digit[i] = tmp->ob_digit[i]; - Py_DECREF(tmp); - return (PyObject *)newobj; + assert(PyType_IsSubtype(type, &PyLong_Type)); + tmp = (PyLongObject *)long_new(&PyLong_Type, args, kwds); + if (tmp == NULL) + return NULL; + assert(PyLong_CheckExact(tmp)); + n = Py_SIZE(tmp); + if (n < 0) + n = -n; + newobj = (PyLongObject *)type->tp_alloc(type, n); + if (newobj == NULL) { + Py_DECREF(tmp); + return NULL; + } + assert(PyLong_Check(newobj)); + Py_SIZE(newobj) = Py_SIZE(tmp); + for (i = 0; i < n; i++) + newobj->ob_digit[i] = tmp->ob_digit[i]; + Py_DECREF(tmp); + return (PyObject *)newobj; } static PyObject * long_getnewargs(PyLongObject *v) { - return Py_BuildValue("(N)", _PyLong_Copy(v)); + return Py_BuildValue("(N)", _PyLong_Copy(v)); } static PyObject * long_get0(PyLongObject *v, void *context) { - return PyLong_FromLong(0L); + return PyLong_FromLong(0L); } static PyObject * long_get1(PyLongObject *v, void *context) { - return PyLong_FromLong(1L); + return PyLong_FromLong(1L); } static PyObject * long__format__(PyObject *self, PyObject *args) { - PyObject *format_spec; + PyObject *format_spec; - if (!PyArg_ParseTuple(args, "U:__format__", &format_spec)) - return NULL; - return _PyLong_FormatAdvanced(self, - PyUnicode_AS_UNICODE(format_spec), - PyUnicode_GET_SIZE(format_spec)); + if (!PyArg_ParseTuple(args, "U:__format__", &format_spec)) + return NULL; + return _PyLong_FormatAdvanced(self, + PyUnicode_AS_UNICODE(format_spec), + PyUnicode_GET_SIZE(format_spec)); } static PyObject * long_round(PyObject *self, PyObject *args) { - PyObject *o_ndigits=NULL, *temp; - PyLongObject *pow=NULL, *q=NULL, *r=NULL, *ndigits=NULL, *one; - int errcode; - digit q_mod_4; - - /* Notes on the algorithm: to round to the nearest 10**n (n positive), - the straightforward method is: - - (1) divide by 10**n - (2) round to nearest integer (round to even in case of tie) - (3) multiply result by 10**n. - - But the rounding step involves examining the fractional part of the - quotient to see whether it's greater than 0.5 or not. Since we - want to do the whole calculation in integer arithmetic, it's - simpler to do: - - (1) divide by (10**n)/2 - (2) round to nearest multiple of 2 (multiple of 4 in case of tie) - (3) multiply result by (10**n)/2. - - Then all we need to know about the fractional part of the quotient - arising in step (2) is whether it's zero or not. - - Doing both a multiplication and division is wasteful, and is easily - avoided if we just figure out how much to adjust the original input - by to do the rounding. - - Here's the whole algorithm expressed in Python. - - def round(self, ndigits = None): - """round(int, int) -> int""" - if ndigits is None or ndigits >= 0: - return self - pow = 10**-ndigits >> 1 - q, r = divmod(self, pow) - self -= r - if (q & 1 != 0): - if (q & 2 == r == 0): - self -= pow - else: - self += pow - return self - - */ - if (!PyArg_ParseTuple(args, "|O", &o_ndigits)) - return NULL; - if (o_ndigits == NULL) - return long_long(self); - - ndigits = (PyLongObject *)PyNumber_Index(o_ndigits); - if (ndigits == NULL) - return NULL; - - if (Py_SIZE(ndigits) >= 0) { - Py_DECREF(ndigits); - return long_long(self); - } - - Py_INCREF(self); /* to keep refcounting simple */ - /* we now own references to self, ndigits */ - - /* pow = 10 ** -ndigits >> 1 */ - pow = (PyLongObject *)PyLong_FromLong(10L); - if (pow == NULL) - goto error; - temp = long_neg(ndigits); - Py_DECREF(ndigits); - ndigits = (PyLongObject *)temp; - if (ndigits == NULL) - goto error; - temp = long_pow((PyObject *)pow, (PyObject *)ndigits, Py_None); - Py_DECREF(pow); - pow = (PyLongObject *)temp; - if (pow == NULL) - goto error; - assert(PyLong_Check(pow)); /* check long_pow returned a long */ - one = (PyLongObject *)PyLong_FromLong(1L); - if (one == NULL) - goto error; - temp = long_rshift(pow, one); - Py_DECREF(one); - Py_DECREF(pow); - pow = (PyLongObject *)temp; - if (pow == NULL) - goto error; - - /* q, r = divmod(self, pow) */ - errcode = l_divmod((PyLongObject *)self, pow, &q, &r); - if (errcode == -1) - goto error; - - /* self -= r */ - temp = long_sub((PyLongObject *)self, r); - Py_DECREF(self); - self = temp; - if (self == NULL) - goto error; - - /* get value of quotient modulo 4 */ - if (Py_SIZE(q) == 0) - q_mod_4 = 0; - else if (Py_SIZE(q) > 0) - q_mod_4 = q->ob_digit[0] & 3; - else - q_mod_4 = (PyLong_BASE-q->ob_digit[0]) & 3; - - if ((q_mod_4 & 1) == 1) { - /* q is odd; round self up or down by adding or subtracting pow */ - if (q_mod_4 == 1 && Py_SIZE(r) == 0) - temp = (PyObject *)long_sub((PyLongObject *)self, pow); - else - temp = (PyObject *)long_add((PyLongObject *)self, pow); - Py_DECREF(self); - self = temp; - if (self == NULL) - goto error; - } - Py_DECREF(q); - Py_DECREF(r); - Py_DECREF(pow); - Py_DECREF(ndigits); - return self; + PyObject *o_ndigits=NULL, *temp; + PyLongObject *pow=NULL, *q=NULL, *r=NULL, *ndigits=NULL, *one; + int errcode; + digit q_mod_4; + + /* Notes on the algorithm: to round to the nearest 10**n (n positive), + the straightforward method is: + + (1) divide by 10**n + (2) round to nearest integer (round to even in case of tie) + (3) multiply result by 10**n. + + But the rounding step involves examining the fractional part of the + quotient to see whether it's greater than 0.5 or not. Since we + want to do the whole calculation in integer arithmetic, it's + simpler to do: + + (1) divide by (10**n)/2 + (2) round to nearest multiple of 2 (multiple of 4 in case of tie) + (3) multiply result by (10**n)/2. + + Then all we need to know about the fractional part of the quotient + arising in step (2) is whether it's zero or not. + + Doing both a multiplication and division is wasteful, and is easily + avoided if we just figure out how much to adjust the original input + by to do the rounding. + + Here's the whole algorithm expressed in Python. + + def round(self, ndigits = None): + """round(int, int) -> int""" + if ndigits is None or ndigits >= 0: + return self + pow = 10**-ndigits >> 1 + q, r = divmod(self, pow) + self -= r + if (q & 1 != 0): + if (q & 2 == r == 0): + self -= pow + else: + self += pow + return self + + */ + if (!PyArg_ParseTuple(args, "|O", &o_ndigits)) + return NULL; + if (o_ndigits == NULL) + return long_long(self); + + ndigits = (PyLongObject *)PyNumber_Index(o_ndigits); + if (ndigits == NULL) + return NULL; + + if (Py_SIZE(ndigits) >= 0) { + Py_DECREF(ndigits); + return long_long(self); + } + + Py_INCREF(self); /* to keep refcounting simple */ + /* we now own references to self, ndigits */ + + /* pow = 10 ** -ndigits >> 1 */ + pow = (PyLongObject *)PyLong_FromLong(10L); + if (pow == NULL) + goto error; + temp = long_neg(ndigits); + Py_DECREF(ndigits); + ndigits = (PyLongObject *)temp; + if (ndigits == NULL) + goto error; + temp = long_pow((PyObject *)pow, (PyObject *)ndigits, Py_None); + Py_DECREF(pow); + pow = (PyLongObject *)temp; + if (pow == NULL) + goto error; + assert(PyLong_Check(pow)); /* check long_pow returned a long */ + one = (PyLongObject *)PyLong_FromLong(1L); + if (one == NULL) + goto error; + temp = long_rshift(pow, one); + Py_DECREF(one); + Py_DECREF(pow); + pow = (PyLongObject *)temp; + if (pow == NULL) + goto error; + + /* q, r = divmod(self, pow) */ + errcode = l_divmod((PyLongObject *)self, pow, &q, &r); + if (errcode == -1) + goto error; + + /* self -= r */ + temp = long_sub((PyLongObject *)self, r); + Py_DECREF(self); + self = temp; + if (self == NULL) + goto error; + + /* get value of quotient modulo 4 */ + if (Py_SIZE(q) == 0) + q_mod_4 = 0; + else if (Py_SIZE(q) > 0) + q_mod_4 = q->ob_digit[0] & 3; + else + q_mod_4 = (PyLong_BASE-q->ob_digit[0]) & 3; + + if ((q_mod_4 & 1) == 1) { + /* q is odd; round self up or down by adding or subtracting pow */ + if (q_mod_4 == 1 && Py_SIZE(r) == 0) + temp = (PyObject *)long_sub((PyLongObject *)self, pow); + else + temp = (PyObject *)long_add((PyLongObject *)self, pow); + Py_DECREF(self); + self = temp; + if (self == NULL) + goto error; + } + Py_DECREF(q); + Py_DECREF(r); + Py_DECREF(pow); + Py_DECREF(ndigits); + return self; error: - Py_XDECREF(q); - Py_XDECREF(r); - Py_XDECREF(pow); - Py_XDECREF(self); - Py_XDECREF(ndigits); - return NULL; + Py_XDECREF(q); + Py_XDECREF(r); + Py_XDECREF(pow); + Py_XDECREF(self); + Py_XDECREF(ndigits); + return NULL; } static PyObject * long_sizeof(PyLongObject *v) { - Py_ssize_t res; + Py_ssize_t res; - res = offsetof(PyLongObject, ob_digit) + ABS(Py_SIZE(v))*sizeof(digit); - return PyLong_FromSsize_t(res); + res = offsetof(PyLongObject, ob_digit) + ABS(Py_SIZE(v))*sizeof(digit); + return PyLong_FromSsize_t(res); } static PyObject * long_bit_length(PyLongObject *v) { - PyLongObject *result, *x, *y; - Py_ssize_t ndigits, msd_bits = 0; - digit msd; - - assert(v != NULL); - assert(PyLong_Check(v)); - - ndigits = ABS(Py_SIZE(v)); - if (ndigits == 0) - return PyLong_FromLong(0); - - msd = v->ob_digit[ndigits-1]; - while (msd >= 32) { - msd_bits += 6; - msd >>= 6; - } - msd_bits += (long)(BitLengthTable[msd]); - - if (ndigits <= PY_SSIZE_T_MAX/PyLong_SHIFT) - return PyLong_FromSsize_t((ndigits-1)*PyLong_SHIFT + msd_bits); - - /* expression above may overflow; use Python integers instead */ - result = (PyLongObject *)PyLong_FromSsize_t(ndigits - 1); - if (result == NULL) - return NULL; - x = (PyLongObject *)PyLong_FromLong(PyLong_SHIFT); - if (x == NULL) - goto error; - y = (PyLongObject *)long_mul(result, x); - Py_DECREF(x); - if (y == NULL) - goto error; - Py_DECREF(result); - result = y; - - x = (PyLongObject *)PyLong_FromLong((long)msd_bits); - if (x == NULL) - goto error; - y = (PyLongObject *)long_add(result, x); - Py_DECREF(x); - if (y == NULL) - goto error; - Py_DECREF(result); - result = y; + PyLongObject *result, *x, *y; + Py_ssize_t ndigits, msd_bits = 0; + digit msd; + + assert(v != NULL); + assert(PyLong_Check(v)); + + ndigits = ABS(Py_SIZE(v)); + if (ndigits == 0) + return PyLong_FromLong(0); + + msd = v->ob_digit[ndigits-1]; + while (msd >= 32) { + msd_bits += 6; + msd >>= 6; + } + msd_bits += (long)(BitLengthTable[msd]); + + if (ndigits <= PY_SSIZE_T_MAX/PyLong_SHIFT) + return PyLong_FromSsize_t((ndigits-1)*PyLong_SHIFT + msd_bits); + + /* expression above may overflow; use Python integers instead */ + result = (PyLongObject *)PyLong_FromSsize_t(ndigits - 1); + if (result == NULL) + return NULL; + x = (PyLongObject *)PyLong_FromLong(PyLong_SHIFT); + if (x == NULL) + goto error; + y = (PyLongObject *)long_mul(result, x); + Py_DECREF(x); + if (y == NULL) + goto error; + Py_DECREF(result); + result = y; + + x = (PyLongObject *)PyLong_FromLong((long)msd_bits); + if (x == NULL) + goto error; + y = (PyLongObject *)long_add(result, x); + Py_DECREF(x); + if (y == NULL) + goto error; + Py_DECREF(result); + result = y; - return (PyObject *)result; + return (PyObject *)result; error: - Py_DECREF(result); - return NULL; + Py_DECREF(result); + return NULL; } PyDoc_STRVAR(long_bit_length_doc, @@ -4083,33 +4083,33 @@ static PyObject * long_is_finite(PyObject *v) { - Py_RETURN_TRUE; + Py_RETURN_TRUE; } #endif static PyMethodDef long_methods[] = { - {"conjugate", (PyCFunction)long_long, METH_NOARGS, - "Returns self, the complex conjugate of any int."}, - {"bit_length", (PyCFunction)long_bit_length, METH_NOARGS, - long_bit_length_doc}, + {"conjugate", (PyCFunction)long_long, METH_NOARGS, + "Returns self, the complex conjugate of any int."}, + {"bit_length", (PyCFunction)long_bit_length, METH_NOARGS, + long_bit_length_doc}, #if 0 - {"is_finite", (PyCFunction)long_is_finite, METH_NOARGS, - "Returns always True."}, + {"is_finite", (PyCFunction)long_is_finite, METH_NOARGS, + "Returns always True."}, #endif - {"__trunc__", (PyCFunction)long_long, METH_NOARGS, - "Truncating an Integral returns itself."}, - {"__floor__", (PyCFunction)long_long, METH_NOARGS, - "Flooring an Integral returns itself."}, - {"__ceil__", (PyCFunction)long_long, METH_NOARGS, - "Ceiling of an Integral returns itself."}, - {"__round__", (PyCFunction)long_round, METH_VARARGS, - "Rounding an Integral returns itself.\n" - "Rounding with an ndigits argument also returns an integer."}, - {"__getnewargs__", (PyCFunction)long_getnewargs, METH_NOARGS}, - {"__format__", (PyCFunction)long__format__, METH_VARARGS}, - {"__sizeof__", (PyCFunction)long_sizeof, METH_NOARGS, - "Returns size in memory, in bytes"}, - {NULL, NULL} /* sentinel */ + {"__trunc__", (PyCFunction)long_long, METH_NOARGS, + "Truncating an Integral returns itself."}, + {"__floor__", (PyCFunction)long_long, METH_NOARGS, + "Flooring an Integral returns itself."}, + {"__ceil__", (PyCFunction)long_long, METH_NOARGS, + "Ceiling of an Integral returns itself."}, + {"__round__", (PyCFunction)long_round, METH_VARARGS, + "Rounding an Integral returns itself.\n" + "Rounding with an ndigits argument also returns an integer."}, + {"__getnewargs__", (PyCFunction)long_getnewargs, METH_NOARGS}, + {"__format__", (PyCFunction)long__format__, METH_VARARGS}, + {"__sizeof__", (PyCFunction)long_sizeof, METH_NOARGS, + "Returns size in memory, in bytes"}, + {NULL, NULL} /* sentinel */ }; static PyGetSetDef long_getset[] = { @@ -4142,83 +4142,83 @@ converting a non-string."); static PyNumberMethods long_as_number = { - (binaryfunc) long_add, /*nb_add*/ - (binaryfunc) long_sub, /*nb_subtract*/ - (binaryfunc) long_mul, /*nb_multiply*/ - long_mod, /*nb_remainder*/ - long_divmod, /*nb_divmod*/ - long_pow, /*nb_power*/ - (unaryfunc) long_neg, /*nb_negative*/ - (unaryfunc) long_long, /*tp_positive*/ - (unaryfunc) long_abs, /*tp_absolute*/ - (inquiry) long_bool, /*tp_bool*/ - (unaryfunc) long_invert, /*nb_invert*/ - long_lshift, /*nb_lshift*/ - (binaryfunc) long_rshift, /*nb_rshift*/ - long_and, /*nb_and*/ - long_xor, /*nb_xor*/ - long_or, /*nb_or*/ - long_long, /*nb_int*/ - 0, /*nb_reserved*/ - long_float, /*nb_float*/ - 0, /* nb_inplace_add */ - 0, /* nb_inplace_subtract */ - 0, /* nb_inplace_multiply */ - 0, /* nb_inplace_remainder */ - 0, /* nb_inplace_power */ - 0, /* nb_inplace_lshift */ - 0, /* nb_inplace_rshift */ - 0, /* nb_inplace_and */ - 0, /* nb_inplace_xor */ - 0, /* nb_inplace_or */ - long_div, /* nb_floor_divide */ - long_true_divide, /* nb_true_divide */ - 0, /* nb_inplace_floor_divide */ - 0, /* nb_inplace_true_divide */ - long_long, /* nb_index */ + (binaryfunc) long_add, /*nb_add*/ + (binaryfunc) long_sub, /*nb_subtract*/ + (binaryfunc) long_mul, /*nb_multiply*/ + long_mod, /*nb_remainder*/ + long_divmod, /*nb_divmod*/ + long_pow, /*nb_power*/ + (unaryfunc) long_neg, /*nb_negative*/ + (unaryfunc) long_long, /*tp_positive*/ + (unaryfunc) long_abs, /*tp_absolute*/ + (inquiry) long_bool, /*tp_bool*/ + (unaryfunc) long_invert, /*nb_invert*/ + long_lshift, /*nb_lshift*/ + (binaryfunc) long_rshift, /*nb_rshift*/ + long_and, /*nb_and*/ + long_xor, /*nb_xor*/ + long_or, /*nb_or*/ + long_long, /*nb_int*/ + 0, /*nb_reserved*/ + long_float, /*nb_float*/ + 0, /* nb_inplace_add */ + 0, /* nb_inplace_subtract */ + 0, /* nb_inplace_multiply */ + 0, /* nb_inplace_remainder */ + 0, /* nb_inplace_power */ + 0, /* nb_inplace_lshift */ + 0, /* nb_inplace_rshift */ + 0, /* nb_inplace_and */ + 0, /* nb_inplace_xor */ + 0, /* nb_inplace_or */ + long_div, /* nb_floor_divide */ + long_true_divide, /* nb_true_divide */ + 0, /* nb_inplace_floor_divide */ + 0, /* nb_inplace_true_divide */ + long_long, /* nb_index */ }; PyTypeObject PyLong_Type = { - PyVarObject_HEAD_INIT(&PyType_Type, 0) - "int", /* tp_name */ - offsetof(PyLongObject, ob_digit), /* tp_basicsize */ - sizeof(digit), /* tp_itemsize */ - long_dealloc, /* tp_dealloc */ - 0, /* tp_print */ - 0, /* tp_getattr */ - 0, /* tp_setattr */ - 0, /* tp_reserved */ - long_repr, /* tp_repr */ - &long_as_number, /* tp_as_number */ - 0, /* tp_as_sequence */ - 0, /* tp_as_mapping */ - (hashfunc)long_hash, /* tp_hash */ - 0, /* tp_call */ - long_repr, /* tp_str */ - PyObject_GenericGetAttr, /* tp_getattro */ - 0, /* tp_setattro */ - 0, /* tp_as_buffer */ - Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | - Py_TPFLAGS_LONG_SUBCLASS, /* tp_flags */ - long_doc, /* tp_doc */ - 0, /* tp_traverse */ - 0, /* tp_clear */ - long_richcompare, /* tp_richcompare */ - 0, /* tp_weaklistoffset */ - 0, /* tp_iter */ - 0, /* tp_iternext */ - long_methods, /* tp_methods */ - 0, /* tp_members */ - long_getset, /* tp_getset */ - 0, /* tp_base */ - 0, /* tp_dict */ - 0, /* tp_descr_get */ - 0, /* tp_descr_set */ - 0, /* tp_dictoffset */ - 0, /* tp_init */ - 0, /* tp_alloc */ - long_new, /* tp_new */ - PyObject_Del, /* tp_free */ + PyVarObject_HEAD_INIT(&PyType_Type, 0) + "int", /* tp_name */ + offsetof(PyLongObject, ob_digit), /* tp_basicsize */ + sizeof(digit), /* tp_itemsize */ + long_dealloc, /* tp_dealloc */ + 0, /* tp_print */ + 0, /* tp_getattr */ + 0, /* tp_setattr */ + 0, /* tp_reserved */ + long_repr, /* tp_repr */ + &long_as_number, /* tp_as_number */ + 0, /* tp_as_sequence */ + 0, /* tp_as_mapping */ + (hashfunc)long_hash, /* tp_hash */ + 0, /* tp_call */ + long_repr, /* tp_str */ + PyObject_GenericGetAttr, /* tp_getattro */ + 0, /* tp_setattro */ + 0, /* tp_as_buffer */ + Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | + Py_TPFLAGS_LONG_SUBCLASS, /* tp_flags */ + long_doc, /* tp_doc */ + 0, /* tp_traverse */ + 0, /* tp_clear */ + long_richcompare, /* tp_richcompare */ + 0, /* tp_weaklistoffset */ + 0, /* tp_iter */ + 0, /* tp_iternext */ + long_methods, /* tp_methods */ + 0, /* tp_members */ + long_getset, /* tp_getset */ + 0, /* tp_base */ + 0, /* tp_dict */ + 0, /* tp_descr_get */ + 0, /* tp_descr_set */ + 0, /* tp_dictoffset */ + 0, /* tp_init */ + 0, /* tp_alloc */ + long_new, /* tp_new */ + PyObject_Del, /* tp_free */ }; static PyTypeObject Int_InfoType; @@ -4230,89 +4230,89 @@ internal representation of integers. The attributes are read only."); static PyStructSequence_Field int_info_fields[] = { - {"bits_per_digit", "size of a digit in bits"}, - {"sizeof_digit", "size in bytes of the C type used to " - "represent a digit"}, - {NULL, NULL} + {"bits_per_digit", "size of a digit in bits"}, + {"sizeof_digit", "size in bytes of the C type used to " + "represent a digit"}, + {NULL, NULL} }; static PyStructSequence_Desc int_info_desc = { - "sys.int_info", /* name */ - int_info__doc__, /* doc */ - int_info_fields, /* fields */ - 2 /* number of fields */ + "sys.int_info", /* name */ + int_info__doc__, /* doc */ + int_info_fields, /* fields */ + 2 /* number of fields */ }; PyObject * PyLong_GetInfo(void) { - PyObject* int_info; - int field = 0; - int_info = PyStructSequence_New(&Int_InfoType); - if (int_info == NULL) - return NULL; - PyStructSequence_SET_ITEM(int_info, field++, - PyLong_FromLong(PyLong_SHIFT)); - PyStructSequence_SET_ITEM(int_info, field++, - PyLong_FromLong(sizeof(digit))); - if (PyErr_Occurred()) { - Py_CLEAR(int_info); - return NULL; - } - return int_info; + PyObject* int_info; + int field = 0; + int_info = PyStructSequence_New(&Int_InfoType); + if (int_info == NULL) + return NULL; + PyStructSequence_SET_ITEM(int_info, field++, + PyLong_FromLong(PyLong_SHIFT)); + PyStructSequence_SET_ITEM(int_info, field++, + PyLong_FromLong(sizeof(digit))); + if (PyErr_Occurred()) { + Py_CLEAR(int_info); + return NULL; + } + return int_info; } int _PyLong_Init(void) { #if NSMALLNEGINTS + NSMALLPOSINTS > 0 - int ival, size; - PyLongObject *v = small_ints; + int ival, size; + PyLongObject *v = small_ints; - for (ival = -NSMALLNEGINTS; ival < NSMALLPOSINTS; ival++, v++) { - size = (ival < 0) ? -1 : ((ival == 0) ? 0 : 1); - if (Py_TYPE(v) == &PyLong_Type) { - /* The element is already initialized, most likely - * the Python interpreter was initialized before. - */ - Py_ssize_t refcnt; - PyObject* op = (PyObject*)v; - - refcnt = Py_REFCNT(op) < 0 ? 0 : Py_REFCNT(op); - _Py_NewReference(op); - /* _Py_NewReference sets the ref count to 1 but - * the ref count might be larger. Set the refcnt - * to the original refcnt + 1 */ - Py_REFCNT(op) = refcnt + 1; - assert(Py_SIZE(op) == size); - assert(v->ob_digit[0] == abs(ival)); - } - else { - PyObject_INIT(v, &PyLong_Type); - } - Py_SIZE(v) = size; - v->ob_digit[0] = abs(ival); - } + for (ival = -NSMALLNEGINTS; ival < NSMALLPOSINTS; ival++, v++) { + size = (ival < 0) ? -1 : ((ival == 0) ? 0 : 1); + if (Py_TYPE(v) == &PyLong_Type) { + /* The element is already initialized, most likely + * the Python interpreter was initialized before. + */ + Py_ssize_t refcnt; + PyObject* op = (PyObject*)v; + + refcnt = Py_REFCNT(op) < 0 ? 0 : Py_REFCNT(op); + _Py_NewReference(op); + /* _Py_NewReference sets the ref count to 1 but + * the ref count might be larger. Set the refcnt + * to the original refcnt + 1 */ + Py_REFCNT(op) = refcnt + 1; + assert(Py_SIZE(op) == size); + assert(v->ob_digit[0] == abs(ival)); + } + else { + PyObject_INIT(v, &PyLong_Type); + } + Py_SIZE(v) = size; + v->ob_digit[0] = abs(ival); + } #endif - /* initialize int_info */ - if (Int_InfoType.tp_name == 0) - PyStructSequence_InitType(&Int_InfoType, &int_info_desc); + /* initialize int_info */ + if (Int_InfoType.tp_name == 0) + PyStructSequence_InitType(&Int_InfoType, &int_info_desc); - return 1; + return 1; } void PyLong_Fini(void) { - /* Integers are currently statically allocated. Py_DECREF is not - needed, but Python must forget about the reference or multiple - reinitializations will fail. */ + /* Integers are currently statically allocated. Py_DECREF is not + needed, but Python must forget about the reference or multiple + reinitializations will fail. */ #if NSMALLNEGINTS + NSMALLPOSINTS > 0 - int i; - PyLongObject *v = small_ints; - for (i = 0; i < NSMALLNEGINTS + NSMALLPOSINTS; i++, v++) { - _Py_DEC_REFTOTAL; - _Py_ForgetReference((PyObject*)v); - } + int i; + PyLongObject *v = small_ints; + for (i = 0; i < NSMALLNEGINTS + NSMALLPOSINTS; i++, v++) { + _Py_DEC_REFTOTAL; + _Py_ForgetReference((PyObject*)v); + } #endif } Modified: python/branches/release31-maint/Objects/methodobject.c ============================================================================== --- python/branches/release31-maint/Objects/methodobject.c (original) +++ python/branches/release31-maint/Objects/methodobject.c Sun May 9 18:14:21 2010 @@ -16,104 +16,104 @@ PyObject * PyCFunction_NewEx(PyMethodDef *ml, PyObject *self, PyObject *module) { - PyCFunctionObject *op; - op = free_list; - if (op != NULL) { - free_list = (PyCFunctionObject *)(op->m_self); - PyObject_INIT(op, &PyCFunction_Type); - numfree--; - } - else { - op = PyObject_GC_New(PyCFunctionObject, &PyCFunction_Type); - if (op == NULL) - return NULL; - } - op->m_ml = ml; - Py_XINCREF(self); - op->m_self = self; - Py_XINCREF(module); - op->m_module = module; - _PyObject_GC_TRACK(op); - return (PyObject *)op; + PyCFunctionObject *op; + op = free_list; + if (op != NULL) { + free_list = (PyCFunctionObject *)(op->m_self); + PyObject_INIT(op, &PyCFunction_Type); + numfree--; + } + else { + op = PyObject_GC_New(PyCFunctionObject, &PyCFunction_Type); + if (op == NULL) + return NULL; + } + op->m_ml = ml; + Py_XINCREF(self); + op->m_self = self; + Py_XINCREF(module); + op->m_module = module; + _PyObject_GC_TRACK(op); + return (PyObject *)op; } PyCFunction PyCFunction_GetFunction(PyObject *op) { - if (!PyCFunction_Check(op)) { - PyErr_BadInternalCall(); - return NULL; - } - return ((PyCFunctionObject *)op) -> m_ml -> ml_meth; + if (!PyCFunction_Check(op)) { + PyErr_BadInternalCall(); + return NULL; + } + return ((PyCFunctionObject *)op) -> m_ml -> ml_meth; } PyObject * PyCFunction_GetSelf(PyObject *op) { - if (!PyCFunction_Check(op)) { - PyErr_BadInternalCall(); - return NULL; - } - return ((PyCFunctionObject *)op) -> m_self; + if (!PyCFunction_Check(op)) { + PyErr_BadInternalCall(); + return NULL; + } + return ((PyCFunctionObject *)op) -> m_self; } int PyCFunction_GetFlags(PyObject *op) { - if (!PyCFunction_Check(op)) { - PyErr_BadInternalCall(); - return -1; - } - return ((PyCFunctionObject *)op) -> m_ml -> ml_flags; + if (!PyCFunction_Check(op)) { + PyErr_BadInternalCall(); + return -1; + } + return ((PyCFunctionObject *)op) -> m_ml -> ml_flags; } PyObject * PyCFunction_Call(PyObject *func, PyObject *arg, PyObject *kw) { - PyCFunctionObject* f = (PyCFunctionObject*)func; - PyCFunction meth = PyCFunction_GET_FUNCTION(func); - PyObject *self = PyCFunction_GET_SELF(func); - Py_ssize_t size; - - switch (PyCFunction_GET_FLAGS(func) & ~(METH_CLASS | METH_STATIC | METH_COEXIST)) { - case METH_VARARGS: - if (kw == NULL || PyDict_Size(kw) == 0) - return (*meth)(self, arg); - break; - case METH_VARARGS | METH_KEYWORDS: - return (*(PyCFunctionWithKeywords)meth)(self, arg, kw); - case METH_NOARGS: - if (kw == NULL || PyDict_Size(kw) == 0) { - size = PyTuple_GET_SIZE(arg); - if (size == 0) - return (*meth)(self, NULL); - PyErr_Format(PyExc_TypeError, - "%.200s() takes no arguments (%zd given)", - f->m_ml->ml_name, size); - return NULL; - } - break; - case METH_O: - if (kw == NULL || PyDict_Size(kw) == 0) { - size = PyTuple_GET_SIZE(arg); - if (size == 1) - return (*meth)(self, PyTuple_GET_ITEM(arg, 0)); - PyErr_Format(PyExc_TypeError, - "%.200s() takes exactly one argument (%zd given)", - f->m_ml->ml_name, size); - return NULL; - } - break; - default: - PyErr_SetString(PyExc_SystemError, "Bad call flags in " - "PyCFunction_Call. METH_OLDARGS is no " - "longer supported!"); - - return NULL; - } - PyErr_Format(PyExc_TypeError, "%.200s() takes no keyword arguments", - f->m_ml->ml_name); - return NULL; + PyCFunctionObject* f = (PyCFunctionObject*)func; + PyCFunction meth = PyCFunction_GET_FUNCTION(func); + PyObject *self = PyCFunction_GET_SELF(func); + Py_ssize_t size; + + switch (PyCFunction_GET_FLAGS(func) & ~(METH_CLASS | METH_STATIC | METH_COEXIST)) { + case METH_VARARGS: + if (kw == NULL || PyDict_Size(kw) == 0) + return (*meth)(self, arg); + break; + case METH_VARARGS | METH_KEYWORDS: + return (*(PyCFunctionWithKeywords)meth)(self, arg, kw); + case METH_NOARGS: + if (kw == NULL || PyDict_Size(kw) == 0) { + size = PyTuple_GET_SIZE(arg); + if (size == 0) + return (*meth)(self, NULL); + PyErr_Format(PyExc_TypeError, + "%.200s() takes no arguments (%zd given)", + f->m_ml->ml_name, size); + return NULL; + } + break; + case METH_O: + if (kw == NULL || PyDict_Size(kw) == 0) { + size = PyTuple_GET_SIZE(arg); + if (size == 1) + return (*meth)(self, PyTuple_GET_ITEM(arg, 0)); + PyErr_Format(PyExc_TypeError, + "%.200s() takes exactly one argument (%zd given)", + f->m_ml->ml_name, size); + return NULL; + } + break; + default: + PyErr_SetString(PyExc_SystemError, "Bad call flags in " + "PyCFunction_Call. METH_OLDARGS is no " + "longer supported!"); + + return NULL; + } + PyErr_Format(PyExc_TypeError, "%.200s() takes no keyword arguments", + f->m_ml->ml_name); + return NULL; } /* Methods (the standard built-in methods, that is) */ @@ -121,163 +121,163 @@ static void meth_dealloc(PyCFunctionObject *m) { - _PyObject_GC_UNTRACK(m); - Py_XDECREF(m->m_self); - Py_XDECREF(m->m_module); - if (numfree < PyCFunction_MAXFREELIST) { - m->m_self = (PyObject *)free_list; - free_list = m; - numfree++; - } - else { - PyObject_GC_Del(m); - } + _PyObject_GC_UNTRACK(m); + Py_XDECREF(m->m_self); + Py_XDECREF(m->m_module); + if (numfree < PyCFunction_MAXFREELIST) { + m->m_self = (PyObject *)free_list; + free_list = m; + numfree++; + } + else { + PyObject_GC_Del(m); + } } static PyObject * meth_get__doc__(PyCFunctionObject *m, void *closure) { - const char *doc = m->m_ml->ml_doc; + const char *doc = m->m_ml->ml_doc; - if (doc != NULL) - return PyUnicode_FromString(doc); - Py_INCREF(Py_None); - return Py_None; + if (doc != NULL) + return PyUnicode_FromString(doc); + Py_INCREF(Py_None); + return Py_None; } static PyObject * meth_get__name__(PyCFunctionObject *m, void *closure) { - return PyUnicode_FromString(m->m_ml->ml_name); + return PyUnicode_FromString(m->m_ml->ml_name); } static int meth_traverse(PyCFunctionObject *m, visitproc visit, void *arg) { - Py_VISIT(m->m_self); - Py_VISIT(m->m_module); - return 0; + Py_VISIT(m->m_self); + Py_VISIT(m->m_module); + return 0; } static PyObject * meth_get__self__(PyCFunctionObject *m, void *closure) { - PyObject *self; + PyObject *self; - self = m->m_self; - if (self == NULL) - self = Py_None; - Py_INCREF(self); - return self; + self = m->m_self; + if (self == NULL) + self = Py_None; + Py_INCREF(self); + return self; } static PyGetSetDef meth_getsets [] = { - {"__doc__", (getter)meth_get__doc__, NULL, NULL}, - {"__name__", (getter)meth_get__name__, NULL, NULL}, - {"__self__", (getter)meth_get__self__, NULL, NULL}, - {0} + {"__doc__", (getter)meth_get__doc__, NULL, NULL}, + {"__name__", (getter)meth_get__name__, NULL, NULL}, + {"__self__", (getter)meth_get__self__, NULL, NULL}, + {0} }; #define OFF(x) offsetof(PyCFunctionObject, x) static PyMemberDef meth_members[] = { - {"__module__", T_OBJECT, OFF(m_module), PY_WRITE_RESTRICTED}, - {NULL} + {"__module__", T_OBJECT, OFF(m_module), PY_WRITE_RESTRICTED}, + {NULL} }; static PyObject * meth_repr(PyCFunctionObject *m) { - if (m->m_self == NULL || PyModule_Check(m->m_self)) - return PyUnicode_FromFormat("", - m->m_ml->ml_name); - return PyUnicode_FromFormat("", - m->m_ml->ml_name, - m->m_self->ob_type->tp_name, - m->m_self); + if (m->m_self == NULL || PyModule_Check(m->m_self)) + return PyUnicode_FromFormat("", + m->m_ml->ml_name); + return PyUnicode_FromFormat("", + m->m_ml->ml_name, + m->m_self->ob_type->tp_name, + m->m_self); } static PyObject * meth_richcompare(PyObject *self, PyObject *other, int op) { - PyCFunctionObject *a, *b; - PyObject *res; - int eq; - - if ((op != Py_EQ && op != Py_NE) || - !PyCFunction_Check(self) || - !PyCFunction_Check(other)) - { - Py_INCREF(Py_NotImplemented); - return Py_NotImplemented; - } - a = (PyCFunctionObject *)self; - b = (PyCFunctionObject *)other; - eq = a->m_self == b->m_self; - if (eq) - eq = a->m_ml->ml_meth == b->m_ml->ml_meth; - if (op == Py_EQ) - res = eq ? Py_True : Py_False; - else - res = eq ? Py_False : Py_True; - Py_INCREF(res); - return res; + PyCFunctionObject *a, *b; + PyObject *res; + int eq; + + if ((op != Py_EQ && op != Py_NE) || + !PyCFunction_Check(self) || + !PyCFunction_Check(other)) + { + Py_INCREF(Py_NotImplemented); + return Py_NotImplemented; + } + a = (PyCFunctionObject *)self; + b = (PyCFunctionObject *)other; + eq = a->m_self == b->m_self; + if (eq) + eq = a->m_ml->ml_meth == b->m_ml->ml_meth; + if (op == Py_EQ) + res = eq ? Py_True : Py_False; + else + res = eq ? Py_False : Py_True; + Py_INCREF(res); + return res; } static long meth_hash(PyCFunctionObject *a) { - long x,y; - if (a->m_self == NULL) - x = 0; - else { - x = PyObject_Hash(a->m_self); - if (x == -1) - return -1; - } - y = _Py_HashPointer((void*)(a->m_ml->ml_meth)); - if (y == -1) - return -1; - x ^= y; - if (x == -1) - x = -2; - return x; + long x,y; + if (a->m_self == NULL) + x = 0; + else { + x = PyObject_Hash(a->m_self); + if (x == -1) + return -1; + } + y = _Py_HashPointer((void*)(a->m_ml->ml_meth)); + if (y == -1) + return -1; + x ^= y; + if (x == -1) + x = -2; + return x; } PyTypeObject PyCFunction_Type = { - PyVarObject_HEAD_INIT(&PyType_Type, 0) - "builtin_function_or_method", - sizeof(PyCFunctionObject), - 0, - (destructor)meth_dealloc, /* tp_dealloc */ - 0, /* tp_print */ - 0, /* tp_getattr */ - 0, /* tp_setattr */ - 0, /* tp_reserved */ - (reprfunc)meth_repr, /* tp_repr */ - 0, /* tp_as_number */ - 0, /* tp_as_sequence */ - 0, /* tp_as_mapping */ - (hashfunc)meth_hash, /* tp_hash */ - PyCFunction_Call, /* 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)meth_traverse, /* tp_traverse */ - 0, /* tp_clear */ - meth_richcompare, /* tp_richcompare */ - 0, /* tp_weaklistoffset */ - 0, /* tp_iter */ - 0, /* tp_iternext */ - 0, /* tp_methods */ - meth_members, /* tp_members */ - meth_getsets, /* tp_getset */ - 0, /* tp_base */ - 0, /* tp_dict */ + PyVarObject_HEAD_INIT(&PyType_Type, 0) + "builtin_function_or_method", + sizeof(PyCFunctionObject), + 0, + (destructor)meth_dealloc, /* tp_dealloc */ + 0, /* tp_print */ + 0, /* tp_getattr */ + 0, /* tp_setattr */ + 0, /* tp_reserved */ + (reprfunc)meth_repr, /* tp_repr */ + 0, /* tp_as_number */ + 0, /* tp_as_sequence */ + 0, /* tp_as_mapping */ + (hashfunc)meth_hash, /* tp_hash */ + PyCFunction_Call, /* 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)meth_traverse, /* tp_traverse */ + 0, /* tp_clear */ + meth_richcompare, /* tp_richcompare */ + 0, /* tp_weaklistoffset */ + 0, /* tp_iter */ + 0, /* tp_iternext */ + 0, /* tp_methods */ + meth_members, /* tp_members */ + meth_getsets, /* tp_getset */ + 0, /* tp_base */ + 0, /* tp_dict */ }; /* Clear out the free list */ @@ -285,22 +285,22 @@ int PyCFunction_ClearFreeList(void) { - int freelist_size = numfree; - - while (free_list) { - PyCFunctionObject *v = free_list; - free_list = (PyCFunctionObject *)(v->m_self); - PyObject_GC_Del(v); - numfree--; - } - assert(numfree == 0); - return freelist_size; + int freelist_size = numfree; + + while (free_list) { + PyCFunctionObject *v = free_list; + free_list = (PyCFunctionObject *)(v->m_self); + PyObject_GC_Del(v); + numfree--; + } + assert(numfree == 0); + return freelist_size; } void PyCFunction_Fini(void) { - (void)PyCFunction_ClearFreeList(); + (void)PyCFunction_ClearFreeList(); } /* PyCFunction_New() is now just a macro that calls PyCFunction_NewEx(), @@ -314,5 +314,5 @@ PyObject * PyCFunction_New(PyMethodDef *ml, PyObject *self) { - return PyCFunction_NewEx(ml, self, NULL); + return PyCFunction_NewEx(ml, self, NULL); } Modified: python/branches/release31-maint/Objects/moduleobject.c ============================================================================== --- python/branches/release31-maint/Objects/moduleobject.c (original) +++ python/branches/release31-maint/Objects/moduleobject.c Sun May 9 18:14:21 2010 @@ -7,53 +7,53 @@ static Py_ssize_t max_module_number; typedef struct { - PyObject_HEAD - PyObject *md_dict; - struct PyModuleDef *md_def; - void *md_state; + PyObject_HEAD + PyObject *md_dict; + struct PyModuleDef *md_def; + void *md_state; } PyModuleObject; static PyMemberDef module_members[] = { - {"__dict__", T_OBJECT, offsetof(PyModuleObject, md_dict), READONLY}, - {0} + {"__dict__", T_OBJECT, offsetof(PyModuleObject, md_dict), READONLY}, + {0} }; static PyTypeObject moduledef_type = { - PyVarObject_HEAD_INIT(&PyType_Type, 0) - "moduledef", /* tp_name */ - sizeof(struct PyModuleDef), /* tp_size */ - 0, /* tp_itemsize */ + PyVarObject_HEAD_INIT(&PyType_Type, 0) + "moduledef", /* tp_name */ + sizeof(struct PyModuleDef), /* tp_size */ + 0, /* tp_itemsize */ }; PyObject * PyModule_New(const char *name) { - PyModuleObject *m; - PyObject *nameobj; - m = PyObject_GC_New(PyModuleObject, &PyModule_Type); - if (m == NULL) - return NULL; - m->md_def = NULL; - m->md_state = NULL; - nameobj = PyUnicode_FromString(name); - m->md_dict = PyDict_New(); - if (m->md_dict == NULL || nameobj == NULL) - goto fail; - if (PyDict_SetItemString(m->md_dict, "__name__", nameobj) != 0) - goto fail; - if (PyDict_SetItemString(m->md_dict, "__doc__", Py_None) != 0) - goto fail; - if (PyDict_SetItemString(m->md_dict, "__package__", Py_None) != 0) - goto fail; - Py_DECREF(nameobj); - PyObject_GC_Track(m); - return (PyObject *)m; + PyModuleObject *m; + PyObject *nameobj; + m = PyObject_GC_New(PyModuleObject, &PyModule_Type); + if (m == NULL) + return NULL; + m->md_def = NULL; + m->md_state = NULL; + nameobj = PyUnicode_FromString(name); + m->md_dict = PyDict_New(); + if (m->md_dict == NULL || nameobj == NULL) + goto fail; + if (PyDict_SetItemString(m->md_dict, "__name__", nameobj) != 0) + goto fail; + if (PyDict_SetItemString(m->md_dict, "__doc__", Py_None) != 0) + goto fail; + if (PyDict_SetItemString(m->md_dict, "__package__", Py_None) != 0) + goto fail; + Py_DECREF(nameobj); + PyObject_GC_Track(m); + return (PyObject *)m; fail: - Py_XDECREF(nameobj); - Py_DECREF(m); - return NULL; + Py_XDECREF(nameobj); + Py_DECREF(m); + return NULL; } static char api_version_warning[] = @@ -63,221 +63,221 @@ PyObject * PyModule_Create2(struct PyModuleDef* module, int module_api_version) { - PyObject *d, *v, *n; - PyMethodDef *ml; - const char* name; - PyModuleObject *m; - if (!Py_IsInitialized()) - Py_FatalError("Interpreter not initialized (version mismatch?)"); - if (PyType_Ready(&moduledef_type) < 0) - return NULL; - if (module->m_base.m_index == 0) { - max_module_number++; - Py_REFCNT(module) = 1; - Py_TYPE(module) = &moduledef_type; - module->m_base.m_index = max_module_number; - } - name = module->m_name; - if (module_api_version != PYTHON_API_VERSION) { - char message[512]; - PyOS_snprintf(message, sizeof(message), - api_version_warning, name, - PYTHON_API_VERSION, name, - module_api_version); - if (PyErr_WarnEx(PyExc_RuntimeWarning, message, 1)) - return NULL; - } - /* Make sure name is fully qualified. - - This is a bit of a hack: when the shared library is loaded, - the module name is "package.module", but the module calls - PyModule_Create*() with just "module" for the name. The shared - library loader squirrels away the true name of the module in - _Py_PackageContext, and PyModule_Create*() will substitute this - (if the name actually matches). - */ - if (_Py_PackageContext != NULL) { - char *p = strrchr(_Py_PackageContext, '.'); - if (p != NULL && strcmp(module->m_name, p+1) == 0) { - name = _Py_PackageContext; - _Py_PackageContext = NULL; - } - } - if ((m = (PyModuleObject*)PyModule_New(name)) == NULL) - return NULL; - - if (module->m_size > 0) { - m->md_state = PyMem_MALLOC(module->m_size); - if (!m->md_state) { - PyErr_NoMemory(); - Py_DECREF(m); - return NULL; - } - memset(m->md_state, 0, module->m_size); - } - - d = PyModule_GetDict((PyObject*)m); - if (module->m_methods != NULL) { - n = PyUnicode_FromString(name); - if (n == NULL) - return NULL; - for (ml = module->m_methods; ml->ml_name != NULL; ml++) { - if ((ml->ml_flags & METH_CLASS) || - (ml->ml_flags & METH_STATIC)) { - PyErr_SetString(PyExc_ValueError, - "module functions cannot set" - " METH_CLASS or METH_STATIC"); - Py_DECREF(n); - return NULL; - } - v = PyCFunction_NewEx(ml, (PyObject*)m, n); - if (v == NULL) { - Py_DECREF(n); - return NULL; - } - if (PyDict_SetItemString(d, ml->ml_name, v) != 0) { - Py_DECREF(v); - Py_DECREF(n); - return NULL; - } - Py_DECREF(v); - } - Py_DECREF(n); - } - if (module->m_doc != NULL) { - v = PyUnicode_FromString(module->m_doc); - if (v == NULL || PyDict_SetItemString(d, "__doc__", v) != 0) { - Py_XDECREF(v); - return NULL; - } - Py_DECREF(v); - } - m->md_def = module; - return (PyObject*)m; + PyObject *d, *v, *n; + PyMethodDef *ml; + const char* name; + PyModuleObject *m; + if (!Py_IsInitialized()) + Py_FatalError("Interpreter not initialized (version mismatch?)"); + if (PyType_Ready(&moduledef_type) < 0) + return NULL; + if (module->m_base.m_index == 0) { + max_module_number++; + Py_REFCNT(module) = 1; + Py_TYPE(module) = &moduledef_type; + module->m_base.m_index = max_module_number; + } + name = module->m_name; + if (module_api_version != PYTHON_API_VERSION) { + char message[512]; + PyOS_snprintf(message, sizeof(message), + api_version_warning, name, + PYTHON_API_VERSION, name, + module_api_version); + if (PyErr_WarnEx(PyExc_RuntimeWarning, message, 1)) + return NULL; + } + /* Make sure name is fully qualified. + + This is a bit of a hack: when the shared library is loaded, + the module name is "package.module", but the module calls + PyModule_Create*() with just "module" for the name. The shared + library loader squirrels away the true name of the module in + _Py_PackageContext, and PyModule_Create*() will substitute this + (if the name actually matches). + */ + if (_Py_PackageContext != NULL) { + char *p = strrchr(_Py_PackageContext, '.'); + if (p != NULL && strcmp(module->m_name, p+1) == 0) { + name = _Py_PackageContext; + _Py_PackageContext = NULL; + } + } + if ((m = (PyModuleObject*)PyModule_New(name)) == NULL) + return NULL; + + if (module->m_size > 0) { + m->md_state = PyMem_MALLOC(module->m_size); + if (!m->md_state) { + PyErr_NoMemory(); + Py_DECREF(m); + return NULL; + } + memset(m->md_state, 0, module->m_size); + } + + d = PyModule_GetDict((PyObject*)m); + if (module->m_methods != NULL) { + n = PyUnicode_FromString(name); + if (n == NULL) + return NULL; + for (ml = module->m_methods; ml->ml_name != NULL; ml++) { + if ((ml->ml_flags & METH_CLASS) || + (ml->ml_flags & METH_STATIC)) { + PyErr_SetString(PyExc_ValueError, + "module functions cannot set" + " METH_CLASS or METH_STATIC"); + Py_DECREF(n); + return NULL; + } + v = PyCFunction_NewEx(ml, (PyObject*)m, n); + if (v == NULL) { + Py_DECREF(n); + return NULL; + } + if (PyDict_SetItemString(d, ml->ml_name, v) != 0) { + Py_DECREF(v); + Py_DECREF(n); + return NULL; + } + Py_DECREF(v); + } + Py_DECREF(n); + } + if (module->m_doc != NULL) { + v = PyUnicode_FromString(module->m_doc); + if (v == NULL || PyDict_SetItemString(d, "__doc__", v) != 0) { + Py_XDECREF(v); + return NULL; + } + Py_DECREF(v); + } + m->md_def = module; + return (PyObject*)m; } PyObject * PyModule_GetDict(PyObject *m) { - PyObject *d; - if (!PyModule_Check(m)) { - PyErr_BadInternalCall(); - return NULL; - } - d = ((PyModuleObject *)m) -> md_dict; - if (d == NULL) - ((PyModuleObject *)m) -> md_dict = d = PyDict_New(); - return d; + PyObject *d; + if (!PyModule_Check(m)) { + PyErr_BadInternalCall(); + return NULL; + } + d = ((PyModuleObject *)m) -> md_dict; + if (d == NULL) + ((PyModuleObject *)m) -> md_dict = d = PyDict_New(); + return d; } const char * PyModule_GetName(PyObject *m) { - PyObject *d; - PyObject *nameobj; - if (!PyModule_Check(m)) { - PyErr_BadArgument(); - return NULL; - } - d = ((PyModuleObject *)m)->md_dict; - if (d == NULL || - (nameobj = PyDict_GetItemString(d, "__name__")) == NULL || - !PyUnicode_Check(nameobj)) - { - PyErr_SetString(PyExc_SystemError, "nameless module"); - return NULL; - } - return _PyUnicode_AsString(nameobj); + PyObject *d; + PyObject *nameobj; + if (!PyModule_Check(m)) { + PyErr_BadArgument(); + return NULL; + } + d = ((PyModuleObject *)m)->md_dict; + if (d == NULL || + (nameobj = PyDict_GetItemString(d, "__name__")) == NULL || + !PyUnicode_Check(nameobj)) + { + PyErr_SetString(PyExc_SystemError, "nameless module"); + return NULL; + } + return _PyUnicode_AsString(nameobj); } const char * PyModule_GetFilename(PyObject *m) { - PyObject *d; - PyObject *fileobj; - if (!PyModule_Check(m)) { - PyErr_BadArgument(); - return NULL; - } - d = ((PyModuleObject *)m)->md_dict; - if (d == NULL || - (fileobj = PyDict_GetItemString(d, "__file__")) == NULL || - !PyUnicode_Check(fileobj)) - { - PyErr_SetString(PyExc_SystemError, "module filename missing"); - return NULL; - } - return _PyUnicode_AsString(fileobj); + PyObject *d; + PyObject *fileobj; + if (!PyModule_Check(m)) { + PyErr_BadArgument(); + return NULL; + } + d = ((PyModuleObject *)m)->md_dict; + if (d == NULL || + (fileobj = PyDict_GetItemString(d, "__file__")) == NULL || + !PyUnicode_Check(fileobj)) + { + PyErr_SetString(PyExc_SystemError, "module filename missing"); + return NULL; + } + return _PyUnicode_AsString(fileobj); } PyModuleDef* PyModule_GetDef(PyObject* m) { - if (!PyModule_Check(m)) { - PyErr_BadArgument(); - return NULL; - } - return ((PyModuleObject *)m)->md_def; + if (!PyModule_Check(m)) { + PyErr_BadArgument(); + return NULL; + } + return ((PyModuleObject *)m)->md_def; } void* PyModule_GetState(PyObject* m) { - if (!PyModule_Check(m)) { - PyErr_BadArgument(); - return NULL; - } - return ((PyModuleObject *)m)->md_state; + if (!PyModule_Check(m)) { + PyErr_BadArgument(); + return NULL; + } + return ((PyModuleObject *)m)->md_state; } void _PyModule_Clear(PyObject *m) { - /* To make the execution order of destructors for global - objects a bit more predictable, we first zap all objects - whose name starts with a single underscore, before we clear - the entire dictionary. We zap them by replacing them with - None, rather than deleting them from the dictionary, to - avoid rehashing the dictionary (to some extent). */ - - Py_ssize_t pos; - PyObject *key, *value; - PyObject *d; - - d = ((PyModuleObject *)m)->md_dict; - if (d == NULL) - return; - - /* First, clear only names starting with a single underscore */ - pos = 0; - while (PyDict_Next(d, &pos, &key, &value)) { - if (value != Py_None && PyUnicode_Check(key)) { - const char *s = _PyUnicode_AsString(key); - if (s[0] == '_' && s[1] != '_') { - if (Py_VerboseFlag > 1) - PySys_WriteStderr("# clear[1] %s\n", s); - PyDict_SetItem(d, key, Py_None); - } - } - } - - /* Next, clear all names except for __builtins__ */ - pos = 0; - while (PyDict_Next(d, &pos, &key, &value)) { - if (value != Py_None && PyUnicode_Check(key)) { - const char *s = _PyUnicode_AsString(key); - if (s[0] != '_' || strcmp(s, "__builtins__") != 0) { - if (Py_VerboseFlag > 1) - PySys_WriteStderr("# clear[2] %s\n", s); - PyDict_SetItem(d, key, Py_None); - } - } - } - - /* Note: we leave __builtins__ in place, so that destructors - of non-global objects defined in this module can still use - builtins, in particularly 'None'. */ + /* To make the execution order of destructors for global + objects a bit more predictable, we first zap all objects + whose name starts with a single underscore, before we clear + the entire dictionary. We zap them by replacing them with + None, rather than deleting them from the dictionary, to + avoid rehashing the dictionary (to some extent). */ + + Py_ssize_t pos; + PyObject *key, *value; + PyObject *d; + + d = ((PyModuleObject *)m)->md_dict; + if (d == NULL) + return; + + /* First, clear only names starting with a single underscore */ + pos = 0; + while (PyDict_Next(d, &pos, &key, &value)) { + if (value != Py_None && PyUnicode_Check(key)) { + const char *s = _PyUnicode_AsString(key); + if (s[0] == '_' && s[1] != '_') { + if (Py_VerboseFlag > 1) + PySys_WriteStderr("# clear[1] %s\n", s); + PyDict_SetItem(d, key, Py_None); + } + } + } + + /* Next, clear all names except for __builtins__ */ + pos = 0; + while (PyDict_Next(d, &pos, &key, &value)) { + if (value != Py_None && PyUnicode_Check(key)) { + const char *s = _PyUnicode_AsString(key); + if (s[0] != '_' || strcmp(s, "__builtins__") != 0) { + if (Py_VerboseFlag > 1) + PySys_WriteStderr("# clear[2] %s\n", s); + PyDict_SetItem(d, key, Py_None); + } + } + } + + /* Note: we leave __builtins__ in place, so that destructors + of non-global objects defined in this module can still use + builtins, in particularly 'None'. */ } @@ -286,86 +286,86 @@ static int module_init(PyModuleObject *m, PyObject *args, PyObject *kwds) { - static char *kwlist[] = {"name", "doc", NULL}; - PyObject *dict, *name = Py_None, *doc = Py_None; - if (!PyArg_ParseTupleAndKeywords(args, kwds, "U|O:module.__init__", - kwlist, &name, &doc)) - return -1; - dict = m->md_dict; - if (dict == NULL) { - dict = PyDict_New(); - if (dict == NULL) - return -1; - m->md_dict = dict; - } - if (PyDict_SetItemString(dict, "__name__", name) < 0) - return -1; - if (PyDict_SetItemString(dict, "__doc__", doc) < 0) - return -1; - return 0; + static char *kwlist[] = {"name", "doc", NULL}; + PyObject *dict, *name = Py_None, *doc = Py_None; + if (!PyArg_ParseTupleAndKeywords(args, kwds, "U|O:module.__init__", + kwlist, &name, &doc)) + return -1; + dict = m->md_dict; + if (dict == NULL) { + dict = PyDict_New(); + if (dict == NULL) + return -1; + m->md_dict = dict; + } + if (PyDict_SetItemString(dict, "__name__", name) < 0) + return -1; + if (PyDict_SetItemString(dict, "__doc__", doc) < 0) + return -1; + return 0; } static void module_dealloc(PyModuleObject *m) { - PyObject_GC_UnTrack(m); - if (m->md_def && m->md_def->m_free) - m->md_def->m_free(m); - if (m->md_dict != NULL) { - /* If we are the only ones holding a reference, we can clear - the dictionary. */ - if (Py_REFCNT(m->md_dict) == 1) - _PyModule_Clear((PyObject *)m); - Py_DECREF(m->md_dict); - } - if (m->md_state != NULL) - PyMem_FREE(m->md_state); - Py_TYPE(m)->tp_free((PyObject *)m); + PyObject_GC_UnTrack(m); + if (m->md_def && m->md_def->m_free) + m->md_def->m_free(m); + if (m->md_dict != NULL) { + /* If we are the only ones holding a reference, we can clear + the dictionary. */ + if (Py_REFCNT(m->md_dict) == 1) + _PyModule_Clear((PyObject *)m); + Py_DECREF(m->md_dict); + } + if (m->md_state != NULL) + PyMem_FREE(m->md_state); + Py_TYPE(m)->tp_free((PyObject *)m); } static PyObject * module_repr(PyModuleObject *m) { - const char *name; - const char *filename; + const char *name; + const char *filename; - name = PyModule_GetName((PyObject *)m); - if (name == NULL) { - PyErr_Clear(); - name = "?"; - } - filename = PyModule_GetFilename((PyObject *)m); - if (filename == NULL) { - PyErr_Clear(); - return PyUnicode_FromFormat("", name); - } - return PyUnicode_FromFormat("", name, filename); + name = PyModule_GetName((PyObject *)m); + if (name == NULL) { + PyErr_Clear(); + name = "?"; + } + filename = PyModule_GetFilename((PyObject *)m); + if (filename == NULL) { + PyErr_Clear(); + return PyUnicode_FromFormat("", name); + } + return PyUnicode_FromFormat("", name, filename); } static int module_traverse(PyModuleObject *m, visitproc visit, void *arg) { - if (m->md_def && m->md_def->m_traverse) { - int res = m->md_def->m_traverse((PyObject*)m, visit, arg); - if (res) - return res; - } - Py_VISIT(m->md_dict); - return 0; + if (m->md_def && m->md_def->m_traverse) { + int res = m->md_def->m_traverse((PyObject*)m, visit, arg); + if (res) + return res; + } + Py_VISIT(m->md_dict); + return 0; } static int module_clear(PyModuleObject *m) { - if (m->md_def && m->md_def->m_clear) { - int res = m->md_def->m_clear((PyObject*)m); - if (res) - return res; - } - Py_CLEAR(m->md_dict); - return 0; + if (m->md_def && m->md_def->m_clear) { + int res = m->md_def->m_clear((PyObject*)m); + if (res) + return res; + } + Py_CLEAR(m->md_dict); + return 0; } - + PyDoc_STRVAR(module_doc, "module(name[, doc])\n\ @@ -374,44 +374,44 @@ 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 */ - 0, /* tp_itemsize */ - (destructor)module_dealloc, /* tp_dealloc */ - 0, /* tp_print */ - 0, /* tp_getattr */ - 0, /* tp_setattr */ - 0, /* tp_reserved */ - (reprfunc)module_repr, /* 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 */ - PyObject_GenericSetAttr, /* tp_setattro */ - 0, /* tp_as_buffer */ - Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC | - Py_TPFLAGS_BASETYPE, /* tp_flags */ - module_doc, /* tp_doc */ - (traverseproc)module_traverse, /* tp_traverse */ - (inquiry)module_clear, /* tp_clear */ - 0, /* tp_richcompare */ - 0, /* tp_weaklistoffset */ - 0, /* tp_iter */ - 0, /* tp_iternext */ - 0, /* tp_methods */ - module_members, /* tp_members */ - 0, /* tp_getset */ - 0, /* tp_base */ - 0, /* tp_dict */ - 0, /* tp_descr_get */ - 0, /* tp_descr_set */ - offsetof(PyModuleObject, md_dict), /* tp_dictoffset */ - (initproc)module_init, /* tp_init */ - PyType_GenericAlloc, /* tp_alloc */ - PyType_GenericNew, /* tp_new */ - PyObject_GC_Del, /* tp_free */ + PyVarObject_HEAD_INIT(&PyType_Type, 0) + "module", /* tp_name */ + sizeof(PyModuleObject), /* tp_size */ + 0, /* tp_itemsize */ + (destructor)module_dealloc, /* tp_dealloc */ + 0, /* tp_print */ + 0, /* tp_getattr */ + 0, /* tp_setattr */ + 0, /* tp_reserved */ + (reprfunc)module_repr, /* 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 */ + PyObject_GenericSetAttr, /* tp_setattro */ + 0, /* tp_as_buffer */ + Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC | + Py_TPFLAGS_BASETYPE, /* tp_flags */ + module_doc, /* tp_doc */ + (traverseproc)module_traverse, /* tp_traverse */ + (inquiry)module_clear, /* tp_clear */ + 0, /* tp_richcompare */ + 0, /* tp_weaklistoffset */ + 0, /* tp_iter */ + 0, /* tp_iternext */ + 0, /* tp_methods */ + module_members, /* tp_members */ + 0, /* tp_getset */ + 0, /* tp_base */ + 0, /* tp_dict */ + 0, /* tp_descr_get */ + 0, /* tp_descr_set */ + offsetof(PyModuleObject, md_dict), /* tp_dictoffset */ + (initproc)module_init, /* tp_init */ + PyType_GenericAlloc, /* tp_alloc */ + PyType_GenericNew, /* tp_new */ + PyObject_GC_Del, /* tp_free */ }; Modified: python/branches/release31-maint/Objects/object.c ============================================================================== --- python/branches/release31-maint/Objects/object.c (original) +++ python/branches/release31-maint/Objects/object.c Sun May 9 18:14:21 2010 @@ -15,18 +15,18 @@ Py_ssize_t _Py_GetRefTotal(void) { - PyObject *o; - Py_ssize_t total = _Py_RefTotal; - /* ignore the references to the dummy object of the dicts and sets - because they are not reliable and not useful (now that the - hash table code is well-tested) */ - o = _PyDict_Dummy(); - if (o != NULL) - total -= o->ob_refcnt; - o = _PySet_Dummy(); - if (o != NULL) - total -= o->ob_refcnt; - return total; + PyObject *o; + Py_ssize_t total = _Py_RefTotal; + /* ignore the references to the dummy object of the dicts and sets + because they are not reliable and not useful (now that the + hash table code is well-tested) */ + o = _PyDict_Dummy(); + if (o != NULL) + total -= o->ob_refcnt; + o = _PySet_Dummy(); + if (o != NULL) + total -= o->ob_refcnt; + return total; } #endif /* Py_REF_DEBUG */ @@ -58,21 +58,21 @@ _Py_AddToAllObjects(PyObject *op, int force) { #ifdef Py_DEBUG - if (!force) { - /* If it's initialized memory, op must be in or out of - * the list unambiguously. - */ - assert((op->_ob_prev == NULL) == (op->_ob_next == NULL)); - } + if (!force) { + /* If it's initialized memory, op must be in or out of + * the list unambiguously. + */ + assert((op->_ob_prev == NULL) == (op->_ob_next == NULL)); + } #endif - if (force || op->_ob_prev == NULL) { - op->_ob_next = refchain._ob_next; - op->_ob_prev = &refchain; - refchain._ob_next->_ob_prev = op; - refchain._ob_next = op; - } + if (force || op->_ob_prev == NULL) { + op->_ob_next = refchain._ob_next; + op->_ob_prev = &refchain; + refchain._ob_next->_ob_prev = op; + refchain._ob_next = op; + } } -#endif /* Py_TRACE_REFS */ +#endif /* Py_TRACE_REFS */ #ifdef COUNT_ALLOCS static PyTypeObject *type_list; @@ -89,99 +89,99 @@ void dump_counts(FILE* f) { - PyTypeObject *tp; + PyTypeObject *tp; - for (tp = type_list; tp; tp = tp->tp_next) - fprintf(f, "%s alloc'd: %" PY_FORMAT_SIZE_T "d, " - "freed: %" PY_FORMAT_SIZE_T "d, " - "max in use: %" PY_FORMAT_SIZE_T "d\n", - tp->tp_name, tp->tp_allocs, tp->tp_frees, - tp->tp_maxalloc); - fprintf(f, "fast tuple allocs: %" PY_FORMAT_SIZE_T "d, " - "empty: %" PY_FORMAT_SIZE_T "d\n", - fast_tuple_allocs, tuple_zero_allocs); - fprintf(f, "fast int allocs: pos: %" PY_FORMAT_SIZE_T "d, " - "neg: %" PY_FORMAT_SIZE_T "d\n", - quick_int_allocs, quick_neg_int_allocs); - fprintf(f, "null strings: %" PY_FORMAT_SIZE_T "d, " - "1-strings: %" PY_FORMAT_SIZE_T "d\n", - null_strings, one_strings); + for (tp = type_list; tp; tp = tp->tp_next) + fprintf(f, "%s alloc'd: %" PY_FORMAT_SIZE_T "d, " + "freed: %" PY_FORMAT_SIZE_T "d, " + "max in use: %" PY_FORMAT_SIZE_T "d\n", + tp->tp_name, tp->tp_allocs, tp->tp_frees, + tp->tp_maxalloc); + fprintf(f, "fast tuple allocs: %" PY_FORMAT_SIZE_T "d, " + "empty: %" PY_FORMAT_SIZE_T "d\n", + fast_tuple_allocs, tuple_zero_allocs); + fprintf(f, "fast int allocs: pos: %" PY_FORMAT_SIZE_T "d, " + "neg: %" PY_FORMAT_SIZE_T "d\n", + quick_int_allocs, quick_neg_int_allocs); + fprintf(f, "null strings: %" PY_FORMAT_SIZE_T "d, " + "1-strings: %" PY_FORMAT_SIZE_T "d\n", + null_strings, one_strings); } PyObject * get_counts(void) { - PyTypeObject *tp; - PyObject *result; - PyObject *v; - - result = PyList_New(0); - if (result == NULL) - return NULL; - for (tp = type_list; tp; tp = tp->tp_next) { - v = Py_BuildValue("(snnn)", tp->tp_name, tp->tp_allocs, - tp->tp_frees, tp->tp_maxalloc); - if (v == NULL) { - Py_DECREF(result); - return NULL; - } - if (PyList_Append(result, v) < 0) { - Py_DECREF(v); - Py_DECREF(result); - return NULL; - } - Py_DECREF(v); - } - return result; + PyTypeObject *tp; + PyObject *result; + PyObject *v; + + result = PyList_New(0); + if (result == NULL) + return NULL; + for (tp = type_list; tp; tp = tp->tp_next) { + v = Py_BuildValue("(snnn)", tp->tp_name, tp->tp_allocs, + tp->tp_frees, tp->tp_maxalloc); + if (v == NULL) { + Py_DECREF(result); + return NULL; + } + if (PyList_Append(result, v) < 0) { + Py_DECREF(v); + Py_DECREF(result); + return NULL; + } + Py_DECREF(v); + } + return result; } void inc_count(PyTypeObject *tp) { - if (tp->tp_next == NULL && tp->tp_prev == NULL) { - /* first time; insert in linked list */ - if (tp->tp_next != NULL) /* sanity check */ - Py_FatalError("XXX inc_count sanity check"); - if (type_list) - type_list->tp_prev = tp; - tp->tp_next = type_list; - /* Note that as of Python 2.2, heap-allocated type objects - * can go away, but this code requires that they stay alive - * until program exit. That's why we're careful with - * refcounts here. type_list gets a new reference to tp, - * while ownership of the reference type_list used to hold - * (if any) was transferred to tp->tp_next in the line above. - * tp is thus effectively immortal after this. - */ - Py_INCREF(tp); - type_list = tp; + if (tp->tp_next == NULL && tp->tp_prev == NULL) { + /* first time; insert in linked list */ + if (tp->tp_next != NULL) /* sanity check */ + Py_FatalError("XXX inc_count sanity check"); + if (type_list) + type_list->tp_prev = tp; + tp->tp_next = type_list; + /* Note that as of Python 2.2, heap-allocated type objects + * can go away, but this code requires that they stay alive + * until program exit. That's why we're careful with + * refcounts here. type_list gets a new reference to tp, + * while ownership of the reference type_list used to hold + * (if any) was transferred to tp->tp_next in the line above. + * tp is thus effectively immortal after this. + */ + Py_INCREF(tp); + type_list = tp; #ifdef Py_TRACE_REFS - /* Also insert in the doubly-linked list of all objects, - * if not already there. - */ - _Py_AddToAllObjects((PyObject *)tp, 0); + /* Also insert in the doubly-linked list of all objects, + * if not already there. + */ + _Py_AddToAllObjects((PyObject *)tp, 0); #endif - } - tp->tp_allocs++; - if (tp->tp_allocs - tp->tp_frees > tp->tp_maxalloc) - tp->tp_maxalloc = tp->tp_allocs - tp->tp_frees; + } + tp->tp_allocs++; + if (tp->tp_allocs - tp->tp_frees > tp->tp_maxalloc) + tp->tp_maxalloc = tp->tp_allocs - tp->tp_frees; } void dec_count(PyTypeObject *tp) { - tp->tp_frees++; - if (unlist_types_without_objects && - tp->tp_allocs == tp->tp_frees) { - /* unlink the type from type_list */ - if (tp->tp_prev) - tp->tp_prev->tp_next = tp->tp_next; - else - type_list = tp->tp_next; - if (tp->tp_next) - tp->tp_next->tp_prev = tp->tp_prev; - tp->tp_next = tp->tp_prev = NULL; - Py_DECREF(tp); - } + tp->tp_frees++; + if (unlist_types_without_objects && + tp->tp_allocs == tp->tp_frees) { + /* unlink the type from type_list */ + if (tp->tp_prev) + tp->tp_prev->tp_next = tp->tp_next; + else + type_list = tp->tp_next; + if (tp->tp_next) + tp->tp_next->tp_prev = tp->tp_prev; + tp->tp_next = tp->tp_prev = NULL; + Py_DECREF(tp); + } } #endif @@ -191,13 +191,13 @@ void _Py_NegativeRefcount(const char *fname, int lineno, PyObject *op) { - char buf[300]; + char buf[300]; - PyOS_snprintf(buf, sizeof(buf), - "%s:%i object at %p has negative ref count " - "%" PY_FORMAT_SIZE_T "d", - fname, lineno, op, op->ob_refcnt); - Py_FatalError(buf); + PyOS_snprintf(buf, sizeof(buf), + "%s:%i object at %p has negative ref count " + "%" PY_FORMAT_SIZE_T "d", + fname, lineno, op, op->ob_refcnt); + Py_FatalError(buf); } #endif /* Py_REF_DEBUG */ @@ -217,123 +217,123 @@ PyObject * PyObject_Init(PyObject *op, PyTypeObject *tp) { - if (op == NULL) - return PyErr_NoMemory(); - /* Any changes should be reflected in PyObject_INIT (objimpl.h) */ - Py_TYPE(op) = tp; - _Py_NewReference(op); - return op; + if (op == NULL) + return PyErr_NoMemory(); + /* Any changes should be reflected in PyObject_INIT (objimpl.h) */ + Py_TYPE(op) = tp; + _Py_NewReference(op); + return op; } PyVarObject * PyObject_InitVar(PyVarObject *op, PyTypeObject *tp, Py_ssize_t size) { - if (op == NULL) - return (PyVarObject *) PyErr_NoMemory(); - /* Any changes should be reflected in PyObject_INIT_VAR */ - op->ob_size = size; - Py_TYPE(op) = tp; - _Py_NewReference((PyObject *)op); - return op; + if (op == NULL) + return (PyVarObject *) PyErr_NoMemory(); + /* Any changes should be reflected in PyObject_INIT_VAR */ + op->ob_size = size; + Py_TYPE(op) = tp; + _Py_NewReference((PyObject *)op); + return op; } PyObject * _PyObject_New(PyTypeObject *tp) { - PyObject *op; - op = (PyObject *) PyObject_MALLOC(_PyObject_SIZE(tp)); - if (op == NULL) - return PyErr_NoMemory(); - return PyObject_INIT(op, tp); + PyObject *op; + op = (PyObject *) PyObject_MALLOC(_PyObject_SIZE(tp)); + if (op == NULL) + return PyErr_NoMemory(); + return PyObject_INIT(op, tp); } PyVarObject * _PyObject_NewVar(PyTypeObject *tp, Py_ssize_t nitems) { - PyVarObject *op; - const size_t size = _PyObject_VAR_SIZE(tp, nitems); - op = (PyVarObject *) PyObject_MALLOC(size); - if (op == NULL) - return (PyVarObject *)PyErr_NoMemory(); - return PyObject_INIT_VAR(op, tp, nitems); + PyVarObject *op; + const size_t size = _PyObject_VAR_SIZE(tp, nitems); + op = (PyVarObject *) PyObject_MALLOC(size); + if (op == NULL) + return (PyVarObject *)PyErr_NoMemory(); + return PyObject_INIT_VAR(op, tp, nitems); } /* Implementation of PyObject_Print with recursion checking */ static int internal_print(PyObject *op, FILE *fp, int flags, int nesting) { - int ret = 0; - if (nesting > 10) { - PyErr_SetString(PyExc_RuntimeError, "print recursion"); - return -1; - } - if (PyErr_CheckSignals()) - return -1; + int ret = 0; + if (nesting > 10) { + PyErr_SetString(PyExc_RuntimeError, "print recursion"); + return -1; + } + if (PyErr_CheckSignals()) + return -1; #ifdef USE_STACKCHECK - if (PyOS_CheckStack()) { - PyErr_SetString(PyExc_MemoryError, "stack overflow"); - return -1; - } + if (PyOS_CheckStack()) { + PyErr_SetString(PyExc_MemoryError, "stack overflow"); + return -1; + } #endif - clearerr(fp); /* Clear any previous error condition */ - if (op == NULL) { - Py_BEGIN_ALLOW_THREADS - fprintf(fp, ""); - Py_END_ALLOW_THREADS - } - else { - if (op->ob_refcnt <= 0) - /* XXX(twouters) cast refcount to long until %zd is - universally available */ - Py_BEGIN_ALLOW_THREADS - fprintf(fp, "", - (long)op->ob_refcnt, op); - Py_END_ALLOW_THREADS - else { - PyObject *s; - if (flags & Py_PRINT_RAW) - s = PyObject_Str(op); - else - s = PyObject_Repr(op); - if (s == NULL) - ret = -1; - else if (PyBytes_Check(s)) { - fwrite(PyBytes_AS_STRING(s), 1, - PyBytes_GET_SIZE(s), fp); - } - else if (PyUnicode_Check(s)) { - PyObject *t; - t = _PyUnicode_AsDefaultEncodedString(s, NULL); - if (t == NULL) - ret = 0; - else { - fwrite(PyBytes_AS_STRING(t), 1, - PyBytes_GET_SIZE(t), fp); - } - } - else { - PyErr_Format(PyExc_TypeError, - "str() or repr() returned '%.100s'", - s->ob_type->tp_name); - ret = -1; - } - Py_XDECREF(s); - } - } - if (ret == 0) { - if (ferror(fp)) { - PyErr_SetFromErrno(PyExc_IOError); - clearerr(fp); - ret = -1; - } - } - return ret; + clearerr(fp); /* Clear any previous error condition */ + if (op == NULL) { + Py_BEGIN_ALLOW_THREADS + fprintf(fp, ""); + Py_END_ALLOW_THREADS + } + else { + if (op->ob_refcnt <= 0) + /* XXX(twouters) cast refcount to long until %zd is + universally available */ + Py_BEGIN_ALLOW_THREADS + fprintf(fp, "", + (long)op->ob_refcnt, op); + Py_END_ALLOW_THREADS + else { + PyObject *s; + if (flags & Py_PRINT_RAW) + s = PyObject_Str(op); + else + s = PyObject_Repr(op); + if (s == NULL) + ret = -1; + else if (PyBytes_Check(s)) { + fwrite(PyBytes_AS_STRING(s), 1, + PyBytes_GET_SIZE(s), fp); + } + else if (PyUnicode_Check(s)) { + PyObject *t; + t = _PyUnicode_AsDefaultEncodedString(s, NULL); + if (t == NULL) + ret = 0; + else { + fwrite(PyBytes_AS_STRING(t), 1, + PyBytes_GET_SIZE(t), fp); + } + } + else { + PyErr_Format(PyExc_TypeError, + "str() or repr() returned '%.100s'", + s->ob_type->tp_name); + ret = -1; + } + Py_XDECREF(s); + } + } + if (ret == 0) { + if (ferror(fp)) { + PyErr_SetFromErrno(PyExc_IOError); + clearerr(fp); + ret = -1; + } + } + return ret; } int PyObject_Print(PyObject *op, FILE *fp, int flags) { - return internal_print(op, fp, flags, 0); + return internal_print(op, fp, flags, 0); } /* For debugging convenience. Set a breakpoint here and call it from your DLL */ @@ -347,159 +347,159 @@ void _PyObject_Dump(PyObject* op) { - if (op == NULL) - fprintf(stderr, "NULL\n"); - else { + if (op == NULL) + fprintf(stderr, "NULL\n"); + else { #ifdef WITH_THREAD - PyGILState_STATE gil; + PyGILState_STATE gil; #endif - fprintf(stderr, "object : "); + fprintf(stderr, "object : "); #ifdef WITH_THREAD - gil = PyGILState_Ensure(); + gil = PyGILState_Ensure(); #endif - (void)PyObject_Print(op, stderr, 0); + (void)PyObject_Print(op, stderr, 0); #ifdef WITH_THREAD - PyGILState_Release(gil); + PyGILState_Release(gil); #endif - /* XXX(twouters) cast refcount to long until %zd is - universally available */ - fprintf(stderr, "\n" - "type : %s\n" - "refcount: %ld\n" - "address : %p\n", - Py_TYPE(op)==NULL ? "NULL" : Py_TYPE(op)->tp_name, - (long)op->ob_refcnt, - op); - } + /* XXX(twouters) cast refcount to long until %zd is + universally available */ + fprintf(stderr, "\n" + "type : %s\n" + "refcount: %ld\n" + "address : %p\n", + Py_TYPE(op)==NULL ? "NULL" : Py_TYPE(op)->tp_name, + (long)op->ob_refcnt, + op); + } } PyObject * PyObject_Repr(PyObject *v) { - PyObject *res; - if (PyErr_CheckSignals()) - return NULL; + PyObject *res; + if (PyErr_CheckSignals()) + return NULL; #ifdef USE_STACKCHECK - if (PyOS_CheckStack()) { - PyErr_SetString(PyExc_MemoryError, "stack overflow"); - return NULL; - } + if (PyOS_CheckStack()) { + PyErr_SetString(PyExc_MemoryError, "stack overflow"); + return NULL; + } #endif - if (v == NULL) - return PyUnicode_FromString(""); - if (Py_TYPE(v)->tp_repr == NULL) - return PyUnicode_FromFormat("<%s object at %p>", - v->ob_type->tp_name, v); - res = (*v->ob_type->tp_repr)(v); - if (res != NULL && !PyUnicode_Check(res)) { - PyErr_Format(PyExc_TypeError, - "__repr__ returned non-string (type %.200s)", - res->ob_type->tp_name); - Py_DECREF(res); - return NULL; - } - return res; + if (v == NULL) + return PyUnicode_FromString(""); + if (Py_TYPE(v)->tp_repr == NULL) + return PyUnicode_FromFormat("<%s object at %p>", + v->ob_type->tp_name, v); + res = (*v->ob_type->tp_repr)(v); + if (res != NULL && !PyUnicode_Check(res)) { + PyErr_Format(PyExc_TypeError, + "__repr__ returned non-string (type %.200s)", + res->ob_type->tp_name); + Py_DECREF(res); + return NULL; + } + return res; } PyObject * PyObject_Str(PyObject *v) { - PyObject *res; - if (PyErr_CheckSignals()) - return NULL; + PyObject *res; + if (PyErr_CheckSignals()) + return NULL; #ifdef USE_STACKCHECK - if (PyOS_CheckStack()) { - PyErr_SetString(PyExc_MemoryError, "stack overflow"); - return NULL; - } + if (PyOS_CheckStack()) { + PyErr_SetString(PyExc_MemoryError, "stack overflow"); + return NULL; + } #endif - if (v == NULL) - return PyUnicode_FromString(""); - if (PyUnicode_CheckExact(v)) { - Py_INCREF(v); - return v; - } - if (Py_TYPE(v)->tp_str == NULL) - return PyObject_Repr(v); - - /* It is possible for a type to have a tp_str representation that loops - infinitely. */ - if (Py_EnterRecursiveCall(" while getting the str of an object")) - return NULL; - res = (*Py_TYPE(v)->tp_str)(v); - Py_LeaveRecursiveCall(); - if (res == NULL) - return NULL; - if (!PyUnicode_Check(res)) { - PyErr_Format(PyExc_TypeError, - "__str__ returned non-string (type %.200s)", - Py_TYPE(res)->tp_name); - Py_DECREF(res); - return NULL; - } - return res; + if (v == NULL) + return PyUnicode_FromString(""); + if (PyUnicode_CheckExact(v)) { + Py_INCREF(v); + return v; + } + if (Py_TYPE(v)->tp_str == NULL) + return PyObject_Repr(v); + + /* It is possible for a type to have a tp_str representation that loops + infinitely. */ + if (Py_EnterRecursiveCall(" while getting the str of an object")) + return NULL; + res = (*Py_TYPE(v)->tp_str)(v); + Py_LeaveRecursiveCall(); + if (res == NULL) + return NULL; + if (!PyUnicode_Check(res)) { + PyErr_Format(PyExc_TypeError, + "__str__ returned non-string (type %.200s)", + Py_TYPE(res)->tp_name); + Py_DECREF(res); + return NULL; + } + return res; } PyObject * PyObject_ASCII(PyObject *v) { - PyObject *repr, *ascii, *res; - - repr = PyObject_Repr(v); - if (repr == NULL) - return NULL; - - /* repr is guaranteed to be a PyUnicode object by PyObject_Repr */ - ascii = PyUnicode_EncodeASCII( - PyUnicode_AS_UNICODE(repr), - PyUnicode_GET_SIZE(repr), - "backslashreplace"); - - Py_DECREF(repr); - if (ascii == NULL) - return NULL; - - res = PyUnicode_DecodeASCII( - PyBytes_AS_STRING(ascii), - PyBytes_GET_SIZE(ascii), - NULL); + PyObject *repr, *ascii, *res; - Py_DECREF(ascii); - return res; + repr = PyObject_Repr(v); + if (repr == NULL) + return NULL; + + /* repr is guaranteed to be a PyUnicode object by PyObject_Repr */ + ascii = PyUnicode_EncodeASCII( + PyUnicode_AS_UNICODE(repr), + PyUnicode_GET_SIZE(repr), + "backslashreplace"); + + Py_DECREF(repr); + if (ascii == NULL) + return NULL; + + res = PyUnicode_DecodeASCII( + PyBytes_AS_STRING(ascii), + PyBytes_GET_SIZE(ascii), + NULL); + + Py_DECREF(ascii); + return res; } PyObject * PyObject_Bytes(PyObject *v) { - PyObject *result, *func; - static PyObject *bytesstring = NULL; + PyObject *result, *func; + static PyObject *bytesstring = NULL; - if (v == NULL) - return PyBytes_FromString(""); + if (v == NULL) + return PyBytes_FromString(""); - if (PyBytes_CheckExact(v)) { - Py_INCREF(v); - return v; - } - - func = _PyObject_LookupSpecial(v, "__bytes__", &bytesstring); - if (func != NULL) { - result = PyObject_CallFunctionObjArgs(func, NULL); - 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; - } - return result; - } - else if (PyErr_Occurred()) - return NULL; - return PyBytes_FromObject(v); + if (PyBytes_CheckExact(v)) { + Py_INCREF(v); + return v; + } + + func = _PyObject_LookupSpecial(v, "__bytes__", &bytesstring); + if (func != NULL) { + result = PyObject_CallFunctionObjArgs(func, NULL); + 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; + } + return result; + } + else if (PyErr_Occurred()) + return NULL; + return PyBytes_FromObject(v); } /* For Python 3.0.1 and later, the old three-way comparison has been @@ -542,49 +542,49 @@ static PyObject * do_richcompare(PyObject *v, PyObject *w, int op) { - richcmpfunc f; - PyObject *res; + richcmpfunc f; + PyObject *res; - if (v->ob_type != w->ob_type && - PyType_IsSubtype(w->ob_type, v->ob_type) && - (f = w->ob_type->tp_richcompare) != NULL) { - res = (*f)(w, v, _Py_SwappedOp[op]); - if (res != Py_NotImplemented) - return res; - Py_DECREF(res); - } - if ((f = v->ob_type->tp_richcompare) != NULL) { - res = (*f)(v, w, op); - if (res != Py_NotImplemented) - return res; - Py_DECREF(res); - } - if ((f = w->ob_type->tp_richcompare) != NULL) { - res = (*f)(w, v, _Py_SwappedOp[op]); - if (res != Py_NotImplemented) - return res; - Py_DECREF(res); - } - /* If neither object implements it, provide a sensible default - for == and !=, but raise an exception for ordering. */ - switch (op) { - case Py_EQ: - res = (v == w) ? Py_True : Py_False; - break; - case Py_NE: - res = (v != w) ? Py_True : Py_False; - break; - default: - /* XXX Special-case None so it doesn't show as NoneType() */ - PyErr_Format(PyExc_TypeError, - "unorderable types: %.100s() %s %.100s()", - v->ob_type->tp_name, - opstrings[op], - w->ob_type->tp_name); - return NULL; - } - Py_INCREF(res); - return res; + if (v->ob_type != w->ob_type && + PyType_IsSubtype(w->ob_type, v->ob_type) && + (f = w->ob_type->tp_richcompare) != NULL) { + res = (*f)(w, v, _Py_SwappedOp[op]); + if (res != Py_NotImplemented) + return res; + Py_DECREF(res); + } + if ((f = v->ob_type->tp_richcompare) != NULL) { + res = (*f)(v, w, op); + if (res != Py_NotImplemented) + return res; + Py_DECREF(res); + } + if ((f = w->ob_type->tp_richcompare) != NULL) { + res = (*f)(w, v, _Py_SwappedOp[op]); + if (res != Py_NotImplemented) + return res; + Py_DECREF(res); + } + /* If neither object implements it, provide a sensible default + for == and !=, but raise an exception for ordering. */ + switch (op) { + case Py_EQ: + res = (v == w) ? Py_True : Py_False; + break; + case Py_NE: + res = (v != w) ? Py_True : Py_False; + break; + default: + /* XXX Special-case None so it doesn't show as NoneType() */ + PyErr_Format(PyExc_TypeError, + "unorderable types: %.100s() %s %.100s()", + v->ob_type->tp_name, + opstrings[op], + w->ob_type->tp_name); + return NULL; + } + Py_INCREF(res); + return res; } /* Perform a rich comparison with object result. This wraps do_richcompare() @@ -593,19 +593,19 @@ PyObject * PyObject_RichCompare(PyObject *v, PyObject *w, int op) { - PyObject *res; + PyObject *res; - assert(Py_LT <= op && op <= Py_GE); - if (v == NULL || w == NULL) { - if (!PyErr_Occurred()) - PyErr_BadInternalCall(); - return NULL; - } - if (Py_EnterRecursiveCall(" in comparison")) - return NULL; - res = do_richcompare(v, w, op); - Py_LeaveRecursiveCall(); - return res; + assert(Py_LT <= op && op <= Py_GE); + if (v == NULL || w == NULL) { + if (!PyErr_Occurred()) + PyErr_BadInternalCall(); + return NULL; + } + if (Py_EnterRecursiveCall(" in comparison")) + return NULL; + res = do_richcompare(v, w, op); + Py_LeaveRecursiveCall(); + return res; } /* Perform a rich comparison with integer result. This wraps @@ -613,31 +613,31 @@ int PyObject_RichCompareBool(PyObject *v, PyObject *w, int op) { - PyObject *res; - int ok; + PyObject *res; + int ok; - /* Quick result when objects are the same. - Guarantees that identity implies equality. */ - if (v == w) { - if (op == Py_EQ) - return 1; - else if (op == Py_NE) - return 0; - } - - res = PyObject_RichCompare(v, w, op); - if (res == NULL) - return -1; - if (PyBool_Check(res)) - ok = (res == Py_True); - else - ok = PyObject_IsTrue(res); - Py_DECREF(res); - return ok; + /* Quick result when objects are the same. + Guarantees that identity implies equality. */ + if (v == w) { + if (op == Py_EQ) + return 1; + else if (op == Py_NE) + return 0; + } + + res = PyObject_RichCompare(v, w, op); + if (res == NULL) + return -1; + if (PyBool_Check(res)) + ok = (res == Py_True); + else + ok = PyObject_IsTrue(res); + Py_DECREF(res); + return ok; } /* Set of hash utility functions to help maintaining the invariant that - if a==b then hash(a)==hash(b) + if a==b then hash(a)==hash(b) All the utility functions (_Py_Hash*()) return "-1" to signify an error. */ @@ -645,227 +645,227 @@ long _Py_HashDouble(double v) { - double intpart, fractpart; - int expo; - long hipart; - long x; /* the final hash value */ - /* This is designed so that Python numbers of different types - * that compare equal hash to the same value; otherwise comparisons - * of mapping keys will turn out weird. - */ - - fractpart = modf(v, &intpart); - if (fractpart == 0.0) { - /* This must return the same hash as an equal int or long. */ - if (intpart > LONG_MAX/2 || -intpart > LONG_MAX/2) { - /* Convert to long and use its hash. */ - PyObject *plong; /* converted to Python long */ - if (Py_IS_INFINITY(intpart)) - /* can't convert to long int -- arbitrary */ - v = v < 0 ? -271828.0 : 314159.0; - plong = PyLong_FromDouble(v); - if (plong == NULL) - return -1; - x = PyObject_Hash(plong); - Py_DECREF(plong); - return x; - } - /* Fits in a C long == a Python int, so is its own hash. */ - x = (long)intpart; - if (x == -1) - x = -2; - return x; - } - /* The fractional part is non-zero, so we don't have to worry about - * making this match the hash of some other type. - * Use frexp to get at the bits in the double. - * Since the VAX D double format has 56 mantissa bits, which is the - * most of any double format in use, each of these parts may have as - * many as (but no more than) 56 significant bits. - * So, assuming sizeof(long) >= 4, each part can be broken into two - * longs; frexp and multiplication are used to do that. - * Also, since the Cray double format has 15 exponent bits, which is - * the most of any double format in use, shifting the exponent field - * left by 15 won't overflow a long (again assuming sizeof(long) >= 4). - */ - v = frexp(v, &expo); - v *= 2147483648.0; /* 2**31 */ - hipart = (long)v; /* take the top 32 bits */ - v = (v - (double)hipart) * 2147483648.0; /* get the next 32 bits */ - x = hipart + (long)v + (expo << 15); - if (x == -1) - x = -2; - return x; + double intpart, fractpart; + int expo; + long hipart; + long x; /* the final hash value */ + /* This is designed so that Python numbers of different types + * that compare equal hash to the same value; otherwise comparisons + * of mapping keys will turn out weird. + */ + + fractpart = modf(v, &intpart); + if (fractpart == 0.0) { + /* This must return the same hash as an equal int or long. */ + if (intpart > LONG_MAX/2 || -intpart > LONG_MAX/2) { + /* Convert to long and use its hash. */ + PyObject *plong; /* converted to Python long */ + if (Py_IS_INFINITY(intpart)) + /* can't convert to long int -- arbitrary */ + v = v < 0 ? -271828.0 : 314159.0; + plong = PyLong_FromDouble(v); + if (plong == NULL) + return -1; + x = PyObject_Hash(plong); + Py_DECREF(plong); + return x; + } + /* Fits in a C long == a Python int, so is its own hash. */ + x = (long)intpart; + if (x == -1) + x = -2; + return x; + } + /* The fractional part is non-zero, so we don't have to worry about + * making this match the hash of some other type. + * Use frexp to get at the bits in the double. + * Since the VAX D double format has 56 mantissa bits, which is the + * most of any double format in use, each of these parts may have as + * many as (but no more than) 56 significant bits. + * So, assuming sizeof(long) >= 4, each part can be broken into two + * longs; frexp and multiplication are used to do that. + * Also, since the Cray double format has 15 exponent bits, which is + * the most of any double format in use, shifting the exponent field + * left by 15 won't overflow a long (again assuming sizeof(long) >= 4). + */ + v = frexp(v, &expo); + v *= 2147483648.0; /* 2**31 */ + hipart = (long)v; /* take the top 32 bits */ + v = (v - (double)hipart) * 2147483648.0; /* get the next 32 bits */ + x = hipart + (long)v + (expo << 15); + if (x == -1) + x = -2; + return x; } long _Py_HashPointer(void *p) { - long x; - size_t y = (size_t)p; - /* bottom 3 or 4 bits are likely to be 0; rotate y by 4 to avoid - excessive hash collisions for dicts and sets */ - y = (y >> 4) | (y << (8 * SIZEOF_VOID_P - 4)); - x = (long)y; - if (x == -1) - x = -2; - return x; + long x; + size_t y = (size_t)p; + /* bottom 3 or 4 bits are likely to be 0; rotate y by 4 to avoid + excessive hash collisions for dicts and sets */ + y = (y >> 4) | (y << (8 * SIZEOF_VOID_P - 4)); + x = (long)y; + if (x == -1) + x = -2; + return x; } long PyObject_HashNotImplemented(PyObject *v) { - PyErr_Format(PyExc_TypeError, "unhashable type: '%.200s'", - Py_TYPE(v)->tp_name); - return -1; + PyErr_Format(PyExc_TypeError, "unhashable type: '%.200s'", + Py_TYPE(v)->tp_name); + return -1; } long PyObject_Hash(PyObject *v) { - PyTypeObject *tp = Py_TYPE(v); - if (tp->tp_hash != NULL) - return (*tp->tp_hash)(v); - /* To keep to the general practice that inheriting - * solely from object in C code should work without - * an explicit call to PyType_Ready, we implicitly call - * PyType_Ready here and then check the tp_hash slot again - */ - if (tp->tp_dict == NULL) { - if (PyType_Ready(tp) < 0) - return -1; - if (tp->tp_hash != NULL) - return (*tp->tp_hash)(v); - } - /* Otherwise, the object can't be hashed */ - return PyObject_HashNotImplemented(v); + PyTypeObject *tp = Py_TYPE(v); + if (tp->tp_hash != NULL) + return (*tp->tp_hash)(v); + /* To keep to the general practice that inheriting + * solely from object in C code should work without + * an explicit call to PyType_Ready, we implicitly call + * PyType_Ready here and then check the tp_hash slot again + */ + if (tp->tp_dict == NULL) { + if (PyType_Ready(tp) < 0) + return -1; + if (tp->tp_hash != NULL) + return (*tp->tp_hash)(v); + } + /* Otherwise, the object can't be hashed */ + return PyObject_HashNotImplemented(v); } PyObject * PyObject_GetAttrString(PyObject *v, const char *name) { - PyObject *w, *res; + PyObject *w, *res; - if (Py_TYPE(v)->tp_getattr != NULL) - return (*Py_TYPE(v)->tp_getattr)(v, (char*)name); - w = PyUnicode_InternFromString(name); - if (w == NULL) - return NULL; - res = PyObject_GetAttr(v, w); - Py_XDECREF(w); - return res; + if (Py_TYPE(v)->tp_getattr != NULL) + return (*Py_TYPE(v)->tp_getattr)(v, (char*)name); + w = PyUnicode_InternFromString(name); + if (w == NULL) + return NULL; + res = PyObject_GetAttr(v, w); + Py_XDECREF(w); + return res; } int PyObject_HasAttrString(PyObject *v, const char *name) { - PyObject *res = PyObject_GetAttrString(v, name); - if (res != NULL) { - Py_DECREF(res); - return 1; - } - PyErr_Clear(); - return 0; + PyObject *res = PyObject_GetAttrString(v, name); + if (res != NULL) { + Py_DECREF(res); + return 1; + } + PyErr_Clear(); + return 0; } int PyObject_SetAttrString(PyObject *v, const char *name, PyObject *w) { - PyObject *s; - int res; + PyObject *s; + int res; - if (Py_TYPE(v)->tp_setattr != NULL) - return (*Py_TYPE(v)->tp_setattr)(v, (char*)name, w); - s = PyUnicode_InternFromString(name); - if (s == NULL) - return -1; - res = PyObject_SetAttr(v, s, w); - Py_XDECREF(s); - return res; + if (Py_TYPE(v)->tp_setattr != NULL) + return (*Py_TYPE(v)->tp_setattr)(v, (char*)name, w); + s = PyUnicode_InternFromString(name); + if (s == NULL) + return -1; + res = PyObject_SetAttr(v, s, w); + Py_XDECREF(s); + return res; } PyObject * PyObject_GetAttr(PyObject *v, PyObject *name) { - PyTypeObject *tp = Py_TYPE(v); + PyTypeObject *tp = Py_TYPE(v); - if (!PyUnicode_Check(name)) { - PyErr_Format(PyExc_TypeError, - "attribute name must be string, not '%.200s'", - name->ob_type->tp_name); - return NULL; - } - if (tp->tp_getattro != NULL) - return (*tp->tp_getattro)(v, name); - if (tp->tp_getattr != NULL) { - char *name_str = _PyUnicode_AsString(name); - if (name_str == NULL) - return NULL; - return (*tp->tp_getattr)(v, name_str); - } - PyErr_Format(PyExc_AttributeError, - "'%.50s' object has no attribute '%U'", - tp->tp_name, name); - return NULL; + if (!PyUnicode_Check(name)) { + PyErr_Format(PyExc_TypeError, + "attribute name must be string, not '%.200s'", + name->ob_type->tp_name); + return NULL; + } + if (tp->tp_getattro != NULL) + return (*tp->tp_getattro)(v, name); + if (tp->tp_getattr != NULL) { + char *name_str = _PyUnicode_AsString(name); + if (name_str == NULL) + return NULL; + return (*tp->tp_getattr)(v, name_str); + } + PyErr_Format(PyExc_AttributeError, + "'%.50s' object has no attribute '%U'", + tp->tp_name, name); + return NULL; } int PyObject_HasAttr(PyObject *v, PyObject *name) { - PyObject *res = PyObject_GetAttr(v, name); - if (res != NULL) { - Py_DECREF(res); - return 1; - } - PyErr_Clear(); - return 0; + PyObject *res = PyObject_GetAttr(v, name); + if (res != NULL) { + Py_DECREF(res); + return 1; + } + PyErr_Clear(); + return 0; } int PyObject_SetAttr(PyObject *v, PyObject *name, PyObject *value) { - PyTypeObject *tp = Py_TYPE(v); - int err; + PyTypeObject *tp = Py_TYPE(v); + int err; - if (!PyUnicode_Check(name)) { - PyErr_Format(PyExc_TypeError, - "attribute name must be string, not '%.200s'", - name->ob_type->tp_name); - return -1; - } - Py_INCREF(name); - - PyUnicode_InternInPlace(&name); - if (tp->tp_setattro != NULL) { - err = (*tp->tp_setattro)(v, name, value); - Py_DECREF(name); - return err; - } - if (tp->tp_setattr != NULL) { - char *name_str = _PyUnicode_AsString(name); - if (name_str == NULL) - return -1; - err = (*tp->tp_setattr)(v, name_str, value); - Py_DECREF(name); - return err; - } - Py_DECREF(name); - assert(name->ob_refcnt >= 1); - if (tp->tp_getattr == NULL && tp->tp_getattro == NULL) - PyErr_Format(PyExc_TypeError, - "'%.100s' object has no attributes " - "(%s .%U)", - tp->tp_name, - value==NULL ? "del" : "assign to", - name); - else - PyErr_Format(PyExc_TypeError, - "'%.100s' object has only read-only attributes " - "(%s .%U)", - tp->tp_name, - value==NULL ? "del" : "assign to", - name); - return -1; + if (!PyUnicode_Check(name)) { + PyErr_Format(PyExc_TypeError, + "attribute name must be string, not '%.200s'", + name->ob_type->tp_name); + return -1; + } + Py_INCREF(name); + + PyUnicode_InternInPlace(&name); + if (tp->tp_setattro != NULL) { + err = (*tp->tp_setattro)(v, name, value); + Py_DECREF(name); + return err; + } + if (tp->tp_setattr != NULL) { + char *name_str = _PyUnicode_AsString(name); + if (name_str == NULL) + return -1; + err = (*tp->tp_setattr)(v, name_str, value); + Py_DECREF(name); + return err; + } + Py_DECREF(name); + assert(name->ob_refcnt >= 1); + if (tp->tp_getattr == NULL && tp->tp_getattro == NULL) + PyErr_Format(PyExc_TypeError, + "'%.100s' object has no attributes " + "(%s .%U)", + tp->tp_name, + value==NULL ? "del" : "assign to", + name); + else + PyErr_Format(PyExc_TypeError, + "'%.100s' object has only read-only attributes " + "(%s .%U)", + tp->tp_name, + value==NULL ? "del" : "assign to", + name); + return -1; } /* Helper to get a pointer to an object's __dict__ slot, if any */ @@ -873,33 +873,33 @@ PyObject ** _PyObject_GetDictPtr(PyObject *obj) { - Py_ssize_t dictoffset; - PyTypeObject *tp = Py_TYPE(obj); + Py_ssize_t dictoffset; + PyTypeObject *tp = Py_TYPE(obj); - dictoffset = tp->tp_dictoffset; - if (dictoffset == 0) - return NULL; - if (dictoffset < 0) { - Py_ssize_t tsize; - size_t size; - - tsize = ((PyVarObject *)obj)->ob_size; - if (tsize < 0) - tsize = -tsize; - size = _PyObject_VAR_SIZE(tp, tsize); - - dictoffset += (long)size; - assert(dictoffset > 0); - assert(dictoffset % SIZEOF_VOID_P == 0); - } - return (PyObject **) ((char *)obj + dictoffset); + dictoffset = tp->tp_dictoffset; + if (dictoffset == 0) + return NULL; + if (dictoffset < 0) { + Py_ssize_t tsize; + size_t size; + + tsize = ((PyVarObject *)obj)->ob_size; + if (tsize < 0) + tsize = -tsize; + size = _PyObject_VAR_SIZE(tp, tsize); + + dictoffset += (long)size; + assert(dictoffset > 0); + assert(dictoffset % SIZEOF_VOID_P == 0); + } + return (PyObject **) ((char *)obj + dictoffset); } PyObject * PyObject_SelfIter(PyObject *obj) { - Py_INCREF(obj); - return obj; + Py_INCREF(obj); + return obj; } /* Helper used when the __next__ method is removed from a type: @@ -910,10 +910,10 @@ PyObject * _PyObject_NextNotImplemented(PyObject *self) { - PyErr_Format(PyExc_TypeError, - "'%.200s' object is not iterable", - Py_TYPE(self)->tp_name); - return NULL; + PyErr_Format(PyExc_TypeError, + "'%.200s' object is not iterable", + Py_TYPE(self)->tp_name); + return NULL; } /* Generic GetAttr functions - put these in your tp_[gs]etattro slot */ @@ -921,189 +921,189 @@ PyObject * PyObject_GenericGetAttr(PyObject *obj, PyObject *name) { - PyTypeObject *tp = Py_TYPE(obj); - PyObject *descr = NULL; - PyObject *res = NULL; - descrgetfunc f; - Py_ssize_t dictoffset; - PyObject **dictptr; - - if (!PyUnicode_Check(name)){ - PyErr_Format(PyExc_TypeError, - "attribute name must be string, not '%.200s'", - name->ob_type->tp_name); - return NULL; - } - else - Py_INCREF(name); - - if (tp->tp_dict == NULL) { - if (PyType_Ready(tp) < 0) - goto done; - } + PyTypeObject *tp = Py_TYPE(obj); + PyObject *descr = NULL; + PyObject *res = NULL; + descrgetfunc f; + Py_ssize_t dictoffset; + PyObject **dictptr; + + if (!PyUnicode_Check(name)){ + PyErr_Format(PyExc_TypeError, + "attribute name must be string, not '%.200s'", + name->ob_type->tp_name); + return NULL; + } + else + Py_INCREF(name); + + if (tp->tp_dict == NULL) { + if (PyType_Ready(tp) < 0) + goto done; + } #if 0 /* XXX this is not quite _PyType_Lookup anymore */ - /* Inline _PyType_Lookup */ - { - Py_ssize_t i, n; - PyObject *mro, *base, *dict; - - /* Look in tp_dict of types in MRO */ - mro = tp->tp_mro; - assert(mro != NULL); - assert(PyTuple_Check(mro)); - n = PyTuple_GET_SIZE(mro); - for (i = 0; i < n; i++) { - base = PyTuple_GET_ITEM(mro, i); - assert(PyType_Check(base)); - dict = ((PyTypeObject *)base)->tp_dict; - assert(dict && PyDict_Check(dict)); - descr = PyDict_GetItem(dict, name); - if (descr != NULL) - break; - } - } + /* Inline _PyType_Lookup */ + { + Py_ssize_t i, n; + PyObject *mro, *base, *dict; + + /* Look in tp_dict of types in MRO */ + mro = tp->tp_mro; + assert(mro != NULL); + assert(PyTuple_Check(mro)); + n = PyTuple_GET_SIZE(mro); + for (i = 0; i < n; i++) { + base = PyTuple_GET_ITEM(mro, i); + assert(PyType_Check(base)); + dict = ((PyTypeObject *)base)->tp_dict; + assert(dict && PyDict_Check(dict)); + descr = PyDict_GetItem(dict, name); + if (descr != NULL) + break; + } + } #else - descr = _PyType_Lookup(tp, name); + descr = _PyType_Lookup(tp, name); #endif - Py_XINCREF(descr); + Py_XINCREF(descr); + + f = NULL; + if (descr != NULL) { + f = descr->ob_type->tp_descr_get; + if (f != NULL && PyDescr_IsData(descr)) { + res = f(descr, obj, (PyObject *)obj->ob_type); + Py_DECREF(descr); + goto done; + } + } - f = NULL; - if (descr != NULL) { - f = descr->ob_type->tp_descr_get; - if (f != NULL && PyDescr_IsData(descr)) { - res = f(descr, obj, (PyObject *)obj->ob_type); - Py_DECREF(descr); - goto done; - } - } - - /* Inline _PyObject_GetDictPtr */ - dictoffset = tp->tp_dictoffset; - if (dictoffset != 0) { - PyObject *dict; - if (dictoffset < 0) { - Py_ssize_t tsize; - size_t size; - - tsize = ((PyVarObject *)obj)->ob_size; - if (tsize < 0) - tsize = -tsize; - size = _PyObject_VAR_SIZE(tp, tsize); - - dictoffset += (long)size; - assert(dictoffset > 0); - assert(dictoffset % SIZEOF_VOID_P == 0); - } - dictptr = (PyObject **) ((char *)obj + dictoffset); - dict = *dictptr; - if (dict != NULL) { - Py_INCREF(dict); - res = PyDict_GetItem(dict, name); - if (res != NULL) { - Py_INCREF(res); - Py_XDECREF(descr); - Py_DECREF(dict); - goto done; - } - Py_DECREF(dict); - } - } - - if (f != NULL) { - res = f(descr, obj, (PyObject *)Py_TYPE(obj)); - Py_DECREF(descr); - goto done; - } - - if (descr != NULL) { - res = descr; - /* descr was already increfed above */ - goto done; - } - - PyErr_Format(PyExc_AttributeError, - "'%.50s' object has no attribute '%U'", - tp->tp_name, name); + /* Inline _PyObject_GetDictPtr */ + dictoffset = tp->tp_dictoffset; + if (dictoffset != 0) { + PyObject *dict; + if (dictoffset < 0) { + Py_ssize_t tsize; + size_t size; + + tsize = ((PyVarObject *)obj)->ob_size; + if (tsize < 0) + tsize = -tsize; + size = _PyObject_VAR_SIZE(tp, tsize); + + dictoffset += (long)size; + assert(dictoffset > 0); + assert(dictoffset % SIZEOF_VOID_P == 0); + } + dictptr = (PyObject **) ((char *)obj + dictoffset); + dict = *dictptr; + if (dict != NULL) { + Py_INCREF(dict); + res = PyDict_GetItem(dict, name); + if (res != NULL) { + Py_INCREF(res); + Py_XDECREF(descr); + Py_DECREF(dict); + goto done; + } + Py_DECREF(dict); + } + } + + if (f != NULL) { + res = f(descr, obj, (PyObject *)Py_TYPE(obj)); + Py_DECREF(descr); + goto done; + } + + if (descr != NULL) { + res = descr; + /* descr was already increfed above */ + goto done; + } + + PyErr_Format(PyExc_AttributeError, + "'%.50s' object has no attribute '%U'", + tp->tp_name, name); done: - Py_DECREF(name); - return res; + Py_DECREF(name); + return res; } int PyObject_GenericSetAttr(PyObject *obj, PyObject *name, PyObject *value) { - PyTypeObject *tp = Py_TYPE(obj); - PyObject *descr; - descrsetfunc f; - PyObject **dictptr; - int res = -1; - - if (!PyUnicode_Check(name)){ - PyErr_Format(PyExc_TypeError, - "attribute name must be string, not '%.200s'", - name->ob_type->tp_name); - return -1; - } - else - Py_INCREF(name); - - if (tp->tp_dict == NULL) { - if (PyType_Ready(tp) < 0) - goto done; - } - - descr = _PyType_Lookup(tp, name); - f = NULL; - if (descr != NULL) { - f = descr->ob_type->tp_descr_set; - if (f != NULL && PyDescr_IsData(descr)) { - res = f(descr, obj, value); - goto done; - } - } - - dictptr = _PyObject_GetDictPtr(obj); - if (dictptr != NULL) { - PyObject *dict = *dictptr; - if (dict == NULL && value != NULL) { - dict = PyDict_New(); - if (dict == NULL) - goto done; - *dictptr = dict; - } - if (dict != NULL) { - Py_INCREF(dict); - if (value == NULL) - res = PyDict_DelItem(dict, name); - else - res = PyDict_SetItem(dict, name, value); - if (res < 0 && PyErr_ExceptionMatches(PyExc_KeyError)) - PyErr_SetObject(PyExc_AttributeError, name); - Py_DECREF(dict); - goto done; - } - } - - if (f != NULL) { - res = f(descr, obj, value); - goto done; - } - - if (descr == NULL) { - PyErr_Format(PyExc_AttributeError, - "'%.100s' object has no attribute '%U'", - tp->tp_name, name); - goto done; - } - - PyErr_Format(PyExc_AttributeError, - "'%.50s' object attribute '%U' is read-only", - tp->tp_name, name); + PyTypeObject *tp = Py_TYPE(obj); + PyObject *descr; + descrsetfunc f; + PyObject **dictptr; + int res = -1; + + if (!PyUnicode_Check(name)){ + PyErr_Format(PyExc_TypeError, + "attribute name must be string, not '%.200s'", + name->ob_type->tp_name); + return -1; + } + else + Py_INCREF(name); + + if (tp->tp_dict == NULL) { + if (PyType_Ready(tp) < 0) + goto done; + } + + descr = _PyType_Lookup(tp, name); + f = NULL; + if (descr != NULL) { + f = descr->ob_type->tp_descr_set; + if (f != NULL && PyDescr_IsData(descr)) { + res = f(descr, obj, value); + goto done; + } + } + + dictptr = _PyObject_GetDictPtr(obj); + if (dictptr != NULL) { + PyObject *dict = *dictptr; + if (dict == NULL && value != NULL) { + dict = PyDict_New(); + if (dict == NULL) + goto done; + *dictptr = dict; + } + if (dict != NULL) { + Py_INCREF(dict); + if (value == NULL) + res = PyDict_DelItem(dict, name); + else + res = PyDict_SetItem(dict, name, value); + if (res < 0 && PyErr_ExceptionMatches(PyExc_KeyError)) + PyErr_SetObject(PyExc_AttributeError, name); + Py_DECREF(dict); + goto done; + } + } + + if (f != NULL) { + res = f(descr, obj, value); + goto done; + } + + if (descr == NULL) { + PyErr_Format(PyExc_AttributeError, + "'%.100s' object has no attribute '%U'", + tp->tp_name, name); + goto done; + } + + PyErr_Format(PyExc_AttributeError, + "'%.50s' object attribute '%U' is read-only", + tp->tp_name, name); done: - Py_DECREF(name); - return res; + Py_DECREF(name); + return res; } /* Test a value used as condition, e.g., in a for or if statement. @@ -1112,26 +1112,26 @@ int PyObject_IsTrue(PyObject *v) { - Py_ssize_t res; - if (v == Py_True) - return 1; - if (v == Py_False) - return 0; - if (v == Py_None) - return 0; - else if (v->ob_type->tp_as_number != NULL && - v->ob_type->tp_as_number->nb_bool != NULL) - res = (*v->ob_type->tp_as_number->nb_bool)(v); - else if (v->ob_type->tp_as_mapping != NULL && - v->ob_type->tp_as_mapping->mp_length != NULL) - res = (*v->ob_type->tp_as_mapping->mp_length)(v); - else if (v->ob_type->tp_as_sequence != NULL && - v->ob_type->tp_as_sequence->sq_length != NULL) - res = (*v->ob_type->tp_as_sequence->sq_length)(v); - else - return 1; - /* if it is negative, it should be either -1 or -2 */ - return (res > 0) ? 1 : Py_SAFE_DOWNCAST(res, Py_ssize_t, int); + Py_ssize_t res; + if (v == Py_True) + return 1; + if (v == Py_False) + return 0; + if (v == Py_None) + return 0; + else if (v->ob_type->tp_as_number != NULL && + v->ob_type->tp_as_number->nb_bool != NULL) + res = (*v->ob_type->tp_as_number->nb_bool)(v); + else if (v->ob_type->tp_as_mapping != NULL && + v->ob_type->tp_as_mapping->mp_length != NULL) + res = (*v->ob_type->tp_as_mapping->mp_length)(v); + else if (v->ob_type->tp_as_sequence != NULL && + v->ob_type->tp_as_sequence->sq_length != NULL) + res = (*v->ob_type->tp_as_sequence->sq_length)(v); + else + return 1; + /* if it is negative, it should be either -1 or -2 */ + return (res > 0) ? 1 : Py_SAFE_DOWNCAST(res, Py_ssize_t, int); } /* equivalent of 'not v' @@ -1140,11 +1140,11 @@ int PyObject_Not(PyObject *v) { - int res; - res = PyObject_IsTrue(v); - if (res < 0) - return res; - return res == 0; + int res; + res = PyObject_IsTrue(v); + if (res < 0) + return res; + return res == 0; } /* Test whether an object can be called */ @@ -1152,9 +1152,9 @@ int PyCallable_Check(PyObject *x) { - if (x == NULL) - return 0; - return x->ob_type->tp_call != NULL; + if (x == NULL) + return 0; + return x->ob_type->tp_call != NULL; } /* ------------------------- PyObject_Dir() helpers ------------------------- */ @@ -1170,78 +1170,78 @@ static int merge_class_dict(PyObject* dict, PyObject* aclass) { - PyObject *classdict; - PyObject *bases; + PyObject *classdict; + PyObject *bases; - assert(PyDict_Check(dict)); - assert(aclass); + assert(PyDict_Check(dict)); + assert(aclass); - /* Merge in the type's dict (if any). */ - classdict = PyObject_GetAttrString(aclass, "__dict__"); - if (classdict == NULL) - PyErr_Clear(); - else { - int status = PyDict_Update(dict, classdict); - Py_DECREF(classdict); - if (status < 0) - return -1; - } - - /* Recursively merge in the base types' (if any) dicts. */ - bases = PyObject_GetAttrString(aclass, "__bases__"); - if (bases == NULL) - PyErr_Clear(); - else { - /* We have no guarantee that bases is a real tuple */ - Py_ssize_t i, n; - n = PySequence_Size(bases); /* This better be right */ - if (n < 0) - PyErr_Clear(); - else { - for (i = 0; i < n; i++) { - int status; - PyObject *base = PySequence_GetItem(bases, i); - if (base == NULL) { - Py_DECREF(bases); - return -1; - } - status = merge_class_dict(dict, base); - Py_DECREF(base); - if (status < 0) { - Py_DECREF(bases); - return -1; - } - } - } - Py_DECREF(bases); - } - return 0; + /* Merge in the type's dict (if any). */ + classdict = PyObject_GetAttrString(aclass, "__dict__"); + if (classdict == NULL) + PyErr_Clear(); + else { + int status = PyDict_Update(dict, classdict); + Py_DECREF(classdict); + if (status < 0) + return -1; + } + + /* Recursively merge in the base types' (if any) dicts. */ + bases = PyObject_GetAttrString(aclass, "__bases__"); + if (bases == NULL) + PyErr_Clear(); + else { + /* We have no guarantee that bases is a real tuple */ + Py_ssize_t i, n; + n = PySequence_Size(bases); /* This better be right */ + if (n < 0) + PyErr_Clear(); + else { + for (i = 0; i < n; i++) { + int status; + PyObject *base = PySequence_GetItem(bases, i); + if (base == NULL) { + Py_DECREF(bases); + return -1; + } + status = merge_class_dict(dict, base); + Py_DECREF(base); + if (status < 0) { + Py_DECREF(bases); + return -1; + } + } + } + Py_DECREF(bases); + } + return 0; } /* Helper for PyObject_Dir without arguments: returns the local scope. */ static PyObject * _dir_locals(void) { - PyObject *names; - PyObject *locals = PyEval_GetLocals(); + PyObject *names; + PyObject *locals = PyEval_GetLocals(); - if (locals == NULL) { - PyErr_SetString(PyExc_SystemError, "frame does not exist"); - return NULL; - } - - names = PyMapping_Keys(locals); - if (!names) - return NULL; - if (!PyList_Check(names)) { - PyErr_Format(PyExc_TypeError, - "dir(): expected keys() of locals to be a list, " - "not '%.200s'", Py_TYPE(names)->tp_name); - Py_DECREF(names); - return NULL; - } - /* the locals don't need to be DECREF'd */ - return names; + if (locals == NULL) { + PyErr_SetString(PyExc_SystemError, "frame does not exist"); + return NULL; + } + + names = PyMapping_Keys(locals); + if (!names) + return NULL; + if (!PyList_Check(names)) { + PyErr_Format(PyExc_TypeError, + "dir(): expected keys() of locals to be a list, " + "not '%.200s'", Py_TYPE(names)->tp_name); + Py_DECREF(names); + return NULL; + } + /* the locals don't need to be DECREF'd */ + return names; } /* Helper for PyObject_Dir of type objects: returns __dict__ and __bases__. @@ -1251,37 +1251,37 @@ static PyObject * _specialized_dir_type(PyObject *obj) { - PyObject *result = NULL; - PyObject *dict = PyDict_New(); + PyObject *result = NULL; + PyObject *dict = PyDict_New(); - if (dict != NULL && merge_class_dict(dict, obj) == 0) - result = PyDict_Keys(dict); + if (dict != NULL && merge_class_dict(dict, obj) == 0) + result = PyDict_Keys(dict); - Py_XDECREF(dict); - return result; + Py_XDECREF(dict); + return result; } /* Helper for PyObject_Dir of module objects: returns the module's __dict__. */ static PyObject * _specialized_dir_module(PyObject *obj) { - PyObject *result = NULL; - PyObject *dict = PyObject_GetAttrString(obj, "__dict__"); + PyObject *result = NULL; + PyObject *dict = PyObject_GetAttrString(obj, "__dict__"); - if (dict != NULL) { - if (PyDict_Check(dict)) - result = PyDict_Keys(dict); - else { - const char *name = PyModule_GetName(obj); - if (name) - PyErr_Format(PyExc_TypeError, - "%.200s.__dict__ is not a dictionary", - name); - } - } + if (dict != NULL) { + if (PyDict_Check(dict)) + result = PyDict_Keys(dict); + else { + const char *name = PyModule_GetName(obj); + if (name) + PyErr_Format(PyExc_TypeError, + "%.200s.__dict__ is not a dictionary", + name); + } + } - Py_XDECREF(dict); - return result; + Py_XDECREF(dict); + return result; } /* Helper for PyObject_Dir of generic objects: returns __dict__, __class__, @@ -1290,47 +1290,47 @@ static PyObject * _generic_dir(PyObject *obj) { - PyObject *result = NULL; - PyObject *dict = NULL; - PyObject *itsclass = NULL; - - /* Get __dict__ (which may or may not be a real dict...) */ - dict = PyObject_GetAttrString(obj, "__dict__"); - if (dict == NULL) { - PyErr_Clear(); - dict = PyDict_New(); - } - else if (!PyDict_Check(dict)) { - Py_DECREF(dict); - dict = PyDict_New(); - } - else { - /* Copy __dict__ to avoid mutating it. */ - PyObject *temp = PyDict_Copy(dict); - Py_DECREF(dict); - dict = temp; - } - - if (dict == NULL) - goto error; - - /* Merge in attrs reachable from its class. */ - itsclass = PyObject_GetAttrString(obj, "__class__"); - if (itsclass == NULL) - /* XXX(tomer): Perhaps fall back to obj->ob_type if no - __class__ exists? */ - PyErr_Clear(); - else { - if (merge_class_dict(dict, itsclass) != 0) - goto error; - } + PyObject *result = NULL; + PyObject *dict = NULL; + PyObject *itsclass = NULL; + + /* Get __dict__ (which may or may not be a real dict...) */ + dict = PyObject_GetAttrString(obj, "__dict__"); + if (dict == NULL) { + PyErr_Clear(); + dict = PyDict_New(); + } + else if (!PyDict_Check(dict)) { + Py_DECREF(dict); + dict = PyDict_New(); + } + else { + /* Copy __dict__ to avoid mutating it. */ + PyObject *temp = PyDict_Copy(dict); + Py_DECREF(dict); + dict = temp; + } + + if (dict == NULL) + goto error; + + /* Merge in attrs reachable from its class. */ + itsclass = PyObject_GetAttrString(obj, "__class__"); + if (itsclass == NULL) + /* XXX(tomer): Perhaps fall back to obj->ob_type if no + __class__ exists? */ + PyErr_Clear(); + else { + if (merge_class_dict(dict, itsclass) != 0) + goto error; + } - result = PyDict_Keys(dict); - /* fall through */ + result = PyDict_Keys(dict); + /* fall through */ error: - Py_XDECREF(itsclass); - Py_XDECREF(dict); - return result; + Py_XDECREF(itsclass); + Py_XDECREF(dict); + return result; } /* Helper for PyObject_Dir: object introspection. @@ -1339,40 +1339,40 @@ static PyObject * _dir_object(PyObject *obj) { - PyObject * result = NULL; - PyObject * dirfunc = PyObject_GetAttrString((PyObject*)obj->ob_type, - "__dir__"); - - assert(obj); - if (dirfunc == NULL) { - /* use default implementation */ - PyErr_Clear(); - if (PyModule_Check(obj)) - result = _specialized_dir_module(obj); - else if (PyType_Check(obj)) - result = _specialized_dir_type(obj); - else - result = _generic_dir(obj); - } - else { - /* use __dir__ */ - result = PyObject_CallFunctionObjArgs(dirfunc, obj, NULL); - Py_DECREF(dirfunc); - if (result == NULL) - return NULL; - - /* result must be a list */ - /* XXX(gbrandl): could also check if all items are strings */ - if (!PyList_Check(result)) { - PyErr_Format(PyExc_TypeError, - "__dir__() must return a list, not %.200s", - Py_TYPE(result)->tp_name); - Py_DECREF(result); - result = NULL; - } - } + PyObject * result = NULL; + PyObject * dirfunc = PyObject_GetAttrString((PyObject*)obj->ob_type, + "__dir__"); + + assert(obj); + if (dirfunc == NULL) { + /* use default implementation */ + PyErr_Clear(); + if (PyModule_Check(obj)) + result = _specialized_dir_module(obj); + else if (PyType_Check(obj)) + result = _specialized_dir_type(obj); + else + result = _generic_dir(obj); + } + else { + /* use __dir__ */ + result = PyObject_CallFunctionObjArgs(dirfunc, obj, NULL); + Py_DECREF(dirfunc); + if (result == NULL) + return NULL; + + /* result must be a list */ + /* XXX(gbrandl): could also check if all items are strings */ + if (!PyList_Check(result)) { + PyErr_Format(PyExc_TypeError, + "__dir__() must return a list, not %.200s", + Py_TYPE(result)->tp_name); + Py_DECREF(result); + result = NULL; + } + } - return result; + return result; } /* Implementation of dir() -- if obj is NULL, returns the names in the current @@ -1382,24 +1382,24 @@ PyObject * PyObject_Dir(PyObject *obj) { - PyObject * result; + PyObject * result; - if (obj == NULL) - /* no object -- introspect the locals */ - result = _dir_locals(); - else - /* object -- introspect the object */ - result = _dir_object(obj); - - assert(result == NULL || PyList_Check(result)); - - if (result != NULL && PyList_Sort(result) != 0) { - /* sorting the list failed */ - Py_DECREF(result); - result = NULL; - } + if (obj == NULL) + /* no object -- introspect the locals */ + result = _dir_locals(); + else + /* object -- introspect the object */ + result = _dir_object(obj); + + assert(result == NULL || PyList_Check(result)); + + if (result != NULL && PyList_Sort(result) != 0) { + /* sorting the list failed */ + Py_DECREF(result); + result = NULL; + } - return result; + return result; } /* @@ -1413,35 +1413,35 @@ static PyObject * none_repr(PyObject *op) { - return PyUnicode_FromString("None"); + return PyUnicode_FromString("None"); } /* ARGUSED */ static void none_dealloc(PyObject* ignore) { - /* This should never get called, but we also don't want to SEGV if - * we accidentally decref None out of existence. - */ - Py_FatalError("deallocating None"); + /* This should never get called, but we also don't want to SEGV if + * we accidentally decref None out of existence. + */ + Py_FatalError("deallocating None"); } static PyTypeObject PyNone_Type = { - PyVarObject_HEAD_INIT(&PyType_Type, 0) - "NoneType", - 0, - 0, - none_dealloc, /*tp_dealloc*/ /*never called*/ - 0, /*tp_print*/ - 0, /*tp_getattr*/ - 0, /*tp_setattr*/ - 0, /*tp_reserved*/ - none_repr, /*tp_repr*/ - 0, /*tp_as_number*/ - 0, /*tp_as_sequence*/ - 0, /*tp_as_mapping*/ - 0, /*tp_hash */ + PyVarObject_HEAD_INIT(&PyType_Type, 0) + "NoneType", + 0, + 0, + none_dealloc, /*tp_dealloc*/ /*never called*/ + 0, /*tp_print*/ + 0, /*tp_getattr*/ + 0, /*tp_setattr*/ + 0, /*tp_reserved*/ + none_repr, /*tp_repr*/ + 0, /*tp_as_number*/ + 0, /*tp_as_sequence*/ + 0, /*tp_as_mapping*/ + 0, /*tp_hash */ }; PyObject _Py_NoneStruct = { @@ -1455,166 +1455,166 @@ static PyObject * NotImplemented_repr(PyObject *op) { - return PyUnicode_FromString("NotImplemented"); + return PyUnicode_FromString("NotImplemented"); } static PyTypeObject PyNotImplemented_Type = { - PyVarObject_HEAD_INIT(&PyType_Type, 0) - "NotImplementedType", - 0, - 0, - none_dealloc, /*tp_dealloc*/ /*never called*/ - 0, /*tp_print*/ - 0, /*tp_getattr*/ - 0, /*tp_setattr*/ - 0, /*tp_reserved*/ - NotImplemented_repr, /*tp_repr*/ - 0, /*tp_as_number*/ - 0, /*tp_as_sequence*/ - 0, /*tp_as_mapping*/ - 0, /*tp_hash */ + PyVarObject_HEAD_INIT(&PyType_Type, 0) + "NotImplementedType", + 0, + 0, + none_dealloc, /*tp_dealloc*/ /*never called*/ + 0, /*tp_print*/ + 0, /*tp_getattr*/ + 0, /*tp_setattr*/ + 0, /*tp_reserved*/ + NotImplemented_repr, /*tp_repr*/ + 0, /*tp_as_number*/ + 0, /*tp_as_sequence*/ + 0, /*tp_as_mapping*/ + 0, /*tp_hash */ }; PyObject _Py_NotImplementedStruct = { - _PyObject_EXTRA_INIT - 1, &PyNotImplemented_Type + _PyObject_EXTRA_INIT + 1, &PyNotImplemented_Type }; void _Py_ReadyTypes(void) { - if (PyType_Ready(&PyType_Type) < 0) - Py_FatalError("Can't initialize type type"); + if (PyType_Ready(&PyType_Type) < 0) + Py_FatalError("Can't initialize type type"); - if (PyType_Ready(&_PyWeakref_RefType) < 0) - Py_FatalError("Can't initialize weakref type"); + if (PyType_Ready(&_PyWeakref_RefType) < 0) + Py_FatalError("Can't initialize weakref type"); - if (PyType_Ready(&_PyWeakref_CallableProxyType) < 0) - Py_FatalError("Can't initialize callable weakref proxy type"); + if (PyType_Ready(&_PyWeakref_CallableProxyType) < 0) + Py_FatalError("Can't initialize callable weakref proxy type"); - if (PyType_Ready(&_PyWeakref_ProxyType) < 0) - Py_FatalError("Can't initialize weakref proxy type"); + if (PyType_Ready(&_PyWeakref_ProxyType) < 0) + Py_FatalError("Can't initialize weakref proxy type"); - if (PyType_Ready(&PyBool_Type) < 0) - Py_FatalError("Can't initialize bool type"); + if (PyType_Ready(&PyBool_Type) < 0) + Py_FatalError("Can't initialize bool type"); - if (PyType_Ready(&PyByteArray_Type) < 0) - Py_FatalError("Can't initialize bytearray type"); + if (PyType_Ready(&PyByteArray_Type) < 0) + Py_FatalError("Can't initialize bytearray type"); - if (PyType_Ready(&PyBytes_Type) < 0) - Py_FatalError("Can't initialize 'str'"); + if (PyType_Ready(&PyBytes_Type) < 0) + Py_FatalError("Can't initialize 'str'"); - if (PyType_Ready(&PyList_Type) < 0) - Py_FatalError("Can't initialize list type"); + if (PyType_Ready(&PyList_Type) < 0) + Py_FatalError("Can't initialize list type"); - if (PyType_Ready(&PyNone_Type) < 0) - Py_FatalError("Can't initialize None type"); + if (PyType_Ready(&PyNone_Type) < 0) + Py_FatalError("Can't initialize None type"); - if (PyType_Ready(Py_Ellipsis->ob_type) < 0) - Py_FatalError("Can't initialize type(Ellipsis)"); + if (PyType_Ready(Py_Ellipsis->ob_type) < 0) + Py_FatalError("Can't initialize type(Ellipsis)"); - if (PyType_Ready(&PyNotImplemented_Type) < 0) - Py_FatalError("Can't initialize NotImplemented type"); + if (PyType_Ready(&PyNotImplemented_Type) < 0) + Py_FatalError("Can't initialize NotImplemented type"); - if (PyType_Ready(&PyTraceBack_Type) < 0) - Py_FatalError("Can't initialize traceback type"); + if (PyType_Ready(&PyTraceBack_Type) < 0) + Py_FatalError("Can't initialize traceback type"); - if (PyType_Ready(&PySuper_Type) < 0) - Py_FatalError("Can't initialize super type"); + if (PyType_Ready(&PySuper_Type) < 0) + Py_FatalError("Can't initialize super type"); - if (PyType_Ready(&PyBaseObject_Type) < 0) - Py_FatalError("Can't initialize object type"); + if (PyType_Ready(&PyBaseObject_Type) < 0) + Py_FatalError("Can't initialize object type"); - if (PyType_Ready(&PyRange_Type) < 0) - Py_FatalError("Can't initialize range type"); + if (PyType_Ready(&PyRange_Type) < 0) + Py_FatalError("Can't initialize range type"); - if (PyType_Ready(&PyDict_Type) < 0) - Py_FatalError("Can't initialize dict type"); + if (PyType_Ready(&PyDict_Type) < 0) + Py_FatalError("Can't initialize dict type"); - if (PyType_Ready(&PySet_Type) < 0) - Py_FatalError("Can't initialize set type"); + if (PyType_Ready(&PySet_Type) < 0) + Py_FatalError("Can't initialize set type"); - if (PyType_Ready(&PyUnicode_Type) < 0) - Py_FatalError("Can't initialize str type"); + if (PyType_Ready(&PyUnicode_Type) < 0) + Py_FatalError("Can't initialize str type"); - if (PyType_Ready(&PySlice_Type) < 0) - Py_FatalError("Can't initialize slice type"); + if (PyType_Ready(&PySlice_Type) < 0) + Py_FatalError("Can't initialize slice type"); - if (PyType_Ready(&PyStaticMethod_Type) < 0) - Py_FatalError("Can't initialize static method type"); + if (PyType_Ready(&PyStaticMethod_Type) < 0) + Py_FatalError("Can't initialize static method type"); #ifndef WITHOUT_COMPLEX - if (PyType_Ready(&PyComplex_Type) < 0) - Py_FatalError("Can't initialize complex type"); + if (PyType_Ready(&PyComplex_Type) < 0) + Py_FatalError("Can't initialize complex type"); #endif - if (PyType_Ready(&PyFloat_Type) < 0) - Py_FatalError("Can't initialize float type"); + if (PyType_Ready(&PyFloat_Type) < 0) + Py_FatalError("Can't initialize float type"); - if (PyType_Ready(&PyLong_Type) < 0) - Py_FatalError("Can't initialize int type"); + if (PyType_Ready(&PyLong_Type) < 0) + Py_FatalError("Can't initialize int type"); - if (PyType_Ready(&PyFrozenSet_Type) < 0) - Py_FatalError("Can't initialize frozenset type"); + if (PyType_Ready(&PyFrozenSet_Type) < 0) + Py_FatalError("Can't initialize frozenset type"); - if (PyType_Ready(&PyProperty_Type) < 0) - Py_FatalError("Can't initialize property type"); + if (PyType_Ready(&PyProperty_Type) < 0) + Py_FatalError("Can't initialize property type"); - if (PyType_Ready(&PyMemoryView_Type) < 0) - Py_FatalError("Can't initialize memoryview type"); + if (PyType_Ready(&PyMemoryView_Type) < 0) + Py_FatalError("Can't initialize memoryview type"); - if (PyType_Ready(&PyTuple_Type) < 0) - Py_FatalError("Can't initialize tuple type"); + if (PyType_Ready(&PyTuple_Type) < 0) + Py_FatalError("Can't initialize tuple type"); - if (PyType_Ready(&PyEnum_Type) < 0) - Py_FatalError("Can't initialize enumerate type"); + if (PyType_Ready(&PyEnum_Type) < 0) + Py_FatalError("Can't initialize enumerate type"); - if (PyType_Ready(&PyReversed_Type) < 0) - Py_FatalError("Can't initialize reversed type"); + if (PyType_Ready(&PyReversed_Type) < 0) + Py_FatalError("Can't initialize reversed type"); - if (PyType_Ready(&PyStdPrinter_Type) < 0) - Py_FatalError("Can't initialize StdPrinter"); + if (PyType_Ready(&PyStdPrinter_Type) < 0) + Py_FatalError("Can't initialize StdPrinter"); - if (PyType_Ready(&PyCode_Type) < 0) - Py_FatalError("Can't initialize code type"); + if (PyType_Ready(&PyCode_Type) < 0) + Py_FatalError("Can't initialize code type"); - if (PyType_Ready(&PyFrame_Type) < 0) - Py_FatalError("Can't initialize frame type"); + if (PyType_Ready(&PyFrame_Type) < 0) + Py_FatalError("Can't initialize frame type"); - if (PyType_Ready(&PyCFunction_Type) < 0) - Py_FatalError("Can't initialize builtin function type"); + if (PyType_Ready(&PyCFunction_Type) < 0) + Py_FatalError("Can't initialize builtin function type"); - if (PyType_Ready(&PyMethod_Type) < 0) - Py_FatalError("Can't initialize method type"); + if (PyType_Ready(&PyMethod_Type) < 0) + Py_FatalError("Can't initialize method type"); - if (PyType_Ready(&PyFunction_Type) < 0) - Py_FatalError("Can't initialize function type"); + if (PyType_Ready(&PyFunction_Type) < 0) + Py_FatalError("Can't initialize function type"); - if (PyType_Ready(&PyDictProxy_Type) < 0) - Py_FatalError("Can't initialize dict proxy type"); + if (PyType_Ready(&PyDictProxy_Type) < 0) + Py_FatalError("Can't initialize dict proxy type"); - if (PyType_Ready(&PyGen_Type) < 0) - Py_FatalError("Can't initialize generator type"); + if (PyType_Ready(&PyGen_Type) < 0) + Py_FatalError("Can't initialize generator type"); - if (PyType_Ready(&PyGetSetDescr_Type) < 0) - Py_FatalError("Can't initialize get-set descriptor type"); + if (PyType_Ready(&PyGetSetDescr_Type) < 0) + Py_FatalError("Can't initialize get-set descriptor type"); - if (PyType_Ready(&PyWrapperDescr_Type) < 0) - Py_FatalError("Can't initialize wrapper type"); + if (PyType_Ready(&PyWrapperDescr_Type) < 0) + Py_FatalError("Can't initialize wrapper type"); - if (PyType_Ready(&PyEllipsis_Type) < 0) - Py_FatalError("Can't initialize ellipsis type"); + if (PyType_Ready(&PyEllipsis_Type) < 0) + Py_FatalError("Can't initialize ellipsis type"); - if (PyType_Ready(&PyMemberDescr_Type) < 0) - Py_FatalError("Can't initialize member descriptor type"); + if (PyType_Ready(&PyMemberDescr_Type) < 0) + Py_FatalError("Can't initialize member descriptor type"); - if (PyType_Ready(&PyFilter_Type) < 0) - Py_FatalError("Can't initialize filter type"); + if (PyType_Ready(&PyFilter_Type) < 0) + Py_FatalError("Can't initialize filter type"); - if (PyType_Ready(&PyMap_Type) < 0) - Py_FatalError("Can't initialize map type"); + if (PyType_Ready(&PyMap_Type) < 0) + Py_FatalError("Can't initialize map type"); - if (PyType_Ready(&PyZip_Type) < 0) - Py_FatalError("Can't initialize zip type"); + if (PyType_Ready(&PyZip_Type) < 0) + Py_FatalError("Can't initialize zip type"); } @@ -1623,50 +1623,50 @@ void _Py_NewReference(PyObject *op) { - _Py_INC_REFTOTAL; - op->ob_refcnt = 1; - _Py_AddToAllObjects(op, 1); - _Py_INC_TPALLOCS(op); + _Py_INC_REFTOTAL; + op->ob_refcnt = 1; + _Py_AddToAllObjects(op, 1); + _Py_INC_TPALLOCS(op); } void _Py_ForgetReference(register PyObject *op) { #ifdef SLOW_UNREF_CHECK - register PyObject *p; + register PyObject *p; #endif - if (op->ob_refcnt < 0) - Py_FatalError("UNREF negative refcnt"); - if (op == &refchain || - op->_ob_prev->_ob_next != op || op->_ob_next->_ob_prev != op) { - fprintf(stderr, "* ob\n"); - _PyObject_Dump(op); - fprintf(stderr, "* op->_ob_prev->_ob_next\n"); - _PyObject_Dump(op->_ob_prev->_ob_next); - fprintf(stderr, "* op->_ob_next->_ob_prev\n"); - _PyObject_Dump(op->_ob_next->_ob_prev); - Py_FatalError("UNREF invalid object"); - } + if (op->ob_refcnt < 0) + Py_FatalError("UNREF negative refcnt"); + if (op == &refchain || + op->_ob_prev->_ob_next != op || op->_ob_next->_ob_prev != op) { + fprintf(stderr, "* ob\n"); + _PyObject_Dump(op); + fprintf(stderr, "* op->_ob_prev->_ob_next\n"); + _PyObject_Dump(op->_ob_prev->_ob_next); + fprintf(stderr, "* op->_ob_next->_ob_prev\n"); + _PyObject_Dump(op->_ob_next->_ob_prev); + Py_FatalError("UNREF invalid object"); + } #ifdef SLOW_UNREF_CHECK - for (p = refchain._ob_next; p != &refchain; p = p->_ob_next) { - if (p == op) - break; - } - if (p == &refchain) /* Not found */ - Py_FatalError("UNREF unknown object"); + for (p = refchain._ob_next; p != &refchain; p = p->_ob_next) { + if (p == op) + break; + } + if (p == &refchain) /* Not found */ + Py_FatalError("UNREF unknown object"); #endif - op->_ob_next->_ob_prev = op->_ob_prev; - op->_ob_prev->_ob_next = op->_ob_next; - op->_ob_next = op->_ob_prev = NULL; - _Py_INC_TPFREES(op); + op->_ob_next->_ob_prev = op->_ob_prev; + op->_ob_prev->_ob_next = op->_ob_next; + op->_ob_next = op->_ob_prev = NULL; + _Py_INC_TPFREES(op); } void _Py_Dealloc(PyObject *op) { - destructor dealloc = Py_TYPE(op)->tp_dealloc; - _Py_ForgetReference(op); - (*dealloc)(op); + destructor dealloc = Py_TYPE(op)->tp_dealloc; + _Py_ForgetReference(op); + (*dealloc)(op); } /* Print all live objects. Because PyObject_Print is called, the @@ -1675,14 +1675,14 @@ void _Py_PrintReferences(FILE *fp) { - PyObject *op; - fprintf(fp, "Remaining objects:\n"); - for (op = refchain._ob_next; op != &refchain; op = op->_ob_next) { - fprintf(fp, "%p [%" PY_FORMAT_SIZE_T "d] ", op, op->ob_refcnt); - if (PyObject_Print(op, fp, 0) != 0) - PyErr_Clear(); - putc('\n', fp); - } + PyObject *op; + fprintf(fp, "Remaining objects:\n"); + for (op = refchain._ob_next; op != &refchain; op = op->_ob_next) { + fprintf(fp, "%p [%" PY_FORMAT_SIZE_T "d] ", op, op->ob_refcnt); + if (PyObject_Print(op, fp, 0) != 0) + PyErr_Clear(); + putc('\n', fp); + } } /* Print the addresses of all live objects. Unlike _Py_PrintReferences, this @@ -1691,40 +1691,40 @@ void _Py_PrintReferenceAddresses(FILE *fp) { - PyObject *op; - fprintf(fp, "Remaining object addresses:\n"); - for (op = refchain._ob_next; op != &refchain; op = op->_ob_next) - fprintf(fp, "%p [%" PY_FORMAT_SIZE_T "d] %s\n", op, - op->ob_refcnt, Py_TYPE(op)->tp_name); + PyObject *op; + fprintf(fp, "Remaining object addresses:\n"); + for (op = refchain._ob_next; op != &refchain; op = op->_ob_next) + fprintf(fp, "%p [%" PY_FORMAT_SIZE_T "d] %s\n", op, + op->ob_refcnt, Py_TYPE(op)->tp_name); } PyObject * _Py_GetObjects(PyObject *self, PyObject *args) { - int i, n; - PyObject *t = NULL; - PyObject *res, *op; - - if (!PyArg_ParseTuple(args, "i|O", &n, &t)) - return NULL; - op = refchain._ob_next; - res = PyList_New(0); - if (res == NULL) - return NULL; - for (i = 0; (n == 0 || i < n) && op != &refchain; i++) { - while (op == self || op == args || op == res || op == t || - (t != NULL && Py_TYPE(op) != (PyTypeObject *) t)) { - op = op->_ob_next; - if (op == &refchain) - return res; - } - if (PyList_Append(res, op) < 0) { - Py_DECREF(res); - return NULL; - } - op = op->_ob_next; - } - return res; + int i, n; + PyObject *t = NULL; + PyObject *res, *op; + + if (!PyArg_ParseTuple(args, "i|O", &n, &t)) + return NULL; + op = refchain._ob_next; + res = PyList_New(0); + if (res == NULL) + return NULL; + for (i = 0; (n == 0 || i < n) && op != &refchain; i++) { + while (op == self || op == args || op == res || op == t || + (t != NULL && Py_TYPE(op) != (PyTypeObject *) t)) { + op = op->_ob_next; + if (op == &refchain) + return res; + } + if (PyList_Append(res, op) < 0) { + Py_DECREF(res); + return NULL; + } + op = op->_ob_next; + } + return res; } #endif @@ -1746,19 +1746,19 @@ void * PyMem_Malloc(size_t nbytes) { - return PyMem_MALLOC(nbytes); + return PyMem_MALLOC(nbytes); } void * PyMem_Realloc(void *p, size_t nbytes) { - return PyMem_REALLOC(p, nbytes); + return PyMem_REALLOC(p, nbytes); } void PyMem_Free(void *p) { - PyMem_FREE(p); + PyMem_FREE(p); } @@ -1779,52 +1779,52 @@ int Py_ReprEnter(PyObject *obj) { - PyObject *dict; - PyObject *list; - Py_ssize_t i; - - dict = PyThreadState_GetDict(); - if (dict == NULL) - return 0; - list = PyDict_GetItemString(dict, KEY); - if (list == NULL) { - list = PyList_New(0); - if (list == NULL) - return -1; - if (PyDict_SetItemString(dict, KEY, list) < 0) - return -1; - Py_DECREF(list); - } - i = PyList_GET_SIZE(list); - while (--i >= 0) { - if (PyList_GET_ITEM(list, i) == obj) - return 1; - } - PyList_Append(list, obj); - return 0; + PyObject *dict; + PyObject *list; + Py_ssize_t i; + + dict = PyThreadState_GetDict(); + if (dict == NULL) + return 0; + list = PyDict_GetItemString(dict, KEY); + if (list == NULL) { + list = PyList_New(0); + if (list == NULL) + return -1; + if (PyDict_SetItemString(dict, KEY, list) < 0) + return -1; + Py_DECREF(list); + } + i = PyList_GET_SIZE(list); + while (--i >= 0) { + if (PyList_GET_ITEM(list, i) == obj) + return 1; + } + PyList_Append(list, obj); + return 0; } void Py_ReprLeave(PyObject *obj) { - PyObject *dict; - PyObject *list; - Py_ssize_t i; - - dict = PyThreadState_GetDict(); - if (dict == NULL) - return; - list = PyDict_GetItemString(dict, KEY); - if (list == NULL || !PyList_Check(list)) - return; - i = PyList_GET_SIZE(list); - /* Count backwards because we always expect obj to be list[-1] */ - while (--i >= 0) { - if (PyList_GET_ITEM(list, i) == obj) { - PyList_SetSlice(list, i, i + 1, NULL); - break; - } - } + PyObject *dict; + PyObject *list; + Py_ssize_t i; + + dict = PyThreadState_GetDict(); + if (dict == NULL) + return; + list = PyDict_GetItemString(dict, KEY); + if (list == NULL || !PyList_Check(list)) + return; + i = PyList_GET_SIZE(list); + /* Count backwards because we always expect obj to be list[-1] */ + while (--i >= 0) { + if (PyList_GET_ITEM(list, i) == obj) { + PyList_SetSlice(list, i, i + 1, NULL); + break; + } + } } /* Trashcan support. */ @@ -1844,11 +1844,11 @@ void _PyTrash_deposit_object(PyObject *op) { - assert(PyObject_IS_GC(op)); - assert(_Py_AS_GC(op)->gc.gc_refs == _PyGC_REFS_UNTRACKED); - assert(op->ob_refcnt == 0); - _Py_AS_GC(op)->gc.gc_prev = (PyGC_Head *)_PyTrash_delete_later; - _PyTrash_delete_later = op; + assert(PyObject_IS_GC(op)); + assert(_Py_AS_GC(op)->gc.gc_refs == _PyGC_REFS_UNTRACKED); + assert(op->ob_refcnt == 0); + _Py_AS_GC(op)->gc.gc_prev = (PyGC_Head *)_PyTrash_delete_later; + _PyTrash_delete_later = op; } /* Dealloccate all the objects in the _PyTrash_delete_later list. Called when @@ -1857,24 +1857,24 @@ void _PyTrash_destroy_chain(void) { - while (_PyTrash_delete_later) { - PyObject *op = _PyTrash_delete_later; - destructor dealloc = Py_TYPE(op)->tp_dealloc; - - _PyTrash_delete_later = - (PyObject*) _Py_AS_GC(op)->gc.gc_prev; - - /* Call the deallocator directly. This used to try to - * fool Py_DECREF into calling it indirectly, but - * Py_DECREF was already called on this object, and in - * assorted non-release builds calling Py_DECREF again ends - * up distorting allocation statistics. - */ - assert(op->ob_refcnt == 0); - ++_PyTrash_delete_nesting; - (*dealloc)(op); - --_PyTrash_delete_nesting; - } + while (_PyTrash_delete_later) { + PyObject *op = _PyTrash_delete_later; + destructor dealloc = Py_TYPE(op)->tp_dealloc; + + _PyTrash_delete_later = + (PyObject*) _Py_AS_GC(op)->gc.gc_prev; + + /* Call the deallocator directly. This used to try to + * fool Py_DECREF into calling it indirectly, but + * Py_DECREF was already called on this object, and in + * assorted non-release builds calling Py_DECREF again ends + * up distorting allocation statistics. + */ + assert(op->ob_refcnt == 0); + ++_PyTrash_delete_nesting; + (*dealloc)(op); + --_PyTrash_delete_nesting; + } } #ifdef __cplusplus Modified: python/branches/release31-maint/Objects/obmalloc.c ============================================================================== --- python/branches/release31-maint/Objects/obmalloc.c (original) +++ python/branches/release31-maint/Objects/obmalloc.c Sun May 9 18:14:21 2010 @@ -12,7 +12,7 @@ the cyclic garbage collector operates selectively on container objects. - Object-specific allocators + Object-specific allocators _____ ______ ______ ________ [ int ] [ dict ] [ list ] ... [ string ] Python core | +3 | <----- Object-specific memory -----> | <-- Non-object memory --> | @@ -52,7 +52,7 @@ * in Proc. 1995 Int'l. Workshop on Memory Management, September 1995. */ -/* #undef WITH_MEMORY_LIMITS */ /* disable mem limit checks */ +/* #undef WITH_MEMORY_LIMITS */ /* disable mem limit checks */ /*==========================================================================*/ @@ -80,22 +80,22 @@ * * For small requests we have the following table: * - * Request in bytes Size of allocated block Size class idx + * Request in bytes Size of allocated block Size class idx * ---------------------------------------------------------------- * 1-8 8 0 - * 9-16 16 1 - * 17-24 24 2 - * 25-32 32 3 - * 33-40 40 4 - * 41-48 48 5 - * 49-56 56 6 - * 57-64 64 7 - * 65-72 72 8 - * ... ... ... - * 241-248 248 30 - * 249-256 256 31 + * 9-16 16 1 + * 17-24 24 2 + * 25-32 32 3 + * 33-40 40 4 + * 41-48 48 5 + * 49-56 56 6 + * 57-64 64 7 + * 65-72 72 8 + * ... ... ... + * 241-248 248 30 + * 249-256 256 31 * - * 0, 257 and up: routed to the underlying allocator. + * 0, 257 and up: routed to the underlying allocator. */ /*==========================================================================*/ @@ -112,9 +112,9 @@ * * You shouldn't change this unless you know what you are doing. */ -#define ALIGNMENT 8 /* must be 2^N */ -#define ALIGNMENT_SHIFT 3 -#define ALIGNMENT_MASK (ALIGNMENT - 1) +#define ALIGNMENT 8 /* must be 2^N */ +#define ALIGNMENT_SHIFT 3 +#define ALIGNMENT_MASK (ALIGNMENT - 1) /* Return the number of bytes in size class I, as a uint. */ #define INDEX2SIZE(I) (((uint)(I) + 1) << ALIGNMENT_SHIFT) @@ -125,14 +125,14 @@ * this value according to your application behaviour and memory needs. * * The following invariants must hold: - * 1) ALIGNMENT <= SMALL_REQUEST_THRESHOLD <= 256 - * 2) SMALL_REQUEST_THRESHOLD is evenly divisible by ALIGNMENT + * 1) ALIGNMENT <= SMALL_REQUEST_THRESHOLD <= 256 + * 2) SMALL_REQUEST_THRESHOLD is evenly divisible by ALIGNMENT * * Although not required, for better performance and space efficiency, * it is recommended that SMALL_REQUEST_THRESHOLD is set to a power of 2. */ -#define SMALL_REQUEST_THRESHOLD 256 -#define NB_SMALL_SIZE_CLASSES (SMALL_REQUEST_THRESHOLD / ALIGNMENT) +#define SMALL_REQUEST_THRESHOLD 256 +#define NB_SMALL_SIZE_CLASSES (SMALL_REQUEST_THRESHOLD / ALIGNMENT) /* * The system's VMM page size can be obtained on most unices with a @@ -144,15 +144,15 @@ * violation fault. 4K is apparently OK for all the platforms that python * currently targets. */ -#define SYSTEM_PAGE_SIZE (4 * 1024) -#define SYSTEM_PAGE_SIZE_MASK (SYSTEM_PAGE_SIZE - 1) +#define SYSTEM_PAGE_SIZE (4 * 1024) +#define SYSTEM_PAGE_SIZE_MASK (SYSTEM_PAGE_SIZE - 1) /* * Maximum amount of memory managed by the allocator for small requests. */ #ifdef WITH_MEMORY_LIMITS #ifndef SMALL_MEMORY_LIMIT -#define SMALL_MEMORY_LIMIT (64 * 1024 * 1024) /* 64 MB -- more? */ +#define SMALL_MEMORY_LIMIT (64 * 1024 * 1024) /* 64 MB -- more? */ #endif #endif @@ -169,18 +169,18 @@ * some address space wastage, but this is the most portable way to request * memory from the system across various platforms. */ -#define ARENA_SIZE (256 << 10) /* 256KB */ +#define ARENA_SIZE (256 << 10) /* 256KB */ #ifdef WITH_MEMORY_LIMITS -#define MAX_ARENAS (SMALL_MEMORY_LIMIT / ARENA_SIZE) +#define MAX_ARENAS (SMALL_MEMORY_LIMIT / ARENA_SIZE) #endif /* * Size of the pools used for small blocks. Should be a power of 2, * between 1K and SYSTEM_PAGE_SIZE, that is: 1k, 2k, 4k. */ -#define POOL_SIZE SYSTEM_PAGE_SIZE /* must be 2^N */ -#define POOL_SIZE_MASK SYSTEM_PAGE_SIZE_MASK +#define POOL_SIZE SYSTEM_PAGE_SIZE /* must be 2^N */ +#define POOL_SIZE_MASK SYSTEM_PAGE_SIZE_MASK /* * -- End of tunable settings section -- @@ -206,92 +206,92 @@ /* * Python's threads are serialized, so object malloc locking is disabled. */ -#define SIMPLELOCK_DECL(lock) /* simple lock declaration */ -#define SIMPLELOCK_INIT(lock) /* allocate (if needed) and initialize */ -#define SIMPLELOCK_FINI(lock) /* free/destroy an existing lock */ -#define SIMPLELOCK_LOCK(lock) /* acquire released lock */ -#define SIMPLELOCK_UNLOCK(lock) /* release acquired lock */ +#define SIMPLELOCK_DECL(lock) /* simple lock declaration */ +#define SIMPLELOCK_INIT(lock) /* allocate (if needed) and initialize */ +#define SIMPLELOCK_FINI(lock) /* free/destroy an existing lock */ +#define SIMPLELOCK_LOCK(lock) /* acquire released lock */ +#define SIMPLELOCK_UNLOCK(lock) /* release acquired lock */ /* * Basic types * I don't care if these are defined in or elsewhere. Axiom. */ #undef uchar -#define uchar unsigned char /* assuming == 8 bits */ +#define uchar unsigned char /* assuming == 8 bits */ #undef uint -#define uint unsigned int /* assuming >= 16 bits */ +#define uint unsigned int /* assuming >= 16 bits */ #undef ulong -#define ulong unsigned long /* assuming >= 32 bits */ +#define ulong unsigned long /* assuming >= 32 bits */ #undef uptr -#define uptr Py_uintptr_t +#define uptr Py_uintptr_t /* When you say memory, my mind reasons in terms of (pointers to) blocks */ typedef uchar block; /* Pool for small blocks. */ struct pool_header { - union { block *_padding; - uint count; } ref; /* number of allocated blocks */ - block *freeblock; /* pool's free list head */ - struct pool_header *nextpool; /* next pool of this size class */ - struct pool_header *prevpool; /* previous pool "" */ - uint arenaindex; /* index into arenas of base adr */ - uint szidx; /* block size class index */ - uint nextoffset; /* bytes to virgin block */ - uint maxnextoffset; /* largest valid nextoffset */ + union { block *_padding; + uint count; } ref; /* number of allocated blocks */ + block *freeblock; /* pool's free list head */ + struct pool_header *nextpool; /* next pool of this size class */ + struct pool_header *prevpool; /* previous pool "" */ + uint arenaindex; /* index into arenas of base adr */ + uint szidx; /* block size class index */ + uint nextoffset; /* bytes to virgin block */ + uint maxnextoffset; /* largest valid nextoffset */ }; typedef struct pool_header *poolp; /* Record keeping for arenas. */ struct arena_object { - /* The address of the arena, as returned by malloc. Note that 0 - * will never be returned by a successful malloc, and is used - * here to mark an arena_object that doesn't correspond to an - * allocated arena. - */ - uptr address; - - /* Pool-aligned pointer to the next pool to be carved off. */ - block* pool_address; - - /* The number of available pools in the arena: free pools + never- - * allocated pools. - */ - uint nfreepools; - - /* The total number of pools in the arena, whether or not available. */ - uint ntotalpools; - - /* Singly-linked list of available pools. */ - struct pool_header* freepools; - - /* Whenever this arena_object is not associated with an allocated - * arena, the nextarena member is used to link all unassociated - * arena_objects in the singly-linked `unused_arena_objects` list. - * The prevarena member is unused in this case. - * - * When this arena_object is associated with an allocated arena - * with at least one available pool, both members are used in the - * doubly-linked `usable_arenas` list, which is maintained in - * increasing order of `nfreepools` values. - * - * Else this arena_object is associated with an allocated arena - * all of whose pools are in use. `nextarena` and `prevarena` - * are both meaningless in this case. - */ - struct arena_object* nextarena; - struct arena_object* prevarena; + /* The address of the arena, as returned by malloc. Note that 0 + * will never be returned by a successful malloc, and is used + * here to mark an arena_object that doesn't correspond to an + * allocated arena. + */ + uptr address; + + /* Pool-aligned pointer to the next pool to be carved off. */ + block* pool_address; + + /* The number of available pools in the arena: free pools + never- + * allocated pools. + */ + uint nfreepools; + + /* The total number of pools in the arena, whether or not available. */ + uint ntotalpools; + + /* Singly-linked list of available pools. */ + struct pool_header* freepools; + + /* Whenever this arena_object is not associated with an allocated + * arena, the nextarena member is used to link all unassociated + * arena_objects in the singly-linked `unused_arena_objects` list. + * The prevarena member is unused in this case. + * + * When this arena_object is associated with an allocated arena + * with at least one available pool, both members are used in the + * doubly-linked `usable_arenas` list, which is maintained in + * increasing order of `nfreepools` values. + * + * Else this arena_object is associated with an allocated arena + * all of whose pools are in use. `nextarena` and `prevarena` + * are both meaningless in this case. + */ + struct arena_object* nextarena; + struct arena_object* prevarena; }; #undef ROUNDUP -#define ROUNDUP(x) (((x) + ALIGNMENT_MASK) & ~ALIGNMENT_MASK) -#define POOL_OVERHEAD ROUNDUP(sizeof(struct pool_header)) +#define ROUNDUP(x) (((x) + ALIGNMENT_MASK) & ~ALIGNMENT_MASK) +#define POOL_OVERHEAD ROUNDUP(sizeof(struct pool_header)) -#define DUMMY_SIZE_IDX 0xffff /* size class of newly cached pools */ +#define DUMMY_SIZE_IDX 0xffff /* size class of newly cached pools */ /* Round pointer P down to the closest pool-aligned address <= P, as a poolp */ #define POOL_ADDR(P) ((poolp)((uptr)(P) & ~(uptr)POOL_SIZE_MASK)) @@ -305,10 +305,10 @@ * This malloc lock */ SIMPLELOCK_DECL(_malloc_lock) -#define LOCK() SIMPLELOCK_LOCK(_malloc_lock) -#define UNLOCK() SIMPLELOCK_UNLOCK(_malloc_lock) -#define LOCK_INIT() SIMPLELOCK_INIT(_malloc_lock) -#define LOCK_FINI() SIMPLELOCK_FINI(_malloc_lock) +#define LOCK() SIMPLELOCK_LOCK(_malloc_lock) +#define UNLOCK() SIMPLELOCK_UNLOCK(_malloc_lock) +#define LOCK_INIT() SIMPLELOCK_INIT(_malloc_lock) +#define LOCK_FINI() SIMPLELOCK_FINI(_malloc_lock) /* * Pool table -- headed, circular, doubly-linked lists of partially used pools. @@ -388,9 +388,9 @@ compensating for that a pool_header's nextpool and prevpool members immediately follow a pool_header's first two members: - union { block *_padding; - uint count; } ref; - block *freeblock; + union { block *_padding; + uint count; } ref; + block *freeblock; each of which consume sizeof(block *) bytes. So what usedpools[i+i] really contains is a fudged-up pointer p such that *if* C believes it's a poolp @@ -406,25 +406,25 @@ the prevpool member. **************************************************************************** */ -#define PTA(x) ((poolp )((uchar *)&(usedpools[2*(x)]) - 2*sizeof(block *))) -#define PT(x) PTA(x), PTA(x) +#define PTA(x) ((poolp )((uchar *)&(usedpools[2*(x)]) - 2*sizeof(block *))) +#define PT(x) PTA(x), PTA(x) static poolp usedpools[2 * ((NB_SMALL_SIZE_CLASSES + 7) / 8) * 8] = { - PT(0), PT(1), PT(2), PT(3), PT(4), PT(5), PT(6), PT(7) + PT(0), PT(1), PT(2), PT(3), PT(4), PT(5), PT(6), PT(7) #if NB_SMALL_SIZE_CLASSES > 8 - , PT(8), PT(9), PT(10), PT(11), PT(12), PT(13), PT(14), PT(15) + , PT(8), PT(9), PT(10), PT(11), PT(12), PT(13), PT(14), PT(15) #if NB_SMALL_SIZE_CLASSES > 16 - , PT(16), PT(17), PT(18), PT(19), PT(20), PT(21), PT(22), PT(23) + , PT(16), PT(17), PT(18), PT(19), PT(20), PT(21), PT(22), PT(23) #if NB_SMALL_SIZE_CLASSES > 24 - , PT(24), PT(25), PT(26), PT(27), PT(28), PT(29), PT(30), PT(31) + , PT(24), PT(25), PT(26), PT(27), PT(28), PT(29), PT(30), PT(31) #if NB_SMALL_SIZE_CLASSES > 32 - , PT(32), PT(33), PT(34), PT(35), PT(36), PT(37), PT(38), PT(39) + , PT(32), PT(33), PT(34), PT(35), PT(36), PT(37), PT(38), PT(39) #if NB_SMALL_SIZE_CLASSES > 40 - , PT(40), PT(41), PT(42), PT(43), PT(44), PT(45), PT(46), PT(47) + , PT(40), PT(41), PT(42), PT(43), PT(44), PT(45), PT(46), PT(47) #if NB_SMALL_SIZE_CLASSES > 48 - , PT(48), PT(49), PT(50), PT(51), PT(52), PT(53), PT(54), PT(55) + , PT(48), PT(49), PT(50), PT(51), PT(52), PT(53), PT(54), PT(55) #if NB_SMALL_SIZE_CLASSES > 56 - , PT(56), PT(57), PT(58), PT(59), PT(60), PT(61), PT(62), PT(63) + , PT(56), PT(57), PT(58), PT(59), PT(60), PT(61), PT(62), PT(63) #endif /* NB_SMALL_SIZE_CLASSES > 56 */ #endif /* NB_SMALL_SIZE_CLASSES > 48 */ #endif /* NB_SMALL_SIZE_CLASSES > 40 */ @@ -508,90 +508,90 @@ static struct arena_object* new_arena(void) { - struct arena_object* arenaobj; - uint excess; /* number of bytes above pool alignment */ + struct arena_object* arenaobj; + uint excess; /* number of bytes above pool alignment */ #ifdef PYMALLOC_DEBUG - if (Py_GETENV("PYTHONMALLOCSTATS")) - _PyObject_DebugMallocStats(); + if (Py_GETENV("PYTHONMALLOCSTATS")) + _PyObject_DebugMallocStats(); #endif - if (unused_arena_objects == NULL) { - uint i; - uint numarenas; - size_t nbytes; - - /* Double the number of arena objects on each allocation. - * Note that it's possible for `numarenas` to overflow. - */ - numarenas = maxarenas ? maxarenas << 1 : INITIAL_ARENA_OBJECTS; - if (numarenas <= maxarenas) - return NULL; /* overflow */ + if (unused_arena_objects == NULL) { + uint i; + uint numarenas; + size_t nbytes; + + /* Double the number of arena objects on each allocation. + * Note that it's possible for `numarenas` to overflow. + */ + numarenas = maxarenas ? maxarenas << 1 : INITIAL_ARENA_OBJECTS; + if (numarenas <= maxarenas) + return NULL; /* overflow */ #if SIZEOF_SIZE_T <= SIZEOF_INT - if (numarenas > PY_SIZE_MAX / sizeof(*arenas)) - return NULL; /* overflow */ + if (numarenas > PY_SIZE_MAX / sizeof(*arenas)) + return NULL; /* overflow */ #endif - nbytes = numarenas * sizeof(*arenas); - arenaobj = (struct arena_object *)realloc(arenas, nbytes); - if (arenaobj == NULL) - return NULL; - arenas = arenaobj; - - /* We might need to fix pointers that were copied. However, - * new_arena only gets called when all the pages in the - * previous arenas are full. Thus, there are *no* pointers - * into the old array. Thus, we don't have to worry about - * invalid pointers. Just to be sure, some asserts: - */ - assert(usable_arenas == NULL); - assert(unused_arena_objects == NULL); - - /* Put the new arenas on the unused_arena_objects list. */ - for (i = maxarenas; i < numarenas; ++i) { - arenas[i].address = 0; /* mark as unassociated */ - arenas[i].nextarena = i < numarenas - 1 ? - &arenas[i+1] : NULL; - } - - /* Update globals. */ - unused_arena_objects = &arenas[maxarenas]; - maxarenas = numarenas; - } - - /* Take the next available arena object off the head of the list. */ - assert(unused_arena_objects != NULL); - arenaobj = unused_arena_objects; - unused_arena_objects = arenaobj->nextarena; - assert(arenaobj->address == 0); - arenaobj->address = (uptr)malloc(ARENA_SIZE); - if (arenaobj->address == 0) { - /* The allocation failed: return NULL after putting the - * arenaobj back. - */ - arenaobj->nextarena = unused_arena_objects; - unused_arena_objects = arenaobj; - return NULL; - } + nbytes = numarenas * sizeof(*arenas); + arenaobj = (struct arena_object *)realloc(arenas, nbytes); + if (arenaobj == NULL) + return NULL; + arenas = arenaobj; + + /* We might need to fix pointers that were copied. However, + * new_arena only gets called when all the pages in the + * previous arenas are full. Thus, there are *no* pointers + * into the old array. Thus, we don't have to worry about + * invalid pointers. Just to be sure, some asserts: + */ + assert(usable_arenas == NULL); + assert(unused_arena_objects == NULL); - ++narenas_currently_allocated; + /* Put the new arenas on the unused_arena_objects list. */ + for (i = maxarenas; i < numarenas; ++i) { + arenas[i].address = 0; /* mark as unassociated */ + arenas[i].nextarena = i < numarenas - 1 ? + &arenas[i+1] : NULL; + } + + /* Update globals. */ + unused_arena_objects = &arenas[maxarenas]; + maxarenas = numarenas; + } + + /* Take the next available arena object off the head of the list. */ + assert(unused_arena_objects != NULL); + arenaobj = unused_arena_objects; + unused_arena_objects = arenaobj->nextarena; + assert(arenaobj->address == 0); + arenaobj->address = (uptr)malloc(ARENA_SIZE); + if (arenaobj->address == 0) { + /* The allocation failed: return NULL after putting the + * arenaobj back. + */ + arenaobj->nextarena = unused_arena_objects; + unused_arena_objects = arenaobj; + return NULL; + } + + ++narenas_currently_allocated; #ifdef PYMALLOC_DEBUG - ++ntimes_arena_allocated; - if (narenas_currently_allocated > narenas_highwater) - narenas_highwater = narenas_currently_allocated; + ++ntimes_arena_allocated; + if (narenas_currently_allocated > narenas_highwater) + narenas_highwater = narenas_currently_allocated; #endif - arenaobj->freepools = NULL; - /* pool_address <- first pool-aligned address in the arena - nfreepools <- number of whole pools that fit after alignment */ - arenaobj->pool_address = (block*)arenaobj->address; - arenaobj->nfreepools = ARENA_SIZE / POOL_SIZE; - assert(POOL_SIZE * arenaobj->nfreepools == ARENA_SIZE); - excess = (uint)(arenaobj->address & POOL_SIZE_MASK); - if (excess != 0) { - --arenaobj->nfreepools; - arenaobj->pool_address += POOL_SIZE - excess; - } - arenaobj->ntotalpools = arenaobj->nfreepools; + arenaobj->freepools = NULL; + /* pool_address <- first pool-aligned address in the arena + nfreepools <- number of whole pools that fit after alignment */ + arenaobj->pool_address = (block*)arenaobj->address; + arenaobj->nfreepools = ARENA_SIZE / POOL_SIZE; + assert(POOL_SIZE * arenaobj->nfreepools == ARENA_SIZE); + excess = (uint)(arenaobj->address & POOL_SIZE_MASK); + if (excess != 0) { + --arenaobj->nfreepools; + arenaobj->pool_address += POOL_SIZE - excess; + } + arenaobj->ntotalpools = arenaobj->nfreepools; - return arenaobj; + return arenaobj; } /* @@ -607,11 +607,11 @@ Tricky: Let B be the arena base address associated with the pool, B = arenas[(POOL)->arenaindex].address. Then P belongs to the arena if and only if - B <= P < B + ARENA_SIZE + B <= P < B + ARENA_SIZE Subtracting B throughout, this is true iff - 0 <= P-B < ARENA_SIZE + 0 <= P-B < ARENA_SIZE By using unsigned arithmetic, the "0 <=" half of the test can be skipped. @@ -645,7 +645,7 @@ arena_object (one not currently associated with an allocated arena), AO.address is 0, and the second test in the macro reduces to: - P < ARENA_SIZE + P < ARENA_SIZE If P >= ARENA_SIZE (extremely likely), the macro again correctly concludes that P is not controlled by obmalloc. However, if P < ARENA_SIZE, this part @@ -668,10 +668,10 @@ obmalloc controls. Since this test is needed at every entry point, it's extremely desirable that it be this fast. */ -#define Py_ADDRESS_IN_RANGE(P, POOL) \ - ((POOL)->arenaindex < maxarenas && \ - (uptr)(P) - arenas[(POOL)->arenaindex].address < (uptr)ARENA_SIZE && \ - arenas[(POOL)->arenaindex].address != 0) +#define Py_ADDRESS_IN_RANGE(P, POOL) \ + ((POOL)->arenaindex < maxarenas && \ + (uptr)(P) - arenas[(POOL)->arenaindex].address < (uptr)ARENA_SIZE && \ + arenas[(POOL)->arenaindex].address != 0) /* This is only useful when running memory debuggers such as @@ -694,7 +694,7 @@ #undef Py_ADDRESS_IN_RANGE #if defined(__GNUC__) && ((__GNUC__ == 3) && (__GNUC_MINOR__ >= 1) || \ - (__GNUC__ >= 4)) + (__GNUC__ >= 4)) #define Py_NO_INLINE __attribute__((__noinline__)) #else #define Py_NO_INLINE @@ -723,194 +723,194 @@ void * PyObject_Malloc(size_t nbytes) { - block *bp; - poolp pool; - poolp next; - uint size; - - /* - * Limit ourselves to PY_SSIZE_T_MAX bytes to prevent security holes. - * Most python internals blindly use a signed Py_ssize_t to track - * things without checking for overflows or negatives. - * As size_t is unsigned, checking for nbytes < 0 is not required. - */ - if (nbytes > PY_SSIZE_T_MAX) - return NULL; - - /* - * This implicitly redirects malloc(0). - */ - if ((nbytes - 1) < SMALL_REQUEST_THRESHOLD) { - LOCK(); - /* - * Most frequent paths first - */ - size = (uint)(nbytes - 1) >> ALIGNMENT_SHIFT; - pool = usedpools[size + size]; - if (pool != pool->nextpool) { - /* - * There is a used pool for this size class. - * Pick up the head block of its free list. - */ - ++pool->ref.count; - bp = pool->freeblock; - assert(bp != NULL); - if ((pool->freeblock = *(block **)bp) != NULL) { - UNLOCK(); - return (void *)bp; - } - /* - * Reached the end of the free list, try to extend it. - */ - if (pool->nextoffset <= pool->maxnextoffset) { - /* There is room for another block. */ - pool->freeblock = (block*)pool + - pool->nextoffset; - pool->nextoffset += INDEX2SIZE(size); - *(block **)(pool->freeblock) = NULL; - UNLOCK(); - return (void *)bp; - } - /* Pool is full, unlink from used pools. */ - next = pool->nextpool; - pool = pool->prevpool; - next->prevpool = pool; - pool->nextpool = next; - UNLOCK(); - return (void *)bp; - } - - /* There isn't a pool of the right size class immediately - * available: use a free pool. - */ - if (usable_arenas == NULL) { - /* No arena has a free pool: allocate a new arena. */ + block *bp; + poolp pool; + poolp next; + uint size; + + /* + * Limit ourselves to PY_SSIZE_T_MAX bytes to prevent security holes. + * Most python internals blindly use a signed Py_ssize_t to track + * things without checking for overflows or negatives. + * As size_t is unsigned, checking for nbytes < 0 is not required. + */ + if (nbytes > PY_SSIZE_T_MAX) + return NULL; + + /* + * This implicitly redirects malloc(0). + */ + if ((nbytes - 1) < SMALL_REQUEST_THRESHOLD) { + LOCK(); + /* + * Most frequent paths first + */ + size = (uint)(nbytes - 1) >> ALIGNMENT_SHIFT; + pool = usedpools[size + size]; + if (pool != pool->nextpool) { + /* + * There is a used pool for this size class. + * Pick up the head block of its free list. + */ + ++pool->ref.count; + bp = pool->freeblock; + assert(bp != NULL); + if ((pool->freeblock = *(block **)bp) != NULL) { + UNLOCK(); + return (void *)bp; + } + /* + * Reached the end of the free list, try to extend it. + */ + if (pool->nextoffset <= pool->maxnextoffset) { + /* There is room for another block. */ + pool->freeblock = (block*)pool + + pool->nextoffset; + pool->nextoffset += INDEX2SIZE(size); + *(block **)(pool->freeblock) = NULL; + UNLOCK(); + return (void *)bp; + } + /* Pool is full, unlink from used pools. */ + next = pool->nextpool; + pool = pool->prevpool; + next->prevpool = pool; + pool->nextpool = next; + UNLOCK(); + return (void *)bp; + } + + /* There isn't a pool of the right size class immediately + * available: use a free pool. + */ + if (usable_arenas == NULL) { + /* No arena has a free pool: allocate a new arena. */ #ifdef WITH_MEMORY_LIMITS - if (narenas_currently_allocated >= MAX_ARENAS) { - UNLOCK(); - goto redirect; - } + if (narenas_currently_allocated >= MAX_ARENAS) { + UNLOCK(); + goto redirect; + } #endif - usable_arenas = new_arena(); - if (usable_arenas == NULL) { - UNLOCK(); - goto redirect; - } - usable_arenas->nextarena = - usable_arenas->prevarena = NULL; - } - assert(usable_arenas->address != 0); - - /* Try to get a cached free pool. */ - pool = usable_arenas->freepools; - if (pool != NULL) { - /* Unlink from cached pools. */ - usable_arenas->freepools = pool->nextpool; - - /* This arena already had the smallest nfreepools - * value, so decreasing nfreepools doesn't change - * that, and we don't need to rearrange the - * usable_arenas list. However, if the arena has - * become wholly allocated, we need to remove its - * arena_object from usable_arenas. - */ - --usable_arenas->nfreepools; - if (usable_arenas->nfreepools == 0) { - /* Wholly allocated: remove. */ - assert(usable_arenas->freepools == NULL); - assert(usable_arenas->nextarena == NULL || - usable_arenas->nextarena->prevarena == - usable_arenas); - - usable_arenas = usable_arenas->nextarena; - if (usable_arenas != NULL) { - usable_arenas->prevarena = NULL; - assert(usable_arenas->address != 0); - } - } - else { - /* nfreepools > 0: it must be that freepools - * isn't NULL, or that we haven't yet carved - * off all the arena's pools for the first - * time. - */ - assert(usable_arenas->freepools != NULL || - usable_arenas->pool_address <= - (block*)usable_arenas->address + - ARENA_SIZE - POOL_SIZE); - } - init_pool: - /* Frontlink to used pools. */ - next = usedpools[size + size]; /* == prev */ - pool->nextpool = next; - pool->prevpool = next; - next->nextpool = pool; - next->prevpool = pool; - pool->ref.count = 1; - if (pool->szidx == size) { - /* Luckily, this pool last contained blocks - * of the same size class, so its header - * and free list are already initialized. - */ - bp = pool->freeblock; - pool->freeblock = *(block **)bp; - UNLOCK(); - return (void *)bp; - } - /* - * Initialize the pool header, set up the free list to - * contain just the second block, and return the first - * block. - */ - pool->szidx = size; - size = INDEX2SIZE(size); - bp = (block *)pool + POOL_OVERHEAD; - pool->nextoffset = POOL_OVERHEAD + (size << 1); - pool->maxnextoffset = POOL_SIZE - size; - pool->freeblock = bp + size; - *(block **)(pool->freeblock) = NULL; - UNLOCK(); - return (void *)bp; - } - - /* Carve off a new pool. */ - assert(usable_arenas->nfreepools > 0); - assert(usable_arenas->freepools == NULL); - pool = (poolp)usable_arenas->pool_address; - assert((block*)pool <= (block*)usable_arenas->address + - ARENA_SIZE - POOL_SIZE); - pool->arenaindex = usable_arenas - arenas; - assert(&arenas[pool->arenaindex] == usable_arenas); - pool->szidx = DUMMY_SIZE_IDX; - usable_arenas->pool_address += POOL_SIZE; - --usable_arenas->nfreepools; - - if (usable_arenas->nfreepools == 0) { - assert(usable_arenas->nextarena == NULL || - usable_arenas->nextarena->prevarena == - usable_arenas); - /* Unlink the arena: it is completely allocated. */ - usable_arenas = usable_arenas->nextarena; - if (usable_arenas != NULL) { - usable_arenas->prevarena = NULL; - assert(usable_arenas->address != 0); - } - } + usable_arenas = new_arena(); + if (usable_arenas == NULL) { + UNLOCK(); + goto redirect; + } + usable_arenas->nextarena = + usable_arenas->prevarena = NULL; + } + assert(usable_arenas->address != 0); + + /* Try to get a cached free pool. */ + pool = usable_arenas->freepools; + if (pool != NULL) { + /* Unlink from cached pools. */ + usable_arenas->freepools = pool->nextpool; + + /* This arena already had the smallest nfreepools + * value, so decreasing nfreepools doesn't change + * that, and we don't need to rearrange the + * usable_arenas list. However, if the arena has + * become wholly allocated, we need to remove its + * arena_object from usable_arenas. + */ + --usable_arenas->nfreepools; + if (usable_arenas->nfreepools == 0) { + /* Wholly allocated: remove. */ + assert(usable_arenas->freepools == NULL); + assert(usable_arenas->nextarena == NULL || + usable_arenas->nextarena->prevarena == + usable_arenas); + + usable_arenas = usable_arenas->nextarena; + if (usable_arenas != NULL) { + usable_arenas->prevarena = NULL; + assert(usable_arenas->address != 0); + } + } + else { + /* nfreepools > 0: it must be that freepools + * isn't NULL, or that we haven't yet carved + * off all the arena's pools for the first + * time. + */ + assert(usable_arenas->freepools != NULL || + usable_arenas->pool_address <= + (block*)usable_arenas->address + + ARENA_SIZE - POOL_SIZE); + } + init_pool: + /* Frontlink to used pools. */ + next = usedpools[size + size]; /* == prev */ + pool->nextpool = next; + pool->prevpool = next; + next->nextpool = pool; + next->prevpool = pool; + pool->ref.count = 1; + if (pool->szidx == size) { + /* Luckily, this pool last contained blocks + * of the same size class, so its header + * and free list are already initialized. + */ + bp = pool->freeblock; + pool->freeblock = *(block **)bp; + UNLOCK(); + return (void *)bp; + } + /* + * Initialize the pool header, set up the free list to + * contain just the second block, and return the first + * block. + */ + pool->szidx = size; + size = INDEX2SIZE(size); + bp = (block *)pool + POOL_OVERHEAD; + pool->nextoffset = POOL_OVERHEAD + (size << 1); + pool->maxnextoffset = POOL_SIZE - size; + pool->freeblock = bp + size; + *(block **)(pool->freeblock) = NULL; + UNLOCK(); + return (void *)bp; + } + + /* Carve off a new pool. */ + assert(usable_arenas->nfreepools > 0); + assert(usable_arenas->freepools == NULL); + pool = (poolp)usable_arenas->pool_address; + assert((block*)pool <= (block*)usable_arenas->address + + ARENA_SIZE - POOL_SIZE); + pool->arenaindex = usable_arenas - arenas; + assert(&arenas[pool->arenaindex] == usable_arenas); + pool->szidx = DUMMY_SIZE_IDX; + usable_arenas->pool_address += POOL_SIZE; + --usable_arenas->nfreepools; + + if (usable_arenas->nfreepools == 0) { + assert(usable_arenas->nextarena == NULL || + usable_arenas->nextarena->prevarena == + usable_arenas); + /* Unlink the arena: it is completely allocated. */ + usable_arenas = usable_arenas->nextarena; + if (usable_arenas != NULL) { + usable_arenas->prevarena = NULL; + assert(usable_arenas->address != 0); + } + } - goto init_pool; - } + goto init_pool; + } - /* The small block allocator ends here. */ + /* The small block allocator ends here. */ redirect: - /* Redirect the original request to the underlying (libc) allocator. - * We jump here on bigger requests, on error in the code above (as a - * last chance to serve the request) or when the max memory limit - * has been reached. - */ - if (nbytes == 0) - nbytes = 1; - return (void *)malloc(nbytes); + /* Redirect the original request to the underlying (libc) allocator. + * We jump here on bigger requests, on error in the code above (as a + * last chance to serve the request) or when the max memory limit + * has been reached. + */ + if (nbytes == 0) + nbytes = 1; + return (void *)malloc(nbytes); } /* free */ @@ -919,210 +919,210 @@ void PyObject_Free(void *p) { - poolp pool; - block *lastfree; - poolp next, prev; - uint size; - - if (p == NULL) /* free(NULL) has no effect */ - return; - - pool = POOL_ADDR(p); - if (Py_ADDRESS_IN_RANGE(p, pool)) { - /* We allocated this address. */ - LOCK(); - /* Link p to the start of the pool's freeblock list. Since - * the pool had at least the p block outstanding, the pool - * wasn't empty (so it's already in a usedpools[] list, or - * was full and is in no list -- it's not in the freeblocks - * list in any case). - */ - assert(pool->ref.count > 0); /* else it was empty */ - *(block **)p = lastfree = pool->freeblock; - pool->freeblock = (block *)p; - if (lastfree) { - struct arena_object* ao; - uint nf; /* ao->nfreepools */ - - /* freeblock wasn't NULL, so the pool wasn't full, - * and the pool is in a usedpools[] list. - */ - if (--pool->ref.count != 0) { - /* pool isn't empty: leave it in usedpools */ - UNLOCK(); - return; - } - /* Pool is now empty: unlink from usedpools, and - * link to the front of freepools. This ensures that - * previously freed pools will be allocated later - * (being not referenced, they are perhaps paged out). - */ - next = pool->nextpool; - prev = pool->prevpool; - next->prevpool = prev; - prev->nextpool = next; - - /* Link the pool to freepools. This is a singly-linked - * list, and pool->prevpool isn't used there. - */ - ao = &arenas[pool->arenaindex]; - pool->nextpool = ao->freepools; - ao->freepools = pool; - nf = ++ao->nfreepools; - - /* All the rest is arena management. We just freed - * a pool, and there are 4 cases for arena mgmt: - * 1. If all the pools are free, return the arena to - * the system free(). - * 2. If this is the only free pool in the arena, - * add the arena back to the `usable_arenas` list. - * 3. If the "next" arena has a smaller count of free - * pools, we have to "slide this arena right" to - * restore that usable_arenas is sorted in order of - * nfreepools. - * 4. Else there's nothing more to do. - */ - if (nf == ao->ntotalpools) { - /* Case 1. First unlink ao from usable_arenas. - */ - assert(ao->prevarena == NULL || - ao->prevarena->address != 0); - assert(ao ->nextarena == NULL || - ao->nextarena->address != 0); - - /* Fix the pointer in the prevarena, or the - * usable_arenas pointer. - */ - if (ao->prevarena == NULL) { - usable_arenas = ao->nextarena; - assert(usable_arenas == NULL || - usable_arenas->address != 0); - } - else { - assert(ao->prevarena->nextarena == ao); - ao->prevarena->nextarena = - ao->nextarena; - } - /* Fix the pointer in the nextarena. */ - if (ao->nextarena != NULL) { - assert(ao->nextarena->prevarena == ao); - ao->nextarena->prevarena = - ao->prevarena; - } - /* Record that this arena_object slot is - * available to be reused. - */ - ao->nextarena = unused_arena_objects; - unused_arena_objects = ao; - - /* Free the entire arena. */ - free((void *)ao->address); - ao->address = 0; /* mark unassociated */ - --narenas_currently_allocated; - - UNLOCK(); - return; - } - if (nf == 1) { - /* Case 2. Put ao at the head of - * usable_arenas. Note that because - * ao->nfreepools was 0 before, ao isn't - * currently on the usable_arenas list. - */ - ao->nextarena = usable_arenas; - ao->prevarena = NULL; - if (usable_arenas) - usable_arenas->prevarena = ao; - usable_arenas = ao; - assert(usable_arenas->address != 0); - - UNLOCK(); - return; - } - /* If this arena is now out of order, we need to keep - * the list sorted. The list is kept sorted so that - * the "most full" arenas are used first, which allows - * the nearly empty arenas to be completely freed. In - * a few un-scientific tests, it seems like this - * approach allowed a lot more memory to be freed. - */ - if (ao->nextarena == NULL || - nf <= ao->nextarena->nfreepools) { - /* Case 4. Nothing to do. */ - UNLOCK(); - return; - } - /* Case 3: We have to move the arena towards the end - * of the list, because it has more free pools than - * the arena to its right. - * First unlink ao from usable_arenas. - */ - if (ao->prevarena != NULL) { - /* ao isn't at the head of the list */ - assert(ao->prevarena->nextarena == ao); - ao->prevarena->nextarena = ao->nextarena; - } - else { - /* ao is at the head of the list */ - assert(usable_arenas == ao); - usable_arenas = ao->nextarena; - } - ao->nextarena->prevarena = ao->prevarena; - - /* Locate the new insertion point by iterating over - * the list, using our nextarena pointer. - */ - while (ao->nextarena != NULL && - nf > ao->nextarena->nfreepools) { - ao->prevarena = ao->nextarena; - ao->nextarena = ao->nextarena->nextarena; - } - - /* Insert ao at this point. */ - assert(ao->nextarena == NULL || - ao->prevarena == ao->nextarena->prevarena); - assert(ao->prevarena->nextarena == ao->nextarena); - - ao->prevarena->nextarena = ao; - if (ao->nextarena != NULL) - ao->nextarena->prevarena = ao; - - /* Verify that the swaps worked. */ - assert(ao->nextarena == NULL || - nf <= ao->nextarena->nfreepools); - assert(ao->prevarena == NULL || - nf > ao->prevarena->nfreepools); - assert(ao->nextarena == NULL || - ao->nextarena->prevarena == ao); - assert((usable_arenas == ao && - ao->prevarena == NULL) || - ao->prevarena->nextarena == ao); - - UNLOCK(); - return; - } - /* Pool was full, so doesn't currently live in any list: - * link it to the front of the appropriate usedpools[] list. - * This mimics LRU pool usage for new allocations and - * targets optimal filling when several pools contain - * blocks of the same size class. - */ - --pool->ref.count; - assert(pool->ref.count > 0); /* else the pool is empty */ - size = pool->szidx; - next = usedpools[size + size]; - prev = next->prevpool; - /* insert pool before next: prev <-> pool <-> next */ - pool->nextpool = next; - pool->prevpool = prev; - next->prevpool = pool; - prev->nextpool = pool; - UNLOCK(); - return; - } + poolp pool; + block *lastfree; + poolp next, prev; + uint size; + + if (p == NULL) /* free(NULL) has no effect */ + return; + + pool = POOL_ADDR(p); + if (Py_ADDRESS_IN_RANGE(p, pool)) { + /* We allocated this address. */ + LOCK(); + /* Link p to the start of the pool's freeblock list. Since + * the pool had at least the p block outstanding, the pool + * wasn't empty (so it's already in a usedpools[] list, or + * was full and is in no list -- it's not in the freeblocks + * list in any case). + */ + assert(pool->ref.count > 0); /* else it was empty */ + *(block **)p = lastfree = pool->freeblock; + pool->freeblock = (block *)p; + if (lastfree) { + struct arena_object* ao; + uint nf; /* ao->nfreepools */ + + /* freeblock wasn't NULL, so the pool wasn't full, + * and the pool is in a usedpools[] list. + */ + if (--pool->ref.count != 0) { + /* pool isn't empty: leave it in usedpools */ + UNLOCK(); + return; + } + /* Pool is now empty: unlink from usedpools, and + * link to the front of freepools. This ensures that + * previously freed pools will be allocated later + * (being not referenced, they are perhaps paged out). + */ + next = pool->nextpool; + prev = pool->prevpool; + next->prevpool = prev; + prev->nextpool = next; + + /* Link the pool to freepools. This is a singly-linked + * list, and pool->prevpool isn't used there. + */ + ao = &arenas[pool->arenaindex]; + pool->nextpool = ao->freepools; + ao->freepools = pool; + nf = ++ao->nfreepools; + + /* All the rest is arena management. We just freed + * a pool, and there are 4 cases for arena mgmt: + * 1. If all the pools are free, return the arena to + * the system free(). + * 2. If this is the only free pool in the arena, + * add the arena back to the `usable_arenas` list. + * 3. If the "next" arena has a smaller count of free + * pools, we have to "slide this arena right" to + * restore that usable_arenas is sorted in order of + * nfreepools. + * 4. Else there's nothing more to do. + */ + if (nf == ao->ntotalpools) { + /* Case 1. First unlink ao from usable_arenas. + */ + assert(ao->prevarena == NULL || + ao->prevarena->address != 0); + assert(ao ->nextarena == NULL || + ao->nextarena->address != 0); + + /* Fix the pointer in the prevarena, or the + * usable_arenas pointer. + */ + if (ao->prevarena == NULL) { + usable_arenas = ao->nextarena; + assert(usable_arenas == NULL || + usable_arenas->address != 0); + } + else { + assert(ao->prevarena->nextarena == ao); + ao->prevarena->nextarena = + ao->nextarena; + } + /* Fix the pointer in the nextarena. */ + if (ao->nextarena != NULL) { + assert(ao->nextarena->prevarena == ao); + ao->nextarena->prevarena = + ao->prevarena; + } + /* Record that this arena_object slot is + * available to be reused. + */ + ao->nextarena = unused_arena_objects; + unused_arena_objects = ao; + + /* Free the entire arena. */ + free((void *)ao->address); + ao->address = 0; /* mark unassociated */ + --narenas_currently_allocated; + + UNLOCK(); + return; + } + if (nf == 1) { + /* Case 2. Put ao at the head of + * usable_arenas. Note that because + * ao->nfreepools was 0 before, ao isn't + * currently on the usable_arenas list. + */ + ao->nextarena = usable_arenas; + ao->prevarena = NULL; + if (usable_arenas) + usable_arenas->prevarena = ao; + usable_arenas = ao; + assert(usable_arenas->address != 0); + + UNLOCK(); + return; + } + /* If this arena is now out of order, we need to keep + * the list sorted. The list is kept sorted so that + * the "most full" arenas are used first, which allows + * the nearly empty arenas to be completely freed. In + * a few un-scientific tests, it seems like this + * approach allowed a lot more memory to be freed. + */ + if (ao->nextarena == NULL || + nf <= ao->nextarena->nfreepools) { + /* Case 4. Nothing to do. */ + UNLOCK(); + return; + } + /* Case 3: We have to move the arena towards the end + * of the list, because it has more free pools than + * the arena to its right. + * First unlink ao from usable_arenas. + */ + if (ao->prevarena != NULL) { + /* ao isn't at the head of the list */ + assert(ao->prevarena->nextarena == ao); + ao->prevarena->nextarena = ao->nextarena; + } + else { + /* ao is at the head of the list */ + assert(usable_arenas == ao); + usable_arenas = ao->nextarena; + } + ao->nextarena->prevarena = ao->prevarena; + + /* Locate the new insertion point by iterating over + * the list, using our nextarena pointer. + */ + while (ao->nextarena != NULL && + nf > ao->nextarena->nfreepools) { + ao->prevarena = ao->nextarena; + ao->nextarena = ao->nextarena->nextarena; + } + + /* Insert ao at this point. */ + assert(ao->nextarena == NULL || + ao->prevarena == ao->nextarena->prevarena); + assert(ao->prevarena->nextarena == ao->nextarena); + + ao->prevarena->nextarena = ao; + if (ao->nextarena != NULL) + ao->nextarena->prevarena = ao; + + /* Verify that the swaps worked. */ + assert(ao->nextarena == NULL || + nf <= ao->nextarena->nfreepools); + assert(ao->prevarena == NULL || + nf > ao->prevarena->nfreepools); + assert(ao->nextarena == NULL || + ao->nextarena->prevarena == ao); + assert((usable_arenas == ao && + ao->prevarena == NULL) || + ao->prevarena->nextarena == ao); + + UNLOCK(); + return; + } + /* Pool was full, so doesn't currently live in any list: + * link it to the front of the appropriate usedpools[] list. + * This mimics LRU pool usage for new allocations and + * targets optimal filling when several pools contain + * blocks of the same size class. + */ + --pool->ref.count; + assert(pool->ref.count > 0); /* else the pool is empty */ + size = pool->szidx; + next = usedpools[size + size]; + prev = next->prevpool; + /* insert pool before next: prev <-> pool <-> next */ + pool->nextpool = next; + pool->prevpool = prev; + next->prevpool = pool; + prev->nextpool = pool; + UNLOCK(); + return; + } - /* We didn't allocate this address. */ - free(p); + /* We didn't allocate this address. */ + free(p); } /* realloc. If p is NULL, this acts like malloc(nbytes). Else if nbytes==0, @@ -1134,72 +1134,72 @@ void * PyObject_Realloc(void *p, size_t nbytes) { - void *bp; - poolp pool; - size_t size; - - if (p == NULL) - return PyObject_Malloc(nbytes); - - /* - * Limit ourselves to PY_SSIZE_T_MAX bytes to prevent security holes. - * Most python internals blindly use a signed Py_ssize_t to track - * things without checking for overflows or negatives. - * As size_t is unsigned, checking for nbytes < 0 is not required. - */ - if (nbytes > PY_SSIZE_T_MAX) - return NULL; - - pool = POOL_ADDR(p); - if (Py_ADDRESS_IN_RANGE(p, pool)) { - /* We're in charge of this block */ - size = INDEX2SIZE(pool->szidx); - if (nbytes <= size) { - /* The block is staying the same or shrinking. If - * it's shrinking, there's a tradeoff: it costs - * cycles to copy the block to a smaller size class, - * but it wastes memory not to copy it. The - * compromise here is to copy on shrink only if at - * least 25% of size can be shaved off. - */ - if (4 * nbytes > 3 * size) { - /* It's the same, - * or shrinking and new/old > 3/4. - */ - return p; - } - size = nbytes; - } - bp = PyObject_Malloc(nbytes); - if (bp != NULL) { - memcpy(bp, p, size); - PyObject_Free(p); - } - return bp; - } - /* We're not managing this block. If nbytes <= - * SMALL_REQUEST_THRESHOLD, it's tempting to try to take over this - * block. However, if we do, we need to copy the valid data from - * the C-managed block to one of our blocks, and there's no portable - * way to know how much of the memory space starting at p is valid. - * As bug 1185883 pointed out the hard way, it's possible that the - * C-managed block is "at the end" of allocated VM space, so that - * a memory fault can occur if we try to copy nbytes bytes starting - * at p. Instead we punt: let C continue to manage this block. - */ - if (nbytes) - return realloc(p, nbytes); - /* C doesn't define the result of realloc(p, 0) (it may or may not - * return NULL then), but Python's docs promise that nbytes==0 never - * returns NULL. We don't pass 0 to realloc(), to avoid that endcase - * to begin with. Even then, we can't be sure that realloc() won't - * return NULL. - */ - bp = realloc(p, 1); - return bp ? bp : p; + void *bp; + poolp pool; + size_t size; + + if (p == NULL) + return PyObject_Malloc(nbytes); + + /* + * Limit ourselves to PY_SSIZE_T_MAX bytes to prevent security holes. + * Most python internals blindly use a signed Py_ssize_t to track + * things without checking for overflows or negatives. + * As size_t is unsigned, checking for nbytes < 0 is not required. + */ + if (nbytes > PY_SSIZE_T_MAX) + return NULL; + + pool = POOL_ADDR(p); + if (Py_ADDRESS_IN_RANGE(p, pool)) { + /* We're in charge of this block */ + size = INDEX2SIZE(pool->szidx); + if (nbytes <= size) { + /* The block is staying the same or shrinking. If + * it's shrinking, there's a tradeoff: it costs + * cycles to copy the block to a smaller size class, + * but it wastes memory not to copy it. The + * compromise here is to copy on shrink only if at + * least 25% of size can be shaved off. + */ + if (4 * nbytes > 3 * size) { + /* It's the same, + * or shrinking and new/old > 3/4. + */ + return p; + } + size = nbytes; + } + bp = PyObject_Malloc(nbytes); + if (bp != NULL) { + memcpy(bp, p, size); + PyObject_Free(p); + } + return bp; + } + /* We're not managing this block. If nbytes <= + * SMALL_REQUEST_THRESHOLD, it's tempting to try to take over this + * block. However, if we do, we need to copy the valid data from + * the C-managed block to one of our blocks, and there's no portable + * way to know how much of the memory space starting at p is valid. + * As bug 1185883 pointed out the hard way, it's possible that the + * C-managed block is "at the end" of allocated VM space, so that + * a memory fault can occur if we try to copy nbytes bytes starting + * at p. Instead we punt: let C continue to manage this block. + */ + if (nbytes) + return realloc(p, nbytes); + /* C doesn't define the result of realloc(p, 0) (it may or may not + * return NULL then), but Python's docs promise that nbytes==0 never + * returns NULL. We don't pass 0 to realloc(), to avoid that endcase + * to begin with. Even then, we can't be sure that realloc() won't + * return NULL. + */ + bp = realloc(p, 1); + return bp ? bp : p; } -#else /* ! WITH_PYMALLOC */ +#else /* ! WITH_PYMALLOC */ /*==========================================================================*/ /* pymalloc not enabled: Redirect the entry points to malloc. These will @@ -1208,19 +1208,19 @@ void * PyObject_Malloc(size_t n) { - return PyMem_MALLOC(n); + return PyMem_MALLOC(n); } void * PyObject_Realloc(void *p, size_t n) { - return PyMem_REALLOC(p, n); + return PyMem_REALLOC(p, n); } void PyObject_Free(void *p) { - PyMem_FREE(p); + PyMem_FREE(p); } #endif /* WITH_PYMALLOC */ @@ -1241,7 +1241,7 @@ #define DEADBYTE 0xDB /* dead (newly freed) memory */ #define FORBIDDENBYTE 0xFB /* untouchable bytes at each end of a block */ -static size_t serialno = 0; /* incremented on each debug {m,re}alloc */ +static size_t serialno = 0; /* incremented on each debug {m,re}alloc */ /* serialno is always incremented via calling this routine. The point is * to supply a single place to set a breakpoint. @@ -1249,7 +1249,7 @@ static void bumpserialno(void) { - ++serialno; + ++serialno; } #define SST SIZEOF_SIZE_T @@ -1258,13 +1258,13 @@ static size_t read_size_t(const void *p) { - const uchar *q = (const uchar *)p; - size_t result = *q++; - int i; - - for (i = SST; --i > 0; ++q) - result = (result << 8) | *q; - return result; + const uchar *q = (const uchar *)p; + size_t result = *q++; + int i; + + for (i = SST; --i > 0; ++q) + result = (result << 8) | *q; + return result; } /* Write n as a big-endian size_t, MSB at address p, LSB at @@ -1273,13 +1273,13 @@ static void write_size_t(void *p, size_t n) { - uchar *q = (uchar *)p + SST - 1; - int i; + uchar *q = (uchar *)p + SST - 1; + int i; - for (i = SST; --i >= 0; --q) { - *q = (uchar)(n & 0xff); - n >>= 8; - } + for (i = SST; --i >= 0; --q) { + *q = (uchar)(n & 0xff); + n >>= 8; + } } #ifdef Py_DEBUG @@ -1290,22 +1290,22 @@ static int pool_is_in_list(const poolp target, poolp list) { - poolp origlist = list; - assert(target != NULL); - if (list == NULL) - return 0; - do { - if (target == list) - return 1; - list = list->nextpool; - } while (list != NULL && list != origlist); - return 0; + poolp origlist = list; + assert(target != NULL); + if (list == NULL) + return 0; + do { + if (target == list) + return 1; + list = list->nextpool; + } while (list != NULL && list != origlist); + return 0; } #else #define pool_is_in_list(X, Y) 1 -#endif /* Py_DEBUG */ +#endif /* Py_DEBUG */ /* Let S = sizeof(size_t). The debug malloc asks for 4*S extra bytes and fills them with useful stuff, here calling the underlying malloc's result p: @@ -1334,31 +1334,31 @@ void * _PyObject_DebugMalloc(size_t nbytes) { - uchar *p; /* base address of malloc'ed block */ - uchar *tail; /* p + 2*SST + nbytes == pointer to tail pad bytes */ - size_t total; /* nbytes + 4*SST */ - - bumpserialno(); - total = nbytes + 4*SST; - if (total < nbytes) - /* overflow: can't represent total as a size_t */ - return NULL; - - p = (uchar *)PyObject_Malloc(total); - if (p == NULL) - return NULL; - - write_size_t(p, nbytes); - memset(p + SST, FORBIDDENBYTE, SST); - - if (nbytes > 0) - memset(p + 2*SST, CLEANBYTE, nbytes); - - tail = p + 2*SST + nbytes; - memset(tail, FORBIDDENBYTE, SST); - write_size_t(tail + SST, serialno); + uchar *p; /* base address of malloc'ed block */ + uchar *tail; /* p + 2*SST + nbytes == pointer to tail pad bytes */ + size_t total; /* nbytes + 4*SST */ + + bumpserialno(); + total = nbytes + 4*SST; + if (total < nbytes) + /* overflow: can't represent total as a size_t */ + return NULL; + + p = (uchar *)PyObject_Malloc(total); + if (p == NULL) + return NULL; + + write_size_t(p, nbytes); + memset(p + SST, FORBIDDENBYTE, SST); + + if (nbytes > 0) + memset(p + 2*SST, CLEANBYTE, nbytes); + + tail = p + 2*SST + nbytes; + memset(tail, FORBIDDENBYTE, SST); + write_size_t(tail + SST, serialno); - return p + 2*SST; + return p + 2*SST; } /* The debug free first checks the 2*SST bytes on each end for sanity (in @@ -1369,63 +1369,63 @@ void _PyObject_DebugFree(void *p) { - uchar *q = (uchar *)p - 2*SST; /* address returned from malloc */ - size_t nbytes; + uchar *q = (uchar *)p - 2*SST; /* address returned from malloc */ + size_t nbytes; - if (p == NULL) - return; - _PyObject_DebugCheckAddress(p); - nbytes = read_size_t(q); - if (nbytes > 0) - memset(q, DEADBYTE, nbytes); - PyObject_Free(q); + if (p == NULL) + return; + _PyObject_DebugCheckAddress(p); + nbytes = read_size_t(q); + if (nbytes > 0) + memset(q, DEADBYTE, nbytes); + PyObject_Free(q); } void * _PyObject_DebugRealloc(void *p, size_t nbytes) { - uchar *q = (uchar *)p; - uchar *tail; - size_t total; /* nbytes + 4*SST */ - size_t original_nbytes; - int i; - - if (p == NULL) - return _PyObject_DebugMalloc(nbytes); - - _PyObject_DebugCheckAddress(p); - bumpserialno(); - original_nbytes = read_size_t(q - 2*SST); - total = nbytes + 4*SST; - if (total < nbytes) - /* overflow: can't represent total as a size_t */ - return NULL; - - if (nbytes < original_nbytes) { - /* shrinking: mark old extra memory dead */ - memset(q + nbytes, DEADBYTE, original_nbytes - nbytes); - } - - /* Resize and add decorations. */ - q = (uchar *)PyObject_Realloc(q - 2*SST, total); - if (q == NULL) - return NULL; - - write_size_t(q, nbytes); - for (i = 0; i < SST; ++i) - assert(q[SST + i] == FORBIDDENBYTE); - q += 2*SST; - tail = q + nbytes; - memset(tail, FORBIDDENBYTE, SST); - write_size_t(tail + SST, serialno); - - if (nbytes > original_nbytes) { - /* growing: mark new extra memory clean */ - memset(q + original_nbytes, CLEANBYTE, - nbytes - original_nbytes); - } + uchar *q = (uchar *)p; + uchar *tail; + size_t total; /* nbytes + 4*SST */ + size_t original_nbytes; + int i; + + if (p == NULL) + return _PyObject_DebugMalloc(nbytes); + + _PyObject_DebugCheckAddress(p); + bumpserialno(); + original_nbytes = read_size_t(q - 2*SST); + total = nbytes + 4*SST; + if (total < nbytes) + /* overflow: can't represent total as a size_t */ + return NULL; + + if (nbytes < original_nbytes) { + /* shrinking: mark old extra memory dead */ + memset(q + nbytes, DEADBYTE, original_nbytes - nbytes); + } + + /* Resize and add decorations. */ + q = (uchar *)PyObject_Realloc(q - 2*SST, total); + if (q == NULL) + return NULL; + + write_size_t(q, nbytes); + for (i = 0; i < SST; ++i) + assert(q[SST + i] == FORBIDDENBYTE); + q += 2*SST; + tail = q + nbytes; + memset(tail, FORBIDDENBYTE, SST); + write_size_t(tail + SST, serialno); + + if (nbytes > original_nbytes) { + /* growing: mark new extra memory clean */ + memset(q + original_nbytes, CLEANBYTE, + nbytes - original_nbytes); + } - return q; + return q; } /* Check the forbidden bytes on both ends of the memory allocated for p. @@ -1435,176 +1435,176 @@ void _PyObject_DebugCheckAddress(const void *p) { - const uchar *q = (const uchar *)p; - char *msg; - size_t nbytes; - const uchar *tail; - int i; - - if (p == NULL) { - msg = "didn't expect a NULL pointer"; - goto error; - } - - /* Check the stuff at the start of p first: if there's underwrite - * corruption, the number-of-bytes field may be nuts, and checking - * the tail could lead to a segfault then. - */ - for (i = SST; i >= 1; --i) { - if (*(q-i) != FORBIDDENBYTE) { - msg = "bad leading pad byte"; - goto error; - } - } - - nbytes = read_size_t(q - 2*SST); - tail = q + nbytes; - for (i = 0; i < SST; ++i) { - if (tail[i] != FORBIDDENBYTE) { - msg = "bad trailing pad byte"; - goto error; - } - } + const uchar *q = (const uchar *)p; + char *msg; + size_t nbytes; + const uchar *tail; + int i; + + if (p == NULL) { + msg = "didn't expect a NULL pointer"; + goto error; + } + + /* Check the stuff at the start of p first: if there's underwrite + * corruption, the number-of-bytes field may be nuts, and checking + * the tail could lead to a segfault then. + */ + for (i = SST; i >= 1; --i) { + if (*(q-i) != FORBIDDENBYTE) { + msg = "bad leading pad byte"; + goto error; + } + } + + nbytes = read_size_t(q - 2*SST); + tail = q + nbytes; + for (i = 0; i < SST; ++i) { + if (tail[i] != FORBIDDENBYTE) { + msg = "bad trailing pad byte"; + goto error; + } + } - return; + return; error: - _PyObject_DebugDumpAddress(p); - Py_FatalError(msg); + _PyObject_DebugDumpAddress(p); + Py_FatalError(msg); } /* Display info to stderr about the memory block at p. */ void _PyObject_DebugDumpAddress(const void *p) { - const uchar *q = (const uchar *)p; - const uchar *tail; - size_t nbytes, serial; - int i; - int ok; - - fprintf(stderr, "Debug memory block at address p=%p:\n", p); - if (p == NULL) - return; - - nbytes = read_size_t(q - 2*SST); - fprintf(stderr, " %" PY_FORMAT_SIZE_T "u bytes originally " - "requested\n", nbytes); - - /* In case this is nuts, check the leading pad bytes first. */ - fprintf(stderr, " The %d pad bytes at p-%d are ", SST, SST); - ok = 1; - for (i = 1; i <= SST; ++i) { - if (*(q-i) != FORBIDDENBYTE) { - ok = 0; - break; - } - } - if (ok) - fputs("FORBIDDENBYTE, as expected.\n", stderr); - else { - fprintf(stderr, "not all FORBIDDENBYTE (0x%02x):\n", - FORBIDDENBYTE); - for (i = SST; i >= 1; --i) { - const uchar byte = *(q-i); - fprintf(stderr, " at p-%d: 0x%02x", i, byte); - if (byte != FORBIDDENBYTE) - fputs(" *** OUCH", stderr); - fputc('\n', stderr); - } - - fputs(" Because memory is corrupted at the start, the " - "count of bytes requested\n" - " may be bogus, and checking the trailing pad " - "bytes may segfault.\n", stderr); - } - - tail = q + nbytes; - fprintf(stderr, " The %d pad bytes at tail=%p are ", SST, tail); - ok = 1; - for (i = 0; i < SST; ++i) { - if (tail[i] != FORBIDDENBYTE) { - ok = 0; - break; - } - } - if (ok) - fputs("FORBIDDENBYTE, as expected.\n", stderr); - else { - fprintf(stderr, "not all FORBIDDENBYTE (0x%02x):\n", - FORBIDDENBYTE); - for (i = 0; i < SST; ++i) { - const uchar byte = tail[i]; - fprintf(stderr, " at tail+%d: 0x%02x", - i, byte); - if (byte != FORBIDDENBYTE) - fputs(" *** OUCH", stderr); - fputc('\n', stderr); - } - } - - serial = read_size_t(tail + SST); - fprintf(stderr, " The block was made by call #%" PY_FORMAT_SIZE_T - "u to debug malloc/realloc.\n", serial); - - if (nbytes > 0) { - i = 0; - fputs(" Data at p:", stderr); - /* print up to 8 bytes at the start */ - while (q < tail && i < 8) { - fprintf(stderr, " %02x", *q); - ++i; - ++q; - } - /* and up to 8 at the end */ - if (q < tail) { - if (tail - q > 8) { - fputs(" ...", stderr); - q = tail - 8; - } - while (q < tail) { - fprintf(stderr, " %02x", *q); - ++q; - } - } - fputc('\n', stderr); - } + const uchar *q = (const uchar *)p; + const uchar *tail; + size_t nbytes, serial; + int i; + int ok; + + fprintf(stderr, "Debug memory block at address p=%p:\n", p); + if (p == NULL) + return; + + nbytes = read_size_t(q - 2*SST); + fprintf(stderr, " %" PY_FORMAT_SIZE_T "u bytes originally " + "requested\n", nbytes); + + /* In case this is nuts, check the leading pad bytes first. */ + fprintf(stderr, " The %d pad bytes at p-%d are ", SST, SST); + ok = 1; + for (i = 1; i <= SST; ++i) { + if (*(q-i) != FORBIDDENBYTE) { + ok = 0; + break; + } + } + if (ok) + fputs("FORBIDDENBYTE, as expected.\n", stderr); + else { + fprintf(stderr, "not all FORBIDDENBYTE (0x%02x):\n", + FORBIDDENBYTE); + for (i = SST; i >= 1; --i) { + const uchar byte = *(q-i); + fprintf(stderr, " at p-%d: 0x%02x", i, byte); + if (byte != FORBIDDENBYTE) + fputs(" *** OUCH", stderr); + fputc('\n', stderr); + } + + fputs(" Because memory is corrupted at the start, the " + "count of bytes requested\n" + " may be bogus, and checking the trailing pad " + "bytes may segfault.\n", stderr); + } + + tail = q + nbytes; + fprintf(stderr, " The %d pad bytes at tail=%p are ", SST, tail); + ok = 1; + for (i = 0; i < SST; ++i) { + if (tail[i] != FORBIDDENBYTE) { + ok = 0; + break; + } + } + if (ok) + fputs("FORBIDDENBYTE, as expected.\n", stderr); + else { + fprintf(stderr, "not all FORBIDDENBYTE (0x%02x):\n", + FORBIDDENBYTE); + for (i = 0; i < SST; ++i) { + const uchar byte = tail[i]; + fprintf(stderr, " at tail+%d: 0x%02x", + i, byte); + if (byte != FORBIDDENBYTE) + fputs(" *** OUCH", stderr); + fputc('\n', stderr); + } + } + + serial = read_size_t(tail + SST); + fprintf(stderr, " The block was made by call #%" PY_FORMAT_SIZE_T + "u to debug malloc/realloc.\n", serial); + + if (nbytes > 0) { + i = 0; + fputs(" Data at p:", stderr); + /* print up to 8 bytes at the start */ + while (q < tail && i < 8) { + fprintf(stderr, " %02x", *q); + ++i; + ++q; + } + /* and up to 8 at the end */ + if (q < tail) { + if (tail - q > 8) { + fputs(" ...", stderr); + q = tail - 8; + } + while (q < tail) { + fprintf(stderr, " %02x", *q); + ++q; + } + } + fputc('\n', stderr); + } } static size_t printone(const char* msg, size_t value) { - int i, k; - char buf[100]; - size_t origvalue = value; - - fputs(msg, stderr); - for (i = (int)strlen(msg); i < 35; ++i) - fputc(' ', stderr); - fputc('=', stderr); - - /* Write the value with commas. */ - i = 22; - buf[i--] = '\0'; - buf[i--] = '\n'; - k = 3; - do { - size_t nextvalue = value / 10; - uint digit = (uint)(value - nextvalue * 10); - value = nextvalue; - buf[i--] = (char)(digit + '0'); - --k; - if (k == 0 && value && i >= 0) { - k = 3; - buf[i--] = ','; - } - } while (value && i >= 0); - - while (i >= 0) - buf[i--] = ' '; - fputs(buf, stderr); + int i, k; + char buf[100]; + size_t origvalue = value; + + fputs(msg, stderr); + for (i = (int)strlen(msg); i < 35; ++i) + fputc(' ', stderr); + fputc('=', stderr); + + /* Write the value with commas. */ + i = 22; + buf[i--] = '\0'; + buf[i--] = '\n'; + k = 3; + do { + size_t nextvalue = value / 10; + uint digit = (uint)(value - nextvalue * 10); + value = nextvalue; + buf[i--] = (char)(digit + '0'); + --k; + if (k == 0 && value && i >= 0) { + k = 3; + buf[i--] = ','; + } + } while (value && i >= 0); + + while (i >= 0) + buf[i--] = ' '; + fputs(buf, stderr); - return origvalue; + return origvalue; } /* Print summary info to stderr about the state of pymalloc's structures. @@ -1614,142 +1614,142 @@ void _PyObject_DebugMallocStats(void) { - uint i; - const uint numclasses = SMALL_REQUEST_THRESHOLD >> ALIGNMENT_SHIFT; - /* # of pools, allocated blocks, and free blocks per class index */ - size_t numpools[SMALL_REQUEST_THRESHOLD >> ALIGNMENT_SHIFT]; - size_t numblocks[SMALL_REQUEST_THRESHOLD >> ALIGNMENT_SHIFT]; - size_t numfreeblocks[SMALL_REQUEST_THRESHOLD >> ALIGNMENT_SHIFT]; - /* total # of allocated bytes in used and full pools */ - size_t allocated_bytes = 0; - /* total # of available bytes in used pools */ - size_t available_bytes = 0; - /* # of free pools + pools not yet carved out of current arena */ - uint numfreepools = 0; - /* # of bytes for arena alignment padding */ - size_t arena_alignment = 0; - /* # of bytes in used and full pools used for pool_headers */ - size_t pool_header_bytes = 0; - /* # of bytes in used and full pools wasted due to quantization, - * i.e. the necessarily leftover space at the ends of used and - * full pools. - */ - size_t quantization = 0; - /* # of arenas actually allocated. */ - size_t narenas = 0; - /* running total -- should equal narenas * ARENA_SIZE */ - size_t total; - char buf[128]; - - fprintf(stderr, "Small block threshold = %d, in %u size classes.\n", - SMALL_REQUEST_THRESHOLD, numclasses); - - for (i = 0; i < numclasses; ++i) - numpools[i] = numblocks[i] = numfreeblocks[i] = 0; - - /* Because full pools aren't linked to from anything, it's easiest - * to march over all the arenas. If we're lucky, most of the memory - * will be living in full pools -- would be a shame to miss them. - */ - for (i = 0; i < maxarenas; ++i) { - uint poolsinarena; - uint j; - uptr base = arenas[i].address; - - /* Skip arenas which are not allocated. */ - if (arenas[i].address == (uptr)NULL) - continue; - narenas += 1; - - poolsinarena = arenas[i].ntotalpools; - numfreepools += arenas[i].nfreepools; - - /* round up to pool alignment */ - if (base & (uptr)POOL_SIZE_MASK) { - arena_alignment += POOL_SIZE; - base &= ~(uptr)POOL_SIZE_MASK; - base += POOL_SIZE; - } - - /* visit every pool in the arena */ - assert(base <= (uptr) arenas[i].pool_address); - for (j = 0; - base < (uptr) arenas[i].pool_address; - ++j, base += POOL_SIZE) { - poolp p = (poolp)base; - const uint sz = p->szidx; - uint freeblocks; - - if (p->ref.count == 0) { - /* currently unused */ - assert(pool_is_in_list(p, arenas[i].freepools)); - continue; - } - ++numpools[sz]; - numblocks[sz] += p->ref.count; - freeblocks = NUMBLOCKS(sz) - p->ref.count; - numfreeblocks[sz] += freeblocks; + uint i; + const uint numclasses = SMALL_REQUEST_THRESHOLD >> ALIGNMENT_SHIFT; + /* # of pools, allocated blocks, and free blocks per class index */ + size_t numpools[SMALL_REQUEST_THRESHOLD >> ALIGNMENT_SHIFT]; + size_t numblocks[SMALL_REQUEST_THRESHOLD >> ALIGNMENT_SHIFT]; + size_t numfreeblocks[SMALL_REQUEST_THRESHOLD >> ALIGNMENT_SHIFT]; + /* total # of allocated bytes in used and full pools */ + size_t allocated_bytes = 0; + /* total # of available bytes in used pools */ + size_t available_bytes = 0; + /* # of free pools + pools not yet carved out of current arena */ + uint numfreepools = 0; + /* # of bytes for arena alignment padding */ + size_t arena_alignment = 0; + /* # of bytes in used and full pools used for pool_headers */ + size_t pool_header_bytes = 0; + /* # of bytes in used and full pools wasted due to quantization, + * i.e. the necessarily leftover space at the ends of used and + * full pools. + */ + size_t quantization = 0; + /* # of arenas actually allocated. */ + size_t narenas = 0; + /* running total -- should equal narenas * ARENA_SIZE */ + size_t total; + char buf[128]; + + fprintf(stderr, "Small block threshold = %d, in %u size classes.\n", + SMALL_REQUEST_THRESHOLD, numclasses); + + for (i = 0; i < numclasses; ++i) + numpools[i] = numblocks[i] = numfreeblocks[i] = 0; + + /* Because full pools aren't linked to from anything, it's easiest + * to march over all the arenas. If we're lucky, most of the memory + * will be living in full pools -- would be a shame to miss them. + */ + for (i = 0; i < maxarenas; ++i) { + uint poolsinarena; + uint j; + uptr base = arenas[i].address; + + /* Skip arenas which are not allocated. */ + if (arenas[i].address == (uptr)NULL) + continue; + narenas += 1; + + poolsinarena = arenas[i].ntotalpools; + numfreepools += arenas[i].nfreepools; + + /* round up to pool alignment */ + if (base & (uptr)POOL_SIZE_MASK) { + arena_alignment += POOL_SIZE; + base &= ~(uptr)POOL_SIZE_MASK; + base += POOL_SIZE; + } + + /* visit every pool in the arena */ + assert(base <= (uptr) arenas[i].pool_address); + for (j = 0; + base < (uptr) arenas[i].pool_address; + ++j, base += POOL_SIZE) { + poolp p = (poolp)base; + const uint sz = p->szidx; + uint freeblocks; + + if (p->ref.count == 0) { + /* currently unused */ + assert(pool_is_in_list(p, arenas[i].freepools)); + continue; + } + ++numpools[sz]; + numblocks[sz] += p->ref.count; + freeblocks = NUMBLOCKS(sz) - p->ref.count; + numfreeblocks[sz] += freeblocks; #ifdef Py_DEBUG - if (freeblocks > 0) - assert(pool_is_in_list(p, usedpools[sz + sz])); + if (freeblocks > 0) + assert(pool_is_in_list(p, usedpools[sz + sz])); #endif - } - } - assert(narenas == narenas_currently_allocated); - - fputc('\n', stderr); - fputs("class size num pools blocks in use avail blocks\n" - "----- ---- --------- ------------- ------------\n", - stderr); - - for (i = 0; i < numclasses; ++i) { - size_t p = numpools[i]; - size_t b = numblocks[i]; - size_t f = numfreeblocks[i]; - uint size = INDEX2SIZE(i); - if (p == 0) { - assert(b == 0 && f == 0); - continue; - } - fprintf(stderr, "%5u %6u " - "%11" PY_FORMAT_SIZE_T "u " - "%15" PY_FORMAT_SIZE_T "u " - "%13" PY_FORMAT_SIZE_T "u\n", - i, size, p, b, f); - allocated_bytes += b * size; - available_bytes += f * size; - pool_header_bytes += p * POOL_OVERHEAD; - quantization += p * ((POOL_SIZE - POOL_OVERHEAD) % size); - } - fputc('\n', stderr); - (void)printone("# times object malloc called", serialno); - - (void)printone("# arenas allocated total", ntimes_arena_allocated); - (void)printone("# arenas reclaimed", ntimes_arena_allocated - narenas); - (void)printone("# arenas highwater mark", narenas_highwater); - (void)printone("# arenas allocated current", narenas); - - PyOS_snprintf(buf, sizeof(buf), - "%" PY_FORMAT_SIZE_T "u arenas * %d bytes/arena", - narenas, ARENA_SIZE); - (void)printone(buf, narenas * ARENA_SIZE); - - fputc('\n', stderr); - - total = printone("# bytes in allocated blocks", allocated_bytes); - total += printone("# bytes in available blocks", available_bytes); - - PyOS_snprintf(buf, sizeof(buf), - "%u unused pools * %d bytes", numfreepools, POOL_SIZE); - total += printone(buf, (size_t)numfreepools * POOL_SIZE); - - total += printone("# bytes lost to pool headers", pool_header_bytes); - total += printone("# bytes lost to quantization", quantization); - total += printone("# bytes lost to arena alignment", arena_alignment); - (void)printone("Total", total); + } + } + assert(narenas == narenas_currently_allocated); + + fputc('\n', stderr); + fputs("class size num pools blocks in use avail blocks\n" + "----- ---- --------- ------------- ------------\n", + stderr); + + for (i = 0; i < numclasses; ++i) { + size_t p = numpools[i]; + size_t b = numblocks[i]; + size_t f = numfreeblocks[i]; + uint size = INDEX2SIZE(i); + if (p == 0) { + assert(b == 0 && f == 0); + continue; + } + fprintf(stderr, "%5u %6u " + "%11" PY_FORMAT_SIZE_T "u " + "%15" PY_FORMAT_SIZE_T "u " + "%13" PY_FORMAT_SIZE_T "u\n", + i, size, p, b, f); + allocated_bytes += b * size; + available_bytes += f * size; + pool_header_bytes += p * POOL_OVERHEAD; + quantization += p * ((POOL_SIZE - POOL_OVERHEAD) % size); + } + fputc('\n', stderr); + (void)printone("# times object malloc called", serialno); + + (void)printone("# arenas allocated total", ntimes_arena_allocated); + (void)printone("# arenas reclaimed", ntimes_arena_allocated - narenas); + (void)printone("# arenas highwater mark", narenas_highwater); + (void)printone("# arenas allocated current", narenas); + + PyOS_snprintf(buf, sizeof(buf), + "%" PY_FORMAT_SIZE_T "u arenas * %d bytes/arena", + narenas, ARENA_SIZE); + (void)printone(buf, narenas * ARENA_SIZE); + + fputc('\n', stderr); + + total = printone("# bytes in allocated blocks", allocated_bytes); + total += printone("# bytes in available blocks", available_bytes); + + PyOS_snprintf(buf, sizeof(buf), + "%u unused pools * %d bytes", numfreepools, POOL_SIZE); + total += printone(buf, (size_t)numfreepools * POOL_SIZE); + + total += printone("# bytes lost to pool headers", pool_header_bytes); + total += printone("# bytes lost to quantization", quantization); + total += printone("# bytes lost to arena alignment", arena_alignment); + (void)printone("Total", total); } -#endif /* PYMALLOC_DEBUG */ +#endif /* PYMALLOC_DEBUG */ #ifdef Py_USING_MEMORY_DEBUGGER /* Make this function last so gcc won't inline it since the definition is @@ -1758,8 +1758,8 @@ int Py_ADDRESS_IN_RANGE(void *P, poolp pool) { - return pool->arenaindex < maxarenas && - (uptr)P - arenas[pool->arenaindex].address < (uptr)ARENA_SIZE && - arenas[pool->arenaindex].address != 0; + return pool->arenaindex < maxarenas && + (uptr)P - arenas[pool->arenaindex].address < (uptr)ARENA_SIZE && + arenas[pool->arenaindex].address != 0; } #endif Modified: python/branches/release31-maint/Objects/rangeobject.c ============================================================================== --- python/branches/release31-maint/Objects/rangeobject.c (original) +++ python/branches/release31-maint/Objects/rangeobject.c Sun May 9 18:14:21 2010 @@ -17,7 +17,7 @@ } rangeobject; /* Helper function for validating step. Always returns a new reference or - NULL on error. + NULL on error. */ static PyObject * validate_step(PyObject *step) @@ -269,16 +269,16 @@ static PyObject * range_reduce(rangeobject *r, PyObject *args) { - return Py_BuildValue("(O(OOO))", Py_TYPE(r), + return Py_BuildValue("(O(OOO))", Py_TYPE(r), r->start, r->stop, r->step); } static PySequenceMethods range_as_sequence = { - (lenfunc)range_length, /* sq_length */ - 0, /* sq_concat */ - 0, /* sq_repeat */ + (lenfunc)range_length, /* sq_length */ + 0, /* sq_concat */ + 0, /* sq_repeat */ (ssizeargfunc)range_item, /* sq_item */ - 0, /* sq_slice */ + 0, /* sq_slice */ }; static PyObject * range_iter(PyObject *seq); @@ -288,51 +288,51 @@ "Returns a reverse iterator."); static PyMethodDef range_methods[] = { - {"__reversed__", (PyCFunction)range_reverse, METH_NOARGS, - reverse_doc}, - {"__reduce__", (PyCFunction)range_reduce, METH_VARARGS}, - {NULL, NULL} /* sentinel */ + {"__reversed__", (PyCFunction)range_reverse, METH_NOARGS, + reverse_doc}, + {"__reduce__", (PyCFunction)range_reduce, METH_VARARGS}, + {NULL, NULL} /* sentinel */ }; PyTypeObject PyRange_Type = { - PyVarObject_HEAD_INIT(&PyType_Type, 0) - "range", /* Name of this type */ - sizeof(rangeobject), /* Basic object size */ - 0, /* Item size for varobject */ - (destructor)range_dealloc, /* tp_dealloc */ - 0, /* tp_print */ - 0, /* tp_getattr */ - 0, /* tp_setattr */ - 0, /* tp_reserved */ - (reprfunc)range_repr, /* tp_repr */ - 0, /* tp_as_number */ - &range_as_sequence, /* tp_as_sequence */ - 0, /* tp_as_mapping */ - 0, /* tp_hash */ - 0, /* tp_call */ - 0, /* tp_str */ - PyObject_GenericGetAttr, /* tp_getattro */ - 0, /* tp_setattro */ - 0, /* tp_as_buffer */ - Py_TPFLAGS_DEFAULT, /* tp_flags */ - range_doc, /* tp_doc */ - 0, /* tp_traverse */ - 0, /* tp_clear */ - 0, /* tp_richcompare */ - 0, /* tp_weaklistoffset */ - range_iter, /* tp_iter */ - 0, /* tp_iternext */ - range_methods, /* tp_methods */ - 0, /* tp_members */ - 0, /* tp_getset */ - 0, /* tp_base */ - 0, /* tp_dict */ - 0, /* tp_descr_get */ - 0, /* tp_descr_set */ - 0, /* tp_dictoffset */ - 0, /* tp_init */ - 0, /* tp_alloc */ - range_new, /* tp_new */ + PyVarObject_HEAD_INIT(&PyType_Type, 0) + "range", /* Name of this type */ + sizeof(rangeobject), /* Basic object size */ + 0, /* Item size for varobject */ + (destructor)range_dealloc, /* tp_dealloc */ + 0, /* tp_print */ + 0, /* tp_getattr */ + 0, /* tp_setattr */ + 0, /* tp_reserved */ + (reprfunc)range_repr, /* tp_repr */ + 0, /* tp_as_number */ + &range_as_sequence, /* tp_as_sequence */ + 0, /* tp_as_mapping */ + 0, /* tp_hash */ + 0, /* tp_call */ + 0, /* tp_str */ + PyObject_GenericGetAttr, /* tp_getattro */ + 0, /* tp_setattro */ + 0, /* tp_as_buffer */ + Py_TPFLAGS_DEFAULT, /* tp_flags */ + range_doc, /* tp_doc */ + 0, /* tp_traverse */ + 0, /* tp_clear */ + 0, /* tp_richcompare */ + 0, /* tp_weaklistoffset */ + range_iter, /* tp_iter */ + 0, /* tp_iternext */ + range_methods, /* tp_methods */ + 0, /* tp_members */ + 0, /* tp_getset */ + 0, /* tp_base */ + 0, /* tp_dict */ + 0, /* tp_descr_get */ + 0, /* tp_descr_set */ + 0, /* tp_dictoffset */ + 0, /* tp_init */ + 0, /* tp_alloc */ + range_new, /* tp_new */ }; /*********************** range Iterator **************************/ @@ -343,18 +343,18 @@ */ typedef struct { - PyObject_HEAD - long index; - long start; - long step; - long len; + PyObject_HEAD + long index; + long start; + long step; + long len; } rangeiterobject; static PyObject * rangeiter_next(rangeiterobject *r) { if (r->index < r->len) - /* cast to unsigned to avoid possible signed overflow + /* cast to unsigned to avoid possible signed overflow in intermediate calculations. */ return PyLong_FromLong((long)(r->start + (unsigned long)(r->index++) * r->step)); @@ -388,50 +388,50 @@ static PyMethodDef rangeiter_methods[] = { {"__length_hint__", (PyCFunction)rangeiter_len, METH_NOARGS, - length_hint_doc}, - {NULL, NULL} /* sentinel */ + length_hint_doc}, + {NULL, NULL} /* sentinel */ }; PyTypeObject PyRangeIter_Type = { - PyVarObject_HEAD_INIT(&PyType_Type, 0) - "range_iterator", /* tp_name */ - sizeof(rangeiterobject), /* tp_basicsize */ - 0, /* tp_itemsize */ - /* methods */ - (destructor)PyObject_Del, /* 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, /* tp_flags */ - 0, /* tp_doc */ - 0, /* tp_traverse */ - 0, /* tp_clear */ - 0, /* tp_richcompare */ - 0, /* tp_weaklistoffset */ - PyObject_SelfIter, /* tp_iter */ - (iternextfunc)rangeiter_next, /* tp_iternext */ - rangeiter_methods, /* tp_methods */ - 0, /* tp_members */ - 0, /* tp_getset */ - 0, /* tp_base */ - 0, /* tp_dict */ - 0, /* tp_descr_get */ - 0, /* tp_descr_set */ - 0, /* tp_dictoffset */ - 0, /* tp_init */ - 0, /* tp_alloc */ - rangeiter_new, /* tp_new */ + PyVarObject_HEAD_INIT(&PyType_Type, 0) + "range_iterator", /* tp_name */ + sizeof(rangeiterobject), /* tp_basicsize */ + 0, /* tp_itemsize */ + /* methods */ + (destructor)PyObject_Del, /* 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, /* tp_flags */ + 0, /* tp_doc */ + 0, /* tp_traverse */ + 0, /* tp_clear */ + 0, /* tp_richcompare */ + 0, /* tp_weaklistoffset */ + PyObject_SelfIter, /* tp_iter */ + (iternextfunc)rangeiter_next, /* tp_iternext */ + rangeiter_methods, /* tp_methods */ + 0, /* tp_members */ + 0, /* tp_getset */ + 0, /* tp_base */ + 0, /* tp_dict */ + 0, /* tp_descr_get */ + 0, /* tp_descr_set */ + 0, /* tp_dictoffset */ + 0, /* tp_init */ + 0, /* tp_alloc */ + rangeiter_new, /* tp_new */ }; /* Return number of items in range (lo, hi, step). step != 0 @@ -503,8 +503,8 @@ static PyMethodDef longrangeiter_methods[] = { {"__length_hint__", (PyCFunction)longrangeiter_len, METH_NOARGS, - length_hint_doc}, - {NULL, NULL} /* sentinel */ + length_hint_doc}, + {NULL, NULL} /* sentinel */ }; static void @@ -553,36 +553,36 @@ } PyTypeObject PyLongRangeIter_Type = { - PyVarObject_HEAD_INIT(&PyType_Type, 0) - "longrange_iterator", /* tp_name */ - sizeof(longrangeiterobject), /* tp_basicsize */ - 0, /* tp_itemsize */ - /* methods */ - (destructor)longrangeiter_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, /* tp_flags */ - 0, /* tp_doc */ - 0, /* tp_traverse */ - 0, /* tp_clear */ - 0, /* tp_richcompare */ - 0, /* tp_weaklistoffset */ - PyObject_SelfIter, /* tp_iter */ - (iternextfunc)longrangeiter_next, /* tp_iternext */ - longrangeiter_methods, /* tp_methods */ - 0, + PyVarObject_HEAD_INIT(&PyType_Type, 0) + "longrange_iterator", /* tp_name */ + sizeof(longrangeiterobject), /* tp_basicsize */ + 0, /* tp_itemsize */ + /* methods */ + (destructor)longrangeiter_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, /* tp_flags */ + 0, /* tp_doc */ + 0, /* tp_traverse */ + 0, /* tp_clear */ + 0, /* tp_richcompare */ + 0, /* tp_weaklistoffset */ + PyObject_SelfIter, /* tp_iter */ + (iternextfunc)longrangeiter_next, /* tp_iternext */ + longrangeiter_methods, /* tp_methods */ + 0, }; static PyObject * Modified: python/branches/release31-maint/Objects/setobject.c ============================================================================== --- python/branches/release31-maint/Objects/setobject.c (original) +++ python/branches/release31-maint/Objects/setobject.c Sun May 9 18:14:21 2010 @@ -1,5 +1,5 @@ -/* set object implementation +/* set object implementation Written and maintained by Raymond D. Hettinger Derived from Lib/sets.py and Objects/dictobject.c. @@ -17,12 +17,12 @@ static void set_key_error(PyObject *arg) { - PyObject *tup; - tup = PyTuple_Pack(1, arg); - if (!tup) - return; /* caller will expect error to be set anyway */ - PyErr_SetObject(PyExc_KeyError, tup); - Py_DECREF(tup); + PyObject *tup; + tup = PyTuple_Pack(1, arg); + if (!tup) + return; /* caller will expect error to be set anyway */ + PyErr_SetObject(PyExc_KeyError, tup); + Py_DECREF(tup); } /* This must be >= 1. */ @@ -35,20 +35,20 @@ PyObject * _PySet_Dummy(void) { - return dummy; + return dummy; } #endif -#define INIT_NONZERO_SET_SLOTS(so) do { \ - (so)->table = (so)->smalltable; \ - (so)->mask = PySet_MINSIZE - 1; \ - (so)->hash = -1; \ +#define INIT_NONZERO_SET_SLOTS(so) do { \ + (so)->table = (so)->smalltable; \ + (so)->mask = PySet_MINSIZE - 1; \ + (so)->hash = -1; \ } while(0) -#define EMPTY_TO_MINSIZE(so) do { \ - memset((so)->smalltable, 0, sizeof((so)->smalltable)); \ - (so)->used = (so)->fill = 0; \ - INIT_NONZERO_SET_SLOTS(so); \ +#define EMPTY_TO_MINSIZE(so) do { \ + memset((so)->smalltable, 0, sizeof((so)->smalltable)); \ + (so)->used = (so)->fill = 0; \ + INIT_NONZERO_SET_SLOTS(so); \ } while(0) /* Reuse scheme to save calls to malloc, free, and memset */ @@ -77,78 +77,78 @@ static setentry * set_lookkey(PySetObject *so, PyObject *key, register long hash) { - register Py_ssize_t i; - register size_t perturb; - register setentry *freeslot; - register size_t mask = so->mask; - setentry *table = so->table; - register setentry *entry; - register int cmp; - PyObject *startkey; - - i = hash & mask; - entry = &table[i]; - if (entry->key == NULL || entry->key == key) - return entry; - - if (entry->key == dummy) - freeslot = entry; - else { - if (entry->hash == hash) { - startkey = entry->key; - Py_INCREF(startkey); - cmp = PyObject_RichCompareBool(startkey, key, Py_EQ); - Py_DECREF(startkey); - if (cmp < 0) - return NULL; - if (table == so->table && entry->key == startkey) { - if (cmp > 0) - return entry; - } - else { - /* The compare did major nasty stuff to the - * set: start over. - */ - return set_lookkey(so, key, hash); - } - } - freeslot = NULL; - } - - /* In the loop, key == dummy is by far (factor of 100s) the - least likely outcome, so test for that last. */ - for (perturb = hash; ; perturb >>= PERTURB_SHIFT) { - i = (i << 2) + i + perturb + 1; - entry = &table[i & mask]; - if (entry->key == NULL) { - if (freeslot != NULL) - entry = freeslot; - break; - } - if (entry->key == key) - break; - if (entry->hash == hash && entry->key != dummy) { - startkey = entry->key; - Py_INCREF(startkey); - cmp = PyObject_RichCompareBool(startkey, key, Py_EQ); - Py_DECREF(startkey); - if (cmp < 0) - return NULL; - if (table == so->table && entry->key == startkey) { - if (cmp > 0) - break; - } - else { - /* The compare did major nasty stuff to the - * set: start over. - */ - return set_lookkey(so, key, hash); - } - } - else if (entry->key == dummy && freeslot == NULL) - freeslot = entry; - } - return entry; + register Py_ssize_t i; + register size_t perturb; + register setentry *freeslot; + register size_t mask = so->mask; + setentry *table = so->table; + register setentry *entry; + register int cmp; + PyObject *startkey; + + i = hash & mask; + entry = &table[i]; + if (entry->key == NULL || entry->key == key) + return entry; + + if (entry->key == dummy) + freeslot = entry; + else { + if (entry->hash == hash) { + startkey = entry->key; + Py_INCREF(startkey); + cmp = PyObject_RichCompareBool(startkey, key, Py_EQ); + Py_DECREF(startkey); + if (cmp < 0) + return NULL; + if (table == so->table && entry->key == startkey) { + if (cmp > 0) + return entry; + } + else { + /* The compare did major nasty stuff to the + * set: start over. + */ + return set_lookkey(so, key, hash); + } + } + freeslot = NULL; + } + + /* In the loop, key == dummy is by far (factor of 100s) the + least likely outcome, so test for that last. */ + for (perturb = hash; ; perturb >>= PERTURB_SHIFT) { + i = (i << 2) + i + perturb + 1; + entry = &table[i & mask]; + if (entry->key == NULL) { + if (freeslot != NULL) + entry = freeslot; + break; + } + if (entry->key == key) + break; + if (entry->hash == hash && entry->key != dummy) { + startkey = entry->key; + Py_INCREF(startkey); + cmp = PyObject_RichCompareBool(startkey, key, Py_EQ); + Py_DECREF(startkey); + if (cmp < 0) + return NULL; + if (table == so->table && entry->key == startkey) { + if (cmp > 0) + break; + } + else { + /* The compare did major nasty stuff to the + * set: start over. + */ + return set_lookkey(so, key, hash); + } + } + else if (entry->key == dummy && freeslot == NULL) + freeslot = entry; + } + return entry; } /* @@ -159,50 +159,50 @@ static setentry * set_lookkey_unicode(PySetObject *so, PyObject *key, register long hash) { - register Py_ssize_t i; - register size_t perturb; - register setentry *freeslot; - register size_t mask = so->mask; - setentry *table = so->table; - register setentry *entry; - - /* Make sure this function doesn't have to handle non-unicode keys, - including subclasses of str; e.g., one reason to subclass - strings is to override __eq__, and for speed we don't cater to - that here. */ - if (!PyUnicode_CheckExact(key)) { - so->lookup = set_lookkey; - return set_lookkey(so, key, hash); - } - i = hash & mask; - entry = &table[i]; - if (entry->key == NULL || entry->key == key) - return entry; - if (entry->key == dummy) - freeslot = entry; - else { - if (entry->hash == hash && unicode_eq(entry->key, key)) - return entry; - freeslot = NULL; - } - - /* In the loop, key == dummy is by far (factor of 100s) the - least likely outcome, so test for that last. */ - for (perturb = hash; ; perturb >>= PERTURB_SHIFT) { - i = (i << 2) + i + perturb + 1; - entry = &table[i & mask]; - if (entry->key == NULL) - return freeslot == NULL ? entry : freeslot; - if (entry->key == key - || (entry->hash == hash - && entry->key != dummy - && unicode_eq(entry->key, key))) - return entry; - if (entry->key == dummy && freeslot == NULL) - freeslot = entry; - } - assert(0); /* NOT REACHED */ - return 0; + register Py_ssize_t i; + register size_t perturb; + register setentry *freeslot; + register size_t mask = so->mask; + setentry *table = so->table; + register setentry *entry; + + /* Make sure this function doesn't have to handle non-unicode keys, + including subclasses of str; e.g., one reason to subclass + strings is to override __eq__, and for speed we don't cater to + that here. */ + if (!PyUnicode_CheckExact(key)) { + so->lookup = set_lookkey; + return set_lookkey(so, key, hash); + } + i = hash & mask; + entry = &table[i]; + if (entry->key == NULL || entry->key == key) + return entry; + if (entry->key == dummy) + freeslot = entry; + else { + if (entry->hash == hash && unicode_eq(entry->key, key)) + return entry; + freeslot = NULL; + } + + /* In the loop, key == dummy is by far (factor of 100s) the + least likely outcome, so test for that last. */ + for (perturb = hash; ; perturb >>= PERTURB_SHIFT) { + i = (i << 2) + i + perturb + 1; + entry = &table[i & mask]; + if (entry->key == NULL) + return freeslot == NULL ? entry : freeslot; + if (entry->key == key + || (entry->hash == hash + && entry->key != dummy + && unicode_eq(entry->key, key))) + return entry; + if (entry->key == dummy && freeslot == NULL) + freeslot = entry; + } + assert(0); /* NOT REACHED */ + return 0; } /* @@ -213,30 +213,30 @@ static int set_insert_key(register PySetObject *so, PyObject *key, long hash) { - register setentry *entry; - typedef setentry *(*lookupfunc)(PySetObject *, PyObject *, long); + register setentry *entry; + typedef setentry *(*lookupfunc)(PySetObject *, PyObject *, long); - assert(so->lookup != NULL); - entry = so->lookup(so, key, hash); - if (entry == NULL) - return -1; - if (entry->key == NULL) { - /* UNUSED */ - so->fill++; - entry->key = key; - entry->hash = hash; - so->used++; - } else if (entry->key == dummy) { - /* DUMMY */ - entry->key = key; - entry->hash = hash; - so->used++; - Py_DECREF(dummy); - } else { - /* ACTIVE */ - Py_DECREF(key); - } - return 0; + assert(so->lookup != NULL); + entry = so->lookup(so, key, hash); + if (entry == NULL) + return -1; + if (entry->key == NULL) { + /* UNUSED */ + so->fill++; + entry->key = key; + entry->hash = hash; + so->used++; + } else if (entry->key == dummy) { + /* DUMMY */ + entry->key = key; + entry->hash = hash; + so->used++; + Py_DECREF(dummy); + } else { + /* ACTIVE */ + Py_DECREF(key); + } + return 0; } /* @@ -250,22 +250,22 @@ static void set_insert_clean(register PySetObject *so, PyObject *key, long hash) { - register size_t i; - register size_t perturb; - register size_t mask = (size_t)so->mask; - setentry *table = so->table; - register setentry *entry; - - i = hash & mask; - entry = &table[i]; - for (perturb = hash; entry->key != NULL; perturb >>= PERTURB_SHIFT) { - i = (i << 2) + i + perturb + 1; - entry = &table[i & mask]; - } - so->fill++; - entry->key = key; - entry->hash = hash; - so->used++; + register size_t i; + register size_t perturb; + register size_t mask = (size_t)so->mask; + setentry *table = so->table; + register setentry *entry; + + i = hash & mask; + entry = &table[i]; + for (perturb = hash; entry->key != NULL; perturb >>= PERTURB_SHIFT) { + i = (i << 2) + i + perturb + 1; + entry = &table[i & mask]; + } + so->fill++; + entry->key = key; + entry->hash = hash; + so->used++; } /* @@ -276,86 +276,86 @@ static int set_table_resize(PySetObject *so, Py_ssize_t minused) { - Py_ssize_t newsize; - setentry *oldtable, *newtable, *entry; - Py_ssize_t i; - int is_oldtable_malloced; - setentry small_copy[PySet_MINSIZE]; - - assert(minused >= 0); - - /* Find the smallest table size > minused. */ - for (newsize = PySet_MINSIZE; - newsize <= minused && newsize > 0; - newsize <<= 1) - ; - if (newsize <= 0) { - PyErr_NoMemory(); - return -1; - } - - /* Get space for a new table. */ - oldtable = so->table; - assert(oldtable != NULL); - is_oldtable_malloced = oldtable != so->smalltable; - - if (newsize == PySet_MINSIZE) { - /* A large table is shrinking, or we can't get any smaller. */ - newtable = so->smalltable; - if (newtable == oldtable) { - if (so->fill == so->used) { - /* No dummies, so no point doing anything. */ - return 0; - } - /* We're not going to resize it, but rebuild the - table anyway to purge old dummy entries. - Subtle: This is *necessary* if fill==size, - as set_lookkey needs at least one virgin slot to - terminate failing searches. If fill < size, it's - merely desirable, as dummies slow searches. */ - assert(so->fill > so->used); - memcpy(small_copy, oldtable, sizeof(small_copy)); - oldtable = small_copy; - } - } - else { - newtable = PyMem_NEW(setentry, newsize); - if (newtable == NULL) { - PyErr_NoMemory(); - return -1; - } - } - - /* Make the set empty, using the new table. */ - assert(newtable != oldtable); - so->table = newtable; - so->mask = newsize - 1; - memset(newtable, 0, sizeof(setentry) * newsize); - so->used = 0; - i = so->fill; - so->fill = 0; - - /* Copy the data over; this is refcount-neutral for active entries; - dummy entries aren't copied over, of course */ - for (entry = oldtable; i > 0; entry++) { - if (entry->key == NULL) { - /* UNUSED */ - ; - } else if (entry->key == dummy) { - /* DUMMY */ - --i; - assert(entry->key == dummy); - Py_DECREF(entry->key); - } else { - /* ACTIVE */ - --i; - set_insert_clean(so, entry->key, entry->hash); - } - } - - if (is_oldtable_malloced) - PyMem_DEL(oldtable); - return 0; + Py_ssize_t newsize; + setentry *oldtable, *newtable, *entry; + Py_ssize_t i; + int is_oldtable_malloced; + setentry small_copy[PySet_MINSIZE]; + + assert(minused >= 0); + + /* Find the smallest table size > minused. */ + for (newsize = PySet_MINSIZE; + newsize <= minused && newsize > 0; + newsize <<= 1) + ; + if (newsize <= 0) { + PyErr_NoMemory(); + return -1; + } + + /* Get space for a new table. */ + oldtable = so->table; + assert(oldtable != NULL); + is_oldtable_malloced = oldtable != so->smalltable; + + if (newsize == PySet_MINSIZE) { + /* A large table is shrinking, or we can't get any smaller. */ + newtable = so->smalltable; + if (newtable == oldtable) { + if (so->fill == so->used) { + /* No dummies, so no point doing anything. */ + return 0; + } + /* We're not going to resize it, but rebuild the + table anyway to purge old dummy entries. + Subtle: This is *necessary* if fill==size, + as set_lookkey needs at least one virgin slot to + terminate failing searches. If fill < size, it's + merely desirable, as dummies slow searches. */ + assert(so->fill > so->used); + memcpy(small_copy, oldtable, sizeof(small_copy)); + oldtable = small_copy; + } + } + else { + newtable = PyMem_NEW(setentry, newsize); + if (newtable == NULL) { + PyErr_NoMemory(); + return -1; + } + } + + /* Make the set empty, using the new table. */ + assert(newtable != oldtable); + so->table = newtable; + so->mask = newsize - 1; + memset(newtable, 0, sizeof(setentry) * newsize); + so->used = 0; + i = so->fill; + so->fill = 0; + + /* Copy the data over; this is refcount-neutral for active entries; + dummy entries aren't copied over, of course */ + for (entry = oldtable; i > 0; entry++) { + if (entry->key == NULL) { + /* UNUSED */ + ; + } else if (entry->key == dummy) { + /* DUMMY */ + --i; + assert(entry->key == dummy); + Py_DECREF(entry->key); + } else { + /* ACTIVE */ + --i; + set_insert_clean(so, entry->key, entry->hash); + } + } + + if (is_oldtable_malloced) + PyMem_DEL(oldtable); + return 0; } /* CAUTION: set_add_key/entry() must guarantee it won't resize the table */ @@ -363,42 +363,42 @@ static int set_add_entry(register PySetObject *so, setentry *entry) { - register Py_ssize_t n_used; + register Py_ssize_t n_used; - assert(so->fill <= so->mask); /* at least one empty slot */ - n_used = so->used; - Py_INCREF(entry->key); - if (set_insert_key(so, entry->key, entry->hash) == -1) { - Py_DECREF(entry->key); - return -1; - } - if (!(so->used > n_used && so->fill*3 >= (so->mask+1)*2)) - return 0; - return set_table_resize(so, so->used>50000 ? so->used*2 : so->used*4); + assert(so->fill <= so->mask); /* at least one empty slot */ + n_used = so->used; + Py_INCREF(entry->key); + if (set_insert_key(so, entry->key, entry->hash) == -1) { + Py_DECREF(entry->key); + return -1; + } + if (!(so->used > n_used && so->fill*3 >= (so->mask+1)*2)) + return 0; + return set_table_resize(so, so->used>50000 ? so->used*2 : so->used*4); } static int set_add_key(register PySetObject *so, PyObject *key) { - register long hash; - register Py_ssize_t n_used; + register long hash; + register Py_ssize_t n_used; - if (!PyUnicode_CheckExact(key) || - (hash = ((PyUnicodeObject *) key)->hash) == -1) { - hash = PyObject_Hash(key); - if (hash == -1) - return -1; - } - assert(so->fill <= so->mask); /* at least one empty slot */ - n_used = so->used; - Py_INCREF(key); - if (set_insert_key(so, key, hash) == -1) { - Py_DECREF(key); - return -1; - } - if (!(so->used > n_used && so->fill*3 >= (so->mask+1)*2)) - return 0; - return set_table_resize(so, so->used>50000 ? so->used*2 : so->used*4); + if (!PyUnicode_CheckExact(key) || + (hash = ((PyUnicodeObject *) key)->hash) == -1) { + hash = PyObject_Hash(key); + if (hash == -1) + return -1; + } + assert(so->fill <= so->mask); /* at least one empty slot */ + n_used = so->used; + Py_INCREF(key); + if (set_insert_key(so, key, hash) == -1) { + Py_DECREF(key); + return -1; + } + if (!(so->used > n_used && so->fill*3 >= (so->mask+1)*2)) + return 0; + return set_table_resize(so, so->used>50000 ? so->used*2 : so->used*4); } #define DISCARD_NOTFOUND 0 @@ -406,112 +406,112 @@ static int set_discard_entry(PySetObject *so, setentry *oldentry) -{ register setentry *entry; - PyObject *old_key; +{ register setentry *entry; + PyObject *old_key; - entry = (so->lookup)(so, oldentry->key, oldentry->hash); - if (entry == NULL) - return -1; - if (entry->key == NULL || entry->key == dummy) - return DISCARD_NOTFOUND; - old_key = entry->key; - Py_INCREF(dummy); - entry->key = dummy; - so->used--; - Py_DECREF(old_key); - return DISCARD_FOUND; + entry = (so->lookup)(so, oldentry->key, oldentry->hash); + if (entry == NULL) + return -1; + if (entry->key == NULL || entry->key == dummy) + return DISCARD_NOTFOUND; + old_key = entry->key; + Py_INCREF(dummy); + entry->key = dummy; + so->used--; + Py_DECREF(old_key); + return DISCARD_FOUND; } static int set_discard_key(PySetObject *so, PyObject *key) { - register long hash; - register setentry *entry; - PyObject *old_key; - - assert (PyAnySet_Check(so)); - - if (!PyUnicode_CheckExact(key) || - (hash = ((PyUnicodeObject *) key)->hash) == -1) { - hash = PyObject_Hash(key); - if (hash == -1) - return -1; - } - entry = (so->lookup)(so, key, hash); - if (entry == NULL) - return -1; - if (entry->key == NULL || entry->key == dummy) - return DISCARD_NOTFOUND; - old_key = entry->key; - Py_INCREF(dummy); - entry->key = dummy; - so->used--; - Py_DECREF(old_key); - return DISCARD_FOUND; + register long hash; + register setentry *entry; + PyObject *old_key; + + assert (PyAnySet_Check(so)); + + if (!PyUnicode_CheckExact(key) || + (hash = ((PyUnicodeObject *) key)->hash) == -1) { + hash = PyObject_Hash(key); + if (hash == -1) + return -1; + } + entry = (so->lookup)(so, key, hash); + if (entry == NULL) + return -1; + if (entry->key == NULL || entry->key == dummy) + return DISCARD_NOTFOUND; + old_key = entry->key; + Py_INCREF(dummy); + entry->key = dummy; + so->used--; + Py_DECREF(old_key); + return DISCARD_FOUND; } static int set_clear_internal(PySetObject *so) { - setentry *entry, *table; - int table_is_malloced; - Py_ssize_t fill; - setentry small_copy[PySet_MINSIZE]; + setentry *entry, *table; + int table_is_malloced; + Py_ssize_t fill; + setentry small_copy[PySet_MINSIZE]; #ifdef Py_DEBUG - Py_ssize_t i, n; - assert (PyAnySet_Check(so)); + Py_ssize_t i, n; + assert (PyAnySet_Check(so)); - n = so->mask + 1; - i = 0; + n = so->mask + 1; + i = 0; #endif - table = so->table; - assert(table != NULL); - table_is_malloced = table != so->smalltable; - - /* This is delicate. During the process of clearing the set, - * decrefs can cause the set to mutate. To avoid fatal confusion - * (voice of experience), we have to make the set empty before - * clearing the slots, and never refer to anything via so->ref while - * clearing. - */ - fill = so->fill; - if (table_is_malloced) - EMPTY_TO_MINSIZE(so); - - else if (fill > 0) { - /* It's a small table with something that needs to be cleared. - * Afraid the only safe way is to copy the set entries into - * another small table first. - */ - memcpy(small_copy, table, sizeof(small_copy)); - table = small_copy; - EMPTY_TO_MINSIZE(so); - } - /* else it's a small table that's already empty */ - - /* Now we can finally clear things. If C had refcounts, we could - * assert that the refcount on table is 1 now, i.e. that this function - * has unique access to it, so decref side-effects can't alter it. - */ - for (entry = table; fill > 0; ++entry) { + table = so->table; + assert(table != NULL); + table_is_malloced = table != so->smalltable; + + /* This is delicate. During the process of clearing the set, + * decrefs can cause the set to mutate. To avoid fatal confusion + * (voice of experience), we have to make the set empty before + * clearing the slots, and never refer to anything via so->ref while + * clearing. + */ + fill = so->fill; + if (table_is_malloced) + EMPTY_TO_MINSIZE(so); + + else if (fill > 0) { + /* It's a small table with something that needs to be cleared. + * Afraid the only safe way is to copy the set entries into + * another small table first. + */ + memcpy(small_copy, table, sizeof(small_copy)); + table = small_copy; + EMPTY_TO_MINSIZE(so); + } + /* else it's a small table that's already empty */ + + /* Now we can finally clear things. If C had refcounts, we could + * assert that the refcount on table is 1 now, i.e. that this function + * has unique access to it, so decref side-effects can't alter it. + */ + for (entry = table; fill > 0; ++entry) { #ifdef Py_DEBUG - assert(i < n); - ++i; + assert(i < n); + ++i; #endif - if (entry->key) { - --fill; - Py_DECREF(entry->key); - } + if (entry->key) { + --fill; + Py_DECREF(entry->key); + } #ifdef Py_DEBUG - else - assert(entry->key == NULL); + else + assert(entry->key == NULL); #endif - } + } - if (table_is_malloced) - PyMem_DEL(table); - return 0; + if (table_is_malloced) + PyMem_DEL(table); + return 0; } /* @@ -525,223 +525,223 @@ * } * * CAUTION: In general, it isn't safe to use set_next in a loop that - * mutates the table. + * mutates the table. */ static int set_next(PySetObject *so, Py_ssize_t *pos_ptr, setentry **entry_ptr) { - Py_ssize_t i; - Py_ssize_t mask; - register setentry *table; - - assert (PyAnySet_Check(so)); - i = *pos_ptr; - assert(i >= 0); - table = so->table; - mask = so->mask; - while (i <= mask && (table[i].key == NULL || table[i].key == dummy)) - i++; - *pos_ptr = i+1; - if (i > mask) - return 0; - assert(table[i].key != NULL); - *entry_ptr = &table[i]; - return 1; + Py_ssize_t i; + Py_ssize_t mask; + register setentry *table; + + assert (PyAnySet_Check(so)); + i = *pos_ptr; + assert(i >= 0); + table = so->table; + mask = so->mask; + while (i <= mask && (table[i].key == NULL || table[i].key == dummy)) + i++; + *pos_ptr = i+1; + if (i > mask) + return 0; + assert(table[i].key != NULL); + *entry_ptr = &table[i]; + return 1; } static void set_dealloc(PySetObject *so) { - register setentry *entry; - Py_ssize_t fill = so->fill; - PyObject_GC_UnTrack(so); - Py_TRASHCAN_SAFE_BEGIN(so) - if (so->weakreflist != NULL) - PyObject_ClearWeakRefs((PyObject *) so); - - for (entry = so->table; fill > 0; entry++) { - if (entry->key) { - --fill; - Py_DECREF(entry->key); - } - } - if (so->table != so->smalltable) - PyMem_DEL(so->table); - if (numfree < PySet_MAXFREELIST && PyAnySet_CheckExact(so)) - free_list[numfree++] = so; - else - Py_TYPE(so)->tp_free(so); - Py_TRASHCAN_SAFE_END(so) + register setentry *entry; + Py_ssize_t fill = so->fill; + PyObject_GC_UnTrack(so); + Py_TRASHCAN_SAFE_BEGIN(so) + if (so->weakreflist != NULL) + PyObject_ClearWeakRefs((PyObject *) so); + + for (entry = so->table; fill > 0; entry++) { + if (entry->key) { + --fill; + Py_DECREF(entry->key); + } + } + if (so->table != so->smalltable) + PyMem_DEL(so->table); + if (numfree < PySet_MAXFREELIST && PyAnySet_CheckExact(so)) + free_list[numfree++] = so; + else + Py_TYPE(so)->tp_free(so); + Py_TRASHCAN_SAFE_END(so) } static PyObject * set_repr(PySetObject *so) { - PyObject *keys, *result=NULL; - Py_UNICODE *u; - int status = Py_ReprEnter((PyObject*)so); - PyObject *listrepr; - Py_ssize_t newsize; - - if (status != 0) { - if (status < 0) - return NULL; - return PyUnicode_FromFormat("%s(...)", Py_TYPE(so)->tp_name); - } - - /* shortcut for the empty set */ - if (!so->used) { - Py_ReprLeave((PyObject*)so); - return PyUnicode_FromFormat("%s()", Py_TYPE(so)->tp_name); - } - - keys = PySequence_List((PyObject *)so); - if (keys == NULL) - goto done; - - listrepr = PyObject_Repr(keys); - Py_DECREF(keys); - if (listrepr == NULL) - goto done; - newsize = PyUnicode_GET_SIZE(listrepr); - result = PyUnicode_FromUnicode(NULL, newsize); - if (result) { - u = PyUnicode_AS_UNICODE(result); - *u++ = '{'; - /* Omit the brackets from the listrepr */ - Py_UNICODE_COPY(u, PyUnicode_AS_UNICODE(listrepr)+1, - PyUnicode_GET_SIZE(listrepr)-2); - u += newsize-2; - *u++ = '}'; - } - Py_DECREF(listrepr); - if (Py_TYPE(so) != &PySet_Type) { - PyObject *tmp = PyUnicode_FromFormat("%s(%U)", - Py_TYPE(so)->tp_name, - result); - Py_DECREF(result); - result = tmp; - } + PyObject *keys, *result=NULL; + Py_UNICODE *u; + int status = Py_ReprEnter((PyObject*)so); + PyObject *listrepr; + Py_ssize_t newsize; + + if (status != 0) { + if (status < 0) + return NULL; + return PyUnicode_FromFormat("%s(...)", Py_TYPE(so)->tp_name); + } + + /* shortcut for the empty set */ + if (!so->used) { + Py_ReprLeave((PyObject*)so); + return PyUnicode_FromFormat("%s()", Py_TYPE(so)->tp_name); + } + + keys = PySequence_List((PyObject *)so); + if (keys == NULL) + goto done; + + listrepr = PyObject_Repr(keys); + Py_DECREF(keys); + if (listrepr == NULL) + goto done; + newsize = PyUnicode_GET_SIZE(listrepr); + result = PyUnicode_FromUnicode(NULL, newsize); + if (result) { + u = PyUnicode_AS_UNICODE(result); + *u++ = '{'; + /* Omit the brackets from the listrepr */ + Py_UNICODE_COPY(u, PyUnicode_AS_UNICODE(listrepr)+1, + PyUnicode_GET_SIZE(listrepr)-2); + u += newsize-2; + *u++ = '}'; + } + Py_DECREF(listrepr); + if (Py_TYPE(so) != &PySet_Type) { + PyObject *tmp = PyUnicode_FromFormat("%s(%U)", + Py_TYPE(so)->tp_name, + result); + Py_DECREF(result); + result = tmp; + } done: - Py_ReprLeave((PyObject*)so); - return result; + Py_ReprLeave((PyObject*)so); + return result; } static Py_ssize_t set_len(PyObject *so) { - return ((PySetObject *)so)->used; + return ((PySetObject *)so)->used; } static int set_merge(PySetObject *so, PyObject *otherset) { - PySetObject *other; - register Py_ssize_t i; - register setentry *entry; - - assert (PyAnySet_Check(so)); - assert (PyAnySet_Check(otherset)); - - other = (PySetObject*)otherset; - if (other == so || other->used == 0) - /* a.update(a) or a.update({}); nothing to do */ - return 0; - /* Do one big resize at the start, rather than - * incrementally resizing as we insert new keys. Expect - * that there will be no (or few) overlapping keys. - */ - if ((so->fill + other->used)*3 >= (so->mask+1)*2) { - if (set_table_resize(so, (so->used + other->used)*2) != 0) - return -1; - } - for (i = 0; i <= other->mask; i++) { - entry = &other->table[i]; - if (entry->key != NULL && - entry->key != dummy) { - Py_INCREF(entry->key); - if (set_insert_key(so, entry->key, entry->hash) == -1) { - Py_DECREF(entry->key); - return -1; - } - } - } - return 0; + PySetObject *other; + register Py_ssize_t i; + register setentry *entry; + + assert (PyAnySet_Check(so)); + assert (PyAnySet_Check(otherset)); + + other = (PySetObject*)otherset; + if (other == so || other->used == 0) + /* a.update(a) or a.update({}); nothing to do */ + return 0; + /* Do one big resize at the start, rather than + * incrementally resizing as we insert new keys. Expect + * that there will be no (or few) overlapping keys. + */ + if ((so->fill + other->used)*3 >= (so->mask+1)*2) { + if (set_table_resize(so, (so->used + other->used)*2) != 0) + return -1; + } + for (i = 0; i <= other->mask; i++) { + entry = &other->table[i]; + if (entry->key != NULL && + entry->key != dummy) { + Py_INCREF(entry->key); + if (set_insert_key(so, entry->key, entry->hash) == -1) { + Py_DECREF(entry->key); + return -1; + } + } + } + return 0; } static int set_contains_key(PySetObject *so, PyObject *key) { - long hash; - setentry *entry; + long hash; + setentry *entry; - if (!PyUnicode_CheckExact(key) || - (hash = ((PyUnicodeObject *) key)->hash) == -1) { - hash = PyObject_Hash(key); - if (hash == -1) - return -1; - } - entry = (so->lookup)(so, key, hash); - if (entry == NULL) - return -1; - key = entry->key; - return key != NULL && key != dummy; + if (!PyUnicode_CheckExact(key) || + (hash = ((PyUnicodeObject *) key)->hash) == -1) { + hash = PyObject_Hash(key); + if (hash == -1) + return -1; + } + entry = (so->lookup)(so, key, hash); + if (entry == NULL) + return -1; + key = entry->key; + return key != NULL && key != dummy; } static int set_contains_entry(PySetObject *so, setentry *entry) { - PyObject *key; - setentry *lu_entry; + PyObject *key; + setentry *lu_entry; - lu_entry = (so->lookup)(so, entry->key, entry->hash); - if (lu_entry == NULL) - return -1; - key = lu_entry->key; - return key != NULL && key != dummy; + lu_entry = (so->lookup)(so, entry->key, entry->hash); + if (lu_entry == NULL) + return -1; + key = lu_entry->key; + return key != NULL && key != dummy; } static PyObject * set_pop(PySetObject *so) { - register Py_ssize_t i = 0; - register setentry *entry; - PyObject *key; - - assert (PyAnySet_Check(so)); - if (so->used == 0) { - PyErr_SetString(PyExc_KeyError, "pop from an empty set"); - return NULL; - } - - /* Set entry to "the first" unused or dummy set entry. We abuse - * the hash field of slot 0 to hold a search finger: - * If slot 0 has a value, use slot 0. - * Else slot 0 is being used to hold a search finger, - * and we use its hash value as the first index to look. - */ - entry = &so->table[0]; - if (entry->key == NULL || entry->key == dummy) { - i = entry->hash; - /* The hash field may be a real hash value, or it may be a - * legit search finger, or it may be a once-legit search - * finger that's out of bounds now because it wrapped around - * or the table shrunk -- simply make sure it's in bounds now. - */ - if (i > so->mask || i < 1) - i = 1; /* skip slot 0 */ - while ((entry = &so->table[i])->key == NULL || entry->key==dummy) { - i++; - if (i > so->mask) - i = 1; - } - } - key = entry->key; - Py_INCREF(dummy); - entry->key = dummy; - so->used--; - so->table[0].hash = i + 1; /* next place to start */ - return key; + register Py_ssize_t i = 0; + register setentry *entry; + PyObject *key; + + assert (PyAnySet_Check(so)); + if (so->used == 0) { + PyErr_SetString(PyExc_KeyError, "pop from an empty set"); + return NULL; + } + + /* Set entry to "the first" unused or dummy set entry. We abuse + * the hash field of slot 0 to hold a search finger: + * If slot 0 has a value, use slot 0. + * Else slot 0 is being used to hold a search finger, + * and we use its hash value as the first index to look. + */ + entry = &so->table[0]; + if (entry->key == NULL || entry->key == dummy) { + i = entry->hash; + /* The hash field may be a real hash value, or it may be a + * legit search finger, or it may be a once-legit search + * finger that's out of bounds now because it wrapped around + * or the table shrunk -- simply make sure it's in bounds now. + */ + if (i > so->mask || i < 1) + i = 1; /* skip slot 0 */ + while ((entry = &so->table[i])->key == NULL || entry->key==dummy) { + i++; + if (i > so->mask) + i = 1; + } + } + key = entry->key; + Py_INCREF(dummy); + entry->key = dummy; + so->used--; + so->table[0].hash = i + 1; /* next place to start */ + return key; } PyDoc_STRVAR(pop_doc, "Remove and return an arbitrary set element.\n\ @@ -750,289 +750,289 @@ static int set_traverse(PySetObject *so, visitproc visit, void *arg) { - Py_ssize_t pos = 0; - setentry *entry; + Py_ssize_t pos = 0; + setentry *entry; - while (set_next(so, &pos, &entry)) - Py_VISIT(entry->key); - return 0; + while (set_next(so, &pos, &entry)) + Py_VISIT(entry->key); + return 0; } static long frozenset_hash(PyObject *self) { - PySetObject *so = (PySetObject *)self; - long h, hash = 1927868237L; - setentry *entry; - Py_ssize_t pos = 0; - - if (so->hash != -1) - return so->hash; - - hash *= PySet_GET_SIZE(self) + 1; - while (set_next(so, &pos, &entry)) { - /* Work to increase the bit dispersion for closely spaced hash - values. The is important because some use cases have many - combinations of a small number of elements with nearby - hashes so that many distinct combinations collapse to only - a handful of distinct hash values. */ - h = entry->hash; - hash ^= (h ^ (h << 16) ^ 89869747L) * 3644798167u; - } - hash = hash * 69069L + 907133923L; - if (hash == -1) - hash = 590923713L; - so->hash = hash; - return hash; + PySetObject *so = (PySetObject *)self; + long h, hash = 1927868237L; + setentry *entry; + Py_ssize_t pos = 0; + + if (so->hash != -1) + return so->hash; + + hash *= PySet_GET_SIZE(self) + 1; + while (set_next(so, &pos, &entry)) { + /* Work to increase the bit dispersion for closely spaced hash + values. The is important because some use cases have many + combinations of a small number of elements with nearby + hashes so that many distinct combinations collapse to only + a handful of distinct hash values. */ + h = entry->hash; + hash ^= (h ^ (h << 16) ^ 89869747L) * 3644798167u; + } + hash = hash * 69069L + 907133923L; + if (hash == -1) + hash = 590923713L; + so->hash = hash; + return hash; } /***** Set iterator type ***********************************************/ typedef struct { - PyObject_HEAD - PySetObject *si_set; /* Set to NULL when iterator is exhausted */ - Py_ssize_t si_used; - Py_ssize_t si_pos; - Py_ssize_t len; + PyObject_HEAD + PySetObject *si_set; /* Set to NULL when iterator is exhausted */ + Py_ssize_t si_used; + Py_ssize_t si_pos; + Py_ssize_t len; } setiterobject; static void setiter_dealloc(setiterobject *si) { - Py_XDECREF(si->si_set); - PyObject_GC_Del(si); + Py_XDECREF(si->si_set); + PyObject_GC_Del(si); } static int setiter_traverse(setiterobject *si, visitproc visit, void *arg) { - Py_VISIT(si->si_set); - return 0; + Py_VISIT(si->si_set); + return 0; } static PyObject * setiter_len(setiterobject *si) { - Py_ssize_t len = 0; - if (si->si_set != NULL && si->si_used == si->si_set->used) - len = si->len; - return PyLong_FromLong(len); + Py_ssize_t len = 0; + if (si->si_set != NULL && si->si_used == si->si_set->used) + len = si->len; + return PyLong_FromLong(len); } PyDoc_STRVAR(length_hint_doc, "Private method returning an estimate of len(list(it))."); static PyMethodDef setiter_methods[] = { - {"__length_hint__", (PyCFunction)setiter_len, METH_NOARGS, length_hint_doc}, - {NULL, NULL} /* sentinel */ + {"__length_hint__", (PyCFunction)setiter_len, METH_NOARGS, length_hint_doc}, + {NULL, NULL} /* sentinel */ }; static PyObject *setiter_iternext(setiterobject *si) { - PyObject *key; - register Py_ssize_t i, mask; - register setentry *entry; - PySetObject *so = si->si_set; - - if (so == NULL) - return NULL; - assert (PyAnySet_Check(so)); - - if (si->si_used != so->used) { - PyErr_SetString(PyExc_RuntimeError, - "Set changed size during iteration"); - si->si_used = -1; /* Make this state sticky */ - return NULL; - } - - i = si->si_pos; - assert(i>=0); - entry = so->table; - mask = so->mask; - while (i <= mask && (entry[i].key == NULL || entry[i].key == dummy)) - i++; - si->si_pos = i+1; - if (i > mask) - goto fail; - si->len--; - key = entry[i].key; - Py_INCREF(key); - return key; + PyObject *key; + register Py_ssize_t i, mask; + register setentry *entry; + PySetObject *so = si->si_set; + + if (so == NULL) + return NULL; + assert (PyAnySet_Check(so)); + + if (si->si_used != so->used) { + PyErr_SetString(PyExc_RuntimeError, + "Set changed size during iteration"); + si->si_used = -1; /* Make this state sticky */ + return NULL; + } + + i = si->si_pos; + assert(i>=0); + entry = so->table; + mask = so->mask; + while (i <= mask && (entry[i].key == NULL || entry[i].key == dummy)) + i++; + si->si_pos = i+1; + if (i > mask) + goto fail; + si->len--; + key = entry[i].key; + Py_INCREF(key); + return key; fail: - Py_DECREF(so); - si->si_set = NULL; - return NULL; + Py_DECREF(so); + si->si_set = NULL; + return NULL; } PyTypeObject PySetIter_Type = { - PyVarObject_HEAD_INIT(&PyType_Type, 0) - "set_iterator", /* tp_name */ - sizeof(setiterobject), /* tp_basicsize */ - 0, /* tp_itemsize */ - /* methods */ - (destructor)setiter_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)setiter_traverse, /* tp_traverse */ - 0, /* tp_clear */ - 0, /* tp_richcompare */ - 0, /* tp_weaklistoffset */ - PyObject_SelfIter, /* tp_iter */ - (iternextfunc)setiter_iternext, /* tp_iternext */ - setiter_methods, /* tp_methods */ - 0, + PyVarObject_HEAD_INIT(&PyType_Type, 0) + "set_iterator", /* tp_name */ + sizeof(setiterobject), /* tp_basicsize */ + 0, /* tp_itemsize */ + /* methods */ + (destructor)setiter_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)setiter_traverse, /* tp_traverse */ + 0, /* tp_clear */ + 0, /* tp_richcompare */ + 0, /* tp_weaklistoffset */ + PyObject_SelfIter, /* tp_iter */ + (iternextfunc)setiter_iternext, /* tp_iternext */ + setiter_methods, /* tp_methods */ + 0, }; static PyObject * set_iter(PySetObject *so) { - setiterobject *si = PyObject_GC_New(setiterobject, &PySetIter_Type); - if (si == NULL) - return NULL; - Py_INCREF(so); - si->si_set = so; - si->si_used = so->used; - si->si_pos = 0; - si->len = so->used; - _PyObject_GC_TRACK(si); - return (PyObject *)si; + setiterobject *si = PyObject_GC_New(setiterobject, &PySetIter_Type); + if (si == NULL) + return NULL; + Py_INCREF(so); + si->si_set = so; + si->si_used = so->used; + si->si_pos = 0; + si->len = so->used; + _PyObject_GC_TRACK(si); + return (PyObject *)si; } static int set_update_internal(PySetObject *so, PyObject *other) { - PyObject *key, *it; + PyObject *key, *it; - if (PyAnySet_Check(other)) - return set_merge(so, other); + if (PyAnySet_Check(other)) + return set_merge(so, other); - if (PyDict_CheckExact(other)) { - PyObject *value; - Py_ssize_t pos = 0; - long hash; - Py_ssize_t dictsize = PyDict_Size(other); - - /* Do one big resize at the start, rather than - * incrementally resizing as we insert new keys. Expect - * that there will be no (or few) overlapping keys. - */ - if (dictsize == -1) - return -1; - if ((so->fill + dictsize)*3 >= (so->mask+1)*2) { - if (set_table_resize(so, (so->used + dictsize)*2) != 0) - return -1; - } - while (_PyDict_Next(other, &pos, &key, &value, &hash)) { - setentry an_entry; - - an_entry.hash = hash; - an_entry.key = key; - if (set_add_entry(so, &an_entry) == -1) - return -1; - } - return 0; - } - - it = PyObject_GetIter(other); - if (it == NULL) - return -1; - - while ((key = PyIter_Next(it)) != NULL) { - if (set_add_key(so, key) == -1) { - Py_DECREF(it); - Py_DECREF(key); - return -1; - } - Py_DECREF(key); - } - Py_DECREF(it); - if (PyErr_Occurred()) - return -1; - return 0; + if (PyDict_CheckExact(other)) { + PyObject *value; + Py_ssize_t pos = 0; + long hash; + Py_ssize_t dictsize = PyDict_Size(other); + + /* Do one big resize at the start, rather than + * incrementally resizing as we insert new keys. Expect + * that there will be no (or few) overlapping keys. + */ + if (dictsize == -1) + return -1; + if ((so->fill + dictsize)*3 >= (so->mask+1)*2) { + if (set_table_resize(so, (so->used + dictsize)*2) != 0) + return -1; + } + while (_PyDict_Next(other, &pos, &key, &value, &hash)) { + setentry an_entry; + + an_entry.hash = hash; + an_entry.key = key; + if (set_add_entry(so, &an_entry) == -1) + return -1; + } + return 0; + } + + it = PyObject_GetIter(other); + if (it == NULL) + return -1; + + while ((key = PyIter_Next(it)) != NULL) { + if (set_add_key(so, key) == -1) { + Py_DECREF(it); + Py_DECREF(key); + return -1; + } + Py_DECREF(key); + } + Py_DECREF(it); + if (PyErr_Occurred()) + return -1; + return 0; } static PyObject * set_update(PySetObject *so, PyObject *args) { - Py_ssize_t i; + Py_ssize_t i; - for (i=0 ; i"); - if (dummy == NULL) - return NULL; - } - - /* create PySetObject structure */ - if (numfree && - (type == &PySet_Type || type == &PyFrozenSet_Type)) { - so = free_list[--numfree]; - assert (so != NULL && PyAnySet_CheckExact(so)); - Py_TYPE(so) = type; - _Py_NewReference((PyObject *)so); - EMPTY_TO_MINSIZE(so); - PyObject_GC_Track(so); - } else { - so = (PySetObject *)type->tp_alloc(type, 0); - if (so == NULL) - return NULL; - /* tp_alloc has already zeroed the structure */ - assert(so->table == NULL && so->fill == 0 && so->used == 0); - INIT_NONZERO_SET_SLOTS(so); - } - - so->lookup = set_lookkey_unicode; - so->weakreflist = NULL; - - if (iterable != NULL) { - if (set_update_internal(so, iterable) == -1) { - Py_DECREF(so); - return NULL; - } - } + if (dummy == NULL) { /* Auto-initialize dummy */ + dummy = PyUnicode_FromString(""); + if (dummy == NULL) + return NULL; + } + + /* create PySetObject structure */ + if (numfree && + (type == &PySet_Type || type == &PyFrozenSet_Type)) { + so = free_list[--numfree]; + assert (so != NULL && PyAnySet_CheckExact(so)); + Py_TYPE(so) = type; + _Py_NewReference((PyObject *)so); + EMPTY_TO_MINSIZE(so); + PyObject_GC_Track(so); + } else { + so = (PySetObject *)type->tp_alloc(type, 0); + if (so == NULL) + return NULL; + /* tp_alloc has already zeroed the structure */ + assert(so->table == NULL && so->fill == 0 && so->used == 0); + INIT_NONZERO_SET_SLOTS(so); + } + + so->lookup = set_lookkey_unicode; + so->weakreflist = NULL; + + if (iterable != NULL) { + if (set_update_internal(so, iterable) == -1) { + Py_DECREF(so); + return NULL; + } + } - return (PyObject *)so; + return (PyObject *)so; } static PyObject * make_new_set_basetype(PyTypeObject *type, PyObject *iterable) { - if (type != &PySet_Type && type != &PyFrozenSet_Type) { - if (PyType_IsSubtype(type, &PySet_Type)) - type = &PySet_Type; - else - type = &PyFrozenSet_Type; - } - return make_new_set(type, iterable); + if (type != &PySet_Type && type != &PyFrozenSet_Type) { + if (PyType_IsSubtype(type, &PySet_Type)) + type = &PySet_Type; + else + type = &PyFrozenSet_Type; + } + return make_new_set(type, iterable); } /* The empty frozenset is a singleton */ @@ -1041,56 +1041,56 @@ static PyObject * frozenset_new(PyTypeObject *type, PyObject *args, PyObject *kwds) { - PyObject *iterable = NULL, *result; + PyObject *iterable = NULL, *result; - if (type == &PyFrozenSet_Type && !_PyArg_NoKeywords("frozenset()", kwds)) - return NULL; + if (type == &PyFrozenSet_Type && !_PyArg_NoKeywords("frozenset()", kwds)) + return NULL; - if (!PyArg_UnpackTuple(args, type->tp_name, 0, 1, &iterable)) - return NULL; + if (!PyArg_UnpackTuple(args, type->tp_name, 0, 1, &iterable)) + return NULL; - if (type != &PyFrozenSet_Type) - return make_new_set(type, iterable); - - if (iterable != NULL) { - /* frozenset(f) is idempotent */ - if (PyFrozenSet_CheckExact(iterable)) { - Py_INCREF(iterable); - return iterable; - } - result = make_new_set(type, iterable); - if (result == NULL || PySet_GET_SIZE(result)) - return result; - Py_DECREF(result); - } - /* The empty frozenset is a singleton */ - if (emptyfrozenset == NULL) - emptyfrozenset = make_new_set(type, NULL); - Py_XINCREF(emptyfrozenset); - return emptyfrozenset; + if (type != &PyFrozenSet_Type) + return make_new_set(type, iterable); + + if (iterable != NULL) { + /* frozenset(f) is idempotent */ + if (PyFrozenSet_CheckExact(iterable)) { + Py_INCREF(iterable); + return iterable; + } + result = make_new_set(type, iterable); + if (result == NULL || PySet_GET_SIZE(result)) + return result; + Py_DECREF(result); + } + /* The empty frozenset is a singleton */ + if (emptyfrozenset == NULL) + emptyfrozenset = make_new_set(type, NULL); + Py_XINCREF(emptyfrozenset); + return emptyfrozenset; } void PySet_Fini(void) { - PySetObject *so; + PySetObject *so; - while (numfree) { - numfree--; - so = free_list[numfree]; - PyObject_GC_Del(so); - } - Py_CLEAR(dummy); - Py_CLEAR(emptyfrozenset); + while (numfree) { + numfree--; + so = free_list[numfree]; + PyObject_GC_Del(so); + } + Py_CLEAR(dummy); + Py_CLEAR(emptyfrozenset); } static PyObject * set_new(PyTypeObject *type, PyObject *args, PyObject *kwds) { - if (type == &PySet_Type && !_PyArg_NoKeywords("set()", kwds)) - return NULL; - - return make_new_set(type, NULL); + if (type == &PySet_Type && !_PyArg_NoKeywords("set()", kwds)) + return NULL; + + return make_new_set(type, NULL); } /* set_swap_bodies() switches the contents of any two sets by moving their @@ -1100,64 +1100,64 @@ t=set(a); a.clear(); a.update(b); b.clear(); b.update(t); del t The function always succeeds and it leaves both objects in a stable state. - Useful for creating temporary frozensets from sets for membership testing + Useful for creating temporary frozensets from sets for membership testing in __contains__(), discard(), and remove(). Also useful for operations - that update in-place (by allowing an intermediate result to be swapped + that update in-place (by allowing an intermediate result to be swapped into one of the original inputs). */ static void set_swap_bodies(PySetObject *a, PySetObject *b) { - Py_ssize_t t; - setentry *u; - setentry *(*f)(PySetObject *so, PyObject *key, long hash); - setentry tab[PySet_MINSIZE]; - long h; - - t = a->fill; a->fill = b->fill; b->fill = t; - t = a->used; a->used = b->used; b->used = t; - t = a->mask; a->mask = b->mask; b->mask = t; - - u = a->table; - if (a->table == a->smalltable) - u = b->smalltable; - a->table = b->table; - if (b->table == b->smalltable) - a->table = a->smalltable; - b->table = u; - - f = a->lookup; a->lookup = b->lookup; b->lookup = f; - - if (a->table == a->smalltable || b->table == b->smalltable) { - memcpy(tab, a->smalltable, sizeof(tab)); - memcpy(a->smalltable, b->smalltable, sizeof(tab)); - memcpy(b->smalltable, tab, sizeof(tab)); - } - - if (PyType_IsSubtype(Py_TYPE(a), &PyFrozenSet_Type) && - PyType_IsSubtype(Py_TYPE(b), &PyFrozenSet_Type)) { - h = a->hash; a->hash = b->hash; b->hash = h; - } else { - a->hash = -1; - b->hash = -1; - } + Py_ssize_t t; + setentry *u; + setentry *(*f)(PySetObject *so, PyObject *key, long hash); + setentry tab[PySet_MINSIZE]; + long h; + + t = a->fill; a->fill = b->fill; b->fill = t; + t = a->used; a->used = b->used; b->used = t; + t = a->mask; a->mask = b->mask; b->mask = t; + + u = a->table; + if (a->table == a->smalltable) + u = b->smalltable; + a->table = b->table; + if (b->table == b->smalltable) + a->table = a->smalltable; + b->table = u; + + f = a->lookup; a->lookup = b->lookup; b->lookup = f; + + if (a->table == a->smalltable || b->table == b->smalltable) { + memcpy(tab, a->smalltable, sizeof(tab)); + memcpy(a->smalltable, b->smalltable, sizeof(tab)); + memcpy(b->smalltable, tab, sizeof(tab)); + } + + if (PyType_IsSubtype(Py_TYPE(a), &PyFrozenSet_Type) && + PyType_IsSubtype(Py_TYPE(b), &PyFrozenSet_Type)) { + h = a->hash; a->hash = b->hash; b->hash = h; + } else { + a->hash = -1; + b->hash = -1; + } } static PyObject * set_copy(PySetObject *so) { - return make_new_set_basetype(Py_TYPE(so), (PyObject *)so); + return make_new_set_basetype(Py_TYPE(so), (PyObject *)so); } static PyObject * frozenset_copy(PySetObject *so) { - if (PyFrozenSet_CheckExact(so)) { - Py_INCREF(so); - return (PyObject *)so; - } - return set_copy(so); + if (PyFrozenSet_CheckExact(so)) { + Py_INCREF(so); + return (PyObject *)so; + } + return set_copy(so); } PyDoc_STRVAR(copy_doc, "Return a shallow copy of a set."); @@ -1165,8 +1165,8 @@ static PyObject * set_clear(PySetObject *so) { - set_clear_internal(so); - Py_RETURN_NONE; + set_clear_internal(so); + Py_RETURN_NONE; } PyDoc_STRVAR(clear_doc, "Remove all elements from this set."); @@ -1174,24 +1174,24 @@ static PyObject * set_union(PySetObject *so, PyObject *args) { - PySetObject *result; - PyObject *other; - Py_ssize_t i; - - result = (PySetObject *)set_copy(so); - if (result == NULL) - return NULL; - - for (i=0 ; i PySet_GET_SIZE(so)) { - tmp = (PyObject *)so; - so = (PySetObject *)other; - other = tmp; - } - - while (set_next((PySetObject *)other, &pos, &entry)) { - int rv = set_contains_entry(so, entry); - if (rv == -1) { - Py_DECREF(result); - return NULL; - } - if (rv) { - if (set_add_entry(result, entry) == -1) { - Py_DECREF(result); - return NULL; - } - } - } - return (PyObject *)result; - } - - it = PyObject_GetIter(other); - if (it == NULL) { - Py_DECREF(result); - return NULL; - } - - while ((key = PyIter_Next(it)) != NULL) { - int rv; - setentry entry; - long hash = PyObject_Hash(key); - - if (hash == -1) { - Py_DECREF(it); - Py_DECREF(result); - Py_DECREF(key); - return NULL; - } - entry.hash = hash; - entry.key = key; - rv = set_contains_entry(so, &entry); - if (rv == -1) { - Py_DECREF(it); - Py_DECREF(result); - Py_DECREF(key); - return NULL; - } - if (rv) { - if (set_add_entry(result, &entry) == -1) { - Py_DECREF(it); - Py_DECREF(result); - Py_DECREF(key); - return NULL; - } - } - Py_DECREF(key); - } - Py_DECREF(it); - if (PyErr_Occurred()) { - Py_DECREF(result); - return NULL; - } - return (PyObject *)result; + result = (PySetObject *)make_new_set_basetype(Py_TYPE(so), NULL); + if (result == NULL) + return NULL; + + if (PyAnySet_Check(other)) { + Py_ssize_t pos = 0; + setentry *entry; + + if (PySet_GET_SIZE(other) > PySet_GET_SIZE(so)) { + tmp = (PyObject *)so; + so = (PySetObject *)other; + other = tmp; + } + + while (set_next((PySetObject *)other, &pos, &entry)) { + int rv = set_contains_entry(so, entry); + if (rv == -1) { + Py_DECREF(result); + return NULL; + } + if (rv) { + if (set_add_entry(result, entry) == -1) { + Py_DECREF(result); + return NULL; + } + } + } + return (PyObject *)result; + } + + it = PyObject_GetIter(other); + if (it == NULL) { + Py_DECREF(result); + return NULL; + } + + while ((key = PyIter_Next(it)) != NULL) { + int rv; + setentry entry; + long hash = PyObject_Hash(key); + + if (hash == -1) { + Py_DECREF(it); + Py_DECREF(result); + Py_DECREF(key); + return NULL; + } + entry.hash = hash; + entry.key = key; + rv = set_contains_entry(so, &entry); + if (rv == -1) { + Py_DECREF(it); + Py_DECREF(result); + Py_DECREF(key); + return NULL; + } + if (rv) { + if (set_add_entry(result, &entry) == -1) { + Py_DECREF(it); + Py_DECREF(result); + Py_DECREF(key); + return NULL; + } + } + Py_DECREF(key); + } + Py_DECREF(it); + if (PyErr_Occurred()) { + Py_DECREF(result); + return NULL; + } + return (PyObject *)result; } static PyObject * set_intersection_multi(PySetObject *so, PyObject *args) { - Py_ssize_t i; - PyObject *result = (PyObject *)so; + Py_ssize_t i; + PyObject *result = (PyObject *)so; - if (PyTuple_GET_SIZE(args) == 0) - return set_copy(so); + if (PyTuple_GET_SIZE(args) == 0) + return set_copy(so); - Py_INCREF(so); - for (i=0 ; i PySet_GET_SIZE(so)) { - tmp = (PyObject *)so; - so = (PySetObject *)other; - other = tmp; - } - while (set_next((PySetObject *)other, &pos, &entry)) { - int rv = set_contains_entry(so, entry); - if (rv == -1) - return NULL; - if (rv) - Py_RETURN_FALSE; - } - Py_RETURN_TRUE; - } - - it = PyObject_GetIter(other); - if (it == NULL) - return NULL; - - while ((key = PyIter_Next(it)) != NULL) { - int rv; - setentry entry; - long hash = PyObject_Hash(key);; - - if (hash == -1) { - Py_DECREF(key); - Py_DECREF(it); - return NULL; - } - entry.hash = hash; - entry.key = key; - rv = set_contains_entry(so, &entry); - Py_DECREF(key); - if (rv == -1) { - Py_DECREF(it); - return NULL; - } - if (rv) { - Py_DECREF(it); - Py_RETURN_FALSE; - } - } - Py_DECREF(it); - if (PyErr_Occurred()) - return NULL; - Py_RETURN_TRUE; + if ((PyObject *)so == other) { + if (PySet_GET_SIZE(so) == 0) + Py_RETURN_TRUE; + else + Py_RETURN_FALSE; + } + + if (PyAnySet_CheckExact(other)) { + Py_ssize_t pos = 0; + setentry *entry; + + if (PySet_GET_SIZE(other) > PySet_GET_SIZE(so)) { + tmp = (PyObject *)so; + so = (PySetObject *)other; + other = tmp; + } + while (set_next((PySetObject *)other, &pos, &entry)) { + int rv = set_contains_entry(so, entry); + if (rv == -1) + return NULL; + if (rv) + Py_RETURN_FALSE; + } + Py_RETURN_TRUE; + } + + it = PyObject_GetIter(other); + if (it == NULL) + return NULL; + + while ((key = PyIter_Next(it)) != NULL) { + int rv; + setentry entry; + long hash = PyObject_Hash(key);; + + if (hash == -1) { + Py_DECREF(key); + Py_DECREF(it); + return NULL; + } + entry.hash = hash; + entry.key = key; + rv = set_contains_entry(so, &entry); + Py_DECREF(key); + if (rv == -1) { + Py_DECREF(it); + return NULL; + } + if (rv) { + Py_DECREF(it); + Py_RETURN_FALSE; + } + } + Py_DECREF(it); + if (PyErr_Occurred()) + return NULL; + Py_RETURN_TRUE; } PyDoc_STRVAR(isdisjoint_doc, @@ -1471,51 +1471,51 @@ static int set_difference_update_internal(PySetObject *so, PyObject *other) { - if ((PyObject *)so == other) - return set_clear_internal(so); - - if (PyAnySet_Check(other)) { - setentry *entry; - Py_ssize_t pos = 0; - - while (set_next((PySetObject *)other, &pos, &entry)) - if (set_discard_entry(so, entry) == -1) - return -1; - } else { - PyObject *key, *it; - it = PyObject_GetIter(other); - if (it == NULL) - return -1; - - while ((key = PyIter_Next(it)) != NULL) { - if (set_discard_key(so, key) == -1) { - Py_DECREF(it); - Py_DECREF(key); - return -1; - } - Py_DECREF(key); - } - Py_DECREF(it); - if (PyErr_Occurred()) - return -1; - } - /* If more than 1/5 are dummies, then resize them away. */ - if ((so->fill - so->used) * 5 < so->mask) - return 0; - return set_table_resize(so, so->used>50000 ? so->used*2 : so->used*4); + if ((PyObject *)so == other) + return set_clear_internal(so); + + if (PyAnySet_Check(other)) { + setentry *entry; + Py_ssize_t pos = 0; + + while (set_next((PySetObject *)other, &pos, &entry)) + if (set_discard_entry(so, entry) == -1) + return -1; + } else { + PyObject *key, *it; + it = PyObject_GetIter(other); + if (it == NULL) + return -1; + + while ((key = PyIter_Next(it)) != NULL) { + if (set_discard_key(so, key) == -1) { + Py_DECREF(it); + Py_DECREF(key); + return -1; + } + Py_DECREF(key); + } + Py_DECREF(it); + if (PyErr_Occurred()) + return -1; + } + /* If more than 1/5 are dummies, then resize them away. */ + if ((so->fill - so->used) * 5 < so->mask) + return 0; + return set_table_resize(so, so->used>50000 ? so->used*2 : so->used*4); } static PyObject * set_difference_update(PySetObject *so, PyObject *args) { - Py_ssize_t i; + Py_ssize_t i; - for (i=0 ; ihash; - entrycopy.key = entry->key; - if (!_PyDict_Contains(other, entry->key, entry->hash)) { - if (set_add_entry((PySetObject *)result, &entrycopy) == -1) { - Py_DECREF(result); - return NULL; - } - } - } - return result; - } - - while (set_next(so, &pos, &entry)) { - int rv = set_contains_entry((PySetObject *)other, entry); - if (rv == -1) { - Py_DECREF(result); - return NULL; - } - if (!rv) { - if (set_add_entry((PySetObject *)result, entry) == -1) { - Py_DECREF(result); - return NULL; - } - } - } - return result; + PyObject *result; + setentry *entry; + Py_ssize_t pos = 0; + + if (!PyAnySet_Check(other) && !PyDict_CheckExact(other)) { + result = set_copy(so); + if (result == NULL) + return NULL; + if (set_difference_update_internal((PySetObject *)result, other) != -1) + return result; + Py_DECREF(result); + return NULL; + } + + result = make_new_set_basetype(Py_TYPE(so), NULL); + if (result == NULL) + return NULL; + + if (PyDict_CheckExact(other)) { + while (set_next(so, &pos, &entry)) { + setentry entrycopy; + entrycopy.hash = entry->hash; + entrycopy.key = entry->key; + if (!_PyDict_Contains(other, entry->key, entry->hash)) { + if (set_add_entry((PySetObject *)result, &entrycopy) == -1) { + Py_DECREF(result); + return NULL; + } + } + } + return result; + } + + while (set_next(so, &pos, &entry)) { + int rv = set_contains_entry((PySetObject *)other, entry); + if (rv == -1) { + Py_DECREF(result); + return NULL; + } + if (!rv) { + if (set_add_entry((PySetObject *)result, entry) == -1) { + Py_DECREF(result); + return NULL; + } + } + } + return result; } static PyObject * set_difference_multi(PySetObject *so, PyObject *args) { - Py_ssize_t i; - PyObject *result, *other; + Py_ssize_t i; + PyObject *result, *other; - if (PyTuple_GET_SIZE(args) == 0) - return set_copy(so); + if (PyTuple_GET_SIZE(args) == 0) + return set_copy(so); - other = PyTuple_GET_ITEM(args, 0); - result = set_difference(so, other); - if (result == NULL) - return NULL; - - for (i=1 ; i PySet_GET_SIZE(other)) - Py_RETURN_FALSE; - - while (set_next(so, &pos, &entry)) { - int rv = set_contains_entry((PySetObject *)other, entry); - if (rv == -1) - return NULL; - if (!rv) - Py_RETURN_FALSE; - } - Py_RETURN_TRUE; + if (!PyAnySet_Check(other)) { + PyObject *tmp, *result; + tmp = make_new_set(&PySet_Type, other); + if (tmp == NULL) + return NULL; + result = set_issubset(so, tmp); + Py_DECREF(tmp); + return result; + } + if (PySet_GET_SIZE(so) > PySet_GET_SIZE(other)) + Py_RETURN_FALSE; + + while (set_next(so, &pos, &entry)) { + int rv = set_contains_entry((PySetObject *)other, entry); + if (rv == -1) + return NULL; + if (!rv) + Py_RETURN_FALSE; + } + Py_RETURN_TRUE; } PyDoc_STRVAR(issubset_doc, "Report whether another set contains this set."); @@ -1765,17 +1765,17 @@ static PyObject * set_issuperset(PySetObject *so, PyObject *other) { - PyObject *tmp, *result; + PyObject *tmp, *result; - if (!PyAnySet_Check(other)) { - tmp = make_new_set(&PySet_Type, other); - if (tmp == NULL) - return NULL; - result = set_issuperset(so, tmp); - Py_DECREF(tmp); - return result; - } - return set_issubset((PySetObject *)other, (PyObject *)so); + if (!PyAnySet_Check(other)) { + tmp = make_new_set(&PySet_Type, other); + if (tmp == NULL) + return NULL; + result = set_issuperset(so, tmp); + Py_DECREF(tmp); + return result; + } + return set_issubset((PySetObject *)other, (PyObject *)so); } PyDoc_STRVAR(issuperset_doc, "Report whether this set contains another set."); @@ -1783,54 +1783,54 @@ static PyObject * set_richcompare(PySetObject *v, PyObject *w, int op) { - PyObject *r1, *r2; + PyObject *r1, *r2; - if(!PyAnySet_Check(w)) { - Py_INCREF(Py_NotImplemented); - return Py_NotImplemented; - } - switch (op) { - case Py_EQ: - if (PySet_GET_SIZE(v) != PySet_GET_SIZE(w)) - Py_RETURN_FALSE; - if (v->hash != -1 && - ((PySetObject *)w)->hash != -1 && - v->hash != ((PySetObject *)w)->hash) - Py_RETURN_FALSE; - return set_issubset(v, w); - case Py_NE: - r1 = set_richcompare(v, w, Py_EQ); - if (r1 == NULL) - return NULL; - r2 = PyBool_FromLong(PyObject_Not(r1)); - Py_DECREF(r1); - return r2; - case Py_LE: - return set_issubset(v, w); - case Py_GE: - return set_issuperset(v, w); - case Py_LT: - if (PySet_GET_SIZE(v) >= PySet_GET_SIZE(w)) - Py_RETURN_FALSE; - return set_issubset(v, w); - case Py_GT: - if (PySet_GET_SIZE(v) <= PySet_GET_SIZE(w)) - Py_RETURN_FALSE; - return set_issuperset(v, w); - } - Py_INCREF(Py_NotImplemented); - return Py_NotImplemented; + if(!PyAnySet_Check(w)) { + Py_INCREF(Py_NotImplemented); + return Py_NotImplemented; + } + switch (op) { + case Py_EQ: + if (PySet_GET_SIZE(v) != PySet_GET_SIZE(w)) + Py_RETURN_FALSE; + if (v->hash != -1 && + ((PySetObject *)w)->hash != -1 && + v->hash != ((PySetObject *)w)->hash) + Py_RETURN_FALSE; + return set_issubset(v, w); + case Py_NE: + r1 = set_richcompare(v, w, Py_EQ); + if (r1 == NULL) + return NULL; + r2 = PyBool_FromLong(PyObject_Not(r1)); + Py_DECREF(r1); + return r2; + case Py_LE: + return set_issubset(v, w); + case Py_GE: + return set_issuperset(v, w); + case Py_LT: + if (PySet_GET_SIZE(v) >= PySet_GET_SIZE(w)) + Py_RETURN_FALSE; + return set_issubset(v, w); + case Py_GT: + if (PySet_GET_SIZE(v) <= PySet_GET_SIZE(w)) + Py_RETURN_FALSE; + return set_issuperset(v, w); + } + Py_INCREF(Py_NotImplemented); + return Py_NotImplemented; } static PyObject * set_add(PySetObject *so, PyObject *key) { - if (set_add_key(so, key) == -1) - return NULL; - Py_RETURN_NONE; + if (set_add_key(so, key) == -1) + return NULL; + Py_RETURN_NONE; } -PyDoc_STRVAR(add_doc, +PyDoc_STRVAR(add_doc, "Add an element to a set.\n\ \n\ This has no effect if the element is already present."); @@ -1838,34 +1838,34 @@ static int set_contains(PySetObject *so, PyObject *key) { - PyObject *tmpkey; - int rv; + PyObject *tmpkey; + int rv; - rv = set_contains_key(so, key); - if (rv == -1) { - if (!PySet_Check(key) || !PyErr_ExceptionMatches(PyExc_TypeError)) - return -1; - PyErr_Clear(); - tmpkey = make_new_set(&PyFrozenSet_Type, NULL); - if (tmpkey == NULL) - return -1; - set_swap_bodies((PySetObject *)tmpkey, (PySetObject *)key); - rv = set_contains(so, tmpkey); - set_swap_bodies((PySetObject *)tmpkey, (PySetObject *)key); - Py_DECREF(tmpkey); - } - return rv; + rv = set_contains_key(so, key); + if (rv == -1) { + if (!PySet_Check(key) || !PyErr_ExceptionMatches(PyExc_TypeError)) + return -1; + PyErr_Clear(); + tmpkey = make_new_set(&PyFrozenSet_Type, NULL); + if (tmpkey == NULL) + return -1; + set_swap_bodies((PySetObject *)tmpkey, (PySetObject *)key); + rv = set_contains(so, tmpkey); + set_swap_bodies((PySetObject *)tmpkey, (PySetObject *)key); + Py_DECREF(tmpkey); + } + return rv; } static PyObject * set_direct_contains(PySetObject *so, PyObject *key) { - long result; + long result; - result = set_contains(so, key); - if (result == -1) - return NULL; - return PyBool_FromLong(result); + result = set_contains(so, key); + if (result == -1) + return NULL; + return PyBool_FromLong(result); } PyDoc_STRVAR(contains_doc, "x.__contains__(y) <==> y in x."); @@ -1873,30 +1873,30 @@ static PyObject * set_remove(PySetObject *so, PyObject *key) { - PyObject *tmpkey; - int rv; + PyObject *tmpkey; + int rv; - rv = set_discard_key(so, key); - if (rv == -1) { - if (!PySet_Check(key) || !PyErr_ExceptionMatches(PyExc_TypeError)) - return NULL; - PyErr_Clear(); - tmpkey = make_new_set(&PyFrozenSet_Type, NULL); - if (tmpkey == NULL) - return NULL; - set_swap_bodies((PySetObject *)tmpkey, (PySetObject *)key); - rv = set_discard_key(so, tmpkey); - set_swap_bodies((PySetObject *)tmpkey, (PySetObject *)key); - Py_DECREF(tmpkey); - if (rv == -1) - return NULL; - } - - if (rv == DISCARD_NOTFOUND) { - set_key_error(key); - return NULL; - } - Py_RETURN_NONE; + rv = set_discard_key(so, key); + if (rv == -1) { + if (!PySet_Check(key) || !PyErr_ExceptionMatches(PyExc_TypeError)) + return NULL; + PyErr_Clear(); + tmpkey = make_new_set(&PyFrozenSet_Type, NULL); + if (tmpkey == NULL) + return NULL; + set_swap_bodies((PySetObject *)tmpkey, (PySetObject *)key); + rv = set_discard_key(so, tmpkey); + set_swap_bodies((PySetObject *)tmpkey, (PySetObject *)key); + Py_DECREF(tmpkey); + if (rv == -1) + return NULL; + } + + if (rv == DISCARD_NOTFOUND) { + set_key_error(key); + return NULL; + } + Py_RETURN_NONE; } PyDoc_STRVAR(remove_doc, @@ -1907,54 +1907,54 @@ static PyObject * set_discard(PySetObject *so, PyObject *key) { - PyObject *tmpkey, *result; - int rv; + PyObject *tmpkey, *result; + int rv; - rv = set_discard_key(so, key); - if (rv == -1) { - if (!PySet_Check(key) || !PyErr_ExceptionMatches(PyExc_TypeError)) - return NULL; - PyErr_Clear(); - tmpkey = make_new_set(&PyFrozenSet_Type, NULL); - if (tmpkey == NULL) - return NULL; - set_swap_bodies((PySetObject *)tmpkey, (PySetObject *)key); - result = set_discard(so, tmpkey); - set_swap_bodies((PySetObject *)tmpkey, (PySetObject *)key); - Py_DECREF(tmpkey); - return result; - } - Py_RETURN_NONE; + rv = set_discard_key(so, key); + if (rv == -1) { + if (!PySet_Check(key) || !PyErr_ExceptionMatches(PyExc_TypeError)) + return NULL; + PyErr_Clear(); + tmpkey = make_new_set(&PyFrozenSet_Type, NULL); + if (tmpkey == NULL) + return NULL; + set_swap_bodies((PySetObject *)tmpkey, (PySetObject *)key); + result = set_discard(so, tmpkey); + set_swap_bodies((PySetObject *)tmpkey, (PySetObject *)key); + Py_DECREF(tmpkey); + return result; + } + Py_RETURN_NONE; } PyDoc_STRVAR(discard_doc, "Remove an element from a set if it is a member.\n\ \n\ -If the element is not a member, do nothing."); +If the element is not a member, do nothing."); static PyObject * set_reduce(PySetObject *so) { - PyObject *keys=NULL, *args=NULL, *result=NULL, *dict=NULL; + PyObject *keys=NULL, *args=NULL, *result=NULL, *dict=NULL; - keys = PySequence_List((PyObject *)so); - if (keys == NULL) - goto done; - args = PyTuple_Pack(1, keys); - if (args == NULL) - goto done; - dict = PyObject_GetAttrString((PyObject *)so, "__dict__"); - if (dict == NULL) { - PyErr_Clear(); - dict = Py_None; - Py_INCREF(dict); - } - result = PyTuple_Pack(3, Py_TYPE(so), args, dict); + keys = PySequence_List((PyObject *)so); + if (keys == NULL) + goto done; + args = PyTuple_Pack(1, keys); + if (args == NULL) + goto done; + dict = PyObject_GetAttrString((PyObject *)so, "__dict__"); + if (dict == NULL) { + PyErr_Clear(); + dict = Py_None; + Py_INCREF(dict); + } + result = PyTuple_Pack(3, Py_TYPE(so), args, dict); done: - Py_XDECREF(args); - Py_XDECREF(keys); - Py_XDECREF(dict); - return result; + Py_XDECREF(args); + Py_XDECREF(keys); + Py_XDECREF(dict); + return result; } PyDoc_STRVAR(reduce_doc, "Return state information for pickling."); @@ -1962,42 +1962,42 @@ static PyObject * set_sizeof(PySetObject *so) { - Py_ssize_t res; + Py_ssize_t res; - res = sizeof(PySetObject); - if (so->table != so->smalltable) - res = res + (so->mask + 1) * sizeof(setentry); - return PyLong_FromSsize_t(res); + res = sizeof(PySetObject); + if (so->table != so->smalltable) + res = res + (so->mask + 1) * sizeof(setentry); + return PyLong_FromSsize_t(res); } PyDoc_STRVAR(sizeof_doc, "S.__sizeof__() -> size of S in memory, in bytes"); static int set_init(PySetObject *self, PyObject *args, PyObject *kwds) { - PyObject *iterable = NULL; + PyObject *iterable = NULL; - if (!PyAnySet_Check(self)) - return -1; - if (PySet_Check(self) && !_PyArg_NoKeywords("set()", kwds)) - return -1; - if (!PyArg_UnpackTuple(args, Py_TYPE(self)->tp_name, 0, 1, &iterable)) - return -1; - set_clear_internal(self); - self->hash = -1; - if (iterable == NULL) - return 0; - return set_update_internal(self, iterable); + if (!PyAnySet_Check(self)) + return -1; + if (PySet_Check(self) && !_PyArg_NoKeywords("set()", kwds)) + return -1; + if (!PyArg_UnpackTuple(args, Py_TYPE(self)->tp_name, 0, 1, &iterable)) + return -1; + set_clear_internal(self); + self->hash = -1; + if (iterable == NULL) + return 0; + return set_update_internal(self, iterable); } static PySequenceMethods set_as_sequence = { - set_len, /* sq_length */ - 0, /* sq_concat */ - 0, /* sq_repeat */ - 0, /* sq_item */ - 0, /* sq_slice */ - 0, /* sq_ass_item */ - 0, /* sq_ass_slice */ - (objobjproc)set_contains, /* sq_contains */ + set_len, /* sq_length */ + 0, /* sq_concat */ + 0, /* sq_repeat */ + 0, /* sq_item */ + 0, /* sq_slice */ + 0, /* sq_ass_item */ + 0, /* sq_ass_slice */ + (objobjproc)set_contains, /* sq_contains */ }; /* set object ********************************************************/ @@ -2010,83 +2010,83 @@ #endif static PyMethodDef set_methods[] = { - {"add", (PyCFunction)set_add, METH_O, - add_doc}, - {"clear", (PyCFunction)set_clear, METH_NOARGS, - clear_doc}, - {"__contains__",(PyCFunction)set_direct_contains, METH_O | METH_COEXIST, - contains_doc}, - {"copy", (PyCFunction)set_copy, METH_NOARGS, - copy_doc}, - {"discard", (PyCFunction)set_discard, METH_O, - discard_doc}, - {"difference", (PyCFunction)set_difference_multi, METH_VARARGS, - difference_doc}, - {"difference_update", (PyCFunction)set_difference_update, METH_VARARGS, - difference_update_doc}, - {"intersection",(PyCFunction)set_intersection_multi, METH_VARARGS, - intersection_doc}, - {"intersection_update",(PyCFunction)set_intersection_update_multi, METH_VARARGS, - intersection_update_doc}, - {"isdisjoint", (PyCFunction)set_isdisjoint, METH_O, - isdisjoint_doc}, - {"issubset", (PyCFunction)set_issubset, METH_O, - issubset_doc}, - {"issuperset", (PyCFunction)set_issuperset, METH_O, - issuperset_doc}, - {"pop", (PyCFunction)set_pop, METH_NOARGS, - pop_doc}, - {"__reduce__", (PyCFunction)set_reduce, METH_NOARGS, - reduce_doc}, - {"remove", (PyCFunction)set_remove, METH_O, - remove_doc}, - {"__sizeof__", (PyCFunction)set_sizeof, METH_NOARGS, - sizeof_doc}, - {"symmetric_difference",(PyCFunction)set_symmetric_difference, METH_O, - symmetric_difference_doc}, - {"symmetric_difference_update",(PyCFunction)set_symmetric_difference_update, METH_O, - symmetric_difference_update_doc}, + {"add", (PyCFunction)set_add, METH_O, + add_doc}, + {"clear", (PyCFunction)set_clear, METH_NOARGS, + clear_doc}, + {"__contains__",(PyCFunction)set_direct_contains, METH_O | METH_COEXIST, + contains_doc}, + {"copy", (PyCFunction)set_copy, METH_NOARGS, + copy_doc}, + {"discard", (PyCFunction)set_discard, METH_O, + discard_doc}, + {"difference", (PyCFunction)set_difference_multi, METH_VARARGS, + difference_doc}, + {"difference_update", (PyCFunction)set_difference_update, METH_VARARGS, + difference_update_doc}, + {"intersection",(PyCFunction)set_intersection_multi, METH_VARARGS, + intersection_doc}, + {"intersection_update",(PyCFunction)set_intersection_update_multi, METH_VARARGS, + intersection_update_doc}, + {"isdisjoint", (PyCFunction)set_isdisjoint, METH_O, + isdisjoint_doc}, + {"issubset", (PyCFunction)set_issubset, METH_O, + issubset_doc}, + {"issuperset", (PyCFunction)set_issuperset, METH_O, + issuperset_doc}, + {"pop", (PyCFunction)set_pop, METH_NOARGS, + pop_doc}, + {"__reduce__", (PyCFunction)set_reduce, METH_NOARGS, + reduce_doc}, + {"remove", (PyCFunction)set_remove, METH_O, + remove_doc}, + {"__sizeof__", (PyCFunction)set_sizeof, METH_NOARGS, + sizeof_doc}, + {"symmetric_difference",(PyCFunction)set_symmetric_difference, METH_O, + symmetric_difference_doc}, + {"symmetric_difference_update",(PyCFunction)set_symmetric_difference_update, METH_O, + symmetric_difference_update_doc}, #ifdef Py_DEBUG - {"test_c_api", (PyCFunction)test_c_api, METH_NOARGS, - test_c_api_doc}, + {"test_c_api", (PyCFunction)test_c_api, METH_NOARGS, + test_c_api_doc}, #endif - {"union", (PyCFunction)set_union, METH_VARARGS, - union_doc}, - {"update", (PyCFunction)set_update, METH_VARARGS, - update_doc}, - {NULL, NULL} /* sentinel */ + {"union", (PyCFunction)set_union, METH_VARARGS, + union_doc}, + {"update", (PyCFunction)set_update, METH_VARARGS, + update_doc}, + {NULL, NULL} /* sentinel */ }; static PyNumberMethods set_as_number = { - 0, /*nb_add*/ - (binaryfunc)set_sub, /*nb_subtract*/ - 0, /*nb_multiply*/ - 0, /*nb_remainder*/ - 0, /*nb_divmod*/ - 0, /*nb_power*/ - 0, /*nb_negative*/ - 0, /*nb_positive*/ - 0, /*nb_absolute*/ - 0, /*nb_bool*/ - 0, /*nb_invert*/ - 0, /*nb_lshift*/ - 0, /*nb_rshift*/ - (binaryfunc)set_and, /*nb_and*/ - (binaryfunc)set_xor, /*nb_xor*/ - (binaryfunc)set_or, /*nb_or*/ - 0, /*nb_int*/ - 0, /*nb_reserved*/ - 0, /*nb_float*/ - 0, /*nb_inplace_add*/ - (binaryfunc)set_isub, /*nb_inplace_subtract*/ - 0, /*nb_inplace_multiply*/ - 0, /*nb_inplace_remainder*/ - 0, /*nb_inplace_power*/ - 0, /*nb_inplace_lshift*/ - 0, /*nb_inplace_rshift*/ - (binaryfunc)set_iand, /*nb_inplace_and*/ - (binaryfunc)set_ixor, /*nb_inplace_xor*/ - (binaryfunc)set_ior, /*nb_inplace_or*/ + 0, /*nb_add*/ + (binaryfunc)set_sub, /*nb_subtract*/ + 0, /*nb_multiply*/ + 0, /*nb_remainder*/ + 0, /*nb_divmod*/ + 0, /*nb_power*/ + 0, /*nb_negative*/ + 0, /*nb_positive*/ + 0, /*nb_absolute*/ + 0, /*nb_bool*/ + 0, /*nb_invert*/ + 0, /*nb_lshift*/ + 0, /*nb_rshift*/ + (binaryfunc)set_and, /*nb_and*/ + (binaryfunc)set_xor, /*nb_xor*/ + (binaryfunc)set_or, /*nb_or*/ + 0, /*nb_int*/ + 0, /*nb_reserved*/ + 0, /*nb_float*/ + 0, /*nb_inplace_add*/ + (binaryfunc)set_isub, /*nb_inplace_subtract*/ + 0, /*nb_inplace_multiply*/ + 0, /*nb_inplace_remainder*/ + 0, /*nb_inplace_power*/ + 0, /*nb_inplace_lshift*/ + 0, /*nb_inplace_rshift*/ + (binaryfunc)set_iand, /*nb_inplace_and*/ + (binaryfunc)set_ixor, /*nb_inplace_xor*/ + (binaryfunc)set_ior, /*nb_inplace_or*/ }; PyDoc_STRVAR(set_doc, @@ -2096,95 +2096,95 @@ Build an unordered collection of unique elements."); PyTypeObject PySet_Type = { - PyVarObject_HEAD_INIT(&PyType_Type, 0) - "set", /* tp_name */ - sizeof(PySetObject), /* tp_basicsize */ - 0, /* tp_itemsize */ - /* methods */ - (destructor)set_dealloc, /* tp_dealloc */ - 0, /* tp_print */ - 0, /* tp_getattr */ - 0, /* tp_setattr */ - 0, /* tp_reserved */ - (reprfunc)set_repr, /* tp_repr */ - &set_as_number, /* tp_as_number */ - &set_as_sequence, /* tp_as_sequence */ - 0, /* tp_as_mapping */ - (hashfunc)PyObject_HashNotImplemented, /* 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 | - Py_TPFLAGS_BASETYPE, /* tp_flags */ - set_doc, /* tp_doc */ - (traverseproc)set_traverse, /* tp_traverse */ - (inquiry)set_clear_internal, /* tp_clear */ - (richcmpfunc)set_richcompare, /* tp_richcompare */ - offsetof(PySetObject, weakreflist), /* tp_weaklistoffset */ - (getiterfunc)set_iter, /* tp_iter */ - 0, /* tp_iternext */ - set_methods, /* tp_methods */ - 0, /* tp_members */ - 0, /* tp_getset */ - 0, /* tp_base */ - 0, /* tp_dict */ - 0, /* tp_descr_get */ - 0, /* tp_descr_set */ - 0, /* tp_dictoffset */ - (initproc)set_init, /* tp_init */ - PyType_GenericAlloc, /* tp_alloc */ - set_new, /* tp_new */ - PyObject_GC_Del, /* tp_free */ + PyVarObject_HEAD_INIT(&PyType_Type, 0) + "set", /* tp_name */ + sizeof(PySetObject), /* tp_basicsize */ + 0, /* tp_itemsize */ + /* methods */ + (destructor)set_dealloc, /* tp_dealloc */ + 0, /* tp_print */ + 0, /* tp_getattr */ + 0, /* tp_setattr */ + 0, /* tp_reserved */ + (reprfunc)set_repr, /* tp_repr */ + &set_as_number, /* tp_as_number */ + &set_as_sequence, /* tp_as_sequence */ + 0, /* tp_as_mapping */ + (hashfunc)PyObject_HashNotImplemented, /* 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 | + Py_TPFLAGS_BASETYPE, /* tp_flags */ + set_doc, /* tp_doc */ + (traverseproc)set_traverse, /* tp_traverse */ + (inquiry)set_clear_internal, /* tp_clear */ + (richcmpfunc)set_richcompare, /* tp_richcompare */ + offsetof(PySetObject, weakreflist), /* tp_weaklistoffset */ + (getiterfunc)set_iter, /* tp_iter */ + 0, /* tp_iternext */ + set_methods, /* tp_methods */ + 0, /* tp_members */ + 0, /* tp_getset */ + 0, /* tp_base */ + 0, /* tp_dict */ + 0, /* tp_descr_get */ + 0, /* tp_descr_set */ + 0, /* tp_dictoffset */ + (initproc)set_init, /* tp_init */ + PyType_GenericAlloc, /* tp_alloc */ + set_new, /* tp_new */ + PyObject_GC_Del, /* tp_free */ }; /* frozenset object ********************************************************/ static PyMethodDef frozenset_methods[] = { - {"__contains__",(PyCFunction)set_direct_contains, METH_O | METH_COEXIST, - contains_doc}, - {"copy", (PyCFunction)frozenset_copy, METH_NOARGS, - copy_doc}, - {"difference", (PyCFunction)set_difference_multi, METH_VARARGS, - difference_doc}, - {"intersection",(PyCFunction)set_intersection_multi, METH_VARARGS, - intersection_doc}, - {"isdisjoint", (PyCFunction)set_isdisjoint, METH_O, - isdisjoint_doc}, - {"issubset", (PyCFunction)set_issubset, METH_O, - issubset_doc}, - {"issuperset", (PyCFunction)set_issuperset, METH_O, - issuperset_doc}, - {"__reduce__", (PyCFunction)set_reduce, METH_NOARGS, - reduce_doc}, - {"__sizeof__", (PyCFunction)set_sizeof, METH_NOARGS, - sizeof_doc}, - {"symmetric_difference",(PyCFunction)set_symmetric_difference, METH_O, - symmetric_difference_doc}, - {"union", (PyCFunction)set_union, METH_VARARGS, - union_doc}, - {NULL, NULL} /* sentinel */ + {"__contains__",(PyCFunction)set_direct_contains, METH_O | METH_COEXIST, + contains_doc}, + {"copy", (PyCFunction)frozenset_copy, METH_NOARGS, + copy_doc}, + {"difference", (PyCFunction)set_difference_multi, METH_VARARGS, + difference_doc}, + {"intersection",(PyCFunction)set_intersection_multi, METH_VARARGS, + intersection_doc}, + {"isdisjoint", (PyCFunction)set_isdisjoint, METH_O, + isdisjoint_doc}, + {"issubset", (PyCFunction)set_issubset, METH_O, + issubset_doc}, + {"issuperset", (PyCFunction)set_issuperset, METH_O, + issuperset_doc}, + {"__reduce__", (PyCFunction)set_reduce, METH_NOARGS, + reduce_doc}, + {"__sizeof__", (PyCFunction)set_sizeof, METH_NOARGS, + sizeof_doc}, + {"symmetric_difference",(PyCFunction)set_symmetric_difference, METH_O, + symmetric_difference_doc}, + {"union", (PyCFunction)set_union, METH_VARARGS, + union_doc}, + {NULL, NULL} /* sentinel */ }; static PyNumberMethods frozenset_as_number = { - 0, /*nb_add*/ - (binaryfunc)set_sub, /*nb_subtract*/ - 0, /*nb_multiply*/ - 0, /*nb_remainder*/ - 0, /*nb_divmod*/ - 0, /*nb_power*/ - 0, /*nb_negative*/ - 0, /*nb_positive*/ - 0, /*nb_absolute*/ - 0, /*nb_bool*/ - 0, /*nb_invert*/ - 0, /*nb_lshift*/ - 0, /*nb_rshift*/ - (binaryfunc)set_and, /*nb_and*/ - (binaryfunc)set_xor, /*nb_xor*/ - (binaryfunc)set_or, /*nb_or*/ + 0, /*nb_add*/ + (binaryfunc)set_sub, /*nb_subtract*/ + 0, /*nb_multiply*/ + 0, /*nb_remainder*/ + 0, /*nb_divmod*/ + 0, /*nb_power*/ + 0, /*nb_negative*/ + 0, /*nb_positive*/ + 0, /*nb_absolute*/ + 0, /*nb_bool*/ + 0, /*nb_invert*/ + 0, /*nb_lshift*/ + 0, /*nb_rshift*/ + (binaryfunc)set_and, /*nb_and*/ + (binaryfunc)set_xor, /*nb_xor*/ + (binaryfunc)set_or, /*nb_or*/ }; PyDoc_STRVAR(frozenset_doc, @@ -2194,47 +2194,47 @@ Build an immutable unordered collection of unique elements."); PyTypeObject PyFrozenSet_Type = { - PyVarObject_HEAD_INIT(&PyType_Type, 0) - "frozenset", /* tp_name */ - sizeof(PySetObject), /* tp_basicsize */ - 0, /* tp_itemsize */ - /* methods */ - (destructor)set_dealloc, /* tp_dealloc */ - 0, /* tp_print */ - 0, /* tp_getattr */ - 0, /* tp_setattr */ - 0, /* tp_reserved */ - (reprfunc)set_repr, /* tp_repr */ - &frozenset_as_number, /* tp_as_number */ - &set_as_sequence, /* tp_as_sequence */ - 0, /* tp_as_mapping */ - frozenset_hash, /* 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 | - Py_TPFLAGS_BASETYPE, /* tp_flags */ - frozenset_doc, /* tp_doc */ - (traverseproc)set_traverse, /* tp_traverse */ - (inquiry)set_clear_internal, /* tp_clear */ - (richcmpfunc)set_richcompare, /* tp_richcompare */ - offsetof(PySetObject, weakreflist), /* tp_weaklistoffset */ - (getiterfunc)set_iter, /* tp_iter */ - 0, /* tp_iternext */ - frozenset_methods, /* tp_methods */ - 0, /* tp_members */ - 0, /* tp_getset */ - 0, /* tp_base */ - 0, /* tp_dict */ - 0, /* tp_descr_get */ - 0, /* tp_descr_set */ - 0, /* tp_dictoffset */ - 0, /* tp_init */ - PyType_GenericAlloc, /* tp_alloc */ - frozenset_new, /* tp_new */ - PyObject_GC_Del, /* tp_free */ + PyVarObject_HEAD_INIT(&PyType_Type, 0) + "frozenset", /* tp_name */ + sizeof(PySetObject), /* tp_basicsize */ + 0, /* tp_itemsize */ + /* methods */ + (destructor)set_dealloc, /* tp_dealloc */ + 0, /* tp_print */ + 0, /* tp_getattr */ + 0, /* tp_setattr */ + 0, /* tp_reserved */ + (reprfunc)set_repr, /* tp_repr */ + &frozenset_as_number, /* tp_as_number */ + &set_as_sequence, /* tp_as_sequence */ + 0, /* tp_as_mapping */ + frozenset_hash, /* 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 | + Py_TPFLAGS_BASETYPE, /* tp_flags */ + frozenset_doc, /* tp_doc */ + (traverseproc)set_traverse, /* tp_traverse */ + (inquiry)set_clear_internal, /* tp_clear */ + (richcmpfunc)set_richcompare, /* tp_richcompare */ + offsetof(PySetObject, weakreflist), /* tp_weaklistoffset */ + (getiterfunc)set_iter, /* tp_iter */ + 0, /* tp_iternext */ + frozenset_methods, /* tp_methods */ + 0, /* tp_members */ + 0, /* tp_getset */ + 0, /* tp_base */ + 0, /* tp_dict */ + 0, /* tp_descr_get */ + 0, /* tp_descr_set */ + 0, /* tp_dictoffset */ + 0, /* tp_init */ + PyType_GenericAlloc, /* tp_alloc */ + frozenset_new, /* tp_new */ + PyObject_GC_Del, /* tp_free */ }; @@ -2243,224 +2243,224 @@ PyObject * PySet_New(PyObject *iterable) { - return make_new_set(&PySet_Type, iterable); + return make_new_set(&PySet_Type, iterable); } PyObject * PyFrozenSet_New(PyObject *iterable) { - return make_new_set(&PyFrozenSet_Type, iterable); + return make_new_set(&PyFrozenSet_Type, iterable); } Py_ssize_t PySet_Size(PyObject *anyset) { - if (!PyAnySet_Check(anyset)) { - PyErr_BadInternalCall(); - return -1; - } - return PySet_GET_SIZE(anyset); + if (!PyAnySet_Check(anyset)) { + PyErr_BadInternalCall(); + return -1; + } + return PySet_GET_SIZE(anyset); } int PySet_Clear(PyObject *set) { - if (!PySet_Check(set)) { - PyErr_BadInternalCall(); - return -1; - } - return set_clear_internal((PySetObject *)set); + if (!PySet_Check(set)) { + PyErr_BadInternalCall(); + return -1; + } + return set_clear_internal((PySetObject *)set); } int PySet_Contains(PyObject *anyset, PyObject *key) { - if (!PyAnySet_Check(anyset)) { - PyErr_BadInternalCall(); - return -1; - } - return set_contains_key((PySetObject *)anyset, key); + if (!PyAnySet_Check(anyset)) { + PyErr_BadInternalCall(); + return -1; + } + return set_contains_key((PySetObject *)anyset, key); } int PySet_Discard(PyObject *set, PyObject *key) { - if (!PySet_Check(set)) { - PyErr_BadInternalCall(); - return -1; - } - return set_discard_key((PySetObject *)set, key); + if (!PySet_Check(set)) { + PyErr_BadInternalCall(); + return -1; + } + return set_discard_key((PySetObject *)set, key); } int PySet_Add(PyObject *anyset, PyObject *key) { - if (!PySet_Check(anyset) && - (!PyFrozenSet_Check(anyset) || Py_REFCNT(anyset) != 1)) { - PyErr_BadInternalCall(); - return -1; - } - return set_add_key((PySetObject *)anyset, key); + if (!PySet_Check(anyset) && + (!PyFrozenSet_Check(anyset) || Py_REFCNT(anyset) != 1)) { + PyErr_BadInternalCall(); + return -1; + } + return set_add_key((PySetObject *)anyset, key); } int _PySet_NextEntry(PyObject *set, Py_ssize_t *pos, PyObject **key, long *hash) { - setentry *entry; + setentry *entry; - if (!PyAnySet_Check(set)) { - PyErr_BadInternalCall(); - return -1; - } - if (set_next((PySetObject *)set, pos, &entry) == 0) - return 0; - *key = entry->key; - *hash = entry->hash; - return 1; + if (!PyAnySet_Check(set)) { + PyErr_BadInternalCall(); + return -1; + } + if (set_next((PySetObject *)set, pos, &entry) == 0) + return 0; + *key = entry->key; + *hash = entry->hash; + return 1; } PyObject * PySet_Pop(PyObject *set) { - if (!PySet_Check(set)) { - PyErr_BadInternalCall(); - return NULL; - } - return set_pop((PySetObject *)set); + if (!PySet_Check(set)) { + PyErr_BadInternalCall(); + return NULL; + } + return set_pop((PySetObject *)set); } int _PySet_Update(PyObject *set, PyObject *iterable) { - if (!PySet_Check(set)) { - PyErr_BadInternalCall(); - return -1; - } - return set_update_internal((PySetObject *)set, iterable); + if (!PySet_Check(set)) { + PyErr_BadInternalCall(); + return -1; + } + return set_update_internal((PySetObject *)set, iterable); } #ifdef Py_DEBUG -/* Test code to be called with any three element set. +/* Test code to be called with any three element set. Returns True and original set is restored. */ -#define assertRaises(call_return_value, exception) \ - do { \ - assert(call_return_value); \ - assert(PyErr_ExceptionMatches(exception)); \ - PyErr_Clear(); \ - } while(0) +#define assertRaises(call_return_value, exception) \ + do { \ + assert(call_return_value); \ + assert(PyErr_ExceptionMatches(exception)); \ + PyErr_Clear(); \ + } while(0) static PyObject * test_c_api(PySetObject *so) { - Py_ssize_t count; - char *s; - Py_ssize_t i; - PyObject *elem=NULL, *dup=NULL, *t, *f, *dup2, *x; - PyObject *ob = (PyObject *)so; - long hash; - - /* Verify preconditions and exercise type/size checks */ - assert(PyAnySet_Check(ob)); - assert(PyAnySet_CheckExact(ob)); - assert(!PyFrozenSet_CheckExact(ob)); - assert(PySet_Size(ob) == 3); - assert(PySet_GET_SIZE(ob) == 3); - - /* Raise TypeError for non-iterable constructor arguments */ - assertRaises(PySet_New(Py_None) == NULL, PyExc_TypeError); - assertRaises(PyFrozenSet_New(Py_None) == NULL, PyExc_TypeError); - - /* Raise TypeError for unhashable key */ - dup = PySet_New(ob); - assertRaises(PySet_Discard(ob, dup) == -1, PyExc_TypeError); - assertRaises(PySet_Contains(ob, dup) == -1, PyExc_TypeError); - assertRaises(PySet_Add(ob, dup) == -1, PyExc_TypeError); - - /* Exercise successful pop, contains, add, and discard */ - elem = PySet_Pop(ob); - assert(PySet_Contains(ob, elem) == 0); - assert(PySet_GET_SIZE(ob) == 2); - assert(PySet_Add(ob, elem) == 0); - assert(PySet_Contains(ob, elem) == 1); - assert(PySet_GET_SIZE(ob) == 3); - assert(PySet_Discard(ob, elem) == 1); - assert(PySet_GET_SIZE(ob) == 2); - assert(PySet_Discard(ob, elem) == 0); - assert(PySet_GET_SIZE(ob) == 2); - - /* Exercise clear */ - dup2 = PySet_New(dup); - assert(PySet_Clear(dup2) == 0); - assert(PySet_Size(dup2) == 0); - Py_DECREF(dup2); - - /* Raise SystemError on clear or update of frozen set */ - f = PyFrozenSet_New(dup); - assertRaises(PySet_Clear(f) == -1, PyExc_SystemError); - assertRaises(_PySet_Update(f, dup) == -1, PyExc_SystemError); - assert(PySet_Add(f, elem) == 0); - Py_INCREF(f); - assertRaises(PySet_Add(f, elem) == -1, PyExc_SystemError); - Py_DECREF(f); - Py_DECREF(f); - - /* Exercise direct iteration */ - i = 0, count = 0; - while (_PySet_NextEntry((PyObject *)dup, &i, &x, &hash)) { - s = _PyUnicode_AsString(x); - assert(s && (s[0] == 'a' || s[0] == 'b' || s[0] == 'c')); - count++; - } - assert(count == 3); - - /* Exercise updates */ - dup2 = PySet_New(NULL); - assert(_PySet_Update(dup2, dup) == 0); - assert(PySet_Size(dup2) == 3); - assert(_PySet_Update(dup2, dup) == 0); - assert(PySet_Size(dup2) == 3); - Py_DECREF(dup2); - - /* Raise SystemError when self argument is not a set or frozenset. */ - t = PyTuple_New(0); - assertRaises(PySet_Size(t) == -1, PyExc_SystemError); - assertRaises(PySet_Contains(t, elem) == -1, PyExc_SystemError); - Py_DECREF(t); - - /* Raise SystemError when self argument is not a set. */ - f = PyFrozenSet_New(dup); - assert(PySet_Size(f) == 3); - assert(PyFrozenSet_CheckExact(f)); - assertRaises(PySet_Discard(f, elem) == -1, PyExc_SystemError); - assertRaises(PySet_Pop(f) == NULL, PyExc_SystemError); - Py_DECREF(f); - - /* Raise KeyError when popping from an empty set */ - assert(PyNumber_InPlaceSubtract(ob, ob) == ob); - Py_DECREF(ob); - assert(PySet_GET_SIZE(ob) == 0); - assertRaises(PySet_Pop(ob) == NULL, PyExc_KeyError); - - /* Restore the set from the copy using the PyNumber API */ - assert(PyNumber_InPlaceOr(ob, dup) == ob); - Py_DECREF(ob); - - /* Verify constructors accept NULL arguments */ - f = PySet_New(NULL); - assert(f != NULL); - assert(PySet_GET_SIZE(f) == 0); - Py_DECREF(f); - f = PyFrozenSet_New(NULL); - assert(f != NULL); - assert(PyFrozenSet_CheckExact(f)); - assert(PySet_GET_SIZE(f) == 0); - Py_DECREF(f); - - Py_DECREF(elem); - Py_DECREF(dup); - Py_RETURN_TRUE; + Py_ssize_t count; + char *s; + Py_ssize_t i; + PyObject *elem=NULL, *dup=NULL, *t, *f, *dup2, *x; + PyObject *ob = (PyObject *)so; + long hash; + + /* Verify preconditions and exercise type/size checks */ + assert(PyAnySet_Check(ob)); + assert(PyAnySet_CheckExact(ob)); + assert(!PyFrozenSet_CheckExact(ob)); + assert(PySet_Size(ob) == 3); + assert(PySet_GET_SIZE(ob) == 3); + + /* Raise TypeError for non-iterable constructor arguments */ + assertRaises(PySet_New(Py_None) == NULL, PyExc_TypeError); + assertRaises(PyFrozenSet_New(Py_None) == NULL, PyExc_TypeError); + + /* Raise TypeError for unhashable key */ + dup = PySet_New(ob); + assertRaises(PySet_Discard(ob, dup) == -1, PyExc_TypeError); + assertRaises(PySet_Contains(ob, dup) == -1, PyExc_TypeError); + assertRaises(PySet_Add(ob, dup) == -1, PyExc_TypeError); + + /* Exercise successful pop, contains, add, and discard */ + elem = PySet_Pop(ob); + assert(PySet_Contains(ob, elem) == 0); + assert(PySet_GET_SIZE(ob) == 2); + assert(PySet_Add(ob, elem) == 0); + assert(PySet_Contains(ob, elem) == 1); + assert(PySet_GET_SIZE(ob) == 3); + assert(PySet_Discard(ob, elem) == 1); + assert(PySet_GET_SIZE(ob) == 2); + assert(PySet_Discard(ob, elem) == 0); + assert(PySet_GET_SIZE(ob) == 2); + + /* Exercise clear */ + dup2 = PySet_New(dup); + assert(PySet_Clear(dup2) == 0); + assert(PySet_Size(dup2) == 0); + Py_DECREF(dup2); + + /* Raise SystemError on clear or update of frozen set */ + f = PyFrozenSet_New(dup); + assertRaises(PySet_Clear(f) == -1, PyExc_SystemError); + assertRaises(_PySet_Update(f, dup) == -1, PyExc_SystemError); + assert(PySet_Add(f, elem) == 0); + Py_INCREF(f); + assertRaises(PySet_Add(f, elem) == -1, PyExc_SystemError); + Py_DECREF(f); + Py_DECREF(f); + + /* Exercise direct iteration */ + i = 0, count = 0; + while (_PySet_NextEntry((PyObject *)dup, &i, &x, &hash)) { + s = _PyUnicode_AsString(x); + assert(s && (s[0] == 'a' || s[0] == 'b' || s[0] == 'c')); + count++; + } + assert(count == 3); + + /* Exercise updates */ + dup2 = PySet_New(NULL); + assert(_PySet_Update(dup2, dup) == 0); + assert(PySet_Size(dup2) == 3); + assert(_PySet_Update(dup2, dup) == 0); + assert(PySet_Size(dup2) == 3); + Py_DECREF(dup2); + + /* Raise SystemError when self argument is not a set or frozenset. */ + t = PyTuple_New(0); + assertRaises(PySet_Size(t) == -1, PyExc_SystemError); + assertRaises(PySet_Contains(t, elem) == -1, PyExc_SystemError); + Py_DECREF(t); + + /* Raise SystemError when self argument is not a set. */ + f = PyFrozenSet_New(dup); + assert(PySet_Size(f) == 3); + assert(PyFrozenSet_CheckExact(f)); + assertRaises(PySet_Discard(f, elem) == -1, PyExc_SystemError); + assertRaises(PySet_Pop(f) == NULL, PyExc_SystemError); + Py_DECREF(f); + + /* Raise KeyError when popping from an empty set */ + assert(PyNumber_InPlaceSubtract(ob, ob) == ob); + Py_DECREF(ob); + assert(PySet_GET_SIZE(ob) == 0); + assertRaises(PySet_Pop(ob) == NULL, PyExc_KeyError); + + /* Restore the set from the copy using the PyNumber API */ + assert(PyNumber_InPlaceOr(ob, dup) == ob); + Py_DECREF(ob); + + /* Verify constructors accept NULL arguments */ + f = PySet_New(NULL); + assert(f != NULL); + assert(PySet_GET_SIZE(f) == 0); + Py_DECREF(f); + f = PyFrozenSet_New(NULL); + assert(f != NULL); + assert(PyFrozenSet_CheckExact(f)); + assert(PySet_GET_SIZE(f) == 0); + Py_DECREF(f); + + Py_DECREF(elem); + Py_DECREF(dup); + Py_RETURN_TRUE; } #undef assertRaises Modified: python/branches/release31-maint/Objects/sliceobject.c ============================================================================== --- python/branches/release31-maint/Objects/sliceobject.c (original) +++ python/branches/release31-maint/Objects/sliceobject.c Sun May 9 18:14:21 2010 @@ -7,7 +7,7 @@ for this file. */ -/* +/* Py_Ellipsis encodes the '...' rubber index token. It is similar to the Py_NoneStruct in that there is no way to create other objects of this type and there is exactly one in existence. @@ -19,35 +19,35 @@ static PyObject * ellipsis_repr(PyObject *op) { - return PyUnicode_FromString("Ellipsis"); + return PyUnicode_FromString("Ellipsis"); } PyTypeObject PyEllipsis_Type = { - PyVarObject_HEAD_INIT(&PyType_Type, 0) - "ellipsis", /* tp_name */ - 0, /* tp_basicsize */ - 0, /* tp_itemsize */ - 0, /*never called*/ /* tp_dealloc */ - 0, /* tp_print */ - 0, /* tp_getattr */ - 0, /* tp_setattr */ - 0, /* tp_reserved */ - ellipsis_repr, /* tp_repr */ - 0, /* tp_as_number */ - 0, /* tp_as_sequence */ - 0, /* tp_as_mapping */ - 0, /* tp_hash */ - 0, /* tp_call */ - 0, /* tp_str */ - PyObject_GenericGetAttr, /* tp_getattro */ - 0, /* tp_setattro */ - 0, /* tp_as_buffer */ - Py_TPFLAGS_DEFAULT, /* tp_flags */ + PyVarObject_HEAD_INIT(&PyType_Type, 0) + "ellipsis", /* tp_name */ + 0, /* tp_basicsize */ + 0, /* tp_itemsize */ + 0, /*never called*/ /* tp_dealloc */ + 0, /* tp_print */ + 0, /* tp_getattr */ + 0, /* tp_setattr */ + 0, /* tp_reserved */ + ellipsis_repr, /* tp_repr */ + 0, /* tp_as_number */ + 0, /* tp_as_sequence */ + 0, /* tp_as_mapping */ + 0, /* tp_hash */ + 0, /* tp_call */ + 0, /* tp_str */ + PyObject_GenericGetAttr, /* tp_getattro */ + 0, /* tp_setattro */ + 0, /* tp_as_buffer */ + Py_TPFLAGS_DEFAULT, /* tp_flags */ }; PyObject _Py_EllipsisObject = { - _PyObject_EXTRA_INIT - 1, &PyEllipsis_Type + _PyObject_EXTRA_INIT + 1, &PyEllipsis_Type }; @@ -60,154 +60,154 @@ PyObject * PySlice_New(PyObject *start, PyObject *stop, PyObject *step) { - PySliceObject *obj = PyObject_New(PySliceObject, &PySlice_Type); + PySliceObject *obj = PyObject_New(PySliceObject, &PySlice_Type); - if (obj == NULL) - return NULL; + if (obj == NULL) + return NULL; - if (step == NULL) step = Py_None; - Py_INCREF(step); - if (start == NULL) start = Py_None; - Py_INCREF(start); - if (stop == NULL) stop = Py_None; - Py_INCREF(stop); - - obj->step = step; - obj->start = start; - obj->stop = stop; + if (step == NULL) step = Py_None; + Py_INCREF(step); + if (start == NULL) start = Py_None; + Py_INCREF(start); + if (stop == NULL) stop = Py_None; + Py_INCREF(stop); + + obj->step = step; + obj->start = start; + obj->stop = stop; - return (PyObject *) obj; + return (PyObject *) obj; } PyObject * _PySlice_FromIndices(Py_ssize_t istart, Py_ssize_t istop) { - PyObject *start, *end, *slice; - start = PyLong_FromSsize_t(istart); - if (!start) - return NULL; - end = PyLong_FromSsize_t(istop); - if (!end) { - Py_DECREF(start); - return NULL; - } - - slice = PySlice_New(start, end, NULL); - Py_DECREF(start); - Py_DECREF(end); - return slice; + PyObject *start, *end, *slice; + start = PyLong_FromSsize_t(istart); + if (!start) + return NULL; + end = PyLong_FromSsize_t(istop); + if (!end) { + Py_DECREF(start); + return NULL; + } + + slice = PySlice_New(start, end, NULL); + Py_DECREF(start); + Py_DECREF(end); + return slice; } int PySlice_GetIndices(PySliceObject *r, Py_ssize_t length, Py_ssize_t *start, Py_ssize_t *stop, Py_ssize_t *step) { - /* XXX support long ints */ - if (r->step == Py_None) { - *step = 1; - } else { - if (!PyLong_Check(r->step)) return -1; - *step = PyLong_AsSsize_t(r->step); - } - if (r->start == Py_None) { - *start = *step < 0 ? length-1 : 0; - } else { - if (!PyLong_Check(r->start)) return -1; - *start = PyLong_AsSsize_t(r->start); - if (*start < 0) *start += length; - } - if (r->stop == Py_None) { - *stop = *step < 0 ? -1 : length; - } else { - if (!PyLong_Check(r->stop)) return -1; - *stop = PyLong_AsSsize_t(r->stop); - if (*stop < 0) *stop += length; - } - if (*stop > length) return -1; - if (*start >= length) return -1; - if (*step == 0) return -1; - return 0; + /* XXX support long ints */ + if (r->step == Py_None) { + *step = 1; + } else { + if (!PyLong_Check(r->step)) return -1; + *step = PyLong_AsSsize_t(r->step); + } + if (r->start == Py_None) { + *start = *step < 0 ? length-1 : 0; + } else { + if (!PyLong_Check(r->start)) return -1; + *start = PyLong_AsSsize_t(r->start); + if (*start < 0) *start += length; + } + if (r->stop == Py_None) { + *stop = *step < 0 ? -1 : length; + } else { + if (!PyLong_Check(r->stop)) return -1; + *stop = PyLong_AsSsize_t(r->stop); + if (*stop < 0) *stop += length; + } + if (*stop > length) return -1; + if (*start >= length) return -1; + if (*step == 0) return -1; + return 0; } int PySlice_GetIndicesEx(PySliceObject *r, Py_ssize_t length, - Py_ssize_t *start, Py_ssize_t *stop, Py_ssize_t *step, Py_ssize_t *slicelength) + Py_ssize_t *start, Py_ssize_t *stop, Py_ssize_t *step, Py_ssize_t *slicelength) { - /* this is harder to get right than you might think */ + /* this is harder to get right than you might think */ - Py_ssize_t defstart, defstop; + Py_ssize_t defstart, defstop; - if (r->step == Py_None) { - *step = 1; - } - else { - if (!_PyEval_SliceIndex(r->step, step)) return -1; - if (*step == 0) { - PyErr_SetString(PyExc_ValueError, - "slice step cannot be zero"); - return -1; - } - } - - defstart = *step < 0 ? length-1 : 0; - defstop = *step < 0 ? -1 : length; - - if (r->start == Py_None) { - *start = defstart; - } - else { - if (!_PyEval_SliceIndex(r->start, start)) return -1; - if (*start < 0) *start += length; - if (*start < 0) *start = (*step < 0) ? -1 : 0; - if (*start >= length) - *start = (*step < 0) ? length - 1 : length; - } - - if (r->stop == Py_None) { - *stop = defstop; - } - else { - if (!_PyEval_SliceIndex(r->stop, stop)) return -1; - if (*stop < 0) *stop += length; - if (*stop < 0) *stop = (*step < 0) ? -1 : 0; - if (*stop >= length) - *stop = (*step < 0) ? length - 1 : length; - } - - if ((*step < 0 && *stop >= *start) - || (*step > 0 && *start >= *stop)) { - *slicelength = 0; - } - else if (*step < 0) { - *slicelength = (*stop-*start+1)/(*step)+1; - } - else { - *slicelength = (*stop-*start-1)/(*step)+1; - } + if (r->step == Py_None) { + *step = 1; + } + else { + if (!_PyEval_SliceIndex(r->step, step)) return -1; + if (*step == 0) { + PyErr_SetString(PyExc_ValueError, + "slice step cannot be zero"); + return -1; + } + } + + defstart = *step < 0 ? length-1 : 0; + defstop = *step < 0 ? -1 : length; + + if (r->start == Py_None) { + *start = defstart; + } + else { + if (!_PyEval_SliceIndex(r->start, start)) return -1; + if (*start < 0) *start += length; + if (*start < 0) *start = (*step < 0) ? -1 : 0; + if (*start >= length) + *start = (*step < 0) ? length - 1 : length; + } + + if (r->stop == Py_None) { + *stop = defstop; + } + else { + if (!_PyEval_SliceIndex(r->stop, stop)) return -1; + if (*stop < 0) *stop += length; + if (*stop < 0) *stop = (*step < 0) ? -1 : 0; + if (*stop >= length) + *stop = (*step < 0) ? length - 1 : length; + } + + if ((*step < 0 && *stop >= *start) + || (*step > 0 && *start >= *stop)) { + *slicelength = 0; + } + else if (*step < 0) { + *slicelength = (*stop-*start+1)/(*step)+1; + } + else { + *slicelength = (*stop-*start-1)/(*step)+1; + } - return 0; + return 0; } static PyObject * slice_new(PyTypeObject *type, PyObject *args, PyObject *kw) { - PyObject *start, *stop, *step; + PyObject *start, *stop, *step; - start = stop = step = NULL; + start = stop = step = NULL; - if (!_PyArg_NoKeywords("slice()", kw)) - return NULL; + if (!_PyArg_NoKeywords("slice()", kw)) + return NULL; - if (!PyArg_UnpackTuple(args, "slice", 1, 3, &start, &stop, &step)) - return NULL; - - /* This swapping of stop and start is to maintain similarity with - range(). */ - if (stop == NULL) { - stop = start; - start = NULL; - } - return PySlice_New(start, stop, step); + if (!PyArg_UnpackTuple(args, "slice", 1, 3, &start, &stop, &step)) + return NULL; + + /* This swapping of stop and start is to maintain similarity with + range(). */ + if (stop == NULL) { + stop = start; + start = NULL; + } + return PySlice_New(start, stop, step); } PyDoc_STRVAR(slice_doc, @@ -218,42 +218,42 @@ static void slice_dealloc(PySliceObject *r) { - Py_DECREF(r->step); - Py_DECREF(r->start); - Py_DECREF(r->stop); - PyObject_Del(r); + Py_DECREF(r->step); + Py_DECREF(r->start); + Py_DECREF(r->stop); + PyObject_Del(r); } static PyObject * slice_repr(PySliceObject *r) { - return PyUnicode_FromFormat("slice(%R, %R, %R)", r->start, r->stop, r->step); + return PyUnicode_FromFormat("slice(%R, %R, %R)", r->start, r->stop, r->step); } static PyMemberDef slice_members[] = { - {"start", T_OBJECT, offsetof(PySliceObject, start), READONLY}, - {"stop", T_OBJECT, offsetof(PySliceObject, stop), READONLY}, - {"step", T_OBJECT, offsetof(PySliceObject, step), READONLY}, - {0} + {"start", T_OBJECT, offsetof(PySliceObject, start), READONLY}, + {"stop", T_OBJECT, offsetof(PySliceObject, stop), READONLY}, + {"step", T_OBJECT, offsetof(PySliceObject, step), READONLY}, + {0} }; static PyObject* slice_indices(PySliceObject* self, PyObject* len) { - Py_ssize_t ilen, start, stop, step, slicelength; + Py_ssize_t ilen, start, stop, step, slicelength; - ilen = PyNumber_AsSsize_t(len, PyExc_OverflowError); + ilen = PyNumber_AsSsize_t(len, PyExc_OverflowError); - if (ilen == -1 && PyErr_Occurred()) { - return NULL; - } + if (ilen == -1 && PyErr_Occurred()) { + return NULL; + } - if (PySlice_GetIndicesEx(self, ilen, &start, &stop, - &step, &slicelength) < 0) { - return NULL; - } + if (PySlice_GetIndicesEx(self, ilen, &start, &stop, + &step, &slicelength) < 0) { + return NULL; + } - return Py_BuildValue("(nnn)", start, stop, step); + return Py_BuildValue("(nnn)", start, stop, step); } PyDoc_STRVAR(slice_indices_doc, @@ -267,119 +267,119 @@ static PyObject * slice_reduce(PySliceObject* self) { - return Py_BuildValue("O(OOO)", Py_TYPE(self), self->start, self->stop, self->step); + return Py_BuildValue("O(OOO)", Py_TYPE(self), self->start, self->stop, self->step); } PyDoc_STRVAR(reduce_doc, "Return state information for pickling."); static PyMethodDef slice_methods[] = { - {"indices", (PyCFunction)slice_indices, - METH_O, slice_indices_doc}, - {"__reduce__", (PyCFunction)slice_reduce, - METH_NOARGS, reduce_doc}, - {NULL, NULL} + {"indices", (PyCFunction)slice_indices, + METH_O, slice_indices_doc}, + {"__reduce__", (PyCFunction)slice_reduce, + METH_NOARGS, reduce_doc}, + {NULL, NULL} }; static PyObject * slice_richcompare(PyObject *v, PyObject *w, int op) { - PyObject *t1; - PyObject *t2; - PyObject *res; - - if (!PySlice_Check(v) || !PySlice_Check(w)) { - Py_INCREF(Py_NotImplemented); - return Py_NotImplemented; - } - - if (v == w) { - /* XXX Do we really need this shortcut? - There's a unit test for it, but is that fair? */ - switch (op) { - case Py_EQ: - case Py_LE: - case Py_GE: - res = Py_True; - break; - default: - res = Py_False; - break; - } - Py_INCREF(res); - return res; - } - - t1 = PyTuple_New(3); - t2 = PyTuple_New(3); - if (t1 == NULL || t2 == NULL) - return NULL; - - PyTuple_SET_ITEM(t1, 0, ((PySliceObject *)v)->start); - PyTuple_SET_ITEM(t1, 1, ((PySliceObject *)v)->stop); - PyTuple_SET_ITEM(t1, 2, ((PySliceObject *)v)->step); - PyTuple_SET_ITEM(t2, 0, ((PySliceObject *)w)->start); - PyTuple_SET_ITEM(t2, 1, ((PySliceObject *)w)->stop); - PyTuple_SET_ITEM(t2, 2, ((PySliceObject *)w)->step); - - res = PyObject_RichCompare(t1, t2, op); - - PyTuple_SET_ITEM(t1, 0, NULL); - PyTuple_SET_ITEM(t1, 1, NULL); - PyTuple_SET_ITEM(t1, 2, NULL); - PyTuple_SET_ITEM(t2, 0, NULL); - PyTuple_SET_ITEM(t2, 1, NULL); - PyTuple_SET_ITEM(t2, 2, NULL); + PyObject *t1; + PyObject *t2; + PyObject *res; + + if (!PySlice_Check(v) || !PySlice_Check(w)) { + Py_INCREF(Py_NotImplemented); + return Py_NotImplemented; + } + + if (v == w) { + /* XXX Do we really need this shortcut? + There's a unit test for it, but is that fair? */ + switch (op) { + case Py_EQ: + case Py_LE: + case Py_GE: + res = Py_True; + break; + default: + res = Py_False; + break; + } + Py_INCREF(res); + return res; + } + + t1 = PyTuple_New(3); + t2 = PyTuple_New(3); + if (t1 == NULL || t2 == NULL) + return NULL; + + PyTuple_SET_ITEM(t1, 0, ((PySliceObject *)v)->start); + PyTuple_SET_ITEM(t1, 1, ((PySliceObject *)v)->stop); + PyTuple_SET_ITEM(t1, 2, ((PySliceObject *)v)->step); + PyTuple_SET_ITEM(t2, 0, ((PySliceObject *)w)->start); + PyTuple_SET_ITEM(t2, 1, ((PySliceObject *)w)->stop); + PyTuple_SET_ITEM(t2, 2, ((PySliceObject *)w)->step); + + res = PyObject_RichCompare(t1, t2, op); + + PyTuple_SET_ITEM(t1, 0, NULL); + PyTuple_SET_ITEM(t1, 1, NULL); + PyTuple_SET_ITEM(t1, 2, NULL); + PyTuple_SET_ITEM(t2, 0, NULL); + PyTuple_SET_ITEM(t2, 1, NULL); + PyTuple_SET_ITEM(t2, 2, NULL); - Py_DECREF(t1); - Py_DECREF(t2); + Py_DECREF(t1); + Py_DECREF(t2); - return res; + return res; } static long slice_hash(PySliceObject *v) { - PyErr_SetString(PyExc_TypeError, "unhashable type"); - return -1L; + PyErr_SetString(PyExc_TypeError, "unhashable type"); + return -1L; } PyTypeObject PySlice_Type = { - PyVarObject_HEAD_INIT(&PyType_Type, 0) - "slice", /* Name of this type */ - sizeof(PySliceObject), /* Basic object size */ - 0, /* Item size for varobject */ - (destructor)slice_dealloc, /* tp_dealloc */ - 0, /* tp_print */ - 0, /* tp_getattr */ - 0, /* tp_setattr */ - 0, /* tp_reserved */ - (reprfunc)slice_repr, /* tp_repr */ - 0, /* tp_as_number */ - 0, /* tp_as_sequence */ - 0, /* tp_as_mapping */ - (hashfunc)slice_hash, /* tp_hash */ - 0, /* tp_call */ - 0, /* tp_str */ - PyObject_GenericGetAttr, /* tp_getattro */ - 0, /* tp_setattro */ - 0, /* tp_as_buffer */ - Py_TPFLAGS_DEFAULT, /* tp_flags */ - slice_doc, /* tp_doc */ - 0, /* tp_traverse */ - 0, /* tp_clear */ - slice_richcompare, /* tp_richcompare */ - 0, /* tp_weaklistoffset */ - 0, /* tp_iter */ - 0, /* tp_iternext */ - slice_methods, /* tp_methods */ - slice_members, /* tp_members */ - 0, /* tp_getset */ - 0, /* tp_base */ - 0, /* tp_dict */ - 0, /* tp_descr_get */ - 0, /* tp_descr_set */ - 0, /* tp_dictoffset */ - 0, /* tp_init */ - 0, /* tp_alloc */ - slice_new, /* tp_new */ + PyVarObject_HEAD_INIT(&PyType_Type, 0) + "slice", /* Name of this type */ + sizeof(PySliceObject), /* Basic object size */ + 0, /* Item size for varobject */ + (destructor)slice_dealloc, /* tp_dealloc */ + 0, /* tp_print */ + 0, /* tp_getattr */ + 0, /* tp_setattr */ + 0, /* tp_reserved */ + (reprfunc)slice_repr, /* tp_repr */ + 0, /* tp_as_number */ + 0, /* tp_as_sequence */ + 0, /* tp_as_mapping */ + (hashfunc)slice_hash, /* tp_hash */ + 0, /* tp_call */ + 0, /* tp_str */ + PyObject_GenericGetAttr, /* tp_getattro */ + 0, /* tp_setattro */ + 0, /* tp_as_buffer */ + Py_TPFLAGS_DEFAULT, /* tp_flags */ + slice_doc, /* tp_doc */ + 0, /* tp_traverse */ + 0, /* tp_clear */ + slice_richcompare, /* tp_richcompare */ + 0, /* tp_weaklistoffset */ + 0, /* tp_iter */ + 0, /* tp_iternext */ + slice_methods, /* tp_methods */ + slice_members, /* tp_members */ + 0, /* tp_getset */ + 0, /* tp_base */ + 0, /* tp_dict */ + 0, /* tp_descr_get */ + 0, /* tp_descr_set */ + 0, /* tp_dictoffset */ + 0, /* tp_init */ + 0, /* tp_alloc */ + slice_new, /* tp_new */ }; Modified: python/branches/release31-maint/Objects/stringlib/eq.h ============================================================================== --- python/branches/release31-maint/Objects/stringlib/eq.h (original) +++ python/branches/release31-maint/Objects/stringlib/eq.h Sun May 9 18:14:21 2010 @@ -6,16 +6,16 @@ Py_LOCAL_INLINE(int) unicode_eq(PyObject *aa, PyObject *bb) { - register PyUnicodeObject *a = (PyUnicodeObject *)aa; - register PyUnicodeObject *b = (PyUnicodeObject *)bb; + register PyUnicodeObject *a = (PyUnicodeObject *)aa; + register PyUnicodeObject *b = (PyUnicodeObject *)bb; - if (a->length != b->length) - return 0; - if (a->length == 0) - return 1; - if (a->str[0] != b->str[0]) - return 0; - if (a->length == 1) - return 1; - return memcmp(a->str, b->str, a->length * sizeof(Py_UNICODE)) == 0; + if (a->length != b->length) + return 0; + if (a->length == 0) + return 1; + if (a->str[0] != b->str[0]) + return 0; + if (a->length == 1) + return 1; + return memcmp(a->str, b->str, a->length * sizeof(Py_UNICODE)) == 0; } Modified: python/branches/release31-maint/Objects/stringlib/partition.h ============================================================================== --- python/branches/release31-maint/Objects/stringlib/partition.h (original) +++ python/branches/release31-maint/Objects/stringlib/partition.h Sun May 9 18:14:21 2010 @@ -18,23 +18,23 @@ if (sep_len == 0) { PyErr_SetString(PyExc_ValueError, "empty separator"); - return NULL; + return NULL; } out = PyTuple_New(3); if (!out) - return NULL; + return NULL; pos = fastsearch(str, str_len, sep, sep_len, FAST_SEARCH); if (pos < 0) { - Py_INCREF(str_obj); - PyTuple_SET_ITEM(out, 0, (PyObject*) str_obj); - Py_INCREF(STRINGLIB_EMPTY); - PyTuple_SET_ITEM(out, 1, (PyObject*) STRINGLIB_EMPTY); - Py_INCREF(STRINGLIB_EMPTY); - PyTuple_SET_ITEM(out, 2, (PyObject*) STRINGLIB_EMPTY); - return out; + Py_INCREF(str_obj); + PyTuple_SET_ITEM(out, 0, (PyObject*) str_obj); + Py_INCREF(STRINGLIB_EMPTY); + PyTuple_SET_ITEM(out, 1, (PyObject*) STRINGLIB_EMPTY); + Py_INCREF(STRINGLIB_EMPTY); + PyTuple_SET_ITEM(out, 2, (PyObject*) STRINGLIB_EMPTY); + return out; } PyTuple_SET_ITEM(out, 0, STRINGLIB_NEW(str, pos)); @@ -44,8 +44,8 @@ PyTuple_SET_ITEM(out, 2, STRINGLIB_NEW(str + pos, str_len - pos)); if (PyErr_Occurred()) { - Py_DECREF(out); - return NULL; + Py_DECREF(out); + return NULL; } return out; @@ -62,29 +62,29 @@ if (sep_len == 0) { PyErr_SetString(PyExc_ValueError, "empty separator"); - return NULL; + return NULL; } out = PyTuple_New(3); if (!out) - return NULL; + return NULL; /* XXX - create reversefastsearch helper! */ pos = -1; - for (j = str_len - sep_len; j >= 0; --j) + for (j = str_len - sep_len; j >= 0; --j) if (STRINGLIB_CMP(str+j, sep, sep_len) == 0) { pos = j; break; } if (pos < 0) { - Py_INCREF(STRINGLIB_EMPTY); - PyTuple_SET_ITEM(out, 0, (PyObject*) STRINGLIB_EMPTY); - Py_INCREF(STRINGLIB_EMPTY); - PyTuple_SET_ITEM(out, 1, (PyObject*) STRINGLIB_EMPTY); - Py_INCREF(str_obj); - PyTuple_SET_ITEM(out, 2, (PyObject*) str_obj); - return out; + Py_INCREF(STRINGLIB_EMPTY); + PyTuple_SET_ITEM(out, 0, (PyObject*) STRINGLIB_EMPTY); + Py_INCREF(STRINGLIB_EMPTY); + PyTuple_SET_ITEM(out, 1, (PyObject*) STRINGLIB_EMPTY); + Py_INCREF(str_obj); + PyTuple_SET_ITEM(out, 2, (PyObject*) str_obj); + return out; } PyTuple_SET_ITEM(out, 0, STRINGLIB_NEW(str, pos)); @@ -94,8 +94,8 @@ PyTuple_SET_ITEM(out, 2, STRINGLIB_NEW(str + pos, str_len - pos)); if (PyErr_Occurred()) { - Py_DECREF(out); - return NULL; + Py_DECREF(out); + return NULL; } return out; Modified: python/branches/release31-maint/Objects/stringlib/string_format.h ============================================================================== --- python/branches/release31-maint/Objects/stringlib/string_format.h (original) +++ python/branches/release31-maint/Objects/stringlib/string_format.h Sun May 9 18:14:21 2010 @@ -563,36 +563,36 @@ PyObject *format_spec_object = NULL; PyObject *(*formatter)(PyObject *, STRINGLIB_CHAR *, Py_ssize_t) = NULL; STRINGLIB_CHAR* format_spec_start = format_spec->ptr ? - format_spec->ptr : NULL; + format_spec->ptr : NULL; Py_ssize_t format_spec_len = format_spec->ptr ? - format_spec->end - format_spec->ptr : 0; + format_spec->end - format_spec->ptr : 0; /* If we know the type exactly, skip the lookup of __format__ and just call the formatter directly. */ if (PyUnicode_CheckExact(fieldobj)) - formatter = _PyUnicode_FormatAdvanced; + formatter = _PyUnicode_FormatAdvanced; else if (PyLong_CheckExact(fieldobj)) - formatter =_PyLong_FormatAdvanced; + formatter =_PyLong_FormatAdvanced; else if (PyFloat_CheckExact(fieldobj)) - formatter = _PyFloat_FormatAdvanced; + formatter = _PyFloat_FormatAdvanced; /* XXX: for 2.6, convert format_spec to the appropriate type (unicode, str) */ if (formatter) { - /* we know exactly which formatter will be called when __format__ is - looked up, so call it directly, instead. */ - result = formatter(fieldobj, format_spec_start, format_spec_len); + /* we know exactly which formatter will be called when __format__ is + looked up, so call it directly, instead. */ + result = formatter(fieldobj, format_spec_start, format_spec_len); } else { - /* We need to create an object out of the pointers we have, because - __format__ takes a string/unicode object for format_spec. */ - format_spec_object = STRINGLIB_NEW(format_spec_start, - format_spec_len); - if (format_spec_object == NULL) - goto done; + /* We need to create an object out of the pointers we have, because + __format__ takes a string/unicode object for format_spec. */ + format_spec_object = STRINGLIB_NEW(format_spec_start, + format_spec_len); + if (format_spec_object == NULL) + goto done; - result = PyObject_Format(fieldobj, format_spec_object); + result = PyObject_Format(fieldobj, format_spec_object); } if (result == NULL) goto done; @@ -605,11 +605,11 @@ /* Convert result to our type. We could be str, and result could be unicode */ { - PyObject *tmp = STRINGLIB_TOSTR(result); - if (tmp == NULL) - goto done; - Py_DECREF(result); - result = tmp; + PyObject *tmp = STRINGLIB_TOSTR(result); + if (tmp == NULL) + goto done; + Py_DECREF(result); + result = tmp; } #endif @@ -844,17 +844,17 @@ return STRINGLIB_TOASCII(obj); #endif default: - if (conversion > 32 && conversion < 127) { - /* It's the ASCII subrange; casting to char is safe - (assuming the execution character set is an ASCII - superset). */ - PyErr_Format(PyExc_ValueError, + if (conversion > 32 && conversion < 127) { + /* It's the ASCII subrange; casting to char is safe + (assuming the execution character set is an ASCII + superset). */ + PyErr_Format(PyExc_ValueError, "Unknown conversion specifier %c", (char)conversion); - } else - PyErr_Format(PyExc_ValueError, - "Unknown conversion specifier \\x%x", - (unsigned int)conversion); + } else + PyErr_Format(PyExc_ValueError, + "Unknown conversion specifier \\x%x", + (unsigned int)conversion); return NULL; } } @@ -1119,7 +1119,7 @@ Py_INCREF(conversion_str); } else - conversion_str = STRINGLIB_NEW(&conversion, 1); + conversion_str = STRINGLIB_NEW(&conversion, 1); if (conversion_str == NULL) goto done; @@ -1135,39 +1135,39 @@ } static PyMethodDef formatteriter_methods[] = { - {NULL, NULL} /* sentinel */ + {NULL, NULL} /* sentinel */ }; static PyTypeObject PyFormatterIter_Type = { PyVarObject_HEAD_INIT(&PyType_Type, 0) - "formatteriterator", /* tp_name */ - sizeof(formatteriterobject), /* tp_basicsize */ - 0, /* tp_itemsize */ + "formatteriterator", /* tp_name */ + sizeof(formatteriterobject), /* tp_basicsize */ + 0, /* tp_itemsize */ /* methods */ - (destructor)formatteriter_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, /* tp_flags */ - 0, /* tp_doc */ - 0, /* tp_traverse */ - 0, /* tp_clear */ - 0, /* tp_richcompare */ - 0, /* tp_weaklistoffset */ - PyObject_SelfIter, /* tp_iter */ - (iternextfunc)formatteriter_next, /* tp_iternext */ - formatteriter_methods, /* tp_methods */ + (destructor)formatteriter_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, /* tp_flags */ + 0, /* tp_doc */ + 0, /* tp_traverse */ + 0, /* tp_clear */ + 0, /* tp_richcompare */ + 0, /* tp_weaklistoffset */ + PyObject_SelfIter, /* tp_iter */ + (iternextfunc)formatteriter_next, /* tp_iternext */ + formatteriter_methods, /* tp_methods */ 0, }; @@ -1268,39 +1268,39 @@ } static PyMethodDef fieldnameiter_methods[] = { - {NULL, NULL} /* sentinel */ + {NULL, NULL} /* sentinel */ }; static PyTypeObject PyFieldNameIter_Type = { PyVarObject_HEAD_INIT(&PyType_Type, 0) - "fieldnameiterator", /* tp_name */ - sizeof(fieldnameiterobject), /* tp_basicsize */ - 0, /* tp_itemsize */ + "fieldnameiterator", /* tp_name */ + sizeof(fieldnameiterobject), /* tp_basicsize */ + 0, /* tp_itemsize */ /* methods */ - (destructor)fieldnameiter_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, /* tp_flags */ - 0, /* tp_doc */ - 0, /* tp_traverse */ - 0, /* tp_clear */ - 0, /* tp_richcompare */ - 0, /* tp_weaklistoffset */ - PyObject_SelfIter, /* tp_iter */ - (iternextfunc)fieldnameiter_next, /* tp_iternext */ - fieldnameiter_methods, /* tp_methods */ + (destructor)fieldnameiter_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, /* tp_flags */ + 0, /* tp_doc */ + 0, /* tp_traverse */ + 0, /* tp_clear */ + 0, /* tp_richcompare */ + 0, /* tp_weaklistoffset */ + PyObject_SelfIter, /* tp_iter */ + (iternextfunc)fieldnameiter_next, /* tp_iternext */ + fieldnameiter_methods, /* tp_methods */ 0}; /* unicode_formatter_field_name_split is used to implement Modified: python/branches/release31-maint/Objects/stringlib/transmogrify.h ============================================================================== --- python/branches/release31-maint/Objects/stringlib/transmogrify.h (original) +++ python/branches/release31-maint/Objects/stringlib/transmogrify.h Sun May 9 18:14:21 2010 @@ -25,10 +25,10 @@ size_t i, j; PyObject *u; int tabsize = 8; - + if (!PyArg_ParseTuple(args, "|i:expandtabs", &tabsize)) return NULL; - + /* First pass: determine size of output string */ i = j = 0; e = STRINGLIB_STR(self) + STRINGLIB_LEN(self); @@ -55,20 +55,20 @@ } } } - + if ((i + j) > PY_SSIZE_T_MAX) { PyErr_SetString(PyExc_OverflowError, "result is too long"); return NULL; } - + /* Second pass: create output string and fill it */ u = STRINGLIB_NEW(NULL, i + j); if (!u) return NULL; - + j = 0; q = STRINGLIB_STR(u); - + for (p = STRINGLIB_STR(self); p < e; p++) if (*p == '\t') { if (tabsize > 0) { @@ -84,7 +84,7 @@ if (*p == '\n' || *p == '\r') j = 0; } - + return u; } @@ -110,16 +110,16 @@ } u = STRINGLIB_NEW(NULL, - left + STRINGLIB_LEN(self) + right); + left + STRINGLIB_LEN(self) + right); if (u) { if (left) memset(STRINGLIB_STR(u), fill, left); Py_MEMCPY(STRINGLIB_STR(u) + left, - STRINGLIB_STR(self), - STRINGLIB_LEN(self)); + STRINGLIB_STR(self), + STRINGLIB_LEN(self)); if (right) memset(STRINGLIB_STR(u) + left + STRINGLIB_LEN(self), - fill, right); + fill, right); } return u; @@ -271,17 +271,17 @@ } -#define _STRINGLIB_SPLIT_APPEND(data, left, right) \ - str = STRINGLIB_NEW((data) + (left), \ - (right) - (left)); \ - if (str == NULL) \ - goto onError; \ - if (PyList_Append(list, str)) { \ - Py_DECREF(str); \ - goto onError; \ - } \ - else \ - Py_DECREF(str); +#define _STRINGLIB_SPLIT_APPEND(data, left, right) \ + str = STRINGLIB_NEW((data) + (left), \ + (right) - (left)); \ + if (str == NULL) \ + goto onError; \ + if (PyList_Append(list, str)) { \ + Py_DECREF(str); \ + goto onError; \ + } \ + else \ + Py_DECREF(str); PyDoc_STRVAR(splitlines__doc__, "B.splitlines([keepends]) -> list of lines\n\ @@ -320,28 +320,28 @@ goto onError; for (i = j = 0; i < len; ) { - Py_ssize_t eol; + Py_ssize_t eol; - /* Find a line and append it */ - while (i < len && data[i] != '\n' && data[i] != '\r') - i++; - - /* Skip the line break reading CRLF as one line break */ - eol = i; - if (i < len) { - if (data[i] == '\r' && i + 1 < len && - data[i+1] == '\n') - i += 2; - else - i++; - if (keepends) - eol = i; - } - _STRINGLIB_SPLIT_APPEND(data, j, eol); - j = i; + /* Find a line and append it */ + while (i < len && data[i] != '\n' && data[i] != '\r') + i++; + + /* Skip the line break reading CRLF as one line break */ + eol = i; + if (i < len) { + if (data[i] == '\r' && i + 1 < len && + data[i+1] == '\n') + i += 2; + else + i++; + if (keepends) + eol = i; + } + _STRINGLIB_SPLIT_APPEND(data, j, eol); + j = i; } if (j < len) { - _STRINGLIB_SPLIT_APPEND(data, j, len); + _STRINGLIB_SPLIT_APPEND(data, j, len); } return list; Modified: python/branches/release31-maint/Objects/structseq.c ============================================================================== --- python/branches/release31-maint/Objects/structseq.c (original) +++ python/branches/release31-maint/Objects/structseq.c Sun May 9 18:14:21 2010 @@ -9,7 +9,7 @@ static char real_length_key[] = "n_fields"; static char unnamed_fields_key[] = "n_unnamed_fields"; -/* Fields with this name have only a field index, not a field name. +/* Fields with this name have only a field index, not a field name. They are only allowed for indices < n_visible_fields. */ char *PyStructSequence_UnnamedField = "unnamed field"; @@ -29,511 +29,511 @@ PyObject * PyStructSequence_New(PyTypeObject *type) { - PyStructSequence *obj; + PyStructSequence *obj; - obj = PyObject_New(PyStructSequence, type); - if (obj == NULL) - return NULL; - Py_SIZE(obj) = VISIBLE_SIZE_TP(type); + obj = PyObject_New(PyStructSequence, type); + if (obj == NULL) + return NULL; + Py_SIZE(obj) = VISIBLE_SIZE_TP(type); - return (PyObject*) obj; + return (PyObject*) obj; } static void structseq_dealloc(PyStructSequence *obj) { - Py_ssize_t i, size; + Py_ssize_t i, size; - size = REAL_SIZE(obj); - for (i = 0; i < size; ++i) { - Py_XDECREF(obj->ob_item[i]); - } - PyObject_Del(obj); + size = REAL_SIZE(obj); + for (i = 0; i < size; ++i) { + Py_XDECREF(obj->ob_item[i]); + } + PyObject_Del(obj); } static Py_ssize_t structseq_length(PyStructSequence *obj) { - return VISIBLE_SIZE(obj); + return VISIBLE_SIZE(obj); } static PyObject* structseq_item(PyStructSequence *obj, Py_ssize_t i) { - if (i < 0 || i >= VISIBLE_SIZE(obj)) { - PyErr_SetString(PyExc_IndexError, "tuple index out of range"); - return NULL; - } - Py_INCREF(obj->ob_item[i]); - return obj->ob_item[i]; + if (i < 0 || i >= VISIBLE_SIZE(obj)) { + PyErr_SetString(PyExc_IndexError, "tuple index out of range"); + return NULL; + } + Py_INCREF(obj->ob_item[i]); + return obj->ob_item[i]; } static PyObject* structseq_slice(PyStructSequence *obj, Py_ssize_t low, Py_ssize_t high) { - PyTupleObject *np; - Py_ssize_t i; + PyTupleObject *np; + Py_ssize_t i; - if (low < 0) - low = 0; - if (high > VISIBLE_SIZE(obj)) - high = VISIBLE_SIZE(obj); - if (high < low) - high = low; - np = (PyTupleObject *)PyTuple_New(high-low); - if (np == NULL) - return NULL; - for(i = low; i < high; ++i) { - PyObject *v = obj->ob_item[i]; - Py_INCREF(v); - PyTuple_SET_ITEM(np, i-low, v); - } - return (PyObject *) np; + if (low < 0) + low = 0; + if (high > VISIBLE_SIZE(obj)) + high = VISIBLE_SIZE(obj); + if (high < low) + high = low; + np = (PyTupleObject *)PyTuple_New(high-low); + if (np == NULL) + return NULL; + for(i = low; i < high; ++i) { + PyObject *v = obj->ob_item[i]; + Py_INCREF(v); + PyTuple_SET_ITEM(np, i-low, v); + } + return (PyObject *) np; } static PyObject * structseq_subscript(PyStructSequence *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 += VISIBLE_SIZE(self); - - if (i < 0 || i >= VISIBLE_SIZE(self)) { - PyErr_SetString(PyExc_IndexError, - "tuple index out of range"); - return NULL; - } - Py_INCREF(self->ob_item[i]); - return self->ob_item[i]; - } - else if (PySlice_Check(item)) { - Py_ssize_t start, stop, step, slicelen, cur, i; - PyObject *result; - - if (PySlice_GetIndicesEx((PySliceObject *)item, - VISIBLE_SIZE(self), &start, &stop, - &step, &slicelen) < 0) { - return NULL; - } - if (slicelen <= 0) - return PyTuple_New(0); - result = PyTuple_New(slicelen); - if (result == NULL) - return NULL; - for (cur = start, i = 0; i < slicelen; - cur += step, i++) { - PyObject *v = self->ob_item[cur]; - Py_INCREF(v); - PyTuple_SET_ITEM(result, i, v); - } - return result; - } - else { - PyErr_SetString(PyExc_TypeError, - "structseq index must be integer"); - return NULL; - } + 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 += VISIBLE_SIZE(self); + + if (i < 0 || i >= VISIBLE_SIZE(self)) { + PyErr_SetString(PyExc_IndexError, + "tuple index out of range"); + return NULL; + } + Py_INCREF(self->ob_item[i]); + return self->ob_item[i]; + } + else if (PySlice_Check(item)) { + Py_ssize_t start, stop, step, slicelen, cur, i; + PyObject *result; + + if (PySlice_GetIndicesEx((PySliceObject *)item, + VISIBLE_SIZE(self), &start, &stop, + &step, &slicelen) < 0) { + return NULL; + } + if (slicelen <= 0) + return PyTuple_New(0); + result = PyTuple_New(slicelen); + if (result == NULL) + return NULL; + for (cur = start, i = 0; i < slicelen; + cur += step, i++) { + PyObject *v = self->ob_item[cur]; + Py_INCREF(v); + PyTuple_SET_ITEM(result, i, v); + } + return result; + } + else { + PyErr_SetString(PyExc_TypeError, + "structseq index must be integer"); + return NULL; + } } static PyObject * structseq_new(PyTypeObject *type, PyObject *args, PyObject *kwds) { - PyObject *arg = NULL; - PyObject *dict = NULL; - PyObject *ob; - PyStructSequence *res = NULL; - Py_ssize_t len, min_len, max_len, i, n_unnamed_fields; - static char *kwlist[] = {"sequence", "dict", 0}; - - if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|O:structseq", - kwlist, &arg, &dict)) - return NULL; - - arg = PySequence_Fast(arg, "constructor requires a sequence"); - - if (!arg) { - return NULL; - } - - if (dict && !PyDict_Check(dict)) { - PyErr_Format(PyExc_TypeError, - "%.500s() takes a dict as second arg, if any", - type->tp_name); - Py_DECREF(arg); - return NULL; - } - - len = PySequence_Fast_GET_SIZE(arg); - min_len = VISIBLE_SIZE_TP(type); - max_len = REAL_SIZE_TP(type); - n_unnamed_fields = UNNAMED_FIELDS_TP(type); - - if (min_len != max_len) { - if (len < min_len) { - PyErr_Format(PyExc_TypeError, - "%.500s() takes an at least %zd-sequence (%zd-sequence given)", - type->tp_name, min_len, len); - Py_DECREF(arg); - return NULL; - } - - if (len > max_len) { - PyErr_Format(PyExc_TypeError, - "%.500s() takes an at most %zd-sequence (%zd-sequence given)", - type->tp_name, max_len, len); - Py_DECREF(arg); - return NULL; - } - } - else { - if (len != min_len) { - PyErr_Format(PyExc_TypeError, - "%.500s() takes a %zd-sequence (%zd-sequence given)", - type->tp_name, min_len, len); - Py_DECREF(arg); - return NULL; - } - } - - res = (PyStructSequence*) PyStructSequence_New(type); - if (res == NULL) { - return NULL; - } - for (i = 0; i < len; ++i) { - PyObject *v = PySequence_Fast_GET_ITEM(arg, i); - Py_INCREF(v); - res->ob_item[i] = v; - } - for (; i < max_len; ++i) { - if (dict && (ob = PyDict_GetItemString( - dict, type->tp_members[i-n_unnamed_fields].name))) { - } - else { - ob = Py_None; - } - Py_INCREF(ob); - res->ob_item[i] = ob; - } - - Py_DECREF(arg); - return (PyObject*) res; + PyObject *arg = NULL; + PyObject *dict = NULL; + PyObject *ob; + PyStructSequence *res = NULL; + Py_ssize_t len, min_len, max_len, i, n_unnamed_fields; + static char *kwlist[] = {"sequence", "dict", 0}; + + if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|O:structseq", + kwlist, &arg, &dict)) + return NULL; + + arg = PySequence_Fast(arg, "constructor requires a sequence"); + + if (!arg) { + return NULL; + } + + if (dict && !PyDict_Check(dict)) { + PyErr_Format(PyExc_TypeError, + "%.500s() takes a dict as second arg, if any", + type->tp_name); + Py_DECREF(arg); + return NULL; + } + + len = PySequence_Fast_GET_SIZE(arg); + min_len = VISIBLE_SIZE_TP(type); + max_len = REAL_SIZE_TP(type); + n_unnamed_fields = UNNAMED_FIELDS_TP(type); + + if (min_len != max_len) { + if (len < min_len) { + PyErr_Format(PyExc_TypeError, + "%.500s() takes an at least %zd-sequence (%zd-sequence given)", + type->tp_name, min_len, len); + Py_DECREF(arg); + return NULL; + } + + if (len > max_len) { + PyErr_Format(PyExc_TypeError, + "%.500s() takes an at most %zd-sequence (%zd-sequence given)", + type->tp_name, max_len, len); + Py_DECREF(arg); + return NULL; + } + } + else { + if (len != min_len) { + PyErr_Format(PyExc_TypeError, + "%.500s() takes a %zd-sequence (%zd-sequence given)", + type->tp_name, min_len, len); + Py_DECREF(arg); + return NULL; + } + } + + res = (PyStructSequence*) PyStructSequence_New(type); + if (res == NULL) { + return NULL; + } + for (i = 0; i < len; ++i) { + PyObject *v = PySequence_Fast_GET_ITEM(arg, i); + Py_INCREF(v); + res->ob_item[i] = v; + } + for (; i < max_len; ++i) { + if (dict && (ob = PyDict_GetItemString( + dict, type->tp_members[i-n_unnamed_fields].name))) { + } + else { + ob = Py_None; + } + Py_INCREF(ob); + res->ob_item[i] = ob; + } + + Py_DECREF(arg); + return (PyObject*) res; } static PyObject * make_tuple(PyStructSequence *obj) { - return structseq_slice(obj, 0, VISIBLE_SIZE(obj)); + return structseq_slice(obj, 0, VISIBLE_SIZE(obj)); } static PyObject * structseq_repr(PyStructSequence *obj) { - /* buffer and type size were chosen well considered. */ + /* buffer and type size were chosen well considered. */ #define REPR_BUFFER_SIZE 512 #define TYPE_MAXSIZE 100 - PyObject *tup; - PyTypeObject *typ = Py_TYPE(obj); - int i, removelast = 0; - Py_ssize_t len; - char buf[REPR_BUFFER_SIZE]; - char *endofbuf, *pbuf = buf; - - /* pointer to end of writeable buffer; safes space for "...)\0" */ - endofbuf= &buf[REPR_BUFFER_SIZE-5]; - - if ((tup = make_tuple(obj)) == NULL) { - return NULL; - } - - /* "typename(", limited to TYPE_MAXSIZE */ - len = strlen(typ->tp_name) > TYPE_MAXSIZE ? TYPE_MAXSIZE : - strlen(typ->tp_name); - strncpy(pbuf, typ->tp_name, len); - pbuf += len; - *pbuf++ = '('; - - for (i=0; i < VISIBLE_SIZE(obj); i++) { - PyObject *val, *repr; - char *cname, *crepr; - - cname = typ->tp_members[i].name; - - val = PyTuple_GetItem(tup, i); - if (cname == NULL || val == NULL) { - return NULL; - } - repr = PyObject_Repr(val); - if (repr == NULL) { - Py_DECREF(tup); - return NULL; - } - crepr = _PyUnicode_AsString(repr); - if (crepr == NULL) { - Py_DECREF(tup); - Py_DECREF(repr); - return NULL; - } - - /* + 3: keep space for "=" and ", " */ - len = strlen(cname) + strlen(crepr) + 3; - if ((pbuf+len) <= endofbuf) { - strcpy(pbuf, cname); - pbuf += strlen(cname); - *pbuf++ = '='; - strcpy(pbuf, crepr); - pbuf += strlen(crepr); - *pbuf++ = ','; - *pbuf++ = ' '; - removelast = 1; - Py_DECREF(repr); - } - else { - strcpy(pbuf, "..."); - pbuf += 3; - removelast = 0; - Py_DECREF(repr); - break; - } - } - Py_DECREF(tup); - if (removelast) { - /* overwrite last ", " */ - pbuf-=2; - } - *pbuf++ = ')'; - *pbuf = '\0'; + PyObject *tup; + PyTypeObject *typ = Py_TYPE(obj); + int i, removelast = 0; + Py_ssize_t len; + char buf[REPR_BUFFER_SIZE]; + char *endofbuf, *pbuf = buf; + + /* pointer to end of writeable buffer; safes space for "...)\0" */ + endofbuf= &buf[REPR_BUFFER_SIZE-5]; + + if ((tup = make_tuple(obj)) == NULL) { + return NULL; + } + + /* "typename(", limited to TYPE_MAXSIZE */ + len = strlen(typ->tp_name) > TYPE_MAXSIZE ? TYPE_MAXSIZE : + strlen(typ->tp_name); + strncpy(pbuf, typ->tp_name, len); + pbuf += len; + *pbuf++ = '('; + + for (i=0; i < VISIBLE_SIZE(obj); i++) { + PyObject *val, *repr; + char *cname, *crepr; + + cname = typ->tp_members[i].name; + + val = PyTuple_GetItem(tup, i); + if (cname == NULL || val == NULL) { + return NULL; + } + repr = PyObject_Repr(val); + if (repr == NULL) { + Py_DECREF(tup); + return NULL; + } + crepr = _PyUnicode_AsString(repr); + if (crepr == NULL) { + Py_DECREF(tup); + Py_DECREF(repr); + return NULL; + } + + /* + 3: keep space for "=" and ", " */ + len = strlen(cname) + strlen(crepr) + 3; + if ((pbuf+len) <= endofbuf) { + strcpy(pbuf, cname); + pbuf += strlen(cname); + *pbuf++ = '='; + strcpy(pbuf, crepr); + pbuf += strlen(crepr); + *pbuf++ = ','; + *pbuf++ = ' '; + removelast = 1; + Py_DECREF(repr); + } + else { + strcpy(pbuf, "..."); + pbuf += 3; + removelast = 0; + Py_DECREF(repr); + break; + } + } + Py_DECREF(tup); + if (removelast) { + /* overwrite last ", " */ + pbuf-=2; + } + *pbuf++ = ')'; + *pbuf = '\0'; - return PyUnicode_FromString(buf); + return PyUnicode_FromString(buf); } static PyObject * structseq_concat(PyStructSequence *obj, PyObject *b) { - PyObject *tup, *result; - tup = make_tuple(obj); - result = PySequence_Concat(tup, b); - Py_DECREF(tup); - return result; + PyObject *tup, *result; + tup = make_tuple(obj); + result = PySequence_Concat(tup, b); + Py_DECREF(tup); + return result; } static PyObject * structseq_repeat(PyStructSequence *obj, Py_ssize_t n) { - PyObject *tup, *result; - tup = make_tuple(obj); - result = PySequence_Repeat(tup, n); - Py_DECREF(tup); - return result; + PyObject *tup, *result; + tup = make_tuple(obj); + result = PySequence_Repeat(tup, n); + Py_DECREF(tup); + return result; } static int structseq_contains(PyStructSequence *obj, PyObject *o) { - PyObject *tup; - int result; - tup = make_tuple(obj); - if (!tup) - return -1; - result = PySequence_Contains(tup, o); - Py_DECREF(tup); - return result; + PyObject *tup; + int result; + tup = make_tuple(obj); + if (!tup) + return -1; + result = PySequence_Contains(tup, o); + Py_DECREF(tup); + return result; } static long structseq_hash(PyObject *obj) { - PyObject *tup; - long result; - tup = make_tuple((PyStructSequence*) obj); - if (!tup) - return -1; - result = PyObject_Hash(tup); - Py_DECREF(tup); - return result; + PyObject *tup; + long result; + tup = make_tuple((PyStructSequence*) obj); + if (!tup) + return -1; + result = PyObject_Hash(tup); + Py_DECREF(tup); + return result; } static PyObject * structseq_richcompare(PyObject *obj, PyObject *o2, int op) { - PyObject *tup, *result; - tup = make_tuple((PyStructSequence*) obj); - result = PyObject_RichCompare(tup, o2, op); - Py_DECREF(tup); - return result; + PyObject *tup, *result; + tup = make_tuple((PyStructSequence*) obj); + result = PyObject_RichCompare(tup, o2, op); + Py_DECREF(tup); + return result; } static PyObject * structseq_reduce(PyStructSequence* self) { - PyObject* tup; - PyObject* dict; - PyObject* result; - Py_ssize_t n_fields, n_visible_fields, n_unnamed_fields; - int i; - - n_fields = REAL_SIZE(self); - n_visible_fields = VISIBLE_SIZE(self); - n_unnamed_fields = UNNAMED_FIELDS(self); - tup = PyTuple_New(n_visible_fields); - if (!tup) { - return NULL; - } - - dict = PyDict_New(); - if (!dict) { - Py_DECREF(tup); - return NULL; - } - - for (i = 0; i < n_visible_fields; i++) { - Py_INCREF(self->ob_item[i]); - PyTuple_SET_ITEM(tup, i, self->ob_item[i]); - } - - for (; i < n_fields; i++) { - char *n = Py_TYPE(self)->tp_members[i-n_unnamed_fields].name; - PyDict_SetItemString(dict, n, - self->ob_item[i]); - } + PyObject* tup; + PyObject* dict; + PyObject* result; + Py_ssize_t n_fields, n_visible_fields, n_unnamed_fields; + int i; + + n_fields = REAL_SIZE(self); + n_visible_fields = VISIBLE_SIZE(self); + n_unnamed_fields = UNNAMED_FIELDS(self); + tup = PyTuple_New(n_visible_fields); + if (!tup) { + return NULL; + } + + dict = PyDict_New(); + if (!dict) { + Py_DECREF(tup); + return NULL; + } + + for (i = 0; i < n_visible_fields; i++) { + Py_INCREF(self->ob_item[i]); + PyTuple_SET_ITEM(tup, i, self->ob_item[i]); + } + + for (; i < n_fields; i++) { + char *n = Py_TYPE(self)->tp_members[i-n_unnamed_fields].name; + PyDict_SetItemString(dict, n, + self->ob_item[i]); + } - result = Py_BuildValue("(O(OO))", Py_TYPE(self), tup, dict); + result = Py_BuildValue("(O(OO))", Py_TYPE(self), tup, dict); - Py_DECREF(tup); - Py_DECREF(dict); + Py_DECREF(tup); + Py_DECREF(dict); - return result; + return result; } static PySequenceMethods structseq_as_sequence = { - (lenfunc)structseq_length, - (binaryfunc)structseq_concat, /* sq_concat */ - (ssizeargfunc)structseq_repeat, /* sq_repeat */ - (ssizeargfunc)structseq_item, /* sq_item */ - 0, /* sq_slice */ - 0, /* sq_ass_item */ - 0, /* sq_ass_slice */ - (objobjproc)structseq_contains, /* sq_contains */ + (lenfunc)structseq_length, + (binaryfunc)structseq_concat, /* sq_concat */ + (ssizeargfunc)structseq_repeat, /* sq_repeat */ + (ssizeargfunc)structseq_item, /* sq_item */ + 0, /* sq_slice */ + 0, /* sq_ass_item */ + 0, /* sq_ass_slice */ + (objobjproc)structseq_contains, /* sq_contains */ }; static PyMappingMethods structseq_as_mapping = { - (lenfunc)structseq_length, - (binaryfunc)structseq_subscript, + (lenfunc)structseq_length, + (binaryfunc)structseq_subscript, }; static PyMethodDef structseq_methods[] = { - {"__reduce__", (PyCFunction)structseq_reduce, - METH_NOARGS, NULL}, - {NULL, NULL} + {"__reduce__", (PyCFunction)structseq_reduce, + METH_NOARGS, NULL}, + {NULL, NULL} }; static PyTypeObject _struct_sequence_template = { - PyVarObject_HEAD_INIT(&PyType_Type, 0) - NULL, /* tp_name */ - 0, /* tp_basicsize */ - 0, /* tp_itemsize */ - (destructor)structseq_dealloc, /* tp_dealloc */ - 0, /* tp_print */ - 0, /* tp_getattr */ - 0, /* tp_setattr */ - 0, /* tp_reserved */ - (reprfunc)structseq_repr, /* tp_repr */ - 0, /* tp_as_number */ - &structseq_as_sequence, /* tp_as_sequence */ - &structseq_as_mapping, /* tp_as_mapping */ - structseq_hash, /* tp_hash */ - 0, /* tp_call */ - 0, /* tp_str */ - 0, /* tp_getattro */ - 0, /* tp_setattro */ - 0, /* tp_as_buffer */ - Py_TPFLAGS_DEFAULT, /* tp_flags */ - NULL, /* tp_doc */ - 0, /* tp_traverse */ - 0, /* tp_clear */ - structseq_richcompare, /* tp_richcompare */ - 0, /* tp_weaklistoffset */ - 0, /* tp_iter */ - 0, /* tp_iternext */ - structseq_methods, /* tp_methods */ - NULL, /* tp_members */ - 0, /* tp_getset */ - 0, /* tp_base */ - 0, /* tp_dict */ - 0, /* tp_descr_get */ - 0, /* tp_descr_set */ - 0, /* tp_dictoffset */ - 0, /* tp_init */ - 0, /* tp_alloc */ - structseq_new, /* tp_new */ + PyVarObject_HEAD_INIT(&PyType_Type, 0) + NULL, /* tp_name */ + 0, /* tp_basicsize */ + 0, /* tp_itemsize */ + (destructor)structseq_dealloc, /* tp_dealloc */ + 0, /* tp_print */ + 0, /* tp_getattr */ + 0, /* tp_setattr */ + 0, /* tp_reserved */ + (reprfunc)structseq_repr, /* tp_repr */ + 0, /* tp_as_number */ + &structseq_as_sequence, /* tp_as_sequence */ + &structseq_as_mapping, /* tp_as_mapping */ + structseq_hash, /* tp_hash */ + 0, /* tp_call */ + 0, /* tp_str */ + 0, /* tp_getattro */ + 0, /* tp_setattro */ + 0, /* tp_as_buffer */ + Py_TPFLAGS_DEFAULT, /* tp_flags */ + NULL, /* tp_doc */ + 0, /* tp_traverse */ + 0, /* tp_clear */ + structseq_richcompare, /* tp_richcompare */ + 0, /* tp_weaklistoffset */ + 0, /* tp_iter */ + 0, /* tp_iternext */ + structseq_methods, /* tp_methods */ + NULL, /* tp_members */ + 0, /* tp_getset */ + 0, /* tp_base */ + 0, /* tp_dict */ + 0, /* tp_descr_get */ + 0, /* tp_descr_set */ + 0, /* tp_dictoffset */ + 0, /* tp_init */ + 0, /* tp_alloc */ + structseq_new, /* tp_new */ }; void PyStructSequence_InitType(PyTypeObject *type, PyStructSequence_Desc *desc) { - PyObject *dict; - PyMemberDef* members; - int n_members, n_unnamed_members, i, k; + PyObject *dict; + PyMemberDef* members; + int n_members, n_unnamed_members, i, k; #ifdef Py_TRACE_REFS - /* if the type object was chained, unchain it first - before overwriting its storage */ - if (type->ob_base.ob_base._ob_next) { - _Py_ForgetReference((PyObject*)type); - } + /* if the type object was chained, unchain it first + before overwriting its storage */ + if (type->ob_base.ob_base._ob_next) { + _Py_ForgetReference((PyObject*)type); + } #endif - n_unnamed_members = 0; - for (i = 0; desc->fields[i].name != NULL; ++i) - if (desc->fields[i].name == PyStructSequence_UnnamedField) - n_unnamed_members++; - n_members = i; - - memcpy(type, &_struct_sequence_template, sizeof(PyTypeObject)); - type->tp_name = desc->name; - type->tp_doc = desc->doc; - type->tp_basicsize = sizeof(PyStructSequence)+ - sizeof(PyObject*)*(n_members-1); - type->tp_itemsize = 0; - - members = PyMem_NEW(PyMemberDef, n_members-n_unnamed_members+1); - if (members == NULL) - return; - - for (i = k = 0; i < n_members; ++i) { - if (desc->fields[i].name == PyStructSequence_UnnamedField) - continue; - members[k].name = desc->fields[i].name; - members[k].type = T_OBJECT; - members[k].offset = offsetof(PyStructSequence, ob_item) - + i * sizeof(PyObject*); - members[k].flags = READONLY; - members[k].doc = desc->fields[i].doc; - k++; - } - members[k].name = NULL; - - type->tp_members = members; - - if (PyType_Ready(type) < 0) - return; - Py_INCREF(type); - - dict = type->tp_dict; -#define SET_DICT_FROM_INT(key, value) \ - do { \ - PyObject *v = PyLong_FromLong((long) value); \ - if (v != NULL) { \ - PyDict_SetItemString(dict, key, v); \ - Py_DECREF(v); \ - } \ - } while (0) - - SET_DICT_FROM_INT(visible_length_key, desc->n_in_sequence); - SET_DICT_FROM_INT(real_length_key, n_members); - SET_DICT_FROM_INT(unnamed_fields_key, n_unnamed_members); + n_unnamed_members = 0; + for (i = 0; desc->fields[i].name != NULL; ++i) + if (desc->fields[i].name == PyStructSequence_UnnamedField) + n_unnamed_members++; + n_members = i; + + memcpy(type, &_struct_sequence_template, sizeof(PyTypeObject)); + type->tp_name = desc->name; + type->tp_doc = desc->doc; + type->tp_basicsize = sizeof(PyStructSequence)+ + sizeof(PyObject*)*(n_members-1); + type->tp_itemsize = 0; + + members = PyMem_NEW(PyMemberDef, n_members-n_unnamed_members+1); + if (members == NULL) + return; + + for (i = k = 0; i < n_members; ++i) { + if (desc->fields[i].name == PyStructSequence_UnnamedField) + continue; + members[k].name = desc->fields[i].name; + members[k].type = T_OBJECT; + members[k].offset = offsetof(PyStructSequence, ob_item) + + i * sizeof(PyObject*); + members[k].flags = READONLY; + members[k].doc = desc->fields[i].doc; + k++; + } + members[k].name = NULL; + + type->tp_members = members; + + if (PyType_Ready(type) < 0) + return; + Py_INCREF(type); + + dict = type->tp_dict; +#define SET_DICT_FROM_INT(key, value) \ + do { \ + PyObject *v = PyLong_FromLong((long) value); \ + if (v != NULL) { \ + PyDict_SetItemString(dict, key, v); \ + Py_DECREF(v); \ + } \ + } while (0) + + SET_DICT_FROM_INT(visible_length_key, desc->n_in_sequence); + SET_DICT_FROM_INT(real_length_key, n_members); + SET_DICT_FROM_INT(unnamed_fields_key, n_unnamed_members); } Modified: python/branches/release31-maint/Objects/tupleobject.c ============================================================================== --- python/branches/release31-maint/Objects/tupleobject.c (original) +++ python/branches/release31-maint/Objects/tupleobject.c Sun May 9 18:14:21 2010 @@ -5,9 +5,9 @@ /* Speed optimization to avoid frequent malloc/free of small tuples */ #ifndef PyTuple_MAXSAVESIZE -#define PyTuple_MAXSAVESIZE 20 /* Largest tuple to save on free list */ +#define PyTuple_MAXSAVESIZE 20 /* Largest tuple to save on free list */ #endif -#ifndef PyTuple_MAXFREELIST +#ifndef PyTuple_MAXFREELIST #define PyTuple_MAXFREELIST 2000 /* Maximum number of tuples of each size to save */ #endif @@ -35,12 +35,12 @@ static void show_track(void) { - fprintf(stderr, "Tuples created: %" PY_FORMAT_SIZE_T "d\n", - count_tracked + count_untracked); - fprintf(stderr, "Tuples tracked by the GC: %" PY_FORMAT_SIZE_T - "d\n", count_tracked); - fprintf(stderr, "%.2f%% tuple tracking rate\n\n", - (100.0*count_tracked/(count_untracked+count_tracked))); + fprintf(stderr, "Tuples created: %" PY_FORMAT_SIZE_T "d\n", + count_tracked + count_untracked); + fprintf(stderr, "Tuples tracked by the GC: %" PY_FORMAT_SIZE_T + "d\n", count_tracked); + fprintf(stderr, "%.2f%% tuple tracking rate\n\n", + (100.0*count_tracked/(count_untracked+count_tracked))); } #endif @@ -48,161 +48,161 @@ PyObject * PyTuple_New(register Py_ssize_t size) { - register PyTupleObject *op; - Py_ssize_t i; - if (size < 0) { - PyErr_BadInternalCall(); - return NULL; - } + register PyTupleObject *op; + Py_ssize_t i; + if (size < 0) { + PyErr_BadInternalCall(); + return NULL; + } #if PyTuple_MAXSAVESIZE > 0 - if (size == 0 && free_list[0]) { - op = free_list[0]; - Py_INCREF(op); + if (size == 0 && free_list[0]) { + op = free_list[0]; + Py_INCREF(op); #ifdef COUNT_ALLOCS - tuple_zero_allocs++; + tuple_zero_allocs++; #endif - return (PyObject *) op; - } - if (size < PyTuple_MAXSAVESIZE && (op = free_list[size]) != NULL) { - free_list[size] = (PyTupleObject *) op->ob_item[0]; - numfree[size]--; + return (PyObject *) op; + } + if (size < PyTuple_MAXSAVESIZE && (op = free_list[size]) != NULL) { + free_list[size] = (PyTupleObject *) op->ob_item[0]; + numfree[size]--; #ifdef COUNT_ALLOCS - fast_tuple_allocs++; + fast_tuple_allocs++; #endif - /* Inline PyObject_InitVar */ + /* Inline PyObject_InitVar */ #ifdef Py_TRACE_REFS - Py_SIZE(op) = size; - Py_TYPE(op) = &PyTuple_Type; + Py_SIZE(op) = size; + Py_TYPE(op) = &PyTuple_Type; #endif - _Py_NewReference((PyObject *)op); - } - else + _Py_NewReference((PyObject *)op); + } + else #endif - { - Py_ssize_t nbytes = size * sizeof(PyObject *); - /* Check for overflow */ - if (nbytes / sizeof(PyObject *) != (size_t)size || - (nbytes > PY_SSIZE_T_MAX - sizeof(PyTupleObject) - sizeof(PyObject *))) - { - return PyErr_NoMemory(); - } - nbytes += sizeof(PyTupleObject) - sizeof(PyObject *); - - op = PyObject_GC_NewVar(PyTupleObject, &PyTuple_Type, size); - if (op == NULL) - return NULL; - } - for (i=0; i < size; i++) - op->ob_item[i] = NULL; + { + Py_ssize_t nbytes = size * sizeof(PyObject *); + /* Check for overflow */ + if (nbytes / sizeof(PyObject *) != (size_t)size || + (nbytes > PY_SSIZE_T_MAX - sizeof(PyTupleObject) - sizeof(PyObject *))) + { + return PyErr_NoMemory(); + } + nbytes += sizeof(PyTupleObject) - sizeof(PyObject *); + + op = PyObject_GC_NewVar(PyTupleObject, &PyTuple_Type, size); + if (op == NULL) + return NULL; + } + for (i=0; i < size; i++) + op->ob_item[i] = NULL; #if PyTuple_MAXSAVESIZE > 0 - if (size == 0) { - free_list[0] = op; - ++numfree[0]; - Py_INCREF(op); /* extra INCREF so that this is never freed */ - } + if (size == 0) { + free_list[0] = op; + ++numfree[0]; + Py_INCREF(op); /* extra INCREF so that this is never freed */ + } #endif #ifdef SHOW_TRACK_COUNT - count_tracked++; + count_tracked++; #endif - _PyObject_GC_TRACK(op); - return (PyObject *) op; + _PyObject_GC_TRACK(op); + return (PyObject *) op; } Py_ssize_t PyTuple_Size(register PyObject *op) { - if (!PyTuple_Check(op)) { - PyErr_BadInternalCall(); - return -1; - } - else - return Py_SIZE(op); + if (!PyTuple_Check(op)) { + PyErr_BadInternalCall(); + return -1; + } + else + return Py_SIZE(op); } PyObject * PyTuple_GetItem(register PyObject *op, register Py_ssize_t i) { - if (!PyTuple_Check(op)) { - PyErr_BadInternalCall(); - return NULL; - } - if (i < 0 || i >= Py_SIZE(op)) { - PyErr_SetString(PyExc_IndexError, "tuple index out of range"); - return NULL; - } - return ((PyTupleObject *)op) -> ob_item[i]; + if (!PyTuple_Check(op)) { + PyErr_BadInternalCall(); + return NULL; + } + if (i < 0 || i >= Py_SIZE(op)) { + PyErr_SetString(PyExc_IndexError, "tuple index out of range"); + return NULL; + } + return ((PyTupleObject *)op) -> ob_item[i]; } int PyTuple_SetItem(register PyObject *op, register Py_ssize_t i, PyObject *newitem) { - register PyObject *olditem; - register PyObject **p; - if (!PyTuple_Check(op) || op->ob_refcnt != 1) { - Py_XDECREF(newitem); - PyErr_BadInternalCall(); - return -1; - } - if (i < 0 || i >= Py_SIZE(op)) { - Py_XDECREF(newitem); - PyErr_SetString(PyExc_IndexError, - "tuple assignment index out of range"); - return -1; - } - p = ((PyTupleObject *)op) -> ob_item + i; - olditem = *p; - *p = newitem; - Py_XDECREF(olditem); - return 0; + register PyObject *olditem; + register PyObject **p; + if (!PyTuple_Check(op) || op->ob_refcnt != 1) { + Py_XDECREF(newitem); + PyErr_BadInternalCall(); + return -1; + } + if (i < 0 || i >= Py_SIZE(op)) { + Py_XDECREF(newitem); + PyErr_SetString(PyExc_IndexError, + "tuple assignment index out of range"); + return -1; + } + p = ((PyTupleObject *)op) -> ob_item + i; + olditem = *p; + *p = newitem; + Py_XDECREF(olditem); + return 0; } void _PyTuple_MaybeUntrack(PyObject *op) { - PyTupleObject *t; - Py_ssize_t i, n; - - if (!PyTuple_CheckExact(op) || !_PyObject_GC_IS_TRACKED(op)) - return; - t = (PyTupleObject *) op; - n = Py_SIZE(t); - for (i = 0; i < n; i++) { - PyObject *elt = PyTuple_GET_ITEM(t, i); - /* Tuple with NULL elements aren't - fully constructed, don't untrack - them yet. */ - if (!elt || - _PyObject_GC_MAY_BE_TRACKED(elt)) - return; - } + PyTupleObject *t; + Py_ssize_t i, n; + + if (!PyTuple_CheckExact(op) || !_PyObject_GC_IS_TRACKED(op)) + return; + t = (PyTupleObject *) op; + n = Py_SIZE(t); + for (i = 0; i < n; i++) { + PyObject *elt = PyTuple_GET_ITEM(t, i); + /* Tuple with NULL elements aren't + fully constructed, don't untrack + them yet. */ + if (!elt || + _PyObject_GC_MAY_BE_TRACKED(elt)) + return; + } #ifdef SHOW_TRACK_COUNT - count_tracked--; - count_untracked++; + count_tracked--; + count_untracked++; #endif - _PyObject_GC_UNTRACK(op); + _PyObject_GC_UNTRACK(op); } PyObject * PyTuple_Pack(Py_ssize_t n, ...) { - Py_ssize_t i; - PyObject *o; - PyObject *result; - PyObject **items; - va_list vargs; - - va_start(vargs, n); - result = PyTuple_New(n); - if (result == NULL) - return NULL; - items = ((PyTupleObject *)result)->ob_item; - for (i = 0; i < n; i++) { - o = va_arg(vargs, PyObject *); - Py_INCREF(o); - items[i] = o; - } - va_end(vargs); - return result; + Py_ssize_t i; + PyObject *o; + PyObject *result; + PyObject **items; + va_list vargs; + + va_start(vargs, n); + result = PyTuple_New(n); + if (result == NULL) + return NULL; + items = ((PyTupleObject *)result)->ob_item; + for (i = 0; i < n; i++) { + o = va_arg(vargs, PyObject *); + Py_INCREF(o); + items[i] = o; + } + va_end(vargs); + return result; } @@ -211,405 +211,405 @@ static void tupledealloc(register PyTupleObject *op) { - register Py_ssize_t i; - register Py_ssize_t len = Py_SIZE(op); - PyObject_GC_UnTrack(op); - Py_TRASHCAN_SAFE_BEGIN(op) - if (len > 0) { - i = len; - while (--i >= 0) - Py_XDECREF(op->ob_item[i]); + register Py_ssize_t i; + register Py_ssize_t len = Py_SIZE(op); + PyObject_GC_UnTrack(op); + Py_TRASHCAN_SAFE_BEGIN(op) + if (len > 0) { + i = len; + while (--i >= 0) + Py_XDECREF(op->ob_item[i]); #if PyTuple_MAXSAVESIZE > 0 - if (len < PyTuple_MAXSAVESIZE && - numfree[len] < PyTuple_MAXFREELIST && - Py_TYPE(op) == &PyTuple_Type) - { - op->ob_item[0] = (PyObject *) free_list[len]; - numfree[len]++; - free_list[len] = op; - goto done; /* return */ - } + if (len < PyTuple_MAXSAVESIZE && + numfree[len] < PyTuple_MAXFREELIST && + Py_TYPE(op) == &PyTuple_Type) + { + op->ob_item[0] = (PyObject *) free_list[len]; + numfree[len]++; + free_list[len] = op; + goto done; /* return */ + } #endif - } - Py_TYPE(op)->tp_free((PyObject *)op); + } + Py_TYPE(op)->tp_free((PyObject *)op); done: - Py_TRASHCAN_SAFE_END(op) + Py_TRASHCAN_SAFE_END(op) } static PyObject * tuplerepr(PyTupleObject *v) { - Py_ssize_t i, n; - PyObject *s, *temp; - PyObject *pieces, *result = NULL; - - n = Py_SIZE(v); - if (n == 0) - return PyUnicode_FromString("()"); - - /* While not mutable, it is still possible to end up with a cycle in a - tuple through an object that stores itself within a tuple (and thus - infinitely asks for the repr of itself). This should only be - possible within a type. */ - i = Py_ReprEnter((PyObject *)v); - if (i != 0) { - return i > 0 ? PyUnicode_FromString("(...)") : NULL; - } - - pieces = PyTuple_New(n); - if (pieces == NULL) - return NULL; - - /* Do repr() on each element. */ - for (i = 0; i < n; ++i) { - if (Py_EnterRecursiveCall(" while getting the repr of a tuple")) - goto Done; - s = PyObject_Repr(v->ob_item[i]); - Py_LeaveRecursiveCall(); - if (s == NULL) - goto Done; - PyTuple_SET_ITEM(pieces, i, s); - } - - /* Add "()" decorations to the first and last items. */ - assert(n > 0); - s = PyUnicode_FromString("("); - if (s == NULL) - goto Done; - temp = PyTuple_GET_ITEM(pieces, 0); - PyUnicode_AppendAndDel(&s, temp); - PyTuple_SET_ITEM(pieces, 0, s); - if (s == NULL) - goto Done; - - s = PyUnicode_FromString(n == 1 ? ",)" : ")"); - if (s == NULL) - goto Done; - temp = PyTuple_GET_ITEM(pieces, n-1); - PyUnicode_AppendAndDel(&temp, s); - PyTuple_SET_ITEM(pieces, n-1, temp); - if (temp == NULL) - goto Done; - - /* Paste them all together with ", " between. */ - s = PyUnicode_FromString(", "); - if (s == NULL) - goto Done; - result = PyUnicode_Join(s, pieces); - Py_DECREF(s); + Py_ssize_t i, n; + PyObject *s, *temp; + PyObject *pieces, *result = NULL; + + n = Py_SIZE(v); + if (n == 0) + return PyUnicode_FromString("()"); + + /* While not mutable, it is still possible to end up with a cycle in a + tuple through an object that stores itself within a tuple (and thus + infinitely asks for the repr of itself). This should only be + possible within a type. */ + i = Py_ReprEnter((PyObject *)v); + if (i != 0) { + return i > 0 ? PyUnicode_FromString("(...)") : NULL; + } + + pieces = PyTuple_New(n); + if (pieces == NULL) + return NULL; + + /* Do repr() on each element. */ + for (i = 0; i < n; ++i) { + if (Py_EnterRecursiveCall(" while getting the repr of a tuple")) + goto Done; + s = PyObject_Repr(v->ob_item[i]); + Py_LeaveRecursiveCall(); + if (s == NULL) + goto Done; + PyTuple_SET_ITEM(pieces, i, s); + } + + /* Add "()" decorations to the first and last items. */ + assert(n > 0); + s = PyUnicode_FromString("("); + if (s == NULL) + goto Done; + temp = PyTuple_GET_ITEM(pieces, 0); + PyUnicode_AppendAndDel(&s, temp); + PyTuple_SET_ITEM(pieces, 0, s); + if (s == NULL) + goto Done; + + s = PyUnicode_FromString(n == 1 ? ",)" : ")"); + if (s == NULL) + goto Done; + temp = PyTuple_GET_ITEM(pieces, n-1); + PyUnicode_AppendAndDel(&temp, s); + PyTuple_SET_ITEM(pieces, n-1, temp); + if (temp == NULL) + goto Done; + + /* Paste them all together with ", " between. */ + s = PyUnicode_FromString(", "); + if (s == NULL) + goto Done; + result = PyUnicode_Join(s, pieces); + Py_DECREF(s); Done: - Py_DECREF(pieces); - Py_ReprLeave((PyObject *)v); - return result; + Py_DECREF(pieces); + Py_ReprLeave((PyObject *)v); + return result; } -/* The addend 82520, was selected from the range(0, 1000000) for - generating the greatest number of prime multipliers for tuples +/* The addend 82520, was selected from the range(0, 1000000) for + generating the greatest number of prime multipliers for tuples upto length eight: - 1082527, 1165049, 1082531, 1165057, 1247581, 1330103, 1082533, + 1082527, 1165049, 1082531, 1165057, 1247581, 1330103, 1082533, 1330111, 1412633, 1165069, 1247599, 1495177, 1577699 */ static long tuplehash(PyTupleObject *v) { - register long x, y; - register Py_ssize_t len = Py_SIZE(v); - register PyObject **p; - long mult = 1000003L; - x = 0x345678L; - p = v->ob_item; - while (--len >= 0) { - y = PyObject_Hash(*p++); - if (y == -1) - return -1; - x = (x ^ y) * mult; - /* the cast might truncate len; that doesn't change hash stability */ - mult += (long)(82520L + len + len); - } - x += 97531L; - if (x == -1) - x = -2; - return x; + register long x, y; + register Py_ssize_t len = Py_SIZE(v); + register PyObject **p; + long mult = 1000003L; + x = 0x345678L; + p = v->ob_item; + while (--len >= 0) { + y = PyObject_Hash(*p++); + if (y == -1) + return -1; + x = (x ^ y) * mult; + /* the cast might truncate len; that doesn't change hash stability */ + mult += (long)(82520L + len + len); + } + x += 97531L; + if (x == -1) + x = -2; + return x; } static Py_ssize_t tuplelength(PyTupleObject *a) { - return Py_SIZE(a); + return Py_SIZE(a); } static int tuplecontains(PyTupleObject *a, PyObject *el) { - Py_ssize_t i; - int cmp; + Py_ssize_t i; + int cmp; - for (i = 0, cmp = 0 ; cmp == 0 && i < Py_SIZE(a); ++i) - cmp = PyObject_RichCompareBool(el, PyTuple_GET_ITEM(a, i), - Py_EQ); - return cmp; + for (i = 0, cmp = 0 ; cmp == 0 && i < Py_SIZE(a); ++i) + cmp = PyObject_RichCompareBool(el, PyTuple_GET_ITEM(a, i), + Py_EQ); + return cmp; } static PyObject * tupleitem(register PyTupleObject *a, register Py_ssize_t i) { - if (i < 0 || i >= Py_SIZE(a)) { - PyErr_SetString(PyExc_IndexError, "tuple index out of range"); - return NULL; - } - Py_INCREF(a->ob_item[i]); - return a->ob_item[i]; + if (i < 0 || i >= Py_SIZE(a)) { + PyErr_SetString(PyExc_IndexError, "tuple index out of range"); + return NULL; + } + Py_INCREF(a->ob_item[i]); + return a->ob_item[i]; } static PyObject * -tupleslice(register PyTupleObject *a, register Py_ssize_t ilow, - register Py_ssize_t ihigh) +tupleslice(register PyTupleObject *a, register Py_ssize_t ilow, + register Py_ssize_t ihigh) { - register PyTupleObject *np; - PyObject **src, **dest; - register Py_ssize_t i; - Py_ssize_t len; - if (ilow < 0) - ilow = 0; - if (ihigh > Py_SIZE(a)) - ihigh = Py_SIZE(a); - if (ihigh < ilow) - ihigh = ilow; - if (ilow == 0 && ihigh == Py_SIZE(a) && PyTuple_CheckExact(a)) { - Py_INCREF(a); - return (PyObject *)a; - } - len = ihigh - ilow; - np = (PyTupleObject *)PyTuple_New(len); - if (np == NULL) - return NULL; - src = a->ob_item + ilow; - dest = np->ob_item; - for (i = 0; i < len; i++) { - PyObject *v = src[i]; - Py_INCREF(v); - dest[i] = v; - } - return (PyObject *)np; + register PyTupleObject *np; + PyObject **src, **dest; + register Py_ssize_t i; + Py_ssize_t len; + if (ilow < 0) + ilow = 0; + if (ihigh > Py_SIZE(a)) + ihigh = Py_SIZE(a); + if (ihigh < ilow) + ihigh = ilow; + if (ilow == 0 && ihigh == Py_SIZE(a) && PyTuple_CheckExact(a)) { + Py_INCREF(a); + return (PyObject *)a; + } + len = ihigh - ilow; + np = (PyTupleObject *)PyTuple_New(len); + if (np == NULL) + return NULL; + src = a->ob_item + ilow; + dest = np->ob_item; + for (i = 0; i < len; i++) { + PyObject *v = src[i]; + Py_INCREF(v); + dest[i] = v; + } + return (PyObject *)np; } PyObject * PyTuple_GetSlice(PyObject *op, Py_ssize_t i, Py_ssize_t j) { - if (op == NULL || !PyTuple_Check(op)) { - PyErr_BadInternalCall(); - return NULL; - } - return tupleslice((PyTupleObject *)op, i, j); + if (op == NULL || !PyTuple_Check(op)) { + PyErr_BadInternalCall(); + return NULL; + } + return tupleslice((PyTupleObject *)op, i, j); } static PyObject * tupleconcat(register PyTupleObject *a, register PyObject *bb) { - register Py_ssize_t size; - register Py_ssize_t i; - PyObject **src, **dest; - PyTupleObject *np; - if (!PyTuple_Check(bb)) { - PyErr_Format(PyExc_TypeError, - "can only concatenate tuple (not \"%.200s\") to tuple", - Py_TYPE(bb)->tp_name); - return NULL; - } + register Py_ssize_t size; + register Py_ssize_t i; + PyObject **src, **dest; + PyTupleObject *np; + if (!PyTuple_Check(bb)) { + PyErr_Format(PyExc_TypeError, + "can only concatenate tuple (not \"%.200s\") to tuple", + Py_TYPE(bb)->tp_name); + return NULL; + } #define b ((PyTupleObject *)bb) - size = Py_SIZE(a) + Py_SIZE(b); - if (size < 0) - return PyErr_NoMemory(); - np = (PyTupleObject *) PyTuple_New(size); - if (np == NULL) { - return NULL; - } - src = a->ob_item; - dest = np->ob_item; - for (i = 0; i < Py_SIZE(a); i++) { - PyObject *v = src[i]; - Py_INCREF(v); - dest[i] = v; - } - src = b->ob_item; - dest = np->ob_item + Py_SIZE(a); - for (i = 0; i < Py_SIZE(b); i++) { - PyObject *v = src[i]; - Py_INCREF(v); - dest[i] = v; - } - return (PyObject *)np; + size = Py_SIZE(a) + Py_SIZE(b); + if (size < 0) + return PyErr_NoMemory(); + np = (PyTupleObject *) PyTuple_New(size); + if (np == NULL) { + return NULL; + } + src = a->ob_item; + dest = np->ob_item; + for (i = 0; i < Py_SIZE(a); i++) { + PyObject *v = src[i]; + Py_INCREF(v); + dest[i] = v; + } + src = b->ob_item; + dest = np->ob_item + Py_SIZE(a); + for (i = 0; i < Py_SIZE(b); i++) { + PyObject *v = src[i]; + Py_INCREF(v); + dest[i] = v; + } + return (PyObject *)np; #undef b } static PyObject * tuplerepeat(PyTupleObject *a, Py_ssize_t n) { - Py_ssize_t i, j; - Py_ssize_t size; - PyTupleObject *np; - PyObject **p, **items; - if (n < 0) - n = 0; - if (Py_SIZE(a) == 0 || n == 1) { - if (PyTuple_CheckExact(a)) { - /* Since tuples are immutable, we can return a shared - copy in this case */ - Py_INCREF(a); - return (PyObject *)a; - } - if (Py_SIZE(a) == 0) - return PyTuple_New(0); - } - size = Py_SIZE(a) * n; - if (size/Py_SIZE(a) != n) - return PyErr_NoMemory(); - np = (PyTupleObject *) PyTuple_New(size); - if (np == NULL) - return NULL; - p = np->ob_item; - items = a->ob_item; - for (i = 0; i < n; i++) { - for (j = 0; j < Py_SIZE(a); j++) { - *p = items[j]; - Py_INCREF(*p); - p++; - } - } - return (PyObject *) np; + Py_ssize_t i, j; + Py_ssize_t size; + PyTupleObject *np; + PyObject **p, **items; + if (n < 0) + n = 0; + if (Py_SIZE(a) == 0 || n == 1) { + if (PyTuple_CheckExact(a)) { + /* Since tuples are immutable, we can return a shared + copy in this case */ + Py_INCREF(a); + return (PyObject *)a; + } + if (Py_SIZE(a) == 0) + return PyTuple_New(0); + } + size = Py_SIZE(a) * n; + if (size/Py_SIZE(a) != n) + return PyErr_NoMemory(); + np = (PyTupleObject *) PyTuple_New(size); + if (np == NULL) + return NULL; + p = np->ob_item; + items = a->ob_item; + for (i = 0; i < n; i++) { + for (j = 0; j < Py_SIZE(a); j++) { + *p = items[j]; + Py_INCREF(*p); + p++; + } + } + return (PyObject *) np; } static PyObject * tupleindex(PyTupleObject *self, PyObject *args) { - Py_ssize_t i, start=0, stop=Py_SIZE(self); - PyObject *v; + Py_ssize_t i, start=0, stop=Py_SIZE(self); + PyObject *v; - if (!PyArg_ParseTuple(args, "O|O&O&:index", &v, - _PyEval_SliceIndex, &start, - _PyEval_SliceIndex, &stop)) - return NULL; - if (start < 0) { - start += Py_SIZE(self); - if (start < 0) - start = 0; - } - if (stop < 0) { - stop += Py_SIZE(self); - if (stop < 0) - stop = 0; - } - for (i = start; i < stop && i < Py_SIZE(self); i++) { - int cmp = PyObject_RichCompareBool(self->ob_item[i], v, Py_EQ); - if (cmp > 0) - return PyLong_FromSsize_t(i); - else if (cmp < 0) - return NULL; - } - PyErr_SetString(PyExc_ValueError, "tuple.index(x): x not in tuple"); - return NULL; + if (!PyArg_ParseTuple(args, "O|O&O&:index", &v, + _PyEval_SliceIndex, &start, + _PyEval_SliceIndex, &stop)) + return NULL; + if (start < 0) { + start += Py_SIZE(self); + if (start < 0) + start = 0; + } + if (stop < 0) { + stop += Py_SIZE(self); + if (stop < 0) + stop = 0; + } + for (i = start; i < stop && i < Py_SIZE(self); i++) { + int cmp = PyObject_RichCompareBool(self->ob_item[i], v, Py_EQ); + if (cmp > 0) + return PyLong_FromSsize_t(i); + else if (cmp < 0) + return NULL; + } + PyErr_SetString(PyExc_ValueError, "tuple.index(x): x not in tuple"); + return NULL; } static PyObject * tuplecount(PyTupleObject *self, PyObject *v) { - Py_ssize_t count = 0; - Py_ssize_t i; + Py_ssize_t count = 0; + Py_ssize_t i; - for (i = 0; i < Py_SIZE(self); i++) { - int cmp = PyObject_RichCompareBool(self->ob_item[i], v, Py_EQ); - if (cmp > 0) - count++; - else if (cmp < 0) - return NULL; - } - return PyLong_FromSsize_t(count); + for (i = 0; i < Py_SIZE(self); i++) { + int cmp = PyObject_RichCompareBool(self->ob_item[i], v, Py_EQ); + if (cmp > 0) + count++; + else if (cmp < 0) + return NULL; + } + return PyLong_FromSsize_t(count); } static int tupletraverse(PyTupleObject *o, visitproc visit, void *arg) { - Py_ssize_t i; + Py_ssize_t i; - for (i = Py_SIZE(o); --i >= 0; ) - Py_VISIT(o->ob_item[i]); - return 0; + for (i = Py_SIZE(o); --i >= 0; ) + Py_VISIT(o->ob_item[i]); + return 0; } static PyObject * tuplerichcompare(PyObject *v, PyObject *w, int op) { - PyTupleObject *vt, *wt; - Py_ssize_t i; - Py_ssize_t vlen, wlen; - - if (!PyTuple_Check(v) || !PyTuple_Check(w)) { - Py_INCREF(Py_NotImplemented); - return Py_NotImplemented; - } - - vt = (PyTupleObject *)v; - wt = (PyTupleObject *)w; - - vlen = Py_SIZE(vt); - wlen = Py_SIZE(wt); - - /* Note: the corresponding code for lists has an "early out" test - * here when op is EQ or NE and the lengths differ. That pays there, - * but Tim was unable to find any real code where EQ/NE tuple - * compares don't have the same length, so testing for it here would - * have cost without benefit. - */ - - /* Search for the first index where items are different. - * Note that because tuples are immutable, it's safe to reuse - * vlen and wlen across the comparison calls. - */ - for (i = 0; i < vlen && i < wlen; i++) { - int k = PyObject_RichCompareBool(vt->ob_item[i], - wt->ob_item[i], Py_EQ); - if (k < 0) - return NULL; - if (!k) - break; - } - - if (i >= vlen || i >= wlen) { - /* No more items to compare -- compare sizes */ - int cmp; - PyObject *res; - switch (op) { - case Py_LT: cmp = vlen < wlen; break; - case Py_LE: cmp = vlen <= wlen; break; - case Py_EQ: cmp = vlen == wlen; break; - case Py_NE: cmp = vlen != wlen; break; - case Py_GT: cmp = vlen > wlen; break; - case Py_GE: cmp = vlen >= wlen; break; - default: return NULL; /* cannot happen */ - } - if (cmp) - res = Py_True; - else - res = Py_False; - Py_INCREF(res); - return res; - } - - /* We have an item that differs -- shortcuts for EQ/NE */ - if (op == Py_EQ) { - Py_INCREF(Py_False); - return Py_False; - } - if (op == Py_NE) { - Py_INCREF(Py_True); - return Py_True; - } + PyTupleObject *vt, *wt; + Py_ssize_t i; + Py_ssize_t vlen, wlen; + + if (!PyTuple_Check(v) || !PyTuple_Check(w)) { + Py_INCREF(Py_NotImplemented); + return Py_NotImplemented; + } + + vt = (PyTupleObject *)v; + wt = (PyTupleObject *)w; + + vlen = Py_SIZE(vt); + wlen = Py_SIZE(wt); + + /* Note: the corresponding code for lists has an "early out" test + * here when op is EQ or NE and the lengths differ. That pays there, + * but Tim was unable to find any real code where EQ/NE tuple + * compares don't have the same length, so testing for it here would + * have cost without benefit. + */ + + /* Search for the first index where items are different. + * Note that because tuples are immutable, it's safe to reuse + * vlen and wlen across the comparison calls. + */ + for (i = 0; i < vlen && i < wlen; i++) { + int k = PyObject_RichCompareBool(vt->ob_item[i], + wt->ob_item[i], Py_EQ); + if (k < 0) + return NULL; + if (!k) + break; + } + + if (i >= vlen || i >= wlen) { + /* No more items to compare -- compare sizes */ + int cmp; + PyObject *res; + switch (op) { + case Py_LT: cmp = vlen < wlen; break; + case Py_LE: cmp = vlen <= wlen; break; + case Py_EQ: cmp = vlen == wlen; break; + case Py_NE: cmp = vlen != wlen; break; + case Py_GT: cmp = vlen > wlen; break; + case Py_GE: cmp = vlen >= wlen; break; + default: return NULL; /* cannot happen */ + } + if (cmp) + res = Py_True; + else + res = Py_False; + Py_INCREF(res); + return res; + } + + /* We have an item that differs -- shortcuts for EQ/NE */ + if (op == Py_EQ) { + Py_INCREF(Py_False); + return Py_False; + } + if (op == Py_NE) { + Py_INCREF(Py_True); + return Py_True; + } - /* Compare the final item again using the proper operator */ - return PyObject_RichCompare(vt->ob_item[i], wt->ob_item[i], op); + /* Compare the final item again using the proper operator */ + return PyObject_RichCompare(vt->ob_item[i], wt->ob_item[i], op); } static PyObject * @@ -618,41 +618,41 @@ static PyObject * tuple_new(PyTypeObject *type, PyObject *args, PyObject *kwds) { - PyObject *arg = NULL; - static char *kwlist[] = {"sequence", 0}; + PyObject *arg = NULL; + static char *kwlist[] = {"sequence", 0}; - if (type != &PyTuple_Type) - return tuple_subtype_new(type, args, kwds); - if (!PyArg_ParseTupleAndKeywords(args, kwds, "|O:tuple", kwlist, &arg)) - return NULL; - - if (arg == NULL) - return PyTuple_New(0); - else - return PySequence_Tuple(arg); + if (type != &PyTuple_Type) + return tuple_subtype_new(type, args, kwds); + if (!PyArg_ParseTupleAndKeywords(args, kwds, "|O:tuple", kwlist, &arg)) + return NULL; + + if (arg == NULL) + return PyTuple_New(0); + else + return PySequence_Tuple(arg); } static PyObject * tuple_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds) { - PyObject *tmp, *newobj, *item; - Py_ssize_t i, n; + PyObject *tmp, *newobj, *item; + Py_ssize_t i, n; - assert(PyType_IsSubtype(type, &PyTuple_Type)); - tmp = tuple_new(&PyTuple_Type, args, kwds); - if (tmp == NULL) - return NULL; - assert(PyTuple_Check(tmp)); - newobj = type->tp_alloc(type, n = PyTuple_GET_SIZE(tmp)); - if (newobj == NULL) - return NULL; - for (i = 0; i < n; i++) { - item = PyTuple_GET_ITEM(tmp, i); - Py_INCREF(item); - PyTuple_SET_ITEM(newobj, i, item); - } - Py_DECREF(tmp); - return newobj; + assert(PyType_IsSubtype(type, &PyTuple_Type)); + tmp = tuple_new(&PyTuple_Type, args, kwds); + if (tmp == NULL) + return NULL; + assert(PyTuple_Check(tmp)); + newobj = type->tp_alloc(type, n = PyTuple_GET_SIZE(tmp)); + if (newobj == NULL) + return NULL; + for (i = 0; i < n; i++) { + item = PyTuple_GET_ITEM(tmp, i); + Py_INCREF(item); + PyTuple_SET_ITEM(newobj, i, item); + } + Py_DECREF(tmp); + return newobj; } PyDoc_STRVAR(tuple_doc, @@ -662,86 +662,86 @@ If the argument is a tuple, the return value is the same object."); static PySequenceMethods tuple_as_sequence = { - (lenfunc)tuplelength, /* sq_length */ - (binaryfunc)tupleconcat, /* sq_concat */ - (ssizeargfunc)tuplerepeat, /* sq_repeat */ - (ssizeargfunc)tupleitem, /* sq_item */ - 0, /* sq_slice */ - 0, /* sq_ass_item */ - 0, /* sq_ass_slice */ - (objobjproc)tuplecontains, /* sq_contains */ + (lenfunc)tuplelength, /* sq_length */ + (binaryfunc)tupleconcat, /* sq_concat */ + (ssizeargfunc)tuplerepeat, /* sq_repeat */ + (ssizeargfunc)tupleitem, /* sq_item */ + 0, /* sq_slice */ + 0, /* sq_ass_item */ + 0, /* sq_ass_slice */ + (objobjproc)tuplecontains, /* sq_contains */ }; static PyObject* tuplesubscript(PyTupleObject* 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 += PyTuple_GET_SIZE(self); - return tupleitem(self, i); - } - else if (PySlice_Check(item)) { - Py_ssize_t start, stop, step, slicelength, cur, i; - PyObject* result; - PyObject* it; - PyObject **src, **dest; - - if (PySlice_GetIndicesEx((PySliceObject*)item, - PyTuple_GET_SIZE(self), - &start, &stop, &step, &slicelength) < 0) { - return NULL; - } - - if (slicelength <= 0) { - return PyTuple_New(0); - } - else if (start == 0 && step == 1 && - slicelength == PyTuple_GET_SIZE(self) && - PyTuple_CheckExact(self)) { - Py_INCREF(self); - return (PyObject *)self; - } - else { - result = PyTuple_New(slicelength); - if (!result) return NULL; - - src = self->ob_item; - dest = ((PyTupleObject *)result)->ob_item; - for (cur = start, i = 0; i < slicelength; - cur += step, i++) { - it = src[cur]; - Py_INCREF(it); - dest[i] = it; - } - - return result; - } - } - else { - PyErr_Format(PyExc_TypeError, - "tuple indices must be integers, not %.200s", - Py_TYPE(item)->tp_name); - return NULL; - } + 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 += PyTuple_GET_SIZE(self); + return tupleitem(self, i); + } + else if (PySlice_Check(item)) { + Py_ssize_t start, stop, step, slicelength, cur, i; + PyObject* result; + PyObject* it; + PyObject **src, **dest; + + if (PySlice_GetIndicesEx((PySliceObject*)item, + PyTuple_GET_SIZE(self), + &start, &stop, &step, &slicelength) < 0) { + return NULL; + } + + if (slicelength <= 0) { + return PyTuple_New(0); + } + else if (start == 0 && step == 1 && + slicelength == PyTuple_GET_SIZE(self) && + PyTuple_CheckExact(self)) { + Py_INCREF(self); + return (PyObject *)self; + } + else { + result = PyTuple_New(slicelength); + if (!result) return NULL; + + src = self->ob_item; + dest = ((PyTupleObject *)result)->ob_item; + for (cur = start, i = 0; i < slicelength; + cur += step, i++) { + it = src[cur]; + Py_INCREF(it); + dest[i] = it; + } + + return result; + } + } + else { + PyErr_Format(PyExc_TypeError, + "tuple indices must be integers, not %.200s", + Py_TYPE(item)->tp_name); + return NULL; + } } static PyObject * tuple_getnewargs(PyTupleObject *v) { - return Py_BuildValue("(N)", tupleslice(v, 0, Py_SIZE(v))); - + return Py_BuildValue("(N)", tupleslice(v, 0, Py_SIZE(v))); + } static PyObject * tuple_sizeof(PyTupleObject *self) { - Py_ssize_t res; + Py_ssize_t res; - res = PyTuple_Type.tp_basicsize + Py_SIZE(self) * sizeof(PyObject *); - return PyLong_FromSsize_t(res); + res = PyTuple_Type.tp_basicsize + Py_SIZE(self) * sizeof(PyObject *); + return PyLong_FromSsize_t(res); } PyDoc_STRVAR(index_doc, @@ -754,62 +754,62 @@ "T.__sizeof__() -- size of T in memory, in bytes"); static PyMethodDef tuple_methods[] = { - {"__getnewargs__", (PyCFunction)tuple_getnewargs, METH_NOARGS}, - {"__sizeof__", (PyCFunction)tuple_sizeof, METH_NOARGS, sizeof_doc}, - {"index", (PyCFunction)tupleindex, METH_VARARGS, index_doc}, - {"count", (PyCFunction)tuplecount, METH_O, count_doc}, - {NULL, NULL} /* sentinel */ + {"__getnewargs__", (PyCFunction)tuple_getnewargs, METH_NOARGS}, + {"__sizeof__", (PyCFunction)tuple_sizeof, METH_NOARGS, sizeof_doc}, + {"index", (PyCFunction)tupleindex, METH_VARARGS, index_doc}, + {"count", (PyCFunction)tuplecount, METH_O, count_doc}, + {NULL, NULL} /* sentinel */ }; static PyMappingMethods tuple_as_mapping = { - (lenfunc)tuplelength, - (binaryfunc)tuplesubscript, - 0 + (lenfunc)tuplelength, + (binaryfunc)tuplesubscript, + 0 }; static PyObject *tuple_iter(PyObject *seq); PyTypeObject PyTuple_Type = { - PyVarObject_HEAD_INIT(&PyType_Type, 0) - "tuple", - sizeof(PyTupleObject) - sizeof(PyObject *), - sizeof(PyObject *), - (destructor)tupledealloc, /* tp_dealloc */ - 0, /* tp_print */ - 0, /* tp_getattr */ - 0, /* tp_setattr */ - 0, /* tp_reserved */ - (reprfunc)tuplerepr, /* tp_repr */ - 0, /* tp_as_number */ - &tuple_as_sequence, /* tp_as_sequence */ - &tuple_as_mapping, /* tp_as_mapping */ - (hashfunc)tuplehash, /* 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 | - Py_TPFLAGS_BASETYPE | Py_TPFLAGS_TUPLE_SUBCLASS, /* tp_flags */ - tuple_doc, /* tp_doc */ - (traverseproc)tupletraverse, /* tp_traverse */ - 0, /* tp_clear */ - tuplerichcompare, /* tp_richcompare */ - 0, /* tp_weaklistoffset */ - tuple_iter, /* tp_iter */ - 0, /* tp_iternext */ - tuple_methods, /* tp_methods */ - 0, /* tp_members */ - 0, /* tp_getset */ - 0, /* tp_base */ - 0, /* tp_dict */ - 0, /* tp_descr_get */ - 0, /* tp_descr_set */ - 0, /* tp_dictoffset */ - 0, /* tp_init */ - 0, /* tp_alloc */ - tuple_new, /* tp_new */ - PyObject_GC_Del, /* tp_free */ + PyVarObject_HEAD_INIT(&PyType_Type, 0) + "tuple", + sizeof(PyTupleObject) - sizeof(PyObject *), + sizeof(PyObject *), + (destructor)tupledealloc, /* tp_dealloc */ + 0, /* tp_print */ + 0, /* tp_getattr */ + 0, /* tp_setattr */ + 0, /* tp_reserved */ + (reprfunc)tuplerepr, /* tp_repr */ + 0, /* tp_as_number */ + &tuple_as_sequence, /* tp_as_sequence */ + &tuple_as_mapping, /* tp_as_mapping */ + (hashfunc)tuplehash, /* 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 | + Py_TPFLAGS_BASETYPE | Py_TPFLAGS_TUPLE_SUBCLASS, /* tp_flags */ + tuple_doc, /* tp_doc */ + (traverseproc)tupletraverse, /* tp_traverse */ + 0, /* tp_clear */ + tuplerichcompare, /* tp_richcompare */ + 0, /* tp_weaklistoffset */ + tuple_iter, /* tp_iter */ + 0, /* tp_iternext */ + tuple_methods, /* tp_methods */ + 0, /* tp_members */ + 0, /* tp_getset */ + 0, /* tp_base */ + 0, /* tp_dict */ + 0, /* tp_descr_get */ + 0, /* tp_descr_set */ + 0, /* tp_dictoffset */ + 0, /* tp_init */ + 0, /* tp_alloc */ + tuple_new, /* tp_new */ + PyObject_GC_Del, /* tp_free */ }; /* The following function breaks the notion that tuples are immutable: @@ -822,207 +822,207 @@ int _PyTuple_Resize(PyObject **pv, Py_ssize_t newsize) { - register PyTupleObject *v; - register PyTupleObject *sv; - Py_ssize_t i; - Py_ssize_t oldsize; - - v = (PyTupleObject *) *pv; - if (v == NULL || Py_TYPE(v) != &PyTuple_Type || - (Py_SIZE(v) != 0 && Py_REFCNT(v) != 1)) { - *pv = 0; - Py_XDECREF(v); - PyErr_BadInternalCall(); - return -1; - } - oldsize = Py_SIZE(v); - if (oldsize == newsize) - return 0; - - if (oldsize == 0) { - /* Empty tuples are often shared, so we should never - resize them in-place even if we do own the only - (current) reference */ - Py_DECREF(v); - *pv = PyTuple_New(newsize); - return *pv == NULL ? -1 : 0; - } - - /* XXX UNREF/NEWREF interface should be more symmetrical */ - _Py_DEC_REFTOTAL; - if (_PyObject_GC_IS_TRACKED(v)) - _PyObject_GC_UNTRACK(v); - _Py_ForgetReference((PyObject *) v); - /* DECREF items deleted by shrinkage */ - for (i = newsize; i < oldsize; i++) { - Py_XDECREF(v->ob_item[i]); - v->ob_item[i] = NULL; - } - sv = PyObject_GC_Resize(PyTupleObject, v, newsize); - if (sv == NULL) { - *pv = NULL; - PyObject_GC_Del(v); - return -1; - } - _Py_NewReference((PyObject *) sv); - /* Zero out items added by growing */ - if (newsize > oldsize) - memset(&sv->ob_item[oldsize], 0, - sizeof(*sv->ob_item) * (newsize - oldsize)); - *pv = (PyObject *) sv; - _PyObject_GC_TRACK(sv); - return 0; + register PyTupleObject *v; + register PyTupleObject *sv; + Py_ssize_t i; + Py_ssize_t oldsize; + + v = (PyTupleObject *) *pv; + if (v == NULL || Py_TYPE(v) != &PyTuple_Type || + (Py_SIZE(v) != 0 && Py_REFCNT(v) != 1)) { + *pv = 0; + Py_XDECREF(v); + PyErr_BadInternalCall(); + return -1; + } + oldsize = Py_SIZE(v); + if (oldsize == newsize) + return 0; + + if (oldsize == 0) { + /* Empty tuples are often shared, so we should never + resize them in-place even if we do own the only + (current) reference */ + Py_DECREF(v); + *pv = PyTuple_New(newsize); + return *pv == NULL ? -1 : 0; + } + + /* XXX UNREF/NEWREF interface should be more symmetrical */ + _Py_DEC_REFTOTAL; + if (_PyObject_GC_IS_TRACKED(v)) + _PyObject_GC_UNTRACK(v); + _Py_ForgetReference((PyObject *) v); + /* DECREF items deleted by shrinkage */ + for (i = newsize; i < oldsize; i++) { + Py_XDECREF(v->ob_item[i]); + v->ob_item[i] = NULL; + } + sv = PyObject_GC_Resize(PyTupleObject, v, newsize); + if (sv == NULL) { + *pv = NULL; + PyObject_GC_Del(v); + return -1; + } + _Py_NewReference((PyObject *) sv); + /* Zero out items added by growing */ + if (newsize > oldsize) + memset(&sv->ob_item[oldsize], 0, + sizeof(*sv->ob_item) * (newsize - oldsize)); + *pv = (PyObject *) sv; + _PyObject_GC_TRACK(sv); + return 0; } int PyTuple_ClearFreeList(void) { - int freelist_size = 0; + int freelist_size = 0; #if PyTuple_MAXSAVESIZE > 0 - int i; - for (i = 1; i < PyTuple_MAXSAVESIZE; i++) { - PyTupleObject *p, *q; - p = free_list[i]; - freelist_size += numfree[i]; - free_list[i] = NULL; - numfree[i] = 0; - while (p) { - q = p; - p = (PyTupleObject *)(p->ob_item[0]); - PyObject_GC_Del(q); - } - } + int i; + for (i = 1; i < PyTuple_MAXSAVESIZE; i++) { + PyTupleObject *p, *q; + p = free_list[i]; + freelist_size += numfree[i]; + free_list[i] = NULL; + numfree[i] = 0; + while (p) { + q = p; + p = (PyTupleObject *)(p->ob_item[0]); + PyObject_GC_Del(q); + } + } #endif - return freelist_size; + return freelist_size; } - + void PyTuple_Fini(void) { #if PyTuple_MAXSAVESIZE > 0 - /* empty tuples are used all over the place and applications may - * rely on the fact that an empty tuple is a singleton. */ - Py_XDECREF(free_list[0]); - free_list[0] = NULL; + /* empty tuples are used all over the place and applications may + * rely on the fact that an empty tuple is a singleton. */ + Py_XDECREF(free_list[0]); + free_list[0] = NULL; - (void)PyTuple_ClearFreeList(); + (void)PyTuple_ClearFreeList(); #endif #ifdef SHOW_TRACK_COUNT - show_track(); + show_track(); #endif } /*********************** Tuple Iterator **************************/ typedef struct { - PyObject_HEAD - long it_index; - PyTupleObject *it_seq; /* Set to NULL when iterator is exhausted */ + PyObject_HEAD + long it_index; + PyTupleObject *it_seq; /* Set to NULL when iterator is exhausted */ } tupleiterobject; static void tupleiter_dealloc(tupleiterobject *it) { - _PyObject_GC_UNTRACK(it); - Py_XDECREF(it->it_seq); - PyObject_GC_Del(it); + _PyObject_GC_UNTRACK(it); + Py_XDECREF(it->it_seq); + PyObject_GC_Del(it); } static int tupleiter_traverse(tupleiterobject *it, visitproc visit, void *arg) { - Py_VISIT(it->it_seq); - return 0; + Py_VISIT(it->it_seq); + return 0; } static PyObject * tupleiter_next(tupleiterobject *it) { - PyTupleObject *seq; - PyObject *item; + PyTupleObject *seq; + PyObject *item; - assert(it != NULL); - seq = it->it_seq; - if (seq == NULL) - return NULL; - assert(PyTuple_Check(seq)); - - if (it->it_index < PyTuple_GET_SIZE(seq)) { - item = PyTuple_GET_ITEM(seq, it->it_index); - ++it->it_index; - Py_INCREF(item); - return item; - } - - Py_DECREF(seq); - it->it_seq = NULL; - return NULL; + assert(it != NULL); + seq = it->it_seq; + if (seq == NULL) + return NULL; + assert(PyTuple_Check(seq)); + + if (it->it_index < PyTuple_GET_SIZE(seq)) { + item = PyTuple_GET_ITEM(seq, it->it_index); + ++it->it_index; + Py_INCREF(item); + return item; + } + + Py_DECREF(seq); + it->it_seq = NULL; + return NULL; } static PyObject * tupleiter_len(tupleiterobject *it) { - Py_ssize_t len = 0; - if (it->it_seq) - len = PyTuple_GET_SIZE(it->it_seq) - it->it_index; - return PyLong_FromSsize_t(len); + Py_ssize_t len = 0; + if (it->it_seq) + len = PyTuple_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 PyMethodDef tupleiter_methods[] = { - {"__length_hint__", (PyCFunction)tupleiter_len, METH_NOARGS, length_hint_doc}, - {NULL, NULL} /* sentinel */ + {"__length_hint__", (PyCFunction)tupleiter_len, METH_NOARGS, length_hint_doc}, + {NULL, NULL} /* sentinel */ }; PyTypeObject PyTupleIter_Type = { - PyVarObject_HEAD_INIT(&PyType_Type, 0) - "tuple_iterator", /* tp_name */ - sizeof(tupleiterobject), /* tp_basicsize */ - 0, /* tp_itemsize */ - /* methods */ - (destructor)tupleiter_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)tupleiter_traverse, /* tp_traverse */ - 0, /* tp_clear */ - 0, /* tp_richcompare */ - 0, /* tp_weaklistoffset */ - PyObject_SelfIter, /* tp_iter */ - (iternextfunc)tupleiter_next, /* tp_iternext */ - tupleiter_methods, /* tp_methods */ - 0, + PyVarObject_HEAD_INIT(&PyType_Type, 0) + "tuple_iterator", /* tp_name */ + sizeof(tupleiterobject), /* tp_basicsize */ + 0, /* tp_itemsize */ + /* methods */ + (destructor)tupleiter_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)tupleiter_traverse, /* tp_traverse */ + 0, /* tp_clear */ + 0, /* tp_richcompare */ + 0, /* tp_weaklistoffset */ + PyObject_SelfIter, /* tp_iter */ + (iternextfunc)tupleiter_next, /* tp_iternext */ + tupleiter_methods, /* tp_methods */ + 0, }; static PyObject * tuple_iter(PyObject *seq) { - tupleiterobject *it; + tupleiterobject *it; - if (!PyTuple_Check(seq)) { - PyErr_BadInternalCall(); - return NULL; - } - it = PyObject_GC_New(tupleiterobject, &PyTupleIter_Type); - if (it == NULL) - return NULL; - it->it_index = 0; - Py_INCREF(seq); - it->it_seq = (PyTupleObject *)seq; - _PyObject_GC_TRACK(it); - return (PyObject *)it; + if (!PyTuple_Check(seq)) { + PyErr_BadInternalCall(); + return NULL; + } + it = PyObject_GC_New(tupleiterobject, &PyTupleIter_Type); + if (it == NULL) + return NULL; + it->it_index = 0; + Py_INCREF(seq); + it->it_seq = (PyTupleObject *)seq; + _PyObject_GC_TRACK(it); + return (PyObject *)it; } Modified: python/branches/release31-maint/Objects/typeobject.c ============================================================================== --- python/branches/release31-maint/Objects/typeobject.c (original) +++ python/branches/release31-maint/Objects/typeobject.c Sun May 9 18:14:21 2010 @@ -13,22 +13,22 @@ they normally would. This is why the maximum size is limited to MCACHE_MAX_ATTR_SIZE, since it might be a problem if very large strings are used as attribute names. */ -#define MCACHE_MAX_ATTR_SIZE 100 -#define MCACHE_SIZE_EXP 10 -#define MCACHE_HASH(version, name_hash) \ - (((unsigned int)(version) * (unsigned int)(name_hash)) \ - >> (8*sizeof(unsigned int) - MCACHE_SIZE_EXP)) +#define MCACHE_MAX_ATTR_SIZE 100 +#define MCACHE_SIZE_EXP 10 +#define MCACHE_HASH(version, name_hash) \ + (((unsigned int)(version) * (unsigned int)(name_hash)) \ + >> (8*sizeof(unsigned int) - MCACHE_SIZE_EXP)) #define MCACHE_HASH_METHOD(type, name) \ - MCACHE_HASH((type)->tp_version_tag, \ - ((PyUnicodeObject *)(name))->hash) + MCACHE_HASH((type)->tp_version_tag, \ + ((PyUnicodeObject *)(name))->hash) #define MCACHE_CACHEABLE_NAME(name) \ - PyUnicode_CheckExact(name) && \ - PyUnicode_GET_SIZE(name) <= MCACHE_MAX_ATTR_SIZE + PyUnicode_CheckExact(name) && \ + PyUnicode_GET_SIZE(name) <= MCACHE_MAX_ATTR_SIZE struct method_cache_entry { - unsigned int version; - PyObject *name; /* reference to exactly a str or None */ - PyObject *value; /* borrowed */ + unsigned int version; + PyObject *name; /* reference to exactly a str or None */ + PyObject *value; /* borrowed */ }; static struct method_cache_entry method_cache[1 << MCACHE_SIZE_EXP]; @@ -37,325 +37,325 @@ unsigned int PyType_ClearCache(void) { - Py_ssize_t i; - unsigned int cur_version_tag = next_version_tag - 1; - - for (i = 0; i < (1 << MCACHE_SIZE_EXP); i++) { - method_cache[i].version = 0; - Py_CLEAR(method_cache[i].name); - method_cache[i].value = NULL; - } - next_version_tag = 0; - /* mark all version tags as invalid */ - PyType_Modified(&PyBaseObject_Type); - return cur_version_tag; + Py_ssize_t i; + unsigned int cur_version_tag = next_version_tag - 1; + + for (i = 0; i < (1 << MCACHE_SIZE_EXP); i++) { + method_cache[i].version = 0; + Py_CLEAR(method_cache[i].name); + method_cache[i].value = NULL; + } + next_version_tag = 0; + /* mark all version tags as invalid */ + PyType_Modified(&PyBaseObject_Type); + return cur_version_tag; } void PyType_Modified(PyTypeObject *type) { - /* Invalidate any cached data for the specified type and all - subclasses. This function is called after the base - classes, mro, or attributes of the type are altered. - - Invariants: - - - Py_TPFLAGS_VALID_VERSION_TAG is never set if - Py_TPFLAGS_HAVE_VERSION_TAG is not set (e.g. on type - objects coming from non-recompiled extension modules) - - - before Py_TPFLAGS_VALID_VERSION_TAG can be set on a type, - it must first be set on all super types. - - This function clears the Py_TPFLAGS_VALID_VERSION_TAG of a - type (so it must first clear it on all subclasses). The - tp_version_tag value is meaningless unless this flag is set. - We don't assign new version tags eagerly, but only as - needed. - */ - PyObject *raw, *ref; - Py_ssize_t i, n; - - if (!PyType_HasFeature(type, Py_TPFLAGS_VALID_VERSION_TAG)) - return; - - raw = type->tp_subclasses; - if (raw != NULL) { - n = PyList_GET_SIZE(raw); - for (i = 0; i < n; i++) { - ref = PyList_GET_ITEM(raw, i); - ref = PyWeakref_GET_OBJECT(ref); - if (ref != Py_None) { - PyType_Modified((PyTypeObject *)ref); - } - } - } - type->tp_flags &= ~Py_TPFLAGS_VALID_VERSION_TAG; + /* Invalidate any cached data for the specified type and all + subclasses. This function is called after the base + classes, mro, or attributes of the type are altered. + + Invariants: + + - Py_TPFLAGS_VALID_VERSION_TAG is never set if + Py_TPFLAGS_HAVE_VERSION_TAG is not set (e.g. on type + objects coming from non-recompiled extension modules) + + - before Py_TPFLAGS_VALID_VERSION_TAG can be set on a type, + it must first be set on all super types. + + This function clears the Py_TPFLAGS_VALID_VERSION_TAG of a + type (so it must first clear it on all subclasses). The + tp_version_tag value is meaningless unless this flag is set. + We don't assign new version tags eagerly, but only as + needed. + */ + PyObject *raw, *ref; + Py_ssize_t i, n; + + if (!PyType_HasFeature(type, Py_TPFLAGS_VALID_VERSION_TAG)) + return; + + raw = type->tp_subclasses; + if (raw != NULL) { + n = PyList_GET_SIZE(raw); + for (i = 0; i < n; i++) { + ref = PyList_GET_ITEM(raw, i); + ref = PyWeakref_GET_OBJECT(ref); + if (ref != Py_None) { + PyType_Modified((PyTypeObject *)ref); + } + } + } + type->tp_flags &= ~Py_TPFLAGS_VALID_VERSION_TAG; } static void type_mro_modified(PyTypeObject *type, PyObject *bases) { - /* - Check that all base classes or elements of the mro of type are - able to be cached. This function is called after the base - classes or mro of the type are altered. - - Unset HAVE_VERSION_TAG and VALID_VERSION_TAG if the type - inherits from an old-style class, either directly or if it - appears in the MRO of a new-style class. No support either for - custom MROs that include types that are not officially super - types. - - Called from mro_internal, which will subsequently be called on - each subclass when their mro is recursively updated. - */ - Py_ssize_t i, n; - int clear = 0; - - if (!PyType_HasFeature(type, Py_TPFLAGS_HAVE_VERSION_TAG)) - return; - - n = PyTuple_GET_SIZE(bases); - for (i = 0; i < n; i++) { - PyObject *b = PyTuple_GET_ITEM(bases, i); - PyTypeObject *cls; - - if (!PyType_Check(b) ) { - clear = 1; - break; - } - - cls = (PyTypeObject *)b; - - if (!PyType_HasFeature(cls, Py_TPFLAGS_HAVE_VERSION_TAG) || - !PyType_IsSubtype(type, cls)) { - clear = 1; - break; - } - } - - if (clear) - type->tp_flags &= ~(Py_TPFLAGS_HAVE_VERSION_TAG| - Py_TPFLAGS_VALID_VERSION_TAG); + /* + Check that all base classes or elements of the mro of type are + able to be cached. This function is called after the base + classes or mro of the type are altered. + + Unset HAVE_VERSION_TAG and VALID_VERSION_TAG if the type + inherits from an old-style class, either directly or if it + appears in the MRO of a new-style class. No support either for + custom MROs that include types that are not officially super + types. + + Called from mro_internal, which will subsequently be called on + each subclass when their mro is recursively updated. + */ + Py_ssize_t i, n; + int clear = 0; + + if (!PyType_HasFeature(type, Py_TPFLAGS_HAVE_VERSION_TAG)) + return; + + n = PyTuple_GET_SIZE(bases); + for (i = 0; i < n; i++) { + PyObject *b = PyTuple_GET_ITEM(bases, i); + PyTypeObject *cls; + + if (!PyType_Check(b) ) { + clear = 1; + break; + } + + cls = (PyTypeObject *)b; + + if (!PyType_HasFeature(cls, Py_TPFLAGS_HAVE_VERSION_TAG) || + !PyType_IsSubtype(type, cls)) { + clear = 1; + break; + } + } + + if (clear) + type->tp_flags &= ~(Py_TPFLAGS_HAVE_VERSION_TAG| + Py_TPFLAGS_VALID_VERSION_TAG); } static int assign_version_tag(PyTypeObject *type) { - /* Ensure that the tp_version_tag is valid and set - Py_TPFLAGS_VALID_VERSION_TAG. To respect the invariant, this - must first be done on all super classes. Return 0 if this - cannot be done, 1 if Py_TPFLAGS_VALID_VERSION_TAG. - */ - Py_ssize_t i, n; - PyObject *bases; - - if (PyType_HasFeature(type, Py_TPFLAGS_VALID_VERSION_TAG)) - return 1; - if (!PyType_HasFeature(type, Py_TPFLAGS_HAVE_VERSION_TAG)) - return 0; - if (!PyType_HasFeature(type, Py_TPFLAGS_READY)) - return 0; - - type->tp_version_tag = next_version_tag++; - /* for stress-testing: next_version_tag &= 0xFF; */ - - if (type->tp_version_tag == 0) { - /* wrap-around or just starting Python - clear the whole - cache by filling names with references to Py_None. - Values are also set to NULL for added protection, as they - are borrowed reference */ - for (i = 0; i < (1 << MCACHE_SIZE_EXP); i++) { - method_cache[i].value = NULL; - Py_XDECREF(method_cache[i].name); - method_cache[i].name = Py_None; - Py_INCREF(Py_None); - } - /* mark all version tags as invalid */ - PyType_Modified(&PyBaseObject_Type); - return 1; - } - bases = type->tp_bases; - n = PyTuple_GET_SIZE(bases); - for (i = 0; i < n; i++) { - PyObject *b = PyTuple_GET_ITEM(bases, i); - assert(PyType_Check(b)); - if (!assign_version_tag((PyTypeObject *)b)) - return 0; - } - type->tp_flags |= Py_TPFLAGS_VALID_VERSION_TAG; - return 1; + /* Ensure that the tp_version_tag is valid and set + Py_TPFLAGS_VALID_VERSION_TAG. To respect the invariant, this + must first be done on all super classes. Return 0 if this + cannot be done, 1 if Py_TPFLAGS_VALID_VERSION_TAG. + */ + Py_ssize_t i, n; + PyObject *bases; + + if (PyType_HasFeature(type, Py_TPFLAGS_VALID_VERSION_TAG)) + return 1; + if (!PyType_HasFeature(type, Py_TPFLAGS_HAVE_VERSION_TAG)) + return 0; + if (!PyType_HasFeature(type, Py_TPFLAGS_READY)) + return 0; + + type->tp_version_tag = next_version_tag++; + /* for stress-testing: next_version_tag &= 0xFF; */ + + if (type->tp_version_tag == 0) { + /* wrap-around or just starting Python - clear the whole + cache by filling names with references to Py_None. + Values are also set to NULL for added protection, as they + are borrowed reference */ + for (i = 0; i < (1 << MCACHE_SIZE_EXP); i++) { + method_cache[i].value = NULL; + Py_XDECREF(method_cache[i].name); + method_cache[i].name = Py_None; + Py_INCREF(Py_None); + } + /* mark all version tags as invalid */ + PyType_Modified(&PyBaseObject_Type); + return 1; + } + bases = type->tp_bases; + n = PyTuple_GET_SIZE(bases); + for (i = 0; i < n; i++) { + PyObject *b = PyTuple_GET_ITEM(bases, i); + assert(PyType_Check(b)); + if (!assign_version_tag((PyTypeObject *)b)) + return 0; + } + type->tp_flags |= Py_TPFLAGS_VALID_VERSION_TAG; + return 1; } static PyMemberDef type_members[] = { - {"__basicsize__", T_INT, offsetof(PyTypeObject,tp_basicsize),READONLY}, - {"__itemsize__", T_INT, offsetof(PyTypeObject, tp_itemsize), READONLY}, - {"__flags__", T_LONG, offsetof(PyTypeObject, tp_flags), READONLY}, - {"__weakrefoffset__", T_LONG, - offsetof(PyTypeObject, tp_weaklistoffset), READONLY}, - {"__base__", T_OBJECT, offsetof(PyTypeObject, tp_base), READONLY}, - {"__dictoffset__", T_LONG, - offsetof(PyTypeObject, tp_dictoffset), READONLY}, - {"__mro__", T_OBJECT, offsetof(PyTypeObject, tp_mro), READONLY}, - {0} + {"__basicsize__", T_INT, offsetof(PyTypeObject,tp_basicsize),READONLY}, + {"__itemsize__", T_INT, offsetof(PyTypeObject, tp_itemsize), READONLY}, + {"__flags__", T_LONG, offsetof(PyTypeObject, tp_flags), READONLY}, + {"__weakrefoffset__", T_LONG, + offsetof(PyTypeObject, tp_weaklistoffset), READONLY}, + {"__base__", T_OBJECT, offsetof(PyTypeObject, tp_base), READONLY}, + {"__dictoffset__", T_LONG, + offsetof(PyTypeObject, tp_dictoffset), READONLY}, + {"__mro__", T_OBJECT, offsetof(PyTypeObject, tp_mro), READONLY}, + {0} }; static PyObject * type_name(PyTypeObject *type, void *context) { - const char *s; + const char *s; - if (type->tp_flags & Py_TPFLAGS_HEAPTYPE) { - PyHeapTypeObject* et = (PyHeapTypeObject*)type; + if (type->tp_flags & Py_TPFLAGS_HEAPTYPE) { + PyHeapTypeObject* et = (PyHeapTypeObject*)type; - Py_INCREF(et->ht_name); - return et->ht_name; - } - else { - s = strrchr(type->tp_name, '.'); - if (s == NULL) - s = type->tp_name; - else - s++; - return PyUnicode_FromString(s); - } + Py_INCREF(et->ht_name); + return et->ht_name; + } + else { + s = strrchr(type->tp_name, '.'); + if (s == NULL) + s = type->tp_name; + else + s++; + return PyUnicode_FromString(s); + } } static int type_set_name(PyTypeObject *type, PyObject *value, void *context) { - PyHeapTypeObject* et; - char *tp_name; - PyObject *tmp; - - if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE)) { - PyErr_Format(PyExc_TypeError, - "can't set %s.__name__", type->tp_name); - return -1; - } - if (!value) { - PyErr_Format(PyExc_TypeError, - "can't delete %s.__name__", type->tp_name); - return -1; - } - if (!PyUnicode_Check(value)) { - PyErr_Format(PyExc_TypeError, - "can only assign string to %s.__name__, not '%s'", - type->tp_name, Py_TYPE(value)->tp_name); - return -1; - } - - /* Check absence of null characters */ - tmp = PyUnicode_FromStringAndSize("\0", 1); - if (tmp == NULL) - return -1; - if (PyUnicode_Contains(value, tmp) != 0) { - Py_DECREF(tmp); - PyErr_Format(PyExc_ValueError, - "__name__ must not contain null bytes"); - return -1; - } - Py_DECREF(tmp); - - tp_name = _PyUnicode_AsString(value); - if (tp_name == NULL) - return -1; - - et = (PyHeapTypeObject*)type; + PyHeapTypeObject* et; + char *tp_name; + PyObject *tmp; + + if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE)) { + PyErr_Format(PyExc_TypeError, + "can't set %s.__name__", type->tp_name); + return -1; + } + if (!value) { + PyErr_Format(PyExc_TypeError, + "can't delete %s.__name__", type->tp_name); + return -1; + } + if (!PyUnicode_Check(value)) { + PyErr_Format(PyExc_TypeError, + "can only assign string to %s.__name__, not '%s'", + type->tp_name, Py_TYPE(value)->tp_name); + return -1; + } + + /* Check absence of null characters */ + tmp = PyUnicode_FromStringAndSize("\0", 1); + if (tmp == NULL) + return -1; + if (PyUnicode_Contains(value, tmp) != 0) { + Py_DECREF(tmp); + PyErr_Format(PyExc_ValueError, + "__name__ must not contain null bytes"); + return -1; + } + Py_DECREF(tmp); + + tp_name = _PyUnicode_AsString(value); + if (tp_name == NULL) + return -1; + + et = (PyHeapTypeObject*)type; - Py_INCREF(value); + Py_INCREF(value); - Py_DECREF(et->ht_name); - et->ht_name = value; + Py_DECREF(et->ht_name); + et->ht_name = value; - type->tp_name = tp_name; + type->tp_name = tp_name; - return 0; + return 0; } static PyObject * type_module(PyTypeObject *type, void *context) { - PyObject *mod; - char *s; + PyObject *mod; + char *s; - if (type->tp_flags & Py_TPFLAGS_HEAPTYPE) { - mod = PyDict_GetItemString(type->tp_dict, "__module__"); - if (!mod) { - PyErr_Format(PyExc_AttributeError, "__module__"); - return 0; - } - Py_XINCREF(mod); - return mod; - } - else { - s = strrchr(type->tp_name, '.'); - if (s != NULL) - return PyUnicode_FromStringAndSize( - type->tp_name, (Py_ssize_t)(s - type->tp_name)); - return PyUnicode_FromString("builtins"); - } + if (type->tp_flags & Py_TPFLAGS_HEAPTYPE) { + mod = PyDict_GetItemString(type->tp_dict, "__module__"); + if (!mod) { + PyErr_Format(PyExc_AttributeError, "__module__"); + return 0; + } + Py_XINCREF(mod); + return mod; + } + else { + s = strrchr(type->tp_name, '.'); + if (s != NULL) + return PyUnicode_FromStringAndSize( + type->tp_name, (Py_ssize_t)(s - type->tp_name)); + return PyUnicode_FromString("builtins"); + } } static int type_set_module(PyTypeObject *type, PyObject *value, void *context) { - if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE)) { - PyErr_Format(PyExc_TypeError, - "can't set %s.__module__", type->tp_name); - return -1; - } - if (!value) { - PyErr_Format(PyExc_TypeError, - "can't delete %s.__module__", type->tp_name); - return -1; - } + if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE)) { + PyErr_Format(PyExc_TypeError, + "can't set %s.__module__", type->tp_name); + return -1; + } + if (!value) { + PyErr_Format(PyExc_TypeError, + "can't delete %s.__module__", type->tp_name); + return -1; + } - PyType_Modified(type); + PyType_Modified(type); - return PyDict_SetItemString(type->tp_dict, "__module__", value); + return PyDict_SetItemString(type->tp_dict, "__module__", value); } static PyObject * type_abstractmethods(PyTypeObject *type, void *context) { - PyObject *mod = PyDict_GetItemString(type->tp_dict, - "__abstractmethods__"); - if (!mod) { - PyErr_Format(PyExc_AttributeError, "__abstractmethods__"); - return NULL; - } - Py_XINCREF(mod); - return mod; + PyObject *mod = PyDict_GetItemString(type->tp_dict, + "__abstractmethods__"); + if (!mod) { + PyErr_Format(PyExc_AttributeError, "__abstractmethods__"); + return NULL; + } + Py_XINCREF(mod); + return mod; } static int type_set_abstractmethods(PyTypeObject *type, PyObject *value, void *context) { - /* __abstractmethods__ should only be set once on a type, in - abc.ABCMeta.__new__, so this function doesn't do anything - special to update subclasses. - */ - int res = PyDict_SetItemString(type->tp_dict, - "__abstractmethods__", value); - if (res == 0) { - PyType_Modified(type); - if (value && PyObject_IsTrue(value)) { - type->tp_flags |= Py_TPFLAGS_IS_ABSTRACT; - } - else { - type->tp_flags &= ~Py_TPFLAGS_IS_ABSTRACT; - } - } - return res; + /* __abstractmethods__ should only be set once on a type, in + abc.ABCMeta.__new__, so this function doesn't do anything + special to update subclasses. + */ + int res = PyDict_SetItemString(type->tp_dict, + "__abstractmethods__", value); + if (res == 0) { + PyType_Modified(type); + if (value && PyObject_IsTrue(value)) { + type->tp_flags |= Py_TPFLAGS_IS_ABSTRACT; + } + else { + type->tp_flags &= ~Py_TPFLAGS_IS_ABSTRACT; + } + } + return res; } static PyObject * type_get_bases(PyTypeObject *type, void *context) { - Py_INCREF(type->tp_bases); - return type->tp_bases; + Py_INCREF(type->tp_bases); + return type->tp_bases; } static PyTypeObject *best_base(PyObject *); @@ -367,357 +367,357 @@ typedef int (*update_callback)(PyTypeObject *, void *); static int update_subclasses(PyTypeObject *type, PyObject *name, - update_callback callback, void *data); + update_callback callback, void *data); static int recurse_down_subclasses(PyTypeObject *type, PyObject *name, - update_callback callback, void *data); + update_callback callback, void *data); static int mro_subclasses(PyTypeObject *type, PyObject* temp) { - PyTypeObject *subclass; - PyObject *ref, *subclasses, *old_mro; - Py_ssize_t i, n; - - subclasses = type->tp_subclasses; - if (subclasses == NULL) - return 0; - assert(PyList_Check(subclasses)); - n = PyList_GET_SIZE(subclasses); - for (i = 0; i < n; i++) { - ref = PyList_GET_ITEM(subclasses, i); - assert(PyWeakref_CheckRef(ref)); - subclass = (PyTypeObject *)PyWeakref_GET_OBJECT(ref); - assert(subclass != NULL); - if ((PyObject *)subclass == Py_None) - continue; - assert(PyType_Check(subclass)); - old_mro = subclass->tp_mro; - if (mro_internal(subclass) < 0) { - subclass->tp_mro = old_mro; - return -1; - } - else { - PyObject* tuple; - tuple = PyTuple_Pack(2, subclass, old_mro); - Py_DECREF(old_mro); - if (!tuple) - return -1; - if (PyList_Append(temp, tuple) < 0) - return -1; - Py_DECREF(tuple); - } - if (mro_subclasses(subclass, temp) < 0) - return -1; - } - return 0; + PyTypeObject *subclass; + PyObject *ref, *subclasses, *old_mro; + Py_ssize_t i, n; + + subclasses = type->tp_subclasses; + if (subclasses == NULL) + return 0; + assert(PyList_Check(subclasses)); + n = PyList_GET_SIZE(subclasses); + for (i = 0; i < n; i++) { + ref = PyList_GET_ITEM(subclasses, i); + assert(PyWeakref_CheckRef(ref)); + subclass = (PyTypeObject *)PyWeakref_GET_OBJECT(ref); + assert(subclass != NULL); + if ((PyObject *)subclass == Py_None) + continue; + assert(PyType_Check(subclass)); + old_mro = subclass->tp_mro; + if (mro_internal(subclass) < 0) { + subclass->tp_mro = old_mro; + return -1; + } + else { + PyObject* tuple; + tuple = PyTuple_Pack(2, subclass, old_mro); + Py_DECREF(old_mro); + if (!tuple) + return -1; + if (PyList_Append(temp, tuple) < 0) + return -1; + Py_DECREF(tuple); + } + if (mro_subclasses(subclass, temp) < 0) + return -1; + } + return 0; } static int type_set_bases(PyTypeObject *type, PyObject *value, void *context) { - Py_ssize_t i; - int r = 0; - PyObject *ob, *temp; - PyTypeObject *new_base, *old_base; - PyObject *old_bases, *old_mro; - - if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE)) { - PyErr_Format(PyExc_TypeError, - "can't set %s.__bases__", type->tp_name); - return -1; - } - if (!value) { - PyErr_Format(PyExc_TypeError, - "can't delete %s.__bases__", type->tp_name); - return -1; - } - if (!PyTuple_Check(value)) { - PyErr_Format(PyExc_TypeError, - "can only assign tuple to %s.__bases__, not %s", - type->tp_name, Py_TYPE(value)->tp_name); - return -1; - } - if (PyTuple_GET_SIZE(value) == 0) { - PyErr_Format(PyExc_TypeError, - "can only assign non-empty tuple to %s.__bases__, not ()", - type->tp_name); - return -1; - } - for (i = 0; i < PyTuple_GET_SIZE(value); i++) { - ob = PyTuple_GET_ITEM(value, i); - if (!PyType_Check(ob)) { - PyErr_Format( - PyExc_TypeError, - "%s.__bases__ must be tuple of old- or new-style classes, not '%s'", - type->tp_name, Py_TYPE(ob)->tp_name); - return -1; - } - if (PyType_Check(ob)) { - if (PyType_IsSubtype((PyTypeObject*)ob, type)) { - PyErr_SetString(PyExc_TypeError, - "a __bases__ item causes an inheritance cycle"); - return -1; - } - } - } - - new_base = best_base(value); - - if (!new_base) { - return -1; - } - - if (!compatible_for_assignment(type->tp_base, new_base, "__bases__")) - return -1; - - Py_INCREF(new_base); - Py_INCREF(value); - - old_bases = type->tp_bases; - old_base = type->tp_base; - old_mro = type->tp_mro; - - type->tp_bases = value; - type->tp_base = new_base; - - if (mro_internal(type) < 0) { - goto bail; - } - - temp = PyList_New(0); - if (!temp) - goto bail; - - r = mro_subclasses(type, temp); - - if (r < 0) { - for (i = 0; i < PyList_Size(temp); i++) { - PyTypeObject* cls; - PyObject* mro; - PyArg_UnpackTuple(PyList_GET_ITEM(temp, i), - "", 2, 2, &cls, &mro); - Py_INCREF(mro); - ob = cls->tp_mro; - cls->tp_mro = mro; - Py_DECREF(ob); - } - Py_DECREF(temp); - goto bail; - } - - Py_DECREF(temp); - - /* any base that was in __bases__ but now isn't, we - need to remove |type| from its tp_subclasses. - conversely, any class now in __bases__ that wasn't - needs to have |type| added to its subclasses. */ - - /* for now, sod that: just remove from all old_bases, - add to all new_bases */ - - for (i = PyTuple_GET_SIZE(old_bases) - 1; i >= 0; i--) { - ob = PyTuple_GET_ITEM(old_bases, i); - if (PyType_Check(ob)) { - remove_subclass( - (PyTypeObject*)ob, type); - } - } - - for (i = PyTuple_GET_SIZE(value) - 1; i >= 0; i--) { - ob = PyTuple_GET_ITEM(value, i); - if (PyType_Check(ob)) { - if (add_subclass((PyTypeObject*)ob, type) < 0) - r = -1; - } - } - - update_all_slots(type); - - Py_DECREF(old_bases); - Py_DECREF(old_base); - Py_DECREF(old_mro); + Py_ssize_t i; + int r = 0; + PyObject *ob, *temp; + PyTypeObject *new_base, *old_base; + PyObject *old_bases, *old_mro; + + if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE)) { + PyErr_Format(PyExc_TypeError, + "can't set %s.__bases__", type->tp_name); + return -1; + } + if (!value) { + PyErr_Format(PyExc_TypeError, + "can't delete %s.__bases__", type->tp_name); + return -1; + } + if (!PyTuple_Check(value)) { + PyErr_Format(PyExc_TypeError, + "can only assign tuple to %s.__bases__, not %s", + type->tp_name, Py_TYPE(value)->tp_name); + return -1; + } + if (PyTuple_GET_SIZE(value) == 0) { + PyErr_Format(PyExc_TypeError, + "can only assign non-empty tuple to %s.__bases__, not ()", + type->tp_name); + return -1; + } + for (i = 0; i < PyTuple_GET_SIZE(value); i++) { + ob = PyTuple_GET_ITEM(value, i); + if (!PyType_Check(ob)) { + PyErr_Format( + PyExc_TypeError, + "%s.__bases__ must be tuple of old- or new-style classes, not '%s'", + type->tp_name, Py_TYPE(ob)->tp_name); + return -1; + } + if (PyType_Check(ob)) { + if (PyType_IsSubtype((PyTypeObject*)ob, type)) { + PyErr_SetString(PyExc_TypeError, + "a __bases__ item causes an inheritance cycle"); + return -1; + } + } + } + + new_base = best_base(value); + + if (!new_base) { + return -1; + } + + if (!compatible_for_assignment(type->tp_base, new_base, "__bases__")) + return -1; + + Py_INCREF(new_base); + Py_INCREF(value); + + old_bases = type->tp_bases; + old_base = type->tp_base; + old_mro = type->tp_mro; + + type->tp_bases = value; + type->tp_base = new_base; + + if (mro_internal(type) < 0) { + goto bail; + } + + temp = PyList_New(0); + if (!temp) + goto bail; + + r = mro_subclasses(type, temp); + + if (r < 0) { + for (i = 0; i < PyList_Size(temp); i++) { + PyTypeObject* cls; + PyObject* mro; + PyArg_UnpackTuple(PyList_GET_ITEM(temp, i), + "", 2, 2, &cls, &mro); + Py_INCREF(mro); + ob = cls->tp_mro; + cls->tp_mro = mro; + Py_DECREF(ob); + } + Py_DECREF(temp); + goto bail; + } + + Py_DECREF(temp); + + /* any base that was in __bases__ but now isn't, we + need to remove |type| from its tp_subclasses. + conversely, any class now in __bases__ that wasn't + needs to have |type| added to its subclasses. */ + + /* for now, sod that: just remove from all old_bases, + add to all new_bases */ + + for (i = PyTuple_GET_SIZE(old_bases) - 1; i >= 0; i--) { + ob = PyTuple_GET_ITEM(old_bases, i); + if (PyType_Check(ob)) { + remove_subclass( + (PyTypeObject*)ob, type); + } + } + + for (i = PyTuple_GET_SIZE(value) - 1; i >= 0; i--) { + ob = PyTuple_GET_ITEM(value, i); + if (PyType_Check(ob)) { + if (add_subclass((PyTypeObject*)ob, type) < 0) + r = -1; + } + } + + update_all_slots(type); + + Py_DECREF(old_bases); + Py_DECREF(old_base); + Py_DECREF(old_mro); - return r; + return r; bail: - Py_DECREF(type->tp_bases); - Py_DECREF(type->tp_base); - if (type->tp_mro != old_mro) { - Py_DECREF(type->tp_mro); - } - - type->tp_bases = old_bases; - type->tp_base = old_base; - type->tp_mro = old_mro; + Py_DECREF(type->tp_bases); + Py_DECREF(type->tp_base); + if (type->tp_mro != old_mro) { + Py_DECREF(type->tp_mro); + } + + type->tp_bases = old_bases; + type->tp_base = old_base; + type->tp_mro = old_mro; - return -1; + return -1; } static PyObject * type_dict(PyTypeObject *type, void *context) { - if (type->tp_dict == NULL) { - Py_INCREF(Py_None); - return Py_None; - } - return PyDictProxy_New(type->tp_dict); + if (type->tp_dict == NULL) { + Py_INCREF(Py_None); + return Py_None; + } + return PyDictProxy_New(type->tp_dict); } static PyObject * type_get_doc(PyTypeObject *type, void *context) { - PyObject *result; - if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE) && type->tp_doc != NULL) - return PyUnicode_FromString(type->tp_doc); - result = PyDict_GetItemString(type->tp_dict, "__doc__"); - if (result == NULL) { - result = Py_None; - Py_INCREF(result); - } - else if (Py_TYPE(result)->tp_descr_get) { - result = Py_TYPE(result)->tp_descr_get(result, NULL, - (PyObject *)type); - } - else { - Py_INCREF(result); - } - return result; + PyObject *result; + if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE) && type->tp_doc != NULL) + return PyUnicode_FromString(type->tp_doc); + result = PyDict_GetItemString(type->tp_dict, "__doc__"); + if (result == NULL) { + result = Py_None; + Py_INCREF(result); + } + else if (Py_TYPE(result)->tp_descr_get) { + result = Py_TYPE(result)->tp_descr_get(result, NULL, + (PyObject *)type); + } + else { + Py_INCREF(result); + } + return result; } static PyObject * type___instancecheck__(PyObject *type, PyObject *inst) { - switch (_PyObject_RealIsInstance(inst, type)) { - case -1: - return NULL; - case 0: - Py_RETURN_FALSE; - default: - Py_RETURN_TRUE; - } + switch (_PyObject_RealIsInstance(inst, type)) { + case -1: + return NULL; + case 0: + Py_RETURN_FALSE; + default: + Py_RETURN_TRUE; + } } static PyObject * type___subclasscheck__(PyObject *type, PyObject *inst) { - switch (_PyObject_RealIsSubclass(inst, type)) { - case -1: - return NULL; - case 0: - Py_RETURN_FALSE; - default: - Py_RETURN_TRUE; - } + switch (_PyObject_RealIsSubclass(inst, type)) { + case -1: + return NULL; + case 0: + Py_RETURN_FALSE; + default: + Py_RETURN_TRUE; + } } static PyGetSetDef type_getsets[] = { - {"__name__", (getter)type_name, (setter)type_set_name, NULL}, - {"__bases__", (getter)type_get_bases, (setter)type_set_bases, NULL}, - {"__module__", (getter)type_module, (setter)type_set_module, NULL}, - {"__abstractmethods__", (getter)type_abstractmethods, - (setter)type_set_abstractmethods, NULL}, - {"__dict__", (getter)type_dict, NULL, NULL}, - {"__doc__", (getter)type_get_doc, NULL, NULL}, - {0} + {"__name__", (getter)type_name, (setter)type_set_name, NULL}, + {"__bases__", (getter)type_get_bases, (setter)type_set_bases, NULL}, + {"__module__", (getter)type_module, (setter)type_set_module, NULL}, + {"__abstractmethods__", (getter)type_abstractmethods, + (setter)type_set_abstractmethods, NULL}, + {"__dict__", (getter)type_dict, NULL, NULL}, + {"__doc__", (getter)type_get_doc, NULL, NULL}, + {0} }; static PyObject * type_repr(PyTypeObject *type) { - PyObject *mod, *name, *rtn; + PyObject *mod, *name, *rtn; - mod = type_module(type, NULL); - if (mod == NULL) - PyErr_Clear(); - else if (!PyUnicode_Check(mod)) { - Py_DECREF(mod); - mod = NULL; - } - name = type_name(type, NULL); - if (name == NULL) - return NULL; - - if (mod != NULL && PyUnicode_CompareWithASCIIString(mod, "builtins")) - rtn = PyUnicode_FromFormat("", mod, name); - else - rtn = PyUnicode_FromFormat("", type->tp_name); - - Py_XDECREF(mod); - Py_DECREF(name); - return rtn; + mod = type_module(type, NULL); + if (mod == NULL) + PyErr_Clear(); + else if (!PyUnicode_Check(mod)) { + Py_DECREF(mod); + mod = NULL; + } + name = type_name(type, NULL); + if (name == NULL) + return NULL; + + if (mod != NULL && PyUnicode_CompareWithASCIIString(mod, "builtins")) + rtn = PyUnicode_FromFormat("", mod, name); + else + rtn = PyUnicode_FromFormat("", type->tp_name); + + Py_XDECREF(mod); + Py_DECREF(name); + return rtn; } static PyObject * type_call(PyTypeObject *type, PyObject *args, PyObject *kwds) { - PyObject *obj; + PyObject *obj; - if (type->tp_new == NULL) { - PyErr_Format(PyExc_TypeError, - "cannot create '%.100s' instances", - type->tp_name); - return NULL; - } - - obj = type->tp_new(type, args, kwds); - if (obj != NULL) { - /* Ugly exception: when the call was type(something), - don't call tp_init on the result. */ - if (type == &PyType_Type && - PyTuple_Check(args) && PyTuple_GET_SIZE(args) == 1 && - (kwds == NULL || - (PyDict_Check(kwds) && PyDict_Size(kwds) == 0))) - return obj; - /* If the returned object is not an instance of type, - it won't be initialized. */ - if (!PyType_IsSubtype(Py_TYPE(obj), type)) - return obj; - type = Py_TYPE(obj); - if (type->tp_init != NULL && - type->tp_init(obj, args, kwds) < 0) { - Py_DECREF(obj); - obj = NULL; - } - } - return obj; + if (type->tp_new == NULL) { + PyErr_Format(PyExc_TypeError, + "cannot create '%.100s' instances", + type->tp_name); + return NULL; + } + + obj = type->tp_new(type, args, kwds); + if (obj != NULL) { + /* Ugly exception: when the call was type(something), + don't call tp_init on the result. */ + if (type == &PyType_Type && + PyTuple_Check(args) && PyTuple_GET_SIZE(args) == 1 && + (kwds == NULL || + (PyDict_Check(kwds) && PyDict_Size(kwds) == 0))) + return obj; + /* If the returned object is not an instance of type, + it won't be initialized. */ + if (!PyType_IsSubtype(Py_TYPE(obj), type)) + return obj; + type = Py_TYPE(obj); + if (type->tp_init != NULL && + type->tp_init(obj, args, kwds) < 0) { + Py_DECREF(obj); + obj = NULL; + } + } + return obj; } PyObject * PyType_GenericAlloc(PyTypeObject *type, Py_ssize_t nitems) { - PyObject *obj; - const size_t size = _PyObject_VAR_SIZE(type, nitems+1); - /* note that we need to add one, for the sentinel */ - - if (PyType_IS_GC(type)) - obj = _PyObject_GC_Malloc(size); - else - obj = (PyObject *)PyObject_MALLOC(size); - - if (obj == NULL) - return PyErr_NoMemory(); - - memset(obj, '\0', size); - - if (type->tp_flags & Py_TPFLAGS_HEAPTYPE) - Py_INCREF(type); - - if (type->tp_itemsize == 0) - PyObject_INIT(obj, type); - else - (void) PyObject_INIT_VAR((PyVarObject *)obj, type, nitems); - - if (PyType_IS_GC(type)) - _PyObject_GC_TRACK(obj); - return obj; + PyObject *obj; + const size_t size = _PyObject_VAR_SIZE(type, nitems+1); + /* note that we need to add one, for the sentinel */ + + if (PyType_IS_GC(type)) + obj = _PyObject_GC_Malloc(size); + else + obj = (PyObject *)PyObject_MALLOC(size); + + if (obj == NULL) + return PyErr_NoMemory(); + + memset(obj, '\0', size); + + if (type->tp_flags & Py_TPFLAGS_HEAPTYPE) + Py_INCREF(type); + + if (type->tp_itemsize == 0) + PyObject_INIT(obj, type); + else + (void) PyObject_INIT_VAR((PyVarObject *)obj, type, nitems); + + if (PyType_IS_GC(type)) + _PyObject_GC_TRACK(obj); + return obj; } PyObject * PyType_GenericNew(PyTypeObject *type, PyObject *args, PyObject *kwds) { - return type->tp_alloc(type, 0); + return type->tp_alloc(type, 0); } /* Helpers for subtyping */ @@ -725,341 +725,341 @@ static int traverse_slots(PyTypeObject *type, PyObject *self, visitproc visit, void *arg) { - Py_ssize_t i, n; - PyMemberDef *mp; + Py_ssize_t i, n; + PyMemberDef *mp; - n = Py_SIZE(type); - mp = PyHeapType_GET_MEMBERS((PyHeapTypeObject *)type); - for (i = 0; i < n; i++, mp++) { - if (mp->type == T_OBJECT_EX) { - char *addr = (char *)self + mp->offset; - PyObject *obj = *(PyObject **)addr; - if (obj != NULL) { - int err = visit(obj, arg); - if (err) - return err; - } - } - } - return 0; + n = Py_SIZE(type); + mp = PyHeapType_GET_MEMBERS((PyHeapTypeObject *)type); + for (i = 0; i < n; i++, mp++) { + if (mp->type == T_OBJECT_EX) { + char *addr = (char *)self + mp->offset; + PyObject *obj = *(PyObject **)addr; + if (obj != NULL) { + int err = visit(obj, arg); + if (err) + return err; + } + } + } + return 0; } static int subtype_traverse(PyObject *self, visitproc visit, void *arg) { - PyTypeObject *type, *base; - traverseproc basetraverse; + PyTypeObject *type, *base; + traverseproc basetraverse; - /* Find the nearest base with a different tp_traverse, - and traverse slots while we're at it */ - type = Py_TYPE(self); - base = type; - while ((basetraverse = base->tp_traverse) == subtype_traverse) { - if (Py_SIZE(base)) { - int err = traverse_slots(base, self, visit, arg); - if (err) - return err; - } - base = base->tp_base; - assert(base); - } - - if (type->tp_dictoffset != base->tp_dictoffset) { - PyObject **dictptr = _PyObject_GetDictPtr(self); - if (dictptr && *dictptr) - Py_VISIT(*dictptr); - } - - if (type->tp_flags & Py_TPFLAGS_HEAPTYPE) - /* For a heaptype, the instances count as references - to the type. Traverse the type so the collector - can find cycles involving this link. */ - Py_VISIT(type); - - if (basetraverse) - return basetraverse(self, visit, arg); - return 0; + /* Find the nearest base with a different tp_traverse, + and traverse slots while we're at it */ + type = Py_TYPE(self); + base = type; + while ((basetraverse = base->tp_traverse) == subtype_traverse) { + if (Py_SIZE(base)) { + int err = traverse_slots(base, self, visit, arg); + if (err) + return err; + } + base = base->tp_base; + assert(base); + } + + if (type->tp_dictoffset != base->tp_dictoffset) { + PyObject **dictptr = _PyObject_GetDictPtr(self); + if (dictptr && *dictptr) + Py_VISIT(*dictptr); + } + + if (type->tp_flags & Py_TPFLAGS_HEAPTYPE) + /* For a heaptype, the instances count as references + to the type. Traverse the type so the collector + can find cycles involving this link. */ + Py_VISIT(type); + + if (basetraverse) + return basetraverse(self, visit, arg); + return 0; } static void clear_slots(PyTypeObject *type, PyObject *self) { - Py_ssize_t i, n; - PyMemberDef *mp; + Py_ssize_t i, n; + PyMemberDef *mp; - n = Py_SIZE(type); - mp = PyHeapType_GET_MEMBERS((PyHeapTypeObject *)type); - for (i = 0; i < n; i++, mp++) { - if (mp->type == T_OBJECT_EX && !(mp->flags & READONLY)) { - char *addr = (char *)self + mp->offset; - PyObject *obj = *(PyObject **)addr; - if (obj != NULL) { - *(PyObject **)addr = NULL; - Py_DECREF(obj); - } - } - } + n = Py_SIZE(type); + mp = PyHeapType_GET_MEMBERS((PyHeapTypeObject *)type); + for (i = 0; i < n; i++, mp++) { + if (mp->type == T_OBJECT_EX && !(mp->flags & READONLY)) { + char *addr = (char *)self + mp->offset; + PyObject *obj = *(PyObject **)addr; + if (obj != NULL) { + *(PyObject **)addr = NULL; + Py_DECREF(obj); + } + } + } } static int subtype_clear(PyObject *self) { - PyTypeObject *type, *base; - inquiry baseclear; + PyTypeObject *type, *base; + inquiry baseclear; - /* Find the nearest base with a different tp_clear - and clear slots while we're at it */ - type = Py_TYPE(self); - base = type; - while ((baseclear = base->tp_clear) == subtype_clear) { - if (Py_SIZE(base)) - clear_slots(base, self); - base = base->tp_base; - assert(base); - } - - /* There's no need to clear the instance dict (if any); - the collector will call its tp_clear handler. */ - - if (baseclear) - return baseclear(self); - return 0; + /* Find the nearest base with a different tp_clear + and clear slots while we're at it */ + type = Py_TYPE(self); + base = type; + while ((baseclear = base->tp_clear) == subtype_clear) { + if (Py_SIZE(base)) + clear_slots(base, self); + base = base->tp_base; + assert(base); + } + + /* There's no need to clear the instance dict (if any); + the collector will call its tp_clear handler. */ + + if (baseclear) + return baseclear(self); + return 0; } static void subtype_dealloc(PyObject *self) { - PyTypeObject *type, *base; - destructor basedealloc; + PyTypeObject *type, *base; + destructor basedealloc; + + /* Extract the type; we expect it to be a heap type */ + type = Py_TYPE(self); + assert(type->tp_flags & Py_TPFLAGS_HEAPTYPE); + + /* Test whether the type has GC exactly once */ + + if (!PyType_IS_GC(type)) { + /* It's really rare to find a dynamic type that doesn't have + GC; it can only happen when deriving from 'object' and not + adding any slots or instance variables. This allows + certain simplifications: there's no need to call + clear_slots(), or DECREF the dict, or clear weakrefs. */ + + /* Maybe call finalizer; exit early if resurrected */ + if (type->tp_del) { + type->tp_del(self); + if (self->ob_refcnt > 0) + return; + } + + /* Find the nearest base with a different tp_dealloc */ + base = type; + while ((basedealloc = base->tp_dealloc) == subtype_dealloc) { + assert(Py_SIZE(base) == 0); + base = base->tp_base; + assert(base); + } + + /* Extract the type again; tp_del may have changed it */ + type = Py_TYPE(self); + + /* Call the base tp_dealloc() */ + assert(basedealloc); + basedealloc(self); + + /* Can't reference self beyond this point */ + Py_DECREF(type); + + /* Done */ + return; + } + + /* We get here only if the type has GC */ + + /* UnTrack and re-Track around the trashcan macro, alas */ + /* See explanation at end of function for full disclosure */ + PyObject_GC_UnTrack(self); + ++_PyTrash_delete_nesting; + Py_TRASHCAN_SAFE_BEGIN(self); + --_PyTrash_delete_nesting; + /* DO NOT restore GC tracking at this point. weakref callbacks + * (if any, and whether directly here or indirectly in something we + * call) may trigger GC, and if self is tracked at that point, it + * will look like trash to GC and GC will try to delete self again. + */ + + /* Find the nearest base with a different tp_dealloc */ + base = type; + while ((basedealloc = base->tp_dealloc) == subtype_dealloc) { + base = base->tp_base; + assert(base); + } + + /* If we added a weaklist, we clear it. Do this *before* calling + the finalizer (__del__), clearing slots, or clearing the instance + dict. */ + + if (type->tp_weaklistoffset && !base->tp_weaklistoffset) + PyObject_ClearWeakRefs(self); + + /* Maybe call finalizer; exit early if resurrected */ + if (type->tp_del) { + _PyObject_GC_TRACK(self); + type->tp_del(self); + if (self->ob_refcnt > 0) + goto endlabel; /* resurrected */ + else + _PyObject_GC_UNTRACK(self); + /* New weakrefs could be created during the finalizer call. + If this occurs, clear them out without calling their + finalizers since they might rely on part of the object + being finalized that has already been destroyed. */ + if (type->tp_weaklistoffset && !base->tp_weaklistoffset) { + /* Modeled after GET_WEAKREFS_LISTPTR() */ + PyWeakReference **list = (PyWeakReference **) \ + PyObject_GET_WEAKREFS_LISTPTR(self); + while (*list) + _PyWeakref_ClearRef(*list); + } + } - /* Extract the type; we expect it to be a heap type */ - type = Py_TYPE(self); - assert(type->tp_flags & Py_TPFLAGS_HEAPTYPE); - - /* Test whether the type has GC exactly once */ - - if (!PyType_IS_GC(type)) { - /* It's really rare to find a dynamic type that doesn't have - GC; it can only happen when deriving from 'object' and not - adding any slots or instance variables. This allows - certain simplifications: there's no need to call - clear_slots(), or DECREF the dict, or clear weakrefs. */ - - /* Maybe call finalizer; exit early if resurrected */ - if (type->tp_del) { - type->tp_del(self); - if (self->ob_refcnt > 0) - return; - } - - /* Find the nearest base with a different tp_dealloc */ - base = type; - while ((basedealloc = base->tp_dealloc) == subtype_dealloc) { - assert(Py_SIZE(base) == 0); - base = base->tp_base; - assert(base); - } - - /* Extract the type again; tp_del may have changed it */ - type = Py_TYPE(self); - - /* Call the base tp_dealloc() */ - assert(basedealloc); - basedealloc(self); - - /* Can't reference self beyond this point */ - Py_DECREF(type); - - /* Done */ - return; - } - - /* We get here only if the type has GC */ - - /* UnTrack and re-Track around the trashcan macro, alas */ - /* See explanation at end of function for full disclosure */ - PyObject_GC_UnTrack(self); - ++_PyTrash_delete_nesting; - Py_TRASHCAN_SAFE_BEGIN(self); - --_PyTrash_delete_nesting; - /* DO NOT restore GC tracking at this point. weakref callbacks - * (if any, and whether directly here or indirectly in something we - * call) may trigger GC, and if self is tracked at that point, it - * will look like trash to GC and GC will try to delete self again. - */ - - /* Find the nearest base with a different tp_dealloc */ - base = type; - while ((basedealloc = base->tp_dealloc) == subtype_dealloc) { - base = base->tp_base; - assert(base); - } - - /* If we added a weaklist, we clear it. Do this *before* calling - the finalizer (__del__), clearing slots, or clearing the instance - dict. */ - - if (type->tp_weaklistoffset && !base->tp_weaklistoffset) - PyObject_ClearWeakRefs(self); - - /* Maybe call finalizer; exit early if resurrected */ - if (type->tp_del) { - _PyObject_GC_TRACK(self); - type->tp_del(self); - if (self->ob_refcnt > 0) - goto endlabel; /* resurrected */ - else - _PyObject_GC_UNTRACK(self); - /* New weakrefs could be created during the finalizer call. - If this occurs, clear them out without calling their - finalizers since they might rely on part of the object - being finalized that has already been destroyed. */ - if (type->tp_weaklistoffset && !base->tp_weaklistoffset) { - /* Modeled after GET_WEAKREFS_LISTPTR() */ - PyWeakReference **list = (PyWeakReference **) \ - PyObject_GET_WEAKREFS_LISTPTR(self); - while (*list) - _PyWeakref_ClearRef(*list); - } - } - - /* Clear slots up to the nearest base with a different tp_dealloc */ - base = type; - while ((basedealloc = base->tp_dealloc) == subtype_dealloc) { - if (Py_SIZE(base)) - clear_slots(base, self); - base = base->tp_base; - assert(base); - } - - /* If we added a dict, DECREF it */ - if (type->tp_dictoffset && !base->tp_dictoffset) { - PyObject **dictptr = _PyObject_GetDictPtr(self); - if (dictptr != NULL) { - PyObject *dict = *dictptr; - if (dict != NULL) { - Py_DECREF(dict); - *dictptr = NULL; - } - } - } - - /* Extract the type again; tp_del may have changed it */ - type = Py_TYPE(self); - - /* Call the base tp_dealloc(); first retrack self if - * basedealloc knows about gc. - */ - if (PyType_IS_GC(base)) - _PyObject_GC_TRACK(self); - assert(basedealloc); - basedealloc(self); + /* Clear slots up to the nearest base with a different tp_dealloc */ + base = type; + while ((basedealloc = base->tp_dealloc) == subtype_dealloc) { + if (Py_SIZE(base)) + clear_slots(base, self); + base = base->tp_base; + assert(base); + } + + /* If we added a dict, DECREF it */ + if (type->tp_dictoffset && !base->tp_dictoffset) { + PyObject **dictptr = _PyObject_GetDictPtr(self); + if (dictptr != NULL) { + PyObject *dict = *dictptr; + if (dict != NULL) { + Py_DECREF(dict); + *dictptr = NULL; + } + } + } + + /* Extract the type again; tp_del may have changed it */ + type = Py_TYPE(self); + + /* Call the base tp_dealloc(); first retrack self if + * basedealloc knows about gc. + */ + if (PyType_IS_GC(base)) + _PyObject_GC_TRACK(self); + assert(basedealloc); + basedealloc(self); - /* Can't reference self beyond this point */ - Py_DECREF(type); + /* Can't reference self beyond this point */ + Py_DECREF(type); endlabel: - ++_PyTrash_delete_nesting; - Py_TRASHCAN_SAFE_END(self); - --_PyTrash_delete_nesting; + ++_PyTrash_delete_nesting; + Py_TRASHCAN_SAFE_END(self); + --_PyTrash_delete_nesting; - /* Explanation of the weirdness around the trashcan macros: + /* Explanation of the weirdness around the trashcan macros: - Q. What do the trashcan macros do? + Q. What do the trashcan macros do? - A. Read the comment titled "Trashcan mechanism" in object.h. - For one, this explains why there must be a call to GC-untrack - before the trashcan begin macro. Without understanding the - trashcan code, the answers to the following questions don't make - sense. + A. Read the comment titled "Trashcan mechanism" in object.h. + For one, this explains why there must be a call to GC-untrack + before the trashcan begin macro. Without understanding the + trashcan code, the answers to the following questions don't make + sense. - Q. Why do we GC-untrack before the trashcan and then immediately - GC-track again afterward? + Q. Why do we GC-untrack before the trashcan and then immediately + GC-track again afterward? - A. In the case that the base class is GC-aware, the base class - probably GC-untracks the object. If it does that using the - UNTRACK macro, this will crash when the object is already - untracked. Because we don't know what the base class does, the - only safe thing is to make sure the object is tracked when we - call the base class dealloc. But... The trashcan begin macro - requires that the object is *untracked* before it is called. So - the dance becomes: + A. In the case that the base class is GC-aware, the base class + probably GC-untracks the object. If it does that using the + UNTRACK macro, this will crash when the object is already + untracked. Because we don't know what the base class does, the + only safe thing is to make sure the object is tracked when we + call the base class dealloc. But... The trashcan begin macro + requires that the object is *untracked* before it is called. So + the dance becomes: - GC untrack - trashcan begin - GC track + GC untrack + trashcan begin + GC track - Q. Why did the last question say "immediately GC-track again"? - It's nowhere near immediately. + Q. Why did the last question say "immediately GC-track again"? + It's nowhere near immediately. - A. Because the code *used* to re-track immediately. Bad Idea. - self has a refcount of 0, and if gc ever gets its hands on it - (which can happen if any weakref callback gets invoked), it - looks like trash to gc too, and gc also tries to delete self - then. But we're already deleting self. Double dealloction is - a subtle disaster. + A. Because the code *used* to re-track immediately. Bad Idea. + self has a refcount of 0, and if gc ever gets its hands on it + (which can happen if any weakref callback gets invoked), it + looks like trash to gc too, and gc also tries to delete self + then. But we're already deleting self. Double dealloction is + a subtle disaster. - Q. Why the bizarre (net-zero) manipulation of - _PyTrash_delete_nesting around the trashcan macros? + Q. Why the bizarre (net-zero) manipulation of + _PyTrash_delete_nesting around the trashcan macros? - A. Some base classes (e.g. list) also use the trashcan mechanism. - The following scenario used to be possible: + A. Some base classes (e.g. list) also use the trashcan mechanism. + The following scenario used to be possible: - - suppose the trashcan level is one below the trashcan limit + - suppose the trashcan level is one below the trashcan limit - - subtype_dealloc() is called + - subtype_dealloc() is called - - the trashcan limit is not yet reached, so the trashcan level - is incremented and the code between trashcan begin and end is - executed + - the trashcan limit is not yet reached, so the trashcan level + is incremented and the code between trashcan begin and end is + executed - - this destroys much of the object's contents, including its - slots and __dict__ + - this destroys much of the object's contents, including its + slots and __dict__ - - basedealloc() is called; this is really list_dealloc(), or - some other type which also uses the trashcan macros + - basedealloc() is called; this is really list_dealloc(), or + some other type which also uses the trashcan macros - - the trashcan limit is now reached, so the object is put on the - trashcan's to-be-deleted-later list + - the trashcan limit is now reached, so the object is put on the + trashcan's to-be-deleted-later list - - basedealloc() returns + - basedealloc() returns - - subtype_dealloc() decrefs the object's type + - subtype_dealloc() decrefs the object's type - - subtype_dealloc() returns + - subtype_dealloc() returns - - later, the trashcan code starts deleting the objects from its - to-be-deleted-later list + - later, the trashcan code starts deleting the objects from its + to-be-deleted-later list - - subtype_dealloc() is called *AGAIN* for the same object + - subtype_dealloc() is called *AGAIN* for the same object - - at the very least (if the destroyed slots and __dict__ don't - cause problems) the object's type gets decref'ed a second - time, which is *BAD*!!! + - at the very least (if the destroyed slots and __dict__ don't + cause problems) the object's type gets decref'ed a second + time, which is *BAD*!!! - The remedy is to make sure that if the code between trashcan - begin and end in subtype_dealloc() is called, the code between - trashcan begin and end in basedealloc() will also be called. - This is done by decrementing the level after passing into the - trashcan block, and incrementing it just before leaving the - block. + The remedy is to make sure that if the code between trashcan + begin and end in subtype_dealloc() is called, the code between + trashcan begin and end in basedealloc() will also be called. + This is done by decrementing the level after passing into the + trashcan block, and incrementing it just before leaving the + block. - But now it's possible that a chain of objects consisting solely - of objects whose deallocator is subtype_dealloc() will defeat - the trashcan mechanism completely: the decremented level means - that the effective level never reaches the limit. Therefore, we - *increment* the level *before* entering the trashcan block, and - matchingly decrement it after leaving. This means the trashcan - code will trigger a little early, but that's no big deal. + But now it's possible that a chain of objects consisting solely + of objects whose deallocator is subtype_dealloc() will defeat + the trashcan mechanism completely: the decremented level means + that the effective level never reaches the limit. Therefore, we + *increment* the level *before* entering the trashcan block, and + matchingly decrement it after leaving. This means the trashcan + code will trigger a little early, but that's no big deal. - Q. Are there any live examples of code in need of all this - complexity? + Q. Are there any live examples of code in need of all this + complexity? - A. Yes. See SF bug 668433 for code that crashed (when Python was - compiled in debug mode) before the trashcan level manipulations - were added. For more discussion, see SF patches 581742, 575073 - and bug 574207. - */ + A. Yes. See SF bug 668433 for code that crashed (when Python was + compiled in debug mode) before the trashcan level manipulations + were added. For more discussion, see SF patches 581742, 575073 + and bug 574207. + */ } static PyTypeObject *solid_base(PyTypeObject *type); @@ -1069,36 +1069,36 @@ int PyType_IsSubtype(PyTypeObject *a, PyTypeObject *b) { - PyObject *mro; + PyObject *mro; - mro = a->tp_mro; - if (mro != NULL) { - /* Deal with multiple inheritance without recursion - by walking the MRO tuple */ - Py_ssize_t i, n; - assert(PyTuple_Check(mro)); - n = PyTuple_GET_SIZE(mro); - for (i = 0; i < n; i++) { - if (PyTuple_GET_ITEM(mro, i) == (PyObject *)b) - return 1; - } - return 0; - } - else { - /* a is not completely initilized yet; follow tp_base */ - do { - if (a == b) - return 1; - a = a->tp_base; - } while (a != NULL); - return b == &PyBaseObject_Type; - } + mro = a->tp_mro; + if (mro != NULL) { + /* Deal with multiple inheritance without recursion + by walking the MRO tuple */ + Py_ssize_t i, n; + assert(PyTuple_Check(mro)); + n = PyTuple_GET_SIZE(mro); + for (i = 0; i < n; i++) { + if (PyTuple_GET_ITEM(mro, i) == (PyObject *)b) + return 1; + } + return 0; + } + else { + /* a is not completely initilized yet; follow tp_base */ + do { + if (a == b) + return 1; + a = a->tp_base; + } while (a != NULL); + return b == &PyBaseObject_Type; + } } /* Internal routines to do a method lookup in the type without looking in the instance dictionary (so we can't use PyObject_GetAttr) but still binding - it to the instance. The arguments are the object, + it to the instance. The arguments are the object, the method name as a C string, and the address of a static variable used to cache the interned Python string. @@ -1115,75 +1115,75 @@ static PyObject * lookup_maybe(PyObject *self, char *attrstr, PyObject **attrobj) { - PyObject *res; + PyObject *res; - if (*attrobj == NULL) { - *attrobj = PyUnicode_InternFromString(attrstr); - if (*attrobj == NULL) - return NULL; - } - res = _PyType_Lookup(Py_TYPE(self), *attrobj); - if (res != NULL) { - descrgetfunc f; - if ((f = Py_TYPE(res)->tp_descr_get) == NULL) - Py_INCREF(res); - else - res = f(res, self, (PyObject *)(Py_TYPE(self))); - } - return res; + if (*attrobj == NULL) { + *attrobj = PyUnicode_InternFromString(attrstr); + if (*attrobj == NULL) + return NULL; + } + res = _PyType_Lookup(Py_TYPE(self), *attrobj); + if (res != NULL) { + descrgetfunc f; + if ((f = Py_TYPE(res)->tp_descr_get) == NULL) + Py_INCREF(res); + else + res = f(res, self, (PyObject *)(Py_TYPE(self))); + } + return res; } static PyObject * lookup_method(PyObject *self, char *attrstr, PyObject **attrobj) { - PyObject *res = lookup_maybe(self, attrstr, attrobj); - if (res == NULL && !PyErr_Occurred()) - PyErr_SetObject(PyExc_AttributeError, *attrobj); - return res; + PyObject *res = lookup_maybe(self, attrstr, attrobj); + if (res == NULL && !PyErr_Occurred()) + PyErr_SetObject(PyExc_AttributeError, *attrobj); + return res; } PyObject * _PyObject_LookupSpecial(PyObject *self, char *attrstr, PyObject **attrobj) { - return lookup_maybe(self, attrstr, attrobj); + return lookup_maybe(self, attrstr, attrobj); } /* A variation of PyObject_CallMethod that uses lookup_method() - instead of PyObject_GetAttrString(). This uses the same convention + instead of PyObject_GetAttrString(). This uses the same convention as lookup_method to cache the interned name string object. */ static PyObject * call_method(PyObject *o, char *name, PyObject **nameobj, char *format, ...) { - va_list va; - PyObject *args, *func = 0, *retval; - va_start(va, format); - - func = lookup_maybe(o, name, nameobj); - if (func == NULL) { - va_end(va); - if (!PyErr_Occurred()) - PyErr_SetObject(PyExc_AttributeError, *nameobj); - return NULL; - } - - if (format && *format) - args = Py_VaBuildValue(format, va); - else - args = PyTuple_New(0); - - va_end(va); - - if (args == NULL) - return NULL; + va_list va; + PyObject *args, *func = 0, *retval; + va_start(va, format); + + func = lookup_maybe(o, name, nameobj); + if (func == NULL) { + va_end(va); + if (!PyErr_Occurred()) + PyErr_SetObject(PyExc_AttributeError, *nameobj); + return NULL; + } + + if (format && *format) + args = Py_VaBuildValue(format, va); + else + args = PyTuple_New(0); + + va_end(va); + + if (args == NULL) + return NULL; - assert(PyTuple_Check(args)); - retval = PyObject_Call(func, args, NULL); + assert(PyTuple_Check(args)); + retval = PyObject_Call(func, args, NULL); - Py_DECREF(args); - Py_DECREF(func); + Py_DECREF(args); + Py_DECREF(func); - return retval; + return retval; } /* Clone of call_method() that returns NotImplemented when the lookup fails. */ @@ -1191,37 +1191,37 @@ static PyObject * call_maybe(PyObject *o, char *name, PyObject **nameobj, char *format, ...) { - va_list va; - PyObject *args, *func = 0, *retval; - va_start(va, format); - - func = lookup_maybe(o, name, nameobj); - if (func == NULL) { - va_end(va); - if (!PyErr_Occurred()) { - Py_INCREF(Py_NotImplemented); - return Py_NotImplemented; - } - return NULL; - } - - if (format && *format) - args = Py_VaBuildValue(format, va); - else - args = PyTuple_New(0); - - va_end(va); - - if (args == NULL) - return NULL; + va_list va; + PyObject *args, *func = 0, *retval; + va_start(va, format); + + func = lookup_maybe(o, name, nameobj); + if (func == NULL) { + va_end(va); + if (!PyErr_Occurred()) { + Py_INCREF(Py_NotImplemented); + return Py_NotImplemented; + } + return NULL; + } + + if (format && *format) + args = Py_VaBuildValue(format, va); + else + args = PyTuple_New(0); - assert(PyTuple_Check(args)); - retval = PyObject_Call(func, args, NULL); + va_end(va); - Py_DECREF(args); - Py_DECREF(func); + if (args == NULL) + return NULL; - return retval; + assert(PyTuple_Check(args)); + retval = PyObject_Call(func, args, NULL); + + Py_DECREF(args); + Py_DECREF(func); + + return retval; } /* @@ -1254,68 +1254,68 @@ static int tail_contains(PyObject *list, int whence, PyObject *o) { - Py_ssize_t j, size; - size = PyList_GET_SIZE(list); + Py_ssize_t j, size; + size = PyList_GET_SIZE(list); - for (j = whence+1; j < size; j++) { - if (PyList_GET_ITEM(list, j) == o) - return 1; - } - return 0; + for (j = whence+1; j < size; j++) { + if (PyList_GET_ITEM(list, j) == o) + return 1; + } + return 0; } static PyObject * class_name(PyObject *cls) { - PyObject *name = PyObject_GetAttrString(cls, "__name__"); - if (name == NULL) { - PyErr_Clear(); - Py_XDECREF(name); - name = PyObject_Repr(cls); - } - if (name == NULL) - return NULL; - if (!PyUnicode_Check(name)) { - Py_DECREF(name); - return NULL; - } - return name; + PyObject *name = PyObject_GetAttrString(cls, "__name__"); + if (name == NULL) { + PyErr_Clear(); + Py_XDECREF(name); + name = PyObject_Repr(cls); + } + if (name == NULL) + return NULL; + if (!PyUnicode_Check(name)) { + Py_DECREF(name); + return NULL; + } + return name; } static int check_duplicates(PyObject *list) { - Py_ssize_t i, j, n; - /* Let's use a quadratic time algorithm, - assuming that the bases lists is short. - */ - n = PyList_GET_SIZE(list); - for (i = 0; i < n; i++) { - PyObject *o = PyList_GET_ITEM(list, i); - for (j = i + 1; j < n; j++) { - if (PyList_GET_ITEM(list, j) == o) { - o = class_name(o); - if (o != NULL) { - PyErr_Format(PyExc_TypeError, - "duplicate base class %U", - o); - Py_DECREF(o); - } else { - PyErr_SetString(PyExc_TypeError, - "duplicate base class"); - } - return -1; - } - } - } - return 0; + Py_ssize_t i, j, n; + /* Let's use a quadratic time algorithm, + assuming that the bases lists is short. + */ + n = PyList_GET_SIZE(list); + for (i = 0; i < n; i++) { + PyObject *o = PyList_GET_ITEM(list, i); + for (j = i + 1; j < n; j++) { + if (PyList_GET_ITEM(list, j) == o) { + o = class_name(o); + if (o != NULL) { + PyErr_Format(PyExc_TypeError, + "duplicate base class %U", + o); + Py_DECREF(o); + } else { + PyErr_SetString(PyExc_TypeError, + "duplicate base class"); + } + return -1; + } + } + } + return 0; } /* Raise a TypeError for an MRO order disagreement. It's hard to produce a good error message. In the absence of better insight into error reporting, report the classes that were candidates - to be put next into the MRO. There is some conflict between the + to be put next into the MRO. There is some conflict between the order in which they should be put in the MRO, but it's hard to diagnose what constraint can't be satisfied. */ @@ -1323,252 +1323,252 @@ static void set_mro_error(PyObject *to_merge, int *remain) { - Py_ssize_t i, n, off, to_merge_size; - char buf[1000]; - PyObject *k, *v; - PyObject *set = PyDict_New(); - if (!set) return; - - to_merge_size = PyList_GET_SIZE(to_merge); - for (i = 0; i < to_merge_size; i++) { - PyObject *L = PyList_GET_ITEM(to_merge, i); - if (remain[i] < PyList_GET_SIZE(L)) { - PyObject *c = PyList_GET_ITEM(L, remain[i]); - if (PyDict_SetItem(set, c, Py_None) < 0) { - Py_DECREF(set); - return; - } - } - } - n = PyDict_Size(set); + Py_ssize_t i, n, off, to_merge_size; + char buf[1000]; + PyObject *k, *v; + PyObject *set = PyDict_New(); + if (!set) return; + + to_merge_size = PyList_GET_SIZE(to_merge); + for (i = 0; i < to_merge_size; i++) { + PyObject *L = PyList_GET_ITEM(to_merge, i); + if (remain[i] < PyList_GET_SIZE(L)) { + PyObject *c = PyList_GET_ITEM(L, remain[i]); + if (PyDict_SetItem(set, c, Py_None) < 0) { + Py_DECREF(set); + return; + } + } + } + n = PyDict_Size(set); - off = PyOS_snprintf(buf, sizeof(buf), "Cannot create a \ + off = PyOS_snprintf(buf, sizeof(buf), "Cannot create a \ consistent method resolution\norder (MRO) for bases"); - i = 0; - while (PyDict_Next(set, &i, &k, &v) && (size_t)off < sizeof(buf)) { - PyObject *name = class_name(k); - off += PyOS_snprintf(buf + off, sizeof(buf) - off, " %s", - name ? _PyUnicode_AsString(name) : "?"); - Py_XDECREF(name); - if (--n && (size_t)(off+1) < sizeof(buf)) { - buf[off++] = ','; - buf[off] = '\0'; - } - } - PyErr_SetString(PyExc_TypeError, buf); - Py_DECREF(set); + i = 0; + while (PyDict_Next(set, &i, &k, &v) && (size_t)off < sizeof(buf)) { + PyObject *name = class_name(k); + off += PyOS_snprintf(buf + off, sizeof(buf) - off, " %s", + name ? _PyUnicode_AsString(name) : "?"); + Py_XDECREF(name); + if (--n && (size_t)(off+1) < sizeof(buf)) { + buf[off++] = ','; + buf[off] = '\0'; + } + } + PyErr_SetString(PyExc_TypeError, buf); + Py_DECREF(set); } static int pmerge(PyObject *acc, PyObject* to_merge) { - Py_ssize_t i, j, to_merge_size, empty_cnt; - int *remain; - int ok; - - to_merge_size = PyList_GET_SIZE(to_merge); - - /* remain stores an index into each sublist of to_merge. - remain[i] is the index of the next base in to_merge[i] - that is not included in acc. - */ - remain = (int *)PyMem_MALLOC(SIZEOF_INT*to_merge_size); - if (remain == NULL) - return -1; - for (i = 0; i < to_merge_size; i++) - remain[i] = 0; + Py_ssize_t i, j, to_merge_size, empty_cnt; + int *remain; + int ok; + + to_merge_size = PyList_GET_SIZE(to_merge); + + /* remain stores an index into each sublist of to_merge. + remain[i] is the index of the next base in to_merge[i] + that is not included in acc. + */ + remain = (int *)PyMem_MALLOC(SIZEOF_INT*to_merge_size); + if (remain == NULL) + return -1; + for (i = 0; i < to_merge_size; i++) + remain[i] = 0; again: - empty_cnt = 0; - for (i = 0; i < to_merge_size; i++) { - PyObject *candidate; - - PyObject *cur_list = PyList_GET_ITEM(to_merge, i); - - if (remain[i] >= PyList_GET_SIZE(cur_list)) { - empty_cnt++; - continue; - } - - /* Choose next candidate for MRO. - - The input sequences alone can determine the choice. - If not, choose the class which appears in the MRO - of the earliest direct superclass of the new class. - */ - - candidate = PyList_GET_ITEM(cur_list, remain[i]); - for (j = 0; j < to_merge_size; j++) { - PyObject *j_lst = PyList_GET_ITEM(to_merge, j); - if (tail_contains(j_lst, remain[j], candidate)) { - goto skip; /* continue outer loop */ - } - } - ok = PyList_Append(acc, candidate); - if (ok < 0) { - PyMem_Free(remain); - return -1; - } - for (j = 0; j < to_merge_size; j++) { - PyObject *j_lst = PyList_GET_ITEM(to_merge, j); - if (remain[j] < PyList_GET_SIZE(j_lst) && - PyList_GET_ITEM(j_lst, remain[j]) == candidate) { - remain[j]++; - } - } - goto again; - skip: ; - } - - if (empty_cnt == to_merge_size) { - PyMem_FREE(remain); - return 0; - } - set_mro_error(to_merge, remain); - PyMem_FREE(remain); - return -1; + empty_cnt = 0; + for (i = 0; i < to_merge_size; i++) { + PyObject *candidate; + + PyObject *cur_list = PyList_GET_ITEM(to_merge, i); + + if (remain[i] >= PyList_GET_SIZE(cur_list)) { + empty_cnt++; + continue; + } + + /* Choose next candidate for MRO. + + The input sequences alone can determine the choice. + If not, choose the class which appears in the MRO + of the earliest direct superclass of the new class. + */ + + candidate = PyList_GET_ITEM(cur_list, remain[i]); + for (j = 0; j < to_merge_size; j++) { + PyObject *j_lst = PyList_GET_ITEM(to_merge, j); + if (tail_contains(j_lst, remain[j], candidate)) { + goto skip; /* continue outer loop */ + } + } + ok = PyList_Append(acc, candidate); + if (ok < 0) { + PyMem_Free(remain); + return -1; + } + for (j = 0; j < to_merge_size; j++) { + PyObject *j_lst = PyList_GET_ITEM(to_merge, j); + if (remain[j] < PyList_GET_SIZE(j_lst) && + PyList_GET_ITEM(j_lst, remain[j]) == candidate) { + remain[j]++; + } + } + goto again; + skip: ; + } + + if (empty_cnt == to_merge_size) { + PyMem_FREE(remain); + return 0; + } + set_mro_error(to_merge, remain); + PyMem_FREE(remain); + return -1; } static PyObject * mro_implementation(PyTypeObject *type) { - Py_ssize_t i, n; - int ok; - PyObject *bases, *result; - PyObject *to_merge, *bases_aslist; - - if (type->tp_dict == NULL) { - if (PyType_Ready(type) < 0) - return NULL; - } - - /* Find a superclass linearization that honors the constraints - of the explicit lists of bases and the constraints implied by - each base class. - - to_merge is a list of lists, where each list is a superclass - linearization implied by a base class. The last element of - to_merge is the declared list of bases. - */ - - bases = type->tp_bases; - n = PyTuple_GET_SIZE(bases); - - to_merge = PyList_New(n+1); - if (to_merge == NULL) - return NULL; - - for (i = 0; i < n; i++) { - PyObject *base = PyTuple_GET_ITEM(bases, i); - PyObject *parentMRO; - parentMRO = PySequence_List(((PyTypeObject*)base)->tp_mro); - if (parentMRO == NULL) { - Py_DECREF(to_merge); - return NULL; - } - - PyList_SET_ITEM(to_merge, i, parentMRO); - } - - bases_aslist = PySequence_List(bases); - if (bases_aslist == NULL) { - Py_DECREF(to_merge); - return NULL; - } - /* This is just a basic sanity check. */ - if (check_duplicates(bases_aslist) < 0) { - Py_DECREF(to_merge); - Py_DECREF(bases_aslist); - return NULL; - } - PyList_SET_ITEM(to_merge, n, bases_aslist); - - result = Py_BuildValue("[O]", (PyObject *)type); - if (result == NULL) { - Py_DECREF(to_merge); - return NULL; - } - - ok = pmerge(result, to_merge); - Py_DECREF(to_merge); - if (ok < 0) { - Py_DECREF(result); - return NULL; - } + Py_ssize_t i, n; + int ok; + PyObject *bases, *result; + PyObject *to_merge, *bases_aslist; + + if (type->tp_dict == NULL) { + if (PyType_Ready(type) < 0) + return NULL; + } + + /* Find a superclass linearization that honors the constraints + of the explicit lists of bases and the constraints implied by + each base class. + + to_merge is a list of lists, where each list is a superclass + linearization implied by a base class. The last element of + to_merge is the declared list of bases. + */ + + bases = type->tp_bases; + n = PyTuple_GET_SIZE(bases); + + to_merge = PyList_New(n+1); + if (to_merge == NULL) + return NULL; + + for (i = 0; i < n; i++) { + PyObject *base = PyTuple_GET_ITEM(bases, i); + PyObject *parentMRO; + parentMRO = PySequence_List(((PyTypeObject*)base)->tp_mro); + if (parentMRO == NULL) { + Py_DECREF(to_merge); + return NULL; + } + + PyList_SET_ITEM(to_merge, i, parentMRO); + } - return result; + bases_aslist = PySequence_List(bases); + if (bases_aslist == NULL) { + Py_DECREF(to_merge); + return NULL; + } + /* This is just a basic sanity check. */ + if (check_duplicates(bases_aslist) < 0) { + Py_DECREF(to_merge); + Py_DECREF(bases_aslist); + return NULL; + } + PyList_SET_ITEM(to_merge, n, bases_aslist); + + result = Py_BuildValue("[O]", (PyObject *)type); + if (result == NULL) { + Py_DECREF(to_merge); + return NULL; + } + + ok = pmerge(result, to_merge); + Py_DECREF(to_merge); + if (ok < 0) { + Py_DECREF(result); + return NULL; + } + + return result; } static PyObject * mro_external(PyObject *self) { - PyTypeObject *type = (PyTypeObject *)self; + PyTypeObject *type = (PyTypeObject *)self; - return mro_implementation(type); + return mro_implementation(type); } static int mro_internal(PyTypeObject *type) { - PyObject *mro, *result, *tuple; - int checkit = 0; + PyObject *mro, *result, *tuple; + int checkit = 0; + + if (Py_TYPE(type) == &PyType_Type) { + result = mro_implementation(type); + } + else { + static PyObject *mro_str; + checkit = 1; + mro = lookup_method((PyObject *)type, "mro", &mro_str); + if (mro == NULL) + return -1; + result = PyObject_CallObject(mro, NULL); + Py_DECREF(mro); + } + if (result == NULL) + return -1; + tuple = PySequence_Tuple(result); + Py_DECREF(result); + if (tuple == NULL) + return -1; + if (checkit) { + Py_ssize_t i, len; + PyObject *cls; + PyTypeObject *solid; + + solid = solid_base(type); + + len = PyTuple_GET_SIZE(tuple); + + for (i = 0; i < len; i++) { + PyTypeObject *t; + cls = PyTuple_GET_ITEM(tuple, i); + if (!PyType_Check(cls)) { + PyErr_Format(PyExc_TypeError, + "mro() returned a non-class ('%.500s')", + Py_TYPE(cls)->tp_name); + Py_DECREF(tuple); + return -1; + } + t = (PyTypeObject*)cls; + if (!PyType_IsSubtype(solid, solid_base(t))) { + PyErr_Format(PyExc_TypeError, + "mro() returned base with unsuitable layout ('%.500s')", + t->tp_name); + Py_DECREF(tuple); + return -1; + } + } + } + type->tp_mro = tuple; - if (Py_TYPE(type) == &PyType_Type) { - result = mro_implementation(type); - } - else { - static PyObject *mro_str; - checkit = 1; - mro = lookup_method((PyObject *)type, "mro", &mro_str); - if (mro == NULL) - return -1; - result = PyObject_CallObject(mro, NULL); - Py_DECREF(mro); - } - if (result == NULL) - return -1; - tuple = PySequence_Tuple(result); - Py_DECREF(result); - if (tuple == NULL) - return -1; - if (checkit) { - Py_ssize_t i, len; - PyObject *cls; - PyTypeObject *solid; - - solid = solid_base(type); - - len = PyTuple_GET_SIZE(tuple); - - for (i = 0; i < len; i++) { - PyTypeObject *t; - cls = PyTuple_GET_ITEM(tuple, i); - if (!PyType_Check(cls)) { - PyErr_Format(PyExc_TypeError, - "mro() returned a non-class ('%.500s')", - Py_TYPE(cls)->tp_name); - Py_DECREF(tuple); - return -1; - } - t = (PyTypeObject*)cls; - if (!PyType_IsSubtype(solid, solid_base(t))) { - PyErr_Format(PyExc_TypeError, - "mro() returned base with unsuitable layout ('%.500s')", - t->tp_name); - Py_DECREF(tuple); - return -1; - } - } - } - type->tp_mro = tuple; - - type_mro_modified(type, type->tp_mro); - /* corner case: the old-style super class might have been hidden - from the custom MRO */ - type_mro_modified(type, type->tp_bases); + type_mro_modified(type, type->tp_mro); + /* corner case: the old-style super class might have been hidden + from the custom MRO */ + type_mro_modified(type, type->tp_bases); - PyType_Modified(type); + PyType_Modified(type); - return 0; + return 0; } @@ -1578,90 +1578,90 @@ static PyTypeObject * best_base(PyObject *bases) { - Py_ssize_t i, n; - PyTypeObject *base, *winner, *candidate, *base_i; - PyObject *base_proto; - - assert(PyTuple_Check(bases)); - n = PyTuple_GET_SIZE(bases); - assert(n > 0); - base = NULL; - winner = NULL; - for (i = 0; i < n; i++) { - base_proto = PyTuple_GET_ITEM(bases, i); - if (!PyType_Check(base_proto)) { - PyErr_SetString( - PyExc_TypeError, - "bases must be types"); - return NULL; - } - base_i = (PyTypeObject *)base_proto; - if (base_i->tp_dict == NULL) { - if (PyType_Ready(base_i) < 0) - return NULL; - } - candidate = solid_base(base_i); - if (winner == NULL) { - winner = candidate; - base = base_i; - } - else if (PyType_IsSubtype(winner, candidate)) - ; - else if (PyType_IsSubtype(candidate, winner)) { - winner = candidate; - base = base_i; - } - else { - PyErr_SetString( - PyExc_TypeError, - "multiple bases have " - "instance lay-out conflict"); - return NULL; - } - } - if (base == NULL) - PyErr_SetString(PyExc_TypeError, - "a new-style class can't have only classic bases"); - return base; + Py_ssize_t i, n; + PyTypeObject *base, *winner, *candidate, *base_i; + PyObject *base_proto; + + assert(PyTuple_Check(bases)); + n = PyTuple_GET_SIZE(bases); + assert(n > 0); + base = NULL; + winner = NULL; + for (i = 0; i < n; i++) { + base_proto = PyTuple_GET_ITEM(bases, i); + if (!PyType_Check(base_proto)) { + PyErr_SetString( + PyExc_TypeError, + "bases must be types"); + return NULL; + } + base_i = (PyTypeObject *)base_proto; + if (base_i->tp_dict == NULL) { + if (PyType_Ready(base_i) < 0) + return NULL; + } + candidate = solid_base(base_i); + if (winner == NULL) { + winner = candidate; + base = base_i; + } + else if (PyType_IsSubtype(winner, candidate)) + ; + else if (PyType_IsSubtype(candidate, winner)) { + winner = candidate; + base = base_i; + } + else { + PyErr_SetString( + PyExc_TypeError, + "multiple bases have " + "instance lay-out conflict"); + return NULL; + } + } + if (base == NULL) + PyErr_SetString(PyExc_TypeError, + "a new-style class can't have only classic bases"); + return base; } static int extra_ivars(PyTypeObject *type, PyTypeObject *base) { - size_t t_size = type->tp_basicsize; - size_t b_size = base->tp_basicsize; + size_t t_size = type->tp_basicsize; + size_t b_size = base->tp_basicsize; - assert(t_size >= b_size); /* Else type smaller than base! */ - if (type->tp_itemsize || base->tp_itemsize) { - /* If itemsize is involved, stricter rules */ - return t_size != b_size || - type->tp_itemsize != base->tp_itemsize; - } - if (type->tp_weaklistoffset && base->tp_weaklistoffset == 0 && - type->tp_weaklistoffset + sizeof(PyObject *) == t_size && - type->tp_flags & Py_TPFLAGS_HEAPTYPE) - t_size -= sizeof(PyObject *); - if (type->tp_dictoffset && base->tp_dictoffset == 0 && - type->tp_dictoffset + sizeof(PyObject *) == t_size && - type->tp_flags & Py_TPFLAGS_HEAPTYPE) - t_size -= sizeof(PyObject *); + assert(t_size >= b_size); /* Else type smaller than base! */ + if (type->tp_itemsize || base->tp_itemsize) { + /* If itemsize is involved, stricter rules */ + return t_size != b_size || + type->tp_itemsize != base->tp_itemsize; + } + if (type->tp_weaklistoffset && base->tp_weaklistoffset == 0 && + type->tp_weaklistoffset + sizeof(PyObject *) == t_size && + type->tp_flags & Py_TPFLAGS_HEAPTYPE) + t_size -= sizeof(PyObject *); + if (type->tp_dictoffset && base->tp_dictoffset == 0 && + type->tp_dictoffset + sizeof(PyObject *) == t_size && + type->tp_flags & Py_TPFLAGS_HEAPTYPE) + t_size -= sizeof(PyObject *); - return t_size != b_size; + return t_size != b_size; } static PyTypeObject * solid_base(PyTypeObject *type) { - PyTypeObject *base; + PyTypeObject *base; - if (type->tp_base) - base = solid_base(type->tp_base); - else - base = &PyBaseObject_Type; - if (extra_ivars(type, base)) - return type; - else - return base; + if (type->tp_base) + base = solid_base(type->tp_base); + else + base = &PyBaseObject_Type; + if (extra_ivars(type, base)) + return type; + else + return base; } static void object_dealloc(PyObject *); @@ -1677,180 +1677,180 @@ static PyTypeObject * get_builtin_base_with_dict(PyTypeObject *type) { - while (type->tp_base != NULL) { - if (type->tp_dictoffset != 0 && - !(type->tp_flags & Py_TPFLAGS_HEAPTYPE)) - return type; - type = type->tp_base; - } - return NULL; + while (type->tp_base != NULL) { + if (type->tp_dictoffset != 0 && + !(type->tp_flags & Py_TPFLAGS_HEAPTYPE)) + return type; + type = type->tp_base; + } + return NULL; } static PyObject * get_dict_descriptor(PyTypeObject *type) { - static PyObject *dict_str; - PyObject *descr; + static PyObject *dict_str; + PyObject *descr; - if (dict_str == NULL) { - dict_str = PyUnicode_InternFromString("__dict__"); - if (dict_str == NULL) - return NULL; - } - descr = _PyType_Lookup(type, dict_str); - if (descr == NULL || !PyDescr_IsData(descr)) - return NULL; + if (dict_str == NULL) { + dict_str = PyUnicode_InternFromString("__dict__"); + if (dict_str == NULL) + return NULL; + } + descr = _PyType_Lookup(type, dict_str); + if (descr == NULL || !PyDescr_IsData(descr)) + return NULL; - return descr; + return descr; } static void raise_dict_descr_error(PyObject *obj) { - PyErr_Format(PyExc_TypeError, - "this __dict__ descriptor does not support " - "'%.200s' objects", Py_TYPE(obj)->tp_name); + PyErr_Format(PyExc_TypeError, + "this __dict__ descriptor does not support " + "'%.200s' objects", Py_TYPE(obj)->tp_name); } static PyObject * subtype_dict(PyObject *obj, void *context) { - PyObject **dictptr; - PyObject *dict; - PyTypeObject *base; - - base = get_builtin_base_with_dict(Py_TYPE(obj)); - if (base != NULL) { - descrgetfunc func; - PyObject *descr = get_dict_descriptor(base); - if (descr == NULL) { - raise_dict_descr_error(obj); - return NULL; - } - func = Py_TYPE(descr)->tp_descr_get; - if (func == NULL) { - raise_dict_descr_error(obj); - return NULL; - } - return func(descr, obj, (PyObject *)(Py_TYPE(obj))); - } - - dictptr = _PyObject_GetDictPtr(obj); - if (dictptr == NULL) { - PyErr_SetString(PyExc_AttributeError, - "This object has no __dict__"); - return NULL; - } - dict = *dictptr; - if (dict == NULL) - *dictptr = dict = PyDict_New(); - Py_XINCREF(dict); - return dict; + PyObject **dictptr; + PyObject *dict; + PyTypeObject *base; + + base = get_builtin_base_with_dict(Py_TYPE(obj)); + if (base != NULL) { + descrgetfunc func; + PyObject *descr = get_dict_descriptor(base); + if (descr == NULL) { + raise_dict_descr_error(obj); + return NULL; + } + func = Py_TYPE(descr)->tp_descr_get; + if (func == NULL) { + raise_dict_descr_error(obj); + return NULL; + } + return func(descr, obj, (PyObject *)(Py_TYPE(obj))); + } + + dictptr = _PyObject_GetDictPtr(obj); + if (dictptr == NULL) { + PyErr_SetString(PyExc_AttributeError, + "This object has no __dict__"); + return NULL; + } + dict = *dictptr; + if (dict == NULL) + *dictptr = dict = PyDict_New(); + Py_XINCREF(dict); + return dict; } static int subtype_setdict(PyObject *obj, PyObject *value, void *context) { - PyObject **dictptr; - PyObject *dict; - PyTypeObject *base; - - base = get_builtin_base_with_dict(Py_TYPE(obj)); - if (base != NULL) { - descrsetfunc func; - PyObject *descr = get_dict_descriptor(base); - if (descr == NULL) { - raise_dict_descr_error(obj); - return -1; - } - func = Py_TYPE(descr)->tp_descr_set; - if (func == NULL) { - raise_dict_descr_error(obj); - return -1; - } - return func(descr, obj, value); - } - - dictptr = _PyObject_GetDictPtr(obj); - if (dictptr == NULL) { - PyErr_SetString(PyExc_AttributeError, - "This object has no __dict__"); - return -1; - } - if (value != NULL && !PyDict_Check(value)) { - PyErr_Format(PyExc_TypeError, - "__dict__ must be set to a dictionary, " - "not a '%.200s'", Py_TYPE(value)->tp_name); - return -1; - } - dict = *dictptr; - Py_XINCREF(value); - *dictptr = value; - Py_XDECREF(dict); - return 0; + PyObject **dictptr; + PyObject *dict; + PyTypeObject *base; + + base = get_builtin_base_with_dict(Py_TYPE(obj)); + if (base != NULL) { + descrsetfunc func; + PyObject *descr = get_dict_descriptor(base); + if (descr == NULL) { + raise_dict_descr_error(obj); + return -1; + } + func = Py_TYPE(descr)->tp_descr_set; + if (func == NULL) { + raise_dict_descr_error(obj); + return -1; + } + return func(descr, obj, value); + } + + dictptr = _PyObject_GetDictPtr(obj); + if (dictptr == NULL) { + PyErr_SetString(PyExc_AttributeError, + "This object has no __dict__"); + return -1; + } + if (value != NULL && !PyDict_Check(value)) { + PyErr_Format(PyExc_TypeError, + "__dict__ must be set to a dictionary, " + "not a '%.200s'", Py_TYPE(value)->tp_name); + return -1; + } + dict = *dictptr; + Py_XINCREF(value); + *dictptr = value; + Py_XDECREF(dict); + return 0; } static PyObject * subtype_getweakref(PyObject *obj, void *context) { - PyObject **weaklistptr; - PyObject *result; + PyObject **weaklistptr; + PyObject *result; - if (Py_TYPE(obj)->tp_weaklistoffset == 0) { - PyErr_SetString(PyExc_AttributeError, - "This object has no __weakref__"); - return NULL; - } - assert(Py_TYPE(obj)->tp_weaklistoffset > 0); - assert(Py_TYPE(obj)->tp_weaklistoffset + sizeof(PyObject *) <= - (size_t)(Py_TYPE(obj)->tp_basicsize)); - weaklistptr = (PyObject **) - ((char *)obj + Py_TYPE(obj)->tp_weaklistoffset); - if (*weaklistptr == NULL) - result = Py_None; - else - result = *weaklistptr; - Py_INCREF(result); - return result; + if (Py_TYPE(obj)->tp_weaklistoffset == 0) { + PyErr_SetString(PyExc_AttributeError, + "This object has no __weakref__"); + return NULL; + } + assert(Py_TYPE(obj)->tp_weaklistoffset > 0); + assert(Py_TYPE(obj)->tp_weaklistoffset + sizeof(PyObject *) <= + (size_t)(Py_TYPE(obj)->tp_basicsize)); + weaklistptr = (PyObject **) + ((char *)obj + Py_TYPE(obj)->tp_weaklistoffset); + if (*weaklistptr == NULL) + result = Py_None; + else + result = *weaklistptr; + Py_INCREF(result); + return result; } /* Three variants on the subtype_getsets list. */ static PyGetSetDef subtype_getsets_full[] = { - {"__dict__", subtype_dict, subtype_setdict, - PyDoc_STR("dictionary for instance variables (if defined)")}, - {"__weakref__", subtype_getweakref, NULL, - PyDoc_STR("list of weak references to the object (if defined)")}, - {0} + {"__dict__", subtype_dict, subtype_setdict, + PyDoc_STR("dictionary for instance variables (if defined)")}, + {"__weakref__", subtype_getweakref, NULL, + PyDoc_STR("list of weak references to the object (if defined)")}, + {0} }; static PyGetSetDef subtype_getsets_dict_only[] = { - {"__dict__", subtype_dict, subtype_setdict, - PyDoc_STR("dictionary for instance variables (if defined)")}, - {0} + {"__dict__", subtype_dict, subtype_setdict, + PyDoc_STR("dictionary for instance variables (if defined)")}, + {0} }; static PyGetSetDef subtype_getsets_weakref_only[] = { - {"__weakref__", subtype_getweakref, NULL, - PyDoc_STR("list of weak references to the object (if defined)")}, - {0} + {"__weakref__", subtype_getweakref, NULL, + PyDoc_STR("list of weak references to the object (if defined)")}, + {0} }; static int valid_identifier(PyObject *s) { - if (!PyUnicode_Check(s)) { - PyErr_Format(PyExc_TypeError, - "__slots__ items must be strings, not '%.200s'", - Py_TYPE(s)->tp_name); - return 0; - } - if (!PyUnicode_IsIdentifier(s)) { - PyErr_SetString(PyExc_TypeError, - "__slots__ must be identifiers"); - return 0; - } - return 1; + if (!PyUnicode_Check(s)) { + PyErr_Format(PyExc_TypeError, + "__slots__ items must be strings, not '%.200s'", + Py_TYPE(s)->tp_name); + return 0; + } + if (!PyUnicode_IsIdentifier(s)) { + PyErr_SetString(PyExc_TypeError, + "__slots__ must be identifiers"); + return 0; + } + return 1; } /* Forward */ @@ -1860,435 +1860,435 @@ static int type_init(PyObject *cls, PyObject *args, PyObject *kwds) { - int res; + int res; - assert(args != NULL && PyTuple_Check(args)); - assert(kwds == NULL || PyDict_Check(kwds)); + assert(args != NULL && PyTuple_Check(args)); + assert(kwds == NULL || PyDict_Check(kwds)); - if (kwds != NULL && PyDict_Check(kwds) && PyDict_Size(kwds) != 0) { - PyErr_SetString(PyExc_TypeError, - "type.__init__() takes no keyword arguments"); - return -1; - } - - if (args != NULL && PyTuple_Check(args) && - (PyTuple_GET_SIZE(args) != 1 && PyTuple_GET_SIZE(args) != 3)) { - PyErr_SetString(PyExc_TypeError, - "type.__init__() takes 1 or 3 arguments"); - return -1; - } - - /* Call object.__init__(self) now. */ - /* XXX Could call super(type, cls).__init__() but what's the point? */ - args = PyTuple_GetSlice(args, 0, 0); - res = object_init(cls, args, NULL); - Py_DECREF(args); - return res; + if (kwds != NULL && PyDict_Check(kwds) && PyDict_Size(kwds) != 0) { + PyErr_SetString(PyExc_TypeError, + "type.__init__() takes no keyword arguments"); + return -1; + } + + if (args != NULL && PyTuple_Check(args) && + (PyTuple_GET_SIZE(args) != 1 && PyTuple_GET_SIZE(args) != 3)) { + PyErr_SetString(PyExc_TypeError, + "type.__init__() takes 1 or 3 arguments"); + return -1; + } + + /* Call object.__init__(self) now. */ + /* XXX Could call super(type, cls).__init__() but what's the point? */ + args = PyTuple_GetSlice(args, 0, 0); + res = object_init(cls, args, NULL); + Py_DECREF(args); + return res; } static PyObject * type_new(PyTypeObject *metatype, PyObject *args, PyObject *kwds) { - PyObject *name, *bases, *dict; - static char *kwlist[] = {"name", "bases", "dict", 0}; - PyObject *slots, *tmp, *newslots; - PyTypeObject *type, *base, *tmptype, *winner; - PyHeapTypeObject *et; - PyMemberDef *mp; - Py_ssize_t i, nbases, nslots, slotoffset, add_dict, add_weak; - int j, may_add_dict, may_add_weak; - - assert(args != NULL && PyTuple_Check(args)); - assert(kwds == NULL || PyDict_Check(kwds)); - - /* Special case: type(x) should return x->ob_type */ - { - const Py_ssize_t nargs = PyTuple_GET_SIZE(args); - const Py_ssize_t nkwds = kwds == NULL ? 0 : PyDict_Size(kwds); - - if (PyType_CheckExact(metatype) && nargs == 1 && nkwds == 0) { - PyObject *x = PyTuple_GET_ITEM(args, 0); - Py_INCREF(Py_TYPE(x)); - return (PyObject *) Py_TYPE(x); - } - - /* SF bug 475327 -- if that didn't trigger, we need 3 - arguments. but PyArg_ParseTupleAndKeywords below may give - a msg saying type() needs exactly 3. */ - if (nargs + nkwds != 3) { - PyErr_SetString(PyExc_TypeError, - "type() takes 1 or 3 arguments"); - return NULL; - } - } - - /* Check arguments: (name, bases, dict) */ - if (!PyArg_ParseTupleAndKeywords(args, kwds, "UO!O!:type", kwlist, - &name, - &PyTuple_Type, &bases, - &PyDict_Type, &dict)) - return NULL; - - /* Determine the proper metatype to deal with this, - and check for metatype conflicts while we're at it. - Note that if some other metatype wins to contract, - it's possible that its instances are not types. */ - nbases = PyTuple_GET_SIZE(bases); - winner = metatype; - for (i = 0; i < nbases; i++) { - tmp = PyTuple_GET_ITEM(bases, i); - tmptype = Py_TYPE(tmp); - if (PyType_IsSubtype(winner, tmptype)) - continue; - if (PyType_IsSubtype(tmptype, winner)) { - winner = tmptype; - continue; - } - PyErr_SetString(PyExc_TypeError, - "metaclass conflict: " - "the metaclass of a derived class " - "must be a (non-strict) subclass " - "of the metaclasses of all its bases"); - return NULL; - } - if (winner != metatype) { - if (winner->tp_new != type_new) /* Pass it to the winner */ - return winner->tp_new(winner, args, kwds); - metatype = winner; - } - - /* Adjust for empty tuple bases */ - if (nbases == 0) { - bases = PyTuple_Pack(1, &PyBaseObject_Type); - if (bases == NULL) - return NULL; - nbases = 1; - } - else - Py_INCREF(bases); - - /* XXX From here until type is allocated, "return NULL" leaks bases! */ - - /* Calculate best base, and check that all bases are type objects */ - base = best_base(bases); - if (base == NULL) { - Py_DECREF(bases); - return NULL; - } - if (!PyType_HasFeature(base, Py_TPFLAGS_BASETYPE)) { - PyErr_Format(PyExc_TypeError, - "type '%.100s' is not an acceptable base type", - base->tp_name); - Py_DECREF(bases); - return NULL; - } - - /* Check for a __slots__ sequence variable in dict, and count it */ - slots = PyDict_GetItemString(dict, "__slots__"); - nslots = 0; - add_dict = 0; - add_weak = 0; - may_add_dict = base->tp_dictoffset == 0; - may_add_weak = base->tp_weaklistoffset == 0 && base->tp_itemsize == 0; - if (slots == NULL) { - if (may_add_dict) { - add_dict++; - } - if (may_add_weak) { - add_weak++; - } - } - else { - /* Have slots */ - - /* Make it into a tuple */ - if (PyUnicode_Check(slots)) - slots = PyTuple_Pack(1, slots); - else - slots = PySequence_Tuple(slots); - if (slots == NULL) { - Py_DECREF(bases); - return NULL; - } - assert(PyTuple_Check(slots)); - - /* Are slots allowed? */ - nslots = PyTuple_GET_SIZE(slots); - if (nslots > 0 && base->tp_itemsize != 0) { - PyErr_Format(PyExc_TypeError, - "nonempty __slots__ " - "not supported for subtype of '%s'", - base->tp_name); - bad_slots: - Py_DECREF(bases); - Py_DECREF(slots); - return NULL; - } - - /* Check for valid slot names and two special cases */ - for (i = 0; i < nslots; i++) { - PyObject *tmp = PyTuple_GET_ITEM(slots, i); - if (!valid_identifier(tmp)) - goto bad_slots; - assert(PyUnicode_Check(tmp)); - if (PyUnicode_CompareWithASCIIString(tmp, "__dict__") == 0) { - if (!may_add_dict || add_dict) { - PyErr_SetString(PyExc_TypeError, - "__dict__ slot disallowed: " - "we already got one"); - goto bad_slots; - } - add_dict++; - } - if (PyUnicode_CompareWithASCIIString(tmp, "__weakref__") == 0) { - if (!may_add_weak || add_weak) { - PyErr_SetString(PyExc_TypeError, - "__weakref__ slot disallowed: " - "either we already got one, " - "or __itemsize__ != 0"); - goto bad_slots; - } - add_weak++; - } - } - - /* Copy slots into a list, mangle names and sort them. - Sorted names are needed for __class__ assignment. - Convert them back to tuple at the end. - */ - newslots = PyList_New(nslots - add_dict - add_weak); - if (newslots == NULL) - goto bad_slots; - for (i = j = 0; i < nslots; i++) { - tmp = PyTuple_GET_ITEM(slots, i); - if ((add_dict && - PyUnicode_CompareWithASCIIString(tmp, "__dict__") == 0) || - (add_weak && - PyUnicode_CompareWithASCIIString(tmp, "__weakref__") == 0)) - continue; - tmp =_Py_Mangle(name, tmp); - if (!tmp) - goto bad_slots; - PyList_SET_ITEM(newslots, j, tmp); - j++; - } - assert(j == nslots - add_dict - add_weak); - nslots = j; - Py_DECREF(slots); - if (PyList_Sort(newslots) == -1) { - Py_DECREF(bases); - Py_DECREF(newslots); - return NULL; - } - slots = PyList_AsTuple(newslots); - Py_DECREF(newslots); - if (slots == NULL) { - Py_DECREF(bases); - return NULL; - } - - /* Secondary bases may provide weakrefs or dict */ - if (nbases > 1 && - ((may_add_dict && !add_dict) || - (may_add_weak && !add_weak))) { - for (i = 0; i < nbases; i++) { - tmp = PyTuple_GET_ITEM(bases, i); - if (tmp == (PyObject *)base) - continue; /* Skip primary base */ - assert(PyType_Check(tmp)); - tmptype = (PyTypeObject *)tmp; - if (may_add_dict && !add_dict && - tmptype->tp_dictoffset != 0) - add_dict++; - if (may_add_weak && !add_weak && - tmptype->tp_weaklistoffset != 0) - add_weak++; - if (may_add_dict && !add_dict) - continue; - if (may_add_weak && !add_weak) - continue; - /* Nothing more to check */ - break; - } - } - } - - /* XXX From here until type is safely allocated, - "return NULL" may leak slots! */ - - /* Allocate the type object */ - type = (PyTypeObject *)metatype->tp_alloc(metatype, nslots); - if (type == NULL) { - Py_XDECREF(slots); - Py_DECREF(bases); - return NULL; - } - - /* Keep name and slots alive in the extended type object */ - et = (PyHeapTypeObject *)type; - Py_INCREF(name); - et->ht_name = name; - et->ht_slots = slots; - - /* Initialize tp_flags */ - type->tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HEAPTYPE | - Py_TPFLAGS_BASETYPE; - if (base->tp_flags & Py_TPFLAGS_HAVE_GC) - type->tp_flags |= Py_TPFLAGS_HAVE_GC; - - /* Initialize essential fields */ - type->tp_as_number = &et->as_number; - type->tp_as_sequence = &et->as_sequence; - type->tp_as_mapping = &et->as_mapping; - type->tp_as_buffer = &et->as_buffer; - type->tp_name = _PyUnicode_AsString(name); - if (!type->tp_name) { - Py_DECREF(type); - return NULL; - } - - /* Set tp_base and tp_bases */ - type->tp_bases = bases; - Py_INCREF(base); - type->tp_base = base; - - /* Initialize tp_dict from passed-in dict */ - type->tp_dict = dict = PyDict_Copy(dict); - if (dict == NULL) { - Py_DECREF(type); - return NULL; - } - - /* Set __module__ in the dict */ - if (PyDict_GetItemString(dict, "__module__") == NULL) { - tmp = PyEval_GetGlobals(); - if (tmp != NULL) { - tmp = PyDict_GetItemString(tmp, "__name__"); - if (tmp != NULL) { - if (PyDict_SetItemString(dict, "__module__", - tmp) < 0) - return NULL; - } - } - } - - /* Set tp_doc to a copy of dict['__doc__'], if the latter is there - and is a string. The __doc__ accessor will first look for tp_doc; - if that fails, it will still look into __dict__. - */ - { - PyObject *doc = PyDict_GetItemString(dict, "__doc__"); - if (doc != NULL && PyUnicode_Check(doc)) { - Py_ssize_t len; - char *doc_str; - char *tp_doc; - - doc_str = _PyUnicode_AsString(doc); - if (doc_str == NULL) { - Py_DECREF(type); - return NULL; - } - /* Silently truncate the docstring if it contains null bytes. */ - len = strlen(doc_str); - tp_doc = (char *)PyObject_MALLOC(len + 1); - if (tp_doc == NULL) { - Py_DECREF(type); - return NULL; - } - memcpy(tp_doc, doc_str, len + 1); - type->tp_doc = tp_doc; - } - } - - /* Special-case __new__: if it's a plain function, - make it a static function */ - tmp = PyDict_GetItemString(dict, "__new__"); - if (tmp != NULL && PyFunction_Check(tmp)) { - tmp = PyStaticMethod_New(tmp); - if (tmp == NULL) { - Py_DECREF(type); - return NULL; - } - PyDict_SetItemString(dict, "__new__", tmp); - Py_DECREF(tmp); - } - - /* Add descriptors for custom slots from __slots__, or for __dict__ */ - mp = PyHeapType_GET_MEMBERS(et); - slotoffset = base->tp_basicsize; - if (slots != NULL) { - for (i = 0; i < nslots; i++, mp++) { - mp->name = _PyUnicode_AsString( - PyTuple_GET_ITEM(slots, i)); - mp->type = T_OBJECT_EX; - mp->offset = slotoffset; - - /* __dict__ and __weakref__ are already filtered out */ - assert(strcmp(mp->name, "__dict__") != 0); - assert(strcmp(mp->name, "__weakref__") != 0); - - slotoffset += sizeof(PyObject *); - } - } - if (add_dict) { - if (base->tp_itemsize) - type->tp_dictoffset = -(long)sizeof(PyObject *); - else - type->tp_dictoffset = slotoffset; - slotoffset += sizeof(PyObject *); - } - if (add_weak) { - assert(!base->tp_itemsize); - type->tp_weaklistoffset = slotoffset; - slotoffset += sizeof(PyObject *); - } - type->tp_basicsize = slotoffset; - type->tp_itemsize = base->tp_itemsize; - type->tp_members = PyHeapType_GET_MEMBERS(et); - - if (type->tp_weaklistoffset && type->tp_dictoffset) - type->tp_getset = subtype_getsets_full; - else if (type->tp_weaklistoffset && !type->tp_dictoffset) - type->tp_getset = subtype_getsets_weakref_only; - else if (!type->tp_weaklistoffset && type->tp_dictoffset) - type->tp_getset = subtype_getsets_dict_only; - else - type->tp_getset = NULL; - - /* Special case some slots */ - if (type->tp_dictoffset != 0 || nslots > 0) { - if (base->tp_getattr == NULL && base->tp_getattro == NULL) - type->tp_getattro = PyObject_GenericGetAttr; - if (base->tp_setattr == NULL && base->tp_setattro == NULL) - type->tp_setattro = PyObject_GenericSetAttr; - } - type->tp_dealloc = subtype_dealloc; - - /* Enable GC unless there are really no instance variables possible */ - if (!(type->tp_basicsize == sizeof(PyObject) && - type->tp_itemsize == 0)) - type->tp_flags |= Py_TPFLAGS_HAVE_GC; - - /* Always override allocation strategy to use regular heap */ - type->tp_alloc = PyType_GenericAlloc; - if (type->tp_flags & Py_TPFLAGS_HAVE_GC) { - type->tp_free = PyObject_GC_Del; - type->tp_traverse = subtype_traverse; - type->tp_clear = subtype_clear; - } - else - type->tp_free = PyObject_Del; - - /* Initialize the rest */ - if (PyType_Ready(type) < 0) { - Py_DECREF(type); - return NULL; - } + PyObject *name, *bases, *dict; + static char *kwlist[] = {"name", "bases", "dict", 0}; + PyObject *slots, *tmp, *newslots; + PyTypeObject *type, *base, *tmptype, *winner; + PyHeapTypeObject *et; + PyMemberDef *mp; + Py_ssize_t i, nbases, nslots, slotoffset, add_dict, add_weak; + int j, may_add_dict, may_add_weak; + + assert(args != NULL && PyTuple_Check(args)); + assert(kwds == NULL || PyDict_Check(kwds)); + + /* Special case: type(x) should return x->ob_type */ + { + const Py_ssize_t nargs = PyTuple_GET_SIZE(args); + const Py_ssize_t nkwds = kwds == NULL ? 0 : PyDict_Size(kwds); + + if (PyType_CheckExact(metatype) && nargs == 1 && nkwds == 0) { + PyObject *x = PyTuple_GET_ITEM(args, 0); + Py_INCREF(Py_TYPE(x)); + return (PyObject *) Py_TYPE(x); + } + + /* SF bug 475327 -- if that didn't trigger, we need 3 + arguments. but PyArg_ParseTupleAndKeywords below may give + a msg saying type() needs exactly 3. */ + if (nargs + nkwds != 3) { + PyErr_SetString(PyExc_TypeError, + "type() takes 1 or 3 arguments"); + return NULL; + } + } + + /* Check arguments: (name, bases, dict) */ + if (!PyArg_ParseTupleAndKeywords(args, kwds, "UO!O!:type", kwlist, + &name, + &PyTuple_Type, &bases, + &PyDict_Type, &dict)) + return NULL; + + /* Determine the proper metatype to deal with this, + and check for metatype conflicts while we're at it. + Note that if some other metatype wins to contract, + it's possible that its instances are not types. */ + nbases = PyTuple_GET_SIZE(bases); + winner = metatype; + for (i = 0; i < nbases; i++) { + tmp = PyTuple_GET_ITEM(bases, i); + tmptype = Py_TYPE(tmp); + if (PyType_IsSubtype(winner, tmptype)) + continue; + if (PyType_IsSubtype(tmptype, winner)) { + winner = tmptype; + continue; + } + PyErr_SetString(PyExc_TypeError, + "metaclass conflict: " + "the metaclass of a derived class " + "must be a (non-strict) subclass " + "of the metaclasses of all its bases"); + return NULL; + } + if (winner != metatype) { + if (winner->tp_new != type_new) /* Pass it to the winner */ + return winner->tp_new(winner, args, kwds); + metatype = winner; + } + + /* Adjust for empty tuple bases */ + if (nbases == 0) { + bases = PyTuple_Pack(1, &PyBaseObject_Type); + if (bases == NULL) + return NULL; + nbases = 1; + } + else + Py_INCREF(bases); + + /* XXX From here until type is allocated, "return NULL" leaks bases! */ + + /* Calculate best base, and check that all bases are type objects */ + base = best_base(bases); + if (base == NULL) { + Py_DECREF(bases); + return NULL; + } + if (!PyType_HasFeature(base, Py_TPFLAGS_BASETYPE)) { + PyErr_Format(PyExc_TypeError, + "type '%.100s' is not an acceptable base type", + base->tp_name); + Py_DECREF(bases); + return NULL; + } + + /* Check for a __slots__ sequence variable in dict, and count it */ + slots = PyDict_GetItemString(dict, "__slots__"); + nslots = 0; + add_dict = 0; + add_weak = 0; + may_add_dict = base->tp_dictoffset == 0; + may_add_weak = base->tp_weaklistoffset == 0 && base->tp_itemsize == 0; + if (slots == NULL) { + if (may_add_dict) { + add_dict++; + } + if (may_add_weak) { + add_weak++; + } + } + else { + /* Have slots */ + + /* Make it into a tuple */ + if (PyUnicode_Check(slots)) + slots = PyTuple_Pack(1, slots); + else + slots = PySequence_Tuple(slots); + if (slots == NULL) { + Py_DECREF(bases); + return NULL; + } + assert(PyTuple_Check(slots)); + + /* Are slots allowed? */ + nslots = PyTuple_GET_SIZE(slots); + if (nslots > 0 && base->tp_itemsize != 0) { + PyErr_Format(PyExc_TypeError, + "nonempty __slots__ " + "not supported for subtype of '%s'", + base->tp_name); + bad_slots: + Py_DECREF(bases); + Py_DECREF(slots); + return NULL; + } - /* Put the proper slots in place */ - fixup_slot_dispatchers(type); + /* Check for valid slot names and two special cases */ + for (i = 0; i < nslots; i++) { + PyObject *tmp = PyTuple_GET_ITEM(slots, i); + if (!valid_identifier(tmp)) + goto bad_slots; + assert(PyUnicode_Check(tmp)); + if (PyUnicode_CompareWithASCIIString(tmp, "__dict__") == 0) { + if (!may_add_dict || add_dict) { + PyErr_SetString(PyExc_TypeError, + "__dict__ slot disallowed: " + "we already got one"); + goto bad_slots; + } + add_dict++; + } + if (PyUnicode_CompareWithASCIIString(tmp, "__weakref__") == 0) { + if (!may_add_weak || add_weak) { + PyErr_SetString(PyExc_TypeError, + "__weakref__ slot disallowed: " + "either we already got one, " + "or __itemsize__ != 0"); + goto bad_slots; + } + add_weak++; + } + } - return (PyObject *)type; + /* Copy slots into a list, mangle names and sort them. + Sorted names are needed for __class__ assignment. + Convert them back to tuple at the end. + */ + newslots = PyList_New(nslots - add_dict - add_weak); + if (newslots == NULL) + goto bad_slots; + for (i = j = 0; i < nslots; i++) { + tmp = PyTuple_GET_ITEM(slots, i); + if ((add_dict && + PyUnicode_CompareWithASCIIString(tmp, "__dict__") == 0) || + (add_weak && + PyUnicode_CompareWithASCIIString(tmp, "__weakref__") == 0)) + continue; + tmp =_Py_Mangle(name, tmp); + if (!tmp) + goto bad_slots; + PyList_SET_ITEM(newslots, j, tmp); + j++; + } + assert(j == nslots - add_dict - add_weak); + nslots = j; + Py_DECREF(slots); + if (PyList_Sort(newslots) == -1) { + Py_DECREF(bases); + Py_DECREF(newslots); + return NULL; + } + slots = PyList_AsTuple(newslots); + Py_DECREF(newslots); + if (slots == NULL) { + Py_DECREF(bases); + return NULL; + } + + /* Secondary bases may provide weakrefs or dict */ + if (nbases > 1 && + ((may_add_dict && !add_dict) || + (may_add_weak && !add_weak))) { + for (i = 0; i < nbases; i++) { + tmp = PyTuple_GET_ITEM(bases, i); + if (tmp == (PyObject *)base) + continue; /* Skip primary base */ + assert(PyType_Check(tmp)); + tmptype = (PyTypeObject *)tmp; + if (may_add_dict && !add_dict && + tmptype->tp_dictoffset != 0) + add_dict++; + if (may_add_weak && !add_weak && + tmptype->tp_weaklistoffset != 0) + add_weak++; + if (may_add_dict && !add_dict) + continue; + if (may_add_weak && !add_weak) + continue; + /* Nothing more to check */ + break; + } + } + } + + /* XXX From here until type is safely allocated, + "return NULL" may leak slots! */ + + /* Allocate the type object */ + type = (PyTypeObject *)metatype->tp_alloc(metatype, nslots); + if (type == NULL) { + Py_XDECREF(slots); + Py_DECREF(bases); + return NULL; + } + + /* Keep name and slots alive in the extended type object */ + et = (PyHeapTypeObject *)type; + Py_INCREF(name); + et->ht_name = name; + et->ht_slots = slots; + + /* Initialize tp_flags */ + type->tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HEAPTYPE | + Py_TPFLAGS_BASETYPE; + if (base->tp_flags & Py_TPFLAGS_HAVE_GC) + type->tp_flags |= Py_TPFLAGS_HAVE_GC; + + /* Initialize essential fields */ + type->tp_as_number = &et->as_number; + type->tp_as_sequence = &et->as_sequence; + type->tp_as_mapping = &et->as_mapping; + type->tp_as_buffer = &et->as_buffer; + type->tp_name = _PyUnicode_AsString(name); + if (!type->tp_name) { + Py_DECREF(type); + return NULL; + } + + /* Set tp_base and tp_bases */ + type->tp_bases = bases; + Py_INCREF(base); + type->tp_base = base; + + /* Initialize tp_dict from passed-in dict */ + type->tp_dict = dict = PyDict_Copy(dict); + if (dict == NULL) { + Py_DECREF(type); + return NULL; + } + + /* Set __module__ in the dict */ + if (PyDict_GetItemString(dict, "__module__") == NULL) { + tmp = PyEval_GetGlobals(); + if (tmp != NULL) { + tmp = PyDict_GetItemString(tmp, "__name__"); + if (tmp != NULL) { + if (PyDict_SetItemString(dict, "__module__", + tmp) < 0) + return NULL; + } + } + } + + /* Set tp_doc to a copy of dict['__doc__'], if the latter is there + and is a string. The __doc__ accessor will first look for tp_doc; + if that fails, it will still look into __dict__. + */ + { + PyObject *doc = PyDict_GetItemString(dict, "__doc__"); + if (doc != NULL && PyUnicode_Check(doc)) { + Py_ssize_t len; + char *doc_str; + char *tp_doc; + + doc_str = _PyUnicode_AsString(doc); + if (doc_str == NULL) { + Py_DECREF(type); + return NULL; + } + /* Silently truncate the docstring if it contains null bytes. */ + len = strlen(doc_str); + tp_doc = (char *)PyObject_MALLOC(len + 1); + if (tp_doc == NULL) { + Py_DECREF(type); + return NULL; + } + memcpy(tp_doc, doc_str, len + 1); + type->tp_doc = tp_doc; + } + } + + /* Special-case __new__: if it's a plain function, + make it a static function */ + tmp = PyDict_GetItemString(dict, "__new__"); + if (tmp != NULL && PyFunction_Check(tmp)) { + tmp = PyStaticMethod_New(tmp); + if (tmp == NULL) { + Py_DECREF(type); + return NULL; + } + PyDict_SetItemString(dict, "__new__", tmp); + Py_DECREF(tmp); + } + + /* Add descriptors for custom slots from __slots__, or for __dict__ */ + mp = PyHeapType_GET_MEMBERS(et); + slotoffset = base->tp_basicsize; + if (slots != NULL) { + for (i = 0; i < nslots; i++, mp++) { + mp->name = _PyUnicode_AsString( + PyTuple_GET_ITEM(slots, i)); + mp->type = T_OBJECT_EX; + mp->offset = slotoffset; + + /* __dict__ and __weakref__ are already filtered out */ + assert(strcmp(mp->name, "__dict__") != 0); + assert(strcmp(mp->name, "__weakref__") != 0); + + slotoffset += sizeof(PyObject *); + } + } + if (add_dict) { + if (base->tp_itemsize) + type->tp_dictoffset = -(long)sizeof(PyObject *); + else + type->tp_dictoffset = slotoffset; + slotoffset += sizeof(PyObject *); + } + if (add_weak) { + assert(!base->tp_itemsize); + type->tp_weaklistoffset = slotoffset; + slotoffset += sizeof(PyObject *); + } + type->tp_basicsize = slotoffset; + type->tp_itemsize = base->tp_itemsize; + type->tp_members = PyHeapType_GET_MEMBERS(et); + + if (type->tp_weaklistoffset && type->tp_dictoffset) + type->tp_getset = subtype_getsets_full; + else if (type->tp_weaklistoffset && !type->tp_dictoffset) + type->tp_getset = subtype_getsets_weakref_only; + else if (!type->tp_weaklistoffset && type->tp_dictoffset) + type->tp_getset = subtype_getsets_dict_only; + else + type->tp_getset = NULL; + + /* Special case some slots */ + if (type->tp_dictoffset != 0 || nslots > 0) { + if (base->tp_getattr == NULL && base->tp_getattro == NULL) + type->tp_getattro = PyObject_GenericGetAttr; + if (base->tp_setattr == NULL && base->tp_setattro == NULL) + type->tp_setattro = PyObject_GenericSetAttr; + } + type->tp_dealloc = subtype_dealloc; + + /* Enable GC unless there are really no instance variables possible */ + if (!(type->tp_basicsize == sizeof(PyObject) && + type->tp_itemsize == 0)) + type->tp_flags |= Py_TPFLAGS_HAVE_GC; + + /* Always override allocation strategy to use regular heap */ + type->tp_alloc = PyType_GenericAlloc; + if (type->tp_flags & Py_TPFLAGS_HAVE_GC) { + type->tp_free = PyObject_GC_Del; + type->tp_traverse = subtype_traverse; + type->tp_clear = subtype_clear; + } + else + type->tp_free = PyObject_Del; + + /* Initialize the rest */ + if (PyType_Ready(type) < 0) { + Py_DECREF(type); + return NULL; + } + + /* Put the proper slots in place */ + fixup_slot_dispatchers(type); + + return (PyObject *)type; } /* Internal API to look for a name through the MRO. @@ -2296,50 +2296,50 @@ PyObject * _PyType_Lookup(PyTypeObject *type, PyObject *name) { - Py_ssize_t i, n; - PyObject *mro, *res, *base, *dict; - unsigned int h; - - if (MCACHE_CACHEABLE_NAME(name) && - PyType_HasFeature(type, Py_TPFLAGS_VALID_VERSION_TAG)) { - /* fast path */ - h = MCACHE_HASH_METHOD(type, name); - if (method_cache[h].version == type->tp_version_tag && - method_cache[h].name == name) - return method_cache[h].value; - } - - /* Look in tp_dict of types in MRO */ - mro = type->tp_mro; - - /* If mro is NULL, the type is either not yet initialized - by PyType_Ready(), or already cleared by type_clear(). - Either way the safest thing to do is to return NULL. */ - if (mro == NULL) - return NULL; - - res = NULL; - assert(PyTuple_Check(mro)); - n = PyTuple_GET_SIZE(mro); - for (i = 0; i < n; i++) { - base = PyTuple_GET_ITEM(mro, i); - assert(PyType_Check(base)); - dict = ((PyTypeObject *)base)->tp_dict; - assert(dict && PyDict_Check(dict)); - res = PyDict_GetItem(dict, name); - if (res != NULL) - break; - } - - if (MCACHE_CACHEABLE_NAME(name) && assign_version_tag(type)) { - h = MCACHE_HASH_METHOD(type, name); - method_cache[h].version = type->tp_version_tag; - method_cache[h].value = res; /* borrowed */ - Py_INCREF(name); - Py_DECREF(method_cache[h].name); - method_cache[h].name = name; - } - return res; + Py_ssize_t i, n; + PyObject *mro, *res, *base, *dict; + unsigned int h; + + if (MCACHE_CACHEABLE_NAME(name) && + PyType_HasFeature(type, Py_TPFLAGS_VALID_VERSION_TAG)) { + /* fast path */ + h = MCACHE_HASH_METHOD(type, name); + if (method_cache[h].version == type->tp_version_tag && + method_cache[h].name == name) + return method_cache[h].value; + } + + /* Look in tp_dict of types in MRO */ + mro = type->tp_mro; + + /* If mro is NULL, the type is either not yet initialized + by PyType_Ready(), or already cleared by type_clear(). + Either way the safest thing to do is to return NULL. */ + if (mro == NULL) + return NULL; + + res = NULL; + assert(PyTuple_Check(mro)); + n = PyTuple_GET_SIZE(mro); + for (i = 0; i < n; i++) { + base = PyTuple_GET_ITEM(mro, i); + assert(PyType_Check(base)); + dict = ((PyTypeObject *)base)->tp_dict; + assert(dict && PyDict_Check(dict)); + res = PyDict_GetItem(dict, name); + if (res != NULL) + break; + } + + if (MCACHE_CACHEABLE_NAME(name) && assign_version_tag(type)) { + h = MCACHE_HASH_METHOD(type, name); + method_cache[h].version = type->tp_version_tag; + method_cache[h].value = res; /* borrowed */ + Py_INCREF(name); + Py_DECREF(method_cache[h].name); + method_cache[h].name = name; + } + return res; } /* This is similar to PyObject_GenericGetAttr(), @@ -2347,166 +2347,166 @@ static PyObject * type_getattro(PyTypeObject *type, PyObject *name) { - PyTypeObject *metatype = Py_TYPE(type); - PyObject *meta_attribute, *attribute; - descrgetfunc meta_get; - - /* Initialize this type (we'll assume the metatype is initialized) */ - if (type->tp_dict == NULL) { - if (PyType_Ready(type) < 0) - return NULL; - } - - /* No readable descriptor found yet */ - meta_get = NULL; - - /* Look for the attribute in the metatype */ - meta_attribute = _PyType_Lookup(metatype, name); - - if (meta_attribute != NULL) { - meta_get = Py_TYPE(meta_attribute)->tp_descr_get; - - if (meta_get != NULL && PyDescr_IsData(meta_attribute)) { - /* Data descriptors implement tp_descr_set to intercept - * 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); - } - Py_INCREF(meta_attribute); - } - - /* No data descriptor found on metatype. Look in tp_dict of this - * type and its bases */ - attribute = _PyType_Lookup(type, name); - if (attribute != NULL) { - /* Implement descriptor functionality, if any */ - descrgetfunc 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); - } - - Py_INCREF(attribute); - return attribute; - } - - /* No attribute found in local __dict__ (or bases): use the - * descriptor from the metatype, if any */ - if (meta_get != NULL) { - PyObject *res; - res = meta_get(meta_attribute, (PyObject *)type, - (PyObject *)metatype); - Py_DECREF(meta_attribute); - return res; - } - - /* If an ordinary attribute was found on the metatype, return it now */ - if (meta_attribute != NULL) { - return meta_attribute; - } - - /* Give up */ - PyErr_Format(PyExc_AttributeError, - "type object '%.50s' has no attribute '%U'", - type->tp_name, name); - return NULL; + PyTypeObject *metatype = Py_TYPE(type); + PyObject *meta_attribute, *attribute; + descrgetfunc meta_get; + + /* Initialize this type (we'll assume the metatype is initialized) */ + if (type->tp_dict == NULL) { + if (PyType_Ready(type) < 0) + return NULL; + } + + /* No readable descriptor found yet */ + meta_get = NULL; + + /* Look for the attribute in the metatype */ + meta_attribute = _PyType_Lookup(metatype, name); + + if (meta_attribute != NULL) { + meta_get = Py_TYPE(meta_attribute)->tp_descr_get; + + if (meta_get != NULL && PyDescr_IsData(meta_attribute)) { + /* Data descriptors implement tp_descr_set to intercept + * 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); + } + Py_INCREF(meta_attribute); + } + + /* No data descriptor found on metatype. Look in tp_dict of this + * type and its bases */ + attribute = _PyType_Lookup(type, name); + if (attribute != NULL) { + /* Implement descriptor functionality, if any */ + descrgetfunc 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); + } + + Py_INCREF(attribute); + return attribute; + } + + /* No attribute found in local __dict__ (or bases): use the + * descriptor from the metatype, if any */ + if (meta_get != NULL) { + PyObject *res; + res = meta_get(meta_attribute, (PyObject *)type, + (PyObject *)metatype); + Py_DECREF(meta_attribute); + return res; + } + + /* If an ordinary attribute was found on the metatype, return it now */ + if (meta_attribute != NULL) { + return meta_attribute; + } + + /* Give up */ + PyErr_Format(PyExc_AttributeError, + "type object '%.50s' has no attribute '%U'", + type->tp_name, name); + return NULL; } static int type_setattro(PyTypeObject *type, PyObject *name, PyObject *value) { - if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE)) { - PyErr_Format( - PyExc_TypeError, - "can't set attributes of built-in/extension type '%s'", - type->tp_name); - return -1; - } - if (PyObject_GenericSetAttr((PyObject *)type, name, value) < 0) - return -1; - return update_slot(type, name); + if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE)) { + PyErr_Format( + PyExc_TypeError, + "can't set attributes of built-in/extension type '%s'", + type->tp_name); + return -1; + } + if (PyObject_GenericSetAttr((PyObject *)type, name, value) < 0) + return -1; + return update_slot(type, name); } static void type_dealloc(PyTypeObject *type) { - PyHeapTypeObject *et; + PyHeapTypeObject *et; - /* Assert this is a heap-allocated type object */ - assert(type->tp_flags & Py_TPFLAGS_HEAPTYPE); - _PyObject_GC_UNTRACK(type); - PyObject_ClearWeakRefs((PyObject *)type); - et = (PyHeapTypeObject *)type; - Py_XDECREF(type->tp_base); - Py_XDECREF(type->tp_dict); - Py_XDECREF(type->tp_bases); - Py_XDECREF(type->tp_mro); - Py_XDECREF(type->tp_cache); - Py_XDECREF(type->tp_subclasses); - /* A type's tp_doc is heap allocated, unlike the tp_doc slots - * of most other objects. It's okay to cast it to char *. - */ - PyObject_Free((char *)type->tp_doc); - Py_XDECREF(et->ht_name); - Py_XDECREF(et->ht_slots); - Py_TYPE(type)->tp_free((PyObject *)type); + /* Assert this is a heap-allocated type object */ + assert(type->tp_flags & Py_TPFLAGS_HEAPTYPE); + _PyObject_GC_UNTRACK(type); + PyObject_ClearWeakRefs((PyObject *)type); + et = (PyHeapTypeObject *)type; + Py_XDECREF(type->tp_base); + Py_XDECREF(type->tp_dict); + Py_XDECREF(type->tp_bases); + Py_XDECREF(type->tp_mro); + Py_XDECREF(type->tp_cache); + Py_XDECREF(type->tp_subclasses); + /* A type's tp_doc is heap allocated, unlike the tp_doc slots + * of most other objects. It's okay to cast it to char *. + */ + PyObject_Free((char *)type->tp_doc); + Py_XDECREF(et->ht_name); + Py_XDECREF(et->ht_slots); + Py_TYPE(type)->tp_free((PyObject *)type); } static PyObject * type_subclasses(PyTypeObject *type, PyObject *args_ignored) { - PyObject *list, *raw, *ref; - Py_ssize_t i, n; + PyObject *list, *raw, *ref; + Py_ssize_t i, n; - list = PyList_New(0); - if (list == NULL) - return NULL; - raw = type->tp_subclasses; - if (raw == NULL) - return list; - assert(PyList_Check(raw)); - n = PyList_GET_SIZE(raw); - for (i = 0; i < n; i++) { - ref = PyList_GET_ITEM(raw, i); - assert(PyWeakref_CheckRef(ref)); - ref = PyWeakref_GET_OBJECT(ref); - if (ref != Py_None) { - if (PyList_Append(list, ref) < 0) { - Py_DECREF(list); - return NULL; - } - } - } - return list; + list = PyList_New(0); + if (list == NULL) + return NULL; + raw = type->tp_subclasses; + if (raw == NULL) + return list; + assert(PyList_Check(raw)); + n = PyList_GET_SIZE(raw); + for (i = 0; i < n; i++) { + ref = PyList_GET_ITEM(raw, i); + assert(PyWeakref_CheckRef(ref)); + ref = PyWeakref_GET_OBJECT(ref); + if (ref != Py_None) { + if (PyList_Append(list, ref) < 0) { + Py_DECREF(list); + return NULL; + } + } + } + return list; } static PyObject * type_prepare(PyObject *self, PyObject *args, PyObject *kwds) { - return PyDict_New(); + return PyDict_New(); } static PyMethodDef type_methods[] = { - {"mro", (PyCFunction)mro_external, METH_NOARGS, - PyDoc_STR("mro() -> list\nreturn a type's method resolution order")}, - {"__subclasses__", (PyCFunction)type_subclasses, METH_NOARGS, - PyDoc_STR("__subclasses__() -> list of immediate subclasses")}, - {"__prepare__", (PyCFunction)type_prepare, - METH_VARARGS | METH_KEYWORDS | METH_CLASS, - PyDoc_STR("__prepare__() -> dict\n" - "used to create the namespace for the class statement")}, - {"__instancecheck__", type___instancecheck__, METH_O, - PyDoc_STR("__instancecheck__() -> check if an object is an instance")}, - {"__subclasscheck__", type___subclasscheck__, METH_O, - PyDoc_STR("__subclasschck__ -> check if an class is a subclass")}, - {0} + {"mro", (PyCFunction)mro_external, METH_NOARGS, + PyDoc_STR("mro() -> list\nreturn a type's method resolution order")}, + {"__subclasses__", (PyCFunction)type_subclasses, METH_NOARGS, + PyDoc_STR("__subclasses__() -> list of immediate subclasses")}, + {"__prepare__", (PyCFunction)type_prepare, + METH_VARARGS | METH_KEYWORDS | METH_CLASS, + PyDoc_STR("__prepare__() -> dict\n" + "used to create the namespace for the class statement")}, + {"__instancecheck__", type___instancecheck__, METH_O, + PyDoc_STR("__instancecheck__() -> check if an object is an instance")}, + {"__subclasscheck__", type___subclasscheck__, METH_O, + PyDoc_STR("__subclasschck__ -> check if an class is a subclass")}, + {0} }; PyDoc_STRVAR(type_doc, @@ -2516,109 +2516,109 @@ static int type_traverse(PyTypeObject *type, visitproc visit, void *arg) { - /* Because of type_is_gc(), the collector only calls this - for heaptypes. */ - assert(type->tp_flags & Py_TPFLAGS_HEAPTYPE); - - Py_VISIT(type->tp_dict); - Py_VISIT(type->tp_cache); - Py_VISIT(type->tp_mro); - Py_VISIT(type->tp_bases); - Py_VISIT(type->tp_base); - - /* There's no need to visit type->tp_subclasses or - ((PyHeapTypeObject *)type)->ht_slots, because they can't be involved - in cycles; tp_subclasses is a list of weak references, - and slots is a tuple of strings. */ + /* Because of type_is_gc(), the collector only calls this + for heaptypes. */ + assert(type->tp_flags & Py_TPFLAGS_HEAPTYPE); + + Py_VISIT(type->tp_dict); + Py_VISIT(type->tp_cache); + Py_VISIT(type->tp_mro); + Py_VISIT(type->tp_bases); + Py_VISIT(type->tp_base); + + /* There's no need to visit type->tp_subclasses or + ((PyHeapTypeObject *)type)->ht_slots, because they can't be involved + in cycles; tp_subclasses is a list of weak references, + and slots is a tuple of strings. */ - return 0; + return 0; } static int type_clear(PyTypeObject *type) { - /* Because of type_is_gc(), the collector only calls this - for heaptypes. */ - assert(type->tp_flags & Py_TPFLAGS_HEAPTYPE); - - /* The only field we need to clear is tp_mro, which is part of a - hard cycle (its first element is the class itself) that won't - be broken otherwise (it's a tuple and tuples don't have a - tp_clear handler). None of the other fields need to be - cleared, and here's why: - - tp_dict: - It is a dict, so the collector will call its tp_clear. - - tp_cache: - Not used; if it were, it would be a dict. - - tp_bases, tp_base: - If these are involved in a cycle, there must be at least - one other, mutable object in the cycle, e.g. a base - class's dict; the cycle will be broken that way. - - tp_subclasses: - A list of weak references can't be part of a cycle; and - lists have their own tp_clear. - - slots (in PyHeapTypeObject): - A tuple of strings can't be part of a cycle. - */ + /* Because of type_is_gc(), the collector only calls this + for heaptypes. */ + assert(type->tp_flags & Py_TPFLAGS_HEAPTYPE); + + /* The only field we need to clear is tp_mro, which is part of a + hard cycle (its first element is the class itself) that won't + be broken otherwise (it's a tuple and tuples don't have a + tp_clear handler). None of the other fields need to be + cleared, and here's why: + + tp_dict: + It is a dict, so the collector will call its tp_clear. + + tp_cache: + Not used; if it were, it would be a dict. + + tp_bases, tp_base: + If these are involved in a cycle, there must be at least + one other, mutable object in the cycle, e.g. a base + class's dict; the cycle will be broken that way. + + tp_subclasses: + A list of weak references can't be part of a cycle; and + lists have their own tp_clear. + + slots (in PyHeapTypeObject): + A tuple of strings can't be part of a cycle. + */ - Py_CLEAR(type->tp_mro); + Py_CLEAR(type->tp_mro); - return 0; + return 0; } static int type_is_gc(PyTypeObject *type) { - return type->tp_flags & Py_TPFLAGS_HEAPTYPE; + return type->tp_flags & Py_TPFLAGS_HEAPTYPE; } PyTypeObject PyType_Type = { - PyVarObject_HEAD_INIT(&PyType_Type, 0) - "type", /* tp_name */ - sizeof(PyHeapTypeObject), /* tp_basicsize */ - sizeof(PyMemberDef), /* tp_itemsize */ - (destructor)type_dealloc, /* tp_dealloc */ - 0, /* tp_print */ - 0, /* tp_getattr */ - 0, /* tp_setattr */ - 0, /* tp_reserved */ - (reprfunc)type_repr, /* tp_repr */ - 0, /* tp_as_number */ - 0, /* tp_as_sequence */ - 0, /* tp_as_mapping */ - 0, /* tp_hash */ - (ternaryfunc)type_call, /* tp_call */ - 0, /* tp_str */ - (getattrofunc)type_getattro, /* tp_getattro */ - (setattrofunc)type_setattro, /* tp_setattro */ - 0, /* tp_as_buffer */ - Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC | - Py_TPFLAGS_BASETYPE | Py_TPFLAGS_TYPE_SUBCLASS, /* tp_flags */ - type_doc, /* tp_doc */ - (traverseproc)type_traverse, /* tp_traverse */ - (inquiry)type_clear, /* tp_clear */ - 0, /* tp_richcompare */ - offsetof(PyTypeObject, tp_weaklist), /* tp_weaklistoffset */ - 0, /* tp_iter */ - 0, /* tp_iternext */ - type_methods, /* tp_methods */ - type_members, /* tp_members */ - type_getsets, /* tp_getset */ - 0, /* tp_base */ - 0, /* tp_dict */ - 0, /* tp_descr_get */ - 0, /* tp_descr_set */ - offsetof(PyTypeObject, tp_dict), /* tp_dictoffset */ - type_init, /* tp_init */ - 0, /* tp_alloc */ - type_new, /* tp_new */ - PyObject_GC_Del, /* tp_free */ - (inquiry)type_is_gc, /* tp_is_gc */ + PyVarObject_HEAD_INIT(&PyType_Type, 0) + "type", /* tp_name */ + sizeof(PyHeapTypeObject), /* tp_basicsize */ + sizeof(PyMemberDef), /* tp_itemsize */ + (destructor)type_dealloc, /* tp_dealloc */ + 0, /* tp_print */ + 0, /* tp_getattr */ + 0, /* tp_setattr */ + 0, /* tp_reserved */ + (reprfunc)type_repr, /* tp_repr */ + 0, /* tp_as_number */ + 0, /* tp_as_sequence */ + 0, /* tp_as_mapping */ + 0, /* tp_hash */ + (ternaryfunc)type_call, /* tp_call */ + 0, /* tp_str */ + (getattrofunc)type_getattro, /* tp_getattro */ + (setattrofunc)type_setattro, /* tp_setattro */ + 0, /* tp_as_buffer */ + Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC | + Py_TPFLAGS_BASETYPE | Py_TPFLAGS_TYPE_SUBCLASS, /* tp_flags */ + type_doc, /* tp_doc */ + (traverseproc)type_traverse, /* tp_traverse */ + (inquiry)type_clear, /* tp_clear */ + 0, /* tp_richcompare */ + offsetof(PyTypeObject, tp_weaklist), /* tp_weaklistoffset */ + 0, /* tp_iter */ + 0, /* tp_iternext */ + type_methods, /* tp_methods */ + type_members, /* tp_members */ + type_getsets, /* tp_getset */ + 0, /* tp_base */ + 0, /* tp_dict */ + 0, /* tp_descr_get */ + 0, /* tp_descr_set */ + offsetof(PyTypeObject, tp_dict), /* tp_dictoffset */ + type_init, /* tp_init */ + 0, /* tp_alloc */ + type_new, /* tp_new */ + PyObject_GC_Del, /* tp_free */ + (inquiry)type_is_gc, /* tp_is_gc */ }; @@ -2671,318 +2671,318 @@ static int excess_args(PyObject *args, PyObject *kwds) { - return PyTuple_GET_SIZE(args) || - (kwds && PyDict_Check(kwds) && PyDict_Size(kwds)); + return PyTuple_GET_SIZE(args) || + (kwds && PyDict_Check(kwds) && PyDict_Size(kwds)); } static int object_init(PyObject *self, PyObject *args, PyObject *kwds) { - int err = 0; - if (excess_args(args, kwds)) { - PyTypeObject *type = Py_TYPE(self); - if (type->tp_init != object_init && - type->tp_new != object_new) - { - err = PyErr_WarnEx(PyExc_DeprecationWarning, - "object.__init__() takes no parameters", - 1); - } - else if (type->tp_init != object_init || - type->tp_new == object_new) - { - PyErr_SetString(PyExc_TypeError, - "object.__init__() takes no parameters"); - err = -1; - } - } - return err; + int err = 0; + if (excess_args(args, kwds)) { + PyTypeObject *type = Py_TYPE(self); + if (type->tp_init != object_init && + type->tp_new != object_new) + { + err = PyErr_WarnEx(PyExc_DeprecationWarning, + "object.__init__() takes no parameters", + 1); + } + else if (type->tp_init != object_init || + type->tp_new == object_new) + { + PyErr_SetString(PyExc_TypeError, + "object.__init__() takes no parameters"); + err = -1; + } + } + return err; } static PyObject * object_new(PyTypeObject *type, PyObject *args, PyObject *kwds) { - int err = 0; - if (excess_args(args, kwds)) { - if (type->tp_new != object_new && - type->tp_init != object_init) - { - err = PyErr_WarnEx(PyExc_DeprecationWarning, - "object.__new__() takes no parameters", - 1); - } - else if (type->tp_new != object_new || - type->tp_init == object_init) - { - PyErr_SetString(PyExc_TypeError, - "object.__new__() takes no parameters"); - err = -1; - } - } - if (err < 0) - return NULL; - - if (type->tp_flags & Py_TPFLAGS_IS_ABSTRACT) { - static PyObject *comma = NULL; - PyObject *abstract_methods = NULL; - PyObject *builtins; - PyObject *sorted; - PyObject *sorted_methods = NULL; - PyObject *joined = NULL; - - /* Compute ", ".join(sorted(type.__abstractmethods__)) - into joined. */ - abstract_methods = type_abstractmethods(type, NULL); - if (abstract_methods == NULL) - goto error; - builtins = PyEval_GetBuiltins(); - if (builtins == NULL) - goto error; - sorted = PyDict_GetItemString(builtins, "sorted"); - if (sorted == NULL) - goto error; - sorted_methods = PyObject_CallFunctionObjArgs(sorted, - abstract_methods, - NULL); - if (sorted_methods == NULL) - goto error; - if (comma == NULL) { - comma = PyUnicode_InternFromString(", "); - if (comma == NULL) - goto error; - } - joined = PyObject_CallMethod(comma, "join", - "O", sorted_methods); - if (joined == NULL) - goto error; - - PyErr_Format(PyExc_TypeError, - "Can't instantiate abstract class %s " - "with abstract methods %U", - type->tp_name, - joined); - error: - Py_XDECREF(joined); - Py_XDECREF(sorted_methods); - Py_XDECREF(abstract_methods); - return NULL; - } - return type->tp_alloc(type, 0); + int err = 0; + if (excess_args(args, kwds)) { + if (type->tp_new != object_new && + type->tp_init != object_init) + { + err = PyErr_WarnEx(PyExc_DeprecationWarning, + "object.__new__() takes no parameters", + 1); + } + else if (type->tp_new != object_new || + type->tp_init == object_init) + { + PyErr_SetString(PyExc_TypeError, + "object.__new__() takes no parameters"); + err = -1; + } + } + if (err < 0) + return NULL; + + if (type->tp_flags & Py_TPFLAGS_IS_ABSTRACT) { + static PyObject *comma = NULL; + PyObject *abstract_methods = NULL; + PyObject *builtins; + PyObject *sorted; + PyObject *sorted_methods = NULL; + PyObject *joined = NULL; + + /* Compute ", ".join(sorted(type.__abstractmethods__)) + into joined. */ + abstract_methods = type_abstractmethods(type, NULL); + if (abstract_methods == NULL) + goto error; + builtins = PyEval_GetBuiltins(); + if (builtins == NULL) + goto error; + sorted = PyDict_GetItemString(builtins, "sorted"); + if (sorted == NULL) + goto error; + sorted_methods = PyObject_CallFunctionObjArgs(sorted, + abstract_methods, + NULL); + if (sorted_methods == NULL) + goto error; + if (comma == NULL) { + comma = PyUnicode_InternFromString(", "); + if (comma == NULL) + goto error; + } + joined = PyObject_CallMethod(comma, "join", + "O", sorted_methods); + if (joined == NULL) + goto error; + + PyErr_Format(PyExc_TypeError, + "Can't instantiate abstract class %s " + "with abstract methods %U", + type->tp_name, + joined); + error: + Py_XDECREF(joined); + Py_XDECREF(sorted_methods); + Py_XDECREF(abstract_methods); + return NULL; + } + return type->tp_alloc(type, 0); } static void object_dealloc(PyObject *self) { - Py_TYPE(self)->tp_free(self); + Py_TYPE(self)->tp_free(self); } static PyObject * object_repr(PyObject *self) { - PyTypeObject *type; - PyObject *mod, *name, *rtn; + PyTypeObject *type; + PyObject *mod, *name, *rtn; - type = Py_TYPE(self); - mod = type_module(type, NULL); - if (mod == NULL) - PyErr_Clear(); - else if (!PyUnicode_Check(mod)) { - Py_DECREF(mod); - mod = NULL; - } - name = type_name(type, NULL); - if (name == NULL) - return NULL; - if (mod != NULL && PyUnicode_CompareWithASCIIString(mod, "builtins")) - rtn = PyUnicode_FromFormat("<%U.%U object at %p>", mod, name, self); - else - rtn = PyUnicode_FromFormat("<%s object at %p>", - type->tp_name, self); - Py_XDECREF(mod); - Py_DECREF(name); - return rtn; + type = Py_TYPE(self); + mod = type_module(type, NULL); + if (mod == NULL) + PyErr_Clear(); + else if (!PyUnicode_Check(mod)) { + Py_DECREF(mod); + mod = NULL; + } + name = type_name(type, NULL); + if (name == NULL) + return NULL; + if (mod != NULL && PyUnicode_CompareWithASCIIString(mod, "builtins")) + rtn = PyUnicode_FromFormat("<%U.%U object at %p>", mod, name, self); + else + rtn = PyUnicode_FromFormat("<%s object at %p>", + type->tp_name, self); + Py_XDECREF(mod); + Py_DECREF(name); + return rtn; } static PyObject * object_str(PyObject *self) { - unaryfunc f; + unaryfunc f; - f = Py_TYPE(self)->tp_repr; - if (f == NULL) - f = object_repr; - return f(self); + f = Py_TYPE(self)->tp_repr; + if (f == NULL) + f = object_repr; + return f(self); } static PyObject * object_richcompare(PyObject *self, PyObject *other, int op) { - PyObject *res; + PyObject *res; - switch (op) { + switch (op) { + + case Py_EQ: + /* Return NotImplemented instead of False, so if two + objects are compared, both get a chance at the + comparison. See issue #1393. */ + res = (self == other) ? Py_True : Py_NotImplemented; + Py_INCREF(res); + break; + + case Py_NE: + /* By default, != returns the opposite of ==, + unless the latter returns NotImplemented. */ + res = PyObject_RichCompare(self, other, Py_EQ); + if (res != NULL && res != Py_NotImplemented) { + int ok = PyObject_IsTrue(res); + Py_DECREF(res); + if (ok < 0) + res = NULL; + else { + if (ok) + res = Py_False; + else + res = Py_True; + Py_INCREF(res); + } + } + break; - case Py_EQ: - /* Return NotImplemented instead of False, so if two - objects are compared, both get a chance at the - comparison. See issue #1393. */ - res = (self == other) ? Py_True : Py_NotImplemented; - Py_INCREF(res); - break; - - case Py_NE: - /* By default, != returns the opposite of ==, - unless the latter returns NotImplemented. */ - res = PyObject_RichCompare(self, other, Py_EQ); - if (res != NULL && res != Py_NotImplemented) { - int ok = PyObject_IsTrue(res); - Py_DECREF(res); - if (ok < 0) - res = NULL; - else { - if (ok) - res = Py_False; - else - res = Py_True; - Py_INCREF(res); - } - } - break; - - default: - res = Py_NotImplemented; - Py_INCREF(res); - break; - } + default: + res = Py_NotImplemented; + Py_INCREF(res); + break; + } - return res; + return res; } static PyObject * object_get_class(PyObject *self, void *closure) { - Py_INCREF(Py_TYPE(self)); - return (PyObject *)(Py_TYPE(self)); + Py_INCREF(Py_TYPE(self)); + return (PyObject *)(Py_TYPE(self)); } static int equiv_structs(PyTypeObject *a, PyTypeObject *b) { - return a == b || - (a != NULL && - b != NULL && - a->tp_basicsize == b->tp_basicsize && - a->tp_itemsize == b->tp_itemsize && - a->tp_dictoffset == b->tp_dictoffset && - a->tp_weaklistoffset == b->tp_weaklistoffset && - ((a->tp_flags & Py_TPFLAGS_HAVE_GC) == - (b->tp_flags & Py_TPFLAGS_HAVE_GC))); + return a == b || + (a != NULL && + b != NULL && + a->tp_basicsize == b->tp_basicsize && + a->tp_itemsize == b->tp_itemsize && + a->tp_dictoffset == b->tp_dictoffset && + a->tp_weaklistoffset == b->tp_weaklistoffset && + ((a->tp_flags & Py_TPFLAGS_HAVE_GC) == + (b->tp_flags & Py_TPFLAGS_HAVE_GC))); } static int same_slots_added(PyTypeObject *a, PyTypeObject *b) { - PyTypeObject *base = a->tp_base; - Py_ssize_t size; - PyObject *slots_a, *slots_b; - - if (base != b->tp_base) - return 0; - if (equiv_structs(a, base) && equiv_structs(b, base)) - return 1; - size = base->tp_basicsize; - if (a->tp_dictoffset == size && b->tp_dictoffset == size) - size += sizeof(PyObject *); - if (a->tp_weaklistoffset == size && b->tp_weaklistoffset == size) - size += sizeof(PyObject *); - - /* Check slots compliance */ - slots_a = ((PyHeapTypeObject *)a)->ht_slots; - slots_b = ((PyHeapTypeObject *)b)->ht_slots; - if (slots_a && slots_b) { - if (PyObject_RichCompareBool(slots_a, slots_b, Py_EQ) != 1) - return 0; - size += sizeof(PyObject *) * PyTuple_GET_SIZE(slots_a); - } - return size == a->tp_basicsize && size == b->tp_basicsize; + PyTypeObject *base = a->tp_base; + Py_ssize_t size; + PyObject *slots_a, *slots_b; + + if (base != b->tp_base) + return 0; + if (equiv_structs(a, base) && equiv_structs(b, base)) + return 1; + size = base->tp_basicsize; + if (a->tp_dictoffset == size && b->tp_dictoffset == size) + size += sizeof(PyObject *); + if (a->tp_weaklistoffset == size && b->tp_weaklistoffset == size) + size += sizeof(PyObject *); + + /* Check slots compliance */ + slots_a = ((PyHeapTypeObject *)a)->ht_slots; + slots_b = ((PyHeapTypeObject *)b)->ht_slots; + if (slots_a && slots_b) { + if (PyObject_RichCompareBool(slots_a, slots_b, Py_EQ) != 1) + return 0; + size += sizeof(PyObject *) * PyTuple_GET_SIZE(slots_a); + } + return size == a->tp_basicsize && size == b->tp_basicsize; } static int compatible_for_assignment(PyTypeObject* oldto, PyTypeObject* newto, char* attr) { - PyTypeObject *newbase, *oldbase; + PyTypeObject *newbase, *oldbase; - if (newto->tp_dealloc != oldto->tp_dealloc || - newto->tp_free != oldto->tp_free) - { - PyErr_Format(PyExc_TypeError, - "%s assignment: " - "'%s' deallocator differs from '%s'", - attr, - newto->tp_name, - oldto->tp_name); - return 0; - } - newbase = newto; - oldbase = oldto; - while (equiv_structs(newbase, newbase->tp_base)) - newbase = newbase->tp_base; - while (equiv_structs(oldbase, oldbase->tp_base)) - oldbase = oldbase->tp_base; - if (newbase != oldbase && - (newbase->tp_base != oldbase->tp_base || - !same_slots_added(newbase, oldbase))) { - PyErr_Format(PyExc_TypeError, - "%s assignment: " - "'%s' object layout differs from '%s'", - attr, - newto->tp_name, - oldto->tp_name); - return 0; - } + if (newto->tp_dealloc != oldto->tp_dealloc || + newto->tp_free != oldto->tp_free) + { + PyErr_Format(PyExc_TypeError, + "%s assignment: " + "'%s' deallocator differs from '%s'", + attr, + newto->tp_name, + oldto->tp_name); + return 0; + } + newbase = newto; + oldbase = oldto; + while (equiv_structs(newbase, newbase->tp_base)) + newbase = newbase->tp_base; + while (equiv_structs(oldbase, oldbase->tp_base)) + oldbase = oldbase->tp_base; + if (newbase != oldbase && + (newbase->tp_base != oldbase->tp_base || + !same_slots_added(newbase, oldbase))) { + PyErr_Format(PyExc_TypeError, + "%s assignment: " + "'%s' object layout differs from '%s'", + attr, + newto->tp_name, + oldto->tp_name); + return 0; + } - return 1; + return 1; } static int object_set_class(PyObject *self, PyObject *value, void *closure) { - PyTypeObject *oldto = Py_TYPE(self); - PyTypeObject *newto; + PyTypeObject *oldto = Py_TYPE(self); + PyTypeObject *newto; - if (value == NULL) { - PyErr_SetString(PyExc_TypeError, - "can't delete __class__ attribute"); - return -1; - } - if (!PyType_Check(value)) { - PyErr_Format(PyExc_TypeError, - "__class__ must be set to new-style class, not '%s' object", - Py_TYPE(value)->tp_name); - return -1; - } - newto = (PyTypeObject *)value; - if (!(newto->tp_flags & Py_TPFLAGS_HEAPTYPE) || - !(oldto->tp_flags & Py_TPFLAGS_HEAPTYPE)) - { - PyErr_Format(PyExc_TypeError, - "__class__ assignment: only for heap types"); - return -1; - } - if (compatible_for_assignment(newto, oldto, "__class__")) { - Py_INCREF(newto); - Py_TYPE(self) = newto; - Py_DECREF(oldto); - return 0; - } - else { - return -1; - } + if (value == NULL) { + PyErr_SetString(PyExc_TypeError, + "can't delete __class__ attribute"); + return -1; + } + if (!PyType_Check(value)) { + PyErr_Format(PyExc_TypeError, + "__class__ must be set to new-style class, not '%s' object", + Py_TYPE(value)->tp_name); + return -1; + } + newto = (PyTypeObject *)value; + if (!(newto->tp_flags & Py_TPFLAGS_HEAPTYPE) || + !(oldto->tp_flags & Py_TPFLAGS_HEAPTYPE)) + { + PyErr_Format(PyExc_TypeError, + "__class__ assignment: only for heap types"); + return -1; + } + if (compatible_for_assignment(newto, oldto, "__class__")) { + Py_INCREF(newto); + Py_TYPE(self) = newto; + Py_DECREF(oldto); + return 0; + } + else { + return -1; + } } static PyGetSetDef object_getsets[] = { - {"__class__", object_get_class, object_set_class, - PyDoc_STR("the object's class")}, - {0} + {"__class__", object_get_class, object_set_class, + PyDoc_STR("the object's class")}, + {0} }; @@ -2996,194 +2996,194 @@ static PyObject * import_copyreg(void) { - static PyObject *copyreg_str; + static PyObject *copyreg_str; - if (!copyreg_str) { - copyreg_str = PyUnicode_InternFromString("copyreg"); - if (copyreg_str == NULL) - return NULL; - } + if (!copyreg_str) { + copyreg_str = PyUnicode_InternFromString("copyreg"); + if (copyreg_str == NULL) + return NULL; + } - return PyImport_Import(copyreg_str); + return PyImport_Import(copyreg_str); } static PyObject * slotnames(PyObject *cls) { - PyObject *clsdict; - PyObject *copyreg; - PyObject *slotnames; - - if (!PyType_Check(cls)) { - Py_INCREF(Py_None); - return Py_None; - } - - clsdict = ((PyTypeObject *)cls)->tp_dict; - slotnames = PyDict_GetItemString(clsdict, "__slotnames__"); - if (slotnames != NULL && PyList_Check(slotnames)) { - Py_INCREF(slotnames); - return slotnames; - } - - copyreg = import_copyreg(); - if (copyreg == NULL) - return NULL; - - slotnames = PyObject_CallMethod(copyreg, "_slotnames", "O", cls); - Py_DECREF(copyreg); - if (slotnames != NULL && - slotnames != Py_None && - !PyList_Check(slotnames)) - { - PyErr_SetString(PyExc_TypeError, - "copyreg._slotnames didn't return a list or None"); - Py_DECREF(slotnames); - slotnames = NULL; - } + PyObject *clsdict; + PyObject *copyreg; + PyObject *slotnames; + + if (!PyType_Check(cls)) { + Py_INCREF(Py_None); + return Py_None; + } + + clsdict = ((PyTypeObject *)cls)->tp_dict; + slotnames = PyDict_GetItemString(clsdict, "__slotnames__"); + if (slotnames != NULL && PyList_Check(slotnames)) { + Py_INCREF(slotnames); + return slotnames; + } + + copyreg = import_copyreg(); + if (copyreg == NULL) + return NULL; + + slotnames = PyObject_CallMethod(copyreg, "_slotnames", "O", cls); + Py_DECREF(copyreg); + if (slotnames != NULL && + slotnames != Py_None && + !PyList_Check(slotnames)) + { + PyErr_SetString(PyExc_TypeError, + "copyreg._slotnames didn't return a list or None"); + Py_DECREF(slotnames); + slotnames = NULL; + } - return slotnames; + return slotnames; } static PyObject * reduce_2(PyObject *obj) { - PyObject *cls, *getnewargs; - PyObject *args = NULL, *args2 = NULL; - PyObject *getstate = NULL, *state = NULL, *names = NULL; - PyObject *slots = NULL, *listitems = NULL, *dictitems = NULL; - PyObject *copyreg = NULL, *newobj = NULL, *res = NULL; - Py_ssize_t i, n; - - cls = PyObject_GetAttrString(obj, "__class__"); - if (cls == NULL) - return NULL; - - getnewargs = PyObject_GetAttrString(obj, "__getnewargs__"); - if (getnewargs != NULL) { - args = PyObject_CallObject(getnewargs, NULL); - Py_DECREF(getnewargs); - if (args != NULL && !PyTuple_Check(args)) { - PyErr_Format(PyExc_TypeError, - "__getnewargs__ should return a tuple, " - "not '%.200s'", Py_TYPE(args)->tp_name); - goto end; - } - } - else { - PyErr_Clear(); - args = PyTuple_New(0); - } - if (args == NULL) - goto end; - - getstate = PyObject_GetAttrString(obj, "__getstate__"); - if (getstate != NULL) { - state = PyObject_CallObject(getstate, NULL); - Py_DECREF(getstate); - if (state == NULL) - goto end; - } - else { - PyErr_Clear(); - state = PyObject_GetAttrString(obj, "__dict__"); - if (state == NULL) { - PyErr_Clear(); - state = Py_None; - Py_INCREF(state); - } - names = slotnames(cls); - if (names == NULL) - goto end; - if (names != Py_None) { - assert(PyList_Check(names)); - slots = PyDict_New(); - if (slots == NULL) - goto end; - n = 0; - /* Can't pre-compute the list size; the list - is stored on the class so accessible to other - threads, which may be run by DECREF */ - for (i = 0; i < PyList_GET_SIZE(names); i++) { - PyObject *name, *value; - name = PyList_GET_ITEM(names, i); - value = PyObject_GetAttr(obj, name); - if (value == NULL) - PyErr_Clear(); - else { - int err = PyDict_SetItem(slots, name, - value); - Py_DECREF(value); - if (err) - goto end; - n++; - } - } - if (n) { - state = Py_BuildValue("(NO)", state, slots); - if (state == NULL) - goto end; - } - } - } - - if (!PyList_Check(obj)) { - listitems = Py_None; - Py_INCREF(listitems); - } - else { - listitems = PyObject_GetIter(obj); - if (listitems == NULL) - goto end; - } - - if (!PyDict_Check(obj)) { - dictitems = Py_None; - Py_INCREF(dictitems); - } - else { - PyObject *items = PyObject_CallMethod(obj, "items", ""); - if (items == NULL) - goto end; - dictitems = PyObject_GetIter(items); - Py_DECREF(items); - if (dictitems == NULL) - goto end; - } - - copyreg = import_copyreg(); - if (copyreg == NULL) - goto end; - newobj = PyObject_GetAttrString(copyreg, "__newobj__"); - if (newobj == NULL) - goto end; - - n = PyTuple_GET_SIZE(args); - args2 = PyTuple_New(n+1); - if (args2 == NULL) - goto end; - PyTuple_SET_ITEM(args2, 0, cls); - cls = NULL; - for (i = 0; i < n; i++) { - PyObject *v = PyTuple_GET_ITEM(args, i); - Py_INCREF(v); - PyTuple_SET_ITEM(args2, i+1, v); - } + PyObject *cls, *getnewargs; + PyObject *args = NULL, *args2 = NULL; + PyObject *getstate = NULL, *state = NULL, *names = NULL; + PyObject *slots = NULL, *listitems = NULL, *dictitems = NULL; + PyObject *copyreg = NULL, *newobj = NULL, *res = NULL; + Py_ssize_t i, n; + + cls = PyObject_GetAttrString(obj, "__class__"); + if (cls == NULL) + return NULL; + + getnewargs = PyObject_GetAttrString(obj, "__getnewargs__"); + if (getnewargs != NULL) { + args = PyObject_CallObject(getnewargs, NULL); + Py_DECREF(getnewargs); + if (args != NULL && !PyTuple_Check(args)) { + PyErr_Format(PyExc_TypeError, + "__getnewargs__ should return a tuple, " + "not '%.200s'", Py_TYPE(args)->tp_name); + goto end; + } + } + else { + PyErr_Clear(); + args = PyTuple_New(0); + } + if (args == NULL) + goto end; + + getstate = PyObject_GetAttrString(obj, "__getstate__"); + if (getstate != NULL) { + state = PyObject_CallObject(getstate, NULL); + Py_DECREF(getstate); + if (state == NULL) + goto end; + } + else { + PyErr_Clear(); + state = PyObject_GetAttrString(obj, "__dict__"); + if (state == NULL) { + PyErr_Clear(); + state = Py_None; + Py_INCREF(state); + } + names = slotnames(cls); + if (names == NULL) + goto end; + if (names != Py_None) { + assert(PyList_Check(names)); + slots = PyDict_New(); + if (slots == NULL) + goto end; + n = 0; + /* Can't pre-compute the list size; the list + is stored on the class so accessible to other + threads, which may be run by DECREF */ + for (i = 0; i < PyList_GET_SIZE(names); i++) { + PyObject *name, *value; + name = PyList_GET_ITEM(names, i); + value = PyObject_GetAttr(obj, name); + if (value == NULL) + PyErr_Clear(); + else { + int err = PyDict_SetItem(slots, name, + value); + Py_DECREF(value); + if (err) + goto end; + n++; + } + } + if (n) { + state = Py_BuildValue("(NO)", state, slots); + if (state == NULL) + goto end; + } + } + } + + if (!PyList_Check(obj)) { + listitems = Py_None; + Py_INCREF(listitems); + } + else { + listitems = PyObject_GetIter(obj); + if (listitems == NULL) + goto end; + } + + if (!PyDict_Check(obj)) { + dictitems = Py_None; + Py_INCREF(dictitems); + } + else { + PyObject *items = PyObject_CallMethod(obj, "items", ""); + if (items == NULL) + goto end; + dictitems = PyObject_GetIter(items); + Py_DECREF(items); + if (dictitems == NULL) + goto end; + } + + copyreg = import_copyreg(); + if (copyreg == NULL) + goto end; + newobj = PyObject_GetAttrString(copyreg, "__newobj__"); + if (newobj == NULL) + goto end; + + n = PyTuple_GET_SIZE(args); + args2 = PyTuple_New(n+1); + if (args2 == NULL) + goto end; + PyTuple_SET_ITEM(args2, 0, cls); + cls = NULL; + for (i = 0; i < n; i++) { + PyObject *v = PyTuple_GET_ITEM(args, i); + Py_INCREF(v); + PyTuple_SET_ITEM(args2, i+1, v); + } - res = PyTuple_Pack(5, newobj, args2, state, listitems, dictitems); + res = PyTuple_Pack(5, newobj, args2, state, listitems, dictitems); end: - Py_XDECREF(cls); - Py_XDECREF(args); - Py_XDECREF(args2); - Py_XDECREF(slots); - Py_XDECREF(state); - Py_XDECREF(names); - Py_XDECREF(listitems); - Py_XDECREF(dictitems); - Py_XDECREF(copyreg); - Py_XDECREF(newobj); - return res; + Py_XDECREF(cls); + Py_XDECREF(args); + Py_XDECREF(args2); + Py_XDECREF(slots); + Py_XDECREF(state); + Py_XDECREF(names); + Py_XDECREF(listitems); + Py_XDECREF(dictitems); + Py_XDECREF(copyreg); + Py_XDECREF(newobj); + return res; } /* @@ -3204,79 +3204,79 @@ static PyObject * _common_reduce(PyObject *self, int proto) { - PyObject *copyreg, *res; + PyObject *copyreg, *res; - if (proto >= 2) - return reduce_2(self); + if (proto >= 2) + return reduce_2(self); - copyreg = import_copyreg(); - if (!copyreg) - return NULL; + copyreg = import_copyreg(); + if (!copyreg) + return NULL; - res = PyEval_CallMethod(copyreg, "_reduce_ex", "(Oi)", self, proto); - Py_DECREF(copyreg); + res = PyEval_CallMethod(copyreg, "_reduce_ex", "(Oi)", self, proto); + Py_DECREF(copyreg); - return res; + return res; } static PyObject * object_reduce(PyObject *self, PyObject *args) { - int proto = 0; + int proto = 0; - if (!PyArg_ParseTuple(args, "|i:__reduce__", &proto)) - return NULL; + if (!PyArg_ParseTuple(args, "|i:__reduce__", &proto)) + return NULL; - return _common_reduce(self, proto); + return _common_reduce(self, proto); } static PyObject * object_reduce_ex(PyObject *self, PyObject *args) { - PyObject *reduce, *res; - int proto = 0; + PyObject *reduce, *res; + int proto = 0; - if (!PyArg_ParseTuple(args, "|i:__reduce_ex__", &proto)) - return NULL; + if (!PyArg_ParseTuple(args, "|i:__reduce_ex__", &proto)) + return NULL; - reduce = PyObject_GetAttrString(self, "__reduce__"); - if (reduce == NULL) - PyErr_Clear(); - else { - PyObject *cls, *clsreduce, *objreduce; - int override; - cls = PyObject_GetAttrString(self, "__class__"); - if (cls == NULL) { - Py_DECREF(reduce); - return NULL; - } - clsreduce = PyObject_GetAttrString(cls, "__reduce__"); - Py_DECREF(cls); - if (clsreduce == NULL) { - Py_DECREF(reduce); - return NULL; - } - objreduce = PyDict_GetItemString(PyBaseObject_Type.tp_dict, - "__reduce__"); - override = (clsreduce != objreduce); - Py_DECREF(clsreduce); - if (override) { - res = PyObject_CallObject(reduce, NULL); - Py_DECREF(reduce); - return res; - } - else - Py_DECREF(reduce); - } + reduce = PyObject_GetAttrString(self, "__reduce__"); + if (reduce == NULL) + PyErr_Clear(); + else { + PyObject *cls, *clsreduce, *objreduce; + int override; + cls = PyObject_GetAttrString(self, "__class__"); + if (cls == NULL) { + Py_DECREF(reduce); + return NULL; + } + clsreduce = PyObject_GetAttrString(cls, "__reduce__"); + Py_DECREF(cls); + if (clsreduce == NULL) { + Py_DECREF(reduce); + return NULL; + } + objreduce = PyDict_GetItemString(PyBaseObject_Type.tp_dict, + "__reduce__"); + override = (clsreduce != objreduce); + Py_DECREF(clsreduce); + if (override) { + res = PyObject_CallObject(reduce, NULL); + Py_DECREF(reduce); + return res; + } + else + Py_DECREF(reduce); + } - return _common_reduce(self, proto); + return _common_reduce(self, proto); } static PyObject * object_subclasshook(PyObject *cls, PyObject *args) { - Py_INCREF(Py_NotImplemented); - return Py_NotImplemented; + Py_INCREF(Py_NotImplemented); + return Py_NotImplemented; } PyDoc_STRVAR(object_subclasshook_doc, @@ -3292,104 +3292,104 @@ class object: def __format__(self, format_spec): - return format(str(self), format_spec) + return format(str(self), format_spec) */ static PyObject * object_format(PyObject *self, PyObject *args) { - PyObject *format_spec; - PyObject *self_as_str = NULL; - PyObject *result = NULL; - PyObject *format_meth = NULL; - - if (!PyArg_ParseTuple(args, "U:__format__", &format_spec)) - return NULL; - - self_as_str = PyObject_Str(self); - if (self_as_str != NULL) { - /* find the format function */ - format_meth = PyObject_GetAttrString(self_as_str, "__format__"); - if (format_meth != NULL) { - /* and call it */ - result = PyObject_CallFunctionObjArgs(format_meth, format_spec, NULL); - } + PyObject *format_spec; + PyObject *self_as_str = NULL; + PyObject *result = NULL; + PyObject *format_meth = NULL; + + if (!PyArg_ParseTuple(args, "U:__format__", &format_spec)) + return NULL; + + self_as_str = PyObject_Str(self); + if (self_as_str != NULL) { + /* find the format function */ + format_meth = PyObject_GetAttrString(self_as_str, "__format__"); + if (format_meth != NULL) { + /* and call it */ + result = PyObject_CallFunctionObjArgs(format_meth, format_spec, NULL); } + } - Py_XDECREF(self_as_str); - Py_XDECREF(format_meth); + Py_XDECREF(self_as_str); + Py_XDECREF(format_meth); - return result; + return result; } static PyObject * object_sizeof(PyObject *self, PyObject *args) { - Py_ssize_t res, isize; + Py_ssize_t res, isize; - res = 0; - isize = self->ob_type->tp_itemsize; - if (isize > 0) - res = Py_SIZE(self->ob_type) * isize; - res += self->ob_type->tp_basicsize; + res = 0; + isize = self->ob_type->tp_itemsize; + if (isize > 0) + res = Py_SIZE(self->ob_type) * isize; + res += self->ob_type->tp_basicsize; - return PyLong_FromSsize_t(res); + return PyLong_FromSsize_t(res); } static PyMethodDef object_methods[] = { - {"__reduce_ex__", object_reduce_ex, METH_VARARGS, - PyDoc_STR("helper for pickle")}, - {"__reduce__", object_reduce, METH_VARARGS, - PyDoc_STR("helper for pickle")}, - {"__subclasshook__", object_subclasshook, METH_CLASS | METH_VARARGS, - object_subclasshook_doc}, - {"__format__", object_format, METH_VARARGS, - PyDoc_STR("default object formatter")}, - {"__sizeof__", object_sizeof, METH_NOARGS, - PyDoc_STR("__sizeof__() -> size of object in memory, in bytes")}, - {0} + {"__reduce_ex__", object_reduce_ex, METH_VARARGS, + PyDoc_STR("helper for pickle")}, + {"__reduce__", object_reduce, METH_VARARGS, + PyDoc_STR("helper for pickle")}, + {"__subclasshook__", object_subclasshook, METH_CLASS | METH_VARARGS, + object_subclasshook_doc}, + {"__format__", object_format, METH_VARARGS, + PyDoc_STR("default object formatter")}, + {"__sizeof__", object_sizeof, METH_NOARGS, + PyDoc_STR("__sizeof__() -> size of object in memory, in bytes")}, + {0} }; PyTypeObject PyBaseObject_Type = { - PyVarObject_HEAD_INIT(&PyType_Type, 0) - "object", /* tp_name */ - sizeof(PyObject), /* tp_basicsize */ - 0, /* tp_itemsize */ - object_dealloc, /* tp_dealloc */ - 0, /* tp_print */ - 0, /* tp_getattr */ - 0, /* tp_setattr */ - 0, /* tp_reserved */ - object_repr, /* tp_repr */ - 0, /* tp_as_number */ - 0, /* tp_as_sequence */ - 0, /* tp_as_mapping */ - (hashfunc)_Py_HashPointer, /* tp_hash */ - 0, /* tp_call */ - object_str, /* tp_str */ - PyObject_GenericGetAttr, /* tp_getattro */ - PyObject_GenericSetAttr, /* tp_setattro */ - 0, /* tp_as_buffer */ - Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */ - PyDoc_STR("The most base type"), /* tp_doc */ - 0, /* tp_traverse */ - 0, /* tp_clear */ - object_richcompare, /* tp_richcompare */ - 0, /* tp_weaklistoffset */ - 0, /* tp_iter */ - 0, /* tp_iternext */ - object_methods, /* tp_methods */ - 0, /* tp_members */ - object_getsets, /* tp_getset */ - 0, /* tp_base */ - 0, /* tp_dict */ - 0, /* tp_descr_get */ - 0, /* tp_descr_set */ - 0, /* tp_dictoffset */ - object_init, /* tp_init */ - PyType_GenericAlloc, /* tp_alloc */ - object_new, /* tp_new */ - PyObject_Del, /* tp_free */ + PyVarObject_HEAD_INIT(&PyType_Type, 0) + "object", /* tp_name */ + sizeof(PyObject), /* tp_basicsize */ + 0, /* tp_itemsize */ + object_dealloc, /* tp_dealloc */ + 0, /* tp_print */ + 0, /* tp_getattr */ + 0, /* tp_setattr */ + 0, /* tp_reserved */ + object_repr, /* tp_repr */ + 0, /* tp_as_number */ + 0, /* tp_as_sequence */ + 0, /* tp_as_mapping */ + (hashfunc)_Py_HashPointer, /* tp_hash */ + 0, /* tp_call */ + object_str, /* tp_str */ + PyObject_GenericGetAttr, /* tp_getattro */ + PyObject_GenericSetAttr, /* tp_setattro */ + 0, /* tp_as_buffer */ + Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */ + PyDoc_STR("The most base type"), /* tp_doc */ + 0, /* tp_traverse */ + 0, /* tp_clear */ + object_richcompare, /* tp_richcompare */ + 0, /* tp_weaklistoffset */ + 0, /* tp_iter */ + 0, /* tp_iternext */ + object_methods, /* tp_methods */ + 0, /* tp_members */ + object_getsets, /* tp_getset */ + 0, /* tp_base */ + 0, /* tp_dict */ + 0, /* tp_descr_get */ + 0, /* tp_descr_set */ + 0, /* tp_dictoffset */ + object_init, /* tp_init */ + PyType_GenericAlloc, /* tp_alloc */ + object_new, /* tp_new */ + PyObject_Del, /* tp_free */ }; @@ -3398,168 +3398,168 @@ static int add_methods(PyTypeObject *type, PyMethodDef *meth) { - PyObject *dict = type->tp_dict; + PyObject *dict = type->tp_dict; - for (; meth->ml_name != NULL; meth++) { - PyObject *descr; - if (PyDict_GetItemString(dict, meth->ml_name) && - !(meth->ml_flags & METH_COEXIST)) - continue; - if (meth->ml_flags & METH_CLASS) { - if (meth->ml_flags & METH_STATIC) { - PyErr_SetString(PyExc_ValueError, - "method cannot be both class and static"); - return -1; - } - descr = PyDescr_NewClassMethod(type, meth); - } - else if (meth->ml_flags & METH_STATIC) { - PyObject *cfunc = PyCFunction_New(meth, NULL); - if (cfunc == NULL) - return -1; - descr = PyStaticMethod_New(cfunc); - Py_DECREF(cfunc); - } - else { - descr = PyDescr_NewMethod(type, meth); - } - if (descr == NULL) - return -1; - if (PyDict_SetItemString(dict, meth->ml_name, descr) < 0) - return -1; - Py_DECREF(descr); - } - return 0; + for (; meth->ml_name != NULL; meth++) { + PyObject *descr; + if (PyDict_GetItemString(dict, meth->ml_name) && + !(meth->ml_flags & METH_COEXIST)) + continue; + if (meth->ml_flags & METH_CLASS) { + if (meth->ml_flags & METH_STATIC) { + PyErr_SetString(PyExc_ValueError, + "method cannot be both class and static"); + return -1; + } + descr = PyDescr_NewClassMethod(type, meth); + } + else if (meth->ml_flags & METH_STATIC) { + PyObject *cfunc = PyCFunction_New(meth, NULL); + if (cfunc == NULL) + return -1; + descr = PyStaticMethod_New(cfunc); + Py_DECREF(cfunc); + } + else { + descr = PyDescr_NewMethod(type, meth); + } + if (descr == NULL) + return -1; + if (PyDict_SetItemString(dict, meth->ml_name, descr) < 0) + return -1; + Py_DECREF(descr); + } + return 0; } static int add_members(PyTypeObject *type, PyMemberDef *memb) { - PyObject *dict = type->tp_dict; + PyObject *dict = type->tp_dict; - for (; memb->name != NULL; memb++) { - PyObject *descr; - if (PyDict_GetItemString(dict, memb->name)) - continue; - descr = PyDescr_NewMember(type, memb); - if (descr == NULL) - return -1; - if (PyDict_SetItemString(dict, memb->name, descr) < 0) - return -1; - Py_DECREF(descr); - } - return 0; + for (; memb->name != NULL; memb++) { + PyObject *descr; + if (PyDict_GetItemString(dict, memb->name)) + continue; + descr = PyDescr_NewMember(type, memb); + if (descr == NULL) + return -1; + if (PyDict_SetItemString(dict, memb->name, descr) < 0) + return -1; + Py_DECREF(descr); + } + return 0; } static int add_getset(PyTypeObject *type, PyGetSetDef *gsp) { - PyObject *dict = type->tp_dict; + PyObject *dict = type->tp_dict; - for (; gsp->name != NULL; gsp++) { - PyObject *descr; - if (PyDict_GetItemString(dict, gsp->name)) - continue; - descr = PyDescr_NewGetSet(type, gsp); - - if (descr == NULL) - return -1; - if (PyDict_SetItemString(dict, gsp->name, descr) < 0) - return -1; - Py_DECREF(descr); - } - return 0; + for (; gsp->name != NULL; gsp++) { + PyObject *descr; + if (PyDict_GetItemString(dict, gsp->name)) + continue; + descr = PyDescr_NewGetSet(type, gsp); + + if (descr == NULL) + return -1; + if (PyDict_SetItemString(dict, gsp->name, descr) < 0) + return -1; + Py_DECREF(descr); + } + return 0; } static void inherit_special(PyTypeObject *type, PyTypeObject *base) { - Py_ssize_t oldsize, newsize; + Py_ssize_t oldsize, newsize; - /* Copying basicsize is connected to the GC flags */ - oldsize = base->tp_basicsize; - newsize = type->tp_basicsize ? type->tp_basicsize : oldsize; - if (!(type->tp_flags & Py_TPFLAGS_HAVE_GC) && - (base->tp_flags & Py_TPFLAGS_HAVE_GC) && - (!type->tp_traverse && !type->tp_clear)) { - type->tp_flags |= Py_TPFLAGS_HAVE_GC; - if (type->tp_traverse == NULL) - type->tp_traverse = base->tp_traverse; - if (type->tp_clear == NULL) - type->tp_clear = base->tp_clear; - } - { - /* The condition below could use some explanation. - It appears that tp_new is not inherited for static types - whose base class is 'object'; this seems to be a precaution - so that old extension types don't suddenly become - callable (object.__new__ wouldn't insure the invariants - that the extension type's own factory function ensures). - Heap types, of course, are under our control, so they do - inherit tp_new; static extension types that specify some - other built-in type as the default are considered - new-style-aware so they also inherit object.__new__. */ - if (base != &PyBaseObject_Type || - (type->tp_flags & Py_TPFLAGS_HEAPTYPE)) { - if (type->tp_new == NULL) - type->tp_new = base->tp_new; - } - } - type->tp_basicsize = newsize; + /* Copying basicsize is connected to the GC flags */ + oldsize = base->tp_basicsize; + newsize = type->tp_basicsize ? type->tp_basicsize : oldsize; + if (!(type->tp_flags & Py_TPFLAGS_HAVE_GC) && + (base->tp_flags & Py_TPFLAGS_HAVE_GC) && + (!type->tp_traverse && !type->tp_clear)) { + type->tp_flags |= Py_TPFLAGS_HAVE_GC; + if (type->tp_traverse == NULL) + type->tp_traverse = base->tp_traverse; + if (type->tp_clear == NULL) + type->tp_clear = base->tp_clear; + } + { + /* The condition below could use some explanation. + It appears that tp_new is not inherited for static types + whose base class is 'object'; this seems to be a precaution + so that old extension types don't suddenly become + callable (object.__new__ wouldn't insure the invariants + that the extension type's own factory function ensures). + Heap types, of course, are under our control, so they do + inherit tp_new; static extension types that specify some + other built-in type as the default are considered + new-style-aware so they also inherit object.__new__. */ + if (base != &PyBaseObject_Type || + (type->tp_flags & Py_TPFLAGS_HEAPTYPE)) { + if (type->tp_new == NULL) + type->tp_new = base->tp_new; + } + } + type->tp_basicsize = newsize; - /* Copy other non-function slots */ + /* Copy other non-function slots */ #undef COPYVAL #define COPYVAL(SLOT) \ - if (type->SLOT == 0) type->SLOT = base->SLOT + if (type->SLOT == 0) type->SLOT = base->SLOT - COPYVAL(tp_itemsize); - COPYVAL(tp_weaklistoffset); - COPYVAL(tp_dictoffset); - - /* Setup fast subclass flags */ - if (PyType_IsSubtype(base, (PyTypeObject*)PyExc_BaseException)) - type->tp_flags |= Py_TPFLAGS_BASE_EXC_SUBCLASS; - else if (PyType_IsSubtype(base, &PyType_Type)) - type->tp_flags |= Py_TPFLAGS_TYPE_SUBCLASS; - else if (PyType_IsSubtype(base, &PyLong_Type)) - type->tp_flags |= Py_TPFLAGS_LONG_SUBCLASS; - else if (PyType_IsSubtype(base, &PyBytes_Type)) - type->tp_flags |= Py_TPFLAGS_BYTES_SUBCLASS; - else if (PyType_IsSubtype(base, &PyUnicode_Type)) - type->tp_flags |= Py_TPFLAGS_UNICODE_SUBCLASS; - else if (PyType_IsSubtype(base, &PyTuple_Type)) - type->tp_flags |= Py_TPFLAGS_TUPLE_SUBCLASS; - else if (PyType_IsSubtype(base, &PyList_Type)) - type->tp_flags |= Py_TPFLAGS_LIST_SUBCLASS; - else if (PyType_IsSubtype(base, &PyDict_Type)) - type->tp_flags |= Py_TPFLAGS_DICT_SUBCLASS; + COPYVAL(tp_itemsize); + COPYVAL(tp_weaklistoffset); + COPYVAL(tp_dictoffset); + + /* Setup fast subclass flags */ + if (PyType_IsSubtype(base, (PyTypeObject*)PyExc_BaseException)) + type->tp_flags |= Py_TPFLAGS_BASE_EXC_SUBCLASS; + else if (PyType_IsSubtype(base, &PyType_Type)) + type->tp_flags |= Py_TPFLAGS_TYPE_SUBCLASS; + else if (PyType_IsSubtype(base, &PyLong_Type)) + type->tp_flags |= Py_TPFLAGS_LONG_SUBCLASS; + else if (PyType_IsSubtype(base, &PyBytes_Type)) + type->tp_flags |= Py_TPFLAGS_BYTES_SUBCLASS; + else if (PyType_IsSubtype(base, &PyUnicode_Type)) + type->tp_flags |= Py_TPFLAGS_UNICODE_SUBCLASS; + else if (PyType_IsSubtype(base, &PyTuple_Type)) + type->tp_flags |= Py_TPFLAGS_TUPLE_SUBCLASS; + else if (PyType_IsSubtype(base, &PyList_Type)) + type->tp_flags |= Py_TPFLAGS_LIST_SUBCLASS; + else if (PyType_IsSubtype(base, &PyDict_Type)) + type->tp_flags |= Py_TPFLAGS_DICT_SUBCLASS; } static char *hash_name_op[] = { - "__eq__", - "__hash__", - NULL + "__eq__", + "__hash__", + NULL }; static int overrides_hash(PyTypeObject *type) { - char **p; - PyObject *dict = type->tp_dict; + char **p; + PyObject *dict = type->tp_dict; - assert(dict != NULL); - for (p = hash_name_op; *p; p++) { - if (PyDict_GetItemString(dict, *p) != NULL) - return 1; - } - return 0; + assert(dict != NULL); + for (p = hash_name_op; *p; p++) { + if (PyDict_GetItemString(dict, *p) != NULL) + return 1; + } + return 0; } static void inherit_slots(PyTypeObject *type, PyTypeObject *base) { - PyTypeObject *basebase; + PyTypeObject *basebase; #undef SLOTDEFINED #undef COPYSLOT @@ -3569,147 +3569,147 @@ #undef COPYBUF #define SLOTDEFINED(SLOT) \ - (base->SLOT != 0 && \ - (basebase == NULL || base->SLOT != basebase->SLOT)) + (base->SLOT != 0 && \ + (basebase == NULL || base->SLOT != basebase->SLOT)) #define COPYSLOT(SLOT) \ - if (!type->SLOT && SLOTDEFINED(SLOT)) type->SLOT = base->SLOT + if (!type->SLOT && SLOTDEFINED(SLOT)) type->SLOT = base->SLOT #define COPYNUM(SLOT) COPYSLOT(tp_as_number->SLOT) #define COPYSEQ(SLOT) COPYSLOT(tp_as_sequence->SLOT) #define COPYMAP(SLOT) COPYSLOT(tp_as_mapping->SLOT) #define COPYBUF(SLOT) COPYSLOT(tp_as_buffer->SLOT) - /* This won't inherit indirect slots (from tp_as_number etc.) - if type doesn't provide the space. */ + /* This won't inherit indirect slots (from tp_as_number etc.) + if type doesn't provide the space. */ - if (type->tp_as_number != NULL && base->tp_as_number != NULL) { - basebase = base->tp_base; - if (basebase->tp_as_number == NULL) - basebase = NULL; - COPYNUM(nb_add); - COPYNUM(nb_subtract); - COPYNUM(nb_multiply); - COPYNUM(nb_remainder); - COPYNUM(nb_divmod); - COPYNUM(nb_power); - COPYNUM(nb_negative); - COPYNUM(nb_positive); - COPYNUM(nb_absolute); - COPYNUM(nb_bool); - COPYNUM(nb_invert); - COPYNUM(nb_lshift); - COPYNUM(nb_rshift); - COPYNUM(nb_and); - COPYNUM(nb_xor); - COPYNUM(nb_or); - COPYNUM(nb_int); - COPYNUM(nb_float); - COPYNUM(nb_inplace_add); - COPYNUM(nb_inplace_subtract); - COPYNUM(nb_inplace_multiply); - COPYNUM(nb_inplace_remainder); - COPYNUM(nb_inplace_power); - COPYNUM(nb_inplace_lshift); - COPYNUM(nb_inplace_rshift); - COPYNUM(nb_inplace_and); - COPYNUM(nb_inplace_xor); - COPYNUM(nb_inplace_or); - COPYNUM(nb_true_divide); - COPYNUM(nb_floor_divide); - COPYNUM(nb_inplace_true_divide); - COPYNUM(nb_inplace_floor_divide); - COPYNUM(nb_index); - } - - if (type->tp_as_sequence != NULL && base->tp_as_sequence != NULL) { - basebase = base->tp_base; - if (basebase->tp_as_sequence == NULL) - basebase = NULL; - COPYSEQ(sq_length); - COPYSEQ(sq_concat); - COPYSEQ(sq_repeat); - COPYSEQ(sq_item); - COPYSEQ(sq_ass_item); - COPYSEQ(sq_contains); - COPYSEQ(sq_inplace_concat); - COPYSEQ(sq_inplace_repeat); - } - - if (type->tp_as_mapping != NULL && base->tp_as_mapping != NULL) { - basebase = base->tp_base; - if (basebase->tp_as_mapping == NULL) - basebase = NULL; - COPYMAP(mp_length); - COPYMAP(mp_subscript); - COPYMAP(mp_ass_subscript); - } - - if (type->tp_as_buffer != NULL && base->tp_as_buffer != NULL) { - basebase = base->tp_base; - if (basebase->tp_as_buffer == NULL) - basebase = NULL; - COPYBUF(bf_getbuffer); - COPYBUF(bf_releasebuffer); - } - - basebase = base->tp_base; - - COPYSLOT(tp_dealloc); - if (type->tp_getattr == NULL && type->tp_getattro == NULL) { - type->tp_getattr = base->tp_getattr; - type->tp_getattro = base->tp_getattro; - } - if (type->tp_setattr == NULL && type->tp_setattro == NULL) { - type->tp_setattr = base->tp_setattr; - type->tp_setattro = base->tp_setattro; - } - /* tp_reserved is ignored */ - COPYSLOT(tp_repr); - /* tp_hash see tp_richcompare */ - COPYSLOT(tp_call); - COPYSLOT(tp_str); - { - /* Copy comparison-related slots only when - not overriding them anywhere */ - if (type->tp_richcompare == NULL && - type->tp_hash == NULL && - !overrides_hash(type)) - { - type->tp_richcompare = base->tp_richcompare; - type->tp_hash = base->tp_hash; - } - } - { - COPYSLOT(tp_iter); - COPYSLOT(tp_iternext); - } - { - COPYSLOT(tp_descr_get); - COPYSLOT(tp_descr_set); - COPYSLOT(tp_dictoffset); - COPYSLOT(tp_init); - COPYSLOT(tp_alloc); - COPYSLOT(tp_is_gc); - if ((type->tp_flags & Py_TPFLAGS_HAVE_GC) == - (base->tp_flags & Py_TPFLAGS_HAVE_GC)) { - /* They agree about gc. */ - COPYSLOT(tp_free); - } - else if ((type->tp_flags & Py_TPFLAGS_HAVE_GC) && - type->tp_free == NULL && - base->tp_free == PyObject_Free) { - /* A bit of magic to plug in the correct default - * tp_free function when a derived class adds gc, - * didn't define tp_free, and the base uses the - * default non-gc tp_free. - */ - type->tp_free = PyObject_GC_Del; - } - /* else they didn't agree about gc, and there isn't something - * obvious to be done -- the type is on its own. - */ - } + if (type->tp_as_number != NULL && base->tp_as_number != NULL) { + basebase = base->tp_base; + if (basebase->tp_as_number == NULL) + basebase = NULL; + COPYNUM(nb_add); + COPYNUM(nb_subtract); + COPYNUM(nb_multiply); + COPYNUM(nb_remainder); + COPYNUM(nb_divmod); + COPYNUM(nb_power); + COPYNUM(nb_negative); + COPYNUM(nb_positive); + COPYNUM(nb_absolute); + COPYNUM(nb_bool); + COPYNUM(nb_invert); + COPYNUM(nb_lshift); + COPYNUM(nb_rshift); + COPYNUM(nb_and); + COPYNUM(nb_xor); + COPYNUM(nb_or); + COPYNUM(nb_int); + COPYNUM(nb_float); + COPYNUM(nb_inplace_add); + COPYNUM(nb_inplace_subtract); + COPYNUM(nb_inplace_multiply); + COPYNUM(nb_inplace_remainder); + COPYNUM(nb_inplace_power); + COPYNUM(nb_inplace_lshift); + COPYNUM(nb_inplace_rshift); + COPYNUM(nb_inplace_and); + COPYNUM(nb_inplace_xor); + COPYNUM(nb_inplace_or); + COPYNUM(nb_true_divide); + COPYNUM(nb_floor_divide); + COPYNUM(nb_inplace_true_divide); + COPYNUM(nb_inplace_floor_divide); + COPYNUM(nb_index); + } + + if (type->tp_as_sequence != NULL && base->tp_as_sequence != NULL) { + basebase = base->tp_base; + if (basebase->tp_as_sequence == NULL) + basebase = NULL; + COPYSEQ(sq_length); + COPYSEQ(sq_concat); + COPYSEQ(sq_repeat); + COPYSEQ(sq_item); + COPYSEQ(sq_ass_item); + COPYSEQ(sq_contains); + COPYSEQ(sq_inplace_concat); + COPYSEQ(sq_inplace_repeat); + } + + if (type->tp_as_mapping != NULL && base->tp_as_mapping != NULL) { + basebase = base->tp_base; + if (basebase->tp_as_mapping == NULL) + basebase = NULL; + COPYMAP(mp_length); + COPYMAP(mp_subscript); + COPYMAP(mp_ass_subscript); + } + + if (type->tp_as_buffer != NULL && base->tp_as_buffer != NULL) { + basebase = base->tp_base; + if (basebase->tp_as_buffer == NULL) + basebase = NULL; + COPYBUF(bf_getbuffer); + COPYBUF(bf_releasebuffer); + } + + basebase = base->tp_base; + + COPYSLOT(tp_dealloc); + if (type->tp_getattr == NULL && type->tp_getattro == NULL) { + type->tp_getattr = base->tp_getattr; + type->tp_getattro = base->tp_getattro; + } + if (type->tp_setattr == NULL && type->tp_setattro == NULL) { + type->tp_setattr = base->tp_setattr; + type->tp_setattro = base->tp_setattro; + } + /* tp_reserved is ignored */ + COPYSLOT(tp_repr); + /* tp_hash see tp_richcompare */ + COPYSLOT(tp_call); + COPYSLOT(tp_str); + { + /* Copy comparison-related slots only when + not overriding them anywhere */ + if (type->tp_richcompare == NULL && + type->tp_hash == NULL && + !overrides_hash(type)) + { + type->tp_richcompare = base->tp_richcompare; + type->tp_hash = base->tp_hash; + } + } + { + COPYSLOT(tp_iter); + COPYSLOT(tp_iternext); + } + { + COPYSLOT(tp_descr_get); + COPYSLOT(tp_descr_set); + COPYSLOT(tp_dictoffset); + COPYSLOT(tp_init); + COPYSLOT(tp_alloc); + COPYSLOT(tp_is_gc); + if ((type->tp_flags & Py_TPFLAGS_HAVE_GC) == + (base->tp_flags & Py_TPFLAGS_HAVE_GC)) { + /* They agree about gc. */ + COPYSLOT(tp_free); + } + else if ((type->tp_flags & Py_TPFLAGS_HAVE_GC) && + type->tp_free == NULL && + base->tp_free == PyObject_Free) { + /* A bit of magic to plug in the correct default + * tp_free function when a derived class adds gc, + * didn't define tp_free, and the base uses the + * default non-gc tp_free. + */ + type->tp_free = PyObject_GC_Del; + } + /* else they didn't agree about gc, and there isn't something + * obvious to be done -- the type is on its own. + */ + } } static int add_operators(PyTypeObject *); @@ -3717,273 +3717,273 @@ int PyType_Ready(PyTypeObject *type) { - PyObject *dict, *bases; - PyTypeObject *base; - Py_ssize_t i, n; - - if (type->tp_flags & Py_TPFLAGS_READY) { - assert(type->tp_dict != NULL); - return 0; - } - assert((type->tp_flags & Py_TPFLAGS_READYING) == 0); + PyObject *dict, *bases; + PyTypeObject *base; + Py_ssize_t i, n; + + if (type->tp_flags & Py_TPFLAGS_READY) { + assert(type->tp_dict != NULL); + return 0; + } + assert((type->tp_flags & Py_TPFLAGS_READYING) == 0); - type->tp_flags |= Py_TPFLAGS_READYING; + type->tp_flags |= Py_TPFLAGS_READYING; #ifdef Py_TRACE_REFS - /* PyType_Ready is the closest thing we have to a choke point - * for type objects, so is the best place I can think of to try - * to get type objects into the doubly-linked list of all objects. - * Still, not all type objects go thru PyType_Ready. - */ - _Py_AddToAllObjects((PyObject *)type, 0); + /* PyType_Ready is the closest thing we have to a choke point + * for type objects, so is the best place I can think of to try + * to get type objects into the doubly-linked list of all objects. + * Still, not all type objects go thru PyType_Ready. + */ + _Py_AddToAllObjects((PyObject *)type, 0); #endif - /* Initialize tp_base (defaults to BaseObject unless that's us) */ - base = type->tp_base; - if (base == NULL && type != &PyBaseObject_Type) { - base = type->tp_base = &PyBaseObject_Type; - Py_INCREF(base); - } - - /* Now the only way base can still be NULL is if type is - * &PyBaseObject_Type. - */ - - /* Initialize the base class */ - if (base != NULL && base->tp_dict == NULL) { - if (PyType_Ready(base) < 0) - goto error; - } - - /* Initialize ob_type if NULL. This means extensions that want to be - compilable separately on Windows can call PyType_Ready() instead of - initializing the ob_type field of their type objects. */ - /* The test for base != NULL is really unnecessary, since base is only - NULL when type is &PyBaseObject_Type, and we know its ob_type is - not NULL (it's initialized to &PyType_Type). But coverity doesn't - know that. */ - if (Py_TYPE(type) == NULL && base != NULL) - Py_TYPE(type) = Py_TYPE(base); - - /* Initialize tp_bases */ - bases = type->tp_bases; - if (bases == NULL) { - if (base == NULL) - bases = PyTuple_New(0); - else - bases = PyTuple_Pack(1, base); - if (bases == NULL) - goto error; - type->tp_bases = bases; - } - - /* Initialize tp_dict */ - dict = type->tp_dict; - if (dict == NULL) { - dict = PyDict_New(); - if (dict == NULL) - goto error; - type->tp_dict = dict; - } - - /* Add type-specific descriptors to tp_dict */ - if (add_operators(type) < 0) - goto error; - if (type->tp_methods != NULL) { - if (add_methods(type, type->tp_methods) < 0) - goto error; - } - if (type->tp_members != NULL) { - if (add_members(type, type->tp_members) < 0) - goto error; - } - if (type->tp_getset != NULL) { - if (add_getset(type, type->tp_getset) < 0) - goto error; - } - - /* Calculate method resolution order */ - if (mro_internal(type) < 0) { - goto error; - } - - /* Inherit special flags from dominant base */ - if (type->tp_base != NULL) - inherit_special(type, type->tp_base); - - /* Initialize tp_dict properly */ - bases = type->tp_mro; - assert(bases != NULL); - assert(PyTuple_Check(bases)); - n = PyTuple_GET_SIZE(bases); - for (i = 1; i < n; i++) { - PyObject *b = PyTuple_GET_ITEM(bases, i); - if (PyType_Check(b)) - inherit_slots(type, (PyTypeObject *)b); - } - - /* Sanity check for tp_free. */ - if (PyType_IS_GC(type) && (type->tp_flags & Py_TPFLAGS_BASETYPE) && - (type->tp_free == NULL || type->tp_free == PyObject_Del)) { - /* This base class needs to call tp_free, but doesn't have - * one, or its tp_free is for non-gc'ed objects. - */ - PyErr_Format(PyExc_TypeError, "type '%.100s' participates in " - "gc and is a base type but has inappropriate " - "tp_free slot", - type->tp_name); - goto error; - } - - /* if the type dictionary doesn't contain a __doc__, set it from - the tp_doc slot. - */ - if (PyDict_GetItemString(type->tp_dict, "__doc__") == NULL) { - if (type->tp_doc != NULL) { - PyObject *doc = PyUnicode_FromString(type->tp_doc); - if (doc == NULL) - goto error; - PyDict_SetItemString(type->tp_dict, "__doc__", doc); - Py_DECREF(doc); - } else { - PyDict_SetItemString(type->tp_dict, - "__doc__", Py_None); - } - } - - /* Hack for tp_hash and __hash__. - If after all that, tp_hash is still NULL, and __hash__ is not in - tp_dict, set tp_hash to PyObject_HashNotImplemented and - tp_dict['__hash__'] equal to None. - This signals that __hash__ is not inherited. - */ - if (type->tp_hash == NULL) { - if (PyDict_GetItemString(type->tp_dict, "__hash__") == NULL) { - if (PyDict_SetItemString(type->tp_dict, "__hash__", Py_None) < 0) - goto error; - type->tp_hash = PyObject_HashNotImplemented; - } - } - - /* Some more special stuff */ - base = type->tp_base; - if (base != NULL) { - if (type->tp_as_number == NULL) - type->tp_as_number = base->tp_as_number; - if (type->tp_as_sequence == NULL) - type->tp_as_sequence = base->tp_as_sequence; - if (type->tp_as_mapping == NULL) - type->tp_as_mapping = base->tp_as_mapping; - if (type->tp_as_buffer == NULL) - type->tp_as_buffer = base->tp_as_buffer; - } - - /* Link into each base class's list of subclasses */ - bases = type->tp_bases; - n = PyTuple_GET_SIZE(bases); - for (i = 0; i < n; i++) { - PyObject *b = PyTuple_GET_ITEM(bases, i); - if (PyType_Check(b) && - add_subclass((PyTypeObject *)b, type) < 0) - goto error; - } - - /* Warn for a type that implements tp_compare (now known as - tp_reserved) but not tp_richcompare. */ - if (type->tp_reserved && !type->tp_richcompare) { - int error; - char msg[240]; - PyOS_snprintf(msg, sizeof(msg), - "Type %.100s defines tp_reserved (formerly " - "tp_compare) but not tp_richcompare. " - "Comparisons may not behave as intended.", - type->tp_name); - error = PyErr_WarnEx(PyExc_DeprecationWarning, msg, 1); - if (error == -1) - goto error; - } - - /* All done -- set the ready flag */ - assert(type->tp_dict != NULL); - type->tp_flags = - (type->tp_flags & ~Py_TPFLAGS_READYING) | Py_TPFLAGS_READY; - return 0; + /* Initialize tp_base (defaults to BaseObject unless that's us) */ + base = type->tp_base; + if (base == NULL && type != &PyBaseObject_Type) { + base = type->tp_base = &PyBaseObject_Type; + Py_INCREF(base); + } + + /* Now the only way base can still be NULL is if type is + * &PyBaseObject_Type. + */ + + /* Initialize the base class */ + if (base != NULL && base->tp_dict == NULL) { + if (PyType_Ready(base) < 0) + goto error; + } + + /* Initialize ob_type if NULL. This means extensions that want to be + compilable separately on Windows can call PyType_Ready() instead of + initializing the ob_type field of their type objects. */ + /* The test for base != NULL is really unnecessary, since base is only + NULL when type is &PyBaseObject_Type, and we know its ob_type is + not NULL (it's initialized to &PyType_Type). But coverity doesn't + know that. */ + if (Py_TYPE(type) == NULL && base != NULL) + Py_TYPE(type) = Py_TYPE(base); + + /* Initialize tp_bases */ + bases = type->tp_bases; + if (bases == NULL) { + if (base == NULL) + bases = PyTuple_New(0); + else + bases = PyTuple_Pack(1, base); + if (bases == NULL) + goto error; + type->tp_bases = bases; + } + + /* Initialize tp_dict */ + dict = type->tp_dict; + if (dict == NULL) { + dict = PyDict_New(); + if (dict == NULL) + goto error; + type->tp_dict = dict; + } + + /* Add type-specific descriptors to tp_dict */ + if (add_operators(type) < 0) + goto error; + if (type->tp_methods != NULL) { + if (add_methods(type, type->tp_methods) < 0) + goto error; + } + if (type->tp_members != NULL) { + if (add_members(type, type->tp_members) < 0) + goto error; + } + if (type->tp_getset != NULL) { + if (add_getset(type, type->tp_getset) < 0) + goto error; + } + + /* Calculate method resolution order */ + if (mro_internal(type) < 0) { + goto error; + } + + /* Inherit special flags from dominant base */ + if (type->tp_base != NULL) + inherit_special(type, type->tp_base); + + /* Initialize tp_dict properly */ + bases = type->tp_mro; + assert(bases != NULL); + assert(PyTuple_Check(bases)); + n = PyTuple_GET_SIZE(bases); + for (i = 1; i < n; i++) { + PyObject *b = PyTuple_GET_ITEM(bases, i); + if (PyType_Check(b)) + inherit_slots(type, (PyTypeObject *)b); + } + + /* Sanity check for tp_free. */ + if (PyType_IS_GC(type) && (type->tp_flags & Py_TPFLAGS_BASETYPE) && + (type->tp_free == NULL || type->tp_free == PyObject_Del)) { + /* This base class needs to call tp_free, but doesn't have + * one, or its tp_free is for non-gc'ed objects. + */ + PyErr_Format(PyExc_TypeError, "type '%.100s' participates in " + "gc and is a base type but has inappropriate " + "tp_free slot", + type->tp_name); + goto error; + } + + /* if the type dictionary doesn't contain a __doc__, set it from + the tp_doc slot. + */ + if (PyDict_GetItemString(type->tp_dict, "__doc__") == NULL) { + if (type->tp_doc != NULL) { + PyObject *doc = PyUnicode_FromString(type->tp_doc); + if (doc == NULL) + goto error; + PyDict_SetItemString(type->tp_dict, "__doc__", doc); + Py_DECREF(doc); + } else { + PyDict_SetItemString(type->tp_dict, + "__doc__", Py_None); + } + } + + /* Hack for tp_hash and __hash__. + If after all that, tp_hash is still NULL, and __hash__ is not in + tp_dict, set tp_hash to PyObject_HashNotImplemented and + tp_dict['__hash__'] equal to None. + This signals that __hash__ is not inherited. + */ + if (type->tp_hash == NULL) { + if (PyDict_GetItemString(type->tp_dict, "__hash__") == NULL) { + if (PyDict_SetItemString(type->tp_dict, "__hash__", Py_None) < 0) + goto error; + type->tp_hash = PyObject_HashNotImplemented; + } + } + + /* Some more special stuff */ + base = type->tp_base; + if (base != NULL) { + if (type->tp_as_number == NULL) + type->tp_as_number = base->tp_as_number; + if (type->tp_as_sequence == NULL) + type->tp_as_sequence = base->tp_as_sequence; + if (type->tp_as_mapping == NULL) + type->tp_as_mapping = base->tp_as_mapping; + if (type->tp_as_buffer == NULL) + type->tp_as_buffer = base->tp_as_buffer; + } + + /* Link into each base class's list of subclasses */ + bases = type->tp_bases; + n = PyTuple_GET_SIZE(bases); + for (i = 0; i < n; i++) { + PyObject *b = PyTuple_GET_ITEM(bases, i); + if (PyType_Check(b) && + add_subclass((PyTypeObject *)b, type) < 0) + goto error; + } + + /* Warn for a type that implements tp_compare (now known as + tp_reserved) but not tp_richcompare. */ + if (type->tp_reserved && !type->tp_richcompare) { + int error; + char msg[240]; + PyOS_snprintf(msg, sizeof(msg), + "Type %.100s defines tp_reserved (formerly " + "tp_compare) but not tp_richcompare. " + "Comparisons may not behave as intended.", + type->tp_name); + error = PyErr_WarnEx(PyExc_DeprecationWarning, msg, 1); + if (error == -1) + goto error; + } + + /* All done -- set the ready flag */ + assert(type->tp_dict != NULL); + type->tp_flags = + (type->tp_flags & ~Py_TPFLAGS_READYING) | Py_TPFLAGS_READY; + return 0; error: - type->tp_flags &= ~Py_TPFLAGS_READYING; - return -1; + type->tp_flags &= ~Py_TPFLAGS_READYING; + return -1; } static int add_subclass(PyTypeObject *base, PyTypeObject *type) { - Py_ssize_t i; - int result; - PyObject *list, *ref, *newobj; - - list = base->tp_subclasses; - if (list == NULL) { - base->tp_subclasses = list = PyList_New(0); - if (list == NULL) - return -1; - } - assert(PyList_Check(list)); - newobj = PyWeakref_NewRef((PyObject *)type, NULL); - i = PyList_GET_SIZE(list); - while (--i >= 0) { - ref = PyList_GET_ITEM(list, i); - assert(PyWeakref_CheckRef(ref)); - if (PyWeakref_GET_OBJECT(ref) == Py_None) - return PyList_SetItem(list, i, newobj); - } - result = PyList_Append(list, newobj); - Py_DECREF(newobj); - return result; + Py_ssize_t i; + int result; + PyObject *list, *ref, *newobj; + + list = base->tp_subclasses; + if (list == NULL) { + base->tp_subclasses = list = PyList_New(0); + if (list == NULL) + return -1; + } + assert(PyList_Check(list)); + newobj = PyWeakref_NewRef((PyObject *)type, NULL); + i = PyList_GET_SIZE(list); + while (--i >= 0) { + ref = PyList_GET_ITEM(list, i); + assert(PyWeakref_CheckRef(ref)); + if (PyWeakref_GET_OBJECT(ref) == Py_None) + return PyList_SetItem(list, i, newobj); + } + result = PyList_Append(list, newobj); + Py_DECREF(newobj); + return result; } static void remove_subclass(PyTypeObject *base, PyTypeObject *type) { - Py_ssize_t i; - PyObject *list, *ref; + Py_ssize_t i; + PyObject *list, *ref; - list = base->tp_subclasses; - if (list == NULL) { - return; - } - assert(PyList_Check(list)); - i = PyList_GET_SIZE(list); - while (--i >= 0) { - ref = PyList_GET_ITEM(list, i); - assert(PyWeakref_CheckRef(ref)); - if (PyWeakref_GET_OBJECT(ref) == (PyObject*)type) { - /* this can't fail, right? */ - PySequence_DelItem(list, i); - return; - } - } + list = base->tp_subclasses; + if (list == NULL) { + return; + } + assert(PyList_Check(list)); + i = PyList_GET_SIZE(list); + while (--i >= 0) { + ref = PyList_GET_ITEM(list, i); + assert(PyWeakref_CheckRef(ref)); + if (PyWeakref_GET_OBJECT(ref) == (PyObject*)type) { + /* this can't fail, right? */ + PySequence_DelItem(list, i); + return; + } + } } static int check_num_args(PyObject *ob, int n) { - if (!PyTuple_CheckExact(ob)) { - PyErr_SetString(PyExc_SystemError, - "PyArg_UnpackTuple() argument list is not a tuple"); - return 0; - } - if (n == PyTuple_GET_SIZE(ob)) - return 1; - PyErr_Format( - PyExc_TypeError, - "expected %d arguments, got %zd", n, PyTuple_GET_SIZE(ob)); - return 0; + if (!PyTuple_CheckExact(ob)) { + PyErr_SetString(PyExc_SystemError, + "PyArg_UnpackTuple() argument list is not a tuple"); + return 0; + } + if (n == PyTuple_GET_SIZE(ob)) + return 1; + PyErr_Format( + PyExc_TypeError, + "expected %d arguments, got %zd", n, PyTuple_GET_SIZE(ob)); + return 0; } /* Generic wrappers for overloadable 'operators' such as __getitem__ */ /* There's a wrapper *function* for each distinct function typedef used - for type object slots (e.g. binaryfunc, ternaryfunc, etc.). There's a + for type object slots (e.g. binaryfunc, ternaryfunc, etc.). There's a wrapper *table* for each distinct operation (e.g. __len__, __add__). Most tables have only one entry; the tables for binary operators have two entries, one regular and one with reversed arguments. */ @@ -3991,253 +3991,253 @@ static PyObject * wrap_lenfunc(PyObject *self, PyObject *args, void *wrapped) { - lenfunc func = (lenfunc)wrapped; - Py_ssize_t res; + lenfunc func = (lenfunc)wrapped; + Py_ssize_t res; - if (!check_num_args(args, 0)) - return NULL; - res = (*func)(self); - if (res == -1 && PyErr_Occurred()) - return NULL; - return PyLong_FromLong((long)res); + if (!check_num_args(args, 0)) + return NULL; + res = (*func)(self); + if (res == -1 && PyErr_Occurred()) + return NULL; + return PyLong_FromLong((long)res); } static PyObject * wrap_inquirypred(PyObject *self, PyObject *args, void *wrapped) { - inquiry func = (inquiry)wrapped; - int res; + inquiry func = (inquiry)wrapped; + int res; - if (!check_num_args(args, 0)) - return NULL; - res = (*func)(self); - if (res == -1 && PyErr_Occurred()) - return NULL; - return PyBool_FromLong((long)res); + if (!check_num_args(args, 0)) + return NULL; + res = (*func)(self); + if (res == -1 && PyErr_Occurred()) + return NULL; + return PyBool_FromLong((long)res); } static PyObject * wrap_binaryfunc(PyObject *self, PyObject *args, void *wrapped) { - binaryfunc func = (binaryfunc)wrapped; - PyObject *other; + binaryfunc func = (binaryfunc)wrapped; + PyObject *other; - if (!check_num_args(args, 1)) - return NULL; - other = PyTuple_GET_ITEM(args, 0); - return (*func)(self, other); + if (!check_num_args(args, 1)) + return NULL; + other = PyTuple_GET_ITEM(args, 0); + return (*func)(self, other); } static PyObject * wrap_binaryfunc_l(PyObject *self, PyObject *args, void *wrapped) { - binaryfunc func = (binaryfunc)wrapped; - PyObject *other; + binaryfunc func = (binaryfunc)wrapped; + PyObject *other; - if (!check_num_args(args, 1)) - return NULL; - other = PyTuple_GET_ITEM(args, 0); - return (*func)(self, other); + if (!check_num_args(args, 1)) + return NULL; + other = PyTuple_GET_ITEM(args, 0); + return (*func)(self, other); } static PyObject * wrap_binaryfunc_r(PyObject *self, PyObject *args, void *wrapped) { - binaryfunc func = (binaryfunc)wrapped; - PyObject *other; + binaryfunc func = (binaryfunc)wrapped; + PyObject *other; - if (!check_num_args(args, 1)) - return NULL; - other = PyTuple_GET_ITEM(args, 0); - if (!PyType_IsSubtype(Py_TYPE(other), Py_TYPE(self))) { - Py_INCREF(Py_NotImplemented); - return Py_NotImplemented; - } - return (*func)(other, self); + if (!check_num_args(args, 1)) + return NULL; + other = PyTuple_GET_ITEM(args, 0); + if (!PyType_IsSubtype(Py_TYPE(other), Py_TYPE(self))) { + Py_INCREF(Py_NotImplemented); + return Py_NotImplemented; + } + return (*func)(other, self); } static PyObject * wrap_ternaryfunc(PyObject *self, PyObject *args, void *wrapped) { - ternaryfunc func = (ternaryfunc)wrapped; - PyObject *other; - PyObject *third = Py_None; - - /* Note: This wrapper only works for __pow__() */ - - if (!PyArg_UnpackTuple(args, "", 1, 2, &other, &third)) - return NULL; - return (*func)(self, other, third); + ternaryfunc func = (ternaryfunc)wrapped; + PyObject *other; + PyObject *third = Py_None; + + /* Note: This wrapper only works for __pow__() */ + + if (!PyArg_UnpackTuple(args, "", 1, 2, &other, &third)) + return NULL; + return (*func)(self, other, third); } static PyObject * wrap_ternaryfunc_r(PyObject *self, PyObject *args, void *wrapped) { - ternaryfunc func = (ternaryfunc)wrapped; - PyObject *other; - PyObject *third = Py_None; - - /* Note: This wrapper only works for __pow__() */ - - if (!PyArg_UnpackTuple(args, "", 1, 2, &other, &third)) - return NULL; - return (*func)(other, self, third); + ternaryfunc func = (ternaryfunc)wrapped; + PyObject *other; + PyObject *third = Py_None; + + /* Note: This wrapper only works for __pow__() */ + + if (!PyArg_UnpackTuple(args, "", 1, 2, &other, &third)) + return NULL; + return (*func)(other, self, third); } static PyObject * wrap_unaryfunc(PyObject *self, PyObject *args, void *wrapped) { - unaryfunc func = (unaryfunc)wrapped; + unaryfunc func = (unaryfunc)wrapped; - if (!check_num_args(args, 0)) - return NULL; - return (*func)(self); + if (!check_num_args(args, 0)) + return NULL; + return (*func)(self); } static PyObject * wrap_indexargfunc(PyObject *self, PyObject *args, void *wrapped) { - ssizeargfunc func = (ssizeargfunc)wrapped; - PyObject* o; - Py_ssize_t i; - - if (!PyArg_UnpackTuple(args, "", 1, 1, &o)) - return NULL; - i = PyNumber_AsSsize_t(o, PyExc_OverflowError); - if (i == -1 && PyErr_Occurred()) - return NULL; - return (*func)(self, i); + ssizeargfunc func = (ssizeargfunc)wrapped; + PyObject* o; + Py_ssize_t i; + + if (!PyArg_UnpackTuple(args, "", 1, 1, &o)) + return NULL; + i = PyNumber_AsSsize_t(o, PyExc_OverflowError); + if (i == -1 && PyErr_Occurred()) + return NULL; + return (*func)(self, i); } static Py_ssize_t getindex(PyObject *self, PyObject *arg) { - Py_ssize_t i; + Py_ssize_t i; - i = PyNumber_AsSsize_t(arg, PyExc_OverflowError); - if (i == -1 && PyErr_Occurred()) - return -1; - if (i < 0) { - PySequenceMethods *sq = Py_TYPE(self)->tp_as_sequence; - if (sq && sq->sq_length) { - Py_ssize_t n = (*sq->sq_length)(self); - if (n < 0) - return -1; - i += n; - } - } - return i; + i = PyNumber_AsSsize_t(arg, PyExc_OverflowError); + if (i == -1 && PyErr_Occurred()) + return -1; + if (i < 0) { + PySequenceMethods *sq = Py_TYPE(self)->tp_as_sequence; + if (sq && sq->sq_length) { + Py_ssize_t n = (*sq->sq_length)(self); + if (n < 0) + return -1; + i += n; + } + } + return i; } static PyObject * wrap_sq_item(PyObject *self, PyObject *args, void *wrapped) { - ssizeargfunc func = (ssizeargfunc)wrapped; - PyObject *arg; - Py_ssize_t i; - - if (PyTuple_GET_SIZE(args) == 1) { - arg = PyTuple_GET_ITEM(args, 0); - i = getindex(self, arg); - if (i == -1 && PyErr_Occurred()) - return NULL; - return (*func)(self, i); - } - check_num_args(args, 1); - assert(PyErr_Occurred()); - return NULL; + ssizeargfunc func = (ssizeargfunc)wrapped; + PyObject *arg; + Py_ssize_t i; + + if (PyTuple_GET_SIZE(args) == 1) { + arg = PyTuple_GET_ITEM(args, 0); + i = getindex(self, arg); + if (i == -1 && PyErr_Occurred()) + return NULL; + return (*func)(self, i); + } + check_num_args(args, 1); + assert(PyErr_Occurred()); + return NULL; } static PyObject * wrap_sq_setitem(PyObject *self, PyObject *args, void *wrapped) { - ssizeobjargproc func = (ssizeobjargproc)wrapped; - Py_ssize_t i; - int res; - PyObject *arg, *value; - - if (!PyArg_UnpackTuple(args, "", 2, 2, &arg, &value)) - return NULL; - i = getindex(self, arg); - if (i == -1 && PyErr_Occurred()) - return NULL; - res = (*func)(self, i, value); - if (res == -1 && PyErr_Occurred()) - return NULL; - Py_INCREF(Py_None); - return Py_None; + ssizeobjargproc func = (ssizeobjargproc)wrapped; + Py_ssize_t i; + int res; + PyObject *arg, *value; + + if (!PyArg_UnpackTuple(args, "", 2, 2, &arg, &value)) + return NULL; + i = getindex(self, arg); + if (i == -1 && PyErr_Occurred()) + return NULL; + res = (*func)(self, i, value); + if (res == -1 && PyErr_Occurred()) + return NULL; + Py_INCREF(Py_None); + return Py_None; } static PyObject * wrap_sq_delitem(PyObject *self, PyObject *args, void *wrapped) { - ssizeobjargproc func = (ssizeobjargproc)wrapped; - Py_ssize_t i; - int res; - PyObject *arg; - - if (!check_num_args(args, 1)) - return NULL; - arg = PyTuple_GET_ITEM(args, 0); - i = getindex(self, arg); - if (i == -1 && PyErr_Occurred()) - return NULL; - res = (*func)(self, i, NULL); - if (res == -1 && PyErr_Occurred()) - return NULL; - Py_INCREF(Py_None); - return Py_None; + ssizeobjargproc func = (ssizeobjargproc)wrapped; + Py_ssize_t i; + int res; + PyObject *arg; + + if (!check_num_args(args, 1)) + return NULL; + arg = PyTuple_GET_ITEM(args, 0); + i = getindex(self, arg); + if (i == -1 && PyErr_Occurred()) + return NULL; + res = (*func)(self, i, NULL); + if (res == -1 && PyErr_Occurred()) + return NULL; + Py_INCREF(Py_None); + return Py_None; } /* XXX objobjproc is a misnomer; should be objargpred */ static PyObject * wrap_objobjproc(PyObject *self, PyObject *args, void *wrapped) { - objobjproc func = (objobjproc)wrapped; - int res; - PyObject *value; - - if (!check_num_args(args, 1)) - return NULL; - value = PyTuple_GET_ITEM(args, 0); - res = (*func)(self, value); - if (res == -1 && PyErr_Occurred()) - return NULL; - else - return PyBool_FromLong(res); + objobjproc func = (objobjproc)wrapped; + int res; + PyObject *value; + + if (!check_num_args(args, 1)) + return NULL; + value = PyTuple_GET_ITEM(args, 0); + res = (*func)(self, value); + if (res == -1 && PyErr_Occurred()) + return NULL; + else + return PyBool_FromLong(res); } static PyObject * wrap_objobjargproc(PyObject *self, PyObject *args, void *wrapped) { - objobjargproc func = (objobjargproc)wrapped; - int res; - PyObject *key, *value; - - if (!PyArg_UnpackTuple(args, "", 2, 2, &key, &value)) - return NULL; - res = (*func)(self, key, value); - if (res == -1 && PyErr_Occurred()) - return NULL; - Py_INCREF(Py_None); - return Py_None; + objobjargproc func = (objobjargproc)wrapped; + int res; + PyObject *key, *value; + + if (!PyArg_UnpackTuple(args, "", 2, 2, &key, &value)) + return NULL; + res = (*func)(self, key, value); + if (res == -1 && PyErr_Occurred()) + return NULL; + Py_INCREF(Py_None); + return Py_None; } static PyObject * wrap_delitem(PyObject *self, PyObject *args, void *wrapped) { - objobjargproc func = (objobjargproc)wrapped; - int res; - PyObject *key; - - if (!check_num_args(args, 1)) - return NULL; - key = PyTuple_GET_ITEM(args, 0); - res = (*func)(self, key, NULL); - if (res == -1 && PyErr_Occurred()) - return NULL; - Py_INCREF(Py_None); - return Py_None; + objobjargproc func = (objobjargproc)wrapped; + int res; + PyObject *key; + + if (!check_num_args(args, 1)) + return NULL; + key = PyTuple_GET_ITEM(args, 0); + res = (*func)(self, key, NULL); + if (res == -1 && PyErr_Occurred()) + return NULL; + Py_INCREF(Py_None); + return Py_None; } /* Helper to check for object.__setattr__ or __delattr__ applied to a type. @@ -4245,90 +4245,90 @@ static int hackcheck(PyObject *self, setattrofunc func, char *what) { - PyTypeObject *type = Py_TYPE(self); - while (type && type->tp_flags & Py_TPFLAGS_HEAPTYPE) - type = type->tp_base; - /* If type is NULL now, this is a really weird type. - In the spirit of backwards compatibility (?), just shut up. */ - if (type && type->tp_setattro != func) { - PyErr_Format(PyExc_TypeError, - "can't apply this %s to %s object", - what, - type->tp_name); - return 0; - } - return 1; + PyTypeObject *type = Py_TYPE(self); + while (type && type->tp_flags & Py_TPFLAGS_HEAPTYPE) + type = type->tp_base; + /* If type is NULL now, this is a really weird type. + In the spirit of backwards compatibility (?), just shut up. */ + if (type && type->tp_setattro != func) { + PyErr_Format(PyExc_TypeError, + "can't apply this %s to %s object", + what, + type->tp_name); + return 0; + } + return 1; } static PyObject * wrap_setattr(PyObject *self, PyObject *args, void *wrapped) { - setattrofunc func = (setattrofunc)wrapped; - int res; - PyObject *name, *value; - - if (!PyArg_UnpackTuple(args, "", 2, 2, &name, &value)) - return NULL; - if (!hackcheck(self, func, "__setattr__")) - return NULL; - res = (*func)(self, name, value); - if (res < 0) - return NULL; - Py_INCREF(Py_None); - return Py_None; + setattrofunc func = (setattrofunc)wrapped; + int res; + PyObject *name, *value; + + if (!PyArg_UnpackTuple(args, "", 2, 2, &name, &value)) + return NULL; + if (!hackcheck(self, func, "__setattr__")) + return NULL; + res = (*func)(self, name, value); + if (res < 0) + return NULL; + Py_INCREF(Py_None); + return Py_None; } static PyObject * wrap_delattr(PyObject *self, PyObject *args, void *wrapped) { - setattrofunc func = (setattrofunc)wrapped; - int res; - PyObject *name; - - if (!check_num_args(args, 1)) - return NULL; - name = PyTuple_GET_ITEM(args, 0); - if (!hackcheck(self, func, "__delattr__")) - return NULL; - res = (*func)(self, name, NULL); - if (res < 0) - return NULL; - Py_INCREF(Py_None); - return Py_None; + setattrofunc func = (setattrofunc)wrapped; + int res; + PyObject *name; + + if (!check_num_args(args, 1)) + return NULL; + name = PyTuple_GET_ITEM(args, 0); + if (!hackcheck(self, func, "__delattr__")) + return NULL; + res = (*func)(self, name, NULL); + if (res < 0) + return NULL; + Py_INCREF(Py_None); + return Py_None; } static PyObject * wrap_hashfunc(PyObject *self, PyObject *args, void *wrapped) { - hashfunc func = (hashfunc)wrapped; - long res; + hashfunc func = (hashfunc)wrapped; + long res; - if (!check_num_args(args, 0)) - return NULL; - res = (*func)(self); - if (res == -1 && PyErr_Occurred()) - return NULL; - return PyLong_FromLong(res); + if (!check_num_args(args, 0)) + return NULL; + res = (*func)(self); + if (res == -1 && PyErr_Occurred()) + return NULL; + return PyLong_FromLong(res); } static PyObject * wrap_call(PyObject *self, PyObject *args, void *wrapped, PyObject *kwds) { - ternaryfunc func = (ternaryfunc)wrapped; + ternaryfunc func = (ternaryfunc)wrapped; - return (*func)(self, args, kwds); + return (*func)(self, args, kwds); } static PyObject * wrap_richcmpfunc(PyObject *self, PyObject *args, void *wrapped, int op) { - richcmpfunc func = (richcmpfunc)wrapped; - PyObject *other; + richcmpfunc func = (richcmpfunc)wrapped; + PyObject *other; - if (!check_num_args(args, 1)) - return NULL; - other = PyTuple_GET_ITEM(args, 0); - return (*func)(self, other, op); + if (!check_num_args(args, 1)) + return NULL; + other = PyTuple_GET_ITEM(args, 0); + return (*func)(self, other, op); } #undef RICHCMP_WRAPPER @@ -4336,7 +4336,7 @@ static PyObject * \ richcmp_##NAME(PyObject *self, PyObject *args, void *wrapped) \ { \ - return wrap_richcmpfunc(self, args, wrapped, OP); \ + return wrap_richcmpfunc(self, args, wrapped, OP); \ } RICHCMP_WRAPPER(lt, Py_LT) @@ -4349,164 +4349,164 @@ static PyObject * wrap_next(PyObject *self, PyObject *args, void *wrapped) { - unaryfunc func = (unaryfunc)wrapped; - PyObject *res; + unaryfunc func = (unaryfunc)wrapped; + PyObject *res; - if (!check_num_args(args, 0)) - return NULL; - res = (*func)(self); - if (res == NULL && !PyErr_Occurred()) - PyErr_SetNone(PyExc_StopIteration); - return res; + if (!check_num_args(args, 0)) + return NULL; + res = (*func)(self); + if (res == NULL && !PyErr_Occurred()) + PyErr_SetNone(PyExc_StopIteration); + return res; } static PyObject * wrap_descr_get(PyObject *self, PyObject *args, void *wrapped) { - descrgetfunc func = (descrgetfunc)wrapped; - PyObject *obj; - PyObject *type = NULL; - - if (!PyArg_UnpackTuple(args, "", 1, 2, &obj, &type)) - return NULL; - if (obj == Py_None) - obj = NULL; - if (type == Py_None) - type = NULL; - if (type == NULL &&obj == NULL) { - PyErr_SetString(PyExc_TypeError, - "__get__(None, None) is invalid"); - return NULL; - } - return (*func)(self, obj, type); + descrgetfunc func = (descrgetfunc)wrapped; + PyObject *obj; + PyObject *type = NULL; + + if (!PyArg_UnpackTuple(args, "", 1, 2, &obj, &type)) + return NULL; + if (obj == Py_None) + obj = NULL; + if (type == Py_None) + type = NULL; + if (type == NULL &&obj == NULL) { + PyErr_SetString(PyExc_TypeError, + "__get__(None, None) is invalid"); + return NULL; + } + return (*func)(self, obj, type); } static PyObject * wrap_descr_set(PyObject *self, PyObject *args, void *wrapped) { - descrsetfunc func = (descrsetfunc)wrapped; - PyObject *obj, *value; - int ret; - - if (!PyArg_UnpackTuple(args, "", 2, 2, &obj, &value)) - return NULL; - ret = (*func)(self, obj, value); - if (ret < 0) - return NULL; - Py_INCREF(Py_None); - return Py_None; + descrsetfunc func = (descrsetfunc)wrapped; + PyObject *obj, *value; + int ret; + + if (!PyArg_UnpackTuple(args, "", 2, 2, &obj, &value)) + return NULL; + ret = (*func)(self, obj, value); + if (ret < 0) + return NULL; + Py_INCREF(Py_None); + return Py_None; } static PyObject * wrap_descr_delete(PyObject *self, PyObject *args, void *wrapped) { - descrsetfunc func = (descrsetfunc)wrapped; - PyObject *obj; - int ret; - - if (!check_num_args(args, 1)) - return NULL; - obj = PyTuple_GET_ITEM(args, 0); - ret = (*func)(self, obj, NULL); - if (ret < 0) - return NULL; - Py_INCREF(Py_None); - return Py_None; + descrsetfunc func = (descrsetfunc)wrapped; + PyObject *obj; + int ret; + + if (!check_num_args(args, 1)) + return NULL; + obj = PyTuple_GET_ITEM(args, 0); + ret = (*func)(self, obj, NULL); + if (ret < 0) + return NULL; + Py_INCREF(Py_None); + return Py_None; } static PyObject * wrap_init(PyObject *self, PyObject *args, void *wrapped, PyObject *kwds) { - initproc func = (initproc)wrapped; + initproc func = (initproc)wrapped; - if (func(self, args, kwds) < 0) - return NULL; - Py_INCREF(Py_None); - return Py_None; + if (func(self, args, kwds) < 0) + return NULL; + Py_INCREF(Py_None); + return Py_None; } static PyObject * tp_new_wrapper(PyObject *self, PyObject *args, PyObject *kwds) { - PyTypeObject *type, *subtype, *staticbase; - PyObject *arg0, *res; + PyTypeObject *type, *subtype, *staticbase; + PyObject *arg0, *res; - if (self == NULL || !PyType_Check(self)) - Py_FatalError("__new__() called with non-type 'self'"); - type = (PyTypeObject *)self; - if (!PyTuple_Check(args) || PyTuple_GET_SIZE(args) < 1) { - PyErr_Format(PyExc_TypeError, - "%s.__new__(): not enough arguments", - type->tp_name); - return NULL; - } - arg0 = PyTuple_GET_ITEM(args, 0); - if (!PyType_Check(arg0)) { - PyErr_Format(PyExc_TypeError, - "%s.__new__(X): X is not a type object (%s)", - type->tp_name, - Py_TYPE(arg0)->tp_name); - return NULL; - } - subtype = (PyTypeObject *)arg0; - if (!PyType_IsSubtype(subtype, type)) { - PyErr_Format(PyExc_TypeError, - "%s.__new__(%s): %s is not a subtype of %s", - type->tp_name, - subtype->tp_name, - subtype->tp_name, - type->tp_name); - return NULL; - } - - /* Check that the use doesn't do something silly and unsafe like - object.__new__(dict). To do this, we check that the - most derived base that's not a heap type is this type. */ - staticbase = subtype; - while (staticbase && (staticbase->tp_flags & Py_TPFLAGS_HEAPTYPE)) - staticbase = staticbase->tp_base; - /* If staticbase is NULL now, it is a really weird type. - In the spirit of backwards compatibility (?), just shut up. */ - if (staticbase && staticbase->tp_new != type->tp_new) { - PyErr_Format(PyExc_TypeError, - "%s.__new__(%s) is not safe, use %s.__new__()", - type->tp_name, - subtype->tp_name, - staticbase == NULL ? "?" : staticbase->tp_name); - return NULL; - } - - args = PyTuple_GetSlice(args, 1, PyTuple_GET_SIZE(args)); - if (args == NULL) - return NULL; - res = type->tp_new(subtype, args, kwds); - Py_DECREF(args); - return res; + if (self == NULL || !PyType_Check(self)) + Py_FatalError("__new__() called with non-type 'self'"); + type = (PyTypeObject *)self; + if (!PyTuple_Check(args) || PyTuple_GET_SIZE(args) < 1) { + PyErr_Format(PyExc_TypeError, + "%s.__new__(): not enough arguments", + type->tp_name); + return NULL; + } + arg0 = PyTuple_GET_ITEM(args, 0); + if (!PyType_Check(arg0)) { + PyErr_Format(PyExc_TypeError, + "%s.__new__(X): X is not a type object (%s)", + type->tp_name, + Py_TYPE(arg0)->tp_name); + return NULL; + } + subtype = (PyTypeObject *)arg0; + if (!PyType_IsSubtype(subtype, type)) { + PyErr_Format(PyExc_TypeError, + "%s.__new__(%s): %s is not a subtype of %s", + type->tp_name, + subtype->tp_name, + subtype->tp_name, + type->tp_name); + return NULL; + } + + /* Check that the use doesn't do something silly and unsafe like + object.__new__(dict). To do this, we check that the + most derived base that's not a heap type is this type. */ + staticbase = subtype; + while (staticbase && (staticbase->tp_flags & Py_TPFLAGS_HEAPTYPE)) + staticbase = staticbase->tp_base; + /* If staticbase is NULL now, it is a really weird type. + In the spirit of backwards compatibility (?), just shut up. */ + if (staticbase && staticbase->tp_new != type->tp_new) { + PyErr_Format(PyExc_TypeError, + "%s.__new__(%s) is not safe, use %s.__new__()", + type->tp_name, + subtype->tp_name, + staticbase == NULL ? "?" : staticbase->tp_name); + return NULL; + } + + args = PyTuple_GetSlice(args, 1, PyTuple_GET_SIZE(args)); + if (args == NULL) + return NULL; + res = type->tp_new(subtype, args, kwds); + Py_DECREF(args); + return res; } static struct PyMethodDef tp_new_methoddef[] = { - {"__new__", (PyCFunction)tp_new_wrapper, METH_VARARGS|METH_KEYWORDS, - PyDoc_STR("T.__new__(S, ...) -> " - "a new object with type S, a subtype of T")}, - {0} + {"__new__", (PyCFunction)tp_new_wrapper, METH_VARARGS|METH_KEYWORDS, + PyDoc_STR("T.__new__(S, ...) -> " + "a new object with type S, a subtype of T")}, + {0} }; static int add_tp_new_wrapper(PyTypeObject *type) { - PyObject *func; + PyObject *func; - if (PyDict_GetItemString(type->tp_dict, "__new__") != NULL) - return 0; - func = PyCFunction_New(tp_new_methoddef, (PyObject *)type); - if (func == NULL) - return -1; - if (PyDict_SetItemString(type->tp_dict, "__new__", func)) { - Py_DECREF(func); - return -1; - } - Py_DECREF(func); - return 0; + if (PyDict_GetItemString(type->tp_dict, "__new__") != NULL) + return 0; + func = PyCFunction_New(tp_new_methoddef, (PyObject *)type); + if (func == NULL) + return -1; + if (PyDict_SetItemString(type->tp_dict, "__new__", func)) { + Py_DECREF(func); + return -1; + } + Py_DECREF(func); + return 0; } /* Slot wrappers that call the corresponding __foo__ slot. See comments @@ -4516,16 +4516,16 @@ static PyObject * \ FUNCNAME(PyObject *self) \ { \ - static PyObject *cache_str; \ - return call_method(self, OPSTR, &cache_str, "()"); \ + static PyObject *cache_str; \ + return call_method(self, OPSTR, &cache_str, "()"); \ } #define SLOT1(FUNCNAME, OPSTR, ARG1TYPE, ARGCODES) \ static PyObject * \ FUNCNAME(PyObject *self, ARG1TYPE arg1) \ { \ - static PyObject *cache_str; \ - return call_method(self, OPSTR, &cache_str, "(" ARGCODES ")", arg1); \ + static PyObject *cache_str; \ + return call_method(self, OPSTR, &cache_str, "(" ARGCODES ")", arg1); \ } /* Boolean helper for SLOT1BINFULL(). @@ -4533,33 +4533,33 @@ static int method_is_overloaded(PyObject *left, PyObject *right, char *name) { - PyObject *a, *b; - int ok; + PyObject *a, *b; + int ok; - b = PyObject_GetAttrString((PyObject *)(Py_TYPE(right)), name); - if (b == NULL) { - PyErr_Clear(); - /* If right doesn't have it, it's not overloaded */ - return 0; - } - - a = PyObject_GetAttrString((PyObject *)(Py_TYPE(left)), name); - if (a == NULL) { - PyErr_Clear(); - Py_DECREF(b); - /* If right has it but left doesn't, it's overloaded */ - return 1; - } - - ok = PyObject_RichCompareBool(a, b, Py_NE); - Py_DECREF(a); - Py_DECREF(b); - if (ok < 0) { - PyErr_Clear(); - return 0; - } + b = PyObject_GetAttrString((PyObject *)(Py_TYPE(right)), name); + if (b == NULL) { + PyErr_Clear(); + /* If right doesn't have it, it's not overloaded */ + return 0; + } + + a = PyObject_GetAttrString((PyObject *)(Py_TYPE(left)), name); + if (a == NULL) { + PyErr_Clear(); + Py_DECREF(b); + /* If right has it but left doesn't, it's overloaded */ + return 1; + } + + ok = PyObject_RichCompareBool(a, b, Py_NE); + Py_DECREF(a); + Py_DECREF(b); + if (ok < 0) { + PyErr_Clear(); + return 0; + } - return ok; + return ok; } @@ -4567,68 +4567,68 @@ static PyObject * \ FUNCNAME(PyObject *self, PyObject *other) \ { \ - static PyObject *cache_str, *rcache_str; \ - int do_other = Py_TYPE(self) != Py_TYPE(other) && \ - Py_TYPE(other)->tp_as_number != NULL && \ - Py_TYPE(other)->tp_as_number->SLOTNAME == TESTFUNC; \ - if (Py_TYPE(self)->tp_as_number != NULL && \ - Py_TYPE(self)->tp_as_number->SLOTNAME == TESTFUNC) { \ - PyObject *r; \ - if (do_other && \ - PyType_IsSubtype(Py_TYPE(other), Py_TYPE(self)) && \ - method_is_overloaded(self, other, ROPSTR)) { \ - r = call_maybe( \ - other, ROPSTR, &rcache_str, "(O)", self); \ - if (r != Py_NotImplemented) \ - return r; \ - Py_DECREF(r); \ - do_other = 0; \ - } \ - r = call_maybe( \ - self, OPSTR, &cache_str, "(O)", other); \ - if (r != Py_NotImplemented || \ - Py_TYPE(other) == Py_TYPE(self)) \ - return r; \ - Py_DECREF(r); \ - } \ - if (do_other) { \ - return call_maybe( \ - other, ROPSTR, &rcache_str, "(O)", self); \ - } \ - Py_INCREF(Py_NotImplemented); \ - return Py_NotImplemented; \ + static PyObject *cache_str, *rcache_str; \ + int do_other = Py_TYPE(self) != Py_TYPE(other) && \ + Py_TYPE(other)->tp_as_number != NULL && \ + Py_TYPE(other)->tp_as_number->SLOTNAME == TESTFUNC; \ + if (Py_TYPE(self)->tp_as_number != NULL && \ + Py_TYPE(self)->tp_as_number->SLOTNAME == TESTFUNC) { \ + PyObject *r; \ + if (do_other && \ + PyType_IsSubtype(Py_TYPE(other), Py_TYPE(self)) && \ + method_is_overloaded(self, other, ROPSTR)) { \ + r = call_maybe( \ + other, ROPSTR, &rcache_str, "(O)", self); \ + if (r != Py_NotImplemented) \ + return r; \ + Py_DECREF(r); \ + do_other = 0; \ + } \ + r = call_maybe( \ + self, OPSTR, &cache_str, "(O)", other); \ + if (r != Py_NotImplemented || \ + Py_TYPE(other) == Py_TYPE(self)) \ + return r; \ + Py_DECREF(r); \ + } \ + if (do_other) { \ + return call_maybe( \ + other, ROPSTR, &rcache_str, "(O)", self); \ + } \ + Py_INCREF(Py_NotImplemented); \ + return Py_NotImplemented; \ } #define SLOT1BIN(FUNCNAME, SLOTNAME, OPSTR, ROPSTR) \ - SLOT1BINFULL(FUNCNAME, FUNCNAME, SLOTNAME, OPSTR, ROPSTR) + SLOT1BINFULL(FUNCNAME, FUNCNAME, SLOTNAME, OPSTR, ROPSTR) #define SLOT2(FUNCNAME, OPSTR, ARG1TYPE, ARG2TYPE, ARGCODES) \ static PyObject * \ FUNCNAME(PyObject *self, ARG1TYPE arg1, ARG2TYPE arg2) \ { \ - static PyObject *cache_str; \ - return call_method(self, OPSTR, &cache_str, \ - "(" ARGCODES ")", arg1, arg2); \ + static PyObject *cache_str; \ + return call_method(self, OPSTR, &cache_str, \ + "(" ARGCODES ")", arg1, arg2); \ } static Py_ssize_t slot_sq_length(PyObject *self) { - static PyObject *len_str; - PyObject *res = call_method(self, "__len__", &len_str, "()"); - Py_ssize_t len; - - if (res == NULL) - return -1; - len = PyNumber_AsSsize_t(res, PyExc_OverflowError); - Py_DECREF(res); - if (len < 0) { - if (!PyErr_Occurred()) - PyErr_SetString(PyExc_ValueError, - "__len__() should return >= 0"); - return -1; - } - return len; + static PyObject *len_str; + PyObject *res = call_method(self, "__len__", &len_str, "()"); + Py_ssize_t len; + + if (res == NULL) + return -1; + len = PyNumber_AsSsize_t(res, PyExc_OverflowError); + Py_DECREF(res); + if (len < 0) { + if (!PyErr_Occurred()) + PyErr_SetString(PyExc_ValueError, + "__len__() should return >= 0"); + return -1; + } + return len; } /* Super-optimized version of slot_sq_item. @@ -4636,93 +4636,93 @@ static PyObject * slot_sq_item(PyObject *self, Py_ssize_t i) { - static PyObject *getitem_str; - PyObject *func, *args = NULL, *ival = NULL, *retval = NULL; - descrgetfunc f; - - if (getitem_str == NULL) { - getitem_str = PyUnicode_InternFromString("__getitem__"); - if (getitem_str == NULL) - return NULL; - } - func = _PyType_Lookup(Py_TYPE(self), getitem_str); - if (func != NULL) { - if ((f = Py_TYPE(func)->tp_descr_get) == NULL) - Py_INCREF(func); - else { - func = f(func, self, (PyObject *)(Py_TYPE(self))); - if (func == NULL) { - return NULL; - } - } - ival = PyLong_FromSsize_t(i); - if (ival != NULL) { - args = PyTuple_New(1); - if (args != NULL) { - PyTuple_SET_ITEM(args, 0, ival); - retval = PyObject_Call(func, args, NULL); - Py_XDECREF(args); - Py_XDECREF(func); - return retval; - } - } - } - else { - PyErr_SetObject(PyExc_AttributeError, getitem_str); - } - Py_XDECREF(args); - Py_XDECREF(ival); - Py_XDECREF(func); - return NULL; + static PyObject *getitem_str; + PyObject *func, *args = NULL, *ival = NULL, *retval = NULL; + descrgetfunc f; + + if (getitem_str == NULL) { + getitem_str = PyUnicode_InternFromString("__getitem__"); + if (getitem_str == NULL) + return NULL; + } + func = _PyType_Lookup(Py_TYPE(self), getitem_str); + if (func != NULL) { + if ((f = Py_TYPE(func)->tp_descr_get) == NULL) + Py_INCREF(func); + else { + func = f(func, self, (PyObject *)(Py_TYPE(self))); + if (func == NULL) { + return NULL; + } + } + ival = PyLong_FromSsize_t(i); + if (ival != NULL) { + args = PyTuple_New(1); + if (args != NULL) { + PyTuple_SET_ITEM(args, 0, ival); + retval = PyObject_Call(func, args, NULL); + Py_XDECREF(args); + Py_XDECREF(func); + return retval; + } + } + } + else { + PyErr_SetObject(PyExc_AttributeError, getitem_str); + } + Py_XDECREF(args); + Py_XDECREF(ival); + Py_XDECREF(func); + return NULL; } static int slot_sq_ass_item(PyObject *self, Py_ssize_t index, PyObject *value) { - PyObject *res; - static PyObject *delitem_str, *setitem_str; + PyObject *res; + static PyObject *delitem_str, *setitem_str; - if (value == NULL) - res = call_method(self, "__delitem__", &delitem_str, - "(n)", index); - else - res = call_method(self, "__setitem__", &setitem_str, - "(nO)", index, value); - if (res == NULL) - return -1; - Py_DECREF(res); - return 0; + if (value == NULL) + res = call_method(self, "__delitem__", &delitem_str, + "(n)", index); + else + res = call_method(self, "__setitem__", &setitem_str, + "(nO)", index, value); + if (res == NULL) + return -1; + Py_DECREF(res); + return 0; } static int slot_sq_contains(PyObject *self, PyObject *value) { - PyObject *func, *res, *args; - int result = -1; + PyObject *func, *res, *args; + int result = -1; - static PyObject *contains_str; + static PyObject *contains_str; - func = lookup_maybe(self, "__contains__", &contains_str); - if (func != NULL) { - args = PyTuple_Pack(1, value); - if (args == NULL) - res = NULL; - else { - res = PyObject_Call(func, args, NULL); - Py_DECREF(args); - } - Py_DECREF(func); - if (res != NULL) { - result = PyObject_IsTrue(res); - Py_DECREF(res); - } - } - else if (! PyErr_Occurred()) { - /* Possible results: -1 and 1 */ - result = (int)_PySequence_IterSearch(self, value, - PY_ITERSEARCH_CONTAINS); - } - return result; + func = lookup_maybe(self, "__contains__", &contains_str); + if (func != NULL) { + args = PyTuple_Pack(1, value); + if (args == NULL) + res = NULL; + else { + res = PyObject_Call(func, args, NULL); + Py_DECREF(args); + } + Py_DECREF(func); + if (res != NULL) { + result = PyObject_IsTrue(res); + Py_DECREF(res); + } + } + else if (! PyErr_Occurred()) { + /* Possible results: -1 and 1 */ + result = (int)_PySequence_IterSearch(self, value, + PY_ITERSEARCH_CONTAINS); + } + return result; } #define slot_mp_length slot_sq_length @@ -4732,19 +4732,19 @@ static int slot_mp_ass_subscript(PyObject *self, PyObject *key, PyObject *value) { - PyObject *res; - static PyObject *delitem_str, *setitem_str; + PyObject *res; + static PyObject *delitem_str, *setitem_str; - if (value == NULL) - res = call_method(self, "__delitem__", &delitem_str, - "(O)", key); - else - res = call_method(self, "__setitem__", &setitem_str, - "(OO)", key, value); - if (res == NULL) - return -1; - Py_DECREF(res); - return 0; + if (value == NULL) + res = call_method(self, "__delitem__", &delitem_str, + "(O)", key); + else + res = call_method(self, "__setitem__", &setitem_str, + "(OO)", key, value); + if (res == NULL) + return -1; + Py_DECREF(res); + return 0; } SLOT1BIN(slot_nb_add, nb_add, "__add__", "__radd__") @@ -4756,25 +4756,25 @@ static PyObject *slot_nb_power(PyObject *, PyObject *, PyObject *); SLOT1BINFULL(slot_nb_power_binary, slot_nb_power, - nb_power, "__pow__", "__rpow__") + nb_power, "__pow__", "__rpow__") static PyObject * slot_nb_power(PyObject *self, PyObject *other, PyObject *modulus) { - static PyObject *pow_str; + static PyObject *pow_str; - if (modulus == Py_None) - return slot_nb_power_binary(self, other); - /* Three-arg power doesn't use __rpow__. But ternary_op - can call this when the second argument's type uses - slot_nb_power, so check before calling self.__pow__. */ - if (Py_TYPE(self)->tp_as_number != NULL && - Py_TYPE(self)->tp_as_number->nb_power == slot_nb_power) { - return call_method(self, "__pow__", &pow_str, - "(OO)", other, modulus); - } - Py_INCREF(Py_NotImplemented); - return Py_NotImplemented; + if (modulus == Py_None) + return slot_nb_power_binary(self, other); + /* Three-arg power doesn't use __rpow__. But ternary_op + can call this when the second argument's type uses + slot_nb_power, so check before calling self.__pow__. */ + if (Py_TYPE(self)->tp_as_number != NULL && + Py_TYPE(self)->tp_as_number->nb_power == slot_nb_power) { + return call_method(self, "__pow__", &pow_str, + "(OO)", other, modulus); + } + Py_INCREF(Py_NotImplemented); + return Py_NotImplemented; } SLOT0(slot_nb_negative, "__neg__") @@ -4784,52 +4784,52 @@ static int slot_nb_bool(PyObject *self) { - PyObject *func, *args; - static PyObject *bool_str, *len_str; - int result = -1; - int using_len = 0; - - func = lookup_maybe(self, "__bool__", &bool_str); - if (func == NULL) { - if (PyErr_Occurred()) - return -1; - func = lookup_maybe(self, "__len__", &len_str); - if (func == NULL) - return PyErr_Occurred() ? -1 : 1; - using_len = 1; - } - args = PyTuple_New(0); - if (args != NULL) { - PyObject *temp = PyObject_Call(func, args, NULL); - Py_DECREF(args); - if (temp != NULL) { - if (using_len) { - /* enforced by slot_nb_len */ - result = PyObject_IsTrue(temp); - } - else if (PyBool_Check(temp)) { - result = PyObject_IsTrue(temp); - } - else { - PyErr_Format(PyExc_TypeError, - "__bool__ should return " - "bool, returned %s", - Py_TYPE(temp)->tp_name); - result = -1; - } - Py_DECREF(temp); - } - } - Py_DECREF(func); - return result; + PyObject *func, *args; + static PyObject *bool_str, *len_str; + int result = -1; + int using_len = 0; + + func = lookup_maybe(self, "__bool__", &bool_str); + if (func == NULL) { + if (PyErr_Occurred()) + return -1; + func = lookup_maybe(self, "__len__", &len_str); + if (func == NULL) + return PyErr_Occurred() ? -1 : 1; + using_len = 1; + } + args = PyTuple_New(0); + if (args != NULL) { + PyObject *temp = PyObject_Call(func, args, NULL); + Py_DECREF(args); + if (temp != NULL) { + if (using_len) { + /* enforced by slot_nb_len */ + result = PyObject_IsTrue(temp); + } + else if (PyBool_Check(temp)) { + result = PyObject_IsTrue(temp); + } + else { + PyErr_Format(PyExc_TypeError, + "__bool__ should return " + "bool, returned %s", + Py_TYPE(temp)->tp_name); + result = -1; + } + Py_DECREF(temp); + } + } + Py_DECREF(func); + return result; } static PyObject * slot_nb_index(PyObject *self) { - static PyObject *index_str; - return call_method(self, "__index__", &index_str, "()"); + static PyObject *index_str; + return call_method(self, "__index__", &index_str, "()"); } @@ -4847,11 +4847,11 @@ SLOT1(slot_nb_inplace_multiply, "__imul__", PyObject *, "O") SLOT1(slot_nb_inplace_remainder, "__imod__", PyObject *, "O") /* Can't use SLOT1 here, because nb_inplace_power is ternary */ -static PyObject * -slot_nb_inplace_power(PyObject *self, PyObject * arg1, PyObject *arg2) -{ - static PyObject *cache_str; - return call_method(self, "__ipow__", &cache_str, "(" "O" ")", arg1); +static PyObject * +slot_nb_inplace_power(PyObject *self, PyObject * arg1, PyObject *arg2) +{ + static PyObject *cache_str; + return call_method(self, "__ipow__", &cache_str, "(" "O" ")", arg1); } SLOT1(slot_nb_inplace_lshift, "__ilshift__", PyObject *, "O") SLOT1(slot_nb_inplace_rshift, "__irshift__", PyObject *, "O") @@ -4859,7 +4859,7 @@ SLOT1(slot_nb_inplace_xor, "__ixor__", PyObject *, "O") SLOT1(slot_nb_inplace_or, "__ior__", PyObject *, "O") SLOT1BIN(slot_nb_floor_divide, nb_floor_divide, - "__floordiv__", "__rfloordiv__") + "__floordiv__", "__rfloordiv__") SLOT1BIN(slot_nb_true_divide, nb_true_divide, "__truediv__", "__rtruediv__") SLOT1(slot_nb_inplace_floor_divide, "__ifloordiv__", PyObject *, "O") SLOT1(slot_nb_inplace_true_divide, "__itruediv__", PyObject *, "O") @@ -4867,90 +4867,90 @@ static PyObject * slot_tp_repr(PyObject *self) { - PyObject *func, *res; - static PyObject *repr_str; + PyObject *func, *res; + static PyObject *repr_str; - func = lookup_method(self, "__repr__", &repr_str); - if (func != NULL) { - res = PyEval_CallObject(func, NULL); - Py_DECREF(func); - return res; - } - PyErr_Clear(); - return PyUnicode_FromFormat("<%s object at %p>", - Py_TYPE(self)->tp_name, self); + func = lookup_method(self, "__repr__", &repr_str); + if (func != NULL) { + res = PyEval_CallObject(func, NULL); + Py_DECREF(func); + return res; + } + PyErr_Clear(); + return PyUnicode_FromFormat("<%s object at %p>", + Py_TYPE(self)->tp_name, self); } static PyObject * slot_tp_str(PyObject *self) { - PyObject *func, *res; - static PyObject *str_str; + PyObject *func, *res; + static PyObject *str_str; - func = lookup_method(self, "__str__", &str_str); - if (func != NULL) { - res = PyEval_CallObject(func, NULL); - Py_DECREF(func); - return res; - } - else { - PyObject *ress; - PyErr_Clear(); - res = slot_tp_repr(self); - if (!res) - return NULL; - ress = _PyUnicode_AsDefaultEncodedString(res, NULL); - Py_DECREF(res); - return ress; - } + func = lookup_method(self, "__str__", &str_str); + if (func != NULL) { + res = PyEval_CallObject(func, NULL); + Py_DECREF(func); + return res; + } + else { + PyObject *ress; + PyErr_Clear(); + res = slot_tp_repr(self); + if (!res) + return NULL; + ress = _PyUnicode_AsDefaultEncodedString(res, NULL); + Py_DECREF(res); + return ress; + } } static long slot_tp_hash(PyObject *self) { - PyObject *func, *res; - static PyObject *hash_str; - long h; - - func = lookup_method(self, "__hash__", &hash_str); - - if (func == Py_None) { - Py_DECREF(func); - func = NULL; - } - - if (func == NULL) { - return PyObject_HashNotImplemented(self); - } - - res = PyEval_CallObject(func, NULL); - Py_DECREF(func); - if (res == NULL) - return -1; - if (PyLong_Check(res)) - h = PyLong_Type.tp_hash(res); - else - h = PyLong_AsLong(res); - Py_DECREF(res); - if (h == -1 && !PyErr_Occurred()) - h = -2; - return h; + PyObject *func, *res; + static PyObject *hash_str; + long h; + + func = lookup_method(self, "__hash__", &hash_str); + + if (func == Py_None) { + Py_DECREF(func); + func = NULL; + } + + if (func == NULL) { + return PyObject_HashNotImplemented(self); + } + + res = PyEval_CallObject(func, NULL); + Py_DECREF(func); + if (res == NULL) + return -1; + if (PyLong_Check(res)) + h = PyLong_Type.tp_hash(res); + else + h = PyLong_AsLong(res); + Py_DECREF(res); + if (h == -1 && !PyErr_Occurred()) + h = -2; + return h; } static PyObject * slot_tp_call(PyObject *self, PyObject *args, PyObject *kwds) { - static PyObject *call_str; - PyObject *meth = lookup_method(self, "__call__", &call_str); - PyObject *res; + static PyObject *call_str; + PyObject *meth = lookup_method(self, "__call__", &call_str); + PyObject *res; - if (meth == NULL) - return NULL; + if (meth == NULL) + return NULL; - res = PyObject_Call(meth, args, kwds); + res = PyObject_Call(meth, args, kwds); - Py_DECREF(meth); - return res; + Py_DECREF(meth); + return res; } /* There are two slot dispatch functions for tp_getattro. @@ -4967,100 +4967,100 @@ static PyObject * slot_tp_getattro(PyObject *self, PyObject *name) { - static PyObject *getattribute_str = NULL; - return call_method(self, "__getattribute__", &getattribute_str, - "(O)", name); + static PyObject *getattribute_str = NULL; + return call_method(self, "__getattribute__", &getattribute_str, + "(O)", name); } static PyObject * call_attribute(PyObject *self, PyObject *attr, PyObject *name) { - PyObject *res, *descr = NULL; - descrgetfunc f = Py_TYPE(attr)->tp_descr_get; + PyObject *res, *descr = NULL; + descrgetfunc f = Py_TYPE(attr)->tp_descr_get; - if (f != NULL) { - descr = f(attr, self, (PyObject *)(Py_TYPE(self))); - if (descr == NULL) - return NULL; - else - attr = descr; - } - res = PyObject_CallFunctionObjArgs(attr, name, NULL); - Py_XDECREF(descr); - return res; + if (f != NULL) { + descr = f(attr, self, (PyObject *)(Py_TYPE(self))); + if (descr == NULL) + return NULL; + else + attr = descr; + } + res = PyObject_CallFunctionObjArgs(attr, name, NULL); + Py_XDECREF(descr); + return res; } static PyObject * slot_tp_getattr_hook(PyObject *self, PyObject *name) { - PyTypeObject *tp = Py_TYPE(self); - PyObject *getattr, *getattribute, *res; - static PyObject *getattribute_str = NULL; - static PyObject *getattr_str = NULL; - - if (getattr_str == NULL) { - getattr_str = PyUnicode_InternFromString("__getattr__"); - if (getattr_str == NULL) - return NULL; - } - if (getattribute_str == NULL) { - getattribute_str = - PyUnicode_InternFromString("__getattribute__"); - if (getattribute_str == NULL) - return NULL; - } - /* speed hack: we could use lookup_maybe, but that would resolve the - method fully for each attribute lookup for classes with - __getattr__, even when the attribute is present. So we use - _PyType_Lookup and create the method only when needed, with - call_attribute. */ - getattr = _PyType_Lookup(tp, getattr_str); - if (getattr == NULL) { - /* No __getattr__ hook: use a simpler dispatcher */ - tp->tp_getattro = slot_tp_getattro; - return slot_tp_getattro(self, name); - } - Py_INCREF(getattr); - /* speed hack: we could use lookup_maybe, but that would resolve the - method fully for each attribute lookup for classes with - __getattr__, even when self has the default __getattribute__ - method. So we use _PyType_Lookup and create the method only when - needed, with call_attribute. */ - getattribute = _PyType_Lookup(tp, getattribute_str); - if (getattribute == NULL || - (Py_TYPE(getattribute) == &PyWrapperDescr_Type && - ((PyWrapperDescrObject *)getattribute)->d_wrapped == - (void *)PyObject_GenericGetAttr)) - res = PyObject_GenericGetAttr(self, name); - else { - Py_INCREF(getattribute); - res = call_attribute(self, getattribute, name); - Py_DECREF(getattribute); - } - if (res == NULL && PyErr_ExceptionMatches(PyExc_AttributeError)) { - PyErr_Clear(); - res = call_attribute(self, getattr, name); - } - Py_DECREF(getattr); - return res; + PyTypeObject *tp = Py_TYPE(self); + PyObject *getattr, *getattribute, *res; + static PyObject *getattribute_str = NULL; + static PyObject *getattr_str = NULL; + + if (getattr_str == NULL) { + getattr_str = PyUnicode_InternFromString("__getattr__"); + if (getattr_str == NULL) + return NULL; + } + if (getattribute_str == NULL) { + getattribute_str = + PyUnicode_InternFromString("__getattribute__"); + if (getattribute_str == NULL) + return NULL; + } + /* speed hack: we could use lookup_maybe, but that would resolve the + method fully for each attribute lookup for classes with + __getattr__, even when the attribute is present. So we use + _PyType_Lookup and create the method only when needed, with + call_attribute. */ + getattr = _PyType_Lookup(tp, getattr_str); + if (getattr == NULL) { + /* No __getattr__ hook: use a simpler dispatcher */ + tp->tp_getattro = slot_tp_getattro; + return slot_tp_getattro(self, name); + } + Py_INCREF(getattr); + /* speed hack: we could use lookup_maybe, but that would resolve the + method fully for each attribute lookup for classes with + __getattr__, even when self has the default __getattribute__ + method. So we use _PyType_Lookup and create the method only when + needed, with call_attribute. */ + getattribute = _PyType_Lookup(tp, getattribute_str); + if (getattribute == NULL || + (Py_TYPE(getattribute) == &PyWrapperDescr_Type && + ((PyWrapperDescrObject *)getattribute)->d_wrapped == + (void *)PyObject_GenericGetAttr)) + res = PyObject_GenericGetAttr(self, name); + else { + Py_INCREF(getattribute); + res = call_attribute(self, getattribute, name); + Py_DECREF(getattribute); + } + if (res == NULL && PyErr_ExceptionMatches(PyExc_AttributeError)) { + PyErr_Clear(); + res = call_attribute(self, getattr, name); + } + Py_DECREF(getattr); + return res; } static int slot_tp_setattro(PyObject *self, PyObject *name, PyObject *value) { - PyObject *res; - static PyObject *delattr_str, *setattr_str; + PyObject *res; + static PyObject *delattr_str, *setattr_str; - if (value == NULL) - res = call_method(self, "__delattr__", &delattr_str, - "(O)", name); - else - res = call_method(self, "__setattr__", &setattr_str, - "(OO)", name, value); - if (res == NULL) - return -1; - Py_DECREF(res); - return 0; + if (value == NULL) + res = call_method(self, "__delattr__", &delattr_str, + "(O)", name); + else + res = call_method(self, "__setattr__", &setattr_str, + "(OO)", name, value); + if (res == NULL) + return -1; + Py_DECREF(res); + return 0; } static char *name_op[] = { @@ -5075,244 +5075,244 @@ static PyObject * half_richcompare(PyObject *self, PyObject *other, int op) { - PyObject *func, *args, *res; - static PyObject *op_str[6]; + PyObject *func, *args, *res; + static PyObject *op_str[6]; - func = lookup_method(self, name_op[op], &op_str[op]); - if (func == NULL) { - PyErr_Clear(); - Py_INCREF(Py_NotImplemented); - return Py_NotImplemented; - } - args = PyTuple_Pack(1, other); - if (args == NULL) - res = NULL; - else { - res = PyObject_Call(func, args, NULL); - Py_DECREF(args); - } - Py_DECREF(func); - return res; + func = lookup_method(self, name_op[op], &op_str[op]); + if (func == NULL) { + PyErr_Clear(); + Py_INCREF(Py_NotImplemented); + return Py_NotImplemented; + } + args = PyTuple_Pack(1, other); + if (args == NULL) + res = NULL; + else { + res = PyObject_Call(func, args, NULL); + Py_DECREF(args); + } + Py_DECREF(func); + return res; } static PyObject * slot_tp_richcompare(PyObject *self, PyObject *other, int op) { - PyObject *res; + PyObject *res; - if (Py_TYPE(self)->tp_richcompare == slot_tp_richcompare) { - res = half_richcompare(self, other, op); - if (res != Py_NotImplemented) - return res; - Py_DECREF(res); - } - if (Py_TYPE(other)->tp_richcompare == slot_tp_richcompare) { - res = half_richcompare(other, self, _Py_SwappedOp[op]); - if (res != Py_NotImplemented) { - return res; - } - Py_DECREF(res); - } - Py_INCREF(Py_NotImplemented); - return Py_NotImplemented; + if (Py_TYPE(self)->tp_richcompare == slot_tp_richcompare) { + res = half_richcompare(self, other, op); + if (res != Py_NotImplemented) + return res; + Py_DECREF(res); + } + if (Py_TYPE(other)->tp_richcompare == slot_tp_richcompare) { + res = half_richcompare(other, self, _Py_SwappedOp[op]); + if (res != Py_NotImplemented) { + return res; + } + Py_DECREF(res); + } + Py_INCREF(Py_NotImplemented); + return Py_NotImplemented; } static PyObject * slot_tp_iter(PyObject *self) { - PyObject *func, *res; - static PyObject *iter_str, *getitem_str; + PyObject *func, *res; + static PyObject *iter_str, *getitem_str; - func = lookup_method(self, "__iter__", &iter_str); - if (func != NULL) { - PyObject *args; - args = res = PyTuple_New(0); - if (args != NULL) { - res = PyObject_Call(func, args, NULL); - Py_DECREF(args); - } - Py_DECREF(func); - return res; - } - PyErr_Clear(); - func = lookup_method(self, "__getitem__", &getitem_str); - if (func == NULL) { - PyErr_Format(PyExc_TypeError, - "'%.200s' object is not iterable", - Py_TYPE(self)->tp_name); - return NULL; - } - Py_DECREF(func); - return PySeqIter_New(self); + func = lookup_method(self, "__iter__", &iter_str); + if (func != NULL) { + PyObject *args; + args = res = PyTuple_New(0); + if (args != NULL) { + res = PyObject_Call(func, args, NULL); + Py_DECREF(args); + } + Py_DECREF(func); + return res; + } + PyErr_Clear(); + func = lookup_method(self, "__getitem__", &getitem_str); + if (func == NULL) { + PyErr_Format(PyExc_TypeError, + "'%.200s' object is not iterable", + Py_TYPE(self)->tp_name); + return NULL; + } + Py_DECREF(func); + return PySeqIter_New(self); } static PyObject * slot_tp_iternext(PyObject *self) { - static PyObject *next_str; - return call_method(self, "__next__", &next_str, "()"); + static PyObject *next_str; + return call_method(self, "__next__", &next_str, "()"); } static PyObject * slot_tp_descr_get(PyObject *self, PyObject *obj, PyObject *type) { - PyTypeObject *tp = Py_TYPE(self); - PyObject *get; - static PyObject *get_str = NULL; - - if (get_str == NULL) { - get_str = PyUnicode_InternFromString("__get__"); - if (get_str == NULL) - return NULL; - } - get = _PyType_Lookup(tp, get_str); - if (get == NULL) { - /* Avoid further slowdowns */ - if (tp->tp_descr_get == slot_tp_descr_get) - tp->tp_descr_get = NULL; - Py_INCREF(self); - return self; - } - if (obj == NULL) - obj = Py_None; - if (type == NULL) - type = Py_None; - return PyObject_CallFunctionObjArgs(get, self, obj, type, NULL); + PyTypeObject *tp = Py_TYPE(self); + PyObject *get; + static PyObject *get_str = NULL; + + if (get_str == NULL) { + get_str = PyUnicode_InternFromString("__get__"); + if (get_str == NULL) + return NULL; + } + get = _PyType_Lookup(tp, get_str); + if (get == NULL) { + /* Avoid further slowdowns */ + if (tp->tp_descr_get == slot_tp_descr_get) + tp->tp_descr_get = NULL; + Py_INCREF(self); + return self; + } + if (obj == NULL) + obj = Py_None; + if (type == NULL) + type = Py_None; + return PyObject_CallFunctionObjArgs(get, self, obj, type, NULL); } static int slot_tp_descr_set(PyObject *self, PyObject *target, PyObject *value) { - PyObject *res; - static PyObject *del_str, *set_str; + PyObject *res; + static PyObject *del_str, *set_str; - if (value == NULL) - res = call_method(self, "__delete__", &del_str, - "(O)", target); - else - res = call_method(self, "__set__", &set_str, - "(OO)", target, value); - if (res == NULL) - return -1; - Py_DECREF(res); - return 0; + if (value == NULL) + res = call_method(self, "__delete__", &del_str, + "(O)", target); + else + res = call_method(self, "__set__", &set_str, + "(OO)", target, value); + if (res == NULL) + return -1; + Py_DECREF(res); + return 0; } static int slot_tp_init(PyObject *self, PyObject *args, PyObject *kwds) { - static PyObject *init_str; - PyObject *meth = lookup_method(self, "__init__", &init_str); - PyObject *res; - - if (meth == NULL) - return -1; - res = PyObject_Call(meth, args, kwds); - Py_DECREF(meth); - if (res == NULL) - return -1; - if (res != Py_None) { - PyErr_Format(PyExc_TypeError, - "__init__() should return None, not '%.200s'", - Py_TYPE(res)->tp_name); - Py_DECREF(res); - return -1; - } - Py_DECREF(res); - return 0; + static PyObject *init_str; + PyObject *meth = lookup_method(self, "__init__", &init_str); + PyObject *res; + + if (meth == NULL) + return -1; + res = PyObject_Call(meth, args, kwds); + Py_DECREF(meth); + if (res == NULL) + return -1; + if (res != Py_None) { + PyErr_Format(PyExc_TypeError, + "__init__() should return None, not '%.200s'", + Py_TYPE(res)->tp_name); + Py_DECREF(res); + return -1; + } + Py_DECREF(res); + return 0; } static PyObject * slot_tp_new(PyTypeObject *type, PyObject *args, PyObject *kwds) { - static PyObject *new_str; - PyObject *func; - PyObject *newargs, *x; - Py_ssize_t i, n; - - if (new_str == NULL) { - new_str = PyUnicode_InternFromString("__new__"); - if (new_str == NULL) - return NULL; - } - func = PyObject_GetAttr((PyObject *)type, new_str); - if (func == NULL) - return NULL; - assert(PyTuple_Check(args)); - n = PyTuple_GET_SIZE(args); - newargs = PyTuple_New(n+1); - if (newargs == NULL) - return NULL; - Py_INCREF(type); - PyTuple_SET_ITEM(newargs, 0, (PyObject *)type); - for (i = 0; i < n; i++) { - x = PyTuple_GET_ITEM(args, i); - Py_INCREF(x); - PyTuple_SET_ITEM(newargs, i+1, x); - } - x = PyObject_Call(func, newargs, kwds); - Py_DECREF(newargs); - Py_DECREF(func); - return x; + static PyObject *new_str; + PyObject *func; + PyObject *newargs, *x; + Py_ssize_t i, n; + + if (new_str == NULL) { + new_str = PyUnicode_InternFromString("__new__"); + if (new_str == NULL) + return NULL; + } + func = PyObject_GetAttr((PyObject *)type, new_str); + if (func == NULL) + return NULL; + assert(PyTuple_Check(args)); + n = PyTuple_GET_SIZE(args); + newargs = PyTuple_New(n+1); + if (newargs == NULL) + return NULL; + Py_INCREF(type); + PyTuple_SET_ITEM(newargs, 0, (PyObject *)type); + for (i = 0; i < n; i++) { + x = PyTuple_GET_ITEM(args, i); + Py_INCREF(x); + PyTuple_SET_ITEM(newargs, i+1, x); + } + x = PyObject_Call(func, newargs, kwds); + Py_DECREF(newargs); + Py_DECREF(func); + return x; } static void slot_tp_del(PyObject *self) { - static PyObject *del_str = NULL; - PyObject *del, *res; - PyObject *error_type, *error_value, *error_traceback; - - /* Temporarily resurrect the object. */ - assert(self->ob_refcnt == 0); - self->ob_refcnt = 1; - - /* Save the current exception, if any. */ - PyErr_Fetch(&error_type, &error_value, &error_traceback); - - /* Execute __del__ method, if any. */ - del = lookup_maybe(self, "__del__", &del_str); - if (del != NULL) { - res = PyEval_CallObject(del, NULL); - if (res == NULL) - PyErr_WriteUnraisable(del); - else - Py_DECREF(res); - Py_DECREF(del); - } - - /* Restore the saved exception. */ - PyErr_Restore(error_type, error_value, error_traceback); - - /* Undo the temporary resurrection; can't use DECREF here, it would - * cause a recursive call. - */ - assert(self->ob_refcnt > 0); - if (--self->ob_refcnt == 0) - return; /* this is the normal path out */ - - /* __del__ resurrected it! Make it look like the original Py_DECREF - * never happened. - */ - { - Py_ssize_t refcnt = self->ob_refcnt; - _Py_NewReference(self); - self->ob_refcnt = refcnt; - } - assert(!PyType_IS_GC(Py_TYPE(self)) || - _Py_AS_GC(self)->gc.gc_refs != _PyGC_REFS_UNTRACKED); - /* If Py_REF_DEBUG, _Py_NewReference bumped _Py_RefTotal, so - * we need to undo that. */ - _Py_DEC_REFTOTAL; - /* If Py_TRACE_REFS, _Py_NewReference re-added self to the object - * chain, so no more to do there. - * If COUNT_ALLOCS, the original decref bumped tp_frees, and - * _Py_NewReference bumped tp_allocs: both of those need to be - * undone. - */ + static PyObject *del_str = NULL; + PyObject *del, *res; + PyObject *error_type, *error_value, *error_traceback; + + /* Temporarily resurrect the object. */ + assert(self->ob_refcnt == 0); + self->ob_refcnt = 1; + + /* Save the current exception, if any. */ + PyErr_Fetch(&error_type, &error_value, &error_traceback); + + /* Execute __del__ method, if any. */ + del = lookup_maybe(self, "__del__", &del_str); + if (del != NULL) { + res = PyEval_CallObject(del, NULL); + if (res == NULL) + PyErr_WriteUnraisable(del); + else + Py_DECREF(res); + Py_DECREF(del); + } + + /* Restore the saved exception. */ + PyErr_Restore(error_type, error_value, error_traceback); + + /* Undo the temporary resurrection; can't use DECREF here, it would + * cause a recursive call. + */ + assert(self->ob_refcnt > 0); + if (--self->ob_refcnt == 0) + return; /* this is the normal path out */ + + /* __del__ resurrected it! Make it look like the original Py_DECREF + * never happened. + */ + { + Py_ssize_t refcnt = self->ob_refcnt; + _Py_NewReference(self); + self->ob_refcnt = refcnt; + } + assert(!PyType_IS_GC(Py_TYPE(self)) || + _Py_AS_GC(self)->gc.gc_refs != _PyGC_REFS_UNTRACKED); + /* If Py_REF_DEBUG, _Py_NewReference bumped _Py_RefTotal, so + * we need to undo that. */ + _Py_DEC_REFTOTAL; + /* If Py_TRACE_REFS, _Py_NewReference re-added self to the object + * chain, so no more to do there. + * If COUNT_ALLOCS, the original decref bumped tp_frees, and + * _Py_NewReference bumped tp_allocs: both of those need to be + * undone. + */ #ifdef COUNT_ALLOCS - --Py_TYPE(self)->tp_frees; - --Py_TYPE(self)->tp_allocs; + --Py_TYPE(self)->tp_frees; + --Py_TYPE(self)->tp_allocs; #endif } @@ -5341,236 +5341,236 @@ #undef RBINSLOT #define TPSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \ - {NAME, offsetof(PyTypeObject, SLOT), (void *)(FUNCTION), WRAPPER, \ - PyDoc_STR(DOC)} + {NAME, offsetof(PyTypeObject, SLOT), (void *)(FUNCTION), WRAPPER, \ + PyDoc_STR(DOC)} #define FLSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC, FLAGS) \ - {NAME, offsetof(PyTypeObject, SLOT), (void *)(FUNCTION), WRAPPER, \ - PyDoc_STR(DOC), FLAGS} + {NAME, offsetof(PyTypeObject, SLOT), (void *)(FUNCTION), WRAPPER, \ + PyDoc_STR(DOC), FLAGS} #define ETSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \ - {NAME, offsetof(PyHeapTypeObject, SLOT), (void *)(FUNCTION), WRAPPER, \ - PyDoc_STR(DOC)} + {NAME, offsetof(PyHeapTypeObject, SLOT), (void *)(FUNCTION), WRAPPER, \ + PyDoc_STR(DOC)} #define SQSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \ - ETSLOT(NAME, as_sequence.SLOT, FUNCTION, WRAPPER, DOC) + ETSLOT(NAME, as_sequence.SLOT, FUNCTION, WRAPPER, DOC) #define MPSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \ - ETSLOT(NAME, as_mapping.SLOT, FUNCTION, WRAPPER, DOC) + ETSLOT(NAME, as_mapping.SLOT, FUNCTION, WRAPPER, DOC) #define NBSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \ - ETSLOT(NAME, as_number.SLOT, FUNCTION, WRAPPER, DOC) + ETSLOT(NAME, as_number.SLOT, FUNCTION, WRAPPER, DOC) #define UNSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \ - ETSLOT(NAME, as_number.SLOT, FUNCTION, WRAPPER, \ - "x." NAME "() <==> " DOC) + ETSLOT(NAME, as_number.SLOT, FUNCTION, WRAPPER, \ + "x." NAME "() <==> " DOC) #define IBSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \ - ETSLOT(NAME, as_number.SLOT, FUNCTION, WRAPPER, \ - "x." NAME "(y) <==> x" DOC "y") + ETSLOT(NAME, as_number.SLOT, FUNCTION, WRAPPER, \ + "x." NAME "(y) <==> x" DOC "y") #define BINSLOT(NAME, SLOT, FUNCTION, DOC) \ - ETSLOT(NAME, as_number.SLOT, FUNCTION, wrap_binaryfunc_l, \ - "x." NAME "(y) <==> x" DOC "y") + ETSLOT(NAME, as_number.SLOT, FUNCTION, wrap_binaryfunc_l, \ + "x." NAME "(y) <==> x" DOC "y") #define RBINSLOT(NAME, SLOT, FUNCTION, DOC) \ - ETSLOT(NAME, as_number.SLOT, FUNCTION, wrap_binaryfunc_r, \ - "x." NAME "(y) <==> y" DOC "x") + ETSLOT(NAME, as_number.SLOT, FUNCTION, wrap_binaryfunc_r, \ + "x." NAME "(y) <==> y" DOC "x") #define BINSLOTNOTINFIX(NAME, SLOT, FUNCTION, DOC) \ - ETSLOT(NAME, as_number.SLOT, FUNCTION, wrap_binaryfunc_l, \ - "x." NAME "(y) <==> " DOC) + ETSLOT(NAME, as_number.SLOT, FUNCTION, wrap_binaryfunc_l, \ + "x." NAME "(y) <==> " DOC) #define RBINSLOTNOTINFIX(NAME, SLOT, FUNCTION, DOC) \ - ETSLOT(NAME, as_number.SLOT, FUNCTION, wrap_binaryfunc_r, \ - "x." NAME "(y) <==> " DOC) + ETSLOT(NAME, as_number.SLOT, FUNCTION, wrap_binaryfunc_r, \ + "x." NAME "(y) <==> " DOC) static slotdef slotdefs[] = { - SQSLOT("__len__", sq_length, slot_sq_length, wrap_lenfunc, - "x.__len__() <==> len(x)"), - /* Heap types defining __add__/__mul__ have sq_concat/sq_repeat == NULL. - The logic in abstract.c always falls back to nb_add/nb_multiply in - this case. Defining both the nb_* and the sq_* slots to call the - user-defined methods has unexpected side-effects, as shown by - test_descr.notimplemented() */ - SQSLOT("__add__", sq_concat, NULL, wrap_binaryfunc, - "x.__add__(y) <==> x+y"), - SQSLOT("__mul__", sq_repeat, NULL, wrap_indexargfunc, - "x.__mul__(n) <==> x*n"), - SQSLOT("__rmul__", sq_repeat, NULL, wrap_indexargfunc, - "x.__rmul__(n) <==> n*x"), - SQSLOT("__getitem__", sq_item, slot_sq_item, wrap_sq_item, - "x.__getitem__(y) <==> x[y]"), - SQSLOT("__setitem__", sq_ass_item, slot_sq_ass_item, wrap_sq_setitem, - "x.__setitem__(i, y) <==> x[i]=y"), - SQSLOT("__delitem__", sq_ass_item, slot_sq_ass_item, wrap_sq_delitem, - "x.__delitem__(y) <==> del x[y]"), - SQSLOT("__contains__", sq_contains, slot_sq_contains, wrap_objobjproc, - "x.__contains__(y) <==> y in x"), - SQSLOT("__iadd__", sq_inplace_concat, NULL, - wrap_binaryfunc, "x.__iadd__(y) <==> x+=y"), - SQSLOT("__imul__", sq_inplace_repeat, NULL, - wrap_indexargfunc, "x.__imul__(y) <==> x*=y"), - - MPSLOT("__len__", mp_length, slot_mp_length, wrap_lenfunc, - "x.__len__() <==> len(x)"), - MPSLOT("__getitem__", mp_subscript, slot_mp_subscript, - wrap_binaryfunc, - "x.__getitem__(y) <==> x[y]"), - MPSLOT("__setitem__", mp_ass_subscript, slot_mp_ass_subscript, - wrap_objobjargproc, - "x.__setitem__(i, y) <==> x[i]=y"), - MPSLOT("__delitem__", mp_ass_subscript, slot_mp_ass_subscript, - wrap_delitem, - "x.__delitem__(y) <==> del x[y]"), - - BINSLOT("__add__", nb_add, slot_nb_add, - "+"), - RBINSLOT("__radd__", nb_add, slot_nb_add, - "+"), - BINSLOT("__sub__", nb_subtract, slot_nb_subtract, - "-"), - RBINSLOT("__rsub__", nb_subtract, slot_nb_subtract, - "-"), - BINSLOT("__mul__", nb_multiply, slot_nb_multiply, - "*"), - RBINSLOT("__rmul__", nb_multiply, slot_nb_multiply, - "*"), - BINSLOT("__mod__", nb_remainder, slot_nb_remainder, - "%"), - RBINSLOT("__rmod__", nb_remainder, slot_nb_remainder, - "%"), - BINSLOTNOTINFIX("__divmod__", nb_divmod, slot_nb_divmod, - "divmod(x, y)"), - RBINSLOTNOTINFIX("__rdivmod__", nb_divmod, slot_nb_divmod, - "divmod(y, x)"), - NBSLOT("__pow__", nb_power, slot_nb_power, wrap_ternaryfunc, - "x.__pow__(y[, z]) <==> pow(x, y[, z])"), - NBSLOT("__rpow__", nb_power, slot_nb_power, wrap_ternaryfunc_r, - "y.__rpow__(x[, z]) <==> pow(x, y[, z])"), - UNSLOT("__neg__", nb_negative, slot_nb_negative, wrap_unaryfunc, "-x"), - UNSLOT("__pos__", nb_positive, slot_nb_positive, wrap_unaryfunc, "+x"), - UNSLOT("__abs__", nb_absolute, slot_nb_absolute, wrap_unaryfunc, - "abs(x)"), - UNSLOT("__bool__", nb_bool, slot_nb_bool, wrap_inquirypred, - "x != 0"), - UNSLOT("__invert__", nb_invert, slot_nb_invert, wrap_unaryfunc, "~x"), - BINSLOT("__lshift__", nb_lshift, slot_nb_lshift, "<<"), - RBINSLOT("__rlshift__", nb_lshift, slot_nb_lshift, "<<"), - BINSLOT("__rshift__", nb_rshift, slot_nb_rshift, ">>"), - RBINSLOT("__rrshift__", nb_rshift, slot_nb_rshift, ">>"), - BINSLOT("__and__", nb_and, slot_nb_and, "&"), - RBINSLOT("__rand__", nb_and, slot_nb_and, "&"), - BINSLOT("__xor__", nb_xor, slot_nb_xor, "^"), - RBINSLOT("__rxor__", nb_xor, slot_nb_xor, "^"), - BINSLOT("__or__", nb_or, slot_nb_or, "|"), - RBINSLOT("__ror__", nb_or, slot_nb_or, "|"), - UNSLOT("__int__", nb_int, slot_nb_int, wrap_unaryfunc, - "int(x)"), - UNSLOT("__float__", nb_float, slot_nb_float, wrap_unaryfunc, - "float(x)"), - NBSLOT("__index__", nb_index, slot_nb_index, wrap_unaryfunc, - "x[y:z] <==> x[y.__index__():z.__index__()]"), - IBSLOT("__iadd__", nb_inplace_add, slot_nb_inplace_add, - wrap_binaryfunc, "+"), - IBSLOT("__isub__", nb_inplace_subtract, slot_nb_inplace_subtract, - wrap_binaryfunc, "-"), - IBSLOT("__imul__", nb_inplace_multiply, slot_nb_inplace_multiply, - wrap_binaryfunc, "*"), - IBSLOT("__imod__", nb_inplace_remainder, slot_nb_inplace_remainder, - wrap_binaryfunc, "%"), - IBSLOT("__ipow__", nb_inplace_power, slot_nb_inplace_power, - wrap_binaryfunc, "**"), - IBSLOT("__ilshift__", nb_inplace_lshift, slot_nb_inplace_lshift, - wrap_binaryfunc, "<<"), - IBSLOT("__irshift__", nb_inplace_rshift, slot_nb_inplace_rshift, - wrap_binaryfunc, ">>"), - IBSLOT("__iand__", nb_inplace_and, slot_nb_inplace_and, - wrap_binaryfunc, "&"), - IBSLOT("__ixor__", nb_inplace_xor, slot_nb_inplace_xor, - wrap_binaryfunc, "^"), - IBSLOT("__ior__", nb_inplace_or, slot_nb_inplace_or, - wrap_binaryfunc, "|"), - BINSLOT("__floordiv__", nb_floor_divide, slot_nb_floor_divide, "//"), - RBINSLOT("__rfloordiv__", nb_floor_divide, slot_nb_floor_divide, "//"), - BINSLOT("__truediv__", nb_true_divide, slot_nb_true_divide, "/"), - RBINSLOT("__rtruediv__", nb_true_divide, slot_nb_true_divide, "/"), - IBSLOT("__ifloordiv__", nb_inplace_floor_divide, - slot_nb_inplace_floor_divide, wrap_binaryfunc, "//"), - IBSLOT("__itruediv__", nb_inplace_true_divide, - slot_nb_inplace_true_divide, wrap_binaryfunc, "/"), - - TPSLOT("__str__", tp_str, slot_tp_str, wrap_unaryfunc, - "x.__str__() <==> str(x)"), - TPSLOT("__repr__", tp_repr, slot_tp_repr, wrap_unaryfunc, - "x.__repr__() <==> repr(x)"), - TPSLOT("__hash__", tp_hash, slot_tp_hash, wrap_hashfunc, - "x.__hash__() <==> hash(x)"), - FLSLOT("__call__", tp_call, slot_tp_call, (wrapperfunc)wrap_call, - "x.__call__(...) <==> x(...)", PyWrapperFlag_KEYWORDS), - TPSLOT("__getattribute__", tp_getattro, slot_tp_getattr_hook, - wrap_binaryfunc, "x.__getattribute__('name') <==> x.name"), - TPSLOT("__getattribute__", tp_getattr, NULL, NULL, ""), - TPSLOT("__getattr__", tp_getattro, slot_tp_getattr_hook, NULL, ""), - TPSLOT("__getattr__", tp_getattr, NULL, NULL, ""), - TPSLOT("__setattr__", tp_setattro, slot_tp_setattro, wrap_setattr, - "x.__setattr__('name', value) <==> x.name = value"), - TPSLOT("__setattr__", tp_setattr, NULL, NULL, ""), - TPSLOT("__delattr__", tp_setattro, slot_tp_setattro, wrap_delattr, - "x.__delattr__('name') <==> del x.name"), - TPSLOT("__delattr__", tp_setattr, NULL, NULL, ""), - TPSLOT("__lt__", tp_richcompare, slot_tp_richcompare, richcmp_lt, - "x.__lt__(y) <==> x x<=y"), - TPSLOT("__eq__", tp_richcompare, slot_tp_richcompare, richcmp_eq, - "x.__eq__(y) <==> x==y"), - TPSLOT("__ne__", tp_richcompare, slot_tp_richcompare, richcmp_ne, - "x.__ne__(y) <==> x!=y"), - TPSLOT("__gt__", tp_richcompare, slot_tp_richcompare, richcmp_gt, - "x.__gt__(y) <==> x>y"), - TPSLOT("__ge__", tp_richcompare, slot_tp_richcompare, richcmp_ge, - "x.__ge__(y) <==> x>=y"), - TPSLOT("__iter__", tp_iter, slot_tp_iter, wrap_unaryfunc, - "x.__iter__() <==> iter(x)"), - TPSLOT("__next__", tp_iternext, slot_tp_iternext, wrap_next, - "x.__next__() <==> next(x)"), - TPSLOT("__get__", tp_descr_get, slot_tp_descr_get, wrap_descr_get, - "descr.__get__(obj[, type]) -> value"), - TPSLOT("__set__", tp_descr_set, slot_tp_descr_set, wrap_descr_set, - "descr.__set__(obj, value)"), - TPSLOT("__delete__", tp_descr_set, slot_tp_descr_set, - wrap_descr_delete, "descr.__delete__(obj)"), - FLSLOT("__init__", tp_init, slot_tp_init, (wrapperfunc)wrap_init, - "x.__init__(...) initializes x; " - "see x.__class__.__doc__ for signature", - PyWrapperFlag_KEYWORDS), - TPSLOT("__new__", tp_new, slot_tp_new, NULL, ""), - TPSLOT("__del__", tp_del, slot_tp_del, NULL, ""), - {NULL} + SQSLOT("__len__", sq_length, slot_sq_length, wrap_lenfunc, + "x.__len__() <==> len(x)"), + /* Heap types defining __add__/__mul__ have sq_concat/sq_repeat == NULL. + The logic in abstract.c always falls back to nb_add/nb_multiply in + this case. Defining both the nb_* and the sq_* slots to call the + user-defined methods has unexpected side-effects, as shown by + test_descr.notimplemented() */ + SQSLOT("__add__", sq_concat, NULL, wrap_binaryfunc, + "x.__add__(y) <==> x+y"), + SQSLOT("__mul__", sq_repeat, NULL, wrap_indexargfunc, + "x.__mul__(n) <==> x*n"), + SQSLOT("__rmul__", sq_repeat, NULL, wrap_indexargfunc, + "x.__rmul__(n) <==> n*x"), + SQSLOT("__getitem__", sq_item, slot_sq_item, wrap_sq_item, + "x.__getitem__(y) <==> x[y]"), + SQSLOT("__setitem__", sq_ass_item, slot_sq_ass_item, wrap_sq_setitem, + "x.__setitem__(i, y) <==> x[i]=y"), + SQSLOT("__delitem__", sq_ass_item, slot_sq_ass_item, wrap_sq_delitem, + "x.__delitem__(y) <==> del x[y]"), + SQSLOT("__contains__", sq_contains, slot_sq_contains, wrap_objobjproc, + "x.__contains__(y) <==> y in x"), + SQSLOT("__iadd__", sq_inplace_concat, NULL, + wrap_binaryfunc, "x.__iadd__(y) <==> x+=y"), + SQSLOT("__imul__", sq_inplace_repeat, NULL, + wrap_indexargfunc, "x.__imul__(y) <==> x*=y"), + + MPSLOT("__len__", mp_length, slot_mp_length, wrap_lenfunc, + "x.__len__() <==> len(x)"), + MPSLOT("__getitem__", mp_subscript, slot_mp_subscript, + wrap_binaryfunc, + "x.__getitem__(y) <==> x[y]"), + MPSLOT("__setitem__", mp_ass_subscript, slot_mp_ass_subscript, + wrap_objobjargproc, + "x.__setitem__(i, y) <==> x[i]=y"), + MPSLOT("__delitem__", mp_ass_subscript, slot_mp_ass_subscript, + wrap_delitem, + "x.__delitem__(y) <==> del x[y]"), + + BINSLOT("__add__", nb_add, slot_nb_add, + "+"), + RBINSLOT("__radd__", nb_add, slot_nb_add, + "+"), + BINSLOT("__sub__", nb_subtract, slot_nb_subtract, + "-"), + RBINSLOT("__rsub__", nb_subtract, slot_nb_subtract, + "-"), + BINSLOT("__mul__", nb_multiply, slot_nb_multiply, + "*"), + RBINSLOT("__rmul__", nb_multiply, slot_nb_multiply, + "*"), + BINSLOT("__mod__", nb_remainder, slot_nb_remainder, + "%"), + RBINSLOT("__rmod__", nb_remainder, slot_nb_remainder, + "%"), + BINSLOTNOTINFIX("__divmod__", nb_divmod, slot_nb_divmod, + "divmod(x, y)"), + RBINSLOTNOTINFIX("__rdivmod__", nb_divmod, slot_nb_divmod, + "divmod(y, x)"), + NBSLOT("__pow__", nb_power, slot_nb_power, wrap_ternaryfunc, + "x.__pow__(y[, z]) <==> pow(x, y[, z])"), + NBSLOT("__rpow__", nb_power, slot_nb_power, wrap_ternaryfunc_r, + "y.__rpow__(x[, z]) <==> pow(x, y[, z])"), + UNSLOT("__neg__", nb_negative, slot_nb_negative, wrap_unaryfunc, "-x"), + UNSLOT("__pos__", nb_positive, slot_nb_positive, wrap_unaryfunc, "+x"), + UNSLOT("__abs__", nb_absolute, slot_nb_absolute, wrap_unaryfunc, + "abs(x)"), + UNSLOT("__bool__", nb_bool, slot_nb_bool, wrap_inquirypred, + "x != 0"), + UNSLOT("__invert__", nb_invert, slot_nb_invert, wrap_unaryfunc, "~x"), + BINSLOT("__lshift__", nb_lshift, slot_nb_lshift, "<<"), + RBINSLOT("__rlshift__", nb_lshift, slot_nb_lshift, "<<"), + BINSLOT("__rshift__", nb_rshift, slot_nb_rshift, ">>"), + RBINSLOT("__rrshift__", nb_rshift, slot_nb_rshift, ">>"), + BINSLOT("__and__", nb_and, slot_nb_and, "&"), + RBINSLOT("__rand__", nb_and, slot_nb_and, "&"), + BINSLOT("__xor__", nb_xor, slot_nb_xor, "^"), + RBINSLOT("__rxor__", nb_xor, slot_nb_xor, "^"), + BINSLOT("__or__", nb_or, slot_nb_or, "|"), + RBINSLOT("__ror__", nb_or, slot_nb_or, "|"), + UNSLOT("__int__", nb_int, slot_nb_int, wrap_unaryfunc, + "int(x)"), + UNSLOT("__float__", nb_float, slot_nb_float, wrap_unaryfunc, + "float(x)"), + NBSLOT("__index__", nb_index, slot_nb_index, wrap_unaryfunc, + "x[y:z] <==> x[y.__index__():z.__index__()]"), + IBSLOT("__iadd__", nb_inplace_add, slot_nb_inplace_add, + wrap_binaryfunc, "+"), + IBSLOT("__isub__", nb_inplace_subtract, slot_nb_inplace_subtract, + wrap_binaryfunc, "-"), + IBSLOT("__imul__", nb_inplace_multiply, slot_nb_inplace_multiply, + wrap_binaryfunc, "*"), + IBSLOT("__imod__", nb_inplace_remainder, slot_nb_inplace_remainder, + wrap_binaryfunc, "%"), + IBSLOT("__ipow__", nb_inplace_power, slot_nb_inplace_power, + wrap_binaryfunc, "**"), + IBSLOT("__ilshift__", nb_inplace_lshift, slot_nb_inplace_lshift, + wrap_binaryfunc, "<<"), + IBSLOT("__irshift__", nb_inplace_rshift, slot_nb_inplace_rshift, + wrap_binaryfunc, ">>"), + IBSLOT("__iand__", nb_inplace_and, slot_nb_inplace_and, + wrap_binaryfunc, "&"), + IBSLOT("__ixor__", nb_inplace_xor, slot_nb_inplace_xor, + wrap_binaryfunc, "^"), + IBSLOT("__ior__", nb_inplace_or, slot_nb_inplace_or, + wrap_binaryfunc, "|"), + BINSLOT("__floordiv__", nb_floor_divide, slot_nb_floor_divide, "//"), + RBINSLOT("__rfloordiv__", nb_floor_divide, slot_nb_floor_divide, "//"), + BINSLOT("__truediv__", nb_true_divide, slot_nb_true_divide, "/"), + RBINSLOT("__rtruediv__", nb_true_divide, slot_nb_true_divide, "/"), + IBSLOT("__ifloordiv__", nb_inplace_floor_divide, + slot_nb_inplace_floor_divide, wrap_binaryfunc, "//"), + IBSLOT("__itruediv__", nb_inplace_true_divide, + slot_nb_inplace_true_divide, wrap_binaryfunc, "/"), + + TPSLOT("__str__", tp_str, slot_tp_str, wrap_unaryfunc, + "x.__str__() <==> str(x)"), + TPSLOT("__repr__", tp_repr, slot_tp_repr, wrap_unaryfunc, + "x.__repr__() <==> repr(x)"), + TPSLOT("__hash__", tp_hash, slot_tp_hash, wrap_hashfunc, + "x.__hash__() <==> hash(x)"), + FLSLOT("__call__", tp_call, slot_tp_call, (wrapperfunc)wrap_call, + "x.__call__(...) <==> x(...)", PyWrapperFlag_KEYWORDS), + TPSLOT("__getattribute__", tp_getattro, slot_tp_getattr_hook, + wrap_binaryfunc, "x.__getattribute__('name') <==> x.name"), + TPSLOT("__getattribute__", tp_getattr, NULL, NULL, ""), + TPSLOT("__getattr__", tp_getattro, slot_tp_getattr_hook, NULL, ""), + TPSLOT("__getattr__", tp_getattr, NULL, NULL, ""), + TPSLOT("__setattr__", tp_setattro, slot_tp_setattro, wrap_setattr, + "x.__setattr__('name', value) <==> x.name = value"), + TPSLOT("__setattr__", tp_setattr, NULL, NULL, ""), + TPSLOT("__delattr__", tp_setattro, slot_tp_setattro, wrap_delattr, + "x.__delattr__('name') <==> del x.name"), + TPSLOT("__delattr__", tp_setattr, NULL, NULL, ""), + TPSLOT("__lt__", tp_richcompare, slot_tp_richcompare, richcmp_lt, + "x.__lt__(y) <==> x x<=y"), + TPSLOT("__eq__", tp_richcompare, slot_tp_richcompare, richcmp_eq, + "x.__eq__(y) <==> x==y"), + TPSLOT("__ne__", tp_richcompare, slot_tp_richcompare, richcmp_ne, + "x.__ne__(y) <==> x!=y"), + TPSLOT("__gt__", tp_richcompare, slot_tp_richcompare, richcmp_gt, + "x.__gt__(y) <==> x>y"), + TPSLOT("__ge__", tp_richcompare, slot_tp_richcompare, richcmp_ge, + "x.__ge__(y) <==> x>=y"), + TPSLOT("__iter__", tp_iter, slot_tp_iter, wrap_unaryfunc, + "x.__iter__() <==> iter(x)"), + TPSLOT("__next__", tp_iternext, slot_tp_iternext, wrap_next, + "x.__next__() <==> next(x)"), + TPSLOT("__get__", tp_descr_get, slot_tp_descr_get, wrap_descr_get, + "descr.__get__(obj[, type]) -> value"), + TPSLOT("__set__", tp_descr_set, slot_tp_descr_set, wrap_descr_set, + "descr.__set__(obj, value)"), + TPSLOT("__delete__", tp_descr_set, slot_tp_descr_set, + wrap_descr_delete, "descr.__delete__(obj)"), + FLSLOT("__init__", tp_init, slot_tp_init, (wrapperfunc)wrap_init, + "x.__init__(...) initializes x; " + "see x.__class__.__doc__ for signature", + PyWrapperFlag_KEYWORDS), + TPSLOT("__new__", tp_new, slot_tp_new, NULL, ""), + TPSLOT("__del__", tp_del, slot_tp_del, NULL, ""), + {NULL} }; /* Given a type pointer and an offset gotten from a slotdef entry, return a - pointer to the actual slot. This is not quite the same as simply adding + pointer to the actual slot. This is not quite the same as simply adding the offset to the type pointer, since it takes care to indirect through the proper indirection pointer (as_buffer, etc.); it returns NULL if the indirection pointer is NULL. */ static void ** slotptr(PyTypeObject *type, int ioffset) { - char *ptr; - long offset = ioffset; + char *ptr; + long offset = ioffset; - /* Note: this depends on the order of the members of PyHeapTypeObject! */ - assert(offset >= 0); - assert((size_t)offset < offsetof(PyHeapTypeObject, as_buffer)); - if ((size_t)offset >= offsetof(PyHeapTypeObject, as_sequence)) { - ptr = (char *)type->tp_as_sequence; - offset -= offsetof(PyHeapTypeObject, as_sequence); - } - else if ((size_t)offset >= offsetof(PyHeapTypeObject, as_mapping)) { - ptr = (char *)type->tp_as_mapping; - offset -= offsetof(PyHeapTypeObject, as_mapping); - } - else if ((size_t)offset >= offsetof(PyHeapTypeObject, as_number)) { - ptr = (char *)type->tp_as_number; - offset -= offsetof(PyHeapTypeObject, as_number); - } - else { - ptr = (char *)type; - } - if (ptr != NULL) - ptr += offset; - return (void **)ptr; + /* Note: this depends on the order of the members of PyHeapTypeObject! */ + assert(offset >= 0); + assert((size_t)offset < offsetof(PyHeapTypeObject, as_buffer)); + if ((size_t)offset >= offsetof(PyHeapTypeObject, as_sequence)) { + ptr = (char *)type->tp_as_sequence; + offset -= offsetof(PyHeapTypeObject, as_sequence); + } + else if ((size_t)offset >= offsetof(PyHeapTypeObject, as_mapping)) { + ptr = (char *)type->tp_as_mapping; + offset -= offsetof(PyHeapTypeObject, as_mapping); + } + else if ((size_t)offset >= offsetof(PyHeapTypeObject, as_number)) { + ptr = (char *)type->tp_as_number; + offset -= offsetof(PyHeapTypeObject, as_number); + } + else { + ptr = (char *)type; + } + if (ptr != NULL) + ptr += offset; + return (void **)ptr; } /* Length of array of slotdef pointers used to store slots with the @@ -5584,37 +5584,37 @@ static void ** resolve_slotdups(PyTypeObject *type, PyObject *name) { - /* XXX Maybe this could be optimized more -- but is it worth it? */ + /* XXX Maybe this could be optimized more -- but is it worth it? */ - /* pname and ptrs act as a little cache */ - static PyObject *pname; - static slotdef *ptrs[MAX_EQUIV]; - slotdef *p, **pp; - void **res, **ptr; - - if (pname != name) { - /* Collect all slotdefs that match name into ptrs. */ - pname = name; - pp = ptrs; - for (p = slotdefs; p->name_strobj; p++) { - if (p->name_strobj == name) - *pp++ = p; - } - *pp = NULL; - } - - /* Look in all matching slots of the type; if exactly one of these has - a filled-in slot, return its value. Otherwise return NULL. */ - res = NULL; - for (pp = ptrs; *pp; pp++) { - ptr = slotptr(type, (*pp)->offset); - if (ptr == NULL || *ptr == NULL) - continue; - if (res != NULL) - return NULL; - res = ptr; - } - return res; + /* pname and ptrs act as a little cache */ + static PyObject *pname; + static slotdef *ptrs[MAX_EQUIV]; + slotdef *p, **pp; + void **res, **ptr; + + if (pname != name) { + /* Collect all slotdefs that match name into ptrs. */ + pname = name; + pp = ptrs; + for (p = slotdefs; p->name_strobj; p++) { + if (p->name_strobj == name) + *pp++ = p; + } + *pp = NULL; + } + + /* Look in all matching slots of the type; if exactly one of these has + a filled-in slot, return its value. Otherwise return NULL. */ + res = NULL; + for (pp = ptrs; *pp; pp++) { + ptr = slotptr(type, (*pp)->offset); + if (ptr == NULL || *ptr == NULL) + continue; + if (res != NULL) + return NULL; + res = ptr; + } + return res; } /* Common code for update_slots_callback() and fixup_slot_dispatchers(). This @@ -5626,81 +5626,81 @@ static slotdef * update_one_slot(PyTypeObject *type, slotdef *p) { - PyObject *descr; - PyWrapperDescrObject *d; - void *generic = NULL, *specific = NULL; - int use_generic = 0; - int offset = p->offset; - void **ptr = slotptr(type, offset); - - if (ptr == NULL) { - do { - ++p; - } while (p->offset == offset); - return p; - } - do { - descr = _PyType_Lookup(type, p->name_strobj); - if (descr == NULL) { - if (ptr == (void**)&type->tp_iternext) { - specific = _PyObject_NextNotImplemented; - } - continue; - } - if (Py_TYPE(descr) == &PyWrapperDescr_Type) { - void **tptr = resolve_slotdups(type, p->name_strobj); - if (tptr == NULL || tptr == ptr) - generic = p->function; - d = (PyWrapperDescrObject *)descr; - if (d->d_base->wrapper == p->wrapper && - PyType_IsSubtype(type, d->d_type)) - { - if (specific == NULL || - specific == d->d_wrapped) - specific = d->d_wrapped; - else - use_generic = 1; - } - } - else if (Py_TYPE(descr) == &PyCFunction_Type && - PyCFunction_GET_FUNCTION(descr) == - (PyCFunction)tp_new_wrapper && - ptr == (void**)&type->tp_new) - { - /* The __new__ wrapper is not a wrapper descriptor, - so must be special-cased differently. - If we don't do this, creating an instance will - always use slot_tp_new which will look up - __new__ in the MRO which will call tp_new_wrapper - which will look through the base classes looking - for a static base and call its tp_new (usually - PyType_GenericNew), after performing various - sanity checks and constructing a new argument - list. Cut all that nonsense short -- this speeds - up instance creation tremendously. */ - specific = (void *)type->tp_new; - /* XXX I'm not 100% sure that there isn't a hole - in this reasoning that requires additional - sanity checks. I'll buy the first person to - point out a bug in this reasoning a beer. */ - } - else if (descr == Py_None && - ptr == (void**)&type->tp_hash) { - /* We specifically allow __hash__ to be set to None - to prevent inheritance of the default - implementation from object.__hash__ */ - specific = PyObject_HashNotImplemented; - } - else { - use_generic = 1; - generic = p->function; - } - } while ((++p)->offset == offset); - if (specific && !use_generic) - *ptr = specific; - else - *ptr = generic; - return p; + PyObject *descr; + PyWrapperDescrObject *d; + void *generic = NULL, *specific = NULL; + int use_generic = 0; + int offset = p->offset; + void **ptr = slotptr(type, offset); + + if (ptr == NULL) { + do { + ++p; + } while (p->offset == offset); + return p; + } + do { + descr = _PyType_Lookup(type, p->name_strobj); + if (descr == NULL) { + if (ptr == (void**)&type->tp_iternext) { + specific = _PyObject_NextNotImplemented; + } + continue; + } + if (Py_TYPE(descr) == &PyWrapperDescr_Type) { + void **tptr = resolve_slotdups(type, p->name_strobj); + if (tptr == NULL || tptr == ptr) + generic = p->function; + d = (PyWrapperDescrObject *)descr; + if (d->d_base->wrapper == p->wrapper && + PyType_IsSubtype(type, d->d_type)) + { + if (specific == NULL || + specific == d->d_wrapped) + specific = d->d_wrapped; + else + use_generic = 1; + } + } + else if (Py_TYPE(descr) == &PyCFunction_Type && + PyCFunction_GET_FUNCTION(descr) == + (PyCFunction)tp_new_wrapper && + ptr == (void**)&type->tp_new) + { + /* The __new__ wrapper is not a wrapper descriptor, + so must be special-cased differently. + If we don't do this, creating an instance will + always use slot_tp_new which will look up + __new__ in the MRO which will call tp_new_wrapper + which will look through the base classes looking + for a static base and call its tp_new (usually + PyType_GenericNew), after performing various + sanity checks and constructing a new argument + list. Cut all that nonsense short -- this speeds + up instance creation tremendously. */ + specific = (void *)type->tp_new; + /* XXX I'm not 100% sure that there isn't a hole + in this reasoning that requires additional + sanity checks. I'll buy the first person to + point out a bug in this reasoning a beer. */ + } + else if (descr == Py_None && + ptr == (void**)&type->tp_hash) { + /* We specifically allow __hash__ to be set to None + to prevent inheritance of the default + implementation from object.__hash__ */ + specific = PyObject_HashNotImplemented; + } + else { + use_generic = 1; + generic = p->function; + } + } while ((++p)->offset == offset); + if (specific && !use_generic) + *ptr = specific; + else + *ptr = generic; + return p; } /* In the type, update the slots whose slotdefs are gathered in the pp array. @@ -5708,11 +5708,11 @@ static int update_slots_callback(PyTypeObject *type, void *data) { - slotdef **pp = (slotdef **)data; + slotdef **pp = (slotdef **)data; - for (; *pp; pp++) - update_one_slot(type, *pp); - return 0; + for (; *pp; pp++) + update_one_slot(type, *pp); + return 0; } /* Comparison function for qsort() to compare slotdefs by their offset, and @@ -5720,14 +5720,14 @@ static int slotdef_cmp(const void *aa, const void *bb) { - const slotdef *a = (const slotdef *)aa, *b = (const slotdef *)bb; - int c = a->offset - b->offset; - if (c != 0) - return c; - else - /* Cannot use a-b, as this gives off_t, - which may lose precision when converted to int. */ - return (a > b) ? 1 : (a < b) ? -1 : 0; + const slotdef *a = (const slotdef *)aa, *b = (const slotdef *)bb; + int c = a->offset - b->offset; + if (c != 0) + return c; + else + /* Cannot use a-b, as this gives off_t, + which may lose precision when converted to int. */ + return (a > b) ? 1 : (a < b) ? -1 : 0; } /* Initialize the slotdefs table by adding interned string objects for the @@ -5735,56 +5735,56 @@ static void init_slotdefs(void) { - slotdef *p; - static int initialized = 0; + slotdef *p; + static int initialized = 0; - if (initialized) - return; - for (p = slotdefs; p->name; p++) { - p->name_strobj = PyUnicode_InternFromString(p->name); - if (!p->name_strobj) - Py_FatalError("Out of memory interning slotdef names"); - } - qsort((void *)slotdefs, (size_t)(p-slotdefs), sizeof(slotdef), - slotdef_cmp); - initialized = 1; + if (initialized) + return; + for (p = slotdefs; p->name; p++) { + p->name_strobj = PyUnicode_InternFromString(p->name); + if (!p->name_strobj) + Py_FatalError("Out of memory interning slotdef names"); + } + qsort((void *)slotdefs, (size_t)(p-slotdefs), sizeof(slotdef), + slotdef_cmp); + initialized = 1; } /* Update the slots after assignment to a class (type) attribute. */ static int update_slot(PyTypeObject *type, PyObject *name) { - slotdef *ptrs[MAX_EQUIV]; - slotdef *p; - slotdef **pp; - int offset; - - /* Clear the VALID_VERSION flag of 'type' and all its - subclasses. This could possibly be unified with the - update_subclasses() recursion below, but carefully: - they each have their own conditions on which to stop - recursing into subclasses. */ - PyType_Modified(type); - - init_slotdefs(); - pp = ptrs; - for (p = slotdefs; p->name; p++) { - /* XXX assume name is interned! */ - if (p->name_strobj == name) - *pp++ = p; - } - *pp = NULL; - for (pp = ptrs; *pp; pp++) { - p = *pp; - offset = p->offset; - while (p > slotdefs && (p-1)->offset == offset) - --p; - *pp = p; - } - if (ptrs[0] == NULL) - return 0; /* Not an attribute that affects any slots */ - return update_subclasses(type, name, - update_slots_callback, (void *)ptrs); + slotdef *ptrs[MAX_EQUIV]; + slotdef *p; + slotdef **pp; + int offset; + + /* Clear the VALID_VERSION flag of 'type' and all its + subclasses. This could possibly be unified with the + update_subclasses() recursion below, but carefully: + they each have their own conditions on which to stop + recursing into subclasses. */ + PyType_Modified(type); + + init_slotdefs(); + pp = ptrs; + for (p = slotdefs; p->name; p++) { + /* XXX assume name is interned! */ + if (p->name_strobj == name) + *pp++ = p; + } + *pp = NULL; + for (pp = ptrs; *pp; pp++) { + p = *pp; + offset = p->offset; + while (p > slotdefs && (p-1)->offset == offset) + --p; + *pp = p; + } + if (ptrs[0] == NULL) + return 0; /* Not an attribute that affects any slots */ + return update_subclasses(type, name, + update_slots_callback, (void *)ptrs); } /* Store the proper functions in the slot dispatches at class (type) @@ -5793,23 +5793,23 @@ static void fixup_slot_dispatchers(PyTypeObject *type) { - slotdef *p; + slotdef *p; - init_slotdefs(); - for (p = slotdefs; p->name; ) - p = update_one_slot(type, p); + init_slotdefs(); + for (p = slotdefs; p->name; ) + p = update_one_slot(type, p); } static void update_all_slots(PyTypeObject* type) { - slotdef *p; + slotdef *p; - init_slotdefs(); - for (p = slotdefs; p->name; p++) { - /* update_slot returns int but can't actually fail */ - update_slot(type, p->name_strobj); - } + init_slotdefs(); + for (p = slotdefs; p->name; p++) { + /* update_slot returns int but can't actually fail */ + update_slot(type, p->name_strobj); + } } /* recurse_down_subclasses() and update_subclasses() are mutually @@ -5818,56 +5818,56 @@ static int update_subclasses(PyTypeObject *type, PyObject *name, - update_callback callback, void *data) + update_callback callback, void *data) { - if (callback(type, data) < 0) - return -1; - return recurse_down_subclasses(type, name, callback, data); + if (callback(type, data) < 0) + return -1; + return recurse_down_subclasses(type, name, callback, data); } static int recurse_down_subclasses(PyTypeObject *type, PyObject *name, - update_callback callback, void *data) + update_callback callback, void *data) { - PyTypeObject *subclass; - PyObject *ref, *subclasses, *dict; - Py_ssize_t i, n; - - subclasses = type->tp_subclasses; - if (subclasses == NULL) - return 0; - assert(PyList_Check(subclasses)); - n = PyList_GET_SIZE(subclasses); - for (i = 0; i < n; i++) { - ref = PyList_GET_ITEM(subclasses, i); - assert(PyWeakref_CheckRef(ref)); - subclass = (PyTypeObject *)PyWeakref_GET_OBJECT(ref); - assert(subclass != NULL); - if ((PyObject *)subclass == Py_None) - continue; - assert(PyType_Check(subclass)); - /* Avoid recursing down into unaffected classes */ - dict = subclass->tp_dict; - if (dict != NULL && PyDict_Check(dict) && - PyDict_GetItem(dict, name) != NULL) - continue; - if (update_subclasses(subclass, name, callback, data) < 0) - return -1; - } - return 0; + PyTypeObject *subclass; + PyObject *ref, *subclasses, *dict; + Py_ssize_t i, n; + + subclasses = type->tp_subclasses; + if (subclasses == NULL) + return 0; + assert(PyList_Check(subclasses)); + n = PyList_GET_SIZE(subclasses); + for (i = 0; i < n; i++) { + ref = PyList_GET_ITEM(subclasses, i); + assert(PyWeakref_CheckRef(ref)); + subclass = (PyTypeObject *)PyWeakref_GET_OBJECT(ref); + assert(subclass != NULL); + if ((PyObject *)subclass == Py_None) + continue; + assert(PyType_Check(subclass)); + /* Avoid recursing down into unaffected classes */ + dict = subclass->tp_dict; + if (dict != NULL && PyDict_Check(dict) && + PyDict_GetItem(dict, name) != NULL) + continue; + if (update_subclasses(subclass, name, callback, data) < 0) + return -1; + } + return 0; } /* This function is called by PyType_Ready() to populate the type's dictionary with method descriptors for function slots. For each function slot (like tp_repr) that's defined in the type, one or more corresponding descriptors are added in the type's tp_dict dictionary - under the appropriate name (like __repr__). Some function slots + under the appropriate name (like __repr__). Some function slots cause more than one descriptor to be added (for example, the nb_add slot adds both __add__ and __radd__ descriptors) and some function slots compete for the same descriptor (for example both sq_item and mp_subscript generate a __getitem__ descriptor). - In the latter case, the first slotdef entry encoutered wins. Since + In the latter case, the first slotdef entry encoutered wins. Since slotdef entries are sorted by the offset of the slot in the PyHeapTypeObject, this gives us some control over disambiguating between competing slots: the members of PyHeapTypeObject are listed @@ -5890,344 +5890,344 @@ static int add_operators(PyTypeObject *type) { - PyObject *dict = type->tp_dict; - slotdef *p; - PyObject *descr; - void **ptr; - - init_slotdefs(); - for (p = slotdefs; p->name; p++) { - if (p->wrapper == NULL) - continue; - ptr = slotptr(type, p->offset); - if (!ptr || !*ptr) - continue; - if (PyDict_GetItem(dict, p->name_strobj)) - continue; - if (*ptr == PyObject_HashNotImplemented) { - /* Classes may prevent the inheritance of the tp_hash - slot by storing PyObject_HashNotImplemented in it. Make it - visible as a None value for the __hash__ attribute. */ - if (PyDict_SetItem(dict, p->name_strobj, Py_None) < 0) - return -1; - } - else { - descr = PyDescr_NewWrapper(type, p, *ptr); - if (descr == NULL) - return -1; - if (PyDict_SetItem(dict, p->name_strobj, descr) < 0) - return -1; - Py_DECREF(descr); - } - } - if (type->tp_new != NULL) { - if (add_tp_new_wrapper(type) < 0) - return -1; - } - return 0; + PyObject *dict = type->tp_dict; + slotdef *p; + PyObject *descr; + void **ptr; + + init_slotdefs(); + for (p = slotdefs; p->name; p++) { + if (p->wrapper == NULL) + continue; + ptr = slotptr(type, p->offset); + if (!ptr || !*ptr) + continue; + if (PyDict_GetItem(dict, p->name_strobj)) + continue; + if (*ptr == PyObject_HashNotImplemented) { + /* Classes may prevent the inheritance of the tp_hash + slot by storing PyObject_HashNotImplemented in it. Make it + visible as a None value for the __hash__ attribute. */ + if (PyDict_SetItem(dict, p->name_strobj, Py_None) < 0) + return -1; + } + else { + descr = PyDescr_NewWrapper(type, p, *ptr); + if (descr == NULL) + return -1; + if (PyDict_SetItem(dict, p->name_strobj, descr) < 0) + return -1; + Py_DECREF(descr); + } + } + if (type->tp_new != NULL) { + if (add_tp_new_wrapper(type) < 0) + return -1; + } + return 0; } /* Cooperative 'super' */ typedef struct { - PyObject_HEAD - PyTypeObject *type; - PyObject *obj; - PyTypeObject *obj_type; + PyObject_HEAD + PyTypeObject *type; + PyObject *obj; + PyTypeObject *obj_type; } superobject; static PyMemberDef super_members[] = { - {"__thisclass__", T_OBJECT, offsetof(superobject, type), READONLY, - "the class invoking super()"}, - {"__self__", T_OBJECT, offsetof(superobject, obj), READONLY, - "the instance invoking super(); may be None"}, - {"__self_class__", T_OBJECT, offsetof(superobject, obj_type), READONLY, - "the type of the instance invoking super(); may be None"}, - {0} + {"__thisclass__", T_OBJECT, offsetof(superobject, type), READONLY, + "the class invoking super()"}, + {"__self__", T_OBJECT, offsetof(superobject, obj), READONLY, + "the instance invoking super(); may be None"}, + {"__self_class__", T_OBJECT, offsetof(superobject, obj_type), READONLY, + "the type of the instance invoking super(); may be None"}, + {0} }; static void super_dealloc(PyObject *self) { - superobject *su = (superobject *)self; + superobject *su = (superobject *)self; - _PyObject_GC_UNTRACK(self); - Py_XDECREF(su->obj); - Py_XDECREF(su->type); - Py_XDECREF(su->obj_type); - Py_TYPE(self)->tp_free(self); + _PyObject_GC_UNTRACK(self); + Py_XDECREF(su->obj); + Py_XDECREF(su->type); + Py_XDECREF(su->obj_type); + Py_TYPE(self)->tp_free(self); } static PyObject * super_repr(PyObject *self) { - superobject *su = (superobject *)self; + superobject *su = (superobject *)self; - if (su->obj_type) - return PyUnicode_FromFormat( - ", <%s object>>", - su->type ? su->type->tp_name : "NULL", - su->obj_type->tp_name); - else - return PyUnicode_FromFormat( - ", NULL>", - su->type ? su->type->tp_name : "NULL"); + if (su->obj_type) + return PyUnicode_FromFormat( + ", <%s object>>", + su->type ? su->type->tp_name : "NULL", + su->obj_type->tp_name); + else + return PyUnicode_FromFormat( + ", NULL>", + su->type ? su->type->tp_name : "NULL"); } static PyObject * super_getattro(PyObject *self, PyObject *name) { - superobject *su = (superobject *)self; - int skip = su->obj_type == NULL; + superobject *su = (superobject *)self; + int skip = su->obj_type == NULL; - if (!skip) { - /* We want __class__ to return the class of the super object - (i.e. super, or a subclass), not the class of su->obj. */ - skip = (PyUnicode_Check(name) && - PyUnicode_GET_SIZE(name) == 9 && - PyUnicode_CompareWithASCIIString(name, "__class__") == 0); - } - - if (!skip) { - PyObject *mro, *res, *tmp, *dict; - PyTypeObject *starttype; - descrgetfunc f; - Py_ssize_t i, n; - - starttype = su->obj_type; - mro = starttype->tp_mro; - - if (mro == NULL) - n = 0; - else { - assert(PyTuple_Check(mro)); - n = PyTuple_GET_SIZE(mro); - } - for (i = 0; i < n; i++) { - if ((PyObject *)(su->type) == PyTuple_GET_ITEM(mro, i)) - break; - } - i++; - res = NULL; - for (; i < n; i++) { - tmp = PyTuple_GET_ITEM(mro, i); - if (PyType_Check(tmp)) - dict = ((PyTypeObject *)tmp)->tp_dict; - else - continue; - res = PyDict_GetItem(dict, name); - if (res != NULL) { - Py_INCREF(res); - f = Py_TYPE(res)->tp_descr_get; - if (f != NULL) { - tmp = f(res, - /* Only pass 'obj' param if - this is instance-mode super - (See SF ID #743627) - */ - (su->obj == (PyObject *) - su->obj_type - ? (PyObject *)NULL - : su->obj), - (PyObject *)starttype); - Py_DECREF(res); - res = tmp; - } - return res; - } - } - } - return PyObject_GenericGetAttr(self, name); + if (!skip) { + /* We want __class__ to return the class of the super object + (i.e. super, or a subclass), not the class of su->obj. */ + skip = (PyUnicode_Check(name) && + PyUnicode_GET_SIZE(name) == 9 && + PyUnicode_CompareWithASCIIString(name, "__class__") == 0); + } + + if (!skip) { + PyObject *mro, *res, *tmp, *dict; + PyTypeObject *starttype; + descrgetfunc f; + Py_ssize_t i, n; + + starttype = su->obj_type; + mro = starttype->tp_mro; + + if (mro == NULL) + n = 0; + else { + assert(PyTuple_Check(mro)); + n = PyTuple_GET_SIZE(mro); + } + for (i = 0; i < n; i++) { + if ((PyObject *)(su->type) == PyTuple_GET_ITEM(mro, i)) + break; + } + i++; + res = NULL; + for (; i < n; i++) { + tmp = PyTuple_GET_ITEM(mro, i); + if (PyType_Check(tmp)) + dict = ((PyTypeObject *)tmp)->tp_dict; + else + continue; + res = PyDict_GetItem(dict, name); + if (res != NULL) { + Py_INCREF(res); + f = Py_TYPE(res)->tp_descr_get; + if (f != NULL) { + tmp = f(res, + /* Only pass 'obj' param if + this is instance-mode super + (See SF ID #743627) + */ + (su->obj == (PyObject *) + su->obj_type + ? (PyObject *)NULL + : su->obj), + (PyObject *)starttype); + Py_DECREF(res); + res = tmp; + } + return res; + } + } + } + return PyObject_GenericGetAttr(self, name); } static PyTypeObject * supercheck(PyTypeObject *type, PyObject *obj) { - /* Check that a super() call makes sense. Return a type object. + /* Check that a super() call makes sense. Return a type object. + + obj can be a new-style class, or an instance of one: - obj can be a new-style class, or an instance of one: + - If it is a class, it must be a subclass of 'type'. This case is + used for class methods; the return value is obj. - - If it is a class, it must be a subclass of 'type'. This case is - used for class methods; the return value is obj. + - If it is an instance, it must be an instance of 'type'. This is + the normal case; the return value is obj.__class__. + + But... when obj is an instance, we want to allow for the case where + Py_TYPE(obj) is not a subclass of type, but obj.__class__ is! + This will allow using super() with a proxy for obj. + */ + + /* Check for first bullet above (special case) */ + if (PyType_Check(obj) && PyType_IsSubtype((PyTypeObject *)obj, type)) { + Py_INCREF(obj); + return (PyTypeObject *)obj; + } + + /* Normal case */ + if (PyType_IsSubtype(Py_TYPE(obj), type)) { + Py_INCREF(Py_TYPE(obj)); + return Py_TYPE(obj); + } + else { + /* Try the slow way */ + static PyObject *class_str = NULL; + PyObject *class_attr; + + if (class_str == NULL) { + class_str = PyUnicode_FromString("__class__"); + if (class_str == NULL) + return NULL; + } + + class_attr = PyObject_GetAttr(obj, class_str); + + if (class_attr != NULL && + PyType_Check(class_attr) && + (PyTypeObject *)class_attr != Py_TYPE(obj)) + { + int ok = PyType_IsSubtype( + (PyTypeObject *)class_attr, type); + if (ok) + return (PyTypeObject *)class_attr; + } - - If it is an instance, it must be an instance of 'type'. This is - the normal case; the return value is obj.__class__. - - But... when obj is an instance, we want to allow for the case where - Py_TYPE(obj) is not a subclass of type, but obj.__class__ is! - This will allow using super() with a proxy for obj. - */ - - /* Check for first bullet above (special case) */ - if (PyType_Check(obj) && PyType_IsSubtype((PyTypeObject *)obj, type)) { - Py_INCREF(obj); - return (PyTypeObject *)obj; - } - - /* Normal case */ - if (PyType_IsSubtype(Py_TYPE(obj), type)) { - Py_INCREF(Py_TYPE(obj)); - return Py_TYPE(obj); - } - else { - /* Try the slow way */ - static PyObject *class_str = NULL; - PyObject *class_attr; - - if (class_str == NULL) { - class_str = PyUnicode_FromString("__class__"); - if (class_str == NULL) - return NULL; - } - - class_attr = PyObject_GetAttr(obj, class_str); - - if (class_attr != NULL && - PyType_Check(class_attr) && - (PyTypeObject *)class_attr != Py_TYPE(obj)) - { - int ok = PyType_IsSubtype( - (PyTypeObject *)class_attr, type); - if (ok) - return (PyTypeObject *)class_attr; - } - - if (class_attr == NULL) - PyErr_Clear(); - else - Py_DECREF(class_attr); - } - - PyErr_SetString(PyExc_TypeError, - "super(type, obj): " - "obj must be an instance or subtype of type"); - return NULL; + if (class_attr == NULL) + PyErr_Clear(); + else + Py_DECREF(class_attr); + } + + PyErr_SetString(PyExc_TypeError, + "super(type, obj): " + "obj must be an instance or subtype of type"); + return NULL; } static PyObject * super_descr_get(PyObject *self, PyObject *obj, PyObject *type) { - superobject *su = (superobject *)self; - superobject *newobj; + superobject *su = (superobject *)self; + superobject *newobj; - if (obj == NULL || obj == Py_None || su->obj != NULL) { - /* Not binding to an object, or already bound */ - Py_INCREF(self); - return self; - } - if (Py_TYPE(su) != &PySuper_Type) - /* If su is an instance of a (strict) subclass of super, - call its type */ - return PyObject_CallFunctionObjArgs((PyObject *)Py_TYPE(su), - su->type, obj, NULL); - else { - /* Inline the common case */ - PyTypeObject *obj_type = supercheck(su->type, obj); - if (obj_type == NULL) - return NULL; - newobj = (superobject *)PySuper_Type.tp_new(&PySuper_Type, - NULL, NULL); - if (newobj == NULL) - return NULL; - Py_INCREF(su->type); - Py_INCREF(obj); - newobj->type = su->type; - newobj->obj = obj; - newobj->obj_type = obj_type; - return (PyObject *)newobj; - } + if (obj == NULL || obj == Py_None || su->obj != NULL) { + /* Not binding to an object, or already bound */ + Py_INCREF(self); + return self; + } + if (Py_TYPE(su) != &PySuper_Type) + /* If su is an instance of a (strict) subclass of super, + call its type */ + return PyObject_CallFunctionObjArgs((PyObject *)Py_TYPE(su), + su->type, obj, NULL); + else { + /* Inline the common case */ + PyTypeObject *obj_type = supercheck(su->type, obj); + if (obj_type == NULL) + return NULL; + newobj = (superobject *)PySuper_Type.tp_new(&PySuper_Type, + NULL, NULL); + if (newobj == NULL) + return NULL; + Py_INCREF(su->type); + Py_INCREF(obj); + newobj->type = su->type; + newobj->obj = obj; + newobj->obj_type = obj_type; + return (PyObject *)newobj; + } } static int super_init(PyObject *self, PyObject *args, PyObject *kwds) { - superobject *su = (superobject *)self; - PyTypeObject *type = NULL; - PyObject *obj = NULL; - PyTypeObject *obj_type = NULL; - - if (!_PyArg_NoKeywords("super", kwds)) - return -1; - if (!PyArg_ParseTuple(args, "|O!O:super", &PyType_Type, &type, &obj)) - return -1; - + superobject *su = (superobject *)self; + PyTypeObject *type = NULL; + PyObject *obj = NULL; + PyTypeObject *obj_type = NULL; + + if (!_PyArg_NoKeywords("super", kwds)) + return -1; + if (!PyArg_ParseTuple(args, "|O!O:super", &PyType_Type, &type, &obj)) + return -1; + + if (type == NULL) { + /* Call super(), without args -- fill in from __class__ + and first local variable on the stack. */ + PyFrameObject *f = PyThreadState_GET()->frame; + PyCodeObject *co = f->f_code; + int i, n; + if (co == NULL) { + PyErr_SetString(PyExc_SystemError, + "super(): no code object"); + return -1; + } + if (co->co_argcount == 0) { + PyErr_SetString(PyExc_SystemError, + "super(): no arguments"); + return -1; + } + obj = f->f_localsplus[0]; + if (obj == NULL) { + PyErr_SetString(PyExc_SystemError, + "super(): arg[0] deleted"); + return -1; + } + if (co->co_freevars == NULL) + n = 0; + else { + assert(PyTuple_Check(co->co_freevars)); + n = PyTuple_GET_SIZE(co->co_freevars); + } + for (i = 0; i < n; i++) { + PyObject *name = PyTuple_GET_ITEM(co->co_freevars, i); + assert(PyUnicode_Check(name)); + if (!PyUnicode_CompareWithASCIIString(name, + "__class__")) { + Py_ssize_t index = co->co_nlocals + + PyTuple_GET_SIZE(co->co_cellvars) + i; + PyObject *cell = f->f_localsplus[index]; + if (cell == NULL || !PyCell_Check(cell)) { + PyErr_SetString(PyExc_SystemError, + "super(): bad __class__ cell"); + return -1; + } + type = (PyTypeObject *) PyCell_GET(cell); + if (type == NULL) { + PyErr_SetString(PyExc_SystemError, + "super(): empty __class__ cell"); + return -1; + } + if (!PyType_Check(type)) { + PyErr_Format(PyExc_SystemError, + "super(): __class__ is not a type (%s)", + Py_TYPE(type)->tp_name); + return -1; + } + break; + } + } if (type == NULL) { - /* Call super(), without args -- fill in from __class__ - and first local variable on the stack. */ - PyFrameObject *f = PyThreadState_GET()->frame; - PyCodeObject *co = f->f_code; - int i, n; - if (co == NULL) { - PyErr_SetString(PyExc_SystemError, - "super(): no code object"); - return -1; - } - if (co->co_argcount == 0) { - PyErr_SetString(PyExc_SystemError, - "super(): no arguments"); - return -1; - } - obj = f->f_localsplus[0]; - if (obj == NULL) { - PyErr_SetString(PyExc_SystemError, - "super(): arg[0] deleted"); - return -1; - } - if (co->co_freevars == NULL) - n = 0; - else { - assert(PyTuple_Check(co->co_freevars)); - n = PyTuple_GET_SIZE(co->co_freevars); - } - for (i = 0; i < n; i++) { - PyObject *name = PyTuple_GET_ITEM(co->co_freevars, i); - assert(PyUnicode_Check(name)); - if (!PyUnicode_CompareWithASCIIString(name, - "__class__")) { - Py_ssize_t index = co->co_nlocals + - PyTuple_GET_SIZE(co->co_cellvars) + i; - PyObject *cell = f->f_localsplus[index]; - if (cell == NULL || !PyCell_Check(cell)) { - PyErr_SetString(PyExc_SystemError, - "super(): bad __class__ cell"); - return -1; - } - type = (PyTypeObject *) PyCell_GET(cell); - if (type == NULL) { - PyErr_SetString(PyExc_SystemError, - "super(): empty __class__ cell"); - return -1; - } - if (!PyType_Check(type)) { - PyErr_Format(PyExc_SystemError, - "super(): __class__ is not a type (%s)", - Py_TYPE(type)->tp_name); - return -1; - } - break; - } - } - if (type == NULL) { - PyErr_SetString(PyExc_SystemError, - "super(): __class__ cell not found"); - return -1; - } - } - - if (obj == Py_None) - obj = NULL; - if (obj != NULL) { - obj_type = supercheck(type, obj); - if (obj_type == NULL) - return -1; - Py_INCREF(obj); - } - Py_INCREF(type); - su->type = type; - su->obj = obj; - su->obj_type = obj_type; - return 0; + PyErr_SetString(PyExc_SystemError, + "super(): __class__ cell not found"); + return -1; + } + } + + if (obj == Py_None) + obj = NULL; + if (obj != NULL) { + obj_type = supercheck(type, obj); + if (obj_type == NULL) + return -1; + Py_INCREF(obj); + } + Py_INCREF(type); + su->type = type; + su->obj = obj; + su->obj_type = obj_type; + return 0; } PyDoc_STRVAR(super_doc, @@ -6238,65 +6238,65 @@ "Typical use to call a cooperative superclass method:\n" "class C(B):\n" " def meth(self, arg):\n" -" super().meth(arg)\n" +" super().meth(arg)\n" "This works for class methods too:\n" "class C(B):\n" " @classmethod\n" " def cmeth(cls, arg):\n" -" super().cmeth(arg)\n"); +" super().cmeth(arg)\n"); static int super_traverse(PyObject *self, visitproc visit, void *arg) { - superobject *su = (superobject *)self; + superobject *su = (superobject *)self; - Py_VISIT(su->obj); - Py_VISIT(su->type); - Py_VISIT(su->obj_type); + Py_VISIT(su->obj); + Py_VISIT(su->type); + Py_VISIT(su->obj_type); - return 0; + return 0; } PyTypeObject PySuper_Type = { - PyVarObject_HEAD_INIT(&PyType_Type, 0) - "super", /* tp_name */ - sizeof(superobject), /* tp_basicsize */ - 0, /* tp_itemsize */ - /* methods */ - super_dealloc, /* tp_dealloc */ - 0, /* tp_print */ - 0, /* tp_getattr */ - 0, /* tp_setattr */ - 0, /* tp_reserved */ - super_repr, /* tp_repr */ - 0, /* tp_as_number */ - 0, /* tp_as_sequence */ - 0, /* tp_as_mapping */ - 0, /* tp_hash */ - 0, /* tp_call */ - 0, /* tp_str */ - super_getattro, /* tp_getattro */ - 0, /* tp_setattro */ - 0, /* tp_as_buffer */ - Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC | - Py_TPFLAGS_BASETYPE, /* tp_flags */ - super_doc, /* tp_doc */ - super_traverse, /* tp_traverse */ - 0, /* tp_clear */ - 0, /* tp_richcompare */ - 0, /* tp_weaklistoffset */ - 0, /* tp_iter */ - 0, /* tp_iternext */ - 0, /* tp_methods */ - super_members, /* tp_members */ - 0, /* tp_getset */ - 0, /* tp_base */ - 0, /* tp_dict */ - super_descr_get, /* tp_descr_get */ - 0, /* tp_descr_set */ - 0, /* tp_dictoffset */ - super_init, /* tp_init */ - PyType_GenericAlloc, /* tp_alloc */ - PyType_GenericNew, /* tp_new */ - PyObject_GC_Del, /* tp_free */ + PyVarObject_HEAD_INIT(&PyType_Type, 0) + "super", /* tp_name */ + sizeof(superobject), /* tp_basicsize */ + 0, /* tp_itemsize */ + /* methods */ + super_dealloc, /* tp_dealloc */ + 0, /* tp_print */ + 0, /* tp_getattr */ + 0, /* tp_setattr */ + 0, /* tp_reserved */ + super_repr, /* tp_repr */ + 0, /* tp_as_number */ + 0, /* tp_as_sequence */ + 0, /* tp_as_mapping */ + 0, /* tp_hash */ + 0, /* tp_call */ + 0, /* tp_str */ + super_getattro, /* tp_getattro */ + 0, /* tp_setattro */ + 0, /* tp_as_buffer */ + Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC | + Py_TPFLAGS_BASETYPE, /* tp_flags */ + super_doc, /* tp_doc */ + super_traverse, /* tp_traverse */ + 0, /* tp_clear */ + 0, /* tp_richcompare */ + 0, /* tp_weaklistoffset */ + 0, /* tp_iter */ + 0, /* tp_iternext */ + 0, /* tp_methods */ + super_members, /* tp_members */ + 0, /* tp_getset */ + 0, /* tp_base */ + 0, /* tp_dict */ + super_descr_get, /* tp_descr_get */ + 0, /* tp_descr_set */ + 0, /* tp_dictoffset */ + super_init, /* tp_init */ + PyType_GenericAlloc, /* tp_alloc */ + PyType_GenericNew, /* tp_new */ + PyObject_GC_Del, /* tp_free */ }; Modified: python/branches/release31-maint/Objects/unicodectype.c ============================================================================== --- python/branches/release31-maint/Objects/unicodectype.c (original) +++ python/branches/release31-maint/Objects/unicodectype.c Sun May 9 18:14:21 2010 @@ -67,9 +67,9 @@ case 0x0085: /* NEXT LINE */ case 0x2028: /* LINE SEPARATOR */ case 0x2029: /* PARAGRAPH SEPARATOR */ - return 1; + return 1; default: - return 0; + return 0; } } @@ -82,10 +82,10 @@ int delta = ctype->title; if (ctype->flags & NODELTA_MASK) - return delta; + return delta; if (delta >= 32768) - delta -= 65536; + delta -= 65536; return ch + delta; } @@ -133,7 +133,7 @@ int _PyUnicode_IsDecimalDigit(Py_UNICODE ch) { if (_PyUnicode_ToDecimalDigit(ch) < 0) - return 0; + return 0; return 1; } @@ -150,7 +150,7 @@ int _PyUnicode_IsDigit(Py_UNICODE ch) { if (_PyUnicode_ToDigit(ch) < 0) - return 0; + return 0; return 1; } @@ -169,7 +169,7 @@ #ifdef Py_UNICODE_WIDE case 0x1018A: #endif - return (double) 0; + return (double) 0; case 0x09F4: case 0x17F1: case 0x215F: @@ -188,7 +188,7 @@ case 0x10320: case 0x103D1: #endif - return (double) 1; + return (double) 1; case 0x00BD: case 0x0F2A: case 0x2CFD: @@ -197,20 +197,20 @@ case 0x10175: case 0x10176: #endif - return (double) 1 / 2; + return (double) 1 / 2; case 0x2153: - return (double) 1 / 3; + return (double) 1 / 3; case 0x00BC: #ifdef Py_UNICODE_WIDE case 0x10140: #endif - return (double) 1 / 4; + return (double) 1 / 4; case 0x2155: - return (double) 1 / 5; + return (double) 1 / 5; case 0x2159: - return (double) 1 / 6; + return (double) 1 / 6; case 0x215B: - return (double) 1 / 8; + return (double) 1 / 8; case 0x0BF0: case 0x1372: case 0x2169: @@ -239,7 +239,7 @@ case 0x103D3: case 0x10A44: #endif - return (double) 10; + return (double) 10; case 0x0BF1: case 0x137B: case 0x216D: @@ -252,7 +252,7 @@ case 0x103D5: case 0x10A46: #endif - return (double) 100; + return (double) 100; case 0x0BF2: case 0x216F: case 0x217F: @@ -264,21 +264,21 @@ case 0x10171: case 0x10A47: #endif - return (double) 1000; + return (double) 1000; case 0x137C: case 0x2182: #ifdef Py_UNICODE_WIDE case 0x1012B: case 0x10155: #endif - return (double) 10000; + return (double) 10000; case 0x216A: case 0x217A: case 0x246A: case 0x247E: case 0x2492: case 0x24EB: - return (double) 11; + return (double) 11; case 0x0F2F: return (double) 11 / 2; case 0x216B: @@ -287,24 +287,24 @@ case 0x247F: case 0x2493: case 0x24EC: - return (double) 12; + return (double) 12; case 0x246C: case 0x2480: case 0x2494: case 0x24ED: - return (double) 13; + return (double) 13; case 0x0F30: return (double) 13 / 2; case 0x246D: case 0x2481: case 0x2495: case 0x24EE: - return (double) 14; + return (double) 14; case 0x246E: case 0x2482: case 0x2496: case 0x24EF: - return (double) 15; + return (double) 15; case 0x0F31: return (double) 15 / 2; case 0x09F9: @@ -312,13 +312,13 @@ case 0x2483: case 0x2497: case 0x24F0: - return (double) 16; + return (double) 16; case 0x16EE: case 0x2470: case 0x2484: case 0x2498: case 0x24F1: - return (double) 17; + return (double) 17; case 0x0F32: return (double) 17 / 2; case 0x16EF: @@ -326,13 +326,13 @@ case 0x2485: case 0x2499: case 0x24F2: - return (double) 18; + return (double) 18; case 0x16F0: case 0x2472: case 0x2486: case 0x249A: case 0x24F3: - return (double) 19; + return (double) 19; case 0x09F5: case 0x17F2: case 0x2161: @@ -349,12 +349,12 @@ case 0x1015E: case 0x103D2: #endif - return (double) 2; + return (double) 2; case 0x2154: #ifdef Py_UNICODE_WIDE case 0x10177: #endif - return (double) 2 / 3; + return (double) 2 / 3; case 0x2156: return (double) 2 / 5; case 0x1373: @@ -406,18 +406,18 @@ #ifdef Py_UNICODE_WIDE case 0x10109: #endif - return (double) 3; + return (double) 3; case 0x0F2B: return (double) 3 / 2; case 0x00BE: #ifdef Py_UNICODE_WIDE case 0x10178: #endif - return (double) 3 / 4; + return (double) 3 / 4; case 0x2157: - return (double) 3 / 5; + return (double) 3 / 5; case 0x215C: - return (double) 3 / 8; + return (double) 3 / 8; case 0x1374: case 0x303A: case 0x325A: @@ -425,7 +425,7 @@ case 0x10112: case 0x10165: #endif - return (double) 30; + return (double) 30; #ifdef Py_UNICODE_WIDE case 0x1011B: case 0x1016B: @@ -464,9 +464,9 @@ #ifdef Py_UNICODE_WIDE case 0x1010A: #endif - return (double) 4; + return (double) 4; case 0x2158: - return (double) 4 / 5; + return (double) 4 / 5; case 0x1375: case 0x32B5: #ifdef Py_UNICODE_WIDE @@ -514,13 +514,13 @@ case 0x10173: case 0x10321: #endif - return (double) 5; + return (double) 5; case 0x0F2C: return (double) 5 / 2; case 0x215A: - return (double) 5 / 6; + return (double) 5 / 6; case 0x215D: - return (double) 5 / 8; + return (double) 5 / 8; case 0x1376: case 0x216C: case 0x217C: @@ -537,7 +537,7 @@ case 0x10174: case 0x10323: #endif - return (double) 50; + return (double) 50; case 0x216E: case 0x217E: #ifdef Py_UNICODE_WIDE @@ -551,7 +551,7 @@ case 0x1016F: case 0x10170: #endif - return (double) 500; + return (double) 500; case 0x2181: #ifdef Py_UNICODE_WIDE case 0x10126: @@ -559,7 +559,7 @@ case 0x1014E: case 0x10172: #endif - return (double) 5000; + return (double) 5000; #ifdef Py_UNICODE_WIDE case 0x1012F: case 0x10147: @@ -575,12 +575,12 @@ #ifdef Py_UNICODE_WIDE case 0x1010C: #endif - return (double) 6; + return (double) 6; case 0x1377: #ifdef Py_UNICODE_WIDE case 0x10115: #endif - return (double) 60; + return (double) 60; #ifdef Py_UNICODE_WIDE case 0x1011E: return (double) 600; @@ -598,16 +598,16 @@ #ifdef Py_UNICODE_WIDE case 0x1010D: #endif - return (double) 7; + return (double) 7; case 0x0F2D: return (double) 7 / 2; case 0x215E: - return (double) 7 / 8; + return (double) 7 / 8; case 0x1378: #ifdef Py_UNICODE_WIDE case 0x10116: #endif - return (double) 70; + return (double) 70; #ifdef Py_UNICODE_WIDE case 0x1011F: return (double) 700; @@ -625,12 +625,12 @@ #ifdef Py_UNICODE_WIDE case 0x1010E: #endif - return (double) 8; + return (double) 8; case 0x1379: #ifdef Py_UNICODE_WIDE case 0x10117: #endif - return (double) 80; + return (double) 80; #ifdef Py_UNICODE_WIDE case 0x10120: return (double) 800; @@ -648,14 +648,14 @@ #ifdef Py_UNICODE_WIDE case 0x1010F: #endif - return (double) 9; + return (double) 9; case 0x0F2E: return (double) 9 / 2; case 0x137A: #ifdef Py_UNICODE_WIDE case 0x10118: #endif - return (double) 90; + return (double) 90; #ifdef Py_UNICODE_WIDE case 0x10121: case 0x1034A: @@ -666,7 +666,7 @@ return (double) 90000; #endif default: - return (double) _PyUnicode_ToDigit(ch); + return (double) _PyUnicode_ToDigit(ch); } } @@ -733,9 +733,9 @@ case 0x202F: /* NARROW NO-BREAK SPACE */ case 0x205F: /* MEDIUM MATHEMATICAL SPACE */ case 0x3000: /* IDEOGRAPHIC SPACE */ - return 1; + return 1; default: - return 0; + return 0; } } @@ -767,9 +767,9 @@ const _PyUnicode_TypeRecord *ctype = gettyperecord(ch); int delta = ctype->upper; if (ctype->flags & NODELTA_MASK) - return delta; + return delta; if (delta >= 32768) - delta -= 65536; + delta -= 65536; return ch + delta; } @@ -781,9 +781,9 @@ const _PyUnicode_TypeRecord *ctype = gettyperecord(ch); int delta = ctype->lower; if (ctype->flags & NODELTA_MASK) - return delta; + return delta; if (delta >= 32768) - delta -= 65536; + delta -= 65536; return ch + delta; } Modified: python/branches/release31-maint/Objects/weakrefobject.c ============================================================================== --- python/branches/release31-maint/Objects/weakrefobject.c (original) +++ python/branches/release31-maint/Objects/weakrefobject.c Sun May 9 18:14:21 2010 @@ -57,9 +57,9 @@ PyWeakref_GET_OBJECT(self)); if (*list == self) - /* If 'self' is the end of the list (and thus self->wr_next == NULL) - then the weakref list itself (and thus the value of *list) will - end up being set to NULL. */ + /* If 'self' is the end of the list (and thus self->wr_next == NULL) + then the weakref list itself (and thus the value of *list) will + end up being set to NULL. */ *list = self->wr_next; self->wr_object = Py_None; if (self->wr_prev != NULL) @@ -161,21 +161,21 @@ PyOS_snprintf(buffer, sizeof(buffer), "", self); } else { - char *name = NULL; - PyObject *nameobj = PyObject_GetAttrString(PyWeakref_GET_OBJECT(self), - "__name__"); - if (nameobj == NULL) - PyErr_Clear(); - else if (PyUnicode_Check(nameobj)) - name = _PyUnicode_AsString(nameobj); + char *name = NULL; + PyObject *nameobj = PyObject_GetAttrString(PyWeakref_GET_OBJECT(self), + "__name__"); + if (nameobj == NULL) + PyErr_Clear(); + else if (PyUnicode_Check(nameobj)) + name = _PyUnicode_AsString(nameobj); PyOS_snprintf(buffer, sizeof(buffer), - name ? "" - : "", - self, - Py_TYPE(PyWeakref_GET_OBJECT(self))->tp_name, - PyWeakref_GET_OBJECT(self), - name); - Py_XDECREF(nameobj); + name ? "" + : "", + self, + Py_TYPE(PyWeakref_GET_OBJECT(self))->tp_name, + PyWeakref_GET_OBJECT(self), + name); + Py_XDECREF(nameobj); } return PyUnicode_FromString(buffer); } @@ -188,8 +188,8 @@ weakref_richcompare(PyWeakReference* self, PyWeakReference* other, int op) { if ((op != Py_EQ && op != Py_NE) || - !PyWeakref_Check(self) || - !PyWeakref_Check(other)) { + !PyWeakref_Check(self) || + !PyWeakref_Check(other)) { Py_INCREF(Py_NotImplemented); return Py_NotImplemented; } @@ -339,10 +339,10 @@ sizeof(PyWeakReference), 0, weakref_dealloc, /*tp_dealloc*/ - 0, /*tp_print*/ + 0, /*tp_print*/ 0, /*tp_getattr*/ 0, /*tp_setattr*/ - 0, /*tp_reserved*/ + 0, /*tp_reserved*/ (reprfunc)weakref_repr, /*tp_repr*/ 0, /*tp_as_number*/ 0, /*tp_as_sequence*/ @@ -358,7 +358,7 @@ 0, /*tp_doc*/ (traverseproc)gc_traverse, /*tp_traverse*/ (inquiry)gc_clear, /*tp_clear*/ - (richcmpfunc)weakref_richcompare, /*tp_richcompare*/ + (richcmpfunc)weakref_richcompare, /*tp_richcompare*/ 0, /*tp_weaklistoffset*/ 0, /*tp_iter*/ 0, /*tp_iternext*/ @@ -438,9 +438,9 @@ #define WRAP_METHOD(method, special) \ static PyObject * \ method(PyObject *proxy) { \ - UNWRAP(proxy); \ - return PyObject_CallMethod(proxy, special, ""); \ - } + UNWRAP(proxy); \ + return PyObject_CallMethod(proxy, special, ""); \ + } /* direct slots */ @@ -454,9 +454,9 @@ { char buf[160]; PyOS_snprintf(buf, sizeof(buf), - "", proxy, - Py_TYPE(PyWeakref_GET_OBJECT(proxy))->tp_name, - PyWeakref_GET_OBJECT(proxy)); + "", proxy, + Py_TYPE(PyWeakref_GET_OBJECT(proxy))->tp_name, + PyWeakref_GET_OBJECT(proxy)); return PyUnicode_FromString(buf); } @@ -587,8 +587,8 @@ static PyMethodDef proxy_methods[] = { - {"__bytes__", (PyCFunction)proxy_bytes, METH_NOARGS}, - {NULL, NULL} + {"__bytes__", (PyCFunction)proxy_bytes, METH_NOARGS}, + {NULL, NULL} }; @@ -636,7 +636,7 @@ 0, /*sq_item*/ 0, /*sq_slice*/ 0, /*sq_ass_item*/ - 0, /*sq_ass_slice*/ + 0, /*sq_ass_slice*/ (objobjproc)proxy_contains, /* sq_contains */ }; @@ -655,20 +655,20 @@ 0, /* methods */ (destructor)proxy_dealloc, /* tp_dealloc */ - 0, /* tp_print */ - 0, /* tp_getattr */ - 0, /* tp_setattr */ - 0, /* tp_reserved */ - (reprfunc)proxy_repr, /* tp_repr */ - &proxy_as_number, /* tp_as_number */ - &proxy_as_sequence, /* tp_as_sequence */ - &proxy_as_mapping, /* tp_as_mapping */ - 0, /* tp_hash */ - 0, /* tp_call */ + 0, /* tp_print */ + 0, /* tp_getattr */ + 0, /* tp_setattr */ + 0, /* tp_reserved */ + (reprfunc)proxy_repr, /* tp_repr */ + &proxy_as_number, /* tp_as_number */ + &proxy_as_sequence, /* tp_as_sequence */ + &proxy_as_mapping, /* tp_as_mapping */ + 0, /* tp_hash */ + 0, /* tp_call */ proxy_str, /* tp_str */ proxy_getattr, /* tp_getattro */ (setattrofunc)proxy_setattr, /* tp_setattro */ - 0, /* tp_as_buffer */ + 0, /* tp_as_buffer */ Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC, /* tp_flags */ 0, /* tp_doc */ (traverseproc)gc_traverse, /* tp_traverse */ @@ -677,7 +677,7 @@ 0, /* tp_weaklistoffset */ (getiterfunc)proxy_iter, /* tp_iter */ (iternextfunc)proxy_iternext, /* tp_iternext */ - proxy_methods, /* tp_methods */ + proxy_methods, /* tp_methods */ }; @@ -689,20 +689,20 @@ 0, /* methods */ (destructor)proxy_dealloc, /* tp_dealloc */ - 0, /* tp_print */ - 0, /* tp_getattr */ - 0, /* tp_setattr */ - 0, /* tp_reserved */ - (unaryfunc)proxy_repr, /* tp_repr */ - &proxy_as_number, /* tp_as_number */ - &proxy_as_sequence, /* tp_as_sequence */ - &proxy_as_mapping, /* tp_as_mapping */ - 0, /* tp_hash */ - proxy_call, /* tp_call */ - proxy_str, /* tp_str */ + 0, /* tp_print */ + 0, /* tp_getattr */ + 0, /* tp_setattr */ + 0, /* tp_reserved */ + (unaryfunc)proxy_repr, /* tp_repr */ + &proxy_as_number, /* tp_as_number */ + &proxy_as_sequence, /* tp_as_sequence */ + &proxy_as_mapping, /* tp_as_mapping */ + 0, /* tp_hash */ + proxy_call, /* tp_call */ + proxy_str, /* tp_str */ proxy_getattr, /* tp_getattro */ (setattrofunc)proxy_setattr, /* tp_setattro */ - 0, /* tp_as_buffer */ + 0, /* tp_as_buffer */ Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC, /* tp_flags */ 0, /* tp_doc */ (traverseproc)gc_traverse, /* tp_traverse */ @@ -724,7 +724,7 @@ if (!PyType_SUPPORTS_WEAKREFS(Py_TYPE(ob))) { PyErr_Format(PyExc_TypeError, - "cannot create weak reference to '%s' object", + "cannot create weak reference to '%s' object", Py_TYPE(ob)->tp_name); return NULL; } @@ -783,7 +783,7 @@ if (!PyType_SUPPORTS_WEAKREFS(Py_TYPE(ob))) { PyErr_Format(PyExc_TypeError, - "cannot create weak reference to '%s' object", + "cannot create weak reference to '%s' object", Py_TYPE(ob)->tp_name); return NULL; } @@ -908,7 +908,7 @@ else { PyObject *tuple; Py_ssize_t i = 0; - + tuple = PyTuple_New(count * 2); if (tuple == NULL) { if (restore_error) Modified: python/branches/release31-maint/PC/VS7.1/make_buildinfo.c ============================================================================== --- python/branches/release31-maint/PC/VS7.1/make_buildinfo.c (original) +++ python/branches/release31-maint/PC/VS7.1/make_buildinfo.c Sun May 9 18:14:21 2010 @@ -21,72 +21,72 @@ int make_buildinfo2() { - struct _stat st; - HKEY hTortoise; - char command[500]; - DWORD type, size; - if (_stat(".svn", &st) < 0) - return 0; - /* Allow suppression of subwcrev.exe invocation if a no_subwcrev file is present. */ - if (_stat("no_subwcrev", &st) == 0) - return 0; - if (RegOpenKey(HKEY_LOCAL_MACHINE, "Software\\TortoiseSVN", &hTortoise) != ERROR_SUCCESS && - RegOpenKey(HKEY_CURRENT_USER, "Software\\TortoiseSVN", &hTortoise) != ERROR_SUCCESS) - /* Tortoise not installed */ - return 0; - command[0] = '"'; /* quote the path to the executable */ - size = sizeof(command) - 1; - if (RegQueryValueEx(hTortoise, "Directory", 0, &type, command+1, &size) != ERROR_SUCCESS || - type != REG_SZ) - /* Registry corrupted */ - return 0; - strcat(command, "bin\\subwcrev.exe"); - if (_stat(command+1, &st) < 0) - /* subwcrev.exe not part of the release */ - return 0; - strcat(command, "\" ..\\.. ..\\..\\Modules\\getbuildinfo.c getbuildinfo2.c"); - puts(command); fflush(stdout); - if (system(command) < 0) - return 0; - return 1; + struct _stat st; + HKEY hTortoise; + char command[500]; + DWORD type, size; + if (_stat(".svn", &st) < 0) + return 0; + /* Allow suppression of subwcrev.exe invocation if a no_subwcrev file is present. */ + if (_stat("no_subwcrev", &st) == 0) + return 0; + if (RegOpenKey(HKEY_LOCAL_MACHINE, "Software\\TortoiseSVN", &hTortoise) != ERROR_SUCCESS && + RegOpenKey(HKEY_CURRENT_USER, "Software\\TortoiseSVN", &hTortoise) != ERROR_SUCCESS) + /* Tortoise not installed */ + return 0; + command[0] = '"'; /* quote the path to the executable */ + size = sizeof(command) - 1; + if (RegQueryValueEx(hTortoise, "Directory", 0, &type, command+1, &size) != ERROR_SUCCESS || + type != REG_SZ) + /* Registry corrupted */ + return 0; + strcat(command, "bin\\subwcrev.exe"); + if (_stat(command+1, &st) < 0) + /* subwcrev.exe not part of the release */ + return 0; + strcat(command, "\" ..\\.. ..\\..\\Modules\\getbuildinfo.c getbuildinfo2.c"); + puts(command); fflush(stdout); + if (system(command) < 0) + return 0; + return 1; } int main(int argc, char*argv[]) { - char command[500] = "cl.exe -c -D_WIN32 -DUSE_DL_EXPORT -D_WINDOWS -DWIN32 -D_WINDLL "; - int do_unlink, result; - if (argc != 2) { - fprintf(stderr, "make_buildinfo $(ConfigurationName)\n"); - return EXIT_FAILURE; - } - if (strcmp(argv[1], "Release") == 0) { - strcat(command, "-MD "); - } - else if (strcmp(argv[1], "Debug") == 0) { - strcat(command, "-D_DEBUG -MDd "); - } - else if (strcmp(argv[1], "ReleaseItanium") == 0) { - strcat(command, "-MD /USECL:MS_ITANIUM "); - } - else if (strcmp(argv[1], "ReleaseAMD64") == 0) { - strcat(command, "-MD "); - strcat(command, "-MD /USECL:MS_OPTERON "); - } - else { - fprintf(stderr, "unsupported configuration %s\n", argv[1]); - return EXIT_FAILURE; - } + char command[500] = "cl.exe -c -D_WIN32 -DUSE_DL_EXPORT -D_WINDOWS -DWIN32 -D_WINDLL "; + int do_unlink, result; + if (argc != 2) { + fprintf(stderr, "make_buildinfo $(ConfigurationName)\n"); + return EXIT_FAILURE; + } + if (strcmp(argv[1], "Release") == 0) { + strcat(command, "-MD "); + } + else if (strcmp(argv[1], "Debug") == 0) { + strcat(command, "-D_DEBUG -MDd "); + } + else if (strcmp(argv[1], "ReleaseItanium") == 0) { + strcat(command, "-MD /USECL:MS_ITANIUM "); + } + else if (strcmp(argv[1], "ReleaseAMD64") == 0) { + strcat(command, "-MD "); + strcat(command, "-MD /USECL:MS_OPTERON "); + } + else { + fprintf(stderr, "unsupported configuration %s\n", argv[1]); + return EXIT_FAILURE; + } - if ((do_unlink = make_buildinfo2())) - strcat(command, "getbuildinfo2.c -DSUBWCREV "); - else - strcat(command, "..\\..\\Modules\\getbuildinfo.c"); - strcat(command, " -Fogetbuildinfo.o -I..\\..\\Include -I..\\..\\PC"); - puts(command); fflush(stdout); - result = system(command); - if (do_unlink) - unlink("getbuildinfo2.c"); - if (result < 0) - return EXIT_FAILURE; - return 0; + if ((do_unlink = make_buildinfo2())) + strcat(command, "getbuildinfo2.c -DSUBWCREV "); + else + strcat(command, "..\\..\\Modules\\getbuildinfo.c"); + strcat(command, " -Fogetbuildinfo.o -I..\\..\\Include -I..\\..\\PC"); + puts(command); fflush(stdout); + result = system(command); + if (do_unlink) + unlink("getbuildinfo2.c"); + if (result < 0) + return EXIT_FAILURE; + return 0; } Modified: python/branches/release31-maint/PC/VS8.0/make_buildinfo.c ============================================================================== --- python/branches/release31-maint/PC/VS8.0/make_buildinfo.c (original) +++ python/branches/release31-maint/PC/VS8.0/make_buildinfo.c Sun May 9 18:14:21 2010 @@ -23,72 +23,72 @@ int make_buildinfo2() { - struct _stat st; - HKEY hTortoise; - char command[CMD_SIZE+1]; - DWORD type, size; - if (_stat(".svn", &st) < 0) - return 0; - /* Allow suppression of subwcrev.exe invocation if a no_subwcrev file is present. */ - if (_stat("no_subwcrev", &st) == 0) - return 0; - if (RegOpenKey(HKEY_LOCAL_MACHINE, "Software\\TortoiseSVN", &hTortoise) != ERROR_SUCCESS && - RegOpenKey(HKEY_CURRENT_USER, "Software\\TortoiseSVN", &hTortoise) != ERROR_SUCCESS) - /* Tortoise not installed */ - return 0; - command[0] = '"'; /* quote the path to the executable */ - size = sizeof(command) - 1; - if (RegQueryValueEx(hTortoise, "Directory", 0, &type, command+1, &size) != ERROR_SUCCESS || - type != REG_SZ) - /* Registry corrupted */ - return 0; - strcat_s(command, CMD_SIZE, "bin\\subwcrev.exe"); - if (_stat(command+1, &st) < 0) - /* subwcrev.exe not part of the release */ - return 0; - strcat_s(command, CMD_SIZE, "\" ..\\.. ..\\..\\Modules\\getbuildinfo.c getbuildinfo2.c"); - puts(command); fflush(stdout); - if (system(command) < 0) - return 0; - return 1; + struct _stat st; + HKEY hTortoise; + char command[CMD_SIZE+1]; + DWORD type, size; + if (_stat(".svn", &st) < 0) + return 0; + /* Allow suppression of subwcrev.exe invocation if a no_subwcrev file is present. */ + if (_stat("no_subwcrev", &st) == 0) + return 0; + if (RegOpenKey(HKEY_LOCAL_MACHINE, "Software\\TortoiseSVN", &hTortoise) != ERROR_SUCCESS && + RegOpenKey(HKEY_CURRENT_USER, "Software\\TortoiseSVN", &hTortoise) != ERROR_SUCCESS) + /* Tortoise not installed */ + return 0; + command[0] = '"'; /* quote the path to the executable */ + size = sizeof(command) - 1; + if (RegQueryValueEx(hTortoise, "Directory", 0, &type, command+1, &size) != ERROR_SUCCESS || + type != REG_SZ) + /* Registry corrupted */ + return 0; + strcat_s(command, CMD_SIZE, "bin\\subwcrev.exe"); + if (_stat(command+1, &st) < 0) + /* subwcrev.exe not part of the release */ + return 0; + strcat_s(command, CMD_SIZE, "\" ..\\.. ..\\..\\Modules\\getbuildinfo.c getbuildinfo2.c"); + puts(command); fflush(stdout); + if (system(command) < 0) + return 0; + return 1; } int main(int argc, char*argv[]) { - char command[500] = "cl.exe -c -D_WIN32 -DUSE_DL_EXPORT -D_WINDOWS -DWIN32 -D_WINDLL "; - int do_unlink, result; - if (argc != 2) { - fprintf(stderr, "make_buildinfo $(ConfigurationName)\n"); - return EXIT_FAILURE; - } - if (strcmp(argv[1], "Release") == 0) { - strcat_s(command, CMD_SIZE, "-MD "); - } - else if (strcmp(argv[1], "Debug") == 0) { - strcat_s(command, CMD_SIZE, "-D_DEBUG -MDd "); - } - else if (strcmp(argv[1], "ReleaseItanium") == 0) { - strcat_s(command, CMD_SIZE, "-MD /USECL:MS_ITANIUM "); - } - else if (strcmp(argv[1], "ReleaseAMD64") == 0) { - strcat_s(command, CMD_SIZE, "-MD "); - strcat_s(command, CMD_SIZE, "-MD /USECL:MS_OPTERON "); - } - else { - fprintf(stderr, "unsupported configuration %s\n", argv[1]); - return EXIT_FAILURE; - } + char command[500] = "cl.exe -c -D_WIN32 -DUSE_DL_EXPORT -D_WINDOWS -DWIN32 -D_WINDLL "; + int do_unlink, result; + if (argc != 2) { + fprintf(stderr, "make_buildinfo $(ConfigurationName)\n"); + return EXIT_FAILURE; + } + if (strcmp(argv[1], "Release") == 0) { + strcat_s(command, CMD_SIZE, "-MD "); + } + else if (strcmp(argv[1], "Debug") == 0) { + strcat_s(command, CMD_SIZE, "-D_DEBUG -MDd "); + } + else if (strcmp(argv[1], "ReleaseItanium") == 0) { + strcat_s(command, CMD_SIZE, "-MD /USECL:MS_ITANIUM "); + } + else if (strcmp(argv[1], "ReleaseAMD64") == 0) { + strcat_s(command, CMD_SIZE, "-MD "); + strcat_s(command, CMD_SIZE, "-MD /USECL:MS_OPTERON "); + } + else { + fprintf(stderr, "unsupported configuration %s\n", argv[1]); + return EXIT_FAILURE; + } - if ((do_unlink = make_buildinfo2())) - strcat_s(command, CMD_SIZE, "getbuildinfo2.c -DSUBWCREV "); - else - strcat_s(command, CMD_SIZE, "..\\..\\Modules\\getbuildinfo.c"); - strcat_s(command, CMD_SIZE, " -Fogetbuildinfo.o -I..\\..\\Include -I..\\..\\PC"); - puts(command); fflush(stdout); - result = system(command); - if (do_unlink) - _unlink("getbuildinfo2.c"); - if (result < 0) - return EXIT_FAILURE; - return 0; -} \ No newline at end of file + if ((do_unlink = make_buildinfo2())) + strcat_s(command, CMD_SIZE, "getbuildinfo2.c -DSUBWCREV "); + else + strcat_s(command, CMD_SIZE, "..\\..\\Modules\\getbuildinfo.c"); + strcat_s(command, CMD_SIZE, " -Fogetbuildinfo.o -I..\\..\\Include -I..\\..\\PC"); + puts(command); fflush(stdout); + result = system(command); + if (do_unlink) + _unlink("getbuildinfo2.c"); + if (result < 0) + return EXIT_FAILURE; + return 0; +} Modified: python/branches/release31-maint/PC/_msi.c ============================================================================== --- python/branches/release31-maint/PC/_msi.c (original) +++ python/branches/release31-maint/PC/_msi.c Sun May 9 18:14:21 2010 @@ -20,19 +20,19 @@ UUID result; unsigned short *cresult; PyObject *oresult; - + /* May return ok, local only, and no address. For local only, the documentation says we still get a uuid. For RPC_S_UUID_NO_ADDRESS, it's not clear whether we can use the result. */ if (UuidCreate(&result) == RPC_S_UUID_NO_ADDRESS) { - PyErr_SetString(PyExc_NotImplementedError, "processing 'no address' result"); - return NULL; + PyErr_SetString(PyExc_NotImplementedError, "processing 'no address' result"); + return NULL; } if (UuidToStringW(&result, &cresult) == RPC_S_OUT_OF_MEMORY) { - PyErr_SetString(PyExc_MemoryError, "out of memory in uuidgen"); - return NULL; + PyErr_SetString(PyExc_MemoryError, "out of memory in uuidgen"); + return NULL; } oresult = PyUnicode_FromUnicode(cresult, wcslen(cresult)); @@ -57,7 +57,7 @@ { int result = _open(pszFile, oflag, pmode); if (result == -1) - *err = errno; + *err = errno; return result; } @@ -65,7 +65,7 @@ { UINT result = (UINT)_read(hf, memory, cb); if (result != cb) - *err = errno; + *err = errno; return result; } @@ -73,7 +73,7 @@ { UINT result = (UINT)_write(hf, memory, cb); if (result != cb) - *err = errno; + *err = errno; return result; } @@ -81,7 +81,7 @@ { int result = _close(hf); if (result != 0) - *err = errno; + *err = errno; return result; } @@ -89,7 +89,7 @@ { long result = (long)_lseek(hf, dist, seektype); if (result == -1) - *err = errno; + *err = errno; return result; } @@ -97,7 +97,7 @@ { int result = remove(pszFile); if (result != 0) - *err = errno; + *err = errno; return result; } @@ -110,9 +110,9 @@ { char *name = _tempnam("", "tmp"); if ((name != NULL) && ((int)strlen(name) < cbTempName)) { - strcpy(pszTempName, name); - free(name); - return TRUE; + strcpy(pszTempName, name); + free(name); + return TRUE; } if (name) free(name); @@ -122,10 +122,10 @@ static FNFCISTATUS(cb_status) { if (pv) { - PyObject *result = PyObject_CallMethod(pv, "status", "iii", typeStatus, cb1, cb2); - if (result == NULL) - return -1; - Py_DECREF(result); + PyObject *result = PyObject_CallMethod(pv, "status", "iii", typeStatus, cb1, cb2); + if (result == NULL) + return -1; + Py_DECREF(result); } return 0; } @@ -133,18 +133,18 @@ static FNFCIGETNEXTCABINET(cb_getnextcabinet) { if (pv) { - PyObject *result = PyObject_CallMethod(pv, "getnextcabinet", "i", pccab->iCab); - if (result == NULL) - return -1; - if (!PyBytes_Check(result)) { - PyErr_Format(PyExc_TypeError, - "Incorrect return type %s from getnextcabinet", - result->ob_type->tp_name); - Py_DECREF(result); - return FALSE; - } - strncpy(pccab->szCab, PyBytes_AsString(result), sizeof(pccab->szCab)); - return TRUE; + PyObject *result = PyObject_CallMethod(pv, "getnextcabinet", "i", pccab->iCab); + if (result == NULL) + return -1; + if (!PyBytes_Check(result)) { + PyErr_Format(PyExc_TypeError, + "Incorrect return type %s from getnextcabinet", + result->ob_type->tp_name); + Py_DECREF(result); + return FALSE; + } + strncpy(pccab->szCab, PyBytes_AsString(result), sizeof(pccab->szCab)); + return TRUE; } return FALSE; } @@ -157,21 +157,21 @@ /* Need Win32 handle to get time stamps */ handle = CreateFile(pszName, GENERIC_READ, FILE_SHARE_READ, NULL, - OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL); + OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL); if (handle == INVALID_HANDLE_VALUE) - return -1; + return -1; if (GetFileInformationByHandle(handle, &bhfi) == FALSE) { - CloseHandle(handle); - return -1; + CloseHandle(handle); + return -1; } FileTimeToLocalFileTime(&bhfi.ftLastWriteTime, &filetime); FileTimeToDosDateTime(&filetime, pdate, ptime); - *pattribs = (int)(bhfi.dwFileAttributes & - (_A_RDONLY | _A_SYSTEM | _A_HIDDEN | _A_ARCH)); + *pattribs = (int)(bhfi.dwFileAttributes & + (_A_RDONLY | _A_SYSTEM | _A_HIDDEN | _A_ARCH)); CloseHandle(handle); @@ -189,11 +189,11 @@ if (!PyArg_ParseTuple(args, "sO:FCICreate", &cabname, &files)) - return NULL; + return NULL; if (!PyList_Check(files)) { - PyErr_SetString(PyExc_TypeError, "FCICreate expects a list"); - return NULL; + PyErr_SetString(PyExc_TypeError, "FCICreate expects a list"); + return NULL; } ccab.cb = INT_MAX; /* no need to split CAB into multiple media */ @@ -209,49 +209,49 @@ ccab.szDisk[0] = '\0'; for (i = 0, p = cabname; *p; p = CharNext(p)) - if (*p == '\\' || *p == '/') - i = p - cabname + 1; + if (*p == '\\' || *p == '/') + i = p - cabname + 1; if (i >= sizeof(ccab.szCabPath) || - strlen(cabname+i) >= sizeof(ccab.szCab)) { - PyErr_SetString(PyExc_ValueError, "path name too long"); - return 0; + strlen(cabname+i) >= sizeof(ccab.szCab)) { + PyErr_SetString(PyExc_ValueError, "path name too long"); + return 0; } if (i > 0) { - memcpy(ccab.szCabPath, cabname, i); - ccab.szCabPath[i] = '\0'; - strcpy(ccab.szCab, cabname+i); + memcpy(ccab.szCabPath, cabname, i); + ccab.szCabPath[i] = '\0'; + strcpy(ccab.szCab, cabname+i); } else { - strcpy(ccab.szCabPath, ".\\"); - strcpy(ccab.szCab, cabname); + strcpy(ccab.szCabPath, ".\\"); + strcpy(ccab.szCab, cabname); } hfci = FCICreate(&erf, cb_fileplaced, cb_alloc, cb_free, - cb_open, cb_read, cb_write, cb_close, cb_seek, cb_delete, - cb_gettempfile, &ccab, NULL); + cb_open, cb_read, cb_write, cb_close, cb_seek, cb_delete, + cb_gettempfile, &ccab, NULL); if (hfci == NULL) { - PyErr_Format(PyExc_ValueError, "FCI error %d", erf.erfOper); - return NULL; + PyErr_Format(PyExc_ValueError, "FCI error %d", erf.erfOper); + return NULL; } for (i=0; i < PyList_GET_SIZE(files); i++) { - PyObject *item = PyList_GET_ITEM(files, i); - char *filename, *cabname; - if (!PyArg_ParseTuple(item, "ss", &filename, &cabname)) - goto err; - if (!FCIAddFile(hfci, filename, cabname, FALSE, - cb_getnextcabinet, cb_status, cb_getopeninfo, - tcompTYPE_MSZIP)) - goto err; + PyObject *item = PyList_GET_ITEM(files, i); + char *filename, *cabname; + if (!PyArg_ParseTuple(item, "ss", &filename, &cabname)) + goto err; + if (!FCIAddFile(hfci, filename, cabname, FALSE, + cb_getnextcabinet, cb_status, cb_getopeninfo, + tcompTYPE_MSZIP)) + goto err; } if (!FCIFlushCabinet(hfci, FALSE, cb_getnextcabinet, cb_status)) - goto err; + goto err; if (!FCIDestroy(hfci)) - goto err; + goto err; Py_INCREF(Py_None); return Py_None; @@ -266,7 +266,7 @@ MSIHANDLE h; }msiobj; -static void +static void msiobj_dealloc(msiobj* msidb) { MsiCloseHandle(msidb->h); @@ -292,41 +292,41 @@ MSIHANDLE err = MsiGetLastErrorRecord(); if (err == 0) { - switch(status) { - case ERROR_ACCESS_DENIED: - PyErr_SetString(MSIError, "access denied"); - return NULL; - case ERROR_FUNCTION_FAILED: - PyErr_SetString(MSIError, "function failed"); - return NULL; - case ERROR_INVALID_DATA: - PyErr_SetString(MSIError, "invalid data"); - return NULL; - case ERROR_INVALID_HANDLE: - PyErr_SetString(MSIError, "invalid handle"); - return NULL; - case ERROR_INVALID_STATE: - PyErr_SetString(MSIError, "invalid state"); - return NULL; - case ERROR_INVALID_PARAMETER: - PyErr_SetString(MSIError, "invalid parameter"); - return NULL; - default: - PyErr_Format(MSIError, "unknown error %x", status); - return NULL; - } + switch(status) { + case ERROR_ACCESS_DENIED: + PyErr_SetString(MSIError, "access denied"); + return NULL; + case ERROR_FUNCTION_FAILED: + PyErr_SetString(MSIError, "function failed"); + return NULL; + case ERROR_INVALID_DATA: + PyErr_SetString(MSIError, "invalid data"); + return NULL; + case ERROR_INVALID_HANDLE: + PyErr_SetString(MSIError, "invalid handle"); + return NULL; + case ERROR_INVALID_STATE: + PyErr_SetString(MSIError, "invalid state"); + return NULL; + case ERROR_INVALID_PARAMETER: + PyErr_SetString(MSIError, "invalid parameter"); + return NULL; + default: + PyErr_Format(MSIError, "unknown error %x", status); + return NULL; + } } code = MsiRecordGetInteger(err, 1); /* XXX code */ if (MsiFormatRecord(0, err, res, &size) == ERROR_MORE_DATA) { - res = malloc(size+1); - MsiFormatRecord(0, err, res, &size); - res[size]='\0'; + res = malloc(size+1); + MsiFormatRecord(0, err, res, &size); + res[size]='\0'; } MsiCloseHandle(err); PyErr_SetString(MSIError, res); if (res != buf) - free(res); + free(res); return NULL; } @@ -343,7 +343,7 @@ { unsigned int field; int status; - + if (!PyArg_ParseTuple(args, "I:GetInteger", &field)) return NULL; status = MsiRecordGetInteger(record->h, field); @@ -363,7 +363,7 @@ WCHAR *res = buf; DWORD size = sizeof(buf); PyObject* string; - + if (!PyArg_ParseTuple(args, "I:GetString", &field)) return NULL; status = MsiRecordGetStringW(record->h, field, res, &size); @@ -386,7 +386,7 @@ { int status = MsiRecordClearData(record->h); if (status != ERROR_SUCCESS) - return msierror(status); + return msierror(status); Py_INCREF(Py_None); return Py_None; @@ -400,10 +400,10 @@ Py_UNICODE *data; if (!PyArg_ParseTuple(args, "iu:SetString", &field, &data)) - return NULL; + return NULL; if ((status = MsiRecordSetStringW(record->h, field, data)) != ERROR_SUCCESS) - return msierror(status); + return msierror(status); Py_INCREF(Py_None); return Py_None; @@ -417,10 +417,10 @@ Py_UNICODE *data; if (!PyArg_ParseTuple(args, "iu:SetStream", &field, &data)) - return NULL; + return NULL; if ((status = MsiRecordSetStreamW(record->h, field, data)) != ERROR_SUCCESS) - return msierror(status); + return msierror(status); Py_INCREF(Py_None); return Py_None; @@ -434,10 +434,10 @@ int data; if (!PyArg_ParseTuple(args, "ii:SetInteger", &field, &data)) - return NULL; + return NULL; if ((status = MsiRecordSetInteger(record->h, field, data)) != ERROR_SUCCESS) - return msierror(status); + return msierror(status); Py_INCREF(Py_None); return Py_None; @@ -446,39 +446,39 @@ static PyMethodDef record_methods[] = { - { "GetFieldCount", (PyCFunction)record_getfieldcount, METH_NOARGS, - PyDoc_STR("GetFieldCount() -> int\nWraps MsiRecordGetFieldCount")}, + { "GetFieldCount", (PyCFunction)record_getfieldcount, METH_NOARGS, + PyDoc_STR("GetFieldCount() -> int\nWraps MsiRecordGetFieldCount")}, { "GetInteger", (PyCFunction)record_getinteger, METH_VARARGS, PyDoc_STR("GetInteger(field) -> int\nWraps MsiRecordGetInteger")}, { "GetString", (PyCFunction)record_getstring, METH_VARARGS, PyDoc_STR("GetString(field) -> string\nWraps MsiRecordGetString")}, - { "SetString", (PyCFunction)record_setstring, METH_VARARGS, - PyDoc_STR("SetString(field,str) -> None\nWraps MsiRecordSetString")}, - { "SetStream", (PyCFunction)record_setstream, METH_VARARGS, - PyDoc_STR("SetStream(field,filename) -> None\nWraps MsiRecordSetInteger")}, - { "SetInteger", (PyCFunction)record_setinteger, METH_VARARGS, - PyDoc_STR("SetInteger(field,int) -> None\nWraps MsiRecordSetInteger")}, - { "ClearData", (PyCFunction)record_cleardata, METH_NOARGS, - PyDoc_STR("ClearData() -> int\nWraps MsiRecordGClearData")}, + { "SetString", (PyCFunction)record_setstring, METH_VARARGS, + PyDoc_STR("SetString(field,str) -> None\nWraps MsiRecordSetString")}, + { "SetStream", (PyCFunction)record_setstream, METH_VARARGS, + PyDoc_STR("SetStream(field,filename) -> None\nWraps MsiRecordSetInteger")}, + { "SetInteger", (PyCFunction)record_setinteger, METH_VARARGS, + PyDoc_STR("SetInteger(field,int) -> None\nWraps MsiRecordSetInteger")}, + { "ClearData", (PyCFunction)record_cleardata, METH_NOARGS, + PyDoc_STR("ClearData() -> int\nWraps MsiRecordGClearData")}, { NULL, NULL } }; static PyTypeObject record_Type = { - PyVarObject_HEAD_INIT(NULL, 0) - "_msi.Record", /*tp_name*/ - sizeof(msiobj), /*tp_basicsize*/ - 0, /*tp_itemsize*/ - /* methods */ - (destructor)msiobj_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*/ + PyVarObject_HEAD_INIT(NULL, 0) + "_msi.Record", /*tp_name*/ + sizeof(msiobj), /*tp_basicsize*/ + 0, /*tp_itemsize*/ + /* methods */ + (destructor)msiobj_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*/ @@ -513,8 +513,8 @@ msiobj *result = PyObject_NEW(struct msiobj, &record_Type); if (!result) { - MsiCloseHandle(h); - return NULL; + MsiCloseHandle(h); + return NULL; } result->h = h; @@ -537,27 +537,27 @@ DWORD ssize = sizeof(sval); if (!PyArg_ParseTuple(args, "i:GetProperty", &field)) - return NULL; + return NULL; - status = MsiSummaryInfoGetProperty(si->h, field, &type, &ival, - &fval, sval, &ssize); + status = MsiSummaryInfoGetProperty(si->h, field, &type, &ival, + &fval, sval, &ssize); if (status == ERROR_MORE_DATA) { - sval = malloc(ssize); - status = MsiSummaryInfoGetProperty(si->h, field, &type, &ival, - &fval, sval, &ssize); + sval = malloc(ssize); + status = MsiSummaryInfoGetProperty(si->h, field, &type, &ival, + &fval, sval, &ssize); } switch(type) { - case VT_I2: case VT_I4: - return PyLong_FromLong(ival); - case VT_FILETIME: - PyErr_SetString(PyExc_NotImplementedError, "FILETIME result"); - return NULL; - case VT_LPSTR: - result = PyBytes_FromStringAndSize(sval, ssize); - if (sval != sbuf) - free(sval); - return result; + case VT_I2: case VT_I4: + return PyLong_FromLong(ival); + case VT_FILETIME: + PyErr_SetString(PyExc_NotImplementedError, "FILETIME result"); + return NULL; + case VT_LPSTR: + result = PyBytes_FromStringAndSize(sval, ssize); + if (sval != sbuf) + free(sval); + return result; } PyErr_Format(PyExc_NotImplementedError, "result of type %d", type); return NULL; @@ -571,7 +571,7 @@ status = MsiSummaryInfoGetPropertyCount(si->h, &result); if (status != ERROR_SUCCESS) - return msierror(status); + return msierror(status); return PyLong_FromLong(result); } @@ -584,25 +584,25 @@ PyObject* data; if (!PyArg_ParseTuple(args, "iO:SetProperty", &field, &data)) - return NULL; + return NULL; if (PyUnicode_Check(data)) { - status = MsiSummaryInfoSetPropertyW(si->h, field, VT_LPSTR, - 0, NULL, PyUnicode_AsUnicode(data)); + status = MsiSummaryInfoSetPropertyW(si->h, field, VT_LPSTR, + 0, NULL, PyUnicode_AsUnicode(data)); } else if (PyLong_CheckExact(data)) { - long value = PyLong_AsLong(data); - if (value == -1 && PyErr_Occurred()) { - return NULL; - } - status = MsiSummaryInfoSetProperty(si->h, field, VT_I4, - value, NULL, NULL); + long value = PyLong_AsLong(data); + if (value == -1 && PyErr_Occurred()) { + return NULL; + } + status = MsiSummaryInfoSetProperty(si->h, field, VT_I4, + value, NULL, NULL); } else { - PyErr_SetString(PyExc_TypeError, "unsupported type"); - return NULL; + PyErr_SetString(PyExc_TypeError, "unsupported type"); + return NULL; } - + if (status != ERROR_SUCCESS) - return msierror(status); + return msierror(status); Py_INCREF(Py_None); return Py_None; @@ -616,39 +616,39 @@ status = MsiSummaryInfoPersist(si->h); if (status != ERROR_SUCCESS) - return msierror(status); + return msierror(status); Py_INCREF(Py_None); return Py_None; } static PyMethodDef summary_methods[] = { - { "GetProperty", (PyCFunction)summary_getproperty, METH_VARARGS, - PyDoc_STR("GetProperty(propid) -> value\nWraps MsiSummaryInfoGetProperty")}, - { "GetPropertyCount", (PyCFunction)summary_getpropertycount, METH_NOARGS, - PyDoc_STR("GetProperty() -> int\nWraps MsiSummaryInfoGetPropertyCount")}, - { "SetProperty", (PyCFunction)summary_setproperty, METH_VARARGS, - PyDoc_STR("SetProperty(value) -> None\nWraps MsiSummaryInfoProperty")}, - { "Persist", (PyCFunction)summary_persist, METH_NOARGS, - PyDoc_STR("Persist() -> None\nWraps MsiSummaryInfoPersist")}, + { "GetProperty", (PyCFunction)summary_getproperty, METH_VARARGS, + PyDoc_STR("GetProperty(propid) -> value\nWraps MsiSummaryInfoGetProperty")}, + { "GetPropertyCount", (PyCFunction)summary_getpropertycount, METH_NOARGS, + PyDoc_STR("GetProperty() -> int\nWraps MsiSummaryInfoGetPropertyCount")}, + { "SetProperty", (PyCFunction)summary_setproperty, METH_VARARGS, + PyDoc_STR("SetProperty(value) -> None\nWraps MsiSummaryInfoProperty")}, + { "Persist", (PyCFunction)summary_persist, METH_NOARGS, + PyDoc_STR("Persist() -> None\nWraps MsiSummaryInfoPersist")}, { NULL, NULL } }; static PyTypeObject summary_Type = { - PyVarObject_HEAD_INIT(NULL, 0) - "_msi.SummaryInformation", /*tp_name*/ - sizeof(msiobj), /*tp_basicsize*/ - 0, /*tp_itemsize*/ - /* methods */ - (destructor)msiobj_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*/ + PyVarObject_HEAD_INIT(NULL, 0) + "_msi.SummaryInformation", /*tp_name*/ + sizeof(msiobj), /*tp_basicsize*/ + 0, /*tp_itemsize*/ + /* methods */ + (destructor)msiobj_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*/ @@ -687,7 +687,7 @@ PyObject *oparams = Py_None; if (!PyArg_ParseTuple(args, "O:Execute", &oparams)) - return NULL; + return NULL; if (oparams != Py_None) { if (oparams->ob_type != &record_Type) { @@ -699,7 +699,7 @@ status = MsiViewExecute(view->h, params); if (status != ERROR_SUCCESS) - return msierror(status); + return msierror(status); Py_INCREF(Py_None); return Py_None; @@ -712,7 +712,7 @@ MSIHANDLE result; if ((status = MsiViewFetch(view->h, &result)) != ERROR_SUCCESS) - return msierror(status); + return msierror(status); return record_new(result); } @@ -725,10 +725,10 @@ MSIHANDLE result; if (!PyArg_ParseTuple(args, "i:GetColumnInfo", &kind)) - return NULL; + return NULL; if ((status = MsiViewGetColumnInfo(view->h, kind, &result)) != ERROR_SUCCESS) - return msierror(status); + return msierror(status); return record_new(result); } @@ -741,15 +741,15 @@ int status; if (!PyArg_ParseTuple(args, "iO:Modify", &kind, &data)) - return NULL; + return NULL; if (data->ob_type != &record_Type) { - PyErr_SetString(PyExc_TypeError, "Modify expects a record object"); - return NULL; + PyErr_SetString(PyExc_TypeError, "Modify expects a record object"); + return NULL; } if ((status = MsiViewModify(view->h, kind, ((msiobj*)data)->h)) != ERROR_SUCCESS) - return msierror(status); + return msierror(status); Py_INCREF(Py_None); return Py_None; @@ -761,42 +761,42 @@ int status; if ((status = MsiViewClose(view->h)) != ERROR_SUCCESS) - return msierror(status); + return msierror(status); Py_INCREF(Py_None); return Py_None; } static PyMethodDef view_methods[] = { - { "Execute", (PyCFunction)view_execute, METH_VARARGS, - PyDoc_STR("Execute(params=None) -> None\nWraps MsiViewExecute")}, + { "Execute", (PyCFunction)view_execute, METH_VARARGS, + PyDoc_STR("Execute(params=None) -> None\nWraps MsiViewExecute")}, { "GetColumnInfo", (PyCFunction)view_getcolumninfo, METH_VARARGS, - PyDoc_STR("GetColumnInfo() -> result\nWraps MsiGetColumnInfo")}, + PyDoc_STR("GetColumnInfo() -> result\nWraps MsiGetColumnInfo")}, { "Fetch", (PyCFunction)view_fetch, METH_NOARGS, - PyDoc_STR("Fetch() -> result\nWraps MsiViewFetch")}, + PyDoc_STR("Fetch() -> result\nWraps MsiViewFetch")}, { "Modify", (PyCFunction)view_modify, METH_VARARGS, - PyDoc_STR("Modify(mode,record) -> None\nWraps MsiViewModify")}, + PyDoc_STR("Modify(mode,record) -> None\nWraps MsiViewModify")}, { "Close", (PyCFunction)view_close, METH_NOARGS, - PyDoc_STR("Close() -> result\nWraps MsiViewClose")}, + PyDoc_STR("Close() -> result\nWraps MsiViewClose")}, { NULL, NULL } }; static PyTypeObject msiview_Type = { - PyVarObject_HEAD_INIT(NULL, 0) - "_msi.View", /*tp_name*/ - sizeof(msiobj), /*tp_basicsize*/ - 0, /*tp_itemsize*/ - /* methods */ - (destructor)msiobj_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*/ + PyVarObject_HEAD_INIT(NULL, 0) + "_msi.View", /*tp_name*/ + sizeof(msiobj), /*tp_basicsize*/ + 0, /*tp_itemsize*/ + /* methods */ + (destructor)msiobj_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*/ @@ -836,15 +836,15 @@ msiobj *result; if (!PyArg_ParseTuple(args, "s:OpenView", &sql)) - return NULL; + return NULL; if ((status = MsiDatabaseOpenView(msidb->h, sql, &hView)) != ERROR_SUCCESS) - return msierror(status); + return msierror(status); result = PyObject_NEW(struct msiobj, &msiview_Type); if (!result) { - MsiCloseHandle(hView); - return NULL; + MsiCloseHandle(hView); + return NULL; } result->h = hView; @@ -857,7 +857,7 @@ int status; if ((status = MsiDatabaseCommit(msidb->h)) != ERROR_SUCCESS) - return msierror(status); + return msierror(status); Py_INCREF(Py_None); return Py_None; @@ -872,16 +872,16 @@ msiobj *oresult; if (!PyArg_ParseTuple(args, "i:GetSummaryInformation", &count)) - return NULL; + return NULL; status = MsiGetSummaryInformation(db->h, NULL, count, &result); if (status != ERROR_SUCCESS) - return msierror(status); + return msierror(status); oresult = PyObject_NEW(struct msiobj, &summary_Type); if (!result) { - MsiCloseHandle(result); - return NULL; + MsiCloseHandle(result); + return NULL; } oresult->h = result; @@ -889,31 +889,31 @@ } static PyMethodDef db_methods[] = { - { "OpenView", (PyCFunction)msidb_openview, METH_VARARGS, - PyDoc_STR("OpenView(sql) -> viewobj\nWraps MsiDatabaseOpenView")}, + { "OpenView", (PyCFunction)msidb_openview, METH_VARARGS, + PyDoc_STR("OpenView(sql) -> viewobj\nWraps MsiDatabaseOpenView")}, { "Commit", (PyCFunction)msidb_commit, METH_NOARGS, - PyDoc_STR("Commit() -> None\nWraps MsiDatabaseCommit")}, - { "GetSummaryInformation", (PyCFunction)msidb_getsummaryinformation, METH_VARARGS, - PyDoc_STR("GetSummaryInformation(updateCount) -> viewobj\nWraps MsiGetSummaryInformation")}, + PyDoc_STR("Commit() -> None\nWraps MsiDatabaseCommit")}, + { "GetSummaryInformation", (PyCFunction)msidb_getsummaryinformation, METH_VARARGS, + PyDoc_STR("GetSummaryInformation(updateCount) -> viewobj\nWraps MsiGetSummaryInformation")}, { NULL, NULL } }; static PyTypeObject msidb_Type = { - PyVarObject_HEAD_INIT(NULL, 0) - "_msi.Database", /*tp_name*/ - sizeof(msiobj), /*tp_basicsize*/ - 0, /*tp_itemsize*/ - /* methods */ - (destructor)msiobj_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*/ + PyVarObject_HEAD_INIT(NULL, 0) + "_msi.Database", /*tp_name*/ + sizeof(msiobj), /*tp_basicsize*/ + 0, /*tp_itemsize*/ + /* methods */ + (destructor)msiobj_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*/ @@ -949,18 +949,18 @@ int persist; MSIHANDLE h; msiobj *result; - + if (!PyArg_ParseTuple(args, "si:MSIOpenDatabase", &path, &persist)) - return NULL; + return NULL; - status = MsiOpenDatabase(path, (LPCSTR)persist, &h); + status = MsiOpenDatabase(path, (LPCSTR)persist, &h); if (status != ERROR_SUCCESS) - return msierror(status); + return msierror(status); result = PyObject_NEW(struct msiobj, &msidb_Type); if (!result) { - MsiCloseHandle(h); - return NULL; + MsiCloseHandle(h); + return NULL; } result->h = h; return (PyObject*)result; @@ -973,11 +973,11 @@ MSIHANDLE h; if (!PyArg_ParseTuple(args, "i:CreateRecord", &count)) - return NULL; - + return NULL; + h = MsiCreateRecord(count); if (h == 0) - return msierror(0); + return msierror(0); return record_new(h); } @@ -985,29 +985,29 @@ static PyMethodDef msi_methods[] = { {"UuidCreate", (PyCFunction)uuidcreate, METH_NOARGS, - PyDoc_STR("UuidCreate() -> string")}, - {"FCICreate", (PyCFunction)fcicreate, METH_VARARGS, - PyDoc_STR("fcicreate(cabname,files) -> None")}, - {"OpenDatabase", (PyCFunction)msiopendb, METH_VARARGS, - PyDoc_STR("OpenDatabase(name, flags) -> dbobj\nWraps MsiOpenDatabase")}, - {"CreateRecord", (PyCFunction)createrecord, METH_VARARGS, - PyDoc_STR("OpenDatabase(name, flags) -> dbobj\nWraps MsiCreateRecord")}, - {NULL, NULL} /* sentinel */ + PyDoc_STR("UuidCreate() -> string")}, + {"FCICreate", (PyCFunction)fcicreate, METH_VARARGS, + PyDoc_STR("fcicreate(cabname,files) -> None")}, + {"OpenDatabase", (PyCFunction)msiopendb, METH_VARARGS, + PyDoc_STR("OpenDatabase(name, flags) -> dbobj\nWraps MsiOpenDatabase")}, + {"CreateRecord", (PyCFunction)createrecord, METH_VARARGS, + PyDoc_STR("OpenDatabase(name, flags) -> dbobj\nWraps MsiCreateRecord")}, + {NULL, NULL} /* sentinel */ }; static char msi_doc[] = "Documentation"; static struct PyModuleDef _msimodule = { - PyModuleDef_HEAD_INIT, - "_msi", - msi_doc, - -1, - msi_methods, - NULL, - NULL, - NULL, - NULL + PyModuleDef_HEAD_INIT, + "_msi", + msi_doc, + -1, + msi_methods, + NULL, + NULL, + NULL, + NULL }; PyMODINIT_FUNC @@ -1017,7 +1017,7 @@ m = PyModule_Create(&_msimodule); if (m == NULL) - return NULL; + return NULL; PyModule_AddIntConstant(m, "MSIDBOPEN_CREATEDIRECT", (int)MSIDBOPEN_CREATEDIRECT); PyModule_AddIntConstant(m, "MSIDBOPEN_CREATE", (int)MSIDBOPEN_CREATE); @@ -1063,7 +1063,7 @@ MSIError = PyErr_NewException ("_msi.MSIError", NULL, NULL); if (!MSIError) - return NULL; + return NULL; PyModule_AddObject(m, "MSIError", MSIError); return m; } Modified: python/branches/release31-maint/PC/_subprocess.c ============================================================================== --- python/branches/release31-maint/PC/_subprocess.c (original) +++ python/branches/release31-maint/PC/_subprocess.c Sun May 9 18:14:21 2010 @@ -46,8 +46,8 @@ the wrapper is used to provide Detach and Close methods */ typedef struct { - PyObject_HEAD - HANDLE handle; + PyObject_HEAD + HANDLE handle; } sp_handle_object; static PyTypeObject sp_handle_type; @@ -55,104 +55,104 @@ static PyObject* sp_handle_new(HANDLE handle) { - sp_handle_object* self; + sp_handle_object* self; - self = PyObject_NEW(sp_handle_object, &sp_handle_type); - if (self == NULL) - return NULL; + self = PyObject_NEW(sp_handle_object, &sp_handle_type); + if (self == NULL) + return NULL; - self->handle = handle; + self->handle = handle; - return (PyObject*) self; + return (PyObject*) self; } #if defined(MS_WIN32) && !defined(MS_WIN64) -#define HANDLE_TO_PYNUM(handle) PyLong_FromLong((long) handle) -#define PY_HANDLE_PARAM "l" +#define HANDLE_TO_PYNUM(handle) PyLong_FromLong((long) handle) +#define PY_HANDLE_PARAM "l" #else -#define HANDLE_TO_PYNUM(handle) PyLong_FromLongLong((long long) handle) -#define PY_HANDLE_PARAM "L" +#define HANDLE_TO_PYNUM(handle) PyLong_FromLongLong((long long) handle) +#define PY_HANDLE_PARAM "L" #endif static PyObject* sp_handle_detach(sp_handle_object* self, PyObject* args) { - HANDLE handle; + HANDLE handle; - if (! PyArg_ParseTuple(args, ":Detach")) - return NULL; + if (! PyArg_ParseTuple(args, ":Detach")) + return NULL; - handle = self->handle; + handle = self->handle; - self->handle = INVALID_HANDLE_VALUE; + self->handle = INVALID_HANDLE_VALUE; - /* note: return the current handle, as an integer */ - return HANDLE_TO_PYNUM(handle); + /* note: return the current handle, as an integer */ + return HANDLE_TO_PYNUM(handle); } static PyObject* sp_handle_close(sp_handle_object* self, PyObject* args) { - if (! PyArg_ParseTuple(args, ":Close")) - return NULL; + if (! PyArg_ParseTuple(args, ":Close")) + return NULL; - if (self->handle != INVALID_HANDLE_VALUE) { - CloseHandle(self->handle); - self->handle = INVALID_HANDLE_VALUE; - } - Py_INCREF(Py_None); - return Py_None; + if (self->handle != INVALID_HANDLE_VALUE) { + CloseHandle(self->handle); + self->handle = INVALID_HANDLE_VALUE; + } + Py_INCREF(Py_None); + return Py_None; } static void sp_handle_dealloc(sp_handle_object* self) { - if (self->handle != INVALID_HANDLE_VALUE) - CloseHandle(self->handle); - PyObject_FREE(self); + if (self->handle != INVALID_HANDLE_VALUE) + CloseHandle(self->handle); + PyObject_FREE(self); } static PyMethodDef sp_handle_methods[] = { - {"Detach", (PyCFunction) sp_handle_detach, METH_VARARGS}, - {"Close", (PyCFunction) sp_handle_close, METH_VARARGS}, - {NULL, NULL} + {"Detach", (PyCFunction) sp_handle_detach, METH_VARARGS}, + {"Close", (PyCFunction) sp_handle_close, METH_VARARGS}, + {NULL, NULL} }; static PyObject* sp_handle_as_int(sp_handle_object* self) { - return HANDLE_TO_PYNUM(self->handle); + return HANDLE_TO_PYNUM(self->handle); } static PyNumberMethods sp_handle_as_number; static PyTypeObject sp_handle_type = { - PyVarObject_HEAD_INIT(NULL, 0) - "_subprocess_handle", sizeof(sp_handle_object), 0, - (destructor) sp_handle_dealloc, /*tp_dealloc*/ - 0, /*tp_print*/ - 0, /*tp_getattr*/ - 0, /*tp_setattr*/ - 0, /*tp_reserved*/ - 0, /*tp_repr*/ - &sp_handle_as_number, /*tp_as_number */ - 0, /*tp_as_sequence */ - 0, /*tp_as_mapping */ - 0, /*tp_hash*/ - 0, /*tp_call*/ - 0, /*tp_str*/ - 0, /*tp_getattro*/ - 0, /*tp_setattro*/ - 0, /*tp_as_buffer*/ - Py_TPFLAGS_DEFAULT, /*tp_flags*/ - 0, /*tp_doc*/ - 0, /*tp_traverse*/ - 0, /*tp_clear*/ - 0, /*tp_richcompare*/ - 0, /*tp_weaklistoffset*/ - 0, /*tp_iter*/ - 0, /*tp_iternext*/ - sp_handle_methods, /*tp_methods*/ + PyVarObject_HEAD_INIT(NULL, 0) + "_subprocess_handle", sizeof(sp_handle_object), 0, + (destructor) sp_handle_dealloc, /*tp_dealloc*/ + 0, /*tp_print*/ + 0, /*tp_getattr*/ + 0, /*tp_setattr*/ + 0, /*tp_reserved*/ + 0, /*tp_repr*/ + &sp_handle_as_number, /*tp_as_number */ + 0, /*tp_as_sequence */ + 0, /*tp_as_mapping */ + 0, /*tp_hash*/ + 0, /*tp_call*/ + 0, /*tp_str*/ + 0, /*tp_getattro*/ + 0, /*tp_setattro*/ + 0, /*tp_as_buffer*/ + Py_TPFLAGS_DEFAULT, /*tp_flags*/ + 0, /*tp_doc*/ + 0, /*tp_traverse*/ + 0, /*tp_clear*/ + 0, /*tp_richcompare*/ + 0, /*tp_weaklistoffset*/ + 0, /*tp_iter*/ + 0, /*tp_iternext*/ + sp_handle_methods, /*tp_methods*/ }; /* -------------------------------------------------------------------- */ @@ -168,26 +168,26 @@ static PyObject * sp_GetStdHandle(PyObject* self, PyObject* args) { - HANDLE handle; - int std_handle; + HANDLE handle; + int std_handle; - if (! PyArg_ParseTuple(args, "i:GetStdHandle", &std_handle)) - return NULL; + if (! PyArg_ParseTuple(args, "i:GetStdHandle", &std_handle)) + return NULL; - Py_BEGIN_ALLOW_THREADS - handle = GetStdHandle((DWORD) std_handle); - Py_END_ALLOW_THREADS - - if (handle == INVALID_HANDLE_VALUE) - return PyErr_SetFromWindowsErr(GetLastError()); - - if (! handle) { - Py_INCREF(Py_None); - return Py_None; - } + Py_BEGIN_ALLOW_THREADS + handle = GetStdHandle((DWORD) std_handle); + Py_END_ALLOW_THREADS + + if (handle == INVALID_HANDLE_VALUE) + return PyErr_SetFromWindowsErr(GetLastError()); + + if (! handle) { + Py_INCREF(Py_None); + return Py_None; + } - /* note: returns integer, not handle object */ - return HANDLE_TO_PYNUM(handle); + /* note: returns integer, not handle object */ + return HANDLE_TO_PYNUM(handle); } PyDoc_STRVAR(GetCurrentProcess_doc, @@ -198,10 +198,10 @@ static PyObject * sp_GetCurrentProcess(PyObject* self, PyObject* args) { - if (! PyArg_ParseTuple(args, ":GetCurrentProcess")) - return NULL; + if (! PyArg_ParseTuple(args, ":GetCurrentProcess")) + return NULL; - return sp_handle_new(GetCurrentProcess()); + return sp_handle_new(GetCurrentProcess()); } PyDoc_STRVAR(DuplicateHandle_doc, @@ -218,43 +218,43 @@ static PyObject * sp_DuplicateHandle(PyObject* self, PyObject* args) { - HANDLE target_handle; - BOOL result; + HANDLE target_handle; + BOOL result; - HANDLE source_process_handle; - HANDLE source_handle; - HANDLE target_process_handle; - int desired_access; - int inherit_handle; - int options = 0; - - if (! PyArg_ParseTuple(args, - PY_HANDLE_PARAM PY_HANDLE_PARAM PY_HANDLE_PARAM - "ii|i:DuplicateHandle", - &source_process_handle, - &source_handle, - &target_process_handle, - &desired_access, - &inherit_handle, - &options)) - return NULL; - - Py_BEGIN_ALLOW_THREADS - result = DuplicateHandle( - source_process_handle, - source_handle, - target_process_handle, - &target_handle, - desired_access, - inherit_handle, - options - ); - Py_END_ALLOW_THREADS + HANDLE source_process_handle; + HANDLE source_handle; + HANDLE target_process_handle; + int desired_access; + int inherit_handle; + int options = 0; + + if (! PyArg_ParseTuple(args, + PY_HANDLE_PARAM PY_HANDLE_PARAM PY_HANDLE_PARAM + "ii|i:DuplicateHandle", + &source_process_handle, + &source_handle, + &target_process_handle, + &desired_access, + &inherit_handle, + &options)) + return NULL; + + Py_BEGIN_ALLOW_THREADS + result = DuplicateHandle( + source_process_handle, + source_handle, + target_process_handle, + &target_handle, + desired_access, + inherit_handle, + options + ); + Py_END_ALLOW_THREADS - if (! result) - return PyErr_SetFromWindowsErr(GetLastError()); + if (! result) + return PyErr_SetFromWindowsErr(GetLastError()); - return sp_handle_new(target_handle); + return sp_handle_new(target_handle); } PyDoc_STRVAR(CreatePipe_doc, @@ -268,25 +268,25 @@ static PyObject * sp_CreatePipe(PyObject* self, PyObject* args) { - HANDLE read_pipe; - HANDLE write_pipe; - BOOL result; + HANDLE read_pipe; + HANDLE write_pipe; + BOOL result; - PyObject* pipe_attributes; /* ignored */ - int size; + PyObject* pipe_attributes; /* ignored */ + int size; - if (! PyArg_ParseTuple(args, "Oi:CreatePipe", &pipe_attributes, &size)) - return NULL; + if (! PyArg_ParseTuple(args, "Oi:CreatePipe", &pipe_attributes, &size)) + return NULL; - Py_BEGIN_ALLOW_THREADS - result = CreatePipe(&read_pipe, &write_pipe, NULL, size); - Py_END_ALLOW_THREADS + Py_BEGIN_ALLOW_THREADS + result = CreatePipe(&read_pipe, &write_pipe, NULL, size); + Py_END_ALLOW_THREADS - if (! result) - return PyErr_SetFromWindowsErr(GetLastError()); + if (! result) + return PyErr_SetFromWindowsErr(GetLastError()); - return Py_BuildValue( - "NN", sp_handle_new(read_pipe), sp_handle_new(write_pipe)); + return Py_BuildValue( + "NN", sp_handle_new(read_pipe), sp_handle_new(write_pipe)); } /* helpers for createprocess */ @@ -294,110 +294,110 @@ static int getint(PyObject* obj, char* name) { - PyObject* value; - int ret; + PyObject* value; + int ret; - value = PyObject_GetAttrString(obj, name); - if (! value) { - PyErr_Clear(); /* FIXME: propagate error? */ - return 0; - } - ret = (int) PyLong_AsLong(value); - Py_DECREF(value); - return ret; + value = PyObject_GetAttrString(obj, name); + if (! value) { + PyErr_Clear(); /* FIXME: propagate error? */ + return 0; + } + ret = (int) PyLong_AsLong(value); + Py_DECREF(value); + return ret; } static HANDLE gethandle(PyObject* obj, char* name) { - sp_handle_object* value; - HANDLE ret; + sp_handle_object* value; + HANDLE ret; - value = (sp_handle_object*) PyObject_GetAttrString(obj, name); - if (! value) { - PyErr_Clear(); /* FIXME: propagate error? */ - return NULL; - } - if (Py_TYPE(value) != &sp_handle_type) - ret = NULL; - else - ret = value->handle; - Py_DECREF(value); - return ret; + value = (sp_handle_object*) PyObject_GetAttrString(obj, name); + if (! value) { + PyErr_Clear(); /* FIXME: propagate error? */ + return NULL; + } + if (Py_TYPE(value) != &sp_handle_type) + ret = NULL; + else + ret = value->handle; + Py_DECREF(value); + return ret; } static PyObject* getenvironment(PyObject* environment) { - int i, envsize; - PyObject* out = NULL; - PyObject* keys; - PyObject* values; - Py_UNICODE* p; - - /* convert environment dictionary to windows enviroment string */ - if (! PyMapping_Check(environment)) { - PyErr_SetString( - PyExc_TypeError, "environment must be dictionary or None"); - return NULL; - } - - envsize = PyMapping_Length(environment); - - keys = PyMapping_Keys(environment); - values = PyMapping_Values(environment); - if (!keys || !values) - goto error; - - out = PyUnicode_FromUnicode(NULL, 2048); - if (! out) - goto error; - - p = PyUnicode_AS_UNICODE(out); - - for (i = 0; i < envsize; i++) { - int ksize, vsize, totalsize; - PyObject* key = PyList_GET_ITEM(keys, i); - PyObject* value = PyList_GET_ITEM(values, i); - - if (! PyUnicode_Check(key) || ! PyUnicode_Check(value)) { - PyErr_SetString(PyExc_TypeError, - "environment can only contain strings"); - goto error; - } - ksize = PyUnicode_GET_SIZE(key); - vsize = PyUnicode_GET_SIZE(value); - totalsize = (p - PyUnicode_AS_UNICODE(out)) + ksize + 1 + - vsize + 1 + 1; - if (totalsize > PyUnicode_GET_SIZE(out)) { - int offset = p - PyUnicode_AS_UNICODE(out); - PyUnicode_Resize(&out, totalsize + 1024); - p = PyUnicode_AS_UNICODE(out) + offset; - } - Py_UNICODE_COPY(p, PyUnicode_AS_UNICODE(key), ksize); - p += ksize; - *p++ = '='; - Py_UNICODE_COPY(p, PyUnicode_AS_UNICODE(value), vsize); - p += vsize; - *p++ = '\0'; - } - - /* add trailing null byte */ - *p++ = '\0'; - PyUnicode_Resize(&out, p - PyUnicode_AS_UNICODE(out)); + int i, envsize; + PyObject* out = NULL; + PyObject* keys; + PyObject* values; + Py_UNICODE* p; + + /* convert environment dictionary to windows enviroment string */ + if (! PyMapping_Check(environment)) { + PyErr_SetString( + PyExc_TypeError, "environment must be dictionary or None"); + return NULL; + } + + envsize = PyMapping_Length(environment); + + keys = PyMapping_Keys(environment); + values = PyMapping_Values(environment); + if (!keys || !values) + goto error; + + out = PyUnicode_FromUnicode(NULL, 2048); + if (! out) + goto error; + + p = PyUnicode_AS_UNICODE(out); + + for (i = 0; i < envsize; i++) { + int ksize, vsize, totalsize; + PyObject* key = PyList_GET_ITEM(keys, i); + PyObject* value = PyList_GET_ITEM(values, i); + + if (! PyUnicode_Check(key) || ! PyUnicode_Check(value)) { + PyErr_SetString(PyExc_TypeError, + "environment can only contain strings"); + goto error; + } + ksize = PyUnicode_GET_SIZE(key); + vsize = PyUnicode_GET_SIZE(value); + totalsize = (p - PyUnicode_AS_UNICODE(out)) + ksize + 1 + + vsize + 1 + 1; + if (totalsize > PyUnicode_GET_SIZE(out)) { + int offset = p - PyUnicode_AS_UNICODE(out); + PyUnicode_Resize(&out, totalsize + 1024); + p = PyUnicode_AS_UNICODE(out) + offset; + } + Py_UNICODE_COPY(p, PyUnicode_AS_UNICODE(key), ksize); + p += ksize; + *p++ = '='; + Py_UNICODE_COPY(p, PyUnicode_AS_UNICODE(value), vsize); + p += vsize; + *p++ = '\0'; + } + + /* add trailing null byte */ + *p++ = '\0'; + PyUnicode_Resize(&out, p - PyUnicode_AS_UNICODE(out)); - /* PyObject_Print(out, stdout, 0); */ + /* PyObject_Print(out, stdout, 0); */ - Py_XDECREF(keys); - Py_XDECREF(values); + Py_XDECREF(keys); + Py_XDECREF(values); - return out; + return out; error: - Py_XDECREF(out); - Py_XDECREF(keys); - Py_XDECREF(values); - return NULL; + Py_XDECREF(out); + Py_XDECREF(keys); + Py_XDECREF(values); + return NULL; } PyDoc_STRVAR(CreateProcess_doc, @@ -415,77 +415,77 @@ static PyObject * sp_CreateProcess(PyObject* self, PyObject* args) { - BOOL result; - PROCESS_INFORMATION pi; - STARTUPINFOW si; - PyObject* environment; - - Py_UNICODE* application_name; - Py_UNICODE* command_line; - PyObject* process_attributes; /* ignored */ - PyObject* thread_attributes; /* ignored */ - int inherit_handles; - int creation_flags; - PyObject* env_mapping; - Py_UNICODE* current_directory; - PyObject* startup_info; - - if (! PyArg_ParseTuple(args, "ZZOOiiOZO:CreateProcess", - &application_name, - &command_line, - &process_attributes, - &thread_attributes, - &inherit_handles, - &creation_flags, - &env_mapping, - ¤t_directory, - &startup_info)) - return NULL; - - ZeroMemory(&si, sizeof(si)); - si.cb = sizeof(si); - - /* note: we only support a small subset of all SI attributes */ - si.dwFlags = getint(startup_info, "dwFlags"); - si.wShowWindow = getint(startup_info, "wShowWindow"); - si.hStdInput = gethandle(startup_info, "hStdInput"); - si.hStdOutput = gethandle(startup_info, "hStdOutput"); - si.hStdError = gethandle(startup_info, "hStdError"); - - if (PyErr_Occurred()) - return NULL; - - if (env_mapping == Py_None) - environment = NULL; - else { - environment = getenvironment(env_mapping); - if (! environment) - return NULL; - } - - Py_BEGIN_ALLOW_THREADS - result = CreateProcessW(application_name, - command_line, - NULL, - NULL, - inherit_handles, - creation_flags | CREATE_UNICODE_ENVIRONMENT, - environment ? PyUnicode_AS_UNICODE(environment) : NULL, - current_directory, - &si, - &pi); - Py_END_ALLOW_THREADS - - Py_XDECREF(environment); - - if (! result) - return PyErr_SetFromWindowsErr(GetLastError()); - - return Py_BuildValue("NNii", - sp_handle_new(pi.hProcess), - sp_handle_new(pi.hThread), - pi.dwProcessId, - pi.dwThreadId); + BOOL result; + PROCESS_INFORMATION pi; + STARTUPINFOW si; + PyObject* environment; + + Py_UNICODE* application_name; + Py_UNICODE* command_line; + PyObject* process_attributes; /* ignored */ + PyObject* thread_attributes; /* ignored */ + int inherit_handles; + int creation_flags; + PyObject* env_mapping; + Py_UNICODE* current_directory; + PyObject* startup_info; + + if (! PyArg_ParseTuple(args, "ZZOOiiOZO:CreateProcess", + &application_name, + &command_line, + &process_attributes, + &thread_attributes, + &inherit_handles, + &creation_flags, + &env_mapping, + ¤t_directory, + &startup_info)) + return NULL; + + ZeroMemory(&si, sizeof(si)); + si.cb = sizeof(si); + + /* note: we only support a small subset of all SI attributes */ + si.dwFlags = getint(startup_info, "dwFlags"); + si.wShowWindow = getint(startup_info, "wShowWindow"); + si.hStdInput = gethandle(startup_info, "hStdInput"); + si.hStdOutput = gethandle(startup_info, "hStdOutput"); + si.hStdError = gethandle(startup_info, "hStdError"); + + if (PyErr_Occurred()) + return NULL; + + if (env_mapping == Py_None) + environment = NULL; + else { + environment = getenvironment(env_mapping); + if (! environment) + return NULL; + } + + Py_BEGIN_ALLOW_THREADS + result = CreateProcessW(application_name, + command_line, + NULL, + NULL, + inherit_handles, + creation_flags | CREATE_UNICODE_ENVIRONMENT, + environment ? PyUnicode_AS_UNICODE(environment) : NULL, + current_directory, + &si, + &pi); + Py_END_ALLOW_THREADS + + Py_XDECREF(environment); + + if (! result) + return PyErr_SetFromWindowsErr(GetLastError()); + + return Py_BuildValue("NNii", + sp_handle_new(pi.hProcess), + sp_handle_new(pi.hThread), + pi.dwProcessId, + pi.dwThreadId); } PyDoc_STRVAR(TerminateProcess_doc, @@ -496,21 +496,21 @@ static PyObject * sp_TerminateProcess(PyObject* self, PyObject* args) { - BOOL result; + BOOL result; - HANDLE process; - int exit_code; - if (! PyArg_ParseTuple(args, PY_HANDLE_PARAM "i:TerminateProcess", - &process, &exit_code)) - return NULL; + HANDLE process; + int exit_code; + if (! PyArg_ParseTuple(args, PY_HANDLE_PARAM "i:TerminateProcess", + &process, &exit_code)) + return NULL; - result = TerminateProcess(process, exit_code); + result = TerminateProcess(process, exit_code); - if (! result) - return PyErr_SetFromWindowsErr(GetLastError()); + if (! result) + return PyErr_SetFromWindowsErr(GetLastError()); - Py_INCREF(Py_None); - return Py_None; + Py_INCREF(Py_None); + return Py_None; } PyDoc_STRVAR(GetExitCodeProcess_doc, @@ -521,19 +521,19 @@ static PyObject * sp_GetExitCodeProcess(PyObject* self, PyObject* args) { - DWORD exit_code; - BOOL result; + DWORD exit_code; + BOOL result; - HANDLE process; - if (! PyArg_ParseTuple(args, PY_HANDLE_PARAM ":GetExitCodeProcess", &process)) - return NULL; + HANDLE process; + if (! PyArg_ParseTuple(args, PY_HANDLE_PARAM ":GetExitCodeProcess", &process)) + return NULL; - result = GetExitCodeProcess(process, &exit_code); + result = GetExitCodeProcess(process, &exit_code); - if (! result) - return PyErr_SetFromWindowsErr(GetLastError()); + if (! result) + return PyErr_SetFromWindowsErr(GetLastError()); - return PyLong_FromLong(exit_code); + return PyLong_FromLong(exit_code); } PyDoc_STRVAR(WaitForSingleObject_doc, @@ -546,23 +546,23 @@ static PyObject * sp_WaitForSingleObject(PyObject* self, PyObject* args) { - DWORD result; + DWORD result; - HANDLE handle; - int milliseconds; - if (! PyArg_ParseTuple(args, PY_HANDLE_PARAM "i:WaitForSingleObject", - &handle, - &milliseconds)) - return NULL; - - Py_BEGIN_ALLOW_THREADS - result = WaitForSingleObject(handle, (DWORD) milliseconds); - Py_END_ALLOW_THREADS + HANDLE handle; + int milliseconds; + if (! PyArg_ParseTuple(args, PY_HANDLE_PARAM "i:WaitForSingleObject", + &handle, + &milliseconds)) + return NULL; + + Py_BEGIN_ALLOW_THREADS + result = WaitForSingleObject(handle, (DWORD) milliseconds); + Py_END_ALLOW_THREADS - if (result == WAIT_FAILED) - return PyErr_SetFromWindowsErr(GetLastError()); + if (result == WAIT_FAILED) + return PyErr_SetFromWindowsErr(GetLastError()); - return PyLong_FromLong((int) result); + return PyLong_FromLong((int) result); } PyDoc_STRVAR(GetVersion_doc, @@ -573,10 +573,10 @@ static PyObject * sp_GetVersion(PyObject* self, PyObject* args) { - if (! PyArg_ParseTuple(args, ":GetVersion")) - return NULL; + if (! PyArg_ParseTuple(args, ":GetVersion")) + return NULL; - return PyLong_FromLong((int) GetVersion()); + return PyLong_FromLong((int) GetVersion()); } PyDoc_STRVAR(GetModuleFileName_doc, @@ -594,41 +594,41 @@ static PyObject * sp_GetModuleFileName(PyObject* self, PyObject* args) { - BOOL result; - HMODULE module; - WCHAR filename[MAX_PATH]; + BOOL result; + HMODULE module; + WCHAR filename[MAX_PATH]; - if (! PyArg_ParseTuple(args, PY_HANDLE_PARAM ":GetModuleFileName", - &module)) - return NULL; + if (! PyArg_ParseTuple(args, PY_HANDLE_PARAM ":GetModuleFileName", + &module)) + return NULL; - result = GetModuleFileNameW(module, filename, MAX_PATH); - filename[MAX_PATH-1] = '\0'; + result = GetModuleFileNameW(module, filename, MAX_PATH); + filename[MAX_PATH-1] = '\0'; - if (! result) - return PyErr_SetFromWindowsErr(GetLastError()); + if (! result) + return PyErr_SetFromWindowsErr(GetLastError()); - return PyUnicode_FromUnicode(filename, Py_UNICODE_strlen(filename)); + return PyUnicode_FromUnicode(filename, Py_UNICODE_strlen(filename)); } static PyMethodDef sp_functions[] = { - {"GetStdHandle", sp_GetStdHandle, METH_VARARGS, GetStdHandle_doc}, - {"GetCurrentProcess", sp_GetCurrentProcess, METH_VARARGS, - GetCurrentProcess_doc}, - {"DuplicateHandle", sp_DuplicateHandle, METH_VARARGS, - DuplicateHandle_doc}, - {"CreatePipe", sp_CreatePipe, METH_VARARGS, CreatePipe_doc}, - {"CreateProcess", sp_CreateProcess, METH_VARARGS, CreateProcess_doc}, - {"TerminateProcess", sp_TerminateProcess, METH_VARARGS, - TerminateProcess_doc}, - {"GetExitCodeProcess", sp_GetExitCodeProcess, METH_VARARGS, - GetExitCodeProcess_doc}, - {"WaitForSingleObject", sp_WaitForSingleObject, METH_VARARGS, - WaitForSingleObject_doc}, - {"GetVersion", sp_GetVersion, METH_VARARGS, GetVersion_doc}, - {"GetModuleFileName", sp_GetModuleFileName, METH_VARARGS, - GetModuleFileName_doc}, - {NULL, NULL} + {"GetStdHandle", sp_GetStdHandle, METH_VARARGS, GetStdHandle_doc}, + {"GetCurrentProcess", sp_GetCurrentProcess, METH_VARARGS, + GetCurrentProcess_doc}, + {"DuplicateHandle", sp_DuplicateHandle, METH_VARARGS, + DuplicateHandle_doc}, + {"CreatePipe", sp_CreatePipe, METH_VARARGS, CreatePipe_doc}, + {"CreateProcess", sp_CreateProcess, METH_VARARGS, CreateProcess_doc}, + {"TerminateProcess", sp_TerminateProcess, METH_VARARGS, + TerminateProcess_doc}, + {"GetExitCodeProcess", sp_GetExitCodeProcess, METH_VARARGS, + GetExitCodeProcess_doc}, + {"WaitForSingleObject", sp_WaitForSingleObject, METH_VARARGS, + WaitForSingleObject_doc}, + {"GetVersion", sp_GetVersion, METH_VARARGS, GetVersion_doc}, + {"GetModuleFileName", sp_GetModuleFileName, METH_VARARGS, + GetModuleFileName_doc}, + {NULL, NULL} }; /* -------------------------------------------------------------------- */ @@ -636,51 +636,51 @@ static void defint(PyObject* d, const char* name, int value) { - PyObject* v = PyLong_FromLong((long) value); - if (v) { - PyDict_SetItemString(d, (char*) name, v); - Py_DECREF(v); - } + PyObject* v = PyLong_FromLong((long) value); + if (v) { + PyDict_SetItemString(d, (char*) name, v); + Py_DECREF(v); + } } static struct PyModuleDef _subprocessmodule = { - PyModuleDef_HEAD_INIT, - "_subprocess", - NULL, - -1, - sp_functions, - NULL, - NULL, - NULL, - NULL + PyModuleDef_HEAD_INIT, + "_subprocess", + NULL, + -1, + sp_functions, + NULL, + NULL, + NULL, + NULL }; PyMODINIT_FUNC PyInit__subprocess() { - PyObject *d; - PyObject *m; + PyObject *d; + PyObject *m; - /* patch up object descriptors */ - sp_handle_as_number.nb_int = (unaryfunc) sp_handle_as_int; - if (PyType_Ready(&sp_handle_type) < 0) - return NULL; - - m = PyModule_Create(&_subprocessmodule); - if (m == NULL) - return NULL; - d = PyModule_GetDict(m); - - /* constants */ - defint(d, "STD_INPUT_HANDLE", STD_INPUT_HANDLE); - defint(d, "STD_OUTPUT_HANDLE", STD_OUTPUT_HANDLE); - defint(d, "STD_ERROR_HANDLE", STD_ERROR_HANDLE); - defint(d, "DUPLICATE_SAME_ACCESS", DUPLICATE_SAME_ACCESS); - defint(d, "STARTF_USESTDHANDLES", STARTF_USESTDHANDLES); - defint(d, "STARTF_USESHOWWINDOW", STARTF_USESHOWWINDOW); - defint(d, "SW_HIDE", SW_HIDE); - defint(d, "INFINITE", INFINITE); - defint(d, "WAIT_OBJECT_0", WAIT_OBJECT_0); - defint(d, "CREATE_NEW_CONSOLE", CREATE_NEW_CONSOLE); - return m; + /* patch up object descriptors */ + sp_handle_as_number.nb_int = (unaryfunc) sp_handle_as_int; + if (PyType_Ready(&sp_handle_type) < 0) + return NULL; + + m = PyModule_Create(&_subprocessmodule); + if (m == NULL) + return NULL; + d = PyModule_GetDict(m); + + /* constants */ + defint(d, "STD_INPUT_HANDLE", STD_INPUT_HANDLE); + defint(d, "STD_OUTPUT_HANDLE", STD_OUTPUT_HANDLE); + defint(d, "STD_ERROR_HANDLE", STD_ERROR_HANDLE); + defint(d, "DUPLICATE_SAME_ACCESS", DUPLICATE_SAME_ACCESS); + defint(d, "STARTF_USESTDHANDLES", STARTF_USESTDHANDLES); + defint(d, "STARTF_USESHOWWINDOW", STARTF_USESHOWWINDOW); + defint(d, "SW_HIDE", SW_HIDE); + defint(d, "INFINITE", INFINITE); + defint(d, "WAIT_OBJECT_0", WAIT_OBJECT_0); + defint(d, "CREATE_NEW_CONSOLE", CREATE_NEW_CONSOLE); + return m; } Modified: python/branches/release31-maint/PC/bdist_wininst/archive.h ============================================================================== --- python/branches/release31-maint/PC/bdist_wininst/archive.h (original) +++ python/branches/release31-maint/PC/bdist_wininst/archive.h Sun May 9 18:14:21 2010 @@ -14,55 +14,55 @@ */ struct eof_cdir { - long tag; /* must be 0x06054b50 */ - short disknum; - short firstdisk; - short nTotalCDirThis; - short nTotalCDir; - long nBytesCDir; - long ofsCDir; - short commentlen; + long tag; /* must be 0x06054b50 */ + short disknum; + short firstdisk; + short nTotalCDirThis; + short nTotalCDir; + long nBytesCDir; + long ofsCDir; + short commentlen; }; struct cdir { - long tag; /* must be 0x02014b50 */ - short version_made; - short version_extract; - short gp_bitflag; - short comp_method; - short last_mod_file_time; - short last_mod_file_date; - long crc32; - long comp_size; - long uncomp_size; - short fname_length; - short extra_length; - short comment_length; - short disknum_start; - short int_file_attr; - long ext_file_attr; - long ofs_local_header; + long tag; /* must be 0x02014b50 */ + short version_made; + short version_extract; + short gp_bitflag; + short comp_method; + short last_mod_file_time; + short last_mod_file_date; + long crc32; + long comp_size; + long uncomp_size; + short fname_length; + short extra_length; + short comment_length; + short disknum_start; + short int_file_attr; + long ext_file_attr; + long ofs_local_header; }; struct fhdr { - long tag; /* must be 0x04034b50 */ - short version_needed; - short flags; - short method; - short last_mod_file_time; - short last_mod_file_date; - long crc32; - long comp_size; - long uncomp_size; - short fname_length; - short extra_length; + long tag; /* must be 0x04034b50 */ + short version_needed; + short flags; + short method; + short last_mod_file_time; + short last_mod_file_date; + long crc32; + long comp_size; + long uncomp_size; + short fname_length; + short extra_length; }; struct meta_data_hdr { - int tag; - int uncomp_size; - int bitmap_size; + int tag; + int uncomp_size; + int bitmap_size; }; #pragma pack() @@ -70,29 +70,29 @@ /* installation scheme */ typedef struct tagSCHEME { - char *name; - char *prefix; + char *name; + char *prefix; } SCHEME; typedef int (*NOTIFYPROC)(int code, LPSTR text, ...); extern BOOL extract_file(char *dst, char *src, int method, int comp_size, - int uncomp_size, NOTIFYPROC notify); + int uncomp_size, NOTIFYPROC notify); extern BOOL unzip_archive(SCHEME *scheme, char *dirname, char *data, - DWORD size, NOTIFYPROC notify); + DWORD size, NOTIFYPROC notify); extern char * map_new_file(DWORD flags, char *filename, char - *pathname_part, int size, - WORD wFatDate, WORD wFatTime, - NOTIFYPROC callback); + *pathname_part, int size, + WORD wFatDate, WORD wFatTime, + NOTIFYPROC callback); extern BOOL ensure_directory (char *pathname, char *new_part, - NOTIFYPROC callback); + NOTIFYPROC callback); /* codes for NOITIFYPROC */ #define DIR_CREATED 1 Modified: python/branches/release31-maint/PC/bdist_wininst/extract.c ============================================================================== --- python/branches/release31-maint/PC/bdist_wininst/extract.c (original) +++ python/branches/release31-maint/PC/bdist_wininst/extract.c Sun May 9 18:14:21 2010 @@ -19,181 +19,181 @@ /* Convert unix-path to dos-path */ static void normpath(char *path) { - while (path && *path) { - if (*path == '/') - *path = '\\'; - ++path; - } + while (path && *path) { + if (*path == '/') + *path = '\\'; + ++path; + } } BOOL ensure_directory(char *pathname, char *new_part, NOTIFYPROC notify) { - while (new_part && *new_part && (new_part = strchr(new_part, '\\'))) { - DWORD attr; - *new_part = '\0'; - attr = GetFileAttributes(pathname); - if (attr == -1) { - /* nothing found */ - if (!CreateDirectory(pathname, NULL) && notify) - notify(SYSTEM_ERROR, - "CreateDirectory (%s)", pathname); - else - notify(DIR_CREATED, pathname); - } - if (attr & FILE_ATTRIBUTE_DIRECTORY) { - ; - } else { - SetLastError(183); - if (notify) - notify(SYSTEM_ERROR, - "CreateDirectory (%s)", pathname); - } - *new_part = '\\'; - ++new_part; - } - return TRUE; + while (new_part && *new_part && (new_part = strchr(new_part, '\\'))) { + DWORD attr; + *new_part = '\0'; + attr = GetFileAttributes(pathname); + if (attr == -1) { + /* nothing found */ + if (!CreateDirectory(pathname, NULL) && notify) + notify(SYSTEM_ERROR, + "CreateDirectory (%s)", pathname); + else + notify(DIR_CREATED, pathname); + } + if (attr & FILE_ATTRIBUTE_DIRECTORY) { + ; + } else { + SetLastError(183); + if (notify) + notify(SYSTEM_ERROR, + "CreateDirectory (%s)", pathname); + } + *new_part = '\\'; + ++new_part; + } + return TRUE; } /* XXX Should better explicitely specify * uncomp_size and file_times instead of pfhdr! */ char *map_new_file(DWORD flags, char *filename, - char *pathname_part, int size, - WORD wFatDate, WORD wFatTime, - NOTIFYPROC notify) + char *pathname_part, int size, + WORD wFatDate, WORD wFatTime, + NOTIFYPROC notify) { - HANDLE hFile, hFileMapping; - char *dst; - FILETIME ft; + HANDLE hFile, hFileMapping; + char *dst; + FILETIME ft; try_again: - if (!flags) - flags = CREATE_NEW; - hFile = CreateFile(filename, - GENERIC_WRITE | GENERIC_READ, - 0, NULL, - flags, - FILE_ATTRIBUTE_NORMAL, NULL); - if (hFile == INVALID_HANDLE_VALUE) { - DWORD x = GetLastError(); - switch (x) { - case ERROR_FILE_EXISTS: - if (notify && notify(CAN_OVERWRITE, filename)) - hFile = CreateFile(filename, - GENERIC_WRITE|GENERIC_READ, - 0, NULL, - CREATE_ALWAYS, - FILE_ATTRIBUTE_NORMAL, - NULL); - else { - if (notify) - notify(FILE_OVERWRITTEN, filename); - return NULL; - } - break; - case ERROR_PATH_NOT_FOUND: - if (ensure_directory(filename, pathname_part, notify)) - goto try_again; - else - return FALSE; - break; - default: - SetLastError(x); - break; - } - } - if (hFile == INVALID_HANDLE_VALUE) { - if (notify) - notify (SYSTEM_ERROR, "CreateFile (%s)", filename); - return NULL; - } - - if (notify) - notify(FILE_CREATED, filename); - - DosDateTimeToFileTime(wFatDate, wFatTime, &ft); - SetFileTime(hFile, &ft, &ft, &ft); - - - if (size == 0) { - /* We cannot map a zero-length file (Also it makes - no sense */ - CloseHandle(hFile); - return NULL; - } - - hFileMapping = CreateFileMapping(hFile, - NULL, PAGE_READWRITE, 0, size, NULL); - - CloseHandle(hFile); - - if (hFileMapping == INVALID_HANDLE_VALUE) { - if (notify) - notify(SYSTEM_ERROR, - "CreateFileMapping (%s)", filename); - return NULL; - } - - dst = MapViewOfFile(hFileMapping, - FILE_MAP_WRITE, 0, 0, 0); - - CloseHandle(hFileMapping); - - if (!dst) { - if (notify) - notify(SYSTEM_ERROR, "MapViewOfFile (%s)", filename); - return NULL; - } - return dst; + if (!flags) + flags = CREATE_NEW; + hFile = CreateFile(filename, + GENERIC_WRITE | GENERIC_READ, + 0, NULL, + flags, + FILE_ATTRIBUTE_NORMAL, NULL); + if (hFile == INVALID_HANDLE_VALUE) { + DWORD x = GetLastError(); + switch (x) { + case ERROR_FILE_EXISTS: + if (notify && notify(CAN_OVERWRITE, filename)) + hFile = CreateFile(filename, + GENERIC_WRITE|GENERIC_READ, + 0, NULL, + CREATE_ALWAYS, + FILE_ATTRIBUTE_NORMAL, + NULL); + else { + if (notify) + notify(FILE_OVERWRITTEN, filename); + return NULL; + } + break; + case ERROR_PATH_NOT_FOUND: + if (ensure_directory(filename, pathname_part, notify)) + goto try_again; + else + return FALSE; + break; + default: + SetLastError(x); + break; + } + } + if (hFile == INVALID_HANDLE_VALUE) { + if (notify) + notify (SYSTEM_ERROR, "CreateFile (%s)", filename); + return NULL; + } + + if (notify) + notify(FILE_CREATED, filename); + + DosDateTimeToFileTime(wFatDate, wFatTime, &ft); + SetFileTime(hFile, &ft, &ft, &ft); + + + if (size == 0) { + /* We cannot map a zero-length file (Also it makes + no sense */ + CloseHandle(hFile); + return NULL; + } + + hFileMapping = CreateFileMapping(hFile, + NULL, PAGE_READWRITE, 0, size, NULL); + + CloseHandle(hFile); + + if (hFileMapping == INVALID_HANDLE_VALUE) { + if (notify) + notify(SYSTEM_ERROR, + "CreateFileMapping (%s)", filename); + return NULL; + } + + dst = MapViewOfFile(hFileMapping, + FILE_MAP_WRITE, 0, 0, 0); + + CloseHandle(hFileMapping); + + if (!dst) { + if (notify) + notify(SYSTEM_ERROR, "MapViewOfFile (%s)", filename); + return NULL; + } + return dst; } BOOL extract_file(char *dst, char *src, int method, int comp_size, - int uncomp_size, NOTIFYPROC notify) + int uncomp_size, NOTIFYPROC notify) { - z_stream zstream; - int result; + z_stream zstream; + int result; - if (method == Z_DEFLATED) { - int x; - memset(&zstream, 0, sizeof(zstream)); - zstream.next_in = src; - zstream.avail_in = comp_size+1; - zstream.next_out = dst; - zstream.avail_out = uncomp_size; + if (method == Z_DEFLATED) { + int x; + memset(&zstream, 0, sizeof(zstream)); + zstream.next_in = src; + zstream.avail_in = comp_size+1; + zstream.next_out = dst; + zstream.avail_out = uncomp_size; /* Apparently an undocumented feature of zlib: Set windowsize to negative values to supress the gzip header and be compatible with zip! */ - result = TRUE; - if (Z_OK != (x = inflateInit2(&zstream, -15))) { - if (notify) - notify(ZLIB_ERROR, - "inflateInit2 returns %d", x); - result = FALSE; - goto cleanup; - } - if (Z_STREAM_END != (x = inflate(&zstream, Z_FINISH))) { - if (notify) - notify(ZLIB_ERROR, - "inflate returns %d", x); - result = FALSE; - } - cleanup: - if (Z_OK != (x = inflateEnd(&zstream))) { - if (notify) - notify (ZLIB_ERROR, - "inflateEnd returns %d", x); - result = FALSE; - } - } else if (method == 0) { - memcpy(dst, src, uncomp_size); - result = TRUE; - } else - result = FALSE; - UnmapViewOfFile(dst); - return result; + result = TRUE; + if (Z_OK != (x = inflateInit2(&zstream, -15))) { + if (notify) + notify(ZLIB_ERROR, + "inflateInit2 returns %d", x); + result = FALSE; + goto cleanup; + } + if (Z_STREAM_END != (x = inflate(&zstream, Z_FINISH))) { + if (notify) + notify(ZLIB_ERROR, + "inflate returns %d", x); + result = FALSE; + } + cleanup: + if (Z_OK != (x = inflateEnd(&zstream))) { + if (notify) + notify (ZLIB_ERROR, + "inflateEnd returns %d", x); + result = FALSE; + } + } else if (method == 0) { + memcpy(dst, src, uncomp_size); + result = TRUE; + } else + result = FALSE; + UnmapViewOfFile(dst); + return result; } /* Open a zip-compatible archive and extract all files @@ -201,121 +201,121 @@ */ BOOL unzip_archive(SCHEME *scheme, char *dirname, char *data, DWORD size, - NOTIFYPROC notify) + NOTIFYPROC notify) { - int n; - char pathname[MAX_PATH]; - char *new_part; - - /* read the end of central directory record */ - struct eof_cdir *pe = (struct eof_cdir *)&data[size - sizeof - (struct eof_cdir)]; - - int arc_start = size - sizeof (struct eof_cdir) - pe->nBytesCDir - - pe->ofsCDir; - - /* set position to start of central directory */ - int pos = arc_start + pe->ofsCDir; - - /* make sure this is a zip file */ - if (pe->tag != 0x06054b50) - return FALSE; - - /* Loop through the central directory, reading all entries */ - for (n = 0; n < pe->nTotalCDir; ++n) { - int i; - char *fname; - char *pcomp; - char *dst; - struct cdir *pcdir; - struct fhdr *pfhdr; - - pcdir = (struct cdir *)&data[pos]; - pfhdr = (struct fhdr *)&data[pcdir->ofs_local_header + - arc_start]; - - if (pcdir->tag != 0x02014b50) - return FALSE; - if (pfhdr->tag != 0x04034b50) - return FALSE; - pos += sizeof(struct cdir); - fname = (char *)&data[pos]; /* This is not null terminated! */ - pos += pcdir->fname_length + pcdir->extra_length + - pcdir->comment_length; - - pcomp = &data[pcdir->ofs_local_header - + sizeof(struct fhdr) - + arc_start - + pfhdr->fname_length - + pfhdr->extra_length]; - - /* dirname is the Python home directory (prefix) */ - strcpy(pathname, dirname); - if (pathname[strlen(pathname)-1] != '\\') - strcat(pathname, "\\"); - new_part = &pathname[lstrlen(pathname)]; - /* we must now match the first part of the pathname - * in the archive to a component in the installation - * scheme (PURELIB, PLATLIB, HEADERS, SCRIPTS, or DATA) - * and replace this part by the one in the scheme to use - */ - for (i = 0; scheme[i].name; ++i) { - if (0 == strnicmp(scheme[i].name, fname, - strlen(scheme[i].name))) { - char *rest; - int len; - - /* length of the replaced part */ - int namelen = strlen(scheme[i].name); - - strcat(pathname, scheme[i].prefix); - - rest = fname + namelen; - len = pfhdr->fname_length - namelen; - - if ((pathname[strlen(pathname)-1] != '\\') - && (pathname[strlen(pathname)-1] != '/')) - strcat(pathname, "\\"); - /* Now that pathname ends with a separator, - * we must make sure rest does not start with - * an additional one. - */ - if ((rest[0] == '\\') || (rest[0] == '/')) { - ++rest; - --len; - } - - strncat(pathname, rest, len); - goto Done; - } - } - /* no prefix to replace found, go unchanged */ - strncat(pathname, fname, pfhdr->fname_length); - Done: - normpath(pathname); - if (pathname[strlen(pathname)-1] != '\\') { - /* - * The local file header (pfhdr) does not always - * contain the compressed and uncompressed sizes of - * the data depending on bit 3 of the flags field. So - * it seems better to use the data from the central - * directory (pcdir). - */ - dst = map_new_file(0, pathname, new_part, - pcdir->uncomp_size, - pcdir->last_mod_file_date, - pcdir->last_mod_file_time, notify); - if (dst) { - if (!extract_file(dst, pcomp, pfhdr->method, - pcdir->comp_size, - pcdir->uncomp_size, - notify)) - return FALSE; - } /* else ??? */ - } - if (notify) - notify(NUM_FILES, new_part, (int)pe->nTotalCDir, - (int)n+1); - } - return TRUE; + int n; + char pathname[MAX_PATH]; + char *new_part; + + /* read the end of central directory record */ + struct eof_cdir *pe = (struct eof_cdir *)&data[size - sizeof + (struct eof_cdir)]; + + int arc_start = size - sizeof (struct eof_cdir) - pe->nBytesCDir - + pe->ofsCDir; + + /* set position to start of central directory */ + int pos = arc_start + pe->ofsCDir; + + /* make sure this is a zip file */ + if (pe->tag != 0x06054b50) + return FALSE; + + /* Loop through the central directory, reading all entries */ + for (n = 0; n < pe->nTotalCDir; ++n) { + int i; + char *fname; + char *pcomp; + char *dst; + struct cdir *pcdir; + struct fhdr *pfhdr; + + pcdir = (struct cdir *)&data[pos]; + pfhdr = (struct fhdr *)&data[pcdir->ofs_local_header + + arc_start]; + + if (pcdir->tag != 0x02014b50) + return FALSE; + if (pfhdr->tag != 0x04034b50) + return FALSE; + pos += sizeof(struct cdir); + fname = (char *)&data[pos]; /* This is not null terminated! */ + pos += pcdir->fname_length + pcdir->extra_length + + pcdir->comment_length; + + pcomp = &data[pcdir->ofs_local_header + + sizeof(struct fhdr) + + arc_start + + pfhdr->fname_length + + pfhdr->extra_length]; + + /* dirname is the Python home directory (prefix) */ + strcpy(pathname, dirname); + if (pathname[strlen(pathname)-1] != '\\') + strcat(pathname, "\\"); + new_part = &pathname[lstrlen(pathname)]; + /* we must now match the first part of the pathname + * in the archive to a component in the installation + * scheme (PURELIB, PLATLIB, HEADERS, SCRIPTS, or DATA) + * and replace this part by the one in the scheme to use + */ + for (i = 0; scheme[i].name; ++i) { + if (0 == strnicmp(scheme[i].name, fname, + strlen(scheme[i].name))) { + char *rest; + int len; + + /* length of the replaced part */ + int namelen = strlen(scheme[i].name); + + strcat(pathname, scheme[i].prefix); + + rest = fname + namelen; + len = pfhdr->fname_length - namelen; + + if ((pathname[strlen(pathname)-1] != '\\') + && (pathname[strlen(pathname)-1] != '/')) + strcat(pathname, "\\"); + /* Now that pathname ends with a separator, + * we must make sure rest does not start with + * an additional one. + */ + if ((rest[0] == '\\') || (rest[0] == '/')) { + ++rest; + --len; + } + + strncat(pathname, rest, len); + goto Done; + } + } + /* no prefix to replace found, go unchanged */ + strncat(pathname, fname, pfhdr->fname_length); + Done: + normpath(pathname); + if (pathname[strlen(pathname)-1] != '\\') { + /* + * The local file header (pfhdr) does not always + * contain the compressed and uncompressed sizes of + * the data depending on bit 3 of the flags field. So + * it seems better to use the data from the central + * directory (pcdir). + */ + dst = map_new_file(0, pathname, new_part, + pcdir->uncomp_size, + pcdir->last_mod_file_date, + pcdir->last_mod_file_time, notify); + if (dst) { + if (!extract_file(dst, pcomp, pfhdr->method, + pcdir->comp_size, + pcdir->uncomp_size, + notify)) + return FALSE; + } /* else ??? */ + } + if (notify) + notify(NUM_FILES, new_part, (int)pe->nTotalCDir, + (int)n+1); + } + return TRUE; } Modified: python/branches/release31-maint/PC/bdist_wininst/install.c ============================================================================== --- python/branches/release31-maint/PC/bdist_wininst/install.c (original) +++ python/branches/release31-maint/PC/bdist_wininst/install.c Sun May 9 18:14:21 2010 @@ -20,21 +20,21 @@ * * At runtime, the exefile has appended: * - compressed setup-data in ini-format, containing the following sections: - * [metadata] - * author=Greg Ward - * author_email=gward at python.net - * description=Python Distribution Utilities - * licence=Python - * name=Distutils - * url=http://www.python.org/sigs/distutils-sig/ - * version=0.9pre + * [metadata] + * author=Greg Ward + * author_email=gward at python.net + * description=Python Distribution Utilities + * licence=Python + * name=Distutils + * url=http://www.python.org/sigs/distutils-sig/ + * version=0.9pre * - * [Setup] - * info= text to be displayed in the edit-box - * title= to be displayed by this program - * target_version = if present, python version required - * pyc_compile = if 0, do not compile py to pyc - * pyo_compile = if 0, do not compile py to pyo + * [Setup] + * info= text to be displayed in the edit-box + * title= to be displayed by this program + * target_version = if present, python version required + * pyc_compile = if 0, do not compile py to pyc + * pyo_compile = if 0, do not compile py to pyo * * - a struct meta_data_hdr, describing the above * - a zip-file, containing the modules to be installed. @@ -119,28 +119,28 @@ HWND hwndMain; HWND hDialog; -char *ini_file; /* Full pathname of ini-file */ +char *ini_file; /* Full pathname of ini-file */ /* From ini-file */ -char info[4096]; /* [Setup] info= */ -char title[80]; /* [Setup] title=, contains package name - including version: "Distutils-1.0.1" */ -char target_version[10]; /* [Setup] target_version=, required python - version or empty string */ -char build_info[80]; /* [Setup] build_info=, distutils version - and build date */ +char info[4096]; /* [Setup] info= */ +char title[80]; /* [Setup] title=, contains package name + including version: "Distutils-1.0.1" */ +char target_version[10]; /* [Setup] target_version=, required python + version or empty string */ +char build_info[80]; /* [Setup] build_info=, distutils version + and build date */ -char meta_name[80]; /* package name without version like - 'Distutils' */ +char meta_name[80]; /* package name without version like + 'Distutils' */ char install_script[MAX_PATH]; char *pre_install_script; /* run before we install a single file */ char user_access_control[10]; // one of 'auto', 'force', otherwise none. -int py_major, py_minor; /* Python version selected for installation */ +int py_major, py_minor; /* Python version selected for installation */ -char *arc_data; /* memory mapped archive */ -DWORD arc_size; /* number of bytes in archive */ -int exe_size; /* number of bytes for exe-file portion */ +char *arc_data; /* memory mapped archive */ +DWORD arc_size; /* number of bytes in archive */ +int exe_size; /* number of bytes for exe-file portion */ char python_dir[MAX_PATH]; char pythondll[MAX_PATH]; BOOL pyc_compile, pyo_compile; @@ -148,7 +148,7 @@ the permissions of the current user. */ HKEY hkey_root = (HKEY)-1; -BOOL success; /* Installation successfull? */ +BOOL success; /* Installation successfull? */ char *failure_reason = NULL; HANDLE hBitmap; @@ -166,128 +166,128 @@ /* Note: If scheme.prefix is nonempty, it must end with a '\'! */ /* Note: purelib must be the FIRST entry! */ SCHEME old_scheme[] = { - { "PURELIB", "" }, - { "PLATLIB", "" }, - { "HEADERS", "" }, /* 'Include/dist_name' part already in archive */ - { "SCRIPTS", "Scripts\\" }, - { "DATA", "" }, - { NULL, NULL }, + { "PURELIB", "" }, + { "PLATLIB", "" }, + { "HEADERS", "" }, /* 'Include/dist_name' part already in archive */ + { "SCRIPTS", "Scripts\\" }, + { "DATA", "" }, + { NULL, NULL }, }; SCHEME new_scheme[] = { - { "PURELIB", "Lib\\site-packages\\" }, - { "PLATLIB", "Lib\\site-packages\\" }, - { "HEADERS", "" }, /* 'Include/dist_name' part already in archive */ - { "SCRIPTS", "Scripts\\" }, - { "DATA", "" }, - { NULL, NULL }, + { "PURELIB", "Lib\\site-packages\\" }, + { "PLATLIB", "Lib\\site-packages\\" }, + { "HEADERS", "" }, /* 'Include/dist_name' part already in archive */ + { "SCRIPTS", "Scripts\\" }, + { "DATA", "" }, + { NULL, NULL }, }; static void unescape(char *dst, char *src, unsigned size) { - char *eon; - char ch; + char *eon; + char ch; - while (src && *src && (size > 2)) { - if (*src == '\\') { - switch (*++src) { - case 'n': - ++src; - *dst++ = '\r'; - *dst++ = '\n'; - size -= 2; - break; - case 'r': - ++src; - *dst++ = '\r'; - --size; - break; - case '0': case '1': case '2': case '3': - ch = (char)strtol(src, &eon, 8); - if (ch == '\n') { - *dst++ = '\r'; - --size; - } - *dst++ = ch; - --size; - src = eon; - } - } else { - *dst++ = *src++; - --size; - } - } - *dst = '\0'; + while (src && *src && (size > 2)) { + if (*src == '\\') { + switch (*++src) { + case 'n': + ++src; + *dst++ = '\r'; + *dst++ = '\n'; + size -= 2; + break; + case 'r': + ++src; + *dst++ = '\r'; + --size; + break; + case '0': case '1': case '2': case '3': + ch = (char)strtol(src, &eon, 8); + if (ch == '\n') { + *dst++ = '\r'; + --size; + } + *dst++ = ch; + --size; + src = eon; + } + } else { + *dst++ = *src++; + --size; + } + } + *dst = '\0'; } static struct tagFile { - char *path; - struct tagFile *next; + char *path; + struct tagFile *next; } *file_list = NULL; static void set_failure_reason(char *reason) { if (failure_reason) - free(failure_reason); + free(failure_reason); failure_reason = strdup(reason); success = FALSE; } static char *get_failure_reason() { if (!failure_reason) - return "Installation failed."; + return "Installation failed."; return failure_reason; } static void add_to_filelist(char *path) { - struct tagFile *p; - p = (struct tagFile *)malloc(sizeof(struct tagFile)); - p->path = strdup(path); - p->next = file_list; - file_list = p; + struct tagFile *p; + p = (struct tagFile *)malloc(sizeof(struct tagFile)); + p->path = strdup(path); + p->next = file_list; + file_list = p; } static int do_compile_files(int (__cdecl * PyRun_SimpleString)(char *), - int optimize) + int optimize) { - struct tagFile *p; - int total, n; - char Buffer[MAX_PATH + 64]; - int errors = 0; - - total = 0; - p = file_list; - while (p) { - ++total; - p = p->next; - } - SendDlgItemMessage(hDialog, IDC_PROGRESS, PBM_SETRANGE, 0, - MAKELPARAM(0, total)); - SendDlgItemMessage(hDialog, IDC_PROGRESS, PBM_SETPOS, 0, 0); - - n = 0; - p = file_list; - while (p) { - ++n; - wsprintf(Buffer, - "import py_compile; py_compile.compile (r'%s')", - p->path); - if (PyRun_SimpleString(Buffer)) { - ++errors; - } - /* We send the notification even if the files could not - * be created so that the uninstaller will remove them - * in case they are created later. - */ - wsprintf(Buffer, "%s%c", p->path, optimize ? 'o' : 'c'); - notify(FILE_CREATED, Buffer); - - SendDlgItemMessage(hDialog, IDC_PROGRESS, PBM_SETPOS, n, 0); - SetDlgItemText(hDialog, IDC_INFO, p->path); - p = p->next; - } - return errors; + struct tagFile *p; + int total, n; + char Buffer[MAX_PATH + 64]; + int errors = 0; + + total = 0; + p = file_list; + while (p) { + ++total; + p = p->next; + } + SendDlgItemMessage(hDialog, IDC_PROGRESS, PBM_SETRANGE, 0, + MAKELPARAM(0, total)); + SendDlgItemMessage(hDialog, IDC_PROGRESS, PBM_SETPOS, 0, 0); + + n = 0; + p = file_list; + while (p) { + ++n; + wsprintf(Buffer, + "import py_compile; py_compile.compile (r'%s')", + p->path); + if (PyRun_SimpleString(Buffer)) { + ++errors; + } + /* We send the notification even if the files could not + * be created so that the uninstaller will remove them + * in case they are created later. + */ + wsprintf(Buffer, "%s%c", p->path, optimize ? 'o' : 'c'); + notify(FILE_CREATED, Buffer); + + SendDlgItemMessage(hDialog, IDC_PROGRESS, PBM_SETPOS, n, 0); + SetDlgItemText(hDialog, IDC_INFO, p->path); + p = p->next; + } + return errors; } #define DECLPROC(dll, result, name, args)\ @@ -304,22 +304,22 @@ // Result string must be free'd wchar_t *widen_string(char *src) { - wchar_t *result; - DWORD dest_cch; - int src_len = strlen(src) + 1; // include NULL term in all ops - /* use MultiByteToWideChar() to see how much we need. */ - /* NOTE: this will include the null-term in the length */ - dest_cch = MultiByteToWideChar(CP_ACP, 0, src, src_len, NULL, 0); - // alloc the buffer - result = (wchar_t *)malloc(dest_cch * sizeof(wchar_t)); - if (result==NULL) - return NULL; - /* do the conversion */ - if (0==MultiByteToWideChar(CP_ACP, 0, src, src_len, result, dest_cch)) { - free(result); - return NULL; - } - return result; + wchar_t *result; + DWORD dest_cch; + int src_len = strlen(src) + 1; // include NULL term in all ops + /* use MultiByteToWideChar() to see how much we need. */ + /* NOTE: this will include the null-term in the length */ + dest_cch = MultiByteToWideChar(CP_ACP, 0, src, src_len, NULL, 0); + // alloc the buffer + result = (wchar_t *)malloc(dest_cch * sizeof(wchar_t)); + if (result==NULL) + return NULL; + /* do the conversion */ + if (0==MultiByteToWideChar(CP_ACP, 0, src, src_len, result, dest_cch)) { + free(result); + return NULL; + } + return result; } /* @@ -328,47 +328,47 @@ */ static int compile_filelist(HINSTANCE hPython, BOOL optimize_flag) { - DECLPROC(hPython, void, Py_Initialize, (void)); - DECLPROC(hPython, void, Py_SetProgramName, (wchar_t *)); - DECLPROC(hPython, void, Py_Finalize, (void)); - DECLPROC(hPython, int, PyRun_SimpleString, (char *)); - DECLPROC(hPython, PyObject *, PySys_GetObject, (char *)); - DECLVAR(hPython, int, Py_OptimizeFlag); + DECLPROC(hPython, void, Py_Initialize, (void)); + DECLPROC(hPython, void, Py_SetProgramName, (wchar_t *)); + DECLPROC(hPython, void, Py_Finalize, (void)); + DECLPROC(hPython, int, PyRun_SimpleString, (char *)); + DECLPROC(hPython, PyObject *, PySys_GetObject, (char *)); + DECLVAR(hPython, int, Py_OptimizeFlag); - int errors = 0; - struct tagFile *p = file_list; + int errors = 0; + struct tagFile *p = file_list; - if (!p) - return 0; + if (!p) + return 0; - if (!Py_Initialize || !Py_SetProgramName || !Py_Finalize) - return -1; + if (!Py_Initialize || !Py_SetProgramName || !Py_Finalize) + return -1; - if (!PyRun_SimpleString || !PySys_GetObject || !Py_OptimizeFlag) - return -1; + if (!PyRun_SimpleString || !PySys_GetObject || !Py_OptimizeFlag) + return -1; - *Py_OptimizeFlag = optimize_flag ? 1 : 0; - Py_SetProgramName(wmodulename); - Py_Initialize(); + *Py_OptimizeFlag = optimize_flag ? 1 : 0; + Py_SetProgramName(wmodulename); + Py_Initialize(); - errors += do_compile_files(PyRun_SimpleString, optimize_flag); - Py_Finalize(); + errors += do_compile_files(PyRun_SimpleString, optimize_flag); + Py_Finalize(); - return errors; + return errors; } typedef PyObject *(*PyCFunction)(PyObject *, PyObject *); struct PyMethodDef { - char *ml_name; - PyCFunction ml_meth; - int ml_flags; - char *ml_doc; + char *ml_name; + PyCFunction ml_meth; + int ml_flags; + char *ml_doc; }; typedef struct PyMethodDef PyMethodDef; // XXX - all of these are potentially fragile! We load and unload -// the Python DLL multiple times - so storing functions pointers +// the Python DLL multiple times - so storing functions pointers // is dangerous (although things *look* OK at present) // Better might be to roll prepare_script_environment() into // LoadPythonDll(), and create a new UnloadPythonDLL() which also @@ -385,249 +385,249 @@ #define DEF_CSIDL(name) { name, #name } struct { - int nFolder; - char *name; + int nFolder; + char *name; } csidl_names[] = { - /* Startup menu for all users. - NT only */ - DEF_CSIDL(CSIDL_COMMON_STARTMENU), - /* Startup menu. */ - DEF_CSIDL(CSIDL_STARTMENU), + /* Startup menu for all users. + NT only */ + DEF_CSIDL(CSIDL_COMMON_STARTMENU), + /* Startup menu. */ + DEF_CSIDL(CSIDL_STARTMENU), /* DEF_CSIDL(CSIDL_COMMON_APPDATA), */ /* DEF_CSIDL(CSIDL_LOCAL_APPDATA), */ - /* Repository for application-specific data. - Needs Internet Explorer 4.0 */ - DEF_CSIDL(CSIDL_APPDATA), - - /* The desktop for all users. - NT only */ - DEF_CSIDL(CSIDL_COMMON_DESKTOPDIRECTORY), - /* The desktop. */ - DEF_CSIDL(CSIDL_DESKTOPDIRECTORY), - - /* Startup folder for all users. - NT only */ - DEF_CSIDL(CSIDL_COMMON_STARTUP), - /* Startup folder. */ - DEF_CSIDL(CSIDL_STARTUP), - - /* Programs item in the start menu for all users. - NT only */ - DEF_CSIDL(CSIDL_COMMON_PROGRAMS), - /* Program item in the user's start menu. */ - DEF_CSIDL(CSIDL_PROGRAMS), + /* Repository for application-specific data. + Needs Internet Explorer 4.0 */ + DEF_CSIDL(CSIDL_APPDATA), + + /* The desktop for all users. + NT only */ + DEF_CSIDL(CSIDL_COMMON_DESKTOPDIRECTORY), + /* The desktop. */ + DEF_CSIDL(CSIDL_DESKTOPDIRECTORY), + + /* Startup folder for all users. + NT only */ + DEF_CSIDL(CSIDL_COMMON_STARTUP), + /* Startup folder. */ + DEF_CSIDL(CSIDL_STARTUP), + + /* Programs item in the start menu for all users. + NT only */ + DEF_CSIDL(CSIDL_COMMON_PROGRAMS), + /* Program item in the user's start menu. */ + DEF_CSIDL(CSIDL_PROGRAMS), /* DEF_CSIDL(CSIDL_PROGRAM_FILES_COMMON), */ /* DEF_CSIDL(CSIDL_PROGRAM_FILES), */ - /* Virtual folder containing fonts. */ - DEF_CSIDL(CSIDL_FONTS), + /* Virtual folder containing fonts. */ + DEF_CSIDL(CSIDL_FONTS), }; #define DIM(a) (sizeof(a) / sizeof((a)[0])) static PyObject *FileCreated(PyObject *self, PyObject *args) { - char *path; - if (!g_PyArg_ParseTuple(args, "s", &path)) - return NULL; - notify(FILE_CREATED, path); - return g_Py_BuildValue(""); + char *path; + if (!g_PyArg_ParseTuple(args, "s", &path)) + return NULL; + notify(FILE_CREATED, path); + return g_Py_BuildValue(""); } static PyObject *DirectoryCreated(PyObject *self, PyObject *args) { - char *path; - if (!g_PyArg_ParseTuple(args, "s", &path)) - return NULL; - notify(DIR_CREATED, path); - return g_Py_BuildValue(""); + char *path; + if (!g_PyArg_ParseTuple(args, "s", &path)) + return NULL; + notify(DIR_CREATED, path); + return g_Py_BuildValue(""); } static PyObject *GetSpecialFolderPath(PyObject *self, PyObject *args) { - char *name; - char lpszPath[MAX_PATH]; - int i; - static HRESULT (WINAPI *My_SHGetSpecialFolderPath)(HWND hwnd, - LPTSTR lpszPath, - int nFolder, - BOOL fCreate); - - if (!My_SHGetSpecialFolderPath) { - HINSTANCE hLib = LoadLibrary("shell32.dll"); - if (!hLib) { - g_PyErr_Format(g_PyExc_OSError, - "function not available"); - return NULL; - } - My_SHGetSpecialFolderPath = (BOOL (WINAPI *)(HWND, LPTSTR, - int, BOOL)) - GetProcAddress(hLib, - "SHGetSpecialFolderPathA"); - } - - if (!g_PyArg_ParseTuple(args, "s", &name)) - return NULL; - - if (!My_SHGetSpecialFolderPath) { - g_PyErr_Format(g_PyExc_OSError, "function not available"); - return NULL; - } - - for (i = 0; i < DIM(csidl_names); ++i) { - if (0 == strcmpi(csidl_names[i].name, name)) { - int nFolder; - nFolder = csidl_names[i].nFolder; - if (My_SHGetSpecialFolderPath(NULL, lpszPath, - nFolder, 0)) - return g_Py_BuildValue("s", lpszPath); - else { - g_PyErr_Format(g_PyExc_OSError, - "no such folder (%s)", name); - return NULL; - } - - } - }; - g_PyErr_Format(g_PyExc_ValueError, "unknown CSIDL (%s)", name); - return NULL; + char *name; + char lpszPath[MAX_PATH]; + int i; + static HRESULT (WINAPI *My_SHGetSpecialFolderPath)(HWND hwnd, + LPTSTR lpszPath, + int nFolder, + BOOL fCreate); + + if (!My_SHGetSpecialFolderPath) { + HINSTANCE hLib = LoadLibrary("shell32.dll"); + if (!hLib) { + g_PyErr_Format(g_PyExc_OSError, + "function not available"); + return NULL; + } + My_SHGetSpecialFolderPath = (BOOL (WINAPI *)(HWND, LPTSTR, + int, BOOL)) + GetProcAddress(hLib, + "SHGetSpecialFolderPathA"); + } + + if (!g_PyArg_ParseTuple(args, "s", &name)) + return NULL; + + if (!My_SHGetSpecialFolderPath) { + g_PyErr_Format(g_PyExc_OSError, "function not available"); + return NULL; + } + + for (i = 0; i < DIM(csidl_names); ++i) { + if (0 == strcmpi(csidl_names[i].name, name)) { + int nFolder; + nFolder = csidl_names[i].nFolder; + if (My_SHGetSpecialFolderPath(NULL, lpszPath, + nFolder, 0)) + return g_Py_BuildValue("s", lpszPath); + else { + g_PyErr_Format(g_PyExc_OSError, + "no such folder (%s)", name); + return NULL; + } + + } + }; + g_PyErr_Format(g_PyExc_ValueError, "unknown CSIDL (%s)", name); + return NULL; } static PyObject *CreateShortcut(PyObject *self, PyObject *args) { - char *path; /* path and filename */ - char *description; - char *filename; - - char *arguments = NULL; - char *iconpath = NULL; - int iconindex = 0; - char *workdir = NULL; - - WCHAR wszFilename[MAX_PATH]; - - IShellLink *ps1 = NULL; - IPersistFile *pPf = NULL; - - HRESULT hr; - - hr = CoInitialize(NULL); - if (FAILED(hr)) { - g_PyErr_Format(g_PyExc_OSError, - "CoInitialize failed, error 0x%x", hr); - goto error; - } - - if (!g_PyArg_ParseTuple(args, "sss|sssi", - &path, &description, &filename, - &arguments, &workdir, &iconpath, &iconindex)) - return NULL; - - hr = CoCreateInstance(&CLSID_ShellLink, - NULL, - CLSCTX_INPROC_SERVER, - &IID_IShellLink, - &ps1); - if (FAILED(hr)) { - g_PyErr_Format(g_PyExc_OSError, - "CoCreateInstance failed, error 0x%x", hr); - goto error; - } - - hr = ps1->lpVtbl->QueryInterface(ps1, &IID_IPersistFile, - (void **)&pPf); - if (FAILED(hr)) { - g_PyErr_Format(g_PyExc_OSError, - "QueryInterface(IPersistFile) error 0x%x", hr); - goto error; - } - - - hr = ps1->lpVtbl->SetPath(ps1, path); - if (FAILED(hr)) { - g_PyErr_Format(g_PyExc_OSError, - "SetPath() failed, error 0x%x", hr); - goto error; - } - - hr = ps1->lpVtbl->SetDescription(ps1, description); - if (FAILED(hr)) { - g_PyErr_Format(g_PyExc_OSError, - "SetDescription() failed, error 0x%x", hr); - goto error; - } - - if (arguments) { - hr = ps1->lpVtbl->SetArguments(ps1, arguments); - if (FAILED(hr)) { - g_PyErr_Format(g_PyExc_OSError, - "SetArguments() error 0x%x", hr); - goto error; - } - } - - if (iconpath) { - hr = ps1->lpVtbl->SetIconLocation(ps1, iconpath, iconindex); - if (FAILED(hr)) { - g_PyErr_Format(g_PyExc_OSError, - "SetIconLocation() error 0x%x", hr); - goto error; - } - } - - if (workdir) { - hr = ps1->lpVtbl->SetWorkingDirectory(ps1, workdir); - if (FAILED(hr)) { - g_PyErr_Format(g_PyExc_OSError, - "SetWorkingDirectory() error 0x%x", hr); - goto error; - } - } - - MultiByteToWideChar(CP_ACP, 0, - filename, -1, - wszFilename, MAX_PATH); - - hr = pPf->lpVtbl->Save(pPf, wszFilename, TRUE); - if (FAILED(hr)) { - g_PyErr_Format(g_PyExc_OSError, - "Failed to create shortcut '%s' - error 0x%x", filename, hr); - goto error; - } - - pPf->lpVtbl->Release(pPf); - ps1->lpVtbl->Release(ps1); - CoUninitialize(); - return g_Py_BuildValue(""); - + char *path; /* path and filename */ + char *description; + char *filename; + + char *arguments = NULL; + char *iconpath = NULL; + int iconindex = 0; + char *workdir = NULL; + + WCHAR wszFilename[MAX_PATH]; + + IShellLink *ps1 = NULL; + IPersistFile *pPf = NULL; + + HRESULT hr; + + hr = CoInitialize(NULL); + if (FAILED(hr)) { + g_PyErr_Format(g_PyExc_OSError, + "CoInitialize failed, error 0x%x", hr); + goto error; + } + + if (!g_PyArg_ParseTuple(args, "sss|sssi", + &path, &description, &filename, + &arguments, &workdir, &iconpath, &iconindex)) + return NULL; + + hr = CoCreateInstance(&CLSID_ShellLink, + NULL, + CLSCTX_INPROC_SERVER, + &IID_IShellLink, + &ps1); + if (FAILED(hr)) { + g_PyErr_Format(g_PyExc_OSError, + "CoCreateInstance failed, error 0x%x", hr); + goto error; + } + + hr = ps1->lpVtbl->QueryInterface(ps1, &IID_IPersistFile, + (void **)&pPf); + if (FAILED(hr)) { + g_PyErr_Format(g_PyExc_OSError, + "QueryInterface(IPersistFile) error 0x%x", hr); + goto error; + } + + + hr = ps1->lpVtbl->SetPath(ps1, path); + if (FAILED(hr)) { + g_PyErr_Format(g_PyExc_OSError, + "SetPath() failed, error 0x%x", hr); + goto error; + } + + hr = ps1->lpVtbl->SetDescription(ps1, description); + if (FAILED(hr)) { + g_PyErr_Format(g_PyExc_OSError, + "SetDescription() failed, error 0x%x", hr); + goto error; + } + + if (arguments) { + hr = ps1->lpVtbl->SetArguments(ps1, arguments); + if (FAILED(hr)) { + g_PyErr_Format(g_PyExc_OSError, + "SetArguments() error 0x%x", hr); + goto error; + } + } + + if (iconpath) { + hr = ps1->lpVtbl->SetIconLocation(ps1, iconpath, iconindex); + if (FAILED(hr)) { + g_PyErr_Format(g_PyExc_OSError, + "SetIconLocation() error 0x%x", hr); + goto error; + } + } + + if (workdir) { + hr = ps1->lpVtbl->SetWorkingDirectory(ps1, workdir); + if (FAILED(hr)) { + g_PyErr_Format(g_PyExc_OSError, + "SetWorkingDirectory() error 0x%x", hr); + goto error; + } + } + + MultiByteToWideChar(CP_ACP, 0, + filename, -1, + wszFilename, MAX_PATH); + + hr = pPf->lpVtbl->Save(pPf, wszFilename, TRUE); + if (FAILED(hr)) { + g_PyErr_Format(g_PyExc_OSError, + "Failed to create shortcut '%s' - error 0x%x", filename, hr); + goto error; + } + + pPf->lpVtbl->Release(pPf); + ps1->lpVtbl->Release(ps1); + CoUninitialize(); + return g_Py_BuildValue(""); + error: - if (pPf) - pPf->lpVtbl->Release(pPf); + if (pPf) + pPf->lpVtbl->Release(pPf); - if (ps1) - ps1->lpVtbl->Release(ps1); + if (ps1) + ps1->lpVtbl->Release(ps1); - CoUninitialize(); + CoUninitialize(); - return NULL; + return NULL; } static PyObject *PyMessageBox(PyObject *self, PyObject *args) { - int rc; - char *text, *caption; - int flags; - if (!g_PyArg_ParseTuple(args, "ssi", &text, &caption, &flags)) - return NULL; - rc = MessageBox(GetFocus(), text, caption, flags); - return g_Py_BuildValue("i", rc); + int rc; + char *text, *caption; + int flags; + if (!g_PyArg_ParseTuple(args, "ssi", &text, &caption, &flags)) + return NULL; + rc = MessageBox(GetFocus(), text, caption, flags); + return g_Py_BuildValue("i", rc); } static PyObject *GetRootHKey(PyObject *self) { - return g_PyLong_FromVoidPtr(hkey_root); + return g_PyLong_FromVoidPtr(hkey_root); } #define METH_VARARGS 0x0001 @@ -635,74 +635,74 @@ typedef PyObject *(*PyCFunction)(PyObject *, PyObject *); PyMethodDef meth[] = { - {"create_shortcut", CreateShortcut, METH_VARARGS, NULL}, - {"get_special_folder_path", GetSpecialFolderPath, METH_VARARGS, NULL}, - {"get_root_hkey", (PyCFunction)GetRootHKey, METH_NOARGS, NULL}, - {"file_created", FileCreated, METH_VARARGS, NULL}, - {"directory_created", DirectoryCreated, METH_VARARGS, NULL}, - {"message_box", PyMessageBox, METH_VARARGS, NULL}, + {"create_shortcut", CreateShortcut, METH_VARARGS, NULL}, + {"get_special_folder_path", GetSpecialFolderPath, METH_VARARGS, NULL}, + {"get_root_hkey", (PyCFunction)GetRootHKey, METH_NOARGS, NULL}, + {"file_created", FileCreated, METH_VARARGS, NULL}, + {"directory_created", DirectoryCreated, METH_VARARGS, NULL}, + {"message_box", PyMessageBox, METH_VARARGS, NULL}, }; static HINSTANCE LoadPythonDll(char *fname) { - char fullpath[_MAX_PATH]; - LONG size = sizeof(fullpath); - char subkey_name[80]; - char buffer[260 + 12]; - HINSTANCE h; - - /* make sure PYTHONHOME is set, to that sys.path is initialized correctly */ - wsprintf(buffer, "PYTHONHOME=%s", python_dir); - _putenv(buffer); - h = LoadLibrary(fname); - if (h) - return h; - wsprintf(subkey_name, - "SOFTWARE\\Python\\PythonCore\\%d.%d\\InstallPath", - py_major, py_minor); - if (ERROR_SUCCESS != RegQueryValue(HKEY_CURRENT_USER, subkey_name, - fullpath, &size) && - ERROR_SUCCESS != RegQueryValue(HKEY_LOCAL_MACHINE, subkey_name, - fullpath, &size)) - return NULL; - strcat(fullpath, "\\"); - strcat(fullpath, fname); - return LoadLibrary(fullpath); + char fullpath[_MAX_PATH]; + LONG size = sizeof(fullpath); + char subkey_name[80]; + char buffer[260 + 12]; + HINSTANCE h; + + /* make sure PYTHONHOME is set, to that sys.path is initialized correctly */ + wsprintf(buffer, "PYTHONHOME=%s", python_dir); + _putenv(buffer); + h = LoadLibrary(fname); + if (h) + return h; + wsprintf(subkey_name, + "SOFTWARE\\Python\\PythonCore\\%d.%d\\InstallPath", + py_major, py_minor); + if (ERROR_SUCCESS != RegQueryValue(HKEY_CURRENT_USER, subkey_name, + fullpath, &size) && + ERROR_SUCCESS != RegQueryValue(HKEY_LOCAL_MACHINE, subkey_name, + fullpath, &size)) + return NULL; + strcat(fullpath, "\\"); + strcat(fullpath, fname); + return LoadLibrary(fullpath); } static int prepare_script_environment(HINSTANCE hPython) { - PyObject *mod; - DECLPROC(hPython, PyObject *, PyImport_ImportModule, (char *)); - DECLPROC(hPython, int, PyObject_SetAttrString, (PyObject *, char *, PyObject *)); - DECLPROC(hPython, PyObject *, PyObject_GetAttrString, (PyObject *, char *)); - DECLPROC(hPython, PyObject *, PyCFunction_New, (PyMethodDef *, PyObject *)); - DECLPROC(hPython, PyObject *, Py_BuildValue, (char *, ...)); - DECLPROC(hPython, int, PyArg_ParseTuple, (PyObject *, char *, ...)); - DECLPROC(hPython, PyObject *, PyErr_Format, (PyObject *, char *)); - DECLPROC(hPython, PyObject *, PyLong_FromVoidPtr, (void *)); - if (!PyImport_ImportModule || !PyObject_GetAttrString || - !PyObject_SetAttrString || !PyCFunction_New) - return 1; - if (!Py_BuildValue || !PyArg_ParseTuple || !PyErr_Format) - return 1; - - mod = PyImport_ImportModule("builtins"); - if (mod) { - int i; - g_PyExc_ValueError = PyObject_GetAttrString(mod, "ValueError"); - g_PyExc_OSError = PyObject_GetAttrString(mod, "OSError"); - for (i = 0; i < DIM(meth); ++i) { - PyObject_SetAttrString(mod, meth[i].ml_name, - PyCFunction_New(&meth[i], NULL)); - } - } - g_Py_BuildValue = Py_BuildValue; - g_PyArg_ParseTuple = PyArg_ParseTuple; - g_PyErr_Format = PyErr_Format; - g_PyLong_FromVoidPtr = PyLong_FromVoidPtr; + PyObject *mod; + DECLPROC(hPython, PyObject *, PyImport_ImportModule, (char *)); + DECLPROC(hPython, int, PyObject_SetAttrString, (PyObject *, char *, PyObject *)); + DECLPROC(hPython, PyObject *, PyObject_GetAttrString, (PyObject *, char *)); + DECLPROC(hPython, PyObject *, PyCFunction_New, (PyMethodDef *, PyObject *)); + DECLPROC(hPython, PyObject *, Py_BuildValue, (char *, ...)); + DECLPROC(hPython, int, PyArg_ParseTuple, (PyObject *, char *, ...)); + DECLPROC(hPython, PyObject *, PyErr_Format, (PyObject *, char *)); + DECLPROC(hPython, PyObject *, PyLong_FromVoidPtr, (void *)); + if (!PyImport_ImportModule || !PyObject_GetAttrString || + !PyObject_SetAttrString || !PyCFunction_New) + return 1; + if (!Py_BuildValue || !PyArg_ParseTuple || !PyErr_Format) + return 1; + + mod = PyImport_ImportModule("builtins"); + if (mod) { + int i; + g_PyExc_ValueError = PyObject_GetAttrString(mod, "ValueError"); + g_PyExc_OSError = PyObject_GetAttrString(mod, "OSError"); + for (i = 0; i < DIM(meth); ++i) { + PyObject_SetAttrString(mod, meth[i].ml_name, + PyCFunction_New(&meth[i], NULL)); + } + } + g_Py_BuildValue = Py_BuildValue; + g_PyArg_ParseTuple = PyArg_ParseTuple; + g_PyErr_Format = PyErr_Format; + g_PyLong_FromVoidPtr = PyLong_FromVoidPtr; - return 0; + return 0; } /* @@ -718,483 +718,483 @@ static int do_run_installscript(HINSTANCE hPython, char *pathname, int argc, char **argv) { - int fh, result, i; - static wchar_t *wargv[256]; - DECLPROC(hPython, void, Py_Initialize, (void)); - DECLPROC(hPython, int, PySys_SetArgv, (int, wchar_t **)); - DECLPROC(hPython, int, PyRun_SimpleString, (char *)); - DECLPROC(hPython, void, Py_Finalize, (void)); - DECLPROC(hPython, PyObject *, Py_BuildValue, (char *, ...)); - DECLPROC(hPython, PyObject *, PyCFunction_New, - (PyMethodDef *, PyObject *)); - DECLPROC(hPython, int, PyArg_ParseTuple, (PyObject *, char *, ...)); - DECLPROC(hPython, PyObject *, PyErr_Format, (PyObject *, char *)); - - if (!Py_Initialize || !PySys_SetArgv - || !PyRun_SimpleString || !Py_Finalize) - return 1; - - if (!Py_BuildValue || !PyArg_ParseTuple || !PyErr_Format) - return 1; - - if (!PyCFunction_New || !PyArg_ParseTuple || !PyErr_Format) - return 1; - - if (pathname == NULL || pathname[0] == '\0') - return 2; - - fh = open(pathname, _O_RDONLY); - if (-1 == fh) { - fprintf(stderr, "Could not open postinstall-script %s\n", - pathname); - return 3; - } - - SetDlgItemText(hDialog, IDC_INFO, "Running Script..."); - - Py_Initialize(); - - prepare_script_environment(hPython); - // widen the argv array for py3k. - memset(wargv, 0, sizeof(wargv)); - for (i=0;i 0) { - script[n] = '\n'; - script[n+1] = 0; - result = PyRun_SimpleString(script); - } - } - } - Py_Finalize(); + int fh, result, i; + static wchar_t *wargv[256]; + DECLPROC(hPython, void, Py_Initialize, (void)); + DECLPROC(hPython, int, PySys_SetArgv, (int, wchar_t **)); + DECLPROC(hPython, int, PyRun_SimpleString, (char *)); + DECLPROC(hPython, void, Py_Finalize, (void)); + DECLPROC(hPython, PyObject *, Py_BuildValue, (char *, ...)); + DECLPROC(hPython, PyObject *, PyCFunction_New, + (PyMethodDef *, PyObject *)); + DECLPROC(hPython, int, PyArg_ParseTuple, (PyObject *, char *, ...)); + DECLPROC(hPython, PyObject *, PyErr_Format, (PyObject *, char *)); + + if (!Py_Initialize || !PySys_SetArgv + || !PyRun_SimpleString || !Py_Finalize) + return 1; + + if (!Py_BuildValue || !PyArg_ParseTuple || !PyErr_Format) + return 1; + + if (!PyCFunction_New || !PyArg_ParseTuple || !PyErr_Format) + return 1; + + if (pathname == NULL || pathname[0] == '\0') + return 2; + + fh = open(pathname, _O_RDONLY); + if (-1 == fh) { + fprintf(stderr, "Could not open postinstall-script %s\n", + pathname); + return 3; + } + + SetDlgItemText(hDialog, IDC_INFO, "Running Script..."); + + Py_Initialize(); + + prepare_script_environment(hPython); + // widen the argv array for py3k. + memset(wargv, 0, sizeof(wargv)); + for (i=0;i 0) { + script[n] = '\n'; + script[n+1] = 0; + result = PyRun_SimpleString(script); + } + } + } + Py_Finalize(); - close(fh); - return result; + close(fh); + return result; } static int run_installscript(char *pathname, int argc, char **argv, char **pOutput) { - HINSTANCE hPython; - int result = 1; - int out_buf_size; - HANDLE redirected, old_stderr, old_stdout; - char *tempname; - - *pOutput = NULL; - - tempname = tempnam(NULL, NULL); - // We use a static CRT while the Python version we load uses - // the CRT from one of various possibile DLLs. As a result we - // need to redirect the standard handles using the API rather - // than the CRT. - redirected = CreateFile( - tempname, - GENERIC_WRITE | GENERIC_READ, - FILE_SHARE_READ, - NULL, - CREATE_ALWAYS, - FILE_ATTRIBUTE_NORMAL | FILE_FLAG_WRITE_THROUGH, - NULL); - old_stdout = GetStdHandle(STD_OUTPUT_HANDLE); - old_stderr = GetStdHandle(STD_ERROR_HANDLE); - SetStdHandle(STD_OUTPUT_HANDLE, redirected); - SetStdHandle(STD_ERROR_HANDLE, redirected); - - hPython = LoadPythonDll(pythondll); - if (hPython) { - result = do_run_installscript(hPython, pathname, argc, argv); - FreeLibrary(hPython); - } else { - fprintf(stderr, "*** Could not load Python ***"); - } - SetStdHandle(STD_OUTPUT_HANDLE, old_stdout); - SetStdHandle(STD_ERROR_HANDLE, old_stderr); - out_buf_size = min(GetFileSize(redirected, NULL), 4096); - *pOutput = malloc(out_buf_size+1); - if (*pOutput) { - DWORD nread = 0; - SetFilePointer(redirected, 0, 0, FILE_BEGIN); - ReadFile(redirected, *pOutput, out_buf_size, &nread, NULL); - (*pOutput)[nread] = '\0'; - } - CloseHandle(redirected); - DeleteFile(tempname); - return result; + HINSTANCE hPython; + int result = 1; + int out_buf_size; + HANDLE redirected, old_stderr, old_stdout; + char *tempname; + + *pOutput = NULL; + + tempname = tempnam(NULL, NULL); + // We use a static CRT while the Python version we load uses + // the CRT from one of various possibile DLLs. As a result we + // need to redirect the standard handles using the API rather + // than the CRT. + redirected = CreateFile( + tempname, + GENERIC_WRITE | GENERIC_READ, + FILE_SHARE_READ, + NULL, + CREATE_ALWAYS, + FILE_ATTRIBUTE_NORMAL | FILE_FLAG_WRITE_THROUGH, + NULL); + old_stdout = GetStdHandle(STD_OUTPUT_HANDLE); + old_stderr = GetStdHandle(STD_ERROR_HANDLE); + SetStdHandle(STD_OUTPUT_HANDLE, redirected); + SetStdHandle(STD_ERROR_HANDLE, redirected); + + hPython = LoadPythonDll(pythondll); + if (hPython) { + result = do_run_installscript(hPython, pathname, argc, argv); + FreeLibrary(hPython); + } else { + fprintf(stderr, "*** Could not load Python ***"); + } + SetStdHandle(STD_OUTPUT_HANDLE, old_stdout); + SetStdHandle(STD_ERROR_HANDLE, old_stderr); + out_buf_size = min(GetFileSize(redirected, NULL), 4096); + *pOutput = malloc(out_buf_size+1); + if (*pOutput) { + DWORD nread = 0; + SetFilePointer(redirected, 0, 0, FILE_BEGIN); + ReadFile(redirected, *pOutput, out_buf_size, &nread, NULL); + (*pOutput)[nread] = '\0'; + } + CloseHandle(redirected); + DeleteFile(tempname); + return result; } static int do_run_simple_script(HINSTANCE hPython, char *script) { - int rc; - DECLPROC(hPython, void, Py_Initialize, (void)); - DECLPROC(hPython, void, Py_SetProgramName, (wchar_t *)); - DECLPROC(hPython, void, Py_Finalize, (void)); - DECLPROC(hPython, int, PyRun_SimpleString, (char *)); - DECLPROC(hPython, void, PyErr_Print, (void)); - - if (!Py_Initialize || !Py_SetProgramName || !Py_Finalize || - !PyRun_SimpleString || !PyErr_Print) - return -1; - - Py_SetProgramName(wmodulename); - Py_Initialize(); - prepare_script_environment(hPython); - rc = PyRun_SimpleString(script); - if (rc) - PyErr_Print(); - Py_Finalize(); - return rc; + int rc; + DECLPROC(hPython, void, Py_Initialize, (void)); + DECLPROC(hPython, void, Py_SetProgramName, (wchar_t *)); + DECLPROC(hPython, void, Py_Finalize, (void)); + DECLPROC(hPython, int, PyRun_SimpleString, (char *)); + DECLPROC(hPython, void, PyErr_Print, (void)); + + if (!Py_Initialize || !Py_SetProgramName || !Py_Finalize || + !PyRun_SimpleString || !PyErr_Print) + return -1; + + Py_SetProgramName(wmodulename); + Py_Initialize(); + prepare_script_environment(hPython); + rc = PyRun_SimpleString(script); + if (rc) + PyErr_Print(); + Py_Finalize(); + return rc; } static int run_simple_script(char *script) { - int rc; - HINSTANCE hPython; - char *tempname = tempnam(NULL, NULL); - // Redirect output using win32 API - see comments above... - HANDLE redirected = CreateFile( - tempname, - GENERIC_WRITE | GENERIC_READ, - FILE_SHARE_READ, - NULL, - CREATE_ALWAYS, - FILE_ATTRIBUTE_NORMAL | FILE_FLAG_WRITE_THROUGH, - NULL); - HANDLE old_stdout = GetStdHandle(STD_OUTPUT_HANDLE); - HANDLE old_stderr = GetStdHandle(STD_ERROR_HANDLE); - SetStdHandle(STD_OUTPUT_HANDLE, redirected); - SetStdHandle(STD_ERROR_HANDLE, redirected); - - hPython = LoadPythonDll(pythondll); - if (!hPython) { - char reason[128]; - wsprintf(reason, "Can't load Python for pre-install script (%d)", GetLastError()); - set_failure_reason(reason); - return -1; - } - rc = do_run_simple_script(hPython, script); - FreeLibrary(hPython); - SetStdHandle(STD_OUTPUT_HANDLE, old_stdout); - SetStdHandle(STD_ERROR_HANDLE, old_stderr); - /* We only care about the output when we fail. If the script works - OK, then we discard it - */ - if (rc) { - int err_buf_size; - char *err_buf; - const char *prefix = "Running the pre-installation script failed\r\n"; - int prefix_len = strlen(prefix); - err_buf_size = GetFileSize(redirected, NULL); - if (err_buf_size==INVALID_FILE_SIZE) // an error - let's try anyway... - err_buf_size = 4096; - err_buf = malloc(prefix_len + err_buf_size + 1); - if (err_buf) { - DWORD n = 0; - strcpy(err_buf, prefix); - SetFilePointer(redirected, 0, 0, FILE_BEGIN); - ReadFile(redirected, err_buf+prefix_len, err_buf_size, &n, NULL); - err_buf[prefix_len+n] = '\0'; - set_failure_reason(err_buf); - free(err_buf); - } else { - set_failure_reason("Out of memory!"); - } - } - CloseHandle(redirected); - DeleteFile(tempname); - return rc; + int rc; + HINSTANCE hPython; + char *tempname = tempnam(NULL, NULL); + // Redirect output using win32 API - see comments above... + HANDLE redirected = CreateFile( + tempname, + GENERIC_WRITE | GENERIC_READ, + FILE_SHARE_READ, + NULL, + CREATE_ALWAYS, + FILE_ATTRIBUTE_NORMAL | FILE_FLAG_WRITE_THROUGH, + NULL); + HANDLE old_stdout = GetStdHandle(STD_OUTPUT_HANDLE); + HANDLE old_stderr = GetStdHandle(STD_ERROR_HANDLE); + SetStdHandle(STD_OUTPUT_HANDLE, redirected); + SetStdHandle(STD_ERROR_HANDLE, redirected); + + hPython = LoadPythonDll(pythondll); + if (!hPython) { + char reason[128]; + wsprintf(reason, "Can't load Python for pre-install script (%d)", GetLastError()); + set_failure_reason(reason); + return -1; + } + rc = do_run_simple_script(hPython, script); + FreeLibrary(hPython); + SetStdHandle(STD_OUTPUT_HANDLE, old_stdout); + SetStdHandle(STD_ERROR_HANDLE, old_stderr); + /* We only care about the output when we fail. If the script works + OK, then we discard it + */ + if (rc) { + int err_buf_size; + char *err_buf; + const char *prefix = "Running the pre-installation script failed\r\n"; + int prefix_len = strlen(prefix); + err_buf_size = GetFileSize(redirected, NULL); + if (err_buf_size==INVALID_FILE_SIZE) // an error - let's try anyway... + err_buf_size = 4096; + err_buf = malloc(prefix_len + err_buf_size + 1); + if (err_buf) { + DWORD n = 0; + strcpy(err_buf, prefix); + SetFilePointer(redirected, 0, 0, FILE_BEGIN); + ReadFile(redirected, err_buf+prefix_len, err_buf_size, &n, NULL); + err_buf[prefix_len+n] = '\0'; + set_failure_reason(err_buf); + free(err_buf); + } else { + set_failure_reason("Out of memory!"); + } + } + CloseHandle(redirected); + DeleteFile(tempname); + return rc; } static BOOL SystemError(int error, char *msg) { - char Buffer[1024]; - int n; + char Buffer[1024]; + int n; - if (error) { - LPVOID lpMsgBuf; - FormatMessage( - FORMAT_MESSAGE_ALLOCATE_BUFFER | - FORMAT_MESSAGE_FROM_SYSTEM, - NULL, - error, - MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), - (LPSTR)&lpMsgBuf, - 0, - NULL - ); - strncpy(Buffer, lpMsgBuf, sizeof(Buffer)); - LocalFree(lpMsgBuf); - } else - Buffer[0] = '\0'; - n = lstrlen(Buffer); - _snprintf(Buffer+n, sizeof(Buffer)-n, msg); - MessageBox(hwndMain, Buffer, "Runtime Error", MB_OK | MB_ICONSTOP); - return FALSE; + if (error) { + LPVOID lpMsgBuf; + FormatMessage( + FORMAT_MESSAGE_ALLOCATE_BUFFER | + FORMAT_MESSAGE_FROM_SYSTEM, + NULL, + error, + MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), + (LPSTR)&lpMsgBuf, + 0, + NULL + ); + strncpy(Buffer, lpMsgBuf, sizeof(Buffer)); + LocalFree(lpMsgBuf); + } else + Buffer[0] = '\0'; + n = lstrlen(Buffer); + _snprintf(Buffer+n, sizeof(Buffer)-n, msg); + MessageBox(hwndMain, Buffer, "Runtime Error", MB_OK | MB_ICONSTOP); + return FALSE; } static BOOL notify (int code, char *fmt, ...) { - char Buffer[1024]; - va_list marker; - BOOL result = TRUE; - int a, b; - char *cp; + char Buffer[1024]; + va_list marker; + BOOL result = TRUE; + int a, b; + char *cp; - va_start(marker, fmt); - _vsnprintf(Buffer, sizeof(Buffer), fmt, marker); + va_start(marker, fmt); + _vsnprintf(Buffer, sizeof(Buffer), fmt, marker); - switch (code) { + switch (code) { /* Questions */ - case CAN_OVERWRITE: - break; + case CAN_OVERWRITE: + break; /* Information notification */ - case DIR_CREATED: - if (logfile) - fprintf(logfile, "100 Made Dir: %s\n", fmt); - break; - - case FILE_CREATED: - if (logfile) - fprintf(logfile, "200 File Copy: %s\n", fmt); - goto add_to_filelist_label; - break; - - case FILE_OVERWRITTEN: - if (logfile) - fprintf(logfile, "200 File Overwrite: %s\n", fmt); - add_to_filelist_label: - if ((cp = strrchr(fmt, '.')) && (0 == strcmp (cp, ".py"))) - add_to_filelist(fmt); - break; + case DIR_CREATED: + if (logfile) + fprintf(logfile, "100 Made Dir: %s\n", fmt); + break; + + case FILE_CREATED: + if (logfile) + fprintf(logfile, "200 File Copy: %s\n", fmt); + goto add_to_filelist_label; + break; + + case FILE_OVERWRITTEN: + if (logfile) + fprintf(logfile, "200 File Overwrite: %s\n", fmt); + add_to_filelist_label: + if ((cp = strrchr(fmt, '.')) && (0 == strcmp (cp, ".py"))) + add_to_filelist(fmt); + break; /* Error Messages */ - case ZLIB_ERROR: - MessageBox(GetFocus(), Buffer, "Error", - MB_OK | MB_ICONWARNING); - break; - - case SYSTEM_ERROR: - SystemError(GetLastError(), Buffer); - break; - - case NUM_FILES: - a = va_arg(marker, int); - b = va_arg(marker, int); - SendMessage(hDialog, WM_NUMFILES, 0, MAKELPARAM(0, a)); - SendMessage(hDialog, WM_NEXTFILE, b,(LPARAM)fmt); - } - va_end(marker); - - return result; + case ZLIB_ERROR: + MessageBox(GetFocus(), Buffer, "Error", + MB_OK | MB_ICONWARNING); + break; + + case SYSTEM_ERROR: + SystemError(GetLastError(), Buffer); + break; + + case NUM_FILES: + a = va_arg(marker, int); + b = va_arg(marker, int); + SendMessage(hDialog, WM_NUMFILES, 0, MAKELPARAM(0, a)); + SendMessage(hDialog, WM_NEXTFILE, b,(LPARAM)fmt); + } + va_end(marker); + + return result; } static char *MapExistingFile(char *pathname, DWORD *psize) { - HANDLE hFile, hFileMapping; - DWORD nSizeLow, nSizeHigh; - char *data; - - hFile = CreateFile(pathname, - GENERIC_READ, FILE_SHARE_READ, NULL, - OPEN_EXISTING, - FILE_ATTRIBUTE_NORMAL, NULL); - if (hFile == INVALID_HANDLE_VALUE) - return NULL; - nSizeLow = GetFileSize(hFile, &nSizeHigh); - hFileMapping = CreateFileMapping(hFile, - NULL, PAGE_READONLY, 0, 0, NULL); - CloseHandle(hFile); - - if (hFileMapping == INVALID_HANDLE_VALUE) - return NULL; - - data = MapViewOfFile(hFileMapping, - FILE_MAP_READ, 0, 0, 0); - - CloseHandle(hFileMapping); - *psize = nSizeLow; - return data; + HANDLE hFile, hFileMapping; + DWORD nSizeLow, nSizeHigh; + char *data; + + hFile = CreateFile(pathname, + GENERIC_READ, FILE_SHARE_READ, NULL, + OPEN_EXISTING, + FILE_ATTRIBUTE_NORMAL, NULL); + if (hFile == INVALID_HANDLE_VALUE) + return NULL; + nSizeLow = GetFileSize(hFile, &nSizeHigh); + hFileMapping = CreateFileMapping(hFile, + NULL, PAGE_READONLY, 0, 0, NULL); + CloseHandle(hFile); + + if (hFileMapping == INVALID_HANDLE_VALUE) + return NULL; + + data = MapViewOfFile(hFileMapping, + FILE_MAP_READ, 0, 0, 0); + + CloseHandle(hFileMapping); + *psize = nSizeLow; + return data; } static void create_bitmap(HWND hwnd) { - BITMAPFILEHEADER *bfh; - BITMAPINFO *bi; - HDC hdc; - - if (!bitmap_bytes) - return; - - if (hBitmap) - return; - - hdc = GetDC(hwnd); - - bfh = (BITMAPFILEHEADER *)bitmap_bytes; - bi = (BITMAPINFO *)(bitmap_bytes + sizeof(BITMAPFILEHEADER)); - - hBitmap = CreateDIBitmap(hdc, - &bi->bmiHeader, - CBM_INIT, - bitmap_bytes + bfh->bfOffBits, - bi, - DIB_RGB_COLORS); - ReleaseDC(hwnd, hdc); + BITMAPFILEHEADER *bfh; + BITMAPINFO *bi; + HDC hdc; + + if (!bitmap_bytes) + return; + + if (hBitmap) + return; + + hdc = GetDC(hwnd); + + bfh = (BITMAPFILEHEADER *)bitmap_bytes; + bi = (BITMAPINFO *)(bitmap_bytes + sizeof(BITMAPFILEHEADER)); + + hBitmap = CreateDIBitmap(hdc, + &bi->bmiHeader, + CBM_INIT, + bitmap_bytes + bfh->bfOffBits, + bi, + DIB_RGB_COLORS); + ReleaseDC(hwnd, hdc); } /* Extract everything we need to begin the installation. Currently this is the INI filename with install data, and the raw pre-install script */ static BOOL ExtractInstallData(char *data, DWORD size, int *pexe_size, - char **out_ini_file, char **out_preinstall_script) + char **out_ini_file, char **out_preinstall_script) { - /* read the end of central directory record */ - struct eof_cdir *pe = (struct eof_cdir *)&data[size - sizeof - (struct eof_cdir)]; - - int arc_start = size - sizeof (struct eof_cdir) - pe->nBytesCDir - - pe->ofsCDir; - - int ofs = arc_start - sizeof (struct meta_data_hdr); - - /* read meta_data info */ - struct meta_data_hdr *pmd = (struct meta_data_hdr *)&data[ofs]; - char *src, *dst; - char *ini_file; - char tempdir[MAX_PATH]; - - /* ensure that if we fail, we don't have garbage out pointers */ - *out_ini_file = *out_preinstall_script = NULL; - - if (pe->tag != 0x06054b50) { - return FALSE; - } - - if (pmd->tag != 0x1234567B) { - return SystemError(0, - "Invalid cfgdata magic number (see bdist_wininst.py)"); - } - if (ofs < 0) { - return FALSE; - } - - if (pmd->bitmap_size) { - /* Store pointer to bitmap bytes */ - bitmap_bytes = (char *)pmd - pmd->uncomp_size - pmd->bitmap_size; - } - - *pexe_size = ofs - pmd->uncomp_size - pmd->bitmap_size; - - src = ((char *)pmd) - pmd->uncomp_size; - ini_file = malloc(MAX_PATH); /* will be returned, so do not free it */ - if (!ini_file) - return FALSE; - if (!GetTempPath(sizeof(tempdir), tempdir) - || !GetTempFileName(tempdir, "~du", 0, ini_file)) { - SystemError(GetLastError(), - "Could not create temporary file"); - return FALSE; - } - - dst = map_new_file(CREATE_ALWAYS, ini_file, NULL, pmd->uncomp_size, - 0, 0, NULL/*notify*/); - if (!dst) - return FALSE; - /* Up to the first \0 is the INI file data. */ - strncpy(dst, src, pmd->uncomp_size); - src += strlen(dst) + 1; - /* Up to next \0 is the pre-install script */ - *out_preinstall_script = strdup(src); - *out_ini_file = ini_file; - UnmapViewOfFile(dst); - return TRUE; + /* read the end of central directory record */ + struct eof_cdir *pe = (struct eof_cdir *)&data[size - sizeof + (struct eof_cdir)]; + + int arc_start = size - sizeof (struct eof_cdir) - pe->nBytesCDir - + pe->ofsCDir; + + int ofs = arc_start - sizeof (struct meta_data_hdr); + + /* read meta_data info */ + struct meta_data_hdr *pmd = (struct meta_data_hdr *)&data[ofs]; + char *src, *dst; + char *ini_file; + char tempdir[MAX_PATH]; + + /* ensure that if we fail, we don't have garbage out pointers */ + *out_ini_file = *out_preinstall_script = NULL; + + if (pe->tag != 0x06054b50) { + return FALSE; + } + + if (pmd->tag != 0x1234567B) { + return SystemError(0, + "Invalid cfgdata magic number (see bdist_wininst.py)"); + } + if (ofs < 0) { + return FALSE; + } + + if (pmd->bitmap_size) { + /* Store pointer to bitmap bytes */ + bitmap_bytes = (char *)pmd - pmd->uncomp_size - pmd->bitmap_size; + } + + *pexe_size = ofs - pmd->uncomp_size - pmd->bitmap_size; + + src = ((char *)pmd) - pmd->uncomp_size; + ini_file = malloc(MAX_PATH); /* will be returned, so do not free it */ + if (!ini_file) + return FALSE; + if (!GetTempPath(sizeof(tempdir), tempdir) + || !GetTempFileName(tempdir, "~du", 0, ini_file)) { + SystemError(GetLastError(), + "Could not create temporary file"); + return FALSE; + } + + dst = map_new_file(CREATE_ALWAYS, ini_file, NULL, pmd->uncomp_size, + 0, 0, NULL/*notify*/); + if (!dst) + return FALSE; + /* Up to the first \0 is the INI file data. */ + strncpy(dst, src, pmd->uncomp_size); + src += strlen(dst) + 1; + /* Up to next \0 is the pre-install script */ + *out_preinstall_script = strdup(src); + *out_ini_file = ini_file; + UnmapViewOfFile(dst); + return TRUE; } static void PumpMessages(void) { - MSG msg; - while (PeekMessage(&msg, NULL, 0, 0, PM_REMOVE)) { - TranslateMessage(&msg); - DispatchMessage(&msg); - } + MSG msg; + while (PeekMessage(&msg, NULL, 0, 0, PM_REMOVE)) { + TranslateMessage(&msg); + DispatchMessage(&msg); + } } LRESULT CALLBACK WindowProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam) { - HDC hdc; - HFONT hFont; - int h; - PAINTSTRUCT ps; - switch (msg) { - case WM_PAINT: - hdc = BeginPaint(hwnd, &ps); - h = GetSystemMetrics(SM_CYSCREEN) / 10; - hFont = CreateFont(h, 0, 0, 0, 700, TRUE, - 0, 0, 0, 0, 0, 0, 0, "Times Roman"); - hFont = SelectObject(hdc, hFont); - SetBkMode(hdc, TRANSPARENT); - TextOut(hdc, 15, 15, title, strlen(title)); - SetTextColor(hdc, RGB(255, 255, 255)); - TextOut(hdc, 10, 10, title, strlen(title)); - DeleteObject(SelectObject(hdc, hFont)); - EndPaint(hwnd, &ps); - return 0; - } - return DefWindowProc(hwnd, msg, wParam, lParam); + HDC hdc; + HFONT hFont; + int h; + PAINTSTRUCT ps; + switch (msg) { + case WM_PAINT: + hdc = BeginPaint(hwnd, &ps); + h = GetSystemMetrics(SM_CYSCREEN) / 10; + hFont = CreateFont(h, 0, 0, 0, 700, TRUE, + 0, 0, 0, 0, 0, 0, 0, "Times Roman"); + hFont = SelectObject(hdc, hFont); + SetBkMode(hdc, TRANSPARENT); + TextOut(hdc, 15, 15, title, strlen(title)); + SetTextColor(hdc, RGB(255, 255, 255)); + TextOut(hdc, 10, 10, title, strlen(title)); + DeleteObject(SelectObject(hdc, hFont)); + EndPaint(hwnd, &ps); + return 0; + } + return DefWindowProc(hwnd, msg, wParam, lParam); } static HWND CreateBackground(char *title) { - WNDCLASS wc; - HWND hwnd; - char buffer[4096]; - - wc.style = CS_VREDRAW | CS_HREDRAW; - wc.lpfnWndProc = WindowProc; - wc.cbWndExtra = 0; - wc.cbClsExtra = 0; - wc.hInstance = GetModuleHandle(NULL); - wc.hIcon = NULL; - wc.hCursor = LoadCursor(NULL, IDC_ARROW); - wc.hbrBackground = CreateSolidBrush(RGB(0, 0, 128)); - wc.lpszMenuName = NULL; - wc.lpszClassName = "SetupWindowClass"; - - if (!RegisterClass(&wc)) - MessageBox(hwndMain, - "Could not register window class", - "Setup.exe", MB_OK); - - wsprintf(buffer, "Setup %s", title); - hwnd = CreateWindow("SetupWindowClass", - buffer, - 0, - 0, 0, - GetSystemMetrics(SM_CXFULLSCREEN), - GetSystemMetrics(SM_CYFULLSCREEN), - NULL, - NULL, - GetModuleHandle(NULL), - NULL); - ShowWindow(hwnd, SW_SHOWMAXIMIZED); - UpdateWindow(hwnd); - return hwnd; + WNDCLASS wc; + HWND hwnd; + char buffer[4096]; + + wc.style = CS_VREDRAW | CS_HREDRAW; + wc.lpfnWndProc = WindowProc; + wc.cbWndExtra = 0; + wc.cbClsExtra = 0; + wc.hInstance = GetModuleHandle(NULL); + wc.hIcon = NULL; + wc.hCursor = LoadCursor(NULL, IDC_ARROW); + wc.hbrBackground = CreateSolidBrush(RGB(0, 0, 128)); + wc.lpszMenuName = NULL; + wc.lpszClassName = "SetupWindowClass"; + + if (!RegisterClass(&wc)) + MessageBox(hwndMain, + "Could not register window class", + "Setup.exe", MB_OK); + + wsprintf(buffer, "Setup %s", title); + hwnd = CreateWindow("SetupWindowClass", + buffer, + 0, + 0, 0, + GetSystemMetrics(SM_CXFULLSCREEN), + GetSystemMetrics(SM_CYFULLSCREEN), + NULL, + NULL, + GetModuleHandle(NULL), + NULL); + ShowWindow(hwnd, SW_SHOWMAXIMIZED); + UpdateWindow(hwnd); + return hwnd; } /* @@ -1202,16 +1202,16 @@ */ static void CenterWindow(HWND hwnd) { - RECT rc; - int w, h; + RECT rc; + int w, h; - GetWindowRect(hwnd, &rc); - w = GetSystemMetrics(SM_CXSCREEN); - h = GetSystemMetrics(SM_CYSCREEN); - MoveWindow(hwnd, - (w - (rc.right-rc.left))/2, - (h - (rc.bottom-rc.top))/2, - rc.right-rc.left, rc.bottom-rc.top, FALSE); + GetWindowRect(hwnd, &rc); + w = GetSystemMetrics(SM_CXSCREEN); + h = GetSystemMetrics(SM_CYSCREEN); + MoveWindow(hwnd, + (w - (rc.right-rc.left))/2, + (h - (rc.bottom-rc.top))/2, + rc.right-rc.left, rc.bottom-rc.top, FALSE); } #include @@ -1219,45 +1219,45 @@ BOOL CALLBACK IntroDlgProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam) { - LPNMHDR lpnm; - char Buffer[4096]; + LPNMHDR lpnm; + char Buffer[4096]; - switch (msg) { - case WM_INITDIALOG: - create_bitmap(hwnd); - if(hBitmap) - SendDlgItemMessage(hwnd, IDC_BITMAP, STM_SETIMAGE, - IMAGE_BITMAP, (LPARAM)hBitmap); - CenterWindow(GetParent(hwnd)); - wsprintf(Buffer, - "This Wizard will install %s on your computer. " - "Click Next to continue " - "or Cancel to exit the Setup Wizard.", - meta_name); - SetDlgItemText(hwnd, IDC_TITLE, Buffer); - SetDlgItemText(hwnd, IDC_INTRO_TEXT, info); - SetDlgItemText(hwnd, IDC_BUILD_INFO, build_info); - return FALSE; - - case WM_NOTIFY: - lpnm = (LPNMHDR) lParam; - - switch (lpnm->code) { - case PSN_SETACTIVE: - PropSheet_SetWizButtons(GetParent(hwnd), PSWIZB_NEXT); - break; - - case PSN_WIZNEXT: - break; - - case PSN_RESET: - break; - - default: - break; - } - } - return FALSE; + switch (msg) { + case WM_INITDIALOG: + create_bitmap(hwnd); + if(hBitmap) + SendDlgItemMessage(hwnd, IDC_BITMAP, STM_SETIMAGE, + IMAGE_BITMAP, (LPARAM)hBitmap); + CenterWindow(GetParent(hwnd)); + wsprintf(Buffer, + "This Wizard will install %s on your computer. " + "Click Next to continue " + "or Cancel to exit the Setup Wizard.", + meta_name); + SetDlgItemText(hwnd, IDC_TITLE, Buffer); + SetDlgItemText(hwnd, IDC_INTRO_TEXT, info); + SetDlgItemText(hwnd, IDC_BUILD_INFO, build_info); + return FALSE; + + case WM_NOTIFY: + lpnm = (LPNMHDR) lParam; + + switch (lpnm->code) { + case PSN_SETACTIVE: + PropSheet_SetWizButtons(GetParent(hwnd), PSWIZB_NEXT); + break; + + case PSN_WIZNEXT: + break; + + case PSN_RESET: + break; + + default: + break; + } + } + return FALSE; } #ifdef USE_OTHER_PYTHON_VERSIONS @@ -1269,133 +1269,133 @@ int bound_image_minor; static BOOL __stdcall StatusRoutine(IMAGEHLP_STATUS_REASON reason, - PSTR ImageName, - PSTR DllName, - ULONG Va, - ULONG Parameter) -{ - char fname[_MAX_PATH]; - int int_version; - - switch(reason) { - case BindOutOfMemory: - case BindRvaToVaFailed: - case BindNoRoomInImage: - case BindImportProcedureFailed: - break; - - case BindImportProcedure: - case BindForwarder: - case BindForwarderNOT: - case BindImageModified: - case BindExpandFileHeaders: - case BindImageComplete: - case BindSymbolsNotUpdated: - case BindMismatchedSymbols: - case BindImportModuleFailed: - break; - - case BindImportModule: - if (1 == sscanf(DllName, "python%d", &int_version)) { - SearchPath(NULL, DllName, NULL, sizeof(fname), - fname, NULL); - strcpy(bound_image_dll, fname); - bound_image_major = int_version / 10; - bound_image_minor = int_version % 10; - OutputDebugString("BOUND "); - OutputDebugString(fname); - OutputDebugString("\n"); - } - break; - } - return TRUE; + PSTR ImageName, + PSTR DllName, + ULONG Va, + ULONG Parameter) +{ + char fname[_MAX_PATH]; + int int_version; + + switch(reason) { + case BindOutOfMemory: + case BindRvaToVaFailed: + case BindNoRoomInImage: + case BindImportProcedureFailed: + break; + + case BindImportProcedure: + case BindForwarder: + case BindForwarderNOT: + case BindImageModified: + case BindExpandFileHeaders: + case BindImageComplete: + case BindSymbolsNotUpdated: + case BindMismatchedSymbols: + case BindImportModuleFailed: + break; + + case BindImportModule: + if (1 == sscanf(DllName, "python%d", &int_version)) { + SearchPath(NULL, DllName, NULL, sizeof(fname), + fname, NULL); + strcpy(bound_image_dll, fname); + bound_image_major = int_version / 10; + bound_image_minor = int_version % 10; + OutputDebugString("BOUND "); + OutputDebugString(fname); + OutputDebugString("\n"); + } + break; + } + return TRUE; } /* */ static LPSTR get_sys_prefix(LPSTR exe, LPSTR dll) { - void (__cdecl * Py_Initialize)(void); - void (__cdecl * Py_SetProgramName)(char *); - void (__cdecl * Py_Finalize)(void); - void* (__cdecl * PySys_GetObject)(char *); - void (__cdecl * PySys_SetArgv)(int, char **); - char* (__cdecl * Py_GetPrefix)(void); - char* (__cdecl * Py_GetPath)(void); - HINSTANCE hPython; - LPSTR prefix = NULL; - int (__cdecl * PyRun_SimpleString)(char *); - - { - char Buffer[256]; - wsprintf(Buffer, "PYTHONHOME=%s", exe); - *strrchr(Buffer, '\\') = '\0'; -// MessageBox(GetFocus(), Buffer, "PYTHONHOME", MB_OK); - _putenv(Buffer); - _putenv("PYTHONPATH="); - } - - hPython = LoadLibrary(dll); - if (!hPython) - return NULL; - Py_Initialize = (void (*)(void))GetProcAddress - (hPython,"Py_Initialize"); - - PySys_SetArgv = (void (*)(int, char **))GetProcAddress - (hPython,"PySys_SetArgv"); - - PyRun_SimpleString = (int (*)(char *))GetProcAddress - (hPython,"PyRun_SimpleString"); - - Py_SetProgramName = (void (*)(char *))GetProcAddress - (hPython,"Py_SetProgramName"); - - PySys_GetObject = (void* (*)(char *))GetProcAddress - (hPython,"PySys_GetObject"); - - Py_GetPrefix = (char * (*)(void))GetProcAddress - (hPython,"Py_GetPrefix"); - - Py_GetPath = (char * (*)(void))GetProcAddress - (hPython,"Py_GetPath"); - - Py_Finalize = (void (*)(void))GetProcAddress(hPython, - "Py_Finalize"); - Py_SetProgramName(exe); - Py_Initialize(); - PySys_SetArgv(1, &exe); + void (__cdecl * Py_Initialize)(void); + void (__cdecl * Py_SetProgramName)(char *); + void (__cdecl * Py_Finalize)(void); + void* (__cdecl * PySys_GetObject)(char *); + void (__cdecl * PySys_SetArgv)(int, char **); + char* (__cdecl * Py_GetPrefix)(void); + char* (__cdecl * Py_GetPath)(void); + HINSTANCE hPython; + LPSTR prefix = NULL; + int (__cdecl * PyRun_SimpleString)(char *); + + { + char Buffer[256]; + wsprintf(Buffer, "PYTHONHOME=%s", exe); + *strrchr(Buffer, '\\') = '\0'; +// MessageBox(GetFocus(), Buffer, "PYTHONHOME", MB_OK); + _putenv(Buffer); + _putenv("PYTHONPATH="); + } + + hPython = LoadLibrary(dll); + if (!hPython) + return NULL; + Py_Initialize = (void (*)(void))GetProcAddress + (hPython,"Py_Initialize"); + + PySys_SetArgv = (void (*)(int, char **))GetProcAddress + (hPython,"PySys_SetArgv"); + + PyRun_SimpleString = (int (*)(char *))GetProcAddress + (hPython,"PyRun_SimpleString"); + + Py_SetProgramName = (void (*)(char *))GetProcAddress + (hPython,"Py_SetProgramName"); + + PySys_GetObject = (void* (*)(char *))GetProcAddress + (hPython,"PySys_GetObject"); + + Py_GetPrefix = (char * (*)(void))GetProcAddress + (hPython,"Py_GetPrefix"); + + Py_GetPath = (char * (*)(void))GetProcAddress + (hPython,"Py_GetPath"); + + Py_Finalize = (void (*)(void))GetProcAddress(hPython, + "Py_Finalize"); + Py_SetProgramName(exe); + Py_Initialize(); + PySys_SetArgv(1, &exe); - MessageBox(GetFocus(), Py_GetPrefix(), "PREFIX", MB_OK); - MessageBox(GetFocus(), Py_GetPath(), "PATH", MB_OK); + MessageBox(GetFocus(), Py_GetPrefix(), "PREFIX", MB_OK); + MessageBox(GetFocus(), Py_GetPath(), "PATH", MB_OK); - Py_Finalize(); - FreeLibrary(hPython); + Py_Finalize(); + FreeLibrary(hPython); - return prefix; + return prefix; } static BOOL CheckPythonExe(LPSTR pathname, LPSTR version, int *pmajor, int *pminor) { - bound_image_dll[0] = '\0'; - if (!BindImageEx(BIND_NO_BOUND_IMPORTS | BIND_NO_UPDATE | BIND_ALL_IMAGES, - pathname, - NULL, - NULL, - StatusRoutine)) - return SystemError(0, "Could not bind image"); - if (bound_image_dll[0] == '\0') - return SystemError(0, "Does not seem to be a python executable"); - *pmajor = bound_image_major; - *pminor = bound_image_minor; - if (version && *version) { - char core_version[12]; - wsprintf(core_version, "%d.%d", bound_image_major, bound_image_minor); - if (strcmp(version, core_version)) - return SystemError(0, "Wrong Python version"); - } - get_sys_prefix(pathname, bound_image_dll); - return TRUE; + bound_image_dll[0] = '\0'; + if (!BindImageEx(BIND_NO_BOUND_IMPORTS | BIND_NO_UPDATE | BIND_ALL_IMAGES, + pathname, + NULL, + NULL, + StatusRoutine)) + return SystemError(0, "Could not bind image"); + if (bound_image_dll[0] == '\0') + return SystemError(0, "Does not seem to be a python executable"); + *pmajor = bound_image_major; + *pminor = bound_image_minor; + if (version && *version) { + char core_version[12]; + wsprintf(core_version, "%d.%d", bound_image_major, bound_image_minor); + if (strcmp(version, core_version)) + return SystemError(0, "Wrong Python version"); + } + get_sys_prefix(pathname, bound_image_dll); + return TRUE; } /* @@ -1404,48 +1404,48 @@ */ static BOOL GetOtherPythonVersion(HWND hwnd, LPSTR version) { - char vers_name[_MAX_PATH + 80]; - DWORD itemindex; - OPENFILENAME of; - char pathname[_MAX_PATH]; - DWORD result; - - strcpy(pathname, "python.exe"); - - memset(&of, 0, sizeof(of)); - of.lStructSize = sizeof(OPENFILENAME); - of.hwndOwner = GetParent(hwnd); - of.hInstance = NULL; - of.lpstrFilter = "python.exe\0python.exe\0"; - of.lpstrCustomFilter = NULL; - of.nMaxCustFilter = 0; - of.nFilterIndex = 1; - of.lpstrFile = pathname; - of.nMaxFile = sizeof(pathname); - of.lpstrFileTitle = NULL; - of.nMaxFileTitle = 0; - of.lpstrInitialDir = NULL; - of.lpstrTitle = "Python executable"; - of.Flags = OFN_FILEMUSTEXIST | OFN_PATHMUSTEXIST; - of.lpstrDefExt = "exe"; - - result = GetOpenFileName(&of); - if (result) { - int major, minor; - if (!CheckPythonExe(pathname, version, &major, &minor)) { - return FALSE; - } - *strrchr(pathname, '\\') = '\0'; - wsprintf(vers_name, "Python Version %d.%d in %s", - major, minor, pathname); - itemindex = SendMessage(hwnd, LB_INSERTSTRING, -1, - (LPARAM)(LPSTR)vers_name); - SendMessage(hwnd, LB_SETCURSEL, itemindex, 0); - SendMessage(hwnd, LB_SETITEMDATA, itemindex, - (LPARAM)(LPSTR)strdup(pathname)); - return TRUE; - } - return FALSE; + char vers_name[_MAX_PATH + 80]; + DWORD itemindex; + OPENFILENAME of; + char pathname[_MAX_PATH]; + DWORD result; + + strcpy(pathname, "python.exe"); + + memset(&of, 0, sizeof(of)); + of.lStructSize = sizeof(OPENFILENAME); + of.hwndOwner = GetParent(hwnd); + of.hInstance = NULL; + of.lpstrFilter = "python.exe\0python.exe\0"; + of.lpstrCustomFilter = NULL; + of.nMaxCustFilter = 0; + of.nFilterIndex = 1; + of.lpstrFile = pathname; + of.nMaxFile = sizeof(pathname); + of.lpstrFileTitle = NULL; + of.nMaxFileTitle = 0; + of.lpstrInitialDir = NULL; + of.lpstrTitle = "Python executable"; + of.Flags = OFN_FILEMUSTEXIST | OFN_PATHMUSTEXIST; + of.lpstrDefExt = "exe"; + + result = GetOpenFileName(&of); + if (result) { + int major, minor; + if (!CheckPythonExe(pathname, version, &major, &minor)) { + return FALSE; + } + *strrchr(pathname, '\\') = '\0'; + wsprintf(vers_name, "Python Version %d.%d in %s", + major, minor, pathname); + itemindex = SendMessage(hwnd, LB_INSERTSTRING, -1, + (LPARAM)(LPSTR)vers_name); + SendMessage(hwnd, LB_SETCURSEL, itemindex, 0); + SendMessage(hwnd, LB_SETITEMDATA, itemindex, + (LPARAM)(LPSTR)strdup(pathname)); + return TRUE; + } + return FALSE; } #endif /* USE_OTHER_PYTHON_VERSIONS */ @@ -1462,71 +1462,71 @@ */ static BOOL GetPythonVersions(HWND hwnd, HKEY hkRoot, LPSTR version) { - DWORD index = 0; - char core_version[80]; - HKEY hKey; - BOOL result = TRUE; - DWORD bufsize; - - if (ERROR_SUCCESS != RegOpenKeyEx(hkRoot, - "Software\\Python\\PythonCore", - 0, KEY_READ, &hKey)) - return FALSE; - bufsize = sizeof(core_version); - while (ERROR_SUCCESS == RegEnumKeyEx(hKey, index, - core_version, &bufsize, NULL, - NULL, NULL, NULL)) { - char subkey_name[80], vers_name[80]; - int itemindex; - DWORD value_size; - HKEY hk; - - bufsize = sizeof(core_version); - ++index; - if (version && *version && strcmp(version, core_version)) - continue; - - wsprintf(vers_name, "Python Version %s (found in registry)", - core_version); - wsprintf(subkey_name, - "Software\\Python\\PythonCore\\%s\\InstallPath", - core_version); - if (ERROR_SUCCESS == RegOpenKeyEx(hkRoot, subkey_name, 0, KEY_READ, &hk)) { - InstalledVersionInfo *ivi = - (InstalledVersionInfo *)malloc(sizeof(InstalledVersionInfo)); - value_size = sizeof(ivi->prefix); - if (ivi && - ERROR_SUCCESS == RegQueryValueEx(hk, NULL, NULL, NULL, - ivi->prefix, &value_size)) { - itemindex = SendMessage(hwnd, LB_ADDSTRING, 0, - (LPARAM)(LPSTR)vers_name); - ivi->hkey = hkRoot; - SendMessage(hwnd, LB_SETITEMDATA, itemindex, - (LPARAM)(LPSTR)ivi); - } - RegCloseKey(hk); - } - } - RegCloseKey(hKey); - return result; + DWORD index = 0; + char core_version[80]; + HKEY hKey; + BOOL result = TRUE; + DWORD bufsize; + + if (ERROR_SUCCESS != RegOpenKeyEx(hkRoot, + "Software\\Python\\PythonCore", + 0, KEY_READ, &hKey)) + return FALSE; + bufsize = sizeof(core_version); + while (ERROR_SUCCESS == RegEnumKeyEx(hKey, index, + core_version, &bufsize, NULL, + NULL, NULL, NULL)) { + char subkey_name[80], vers_name[80]; + int itemindex; + DWORD value_size; + HKEY hk; + + bufsize = sizeof(core_version); + ++index; + if (version && *version && strcmp(version, core_version)) + continue; + + wsprintf(vers_name, "Python Version %s (found in registry)", + core_version); + wsprintf(subkey_name, + "Software\\Python\\PythonCore\\%s\\InstallPath", + core_version); + if (ERROR_SUCCESS == RegOpenKeyEx(hkRoot, subkey_name, 0, KEY_READ, &hk)) { + InstalledVersionInfo *ivi = + (InstalledVersionInfo *)malloc(sizeof(InstalledVersionInfo)); + value_size = sizeof(ivi->prefix); + if (ivi && + ERROR_SUCCESS == RegQueryValueEx(hk, NULL, NULL, NULL, + ivi->prefix, &value_size)) { + itemindex = SendMessage(hwnd, LB_ADDSTRING, 0, + (LPARAM)(LPSTR)vers_name); + ivi->hkey = hkRoot; + SendMessage(hwnd, LB_SETITEMDATA, itemindex, + (LPARAM)(LPSTR)ivi); + } + RegCloseKey(hk); + } + } + RegCloseKey(hKey); + return result; } /* Determine if the current user can write to HKEY_LOCAL_MACHINE */ BOOL HasLocalMachinePrivs() { - HKEY hKey; - DWORD result; - static char KeyName[] = - "Software\\Microsoft\\Windows\\CurrentVersion\\Uninstall"; - - result = RegOpenKeyEx(HKEY_LOCAL_MACHINE, - KeyName, - 0, - KEY_CREATE_SUB_KEY, - &hKey); - if (result==0) - RegCloseKey(hKey); - return result==0; + HKEY hKey; + DWORD result; + static char KeyName[] = + "Software\\Microsoft\\Windows\\CurrentVersion\\Uninstall"; + + result = RegOpenKeyEx(HKEY_LOCAL_MACHINE, + KeyName, + 0, + KEY_CREATE_SUB_KEY, + &hKey); + if (result==0) + RegCloseKey(hKey); + return result==0; } // Check the root registry key to use - either HKLM or HKCU. @@ -1539,86 +1539,86 @@ // We assume hkey_root is already set to where Python itself is installed. void CheckRootKey(HWND hwnd) { - if (hkey_root==HKEY_CURRENT_USER) { - ; // as above, always install ourself in HKCU too. - } else if (hkey_root==HKEY_LOCAL_MACHINE) { - // Python in HKLM, but we may or may not have permissions there. - // Open the uninstall key with 'create' permissions - if this fails, - // we don't have permission. - if (!HasLocalMachinePrivs()) - hkey_root = HKEY_CURRENT_USER; - } else { - MessageBox(hwnd, "Don't know Python's installation type", - "Strange", MB_OK | MB_ICONSTOP); - /* Default to wherever they can, but preferring HKLM */ - hkey_root = HasLocalMachinePrivs() ? HKEY_LOCAL_MACHINE : HKEY_CURRENT_USER; - } + if (hkey_root==HKEY_CURRENT_USER) { + ; // as above, always install ourself in HKCU too. + } else if (hkey_root==HKEY_LOCAL_MACHINE) { + // Python in HKLM, but we may or may not have permissions there. + // Open the uninstall key with 'create' permissions - if this fails, + // we don't have permission. + if (!HasLocalMachinePrivs()) + hkey_root = HKEY_CURRENT_USER; + } else { + MessageBox(hwnd, "Don't know Python's installation type", + "Strange", MB_OK | MB_ICONSTOP); + /* Default to wherever they can, but preferring HKLM */ + hkey_root = HasLocalMachinePrivs() ? HKEY_LOCAL_MACHINE : HKEY_CURRENT_USER; + } } /* Return the installation scheme depending on Python version number */ SCHEME *GetScheme(int major, int minor) { - if (major > 2) - return new_scheme; - else if((major == 2) && (minor >= 2)) - return new_scheme; - return old_scheme; + if (major > 2) + return new_scheme; + else if((major == 2) && (minor >= 2)) + return new_scheme; + return old_scheme; } BOOL CALLBACK SelectPythonDlgProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam) { - LPNMHDR lpnm; + LPNMHDR lpnm; - switch (msg) { - case WM_INITDIALOG: - if (hBitmap) - SendDlgItemMessage(hwnd, IDC_BITMAP, STM_SETIMAGE, - IMAGE_BITMAP, (LPARAM)hBitmap); - GetPythonVersions(GetDlgItem(hwnd, IDC_VERSIONS_LIST), - HKEY_LOCAL_MACHINE, target_version); - GetPythonVersions(GetDlgItem(hwnd, IDC_VERSIONS_LIST), - HKEY_CURRENT_USER, target_version); - { /* select the last entry which is the highest python - version found */ - int count; - count = SendDlgItemMessage(hwnd, IDC_VERSIONS_LIST, - LB_GETCOUNT, 0, 0); - if (count && count != LB_ERR) - SendDlgItemMessage(hwnd, IDC_VERSIONS_LIST, LB_SETCURSEL, - count-1, 0); - - /* If a specific Python version is required, - * display a prominent notice showing this fact. - */ - if (target_version && target_version[0]) { - char buffer[4096]; - wsprintf(buffer, - "Python %s is required for this package. " - "Select installation to use:", - target_version); - SetDlgItemText(hwnd, IDC_TITLE, buffer); - } - - if (count == 0) { - char Buffer[4096]; - char *msg; - if (target_version && target_version[0]) { - wsprintf(Buffer, - "Python version %s required, which was not found" - " in the registry.", target_version); - msg = Buffer; - } else - msg = "No Python installation found in the registry."; - MessageBox(hwnd, msg, "Cannot install", - MB_OK | MB_ICONSTOP); - } - } - goto UpdateInstallDir; - break; + switch (msg) { + case WM_INITDIALOG: + if (hBitmap) + SendDlgItemMessage(hwnd, IDC_BITMAP, STM_SETIMAGE, + IMAGE_BITMAP, (LPARAM)hBitmap); + GetPythonVersions(GetDlgItem(hwnd, IDC_VERSIONS_LIST), + HKEY_LOCAL_MACHINE, target_version); + GetPythonVersions(GetDlgItem(hwnd, IDC_VERSIONS_LIST), + HKEY_CURRENT_USER, target_version); + { /* select the last entry which is the highest python + version found */ + int count; + count = SendDlgItemMessage(hwnd, IDC_VERSIONS_LIST, + LB_GETCOUNT, 0, 0); + if (count && count != LB_ERR) + SendDlgItemMessage(hwnd, IDC_VERSIONS_LIST, LB_SETCURSEL, + count-1, 0); + + /* If a specific Python version is required, + * display a prominent notice showing this fact. + */ + if (target_version && target_version[0]) { + char buffer[4096]; + wsprintf(buffer, + "Python %s is required for this package. " + "Select installation to use:", + target_version); + SetDlgItemText(hwnd, IDC_TITLE, buffer); + } + + if (count == 0) { + char Buffer[4096]; + char *msg; + if (target_version && target_version[0]) { + wsprintf(Buffer, + "Python version %s required, which was not found" + " in the registry.", target_version); + msg = Buffer; + } else + msg = "No Python installation found in the registry."; + MessageBox(hwnd, msg, "Cannot install", + MB_OK | MB_ICONSTOP); + } + } + goto UpdateInstallDir; + break; - case WM_COMMAND: - switch (LOWORD(wParam)) { + case WM_COMMAND: + switch (LOWORD(wParam)) { /* case IDC_OTHERPYTHON: if (GetOtherPythonVersion(GetDlgItem(hwnd, IDC_VERSIONS_LIST), @@ -1626,307 +1626,307 @@ goto UpdateInstallDir; break; */ - case IDC_VERSIONS_LIST: - switch (HIWORD(wParam)) { - int id; - case LBN_SELCHANGE: - UpdateInstallDir: - PropSheet_SetWizButtons(GetParent(hwnd), - PSWIZB_BACK | PSWIZB_NEXT); - id = SendDlgItemMessage(hwnd, IDC_VERSIONS_LIST, - LB_GETCURSEL, 0, 0); - if (id == LB_ERR) { - PropSheet_SetWizButtons(GetParent(hwnd), - PSWIZB_BACK); - SetDlgItemText(hwnd, IDC_PATH, ""); - SetDlgItemText(hwnd, IDC_INSTALL_PATH, ""); - strcpy(python_dir, ""); - strcpy(pythondll, ""); - } else { - char *pbuf; - int result; - InstalledVersionInfo *ivi; - PropSheet_SetWizButtons(GetParent(hwnd), - PSWIZB_BACK | PSWIZB_NEXT); - /* Get the python directory */ - ivi = (InstalledVersionInfo *) - SendDlgItemMessage(hwnd, - IDC_VERSIONS_LIST, - LB_GETITEMDATA, - id, - 0); - hkey_root = ivi->hkey; - strcpy(python_dir, ivi->prefix); - SetDlgItemText(hwnd, IDC_PATH, python_dir); - /* retrieve the python version and pythondll to use */ - result = SendDlgItemMessage(hwnd, IDC_VERSIONS_LIST, - LB_GETTEXTLEN, (WPARAM)id, 0); - pbuf = (char *)malloc(result + 1); - if (pbuf) { - /* guess the name of the python-dll */ - SendDlgItemMessage(hwnd, IDC_VERSIONS_LIST, - LB_GETTEXT, (WPARAM)id, - (LPARAM)pbuf); - result = sscanf(pbuf, "Python Version %d.%d", - &py_major, &py_minor); - if (result == 2) { + case IDC_VERSIONS_LIST: + switch (HIWORD(wParam)) { + int id; + case LBN_SELCHANGE: + UpdateInstallDir: + PropSheet_SetWizButtons(GetParent(hwnd), + PSWIZB_BACK | PSWIZB_NEXT); + id = SendDlgItemMessage(hwnd, IDC_VERSIONS_LIST, + LB_GETCURSEL, 0, 0); + if (id == LB_ERR) { + PropSheet_SetWizButtons(GetParent(hwnd), + PSWIZB_BACK); + SetDlgItemText(hwnd, IDC_PATH, ""); + SetDlgItemText(hwnd, IDC_INSTALL_PATH, ""); + strcpy(python_dir, ""); + strcpy(pythondll, ""); + } else { + char *pbuf; + int result; + InstalledVersionInfo *ivi; + PropSheet_SetWizButtons(GetParent(hwnd), + PSWIZB_BACK | PSWIZB_NEXT); + /* Get the python directory */ + ivi = (InstalledVersionInfo *) + SendDlgItemMessage(hwnd, + IDC_VERSIONS_LIST, + LB_GETITEMDATA, + id, + 0); + hkey_root = ivi->hkey; + strcpy(python_dir, ivi->prefix); + SetDlgItemText(hwnd, IDC_PATH, python_dir); + /* retrieve the python version and pythondll to use */ + result = SendDlgItemMessage(hwnd, IDC_VERSIONS_LIST, + LB_GETTEXTLEN, (WPARAM)id, 0); + pbuf = (char *)malloc(result + 1); + if (pbuf) { + /* guess the name of the python-dll */ + SendDlgItemMessage(hwnd, IDC_VERSIONS_LIST, + LB_GETTEXT, (WPARAM)id, + (LPARAM)pbuf); + result = sscanf(pbuf, "Python Version %d.%d", + &py_major, &py_minor); + if (result == 2) { #ifdef _DEBUG - wsprintf(pythondll, "python%d%d_d.dll", - py_major, py_minor); + wsprintf(pythondll, "python%d%d_d.dll", + py_major, py_minor); #else - wsprintf(pythondll, "python%d%d.dll", - py_major, py_minor); + wsprintf(pythondll, "python%d%d.dll", + py_major, py_minor); #endif - } - free(pbuf); - } else - strcpy(pythondll, ""); - /* retrieve the scheme for this version */ - { - char install_path[_MAX_PATH]; - SCHEME *scheme = GetScheme(py_major, py_minor); - strcpy(install_path, python_dir); - if (install_path[strlen(install_path)-1] != '\\') - strcat(install_path, "\\"); - strcat(install_path, scheme[0].prefix); - SetDlgItemText(hwnd, IDC_INSTALL_PATH, install_path); - } - } - } - break; - } - return 0; - - case WM_NOTIFY: - lpnm = (LPNMHDR) lParam; - - switch (lpnm->code) { - int id; - case PSN_SETACTIVE: - id = SendDlgItemMessage(hwnd, IDC_VERSIONS_LIST, - LB_GETCURSEL, 0, 0); - if (id == LB_ERR) - PropSheet_SetWizButtons(GetParent(hwnd), - PSWIZB_BACK); - else - PropSheet_SetWizButtons(GetParent(hwnd), - PSWIZB_BACK | PSWIZB_NEXT); - break; - - case PSN_WIZNEXT: - break; - - case PSN_WIZFINISH: - break; - - case PSN_RESET: - break; - - default: - break; - } - } - return 0; + } + free(pbuf); + } else + strcpy(pythondll, ""); + /* retrieve the scheme for this version */ + { + char install_path[_MAX_PATH]; + SCHEME *scheme = GetScheme(py_major, py_minor); + strcpy(install_path, python_dir); + if (install_path[strlen(install_path)-1] != '\\') + strcat(install_path, "\\"); + strcat(install_path, scheme[0].prefix); + SetDlgItemText(hwnd, IDC_INSTALL_PATH, install_path); + } + } + } + break; + } + return 0; + + case WM_NOTIFY: + lpnm = (LPNMHDR) lParam; + + switch (lpnm->code) { + int id; + case PSN_SETACTIVE: + id = SendDlgItemMessage(hwnd, IDC_VERSIONS_LIST, + LB_GETCURSEL, 0, 0); + if (id == LB_ERR) + PropSheet_SetWizButtons(GetParent(hwnd), + PSWIZB_BACK); + else + PropSheet_SetWizButtons(GetParent(hwnd), + PSWIZB_BACK | PSWIZB_NEXT); + break; + + case PSN_WIZNEXT: + break; + + case PSN_WIZFINISH: + break; + + case PSN_RESET: + break; + + default: + break; + } + } + return 0; } static BOOL OpenLogfile(char *dir) { - char buffer[_MAX_PATH+1]; - time_t ltime; - struct tm *now; - long result; - HKEY hKey, hSubkey; - char subkey_name[256]; - static char KeyName[] = - "Software\\Microsoft\\Windows\\CurrentVersion\\Uninstall"; - const char *root_name = (hkey_root==HKEY_LOCAL_MACHINE ? - "HKEY_LOCAL_MACHINE" : "HKEY_CURRENT_USER"); - DWORD disposition; - - /* Use Create, as the Uninstall subkey may not exist under HKCU. - Use CreateKeyEx, so we can specify a SAM specifying write access - */ - result = RegCreateKeyEx(hkey_root, - KeyName, - 0, /* reserved */ - NULL, /* class */ - 0, /* options */ - KEY_CREATE_SUB_KEY, /* sam */ - NULL, /* security */ - &hKey, /* result key */ - NULL); /* disposition */ - if (result != ERROR_SUCCESS) { - if (result == ERROR_ACCESS_DENIED) { - /* This should no longer be able to happen - we have already - checked if they have permissions in HKLM, and all users - should have write access to HKCU. - */ - MessageBox(GetFocus(), - "You do not seem to have sufficient access rights\n" - "on this machine to install this software", - NULL, - MB_OK | MB_ICONSTOP); - return FALSE; - } else { - MessageBox(GetFocus(), KeyName, "Could not open key", MB_OK); - } - } - - sprintf(buffer, "%s\\%s-wininst.log", dir, meta_name); - logfile = fopen(buffer, "a"); - time(<ime); - now = localtime(<ime); - strftime(buffer, sizeof(buffer), - "*** Installation started %Y/%m/%d %H:%M ***\n", - localtime(<ime)); - fprintf(logfile, buffer); - fprintf(logfile, "Source: %s\n", modulename); - - /* Root key must be first entry processed by uninstaller. */ - fprintf(logfile, "999 Root Key: %s\n", root_name); - - sprintf(subkey_name, "%s-py%d.%d", meta_name, py_major, py_minor); - - result = RegCreateKeyEx(hKey, subkey_name, - 0, NULL, 0, - KEY_WRITE, - NULL, - &hSubkey, - &disposition); - - if (result != ERROR_SUCCESS) - MessageBox(GetFocus(), subkey_name, "Could not create key", MB_OK); - - RegCloseKey(hKey); - - if (disposition == REG_CREATED_NEW_KEY) - fprintf(logfile, "020 Reg DB Key: [%s]%s\n", KeyName, subkey_name); - - sprintf(buffer, "Python %d.%d %s", py_major, py_minor, title); - - result = RegSetValueEx(hSubkey, "DisplayName", - 0, - REG_SZ, - buffer, - strlen(buffer)+1); - - if (result != ERROR_SUCCESS) - MessageBox(GetFocus(), buffer, "Could not set key value", MB_OK); - - fprintf(logfile, "040 Reg DB Value: [%s\\%s]%s=%s\n", - KeyName, subkey_name, "DisplayName", buffer); - - { - FILE *fp; - sprintf(buffer, "%s\\Remove%s.exe", dir, meta_name); - fp = fopen(buffer, "wb"); - fwrite(arc_data, exe_size, 1, fp); - fclose(fp); - - sprintf(buffer, "\"%s\\Remove%s.exe\" -u \"%s\\%s-wininst.log\"", - dir, meta_name, dir, meta_name); - - result = RegSetValueEx(hSubkey, "UninstallString", - 0, - REG_SZ, - buffer, - strlen(buffer)+1); - - if (result != ERROR_SUCCESS) - MessageBox(GetFocus(), buffer, "Could not set key value", MB_OK); - - fprintf(logfile, "040 Reg DB Value: [%s\\%s]%s=%s\n", - KeyName, subkey_name, "UninstallString", buffer); - } - return TRUE; + char buffer[_MAX_PATH+1]; + time_t ltime; + struct tm *now; + long result; + HKEY hKey, hSubkey; + char subkey_name[256]; + static char KeyName[] = + "Software\\Microsoft\\Windows\\CurrentVersion\\Uninstall"; + const char *root_name = (hkey_root==HKEY_LOCAL_MACHINE ? + "HKEY_LOCAL_MACHINE" : "HKEY_CURRENT_USER"); + DWORD disposition; + + /* Use Create, as the Uninstall subkey may not exist under HKCU. + Use CreateKeyEx, so we can specify a SAM specifying write access + */ + result = RegCreateKeyEx(hkey_root, + KeyName, + 0, /* reserved */ + NULL, /* class */ + 0, /* options */ + KEY_CREATE_SUB_KEY, /* sam */ + NULL, /* security */ + &hKey, /* result key */ + NULL); /* disposition */ + if (result != ERROR_SUCCESS) { + if (result == ERROR_ACCESS_DENIED) { + /* This should no longer be able to happen - we have already + checked if they have permissions in HKLM, and all users + should have write access to HKCU. + */ + MessageBox(GetFocus(), + "You do not seem to have sufficient access rights\n" + "on this machine to install this software", + NULL, + MB_OK | MB_ICONSTOP); + return FALSE; + } else { + MessageBox(GetFocus(), KeyName, "Could not open key", MB_OK); + } + } + + sprintf(buffer, "%s\\%s-wininst.log", dir, meta_name); + logfile = fopen(buffer, "a"); + time(<ime); + now = localtime(<ime); + strftime(buffer, sizeof(buffer), + "*** Installation started %Y/%m/%d %H:%M ***\n", + localtime(<ime)); + fprintf(logfile, buffer); + fprintf(logfile, "Source: %s\n", modulename); + + /* Root key must be first entry processed by uninstaller. */ + fprintf(logfile, "999 Root Key: %s\n", root_name); + + sprintf(subkey_name, "%s-py%d.%d", meta_name, py_major, py_minor); + + result = RegCreateKeyEx(hKey, subkey_name, + 0, NULL, 0, + KEY_WRITE, + NULL, + &hSubkey, + &disposition); + + if (result != ERROR_SUCCESS) + MessageBox(GetFocus(), subkey_name, "Could not create key", MB_OK); + + RegCloseKey(hKey); + + if (disposition == REG_CREATED_NEW_KEY) + fprintf(logfile, "020 Reg DB Key: [%s]%s\n", KeyName, subkey_name); + + sprintf(buffer, "Python %d.%d %s", py_major, py_minor, title); + + result = RegSetValueEx(hSubkey, "DisplayName", + 0, + REG_SZ, + buffer, + strlen(buffer)+1); + + if (result != ERROR_SUCCESS) + MessageBox(GetFocus(), buffer, "Could not set key value", MB_OK); + + fprintf(logfile, "040 Reg DB Value: [%s\\%s]%s=%s\n", + KeyName, subkey_name, "DisplayName", buffer); + + { + FILE *fp; + sprintf(buffer, "%s\\Remove%s.exe", dir, meta_name); + fp = fopen(buffer, "wb"); + fwrite(arc_data, exe_size, 1, fp); + fclose(fp); + + sprintf(buffer, "\"%s\\Remove%s.exe\" -u \"%s\\%s-wininst.log\"", + dir, meta_name, dir, meta_name); + + result = RegSetValueEx(hSubkey, "UninstallString", + 0, + REG_SZ, + buffer, + strlen(buffer)+1); + + if (result != ERROR_SUCCESS) + MessageBox(GetFocus(), buffer, "Could not set key value", MB_OK); + + fprintf(logfile, "040 Reg DB Value: [%s\\%s]%s=%s\n", + KeyName, subkey_name, "UninstallString", buffer); + } + return TRUE; } static void CloseLogfile(void) { - char buffer[_MAX_PATH+1]; - time_t ltime; - struct tm *now; - - time(<ime); - now = localtime(<ime); - strftime(buffer, sizeof(buffer), - "*** Installation finished %Y/%m/%d %H:%M ***\n", - localtime(<ime)); - fprintf(logfile, buffer); - if (logfile) - fclose(logfile); + char buffer[_MAX_PATH+1]; + time_t ltime; + struct tm *now; + + time(<ime); + now = localtime(<ime); + strftime(buffer, sizeof(buffer), + "*** Installation finished %Y/%m/%d %H:%M ***\n", + localtime(<ime)); + fprintf(logfile, buffer); + if (logfile) + fclose(logfile); } BOOL CALLBACK InstallFilesDlgProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam) { - LPNMHDR lpnm; - char Buffer[4096]; - SCHEME *scheme; - - switch (msg) { - case WM_INITDIALOG: - if (hBitmap) - SendDlgItemMessage(hwnd, IDC_BITMAP, STM_SETIMAGE, - IMAGE_BITMAP, (LPARAM)hBitmap); - wsprintf(Buffer, - "Click Next to begin the installation of %s. " - "If you want to review or change any of your " - " installation settings, click Back. " - "Click Cancel to exit the wizard.", - meta_name); - SetDlgItemText(hwnd, IDC_TITLE, Buffer); - SetDlgItemText(hwnd, IDC_INFO, "Ready to install"); - break; - - case WM_NUMFILES: - SendDlgItemMessage(hwnd, IDC_PROGRESS, PBM_SETRANGE, 0, lParam); - PumpMessages(); - return TRUE; - - case WM_NEXTFILE: - SendDlgItemMessage(hwnd, IDC_PROGRESS, PBM_SETPOS, wParam, - 0); - SetDlgItemText(hwnd, IDC_INFO, (LPSTR)lParam); - PumpMessages(); - return TRUE; - - case WM_NOTIFY: - lpnm = (LPNMHDR) lParam; - - switch (lpnm->code) { - case PSN_SETACTIVE: - PropSheet_SetWizButtons(GetParent(hwnd), - PSWIZB_BACK | PSWIZB_NEXT); - break; - - case PSN_WIZFINISH: - break; - - case PSN_WIZNEXT: - /* Handle a Next button click here */ - hDialog = hwnd; - success = TRUE; - - /* Disable the buttons while we work. Sending CANCELTOCLOSE has - the effect of disabling the cancel button, which is a) as we - do everything synchronously we can't cancel, and b) the next - step is 'finished', when it is too late to cancel anyway. - The next step being 'Finished' means we also don't need to - restore the button state back */ - PropSheet_SetWizButtons(GetParent(hwnd), 0); - SendMessage(GetParent(hwnd), PSM_CANCELTOCLOSE, 0, 0); - /* Make sure the installation directory name ends in a */ - /* backslash */ - if (python_dir[strlen(python_dir)-1] != '\\') - strcat(python_dir, "\\"); - /* Strip the trailing backslash again */ - python_dir[strlen(python_dir)-1] = '\0'; - - CheckRootKey(hwnd); - - if (!OpenLogfile(python_dir)) - break; + LPNMHDR lpnm; + char Buffer[4096]; + SCHEME *scheme; + + switch (msg) { + case WM_INITDIALOG: + if (hBitmap) + SendDlgItemMessage(hwnd, IDC_BITMAP, STM_SETIMAGE, + IMAGE_BITMAP, (LPARAM)hBitmap); + wsprintf(Buffer, + "Click Next to begin the installation of %s. " + "If you want to review or change any of your " + " installation settings, click Back. " + "Click Cancel to exit the wizard.", + meta_name); + SetDlgItemText(hwnd, IDC_TITLE, Buffer); + SetDlgItemText(hwnd, IDC_INFO, "Ready to install"); + break; + + case WM_NUMFILES: + SendDlgItemMessage(hwnd, IDC_PROGRESS, PBM_SETRANGE, 0, lParam); + PumpMessages(); + return TRUE; + + case WM_NEXTFILE: + SendDlgItemMessage(hwnd, IDC_PROGRESS, PBM_SETPOS, wParam, + 0); + SetDlgItemText(hwnd, IDC_INFO, (LPSTR)lParam); + PumpMessages(); + return TRUE; + + case WM_NOTIFY: + lpnm = (LPNMHDR) lParam; + + switch (lpnm->code) { + case PSN_SETACTIVE: + PropSheet_SetWizButtons(GetParent(hwnd), + PSWIZB_BACK | PSWIZB_NEXT); + break; + + case PSN_WIZFINISH: + break; + + case PSN_WIZNEXT: + /* Handle a Next button click here */ + hDialog = hwnd; + success = TRUE; + + /* Disable the buttons while we work. Sending CANCELTOCLOSE has + the effect of disabling the cancel button, which is a) as we + do everything synchronously we can't cancel, and b) the next + step is 'finished', when it is too late to cancel anyway. + The next step being 'Finished' means we also don't need to + restore the button state back */ + PropSheet_SetWizButtons(GetParent(hwnd), 0); + SendMessage(GetParent(hwnd), PSM_CANCELTOCLOSE, 0, 0); + /* Make sure the installation directory name ends in a */ + /* backslash */ + if (python_dir[strlen(python_dir)-1] != '\\') + strcat(python_dir, "\\"); + /* Strip the trailing backslash again */ + python_dir[strlen(python_dir)-1] = '\0'; + + CheckRootKey(hwnd); + + if (!OpenLogfile(python_dir)) + break; /* * The scheme we have to use depends on the Python version... @@ -1947,202 +1947,202 @@ 'data' : '$base', } */ - scheme = GetScheme(py_major, py_minor); - /* Run the pre-install script. */ - if (pre_install_script && *pre_install_script) { - SetDlgItemText (hwnd, IDC_TITLE, - "Running pre-installation script"); - run_simple_script(pre_install_script); - } - if (!success) { - break; - } - /* Extract all files from the archive */ - SetDlgItemText(hwnd, IDC_TITLE, "Installing files..."); - if (!unzip_archive (scheme, - python_dir, arc_data, - arc_size, notify)) - set_failure_reason("Failed to unzip installation files"); - /* Compile the py-files */ - if (success && pyc_compile) { - int errors; - HINSTANCE hPython; - SetDlgItemText(hwnd, IDC_TITLE, - "Compiling files to .pyc..."); - - SetDlgItemText(hDialog, IDC_INFO, "Loading python..."); - hPython = LoadPythonDll(pythondll); - if (hPython) { - errors = compile_filelist(hPython, FALSE); - FreeLibrary(hPython); - } - /* Compilation errors are intentionally ignored: - * Python2.0 contains a bug which will result - * in sys.path containing garbage under certain - * circumstances, and an error message will only - * confuse the user. - */ - } - if (success && pyo_compile) { - int errors; - HINSTANCE hPython; - SetDlgItemText(hwnd, IDC_TITLE, - "Compiling files to .pyo..."); - - SetDlgItemText(hDialog, IDC_INFO, "Loading python..."); - hPython = LoadPythonDll(pythondll); - if (hPython) { - errors = compile_filelist(hPython, TRUE); - FreeLibrary(hPython); - } - /* Errors ignored: see above */ - } - - - break; - - case PSN_RESET: - break; - - default: - break; - } - } - return 0; + scheme = GetScheme(py_major, py_minor); + /* Run the pre-install script. */ + if (pre_install_script && *pre_install_script) { + SetDlgItemText (hwnd, IDC_TITLE, + "Running pre-installation script"); + run_simple_script(pre_install_script); + } + if (!success) { + break; + } + /* Extract all files from the archive */ + SetDlgItemText(hwnd, IDC_TITLE, "Installing files..."); + if (!unzip_archive (scheme, + python_dir, arc_data, + arc_size, notify)) + set_failure_reason("Failed to unzip installation files"); + /* Compile the py-files */ + if (success && pyc_compile) { + int errors; + HINSTANCE hPython; + SetDlgItemText(hwnd, IDC_TITLE, + "Compiling files to .pyc..."); + + SetDlgItemText(hDialog, IDC_INFO, "Loading python..."); + hPython = LoadPythonDll(pythondll); + if (hPython) { + errors = compile_filelist(hPython, FALSE); + FreeLibrary(hPython); + } + /* Compilation errors are intentionally ignored: + * Python2.0 contains a bug which will result + * in sys.path containing garbage under certain + * circumstances, and an error message will only + * confuse the user. + */ + } + if (success && pyo_compile) { + int errors; + HINSTANCE hPython; + SetDlgItemText(hwnd, IDC_TITLE, + "Compiling files to .pyo..."); + + SetDlgItemText(hDialog, IDC_INFO, "Loading python..."); + hPython = LoadPythonDll(pythondll); + if (hPython) { + errors = compile_filelist(hPython, TRUE); + FreeLibrary(hPython); + } + /* Errors ignored: see above */ + } + + + break; + + case PSN_RESET: + break; + + default: + break; + } + } + return 0; } BOOL CALLBACK FinishedDlgProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam) { - LPNMHDR lpnm; + LPNMHDR lpnm; - switch (msg) { - case WM_INITDIALOG: - if (hBitmap) - SendDlgItemMessage(hwnd, IDC_BITMAP, STM_SETIMAGE, - IMAGE_BITMAP, (LPARAM)hBitmap); - if (!success) - SetDlgItemText(hwnd, IDC_INFO, get_failure_reason()); - - /* async delay: will show the dialog box completely before - the install_script is started */ - PostMessage(hwnd, WM_USER, 0, 0L); - return TRUE; - - case WM_USER: - - if (success && install_script && install_script[0]) { - char fname[MAX_PATH]; - char *buffer; - HCURSOR hCursor; - int result; - - char *argv[3] = {NULL, "-install", NULL}; - - SetDlgItemText(hwnd, IDC_TITLE, - "Please wait while running postinstall script..."); - strcpy(fname, python_dir); - strcat(fname, "\\Scripts\\"); - strcat(fname, install_script); - - if (logfile) - fprintf(logfile, "300 Run Script: [%s]%s\n", pythondll, fname); - - hCursor = SetCursor(LoadCursor(NULL, IDC_WAIT)); - - argv[0] = fname; - - result = run_installscript(fname, 2, argv, &buffer); - if (0 != result) { - fprintf(stderr, "*** run_installscript: internal error 0x%X ***\n", result); - } - if (buffer) - SetDlgItemText(hwnd, IDC_INFO, buffer); - SetDlgItemText(hwnd, IDC_TITLE, - "Postinstall script finished.\n" - "Click the Finish button to exit the Setup wizard."); - - free(buffer); - SetCursor(hCursor); - CloseLogfile(); - } - - return TRUE; - - case WM_NOTIFY: - lpnm = (LPNMHDR) lParam; - - switch (lpnm->code) { - case PSN_SETACTIVE: /* Enable the Finish button */ - PropSheet_SetWizButtons(GetParent(hwnd), PSWIZB_FINISH); - break; - - case PSN_WIZNEXT: - break; - - case PSN_WIZFINISH: - break; - - case PSN_RESET: - break; - - default: - break; - } - } - return 0; + switch (msg) { + case WM_INITDIALOG: + if (hBitmap) + SendDlgItemMessage(hwnd, IDC_BITMAP, STM_SETIMAGE, + IMAGE_BITMAP, (LPARAM)hBitmap); + if (!success) + SetDlgItemText(hwnd, IDC_INFO, get_failure_reason()); + + /* async delay: will show the dialog box completely before + the install_script is started */ + PostMessage(hwnd, WM_USER, 0, 0L); + return TRUE; + + case WM_USER: + + if (success && install_script && install_script[0]) { + char fname[MAX_PATH]; + char *buffer; + HCURSOR hCursor; + int result; + + char *argv[3] = {NULL, "-install", NULL}; + + SetDlgItemText(hwnd, IDC_TITLE, + "Please wait while running postinstall script..."); + strcpy(fname, python_dir); + strcat(fname, "\\Scripts\\"); + strcat(fname, install_script); + + if (logfile) + fprintf(logfile, "300 Run Script: [%s]%s\n", pythondll, fname); + + hCursor = SetCursor(LoadCursor(NULL, IDC_WAIT)); + + argv[0] = fname; + + result = run_installscript(fname, 2, argv, &buffer); + if (0 != result) { + fprintf(stderr, "*** run_installscript: internal error 0x%X ***\n", result); + } + if (buffer) + SetDlgItemText(hwnd, IDC_INFO, buffer); + SetDlgItemText(hwnd, IDC_TITLE, + "Postinstall script finished.\n" + "Click the Finish button to exit the Setup wizard."); + + free(buffer); + SetCursor(hCursor); + CloseLogfile(); + } + + return TRUE; + + case WM_NOTIFY: + lpnm = (LPNMHDR) lParam; + + switch (lpnm->code) { + case PSN_SETACTIVE: /* Enable the Finish button */ + PropSheet_SetWizButtons(GetParent(hwnd), PSWIZB_FINISH); + break; + + case PSN_WIZNEXT: + break; + + case PSN_WIZFINISH: + break; + + case PSN_RESET: + break; + + default: + break; + } + } + return 0; } void RunWizard(HWND hwnd) { - PROPSHEETPAGE psp = {0}; - HPROPSHEETPAGE ahpsp[4] = {0}; - PROPSHEETHEADER psh = {0}; - - /* Display module information */ - psp.dwSize = sizeof(psp); - psp.dwFlags = PSP_DEFAULT|PSP_HIDEHEADER; - psp.hInstance = GetModuleHandle (NULL); - psp.lParam = 0; - psp.pfnDlgProc = IntroDlgProc; - psp.pszTemplate = MAKEINTRESOURCE(IDD_INTRO); - - ahpsp[0] = CreatePropertySheetPage(&psp); - - /* Select python version to use */ - psp.dwFlags = PSP_DEFAULT|PSP_HIDEHEADER; - psp.pszTemplate = MAKEINTRESOURCE(IDD_SELECTPYTHON); - psp.pfnDlgProc = SelectPythonDlgProc; - - ahpsp[1] = CreatePropertySheetPage(&psp); - - /* Install the files */ - psp.dwFlags = PSP_DEFAULT|PSP_HIDEHEADER; - psp.pszTemplate = MAKEINTRESOURCE(IDD_INSTALLFILES); - psp.pfnDlgProc = InstallFilesDlgProc; - - ahpsp[2] = CreatePropertySheetPage(&psp); - - /* Show success or failure */ - psp.dwFlags = PSP_DEFAULT|PSP_HIDEHEADER; - psp.pszTemplate = MAKEINTRESOURCE(IDD_FINISHED); - psp.pfnDlgProc = FinishedDlgProc; - - ahpsp[3] = CreatePropertySheetPage(&psp); - - /* Create the property sheet */ - psh.dwSize = sizeof(psh); - psh.hInstance = GetModuleHandle(NULL); - psh.hwndParent = hwnd; - psh.phpage = ahpsp; - psh.dwFlags = PSH_WIZARD/*97*//*|PSH_WATERMARK|PSH_HEADER*/; - psh.pszbmWatermark = NULL; - psh.pszbmHeader = NULL; - psh.nStartPage = 0; - psh.nPages = 4; + PROPSHEETPAGE psp = {0}; + HPROPSHEETPAGE ahpsp[4] = {0}; + PROPSHEETHEADER psh = {0}; + + /* Display module information */ + psp.dwSize = sizeof(psp); + psp.dwFlags = PSP_DEFAULT|PSP_HIDEHEADER; + psp.hInstance = GetModuleHandle (NULL); + psp.lParam = 0; + psp.pfnDlgProc = IntroDlgProc; + psp.pszTemplate = MAKEINTRESOURCE(IDD_INTRO); + + ahpsp[0] = CreatePropertySheetPage(&psp); + + /* Select python version to use */ + psp.dwFlags = PSP_DEFAULT|PSP_HIDEHEADER; + psp.pszTemplate = MAKEINTRESOURCE(IDD_SELECTPYTHON); + psp.pfnDlgProc = SelectPythonDlgProc; + + ahpsp[1] = CreatePropertySheetPage(&psp); + + /* Install the files */ + psp.dwFlags = PSP_DEFAULT|PSP_HIDEHEADER; + psp.pszTemplate = MAKEINTRESOURCE(IDD_INSTALLFILES); + psp.pfnDlgProc = InstallFilesDlgProc; + + ahpsp[2] = CreatePropertySheetPage(&psp); + + /* Show success or failure */ + psp.dwFlags = PSP_DEFAULT|PSP_HIDEHEADER; + psp.pszTemplate = MAKEINTRESOURCE(IDD_FINISHED); + psp.pfnDlgProc = FinishedDlgProc; + + ahpsp[3] = CreatePropertySheetPage(&psp); + + /* Create the property sheet */ + psh.dwSize = sizeof(psh); + psh.hInstance = GetModuleHandle(NULL); + psh.hwndParent = hwnd; + psh.phpage = ahpsp; + psh.dwFlags = PSH_WIZARD/*97*//*|PSH_WATERMARK|PSH_HEADER*/; + psh.pszbmWatermark = NULL; + psh.pszbmHeader = NULL; + psh.nStartPage = 0; + psh.nPages = 4; - PropertySheet(&psh); + PropertySheet(&psh); } // subtly different from HasLocalMachinePrivs(), in that after executing @@ -2150,16 +2150,16 @@ // such implication for HasLocalMachinePrivs BOOL MyIsUserAnAdmin() { - typedef BOOL (WINAPI *PFNIsUserAnAdmin)(); - static PFNIsUserAnAdmin pfnIsUserAnAdmin = NULL; - HMODULE shell32; - // This function isn't guaranteed to be available (and it can't hurt - // to leave the library loaded) - if (0 == (shell32=LoadLibrary("shell32.dll"))) - return FALSE; - if (0 == (pfnIsUserAnAdmin=(PFNIsUserAnAdmin)GetProcAddress(shell32, "IsUserAnAdmin"))) - return FALSE; - return (*pfnIsUserAnAdmin)(); + typedef BOOL (WINAPI *PFNIsUserAnAdmin)(); + static PFNIsUserAnAdmin pfnIsUserAnAdmin = NULL; + HMODULE shell32; + // This function isn't guaranteed to be available (and it can't hurt + // to leave the library loaded) + if (0 == (shell32=LoadLibrary("shell32.dll"))) + return FALSE; + if (0 == (pfnIsUserAnAdmin=(PFNIsUserAnAdmin)GetProcAddress(shell32, "IsUserAnAdmin"))) + return FALSE; + return (*pfnIsUserAnAdmin)(); } // Some magic for Vista's UAC. If there is a target_version, and @@ -2171,38 +2171,38 @@ // Returns TRUE if we should spawn an elevated child BOOL NeedAutoUAC() { - HKEY hk; - char key_name[80]; - // no Python version info == we can't know yet. - if (target_version[0] == '\0') - return FALSE; - // see how python is current installed - wsprintf(key_name, - "Software\\Python\\PythonCore\\%s\\InstallPath", - target_version); - if (ERROR_SUCCESS != RegOpenKeyEx(HKEY_LOCAL_MACHINE, - key_name, 0, KEY_READ, &hk)) - return FALSE; - RegCloseKey(hk); - // Python is installed in HKLM - we must elevate. - return TRUE; + HKEY hk; + char key_name[80]; + // no Python version info == we can't know yet. + if (target_version[0] == '\0') + return FALSE; + // see how python is current installed + wsprintf(key_name, + "Software\\Python\\PythonCore\\%s\\InstallPath", + target_version); + if (ERROR_SUCCESS != RegOpenKeyEx(HKEY_LOCAL_MACHINE, + key_name, 0, KEY_READ, &hk)) + return FALSE; + RegCloseKey(hk); + // Python is installed in HKLM - we must elevate. + return TRUE; } // Returns TRUE if the platform supports UAC. BOOL PlatformSupportsUAC() { - // Note that win2k does seem to support ShellExecute with 'runas', - // but does *not* support IsUserAnAdmin - so we just pretend things - // only work on XP and later. - BOOL bIsWindowsXPorLater; - OSVERSIONINFO winverinfo; - winverinfo.dwOSVersionInfoSize = sizeof(winverinfo); - if (!GetVersionEx(&winverinfo)) - return FALSE; // something bad has gone wrong - bIsWindowsXPorLater = + // Note that win2k does seem to support ShellExecute with 'runas', + // but does *not* support IsUserAnAdmin - so we just pretend things + // only work on XP and later. + BOOL bIsWindowsXPorLater; + OSVERSIONINFO winverinfo; + winverinfo.dwOSVersionInfoSize = sizeof(winverinfo); + if (!GetVersionEx(&winverinfo)) + return FALSE; // something bad has gone wrong + bIsWindowsXPorLater = ( (winverinfo.dwMajorVersion > 5) || ( (winverinfo.dwMajorVersion == 5) && (winverinfo.dwMinorVersion >= 1) )); - return bIsWindowsXPorLater; + return bIsWindowsXPorLater; } // Spawn ourself as an elevated application. On failure, a message is @@ -2210,97 +2210,97 @@ // on error. void SpawnUAC() { - // interesting failure scenario that has been seen: initial executable - // runs from a network drive - but once elevated, that network share - // isn't seen, and ShellExecute fails with SE_ERR_ACCESSDENIED. - int ret = (int)ShellExecute(0, "runas", modulename, "", NULL, - SW_SHOWNORMAL); - if (ret <= 32) { - char msg[128]; - wsprintf(msg, "Failed to start elevated process (ShellExecute returned %d)", ret); - MessageBox(0, msg, "Setup", MB_OK | MB_ICONERROR); - } + // interesting failure scenario that has been seen: initial executable + // runs from a network drive - but once elevated, that network share + // isn't seen, and ShellExecute fails with SE_ERR_ACCESSDENIED. + int ret = (int)ShellExecute(0, "runas", modulename, "", NULL, + SW_SHOWNORMAL); + if (ret <= 32) { + char msg[128]; + wsprintf(msg, "Failed to start elevated process (ShellExecute returned %d)", ret); + MessageBox(0, msg, "Setup", MB_OK | MB_ICONERROR); + } } int DoInstall(void) { - char ini_buffer[4096]; + char ini_buffer[4096]; - /* Read installation information */ - GetPrivateProfileString("Setup", "title", "", ini_buffer, - sizeof(ini_buffer), ini_file); - unescape(title, ini_buffer, sizeof(title)); - - GetPrivateProfileString("Setup", "info", "", ini_buffer, - sizeof(ini_buffer), ini_file); - unescape(info, ini_buffer, sizeof(info)); - - GetPrivateProfileString("Setup", "build_info", "", build_info, - sizeof(build_info), ini_file); - - pyc_compile = GetPrivateProfileInt("Setup", "target_compile", 1, - ini_file); - pyo_compile = GetPrivateProfileInt("Setup", "target_optimize", 1, - ini_file); - - GetPrivateProfileString("Setup", "target_version", "", - target_version, sizeof(target_version), - ini_file); - - GetPrivateProfileString("metadata", "name", "", - meta_name, sizeof(meta_name), - ini_file); - - GetPrivateProfileString("Setup", "install_script", "", - install_script, sizeof(install_script), - ini_file); - - GetPrivateProfileString("Setup", "user_access_control", "", - user_access_control, sizeof(user_access_control), ini_file); - - // See if we need to do the Vista UAC magic. - if (strcmp(user_access_control, "force")==0) { - if (PlatformSupportsUAC() && !MyIsUserAnAdmin()) { - SpawnUAC(); - return 0; - } - // already admin - keep going - } else if (strcmp(user_access_control, "auto")==0) { - // Check if it looks like we need UAC control, based - // on how Python itself was installed. - if (PlatformSupportsUAC() && !MyIsUserAnAdmin() && NeedAutoUAC()) { - SpawnUAC(); - return 0; - } - } else { - // display a warning about unknown values - only the developer - // of the extension will see it (until they fix it!) - if (user_access_control[0] && strcmp(user_access_control, "none") != 0) { - MessageBox(GetFocus(), "Bad user_access_control value", "oops", MB_OK); - // nothing to do. - } - } - - hwndMain = CreateBackground(title); - - RunWizard(hwndMain); - - /* Clean up */ - UnmapViewOfFile(arc_data); - if (ini_file) - DeleteFile(ini_file); + /* Read installation information */ + GetPrivateProfileString("Setup", "title", "", ini_buffer, + sizeof(ini_buffer), ini_file); + unescape(title, ini_buffer, sizeof(title)); + + GetPrivateProfileString("Setup", "info", "", ini_buffer, + sizeof(ini_buffer), ini_file); + unescape(info, ini_buffer, sizeof(info)); + + GetPrivateProfileString("Setup", "build_info", "", build_info, + sizeof(build_info), ini_file); + + pyc_compile = GetPrivateProfileInt("Setup", "target_compile", 1, + ini_file); + pyo_compile = GetPrivateProfileInt("Setup", "target_optimize", 1, + ini_file); + + GetPrivateProfileString("Setup", "target_version", "", + target_version, sizeof(target_version), + ini_file); + + GetPrivateProfileString("metadata", "name", "", + meta_name, sizeof(meta_name), + ini_file); + + GetPrivateProfileString("Setup", "install_script", "", + install_script, sizeof(install_script), + ini_file); + + GetPrivateProfileString("Setup", "user_access_control", "", + user_access_control, sizeof(user_access_control), ini_file); + + // See if we need to do the Vista UAC magic. + if (strcmp(user_access_control, "force")==0) { + if (PlatformSupportsUAC() && !MyIsUserAnAdmin()) { + SpawnUAC(); + return 0; + } + // already admin - keep going + } else if (strcmp(user_access_control, "auto")==0) { + // Check if it looks like we need UAC control, based + // on how Python itself was installed. + if (PlatformSupportsUAC() && !MyIsUserAnAdmin() && NeedAutoUAC()) { + SpawnUAC(); + return 0; + } + } else { + // display a warning about unknown values - only the developer + // of the extension will see it (until they fix it!) + if (user_access_control[0] && strcmp(user_access_control, "none") != 0) { + MessageBox(GetFocus(), "Bad user_access_control value", "oops", MB_OK); + // nothing to do. + } + } + + hwndMain = CreateBackground(title); + + RunWizard(hwndMain); + + /* Clean up */ + UnmapViewOfFile(arc_data); + if (ini_file) + DeleteFile(ini_file); - if (hBitmap) - DeleteObject(hBitmap); + if (hBitmap) + DeleteObject(hBitmap); - return 0; + return 0; } /*********************** uninstall section ******************************/ static int compare(const void *p1, const void *p2) { - return strcmp(*(char **)p2, *(char **)p1); + return strcmp(*(char **)p2, *(char **)p1); } /* @@ -2314,380 +2314,380 @@ */ void remove_exe(void) { - char exename[_MAX_PATH]; - char batname[_MAX_PATH]; - FILE *fp; - STARTUPINFO si; - PROCESS_INFORMATION pi; - - GetModuleFileName(NULL, exename, sizeof(exename)); - sprintf(batname, "%s.bat", exename); - fp = fopen(batname, "w"); - fprintf(fp, ":Repeat\n"); - fprintf(fp, "del \"%s\"\n", exename); - fprintf(fp, "if exist \"%s\" goto Repeat\n", exename); - fprintf(fp, "del \"%s\"\n", batname); - fclose(fp); - - ZeroMemory(&si, sizeof(si)); - si.cb = sizeof(si); - si.dwFlags = STARTF_USESHOWWINDOW; - si.wShowWindow = SW_HIDE; - if (CreateProcess(NULL, - batname, - NULL, - NULL, - FALSE, - CREATE_SUSPENDED | IDLE_PRIORITY_CLASS, - NULL, - "\\", - &si, - &pi)) { - SetThreadPriority(pi.hThread, THREAD_PRIORITY_IDLE); - SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_TIME_CRITICAL); - SetPriorityClass(GetCurrentProcess(), HIGH_PRIORITY_CLASS); - CloseHandle(pi.hProcess); - ResumeThread(pi.hThread); - CloseHandle(pi.hThread); - } + char exename[_MAX_PATH]; + char batname[_MAX_PATH]; + FILE *fp; + STARTUPINFO si; + PROCESS_INFORMATION pi; + + GetModuleFileName(NULL, exename, sizeof(exename)); + sprintf(batname, "%s.bat", exename); + fp = fopen(batname, "w"); + fprintf(fp, ":Repeat\n"); + fprintf(fp, "del \"%s\"\n", exename); + fprintf(fp, "if exist \"%s\" goto Repeat\n", exename); + fprintf(fp, "del \"%s\"\n", batname); + fclose(fp); + + ZeroMemory(&si, sizeof(si)); + si.cb = sizeof(si); + si.dwFlags = STARTF_USESHOWWINDOW; + si.wShowWindow = SW_HIDE; + if (CreateProcess(NULL, + batname, + NULL, + NULL, + FALSE, + CREATE_SUSPENDED | IDLE_PRIORITY_CLASS, + NULL, + "\\", + &si, + &pi)) { + SetThreadPriority(pi.hThread, THREAD_PRIORITY_IDLE); + SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_TIME_CRITICAL); + SetPriorityClass(GetCurrentProcess(), HIGH_PRIORITY_CLASS); + CloseHandle(pi.hProcess); + ResumeThread(pi.hThread); + CloseHandle(pi.hThread); + } } void DeleteRegistryKey(char *string) { - char *keyname; - char *subkeyname; - char *delim; - HKEY hKey; - long result; - char *line; - - line = strdup(string); /* so we can change it */ - - keyname = strchr(line, '['); - if (!keyname) - return; - ++keyname; - - subkeyname = strchr(keyname, ']'); - if (!subkeyname) - return; - *subkeyname++='\0'; - delim = strchr(subkeyname, '\n'); - if (delim) - *delim = '\0'; - - result = RegOpenKeyEx(hkey_root, - keyname, - 0, - KEY_WRITE, - &hKey); - - if (result != ERROR_SUCCESS) - MessageBox(GetFocus(), string, "Could not open key", MB_OK); - else { - result = RegDeleteKey(hKey, subkeyname); - if (result != ERROR_SUCCESS && result != ERROR_FILE_NOT_FOUND) - MessageBox(GetFocus(), string, "Could not delete key", MB_OK); - RegCloseKey(hKey); - } - free(line); + char *keyname; + char *subkeyname; + char *delim; + HKEY hKey; + long result; + char *line; + + line = strdup(string); /* so we can change it */ + + keyname = strchr(line, '['); + if (!keyname) + return; + ++keyname; + + subkeyname = strchr(keyname, ']'); + if (!subkeyname) + return; + *subkeyname++='\0'; + delim = strchr(subkeyname, '\n'); + if (delim) + *delim = '\0'; + + result = RegOpenKeyEx(hkey_root, + keyname, + 0, + KEY_WRITE, + &hKey); + + if (result != ERROR_SUCCESS) + MessageBox(GetFocus(), string, "Could not open key", MB_OK); + else { + result = RegDeleteKey(hKey, subkeyname); + if (result != ERROR_SUCCESS && result != ERROR_FILE_NOT_FOUND) + MessageBox(GetFocus(), string, "Could not delete key", MB_OK); + RegCloseKey(hKey); + } + free(line); } void DeleteRegistryValue(char *string) { - char *keyname; - char *valuename; - char *value; - HKEY hKey; - long result; - char *line; + char *keyname; + char *valuename; + char *value; + HKEY hKey; + long result; + char *line; - line = strdup(string); /* so we can change it */ + line = strdup(string); /* so we can change it */ /* Format is 'Reg DB Value: [key]name=value' */ - keyname = strchr(line, '['); - if (!keyname) - return; - ++keyname; - valuename = strchr(keyname, ']'); - if (!valuename) - return; - *valuename++ = '\0'; - value = strchr(valuename, '='); - if (!value) - return; - - *value++ = '\0'; - - result = RegOpenKeyEx(hkey_root, - keyname, - 0, - KEY_WRITE, - &hKey); - if (result != ERROR_SUCCESS) - MessageBox(GetFocus(), string, "Could not open key", MB_OK); - else { - result = RegDeleteValue(hKey, valuename); - if (result != ERROR_SUCCESS && result != ERROR_FILE_NOT_FOUND) - MessageBox(GetFocus(), string, "Could not delete value", MB_OK); - RegCloseKey(hKey); - } - free(line); + keyname = strchr(line, '['); + if (!keyname) + return; + ++keyname; + valuename = strchr(keyname, ']'); + if (!valuename) + return; + *valuename++ = '\0'; + value = strchr(valuename, '='); + if (!value) + return; + + *value++ = '\0'; + + result = RegOpenKeyEx(hkey_root, + keyname, + 0, + KEY_WRITE, + &hKey); + if (result != ERROR_SUCCESS) + MessageBox(GetFocus(), string, "Could not open key", MB_OK); + else { + result = RegDeleteValue(hKey, valuename); + if (result != ERROR_SUCCESS && result != ERROR_FILE_NOT_FOUND) + MessageBox(GetFocus(), string, "Could not delete value", MB_OK); + RegCloseKey(hKey); + } + free(line); } BOOL MyDeleteFile(char *line) { - char *pathname = strchr(line, ':'); - if (!pathname) - return FALSE; - ++pathname; - while (isspace(*pathname)) - ++pathname; - return DeleteFile(pathname); + char *pathname = strchr(line, ':'); + if (!pathname) + return FALSE; + ++pathname; + while (isspace(*pathname)) + ++pathname; + return DeleteFile(pathname); } BOOL MyRemoveDirectory(char *line) { - char *pathname = strchr(line, ':'); - if (!pathname) - return FALSE; - ++pathname; - while (isspace(*pathname)) - ++pathname; - return RemoveDirectory(pathname); + char *pathname = strchr(line, ':'); + if (!pathname) + return FALSE; + ++pathname; + while (isspace(*pathname)) + ++pathname; + return RemoveDirectory(pathname); } BOOL Run_RemoveScript(char *line) { - char *dllname; - char *scriptname; - static char lastscript[MAX_PATH]; + char *dllname; + char *scriptname; + static char lastscript[MAX_PATH]; /* Format is 'Run Scripts: [pythondll]scriptname' */ /* XXX Currently, pythondll carries no path!!! */ - dllname = strchr(line, '['); - if (!dllname) - return FALSE; - ++dllname; - scriptname = strchr(dllname, ']'); - if (!scriptname) - return FALSE; - *scriptname++ = '\0'; - /* this function may be called more than one time with the same - script, only run it one time */ - if (strcmp(lastscript, scriptname)) { - char *argv[3] = {NULL, "-remove", NULL}; - char *buffer = NULL; - - argv[0] = scriptname; - - if (0 != run_installscript(scriptname, 2, argv, &buffer)) - fprintf(stderr, "*** Could not run installation script ***"); - - if (buffer && buffer[0]) - MessageBox(GetFocus(), buffer, "uninstall-script", MB_OK); - free(buffer); - - strcpy(lastscript, scriptname); - } - return TRUE; + dllname = strchr(line, '['); + if (!dllname) + return FALSE; + ++dllname; + scriptname = strchr(dllname, ']'); + if (!scriptname) + return FALSE; + *scriptname++ = '\0'; + /* this function may be called more than one time with the same + script, only run it one time */ + if (strcmp(lastscript, scriptname)) { + char *argv[3] = {NULL, "-remove", NULL}; + char *buffer = NULL; + + argv[0] = scriptname; + + if (0 != run_installscript(scriptname, 2, argv, &buffer)) + fprintf(stderr, "*** Could not run installation script ***"); + + if (buffer && buffer[0]) + MessageBox(GetFocus(), buffer, "uninstall-script", MB_OK); + free(buffer); + + strcpy(lastscript, scriptname); + } + return TRUE; } int DoUninstall(int argc, char **argv) { - FILE *logfile; - char buffer[4096]; - int nLines = 0; - int i; - char *cp; - int nFiles = 0; - int nDirs = 0; - int nErrors = 0; - char **lines; - int lines_buffer_size = 10; - - if (argc != 3) { - MessageBox(NULL, - "Wrong number of args", - NULL, - MB_OK); - return 1; /* Error */ - } - if (strcmp(argv[1], "-u")) { - MessageBox(NULL, - "2. arg is not -u", - NULL, - MB_OK); - return 1; /* Error */ - } - - logfile = fopen(argv[2], "r"); - if (!logfile) { - MessageBox(NULL, - "could not open logfile", - NULL, - MB_OK); - return 1; /* Error */ - } - - lines = (char **)malloc(sizeof(char *) * lines_buffer_size); - if (!lines) - return SystemError(0, "Out of memory"); - - /* Read the whole logfile, realloacting the buffer */ - while (fgets(buffer, sizeof(buffer), logfile)) { - int len = strlen(buffer); - /* remove trailing white space */ - while (isspace(buffer[len-1])) - len -= 1; - buffer[len] = '\0'; - lines[nLines++] = strdup(buffer); - if (nLines >= lines_buffer_size) { - lines_buffer_size += 10; - lines = (char **)realloc(lines, - sizeof(char *) * lines_buffer_size); - if (!lines) - return SystemError(0, "Out of memory"); - } - } - fclose(logfile); - - /* Sort all the lines, so that highest 3-digit codes are first */ - qsort(&lines[0], nLines, sizeof(char *), - compare); - - if (IDYES != MessageBox(NULL, - "Are you sure you want to remove\n" - "this package from your computer?", - "Please confirm", - MB_YESNO | MB_ICONQUESTION)) - return 0; - - hkey_root = HKEY_LOCAL_MACHINE; - cp = ""; - for (i = 0; i < nLines; ++i) { - /* Ignore duplicate lines */ - if (strcmp(cp, lines[i])) { - int ign; - cp = lines[i]; - /* Parse the lines */ - if (2 == sscanf(cp, "%d Root Key: %s", &ign, &buffer)) { - if (strcmp(buffer, "HKEY_CURRENT_USER")==0) - hkey_root = HKEY_CURRENT_USER; - else { - // HKLM - check they have permissions. - if (!HasLocalMachinePrivs()) { - MessageBox(GetFocus(), - "You do not seem to have sufficient access rights\n" - "on this machine to uninstall this software", - NULL, - MB_OK | MB_ICONSTOP); - return 1; /* Error */ - } - } - } else if (2 == sscanf(cp, "%d Made Dir: %s", &ign, &buffer)) { - if (MyRemoveDirectory(cp)) - ++nDirs; - else { - int code = GetLastError(); - if (code != 2 && code != 3) { /* file or path not found */ - ++nErrors; - } - } - } else if (2 == sscanf(cp, "%d File Copy: %s", &ign, &buffer)) { - if (MyDeleteFile(cp)) - ++nFiles; - else { - int code = GetLastError(); - if (code != 2 && code != 3) { /* file or path not found */ - ++nErrors; - } - } - } else if (2 == sscanf(cp, "%d File Overwrite: %s", &ign, &buffer)) { - if (MyDeleteFile(cp)) - ++nFiles; - else { - int code = GetLastError(); - if (code != 2 && code != 3) { /* file or path not found */ - ++nErrors; - } - } - } else if (2 == sscanf(cp, "%d Reg DB Key: %s", &ign, &buffer)) { - DeleteRegistryKey(cp); - } else if (2 == sscanf(cp, "%d Reg DB Value: %s", &ign, &buffer)) { - DeleteRegistryValue(cp); - } else if (2 == sscanf(cp, "%d Run Script: %s", &ign, &buffer)) { - Run_RemoveScript(cp); - } - } - } - - if (DeleteFile(argv[2])) { - ++nFiles; - } else { - ++nErrors; - SystemError(GetLastError(), argv[2]); - } - if (nErrors) - wsprintf(buffer, - "%d files and %d directories removed\n" - "%d files or directories could not be removed", - nFiles, nDirs, nErrors); - else - wsprintf(buffer, "%d files and %d directories removed", - nFiles, nDirs); - MessageBox(NULL, buffer, "Uninstall Finished!", - MB_OK | MB_ICONINFORMATION); - remove_exe(); - return 0; + FILE *logfile; + char buffer[4096]; + int nLines = 0; + int i; + char *cp; + int nFiles = 0; + int nDirs = 0; + int nErrors = 0; + char **lines; + int lines_buffer_size = 10; + + if (argc != 3) { + MessageBox(NULL, + "Wrong number of args", + NULL, + MB_OK); + return 1; /* Error */ + } + if (strcmp(argv[1], "-u")) { + MessageBox(NULL, + "2. arg is not -u", + NULL, + MB_OK); + return 1; /* Error */ + } + + logfile = fopen(argv[2], "r"); + if (!logfile) { + MessageBox(NULL, + "could not open logfile", + NULL, + MB_OK); + return 1; /* Error */ + } + + lines = (char **)malloc(sizeof(char *) * lines_buffer_size); + if (!lines) + return SystemError(0, "Out of memory"); + + /* Read the whole logfile, realloacting the buffer */ + while (fgets(buffer, sizeof(buffer), logfile)) { + int len = strlen(buffer); + /* remove trailing white space */ + while (isspace(buffer[len-1])) + len -= 1; + buffer[len] = '\0'; + lines[nLines++] = strdup(buffer); + if (nLines >= lines_buffer_size) { + lines_buffer_size += 10; + lines = (char **)realloc(lines, + sizeof(char *) * lines_buffer_size); + if (!lines) + return SystemError(0, "Out of memory"); + } + } + fclose(logfile); + + /* Sort all the lines, so that highest 3-digit codes are first */ + qsort(&lines[0], nLines, sizeof(char *), + compare); + + if (IDYES != MessageBox(NULL, + "Are you sure you want to remove\n" + "this package from your computer?", + "Please confirm", + MB_YESNO | MB_ICONQUESTION)) + return 0; + + hkey_root = HKEY_LOCAL_MACHINE; + cp = ""; + for (i = 0; i < nLines; ++i) { + /* Ignore duplicate lines */ + if (strcmp(cp, lines[i])) { + int ign; + cp = lines[i]; + /* Parse the lines */ + if (2 == sscanf(cp, "%d Root Key: %s", &ign, &buffer)) { + if (strcmp(buffer, "HKEY_CURRENT_USER")==0) + hkey_root = HKEY_CURRENT_USER; + else { + // HKLM - check they have permissions. + if (!HasLocalMachinePrivs()) { + MessageBox(GetFocus(), + "You do not seem to have sufficient access rights\n" + "on this machine to uninstall this software", + NULL, + MB_OK | MB_ICONSTOP); + return 1; /* Error */ + } + } + } else if (2 == sscanf(cp, "%d Made Dir: %s", &ign, &buffer)) { + if (MyRemoveDirectory(cp)) + ++nDirs; + else { + int code = GetLastError(); + if (code != 2 && code != 3) { /* file or path not found */ + ++nErrors; + } + } + } else if (2 == sscanf(cp, "%d File Copy: %s", &ign, &buffer)) { + if (MyDeleteFile(cp)) + ++nFiles; + else { + int code = GetLastError(); + if (code != 2 && code != 3) { /* file or path not found */ + ++nErrors; + } + } + } else if (2 == sscanf(cp, "%d File Overwrite: %s", &ign, &buffer)) { + if (MyDeleteFile(cp)) + ++nFiles; + else { + int code = GetLastError(); + if (code != 2 && code != 3) { /* file or path not found */ + ++nErrors; + } + } + } else if (2 == sscanf(cp, "%d Reg DB Key: %s", &ign, &buffer)) { + DeleteRegistryKey(cp); + } else if (2 == sscanf(cp, "%d Reg DB Value: %s", &ign, &buffer)) { + DeleteRegistryValue(cp); + } else if (2 == sscanf(cp, "%d Run Script: %s", &ign, &buffer)) { + Run_RemoveScript(cp); + } + } + } + + if (DeleteFile(argv[2])) { + ++nFiles; + } else { + ++nErrors; + SystemError(GetLastError(), argv[2]); + } + if (nErrors) + wsprintf(buffer, + "%d files and %d directories removed\n" + "%d files or directories could not be removed", + nFiles, nDirs, nErrors); + else + wsprintf(buffer, "%d files and %d directories removed", + nFiles, nDirs); + MessageBox(NULL, buffer, "Uninstall Finished!", + MB_OK | MB_ICONINFORMATION); + remove_exe(); + return 0; } int WINAPI WinMain(HINSTANCE hInst, HINSTANCE hPrevInst, - LPSTR lpszCmdLine, INT nCmdShow) + LPSTR lpszCmdLine, INT nCmdShow) { - extern int __argc; - extern char **__argv; - char *basename; - - GetModuleFileName(NULL, modulename, sizeof(modulename)); - GetModuleFileNameW(NULL, wmodulename, sizeof(wmodulename)/sizeof(wmodulename[0])); - - /* Map the executable file to memory */ - arc_data = MapExistingFile(modulename, &arc_size); - if (!arc_data) { - SystemError(GetLastError(), "Could not open archive"); - return 1; - } - - /* OK. So this program can act as installer (self-extracting - * zip-file, or as uninstaller when started with '-u logfile' - * command line flags. - * - * The installer is usually started without command line flags, - * and the uninstaller is usually started with the '-u logfile' - * flag. What to do if some innocent user double-clicks the - * exe-file? - * The following implements a defensive strategy... - */ - - /* Try to extract the configuration data into a temporary file */ - if (ExtractInstallData(arc_data, arc_size, &exe_size, - &ini_file, &pre_install_script)) - return DoInstall(); - - if (!ini_file && __argc > 1) { - return DoUninstall(__argc, __argv); - } - - - basename = strrchr(modulename, '\\'); - if (basename) - ++basename; - - /* Last guess about the purpose of this program */ - if (basename && (0 == strncmp(basename, "Remove", 6))) - SystemError(0, "This program is normally started by windows"); - else - SystemError(0, "Setup program invalid or damaged"); - return 1; + extern int __argc; + extern char **__argv; + char *basename; + + GetModuleFileName(NULL, modulename, sizeof(modulename)); + GetModuleFileNameW(NULL, wmodulename, sizeof(wmodulename)/sizeof(wmodulename[0])); + + /* Map the executable file to memory */ + arc_data = MapExistingFile(modulename, &arc_size); + if (!arc_data) { + SystemError(GetLastError(), "Could not open archive"); + return 1; + } + + /* OK. So this program can act as installer (self-extracting + * zip-file, or as uninstaller when started with '-u logfile' + * command line flags. + * + * The installer is usually started without command line flags, + * and the uninstaller is usually started with the '-u logfile' + * flag. What to do if some innocent user double-clicks the + * exe-file? + * The following implements a defensive strategy... + */ + + /* Try to extract the configuration data into a temporary file */ + if (ExtractInstallData(arc_data, arc_size, &exe_size, + &ini_file, &pre_install_script)) + return DoInstall(); + + if (!ini_file && __argc > 1) { + return DoUninstall(__argc, __argv); + } + + + basename = strrchr(modulename, '\\'); + if (basename) + ++basename; + + /* Last guess about the purpose of this program */ + if (basename && (0 == strncmp(basename, "Remove", 6))) + SystemError(0, "This program is normally started by windows"); + else + SystemError(0, "Setup program invalid or damaged"); + return 1; } Modified: python/branches/release31-maint/PC/config.c ============================================================================== --- python/branches/release31-maint/PC/config.c (original) +++ python/branches/release31-maint/PC/config.c Sun May 9 18:14:21 2010 @@ -71,87 +71,87 @@ struct _inittab _PyImport_Inittab[] = { - {"array", PyInit_array}, - {"_ast", PyInit__ast}, + {"array", PyInit_array}, + {"_ast", PyInit__ast}, #ifdef MS_WINDOWS #ifndef MS_WINI64 - {"audioop", PyInit_audioop}, + {"audioop", PyInit_audioop}, #endif #endif - {"binascii", PyInit_binascii}, - {"cmath", PyInit_cmath}, - {"errno", PyInit_errno}, - {"gc", PyInit_gc}, - {"math", PyInit_math}, - {"nt", PyInit_nt}, /* Use the NT os functions, not posix */ - {"operator", PyInit_operator}, - {"signal", PyInit_signal}, - {"_md5", PyInit__md5}, - {"_sha1", PyInit__sha1}, - {"_sha256", PyInit__sha256}, - {"_sha512", PyInit__sha512}, - {"time", PyInit_time}, + {"binascii", PyInit_binascii}, + {"cmath", PyInit_cmath}, + {"errno", PyInit_errno}, + {"gc", PyInit_gc}, + {"math", PyInit_math}, + {"nt", PyInit_nt}, /* Use the NT os functions, not posix */ + {"operator", PyInit_operator}, + {"signal", PyInit_signal}, + {"_md5", PyInit__md5}, + {"_sha1", PyInit__sha1}, + {"_sha256", PyInit__sha256}, + {"_sha512", PyInit__sha512}, + {"time", PyInit_time}, #ifdef WITH_THREAD - {"_thread", PyInit__thread}, + {"_thread", PyInit__thread}, #endif #ifdef WIN32 - {"msvcrt", PyInit_msvcrt}, - {"_locale", PyInit__locale}, + {"msvcrt", PyInit_msvcrt}, + {"_locale", PyInit__locale}, #endif - /* XXX Should _subprocess go in a WIN32 block? not WIN64? */ - {"_subprocess", PyInit__subprocess}, + /* XXX Should _subprocess go in a WIN32 block? not WIN64? */ + {"_subprocess", PyInit__subprocess}, - {"_codecs", PyInit__codecs}, - {"_weakref", PyInit__weakref}, - {"_random", PyInit__random}, - {"_bisect", PyInit__bisect}, - {"_heapq", PyInit__heapq}, - {"_lsprof", PyInit__lsprof}, - {"itertools", PyInit_itertools}, - {"_collections", PyInit__collections}, - {"_symtable", PyInit__symtable}, - {"mmap", PyInit_mmap}, - {"_csv", PyInit__csv}, - {"_sre", PyInit__sre}, - {"parser", PyInit_parser}, - {"winreg", PyInit_winreg}, - {"_struct", PyInit__struct}, - {"datetime", PyInit_datetime}, - {"_functools", PyInit__functools}, - {"_json", PyInit__json}, - - {"xxsubtype", PyInit_xxsubtype}, - {"zipimport", PyInit_zipimport}, - {"zlib", PyInit_zlib}, - - /* CJK codecs */ - {"_multibytecodec", PyInit__multibytecodec}, - {"_codecs_cn", PyInit__codecs_cn}, - {"_codecs_hk", PyInit__codecs_hk}, - {"_codecs_iso2022", PyInit__codecs_iso2022}, - {"_codecs_jp", PyInit__codecs_jp}, - {"_codecs_kr", PyInit__codecs_kr}, - {"_codecs_tw", PyInit__codecs_tw}, + {"_codecs", PyInit__codecs}, + {"_weakref", PyInit__weakref}, + {"_random", PyInit__random}, + {"_bisect", PyInit__bisect}, + {"_heapq", PyInit__heapq}, + {"_lsprof", PyInit__lsprof}, + {"itertools", PyInit_itertools}, + {"_collections", PyInit__collections}, + {"_symtable", PyInit__symtable}, + {"mmap", PyInit_mmap}, + {"_csv", PyInit__csv}, + {"_sre", PyInit__sre}, + {"parser", PyInit_parser}, + {"winreg", PyInit_winreg}, + {"_struct", PyInit__struct}, + {"datetime", PyInit_datetime}, + {"_functools", PyInit__functools}, + {"_json", PyInit__json}, + + {"xxsubtype", PyInit_xxsubtype}, + {"zipimport", PyInit_zipimport}, + {"zlib", PyInit_zlib}, + + /* CJK codecs */ + {"_multibytecodec", PyInit__multibytecodec}, + {"_codecs_cn", PyInit__codecs_cn}, + {"_codecs_hk", PyInit__codecs_hk}, + {"_codecs_iso2022", PyInit__codecs_iso2022}, + {"_codecs_jp", PyInit__codecs_jp}, + {"_codecs_kr", PyInit__codecs_kr}, + {"_codecs_tw", PyInit__codecs_tw}, /* tools/freeze/makeconfig.py marker for additional "_inittab" entries */ /* -- ADDMODULE MARKER 2 -- */ - /* This module "lives in" with marshal.c */ - {"marshal", PyMarshal_Init}, + /* This module "lives in" with marshal.c */ + {"marshal", PyMarshal_Init}, - /* This lives it with import.c */ - {"imp", PyInit_imp}, + /* This lives it with import.c */ + {"imp", PyInit_imp}, - /* These entries are here for sys.builtin_module_names */ - {"__main__", NULL}, - {"builtins", NULL}, - {"sys", NULL}, - {"_warnings", _PyWarnings_Init}, - - {"_io", PyInit__io}, - {"_pickle", PyInit__pickle}, - {"atexit", PyInit_atexit}, + /* These entries are here for sys.builtin_module_names */ + {"__main__", NULL}, + {"builtins", NULL}, + {"sys", NULL}, + {"_warnings", _PyWarnings_Init}, + + {"_io", PyInit__io}, + {"_pickle", PyInit__pickle}, + {"atexit", PyInit_atexit}, - /* Sentinel */ - {0, 0} + /* Sentinel */ + {0, 0} }; Modified: python/branches/release31-maint/PC/dl_nt.c ============================================================================== --- python/branches/release31-maint/PC/dl_nt.c (original) +++ python/branches/release31-maint/PC/dl_nt.c Sun May 9 18:14:21 2010 @@ -3,7 +3,7 @@ Entry point for the Windows NT DLL. About the only reason for having this, is so initall() can automatically -be called, removing that burden (and possible source of frustration if +be called, removing that burden (and possible source of frustration if forgotten) from the programmer. */ @@ -46,61 +46,61 @@ void _LoadActCtxPointers() { - HINSTANCE hKernel32 = GetModuleHandleW(L"kernel32.dll"); - if (hKernel32) - pfnGetCurrentActCtx = (PFN_GETCURRENTACTCTX) GetProcAddress(hKernel32, "GetCurrentActCtx"); - // If we can't load GetCurrentActCtx (ie, pre XP) , don't bother with the rest. - if (pfnGetCurrentActCtx) { - pfnActivateActCtx = (PFN_ACTIVATEACTCTX) GetProcAddress(hKernel32, "ActivateActCtx"); - pfnDeactivateActCtx = (PFN_DEACTIVATEACTCTX) GetProcAddress(hKernel32, "DeactivateActCtx"); - pfnAddRefActCtx = (PFN_ADDREFACTCTX) GetProcAddress(hKernel32, "AddRefActCtx"); - pfnReleaseActCtx = (PFN_RELEASEACTCTX) GetProcAddress(hKernel32, "ReleaseActCtx"); - } + HINSTANCE hKernel32 = GetModuleHandleW(L"kernel32.dll"); + if (hKernel32) + pfnGetCurrentActCtx = (PFN_GETCURRENTACTCTX) GetProcAddress(hKernel32, "GetCurrentActCtx"); + // If we can't load GetCurrentActCtx (ie, pre XP) , don't bother with the rest. + if (pfnGetCurrentActCtx) { + pfnActivateActCtx = (PFN_ACTIVATEACTCTX) GetProcAddress(hKernel32, "ActivateActCtx"); + pfnDeactivateActCtx = (PFN_DEACTIVATEACTCTX) GetProcAddress(hKernel32, "DeactivateActCtx"); + pfnAddRefActCtx = (PFN_ADDREFACTCTX) GetProcAddress(hKernel32, "AddRefActCtx"); + pfnReleaseActCtx = (PFN_RELEASEACTCTX) GetProcAddress(hKernel32, "ReleaseActCtx"); + } } ULONG_PTR _Py_ActivateActCtx() { - ULONG_PTR ret = 0; - if (PyWin_DLLhActivationContext && pfnActivateActCtx) - if (!(*pfnActivateActCtx)(PyWin_DLLhActivationContext, &ret)) { - OutputDebugString("Python failed to activate the activation context before loading a DLL\n"); - ret = 0; // no promise the failing function didn't change it! - } - return ret; + ULONG_PTR ret = 0; + if (PyWin_DLLhActivationContext && pfnActivateActCtx) + if (!(*pfnActivateActCtx)(PyWin_DLLhActivationContext, &ret)) { + OutputDebugString("Python failed to activate the activation context before loading a DLL\n"); + ret = 0; // no promise the failing function didn't change it! + } + return ret; } void _Py_DeactivateActCtx(ULONG_PTR cookie) { - if (cookie && pfnDeactivateActCtx) - if (!(*pfnDeactivateActCtx)(0, cookie)) - OutputDebugString("Python failed to de-activate the activation context\n"); + if (cookie && pfnDeactivateActCtx) + if (!(*pfnDeactivateActCtx)(0, cookie)) + OutputDebugString("Python failed to de-activate the activation context\n"); } -BOOL WINAPI DllMain (HANDLE hInst, - ULONG ul_reason_for_call, - LPVOID lpReserved) +BOOL WINAPI DllMain (HANDLE hInst, + ULONG ul_reason_for_call, + LPVOID lpReserved) { - switch (ul_reason_for_call) - { - case DLL_PROCESS_ATTACH: - PyWin_DLLhModule = hInst; - // 1000 is a magic number I picked out of the air. Could do with a #define, I spose... - LoadString(hInst, 1000, dllVersionBuffer, sizeof(dllVersionBuffer)); - - // and capture our activation context for use when loading extensions. - _LoadActCtxPointers(); - if (pfnGetCurrentActCtx && pfnAddRefActCtx) - if ((*pfnGetCurrentActCtx)(&PyWin_DLLhActivationContext)) - if (!(*pfnAddRefActCtx)(PyWin_DLLhActivationContext)) - OutputDebugString("Python failed to load the default activation context\n"); - break; - - case DLL_PROCESS_DETACH: - if (pfnReleaseActCtx) - (*pfnReleaseActCtx)(PyWin_DLLhActivationContext); - break; - } - return TRUE; + switch (ul_reason_for_call) + { + case DLL_PROCESS_ATTACH: + PyWin_DLLhModule = hInst; + // 1000 is a magic number I picked out of the air. Could do with a #define, I spose... + LoadString(hInst, 1000, dllVersionBuffer, sizeof(dllVersionBuffer)); + + // and capture our activation context for use when loading extensions. + _LoadActCtxPointers(); + if (pfnGetCurrentActCtx && pfnAddRefActCtx) + if ((*pfnGetCurrentActCtx)(&PyWin_DLLhActivationContext)) + if (!(*pfnAddRefActCtx)(PyWin_DLLhActivationContext)) + OutputDebugString("Python failed to load the default activation context\n"); + break; + + case DLL_PROCESS_DETACH: + if (pfnReleaseActCtx) + (*pfnReleaseActCtx)(PyWin_DLLhActivationContext); + break; + } + return TRUE; } #endif /* Py_ENABLE_SHARED */ Modified: python/branches/release31-maint/PC/errmap.h ============================================================================== --- python/branches/release31-maint/PC/errmap.h (original) +++ python/branches/release31-maint/PC/errmap.h Sun May 9 18:14:21 2010 @@ -1,78 +1,78 @@ /* Generated file. Do not edit. */ int winerror_to_errno(int winerror) { - switch(winerror) { - case 2: return 2; - case 3: return 2; - case 4: return 24; - case 5: return 13; - case 6: return 9; - case 7: return 12; - case 8: return 12; - case 9: return 12; - case 10: return 7; - case 11: return 8; - case 15: return 2; - case 16: return 13; - case 17: return 18; - case 18: return 2; - case 19: return 13; - case 20: return 13; - case 21: return 13; - case 22: return 13; - case 23: return 13; - case 24: return 13; - case 25: return 13; - case 26: return 13; - case 27: return 13; - case 28: return 13; - case 29: return 13; - case 30: return 13; - case 31: return 13; - case 32: return 13; - case 33: return 13; - case 34: return 13; - case 35: return 13; - case 36: return 13; - case 53: return 2; - case 65: return 13; - case 67: return 2; - case 80: return 17; - case 82: return 13; - case 83: return 13; - case 89: return 11; - case 108: return 13; - case 109: return 32; - case 112: return 28; - case 114: return 9; - case 128: return 10; - case 129: return 10; - case 130: return 9; - case 132: return 13; - case 145: return 41; - case 158: return 13; - case 161: return 2; - case 164: return 11; - case 167: return 13; - case 183: return 17; - case 188: return 8; - case 189: return 8; - case 190: return 8; - case 191: return 8; - case 192: return 8; - case 193: return 8; - case 194: return 8; - case 195: return 8; - case 196: return 8; - case 197: return 8; - case 198: return 8; - case 199: return 8; - case 200: return 8; - case 201: return 8; - case 202: return 8; - case 206: return 2; - case 215: return 11; - case 1816: return 12; - default: return EINVAL; - } + switch(winerror) { + case 2: return 2; + case 3: return 2; + case 4: return 24; + case 5: return 13; + case 6: return 9; + case 7: return 12; + case 8: return 12; + case 9: return 12; + case 10: return 7; + case 11: return 8; + case 15: return 2; + case 16: return 13; + case 17: return 18; + case 18: return 2; + case 19: return 13; + case 20: return 13; + case 21: return 13; + case 22: return 13; + case 23: return 13; + case 24: return 13; + case 25: return 13; + case 26: return 13; + case 27: return 13; + case 28: return 13; + case 29: return 13; + case 30: return 13; + case 31: return 13; + case 32: return 13; + case 33: return 13; + case 34: return 13; + case 35: return 13; + case 36: return 13; + case 53: return 2; + case 65: return 13; + case 67: return 2; + case 80: return 17; + case 82: return 13; + case 83: return 13; + case 89: return 11; + case 108: return 13; + case 109: return 32; + case 112: return 28; + case 114: return 9; + case 128: return 10; + case 129: return 10; + case 130: return 9; + case 132: return 13; + case 145: return 41; + case 158: return 13; + case 161: return 2; + case 164: return 11; + case 167: return 13; + case 183: return 17; + case 188: return 8; + case 189: return 8; + case 190: return 8; + case 191: return 8; + case 192: return 8; + case 193: return 8; + case 194: return 8; + case 195: return 8; + case 196: return 8; + case 197: return 8; + case 198: return 8; + case 199: return 8; + case 200: return 8; + case 201: return 8; + case 202: return 8; + case 206: return 2; + case 215: return 11; + case 1816: return 12; + default: return EINVAL; + } } Modified: python/branches/release31-maint/PC/example_nt/example.c ============================================================================== --- python/branches/release31-maint/PC/example_nt/example.c (original) +++ python/branches/release31-maint/PC/example_nt/example.c Sun May 9 18:14:21 2010 @@ -3,30 +3,30 @@ static PyObject * ex_foo(PyObject *self, PyObject *args) { - printf("Hello, world\n"); - Py_INCREF(Py_None); - return Py_None; + printf("Hello, world\n"); + Py_INCREF(Py_None); + return Py_None; } static PyMethodDef example_methods[] = { - {"foo", ex_foo, METH_VARARGS, "foo() doc string"}, - {NULL, NULL} + {"foo", ex_foo, METH_VARARGS, "foo() doc string"}, + {NULL, NULL} }; static struct PyModuleDef examplemodule = { - PyModuleDef_HEAD_INIT, - "example", - "example module doc string", - -1, - example_methods, - NULL, - NULL, - NULL, - NULL + PyModuleDef_HEAD_INIT, + "example", + "example module doc string", + -1, + example_methods, + NULL, + NULL, + NULL, + NULL }; PyMODINIT_FUNC PyInit_example(void) { - return PyModule_Create(&examplemodule); + return PyModule_Create(&examplemodule); } Modified: python/branches/release31-maint/PC/frozen_dllmain.c ============================================================================== --- python/branches/release31-maint/PC/frozen_dllmain.c (original) +++ python/branches/release31-maint/PC/frozen_dllmain.c Sun May 9 18:14:21 2010 @@ -9,7 +9,7 @@ The solution is: * Each module checks for a frozen build, and if so, defines its DLLMain - function as "__declspec(dllexport) DllMain%module%" + function as "__declspec(dllexport) DllMain%module%" (eg, DllMainpythoncom, or DllMainpywintypes) * The frozen .EXE/.DLL links against this module, which provides @@ -47,10 +47,10 @@ #include "windows.h" static char *possibleModules[] = { - "pywintypes", - "pythoncom", - "win32ui", - NULL, + "pywintypes", + "pythoncom", + "win32ui", + NULL, }; BOOL CallModuleDllMain(char *modName, DWORD dwReason); @@ -62,73 +62,73 @@ */ void PyWinFreeze_ExeInit(void) { - char **modName; - for (modName = possibleModules;*modName;*modName++) { -/* printf("Initialising '%s'\n", *modName); */ - CallModuleDllMain(*modName, DLL_PROCESS_ATTACH); - } + char **modName; + for (modName = possibleModules;*modName;*modName++) { +/* printf("Initialising '%s'\n", *modName); */ + CallModuleDllMain(*modName, DLL_PROCESS_ATTACH); + } } /* Called by a frozen .EXE only, so that built-in extension - modules are cleaned up + modules are cleaned up */ void PyWinFreeze_ExeTerm(void) { - // Must go backwards - char **modName; - for (modName = possibleModules+(sizeof(possibleModules) / sizeof(char *))-2; - modName >= possibleModules; - *modName--) { -/* printf("Terminating '%s'\n", *modName);*/ - CallModuleDllMain(*modName, DLL_PROCESS_DETACH); - } + // Must go backwards + char **modName; + for (modName = possibleModules+(sizeof(possibleModules) / sizeof(char *))-2; + modName >= possibleModules; + *modName--) { +/* printf("Terminating '%s'\n", *modName);*/ + CallModuleDllMain(*modName, DLL_PROCESS_DETACH); + } } BOOL WINAPI DllMain(HINSTANCE hInstance, DWORD dwReason, LPVOID lpReserved) { - BOOL ret = TRUE; - switch (dwReason) { - case DLL_PROCESS_ATTACH: - { - char **modName; - for (modName = possibleModules;*modName;*modName++) { - BOOL ok = CallModuleDllMain(*modName, dwReason); - if (!ok) - ret = FALSE; - } - break; - } - case DLL_PROCESS_DETACH: - { - // Must go backwards - char **modName; - for (modName = possibleModules+(sizeof(possibleModules) / sizeof(char *))-2; - modName >= possibleModules; - *modName--) - CallModuleDllMain(*modName, DLL_PROCESS_DETACH); - break; - } - } - return ret; + BOOL ret = TRUE; + switch (dwReason) { + case DLL_PROCESS_ATTACH: + { + char **modName; + for (modName = possibleModules;*modName;*modName++) { + BOOL ok = CallModuleDllMain(*modName, dwReason); + if (!ok) + ret = FALSE; + } + break; + } + case DLL_PROCESS_DETACH: + { + // Must go backwards + char **modName; + for (modName = possibleModules+(sizeof(possibleModules) / sizeof(char *))-2; + modName >= possibleModules; + *modName--) + CallModuleDllMain(*modName, DLL_PROCESS_DETACH); + break; + } + } + return ret; } BOOL CallModuleDllMain(char *modName, DWORD dwReason) { - BOOL (WINAPI * pfndllmain)(HINSTANCE, DWORD, LPVOID); + BOOL (WINAPI * pfndllmain)(HINSTANCE, DWORD, LPVOID); - char funcName[255]; - HMODULE hmod = GetModuleHandle(NULL); - strcpy(funcName, "_DllMain"); - strcat(funcName, modName); - strcat(funcName, "@12"); // stdcall convention. - pfndllmain = (BOOL (WINAPI *)(HINSTANCE, DWORD, LPVOID))GetProcAddress(hmod, funcName); - if (pfndllmain==NULL) { - /* No function by that name exported - then that module does - not appear in our frozen program - return OK - */ - return TRUE; - } - return (*pfndllmain)(hmod, dwReason, NULL); + char funcName[255]; + HMODULE hmod = GetModuleHandle(NULL); + strcpy(funcName, "_DllMain"); + strcat(funcName, modName); + strcat(funcName, "@12"); // stdcall convention. + pfndllmain = (BOOL (WINAPI *)(HINSTANCE, DWORD, LPVOID))GetProcAddress(hmod, funcName); + if (pfndllmain==NULL) { + /* No function by that name exported - then that module does + not appear in our frozen program - return OK + */ + return TRUE; + } + return (*pfndllmain)(hmod, dwReason, NULL); } Modified: python/branches/release31-maint/PC/generrmap.c ============================================================================== --- python/branches/release31-maint/PC/generrmap.c (original) +++ python/branches/release31-maint/PC/generrmap.c Sun May 9 18:14:21 2010 @@ -5,16 +5,16 @@ int main() { - int i; - printf("/* Generated file. Do not edit. */\n"); - printf("int winerror_to_errno(int winerror)\n"); - printf("{\n\tswitch(winerror) {\n"); - for(i=1; i < 65000; i++) { - _dosmaperr(i); - if (errno == EINVAL) - continue; - printf("\t\tcase %d: return %d;\n", i, errno); - } - printf("\t\tdefault: return EINVAL;\n"); - printf("\t}\n}\n"); + int i; + printf("/* Generated file. Do not edit. */\n"); + printf("int winerror_to_errno(int winerror)\n"); + printf("{\n\tswitch(winerror) {\n"); + for(i=1; i < 65000; i++) { + _dosmaperr(i); + if (errno == EINVAL) + continue; + printf("\t\tcase %d: return %d;\n", i, errno); + } + printf("\t\tdefault: return EINVAL;\n"); + printf("\t}\n}\n"); } Modified: python/branches/release31-maint/PC/getpathp.c ============================================================================== --- python/branches/release31-maint/PC/getpathp.c (original) +++ python/branches/release31-maint/PC/getpathp.c Sun May 9 18:14:21 2010 @@ -4,8 +4,8 @@ /* ---------------------------------------------------------------- PATH RULES FOR WINDOWS: - This describes how sys.path is formed on Windows. It describes the - functionality, not the implementation (ie, the order in which these + This describes how sys.path is formed on Windows. It describes the + functionality, not the implementation (ie, the order in which these are actually fetched is different) * Python always adds an empty entry at the start, which corresponds @@ -24,15 +24,15 @@ * We attempt to locate the "Python Home" - if the PYTHONHOME env var is set, we believe it. Otherwise, we use the path of our host .EXE's to try and locate our "landmark" (lib\\os.py) and deduce our home. - - If we DO have a Python Home: The relevant sub-directories (Lib, + - If we DO have a Python Home: The relevant sub-directories (Lib, plat-win, etc) are based on the Python Home - If we DO NOT have a Python Home, the core Python Path is - loaded from the registry. This is the main PythonPath key, + loaded from the registry. This is the main PythonPath key, and both HKLM and HKCU are combined to form the path) * Iff - we can not locate the Python Home, have not had a PYTHONPATH specified, and can't locate any Registry entries (ie, we have _nothing_ - we can assume is a good path), a default path with relative entries is + we can assume is a good path), a default path with relative entries is used (eg. .\Lib;.\plat-win, etc) @@ -42,9 +42,9 @@ the core path is deduced, and the core paths in the registry are ignored. Other "application paths" in the registry are always read. - * When Python is hosted in another exe (different directory, embedded via + * When Python is hosted in another exe (different directory, embedded via COM, etc), the Python Home will not be deduced, so the core path from - the registry is used. Other "application paths" in the registry are + the registry is used. Other "application paths" in the registry are always read. * If Python can't find its home and there is no registry (eg, frozen @@ -92,12 +92,12 @@ static int -is_sep(wchar_t ch) /* determine if "ch" is a separator character */ +is_sep(wchar_t ch) /* determine if "ch" is a separator character */ { #ifdef ALTSEP - return ch == SEP || ch == ALTSEP; + return ch == SEP || ch == ALTSEP; #else - return ch == SEP; + return ch == SEP; #endif } @@ -107,35 +107,35 @@ static void reduce(wchar_t *dir) { - size_t i = wcslen(dir); - while (i > 0 && !is_sep(dir[i])) - --i; - dir[i] = '\0'; + size_t i = wcslen(dir); + while (i > 0 && !is_sep(dir[i])) + --i; + dir[i] = '\0'; } - + static int exists(wchar_t *filename) { - return GetFileAttributesW(filename) != 0xFFFFFFFF; + return GetFileAttributesW(filename) != 0xFFFFFFFF; } -/* Assumes 'filename' MAXPATHLEN+1 bytes long - +/* Assumes 'filename' MAXPATHLEN+1 bytes long - may extend 'filename' by one character. */ static int -ismodule(wchar_t *filename) /* Is module -- check for .pyc/.pyo too */ +ismodule(wchar_t *filename) /* Is module -- check for .pyc/.pyo too */ { - if (exists(filename)) - return 1; + if (exists(filename)) + return 1; - /* Check for the compiled version of prefix. */ - if (wcslen(filename) < MAXPATHLEN) { - wcscat(filename, Py_OptimizeFlag ? L"o" : L"c"); - if (exists(filename)) - return 1; - } - return 0; + /* Check for the compiled version of prefix. */ + if (wcslen(filename) < MAXPATHLEN) { + wcscat(filename, Py_OptimizeFlag ? L"o" : L"c"); + if (exists(filename)) + return 1; + } + return 0; } /* Add a path component, by appending stuff to buffer. @@ -150,21 +150,21 @@ static void join(wchar_t *buffer, wchar_t *stuff) { - size_t n, k; - if (is_sep(stuff[0])) - n = 0; - else { - n = wcslen(buffer); - if (n > 0 && !is_sep(buffer[n-1]) && n < MAXPATHLEN) - buffer[n++] = SEP; - } - if (n > MAXPATHLEN) - Py_FatalError("buffer overflow in getpathp.c's joinpath()"); - k = wcslen(stuff); - if (n + k > MAXPATHLEN) - k = MAXPATHLEN - n; - wcsncpy(buffer+n, stuff, k); - buffer[n+k] = '\0'; + size_t n, k; + if (is_sep(stuff[0])) + n = 0; + else { + n = wcslen(buffer); + if (n > 0 && !is_sep(buffer[n-1]) && n < MAXPATHLEN) + buffer[n++] = SEP; + } + if (n > MAXPATHLEN) + Py_FatalError("buffer overflow in getpathp.c's joinpath()"); + k = wcslen(stuff); + if (n + k > MAXPATHLEN) + k = MAXPATHLEN - n; + wcsncpy(buffer+n, stuff, k); + buffer[n+k] = '\0'; } /* gotlandmark only called by search_for_prefix, which ensures @@ -174,29 +174,29 @@ static int gotlandmark(wchar_t *landmark) { - int ok; - Py_ssize_t n; + int ok; + Py_ssize_t n; - n = wcslen(prefix); - join(prefix, landmark); - ok = ismodule(prefix); - prefix[n] = '\0'; - return ok; + n = wcslen(prefix); + join(prefix, landmark); + ok = ismodule(prefix); + prefix[n] = '\0'; + return ok; } -/* assumes argv0_path is MAXPATHLEN+1 bytes long, already \0 term'd. +/* assumes argv0_path is MAXPATHLEN+1 bytes long, already \0 term'd. assumption provided by only caller, calculate_path() */ static int search_for_prefix(wchar_t *argv0_path, wchar_t *landmark) { - /* Search from argv0_path, until landmark is found */ - wcscpy(prefix, argv0_path); - do { - if (gotlandmark(landmark)) - return 1; - reduce(prefix); - } while (prefix[0]); - return 0; + /* Search from argv0_path, until landmark is found */ + wcscpy(prefix, argv0_path); + do { + if (gotlandmark(landmark)) + return 1; + reduce(prefix); + } while (prefix[0]); + return 0; } #ifdef MS_WINDOWS @@ -222,133 +222,133 @@ static wchar_t * getpythonregpath(HKEY keyBase, int skipcore) { - HKEY newKey = 0; - DWORD dataSize = 0; - DWORD numKeys = 0; - LONG rc; - wchar_t *retval = NULL; - WCHAR *dataBuf = NULL; - static const WCHAR keyPrefix[] = L"Software\\Python\\PythonCore\\"; - static const WCHAR keySuffix[] = L"\\PythonPath"; - size_t versionLen; - DWORD index; - WCHAR *keyBuf = NULL; - WCHAR *keyBufPtr; - WCHAR **ppPaths = NULL; - - /* Tried to use sysget("winver") but here is too early :-( */ - versionLen = strlen(PyWin_DLLVersionString); - /* Space for all the chars, plus one \0 */ - keyBuf = keyBufPtr = malloc(sizeof(keyPrefix) + - sizeof(WCHAR)*(versionLen-1) + - sizeof(keySuffix)); - if (keyBuf==NULL) goto done; - - memcpy(keyBufPtr, keyPrefix, sizeof(keyPrefix)-sizeof(WCHAR)); - keyBufPtr += sizeof(keyPrefix)/sizeof(WCHAR) - 1; - mbstowcs(keyBufPtr, PyWin_DLLVersionString, versionLen); - keyBufPtr += versionLen; - /* NULL comes with this one! */ - memcpy(keyBufPtr, keySuffix, sizeof(keySuffix)); - /* Open the root Python key */ - rc=RegOpenKeyExW(keyBase, - keyBuf, /* subkey */ - 0, /* reserved */ - KEY_READ, - &newKey); - if (rc!=ERROR_SUCCESS) goto done; - /* Find out how big our core buffer is, and how many subkeys we have */ - rc = RegQueryInfoKey(newKey, NULL, NULL, NULL, &numKeys, NULL, NULL, - NULL, NULL, &dataSize, NULL, NULL); - if (rc!=ERROR_SUCCESS) goto done; - if (skipcore) dataSize = 0; /* Only count core ones if we want them! */ - /* Allocate a temp array of char buffers, so we only need to loop - reading the registry once - */ - ppPaths = malloc( sizeof(WCHAR *) * numKeys ); - if (ppPaths==NULL) goto done; - memset(ppPaths, 0, sizeof(WCHAR *) * numKeys); - /* Loop over all subkeys, allocating a temp sub-buffer. */ - for(index=0;index 0) { - *(szCur++) = L';'; - dataSize--; - } - if (ppPaths[index]) { - Py_ssize_t len = wcslen(ppPaths[index]); - wcsncpy(szCur, ppPaths[index], len); - szCur += len; - assert(dataSize > (DWORD)len); - dataSize -= (DWORD)len; - } - } - if (skipcore) - *szCur = '\0'; - else { - /* If we have no values, we dont need a ';' */ - if (numKeys) { - *(szCur++) = L';'; - dataSize--; - } - /* Now append the core path entries - - this will include the NULL - */ - rc = RegQueryValueExW(newKey, NULL, 0, NULL, - (LPBYTE)szCur, &dataSize); - } - /* And set the result - caller must free */ - retval = dataBuf; - } + HKEY newKey = 0; + DWORD dataSize = 0; + DWORD numKeys = 0; + LONG rc; + wchar_t *retval = NULL; + WCHAR *dataBuf = NULL; + static const WCHAR keyPrefix[] = L"Software\\Python\\PythonCore\\"; + static const WCHAR keySuffix[] = L"\\PythonPath"; + size_t versionLen; + DWORD index; + WCHAR *keyBuf = NULL; + WCHAR *keyBufPtr; + WCHAR **ppPaths = NULL; + + /* Tried to use sysget("winver") but here is too early :-( */ + versionLen = strlen(PyWin_DLLVersionString); + /* Space for all the chars, plus one \0 */ + keyBuf = keyBufPtr = malloc(sizeof(keyPrefix) + + sizeof(WCHAR)*(versionLen-1) + + sizeof(keySuffix)); + if (keyBuf==NULL) goto done; + + memcpy(keyBufPtr, keyPrefix, sizeof(keyPrefix)-sizeof(WCHAR)); + keyBufPtr += sizeof(keyPrefix)/sizeof(WCHAR) - 1; + mbstowcs(keyBufPtr, PyWin_DLLVersionString, versionLen); + keyBufPtr += versionLen; + /* NULL comes with this one! */ + memcpy(keyBufPtr, keySuffix, sizeof(keySuffix)); + /* Open the root Python key */ + rc=RegOpenKeyExW(keyBase, + keyBuf, /* subkey */ + 0, /* reserved */ + KEY_READ, + &newKey); + if (rc!=ERROR_SUCCESS) goto done; + /* Find out how big our core buffer is, and how many subkeys we have */ + rc = RegQueryInfoKey(newKey, NULL, NULL, NULL, &numKeys, NULL, NULL, + NULL, NULL, &dataSize, NULL, NULL); + if (rc!=ERROR_SUCCESS) goto done; + if (skipcore) dataSize = 0; /* Only count core ones if we want them! */ + /* Allocate a temp array of char buffers, so we only need to loop + reading the registry once + */ + ppPaths = malloc( sizeof(WCHAR *) * numKeys ); + if (ppPaths==NULL) goto done; + memset(ppPaths, 0, sizeof(WCHAR *) * numKeys); + /* Loop over all subkeys, allocating a temp sub-buffer. */ + for(index=0;index 0) { + *(szCur++) = L';'; + dataSize--; + } + if (ppPaths[index]) { + Py_ssize_t len = wcslen(ppPaths[index]); + wcsncpy(szCur, ppPaths[index], len); + szCur += len; + assert(dataSize > (DWORD)len); + dataSize -= (DWORD)len; + } + } + if (skipcore) + *szCur = '\0'; + else { + /* If we have no values, we dont need a ';' */ + if (numKeys) { + *(szCur++) = L';'; + dataSize--; + } + /* Now append the core path entries - + this will include the NULL + */ + rc = RegQueryValueExW(newKey, NULL, 0, NULL, + (LPBYTE)szCur, &dataSize); + } + /* And set the result - caller must free */ + retval = dataBuf; + } done: - /* Loop freeing my temp buffers */ - if (ppPaths) { - for(index=0;index= MAXPATHLEN) - envpath = NULL; - } + char *_envpath = Py_GETENV("PYTHONPATH"); + wchar_t wenvpath[MAXPATHLEN+1]; + if (_envpath) { + size_t r = mbstowcs(wenvpath, _envpath, MAXPATHLEN+1); + envpath = wenvpath; + if (r == (size_t)-1 || r >= MAXPATHLEN) + envpath = NULL; + } #endif - get_progpath(); - /* progpath guaranteed \0 terminated in MAXPATH+1 bytes. */ - wcscpy(argv0_path, progpath); - reduce(argv0_path); - if (pythonhome == NULL || *pythonhome == '\0') { - if (search_for_prefix(argv0_path, LANDMARK)) - pythonhome = prefix; - else - pythonhome = NULL; - } - else - wcsncpy(prefix, pythonhome, MAXPATHLEN); + get_progpath(); + /* progpath guaranteed \0 terminated in MAXPATH+1 bytes. */ + wcscpy(argv0_path, progpath); + reduce(argv0_path); + if (pythonhome == NULL || *pythonhome == '\0') { + if (search_for_prefix(argv0_path, LANDMARK)) + pythonhome = prefix; + else + pythonhome = NULL; + } + else + wcsncpy(prefix, pythonhome, MAXPATHLEN); - if (envpath && *envpath == '\0') - envpath = NULL; + if (envpath && *envpath == '\0') + envpath = NULL; #ifdef MS_WINDOWS - /* Calculate zip archive path */ - if (dllpath[0]) /* use name of python DLL */ - wcsncpy(zip_path, dllpath, MAXPATHLEN); - else /* use name of executable program */ - wcsncpy(zip_path, progpath, MAXPATHLEN); - zip_path[MAXPATHLEN] = '\0'; - len = wcslen(zip_path); - if (len > 4) { - zip_path[len-3] = 'z'; /* change ending to "zip" */ - zip_path[len-2] = 'i'; - zip_path[len-1] = 'p'; - } - else { - zip_path[0] = 0; - } - - skiphome = pythonhome==NULL ? 0 : 1; + /* Calculate zip archive path */ + if (dllpath[0]) /* use name of python DLL */ + wcsncpy(zip_path, dllpath, MAXPATHLEN); + else /* use name of executable program */ + wcsncpy(zip_path, progpath, MAXPATHLEN); + zip_path[MAXPATHLEN] = '\0'; + len = wcslen(zip_path); + if (len > 4) { + zip_path[len-3] = 'z'; /* change ending to "zip" */ + zip_path[len-2] = 'i'; + zip_path[len-1] = 'p'; + } + else { + zip_path[0] = 0; + } + + skiphome = pythonhome==NULL ? 0 : 1; #ifdef Py_ENABLE_SHARED - machinepath = getpythonregpath(HKEY_LOCAL_MACHINE, skiphome); - userpath = getpythonregpath(HKEY_CURRENT_USER, skiphome); + machinepath = getpythonregpath(HKEY_LOCAL_MACHINE, skiphome); + userpath = getpythonregpath(HKEY_CURRENT_USER, skiphome); #endif - /* We only use the default relative PYTHONPATH if we havent - anything better to use! */ - skipdefault = envpath!=NULL || pythonhome!=NULL || \ - machinepath!=NULL || userpath!=NULL; + /* We only use the default relative PYTHONPATH if we havent + anything better to use! */ + skipdefault = envpath!=NULL || pythonhome!=NULL || \ + machinepath!=NULL || userpath!=NULL; #endif - /* We need to construct a path from the following parts. - (1) the PYTHONPATH environment variable, if set; - (2) for Win32, the zip archive file path; - (3) for Win32, the machinepath and userpath, if set; - (4) the PYTHONPATH config macro, with the leading "." - of each component replaced with pythonhome, if set; - (5) the directory containing the executable (argv0_path). - The length calculation calculates #4 first. - Extra rules: - - If PYTHONHOME is set (in any way) item (3) is ignored. - - If registry values are used, (4) and (5) are ignored. - */ - - /* Calculate size of return buffer */ - if (pythonhome != NULL) { - wchar_t *p; - bufsz = 1; - for (p = PYTHONPATH; *p; p++) { - if (*p == DELIM) - bufsz++; /* number of DELIM plus one */ - } - bufsz *= wcslen(pythonhome); - } - else - bufsz = 0; - bufsz += wcslen(PYTHONPATH) + 1; - bufsz += wcslen(argv0_path) + 1; + /* We need to construct a path from the following parts. + (1) the PYTHONPATH environment variable, if set; + (2) for Win32, the zip archive file path; + (3) for Win32, the machinepath and userpath, if set; + (4) the PYTHONPATH config macro, with the leading "." + of each component replaced with pythonhome, if set; + (5) the directory containing the executable (argv0_path). + The length calculation calculates #4 first. + Extra rules: + - If PYTHONHOME is set (in any way) item (3) is ignored. + - If registry values are used, (4) and (5) are ignored. + */ + + /* Calculate size of return buffer */ + if (pythonhome != NULL) { + wchar_t *p; + bufsz = 1; + for (p = PYTHONPATH; *p; p++) { + if (*p == DELIM) + bufsz++; /* number of DELIM plus one */ + } + bufsz *= wcslen(pythonhome); + } + else + bufsz = 0; + bufsz += wcslen(PYTHONPATH) + 1; + bufsz += wcslen(argv0_path) + 1; #ifdef MS_WINDOWS - if (userpath) - bufsz += wcslen(userpath) + 1; - if (machinepath) - bufsz += wcslen(machinepath) + 1; - bufsz += wcslen(zip_path) + 1; + if (userpath) + bufsz += wcslen(userpath) + 1; + if (machinepath) + bufsz += wcslen(machinepath) + 1; + bufsz += wcslen(zip_path) + 1; #endif - if (envpath != NULL) - bufsz += wcslen(envpath) + 1; + if (envpath != NULL) + bufsz += wcslen(envpath) + 1; - module_search_path = buf = malloc(bufsz*sizeof(wchar_t)); - if (buf == NULL) { - /* We can't exit, so print a warning and limp along */ - fprintf(stderr, "Can't malloc dynamic PYTHONPATH.\n"); - if (envpath) { - fprintf(stderr, "Using environment $PYTHONPATH.\n"); - module_search_path = envpath; - } - else { - fprintf(stderr, "Using default static path.\n"); - module_search_path = PYTHONPATH; - } + module_search_path = buf = malloc(bufsz*sizeof(wchar_t)); + if (buf == NULL) { + /* We can't exit, so print a warning and limp along */ + fprintf(stderr, "Can't malloc dynamic PYTHONPATH.\n"); + if (envpath) { + fprintf(stderr, "Using environment $PYTHONPATH.\n"); + module_search_path = envpath; + } + else { + fprintf(stderr, "Using default static path.\n"); + module_search_path = PYTHONPATH; + } #ifdef MS_WINDOWS - if (machinepath) - free(machinepath); - if (userpath) - free(userpath); + if (machinepath) + free(machinepath); + if (userpath) + free(userpath); #endif /* MS_WINDOWS */ - return; - } + return; + } - if (envpath) { - wcscpy(buf, envpath); - buf = wcschr(buf, L'\0'); - *buf++ = DELIM; - } + if (envpath) { + wcscpy(buf, envpath); + buf = wcschr(buf, L'\0'); + *buf++ = DELIM; + } #ifdef MS_WINDOWS - if (zip_path[0]) { - wcscpy(buf, zip_path); - buf = wcschr(buf, L'\0'); - *buf++ = DELIM; - } - if (userpath) { - wcscpy(buf, userpath); - buf = wcschr(buf, L'\0'); - *buf++ = DELIM; - free(userpath); - } - if (machinepath) { - wcscpy(buf, machinepath); - buf = wcschr(buf, L'\0'); - *buf++ = DELIM; - free(machinepath); - } - if (pythonhome == NULL) { - if (!skipdefault) { - wcscpy(buf, PYTHONPATH); - buf = wcschr(buf, L'\0'); - } - } + if (zip_path[0]) { + wcscpy(buf, zip_path); + buf = wcschr(buf, L'\0'); + *buf++ = DELIM; + } + if (userpath) { + wcscpy(buf, userpath); + buf = wcschr(buf, L'\0'); + *buf++ = DELIM; + free(userpath); + } + if (machinepath) { + wcscpy(buf, machinepath); + buf = wcschr(buf, L'\0'); + *buf++ = DELIM; + free(machinepath); + } + if (pythonhome == NULL) { + if (!skipdefault) { + wcscpy(buf, PYTHONPATH); + buf = wcschr(buf, L'\0'); + } + } #else - if (pythonhome == NULL) { - wcscpy(buf, PYTHONPATH); - buf = wcschr(buf, L'\0'); - } + if (pythonhome == NULL) { + wcscpy(buf, PYTHONPATH); + buf = wcschr(buf, L'\0'); + } #endif /* MS_WINDOWS */ - else { - wchar_t *p = PYTHONPATH; - wchar_t *q; - size_t n; - for (;;) { - q = wcschr(p, DELIM); - if (q == NULL) - n = wcslen(p); - else - n = q-p; - if (p[0] == '.' && is_sep(p[1])) { - wcscpy(buf, pythonhome); - buf = wcschr(buf, L'\0'); - p++; - n--; - } - wcsncpy(buf, p, n); - buf += n; - if (q == NULL) - break; - *buf++ = DELIM; - p = q+1; - } - } - if (argv0_path) { - *buf++ = DELIM; - wcscpy(buf, argv0_path); - buf = wcschr(buf, L'\0'); - } - *buf = L'\0'; - /* Now to pull one last hack/trick. If sys.prefix is - empty, then try and find it somewhere on the paths - we calculated. We scan backwards, as our general policy - is that Python core directories are at the *end* of - sys.path. We assume that our "lib" directory is - on the path, and that our 'prefix' directory is - the parent of that. - */ - if (*prefix==L'\0') { - wchar_t lookBuf[MAXPATHLEN+1]; - wchar_t *look = buf - 1; /* 'buf' is at the end of the buffer */ - while (1) { - Py_ssize_t nchars; - wchar_t *lookEnd = look; - /* 'look' will end up one character before the - start of the path in question - even if this - is one character before the start of the buffer - */ - while (look >= module_search_path && *look != DELIM) - look--; - nchars = lookEnd-look; - wcsncpy(lookBuf, look+1, nchars); - lookBuf[nchars] = L'\0'; - /* Up one level to the parent */ - reduce(lookBuf); - if (search_for_prefix(lookBuf, LANDMARK)) { - break; - } - /* If we are out of paths to search - give up */ - if (look < module_search_path) - break; - look--; - } - } + else { + wchar_t *p = PYTHONPATH; + wchar_t *q; + size_t n; + for (;;) { + q = wcschr(p, DELIM); + if (q == NULL) + n = wcslen(p); + else + n = q-p; + if (p[0] == '.' && is_sep(p[1])) { + wcscpy(buf, pythonhome); + buf = wcschr(buf, L'\0'); + p++; + n--; + } + wcsncpy(buf, p, n); + buf += n; + if (q == NULL) + break; + *buf++ = DELIM; + p = q+1; + } + } + if (argv0_path) { + *buf++ = DELIM; + wcscpy(buf, argv0_path); + buf = wcschr(buf, L'\0'); + } + *buf = L'\0'; + /* Now to pull one last hack/trick. If sys.prefix is + empty, then try and find it somewhere on the paths + we calculated. We scan backwards, as our general policy + is that Python core directories are at the *end* of + sys.path. We assume that our "lib" directory is + on the path, and that our 'prefix' directory is + the parent of that. + */ + if (*prefix==L'\0') { + wchar_t lookBuf[MAXPATHLEN+1]; + wchar_t *look = buf - 1; /* 'buf' is at the end of the buffer */ + while (1) { + Py_ssize_t nchars; + wchar_t *lookEnd = look; + /* 'look' will end up one character before the + start of the path in question - even if this + is one character before the start of the buffer + */ + while (look >= module_search_path && *look != DELIM) + look--; + nchars = lookEnd-look; + wcsncpy(lookBuf, look+1, nchars); + lookBuf[nchars] = L'\0'; + /* Up one level to the parent */ + reduce(lookBuf); + if (search_for_prefix(lookBuf, LANDMARK)) { + break; + } + /* If we are out of paths to search - give up */ + if (look < module_search_path) + break; + look--; + } + } } @@ -657,29 +657,29 @@ wchar_t * Py_GetPath(void) { - if (!module_search_path) - calculate_path(); - return module_search_path; + if (!module_search_path) + calculate_path(); + return module_search_path; } wchar_t * Py_GetPrefix(void) { - if (!module_search_path) - calculate_path(); - return prefix; + if (!module_search_path) + calculate_path(); + return prefix; } wchar_t * Py_GetExecPrefix(void) { - return Py_GetPrefix(); + return Py_GetPrefix(); } wchar_t * Py_GetProgramFullPath(void) { - if (!module_search_path) - calculate_path(); - return progpath; + if (!module_search_path) + calculate_path(); + return progpath; } Modified: python/branches/release31-maint/PC/import_nt.c ============================================================================== --- python/branches/release31-maint/PC/import_nt.c (original) +++ python/branches/release31-maint/PC/import_nt.c Sun May 9 18:14:21 2010 @@ -1,6 +1,6 @@ /******************************************************************** - import_nt.c + import_nt.c Win32 specific import code. @@ -16,71 +16,71 @@ extern const char *PyWin_DLLVersionString; FILE *PyWin_FindRegisteredModule(const char *moduleName, - struct filedescr **ppFileDesc, - char *pathBuf, - Py_ssize_t pathLen) + struct filedescr **ppFileDesc, + char *pathBuf, + Py_ssize_t pathLen) { - char *moduleKey; - const char keyPrefix[] = "Software\\Python\\PythonCore\\"; - const char keySuffix[] = "\\Modules\\"; + char *moduleKey; + const char keyPrefix[] = "Software\\Python\\PythonCore\\"; + const char keySuffix[] = "\\Modules\\"; #ifdef _DEBUG - /* In debugging builds, we _must_ have the debug version - * registered. - */ - const char debugString[] = "\\Debug"; + /* In debugging builds, we _must_ have the debug version + * registered. + */ + const char debugString[] = "\\Debug"; #else - const char debugString[] = ""; + const char debugString[] = ""; #endif - struct filedescr *fdp = NULL; - FILE *fp; - HKEY keyBase = HKEY_CURRENT_USER; - int modNameSize; - long regStat; - - /* Calculate the size for the sprintf buffer. - * Get the size of the chars only, plus 1 NULL. - */ - size_t bufSize = sizeof(keyPrefix)-1 + - strlen(PyWin_DLLVersionString) + - sizeof(keySuffix) + - strlen(moduleName) + - sizeof(debugString) - 1; - /* alloca == no free required, but memory only local to fn, - * also no heap fragmentation! - */ - moduleKey = alloca(bufSize); - PyOS_snprintf(moduleKey, bufSize, - "Software\\Python\\PythonCore\\%s\\Modules\\%s%s", - PyWin_DLLVersionString, moduleName, debugString); - - assert(pathLen < INT_MAX); - modNameSize = (int)pathLen; - regStat = RegQueryValue(keyBase, moduleKey, pathBuf, &modNameSize); - if (regStat != ERROR_SUCCESS) { - /* No user setting - lookup in machine settings */ - keyBase = HKEY_LOCAL_MACHINE; - /* be anal - failure may have reset size param */ - modNameSize = (int)pathLen; - regStat = RegQueryValue(keyBase, moduleKey, - pathBuf, &modNameSize); - - if (regStat != ERROR_SUCCESS) - return NULL; - } - /* use the file extension to locate the type entry. */ - for (fdp = _PyImport_Filetab; fdp->suffix != NULL; fdp++) { - size_t extLen = strlen(fdp->suffix); - assert(modNameSize >= 0); /* else cast to size_t is wrong */ - if ((size_t)modNameSize > extLen && - strnicmp(pathBuf + ((size_t)modNameSize-extLen-1), - fdp->suffix, - extLen) == 0) - break; - } - if (fdp->suffix == NULL) - return NULL; - fp = fopen(pathBuf, fdp->mode); - if (fp != NULL) - *ppFileDesc = fdp; - return fp; + struct filedescr *fdp = NULL; + FILE *fp; + HKEY keyBase = HKEY_CURRENT_USER; + int modNameSize; + long regStat; + + /* Calculate the size for the sprintf buffer. + * Get the size of the chars only, plus 1 NULL. + */ + size_t bufSize = sizeof(keyPrefix)-1 + + strlen(PyWin_DLLVersionString) + + sizeof(keySuffix) + + strlen(moduleName) + + sizeof(debugString) - 1; + /* alloca == no free required, but memory only local to fn, + * also no heap fragmentation! + */ + moduleKey = alloca(bufSize); + PyOS_snprintf(moduleKey, bufSize, + "Software\\Python\\PythonCore\\%s\\Modules\\%s%s", + PyWin_DLLVersionString, moduleName, debugString); + + assert(pathLen < INT_MAX); + modNameSize = (int)pathLen; + regStat = RegQueryValue(keyBase, moduleKey, pathBuf, &modNameSize); + if (regStat != ERROR_SUCCESS) { + /* No user setting - lookup in machine settings */ + keyBase = HKEY_LOCAL_MACHINE; + /* be anal - failure may have reset size param */ + modNameSize = (int)pathLen; + regStat = RegQueryValue(keyBase, moduleKey, + pathBuf, &modNameSize); + + if (regStat != ERROR_SUCCESS) + return NULL; + } + /* use the file extension to locate the type entry. */ + for (fdp = _PyImport_Filetab; fdp->suffix != NULL; fdp++) { + size_t extLen = strlen(fdp->suffix); + assert(modNameSize >= 0); /* else cast to size_t is wrong */ + if ((size_t)modNameSize > extLen && + strnicmp(pathBuf + ((size_t)modNameSize-extLen-1), + fdp->suffix, + extLen) == 0) + break; + } + if (fdp->suffix == NULL) + return NULL; + fp = fopen(pathBuf, fdp->mode); + if (fp != NULL) + *ppFileDesc = fdp; + return fp; } Modified: python/branches/release31-maint/PC/make_versioninfo.c ============================================================================== --- python/branches/release31-maint/PC/make_versioninfo.c (original) +++ python/branches/release31-maint/PC/make_versioninfo.c Sun May 9 18:14:21 2010 @@ -22,17 +22,17 @@ */ int main(int argc, char **argv) { - printf("/* This file created by make_versioninfo.exe */\n"); - printf("#define FIELD3 %d\n", - PY_MICRO_VERSION*1000 + PY_RELEASE_LEVEL*10 + PY_RELEASE_SERIAL); - printf("#define MS_DLL_ID \"%d.%d\"\n", - PY_MAJOR_VERSION, PY_MINOR_VERSION); - printf("#ifndef _DEBUG\n"); - printf("#define PYTHON_DLL_NAME \"python%d%d.dll\"\n", - PY_MAJOR_VERSION, PY_MINOR_VERSION); - printf("#else\n"); - printf("#define PYTHON_DLL_NAME \"python%d%d_d.dll\"\n", - PY_MAJOR_VERSION, PY_MINOR_VERSION); - printf("#endif\n"); - return 0; + printf("/* This file created by make_versioninfo.exe */\n"); + printf("#define FIELD3 %d\n", + PY_MICRO_VERSION*1000 + PY_RELEASE_LEVEL*10 + PY_RELEASE_SERIAL); + printf("#define MS_DLL_ID \"%d.%d\"\n", + PY_MAJOR_VERSION, PY_MINOR_VERSION); + printf("#ifndef _DEBUG\n"); + printf("#define PYTHON_DLL_NAME \"python%d%d.dll\"\n", + PY_MAJOR_VERSION, PY_MINOR_VERSION); + printf("#else\n"); + printf("#define PYTHON_DLL_NAME \"python%d%d_d.dll\"\n", + PY_MAJOR_VERSION, PY_MINOR_VERSION); + printf("#endif\n"); + return 0; } Modified: python/branches/release31-maint/PC/msvcrtmodule.c ============================================================================== --- python/branches/release31-maint/PC/msvcrtmodule.c (original) +++ python/branches/release31-maint/PC/msvcrtmodule.c Sun May 9 18:14:21 2010 @@ -1,18 +1,18 @@ /********************************************************* - msvcrtmodule.c + msvcrtmodule.c - A Python interface to the Microsoft Visual C Runtime - Library, providing access to those non-portable, but - still useful routines. + A Python interface to the Microsoft Visual C Runtime + Library, providing access to those non-portable, but + still useful routines. - Only ever compiled with an MS compiler, so no attempt - has been made to avoid MS language extensions, etc... + Only ever compiled with an MS compiler, so no attempt + has been made to avoid MS language extensions, etc... - This may only work on NT or 95... + This may only work on NT or 95... - Author: Mark Hammond and Guido van Rossum. - Maintenance: Guido van Rossum. + Author: Mark Hammond and Guido van Rossum. + Maintenance: Guido van Rossum. ***********************************************************/ @@ -35,14 +35,14 @@ static PyObject * msvcrt_heapmin(PyObject *self, PyObject *args) { - if (!PyArg_ParseTuple(args, ":heapmin")) - return NULL; + if (!PyArg_ParseTuple(args, ":heapmin")) + return NULL; - if (_heapmin() != 0) - return PyErr_SetFromErrno(PyExc_IOError); + if (_heapmin() != 0) + return PyErr_SetFromErrno(PyExc_IOError); - Py_INCREF(Py_None); - return Py_None; + Py_INCREF(Py_None); + return Py_None; } PyDoc_STRVAR(heapmin_doc, @@ -55,22 +55,22 @@ static PyObject * msvcrt_locking(PyObject *self, PyObject *args) { - int fd; - int mode; - long nbytes; - int err; - - if (!PyArg_ParseTuple(args, "iil:locking", &fd, &mode, &nbytes)) - return NULL; - - Py_BEGIN_ALLOW_THREADS - err = _locking(fd, mode, nbytes); - Py_END_ALLOW_THREADS - if (err != 0) - return PyErr_SetFromErrno(PyExc_IOError); + int fd; + int mode; + long nbytes; + int err; + + if (!PyArg_ParseTuple(args, "iil:locking", &fd, &mode, &nbytes)) + return NULL; + + Py_BEGIN_ALLOW_THREADS + err = _locking(fd, mode, nbytes); + Py_END_ALLOW_THREADS + if (err != 0) + return PyErr_SetFromErrno(PyExc_IOError); - Py_INCREF(Py_None); - return Py_None; + Py_INCREF(Py_None); + return Py_None; } PyDoc_STRVAR(locking_doc, @@ -88,16 +88,16 @@ static PyObject * msvcrt_setmode(PyObject *self, PyObject *args) { - int fd; - int flags; - if (!PyArg_ParseTuple(args,"ii:setmode", &fd, &flags)) - return NULL; - - flags = _setmode(fd, flags); - if (flags == -1) - return PyErr_SetFromErrno(PyExc_IOError); + int fd; + int flags; + if (!PyArg_ParseTuple(args,"ii:setmode", &fd, &flags)) + return NULL; + + flags = _setmode(fd, flags); + if (flags == -1) + return PyErr_SetFromErrno(PyExc_IOError); - return PyLong_FromLong(flags); + return PyLong_FromLong(flags); } PyDoc_STRVAR(setmode_doc, @@ -111,18 +111,18 @@ static PyObject * msvcrt_open_osfhandle(PyObject *self, PyObject *args) { - long handle; - int flags; - int fd; - - if (!PyArg_ParseTuple(args, "li:open_osfhandle", &handle, &flags)) - return NULL; - - fd = _open_osfhandle(handle, flags); - if (fd == -1) - return PyErr_SetFromErrno(PyExc_IOError); + long handle; + int flags; + int fd; + + if (!PyArg_ParseTuple(args, "li:open_osfhandle", &handle, &flags)) + return NULL; + + fd = _open_osfhandle(handle, flags); + if (fd == -1) + return PyErr_SetFromErrno(PyExc_IOError); - return PyLong_FromLong(fd); + return PyLong_FromLong(fd); } PyDoc_STRVAR(open_osfhandle_doc, @@ -137,20 +137,20 @@ static PyObject * msvcrt_get_osfhandle(PyObject *self, PyObject *args) { - int fd; - Py_intptr_t handle; + int fd; + Py_intptr_t handle; - if (!PyArg_ParseTuple(args,"i:get_osfhandle", &fd)) - return NULL; + if (!PyArg_ParseTuple(args,"i:get_osfhandle", &fd)) + return NULL; - handle = _get_osfhandle(fd); - if (handle == -1) - return PyErr_SetFromErrno(PyExc_IOError); - - /* technically 'handle' is not a pointer, but a integer as - large as a pointer, Python's *VoidPtr interface is the - most appropriate here */ - return PyLong_FromVoidPtr((void*)handle); + handle = _get_osfhandle(fd); + if (handle == -1) + return PyErr_SetFromErrno(PyExc_IOError); + + /* technically 'handle' is not a pointer, but a integer as + large as a pointer, Python's *VoidPtr interface is the + most appropriate here */ + return PyLong_FromVoidPtr((void*)handle); } PyDoc_STRVAR(get_osfhandle_doc, @@ -164,13 +164,13 @@ static PyObject * msvcrt_kbhit(PyObject *self, PyObject *args) { - int ok; + int ok; - if (!PyArg_ParseTuple(args, ":kbhit")) - return NULL; + if (!PyArg_ParseTuple(args, ":kbhit")) + return NULL; - ok = _kbhit(); - return PyLong_FromLong(ok); + ok = _kbhit(); + return PyLong_FromLong(ok); } PyDoc_STRVAR(kbhit_doc, @@ -181,17 +181,17 @@ static PyObject * msvcrt_getch(PyObject *self, PyObject *args) { - int ch; - char s[1]; + int ch; + char s[1]; - if (!PyArg_ParseTuple(args, ":getch")) - return NULL; + if (!PyArg_ParseTuple(args, ":getch")) + return NULL; - Py_BEGIN_ALLOW_THREADS - ch = _getch(); - Py_END_ALLOW_THREADS - s[0] = ch; - return PyBytes_FromStringAndSize(s, 1); + Py_BEGIN_ALLOW_THREADS + ch = _getch(); + Py_END_ALLOW_THREADS + s[0] = ch; + return PyBytes_FromStringAndSize(s, 1); } PyDoc_STRVAR(getch_doc, @@ -208,17 +208,17 @@ static PyObject * msvcrt_getwch(PyObject *self, PyObject *args) { - Py_UNICODE ch; - Py_UNICODE u[1]; + Py_UNICODE ch; + Py_UNICODE u[1]; - if (!PyArg_ParseTuple(args, ":getwch")) - return NULL; + if (!PyArg_ParseTuple(args, ":getwch")) + return NULL; - Py_BEGIN_ALLOW_THREADS - ch = _getwch(); - Py_END_ALLOW_THREADS - u[0] = ch; - return PyUnicode_FromUnicode(u, 1); + Py_BEGIN_ALLOW_THREADS + ch = _getwch(); + Py_END_ALLOW_THREADS + u[0] = ch; + return PyUnicode_FromUnicode(u, 1); } PyDoc_STRVAR(getwch_doc, @@ -230,17 +230,17 @@ static PyObject * msvcrt_getche(PyObject *self, PyObject *args) { - int ch; - char s[1]; + int ch; + char s[1]; - if (!PyArg_ParseTuple(args, ":getche")) - return NULL; + if (!PyArg_ParseTuple(args, ":getche")) + return NULL; - Py_BEGIN_ALLOW_THREADS - ch = _getche(); - Py_END_ALLOW_THREADS - s[0] = ch; - return PyBytes_FromStringAndSize(s, 1); + Py_BEGIN_ALLOW_THREADS + ch = _getche(); + Py_END_ALLOW_THREADS + s[0] = ch; + return PyBytes_FromStringAndSize(s, 1); } PyDoc_STRVAR(getche_doc, @@ -253,17 +253,17 @@ static PyObject * msvcrt_getwche(PyObject *self, PyObject *args) { - Py_UNICODE ch; - Py_UNICODE s[1]; + Py_UNICODE ch; + Py_UNICODE s[1]; - if (!PyArg_ParseTuple(args, ":getwche")) - return NULL; + if (!PyArg_ParseTuple(args, ":getwche")) + return NULL; - Py_BEGIN_ALLOW_THREADS - ch = _getwche(); - Py_END_ALLOW_THREADS - s[0] = ch; - return PyUnicode_FromUnicode(s, 1); + Py_BEGIN_ALLOW_THREADS + ch = _getwche(); + Py_END_ALLOW_THREADS + s[0] = ch; + return PyUnicode_FromUnicode(s, 1); } PyDoc_STRVAR(getwche_doc, @@ -275,14 +275,14 @@ static PyObject * msvcrt_putch(PyObject *self, PyObject *args) { - char ch; + char ch; - if (!PyArg_ParseTuple(args, "c:putch", &ch)) - return NULL; + if (!PyArg_ParseTuple(args, "c:putch", &ch)) + return NULL; - _putch(ch); - Py_INCREF(Py_None); - return Py_None; + _putch(ch); + Py_INCREF(Py_None); + return Py_None; } PyDoc_STRVAR(putch_doc, @@ -294,13 +294,13 @@ static PyObject * msvcrt_putwch(PyObject *self, PyObject *args) { - int ch; + int ch; - if (!PyArg_ParseTuple(args, "C:putwch", &ch)) - return NULL; + if (!PyArg_ParseTuple(args, "C:putwch", &ch)) + return NULL; - _putwch(ch); - Py_RETURN_NONE; + _putwch(ch); + Py_RETURN_NONE; } @@ -313,15 +313,15 @@ static PyObject * msvcrt_ungetch(PyObject *self, PyObject *args) { - char ch; + char ch; - if (!PyArg_ParseTuple(args, "c:ungetch", &ch)) - return NULL; + if (!PyArg_ParseTuple(args, "c:ungetch", &ch)) + return NULL; - if (_ungetch(ch) == EOF) - return PyErr_SetFromErrno(PyExc_IOError); - Py_INCREF(Py_None); - return Py_None; + if (_ungetch(ch) == EOF) + return PyErr_SetFromErrno(PyExc_IOError); + Py_INCREF(Py_None); + return Py_None; } PyDoc_STRVAR(ungetch_doc, @@ -334,15 +334,15 @@ static PyObject * msvcrt_ungetwch(PyObject *self, PyObject *args) { - int ch; + int ch; - if (!PyArg_ParseTuple(args, "C:ungetwch", &ch)) - return NULL; + if (!PyArg_ParseTuple(args, "C:ungetwch", &ch)) + return NULL; - if (_ungetwch(ch) == WEOF) - return PyErr_SetFromErrno(PyExc_IOError); - Py_INCREF(Py_None); - return Py_None; + if (_ungetwch(ch) == WEOF) + return PyErr_SetFromErrno(PyExc_IOError); + Py_INCREF(Py_None); + return Py_None; } PyDoc_STRVAR(ungetwch_doc, @@ -354,15 +354,15 @@ static void insertint(PyObject *d, char *name, int value) { - PyObject *v = PyLong_FromLong((long) value); - if (v == NULL) { - /* Don't bother reporting this error */ - PyErr_Clear(); - } - else { - PyDict_SetItemString(d, name, v); - Py_DECREF(v); - } + PyObject *v = PyLong_FromLong((long) value); + if (v == NULL) { + /* Don't bother reporting this error */ + PyErr_Clear(); + } + else { + PyDict_SetItemString(d, name, v); + Py_DECREF(v); + } } #ifdef _DEBUG @@ -370,40 +370,40 @@ static PyObject* msvcrt_setreportfile(PyObject *self, PyObject *args) { - int type, file; - _HFILE res; + int type, file; + _HFILE res; - if (!PyArg_ParseTuple(args, "ii", &type, &file)) - return NULL; - res = _CrtSetReportFile(type, (_HFILE)file); - return PyLong_FromLong((long)res); - Py_INCREF(Py_None); - return Py_None; + if (!PyArg_ParseTuple(args, "ii", &type, &file)) + return NULL; + res = _CrtSetReportFile(type, (_HFILE)file); + return PyLong_FromLong((long)res); + Py_INCREF(Py_None); + return Py_None; } static PyObject* msvcrt_setreportmode(PyObject *self, PyObject *args) { - int type, mode; - int res; + int type, mode; + int res; - if (!PyArg_ParseTuple(args, "ii", &type, &mode)) - return NULL; - res = _CrtSetReportMode(type, mode); - if (res == -1) - return PyErr_SetFromErrno(PyExc_IOError); - return PyLong_FromLong(res); + if (!PyArg_ParseTuple(args, "ii", &type, &mode)) + return NULL; + res = _CrtSetReportMode(type, mode); + if (res == -1) + return PyErr_SetFromErrno(PyExc_IOError); + return PyLong_FromLong(res); } static PyObject* msvcrt_seterrormode(PyObject *self, PyObject *args) { - int mode, res; + int mode, res; - if (!PyArg_ParseTuple(args, "i", &mode)) - return NULL; - res = _set_error_mode(mode); - return PyLong_FromLong(res); + if (!PyArg_ParseTuple(args, "i", &mode)) + return NULL; + res = _set_error_mode(mode); + return PyLong_FromLong(res); } #endif @@ -411,104 +411,104 @@ static PyObject* seterrormode(PyObject *self, PyObject *args) { - unsigned int mode, res; + unsigned int mode, res; - if (!PyArg_ParseTuple(args, "I", &mode)) - return NULL; - res = SetErrorMode(mode); - return PyLong_FromUnsignedLong(res); + if (!PyArg_ParseTuple(args, "I", &mode)) + return NULL; + res = SetErrorMode(mode); + return PyLong_FromUnsignedLong(res); } /* List of functions exported by this module */ static struct PyMethodDef msvcrt_functions[] = { - {"heapmin", msvcrt_heapmin, METH_VARARGS, heapmin_doc}, - {"locking", msvcrt_locking, METH_VARARGS, locking_doc}, - {"setmode", msvcrt_setmode, METH_VARARGS, setmode_doc}, - {"open_osfhandle", msvcrt_open_osfhandle, METH_VARARGS, open_osfhandle_doc}, - {"get_osfhandle", msvcrt_get_osfhandle, METH_VARARGS, get_osfhandle_doc}, - {"kbhit", msvcrt_kbhit, METH_VARARGS, kbhit_doc}, - {"getch", msvcrt_getch, METH_VARARGS, getch_doc}, - {"getche", msvcrt_getche, METH_VARARGS, getche_doc}, - {"putch", msvcrt_putch, METH_VARARGS, putch_doc}, - {"ungetch", msvcrt_ungetch, METH_VARARGS, ungetch_doc}, - {"SetErrorMode", seterrormode, METH_VARARGS}, + {"heapmin", msvcrt_heapmin, METH_VARARGS, heapmin_doc}, + {"locking", msvcrt_locking, METH_VARARGS, locking_doc}, + {"setmode", msvcrt_setmode, METH_VARARGS, setmode_doc}, + {"open_osfhandle", msvcrt_open_osfhandle, METH_VARARGS, open_osfhandle_doc}, + {"get_osfhandle", msvcrt_get_osfhandle, METH_VARARGS, get_osfhandle_doc}, + {"kbhit", msvcrt_kbhit, METH_VARARGS, kbhit_doc}, + {"getch", msvcrt_getch, METH_VARARGS, getch_doc}, + {"getche", msvcrt_getche, METH_VARARGS, getche_doc}, + {"putch", msvcrt_putch, METH_VARARGS, putch_doc}, + {"ungetch", msvcrt_ungetch, METH_VARARGS, ungetch_doc}, + {"SetErrorMode", seterrormode, METH_VARARGS}, #ifdef _DEBUG - {"CrtSetReportFile", msvcrt_setreportfile, METH_VARARGS}, - {"CrtSetReportMode", msvcrt_setreportmode, METH_VARARGS}, - {"set_error_mode", msvcrt_seterrormode, METH_VARARGS}, + {"CrtSetReportFile", msvcrt_setreportfile, METH_VARARGS}, + {"CrtSetReportMode", msvcrt_setreportmode, METH_VARARGS}, + {"set_error_mode", msvcrt_seterrormode, METH_VARARGS}, #endif #ifdef _WCONIO_DEFINED - {"getwch", msvcrt_getwch, METH_VARARGS, getwch_doc}, - {"getwche", msvcrt_getwche, METH_VARARGS, getwche_doc}, - {"putwch", msvcrt_putwch, METH_VARARGS, putwch_doc}, - {"ungetwch", msvcrt_ungetwch, METH_VARARGS, ungetwch_doc}, + {"getwch", msvcrt_getwch, METH_VARARGS, getwch_doc}, + {"getwche", msvcrt_getwche, METH_VARARGS, getwche_doc}, + {"putwch", msvcrt_putwch, METH_VARARGS, putwch_doc}, + {"ungetwch", msvcrt_ungetwch, METH_VARARGS, ungetwch_doc}, #endif - {NULL, NULL} + {NULL, NULL} }; static struct PyModuleDef msvcrtmodule = { - PyModuleDef_HEAD_INIT, - "msvcrt", - NULL, - -1, - msvcrt_functions, - NULL, - NULL, - NULL, - NULL + PyModuleDef_HEAD_INIT, + "msvcrt", + NULL, + -1, + msvcrt_functions, + NULL, + NULL, + NULL, + NULL }; PyMODINIT_FUNC PyInit_msvcrt(void) { - int st; - PyObject *d; - PyObject *m = PyModule_Create(&msvcrtmodule); - if (m == NULL) - return NULL; - d = PyModule_GetDict(m); - - /* constants for the locking() function's mode argument */ - insertint(d, "LK_LOCK", _LK_LOCK); - insertint(d, "LK_NBLCK", _LK_NBLCK); - insertint(d, "LK_NBRLCK", _LK_NBRLCK); - insertint(d, "LK_RLCK", _LK_RLCK); - insertint(d, "LK_UNLCK", _LK_UNLCK); - insertint(d, "SEM_FAILCRITICALERRORS", SEM_FAILCRITICALERRORS); - insertint(d, "SEM_NOALIGNMENTFAULTEXCEPT", SEM_NOALIGNMENTFAULTEXCEPT); - insertint(d, "SEM_NOGPFAULTERRORBOX", SEM_NOGPFAULTERRORBOX); - insertint(d, "SEM_NOOPENFILEERRORBOX", SEM_NOOPENFILEERRORBOX); + int st; + PyObject *d; + PyObject *m = PyModule_Create(&msvcrtmodule); + if (m == NULL) + return NULL; + d = PyModule_GetDict(m); + + /* constants for the locking() function's mode argument */ + insertint(d, "LK_LOCK", _LK_LOCK); + insertint(d, "LK_NBLCK", _LK_NBLCK); + insertint(d, "LK_NBRLCK", _LK_NBRLCK); + insertint(d, "LK_RLCK", _LK_RLCK); + insertint(d, "LK_UNLCK", _LK_UNLCK); + insertint(d, "SEM_FAILCRITICALERRORS", SEM_FAILCRITICALERRORS); + insertint(d, "SEM_NOALIGNMENTFAULTEXCEPT", SEM_NOALIGNMENTFAULTEXCEPT); + insertint(d, "SEM_NOGPFAULTERRORBOX", SEM_NOGPFAULTERRORBOX); + insertint(d, "SEM_NOOPENFILEERRORBOX", SEM_NOOPENFILEERRORBOX); #ifdef _DEBUG - insertint(d, "CRT_WARN", _CRT_WARN); - insertint(d, "CRT_ERROR", _CRT_ERROR); - insertint(d, "CRT_ASSERT", _CRT_ASSERT); - insertint(d, "CRTDBG_MODE_DEBUG", _CRTDBG_MODE_DEBUG); - insertint(d, "CRTDBG_MODE_FILE", _CRTDBG_MODE_FILE); - insertint(d, "CRTDBG_MODE_WNDW", _CRTDBG_MODE_WNDW); - insertint(d, "CRTDBG_REPORT_MODE", _CRTDBG_REPORT_MODE); - insertint(d, "CRTDBG_FILE_STDERR", (int)_CRTDBG_FILE_STDERR); - insertint(d, "CRTDBG_FILE_STDOUT", (int)_CRTDBG_FILE_STDOUT); - insertint(d, "CRTDBG_REPORT_FILE", (int)_CRTDBG_REPORT_FILE); + insertint(d, "CRT_WARN", _CRT_WARN); + insertint(d, "CRT_ERROR", _CRT_ERROR); + insertint(d, "CRT_ASSERT", _CRT_ASSERT); + insertint(d, "CRTDBG_MODE_DEBUG", _CRTDBG_MODE_DEBUG); + insertint(d, "CRTDBG_MODE_FILE", _CRTDBG_MODE_FILE); + insertint(d, "CRTDBG_MODE_WNDW", _CRTDBG_MODE_WNDW); + insertint(d, "CRTDBG_REPORT_MODE", _CRTDBG_REPORT_MODE); + insertint(d, "CRTDBG_FILE_STDERR", (int)_CRTDBG_FILE_STDERR); + insertint(d, "CRTDBG_FILE_STDOUT", (int)_CRTDBG_FILE_STDOUT); + insertint(d, "CRTDBG_REPORT_FILE", (int)_CRTDBG_REPORT_FILE); #endif - /* constants for the crt versions */ + /* constants for the crt versions */ #ifdef _VC_ASSEMBLY_PUBLICKEYTOKEN - st = PyModule_AddStringConstant(m, "VC_ASSEMBLY_PUBLICKEYTOKEN", - _VC_ASSEMBLY_PUBLICKEYTOKEN); - if (st < 0) return NULL; + st = PyModule_AddStringConstant(m, "VC_ASSEMBLY_PUBLICKEYTOKEN", + _VC_ASSEMBLY_PUBLICKEYTOKEN); + if (st < 0) return NULL; #endif #ifdef _CRT_ASSEMBLY_VERSION - st = PyModule_AddStringConstant(m, "CRT_ASSEMBLY_VERSION", - _CRT_ASSEMBLY_VERSION); - if (st < 0) return NULL; + st = PyModule_AddStringConstant(m, "CRT_ASSEMBLY_VERSION", + _CRT_ASSEMBLY_VERSION); + if (st < 0) return NULL; #endif #ifdef __LIBRARIES_ASSEMBLY_NAME_PREFIX - st = PyModule_AddStringConstant(m, "LIBRARIES_ASSEMBLY_NAME_PREFIX", - __LIBRARIES_ASSEMBLY_NAME_PREFIX); - if (st < 0) return NULL; + st = PyModule_AddStringConstant(m, "LIBRARIES_ASSEMBLY_NAME_PREFIX", + __LIBRARIES_ASSEMBLY_NAME_PREFIX); + if (st < 0) return NULL; #endif - return m; + return m; } Modified: python/branches/release31-maint/PC/os2emx/config.c ============================================================================== --- python/branches/release31-maint/PC/os2emx/config.c (original) +++ python/branches/release31-maint/PC/os2emx/config.c Sun May 9 18:14:21 2010 @@ -95,71 +95,71 @@ struct _inittab _PyImport_Inittab[] = { - {"os2", initos2}, - {"signal", initsignal}, + {"os2", initos2}, + {"signal", initsignal}, #ifdef WITH_THREAD - {"_thread", init_thread}, + {"_thread", init_thread}, #endif - {"_codecs", init_codecs}, - {"_csv", init_csv}, - {"_locale", init_locale}, - {"_random", init_random}, - {"_sre", init_sre}, - {"_symtable", init_symtable}, - {"_weakref", init_weakref}, - {"array", initarray}, - {"binascii", initbinascii}, - {"collections", initcollections}, - {"cmath", initcmath}, - {"datetime", initdatetime}, - {"dl", initdl}, - {"errno", initerrno}, - {"fcntl", initfcntl}, - {"_functools", init_functools}, - {"_heapq", init_heapq}, - {"imageop", initimageop}, - {"itertools", inititertools}, - {"math", initmath}, - {"operator", initoperator}, - {"_sha256", init_sha256}, - {"_sha512", init_sha512}, - {"_struct", init_struct}, - {"termios", inittermios}, - {"time", inittime}, - {"xxsubtype", initxxsubtype}, - {"zipimport", initzipimport}, + {"_codecs", init_codecs}, + {"_csv", init_csv}, + {"_locale", init_locale}, + {"_random", init_random}, + {"_sre", init_sre}, + {"_symtable", init_symtable}, + {"_weakref", init_weakref}, + {"array", initarray}, + {"binascii", initbinascii}, + {"collections", initcollections}, + {"cmath", initcmath}, + {"datetime", initdatetime}, + {"dl", initdl}, + {"errno", initerrno}, + {"fcntl", initfcntl}, + {"_functools", init_functools}, + {"_heapq", init_heapq}, + {"imageop", initimageop}, + {"itertools", inititertools}, + {"math", initmath}, + {"operator", initoperator}, + {"_sha256", init_sha256}, + {"_sha512", init_sha512}, + {"_struct", init_struct}, + {"termios", inittermios}, + {"time", inittime}, + {"xxsubtype", initxxsubtype}, + {"zipimport", initzipimport}, #if !HAVE_DYNAMIC_LOADING - {"_curses", init_curses}, - {"_curses_panel", init_curses_panel}, - {"_testcapi", init_testcapi}, - {"bz2", initbz2}, - {"fpectl", initfpectl}, - {"fpetest", initfpetest}, - {"parser", initparser}, - {"pwd", initpwd}, - {"unicodedata", initunicodedata}, - {"zlib", initzlib}, + {"_curses", init_curses}, + {"_curses_panel", init_curses_panel}, + {"_testcapi", init_testcapi}, + {"bz2", initbz2}, + {"fpectl", initfpectl}, + {"fpetest", initfpetest}, + {"parser", initparser}, + {"pwd", initpwd}, + {"unicodedata", initunicodedata}, + {"zlib", initzlib}, #ifdef USE_SOCKET - {"_socket", init_socket}, - {"select", initselect}, + {"_socket", init_socket}, + {"select", initselect}, #endif #endif /* -- ADDMODULE MARKER 2 -- */ - /* This module "lives in" with marshal.c */ - {"marshal", PyMarshal_Init}, + /* This module "lives in" with marshal.c */ + {"marshal", PyMarshal_Init}, - /* This lives it with import.c */ - {"imp", initimp}, + /* This lives it with import.c */ + {"imp", initimp}, - /* These entries are here for sys.builtin_module_names */ - {"__main__", NULL}, - {"builtins", NULL}, - {"sys", NULL}, + /* These entries are here for sys.builtin_module_names */ + {"__main__", NULL}, + {"builtins", NULL}, + {"sys", NULL}, - /* This lives in gcmodule.c */ - {"gc", initgc}, + /* This lives in gcmodule.c */ + {"gc", initgc}, - /* Sentinel */ - {0, 0} + /* Sentinel */ + {0, 0} }; Modified: python/branches/release31-maint/PC/os2emx/dlfcn.c ============================================================================== --- python/branches/release31-maint/PC/os2emx/dlfcn.c (original) +++ python/branches/release31-maint/PC/os2emx/dlfcn.c Sun May 9 18:14:21 2010 @@ -46,178 +46,178 @@ #include typedef struct _track_rec { - char *name; - HMODULE handle; - void *id; - struct _track_rec *next; + char *name; + HMODULE handle; + void *id; + struct _track_rec *next; } tDLLchain, *DLLchain; -static DLLchain dlload = NULL; /* A simple chained list of DLL names */ -static char dlerr [256]; /* last error text string */ +static DLLchain dlload = NULL; /* A simple chained list of DLL names */ +static char dlerr [256]; /* last error text string */ static void *last_id; static DLLchain find_id(void *id) { - DLLchain tmp; + DLLchain tmp; - for (tmp = dlload; tmp; tmp = tmp->next) - if (id == tmp->id) - return tmp; + for (tmp = dlload; tmp; tmp = tmp->next) + if (id == tmp->id) + return tmp; - return NULL; + return NULL; } /* load a dynamic-link library and return handle */ void *dlopen(char *filename, int flags) { - HMODULE hm; - DLLchain tmp; - char err[256]; - char *errtxt; - int rc = 0, set_chain = 0; - - for (tmp = dlload; tmp; tmp = tmp->next) - if (strnicmp(tmp->name, filename, 999) == 0) - break; - - if (!tmp) - { - tmp = (DLLchain) malloc(sizeof(tDLLchain)); - if (!tmp) - goto nomem; - tmp->name = strdup(filename); - tmp->next = dlload; - set_chain = 1; - } - - switch (rc = DosLoadModule((PSZ)&err, sizeof(err), filename, &hm)) - { - case NO_ERROR: - tmp->handle = hm; - if (set_chain) - { - do - last_id++; - while ((last_id == 0) || (find_id(last_id))); - tmp->id = last_id; - dlload = tmp; - } - return tmp->id; - case ERROR_FILE_NOT_FOUND: - case ERROR_PATH_NOT_FOUND: - errtxt = "module `%s' not found"; - break; - case ERROR_TOO_MANY_OPEN_FILES: - case ERROR_NOT_ENOUGH_MEMORY: - case ERROR_SHARING_BUFFER_EXCEEDED: + HMODULE hm; + DLLchain tmp; + char err[256]; + char *errtxt; + int rc = 0, set_chain = 0; + + for (tmp = dlload; tmp; tmp = tmp->next) + if (strnicmp(tmp->name, filename, 999) == 0) + break; + + if (!tmp) + { + tmp = (DLLchain) malloc(sizeof(tDLLchain)); + if (!tmp) + goto nomem; + tmp->name = strdup(filename); + tmp->next = dlload; + set_chain = 1; + } + + switch (rc = DosLoadModule((PSZ)&err, sizeof(err), filename, &hm)) + { + case NO_ERROR: + tmp->handle = hm; + if (set_chain) + { + do + last_id++; + while ((last_id == 0) || (find_id(last_id))); + tmp->id = last_id; + dlload = tmp; + } + return tmp->id; + case ERROR_FILE_NOT_FOUND: + case ERROR_PATH_NOT_FOUND: + errtxt = "module `%s' not found"; + break; + case ERROR_TOO_MANY_OPEN_FILES: + case ERROR_NOT_ENOUGH_MEMORY: + case ERROR_SHARING_BUFFER_EXCEEDED: nomem: - errtxt = "out of system resources"; - break; - case ERROR_ACCESS_DENIED: - errtxt = "access denied"; - break; - case ERROR_BAD_FORMAT: - case ERROR_INVALID_SEGMENT_NUMBER: - case ERROR_INVALID_ORDINAL: - case ERROR_INVALID_MODULETYPE: - case ERROR_INVALID_EXE_SIGNATURE: - case ERROR_EXE_MARKED_INVALID: - case ERROR_ITERATED_DATA_EXCEEDS_64K: - case ERROR_INVALID_MINALLOCSIZE: - case ERROR_INVALID_SEGDPL: - case ERROR_AUTODATASEG_EXCEEDS_64K: - case ERROR_RELOCSRC_CHAIN_EXCEEDS_SEGLIMIT: - errtxt = "invalid module format"; - break; - case ERROR_INVALID_NAME: - errtxt = "filename doesn't match module name"; - break; - case ERROR_SHARING_VIOLATION: - case ERROR_LOCK_VIOLATION: - errtxt = "sharing violation"; - break; - case ERROR_INIT_ROUTINE_FAILED: - errtxt = "module initialization failed"; - break; - default: - errtxt = "cause `%s', error code = %d"; - break; - } - snprintf(dlerr, sizeof(dlerr), errtxt, &err, rc); - if (tmp) - { - if (tmp->name) - free(tmp->name); - free(tmp); - } - return 0; + errtxt = "out of system resources"; + break; + case ERROR_ACCESS_DENIED: + errtxt = "access denied"; + break; + case ERROR_BAD_FORMAT: + case ERROR_INVALID_SEGMENT_NUMBER: + case ERROR_INVALID_ORDINAL: + case ERROR_INVALID_MODULETYPE: + case ERROR_INVALID_EXE_SIGNATURE: + case ERROR_EXE_MARKED_INVALID: + case ERROR_ITERATED_DATA_EXCEEDS_64K: + case ERROR_INVALID_MINALLOCSIZE: + case ERROR_INVALID_SEGDPL: + case ERROR_AUTODATASEG_EXCEEDS_64K: + case ERROR_RELOCSRC_CHAIN_EXCEEDS_SEGLIMIT: + errtxt = "invalid module format"; + break; + case ERROR_INVALID_NAME: + errtxt = "filename doesn't match module name"; + break; + case ERROR_SHARING_VIOLATION: + case ERROR_LOCK_VIOLATION: + errtxt = "sharing violation"; + break; + case ERROR_INIT_ROUTINE_FAILED: + errtxt = "module initialization failed"; + break; + default: + errtxt = "cause `%s', error code = %d"; + break; + } + snprintf(dlerr, sizeof(dlerr), errtxt, &err, rc); + if (tmp) + { + if (tmp->name) + free(tmp->name); + free(tmp); + } + return 0; } /* return a pointer to the `symbol' in DLL */ void *dlsym(void *handle, char *symbol) { - int rc = 0; - PFN addr; - char *errtxt; - int symord = 0; - DLLchain tmp = find_id(handle); - - if (!tmp) - goto inv_handle; - - if (*symbol == '#') - symord = atoi(symbol + 1); - - switch (rc = DosQueryProcAddr(tmp->handle, symord, symbol, &addr)) - { - case NO_ERROR: - return (void *)addr; - case ERROR_INVALID_HANDLE: + int rc = 0; + PFN addr; + char *errtxt; + int symord = 0; + DLLchain tmp = find_id(handle); + + if (!tmp) + goto inv_handle; + + if (*symbol == '#') + symord = atoi(symbol + 1); + + switch (rc = DosQueryProcAddr(tmp->handle, symord, symbol, &addr)) + { + case NO_ERROR: + return (void *)addr; + case ERROR_INVALID_HANDLE: inv_handle: - errtxt = "invalid module handle"; - break; - case ERROR_PROC_NOT_FOUND: - case ERROR_INVALID_NAME: - errtxt = "no symbol `%s' in module"; - break; - default: - errtxt = "symbol `%s', error code = %d"; - break; - } - snprintf(dlerr, sizeof(dlerr), errtxt, symbol, rc); - return NULL; + errtxt = "invalid module handle"; + break; + case ERROR_PROC_NOT_FOUND: + case ERROR_INVALID_NAME: + errtxt = "no symbol `%s' in module"; + break; + default: + errtxt = "symbol `%s', error code = %d"; + break; + } + snprintf(dlerr, sizeof(dlerr), errtxt, symbol, rc); + return NULL; } /* free dynamicaly-linked library */ int dlclose(void *handle) { - int rc; - DLLchain tmp = find_id(handle); + int rc; + DLLchain tmp = find_id(handle); - if (!tmp) - goto inv_handle; + if (!tmp) + goto inv_handle; - switch (rc = DosFreeModule(tmp->handle)) - { - case NO_ERROR: - free(tmp->name); - dlload = tmp->next; - free(tmp); - return 0; - case ERROR_INVALID_HANDLE: + switch (rc = DosFreeModule(tmp->handle)) + { + case NO_ERROR: + free(tmp->name); + dlload = tmp->next; + free(tmp); + return 0; + case ERROR_INVALID_HANDLE: inv_handle: - strcpy(dlerr, "invalid module handle"); - return -1; - case ERROR_INVALID_ACCESS: - strcpy(dlerr, "access denied"); - return -1; - default: - return -1; - } + strcpy(dlerr, "invalid module handle"); + return -1; + case ERROR_INVALID_ACCESS: + strcpy(dlerr, "access denied"); + return -1; + default: + return -1; + } } /* return a string describing last occurred dl error */ char *dlerror() { - return dlerr; + return dlerr; } Modified: python/branches/release31-maint/PC/os2emx/dllentry.c ============================================================================== --- python/branches/release31-maint/PC/os2emx/dllentry.c (original) +++ python/branches/release31-maint/PC/os2emx/dllentry.c Sun May 9 18:14:21 2010 @@ -4,7 +4,7 @@ #define NULL 0 -#define REF(s) extern void s(); void *____ref_##s = &s; +#define REF(s) extern void s(); void *____ref_##s = &s; /* Make references to imported symbols to pull them from static library */ REF(Py_Main); @@ -18,25 +18,25 @@ unsigned long _DLL_InitTerm(unsigned long mod_handle, unsigned long flag) { - switch (flag) - { - case 0: - if (_CRT_init()) - return 0; - __ctordtorInit(); - - /* Ignore fatal signals */ - signal(SIGSEGV, SIG_IGN); - signal(SIGFPE, SIG_IGN); - - return 1; - - case 1: - __ctordtorTerm(); - _CRT_term(); - return 1; - - default: - return 0; - } + switch (flag) + { + case 0: + if (_CRT_init()) + return 0; + __ctordtorInit(); + + /* Ignore fatal signals */ + signal(SIGSEGV, SIG_IGN); + signal(SIGFPE, SIG_IGN); + + return 1; + + case 1: + __ctordtorTerm(); + _CRT_term(); + return 1; + + default: + return 0; + } } Modified: python/branches/release31-maint/PC/os2emx/getpathp.c ============================================================================== --- python/branches/release31-maint/PC/os2emx/getpathp.c (original) +++ python/branches/release31-maint/PC/os2emx/getpathp.c Sun May 9 18:14:21 2010 @@ -4,8 +4,8 @@ /* ---------------------------------------------------------------- PATH RULES FOR OS/2+EMX: - This describes how sys.path is formed on OS/2+EMX. It describes the - functionality, not the implementation (ie, the order in which these + This describes how sys.path is formed on OS/2+EMX. It describes the + functionality, not the implementation (ie, the order in which these are actually fetched is different) * Python always adds an empty entry at the start, which corresponds @@ -16,10 +16,10 @@ * We attempt to locate the "Python Home" - if the PYTHONHOME env var is set, we believe it. Otherwise, we use the path of our host .EXE's to try and locate our "landmark" (lib\\os.py) and deduce our home. - - If we DO have a Python Home: The relevant sub-directories (Lib, + - If we DO have a Python Home: The relevant sub-directories (Lib, plat-win, etc) are based on the Python Home - If we DO NOT have a Python Home, the core Python Path is - loaded from the registry. This is the main PythonPath key, + loaded from the registry. This is the main PythonPath key, and both HKLM and HKCU are combined to form the path) * Iff - we can not locate the Python Home, and have not had a PYTHONPATH @@ -32,9 +32,9 @@ (either an installed version, or directly from the PCbuild directory), the core path is deduced. - * When Python is hosted in another exe (different directory, embedded via + * When Python is hosted in another exe (different directory, embedded via COM, etc), the Python Home will not be deduced, so the core path from - the registry is used. Other "application paths "in the registry are + the registry is used. Other "application paths "in the registry are always read. * If Python can't find its home and there is no registry (eg, frozen @@ -85,12 +85,12 @@ static int -is_sep(char ch) /* determine if "ch" is a separator character */ +is_sep(char ch) /* determine if "ch" is a separator character */ { #ifdef ALTSEP - return ch == SEP || ch == ALTSEP; + return ch == SEP || ch == ALTSEP; #else - return ch == SEP; + return ch == SEP; #endif } @@ -100,36 +100,36 @@ static void reduce(char *dir) { - size_t i = strlen(dir); - while (i > 0 && !is_sep(dir[i])) - --i; - dir[i] = '\0'; + size_t i = strlen(dir); + while (i > 0 && !is_sep(dir[i])) + --i; + dir[i] = '\0'; } - + static int exists(char *filename) { - struct stat buf; - return stat(filename, &buf) == 0; + struct stat buf; + return stat(filename, &buf) == 0; } /* Is module (check for .pyc/.pyo too) - * Assumes 'filename' MAXPATHLEN+1 bytes long - + * Assumes 'filename' MAXPATHLEN+1 bytes long - * may extend 'filename' by one character. */ static int ismodule(char *filename) { - if (exists(filename)) - return 1; + if (exists(filename)) + return 1; - /* Check for the compiled version of prefix. */ - if (strlen(filename) < MAXPATHLEN) { - strcat(filename, Py_OptimizeFlag ? "o" : "c"); - if (exists(filename)) - return 1; - } - return 0; + /* Check for the compiled version of prefix. */ + if (strlen(filename) < MAXPATHLEN) { + strcat(filename, Py_OptimizeFlag ? "o" : "c"); + if (exists(filename)) + return 1; + } + return 0; } /* Add a path component, by appending stuff to buffer. @@ -145,21 +145,21 @@ static void join(char *buffer, char *stuff) { - size_t n, k; - if (is_sep(stuff[0])) - n = 0; - else { - n = strlen(buffer); - if (n > 0 && !is_sep(buffer[n-1]) && n < MAXPATHLEN) - buffer[n++] = SEP; - } - if (n > MAXPATHLEN) - Py_FatalError("buffer overflow in getpathp.c's joinpath()"); - k = strlen(stuff); - if (n + k > MAXPATHLEN) - k = MAXPATHLEN - n; - strncpy(buffer+n, stuff, k); - buffer[n+k] = '\0'; + size_t n, k; + if (is_sep(stuff[0])) + n = 0; + else { + n = strlen(buffer); + if (n > 0 && !is_sep(buffer[n-1]) && n < MAXPATHLEN) + buffer[n++] = SEP; + } + if (n > MAXPATHLEN) + Py_FatalError("buffer overflow in getpathp.c's joinpath()"); + k = strlen(stuff); + if (n + k > MAXPATHLEN) + k = MAXPATHLEN - n; + strncpy(buffer+n, stuff, k); + buffer[n+k] = '\0'; } /* gotlandmark only called by search_for_prefix, which ensures @@ -169,219 +169,219 @@ static int gotlandmark(char *landmark) { - int n, ok; + int n, ok; - n = strlen(prefix); - join(prefix, landmark); - ok = ismodule(prefix); - prefix[n] = '\0'; - return ok; + n = strlen(prefix); + join(prefix, landmark); + ok = ismodule(prefix); + prefix[n] = '\0'; + return ok; } -/* assumes argv0_path is MAXPATHLEN+1 bytes long, already \0 term'd. +/* assumes argv0_path is MAXPATHLEN+1 bytes long, already \0 term'd. * assumption provided by only caller, calculate_path() */ static int search_for_prefix(char *argv0_path, char *landmark) { - /* Search from argv0_path, until landmark is found */ - strcpy(prefix, argv0_path); - do { - if (gotlandmark(landmark)) - return 1; - reduce(prefix); - } while (prefix[0]); - return 0; + /* Search from argv0_path, until landmark is found */ + strcpy(prefix, argv0_path); + do { + if (gotlandmark(landmark)) + return 1; + reduce(prefix); + } while (prefix[0]); + return 0; } static void get_progpath(void) { - extern char *Py_GetProgramName(void); - char *path = getenv("PATH"); - char *prog = Py_GetProgramName(); - - PPIB pib; - if ((DosGetInfoBlocks(NULL, &pib) == 0) && - (DosQueryModuleName(pib->pib_hmte, sizeof(progpath), progpath) == 0)) - return; - - if (prog == NULL || *prog == '\0') - prog = "python"; - - /* If there is no slash in the argv0 path, then we have to - * assume python is on the user's $PATH, since there's no - * other way to find a directory to start the search from. If - * $PATH isn't exported, you lose. - */ + extern char *Py_GetProgramName(void); + char *path = getenv("PATH"); + char *prog = Py_GetProgramName(); + + PPIB pib; + if ((DosGetInfoBlocks(NULL, &pib) == 0) && + (DosQueryModuleName(pib->pib_hmte, sizeof(progpath), progpath) == 0)) + return; + + if (prog == NULL || *prog == '\0') + prog = "python"; + + /* If there is no slash in the argv0 path, then we have to + * assume python is on the user's $PATH, since there's no + * other way to find a directory to start the search from. If + * $PATH isn't exported, you lose. + */ #ifdef ALTSEP - if (strchr(prog, SEP) || strchr(prog, ALTSEP)) + if (strchr(prog, SEP) || strchr(prog, ALTSEP)) #else - if (strchr(prog, SEP)) + if (strchr(prog, SEP)) #endif - strncpy(progpath, prog, MAXPATHLEN); - else if (path) { - while (1) { - char *delim = strchr(path, DELIM); - - if (delim) { - size_t len = delim - path; - /* ensure we can't overwrite buffer */ + strncpy(progpath, prog, MAXPATHLEN); + else if (path) { + while (1) { + char *delim = strchr(path, DELIM); + + if (delim) { + size_t len = delim - path; + /* ensure we can't overwrite buffer */ #if !defined(PYCC_GCC) - len = min(MAXPATHLEN,len); + len = min(MAXPATHLEN,len); #else - len = MAXPATHLEN < len ? MAXPATHLEN : len; + len = MAXPATHLEN < len ? MAXPATHLEN : len; #endif - strncpy(progpath, path, len); - *(progpath + len) = '\0'; - } - else - strncpy(progpath, path, MAXPATHLEN); - - /* join() is safe for MAXPATHLEN+1 size buffer */ - join(progpath, prog); - if (exists(progpath)) - break; - - if (!delim) { - progpath[0] = '\0'; - break; - } - path = delim + 1; - } - } - else - progpath[0] = '\0'; + strncpy(progpath, path, len); + *(progpath + len) = '\0'; + } + else + strncpy(progpath, path, MAXPATHLEN); + + /* join() is safe for MAXPATHLEN+1 size buffer */ + join(progpath, prog); + if (exists(progpath)) + break; + + if (!delim) { + progpath[0] = '\0'; + break; + } + path = delim + 1; + } + } + else + progpath[0] = '\0'; } static void calculate_path(void) { - char argv0_path[MAXPATHLEN+1]; - char *buf; - size_t bufsz; - char *pythonhome = Py_GetPythonHome(); - char *envpath = getenv("PYTHONPATH"); - char zip_path[MAXPATHLEN+1]; - size_t len; - - get_progpath(); - /* progpath guaranteed \0 terminated in MAXPATH+1 bytes. */ - strcpy(argv0_path, progpath); - reduce(argv0_path); - if (pythonhome == NULL || *pythonhome == '\0') { - if (search_for_prefix(argv0_path, LANDMARK)) - pythonhome = prefix; - else - pythonhome = NULL; - } - else - strncpy(prefix, pythonhome, MAXPATHLEN); - - if (envpath && *envpath == '\0') - envpath = NULL; - - /* Calculate zip archive path */ - strncpy(zip_path, progpath, MAXPATHLEN); - zip_path[MAXPATHLEN] = '\0'; - len = strlen(zip_path); - if (len > 4) { - zip_path[len-3] = 'z'; /* change ending to "zip" */ - zip_path[len-2] = 'i'; - zip_path[len-1] = 'p'; - } - else { - zip_path[0] = 0; - } - - /* We need to construct a path from the following parts. - * (1) the PYTHONPATH environment variable, if set; - * (2) the zip archive file path; - * (3) the PYTHONPATH config macro, with the leading "." - * of each component replaced with pythonhome, if set; - * (4) the directory containing the executable (argv0_path). - * The length calculation calculates #3 first. - */ - - /* Calculate size of return buffer */ - if (pythonhome != NULL) { - char *p; - bufsz = 1; - for (p = PYTHONPATH; *p; p++) { - if (*p == DELIM) - bufsz++; /* number of DELIM plus one */ - } - bufsz *= strlen(pythonhome); - } - else - bufsz = 0; - bufsz += strlen(PYTHONPATH) + 1; - bufsz += strlen(argv0_path) + 1; - bufsz += strlen(zip_path) + 1; - if (envpath != NULL) - bufsz += strlen(envpath) + 1; - - module_search_path = buf = malloc(bufsz); - if (buf == NULL) { - /* We can't exit, so print a warning and limp along */ - fprintf(stderr, "Can't malloc dynamic PYTHONPATH.\n"); - if (envpath) { - fprintf(stderr, "Using environment $PYTHONPATH.\n"); - module_search_path = envpath; - } - else { - fprintf(stderr, "Using default static path.\n"); - module_search_path = PYTHONPATH; - } - return; - } - - if (envpath) { - strcpy(buf, envpath); - buf = strchr(buf, '\0'); - *buf++ = DELIM; - } - if (zip_path[0]) { - strcpy(buf, zip_path); - buf = strchr(buf, '\0'); - *buf++ = DELIM; - } - - if (pythonhome == NULL) { - strcpy(buf, PYTHONPATH); - buf = strchr(buf, '\0'); - } - else { - char *p = PYTHONPATH; - char *q; - size_t n; - for (;;) { - q = strchr(p, DELIM); - if (q == NULL) - n = strlen(p); - else - n = q-p; - if (p[0] == '.' && is_sep(p[1])) { - strcpy(buf, pythonhome); - buf = strchr(buf, '\0'); - p++; - n--; - } - strncpy(buf, p, n); - buf += n; - if (q == NULL) - break; - *buf++ = DELIM; - p = q+1; - } - } - if (argv0_path) { - *buf++ = DELIM; - strcpy(buf, argv0_path); - buf = strchr(buf, '\0'); - } - *buf = '\0'; + char argv0_path[MAXPATHLEN+1]; + char *buf; + size_t bufsz; + char *pythonhome = Py_GetPythonHome(); + char *envpath = getenv("PYTHONPATH"); + char zip_path[MAXPATHLEN+1]; + size_t len; + + get_progpath(); + /* progpath guaranteed \0 terminated in MAXPATH+1 bytes. */ + strcpy(argv0_path, progpath); + reduce(argv0_path); + if (pythonhome == NULL || *pythonhome == '\0') { + if (search_for_prefix(argv0_path, LANDMARK)) + pythonhome = prefix; + else + pythonhome = NULL; + } + else + strncpy(prefix, pythonhome, MAXPATHLEN); + + if (envpath && *envpath == '\0') + envpath = NULL; + + /* Calculate zip archive path */ + strncpy(zip_path, progpath, MAXPATHLEN); + zip_path[MAXPATHLEN] = '\0'; + len = strlen(zip_path); + if (len > 4) { + zip_path[len-3] = 'z'; /* change ending to "zip" */ + zip_path[len-2] = 'i'; + zip_path[len-1] = 'p'; + } + else { + zip_path[0] = 0; + } + + /* We need to construct a path from the following parts. + * (1) the PYTHONPATH environment variable, if set; + * (2) the zip archive file path; + * (3) the PYTHONPATH config macro, with the leading "." + * of each component replaced with pythonhome, if set; + * (4) the directory containing the executable (argv0_path). + * The length calculation calculates #3 first. + */ + + /* Calculate size of return buffer */ + if (pythonhome != NULL) { + char *p; + bufsz = 1; + for (p = PYTHONPATH; *p; p++) { + if (*p == DELIM) + bufsz++; /* number of DELIM plus one */ + } + bufsz *= strlen(pythonhome); + } + else + bufsz = 0; + bufsz += strlen(PYTHONPATH) + 1; + bufsz += strlen(argv0_path) + 1; + bufsz += strlen(zip_path) + 1; + if (envpath != NULL) + bufsz += strlen(envpath) + 1; + + module_search_path = buf = malloc(bufsz); + if (buf == NULL) { + /* We can't exit, so print a warning and limp along */ + fprintf(stderr, "Can't malloc dynamic PYTHONPATH.\n"); + if (envpath) { + fprintf(stderr, "Using environment $PYTHONPATH.\n"); + module_search_path = envpath; + } + else { + fprintf(stderr, "Using default static path.\n"); + module_search_path = PYTHONPATH; + } + return; + } + + if (envpath) { + strcpy(buf, envpath); + buf = strchr(buf, '\0'); + *buf++ = DELIM; + } + if (zip_path[0]) { + strcpy(buf, zip_path); + buf = strchr(buf, '\0'); + *buf++ = DELIM; + } + + if (pythonhome == NULL) { + strcpy(buf, PYTHONPATH); + buf = strchr(buf, '\0'); + } + else { + char *p = PYTHONPATH; + char *q; + size_t n; + for (;;) { + q = strchr(p, DELIM); + if (q == NULL) + n = strlen(p); + else + n = q-p; + if (p[0] == '.' && is_sep(p[1])) { + strcpy(buf, pythonhome); + buf = strchr(buf, '\0'); + p++; + n--; + } + strncpy(buf, p, n); + buf += n; + if (q == NULL) + break; + *buf++ = DELIM; + p = q+1; + } + } + if (argv0_path) { + *buf++ = DELIM; + strcpy(buf, argv0_path); + buf = strchr(buf, '\0'); + } + *buf = '\0'; } @@ -390,29 +390,29 @@ char * Py_GetPath(void) { - if (!module_search_path) - calculate_path(); - return module_search_path; + if (!module_search_path) + calculate_path(); + return module_search_path; } char * Py_GetPrefix(void) { - if (!module_search_path) - calculate_path(); - return prefix; + if (!module_search_path) + calculate_path(); + return prefix; } char * Py_GetExecPrefix(void) { - return Py_GetPrefix(); + return Py_GetPrefix(); } char * Py_GetProgramFullPath(void) { - if (!module_search_path) - calculate_path(); - return progpath; + if (!module_search_path) + calculate_path(); + return progpath; } Modified: python/branches/release31-maint/PC/os2emx/pythonpm.c ============================================================================== --- python/branches/release31-maint/PC/os2emx/pythonpm.c (original) +++ python/branches/release31-maint/PC/os2emx/pythonpm.c Sun May 9 18:14:21 2010 @@ -27,10 +27,10 @@ /* use structure to pass command line to Python thread */ typedef struct { - int argc; - char **argv; - HWND Frame; - int running; + int argc; + char **argv; + HWND Frame; + int running; } arglist; /* make this a global to simplify access. @@ -45,80 +45,80 @@ int main(int argc, char **argv) { - ULONG FrameFlags = FCF_TITLEBAR | - FCF_SYSMENU | - FCF_SIZEBORDER | - FCF_HIDEBUTTON | - FCF_SHELLPOSITION | - FCF_TASKLIST; - HAB hab; - HMQ hmq; - HWND Client; - QMSG qmsg; - arglist args; - int python_tid; - - /* init PM and create message queue */ - hab = WinInitialize(0); - hmq = WinCreateMsgQueue(hab, 0); - - /* create a (hidden) Window to house the window procedure */ - args.Frame = WinCreateStdWindow(HWND_DESKTOP, - 0, - &FrameFlags, - NULL, - "PythonPM", - 0L, - 0, - 0, - &Client); - - /* run Python interpreter in a thread */ - args.argc = argc; - args.argv = argv; - args.running = 0; - if (-1 == (python_tid = _beginthread(PythonThread, NULL, 1024 * 1024, &args))) - { - /* couldn't start thread */ - WinAlarm(HWND_DESKTOP, WA_ERROR); - PythonRC = 1; - } - else - { - /* process PM messages, until Python exits */ - while (WinGetMsg(hab, &qmsg, NULLHANDLE, 0, 0)) - WinDispatchMsg(hab, &qmsg); - if (args.running > 0) - DosKillThread(python_tid); - } - - /* destroy window, shutdown message queue and PM */ - WinDestroyWindow(args.Frame); - WinDestroyMsgQueue(hmq); - WinTerminate(hab); + ULONG FrameFlags = FCF_TITLEBAR | + FCF_SYSMENU | + FCF_SIZEBORDER | + FCF_HIDEBUTTON | + FCF_SHELLPOSITION | + FCF_TASKLIST; + HAB hab; + HMQ hmq; + HWND Client; + QMSG qmsg; + arglist args; + int python_tid; + + /* init PM and create message queue */ + hab = WinInitialize(0); + hmq = WinCreateMsgQueue(hab, 0); + + /* create a (hidden) Window to house the window procedure */ + args.Frame = WinCreateStdWindow(HWND_DESKTOP, + 0, + &FrameFlags, + NULL, + "PythonPM", + 0L, + 0, + 0, + &Client); + + /* run Python interpreter in a thread */ + args.argc = argc; + args.argv = argv; + args.running = 0; + if (-1 == (python_tid = _beginthread(PythonThread, NULL, 1024 * 1024, &args))) + { + /* couldn't start thread */ + WinAlarm(HWND_DESKTOP, WA_ERROR); + PythonRC = 1; + } + else + { + /* process PM messages, until Python exits */ + while (WinGetMsg(hab, &qmsg, NULLHANDLE, 0, 0)) + WinDispatchMsg(hab, &qmsg); + if (args.running > 0) + DosKillThread(python_tid); + } + + /* destroy window, shutdown message queue and PM */ + WinDestroyWindow(args.Frame); + WinDestroyMsgQueue(hmq); + WinTerminate(hab); - return PythonRC; + return PythonRC; } void PythonThread(void *argl) { - HAB hab; - arglist *args; + HAB hab; + arglist *args; - /* PM initialisation */ - hab = WinInitialize(0); + /* PM initialisation */ + hab = WinInitialize(0); - /* start Python */ - args = (arglist *)argl; - args->running = 1; - PythonRC = Py_Main(args->argc, args->argv); - - /* enter a critical section and send the termination message */ - DosEnterCritSec(); - args->running = 0; - WinPostMsg(args->Frame, WM_QUIT, NULL, NULL); - - /* shutdown PM and terminate thread */ - WinTerminate(hab); - _endthread(); + /* start Python */ + args = (arglist *)argl; + args->running = 1; + PythonRC = Py_Main(args->argc, args->argv); + + /* enter a critical section and send the termination message */ + DosEnterCritSec(); + args->running = 0; + WinPostMsg(args->Frame, WM_QUIT, NULL, NULL); + + /* shutdown PM and terminate thread */ + WinTerminate(hab); + _endthread(); } Modified: python/branches/release31-maint/PC/os2vacpp/getpathp.c ============================================================================== --- python/branches/release31-maint/PC/os2vacpp/getpathp.c (original) +++ python/branches/release31-maint/PC/os2vacpp/getpathp.c Sun May 9 18:14:21 2010 @@ -55,12 +55,12 @@ static int -is_sep(char ch) /* determine if "ch" is a separator character */ +is_sep(char ch) /* determine if "ch" is a separator character */ { #ifdef ALTSEP - return ch == SEP || ch == ALTSEP; + return ch == SEP || ch == ALTSEP; #else - return ch == SEP; + return ch == SEP; #endif } @@ -68,18 +68,18 @@ static void reduce(char *dir) { - int i = strlen(dir); - while (i > 0 && !is_sep(dir[i])) - --i; - dir[i] = '\0'; + int i = strlen(dir); + while (i > 0 && !is_sep(dir[i])) + --i; + dir[i] = '\0'; } - + static int exists(char *filename) { - struct stat buf; - return stat(filename, &buf) == 0; + struct stat buf; + return stat(filename, &buf) == 0; } @@ -95,42 +95,42 @@ static void join(char *buffer, char *stuff) { - int n, k; - if (is_sep(stuff[0])) - n = 0; - else { - n = strlen(buffer); - if (n > 0 && !is_sep(buffer[n-1]) && n < MAXPATHLEN) - buffer[n++] = SEP; - } - if (n > MAXPATHLEN) - Py_FatalError("buffer overflow in getpathp.c's joinpath()"); - k = strlen(stuff); - if (n + k > MAXPATHLEN) - k = MAXPATHLEN - n; - strncpy(buffer+n, stuff, k); - buffer[n+k] = '\0'; + int n, k; + if (is_sep(stuff[0])) + n = 0; + else { + n = strlen(buffer); + if (n > 0 && !is_sep(buffer[n-1]) && n < MAXPATHLEN) + buffer[n++] = SEP; + } + if (n > MAXPATHLEN) + Py_FatalError("buffer overflow in getpathp.c's joinpath()"); + k = strlen(stuff); + if (n + k > MAXPATHLEN) + k = MAXPATHLEN - n; + strncpy(buffer+n, stuff, k); + buffer[n+k] = '\0'; } static int search_for_prefix(char *argv0_path, char *landmark) { - int n; + int n; - /* Search from argv0_path, until root is found */ - strcpy(prefix, argv0_path); - do { - n = strlen(prefix); - join(prefix, landmark); - if (exists(prefix)) { - prefix[n] = '\0'; - return 1; - } - prefix[n] = '\0'; - reduce(prefix); - } while (prefix[0]); - return 0; + /* Search from argv0_path, until root is found */ + strcpy(prefix, argv0_path); + do { + n = strlen(prefix); + join(prefix, landmark); + if (exists(prefix)) { + prefix[n] = '\0'; + return 1; + } + prefix[n] = '\0'; + reduce(prefix); + } while (prefix[0]); + return 0; } #ifdef MS_WIN32 @@ -147,299 +147,299 @@ static char * getpythonregpath(HKEY keyBase, BOOL bWin32s) { - HKEY newKey = 0; - DWORD nameSize = 0; - DWORD dataSize = 0; - DWORD numEntries = 0; - LONG rc; - char *retval = NULL; - char *dataBuf; - const char keyPrefix[] = "Software\\Python\\PythonCore\\"; - const char keySuffix[] = "\\PythonPath"; - int versionLen; - char *keyBuf; - - // Tried to use sysget("winver") but here is too early :-( - versionLen = strlen(PyWin_DLLVersionString); - // alloca == no free required, but memory only local to fn. - // also no heap fragmentation! Am I being silly? - keyBuf = alloca(sizeof(keyPrefix)-1 + versionLen + sizeof(keySuffix)); // chars only, plus 1 NULL. - // lots of constants here for the compiler to optimize away :-) - memcpy(keyBuf, keyPrefix, sizeof(keyPrefix)-1); - memcpy(keyBuf+sizeof(keyPrefix)-1, PyWin_DLLVersionString, versionLen); - memcpy(keyBuf+sizeof(keyPrefix)-1+versionLen, keySuffix, sizeof(keySuffix)); // NULL comes with this one! - - rc=RegOpenKey(keyBase, - keyBuf, - &newKey); - if (rc==ERROR_SUCCESS) { - RegQueryInfoKey(newKey, NULL, NULL, NULL, NULL, NULL, NULL, - &numEntries, &nameSize, &dataSize, NULL, NULL); - } - if (bWin32s && numEntries==0 && dataSize==0) { - /* must hardcode for Win32s */ - numEntries = 1; - dataSize = 511; - } - if (numEntries) { - /* Loop over all subkeys. */ - /* Win32s doesnt know how many subkeys, so we do - it twice */ - char keyBuf[MAX_PATH+1]; - int index = 0; - int off = 0; - for(index=0;;index++) { - long reqdSize = 0; - DWORD rc = RegEnumKey(newKey, - index, keyBuf, MAX_PATH+1); - if (rc) break; - rc = RegQueryValue(newKey, keyBuf, NULL, &reqdSize); - if (rc) break; - if (bWin32s && reqdSize==0) reqdSize = 512; - dataSize += reqdSize + 1; /* 1 for the ";" */ - } - dataBuf = malloc(dataSize+1); - if (dataBuf==NULL) - return NULL; /* pretty serious? Raise error? */ - /* Now loop over, grabbing the paths. - Subkeys before main library */ - for(index=0;;index++) { - int adjust; - long reqdSize = dataSize; - DWORD rc = RegEnumKey(newKey, - index, keyBuf,MAX_PATH+1); - if (rc) break; - rc = RegQueryValue(newKey, - keyBuf, dataBuf+off, &reqdSize); - if (rc) break; - if (reqdSize>1) { - /* If Nothing, or only '\0' copied. */ - adjust = strlen(dataBuf+off); - dataSize -= adjust; - off += adjust; - dataBuf[off++] = ';'; - dataBuf[off] = '\0'; - dataSize--; - } - } - /* Additionally, win32s doesnt work as expected, so - the specific strlen() is required for 3.1. */ - rc = RegQueryValue(newKey, "", dataBuf+off, &dataSize); - if (rc==ERROR_SUCCESS) { - if (strlen(dataBuf)==0) - free(dataBuf); - else - retval = dataBuf; /* caller will free */ - } - else - free(dataBuf); - } - - if (newKey) - RegCloseKey(newKey); - return retval; + HKEY newKey = 0; + DWORD nameSize = 0; + DWORD dataSize = 0; + DWORD numEntries = 0; + LONG rc; + char *retval = NULL; + char *dataBuf; + const char keyPrefix[] = "Software\\Python\\PythonCore\\"; + const char keySuffix[] = "\\PythonPath"; + int versionLen; + char *keyBuf; + + // Tried to use sysget("winver") but here is too early :-( + versionLen = strlen(PyWin_DLLVersionString); + // alloca == no free required, but memory only local to fn. + // also no heap fragmentation! Am I being silly? + keyBuf = alloca(sizeof(keyPrefix)-1 + versionLen + sizeof(keySuffix)); // chars only, plus 1 NULL. + // lots of constants here for the compiler to optimize away :-) + memcpy(keyBuf, keyPrefix, sizeof(keyPrefix)-1); + memcpy(keyBuf+sizeof(keyPrefix)-1, PyWin_DLLVersionString, versionLen); + memcpy(keyBuf+sizeof(keyPrefix)-1+versionLen, keySuffix, sizeof(keySuffix)); // NULL comes with this one! + + rc=RegOpenKey(keyBase, + keyBuf, + &newKey); + if (rc==ERROR_SUCCESS) { + RegQueryInfoKey(newKey, NULL, NULL, NULL, NULL, NULL, NULL, + &numEntries, &nameSize, &dataSize, NULL, NULL); + } + if (bWin32s && numEntries==0 && dataSize==0) { + /* must hardcode for Win32s */ + numEntries = 1; + dataSize = 511; + } + if (numEntries) { + /* Loop over all subkeys. */ + /* Win32s doesnt know how many subkeys, so we do + it twice */ + char keyBuf[MAX_PATH+1]; + int index = 0; + int off = 0; + for(index=0;;index++) { + long reqdSize = 0; + DWORD rc = RegEnumKey(newKey, + index, keyBuf, MAX_PATH+1); + if (rc) break; + rc = RegQueryValue(newKey, keyBuf, NULL, &reqdSize); + if (rc) break; + if (bWin32s && reqdSize==0) reqdSize = 512; + dataSize += reqdSize + 1; /* 1 for the ";" */ + } + dataBuf = malloc(dataSize+1); + if (dataBuf==NULL) + return NULL; /* pretty serious? Raise error? */ + /* Now loop over, grabbing the paths. + Subkeys before main library */ + for(index=0;;index++) { + int adjust; + long reqdSize = dataSize; + DWORD rc = RegEnumKey(newKey, + index, keyBuf,MAX_PATH+1); + if (rc) break; + rc = RegQueryValue(newKey, + keyBuf, dataBuf+off, &reqdSize); + if (rc) break; + if (reqdSize>1) { + /* If Nothing, or only '\0' copied. */ + adjust = strlen(dataBuf+off); + dataSize -= adjust; + off += adjust; + dataBuf[off++] = ';'; + dataBuf[off] = '\0'; + dataSize--; + } + } + /* Additionally, win32s doesnt work as expected, so + the specific strlen() is required for 3.1. */ + rc = RegQueryValue(newKey, "", dataBuf+off, &dataSize); + if (rc==ERROR_SUCCESS) { + if (strlen(dataBuf)==0) + free(dataBuf); + else + retval = dataBuf; /* caller will free */ + } + else + free(dataBuf); + } + + if (newKey) + RegCloseKey(newKey); + return retval; } #endif /* MS_WIN32 */ static void get_progpath(void) { - extern char *Py_GetProgramName(void); - char *path = getenv("PATH"); - char *prog = Py_GetProgramName(); + extern char *Py_GetProgramName(void); + char *path = getenv("PATH"); + char *prog = Py_GetProgramName(); #ifdef MS_WIN32 - if (GetModuleFileName(NULL, progpath, MAXPATHLEN)) - return; + if (GetModuleFileName(NULL, progpath, MAXPATHLEN)) + return; #endif - if (prog == NULL || *prog == '\0') - prog = "python"; + if (prog == NULL || *prog == '\0') + prog = "python"; - /* If there is no slash in the argv0 path, then we have to - * assume python is on the user's $PATH, since there's no - * other way to find a directory to start the search from. If - * $PATH isn't exported, you lose. - */ + /* If there is no slash in the argv0 path, then we have to + * assume python is on the user's $PATH, since there's no + * other way to find a directory to start the search from. If + * $PATH isn't exported, you lose. + */ #ifdef ALTSEP - if (strchr(prog, SEP) || strchr(prog, ALTSEP)) + if (strchr(prog, SEP) || strchr(prog, ALTSEP)) #else - if (strchr(prog, SEP)) + if (strchr(prog, SEP)) #endif - strcpy(progpath, prog); - else if (path) { - while (1) { - char *delim = strchr(path, DELIM); - - if (delim) { - int len = delim - path; - strncpy(progpath, path, len); - *(progpath + len) = '\0'; - } - else - strcpy(progpath, path); - - join(progpath, prog); - if (exists(progpath)) - break; - - if (!delim) { - progpath[0] = '\0'; - break; - } - path = delim + 1; - } - } - else - progpath[0] = '\0'; + strcpy(progpath, prog); + else if (path) { + while (1) { + char *delim = strchr(path, DELIM); + + if (delim) { + int len = delim - path; + strncpy(progpath, path, len); + *(progpath + len) = '\0'; + } + else + strcpy(progpath, path); + + join(progpath, prog); + if (exists(progpath)) + break; + + if (!delim) { + progpath[0] = '\0'; + break; + } + path = delim + 1; + } + } + else + progpath[0] = '\0'; } static void calculate_path(void) { - char argv0_path[MAXPATHLEN+1]; - char *buf; - int bufsz; - char *pythonhome = Py_GetPythonHome(); - char *envpath = Py_GETENV("PYTHONPATH"); + char argv0_path[MAXPATHLEN+1]; + char *buf; + int bufsz; + char *pythonhome = Py_GetPythonHome(); + char *envpath = Py_GETENV("PYTHONPATH"); #ifdef MS_WIN32 - char *machinepath, *userpath; + char *machinepath, *userpath; - /* Are we running under Windows 3.1(1) Win32s? */ - if (PyWin_IsWin32s()) { - /* Only CLASSES_ROOT is supported */ - machinepath = getpythonregpath(HKEY_CLASSES_ROOT, TRUE); - userpath = NULL; - } else { - machinepath = getpythonregpath(HKEY_LOCAL_MACHINE, FALSE); - userpath = getpythonregpath(HKEY_CURRENT_USER, FALSE); - } + /* Are we running under Windows 3.1(1) Win32s? */ + if (PyWin_IsWin32s()) { + /* Only CLASSES_ROOT is supported */ + machinepath = getpythonregpath(HKEY_CLASSES_ROOT, TRUE); + userpath = NULL; + } else { + machinepath = getpythonregpath(HKEY_LOCAL_MACHINE, FALSE); + userpath = getpythonregpath(HKEY_CURRENT_USER, FALSE); + } #endif - get_progpath(); - strcpy(argv0_path, progpath); - reduce(argv0_path); - if (pythonhome == NULL || *pythonhome == '\0') { - if (search_for_prefix(argv0_path, LANDMARK)) - pythonhome = prefix; - else - pythonhome = NULL; - } - else { - char *delim; - - strcpy(prefix, pythonhome); - - /* Extract Any Optional Trailing EXEC_PREFIX */ - /* e.g. PYTHONHOME=: */ - delim = strchr(prefix, DELIM); - if (delim) { - *delim = '\0'; - strcpy(exec_prefix, delim+1); - } else - strcpy(exec_prefix, EXEC_PREFIX); - } - - if (envpath && *envpath == '\0') - envpath = NULL; - - /* We need to construct a path from the following parts: - (1) the PYTHONPATH environment variable, if set; - (2) for Win32, the machinepath and userpath, if set; - (3) the PYTHONPATH config macro, with the leading "." - of each component replaced with pythonhome, if set; - (4) the directory containing the executable (argv0_path). - The length calculation calculates #3 first. - */ - - /* Calculate size of return buffer */ - if (pythonhome != NULL) { - char *p; - bufsz = 1; - for (p = PYTHONPATH; *p; p++) { - if (*p == DELIM) - bufsz++; /* number of DELIM plus one */ - } - bufsz *= strlen(pythonhome); - } - else - bufsz = 0; - bufsz += strlen(PYTHONPATH) + 1; - if (envpath != NULL) - bufsz += strlen(envpath) + 1; - bufsz += strlen(argv0_path) + 1; + get_progpath(); + strcpy(argv0_path, progpath); + reduce(argv0_path); + if (pythonhome == NULL || *pythonhome == '\0') { + if (search_for_prefix(argv0_path, LANDMARK)) + pythonhome = prefix; + else + pythonhome = NULL; + } + else { + char *delim; + + strcpy(prefix, pythonhome); + + /* Extract Any Optional Trailing EXEC_PREFIX */ + /* e.g. PYTHONHOME=: */ + delim = strchr(prefix, DELIM); + if (delim) { + *delim = '\0'; + strcpy(exec_prefix, delim+1); + } else + strcpy(exec_prefix, EXEC_PREFIX); + } + + if (envpath && *envpath == '\0') + envpath = NULL; + + /* We need to construct a path from the following parts: + (1) the PYTHONPATH environment variable, if set; + (2) for Win32, the machinepath and userpath, if set; + (3) the PYTHONPATH config macro, with the leading "." + of each component replaced with pythonhome, if set; + (4) the directory containing the executable (argv0_path). + The length calculation calculates #3 first. + */ + + /* Calculate size of return buffer */ + if (pythonhome != NULL) { + char *p; + bufsz = 1; + for (p = PYTHONPATH; *p; p++) { + if (*p == DELIM) + bufsz++; /* number of DELIM plus one */ + } + bufsz *= strlen(pythonhome); + } + else + bufsz = 0; + bufsz += strlen(PYTHONPATH) + 1; + if (envpath != NULL) + bufsz += strlen(envpath) + 1; + bufsz += strlen(argv0_path) + 1; #ifdef MS_WIN32 - if (machinepath) - bufsz += strlen(machinepath) + 1; - if (userpath) - bufsz += strlen(userpath) + 1; + if (machinepath) + bufsz += strlen(machinepath) + 1; + if (userpath) + bufsz += strlen(userpath) + 1; #endif - module_search_path = buf = malloc(bufsz); - if (buf == NULL) { - /* We can't exit, so print a warning and limp along */ - fprintf(stderr, "Can't malloc dynamic PYTHONPATH.\n"); - if (envpath) { - fprintf(stderr, "Using default static $PYTHONPATH.\n"); - module_search_path = envpath; - } - else { - fprintf(stderr, "Using environment $PYTHONPATH.\n"); - module_search_path = PYTHONPATH; - } - return; - } - - if (envpath) { - strcpy(buf, envpath); - buf = strchr(buf, '\0'); - *buf++ = DELIM; - } + module_search_path = buf = malloc(bufsz); + if (buf == NULL) { + /* We can't exit, so print a warning and limp along */ + fprintf(stderr, "Can't malloc dynamic PYTHONPATH.\n"); + if (envpath) { + fprintf(stderr, "Using default static $PYTHONPATH.\n"); + module_search_path = envpath; + } + else { + fprintf(stderr, "Using environment $PYTHONPATH.\n"); + module_search_path = PYTHONPATH; + } + return; + } + + if (envpath) { + strcpy(buf, envpath); + buf = strchr(buf, '\0'); + *buf++ = DELIM; + } #ifdef MS_WIN32 - if (machinepath) { - strcpy(buf, machinepath); - buf = strchr(buf, '\0'); - *buf++ = DELIM; - } - if (userpath) { - strcpy(buf, userpath); - buf = strchr(buf, '\0'); - *buf++ = DELIM; - } + if (machinepath) { + strcpy(buf, machinepath); + buf = strchr(buf, '\0'); + *buf++ = DELIM; + } + if (userpath) { + strcpy(buf, userpath); + buf = strchr(buf, '\0'); + *buf++ = DELIM; + } #endif - if (pythonhome == NULL) { - strcpy(buf, PYTHONPATH); - buf = strchr(buf, '\0'); - } - else { - char *p = PYTHONPATH; - char *q; - int n; - for (;;) { - q = strchr(p, DELIM); - if (q == NULL) - n = strlen(p); - else - n = q-p; - if (p[0] == '.' && is_sep(p[1])) { - strcpy(buf, pythonhome); - buf = strchr(buf, '\0'); - p++; - n--; - } - strncpy(buf, p, n); - buf += n; - if (q == NULL) - break; - *buf++ = DELIM; - p = q+1; - } - } - if (argv0_path) { - *buf++ = DELIM; - strcpy(buf, argv0_path); - buf = strchr(buf, '\0'); - } - *buf = '\0'; + if (pythonhome == NULL) { + strcpy(buf, PYTHONPATH); + buf = strchr(buf, '\0'); + } + else { + char *p = PYTHONPATH; + char *q; + int n; + for (;;) { + q = strchr(p, DELIM); + if (q == NULL) + n = strlen(p); + else + n = q-p; + if (p[0] == '.' && is_sep(p[1])) { + strcpy(buf, pythonhome); + buf = strchr(buf, '\0'); + p++; + n--; + } + strncpy(buf, p, n); + buf += n; + if (q == NULL) + break; + *buf++ = DELIM; + p = q+1; + } + } + if (argv0_path) { + *buf++ = DELIM; + strcpy(buf, argv0_path); + buf = strchr(buf, '\0'); + } + *buf = '\0'; } @@ -448,35 +448,35 @@ char * Py_GetPath(void) { - if (!module_search_path) - calculate_path(); + if (!module_search_path) + calculate_path(); - return module_search_path; + return module_search_path; } char * Py_GetPrefix(void) { - if (!module_search_path) - calculate_path(); + if (!module_search_path) + calculate_path(); - return prefix; + return prefix; } char * Py_GetExecPrefix(void) { - if (!module_search_path) - calculate_path(); + if (!module_search_path) + calculate_path(); - return exec_prefix; + return exec_prefix; } char * Py_GetProgramFullPath(void) { - if (!module_search_path) - calculate_path(); + if (!module_search_path) + calculate_path(); - return progpath; + return progpath; } Modified: python/branches/release31-maint/PC/winreg.c ============================================================================== --- python/branches/release31-maint/PC/winreg.c (original) +++ python/branches/release31-maint/PC/winreg.c Sun May 9 18:14:21 2010 @@ -4,7 +4,7 @@ Windows Registry access module for Python. * Simple registry access written by Mark Hammond in win32api - module circa 1995. + module circa 1995. * Bill Tutt expanded the support significantly not long after. * Numerous other people have submitted patches since then. * Ripped from win32api module 03-Feb-2000 by Mark Hammond, and @@ -28,7 +28,7 @@ want to lose this info... */ #define PyErr_SetFromWindowsErrWithFunction(rc, fnname) \ - PyErr_SetFromWindowsErr(rc) + PyErr_SetFromWindowsErr(rc) /* Forward declares */ @@ -353,8 +353,8 @@ ************************************************************************/ typedef struct { - PyObject_VAR_HEAD - HKEY hkey; + PyObject_VAR_HEAD + HKEY hkey; } PyHKEYObject; #define PyHKEY_Check(op) ((op)->ob_type == &PyHKEY_Type) @@ -364,95 +364,95 @@ static PyObject * PyHKEY_unaryFailureFunc(PyObject *ob) { - PyErr_SetString(PyExc_TypeError, failMsg); - return NULL; + PyErr_SetString(PyExc_TypeError, failMsg); + return NULL; } static PyObject * PyHKEY_binaryFailureFunc(PyObject *ob1, PyObject *ob2) { - PyErr_SetString(PyExc_TypeError, failMsg); - return NULL; + PyErr_SetString(PyExc_TypeError, failMsg); + return NULL; } static PyObject * PyHKEY_ternaryFailureFunc(PyObject *ob1, PyObject *ob2, PyObject *ob3) { - PyErr_SetString(PyExc_TypeError, failMsg); - return NULL; + PyErr_SetString(PyExc_TypeError, failMsg); + return NULL; } static void PyHKEY_deallocFunc(PyObject *ob) { - /* Can not call PyHKEY_Close, as the ob->tp_type - has already been cleared, thus causing the type - check to fail! - */ - PyHKEYObject *obkey = (PyHKEYObject *)ob; - if (obkey->hkey) - RegCloseKey((HKEY)obkey->hkey); - PyObject_DEL(ob); + /* Can not call PyHKEY_Close, as the ob->tp_type + has already been cleared, thus causing the type + check to fail! + */ + PyHKEYObject *obkey = (PyHKEYObject *)ob; + if (obkey->hkey) + RegCloseKey((HKEY)obkey->hkey); + PyObject_DEL(ob); } static int PyHKEY_boolFunc(PyObject *ob) { - return ((PyHKEYObject *)ob)->hkey != 0; + return ((PyHKEYObject *)ob)->hkey != 0; } static PyObject * PyHKEY_intFunc(PyObject *ob) { - PyHKEYObject *pyhkey = (PyHKEYObject *)ob; - return PyLong_FromVoidPtr(pyhkey->hkey); + PyHKEYObject *pyhkey = (PyHKEYObject *)ob; + return PyLong_FromVoidPtr(pyhkey->hkey); } static PyObject * PyHKEY_strFunc(PyObject *ob) { - PyHKEYObject *pyhkey = (PyHKEYObject *)ob; - return PyUnicode_FromFormat("", pyhkey->hkey); + PyHKEYObject *pyhkey = (PyHKEYObject *)ob; + return PyUnicode_FromFormat("", pyhkey->hkey); } static int PyHKEY_compareFunc(PyObject *ob1, PyObject *ob2) { - PyHKEYObject *pyhkey1 = (PyHKEYObject *)ob1; - PyHKEYObject *pyhkey2 = (PyHKEYObject *)ob2; - return pyhkey1 == pyhkey2 ? 0 : - (pyhkey1 < pyhkey2 ? -1 : 1); + PyHKEYObject *pyhkey1 = (PyHKEYObject *)ob1; + PyHKEYObject *pyhkey2 = (PyHKEYObject *)ob2; + return pyhkey1 == pyhkey2 ? 0 : + (pyhkey1 < pyhkey2 ? -1 : 1); } static long PyHKEY_hashFunc(PyObject *ob) { - /* Just use the address. - XXX - should we use the handle value? - */ - return _Py_HashPointer(ob); + /* Just use the address. + XXX - should we use the handle value? + */ + return _Py_HashPointer(ob); } static PyNumberMethods PyHKEY_NumberMethods = { - PyHKEY_binaryFailureFunc, /* nb_add */ - PyHKEY_binaryFailureFunc, /* nb_subtract */ - PyHKEY_binaryFailureFunc, /* nb_multiply */ - PyHKEY_binaryFailureFunc, /* nb_remainder */ - PyHKEY_binaryFailureFunc, /* nb_divmod */ - PyHKEY_ternaryFailureFunc, /* nb_power */ - PyHKEY_unaryFailureFunc, /* nb_negative */ - PyHKEY_unaryFailureFunc, /* nb_positive */ - PyHKEY_unaryFailureFunc, /* nb_absolute */ - PyHKEY_boolFunc, /* nb_bool */ - PyHKEY_unaryFailureFunc, /* nb_invert */ - PyHKEY_binaryFailureFunc, /* nb_lshift */ - PyHKEY_binaryFailureFunc, /* nb_rshift */ - PyHKEY_binaryFailureFunc, /* nb_and */ - PyHKEY_binaryFailureFunc, /* nb_xor */ - PyHKEY_binaryFailureFunc, /* nb_or */ - PyHKEY_intFunc, /* nb_int */ - 0, /* nb_reserved */ - PyHKEY_unaryFailureFunc, /* nb_float */ + PyHKEY_binaryFailureFunc, /* nb_add */ + PyHKEY_binaryFailureFunc, /* nb_subtract */ + PyHKEY_binaryFailureFunc, /* nb_multiply */ + PyHKEY_binaryFailureFunc, /* nb_remainder */ + PyHKEY_binaryFailureFunc, /* nb_divmod */ + PyHKEY_ternaryFailureFunc, /* nb_power */ + PyHKEY_unaryFailureFunc, /* nb_negative */ + PyHKEY_unaryFailureFunc, /* nb_positive */ + PyHKEY_unaryFailureFunc, /* nb_absolute */ + PyHKEY_boolFunc, /* nb_bool */ + PyHKEY_unaryFailureFunc, /* nb_invert */ + PyHKEY_binaryFailureFunc, /* nb_lshift */ + PyHKEY_binaryFailureFunc, /* nb_rshift */ + PyHKEY_binaryFailureFunc, /* nb_and */ + PyHKEY_binaryFailureFunc, /* nb_xor */ + PyHKEY_binaryFailureFunc, /* nb_or */ + PyHKEY_intFunc, /* nb_int */ + 0, /* nb_reserved */ + PyHKEY_unaryFailureFunc, /* nb_float */ }; static PyObject *PyHKEY_CloseMethod(PyObject *self, PyObject *args); @@ -461,51 +461,51 @@ static PyObject *PyHKEY_Exit(PyObject *self, PyObject *args); static struct PyMethodDef PyHKEY_methods[] = { - {"Close", PyHKEY_CloseMethod, METH_VARARGS, PyHKEY_Close_doc}, - {"Detach", PyHKEY_DetachMethod, METH_VARARGS, PyHKEY_Detach_doc}, - {"__enter__", (PyCFunction)PyHKEY_Enter, METH_NOARGS, NULL}, - {"__exit__", PyHKEY_Exit, METH_VARARGS, NULL}, - {NULL} + {"Close", PyHKEY_CloseMethod, METH_VARARGS, PyHKEY_Close_doc}, + {"Detach", PyHKEY_DetachMethod, METH_VARARGS, PyHKEY_Detach_doc}, + {"__enter__", (PyCFunction)PyHKEY_Enter, METH_NOARGS, NULL}, + {"__exit__", PyHKEY_Exit, METH_VARARGS, NULL}, + {NULL} }; #define OFF(e) offsetof(PyHKEYObject, e) static PyMemberDef PyHKEY_memberlist[] = { - {"handle", T_INT, OFF(hkey), READONLY}, - {NULL} /* Sentinel */ + {"handle", T_INT, OFF(hkey), READONLY}, + {NULL} /* Sentinel */ }; /* The type itself */ PyTypeObject PyHKEY_Type = { - PyVarObject_HEAD_INIT(0, 0) /* fill in type at module init */ - "PyHKEY", - sizeof(PyHKEYObject), - 0, - PyHKEY_deallocFunc, /* tp_dealloc */ - 0, /* tp_print */ - 0, /* tp_getattr */ - 0, /* tp_setattr */ - 0, /* tp_reserved */ - 0, /* tp_repr */ - &PyHKEY_NumberMethods, /* tp_as_number */ - 0, /* tp_as_sequence */ - 0, /* tp_as_mapping */ - PyHKEY_hashFunc, /* tp_hash */ - 0, /* tp_call */ - PyHKEY_strFunc, /* tp_str */ - 0, /* tp_getattro */ - 0, /* tp_setattro */ - 0, /* tp_as_buffer */ - 0, /* tp_flags */ - PyHKEY_doc, /* tp_doc */ - 0, /*tp_traverse*/ - 0, /*tp_clear*/ - 0, /*tp_richcompare*/ - 0, /*tp_weaklistoffset*/ - 0, /*tp_iter*/ - 0, /*tp_iternext*/ - PyHKEY_methods, /*tp_methods*/ - PyHKEY_memberlist, /*tp_members*/ + PyVarObject_HEAD_INIT(0, 0) /* fill in type at module init */ + "PyHKEY", + sizeof(PyHKEYObject), + 0, + PyHKEY_deallocFunc, /* tp_dealloc */ + 0, /* tp_print */ + 0, /* tp_getattr */ + 0, /* tp_setattr */ + 0, /* tp_reserved */ + 0, /* tp_repr */ + &PyHKEY_NumberMethods, /* tp_as_number */ + 0, /* tp_as_sequence */ + 0, /* tp_as_mapping */ + PyHKEY_hashFunc, /* tp_hash */ + 0, /* tp_call */ + PyHKEY_strFunc, /* tp_str */ + 0, /* tp_getattro */ + 0, /* tp_setattro */ + 0, /* tp_as_buffer */ + 0, /* tp_flags */ + PyHKEY_doc, /* tp_doc */ + 0, /*tp_traverse*/ + 0, /*tp_clear*/ + 0, /*tp_richcompare*/ + 0, /*tp_weaklistoffset*/ + 0, /*tp_iter*/ + 0, /*tp_iternext*/ + PyHKEY_methods, /*tp_methods*/ + PyHKEY_memberlist, /*tp_members*/ }; /************************************************************************ @@ -516,39 +516,39 @@ static PyObject * PyHKEY_CloseMethod(PyObject *self, PyObject *args) { - if (!PyArg_ParseTuple(args, ":Close")) - return NULL; - if (!PyHKEY_Close(self)) - return NULL; - Py_INCREF(Py_None); - return Py_None; + if (!PyArg_ParseTuple(args, ":Close")) + return NULL; + if (!PyHKEY_Close(self)) + return NULL; + Py_INCREF(Py_None); + return Py_None; } static PyObject * PyHKEY_DetachMethod(PyObject *self, PyObject *args) { - void* ret; - PyHKEYObject *pThis = (PyHKEYObject *)self; - if (!PyArg_ParseTuple(args, ":Detach")) - return NULL; - ret = (void*)pThis->hkey; - pThis->hkey = 0; - return PyLong_FromVoidPtr(ret); + void* ret; + PyHKEYObject *pThis = (PyHKEYObject *)self; + if (!PyArg_ParseTuple(args, ":Detach")) + return NULL; + ret = (void*)pThis->hkey; + pThis->hkey = 0; + return PyLong_FromVoidPtr(ret); } static PyObject * PyHKEY_Enter(PyObject *self) { - Py_XINCREF(self); - return self; + Py_XINCREF(self); + return self; } static PyObject * PyHKEY_Exit(PyObject *self, PyObject *args) { - if (!PyHKEY_Close(self)) - return NULL; - Py_RETURN_NONE; + if (!PyHKEY_Close(self)) + return NULL; + Py_RETURN_NONE; } @@ -558,74 +558,74 @@ PyObject * PyHKEY_New(HKEY hInit) { - PyHKEYObject *key = PyObject_NEW(PyHKEYObject, &PyHKEY_Type); - if (key) - key->hkey = hInit; - return (PyObject *)key; + PyHKEYObject *key = PyObject_NEW(PyHKEYObject, &PyHKEY_Type); + if (key) + key->hkey = hInit; + return (PyObject *)key; } BOOL PyHKEY_Close(PyObject *ob_handle) { - LONG rc; - PyHKEYObject *key; + LONG rc; + PyHKEYObject *key; - if (!PyHKEY_Check(ob_handle)) { - PyErr_SetString(PyExc_TypeError, "bad operand type"); - return FALSE; - } - key = (PyHKEYObject *)ob_handle; - rc = key->hkey ? RegCloseKey((HKEY)key->hkey) : ERROR_SUCCESS; - key->hkey = 0; - if (rc != ERROR_SUCCESS) - PyErr_SetFromWindowsErrWithFunction(rc, "RegCloseKey"); - return rc == ERROR_SUCCESS; + if (!PyHKEY_Check(ob_handle)) { + PyErr_SetString(PyExc_TypeError, "bad operand type"); + return FALSE; + } + key = (PyHKEYObject *)ob_handle; + rc = key->hkey ? RegCloseKey((HKEY)key->hkey) : ERROR_SUCCESS; + key->hkey = 0; + if (rc != ERROR_SUCCESS) + PyErr_SetFromWindowsErrWithFunction(rc, "RegCloseKey"); + return rc == ERROR_SUCCESS; } BOOL PyHKEY_AsHKEY(PyObject *ob, HKEY *pHANDLE, BOOL bNoneOK) { - if (ob == Py_None) { - if (!bNoneOK) { - PyErr_SetString( - PyExc_TypeError, - "None is not a valid HKEY in this context"); - return FALSE; - } - *pHANDLE = (HKEY)0; - } - else if (PyHKEY_Check(ob)) { - PyHKEYObject *pH = (PyHKEYObject *)ob; - *pHANDLE = pH->hkey; - } - else if (PyLong_Check(ob)) { - /* We also support integers */ - PyErr_Clear(); - *pHANDLE = (HKEY)PyLong_AsVoidPtr(ob); - if (PyErr_Occurred()) - return FALSE; - } - else { - PyErr_SetString( - PyExc_TypeError, - "The object is not a PyHKEY object"); - return FALSE; - } - return TRUE; + if (ob == Py_None) { + if (!bNoneOK) { + PyErr_SetString( + PyExc_TypeError, + "None is not a valid HKEY in this context"); + return FALSE; + } + *pHANDLE = (HKEY)0; + } + else if (PyHKEY_Check(ob)) { + PyHKEYObject *pH = (PyHKEYObject *)ob; + *pHANDLE = pH->hkey; + } + else if (PyLong_Check(ob)) { + /* We also support integers */ + PyErr_Clear(); + *pHANDLE = (HKEY)PyLong_AsVoidPtr(ob); + if (PyErr_Occurred()) + return FALSE; + } + else { + PyErr_SetString( + PyExc_TypeError, + "The object is not a PyHKEY object"); + return FALSE; + } + return TRUE; } PyObject * PyHKEY_FromHKEY(HKEY h) { - PyHKEYObject *op; + PyHKEYObject *op; - /* Inline PyObject_New */ - op = (PyHKEYObject *) PyObject_MALLOC(sizeof(PyHKEYObject)); - if (op == NULL) - return PyErr_NoMemory(); - PyObject_INIT(op, &PyHKEY_Type); - op->hkey = h; - return (PyObject *)op; + /* Inline PyObject_New */ + op = (PyHKEYObject *) PyObject_MALLOC(sizeof(PyHKEYObject)); + if (op == NULL) + return PyErr_NoMemory(); + PyObject_INIT(op, &PyHKEY_Type); + op->hkey = h; + return (PyObject *)op; } @@ -635,32 +635,32 @@ BOOL PyWinObject_CloseHKEY(PyObject *obHandle) { - BOOL ok; - if (PyHKEY_Check(obHandle)) { - ok = PyHKEY_Close(obHandle); - } + BOOL ok; + if (PyHKEY_Check(obHandle)) { + ok = PyHKEY_Close(obHandle); + } #if SIZEOF_LONG >= SIZEOF_HKEY - else if (PyLong_Check(obHandle)) { - long rc = RegCloseKey((HKEY)PyLong_AsLong(obHandle)); - ok = (rc == ERROR_SUCCESS); - if (!ok) - PyErr_SetFromWindowsErrWithFunction(rc, "RegCloseKey"); - } + else if (PyLong_Check(obHandle)) { + long rc = RegCloseKey((HKEY)PyLong_AsLong(obHandle)); + ok = (rc == ERROR_SUCCESS); + if (!ok) + PyErr_SetFromWindowsErrWithFunction(rc, "RegCloseKey"); + } #else - else if (PyLong_Check(obHandle)) { - long rc = RegCloseKey((HKEY)PyLong_AsVoidPtr(obHandle)); - ok = (rc == ERROR_SUCCESS); - if (!ok) - PyErr_SetFromWindowsErrWithFunction(rc, "RegCloseKey"); - } + else if (PyLong_Check(obHandle)) { + long rc = RegCloseKey((HKEY)PyLong_AsVoidPtr(obHandle)); + ok = (rc == ERROR_SUCCESS); + if (!ok) + PyErr_SetFromWindowsErrWithFunction(rc, "RegCloseKey"); + } #endif - else { - PyErr_SetString( - PyExc_TypeError, - "A handle must be a HKEY object or an integer"); - return FALSE; - } - return ok; + else { + PyErr_SetString( + PyExc_TypeError, + "A handle must be a HKEY object or an integer"); + return FALSE; + } + return ok; } @@ -677,29 +677,29 @@ static void fixupMultiSZ(wchar_t **str, wchar_t *data, int len) { - wchar_t *P; - int i; - wchar_t *Q; - - Q = data + len; - for (P = data, i = 0; P < Q && *P != '\0'; P++, i++) { - str[i] = P; - for(; *P != '\0'; P++) - ; - } + wchar_t *P; + int i; + wchar_t *Q; + + Q = data + len; + for (P = data, i = 0; P < Q && *P != '\0'; P++, i++) { + str[i] = P; + for(; *P != '\0'; P++) + ; + } } static int countStrings(wchar_t *data, int len) { - int strings; - wchar_t *P; - wchar_t *Q = data + len; - - for (P = data, strings = 0; P < Q && *P != '\0'; P++, strings++) - for (; P < Q && *P != '\0'; P++) - ; - return strings; + int strings; + wchar_t *P; + wchar_t *Q = data + len; + + for (P = data, strings = 0; P < Q && *P != '\0'; P++, strings++) + for (; P < Q && *P != '\0'; P++) + ; + return strings; } /* Convert PyObject into Registry data. @@ -707,200 +707,200 @@ static BOOL Py2Reg(PyObject *value, DWORD typ, BYTE **retDataBuf, DWORD *retDataSize) { - Py_ssize_t i,j; - switch (typ) { - case REG_DWORD: - if (value != Py_None && !PyLong_Check(value)) - return FALSE; - *retDataBuf = (BYTE *)PyMem_NEW(DWORD, 1); - if (*retDataBuf==NULL){ - PyErr_NoMemory(); - return FALSE; - } - *retDataSize = sizeof(DWORD); - if (value == Py_None) { - DWORD zero = 0; - memcpy(*retDataBuf, &zero, sizeof(DWORD)); - } - else { - DWORD d = PyLong_AsLong(value); - memcpy(*retDataBuf, &d, sizeof(DWORD)); - } - break; - case REG_SZ: - case REG_EXPAND_SZ: - { - if (value == Py_None) - *retDataSize = 1; - else { - if (!PyUnicode_Check(value)) - return FALSE; - - *retDataSize = 2 + PyUnicode_GET_DATA_SIZE(value); - } - *retDataBuf = (BYTE *)PyMem_NEW(DWORD, *retDataSize); - if (*retDataBuf==NULL){ - PyErr_NoMemory(); - return FALSE; - } - if (value == Py_None) - wcscpy((wchar_t *)*retDataBuf, L""); - else - wcscpy((wchar_t *)*retDataBuf, - PyUnicode_AS_UNICODE(value)); - break; - } - case REG_MULTI_SZ: - { - DWORD size = 0; - wchar_t *P; - - if (value == Py_None) - i = 0; - else { - if (!PyList_Check(value)) - return FALSE; - i = PyList_Size(value); - } - for (j = 0; j < i; j++) - { - PyObject *t; - t = PyList_GET_ITEM(value, j); - if (!PyUnicode_Check(t)) - return FALSE; - size += 2 + PyUnicode_GET_DATA_SIZE(t); - } - - *retDataSize = size + 2; - *retDataBuf = (BYTE *)PyMem_NEW(char, - *retDataSize); - if (*retDataBuf==NULL){ - PyErr_NoMemory(); - return FALSE; - } - P = (wchar_t *)*retDataBuf; - - for (j = 0; j < i; j++) - { - PyObject *t; - t = PyList_GET_ITEM(value, j); - wcscpy(P, PyUnicode_AS_UNICODE(t)); - P += 1 + wcslen( - PyUnicode_AS_UNICODE(t)); - } - /* And doubly-terminate the list... */ - *P = '\0'; - break; - } - case REG_BINARY: - /* ALSO handle ALL unknown data types here. Even if we can't - support it natively, we should handle the bits. */ - default: - if (value == Py_None) - *retDataSize = 0; - else { - Py_buffer view; - - if (!PyObject_CheckBuffer(value)) { - PyErr_Format(PyExc_TypeError, - "Objects of type '%s' can not " - "be used as binary registry values", - value->ob_type->tp_name); - return FALSE; - } - - if (PyObject_GetBuffer(value, &view, PyBUF_SIMPLE) < 0) - return FALSE; - - *retDataBuf = (BYTE *)PyMem_NEW(char, view.len); - if (*retDataBuf==NULL){ - PyBuffer_Release(&view); - PyErr_NoMemory(); - return FALSE; - } - *retDataSize = view.len; - memcpy(*retDataBuf, view.buf, view.len); - PyBuffer_Release(&view); - } - break; - } - return TRUE; + Py_ssize_t i,j; + switch (typ) { + case REG_DWORD: + if (value != Py_None && !PyLong_Check(value)) + return FALSE; + *retDataBuf = (BYTE *)PyMem_NEW(DWORD, 1); + if (*retDataBuf==NULL){ + PyErr_NoMemory(); + return FALSE; + } + *retDataSize = sizeof(DWORD); + if (value == Py_None) { + DWORD zero = 0; + memcpy(*retDataBuf, &zero, sizeof(DWORD)); + } + else { + DWORD d = PyLong_AsLong(value); + memcpy(*retDataBuf, &d, sizeof(DWORD)); + } + break; + case REG_SZ: + case REG_EXPAND_SZ: + { + if (value == Py_None) + *retDataSize = 1; + else { + if (!PyUnicode_Check(value)) + return FALSE; + + *retDataSize = 2 + PyUnicode_GET_DATA_SIZE(value); + } + *retDataBuf = (BYTE *)PyMem_NEW(DWORD, *retDataSize); + if (*retDataBuf==NULL){ + PyErr_NoMemory(); + return FALSE; + } + if (value == Py_None) + wcscpy((wchar_t *)*retDataBuf, L""); + else + wcscpy((wchar_t *)*retDataBuf, + PyUnicode_AS_UNICODE(value)); + break; + } + case REG_MULTI_SZ: + { + DWORD size = 0; + wchar_t *P; + + if (value == Py_None) + i = 0; + else { + if (!PyList_Check(value)) + return FALSE; + i = PyList_Size(value); + } + for (j = 0; j < i; j++) + { + PyObject *t; + t = PyList_GET_ITEM(value, j); + if (!PyUnicode_Check(t)) + return FALSE; + size += 2 + PyUnicode_GET_DATA_SIZE(t); + } + + *retDataSize = size + 2; + *retDataBuf = (BYTE *)PyMem_NEW(char, + *retDataSize); + if (*retDataBuf==NULL){ + PyErr_NoMemory(); + return FALSE; + } + P = (wchar_t *)*retDataBuf; + + for (j = 0; j < i; j++) + { + PyObject *t; + t = PyList_GET_ITEM(value, j); + wcscpy(P, PyUnicode_AS_UNICODE(t)); + P += 1 + wcslen( + PyUnicode_AS_UNICODE(t)); + } + /* And doubly-terminate the list... */ + *P = '\0'; + break; + } + case REG_BINARY: + /* ALSO handle ALL unknown data types here. Even if we can't + support it natively, we should handle the bits. */ + default: + if (value == Py_None) + *retDataSize = 0; + else { + Py_buffer view; + + if (!PyObject_CheckBuffer(value)) { + PyErr_Format(PyExc_TypeError, + "Objects of type '%s' can not " + "be used as binary registry values", + value->ob_type->tp_name); + return FALSE; + } + + if (PyObject_GetBuffer(value, &view, PyBUF_SIMPLE) < 0) + return FALSE; + + *retDataBuf = (BYTE *)PyMem_NEW(char, view.len); + if (*retDataBuf==NULL){ + PyBuffer_Release(&view); + PyErr_NoMemory(); + return FALSE; + } + *retDataSize = view.len; + memcpy(*retDataBuf, view.buf, view.len); + PyBuffer_Release(&view); + } + break; + } + return TRUE; } /* Convert Registry data into PyObject*/ static PyObject * Reg2Py(BYTE *retDataBuf, DWORD retDataSize, DWORD typ) { - PyObject *obData; + PyObject *obData; - switch (typ) { - case REG_DWORD: - if (retDataSize == 0) - obData = PyLong_FromLong(0); - else - obData = PyLong_FromLong(*(int *)retDataBuf); - break; - case REG_SZ: - case REG_EXPAND_SZ: - { - /* the buffer may or may not have a trailing NULL */ - wchar_t *data = (wchar_t *)retDataBuf; - int len = retDataSize / 2; - if (retDataSize && data[len-1] == '\0') - retDataSize -= 2; - if (retDataSize <= 0) - data = L""; - obData = PyUnicode_FromUnicode(data, retDataSize/2); - break; - } - case REG_MULTI_SZ: - if (retDataSize == 0) - obData = PyList_New(0); - else - { - int index = 0; - wchar_t *data = (wchar_t *)retDataBuf; - int len = retDataSize / 2; - int s = countStrings(data, len); - wchar_t **str = (wchar_t **)malloc(sizeof(wchar_t *)*s); - if (str == NULL) - return PyErr_NoMemory(); - - fixupMultiSZ(str, data, len); - obData = PyList_New(s); - if (obData == NULL) - return NULL; - for (index = 0; index < s; index++) - { - size_t len = wcslen(str[index]); - if (len > INT_MAX) { - PyErr_SetString(PyExc_OverflowError, - "registry string is too long for a Python string"); - Py_DECREF(obData); - return NULL; - } - PyList_SetItem(obData, - index, - PyUnicode_FromUnicode(str[index], len)); - } - free(str); - - break; - } - case REG_BINARY: - /* ALSO handle ALL unknown data types here. Even if we can't - support it natively, we should handle the bits. */ - default: - if (retDataSize == 0) { - Py_INCREF(Py_None); - obData = Py_None; - } - else - obData = PyBytes_FromStringAndSize( - (char *)retDataBuf, retDataSize); - break; - } - return obData; + switch (typ) { + case REG_DWORD: + if (retDataSize == 0) + obData = PyLong_FromLong(0); + else + obData = PyLong_FromLong(*(int *)retDataBuf); + break; + case REG_SZ: + case REG_EXPAND_SZ: + { + /* the buffer may or may not have a trailing NULL */ + wchar_t *data = (wchar_t *)retDataBuf; + int len = retDataSize / 2; + if (retDataSize && data[len-1] == '\0') + retDataSize -= 2; + if (retDataSize <= 0) + data = L""; + obData = PyUnicode_FromUnicode(data, retDataSize/2); + break; + } + case REG_MULTI_SZ: + if (retDataSize == 0) + obData = PyList_New(0); + else + { + int index = 0; + wchar_t *data = (wchar_t *)retDataBuf; + int len = retDataSize / 2; + int s = countStrings(data, len); + wchar_t **str = (wchar_t **)malloc(sizeof(wchar_t *)*s); + if (str == NULL) + return PyErr_NoMemory(); + + fixupMultiSZ(str, data, len); + obData = PyList_New(s); + if (obData == NULL) + return NULL; + for (index = 0; index < s; index++) + { + size_t len = wcslen(str[index]); + if (len > INT_MAX) { + PyErr_SetString(PyExc_OverflowError, + "registry string is too long for a Python string"); + Py_DECREF(obData); + return NULL; + } + PyList_SetItem(obData, + index, + PyUnicode_FromUnicode(str[index], len)); + } + free(str); + + break; + } + case REG_BINARY: + /* ALSO handle ALL unknown data types here. Even if we can't + support it natively, we should handle the bits. */ + default: + if (retDataSize == 0) { + Py_INCREF(Py_None); + obData = Py_None; + } + else + obData = PyBytes_FromStringAndSize( + (char *)retDataBuf, retDataSize); + break; + } + return obData; } /* The Python methods */ @@ -908,281 +908,281 @@ static PyObject * PyCloseKey(PyObject *self, PyObject *args) { - PyObject *obKey; - if (!PyArg_ParseTuple(args, "O:CloseKey", &obKey)) - return NULL; - if (!PyHKEY_Close(obKey)) - return NULL; - Py_INCREF(Py_None); - return Py_None; + PyObject *obKey; + if (!PyArg_ParseTuple(args, "O:CloseKey", &obKey)) + return NULL; + if (!PyHKEY_Close(obKey)) + return NULL; + Py_INCREF(Py_None); + return Py_None; } static PyObject * PyConnectRegistry(PyObject *self, PyObject *args) { - HKEY hKey; - PyObject *obKey; - wchar_t *szCompName = NULL; - HKEY retKey; - long rc; - if (!PyArg_ParseTuple(args, "ZO:ConnectRegistry", &szCompName, &obKey)) - return NULL; - if (!PyHKEY_AsHKEY(obKey, &hKey, FALSE)) - return NULL; - Py_BEGIN_ALLOW_THREADS - rc = RegConnectRegistryW(szCompName, hKey, &retKey); - Py_END_ALLOW_THREADS - if (rc != ERROR_SUCCESS) - return PyErr_SetFromWindowsErrWithFunction(rc, - "ConnectRegistry"); - return PyHKEY_FromHKEY(retKey); + HKEY hKey; + PyObject *obKey; + wchar_t *szCompName = NULL; + HKEY retKey; + long rc; + if (!PyArg_ParseTuple(args, "ZO:ConnectRegistry", &szCompName, &obKey)) + return NULL; + if (!PyHKEY_AsHKEY(obKey, &hKey, FALSE)) + return NULL; + Py_BEGIN_ALLOW_THREADS + rc = RegConnectRegistryW(szCompName, hKey, &retKey); + Py_END_ALLOW_THREADS + if (rc != ERROR_SUCCESS) + return PyErr_SetFromWindowsErrWithFunction(rc, + "ConnectRegistry"); + return PyHKEY_FromHKEY(retKey); } static PyObject * PyCreateKey(PyObject *self, PyObject *args) { - HKEY hKey; - PyObject *obKey; - wchar_t *subKey; - HKEY retKey; - long rc; - if (!PyArg_ParseTuple(args, "OZ:CreateKey", &obKey, &subKey)) - return NULL; - if (!PyHKEY_AsHKEY(obKey, &hKey, FALSE)) - return NULL; - rc = RegCreateKeyW(hKey, subKey, &retKey); - if (rc != ERROR_SUCCESS) - return PyErr_SetFromWindowsErrWithFunction(rc, "CreateKey"); - return PyHKEY_FromHKEY(retKey); + HKEY hKey; + PyObject *obKey; + wchar_t *subKey; + HKEY retKey; + long rc; + if (!PyArg_ParseTuple(args, "OZ:CreateKey", &obKey, &subKey)) + return NULL; + if (!PyHKEY_AsHKEY(obKey, &hKey, FALSE)) + return NULL; + rc = RegCreateKeyW(hKey, subKey, &retKey); + if (rc != ERROR_SUCCESS) + return PyErr_SetFromWindowsErrWithFunction(rc, "CreateKey"); + return PyHKEY_FromHKEY(retKey); } static PyObject * PyDeleteKey(PyObject *self, PyObject *args) { - HKEY hKey; - PyObject *obKey; - wchar_t *subKey; - long rc; - if (!PyArg_ParseTuple(args, "Ou:DeleteKey", &obKey, &subKey)) - return NULL; - if (!PyHKEY_AsHKEY(obKey, &hKey, FALSE)) - return NULL; - rc = RegDeleteKeyW(hKey, subKey ); - if (rc != ERROR_SUCCESS) - return PyErr_SetFromWindowsErrWithFunction(rc, "RegDeleteKey"); - Py_INCREF(Py_None); - return Py_None; + HKEY hKey; + PyObject *obKey; + wchar_t *subKey; + long rc; + if (!PyArg_ParseTuple(args, "Ou:DeleteKey", &obKey, &subKey)) + return NULL; + if (!PyHKEY_AsHKEY(obKey, &hKey, FALSE)) + return NULL; + rc = RegDeleteKeyW(hKey, subKey ); + if (rc != ERROR_SUCCESS) + return PyErr_SetFromWindowsErrWithFunction(rc, "RegDeleteKey"); + Py_INCREF(Py_None); + return Py_None; } static PyObject * PyDeleteValue(PyObject *self, PyObject *args) { - HKEY hKey; - PyObject *obKey; - wchar_t *subKey; - long rc; - if (!PyArg_ParseTuple(args, "OZ:DeleteValue", &obKey, &subKey)) - return NULL; - if (!PyHKEY_AsHKEY(obKey, &hKey, FALSE)) - return NULL; - Py_BEGIN_ALLOW_THREADS - rc = RegDeleteValueW(hKey, subKey); - Py_END_ALLOW_THREADS - if (rc !=ERROR_SUCCESS) - return PyErr_SetFromWindowsErrWithFunction(rc, - "RegDeleteValue"); - Py_INCREF(Py_None); - return Py_None; + HKEY hKey; + PyObject *obKey; + wchar_t *subKey; + long rc; + if (!PyArg_ParseTuple(args, "OZ:DeleteValue", &obKey, &subKey)) + return NULL; + if (!PyHKEY_AsHKEY(obKey, &hKey, FALSE)) + return NULL; + Py_BEGIN_ALLOW_THREADS + rc = RegDeleteValueW(hKey, subKey); + Py_END_ALLOW_THREADS + if (rc !=ERROR_SUCCESS) + return PyErr_SetFromWindowsErrWithFunction(rc, + "RegDeleteValue"); + Py_INCREF(Py_None); + return Py_None; } static PyObject * PyEnumKey(PyObject *self, PyObject *args) { - HKEY hKey; - PyObject *obKey; - int index; - long rc; - PyObject *retStr; - wchar_t tmpbuf[256]; /* max key name length is 255 */ - DWORD len = sizeof(tmpbuf); /* includes NULL terminator */ - - if (!PyArg_ParseTuple(args, "Oi:EnumKey", &obKey, &index)) - return NULL; - if (!PyHKEY_AsHKEY(obKey, &hKey, FALSE)) - return NULL; - - Py_BEGIN_ALLOW_THREADS - rc = RegEnumKeyExW(hKey, index, tmpbuf, &len, NULL, NULL, NULL, NULL); - Py_END_ALLOW_THREADS - if (rc != ERROR_SUCCESS) - return PyErr_SetFromWindowsErrWithFunction(rc, "RegEnumKeyEx"); + HKEY hKey; + PyObject *obKey; + int index; + long rc; + PyObject *retStr; + wchar_t tmpbuf[256]; /* max key name length is 255 */ + DWORD len = sizeof(tmpbuf); /* includes NULL terminator */ + + if (!PyArg_ParseTuple(args, "Oi:EnumKey", &obKey, &index)) + return NULL; + if (!PyHKEY_AsHKEY(obKey, &hKey, FALSE)) + return NULL; + + Py_BEGIN_ALLOW_THREADS + rc = RegEnumKeyExW(hKey, index, tmpbuf, &len, NULL, NULL, NULL, NULL); + Py_END_ALLOW_THREADS + if (rc != ERROR_SUCCESS) + return PyErr_SetFromWindowsErrWithFunction(rc, "RegEnumKeyEx"); - retStr = PyUnicode_FromUnicode(tmpbuf, len); - return retStr; /* can be NULL */ + retStr = PyUnicode_FromUnicode(tmpbuf, len); + return retStr; /* can be NULL */ } static PyObject * PyEnumValue(PyObject *self, PyObject *args) { - HKEY hKey; - PyObject *obKey; - int index; - long rc; - wchar_t *retValueBuf; - BYTE *retDataBuf; - DWORD retValueSize; - DWORD retDataSize; - DWORD typ; - PyObject *obData; - PyObject *retVal; - - if (!PyArg_ParseTuple(args, "Oi:EnumValue", &obKey, &index)) - return NULL; - if (!PyHKEY_AsHKEY(obKey, &hKey, FALSE)) - return NULL; - - if ((rc = RegQueryInfoKeyW(hKey, NULL, NULL, NULL, NULL, NULL, NULL, - NULL, - &retValueSize, &retDataSize, NULL, NULL)) - != ERROR_SUCCESS) - return PyErr_SetFromWindowsErrWithFunction(rc, - "RegQueryInfoKey"); - ++retValueSize; /* include null terminators */ - ++retDataSize; - retValueBuf = (wchar_t *)PyMem_Malloc(sizeof(wchar_t) * retValueSize); - if (retValueBuf == NULL) - return PyErr_NoMemory(); - retDataBuf = (BYTE *)PyMem_Malloc(retDataSize); - if (retDataBuf == NULL) { - PyMem_Free(retValueBuf); - return PyErr_NoMemory(); - } - - Py_BEGIN_ALLOW_THREADS - rc = RegEnumValueW(hKey, - index, - retValueBuf, - &retValueSize, - NULL, - &typ, - retDataBuf, - &retDataSize); - Py_END_ALLOW_THREADS - - if (rc != ERROR_SUCCESS) { - retVal = PyErr_SetFromWindowsErrWithFunction(rc, - "PyRegEnumValue"); - goto fail; - } - obData = Reg2Py(retDataBuf, retDataSize, typ); - if (obData == NULL) { - retVal = NULL; - goto fail; - } - retVal = Py_BuildValue("uOi", retValueBuf, obData, typ); - Py_DECREF(obData); + HKEY hKey; + PyObject *obKey; + int index; + long rc; + wchar_t *retValueBuf; + BYTE *retDataBuf; + DWORD retValueSize; + DWORD retDataSize; + DWORD typ; + PyObject *obData; + PyObject *retVal; + + if (!PyArg_ParseTuple(args, "Oi:EnumValue", &obKey, &index)) + return NULL; + if (!PyHKEY_AsHKEY(obKey, &hKey, FALSE)) + return NULL; + + if ((rc = RegQueryInfoKeyW(hKey, NULL, NULL, NULL, NULL, NULL, NULL, + NULL, + &retValueSize, &retDataSize, NULL, NULL)) + != ERROR_SUCCESS) + return PyErr_SetFromWindowsErrWithFunction(rc, + "RegQueryInfoKey"); + ++retValueSize; /* include null terminators */ + ++retDataSize; + retValueBuf = (wchar_t *)PyMem_Malloc(sizeof(wchar_t) * retValueSize); + if (retValueBuf == NULL) + return PyErr_NoMemory(); + retDataBuf = (BYTE *)PyMem_Malloc(retDataSize); + if (retDataBuf == NULL) { + PyMem_Free(retValueBuf); + return PyErr_NoMemory(); + } + + Py_BEGIN_ALLOW_THREADS + rc = RegEnumValueW(hKey, + index, + retValueBuf, + &retValueSize, + NULL, + &typ, + retDataBuf, + &retDataSize); + Py_END_ALLOW_THREADS + + if (rc != ERROR_SUCCESS) { + retVal = PyErr_SetFromWindowsErrWithFunction(rc, + "PyRegEnumValue"); + goto fail; + } + obData = Reg2Py(retDataBuf, retDataSize, typ); + if (obData == NULL) { + retVal = NULL; + goto fail; + } + retVal = Py_BuildValue("uOi", retValueBuf, obData, typ); + Py_DECREF(obData); fail: - PyMem_Free(retValueBuf); - PyMem_Free(retDataBuf); - return retVal; + PyMem_Free(retValueBuf); + PyMem_Free(retDataBuf); + return retVal; } static PyObject * PyExpandEnvironmentStrings(PyObject *self, PyObject *args) { - Py_UNICODE *retValue = NULL; - Py_UNICODE *src; - DWORD retValueSize; - DWORD rc; - PyObject *o; - - if (!PyArg_ParseTuple(args, "u:ExpandEnvironmentStrings", &src)) - return NULL; - - retValueSize = ExpandEnvironmentStringsW(src, retValue, 0); - if (retValueSize == 0) { - return PyErr_SetFromWindowsErrWithFunction(retValueSize, - "ExpandEnvironmentStrings"); - } - retValue = (Py_UNICODE *)PyMem_Malloc(retValueSize * sizeof(Py_UNICODE)); - if (retValue == NULL) { - return PyErr_NoMemory(); - } - - rc = ExpandEnvironmentStringsW(src, retValue, retValueSize); - if (rc == 0) { - PyMem_Free(retValue); - return PyErr_SetFromWindowsErrWithFunction(retValueSize, - "ExpandEnvironmentStrings"); - } - o = PyUnicode_FromUnicode(retValue, wcslen(retValue)); - PyMem_Free(retValue); - return o; + Py_UNICODE *retValue = NULL; + Py_UNICODE *src; + DWORD retValueSize; + DWORD rc; + PyObject *o; + + if (!PyArg_ParseTuple(args, "u:ExpandEnvironmentStrings", &src)) + return NULL; + + retValueSize = ExpandEnvironmentStringsW(src, retValue, 0); + if (retValueSize == 0) { + return PyErr_SetFromWindowsErrWithFunction(retValueSize, + "ExpandEnvironmentStrings"); + } + retValue = (Py_UNICODE *)PyMem_Malloc(retValueSize * sizeof(Py_UNICODE)); + if (retValue == NULL) { + return PyErr_NoMemory(); + } + + rc = ExpandEnvironmentStringsW(src, retValue, retValueSize); + if (rc == 0) { + PyMem_Free(retValue); + return PyErr_SetFromWindowsErrWithFunction(retValueSize, + "ExpandEnvironmentStrings"); + } + o = PyUnicode_FromUnicode(retValue, wcslen(retValue)); + PyMem_Free(retValue); + return o; } static PyObject * PyFlushKey(PyObject *self, PyObject *args) { - HKEY hKey; - PyObject *obKey; - long rc; - if (!PyArg_ParseTuple(args, "O:FlushKey", &obKey)) - return NULL; - if (!PyHKEY_AsHKEY(obKey, &hKey, FALSE)) - return NULL; - Py_BEGIN_ALLOW_THREADS - rc = RegFlushKey(hKey); - Py_END_ALLOW_THREADS - if (rc != ERROR_SUCCESS) - return PyErr_SetFromWindowsErrWithFunction(rc, "RegFlushKey"); - Py_INCREF(Py_None); - return Py_None; + HKEY hKey; + PyObject *obKey; + long rc; + if (!PyArg_ParseTuple(args, "O:FlushKey", &obKey)) + return NULL; + if (!PyHKEY_AsHKEY(obKey, &hKey, FALSE)) + return NULL; + Py_BEGIN_ALLOW_THREADS + rc = RegFlushKey(hKey); + Py_END_ALLOW_THREADS + if (rc != ERROR_SUCCESS) + return PyErr_SetFromWindowsErrWithFunction(rc, "RegFlushKey"); + Py_INCREF(Py_None); + return Py_None; } static PyObject * PyLoadKey(PyObject *self, PyObject *args) { - HKEY hKey; - PyObject *obKey; - wchar_t *subKey; - wchar_t *fileName; - - long rc; - if (!PyArg_ParseTuple(args, "Ouu:LoadKey", &obKey, &subKey, &fileName)) - return NULL; - if (!PyHKEY_AsHKEY(obKey, &hKey, FALSE)) - return NULL; - Py_BEGIN_ALLOW_THREADS - rc = RegLoadKeyW(hKey, subKey, fileName ); - Py_END_ALLOW_THREADS - if (rc != ERROR_SUCCESS) - return PyErr_SetFromWindowsErrWithFunction(rc, "RegLoadKey"); - Py_INCREF(Py_None); - return Py_None; + HKEY hKey; + PyObject *obKey; + wchar_t *subKey; + wchar_t *fileName; + + long rc; + if (!PyArg_ParseTuple(args, "Ouu:LoadKey", &obKey, &subKey, &fileName)) + return NULL; + if (!PyHKEY_AsHKEY(obKey, &hKey, FALSE)) + return NULL; + Py_BEGIN_ALLOW_THREADS + rc = RegLoadKeyW(hKey, subKey, fileName ); + Py_END_ALLOW_THREADS + if (rc != ERROR_SUCCESS) + return PyErr_SetFromWindowsErrWithFunction(rc, "RegLoadKey"); + Py_INCREF(Py_None); + return Py_None; } static PyObject * PyOpenKey(PyObject *self, PyObject *args) { - HKEY hKey; - PyObject *obKey; + HKEY hKey; + PyObject *obKey; - wchar_t *subKey; - int res = 0; - HKEY retKey; - long rc; - REGSAM sam = KEY_READ; - if (!PyArg_ParseTuple(args, "OZ|ii:OpenKey", &obKey, &subKey, - &res, &sam)) - return NULL; - if (!PyHKEY_AsHKEY(obKey, &hKey, FALSE)) - return NULL; - - Py_BEGIN_ALLOW_THREADS - rc = RegOpenKeyExW(hKey, subKey, res, sam, &retKey); - Py_END_ALLOW_THREADS - if (rc != ERROR_SUCCESS) - return PyErr_SetFromWindowsErrWithFunction(rc, "RegOpenKeyEx"); - return PyHKEY_FromHKEY(retKey); + wchar_t *subKey; + int res = 0; + HKEY retKey; + long rc; + REGSAM sam = KEY_READ; + if (!PyArg_ParseTuple(args, "OZ|ii:OpenKey", &obKey, &subKey, + &res, &sam)) + return NULL; + if (!PyHKEY_AsHKEY(obKey, &hKey, FALSE)) + return NULL; + + Py_BEGIN_ALLOW_THREADS + rc = RegOpenKeyExW(hKey, subKey, res, sam, &retKey); + Py_END_ALLOW_THREADS + if (rc != ERROR_SUCCESS) + return PyErr_SetFromWindowsErrWithFunction(rc, "RegOpenKeyEx"); + return PyHKEY_FromHKEY(retKey); } @@ -1198,18 +1198,18 @@ PyObject *l; PyObject *ret; if (!PyArg_ParseTuple(args, "O:QueryInfoKey", &obKey)) - return NULL; + return NULL; if (!PyHKEY_AsHKEY(obKey, &hKey, FALSE)) - return NULL; + return NULL; if ((rc = RegQueryInfoKey(hKey, NULL, NULL, 0, &nSubKeys, NULL, NULL, - &nValues, NULL, NULL, NULL, &ft)) + &nValues, NULL, NULL, NULL, &ft)) != ERROR_SUCCESS) - return PyErr_SetFromWindowsErrWithFunction(rc, "RegQueryInfoKey"); + return PyErr_SetFromWindowsErrWithFunction(rc, "RegQueryInfoKey"); li.LowPart = ft.dwLowDateTime; li.HighPart = ft.dwHighDateTime; l = PyLong_FromLongLong(li.QuadPart); if (l == NULL) - return NULL; + return NULL; ret = Py_BuildValue("iiO", nSubKeys, nValues, l); Py_DECREF(l); return ret; @@ -1218,326 +1218,326 @@ static PyObject * PyQueryValue(PyObject *self, PyObject *args) { - HKEY hKey; - PyObject *obKey; - wchar_t *subKey; - long rc; - PyObject *retStr; - wchar_t *retBuf; - long bufSize = 0; - - if (!PyArg_ParseTuple(args, "OZ:QueryValue", &obKey, &subKey)) - return NULL; - - if (!PyHKEY_AsHKEY(obKey, &hKey, FALSE)) - return NULL; - if ((rc = RegQueryValueW(hKey, subKey, NULL, &bufSize)) - != ERROR_SUCCESS) - return PyErr_SetFromWindowsErrWithFunction(rc, - "RegQueryValue"); - retBuf = (wchar_t *)PyMem_Malloc(bufSize); - if (retBuf == NULL) - return PyErr_NoMemory(); - - if ((rc = RegQueryValueW(hKey, subKey, retBuf, &bufSize)) - != ERROR_SUCCESS) { - PyMem_Free(retBuf); - return PyErr_SetFromWindowsErrWithFunction(rc, - "RegQueryValue"); - } - - retStr = PyUnicode_FromUnicode(retBuf, wcslen(retBuf)); - PyMem_Free(retBuf); - return retStr; + HKEY hKey; + PyObject *obKey; + wchar_t *subKey; + long rc; + PyObject *retStr; + wchar_t *retBuf; + long bufSize = 0; + + if (!PyArg_ParseTuple(args, "OZ:QueryValue", &obKey, &subKey)) + return NULL; + + if (!PyHKEY_AsHKEY(obKey, &hKey, FALSE)) + return NULL; + if ((rc = RegQueryValueW(hKey, subKey, NULL, &bufSize)) + != ERROR_SUCCESS) + return PyErr_SetFromWindowsErrWithFunction(rc, + "RegQueryValue"); + retBuf = (wchar_t *)PyMem_Malloc(bufSize); + if (retBuf == NULL) + return PyErr_NoMemory(); + + if ((rc = RegQueryValueW(hKey, subKey, retBuf, &bufSize)) + != ERROR_SUCCESS) { + PyMem_Free(retBuf); + return PyErr_SetFromWindowsErrWithFunction(rc, + "RegQueryValue"); + } + + retStr = PyUnicode_FromUnicode(retBuf, wcslen(retBuf)); + PyMem_Free(retBuf); + return retStr; } static PyObject * PyQueryValueEx(PyObject *self, PyObject *args) { - HKEY hKey; - PyObject *obKey; - wchar_t *valueName; - - long rc; - BYTE *retBuf; - DWORD bufSize = 0; - DWORD typ; - PyObject *obData; - PyObject *result; - - if (!PyArg_ParseTuple(args, "OZ:QueryValueEx", &obKey, &valueName)) - return NULL; - - if (!PyHKEY_AsHKEY(obKey, &hKey, FALSE)) - return NULL; - if ((rc = RegQueryValueExW(hKey, valueName, - NULL, NULL, NULL, - &bufSize)) - != ERROR_SUCCESS) - return PyErr_SetFromWindowsErrWithFunction(rc, - "RegQueryValueEx"); - retBuf = (BYTE *)PyMem_Malloc(bufSize); - if (retBuf == NULL) - return PyErr_NoMemory(); - if ((rc = RegQueryValueExW(hKey, valueName, NULL, - &typ, retBuf, &bufSize)) - != ERROR_SUCCESS) { - PyMem_Free(retBuf); - return PyErr_SetFromWindowsErrWithFunction(rc, - "RegQueryValueEx"); - } - obData = Reg2Py(retBuf, bufSize, typ); - PyMem_Free(retBuf); - if (obData == NULL) - return NULL; - result = Py_BuildValue("Oi", obData, typ); - Py_DECREF(obData); - return result; + HKEY hKey; + PyObject *obKey; + wchar_t *valueName; + + long rc; + BYTE *retBuf; + DWORD bufSize = 0; + DWORD typ; + PyObject *obData; + PyObject *result; + + if (!PyArg_ParseTuple(args, "OZ:QueryValueEx", &obKey, &valueName)) + return NULL; + + if (!PyHKEY_AsHKEY(obKey, &hKey, FALSE)) + return NULL; + if ((rc = RegQueryValueExW(hKey, valueName, + NULL, NULL, NULL, + &bufSize)) + != ERROR_SUCCESS) + return PyErr_SetFromWindowsErrWithFunction(rc, + "RegQueryValueEx"); + retBuf = (BYTE *)PyMem_Malloc(bufSize); + if (retBuf == NULL) + return PyErr_NoMemory(); + if ((rc = RegQueryValueExW(hKey, valueName, NULL, + &typ, retBuf, &bufSize)) + != ERROR_SUCCESS) { + PyMem_Free(retBuf); + return PyErr_SetFromWindowsErrWithFunction(rc, + "RegQueryValueEx"); + } + obData = Reg2Py(retBuf, bufSize, typ); + PyMem_Free(retBuf); + if (obData == NULL) + return NULL; + result = Py_BuildValue("Oi", obData, typ); + Py_DECREF(obData); + return result; } static PyObject * PySaveKey(PyObject *self, PyObject *args) { - HKEY hKey; - PyObject *obKey; - wchar_t *fileName; - LPSECURITY_ATTRIBUTES pSA = NULL; - - long rc; - if (!PyArg_ParseTuple(args, "Ou:SaveKey", &obKey, &fileName)) - return NULL; - if (!PyHKEY_AsHKEY(obKey, &hKey, FALSE)) - return NULL; + HKEY hKey; + PyObject *obKey; + wchar_t *fileName; + LPSECURITY_ATTRIBUTES pSA = NULL; + + long rc; + if (!PyArg_ParseTuple(args, "Ou:SaveKey", &obKey, &fileName)) + return NULL; + if (!PyHKEY_AsHKEY(obKey, &hKey, FALSE)) + return NULL; /* One day we may get security into the core? - if (!PyWinObject_AsSECURITY_ATTRIBUTES(obSA, &pSA, TRUE)) - return NULL; + if (!PyWinObject_AsSECURITY_ATTRIBUTES(obSA, &pSA, TRUE)) + return NULL; */ - Py_BEGIN_ALLOW_THREADS - rc = RegSaveKeyW(hKey, fileName, pSA ); - Py_END_ALLOW_THREADS - if (rc != ERROR_SUCCESS) - return PyErr_SetFromWindowsErrWithFunction(rc, "RegSaveKey"); - Py_INCREF(Py_None); - return Py_None; + Py_BEGIN_ALLOW_THREADS + rc = RegSaveKeyW(hKey, fileName, pSA ); + Py_END_ALLOW_THREADS + if (rc != ERROR_SUCCESS) + return PyErr_SetFromWindowsErrWithFunction(rc, "RegSaveKey"); + Py_INCREF(Py_None); + return Py_None; } static PyObject * PySetValue(PyObject *self, PyObject *args) { - HKEY hKey; - PyObject *obKey; - wchar_t *subKey; - wchar_t *str; - DWORD typ; - DWORD len; - long rc; - if (!PyArg_ParseTuple(args, "OZiu#:SetValue", - &obKey, - &subKey, - &typ, - &str, - &len)) - return NULL; - if (!PyHKEY_AsHKEY(obKey, &hKey, FALSE)) - return NULL; - if (typ != REG_SZ) { - PyErr_SetString(PyExc_TypeError, - "Type must be winreg.REG_SZ"); - return NULL; - } - - Py_BEGIN_ALLOW_THREADS - rc = RegSetValueW(hKey, subKey, REG_SZ, str, len+1); - Py_END_ALLOW_THREADS - if (rc != ERROR_SUCCESS) - return PyErr_SetFromWindowsErrWithFunction(rc, "RegSetValue"); - Py_INCREF(Py_None); - return Py_None; + HKEY hKey; + PyObject *obKey; + wchar_t *subKey; + wchar_t *str; + DWORD typ; + DWORD len; + long rc; + if (!PyArg_ParseTuple(args, "OZiu#:SetValue", + &obKey, + &subKey, + &typ, + &str, + &len)) + return NULL; + if (!PyHKEY_AsHKEY(obKey, &hKey, FALSE)) + return NULL; + if (typ != REG_SZ) { + PyErr_SetString(PyExc_TypeError, + "Type must be winreg.REG_SZ"); + return NULL; + } + + Py_BEGIN_ALLOW_THREADS + rc = RegSetValueW(hKey, subKey, REG_SZ, str, len+1); + Py_END_ALLOW_THREADS + if (rc != ERROR_SUCCESS) + return PyErr_SetFromWindowsErrWithFunction(rc, "RegSetValue"); + Py_INCREF(Py_None); + return Py_None; } static PyObject * PySetValueEx(PyObject *self, PyObject *args) { - HKEY hKey; - PyObject *obKey; - Py_UNICODE *valueName; - PyObject *obRes; - PyObject *value; - BYTE *data; - DWORD len; - DWORD typ; - - LONG rc; - - if (!PyArg_ParseTuple(args, "OZOiO:SetValueEx", - &obKey, - &valueName, - &obRes, - &typ, - &value)) - return NULL; - if (!PyHKEY_AsHKEY(obKey, &hKey, FALSE)) - return NULL; - if (!Py2Reg(value, typ, &data, &len)) - { - if (!PyErr_Occurred()) - PyErr_SetString(PyExc_ValueError, - "Could not convert the data to the specified type."); - return NULL; - } - Py_BEGIN_ALLOW_THREADS - rc = RegSetValueExW(hKey, valueName, 0, typ, data, len); - Py_END_ALLOW_THREADS - PyMem_DEL(data); - if (rc != ERROR_SUCCESS) - return PyErr_SetFromWindowsErrWithFunction(rc, - "RegSetValueEx"); - Py_INCREF(Py_None); - return Py_None; + HKEY hKey; + PyObject *obKey; + Py_UNICODE *valueName; + PyObject *obRes; + PyObject *value; + BYTE *data; + DWORD len; + DWORD typ; + + LONG rc; + + if (!PyArg_ParseTuple(args, "OZOiO:SetValueEx", + &obKey, + &valueName, + &obRes, + &typ, + &value)) + return NULL; + if (!PyHKEY_AsHKEY(obKey, &hKey, FALSE)) + return NULL; + if (!Py2Reg(value, typ, &data, &len)) + { + if (!PyErr_Occurred()) + PyErr_SetString(PyExc_ValueError, + "Could not convert the data to the specified type."); + return NULL; + } + Py_BEGIN_ALLOW_THREADS + rc = RegSetValueExW(hKey, valueName, 0, typ, data, len); + Py_END_ALLOW_THREADS + PyMem_DEL(data); + if (rc != ERROR_SUCCESS) + return PyErr_SetFromWindowsErrWithFunction(rc, + "RegSetValueEx"); + Py_INCREF(Py_None); + return Py_None; } static PyObject * PyDisableReflectionKey(PyObject *self, PyObject *args) { - HKEY hKey; - PyObject *obKey; - HMODULE hMod; - typedef LONG (WINAPI *RDRKFunc)(HKEY); - RDRKFunc pfn = NULL; - LONG rc; - - if (!PyArg_ParseTuple(args, "O:DisableReflectionKey", &obKey)) - return NULL; - if (!PyHKEY_AsHKEY(obKey, &hKey, FALSE)) - return NULL; - - // Only available on 64bit platforms, so we must load it - // dynamically. - hMod = GetModuleHandle("advapi32.dll"); - if (hMod) - pfn = (RDRKFunc)GetProcAddress(hMod, - "RegDisableReflectionKey"); - if (!pfn) { - PyErr_SetString(PyExc_NotImplementedError, - "not implemented on this platform"); - return NULL; - } - Py_BEGIN_ALLOW_THREADS - rc = (*pfn)(hKey); - Py_END_ALLOW_THREADS - if (rc != ERROR_SUCCESS) - return PyErr_SetFromWindowsErrWithFunction(rc, - "RegDisableReflectionKey"); - Py_INCREF(Py_None); - return Py_None; + HKEY hKey; + PyObject *obKey; + HMODULE hMod; + typedef LONG (WINAPI *RDRKFunc)(HKEY); + RDRKFunc pfn = NULL; + LONG rc; + + if (!PyArg_ParseTuple(args, "O:DisableReflectionKey", &obKey)) + return NULL; + if (!PyHKEY_AsHKEY(obKey, &hKey, FALSE)) + return NULL; + + // Only available on 64bit platforms, so we must load it + // dynamically. + hMod = GetModuleHandle("advapi32.dll"); + if (hMod) + pfn = (RDRKFunc)GetProcAddress(hMod, + "RegDisableReflectionKey"); + if (!pfn) { + PyErr_SetString(PyExc_NotImplementedError, + "not implemented on this platform"); + return NULL; + } + Py_BEGIN_ALLOW_THREADS + rc = (*pfn)(hKey); + Py_END_ALLOW_THREADS + if (rc != ERROR_SUCCESS) + return PyErr_SetFromWindowsErrWithFunction(rc, + "RegDisableReflectionKey"); + Py_INCREF(Py_None); + return Py_None; } static PyObject * PyEnableReflectionKey(PyObject *self, PyObject *args) { - HKEY hKey; - PyObject *obKey; - HMODULE hMod; - typedef LONG (WINAPI *RERKFunc)(HKEY); - RERKFunc pfn = NULL; - LONG rc; - - if (!PyArg_ParseTuple(args, "O:EnableReflectionKey", &obKey)) - return NULL; - if (!PyHKEY_AsHKEY(obKey, &hKey, FALSE)) - return NULL; - - // Only available on 64bit platforms, so we must load it - // dynamically. - hMod = GetModuleHandle("advapi32.dll"); - if (hMod) - pfn = (RERKFunc)GetProcAddress(hMod, - "RegEnableReflectionKey"); - if (!pfn) { - PyErr_SetString(PyExc_NotImplementedError, - "not implemented on this platform"); - return NULL; - } - Py_BEGIN_ALLOW_THREADS - rc = (*pfn)(hKey); - Py_END_ALLOW_THREADS - if (rc != ERROR_SUCCESS) - return PyErr_SetFromWindowsErrWithFunction(rc, - "RegEnableReflectionKey"); - Py_INCREF(Py_None); - return Py_None; + HKEY hKey; + PyObject *obKey; + HMODULE hMod; + typedef LONG (WINAPI *RERKFunc)(HKEY); + RERKFunc pfn = NULL; + LONG rc; + + if (!PyArg_ParseTuple(args, "O:EnableReflectionKey", &obKey)) + return NULL; + if (!PyHKEY_AsHKEY(obKey, &hKey, FALSE)) + return NULL; + + // Only available on 64bit platforms, so we must load it + // dynamically. + hMod = GetModuleHandle("advapi32.dll"); + if (hMod) + pfn = (RERKFunc)GetProcAddress(hMod, + "RegEnableReflectionKey"); + if (!pfn) { + PyErr_SetString(PyExc_NotImplementedError, + "not implemented on this platform"); + return NULL; + } + Py_BEGIN_ALLOW_THREADS + rc = (*pfn)(hKey); + Py_END_ALLOW_THREADS + if (rc != ERROR_SUCCESS) + return PyErr_SetFromWindowsErrWithFunction(rc, + "RegEnableReflectionKey"); + Py_INCREF(Py_None); + return Py_None; } static PyObject * PyQueryReflectionKey(PyObject *self, PyObject *args) { - HKEY hKey; - PyObject *obKey; - HMODULE hMod; - typedef LONG (WINAPI *RQRKFunc)(HKEY, BOOL *); - RQRKFunc pfn = NULL; - BOOL result; - LONG rc; - - if (!PyArg_ParseTuple(args, "O:QueryReflectionKey", &obKey)) - return NULL; - if (!PyHKEY_AsHKEY(obKey, &hKey, FALSE)) - return NULL; - - // Only available on 64bit platforms, so we must load it - // dynamically. - hMod = GetModuleHandle("advapi32.dll"); - if (hMod) - pfn = (RQRKFunc)GetProcAddress(hMod, - "RegQueryReflectionKey"); - if (!pfn) { - PyErr_SetString(PyExc_NotImplementedError, - "not implemented on this platform"); - return NULL; - } - Py_BEGIN_ALLOW_THREADS - rc = (*pfn)(hKey, &result); - Py_END_ALLOW_THREADS - if (rc != ERROR_SUCCESS) - return PyErr_SetFromWindowsErrWithFunction(rc, - "RegQueryReflectionKey"); - return PyBool_FromLong(rc); + HKEY hKey; + PyObject *obKey; + HMODULE hMod; + typedef LONG (WINAPI *RQRKFunc)(HKEY, BOOL *); + RQRKFunc pfn = NULL; + BOOL result; + LONG rc; + + if (!PyArg_ParseTuple(args, "O:QueryReflectionKey", &obKey)) + return NULL; + if (!PyHKEY_AsHKEY(obKey, &hKey, FALSE)) + return NULL; + + // Only available on 64bit platforms, so we must load it + // dynamically. + hMod = GetModuleHandle("advapi32.dll"); + if (hMod) + pfn = (RQRKFunc)GetProcAddress(hMod, + "RegQueryReflectionKey"); + if (!pfn) { + PyErr_SetString(PyExc_NotImplementedError, + "not implemented on this platform"); + return NULL; + } + Py_BEGIN_ALLOW_THREADS + rc = (*pfn)(hKey, &result); + Py_END_ALLOW_THREADS + if (rc != ERROR_SUCCESS) + return PyErr_SetFromWindowsErrWithFunction(rc, + "RegQueryReflectionKey"); + return PyBool_FromLong(rc); } static struct PyMethodDef winreg_methods[] = { - {"CloseKey", PyCloseKey, METH_VARARGS, CloseKey_doc}, - {"ConnectRegistry", PyConnectRegistry, METH_VARARGS, ConnectRegistry_doc}, - {"CreateKey", PyCreateKey, METH_VARARGS, CreateKey_doc}, - {"DeleteKey", PyDeleteKey, METH_VARARGS, DeleteKey_doc}, - {"DeleteValue", PyDeleteValue, METH_VARARGS, DeleteValue_doc}, - {"DisableReflectionKey", PyDisableReflectionKey, METH_VARARGS, DisableReflectionKey_doc}, - {"EnableReflectionKey", PyEnableReflectionKey, METH_VARARGS, EnableReflectionKey_doc}, - {"EnumKey", PyEnumKey, METH_VARARGS, EnumKey_doc}, - {"EnumValue", PyEnumValue, METH_VARARGS, EnumValue_doc}, - {"ExpandEnvironmentStrings", PyExpandEnvironmentStrings, METH_VARARGS, - ExpandEnvironmentStrings_doc }, - {"FlushKey", PyFlushKey, METH_VARARGS, FlushKey_doc}, - {"LoadKey", PyLoadKey, METH_VARARGS, LoadKey_doc}, - {"OpenKey", PyOpenKey, METH_VARARGS, OpenKey_doc}, - {"OpenKeyEx", PyOpenKey, METH_VARARGS, OpenKeyEx_doc}, - {"QueryValue", PyQueryValue, METH_VARARGS, QueryValue_doc}, - {"QueryValueEx", PyQueryValueEx, METH_VARARGS, QueryValueEx_doc}, - {"QueryInfoKey", PyQueryInfoKey, METH_VARARGS, QueryInfoKey_doc}, - {"QueryReflectionKey",PyQueryReflectionKey,METH_VARARGS, QueryReflectionKey_doc}, - {"SaveKey", PySaveKey, METH_VARARGS, SaveKey_doc}, - {"SetValue", PySetValue, METH_VARARGS, SetValue_doc}, - {"SetValueEx", PySetValueEx, METH_VARARGS, SetValueEx_doc}, - NULL, + {"CloseKey", PyCloseKey, METH_VARARGS, CloseKey_doc}, + {"ConnectRegistry", PyConnectRegistry, METH_VARARGS, ConnectRegistry_doc}, + {"CreateKey", PyCreateKey, METH_VARARGS, CreateKey_doc}, + {"DeleteKey", PyDeleteKey, METH_VARARGS, DeleteKey_doc}, + {"DeleteValue", PyDeleteValue, METH_VARARGS, DeleteValue_doc}, + {"DisableReflectionKey", PyDisableReflectionKey, METH_VARARGS, DisableReflectionKey_doc}, + {"EnableReflectionKey", PyEnableReflectionKey, METH_VARARGS, EnableReflectionKey_doc}, + {"EnumKey", PyEnumKey, METH_VARARGS, EnumKey_doc}, + {"EnumValue", PyEnumValue, METH_VARARGS, EnumValue_doc}, + {"ExpandEnvironmentStrings", PyExpandEnvironmentStrings, METH_VARARGS, + ExpandEnvironmentStrings_doc }, + {"FlushKey", PyFlushKey, METH_VARARGS, FlushKey_doc}, + {"LoadKey", PyLoadKey, METH_VARARGS, LoadKey_doc}, + {"OpenKey", PyOpenKey, METH_VARARGS, OpenKey_doc}, + {"OpenKeyEx", PyOpenKey, METH_VARARGS, OpenKeyEx_doc}, + {"QueryValue", PyQueryValue, METH_VARARGS, QueryValue_doc}, + {"QueryValueEx", PyQueryValueEx, METH_VARARGS, QueryValueEx_doc}, + {"QueryInfoKey", PyQueryInfoKey, METH_VARARGS, QueryInfoKey_doc}, + {"QueryReflectionKey",PyQueryReflectionKey,METH_VARARGS, QueryReflectionKey_doc}, + {"SaveKey", PySaveKey, METH_VARARGS, SaveKey_doc}, + {"SetValue", PySetValue, METH_VARARGS, SetValue_doc}, + {"SetValueEx", PySetValueEx, METH_VARARGS, SetValueEx_doc}, + NULL, }; static void insint(PyObject * d, char * name, long value) { - PyObject *v = PyLong_FromLong(value); - if (!v || PyDict_SetItemString(d, name, v)) - PyErr_Clear(); - Py_XDECREF(v); + PyObject *v = PyLong_FromLong(value); + if (!v || PyDict_SetItemString(d, name, v)) + PyErr_Clear(); + Py_XDECREF(v); } #define ADD_INT(val) insint(d, #val, val) @@ -1545,104 +1545,104 @@ static void inskey(PyObject * d, char * name, HKEY key) { - PyObject *v = PyLong_FromVoidPtr(key); - if (!v || PyDict_SetItemString(d, name, v)) - PyErr_Clear(); - Py_XDECREF(v); + PyObject *v = PyLong_FromVoidPtr(key); + if (!v || PyDict_SetItemString(d, name, v)) + PyErr_Clear(); + Py_XDECREF(v); } #define ADD_KEY(val) inskey(d, #val, val) static struct PyModuleDef winregmodule = { - PyModuleDef_HEAD_INIT, - "winreg", - module_doc, - -1, - winreg_methods, - NULL, - NULL, - NULL, - NULL + PyModuleDef_HEAD_INIT, + "winreg", + module_doc, + -1, + winreg_methods, + NULL, + NULL, + NULL, + NULL }; PyMODINIT_FUNC PyInit_winreg(void) { - PyObject *m, *d; - m = PyModule_Create(&winregmodule); - if (m == NULL) - return NULL; - d = PyModule_GetDict(m); - PyHKEY_Type.tp_doc = PyHKEY_doc; - if (PyType_Ready(&PyHKEY_Type) < 0) - return NULL; - Py_INCREF(&PyHKEY_Type); - if (PyDict_SetItemString(d, "HKEYType", - (PyObject *)&PyHKEY_Type) != 0) - return NULL; - Py_INCREF(PyExc_WindowsError); - if (PyDict_SetItemString(d, "error", - PyExc_WindowsError) != 0) - return NULL; - - /* Add the relevant constants */ - ADD_KEY(HKEY_CLASSES_ROOT); - ADD_KEY(HKEY_CURRENT_USER); - ADD_KEY(HKEY_LOCAL_MACHINE); - ADD_KEY(HKEY_USERS); - ADD_KEY(HKEY_PERFORMANCE_DATA); + PyObject *m, *d; + m = PyModule_Create(&winregmodule); + if (m == NULL) + return NULL; + d = PyModule_GetDict(m); + PyHKEY_Type.tp_doc = PyHKEY_doc; + if (PyType_Ready(&PyHKEY_Type) < 0) + return NULL; + Py_INCREF(&PyHKEY_Type); + if (PyDict_SetItemString(d, "HKEYType", + (PyObject *)&PyHKEY_Type) != 0) + return NULL; + Py_INCREF(PyExc_WindowsError); + if (PyDict_SetItemString(d, "error", + PyExc_WindowsError) != 0) + return NULL; + + /* Add the relevant constants */ + ADD_KEY(HKEY_CLASSES_ROOT); + ADD_KEY(HKEY_CURRENT_USER); + ADD_KEY(HKEY_LOCAL_MACHINE); + ADD_KEY(HKEY_USERS); + ADD_KEY(HKEY_PERFORMANCE_DATA); #ifdef HKEY_CURRENT_CONFIG - ADD_KEY(HKEY_CURRENT_CONFIG); + ADD_KEY(HKEY_CURRENT_CONFIG); #endif #ifdef HKEY_DYN_DATA - ADD_KEY(HKEY_DYN_DATA); + ADD_KEY(HKEY_DYN_DATA); #endif - ADD_INT(KEY_QUERY_VALUE); - ADD_INT(KEY_SET_VALUE); - ADD_INT(KEY_CREATE_SUB_KEY); - ADD_INT(KEY_ENUMERATE_SUB_KEYS); - ADD_INT(KEY_NOTIFY); - ADD_INT(KEY_CREATE_LINK); - ADD_INT(KEY_READ); - ADD_INT(KEY_WRITE); - ADD_INT(KEY_EXECUTE); - ADD_INT(KEY_ALL_ACCESS); + ADD_INT(KEY_QUERY_VALUE); + ADD_INT(KEY_SET_VALUE); + ADD_INT(KEY_CREATE_SUB_KEY); + ADD_INT(KEY_ENUMERATE_SUB_KEYS); + ADD_INT(KEY_NOTIFY); + ADD_INT(KEY_CREATE_LINK); + ADD_INT(KEY_READ); + ADD_INT(KEY_WRITE); + ADD_INT(KEY_EXECUTE); + ADD_INT(KEY_ALL_ACCESS); #ifdef KEY_WOW64_64KEY - ADD_INT(KEY_WOW64_64KEY); + ADD_INT(KEY_WOW64_64KEY); #endif #ifdef KEY_WOW64_32KEY - ADD_INT(KEY_WOW64_32KEY); + ADD_INT(KEY_WOW64_32KEY); #endif - ADD_INT(REG_OPTION_RESERVED); - ADD_INT(REG_OPTION_NON_VOLATILE); - ADD_INT(REG_OPTION_VOLATILE); - ADD_INT(REG_OPTION_CREATE_LINK); - ADD_INT(REG_OPTION_BACKUP_RESTORE); - ADD_INT(REG_OPTION_OPEN_LINK); - ADD_INT(REG_LEGAL_OPTION); - ADD_INT(REG_CREATED_NEW_KEY); - ADD_INT(REG_OPENED_EXISTING_KEY); - ADD_INT(REG_WHOLE_HIVE_VOLATILE); - ADD_INT(REG_REFRESH_HIVE); - ADD_INT(REG_NO_LAZY_FLUSH); - ADD_INT(REG_NOTIFY_CHANGE_NAME); - ADD_INT(REG_NOTIFY_CHANGE_ATTRIBUTES); - ADD_INT(REG_NOTIFY_CHANGE_LAST_SET); - ADD_INT(REG_NOTIFY_CHANGE_SECURITY); - ADD_INT(REG_LEGAL_CHANGE_FILTER); - ADD_INT(REG_NONE); - ADD_INT(REG_SZ); - ADD_INT(REG_EXPAND_SZ); - ADD_INT(REG_BINARY); - ADD_INT(REG_DWORD); - ADD_INT(REG_DWORD_LITTLE_ENDIAN); - ADD_INT(REG_DWORD_BIG_ENDIAN); - ADD_INT(REG_LINK); - ADD_INT(REG_MULTI_SZ); - ADD_INT(REG_RESOURCE_LIST); - ADD_INT(REG_FULL_RESOURCE_DESCRIPTOR); - ADD_INT(REG_RESOURCE_REQUIREMENTS_LIST); - return m; + ADD_INT(REG_OPTION_RESERVED); + ADD_INT(REG_OPTION_NON_VOLATILE); + ADD_INT(REG_OPTION_VOLATILE); + ADD_INT(REG_OPTION_CREATE_LINK); + ADD_INT(REG_OPTION_BACKUP_RESTORE); + ADD_INT(REG_OPTION_OPEN_LINK); + ADD_INT(REG_LEGAL_OPTION); + ADD_INT(REG_CREATED_NEW_KEY); + ADD_INT(REG_OPENED_EXISTING_KEY); + ADD_INT(REG_WHOLE_HIVE_VOLATILE); + ADD_INT(REG_REFRESH_HIVE); + ADD_INT(REG_NO_LAZY_FLUSH); + ADD_INT(REG_NOTIFY_CHANGE_NAME); + ADD_INT(REG_NOTIFY_CHANGE_ATTRIBUTES); + ADD_INT(REG_NOTIFY_CHANGE_LAST_SET); + ADD_INT(REG_NOTIFY_CHANGE_SECURITY); + ADD_INT(REG_LEGAL_CHANGE_FILTER); + ADD_INT(REG_NONE); + ADD_INT(REG_SZ); + ADD_INT(REG_EXPAND_SZ); + ADD_INT(REG_BINARY); + ADD_INT(REG_DWORD); + ADD_INT(REG_DWORD_LITTLE_ENDIAN); + ADD_INT(REG_DWORD_BIG_ENDIAN); + ADD_INT(REG_LINK); + ADD_INT(REG_MULTI_SZ); + ADD_INT(REG_RESOURCE_LIST); + ADD_INT(REG_FULL_RESOURCE_DESCRIPTOR); + ADD_INT(REG_RESOURCE_REQUIREMENTS_LIST); + return m; } Modified: python/branches/release31-maint/PC/winsound.c ============================================================================== --- python/branches/release31-maint/PC/winsound.c (original) +++ python/branches/release31-maint/PC/winsound.c Sun May 9 18:14:21 2010 @@ -78,14 +78,14 @@ int ok; if(!PyArg_ParseTuple(args,"z#i:PlaySound",&sound,&length,&flags)) { - return NULL; + return NULL; } if(flags&SND_ASYNC && flags &SND_MEMORY) { - /* Sidestep reference counting headache; unfortunately this also - prevent SND_LOOP from memory. */ - PyErr_SetString(PyExc_RuntimeError,"Cannot play asynchronously from memory"); - return NULL; + /* Sidestep reference counting headache; unfortunately this also + prevent SND_LOOP from memory. */ + PyErr_SetString(PyExc_RuntimeError,"Cannot play asynchronously from memory"); + return NULL; } Py_BEGIN_ALLOW_THREADS @@ -93,8 +93,8 @@ Py_END_ALLOW_THREADS if(!ok) { - PyErr_SetString(PyExc_RuntimeError,"Failed to play sound"); - return NULL; + PyErr_SetString(PyExc_RuntimeError,"Failed to play sound"); + return NULL; } Py_INCREF(Py_None); @@ -104,40 +104,40 @@ static PyObject * sound_beep(PyObject *self, PyObject *args) { - int freq; - int dur; - BOOL ok; - - if (!PyArg_ParseTuple(args, "ii:Beep", &freq, &dur)) - return NULL; - - if (freq < 37 || freq > 32767) { - PyErr_SetString(PyExc_ValueError, - "frequency must be in 37 thru 32767"); - return NULL; - } - - Py_BEGIN_ALLOW_THREADS - ok = Beep(freq, dur); - Py_END_ALLOW_THREADS - if (!ok) { - PyErr_SetString(PyExc_RuntimeError,"Failed to beep"); - return NULL; - } + int freq; + int dur; + BOOL ok; + + if (!PyArg_ParseTuple(args, "ii:Beep", &freq, &dur)) + return NULL; + + if (freq < 37 || freq > 32767) { + PyErr_SetString(PyExc_ValueError, + "frequency must be in 37 thru 32767"); + return NULL; + } + + Py_BEGIN_ALLOW_THREADS + ok = Beep(freq, dur); + Py_END_ALLOW_THREADS + if (!ok) { + PyErr_SetString(PyExc_RuntimeError,"Failed to beep"); + return NULL; + } - Py_INCREF(Py_None); - return Py_None; + Py_INCREF(Py_None); + return Py_None; } static PyObject * sound_msgbeep(PyObject *self, PyObject *args) { - int x = MB_OK; - if (!PyArg_ParseTuple(args, "|i:MessageBeep", &x)) - return NULL; - MessageBeep(x); - Py_INCREF(Py_None); - return Py_None; + int x = MB_OK; + if (!PyArg_ParseTuple(args, "|i:MessageBeep", &x)) + return NULL; + MessageBeep(x); + Py_INCREF(Py_None); + return Py_None; } static struct PyMethodDef sound_methods[] = @@ -155,7 +155,7 @@ PyObject *v=PyLong_FromLong(value); if(v&&k) { - PyDict_SetItem(dict,k,v); + PyDict_SetItem(dict,k,v); } Py_XDECREF(k); Py_XDECREF(v); @@ -165,41 +165,41 @@ static struct PyModuleDef winsoundmodule = { - PyModuleDef_HEAD_INIT, - "winsound", - sound_module_doc, - -1, - sound_methods, - NULL, - NULL, - NULL, - NULL + PyModuleDef_HEAD_INIT, + "winsound", + sound_module_doc, + -1, + sound_methods, + NULL, + NULL, + NULL, + NULL }; PyMODINIT_FUNC PyInit_winsound(void) { - PyObject *dict; - PyObject *module = PyModule_Create(&winsoundmodule); - if (module == NULL) - return NULL; - dict = PyModule_GetDict(module); - - ADD_DEFINE(SND_ASYNC); - ADD_DEFINE(SND_NODEFAULT); - ADD_DEFINE(SND_NOSTOP); - ADD_DEFINE(SND_NOWAIT); - ADD_DEFINE(SND_ALIAS); - ADD_DEFINE(SND_FILENAME); - ADD_DEFINE(SND_MEMORY); - ADD_DEFINE(SND_PURGE); - ADD_DEFINE(SND_LOOP); - ADD_DEFINE(SND_APPLICATION); - - ADD_DEFINE(MB_OK); - ADD_DEFINE(MB_ICONASTERISK); - ADD_DEFINE(MB_ICONEXCLAMATION); - ADD_DEFINE(MB_ICONHAND); - ADD_DEFINE(MB_ICONQUESTION); - return module; + PyObject *dict; + PyObject *module = PyModule_Create(&winsoundmodule); + if (module == NULL) + return NULL; + dict = PyModule_GetDict(module); + + ADD_DEFINE(SND_ASYNC); + ADD_DEFINE(SND_NODEFAULT); + ADD_DEFINE(SND_NOSTOP); + ADD_DEFINE(SND_NOWAIT); + ADD_DEFINE(SND_ALIAS); + ADD_DEFINE(SND_FILENAME); + ADD_DEFINE(SND_MEMORY); + ADD_DEFINE(SND_PURGE); + ADD_DEFINE(SND_LOOP); + ADD_DEFINE(SND_APPLICATION); + + ADD_DEFINE(MB_OK); + ADD_DEFINE(MB_ICONASTERISK); + ADD_DEFINE(MB_ICONEXCLAMATION); + ADD_DEFINE(MB_ICONHAND); + ADD_DEFINE(MB_ICONQUESTION); + return module; } Modified: python/branches/release31-maint/PCbuild/make_buildinfo.c ============================================================================== --- python/branches/release31-maint/PCbuild/make_buildinfo.c (original) +++ python/branches/release31-maint/PCbuild/make_buildinfo.c Sun May 9 18:14:21 2010 @@ -23,72 +23,72 @@ int make_buildinfo2() { - struct _stat st; - HKEY hTortoise; - char command[CMD_SIZE+1]; - DWORD type, size; - if (_stat(".svn", &st) < 0) - return 0; - /* Allow suppression of subwcrev.exe invocation if a no_subwcrev file is present. */ - if (_stat("no_subwcrev", &st) == 0) - return 0; - if (RegOpenKey(HKEY_LOCAL_MACHINE, "Software\\TortoiseSVN", &hTortoise) != ERROR_SUCCESS && - RegOpenKey(HKEY_CURRENT_USER, "Software\\TortoiseSVN", &hTortoise) != ERROR_SUCCESS) - /* Tortoise not installed */ - return 0; - command[0] = '"'; /* quote the path to the executable */ - size = sizeof(command) - 1; - if (RegQueryValueEx(hTortoise, "Directory", 0, &type, command+1, &size) != ERROR_SUCCESS || - type != REG_SZ) - /* Registry corrupted */ - return 0; - strcat_s(command, CMD_SIZE, "bin\\subwcrev.exe"); - if (_stat(command+1, &st) < 0) - /* subwcrev.exe not part of the release */ - return 0; - strcat_s(command, CMD_SIZE, "\" .. ..\\Modules\\getbuildinfo.c getbuildinfo2.c"); - puts(command); fflush(stdout); - if (system(command) < 0) - return 0; - return 1; + struct _stat st; + HKEY hTortoise; + char command[CMD_SIZE+1]; + DWORD type, size; + if (_stat(".svn", &st) < 0) + return 0; + /* Allow suppression of subwcrev.exe invocation if a no_subwcrev file is present. */ + if (_stat("no_subwcrev", &st) == 0) + return 0; + if (RegOpenKey(HKEY_LOCAL_MACHINE, "Software\\TortoiseSVN", &hTortoise) != ERROR_SUCCESS && + RegOpenKey(HKEY_CURRENT_USER, "Software\\TortoiseSVN", &hTortoise) != ERROR_SUCCESS) + /* Tortoise not installed */ + return 0; + command[0] = '"'; /* quote the path to the executable */ + size = sizeof(command) - 1; + if (RegQueryValueEx(hTortoise, "Directory", 0, &type, command+1, &size) != ERROR_SUCCESS || + type != REG_SZ) + /* Registry corrupted */ + return 0; + strcat_s(command, CMD_SIZE, "bin\\subwcrev.exe"); + if (_stat(command+1, &st) < 0) + /* subwcrev.exe not part of the release */ + return 0; + strcat_s(command, CMD_SIZE, "\" .. ..\\Modules\\getbuildinfo.c getbuildinfo2.c"); + puts(command); fflush(stdout); + if (system(command) < 0) + return 0; + return 1; } int main(int argc, char*argv[]) { - char command[500] = "cl.exe -c -D_WIN32 -DUSE_DL_EXPORT -D_WINDOWS -DWIN32 -D_WINDLL "; - int do_unlink, result; - if (argc != 2) { - fprintf(stderr, "make_buildinfo $(ConfigurationName)\n"); - return EXIT_FAILURE; - } - if (strcmp(argv[1], "Release") == 0) { - strcat_s(command, CMD_SIZE, "-MD "); - } - else if (strcmp(argv[1], "Debug") == 0) { - strcat_s(command, CMD_SIZE, "-D_DEBUG -MDd "); - } - else if (strcmp(argv[1], "ReleaseItanium") == 0) { - strcat_s(command, CMD_SIZE, "-MD /USECL:MS_ITANIUM "); - } - else if (strcmp(argv[1], "ReleaseAMD64") == 0) { - strcat_s(command, CMD_SIZE, "-MD "); - strcat_s(command, CMD_SIZE, "-MD /USECL:MS_OPTERON "); - } - else { - fprintf(stderr, "unsupported configuration %s\n", argv[1]); - return EXIT_FAILURE; - } + char command[500] = "cl.exe -c -D_WIN32 -DUSE_DL_EXPORT -D_WINDOWS -DWIN32 -D_WINDLL "; + int do_unlink, result; + if (argc != 2) { + fprintf(stderr, "make_buildinfo $(ConfigurationName)\n"); + return EXIT_FAILURE; + } + if (strcmp(argv[1], "Release") == 0) { + strcat_s(command, CMD_SIZE, "-MD "); + } + else if (strcmp(argv[1], "Debug") == 0) { + strcat_s(command, CMD_SIZE, "-D_DEBUG -MDd "); + } + else if (strcmp(argv[1], "ReleaseItanium") == 0) { + strcat_s(command, CMD_SIZE, "-MD /USECL:MS_ITANIUM "); + } + else if (strcmp(argv[1], "ReleaseAMD64") == 0) { + strcat_s(command, CMD_SIZE, "-MD "); + strcat_s(command, CMD_SIZE, "-MD /USECL:MS_OPTERON "); + } + else { + fprintf(stderr, "unsupported configuration %s\n", argv[1]); + return EXIT_FAILURE; + } - if ((do_unlink = make_buildinfo2())) - strcat_s(command, CMD_SIZE, "getbuildinfo2.c -DSUBWCREV "); - else - strcat_s(command, CMD_SIZE, "..\\Modules\\getbuildinfo.c"); - strcat_s(command, CMD_SIZE, " -Fogetbuildinfo.o -I..\\Include -I..\\PC"); - puts(command); fflush(stdout); - result = system(command); - if (do_unlink) - _unlink("getbuildinfo2.c"); - if (result < 0) - return EXIT_FAILURE; - return 0; -} \ No newline at end of file + if ((do_unlink = make_buildinfo2())) + strcat_s(command, CMD_SIZE, "getbuildinfo2.c -DSUBWCREV "); + else + strcat_s(command, CMD_SIZE, "..\\Modules\\getbuildinfo.c"); + strcat_s(command, CMD_SIZE, " -Fogetbuildinfo.o -I..\\Include -I..\\PC"); + puts(command); fflush(stdout); + result = system(command); + if (do_unlink) + _unlink("getbuildinfo2.c"); + if (result < 0) + return EXIT_FAILURE; + return 0; +} Modified: python/branches/release31-maint/Parser/acceler.c ============================================================================== --- python/branches/release31-maint/Parser/acceler.c (original) +++ python/branches/release31-maint/Parser/acceler.c Sun May 9 18:14:21 2010 @@ -23,103 +23,103 @@ void PyGrammar_AddAccelerators(grammar *g) { - dfa *d; - int i; - d = g->g_dfa; - for (i = g->g_ndfas; --i >= 0; d++) - fixdfa(g, d); - g->g_accel = 1; + dfa *d; + int i; + d = g->g_dfa; + for (i = g->g_ndfas; --i >= 0; d++) + fixdfa(g, d); + g->g_accel = 1; } void PyGrammar_RemoveAccelerators(grammar *g) { - dfa *d; - int i; - g->g_accel = 0; - d = g->g_dfa; - for (i = g->g_ndfas; --i >= 0; d++) { - state *s; - int j; - s = d->d_state; - for (j = 0; j < d->d_nstates; j++, s++) { - if (s->s_accel) - PyObject_FREE(s->s_accel); - s->s_accel = NULL; - } - } + dfa *d; + int i; + g->g_accel = 0; + d = g->g_dfa; + for (i = g->g_ndfas; --i >= 0; d++) { + state *s; + int j; + s = d->d_state; + for (j = 0; j < d->d_nstates; j++, s++) { + if (s->s_accel) + PyObject_FREE(s->s_accel); + s->s_accel = NULL; + } + } } static void fixdfa(grammar *g, dfa *d) { - state *s; - int j; - s = d->d_state; - for (j = 0; j < d->d_nstates; j++, s++) - fixstate(g, s); + state *s; + int j; + s = d->d_state; + for (j = 0; j < d->d_nstates; j++, s++) + fixstate(g, s); } static void fixstate(grammar *g, state *s) { - arc *a; - int k; - int *accel; - int nl = g->g_ll.ll_nlabels; - s->s_accept = 0; - accel = (int *) PyObject_MALLOC(nl * sizeof(int)); - if (accel == NULL) { - fprintf(stderr, "no mem to build parser accelerators\n"); - exit(1); - } - for (k = 0; k < nl; k++) - accel[k] = -1; - a = s->s_arc; - for (k = s->s_narcs; --k >= 0; a++) { - int lbl = a->a_lbl; - label *l = &g->g_ll.ll_label[lbl]; - int type = l->lb_type; - if (a->a_arrow >= (1 << 7)) { - printf("XXX too many states!\n"); - continue; - } - if (ISNONTERMINAL(type)) { - dfa *d1 = PyGrammar_FindDFA(g, type); - int ibit; - if (type - NT_OFFSET >= (1 << 7)) { - printf("XXX too high nonterminal number!\n"); - continue; - } - for (ibit = 0; ibit < g->g_ll.ll_nlabels; ibit++) { - if (testbit(d1->d_first, ibit)) { - if (accel[ibit] != -1) - printf("XXX ambiguity!\n"); - accel[ibit] = a->a_arrow | (1 << 7) | - ((type - NT_OFFSET) << 8); - } - } - } - else if (lbl == EMPTY) - s->s_accept = 1; - else if (lbl >= 0 && lbl < nl) - accel[lbl] = a->a_arrow; - } - while (nl > 0 && accel[nl-1] == -1) - nl--; - for (k = 0; k < nl && accel[k] == -1;) - k++; - if (k < nl) { - int i; - s->s_accel = (int *) PyObject_MALLOC((nl-k) * sizeof(int)); - if (s->s_accel == NULL) { - fprintf(stderr, "no mem to add parser accelerators\n"); - exit(1); - } - s->s_lower = k; - s->s_upper = nl; - for (i = 0; k < nl; i++, k++) - s->s_accel[i] = accel[k]; - } - PyObject_FREE(accel); + arc *a; + int k; + int *accel; + int nl = g->g_ll.ll_nlabels; + s->s_accept = 0; + accel = (int *) PyObject_MALLOC(nl * sizeof(int)); + if (accel == NULL) { + fprintf(stderr, "no mem to build parser accelerators\n"); + exit(1); + } + for (k = 0; k < nl; k++) + accel[k] = -1; + a = s->s_arc; + for (k = s->s_narcs; --k >= 0; a++) { + int lbl = a->a_lbl; + label *l = &g->g_ll.ll_label[lbl]; + int type = l->lb_type; + if (a->a_arrow >= (1 << 7)) { + printf("XXX too many states!\n"); + continue; + } + if (ISNONTERMINAL(type)) { + dfa *d1 = PyGrammar_FindDFA(g, type); + int ibit; + if (type - NT_OFFSET >= (1 << 7)) { + printf("XXX too high nonterminal number!\n"); + continue; + } + for (ibit = 0; ibit < g->g_ll.ll_nlabels; ibit++) { + if (testbit(d1->d_first, ibit)) { + if (accel[ibit] != -1) + printf("XXX ambiguity!\n"); + accel[ibit] = a->a_arrow | (1 << 7) | + ((type - NT_OFFSET) << 8); + } + } + } + else if (lbl == EMPTY) + s->s_accept = 1; + else if (lbl >= 0 && lbl < nl) + accel[lbl] = a->a_arrow; + } + while (nl > 0 && accel[nl-1] == -1) + nl--; + for (k = 0; k < nl && accel[k] == -1;) + k++; + if (k < nl) { + int i; + s->s_accel = (int *) PyObject_MALLOC((nl-k) * sizeof(int)); + if (s->s_accel == NULL) { + fprintf(stderr, "no mem to add parser accelerators\n"); + exit(1); + } + s->s_lower = k; + s->s_upper = nl; + for (i = 0; k < nl; i++, k++) + s->s_accel[i] = accel[k]; + } + PyObject_FREE(accel); } Modified: python/branches/release31-maint/Parser/bitset.c ============================================================================== --- python/branches/release31-maint/Parser/bitset.c (original) +++ python/branches/release31-maint/Parser/bitset.c Sun May 9 18:14:21 2010 @@ -7,60 +7,60 @@ bitset newbitset(int nbits) { - int nbytes = NBYTES(nbits); - bitset ss = (char *)PyObject_MALLOC(sizeof(BYTE) * nbytes); - - if (ss == NULL) - Py_FatalError("no mem for bitset"); - - ss += nbytes; - while (--nbytes >= 0) - *--ss = 0; - return ss; + int nbytes = NBYTES(nbits); + bitset ss = (char *)PyObject_MALLOC(sizeof(BYTE) * nbytes); + + if (ss == NULL) + Py_FatalError("no mem for bitset"); + + ss += nbytes; + while (--nbytes >= 0) + *--ss = 0; + return ss; } void delbitset(bitset ss) { - PyObject_FREE(ss); + PyObject_FREE(ss); } int addbit(bitset ss, int ibit) { - int ibyte = BIT2BYTE(ibit); - BYTE mask = BIT2MASK(ibit); - - if (ss[ibyte] & mask) - return 0; /* Bit already set */ - ss[ibyte] |= mask; - return 1; + int ibyte = BIT2BYTE(ibit); + BYTE mask = BIT2MASK(ibit); + + if (ss[ibyte] & mask) + return 0; /* Bit already set */ + ss[ibyte] |= mask; + return 1; } #if 0 /* Now a macro */ int testbit(bitset ss, int ibit) { - return (ss[BIT2BYTE(ibit)] & BIT2MASK(ibit)) != 0; + return (ss[BIT2BYTE(ibit)] & BIT2MASK(ibit)) != 0; } #endif int samebitset(bitset ss1, bitset ss2, int nbits) { - int i; - - for (i = NBYTES(nbits); --i >= 0; ) - if (*ss1++ != *ss2++) - return 0; - return 1; + int i; + + for (i = NBYTES(nbits); --i >= 0; ) + if (*ss1++ != *ss2++) + return 0; + return 1; } void mergebitset(bitset ss1, bitset ss2, int nbits) { - int i; - - for (i = NBYTES(nbits); --i >= 0; ) - *ss1++ |= *ss2++; + int i; + + for (i = NBYTES(nbits); --i >= 0; ) + *ss1++ |= *ss2++; } Modified: python/branches/release31-maint/Parser/firstsets.c ============================================================================== --- python/branches/release31-maint/Parser/firstsets.c (original) +++ python/branches/release31-maint/Parser/firstsets.c Sun May 9 18:14:21 2010 @@ -13,101 +13,101 @@ void addfirstsets(grammar *g) { - int i; - dfa *d; + int i; + dfa *d; - if (Py_DebugFlag) - printf("Adding FIRST sets ...\n"); - for (i = 0; i < g->g_ndfas; i++) { - d = &g->g_dfa[i]; - if (d->d_first == NULL) - calcfirstset(g, d); - } + if (Py_DebugFlag) + printf("Adding FIRST sets ...\n"); + for (i = 0; i < g->g_ndfas; i++) { + d = &g->g_dfa[i]; + if (d->d_first == NULL) + calcfirstset(g, d); + } } static void calcfirstset(grammar *g, dfa *d) { - int i, j; - state *s; - arc *a; - int nsyms; - int *sym; - int nbits; - static bitset dummy; - bitset result; - int type; - dfa *d1; - label *l0; - - if (Py_DebugFlag) - printf("Calculate FIRST set for '%s'\n", d->d_name); - - if (dummy == NULL) - dummy = newbitset(1); - if (d->d_first == dummy) { - fprintf(stderr, "Left-recursion for '%s'\n", d->d_name); - return; - } - if (d->d_first != NULL) { - fprintf(stderr, "Re-calculating FIRST set for '%s' ???\n", - d->d_name); - } - d->d_first = dummy; - - l0 = g->g_ll.ll_label; - nbits = g->g_ll.ll_nlabels; - result = newbitset(nbits); - - sym = (int *)PyObject_MALLOC(sizeof(int)); - if (sym == NULL) - Py_FatalError("no mem for new sym in calcfirstset"); - nsyms = 1; - sym[0] = findlabel(&g->g_ll, d->d_type, (char *)NULL); - - s = &d->d_state[d->d_initial]; - for (i = 0; i < s->s_narcs; i++) { - a = &s->s_arc[i]; - for (j = 0; j < nsyms; j++) { - if (sym[j] == a->a_lbl) - break; - } - if (j >= nsyms) { /* New label */ - sym = (int *)PyObject_REALLOC(sym, - sizeof(int) * (nsyms + 1)); - if (sym == NULL) - Py_FatalError( - "no mem to resize sym in calcfirstset"); - sym[nsyms++] = a->a_lbl; - type = l0[a->a_lbl].lb_type; - if (ISNONTERMINAL(type)) { - d1 = PyGrammar_FindDFA(g, type); - if (d1->d_first == dummy) { - fprintf(stderr, - "Left-recursion below '%s'\n", - d->d_name); - } - else { - if (d1->d_first == NULL) - calcfirstset(g, d1); - mergebitset(result, - d1->d_first, nbits); - } - } - else if (ISTERMINAL(type)) { - addbit(result, a->a_lbl); - } - } - } - d->d_first = result; - if (Py_DebugFlag) { - printf("FIRST set for '%s': {", d->d_name); - for (i = 0; i < nbits; i++) { - if (testbit(result, i)) - printf(" %s", PyGrammar_LabelRepr(&l0[i])); - } - printf(" }\n"); - } + int i, j; + state *s; + arc *a; + int nsyms; + int *sym; + int nbits; + static bitset dummy; + bitset result; + int type; + dfa *d1; + label *l0; - PyObject_FREE(sym); + if (Py_DebugFlag) + printf("Calculate FIRST set for '%s'\n", d->d_name); + + if (dummy == NULL) + dummy = newbitset(1); + if (d->d_first == dummy) { + fprintf(stderr, "Left-recursion for '%s'\n", d->d_name); + return; + } + if (d->d_first != NULL) { + fprintf(stderr, "Re-calculating FIRST set for '%s' ???\n", + d->d_name); + } + d->d_first = dummy; + + l0 = g->g_ll.ll_label; + nbits = g->g_ll.ll_nlabels; + result = newbitset(nbits); + + sym = (int *)PyObject_MALLOC(sizeof(int)); + if (sym == NULL) + Py_FatalError("no mem for new sym in calcfirstset"); + nsyms = 1; + sym[0] = findlabel(&g->g_ll, d->d_type, (char *)NULL); + + s = &d->d_state[d->d_initial]; + for (i = 0; i < s->s_narcs; i++) { + a = &s->s_arc[i]; + for (j = 0; j < nsyms; j++) { + if (sym[j] == a->a_lbl) + break; + } + if (j >= nsyms) { /* New label */ + sym = (int *)PyObject_REALLOC(sym, + sizeof(int) * (nsyms + 1)); + if (sym == NULL) + Py_FatalError( + "no mem to resize sym in calcfirstset"); + sym[nsyms++] = a->a_lbl; + type = l0[a->a_lbl].lb_type; + if (ISNONTERMINAL(type)) { + d1 = PyGrammar_FindDFA(g, type); + if (d1->d_first == dummy) { + fprintf(stderr, + "Left-recursion below '%s'\n", + d->d_name); + } + else { + if (d1->d_first == NULL) + calcfirstset(g, d1); + mergebitset(result, + d1->d_first, nbits); + } + } + else if (ISTERMINAL(type)) { + addbit(result, a->a_lbl); + } + } + } + d->d_first = result; + if (Py_DebugFlag) { + printf("FIRST set for '%s': {", d->d_name); + for (i = 0; i < nbits; i++) { + if (testbit(result, i)) + printf(" %s", PyGrammar_LabelRepr(&l0[i])); + } + printf(" }\n"); + } + + PyObject_FREE(sym); } Modified: python/branches/release31-maint/Parser/grammar.c ============================================================================== --- python/branches/release31-maint/Parser/grammar.c (original) +++ python/branches/release31-maint/Parser/grammar.c Sun May 9 18:14:21 2010 @@ -14,98 +14,98 @@ grammar * newgrammar(int start) { - grammar *g; - - g = (grammar *)PyObject_MALLOC(sizeof(grammar)); - if (g == NULL) - Py_FatalError("no mem for new grammar"); - g->g_ndfas = 0; - g->g_dfa = NULL; - g->g_start = start; - g->g_ll.ll_nlabels = 0; - g->g_ll.ll_label = NULL; - g->g_accel = 0; - return g; + grammar *g; + + g = (grammar *)PyObject_MALLOC(sizeof(grammar)); + if (g == NULL) + Py_FatalError("no mem for new grammar"); + g->g_ndfas = 0; + g->g_dfa = NULL; + g->g_start = start; + g->g_ll.ll_nlabels = 0; + g->g_ll.ll_label = NULL; + g->g_accel = 0; + return g; } dfa * adddfa(grammar *g, int type, char *name) { - dfa *d; - - g->g_dfa = (dfa *)PyObject_REALLOC(g->g_dfa, - sizeof(dfa) * (g->g_ndfas + 1)); - if (g->g_dfa == NULL) - Py_FatalError("no mem to resize dfa in adddfa"); - d = &g->g_dfa[g->g_ndfas++]; - d->d_type = type; - d->d_name = strdup(name); - d->d_nstates = 0; - d->d_state = NULL; - d->d_initial = -1; - d->d_first = NULL; - return d; /* Only use while fresh! */ + dfa *d; + + g->g_dfa = (dfa *)PyObject_REALLOC(g->g_dfa, + sizeof(dfa) * (g->g_ndfas + 1)); + if (g->g_dfa == NULL) + Py_FatalError("no mem to resize dfa in adddfa"); + d = &g->g_dfa[g->g_ndfas++]; + d->d_type = type; + d->d_name = strdup(name); + d->d_nstates = 0; + d->d_state = NULL; + d->d_initial = -1; + d->d_first = NULL; + return d; /* Only use while fresh! */ } int addstate(dfa *d) { - state *s; - - d->d_state = (state *)PyObject_REALLOC(d->d_state, - sizeof(state) * (d->d_nstates + 1)); - if (d->d_state == NULL) - Py_FatalError("no mem to resize state in addstate"); - s = &d->d_state[d->d_nstates++]; - s->s_narcs = 0; - s->s_arc = NULL; - s->s_lower = 0; - s->s_upper = 0; - s->s_accel = NULL; - s->s_accept = 0; - return s - d->d_state; + state *s; + + d->d_state = (state *)PyObject_REALLOC(d->d_state, + sizeof(state) * (d->d_nstates + 1)); + if (d->d_state == NULL) + Py_FatalError("no mem to resize state in addstate"); + s = &d->d_state[d->d_nstates++]; + s->s_narcs = 0; + s->s_arc = NULL; + s->s_lower = 0; + s->s_upper = 0; + s->s_accel = NULL; + s->s_accept = 0; + return s - d->d_state; } void addarc(dfa *d, int from, int to, int lbl) { - state *s; - arc *a; - - assert(0 <= from && from < d->d_nstates); - assert(0 <= to && to < d->d_nstates); - - s = &d->d_state[from]; - s->s_arc = (arc *)PyObject_REALLOC(s->s_arc, sizeof(arc) * (s->s_narcs + 1)); - if (s->s_arc == NULL) - Py_FatalError("no mem to resize arc list in addarc"); - a = &s->s_arc[s->s_narcs++]; - a->a_lbl = lbl; - a->a_arrow = to; + state *s; + arc *a; + + assert(0 <= from && from < d->d_nstates); + assert(0 <= to && to < d->d_nstates); + + s = &d->d_state[from]; + s->s_arc = (arc *)PyObject_REALLOC(s->s_arc, sizeof(arc) * (s->s_narcs + 1)); + if (s->s_arc == NULL) + Py_FatalError("no mem to resize arc list in addarc"); + a = &s->s_arc[s->s_narcs++]; + a->a_lbl = lbl; + a->a_arrow = to; } int addlabel(labellist *ll, int type, char *str) { - int i; - label *lb; - - for (i = 0; i < ll->ll_nlabels; i++) { - if (ll->ll_label[i].lb_type == type && - strcmp(ll->ll_label[i].lb_str, str) == 0) - return i; - } - ll->ll_label = (label *)PyObject_REALLOC(ll->ll_label, - sizeof(label) * (ll->ll_nlabels + 1)); - if (ll->ll_label == NULL) - Py_FatalError("no mem to resize labellist in addlabel"); - lb = &ll->ll_label[ll->ll_nlabels++]; - lb->lb_type = type; - lb->lb_str = strdup(str); - if (Py_DebugFlag) - printf("Label @ %8p, %d: %s\n", ll, ll->ll_nlabels, - PyGrammar_LabelRepr(lb)); - return lb - ll->ll_label; + int i; + label *lb; + + for (i = 0; i < ll->ll_nlabels; i++) { + if (ll->ll_label[i].lb_type == type && + strcmp(ll->ll_label[i].lb_str, str) == 0) + return i; + } + ll->ll_label = (label *)PyObject_REALLOC(ll->ll_label, + sizeof(label) * (ll->ll_nlabels + 1)); + if (ll->ll_label == NULL) + Py_FatalError("no mem to resize labellist in addlabel"); + lb = &ll->ll_label[ll->ll_nlabels++]; + lb->lb_type = type; + lb->lb_str = strdup(str); + if (Py_DebugFlag) + printf("Label @ %8p, %d: %s\n", ll, ll->ll_nlabels, + PyGrammar_LabelRepr(lb)); + return lb - ll->ll_label; } /* Same, but rather dies than adds */ @@ -113,16 +113,16 @@ int findlabel(labellist *ll, int type, char *str) { - int i; - - for (i = 0; i < ll->ll_nlabels; i++) { - if (ll->ll_label[i].lb_type == type /*&& - strcmp(ll->ll_label[i].lb_str, str) == 0*/) - return i; - } - fprintf(stderr, "Label %d/'%s' not found\n", type, str); - Py_FatalError("grammar.c:findlabel()"); - return 0; /* Make gcc -Wall happy */ + int i; + + for (i = 0; i < ll->ll_nlabels; i++) { + if (ll->ll_label[i].lb_type == type /*&& + strcmp(ll->ll_label[i].lb_str, str) == 0*/) + return i; + } + fprintf(stderr, "Label %d/'%s' not found\n", type, str); + Py_FatalError("grammar.c:findlabel()"); + return 0; /* Make gcc -Wall happy */ } /* Forward */ @@ -131,120 +131,120 @@ void translatelabels(grammar *g) { - int i; + int i; #ifdef Py_DEBUG - printf("Translating labels ...\n"); + printf("Translating labels ...\n"); #endif - /* Don't translate EMPTY */ - for (i = EMPTY+1; i < g->g_ll.ll_nlabels; i++) - translabel(g, &g->g_ll.ll_label[i]); + /* Don't translate EMPTY */ + for (i = EMPTY+1; i < g->g_ll.ll_nlabels; i++) + translabel(g, &g->g_ll.ll_label[i]); } static void translabel(grammar *g, label *lb) { - int i; - - if (Py_DebugFlag) - printf("Translating label %s ...\n", PyGrammar_LabelRepr(lb)); - - if (lb->lb_type == NAME) { - for (i = 0; i < g->g_ndfas; i++) { - if (strcmp(lb->lb_str, g->g_dfa[i].d_name) == 0) { - if (Py_DebugFlag) - printf( - "Label %s is non-terminal %d.\n", - lb->lb_str, - g->g_dfa[i].d_type); - lb->lb_type = g->g_dfa[i].d_type; - free(lb->lb_str); - lb->lb_str = NULL; - return; - } - } - for (i = 0; i < (int)N_TOKENS; i++) { - if (strcmp(lb->lb_str, _PyParser_TokenNames[i]) == 0) { - if (Py_DebugFlag) - printf("Label %s is terminal %d.\n", - lb->lb_str, i); - lb->lb_type = i; - free(lb->lb_str); - lb->lb_str = NULL; - return; - } - } - printf("Can't translate NAME label '%s'\n", lb->lb_str); - return; - } - - if (lb->lb_type == STRING) { - if (isalpha(Py_CHARMASK(lb->lb_str[1])) || - lb->lb_str[1] == '_') { - char *p; - char *src; - char *dest; - size_t name_len; - if (Py_DebugFlag) - printf("Label %s is a keyword\n", lb->lb_str); - lb->lb_type = NAME; - src = lb->lb_str + 1; - p = strchr(src, '\''); - if (p) - name_len = p - src; - else - name_len = strlen(src); - dest = (char *)malloc(name_len + 1); - if (!dest) { - printf("Can't alloc dest '%s'\n", src); - return; - } - strncpy(dest, src, name_len); - dest[name_len] = '\0'; - free(lb->lb_str); - lb->lb_str = dest; - } - else if (lb->lb_str[2] == lb->lb_str[0]) { - int type = (int) PyToken_OneChar(lb->lb_str[1]); - if (type != OP) { - lb->lb_type = type; - free(lb->lb_str); - lb->lb_str = NULL; - } - else - printf("Unknown OP label %s\n", - lb->lb_str); - } - else if (lb->lb_str[2] && lb->lb_str[3] == lb->lb_str[0]) { - int type = (int) PyToken_TwoChars(lb->lb_str[1], - lb->lb_str[2]); - if (type != OP) { - lb->lb_type = type; - free(lb->lb_str); - lb->lb_str = NULL; - } - else - printf("Unknown OP label %s\n", - lb->lb_str); - } - else if (lb->lb_str[2] && lb->lb_str[3] && lb->lb_str[4] == lb->lb_str[0]) { - int type = (int) PyToken_ThreeChars(lb->lb_str[1], - lb->lb_str[2], - lb->lb_str[3]); - if (type != OP) { - lb->lb_type = type; - free(lb->lb_str); - lb->lb_str = NULL; - } - else - printf("Unknown OP label %s\n", - lb->lb_str); - } - else - printf("Can't translate STRING label %s\n", - lb->lb_str); - } - else - printf("Can't translate label '%s'\n", - PyGrammar_LabelRepr(lb)); + int i; + + if (Py_DebugFlag) + printf("Translating label %s ...\n", PyGrammar_LabelRepr(lb)); + + if (lb->lb_type == NAME) { + for (i = 0; i < g->g_ndfas; i++) { + if (strcmp(lb->lb_str, g->g_dfa[i].d_name) == 0) { + if (Py_DebugFlag) + printf( + "Label %s is non-terminal %d.\n", + lb->lb_str, + g->g_dfa[i].d_type); + lb->lb_type = g->g_dfa[i].d_type; + free(lb->lb_str); + lb->lb_str = NULL; + return; + } + } + for (i = 0; i < (int)N_TOKENS; i++) { + if (strcmp(lb->lb_str, _PyParser_TokenNames[i]) == 0) { + if (Py_DebugFlag) + printf("Label %s is terminal %d.\n", + lb->lb_str, i); + lb->lb_type = i; + free(lb->lb_str); + lb->lb_str = NULL; + return; + } + } + printf("Can't translate NAME label '%s'\n", lb->lb_str); + return; + } + + if (lb->lb_type == STRING) { + if (isalpha(Py_CHARMASK(lb->lb_str[1])) || + lb->lb_str[1] == '_') { + char *p; + char *src; + char *dest; + size_t name_len; + if (Py_DebugFlag) + printf("Label %s is a keyword\n", lb->lb_str); + lb->lb_type = NAME; + src = lb->lb_str + 1; + p = strchr(src, '\''); + if (p) + name_len = p - src; + else + name_len = strlen(src); + dest = (char *)malloc(name_len + 1); + if (!dest) { + printf("Can't alloc dest '%s'\n", src); + return; + } + strncpy(dest, src, name_len); + dest[name_len] = '\0'; + free(lb->lb_str); + lb->lb_str = dest; + } + else if (lb->lb_str[2] == lb->lb_str[0]) { + int type = (int) PyToken_OneChar(lb->lb_str[1]); + if (type != OP) { + lb->lb_type = type; + free(lb->lb_str); + lb->lb_str = NULL; + } + else + printf("Unknown OP label %s\n", + lb->lb_str); + } + else if (lb->lb_str[2] && lb->lb_str[3] == lb->lb_str[0]) { + int type = (int) PyToken_TwoChars(lb->lb_str[1], + lb->lb_str[2]); + if (type != OP) { + lb->lb_type = type; + free(lb->lb_str); + lb->lb_str = NULL; + } + else + printf("Unknown OP label %s\n", + lb->lb_str); + } + else if (lb->lb_str[2] && lb->lb_str[3] && lb->lb_str[4] == lb->lb_str[0]) { + int type = (int) PyToken_ThreeChars(lb->lb_str[1], + lb->lb_str[2], + lb->lb_str[3]); + if (type != OP) { + lb->lb_type = type; + free(lb->lb_str); + lb->lb_str = NULL; + } + else + printf("Unknown OP label %s\n", + lb->lb_str); + } + else + printf("Can't translate STRING label %s\n", + lb->lb_str); + } + else + printf("Can't translate label '%s'\n", + PyGrammar_LabelRepr(lb)); } Modified: python/branches/release31-maint/Parser/grammar1.c ============================================================================== --- python/branches/release31-maint/Parser/grammar1.c (original) +++ python/branches/release31-maint/Parser/grammar1.c Sun May 9 18:14:21 2010 @@ -11,47 +11,47 @@ dfa * PyGrammar_FindDFA(grammar *g, register int type) { - register dfa *d; + register dfa *d; #if 1 - /* Massive speed-up */ - d = &g->g_dfa[type - NT_OFFSET]; - assert(d->d_type == type); - return d; + /* Massive speed-up */ + d = &g->g_dfa[type - NT_OFFSET]; + assert(d->d_type == type); + return d; #else - /* Old, slow version */ - register int i; - - for (i = g->g_ndfas, d = g->g_dfa; --i >= 0; d++) { - if (d->d_type == type) - return d; - } - assert(0); - /* NOTREACHED */ + /* Old, slow version */ + register int i; + + for (i = g->g_ndfas, d = g->g_dfa; --i >= 0; d++) { + if (d->d_type == type) + return d; + } + assert(0); + /* NOTREACHED */ #endif } char * PyGrammar_LabelRepr(label *lb) { - static char buf[100]; - - if (lb->lb_type == ENDMARKER) - return "EMPTY"; - else if (ISNONTERMINAL(lb->lb_type)) { - if (lb->lb_str == NULL) { - PyOS_snprintf(buf, sizeof(buf), "NT%d", lb->lb_type); - return buf; - } - else - return lb->lb_str; - } - else { - if (lb->lb_str == NULL) - return _PyParser_TokenNames[lb->lb_type]; - else { - PyOS_snprintf(buf, sizeof(buf), "%.32s(%.32s)", - _PyParser_TokenNames[lb->lb_type], lb->lb_str); - return buf; - } - } + static char buf[100]; + + if (lb->lb_type == ENDMARKER) + return "EMPTY"; + else if (ISNONTERMINAL(lb->lb_type)) { + if (lb->lb_str == NULL) { + PyOS_snprintf(buf, sizeof(buf), "NT%d", lb->lb_type); + return buf; + } + else + return lb->lb_str; + } + else { + if (lb->lb_str == NULL) + return _PyParser_TokenNames[lb->lb_type]; + else { + PyOS_snprintf(buf, sizeof(buf), "%.32s(%.32s)", + _PyParser_TokenNames[lb->lb_type], lb->lb_str); + return buf; + } + } } Modified: python/branches/release31-maint/Parser/intrcheck.c ============================================================================== --- python/branches/release31-maint/Parser/intrcheck.c (original) +++ python/branches/release31-maint/Parser/intrcheck.c Sun May 9 18:14:21 2010 @@ -21,7 +21,7 @@ int PyOS_InterruptOccurred(void) { - _wyield(); + _wyield(); } #define OK @@ -47,7 +47,7 @@ void PyOS_InitInterrupts(void) { - _go32_want_ctrl_break(1 /* TRUE */); + _go32_want_ctrl_break(1 /* TRUE */); } void @@ -58,7 +58,7 @@ int PyOS_InterruptOccurred(void) { - return _go32_was_ctrl_break_hit(); + return _go32_was_ctrl_break_hit(); } #else /* !__GNUC__ */ @@ -78,12 +78,12 @@ int PyOS_InterruptOccurred(void) { - int interrupted = 0; - while (kbhit()) { - if (getch() == '\003') - interrupted = 1; - } - return interrupted; + int interrupted = 0; + while (kbhit()) { + if (getch() == '\003') + interrupted = 1; + } + return interrupted; } #endif /* __GNUC__ */ @@ -106,7 +106,7 @@ void PyErr_SetInterrupt(void) { - interrupted = 1; + interrupted = 1; } extern int PyErr_CheckSignals(void); @@ -114,28 +114,28 @@ static int checksignals_witharg(void * arg) { - return PyErr_CheckSignals(); + return PyErr_CheckSignals(); } static void intcatcher(int sig) { - extern void Py_Exit(int); - static char message[] = + extern void Py_Exit(int); + static char message[] = "python: to interrupt a truly hanging Python program, interrupt once more.\n"; - switch (interrupted++) { - case 0: - break; - case 1: - write(2, message, strlen(message)); - break; - case 2: - interrupted = 0; - Py_Exit(1); - break; - } - PyOS_setsig(SIGINT, intcatcher); - Py_AddPendingCall(checksignals_witharg, NULL); + switch (interrupted++) { + case 0: + break; + case 1: + write(2, message, strlen(message)); + break; + case 2: + interrupted = 0; + Py_Exit(1); + break; + } + PyOS_setsig(SIGINT, intcatcher); + Py_AddPendingCall(checksignals_witharg, NULL); } static void (*old_siginthandler)(int) = SIG_DFL; @@ -143,23 +143,23 @@ void PyOS_InitInterrupts(void) { - if ((old_siginthandler = PyOS_setsig(SIGINT, SIG_IGN)) != SIG_IGN) - PyOS_setsig(SIGINT, intcatcher); + if ((old_siginthandler = PyOS_setsig(SIGINT, SIG_IGN)) != SIG_IGN) + PyOS_setsig(SIGINT, intcatcher); } void PyOS_FiniInterrupts(void) { - PyOS_setsig(SIGINT, old_siginthandler); + PyOS_setsig(SIGINT, old_siginthandler); } int PyOS_InterruptOccurred(void) { - if (!interrupted) - return 0; - interrupted = 0; - return 1; + if (!interrupted) + return 0; + interrupted = 0; + return 1; } #endif /* !OK */ @@ -168,7 +168,7 @@ PyOS_AfterFork(void) { #ifdef WITH_THREAD - PyEval_ReInitThreads(); - PyThread_ReInitTLS(); + PyEval_ReInitThreads(); + PyThread_ReInitTLS(); #endif } Modified: python/branches/release31-maint/Parser/listnode.c ============================================================================== --- python/branches/release31-maint/Parser/listnode.c (original) +++ python/branches/release31-maint/Parser/listnode.c Sun May 9 18:14:21 2010 @@ -12,7 +12,7 @@ void PyNode_ListTree(node *n) { - listnode(stdout, n); + listnode(stdout, n); } static int level, atbol; @@ -20,47 +20,47 @@ static void listnode(FILE *fp, node *n) { - level = 0; - atbol = 1; - list1node(fp, n); + level = 0; + atbol = 1; + list1node(fp, n); } static void list1node(FILE *fp, node *n) { - if (n == 0) - return; - if (ISNONTERMINAL(TYPE(n))) { - int i; - for (i = 0; i < NCH(n); i++) - list1node(fp, CHILD(n, i)); - } - else if (ISTERMINAL(TYPE(n))) { - switch (TYPE(n)) { - case INDENT: - ++level; - break; - case DEDENT: - --level; - break; - default: - if (atbol) { - int i; - for (i = 0; i < level; ++i) - fprintf(fp, "\t"); - atbol = 0; - } - if (TYPE(n) == NEWLINE) { - if (STR(n) != NULL) - fprintf(fp, "%s", STR(n)); - fprintf(fp, "\n"); - atbol = 1; - } - else - fprintf(fp, "%s ", STR(n)); - break; - } - } - else - fprintf(fp, "? "); + if (n == 0) + return; + if (ISNONTERMINAL(TYPE(n))) { + int i; + for (i = 0; i < NCH(n); i++) + list1node(fp, CHILD(n, i)); + } + else if (ISTERMINAL(TYPE(n))) { + switch (TYPE(n)) { + case INDENT: + ++level; + break; + case DEDENT: + --level; + break; + default: + if (atbol) { + int i; + for (i = 0; i < level; ++i) + fprintf(fp, "\t"); + atbol = 0; + } + if (TYPE(n) == NEWLINE) { + if (STR(n) != NULL) + fprintf(fp, "%s", STR(n)); + fprintf(fp, "\n"); + atbol = 1; + } + else + fprintf(fp, "%s ", STR(n)); + break; + } + } + else + fprintf(fp, "? "); } Modified: python/branches/release31-maint/Parser/metagrammar.c ============================================================================== --- python/branches/release31-maint/Parser/metagrammar.c (original) +++ python/branches/release31-maint/Parser/metagrammar.c Sun May 9 18:14:21 2010 @@ -4,152 +4,152 @@ #include "grammar.h" #include "pgen.h" static arc arcs_0_0[3] = { - {2, 0}, - {3, 0}, - {4, 1}, + {2, 0}, + {3, 0}, + {4, 1}, }; static arc arcs_0_1[1] = { - {0, 1}, + {0, 1}, }; static state states_0[2] = { - {3, arcs_0_0}, - {1, arcs_0_1}, + {3, arcs_0_0}, + {1, arcs_0_1}, }; static arc arcs_1_0[1] = { - {5, 1}, + {5, 1}, }; static arc arcs_1_1[1] = { - {6, 2}, + {6, 2}, }; static arc arcs_1_2[1] = { - {7, 3}, + {7, 3}, }; static arc arcs_1_3[1] = { - {3, 4}, + {3, 4}, }; static arc arcs_1_4[1] = { - {0, 4}, + {0, 4}, }; static state states_1[5] = { - {1, arcs_1_0}, - {1, arcs_1_1}, - {1, arcs_1_2}, - {1, arcs_1_3}, - {1, arcs_1_4}, + {1, arcs_1_0}, + {1, arcs_1_1}, + {1, arcs_1_2}, + {1, arcs_1_3}, + {1, arcs_1_4}, }; static arc arcs_2_0[1] = { - {8, 1}, + {8, 1}, }; static arc arcs_2_1[2] = { - {9, 0}, - {0, 1}, + {9, 0}, + {0, 1}, }; static state states_2[2] = { - {1, arcs_2_0}, - {2, arcs_2_1}, + {1, arcs_2_0}, + {2, arcs_2_1}, }; static arc arcs_3_0[1] = { - {10, 1}, + {10, 1}, }; static arc arcs_3_1[2] = { - {10, 1}, - {0, 1}, + {10, 1}, + {0, 1}, }; static state states_3[2] = { - {1, arcs_3_0}, - {2, arcs_3_1}, + {1, arcs_3_0}, + {2, arcs_3_1}, }; static arc arcs_4_0[2] = { - {11, 1}, - {13, 2}, + {11, 1}, + {13, 2}, }; static arc arcs_4_1[1] = { - {7, 3}, + {7, 3}, }; static arc arcs_4_2[3] = { - {14, 4}, - {15, 4}, - {0, 2}, + {14, 4}, + {15, 4}, + {0, 2}, }; static arc arcs_4_3[1] = { - {12, 4}, + {12, 4}, }; static arc arcs_4_4[1] = { - {0, 4}, + {0, 4}, }; static state states_4[5] = { - {2, arcs_4_0}, - {1, arcs_4_1}, - {3, arcs_4_2}, - {1, arcs_4_3}, - {1, arcs_4_4}, + {2, arcs_4_0}, + {1, arcs_4_1}, + {3, arcs_4_2}, + {1, arcs_4_3}, + {1, arcs_4_4}, }; static arc arcs_5_0[3] = { - {5, 1}, - {16, 1}, - {17, 2}, + {5, 1}, + {16, 1}, + {17, 2}, }; static arc arcs_5_1[1] = { - {0, 1}, + {0, 1}, }; static arc arcs_5_2[1] = { - {7, 3}, + {7, 3}, }; static arc arcs_5_3[1] = { - {18, 1}, + {18, 1}, }; static state states_5[4] = { - {3, arcs_5_0}, - {1, arcs_5_1}, - {1, arcs_5_2}, - {1, arcs_5_3}, + {3, arcs_5_0}, + {1, arcs_5_1}, + {1, arcs_5_2}, + {1, arcs_5_3}, }; static dfa dfas[6] = { - {256, "MSTART", 0, 2, states_0, - "\070\000\000"}, - {257, "RULE", 0, 5, states_1, - "\040\000\000"}, - {258, "RHS", 0, 2, states_2, - "\040\010\003"}, - {259, "ALT", 0, 2, states_3, - "\040\010\003"}, - {260, "ITEM", 0, 5, states_4, - "\040\010\003"}, - {261, "ATOM", 0, 4, states_5, - "\040\000\003"}, + {256, "MSTART", 0, 2, states_0, + "\070\000\000"}, + {257, "RULE", 0, 5, states_1, + "\040\000\000"}, + {258, "RHS", 0, 2, states_2, + "\040\010\003"}, + {259, "ALT", 0, 2, states_3, + "\040\010\003"}, + {260, "ITEM", 0, 5, states_4, + "\040\010\003"}, + {261, "ATOM", 0, 4, states_5, + "\040\000\003"}, }; static label labels[19] = { - {0, "EMPTY"}, - {256, 0}, - {257, 0}, - {4, 0}, - {0, 0}, - {1, 0}, - {11, 0}, - {258, 0}, - {259, 0}, - {18, 0}, - {260, 0}, - {9, 0}, - {10, 0}, - {261, 0}, - {16, 0}, - {14, 0}, - {3, 0}, - {7, 0}, - {8, 0}, + {0, "EMPTY"}, + {256, 0}, + {257, 0}, + {4, 0}, + {0, 0}, + {1, 0}, + {11, 0}, + {258, 0}, + {259, 0}, + {18, 0}, + {260, 0}, + {9, 0}, + {10, 0}, + {261, 0}, + {16, 0}, + {14, 0}, + {3, 0}, + {7, 0}, + {8, 0}, }; static grammar _PyParser_Grammar = { - 6, - dfas, - {19, labels}, - 256 + 6, + dfas, + {19, labels}, + 256 }; grammar * meta_grammar(void) { - return &_PyParser_Grammar; + return &_PyParser_Grammar; } grammar * Modified: python/branches/release31-maint/Parser/myreadline.c ============================================================================== --- python/branches/release31-maint/Parser/myreadline.c (original) +++ python/branches/release31-maint/Parser/myreadline.c Sun May 9 18:14:21 2010 @@ -35,67 +35,67 @@ static int my_fgets(char *buf, int len, FILE *fp) { - char *p; - for (;;) { - if (PyOS_InputHook != NULL) - (void)(PyOS_InputHook)(); - errno = 0; - p = fgets(buf, len, fp); - if (p != NULL) - return 0; /* No error */ + char *p; + for (;;) { + if (PyOS_InputHook != NULL) + (void)(PyOS_InputHook)(); + errno = 0; + p = fgets(buf, len, fp); + if (p != NULL) + return 0; /* No error */ #ifdef MS_WINDOWS - /* In the case of a Ctrl+C or some other external event - interrupting the operation: - Win2k/NT: ERROR_OPERATION_ABORTED is the most recent Win32 - error code (and feof() returns TRUE). - Win9x: Ctrl+C seems to have no effect on fgets() returning - early - the signal handler is called, but the fgets() - only returns "normally" (ie, when Enter hit or feof()) - */ - if (GetLastError()==ERROR_OPERATION_ABORTED) { - /* Signals come asynchronously, so we sleep a brief - moment before checking if the handler has been - triggered (we cant just return 1 before the - signal handler has been called, as the later - signal may be treated as a separate interrupt). - */ - Sleep(1); - if (PyOS_InterruptOccurred()) { - return 1; /* Interrupt */ - } - /* Either the sleep wasn't long enough (need a - short loop retrying?) or not interrupted at all - (in which case we should revisit the whole thing!) - Logging some warning would be nice. assert is not - viable as under the debugger, the various dialogs - mean the condition is not true. - */ - } + /* In the case of a Ctrl+C or some other external event + interrupting the operation: + Win2k/NT: ERROR_OPERATION_ABORTED is the most recent Win32 + error code (and feof() returns TRUE). + Win9x: Ctrl+C seems to have no effect on fgets() returning + early - the signal handler is called, but the fgets() + only returns "normally" (ie, when Enter hit or feof()) + */ + if (GetLastError()==ERROR_OPERATION_ABORTED) { + /* Signals come asynchronously, so we sleep a brief + moment before checking if the handler has been + triggered (we cant just return 1 before the + signal handler has been called, as the later + signal may be treated as a separate interrupt). + */ + Sleep(1); + if (PyOS_InterruptOccurred()) { + return 1; /* Interrupt */ + } + /* Either the sleep wasn't long enough (need a + short loop retrying?) or not interrupted at all + (in which case we should revisit the whole thing!) + Logging some warning would be nice. assert is not + viable as under the debugger, the various dialogs + mean the condition is not true. + */ + } #endif /* MS_WINDOWS */ - if (feof(fp)) { - return -1; /* EOF */ - } + if (feof(fp)) { + return -1; /* EOF */ + } #ifdef EINTR - if (errno == EINTR) { - int s; + if (errno == EINTR) { + int s; #ifdef WITH_THREAD - PyEval_RestoreThread(_PyOS_ReadlineTState); + PyEval_RestoreThread(_PyOS_ReadlineTState); #endif - s = PyErr_CheckSignals(); + s = PyErr_CheckSignals(); #ifdef WITH_THREAD - PyEval_SaveThread(); + PyEval_SaveThread(); #endif - if (s < 0) { - return 1; - } - } -#endif - if (PyOS_InterruptOccurred()) { - return 1; /* Interrupt */ - } - return -2; /* Error */ - } - /* NOTREACHED */ + if (s < 0) { + return 1; + } + } +#endif + if (PyOS_InterruptOccurred()) { + return 1; /* Interrupt */ + } + return -2; /* Error */ + } + /* NOTREACHED */ } @@ -104,41 +104,41 @@ char * PyOS_StdioReadline(FILE *sys_stdin, FILE *sys_stdout, char *prompt) { - size_t n; - char *p; - n = 100; - if ((p = (char *)PyMem_MALLOC(n)) == NULL) - return NULL; - fflush(sys_stdout); - if (prompt) - fprintf(stderr, "%s", prompt); - fflush(stderr); - switch (my_fgets(p, (int)n, sys_stdin)) { - case 0: /* Normal case */ - break; - case 1: /* Interrupt */ - PyMem_FREE(p); - return NULL; - case -1: /* EOF */ - case -2: /* Error */ - default: /* Shouldn't happen */ - *p = '\0'; - break; - } - n = strlen(p); - while (n > 0 && p[n-1] != '\n') { - size_t incr = n+2; - p = (char *)PyMem_REALLOC(p, n + incr); - if (p == NULL) - return NULL; - if (incr > INT_MAX) { - PyErr_SetString(PyExc_OverflowError, "input line too long"); - } - if (my_fgets(p+n, (int)incr, sys_stdin) != 0) - break; - n += strlen(p+n); - } - return (char *)PyMem_REALLOC(p, n+1); + size_t n; + char *p; + n = 100; + if ((p = (char *)PyMem_MALLOC(n)) == NULL) + return NULL; + fflush(sys_stdout); + if (prompt) + fprintf(stderr, "%s", prompt); + fflush(stderr); + switch (my_fgets(p, (int)n, sys_stdin)) { + case 0: /* Normal case */ + break; + case 1: /* Interrupt */ + PyMem_FREE(p); + return NULL; + case -1: /* EOF */ + case -2: /* Error */ + default: /* Shouldn't happen */ + *p = '\0'; + break; + } + n = strlen(p); + while (n > 0 && p[n-1] != '\n') { + size_t incr = n+2; + p = (char *)PyMem_REALLOC(p, n + incr); + if (p == NULL) + return NULL; + if (incr > INT_MAX) { + PyErr_SetString(PyExc_OverflowError, "input line too long"); + } + if (my_fgets(p+n, (int)incr, sys_stdin) != 0) + break; + n += strlen(p+n); + } + return (char *)PyMem_REALLOC(p, n+1); } @@ -155,52 +155,52 @@ char * PyOS_Readline(FILE *sys_stdin, FILE *sys_stdout, char *prompt) { - char *rv; + char *rv; - if (_PyOS_ReadlineTState == PyThreadState_GET()) { - PyErr_SetString(PyExc_RuntimeError, - "can't re-enter readline"); - return NULL; - } - + if (_PyOS_ReadlineTState == PyThreadState_GET()) { + PyErr_SetString(PyExc_RuntimeError, + "can't re-enter readline"); + return NULL; + } - if (PyOS_ReadlineFunctionPointer == NULL) { + + if (PyOS_ReadlineFunctionPointer == NULL) { #ifdef __VMS - PyOS_ReadlineFunctionPointer = vms__StdioReadline; + PyOS_ReadlineFunctionPointer = vms__StdioReadline; #else - PyOS_ReadlineFunctionPointer = PyOS_StdioReadline; + PyOS_ReadlineFunctionPointer = PyOS_StdioReadline; #endif - } - + } + #ifdef WITH_THREAD - if (_PyOS_ReadlineLock == NULL) { - _PyOS_ReadlineLock = PyThread_allocate_lock(); - } + if (_PyOS_ReadlineLock == NULL) { + _PyOS_ReadlineLock = PyThread_allocate_lock(); + } #endif - _PyOS_ReadlineTState = PyThreadState_GET(); - Py_BEGIN_ALLOW_THREADS + _PyOS_ReadlineTState = PyThreadState_GET(); + Py_BEGIN_ALLOW_THREADS #ifdef WITH_THREAD - PyThread_acquire_lock(_PyOS_ReadlineLock, 1); + PyThread_acquire_lock(_PyOS_ReadlineLock, 1); #endif - /* This is needed to handle the unlikely case that the - * interpreter is in interactive mode *and* stdin/out are not - * a tty. This can happen, for example if python is run like - * this: python -i < test1.py - */ - if (!isatty (fileno (sys_stdin)) || !isatty (fileno (sys_stdout))) - rv = PyOS_StdioReadline (sys_stdin, sys_stdout, prompt); - else - rv = (*PyOS_ReadlineFunctionPointer)(sys_stdin, sys_stdout, - prompt); - Py_END_ALLOW_THREADS + /* This is needed to handle the unlikely case that the + * interpreter is in interactive mode *and* stdin/out are not + * a tty. This can happen, for example if python is run like + * this: python -i < test1.py + */ + if (!isatty (fileno (sys_stdin)) || !isatty (fileno (sys_stdout))) + rv = PyOS_StdioReadline (sys_stdin, sys_stdout, prompt); + else + rv = (*PyOS_ReadlineFunctionPointer)(sys_stdin, sys_stdout, + prompt); + Py_END_ALLOW_THREADS #ifdef WITH_THREAD - PyThread_release_lock(_PyOS_ReadlineLock); + PyThread_release_lock(_PyOS_ReadlineLock); #endif - _PyOS_ReadlineTState = NULL; + _PyOS_ReadlineTState = NULL; - return rv; + return rv; } Modified: python/branches/release31-maint/Parser/node.c ============================================================================== --- python/branches/release31-maint/Parser/node.c (original) +++ python/branches/release31-maint/Parser/node.c Sun May 9 18:14:21 2010 @@ -7,30 +7,30 @@ node * PyNode_New(int type) { - node *n = (node *) PyObject_MALLOC(1 * sizeof(node)); - if (n == NULL) - return NULL; - n->n_type = type; - n->n_str = NULL; - n->n_lineno = 0; - n->n_nchildren = 0; - n->n_child = NULL; - return n; + node *n = (node *) PyObject_MALLOC(1 * sizeof(node)); + if (n == NULL) + return NULL; + n->n_type = type; + n->n_str = NULL; + n->n_lineno = 0; + n->n_nchildren = 0; + n->n_child = NULL; + return n; } /* See comments at XXXROUNDUP below. Returns -1 on overflow. */ static int fancy_roundup(int n) { - /* Round up to the closest power of 2 >= n. */ - int result = 256; - assert(n > 128); - while (result < n) { - result <<= 1; - if (result <= 0) - return -1; - } - return result; + /* Round up to the closest power of 2 >= n. */ + int result = 256; + assert(n > 128); + while (result < n) { + result <<= 1; + if (result <= 0) + return -1; + } + return result; } /* A gimmick to make massive numbers of reallocs quicker. The result is @@ -70,46 +70,46 @@ * Note that this would be straightforward if a node stored its current * capacity. The code is tricky to avoid that. */ -#define XXXROUNDUP(n) ((n) <= 1 ? (n) : \ - (n) <= 128 ? (((n) + 3) & ~3) : \ - fancy_roundup(n)) +#define XXXROUNDUP(n) ((n) <= 1 ? (n) : \ + (n) <= 128 ? (((n) + 3) & ~3) : \ + fancy_roundup(n)) int PyNode_AddChild(register node *n1, int type, char *str, int lineno, int col_offset) { - const int nch = n1->n_nchildren; - int current_capacity; - int required_capacity; - node *n; - - if (nch == INT_MAX || nch < 0) - return E_OVERFLOW; - - current_capacity = XXXROUNDUP(nch); - required_capacity = XXXROUNDUP(nch + 1); - if (current_capacity < 0 || required_capacity < 0) - return E_OVERFLOW; - if (current_capacity < required_capacity) { - if (required_capacity > PY_SIZE_MAX / sizeof(node)) { - return E_NOMEM; - } - n = n1->n_child; - n = (node *) PyObject_REALLOC(n, - required_capacity * sizeof(node)); - if (n == NULL) - return E_NOMEM; - n1->n_child = n; - } - - n = &n1->n_child[n1->n_nchildren++]; - n->n_type = type; - n->n_str = str; - n->n_lineno = lineno; - n->n_col_offset = col_offset; - n->n_nchildren = 0; - n->n_child = NULL; - return 0; + const int nch = n1->n_nchildren; + int current_capacity; + int required_capacity; + node *n; + + if (nch == INT_MAX || nch < 0) + return E_OVERFLOW; + + current_capacity = XXXROUNDUP(nch); + required_capacity = XXXROUNDUP(nch + 1); + if (current_capacity < 0 || required_capacity < 0) + return E_OVERFLOW; + if (current_capacity < required_capacity) { + if (required_capacity > PY_SIZE_MAX / sizeof(node)) { + return E_NOMEM; + } + n = n1->n_child; + n = (node *) PyObject_REALLOC(n, + required_capacity * sizeof(node)); + if (n == NULL) + return E_NOMEM; + n1->n_child = n; + } + + n = &n1->n_child[n1->n_nchildren++]; + n->n_type = type; + n->n_str = str; + n->n_lineno = lineno; + n->n_col_offset = col_offset; + n->n_nchildren = 0; + n->n_child = NULL; + return 0; } /* Forward */ @@ -119,20 +119,20 @@ void PyNode_Free(node *n) { - if (n != NULL) { - freechildren(n); - PyObject_FREE(n); - } + if (n != NULL) { + freechildren(n); + PyObject_FREE(n); + } } static void freechildren(node *n) { - int i; - for (i = NCH(n); --i >= 0; ) - freechildren(CHILD(n, i)); - if (n->n_child != NULL) - PyObject_FREE(n->n_child); - if (STR(n) != NULL) - PyObject_FREE(STR(n)); + int i; + for (i = NCH(n); --i >= 0; ) + freechildren(CHILD(n, i)); + if (n->n_child != NULL) + PyObject_FREE(n->n_child); + if (STR(n) != NULL) + PyObject_FREE(STR(n)); } Modified: python/branches/release31-maint/Parser/parser.c ============================================================================== --- python/branches/release31-maint/Parser/parser.c (original) +++ python/branches/release31-maint/Parser/parser.c Sun May 9 18:14:21 2010 @@ -29,7 +29,7 @@ static void s_reset(stack *s) { - s->s_top = &s->s_base[MAXSTACK]; + s->s_top = &s->s_base[MAXSTACK]; } #define s_empty(s) ((s)->s_top == &(s)->s_base[MAXSTACK]) @@ -37,16 +37,16 @@ static int s_push(register stack *s, dfa *d, node *parent) { - register stackentry *top; - if (s->s_top == s->s_base) { - fprintf(stderr, "s_push: parser stack overflow\n"); - return E_NOMEM; - } - top = --s->s_top; - top->s_dfa = d; - top->s_parent = parent; - top->s_state = 0; - return 0; + register stackentry *top; + if (s->s_top == s->s_base) { + fprintf(stderr, "s_push: parser stack overflow\n"); + return E_NOMEM; + } + top = --s->s_top; + top->s_dfa = d; + top->s_parent = parent; + top->s_state = 0; + return 0; } #ifdef Py_DEBUG @@ -54,9 +54,9 @@ static void s_pop(register stack *s) { - if (s_empty(s)) - Py_FatalError("s_pop: parser stack underflow -- FATAL"); - s->s_top++; + if (s_empty(s)) + Py_FatalError("s_pop: parser stack underflow -- FATAL"); + s->s_top++; } #else /* !Py_DEBUG */ @@ -71,34 +71,34 @@ parser_state * PyParser_New(grammar *g, int start) { - parser_state *ps; - - if (!g->g_accel) - PyGrammar_AddAccelerators(g); - ps = (parser_state *)PyMem_MALLOC(sizeof(parser_state)); - if (ps == NULL) - return NULL; - ps->p_grammar = g; + parser_state *ps; + + if (!g->g_accel) + PyGrammar_AddAccelerators(g); + ps = (parser_state *)PyMem_MALLOC(sizeof(parser_state)); + if (ps == NULL) + return NULL; + ps->p_grammar = g; #ifdef PY_PARSER_REQUIRES_FUTURE_KEYWORD - ps->p_flags = 0; + ps->p_flags = 0; #endif - ps->p_tree = PyNode_New(start); - if (ps->p_tree == NULL) { - PyMem_FREE(ps); - return NULL; - } - s_reset(&ps->p_stack); - (void) s_push(&ps->p_stack, PyGrammar_FindDFA(g, start), ps->p_tree); - return ps; + ps->p_tree = PyNode_New(start); + if (ps->p_tree == NULL) { + PyMem_FREE(ps); + return NULL; + } + s_reset(&ps->p_stack); + (void) s_push(&ps->p_stack, PyGrammar_FindDFA(g, start), ps->p_tree); + return ps; } void PyParser_Delete(parser_state *ps) { - /* NB If you want to save the parse tree, - you must set p_tree to NULL before calling delparser! */ - PyNode_Free(ps->p_tree); - PyMem_FREE(ps); + /* NB If you want to save the parse tree, + you must set p_tree to NULL before calling delparser! */ + PyNode_Free(ps->p_tree); + PyMem_FREE(ps); } @@ -107,27 +107,27 @@ static int shift(register stack *s, int type, char *str, int newstate, int lineno, int col_offset) { - int err; - assert(!s_empty(s)); - err = PyNode_AddChild(s->s_top->s_parent, type, str, lineno, col_offset); - if (err) - return err; - s->s_top->s_state = newstate; - return 0; + int err; + assert(!s_empty(s)); + err = PyNode_AddChild(s->s_top->s_parent, type, str, lineno, col_offset); + if (err) + return err; + s->s_top->s_state = newstate; + return 0; } static int push(register stack *s, int type, dfa *d, int newstate, int lineno, int col_offset) { - int err; - register node *n; - n = s->s_top->s_parent; - assert(!s_empty(s)); - err = PyNode_AddChild(n, type, (char *)NULL, lineno, col_offset); - if (err) - return err; - s->s_top->s_state = newstate; - return s_push(s, d, CHILD(n, NCH(n)-1)); + int err; + register node *n; + n = s->s_top->s_parent; + assert(!s_empty(s)); + err = PyNode_AddChild(n, type, (char *)NULL, lineno, col_offset); + if (err) + return err; + s->s_top->s_state = newstate; + return s_push(s, d, CHILD(n, NCH(n)-1)); } @@ -136,47 +136,47 @@ static int classify(parser_state *ps, int type, char *str) { - grammar *g = ps->p_grammar; - register int n = g->g_ll.ll_nlabels; - - if (type == NAME) { - register char *s = str; - register label *l = g->g_ll.ll_label; - register int i; - for (i = n; i > 0; i--, l++) { - if (l->lb_type != NAME || l->lb_str == NULL || - l->lb_str[0] != s[0] || - strcmp(l->lb_str, s) != 0) - continue; + grammar *g = ps->p_grammar; + register int n = g->g_ll.ll_nlabels; + + if (type == NAME) { + register char *s = str; + register label *l = g->g_ll.ll_label; + register int i; + for (i = n; i > 0; i--, l++) { + if (l->lb_type != NAME || l->lb_str == NULL || + l->lb_str[0] != s[0] || + strcmp(l->lb_str, s) != 0) + continue; #ifdef PY_PARSER_REQUIRES_FUTURE_KEYWORD #if 0 - /* Leaving this in as an example */ - if (!(ps->p_flags & CO_FUTURE_WITH_STATEMENT)) { - if (s[0] == 'w' && strcmp(s, "with") == 0) - break; /* not a keyword yet */ - else if (s[0] == 'a' && strcmp(s, "as") == 0) - break; /* not a keyword yet */ - } + /* Leaving this in as an example */ + if (!(ps->p_flags & CO_FUTURE_WITH_STATEMENT)) { + if (s[0] == 'w' && strcmp(s, "with") == 0) + break; /* not a keyword yet */ + else if (s[0] == 'a' && strcmp(s, "as") == 0) + break; /* not a keyword yet */ + } #endif #endif - D(printf("It's a keyword\n")); - return n - i; - } - } - - { - register label *l = g->g_ll.ll_label; - register int i; - for (i = n; i > 0; i--, l++) { - if (l->lb_type == type && l->lb_str == NULL) { - D(printf("It's a token we know\n")); - return n - i; - } - } - } - - D(printf("Illegal token\n")); - return -1; + D(printf("It's a keyword\n")); + return n - i; + } + } + + { + register label *l = g->g_ll.ll_label; + register int i; + for (i = n; i > 0; i--, l++) { + if (l->lb_type == type && l->lb_str == NULL) { + D(printf("It's a token we know\n")); + return n - i; + } + } + } + + D(printf("Illegal token\n")); + return -1; } #ifdef PY_PARSER_REQUIRES_FUTURE_KEYWORD @@ -185,152 +185,152 @@ static void future_hack(parser_state *ps) { - node *n = ps->p_stack.s_top->s_parent; - node *ch, *cch; - int i; - - /* from __future__ import ..., must have at least 4 children */ - n = CHILD(n, 0); - if (NCH(n) < 4) - return; - ch = CHILD(n, 0); - if (STR(ch) == NULL || strcmp(STR(ch), "from") != 0) - return; - ch = CHILD(n, 1); - if (NCH(ch) == 1 && STR(CHILD(ch, 0)) && - strcmp(STR(CHILD(ch, 0)), "__future__") != 0) - return; - ch = CHILD(n, 3); - /* ch can be a star, a parenthesis or import_as_names */ - if (TYPE(ch) == STAR) - return; - if (TYPE(ch) == LPAR) - ch = CHILD(n, 4); - - for (i = 0; i < NCH(ch); i += 2) { - cch = CHILD(ch, i); - if (NCH(cch) >= 1 && TYPE(CHILD(cch, 0)) == NAME) { - char *str_ch = STR(CHILD(cch, 0)); - if (strcmp(str_ch, FUTURE_WITH_STATEMENT) == 0) { - ps->p_flags |= CO_FUTURE_WITH_STATEMENT; - } else if (strcmp(str_ch, FUTURE_PRINT_FUNCTION) == 0) { - ps->p_flags |= CO_FUTURE_PRINT_FUNCTION; - } else if (strcmp(str_ch, FUTURE_UNICODE_LITERALS) == 0) { - ps->p_flags |= CO_FUTURE_UNICODE_LITERALS; - } - } - } + node *n = ps->p_stack.s_top->s_parent; + node *ch, *cch; + int i; + + /* from __future__ import ..., must have at least 4 children */ + n = CHILD(n, 0); + if (NCH(n) < 4) + return; + ch = CHILD(n, 0); + if (STR(ch) == NULL || strcmp(STR(ch), "from") != 0) + return; + ch = CHILD(n, 1); + if (NCH(ch) == 1 && STR(CHILD(ch, 0)) && + strcmp(STR(CHILD(ch, 0)), "__future__") != 0) + return; + ch = CHILD(n, 3); + /* ch can be a star, a parenthesis or import_as_names */ + if (TYPE(ch) == STAR) + return; + if (TYPE(ch) == LPAR) + ch = CHILD(n, 4); + + for (i = 0; i < NCH(ch); i += 2) { + cch = CHILD(ch, i); + if (NCH(cch) >= 1 && TYPE(CHILD(cch, 0)) == NAME) { + char *str_ch = STR(CHILD(cch, 0)); + if (strcmp(str_ch, FUTURE_WITH_STATEMENT) == 0) { + ps->p_flags |= CO_FUTURE_WITH_STATEMENT; + } else if (strcmp(str_ch, FUTURE_PRINT_FUNCTION) == 0) { + ps->p_flags |= CO_FUTURE_PRINT_FUNCTION; + } else if (strcmp(str_ch, FUTURE_UNICODE_LITERALS) == 0) { + ps->p_flags |= CO_FUTURE_UNICODE_LITERALS; + } + } + } } #endif #endif /* future keyword */ int PyParser_AddToken(register parser_state *ps, register int type, char *str, - int lineno, int col_offset, int *expected_ret) + int lineno, int col_offset, int *expected_ret) { - register int ilabel; - int err; - - D(printf("Token %s/'%s' ... ", _PyParser_TokenNames[type], str)); - - /* Find out which label this token is */ - ilabel = classify(ps, type, str); - if (ilabel < 0) - return E_SYNTAX; - - /* Loop until the token is shifted or an error occurred */ - for (;;) { - /* Fetch the current dfa and state */ - register dfa *d = ps->p_stack.s_top->s_dfa; - register state *s = &d->d_state[ps->p_stack.s_top->s_state]; - - D(printf(" DFA '%s', state %d:", - d->d_name, ps->p_stack.s_top->s_state)); - - /* Check accelerator */ - if (s->s_lower <= ilabel && ilabel < s->s_upper) { - register int x = s->s_accel[ilabel - s->s_lower]; - if (x != -1) { - if (x & (1<<7)) { - /* Push non-terminal */ - int nt = (x >> 8) + NT_OFFSET; - int arrow = x & ((1<<7)-1); - dfa *d1 = PyGrammar_FindDFA( - ps->p_grammar, nt); - if ((err = push(&ps->p_stack, nt, d1, - arrow, lineno, col_offset)) > 0) { - D(printf(" MemError: push\n")); - return err; - } - D(printf(" Push ...\n")); - continue; - } - - /* Shift the token */ - if ((err = shift(&ps->p_stack, type, str, - x, lineno, col_offset)) > 0) { - D(printf(" MemError: shift.\n")); - return err; - } - D(printf(" Shift.\n")); - /* Pop while we are in an accept-only state */ - while (s = &d->d_state - [ps->p_stack.s_top->s_state], - s->s_accept && s->s_narcs == 1) { - D(printf(" DFA '%s', state %d: " - "Direct pop.\n", - d->d_name, - ps->p_stack.s_top->s_state)); + register int ilabel; + int err; + + D(printf("Token %s/'%s' ... ", _PyParser_TokenNames[type], str)); + + /* Find out which label this token is */ + ilabel = classify(ps, type, str); + if (ilabel < 0) + return E_SYNTAX; + + /* Loop until the token is shifted or an error occurred */ + for (;;) { + /* Fetch the current dfa and state */ + register dfa *d = ps->p_stack.s_top->s_dfa; + register state *s = &d->d_state[ps->p_stack.s_top->s_state]; + + D(printf(" DFA '%s', state %d:", + d->d_name, ps->p_stack.s_top->s_state)); + + /* Check accelerator */ + if (s->s_lower <= ilabel && ilabel < s->s_upper) { + register int x = s->s_accel[ilabel - s->s_lower]; + if (x != -1) { + if (x & (1<<7)) { + /* Push non-terminal */ + int nt = (x >> 8) + NT_OFFSET; + int arrow = x & ((1<<7)-1); + dfa *d1 = PyGrammar_FindDFA( + ps->p_grammar, nt); + if ((err = push(&ps->p_stack, nt, d1, + arrow, lineno, col_offset)) > 0) { + D(printf(" MemError: push\n")); + return err; + } + D(printf(" Push ...\n")); + continue; + } + + /* Shift the token */ + if ((err = shift(&ps->p_stack, type, str, + x, lineno, col_offset)) > 0) { + D(printf(" MemError: shift.\n")); + return err; + } + D(printf(" Shift.\n")); + /* Pop while we are in an accept-only state */ + while (s = &d->d_state + [ps->p_stack.s_top->s_state], + s->s_accept && s->s_narcs == 1) { + D(printf(" DFA '%s', state %d: " + "Direct pop.\n", + d->d_name, + ps->p_stack.s_top->s_state)); #ifdef PY_PARSER_REQUIRES_FUTURE_KEYWORD #if 0 - if (d->d_name[0] == 'i' && - strcmp(d->d_name, - "import_stmt") == 0) - future_hack(ps); + if (d->d_name[0] == 'i' && + strcmp(d->d_name, + "import_stmt") == 0) + future_hack(ps); #endif #endif - s_pop(&ps->p_stack); - if (s_empty(&ps->p_stack)) { - D(printf(" ACCEPT.\n")); - return E_DONE; - } - d = ps->p_stack.s_top->s_dfa; - } - return E_OK; - } - } - - if (s->s_accept) { + s_pop(&ps->p_stack); + if (s_empty(&ps->p_stack)) { + D(printf(" ACCEPT.\n")); + return E_DONE; + } + d = ps->p_stack.s_top->s_dfa; + } + return E_OK; + } + } + + if (s->s_accept) { #ifdef PY_PARSER_REQUIRES_FUTURE_KEYWORD #if 0 - if (d->d_name[0] == 'i' && - strcmp(d->d_name, "import_stmt") == 0) - future_hack(ps); + if (d->d_name[0] == 'i' && + strcmp(d->d_name, "import_stmt") == 0) + future_hack(ps); #endif #endif - /* Pop this dfa and try again */ - s_pop(&ps->p_stack); - D(printf(" Pop ...\n")); - if (s_empty(&ps->p_stack)) { - D(printf(" Error: bottom of stack.\n")); - return E_SYNTAX; - } - continue; - } - - /* Stuck, report syntax error */ - D(printf(" Error.\n")); - if (expected_ret) { - if (s->s_lower == s->s_upper - 1) { - /* Only one possible expected token */ - *expected_ret = ps->p_grammar-> - g_ll.ll_label[s->s_lower].lb_type; - } - else - *expected_ret = -1; - } - return E_SYNTAX; - } + /* Pop this dfa and try again */ + s_pop(&ps->p_stack); + D(printf(" Pop ...\n")); + if (s_empty(&ps->p_stack)) { + D(printf(" Error: bottom of stack.\n")); + return E_SYNTAX; + } + continue; + } + + /* Stuck, report syntax error */ + D(printf(" Error.\n")); + if (expected_ret) { + if (s->s_lower == s->s_upper - 1) { + /* Only one possible expected token */ + *expected_ret = ps->p_grammar-> + g_ll.ll_label[s->s_lower].lb_type; + } + else + *expected_ret = -1; + } + return E_SYNTAX; + } } @@ -341,62 +341,62 @@ void dumptree(grammar *g, node *n) { - int i; - - if (n == NULL) - printf("NIL"); - else { - label l; - l.lb_type = TYPE(n); - l.lb_str = STR(n); - printf("%s", PyGrammar_LabelRepr(&l)); - if (ISNONTERMINAL(TYPE(n))) { - printf("("); - for (i = 0; i < NCH(n); i++) { - if (i > 0) - printf(","); - dumptree(g, CHILD(n, i)); - } - printf(")"); - } - } + int i; + + if (n == NULL) + printf("NIL"); + else { + label l; + l.lb_type = TYPE(n); + l.lb_str = STR(n); + printf("%s", PyGrammar_LabelRepr(&l)); + if (ISNONTERMINAL(TYPE(n))) { + printf("("); + for (i = 0; i < NCH(n); i++) { + if (i > 0) + printf(","); + dumptree(g, CHILD(n, i)); + } + printf(")"); + } + } } void showtree(grammar *g, node *n) { - int i; - - if (n == NULL) - return; - if (ISNONTERMINAL(TYPE(n))) { - for (i = 0; i < NCH(n); i++) - showtree(g, CHILD(n, i)); - } - else if (ISTERMINAL(TYPE(n))) { - printf("%s", _PyParser_TokenNames[TYPE(n)]); - if (TYPE(n) == NUMBER || TYPE(n) == NAME) - printf("(%s)", STR(n)); - printf(" "); - } - else - printf("? "); + int i; + + if (n == NULL) + return; + if (ISNONTERMINAL(TYPE(n))) { + for (i = 0; i < NCH(n); i++) + showtree(g, CHILD(n, i)); + } + else if (ISTERMINAL(TYPE(n))) { + printf("%s", _PyParser_TokenNames[TYPE(n)]); + if (TYPE(n) == NUMBER || TYPE(n) == NAME) + printf("(%s)", STR(n)); + printf(" "); + } + else + printf("? "); } void printtree(parser_state *ps) { - if (Py_DebugFlag) { - printf("Parse tree:\n"); - dumptree(ps->p_grammar, ps->p_tree); - printf("\n"); - printf("Tokens:\n"); - showtree(ps->p_grammar, ps->p_tree); - printf("\n"); - } - printf("Listing:\n"); - PyNode_ListTree(ps->p_tree); - printf("\n"); + if (Py_DebugFlag) { + printf("Parse tree:\n"); + dumptree(ps->p_grammar, ps->p_tree); + printf("\n"); + printf("Tokens:\n"); + showtree(ps->p_grammar, ps->p_tree); + printf("\n"); + } + printf("Listing:\n"); + PyNode_ListTree(ps->p_tree); + printf("\n"); } #endif /* Py_DEBUG */ @@ -431,15 +431,15 @@ As an example, consider this grammar: -expr: term (OP term)* -term: CONSTANT | '(' expr ')' +expr: term (OP term)* +term: CONSTANT | '(' expr ')' The DFA corresponding to the rule for expr is: ------->.---term-->.-------> - ^ | - | | - \----OP----/ + ^ | + | | + \----OP----/ The parse tree generated for the input a+b is: Modified: python/branches/release31-maint/Parser/parsetok.c ============================================================================== --- python/branches/release31-maint/Parser/parsetok.c (original) +++ python/branches/release31-maint/Parser/parsetok.c Sun May 9 18:14:21 2010 @@ -19,84 +19,84 @@ node * PyParser_ParseString(const char *s, grammar *g, int start, perrdetail *err_ret) { - return PyParser_ParseStringFlagsFilename(s, NULL, g, start, err_ret, 0); + return PyParser_ParseStringFlagsFilename(s, NULL, g, start, err_ret, 0); } node * PyParser_ParseStringFlags(const char *s, grammar *g, int start, - perrdetail *err_ret, int flags) + perrdetail *err_ret, int flags) { - return PyParser_ParseStringFlagsFilename(s, NULL, - g, start, err_ret, flags); + return PyParser_ParseStringFlagsFilename(s, NULL, + g, start, err_ret, flags); } node * PyParser_ParseStringFlagsFilename(const char *s, const char *filename, - grammar *g, int start, - perrdetail *err_ret, int flags) + grammar *g, int start, + perrdetail *err_ret, int flags) { - int iflags = flags; - return PyParser_ParseStringFlagsFilenameEx(s, filename, g, start, - err_ret, &iflags); + int iflags = flags; + return PyParser_ParseStringFlagsFilenameEx(s, filename, g, start, + err_ret, &iflags); } node * PyParser_ParseStringFlagsFilenameEx(const char *s, const char *filename, - grammar *g, int start, - perrdetail *err_ret, int *flags) + grammar *g, int start, + perrdetail *err_ret, int *flags) { - struct tok_state *tok; + struct tok_state *tok; - initerr(err_ret, filename); + initerr(err_ret, filename); - if (*flags & PyPARSE_IGNORE_COOKIE) - tok = PyTokenizer_FromUTF8(s); - else - tok = PyTokenizer_FromString(s); - if (tok == NULL) { - err_ret->error = PyErr_Occurred() ? E_DECODE : E_NOMEM; - return NULL; - } + if (*flags & PyPARSE_IGNORE_COOKIE) + tok = PyTokenizer_FromUTF8(s); + else + tok = PyTokenizer_FromString(s); + if (tok == NULL) { + err_ret->error = PyErr_Occurred() ? E_DECODE : E_NOMEM; + return NULL; + } - tok->filename = filename ? filename : ""; - return parsetok(tok, g, start, err_ret, flags); + tok->filename = filename ? filename : ""; + return parsetok(tok, g, start, err_ret, flags); } /* Parse input coming from a file. Return error code, print some errors. */ node * PyParser_ParseFile(FILE *fp, const char *filename, grammar *g, int start, - char *ps1, char *ps2, perrdetail *err_ret) + char *ps1, char *ps2, perrdetail *err_ret) { - return PyParser_ParseFileFlags(fp, filename, NULL, - g, start, ps1, ps2, err_ret, 0); + return PyParser_ParseFileFlags(fp, filename, NULL, + g, start, ps1, ps2, err_ret, 0); } node * PyParser_ParseFileFlags(FILE *fp, const char *filename, const char *enc, - grammar *g, int start, - char *ps1, char *ps2, perrdetail *err_ret, int flags) + grammar *g, int start, + char *ps1, char *ps2, perrdetail *err_ret, int flags) { - int iflags = flags; - return PyParser_ParseFileFlagsEx(fp, filename, enc, g, start, ps1, - ps2, err_ret, &iflags); + int iflags = flags; + return PyParser_ParseFileFlagsEx(fp, filename, enc, g, start, ps1, + ps2, err_ret, &iflags); } node * -PyParser_ParseFileFlagsEx(FILE *fp, const char *filename, - const char *enc, grammar *g, int start, - char *ps1, char *ps2, perrdetail *err_ret, int *flags) +PyParser_ParseFileFlagsEx(FILE *fp, const char *filename, + const char *enc, grammar *g, int start, + char *ps1, char *ps2, perrdetail *err_ret, int *flags) { - struct tok_state *tok; + struct tok_state *tok; - initerr(err_ret, filename); + initerr(err_ret, filename); - if ((tok = PyTokenizer_FromFile(fp, (char *)enc, ps1, ps2)) == NULL) { - err_ret->error = E_NOMEM; - return NULL; - } - tok->filename = filename; - return parsetok(tok, g, start, err_ret, flags); + if ((tok = PyTokenizer_FromFile(fp, (char *)enc, ps1, ps2)) == NULL) { + err_ret->error = E_NOMEM; + return NULL; + } + tok->filename = filename; + return parsetok(tok, g, start, err_ret, flags); } #ifdef PY_PARSER_REQUIRES_FUTURE_KEYWORD @@ -110,9 +110,9 @@ static void warn(const char *msg, const char *filename, int lineno) { - if (filename == NULL) - filename = ""; - PySys_WriteStderr(msg, filename, lineno); + if (filename == NULL) + filename = ""; + PySys_WriteStderr(msg, filename, lineno); } #endif #endif @@ -122,151 +122,151 @@ static node * parsetok(struct tok_state *tok, grammar *g, int start, perrdetail *err_ret, - int *flags) + int *flags) { - parser_state *ps; - node *n; - int started = 0, handling_import = 0, handling_with = 0; - - if ((ps = PyParser_New(g, start)) == NULL) { - fprintf(stderr, "no mem for new parser\n"); - err_ret->error = E_NOMEM; - PyTokenizer_Free(tok); - return NULL; - } + parser_state *ps; + node *n; + int started = 0, handling_import = 0, handling_with = 0; + + if ((ps = PyParser_New(g, start)) == NULL) { + fprintf(stderr, "no mem for new parser\n"); + err_ret->error = E_NOMEM; + PyTokenizer_Free(tok); + return NULL; + } #ifdef PY_PARSER_REQUIRES_FUTURE_KEYWORD - if (*flags & PyPARSE_BARRY_AS_BDFL) - ps->p_flags |= CO_FUTURE_BARRY_AS_BDFL; + if (*flags & PyPARSE_BARRY_AS_BDFL) + ps->p_flags |= CO_FUTURE_BARRY_AS_BDFL; #endif - for (;;) { - char *a, *b; - int type; - size_t len; - char *str; - int col_offset; - - type = PyTokenizer_Get(tok, &a, &b); - if (type == ERRORTOKEN) { - err_ret->error = tok->done; - break; - } - if (type == ENDMARKER && started) { - type = NEWLINE; /* Add an extra newline */ - handling_with = handling_import = 0; - started = 0; - /* Add the right number of dedent tokens, - except if a certain flag is given -- - codeop.py uses this. */ - if (tok->indent && - !(*flags & PyPARSE_DONT_IMPLY_DEDENT)) - { - tok->pendin = -tok->indent; - tok->indent = 0; - } - } - else - started = 1; - len = b - a; /* XXX this may compute NULL - NULL */ - str = (char *) PyObject_MALLOC(len + 1); - if (str == NULL) { - fprintf(stderr, "no mem for next token\n"); - err_ret->error = E_NOMEM; - break; - } - if (len > 0) - strncpy(str, a, len); - str[len] = '\0'; + for (;;) { + char *a, *b; + int type; + size_t len; + char *str; + int col_offset; + + type = PyTokenizer_Get(tok, &a, &b); + if (type == ERRORTOKEN) { + err_ret->error = tok->done; + break; + } + if (type == ENDMARKER && started) { + type = NEWLINE; /* Add an extra newline */ + handling_with = handling_import = 0; + started = 0; + /* Add the right number of dedent tokens, + except if a certain flag is given -- + codeop.py uses this. */ + if (tok->indent && + !(*flags & PyPARSE_DONT_IMPLY_DEDENT)) + { + tok->pendin = -tok->indent; + tok->indent = 0; + } + } + else + started = 1; + len = b - a; /* XXX this may compute NULL - NULL */ + str = (char *) PyObject_MALLOC(len + 1); + if (str == NULL) { + fprintf(stderr, "no mem for next token\n"); + err_ret->error = E_NOMEM; + break; + } + if (len > 0) + strncpy(str, a, len); + str[len] = '\0'; #ifdef PY_PARSER_REQUIRES_FUTURE_KEYWORD - if (type == NOTEQUAL) { - if (!(ps->p_flags & CO_FUTURE_BARRY_AS_BDFL) && - strcmp(str, "!=")) { - err_ret->error = E_SYNTAX; - break; - } - else if ((ps->p_flags & CO_FUTURE_BARRY_AS_BDFL) && - strcmp(str, "<>")) { - err_ret->text = "with Barry as BDFL, use '<>' " - "instead of '!='"; - err_ret->error = E_SYNTAX; - break; - } - } + if (type == NOTEQUAL) { + if (!(ps->p_flags & CO_FUTURE_BARRY_AS_BDFL) && + strcmp(str, "!=")) { + err_ret->error = E_SYNTAX; + break; + } + else if ((ps->p_flags & CO_FUTURE_BARRY_AS_BDFL) && + strcmp(str, "<>")) { + err_ret->text = "with Barry as BDFL, use '<>' " + "instead of '!='"; + err_ret->error = E_SYNTAX; + break; + } + } #endif - if (a >= tok->line_start) - col_offset = a - tok->line_start; - else - col_offset = -1; - - if ((err_ret->error = - PyParser_AddToken(ps, (int)type, str, - tok->lineno, col_offset, - &(err_ret->expected))) != E_OK) { - if (err_ret->error != E_DONE) { - PyObject_FREE(str); - err_ret->token = type; - } - break; - } - } - - if (err_ret->error == E_DONE) { - n = ps->p_tree; - ps->p_tree = NULL; - } - else - n = NULL; + if (a >= tok->line_start) + col_offset = a - tok->line_start; + else + col_offset = -1; + + if ((err_ret->error = + PyParser_AddToken(ps, (int)type, str, + tok->lineno, col_offset, + &(err_ret->expected))) != E_OK) { + if (err_ret->error != E_DONE) { + PyObject_FREE(str); + err_ret->token = type; + } + break; + } + } + + if (err_ret->error == E_DONE) { + n = ps->p_tree; + ps->p_tree = NULL; + } + else + n = NULL; #ifdef PY_PARSER_REQUIRES_FUTURE_KEYWORD - *flags = ps->p_flags; + *flags = ps->p_flags; #endif - PyParser_Delete(ps); + PyParser_Delete(ps); - if (n == NULL) { - if (tok->lineno <= 1 && tok->done == E_EOF) - err_ret->error = E_EOF; - err_ret->lineno = tok->lineno; - if (tok->buf != NULL) { - size_t len; - assert(tok->cur - tok->buf < INT_MAX); - err_ret->offset = (int)(tok->cur - tok->buf); - len = tok->inp - tok->buf; - err_ret->text = (char *) PyObject_MALLOC(len + 1); - if (err_ret->text != NULL) { - if (len > 0) - strncpy(err_ret->text, tok->buf, len); - err_ret->text[len] = '\0'; - } - } - } else if (tok->encoding != NULL) { - node* r = PyNode_New(encoding_decl); - if (!r) { - err_ret->error = E_NOMEM; - n = NULL; - goto done; - } - r->n_str = tok->encoding; - r->n_nchildren = 1; - r->n_child = n; - tok->encoding = NULL; - n = r; - } + if (n == NULL) { + if (tok->lineno <= 1 && tok->done == E_EOF) + err_ret->error = E_EOF; + err_ret->lineno = tok->lineno; + if (tok->buf != NULL) { + size_t len; + assert(tok->cur - tok->buf < INT_MAX); + err_ret->offset = (int)(tok->cur - tok->buf); + len = tok->inp - tok->buf; + err_ret->text = (char *) PyObject_MALLOC(len + 1); + if (err_ret->text != NULL) { + if (len > 0) + strncpy(err_ret->text, tok->buf, len); + err_ret->text[len] = '\0'; + } + } + } else if (tok->encoding != NULL) { + node* r = PyNode_New(encoding_decl); + if (!r) { + err_ret->error = E_NOMEM; + n = NULL; + goto done; + } + r->n_str = tok->encoding; + r->n_nchildren = 1; + r->n_child = n; + tok->encoding = NULL; + n = r; + } done: - PyTokenizer_Free(tok); + PyTokenizer_Free(tok); - return n; + return n; } static void initerr(perrdetail *err_ret, const char *filename) { - err_ret->error = E_OK; - err_ret->filename = filename; - err_ret->lineno = 0; - err_ret->offset = 0; - err_ret->text = NULL; - err_ret->token = -1; - err_ret->expected = -1; + err_ret->error = E_OK; + err_ret->filename = filename; + err_ret->lineno = 0; + err_ret->offset = 0; + err_ret->text = NULL; + err_ret->token = -1; + err_ret->expected = -1; } Modified: python/branches/release31-maint/Parser/pgen.c ============================================================================== --- python/branches/release31-maint/Parser/pgen.c (original) +++ python/branches/release31-maint/Parser/pgen.c Sun May 9 18:14:21 2010 @@ -17,85 +17,85 @@ /* PART ONE -- CONSTRUCT NFA -- Cf. Algorithm 3.2 from [Aho&Ullman 77] */ typedef struct _nfaarc { - int ar_label; - int ar_arrow; + int ar_label; + int ar_arrow; } nfaarc; typedef struct _nfastate { - int st_narcs; - nfaarc *st_arc; + int st_narcs; + nfaarc *st_arc; } nfastate; typedef struct _nfa { - int nf_type; - char *nf_name; - int nf_nstates; - nfastate *nf_state; - int nf_start, nf_finish; + int nf_type; + char *nf_name; + int nf_nstates; + nfastate *nf_state; + int nf_start, nf_finish; } nfa; /* Forward */ static void compile_rhs(labellist *ll, - nfa *nf, node *n, int *pa, int *pb); + nfa *nf, node *n, int *pa, int *pb); static void compile_alt(labellist *ll, - nfa *nf, node *n, int *pa, int *pb); + nfa *nf, node *n, int *pa, int *pb); static void compile_item(labellist *ll, - nfa *nf, node *n, int *pa, int *pb); + nfa *nf, node *n, int *pa, int *pb); static void compile_atom(labellist *ll, - nfa *nf, node *n, int *pa, int *pb); + nfa *nf, node *n, int *pa, int *pb); static int addnfastate(nfa *nf) { - nfastate *st; - - nf->nf_state = (nfastate *)PyObject_REALLOC(nf->nf_state, - sizeof(nfastate) * (nf->nf_nstates + 1)); - if (nf->nf_state == NULL) - Py_FatalError("out of mem"); - st = &nf->nf_state[nf->nf_nstates++]; - st->st_narcs = 0; - st->st_arc = NULL; - return st - nf->nf_state; + nfastate *st; + + nf->nf_state = (nfastate *)PyObject_REALLOC(nf->nf_state, + sizeof(nfastate) * (nf->nf_nstates + 1)); + if (nf->nf_state == NULL) + Py_FatalError("out of mem"); + st = &nf->nf_state[nf->nf_nstates++]; + st->st_narcs = 0; + st->st_arc = NULL; + return st - nf->nf_state; } static void addnfaarc(nfa *nf, int from, int to, int lbl) { - nfastate *st; - nfaarc *ar; - - st = &nf->nf_state[from]; - st->st_arc = (nfaarc *)PyObject_REALLOC(st->st_arc, - sizeof(nfaarc) * (st->st_narcs + 1)); - if (st->st_arc == NULL) - Py_FatalError("out of mem"); - ar = &st->st_arc[st->st_narcs++]; - ar->ar_label = lbl; - ar->ar_arrow = to; + nfastate *st; + nfaarc *ar; + + st = &nf->nf_state[from]; + st->st_arc = (nfaarc *)PyObject_REALLOC(st->st_arc, + sizeof(nfaarc) * (st->st_narcs + 1)); + if (st->st_arc == NULL) + Py_FatalError("out of mem"); + ar = &st->st_arc[st->st_narcs++]; + ar->ar_label = lbl; + ar->ar_arrow = to; } static nfa * newnfa(char *name) { - nfa *nf; - static int type = NT_OFFSET; /* All types will be disjunct */ - - nf = (nfa *)PyObject_MALLOC(sizeof(nfa)); - if (nf == NULL) - Py_FatalError("no mem for new nfa"); - nf->nf_type = type++; - nf->nf_name = name; /* XXX strdup(name) ??? */ - nf->nf_nstates = 0; - nf->nf_state = NULL; - nf->nf_start = nf->nf_finish = -1; - return nf; + nfa *nf; + static int type = NT_OFFSET; /* All types will be disjunct */ + + nf = (nfa *)PyObject_MALLOC(sizeof(nfa)); + if (nf == NULL) + Py_FatalError("no mem for new nfa"); + nf->nf_type = type++; + nf->nf_name = name; /* XXX strdup(name) ??? */ + nf->nf_nstates = 0; + nf->nf_state = NULL; + nf->nf_start = nf->nf_finish = -1; + return nf; } typedef struct _nfagrammar { - int gr_nnfas; - nfa **gr_nfa; - labellist gr_ll; + int gr_nnfas; + nfa **gr_nfa; + labellist gr_ll; } nfagrammar; /* Forward */ @@ -104,32 +104,32 @@ static nfagrammar * newnfagrammar(void) { - nfagrammar *gr; - - gr = (nfagrammar *)PyObject_MALLOC(sizeof(nfagrammar)); - if (gr == NULL) - Py_FatalError("no mem for new nfa grammar"); - gr->gr_nnfas = 0; - gr->gr_nfa = NULL; - gr->gr_ll.ll_nlabels = 0; - gr->gr_ll.ll_label = NULL; - addlabel(&gr->gr_ll, ENDMARKER, "EMPTY"); - return gr; + nfagrammar *gr; + + gr = (nfagrammar *)PyObject_MALLOC(sizeof(nfagrammar)); + if (gr == NULL) + Py_FatalError("no mem for new nfa grammar"); + gr->gr_nnfas = 0; + gr->gr_nfa = NULL; + gr->gr_ll.ll_nlabels = 0; + gr->gr_ll.ll_label = NULL; + addlabel(&gr->gr_ll, ENDMARKER, "EMPTY"); + return gr; } static nfa * addnfa(nfagrammar *gr, char *name) { - nfa *nf; - - nf = newnfa(name); - gr->gr_nfa = (nfa **)PyObject_REALLOC(gr->gr_nfa, - sizeof(nfa*) * (gr->gr_nnfas + 1)); - if (gr->gr_nfa == NULL) - Py_FatalError("out of mem"); - gr->gr_nfa[gr->gr_nnfas++] = nf; - addlabel(&gr->gr_ll, NAME, nf->nf_name); - return nf; + nfa *nf; + + nf = newnfa(name); + gr->gr_nfa = (nfa **)PyObject_REALLOC(gr->gr_nfa, + sizeof(nfa*) * (gr->gr_nnfas + 1)); + if (gr->gr_nfa == NULL) + Py_FatalError("out of mem"); + gr->gr_nfa[gr->gr_nnfas++] = nf; + addlabel(&gr->gr_ll, NAME, nf->nf_name); + return nf; } #ifdef Py_DEBUG @@ -137,203 +137,203 @@ static char REQNFMT[] = "metacompile: less than %d children\n"; #define REQN(i, count) \ - if (i < count) { \ - fprintf(stderr, REQNFMT, count); \ - Py_FatalError("REQN"); \ - } else + if (i < count) { \ + fprintf(stderr, REQNFMT, count); \ + Py_FatalError("REQN"); \ + } else #else -#define REQN(i, count) /* empty */ +#define REQN(i, count) /* empty */ #endif static nfagrammar * metacompile(node *n) { - nfagrammar *gr; - int i; + nfagrammar *gr; + int i; - if (Py_DebugFlag) - printf("Compiling (meta-) parse tree into NFA grammar\n"); - gr = newnfagrammar(); - REQ(n, MSTART); - i = n->n_nchildren - 1; /* Last child is ENDMARKER */ - n = n->n_child; - for (; --i >= 0; n++) { - if (n->n_type != NEWLINE) - compile_rule(gr, n); - } - return gr; + if (Py_DebugFlag) + printf("Compiling (meta-) parse tree into NFA grammar\n"); + gr = newnfagrammar(); + REQ(n, MSTART); + i = n->n_nchildren - 1; /* Last child is ENDMARKER */ + n = n->n_child; + for (; --i >= 0; n++) { + if (n->n_type != NEWLINE) + compile_rule(gr, n); + } + return gr; } static void compile_rule(nfagrammar *gr, node *n) { - nfa *nf; - - REQ(n, RULE); - REQN(n->n_nchildren, 4); - n = n->n_child; - REQ(n, NAME); - nf = addnfa(gr, n->n_str); - n++; - REQ(n, COLON); - n++; - REQ(n, RHS); - compile_rhs(&gr->gr_ll, nf, n, &nf->nf_start, &nf->nf_finish); - n++; - REQ(n, NEWLINE); + nfa *nf; + + REQ(n, RULE); + REQN(n->n_nchildren, 4); + n = n->n_child; + REQ(n, NAME); + nf = addnfa(gr, n->n_str); + n++; + REQ(n, COLON); + n++; + REQ(n, RHS); + compile_rhs(&gr->gr_ll, nf, n, &nf->nf_start, &nf->nf_finish); + n++; + REQ(n, NEWLINE); } static void compile_rhs(labellist *ll, nfa *nf, node *n, int *pa, int *pb) { - int i; - int a, b; - - REQ(n, RHS); - i = n->n_nchildren; - REQN(i, 1); - n = n->n_child; - REQ(n, ALT); - compile_alt(ll, nf, n, pa, pb); - if (--i <= 0) - return; - n++; - a = *pa; - b = *pb; - *pa = addnfastate(nf); - *pb = addnfastate(nf); - addnfaarc(nf, *pa, a, EMPTY); - addnfaarc(nf, b, *pb, EMPTY); - for (; --i >= 0; n++) { - REQ(n, VBAR); - REQN(i, 1); - --i; - n++; - REQ(n, ALT); - compile_alt(ll, nf, n, &a, &b); - addnfaarc(nf, *pa, a, EMPTY); - addnfaarc(nf, b, *pb, EMPTY); - } + int i; + int a, b; + + REQ(n, RHS); + i = n->n_nchildren; + REQN(i, 1); + n = n->n_child; + REQ(n, ALT); + compile_alt(ll, nf, n, pa, pb); + if (--i <= 0) + return; + n++; + a = *pa; + b = *pb; + *pa = addnfastate(nf); + *pb = addnfastate(nf); + addnfaarc(nf, *pa, a, EMPTY); + addnfaarc(nf, b, *pb, EMPTY); + for (; --i >= 0; n++) { + REQ(n, VBAR); + REQN(i, 1); + --i; + n++; + REQ(n, ALT); + compile_alt(ll, nf, n, &a, &b); + addnfaarc(nf, *pa, a, EMPTY); + addnfaarc(nf, b, *pb, EMPTY); + } } static void compile_alt(labellist *ll, nfa *nf, node *n, int *pa, int *pb) { - int i; - int a, b; - - REQ(n, ALT); - i = n->n_nchildren; - REQN(i, 1); - n = n->n_child; - REQ(n, ITEM); - compile_item(ll, nf, n, pa, pb); - --i; - n++; - for (; --i >= 0; n++) { - REQ(n, ITEM); - compile_item(ll, nf, n, &a, &b); - addnfaarc(nf, *pb, a, EMPTY); - *pb = b; - } + int i; + int a, b; + + REQ(n, ALT); + i = n->n_nchildren; + REQN(i, 1); + n = n->n_child; + REQ(n, ITEM); + compile_item(ll, nf, n, pa, pb); + --i; + n++; + for (; --i >= 0; n++) { + REQ(n, ITEM); + compile_item(ll, nf, n, &a, &b); + addnfaarc(nf, *pb, a, EMPTY); + *pb = b; + } } static void compile_item(labellist *ll, nfa *nf, node *n, int *pa, int *pb) { - int i; - int a, b; - - REQ(n, ITEM); - i = n->n_nchildren; - REQN(i, 1); - n = n->n_child; - if (n->n_type == LSQB) { - REQN(i, 3); - n++; - REQ(n, RHS); - *pa = addnfastate(nf); - *pb = addnfastate(nf); - addnfaarc(nf, *pa, *pb, EMPTY); - compile_rhs(ll, nf, n, &a, &b); - addnfaarc(nf, *pa, a, EMPTY); - addnfaarc(nf, b, *pb, EMPTY); - REQN(i, 1); - n++; - REQ(n, RSQB); - } - else { - compile_atom(ll, nf, n, pa, pb); - if (--i <= 0) - return; - n++; - addnfaarc(nf, *pb, *pa, EMPTY); - if (n->n_type == STAR) - *pb = *pa; - else - REQ(n, PLUS); - } + int i; + int a, b; + + REQ(n, ITEM); + i = n->n_nchildren; + REQN(i, 1); + n = n->n_child; + if (n->n_type == LSQB) { + REQN(i, 3); + n++; + REQ(n, RHS); + *pa = addnfastate(nf); + *pb = addnfastate(nf); + addnfaarc(nf, *pa, *pb, EMPTY); + compile_rhs(ll, nf, n, &a, &b); + addnfaarc(nf, *pa, a, EMPTY); + addnfaarc(nf, b, *pb, EMPTY); + REQN(i, 1); + n++; + REQ(n, RSQB); + } + else { + compile_atom(ll, nf, n, pa, pb); + if (--i <= 0) + return; + n++; + addnfaarc(nf, *pb, *pa, EMPTY); + if (n->n_type == STAR) + *pb = *pa; + else + REQ(n, PLUS); + } } static void compile_atom(labellist *ll, nfa *nf, node *n, int *pa, int *pb) { - int i; - - REQ(n, ATOM); - i = n->n_nchildren; - REQN(i, 1); - n = n->n_child; - if (n->n_type == LPAR) { - REQN(i, 3); - n++; - REQ(n, RHS); - compile_rhs(ll, nf, n, pa, pb); - n++; - REQ(n, RPAR); - } - else if (n->n_type == NAME || n->n_type == STRING) { - *pa = addnfastate(nf); - *pb = addnfastate(nf); - addnfaarc(nf, *pa, *pb, addlabel(ll, n->n_type, n->n_str)); - } - else - REQ(n, NAME); + int i; + + REQ(n, ATOM); + i = n->n_nchildren; + REQN(i, 1); + n = n->n_child; + if (n->n_type == LPAR) { + REQN(i, 3); + n++; + REQ(n, RHS); + compile_rhs(ll, nf, n, pa, pb); + n++; + REQ(n, RPAR); + } + else if (n->n_type == NAME || n->n_type == STRING) { + *pa = addnfastate(nf); + *pb = addnfastate(nf); + addnfaarc(nf, *pa, *pb, addlabel(ll, n->n_type, n->n_str)); + } + else + REQ(n, NAME); } static void dumpstate(labellist *ll, nfa *nf, int istate) { - nfastate *st; - int i; - nfaarc *ar; - - printf("%c%2d%c", - istate == nf->nf_start ? '*' : ' ', - istate, - istate == nf->nf_finish ? '.' : ' '); - st = &nf->nf_state[istate]; - ar = st->st_arc; - for (i = 0; i < st->st_narcs; i++) { - if (i > 0) - printf("\n "); - printf("-> %2d %s", ar->ar_arrow, - PyGrammar_LabelRepr(&ll->ll_label[ar->ar_label])); - ar++; - } - printf("\n"); + nfastate *st; + int i; + nfaarc *ar; + + printf("%c%2d%c", + istate == nf->nf_start ? '*' : ' ', + istate, + istate == nf->nf_finish ? '.' : ' '); + st = &nf->nf_state[istate]; + ar = st->st_arc; + for (i = 0; i < st->st_narcs; i++) { + if (i > 0) + printf("\n "); + printf("-> %2d %s", ar->ar_arrow, + PyGrammar_LabelRepr(&ll->ll_label[ar->ar_label])); + ar++; + } + printf("\n"); } static void dumpnfa(labellist *ll, nfa *nf) { - int i; - - printf("NFA '%s' has %d states; start %d, finish %d\n", - nf->nf_name, nf->nf_nstates, nf->nf_start, nf->nf_finish); - for (i = 0; i < nf->nf_nstates; i++) - dumpstate(ll, nf, i); + int i; + + printf("NFA '%s' has %d states; start %d, finish %d\n", + nf->nf_name, nf->nf_nstates, nf->nf_start, nf->nf_finish); + for (i = 0; i < nf->nf_nstates; i++) + dumpstate(ll, nf, i); } @@ -342,184 +342,184 @@ static void addclosure(bitset ss, nfa *nf, int istate) { - if (addbit(ss, istate)) { - nfastate *st = &nf->nf_state[istate]; - nfaarc *ar = st->st_arc; - int i; - - for (i = st->st_narcs; --i >= 0; ) { - if (ar->ar_label == EMPTY) - addclosure(ss, nf, ar->ar_arrow); - ar++; - } - } + if (addbit(ss, istate)) { + nfastate *st = &nf->nf_state[istate]; + nfaarc *ar = st->st_arc; + int i; + + for (i = st->st_narcs; --i >= 0; ) { + if (ar->ar_label == EMPTY) + addclosure(ss, nf, ar->ar_arrow); + ar++; + } + } } typedef struct _ss_arc { - bitset sa_bitset; - int sa_arrow; - int sa_label; + bitset sa_bitset; + int sa_arrow; + int sa_label; } ss_arc; typedef struct _ss_state { - bitset ss_ss; - int ss_narcs; - struct _ss_arc *ss_arc; - int ss_deleted; - int ss_finish; - int ss_rename; + bitset ss_ss; + int ss_narcs; + struct _ss_arc *ss_arc; + int ss_deleted; + int ss_finish; + int ss_rename; } ss_state; typedef struct _ss_dfa { - int sd_nstates; - ss_state *sd_state; + int sd_nstates; + ss_state *sd_state; } ss_dfa; /* Forward */ static void printssdfa(int xx_nstates, ss_state *xx_state, int nbits, - labellist *ll, char *msg); + labellist *ll, char *msg); static void simplify(int xx_nstates, ss_state *xx_state); static void convert(dfa *d, int xx_nstates, ss_state *xx_state); static void makedfa(nfagrammar *gr, nfa *nf, dfa *d) { - int nbits = nf->nf_nstates; - bitset ss; - int xx_nstates; - ss_state *xx_state, *yy; - ss_arc *zz; - int istate, jstate, iarc, jarc, ibit; - nfastate *st; - nfaarc *ar; - - ss = newbitset(nbits); - addclosure(ss, nf, nf->nf_start); - xx_state = (ss_state *)PyObject_MALLOC(sizeof(ss_state)); - if (xx_state == NULL) - Py_FatalError("no mem for xx_state in makedfa"); - xx_nstates = 1; - yy = &xx_state[0]; - yy->ss_ss = ss; - yy->ss_narcs = 0; - yy->ss_arc = NULL; - yy->ss_deleted = 0; - yy->ss_finish = testbit(ss, nf->nf_finish); - if (yy->ss_finish) - printf("Error: nonterminal '%s' may produce empty.\n", - nf->nf_name); - - /* This algorithm is from a book written before - the invention of structured programming... */ - - /* For each unmarked state... */ - for (istate = 0; istate < xx_nstates; ++istate) { - size_t size; - yy = &xx_state[istate]; - ss = yy->ss_ss; - /* For all its states... */ - for (ibit = 0; ibit < nf->nf_nstates; ++ibit) { - if (!testbit(ss, ibit)) - continue; - st = &nf->nf_state[ibit]; - /* For all non-empty arcs from this state... */ - for (iarc = 0; iarc < st->st_narcs; iarc++) { - ar = &st->st_arc[iarc]; - if (ar->ar_label == EMPTY) - continue; - /* Look up in list of arcs from this state */ - for (jarc = 0; jarc < yy->ss_narcs; ++jarc) { - zz = &yy->ss_arc[jarc]; - if (ar->ar_label == zz->sa_label) - goto found; - } - /* Add new arc for this state */ - size = sizeof(ss_arc) * (yy->ss_narcs + 1); - yy->ss_arc = (ss_arc *)PyObject_REALLOC( - yy->ss_arc, size); - if (yy->ss_arc == NULL) - Py_FatalError("out of mem"); - zz = &yy->ss_arc[yy->ss_narcs++]; - zz->sa_label = ar->ar_label; - zz->sa_bitset = newbitset(nbits); - zz->sa_arrow = -1; - found: ; - /* Add destination */ - addclosure(zz->sa_bitset, nf, ar->ar_arrow); - } - } - /* Now look up all the arrow states */ - for (jarc = 0; jarc < xx_state[istate].ss_narcs; jarc++) { - zz = &xx_state[istate].ss_arc[jarc]; - for (jstate = 0; jstate < xx_nstates; jstate++) { - if (samebitset(zz->sa_bitset, - xx_state[jstate].ss_ss, nbits)) { - zz->sa_arrow = jstate; - goto done; - } - } - size = sizeof(ss_state) * (xx_nstates + 1); - xx_state = (ss_state *)PyObject_REALLOC(xx_state, - size); - if (xx_state == NULL) - Py_FatalError("out of mem"); - zz->sa_arrow = xx_nstates; - yy = &xx_state[xx_nstates++]; - yy->ss_ss = zz->sa_bitset; - yy->ss_narcs = 0; - yy->ss_arc = NULL; - yy->ss_deleted = 0; - yy->ss_finish = testbit(yy->ss_ss, nf->nf_finish); - done: ; - } - } - - if (Py_DebugFlag) - printssdfa(xx_nstates, xx_state, nbits, &gr->gr_ll, - "before minimizing"); - - simplify(xx_nstates, xx_state); - - if (Py_DebugFlag) - printssdfa(xx_nstates, xx_state, nbits, &gr->gr_ll, - "after minimizing"); - - convert(d, xx_nstates, xx_state); - - /* XXX cleanup */ - PyObject_FREE(xx_state); + int nbits = nf->nf_nstates; + bitset ss; + int xx_nstates; + ss_state *xx_state, *yy; + ss_arc *zz; + int istate, jstate, iarc, jarc, ibit; + nfastate *st; + nfaarc *ar; + + ss = newbitset(nbits); + addclosure(ss, nf, nf->nf_start); + xx_state = (ss_state *)PyObject_MALLOC(sizeof(ss_state)); + if (xx_state == NULL) + Py_FatalError("no mem for xx_state in makedfa"); + xx_nstates = 1; + yy = &xx_state[0]; + yy->ss_ss = ss; + yy->ss_narcs = 0; + yy->ss_arc = NULL; + yy->ss_deleted = 0; + yy->ss_finish = testbit(ss, nf->nf_finish); + if (yy->ss_finish) + printf("Error: nonterminal '%s' may produce empty.\n", + nf->nf_name); + + /* This algorithm is from a book written before + the invention of structured programming... */ + + /* For each unmarked state... */ + for (istate = 0; istate < xx_nstates; ++istate) { + size_t size; + yy = &xx_state[istate]; + ss = yy->ss_ss; + /* For all its states... */ + for (ibit = 0; ibit < nf->nf_nstates; ++ibit) { + if (!testbit(ss, ibit)) + continue; + st = &nf->nf_state[ibit]; + /* For all non-empty arcs from this state... */ + for (iarc = 0; iarc < st->st_narcs; iarc++) { + ar = &st->st_arc[iarc]; + if (ar->ar_label == EMPTY) + continue; + /* Look up in list of arcs from this state */ + for (jarc = 0; jarc < yy->ss_narcs; ++jarc) { + zz = &yy->ss_arc[jarc]; + if (ar->ar_label == zz->sa_label) + goto found; + } + /* Add new arc for this state */ + size = sizeof(ss_arc) * (yy->ss_narcs + 1); + yy->ss_arc = (ss_arc *)PyObject_REALLOC( + yy->ss_arc, size); + if (yy->ss_arc == NULL) + Py_FatalError("out of mem"); + zz = &yy->ss_arc[yy->ss_narcs++]; + zz->sa_label = ar->ar_label; + zz->sa_bitset = newbitset(nbits); + zz->sa_arrow = -1; + found: ; + /* Add destination */ + addclosure(zz->sa_bitset, nf, ar->ar_arrow); + } + } + /* Now look up all the arrow states */ + for (jarc = 0; jarc < xx_state[istate].ss_narcs; jarc++) { + zz = &xx_state[istate].ss_arc[jarc]; + for (jstate = 0; jstate < xx_nstates; jstate++) { + if (samebitset(zz->sa_bitset, + xx_state[jstate].ss_ss, nbits)) { + zz->sa_arrow = jstate; + goto done; + } + } + size = sizeof(ss_state) * (xx_nstates + 1); + xx_state = (ss_state *)PyObject_REALLOC(xx_state, + size); + if (xx_state == NULL) + Py_FatalError("out of mem"); + zz->sa_arrow = xx_nstates; + yy = &xx_state[xx_nstates++]; + yy->ss_ss = zz->sa_bitset; + yy->ss_narcs = 0; + yy->ss_arc = NULL; + yy->ss_deleted = 0; + yy->ss_finish = testbit(yy->ss_ss, nf->nf_finish); + done: ; + } + } + + if (Py_DebugFlag) + printssdfa(xx_nstates, xx_state, nbits, &gr->gr_ll, + "before minimizing"); + + simplify(xx_nstates, xx_state); + + if (Py_DebugFlag) + printssdfa(xx_nstates, xx_state, nbits, &gr->gr_ll, + "after minimizing"); + + convert(d, xx_nstates, xx_state); + + /* XXX cleanup */ + PyObject_FREE(xx_state); } static void printssdfa(int xx_nstates, ss_state *xx_state, int nbits, - labellist *ll, char *msg) + labellist *ll, char *msg) { - int i, ibit, iarc; - ss_state *yy; - ss_arc *zz; - - printf("Subset DFA %s\n", msg); - for (i = 0; i < xx_nstates; i++) { - yy = &xx_state[i]; - if (yy->ss_deleted) - continue; - printf(" Subset %d", i); - if (yy->ss_finish) - printf(" (finish)"); - printf(" { "); - for (ibit = 0; ibit < nbits; ibit++) { - if (testbit(yy->ss_ss, ibit)) - printf("%d ", ibit); - } - printf("}\n"); - for (iarc = 0; iarc < yy->ss_narcs; iarc++) { - zz = &yy->ss_arc[iarc]; - printf(" Arc to state %d, label %s\n", - zz->sa_arrow, - PyGrammar_LabelRepr( - &ll->ll_label[zz->sa_label])); - } - } + int i, ibit, iarc; + ss_state *yy; + ss_arc *zz; + + printf("Subset DFA %s\n", msg); + for (i = 0; i < xx_nstates; i++) { + yy = &xx_state[i]; + if (yy->ss_deleted) + continue; + printf(" Subset %d", i); + if (yy->ss_finish) + printf(" (finish)"); + printf(" { "); + for (ibit = 0; ibit < nbits; ibit++) { + if (testbit(yy->ss_ss, ibit)) + printf("%d ", ibit); + } + printf("}\n"); + for (iarc = 0; iarc < yy->ss_narcs; iarc++) { + zz = &yy->ss_arc[iarc]; + printf(" Arc to state %d, label %s\n", + zz->sa_arrow, + PyGrammar_LabelRepr( + &ll->ll_label[zz->sa_label])); + } + } } @@ -535,59 +535,59 @@ static int samestate(ss_state *s1, ss_state *s2) { - int i; - - if (s1->ss_narcs != s2->ss_narcs || s1->ss_finish != s2->ss_finish) - return 0; - for (i = 0; i < s1->ss_narcs; i++) { - if (s1->ss_arc[i].sa_arrow != s2->ss_arc[i].sa_arrow || - s1->ss_arc[i].sa_label != s2->ss_arc[i].sa_label) - return 0; - } - return 1; + int i; + + if (s1->ss_narcs != s2->ss_narcs || s1->ss_finish != s2->ss_finish) + return 0; + for (i = 0; i < s1->ss_narcs; i++) { + if (s1->ss_arc[i].sa_arrow != s2->ss_arc[i].sa_arrow || + s1->ss_arc[i].sa_label != s2->ss_arc[i].sa_label) + return 0; + } + return 1; } static void renamestates(int xx_nstates, ss_state *xx_state, int from, int to) { - int i, j; - - if (Py_DebugFlag) - printf("Rename state %d to %d.\n", from, to); - for (i = 0; i < xx_nstates; i++) { - if (xx_state[i].ss_deleted) - continue; - for (j = 0; j < xx_state[i].ss_narcs; j++) { - if (xx_state[i].ss_arc[j].sa_arrow == from) - xx_state[i].ss_arc[j].sa_arrow = to; - } - } + int i, j; + + if (Py_DebugFlag) + printf("Rename state %d to %d.\n", from, to); + for (i = 0; i < xx_nstates; i++) { + if (xx_state[i].ss_deleted) + continue; + for (j = 0; j < xx_state[i].ss_narcs; j++) { + if (xx_state[i].ss_arc[j].sa_arrow == from) + xx_state[i].ss_arc[j].sa_arrow = to; + } + } } static void simplify(int xx_nstates, ss_state *xx_state) { - int changes; - int i, j; - - do { - changes = 0; - for (i = 1; i < xx_nstates; i++) { - if (xx_state[i].ss_deleted) - continue; - for (j = 0; j < i; j++) { - if (xx_state[j].ss_deleted) - continue; - if (samestate(&xx_state[i], &xx_state[j])) { - xx_state[i].ss_deleted++; - renamestates(xx_nstates, xx_state, - i, j); - changes++; - break; - } - } - } - } while (changes); + int changes; + int i, j; + + do { + changes = 0; + for (i = 1; i < xx_nstates; i++) { + if (xx_state[i].ss_deleted) + continue; + for (j = 0; j < i; j++) { + if (xx_state[j].ss_deleted) + continue; + if (samestate(&xx_state[i], &xx_state[j])) { + xx_state[i].ss_deleted++; + renamestates(xx_nstates, xx_state, + i, j); + changes++; + break; + } + } + } + } while (changes); } @@ -598,32 +598,32 @@ static void convert(dfa *d, int xx_nstates, ss_state *xx_state) { - int i, j; - ss_state *yy; - ss_arc *zz; - - for (i = 0; i < xx_nstates; i++) { - yy = &xx_state[i]; - if (yy->ss_deleted) - continue; - yy->ss_rename = addstate(d); - } - - for (i = 0; i < xx_nstates; i++) { - yy = &xx_state[i]; - if (yy->ss_deleted) - continue; - for (j = 0; j < yy->ss_narcs; j++) { - zz = &yy->ss_arc[j]; - addarc(d, yy->ss_rename, - xx_state[zz->sa_arrow].ss_rename, - zz->sa_label); - } - if (yy->ss_finish) - addarc(d, yy->ss_rename, yy->ss_rename, 0); - } - - d->d_initial = 0; + int i, j; + ss_state *yy; + ss_arc *zz; + + for (i = 0; i < xx_nstates; i++) { + yy = &xx_state[i]; + if (yy->ss_deleted) + continue; + yy->ss_rename = addstate(d); + } + + for (i = 0; i < xx_nstates; i++) { + yy = &xx_state[i]; + if (yy->ss_deleted) + continue; + for (j = 0; j < yy->ss_narcs; j++) { + zz = &yy->ss_arc[j]; + addarc(d, yy->ss_rename, + xx_state[zz->sa_arrow].ss_rename, + zz->sa_label); + } + if (yy->ss_finish) + addarc(d, yy->ss_rename, yy->ss_rename, 0); + } + + d->d_initial = 0; } @@ -632,43 +632,43 @@ static grammar * maketables(nfagrammar *gr) { - int i; - nfa *nf; - dfa *d; - grammar *g; - - if (gr->gr_nnfas == 0) - return NULL; - g = newgrammar(gr->gr_nfa[0]->nf_type); - /* XXX first rule must be start rule */ - g->g_ll = gr->gr_ll; - - for (i = 0; i < gr->gr_nnfas; i++) { - nf = gr->gr_nfa[i]; - if (Py_DebugFlag) { - printf("Dump of NFA for '%s' ...\n", nf->nf_name); - dumpnfa(&gr->gr_ll, nf); - printf("Making DFA for '%s' ...\n", nf->nf_name); - } - d = adddfa(g, nf->nf_type, nf->nf_name); - makedfa(gr, gr->gr_nfa[i], d); - } - - return g; + int i; + nfa *nf; + dfa *d; + grammar *g; + + if (gr->gr_nnfas == 0) + return NULL; + g = newgrammar(gr->gr_nfa[0]->nf_type); + /* XXX first rule must be start rule */ + g->g_ll = gr->gr_ll; + + for (i = 0; i < gr->gr_nnfas; i++) { + nf = gr->gr_nfa[i]; + if (Py_DebugFlag) { + printf("Dump of NFA for '%s' ...\n", nf->nf_name); + dumpnfa(&gr->gr_ll, nf); + printf("Making DFA for '%s' ...\n", nf->nf_name); + } + d = adddfa(g, nf->nf_type, nf->nf_name); + makedfa(gr, gr->gr_nfa[i], d); + } + + return g; } grammar * pgen(node *n) { - nfagrammar *gr; - grammar *g; - - gr = metacompile(n); - g = maketables(gr); - translatelabels(g); - addfirstsets(g); - PyObject_FREE(gr); - return g; + nfagrammar *gr; + grammar *g; + + gr = metacompile(n); + g = maketables(gr); + translatelabels(g); + addfirstsets(g); + PyObject_FREE(gr); + return g; } grammar * @@ -702,7 +702,7 @@ --------- [Aho&Ullman 77] - Aho&Ullman, Principles of Compiler Design, Addison-Wesley 1977 - (first edition) + Aho&Ullman, Principles of Compiler Design, Addison-Wesley 1977 + (first edition) */ Modified: python/branches/release31-maint/Parser/pgenmain.c ============================================================================== --- python/branches/release31-maint/Parser/pgenmain.c (original) +++ python/branches/release31-maint/Parser/pgenmain.c Sun May 9 18:14:21 2010 @@ -30,104 +30,104 @@ void Py_Exit(int sts) { - exit(sts); + exit(sts); } int main(int argc, char **argv) { - grammar *g; - FILE *fp; - char *filename, *graminit_h, *graminit_c; - - if (argc != 4) { - fprintf(stderr, - "usage: %s grammar graminit.h graminit.c\n", argv[0]); - Py_Exit(2); - } - filename = argv[1]; - graminit_h = argv[2]; - graminit_c = argv[3]; - g = getgrammar(filename); - fp = fopen(graminit_c, "w"); - if (fp == NULL) { - perror(graminit_c); - Py_Exit(1); - } - if (Py_DebugFlag) - printf("Writing %s ...\n", graminit_c); - printgrammar(g, fp); - fclose(fp); - fp = fopen(graminit_h, "w"); - if (fp == NULL) { - perror(graminit_h); - Py_Exit(1); - } - if (Py_DebugFlag) - printf("Writing %s ...\n", graminit_h); - printnonterminals(g, fp); - fclose(fp); - Py_Exit(0); - return 0; /* Make gcc -Wall happy */ + grammar *g; + FILE *fp; + char *filename, *graminit_h, *graminit_c; + + if (argc != 4) { + fprintf(stderr, + "usage: %s grammar graminit.h graminit.c\n", argv[0]); + Py_Exit(2); + } + filename = argv[1]; + graminit_h = argv[2]; + graminit_c = argv[3]; + g = getgrammar(filename); + fp = fopen(graminit_c, "w"); + if (fp == NULL) { + perror(graminit_c); + Py_Exit(1); + } + if (Py_DebugFlag) + printf("Writing %s ...\n", graminit_c); + printgrammar(g, fp); + fclose(fp); + fp = fopen(graminit_h, "w"); + if (fp == NULL) { + perror(graminit_h); + Py_Exit(1); + } + if (Py_DebugFlag) + printf("Writing %s ...\n", graminit_h); + printnonterminals(g, fp); + fclose(fp); + Py_Exit(0); + return 0; /* Make gcc -Wall happy */ } grammar * getgrammar(char *filename) { - FILE *fp; - node *n; - grammar *g0, *g; - perrdetail err; - - fp = fopen(filename, "r"); - if (fp == NULL) { - perror(filename); - Py_Exit(1); - } - g0 = meta_grammar(); - n = PyParser_ParseFile(fp, filename, g0, g0->g_start, - (char *)NULL, (char *)NULL, &err); - fclose(fp); - if (n == NULL) { - fprintf(stderr, "Parsing error %d, line %d.\n", - err.error, err.lineno); - if (err.text != NULL) { - size_t i; - fprintf(stderr, "%s", err.text); - i = strlen(err.text); - if (i == 0 || err.text[i-1] != '\n') - fprintf(stderr, "\n"); - for (i = 0; i < err.offset; i++) { - if (err.text[i] == '\t') - putc('\t', stderr); - else - putc(' ', stderr); - } - fprintf(stderr, "^\n"); - PyObject_FREE(err.text); - } - Py_Exit(1); - } - g = pgen(n); - if (g == NULL) { - printf("Bad grammar.\n"); - Py_Exit(1); - } - return g; + FILE *fp; + node *n; + grammar *g0, *g; + perrdetail err; + + fp = fopen(filename, "r"); + if (fp == NULL) { + perror(filename); + Py_Exit(1); + } + g0 = meta_grammar(); + n = PyParser_ParseFile(fp, filename, g0, g0->g_start, + (char *)NULL, (char *)NULL, &err); + fclose(fp); + if (n == NULL) { + fprintf(stderr, "Parsing error %d, line %d.\n", + err.error, err.lineno); + if (err.text != NULL) { + size_t i; + fprintf(stderr, "%s", err.text); + i = strlen(err.text); + if (i == 0 || err.text[i-1] != '\n') + fprintf(stderr, "\n"); + for (i = 0; i < err.offset; i++) { + if (err.text[i] == '\t') + putc('\t', stderr); + else + putc(' ', stderr); + } + fprintf(stderr, "^\n"); + PyObject_FREE(err.text); + } + Py_Exit(1); + } + g = pgen(n); + if (g == NULL) { + printf("Bad grammar.\n"); + Py_Exit(1); + } + return g; } /* Can't happen in pgen */ PyObject* PyErr_Occurred() { - return 0; + return 0; } void Py_FatalError(const char *msg) { - fprintf(stderr, "pgen: FATAL ERROR: %s\n", msg); - Py_Exit(1); + fprintf(stderr, "pgen: FATAL ERROR: %s\n", msg); + Py_Exit(1); } /* No-nonsense my_readline() for tokenizer.c */ @@ -135,28 +135,28 @@ char * PyOS_Readline(FILE *sys_stdin, FILE *sys_stdout, char *prompt) { - size_t n = 1000; - char *p = (char *)PyMem_MALLOC(n); - char *q; - if (p == NULL) - return NULL; - fprintf(stderr, "%s", prompt); - q = fgets(p, n, sys_stdin); - if (q == NULL) { - *p = '\0'; - return p; - } - n = strlen(p); - if (n > 0 && p[n-1] != '\n') - p[n-1] = '\n'; - return (char *)PyMem_REALLOC(p, n+1); + size_t n = 1000; + char *p = (char *)PyMem_MALLOC(n); + char *q; + if (p == NULL) + return NULL; + fprintf(stderr, "%s", prompt); + q = fgets(p, n, sys_stdin); + if (q == NULL) { + *p = '\0'; + return p; + } + n = strlen(p); + if (n > 0 && p[n-1] != '\n') + p[n-1] = '\n'; + return (char *)PyMem_REALLOC(p, n+1); } /* No-nonsense fgets */ char * Py_UniversalNewlineFgets(char *buf, int n, FILE *stream, PyObject *fobj) { - return fgets(buf, n, stream); + return fgets(buf, n, stream); } @@ -165,9 +165,9 @@ void PySys_WriteStderr(const char *format, ...) { - va_list va; + va_list va; - va_start(va, format); - vfprintf(stderr, format, va); - va_end(va); + va_start(va, format); + vfprintf(stderr, format, va); + va_end(va); } Modified: python/branches/release31-maint/Parser/printgrammar.c ============================================================================== --- python/branches/release31-maint/Parser/printgrammar.c (original) +++ python/branches/release31-maint/Parser/printgrammar.c Sun May 9 18:14:21 2010 @@ -13,105 +13,105 @@ void printgrammar(grammar *g, FILE *fp) { - fprintf(fp, "/* Generated by Parser/pgen */\n\n"); - fprintf(fp, "#include \"pgenheaders.h\"\n"); - fprintf(fp, "#include \"grammar.h\"\n"); - fprintf(fp, "PyAPI_DATA(grammar) _PyParser_Grammar;\n"); - printdfas(g, fp); - printlabels(g, fp); - fprintf(fp, "grammar _PyParser_Grammar = {\n"); - fprintf(fp, "\t%d,\n", g->g_ndfas); - fprintf(fp, "\tdfas,\n"); - fprintf(fp, "\t{%d, labels},\n", g->g_ll.ll_nlabels); - fprintf(fp, "\t%d\n", g->g_start); - fprintf(fp, "};\n"); + fprintf(fp, "/* Generated by Parser/pgen */\n\n"); + fprintf(fp, "#include \"pgenheaders.h\"\n"); + fprintf(fp, "#include \"grammar.h\"\n"); + fprintf(fp, "PyAPI_DATA(grammar) _PyParser_Grammar;\n"); + printdfas(g, fp); + printlabels(g, fp); + fprintf(fp, "grammar _PyParser_Grammar = {\n"); + fprintf(fp, "\t%d,\n", g->g_ndfas); + fprintf(fp, "\tdfas,\n"); + fprintf(fp, "\t{%d, labels},\n", g->g_ll.ll_nlabels); + fprintf(fp, "\t%d\n", g->g_start); + fprintf(fp, "};\n"); } void printnonterminals(grammar *g, FILE *fp) { - dfa *d; - int i; - - fprintf(fp, "/* Generated by Parser/pgen */\n\n"); - - d = g->g_dfa; - for (i = g->g_ndfas; --i >= 0; d++) - fprintf(fp, "#define %s %d\n", d->d_name, d->d_type); + dfa *d; + int i; + + fprintf(fp, "/* Generated by Parser/pgen */\n\n"); + + d = g->g_dfa; + for (i = g->g_ndfas; --i >= 0; d++) + fprintf(fp, "#define %s %d\n", d->d_name, d->d_type); } static void printarcs(int i, dfa *d, FILE *fp) { - arc *a; - state *s; - int j, k; - - s = d->d_state; - for (j = 0; j < d->d_nstates; j++, s++) { - fprintf(fp, "static arc arcs_%d_%d[%d] = {\n", - i, j, s->s_narcs); - a = s->s_arc; - for (k = 0; k < s->s_narcs; k++, a++) - fprintf(fp, "\t{%d, %d},\n", a->a_lbl, a->a_arrow); - fprintf(fp, "};\n"); - } + arc *a; + state *s; + int j, k; + + s = d->d_state; + for (j = 0; j < d->d_nstates; j++, s++) { + fprintf(fp, "static arc arcs_%d_%d[%d] = {\n", + i, j, s->s_narcs); + a = s->s_arc; + for (k = 0; k < s->s_narcs; k++, a++) + fprintf(fp, "\t{%d, %d},\n", a->a_lbl, a->a_arrow); + fprintf(fp, "};\n"); + } } static void printstates(grammar *g, FILE *fp) { - state *s; - dfa *d; - int i, j; - - d = g->g_dfa; - for (i = 0; i < g->g_ndfas; i++, d++) { - printarcs(i, d, fp); - fprintf(fp, "static state states_%d[%d] = {\n", - i, d->d_nstates); - s = d->d_state; - for (j = 0; j < d->d_nstates; j++, s++) - fprintf(fp, "\t{%d, arcs_%d_%d},\n", - s->s_narcs, i, j); - fprintf(fp, "};\n"); - } + state *s; + dfa *d; + int i, j; + + d = g->g_dfa; + for (i = 0; i < g->g_ndfas; i++, d++) { + printarcs(i, d, fp); + fprintf(fp, "static state states_%d[%d] = {\n", + i, d->d_nstates); + s = d->d_state; + for (j = 0; j < d->d_nstates; j++, s++) + fprintf(fp, "\t{%d, arcs_%d_%d},\n", + s->s_narcs, i, j); + fprintf(fp, "};\n"); + } } static void printdfas(grammar *g, FILE *fp) { - dfa *d; - int i, j; - - printstates(g, fp); - fprintf(fp, "static dfa dfas[%d] = {\n", g->g_ndfas); - d = g->g_dfa; - for (i = 0; i < g->g_ndfas; i++, d++) { - fprintf(fp, "\t{%d, \"%s\", %d, %d, states_%d,\n", - d->d_type, d->d_name, d->d_initial, d->d_nstates, i); - fprintf(fp, "\t \""); - for (j = 0; j < NBYTES(g->g_ll.ll_nlabels); j++) - fprintf(fp, "\\%03o", d->d_first[j] & 0xff); - fprintf(fp, "\"},\n"); - } - fprintf(fp, "};\n"); + dfa *d; + int i, j; + + printstates(g, fp); + fprintf(fp, "static dfa dfas[%d] = {\n", g->g_ndfas); + d = g->g_dfa; + for (i = 0; i < g->g_ndfas; i++, d++) { + fprintf(fp, "\t{%d, \"%s\", %d, %d, states_%d,\n", + d->d_type, d->d_name, d->d_initial, d->d_nstates, i); + fprintf(fp, "\t \""); + for (j = 0; j < NBYTES(g->g_ll.ll_nlabels); j++) + fprintf(fp, "\\%03o", d->d_first[j] & 0xff); + fprintf(fp, "\"},\n"); + } + fprintf(fp, "};\n"); } static void printlabels(grammar *g, FILE *fp) { - label *l; - int i; - - fprintf(fp, "static label labels[%d] = {\n", g->g_ll.ll_nlabels); - l = g->g_ll.ll_label; - for (i = g->g_ll.ll_nlabels; --i >= 0; l++) { - if (l->lb_str == NULL) - fprintf(fp, "\t{%d, 0},\n", l->lb_type); - else - fprintf(fp, "\t{%d, \"%s\"},\n", - l->lb_type, l->lb_str); - } - fprintf(fp, "};\n"); + label *l; + int i; + + fprintf(fp, "static label labels[%d] = {\n", g->g_ll.ll_nlabels); + l = g->g_ll.ll_label; + for (i = g->g_ll.ll_nlabels; --i >= 0; l++) { + if (l->lb_str == NULL) + fprintf(fp, "\t{%d, 0},\n", l->lb_type); + else + fprintf(fp, "\t{%d, \"%s\"},\n", + l->lb_type, l->lb_str); + } + fprintf(fp, "};\n"); } Modified: python/branches/release31-maint/Parser/tokenizer.c ============================================================================== --- python/branches/release31-maint/Parser/tokenizer.c (original) +++ python/branches/release31-maint/Parser/tokenizer.c Sun May 9 18:14:21 2010 @@ -19,17 +19,17 @@ #endif /* PGEN */ #define is_potential_identifier_start(c) (\ - (c >= 'a' && c <= 'z')\ - || (c >= 'A' && c <= 'Z')\ - || c == '_'\ - || (c >= 128)) + (c >= 'a' && c <= 'z')\ + || (c >= 'A' && c <= 'Z')\ + || c == '_'\ + || (c >= 128)) #define is_potential_identifier_char(c) (\ - (c >= 'a' && c <= 'z')\ - || (c >= 'A' && c <= 'Z')\ - || (c >= '0' && c <= '9')\ - || c == '_'\ - || (c >= 128)) + (c >= 'a' && c <= 'z')\ + || (c >= 'A' && c <= 'Z')\ + || (c >= '0' && c <= '9')\ + || c == '_'\ + || (c >= 128)) extern char *PyOS_Readline(FILE *, FILE *, char *); /* Return malloc'ed string including trailing \n; @@ -48,62 +48,62 @@ /* Token names */ char *_PyParser_TokenNames[] = { - "ENDMARKER", - "NAME", - "NUMBER", - "STRING", - "NEWLINE", - "INDENT", - "DEDENT", - "LPAR", - "RPAR", - "LSQB", - "RSQB", - "COLON", - "COMMA", - "SEMI", - "PLUS", - "MINUS", - "STAR", - "SLASH", - "VBAR", - "AMPER", - "LESS", - "GREATER", - "EQUAL", - "DOT", - "PERCENT", - "LBRACE", - "RBRACE", - "EQEQUAL", - "NOTEQUAL", - "LESSEQUAL", - "GREATEREQUAL", - "TILDE", - "CIRCUMFLEX", - "LEFTSHIFT", - "RIGHTSHIFT", - "DOUBLESTAR", - "PLUSEQUAL", - "MINEQUAL", - "STAREQUAL", - "SLASHEQUAL", - "PERCENTEQUAL", - "AMPEREQUAL", - "VBAREQUAL", - "CIRCUMFLEXEQUAL", - "LEFTSHIFTEQUAL", - "RIGHTSHIFTEQUAL", - "DOUBLESTAREQUAL", - "DOUBLESLASH", - "DOUBLESLASHEQUAL", - "AT", - "RARROW", - "ELLIPSIS", - /* This table must match the #defines in token.h! */ - "OP", - "", - "" + "ENDMARKER", + "NAME", + "NUMBER", + "STRING", + "NEWLINE", + "INDENT", + "DEDENT", + "LPAR", + "RPAR", + "LSQB", + "RSQB", + "COLON", + "COMMA", + "SEMI", + "PLUS", + "MINUS", + "STAR", + "SLASH", + "VBAR", + "AMPER", + "LESS", + "GREATER", + "EQUAL", + "DOT", + "PERCENT", + "LBRACE", + "RBRACE", + "EQEQUAL", + "NOTEQUAL", + "LESSEQUAL", + "GREATEREQUAL", + "TILDE", + "CIRCUMFLEX", + "LEFTSHIFT", + "RIGHTSHIFT", + "DOUBLESTAR", + "PLUSEQUAL", + "MINEQUAL", + "STAREQUAL", + "SLASHEQUAL", + "PERCENTEQUAL", + "AMPEREQUAL", + "VBAREQUAL", + "CIRCUMFLEXEQUAL", + "LEFTSHIFTEQUAL", + "RIGHTSHIFTEQUAL", + "DOUBLESTAREQUAL", + "DOUBLESLASH", + "DOUBLESLASHEQUAL", + "AT", + "RARROW", + "ELLIPSIS", + /* This table must match the #defines in token.h! */ + "OP", + "", + "" }; @@ -112,37 +112,37 @@ static struct tok_state * tok_new(void) { - struct tok_state *tok = (struct tok_state *)PyMem_MALLOC( - sizeof(struct tok_state)); - if (tok == NULL) - return NULL; - tok->buf = tok->cur = tok->end = tok->inp = tok->start = NULL; - tok->done = E_OK; - tok->fp = NULL; - tok->tabsize = TABSIZE; - tok->indent = 0; - tok->indstack[0] = 0; - tok->atbol = 1; - tok->pendin = 0; - tok->prompt = tok->nextprompt = NULL; - tok->lineno = 0; - tok->level = 0; - tok->filename = NULL; - tok->altwarning = 1; - tok->alterror = 1; - tok->alttabsize = 1; - tok->altindstack[0] = 0; - tok->decoding_state = STATE_INIT; - tok->decoding_erred = 0; - tok->read_coding_spec = 0; - tok->enc = NULL; - tok->encoding = NULL; - tok->cont_line = 0; + struct tok_state *tok = (struct tok_state *)PyMem_MALLOC( + sizeof(struct tok_state)); + if (tok == NULL) + return NULL; + tok->buf = tok->cur = tok->end = tok->inp = tok->start = NULL; + tok->done = E_OK; + tok->fp = NULL; + tok->tabsize = TABSIZE; + tok->indent = 0; + tok->indstack[0] = 0; + tok->atbol = 1; + tok->pendin = 0; + tok->prompt = tok->nextprompt = NULL; + tok->lineno = 0; + tok->level = 0; + tok->filename = NULL; + tok->altwarning = 1; + tok->alterror = 1; + tok->alttabsize = 1; + tok->altindstack[0] = 0; + tok->decoding_state = STATE_INIT; + tok->decoding_erred = 0; + tok->read_coding_spec = 0; + tok->enc = NULL; + tok->encoding = NULL; + tok->cont_line = 0; #ifndef PGEN - tok->decoding_readline = NULL; - tok->decoding_buffer = NULL; + tok->decoding_readline = NULL; + tok->decoding_buffer = NULL; #endif - return tok; + return tok; } #ifdef PGEN @@ -150,19 +150,19 @@ static char * decoding_fgets(char *s, int size, struct tok_state *tok) { - return fgets(s, size, tok->fp); + return fgets(s, size, tok->fp); } static int decoding_feof(struct tok_state *tok) { - return feof(tok->fp); + return feof(tok->fp); } static const char * decode_str(const char *str, struct tok_state *tok) { - return str; + return str; } #else /* PGEN */ @@ -170,51 +170,51 @@ static char * error_ret(struct tok_state *tok) /* XXX */ { - tok->decoding_erred = 1; - if (tok->fp != NULL && tok->buf != NULL) /* see PyTokenizer_Free */ - PyMem_FREE(tok->buf); - tok->buf = NULL; - return NULL; /* as if it were EOF */ + tok->decoding_erred = 1; + if (tok->fp != NULL && tok->buf != NULL) /* see PyTokenizer_Free */ + PyMem_FREE(tok->buf); + tok->buf = NULL; + return NULL; /* as if it were EOF */ } static char * new_string(const char *s, Py_ssize_t len) { - char* result = (char *)PyMem_MALLOC(len + 1); - if (result != NULL) { - memcpy(result, s, len); - result[len] = '\0'; - } - return result; + char* result = (char *)PyMem_MALLOC(len + 1); + if (result != NULL) { + memcpy(result, s, len); + result[len] = '\0'; + } + return result; } static char * -get_normal_name(char *s) /* for utf-8 and latin-1 */ +get_normal_name(char *s) /* for utf-8 and latin-1 */ { - char buf[13]; - int i; - for (i = 0; i < 12; i++) { - int c = s[i]; - if (c == '\0') - break; - else if (c == '_') - buf[i] = '-'; - else - buf[i] = tolower(c); - } - buf[i] = '\0'; - if (strcmp(buf, "utf-8") == 0 || - strncmp(buf, "utf-8-", 6) == 0) - return "utf-8"; - else if (strcmp(buf, "latin-1") == 0 || - strcmp(buf, "iso-8859-1") == 0 || - strcmp(buf, "iso-latin-1") == 0 || - strncmp(buf, "latin-1-", 8) == 0 || - strncmp(buf, "iso-8859-1-", 11) == 0 || - strncmp(buf, "iso-latin-1-", 12) == 0) - return "iso-8859-1"; - else - return s; + char buf[13]; + int i; + for (i = 0; i < 12; i++) { + int c = s[i]; + if (c == '\0') + break; + else if (c == '_') + buf[i] = '-'; + else + buf[i] = tolower(c); + } + buf[i] = '\0'; + if (strcmp(buf, "utf-8") == 0 || + strncmp(buf, "utf-8-", 6) == 0) + return "utf-8"; + else if (strcmp(buf, "latin-1") == 0 || + strcmp(buf, "iso-8859-1") == 0 || + strcmp(buf, "iso-latin-1") == 0 || + strncmp(buf, "latin-1-", 8) == 0 || + strncmp(buf, "iso-8859-1-", 11) == 0 || + strncmp(buf, "iso-latin-1-", 12) == 0) + return "iso-8859-1"; + else + return s; } /* Return the coding spec in S, or NULL if none is found. */ @@ -222,43 +222,43 @@ static char * get_coding_spec(const char *s, Py_ssize_t size) { - Py_ssize_t i; - /* Coding spec must be in a comment, and that comment must be - * the only statement on the source code line. */ - for (i = 0; i < size - 6; i++) { - if (s[i] == '#') - break; - if (s[i] != ' ' && s[i] != '\t' && s[i] != '\014') - return NULL; - } - for (; i < size - 6; i++) { /* XXX inefficient search */ - const char* t = s + i; - if (strncmp(t, "coding", 6) == 0) { - const char* begin = NULL; - t += 6; - if (t[0] != ':' && t[0] != '=') - continue; - do { - t++; - } while (t[0] == '\x20' || t[0] == '\t'); - - begin = t; - while (isalnum(Py_CHARMASK(t[0])) || - t[0] == '-' || t[0] == '_' || t[0] == '.') - t++; - - if (begin < t) { - char* r = new_string(begin, t - begin); - char* q = get_normal_name(r); - if (r != q) { - PyMem_FREE(r); - r = new_string(q, strlen(q)); - } - return r; - } - } - } - return NULL; + Py_ssize_t i; + /* Coding spec must be in a comment, and that comment must be + * the only statement on the source code line. */ + for (i = 0; i < size - 6; i++) { + if (s[i] == '#') + break; + if (s[i] != ' ' && s[i] != '\t' && s[i] != '\014') + return NULL; + } + for (; i < size - 6; i++) { /* XXX inefficient search */ + const char* t = s + i; + if (strncmp(t, "coding", 6) == 0) { + const char* begin = NULL; + t += 6; + if (t[0] != ':' && t[0] != '=') + continue; + do { + t++; + } while (t[0] == '\x20' || t[0] == '\t'); + + begin = t; + while (isalnum(Py_CHARMASK(t[0])) || + t[0] == '-' || t[0] == '_' || t[0] == '.') + t++; + + if (begin < t) { + char* r = new_string(begin, t - begin); + char* q = get_normal_name(r); + if (r != q) { + PyMem_FREE(r); + r = new_string(q, strlen(q)); + } + return r; + } + } + } + return NULL; } /* Check whether the line contains a coding spec. If it does, @@ -268,42 +268,42 @@ static int check_coding_spec(const char* line, Py_ssize_t size, struct tok_state *tok, - int set_readline(struct tok_state *, const char *)) + int set_readline(struct tok_state *, const char *)) { - char * cs; - int r = 1; + char * cs; + int r = 1; - if (tok->cont_line) - /* It's a continuation line, so it can't be a coding spec. */ - return 1; - cs = get_coding_spec(line, size); - if (cs != NULL) { - tok->read_coding_spec = 1; - if (tok->encoding == NULL) { - assert(tok->decoding_state == STATE_RAW); - if (strcmp(cs, "utf-8") == 0) { - tok->encoding = cs; - } else { - r = set_readline(tok, cs); - if (r) { - tok->encoding = cs; - tok->decoding_state = STATE_NORMAL; - } - else - PyMem_FREE(cs); - } - } else { /* then, compare cs with BOM */ - r = (strcmp(tok->encoding, cs) == 0); - PyMem_FREE(cs); - } - } - if (!r) { - cs = tok->encoding; - if (!cs) - cs = "with BOM"; - PyErr_Format(PyExc_SyntaxError, "encoding problem: %s", cs); - } - return r; + if (tok->cont_line) + /* It's a continuation line, so it can't be a coding spec. */ + return 1; + cs = get_coding_spec(line, size); + if (cs != NULL) { + tok->read_coding_spec = 1; + if (tok->encoding == NULL) { + assert(tok->decoding_state == STATE_RAW); + if (strcmp(cs, "utf-8") == 0) { + tok->encoding = cs; + } else { + r = set_readline(tok, cs); + if (r) { + tok->encoding = cs; + tok->decoding_state = STATE_NORMAL; + } + else + PyMem_FREE(cs); + } + } else { /* then, compare cs with BOM */ + r = (strcmp(tok->encoding, cs) == 0); + PyMem_FREE(cs); + } + } + if (!r) { + cs = tok->encoding; + if (!cs) + cs = "with BOM"; + PyErr_Format(PyExc_SyntaxError, "encoding problem: %s", cs); + } + return r; } /* See whether the file starts with a BOM. If it does, @@ -312,62 +312,62 @@ static int check_bom(int get_char(struct tok_state *), - void unget_char(int, struct tok_state *), - int set_readline(struct tok_state *, const char *), - struct tok_state *tok) -{ - int ch1, ch2, ch3; - ch1 = get_char(tok); - tok->decoding_state = STATE_RAW; - if (ch1 == EOF) { - return 1; - } else if (ch1 == 0xEF) { - ch2 = get_char(tok); - if (ch2 != 0xBB) { - unget_char(ch2, tok); - unget_char(ch1, tok); - return 1; - } - ch3 = get_char(tok); - if (ch3 != 0xBF) { - unget_char(ch3, tok); - unget_char(ch2, tok); - unget_char(ch1, tok); - return 1; - } + void unget_char(int, struct tok_state *), + int set_readline(struct tok_state *, const char *), + struct tok_state *tok) +{ + int ch1, ch2, ch3; + ch1 = get_char(tok); + tok->decoding_state = STATE_RAW; + if (ch1 == EOF) { + return 1; + } else if (ch1 == 0xEF) { + ch2 = get_char(tok); + if (ch2 != 0xBB) { + unget_char(ch2, tok); + unget_char(ch1, tok); + return 1; + } + ch3 = get_char(tok); + if (ch3 != 0xBF) { + unget_char(ch3, tok); + unget_char(ch2, tok); + unget_char(ch1, tok); + return 1; + } #if 0 - /* Disable support for UTF-16 BOMs until a decision - is made whether this needs to be supported. */ - } else if (ch1 == 0xFE) { - ch2 = get_char(tok); - if (ch2 != 0xFF) { - unget_char(ch2, tok); - unget_char(ch1, tok); - return 1; - } - if (!set_readline(tok, "utf-16-be")) - return 0; - tok->decoding_state = STATE_NORMAL; - } else if (ch1 == 0xFF) { - ch2 = get_char(tok); - if (ch2 != 0xFE) { - unget_char(ch2, tok); - unget_char(ch1, tok); - return 1; - } - if (!set_readline(tok, "utf-16-le")) - return 0; - tok->decoding_state = STATE_NORMAL; + /* Disable support for UTF-16 BOMs until a decision + is made whether this needs to be supported. */ + } else if (ch1 == 0xFE) { + ch2 = get_char(tok); + if (ch2 != 0xFF) { + unget_char(ch2, tok); + unget_char(ch1, tok); + return 1; + } + if (!set_readline(tok, "utf-16-be")) + return 0; + tok->decoding_state = STATE_NORMAL; + } else if (ch1 == 0xFF) { + ch2 = get_char(tok); + if (ch2 != 0xFE) { + unget_char(ch2, tok); + unget_char(ch1, tok); + return 1; + } + if (!set_readline(tok, "utf-16-le")) + return 0; + tok->decoding_state = STATE_NORMAL; #endif - } else { - unget_char(ch1, tok); - return 1; - } - if (tok->encoding != NULL) - PyMem_FREE(tok->encoding); - tok->encoding = new_string("utf-8", 5); /* resulting is in utf-8 */ - /* No need to set_readline: input is already utf-8 */ - return 1; + } else { + unget_char(ch1, tok); + return 1; + } + if (tok->encoding != NULL) + PyMem_FREE(tok->encoding); + tok->encoding = new_string("utf-8", 5); /* resulting is in utf-8 */ + /* No need to set_readline: input is already utf-8 */ + return 1; } /* Read a line of text from TOK into S, using the stream in TOK. @@ -376,74 +376,74 @@ On entry, tok->decoding_buffer will be one of: 1) NULL: need to call tok->decoding_readline to get a new line 2) PyUnicodeObject *: decoding_feof has called tok->decoding_readline and - stored the result in tok->decoding_buffer + stored the result in tok->decoding_buffer 3) PyByteArrayObject *: previous call to fp_readl did not have enough room - (in the s buffer) to copy entire contents of the line read - by tok->decoding_readline. tok->decoding_buffer has the overflow. - In this case, fp_readl is called in a loop (with an expanded buffer) - until the buffer ends with a '\n' (or until the end of the file is - reached): see tok_nextc and its calls to decoding_fgets. + (in the s buffer) to copy entire contents of the line read + by tok->decoding_readline. tok->decoding_buffer has the overflow. + In this case, fp_readl is called in a loop (with an expanded buffer) + until the buffer ends with a '\n' (or until the end of the file is + reached): see tok_nextc and its calls to decoding_fgets. */ static char * fp_readl(char *s, int size, struct tok_state *tok) { - PyObject* bufobj; - const char *buf; - Py_ssize_t buflen; - - /* Ask for one less byte so we can terminate it */ - assert(size > 0); - size--; - - if (tok->decoding_buffer) { - bufobj = tok->decoding_buffer; - Py_INCREF(bufobj); - } - else - { - bufobj = PyObject_CallObject(tok->decoding_readline, NULL); - if (bufobj == NULL) - goto error; - } - if (PyUnicode_CheckExact(bufobj)) - { - buf = _PyUnicode_AsStringAndSize(bufobj, &buflen); - if (buf == NULL) { - goto error; - } - } - else - { - buf = PyByteArray_AsString(bufobj); - if (buf == NULL) { - goto error; - } - buflen = PyByteArray_GET_SIZE(bufobj); - } - - Py_XDECREF(tok->decoding_buffer); - if (buflen > size) { - /* Too many chars, the rest goes into tok->decoding_buffer */ - tok->decoding_buffer = PyByteArray_FromStringAndSize(buf+size, - buflen-size); - if (tok->decoding_buffer == NULL) - goto error; - buflen = size; - } - else - tok->decoding_buffer = NULL; - - memcpy(s, buf, buflen); - s[buflen] = '\0'; - if (buflen == 0) /* EOF */ - s = NULL; - Py_DECREF(bufobj); - return s; + PyObject* bufobj; + const char *buf; + Py_ssize_t buflen; + + /* Ask for one less byte so we can terminate it */ + assert(size > 0); + size--; + + if (tok->decoding_buffer) { + bufobj = tok->decoding_buffer; + Py_INCREF(bufobj); + } + else + { + bufobj = PyObject_CallObject(tok->decoding_readline, NULL); + if (bufobj == NULL) + goto error; + } + if (PyUnicode_CheckExact(bufobj)) + { + buf = _PyUnicode_AsStringAndSize(bufobj, &buflen); + if (buf == NULL) { + goto error; + } + } + else + { + buf = PyByteArray_AsString(bufobj); + if (buf == NULL) { + goto error; + } + buflen = PyByteArray_GET_SIZE(bufobj); + } + + Py_XDECREF(tok->decoding_buffer); + if (buflen > size) { + /* Too many chars, the rest goes into tok->decoding_buffer */ + tok->decoding_buffer = PyByteArray_FromStringAndSize(buf+size, + buflen-size); + if (tok->decoding_buffer == NULL) + goto error; + buflen = size; + } + else + tok->decoding_buffer = NULL; + + memcpy(s, buf, buflen); + s[buflen] = '\0'; + if (buflen == 0) /* EOF */ + s = NULL; + Py_DECREF(bufobj); + return s; error: - Py_XDECREF(bufobj); - return error_ret(tok); + Py_XDECREF(bufobj); + return error_ret(tok); } /* Set the readline function for TOK to a StreamReader's @@ -459,49 +459,49 @@ static int fp_setreadl(struct tok_state *tok, const char* enc) { - PyObject *readline = NULL, *stream = NULL, *io = NULL; + PyObject *readline = NULL, *stream = NULL, *io = NULL; - io = PyImport_ImportModuleNoBlock("io"); - if (io == NULL) - goto cleanup; - - if (tok->filename) - stream = PyObject_CallMethod(io, "open", "ssis", - tok->filename, "r", -1, enc); - else - stream = PyObject_CallMethod(io, "open", "isisOOO", - fileno(tok->fp), "r", -1, enc, Py_None, Py_None, Py_False); - if (stream == NULL) - goto cleanup; - - Py_XDECREF(tok->decoding_readline); - readline = PyObject_GetAttrString(stream, "readline"); - tok->decoding_readline = readline; - - /* The file has been reopened; parsing will restart from - * the beginning of the file, we have to reset the line number. - * But this function has been called from inside tok_nextc() which - * will increment lineno before it returns. So we set it -1 so that - * the next call to tok_nextc() will start with tok->lineno == 0. - */ - tok->lineno = -1; + io = PyImport_ImportModuleNoBlock("io"); + if (io == NULL) + goto cleanup; + + if (tok->filename) + stream = PyObject_CallMethod(io, "open", "ssis", + tok->filename, "r", -1, enc); + else + stream = PyObject_CallMethod(io, "open", "isisOOO", + fileno(tok->fp), "r", -1, enc, Py_None, Py_None, Py_False); + if (stream == NULL) + goto cleanup; + + Py_XDECREF(tok->decoding_readline); + readline = PyObject_GetAttrString(stream, "readline"); + tok->decoding_readline = readline; + + /* The file has been reopened; parsing will restart from + * the beginning of the file, we have to reset the line number. + * But this function has been called from inside tok_nextc() which + * will increment lineno before it returns. So we set it -1 so that + * the next call to tok_nextc() will start with tok->lineno == 0. + */ + tok->lineno = -1; cleanup: - Py_XDECREF(stream); - Py_XDECREF(io); - return readline != NULL; + Py_XDECREF(stream); + Py_XDECREF(io); + return readline != NULL; } /* Fetch the next byte from TOK. */ static int fp_getc(struct tok_state *tok) { - return getc(tok->fp); + return getc(tok->fp); } /* Unfetch the last byte back into TOK. */ static void fp_ungetc(int c, struct tok_state *tok) { - ungetc(c, tok->fp); + ungetc(c, tok->fp); } /* Check whether the characters at s start a valid @@ -509,27 +509,27 @@ the sequence if yes, 0 if not. */ static int valid_utf8(const unsigned char* s) { - int expected = 0; - int length; - if (*s < 0x80) - /* single-byte code */ - return 1; - if (*s < 0xc0) - /* following byte */ - return 0; - if (*s < 0xE0) - expected = 1; - else if (*s < 0xF0) - expected = 2; - else if (*s < 0xF8) - expected = 3; - else - return 0; - length = expected + 1; - for (; expected; expected--) - if (s[expected] < 0x80 || s[expected] >= 0xC0) - return 0; - return length; + int expected = 0; + int length; + if (*s < 0x80) + /* single-byte code */ + return 1; + if (*s < 0xc0) + /* following byte */ + return 0; + if (*s < 0xE0) + expected = 1; + else if (*s < 0xF0) + expected = 2; + else if (*s < 0xF8) + expected = 3; + else + return 0; + length = expected + 1; + for (; expected; expected--) + if (s[expected] < 0x80 || s[expected] >= 0xC0) + return 0; + return length; } /* Read a line of input from TOK. Determine encoding @@ -538,95 +538,95 @@ static char * decoding_fgets(char *s, int size, struct tok_state *tok) { - char *line = NULL; - int badchar = 0; - for (;;) { - if (tok->decoding_state == STATE_NORMAL) { - /* We already have a codec associated with - this input. */ - line = fp_readl(s, size, tok); - break; - } else if (tok->decoding_state == STATE_RAW) { - /* We want a 'raw' read. */ - line = Py_UniversalNewlineFgets(s, size, - tok->fp, NULL); - break; - } else { - /* We have not yet determined the encoding. - If an encoding is found, use the file-pointer - reader functions from now on. */ - if (!check_bom(fp_getc, fp_ungetc, fp_setreadl, tok)) - return error_ret(tok); - assert(tok->decoding_state != STATE_INIT); - } - } - if (line != NULL && tok->lineno < 2 && !tok->read_coding_spec) { - if (!check_coding_spec(line, strlen(line), tok, fp_setreadl)) { - return error_ret(tok); - } - } + char *line = NULL; + int badchar = 0; + for (;;) { + if (tok->decoding_state == STATE_NORMAL) { + /* We already have a codec associated with + this input. */ + line = fp_readl(s, size, tok); + break; + } else if (tok->decoding_state == STATE_RAW) { + /* We want a 'raw' read. */ + line = Py_UniversalNewlineFgets(s, size, + tok->fp, NULL); + break; + } else { + /* We have not yet determined the encoding. + If an encoding is found, use the file-pointer + reader functions from now on. */ + if (!check_bom(fp_getc, fp_ungetc, fp_setreadl, tok)) + return error_ret(tok); + assert(tok->decoding_state != STATE_INIT); + } + } + if (line != NULL && tok->lineno < 2 && !tok->read_coding_spec) { + if (!check_coding_spec(line, strlen(line), tok, fp_setreadl)) { + return error_ret(tok); + } + } #ifndef PGEN - /* The default encoding is UTF-8, so make sure we don't have any - non-UTF-8 sequences in it. */ - if (line && !tok->encoding) { - unsigned char *c; - int length; - for (c = (unsigned char *)line; *c; c += length) - if (!(length = valid_utf8(c))) { - badchar = *c; - break; - } - } - if (badchar) { - char buf[500]; - /* Need to add 1 to the line number, since this line - has not been counted, yet. */ - sprintf(buf, - "Non-UTF-8 code starting with '\\x%.2x' " - "in file %.200s on line %i, " - "but no encoding declared; " - "see http://python.org/dev/peps/pep-0263/ for details", - badchar, tok->filename, tok->lineno + 1); - PyErr_SetString(PyExc_SyntaxError, buf); - return error_ret(tok); - } + /* The default encoding is UTF-8, so make sure we don't have any + non-UTF-8 sequences in it. */ + if (line && !tok->encoding) { + unsigned char *c; + int length; + for (c = (unsigned char *)line; *c; c += length) + if (!(length = valid_utf8(c))) { + badchar = *c; + break; + } + } + if (badchar) { + char buf[500]; + /* Need to add 1 to the line number, since this line + has not been counted, yet. */ + sprintf(buf, + "Non-UTF-8 code starting with '\\x%.2x' " + "in file %.200s on line %i, " + "but no encoding declared; " + "see http://python.org/dev/peps/pep-0263/ for details", + badchar, tok->filename, tok->lineno + 1); + PyErr_SetString(PyExc_SyntaxError, buf); + return error_ret(tok); + } #endif - return line; + return line; } static int decoding_feof(struct tok_state *tok) { - if (tok->decoding_state != STATE_NORMAL) { - return feof(tok->fp); - } else { - PyObject* buf = tok->decoding_buffer; - if (buf == NULL) { - buf = PyObject_CallObject(tok->decoding_readline, NULL); - if (buf == NULL) { - error_ret(tok); - return 1; - } else { - tok->decoding_buffer = buf; - } - } - return PyObject_Length(buf) == 0; - } + if (tok->decoding_state != STATE_NORMAL) { + return feof(tok->fp); + } else { + PyObject* buf = tok->decoding_buffer; + if (buf == NULL) { + buf = PyObject_CallObject(tok->decoding_readline, NULL); + if (buf == NULL) { + error_ret(tok); + return 1; + } else { + tok->decoding_buffer = buf; + } + } + return PyObject_Length(buf) == 0; + } } /* Fetch a byte from TOK, using the string buffer. */ static int buf_getc(struct tok_state *tok) { - return Py_CHARMASK(*tok->str++); + return Py_CHARMASK(*tok->str++); } /* Unfetch a byte from TOK, using the string buffer. */ static void buf_ungetc(int c, struct tok_state *tok) { - tok->str--; - assert(Py_CHARMASK(*tok->str) == c); /* tok->cur may point to read-only segment */ + tok->str--; + assert(Py_CHARMASK(*tok->str) == c); /* tok->cur may point to read-only segment */ } /* Set the readline function for TOK to ENC. For the string-based @@ -634,8 +634,8 @@ static int buf_setreadl(struct tok_state *tok, const char* enc) { - tok->enc = enc; - return 1; + tok->enc = enc; + return 1; } /* Return a UTF-8 encoding Python string object from the @@ -643,13 +643,13 @@ static PyObject * translate_into_utf8(const char* str, const char* enc) { - PyObject *utf8; - PyObject* buf = PyUnicode_Decode(str, strlen(str), enc, NULL); - if (buf == NULL) - return NULL; - utf8 = PyUnicode_AsUTF8String(buf); - Py_DECREF(buf); - return utf8; + PyObject *utf8; + PyObject* buf = PyUnicode_Decode(str, strlen(str), enc, NULL); + if (buf == NULL) + return NULL; + utf8 = PyUnicode_AsUTF8String(buf); + Py_DECREF(buf); + return utf8; } /* Decode a byte string STR for use as the buffer of TOK. @@ -659,53 +659,53 @@ static const char * decode_str(const char *str, struct tok_state *tok) { - PyObject* utf8 = NULL; - const char *s; - const char *newl[2] = {NULL, NULL}; - int lineno = 0; - tok->enc = NULL; - tok->str = str; - if (!check_bom(buf_getc, buf_ungetc, buf_setreadl, tok)) - return error_ret(tok); - str = tok->str; /* string after BOM if any */ - assert(str); - if (tok->enc != NULL) { - utf8 = translate_into_utf8(str, tok->enc); - if (utf8 == NULL) - return error_ret(tok); - str = PyBytes_AsString(utf8); - } - for (s = str;; s++) { - if (*s == '\0') break; - else if (*s == '\n') { - assert(lineno < 2); - newl[lineno] = s; - lineno++; - if (lineno == 2) break; - } - } - tok->enc = NULL; - /* need to check line 1 and 2 separately since check_coding_spec - assumes a single line as input */ - if (newl[0]) { - if (!check_coding_spec(str, newl[0] - str, tok, buf_setreadl)) - return error_ret(tok); - if (tok->enc == NULL && newl[1]) { - if (!check_coding_spec(newl[0]+1, newl[1] - newl[0], - tok, buf_setreadl)) - return error_ret(tok); - } - } - if (tok->enc != NULL) { - assert(utf8 == NULL); - utf8 = translate_into_utf8(str, tok->enc); - if (utf8 == NULL) - return error_ret(tok); - str = PyBytes_AS_STRING(utf8); - } - assert(tok->decoding_buffer == NULL); - tok->decoding_buffer = utf8; /* CAUTION */ - return str; + PyObject* utf8 = NULL; + const char *s; + const char *newl[2] = {NULL, NULL}; + int lineno = 0; + tok->enc = NULL; + tok->str = str; + if (!check_bom(buf_getc, buf_ungetc, buf_setreadl, tok)) + return error_ret(tok); + str = tok->str; /* string after BOM if any */ + assert(str); + if (tok->enc != NULL) { + utf8 = translate_into_utf8(str, tok->enc); + if (utf8 == NULL) + return error_ret(tok); + str = PyBytes_AsString(utf8); + } + for (s = str;; s++) { + if (*s == '\0') break; + else if (*s == '\n') { + assert(lineno < 2); + newl[lineno] = s; + lineno++; + if (lineno == 2) break; + } + } + tok->enc = NULL; + /* need to check line 1 and 2 separately since check_coding_spec + assumes a single line as input */ + if (newl[0]) { + if (!check_coding_spec(str, newl[0] - str, tok, buf_setreadl)) + return error_ret(tok); + if (tok->enc == NULL && newl[1]) { + if (!check_coding_spec(newl[0]+1, newl[1] - newl[0], + tok, buf_setreadl)) + return error_ret(tok); + } + } + if (tok->enc != NULL) { + assert(utf8 == NULL); + utf8 = translate_into_utf8(str, tok->enc); + if (utf8 == NULL) + return error_ret(tok); + str = PyBytes_AS_STRING(utf8); + } + assert(tok->decoding_buffer == NULL); + tok->decoding_buffer = utf8; /* CAUTION */ + return str; } #endif /* PGEN */ @@ -715,40 +715,40 @@ struct tok_state * PyTokenizer_FromString(const char *str) { - struct tok_state *tok = tok_new(); - if (tok == NULL) - return NULL; - str = (char *)decode_str(str, tok); - if (str == NULL) { - PyTokenizer_Free(tok); - return NULL; - } - - /* XXX: constify members. */ - tok->buf = tok->cur = tok->end = tok->inp = (char*)str; - return tok; + struct tok_state *tok = tok_new(); + if (tok == NULL) + return NULL; + str = (char *)decode_str(str, tok); + if (str == NULL) { + PyTokenizer_Free(tok); + return NULL; + } + + /* XXX: constify members. */ + tok->buf = tok->cur = tok->end = tok->inp = (char*)str; + return tok; } struct tok_state * PyTokenizer_FromUTF8(const char *str) { - struct tok_state *tok = tok_new(); - if (tok == NULL) - return NULL; - tok->decoding_state = STATE_RAW; - tok->read_coding_spec = 1; - tok->enc = NULL; - tok->str = str; - tok->encoding = (char *)PyMem_MALLOC(6); - if (!tok->encoding) { - PyTokenizer_Free(tok); - return NULL; - } - strcpy(tok->encoding, "utf-8"); - - /* XXX: constify members. */ - tok->buf = tok->cur = tok->end = tok->inp = (char*)str; - return tok; + struct tok_state *tok = tok_new(); + if (tok == NULL) + return NULL; + tok->decoding_state = STATE_RAW; + tok->read_coding_spec = 1; + tok->enc = NULL; + tok->str = str; + tok->encoding = (char *)PyMem_MALLOC(6); + if (!tok->encoding) { + PyTokenizer_Free(tok); + return NULL; + } + strcpy(tok->encoding, "utf-8"); + + /* XXX: constify members. */ + tok->buf = tok->cur = tok->end = tok->inp = (char*)str; + return tok; } @@ -757,30 +757,30 @@ struct tok_state * PyTokenizer_FromFile(FILE *fp, char* enc, char *ps1, char *ps2) { - struct tok_state *tok = tok_new(); - if (tok == NULL) - return NULL; - if ((tok->buf = (char *)PyMem_MALLOC(BUFSIZ)) == NULL) { - PyTokenizer_Free(tok); - return NULL; - } - tok->cur = tok->inp = tok->buf; - tok->end = tok->buf + BUFSIZ; - tok->fp = fp; - tok->prompt = ps1; - tok->nextprompt = ps2; - if (enc != NULL) { - /* Must copy encoding declaration since it - gets copied into the parse tree. */ - tok->encoding = PyMem_MALLOC(strlen(enc)+1); - if (!tok->encoding) { - PyTokenizer_Free(tok); - return NULL; - } - strcpy(tok->encoding, enc); - tok->decoding_state = STATE_NORMAL; - } - return tok; + struct tok_state *tok = tok_new(); + if (tok == NULL) + return NULL; + if ((tok->buf = (char *)PyMem_MALLOC(BUFSIZ)) == NULL) { + PyTokenizer_Free(tok); + return NULL; + } + tok->cur = tok->inp = tok->buf; + tok->end = tok->buf + BUFSIZ; + tok->fp = fp; + tok->prompt = ps1; + tok->nextprompt = ps2; + if (enc != NULL) { + /* Must copy encoding declaration since it + gets copied into the parse tree. */ + tok->encoding = PyMem_MALLOC(strlen(enc)+1); + if (!tok->encoding) { + PyTokenizer_Free(tok); + return NULL; + } + strcpy(tok->encoding, enc); + tok->decoding_state = STATE_NORMAL; + } + return tok; } @@ -789,15 +789,15 @@ void PyTokenizer_Free(struct tok_state *tok) { - if (tok->encoding != NULL) - PyMem_FREE(tok->encoding); + if (tok->encoding != NULL) + PyMem_FREE(tok->encoding); #ifndef PGEN - Py_XDECREF(tok->decoding_readline); - Py_XDECREF(tok->decoding_buffer); + Py_XDECREF(tok->decoding_readline); + Py_XDECREF(tok->decoding_buffer); #endif - if (tok->fp != NULL && tok->buf != NULL) - PyMem_FREE(tok->buf); - PyMem_FREE(tok); + if (tok->fp != NULL && tok->buf != NULL) + PyMem_FREE(tok->buf); + PyMem_FREE(tok); } /* Get next char, updating state; error code goes into tok->done */ @@ -805,188 +805,188 @@ static int tok_nextc(register struct tok_state *tok) { - for (;;) { - if (tok->cur != tok->inp) { - return Py_CHARMASK(*tok->cur++); /* Fast path */ - } - if (tok->done != E_OK) - return EOF; - if (tok->fp == NULL) { - char *end = strchr(tok->inp, '\n'); - if (end != NULL) - end++; - else { - end = strchr(tok->inp, '\0'); - if (end == tok->inp) { - tok->done = E_EOF; - return EOF; - } - } - if (tok->start == NULL) - tok->buf = tok->cur; - tok->line_start = tok->cur; - tok->lineno++; - tok->inp = end; - return Py_CHARMASK(*tok->cur++); - } - if (tok->prompt != NULL) { - char *newtok = PyOS_Readline(stdin, stdout, tok->prompt); + for (;;) { + if (tok->cur != tok->inp) { + return Py_CHARMASK(*tok->cur++); /* Fast path */ + } + if (tok->done != E_OK) + return EOF; + if (tok->fp == NULL) { + char *end = strchr(tok->inp, '\n'); + if (end != NULL) + end++; + else { + end = strchr(tok->inp, '\0'); + if (end == tok->inp) { + tok->done = E_EOF; + return EOF; + } + } + if (tok->start == NULL) + tok->buf = tok->cur; + tok->line_start = tok->cur; + tok->lineno++; + tok->inp = end; + return Py_CHARMASK(*tok->cur++); + } + if (tok->prompt != NULL) { + char *newtok = PyOS_Readline(stdin, stdout, tok->prompt); #ifndef PGEN - if (tok->encoding && newtok && *newtok) { - /* Recode to UTF-8 */ - Py_ssize_t buflen; - const char* buf; - PyObject *u = translate_into_utf8(newtok, tok->encoding); - PyMem_FREE(newtok); - if (!u) { - tok->done = E_DECODE; - return EOF; - } - buflen = PyBytes_GET_SIZE(u); - buf = PyBytes_AS_STRING(u); - if (!buf) { - Py_DECREF(u); - tok->done = E_DECODE; - return EOF; - } - newtok = PyMem_MALLOC(buflen+1); - strcpy(newtok, buf); - Py_DECREF(u); - } + if (tok->encoding && newtok && *newtok) { + /* Recode to UTF-8 */ + Py_ssize_t buflen; + const char* buf; + PyObject *u = translate_into_utf8(newtok, tok->encoding); + PyMem_FREE(newtok); + if (!u) { + tok->done = E_DECODE; + return EOF; + } + buflen = PyBytes_GET_SIZE(u); + buf = PyBytes_AS_STRING(u); + if (!buf) { + Py_DECREF(u); + tok->done = E_DECODE; + return EOF; + } + newtok = PyMem_MALLOC(buflen+1); + strcpy(newtok, buf); + Py_DECREF(u); + } #endif - if (tok->nextprompt != NULL) - tok->prompt = tok->nextprompt; - if (newtok == NULL) - tok->done = E_INTR; - else if (*newtok == '\0') { - PyMem_FREE(newtok); - tok->done = E_EOF; - } - else if (tok->start != NULL) { - size_t start = tok->start - tok->buf; - size_t oldlen = tok->cur - tok->buf; - size_t newlen = oldlen + strlen(newtok); - char *buf = tok->buf; - buf = (char *)PyMem_REALLOC(buf, newlen+1); - tok->lineno++; - if (buf == NULL) { - PyMem_FREE(tok->buf); - tok->buf = NULL; - PyMem_FREE(newtok); - tok->done = E_NOMEM; - return EOF; - } - tok->buf = buf; - tok->cur = tok->buf + oldlen; - tok->line_start = tok->cur; - strcpy(tok->buf + oldlen, newtok); - PyMem_FREE(newtok); - tok->inp = tok->buf + newlen; - tok->end = tok->inp + 1; - tok->start = tok->buf + start; - } - else { - tok->lineno++; - if (tok->buf != NULL) - PyMem_FREE(tok->buf); - tok->buf = newtok; - tok->line_start = tok->buf; - tok->cur = tok->buf; - tok->line_start = tok->buf; - tok->inp = strchr(tok->buf, '\0'); - tok->end = tok->inp + 1; - } - } - else { - int done = 0; - Py_ssize_t cur = 0; - char *pt; - if (tok->start == NULL) { - if (tok->buf == NULL) { - tok->buf = (char *) - PyMem_MALLOC(BUFSIZ); - if (tok->buf == NULL) { - tok->done = E_NOMEM; - return EOF; - } - tok->end = tok->buf + BUFSIZ; - } - if (decoding_fgets(tok->buf, (int)(tok->end - tok->buf), - tok) == NULL) { - tok->done = E_EOF; - done = 1; - } - else { - tok->done = E_OK; - tok->inp = strchr(tok->buf, '\0'); - done = tok->inp[-1] == '\n'; - } - } - else { - cur = tok->cur - tok->buf; - if (decoding_feof(tok)) { - tok->done = E_EOF; - done = 1; - } - else - tok->done = E_OK; - } - tok->lineno++; - /* Read until '\n' or EOF */ - while (!done) { - Py_ssize_t curstart = tok->start == NULL ? -1 : - tok->start - tok->buf; - Py_ssize_t curvalid = tok->inp - tok->buf; - Py_ssize_t newsize = curvalid + BUFSIZ; - char *newbuf = tok->buf; - newbuf = (char *)PyMem_REALLOC(newbuf, - newsize); - if (newbuf == NULL) { - tok->done = E_NOMEM; - tok->cur = tok->inp; - return EOF; - } - tok->buf = newbuf; - tok->inp = tok->buf + curvalid; - tok->end = tok->buf + newsize; - tok->start = curstart < 0 ? NULL : - tok->buf + curstart; - if (decoding_fgets(tok->inp, - (int)(tok->end - tok->inp), - tok) == NULL) { - /* Break out early on decoding - errors, as tok->buf will be NULL - */ - if (tok->decoding_erred) - return EOF; - /* Last line does not end in \n, - fake one */ - strcpy(tok->inp, "\n"); - } - tok->inp = strchr(tok->inp, '\0'); - done = tok->inp[-1] == '\n'; - } - if (tok->buf != NULL) { - tok->cur = tok->buf + cur; - tok->line_start = tok->cur; - /* replace "\r\n" with "\n" */ - /* For Mac leave the \r, giving a syntax error */ - pt = tok->inp - 2; - if (pt >= tok->buf && *pt == '\r') { - *pt++ = '\n'; - *pt = '\0'; - tok->inp = pt; - } - } - } - if (tok->done != E_OK) { - if (tok->prompt != NULL) - PySys_WriteStderr("\n"); - tok->cur = tok->inp; - return EOF; - } - } - /*NOTREACHED*/ + if (tok->nextprompt != NULL) + tok->prompt = tok->nextprompt; + if (newtok == NULL) + tok->done = E_INTR; + else if (*newtok == '\0') { + PyMem_FREE(newtok); + tok->done = E_EOF; + } + else if (tok->start != NULL) { + size_t start = tok->start - tok->buf; + size_t oldlen = tok->cur - tok->buf; + size_t newlen = oldlen + strlen(newtok); + char *buf = tok->buf; + buf = (char *)PyMem_REALLOC(buf, newlen+1); + tok->lineno++; + if (buf == NULL) { + PyMem_FREE(tok->buf); + tok->buf = NULL; + PyMem_FREE(newtok); + tok->done = E_NOMEM; + return EOF; + } + tok->buf = buf; + tok->cur = tok->buf + oldlen; + tok->line_start = tok->cur; + strcpy(tok->buf + oldlen, newtok); + PyMem_FREE(newtok); + tok->inp = tok->buf + newlen; + tok->end = tok->inp + 1; + tok->start = tok->buf + start; + } + else { + tok->lineno++; + if (tok->buf != NULL) + PyMem_FREE(tok->buf); + tok->buf = newtok; + tok->line_start = tok->buf; + tok->cur = tok->buf; + tok->line_start = tok->buf; + tok->inp = strchr(tok->buf, '\0'); + tok->end = tok->inp + 1; + } + } + else { + int done = 0; + Py_ssize_t cur = 0; + char *pt; + if (tok->start == NULL) { + if (tok->buf == NULL) { + tok->buf = (char *) + PyMem_MALLOC(BUFSIZ); + if (tok->buf == NULL) { + tok->done = E_NOMEM; + return EOF; + } + tok->end = tok->buf + BUFSIZ; + } + if (decoding_fgets(tok->buf, (int)(tok->end - tok->buf), + tok) == NULL) { + tok->done = E_EOF; + done = 1; + } + else { + tok->done = E_OK; + tok->inp = strchr(tok->buf, '\0'); + done = tok->inp[-1] == '\n'; + } + } + else { + cur = tok->cur - tok->buf; + if (decoding_feof(tok)) { + tok->done = E_EOF; + done = 1; + } + else + tok->done = E_OK; + } + tok->lineno++; + /* Read until '\n' or EOF */ + while (!done) { + Py_ssize_t curstart = tok->start == NULL ? -1 : + tok->start - tok->buf; + Py_ssize_t curvalid = tok->inp - tok->buf; + Py_ssize_t newsize = curvalid + BUFSIZ; + char *newbuf = tok->buf; + newbuf = (char *)PyMem_REALLOC(newbuf, + newsize); + if (newbuf == NULL) { + tok->done = E_NOMEM; + tok->cur = tok->inp; + return EOF; + } + tok->buf = newbuf; + tok->inp = tok->buf + curvalid; + tok->end = tok->buf + newsize; + tok->start = curstart < 0 ? NULL : + tok->buf + curstart; + if (decoding_fgets(tok->inp, + (int)(tok->end - tok->inp), + tok) == NULL) { + /* Break out early on decoding + errors, as tok->buf will be NULL + */ + if (tok->decoding_erred) + return EOF; + /* Last line does not end in \n, + fake one */ + strcpy(tok->inp, "\n"); + } + tok->inp = strchr(tok->inp, '\0'); + done = tok->inp[-1] == '\n'; + } + if (tok->buf != NULL) { + tok->cur = tok->buf + cur; + tok->line_start = tok->cur; + /* replace "\r\n" with "\n" */ + /* For Mac leave the \r, giving a syntax error */ + pt = tok->inp - 2; + if (pt >= tok->buf && *pt == '\r') { + *pt++ = '\n'; + *pt = '\0'; + tok->inp = pt; + } + } + } + if (tok->done != E_OK) { + if (tok->prompt != NULL) + PySys_WriteStderr("\n"); + tok->cur = tok->inp; + return EOF; + } + } + /*NOTREACHED*/ } @@ -995,12 +995,12 @@ static void tok_backup(register struct tok_state *tok, register int c) { - if (c != EOF) { - if (--tok->cur < tok->buf) - Py_FatalError("tok_backup: beginning of buffer"); - if (*tok->cur != c) - *tok->cur = c; - } + if (c != EOF) { + if (--tok->cur < tok->buf) + Py_FatalError("tok_backup: beginning of buffer"); + if (*tok->cur != c) + *tok->cur = c; + } } @@ -1009,181 +1009,181 @@ int PyToken_OneChar(int c) { - switch (c) { - case '(': return LPAR; - case ')': return RPAR; - case '[': return LSQB; - case ']': return RSQB; - case ':': return COLON; - case ',': return COMMA; - case ';': return SEMI; - case '+': return PLUS; - case '-': return MINUS; - case '*': return STAR; - case '/': return SLASH; - case '|': return VBAR; - case '&': return AMPER; - case '<': return LESS; - case '>': return GREATER; - case '=': return EQUAL; - case '.': return DOT; - case '%': return PERCENT; - case '{': return LBRACE; - case '}': return RBRACE; - case '^': return CIRCUMFLEX; - case '~': return TILDE; - case '@': return AT; - default: return OP; - } + switch (c) { + case '(': return LPAR; + case ')': return RPAR; + case '[': return LSQB; + case ']': return RSQB; + case ':': return COLON; + case ',': return COMMA; + case ';': return SEMI; + case '+': return PLUS; + case '-': return MINUS; + case '*': return STAR; + case '/': return SLASH; + case '|': return VBAR; + case '&': return AMPER; + case '<': return LESS; + case '>': return GREATER; + case '=': return EQUAL; + case '.': return DOT; + case '%': return PERCENT; + case '{': return LBRACE; + case '}': return RBRACE; + case '^': return CIRCUMFLEX; + case '~': return TILDE; + case '@': return AT; + default: return OP; + } } int PyToken_TwoChars(int c1, int c2) { - switch (c1) { - case '=': - switch (c2) { - case '=': return EQEQUAL; - } - break; - case '!': - switch (c2) { - case '=': return NOTEQUAL; - } - break; - case '<': - switch (c2) { - case '>': return NOTEQUAL; - case '=': return LESSEQUAL; - case '<': return LEFTSHIFT; - } - break; - case '>': - switch (c2) { - case '=': return GREATEREQUAL; - case '>': return RIGHTSHIFT; - } - break; - case '+': - switch (c2) { - case '=': return PLUSEQUAL; - } - break; - case '-': - switch (c2) { - case '=': return MINEQUAL; - case '>': return RARROW; - } - break; - case '*': - switch (c2) { - case '*': return DOUBLESTAR; - case '=': return STAREQUAL; - } - break; - case '/': - switch (c2) { - case '/': return DOUBLESLASH; - case '=': return SLASHEQUAL; - } - break; - case '|': - switch (c2) { - case '=': return VBAREQUAL; - } - break; - case '%': - switch (c2) { - case '=': return PERCENTEQUAL; - } - break; - case '&': - switch (c2) { - case '=': return AMPEREQUAL; - } - break; - case '^': - switch (c2) { - case '=': return CIRCUMFLEXEQUAL; - } - break; - } - return OP; + switch (c1) { + case '=': + switch (c2) { + case '=': return EQEQUAL; + } + break; + case '!': + switch (c2) { + case '=': return NOTEQUAL; + } + break; + case '<': + switch (c2) { + case '>': return NOTEQUAL; + case '=': return LESSEQUAL; + case '<': return LEFTSHIFT; + } + break; + case '>': + switch (c2) { + case '=': return GREATEREQUAL; + case '>': return RIGHTSHIFT; + } + break; + case '+': + switch (c2) { + case '=': return PLUSEQUAL; + } + break; + case '-': + switch (c2) { + case '=': return MINEQUAL; + case '>': return RARROW; + } + break; + case '*': + switch (c2) { + case '*': return DOUBLESTAR; + case '=': return STAREQUAL; + } + break; + case '/': + switch (c2) { + case '/': return DOUBLESLASH; + case '=': return SLASHEQUAL; + } + break; + case '|': + switch (c2) { + case '=': return VBAREQUAL; + } + break; + case '%': + switch (c2) { + case '=': return PERCENTEQUAL; + } + break; + case '&': + switch (c2) { + case '=': return AMPEREQUAL; + } + break; + case '^': + switch (c2) { + case '=': return CIRCUMFLEXEQUAL; + } + break; + } + return OP; } int PyToken_ThreeChars(int c1, int c2, int c3) { - switch (c1) { - case '<': - switch (c2) { - case '<': - switch (c3) { - case '=': - return LEFTSHIFTEQUAL; - } - break; - } - break; - case '>': - switch (c2) { - case '>': - switch (c3) { - case '=': - return RIGHTSHIFTEQUAL; - } - break; - } - break; - case '*': - switch (c2) { - case '*': - switch (c3) { - case '=': - return DOUBLESTAREQUAL; - } - break; - } - break; - case '/': - switch (c2) { - case '/': - switch (c3) { - case '=': - return DOUBLESLASHEQUAL; - } - break; - } - break; + switch (c1) { + case '<': + switch (c2) { + case '<': + switch (c3) { + case '=': + return LEFTSHIFTEQUAL; + } + break; + } + break; + case '>': + switch (c2) { + case '>': + switch (c3) { + case '=': + return RIGHTSHIFTEQUAL; + } + break; + } + break; + case '*': + switch (c2) { + case '*': + switch (c3) { + case '=': + return DOUBLESTAREQUAL; + } + break; + } + break; + case '/': + switch (c2) { + case '/': + switch (c3) { + case '=': + return DOUBLESLASHEQUAL; + } + break; + } + break; + case '.': + switch (c2) { case '.': - switch (c2) { - case '.': - switch (c3) { - case '.': - return ELLIPSIS; - } - break; - } - break; - } - return OP; + switch (c3) { + case '.': + return ELLIPSIS; + } + break; + } + break; + } + return OP; } static int indenterror(struct tok_state *tok) { - if (tok->alterror) { - tok->done = E_TABSPACE; - tok->cur = tok->inp; - return 1; - } - if (tok->altwarning) { - PySys_WriteStderr("%s: inconsistent use of tabs and spaces " - "in indentation\n", tok->filename); - tok->altwarning = 0; - } - return 0; + if (tok->alterror) { + tok->done = E_TABSPACE; + tok->cur = tok->inp; + return 1; + } + if (tok->altwarning) { + PySys_WriteStderr("%s: inconsistent use of tabs and spaces " + "in indentation\n", tok->filename); + tok->altwarning = 0; + } + return 0; } #ifdef PGEN @@ -1193,23 +1193,23 @@ static int verify_identifier(struct tok_state *tok) { - PyObject *s; - int result; - s = PyUnicode_DecodeUTF8(tok->start, tok->cur - tok->start, NULL); - if (s == NULL) { - if (PyErr_ExceptionMatches(PyExc_UnicodeDecodeError)) { - PyErr_Clear(); - tok->done = E_IDENTIFIER; - } else { - tok->done = E_ERROR; - } - return 0; - } - result = PyUnicode_IsIdentifier(s); - Py_DECREF(s); - if (result == 0) - tok->done = E_IDENTIFIER; - return result; + PyObject *s; + int result; + s = PyUnicode_DecodeUTF8(tok->start, tok->cur - tok->start, NULL); + if (s == NULL) { + if (PyErr_ExceptionMatches(PyExc_UnicodeDecodeError)) { + PyErr_Clear(); + tok->done = E_IDENTIFIER; + } else { + tok->done = E_ERROR; + } + return 0; + } + result = PyUnicode_IsIdentifier(s); + Py_DECREF(s); + if (result == 0) + tok->done = E_IDENTIFIER; + return result; } #endif @@ -1218,413 +1218,413 @@ static int tok_get(register struct tok_state *tok, char **p_start, char **p_end) { - register int c; - int blankline, nonascii; + register int c; + int blankline, nonascii; - *p_start = *p_end = NULL; + *p_start = *p_end = NULL; nextline: - tok->start = NULL; - blankline = 0; + tok->start = NULL; + blankline = 0; + + /* Get indentation level */ + if (tok->atbol) { + register int col = 0; + register int altcol = 0; + tok->atbol = 0; + for (;;) { + c = tok_nextc(tok); + if (c == ' ') + col++, altcol++; + else if (c == '\t') { + col = (col/tok->tabsize + 1) * tok->tabsize; + altcol = (altcol/tok->alttabsize + 1) + * tok->alttabsize; + } + else if (c == '\014') /* Control-L (formfeed) */ + col = altcol = 0; /* For Emacs users */ + else + break; + } + tok_backup(tok, c); + if (c == '#' || c == '\n') { + /* Lines with only whitespace and/or comments + shouldn't affect the indentation and are + not passed to the parser as NEWLINE tokens, + except *totally* empty lines in interactive + mode, which signal the end of a command group. */ + if (col == 0 && c == '\n' && tok->prompt != NULL) + blankline = 0; /* Let it through */ + else + blankline = 1; /* Ignore completely */ + /* We can't jump back right here since we still + may need to skip to the end of a comment */ + } + if (!blankline && tok->level == 0) { + if (col == tok->indstack[tok->indent]) { + /* No change */ + if (altcol != tok->altindstack[tok->indent]) { + if (indenterror(tok)) + return ERRORTOKEN; + } + } + else if (col > tok->indstack[tok->indent]) { + /* Indent -- always one */ + if (tok->indent+1 >= MAXINDENT) { + tok->done = E_TOODEEP; + tok->cur = tok->inp; + return ERRORTOKEN; + } + if (altcol <= tok->altindstack[tok->indent]) { + if (indenterror(tok)) + return ERRORTOKEN; + } + tok->pendin++; + tok->indstack[++tok->indent] = col; + tok->altindstack[tok->indent] = altcol; + } + else /* col < tok->indstack[tok->indent] */ { + /* Dedent -- any number, must be consistent */ + while (tok->indent > 0 && + col < tok->indstack[tok->indent]) { + tok->pendin--; + tok->indent--; + } + if (col != tok->indstack[tok->indent]) { + tok->done = E_DEDENT; + tok->cur = tok->inp; + return ERRORTOKEN; + } + if (altcol != tok->altindstack[tok->indent]) { + if (indenterror(tok)) + return ERRORTOKEN; + } + } + } + } + + tok->start = tok->cur; - /* Get indentation level */ - if (tok->atbol) { - register int col = 0; - register int altcol = 0; - tok->atbol = 0; - for (;;) { - c = tok_nextc(tok); - if (c == ' ') - col++, altcol++; - else if (c == '\t') { - col = (col/tok->tabsize + 1) * tok->tabsize; - altcol = (altcol/tok->alttabsize + 1) - * tok->alttabsize; - } - else if (c == '\014') /* Control-L (formfeed) */ - col = altcol = 0; /* For Emacs users */ - else - break; - } - tok_backup(tok, c); - if (c == '#' || c == '\n') { - /* Lines with only whitespace and/or comments - shouldn't affect the indentation and are - not passed to the parser as NEWLINE tokens, - except *totally* empty lines in interactive - mode, which signal the end of a command group. */ - if (col == 0 && c == '\n' && tok->prompt != NULL) - blankline = 0; /* Let it through */ - else - blankline = 1; /* Ignore completely */ - /* We can't jump back right here since we still - may need to skip to the end of a comment */ - } - if (!blankline && tok->level == 0) { - if (col == tok->indstack[tok->indent]) { - /* No change */ - if (altcol != tok->altindstack[tok->indent]) { - if (indenterror(tok)) - return ERRORTOKEN; - } - } - else if (col > tok->indstack[tok->indent]) { - /* Indent -- always one */ - if (tok->indent+1 >= MAXINDENT) { - tok->done = E_TOODEEP; - tok->cur = tok->inp; - return ERRORTOKEN; - } - if (altcol <= tok->altindstack[tok->indent]) { - if (indenterror(tok)) - return ERRORTOKEN; - } - tok->pendin++; - tok->indstack[++tok->indent] = col; - tok->altindstack[tok->indent] = altcol; - } - else /* col < tok->indstack[tok->indent] */ { - /* Dedent -- any number, must be consistent */ - while (tok->indent > 0 && - col < tok->indstack[tok->indent]) { - tok->pendin--; - tok->indent--; - } - if (col != tok->indstack[tok->indent]) { - tok->done = E_DEDENT; - tok->cur = tok->inp; - return ERRORTOKEN; - } - if (altcol != tok->altindstack[tok->indent]) { - if (indenterror(tok)) - return ERRORTOKEN; - } - } - } - } - - tok->start = tok->cur; - - /* Return pending indents/dedents */ - if (tok->pendin != 0) { - if (tok->pendin < 0) { - tok->pendin++; - return DEDENT; - } - else { - tok->pendin--; - return INDENT; - } - } + /* Return pending indents/dedents */ + if (tok->pendin != 0) { + if (tok->pendin < 0) { + tok->pendin++; + return DEDENT; + } + else { + tok->pendin--; + return INDENT; + } + } again: - tok->start = NULL; - /* Skip spaces */ - do { - c = tok_nextc(tok); - } while (c == ' ' || c == '\t' || c == '\014'); - - /* Set start of current token */ - tok->start = tok->cur - 1; - - /* Skip comment */ - if (c == '#') - while (c != EOF && c != '\n') - c = tok_nextc(tok); - - /* Check for EOF and errors now */ - if (c == EOF) { - return tok->done == E_EOF ? ENDMARKER : ERRORTOKEN; - } - - /* Identifier (most frequent token!) */ - nonascii = 0; - if (is_potential_identifier_start(c)) { - /* Process b"", r"" and br"" */ - if (c == 'b' || c == 'B') { - c = tok_nextc(tok); - if (c == '"' || c == '\'') - goto letter_quote; - } - if (c == 'r' || c == 'R') { - c = tok_nextc(tok); - if (c == '"' || c == '\'') - goto letter_quote; - } - while (is_potential_identifier_char(c)) { - if (c >= 128) - nonascii = 1; - c = tok_nextc(tok); - } - tok_backup(tok, c); - if (nonascii && - !verify_identifier(tok)) { - tok->done = E_IDENTIFIER; - return ERRORTOKEN; - } - *p_start = tok->start; - *p_end = tok->cur; - return NAME; - } - - /* Newline */ - if (c == '\n') { - tok->atbol = 1; - if (blankline || tok->level > 0) - goto nextline; - *p_start = tok->start; - *p_end = tok->cur - 1; /* Leave '\n' out of the string */ - tok->cont_line = 0; - return NEWLINE; - } - - /* Period or number starting with period? */ - if (c == '.') { - c = tok_nextc(tok); - if (isdigit(c)) { - goto fraction; - } else if (c == '.') { - c = tok_nextc(tok); - if (c == '.') { - *p_start = tok->start; - *p_end = tok->cur; - return ELLIPSIS; - } else { - tok_backup(tok, c); - } - tok_backup(tok, '.'); - } else { - tok_backup(tok, c); - } - *p_start = tok->start; - *p_end = tok->cur; - return DOT; - } - - /* Number */ - if (isdigit(c)) { - if (c == '0') { - /* Hex, octal or binary -- maybe. */ - c = tok_nextc(tok); - if (c == '.') - goto fraction; + tok->start = NULL; + /* Skip spaces */ + do { + c = tok_nextc(tok); + } while (c == ' ' || c == '\t' || c == '\014'); + + /* Set start of current token */ + tok->start = tok->cur - 1; + + /* Skip comment */ + if (c == '#') + while (c != EOF && c != '\n') + c = tok_nextc(tok); + + /* Check for EOF and errors now */ + if (c == EOF) { + return tok->done == E_EOF ? ENDMARKER : ERRORTOKEN; + } + + /* Identifier (most frequent token!) */ + nonascii = 0; + if (is_potential_identifier_start(c)) { + /* Process b"", r"" and br"" */ + if (c == 'b' || c == 'B') { + c = tok_nextc(tok); + if (c == '"' || c == '\'') + goto letter_quote; + } + if (c == 'r' || c == 'R') { + c = tok_nextc(tok); + if (c == '"' || c == '\'') + goto letter_quote; + } + while (is_potential_identifier_char(c)) { + if (c >= 128) + nonascii = 1; + c = tok_nextc(tok); + } + tok_backup(tok, c); + if (nonascii && + !verify_identifier(tok)) { + tok->done = E_IDENTIFIER; + return ERRORTOKEN; + } + *p_start = tok->start; + *p_end = tok->cur; + return NAME; + } + + /* Newline */ + if (c == '\n') { + tok->atbol = 1; + if (blankline || tok->level > 0) + goto nextline; + *p_start = tok->start; + *p_end = tok->cur - 1; /* Leave '\n' out of the string */ + tok->cont_line = 0; + return NEWLINE; + } + + /* Period or number starting with period? */ + if (c == '.') { + c = tok_nextc(tok); + if (isdigit(c)) { + goto fraction; + } else if (c == '.') { + c = tok_nextc(tok); + if (c == '.') { + *p_start = tok->start; + *p_end = tok->cur; + return ELLIPSIS; + } else { + tok_backup(tok, c); + } + tok_backup(tok, '.'); + } else { + tok_backup(tok, c); + } + *p_start = tok->start; + *p_end = tok->cur; + return DOT; + } + + /* Number */ + if (isdigit(c)) { + if (c == '0') { + /* Hex, octal or binary -- maybe. */ + c = tok_nextc(tok); + if (c == '.') + goto fraction; #ifndef WITHOUT_COMPLEX - if (c == 'j' || c == 'J') - goto imaginary; + if (c == 'j' || c == 'J') + goto imaginary; #endif - if (c == 'x' || c == 'X') { + if (c == 'x' || c == 'X') { - /* Hex */ - c = tok_nextc(tok); - if (!isxdigit(c)) { - tok->done = E_TOKEN; - tok_backup(tok, c); - return ERRORTOKEN; - } - do { - c = tok_nextc(tok); - } while (isxdigit(c)); - } - else if (c == 'o' || c == 'O') { - /* Octal */ - c = tok_nextc(tok); - if (c < '0' || c >= '8') { - tok->done = E_TOKEN; - tok_backup(tok, c); - return ERRORTOKEN; - } - do { - c = tok_nextc(tok); - } while ('0' <= c && c < '8'); - } - else if (c == 'b' || c == 'B') { - /* Binary */ - c = tok_nextc(tok); - if (c != '0' && c != '1') { - tok->done = E_TOKEN; - tok_backup(tok, c); - return ERRORTOKEN; - } - do { - c = tok_nextc(tok); - } while (c == '0' || c == '1'); - } - else { - int nonzero = 0; - /* maybe old-style octal; c is first char of it */ - /* in any case, allow '0' as a literal */ - while (c == '0') - c = tok_nextc(tok); - while (isdigit(c)) { - nonzero = 1; - c = tok_nextc(tok); - } - if (c == '.') - goto fraction; - else if (c == 'e' || c == 'E') - goto exponent; + /* Hex */ + c = tok_nextc(tok); + if (!isxdigit(c)) { + tok->done = E_TOKEN; + tok_backup(tok, c); + return ERRORTOKEN; + } + do { + c = tok_nextc(tok); + } while (isxdigit(c)); + } + else if (c == 'o' || c == 'O') { + /* Octal */ + c = tok_nextc(tok); + if (c < '0' || c >= '8') { + tok->done = E_TOKEN; + tok_backup(tok, c); + return ERRORTOKEN; + } + do { + c = tok_nextc(tok); + } while ('0' <= c && c < '8'); + } + else if (c == 'b' || c == 'B') { + /* Binary */ + c = tok_nextc(tok); + if (c != '0' && c != '1') { + tok->done = E_TOKEN; + tok_backup(tok, c); + return ERRORTOKEN; + } + do { + c = tok_nextc(tok); + } while (c == '0' || c == '1'); + } + else { + int nonzero = 0; + /* maybe old-style octal; c is first char of it */ + /* in any case, allow '0' as a literal */ + while (c == '0') + c = tok_nextc(tok); + while (isdigit(c)) { + nonzero = 1; + c = tok_nextc(tok); + } + if (c == '.') + goto fraction; + else if (c == 'e' || c == 'E') + goto exponent; #ifndef WITHOUT_COMPLEX - else if (c == 'j' || c == 'J') - goto imaginary; + else if (c == 'j' || c == 'J') + goto imaginary; #endif - else if (nonzero) { - tok->done = E_TOKEN; - tok_backup(tok, c); - return ERRORTOKEN; - } - } - } - else { - /* Decimal */ - do { - c = tok_nextc(tok); - } while (isdigit(c)); - { - /* Accept floating point numbers. */ - if (c == '.') { - fraction: - /* Fraction */ - do { - c = tok_nextc(tok); - } while (isdigit(c)); - } - if (c == 'e' || c == 'E') { - exponent: - /* Exponent part */ - c = tok_nextc(tok); - if (c == '+' || c == '-') - c = tok_nextc(tok); - if (!isdigit(c)) { - tok->done = E_TOKEN; - tok_backup(tok, c); - return ERRORTOKEN; - } - do { - c = tok_nextc(tok); - } while (isdigit(c)); - } + else if (nonzero) { + tok->done = E_TOKEN; + tok_backup(tok, c); + return ERRORTOKEN; + } + } + } + else { + /* Decimal */ + do { + c = tok_nextc(tok); + } while (isdigit(c)); + { + /* Accept floating point numbers. */ + if (c == '.') { + fraction: + /* Fraction */ + do { + c = tok_nextc(tok); + } while (isdigit(c)); + } + if (c == 'e' || c == 'E') { + exponent: + /* Exponent part */ + c = tok_nextc(tok); + if (c == '+' || c == '-') + c = tok_nextc(tok); + if (!isdigit(c)) { + tok->done = E_TOKEN; + tok_backup(tok, c); + return ERRORTOKEN; + } + do { + c = tok_nextc(tok); + } while (isdigit(c)); + } #ifndef WITHOUT_COMPLEX - if (c == 'j' || c == 'J') - /* Imaginary part */ - imaginary: - c = tok_nextc(tok); + if (c == 'j' || c == 'J') + /* Imaginary part */ + imaginary: + c = tok_nextc(tok); #endif - } - } - tok_backup(tok, c); - *p_start = tok->start; - *p_end = tok->cur; - return NUMBER; - } + } + } + tok_backup(tok, c); + *p_start = tok->start; + *p_end = tok->cur; + return NUMBER; + } letter_quote: - /* String */ - if (c == '\'' || c == '"') { - int quote = c; - int quote_size = 1; /* 1 or 3 */ - int end_quote_size = 0; - - /* Find the quote size and start of string */ - c = tok_nextc(tok); - if (c == quote) { - c = tok_nextc(tok); - if (c == quote) - quote_size = 3; - else - end_quote_size = 1; /* empty string found */ - } - if (c != quote) - tok_backup(tok, c); - - /* Get rest of string */ - while (end_quote_size != quote_size) { - c = tok_nextc(tok); - if (c == EOF) { - if (quote_size == 3) - tok->done = E_EOFS; - else - tok->done = E_EOLS; - tok->cur = tok->inp; - return ERRORTOKEN; - } - if (quote_size == 1 && c == '\n') { - tok->done = E_EOLS; - tok->cur = tok->inp; - return ERRORTOKEN; - } - if (c == quote) - end_quote_size += 1; - else { - end_quote_size = 0; - if (c == '\\') - c = tok_nextc(tok); /* skip escaped char */ - } - } - - *p_start = tok->start; - *p_end = tok->cur; - return STRING; - } - - /* Line continuation */ - if (c == '\\') { - c = tok_nextc(tok); - if (c != '\n') { - tok->done = E_LINECONT; - tok->cur = tok->inp; - return ERRORTOKEN; - } - tok->cont_line = 1; - goto again; /* Read next line */ - } - - /* Check for two-character token */ - { - int c2 = tok_nextc(tok); - int token = PyToken_TwoChars(c, c2); - if (token != OP) { - int c3 = tok_nextc(tok); - int token3 = PyToken_ThreeChars(c, c2, c3); - if (token3 != OP) { - token = token3; - } else { - tok_backup(tok, c3); - } - *p_start = tok->start; - *p_end = tok->cur; - return token; - } - tok_backup(tok, c2); - } - - /* Keep track of parentheses nesting level */ - switch (c) { - case '(': - case '[': - case '{': - tok->level++; - break; - case ')': - case ']': - case '}': - tok->level--; - break; - } - - /* Punctuation character */ - *p_start = tok->start; - *p_end = tok->cur; - return PyToken_OneChar(c); + /* String */ + if (c == '\'' || c == '"') { + int quote = c; + int quote_size = 1; /* 1 or 3 */ + int end_quote_size = 0; + + /* Find the quote size and start of string */ + c = tok_nextc(tok); + if (c == quote) { + c = tok_nextc(tok); + if (c == quote) + quote_size = 3; + else + end_quote_size = 1; /* empty string found */ + } + if (c != quote) + tok_backup(tok, c); + + /* Get rest of string */ + while (end_quote_size != quote_size) { + c = tok_nextc(tok); + if (c == EOF) { + if (quote_size == 3) + tok->done = E_EOFS; + else + tok->done = E_EOLS; + tok->cur = tok->inp; + return ERRORTOKEN; + } + if (quote_size == 1 && c == '\n') { + tok->done = E_EOLS; + tok->cur = tok->inp; + return ERRORTOKEN; + } + if (c == quote) + end_quote_size += 1; + else { + end_quote_size = 0; + if (c == '\\') + c = tok_nextc(tok); /* skip escaped char */ + } + } + + *p_start = tok->start; + *p_end = tok->cur; + return STRING; + } + + /* Line continuation */ + if (c == '\\') { + c = tok_nextc(tok); + if (c != '\n') { + tok->done = E_LINECONT; + tok->cur = tok->inp; + return ERRORTOKEN; + } + tok->cont_line = 1; + goto again; /* Read next line */ + } + + /* Check for two-character token */ + { + int c2 = tok_nextc(tok); + int token = PyToken_TwoChars(c, c2); + if (token != OP) { + int c3 = tok_nextc(tok); + int token3 = PyToken_ThreeChars(c, c2, c3); + if (token3 != OP) { + token = token3; + } else { + tok_backup(tok, c3); + } + *p_start = tok->start; + *p_end = tok->cur; + return token; + } + tok_backup(tok, c2); + } + + /* Keep track of parentheses nesting level */ + switch (c) { + case '(': + case '[': + case '{': + tok->level++; + break; + case ')': + case ']': + case '}': + tok->level--; + break; + } + + /* Punctuation character */ + *p_start = tok->start; + *p_end = tok->cur; + return PyToken_OneChar(c); } int PyTokenizer_Get(struct tok_state *tok, char **p_start, char **p_end) { - int result = tok_get(tok, p_start, p_end); - if (tok->decoding_erred) { - result = ERRORTOKEN; - tok->done = E_DECODE; - } - return result; + int result = tok_get(tok, p_start, p_end); + if (tok->decoding_erred) { + result = ERRORTOKEN; + tok->done = E_DECODE; + } + return result; } /* Get -*- encoding -*- from a Python file. @@ -1639,34 +1639,34 @@ char * PyTokenizer_FindEncoding(int fd) { - struct tok_state *tok; - FILE *fp; - char *p_start =NULL , *p_end =NULL , *encoding = NULL; - - fd = dup(fd); - if (fd < 0) { - return NULL; - } - fp = fdopen(fd, "r"); - if (fp == NULL) { - return NULL; - } - tok = PyTokenizer_FromFile(fp, NULL, NULL, NULL); - if (tok == NULL) { - fclose(fp); - return NULL; - } - while (tok->lineno < 2 && tok->done == E_OK) { - PyTokenizer_Get(tok, &p_start, &p_end); - } - fclose(fp); - if (tok->encoding) { - encoding = (char *)PyMem_MALLOC(strlen(tok->encoding) + 1); - if (encoding) - strcpy(encoding, tok->encoding); - } - PyTokenizer_Free(tok); - return encoding; + struct tok_state *tok; + FILE *fp; + char *p_start =NULL , *p_end =NULL , *encoding = NULL; + + fd = dup(fd); + if (fd < 0) { + return NULL; + } + fp = fdopen(fd, "r"); + if (fp == NULL) { + return NULL; + } + tok = PyTokenizer_FromFile(fp, NULL, NULL, NULL); + if (tok == NULL) { + fclose(fp); + return NULL; + } + while (tok->lineno < 2 && tok->done == E_OK) { + PyTokenizer_Get(tok, &p_start, &p_end); + } + fclose(fp); + if (tok->encoding) { + encoding = (char *)PyMem_MALLOC(strlen(tok->encoding) + 1); + if (encoding) + strcpy(encoding, tok->encoding); + } + PyTokenizer_Free(tok); + return encoding; } #ifdef Py_DEBUG @@ -1674,9 +1674,9 @@ void tok_dump(int type, char *start, char *end) { - printf("%s", _PyParser_TokenNames[type]); - if (type == NAME || type == NUMBER || type == STRING || type == OP) - printf("(%.*s)", (int)(end - start), start); + printf("%s", _PyParser_TokenNames[type]); + if (type == NAME || type == NUMBER || type == STRING || type == OP) + printf("(%.*s)", (int)(end - start), start); } #endif Modified: python/branches/release31-maint/Parser/tokenizer.h ============================================================================== --- python/branches/release31-maint/Parser/tokenizer.h (original) +++ python/branches/release31-maint/Parser/tokenizer.h Sun May 9 18:14:21 2010 @@ -8,66 +8,66 @@ /* Tokenizer interface */ -#include "token.h" /* For token types */ +#include "token.h" /* For token types */ -#define MAXINDENT 100 /* Max indentation level */ +#define MAXINDENT 100 /* Max indentation level */ enum decoding_state { - STATE_INIT, - STATE_RAW, - STATE_NORMAL, /* have a codec associated with input */ + STATE_INIT, + STATE_RAW, + STATE_NORMAL, /* have a codec associated with input */ }; /* Tokenizer state */ struct tok_state { - /* Input state; buf <= cur <= inp <= end */ - /* NB an entire line is held in the buffer */ - char *buf; /* Input buffer, or NULL; malloc'ed if fp != NULL */ - char *cur; /* Next character in buffer */ - char *inp; /* End of data in buffer */ - char *end; /* End of input buffer if buf != NULL */ - char *start; /* Start of current token if not NULL */ - int done; /* E_OK normally, E_EOF at EOF, otherwise error code */ - /* NB If done != E_OK, cur must be == inp!!! */ - FILE *fp; /* Rest of input; NULL if tokenizing a string */ - int tabsize; /* Tab spacing */ - int indent; /* Current indentation index */ - int indstack[MAXINDENT]; /* Stack of indents */ - int atbol; /* Nonzero if at begin of new line */ - int pendin; /* Pending indents (if > 0) or dedents (if < 0) */ - char *prompt, *nextprompt; /* For interactive prompting */ - int lineno; /* Current line number */ - int level; /* () [] {} Parentheses nesting level */ - /* Used to allow free continuations inside them */ - /* Stuff for checking on different tab sizes */ - const char *filename; /* For error messages */ - int altwarning; /* Issue warning if alternate tabs don't match */ - int alterror; /* Issue error if alternate tabs don't match */ - int alttabsize; /* Alternate tab spacing */ - int altindstack[MAXINDENT]; /* Stack of alternate indents */ - /* Stuff for PEP 0263 */ - enum decoding_state decoding_state; - int decoding_erred; /* whether erred in decoding */ - int read_coding_spec; /* whether 'coding:...' has been read */ - char *encoding; /* Source encoding. */ - int cont_line; /* whether we are in a continuation line. */ - const char* line_start; /* pointer to start of current line */ + /* Input state; buf <= cur <= inp <= end */ + /* NB an entire line is held in the buffer */ + char *buf; /* Input buffer, or NULL; malloc'ed if fp != NULL */ + char *cur; /* Next character in buffer */ + char *inp; /* End of data in buffer */ + char *end; /* End of input buffer if buf != NULL */ + char *start; /* Start of current token if not NULL */ + int done; /* E_OK normally, E_EOF at EOF, otherwise error code */ + /* NB If done != E_OK, cur must be == inp!!! */ + FILE *fp; /* Rest of input; NULL if tokenizing a string */ + int tabsize; /* Tab spacing */ + int indent; /* Current indentation index */ + int indstack[MAXINDENT]; /* Stack of indents */ + int atbol; /* Nonzero if at begin of new line */ + int pendin; /* Pending indents (if > 0) or dedents (if < 0) */ + char *prompt, *nextprompt; /* For interactive prompting */ + int lineno; /* Current line number */ + int level; /* () [] {} Parentheses nesting level */ + /* Used to allow free continuations inside them */ + /* Stuff for checking on different tab sizes */ + const char *filename; /* For error messages */ + int altwarning; /* Issue warning if alternate tabs don't match */ + int alterror; /* Issue error if alternate tabs don't match */ + int alttabsize; /* Alternate tab spacing */ + int altindstack[MAXINDENT]; /* Stack of alternate indents */ + /* Stuff for PEP 0263 */ + enum decoding_state decoding_state; + int decoding_erred; /* whether erred in decoding */ + int read_coding_spec; /* whether 'coding:...' has been read */ + char *encoding; /* Source encoding. */ + int cont_line; /* whether we are in a continuation line. */ + const char* line_start; /* pointer to start of current line */ #ifndef PGEN - PyObject *decoding_readline; /* codecs.open(...).readline */ - PyObject *decoding_buffer; + PyObject *decoding_readline; /* codecs.open(...).readline */ + PyObject *decoding_buffer; #endif - const char* enc; /* Encoding for the current str. */ - const char* str; + const char* enc; /* Encoding for the current str. */ + const char* str; }; extern struct tok_state *PyTokenizer_FromString(const char *); extern struct tok_state *PyTokenizer_FromUTF8(const char *); extern struct tok_state *PyTokenizer_FromFile(FILE *, char*, - char *, char *); + char *, char *); extern void PyTokenizer_Free(struct tok_state *); extern int PyTokenizer_Get(struct tok_state *, char **, char **); -extern char * PyTokenizer_RestoreEncoding(struct tok_state* tok, - int len, int *offset); +extern char * PyTokenizer_RestoreEncoding(struct tok_state* tok, + int len, int *offset); extern char * PyTokenizer_FindEncoding(int); #ifdef __cplusplus Modified: python/branches/release31-maint/Python/_warnings.c ============================================================================== --- python/branches/release31-maint/Python/_warnings.c (original) +++ python/branches/release31-maint/Python/_warnings.c Sun May 9 18:14:21 2010 @@ -85,10 +85,10 @@ default_action = get_warnings_attr("defaultaction"); if (default_action == NULL) { - if (PyErr_Occurred()) { - return NULL; - } - return _default_action; + if (PyErr_Occurred()) { + return NULL; + } + return _default_action; } Py_DECREF(_default_action); @@ -202,12 +202,12 @@ mod_str = _PyUnicode_AsString(filename); if (mod_str == NULL) - return NULL; + return NULL; len = PyUnicode_GetSize(filename); if (len < 0) return NULL; if (len >= 3 && - strncmp(mod_str + (len - 3), ".py", 3) == 0) { + strncmp(mod_str + (len - 3), ".py", 3) == 0) { module = PyUnicode_FromStringAndSize(mod_str, len-3); } else { @@ -243,15 +243,15 @@ show_warning(PyObject *filename, int lineno, PyObject *text, PyObject *category, PyObject *sourceline) { - PyObject *f_stderr; - PyObject *name; + PyObject *f_stderr; + PyObject *name; char lineno_str[128]; PyOS_snprintf(lineno_str, sizeof(lineno_str), ":%d: ", lineno); name = PyObject_GetAttrString(category, "__name__"); if (name == NULL) /* XXX Can an object lack a '__name__' attribute? */ - return; + return; f_stderr = PySys_GetObject("stderr"); if (f_stderr == NULL) { @@ -272,8 +272,8 @@ /* Print " source_line\n" */ if (sourceline) { char *source_line_str = _PyUnicode_AsString(sourceline); - if (source_line_str == NULL) - return; + if (source_line_str == NULL) + return; while (*source_line_str == ' ' || *source_line_str == '\t' || *source_line_str == '\014') source_line_str++; @@ -284,12 +284,12 @@ else if (_Py_DisplaySourceLine(f_stderr, _PyUnicode_AsString(filename), lineno, 2) < 0) - return; + return; PyErr_Clear(); } static PyObject * -warn_explicit(PyObject *category, PyObject *message, +warn_explicit(PyObject *category, PyObject *message, PyObject *filename, int lineno, PyObject *module, PyObject *registry, PyObject *sourceline) { @@ -297,7 +297,7 @@ PyObject *item = Py_None; const char *action; int rc; - + if (registry && !PyDict_Check(registry) && (registry != Py_None)) { PyErr_SetString(PyExc_TypeError, "'registry' must be a dict"); return NULL; @@ -344,7 +344,7 @@ rc = already_warned(registry, key, 0); if (rc == -1) goto cleanup; - else if (rc == 1) + else if (rc == 1) goto return_none; /* Else this warning hasn't been generated before. */ } @@ -374,12 +374,12 @@ goto cleanup; } /* _once_registry[(text, category)] = 1 */ - rc = update_registry(registry, text, category, 0); + rc = update_registry(registry, text, category, 0); } else if (strcmp(action, "module") == 0) { /* registry[(text, category, 0)] = 1 */ if (registry != NULL && registry != Py_None) - rc = update_registry(registry, text, category, 0); + rc = update_registry(registry, text, category, 0); } else if (strcmp(action, "default") != 0) { PyObject *to_str = PyObject_Str(item); @@ -387,9 +387,9 @@ if (to_str != NULL) { err_str = _PyUnicode_AsString(to_str); - if (err_str == NULL) - goto cleanup; - } + if (err_str == NULL) + goto cleanup; + } PyErr_Format(PyExc_RuntimeError, "Unrecognized action (%s) in warnings.filters:\n %s", action, err_str); @@ -500,7 +500,7 @@ if (*filename != NULL) { Py_ssize_t len = PyUnicode_GetSize(*filename); const char *file_str = _PyUnicode_AsString(*filename); - if (file_str == NULL || (len < 0 && PyErr_Occurred())) + if (file_str == NULL || (len < 0 && PyErr_Occurred())) goto handle_error; /* if filename.lower().endswith((".pyc", ".pyo")): */ @@ -512,16 +512,16 @@ tolower(file_str[len-1]) == 'o')) { *filename = PyUnicode_FromStringAndSize(file_str, len-1); - if (*filename == NULL) - goto handle_error; - } - else + if (*filename == NULL) + goto handle_error; + } + else Py_INCREF(*filename); } else { const char *module_str = _PyUnicode_AsString(*module); - if (module_str == NULL) - goto handle_error; + if (module_str == NULL) + goto handle_error; if (strcmp(module_str, "__main__") == 0) { PyObject *argv = PySys_GetObject("argv"); if (argv != NULL && PyList_Size(argv) > 0) { @@ -544,8 +544,8 @@ else { /* embedded interpreters don't have sys.argv, see bug #839151 */ *filename = PyUnicode_FromString("__main__"); - if (*filename == NULL) - goto handle_error; + if (*filename == NULL) + goto handle_error; } } if (*filename == NULL) { @@ -616,7 +616,7 @@ PyObject *message, *category = NULL; Py_ssize_t stack_level = 1; - if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|On:warn", kw_list, + if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|On:warn", kw_list, &message, &category, &stack_level)) return NULL; @@ -794,7 +794,7 @@ METH_VARARGS | METH_KEYWORDS, warn_explicit_doc}, /* XXX(brett.cannon): add showwarning? */ /* XXX(brett.cannon): Reasonable to add formatwarning? */ - {NULL, NULL} /* sentinel */ + {NULL, NULL} /* sentinel */ }; @@ -875,15 +875,15 @@ } static struct PyModuleDef warningsmodule = { - PyModuleDef_HEAD_INIT, - MODULE_NAME, - warnings__doc__, - 0, - warnings_functions, - NULL, - NULL, - NULL, - NULL + PyModuleDef_HEAD_INIT, + MODULE_NAME, + warnings__doc__, + 0, + warnings_functions, + NULL, + NULL, + NULL, + NULL }; Modified: python/branches/release31-maint/Python/asdl.c ============================================================================== --- python/branches/release31-maint/Python/asdl.c (original) +++ python/branches/release31-maint/Python/asdl.c Sun May 9 18:14:21 2010 @@ -4,61 +4,61 @@ asdl_seq * asdl_seq_new(int size, PyArena *arena) { - asdl_seq *seq = NULL; - size_t n = (size ? (sizeof(void *) * (size - 1)) : 0); + asdl_seq *seq = NULL; + size_t n = (size ? (sizeof(void *) * (size - 1)) : 0); - /* check size is sane */ - if (size < 0 || size == INT_MIN || - (size && ((size - 1) > (PY_SIZE_MAX / sizeof(void *))))) { - PyErr_NoMemory(); - return NULL; - } - - /* check if size can be added safely */ - if (n > PY_SIZE_MAX - sizeof(asdl_seq)) { - PyErr_NoMemory(); - return NULL; - } - - n += sizeof(asdl_seq); - - seq = (asdl_seq *)PyArena_Malloc(arena, n); - if (!seq) { - PyErr_NoMemory(); - return NULL; - } - memset(seq, 0, n); - seq->size = size; - return seq; + /* check size is sane */ + if (size < 0 || size == INT_MIN || + (size && ((size - 1) > (PY_SIZE_MAX / sizeof(void *))))) { + PyErr_NoMemory(); + return NULL; + } + + /* check if size can be added safely */ + if (n > PY_SIZE_MAX - sizeof(asdl_seq)) { + PyErr_NoMemory(); + return NULL; + } + + n += sizeof(asdl_seq); + + seq = (asdl_seq *)PyArena_Malloc(arena, n); + if (!seq) { + PyErr_NoMemory(); + return NULL; + } + memset(seq, 0, n); + seq->size = size; + return seq; } asdl_int_seq * asdl_int_seq_new(int size, PyArena *arena) { - asdl_int_seq *seq = NULL; - size_t n = (size ? (sizeof(void *) * (size - 1)) : 0); + asdl_int_seq *seq = NULL; + size_t n = (size ? (sizeof(void *) * (size - 1)) : 0); - /* check size is sane */ - if (size < 0 || size == INT_MIN || - (size && ((size - 1) > (PY_SIZE_MAX / sizeof(void *))))) { - PyErr_NoMemory(); - return NULL; - } - - /* check if size can be added safely */ - if (n > PY_SIZE_MAX - sizeof(asdl_seq)) { - PyErr_NoMemory(); - return NULL; - } - - n += sizeof(asdl_seq); - - seq = (asdl_int_seq *)PyArena_Malloc(arena, n); - if (!seq) { - PyErr_NoMemory(); - return NULL; - } - memset(seq, 0, n); - seq->size = size; - return seq; + /* check size is sane */ + if (size < 0 || size == INT_MIN || + (size && ((size - 1) > (PY_SIZE_MAX / sizeof(void *))))) { + PyErr_NoMemory(); + return NULL; + } + + /* check if size can be added safely */ + if (n > PY_SIZE_MAX - sizeof(asdl_seq)) { + PyErr_NoMemory(); + return NULL; + } + + n += sizeof(asdl_seq); + + seq = (asdl_int_seq *)PyArena_Malloc(arena, n); + if (!seq) { + PyErr_NoMemory(); + return NULL; + } + memset(seq, 0, n); + seq->size = size; + return seq; } Modified: python/branches/release31-maint/Python/ast.c ============================================================================== --- python/branches/release31-maint/Python/ast.c (original) +++ python/branches/release31-maint/Python/ast.c Sun May 9 18:14:21 2010 @@ -58,19 +58,19 @@ /* Check whether there are non-ASCII characters in the identifier; if so, normalize to NFKC. */ for (; *u; u++) { - if (*u >= 128) { - PyObject *m = PyImport_ImportModuleNoBlock("unicodedata"); - PyObject *id2; - if (!m) - return NULL; - id2 = PyObject_CallMethod(m, "normalize", "sO", "NFKC", id); - Py_DECREF(m); - if (!id2) - return NULL; - Py_DECREF(id); - id = id2; - break; - } + if (*u >= 128) { + PyObject *m = PyImport_ImportModuleNoBlock("unicodedata"); + PyObject *id2; + if (!m) + return NULL; + id2 = PyObject_CallMethod(m, "normalize", "sO", "NFKC", id); + Py_DECREF(m); + if (!id2) + return NULL; + Py_DECREF(id); + id = id2; + break; + } } PyUnicode_InternInPlace(&id); PyArena_AddPyObject(arena, id); @@ -226,7 +226,7 @@ c.c_encoding = STR(n); n = CHILD(n, 0); } else { - /* PEP 3120 */ + /* PEP 3120 */ c.c_encoding = "utf-8"; } c.c_arena = arena; @@ -424,7 +424,7 @@ s = e->v.List.elts; break; case Tuple_kind: - if (asdl_seq_LEN(e->v.Tuple.elts) == 0) + if (asdl_seq_LEN(e->v.Tuple.elts) == 0) return ast_error(n, "can't assign to ()"); e->v.Tuple.ctx = ctx; s = e->v.Tuple.elts; @@ -471,8 +471,8 @@ expr_name = "conditional expression"; break; default: - PyErr_Format(PyExc_SystemError, - "unexpected expression in assignment %d (line %d)", + PyErr_Format(PyExc_SystemError, + "unexpected expression in assignment %d (line %d)", e->kind, e->lineno); return 0; } @@ -487,7 +487,7 @@ } /* If the LHS is a list or tuple, we need to set the assignment - context for all the contained elements. + context for all the contained elements. */ if (s) { int i; @@ -709,7 +709,7 @@ } return i; error: - return -1; + return -1; } /* Create AST for argument list. */ @@ -722,12 +722,12 @@ parameters: '(' [typedargslist] ')' typedargslist: ((tfpdef ['=' test] ',')* - ('*' [tfpdef] (',' tfpdef ['=' test])* [',' '**' tfpdef] + ('*' [tfpdef] (',' tfpdef ['=' test])* [',' '**' tfpdef] | '**' tfpdef) | tfpdef ['=' test] (',' tfpdef ['=' test])* [',']) tfpdef: NAME [':' test] varargslist: ((vfpdef ['=' test] ',')* - ('*' [vfpdef] (',' vfpdef ['=' test])* [',' '**' vfpdef] + ('*' [vfpdef] (',' vfpdef ['=' test])* [',' '**' vfpdef] | '**' vfpdef) | vfpdef ['=' test] (',' vfpdef ['=' test])* [',']) vfpdef: NAME @@ -768,7 +768,7 @@ if (TYPE(ch) == vfpdef || TYPE(ch) == tfpdef) nposargs++; if (TYPE(ch) == EQUAL) nposdefaults++; } - /* count the number of keyword only args & + /* count the number of keyword only args & defaults for keyword only args */ for ( ; i < NCH(n); ++i) { ch = CHILD(n, i); @@ -782,11 +782,11 @@ asdl_seq_new(nkwonlyargs, c->c_arena) : NULL); if (!kwonlyargs && nkwonlyargs) goto error; - posdefaults = (nposdefaults ? + posdefaults = (nposdefaults ? asdl_seq_new(nposdefaults, c->c_arena) : NULL); if (!posdefaults && nposdefaults) goto error; - /* The length of kwonlyargs and kwdefaults are same + /* The length of kwonlyargs and kwdefaults are same since we set NULL as default for keyword only argument w/o default - we have sequence data structure, but no dictionary */ kwdefaults = (nkwonlyargs ? @@ -823,7 +823,7 @@ found_default = 1; } else if (found_default) { - ast_error(n, + ast_error(n, "non-default argument follows default argument"); goto error; } @@ -835,7 +835,7 @@ break; case STAR: if (i+1 >= NCH(n)) { - ast_error(CHILD(n, i), + ast_error(CHILD(n, i), "named arguments must follow bare *"); goto error; } @@ -932,15 +932,15 @@ /* decorator: '@' dotted_name [ '(' [arglist] ')' ] NEWLINE */ expr_ty d = NULL; expr_ty name_expr; - + REQ(n, decorator); REQ(CHILD(n, 0), AT); REQ(RCHILD(n, -1), NEWLINE); - + name_expr = ast_for_dotted_name(c, CHILD(n, 1)); if (!name_expr) return NULL; - + if (NCH(n) == 3) { /* No arguments */ d = name_expr; name_expr = NULL; @@ -968,12 +968,12 @@ asdl_seq* decorator_seq; expr_ty d; int i; - + REQ(n, decorators); decorator_seq = asdl_seq_new(NCH(n), c->c_arena); if (!decorator_seq) return NULL; - + for (i = 0; i < NCH(n); i++) { d = ast_for_decorator(c, CHILD(n, i)); if (!d) @@ -1029,7 +1029,7 @@ return NULL; assert(TYPE(CHILD(n, 1)) == funcdef || - TYPE(CHILD(n, 1)) == classdef); + TYPE(CHILD(n, 1)) == classdef); if (TYPE(CHILD(n, 1)) == funcdef) { thing = ast_for_funcdef(c, CHILD(n, 1), decorator_seq); @@ -1077,7 +1077,7 @@ static expr_ty ast_for_ifexpr(struct compiling *c, const node *n) { - /* test: or_test 'if' or_test 'else' test */ + /* test: or_test 'if' or_test 'else' test */ expr_ty expression, body, orelse; assert(NCH(n) == 5); @@ -1174,9 +1174,9 @@ asdl_seq *t; expr_ty expression; node *for_ch; - + REQ(n, comp_for); - + for_ch = CHILD(n, 1); t = ast_for_exprlist(c, for_ch, Store); if (!t) @@ -1201,7 +1201,7 @@ if (NCH(n) == 5) { int j, n_ifs; asdl_seq *ifs; - + n = CHILD(n, 4); n_ifs = count_comp_ifs(c, n); if (n_ifs == -1) @@ -1215,7 +1215,7 @@ REQ(n, comp_iter); n = CHILD(n, 0); REQ(n, comp_if); - + expression = ast_for_expr(c, CHILD(n, 1)); if (!expression) return NULL; @@ -1240,13 +1240,13 @@ argument: [test '='] test [comp_for] # Really [keyword '='] test */ expr_ty elt; asdl_seq *comps; - + assert(NCH(n) > 1); - + elt = ast_for_expr(c, CHILD(n, 0)); if (!elt) return NULL; - + comps = ast_for_comprehension(c, CHILD(n, 1)); if (!comps) return NULL; @@ -1267,10 +1267,10 @@ { expr_ty key, value; asdl_seq *comps; - + assert(NCH(n) > 3); REQ(CHILD(n, 1), COLON); - + key = ast_for_expr(c, CHILD(n, 0)); if (!key) return NULL; @@ -1278,11 +1278,11 @@ value = ast_for_expr(c, CHILD(n, 2)); if (!value) return NULL; - + comps = ast_for_comprehension(c, CHILD(n, 3)); if (!comps) return NULL; - + return DictComp(key, value, comps, LINENO(n), n->n_col_offset, c->c_arena); } @@ -1317,7 +1317,7 @@ */ node *ch = CHILD(n, 0); int bytesmode = 0; - + switch (TYPE(ch)) { case NAME: { /* All names start in Load context, but may later be @@ -1368,24 +1368,24 @@ return Ellipsis(LINENO(n), n->n_col_offset, c->c_arena); case LPAR: /* some parenthesized expressions */ ch = CHILD(n, 1); - + if (TYPE(ch) == RPAR) return Tuple(NULL, Load, LINENO(n), n->n_col_offset, c->c_arena); - + if (TYPE(ch) == yield_expr) return ast_for_expr(c, ch); - /* testlist_comp: test ( comp_for | (',' test)* [','] ) */ + /* testlist_comp: test ( comp_for | (',' test)* [','] ) */ if ((NCH(ch) > 1) && (TYPE(CHILD(ch, 1)) == comp_for)) return ast_for_genexp(c, ch); - + return ast_for_testlist(c, ch); case LSQB: /* list (or list comprehension) */ ch = CHILD(n, 1); - + if (TYPE(ch) == RSQB) return List(NULL, Load, LINENO(n), n->n_col_offset, c->c_arena); - + REQ(ch, testlist_comp); if (NCH(ch) == 1 || TYPE(CHILD(ch, 1)) == COMMA) { asdl_seq *elts = seq_for_testlist(c, ch); @@ -1432,14 +1432,14 @@ keys = asdl_seq_new(size, c->c_arena); if (!keys) return NULL; - + values = asdl_seq_new(size, c->c_arena); if (!values) return NULL; - + for (i = 0; i < NCH(ch); i += 4) { expr_ty expression; - + expression = ast_for_expr(c, CHILD(ch, i)); if (!expression) return NULL; @@ -1477,10 +1477,10 @@ if (NCH(n) == 1 && TYPE(ch) == test) { /* 'step' variable hold no significance in terms of being used over other vars */ - step = ast_for_expr(c, ch); + step = ast_for_expr(c, ch); if (!step) return NULL; - + return Index(step, c->c_arena); } @@ -1537,7 +1537,7 @@ ast_for_binop(struct compiling *c, const node *n) { /* Must account for a sequence of expressions. - How should A op B op C by represented? + How should A op B op C by represented? BinOp(BinOp(A, op, B), op, C). */ @@ -1575,10 +1575,10 @@ if (!tmp) return NULL; - tmp_result = BinOp(result, newoperator, tmp, + tmp_result = BinOp(result, newoperator, tmp, LINENO(next_oper), next_oper->n_col_offset, c->c_arena); - if (!tmp_result) + if (!tmp_result) return NULL; result = tmp_result; } @@ -1588,7 +1588,7 @@ static expr_ty ast_for_trailer(struct compiling *c, const node *n, expr_ty left_expr) { - /* trailer: '(' [arglist] ')' | '[' subscriptlist ']' | '.' NAME + /* trailer: '(' [arglist] ')' | '[' subscriptlist ']' | '.' NAME subscriptlist: subscript (',' subscript)* [','] subscript: '.' '.' '.' | test | [test] ':' [test] [sliceop] */ @@ -1619,7 +1619,7 @@ c->c_arena); } else { - /* The grammar is ambiguous here. The ambiguity is resolved + /* The grammar is ambiguous here. The ambiguity is resolved by treating the sequence as a tuple literal if there are no slice features. */ @@ -1772,7 +1772,7 @@ /* handle the full range of simple expressions test: or_test ['if' or_test 'else' test] | lambdef test_nocond: or_test | lambdef_nocond - or_test: and_test ('or' and_test)* + or_test: and_test ('or' and_test)* and_test: not_test ('and' not_test)* not_test: 'not' not_test | comparison comparison: expr (comp_op expr)* @@ -1860,7 +1860,7 @@ if (!expression) { return NULL; } - + asdl_seq_SET(ops, i / 2, newoperator); asdl_seq_SET(cmps, i / 2, expression); } @@ -1868,7 +1868,7 @@ if (!expression) { return NULL; } - + return Compare(expression, ops, cmps, LINENO(n), n->n_col_offset, c->c_arena); } @@ -1987,7 +1987,7 @@ if (!e) return NULL; asdl_seq_SET(args, nargs++, e); - } + } else if (TYPE(CHILD(ch, 1)) == comp_for) { e = ast_for_genexp(c, ch); if (!e) @@ -1999,7 +1999,7 @@ identifier key, tmp; int k; - /* CHILD(ch, 0) is test, but must be an identifier? */ + /* CHILD(ch, 0) is test, but must be an identifier? */ e = ast_for_expr(c, CHILD(ch, 0)); if (!e) return NULL; @@ -2015,8 +2015,8 @@ ast_error(CHILD(ch, 0), "keyword can't be an expression"); return NULL; } else if (forbidden_name(e, ch)) { - return NULL; - } + return NULL; + } key = e->v.Name.id; for (k = 0; k < nkeywords; k++) { tmp = ((keyword_ty)asdl_seq_GET(keywords, k))->arg; @@ -2080,7 +2080,7 @@ ast_for_expr_stmt(struct compiling *c, const node *n) { REQ(n, expr_stmt); - /* expr_stmt: testlist (augassign (yield_expr|testlist) + /* expr_stmt: testlist (augassign (yield_expr|testlist) | ('=' (yield_expr|testlist))*) testlist: test (',' test)* [','] augassign: '+=' | '-=' | '*=' | '/=' | '%=' | '&=' | '|=' | '^=' @@ -2154,7 +2154,7 @@ e = ast_for_testlist(c, ch); /* set context to assign */ - if (!e) + if (!e) return NULL; if (!set_context(c, e, Store, CHILD(n, i))) @@ -2200,7 +2200,7 @@ ast_for_del_stmt(struct compiling *c, const node *n) { asdl_seq *expr_list; - + /* del_stmt: 'del' exprlist */ REQ(n, del_stmt); @@ -2323,7 +2323,7 @@ int i; size_t len; char *s; - PyObject *uni; + PyObject *uni; len = 0; for (i = 0; i < NCH(n); i += 2) @@ -2344,13 +2344,13 @@ } --s; *s = '\0'; - uni = PyUnicode_DecodeUTF8(PyBytes_AS_STRING(str), - PyBytes_GET_SIZE(str), - NULL); - Py_DECREF(str); - if (!uni) - return NULL; - str = uni; + uni = PyUnicode_DecodeUTF8(PyBytes_AS_STRING(str), + PyBytes_GET_SIZE(str), + NULL); + Py_DECREF(str); + if (!uni) + return NULL; + str = uni; PyUnicode_InternInPlace(&str); PyArena_AddPyObject(c->c_arena, str); return alias(str, NULL, c->c_arena); @@ -2407,7 +2407,7 @@ int idx, ndots = 0; alias_ty mod = NULL; identifier modname; - + /* Count the number of dots (for relative imports) and check for the optional module name */ for (idx = 1; idx < NCH(n); idx++) { @@ -2416,7 +2416,7 @@ idx++; break; } else if (TYPE(CHILD(n, idx)) == ELLIPSIS) { - /* three consecutive dots are tokenized as one ELLIPSIS */ + /* three consecutive dots are tokenized as one ELLIPSIS */ ndots += 3; continue; } else if (TYPE(CHILD(n, idx)) != DOT) { @@ -2545,7 +2545,7 @@ expr2 = ast_for_expr(c, CHILD(n, 3)); if (!expr2) return NULL; - + return Assert(expr1, expr2, LINENO(n), n->n_col_offset, c->c_arena); } PyErr_Format(PyExc_SystemError, @@ -2572,7 +2572,7 @@ if (TYPE(CHILD(n, 0)) == simple_stmt) { n = CHILD(n, 0); /* simple_stmt always ends with a NEWLINE, - and may have a trailing SEMI + and may have a trailing SEMI */ end = NCH(n) - 1; if (TYPE(CHILD(n, end - 1)) == SEMI) @@ -2637,10 +2637,10 @@ expression = ast_for_expr(c, CHILD(n, 1)); if (!expression) return NULL; - suite_seq = ast_for_suite(c, CHILD(n, 3)); + suite_seq = ast_for_suite(c, CHILD(n, 3)); if (!suite_seq) return NULL; - + return If(expression, suite_seq, NULL, LINENO(n), n->n_col_offset, c->c_arena); } @@ -2698,8 +2698,8 @@ if (!suite_seq2) return NULL; - asdl_seq_SET(orelse, 0, - If(expression, suite_seq, suite_seq2, + asdl_seq_SET(orelse, 0, + If(expression, suite_seq, suite_seq2, LINENO(CHILD(n, NCH(n) - 6)), CHILD(n, NCH(n) - 6)->n_col_offset, c->c_arena)); @@ -2720,7 +2720,7 @@ return NULL; asdl_seq_SET(newobj, 0, - If(expression, suite_seq, orelse, + If(expression, suite_seq, orelse, LINENO(CHILD(n, off)), CHILD(n, off)->n_col_offset, c->c_arena)); orelse = newobj; @@ -2914,7 +2914,7 @@ ast_error(n, "malformed 'try' statement"); return NULL; } - + if (n_except > 0) { int i; stmt_ty except_st; @@ -3125,8 +3125,8 @@ return ast_for_funcdef(c, ch, NULL); case classdef: return ast_for_classdef(c, ch, NULL); - case decorated: - return ast_for_decorated(c, ch); + case decorated: + return ast_for_decorated(c, ch); default: PyErr_Format(PyExc_SystemError, "unhandled small_stmt: TYPE=%d NCH=%d\n", @@ -3288,7 +3288,7 @@ if (quote == 'b' || quote == 'B') { quote = *++s; *bytesmode = 1; - } + } if (quote == 'r' || quote == 'R') { quote = *++s; rawmode = 1; @@ -3301,7 +3301,7 @@ s++; len = strlen(s); if (len > INT_MAX) { - PyErr_SetString(PyExc_OverflowError, + PyErr_SetString(PyExc_OverflowError, "string to parse is too long"); return NULL; } @@ -3345,7 +3345,7 @@ return PyBytes_FromStringAndSize(s, len); } else if (strcmp(c->c_encoding, "utf-8") == 0) { return PyUnicode_FromStringAndSize(s, len); - } else { + } else { return PyUnicode_DecodeLatin1(s, len, NULL); } } Modified: python/branches/release31-maint/Python/bltinmodule.c ============================================================================== --- python/branches/release31-maint/Python/bltinmodule.c (original) +++ python/branches/release31-maint/Python/bltinmodule.c Sun May 9 18:14:21 2010 @@ -29,138 +29,138 @@ int _Py_SetFileSystemEncoding(PyObject *s) { - PyObject *defenc, *codec; - if (!PyUnicode_Check(s)) { - PyErr_BadInternalCall(); - return -1; - } - defenc = _PyUnicode_AsDefaultEncodedString(s, NULL); - if (!defenc) - return -1; - codec = _PyCodec_Lookup(PyBytes_AsString(defenc)); - if (codec == NULL) - return -1; - Py_DECREF(codec); - if (!Py_HasFileSystemDefaultEncoding && Py_FileSystemDefaultEncoding) - /* A file system encoding was set at run-time */ - free((char*)Py_FileSystemDefaultEncoding); - Py_FileSystemDefaultEncoding = strdup(PyBytes_AsString(defenc)); - Py_HasFileSystemDefaultEncoding = 0; - return 0; + PyObject *defenc, *codec; + if (!PyUnicode_Check(s)) { + PyErr_BadInternalCall(); + return -1; + } + defenc = _PyUnicode_AsDefaultEncodedString(s, NULL); + if (!defenc) + return -1; + codec = _PyCodec_Lookup(PyBytes_AsString(defenc)); + if (codec == NULL) + return -1; + Py_DECREF(codec); + if (!Py_HasFileSystemDefaultEncoding && Py_FileSystemDefaultEncoding) + /* A file system encoding was set at run-time */ + free((char*)Py_FileSystemDefaultEncoding); + Py_FileSystemDefaultEncoding = strdup(PyBytes_AsString(defenc)); + Py_HasFileSystemDefaultEncoding = 0; + return 0; } static PyObject * builtin___build_class__(PyObject *self, PyObject *args, PyObject *kwds) { - PyObject *func, *name, *bases, *mkw, *meta, *prep, *ns, *cell; - PyObject *cls = NULL; - Py_ssize_t nargs, nbases; - - assert(args != NULL); - if (!PyTuple_Check(args)) { - PyErr_SetString(PyExc_TypeError, - "__build_class__: args is not a tuple"); - return NULL; - } - nargs = PyTuple_GET_SIZE(args); - if (nargs < 2) { - PyErr_SetString(PyExc_TypeError, - "__build_class__: not enough arguments"); - return NULL; - } - func = PyTuple_GET_ITEM(args, 0); /* Better be callable */ - name = PyTuple_GET_ITEM(args, 1); - if (!PyUnicode_Check(name)) { - PyErr_SetString(PyExc_TypeError, - "__build_class__: name is not a string"); - return NULL; - } - bases = PyTuple_GetSlice(args, 2, nargs); - if (bases == NULL) - return NULL; - nbases = nargs - 2; - - if (kwds == NULL) { - meta = NULL; - mkw = NULL; - } - else { - mkw = PyDict_Copy(kwds); /* Don't modify kwds passed in! */ - if (mkw == NULL) { - Py_DECREF(bases); - return NULL; - } - meta = PyDict_GetItemString(mkw, "metaclass"); - if (meta != NULL) { - Py_INCREF(meta); - if (PyDict_DelItemString(mkw, "metaclass") < 0) { - Py_DECREF(meta); - Py_DECREF(mkw); - Py_DECREF(bases); - return NULL; - } - } - } - if (meta == NULL) { - if (PyTuple_GET_SIZE(bases) == 0) - meta = (PyObject *) (&PyType_Type); - else { - PyObject *base0 = PyTuple_GET_ITEM(bases, 0); - meta = (PyObject *) (base0->ob_type); - } - Py_INCREF(meta); - } - prep = PyObject_GetAttrString(meta, "__prepare__"); - if (prep == NULL) { - if (PyErr_ExceptionMatches(PyExc_AttributeError)) { - PyErr_Clear(); - ns = PyDict_New(); - } - else { - Py_DECREF(meta); - Py_XDECREF(mkw); - Py_DECREF(bases); - return NULL; - } - } - else { - PyObject *pargs = PyTuple_Pack(2, name, bases); - if (pargs == NULL) { - Py_DECREF(prep); - Py_DECREF(meta); - Py_XDECREF(mkw); - Py_DECREF(bases); - return NULL; - } - ns = PyEval_CallObjectWithKeywords(prep, pargs, mkw); - Py_DECREF(pargs); - Py_DECREF(prep); - } - if (ns == NULL) { - Py_DECREF(meta); - Py_XDECREF(mkw); - Py_DECREF(bases); - return NULL; - } - cell = PyObject_CallFunctionObjArgs(func, ns, NULL); - if (cell != NULL) { - PyObject *margs; - margs = PyTuple_Pack(3, name, bases, ns); - if (margs != NULL) { - cls = PyEval_CallObjectWithKeywords(meta, margs, mkw); - Py_DECREF(margs); - } - if (cls != NULL && PyCell_Check(cell)) { - Py_INCREF(cls); - PyCell_SET(cell, cls); - } - Py_DECREF(cell); - } - Py_DECREF(ns); - Py_DECREF(meta); - Py_XDECREF(mkw); - Py_DECREF(bases); - return cls; + PyObject *func, *name, *bases, *mkw, *meta, *prep, *ns, *cell; + PyObject *cls = NULL; + Py_ssize_t nargs, nbases; + + assert(args != NULL); + if (!PyTuple_Check(args)) { + PyErr_SetString(PyExc_TypeError, + "__build_class__: args is not a tuple"); + return NULL; + } + nargs = PyTuple_GET_SIZE(args); + if (nargs < 2) { + PyErr_SetString(PyExc_TypeError, + "__build_class__: not enough arguments"); + return NULL; + } + func = PyTuple_GET_ITEM(args, 0); /* Better be callable */ + name = PyTuple_GET_ITEM(args, 1); + if (!PyUnicode_Check(name)) { + PyErr_SetString(PyExc_TypeError, + "__build_class__: name is not a string"); + return NULL; + } + bases = PyTuple_GetSlice(args, 2, nargs); + if (bases == NULL) + return NULL; + nbases = nargs - 2; + + if (kwds == NULL) { + meta = NULL; + mkw = NULL; + } + else { + mkw = PyDict_Copy(kwds); /* Don't modify kwds passed in! */ + if (mkw == NULL) { + Py_DECREF(bases); + return NULL; + } + meta = PyDict_GetItemString(mkw, "metaclass"); + if (meta != NULL) { + Py_INCREF(meta); + if (PyDict_DelItemString(mkw, "metaclass") < 0) { + Py_DECREF(meta); + Py_DECREF(mkw); + Py_DECREF(bases); + return NULL; + } + } + } + if (meta == NULL) { + if (PyTuple_GET_SIZE(bases) == 0) + meta = (PyObject *) (&PyType_Type); + else { + PyObject *base0 = PyTuple_GET_ITEM(bases, 0); + meta = (PyObject *) (base0->ob_type); + } + Py_INCREF(meta); + } + prep = PyObject_GetAttrString(meta, "__prepare__"); + if (prep == NULL) { + if (PyErr_ExceptionMatches(PyExc_AttributeError)) { + PyErr_Clear(); + ns = PyDict_New(); + } + else { + Py_DECREF(meta); + Py_XDECREF(mkw); + Py_DECREF(bases); + return NULL; + } + } + else { + PyObject *pargs = PyTuple_Pack(2, name, bases); + if (pargs == NULL) { + Py_DECREF(prep); + Py_DECREF(meta); + Py_XDECREF(mkw); + Py_DECREF(bases); + return NULL; + } + ns = PyEval_CallObjectWithKeywords(prep, pargs, mkw); + Py_DECREF(pargs); + Py_DECREF(prep); + } + if (ns == NULL) { + Py_DECREF(meta); + Py_XDECREF(mkw); + Py_DECREF(bases); + return NULL; + } + cell = PyObject_CallFunctionObjArgs(func, ns, NULL); + if (cell != NULL) { + PyObject *margs; + margs = PyTuple_Pack(3, name, bases, ns); + if (margs != NULL) { + cls = PyEval_CallObjectWithKeywords(meta, margs, mkw); + Py_DECREF(margs); + } + if (cls != NULL && PyCell_Check(cell)) { + Py_INCREF(cls); + PyCell_SET(cell, cls); + } + Py_DECREF(cell); + } + Py_DECREF(ns); + Py_DECREF(meta); + Py_XDECREF(mkw); + Py_DECREF(bases); + return cls; } PyDoc_STRVAR(build_class_doc, @@ -171,19 +171,19 @@ static PyObject * builtin___import__(PyObject *self, PyObject *args, PyObject *kwds) { - static char *kwlist[] = {"name", "globals", "locals", "fromlist", - "level", 0}; - char *name; - PyObject *globals = NULL; - PyObject *locals = NULL; - PyObject *fromlist = NULL; - int level = -1; - - if (!PyArg_ParseTupleAndKeywords(args, kwds, "s|OOOi:__import__", - kwlist, &name, &globals, &locals, &fromlist, &level)) - return NULL; - return PyImport_ImportModuleLevel(name, globals, locals, - fromlist, level); + static char *kwlist[] = {"name", "globals", "locals", "fromlist", + "level", 0}; + char *name; + PyObject *globals = NULL; + PyObject *locals = NULL; + PyObject *fromlist = NULL; + int level = -1; + + if (!PyArg_ParseTupleAndKeywords(args, kwds, "s|OOOi:__import__", + kwlist, &name, &globals, &locals, &fromlist, &level)) + return NULL; + return PyImport_ImportModuleLevel(name, globals, locals, + fromlist, level); } PyDoc_STRVAR(import_doc, @@ -204,7 +204,7 @@ static PyObject * builtin_abs(PyObject *self, PyObject *v) { - return PyNumber_Absolute(v); + return PyNumber_Absolute(v); } PyDoc_STRVAR(abs_doc, @@ -215,38 +215,38 @@ static PyObject * builtin_all(PyObject *self, PyObject *v) { - PyObject *it, *item; - PyObject *(*iternext)(PyObject *); - int cmp; - - it = PyObject_GetIter(v); - if (it == NULL) - return NULL; - iternext = *Py_TYPE(it)->tp_iternext; - - for (;;) { - item = iternext(it); - if (item == NULL) - break; - cmp = PyObject_IsTrue(item); - Py_DECREF(item); - if (cmp < 0) { - Py_DECREF(it); - return NULL; - } - if (cmp == 0) { - Py_DECREF(it); - Py_RETURN_FALSE; - } - } - Py_DECREF(it); - if (PyErr_Occurred()) { - if (PyErr_ExceptionMatches(PyExc_StopIteration)) - PyErr_Clear(); - else - return NULL; - } - Py_RETURN_TRUE; + PyObject *it, *item; + PyObject *(*iternext)(PyObject *); + int cmp; + + it = PyObject_GetIter(v); + if (it == NULL) + return NULL; + iternext = *Py_TYPE(it)->tp_iternext; + + for (;;) { + item = iternext(it); + if (item == NULL) + break; + cmp = PyObject_IsTrue(item); + Py_DECREF(item); + if (cmp < 0) { + Py_DECREF(it); + return NULL; + } + if (cmp == 0) { + Py_DECREF(it); + Py_RETURN_FALSE; + } + } + Py_DECREF(it); + if (PyErr_Occurred()) { + if (PyErr_ExceptionMatches(PyExc_StopIteration)) + PyErr_Clear(); + else + return NULL; + } + Py_RETURN_TRUE; } PyDoc_STRVAR(all_doc, @@ -257,38 +257,38 @@ static PyObject * builtin_any(PyObject *self, PyObject *v) { - PyObject *it, *item; - PyObject *(*iternext)(PyObject *); - int cmp; - - it = PyObject_GetIter(v); - if (it == NULL) - return NULL; - iternext = *Py_TYPE(it)->tp_iternext; - - for (;;) { - item = iternext(it); - if (item == NULL) - break; - cmp = PyObject_IsTrue(item); - Py_DECREF(item); - if (cmp < 0) { - Py_DECREF(it); - return NULL; - } - if (cmp == 1) { - Py_DECREF(it); - Py_RETURN_TRUE; - } - } - Py_DECREF(it); - if (PyErr_Occurred()) { - if (PyErr_ExceptionMatches(PyExc_StopIteration)) - PyErr_Clear(); - else - return NULL; - } - Py_RETURN_FALSE; + PyObject *it, *item; + PyObject *(*iternext)(PyObject *); + int cmp; + + it = PyObject_GetIter(v); + if (it == NULL) + return NULL; + iternext = *Py_TYPE(it)->tp_iternext; + + for (;;) { + item = iternext(it); + if (item == NULL) + break; + cmp = PyObject_IsTrue(item); + Py_DECREF(item); + if (cmp < 0) { + Py_DECREF(it); + return NULL; + } + if (cmp == 1) { + Py_DECREF(it); + Py_RETURN_TRUE; + } + } + Py_DECREF(it); + if (PyErr_Occurred()) { + if (PyErr_ExceptionMatches(PyExc_StopIteration)) + PyErr_Clear(); + else + return NULL; + } + Py_RETURN_FALSE; } PyDoc_STRVAR(any_doc, @@ -299,7 +299,7 @@ static PyObject * builtin_ascii(PyObject *self, PyObject *v) { - return PyObject_ASCII(v); + return PyObject_ASCII(v); } PyDoc_STRVAR(ascii_doc, @@ -314,7 +314,7 @@ static PyObject * builtin_bin(PyObject *self, PyObject *v) { - return PyNumber_ToBase(v, 2); + return PyNumber_ToBase(v, 2); } PyDoc_STRVAR(bin_doc, @@ -324,90 +324,90 @@ typedef struct { - PyObject_HEAD - PyObject *func; - PyObject *it; + PyObject_HEAD + PyObject *func; + PyObject *it; } filterobject; static PyObject * filter_new(PyTypeObject *type, PyObject *args, PyObject *kwds) { - PyObject *func, *seq; - PyObject *it; - filterobject *lz; - - if (type == &PyFilter_Type && !_PyArg_NoKeywords("filter()", kwds)) - return NULL; - - if (!PyArg_UnpackTuple(args, "filter", 2, 2, &func, &seq)) - return NULL; - - /* Get iterator. */ - it = PyObject_GetIter(seq); - if (it == NULL) - return NULL; - - /* create filterobject structure */ - lz = (filterobject *)type->tp_alloc(type, 0); - if (lz == NULL) { - Py_DECREF(it); - return NULL; - } - Py_INCREF(func); - lz->func = func; - lz->it = it; + PyObject *func, *seq; + PyObject *it; + filterobject *lz; + + if (type == &PyFilter_Type && !_PyArg_NoKeywords("filter()", kwds)) + return NULL; + + if (!PyArg_UnpackTuple(args, "filter", 2, 2, &func, &seq)) + return NULL; + + /* Get iterator. */ + it = PyObject_GetIter(seq); + if (it == NULL) + return NULL; - return (PyObject *)lz; + /* create filterobject structure */ + lz = (filterobject *)type->tp_alloc(type, 0); + if (lz == NULL) { + Py_DECREF(it); + return NULL; + } + Py_INCREF(func); + lz->func = func; + lz->it = it; + + return (PyObject *)lz; } static void filter_dealloc(filterobject *lz) { - PyObject_GC_UnTrack(lz); - Py_XDECREF(lz->func); - Py_XDECREF(lz->it); - Py_TYPE(lz)->tp_free(lz); + PyObject_GC_UnTrack(lz); + Py_XDECREF(lz->func); + Py_XDECREF(lz->it); + Py_TYPE(lz)->tp_free(lz); } static int filter_traverse(filterobject *lz, visitproc visit, void *arg) { - Py_VISIT(lz->it); - Py_VISIT(lz->func); - return 0; + Py_VISIT(lz->it); + Py_VISIT(lz->func); + return 0; } static PyObject * filter_next(filterobject *lz) { - PyObject *item; - PyObject *it = lz->it; - long ok; - PyObject *(*iternext)(PyObject *); - - iternext = *Py_TYPE(it)->tp_iternext; - for (;;) { - item = iternext(it); - if (item == NULL) - return NULL; - - if (lz->func == Py_None || lz->func == (PyObject *)&PyBool_Type) { - ok = PyObject_IsTrue(item); - } else { - PyObject *good; - good = PyObject_CallFunctionObjArgs(lz->func, - item, NULL); - if (good == NULL) { - Py_DECREF(item); - return NULL; - } - ok = PyObject_IsTrue(good); - Py_DECREF(good); - } - if (ok) - return item; - Py_DECREF(item); - } + PyObject *item; + PyObject *it = lz->it; + long ok; + PyObject *(*iternext)(PyObject *); + + iternext = *Py_TYPE(it)->tp_iternext; + for (;;) { + item = iternext(it); + if (item == NULL) + return NULL; + + if (lz->func == Py_None || lz->func == (PyObject *)&PyBool_Type) { + ok = PyObject_IsTrue(item); + } else { + PyObject *good; + good = PyObject_CallFunctionObjArgs(lz->func, + item, NULL); + if (good == NULL) { + Py_DECREF(item); + return NULL; + } + ok = PyObject_IsTrue(good); + Py_DECREF(good); + } + if (ok) + return item; + Py_DECREF(item); + } } PyDoc_STRVAR(filter_doc, @@ -417,47 +417,47 @@ is true. If function is None, return the items that are true."); PyTypeObject PyFilter_Type = { - PyVarObject_HEAD_INIT(&PyType_Type, 0) - "filter", /* tp_name */ - sizeof(filterobject), /* tp_basicsize */ - 0, /* tp_itemsize */ - /* methods */ - (destructor)filter_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 | - Py_TPFLAGS_BASETYPE, /* tp_flags */ - filter_doc, /* tp_doc */ - (traverseproc)filter_traverse, /* tp_traverse */ - 0, /* tp_clear */ - 0, /* tp_richcompare */ - 0, /* tp_weaklistoffset */ - PyObject_SelfIter, /* tp_iter */ - (iternextfunc)filter_next, /* tp_iternext */ - 0, /* tp_methods */ - 0, /* tp_members */ - 0, /* tp_getset */ - 0, /* tp_base */ - 0, /* tp_dict */ - 0, /* tp_descr_get */ - 0, /* tp_descr_set */ - 0, /* tp_dictoffset */ - 0, /* tp_init */ - PyType_GenericAlloc, /* tp_alloc */ - filter_new, /* tp_new */ - PyObject_GC_Del, /* tp_free */ + PyVarObject_HEAD_INIT(&PyType_Type, 0) + "filter", /* tp_name */ + sizeof(filterobject), /* tp_basicsize */ + 0, /* tp_itemsize */ + /* methods */ + (destructor)filter_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 | + Py_TPFLAGS_BASETYPE, /* tp_flags */ + filter_doc, /* tp_doc */ + (traverseproc)filter_traverse, /* tp_traverse */ + 0, /* tp_clear */ + 0, /* tp_richcompare */ + 0, /* tp_weaklistoffset */ + PyObject_SelfIter, /* tp_iter */ + (iternextfunc)filter_next, /* tp_iternext */ + 0, /* tp_methods */ + 0, /* tp_members */ + 0, /* tp_getset */ + 0, /* tp_base */ + 0, /* tp_dict */ + 0, /* tp_descr_get */ + 0, /* tp_descr_set */ + 0, /* tp_dictoffset */ + 0, /* tp_init */ + PyType_GenericAlloc, /* tp_alloc */ + filter_new, /* tp_new */ + PyObject_GC_Del, /* tp_free */ }; @@ -468,7 +468,7 @@ PyObject *format_spec = NULL; if (!PyArg_ParseTuple(args, "O|U:format", &value, &format_spec)) - return NULL; + return NULL; return PyObject_Format(value, format_spec); } @@ -482,12 +482,12 @@ static PyObject * builtin_chr(PyObject *self, PyObject *args) { - int x; + int x; - if (!PyArg_ParseTuple(args, "i:chr", &x)) - return NULL; + if (!PyArg_ParseTuple(args, "i:chr", &x)) + return NULL; - return PyUnicode_FromOrdinal(x); + return PyUnicode_FromOrdinal(x); } PyDoc_VAR(chr_doc) = PyDoc_STR( @@ -506,111 +506,111 @@ static char * source_as_string(PyObject *cmd, char *funcname, char *what, PyCompilerFlags *cf) { - char *str; - Py_ssize_t size; + char *str; + Py_ssize_t size; - if (PyUnicode_Check(cmd)) { - cf->cf_flags |= PyCF_IGNORE_COOKIE; - cmd = _PyUnicode_AsDefaultEncodedString(cmd, NULL); - if (cmd == NULL) - return NULL; - } - else if (!PyObject_CheckReadBuffer(cmd)) { - PyErr_Format(PyExc_TypeError, - "%s() arg 1 must be a %s object", - funcname, what); - return NULL; - } - if (PyObject_AsReadBuffer(cmd, (const void **)&str, &size) < 0) { - return NULL; - } - if (strlen(str) != size) { - PyErr_SetString(PyExc_TypeError, - "source code string cannot contain null bytes"); - return NULL; - } - return str; + if (PyUnicode_Check(cmd)) { + cf->cf_flags |= PyCF_IGNORE_COOKIE; + cmd = _PyUnicode_AsDefaultEncodedString(cmd, NULL); + if (cmd == NULL) + return NULL; + } + else if (!PyObject_CheckReadBuffer(cmd)) { + PyErr_Format(PyExc_TypeError, + "%s() arg 1 must be a %s object", + funcname, what); + return NULL; + } + if (PyObject_AsReadBuffer(cmd, (const void **)&str, &size) < 0) { + return NULL; + } + if (strlen(str) != size) { + PyErr_SetString(PyExc_TypeError, + "source code string cannot contain null bytes"); + return NULL; + } + return str; } static PyObject * builtin_compile(PyObject *self, PyObject *args, PyObject *kwds) { - char *str; - char *filename; - char *startstr; - int mode = -1; - int dont_inherit = 0; - int supplied_flags = 0; - int is_ast; - PyCompilerFlags cf; - PyObject *cmd; - static char *kwlist[] = {"source", "filename", "mode", "flags", - "dont_inherit", NULL}; - int start[] = {Py_file_input, Py_eval_input, Py_single_input}; - - if (!PyArg_ParseTupleAndKeywords(args, kwds, "Oss|ii:compile", - kwlist, &cmd, &filename, &startstr, - &supplied_flags, &dont_inherit)) - return NULL; - - cf.cf_flags = supplied_flags | PyCF_SOURCE_IS_UTF8; - - if (supplied_flags & - ~(PyCF_MASK | PyCF_MASK_OBSOLETE | PyCF_DONT_IMPLY_DEDENT | PyCF_ONLY_AST)) - { - PyErr_SetString(PyExc_ValueError, - "compile(): unrecognised flags"); - return NULL; - } - /* XXX Warn if (supplied_flags & PyCF_MASK_OBSOLETE) != 0? */ - - if (!dont_inherit) { - PyEval_MergeCompilerFlags(&cf); - } - - if (strcmp(startstr, "exec") == 0) - mode = 0; - else if (strcmp(startstr, "eval") == 0) - mode = 1; - else if (strcmp(startstr, "single") == 0) - mode = 2; - else { - PyErr_SetString(PyExc_ValueError, - "compile() arg 3 must be 'exec', 'eval' or 'single'"); - return NULL; - } - - is_ast = PyAST_Check(cmd); - if (is_ast == -1) - return NULL; - if (is_ast) { - PyObject *result; - if (supplied_flags & PyCF_ONLY_AST) { - Py_INCREF(cmd); - result = cmd; - } - else { - PyArena *arena; - mod_ty mod; - - arena = PyArena_New(); - mod = PyAST_obj2mod(cmd, arena, mode); - if (mod == NULL) { - PyArena_Free(arena); - return NULL; - } - result = (PyObject*)PyAST_Compile(mod, filename, - &cf, arena); - PyArena_Free(arena); - } - return result; - } - - str = source_as_string(cmd, "compile", "string, bytes, AST or code", &cf); - if (str == NULL) - return NULL; + char *str; + char *filename; + char *startstr; + int mode = -1; + int dont_inherit = 0; + int supplied_flags = 0; + int is_ast; + PyCompilerFlags cf; + PyObject *cmd; + static char *kwlist[] = {"source", "filename", "mode", "flags", + "dont_inherit", NULL}; + int start[] = {Py_file_input, Py_eval_input, Py_single_input}; + + if (!PyArg_ParseTupleAndKeywords(args, kwds, "Oss|ii:compile", + kwlist, &cmd, &filename, &startstr, + &supplied_flags, &dont_inherit)) + return NULL; + + cf.cf_flags = supplied_flags | PyCF_SOURCE_IS_UTF8; + + if (supplied_flags & + ~(PyCF_MASK | PyCF_MASK_OBSOLETE | PyCF_DONT_IMPLY_DEDENT | PyCF_ONLY_AST)) + { + PyErr_SetString(PyExc_ValueError, + "compile(): unrecognised flags"); + return NULL; + } + /* XXX Warn if (supplied_flags & PyCF_MASK_OBSOLETE) != 0? */ + + if (!dont_inherit) { + PyEval_MergeCompilerFlags(&cf); + } + + if (strcmp(startstr, "exec") == 0) + mode = 0; + else if (strcmp(startstr, "eval") == 0) + mode = 1; + else if (strcmp(startstr, "single") == 0) + mode = 2; + else { + PyErr_SetString(PyExc_ValueError, + "compile() arg 3 must be 'exec', 'eval' or 'single'"); + return NULL; + } + + is_ast = PyAST_Check(cmd); + if (is_ast == -1) + return NULL; + if (is_ast) { + PyObject *result; + if (supplied_flags & PyCF_ONLY_AST) { + Py_INCREF(cmd); + result = cmd; + } + else { + PyArena *arena; + mod_ty mod; + + arena = PyArena_New(); + mod = PyAST_obj2mod(cmd, arena, mode); + if (mod == NULL) { + PyArena_Free(arena); + return NULL; + } + result = (PyObject*)PyAST_Compile(mod, filename, + &cf, arena); + PyArena_Free(arena); + } + return result; + } - return Py_CompileStringFlags(str, filename, start[mode], &cf); + str = source_as_string(cmd, "compile", "string, bytes, AST or code", &cf); + if (str == NULL) + return NULL; + + return Py_CompileStringFlags(str, filename, start[mode], &cf); } PyDoc_STRVAR(compile_doc, @@ -631,11 +631,11 @@ static PyObject * builtin_dir(PyObject *self, PyObject *args) { - PyObject *arg = NULL; + PyObject *arg = NULL; - if (!PyArg_UnpackTuple(args, "dir", 0, 1, &arg)) - return NULL; - return PyObject_Dir(arg); + if (!PyArg_UnpackTuple(args, "dir", 0, 1, &arg)) + return NULL; + return PyObject_Dir(arg); } PyDoc_STRVAR(dir_doc, @@ -655,11 +655,11 @@ static PyObject * builtin_divmod(PyObject *self, PyObject *args) { - PyObject *v, *w; + PyObject *v, *w; - if (!PyArg_UnpackTuple(args, "divmod", 2, 2, &v, &w)) - return NULL; - return PyNumber_Divmod(v, w); + if (!PyArg_UnpackTuple(args, "divmod", 2, 2, &v, &w)) + return NULL; + return PyNumber_Divmod(v, w); } PyDoc_STRVAR(divmod_doc, @@ -671,65 +671,65 @@ static PyObject * builtin_eval(PyObject *self, PyObject *args) { - PyObject *cmd, *result, *tmp = NULL; - PyObject *globals = Py_None, *locals = Py_None; - char *str; - PyCompilerFlags cf; - - if (!PyArg_UnpackTuple(args, "eval", 1, 3, &cmd, &globals, &locals)) - return NULL; - if (locals != Py_None && !PyMapping_Check(locals)) { - PyErr_SetString(PyExc_TypeError, "locals must be a mapping"); - return NULL; - } - if (globals != Py_None && !PyDict_Check(globals)) { - PyErr_SetString(PyExc_TypeError, PyMapping_Check(globals) ? - "globals must be a real dict; try eval(expr, {}, mapping)" - : "globals must be a dict"); - return NULL; - } - if (globals == Py_None) { - globals = PyEval_GetGlobals(); - if (locals == Py_None) - locals = PyEval_GetLocals(); - } - else if (locals == Py_None) - locals = globals; - - if (globals == NULL || locals == NULL) { - PyErr_SetString(PyExc_TypeError, - "eval must be given globals and locals " - "when called without a frame"); - return NULL; - } - - if (PyDict_GetItemString(globals, "__builtins__") == NULL) { - if (PyDict_SetItemString(globals, "__builtins__", - PyEval_GetBuiltins()) != 0) - return NULL; - } - - if (PyCode_Check(cmd)) { - if (PyCode_GetNumFree((PyCodeObject *)cmd) > 0) { - PyErr_SetString(PyExc_TypeError, - "code object passed to eval() may not contain free variables"); - return NULL; - } - return PyEval_EvalCode((PyCodeObject *) cmd, globals, locals); - } - - cf.cf_flags = PyCF_SOURCE_IS_UTF8; - str = source_as_string(cmd, "eval", "string, bytes or code", &cf); - if (str == NULL) - return NULL; - - while (*str == ' ' || *str == '\t') - str++; - - (void)PyEval_MergeCompilerFlags(&cf); - result = PyRun_StringFlags(str, Py_eval_input, globals, locals, &cf); - Py_XDECREF(tmp); - return result; + PyObject *cmd, *result, *tmp = NULL; + PyObject *globals = Py_None, *locals = Py_None; + char *str; + PyCompilerFlags cf; + + if (!PyArg_UnpackTuple(args, "eval", 1, 3, &cmd, &globals, &locals)) + return NULL; + if (locals != Py_None && !PyMapping_Check(locals)) { + PyErr_SetString(PyExc_TypeError, "locals must be a mapping"); + return NULL; + } + if (globals != Py_None && !PyDict_Check(globals)) { + PyErr_SetString(PyExc_TypeError, PyMapping_Check(globals) ? + "globals must be a real dict; try eval(expr, {}, mapping)" + : "globals must be a dict"); + return NULL; + } + if (globals == Py_None) { + globals = PyEval_GetGlobals(); + if (locals == Py_None) + locals = PyEval_GetLocals(); + } + else if (locals == Py_None) + locals = globals; + + if (globals == NULL || locals == NULL) { + PyErr_SetString(PyExc_TypeError, + "eval must be given globals and locals " + "when called without a frame"); + return NULL; + } + + if (PyDict_GetItemString(globals, "__builtins__") == NULL) { + if (PyDict_SetItemString(globals, "__builtins__", + PyEval_GetBuiltins()) != 0) + return NULL; + } + + if (PyCode_Check(cmd)) { + if (PyCode_GetNumFree((PyCodeObject *)cmd) > 0) { + PyErr_SetString(PyExc_TypeError, + "code object passed to eval() may not contain free variables"); + return NULL; + } + return PyEval_EvalCode((PyCodeObject *) cmd, globals, locals); + } + + cf.cf_flags = PyCF_SOURCE_IS_UTF8; + str = source_as_string(cmd, "eval", "string, bytes or code", &cf); + if (str == NULL) + return NULL; + + while (*str == ' ' || *str == '\t') + str++; + + (void)PyEval_MergeCompilerFlags(&cf); + result = PyRun_StringFlags(str, Py_eval_input, globals, locals, &cf); + Py_XDECREF(tmp); + return result; } PyDoc_STRVAR(eval_doc, @@ -745,72 +745,72 @@ static PyObject * builtin_exec(PyObject *self, PyObject *args) { - PyObject *v; - PyObject *prog, *globals = Py_None, *locals = Py_None; - int plain = 0; - - if (!PyArg_UnpackTuple(args, "exec", 1, 3, &prog, &globals, &locals)) - return NULL; - - if (globals == Py_None) { - globals = PyEval_GetGlobals(); - if (locals == Py_None) { - locals = PyEval_GetLocals(); - plain = 1; - } - if (!globals || !locals) { - PyErr_SetString(PyExc_SystemError, - "globals and locals cannot be NULL"); - return NULL; - } - } - else if (locals == Py_None) - locals = globals; - - if (!PyDict_Check(globals)) { - PyErr_Format(PyExc_TypeError, "exec() arg 2 must be a dict, not %.100s", - globals->ob_type->tp_name); - return NULL; - } - if (!PyMapping_Check(locals)) { - PyErr_Format(PyExc_TypeError, - "arg 3 must be a mapping or None, not %.100s", - locals->ob_type->tp_name); - return NULL; - } - if (PyDict_GetItemString(globals, "__builtins__") == NULL) { - if (PyDict_SetItemString(globals, "__builtins__", - PyEval_GetBuiltins()) != 0) - return NULL; - } - - if (PyCode_Check(prog)) { - if (PyCode_GetNumFree((PyCodeObject *)prog) > 0) { - PyErr_SetString(PyExc_TypeError, - "code object passed to exec() may not " - "contain free variables"); - return NULL; - } - v = PyEval_EvalCode((PyCodeObject *) prog, globals, locals); - } - else { - char *str; - PyCompilerFlags cf; - cf.cf_flags = PyCF_SOURCE_IS_UTF8; - str = source_as_string(prog, "exec", - "string, bytes or code", &cf); - if (str == NULL) - return NULL; - if (PyEval_MergeCompilerFlags(&cf)) - v = PyRun_StringFlags(str, Py_file_input, globals, - locals, &cf); - else - v = PyRun_String(str, Py_file_input, globals, locals); - } - if (v == NULL) - return NULL; - Py_DECREF(v); - Py_RETURN_NONE; + PyObject *v; + PyObject *prog, *globals = Py_None, *locals = Py_None; + int plain = 0; + + if (!PyArg_UnpackTuple(args, "exec", 1, 3, &prog, &globals, &locals)) + return NULL; + + if (globals == Py_None) { + globals = PyEval_GetGlobals(); + if (locals == Py_None) { + locals = PyEval_GetLocals(); + plain = 1; + } + if (!globals || !locals) { + PyErr_SetString(PyExc_SystemError, + "globals and locals cannot be NULL"); + return NULL; + } + } + else if (locals == Py_None) + locals = globals; + + if (!PyDict_Check(globals)) { + PyErr_Format(PyExc_TypeError, "exec() arg 2 must be a dict, not %.100s", + globals->ob_type->tp_name); + return NULL; + } + if (!PyMapping_Check(locals)) { + PyErr_Format(PyExc_TypeError, + "arg 3 must be a mapping or None, not %.100s", + locals->ob_type->tp_name); + return NULL; + } + if (PyDict_GetItemString(globals, "__builtins__") == NULL) { + if (PyDict_SetItemString(globals, "__builtins__", + PyEval_GetBuiltins()) != 0) + return NULL; + } + + if (PyCode_Check(prog)) { + if (PyCode_GetNumFree((PyCodeObject *)prog) > 0) { + PyErr_SetString(PyExc_TypeError, + "code object passed to exec() may not " + "contain free variables"); + return NULL; + } + v = PyEval_EvalCode((PyCodeObject *) prog, globals, locals); + } + else { + char *str; + PyCompilerFlags cf; + cf.cf_flags = PyCF_SOURCE_IS_UTF8; + str = source_as_string(prog, "exec", + "string, bytes or code", &cf); + if (str == NULL) + return NULL; + if (PyEval_MergeCompilerFlags(&cf)) + v = PyRun_StringFlags(str, Py_file_input, globals, + locals, &cf); + else + v = PyRun_String(str, Py_file_input, globals, locals); + } + if (v == NULL) + return NULL; + Py_DECREF(v); + Py_RETURN_NONE; } PyDoc_STRVAR(exec_doc, @@ -825,26 +825,26 @@ static PyObject * builtin_getattr(PyObject *self, PyObject *args) { - PyObject *v, *result, *dflt = NULL; - PyObject *name; + PyObject *v, *result, *dflt = NULL; + PyObject *name; - if (!PyArg_UnpackTuple(args, "getattr", 2, 3, &v, &name, &dflt)) - return NULL; + if (!PyArg_UnpackTuple(args, "getattr", 2, 3, &v, &name, &dflt)) + return NULL; - if (!PyUnicode_Check(name)) { - PyErr_SetString(PyExc_TypeError, - "getattr(): attribute name must be string"); - return NULL; - } - result = PyObject_GetAttr(v, name); - if (result == NULL && dflt != NULL && - PyErr_ExceptionMatches(PyExc_AttributeError)) - { - PyErr_Clear(); - Py_INCREF(dflt); - result = dflt; - } - return result; + if (!PyUnicode_Check(name)) { + PyErr_SetString(PyExc_TypeError, + "getattr(): attribute name must be string"); + return NULL; + } + result = PyObject_GetAttr(v, name); + if (result == NULL && dflt != NULL && + PyErr_ExceptionMatches(PyExc_AttributeError)) + { + PyErr_Clear(); + Py_INCREF(dflt); + result = dflt; + } + return result; } PyDoc_STRVAR(getattr_doc, @@ -858,11 +858,11 @@ static PyObject * builtin_globals(PyObject *self) { - PyObject *d; + PyObject *d; - d = PyEval_GetGlobals(); - Py_XINCREF(d); - return d; + d = PyEval_GetGlobals(); + Py_XINCREF(d); + return d; } PyDoc_STRVAR(globals_doc, @@ -874,29 +874,29 @@ static PyObject * builtin_hasattr(PyObject *self, PyObject *args) { - PyObject *v; - PyObject *name; + PyObject *v; + PyObject *name; - if (!PyArg_UnpackTuple(args, "hasattr", 2, 2, &v, &name)) - return NULL; - if (!PyUnicode_Check(name)) { - PyErr_SetString(PyExc_TypeError, - "hasattr(): attribute name must be string"); - return NULL; - } - v = PyObject_GetAttr(v, name); - if (v == NULL) { - if (!PyErr_ExceptionMatches(PyExc_Exception)) - return NULL; - else { - PyErr_Clear(); - Py_INCREF(Py_False); - return Py_False; - } - } - Py_DECREF(v); - Py_INCREF(Py_True); - return Py_True; + if (!PyArg_UnpackTuple(args, "hasattr", 2, 2, &v, &name)) + return NULL; + if (!PyUnicode_Check(name)) { + PyErr_SetString(PyExc_TypeError, + "hasattr(): attribute name must be string"); + return NULL; + } + v = PyObject_GetAttr(v, name); + if (v == NULL) { + if (!PyErr_ExceptionMatches(PyExc_Exception)) + return NULL; + else { + PyErr_Clear(); + Py_INCREF(Py_False); + return Py_False; + } + } + Py_DECREF(v); + Py_INCREF(Py_True); + return Py_True; } PyDoc_STRVAR(hasattr_doc, @@ -909,7 +909,7 @@ static PyObject * builtin_id(PyObject *self, PyObject *v) { - return PyLong_FromVoidPtr(v); + return PyLong_FromVoidPtr(v); } PyDoc_STRVAR(id_doc, @@ -922,181 +922,181 @@ /* map object ************************************************************/ typedef struct { - PyObject_HEAD - PyObject *iters; - PyObject *func; + PyObject_HEAD + PyObject *iters; + PyObject *func; } mapobject; static PyObject * map_new(PyTypeObject *type, PyObject *args, PyObject *kwds) { - PyObject *it, *iters, *func; - mapobject *lz; - Py_ssize_t numargs, i; - - if (type == &PyMap_Type && !_PyArg_NoKeywords("map()", kwds)) - return NULL; - - numargs = PyTuple_Size(args); - if (numargs < 2) { - PyErr_SetString(PyExc_TypeError, - "map() must have at least two arguments."); - return NULL; - } - - iters = PyTuple_New(numargs-1); - if (iters == NULL) - return NULL; - - for (i=1 ; itp_alloc(type, 0); - if (lz == NULL) { - Py_DECREF(iters); - return NULL; - } - lz->iters = iters; - func = PyTuple_GET_ITEM(args, 0); - Py_INCREF(func); - lz->func = func; + PyObject *it, *iters, *func; + mapobject *lz; + Py_ssize_t numargs, i; - return (PyObject *)lz; + if (type == &PyMap_Type && !_PyArg_NoKeywords("map()", kwds)) + return NULL; + + numargs = PyTuple_Size(args); + if (numargs < 2) { + PyErr_SetString(PyExc_TypeError, + "map() must have at least two arguments."); + return NULL; + } + + iters = PyTuple_New(numargs-1); + if (iters == NULL) + return NULL; + + for (i=1 ; itp_alloc(type, 0); + if (lz == NULL) { + Py_DECREF(iters); + return NULL; + } + lz->iters = iters; + func = PyTuple_GET_ITEM(args, 0); + Py_INCREF(func); + lz->func = func; + + return (PyObject *)lz; } static void map_dealloc(mapobject *lz) { - PyObject_GC_UnTrack(lz); - Py_XDECREF(lz->iters); - Py_XDECREF(lz->func); - Py_TYPE(lz)->tp_free(lz); + PyObject_GC_UnTrack(lz); + Py_XDECREF(lz->iters); + Py_XDECREF(lz->func); + Py_TYPE(lz)->tp_free(lz); } static int map_traverse(mapobject *lz, visitproc visit, void *arg) { - Py_VISIT(lz->iters); - Py_VISIT(lz->func); - return 0; + Py_VISIT(lz->iters); + Py_VISIT(lz->func); + return 0; } static PyObject * map_next(mapobject *lz) { - PyObject *val; - PyObject *argtuple; - PyObject *result; - Py_ssize_t numargs, i; - - numargs = PyTuple_Size(lz->iters); - argtuple = PyTuple_New(numargs); - if (argtuple == NULL) - return NULL; - - for (i=0 ; iiters, i)); - if (val == NULL) { - Py_DECREF(argtuple); - return NULL; - } - PyTuple_SET_ITEM(argtuple, i, val); - } - result = PyObject_Call(lz->func, argtuple, NULL); - Py_DECREF(argtuple); - return result; + PyObject *val; + PyObject *argtuple; + PyObject *result; + Py_ssize_t numargs, i; + + numargs = PyTuple_Size(lz->iters); + argtuple = PyTuple_New(numargs); + if (argtuple == NULL) + return NULL; + + for (i=0 ; iiters, i)); + if (val == NULL) { + Py_DECREF(argtuple); + return NULL; + } + PyTuple_SET_ITEM(argtuple, i, val); + } + result = PyObject_Call(lz->func, argtuple, NULL); + Py_DECREF(argtuple); + return result; } PyDoc_STRVAR(map_doc, "map(func, *iterables) --> map object\n\ \n\ Make an iterator that computes the function using arguments from\n\ -each of the iterables. Stops when the shortest iterable is exhausted."); +each of the iterables. Stops when the shortest iterable is exhausted."); PyTypeObject PyMap_Type = { - PyVarObject_HEAD_INIT(&PyType_Type, 0) - "map", /* tp_name */ - sizeof(mapobject), /* tp_basicsize */ - 0, /* tp_itemsize */ - /* methods */ - (destructor)map_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 | - Py_TPFLAGS_BASETYPE, /* tp_flags */ - map_doc, /* tp_doc */ - (traverseproc)map_traverse, /* tp_traverse */ - 0, /* tp_clear */ - 0, /* tp_richcompare */ - 0, /* tp_weaklistoffset */ - PyObject_SelfIter, /* tp_iter */ - (iternextfunc)map_next, /* tp_iternext */ - 0, /* tp_methods */ - 0, /* tp_members */ - 0, /* tp_getset */ - 0, /* tp_base */ - 0, /* tp_dict */ - 0, /* tp_descr_get */ - 0, /* tp_descr_set */ - 0, /* tp_dictoffset */ - 0, /* tp_init */ - PyType_GenericAlloc, /* tp_alloc */ - map_new, /* tp_new */ - PyObject_GC_Del, /* tp_free */ + PyVarObject_HEAD_INIT(&PyType_Type, 0) + "map", /* tp_name */ + sizeof(mapobject), /* tp_basicsize */ + 0, /* tp_itemsize */ + /* methods */ + (destructor)map_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 | + Py_TPFLAGS_BASETYPE, /* tp_flags */ + map_doc, /* tp_doc */ + (traverseproc)map_traverse, /* tp_traverse */ + 0, /* tp_clear */ + 0, /* tp_richcompare */ + 0, /* tp_weaklistoffset */ + PyObject_SelfIter, /* tp_iter */ + (iternextfunc)map_next, /* tp_iternext */ + 0, /* tp_methods */ + 0, /* tp_members */ + 0, /* tp_getset */ + 0, /* tp_base */ + 0, /* tp_dict */ + 0, /* tp_descr_get */ + 0, /* tp_descr_set */ + 0, /* tp_dictoffset */ + 0, /* tp_init */ + PyType_GenericAlloc, /* tp_alloc */ + map_new, /* tp_new */ + PyObject_GC_Del, /* tp_free */ }; static PyObject * builtin_next(PyObject *self, PyObject *args) { - PyObject *it, *res; - PyObject *def = NULL; + PyObject *it, *res; + PyObject *def = NULL; + + if (!PyArg_UnpackTuple(args, "next", 1, 2, &it, &def)) + return NULL; + if (!PyIter_Check(it)) { + PyErr_Format(PyExc_TypeError, + "%.200s object is not an iterator", + it->ob_type->tp_name); + return NULL; + } - if (!PyArg_UnpackTuple(args, "next", 1, 2, &it, &def)) - return NULL; - if (!PyIter_Check(it)) { - PyErr_Format(PyExc_TypeError, - "%.200s object is not an iterator", - it->ob_type->tp_name); - return NULL; - } - - res = (*it->ob_type->tp_iternext)(it); - if (res != NULL) { - return res; - } else if (def != NULL) { - if (PyErr_Occurred()) { - if(!PyErr_ExceptionMatches(PyExc_StopIteration)) - return NULL; - PyErr_Clear(); - } - Py_INCREF(def); - return def; - } else if (PyErr_Occurred()) { - return NULL; - } else { - PyErr_SetNone(PyExc_StopIteration); - return NULL; - } + res = (*it->ob_type->tp_iternext)(it); + if (res != NULL) { + return res; + } else if (def != NULL) { + if (PyErr_Occurred()) { + if(!PyErr_ExceptionMatches(PyExc_StopIteration)) + return NULL; + PyErr_Clear(); + } + Py_INCREF(def); + return def; + } else if (PyErr_Occurred()) { + return NULL; + } else { + PyErr_SetNone(PyExc_StopIteration); + return NULL; + } } PyDoc_STRVAR(next_doc, @@ -1109,16 +1109,16 @@ static PyObject * builtin_setattr(PyObject *self, PyObject *args) { - PyObject *v; - PyObject *name; - PyObject *value; - - if (!PyArg_UnpackTuple(args, "setattr", 3, 3, &v, &name, &value)) - return NULL; - if (PyObject_SetAttr(v, name, value) != 0) - return NULL; - Py_INCREF(Py_None); - return Py_None; + PyObject *v; + PyObject *name; + PyObject *value; + + if (!PyArg_UnpackTuple(args, "setattr", 3, 3, &v, &name, &value)) + return NULL; + if (PyObject_SetAttr(v, name, value) != 0) + return NULL; + Py_INCREF(Py_None); + return Py_None; } PyDoc_STRVAR(setattr_doc, @@ -1131,15 +1131,15 @@ static PyObject * builtin_delattr(PyObject *self, PyObject *args) { - PyObject *v; - PyObject *name; + PyObject *v; + PyObject *name; - if (!PyArg_UnpackTuple(args, "delattr", 2, 2, &v, &name)) - return NULL; - if (PyObject_SetAttr(v, name, (PyObject *)NULL) != 0) - return NULL; - Py_INCREF(Py_None); - return Py_None; + if (!PyArg_UnpackTuple(args, "delattr", 2, 2, &v, &name)) + return NULL; + if (PyObject_SetAttr(v, name, (PyObject *)NULL) != 0) + return NULL; + Py_INCREF(Py_None); + return Py_None; } PyDoc_STRVAR(delattr_doc, @@ -1152,12 +1152,12 @@ static PyObject * builtin_hash(PyObject *self, PyObject *v) { - long x; + long x; - x = PyObject_Hash(v); - if (x == -1) - return NULL; - return PyLong_FromLong(x); + x = PyObject_Hash(v); + if (x == -1) + return NULL; + return PyLong_FromLong(x); } PyDoc_STRVAR(hash_doc, @@ -1170,7 +1170,7 @@ static PyObject * builtin_hex(PyObject *self, PyObject *v) { - return PyNumber_ToBase(v, 16); + return PyNumber_ToBase(v, 16); } PyDoc_STRVAR(hex_doc, @@ -1182,18 +1182,18 @@ static PyObject * builtin_iter(PyObject *self, PyObject *args) { - PyObject *v, *w = NULL; + PyObject *v, *w = NULL; - if (!PyArg_UnpackTuple(args, "iter", 1, 2, &v, &w)) - return NULL; - if (w == NULL) - return PyObject_GetIter(v); - if (!PyCallable_Check(v)) { - PyErr_SetString(PyExc_TypeError, - "iter(v, w): v must be callable"); - return NULL; - } - return PyCallIter_New(v, w); + if (!PyArg_UnpackTuple(args, "iter", 1, 2, &v, &w)) + return NULL; + if (w == NULL) + return PyObject_GetIter(v); + if (!PyCallable_Check(v)) { + PyErr_SetString(PyExc_TypeError, + "iter(v, w): v must be callable"); + return NULL; + } + return PyCallIter_New(v, w); } PyDoc_STRVAR(iter_doc, @@ -1208,12 +1208,12 @@ static PyObject * builtin_len(PyObject *self, PyObject *v) { - Py_ssize_t res; + Py_ssize_t res; - res = PyObject_Size(v); - if (res < 0 && PyErr_Occurred()) - return NULL; - return PyLong_FromSsize_t(res); + res = PyObject_Size(v); + if (res < 0 && PyErr_Occurred()) + return NULL; + return PyLong_FromSsize_t(res); } PyDoc_STRVAR(len_doc, @@ -1225,11 +1225,11 @@ static PyObject * builtin_locals(PyObject *self) { - PyObject *d; + PyObject *d; - d = PyEval_GetLocals(); - Py_XINCREF(d); - return d; + d = PyEval_GetLocals(); + Py_XINCREF(d); + return d; } PyDoc_STRVAR(locals_doc, @@ -1241,96 +1241,96 @@ static PyObject * min_max(PyObject *args, PyObject *kwds, int op) { - PyObject *v, *it, *item, *val, *maxitem, *maxval, *keyfunc=NULL; - const char *name = op == Py_LT ? "min" : "max"; + PyObject *v, *it, *item, *val, *maxitem, *maxval, *keyfunc=NULL; + const char *name = op == Py_LT ? "min" : "max"; + + if (PyTuple_Size(args) > 1) + v = args; + else if (!PyArg_UnpackTuple(args, (char *)name, 1, 1, &v)) + return NULL; - if (PyTuple_Size(args) > 1) - v = args; - else if (!PyArg_UnpackTuple(args, (char *)name, 1, 1, &v)) - return NULL; - - if (kwds != NULL && PyDict_Check(kwds) && PyDict_Size(kwds)) { - keyfunc = PyDict_GetItemString(kwds, "key"); - if (PyDict_Size(kwds)!=1 || keyfunc == NULL) { - PyErr_Format(PyExc_TypeError, - "%s() got an unexpected keyword argument", name); - return NULL; - } - Py_INCREF(keyfunc); - } - - it = PyObject_GetIter(v); - if (it == NULL) { - Py_XDECREF(keyfunc); - return NULL; - } - - maxitem = NULL; /* the result */ - maxval = NULL; /* the value associated with the result */ - while (( item = PyIter_Next(it) )) { - /* get the value from the key function */ - if (keyfunc != NULL) { - val = PyObject_CallFunctionObjArgs(keyfunc, item, NULL); - if (val == NULL) - goto Fail_it_item; - } - /* no key function; the value is the item */ - else { - val = item; - Py_INCREF(val); - } - - /* maximum value and item are unset; set them */ - if (maxval == NULL) { - maxitem = item; - maxval = val; - } - /* maximum value and item are set; update them as necessary */ - else { - int cmp = PyObject_RichCompareBool(val, maxval, op); - if (cmp < 0) - goto Fail_it_item_and_val; - else if (cmp > 0) { - Py_DECREF(maxval); - Py_DECREF(maxitem); - maxval = val; - maxitem = item; - } - else { - Py_DECREF(item); - Py_DECREF(val); - } - } - } - if (PyErr_Occurred()) - goto Fail_it; - if (maxval == NULL) { - PyErr_Format(PyExc_ValueError, - "%s() arg is an empty sequence", name); - assert(maxitem == NULL); - } - else - Py_DECREF(maxval); - Py_DECREF(it); - Py_XDECREF(keyfunc); - return maxitem; + if (kwds != NULL && PyDict_Check(kwds) && PyDict_Size(kwds)) { + keyfunc = PyDict_GetItemString(kwds, "key"); + if (PyDict_Size(kwds)!=1 || keyfunc == NULL) { + PyErr_Format(PyExc_TypeError, + "%s() got an unexpected keyword argument", name); + return NULL; + } + Py_INCREF(keyfunc); + } + + it = PyObject_GetIter(v); + if (it == NULL) { + Py_XDECREF(keyfunc); + return NULL; + } + + maxitem = NULL; /* the result */ + maxval = NULL; /* the value associated with the result */ + while (( item = PyIter_Next(it) )) { + /* get the value from the key function */ + if (keyfunc != NULL) { + val = PyObject_CallFunctionObjArgs(keyfunc, item, NULL); + if (val == NULL) + goto Fail_it_item; + } + /* no key function; the value is the item */ + else { + val = item; + Py_INCREF(val); + } + + /* maximum value and item are unset; set them */ + if (maxval == NULL) { + maxitem = item; + maxval = val; + } + /* maximum value and item are set; update them as necessary */ + else { + int cmp = PyObject_RichCompareBool(val, maxval, op); + if (cmp < 0) + goto Fail_it_item_and_val; + else if (cmp > 0) { + Py_DECREF(maxval); + Py_DECREF(maxitem); + maxval = val; + maxitem = item; + } + else { + Py_DECREF(item); + Py_DECREF(val); + } + } + } + if (PyErr_Occurred()) + goto Fail_it; + if (maxval == NULL) { + PyErr_Format(PyExc_ValueError, + "%s() arg is an empty sequence", name); + assert(maxitem == NULL); + } + else + Py_DECREF(maxval); + Py_DECREF(it); + Py_XDECREF(keyfunc); + return maxitem; Fail_it_item_and_val: - Py_DECREF(val); + Py_DECREF(val); Fail_it_item: - Py_DECREF(item); + Py_DECREF(item); Fail_it: - Py_XDECREF(maxval); - Py_XDECREF(maxitem); - Py_DECREF(it); - Py_XDECREF(keyfunc); - return NULL; + Py_XDECREF(maxval); + Py_XDECREF(maxitem); + Py_DECREF(it); + Py_XDECREF(keyfunc); + return NULL; } static PyObject * builtin_min(PyObject *self, PyObject *args, PyObject *kwds) { - return min_max(args, kwds, Py_LT); + return min_max(args, kwds, Py_LT); } PyDoc_STRVAR(min_doc, @@ -1344,7 +1344,7 @@ static PyObject * builtin_max(PyObject *self, PyObject *args, PyObject *kwds) { - return min_max(args, kwds, Py_GT); + return min_max(args, kwds, Py_GT); } PyDoc_STRVAR(max_doc, @@ -1358,7 +1358,7 @@ static PyObject * builtin_oct(PyObject *self, PyObject *v) { - return PyNumber_ToBase(v, 8); + return PyNumber_ToBase(v, 8); } PyDoc_STRVAR(oct_doc, @@ -1370,56 +1370,56 @@ static PyObject * builtin_ord(PyObject *self, PyObject* obj) { - long ord; - Py_ssize_t size; + long ord; + Py_ssize_t size; - if (PyBytes_Check(obj)) { - size = PyBytes_GET_SIZE(obj); - if (size == 1) { - ord = (long)((unsigned char)*PyBytes_AS_STRING(obj)); - return PyLong_FromLong(ord); - } - } - else if (PyUnicode_Check(obj)) { - size = PyUnicode_GET_SIZE(obj); - if (size == 1) { - ord = (long)*PyUnicode_AS_UNICODE(obj); - return PyLong_FromLong(ord); - } + if (PyBytes_Check(obj)) { + size = PyBytes_GET_SIZE(obj); + if (size == 1) { + ord = (long)((unsigned char)*PyBytes_AS_STRING(obj)); + return PyLong_FromLong(ord); + } + } + else if (PyUnicode_Check(obj)) { + size = PyUnicode_GET_SIZE(obj); + if (size == 1) { + ord = (long)*PyUnicode_AS_UNICODE(obj); + return PyLong_FromLong(ord); + } #ifndef Py_UNICODE_WIDE - if (size == 2) { - /* Decode a valid surrogate pair */ - int c0 = PyUnicode_AS_UNICODE(obj)[0]; - int c1 = PyUnicode_AS_UNICODE(obj)[1]; - if (0xD800 <= c0 && c0 <= 0xDBFF && - 0xDC00 <= c1 && c1 <= 0xDFFF) { - ord = ((((c0 & 0x03FF) << 10) | (c1 & 0x03FF)) + - 0x00010000); - return PyLong_FromLong(ord); - } - } + if (size == 2) { + /* Decode a valid surrogate pair */ + int c0 = PyUnicode_AS_UNICODE(obj)[0]; + int c1 = PyUnicode_AS_UNICODE(obj)[1]; + if (0xD800 <= c0 && c0 <= 0xDBFF && + 0xDC00 <= c1 && c1 <= 0xDFFF) { + ord = ((((c0 & 0x03FF) << 10) | (c1 & 0x03FF)) + + 0x00010000); + return PyLong_FromLong(ord); + } + } #endif - } - else if (PyByteArray_Check(obj)) { - /* XXX Hopefully this is temporary */ - size = PyByteArray_GET_SIZE(obj); - if (size == 1) { - ord = (long)((unsigned char)*PyByteArray_AS_STRING(obj)); - return PyLong_FromLong(ord); - } - } - else { - PyErr_Format(PyExc_TypeError, - "ord() expected string of length 1, but " \ - "%.200s found", obj->ob_type->tp_name); - return NULL; - } - - PyErr_Format(PyExc_TypeError, - "ord() expected a character, " - "but string of length %zd found", - size); - return NULL; + } + else if (PyByteArray_Check(obj)) { + /* XXX Hopefully this is temporary */ + size = PyByteArray_GET_SIZE(obj); + if (size == 1) { + ord = (long)((unsigned char)*PyByteArray_AS_STRING(obj)); + return PyLong_FromLong(ord); + } + } + else { + PyErr_Format(PyExc_TypeError, + "ord() expected string of length 1, but " \ + "%.200s found", obj->ob_type->tp_name); + return NULL; + } + + PyErr_Format(PyExc_TypeError, + "ord() expected a character, " + "but string of length %zd found", + size); + return NULL; } PyDoc_VAR(ord_doc) = PyDoc_STR( @@ -1438,11 +1438,11 @@ static PyObject * builtin_pow(PyObject *self, PyObject *args) { - PyObject *v, *w, *z = Py_None; + PyObject *v, *w, *z = Py_None; - if (!PyArg_UnpackTuple(args, "pow", 2, 3, &v, &w, &z)) - return NULL; - return PyNumber_Power(v, w, z); + if (!PyArg_UnpackTuple(args, "pow", 2, 3, &v, &w, &z)) + return NULL; + return PyNumber_Power(v, w, z); } PyDoc_STRVAR(pow_doc, @@ -1456,62 +1456,62 @@ static PyObject * builtin_print(PyObject *self, PyObject *args, PyObject *kwds) { - static char *kwlist[] = {"sep", "end", "file", 0}; - static PyObject *dummy_args; - PyObject *sep = NULL, *end = NULL, *file = NULL; - int i, err; - - if (dummy_args == NULL) { - if (!(dummy_args = PyTuple_New(0))) - return NULL; - } - if (!PyArg_ParseTupleAndKeywords(dummy_args, kwds, "|OOO:print", - kwlist, &sep, &end, &file)) - return NULL; - if (file == NULL || file == Py_None) { - file = PySys_GetObject("stdout"); - /* sys.stdout may be None when FILE* stdout isn't connected */ - if (file == Py_None) - Py_RETURN_NONE; - } - - if (sep && sep != Py_None && !PyUnicode_Check(sep)) { - PyErr_Format(PyExc_TypeError, - "sep must be None or a string, not %.200s", - sep->ob_type->tp_name); - return NULL; - } - if (end && end != Py_None && !PyUnicode_Check(end)) { - PyErr_Format(PyExc_TypeError, - "end must be None or a string, not %.200s", - end->ob_type->tp_name); - return NULL; - } - - for (i = 0; i < PyTuple_Size(args); i++) { - if (i > 0) { - if (sep == NULL || sep == Py_None) - err = PyFile_WriteString(" ", file); - else - err = PyFile_WriteObject(sep, file, - Py_PRINT_RAW); - if (err) - return NULL; - } - err = PyFile_WriteObject(PyTuple_GetItem(args, i), file, - Py_PRINT_RAW); - if (err) - return NULL; - } - - if (end == NULL || end == Py_None) - err = PyFile_WriteString("\n", file); - else - err = PyFile_WriteObject(end, file, Py_PRINT_RAW); - if (err) - return NULL; + static char *kwlist[] = {"sep", "end", "file", 0}; + static PyObject *dummy_args; + PyObject *sep = NULL, *end = NULL, *file = NULL; + int i, err; + + if (dummy_args == NULL) { + if (!(dummy_args = PyTuple_New(0))) + return NULL; + } + if (!PyArg_ParseTupleAndKeywords(dummy_args, kwds, "|OOO:print", + kwlist, &sep, &end, &file)) + return NULL; + if (file == NULL || file == Py_None) { + file = PySys_GetObject("stdout"); + /* sys.stdout may be None when FILE* stdout isn't connected */ + if (file == Py_None) + Py_RETURN_NONE; + } + + if (sep && sep != Py_None && !PyUnicode_Check(sep)) { + PyErr_Format(PyExc_TypeError, + "sep must be None or a string, not %.200s", + sep->ob_type->tp_name); + return NULL; + } + if (end && end != Py_None && !PyUnicode_Check(end)) { + PyErr_Format(PyExc_TypeError, + "end must be None or a string, not %.200s", + end->ob_type->tp_name); + return NULL; + } + + for (i = 0; i < PyTuple_Size(args); i++) { + if (i > 0) { + if (sep == NULL || sep == Py_None) + err = PyFile_WriteString(" ", file); + else + err = PyFile_WriteObject(sep, file, + Py_PRINT_RAW); + if (err) + return NULL; + } + err = PyFile_WriteObject(PyTuple_GetItem(args, i), file, + Py_PRINT_RAW); + if (err) + return NULL; + } + + if (end == NULL || end == Py_None) + err = PyFile_WriteString("\n", file); + else + err = PyFile_WriteObject(end, file, Py_PRINT_RAW); + if (err) + return NULL; - Py_RETURN_NONE; + Py_RETURN_NONE; } PyDoc_STRVAR(print_doc, @@ -1527,164 +1527,164 @@ static PyObject * builtin_input(PyObject *self, PyObject *args) { - PyObject *promptarg = NULL; - PyObject *fin = PySys_GetObject("stdin"); - PyObject *fout = PySys_GetObject("stdout"); - PyObject *ferr = PySys_GetObject("stderr"); - PyObject *tmp; - long fd; - int tty; - - /* Parse arguments */ - if (!PyArg_UnpackTuple(args, "input", 0, 1, &promptarg)) - return NULL; - - /* Check that stdin/out/err are intact */ - if (fin == NULL || fin == Py_None) { - PyErr_SetString(PyExc_RuntimeError, - "input(): lost sys.stdin"); - return NULL; - } - if (fout == NULL || fout == Py_None) { - PyErr_SetString(PyExc_RuntimeError, - "input(): lost sys.stdout"); - return NULL; - } - if (ferr == NULL || ferr == Py_None) { - PyErr_SetString(PyExc_RuntimeError, - "input(): lost sys.stderr"); - return NULL; - } - - /* First of all, flush stderr */ - tmp = PyObject_CallMethod(ferr, "flush", ""); - if (tmp == NULL) - PyErr_Clear(); - else - Py_DECREF(tmp); - - /* We should only use (GNU) readline if Python's sys.stdin and - sys.stdout are the same as C's stdin and stdout, because we - need to pass it those. */ - tmp = PyObject_CallMethod(fin, "fileno", ""); - if (tmp == NULL) { - PyErr_Clear(); - tty = 0; - } - else { - fd = PyLong_AsLong(tmp); - Py_DECREF(tmp); - if (fd < 0 && PyErr_Occurred()) - return NULL; - tty = fd == fileno(stdin) && isatty(fd); - } - if (tty) { - tmp = PyObject_CallMethod(fout, "fileno", ""); - if (tmp == NULL) - PyErr_Clear(); - else { - fd = PyLong_AsLong(tmp); - Py_DECREF(tmp); - if (fd < 0 && PyErr_Occurred()) - return NULL; - tty = fd == fileno(stdout) && isatty(fd); - } - } - - /* If we're interactive, use (GNU) readline */ - if (tty) { - PyObject *po; - char *prompt; - char *s; - PyObject *stdin_encoding; - PyObject *result; - - stdin_encoding = PyObject_GetAttrString(fin, "encoding"); - if (!stdin_encoding) - /* stdin is a text stream, so it must have an - encoding. */ - return NULL; - tmp = PyObject_CallMethod(fout, "flush", ""); - if (tmp == NULL) - PyErr_Clear(); - else - Py_DECREF(tmp); - if (promptarg != NULL) { - PyObject *stringpo; - PyObject *stdout_encoding; - stdout_encoding = PyObject_GetAttrString(fout, - "encoding"); - if (stdout_encoding == NULL) { - Py_DECREF(stdin_encoding); - return NULL; - } - stringpo = PyObject_Str(promptarg); - if (stringpo == NULL) { - Py_DECREF(stdin_encoding); - Py_DECREF(stdout_encoding); - return NULL; - } - po = PyUnicode_AsEncodedString(stringpo, - _PyUnicode_AsString(stdout_encoding), NULL); - Py_DECREF(stdout_encoding); - Py_DECREF(stringpo); - if (po == NULL) { - Py_DECREF(stdin_encoding); - return NULL; - } - prompt = PyBytes_AsString(po); - if (prompt == NULL) { - Py_DECREF(stdin_encoding); - Py_DECREF(po); - return NULL; - } - } - else { - po = NULL; - prompt = ""; - } - s = PyOS_Readline(stdin, stdout, prompt); - Py_XDECREF(po); - if (s == NULL) { - if (!PyErr_Occurred()) - PyErr_SetNone(PyExc_KeyboardInterrupt); - Py_DECREF(stdin_encoding); - return NULL; - } - if (*s == '\0') { - PyErr_SetNone(PyExc_EOFError); - result = NULL; - } - else { /* strip trailing '\n' */ - size_t len = strlen(s); - if (len > PY_SSIZE_T_MAX) { - PyErr_SetString(PyExc_OverflowError, - "input: input too long"); - result = NULL; - } - else { - result = PyUnicode_Decode - (s, len-1, - _PyUnicode_AsString(stdin_encoding), - NULL); - } - } - Py_DECREF(stdin_encoding); - PyMem_FREE(s); - return result; - } - - /* Fallback if we're not interactive */ - if (promptarg != NULL) { - if (PyFile_WriteObject(promptarg, fout, Py_PRINT_RAW) != 0) - return NULL; - } - tmp = PyObject_CallMethod(fout, "flush", ""); - if (tmp == NULL) - PyErr_Clear(); - else - Py_DECREF(tmp); - return PyFile_GetLine(fin, -1); + PyObject *promptarg = NULL; + PyObject *fin = PySys_GetObject("stdin"); + PyObject *fout = PySys_GetObject("stdout"); + PyObject *ferr = PySys_GetObject("stderr"); + PyObject *tmp; + long fd; + int tty; + + /* Parse arguments */ + if (!PyArg_UnpackTuple(args, "input", 0, 1, &promptarg)) + return NULL; + + /* Check that stdin/out/err are intact */ + if (fin == NULL || fin == Py_None) { + PyErr_SetString(PyExc_RuntimeError, + "input(): lost sys.stdin"); + return NULL; + } + if (fout == NULL || fout == Py_None) { + PyErr_SetString(PyExc_RuntimeError, + "input(): lost sys.stdout"); + return NULL; + } + if (ferr == NULL || ferr == Py_None) { + PyErr_SetString(PyExc_RuntimeError, + "input(): lost sys.stderr"); + return NULL; + } + + /* First of all, flush stderr */ + tmp = PyObject_CallMethod(ferr, "flush", ""); + if (tmp == NULL) + PyErr_Clear(); + else + Py_DECREF(tmp); + + /* We should only use (GNU) readline if Python's sys.stdin and + sys.stdout are the same as C's stdin and stdout, because we + need to pass it those. */ + tmp = PyObject_CallMethod(fin, "fileno", ""); + if (tmp == NULL) { + PyErr_Clear(); + tty = 0; + } + else { + fd = PyLong_AsLong(tmp); + Py_DECREF(tmp); + if (fd < 0 && PyErr_Occurred()) + return NULL; + tty = fd == fileno(stdin) && isatty(fd); + } + if (tty) { + tmp = PyObject_CallMethod(fout, "fileno", ""); + if (tmp == NULL) + PyErr_Clear(); + else { + fd = PyLong_AsLong(tmp); + Py_DECREF(tmp); + if (fd < 0 && PyErr_Occurred()) + return NULL; + tty = fd == fileno(stdout) && isatty(fd); + } + } + + /* If we're interactive, use (GNU) readline */ + if (tty) { + PyObject *po; + char *prompt; + char *s; + PyObject *stdin_encoding; + PyObject *result; + + stdin_encoding = PyObject_GetAttrString(fin, "encoding"); + if (!stdin_encoding) + /* stdin is a text stream, so it must have an + encoding. */ + return NULL; + tmp = PyObject_CallMethod(fout, "flush", ""); + if (tmp == NULL) + PyErr_Clear(); + else + Py_DECREF(tmp); + if (promptarg != NULL) { + PyObject *stringpo; + PyObject *stdout_encoding; + stdout_encoding = PyObject_GetAttrString(fout, + "encoding"); + if (stdout_encoding == NULL) { + Py_DECREF(stdin_encoding); + return NULL; + } + stringpo = PyObject_Str(promptarg); + if (stringpo == NULL) { + Py_DECREF(stdin_encoding); + Py_DECREF(stdout_encoding); + return NULL; + } + po = PyUnicode_AsEncodedString(stringpo, + _PyUnicode_AsString(stdout_encoding), NULL); + Py_DECREF(stdout_encoding); + Py_DECREF(stringpo); + if (po == NULL) { + Py_DECREF(stdin_encoding); + return NULL; + } + prompt = PyBytes_AsString(po); + if (prompt == NULL) { + Py_DECREF(stdin_encoding); + Py_DECREF(po); + return NULL; + } + } + else { + po = NULL; + prompt = ""; + } + s = PyOS_Readline(stdin, stdout, prompt); + Py_XDECREF(po); + if (s == NULL) { + if (!PyErr_Occurred()) + PyErr_SetNone(PyExc_KeyboardInterrupt); + Py_DECREF(stdin_encoding); + return NULL; + } + if (*s == '\0') { + PyErr_SetNone(PyExc_EOFError); + result = NULL; + } + else { /* strip trailing '\n' */ + size_t len = strlen(s); + if (len > PY_SSIZE_T_MAX) { + PyErr_SetString(PyExc_OverflowError, + "input: input too long"); + result = NULL; + } + else { + result = PyUnicode_Decode + (s, len-1, + _PyUnicode_AsString(stdin_encoding), + NULL); + } + } + Py_DECREF(stdin_encoding); + PyMem_FREE(s); + return result; + } + + /* Fallback if we're not interactive */ + if (promptarg != NULL) { + if (PyFile_WriteObject(promptarg, fout, Py_PRINT_RAW) != 0) + return NULL; + } + tmp = PyObject_CallMethod(fout, "flush", ""); + if (tmp == NULL) + PyErr_Clear(); + else + Py_DECREF(tmp); + return PyFile_GetLine(fin, -1); } PyDoc_STRVAR(input_doc, @@ -1699,7 +1699,7 @@ static PyObject * builtin_repr(PyObject *self, PyObject *v) { - return PyObject_Repr(v); + return PyObject_Repr(v); } PyDoc_STRVAR(repr_doc, @@ -1712,38 +1712,38 @@ static PyObject * builtin_round(PyObject *self, PyObject *args, PyObject *kwds) { - static PyObject *round_str = NULL; - PyObject *ndigits = NULL; - static char *kwlist[] = {"number", "ndigits", 0}; - PyObject *number, *round; - - if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|O:round", - kwlist, &number, &ndigits)) - return NULL; - - if (Py_TYPE(number)->tp_dict == NULL) { - if (PyType_Ready(Py_TYPE(number)) < 0) - return NULL; - } - - if (round_str == NULL) { - round_str = PyUnicode_InternFromString("__round__"); - if (round_str == NULL) - return NULL; - } - - round = _PyType_Lookup(Py_TYPE(number), round_str); - if (round == NULL) { - PyErr_Format(PyExc_TypeError, - "type %.100s doesn't define __round__ method", - Py_TYPE(number)->tp_name); - return NULL; - } - - if (ndigits == NULL) - return PyObject_CallFunction(round, "O", number); - else - return PyObject_CallFunction(round, "OO", number, ndigits); + static PyObject *round_str = NULL; + PyObject *ndigits = NULL; + static char *kwlist[] = {"number", "ndigits", 0}; + PyObject *number, *round; + + if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|O:round", + kwlist, &number, &ndigits)) + return NULL; + + if (Py_TYPE(number)->tp_dict == NULL) { + if (PyType_Ready(Py_TYPE(number)) < 0) + return NULL; + } + + if (round_str == NULL) { + round_str = PyUnicode_InternFromString("__round__"); + if (round_str == NULL) + return NULL; + } + + round = _PyType_Lookup(Py_TYPE(number), round_str); + if (round == NULL) { + PyErr_Format(PyExc_TypeError, + "type %.100s doesn't define __round__ method", + Py_TYPE(number)->tp_name); + return NULL; + } + + if (ndigits == NULL) + return PyObject_CallFunction(round, "O", number); + else + return PyObject_CallFunction(round, "OO", number, ndigits); } PyDoc_STRVAR(round_doc, @@ -1757,42 +1757,42 @@ static PyObject * builtin_sorted(PyObject *self, PyObject *args, PyObject *kwds) { - PyObject *newlist, *v, *seq, *keyfunc=NULL, *newargs; - PyObject *callable; - static char *kwlist[] = {"iterable", "key", "reverse", 0}; - int reverse; - - /* args 1-3 should match listsort in Objects/listobject.c */ - if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|Oi:sorted", - kwlist, &seq, &keyfunc, &reverse)) - return NULL; - - newlist = PySequence_List(seq); - if (newlist == NULL) - return NULL; - - callable = PyObject_GetAttrString(newlist, "sort"); - if (callable == NULL) { - Py_DECREF(newlist); - return NULL; - } - - newargs = PyTuple_GetSlice(args, 1, 4); - if (newargs == NULL) { - Py_DECREF(newlist); - Py_DECREF(callable); - return NULL; - } - - v = PyObject_Call(callable, newargs, kwds); - Py_DECREF(newargs); - Py_DECREF(callable); - if (v == NULL) { - Py_DECREF(newlist); - return NULL; - } - Py_DECREF(v); - return newlist; + PyObject *newlist, *v, *seq, *keyfunc=NULL, *newargs; + PyObject *callable; + static char *kwlist[] = {"iterable", "key", "reverse", 0}; + int reverse; + + /* args 1-3 should match listsort in Objects/listobject.c */ + if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|Oi:sorted", + kwlist, &seq, &keyfunc, &reverse)) + return NULL; + + newlist = PySequence_List(seq); + if (newlist == NULL) + return NULL; + + callable = PyObject_GetAttrString(newlist, "sort"); + if (callable == NULL) { + Py_DECREF(newlist); + return NULL; + } + + newargs = PyTuple_GetSlice(args, 1, 4); + if (newargs == NULL) { + Py_DECREF(newlist); + Py_DECREF(callable); + return NULL; + } + + v = PyObject_Call(callable, newargs, kwds); + Py_DECREF(newargs); + Py_DECREF(callable); + if (v == NULL) { + Py_DECREF(newlist); + return NULL; + } + Py_DECREF(v); + return newlist; } PyDoc_STRVAR(sorted_doc, @@ -1801,30 +1801,30 @@ static PyObject * builtin_vars(PyObject *self, PyObject *args) { - PyObject *v = NULL; - PyObject *d; + PyObject *v = NULL; + PyObject *d; - if (!PyArg_UnpackTuple(args, "vars", 0, 1, &v)) - return NULL; - if (v == NULL) { - d = PyEval_GetLocals(); - if (d == NULL) { - if (!PyErr_Occurred()) - PyErr_SetString(PyExc_SystemError, - "vars(): no locals!?"); - } - else - Py_INCREF(d); - } - else { - d = PyObject_GetAttrString(v, "__dict__"); - if (d == NULL) { - PyErr_SetString(PyExc_TypeError, - "vars() argument must have __dict__ attribute"); - return NULL; - } - } - return d; + if (!PyArg_UnpackTuple(args, "vars", 0, 1, &v)) + return NULL; + if (v == NULL) { + d = PyEval_GetLocals(); + if (d == NULL) { + if (!PyErr_Occurred()) + PyErr_SetString(PyExc_SystemError, + "vars(): no locals!?"); + } + else + Py_INCREF(d); + } + else { + d = PyObject_GetAttrString(v, "__dict__"); + if (d == NULL) { + PyErr_SetString(PyExc_TypeError, + "vars() argument must have __dict__ attribute"); + return NULL; + } + } + return d; } PyDoc_STRVAR(vars_doc, @@ -1836,147 +1836,147 @@ static PyObject* builtin_sum(PyObject *self, PyObject *args) { - PyObject *seq; - PyObject *result = NULL; - PyObject *temp, *item, *iter; - - if (!PyArg_UnpackTuple(args, "sum", 1, 2, &seq, &result)) - return NULL; - - iter = PyObject_GetIter(seq); - if (iter == NULL) - return NULL; - - if (result == NULL) { - result = PyLong_FromLong(0); - if (result == NULL) { - Py_DECREF(iter); - return NULL; - } - } else { - /* reject string values for 'start' parameter */ - if (PyUnicode_Check(result)) { - PyErr_SetString(PyExc_TypeError, - "sum() can't sum strings [use ''.join(seq) instead]"); - Py_DECREF(iter); - return NULL; - } - if (PyByteArray_Check(result)) { - PyErr_SetString(PyExc_TypeError, - "sum() can't sum bytes [use b''.join(seq) instead]"); - Py_DECREF(iter); - return NULL; - } + PyObject *seq; + PyObject *result = NULL; + PyObject *temp, *item, *iter; - Py_INCREF(result); - } + if (!PyArg_UnpackTuple(args, "sum", 1, 2, &seq, &result)) + return NULL; + + iter = PyObject_GetIter(seq); + if (iter == NULL) + return NULL; + + if (result == NULL) { + result = PyLong_FromLong(0); + if (result == NULL) { + Py_DECREF(iter); + return NULL; + } + } else { + /* reject string values for 'start' parameter */ + if (PyUnicode_Check(result)) { + PyErr_SetString(PyExc_TypeError, + "sum() can't sum strings [use ''.join(seq) instead]"); + Py_DECREF(iter); + return NULL; + } + if (PyByteArray_Check(result)) { + PyErr_SetString(PyExc_TypeError, + "sum() can't sum bytes [use b''.join(seq) instead]"); + Py_DECREF(iter); + return NULL; + } + + Py_INCREF(result); + } #ifndef SLOW_SUM - /* Fast addition by keeping temporary sums in C instead of new Python objects. - Assumes all inputs are the same type. If the assumption fails, default - to the more general routine. - */ - if (PyLong_CheckExact(result)) { - int overflow; - long i_result = PyLong_AsLongAndOverflow(result, &overflow); - /* If this already overflowed, don't even enter the loop. */ - if (overflow == 0) { - Py_DECREF(result); - result = NULL; - } - while(result == NULL) { - item = PyIter_Next(iter); - if (item == NULL) { - Py_DECREF(iter); - if (PyErr_Occurred()) - return NULL; - return PyLong_FromLong(i_result); - } - if (PyLong_CheckExact(item)) { - long b = PyLong_AsLongAndOverflow(item, &overflow); - long x = i_result + b; - if (overflow == 0 && ((x^i_result) >= 0 || (x^b) >= 0)) { - i_result = x; - Py_DECREF(item); - continue; - } - } - /* Either overflowed or is not an int. Restore real objects and process normally */ - result = PyLong_FromLong(i_result); - temp = PyNumber_Add(result, item); - Py_DECREF(result); - Py_DECREF(item); - result = temp; - if (result == NULL) { - Py_DECREF(iter); - return NULL; - } - } - } - - if (PyFloat_CheckExact(result)) { - double f_result = PyFloat_AS_DOUBLE(result); - Py_DECREF(result); - result = NULL; - while(result == NULL) { - item = PyIter_Next(iter); - if (item == NULL) { - Py_DECREF(iter); - if (PyErr_Occurred()) - return NULL; - return PyFloat_FromDouble(f_result); - } - if (PyFloat_CheckExact(item)) { - PyFPE_START_PROTECT("add", Py_DECREF(item); Py_DECREF(iter); return 0) - f_result += PyFloat_AS_DOUBLE(item); - PyFPE_END_PROTECT(f_result) - Py_DECREF(item); - continue; - } - if (PyLong_CheckExact(item)) { - long value; - int overflow; - value = PyLong_AsLongAndOverflow(item, &overflow); - if (!overflow) { - PyFPE_START_PROTECT("add", Py_DECREF(item); Py_DECREF(iter); return 0) - f_result += (double)value; - PyFPE_END_PROTECT(f_result) - Py_DECREF(item); - continue; - } - } - result = PyFloat_FromDouble(f_result); - temp = PyNumber_Add(result, item); - Py_DECREF(result); - Py_DECREF(item); - result = temp; - if (result == NULL) { - Py_DECREF(iter); - return NULL; - } - } - } + /* Fast addition by keeping temporary sums in C instead of new Python objects. + Assumes all inputs are the same type. If the assumption fails, default + to the more general routine. + */ + if (PyLong_CheckExact(result)) { + int overflow; + long i_result = PyLong_AsLongAndOverflow(result, &overflow); + /* If this already overflowed, don't even enter the loop. */ + if (overflow == 0) { + Py_DECREF(result); + result = NULL; + } + while(result == NULL) { + item = PyIter_Next(iter); + if (item == NULL) { + Py_DECREF(iter); + if (PyErr_Occurred()) + return NULL; + return PyLong_FromLong(i_result); + } + if (PyLong_CheckExact(item)) { + long b = PyLong_AsLongAndOverflow(item, &overflow); + long x = i_result + b; + if (overflow == 0 && ((x^i_result) >= 0 || (x^b) >= 0)) { + i_result = x; + Py_DECREF(item); + continue; + } + } + /* Either overflowed or is not an int. Restore real objects and process normally */ + result = PyLong_FromLong(i_result); + temp = PyNumber_Add(result, item); + Py_DECREF(result); + Py_DECREF(item); + result = temp; + if (result == NULL) { + Py_DECREF(iter); + return NULL; + } + } + } + + if (PyFloat_CheckExact(result)) { + double f_result = PyFloat_AS_DOUBLE(result); + Py_DECREF(result); + result = NULL; + while(result == NULL) { + item = PyIter_Next(iter); + if (item == NULL) { + Py_DECREF(iter); + if (PyErr_Occurred()) + return NULL; + return PyFloat_FromDouble(f_result); + } + if (PyFloat_CheckExact(item)) { + PyFPE_START_PROTECT("add", Py_DECREF(item); Py_DECREF(iter); return 0) + f_result += PyFloat_AS_DOUBLE(item); + PyFPE_END_PROTECT(f_result) + Py_DECREF(item); + continue; + } + if (PyLong_CheckExact(item)) { + long value; + int overflow; + value = PyLong_AsLongAndOverflow(item, &overflow); + if (!overflow) { + PyFPE_START_PROTECT("add", Py_DECREF(item); Py_DECREF(iter); return 0) + f_result += (double)value; + PyFPE_END_PROTECT(f_result) + Py_DECREF(item); + continue; + } + } + result = PyFloat_FromDouble(f_result); + temp = PyNumber_Add(result, item); + Py_DECREF(result); + Py_DECREF(item); + result = temp; + if (result == NULL) { + Py_DECREF(iter); + return NULL; + } + } + } #endif - for(;;) { - item = PyIter_Next(iter); - if (item == NULL) { - /* error, or end-of-sequence */ - if (PyErr_Occurred()) { - Py_DECREF(result); - result = NULL; - } - break; - } - temp = PyNumber_Add(result, item); - Py_DECREF(result); - Py_DECREF(item); - result = temp; - if (result == NULL) - break; - } - Py_DECREF(iter); - return result; + for(;;) { + item = PyIter_Next(iter); + if (item == NULL) { + /* error, or end-of-sequence */ + if (PyErr_Occurred()) { + Py_DECREF(result); + result = NULL; + } + break; + } + temp = PyNumber_Add(result, item); + Py_DECREF(result); + Py_DECREF(item); + result = temp; + if (result == NULL) + break; + } + Py_DECREF(iter); + return result; } PyDoc_STRVAR(sum_doc, @@ -1990,17 +1990,17 @@ static PyObject * builtin_isinstance(PyObject *self, PyObject *args) { - PyObject *inst; - PyObject *cls; - int retval; - - if (!PyArg_UnpackTuple(args, "isinstance", 2, 2, &inst, &cls)) - return NULL; - - retval = PyObject_IsInstance(inst, cls); - if (retval < 0) - return NULL; - return PyBool_FromLong(retval); + PyObject *inst; + PyObject *cls; + int retval; + + if (!PyArg_UnpackTuple(args, "isinstance", 2, 2, &inst, &cls)) + return NULL; + + retval = PyObject_IsInstance(inst, cls); + if (retval < 0) + return NULL; + return PyBool_FromLong(retval); } PyDoc_STRVAR(isinstance_doc, @@ -2015,17 +2015,17 @@ static PyObject * builtin_issubclass(PyObject *self, PyObject *args) { - PyObject *derived; - PyObject *cls; - int retval; - - if (!PyArg_UnpackTuple(args, "issubclass", 2, 2, &derived, &cls)) - return NULL; - - retval = PyObject_IsSubclass(derived, cls); - if (retval < 0) - return NULL; - return PyBool_FromLong(retval); + PyObject *derived; + PyObject *cls; + int retval; + + if (!PyArg_UnpackTuple(args, "issubclass", 2, 2, &derived, &cls)) + return NULL; + + retval = PyObject_IsSubclass(derived, cls); + if (retval < 0) + return NULL; + return PyBool_FromLong(retval); } PyDoc_STRVAR(issubclass_doc, @@ -2037,127 +2037,127 @@ typedef struct { - PyObject_HEAD - Py_ssize_t tuplesize; - PyObject *ittuple; /* tuple of iterators */ - PyObject *result; + PyObject_HEAD + Py_ssize_t tuplesize; + PyObject *ittuple; /* tuple of iterators */ + PyObject *result; } zipobject; static PyObject * zip_new(PyTypeObject *type, PyObject *args, PyObject *kwds) { - zipobject *lz; - Py_ssize_t i; - PyObject *ittuple; /* tuple of iterators */ - PyObject *result; - Py_ssize_t tuplesize = PySequence_Length(args); - - if (type == &PyZip_Type && !_PyArg_NoKeywords("zip()", kwds)) - return NULL; - - /* args must be a tuple */ - assert(PyTuple_Check(args)); - - /* obtain iterators */ - ittuple = PyTuple_New(tuplesize); - if (ittuple == NULL) - return NULL; - for (i=0; i < tuplesize; ++i) { - PyObject *item = PyTuple_GET_ITEM(args, i); - PyObject *it = PyObject_GetIter(item); - if (it == NULL) { - if (PyErr_ExceptionMatches(PyExc_TypeError)) - PyErr_Format(PyExc_TypeError, - "zip argument #%zd must support iteration", - i+1); - Py_DECREF(ittuple); - return NULL; - } - PyTuple_SET_ITEM(ittuple, i, it); - } - - /* create a result holder */ - result = PyTuple_New(tuplesize); - if (result == NULL) { - Py_DECREF(ittuple); - return NULL; - } - for (i=0 ; i < tuplesize ; i++) { - Py_INCREF(Py_None); - PyTuple_SET_ITEM(result, i, Py_None); - } - - /* create zipobject structure */ - lz = (zipobject *)type->tp_alloc(type, 0); - if (lz == NULL) { - Py_DECREF(ittuple); - Py_DECREF(result); - return NULL; - } - lz->ittuple = ittuple; - lz->tuplesize = tuplesize; - lz->result = result; + zipobject *lz; + Py_ssize_t i; + PyObject *ittuple; /* tuple of iterators */ + PyObject *result; + Py_ssize_t tuplesize = PySequence_Length(args); + + if (type == &PyZip_Type && !_PyArg_NoKeywords("zip()", kwds)) + return NULL; + + /* args must be a tuple */ + assert(PyTuple_Check(args)); - return (PyObject *)lz; + /* obtain iterators */ + ittuple = PyTuple_New(tuplesize); + if (ittuple == NULL) + return NULL; + for (i=0; i < tuplesize; ++i) { + PyObject *item = PyTuple_GET_ITEM(args, i); + PyObject *it = PyObject_GetIter(item); + if (it == NULL) { + if (PyErr_ExceptionMatches(PyExc_TypeError)) + PyErr_Format(PyExc_TypeError, + "zip argument #%zd must support iteration", + i+1); + Py_DECREF(ittuple); + return NULL; + } + PyTuple_SET_ITEM(ittuple, i, it); + } + + /* create a result holder */ + result = PyTuple_New(tuplesize); + if (result == NULL) { + Py_DECREF(ittuple); + return NULL; + } + for (i=0 ; i < tuplesize ; i++) { + Py_INCREF(Py_None); + PyTuple_SET_ITEM(result, i, Py_None); + } + + /* create zipobject structure */ + lz = (zipobject *)type->tp_alloc(type, 0); + if (lz == NULL) { + Py_DECREF(ittuple); + Py_DECREF(result); + return NULL; + } + lz->ittuple = ittuple; + lz->tuplesize = tuplesize; + lz->result = result; + + return (PyObject *)lz; } static void zip_dealloc(zipobject *lz) { - PyObject_GC_UnTrack(lz); - Py_XDECREF(lz->ittuple); - Py_XDECREF(lz->result); - Py_TYPE(lz)->tp_free(lz); + PyObject_GC_UnTrack(lz); + Py_XDECREF(lz->ittuple); + Py_XDECREF(lz->result); + Py_TYPE(lz)->tp_free(lz); } static int zip_traverse(zipobject *lz, visitproc visit, void *arg) { - Py_VISIT(lz->ittuple); - Py_VISIT(lz->result); - return 0; + Py_VISIT(lz->ittuple); + Py_VISIT(lz->result); + return 0; } static PyObject * zip_next(zipobject *lz) { - Py_ssize_t i; - Py_ssize_t tuplesize = lz->tuplesize; - PyObject *result = lz->result; - PyObject *it; - PyObject *item; - PyObject *olditem; - - if (tuplesize == 0) - return NULL; - if (Py_REFCNT(result) == 1) { - Py_INCREF(result); - for (i=0 ; i < tuplesize ; i++) { - it = PyTuple_GET_ITEM(lz->ittuple, i); - item = (*Py_TYPE(it)->tp_iternext)(it); - if (item == NULL) { - Py_DECREF(result); - return NULL; - } - olditem = PyTuple_GET_ITEM(result, i); - PyTuple_SET_ITEM(result, i, item); - Py_DECREF(olditem); - } - } else { - result = PyTuple_New(tuplesize); - if (result == NULL) - return NULL; - for (i=0 ; i < tuplesize ; i++) { - it = PyTuple_GET_ITEM(lz->ittuple, i); - item = (*Py_TYPE(it)->tp_iternext)(it); - if (item == NULL) { - Py_DECREF(result); - return NULL; - } - PyTuple_SET_ITEM(result, i, item); - } - } - return result; + Py_ssize_t i; + Py_ssize_t tuplesize = lz->tuplesize; + PyObject *result = lz->result; + PyObject *it; + PyObject *item; + PyObject *olditem; + + if (tuplesize == 0) + return NULL; + if (Py_REFCNT(result) == 1) { + Py_INCREF(result); + for (i=0 ; i < tuplesize ; i++) { + it = PyTuple_GET_ITEM(lz->ittuple, i); + item = (*Py_TYPE(it)->tp_iternext)(it); + if (item == NULL) { + Py_DECREF(result); + return NULL; + } + olditem = PyTuple_GET_ITEM(result, i); + PyTuple_SET_ITEM(result, i, item); + Py_DECREF(olditem); + } + } else { + result = PyTuple_New(tuplesize); + if (result == NULL) + return NULL; + for (i=0 ; i < tuplesize ; i++) { + it = PyTuple_GET_ITEM(lz->ittuple, i); + item = (*Py_TYPE(it)->tp_iternext)(it); + if (item == NULL) { + Py_DECREF(result); + return NULL; + } + PyTuple_SET_ITEM(result, i, item); + } + } + return result; } PyDoc_STRVAR(zip_doc, @@ -2169,93 +2169,93 @@ is exhausted and then it raises StopIteration."); PyTypeObject PyZip_Type = { - PyVarObject_HEAD_INIT(&PyType_Type, 0) - "zip", /* tp_name */ - sizeof(zipobject), /* tp_basicsize */ - 0, /* tp_itemsize */ - /* methods */ - (destructor)zip_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 | - Py_TPFLAGS_BASETYPE, /* tp_flags */ - zip_doc, /* tp_doc */ - (traverseproc)zip_traverse, /* tp_traverse */ - 0, /* tp_clear */ - 0, /* tp_richcompare */ - 0, /* tp_weaklistoffset */ - PyObject_SelfIter, /* tp_iter */ - (iternextfunc)zip_next, /* tp_iternext */ - 0, /* tp_methods */ - 0, /* tp_members */ - 0, /* tp_getset */ - 0, /* tp_base */ - 0, /* tp_dict */ - 0, /* tp_descr_get */ - 0, /* tp_descr_set */ - 0, /* tp_dictoffset */ - 0, /* tp_init */ - PyType_GenericAlloc, /* tp_alloc */ - zip_new, /* tp_new */ - PyObject_GC_Del, /* tp_free */ + PyVarObject_HEAD_INIT(&PyType_Type, 0) + "zip", /* tp_name */ + sizeof(zipobject), /* tp_basicsize */ + 0, /* tp_itemsize */ + /* methods */ + (destructor)zip_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 | + Py_TPFLAGS_BASETYPE, /* tp_flags */ + zip_doc, /* tp_doc */ + (traverseproc)zip_traverse, /* tp_traverse */ + 0, /* tp_clear */ + 0, /* tp_richcompare */ + 0, /* tp_weaklistoffset */ + PyObject_SelfIter, /* tp_iter */ + (iternextfunc)zip_next, /* tp_iternext */ + 0, /* tp_methods */ + 0, /* tp_members */ + 0, /* tp_getset */ + 0, /* tp_base */ + 0, /* tp_dict */ + 0, /* tp_descr_get */ + 0, /* tp_descr_set */ + 0, /* tp_dictoffset */ + 0, /* tp_init */ + PyType_GenericAlloc, /* tp_alloc */ + zip_new, /* tp_new */ + PyObject_GC_Del, /* tp_free */ }; static PyMethodDef builtin_methods[] = { - {"__build_class__", (PyCFunction)builtin___build_class__, - METH_VARARGS | METH_KEYWORDS, build_class_doc}, - {"__import__", (PyCFunction)builtin___import__, METH_VARARGS | METH_KEYWORDS, import_doc}, - {"abs", builtin_abs, METH_O, abs_doc}, - {"all", builtin_all, METH_O, all_doc}, - {"any", builtin_any, METH_O, any_doc}, - {"ascii", builtin_ascii, METH_O, ascii_doc}, - {"bin", builtin_bin, METH_O, bin_doc}, - {"chr", builtin_chr, METH_VARARGS, chr_doc}, - {"compile", (PyCFunction)builtin_compile, METH_VARARGS | METH_KEYWORDS, compile_doc}, - {"delattr", builtin_delattr, METH_VARARGS, delattr_doc}, - {"dir", builtin_dir, METH_VARARGS, dir_doc}, - {"divmod", builtin_divmod, METH_VARARGS, divmod_doc}, - {"eval", builtin_eval, METH_VARARGS, eval_doc}, - {"exec", builtin_exec, METH_VARARGS, exec_doc}, - {"format", builtin_format, METH_VARARGS, format_doc}, - {"getattr", builtin_getattr, METH_VARARGS, getattr_doc}, - {"globals", (PyCFunction)builtin_globals, METH_NOARGS, globals_doc}, - {"hasattr", builtin_hasattr, METH_VARARGS, hasattr_doc}, - {"hash", builtin_hash, METH_O, hash_doc}, - {"hex", builtin_hex, METH_O, hex_doc}, - {"id", builtin_id, METH_O, id_doc}, - {"input", builtin_input, METH_VARARGS, input_doc}, - {"isinstance", builtin_isinstance, METH_VARARGS, isinstance_doc}, - {"issubclass", builtin_issubclass, METH_VARARGS, issubclass_doc}, - {"iter", builtin_iter, METH_VARARGS, iter_doc}, - {"len", builtin_len, METH_O, len_doc}, - {"locals", (PyCFunction)builtin_locals, METH_NOARGS, locals_doc}, - {"max", (PyCFunction)builtin_max, METH_VARARGS | METH_KEYWORDS, max_doc}, - {"min", (PyCFunction)builtin_min, METH_VARARGS | METH_KEYWORDS, min_doc}, - {"next", (PyCFunction)builtin_next, METH_VARARGS, next_doc}, - {"oct", builtin_oct, METH_O, oct_doc}, - {"ord", builtin_ord, METH_O, ord_doc}, - {"pow", builtin_pow, METH_VARARGS, pow_doc}, - {"print", (PyCFunction)builtin_print, METH_VARARGS | METH_KEYWORDS, print_doc}, - {"repr", builtin_repr, METH_O, repr_doc}, - {"round", (PyCFunction)builtin_round, METH_VARARGS | METH_KEYWORDS, round_doc}, - {"setattr", builtin_setattr, METH_VARARGS, setattr_doc}, - {"sorted", (PyCFunction)builtin_sorted, METH_VARARGS | METH_KEYWORDS, sorted_doc}, - {"sum", builtin_sum, METH_VARARGS, sum_doc}, - {"vars", builtin_vars, METH_VARARGS, vars_doc}, - {NULL, NULL}, + {"__build_class__", (PyCFunction)builtin___build_class__, + METH_VARARGS | METH_KEYWORDS, build_class_doc}, + {"__import__", (PyCFunction)builtin___import__, METH_VARARGS | METH_KEYWORDS, import_doc}, + {"abs", builtin_abs, METH_O, abs_doc}, + {"all", builtin_all, METH_O, all_doc}, + {"any", builtin_any, METH_O, any_doc}, + {"ascii", builtin_ascii, METH_O, ascii_doc}, + {"bin", builtin_bin, METH_O, bin_doc}, + {"chr", builtin_chr, METH_VARARGS, chr_doc}, + {"compile", (PyCFunction)builtin_compile, METH_VARARGS | METH_KEYWORDS, compile_doc}, + {"delattr", builtin_delattr, METH_VARARGS, delattr_doc}, + {"dir", builtin_dir, METH_VARARGS, dir_doc}, + {"divmod", builtin_divmod, METH_VARARGS, divmod_doc}, + {"eval", builtin_eval, METH_VARARGS, eval_doc}, + {"exec", builtin_exec, METH_VARARGS, exec_doc}, + {"format", builtin_format, METH_VARARGS, format_doc}, + {"getattr", builtin_getattr, METH_VARARGS, getattr_doc}, + {"globals", (PyCFunction)builtin_globals, METH_NOARGS, globals_doc}, + {"hasattr", builtin_hasattr, METH_VARARGS, hasattr_doc}, + {"hash", builtin_hash, METH_O, hash_doc}, + {"hex", builtin_hex, METH_O, hex_doc}, + {"id", builtin_id, METH_O, id_doc}, + {"input", builtin_input, METH_VARARGS, input_doc}, + {"isinstance", builtin_isinstance, METH_VARARGS, isinstance_doc}, + {"issubclass", builtin_issubclass, METH_VARARGS, issubclass_doc}, + {"iter", builtin_iter, METH_VARARGS, iter_doc}, + {"len", builtin_len, METH_O, len_doc}, + {"locals", (PyCFunction)builtin_locals, METH_NOARGS, locals_doc}, + {"max", (PyCFunction)builtin_max, METH_VARARGS | METH_KEYWORDS, max_doc}, + {"min", (PyCFunction)builtin_min, METH_VARARGS | METH_KEYWORDS, min_doc}, + {"next", (PyCFunction)builtin_next, METH_VARARGS, next_doc}, + {"oct", builtin_oct, METH_O, oct_doc}, + {"ord", builtin_ord, METH_O, ord_doc}, + {"pow", builtin_pow, METH_VARARGS, pow_doc}, + {"print", (PyCFunction)builtin_print, METH_VARARGS | METH_KEYWORDS, print_doc}, + {"repr", builtin_repr, METH_O, repr_doc}, + {"round", (PyCFunction)builtin_round, METH_VARARGS | METH_KEYWORDS, round_doc}, + {"setattr", builtin_setattr, METH_VARARGS, setattr_doc}, + {"sorted", (PyCFunction)builtin_sorted, METH_VARARGS | METH_KEYWORDS, sorted_doc}, + {"sum", builtin_sum, METH_VARARGS, sum_doc}, + {"vars", builtin_vars, METH_VARARGS, vars_doc}, + {NULL, NULL}, }; PyDoc_STRVAR(builtin_doc, @@ -2264,85 +2264,85 @@ Noteworthy: None is the `nil' object; Ellipsis represents `...' in slices."); static struct PyModuleDef builtinsmodule = { - PyModuleDef_HEAD_INIT, - "builtins", - builtin_doc, - -1, /* multiple "initialization" just copies the module dict. */ - builtin_methods, - NULL, - NULL, - NULL, - NULL + PyModuleDef_HEAD_INIT, + "builtins", + builtin_doc, + -1, /* multiple "initialization" just copies the module dict. */ + builtin_methods, + NULL, + NULL, + NULL, + NULL }; PyObject * _PyBuiltin_Init(void) { - PyObject *mod, *dict, *debug; - mod = PyModule_Create(&builtinsmodule); - if (mod == NULL) - return NULL; - dict = PyModule_GetDict(mod); + PyObject *mod, *dict, *debug; + mod = PyModule_Create(&builtinsmodule); + if (mod == NULL) + return NULL; + dict = PyModule_GetDict(mod); #ifdef Py_TRACE_REFS - /* "builtins" exposes a number of statically allocated objects - * that, before this code was added in 2.3, never showed up in - * the list of "all objects" maintained by Py_TRACE_REFS. As a - * result, programs leaking references to None and False (etc) - * couldn't be diagnosed by examining sys.getobjects(0). - */ + /* "builtins" exposes a number of statically allocated objects + * that, before this code was added in 2.3, never showed up in + * the list of "all objects" maintained by Py_TRACE_REFS. As a + * result, programs leaking references to None and False (etc) + * couldn't be diagnosed by examining sys.getobjects(0). + */ #define ADD_TO_ALL(OBJECT) _Py_AddToAllObjects((PyObject *)(OBJECT), 0) #else #define ADD_TO_ALL(OBJECT) (void)0 #endif #define SETBUILTIN(NAME, OBJECT) \ - if (PyDict_SetItemString(dict, NAME, (PyObject *)OBJECT) < 0) \ - return NULL; \ - ADD_TO_ALL(OBJECT) - - SETBUILTIN("None", Py_None); - SETBUILTIN("Ellipsis", Py_Ellipsis); - SETBUILTIN("NotImplemented", Py_NotImplemented); - SETBUILTIN("False", Py_False); - SETBUILTIN("True", Py_True); - SETBUILTIN("bool", &PyBool_Type); - SETBUILTIN("memoryview", &PyMemoryView_Type); - SETBUILTIN("bytearray", &PyByteArray_Type); - SETBUILTIN("bytes", &PyBytes_Type); - SETBUILTIN("classmethod", &PyClassMethod_Type); + if (PyDict_SetItemString(dict, NAME, (PyObject *)OBJECT) < 0) \ + return NULL; \ + ADD_TO_ALL(OBJECT) + + SETBUILTIN("None", Py_None); + SETBUILTIN("Ellipsis", Py_Ellipsis); + SETBUILTIN("NotImplemented", Py_NotImplemented); + SETBUILTIN("False", Py_False); + SETBUILTIN("True", Py_True); + SETBUILTIN("bool", &PyBool_Type); + SETBUILTIN("memoryview", &PyMemoryView_Type); + SETBUILTIN("bytearray", &PyByteArray_Type); + SETBUILTIN("bytes", &PyBytes_Type); + SETBUILTIN("classmethod", &PyClassMethod_Type); #ifndef WITHOUT_COMPLEX - SETBUILTIN("complex", &PyComplex_Type); + SETBUILTIN("complex", &PyComplex_Type); #endif - SETBUILTIN("dict", &PyDict_Type); - SETBUILTIN("enumerate", &PyEnum_Type); - SETBUILTIN("filter", &PyFilter_Type); - SETBUILTIN("float", &PyFloat_Type); - SETBUILTIN("frozenset", &PyFrozenSet_Type); - SETBUILTIN("property", &PyProperty_Type); - SETBUILTIN("int", &PyLong_Type); - SETBUILTIN("list", &PyList_Type); - SETBUILTIN("map", &PyMap_Type); - SETBUILTIN("object", &PyBaseObject_Type); - SETBUILTIN("range", &PyRange_Type); - SETBUILTIN("reversed", &PyReversed_Type); - SETBUILTIN("set", &PySet_Type); - SETBUILTIN("slice", &PySlice_Type); - SETBUILTIN("staticmethod", &PyStaticMethod_Type); - SETBUILTIN("str", &PyUnicode_Type); - SETBUILTIN("super", &PySuper_Type); - SETBUILTIN("tuple", &PyTuple_Type); - SETBUILTIN("type", &PyType_Type); - SETBUILTIN("zip", &PyZip_Type); - debug = PyBool_FromLong(Py_OptimizeFlag == 0); - if (PyDict_SetItemString(dict, "__debug__", debug) < 0) { - Py_XDECREF(debug); - return NULL; - } - Py_XDECREF(debug); + SETBUILTIN("dict", &PyDict_Type); + SETBUILTIN("enumerate", &PyEnum_Type); + SETBUILTIN("filter", &PyFilter_Type); + SETBUILTIN("float", &PyFloat_Type); + SETBUILTIN("frozenset", &PyFrozenSet_Type); + SETBUILTIN("property", &PyProperty_Type); + SETBUILTIN("int", &PyLong_Type); + SETBUILTIN("list", &PyList_Type); + SETBUILTIN("map", &PyMap_Type); + SETBUILTIN("object", &PyBaseObject_Type); + SETBUILTIN("range", &PyRange_Type); + SETBUILTIN("reversed", &PyReversed_Type); + SETBUILTIN("set", &PySet_Type); + SETBUILTIN("slice", &PySlice_Type); + SETBUILTIN("staticmethod", &PyStaticMethod_Type); + SETBUILTIN("str", &PyUnicode_Type); + SETBUILTIN("super", &PySuper_Type); + SETBUILTIN("tuple", &PyTuple_Type); + SETBUILTIN("type", &PyType_Type); + SETBUILTIN("zip", &PyZip_Type); + debug = PyBool_FromLong(Py_OptimizeFlag == 0); + if (PyDict_SetItemString(dict, "__debug__", debug) < 0) { + Py_XDECREF(debug); + return NULL; + } + Py_XDECREF(debug); - return mod; + return mod; #undef ADD_TO_ALL #undef SETBUILTIN } Modified: python/branches/release31-maint/Python/ceval.c ============================================================================== --- python/branches/release31-maint/Python/ceval.c (original) +++ python/branches/release31-maint/Python/ceval.c Sun May 9 18:14:21 2010 @@ -28,27 +28,27 @@ typedef unsigned long long uint64; #if defined(__ppc__) /* <- Don't know if this is the correct symbol; this - section should work for GCC on any PowerPC - platform, irrespective of OS. - POWER? Who knows :-) */ + section should work for GCC on any PowerPC + platform, irrespective of OS. + POWER? Who knows :-) */ #define READ_TIMESTAMP(var) ppc_getcounter(&var) static void ppc_getcounter(uint64 *v) { - register unsigned long tbu, tb, tbu2; + register unsigned long tbu, tb, tbu2; loop: - asm volatile ("mftbu %0" : "=r" (tbu) ); - asm volatile ("mftb %0" : "=r" (tb) ); - asm volatile ("mftbu %0" : "=r" (tbu2)); - if (__builtin_expect(tbu != tbu2, 0)) goto loop; - - /* The slightly peculiar way of writing the next lines is - compiled better by GCC than any other way I tried. */ - ((long*)(v))[0] = tbu; - ((long*)(v))[1] = tb; + asm volatile ("mftbu %0" : "=r" (tbu) ); + asm volatile ("mftb %0" : "=r" (tb) ); + asm volatile ("mftbu %0" : "=r" (tbu2)); + if (__builtin_expect(tbu != tbu2, 0)) goto loop; + + /* The slightly peculiar way of writing the next lines is + compiled better by GCC than any other way I tried. */ + ((long*)(v))[0] = tbu; + ((long*)(v))[1] = tb; } #elif defined(__i386__) @@ -77,17 +77,17 @@ #endif void dump_tsc(int opcode, int ticked, uint64 inst0, uint64 inst1, - uint64 loop0, uint64 loop1, uint64 intr0, uint64 intr1) + uint64 loop0, uint64 loop1, uint64 intr0, uint64 intr1) { - uint64 intr, inst, loop; - PyThreadState *tstate = PyThreadState_Get(); - if (!tstate->interp->tscdump) - return; - intr = intr1 - intr0; - inst = inst1 - inst0 - intr; - loop = loop1 - loop0 - intr; - fprintf(stderr, "opcode=%03d t=%d inst=%06lld loop=%06lld\n", - opcode, ticked, inst, loop); + uint64 intr, inst, loop; + PyThreadState *tstate = PyThreadState_Get(); + if (!tstate->interp->tscdump) + return; + intr = intr1 - intr0; + inst = inst1 - inst0 - intr; + loop = loop1 - loop0 - intr; + fprintf(stderr, "opcode=%03d t=%d inst=%06lld loop=%06lld\n", + opcode, ticked, inst, loop); } #endif @@ -97,8 +97,8 @@ #ifdef Py_DEBUG /* For debugging the interpreter: */ -#define LLTRACE 1 /* Low-level trace feature */ -#define CHECKEXC 1 /* Double-check exception checking */ +#define LLTRACE 1 /* Low-level trace feature */ +#define CHECKEXC 1 /* Double-check exception checking */ #endif typedef PyObject *(*callproc)(PyObject *, PyObject *, PyObject *); @@ -113,7 +113,7 @@ static PyObject * do_call(PyObject *, PyObject ***, int, int); static PyObject * ext_do_call(PyObject *, PyObject ***, int, int, int); static PyObject * update_keyword_args(PyObject *, int, PyObject ***, - PyObject *); + PyObject *); static PyObject * update_star_args(int, int, PyObject *, PyObject ***); static PyObject * load_args(PyObject ***, int); #define CALL_FLAG_VAR 1 @@ -124,12 +124,12 @@ static int prtrace(PyObject *, char *); #endif static int call_trace(Py_tracefunc, PyObject *, PyFrameObject *, - int, PyObject *); + int, PyObject *); static int call_trace_protected(Py_tracefunc, PyObject *, - PyFrameObject *, int, PyObject *); + PyFrameObject *, int, PyObject *); static void call_exc_trace(Py_tracefunc, PyObject *, PyFrameObject *); static int maybe_call_line_trace(Py_tracefunc, PyObject *, - PyFrameObject *, int *, int *, int *); + PyFrameObject *, int *, int *, int *); static PyObject * cmp_outcome(int, PyObject *, PyObject *); static PyObject * import_from(PyObject *, PyObject *); @@ -139,14 +139,14 @@ PyFrameObject *, unsigned char *); #define NAME_ERROR_MSG \ - "name '%.200s' is not defined" + "name '%.200s' is not defined" #define GLOBAL_NAME_ERROR_MSG \ - "global name '%.200s' is not defined" + "global name '%.200s' is not defined" #define UNBOUNDLOCAL_ERROR_MSG \ - "local variable '%.200s' referenced before assignment" + "local variable '%.200s' referenced before assignment" #define UNBOUNDFREE_ERROR_MSG \ - "free variable '%.200s' referenced before assignment" \ - " in enclosing scope" + "free variable '%.200s' referenced before assignment" \ + " in enclosing scope" /* Dynamic execution profile */ #ifdef DYNAMIC_EXECUTION_PROFILE @@ -198,10 +198,10 @@ PyObject * PyEval_GetCallStats(PyObject *self) { - return Py_BuildValue("iiiiiiiiiii", - pcall[0], pcall[1], pcall[2], pcall[3], - pcall[4], pcall[5], pcall[6], pcall[7], - pcall[8], pcall[9], pcall[10]); + return Py_BuildValue("iiiiiiiiiii", + pcall[0], pcall[1], pcall[2], pcall[3], + pcall[4], pcall[5], pcall[6], pcall[7], + pcall[8], pcall[9], pcall[10]); } #else #define PCALL(O) @@ -209,8 +209,8 @@ PyObject * PyEval_GetCallStats(PyObject *self) { - Py_INCREF(Py_None); - return Py_None; + Py_INCREF(Py_None); + return Py_None; } #endif @@ -229,52 +229,52 @@ int PyEval_ThreadsInitialized(void) { - return interpreter_lock != 0; + return interpreter_lock != 0; } void PyEval_InitThreads(void) { - if (interpreter_lock) - return; - interpreter_lock = PyThread_allocate_lock(); - PyThread_acquire_lock(interpreter_lock, 1); - main_thread = PyThread_get_thread_ident(); + if (interpreter_lock) + return; + interpreter_lock = PyThread_allocate_lock(); + PyThread_acquire_lock(interpreter_lock, 1); + main_thread = PyThread_get_thread_ident(); } void PyEval_AcquireLock(void) { - PyThread_acquire_lock(interpreter_lock, 1); + PyThread_acquire_lock(interpreter_lock, 1); } void PyEval_ReleaseLock(void) { - PyThread_release_lock(interpreter_lock); + PyThread_release_lock(interpreter_lock); } void PyEval_AcquireThread(PyThreadState *tstate) { - if (tstate == NULL) - Py_FatalError("PyEval_AcquireThread: NULL new thread state"); - /* Check someone has called PyEval_InitThreads() to create the lock */ - assert(interpreter_lock); - PyThread_acquire_lock(interpreter_lock, 1); - if (PyThreadState_Swap(tstate) != NULL) - Py_FatalError( - "PyEval_AcquireThread: non-NULL old thread state"); + if (tstate == NULL) + Py_FatalError("PyEval_AcquireThread: NULL new thread state"); + /* Check someone has called PyEval_InitThreads() to create the lock */ + assert(interpreter_lock); + PyThread_acquire_lock(interpreter_lock, 1); + if (PyThreadState_Swap(tstate) != NULL) + Py_FatalError( + "PyEval_AcquireThread: non-NULL old thread state"); } void PyEval_ReleaseThread(PyThreadState *tstate) { - if (tstate == NULL) - Py_FatalError("PyEval_ReleaseThread: NULL thread state"); - if (PyThreadState_Swap(NULL) != tstate) - Py_FatalError("PyEval_ReleaseThread: wrong thread state"); - PyThread_release_lock(interpreter_lock); + if (tstate == NULL) + Py_FatalError("PyEval_ReleaseThread: NULL thread state"); + if (PyThreadState_Swap(NULL) != tstate) + Py_FatalError("PyEval_ReleaseThread: wrong thread state"); + PyThread_release_lock(interpreter_lock); } /* This function is called from PyOS_AfterFork to ensure that newly @@ -285,36 +285,36 @@ void PyEval_ReInitThreads(void) { - PyObject *threading, *result; - PyThreadState *tstate; + PyObject *threading, *result; + PyThreadState *tstate; - if (!interpreter_lock) - return; - /*XXX Can't use PyThread_free_lock here because it does too - much error-checking. Doing this cleanly would require - adding a new function to each thread_*.h. Instead, just - create a new lock and waste a little bit of memory */ - interpreter_lock = PyThread_allocate_lock(); - pending_lock = PyThread_allocate_lock(); - PyThread_acquire_lock(interpreter_lock, 1); - main_thread = PyThread_get_thread_ident(); - - /* Update the threading module with the new state. - */ - tstate = PyThreadState_GET(); - threading = PyMapping_GetItemString(tstate->interp->modules, - "threading"); - if (threading == NULL) { - /* threading not imported */ - PyErr_Clear(); - return; - } - result = PyObject_CallMethod(threading, "_after_fork", NULL); - if (result == NULL) - PyErr_WriteUnraisable(threading); - else - Py_DECREF(result); - Py_DECREF(threading); + if (!interpreter_lock) + return; + /*XXX Can't use PyThread_free_lock here because it does too + much error-checking. Doing this cleanly would require + adding a new function to each thread_*.h. Instead, just + create a new lock and waste a little bit of memory */ + interpreter_lock = PyThread_allocate_lock(); + pending_lock = PyThread_allocate_lock(); + PyThread_acquire_lock(interpreter_lock, 1); + main_thread = PyThread_get_thread_ident(); + + /* Update the threading module with the new state. + */ + tstate = PyThreadState_GET(); + threading = PyMapping_GetItemString(tstate->interp->modules, + "threading"); + if (threading == NULL) { + /* threading not imported */ + PyErr_Clear(); + return; + } + result = PyObject_CallMethod(threading, "_after_fork", NULL); + if (result == NULL) + PyErr_WriteUnraisable(threading); + else + Py_DECREF(result); + Py_DECREF(threading); } #endif @@ -325,29 +325,29 @@ PyThreadState * PyEval_SaveThread(void) { - PyThreadState *tstate = PyThreadState_Swap(NULL); - if (tstate == NULL) - Py_FatalError("PyEval_SaveThread: NULL tstate"); + PyThreadState *tstate = PyThreadState_Swap(NULL); + if (tstate == NULL) + Py_FatalError("PyEval_SaveThread: NULL tstate"); #ifdef WITH_THREAD - if (interpreter_lock) - PyThread_release_lock(interpreter_lock); + if (interpreter_lock) + PyThread_release_lock(interpreter_lock); #endif - return tstate; + return tstate; } void PyEval_RestoreThread(PyThreadState *tstate) { - if (tstate == NULL) - Py_FatalError("PyEval_RestoreThread: NULL tstate"); + if (tstate == NULL) + Py_FatalError("PyEval_RestoreThread: NULL tstate"); #ifdef WITH_THREAD - if (interpreter_lock) { - int err = errno; - PyThread_acquire_lock(interpreter_lock, 1); - errno = err; - } + if (interpreter_lock) { + int err = errno; + PyThread_acquire_lock(interpreter_lock, 1); + errno = err; + } #endif - PyThreadState_Swap(tstate); + PyThreadState_Swap(tstate); } @@ -384,8 +384,8 @@ #define NPENDINGCALLS 32 static struct { - int (*func)(void *); - void *arg; + int (*func)(void *); + void *arg; } pendingcalls[NPENDINGCALLS]; static int pendingfirst = 0; static int pendinglast = 0; @@ -395,93 +395,93 @@ int Py_AddPendingCall(int (*func)(void *), void *arg) { - int i, j, result=0; - PyThread_type_lock lock = pending_lock; - - /* try a few times for the lock. Since this mechanism is used - * for signal handling (on the main thread), there is a (slim) - * chance that a signal is delivered on the same thread while we - * hold the lock during the Py_MakePendingCalls() function. - * This avoids a deadlock in that case. - * Note that signals can be delivered on any thread. In particular, - * on Windows, a SIGINT is delivered on a system-created worker - * thread. - * We also check for lock being NULL, in the unlikely case that - * this function is called before any bytecode evaluation takes place. - */ - if (lock != NULL) { - for (i = 0; i<100; i++) { - if (PyThread_acquire_lock(lock, NOWAIT_LOCK)) - break; - } - if (i == 100) - return -1; - } - - i = pendinglast; - j = (i + 1) % NPENDINGCALLS; - if (j == pendingfirst) { - result = -1; /* Queue full */ - } else { - pendingcalls[i].func = func; - pendingcalls[i].arg = arg; - pendinglast = j; - } - /* signal main loop */ - _Py_Ticker = 0; - pendingcalls_to_do = 1; - if (lock != NULL) - PyThread_release_lock(lock); - return result; + int i, j, result=0; + PyThread_type_lock lock = pending_lock; + + /* try a few times for the lock. Since this mechanism is used + * for signal handling (on the main thread), there is a (slim) + * chance that a signal is delivered on the same thread while we + * hold the lock during the Py_MakePendingCalls() function. + * This avoids a deadlock in that case. + * Note that signals can be delivered on any thread. In particular, + * on Windows, a SIGINT is delivered on a system-created worker + * thread. + * We also check for lock being NULL, in the unlikely case that + * this function is called before any bytecode evaluation takes place. + */ + if (lock != NULL) { + for (i = 0; i<100; i++) { + if (PyThread_acquire_lock(lock, NOWAIT_LOCK)) + break; + } + if (i == 100) + return -1; + } + + i = pendinglast; + j = (i + 1) % NPENDINGCALLS; + if (j == pendingfirst) { + result = -1; /* Queue full */ + } else { + pendingcalls[i].func = func; + pendingcalls[i].arg = arg; + pendinglast = j; + } + /* signal main loop */ + _Py_Ticker = 0; + pendingcalls_to_do = 1; + if (lock != NULL) + PyThread_release_lock(lock); + return result; } int Py_MakePendingCalls(void) { - int i; - int r = 0; + int i; + int r = 0; - if (!pending_lock) { - /* initial allocation of the lock */ - pending_lock = PyThread_allocate_lock(); - if (pending_lock == NULL) - return -1; - } - - /* only service pending calls on main thread */ - if (main_thread && PyThread_get_thread_ident() != main_thread) - return 0; - /* don't perform recursive pending calls */ - if (pendingbusy) - return 0; - pendingbusy = 1; - /* perform a bounded number of calls, in case of recursion */ - for (i=0; irecursion_depth; - PyErr_SetString(PyExc_MemoryError, "Stack overflow"); - return -1; - } -#endif - _Py_CheckRecursionLimit = recursion_limit; - if (tstate->recursion_critical) - /* Somebody asked that we don't check for recursion. */ - return 0; - if (tstate->overflowed) { - if (tstate->recursion_depth > recursion_limit + 50) { - /* Overflowing while handling an overflow. Give up. */ - Py_FatalError("Cannot recover from stack overflow."); - } - return 0; - } - if (tstate->recursion_depth > recursion_limit) { - --tstate->recursion_depth; - tstate->overflowed = 1; - PyErr_Format(PyExc_RuntimeError, - "maximum recursion depth exceeded%s", - where); - return -1; - } - return 0; + if (PyOS_CheckStack()) { + --tstate->recursion_depth; + PyErr_SetString(PyExc_MemoryError, "Stack overflow"); + return -1; + } +#endif + _Py_CheckRecursionLimit = recursion_limit; + if (tstate->recursion_critical) + /* Somebody asked that we don't check for recursion. */ + return 0; + if (tstate->overflowed) { + if (tstate->recursion_depth > recursion_limit + 50) { + /* Overflowing while handling an overflow. Give up. */ + Py_FatalError("Cannot recover from stack overflow."); + } + return 0; + } + if (tstate->recursion_depth > recursion_limit) { + --tstate->recursion_depth; + tstate->overflowed = 1; + PyErr_Format(PyExc_RuntimeError, + "maximum recursion depth exceeded%s", + where); + return -1; + } + return 0; } /* Status code for main loop (reason for stack unwind) */ enum why_code { - WHY_NOT = 0x0001, /* No error */ - WHY_EXCEPTION = 0x0002, /* Exception occurred */ - WHY_RERAISE = 0x0004, /* Exception re-raised by 'finally' */ - WHY_RETURN = 0x0008, /* 'return' statement */ - WHY_BREAK = 0x0010, /* 'break' statement */ - WHY_CONTINUE = 0x0020, /* 'continue' statement */ - WHY_YIELD = 0x0040, /* 'yield' operator */ - WHY_SILENCED = 0x0080 /* Exception silenced by 'with' */ + WHY_NOT = 0x0001, /* No error */ + WHY_EXCEPTION = 0x0002, /* Exception occurred */ + WHY_RERAISE = 0x0004, /* Exception re-raised by 'finally' */ + WHY_RETURN = 0x0008, /* 'return' statement */ + WHY_BREAK = 0x0010, /* 'break' statement */ + WHY_CONTINUE = 0x0020, /* 'continue' statement */ + WHY_YIELD = 0x0040, /* 'yield' operator */ + WHY_SILENCED = 0x0080 /* Exception silenced by 'with' */ }; static enum why_code do_raise(PyObject *, PyObject *); @@ -665,12 +665,12 @@ PyObject * PyEval_EvalCode(PyCodeObject *co, PyObject *globals, PyObject *locals) { - return PyEval_EvalCodeEx(co, - globals, locals, - (PyObject **)NULL, 0, - (PyObject **)NULL, 0, - (PyObject **)NULL, 0, - NULL, NULL); + return PyEval_EvalCodeEx(co, + globals, locals, + (PyObject **)NULL, 0, + (PyObject **)NULL, 0, + (PyObject **)NULL, 0, + NULL, NULL); } @@ -678,49 +678,49 @@ PyObject * PyEval_EvalFrame(PyFrameObject *f) { - /* This is for backward compatibility with extension modules that - used this API; core interpreter code should call - PyEval_EvalFrameEx() */ - return PyEval_EvalFrameEx(f, 0); + /* This is for backward compatibility with extension modules that + used this API; core interpreter code should call + PyEval_EvalFrameEx() */ + return PyEval_EvalFrameEx(f, 0); } PyObject * PyEval_EvalFrameEx(PyFrameObject *f, int throwflag) { #ifdef DXPAIRS - int lastopcode = 0; + int lastopcode = 0; #endif - register PyObject **stack_pointer; /* Next free slot in value stack */ - register unsigned char *next_instr; - register int opcode; /* Current opcode */ - register int oparg; /* Current opcode argument, if any */ - register enum why_code why; /* Reason for block stack unwind */ - register int err; /* Error status -- nonzero if error */ - register PyObject *x; /* Result object -- NULL if error */ - register PyObject *v; /* Temporary objects popped off stack */ - register PyObject *w; - register PyObject *u; - register PyObject *t; - register PyObject **fastlocals, **freevars; - PyObject *retval = NULL; /* Return value */ - PyThreadState *tstate = PyThreadState_GET(); - PyCodeObject *co; - - /* when tracing we set things up so that - - not (instr_lb <= current_bytecode_offset < instr_ub) - - is true when the line being executed has changed. The - initial values are such as to make this false the first - time it is tested. */ - int instr_ub = -1, instr_lb = 0, instr_prev = -1; - - unsigned char *first_instr; - PyObject *names; - PyObject *consts; + register PyObject **stack_pointer; /* Next free slot in value stack */ + register unsigned char *next_instr; + register int opcode; /* Current opcode */ + register int oparg; /* Current opcode argument, if any */ + register enum why_code why; /* Reason for block stack unwind */ + register int err; /* Error status -- nonzero if error */ + register PyObject *x; /* Result object -- NULL if error */ + register PyObject *v; /* Temporary objects popped off stack */ + register PyObject *w; + register PyObject *u; + register PyObject *t; + register PyObject **fastlocals, **freevars; + PyObject *retval = NULL; /* Return value */ + PyThreadState *tstate = PyThreadState_GET(); + PyCodeObject *co; + + /* when tracing we set things up so that + + not (instr_lb <= current_bytecode_offset < instr_ub) + + is true when the line being executed has changed. The + initial values are such as to make this false the first + time it is tested. */ + int instr_ub = -1, instr_lb = 0, instr_prev = -1; + + unsigned char *first_instr; + PyObject *names; + PyObject *consts; #if defined(Py_DEBUG) || defined(LLTRACE) - /* Make it easier to find out where we are with a debugger */ - char *filename; + /* Make it easier to find out where we are with a debugger */ + char *filename; #endif /* Computed GOTOs, or @@ -729,7 +729,7 @@ (http://gcc.gnu.org/onlinedocs/gcc/Labels-as-Values.html). The traditional bytecode evaluation loop uses a "switch" statement, which - decent compilers will optimize as a single indirect branch instruction + decent compilers will optimize as a single indirect branch instruction combined with a lookup table of jump addresses. However, since the indirect jump instruction is shared by all opcodes, the CPU will have a hard time making the right prediction for where to jump next (actually, @@ -744,7 +744,7 @@ a much better chance to turn out valid, especially in small bytecode loops. A mispredicted branch on a modern CPU flushes the whole pipeline and - can cost several CPU cycles (depending on the pipeline depth), + can cost several CPU cycles (depending on the pipeline depth), and potentially many more instructions (depending on the pipeline width). A correctly predicted branch, however, is nearly free. @@ -773,59 +773,59 @@ /* This macro is used when several opcodes defer to the same implementation (e.g. SETUP_LOOP, SETUP_FINALLY) */ #define TARGET_WITH_IMPL(op, impl) \ - TARGET_##op: \ - opcode = op; \ - if (HAS_ARG(op)) \ - oparg = NEXTARG(); \ - case op: \ - goto impl; \ + TARGET_##op: \ + opcode = op; \ + if (HAS_ARG(op)) \ + oparg = NEXTARG(); \ + case op: \ + goto impl; \ #define TARGET(op) \ - TARGET_##op: \ - opcode = op; \ - if (HAS_ARG(op)) \ - oparg = NEXTARG(); \ - case op: + TARGET_##op: \ + opcode = op; \ + if (HAS_ARG(op)) \ + oparg = NEXTARG(); \ + case op: #define DISPATCH() \ - { \ - /* Avoid multiple loads from _Py_Ticker despite `volatile` */ \ - int _tick = _Py_Ticker - 1; \ - _Py_Ticker = _tick; \ - if (_tick >= 0) { \ - FAST_DISPATCH(); \ - } \ - continue; \ - } + { \ + /* Avoid multiple loads from _Py_Ticker despite `volatile` */ \ + int _tick = _Py_Ticker - 1; \ + _Py_Ticker = _tick; \ + if (_tick >= 0) { \ + FAST_DISPATCH(); \ + } \ + continue; \ + } #ifdef LLTRACE #define FAST_DISPATCH() \ - { \ - if (!lltrace && !_Py_TracingPossible) { \ - f->f_lasti = INSTR_OFFSET(); \ - goto *opcode_targets[*next_instr++]; \ - } \ - goto fast_next_opcode; \ - } + { \ + if (!lltrace && !_Py_TracingPossible) { \ + f->f_lasti = INSTR_OFFSET(); \ + goto *opcode_targets[*next_instr++]; \ + } \ + goto fast_next_opcode; \ + } #else #define FAST_DISPATCH() \ - { \ - if (!_Py_TracingPossible) { \ - f->f_lasti = INSTR_OFFSET(); \ - goto *opcode_targets[*next_instr++]; \ - } \ - goto fast_next_opcode; \ - } + { \ + if (!_Py_TracingPossible) { \ + f->f_lasti = INSTR_OFFSET(); \ + goto *opcode_targets[*next_instr++]; \ + } \ + goto fast_next_opcode; \ + } #endif #else #define TARGET(op) \ - case op: + case op: #define TARGET_WITH_IMPL(op, impl) \ - /* silence compiler warnings about `impl` unused */ \ - if (0) goto impl; \ - case op: + /* silence compiler warnings about `impl` unused */ \ + if (0) goto impl; \ + case op: #define DISPATCH() continue #define FAST_DISPATCH() goto fast_next_opcode #endif @@ -867,62 +867,62 @@ CALL_FUNCTION (and friends) */ - uint64 inst0, inst1, loop0, loop1, intr0 = 0, intr1 = 0; - int ticked = 0; + uint64 inst0, inst1, loop0, loop1, intr0 = 0, intr1 = 0; + int ticked = 0; - READ_TIMESTAMP(inst0); - READ_TIMESTAMP(inst1); - READ_TIMESTAMP(loop0); - READ_TIMESTAMP(loop1); + READ_TIMESTAMP(inst0); + READ_TIMESTAMP(inst1); + READ_TIMESTAMP(loop0); + READ_TIMESTAMP(loop1); - /* shut up the compiler */ - opcode = 0; + /* shut up the compiler */ + opcode = 0; #endif /* Code access macros */ -#define INSTR_OFFSET() ((int)(next_instr - first_instr)) -#define NEXTOP() (*next_instr++) -#define NEXTARG() (next_instr += 2, (next_instr[-1]<<8) + next_instr[-2]) -#define PEEKARG() ((next_instr[2]<<8) + next_instr[1]) -#define JUMPTO(x) (next_instr = first_instr + (x)) -#define JUMPBY(x) (next_instr += (x)) +#define INSTR_OFFSET() ((int)(next_instr - first_instr)) +#define NEXTOP() (*next_instr++) +#define NEXTARG() (next_instr += 2, (next_instr[-1]<<8) + next_instr[-2]) +#define PEEKARG() ((next_instr[2]<<8) + next_instr[1]) +#define JUMPTO(x) (next_instr = first_instr + (x)) +#define JUMPBY(x) (next_instr += (x)) /* OpCode prediction macros - Some opcodes tend to come in pairs thus making it possible to - predict the second code when the first is run. For example, - COMPARE_OP is often followed by JUMP_IF_FALSE or JUMP_IF_TRUE. And, - those opcodes are often followed by a POP_TOP. - - Verifying the prediction costs a single high-speed test of a register - variable against a constant. If the pairing was good, then the - processor's own internal branch predication has a high likelihood of - success, resulting in a nearly zero-overhead transition to the - next opcode. A successful prediction saves a trip through the eval-loop - including its two unpredictable branches, the HAS_ARG test and the - switch-case. Combined with the processor's internal branch prediction, - a successful PREDICT has the effect of making the two opcodes run as if - they were a single new opcode with the bodies combined. + Some opcodes tend to come in pairs thus making it possible to + predict the second code when the first is run. For example, + COMPARE_OP is often followed by JUMP_IF_FALSE or JUMP_IF_TRUE. And, + those opcodes are often followed by a POP_TOP. + + Verifying the prediction costs a single high-speed test of a register + variable against a constant. If the pairing was good, then the + processor's own internal branch predication has a high likelihood of + success, resulting in a nearly zero-overhead transition to the + next opcode. A successful prediction saves a trip through the eval-loop + including its two unpredictable branches, the HAS_ARG test and the + switch-case. Combined with the processor's internal branch prediction, + a successful PREDICT has the effect of making the two opcodes run as if + they were a single new opcode with the bodies combined. If collecting opcode statistics, your choices are to either keep the - predictions turned-on and interpret the results as if some opcodes - had been combined or turn-off predictions so that the opcode frequency - counter updates for both opcodes. + predictions turned-on and interpret the results as if some opcodes + had been combined or turn-off predictions so that the opcode frequency + counter updates for both opcodes. Opcode prediction is disabled with threaded code, since the latter allows - the CPU to record separate branch prediction information for each - opcode. + the CPU to record separate branch prediction information for each + opcode. */ #if defined(DYNAMIC_EXECUTION_PROFILE) || defined(USE_COMPUTED_GOTOS) -#define PREDICT(op) if (0) goto PRED_##op -#define PREDICTED(op) PRED_##op: -#define PREDICTED_WITH_ARG(op) PRED_##op: +#define PREDICT(op) if (0) goto PRED_##op +#define PREDICTED(op) PRED_##op: +#define PREDICTED_WITH_ARG(op) PRED_##op: #else -#define PREDICT(op) if (*next_instr == op) goto PRED_##op -#define PREDICTED(op) PRED_##op: next_instr++ -#define PREDICTED_WITH_ARG(op) PRED_##op: oparg = PEEKARG(); next_instr += 3 +#define PREDICT(op) if (*next_instr == op) goto PRED_##op +#define PREDICTED(op) PRED_##op: next_instr++ +#define PREDICTED_WITH_ARG(op) PRED_##op: oparg = PEEKARG(); next_instr += 3 #endif @@ -930,42 +930,42 @@ /* The stack can grow at most MAXINT deep, as co_nlocals and co_stacksize are ints. */ -#define STACK_LEVEL() ((int)(stack_pointer - f->f_valuestack)) -#define EMPTY() (STACK_LEVEL() == 0) -#define TOP() (stack_pointer[-1]) -#define SECOND() (stack_pointer[-2]) -#define THIRD() (stack_pointer[-3]) -#define FOURTH() (stack_pointer[-4]) -#define SET_TOP(v) (stack_pointer[-1] = (v)) -#define SET_SECOND(v) (stack_pointer[-2] = (v)) -#define SET_THIRD(v) (stack_pointer[-3] = (v)) -#define SET_FOURTH(v) (stack_pointer[-4] = (v)) -#define BASIC_STACKADJ(n) (stack_pointer += n) -#define BASIC_PUSH(v) (*stack_pointer++ = (v)) -#define BASIC_POP() (*--stack_pointer) +#define STACK_LEVEL() ((int)(stack_pointer - f->f_valuestack)) +#define EMPTY() (STACK_LEVEL() == 0) +#define TOP() (stack_pointer[-1]) +#define SECOND() (stack_pointer[-2]) +#define THIRD() (stack_pointer[-3]) +#define FOURTH() (stack_pointer[-4]) +#define SET_TOP(v) (stack_pointer[-1] = (v)) +#define SET_SECOND(v) (stack_pointer[-2] = (v)) +#define SET_THIRD(v) (stack_pointer[-3] = (v)) +#define SET_FOURTH(v) (stack_pointer[-4] = (v)) +#define BASIC_STACKADJ(n) (stack_pointer += n) +#define BASIC_PUSH(v) (*stack_pointer++ = (v)) +#define BASIC_POP() (*--stack_pointer) #ifdef LLTRACE -#define PUSH(v) { (void)(BASIC_PUSH(v), \ - lltrace && prtrace(TOP(), "push")); \ - assert(STACK_LEVEL() <= co->co_stacksize); } -#define POP() ((void)(lltrace && prtrace(TOP(), "pop")), \ - BASIC_POP()) -#define STACKADJ(n) { (void)(BASIC_STACKADJ(n), \ - lltrace && prtrace(TOP(), "stackadj")); \ - assert(STACK_LEVEL() <= co->co_stacksize); } +#define PUSH(v) { (void)(BASIC_PUSH(v), \ + lltrace && prtrace(TOP(), "push")); \ + assert(STACK_LEVEL() <= co->co_stacksize); } +#define POP() ((void)(lltrace && prtrace(TOP(), "pop")), \ + BASIC_POP()) +#define STACKADJ(n) { (void)(BASIC_STACKADJ(n), \ + lltrace && prtrace(TOP(), "stackadj")); \ + assert(STACK_LEVEL() <= co->co_stacksize); } #define EXT_POP(STACK_POINTER) ((void)(lltrace && \ - prtrace((STACK_POINTER)[-1], "ext_pop")), \ - *--(STACK_POINTER)) + prtrace((STACK_POINTER)[-1], "ext_pop")), \ + *--(STACK_POINTER)) #else -#define PUSH(v) BASIC_PUSH(v) -#define POP() BASIC_POP() -#define STACKADJ(n) BASIC_STACKADJ(n) +#define PUSH(v) BASIC_PUSH(v) +#define POP() BASIC_POP() +#define STACKADJ(n) BASIC_STACKADJ(n) #define EXT_POP(STACK_POINTER) (*--(STACK_POINTER)) #endif /* Local variable macros */ -#define GETLOCAL(i) (fastlocals[i]) +#define GETLOCAL(i) (fastlocals[i]) /* The SETLOCAL() macro must not DECREF the local variable in-place and then store the new value; it must copy the old value to a temporary @@ -973,1962 +973,1962 @@ This is because it is possible that during the DECREF the frame is accessed by other code (e.g. a __del__ method or gc.collect()) and the variable would be pointing to already-freed memory. */ -#define SETLOCAL(i, value) do { PyObject *tmp = GETLOCAL(i); \ - GETLOCAL(i) = value; \ - Py_XDECREF(tmp); } while (0) +#define SETLOCAL(i, value) do { PyObject *tmp = GETLOCAL(i); \ + GETLOCAL(i) = value; \ + Py_XDECREF(tmp); } while (0) #define UNWIND_BLOCK(b) \ - while (STACK_LEVEL() > (b)->b_level) { \ - PyObject *v = POP(); \ - Py_XDECREF(v); \ - } + while (STACK_LEVEL() > (b)->b_level) { \ + PyObject *v = POP(); \ + Py_XDECREF(v); \ + } #define UNWIND_EXCEPT_HANDLER(b) \ - { \ - PyObject *type, *value, *traceback; \ - assert(STACK_LEVEL() >= (b)->b_level + 3); \ - while (STACK_LEVEL() > (b)->b_level + 3) { \ - value = POP(); \ - Py_XDECREF(value); \ - } \ - type = tstate->exc_type; \ - value = tstate->exc_value; \ - traceback = tstate->exc_traceback; \ - tstate->exc_type = POP(); \ - tstate->exc_value = POP(); \ - tstate->exc_traceback = POP(); \ - Py_XDECREF(type); \ - Py_XDECREF(value); \ - Py_XDECREF(traceback); \ - } + { \ + PyObject *type, *value, *traceback; \ + assert(STACK_LEVEL() >= (b)->b_level + 3); \ + while (STACK_LEVEL() > (b)->b_level + 3) { \ + value = POP(); \ + Py_XDECREF(value); \ + } \ + type = tstate->exc_type; \ + value = tstate->exc_value; \ + traceback = tstate->exc_traceback; \ + tstate->exc_type = POP(); \ + tstate->exc_value = POP(); \ + tstate->exc_traceback = POP(); \ + Py_XDECREF(type); \ + Py_XDECREF(value); \ + Py_XDECREF(traceback); \ + } #define SAVE_EXC_STATE() \ - { \ - PyObject *type, *value, *traceback; \ - Py_XINCREF(tstate->exc_type); \ - Py_XINCREF(tstate->exc_value); \ - Py_XINCREF(tstate->exc_traceback); \ - type = f->f_exc_type; \ - value = f->f_exc_value; \ - traceback = f->f_exc_traceback; \ - f->f_exc_type = tstate->exc_type; \ - f->f_exc_value = tstate->exc_value; \ - f->f_exc_traceback = tstate->exc_traceback; \ - Py_XDECREF(type); \ - Py_XDECREF(value); \ - Py_XDECREF(traceback); \ - } + { \ + PyObject *type, *value, *traceback; \ + Py_XINCREF(tstate->exc_type); \ + Py_XINCREF(tstate->exc_value); \ + Py_XINCREF(tstate->exc_traceback); \ + type = f->f_exc_type; \ + value = f->f_exc_value; \ + traceback = f->f_exc_traceback; \ + f->f_exc_type = tstate->exc_type; \ + f->f_exc_value = tstate->exc_value; \ + f->f_exc_traceback = tstate->exc_traceback; \ + Py_XDECREF(type); \ + Py_XDECREF(value); \ + Py_XDECREF(traceback); \ + } #define SWAP_EXC_STATE() \ - { \ - PyObject *tmp; \ - tmp = tstate->exc_type; \ - tstate->exc_type = f->f_exc_type; \ - f->f_exc_type = tmp; \ - tmp = tstate->exc_value; \ - tstate->exc_value = f->f_exc_value; \ - f->f_exc_value = tmp; \ - tmp = tstate->exc_traceback; \ - tstate->exc_traceback = f->f_exc_traceback; \ - f->f_exc_traceback = tmp; \ - } + { \ + PyObject *tmp; \ + tmp = tstate->exc_type; \ + tstate->exc_type = f->f_exc_type; \ + f->f_exc_type = tmp; \ + tmp = tstate->exc_value; \ + tstate->exc_value = f->f_exc_value; \ + f->f_exc_value = tmp; \ + tmp = tstate->exc_traceback; \ + tstate->exc_traceback = f->f_exc_traceback; \ + f->f_exc_traceback = tmp; \ + } /* Start of code */ - if (f == NULL) - return NULL; + if (f == NULL) + return NULL; - /* push frame */ - if (Py_EnterRecursiveCall("")) - return NULL; - - tstate->frame = f; - - if (tstate->use_tracing) { - if (tstate->c_tracefunc != NULL) { - /* tstate->c_tracefunc, if defined, is a - function that will be called on *every* entry - to a code block. Its return value, if not - None, is a function that will be called at - the start of each executed line of code. - (Actually, the function must return itself - in order to continue tracing.) The trace - functions are called with three arguments: - a pointer to the current frame, a string - indicating why the function is called, and - an argument which depends on the situation. - The global trace function is also called - whenever an exception is detected. */ - if (call_trace_protected(tstate->c_tracefunc, - tstate->c_traceobj, - f, PyTrace_CALL, Py_None)) { - /* Trace function raised an error */ - goto exit_eval_frame; - } - } - if (tstate->c_profilefunc != NULL) { - /* Similar for c_profilefunc, except it needn't - return itself and isn't called for "line" events */ - if (call_trace_protected(tstate->c_profilefunc, - tstate->c_profileobj, - f, PyTrace_CALL, Py_None)) { - /* Profile function raised an error */ - goto exit_eval_frame; - } - } - } - - co = f->f_code; - names = co->co_names; - consts = co->co_consts; - fastlocals = f->f_localsplus; - freevars = f->f_localsplus + co->co_nlocals; - first_instr = (unsigned char*) PyBytes_AS_STRING(co->co_code); - /* An explanation is in order for the next line. - - f->f_lasti now refers to the index of the last instruction - executed. You might think this was obvious from the name, but - this wasn't always true before 2.3! PyFrame_New now sets - f->f_lasti to -1 (i.e. the index *before* the first instruction) - and YIELD_VALUE doesn't fiddle with f_lasti any more. So this - does work. Promise. - - When the PREDICT() macros are enabled, some opcode pairs follow in - direct succession without updating f->f_lasti. A successful - prediction effectively links the two codes together as if they - were a single new opcode; accordingly,f->f_lasti will point to - the first code in the pair (for instance, GET_ITER followed by - FOR_ITER is effectively a single opcode and f->f_lasti will point - at to the beginning of the combined pair.) - */ - next_instr = first_instr + f->f_lasti + 1; - stack_pointer = f->f_stacktop; - assert(stack_pointer != NULL); - f->f_stacktop = NULL; /* remains NULL unless yield suspends frame */ - - if (co->co_flags & CO_GENERATOR && !throwflag) { - if (f->f_exc_type != NULL && f->f_exc_type != Py_None) { - /* We were in an except handler when we left, - restore the exception state which was put aside - (see YIELD_VALUE). */ - SWAP_EXC_STATE(); - } - else { - SAVE_EXC_STATE(); - } - } + /* push frame */ + if (Py_EnterRecursiveCall("")) + return NULL; + + tstate->frame = f; + + if (tstate->use_tracing) { + if (tstate->c_tracefunc != NULL) { + /* tstate->c_tracefunc, if defined, is a + function that will be called on *every* entry + to a code block. Its return value, if not + None, is a function that will be called at + the start of each executed line of code. + (Actually, the function must return itself + in order to continue tracing.) The trace + functions are called with three arguments: + a pointer to the current frame, a string + indicating why the function is called, and + an argument which depends on the situation. + The global trace function is also called + whenever an exception is detected. */ + if (call_trace_protected(tstate->c_tracefunc, + tstate->c_traceobj, + f, PyTrace_CALL, Py_None)) { + /* Trace function raised an error */ + goto exit_eval_frame; + } + } + if (tstate->c_profilefunc != NULL) { + /* Similar for c_profilefunc, except it needn't + return itself and isn't called for "line" events */ + if (call_trace_protected(tstate->c_profilefunc, + tstate->c_profileobj, + f, PyTrace_CALL, Py_None)) { + /* Profile function raised an error */ + goto exit_eval_frame; + } + } + } + + co = f->f_code; + names = co->co_names; + consts = co->co_consts; + fastlocals = f->f_localsplus; + freevars = f->f_localsplus + co->co_nlocals; + first_instr = (unsigned char*) PyBytes_AS_STRING(co->co_code); + /* An explanation is in order for the next line. + + f->f_lasti now refers to the index of the last instruction + executed. You might think this was obvious from the name, but + this wasn't always true before 2.3! PyFrame_New now sets + f->f_lasti to -1 (i.e. the index *before* the first instruction) + and YIELD_VALUE doesn't fiddle with f_lasti any more. So this + does work. Promise. + + When the PREDICT() macros are enabled, some opcode pairs follow in + direct succession without updating f->f_lasti. A successful + prediction effectively links the two codes together as if they + were a single new opcode; accordingly,f->f_lasti will point to + the first code in the pair (for instance, GET_ITER followed by + FOR_ITER is effectively a single opcode and f->f_lasti will point + at to the beginning of the combined pair.) + */ + next_instr = first_instr + f->f_lasti + 1; + stack_pointer = f->f_stacktop; + assert(stack_pointer != NULL); + f->f_stacktop = NULL; /* remains NULL unless yield suspends frame */ + + if (co->co_flags & CO_GENERATOR && !throwflag) { + if (f->f_exc_type != NULL && f->f_exc_type != Py_None) { + /* We were in an except handler when we left, + restore the exception state which was put aside + (see YIELD_VALUE). */ + SWAP_EXC_STATE(); + } + else { + SAVE_EXC_STATE(); + } + } #ifdef LLTRACE - lltrace = PyDict_GetItemString(f->f_globals, "__lltrace__") != NULL; + lltrace = PyDict_GetItemString(f->f_globals, "__lltrace__") != NULL; #endif #if defined(Py_DEBUG) || defined(LLTRACE) - filename = _PyUnicode_AsString(co->co_filename); + filename = _PyUnicode_AsString(co->co_filename); #endif - why = WHY_NOT; - err = 0; - x = Py_None; /* Not a reference, just anything non-NULL */ - w = NULL; + why = WHY_NOT; + err = 0; + x = Py_None; /* Not a reference, just anything non-NULL */ + w = NULL; - if (throwflag) { /* support for generator.throw() */ - why = WHY_EXCEPTION; - goto on_error; - } + if (throwflag) { /* support for generator.throw() */ + why = WHY_EXCEPTION; + goto on_error; + } - for (;;) { + for (;;) { #ifdef WITH_TSC - if (inst1 == 0) { - /* Almost surely, the opcode executed a break - or a continue, preventing inst1 from being set - on the way out of the loop. - */ - READ_TIMESTAMP(inst1); - loop1 = inst1; - } - dump_tsc(opcode, ticked, inst0, inst1, loop0, loop1, - intr0, intr1); - ticked = 0; - inst1 = 0; - intr0 = 0; - intr1 = 0; - READ_TIMESTAMP(loop0); -#endif - assert(stack_pointer >= f->f_valuestack); /* else underflow */ - assert(STACK_LEVEL() <= co->co_stacksize); /* else overflow */ - - /* Do periodic things. Doing this every time through - the loop would add too much overhead, so we do it - only every Nth instruction. We also do it if - ``pendingcalls_to_do'' is set, i.e. when an asynchronous - event needs attention (e.g. a signal handler or - async I/O handler); see Py_AddPendingCall() and - Py_MakePendingCalls() above. */ - - if (--_Py_Ticker < 0) { - if (*next_instr == SETUP_FINALLY) { - /* Make the last opcode before - a try: finally: block uninterruptable. */ - goto fast_next_opcode; - } - _Py_Ticker = _Py_CheckInterval; - tstate->tick_counter++; + if (inst1 == 0) { + /* Almost surely, the opcode executed a break + or a continue, preventing inst1 from being set + on the way out of the loop. + */ + READ_TIMESTAMP(inst1); + loop1 = inst1; + } + dump_tsc(opcode, ticked, inst0, inst1, loop0, loop1, + intr0, intr1); + ticked = 0; + inst1 = 0; + intr0 = 0; + intr1 = 0; + READ_TIMESTAMP(loop0); +#endif + assert(stack_pointer >= f->f_valuestack); /* else underflow */ + assert(STACK_LEVEL() <= co->co_stacksize); /* else overflow */ + + /* Do periodic things. Doing this every time through + the loop would add too much overhead, so we do it + only every Nth instruction. We also do it if + ``pendingcalls_to_do'' is set, i.e. when an asynchronous + event needs attention (e.g. a signal handler or + async I/O handler); see Py_AddPendingCall() and + Py_MakePendingCalls() above. */ + + if (--_Py_Ticker < 0) { + if (*next_instr == SETUP_FINALLY) { + /* Make the last opcode before + a try: finally: block uninterruptable. */ + goto fast_next_opcode; + } + _Py_Ticker = _Py_CheckInterval; + tstate->tick_counter++; #ifdef WITH_TSC - ticked = 1; + ticked = 1; #endif - if (pendingcalls_to_do) { - if (Py_MakePendingCalls() < 0) { - why = WHY_EXCEPTION; - goto on_error; - } - if (pendingcalls_to_do) - /* MakePendingCalls() didn't succeed. - Force early re-execution of this - "periodic" code, possibly after - a thread switch */ - _Py_Ticker = 0; - } + if (pendingcalls_to_do) { + if (Py_MakePendingCalls() < 0) { + why = WHY_EXCEPTION; + goto on_error; + } + if (pendingcalls_to_do) + /* MakePendingCalls() didn't succeed. + Force early re-execution of this + "periodic" code, possibly after + a thread switch */ + _Py_Ticker = 0; + } #ifdef WITH_THREAD - if (interpreter_lock) { - /* Give another thread a chance */ + if (interpreter_lock) { + /* Give another thread a chance */ - if (PyThreadState_Swap(NULL) != tstate) - Py_FatalError("ceval: tstate mix-up"); - PyThread_release_lock(interpreter_lock); - - /* Other threads may run now */ - - PyThread_acquire_lock(interpreter_lock, 1); - if (PyThreadState_Swap(tstate) != NULL) - Py_FatalError("ceval: orphan tstate"); - - /* Check for thread interrupts */ - - if (tstate->async_exc != NULL) { - x = tstate->async_exc; - tstate->async_exc = NULL; - PyErr_SetNone(x); - Py_DECREF(x); - why = WHY_EXCEPTION; - goto on_error; - } - } -#endif - } - - fast_next_opcode: - f->f_lasti = INSTR_OFFSET(); - - /* line-by-line tracing support */ - - if (_Py_TracingPossible && - tstate->c_tracefunc != NULL && !tstate->tracing) { - /* see maybe_call_line_trace - for expository comments */ - f->f_stacktop = stack_pointer; - - err = maybe_call_line_trace(tstate->c_tracefunc, - tstate->c_traceobj, - f, &instr_lb, &instr_ub, - &instr_prev); - /* Reload possibly changed frame fields */ - JUMPTO(f->f_lasti); - if (f->f_stacktop != NULL) { - stack_pointer = f->f_stacktop; - f->f_stacktop = NULL; - } - if (err) { - /* trace function raised an exception */ - goto on_error; - } - } - - /* Extract opcode and argument */ - - opcode = NEXTOP(); - oparg = 0; /* allows oparg to be stored in a register because - it doesn't have to be remembered across a full loop */ - if (HAS_ARG(opcode)) - oparg = NEXTARG(); - dispatch_opcode: + if (PyThreadState_Swap(NULL) != tstate) + Py_FatalError("ceval: tstate mix-up"); + PyThread_release_lock(interpreter_lock); + + /* Other threads may run now */ + + PyThread_acquire_lock(interpreter_lock, 1); + if (PyThreadState_Swap(tstate) != NULL) + Py_FatalError("ceval: orphan tstate"); + + /* Check for thread interrupts */ + + if (tstate->async_exc != NULL) { + x = tstate->async_exc; + tstate->async_exc = NULL; + PyErr_SetNone(x); + Py_DECREF(x); + why = WHY_EXCEPTION; + goto on_error; + } + } +#endif + } + + fast_next_opcode: + f->f_lasti = INSTR_OFFSET(); + + /* line-by-line tracing support */ + + if (_Py_TracingPossible && + tstate->c_tracefunc != NULL && !tstate->tracing) { + /* see maybe_call_line_trace + for expository comments */ + f->f_stacktop = stack_pointer; + + err = maybe_call_line_trace(tstate->c_tracefunc, + tstate->c_traceobj, + f, &instr_lb, &instr_ub, + &instr_prev); + /* Reload possibly changed frame fields */ + JUMPTO(f->f_lasti); + if (f->f_stacktop != NULL) { + stack_pointer = f->f_stacktop; + f->f_stacktop = NULL; + } + if (err) { + /* trace function raised an exception */ + goto on_error; + } + } + + /* Extract opcode and argument */ + + opcode = NEXTOP(); + oparg = 0; /* allows oparg to be stored in a register because + it doesn't have to be remembered across a full loop */ + if (HAS_ARG(opcode)) + oparg = NEXTARG(); + dispatch_opcode: #ifdef DYNAMIC_EXECUTION_PROFILE #ifdef DXPAIRS - dxpairs[lastopcode][opcode]++; - lastopcode = opcode; + dxpairs[lastopcode][opcode]++; + lastopcode = opcode; #endif - dxp[opcode]++; + dxp[opcode]++; #endif #ifdef LLTRACE - /* Instruction tracing */ + /* Instruction tracing */ - if (lltrace) { - if (HAS_ARG(opcode)) { - printf("%d: %d, %d\n", - f->f_lasti, opcode, oparg); - } - else { - printf("%d: %d\n", - f->f_lasti, opcode); - } - } -#endif - - /* Main switch on opcode */ - READ_TIMESTAMP(inst0); - - switch (opcode) { - - /* BEWARE! - It is essential that any operation that fails sets either - x to NULL, err to nonzero, or why to anything but WHY_NOT, - and that no operation that succeeds does this! */ - - /* case STOP_CODE: this is an error! */ - - TARGET(NOP) - FAST_DISPATCH(); - - TARGET(LOAD_FAST) - x = GETLOCAL(oparg); - if (x != NULL) { - Py_INCREF(x); - PUSH(x); - FAST_DISPATCH(); - } - format_exc_check_arg(PyExc_UnboundLocalError, - UNBOUNDLOCAL_ERROR_MSG, - PyTuple_GetItem(co->co_varnames, oparg)); - break; - - TARGET(LOAD_CONST) - x = GETITEM(consts, oparg); - Py_INCREF(x); - PUSH(x); - FAST_DISPATCH(); - - PREDICTED_WITH_ARG(STORE_FAST); - TARGET(STORE_FAST) - v = POP(); - SETLOCAL(oparg, v); - FAST_DISPATCH(); - - TARGET(POP_TOP) - v = POP(); - Py_DECREF(v); - FAST_DISPATCH(); - - TARGET(ROT_TWO) - v = TOP(); - w = SECOND(); - SET_TOP(w); - SET_SECOND(v); - FAST_DISPATCH(); - - TARGET(ROT_THREE) - v = TOP(); - w = SECOND(); - x = THIRD(); - SET_TOP(w); - SET_SECOND(x); - SET_THIRD(v); - FAST_DISPATCH(); - - TARGET(ROT_FOUR) - u = TOP(); - v = SECOND(); - w = THIRD(); - x = FOURTH(); - SET_TOP(v); - SET_SECOND(w); - SET_THIRD(x); - SET_FOURTH(u); - FAST_DISPATCH(); - - TARGET(DUP_TOP) - v = TOP(); - Py_INCREF(v); - PUSH(v); - FAST_DISPATCH(); - - TARGET(DUP_TOPX) - if (oparg == 2) { - x = TOP(); - Py_INCREF(x); - w = SECOND(); - Py_INCREF(w); - STACKADJ(2); - SET_TOP(x); - SET_SECOND(w); - FAST_DISPATCH(); - } else if (oparg == 3) { - x = TOP(); - Py_INCREF(x); - w = SECOND(); - Py_INCREF(w); - v = THIRD(); - Py_INCREF(v); - STACKADJ(3); - SET_TOP(x); - SET_SECOND(w); - SET_THIRD(v); - FAST_DISPATCH(); - } - Py_FatalError("invalid argument to DUP_TOPX" - " (bytecode corruption?)"); - /* Never returns, so don't bother to set why. */ - break; - - TARGET(UNARY_POSITIVE) - v = TOP(); - x = PyNumber_Positive(v); - Py_DECREF(v); - SET_TOP(x); - if (x != NULL) DISPATCH(); - break; - - TARGET(UNARY_NEGATIVE) - v = TOP(); - x = PyNumber_Negative(v); - Py_DECREF(v); - SET_TOP(x); - if (x != NULL) DISPATCH(); - break; - - TARGET(UNARY_NOT) - v = TOP(); - err = PyObject_IsTrue(v); - Py_DECREF(v); - if (err == 0) { - Py_INCREF(Py_True); - SET_TOP(Py_True); - DISPATCH(); - } - else if (err > 0) { - Py_INCREF(Py_False); - SET_TOP(Py_False); - err = 0; - DISPATCH(); - } - STACKADJ(-1); - break; - - TARGET(UNARY_INVERT) - v = TOP(); - x = PyNumber_Invert(v); - Py_DECREF(v); - SET_TOP(x); - if (x != NULL) DISPATCH(); - break; - - TARGET(BINARY_POWER) - w = POP(); - v = TOP(); - x = PyNumber_Power(v, w, Py_None); - Py_DECREF(v); - Py_DECREF(w); - SET_TOP(x); - if (x != NULL) DISPATCH(); - break; - - TARGET(BINARY_MULTIPLY) - w = POP(); - v = TOP(); - x = PyNumber_Multiply(v, w); - Py_DECREF(v); - Py_DECREF(w); - SET_TOP(x); - if (x != NULL) DISPATCH(); - break; - - TARGET(BINARY_TRUE_DIVIDE) - w = POP(); - v = TOP(); - x = PyNumber_TrueDivide(v, w); - Py_DECREF(v); - Py_DECREF(w); - SET_TOP(x); - if (x != NULL) DISPATCH(); - break; - - TARGET(BINARY_FLOOR_DIVIDE) - w = POP(); - v = TOP(); - x = PyNumber_FloorDivide(v, w); - Py_DECREF(v); - Py_DECREF(w); - SET_TOP(x); - if (x != NULL) DISPATCH(); - break; - - TARGET(BINARY_MODULO) - w = POP(); - v = TOP(); - if (PyUnicode_CheckExact(v)) - x = PyUnicode_Format(v, w); - else - x = PyNumber_Remainder(v, w); - Py_DECREF(v); - Py_DECREF(w); - SET_TOP(x); - if (x != NULL) DISPATCH(); - break; - - TARGET(BINARY_ADD) - w = POP(); - v = TOP(); - if (PyUnicode_CheckExact(v) && - PyUnicode_CheckExact(w)) { - x = unicode_concatenate(v, w, f, next_instr); - /* unicode_concatenate consumed the ref to v */ - goto skip_decref_vx; - } - else { - x = PyNumber_Add(v, w); - } - Py_DECREF(v); - skip_decref_vx: - Py_DECREF(w); - SET_TOP(x); - if (x != NULL) DISPATCH(); - break; - - TARGET(BINARY_SUBTRACT) - w = POP(); - v = TOP(); - x = PyNumber_Subtract(v, w); - Py_DECREF(v); - Py_DECREF(w); - SET_TOP(x); - if (x != NULL) DISPATCH(); - break; - - TARGET(BINARY_SUBSCR) - w = POP(); - v = TOP(); - x = PyObject_GetItem(v, w); - Py_DECREF(v); - Py_DECREF(w); - SET_TOP(x); - if (x != NULL) DISPATCH(); - break; - - TARGET(BINARY_LSHIFT) - w = POP(); - v = TOP(); - x = PyNumber_Lshift(v, w); - Py_DECREF(v); - Py_DECREF(w); - SET_TOP(x); - if (x != NULL) DISPATCH(); - break; - - TARGET(BINARY_RSHIFT) - w = POP(); - v = TOP(); - x = PyNumber_Rshift(v, w); - Py_DECREF(v); - Py_DECREF(w); - SET_TOP(x); - if (x != NULL) DISPATCH(); - break; - - TARGET(BINARY_AND) - w = POP(); - v = TOP(); - x = PyNumber_And(v, w); - Py_DECREF(v); - Py_DECREF(w); - SET_TOP(x); - if (x != NULL) DISPATCH(); - break; - - TARGET(BINARY_XOR) - w = POP(); - v = TOP(); - x = PyNumber_Xor(v, w); - Py_DECREF(v); - Py_DECREF(w); - SET_TOP(x); - if (x != NULL) DISPATCH(); - break; - - TARGET(BINARY_OR) - w = POP(); - v = TOP(); - x = PyNumber_Or(v, w); - Py_DECREF(v); - Py_DECREF(w); - SET_TOP(x); - if (x != NULL) DISPATCH(); - break; - - TARGET(LIST_APPEND) - w = POP(); - v = stack_pointer[-oparg]; - err = PyList_Append(v, w); - Py_DECREF(w); - if (err == 0) { - PREDICT(JUMP_ABSOLUTE); - DISPATCH(); - } - break; - - TARGET(SET_ADD) - w = POP(); - v = stack_pointer[-oparg]; - err = PySet_Add(v, w); - Py_DECREF(w); - if (err == 0) { - PREDICT(JUMP_ABSOLUTE); - DISPATCH(); - } - break; - - TARGET(INPLACE_POWER) - w = POP(); - v = TOP(); - x = PyNumber_InPlacePower(v, w, Py_None); - Py_DECREF(v); - Py_DECREF(w); - SET_TOP(x); - if (x != NULL) DISPATCH(); - break; - - TARGET(INPLACE_MULTIPLY) - w = POP(); - v = TOP(); - x = PyNumber_InPlaceMultiply(v, w); - Py_DECREF(v); - Py_DECREF(w); - SET_TOP(x); - if (x != NULL) DISPATCH(); - break; - - TARGET(INPLACE_TRUE_DIVIDE) - w = POP(); - v = TOP(); - x = PyNumber_InPlaceTrueDivide(v, w); - Py_DECREF(v); - Py_DECREF(w); - SET_TOP(x); - if (x != NULL) DISPATCH(); - break; - - TARGET(INPLACE_FLOOR_DIVIDE) - w = POP(); - v = TOP(); - x = PyNumber_InPlaceFloorDivide(v, w); - Py_DECREF(v); - Py_DECREF(w); - SET_TOP(x); - if (x != NULL) DISPATCH(); - break; - - TARGET(INPLACE_MODULO) - w = POP(); - v = TOP(); - x = PyNumber_InPlaceRemainder(v, w); - Py_DECREF(v); - Py_DECREF(w); - SET_TOP(x); - if (x != NULL) DISPATCH(); - break; - - TARGET(INPLACE_ADD) - w = POP(); - v = TOP(); - if (PyUnicode_CheckExact(v) && - PyUnicode_CheckExact(w)) { - x = unicode_concatenate(v, w, f, next_instr); - /* unicode_concatenate consumed the ref to v */ - goto skip_decref_v; - } - else { - x = PyNumber_InPlaceAdd(v, w); - } - Py_DECREF(v); - skip_decref_v: - Py_DECREF(w); - SET_TOP(x); - if (x != NULL) DISPATCH(); - break; - - TARGET(INPLACE_SUBTRACT) - w = POP(); - v = TOP(); - x = PyNumber_InPlaceSubtract(v, w); - Py_DECREF(v); - Py_DECREF(w); - SET_TOP(x); - if (x != NULL) DISPATCH(); - break; - - TARGET(INPLACE_LSHIFT) - w = POP(); - v = TOP(); - x = PyNumber_InPlaceLshift(v, w); - Py_DECREF(v); - Py_DECREF(w); - SET_TOP(x); - if (x != NULL) DISPATCH(); - break; - - TARGET(INPLACE_RSHIFT) - w = POP(); - v = TOP(); - x = PyNumber_InPlaceRshift(v, w); - Py_DECREF(v); - Py_DECREF(w); - SET_TOP(x); - if (x != NULL) DISPATCH(); - break; - - TARGET(INPLACE_AND) - w = POP(); - v = TOP(); - x = PyNumber_InPlaceAnd(v, w); - Py_DECREF(v); - Py_DECREF(w); - SET_TOP(x); - if (x != NULL) DISPATCH(); - break; - - TARGET(INPLACE_XOR) - w = POP(); - v = TOP(); - x = PyNumber_InPlaceXor(v, w); - Py_DECREF(v); - Py_DECREF(w); - SET_TOP(x); - if (x != NULL) DISPATCH(); - break; - - TARGET(INPLACE_OR) - w = POP(); - v = TOP(); - x = PyNumber_InPlaceOr(v, w); - Py_DECREF(v); - Py_DECREF(w); - SET_TOP(x); - if (x != NULL) DISPATCH(); - break; - - TARGET(STORE_SUBSCR) - w = TOP(); - v = SECOND(); - u = THIRD(); - STACKADJ(-3); - /* v[w] = u */ - err = PyObject_SetItem(v, w, u); - Py_DECREF(u); - Py_DECREF(v); - Py_DECREF(w); - if (err == 0) DISPATCH(); - break; - - TARGET(DELETE_SUBSCR) - w = TOP(); - v = SECOND(); - STACKADJ(-2); - /* del v[w] */ - err = PyObject_DelItem(v, w); - Py_DECREF(v); - Py_DECREF(w); - if (err == 0) DISPATCH(); - break; - - TARGET(PRINT_EXPR) - v = POP(); - w = PySys_GetObject("displayhook"); - if (w == NULL) { - PyErr_SetString(PyExc_RuntimeError, - "lost sys.displayhook"); - err = -1; - x = NULL; - } - if (err == 0) { - x = PyTuple_Pack(1, v); - if (x == NULL) - err = -1; - } - if (err == 0) { - w = PyEval_CallObject(w, x); - Py_XDECREF(w); - if (w == NULL) - err = -1; - } - Py_DECREF(v); - Py_XDECREF(x); - break; + if (lltrace) { + if (HAS_ARG(opcode)) { + printf("%d: %d, %d\n", + f->f_lasti, opcode, oparg); + } + else { + printf("%d: %d\n", + f->f_lasti, opcode); + } + } +#endif + + /* Main switch on opcode */ + READ_TIMESTAMP(inst0); + + switch (opcode) { + + /* BEWARE! + It is essential that any operation that fails sets either + x to NULL, err to nonzero, or why to anything but WHY_NOT, + and that no operation that succeeds does this! */ + + /* case STOP_CODE: this is an error! */ + + TARGET(NOP) + FAST_DISPATCH(); + + TARGET(LOAD_FAST) + x = GETLOCAL(oparg); + if (x != NULL) { + Py_INCREF(x); + PUSH(x); + FAST_DISPATCH(); + } + format_exc_check_arg(PyExc_UnboundLocalError, + UNBOUNDLOCAL_ERROR_MSG, + PyTuple_GetItem(co->co_varnames, oparg)); + break; + + TARGET(LOAD_CONST) + x = GETITEM(consts, oparg); + Py_INCREF(x); + PUSH(x); + FAST_DISPATCH(); + + PREDICTED_WITH_ARG(STORE_FAST); + TARGET(STORE_FAST) + v = POP(); + SETLOCAL(oparg, v); + FAST_DISPATCH(); + + TARGET(POP_TOP) + v = POP(); + Py_DECREF(v); + FAST_DISPATCH(); + + TARGET(ROT_TWO) + v = TOP(); + w = SECOND(); + SET_TOP(w); + SET_SECOND(v); + FAST_DISPATCH(); + + TARGET(ROT_THREE) + v = TOP(); + w = SECOND(); + x = THIRD(); + SET_TOP(w); + SET_SECOND(x); + SET_THIRD(v); + FAST_DISPATCH(); + + TARGET(ROT_FOUR) + u = TOP(); + v = SECOND(); + w = THIRD(); + x = FOURTH(); + SET_TOP(v); + SET_SECOND(w); + SET_THIRD(x); + SET_FOURTH(u); + FAST_DISPATCH(); + + TARGET(DUP_TOP) + v = TOP(); + Py_INCREF(v); + PUSH(v); + FAST_DISPATCH(); + + TARGET(DUP_TOPX) + if (oparg == 2) { + x = TOP(); + Py_INCREF(x); + w = SECOND(); + Py_INCREF(w); + STACKADJ(2); + SET_TOP(x); + SET_SECOND(w); + FAST_DISPATCH(); + } else if (oparg == 3) { + x = TOP(); + Py_INCREF(x); + w = SECOND(); + Py_INCREF(w); + v = THIRD(); + Py_INCREF(v); + STACKADJ(3); + SET_TOP(x); + SET_SECOND(w); + SET_THIRD(v); + FAST_DISPATCH(); + } + Py_FatalError("invalid argument to DUP_TOPX" + " (bytecode corruption?)"); + /* Never returns, so don't bother to set why. */ + break; + + TARGET(UNARY_POSITIVE) + v = TOP(); + x = PyNumber_Positive(v); + Py_DECREF(v); + SET_TOP(x); + if (x != NULL) DISPATCH(); + break; + + TARGET(UNARY_NEGATIVE) + v = TOP(); + x = PyNumber_Negative(v); + Py_DECREF(v); + SET_TOP(x); + if (x != NULL) DISPATCH(); + break; + + TARGET(UNARY_NOT) + v = TOP(); + err = PyObject_IsTrue(v); + Py_DECREF(v); + if (err == 0) { + Py_INCREF(Py_True); + SET_TOP(Py_True); + DISPATCH(); + } + else if (err > 0) { + Py_INCREF(Py_False); + SET_TOP(Py_False); + err = 0; + DISPATCH(); + } + STACKADJ(-1); + break; + + TARGET(UNARY_INVERT) + v = TOP(); + x = PyNumber_Invert(v); + Py_DECREF(v); + SET_TOP(x); + if (x != NULL) DISPATCH(); + break; + + TARGET(BINARY_POWER) + w = POP(); + v = TOP(); + x = PyNumber_Power(v, w, Py_None); + Py_DECREF(v); + Py_DECREF(w); + SET_TOP(x); + if (x != NULL) DISPATCH(); + break; + + TARGET(BINARY_MULTIPLY) + w = POP(); + v = TOP(); + x = PyNumber_Multiply(v, w); + Py_DECREF(v); + Py_DECREF(w); + SET_TOP(x); + if (x != NULL) DISPATCH(); + break; + + TARGET(BINARY_TRUE_DIVIDE) + w = POP(); + v = TOP(); + x = PyNumber_TrueDivide(v, w); + Py_DECREF(v); + Py_DECREF(w); + SET_TOP(x); + if (x != NULL) DISPATCH(); + break; + + TARGET(BINARY_FLOOR_DIVIDE) + w = POP(); + v = TOP(); + x = PyNumber_FloorDivide(v, w); + Py_DECREF(v); + Py_DECREF(w); + SET_TOP(x); + if (x != NULL) DISPATCH(); + break; + + TARGET(BINARY_MODULO) + w = POP(); + v = TOP(); + if (PyUnicode_CheckExact(v)) + x = PyUnicode_Format(v, w); + else + x = PyNumber_Remainder(v, w); + Py_DECREF(v); + Py_DECREF(w); + SET_TOP(x); + if (x != NULL) DISPATCH(); + break; + + TARGET(BINARY_ADD) + w = POP(); + v = TOP(); + if (PyUnicode_CheckExact(v) && + PyUnicode_CheckExact(w)) { + x = unicode_concatenate(v, w, f, next_instr); + /* unicode_concatenate consumed the ref to v */ + goto skip_decref_vx; + } + else { + x = PyNumber_Add(v, w); + } + Py_DECREF(v); + skip_decref_vx: + Py_DECREF(w); + SET_TOP(x); + if (x != NULL) DISPATCH(); + break; + + TARGET(BINARY_SUBTRACT) + w = POP(); + v = TOP(); + x = PyNumber_Subtract(v, w); + Py_DECREF(v); + Py_DECREF(w); + SET_TOP(x); + if (x != NULL) DISPATCH(); + break; + + TARGET(BINARY_SUBSCR) + w = POP(); + v = TOP(); + x = PyObject_GetItem(v, w); + Py_DECREF(v); + Py_DECREF(w); + SET_TOP(x); + if (x != NULL) DISPATCH(); + break; + + TARGET(BINARY_LSHIFT) + w = POP(); + v = TOP(); + x = PyNumber_Lshift(v, w); + Py_DECREF(v); + Py_DECREF(w); + SET_TOP(x); + if (x != NULL) DISPATCH(); + break; + + TARGET(BINARY_RSHIFT) + w = POP(); + v = TOP(); + x = PyNumber_Rshift(v, w); + Py_DECREF(v); + Py_DECREF(w); + SET_TOP(x); + if (x != NULL) DISPATCH(); + break; + + TARGET(BINARY_AND) + w = POP(); + v = TOP(); + x = PyNumber_And(v, w); + Py_DECREF(v); + Py_DECREF(w); + SET_TOP(x); + if (x != NULL) DISPATCH(); + break; + + TARGET(BINARY_XOR) + w = POP(); + v = TOP(); + x = PyNumber_Xor(v, w); + Py_DECREF(v); + Py_DECREF(w); + SET_TOP(x); + if (x != NULL) DISPATCH(); + break; + + TARGET(BINARY_OR) + w = POP(); + v = TOP(); + x = PyNumber_Or(v, w); + Py_DECREF(v); + Py_DECREF(w); + SET_TOP(x); + if (x != NULL) DISPATCH(); + break; + + TARGET(LIST_APPEND) + w = POP(); + v = stack_pointer[-oparg]; + err = PyList_Append(v, w); + Py_DECREF(w); + if (err == 0) { + PREDICT(JUMP_ABSOLUTE); + DISPATCH(); + } + break; + + TARGET(SET_ADD) + w = POP(); + v = stack_pointer[-oparg]; + err = PySet_Add(v, w); + Py_DECREF(w); + if (err == 0) { + PREDICT(JUMP_ABSOLUTE); + DISPATCH(); + } + break; + + TARGET(INPLACE_POWER) + w = POP(); + v = TOP(); + x = PyNumber_InPlacePower(v, w, Py_None); + Py_DECREF(v); + Py_DECREF(w); + SET_TOP(x); + if (x != NULL) DISPATCH(); + break; + + TARGET(INPLACE_MULTIPLY) + w = POP(); + v = TOP(); + x = PyNumber_InPlaceMultiply(v, w); + Py_DECREF(v); + Py_DECREF(w); + SET_TOP(x); + if (x != NULL) DISPATCH(); + break; + + TARGET(INPLACE_TRUE_DIVIDE) + w = POP(); + v = TOP(); + x = PyNumber_InPlaceTrueDivide(v, w); + Py_DECREF(v); + Py_DECREF(w); + SET_TOP(x); + if (x != NULL) DISPATCH(); + break; + + TARGET(INPLACE_FLOOR_DIVIDE) + w = POP(); + v = TOP(); + x = PyNumber_InPlaceFloorDivide(v, w); + Py_DECREF(v); + Py_DECREF(w); + SET_TOP(x); + if (x != NULL) DISPATCH(); + break; + + TARGET(INPLACE_MODULO) + w = POP(); + v = TOP(); + x = PyNumber_InPlaceRemainder(v, w); + Py_DECREF(v); + Py_DECREF(w); + SET_TOP(x); + if (x != NULL) DISPATCH(); + break; + + TARGET(INPLACE_ADD) + w = POP(); + v = TOP(); + if (PyUnicode_CheckExact(v) && + PyUnicode_CheckExact(w)) { + x = unicode_concatenate(v, w, f, next_instr); + /* unicode_concatenate consumed the ref to v */ + goto skip_decref_v; + } + else { + x = PyNumber_InPlaceAdd(v, w); + } + Py_DECREF(v); + skip_decref_v: + Py_DECREF(w); + SET_TOP(x); + if (x != NULL) DISPATCH(); + break; + + TARGET(INPLACE_SUBTRACT) + w = POP(); + v = TOP(); + x = PyNumber_InPlaceSubtract(v, w); + Py_DECREF(v); + Py_DECREF(w); + SET_TOP(x); + if (x != NULL) DISPATCH(); + break; + + TARGET(INPLACE_LSHIFT) + w = POP(); + v = TOP(); + x = PyNumber_InPlaceLshift(v, w); + Py_DECREF(v); + Py_DECREF(w); + SET_TOP(x); + if (x != NULL) DISPATCH(); + break; + + TARGET(INPLACE_RSHIFT) + w = POP(); + v = TOP(); + x = PyNumber_InPlaceRshift(v, w); + Py_DECREF(v); + Py_DECREF(w); + SET_TOP(x); + if (x != NULL) DISPATCH(); + break; + + TARGET(INPLACE_AND) + w = POP(); + v = TOP(); + x = PyNumber_InPlaceAnd(v, w); + Py_DECREF(v); + Py_DECREF(w); + SET_TOP(x); + if (x != NULL) DISPATCH(); + break; + + TARGET(INPLACE_XOR) + w = POP(); + v = TOP(); + x = PyNumber_InPlaceXor(v, w); + Py_DECREF(v); + Py_DECREF(w); + SET_TOP(x); + if (x != NULL) DISPATCH(); + break; + + TARGET(INPLACE_OR) + w = POP(); + v = TOP(); + x = PyNumber_InPlaceOr(v, w); + Py_DECREF(v); + Py_DECREF(w); + SET_TOP(x); + if (x != NULL) DISPATCH(); + break; + + TARGET(STORE_SUBSCR) + w = TOP(); + v = SECOND(); + u = THIRD(); + STACKADJ(-3); + /* v[w] = u */ + err = PyObject_SetItem(v, w, u); + Py_DECREF(u); + Py_DECREF(v); + Py_DECREF(w); + if (err == 0) DISPATCH(); + break; + + TARGET(DELETE_SUBSCR) + w = TOP(); + v = SECOND(); + STACKADJ(-2); + /* del v[w] */ + err = PyObject_DelItem(v, w); + Py_DECREF(v); + Py_DECREF(w); + if (err == 0) DISPATCH(); + break; + + TARGET(PRINT_EXPR) + v = POP(); + w = PySys_GetObject("displayhook"); + if (w == NULL) { + PyErr_SetString(PyExc_RuntimeError, + "lost sys.displayhook"); + err = -1; + x = NULL; + } + if (err == 0) { + x = PyTuple_Pack(1, v); + if (x == NULL) + err = -1; + } + if (err == 0) { + w = PyEval_CallObject(w, x); + Py_XDECREF(w); + if (w == NULL) + err = -1; + } + Py_DECREF(v); + Py_XDECREF(x); + break; #ifdef CASE_TOO_BIG - default: switch (opcode) { + default: switch (opcode) { #endif - TARGET(RAISE_VARARGS) - v = w = NULL; - switch (oparg) { - case 2: - v = POP(); /* cause */ - case 1: - w = POP(); /* exc */ - case 0: /* Fallthrough */ - why = do_raise(w, v); - break; - default: - PyErr_SetString(PyExc_SystemError, - "bad RAISE_VARARGS oparg"); - why = WHY_EXCEPTION; - break; - } - break; - - TARGET(STORE_LOCALS) - x = POP(); - v = f->f_locals; - Py_XDECREF(v); - f->f_locals = x; - DISPATCH(); - - TARGET(RETURN_VALUE) - retval = POP(); - why = WHY_RETURN; - goto fast_block_end; - - TARGET(YIELD_VALUE) - retval = POP(); - f->f_stacktop = stack_pointer; - why = WHY_YIELD; - /* Put aside the current exception state and restore - that of the calling frame. This only serves when - "yield" is used inside an except handler. */ - SWAP_EXC_STATE(); - goto fast_yield; - - TARGET(POP_EXCEPT) - { - PyTryBlock *b = PyFrame_BlockPop(f); - if (b->b_type != EXCEPT_HANDLER) { - PyErr_SetString(PyExc_SystemError, - "popped block is not an except handler"); - why = WHY_EXCEPTION; - break; - } - UNWIND_EXCEPT_HANDLER(b); - } - DISPATCH(); - - TARGET(POP_BLOCK) - { - PyTryBlock *b = PyFrame_BlockPop(f); - UNWIND_BLOCK(b); - } - DISPATCH(); - - PREDICTED(END_FINALLY); - TARGET(END_FINALLY) - v = POP(); - if (PyLong_Check(v)) { - why = (enum why_code) PyLong_AS_LONG(v); - assert(why != WHY_YIELD); - if (why == WHY_RETURN || - why == WHY_CONTINUE) - retval = POP(); - if (why == WHY_SILENCED) { - /* An exception was silenced by 'with', we must - manually unwind the EXCEPT_HANDLER block which was - created when the exception was caught, otherwise - the stack will be in an inconsistent state. */ - PyTryBlock *b = PyFrame_BlockPop(f); - if (b->b_type != EXCEPT_HANDLER) { - PyErr_SetString(PyExc_SystemError, - "popped block is not an except handler"); - why = WHY_EXCEPTION; - } - else { - UNWIND_EXCEPT_HANDLER(b); - why = WHY_NOT; - } - } - } - else if (PyExceptionClass_Check(v)) { - w = POP(); - u = POP(); - PyErr_Restore(v, w, u); - why = WHY_RERAISE; - break; - } - else if (v != Py_None) { - PyErr_SetString(PyExc_SystemError, - "'finally' pops bad exception"); - why = WHY_EXCEPTION; - } - Py_DECREF(v); - break; - - TARGET(LOAD_BUILD_CLASS) - x = PyDict_GetItemString(f->f_builtins, - "__build_class__"); - if (x == NULL) { - PyErr_SetString(PyExc_ImportError, - "__build_class__ not found"); - break; - } - Py_INCREF(x); - PUSH(x); - break; - - TARGET(STORE_NAME) - w = GETITEM(names, oparg); - v = POP(); - if ((x = f->f_locals) != NULL) { - if (PyDict_CheckExact(x)) - err = PyDict_SetItem(x, w, v); - else - err = PyObject_SetItem(x, w, v); - Py_DECREF(v); - if (err == 0) DISPATCH(); - break; - } - PyErr_Format(PyExc_SystemError, - "no locals found when storing %R", w); - break; - - TARGET(DELETE_NAME) - w = GETITEM(names, oparg); - if ((x = f->f_locals) != NULL) { - if ((err = PyObject_DelItem(x, w)) != 0) - format_exc_check_arg(PyExc_NameError, - NAME_ERROR_MSG, - w); - break; - } - PyErr_Format(PyExc_SystemError, - "no locals when deleting %R", w); - break; - - PREDICTED_WITH_ARG(UNPACK_SEQUENCE); - TARGET(UNPACK_SEQUENCE) - v = POP(); - if (PyTuple_CheckExact(v) && - PyTuple_GET_SIZE(v) == oparg) { - PyObject **items = \ - ((PyTupleObject *)v)->ob_item; - while (oparg--) { - w = items[oparg]; - Py_INCREF(w); - PUSH(w); - } - Py_DECREF(v); - DISPATCH(); - } else if (PyList_CheckExact(v) && - PyList_GET_SIZE(v) == oparg) { - PyObject **items = \ - ((PyListObject *)v)->ob_item; - while (oparg--) { - w = items[oparg]; - Py_INCREF(w); - PUSH(w); - } - } else if (unpack_iterable(v, oparg, -1, - stack_pointer + oparg)) { - stack_pointer += oparg; - } else { - /* unpack_iterable() raised an exception */ - why = WHY_EXCEPTION; - } - Py_DECREF(v); - break; - - TARGET(UNPACK_EX) - { - int totalargs = 1 + (oparg & 0xFF) + (oparg >> 8); - v = POP(); - - if (unpack_iterable(v, oparg & 0xFF, oparg >> 8, - stack_pointer + totalargs)) { - stack_pointer += totalargs; - } else { - why = WHY_EXCEPTION; - } - Py_DECREF(v); - break; - } - - TARGET(STORE_ATTR) - w = GETITEM(names, oparg); - v = TOP(); - u = SECOND(); - STACKADJ(-2); - err = PyObject_SetAttr(v, w, u); /* v.w = u */ - Py_DECREF(v); - Py_DECREF(u); - if (err == 0) DISPATCH(); - break; - - TARGET(DELETE_ATTR) - w = GETITEM(names, oparg); - v = POP(); - err = PyObject_SetAttr(v, w, (PyObject *)NULL); - /* del v.w */ - Py_DECREF(v); - break; - - TARGET(STORE_GLOBAL) - w = GETITEM(names, oparg); - v = POP(); - err = PyDict_SetItem(f->f_globals, w, v); - Py_DECREF(v); - if (err == 0) DISPATCH(); - break; - - TARGET(DELETE_GLOBAL) - w = GETITEM(names, oparg); - if ((err = PyDict_DelItem(f->f_globals, w)) != 0) - format_exc_check_arg( - PyExc_NameError, GLOBAL_NAME_ERROR_MSG, w); - break; - - TARGET(LOAD_NAME) - w = GETITEM(names, oparg); - if ((v = f->f_locals) == NULL) { - PyErr_Format(PyExc_SystemError, - "no locals when loading %R", w); - why = WHY_EXCEPTION; - break; - } - if (PyDict_CheckExact(v)) { - x = PyDict_GetItem(v, w); - Py_XINCREF(x); - } - else { - x = PyObject_GetItem(v, w); - if (x == NULL && PyErr_Occurred()) { - if (!PyErr_ExceptionMatches( - PyExc_KeyError)) - break; - PyErr_Clear(); - } - } - if (x == NULL) { - x = PyDict_GetItem(f->f_globals, w); - if (x == NULL) { - x = PyDict_GetItem(f->f_builtins, w); - if (x == NULL) { - format_exc_check_arg( - PyExc_NameError, - NAME_ERROR_MSG, w); - break; - } - } - Py_INCREF(x); - } - PUSH(x); - DISPATCH(); - - TARGET(LOAD_GLOBAL) - w = GETITEM(names, oparg); - if (PyUnicode_CheckExact(w)) { - /* Inline the PyDict_GetItem() calls. - WARNING: this is an extreme speed hack. - Do not try this at home. */ - long hash = ((PyUnicodeObject *)w)->hash; - if (hash != -1) { - PyDictObject *d; - PyDictEntry *e; - d = (PyDictObject *)(f->f_globals); - e = d->ma_lookup(d, w, hash); - if (e == NULL) { - x = NULL; - break; - } - x = e->me_value; - if (x != NULL) { - Py_INCREF(x); - PUSH(x); - DISPATCH(); - } - d = (PyDictObject *)(f->f_builtins); - e = d->ma_lookup(d, w, hash); - if (e == NULL) { - x = NULL; - break; - } - x = e->me_value; - if (x != NULL) { - Py_INCREF(x); - PUSH(x); - DISPATCH(); - } - goto load_global_error; - } - } - /* This is the un-inlined version of the code above */ - x = PyDict_GetItem(f->f_globals, w); - if (x == NULL) { - x = PyDict_GetItem(f->f_builtins, w); - if (x == NULL) { - load_global_error: - format_exc_check_arg( - PyExc_NameError, - GLOBAL_NAME_ERROR_MSG, w); - break; - } - } - Py_INCREF(x); - PUSH(x); - DISPATCH(); - - TARGET(DELETE_FAST) - x = GETLOCAL(oparg); - if (x != NULL) { - SETLOCAL(oparg, NULL); - DISPATCH(); - } - format_exc_check_arg( - PyExc_UnboundLocalError, - UNBOUNDLOCAL_ERROR_MSG, - PyTuple_GetItem(co->co_varnames, oparg) - ); - break; - - TARGET(LOAD_CLOSURE) - x = freevars[oparg]; - Py_INCREF(x); - PUSH(x); - if (x != NULL) DISPATCH(); - break; - - TARGET(LOAD_DEREF) - x = freevars[oparg]; - w = PyCell_Get(x); - if (w != NULL) { - PUSH(w); - DISPATCH(); - } - err = -1; - /* Don't stomp existing exception */ - if (PyErr_Occurred()) - break; - if (oparg < PyTuple_GET_SIZE(co->co_cellvars)) { - v = PyTuple_GET_ITEM(co->co_cellvars, - oparg); - format_exc_check_arg( - PyExc_UnboundLocalError, - UNBOUNDLOCAL_ERROR_MSG, - v); - } else { - v = PyTuple_GET_ITEM(co->co_freevars, oparg - - PyTuple_GET_SIZE(co->co_cellvars)); - format_exc_check_arg(PyExc_NameError, - UNBOUNDFREE_ERROR_MSG, v); - } - break; - - TARGET(STORE_DEREF) - w = POP(); - x = freevars[oparg]; - PyCell_Set(x, w); - Py_DECREF(w); - DISPATCH(); - - TARGET(BUILD_TUPLE) - x = PyTuple_New(oparg); - if (x != NULL) { - for (; --oparg >= 0;) { - w = POP(); - PyTuple_SET_ITEM(x, oparg, w); - } - PUSH(x); - DISPATCH(); - } - break; - - TARGET(BUILD_LIST) - x = PyList_New(oparg); - if (x != NULL) { - for (; --oparg >= 0;) { - w = POP(); - PyList_SET_ITEM(x, oparg, w); - } - PUSH(x); - DISPATCH(); - } - break; - - TARGET(BUILD_SET) - x = PySet_New(NULL); - if (x != NULL) { - for (; --oparg >= 0;) { - w = POP(); - if (err == 0) - err = PySet_Add(x, w); - Py_DECREF(w); - } - if (err != 0) { - Py_DECREF(x); - break; - } - PUSH(x); - DISPATCH(); - } - break; - - TARGET(BUILD_MAP) - x = _PyDict_NewPresized((Py_ssize_t)oparg); - PUSH(x); - if (x != NULL) DISPATCH(); - break; - - TARGET(STORE_MAP) - w = TOP(); /* key */ - u = SECOND(); /* value */ - v = THIRD(); /* dict */ - STACKADJ(-2); - assert (PyDict_CheckExact(v)); - err = PyDict_SetItem(v, w, u); /* v[w] = u */ - Py_DECREF(u); - Py_DECREF(w); - if (err == 0) DISPATCH(); - break; - - TARGET(MAP_ADD) - w = TOP(); /* key */ - u = SECOND(); /* value */ - STACKADJ(-2); - v = stack_pointer[-oparg]; /* dict */ - assert (PyDict_CheckExact(v)); - err = PyDict_SetItem(v, w, u); /* v[w] = u */ - Py_DECREF(u); - Py_DECREF(w); - if (err == 0) { - PREDICT(JUMP_ABSOLUTE); - DISPATCH(); - } - break; - - TARGET(LOAD_ATTR) - w = GETITEM(names, oparg); - v = TOP(); - x = PyObject_GetAttr(v, w); - Py_DECREF(v); - SET_TOP(x); - if (x != NULL) DISPATCH(); - break; - - TARGET(COMPARE_OP) - w = POP(); - v = TOP(); - x = cmp_outcome(oparg, v, w); - Py_DECREF(v); - Py_DECREF(w); - SET_TOP(x); - if (x == NULL) break; - PREDICT(POP_JUMP_IF_FALSE); - PREDICT(POP_JUMP_IF_TRUE); - DISPATCH(); - - TARGET(IMPORT_NAME) - w = GETITEM(names, oparg); - x = PyDict_GetItemString(f->f_builtins, "__import__"); - if (x == NULL) { - PyErr_SetString(PyExc_ImportError, - "__import__ not found"); - break; - } - Py_INCREF(x); - v = POP(); - u = TOP(); - if (PyLong_AsLong(u) != -1 || PyErr_Occurred()) - w = PyTuple_Pack(5, - w, - f->f_globals, - f->f_locals == NULL ? - Py_None : f->f_locals, - v, - u); - else - w = PyTuple_Pack(4, - w, - f->f_globals, - f->f_locals == NULL ? - Py_None : f->f_locals, - v); - Py_DECREF(v); - Py_DECREF(u); - if (w == NULL) { - u = POP(); - Py_DECREF(x); - x = NULL; - break; - } - READ_TIMESTAMP(intr0); - v = x; - x = PyEval_CallObject(v, w); - Py_DECREF(v); - READ_TIMESTAMP(intr1); - Py_DECREF(w); - SET_TOP(x); - if (x != NULL) DISPATCH(); - break; - - TARGET(IMPORT_STAR) - v = POP(); - PyFrame_FastToLocals(f); - if ((x = f->f_locals) == NULL) { - PyErr_SetString(PyExc_SystemError, - "no locals found during 'import *'"); - break; - } - READ_TIMESTAMP(intr0); - err = import_all_from(x, v); - READ_TIMESTAMP(intr1); - PyFrame_LocalsToFast(f, 0); - Py_DECREF(v); - if (err == 0) DISPATCH(); - break; - - TARGET(IMPORT_FROM) - w = GETITEM(names, oparg); - v = TOP(); - READ_TIMESTAMP(intr0); - x = import_from(v, w); - READ_TIMESTAMP(intr1); - PUSH(x); - if (x != NULL) DISPATCH(); - break; - - TARGET(JUMP_FORWARD) - JUMPBY(oparg); - FAST_DISPATCH(); - - PREDICTED_WITH_ARG(POP_JUMP_IF_FALSE); - TARGET(POP_JUMP_IF_FALSE) - w = POP(); - if (w == Py_True) { - Py_DECREF(w); - FAST_DISPATCH(); - } - if (w == Py_False) { - Py_DECREF(w); - JUMPTO(oparg); - FAST_DISPATCH(); - } - err = PyObject_IsTrue(w); - Py_DECREF(w); - if (err > 0) - err = 0; - else if (err == 0) - JUMPTO(oparg); - else - break; - DISPATCH(); - - PREDICTED_WITH_ARG(POP_JUMP_IF_TRUE); - TARGET(POP_JUMP_IF_TRUE) - w = POP(); - if (w == Py_False) { - Py_DECREF(w); - FAST_DISPATCH(); - } - if (w == Py_True) { - Py_DECREF(w); - JUMPTO(oparg); - FAST_DISPATCH(); - } - err = PyObject_IsTrue(w); - Py_DECREF(w); - if (err > 0) { - err = 0; - JUMPTO(oparg); - } - else if (err == 0) - ; - else - break; - DISPATCH(); - - TARGET(JUMP_IF_FALSE_OR_POP) - w = TOP(); - if (w == Py_True) { - STACKADJ(-1); - Py_DECREF(w); - FAST_DISPATCH(); - } - if (w == Py_False) { - JUMPTO(oparg); - FAST_DISPATCH(); - } - err = PyObject_IsTrue(w); - if (err > 0) { - STACKADJ(-1); - Py_DECREF(w); - err = 0; - } - else if (err == 0) - JUMPTO(oparg); - else - break; - DISPATCH(); - - TARGET(JUMP_IF_TRUE_OR_POP) - w = TOP(); - if (w == Py_False) { - STACKADJ(-1); - Py_DECREF(w); - FAST_DISPATCH(); - } - if (w == Py_True) { - JUMPTO(oparg); - FAST_DISPATCH(); - } - err = PyObject_IsTrue(w); - if (err > 0) { - err = 0; - JUMPTO(oparg); - } - else if (err == 0) { - STACKADJ(-1); - Py_DECREF(w); - } - else - break; - DISPATCH(); - - PREDICTED_WITH_ARG(JUMP_ABSOLUTE); - TARGET(JUMP_ABSOLUTE) - JUMPTO(oparg); + TARGET(RAISE_VARARGS) + v = w = NULL; + switch (oparg) { + case 2: + v = POP(); /* cause */ + case 1: + w = POP(); /* exc */ + case 0: /* Fallthrough */ + why = do_raise(w, v); + break; + default: + PyErr_SetString(PyExc_SystemError, + "bad RAISE_VARARGS oparg"); + why = WHY_EXCEPTION; + break; + } + break; + + TARGET(STORE_LOCALS) + x = POP(); + v = f->f_locals; + Py_XDECREF(v); + f->f_locals = x; + DISPATCH(); + + TARGET(RETURN_VALUE) + retval = POP(); + why = WHY_RETURN; + goto fast_block_end; + + TARGET(YIELD_VALUE) + retval = POP(); + f->f_stacktop = stack_pointer; + why = WHY_YIELD; + /* Put aside the current exception state and restore + that of the calling frame. This only serves when + "yield" is used inside an except handler. */ + SWAP_EXC_STATE(); + goto fast_yield; + + TARGET(POP_EXCEPT) + { + PyTryBlock *b = PyFrame_BlockPop(f); + if (b->b_type != EXCEPT_HANDLER) { + PyErr_SetString(PyExc_SystemError, + "popped block is not an except handler"); + why = WHY_EXCEPTION; + break; + } + UNWIND_EXCEPT_HANDLER(b); + } + DISPATCH(); + + TARGET(POP_BLOCK) + { + PyTryBlock *b = PyFrame_BlockPop(f); + UNWIND_BLOCK(b); + } + DISPATCH(); + + PREDICTED(END_FINALLY); + TARGET(END_FINALLY) + v = POP(); + if (PyLong_Check(v)) { + why = (enum why_code) PyLong_AS_LONG(v); + assert(why != WHY_YIELD); + if (why == WHY_RETURN || + why == WHY_CONTINUE) + retval = POP(); + if (why == WHY_SILENCED) { + /* An exception was silenced by 'with', we must + manually unwind the EXCEPT_HANDLER block which was + created when the exception was caught, otherwise + the stack will be in an inconsistent state. */ + PyTryBlock *b = PyFrame_BlockPop(f); + if (b->b_type != EXCEPT_HANDLER) { + PyErr_SetString(PyExc_SystemError, + "popped block is not an except handler"); + why = WHY_EXCEPTION; + } + else { + UNWIND_EXCEPT_HANDLER(b); + why = WHY_NOT; + } + } + } + else if (PyExceptionClass_Check(v)) { + w = POP(); + u = POP(); + PyErr_Restore(v, w, u); + why = WHY_RERAISE; + break; + } + else if (v != Py_None) { + PyErr_SetString(PyExc_SystemError, + "'finally' pops bad exception"); + why = WHY_EXCEPTION; + } + Py_DECREF(v); + break; + + TARGET(LOAD_BUILD_CLASS) + x = PyDict_GetItemString(f->f_builtins, + "__build_class__"); + if (x == NULL) { + PyErr_SetString(PyExc_ImportError, + "__build_class__ not found"); + break; + } + Py_INCREF(x); + PUSH(x); + break; + + TARGET(STORE_NAME) + w = GETITEM(names, oparg); + v = POP(); + if ((x = f->f_locals) != NULL) { + if (PyDict_CheckExact(x)) + err = PyDict_SetItem(x, w, v); + else + err = PyObject_SetItem(x, w, v); + Py_DECREF(v); + if (err == 0) DISPATCH(); + break; + } + PyErr_Format(PyExc_SystemError, + "no locals found when storing %R", w); + break; + + TARGET(DELETE_NAME) + w = GETITEM(names, oparg); + if ((x = f->f_locals) != NULL) { + if ((err = PyObject_DelItem(x, w)) != 0) + format_exc_check_arg(PyExc_NameError, + NAME_ERROR_MSG, + w); + break; + } + PyErr_Format(PyExc_SystemError, + "no locals when deleting %R", w); + break; + + PREDICTED_WITH_ARG(UNPACK_SEQUENCE); + TARGET(UNPACK_SEQUENCE) + v = POP(); + if (PyTuple_CheckExact(v) && + PyTuple_GET_SIZE(v) == oparg) { + PyObject **items = \ + ((PyTupleObject *)v)->ob_item; + while (oparg--) { + w = items[oparg]; + Py_INCREF(w); + PUSH(w); + } + Py_DECREF(v); + DISPATCH(); + } else if (PyList_CheckExact(v) && + PyList_GET_SIZE(v) == oparg) { + PyObject **items = \ + ((PyListObject *)v)->ob_item; + while (oparg--) { + w = items[oparg]; + Py_INCREF(w); + PUSH(w); + } + } else if (unpack_iterable(v, oparg, -1, + stack_pointer + oparg)) { + stack_pointer += oparg; + } else { + /* unpack_iterable() raised an exception */ + why = WHY_EXCEPTION; + } + Py_DECREF(v); + break; + + TARGET(UNPACK_EX) + { + int totalargs = 1 + (oparg & 0xFF) + (oparg >> 8); + v = POP(); + + if (unpack_iterable(v, oparg & 0xFF, oparg >> 8, + stack_pointer + totalargs)) { + stack_pointer += totalargs; + } else { + why = WHY_EXCEPTION; + } + Py_DECREF(v); + break; + } + + TARGET(STORE_ATTR) + w = GETITEM(names, oparg); + v = TOP(); + u = SECOND(); + STACKADJ(-2); + err = PyObject_SetAttr(v, w, u); /* v.w = u */ + Py_DECREF(v); + Py_DECREF(u); + if (err == 0) DISPATCH(); + break; + + TARGET(DELETE_ATTR) + w = GETITEM(names, oparg); + v = POP(); + err = PyObject_SetAttr(v, w, (PyObject *)NULL); + /* del v.w */ + Py_DECREF(v); + break; + + TARGET(STORE_GLOBAL) + w = GETITEM(names, oparg); + v = POP(); + err = PyDict_SetItem(f->f_globals, w, v); + Py_DECREF(v); + if (err == 0) DISPATCH(); + break; + + TARGET(DELETE_GLOBAL) + w = GETITEM(names, oparg); + if ((err = PyDict_DelItem(f->f_globals, w)) != 0) + format_exc_check_arg( + PyExc_NameError, GLOBAL_NAME_ERROR_MSG, w); + break; + + TARGET(LOAD_NAME) + w = GETITEM(names, oparg); + if ((v = f->f_locals) == NULL) { + PyErr_Format(PyExc_SystemError, + "no locals when loading %R", w); + why = WHY_EXCEPTION; + break; + } + if (PyDict_CheckExact(v)) { + x = PyDict_GetItem(v, w); + Py_XINCREF(x); + } + else { + x = PyObject_GetItem(v, w); + if (x == NULL && PyErr_Occurred()) { + if (!PyErr_ExceptionMatches( + PyExc_KeyError)) + break; + PyErr_Clear(); + } + } + if (x == NULL) { + x = PyDict_GetItem(f->f_globals, w); + if (x == NULL) { + x = PyDict_GetItem(f->f_builtins, w); + if (x == NULL) { + format_exc_check_arg( + PyExc_NameError, + NAME_ERROR_MSG, w); + break; + } + } + Py_INCREF(x); + } + PUSH(x); + DISPATCH(); + + TARGET(LOAD_GLOBAL) + w = GETITEM(names, oparg); + if (PyUnicode_CheckExact(w)) { + /* Inline the PyDict_GetItem() calls. + WARNING: this is an extreme speed hack. + Do not try this at home. */ + long hash = ((PyUnicodeObject *)w)->hash; + if (hash != -1) { + PyDictObject *d; + PyDictEntry *e; + d = (PyDictObject *)(f->f_globals); + e = d->ma_lookup(d, w, hash); + if (e == NULL) { + x = NULL; + break; + } + x = e->me_value; + if (x != NULL) { + Py_INCREF(x); + PUSH(x); + DISPATCH(); + } + d = (PyDictObject *)(f->f_builtins); + e = d->ma_lookup(d, w, hash); + if (e == NULL) { + x = NULL; + break; + } + x = e->me_value; + if (x != NULL) { + Py_INCREF(x); + PUSH(x); + DISPATCH(); + } + goto load_global_error; + } + } + /* This is the un-inlined version of the code above */ + x = PyDict_GetItem(f->f_globals, w); + if (x == NULL) { + x = PyDict_GetItem(f->f_builtins, w); + if (x == NULL) { + load_global_error: + format_exc_check_arg( + PyExc_NameError, + GLOBAL_NAME_ERROR_MSG, w); + break; + } + } + Py_INCREF(x); + PUSH(x); + DISPATCH(); + + TARGET(DELETE_FAST) + x = GETLOCAL(oparg); + if (x != NULL) { + SETLOCAL(oparg, NULL); + DISPATCH(); + } + format_exc_check_arg( + PyExc_UnboundLocalError, + UNBOUNDLOCAL_ERROR_MSG, + PyTuple_GetItem(co->co_varnames, oparg) + ); + break; + + TARGET(LOAD_CLOSURE) + x = freevars[oparg]; + Py_INCREF(x); + PUSH(x); + if (x != NULL) DISPATCH(); + break; + + TARGET(LOAD_DEREF) + x = freevars[oparg]; + w = PyCell_Get(x); + if (w != NULL) { + PUSH(w); + DISPATCH(); + } + err = -1; + /* Don't stomp existing exception */ + if (PyErr_Occurred()) + break; + if (oparg < PyTuple_GET_SIZE(co->co_cellvars)) { + v = PyTuple_GET_ITEM(co->co_cellvars, + oparg); + format_exc_check_arg( + PyExc_UnboundLocalError, + UNBOUNDLOCAL_ERROR_MSG, + v); + } else { + v = PyTuple_GET_ITEM(co->co_freevars, oparg - + PyTuple_GET_SIZE(co->co_cellvars)); + format_exc_check_arg(PyExc_NameError, + UNBOUNDFREE_ERROR_MSG, v); + } + break; + + TARGET(STORE_DEREF) + w = POP(); + x = freevars[oparg]; + PyCell_Set(x, w); + Py_DECREF(w); + DISPATCH(); + + TARGET(BUILD_TUPLE) + x = PyTuple_New(oparg); + if (x != NULL) { + for (; --oparg >= 0;) { + w = POP(); + PyTuple_SET_ITEM(x, oparg, w); + } + PUSH(x); + DISPATCH(); + } + break; + + TARGET(BUILD_LIST) + x = PyList_New(oparg); + if (x != NULL) { + for (; --oparg >= 0;) { + w = POP(); + PyList_SET_ITEM(x, oparg, w); + } + PUSH(x); + DISPATCH(); + } + break; + + TARGET(BUILD_SET) + x = PySet_New(NULL); + if (x != NULL) { + for (; --oparg >= 0;) { + w = POP(); + if (err == 0) + err = PySet_Add(x, w); + Py_DECREF(w); + } + if (err != 0) { + Py_DECREF(x); + break; + } + PUSH(x); + DISPATCH(); + } + break; + + TARGET(BUILD_MAP) + x = _PyDict_NewPresized((Py_ssize_t)oparg); + PUSH(x); + if (x != NULL) DISPATCH(); + break; + + TARGET(STORE_MAP) + w = TOP(); /* key */ + u = SECOND(); /* value */ + v = THIRD(); /* dict */ + STACKADJ(-2); + assert (PyDict_CheckExact(v)); + err = PyDict_SetItem(v, w, u); /* v[w] = u */ + Py_DECREF(u); + Py_DECREF(w); + if (err == 0) DISPATCH(); + break; + + TARGET(MAP_ADD) + w = TOP(); /* key */ + u = SECOND(); /* value */ + STACKADJ(-2); + v = stack_pointer[-oparg]; /* dict */ + assert (PyDict_CheckExact(v)); + err = PyDict_SetItem(v, w, u); /* v[w] = u */ + Py_DECREF(u); + Py_DECREF(w); + if (err == 0) { + PREDICT(JUMP_ABSOLUTE); + DISPATCH(); + } + break; + + TARGET(LOAD_ATTR) + w = GETITEM(names, oparg); + v = TOP(); + x = PyObject_GetAttr(v, w); + Py_DECREF(v); + SET_TOP(x); + if (x != NULL) DISPATCH(); + break; + + TARGET(COMPARE_OP) + w = POP(); + v = TOP(); + x = cmp_outcome(oparg, v, w); + Py_DECREF(v); + Py_DECREF(w); + SET_TOP(x); + if (x == NULL) break; + PREDICT(POP_JUMP_IF_FALSE); + PREDICT(POP_JUMP_IF_TRUE); + DISPATCH(); + + TARGET(IMPORT_NAME) + w = GETITEM(names, oparg); + x = PyDict_GetItemString(f->f_builtins, "__import__"); + if (x == NULL) { + PyErr_SetString(PyExc_ImportError, + "__import__ not found"); + break; + } + Py_INCREF(x); + v = POP(); + u = TOP(); + if (PyLong_AsLong(u) != -1 || PyErr_Occurred()) + w = PyTuple_Pack(5, + w, + f->f_globals, + f->f_locals == NULL ? + Py_None : f->f_locals, + v, + u); + else + w = PyTuple_Pack(4, + w, + f->f_globals, + f->f_locals == NULL ? + Py_None : f->f_locals, + v); + Py_DECREF(v); + Py_DECREF(u); + if (w == NULL) { + u = POP(); + Py_DECREF(x); + x = NULL; + break; + } + READ_TIMESTAMP(intr0); + v = x; + x = PyEval_CallObject(v, w); + Py_DECREF(v); + READ_TIMESTAMP(intr1); + Py_DECREF(w); + SET_TOP(x); + if (x != NULL) DISPATCH(); + break; + + TARGET(IMPORT_STAR) + v = POP(); + PyFrame_FastToLocals(f); + if ((x = f->f_locals) == NULL) { + PyErr_SetString(PyExc_SystemError, + "no locals found during 'import *'"); + break; + } + READ_TIMESTAMP(intr0); + err = import_all_from(x, v); + READ_TIMESTAMP(intr1); + PyFrame_LocalsToFast(f, 0); + Py_DECREF(v); + if (err == 0) DISPATCH(); + break; + + TARGET(IMPORT_FROM) + w = GETITEM(names, oparg); + v = TOP(); + READ_TIMESTAMP(intr0); + x = import_from(v, w); + READ_TIMESTAMP(intr1); + PUSH(x); + if (x != NULL) DISPATCH(); + break; + + TARGET(JUMP_FORWARD) + JUMPBY(oparg); + FAST_DISPATCH(); + + PREDICTED_WITH_ARG(POP_JUMP_IF_FALSE); + TARGET(POP_JUMP_IF_FALSE) + w = POP(); + if (w == Py_True) { + Py_DECREF(w); + FAST_DISPATCH(); + } + if (w == Py_False) { + Py_DECREF(w); + JUMPTO(oparg); + FAST_DISPATCH(); + } + err = PyObject_IsTrue(w); + Py_DECREF(w); + if (err > 0) + err = 0; + else if (err == 0) + JUMPTO(oparg); + else + break; + DISPATCH(); + + PREDICTED_WITH_ARG(POP_JUMP_IF_TRUE); + TARGET(POP_JUMP_IF_TRUE) + w = POP(); + if (w == Py_False) { + Py_DECREF(w); + FAST_DISPATCH(); + } + if (w == Py_True) { + Py_DECREF(w); + JUMPTO(oparg); + FAST_DISPATCH(); + } + err = PyObject_IsTrue(w); + Py_DECREF(w); + if (err > 0) { + err = 0; + JUMPTO(oparg); + } + else if (err == 0) + ; + else + break; + DISPATCH(); + + TARGET(JUMP_IF_FALSE_OR_POP) + w = TOP(); + if (w == Py_True) { + STACKADJ(-1); + Py_DECREF(w); + FAST_DISPATCH(); + } + if (w == Py_False) { + JUMPTO(oparg); + FAST_DISPATCH(); + } + err = PyObject_IsTrue(w); + if (err > 0) { + STACKADJ(-1); + Py_DECREF(w); + err = 0; + } + else if (err == 0) + JUMPTO(oparg); + else + break; + DISPATCH(); + + TARGET(JUMP_IF_TRUE_OR_POP) + w = TOP(); + if (w == Py_False) { + STACKADJ(-1); + Py_DECREF(w); + FAST_DISPATCH(); + } + if (w == Py_True) { + JUMPTO(oparg); + FAST_DISPATCH(); + } + err = PyObject_IsTrue(w); + if (err > 0) { + err = 0; + JUMPTO(oparg); + } + else if (err == 0) { + STACKADJ(-1); + Py_DECREF(w); + } + else + break; + DISPATCH(); + + PREDICTED_WITH_ARG(JUMP_ABSOLUTE); + TARGET(JUMP_ABSOLUTE) + JUMPTO(oparg); #if FAST_LOOPS - /* Enabling this path speeds-up all while and for-loops by bypassing - the per-loop checks for signals. By default, this should be turned-off - because it prevents detection of a control-break in tight loops like - "while 1: pass". Compile with this option turned-on when you need - the speed-up and do not need break checking inside tight loops (ones - that contain only instructions ending with FAST_DISPATCH). - */ - FAST_DISPATCH(); + /* Enabling this path speeds-up all while and for-loops by bypassing + the per-loop checks for signals. By default, this should be turned-off + because it prevents detection of a control-break in tight loops like + "while 1: pass". Compile with this option turned-on when you need + the speed-up and do not need break checking inside tight loops (ones + that contain only instructions ending with FAST_DISPATCH). + */ + FAST_DISPATCH(); #else - DISPATCH(); + DISPATCH(); #endif - TARGET(GET_ITER) - /* before: [obj]; after [getiter(obj)] */ - v = TOP(); - x = PyObject_GetIter(v); - Py_DECREF(v); - if (x != NULL) { - SET_TOP(x); - PREDICT(FOR_ITER); - DISPATCH(); - } - STACKADJ(-1); - break; - - PREDICTED_WITH_ARG(FOR_ITER); - TARGET(FOR_ITER) - /* before: [iter]; after: [iter, iter()] *or* [] */ - v = TOP(); - x = (*v->ob_type->tp_iternext)(v); - if (x != NULL) { - PUSH(x); - PREDICT(STORE_FAST); - PREDICT(UNPACK_SEQUENCE); - DISPATCH(); - } - if (PyErr_Occurred()) { - if (!PyErr_ExceptionMatches( - PyExc_StopIteration)) - break; - PyErr_Clear(); - } - /* iterator ended normally */ - x = v = POP(); - Py_DECREF(v); - JUMPBY(oparg); - DISPATCH(); - - TARGET(BREAK_LOOP) - why = WHY_BREAK; - goto fast_block_end; - - TARGET(CONTINUE_LOOP) - retval = PyLong_FromLong(oparg); - if (!retval) { - x = NULL; - break; - } - why = WHY_CONTINUE; - goto fast_block_end; - - TARGET_WITH_IMPL(SETUP_LOOP, _setup_finally) - TARGET_WITH_IMPL(SETUP_EXCEPT, _setup_finally) - TARGET(SETUP_FINALLY) - _setup_finally: - /* NOTE: If you add any new block-setup opcodes that - are not try/except/finally handlers, you may need - to update the PyGen_NeedsFinalizing() function. - */ - - PyFrame_BlockSetup(f, opcode, INSTR_OFFSET() + oparg, - STACK_LEVEL()); - DISPATCH(); - - TARGET(WITH_CLEANUP) - { - /* At the top of the stack are 1-3 values indicating - how/why we entered the finally clause: - - TOP = None - - (TOP, SECOND) = (WHY_{RETURN,CONTINUE}), retval - - TOP = WHY_*; no retval below it - - (TOP, SECOND, THIRD) = exc_info() - Below them is EXIT, the context.__exit__ bound method. - In the last case, we must call - EXIT(TOP, SECOND, THIRD) - otherwise we must call - EXIT(None, None, None) - - In all cases, we remove EXIT from the stack, leaving - the rest in the same order. - - In addition, if the stack represents an exception, - *and* the function call returns a 'true' value, we - "zap" this information, to prevent END_FINALLY from - re-raising the exception. (But non-local gotos - should still be resumed.) - */ - - PyObject *exit_func = POP(); - u = TOP(); - if (u == Py_None) { - v = w = Py_None; - } - else if (PyLong_Check(u)) { - u = v = w = Py_None; - } - else { - v = SECOND(); - w = THIRD(); - } - /* XXX Not the fastest way to call it... */ - x = PyObject_CallFunctionObjArgs(exit_func, u, v, w, - NULL); - Py_DECREF(exit_func); - if (x == NULL) - break; /* Go to error exit */ - - if (u != Py_None) - err = PyObject_IsTrue(x); - else - err = 0; - Py_DECREF(x); - - if (err < 0) - break; /* Go to error exit */ - else if (err > 0) { - err = 0; - /* There was an exception and a True return */ - STACKADJ(-2); - SET_TOP(PyLong_FromLong((long) WHY_SILENCED)); - Py_DECREF(u); - Py_DECREF(v); - Py_DECREF(w); - } - PREDICT(END_FINALLY); - break; - } - - TARGET(CALL_FUNCTION) - { - PyObject **sp; - PCALL(PCALL_ALL); - sp = stack_pointer; + TARGET(GET_ITER) + /* before: [obj]; after [getiter(obj)] */ + v = TOP(); + x = PyObject_GetIter(v); + Py_DECREF(v); + if (x != NULL) { + SET_TOP(x); + PREDICT(FOR_ITER); + DISPATCH(); + } + STACKADJ(-1); + break; + + PREDICTED_WITH_ARG(FOR_ITER); + TARGET(FOR_ITER) + /* before: [iter]; after: [iter, iter()] *or* [] */ + v = TOP(); + x = (*v->ob_type->tp_iternext)(v); + if (x != NULL) { + PUSH(x); + PREDICT(STORE_FAST); + PREDICT(UNPACK_SEQUENCE); + DISPATCH(); + } + if (PyErr_Occurred()) { + if (!PyErr_ExceptionMatches( + PyExc_StopIteration)) + break; + PyErr_Clear(); + } + /* iterator ended normally */ + x = v = POP(); + Py_DECREF(v); + JUMPBY(oparg); + DISPATCH(); + + TARGET(BREAK_LOOP) + why = WHY_BREAK; + goto fast_block_end; + + TARGET(CONTINUE_LOOP) + retval = PyLong_FromLong(oparg); + if (!retval) { + x = NULL; + break; + } + why = WHY_CONTINUE; + goto fast_block_end; + + TARGET_WITH_IMPL(SETUP_LOOP, _setup_finally) + TARGET_WITH_IMPL(SETUP_EXCEPT, _setup_finally) + TARGET(SETUP_FINALLY) + _setup_finally: + /* NOTE: If you add any new block-setup opcodes that + are not try/except/finally handlers, you may need + to update the PyGen_NeedsFinalizing() function. + */ + + PyFrame_BlockSetup(f, opcode, INSTR_OFFSET() + oparg, + STACK_LEVEL()); + DISPATCH(); + + TARGET(WITH_CLEANUP) + { + /* At the top of the stack are 1-3 values indicating + how/why we entered the finally clause: + - TOP = None + - (TOP, SECOND) = (WHY_{RETURN,CONTINUE}), retval + - TOP = WHY_*; no retval below it + - (TOP, SECOND, THIRD) = exc_info() + Below them is EXIT, the context.__exit__ bound method. + In the last case, we must call + EXIT(TOP, SECOND, THIRD) + otherwise we must call + EXIT(None, None, None) + + In all cases, we remove EXIT from the stack, leaving + the rest in the same order. + + In addition, if the stack represents an exception, + *and* the function call returns a 'true' value, we + "zap" this information, to prevent END_FINALLY from + re-raising the exception. (But non-local gotos + should still be resumed.) + */ + + PyObject *exit_func = POP(); + u = TOP(); + if (u == Py_None) { + v = w = Py_None; + } + else if (PyLong_Check(u)) { + u = v = w = Py_None; + } + else { + v = SECOND(); + w = THIRD(); + } + /* XXX Not the fastest way to call it... */ + x = PyObject_CallFunctionObjArgs(exit_func, u, v, w, + NULL); + Py_DECREF(exit_func); + if (x == NULL) + break; /* Go to error exit */ + + if (u != Py_None) + err = PyObject_IsTrue(x); + else + err = 0; + Py_DECREF(x); + + if (err < 0) + break; /* Go to error exit */ + else if (err > 0) { + err = 0; + /* There was an exception and a True return */ + STACKADJ(-2); + SET_TOP(PyLong_FromLong((long) WHY_SILENCED)); + Py_DECREF(u); + Py_DECREF(v); + Py_DECREF(w); + } + PREDICT(END_FINALLY); + break; + } + + TARGET(CALL_FUNCTION) + { + PyObject **sp; + PCALL(PCALL_ALL); + sp = stack_pointer; #ifdef WITH_TSC - x = call_function(&sp, oparg, &intr0, &intr1); + x = call_function(&sp, oparg, &intr0, &intr1); #else - x = call_function(&sp, oparg); + x = call_function(&sp, oparg); #endif - stack_pointer = sp; - PUSH(x); - if (x != NULL) - DISPATCH(); - break; - } - - TARGET_WITH_IMPL(CALL_FUNCTION_VAR, _call_function_var_kw) - TARGET_WITH_IMPL(CALL_FUNCTION_KW, _call_function_var_kw) - TARGET(CALL_FUNCTION_VAR_KW) - _call_function_var_kw: - { - int na = oparg & 0xff; - int nk = (oparg>>8) & 0xff; - int flags = (opcode - CALL_FUNCTION) & 3; - int n = na + 2 * nk; - PyObject **pfunc, *func, **sp; - PCALL(PCALL_ALL); - if (flags & CALL_FLAG_VAR) - n++; - if (flags & CALL_FLAG_KW) - n++; - pfunc = stack_pointer - n - 1; - func = *pfunc; - - if (PyMethod_Check(func) - && PyMethod_GET_SELF(func) != NULL) { - PyObject *self = PyMethod_GET_SELF(func); - Py_INCREF(self); - func = PyMethod_GET_FUNCTION(func); - Py_INCREF(func); - Py_DECREF(*pfunc); - *pfunc = self; - na++; - n++; - } else - Py_INCREF(func); - sp = stack_pointer; - READ_TIMESTAMP(intr0); - x = ext_do_call(func, &sp, flags, na, nk); - READ_TIMESTAMP(intr1); - stack_pointer = sp; - Py_DECREF(func); - - while (stack_pointer > pfunc) { - w = POP(); - Py_DECREF(w); - } - PUSH(x); - if (x != NULL) - DISPATCH(); - break; - } - - TARGET_WITH_IMPL(MAKE_CLOSURE, _make_function) - TARGET(MAKE_FUNCTION) - _make_function: - { - int posdefaults = oparg & 0xff; - int kwdefaults = (oparg>>8) & 0xff; - int num_annotations = (oparg >> 16) & 0x7fff; - - v = POP(); /* code object */ - x = PyFunction_New(v, f->f_globals); - Py_DECREF(v); - - if (x != NULL && opcode == MAKE_CLOSURE) { - v = POP(); - if (PyFunction_SetClosure(x, v) != 0) { - /* Can't happen unless bytecode is corrupt. */ - why = WHY_EXCEPTION; - } - Py_DECREF(v); - } - - if (x != NULL && num_annotations > 0) { - Py_ssize_t name_ix; - u = POP(); /* names of args with annotations */ - v = PyDict_New(); - if (v == NULL) { - Py_DECREF(x); - x = NULL; - break; - } - name_ix = PyTuple_Size(u); - assert(num_annotations == name_ix+1); - while (name_ix > 0) { - --name_ix; - t = PyTuple_GET_ITEM(u, name_ix); - w = POP(); - /* XXX(nnorwitz): check for errors */ - PyDict_SetItem(v, t, w); - Py_DECREF(w); - } - - if (PyFunction_SetAnnotations(x, v) != 0) { - /* Can't happen unless - PyFunction_SetAnnotations changes. */ - why = WHY_EXCEPTION; - } - Py_DECREF(v); - Py_DECREF(u); - } - - /* XXX Maybe this should be a separate opcode? */ - if (x != NULL && posdefaults > 0) { - v = PyTuple_New(posdefaults); - if (v == NULL) { - Py_DECREF(x); - x = NULL; - break; - } - while (--posdefaults >= 0) { - w = POP(); - PyTuple_SET_ITEM(v, posdefaults, w); - } - if (PyFunction_SetDefaults(x, v) != 0) { - /* Can't happen unless - PyFunction_SetDefaults changes. */ - why = WHY_EXCEPTION; - } - Py_DECREF(v); - } - if (x != NULL && kwdefaults > 0) { - v = PyDict_New(); - if (v == NULL) { - Py_DECREF(x); - x = NULL; - break; - } - while (--kwdefaults >= 0) { - w = POP(); /* default value */ - u = POP(); /* kw only arg name */ - /* XXX(nnorwitz): check for errors */ - PyDict_SetItem(v, u, w); - Py_DECREF(w); - Py_DECREF(u); - } - if (PyFunction_SetKwDefaults(x, v) != 0) { - /* Can't happen unless - PyFunction_SetKwDefaults changes. */ - why = WHY_EXCEPTION; - } - Py_DECREF(v); - } - PUSH(x); - break; - } - - TARGET(BUILD_SLICE) - if (oparg == 3) - w = POP(); - else - w = NULL; - v = POP(); - u = TOP(); - x = PySlice_New(u, v, w); - Py_DECREF(u); - Py_DECREF(v); - Py_XDECREF(w); - SET_TOP(x); - if (x != NULL) DISPATCH(); - break; - - TARGET(EXTENDED_ARG) - opcode = NEXTOP(); - oparg = oparg<<16 | NEXTARG(); - goto dispatch_opcode; + stack_pointer = sp; + PUSH(x); + if (x != NULL) + DISPATCH(); + break; + } + + TARGET_WITH_IMPL(CALL_FUNCTION_VAR, _call_function_var_kw) + TARGET_WITH_IMPL(CALL_FUNCTION_KW, _call_function_var_kw) + TARGET(CALL_FUNCTION_VAR_KW) + _call_function_var_kw: + { + int na = oparg & 0xff; + int nk = (oparg>>8) & 0xff; + int flags = (opcode - CALL_FUNCTION) & 3; + int n = na + 2 * nk; + PyObject **pfunc, *func, **sp; + PCALL(PCALL_ALL); + if (flags & CALL_FLAG_VAR) + n++; + if (flags & CALL_FLAG_KW) + n++; + pfunc = stack_pointer - n - 1; + func = *pfunc; + + if (PyMethod_Check(func) + && PyMethod_GET_SELF(func) != NULL) { + PyObject *self = PyMethod_GET_SELF(func); + Py_INCREF(self); + func = PyMethod_GET_FUNCTION(func); + Py_INCREF(func); + Py_DECREF(*pfunc); + *pfunc = self; + na++; + n++; + } else + Py_INCREF(func); + sp = stack_pointer; + READ_TIMESTAMP(intr0); + x = ext_do_call(func, &sp, flags, na, nk); + READ_TIMESTAMP(intr1); + stack_pointer = sp; + Py_DECREF(func); + + while (stack_pointer > pfunc) { + w = POP(); + Py_DECREF(w); + } + PUSH(x); + if (x != NULL) + DISPATCH(); + break; + } + + TARGET_WITH_IMPL(MAKE_CLOSURE, _make_function) + TARGET(MAKE_FUNCTION) + _make_function: + { + int posdefaults = oparg & 0xff; + int kwdefaults = (oparg>>8) & 0xff; + int num_annotations = (oparg >> 16) & 0x7fff; + + v = POP(); /* code object */ + x = PyFunction_New(v, f->f_globals); + Py_DECREF(v); + + if (x != NULL && opcode == MAKE_CLOSURE) { + v = POP(); + if (PyFunction_SetClosure(x, v) != 0) { + /* Can't happen unless bytecode is corrupt. */ + why = WHY_EXCEPTION; + } + Py_DECREF(v); + } + + if (x != NULL && num_annotations > 0) { + Py_ssize_t name_ix; + u = POP(); /* names of args with annotations */ + v = PyDict_New(); + if (v == NULL) { + Py_DECREF(x); + x = NULL; + break; + } + name_ix = PyTuple_Size(u); + assert(num_annotations == name_ix+1); + while (name_ix > 0) { + --name_ix; + t = PyTuple_GET_ITEM(u, name_ix); + w = POP(); + /* XXX(nnorwitz): check for errors */ + PyDict_SetItem(v, t, w); + Py_DECREF(w); + } + + if (PyFunction_SetAnnotations(x, v) != 0) { + /* Can't happen unless + PyFunction_SetAnnotations changes. */ + why = WHY_EXCEPTION; + } + Py_DECREF(v); + Py_DECREF(u); + } + + /* XXX Maybe this should be a separate opcode? */ + if (x != NULL && posdefaults > 0) { + v = PyTuple_New(posdefaults); + if (v == NULL) { + Py_DECREF(x); + x = NULL; + break; + } + while (--posdefaults >= 0) { + w = POP(); + PyTuple_SET_ITEM(v, posdefaults, w); + } + if (PyFunction_SetDefaults(x, v) != 0) { + /* Can't happen unless + PyFunction_SetDefaults changes. */ + why = WHY_EXCEPTION; + } + Py_DECREF(v); + } + if (x != NULL && kwdefaults > 0) { + v = PyDict_New(); + if (v == NULL) { + Py_DECREF(x); + x = NULL; + break; + } + while (--kwdefaults >= 0) { + w = POP(); /* default value */ + u = POP(); /* kw only arg name */ + /* XXX(nnorwitz): check for errors */ + PyDict_SetItem(v, u, w); + Py_DECREF(w); + Py_DECREF(u); + } + if (PyFunction_SetKwDefaults(x, v) != 0) { + /* Can't happen unless + PyFunction_SetKwDefaults changes. */ + why = WHY_EXCEPTION; + } + Py_DECREF(v); + } + PUSH(x); + break; + } + + TARGET(BUILD_SLICE) + if (oparg == 3) + w = POP(); + else + w = NULL; + v = POP(); + u = TOP(); + x = PySlice_New(u, v, w); + Py_DECREF(u); + Py_DECREF(v); + Py_XDECREF(w); + SET_TOP(x); + if (x != NULL) DISPATCH(); + break; + + TARGET(EXTENDED_ARG) + opcode = NEXTOP(); + oparg = oparg<<16 | NEXTARG(); + goto dispatch_opcode; #ifdef USE_COMPUTED_GOTOS - _unknown_opcode: + _unknown_opcode: #endif - default: - fprintf(stderr, - "XXX lineno: %d, opcode: %d\n", - PyCode_Addr2Line(f->f_code, f->f_lasti), - opcode); - PyErr_SetString(PyExc_SystemError, "unknown opcode"); - why = WHY_EXCEPTION; - break; + default: + fprintf(stderr, + "XXX lineno: %d, opcode: %d\n", + PyCode_Addr2Line(f->f_code, f->f_lasti), + opcode); + PyErr_SetString(PyExc_SystemError, "unknown opcode"); + why = WHY_EXCEPTION; + break; #ifdef CASE_TOO_BIG - } + } #endif - } /* switch */ + } /* switch */ - on_error: + on_error: - READ_TIMESTAMP(inst1); + READ_TIMESTAMP(inst1); - /* Quickly continue if no error occurred */ + /* Quickly continue if no error occurred */ - if (why == WHY_NOT) { - if (err == 0 && x != NULL) { + if (why == WHY_NOT) { + if (err == 0 && x != NULL) { #ifdef CHECKEXC - /* This check is expensive! */ - if (PyErr_Occurred()) - fprintf(stderr, - "XXX undetected error\n"); - else { + /* This check is expensive! */ + if (PyErr_Occurred()) + fprintf(stderr, + "XXX undetected error\n"); + else { #endif - READ_TIMESTAMP(loop1); - continue; /* Normal, fast path */ + READ_TIMESTAMP(loop1); + continue; /* Normal, fast path */ #ifdef CHECKEXC - } + } #endif - } - why = WHY_EXCEPTION; - x = Py_None; - err = 0; - } - - /* Double-check exception status */ - - if (why == WHY_EXCEPTION || why == WHY_RERAISE) { - if (!PyErr_Occurred()) { - PyErr_SetString(PyExc_SystemError, - "error return without exception set"); - why = WHY_EXCEPTION; - } - } + } + why = WHY_EXCEPTION; + x = Py_None; + err = 0; + } + + /* Double-check exception status */ + + if (why == WHY_EXCEPTION || why == WHY_RERAISE) { + if (!PyErr_Occurred()) { + PyErr_SetString(PyExc_SystemError, + "error return without exception set"); + why = WHY_EXCEPTION; + } + } #ifdef CHECKEXC - else { - /* This check is expensive! */ - if (PyErr_Occurred()) { - char buf[128]; - sprintf(buf, "Stack unwind with exception " - "set and why=%d", why); - Py_FatalError(buf); - } - } + else { + /* This check is expensive! */ + if (PyErr_Occurred()) { + char buf[128]; + sprintf(buf, "Stack unwind with exception " + "set and why=%d", why); + Py_FatalError(buf); + } + } #endif - /* Log traceback info if this is a real exception */ + /* Log traceback info if this is a real exception */ - if (why == WHY_EXCEPTION) { - PyTraceBack_Here(f); + if (why == WHY_EXCEPTION) { + PyTraceBack_Here(f); - if (tstate->c_tracefunc != NULL) - call_exc_trace(tstate->c_tracefunc, - tstate->c_traceobj, f); - } + if (tstate->c_tracefunc != NULL) + call_exc_trace(tstate->c_tracefunc, + tstate->c_traceobj, f); + } - /* For the rest, treat WHY_RERAISE as WHY_EXCEPTION */ + /* For the rest, treat WHY_RERAISE as WHY_EXCEPTION */ - if (why == WHY_RERAISE) - why = WHY_EXCEPTION; + if (why == WHY_RERAISE) + why = WHY_EXCEPTION; - /* Unwind stacks if a (pseudo) exception occurred */ + /* Unwind stacks if a (pseudo) exception occurred */ fast_block_end: - while (why != WHY_NOT && f->f_iblock > 0) { - PyTryBlock *b = PyFrame_BlockPop(f); + while (why != WHY_NOT && f->f_iblock > 0) { + PyTryBlock *b = PyFrame_BlockPop(f); - assert(why != WHY_YIELD); - if (b->b_type == SETUP_LOOP && why == WHY_CONTINUE) { - /* For a continue inside a try block, - don't pop the block for the loop. */ - PyFrame_BlockSetup(f, b->b_type, b->b_handler, - b->b_level); - why = WHY_NOT; - JUMPTO(PyLong_AS_LONG(retval)); - Py_DECREF(retval); - break; - } - - if (b->b_type == EXCEPT_HANDLER) { - UNWIND_EXCEPT_HANDLER(b); - continue; - } - UNWIND_BLOCK(b); - if (b->b_type == SETUP_LOOP && why == WHY_BREAK) { - why = WHY_NOT; - JUMPTO(b->b_handler); - break; - } - if (why == WHY_EXCEPTION && (b->b_type == SETUP_EXCEPT - || b->b_type == SETUP_FINALLY)) { - PyObject *exc, *val, *tb; - int handler = b->b_handler; - /* Beware, this invalidates all b->b_* fields */ - PyFrame_BlockSetup(f, EXCEPT_HANDLER, -1, STACK_LEVEL()); - PUSH(tstate->exc_traceback); - PUSH(tstate->exc_value); - if (tstate->exc_type != NULL) { - PUSH(tstate->exc_type); - } - else { - Py_INCREF(Py_None); - PUSH(Py_None); - } - PyErr_Fetch(&exc, &val, &tb); - /* Make the raw exception data - available to the handler, - so a program can emulate the - Python main loop. */ - PyErr_NormalizeException( - &exc, &val, &tb); - PyException_SetTraceback(val, tb); - Py_INCREF(exc); - tstate->exc_type = exc; - Py_INCREF(val); - tstate->exc_value = val; - tstate->exc_traceback = tb; - if (tb == NULL) - tb = Py_None; - Py_INCREF(tb); - PUSH(tb); - PUSH(val); - PUSH(exc); - why = WHY_NOT; - JUMPTO(handler); - break; - } - if (b->b_type == SETUP_FINALLY) { - if (why & (WHY_RETURN | WHY_CONTINUE)) - PUSH(retval); - PUSH(PyLong_FromLong((long)why)); - why = WHY_NOT; - JUMPTO(b->b_handler); - break; - } - } /* unwind stack */ - - /* End the loop if we still have an error (or return) */ - - if (why != WHY_NOT) - break; - READ_TIMESTAMP(loop1); - - } /* main loop */ - - assert(why != WHY_YIELD); - /* Pop remaining stack entries. */ - while (!EMPTY()) { - v = POP(); - Py_XDECREF(v); - } + assert(why != WHY_YIELD); + if (b->b_type == SETUP_LOOP && why == WHY_CONTINUE) { + /* For a continue inside a try block, + don't pop the block for the loop. */ + PyFrame_BlockSetup(f, b->b_type, b->b_handler, + b->b_level); + why = WHY_NOT; + JUMPTO(PyLong_AS_LONG(retval)); + Py_DECREF(retval); + break; + } + + if (b->b_type == EXCEPT_HANDLER) { + UNWIND_EXCEPT_HANDLER(b); + continue; + } + UNWIND_BLOCK(b); + if (b->b_type == SETUP_LOOP && why == WHY_BREAK) { + why = WHY_NOT; + JUMPTO(b->b_handler); + break; + } + if (why == WHY_EXCEPTION && (b->b_type == SETUP_EXCEPT + || b->b_type == SETUP_FINALLY)) { + PyObject *exc, *val, *tb; + int handler = b->b_handler; + /* Beware, this invalidates all b->b_* fields */ + PyFrame_BlockSetup(f, EXCEPT_HANDLER, -1, STACK_LEVEL()); + PUSH(tstate->exc_traceback); + PUSH(tstate->exc_value); + if (tstate->exc_type != NULL) { + PUSH(tstate->exc_type); + } + else { + Py_INCREF(Py_None); + PUSH(Py_None); + } + PyErr_Fetch(&exc, &val, &tb); + /* Make the raw exception data + available to the handler, + so a program can emulate the + Python main loop. */ + PyErr_NormalizeException( + &exc, &val, &tb); + PyException_SetTraceback(val, tb); + Py_INCREF(exc); + tstate->exc_type = exc; + Py_INCREF(val); + tstate->exc_value = val; + tstate->exc_traceback = tb; + if (tb == NULL) + tb = Py_None; + Py_INCREF(tb); + PUSH(tb); + PUSH(val); + PUSH(exc); + why = WHY_NOT; + JUMPTO(handler); + break; + } + if (b->b_type == SETUP_FINALLY) { + if (why & (WHY_RETURN | WHY_CONTINUE)) + PUSH(retval); + PUSH(PyLong_FromLong((long)why)); + why = WHY_NOT; + JUMPTO(b->b_handler); + break; + } + } /* unwind stack */ + + /* End the loop if we still have an error (or return) */ + + if (why != WHY_NOT) + break; + READ_TIMESTAMP(loop1); + + } /* main loop */ + + assert(why != WHY_YIELD); + /* Pop remaining stack entries. */ + while (!EMPTY()) { + v = POP(); + Py_XDECREF(v); + } - if (why != WHY_RETURN) - retval = NULL; + if (why != WHY_RETURN) + retval = NULL; fast_yield: - if (tstate->use_tracing) { - if (tstate->c_tracefunc) { - if (why == WHY_RETURN || why == WHY_YIELD) { - if (call_trace(tstate->c_tracefunc, - tstate->c_traceobj, f, - PyTrace_RETURN, retval)) { - Py_XDECREF(retval); - retval = NULL; - why = WHY_EXCEPTION; - } - } - else if (why == WHY_EXCEPTION) { - call_trace_protected(tstate->c_tracefunc, - tstate->c_traceobj, f, - PyTrace_RETURN, NULL); - } - } - if (tstate->c_profilefunc) { - if (why == WHY_EXCEPTION) - call_trace_protected(tstate->c_profilefunc, - tstate->c_profileobj, f, - PyTrace_RETURN, NULL); - else if (call_trace(tstate->c_profilefunc, - tstate->c_profileobj, f, - PyTrace_RETURN, retval)) { - Py_XDECREF(retval); - retval = NULL; - why = WHY_EXCEPTION; - } - } - } + if (tstate->use_tracing) { + if (tstate->c_tracefunc) { + if (why == WHY_RETURN || why == WHY_YIELD) { + if (call_trace(tstate->c_tracefunc, + tstate->c_traceobj, f, + PyTrace_RETURN, retval)) { + Py_XDECREF(retval); + retval = NULL; + why = WHY_EXCEPTION; + } + } + else if (why == WHY_EXCEPTION) { + call_trace_protected(tstate->c_tracefunc, + tstate->c_traceobj, f, + PyTrace_RETURN, NULL); + } + } + if (tstate->c_profilefunc) { + if (why == WHY_EXCEPTION) + call_trace_protected(tstate->c_profilefunc, + tstate->c_profileobj, f, + PyTrace_RETURN, NULL); + else if (call_trace(tstate->c_profilefunc, + tstate->c_profileobj, f, + PyTrace_RETURN, retval)) { + Py_XDECREF(retval); + retval = NULL; + why = WHY_EXCEPTION; + } + } + } - /* pop frame */ + /* pop frame */ exit_eval_frame: - Py_LeaveRecursiveCall(); - tstate->frame = f->f_back; + Py_LeaveRecursiveCall(); + tstate->frame = f->f_back; - return retval; + return retval; } /* This is gonna seem *real weird*, but if you put some other code between @@ -2937,278 +2937,278 @@ PyObject * PyEval_EvalCodeEx(PyCodeObject *co, PyObject *globals, PyObject *locals, - PyObject **args, int argcount, PyObject **kws, int kwcount, - PyObject **defs, int defcount, PyObject *kwdefs, PyObject *closure) + PyObject **args, int argcount, PyObject **kws, int kwcount, + PyObject **defs, int defcount, PyObject *kwdefs, PyObject *closure) { - register PyFrameObject *f; - register PyObject *retval = NULL; - register PyObject **fastlocals, **freevars; - PyThreadState *tstate = PyThreadState_GET(); - PyObject *x, *u; - - if (globals == NULL) { - PyErr_SetString(PyExc_SystemError, - "PyEval_EvalCodeEx: NULL globals"); - return NULL; - } - - assert(tstate != NULL); - assert(globals != NULL); - f = PyFrame_New(tstate, co, globals, locals); - if (f == NULL) - return NULL; - - fastlocals = f->f_localsplus; - freevars = f->f_localsplus + co->co_nlocals; - - if (co->co_argcount > 0 || - co->co_kwonlyargcount > 0 || - co->co_flags & (CO_VARARGS | CO_VARKEYWORDS)) { - int i; - int n = argcount; - PyObject *kwdict = NULL; - if (co->co_flags & CO_VARKEYWORDS) { - kwdict = PyDict_New(); - if (kwdict == NULL) - goto fail; - i = co->co_argcount + co->co_kwonlyargcount; - if (co->co_flags & CO_VARARGS) - i++; - SETLOCAL(i, kwdict); - } - if (argcount > co->co_argcount) { - if (!(co->co_flags & CO_VARARGS)) { - PyErr_Format(PyExc_TypeError, - "%U() takes %s %d " - "%spositional argument%s (%d given)", - co->co_name, - defcount ? "at most" : "exactly", - co->co_argcount, - kwcount ? "non-keyword " : "", - co->co_argcount == 1 ? "" : "s", - argcount); - goto fail; - } - n = co->co_argcount; - } - for (i = 0; i < n; i++) { - x = args[i]; - Py_INCREF(x); - SETLOCAL(i, x); - } - if (co->co_flags & CO_VARARGS) { - u = PyTuple_New(argcount - n); - if (u == NULL) - goto fail; - SETLOCAL(co->co_argcount + co->co_kwonlyargcount, u); - for (i = n; i < argcount; i++) { - x = args[i]; - Py_INCREF(x); - PyTuple_SET_ITEM(u, i-n, x); - } - } - for (i = 0; i < kwcount; i++) { - PyObject **co_varnames; - PyObject *keyword = kws[2*i]; - PyObject *value = kws[2*i + 1]; - int j; - if (keyword == NULL || !PyUnicode_Check(keyword)) { - PyErr_Format(PyExc_TypeError, - "%U() keywords must be strings", - co->co_name); - goto fail; - } - /* Speed hack: do raw pointer compares. As names are - normally interned this should almost always hit. */ - co_varnames = PySequence_Fast_ITEMS(co->co_varnames); - for (j = 0; - j < co->co_argcount + co->co_kwonlyargcount; - j++) { - PyObject *nm = co_varnames[j]; - if (nm == keyword) - goto kw_found; - } - /* Slow fallback, just in case */ - for (j = 0; - j < co->co_argcount + co->co_kwonlyargcount; - j++) { - PyObject *nm = co_varnames[j]; - int cmp = PyObject_RichCompareBool( - keyword, nm, Py_EQ); - if (cmp > 0) - goto kw_found; - else if (cmp < 0) - goto fail; - } - /* Check errors from Compare */ - if (PyErr_Occurred()) - goto fail; - if (j >= co->co_argcount + co->co_kwonlyargcount) { - if (kwdict == NULL) { - PyErr_Format(PyExc_TypeError, - "%U() got an unexpected " - "keyword argument '%S'", - co->co_name, - keyword); - goto fail; - } - PyDict_SetItem(kwdict, keyword, value); - continue; - } + register PyFrameObject *f; + register PyObject *retval = NULL; + register PyObject **fastlocals, **freevars; + PyThreadState *tstate = PyThreadState_GET(); + PyObject *x, *u; + + if (globals == NULL) { + PyErr_SetString(PyExc_SystemError, + "PyEval_EvalCodeEx: NULL globals"); + return NULL; + } + + assert(tstate != NULL); + assert(globals != NULL); + f = PyFrame_New(tstate, co, globals, locals); + if (f == NULL) + return NULL; + + fastlocals = f->f_localsplus; + freevars = f->f_localsplus + co->co_nlocals; + + if (co->co_argcount > 0 || + co->co_kwonlyargcount > 0 || + co->co_flags & (CO_VARARGS | CO_VARKEYWORDS)) { + int i; + int n = argcount; + PyObject *kwdict = NULL; + if (co->co_flags & CO_VARKEYWORDS) { + kwdict = PyDict_New(); + if (kwdict == NULL) + goto fail; + i = co->co_argcount + co->co_kwonlyargcount; + if (co->co_flags & CO_VARARGS) + i++; + SETLOCAL(i, kwdict); + } + if (argcount > co->co_argcount) { + if (!(co->co_flags & CO_VARARGS)) { + PyErr_Format(PyExc_TypeError, + "%U() takes %s %d " + "%spositional argument%s (%d given)", + co->co_name, + defcount ? "at most" : "exactly", + co->co_argcount, + kwcount ? "non-keyword " : "", + co->co_argcount == 1 ? "" : "s", + argcount); + goto fail; + } + n = co->co_argcount; + } + for (i = 0; i < n; i++) { + x = args[i]; + Py_INCREF(x); + SETLOCAL(i, x); + } + if (co->co_flags & CO_VARARGS) { + u = PyTuple_New(argcount - n); + if (u == NULL) + goto fail; + SETLOCAL(co->co_argcount + co->co_kwonlyargcount, u); + for (i = n; i < argcount; i++) { + x = args[i]; + Py_INCREF(x); + PyTuple_SET_ITEM(u, i-n, x); + } + } + for (i = 0; i < kwcount; i++) { + PyObject **co_varnames; + PyObject *keyword = kws[2*i]; + PyObject *value = kws[2*i + 1]; + int j; + if (keyword == NULL || !PyUnicode_Check(keyword)) { + PyErr_Format(PyExc_TypeError, + "%U() keywords must be strings", + co->co_name); + goto fail; + } + /* Speed hack: do raw pointer compares. As names are + normally interned this should almost always hit. */ + co_varnames = PySequence_Fast_ITEMS(co->co_varnames); + for (j = 0; + j < co->co_argcount + co->co_kwonlyargcount; + j++) { + PyObject *nm = co_varnames[j]; + if (nm == keyword) + goto kw_found; + } + /* Slow fallback, just in case */ + for (j = 0; + j < co->co_argcount + co->co_kwonlyargcount; + j++) { + PyObject *nm = co_varnames[j]; + int cmp = PyObject_RichCompareBool( + keyword, nm, Py_EQ); + if (cmp > 0) + goto kw_found; + else if (cmp < 0) + goto fail; + } + /* Check errors from Compare */ + if (PyErr_Occurred()) + goto fail; + if (j >= co->co_argcount + co->co_kwonlyargcount) { + if (kwdict == NULL) { + PyErr_Format(PyExc_TypeError, + "%U() got an unexpected " + "keyword argument '%S'", + co->co_name, + keyword); + goto fail; + } + PyDict_SetItem(kwdict, keyword, value); + continue; + } kw_found: - if (GETLOCAL(j) != NULL) { - PyErr_Format(PyExc_TypeError, - "%U() got multiple " - "values for keyword " - "argument '%S'", - co->co_name, - keyword); - goto fail; - } - Py_INCREF(value); - SETLOCAL(j, value); - } - if (co->co_kwonlyargcount > 0) { - for (i = co->co_argcount; - i < co->co_argcount + co->co_kwonlyargcount; - i++) { - PyObject *name, *def; - if (GETLOCAL(i) != NULL) - continue; - name = PyTuple_GET_ITEM(co->co_varnames, i); - def = NULL; - if (kwdefs != NULL) - def = PyDict_GetItem(kwdefs, name); - if (def != NULL) { - Py_INCREF(def); - SETLOCAL(i, def); - continue; - } - PyErr_Format(PyExc_TypeError, - "%U() needs keyword-only argument %S", - co->co_name, name); - goto fail; - } - } - if (argcount < co->co_argcount) { - int m = co->co_argcount - defcount; - for (i = argcount; i < m; i++) { - if (GETLOCAL(i) == NULL) { - PyErr_Format(PyExc_TypeError, - "%U() takes %s %d " - "%spositional argument%s " - "(%d given)", - co->co_name, - ((co->co_flags & CO_VARARGS) || - defcount) ? "at least" - : "exactly", - m, kwcount ? "non-keyword " : "", - m == 1 ? "" : "s", i); - goto fail; - } - } - if (n > m) - i = n - m; - else - i = 0; - for (; i < defcount; i++) { - if (GETLOCAL(m+i) == NULL) { - PyObject *def = defs[i]; - Py_INCREF(def); - SETLOCAL(m+i, def); - } - } - } - } - else { - if (argcount > 0 || kwcount > 0) { - PyErr_Format(PyExc_TypeError, - "%U() takes no arguments (%d given)", - co->co_name, - argcount + kwcount); - goto fail; - } - } - /* Allocate and initialize storage for cell vars, and copy free - vars into frame. This isn't too efficient right now. */ - if (PyTuple_GET_SIZE(co->co_cellvars)) { - int i, j, nargs, found; - Py_UNICODE *cellname, *argname; - PyObject *c; - - nargs = co->co_argcount + co->co_kwonlyargcount; - if (co->co_flags & CO_VARARGS) - nargs++; - if (co->co_flags & CO_VARKEYWORDS) - nargs++; - - /* Initialize each cell var, taking into account - cell vars that are initialized from arguments. - - Should arrange for the compiler to put cellvars - that are arguments at the beginning of the cellvars - list so that we can march over it more efficiently? - */ - for (i = 0; i < PyTuple_GET_SIZE(co->co_cellvars); ++i) { - cellname = PyUnicode_AS_UNICODE( - PyTuple_GET_ITEM(co->co_cellvars, i)); - found = 0; - for (j = 0; j < nargs; j++) { - argname = PyUnicode_AS_UNICODE( - PyTuple_GET_ITEM(co->co_varnames, j)); - if (Py_UNICODE_strcmp(cellname, argname) == 0) { - c = PyCell_New(GETLOCAL(j)); - if (c == NULL) - goto fail; - GETLOCAL(co->co_nlocals + i) = c; - found = 1; - break; - } - } - if (found == 0) { - c = PyCell_New(NULL); - if (c == NULL) - goto fail; - SETLOCAL(co->co_nlocals + i, c); - } - } - } - if (PyTuple_GET_SIZE(co->co_freevars)) { - int i; - for (i = 0; i < PyTuple_GET_SIZE(co->co_freevars); ++i) { - PyObject *o = PyTuple_GET_ITEM(closure, i); - Py_INCREF(o); - freevars[PyTuple_GET_SIZE(co->co_cellvars) + i] = o; - } - } - - if (co->co_flags & CO_GENERATOR) { - /* Don't need to keep the reference to f_back, it will be set - * when the generator is resumed. */ - Py_XDECREF(f->f_back); - f->f_back = NULL; - - PCALL(PCALL_GENERATOR); - - /* Create a new generator that owns the ready to run frame - * and return that as the value. */ - return PyGen_New(f); - } + if (GETLOCAL(j) != NULL) { + PyErr_Format(PyExc_TypeError, + "%U() got multiple " + "values for keyword " + "argument '%S'", + co->co_name, + keyword); + goto fail; + } + Py_INCREF(value); + SETLOCAL(j, value); + } + if (co->co_kwonlyargcount > 0) { + for (i = co->co_argcount; + i < co->co_argcount + co->co_kwonlyargcount; + i++) { + PyObject *name, *def; + if (GETLOCAL(i) != NULL) + continue; + name = PyTuple_GET_ITEM(co->co_varnames, i); + def = NULL; + if (kwdefs != NULL) + def = PyDict_GetItem(kwdefs, name); + if (def != NULL) { + Py_INCREF(def); + SETLOCAL(i, def); + continue; + } + PyErr_Format(PyExc_TypeError, + "%U() needs keyword-only argument %S", + co->co_name, name); + goto fail; + } + } + if (argcount < co->co_argcount) { + int m = co->co_argcount - defcount; + for (i = argcount; i < m; i++) { + if (GETLOCAL(i) == NULL) { + PyErr_Format(PyExc_TypeError, + "%U() takes %s %d " + "%spositional argument%s " + "(%d given)", + co->co_name, + ((co->co_flags & CO_VARARGS) || + defcount) ? "at least" + : "exactly", + m, kwcount ? "non-keyword " : "", + m == 1 ? "" : "s", i); + goto fail; + } + } + if (n > m) + i = n - m; + else + i = 0; + for (; i < defcount; i++) { + if (GETLOCAL(m+i) == NULL) { + PyObject *def = defs[i]; + Py_INCREF(def); + SETLOCAL(m+i, def); + } + } + } + } + else { + if (argcount > 0 || kwcount > 0) { + PyErr_Format(PyExc_TypeError, + "%U() takes no arguments (%d given)", + co->co_name, + argcount + kwcount); + goto fail; + } + } + /* Allocate and initialize storage for cell vars, and copy free + vars into frame. This isn't too efficient right now. */ + if (PyTuple_GET_SIZE(co->co_cellvars)) { + int i, j, nargs, found; + Py_UNICODE *cellname, *argname; + PyObject *c; + + nargs = co->co_argcount + co->co_kwonlyargcount; + if (co->co_flags & CO_VARARGS) + nargs++; + if (co->co_flags & CO_VARKEYWORDS) + nargs++; + + /* Initialize each cell var, taking into account + cell vars that are initialized from arguments. + + Should arrange for the compiler to put cellvars + that are arguments at the beginning of the cellvars + list so that we can march over it more efficiently? + */ + for (i = 0; i < PyTuple_GET_SIZE(co->co_cellvars); ++i) { + cellname = PyUnicode_AS_UNICODE( + PyTuple_GET_ITEM(co->co_cellvars, i)); + found = 0; + for (j = 0; j < nargs; j++) { + argname = PyUnicode_AS_UNICODE( + PyTuple_GET_ITEM(co->co_varnames, j)); + if (Py_UNICODE_strcmp(cellname, argname) == 0) { + c = PyCell_New(GETLOCAL(j)); + if (c == NULL) + goto fail; + GETLOCAL(co->co_nlocals + i) = c; + found = 1; + break; + } + } + if (found == 0) { + c = PyCell_New(NULL); + if (c == NULL) + goto fail; + SETLOCAL(co->co_nlocals + i, c); + } + } + } + if (PyTuple_GET_SIZE(co->co_freevars)) { + int i; + for (i = 0; i < PyTuple_GET_SIZE(co->co_freevars); ++i) { + PyObject *o = PyTuple_GET_ITEM(closure, i); + Py_INCREF(o); + freevars[PyTuple_GET_SIZE(co->co_cellvars) + i] = o; + } + } + + if (co->co_flags & CO_GENERATOR) { + /* Don't need to keep the reference to f_back, it will be set + * when the generator is resumed. */ + Py_XDECREF(f->f_back); + f->f_back = NULL; + + PCALL(PCALL_GENERATOR); + + /* Create a new generator that owns the ready to run frame + * and return that as the value. */ + return PyGen_New(f); + } - retval = PyEval_EvalFrameEx(f,0); + retval = PyEval_EvalFrameEx(f,0); fail: /* Jump here from prelude on failure */ - /* decref'ing the frame can cause __del__ methods to get invoked, - which can call back into Python. While we're done with the - current Python frame (f), the associated C stack is still in use, - so recursion_depth must be boosted for the duration. - */ - assert(tstate != NULL); - ++tstate->recursion_depth; - Py_DECREF(f); - --tstate->recursion_depth; - return retval; + /* decref'ing the frame can cause __del__ methods to get invoked, + which can call back into Python. While we're done with the + current Python frame (f), the associated C stack is still in use, + so recursion_depth must be boosted for the duration. + */ + assert(tstate != NULL); + ++tstate->recursion_depth; + Py_DECREF(f); + --tstate->recursion_depth; + return retval; } @@ -3217,83 +3217,83 @@ static enum why_code do_raise(PyObject *exc, PyObject *cause) { - PyObject *type = NULL, *value = NULL; + PyObject *type = NULL, *value = NULL; - if (exc == NULL) { - /* Reraise */ - PyThreadState *tstate = PyThreadState_GET(); - PyObject *tb; - type = tstate->exc_type; - value = tstate->exc_value; - tb = tstate->exc_traceback; - if (type == Py_None) { - PyErr_SetString(PyExc_RuntimeError, - "No active exception to reraise"); - return WHY_EXCEPTION; - } - Py_XINCREF(type); - Py_XINCREF(value); - Py_XINCREF(tb); - PyErr_Restore(type, value, tb); - return WHY_RERAISE; - } + if (exc == NULL) { + /* Reraise */ + PyThreadState *tstate = PyThreadState_GET(); + PyObject *tb; + type = tstate->exc_type; + value = tstate->exc_value; + tb = tstate->exc_traceback; + if (type == Py_None) { + PyErr_SetString(PyExc_RuntimeError, + "No active exception to reraise"); + return WHY_EXCEPTION; + } + Py_XINCREF(type); + Py_XINCREF(value); + Py_XINCREF(tb); + PyErr_Restore(type, value, tb); + return WHY_RERAISE; + } - /* We support the following forms of raise: - raise + /* We support the following forms of raise: + raise raise raise */ - if (PyExceptionClass_Check(exc)) { - type = exc; - value = PyObject_CallObject(exc, NULL); - if (value == NULL) - goto raise_error; - } - else if (PyExceptionInstance_Check(exc)) { - value = exc; - type = PyExceptionInstance_Class(exc); - Py_INCREF(type); - } - else { - /* Not something you can raise. You get an exception - anyway, just not what you specified :-) */ - Py_DECREF(exc); - PyErr_SetString(PyExc_TypeError, - "exceptions must derive from BaseException"); - goto raise_error; - } - - if (cause) { - PyObject *fixed_cause; - if (PyExceptionClass_Check(cause)) { - fixed_cause = PyObject_CallObject(cause, NULL); - if (fixed_cause == NULL) - goto raise_error; - Py_DECREF(cause); - } - else if (PyExceptionInstance_Check(cause)) { - fixed_cause = cause; - } - else { - PyErr_SetString(PyExc_TypeError, - "exception causes must derive from " - "BaseException"); - goto raise_error; - } - PyException_SetCause(value, fixed_cause); - } - - PyErr_SetObject(type, value); - /* PyErr_SetObject incref's its arguments */ - Py_XDECREF(value); - Py_XDECREF(type); - return WHY_EXCEPTION; + if (PyExceptionClass_Check(exc)) { + type = exc; + value = PyObject_CallObject(exc, NULL); + if (value == NULL) + goto raise_error; + } + else if (PyExceptionInstance_Check(exc)) { + value = exc; + type = PyExceptionInstance_Class(exc); + Py_INCREF(type); + } + else { + /* Not something you can raise. You get an exception + anyway, just not what you specified :-) */ + Py_DECREF(exc); + PyErr_SetString(PyExc_TypeError, + "exceptions must derive from BaseException"); + goto raise_error; + } + + if (cause) { + PyObject *fixed_cause; + if (PyExceptionClass_Check(cause)) { + fixed_cause = PyObject_CallObject(cause, NULL); + if (fixed_cause == NULL) + goto raise_error; + Py_DECREF(cause); + } + else if (PyExceptionInstance_Check(cause)) { + fixed_cause = cause; + } + else { + PyErr_SetString(PyExc_TypeError, + "exception causes must derive from " + "BaseException"); + goto raise_error; + } + PyException_SetCause(value, fixed_cause); + } + + PyErr_SetObject(type, value); + /* PyErr_SetObject incref's its arguments */ + Py_XDECREF(value); + Py_XDECREF(type); + return WHY_EXCEPTION; raise_error: - Py_XDECREF(value); - Py_XDECREF(type); - Py_XDECREF(cause); - return WHY_EXCEPTION; + Py_XDECREF(value); + Py_XDECREF(type); + Py_XDECREF(cause); + return WHY_EXCEPTION; } /* Iterate v argcnt times and store the results on the stack (via decreasing @@ -3306,73 +3306,73 @@ static int unpack_iterable(PyObject *v, int argcnt, int argcntafter, PyObject **sp) { - int i = 0, j = 0; - Py_ssize_t ll = 0; - PyObject *it; /* iter(v) */ - PyObject *w; - PyObject *l = NULL; /* variable list */ - - assert(v != NULL); - - it = PyObject_GetIter(v); - if (it == NULL) - goto Error; - - for (; i < argcnt; i++) { - w = PyIter_Next(it); - if (w == NULL) { - /* Iterator done, via error or exhaustion. */ - if (!PyErr_Occurred()) { - PyErr_Format(PyExc_ValueError, - "need more than %d value%s to unpack", - i, i == 1 ? "" : "s"); - } - goto Error; - } - *--sp = w; - } - - if (argcntafter == -1) { - /* We better have exhausted the iterator now. */ - w = PyIter_Next(it); - if (w == NULL) { - if (PyErr_Occurred()) - goto Error; - Py_DECREF(it); - return 1; - } - Py_DECREF(w); - PyErr_SetString(PyExc_ValueError, "too many values to unpack"); - goto Error; - } - - l = PySequence_List(it); - if (l == NULL) - goto Error; - *--sp = l; - i++; - - ll = PyList_GET_SIZE(l); - if (ll < argcntafter) { - PyErr_Format(PyExc_ValueError, "need more than %zd values to unpack", - argcnt + ll); - goto Error; - } - - /* Pop the "after-variable" args off the list. */ - for (j = argcntafter; j > 0; j--, i++) { - *--sp = PyList_GET_ITEM(l, ll - j); - } - /* Resize the list. */ - Py_SIZE(l) = ll - argcntafter; - Py_DECREF(it); - return 1; + int i = 0, j = 0; + Py_ssize_t ll = 0; + PyObject *it; /* iter(v) */ + PyObject *w; + PyObject *l = NULL; /* variable list */ + + assert(v != NULL); + + it = PyObject_GetIter(v); + if (it == NULL) + goto Error; + + for (; i < argcnt; i++) { + w = PyIter_Next(it); + if (w == NULL) { + /* Iterator done, via error or exhaustion. */ + if (!PyErr_Occurred()) { + PyErr_Format(PyExc_ValueError, + "need more than %d value%s to unpack", + i, i == 1 ? "" : "s"); + } + goto Error; + } + *--sp = w; + } + + if (argcntafter == -1) { + /* We better have exhausted the iterator now. */ + w = PyIter_Next(it); + if (w == NULL) { + if (PyErr_Occurred()) + goto Error; + Py_DECREF(it); + return 1; + } + Py_DECREF(w); + PyErr_SetString(PyExc_ValueError, "too many values to unpack"); + goto Error; + } + + l = PySequence_List(it); + if (l == NULL) + goto Error; + *--sp = l; + i++; + + ll = PyList_GET_SIZE(l); + if (ll < argcntafter) { + PyErr_Format(PyExc_ValueError, "need more than %zd values to unpack", + argcnt + ll); + goto Error; + } + + /* Pop the "after-variable" args off the list. */ + for (j = argcntafter; j > 0; j--, i++) { + *--sp = PyList_GET_ITEM(l, ll - j); + } + /* Resize the list. */ + Py_SIZE(l) = ll - argcntafter; + Py_DECREF(it); + return 1; Error: - for (; i > 0; i--, sp++) - Py_DECREF(*sp); - Py_XDECREF(it); - return 0; + for (; i > 0; i--, sp++) + Py_DECREF(*sp); + Py_XDECREF(it); + return 0; } @@ -3380,223 +3380,223 @@ static int prtrace(PyObject *v, char *str) { - printf("%s ", str); - if (PyObject_Print(v, stdout, 0) != 0) - PyErr_Clear(); /* Don't know what else to do */ - printf("\n"); - return 1; + printf("%s ", str); + if (PyObject_Print(v, stdout, 0) != 0) + PyErr_Clear(); /* Don't know what else to do */ + printf("\n"); + return 1; } #endif static void call_exc_trace(Py_tracefunc func, PyObject *self, PyFrameObject *f) { - PyObject *type, *value, *traceback, *arg; - int err; - PyErr_Fetch(&type, &value, &traceback); - if (value == NULL) { - value = Py_None; - Py_INCREF(value); - } - arg = PyTuple_Pack(3, type, value, traceback); - if (arg == NULL) { - PyErr_Restore(type, value, traceback); - return; - } - err = call_trace(func, self, f, PyTrace_EXCEPTION, arg); - Py_DECREF(arg); - if (err == 0) - PyErr_Restore(type, value, traceback); - else { - Py_XDECREF(type); - Py_XDECREF(value); - Py_XDECREF(traceback); - } + PyObject *type, *value, *traceback, *arg; + int err; + PyErr_Fetch(&type, &value, &traceback); + if (value == NULL) { + value = Py_None; + Py_INCREF(value); + } + arg = PyTuple_Pack(3, type, value, traceback); + if (arg == NULL) { + PyErr_Restore(type, value, traceback); + return; + } + err = call_trace(func, self, f, PyTrace_EXCEPTION, arg); + Py_DECREF(arg); + if (err == 0) + PyErr_Restore(type, value, traceback); + else { + Py_XDECREF(type); + Py_XDECREF(value); + Py_XDECREF(traceback); + } } static int call_trace_protected(Py_tracefunc func, PyObject *obj, PyFrameObject *frame, - int what, PyObject *arg) + int what, PyObject *arg) { - PyObject *type, *value, *traceback; - int err; - PyErr_Fetch(&type, &value, &traceback); - err = call_trace(func, obj, frame, what, arg); - if (err == 0) - { - PyErr_Restore(type, value, traceback); - return 0; - } - else { - Py_XDECREF(type); - Py_XDECREF(value); - Py_XDECREF(traceback); - return -1; - } + PyObject *type, *value, *traceback; + int err; + PyErr_Fetch(&type, &value, &traceback); + err = call_trace(func, obj, frame, what, arg); + if (err == 0) + { + PyErr_Restore(type, value, traceback); + return 0; + } + else { + Py_XDECREF(type); + Py_XDECREF(value); + Py_XDECREF(traceback); + return -1; + } } static int call_trace(Py_tracefunc func, PyObject *obj, PyFrameObject *frame, - int what, PyObject *arg) + int what, PyObject *arg) { - register PyThreadState *tstate = frame->f_tstate; - int result; - if (tstate->tracing) - return 0; - tstate->tracing++; - tstate->use_tracing = 0; - result = func(obj, frame, what, arg); - tstate->use_tracing = ((tstate->c_tracefunc != NULL) - || (tstate->c_profilefunc != NULL)); - tstate->tracing--; - return result; + register PyThreadState *tstate = frame->f_tstate; + int result; + if (tstate->tracing) + return 0; + tstate->tracing++; + tstate->use_tracing = 0; + result = func(obj, frame, what, arg); + tstate->use_tracing = ((tstate->c_tracefunc != NULL) + || (tstate->c_profilefunc != NULL)); + tstate->tracing--; + return result; } PyObject * _PyEval_CallTracing(PyObject *func, PyObject *args) { - PyFrameObject *frame = PyEval_GetFrame(); - PyThreadState *tstate = frame->f_tstate; - int save_tracing = tstate->tracing; - int save_use_tracing = tstate->use_tracing; - PyObject *result; - - tstate->tracing = 0; - tstate->use_tracing = ((tstate->c_tracefunc != NULL) - || (tstate->c_profilefunc != NULL)); - result = PyObject_Call(func, args, NULL); - tstate->tracing = save_tracing; - tstate->use_tracing = save_use_tracing; - return result; + PyFrameObject *frame = PyEval_GetFrame(); + PyThreadState *tstate = frame->f_tstate; + int save_tracing = tstate->tracing; + int save_use_tracing = tstate->use_tracing; + PyObject *result; + + tstate->tracing = 0; + tstate->use_tracing = ((tstate->c_tracefunc != NULL) + || (tstate->c_profilefunc != NULL)); + result = PyObject_Call(func, args, NULL); + tstate->tracing = save_tracing; + tstate->use_tracing = save_use_tracing; + return result; } static int maybe_call_line_trace(Py_tracefunc func, PyObject *obj, - PyFrameObject *frame, int *instr_lb, int *instr_ub, - int *instr_prev) + PyFrameObject *frame, int *instr_lb, int *instr_ub, + int *instr_prev) { - int result = 0; + int result = 0; - /* If the last instruction executed isn't in the current - instruction window, reset the window. If the last - instruction happens to fall at the start of a line or if it - represents a jump backwards, call the trace function. - */ - if ((frame->f_lasti < *instr_lb || frame->f_lasti >= *instr_ub)) { - int line; - PyAddrPair bounds; - - line = PyCode_CheckLineNumber(frame->f_code, frame->f_lasti, - &bounds); - if (line >= 0) { - frame->f_lineno = line; - result = call_trace(func, obj, frame, - PyTrace_LINE, Py_None); - } - *instr_lb = bounds.ap_lower; - *instr_ub = bounds.ap_upper; - } - else if (frame->f_lasti <= *instr_prev) { - result = call_trace(func, obj, frame, PyTrace_LINE, Py_None); - } - *instr_prev = frame->f_lasti; - return result; + /* If the last instruction executed isn't in the current + instruction window, reset the window. If the last + instruction happens to fall at the start of a line or if it + represents a jump backwards, call the trace function. + */ + if ((frame->f_lasti < *instr_lb || frame->f_lasti >= *instr_ub)) { + int line; + PyAddrPair bounds; + + line = PyCode_CheckLineNumber(frame->f_code, frame->f_lasti, + &bounds); + if (line >= 0) { + frame->f_lineno = line; + result = call_trace(func, obj, frame, + PyTrace_LINE, Py_None); + } + *instr_lb = bounds.ap_lower; + *instr_ub = bounds.ap_upper; + } + else if (frame->f_lasti <= *instr_prev) { + result = call_trace(func, obj, frame, PyTrace_LINE, Py_None); + } + *instr_prev = frame->f_lasti; + return result; } void PyEval_SetProfile(Py_tracefunc func, PyObject *arg) { - PyThreadState *tstate = PyThreadState_GET(); - PyObject *temp = tstate->c_profileobj; - Py_XINCREF(arg); - tstate->c_profilefunc = NULL; - tstate->c_profileobj = NULL; - /* Must make sure that tracing is not ignored if 'temp' is freed */ - tstate->use_tracing = tstate->c_tracefunc != NULL; - Py_XDECREF(temp); - tstate->c_profilefunc = func; - tstate->c_profileobj = arg; - /* Flag that tracing or profiling is turned on */ - tstate->use_tracing = (func != NULL) || (tstate->c_tracefunc != NULL); + PyThreadState *tstate = PyThreadState_GET(); + PyObject *temp = tstate->c_profileobj; + Py_XINCREF(arg); + tstate->c_profilefunc = NULL; + tstate->c_profileobj = NULL; + /* Must make sure that tracing is not ignored if 'temp' is freed */ + tstate->use_tracing = tstate->c_tracefunc != NULL; + Py_XDECREF(temp); + tstate->c_profilefunc = func; + tstate->c_profileobj = arg; + /* Flag that tracing or profiling is turned on */ + tstate->use_tracing = (func != NULL) || (tstate->c_tracefunc != NULL); } void PyEval_SetTrace(Py_tracefunc func, PyObject *arg) { - PyThreadState *tstate = PyThreadState_GET(); - PyObject *temp = tstate->c_traceobj; - _Py_TracingPossible += (func != NULL) - (tstate->c_tracefunc != NULL); - Py_XINCREF(arg); - tstate->c_tracefunc = NULL; - tstate->c_traceobj = NULL; - /* Must make sure that profiling is not ignored if 'temp' is freed */ - tstate->use_tracing = tstate->c_profilefunc != NULL; - Py_XDECREF(temp); - tstate->c_tracefunc = func; - tstate->c_traceobj = arg; - /* Flag that tracing or profiling is turned on */ - tstate->use_tracing = ((func != NULL) - || (tstate->c_profilefunc != NULL)); + PyThreadState *tstate = PyThreadState_GET(); + PyObject *temp = tstate->c_traceobj; + _Py_TracingPossible += (func != NULL) - (tstate->c_tracefunc != NULL); + Py_XINCREF(arg); + tstate->c_tracefunc = NULL; + tstate->c_traceobj = NULL; + /* Must make sure that profiling is not ignored if 'temp' is freed */ + tstate->use_tracing = tstate->c_profilefunc != NULL; + Py_XDECREF(temp); + tstate->c_tracefunc = func; + tstate->c_traceobj = arg; + /* Flag that tracing or profiling is turned on */ + tstate->use_tracing = ((func != NULL) + || (tstate->c_profilefunc != NULL)); } PyObject * PyEval_GetBuiltins(void) { - PyFrameObject *current_frame = PyEval_GetFrame(); - if (current_frame == NULL) - return PyThreadState_GET()->interp->builtins; - else - return current_frame->f_builtins; + PyFrameObject *current_frame = PyEval_GetFrame(); + if (current_frame == NULL) + return PyThreadState_GET()->interp->builtins; + else + return current_frame->f_builtins; } PyObject * PyEval_GetLocals(void) { - PyFrameObject *current_frame = PyEval_GetFrame(); - if (current_frame == NULL) - return NULL; - PyFrame_FastToLocals(current_frame); - return current_frame->f_locals; + PyFrameObject *current_frame = PyEval_GetFrame(); + if (current_frame == NULL) + return NULL; + PyFrame_FastToLocals(current_frame); + return current_frame->f_locals; } PyObject * PyEval_GetGlobals(void) { - PyFrameObject *current_frame = PyEval_GetFrame(); - if (current_frame == NULL) - return NULL; - else - return current_frame->f_globals; + PyFrameObject *current_frame = PyEval_GetFrame(); + if (current_frame == NULL) + return NULL; + else + return current_frame->f_globals; } PyFrameObject * PyEval_GetFrame(void) { - PyThreadState *tstate = PyThreadState_GET(); - return _PyThreadState_GetFrame(tstate); + PyThreadState *tstate = PyThreadState_GET(); + return _PyThreadState_GetFrame(tstate); } int PyEval_MergeCompilerFlags(PyCompilerFlags *cf) { - PyFrameObject *current_frame = PyEval_GetFrame(); - int result = cf->cf_flags != 0; + PyFrameObject *current_frame = PyEval_GetFrame(); + int result = cf->cf_flags != 0; - if (current_frame != NULL) { - const int codeflags = current_frame->f_code->co_flags; - const int compilerflags = codeflags & PyCF_MASK; - if (compilerflags) { - result = 1; - cf->cf_flags |= compilerflags; - } + if (current_frame != NULL) { + const int codeflags = current_frame->f_code->co_flags; + const int compilerflags = codeflags & PyCF_MASK; + if (compilerflags) { + result = 1; + cf->cf_flags |= compilerflags; + } #if 0 /* future keyword */ - if (codeflags & CO_GENERATOR_ALLOWED) { - result = 1; - cf->cf_flags |= CO_GENERATOR_ALLOWED; - } + if (codeflags & CO_GENERATOR_ALLOWED) { + result = 1; + cf->cf_flags |= CO_GENERATOR_ALLOWED; + } #endif - } - return result; + } + return result; } @@ -3609,194 +3609,194 @@ PyObject * PyEval_CallObject(PyObject *func, PyObject *arg) { - return PyEval_CallObjectWithKeywords(func, arg, (PyObject *)NULL); + return PyEval_CallObjectWithKeywords(func, arg, (PyObject *)NULL); } #define PyEval_CallObject(func,arg) \ - PyEval_CallObjectWithKeywords(func, arg, (PyObject *)NULL) + PyEval_CallObjectWithKeywords(func, arg, (PyObject *)NULL) PyObject * PyEval_CallObjectWithKeywords(PyObject *func, PyObject *arg, PyObject *kw) { - PyObject *result; + PyObject *result; - if (arg == NULL) { - arg = PyTuple_New(0); - if (arg == NULL) - return NULL; - } - else if (!PyTuple_Check(arg)) { - PyErr_SetString(PyExc_TypeError, - "argument list must be a tuple"); - return NULL; - } - else - Py_INCREF(arg); - - if (kw != NULL && !PyDict_Check(kw)) { - PyErr_SetString(PyExc_TypeError, - "keyword list must be a dictionary"); - Py_DECREF(arg); - return NULL; - } - - result = PyObject_Call(func, arg, kw); - Py_DECREF(arg); - return result; + if (arg == NULL) { + arg = PyTuple_New(0); + if (arg == NULL) + return NULL; + } + else if (!PyTuple_Check(arg)) { + PyErr_SetString(PyExc_TypeError, + "argument list must be a tuple"); + return NULL; + } + else + Py_INCREF(arg); + + if (kw != NULL && !PyDict_Check(kw)) { + PyErr_SetString(PyExc_TypeError, + "keyword list must be a dictionary"); + Py_DECREF(arg); + return NULL; + } + + result = PyObject_Call(func, arg, kw); + Py_DECREF(arg); + return result; } const char * PyEval_GetFuncName(PyObject *func) { - if (PyMethod_Check(func)) - return PyEval_GetFuncName(PyMethod_GET_FUNCTION(func)); - else if (PyFunction_Check(func)) - return _PyUnicode_AsString(((PyFunctionObject*)func)->func_name); - else if (PyCFunction_Check(func)) - return ((PyCFunctionObject*)func)->m_ml->ml_name; - else - return func->ob_type->tp_name; + if (PyMethod_Check(func)) + return PyEval_GetFuncName(PyMethod_GET_FUNCTION(func)); + else if (PyFunction_Check(func)) + return _PyUnicode_AsString(((PyFunctionObject*)func)->func_name); + else if (PyCFunction_Check(func)) + return ((PyCFunctionObject*)func)->m_ml->ml_name; + else + return func->ob_type->tp_name; } const char * PyEval_GetFuncDesc(PyObject *func) { - if (PyMethod_Check(func)) - return "()"; - else if (PyFunction_Check(func)) - return "()"; - else if (PyCFunction_Check(func)) - return "()"; - else - return " object"; + if (PyMethod_Check(func)) + return "()"; + else if (PyFunction_Check(func)) + return "()"; + else if (PyCFunction_Check(func)) + return "()"; + else + return " object"; } static void err_args(PyObject *func, int flags, int nargs) { - if (flags & METH_NOARGS) - PyErr_Format(PyExc_TypeError, - "%.200s() takes no arguments (%d given)", - ((PyCFunctionObject *)func)->m_ml->ml_name, - nargs); - else - PyErr_Format(PyExc_TypeError, - "%.200s() takes exactly one argument (%d given)", - ((PyCFunctionObject *)func)->m_ml->ml_name, - nargs); + if (flags & METH_NOARGS) + PyErr_Format(PyExc_TypeError, + "%.200s() takes no arguments (%d given)", + ((PyCFunctionObject *)func)->m_ml->ml_name, + nargs); + else + PyErr_Format(PyExc_TypeError, + "%.200s() takes exactly one argument (%d given)", + ((PyCFunctionObject *)func)->m_ml->ml_name, + nargs); } #define C_TRACE(x, call) \ if (tstate->use_tracing && tstate->c_profilefunc) { \ - if (call_trace(tstate->c_profilefunc, \ - tstate->c_profileobj, \ - tstate->frame, PyTrace_C_CALL, \ - func)) { \ - x = NULL; \ - } \ - else { \ - x = call; \ - if (tstate->c_profilefunc != NULL) { \ - if (x == NULL) { \ - call_trace_protected(tstate->c_profilefunc, \ - tstate->c_profileobj, \ - tstate->frame, PyTrace_C_EXCEPTION, \ - func); \ - /* XXX should pass (type, value, tb) */ \ - } else { \ - if (call_trace(tstate->c_profilefunc, \ - tstate->c_profileobj, \ - tstate->frame, PyTrace_C_RETURN, \ - func)) { \ - Py_DECREF(x); \ - x = NULL; \ - } \ - } \ - } \ - } \ + if (call_trace(tstate->c_profilefunc, \ + tstate->c_profileobj, \ + tstate->frame, PyTrace_C_CALL, \ + func)) { \ + x = NULL; \ + } \ + else { \ + x = call; \ + if (tstate->c_profilefunc != NULL) { \ + if (x == NULL) { \ + call_trace_protected(tstate->c_profilefunc, \ + tstate->c_profileobj, \ + tstate->frame, PyTrace_C_EXCEPTION, \ + func); \ + /* XXX should pass (type, value, tb) */ \ + } else { \ + if (call_trace(tstate->c_profilefunc, \ + tstate->c_profileobj, \ + tstate->frame, PyTrace_C_RETURN, \ + func)) { \ + Py_DECREF(x); \ + x = NULL; \ + } \ + } \ + } \ + } \ } else { \ - x = call; \ - } + x = call; \ + } static PyObject * call_function(PyObject ***pp_stack, int oparg #ifdef WITH_TSC - , uint64* pintr0, uint64* pintr1 + , uint64* pintr0, uint64* pintr1 #endif - ) + ) { - int na = oparg & 0xff; - int nk = (oparg>>8) & 0xff; - int n = na + 2 * nk; - PyObject **pfunc = (*pp_stack) - n - 1; - PyObject *func = *pfunc; - PyObject *x, *w; - - /* Always dispatch PyCFunction first, because these are - presumed to be the most frequent callable object. - */ - if (PyCFunction_Check(func) && nk == 0) { - int flags = PyCFunction_GET_FLAGS(func); - PyThreadState *tstate = PyThreadState_GET(); - - PCALL(PCALL_CFUNCTION); - if (flags & (METH_NOARGS | METH_O)) { - PyCFunction meth = PyCFunction_GET_FUNCTION(func); - PyObject *self = PyCFunction_GET_SELF(func); - if (flags & METH_NOARGS && na == 0) { - C_TRACE(x, (*meth)(self,NULL)); - } - else if (flags & METH_O && na == 1) { - PyObject *arg = EXT_POP(*pp_stack); - C_TRACE(x, (*meth)(self,arg)); - Py_DECREF(arg); - } - else { - err_args(func, flags, na); - x = NULL; - } - } - else { - PyObject *callargs; - callargs = load_args(pp_stack, na); - READ_TIMESTAMP(*pintr0); - C_TRACE(x, PyCFunction_Call(func,callargs,NULL)); - READ_TIMESTAMP(*pintr1); - Py_XDECREF(callargs); - } - } else { - if (PyMethod_Check(func) && PyMethod_GET_SELF(func) != NULL) { - /* optimize access to bound methods */ - PyObject *self = PyMethod_GET_SELF(func); - PCALL(PCALL_METHOD); - PCALL(PCALL_BOUND_METHOD); - Py_INCREF(self); - func = PyMethod_GET_FUNCTION(func); - Py_INCREF(func); - Py_DECREF(*pfunc); - *pfunc = self; - na++; - n++; - } else - Py_INCREF(func); - READ_TIMESTAMP(*pintr0); - if (PyFunction_Check(func)) - x = fast_function(func, pp_stack, n, na, nk); - else - x = do_call(func, pp_stack, na, nk); - READ_TIMESTAMP(*pintr1); - Py_DECREF(func); - } - - /* Clear the stack of the function object. Also removes - the arguments in case they weren't consumed already - (fast_function() and err_args() leave them on the stack). - */ - while ((*pp_stack) > pfunc) { - w = EXT_POP(*pp_stack); - Py_DECREF(w); - PCALL(PCALL_POP); - } - return x; + int na = oparg & 0xff; + int nk = (oparg>>8) & 0xff; + int n = na + 2 * nk; + PyObject **pfunc = (*pp_stack) - n - 1; + PyObject *func = *pfunc; + PyObject *x, *w; + + /* Always dispatch PyCFunction first, because these are + presumed to be the most frequent callable object. + */ + if (PyCFunction_Check(func) && nk == 0) { + int flags = PyCFunction_GET_FLAGS(func); + PyThreadState *tstate = PyThreadState_GET(); + + PCALL(PCALL_CFUNCTION); + if (flags & (METH_NOARGS | METH_O)) { + PyCFunction meth = PyCFunction_GET_FUNCTION(func); + PyObject *self = PyCFunction_GET_SELF(func); + if (flags & METH_NOARGS && na == 0) { + C_TRACE(x, (*meth)(self,NULL)); + } + else if (flags & METH_O && na == 1) { + PyObject *arg = EXT_POP(*pp_stack); + C_TRACE(x, (*meth)(self,arg)); + Py_DECREF(arg); + } + else { + err_args(func, flags, na); + x = NULL; + } + } + else { + PyObject *callargs; + callargs = load_args(pp_stack, na); + READ_TIMESTAMP(*pintr0); + C_TRACE(x, PyCFunction_Call(func,callargs,NULL)); + READ_TIMESTAMP(*pintr1); + Py_XDECREF(callargs); + } + } else { + if (PyMethod_Check(func) && PyMethod_GET_SELF(func) != NULL) { + /* optimize access to bound methods */ + PyObject *self = PyMethod_GET_SELF(func); + PCALL(PCALL_METHOD); + PCALL(PCALL_BOUND_METHOD); + Py_INCREF(self); + func = PyMethod_GET_FUNCTION(func); + Py_INCREF(func); + Py_DECREF(*pfunc); + *pfunc = self; + na++; + n++; + } else + Py_INCREF(func); + READ_TIMESTAMP(*pintr0); + if (PyFunction_Check(func)) + x = fast_function(func, pp_stack, n, na, nk); + else + x = do_call(func, pp_stack, na, nk); + READ_TIMESTAMP(*pintr1); + Py_DECREF(func); + } + + /* Clear the stack of the function object. Also removes + the arguments in case they weren't consumed already + (fast_function() and err_args() leave them on the stack). + */ + while ((*pp_stack) > pfunc) { + w = EXT_POP(*pp_stack); + Py_DECREF(w); + PCALL(PCALL_POP); + } + return x; } /* The fast_function() function optimize calls for which no argument @@ -3811,275 +3811,275 @@ static PyObject * fast_function(PyObject *func, PyObject ***pp_stack, int n, int na, int nk) { - PyCodeObject *co = (PyCodeObject *)PyFunction_GET_CODE(func); - PyObject *globals = PyFunction_GET_GLOBALS(func); - PyObject *argdefs = PyFunction_GET_DEFAULTS(func); - PyObject *kwdefs = PyFunction_GET_KW_DEFAULTS(func); - PyObject **d = NULL; - int nd = 0; - - PCALL(PCALL_FUNCTION); - PCALL(PCALL_FAST_FUNCTION); - if (argdefs == NULL && co->co_argcount == n && - co->co_kwonlyargcount == 0 && nk==0 && - co->co_flags == (CO_OPTIMIZED | CO_NEWLOCALS | CO_NOFREE)) { - PyFrameObject *f; - PyObject *retval = NULL; - PyThreadState *tstate = PyThreadState_GET(); - PyObject **fastlocals, **stack; - int i; - - PCALL(PCALL_FASTER_FUNCTION); - assert(globals != NULL); - /* XXX Perhaps we should create a specialized - PyFrame_New() that doesn't take locals, but does - take builtins without sanity checking them. - */ - assert(tstate != NULL); - f = PyFrame_New(tstate, co, globals, NULL); - if (f == NULL) - return NULL; - - fastlocals = f->f_localsplus; - stack = (*pp_stack) - n; - - for (i = 0; i < n; i++) { - Py_INCREF(*stack); - fastlocals[i] = *stack++; - } - retval = PyEval_EvalFrameEx(f,0); - ++tstate->recursion_depth; - Py_DECREF(f); - --tstate->recursion_depth; - return retval; - } - if (argdefs != NULL) { - d = &PyTuple_GET_ITEM(argdefs, 0); - nd = Py_SIZE(argdefs); - } - return PyEval_EvalCodeEx(co, globals, - (PyObject *)NULL, (*pp_stack)-n, na, - (*pp_stack)-2*nk, nk, d, nd, kwdefs, - PyFunction_GET_CLOSURE(func)); + PyCodeObject *co = (PyCodeObject *)PyFunction_GET_CODE(func); + PyObject *globals = PyFunction_GET_GLOBALS(func); + PyObject *argdefs = PyFunction_GET_DEFAULTS(func); + PyObject *kwdefs = PyFunction_GET_KW_DEFAULTS(func); + PyObject **d = NULL; + int nd = 0; + + PCALL(PCALL_FUNCTION); + PCALL(PCALL_FAST_FUNCTION); + if (argdefs == NULL && co->co_argcount == n && + co->co_kwonlyargcount == 0 && nk==0 && + co->co_flags == (CO_OPTIMIZED | CO_NEWLOCALS | CO_NOFREE)) { + PyFrameObject *f; + PyObject *retval = NULL; + PyThreadState *tstate = PyThreadState_GET(); + PyObject **fastlocals, **stack; + int i; + + PCALL(PCALL_FASTER_FUNCTION); + assert(globals != NULL); + /* XXX Perhaps we should create a specialized + PyFrame_New() that doesn't take locals, but does + take builtins without sanity checking them. + */ + assert(tstate != NULL); + f = PyFrame_New(tstate, co, globals, NULL); + if (f == NULL) + return NULL; + + fastlocals = f->f_localsplus; + stack = (*pp_stack) - n; + + for (i = 0; i < n; i++) { + Py_INCREF(*stack); + fastlocals[i] = *stack++; + } + retval = PyEval_EvalFrameEx(f,0); + ++tstate->recursion_depth; + Py_DECREF(f); + --tstate->recursion_depth; + return retval; + } + if (argdefs != NULL) { + d = &PyTuple_GET_ITEM(argdefs, 0); + nd = Py_SIZE(argdefs); + } + return PyEval_EvalCodeEx(co, globals, + (PyObject *)NULL, (*pp_stack)-n, na, + (*pp_stack)-2*nk, nk, d, nd, kwdefs, + PyFunction_GET_CLOSURE(func)); } static PyObject * update_keyword_args(PyObject *orig_kwdict, int nk, PyObject ***pp_stack, PyObject *func) { - PyObject *kwdict = NULL; - if (orig_kwdict == NULL) - kwdict = PyDict_New(); - else { - kwdict = PyDict_Copy(orig_kwdict); - Py_DECREF(orig_kwdict); - } - if (kwdict == NULL) - return NULL; - while (--nk >= 0) { - int err; - PyObject *value = EXT_POP(*pp_stack); - PyObject *key = EXT_POP(*pp_stack); - if (PyDict_GetItem(kwdict, key) != NULL) { - PyErr_Format(PyExc_TypeError, - "%.200s%s got multiple values " - "for keyword argument '%U'", - PyEval_GetFuncName(func), - PyEval_GetFuncDesc(func), - key); - Py_DECREF(key); - Py_DECREF(value); - Py_DECREF(kwdict); - return NULL; - } - err = PyDict_SetItem(kwdict, key, value); - Py_DECREF(key); - Py_DECREF(value); - if (err) { - Py_DECREF(kwdict); - return NULL; - } - } - return kwdict; + PyObject *kwdict = NULL; + if (orig_kwdict == NULL) + kwdict = PyDict_New(); + else { + kwdict = PyDict_Copy(orig_kwdict); + Py_DECREF(orig_kwdict); + } + if (kwdict == NULL) + return NULL; + while (--nk >= 0) { + int err; + PyObject *value = EXT_POP(*pp_stack); + PyObject *key = EXT_POP(*pp_stack); + if (PyDict_GetItem(kwdict, key) != NULL) { + PyErr_Format(PyExc_TypeError, + "%.200s%s got multiple values " + "for keyword argument '%U'", + PyEval_GetFuncName(func), + PyEval_GetFuncDesc(func), + key); + Py_DECREF(key); + Py_DECREF(value); + Py_DECREF(kwdict); + return NULL; + } + err = PyDict_SetItem(kwdict, key, value); + Py_DECREF(key); + Py_DECREF(value); + if (err) { + Py_DECREF(kwdict); + return NULL; + } + } + return kwdict; } static PyObject * update_star_args(int nstack, int nstar, PyObject *stararg, - PyObject ***pp_stack) + PyObject ***pp_stack) { - PyObject *callargs, *w; + PyObject *callargs, *w; - callargs = PyTuple_New(nstack + nstar); - if (callargs == NULL) { - return NULL; - } - if (nstar) { - int i; - for (i = 0; i < nstar; i++) { - PyObject *a = PyTuple_GET_ITEM(stararg, i); - Py_INCREF(a); - PyTuple_SET_ITEM(callargs, nstack + i, a); - } - } - while (--nstack >= 0) { - w = EXT_POP(*pp_stack); - PyTuple_SET_ITEM(callargs, nstack, w); - } - return callargs; + callargs = PyTuple_New(nstack + nstar); + if (callargs == NULL) { + return NULL; + } + if (nstar) { + int i; + for (i = 0; i < nstar; i++) { + PyObject *a = PyTuple_GET_ITEM(stararg, i); + Py_INCREF(a); + PyTuple_SET_ITEM(callargs, nstack + i, a); + } + } + while (--nstack >= 0) { + w = EXT_POP(*pp_stack); + PyTuple_SET_ITEM(callargs, nstack, w); + } + return callargs; } static PyObject * load_args(PyObject ***pp_stack, int na) { - PyObject *args = PyTuple_New(na); - PyObject *w; + PyObject *args = PyTuple_New(na); + PyObject *w; - if (args == NULL) - return NULL; - while (--na >= 0) { - w = EXT_POP(*pp_stack); - PyTuple_SET_ITEM(args, na, w); - } - return args; + if (args == NULL) + return NULL; + while (--na >= 0) { + w = EXT_POP(*pp_stack); + PyTuple_SET_ITEM(args, na, w); + } + return args; } static PyObject * do_call(PyObject *func, PyObject ***pp_stack, int na, int nk) { - PyObject *callargs = NULL; - PyObject *kwdict = NULL; - PyObject *result = NULL; - - if (nk > 0) { - kwdict = update_keyword_args(NULL, nk, pp_stack, func); - if (kwdict == NULL) - goto call_fail; - } - callargs = load_args(pp_stack, na); - if (callargs == NULL) - goto call_fail; + PyObject *callargs = NULL; + PyObject *kwdict = NULL; + PyObject *result = NULL; + + if (nk > 0) { + kwdict = update_keyword_args(NULL, nk, pp_stack, func); + if (kwdict == NULL) + goto call_fail; + } + callargs = load_args(pp_stack, na); + if (callargs == NULL) + goto call_fail; #ifdef CALL_PROFILE - /* At this point, we have to look at the type of func to - update the call stats properly. Do it here so as to avoid - exposing the call stats machinery outside ceval.c - */ - if (PyFunction_Check(func)) - PCALL(PCALL_FUNCTION); - else if (PyMethod_Check(func)) - PCALL(PCALL_METHOD); - else if (PyType_Check(func)) - PCALL(PCALL_TYPE); - else if (PyCFunction_Check(func)) - PCALL(PCALL_CFUNCTION); - else - PCALL(PCALL_OTHER); -#endif - if (PyCFunction_Check(func)) { - PyThreadState *tstate = PyThreadState_GET(); - C_TRACE(result, PyCFunction_Call(func, callargs, kwdict)); - } - else - result = PyObject_Call(func, callargs, kwdict); + /* At this point, we have to look at the type of func to + update the call stats properly. Do it here so as to avoid + exposing the call stats machinery outside ceval.c + */ + if (PyFunction_Check(func)) + PCALL(PCALL_FUNCTION); + else if (PyMethod_Check(func)) + PCALL(PCALL_METHOD); + else if (PyType_Check(func)) + PCALL(PCALL_TYPE); + else if (PyCFunction_Check(func)) + PCALL(PCALL_CFUNCTION); + else + PCALL(PCALL_OTHER); +#endif + if (PyCFunction_Check(func)) { + PyThreadState *tstate = PyThreadState_GET(); + C_TRACE(result, PyCFunction_Call(func, callargs, kwdict)); + } + else + result = PyObject_Call(func, callargs, kwdict); call_fail: - Py_XDECREF(callargs); - Py_XDECREF(kwdict); - return result; + Py_XDECREF(callargs); + Py_XDECREF(kwdict); + return result; } static PyObject * ext_do_call(PyObject *func, PyObject ***pp_stack, int flags, int na, int nk) { - int nstar = 0; - PyObject *callargs = NULL; - PyObject *stararg = NULL; - PyObject *kwdict = NULL; - PyObject *result = NULL; - - if (flags & CALL_FLAG_KW) { - kwdict = EXT_POP(*pp_stack); - if (!PyDict_Check(kwdict)) { - PyObject *d; - d = PyDict_New(); - if (d == NULL) - goto ext_call_fail; - if (PyDict_Update(d, kwdict) != 0) { - Py_DECREF(d); - /* PyDict_Update raises attribute - * error (percolated from an attempt - * to get 'keys' attribute) instead of - * a type error if its second argument - * is not a mapping. - */ - if (PyErr_ExceptionMatches(PyExc_AttributeError)) { - PyErr_Format(PyExc_TypeError, - "%.200s%.200s argument after ** " - "must be a mapping, not %.200s", - PyEval_GetFuncName(func), - PyEval_GetFuncDesc(func), - kwdict->ob_type->tp_name); - } - goto ext_call_fail; - } - Py_DECREF(kwdict); - kwdict = d; - } - } - if (flags & CALL_FLAG_VAR) { - stararg = EXT_POP(*pp_stack); - if (!PyTuple_Check(stararg)) { - PyObject *t = NULL; - t = PySequence_Tuple(stararg); - if (t == NULL) { - if (PyErr_ExceptionMatches(PyExc_TypeError)) { - PyErr_Format(PyExc_TypeError, - "%.200s%.200s argument after * " - "must be a sequence, not %200s", - PyEval_GetFuncName(func), - PyEval_GetFuncDesc(func), - stararg->ob_type->tp_name); - } - goto ext_call_fail; - } - Py_DECREF(stararg); - stararg = t; - } - nstar = PyTuple_GET_SIZE(stararg); - } - if (nk > 0) { - kwdict = update_keyword_args(kwdict, nk, pp_stack, func); - if (kwdict == NULL) - goto ext_call_fail; - } - callargs = update_star_args(na, nstar, stararg, pp_stack); - if (callargs == NULL) - goto ext_call_fail; + int nstar = 0; + PyObject *callargs = NULL; + PyObject *stararg = NULL; + PyObject *kwdict = NULL; + PyObject *result = NULL; + + if (flags & CALL_FLAG_KW) { + kwdict = EXT_POP(*pp_stack); + if (!PyDict_Check(kwdict)) { + PyObject *d; + d = PyDict_New(); + if (d == NULL) + goto ext_call_fail; + if (PyDict_Update(d, kwdict) != 0) { + Py_DECREF(d); + /* PyDict_Update raises attribute + * error (percolated from an attempt + * to get 'keys' attribute) instead of + * a type error if its second argument + * is not a mapping. + */ + if (PyErr_ExceptionMatches(PyExc_AttributeError)) { + PyErr_Format(PyExc_TypeError, + "%.200s%.200s argument after ** " + "must be a mapping, not %.200s", + PyEval_GetFuncName(func), + PyEval_GetFuncDesc(func), + kwdict->ob_type->tp_name); + } + goto ext_call_fail; + } + Py_DECREF(kwdict); + kwdict = d; + } + } + if (flags & CALL_FLAG_VAR) { + stararg = EXT_POP(*pp_stack); + if (!PyTuple_Check(stararg)) { + PyObject *t = NULL; + t = PySequence_Tuple(stararg); + if (t == NULL) { + if (PyErr_ExceptionMatches(PyExc_TypeError)) { + PyErr_Format(PyExc_TypeError, + "%.200s%.200s argument after * " + "must be a sequence, not %200s", + PyEval_GetFuncName(func), + PyEval_GetFuncDesc(func), + stararg->ob_type->tp_name); + } + goto ext_call_fail; + } + Py_DECREF(stararg); + stararg = t; + } + nstar = PyTuple_GET_SIZE(stararg); + } + if (nk > 0) { + kwdict = update_keyword_args(kwdict, nk, pp_stack, func); + if (kwdict == NULL) + goto ext_call_fail; + } + callargs = update_star_args(na, nstar, stararg, pp_stack); + if (callargs == NULL) + goto ext_call_fail; #ifdef CALL_PROFILE - /* At this point, we have to look at the type of func to - update the call stats properly. Do it here so as to avoid - exposing the call stats machinery outside ceval.c - */ - if (PyFunction_Check(func)) - PCALL(PCALL_FUNCTION); - else if (PyMethod_Check(func)) - PCALL(PCALL_METHOD); - else if (PyType_Check(func)) - PCALL(PCALL_TYPE); - else if (PyCFunction_Check(func)) - PCALL(PCALL_CFUNCTION); - else - PCALL(PCALL_OTHER); -#endif - if (PyCFunction_Check(func)) { - PyThreadState *tstate = PyThreadState_GET(); - C_TRACE(result, PyCFunction_Call(func, callargs, kwdict)); - } - else - result = PyObject_Call(func, callargs, kwdict); + /* At this point, we have to look at the type of func to + update the call stats properly. Do it here so as to avoid + exposing the call stats machinery outside ceval.c + */ + if (PyFunction_Check(func)) + PCALL(PCALL_FUNCTION); + else if (PyMethod_Check(func)) + PCALL(PCALL_METHOD); + else if (PyType_Check(func)) + PCALL(PCALL_TYPE); + else if (PyCFunction_Check(func)) + PCALL(PCALL_CFUNCTION); + else + PCALL(PCALL_OTHER); +#endif + if (PyCFunction_Check(func)) { + PyThreadState *tstate = PyThreadState_GET(); + C_TRACE(result, PyCFunction_Call(func, callargs, kwdict)); + } + else + result = PyObject_Call(func, callargs, kwdict); ext_call_fail: - Py_XDECREF(callargs); - Py_XDECREF(kwdict); - Py_XDECREF(stararg); - return result; + Py_XDECREF(callargs); + Py_XDECREF(kwdict); + Py_XDECREF(stararg); + return result; } /* Extract a slice index from a PyInt or PyLong or an object with the @@ -4095,245 +4095,245 @@ int _PyEval_SliceIndex(PyObject *v, Py_ssize_t *pi) { - if (v != NULL) { - Py_ssize_t x; - if (PyIndex_Check(v)) { - x = PyNumber_AsSsize_t(v, NULL); - if (x == -1 && PyErr_Occurred()) - return 0; - } - else { - PyErr_SetString(PyExc_TypeError, - "slice indices must be integers or " - "None or have an __index__ method"); - return 0; - } - *pi = x; - } - return 1; + if (v != NULL) { + Py_ssize_t x; + if (PyIndex_Check(v)) { + x = PyNumber_AsSsize_t(v, NULL); + if (x == -1 && PyErr_Occurred()) + return 0; + } + else { + PyErr_SetString(PyExc_TypeError, + "slice indices must be integers or " + "None or have an __index__ method"); + return 0; + } + *pi = x; + } + return 1; } #define CANNOT_CATCH_MSG "catching classes that do not inherit from "\ - "BaseException is not allowed" + "BaseException is not allowed" static PyObject * cmp_outcome(int op, register PyObject *v, register PyObject *w) { - int res = 0; - switch (op) { - case PyCmp_IS: - res = (v == w); - break; - case PyCmp_IS_NOT: - res = (v != w); - break; - case PyCmp_IN: - res = PySequence_Contains(w, v); - if (res < 0) - return NULL; - break; - case PyCmp_NOT_IN: - res = PySequence_Contains(w, v); - if (res < 0) - return NULL; - res = !res; - break; - case PyCmp_EXC_MATCH: - if (PyTuple_Check(w)) { - Py_ssize_t i, length; - length = PyTuple_Size(w); - for (i = 0; i < length; i += 1) { - PyObject *exc = PyTuple_GET_ITEM(w, i); - if (!PyExceptionClass_Check(exc)) { - PyErr_SetString(PyExc_TypeError, - CANNOT_CATCH_MSG); - return NULL; - } - } - } - else { - if (!PyExceptionClass_Check(w)) { - PyErr_SetString(PyExc_TypeError, - CANNOT_CATCH_MSG); - return NULL; - } - } - res = PyErr_GivenExceptionMatches(v, w); - break; - default: - return PyObject_RichCompare(v, w, op); - } - v = res ? Py_True : Py_False; - Py_INCREF(v); - return v; + int res = 0; + switch (op) { + case PyCmp_IS: + res = (v == w); + break; + case PyCmp_IS_NOT: + res = (v != w); + break; + case PyCmp_IN: + res = PySequence_Contains(w, v); + if (res < 0) + return NULL; + break; + case PyCmp_NOT_IN: + res = PySequence_Contains(w, v); + if (res < 0) + return NULL; + res = !res; + break; + case PyCmp_EXC_MATCH: + if (PyTuple_Check(w)) { + Py_ssize_t i, length; + length = PyTuple_Size(w); + for (i = 0; i < length; i += 1) { + PyObject *exc = PyTuple_GET_ITEM(w, i); + if (!PyExceptionClass_Check(exc)) { + PyErr_SetString(PyExc_TypeError, + CANNOT_CATCH_MSG); + return NULL; + } + } + } + else { + if (!PyExceptionClass_Check(w)) { + PyErr_SetString(PyExc_TypeError, + CANNOT_CATCH_MSG); + return NULL; + } + } + res = PyErr_GivenExceptionMatches(v, w); + break; + default: + return PyObject_RichCompare(v, w, op); + } + v = res ? Py_True : Py_False; + Py_INCREF(v); + return v; } static PyObject * import_from(PyObject *v, PyObject *name) { - PyObject *x; + PyObject *x; - x = PyObject_GetAttr(v, name); - if (x == NULL && PyErr_ExceptionMatches(PyExc_AttributeError)) { - PyErr_Format(PyExc_ImportError, "cannot import name %S", name); - } - return x; + x = PyObject_GetAttr(v, name); + if (x == NULL && PyErr_ExceptionMatches(PyExc_AttributeError)) { + PyErr_Format(PyExc_ImportError, "cannot import name %S", name); + } + return x; } static int import_all_from(PyObject *locals, PyObject *v) { - PyObject *all = PyObject_GetAttrString(v, "__all__"); - PyObject *dict, *name, *value; - int skip_leading_underscores = 0; - int pos, err; - - if (all == NULL) { - if (!PyErr_ExceptionMatches(PyExc_AttributeError)) - return -1; /* Unexpected error */ - PyErr_Clear(); - dict = PyObject_GetAttrString(v, "__dict__"); - if (dict == NULL) { - if (!PyErr_ExceptionMatches(PyExc_AttributeError)) - return -1; - PyErr_SetString(PyExc_ImportError, - "from-import-* object has no __dict__ and no __all__"); - return -1; - } - all = PyMapping_Keys(dict); - Py_DECREF(dict); - if (all == NULL) - return -1; - skip_leading_underscores = 1; - } - - for (pos = 0, err = 0; ; pos++) { - name = PySequence_GetItem(all, pos); - if (name == NULL) { - if (!PyErr_ExceptionMatches(PyExc_IndexError)) - err = -1; - else - PyErr_Clear(); - break; - } - if (skip_leading_underscores && - PyUnicode_Check(name) && - PyUnicode_AS_UNICODE(name)[0] == '_') - { - Py_DECREF(name); - continue; - } - value = PyObject_GetAttr(v, name); - if (value == NULL) - err = -1; - else if (PyDict_CheckExact(locals)) - err = PyDict_SetItem(locals, name, value); - else - err = PyObject_SetItem(locals, name, value); - Py_DECREF(name); - Py_XDECREF(value); - if (err != 0) - break; - } - Py_DECREF(all); - return err; + PyObject *all = PyObject_GetAttrString(v, "__all__"); + PyObject *dict, *name, *value; + int skip_leading_underscores = 0; + int pos, err; + + if (all == NULL) { + if (!PyErr_ExceptionMatches(PyExc_AttributeError)) + return -1; /* Unexpected error */ + PyErr_Clear(); + dict = PyObject_GetAttrString(v, "__dict__"); + if (dict == NULL) { + if (!PyErr_ExceptionMatches(PyExc_AttributeError)) + return -1; + PyErr_SetString(PyExc_ImportError, + "from-import-* object has no __dict__ and no __all__"); + return -1; + } + all = PyMapping_Keys(dict); + Py_DECREF(dict); + if (all == NULL) + return -1; + skip_leading_underscores = 1; + } + + for (pos = 0, err = 0; ; pos++) { + name = PySequence_GetItem(all, pos); + if (name == NULL) { + if (!PyErr_ExceptionMatches(PyExc_IndexError)) + err = -1; + else + PyErr_Clear(); + break; + } + if (skip_leading_underscores && + PyUnicode_Check(name) && + PyUnicode_AS_UNICODE(name)[0] == '_') + { + Py_DECREF(name); + continue; + } + value = PyObject_GetAttr(v, name); + if (value == NULL) + err = -1; + else if (PyDict_CheckExact(locals)) + err = PyDict_SetItem(locals, name, value); + else + err = PyObject_SetItem(locals, name, value); + Py_DECREF(name); + Py_XDECREF(value); + if (err != 0) + break; + } + Py_DECREF(all); + return err; } static void format_exc_check_arg(PyObject *exc, const char *format_str, PyObject *obj) { - const char *obj_str; + const char *obj_str; - if (!obj) - return; + if (!obj) + return; - obj_str = _PyUnicode_AsString(obj); - if (!obj_str) - return; + obj_str = _PyUnicode_AsString(obj); + if (!obj_str) + return; - PyErr_Format(exc, format_str, obj_str); + PyErr_Format(exc, format_str, obj_str); } static PyObject * unicode_concatenate(PyObject *v, PyObject *w, - PyFrameObject *f, unsigned char *next_instr) + PyFrameObject *f, unsigned char *next_instr) { - /* This function implements 'variable += expr' when both arguments - are (Unicode) strings. */ - Py_ssize_t v_len = PyUnicode_GET_SIZE(v); - Py_ssize_t w_len = PyUnicode_GET_SIZE(w); - Py_ssize_t new_len = v_len + w_len; - if (new_len < 0) { - PyErr_SetString(PyExc_OverflowError, - "strings are too large to concat"); - return NULL; - } - - if (v->ob_refcnt == 2) { - /* In the common case, there are 2 references to the value - * stored in 'variable' when the += is performed: one on the - * value stack (in 'v') and one still stored in the - * 'variable'. We try to delete the variable now to reduce - * the refcnt to 1. - */ - switch (*next_instr) { - case STORE_FAST: - { - int oparg = PEEKARG(); - PyObject **fastlocals = f->f_localsplus; - if (GETLOCAL(oparg) == v) - SETLOCAL(oparg, NULL); - break; - } - case STORE_DEREF: - { - PyObject **freevars = (f->f_localsplus + - f->f_code->co_nlocals); - PyObject *c = freevars[PEEKARG()]; - if (PyCell_GET(c) == v) - PyCell_Set(c, NULL); - break; - } - case STORE_NAME: - { - PyObject *names = f->f_code->co_names; - PyObject *name = GETITEM(names, PEEKARG()); - PyObject *locals = f->f_locals; - if (PyDict_CheckExact(locals) && - PyDict_GetItem(locals, name) == v) { - if (PyDict_DelItem(locals, name) != 0) { - PyErr_Clear(); - } - } - break; - } - } - } - - if (v->ob_refcnt == 1 && !PyUnicode_CHECK_INTERNED(v)) { - /* Now we own the last reference to 'v', so we can resize it - * in-place. - */ - if (PyUnicode_Resize(&v, new_len) != 0) { - /* XXX if PyUnicode_Resize() fails, 'v' has been - * deallocated so it cannot be put back into - * 'variable'. The MemoryError is raised when there - * is no value in 'variable', which might (very - * remotely) be a cause of incompatibilities. - */ - return NULL; - } - /* copy 'w' into the newly allocated area of 'v' */ - memcpy(PyUnicode_AS_UNICODE(v) + v_len, - PyUnicode_AS_UNICODE(w), w_len*sizeof(Py_UNICODE)); - return v; - } - else { - /* When in-place resizing is not an option. */ - w = PyUnicode_Concat(v, w); - Py_DECREF(v); - return w; - } + /* This function implements 'variable += expr' when both arguments + are (Unicode) strings. */ + Py_ssize_t v_len = PyUnicode_GET_SIZE(v); + Py_ssize_t w_len = PyUnicode_GET_SIZE(w); + Py_ssize_t new_len = v_len + w_len; + if (new_len < 0) { + PyErr_SetString(PyExc_OverflowError, + "strings are too large to concat"); + return NULL; + } + + if (v->ob_refcnt == 2) { + /* In the common case, there are 2 references to the value + * stored in 'variable' when the += is performed: one on the + * value stack (in 'v') and one still stored in the + * 'variable'. We try to delete the variable now to reduce + * the refcnt to 1. + */ + switch (*next_instr) { + case STORE_FAST: + { + int oparg = PEEKARG(); + PyObject **fastlocals = f->f_localsplus; + if (GETLOCAL(oparg) == v) + SETLOCAL(oparg, NULL); + break; + } + case STORE_DEREF: + { + PyObject **freevars = (f->f_localsplus + + f->f_code->co_nlocals); + PyObject *c = freevars[PEEKARG()]; + if (PyCell_GET(c) == v) + PyCell_Set(c, NULL); + break; + } + case STORE_NAME: + { + PyObject *names = f->f_code->co_names; + PyObject *name = GETITEM(names, PEEKARG()); + PyObject *locals = f->f_locals; + if (PyDict_CheckExact(locals) && + PyDict_GetItem(locals, name) == v) { + if (PyDict_DelItem(locals, name) != 0) { + PyErr_Clear(); + } + } + break; + } + } + } + + if (v->ob_refcnt == 1 && !PyUnicode_CHECK_INTERNED(v)) { + /* Now we own the last reference to 'v', so we can resize it + * in-place. + */ + if (PyUnicode_Resize(&v, new_len) != 0) { + /* XXX if PyUnicode_Resize() fails, 'v' has been + * deallocated so it cannot be put back into + * 'variable'. The MemoryError is raised when there + * is no value in 'variable', which might (very + * remotely) be a cause of incompatibilities. + */ + return NULL; + } + /* copy 'w' into the newly allocated area of 'v' */ + memcpy(PyUnicode_AS_UNICODE(v) + v_len, + PyUnicode_AS_UNICODE(w), w_len*sizeof(Py_UNICODE)); + return v; + } + else { + /* When in-place resizing is not an option. */ + w = PyUnicode_Concat(v, w); + Py_DECREF(v); + return w; + } } #ifdef DYNAMIC_EXECUTION_PROFILE @@ -4341,40 +4341,40 @@ static PyObject * getarray(long a[256]) { - int i; - PyObject *l = PyList_New(256); - if (l == NULL) return NULL; - for (i = 0; i < 256; i++) { - PyObject *x = PyLong_FromLong(a[i]); - if (x == NULL) { - Py_DECREF(l); - return NULL; - } - PyList_SetItem(l, i, x); - } - for (i = 0; i < 256; i++) - a[i] = 0; - return l; + int i; + PyObject *l = PyList_New(256); + if (l == NULL) return NULL; + for (i = 0; i < 256; i++) { + PyObject *x = PyLong_FromLong(a[i]); + if (x == NULL) { + Py_DECREF(l); + return NULL; + } + PyList_SetItem(l, i, x); + } + for (i = 0; i < 256; i++) + a[i] = 0; + return l; } PyObject * _Py_GetDXProfile(PyObject *self, PyObject *args) { #ifndef DXPAIRS - return getarray(dxp); + return getarray(dxp); #else - int i; - PyObject *l = PyList_New(257); - if (l == NULL) return NULL; - for (i = 0; i < 257; i++) { - PyObject *x = getarray(dxpairs[i]); - if (x == NULL) { - Py_DECREF(l); - return NULL; - } - PyList_SetItem(l, i, x); - } - return l; + int i; + PyObject *l = PyList_New(257); + if (l == NULL) return NULL; + for (i = 0; i < 257; i++) { + PyObject *x = getarray(dxpairs[i]); + if (x == NULL) { + Py_DECREF(l); + return NULL; + } + PyList_SetItem(l, i, x); + } + return l; #endif } Modified: python/branches/release31-maint/Python/codecs.c ============================================================================== --- python/branches/release31-maint/Python/codecs.c (original) +++ python/branches/release31-maint/Python/codecs.c Sun May 9 18:14:21 2010 @@ -30,14 +30,14 @@ { PyInterpreterState *interp = PyThreadState_GET()->interp; if (interp->codec_search_path == NULL && _PyCodecRegistry_Init()) - goto onError; + goto onError; if (search_function == NULL) { - PyErr_BadArgument(); - goto onError; + PyErr_BadArgument(); + goto onError; } if (!PyCallable_Check(search_function)) { - PyErr_SetString(PyExc_TypeError, "argument must be callable"); - goto onError; + PyErr_SetString(PyExc_TypeError, "argument must be callable"); + goto onError; } return PyList_Append(interp->codec_search_path, search_function); @@ -57,8 +57,8 @@ PyObject *v; if (len > PY_SSIZE_T_MAX) { - PyErr_SetString(PyExc_OverflowError, "string is too large"); - return NULL; + PyErr_SetString(PyExc_OverflowError, "string is too large"); + return NULL; } p = PyMem_Malloc(len + 1); @@ -70,7 +70,7 @@ ch = '-'; else ch = tolower(Py_CHARMASK(ch)); - p[i] = ch; + p[i] = ch; } p[i] = '\0'; v = PyUnicode_FromString(p); @@ -102,78 +102,78 @@ Py_ssize_t i, len; if (encoding == NULL) { - PyErr_BadArgument(); - goto onError; + PyErr_BadArgument(); + goto onError; } interp = PyThreadState_GET()->interp; if (interp->codec_search_path == NULL && _PyCodecRegistry_Init()) - goto onError; + goto onError; /* Convert the encoding to a normalized Python string: all characters are converted to lower case, spaces and hyphens are replaced with underscores. */ v = normalizestring(encoding); if (v == NULL) - goto onError; + goto onError; PyUnicode_InternInPlace(&v); /* First, try to lookup the name in the registry dictionary */ result = PyDict_GetItem(interp->codec_search_cache, v); if (result != NULL) { - Py_INCREF(result); - Py_DECREF(v); - return result; + Py_INCREF(result); + Py_DECREF(v); + return result; } /* Next, scan the search functions in order of registration */ args = PyTuple_New(1); if (args == NULL) - goto onError; + goto onError; PyTuple_SET_ITEM(args,0,v); len = PyList_Size(interp->codec_search_path); if (len < 0) - goto onError; + goto onError; if (len == 0) { - PyErr_SetString(PyExc_LookupError, - "no codec search functions registered: " - "can't find encoding"); - goto onError; + PyErr_SetString(PyExc_LookupError, + "no codec search functions registered: " + "can't find encoding"); + goto onError; } for (i = 0; i < len; i++) { - PyObject *func; + PyObject *func; - func = PyList_GetItem(interp->codec_search_path, i); - if (func == NULL) - goto onError; - result = PyEval_CallObject(func, args); - if (result == NULL) - goto onError; - if (result == Py_None) { - Py_DECREF(result); - continue; - } - if (!PyTuple_Check(result) || PyTuple_GET_SIZE(result) != 4) { - PyErr_SetString(PyExc_TypeError, - "codec search functions must return 4-tuples"); - Py_DECREF(result); - goto onError; - } - break; + func = PyList_GetItem(interp->codec_search_path, i); + if (func == NULL) + goto onError; + result = PyEval_CallObject(func, args); + if (result == NULL) + goto onError; + if (result == Py_None) { + Py_DECREF(result); + continue; + } + if (!PyTuple_Check(result) || PyTuple_GET_SIZE(result) != 4) { + PyErr_SetString(PyExc_TypeError, + "codec search functions must return 4-tuples"); + Py_DECREF(result); + goto onError; + } + break; } if (i == len) { - /* XXX Perhaps we should cache misses too ? */ - PyErr_Format(PyExc_LookupError, + /* XXX Perhaps we should cache misses too ? */ + PyErr_Format(PyExc_LookupError, "unknown encoding: %s", encoding); - goto onError; + goto onError; } /* Cache and return the result */ if (PyDict_SetItem(interp->codec_search_cache, v, result) < 0) { - Py_DECREF(result); - goto onError; + Py_DECREF(result); + goto onError; } Py_DECREF(args); return result; @@ -188,38 +188,38 @@ int PyCodec_KnownEncoding(const char *encoding) { PyObject *codecs; - + codecs = _PyCodec_Lookup(encoding); if (!codecs) { - PyErr_Clear(); - return 0; + PyErr_Clear(); + return 0; } else { - Py_DECREF(codecs); - return 1; + Py_DECREF(codecs); + return 1; } } static PyObject *args_tuple(PyObject *object, - const char *errors) + const char *errors) { PyObject *args; args = PyTuple_New(1 + (errors != NULL)); if (args == NULL) - return NULL; + return NULL; Py_INCREF(object); PyTuple_SET_ITEM(args,0,object); if (errors) { - PyObject *v; + PyObject *v; - v = PyUnicode_FromString(errors); - if (v == NULL) { - Py_DECREF(args); - return NULL; - } - PyTuple_SET_ITEM(args, 1, v); + v = PyUnicode_FromString(errors); + if (v == NULL) { + Py_DECREF(args); + return NULL; + } + PyTuple_SET_ITEM(args, 1, v); } return args; } @@ -234,7 +234,7 @@ codecs = _PyCodec_Lookup(encoding); if (codecs == NULL) - return NULL; + return NULL; v = PyTuple_GET_ITEM(codecs, index); Py_DECREF(codecs); Py_INCREF(v); @@ -245,22 +245,22 @@ static PyObject *codec_getincrementalcodec(const char *encoding, - const char *errors, - const char *attrname) + const char *errors, + const char *attrname) { PyObject *codecs, *ret, *inccodec; codecs = _PyCodec_Lookup(encoding); if (codecs == NULL) - return NULL; + return NULL; inccodec = PyObject_GetAttrString(codecs, attrname); Py_DECREF(codecs); if (inccodec == NULL) - return NULL; + return NULL; if (errors) - ret = PyObject_CallFunction(inccodec, "s", errors); + ret = PyObject_CallFunction(inccodec, "s", errors); else - ret = PyObject_CallFunction(inccodec, NULL); + ret = PyObject_CallFunction(inccodec, NULL); Py_DECREF(inccodec); return ret; } @@ -269,21 +269,21 @@ static PyObject *codec_getstreamcodec(const char *encoding, - PyObject *stream, - const char *errors, - const int index) + PyObject *stream, + const char *errors, + const int index) { PyObject *codecs, *streamcodec, *codeccls; codecs = _PyCodec_Lookup(encoding); if (codecs == NULL) - return NULL; + return NULL; codeccls = PyTuple_GET_ITEM(codecs, index); if (errors != NULL) - streamcodec = PyObject_CallFunction(codeccls, "Os", stream, errors); + streamcodec = PyObject_CallFunction(codeccls, "Os", stream, errors); else - streamcodec = PyObject_CallFunction(codeccls, "O", stream); + streamcodec = PyObject_CallFunction(codeccls, "O", stream); Py_DECREF(codecs); return streamcodec; } @@ -305,27 +305,27 @@ } PyObject *PyCodec_IncrementalEncoder(const char *encoding, - const char *errors) + const char *errors) { return codec_getincrementalcodec(encoding, errors, "incrementalencoder"); } PyObject *PyCodec_IncrementalDecoder(const char *encoding, - const char *errors) + const char *errors) { return codec_getincrementalcodec(encoding, errors, "incrementaldecoder"); } PyObject *PyCodec_StreamReader(const char *encoding, - PyObject *stream, - const char *errors) + PyObject *stream, + const char *errors) { return codec_getstreamcodec(encoding, stream, errors, 2); } PyObject *PyCodec_StreamWriter(const char *encoding, - PyObject *stream, - const char *errors) + PyObject *stream, + const char *errors) { return codec_getstreamcodec(encoding, stream, errors, 3); } @@ -336,8 +336,8 @@ errors is passed to the encoder factory as argument if non-NULL. */ PyObject *PyCodec_Encode(PyObject *object, - const char *encoding, - const char *errors) + const char *encoding, + const char *errors) { PyObject *encoder = NULL; PyObject *args = NULL, *result = NULL; @@ -345,21 +345,21 @@ encoder = PyCodec_Encoder(encoding); if (encoder == NULL) - goto onError; + goto onError; args = args_tuple(object, errors); if (args == NULL) - goto onError; + goto onError; result = PyEval_CallObject(encoder, args); if (result == NULL) - goto onError; + goto onError; if (!PyTuple_Check(result) || - PyTuple_GET_SIZE(result) != 2) { - PyErr_SetString(PyExc_TypeError, - "encoder must return a tuple (object, integer)"); - goto onError; + PyTuple_GET_SIZE(result) != 2) { + PyErr_SetString(PyExc_TypeError, + "encoder must return a tuple (object, integer)"); + goto onError; } v = PyTuple_GET_ITEM(result,0); Py_INCREF(v); @@ -369,7 +369,7 @@ Py_DECREF(encoder); Py_DECREF(result); return v; - + onError: Py_XDECREF(result); Py_XDECREF(args); @@ -383,8 +383,8 @@ errors is passed to the decoder factory as argument if non-NULL. */ PyObject *PyCodec_Decode(PyObject *object, - const char *encoding, - const char *errors) + const char *encoding, + const char *errors) { PyObject *decoder = NULL; PyObject *args = NULL, *result = NULL; @@ -392,20 +392,20 @@ decoder = PyCodec_Decoder(encoding); if (decoder == NULL) - goto onError; + goto onError; args = args_tuple(object, errors); if (args == NULL) - goto onError; + goto onError; result = PyEval_CallObject(decoder,args); if (result == NULL) - goto onError; + goto onError; if (!PyTuple_Check(result) || - PyTuple_GET_SIZE(result) != 2) { - PyErr_SetString(PyExc_TypeError, - "decoder must return a tuple (object,integer)"); - goto onError; + PyTuple_GET_SIZE(result) != 2) { + PyErr_SetString(PyExc_TypeError, + "decoder must return a tuple (object,integer)"); + goto onError; } v = PyTuple_GET_ITEM(result,0); Py_INCREF(v); @@ -433,13 +433,13 @@ { PyInterpreterState *interp = PyThreadState_GET()->interp; if (interp->codec_search_path == NULL && _PyCodecRegistry_Init()) - return -1; + return -1; if (!PyCallable_Check(error)) { - PyErr_SetString(PyExc_TypeError, "handler must be callable"); - return -1; + PyErr_SetString(PyExc_TypeError, "handler must be callable"); + return -1; } return PyDict_SetItemString(interp->codec_error_registry, - (char *)name, error); + (char *)name, error); } /* Lookup the error handling callback function registered under the @@ -451,15 +451,15 @@ PyInterpreterState *interp = PyThreadState_GET()->interp; if (interp->codec_search_path == NULL && _PyCodecRegistry_Init()) - return NULL; + return NULL; if (name==NULL) - name = "strict"; + name = "strict"; handler = PyDict_GetItemString(interp->codec_error_registry, (char *)name); if (!handler) - PyErr_Format(PyExc_LookupError, "unknown error handler name '%.400s'", name); + PyErr_Format(PyExc_LookupError, "unknown error handler name '%.400s'", name); else - Py_INCREF(handler); + Py_INCREF(handler); return handler; } @@ -482,7 +482,7 @@ if (PyExceptionInstance_Check(exc)) PyErr_SetObject(PyExceptionInstance_Class(exc), exc); else - PyErr_SetString(PyExc_TypeError, "codec must pass exception instance"); + PyErr_SetString(PyExc_TypeError, "codec must pass exception instance"); return NULL; } @@ -491,20 +491,20 @@ { Py_ssize_t end; if (PyObject_IsInstance(exc, PyExc_UnicodeEncodeError)) { - if (PyUnicodeEncodeError_GetEnd(exc, &end)) - return NULL; + if (PyUnicodeEncodeError_GetEnd(exc, &end)) + return NULL; } else if (PyObject_IsInstance(exc, PyExc_UnicodeDecodeError)) { - if (PyUnicodeDecodeError_GetEnd(exc, &end)) - return NULL; + if (PyUnicodeDecodeError_GetEnd(exc, &end)) + return NULL; } else if (PyObject_IsInstance(exc, PyExc_UnicodeTranslateError)) { - if (PyUnicodeTranslateError_GetEnd(exc, &end)) - return NULL; + if (PyUnicodeTranslateError_GetEnd(exc, &end)) + return NULL; } else { - wrong_exception_type(exc); - return NULL; + wrong_exception_type(exc); + return NULL; } /* ouch: passing NULL, 0, pos gives None instead of u'' */ return Py_BuildValue("(u#n)", &end, 0, end); @@ -519,155 +519,155 @@ Py_ssize_t i; if (PyObject_IsInstance(exc, PyExc_UnicodeEncodeError)) { - PyObject *res; - Py_UNICODE *p; - if (PyUnicodeEncodeError_GetStart(exc, &start)) - return NULL; - if (PyUnicodeEncodeError_GetEnd(exc, &end)) - return NULL; - res = PyUnicode_FromUnicode(NULL, end-start); - if (res == NULL) - return NULL; - for (p = PyUnicode_AS_UNICODE(res), i = start; - i0) { - *outp++ = '0' + c/base; - c %= base; - base /= 10; - } - *outp++ = ';'; - } - restuple = Py_BuildValue("(On)", res, end); - Py_DECREF(res); - Py_DECREF(object); - return restuple; + while (digits-->0) { + *outp++ = '0' + c/base; + c %= base; + base /= 10; + } + *outp++ = ';'; + } + restuple = Py_BuildValue("(On)", res, end); + Py_DECREF(res); + Py_DECREF(object); + return restuple; } else { - wrong_exception_type(exc); - return NULL; + wrong_exception_type(exc); + return NULL; } } @@ -679,72 +679,72 @@ PyObject *PyCodec_BackslashReplaceErrors(PyObject *exc) { if (PyObject_IsInstance(exc, PyExc_UnicodeEncodeError)) { - PyObject *restuple; - PyObject *object; - Py_ssize_t start; - Py_ssize_t end; - PyObject *res; - Py_UNICODE *p; - Py_UNICODE *startp; - Py_UNICODE *outp; - int ressize; - if (PyUnicodeEncodeError_GetStart(exc, &start)) - return NULL; - if (PyUnicodeEncodeError_GetEnd(exc, &end)) - return NULL; - if (!(object = PyUnicodeEncodeError_GetObject(exc))) - return NULL; - startp = PyUnicode_AS_UNICODE(object); - for (p = startp+start, ressize = 0; p < startp+end; ++p) { + PyObject *restuple; + PyObject *object; + Py_ssize_t start; + Py_ssize_t end; + PyObject *res; + Py_UNICODE *p; + Py_UNICODE *startp; + Py_UNICODE *outp; + int ressize; + if (PyUnicodeEncodeError_GetStart(exc, &start)) + return NULL; + if (PyUnicodeEncodeError_GetEnd(exc, &end)) + return NULL; + if (!(object = PyUnicodeEncodeError_GetObject(exc))) + return NULL; + startp = PyUnicode_AS_UNICODE(object); + for (p = startp+start, ressize = 0; p < startp+end; ++p) { #ifdef Py_UNICODE_WIDE - if (*p >= 0x00010000) - ressize += 1+1+8; - else + if (*p >= 0x00010000) + ressize += 1+1+8; + else #endif - if (*p >= 0x100) { - ressize += 1+1+4; - } - else - ressize += 1+1+2; - } - res = PyUnicode_FromUnicode(NULL, ressize); - if (res==NULL) - return NULL; - for (p = startp+start, outp = PyUnicode_AS_UNICODE(res); - p < startp+end; ++p) { - Py_UNICODE c = *p; - *outp++ = '\\'; + if (*p >= 0x100) { + ressize += 1+1+4; + } + else + ressize += 1+1+2; + } + res = PyUnicode_FromUnicode(NULL, ressize); + if (res==NULL) + return NULL; + for (p = startp+start, outp = PyUnicode_AS_UNICODE(res); + p < startp+end; ++p) { + Py_UNICODE c = *p; + *outp++ = '\\'; #ifdef Py_UNICODE_WIDE - if (c >= 0x00010000) { - *outp++ = 'U'; - *outp++ = hexdigits[(c>>28)&0xf]; - *outp++ = hexdigits[(c>>24)&0xf]; - *outp++ = hexdigits[(c>>20)&0xf]; - *outp++ = hexdigits[(c>>16)&0xf]; - *outp++ = hexdigits[(c>>12)&0xf]; - *outp++ = hexdigits[(c>>8)&0xf]; - } - else + if (c >= 0x00010000) { + *outp++ = 'U'; + *outp++ = hexdigits[(c>>28)&0xf]; + *outp++ = hexdigits[(c>>24)&0xf]; + *outp++ = hexdigits[(c>>20)&0xf]; + *outp++ = hexdigits[(c>>16)&0xf]; + *outp++ = hexdigits[(c>>12)&0xf]; + *outp++ = hexdigits[(c>>8)&0xf]; + } + else #endif - if (c >= 0x100) { - *outp++ = 'u'; - *outp++ = hexdigits[(c>>12)&0xf]; - *outp++ = hexdigits[(c>>8)&0xf]; - } - else - *outp++ = 'x'; - *outp++ = hexdigits[(c>>4)&0xf]; - *outp++ = hexdigits[c&0xf]; - } - - restuple = Py_BuildValue("(On)", res, end); - Py_DECREF(res); - Py_DECREF(object); - return restuple; + if (c >= 0x100) { + *outp++ = 'u'; + *outp++ = hexdigits[(c>>12)&0xf]; + *outp++ = hexdigits[(c>>8)&0xf]; + } + else + *outp++ = 'x'; + *outp++ = hexdigits[(c>>4)&0xf]; + *outp++ = hexdigits[c&0xf]; + } + + restuple = Py_BuildValue("(On)", res, end); + Py_DECREF(res); + Py_DECREF(object); + return restuple; } else { - wrong_exception_type(exc); - return NULL; + wrong_exception_type(exc); + return NULL; } } @@ -759,73 +759,73 @@ Py_ssize_t end; PyObject *res; if (PyObject_IsInstance(exc, PyExc_UnicodeEncodeError)) { - Py_UNICODE *p; - Py_UNICODE *startp; - char *outp; - if (PyUnicodeEncodeError_GetStart(exc, &start)) - return NULL; - if (PyUnicodeEncodeError_GetEnd(exc, &end)) - return NULL; - if (!(object = PyUnicodeEncodeError_GetObject(exc))) - return NULL; - startp = PyUnicode_AS_UNICODE(object); - res = PyBytes_FromStringAndSize(NULL, 3*(end-start)); - if (!res) { - Py_DECREF(object); - return NULL; - } - outp = PyBytes_AsString(res); - for (p = startp+start; p < startp+end; p++) { - Py_UNICODE ch = *p; - if (ch < 0xd800 || ch > 0xdfff) { - /* Not a surrogate, fail with original exception */ - PyErr_SetObject(PyExceptionInstance_Class(exc), exc); - Py_DECREF(res); - Py_DECREF(object); - return NULL; - } - *outp++ = (char)(0xe0 | (ch >> 12)); - *outp++ = (char)(0x80 | ((ch >> 6) & 0x3f)); - *outp++ = (char)(0x80 | (ch & 0x3f)); - } - restuple = Py_BuildValue("(On)", res, end); - Py_DECREF(res); - Py_DECREF(object); - return restuple; + Py_UNICODE *p; + Py_UNICODE *startp; + char *outp; + if (PyUnicodeEncodeError_GetStart(exc, &start)) + return NULL; + if (PyUnicodeEncodeError_GetEnd(exc, &end)) + return NULL; + if (!(object = PyUnicodeEncodeError_GetObject(exc))) + return NULL; + startp = PyUnicode_AS_UNICODE(object); + res = PyBytes_FromStringAndSize(NULL, 3*(end-start)); + if (!res) { + Py_DECREF(object); + return NULL; + } + outp = PyBytes_AsString(res); + for (p = startp+start; p < startp+end; p++) { + Py_UNICODE ch = *p; + if (ch < 0xd800 || ch > 0xdfff) { + /* Not a surrogate, fail with original exception */ + PyErr_SetObject(PyExceptionInstance_Class(exc), exc); + Py_DECREF(res); + Py_DECREF(object); + return NULL; + } + *outp++ = (char)(0xe0 | (ch >> 12)); + *outp++ = (char)(0x80 | ((ch >> 6) & 0x3f)); + *outp++ = (char)(0x80 | (ch & 0x3f)); + } + restuple = Py_BuildValue("(On)", res, end); + Py_DECREF(res); + Py_DECREF(object); + return restuple; } else if (PyObject_IsInstance(exc, PyExc_UnicodeDecodeError)) { - unsigned char *p; - Py_UNICODE ch = 0; - if (PyUnicodeDecodeError_GetStart(exc, &start)) - return NULL; - if (!(object = PyUnicodeDecodeError_GetObject(exc))) - return NULL; - if (!(p = (unsigned char*)PyBytes_AsString(object))) { - Py_DECREF(object); - return NULL; - } - /* Try decoding a single surrogate character. If - there are more, let the codec call us again. */ - p += start; - if ((p[0] & 0xf0) == 0xe0 || - (p[1] & 0xc0) == 0x80 || - (p[2] & 0xc0) == 0x80) { - /* it's a three-byte code */ - ch = ((p[0] & 0x0f) << 12) + ((p[1] & 0x3f) << 6) + (p[2] & 0x3f); - if (ch < 0xd800 || ch > 0xdfff) - /* it's not a surrogate - fail */ - ch = 0; - } - Py_DECREF(object); - if (ch == 0) { - PyErr_SetObject(PyExceptionInstance_Class(exc), exc); - return NULL; - } - return Py_BuildValue("(u#n)", &ch, 1, start+3); + unsigned char *p; + Py_UNICODE ch = 0; + if (PyUnicodeDecodeError_GetStart(exc, &start)) + return NULL; + if (!(object = PyUnicodeDecodeError_GetObject(exc))) + return NULL; + if (!(p = (unsigned char*)PyBytes_AsString(object))) { + Py_DECREF(object); + return NULL; + } + /* Try decoding a single surrogate character. If + there are more, let the codec call us again. */ + p += start; + if ((p[0] & 0xf0) == 0xe0 || + (p[1] & 0xc0) == 0x80 || + (p[2] & 0xc0) == 0x80) { + /* it's a three-byte code */ + ch = ((p[0] & 0x0f) << 12) + ((p[1] & 0x3f) << 6) + (p[2] & 0x3f); + if (ch < 0xd800 || ch > 0xdfff) + /* it's not a surrogate - fail */ + ch = 0; + } + Py_DECREF(object); + if (ch == 0) { + PyErr_SetObject(PyExceptionInstance_Class(exc), exc); + return NULL; + } + return Py_BuildValue("(u#n)", &ch, 1, start+3); } else { - wrong_exception_type(exc); - return NULL; + wrong_exception_type(exc); + return NULL; } } @@ -838,74 +838,74 @@ Py_ssize_t end; PyObject *res; if (PyObject_IsInstance(exc, PyExc_UnicodeEncodeError)) { - Py_UNICODE *p; - Py_UNICODE *startp; - char *outp; - if (PyUnicodeEncodeError_GetStart(exc, &start)) - return NULL; - if (PyUnicodeEncodeError_GetEnd(exc, &end)) - return NULL; - if (!(object = PyUnicodeEncodeError_GetObject(exc))) - return NULL; - startp = PyUnicode_AS_UNICODE(object); - res = PyBytes_FromStringAndSize(NULL, end-start); - if (!res) { - Py_DECREF(object); - return NULL; - } - outp = PyBytes_AsString(res); - for (p = startp+start; p < startp+end; p++) { - Py_UNICODE ch = *p; - if (ch < 0xdc80 || ch > 0xdcff) { - /* Not a UTF-8b surrogate, fail with original exception */ - PyErr_SetObject(PyExceptionInstance_Class(exc), exc); - Py_DECREF(res); - Py_DECREF(object); - return NULL; - } - *outp++ = ch - 0xdc00; - } - restuple = Py_BuildValue("(On)", res, end); - Py_DECREF(res); - Py_DECREF(object); - return restuple; + Py_UNICODE *p; + Py_UNICODE *startp; + char *outp; + if (PyUnicodeEncodeError_GetStart(exc, &start)) + return NULL; + if (PyUnicodeEncodeError_GetEnd(exc, &end)) + return NULL; + if (!(object = PyUnicodeEncodeError_GetObject(exc))) + return NULL; + startp = PyUnicode_AS_UNICODE(object); + res = PyBytes_FromStringAndSize(NULL, end-start); + if (!res) { + Py_DECREF(object); + return NULL; + } + outp = PyBytes_AsString(res); + for (p = startp+start; p < startp+end; p++) { + Py_UNICODE ch = *p; + if (ch < 0xdc80 || ch > 0xdcff) { + /* Not a UTF-8b surrogate, fail with original exception */ + PyErr_SetObject(PyExceptionInstance_Class(exc), exc); + Py_DECREF(res); + Py_DECREF(object); + return NULL; + } + *outp++ = ch - 0xdc00; + } + restuple = Py_BuildValue("(On)", res, end); + Py_DECREF(res); + Py_DECREF(object); + return restuple; } else if (PyObject_IsInstance(exc, PyExc_UnicodeDecodeError)) { - unsigned char *p; - Py_UNICODE ch[4]; /* decode up to 4 bad bytes. */ - int consumed = 0; - if (PyUnicodeDecodeError_GetStart(exc, &start)) - return NULL; - if (PyUnicodeDecodeError_GetEnd(exc, &end)) - return NULL; - if (!(object = PyUnicodeDecodeError_GetObject(exc))) - return NULL; - if (!(p = (unsigned char*)PyBytes_AsString(object))) { - Py_DECREF(object); - return NULL; - } - while (consumed < 4 && consumed < end-start) { - /* Refuse to escape ASCII bytes. */ - if (p[start+consumed] < 128) - break; - ch[consumed] = 0xdc00 + p[start+consumed]; - consumed++; - } - Py_DECREF(object); - if (!consumed) { - /* codec complained about ASCII byte. */ - PyErr_SetObject(PyExceptionInstance_Class(exc), exc); - return NULL; - } - return Py_BuildValue("(u#n)", ch, consumed, start+consumed); + unsigned char *p; + Py_UNICODE ch[4]; /* decode up to 4 bad bytes. */ + int consumed = 0; + if (PyUnicodeDecodeError_GetStart(exc, &start)) + return NULL; + if (PyUnicodeDecodeError_GetEnd(exc, &end)) + return NULL; + if (!(object = PyUnicodeDecodeError_GetObject(exc))) + return NULL; + if (!(p = (unsigned char*)PyBytes_AsString(object))) { + Py_DECREF(object); + return NULL; + } + while (consumed < 4 && consumed < end-start) { + /* Refuse to escape ASCII bytes. */ + if (p[start+consumed] < 128) + break; + ch[consumed] = 0xdc00 + p[start+consumed]; + consumed++; + } + Py_DECREF(object); + if (!consumed) { + /* codec complained about ASCII byte. */ + PyErr_SetObject(PyExceptionInstance_Class(exc), exc); + return NULL; + } + return Py_BuildValue("(u#n)", ch, consumed, start+consumed); } else { - wrong_exception_type(exc); - return NULL; + wrong_exception_type(exc); + return NULL; } } - + static PyObject *strict_errors(PyObject *self, PyObject *exc) { return PyCodec_StrictErrors(exc); @@ -948,78 +948,78 @@ static int _PyCodecRegistry_Init(void) { static struct { - char *name; - PyMethodDef def; + char *name; + PyMethodDef def; } methods[] = { - { - "strict", - { - "strict_errors", - strict_errors, - METH_O, - PyDoc_STR("Implements the 'strict' error handling, which " - "raises a UnicodeError on coding errors.") - } - }, - { - "ignore", - { - "ignore_errors", - ignore_errors, - METH_O, - PyDoc_STR("Implements the 'ignore' error handling, which " - "ignores malformed data and continues.") - } - }, - { - "replace", - { - "replace_errors", - replace_errors, - METH_O, - PyDoc_STR("Implements the 'replace' error handling, which " - "replaces malformed data with a replacement marker.") - } - }, - { - "xmlcharrefreplace", - { - "xmlcharrefreplace_errors", - xmlcharrefreplace_errors, - METH_O, - PyDoc_STR("Implements the 'xmlcharrefreplace' error handling, " - "which replaces an unencodable character with the " - "appropriate XML character reference.") - } - }, - { - "backslashreplace", - { - "backslashreplace_errors", - backslashreplace_errors, - METH_O, - PyDoc_STR("Implements the 'backslashreplace' error handling, " - "which replaces an unencodable character with a " - "backslashed escape sequence.") - } - }, - { - "surrogatepass", - { - "surrogatepass", - surrogatepass_errors, - METH_O - } - }, - { - "surrogateescape", - { - "surrogateescape", - surrogateescape_errors, - METH_O - } - } + { + "strict", + { + "strict_errors", + strict_errors, + METH_O, + PyDoc_STR("Implements the 'strict' error handling, which " + "raises a UnicodeError on coding errors.") + } + }, + { + "ignore", + { + "ignore_errors", + ignore_errors, + METH_O, + PyDoc_STR("Implements the 'ignore' error handling, which " + "ignores malformed data and continues.") + } + }, + { + "replace", + { + "replace_errors", + replace_errors, + METH_O, + PyDoc_STR("Implements the 'replace' error handling, which " + "replaces malformed data with a replacement marker.") + } + }, + { + "xmlcharrefreplace", + { + "xmlcharrefreplace_errors", + xmlcharrefreplace_errors, + METH_O, + PyDoc_STR("Implements the 'xmlcharrefreplace' error handling, " + "which replaces an unencodable character with the " + "appropriate XML character reference.") + } + }, + { + "backslashreplace", + { + "backslashreplace_errors", + backslashreplace_errors, + METH_O, + PyDoc_STR("Implements the 'backslashreplace' error handling, " + "which replaces an unencodable character with a " + "backslashed escape sequence.") + } + }, + { + "surrogatepass", + { + "surrogatepass", + surrogatepass_errors, + METH_O + } + }, + { + "surrogateescape", + { + "surrogateescape", + surrogateescape_errors, + METH_O + } + } }; PyInterpreterState *interp = PyThreadState_GET()->interp; @@ -1027,42 +1027,42 @@ unsigned i; if (interp->codec_search_path != NULL) - return 0; + return 0; interp->codec_search_path = PyList_New(0); interp->codec_search_cache = PyDict_New(); interp->codec_error_registry = PyDict_New(); if (interp->codec_error_registry) { - for (i = 0; i < sizeof(methods)/sizeof(methods[0]); ++i) { - PyObject *func = PyCFunction_New(&methods[i].def, NULL); - int res; - if (!func) - Py_FatalError("can't initialize codec error registry"); - res = PyCodec_RegisterError(methods[i].name, func); - Py_DECREF(func); - if (res) - Py_FatalError("can't initialize codec error registry"); - } + for (i = 0; i < sizeof(methods)/sizeof(methods[0]); ++i) { + PyObject *func = PyCFunction_New(&methods[i].def, NULL); + int res; + if (!func) + Py_FatalError("can't initialize codec error registry"); + res = PyCodec_RegisterError(methods[i].name, func); + Py_DECREF(func); + if (res) + Py_FatalError("can't initialize codec error registry"); + } } if (interp->codec_search_path == NULL || - interp->codec_search_cache == NULL || - interp->codec_error_registry == NULL) - Py_FatalError("can't initialize codec registry"); + interp->codec_search_cache == NULL || + interp->codec_error_registry == NULL) + Py_FatalError("can't initialize codec registry"); mod = PyImport_ImportModuleNoBlock("encodings"); if (mod == NULL) { - if (PyErr_ExceptionMatches(PyExc_ImportError)) { - /* Ignore ImportErrors... this is done so that - distributions can disable the encodings package. Note - that other errors are not masked, e.g. SystemErrors - raised to inform the user of an error in the Python - configuration are still reported back to the user. */ - PyErr_Clear(); - return 0; - } - return -1; + if (PyErr_ExceptionMatches(PyExc_ImportError)) { + /* Ignore ImportErrors... this is done so that + distributions can disable the encodings package. Note + that other errors are not masked, e.g. SystemErrors + raised to inform the user of an error in the Python + configuration are still reported back to the user. */ + PyErr_Clear(); + return 0; + } + return -1; } Py_DECREF(mod); interp->codecs_initialized = 1; Modified: python/branches/release31-maint/Python/compile.c ============================================================================== --- python/branches/release31-maint/Python/compile.c (original) +++ python/branches/release31-maint/Python/compile.c Sun May 9 18:14:21 2010 @@ -5,10 +5,10 @@ * PyCodeObject. The compiler makes several passes to build the code * object: * 1. Checks for future statements. See future.c - * 2. Builds a symbol table. See symtable.c. + * 2. Builds a symbol table. See symtable.c. * 3. Generate code for basic blocks. See compiler_mod() in this file. * 4. Assemble the basic blocks into final code. See assemble() in - * this file. + * this file. * 5. Optimize the byte code (peephole optimizations). See peephole.c * * Note that compiler_mod() suggests module, but the module ast type @@ -45,37 +45,37 @@ #define COMP_DICTCOMP 3 struct instr { - unsigned i_jabs : 1; - unsigned i_jrel : 1; - unsigned i_hasarg : 1; - unsigned char i_opcode; - int i_oparg; - struct basicblock_ *i_target; /* target block (if jump instruction) */ - int i_lineno; + unsigned i_jabs : 1; + unsigned i_jrel : 1; + unsigned i_hasarg : 1; + unsigned char i_opcode; + int i_oparg; + struct basicblock_ *i_target; /* target block (if jump instruction) */ + int i_lineno; }; typedef struct basicblock_ { /* Each basicblock in a compilation unit is linked via b_list in the reverse order that the block are allocated. b_list points to the next block, not to be confused with b_next, which is next by control flow. */ - struct basicblock_ *b_list; - /* number of instructions used */ - int b_iused; - /* length of instruction array (b_instr) */ - int b_ialloc; - /* pointer to an array of instructions, initially NULL */ - struct instr *b_instr; - /* If b_next is non-NULL, it is a pointer to the next - block reached by normal control flow. */ - struct basicblock_ *b_next; - /* b_seen is used to perform a DFS of basicblocks. */ - unsigned b_seen : 1; - /* b_return is true if a RETURN_VALUE opcode is inserted. */ - unsigned b_return : 1; - /* depth of stack upon entry of block, computed by stackdepth() */ - int b_startdepth; - /* instruction offset for block, computed by assemble_jump_offsets() */ - int b_offset; + struct basicblock_ *b_list; + /* number of instructions used */ + int b_iused; + /* length of instruction array (b_instr) */ + int b_ialloc; + /* pointer to an array of instructions, initially NULL */ + struct instr *b_instr; + /* If b_next is non-NULL, it is a pointer to the next + block reached by normal control flow. */ + struct basicblock_ *b_next; + /* b_seen is used to perform a DFS of basicblocks. */ + unsigned b_seen : 1; + /* b_return is true if a RETURN_VALUE opcode is inserted. */ + unsigned b_return : 1; + /* depth of stack upon entry of block, computed by stackdepth() */ + int b_startdepth; + /* instruction offset for block, computed by assemble_jump_offsets() */ + int b_offset; } basicblock; /* fblockinfo tracks the current frame block. @@ -88,66 +88,66 @@ enum fblocktype { LOOP, EXCEPT, FINALLY_TRY, FINALLY_END }; struct fblockinfo { - enum fblocktype fb_type; - basicblock *fb_block; + enum fblocktype fb_type; + basicblock *fb_block; }; /* The following items change on entry and exit of code blocks. They must be saved and restored when returning to a block. */ struct compiler_unit { - PySTEntryObject *u_ste; + PySTEntryObject *u_ste; - PyObject *u_name; - /* The following fields are dicts that map objects to - the index of them in co_XXX. The index is used as - the argument for opcodes that refer to those collections. - */ - PyObject *u_consts; /* all constants */ - PyObject *u_names; /* all names */ - PyObject *u_varnames; /* local variables */ - PyObject *u_cellvars; /* cell variables */ - PyObject *u_freevars; /* free variables */ - - PyObject *u_private; /* for private name mangling */ - - int u_argcount; /* number of arguments for block */ - int u_kwonlyargcount; /* number of keyword only arguments for block */ - /* Pointer to the most recently allocated block. By following b_list - members, you can reach all early allocated blocks. */ - basicblock *u_blocks; - basicblock *u_curblock; /* pointer to current block */ - int u_tmpname; /* temporary variables for list comps */ - - int u_nfblocks; - struct fblockinfo u_fblock[CO_MAXBLOCKS]; - - int u_firstlineno; /* the first lineno of the block */ - int u_lineno; /* the lineno for the current stmt */ - int u_lineno_set; /* boolean to indicate whether instr - has been generated with current lineno */ + PyObject *u_name; + /* The following fields are dicts that map objects to + the index of them in co_XXX. The index is used as + the argument for opcodes that refer to those collections. + */ + PyObject *u_consts; /* all constants */ + PyObject *u_names; /* all names */ + PyObject *u_varnames; /* local variables */ + PyObject *u_cellvars; /* cell variables */ + PyObject *u_freevars; /* free variables */ + + PyObject *u_private; /* for private name mangling */ + + int u_argcount; /* number of arguments for block */ + int u_kwonlyargcount; /* number of keyword only arguments for block */ + /* Pointer to the most recently allocated block. By following b_list + members, you can reach all early allocated blocks. */ + basicblock *u_blocks; + basicblock *u_curblock; /* pointer to current block */ + int u_tmpname; /* temporary variables for list comps */ + + int u_nfblocks; + struct fblockinfo u_fblock[CO_MAXBLOCKS]; + + int u_firstlineno; /* the first lineno of the block */ + int u_lineno; /* the lineno for the current stmt */ + int u_lineno_set; /* boolean to indicate whether instr + has been generated with current lineno */ }; -/* This struct captures the global state of a compilation. +/* This struct captures the global state of a compilation. The u pointer points to the current compilation unit, while units -for enclosing blocks are stored in c_stack. The u and c_stack are +for enclosing blocks are stored in c_stack. The u and c_stack are managed by compiler_enter_scope() and compiler_exit_scope(). */ struct compiler { - const char *c_filename; - struct symtable *c_st; - PyFutureFeatures *c_future; /* pointer to module's __future__ */ - PyCompilerFlags *c_flags; - - int c_interactive; /* true if in interactive mode */ - int c_nestlevel; - - struct compiler_unit *u; /* compiler state for current block */ - PyObject *c_stack; /* Python list holding compiler_unit ptrs */ - char *c_encoding; /* source encoding (a borrowed reference) */ - PyArena *c_arena; /* pointer to memory allocation arena */ + const char *c_filename; + struct symtable *c_st; + PyFutureFeatures *c_future; /* pointer to module's __future__ */ + PyCompilerFlags *c_flags; + + int c_interactive; /* true if in interactive mode */ + int c_nestlevel; + + struct compiler_unit *u; /* compiler state for current block */ + PyObject *c_stack; /* Python list holding compiler_unit ptrs */ + char *c_encoding; /* source encoding (a borrowed reference) */ + PyArena *c_arena; /* pointer to memory allocation arena */ }; static int compiler_enter_scope(struct compiler *, identifier, void *, int); @@ -168,12 +168,12 @@ static int compiler_visit_expr(struct compiler *, expr_ty); static int compiler_augassign(struct compiler *, stmt_ty); static int compiler_visit_slice(struct compiler *, slice_ty, - expr_context_ty); + expr_context_ty); static int compiler_push_fblock(struct compiler *, enum fblocktype, - basicblock *); + basicblock *); static void compiler_pop_fblock(struct compiler *, enum fblocktype, - basicblock *); + basicblock *); /* Returns true if there is a loop on the fblock stack. */ static int compiler_in_loop(struct compiler *); @@ -182,10 +182,10 @@ static int compiler_with(struct compiler *, stmt_ty); static int compiler_call_helper(struct compiler *c, int n, - asdl_seq *args, - asdl_seq *keywords, - expr_ty starargs, - expr_ty kwargs); + asdl_seq *args, + asdl_seq *keywords, + expr_ty starargs, + expr_ty kwargs); static PyCodeObject *assemble(struct compiler *, int addNone); static PyObject *__doc__; @@ -195,175 +195,175 @@ PyObject * _Py_Mangle(PyObject *privateobj, PyObject *ident) { - /* Name mangling: __private becomes _classname__private. - This is independent from how the name is used. */ - const Py_UNICODE *p, *name = PyUnicode_AS_UNICODE(ident); - Py_UNICODE *buffer; - size_t nlen, plen; - if (privateobj == NULL || !PyUnicode_Check(privateobj) || - name == NULL || name[0] != '_' || name[1] != '_') { - Py_INCREF(ident); - return ident; - } - p = PyUnicode_AS_UNICODE(privateobj); - nlen = Py_UNICODE_strlen(name); - /* Don't mangle __id__ or names with dots. - - The only time a name with a dot can occur is when - we are compiling an import statement that has a - package name. - - TODO(jhylton): Decide whether we want to support - mangling of the module name, e.g. __M.X. - */ - if ((name[nlen-1] == '_' && name[nlen-2] == '_') - || Py_UNICODE_strchr(name, '.')) { - Py_INCREF(ident); - return ident; /* Don't mangle __whatever__ */ - } - /* Strip leading underscores from class name */ - while (*p == '_') - p++; - if (*p == 0) { - Py_INCREF(ident); - return ident; /* Don't mangle if class is just underscores */ - } - plen = Py_UNICODE_strlen(p); - - assert(1 <= PY_SSIZE_T_MAX - nlen); - assert(1 + nlen <= PY_SSIZE_T_MAX - plen); - - ident = PyUnicode_FromStringAndSize(NULL, 1 + nlen + plen); - if (!ident) - return 0; - /* ident = "_" + p[:plen] + name # i.e. 1+plen+nlen bytes */ - buffer = PyUnicode_AS_UNICODE(ident); - buffer[0] = '_'; - Py_UNICODE_strncpy(buffer+1, p, plen); - Py_UNICODE_strcpy(buffer+1+plen, name); - return ident; + /* Name mangling: __private becomes _classname__private. + This is independent from how the name is used. */ + const Py_UNICODE *p, *name = PyUnicode_AS_UNICODE(ident); + Py_UNICODE *buffer; + size_t nlen, plen; + if (privateobj == NULL || !PyUnicode_Check(privateobj) || + name == NULL || name[0] != '_' || name[1] != '_') { + Py_INCREF(ident); + return ident; + } + p = PyUnicode_AS_UNICODE(privateobj); + nlen = Py_UNICODE_strlen(name); + /* Don't mangle __id__ or names with dots. + + The only time a name with a dot can occur is when + we are compiling an import statement that has a + package name. + + TODO(jhylton): Decide whether we want to support + mangling of the module name, e.g. __M.X. + */ + if ((name[nlen-1] == '_' && name[nlen-2] == '_') + || Py_UNICODE_strchr(name, '.')) { + Py_INCREF(ident); + return ident; /* Don't mangle __whatever__ */ + } + /* Strip leading underscores from class name */ + while (*p == '_') + p++; + if (*p == 0) { + Py_INCREF(ident); + return ident; /* Don't mangle if class is just underscores */ + } + plen = Py_UNICODE_strlen(p); + + assert(1 <= PY_SSIZE_T_MAX - nlen); + assert(1 + nlen <= PY_SSIZE_T_MAX - plen); + + ident = PyUnicode_FromStringAndSize(NULL, 1 + nlen + plen); + if (!ident) + return 0; + /* ident = "_" + p[:plen] + name # i.e. 1+plen+nlen bytes */ + buffer = PyUnicode_AS_UNICODE(ident); + buffer[0] = '_'; + Py_UNICODE_strncpy(buffer+1, p, plen); + Py_UNICODE_strcpy(buffer+1+plen, name); + return ident; } static int compiler_init(struct compiler *c) { - memset(c, 0, sizeof(struct compiler)); + memset(c, 0, sizeof(struct compiler)); - c->c_stack = PyList_New(0); - if (!c->c_stack) - return 0; + c->c_stack = PyList_New(0); + if (!c->c_stack) + return 0; - return 1; + return 1; } PyCodeObject * PyAST_Compile(mod_ty mod, const char *filename, PyCompilerFlags *flags, - PyArena *arena) + PyArena *arena) { - struct compiler c; - PyCodeObject *co = NULL; - PyCompilerFlags local_flags; - int merged; - - if (!__doc__) { - __doc__ = PyUnicode_InternFromString("__doc__"); - if (!__doc__) - return NULL; - } - - if (!compiler_init(&c)) - return NULL; - c.c_filename = filename; - c.c_arena = arena; - c.c_future = PyFuture_FromAST(mod, filename); - if (c.c_future == NULL) - goto finally; - if (!flags) { - local_flags.cf_flags = 0; - flags = &local_flags; - } - merged = c.c_future->ff_features | flags->cf_flags; - c.c_future->ff_features = merged; - flags->cf_flags = merged; - c.c_flags = flags; - c.c_nestlevel = 0; - - c.c_st = PySymtable_Build(mod, filename, c.c_future); - if (c.c_st == NULL) { - if (!PyErr_Occurred()) - PyErr_SetString(PyExc_SystemError, "no symtable"); - goto finally; - } + struct compiler c; + PyCodeObject *co = NULL; + PyCompilerFlags local_flags; + int merged; + + if (!__doc__) { + __doc__ = PyUnicode_InternFromString("__doc__"); + if (!__doc__) + return NULL; + } + + if (!compiler_init(&c)) + return NULL; + c.c_filename = filename; + c.c_arena = arena; + c.c_future = PyFuture_FromAST(mod, filename); + if (c.c_future == NULL) + goto finally; + if (!flags) { + local_flags.cf_flags = 0; + flags = &local_flags; + } + merged = c.c_future->ff_features | flags->cf_flags; + c.c_future->ff_features = merged; + flags->cf_flags = merged; + c.c_flags = flags; + c.c_nestlevel = 0; + + c.c_st = PySymtable_Build(mod, filename, c.c_future); + if (c.c_st == NULL) { + if (!PyErr_Occurred()) + PyErr_SetString(PyExc_SystemError, "no symtable"); + goto finally; + } - /* XXX initialize to NULL for now, need to handle */ - c.c_encoding = NULL; + /* XXX initialize to NULL for now, need to handle */ + c.c_encoding = NULL; - co = compiler_mod(&c, mod); + co = compiler_mod(&c, mod); finally: - compiler_free(&c); - assert(co || PyErr_Occurred()); - return co; + compiler_free(&c); + assert(co || PyErr_Occurred()); + return co; } PyCodeObject * PyNode_Compile(struct _node *n, const char *filename) { - PyCodeObject *co = NULL; - mod_ty mod; - PyArena *arena = PyArena_New(); - if (!arena) - return NULL; - mod = PyAST_FromNode(n, NULL, filename, arena); - if (mod) - co = PyAST_Compile(mod, filename, NULL, arena); - PyArena_Free(arena); - return co; + PyCodeObject *co = NULL; + mod_ty mod; + PyArena *arena = PyArena_New(); + if (!arena) + return NULL; + mod = PyAST_FromNode(n, NULL, filename, arena); + if (mod) + co = PyAST_Compile(mod, filename, NULL, arena); + PyArena_Free(arena); + return co; } static void compiler_free(struct compiler *c) { - if (c->c_st) - PySymtable_Free(c->c_st); - if (c->c_future) - PyObject_Free(c->c_future); - Py_DECREF(c->c_stack); + if (c->c_st) + PySymtable_Free(c->c_st); + if (c->c_future) + PyObject_Free(c->c_future); + Py_DECREF(c->c_stack); } static PyObject * list2dict(PyObject *list) { - Py_ssize_t i, n; - PyObject *v, *k; - PyObject *dict = PyDict_New(); - if (!dict) return NULL; - - n = PyList_Size(list); - for (i = 0; i < n; i++) { - v = PyLong_FromLong(i); - if (!v) { - Py_DECREF(dict); - return NULL; - } - k = PyList_GET_ITEM(list, i); - k = PyTuple_Pack(2, k, k->ob_type); - if (k == NULL || PyDict_SetItem(dict, k, v) < 0) { - Py_XDECREF(k); - Py_DECREF(v); - Py_DECREF(dict); - return NULL; - } - Py_DECREF(k); - Py_DECREF(v); - } - return dict; + Py_ssize_t i, n; + PyObject *v, *k; + PyObject *dict = PyDict_New(); + if (!dict) return NULL; + + n = PyList_Size(list); + for (i = 0; i < n; i++) { + v = PyLong_FromLong(i); + if (!v) { + Py_DECREF(dict); + return NULL; + } + k = PyList_GET_ITEM(list, i); + k = PyTuple_Pack(2, k, k->ob_type); + if (k == NULL || PyDict_SetItem(dict, k, v) < 0) { + Py_XDECREF(k); + Py_DECREF(v); + Py_DECREF(dict); + return NULL; + } + Py_DECREF(k); + Py_DECREF(v); + } + return dict; } /* Return new dict containing names from src that match scope(s). src is a symbol table dictionary. If the scope of a name matches -either scope_type or flag is set, insert it into the new dict. The +either scope_type or flag is set, insert it into the new dict. The values are integers, starting at offset and increasing by one for each key. */ @@ -371,194 +371,194 @@ static PyObject * dictbytype(PyObject *src, int scope_type, int flag, int offset) { - Py_ssize_t pos = 0, i = offset, scope; - PyObject *k, *v, *dest = PyDict_New(); + Py_ssize_t pos = 0, i = offset, scope; + PyObject *k, *v, *dest = PyDict_New(); - assert(offset >= 0); - if (dest == NULL) - return NULL; - - while (PyDict_Next(src, &pos, &k, &v)) { - /* XXX this should probably be a macro in symtable.h */ - long vi; - assert(PyLong_Check(v)); - vi = PyLong_AS_LONG(v); - scope = (vi >> SCOPE_OFFSET) & SCOPE_MASK; - - if (scope == scope_type || vi & flag) { - PyObject *tuple, *item = PyLong_FromLong(i); - if (item == NULL) { - Py_DECREF(dest); - return NULL; - } - i++; - tuple = PyTuple_Pack(2, k, k->ob_type); - if (!tuple || PyDict_SetItem(dest, tuple, item) < 0) { - Py_DECREF(item); - Py_DECREF(dest); - Py_XDECREF(tuple); - return NULL; - } - Py_DECREF(item); - Py_DECREF(tuple); - } - } - return dest; + assert(offset >= 0); + if (dest == NULL) + return NULL; + + while (PyDict_Next(src, &pos, &k, &v)) { + /* XXX this should probably be a macro in symtable.h */ + long vi; + assert(PyLong_Check(v)); + vi = PyLong_AS_LONG(v); + scope = (vi >> SCOPE_OFFSET) & SCOPE_MASK; + + if (scope == scope_type || vi & flag) { + PyObject *tuple, *item = PyLong_FromLong(i); + if (item == NULL) { + Py_DECREF(dest); + return NULL; + } + i++; + tuple = PyTuple_Pack(2, k, k->ob_type); + if (!tuple || PyDict_SetItem(dest, tuple, item) < 0) { + Py_DECREF(item); + Py_DECREF(dest); + Py_XDECREF(tuple); + return NULL; + } + Py_DECREF(item); + Py_DECREF(tuple); + } + } + return dest; } static void compiler_unit_check(struct compiler_unit *u) { - basicblock *block; - for (block = u->u_blocks; block != NULL; block = block->b_list) { - assert((void *)block != (void *)0xcbcbcbcb); - assert((void *)block != (void *)0xfbfbfbfb); - assert((void *)block != (void *)0xdbdbdbdb); - if (block->b_instr != NULL) { - assert(block->b_ialloc > 0); - assert(block->b_iused > 0); - assert(block->b_ialloc >= block->b_iused); - } - else { - assert (block->b_iused == 0); - assert (block->b_ialloc == 0); - } - } + basicblock *block; + for (block = u->u_blocks; block != NULL; block = block->b_list) { + assert((void *)block != (void *)0xcbcbcbcb); + assert((void *)block != (void *)0xfbfbfbfb); + assert((void *)block != (void *)0xdbdbdbdb); + if (block->b_instr != NULL) { + assert(block->b_ialloc > 0); + assert(block->b_iused > 0); + assert(block->b_ialloc >= block->b_iused); + } + else { + assert (block->b_iused == 0); + assert (block->b_ialloc == 0); + } + } } static void compiler_unit_free(struct compiler_unit *u) { - basicblock *b, *next; + basicblock *b, *next; - compiler_unit_check(u); - b = u->u_blocks; - while (b != NULL) { - if (b->b_instr) - PyObject_Free((void *)b->b_instr); - next = b->b_list; - PyObject_Free((void *)b); - b = next; - } - Py_CLEAR(u->u_ste); - Py_CLEAR(u->u_name); - Py_CLEAR(u->u_consts); - Py_CLEAR(u->u_names); - Py_CLEAR(u->u_varnames); - Py_CLEAR(u->u_freevars); - Py_CLEAR(u->u_cellvars); - Py_CLEAR(u->u_private); - PyObject_Free(u); + compiler_unit_check(u); + b = u->u_blocks; + while (b != NULL) { + if (b->b_instr) + PyObject_Free((void *)b->b_instr); + next = b->b_list; + PyObject_Free((void *)b); + b = next; + } + Py_CLEAR(u->u_ste); + Py_CLEAR(u->u_name); + Py_CLEAR(u->u_consts); + Py_CLEAR(u->u_names); + Py_CLEAR(u->u_varnames); + Py_CLEAR(u->u_freevars); + Py_CLEAR(u->u_cellvars); + Py_CLEAR(u->u_private); + PyObject_Free(u); } static int compiler_enter_scope(struct compiler *c, identifier name, void *key, - int lineno) + int lineno) { - struct compiler_unit *u; + struct compiler_unit *u; - u = (struct compiler_unit *)PyObject_Malloc(sizeof( - struct compiler_unit)); - if (!u) { - PyErr_NoMemory(); - return 0; - } - memset(u, 0, sizeof(struct compiler_unit)); - u->u_argcount = 0; - u->u_kwonlyargcount = 0; - u->u_ste = PySymtable_Lookup(c->c_st, key); - if (!u->u_ste) { - compiler_unit_free(u); - return 0; - } - Py_INCREF(name); - u->u_name = name; - u->u_varnames = list2dict(u->u_ste->ste_varnames); - u->u_cellvars = dictbytype(u->u_ste->ste_symbols, CELL, 0, 0); - if (!u->u_varnames || !u->u_cellvars) { - compiler_unit_free(u); - return 0; - } - - u->u_freevars = dictbytype(u->u_ste->ste_symbols, FREE, DEF_FREE_CLASS, - PyDict_Size(u->u_cellvars)); - if (!u->u_freevars) { - compiler_unit_free(u); - return 0; - } - - u->u_blocks = NULL; - u->u_tmpname = 0; - u->u_nfblocks = 0; - u->u_firstlineno = lineno; - u->u_lineno = 0; - u->u_lineno_set = 0; - u->u_consts = PyDict_New(); - if (!u->u_consts) { - compiler_unit_free(u); - return 0; - } - u->u_names = PyDict_New(); - if (!u->u_names) { - compiler_unit_free(u); - return 0; - } - - u->u_private = NULL; - - /* Push the old compiler_unit on the stack. */ - if (c->u) { - PyObject *capsule = PyCapsule_New(c->u, COMPILER_CAPSULE_NAME_COMPILER_UNIT, NULL); - if (!capsule || PyList_Append(c->c_stack, capsule) < 0) { - Py_XDECREF(capsule); - compiler_unit_free(u); - return 0; - } - Py_DECREF(capsule); - u->u_private = c->u->u_private; - Py_XINCREF(u->u_private); - } - c->u = u; - - c->c_nestlevel++; - if (compiler_use_new_block(c) == NULL) - return 0; + u = (struct compiler_unit *)PyObject_Malloc(sizeof( + struct compiler_unit)); + if (!u) { + PyErr_NoMemory(); + return 0; + } + memset(u, 0, sizeof(struct compiler_unit)); + u->u_argcount = 0; + u->u_kwonlyargcount = 0; + u->u_ste = PySymtable_Lookup(c->c_st, key); + if (!u->u_ste) { + compiler_unit_free(u); + return 0; + } + Py_INCREF(name); + u->u_name = name; + u->u_varnames = list2dict(u->u_ste->ste_varnames); + u->u_cellvars = dictbytype(u->u_ste->ste_symbols, CELL, 0, 0); + if (!u->u_varnames || !u->u_cellvars) { + compiler_unit_free(u); + return 0; + } + + u->u_freevars = dictbytype(u->u_ste->ste_symbols, FREE, DEF_FREE_CLASS, + PyDict_Size(u->u_cellvars)); + if (!u->u_freevars) { + compiler_unit_free(u); + return 0; + } + + u->u_blocks = NULL; + u->u_tmpname = 0; + u->u_nfblocks = 0; + u->u_firstlineno = lineno; + u->u_lineno = 0; + u->u_lineno_set = 0; + u->u_consts = PyDict_New(); + if (!u->u_consts) { + compiler_unit_free(u); + return 0; + } + u->u_names = PyDict_New(); + if (!u->u_names) { + compiler_unit_free(u); + return 0; + } + + u->u_private = NULL; + + /* Push the old compiler_unit on the stack. */ + if (c->u) { + PyObject *capsule = PyCapsule_New(c->u, COMPILER_CAPSULE_NAME_COMPILER_UNIT, NULL); + if (!capsule || PyList_Append(c->c_stack, capsule) < 0) { + Py_XDECREF(capsule); + compiler_unit_free(u); + return 0; + } + Py_DECREF(capsule); + u->u_private = c->u->u_private; + Py_XINCREF(u->u_private); + } + c->u = u; + + c->c_nestlevel++; + if (compiler_use_new_block(c) == NULL) + return 0; - return 1; + return 1; } static void compiler_exit_scope(struct compiler *c) { - int n; - PyObject *capsule; + int n; + PyObject *capsule; - c->c_nestlevel--; - compiler_unit_free(c->u); - /* Restore c->u to the parent unit. */ - n = PyList_GET_SIZE(c->c_stack) - 1; - if (n >= 0) { - capsule = PyList_GET_ITEM(c->c_stack, n); - c->u = (struct compiler_unit *)PyCapsule_GetPointer(capsule, COMPILER_CAPSULE_NAME_COMPILER_UNIT); - assert(c->u); - /* we are deleting from a list so this really shouldn't fail */ - if (PySequence_DelItem(c->c_stack, n) < 0) - Py_FatalError("compiler_exit_scope()"); - compiler_unit_check(c->u); - } - else - c->u = NULL; + c->c_nestlevel--; + compiler_unit_free(c->u); + /* Restore c->u to the parent unit. */ + n = PyList_GET_SIZE(c->c_stack) - 1; + if (n >= 0) { + capsule = PyList_GET_ITEM(c->c_stack, n); + c->u = (struct compiler_unit *)PyCapsule_GetPointer(capsule, COMPILER_CAPSULE_NAME_COMPILER_UNIT); + assert(c->u); + /* we are deleting from a list so this really shouldn't fail */ + if (PySequence_DelItem(c->c_stack, n) < 0) + Py_FatalError("compiler_exit_scope()"); + compiler_unit_check(c->u); + } + else + c->u = NULL; } -/* Allocate a new "anonymous" local variable. Used by with statements. */ - -static PyObject * -compiler_new_tmpname(struct compiler *c) -{ - char tmpname[256]; - PyOS_snprintf(tmpname, sizeof(tmpname), "_[%d]", ++c->u->u_tmpname); - return PyUnicode_FromString(tmpname); +/* Allocate a new "anonymous" local variable. Used by with statements. */ + +static PyObject * +compiler_new_tmpname(struct compiler *c) +{ + char tmpname[256]; + PyOS_snprintf(tmpname, sizeof(tmpname), "_[%d]", ++c->u->u_tmpname); + return PyUnicode_FromString(tmpname); } /* Allocate a new block and return a pointer to it. @@ -568,50 +568,50 @@ static basicblock * compiler_new_block(struct compiler *c) { - basicblock *b; - struct compiler_unit *u; + basicblock *b; + struct compiler_unit *u; - u = c->u; - b = (basicblock *)PyObject_Malloc(sizeof(basicblock)); - if (b == NULL) { - PyErr_NoMemory(); - return NULL; - } - memset((void *)b, 0, sizeof(basicblock)); - /* Extend the singly linked list of blocks with new block. */ - b->b_list = u->u_blocks; - u->u_blocks = b; - return b; + u = c->u; + b = (basicblock *)PyObject_Malloc(sizeof(basicblock)); + if (b == NULL) { + PyErr_NoMemory(); + return NULL; + } + memset((void *)b, 0, sizeof(basicblock)); + /* Extend the singly linked list of blocks with new block. */ + b->b_list = u->u_blocks; + u->u_blocks = b; + return b; } static basicblock * compiler_use_new_block(struct compiler *c) { - basicblock *block = compiler_new_block(c); - if (block == NULL) - return NULL; - c->u->u_curblock = block; - return block; + basicblock *block = compiler_new_block(c); + if (block == NULL) + return NULL; + c->u->u_curblock = block; + return block; } static basicblock * compiler_next_block(struct compiler *c) { - basicblock *block = compiler_new_block(c); - if (block == NULL) - return NULL; - c->u->u_curblock->b_next = block; - c->u->u_curblock = block; - return block; + basicblock *block = compiler_new_block(c); + if (block == NULL) + return NULL; + c->u->u_curblock->b_next = block; + c->u->u_curblock = block; + return block; } static basicblock * compiler_use_next_block(struct compiler *c, basicblock *block) { - assert(block != NULL); - c->u->u_curblock->b_next = block; - c->u->u_curblock = block; - return block; + assert(block != NULL); + c->u->u_curblock->b_next = block; + c->u->u_curblock = block; + return block; } /* Returns the offset of the next instruction in the current block's @@ -622,44 +622,44 @@ static int compiler_next_instr(struct compiler *c, basicblock *b) { - assert(b != NULL); - if (b->b_instr == NULL) { - b->b_instr = (struct instr *)PyObject_Malloc( - sizeof(struct instr) * DEFAULT_BLOCK_SIZE); - if (b->b_instr == NULL) { - PyErr_NoMemory(); - return -1; - } - b->b_ialloc = DEFAULT_BLOCK_SIZE; - memset((char *)b->b_instr, 0, - sizeof(struct instr) * DEFAULT_BLOCK_SIZE); - } - else if (b->b_iused == b->b_ialloc) { - struct instr *tmp; - size_t oldsize, newsize; - oldsize = b->b_ialloc * sizeof(struct instr); - newsize = oldsize << 1; - - if (oldsize > (PY_SIZE_MAX >> 1)) { - PyErr_NoMemory(); - return -1; - } - - if (newsize == 0) { - PyErr_NoMemory(); - return -1; - } - b->b_ialloc <<= 1; - tmp = (struct instr *)PyObject_Realloc( - (void *)b->b_instr, newsize); - if (tmp == NULL) { - PyErr_NoMemory(); - return -1; - } - b->b_instr = tmp; - memset((char *)b->b_instr + oldsize, 0, newsize - oldsize); - } - return b->b_iused++; + assert(b != NULL); + if (b->b_instr == NULL) { + b->b_instr = (struct instr *)PyObject_Malloc( + sizeof(struct instr) * DEFAULT_BLOCK_SIZE); + if (b->b_instr == NULL) { + PyErr_NoMemory(); + return -1; + } + b->b_ialloc = DEFAULT_BLOCK_SIZE; + memset((char *)b->b_instr, 0, + sizeof(struct instr) * DEFAULT_BLOCK_SIZE); + } + else if (b->b_iused == b->b_ialloc) { + struct instr *tmp; + size_t oldsize, newsize; + oldsize = b->b_ialloc * sizeof(struct instr); + newsize = oldsize << 1; + + if (oldsize > (PY_SIZE_MAX >> 1)) { + PyErr_NoMemory(); + return -1; + } + + if (newsize == 0) { + PyErr_NoMemory(); + return -1; + } + b->b_ialloc <<= 1; + tmp = (struct instr *)PyObject_Realloc( + (void *)b->b_instr, newsize); + if (tmp == NULL) { + PyErr_NoMemory(); + return -1; + } + b->b_instr = tmp; + memset((char *)b->b_instr + oldsize, 0, newsize - oldsize); + } + return b->b_iused++; } /* Set the i_lineno member of the instruction at offset off if the @@ -677,208 +677,208 @@ static void compiler_set_lineno(struct compiler *c, int off) { - basicblock *b; - if (c->u->u_lineno_set) - return; - c->u->u_lineno_set = 1; - b = c->u->u_curblock; - b->b_instr[off].i_lineno = c->u->u_lineno; + basicblock *b; + if (c->u->u_lineno_set) + return; + c->u->u_lineno_set = 1; + b = c->u->u_curblock; + b->b_instr[off].i_lineno = c->u->u_lineno; } static int opcode_stack_effect(int opcode, int oparg) { - switch (opcode) { - case POP_TOP: - return -1; - case ROT_TWO: - case ROT_THREE: - return 0; - case DUP_TOP: - return 1; - case ROT_FOUR: - return 0; - - case UNARY_POSITIVE: - case UNARY_NEGATIVE: - case UNARY_NOT: - case UNARY_INVERT: - return 0; - - case SET_ADD: - case LIST_APPEND: - return -1; - case MAP_ADD: - return -2; - - case BINARY_POWER: - case BINARY_MULTIPLY: - case BINARY_MODULO: - case BINARY_ADD: - case BINARY_SUBTRACT: - case BINARY_SUBSCR: - case BINARY_FLOOR_DIVIDE: - case BINARY_TRUE_DIVIDE: - return -1; - case INPLACE_FLOOR_DIVIDE: - case INPLACE_TRUE_DIVIDE: - return -1; - - case INPLACE_ADD: - case INPLACE_SUBTRACT: - case INPLACE_MULTIPLY: - case INPLACE_MODULO: - return -1; - case STORE_SUBSCR: - return -3; - case STORE_MAP: - return -2; - case DELETE_SUBSCR: - return -2; - - case BINARY_LSHIFT: - case BINARY_RSHIFT: - case BINARY_AND: - case BINARY_XOR: - case BINARY_OR: - return -1; - case INPLACE_POWER: - return -1; - case GET_ITER: - return 0; - - case PRINT_EXPR: - return -1; - case LOAD_BUILD_CLASS: - return 1; - case INPLACE_LSHIFT: - case INPLACE_RSHIFT: - case INPLACE_AND: - case INPLACE_XOR: - case INPLACE_OR: - return -1; - case BREAK_LOOP: - return 0; - case WITH_CLEANUP: - return -1; /* XXX Sometimes more */ - case STORE_LOCALS: - return -1; - case RETURN_VALUE: - return -1; - case IMPORT_STAR: - return -1; - case YIELD_VALUE: - return 0; - - case POP_BLOCK: - return 0; - case POP_EXCEPT: - return 0; /* -3 except if bad bytecode */ - case END_FINALLY: - return -1; /* or -2 or -3 if exception occurred */ - - case STORE_NAME: - return -1; - case DELETE_NAME: - return 0; - case UNPACK_SEQUENCE: - return oparg-1; - case UNPACK_EX: - return (oparg&0xFF) + (oparg>>8); - case FOR_ITER: - return 1; - - case STORE_ATTR: - return -2; - case DELETE_ATTR: - return -1; - case STORE_GLOBAL: - return -1; - case DELETE_GLOBAL: - return 0; - case DUP_TOPX: - return oparg; - case LOAD_CONST: - return 1; - case LOAD_NAME: - return 1; - case BUILD_TUPLE: - case BUILD_LIST: - case BUILD_SET: - return 1-oparg; - case BUILD_MAP: - return 1; - case LOAD_ATTR: - return 0; - case COMPARE_OP: - return -1; - case IMPORT_NAME: - return 0; - case IMPORT_FROM: - return 1; - - case JUMP_FORWARD: - case JUMP_IF_TRUE_OR_POP: /* -1 if jump not taken */ - case JUMP_IF_FALSE_OR_POP: /* "" */ - case JUMP_ABSOLUTE: - return 0; - - case POP_JUMP_IF_FALSE: - case POP_JUMP_IF_TRUE: - return -1; - - case LOAD_GLOBAL: - return 1; - - case CONTINUE_LOOP: - return 0; - case SETUP_LOOP: - return 0; - case SETUP_EXCEPT: - case SETUP_FINALLY: - return 6; /* can push 3 values for the new exception - + 3 others for the previous exception state */ - - case LOAD_FAST: - return 1; - case STORE_FAST: - return -1; - case DELETE_FAST: - return 0; + switch (opcode) { + case POP_TOP: + return -1; + case ROT_TWO: + case ROT_THREE: + return 0; + case DUP_TOP: + return 1; + case ROT_FOUR: + return 0; + + case UNARY_POSITIVE: + case UNARY_NEGATIVE: + case UNARY_NOT: + case UNARY_INVERT: + return 0; + + case SET_ADD: + case LIST_APPEND: + return -1; + case MAP_ADD: + return -2; + + case BINARY_POWER: + case BINARY_MULTIPLY: + case BINARY_MODULO: + case BINARY_ADD: + case BINARY_SUBTRACT: + case BINARY_SUBSCR: + case BINARY_FLOOR_DIVIDE: + case BINARY_TRUE_DIVIDE: + return -1; + case INPLACE_FLOOR_DIVIDE: + case INPLACE_TRUE_DIVIDE: + return -1; + + case INPLACE_ADD: + case INPLACE_SUBTRACT: + case INPLACE_MULTIPLY: + case INPLACE_MODULO: + return -1; + case STORE_SUBSCR: + return -3; + case STORE_MAP: + return -2; + case DELETE_SUBSCR: + return -2; + + case BINARY_LSHIFT: + case BINARY_RSHIFT: + case BINARY_AND: + case BINARY_XOR: + case BINARY_OR: + return -1; + case INPLACE_POWER: + return -1; + case GET_ITER: + return 0; + + case PRINT_EXPR: + return -1; + case LOAD_BUILD_CLASS: + return 1; + case INPLACE_LSHIFT: + case INPLACE_RSHIFT: + case INPLACE_AND: + case INPLACE_XOR: + case INPLACE_OR: + return -1; + case BREAK_LOOP: + return 0; + case WITH_CLEANUP: + return -1; /* XXX Sometimes more */ + case STORE_LOCALS: + return -1; + case RETURN_VALUE: + return -1; + case IMPORT_STAR: + return -1; + case YIELD_VALUE: + return 0; + + case POP_BLOCK: + return 0; + case POP_EXCEPT: + return 0; /* -3 except if bad bytecode */ + case END_FINALLY: + return -1; /* or -2 or -3 if exception occurred */ + + case STORE_NAME: + return -1; + case DELETE_NAME: + return 0; + case UNPACK_SEQUENCE: + return oparg-1; + case UNPACK_EX: + return (oparg&0xFF) + (oparg>>8); + case FOR_ITER: + return 1; + + case STORE_ATTR: + return -2; + case DELETE_ATTR: + return -1; + case STORE_GLOBAL: + return -1; + case DELETE_GLOBAL: + return 0; + case DUP_TOPX: + return oparg; + case LOAD_CONST: + return 1; + case LOAD_NAME: + return 1; + case BUILD_TUPLE: + case BUILD_LIST: + case BUILD_SET: + return 1-oparg; + case BUILD_MAP: + return 1; + case LOAD_ATTR: + return 0; + case COMPARE_OP: + return -1; + case IMPORT_NAME: + return 0; + case IMPORT_FROM: + return 1; + + case JUMP_FORWARD: + case JUMP_IF_TRUE_OR_POP: /* -1 if jump not taken */ + case JUMP_IF_FALSE_OR_POP: /* "" */ + case JUMP_ABSOLUTE: + return 0; + + case POP_JUMP_IF_FALSE: + case POP_JUMP_IF_TRUE: + return -1; + + case LOAD_GLOBAL: + return 1; + + case CONTINUE_LOOP: + return 0; + case SETUP_LOOP: + return 0; + case SETUP_EXCEPT: + case SETUP_FINALLY: + return 6; /* can push 3 values for the new exception + + 3 others for the previous exception state */ + + case LOAD_FAST: + return 1; + case STORE_FAST: + return -1; + case DELETE_FAST: + return 0; - case RAISE_VARARGS: - return -oparg; + case RAISE_VARARGS: + return -oparg; #define NARGS(o) (((o) % 256) + 2*(((o) / 256) % 256)) - case CALL_FUNCTION: - return -NARGS(oparg); - case CALL_FUNCTION_VAR: - case CALL_FUNCTION_KW: - return -NARGS(oparg)-1; - case CALL_FUNCTION_VAR_KW: - return -NARGS(oparg)-2; - case MAKE_FUNCTION: - return -NARGS(oparg) - ((oparg >> 16) & 0xffff); - case MAKE_CLOSURE: - return -1 - NARGS(oparg) - ((oparg >> 16) & 0xffff); + case CALL_FUNCTION: + return -NARGS(oparg); + case CALL_FUNCTION_VAR: + case CALL_FUNCTION_KW: + return -NARGS(oparg)-1; + case CALL_FUNCTION_VAR_KW: + return -NARGS(oparg)-2; + case MAKE_FUNCTION: + return -NARGS(oparg) - ((oparg >> 16) & 0xffff); + case MAKE_CLOSURE: + return -1 - NARGS(oparg) - ((oparg >> 16) & 0xffff); #undef NARGS - case BUILD_SLICE: - if (oparg == 3) - return -2; - else - return -1; - - case LOAD_CLOSURE: - return 1; - case LOAD_DEREF: - return 1; - case STORE_DEREF: - return -1; - default: - fprintf(stderr, "opcode = %d\n", opcode); - Py_FatalError("opcode_stack_effect()"); + case BUILD_SLICE: + if (oparg == 3) + return -2; + else + return -1; + + case LOAD_CLOSURE: + return 1; + case LOAD_DEREF: + return 1; + case STORE_DEREF: + return -1; + default: + fprintf(stderr, "opcode = %d\n", opcode); + Py_FatalError("opcode_stack_effect()"); - } - return 0; /* not reachable */ + } + return 0; /* not reachable */ } /* Add an opcode with no argument. @@ -888,118 +888,118 @@ static int compiler_addop(struct compiler *c, int opcode) { - basicblock *b; - struct instr *i; - int off; - off = compiler_next_instr(c, c->u->u_curblock); - if (off < 0) - return 0; - b = c->u->u_curblock; - i = &b->b_instr[off]; - i->i_opcode = opcode; - i->i_hasarg = 0; - if (opcode == RETURN_VALUE) - b->b_return = 1; - compiler_set_lineno(c, off); - return 1; + basicblock *b; + struct instr *i; + int off; + off = compiler_next_instr(c, c->u->u_curblock); + if (off < 0) + return 0; + b = c->u->u_curblock; + i = &b->b_instr[off]; + i->i_opcode = opcode; + i->i_hasarg = 0; + if (opcode == RETURN_VALUE) + b->b_return = 1; + compiler_set_lineno(c, off); + return 1; } static int compiler_add_o(struct compiler *c, PyObject *dict, PyObject *o) { - PyObject *t, *v; - Py_ssize_t arg; - double d; - - /* necessary to make sure types aren't coerced (e.g., int and long) */ - /* _and_ to distinguish 0.0 from -0.0 e.g. on IEEE platforms */ - if (PyFloat_Check(o)) { - d = PyFloat_AS_DOUBLE(o); - /* all we need is to make the tuple different in either the 0.0 - * or -0.0 case from all others, just to avoid the "coercion". - */ - if (d == 0.0 && copysign(1.0, d) < 0.0) - t = PyTuple_Pack(3, o, o->ob_type, Py_None); - else - t = PyTuple_Pack(2, o, o->ob_type); - } + PyObject *t, *v; + Py_ssize_t arg; + double d; + + /* necessary to make sure types aren't coerced (e.g., int and long) */ + /* _and_ to distinguish 0.0 from -0.0 e.g. on IEEE platforms */ + if (PyFloat_Check(o)) { + d = PyFloat_AS_DOUBLE(o); + /* all we need is to make the tuple different in either the 0.0 + * or -0.0 case from all others, just to avoid the "coercion". + */ + if (d == 0.0 && copysign(1.0, d) < 0.0) + t = PyTuple_Pack(3, o, o->ob_type, Py_None); + else + t = PyTuple_Pack(2, o, o->ob_type); + } #ifndef WITHOUT_COMPLEX - else if (PyComplex_Check(o)) { - Py_complex z; - int real_negzero, imag_negzero; - /* For the complex case we must make complex(x, 0.) - different from complex(x, -0.) and complex(0., y) - different from complex(-0., y), for any x and y. - All four complex zeros must be distinguished.*/ - z = PyComplex_AsCComplex(o); - real_negzero = z.real == 0.0 && copysign(1.0, z.real) < 0.0; - imag_negzero = z.imag == 0.0 && copysign(1.0, z.imag) < 0.0; - if (real_negzero && imag_negzero) { - t = PyTuple_Pack(5, o, o->ob_type, - Py_None, Py_None, Py_None); - } - else if (imag_negzero) { - t = PyTuple_Pack(4, o, o->ob_type, Py_None, Py_None); - } - else if (real_negzero) { - t = PyTuple_Pack(3, o, o->ob_type, Py_None); - } - else { - t = PyTuple_Pack(2, o, o->ob_type); - } + else if (PyComplex_Check(o)) { + Py_complex z; + int real_negzero, imag_negzero; + /* For the complex case we must make complex(x, 0.) + different from complex(x, -0.) and complex(0., y) + different from complex(-0., y), for any x and y. + All four complex zeros must be distinguished.*/ + z = PyComplex_AsCComplex(o); + real_negzero = z.real == 0.0 && copysign(1.0, z.real) < 0.0; + imag_negzero = z.imag == 0.0 && copysign(1.0, z.imag) < 0.0; + if (real_negzero && imag_negzero) { + t = PyTuple_Pack(5, o, o->ob_type, + Py_None, Py_None, Py_None); } -#endif /* WITHOUT_COMPLEX */ - else { - t = PyTuple_Pack(2, o, o->ob_type); + else if (imag_negzero) { + t = PyTuple_Pack(4, o, o->ob_type, Py_None, Py_None); } - if (t == NULL) - return -1; + else if (real_negzero) { + t = PyTuple_Pack(3, o, o->ob_type, Py_None); + } + else { + t = PyTuple_Pack(2, o, o->ob_type); + } + } +#endif /* WITHOUT_COMPLEX */ + else { + t = PyTuple_Pack(2, o, o->ob_type); + } + if (t == NULL) + return -1; - v = PyDict_GetItem(dict, t); - if (!v) { - if (PyErr_Occurred()) - return -1; - arg = PyDict_Size(dict); - v = PyLong_FromLong(arg); - if (!v) { - Py_DECREF(t); - return -1; - } - if (PyDict_SetItem(dict, t, v) < 0) { - Py_DECREF(t); - Py_DECREF(v); - return -1; - } - Py_DECREF(v); - } - else - arg = PyLong_AsLong(v); - Py_DECREF(t); - return arg; + v = PyDict_GetItem(dict, t); + if (!v) { + if (PyErr_Occurred()) + return -1; + arg = PyDict_Size(dict); + v = PyLong_FromLong(arg); + if (!v) { + Py_DECREF(t); + return -1; + } + if (PyDict_SetItem(dict, t, v) < 0) { + Py_DECREF(t); + Py_DECREF(v); + return -1; + } + Py_DECREF(v); + } + else + arg = PyLong_AsLong(v); + Py_DECREF(t); + return arg; } static int compiler_addop_o(struct compiler *c, int opcode, PyObject *dict, - PyObject *o) + PyObject *o) { int arg = compiler_add_o(c, dict, o); if (arg < 0) - return 0; + return 0; return compiler_addop_i(c, opcode, arg); } static int compiler_addop_name(struct compiler *c, int opcode, PyObject *dict, - PyObject *o) + PyObject *o) { int arg; PyObject *mangled = _Py_Mangle(c->u->u_private, o); if (!mangled) - return 0; + return 0; arg = compiler_add_o(c, dict, mangled); Py_DECREF(mangled); if (arg < 0) - return 0; + return 0; return compiler_addop_i(c, opcode, arg); } @@ -1010,43 +1010,43 @@ static int compiler_addop_i(struct compiler *c, int opcode, int oparg) { - struct instr *i; - int off; - off = compiler_next_instr(c, c->u->u_curblock); - if (off < 0) - return 0; - i = &c->u->u_curblock->b_instr[off]; - i->i_opcode = opcode; - i->i_oparg = oparg; - i->i_hasarg = 1; - compiler_set_lineno(c, off); - return 1; + struct instr *i; + int off; + off = compiler_next_instr(c, c->u->u_curblock); + if (off < 0) + return 0; + i = &c->u->u_curblock->b_instr[off]; + i->i_opcode = opcode; + i->i_oparg = oparg; + i->i_hasarg = 1; + compiler_set_lineno(c, off); + return 1; } static int compiler_addop_j(struct compiler *c, int opcode, basicblock *b, int absolute) { - struct instr *i; - int off; + struct instr *i; + int off; - assert(b != NULL); - off = compiler_next_instr(c, c->u->u_curblock); - if (off < 0) - return 0; - i = &c->u->u_curblock->b_instr[off]; - i->i_opcode = opcode; - i->i_target = b; - i->i_hasarg = 1; - if (absolute) - i->i_jabs = 1; - else - i->i_jrel = 1; - compiler_set_lineno(c, off); - return 1; + assert(b != NULL); + off = compiler_next_instr(c, c->u->u_curblock); + if (off < 0) + return 0; + i = &c->u->u_curblock->b_instr[off]; + i->i_opcode = opcode; + i->i_target = b; + i->i_hasarg = 1; + if (absolute) + i->i_jabs = 1; + else + i->i_jrel = 1; + compiler_set_lineno(c, off); + return 1; } -/* The distinction between NEW_BLOCK and NEXT_BLOCK is subtle. (I'd - like to find better names.) NEW_BLOCK() creates a new block and sets +/* The distinction between NEW_BLOCK and NEXT_BLOCK is subtle. (I'd + like to find better names.) NEW_BLOCK() creates a new block and sets it as the current block. NEXT_BLOCK() also creates an implicit jump from the current block to the new block. */ @@ -1057,50 +1057,50 @@ #define NEW_BLOCK(C) { \ - if (compiler_use_new_block((C)) == NULL) \ - return 0; \ + if (compiler_use_new_block((C)) == NULL) \ + return 0; \ } #define NEXT_BLOCK(C) { \ - if (compiler_next_block((C)) == NULL) \ - return 0; \ + if (compiler_next_block((C)) == NULL) \ + return 0; \ } #define ADDOP(C, OP) { \ - if (!compiler_addop((C), (OP))) \ - return 0; \ + if (!compiler_addop((C), (OP))) \ + return 0; \ } #define ADDOP_IN_SCOPE(C, OP) { \ - if (!compiler_addop((C), (OP))) { \ - compiler_exit_scope(c); \ - return 0; \ - } \ + if (!compiler_addop((C), (OP))) { \ + compiler_exit_scope(c); \ + return 0; \ + } \ } #define ADDOP_O(C, OP, O, TYPE) { \ - if (!compiler_addop_o((C), (OP), (C)->u->u_ ## TYPE, (O))) \ - return 0; \ + if (!compiler_addop_o((C), (OP), (C)->u->u_ ## TYPE, (O))) \ + return 0; \ } #define ADDOP_NAME(C, OP, O, TYPE) { \ - if (!compiler_addop_name((C), (OP), (C)->u->u_ ## TYPE, (O))) \ - return 0; \ + if (!compiler_addop_name((C), (OP), (C)->u->u_ ## TYPE, (O))) \ + return 0; \ } #define ADDOP_I(C, OP, O) { \ - if (!compiler_addop_i((C), (OP), (O))) \ - return 0; \ + if (!compiler_addop_i((C), (OP), (O))) \ + return 0; \ } #define ADDOP_JABS(C, OP, O) { \ - if (!compiler_addop_j((C), (OP), (O), 1)) \ - return 0; \ + if (!compiler_addop_j((C), (OP), (O), 1)) \ + return 0; \ } #define ADDOP_JREL(C, OP, O) { \ - if (!compiler_addop_j((C), (OP), (O), 0)) \ - return 0; \ + if (!compiler_addop_j((C), (OP), (O), 0)) \ + return 0; \ } /* VISIT and VISIT_SEQ takes an ASDL type as their second argument. They use @@ -1108,49 +1108,49 @@ */ #define VISIT(C, TYPE, V) {\ - if (!compiler_visit_ ## TYPE((C), (V))) \ - return 0; \ + if (!compiler_visit_ ## TYPE((C), (V))) \ + return 0; \ } #define VISIT_IN_SCOPE(C, TYPE, V) {\ - if (!compiler_visit_ ## TYPE((C), (V))) { \ - compiler_exit_scope(c); \ - return 0; \ - } \ + if (!compiler_visit_ ## TYPE((C), (V))) { \ + compiler_exit_scope(c); \ + return 0; \ + } \ } #define VISIT_SLICE(C, V, CTX) {\ - if (!compiler_visit_slice((C), (V), (CTX))) \ - return 0; \ + if (!compiler_visit_slice((C), (V), (CTX))) \ + return 0; \ } #define VISIT_SEQ(C, TYPE, SEQ) { \ - int _i; \ - asdl_seq *seq = (SEQ); /* avoid variable capture */ \ - for (_i = 0; _i < asdl_seq_LEN(seq); _i++) { \ - TYPE ## _ty elt = (TYPE ## _ty)asdl_seq_GET(seq, _i); \ - if (!compiler_visit_ ## TYPE((C), elt)) \ - return 0; \ - } \ + int _i; \ + asdl_seq *seq = (SEQ); /* avoid variable capture */ \ + for (_i = 0; _i < asdl_seq_LEN(seq); _i++) { \ + TYPE ## _ty elt = (TYPE ## _ty)asdl_seq_GET(seq, _i); \ + if (!compiler_visit_ ## TYPE((C), elt)) \ + return 0; \ + } \ } #define VISIT_SEQ_IN_SCOPE(C, TYPE, SEQ) { \ - int _i; \ - asdl_seq *seq = (SEQ); /* avoid variable capture */ \ - for (_i = 0; _i < asdl_seq_LEN(seq); _i++) { \ - TYPE ## _ty elt = (TYPE ## _ty)asdl_seq_GET(seq, _i); \ - if (!compiler_visit_ ## TYPE((C), elt)) { \ - compiler_exit_scope(c); \ - return 0; \ - } \ - } \ + int _i; \ + asdl_seq *seq = (SEQ); /* avoid variable capture */ \ + for (_i = 0; _i < asdl_seq_LEN(seq); _i++) { \ + TYPE ## _ty elt = (TYPE ## _ty)asdl_seq_GET(seq, _i); \ + if (!compiler_visit_ ## TYPE((C), elt)) { \ + compiler_exit_scope(c); \ + return 0; \ + } \ + } \ } static int compiler_isdocstring(stmt_ty s) { if (s->kind != Expr_kind) - return 0; + return 0; return s->v.Expr.value->kind == Str_kind; } @@ -1159,67 +1159,67 @@ static int compiler_body(struct compiler *c, asdl_seq *stmts) { - int i = 0; - stmt_ty st; + int i = 0; + stmt_ty st; - if (!asdl_seq_LEN(stmts)) - return 1; - st = (stmt_ty)asdl_seq_GET(stmts, 0); - if (compiler_isdocstring(st) && Py_OptimizeFlag < 2) { - /* don't generate docstrings if -OO */ - i = 1; - VISIT(c, expr, st->v.Expr.value); - if (!compiler_nameop(c, __doc__, Store)) - return 0; - } - for (; i < asdl_seq_LEN(stmts); i++) - VISIT(c, stmt, (stmt_ty)asdl_seq_GET(stmts, i)); - return 1; + if (!asdl_seq_LEN(stmts)) + return 1; + st = (stmt_ty)asdl_seq_GET(stmts, 0); + if (compiler_isdocstring(st) && Py_OptimizeFlag < 2) { + /* don't generate docstrings if -OO */ + i = 1; + VISIT(c, expr, st->v.Expr.value); + if (!compiler_nameop(c, __doc__, Store)) + return 0; + } + for (; i < asdl_seq_LEN(stmts); i++) + VISIT(c, stmt, (stmt_ty)asdl_seq_GET(stmts, i)); + return 1; } static PyCodeObject * compiler_mod(struct compiler *c, mod_ty mod) { - PyCodeObject *co; - int addNone = 1; - static PyObject *module; - if (!module) { - module = PyUnicode_InternFromString(""); - if (!module) - return NULL; - } - /* Use 0 for firstlineno initially, will fixup in assemble(). */ - if (!compiler_enter_scope(c, module, mod, 0)) - return NULL; - switch (mod->kind) { - case Module_kind: - if (!compiler_body(c, mod->v.Module.body)) { - compiler_exit_scope(c); - return 0; - } - break; - case Interactive_kind: - c->c_interactive = 1; - VISIT_SEQ_IN_SCOPE(c, stmt, - mod->v.Interactive.body); - break; - case Expression_kind: - VISIT_IN_SCOPE(c, expr, mod->v.Expression.body); - addNone = 0; - break; - case Suite_kind: - PyErr_SetString(PyExc_SystemError, - "suite should not be possible"); - return 0; - default: - PyErr_Format(PyExc_SystemError, - "module kind %d should not be possible", - mod->kind); - return 0; - } - co = assemble(c, addNone); - compiler_exit_scope(c); - return co; + PyCodeObject *co; + int addNone = 1; + static PyObject *module; + if (!module) { + module = PyUnicode_InternFromString(""); + if (!module) + return NULL; + } + /* Use 0 for firstlineno initially, will fixup in assemble(). */ + if (!compiler_enter_scope(c, module, mod, 0)) + return NULL; + switch (mod->kind) { + case Module_kind: + if (!compiler_body(c, mod->v.Module.body)) { + compiler_exit_scope(c); + return 0; + } + break; + case Interactive_kind: + c->c_interactive = 1; + VISIT_SEQ_IN_SCOPE(c, stmt, + mod->v.Interactive.body); + break; + case Expression_kind: + VISIT_IN_SCOPE(c, expr, mod->v.Expression.body); + addNone = 0; + break; + case Suite_kind: + PyErr_SetString(PyExc_SystemError, + "suite should not be possible"); + return 0; + default: + PyErr_Format(PyExc_SystemError, + "module kind %d should not be possible", + mod->kind); + return 0; + } + co = assemble(c, addNone); + compiler_exit_scope(c); + return co; } /* The test for LOCAL must come before the test for FREE in order to @@ -1230,24 +1230,24 @@ static int get_ref_type(struct compiler *c, PyObject *name) { - int scope = PyST_GetScope(c->u->u_ste, name); - if (scope == 0) { - char buf[350]; - PyOS_snprintf(buf, sizeof(buf), - "unknown scope for %.100s in %.100s(%s) in %s\n" - "symbols: %s\nlocals: %s\nglobals: %s", - PyBytes_AS_STRING(name), - PyBytes_AS_STRING(c->u->u_name), - PyObject_REPR(c->u->u_ste->ste_id), - c->c_filename, - PyObject_REPR(c->u->u_ste->ste_symbols), - PyObject_REPR(c->u->u_varnames), - PyObject_REPR(c->u->u_names) - ); - Py_FatalError(buf); - } + int scope = PyST_GetScope(c->u->u_ste, name); + if (scope == 0) { + char buf[350]; + PyOS_snprintf(buf, sizeof(buf), + "unknown scope for %.100s in %.100s(%s) in %s\n" + "symbols: %s\nlocals: %s\nglobals: %s", + PyBytes_AS_STRING(name), + PyBytes_AS_STRING(c->u->u_name), + PyObject_REPR(c->u->u_ste->ste_id), + c->c_filename, + PyObject_REPR(c->u->u_ste->ste_symbols), + PyObject_REPR(c->u->u_varnames), + PyObject_REPR(c->u->u_names) + ); + Py_FatalError(buf); + } - return scope; + return scope; } static int @@ -1256,637 +1256,637 @@ PyObject *k, *v; k = PyTuple_Pack(2, name, name->ob_type); if (k == NULL) - return -1; + return -1; v = PyDict_GetItem(dict, k); Py_DECREF(k); if (v == NULL) - return -1; + return -1; return PyLong_AS_LONG(v); } static int compiler_make_closure(struct compiler *c, PyCodeObject *co, int args) { - int i, free = PyCode_GetNumFree(co); - if (free == 0) { - ADDOP_O(c, LOAD_CONST, (PyObject*)co, consts); - ADDOP_I(c, MAKE_FUNCTION, args); - return 1; - } - for (i = 0; i < free; ++i) { - /* Bypass com_addop_varname because it will generate - LOAD_DEREF but LOAD_CLOSURE is needed. - */ - PyObject *name = PyTuple_GET_ITEM(co->co_freevars, i); - int arg, reftype; - - /* Special case: If a class contains a method with a - free variable that has the same name as a method, - the name will be considered free *and* local in the - class. It should be handled by the closure, as - well as by the normal name loookup logic. - */ - reftype = get_ref_type(c, name); - if (reftype == CELL) - arg = compiler_lookup_arg(c->u->u_cellvars, name); - else /* (reftype == FREE) */ - arg = compiler_lookup_arg(c->u->u_freevars, name); - if (arg == -1) { - fprintf(stderr, - "lookup %s in %s %d %d\n" - "freevars of %s: %s\n", - PyObject_REPR(name), - PyBytes_AS_STRING(c->u->u_name), - reftype, arg, - _PyUnicode_AsString(co->co_name), - PyObject_REPR(co->co_freevars)); - Py_FatalError("compiler_make_closure()"); - } - ADDOP_I(c, LOAD_CLOSURE, arg); - } - ADDOP_I(c, BUILD_TUPLE, free); - ADDOP_O(c, LOAD_CONST, (PyObject*)co, consts); - ADDOP_I(c, MAKE_CLOSURE, args); - return 1; + int i, free = PyCode_GetNumFree(co); + if (free == 0) { + ADDOP_O(c, LOAD_CONST, (PyObject*)co, consts); + ADDOP_I(c, MAKE_FUNCTION, args); + return 1; + } + for (i = 0; i < free; ++i) { + /* Bypass com_addop_varname because it will generate + LOAD_DEREF but LOAD_CLOSURE is needed. + */ + PyObject *name = PyTuple_GET_ITEM(co->co_freevars, i); + int arg, reftype; + + /* Special case: If a class contains a method with a + free variable that has the same name as a method, + the name will be considered free *and* local in the + class. It should be handled by the closure, as + well as by the normal name loookup logic. + */ + reftype = get_ref_type(c, name); + if (reftype == CELL) + arg = compiler_lookup_arg(c->u->u_cellvars, name); + else /* (reftype == FREE) */ + arg = compiler_lookup_arg(c->u->u_freevars, name); + if (arg == -1) { + fprintf(stderr, + "lookup %s in %s %d %d\n" + "freevars of %s: %s\n", + PyObject_REPR(name), + PyBytes_AS_STRING(c->u->u_name), + reftype, arg, + _PyUnicode_AsString(co->co_name), + PyObject_REPR(co->co_freevars)); + Py_FatalError("compiler_make_closure()"); + } + ADDOP_I(c, LOAD_CLOSURE, arg); + } + ADDOP_I(c, BUILD_TUPLE, free); + ADDOP_O(c, LOAD_CONST, (PyObject*)co, consts); + ADDOP_I(c, MAKE_CLOSURE, args); + return 1; } static int compiler_decorators(struct compiler *c, asdl_seq* decos) { - int i; + int i; - if (!decos) - return 1; + if (!decos) + return 1; - for (i = 0; i < asdl_seq_LEN(decos); i++) { - VISIT(c, expr, (expr_ty)asdl_seq_GET(decos, i)); - } - return 1; + for (i = 0; i < asdl_seq_LEN(decos); i++) { + VISIT(c, expr, (expr_ty)asdl_seq_GET(decos, i)); + } + return 1; } static int compiler_visit_kwonlydefaults(struct compiler *c, asdl_seq *kwonlyargs, - asdl_seq *kw_defaults) + asdl_seq *kw_defaults) { - int i, default_count = 0; - for (i = 0; i < asdl_seq_LEN(kwonlyargs); i++) { - arg_ty arg = asdl_seq_GET(kwonlyargs, i); - expr_ty default_ = asdl_seq_GET(kw_defaults, i); - if (default_) { - ADDOP_O(c, LOAD_CONST, arg->arg, consts); - if (!compiler_visit_expr(c, default_)) { - return -1; - } - default_count++; - } - } - return default_count; + int i, default_count = 0; + for (i = 0; i < asdl_seq_LEN(kwonlyargs); i++) { + arg_ty arg = asdl_seq_GET(kwonlyargs, i); + expr_ty default_ = asdl_seq_GET(kw_defaults, i); + if (default_) { + ADDOP_O(c, LOAD_CONST, arg->arg, consts); + if (!compiler_visit_expr(c, default_)) { + return -1; + } + default_count++; + } + } + return default_count; } static int compiler_visit_argannotation(struct compiler *c, identifier id, expr_ty annotation, PyObject *names) { - if (annotation) { - VISIT(c, expr, annotation); - if (PyList_Append(names, id)) - return -1; - } - return 0; + if (annotation) { + VISIT(c, expr, annotation); + if (PyList_Append(names, id)) + return -1; + } + return 0; } static int compiler_visit_argannotations(struct compiler *c, asdl_seq* args, PyObject *names) { - int i, error; - for (i = 0; i < asdl_seq_LEN(args); i++) { - arg_ty arg = (arg_ty)asdl_seq_GET(args, i); - error = compiler_visit_argannotation( - c, - arg->arg, - arg->annotation, - names); - if (error) - return error; - } - return 0; + int i, error; + for (i = 0; i < asdl_seq_LEN(args); i++) { + arg_ty arg = (arg_ty)asdl_seq_GET(args, i); + error = compiler_visit_argannotation( + c, + arg->arg, + arg->annotation, + names); + if (error) + return error; + } + return 0; } static int compiler_visit_annotations(struct compiler *c, arguments_ty args, expr_ty returns) { - /* Push arg annotations and a list of the argument names. Return the # - of items pushed. The expressions are evaluated out-of-order wrt the - source code. - - More than 2^16-1 annotations is a SyntaxError. Returns -1 on error. - */ - static identifier return_str; - PyObject *names; - int len; - names = PyList_New(0); - if (!names) - return -1; - - if (compiler_visit_argannotations(c, args->args, names)) - goto error; - if (args->varargannotation && - compiler_visit_argannotation(c, args->vararg, - args->varargannotation, names)) - goto error; - if (compiler_visit_argannotations(c, args->kwonlyargs, names)) - goto error; - if (args->kwargannotation && - compiler_visit_argannotation(c, args->kwarg, - args->kwargannotation, names)) - goto error; - - if (!return_str) { - return_str = PyUnicode_InternFromString("return"); - if (!return_str) - goto error; - } - if (compiler_visit_argannotation(c, return_str, returns, names)) { - goto error; - } - - len = PyList_GET_SIZE(names); - if (len > 65534) { - /* len must fit in 16 bits, and len is incremented below */ - PyErr_SetString(PyExc_SyntaxError, - "too many annotations"); - goto error; - } - if (len) { - /* convert names to a tuple and place on stack */ - PyObject *elt; - int i; - PyObject *s = PyTuple_New(len); - if (!s) - goto error; - for (i = 0; i < len; i++) { - elt = PyList_GET_ITEM(names, i); - Py_INCREF(elt); - PyTuple_SET_ITEM(s, i, elt); - } - ADDOP_O(c, LOAD_CONST, s, consts); - Py_DECREF(s); - len++; /* include the just-pushed tuple */ - } - Py_DECREF(names); - return len; + /* Push arg annotations and a list of the argument names. Return the # + of items pushed. The expressions are evaluated out-of-order wrt the + source code. + + More than 2^16-1 annotations is a SyntaxError. Returns -1 on error. + */ + static identifier return_str; + PyObject *names; + int len; + names = PyList_New(0); + if (!names) + return -1; + + if (compiler_visit_argannotations(c, args->args, names)) + goto error; + if (args->varargannotation && + compiler_visit_argannotation(c, args->vararg, + args->varargannotation, names)) + goto error; + if (compiler_visit_argannotations(c, args->kwonlyargs, names)) + goto error; + if (args->kwargannotation && + compiler_visit_argannotation(c, args->kwarg, + args->kwargannotation, names)) + goto error; + + if (!return_str) { + return_str = PyUnicode_InternFromString("return"); + if (!return_str) + goto error; + } + if (compiler_visit_argannotation(c, return_str, returns, names)) { + goto error; + } + + len = PyList_GET_SIZE(names); + if (len > 65534) { + /* len must fit in 16 bits, and len is incremented below */ + PyErr_SetString(PyExc_SyntaxError, + "too many annotations"); + goto error; + } + if (len) { + /* convert names to a tuple and place on stack */ + PyObject *elt; + int i; + PyObject *s = PyTuple_New(len); + if (!s) + goto error; + for (i = 0; i < len; i++) { + elt = PyList_GET_ITEM(names, i); + Py_INCREF(elt); + PyTuple_SET_ITEM(s, i, elt); + } + ADDOP_O(c, LOAD_CONST, s, consts); + Py_DECREF(s); + len++; /* include the just-pushed tuple */ + } + Py_DECREF(names); + return len; error: - Py_DECREF(names); - return -1; + Py_DECREF(names); + return -1; } static int compiler_function(struct compiler *c, stmt_ty s) { - PyCodeObject *co; - PyObject *first_const = Py_None; - arguments_ty args = s->v.FunctionDef.args; - expr_ty returns = s->v.FunctionDef.returns; - asdl_seq* decos = s->v.FunctionDef.decorator_list; - stmt_ty st; - int i, n, docstring, kw_default_count = 0, arglength; - int num_annotations; - - assert(s->kind == FunctionDef_kind); - - if (!compiler_decorators(c, decos)) - return 0; - if (args->kwonlyargs) { - int res = compiler_visit_kwonlydefaults(c, args->kwonlyargs, - args->kw_defaults); - if (res < 0) - return 0; - kw_default_count = res; - } - if (args->defaults) - VISIT_SEQ(c, expr, args->defaults); - num_annotations = compiler_visit_annotations(c, args, returns); - if (num_annotations < 0) - return 0; - assert((num_annotations & 0xFFFF) == num_annotations); - - if (!compiler_enter_scope(c, s->v.FunctionDef.name, (void *)s, - s->lineno)) - return 0; - - st = (stmt_ty)asdl_seq_GET(s->v.FunctionDef.body, 0); - docstring = compiler_isdocstring(st); - if (docstring && Py_OptimizeFlag < 2) - first_const = st->v.Expr.value->v.Str.s; - if (compiler_add_o(c, c->u->u_consts, first_const) < 0) { - compiler_exit_scope(c); - return 0; - } - - c->u->u_argcount = asdl_seq_LEN(args->args); - c->u->u_kwonlyargcount = asdl_seq_LEN(args->kwonlyargs); - n = asdl_seq_LEN(s->v.FunctionDef.body); - /* if there was a docstring, we need to skip the first statement */ - for (i = docstring; i < n; i++) { - st = (stmt_ty)asdl_seq_GET(s->v.FunctionDef.body, i); - VISIT_IN_SCOPE(c, stmt, st); - } - co = assemble(c, 1); - compiler_exit_scope(c); - if (co == NULL) - return 0; - - arglength = asdl_seq_LEN(args->defaults); - arglength |= kw_default_count << 8; - arglength |= num_annotations << 16; - compiler_make_closure(c, co, arglength); - Py_DECREF(co); - - /* decorators */ - for (i = 0; i < asdl_seq_LEN(decos); i++) { - ADDOP_I(c, CALL_FUNCTION, 1); - } + PyCodeObject *co; + PyObject *first_const = Py_None; + arguments_ty args = s->v.FunctionDef.args; + expr_ty returns = s->v.FunctionDef.returns; + asdl_seq* decos = s->v.FunctionDef.decorator_list; + stmt_ty st; + int i, n, docstring, kw_default_count = 0, arglength; + int num_annotations; + + assert(s->kind == FunctionDef_kind); + + if (!compiler_decorators(c, decos)) + return 0; + if (args->kwonlyargs) { + int res = compiler_visit_kwonlydefaults(c, args->kwonlyargs, + args->kw_defaults); + if (res < 0) + return 0; + kw_default_count = res; + } + if (args->defaults) + VISIT_SEQ(c, expr, args->defaults); + num_annotations = compiler_visit_annotations(c, args, returns); + if (num_annotations < 0) + return 0; + assert((num_annotations & 0xFFFF) == num_annotations); + + if (!compiler_enter_scope(c, s->v.FunctionDef.name, (void *)s, + s->lineno)) + return 0; + + st = (stmt_ty)asdl_seq_GET(s->v.FunctionDef.body, 0); + docstring = compiler_isdocstring(st); + if (docstring && Py_OptimizeFlag < 2) + first_const = st->v.Expr.value->v.Str.s; + if (compiler_add_o(c, c->u->u_consts, first_const) < 0) { + compiler_exit_scope(c); + return 0; + } + + c->u->u_argcount = asdl_seq_LEN(args->args); + c->u->u_kwonlyargcount = asdl_seq_LEN(args->kwonlyargs); + n = asdl_seq_LEN(s->v.FunctionDef.body); + /* if there was a docstring, we need to skip the first statement */ + for (i = docstring; i < n; i++) { + st = (stmt_ty)asdl_seq_GET(s->v.FunctionDef.body, i); + VISIT_IN_SCOPE(c, stmt, st); + } + co = assemble(c, 1); + compiler_exit_scope(c); + if (co == NULL) + return 0; + + arglength = asdl_seq_LEN(args->defaults); + arglength |= kw_default_count << 8; + arglength |= num_annotations << 16; + compiler_make_closure(c, co, arglength); + Py_DECREF(co); + + /* decorators */ + for (i = 0; i < asdl_seq_LEN(decos); i++) { + ADDOP_I(c, CALL_FUNCTION, 1); + } - return compiler_nameop(c, s->v.FunctionDef.name, Store); + return compiler_nameop(c, s->v.FunctionDef.name, Store); } static int compiler_class(struct compiler *c, stmt_ty s) { - PyCodeObject *co; - PyObject *str; - int i; - asdl_seq* decos = s->v.ClassDef.decorator_list; - - if (!compiler_decorators(c, decos)) - return 0; + PyCodeObject *co; + PyObject *str; + int i; + asdl_seq* decos = s->v.ClassDef.decorator_list; + + if (!compiler_decorators(c, decos)) + return 0; + + /* ultimately generate code for: + = __build_class__(, , *, **) + where: + is a function/closure created from the class body; + it has a single argument (__locals__) where the dict + (or MutableSequence) representing the locals is passed + is the class name + is the positional arguments and *varargs argument + is the keyword arguments and **kwds argument + This borrows from compiler_call. + */ + + /* 1. compile the class body into a code object */ + if (!compiler_enter_scope(c, s->v.ClassDef.name, (void *)s, s->lineno)) + return 0; + /* this block represents what we do in the new scope */ + { + /* use the class name for name mangling */ + Py_INCREF(s->v.ClassDef.name); + Py_XDECREF(c->u->u_private); + c->u->u_private = s->v.ClassDef.name; + /* force it to have one mandatory argument */ + c->u->u_argcount = 1; + /* load the first argument (__locals__) ... */ + ADDOP_I(c, LOAD_FAST, 0); + /* ... and store it into f_locals */ + ADDOP_IN_SCOPE(c, STORE_LOCALS); + /* load (global) __name__ ... */ + str = PyUnicode_InternFromString("__name__"); + if (!str || !compiler_nameop(c, str, Load)) { + Py_XDECREF(str); + compiler_exit_scope(c); + return 0; + } + Py_DECREF(str); + /* ... and store it as __module__ */ + str = PyUnicode_InternFromString("__module__"); + if (!str || !compiler_nameop(c, str, Store)) { + Py_XDECREF(str); + compiler_exit_scope(c); + return 0; + } + Py_DECREF(str); + /* compile the body proper */ + if (!compiler_body(c, s->v.ClassDef.body)) { + compiler_exit_scope(c); + return 0; + } + /* return the (empty) __class__ cell */ + str = PyUnicode_InternFromString("__class__"); + if (str == NULL) { + compiler_exit_scope(c); + return 0; + } + i = compiler_lookup_arg(c->u->u_cellvars, str); + Py_DECREF(str); + if (i == -1) { + /* This happens when nobody references the cell */ + PyErr_Clear(); + /* Return None */ + ADDOP_O(c, LOAD_CONST, Py_None, consts); + } + else { + /* Return the cell where to store __class__ */ + ADDOP_I(c, LOAD_CLOSURE, i); + } + ADDOP_IN_SCOPE(c, RETURN_VALUE); + /* create the code object */ + co = assemble(c, 1); + } + /* leave the new scope */ + compiler_exit_scope(c); + if (co == NULL) + return 0; + + /* 2. load the 'build_class' function */ + ADDOP(c, LOAD_BUILD_CLASS); + + /* 3. load a function (or closure) made from the code object */ + compiler_make_closure(c, co, 0); + Py_DECREF(co); + + /* 4. load class name */ + ADDOP_O(c, LOAD_CONST, s->v.ClassDef.name, consts); + + /* 5. generate the rest of the code for the call */ + if (!compiler_call_helper(c, 2, + s->v.ClassDef.bases, + s->v.ClassDef.keywords, + s->v.ClassDef.starargs, + s->v.ClassDef.kwargs)) + return 0; + + /* 6. apply decorators */ + for (i = 0; i < asdl_seq_LEN(decos); i++) { + ADDOP_I(c, CALL_FUNCTION, 1); + } - /* ultimately generate code for: - = __build_class__(, , *, **) - where: - is a function/closure created from the class body; - it has a single argument (__locals__) where the dict - (or MutableSequence) representing the locals is passed - is the class name - is the positional arguments and *varargs argument - is the keyword arguments and **kwds argument - This borrows from compiler_call. - */ - - /* 1. compile the class body into a code object */ - if (!compiler_enter_scope(c, s->v.ClassDef.name, (void *)s, s->lineno)) - return 0; - /* this block represents what we do in the new scope */ - { - /* use the class name for name mangling */ - Py_INCREF(s->v.ClassDef.name); - Py_XDECREF(c->u->u_private); - c->u->u_private = s->v.ClassDef.name; - /* force it to have one mandatory argument */ - c->u->u_argcount = 1; - /* load the first argument (__locals__) ... */ - ADDOP_I(c, LOAD_FAST, 0); - /* ... and store it into f_locals */ - ADDOP_IN_SCOPE(c, STORE_LOCALS); - /* load (global) __name__ ... */ - str = PyUnicode_InternFromString("__name__"); - if (!str || !compiler_nameop(c, str, Load)) { - Py_XDECREF(str); - compiler_exit_scope(c); - return 0; - } - Py_DECREF(str); - /* ... and store it as __module__ */ - str = PyUnicode_InternFromString("__module__"); - if (!str || !compiler_nameop(c, str, Store)) { - Py_XDECREF(str); - compiler_exit_scope(c); - return 0; - } - Py_DECREF(str); - /* compile the body proper */ - if (!compiler_body(c, s->v.ClassDef.body)) { - compiler_exit_scope(c); - return 0; - } - /* return the (empty) __class__ cell */ - str = PyUnicode_InternFromString("__class__"); - if (str == NULL) { - compiler_exit_scope(c); - return 0; - } - i = compiler_lookup_arg(c->u->u_cellvars, str); - Py_DECREF(str); - if (i == -1) { - /* This happens when nobody references the cell */ - PyErr_Clear(); - /* Return None */ - ADDOP_O(c, LOAD_CONST, Py_None, consts); - } - else { - /* Return the cell where to store __class__ */ - ADDOP_I(c, LOAD_CLOSURE, i); - } - ADDOP_IN_SCOPE(c, RETURN_VALUE); - /* create the code object */ - co = assemble(c, 1); - } - /* leave the new scope */ - compiler_exit_scope(c); - if (co == NULL) - return 0; - - /* 2. load the 'build_class' function */ - ADDOP(c, LOAD_BUILD_CLASS); - - /* 3. load a function (or closure) made from the code object */ - compiler_make_closure(c, co, 0); - Py_DECREF(co); - - /* 4. load class name */ - ADDOP_O(c, LOAD_CONST, s->v.ClassDef.name, consts); - - /* 5. generate the rest of the code for the call */ - if (!compiler_call_helper(c, 2, - s->v.ClassDef.bases, - s->v.ClassDef.keywords, - s->v.ClassDef.starargs, - s->v.ClassDef.kwargs)) - return 0; - - /* 6. apply decorators */ - for (i = 0; i < asdl_seq_LEN(decos); i++) { - ADDOP_I(c, CALL_FUNCTION, 1); - } - - /* 7. store into */ - if (!compiler_nameop(c, s->v.ClassDef.name, Store)) - return 0; - return 1; + /* 7. store into */ + if (!compiler_nameop(c, s->v.ClassDef.name, Store)) + return 0; + return 1; } static int compiler_ifexp(struct compiler *c, expr_ty e) { - basicblock *end, *next; - - assert(e->kind == IfExp_kind); - end = compiler_new_block(c); - if (end == NULL) - return 0; - next = compiler_new_block(c); - if (next == NULL) - return 0; - VISIT(c, expr, e->v.IfExp.test); - ADDOP_JABS(c, POP_JUMP_IF_FALSE, next); - VISIT(c, expr, e->v.IfExp.body); - ADDOP_JREL(c, JUMP_FORWARD, end); - compiler_use_next_block(c, next); - VISIT(c, expr, e->v.IfExp.orelse); - compiler_use_next_block(c, end); - return 1; + basicblock *end, *next; + + assert(e->kind == IfExp_kind); + end = compiler_new_block(c); + if (end == NULL) + return 0; + next = compiler_new_block(c); + if (next == NULL) + return 0; + VISIT(c, expr, e->v.IfExp.test); + ADDOP_JABS(c, POP_JUMP_IF_FALSE, next); + VISIT(c, expr, e->v.IfExp.body); + ADDOP_JREL(c, JUMP_FORWARD, end); + compiler_use_next_block(c, next); + VISIT(c, expr, e->v.IfExp.orelse); + compiler_use_next_block(c, end); + return 1; } static int compiler_lambda(struct compiler *c, expr_ty e) { - PyCodeObject *co; - static identifier name; - int kw_default_count = 0, arglength; - arguments_ty args = e->v.Lambda.args; - assert(e->kind == Lambda_kind); - - if (!name) { - name = PyUnicode_InternFromString(""); - if (!name) - return 0; - } - - if (args->kwonlyargs) { - int res = compiler_visit_kwonlydefaults(c, args->kwonlyargs, - args->kw_defaults); - if (res < 0) return 0; - kw_default_count = res; - } - if (args->defaults) - VISIT_SEQ(c, expr, args->defaults); - if (!compiler_enter_scope(c, name, (void *)e, e->lineno)) - return 0; - - c->u->u_argcount = asdl_seq_LEN(args->args); - c->u->u_kwonlyargcount = asdl_seq_LEN(args->kwonlyargs); - VISIT_IN_SCOPE(c, expr, e->v.Lambda.body); - if (c->u->u_ste->ste_generator) { - ADDOP_IN_SCOPE(c, POP_TOP); - } - else { - ADDOP_IN_SCOPE(c, RETURN_VALUE); - } - co = assemble(c, 1); - compiler_exit_scope(c); - if (co == NULL) - return 0; - - arglength = asdl_seq_LEN(args->defaults); - arglength |= kw_default_count << 8; - compiler_make_closure(c, co, arglength); - Py_DECREF(co); + PyCodeObject *co; + static identifier name; + int kw_default_count = 0, arglength; + arguments_ty args = e->v.Lambda.args; + assert(e->kind == Lambda_kind); + + if (!name) { + name = PyUnicode_InternFromString(""); + if (!name) + return 0; + } - return 1; + if (args->kwonlyargs) { + int res = compiler_visit_kwonlydefaults(c, args->kwonlyargs, + args->kw_defaults); + if (res < 0) return 0; + kw_default_count = res; + } + if (args->defaults) + VISIT_SEQ(c, expr, args->defaults); + if (!compiler_enter_scope(c, name, (void *)e, e->lineno)) + return 0; + + c->u->u_argcount = asdl_seq_LEN(args->args); + c->u->u_kwonlyargcount = asdl_seq_LEN(args->kwonlyargs); + VISIT_IN_SCOPE(c, expr, e->v.Lambda.body); + if (c->u->u_ste->ste_generator) { + ADDOP_IN_SCOPE(c, POP_TOP); + } + else { + ADDOP_IN_SCOPE(c, RETURN_VALUE); + } + co = assemble(c, 1); + compiler_exit_scope(c); + if (co == NULL) + return 0; + + arglength = asdl_seq_LEN(args->defaults); + arglength |= kw_default_count << 8; + compiler_make_closure(c, co, arglength); + Py_DECREF(co); + + return 1; } static int compiler_if(struct compiler *c, stmt_ty s) { - basicblock *end, *next; - int constant; - assert(s->kind == If_kind); - end = compiler_new_block(c); - if (end == NULL) - return 0; - - constant = expr_constant(s->v.If.test); - /* constant = 0: "if 0" - * constant = 1: "if 1", "if 2", ... - * constant = -1: rest */ - if (constant == 0) { - if (s->v.If.orelse) - VISIT_SEQ(c, stmt, s->v.If.orelse); - } else if (constant == 1) { - VISIT_SEQ(c, stmt, s->v.If.body); - } else { - if (s->v.If.orelse) { - next = compiler_new_block(c); - if (next == NULL) - return 0; - } - else - next = end; - VISIT(c, expr, s->v.If.test); - ADDOP_JABS(c, POP_JUMP_IF_FALSE, next); - VISIT_SEQ(c, stmt, s->v.If.body); - ADDOP_JREL(c, JUMP_FORWARD, end); - if (s->v.If.orelse) { - compiler_use_next_block(c, next); - VISIT_SEQ(c, stmt, s->v.If.orelse); - } - } - compiler_use_next_block(c, end); - return 1; + basicblock *end, *next; + int constant; + assert(s->kind == If_kind); + end = compiler_new_block(c); + if (end == NULL) + return 0; + + constant = expr_constant(s->v.If.test); + /* constant = 0: "if 0" + * constant = 1: "if 1", "if 2", ... + * constant = -1: rest */ + if (constant == 0) { + if (s->v.If.orelse) + VISIT_SEQ(c, stmt, s->v.If.orelse); + } else if (constant == 1) { + VISIT_SEQ(c, stmt, s->v.If.body); + } else { + if (s->v.If.orelse) { + next = compiler_new_block(c); + if (next == NULL) + return 0; + } + else + next = end; + VISIT(c, expr, s->v.If.test); + ADDOP_JABS(c, POP_JUMP_IF_FALSE, next); + VISIT_SEQ(c, stmt, s->v.If.body); + ADDOP_JREL(c, JUMP_FORWARD, end); + if (s->v.If.orelse) { + compiler_use_next_block(c, next); + VISIT_SEQ(c, stmt, s->v.If.orelse); + } + } + compiler_use_next_block(c, end); + return 1; } static int compiler_for(struct compiler *c, stmt_ty s) { - basicblock *start, *cleanup, *end; + basicblock *start, *cleanup, *end; - start = compiler_new_block(c); - cleanup = compiler_new_block(c); - end = compiler_new_block(c); - if (start == NULL || end == NULL || cleanup == NULL) - return 0; - ADDOP_JREL(c, SETUP_LOOP, end); - if (!compiler_push_fblock(c, LOOP, start)) - return 0; - VISIT(c, expr, s->v.For.iter); - ADDOP(c, GET_ITER); - compiler_use_next_block(c, start); - /* for expressions must be traced on each iteration, - so we need to set an extra line number. */ - c->u->u_lineno_set = 0; - ADDOP_JREL(c, FOR_ITER, cleanup); - VISIT(c, expr, s->v.For.target); - VISIT_SEQ(c, stmt, s->v.For.body); - ADDOP_JABS(c, JUMP_ABSOLUTE, start); - compiler_use_next_block(c, cleanup); - ADDOP(c, POP_BLOCK); - compiler_pop_fblock(c, LOOP, start); - VISIT_SEQ(c, stmt, s->v.For.orelse); - compiler_use_next_block(c, end); - return 1; + start = compiler_new_block(c); + cleanup = compiler_new_block(c); + end = compiler_new_block(c); + if (start == NULL || end == NULL || cleanup == NULL) + return 0; + ADDOP_JREL(c, SETUP_LOOP, end); + if (!compiler_push_fblock(c, LOOP, start)) + return 0; + VISIT(c, expr, s->v.For.iter); + ADDOP(c, GET_ITER); + compiler_use_next_block(c, start); + /* for expressions must be traced on each iteration, + so we need to set an extra line number. */ + c->u->u_lineno_set = 0; + ADDOP_JREL(c, FOR_ITER, cleanup); + VISIT(c, expr, s->v.For.target); + VISIT_SEQ(c, stmt, s->v.For.body); + ADDOP_JABS(c, JUMP_ABSOLUTE, start); + compiler_use_next_block(c, cleanup); + ADDOP(c, POP_BLOCK); + compiler_pop_fblock(c, LOOP, start); + VISIT_SEQ(c, stmt, s->v.For.orelse); + compiler_use_next_block(c, end); + return 1; } static int compiler_while(struct compiler *c, stmt_ty s) { - basicblock *loop, *orelse, *end, *anchor = NULL; - int constant = expr_constant(s->v.While.test); + basicblock *loop, *orelse, *end, *anchor = NULL; + int constant = expr_constant(s->v.While.test); + + if (constant == 0) { + if (s->v.While.orelse) + VISIT_SEQ(c, stmt, s->v.While.orelse); + return 1; + } + loop = compiler_new_block(c); + end = compiler_new_block(c); + if (constant == -1) { + anchor = compiler_new_block(c); + if (anchor == NULL) + return 0; + } + if (loop == NULL || end == NULL) + return 0; + if (s->v.While.orelse) { + orelse = compiler_new_block(c); + if (orelse == NULL) + return 0; + } + else + orelse = NULL; + + ADDOP_JREL(c, SETUP_LOOP, end); + compiler_use_next_block(c, loop); + if (!compiler_push_fblock(c, LOOP, loop)) + return 0; + if (constant == -1) { + /* while expressions must be traced on each iteration, + so we need to set an extra line number. */ + c->u->u_lineno_set = 0; + VISIT(c, expr, s->v.While.test); + ADDOP_JABS(c, POP_JUMP_IF_FALSE, anchor); + } + VISIT_SEQ(c, stmt, s->v.While.body); + ADDOP_JABS(c, JUMP_ABSOLUTE, loop); - if (constant == 0) { - if (s->v.While.orelse) - VISIT_SEQ(c, stmt, s->v.While.orelse); - return 1; - } - loop = compiler_new_block(c); - end = compiler_new_block(c); - if (constant == -1) { - anchor = compiler_new_block(c); - if (anchor == NULL) - return 0; - } - if (loop == NULL || end == NULL) - return 0; - if (s->v.While.orelse) { - orelse = compiler_new_block(c); - if (orelse == NULL) - return 0; - } - else - orelse = NULL; - - ADDOP_JREL(c, SETUP_LOOP, end); - compiler_use_next_block(c, loop); - if (!compiler_push_fblock(c, LOOP, loop)) - return 0; - if (constant == -1) { - /* while expressions must be traced on each iteration, - so we need to set an extra line number. */ - c->u->u_lineno_set = 0; - VISIT(c, expr, s->v.While.test); - ADDOP_JABS(c, POP_JUMP_IF_FALSE, anchor); - } - VISIT_SEQ(c, stmt, s->v.While.body); - ADDOP_JABS(c, JUMP_ABSOLUTE, loop); - - /* XXX should the two POP instructions be in a separate block - if there is no else clause ? - */ - - if (constant == -1) { - compiler_use_next_block(c, anchor); - ADDOP(c, POP_BLOCK); - } - compiler_pop_fblock(c, LOOP, loop); - if (orelse != NULL) /* what if orelse is just pass? */ - VISIT_SEQ(c, stmt, s->v.While.orelse); - compiler_use_next_block(c, end); + /* XXX should the two POP instructions be in a separate block + if there is no else clause ? + */ + + if (constant == -1) { + compiler_use_next_block(c, anchor); + ADDOP(c, POP_BLOCK); + } + compiler_pop_fblock(c, LOOP, loop); + if (orelse != NULL) /* what if orelse is just pass? */ + VISIT_SEQ(c, stmt, s->v.While.orelse); + compiler_use_next_block(c, end); - return 1; + return 1; } static int compiler_continue(struct compiler *c) { - static const char LOOP_ERROR_MSG[] = "'continue' not properly in loop"; - static const char IN_FINALLY_ERROR_MSG[] = - "'continue' not supported inside 'finally' clause"; - int i; - - if (!c->u->u_nfblocks) - return compiler_error(c, LOOP_ERROR_MSG); - i = c->u->u_nfblocks - 1; - switch (c->u->u_fblock[i].fb_type) { - case LOOP: - ADDOP_JABS(c, JUMP_ABSOLUTE, c->u->u_fblock[i].fb_block); - break; - case EXCEPT: - case FINALLY_TRY: - while (--i >= 0 && c->u->u_fblock[i].fb_type != LOOP) { - /* Prevent continue anywhere under a finally - even if hidden in a sub-try or except. */ - if (c->u->u_fblock[i].fb_type == FINALLY_END) - return compiler_error(c, IN_FINALLY_ERROR_MSG); - } - if (i == -1) - return compiler_error(c, LOOP_ERROR_MSG); - ADDOP_JABS(c, CONTINUE_LOOP, c->u->u_fblock[i].fb_block); - break; - case FINALLY_END: - return compiler_error(c, IN_FINALLY_ERROR_MSG); - } + static const char LOOP_ERROR_MSG[] = "'continue' not properly in loop"; + static const char IN_FINALLY_ERROR_MSG[] = + "'continue' not supported inside 'finally' clause"; + int i; + + if (!c->u->u_nfblocks) + return compiler_error(c, LOOP_ERROR_MSG); + i = c->u->u_nfblocks - 1; + switch (c->u->u_fblock[i].fb_type) { + case LOOP: + ADDOP_JABS(c, JUMP_ABSOLUTE, c->u->u_fblock[i].fb_block); + break; + case EXCEPT: + case FINALLY_TRY: + while (--i >= 0 && c->u->u_fblock[i].fb_type != LOOP) { + /* Prevent continue anywhere under a finally + even if hidden in a sub-try or except. */ + if (c->u->u_fblock[i].fb_type == FINALLY_END) + return compiler_error(c, IN_FINALLY_ERROR_MSG); + } + if (i == -1) + return compiler_error(c, LOOP_ERROR_MSG); + ADDOP_JABS(c, CONTINUE_LOOP, c->u->u_fblock[i].fb_block); + break; + case FINALLY_END: + return compiler_error(c, IN_FINALLY_ERROR_MSG); + } - return 1; + return 1; } /* Code generated for "try: finally: " is as follows: - - SETUP_FINALLY L - - POP_BLOCK - LOAD_CONST - L: - END_FINALLY - + + SETUP_FINALLY L + + POP_BLOCK + LOAD_CONST + L: + END_FINALLY + The special instructions use the block stack. Each block stack entry contains the instruction that created it (here SETUP_FINALLY), the level of the value stack at the time the block stack entry was created, and a label (here L). - + SETUP_FINALLY: - Pushes the current value stack level and the label - onto the block stack. + Pushes the current value stack level and the label + onto the block stack. POP_BLOCK: - Pops en entry from the block stack, and pops the value - stack until its level is the same as indicated on the - block stack. (The label is ignored.) + Pops en entry from the block stack, and pops the value + stack until its level is the same as indicated on the + block stack. (The label is ignored.) END_FINALLY: - Pops a variable number of entries from the *value* stack - and re-raises the exception they specify. The number of - entries popped depends on the (pseudo) exception type. - + Pops a variable number of entries from the *value* stack + and re-raises the exception they specify. The number of + entries popped depends on the (pseudo) exception type. + The block stack is unwound when an exception is raised: when a SETUP_FINALLY entry is found, the exception is pushed onto the value stack (and the exception condition is cleared), @@ -1897,29 +1897,29 @@ static int compiler_try_finally(struct compiler *c, stmt_ty s) { - basicblock *body, *end; - body = compiler_new_block(c); - end = compiler_new_block(c); - if (body == NULL || end == NULL) - return 0; - - ADDOP_JREL(c, SETUP_FINALLY, end); - compiler_use_next_block(c, body); - if (!compiler_push_fblock(c, FINALLY_TRY, body)) - return 0; - VISIT_SEQ(c, stmt, s->v.TryFinally.body); - ADDOP(c, POP_BLOCK); - compiler_pop_fblock(c, FINALLY_TRY, body); - - ADDOP_O(c, LOAD_CONST, Py_None, consts); - compiler_use_next_block(c, end); - if (!compiler_push_fblock(c, FINALLY_END, end)) - return 0; - VISIT_SEQ(c, stmt, s->v.TryFinally.finalbody); - ADDOP(c, END_FINALLY); - compiler_pop_fblock(c, FINALLY_END, end); + basicblock *body, *end; + body = compiler_new_block(c); + end = compiler_new_block(c); + if (body == NULL || end == NULL) + return 0; + + ADDOP_JREL(c, SETUP_FINALLY, end); + compiler_use_next_block(c, body); + if (!compiler_push_fblock(c, FINALLY_TRY, body)) + return 0; + VISIT_SEQ(c, stmt, s->v.TryFinally.body); + ADDOP(c, POP_BLOCK); + compiler_pop_fblock(c, FINALLY_TRY, body); - return 1; + ADDOP_O(c, LOAD_CONST, Py_None, consts); + compiler_use_next_block(c, end); + if (!compiler_push_fblock(c, FINALLY_END, end)) + return 0; + VISIT_SEQ(c, stmt, s->v.TryFinally.finalbody); + ADDOP(c, END_FINALLY); + compiler_pop_fblock(c, FINALLY_END, end); + + return 1; } /* @@ -1927,856 +1927,856 @@ (The contents of the value stack is shown in [], with the top at the right; 'tb' is trace-back info, 'val' the exception's associated value, and 'exc' the exception.) - - Value stack Label Instruction Argument - [] SETUP_EXCEPT L1 - [] - [] POP_BLOCK - [] JUMP_FORWARD L0 - - [tb, val, exc] L1: DUP ) - [tb, val, exc, exc] ) - [tb, val, exc, exc, E1] COMPARE_OP EXC_MATCH ) only if E1 - [tb, val, exc, 1-or-0] POP_JUMP_IF_FALSE L2 ) - [tb, val, exc] POP - [tb, val] (or POP if no V1) - [tb] POP - [] - JUMP_FORWARD L0 - - [tb, val, exc] L2: DUP + + Value stack Label Instruction Argument + [] SETUP_EXCEPT L1 + [] + [] POP_BLOCK + [] JUMP_FORWARD L0 + + [tb, val, exc] L1: DUP ) + [tb, val, exc, exc] ) + [tb, val, exc, exc, E1] COMPARE_OP EXC_MATCH ) only if E1 + [tb, val, exc, 1-or-0] POP_JUMP_IF_FALSE L2 ) + [tb, val, exc] POP + [tb, val] (or POP if no V1) + [tb] POP + [] + JUMP_FORWARD L0 + + [tb, val, exc] L2: DUP .............................etc....................... - [tb, val, exc] Ln+1: END_FINALLY # re-raise exception - - [] L0: - + [tb, val, exc] Ln+1: END_FINALLY # re-raise exception + + [] L0: + Of course, parts are not generated if Vi or Ei is not present. */ static int compiler_try_except(struct compiler *c, stmt_ty s) { - basicblock *body, *orelse, *except, *end; - int i, n; - - body = compiler_new_block(c); - except = compiler_new_block(c); - orelse = compiler_new_block(c); - end = compiler_new_block(c); - if (body == NULL || except == NULL || orelse == NULL || end == NULL) - return 0; - ADDOP_JREL(c, SETUP_EXCEPT, except); - compiler_use_next_block(c, body); - if (!compiler_push_fblock(c, EXCEPT, body)) - return 0; - VISIT_SEQ(c, stmt, s->v.TryExcept.body); - ADDOP(c, POP_BLOCK); - compiler_pop_fblock(c, EXCEPT, body); - ADDOP_JREL(c, JUMP_FORWARD, orelse); - n = asdl_seq_LEN(s->v.TryExcept.handlers); - compiler_use_next_block(c, except); - for (i = 0; i < n; i++) { - excepthandler_ty handler = (excepthandler_ty)asdl_seq_GET( - s->v.TryExcept.handlers, i); - if (!handler->v.ExceptHandler.type && i < n-1) - return compiler_error(c, "default 'except:' must be last"); - c->u->u_lineno_set = 0; - c->u->u_lineno = handler->lineno; - except = compiler_new_block(c); - if (except == NULL) - return 0; - if (handler->v.ExceptHandler.type) { - ADDOP(c, DUP_TOP); - VISIT(c, expr, handler->v.ExceptHandler.type); - ADDOP_I(c, COMPARE_OP, PyCmp_EXC_MATCH); - ADDOP_JABS(c, POP_JUMP_IF_FALSE, except); - } - ADDOP(c, POP_TOP); - if (handler->v.ExceptHandler.name) { - basicblock *cleanup_end, *cleanup_body; - - cleanup_end = compiler_new_block(c); - cleanup_body = compiler_new_block(c); - if(!(cleanup_end || cleanup_body)) - return 0; - - compiler_nameop(c, handler->v.ExceptHandler.name, Store); - ADDOP(c, POP_TOP); + basicblock *body, *orelse, *except, *end; + int i, n; - /* - try: - # body - except type as name: - try: - # body - finally: - name = None - del name - */ - - /* second try: */ - ADDOP_JREL(c, SETUP_FINALLY, cleanup_end); - compiler_use_next_block(c, cleanup_body); - if (!compiler_push_fblock(c, FINALLY_TRY, cleanup_body)) - return 0; - - /* second # body */ - VISIT_SEQ(c, stmt, handler->v.ExceptHandler.body); - ADDOP(c, POP_BLOCK); - ADDOP(c, POP_EXCEPT); - compiler_pop_fblock(c, FINALLY_TRY, cleanup_body); - - /* finally: */ - ADDOP_O(c, LOAD_CONST, Py_None, consts); - compiler_use_next_block(c, cleanup_end); - if (!compiler_push_fblock(c, FINALLY_END, cleanup_end)) - return 0; - - /* name = None */ - ADDOP_O(c, LOAD_CONST, Py_None, consts); - compiler_nameop(c, handler->v.ExceptHandler.name, Store); + body = compiler_new_block(c); + except = compiler_new_block(c); + orelse = compiler_new_block(c); + end = compiler_new_block(c); + if (body == NULL || except == NULL || orelse == NULL || end == NULL) + return 0; + ADDOP_JREL(c, SETUP_EXCEPT, except); + compiler_use_next_block(c, body); + if (!compiler_push_fblock(c, EXCEPT, body)) + return 0; + VISIT_SEQ(c, stmt, s->v.TryExcept.body); + ADDOP(c, POP_BLOCK); + compiler_pop_fblock(c, EXCEPT, body); + ADDOP_JREL(c, JUMP_FORWARD, orelse); + n = asdl_seq_LEN(s->v.TryExcept.handlers); + compiler_use_next_block(c, except); + for (i = 0; i < n; i++) { + excepthandler_ty handler = (excepthandler_ty)asdl_seq_GET( + s->v.TryExcept.handlers, i); + if (!handler->v.ExceptHandler.type && i < n-1) + return compiler_error(c, "default 'except:' must be last"); + c->u->u_lineno_set = 0; + c->u->u_lineno = handler->lineno; + except = compiler_new_block(c); + if (except == NULL) + return 0; + if (handler->v.ExceptHandler.type) { + ADDOP(c, DUP_TOP); + VISIT(c, expr, handler->v.ExceptHandler.type); + ADDOP_I(c, COMPARE_OP, PyCmp_EXC_MATCH); + ADDOP_JABS(c, POP_JUMP_IF_FALSE, except); + } + ADDOP(c, POP_TOP); + if (handler->v.ExceptHandler.name) { + basicblock *cleanup_end, *cleanup_body; + + cleanup_end = compiler_new_block(c); + cleanup_body = compiler_new_block(c); + if(!(cleanup_end || cleanup_body)) + return 0; + + compiler_nameop(c, handler->v.ExceptHandler.name, Store); + ADDOP(c, POP_TOP); + + /* + try: + # body + except type as name: + try: + # body + finally: + name = None + del name + */ + + /* second try: */ + ADDOP_JREL(c, SETUP_FINALLY, cleanup_end); + compiler_use_next_block(c, cleanup_body); + if (!compiler_push_fblock(c, FINALLY_TRY, cleanup_body)) + return 0; + + /* second # body */ + VISIT_SEQ(c, stmt, handler->v.ExceptHandler.body); + ADDOP(c, POP_BLOCK); + ADDOP(c, POP_EXCEPT); + compiler_pop_fblock(c, FINALLY_TRY, cleanup_body); + + /* finally: */ + ADDOP_O(c, LOAD_CONST, Py_None, consts); + compiler_use_next_block(c, cleanup_end); + if (!compiler_push_fblock(c, FINALLY_END, cleanup_end)) + return 0; + + /* name = None */ + ADDOP_O(c, LOAD_CONST, Py_None, consts); + compiler_nameop(c, handler->v.ExceptHandler.name, Store); - /* del name */ - compiler_nameop(c, handler->v.ExceptHandler.name, Del); + /* del name */ + compiler_nameop(c, handler->v.ExceptHandler.name, Del); - ADDOP(c, END_FINALLY); - compiler_pop_fblock(c, FINALLY_END, cleanup_end); - } - else { - basicblock *cleanup_body; + ADDOP(c, END_FINALLY); + compiler_pop_fblock(c, FINALLY_END, cleanup_end); + } + else { + basicblock *cleanup_body; - cleanup_body = compiler_new_block(c); - if(!cleanup_body) - return 0; + cleanup_body = compiler_new_block(c); + if(!cleanup_body) + return 0; - ADDOP(c, POP_TOP); ADDOP(c, POP_TOP); - compiler_use_next_block(c, cleanup_body); - if (!compiler_push_fblock(c, FINALLY_TRY, cleanup_body)) - return 0; - VISIT_SEQ(c, stmt, handler->v.ExceptHandler.body); - ADDOP(c, POP_EXCEPT); - compiler_pop_fblock(c, FINALLY_TRY, cleanup_body); - } - ADDOP_JREL(c, JUMP_FORWARD, end); - compiler_use_next_block(c, except); - } - ADDOP(c, END_FINALLY); - compiler_use_next_block(c, orelse); - VISIT_SEQ(c, stmt, s->v.TryExcept.orelse); - compiler_use_next_block(c, end); - return 1; + ADDOP(c, POP_TOP); + compiler_use_next_block(c, cleanup_body); + if (!compiler_push_fblock(c, FINALLY_TRY, cleanup_body)) + return 0; + VISIT_SEQ(c, stmt, handler->v.ExceptHandler.body); + ADDOP(c, POP_EXCEPT); + compiler_pop_fblock(c, FINALLY_TRY, cleanup_body); + } + ADDOP_JREL(c, JUMP_FORWARD, end); + compiler_use_next_block(c, except); + } + ADDOP(c, END_FINALLY); + compiler_use_next_block(c, orelse); + VISIT_SEQ(c, stmt, s->v.TryExcept.orelse); + compiler_use_next_block(c, end); + return 1; } static int compiler_import_as(struct compiler *c, identifier name, identifier asname) { - /* The IMPORT_NAME opcode was already generated. This function - merely needs to bind the result to a name. + /* The IMPORT_NAME opcode was already generated. This function + merely needs to bind the result to a name. - If there is a dot in name, we need to split it and emit a - LOAD_ATTR for each name. - */ - const Py_UNICODE *src = PyUnicode_AS_UNICODE(name); - const Py_UNICODE *dot = Py_UNICODE_strchr(src, '.'); - if (dot) { - /* Consume the base module name to get the first attribute */ - src = dot + 1; - while (dot) { - /* NB src is only defined when dot != NULL */ - PyObject *attr; - dot = Py_UNICODE_strchr(src, '.'); - attr = PyUnicode_FromUnicode(src, - dot ? dot - src : Py_UNICODE_strlen(src)); - if (!attr) - return -1; - ADDOP_O(c, LOAD_ATTR, attr, names); - Py_DECREF(attr); - src = dot + 1; - } - } - return compiler_nameop(c, asname, Store); + If there is a dot in name, we need to split it and emit a + LOAD_ATTR for each name. + */ + const Py_UNICODE *src = PyUnicode_AS_UNICODE(name); + const Py_UNICODE *dot = Py_UNICODE_strchr(src, '.'); + if (dot) { + /* Consume the base module name to get the first attribute */ + src = dot + 1; + while (dot) { + /* NB src is only defined when dot != NULL */ + PyObject *attr; + dot = Py_UNICODE_strchr(src, '.'); + attr = PyUnicode_FromUnicode(src, + dot ? dot - src : Py_UNICODE_strlen(src)); + if (!attr) + return -1; + ADDOP_O(c, LOAD_ATTR, attr, names); + Py_DECREF(attr); + src = dot + 1; + } + } + return compiler_nameop(c, asname, Store); } static int compiler_import(struct compiler *c, stmt_ty s) { - /* The Import node stores a module name like a.b.c as a single - string. This is convenient for all cases except - import a.b.c as d - where we need to parse that string to extract the individual - module names. - XXX Perhaps change the representation to make this case simpler? - */ - int i, n = asdl_seq_LEN(s->v.Import.names); - - for (i = 0; i < n; i++) { - alias_ty alias = (alias_ty)asdl_seq_GET(s->v.Import.names, i); - int r; - PyObject *level; - - level = PyLong_FromLong(0); - if (level == NULL) - return 0; - - ADDOP_O(c, LOAD_CONST, level, consts); - Py_DECREF(level); - ADDOP_O(c, LOAD_CONST, Py_None, consts); - ADDOP_NAME(c, IMPORT_NAME, alias->name, names); - - if (alias->asname) { - r = compiler_import_as(c, alias->name, alias->asname); - if (!r) - return r; - } - else { - identifier tmp = alias->name; - const Py_UNICODE *base = PyUnicode_AS_UNICODE(alias->name); - Py_UNICODE *dot = Py_UNICODE_strchr(base, '.'); - if (dot) - tmp = PyUnicode_FromUnicode(base, - dot - base); - r = compiler_nameop(c, tmp, Store); - if (dot) { - Py_DECREF(tmp); - } - if (!r) - return r; - } - } - return 1; + /* The Import node stores a module name like a.b.c as a single + string. This is convenient for all cases except + import a.b.c as d + where we need to parse that string to extract the individual + module names. + XXX Perhaps change the representation to make this case simpler? + */ + int i, n = asdl_seq_LEN(s->v.Import.names); + + for (i = 0; i < n; i++) { + alias_ty alias = (alias_ty)asdl_seq_GET(s->v.Import.names, i); + int r; + PyObject *level; + + level = PyLong_FromLong(0); + if (level == NULL) + return 0; + + ADDOP_O(c, LOAD_CONST, level, consts); + Py_DECREF(level); + ADDOP_O(c, LOAD_CONST, Py_None, consts); + ADDOP_NAME(c, IMPORT_NAME, alias->name, names); + + if (alias->asname) { + r = compiler_import_as(c, alias->name, alias->asname); + if (!r) + return r; + } + else { + identifier tmp = alias->name; + const Py_UNICODE *base = PyUnicode_AS_UNICODE(alias->name); + Py_UNICODE *dot = Py_UNICODE_strchr(base, '.'); + if (dot) + tmp = PyUnicode_FromUnicode(base, + dot - base); + r = compiler_nameop(c, tmp, Store); + if (dot) { + Py_DECREF(tmp); + } + if (!r) + return r; + } + } + return 1; } static int compiler_from_import(struct compiler *c, stmt_ty s) { - int i, n = asdl_seq_LEN(s->v.ImportFrom.names); + int i, n = asdl_seq_LEN(s->v.ImportFrom.names); + + PyObject *names = PyTuple_New(n); + PyObject *level; + + if (!names) + return 0; + + level = PyLong_FromLong(s->v.ImportFrom.level); + if (!level) { + Py_DECREF(names); + return 0; + } + + /* build up the names */ + for (i = 0; i < n; i++) { + alias_ty alias = (alias_ty)asdl_seq_GET(s->v.ImportFrom.names, i); + Py_INCREF(alias->name); + PyTuple_SET_ITEM(names, i, alias->name); + } - PyObject *names = PyTuple_New(n); - PyObject *level; - - if (!names) - return 0; - - level = PyLong_FromLong(s->v.ImportFrom.level); - if (!level) { - Py_DECREF(names); - return 0; - } - - /* build up the names */ - for (i = 0; i < n; i++) { - alias_ty alias = (alias_ty)asdl_seq_GET(s->v.ImportFrom.names, i); - Py_INCREF(alias->name); - PyTuple_SET_ITEM(names, i, alias->name); - } - - if (s->lineno > c->c_future->ff_lineno) { - if (!PyUnicode_CompareWithASCIIString(s->v.ImportFrom.module, - "__future__")) { - Py_DECREF(level); - Py_DECREF(names); - return compiler_error(c, - "from __future__ imports must occur " - "at the beginning of the file"); - - } - } - - ADDOP_O(c, LOAD_CONST, level, consts); - Py_DECREF(level); - ADDOP_O(c, LOAD_CONST, names, consts); - Py_DECREF(names); - ADDOP_NAME(c, IMPORT_NAME, s->v.ImportFrom.module, names); - for (i = 0; i < n; i++) { - alias_ty alias = (alias_ty)asdl_seq_GET(s->v.ImportFrom.names, i); - identifier store_name; - - if (i == 0 && *PyUnicode_AS_UNICODE(alias->name) == '*') { - assert(n == 1); - ADDOP(c, IMPORT_STAR); - return 1; - } - - ADDOP_NAME(c, IMPORT_FROM, alias->name, names); - store_name = alias->name; - if (alias->asname) - store_name = alias->asname; - - if (!compiler_nameop(c, store_name, Store)) { - Py_DECREF(names); - return 0; - } - } - /* remove imported module */ - ADDOP(c, POP_TOP); - return 1; + if (s->lineno > c->c_future->ff_lineno) { + if (!PyUnicode_CompareWithASCIIString(s->v.ImportFrom.module, + "__future__")) { + Py_DECREF(level); + Py_DECREF(names); + return compiler_error(c, + "from __future__ imports must occur " + "at the beginning of the file"); + + } + } + + ADDOP_O(c, LOAD_CONST, level, consts); + Py_DECREF(level); + ADDOP_O(c, LOAD_CONST, names, consts); + Py_DECREF(names); + ADDOP_NAME(c, IMPORT_NAME, s->v.ImportFrom.module, names); + for (i = 0; i < n; i++) { + alias_ty alias = (alias_ty)asdl_seq_GET(s->v.ImportFrom.names, i); + identifier store_name; + + if (i == 0 && *PyUnicode_AS_UNICODE(alias->name) == '*') { + assert(n == 1); + ADDOP(c, IMPORT_STAR); + return 1; + } + + ADDOP_NAME(c, IMPORT_FROM, alias->name, names); + store_name = alias->name; + if (alias->asname) + store_name = alias->asname; + + if (!compiler_nameop(c, store_name, Store)) { + Py_DECREF(names); + return 0; + } + } + /* remove imported module */ + ADDOP(c, POP_TOP); + return 1; } static int compiler_assert(struct compiler *c, stmt_ty s) { - static PyObject *assertion_error = NULL; - basicblock *end; + static PyObject *assertion_error = NULL; + basicblock *end; - if (Py_OptimizeFlag) - return 1; - if (assertion_error == NULL) { - assertion_error = PyUnicode_InternFromString("AssertionError"); - if (assertion_error == NULL) - return 0; - } - if (s->v.Assert.test->kind == Tuple_kind && - asdl_seq_LEN(s->v.Assert.test->v.Tuple.elts) > 0) { - const char* msg = - "assertion is always true, perhaps remove parentheses?"; - if (PyErr_WarnExplicit(PyExc_SyntaxWarning, msg, c->c_filename, - c->u->u_lineno, NULL, NULL) == -1) - return 0; - } - VISIT(c, expr, s->v.Assert.test); - end = compiler_new_block(c); - if (end == NULL) - return 0; - ADDOP_JABS(c, POP_JUMP_IF_TRUE, end); - ADDOP_O(c, LOAD_GLOBAL, assertion_error, names); - if (s->v.Assert.msg) { - VISIT(c, expr, s->v.Assert.msg); - ADDOP_I(c, CALL_FUNCTION, 1); - } - ADDOP_I(c, RAISE_VARARGS, 1); - compiler_use_next_block(c, end); - return 1; + if (Py_OptimizeFlag) + return 1; + if (assertion_error == NULL) { + assertion_error = PyUnicode_InternFromString("AssertionError"); + if (assertion_error == NULL) + return 0; + } + if (s->v.Assert.test->kind == Tuple_kind && + asdl_seq_LEN(s->v.Assert.test->v.Tuple.elts) > 0) { + const char* msg = + "assertion is always true, perhaps remove parentheses?"; + if (PyErr_WarnExplicit(PyExc_SyntaxWarning, msg, c->c_filename, + c->u->u_lineno, NULL, NULL) == -1) + return 0; + } + VISIT(c, expr, s->v.Assert.test); + end = compiler_new_block(c); + if (end == NULL) + return 0; + ADDOP_JABS(c, POP_JUMP_IF_TRUE, end); + ADDOP_O(c, LOAD_GLOBAL, assertion_error, names); + if (s->v.Assert.msg) { + VISIT(c, expr, s->v.Assert.msg); + ADDOP_I(c, CALL_FUNCTION, 1); + } + ADDOP_I(c, RAISE_VARARGS, 1); + compiler_use_next_block(c, end); + return 1; } static int compiler_visit_stmt(struct compiler *c, stmt_ty s) { - int i, n; + int i, n; - /* Always assign a lineno to the next instruction for a stmt. */ - c->u->u_lineno = s->lineno; - c->u->u_lineno_set = 0; - - switch (s->kind) { - case FunctionDef_kind: - return compiler_function(c, s); - case ClassDef_kind: - return compiler_class(c, s); - case Return_kind: - if (c->u->u_ste->ste_type != FunctionBlock) - return compiler_error(c, "'return' outside function"); - if (s->v.Return.value) { - VISIT(c, expr, s->v.Return.value); - } - else - ADDOP_O(c, LOAD_CONST, Py_None, consts); - ADDOP(c, RETURN_VALUE); - break; - case Delete_kind: - VISIT_SEQ(c, expr, s->v.Delete.targets) - break; - case Assign_kind: - n = asdl_seq_LEN(s->v.Assign.targets); - VISIT(c, expr, s->v.Assign.value); - for (i = 0; i < n; i++) { - if (i < n - 1) - ADDOP(c, DUP_TOP); - VISIT(c, expr, - (expr_ty)asdl_seq_GET(s->v.Assign.targets, i)); - } - break; - case AugAssign_kind: - return compiler_augassign(c, s); - case For_kind: - return compiler_for(c, s); - case While_kind: - return compiler_while(c, s); - case If_kind: - return compiler_if(c, s); - case Raise_kind: - n = 0; - if (s->v.Raise.exc) { - VISIT(c, expr, s->v.Raise.exc); - n++; - if (s->v.Raise.cause) { - VISIT(c, expr, s->v.Raise.cause); - n++; - } - } - ADDOP_I(c, RAISE_VARARGS, n); - break; - case TryExcept_kind: - return compiler_try_except(c, s); - case TryFinally_kind: - return compiler_try_finally(c, s); - case Assert_kind: - return compiler_assert(c, s); - case Import_kind: - return compiler_import(c, s); - case ImportFrom_kind: - return compiler_from_import(c, s); - case Global_kind: - case Nonlocal_kind: - break; - case Expr_kind: - if (c->c_interactive && c->c_nestlevel <= 1) { - VISIT(c, expr, s->v.Expr.value); - ADDOP(c, PRINT_EXPR); - } - else if (s->v.Expr.value->kind != Str_kind && - s->v.Expr.value->kind != Num_kind) { - VISIT(c, expr, s->v.Expr.value); - ADDOP(c, POP_TOP); - } - break; - case Pass_kind: - break; - case Break_kind: - if (!compiler_in_loop(c)) - return compiler_error(c, "'break' outside loop"); - ADDOP(c, BREAK_LOOP); - break; - case Continue_kind: - return compiler_continue(c); - case With_kind: - return compiler_with(c, s); - } - return 1; + /* Always assign a lineno to the next instruction for a stmt. */ + c->u->u_lineno = s->lineno; + c->u->u_lineno_set = 0; + + switch (s->kind) { + case FunctionDef_kind: + return compiler_function(c, s); + case ClassDef_kind: + return compiler_class(c, s); + case Return_kind: + if (c->u->u_ste->ste_type != FunctionBlock) + return compiler_error(c, "'return' outside function"); + if (s->v.Return.value) { + VISIT(c, expr, s->v.Return.value); + } + else + ADDOP_O(c, LOAD_CONST, Py_None, consts); + ADDOP(c, RETURN_VALUE); + break; + case Delete_kind: + VISIT_SEQ(c, expr, s->v.Delete.targets) + break; + case Assign_kind: + n = asdl_seq_LEN(s->v.Assign.targets); + VISIT(c, expr, s->v.Assign.value); + for (i = 0; i < n; i++) { + if (i < n - 1) + ADDOP(c, DUP_TOP); + VISIT(c, expr, + (expr_ty)asdl_seq_GET(s->v.Assign.targets, i)); + } + break; + case AugAssign_kind: + return compiler_augassign(c, s); + case For_kind: + return compiler_for(c, s); + case While_kind: + return compiler_while(c, s); + case If_kind: + return compiler_if(c, s); + case Raise_kind: + n = 0; + if (s->v.Raise.exc) { + VISIT(c, expr, s->v.Raise.exc); + n++; + if (s->v.Raise.cause) { + VISIT(c, expr, s->v.Raise.cause); + n++; + } + } + ADDOP_I(c, RAISE_VARARGS, n); + break; + case TryExcept_kind: + return compiler_try_except(c, s); + case TryFinally_kind: + return compiler_try_finally(c, s); + case Assert_kind: + return compiler_assert(c, s); + case Import_kind: + return compiler_import(c, s); + case ImportFrom_kind: + return compiler_from_import(c, s); + case Global_kind: + case Nonlocal_kind: + break; + case Expr_kind: + if (c->c_interactive && c->c_nestlevel <= 1) { + VISIT(c, expr, s->v.Expr.value); + ADDOP(c, PRINT_EXPR); + } + else if (s->v.Expr.value->kind != Str_kind && + s->v.Expr.value->kind != Num_kind) { + VISIT(c, expr, s->v.Expr.value); + ADDOP(c, POP_TOP); + } + break; + case Pass_kind: + break; + case Break_kind: + if (!compiler_in_loop(c)) + return compiler_error(c, "'break' outside loop"); + ADDOP(c, BREAK_LOOP); + break; + case Continue_kind: + return compiler_continue(c); + case With_kind: + return compiler_with(c, s); + } + return 1; } static int unaryop(unaryop_ty op) { - switch (op) { - case Invert: - return UNARY_INVERT; - case Not: - return UNARY_NOT; - case UAdd: - return UNARY_POSITIVE; - case USub: - return UNARY_NEGATIVE; - default: - PyErr_Format(PyExc_SystemError, - "unary op %d should not be possible", op); - return 0; - } + switch (op) { + case Invert: + return UNARY_INVERT; + case Not: + return UNARY_NOT; + case UAdd: + return UNARY_POSITIVE; + case USub: + return UNARY_NEGATIVE; + default: + PyErr_Format(PyExc_SystemError, + "unary op %d should not be possible", op); + return 0; + } } static int binop(struct compiler *c, operator_ty op) { - switch (op) { - case Add: - return BINARY_ADD; - case Sub: - return BINARY_SUBTRACT; - case Mult: - return BINARY_MULTIPLY; - case Div: - return BINARY_TRUE_DIVIDE; - case Mod: - return BINARY_MODULO; - case Pow: - return BINARY_POWER; - case LShift: - return BINARY_LSHIFT; - case RShift: - return BINARY_RSHIFT; - case BitOr: - return BINARY_OR; - case BitXor: - return BINARY_XOR; - case BitAnd: - return BINARY_AND; - case FloorDiv: - return BINARY_FLOOR_DIVIDE; - default: - PyErr_Format(PyExc_SystemError, - "binary op %d should not be possible", op); - return 0; - } + switch (op) { + case Add: + return BINARY_ADD; + case Sub: + return BINARY_SUBTRACT; + case Mult: + return BINARY_MULTIPLY; + case Div: + return BINARY_TRUE_DIVIDE; + case Mod: + return BINARY_MODULO; + case Pow: + return BINARY_POWER; + case LShift: + return BINARY_LSHIFT; + case RShift: + return BINARY_RSHIFT; + case BitOr: + return BINARY_OR; + case BitXor: + return BINARY_XOR; + case BitAnd: + return BINARY_AND; + case FloorDiv: + return BINARY_FLOOR_DIVIDE; + default: + PyErr_Format(PyExc_SystemError, + "binary op %d should not be possible", op); + return 0; + } } static int cmpop(cmpop_ty op) { - switch (op) { - case Eq: - return PyCmp_EQ; - case NotEq: - return PyCmp_NE; - case Lt: - return PyCmp_LT; - case LtE: - return PyCmp_LE; - case Gt: - return PyCmp_GT; - case GtE: - return PyCmp_GE; - case Is: - return PyCmp_IS; - case IsNot: - return PyCmp_IS_NOT; - case In: - return PyCmp_IN; - case NotIn: - return PyCmp_NOT_IN; - default: - return PyCmp_BAD; - } + switch (op) { + case Eq: + return PyCmp_EQ; + case NotEq: + return PyCmp_NE; + case Lt: + return PyCmp_LT; + case LtE: + return PyCmp_LE; + case Gt: + return PyCmp_GT; + case GtE: + return PyCmp_GE; + case Is: + return PyCmp_IS; + case IsNot: + return PyCmp_IS_NOT; + case In: + return PyCmp_IN; + case NotIn: + return PyCmp_NOT_IN; + default: + return PyCmp_BAD; + } } static int inplace_binop(struct compiler *c, operator_ty op) { - switch (op) { - case Add: - return INPLACE_ADD; - case Sub: - return INPLACE_SUBTRACT; - case Mult: - return INPLACE_MULTIPLY; - case Div: - return INPLACE_TRUE_DIVIDE; - case Mod: - return INPLACE_MODULO; - case Pow: - return INPLACE_POWER; - case LShift: - return INPLACE_LSHIFT; - case RShift: - return INPLACE_RSHIFT; - case BitOr: - return INPLACE_OR; - case BitXor: - return INPLACE_XOR; - case BitAnd: - return INPLACE_AND; - case FloorDiv: - return INPLACE_FLOOR_DIVIDE; - default: - PyErr_Format(PyExc_SystemError, - "inplace binary op %d should not be possible", op); - return 0; - } + switch (op) { + case Add: + return INPLACE_ADD; + case Sub: + return INPLACE_SUBTRACT; + case Mult: + return INPLACE_MULTIPLY; + case Div: + return INPLACE_TRUE_DIVIDE; + case Mod: + return INPLACE_MODULO; + case Pow: + return INPLACE_POWER; + case LShift: + return INPLACE_LSHIFT; + case RShift: + return INPLACE_RSHIFT; + case BitOr: + return INPLACE_OR; + case BitXor: + return INPLACE_XOR; + case BitAnd: + return INPLACE_AND; + case FloorDiv: + return INPLACE_FLOOR_DIVIDE; + default: + PyErr_Format(PyExc_SystemError, + "inplace binary op %d should not be possible", op); + return 0; + } } static int compiler_nameop(struct compiler *c, identifier name, expr_context_ty ctx) { - int op, scope, arg; - enum { OP_FAST, OP_GLOBAL, OP_DEREF, OP_NAME } optype; + int op, scope, arg; + enum { OP_FAST, OP_GLOBAL, OP_DEREF, OP_NAME } optype; + + PyObject *dict = c->u->u_names; + PyObject *mangled; + /* XXX AugStore isn't used anywhere! */ + + mangled = _Py_Mangle(c->u->u_private, name); + if (!mangled) + return 0; - PyObject *dict = c->u->u_names; - PyObject *mangled; - /* XXX AugStore isn't used anywhere! */ - - mangled = _Py_Mangle(c->u->u_private, name); - if (!mangled) - return 0; - - op = 0; - optype = OP_NAME; - scope = PyST_GetScope(c->u->u_ste, mangled); - switch (scope) { - case FREE: - dict = c->u->u_freevars; - optype = OP_DEREF; - break; - case CELL: - dict = c->u->u_cellvars; - optype = OP_DEREF; - break; - case LOCAL: - if (c->u->u_ste->ste_type == FunctionBlock) - optype = OP_FAST; - break; - case GLOBAL_IMPLICIT: - if (c->u->u_ste->ste_type == FunctionBlock && - !c->u->u_ste->ste_unoptimized) - optype = OP_GLOBAL; - break; - case GLOBAL_EXPLICIT: - optype = OP_GLOBAL; - break; - default: - /* scope can be 0 */ - break; - } - - /* XXX Leave assert here, but handle __doc__ and the like better */ - assert(scope || PyUnicode_AS_UNICODE(name)[0] == '_'); - - switch (optype) { - case OP_DEREF: - switch (ctx) { - case Load: op = LOAD_DEREF; break; - case Store: op = STORE_DEREF; break; - case AugLoad: - case AugStore: - break; - case Del: - PyErr_Format(PyExc_SyntaxError, - "can not delete variable '%S' referenced " - "in nested scope", - name); - Py_DECREF(mangled); - return 0; - case Param: - default: - PyErr_SetString(PyExc_SystemError, - "param invalid for deref variable"); - return 0; - } - break; - case OP_FAST: - switch (ctx) { - case Load: op = LOAD_FAST; break; - case Store: op = STORE_FAST; break; - case Del: op = DELETE_FAST; break; - case AugLoad: - case AugStore: - break; - case Param: - default: - PyErr_SetString(PyExc_SystemError, - "param invalid for local variable"); - return 0; - } - ADDOP_O(c, op, mangled, varnames); - Py_DECREF(mangled); - return 1; - case OP_GLOBAL: - switch (ctx) { - case Load: op = LOAD_GLOBAL; break; - case Store: op = STORE_GLOBAL; break; - case Del: op = DELETE_GLOBAL; break; - case AugLoad: - case AugStore: - break; - case Param: - default: - PyErr_SetString(PyExc_SystemError, - "param invalid for global variable"); - return 0; - } - break; - case OP_NAME: - switch (ctx) { - case Load: op = LOAD_NAME; break; - case Store: op = STORE_NAME; break; - case Del: op = DELETE_NAME; break; - case AugLoad: - case AugStore: - break; - case Param: - default: - PyErr_SetString(PyExc_SystemError, - "param invalid for name variable"); - return 0; - } - break; - } - - assert(op); - arg = compiler_add_o(c, dict, mangled); - Py_DECREF(mangled); - if (arg < 0) - return 0; - return compiler_addop_i(c, op, arg); + op = 0; + optype = OP_NAME; + scope = PyST_GetScope(c->u->u_ste, mangled); + switch (scope) { + case FREE: + dict = c->u->u_freevars; + optype = OP_DEREF; + break; + case CELL: + dict = c->u->u_cellvars; + optype = OP_DEREF; + break; + case LOCAL: + if (c->u->u_ste->ste_type == FunctionBlock) + optype = OP_FAST; + break; + case GLOBAL_IMPLICIT: + if (c->u->u_ste->ste_type == FunctionBlock && + !c->u->u_ste->ste_unoptimized) + optype = OP_GLOBAL; + break; + case GLOBAL_EXPLICIT: + optype = OP_GLOBAL; + break; + default: + /* scope can be 0 */ + break; + } + + /* XXX Leave assert here, but handle __doc__ and the like better */ + assert(scope || PyUnicode_AS_UNICODE(name)[0] == '_'); + + switch (optype) { + case OP_DEREF: + switch (ctx) { + case Load: op = LOAD_DEREF; break; + case Store: op = STORE_DEREF; break; + case AugLoad: + case AugStore: + break; + case Del: + PyErr_Format(PyExc_SyntaxError, + "can not delete variable '%S' referenced " + "in nested scope", + name); + Py_DECREF(mangled); + return 0; + case Param: + default: + PyErr_SetString(PyExc_SystemError, + "param invalid for deref variable"); + return 0; + } + break; + case OP_FAST: + switch (ctx) { + case Load: op = LOAD_FAST; break; + case Store: op = STORE_FAST; break; + case Del: op = DELETE_FAST; break; + case AugLoad: + case AugStore: + break; + case Param: + default: + PyErr_SetString(PyExc_SystemError, + "param invalid for local variable"); + return 0; + } + ADDOP_O(c, op, mangled, varnames); + Py_DECREF(mangled); + return 1; + case OP_GLOBAL: + switch (ctx) { + case Load: op = LOAD_GLOBAL; break; + case Store: op = STORE_GLOBAL; break; + case Del: op = DELETE_GLOBAL; break; + case AugLoad: + case AugStore: + break; + case Param: + default: + PyErr_SetString(PyExc_SystemError, + "param invalid for global variable"); + return 0; + } + break; + case OP_NAME: + switch (ctx) { + case Load: op = LOAD_NAME; break; + case Store: op = STORE_NAME; break; + case Del: op = DELETE_NAME; break; + case AugLoad: + case AugStore: + break; + case Param: + default: + PyErr_SetString(PyExc_SystemError, + "param invalid for name variable"); + return 0; + } + break; + } + + assert(op); + arg = compiler_add_o(c, dict, mangled); + Py_DECREF(mangled); + if (arg < 0) + return 0; + return compiler_addop_i(c, op, arg); } static int compiler_boolop(struct compiler *c, expr_ty e) { - basicblock *end; - int jumpi, i, n; - asdl_seq *s; - - assert(e->kind == BoolOp_kind); - if (e->v.BoolOp.op == And) - jumpi = JUMP_IF_FALSE_OR_POP; - else - jumpi = JUMP_IF_TRUE_OR_POP; - end = compiler_new_block(c); - if (end == NULL) - return 0; - s = e->v.BoolOp.values; - n = asdl_seq_LEN(s) - 1; - assert(n >= 0); - for (i = 0; i < n; ++i) { - VISIT(c, expr, (expr_ty)asdl_seq_GET(s, i)); - ADDOP_JABS(c, jumpi, end); - } - VISIT(c, expr, (expr_ty)asdl_seq_GET(s, n)); - compiler_use_next_block(c, end); - return 1; + basicblock *end; + int jumpi, i, n; + asdl_seq *s; + + assert(e->kind == BoolOp_kind); + if (e->v.BoolOp.op == And) + jumpi = JUMP_IF_FALSE_OR_POP; + else + jumpi = JUMP_IF_TRUE_OR_POP; + end = compiler_new_block(c); + if (end == NULL) + return 0; + s = e->v.BoolOp.values; + n = asdl_seq_LEN(s) - 1; + assert(n >= 0); + for (i = 0; i < n; ++i) { + VISIT(c, expr, (expr_ty)asdl_seq_GET(s, i)); + ADDOP_JABS(c, jumpi, end); + } + VISIT(c, expr, (expr_ty)asdl_seq_GET(s, n)); + compiler_use_next_block(c, end); + return 1; } static int compiler_list(struct compiler *c, expr_ty e) { - int n = asdl_seq_LEN(e->v.List.elts); - if (e->v.List.ctx == Store) { - int i, seen_star = 0; - for (i = 0; i < n; i++) { - expr_ty elt = asdl_seq_GET(e->v.List.elts, i); - if (elt->kind == Starred_kind && !seen_star) { - if ((i >= (1 << 8)) || - (n-i-1 >= (INT_MAX >> 8))) - return compiler_error(c, - "too many expressions in " - "star-unpacking assignment"); - ADDOP_I(c, UNPACK_EX, (i + ((n-i-1) << 8))); - seen_star = 1; - asdl_seq_SET(e->v.List.elts, i, elt->v.Starred.value); - } else if (elt->kind == Starred_kind) { - return compiler_error(c, - "two starred expressions in assignment"); - } - } - if (!seen_star) { - ADDOP_I(c, UNPACK_SEQUENCE, n); - } - } - VISIT_SEQ(c, expr, e->v.List.elts); - if (e->v.List.ctx == Load) { - ADDOP_I(c, BUILD_LIST, n); - } - return 1; + int n = asdl_seq_LEN(e->v.List.elts); + if (e->v.List.ctx == Store) { + int i, seen_star = 0; + for (i = 0; i < n; i++) { + expr_ty elt = asdl_seq_GET(e->v.List.elts, i); + if (elt->kind == Starred_kind && !seen_star) { + if ((i >= (1 << 8)) || + (n-i-1 >= (INT_MAX >> 8))) + return compiler_error(c, + "too many expressions in " + "star-unpacking assignment"); + ADDOP_I(c, UNPACK_EX, (i + ((n-i-1) << 8))); + seen_star = 1; + asdl_seq_SET(e->v.List.elts, i, elt->v.Starred.value); + } else if (elt->kind == Starred_kind) { + return compiler_error(c, + "two starred expressions in assignment"); + } + } + if (!seen_star) { + ADDOP_I(c, UNPACK_SEQUENCE, n); + } + } + VISIT_SEQ(c, expr, e->v.List.elts); + if (e->v.List.ctx == Load) { + ADDOP_I(c, BUILD_LIST, n); + } + return 1; } static int compiler_tuple(struct compiler *c, expr_ty e) { - int n = asdl_seq_LEN(e->v.Tuple.elts); - if (e->v.Tuple.ctx == Store) { - int i, seen_star = 0; - for (i = 0; i < n; i++) { - expr_ty elt = asdl_seq_GET(e->v.Tuple.elts, i); - if (elt->kind == Starred_kind && !seen_star) { - if ((i >= (1 << 8)) || - (n-i-1 >= (INT_MAX >> 8))) - return compiler_error(c, - "too many expressions in " - "star-unpacking assignment"); - ADDOP_I(c, UNPACK_EX, (i + ((n-i-1) << 8))); - seen_star = 1; - asdl_seq_SET(e->v.Tuple.elts, i, elt->v.Starred.value); - } else if (elt->kind == Starred_kind) { - return compiler_error(c, - "two starred expressions in assignment"); - } - } - if (!seen_star) { - ADDOP_I(c, UNPACK_SEQUENCE, n); - } - } - VISIT_SEQ(c, expr, e->v.Tuple.elts); - if (e->v.Tuple.ctx == Load) { - ADDOP_I(c, BUILD_TUPLE, n); - } - return 1; + int n = asdl_seq_LEN(e->v.Tuple.elts); + if (e->v.Tuple.ctx == Store) { + int i, seen_star = 0; + for (i = 0; i < n; i++) { + expr_ty elt = asdl_seq_GET(e->v.Tuple.elts, i); + if (elt->kind == Starred_kind && !seen_star) { + if ((i >= (1 << 8)) || + (n-i-1 >= (INT_MAX >> 8))) + return compiler_error(c, + "too many expressions in " + "star-unpacking assignment"); + ADDOP_I(c, UNPACK_EX, (i + ((n-i-1) << 8))); + seen_star = 1; + asdl_seq_SET(e->v.Tuple.elts, i, elt->v.Starred.value); + } else if (elt->kind == Starred_kind) { + return compiler_error(c, + "two starred expressions in assignment"); + } + } + if (!seen_star) { + ADDOP_I(c, UNPACK_SEQUENCE, n); + } + } + VISIT_SEQ(c, expr, e->v.Tuple.elts); + if (e->v.Tuple.ctx == Load) { + ADDOP_I(c, BUILD_TUPLE, n); + } + return 1; } static int compiler_compare(struct compiler *c, expr_ty e) { - int i, n; - basicblock *cleanup = NULL; + int i, n; + basicblock *cleanup = NULL; - /* XXX the logic can be cleaned up for 1 or multiple comparisons */ - VISIT(c, expr, e->v.Compare.left); - n = asdl_seq_LEN(e->v.Compare.ops); - assert(n > 0); - if (n > 1) { - cleanup = compiler_new_block(c); - if (cleanup == NULL) - return 0; - VISIT(c, expr, - (expr_ty)asdl_seq_GET(e->v.Compare.comparators, 0)); - } - for (i = 1; i < n; i++) { - ADDOP(c, DUP_TOP); - ADDOP(c, ROT_THREE); - ADDOP_I(c, COMPARE_OP, - cmpop((cmpop_ty)(asdl_seq_GET( - e->v.Compare.ops, i - 1)))); - ADDOP_JABS(c, JUMP_IF_FALSE_OR_POP, cleanup); - NEXT_BLOCK(c); - if (i < (n - 1)) - VISIT(c, expr, - (expr_ty)asdl_seq_GET(e->v.Compare.comparators, i)); - } - VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Compare.comparators, n - 1)); - ADDOP_I(c, COMPARE_OP, - cmpop((cmpop_ty)(asdl_seq_GET(e->v.Compare.ops, n - 1)))); - if (n > 1) { - basicblock *end = compiler_new_block(c); - if (end == NULL) - return 0; - ADDOP_JREL(c, JUMP_FORWARD, end); - compiler_use_next_block(c, cleanup); - ADDOP(c, ROT_TWO); - ADDOP(c, POP_TOP); - compiler_use_next_block(c, end); - } - return 1; + /* XXX the logic can be cleaned up for 1 or multiple comparisons */ + VISIT(c, expr, e->v.Compare.left); + n = asdl_seq_LEN(e->v.Compare.ops); + assert(n > 0); + if (n > 1) { + cleanup = compiler_new_block(c); + if (cleanup == NULL) + return 0; + VISIT(c, expr, + (expr_ty)asdl_seq_GET(e->v.Compare.comparators, 0)); + } + for (i = 1; i < n; i++) { + ADDOP(c, DUP_TOP); + ADDOP(c, ROT_THREE); + ADDOP_I(c, COMPARE_OP, + cmpop((cmpop_ty)(asdl_seq_GET( + e->v.Compare.ops, i - 1)))); + ADDOP_JABS(c, JUMP_IF_FALSE_OR_POP, cleanup); + NEXT_BLOCK(c); + if (i < (n - 1)) + VISIT(c, expr, + (expr_ty)asdl_seq_GET(e->v.Compare.comparators, i)); + } + VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Compare.comparators, n - 1)); + ADDOP_I(c, COMPARE_OP, + cmpop((cmpop_ty)(asdl_seq_GET(e->v.Compare.ops, n - 1)))); + if (n > 1) { + basicblock *end = compiler_new_block(c); + if (end == NULL) + return 0; + ADDOP_JREL(c, JUMP_FORWARD, end); + compiler_use_next_block(c, cleanup); + ADDOP(c, ROT_TWO); + ADDOP(c, POP_TOP); + compiler_use_next_block(c, end); + } + return 1; } static int compiler_call(struct compiler *c, expr_ty e) { - VISIT(c, expr, e->v.Call.func); - return compiler_call_helper(c, 0, - e->v.Call.args, - e->v.Call.keywords, - e->v.Call.starargs, - e->v.Call.kwargs); + VISIT(c, expr, e->v.Call.func); + return compiler_call_helper(c, 0, + e->v.Call.args, + e->v.Call.keywords, + e->v.Call.starargs, + e->v.Call.kwargs); } /* shared code between compiler_call and compiler_class */ static int compiler_call_helper(struct compiler *c, - int n, /* Args already pushed */ - asdl_seq *args, - asdl_seq *keywords, - expr_ty starargs, - expr_ty kwargs) -{ - int code = 0; - - n += asdl_seq_LEN(args); - VISIT_SEQ(c, expr, args); - if (keywords) { - VISIT_SEQ(c, keyword, keywords); - n |= asdl_seq_LEN(keywords) << 8; - } - if (starargs) { - VISIT(c, expr, starargs); - code |= 1; - } - if (kwargs) { - VISIT(c, expr, kwargs); - code |= 2; - } - switch (code) { - case 0: - ADDOP_I(c, CALL_FUNCTION, n); - break; - case 1: - ADDOP_I(c, CALL_FUNCTION_VAR, n); - break; - case 2: - ADDOP_I(c, CALL_FUNCTION_KW, n); - break; - case 3: - ADDOP_I(c, CALL_FUNCTION_VAR_KW, n); - break; - } - return 1; + int n, /* Args already pushed */ + asdl_seq *args, + asdl_seq *keywords, + expr_ty starargs, + expr_ty kwargs) +{ + int code = 0; + + n += asdl_seq_LEN(args); + VISIT_SEQ(c, expr, args); + if (keywords) { + VISIT_SEQ(c, keyword, keywords); + n |= asdl_seq_LEN(keywords) << 8; + } + if (starargs) { + VISIT(c, expr, starargs); + code |= 1; + } + if (kwargs) { + VISIT(c, expr, kwargs); + code |= 2; + } + switch (code) { + case 0: + ADDOP_I(c, CALL_FUNCTION, n); + break; + case 1: + ADDOP_I(c, CALL_FUNCTION_VAR, n); + break; + case 2: + ADDOP_I(c, CALL_FUNCTION_KW, n); + break; + case 3: + ADDOP_I(c, CALL_FUNCTION_VAR_KW, n); + break; + } + return 1; } @@ -2796,228 +2796,228 @@ */ static int -compiler_comprehension_generator(struct compiler *c, - asdl_seq *generators, int gen_index, - expr_ty elt, expr_ty val, int type) -{ - /* generate code for the iterator, then each of the ifs, - and then write to the element */ - - comprehension_ty gen; - basicblock *start, *anchor, *skip, *if_cleanup; - int i, n; - - start = compiler_new_block(c); - skip = compiler_new_block(c); - if_cleanup = compiler_new_block(c); - anchor = compiler_new_block(c); - - if (start == NULL || skip == NULL || if_cleanup == NULL || - anchor == NULL) - return 0; - - gen = (comprehension_ty)asdl_seq_GET(generators, gen_index); - - if (gen_index == 0) { - /* Receive outermost iter as an implicit argument */ - c->u->u_argcount = 1; - ADDOP_I(c, LOAD_FAST, 0); - } - else { - /* Sub-iter - calculate on the fly */ - VISIT(c, expr, gen->iter); - ADDOP(c, GET_ITER); - } - compiler_use_next_block(c, start); - ADDOP_JREL(c, FOR_ITER, anchor); - NEXT_BLOCK(c); - VISIT(c, expr, gen->target); - - /* XXX this needs to be cleaned up...a lot! */ - n = asdl_seq_LEN(gen->ifs); - for (i = 0; i < n; i++) { - expr_ty e = (expr_ty)asdl_seq_GET(gen->ifs, i); - VISIT(c, expr, e); - ADDOP_JABS(c, POP_JUMP_IF_FALSE, if_cleanup); - NEXT_BLOCK(c); - } - - if (++gen_index < asdl_seq_LEN(generators)) - if (!compiler_comprehension_generator(c, - generators, gen_index, - elt, val, type)) - return 0; - - /* only append after the last for generator */ - if (gen_index >= asdl_seq_LEN(generators)) { - /* comprehension specific code */ - switch (type) { - case COMP_GENEXP: - VISIT(c, expr, elt); - ADDOP(c, YIELD_VALUE); - ADDOP(c, POP_TOP); - break; - case COMP_LISTCOMP: - VISIT(c, expr, elt); - ADDOP_I(c, LIST_APPEND, gen_index + 1); - break; - case COMP_SETCOMP: - VISIT(c, expr, elt); - ADDOP_I(c, SET_ADD, gen_index + 1); - break; - case COMP_DICTCOMP: - /* With 'd[k] = v', v is evaluated before k, so we do - the same. */ - VISIT(c, expr, val); - VISIT(c, expr, elt); - ADDOP_I(c, MAP_ADD, gen_index + 1); - break; - default: - return 0; - } - - compiler_use_next_block(c, skip); - } - compiler_use_next_block(c, if_cleanup); - ADDOP_JABS(c, JUMP_ABSOLUTE, start); - compiler_use_next_block(c, anchor); +compiler_comprehension_generator(struct compiler *c, + asdl_seq *generators, int gen_index, + expr_ty elt, expr_ty val, int type) +{ + /* generate code for the iterator, then each of the ifs, + and then write to the element */ + + comprehension_ty gen; + basicblock *start, *anchor, *skip, *if_cleanup; + int i, n; + + start = compiler_new_block(c); + skip = compiler_new_block(c); + if_cleanup = compiler_new_block(c); + anchor = compiler_new_block(c); + + if (start == NULL || skip == NULL || if_cleanup == NULL || + anchor == NULL) + return 0; + + gen = (comprehension_ty)asdl_seq_GET(generators, gen_index); + + if (gen_index == 0) { + /* Receive outermost iter as an implicit argument */ + c->u->u_argcount = 1; + ADDOP_I(c, LOAD_FAST, 0); + } + else { + /* Sub-iter - calculate on the fly */ + VISIT(c, expr, gen->iter); + ADDOP(c, GET_ITER); + } + compiler_use_next_block(c, start); + ADDOP_JREL(c, FOR_ITER, anchor); + NEXT_BLOCK(c); + VISIT(c, expr, gen->target); + + /* XXX this needs to be cleaned up...a lot! */ + n = asdl_seq_LEN(gen->ifs); + for (i = 0; i < n; i++) { + expr_ty e = (expr_ty)asdl_seq_GET(gen->ifs, i); + VISIT(c, expr, e); + ADDOP_JABS(c, POP_JUMP_IF_FALSE, if_cleanup); + NEXT_BLOCK(c); + } + + if (++gen_index < asdl_seq_LEN(generators)) + if (!compiler_comprehension_generator(c, + generators, gen_index, + elt, val, type)) + return 0; + + /* only append after the last for generator */ + if (gen_index >= asdl_seq_LEN(generators)) { + /* comprehension specific code */ + switch (type) { + case COMP_GENEXP: + VISIT(c, expr, elt); + ADDOP(c, YIELD_VALUE); + ADDOP(c, POP_TOP); + break; + case COMP_LISTCOMP: + VISIT(c, expr, elt); + ADDOP_I(c, LIST_APPEND, gen_index + 1); + break; + case COMP_SETCOMP: + VISIT(c, expr, elt); + ADDOP_I(c, SET_ADD, gen_index + 1); + break; + case COMP_DICTCOMP: + /* With 'd[k] = v', v is evaluated before k, so we do + the same. */ + VISIT(c, expr, val); + VISIT(c, expr, elt); + ADDOP_I(c, MAP_ADD, gen_index + 1); + break; + default: + return 0; + } + + compiler_use_next_block(c, skip); + } + compiler_use_next_block(c, if_cleanup); + ADDOP_JABS(c, JUMP_ABSOLUTE, start); + compiler_use_next_block(c, anchor); - return 1; + return 1; } static int compiler_comprehension(struct compiler *c, expr_ty e, int type, identifier name, - asdl_seq *generators, expr_ty elt, expr_ty val) + asdl_seq *generators, expr_ty elt, expr_ty val) { - PyCodeObject *co = NULL; - expr_ty outermost_iter; + PyCodeObject *co = NULL; + expr_ty outermost_iter; + + outermost_iter = ((comprehension_ty) + asdl_seq_GET(generators, 0))->iter; + + if (!compiler_enter_scope(c, name, (void *)e, e->lineno)) + goto error; + + if (type != COMP_GENEXP) { + int op; + switch (type) { + case COMP_LISTCOMP: + op = BUILD_LIST; + break; + case COMP_SETCOMP: + op = BUILD_SET; + break; + case COMP_DICTCOMP: + op = BUILD_MAP; + break; + default: + PyErr_Format(PyExc_SystemError, + "unknown comprehension type %d", type); + goto error_in_scope; + } + + ADDOP_I(c, op, 0); + } - outermost_iter = ((comprehension_ty) - asdl_seq_GET(generators, 0))->iter; + if (!compiler_comprehension_generator(c, generators, 0, elt, + val, type)) + goto error_in_scope; - if (!compiler_enter_scope(c, name, (void *)e, e->lineno)) - goto error; - - if (type != COMP_GENEXP) { - int op; - switch (type) { - case COMP_LISTCOMP: - op = BUILD_LIST; - break; - case COMP_SETCOMP: - op = BUILD_SET; - break; - case COMP_DICTCOMP: - op = BUILD_MAP; - break; - default: - PyErr_Format(PyExc_SystemError, - "unknown comprehension type %d", type); - goto error_in_scope; - } - - ADDOP_I(c, op, 0); - } - - if (!compiler_comprehension_generator(c, generators, 0, elt, - val, type)) - goto error_in_scope; - - if (type != COMP_GENEXP) { - ADDOP(c, RETURN_VALUE); - } - - co = assemble(c, 1); - compiler_exit_scope(c); - if (co == NULL) - goto error; - - if (!compiler_make_closure(c, co, 0)) - goto error; - Py_DECREF(co); - - VISIT(c, expr, outermost_iter); - ADDOP(c, GET_ITER); - ADDOP_I(c, CALL_FUNCTION, 1); - return 1; + if (type != COMP_GENEXP) { + ADDOP(c, RETURN_VALUE); + } + + co = assemble(c, 1); + compiler_exit_scope(c); + if (co == NULL) + goto error; + + if (!compiler_make_closure(c, co, 0)) + goto error; + Py_DECREF(co); + + VISIT(c, expr, outermost_iter); + ADDOP(c, GET_ITER); + ADDOP_I(c, CALL_FUNCTION, 1); + return 1; error_in_scope: - compiler_exit_scope(c); + compiler_exit_scope(c); error: - Py_XDECREF(co); - return 0; + Py_XDECREF(co); + return 0; } static int compiler_genexp(struct compiler *c, expr_ty e) { - static identifier name; - if (!name) { - name = PyUnicode_FromString(""); - if (!name) - return 0; - } - assert(e->kind == GeneratorExp_kind); - return compiler_comprehension(c, e, COMP_GENEXP, name, - e->v.GeneratorExp.generators, - e->v.GeneratorExp.elt, NULL); + static identifier name; + if (!name) { + name = PyUnicode_FromString(""); + if (!name) + return 0; + } + assert(e->kind == GeneratorExp_kind); + return compiler_comprehension(c, e, COMP_GENEXP, name, + e->v.GeneratorExp.generators, + e->v.GeneratorExp.elt, NULL); } static int compiler_listcomp(struct compiler *c, expr_ty e) { - static identifier name; - if (!name) { - name = PyUnicode_FromString(""); - if (!name) - return 0; - } - assert(e->kind == ListComp_kind); - return compiler_comprehension(c, e, COMP_LISTCOMP, name, - e->v.ListComp.generators, - e->v.ListComp.elt, NULL); + static identifier name; + if (!name) { + name = PyUnicode_FromString(""); + if (!name) + return 0; + } + assert(e->kind == ListComp_kind); + return compiler_comprehension(c, e, COMP_LISTCOMP, name, + e->v.ListComp.generators, + e->v.ListComp.elt, NULL); } static int compiler_setcomp(struct compiler *c, expr_ty e) { - static identifier name; - if (!name) { - name = PyUnicode_FromString(""); - if (!name) - return 0; - } - assert(e->kind == SetComp_kind); - return compiler_comprehension(c, e, COMP_SETCOMP, name, - e->v.SetComp.generators, - e->v.SetComp.elt, NULL); + static identifier name; + if (!name) { + name = PyUnicode_FromString(""); + if (!name) + return 0; + } + assert(e->kind == SetComp_kind); + return compiler_comprehension(c, e, COMP_SETCOMP, name, + e->v.SetComp.generators, + e->v.SetComp.elt, NULL); } static int compiler_dictcomp(struct compiler *c, expr_ty e) { - static identifier name; - if (!name) { - name = PyUnicode_FromString(""); - if (!name) - return 0; - } - assert(e->kind == DictComp_kind); - return compiler_comprehension(c, e, COMP_DICTCOMP, name, - e->v.DictComp.generators, - e->v.DictComp.key, e->v.DictComp.value); + static identifier name; + if (!name) { + name = PyUnicode_FromString(""); + if (!name) + return 0; + } + assert(e->kind == DictComp_kind); + return compiler_comprehension(c, e, COMP_DICTCOMP, name, + e->v.DictComp.generators, + e->v.DictComp.key, e->v.DictComp.value); } static int compiler_visit_keyword(struct compiler *c, keyword_ty k) { - ADDOP_O(c, LOAD_CONST, k->arg, consts); - VISIT(c, expr, k->value); - return 1; + ADDOP_O(c, LOAD_CONST, k->arg, consts); + VISIT(c, expr, k->value); + return 1; } -/* Test whether expression is constant. For constants, report +/* Test whether expression is constant. For constants, report whether they are true or false. Return values: 1 for true, 0 for false, -1 for non-constant. @@ -3026,39 +3026,39 @@ static int expr_constant(expr_ty e) { - char *id; - switch (e->kind) { - case Ellipsis_kind: - return 1; - case Num_kind: - return PyObject_IsTrue(e->v.Num.n); - case Str_kind: - return PyObject_IsTrue(e->v.Str.s); - case Name_kind: - /* optimize away names that can't be reassigned */ - id = PyBytes_AS_STRING( - _PyUnicode_AsDefaultEncodedString(e->v.Name.id, NULL)); - if (strcmp(id, "True") == 0) return 1; - if (strcmp(id, "False") == 0) return 0; - if (strcmp(id, "None") == 0) return 0; - if (strcmp(id, "__debug__") == 0) - return ! Py_OptimizeFlag; - /* fall through */ - default: - return -1; - } + char *id; + switch (e->kind) { + case Ellipsis_kind: + return 1; + case Num_kind: + return PyObject_IsTrue(e->v.Num.n); + case Str_kind: + return PyObject_IsTrue(e->v.Str.s); + case Name_kind: + /* optimize away names that can't be reassigned */ + id = PyBytes_AS_STRING( + _PyUnicode_AsDefaultEncodedString(e->v.Name.id, NULL)); + if (strcmp(id, "True") == 0) return 1; + if (strcmp(id, "False") == 0) return 0; + if (strcmp(id, "None") == 0) return 0; + if (strcmp(id, "__debug__") == 0) + return ! Py_OptimizeFlag; + /* fall through */ + default: + return -1; + } } /* Implements the with statement from PEP 343. - The semantics outlined in that PEP are as follows: + The semantics outlined in that PEP are as follows: with EXPR as VAR: BLOCK - + It is implemented roughly as: - + context = EXPR exit = context.__exit__ # not calling it value = context.__enter__() @@ -3067,9 +3067,9 @@ BLOCK finally: if an exception was raised: - exc = copy of (exception, instance, traceback) + exc = copy of (exception, instance, traceback) else: - exc = (None, None, None) + exc = (None, None, None) exit(*exc) */ static int @@ -3082,40 +3082,40 @@ assert(s->kind == With_kind); if (!enter_attr) { - enter_attr = PyUnicode_InternFromString("__enter__"); - if (!enter_attr) - return 0; + enter_attr = PyUnicode_InternFromString("__enter__"); + if (!enter_attr) + return 0; } if (!exit_attr) { - exit_attr = PyUnicode_InternFromString("__exit__"); - if (!exit_attr) - return 0; + exit_attr = PyUnicode_InternFromString("__exit__"); + if (!exit_attr) + return 0; } block = compiler_new_block(c); finally = compiler_new_block(c); if (!block || !finally) - return 0; + return 0; if (s->v.With.optional_vars) { - /* Create a temporary variable to hold context.__enter__(). - We need to do this rather than preserving it on the stack - because SETUP_FINALLY remembers the stack level. - We need to do the assignment *inside* the try/finally - so that context.__exit__() is called when the assignment - fails. But we need to call context.__enter__() *before* - the try/finally so that if it fails we won't call - context.__exit__(). - */ - tmpvalue = compiler_new_tmpname(c); - if (tmpvalue == NULL) - return 0; - PyArena_AddPyObject(c->c_arena, tmpvalue); - } - tmpexit = compiler_new_tmpname(c); - if (tmpexit == NULL) - return 0; - PyArena_AddPyObject(c->c_arena, tmpexit); + /* Create a temporary variable to hold context.__enter__(). + We need to do this rather than preserving it on the stack + because SETUP_FINALLY remembers the stack level. + We need to do the assignment *inside* the try/finally + so that context.__exit__() is called when the assignment + fails. But we need to call context.__enter__() *before* + the try/finally so that if it fails we won't call + context.__exit__(). + */ + tmpvalue = compiler_new_tmpname(c); + if (tmpvalue == NULL) + return 0; + PyArena_AddPyObject(c->c_arena, tmpvalue); + } + tmpexit = compiler_new_tmpname(c); + if (tmpexit == NULL) + return 0; + PyArena_AddPyObject(c->c_arena, tmpexit); /* Evaluate EXPR */ VISIT(c, expr, s->v.With.context_expr); @@ -3123,21 +3123,21 @@ /* Squirrel away context.__exit__ by stuffing it under context */ ADDOP(c, DUP_TOP); ADDOP_O(c, LOAD_ATTR, exit_attr, names); - if (!compiler_nameop(c, tmpexit, Store)) - return 0; + if (!compiler_nameop(c, tmpexit, Store)) + return 0; /* Call context.__enter__() */ ADDOP_O(c, LOAD_ATTR, enter_attr, names); ADDOP_I(c, CALL_FUNCTION, 0); if (s->v.With.optional_vars) { - /* Store it in tmpvalue */ - if (!compiler_nameop(c, tmpvalue, Store)) - return 0; + /* Store it in tmpvalue */ + if (!compiler_nameop(c, tmpvalue, Store)) + return 0; } else { - /* Discard result from context.__enter__() */ - ADDOP(c, POP_TOP); + /* Discard result from context.__enter__() */ + ADDOP(c, POP_TOP); } /* Start the try block */ @@ -3145,15 +3145,15 @@ compiler_use_next_block(c, block); if (!compiler_push_fblock(c, FINALLY_TRY, block)) { - return 0; + return 0; } if (s->v.With.optional_vars) { - /* Bind saved result of context.__enter__() to VAR */ - if (!compiler_nameop(c, tmpvalue, Load) || - !compiler_nameop(c, tmpvalue, Del)) - return 0; - VISIT(c, expr, s->v.With.optional_vars); + /* Bind saved result of context.__enter__() to VAR */ + if (!compiler_nameop(c, tmpvalue, Load) || + !compiler_nameop(c, tmpvalue, Del)) + return 0; + VISIT(c, expr, s->v.With.optional_vars); } /* BLOCK code */ @@ -3166,14 +3166,14 @@ ADDOP_O(c, LOAD_CONST, Py_None, consts); compiler_use_next_block(c, finally); if (!compiler_push_fblock(c, FINALLY_END, finally)) - return 0; + return 0; /* Finally block starts; context.__exit__ is on the stack under the exception or return information. Just issue our magic opcode. */ - if (!compiler_nameop(c, tmpexit, Load) || - !compiler_nameop(c, tmpexit, Del)) - return 0; + if (!compiler_nameop(c, tmpexit, Load) || + !compiler_nameop(c, tmpexit, Del)) + return 0; ADDOP(c, WITH_CLEANUP); /* Finally block ends. */ @@ -3185,240 +3185,240 @@ static int compiler_visit_expr(struct compiler *c, expr_ty e) { - int i, n; + int i, n; - /* If expr e has a different line number than the last expr/stmt, - set a new line number for the next instruction. - */ - if (e->lineno > c->u->u_lineno) { - c->u->u_lineno = e->lineno; - c->u->u_lineno_set = 0; - } - switch (e->kind) { - case BoolOp_kind: - return compiler_boolop(c, e); - case BinOp_kind: - VISIT(c, expr, e->v.BinOp.left); - VISIT(c, expr, e->v.BinOp.right); - ADDOP(c, binop(c, e->v.BinOp.op)); - break; - case UnaryOp_kind: - VISIT(c, expr, e->v.UnaryOp.operand); - ADDOP(c, unaryop(e->v.UnaryOp.op)); - break; - case Lambda_kind: - return compiler_lambda(c, e); - case IfExp_kind: - return compiler_ifexp(c, e); - case Dict_kind: - n = asdl_seq_LEN(e->v.Dict.values); - ADDOP_I(c, BUILD_MAP, (n>0xFFFF ? 0xFFFF : n)); - for (i = 0; i < n; i++) { - VISIT(c, expr, - (expr_ty)asdl_seq_GET(e->v.Dict.values, i)); - VISIT(c, expr, - (expr_ty)asdl_seq_GET(e->v.Dict.keys, i)); - ADDOP(c, STORE_MAP); - } - break; - case Set_kind: - n = asdl_seq_LEN(e->v.Set.elts); - VISIT_SEQ(c, expr, e->v.Set.elts); - ADDOP_I(c, BUILD_SET, n); - break; - case GeneratorExp_kind: - return compiler_genexp(c, e); - case ListComp_kind: - return compiler_listcomp(c, e); - case SetComp_kind: - return compiler_setcomp(c, e); - case DictComp_kind: - return compiler_dictcomp(c, e); - case Yield_kind: - if (c->u->u_ste->ste_type != FunctionBlock) - return compiler_error(c, "'yield' outside function"); - if (e->v.Yield.value) { - VISIT(c, expr, e->v.Yield.value); - } - else { - ADDOP_O(c, LOAD_CONST, Py_None, consts); - } - ADDOP(c, YIELD_VALUE); - break; - case Compare_kind: - return compiler_compare(c, e); - case Call_kind: - return compiler_call(c, e); - case Num_kind: - ADDOP_O(c, LOAD_CONST, e->v.Num.n, consts); - break; - case Str_kind: - ADDOP_O(c, LOAD_CONST, e->v.Str.s, consts); - break; - case Bytes_kind: - ADDOP_O(c, LOAD_CONST, e->v.Bytes.s, consts); - break; - case Ellipsis_kind: - ADDOP_O(c, LOAD_CONST, Py_Ellipsis, consts); - break; - /* The following exprs can be assignment targets. */ - case Attribute_kind: - if (e->v.Attribute.ctx != AugStore) - VISIT(c, expr, e->v.Attribute.value); - switch (e->v.Attribute.ctx) { - case AugLoad: - ADDOP(c, DUP_TOP); - /* Fall through to load */ - case Load: - ADDOP_NAME(c, LOAD_ATTR, e->v.Attribute.attr, names); - break; - case AugStore: - ADDOP(c, ROT_TWO); - /* Fall through to save */ - case Store: - ADDOP_NAME(c, STORE_ATTR, e->v.Attribute.attr, names); - break; - case Del: - ADDOP_NAME(c, DELETE_ATTR, e->v.Attribute.attr, names); - break; - case Param: - default: - PyErr_SetString(PyExc_SystemError, - "param invalid in attribute expression"); - return 0; - } - break; - case Subscript_kind: - switch (e->v.Subscript.ctx) { - case AugLoad: - VISIT(c, expr, e->v.Subscript.value); - VISIT_SLICE(c, e->v.Subscript.slice, AugLoad); - break; - case Load: - VISIT(c, expr, e->v.Subscript.value); - VISIT_SLICE(c, e->v.Subscript.slice, Load); - break; - case AugStore: - VISIT_SLICE(c, e->v.Subscript.slice, AugStore); - break; - case Store: - VISIT(c, expr, e->v.Subscript.value); - VISIT_SLICE(c, e->v.Subscript.slice, Store); - break; - case Del: - VISIT(c, expr, e->v.Subscript.value); - VISIT_SLICE(c, e->v.Subscript.slice, Del); - break; - case Param: - default: - PyErr_SetString(PyExc_SystemError, - "param invalid in subscript expression"); - return 0; - } - break; - case Starred_kind: - switch (e->v.Starred.ctx) { - case Store: - /* In all legitimate cases, the Starred node was already replaced - * by compiler_list/compiler_tuple. XXX: is that okay? */ - return compiler_error(c, - "starred assignment target must be in a list or tuple"); - default: - return compiler_error(c, - "can use starred expression only as assignment target"); - } - break; - case Name_kind: - return compiler_nameop(c, e->v.Name.id, e->v.Name.ctx); - /* child nodes of List and Tuple will have expr_context set */ - case List_kind: - return compiler_list(c, e); - case Tuple_kind: - return compiler_tuple(c, e); - } - return 1; + /* If expr e has a different line number than the last expr/stmt, + set a new line number for the next instruction. + */ + if (e->lineno > c->u->u_lineno) { + c->u->u_lineno = e->lineno; + c->u->u_lineno_set = 0; + } + switch (e->kind) { + case BoolOp_kind: + return compiler_boolop(c, e); + case BinOp_kind: + VISIT(c, expr, e->v.BinOp.left); + VISIT(c, expr, e->v.BinOp.right); + ADDOP(c, binop(c, e->v.BinOp.op)); + break; + case UnaryOp_kind: + VISIT(c, expr, e->v.UnaryOp.operand); + ADDOP(c, unaryop(e->v.UnaryOp.op)); + break; + case Lambda_kind: + return compiler_lambda(c, e); + case IfExp_kind: + return compiler_ifexp(c, e); + case Dict_kind: + n = asdl_seq_LEN(e->v.Dict.values); + ADDOP_I(c, BUILD_MAP, (n>0xFFFF ? 0xFFFF : n)); + for (i = 0; i < n; i++) { + VISIT(c, expr, + (expr_ty)asdl_seq_GET(e->v.Dict.values, i)); + VISIT(c, expr, + (expr_ty)asdl_seq_GET(e->v.Dict.keys, i)); + ADDOP(c, STORE_MAP); + } + break; + case Set_kind: + n = asdl_seq_LEN(e->v.Set.elts); + VISIT_SEQ(c, expr, e->v.Set.elts); + ADDOP_I(c, BUILD_SET, n); + break; + case GeneratorExp_kind: + return compiler_genexp(c, e); + case ListComp_kind: + return compiler_listcomp(c, e); + case SetComp_kind: + return compiler_setcomp(c, e); + case DictComp_kind: + return compiler_dictcomp(c, e); + case Yield_kind: + if (c->u->u_ste->ste_type != FunctionBlock) + return compiler_error(c, "'yield' outside function"); + if (e->v.Yield.value) { + VISIT(c, expr, e->v.Yield.value); + } + else { + ADDOP_O(c, LOAD_CONST, Py_None, consts); + } + ADDOP(c, YIELD_VALUE); + break; + case Compare_kind: + return compiler_compare(c, e); + case Call_kind: + return compiler_call(c, e); + case Num_kind: + ADDOP_O(c, LOAD_CONST, e->v.Num.n, consts); + break; + case Str_kind: + ADDOP_O(c, LOAD_CONST, e->v.Str.s, consts); + break; + case Bytes_kind: + ADDOP_O(c, LOAD_CONST, e->v.Bytes.s, consts); + break; + case Ellipsis_kind: + ADDOP_O(c, LOAD_CONST, Py_Ellipsis, consts); + break; + /* The following exprs can be assignment targets. */ + case Attribute_kind: + if (e->v.Attribute.ctx != AugStore) + VISIT(c, expr, e->v.Attribute.value); + switch (e->v.Attribute.ctx) { + case AugLoad: + ADDOP(c, DUP_TOP); + /* Fall through to load */ + case Load: + ADDOP_NAME(c, LOAD_ATTR, e->v.Attribute.attr, names); + break; + case AugStore: + ADDOP(c, ROT_TWO); + /* Fall through to save */ + case Store: + ADDOP_NAME(c, STORE_ATTR, e->v.Attribute.attr, names); + break; + case Del: + ADDOP_NAME(c, DELETE_ATTR, e->v.Attribute.attr, names); + break; + case Param: + default: + PyErr_SetString(PyExc_SystemError, + "param invalid in attribute expression"); + return 0; + } + break; + case Subscript_kind: + switch (e->v.Subscript.ctx) { + case AugLoad: + VISIT(c, expr, e->v.Subscript.value); + VISIT_SLICE(c, e->v.Subscript.slice, AugLoad); + break; + case Load: + VISIT(c, expr, e->v.Subscript.value); + VISIT_SLICE(c, e->v.Subscript.slice, Load); + break; + case AugStore: + VISIT_SLICE(c, e->v.Subscript.slice, AugStore); + break; + case Store: + VISIT(c, expr, e->v.Subscript.value); + VISIT_SLICE(c, e->v.Subscript.slice, Store); + break; + case Del: + VISIT(c, expr, e->v.Subscript.value); + VISIT_SLICE(c, e->v.Subscript.slice, Del); + break; + case Param: + default: + PyErr_SetString(PyExc_SystemError, + "param invalid in subscript expression"); + return 0; + } + break; + case Starred_kind: + switch (e->v.Starred.ctx) { + case Store: + /* In all legitimate cases, the Starred node was already replaced + * by compiler_list/compiler_tuple. XXX: is that okay? */ + return compiler_error(c, + "starred assignment target must be in a list or tuple"); + default: + return compiler_error(c, + "can use starred expression only as assignment target"); + } + break; + case Name_kind: + return compiler_nameop(c, e->v.Name.id, e->v.Name.ctx); + /* child nodes of List and Tuple will have expr_context set */ + case List_kind: + return compiler_list(c, e); + case Tuple_kind: + return compiler_tuple(c, e); + } + return 1; } static int compiler_augassign(struct compiler *c, stmt_ty s) { - expr_ty e = s->v.AugAssign.target; - expr_ty auge; + expr_ty e = s->v.AugAssign.target; + expr_ty auge; - assert(s->kind == AugAssign_kind); + assert(s->kind == AugAssign_kind); - switch (e->kind) { - case Attribute_kind: - auge = Attribute(e->v.Attribute.value, e->v.Attribute.attr, - AugLoad, e->lineno, e->col_offset, c->c_arena); - if (auge == NULL) - return 0; - VISIT(c, expr, auge); - VISIT(c, expr, s->v.AugAssign.value); - ADDOP(c, inplace_binop(c, s->v.AugAssign.op)); - auge->v.Attribute.ctx = AugStore; - VISIT(c, expr, auge); - break; - case Subscript_kind: - auge = Subscript(e->v.Subscript.value, e->v.Subscript.slice, - AugLoad, e->lineno, e->col_offset, c->c_arena); - if (auge == NULL) - return 0; - VISIT(c, expr, auge); - VISIT(c, expr, s->v.AugAssign.value); - ADDOP(c, inplace_binop(c, s->v.AugAssign.op)); - auge->v.Subscript.ctx = AugStore; - VISIT(c, expr, auge); - break; - case Name_kind: - if (!compiler_nameop(c, e->v.Name.id, Load)) - return 0; - VISIT(c, expr, s->v.AugAssign.value); - ADDOP(c, inplace_binop(c, s->v.AugAssign.op)); - return compiler_nameop(c, e->v.Name.id, Store); - default: - PyErr_Format(PyExc_SystemError, - "invalid node type (%d) for augmented assignment", - e->kind); - return 0; - } - return 1; + switch (e->kind) { + case Attribute_kind: + auge = Attribute(e->v.Attribute.value, e->v.Attribute.attr, + AugLoad, e->lineno, e->col_offset, c->c_arena); + if (auge == NULL) + return 0; + VISIT(c, expr, auge); + VISIT(c, expr, s->v.AugAssign.value); + ADDOP(c, inplace_binop(c, s->v.AugAssign.op)); + auge->v.Attribute.ctx = AugStore; + VISIT(c, expr, auge); + break; + case Subscript_kind: + auge = Subscript(e->v.Subscript.value, e->v.Subscript.slice, + AugLoad, e->lineno, e->col_offset, c->c_arena); + if (auge == NULL) + return 0; + VISIT(c, expr, auge); + VISIT(c, expr, s->v.AugAssign.value); + ADDOP(c, inplace_binop(c, s->v.AugAssign.op)); + auge->v.Subscript.ctx = AugStore; + VISIT(c, expr, auge); + break; + case Name_kind: + if (!compiler_nameop(c, e->v.Name.id, Load)) + return 0; + VISIT(c, expr, s->v.AugAssign.value); + ADDOP(c, inplace_binop(c, s->v.AugAssign.op)); + return compiler_nameop(c, e->v.Name.id, Store); + default: + PyErr_Format(PyExc_SystemError, + "invalid node type (%d) for augmented assignment", + e->kind); + return 0; + } + return 1; } static int compiler_push_fblock(struct compiler *c, enum fblocktype t, basicblock *b) { - struct fblockinfo *f; - if (c->u->u_nfblocks >= CO_MAXBLOCKS) { - PyErr_SetString(PyExc_SystemError, - "too many statically nested blocks"); - return 0; - } - f = &c->u->u_fblock[c->u->u_nfblocks++]; - f->fb_type = t; - f->fb_block = b; - return 1; + struct fblockinfo *f; + if (c->u->u_nfblocks >= CO_MAXBLOCKS) { + PyErr_SetString(PyExc_SystemError, + "too many statically nested blocks"); + return 0; + } + f = &c->u->u_fblock[c->u->u_nfblocks++]; + f->fb_type = t; + f->fb_block = b; + return 1; } static void compiler_pop_fblock(struct compiler *c, enum fblocktype t, basicblock *b) { - struct compiler_unit *u = c->u; - assert(u->u_nfblocks > 0); - u->u_nfblocks--; - assert(u->u_fblock[u->u_nfblocks].fb_type == t); - assert(u->u_fblock[u->u_nfblocks].fb_block == b); + struct compiler_unit *u = c->u; + assert(u->u_nfblocks > 0); + u->u_nfblocks--; + assert(u->u_fblock[u->u_nfblocks].fb_type == t); + assert(u->u_fblock[u->u_nfblocks].fb_block == b); } static int compiler_in_loop(struct compiler *c) { - int i; - struct compiler_unit *u = c->u; - for (i = 0; i < u->u_nfblocks; ++i) { - if (u->u_fblock[i].fb_type == LOOP) - return 1; - } - return 0; + int i; + struct compiler_unit *u = c->u; + for (i = 0; i < u->u_nfblocks; ++i) { + if (u->u_fblock[i].fb_type == LOOP) + return 1; + } + return 0; } /* Raises a SyntaxError and returns 0. If something goes wrong, a different exception may be raised. @@ -3427,143 +3427,143 @@ static int compiler_error(struct compiler *c, const char *errstr) { - PyObject *loc; - PyObject *u = NULL, *v = NULL; + PyObject *loc; + PyObject *u = NULL, *v = NULL; - loc = PyErr_ProgramText(c->c_filename, c->u->u_lineno); - if (!loc) { - Py_INCREF(Py_None); - loc = Py_None; - } - u = Py_BuildValue("(ziOO)", c->c_filename, c->u->u_lineno, - Py_None, loc); - if (!u) - goto exit; - v = Py_BuildValue("(zO)", errstr, u); - if (!v) - goto exit; - PyErr_SetObject(PyExc_SyntaxError, v); + loc = PyErr_ProgramText(c->c_filename, c->u->u_lineno); + if (!loc) { + Py_INCREF(Py_None); + loc = Py_None; + } + u = Py_BuildValue("(ziOO)", c->c_filename, c->u->u_lineno, + Py_None, loc); + if (!u) + goto exit; + v = Py_BuildValue("(zO)", errstr, u); + if (!v) + goto exit; + PyErr_SetObject(PyExc_SyntaxError, v); exit: - Py_DECREF(loc); - Py_XDECREF(u); - Py_XDECREF(v); - return 0; + Py_DECREF(loc); + Py_XDECREF(u); + Py_XDECREF(v); + return 0; } static int -compiler_handle_subscr(struct compiler *c, const char *kind, - expr_context_ty ctx) -{ - int op = 0; - - /* XXX this code is duplicated */ - switch (ctx) { - case AugLoad: /* fall through to Load */ - case Load: op = BINARY_SUBSCR; break; - case AugStore:/* fall through to Store */ - case Store: op = STORE_SUBSCR; break; - case Del: op = DELETE_SUBSCR; break; - case Param: - PyErr_Format(PyExc_SystemError, - "invalid %s kind %d in subscript\n", - kind, ctx); - return 0; - } - if (ctx == AugLoad) { - ADDOP_I(c, DUP_TOPX, 2); - } - else if (ctx == AugStore) { - ADDOP(c, ROT_THREE); - } - ADDOP(c, op); - return 1; +compiler_handle_subscr(struct compiler *c, const char *kind, + expr_context_ty ctx) +{ + int op = 0; + + /* XXX this code is duplicated */ + switch (ctx) { + case AugLoad: /* fall through to Load */ + case Load: op = BINARY_SUBSCR; break; + case AugStore:/* fall through to Store */ + case Store: op = STORE_SUBSCR; break; + case Del: op = DELETE_SUBSCR; break; + case Param: + PyErr_Format(PyExc_SystemError, + "invalid %s kind %d in subscript\n", + kind, ctx); + return 0; + } + if (ctx == AugLoad) { + ADDOP_I(c, DUP_TOPX, 2); + } + else if (ctx == AugStore) { + ADDOP(c, ROT_THREE); + } + ADDOP(c, op); + return 1; } static int compiler_slice(struct compiler *c, slice_ty s, expr_context_ty ctx) { - int n = 2; - assert(s->kind == Slice_kind); + int n = 2; + assert(s->kind == Slice_kind); - /* only handles the cases where BUILD_SLICE is emitted */ - if (s->v.Slice.lower) { - VISIT(c, expr, s->v.Slice.lower); - } - else { - ADDOP_O(c, LOAD_CONST, Py_None, consts); - } - - if (s->v.Slice.upper) { - VISIT(c, expr, s->v.Slice.upper); - } - else { - ADDOP_O(c, LOAD_CONST, Py_None, consts); - } - - if (s->v.Slice.step) { - n++; - VISIT(c, expr, s->v.Slice.step); - } - ADDOP_I(c, BUILD_SLICE, n); - return 1; + /* only handles the cases where BUILD_SLICE is emitted */ + if (s->v.Slice.lower) { + VISIT(c, expr, s->v.Slice.lower); + } + else { + ADDOP_O(c, LOAD_CONST, Py_None, consts); + } + + if (s->v.Slice.upper) { + VISIT(c, expr, s->v.Slice.upper); + } + else { + ADDOP_O(c, LOAD_CONST, Py_None, consts); + } + + if (s->v.Slice.step) { + n++; + VISIT(c, expr, s->v.Slice.step); + } + ADDOP_I(c, BUILD_SLICE, n); + return 1; } static int -compiler_visit_nested_slice(struct compiler *c, slice_ty s, - expr_context_ty ctx) -{ - switch (s->kind) { - case Slice_kind: - return compiler_slice(c, s, ctx); - case Index_kind: - VISIT(c, expr, s->v.Index.value); - break; - case ExtSlice_kind: - default: - PyErr_SetString(PyExc_SystemError, - "extended slice invalid in nested slice"); - return 0; - } - return 1; +compiler_visit_nested_slice(struct compiler *c, slice_ty s, + expr_context_ty ctx) +{ + switch (s->kind) { + case Slice_kind: + return compiler_slice(c, s, ctx); + case Index_kind: + VISIT(c, expr, s->v.Index.value); + break; + case ExtSlice_kind: + default: + PyErr_SetString(PyExc_SystemError, + "extended slice invalid in nested slice"); + return 0; + } + return 1; } static int compiler_visit_slice(struct compiler *c, slice_ty s, expr_context_ty ctx) { - char * kindname = NULL; - switch (s->kind) { - case Index_kind: - kindname = "index"; - if (ctx != AugStore) { - VISIT(c, expr, s->v.Index.value); - } - break; - case Slice_kind: - kindname = "slice"; - if (ctx != AugStore) { - if (!compiler_slice(c, s, ctx)) - return 0; - } - break; - case ExtSlice_kind: - kindname = "extended slice"; - if (ctx != AugStore) { - int i, n = asdl_seq_LEN(s->v.ExtSlice.dims); - for (i = 0; i < n; i++) { - slice_ty sub = (slice_ty)asdl_seq_GET( - s->v.ExtSlice.dims, i); - if (!compiler_visit_nested_slice(c, sub, ctx)) - return 0; - } - ADDOP_I(c, BUILD_TUPLE, n); - } - break; - default: - PyErr_Format(PyExc_SystemError, - "invalid subscript kind %d", s->kind); - return 0; - } - return compiler_handle_subscr(c, kindname, ctx); + char * kindname = NULL; + switch (s->kind) { + case Index_kind: + kindname = "index"; + if (ctx != AugStore) { + VISIT(c, expr, s->v.Index.value); + } + break; + case Slice_kind: + kindname = "slice"; + if (ctx != AugStore) { + if (!compiler_slice(c, s, ctx)) + return 0; + } + break; + case ExtSlice_kind: + kindname = "extended slice"; + if (ctx != AugStore) { + int i, n = asdl_seq_LEN(s->v.ExtSlice.dims); + for (i = 0; i < n; i++) { + slice_ty sub = (slice_ty)asdl_seq_GET( + s->v.ExtSlice.dims, i); + if (!compiler_visit_nested_slice(c, sub, ctx)) + return 0; + } + ADDOP_I(c, BUILD_TUPLE, n); + } + break; + default: + PyErr_Format(PyExc_SystemError, + "invalid subscript kind %d", s->kind); + return 0; + } + return compiler_handle_subscr(c, kindname, ctx); } /* End of the compiler section, beginning of the assembler section */ @@ -3575,64 +3575,64 @@ */ struct assembler { - PyObject *a_bytecode; /* string containing bytecode */ - int a_offset; /* offset into bytecode */ - int a_nblocks; /* number of reachable blocks */ - basicblock **a_postorder; /* list of blocks in dfs postorder */ - PyObject *a_lnotab; /* string containing lnotab */ - int a_lnotab_off; /* offset into lnotab */ - int a_lineno; /* last lineno of emitted instruction */ - int a_lineno_off; /* bytecode offset of last lineno */ + PyObject *a_bytecode; /* string containing bytecode */ + int a_offset; /* offset into bytecode */ + int a_nblocks; /* number of reachable blocks */ + basicblock **a_postorder; /* list of blocks in dfs postorder */ + PyObject *a_lnotab; /* string containing lnotab */ + int a_lnotab_off; /* offset into lnotab */ + int a_lineno; /* last lineno of emitted instruction */ + int a_lineno_off; /* bytecode offset of last lineno */ }; static void dfs(struct compiler *c, basicblock *b, struct assembler *a) { - int i; - struct instr *instr = NULL; + int i; + struct instr *instr = NULL; - if (b->b_seen) - return; - b->b_seen = 1; - if (b->b_next != NULL) - dfs(c, b->b_next, a); - for (i = 0; i < b->b_iused; i++) { - instr = &b->b_instr[i]; - if (instr->i_jrel || instr->i_jabs) - dfs(c, instr->i_target, a); - } - a->a_postorder[a->a_nblocks++] = b; + if (b->b_seen) + return; + b->b_seen = 1; + if (b->b_next != NULL) + dfs(c, b->b_next, a); + for (i = 0; i < b->b_iused; i++) { + instr = &b->b_instr[i]; + if (instr->i_jrel || instr->i_jabs) + dfs(c, instr->i_target, a); + } + a->a_postorder[a->a_nblocks++] = b; } static int stackdepth_walk(struct compiler *c, basicblock *b, int depth, int maxdepth) { - int i; - struct instr *instr; - if (b->b_seen || b->b_startdepth >= depth) - return maxdepth; - b->b_seen = 1; - b->b_startdepth = depth; - for (i = 0; i < b->b_iused; i++) { - instr = &b->b_instr[i]; - depth += opcode_stack_effect(instr->i_opcode, instr->i_oparg); - if (depth > maxdepth) - maxdepth = depth; - assert(depth >= 0); /* invalid code or bug in stackdepth() */ - if (instr->i_jrel || instr->i_jabs) { - maxdepth = stackdepth_walk(c, instr->i_target, - depth, maxdepth); - if (instr->i_opcode == JUMP_ABSOLUTE || - instr->i_opcode == JUMP_FORWARD) { - goto out; /* remaining code is dead */ - } - } - } - if (b->b_next) - maxdepth = stackdepth_walk(c, b->b_next, depth, maxdepth); + int i; + struct instr *instr; + if (b->b_seen || b->b_startdepth >= depth) + return maxdepth; + b->b_seen = 1; + b->b_startdepth = depth; + for (i = 0; i < b->b_iused; i++) { + instr = &b->b_instr[i]; + depth += opcode_stack_effect(instr->i_opcode, instr->i_oparg); + if (depth > maxdepth) + maxdepth = depth; + assert(depth >= 0); /* invalid code or bug in stackdepth() */ + if (instr->i_jrel || instr->i_jabs) { + maxdepth = stackdepth_walk(c, instr->i_target, + depth, maxdepth); + if (instr->i_opcode == JUMP_ABSOLUTE || + instr->i_opcode == JUMP_FORWARD) { + goto out; /* remaining code is dead */ + } + } + } + if (b->b_next) + maxdepth = stackdepth_walk(c, b->b_next, depth, maxdepth); out: - b->b_seen = 0; - return maxdepth; + b->b_seen = 0; + return maxdepth; } /* Find the flow path that needs the largest stack. We assume that @@ -3641,49 +3641,49 @@ static int stackdepth(struct compiler *c) { - basicblock *b, *entryblock; - entryblock = NULL; - for (b = c->u->u_blocks; b != NULL; b = b->b_list) { - b->b_seen = 0; - b->b_startdepth = INT_MIN; - entryblock = b; - } - if (!entryblock) - return 0; - return stackdepth_walk(c, entryblock, 0, 0); + basicblock *b, *entryblock; + entryblock = NULL; + for (b = c->u->u_blocks; b != NULL; b = b->b_list) { + b->b_seen = 0; + b->b_startdepth = INT_MIN; + entryblock = b; + } + if (!entryblock) + return 0; + return stackdepth_walk(c, entryblock, 0, 0); } static int assemble_init(struct assembler *a, int nblocks, int firstlineno) { - memset(a, 0, sizeof(struct assembler)); - a->a_lineno = firstlineno; - a->a_bytecode = PyBytes_FromStringAndSize(NULL, DEFAULT_CODE_SIZE); - if (!a->a_bytecode) - return 0; - a->a_lnotab = PyBytes_FromStringAndSize(NULL, DEFAULT_LNOTAB_SIZE); - if (!a->a_lnotab) - return 0; - if (nblocks > PY_SIZE_MAX / sizeof(basicblock *)) { - PyErr_NoMemory(); - return 0; - } - a->a_postorder = (basicblock **)PyObject_Malloc( - sizeof(basicblock *) * nblocks); - if (!a->a_postorder) { - PyErr_NoMemory(); - return 0; - } - return 1; + memset(a, 0, sizeof(struct assembler)); + a->a_lineno = firstlineno; + a->a_bytecode = PyBytes_FromStringAndSize(NULL, DEFAULT_CODE_SIZE); + if (!a->a_bytecode) + return 0; + a->a_lnotab = PyBytes_FromStringAndSize(NULL, DEFAULT_LNOTAB_SIZE); + if (!a->a_lnotab) + return 0; + if (nblocks > PY_SIZE_MAX / sizeof(basicblock *)) { + PyErr_NoMemory(); + return 0; + } + a->a_postorder = (basicblock **)PyObject_Malloc( + sizeof(basicblock *) * nblocks); + if (!a->a_postorder) { + PyErr_NoMemory(); + return 0; + } + return 1; } static void assemble_free(struct assembler *a) { - Py_XDECREF(a->a_bytecode); - Py_XDECREF(a->a_lnotab); - if (a->a_postorder) - PyObject_Free(a->a_postorder); + Py_XDECREF(a->a_bytecode); + Py_XDECREF(a->a_lnotab); + if (a->a_postorder) + PyObject_Free(a->a_postorder); } /* Return the size of a basic block in bytes. */ @@ -3691,22 +3691,22 @@ static int instrsize(struct instr *instr) { - if (!instr->i_hasarg) - return 1; /* 1 byte for the opcode*/ - if (instr->i_oparg > 0xffff) - return 6; /* 1 (opcode) + 1 (EXTENDED_ARG opcode) + 2 (oparg) + 2(oparg extended) */ - return 3; /* 1 (opcode) + 2 (oparg) */ + if (!instr->i_hasarg) + return 1; /* 1 byte for the opcode*/ + if (instr->i_oparg > 0xffff) + return 6; /* 1 (opcode) + 1 (EXTENDED_ARG opcode) + 2 (oparg) + 2(oparg extended) */ + return 3; /* 1 (opcode) + 2 (oparg) */ } static int blocksize(basicblock *b) { - int i; - int size = 0; + int i; + int size = 0; - for (i = 0; i < b->b_iused; i++) - size += instrsize(&b->b_instr[i]); - return size; + for (i = 0; i < b->b_iused; i++) + size += instrsize(&b->b_instr[i]); + return size; } /* All about a_lnotab. @@ -3717,14 +3717,14 @@ The array is conceptually a list of (bytecode offset increment, line number increment) -pairs. The details are important and delicate, best illustrated by example: +pairs. The details are important and delicate, best illustrated by example: - byte code offset source code line number - 0 1 - 6 2 - 50 7 - 350 307 - 361 308 + byte code offset source code line number + 0 1 + 6 2 + 50 7 + 350 307 + 361 308 The first trick is that these numbers aren't stored, only the increments from one row to the next (this doesn't really work, but it's a start): @@ -3736,116 +3736,116 @@ offsets and their corresponding line #s both increase monotonically, and (b) if at least one column jumps by more than 255 from one row to the next, more than one pair is written to the table. In case #b, there's no way to know -from looking at the table later how many were written. That's the delicate +from looking at the table later how many were written. That's the delicate part. A user of c_lnotab desiring to find the source line number corresponding to a bytecode address A should do something like this lineno = addr = 0 for addr_incr, line_incr in c_lnotab: - addr += addr_incr - if addr > A: - return lineno - lineno += line_incr + addr += addr_incr + if addr > A: + return lineno + lineno += line_incr In order for this to work, when the addr field increments by more than 255, the line # increment in each pair generated must be 0 until the remaining addr increment is < 256. So, in the example above, assemble_lnotab (it used to be called com_set_lineno) should not (as was actually done until 2.2) -expand 300, 300 to 255, 255, 45, 45, - but to 255, 0, 45, 255, 0, 45. +expand 300, 300 to 255, 255, 45, 45, + but to 255, 0, 45, 255, 0, 45. */ static int assemble_lnotab(struct assembler *a, struct instr *i) { - int d_bytecode, d_lineno; - int len; - unsigned char *lnotab; - - d_bytecode = a->a_offset - a->a_lineno_off; - d_lineno = i->i_lineno - a->a_lineno; - - assert(d_bytecode >= 0); - assert(d_lineno >= 0); - - if(d_bytecode == 0 && d_lineno == 0) - return 1; - - if (d_bytecode > 255) { - int j, nbytes, ncodes = d_bytecode / 255; - nbytes = a->a_lnotab_off + 2 * ncodes; - len = PyBytes_GET_SIZE(a->a_lnotab); - if (nbytes >= len) { - if ((len <= INT_MAX / 2) && (len * 2 < nbytes)) - len = nbytes; - else if (len <= INT_MAX / 2) - len *= 2; - else { - PyErr_NoMemory(); - return 0; - } - if (_PyBytes_Resize(&a->a_lnotab, len) < 0) - return 0; - } - lnotab = (unsigned char *) - PyBytes_AS_STRING(a->a_lnotab) + a->a_lnotab_off; - for (j = 0; j < ncodes; j++) { - *lnotab++ = 255; - *lnotab++ = 0; - } - d_bytecode -= ncodes * 255; - a->a_lnotab_off += ncodes * 2; - } - assert(d_bytecode <= 255); - if (d_lineno > 255) { - int j, nbytes, ncodes = d_lineno / 255; - nbytes = a->a_lnotab_off + 2 * ncodes; - len = PyBytes_GET_SIZE(a->a_lnotab); - if (nbytes >= len) { - if ((len <= INT_MAX / 2) && len * 2 < nbytes) - len = nbytes; - else if (len <= INT_MAX / 2) - len *= 2; - else { - PyErr_NoMemory(); - return 0; - } - if (_PyBytes_Resize(&a->a_lnotab, len) < 0) - return 0; - } - lnotab = (unsigned char *) - PyBytes_AS_STRING(a->a_lnotab) + a->a_lnotab_off; - *lnotab++ = d_bytecode; - *lnotab++ = 255; - d_bytecode = 0; - for (j = 1; j < ncodes; j++) { - *lnotab++ = 0; - *lnotab++ = 255; - } - d_lineno -= ncodes * 255; - a->a_lnotab_off += ncodes * 2; - } - - len = PyBytes_GET_SIZE(a->a_lnotab); - if (a->a_lnotab_off + 2 >= len) { - if (_PyBytes_Resize(&a->a_lnotab, len * 2) < 0) - return 0; - } - lnotab = (unsigned char *) - PyBytes_AS_STRING(a->a_lnotab) + a->a_lnotab_off; - - a->a_lnotab_off += 2; - if (d_bytecode) { - *lnotab++ = d_bytecode; - *lnotab++ = d_lineno; - } - else { /* First line of a block; def stmt, etc. */ - *lnotab++ = 0; - *lnotab++ = d_lineno; - } - a->a_lineno = i->i_lineno; - a->a_lineno_off = a->a_offset; - return 1; + int d_bytecode, d_lineno; + int len; + unsigned char *lnotab; + + d_bytecode = a->a_offset - a->a_lineno_off; + d_lineno = i->i_lineno - a->a_lineno; + + assert(d_bytecode >= 0); + assert(d_lineno >= 0); + + if(d_bytecode == 0 && d_lineno == 0) + return 1; + + if (d_bytecode > 255) { + int j, nbytes, ncodes = d_bytecode / 255; + nbytes = a->a_lnotab_off + 2 * ncodes; + len = PyBytes_GET_SIZE(a->a_lnotab); + if (nbytes >= len) { + if ((len <= INT_MAX / 2) && (len * 2 < nbytes)) + len = nbytes; + else if (len <= INT_MAX / 2) + len *= 2; + else { + PyErr_NoMemory(); + return 0; + } + if (_PyBytes_Resize(&a->a_lnotab, len) < 0) + return 0; + } + lnotab = (unsigned char *) + PyBytes_AS_STRING(a->a_lnotab) + a->a_lnotab_off; + for (j = 0; j < ncodes; j++) { + *lnotab++ = 255; + *lnotab++ = 0; + } + d_bytecode -= ncodes * 255; + a->a_lnotab_off += ncodes * 2; + } + assert(d_bytecode <= 255); + if (d_lineno > 255) { + int j, nbytes, ncodes = d_lineno / 255; + nbytes = a->a_lnotab_off + 2 * ncodes; + len = PyBytes_GET_SIZE(a->a_lnotab); + if (nbytes >= len) { + if ((len <= INT_MAX / 2) && len * 2 < nbytes) + len = nbytes; + else if (len <= INT_MAX / 2) + len *= 2; + else { + PyErr_NoMemory(); + return 0; + } + if (_PyBytes_Resize(&a->a_lnotab, len) < 0) + return 0; + } + lnotab = (unsigned char *) + PyBytes_AS_STRING(a->a_lnotab) + a->a_lnotab_off; + *lnotab++ = d_bytecode; + *lnotab++ = 255; + d_bytecode = 0; + for (j = 1; j < ncodes; j++) { + *lnotab++ = 0; + *lnotab++ = 255; + } + d_lineno -= ncodes * 255; + a->a_lnotab_off += ncodes * 2; + } + + len = PyBytes_GET_SIZE(a->a_lnotab); + if (a->a_lnotab_off + 2 >= len) { + if (_PyBytes_Resize(&a->a_lnotab, len * 2) < 0) + return 0; + } + lnotab = (unsigned char *) + PyBytes_AS_STRING(a->a_lnotab) + a->a_lnotab_off; + + a->a_lnotab_off += 2; + if (d_bytecode) { + *lnotab++ = d_bytecode; + *lnotab++ = d_lineno; + } + else { /* First line of a block; def stmt, etc. */ + *lnotab++ = 0; + *lnotab++ = d_lineno; + } + a->a_lineno = i->i_lineno; + a->a_lineno_off = a->a_offset; + return 1; } /* assemble_emit() @@ -3856,232 +3856,232 @@ static int assemble_emit(struct assembler *a, struct instr *i) { - int size, arg = 0, ext = 0; - Py_ssize_t len = PyBytes_GET_SIZE(a->a_bytecode); - char *code; - - size = instrsize(i); - if (i->i_hasarg) { - arg = i->i_oparg; - ext = arg >> 16; - } - if (i->i_lineno && !assemble_lnotab(a, i)) - return 0; - if (a->a_offset + size >= len) { - if (len > PY_SSIZE_T_MAX / 2) - return 0; - if (_PyBytes_Resize(&a->a_bytecode, len * 2) < 0) - return 0; - } - code = PyBytes_AS_STRING(a->a_bytecode) + a->a_offset; - a->a_offset += size; - if (size == 6) { - assert(i->i_hasarg); - *code++ = (char)EXTENDED_ARG; - *code++ = ext & 0xff; - *code++ = ext >> 8; - arg &= 0xffff; - } - *code++ = i->i_opcode; - if (i->i_hasarg) { - assert(size == 3 || size == 6); - *code++ = arg & 0xff; - *code++ = arg >> 8; - } - return 1; + int size, arg = 0, ext = 0; + Py_ssize_t len = PyBytes_GET_SIZE(a->a_bytecode); + char *code; + + size = instrsize(i); + if (i->i_hasarg) { + arg = i->i_oparg; + ext = arg >> 16; + } + if (i->i_lineno && !assemble_lnotab(a, i)) + return 0; + if (a->a_offset + size >= len) { + if (len > PY_SSIZE_T_MAX / 2) + return 0; + if (_PyBytes_Resize(&a->a_bytecode, len * 2) < 0) + return 0; + } + code = PyBytes_AS_STRING(a->a_bytecode) + a->a_offset; + a->a_offset += size; + if (size == 6) { + assert(i->i_hasarg); + *code++ = (char)EXTENDED_ARG; + *code++ = ext & 0xff; + *code++ = ext >> 8; + arg &= 0xffff; + } + *code++ = i->i_opcode; + if (i->i_hasarg) { + assert(size == 3 || size == 6); + *code++ = arg & 0xff; + *code++ = arg >> 8; + } + return 1; } static void assemble_jump_offsets(struct assembler *a, struct compiler *c) { - basicblock *b; - int bsize, totsize, extended_arg_count, last_extended_arg_count = 0; - int i; + basicblock *b; + int bsize, totsize, extended_arg_count, last_extended_arg_count = 0; + int i; - /* Compute the size of each block and fixup jump args. - Replace block pointer with position in bytecode. */ + /* Compute the size of each block and fixup jump args. + Replace block pointer with position in bytecode. */ start: - totsize = 0; - for (i = a->a_nblocks - 1; i >= 0; i--) { - b = a->a_postorder[i]; - bsize = blocksize(b); - b->b_offset = totsize; - totsize += bsize; - } - extended_arg_count = 0; - for (b = c->u->u_blocks; b != NULL; b = b->b_list) { - bsize = b->b_offset; - for (i = 0; i < b->b_iused; i++) { - struct instr *instr = &b->b_instr[i]; - /* Relative jumps are computed relative to - the instruction pointer after fetching - the jump instruction. - */ - bsize += instrsize(instr); - if (instr->i_jabs) - instr->i_oparg = instr->i_target->b_offset; - else if (instr->i_jrel) { - int delta = instr->i_target->b_offset - bsize; - instr->i_oparg = delta; - } - else - continue; - if (instr->i_oparg > 0xffff) - extended_arg_count++; - } - } - - /* XXX: This is an awful hack that could hurt performance, but - on the bright side it should work until we come up - with a better solution. - - In the meantime, should the goto be dropped in favor - of a loop? - - The issue is that in the first loop blocksize() is called - which calls instrsize() which requires i_oparg be set - appropriately. There is a bootstrap problem because - i_oparg is calculated in the second loop above. - - So we loop until we stop seeing new EXTENDED_ARGs. - The only EXTENDED_ARGs that could be popping up are - ones in jump instructions. So this should converge - fairly quickly. - */ - if (last_extended_arg_count != extended_arg_count) { - last_extended_arg_count = extended_arg_count; - goto start; - } + totsize = 0; + for (i = a->a_nblocks - 1; i >= 0; i--) { + b = a->a_postorder[i]; + bsize = blocksize(b); + b->b_offset = totsize; + totsize += bsize; + } + extended_arg_count = 0; + for (b = c->u->u_blocks; b != NULL; b = b->b_list) { + bsize = b->b_offset; + for (i = 0; i < b->b_iused; i++) { + struct instr *instr = &b->b_instr[i]; + /* Relative jumps are computed relative to + the instruction pointer after fetching + the jump instruction. + */ + bsize += instrsize(instr); + if (instr->i_jabs) + instr->i_oparg = instr->i_target->b_offset; + else if (instr->i_jrel) { + int delta = instr->i_target->b_offset - bsize; + instr->i_oparg = delta; + } + else + continue; + if (instr->i_oparg > 0xffff) + extended_arg_count++; + } + } + + /* XXX: This is an awful hack that could hurt performance, but + on the bright side it should work until we come up + with a better solution. + + In the meantime, should the goto be dropped in favor + of a loop? + + The issue is that in the first loop blocksize() is called + which calls instrsize() which requires i_oparg be set + appropriately. There is a bootstrap problem because + i_oparg is calculated in the second loop above. + + So we loop until we stop seeing new EXTENDED_ARGs. + The only EXTENDED_ARGs that could be popping up are + ones in jump instructions. So this should converge + fairly quickly. + */ + if (last_extended_arg_count != extended_arg_count) { + last_extended_arg_count = extended_arg_count; + goto start; + } } static PyObject * dict_keys_inorder(PyObject *dict, int offset) { - PyObject *tuple, *k, *v; - Py_ssize_t i, pos = 0, size = PyDict_Size(dict); + PyObject *tuple, *k, *v; + Py_ssize_t i, pos = 0, size = PyDict_Size(dict); - tuple = PyTuple_New(size); - if (tuple == NULL) - return NULL; - while (PyDict_Next(dict, &pos, &k, &v)) { - i = PyLong_AS_LONG(v); - /* The keys of the dictionary are tuples. (see compiler_add_o) - The object we want is always first, though. */ - k = PyTuple_GET_ITEM(k, 0); - Py_INCREF(k); - assert((i - offset) < size); - assert((i - offset) >= 0); - PyTuple_SET_ITEM(tuple, i - offset, k); - } - return tuple; + tuple = PyTuple_New(size); + if (tuple == NULL) + return NULL; + while (PyDict_Next(dict, &pos, &k, &v)) { + i = PyLong_AS_LONG(v); + /* The keys of the dictionary are tuples. (see compiler_add_o) + The object we want is always first, though. */ + k = PyTuple_GET_ITEM(k, 0); + Py_INCREF(k); + assert((i - offset) < size); + assert((i - offset) >= 0); + PyTuple_SET_ITEM(tuple, i - offset, k); + } + return tuple; } static int compute_code_flags(struct compiler *c) { - PySTEntryObject *ste = c->u->u_ste; - int flags = 0, n; - if (ste->ste_type != ModuleBlock) - flags |= CO_NEWLOCALS; - if (ste->ste_type == FunctionBlock) { - if (!ste->ste_unoptimized) - flags |= CO_OPTIMIZED; - if (ste->ste_nested) - flags |= CO_NESTED; - if (ste->ste_generator) - flags |= CO_GENERATOR; - if (ste->ste_varargs) - flags |= CO_VARARGS; - if (ste->ste_varkeywords) - flags |= CO_VARKEYWORDS; - } - - /* (Only) inherit compilerflags in PyCF_MASK */ - flags |= (c->c_flags->cf_flags & PyCF_MASK); - - n = PyDict_Size(c->u->u_freevars); - if (n < 0) - return -1; - if (n == 0) { - n = PyDict_Size(c->u->u_cellvars); - if (n < 0) - return -1; - if (n == 0) { - flags |= CO_NOFREE; - } - } + PySTEntryObject *ste = c->u->u_ste; + int flags = 0, n; + if (ste->ste_type != ModuleBlock) + flags |= CO_NEWLOCALS; + if (ste->ste_type == FunctionBlock) { + if (!ste->ste_unoptimized) + flags |= CO_OPTIMIZED; + if (ste->ste_nested) + flags |= CO_NESTED; + if (ste->ste_generator) + flags |= CO_GENERATOR; + if (ste->ste_varargs) + flags |= CO_VARARGS; + if (ste->ste_varkeywords) + flags |= CO_VARKEYWORDS; + } + + /* (Only) inherit compilerflags in PyCF_MASK */ + flags |= (c->c_flags->cf_flags & PyCF_MASK); + + n = PyDict_Size(c->u->u_freevars); + if (n < 0) + return -1; + if (n == 0) { + n = PyDict_Size(c->u->u_cellvars); + if (n < 0) + return -1; + if (n == 0) { + flags |= CO_NOFREE; + } + } - return flags; + return flags; } static PyCodeObject * makecode(struct compiler *c, struct assembler *a) { - PyObject *tmp; - PyCodeObject *co = NULL; - PyObject *consts = NULL; - PyObject *names = NULL; - PyObject *varnames = NULL; - PyObject *filename = NULL; - PyObject *name = NULL; - PyObject *freevars = NULL; - PyObject *cellvars = NULL; - PyObject *bytecode = NULL; - int nlocals, flags; - - tmp = dict_keys_inorder(c->u->u_consts, 0); - if (!tmp) - goto error; - consts = PySequence_List(tmp); /* optimize_code requires a list */ - Py_DECREF(tmp); - - names = dict_keys_inorder(c->u->u_names, 0); - varnames = dict_keys_inorder(c->u->u_varnames, 0); - if (!consts || !names || !varnames) - goto error; - - cellvars = dict_keys_inorder(c->u->u_cellvars, 0); - if (!cellvars) - goto error; - freevars = dict_keys_inorder(c->u->u_freevars, PyTuple_Size(cellvars)); - if (!freevars) - goto error; - filename = PyUnicode_DecodeFSDefault(c->c_filename); - if (!filename) - goto error; - - nlocals = PyDict_Size(c->u->u_varnames); - flags = compute_code_flags(c); - if (flags < 0) - goto error; - - bytecode = PyCode_Optimize(a->a_bytecode, consts, names, a->a_lnotab); - if (!bytecode) - goto error; - - tmp = PyList_AsTuple(consts); /* PyCode_New requires a tuple */ - if (!tmp) - goto error; - Py_DECREF(consts); - consts = tmp; - - co = PyCode_New(c->u->u_argcount, c->u->u_kwonlyargcount, - nlocals, stackdepth(c), flags, - bytecode, consts, names, varnames, - freevars, cellvars, - filename, c->u->u_name, - c->u->u_firstlineno, - a->a_lnotab); + PyObject *tmp; + PyCodeObject *co = NULL; + PyObject *consts = NULL; + PyObject *names = NULL; + PyObject *varnames = NULL; + PyObject *filename = NULL; + PyObject *name = NULL; + PyObject *freevars = NULL; + PyObject *cellvars = NULL; + PyObject *bytecode = NULL; + int nlocals, flags; + + tmp = dict_keys_inorder(c->u->u_consts, 0); + if (!tmp) + goto error; + consts = PySequence_List(tmp); /* optimize_code requires a list */ + Py_DECREF(tmp); + + names = dict_keys_inorder(c->u->u_names, 0); + varnames = dict_keys_inorder(c->u->u_varnames, 0); + if (!consts || !names || !varnames) + goto error; + + cellvars = dict_keys_inorder(c->u->u_cellvars, 0); + if (!cellvars) + goto error; + freevars = dict_keys_inorder(c->u->u_freevars, PyTuple_Size(cellvars)); + if (!freevars) + goto error; + filename = PyUnicode_DecodeFSDefault(c->c_filename); + if (!filename) + goto error; + + nlocals = PyDict_Size(c->u->u_varnames); + flags = compute_code_flags(c); + if (flags < 0) + goto error; + + bytecode = PyCode_Optimize(a->a_bytecode, consts, names, a->a_lnotab); + if (!bytecode) + goto error; + + tmp = PyList_AsTuple(consts); /* PyCode_New requires a tuple */ + if (!tmp) + goto error; + Py_DECREF(consts); + consts = tmp; + + co = PyCode_New(c->u->u_argcount, c->u->u_kwonlyargcount, + nlocals, stackdepth(c), flags, + bytecode, consts, names, varnames, + freevars, cellvars, + filename, c->u->u_name, + c->u->u_firstlineno, + a->a_lnotab); error: - Py_XDECREF(consts); - Py_XDECREF(names); - Py_XDECREF(varnames); - Py_XDECREF(filename); - Py_XDECREF(name); - Py_XDECREF(freevars); - Py_XDECREF(cellvars); - Py_XDECREF(bytecode); - return co; + Py_XDECREF(consts); + Py_XDECREF(names); + Py_XDECREF(varnames); + Py_XDECREF(filename); + Py_XDECREF(name); + Py_XDECREF(freevars); + Py_XDECREF(cellvars); + Py_XDECREF(bytecode); + return co; } @@ -4090,90 +4090,90 @@ static void dump_instr(const struct instr *i) { - const char *jrel = i->i_jrel ? "jrel " : ""; - const char *jabs = i->i_jabs ? "jabs " : ""; - char arg[128]; - - *arg = '\0'; - if (i->i_hasarg) - sprintf(arg, "arg: %d ", i->i_oparg); + const char *jrel = i->i_jrel ? "jrel " : ""; + const char *jabs = i->i_jabs ? "jabs " : ""; + char arg[128]; + + *arg = '\0'; + if (i->i_hasarg) + sprintf(arg, "arg: %d ", i->i_oparg); - fprintf(stderr, "line: %d, opcode: %d %s%s%s\n", - i->i_lineno, i->i_opcode, arg, jabs, jrel); + fprintf(stderr, "line: %d, opcode: %d %s%s%s\n", + i->i_lineno, i->i_opcode, arg, jabs, jrel); } static void dump_basicblock(const basicblock *b) { - const char *seen = b->b_seen ? "seen " : ""; - const char *b_return = b->b_return ? "return " : ""; - fprintf(stderr, "used: %d, depth: %d, offset: %d %s%s\n", - b->b_iused, b->b_startdepth, b->b_offset, seen, b_return); - if (b->b_instr) { - int i; - for (i = 0; i < b->b_iused; i++) { - fprintf(stderr, " [%02d] ", i); - dump_instr(b->b_instr + i); - } - } + const char *seen = b->b_seen ? "seen " : ""; + const char *b_return = b->b_return ? "return " : ""; + fprintf(stderr, "used: %d, depth: %d, offset: %d %s%s\n", + b->b_iused, b->b_startdepth, b->b_offset, seen, b_return); + if (b->b_instr) { + int i; + for (i = 0; i < b->b_iused; i++) { + fprintf(stderr, " [%02d] ", i); + dump_instr(b->b_instr + i); + } + } } #endif static PyCodeObject * assemble(struct compiler *c, int addNone) { - basicblock *b, *entryblock; - struct assembler a; - int i, j, nblocks; - PyCodeObject *co = NULL; - - /* Make sure every block that falls off the end returns None. - XXX NEXT_BLOCK() isn't quite right, because if the last - block ends with a jump or return b_next shouldn't set. - */ - if (!c->u->u_curblock->b_return) { - NEXT_BLOCK(c); - if (addNone) - ADDOP_O(c, LOAD_CONST, Py_None, consts); - ADDOP(c, RETURN_VALUE); - } - - nblocks = 0; - entryblock = NULL; - for (b = c->u->u_blocks; b != NULL; b = b->b_list) { - nblocks++; - entryblock = b; - } - - /* Set firstlineno if it wasn't explicitly set. */ - if (!c->u->u_firstlineno) { - if (entryblock && entryblock->b_instr) - c->u->u_firstlineno = entryblock->b_instr->i_lineno; - else - c->u->u_firstlineno = 1; - } - if (!assemble_init(&a, nblocks, c->u->u_firstlineno)) - goto error; - dfs(c, entryblock, &a); - - /* Can't modify the bytecode after computing jump offsets. */ - assemble_jump_offsets(&a, c); - - /* Emit code in reverse postorder from dfs. */ - for (i = a.a_nblocks - 1; i >= 0; i--) { - b = a.a_postorder[i]; - for (j = 0; j < b->b_iused; j++) - if (!assemble_emit(&a, &b->b_instr[j])) - goto error; - } - - if (_PyBytes_Resize(&a.a_lnotab, a.a_lnotab_off) < 0) - goto error; - if (_PyBytes_Resize(&a.a_bytecode, a.a_offset) < 0) - goto error; + basicblock *b, *entryblock; + struct assembler a; + int i, j, nblocks; + PyCodeObject *co = NULL; + + /* Make sure every block that falls off the end returns None. + XXX NEXT_BLOCK() isn't quite right, because if the last + block ends with a jump or return b_next shouldn't set. + */ + if (!c->u->u_curblock->b_return) { + NEXT_BLOCK(c); + if (addNone) + ADDOP_O(c, LOAD_CONST, Py_None, consts); + ADDOP(c, RETURN_VALUE); + } + + nblocks = 0; + entryblock = NULL; + for (b = c->u->u_blocks; b != NULL; b = b->b_list) { + nblocks++; + entryblock = b; + } + + /* Set firstlineno if it wasn't explicitly set. */ + if (!c->u->u_firstlineno) { + if (entryblock && entryblock->b_instr) + c->u->u_firstlineno = entryblock->b_instr->i_lineno; + else + c->u->u_firstlineno = 1; + } + if (!assemble_init(&a, nblocks, c->u->u_firstlineno)) + goto error; + dfs(c, entryblock, &a); + + /* Can't modify the bytecode after computing jump offsets. */ + assemble_jump_offsets(&a, c); + + /* Emit code in reverse postorder from dfs. */ + for (i = a.a_nblocks - 1; i >= 0; i--) { + b = a.a_postorder[i]; + for (j = 0; j < b->b_iused; j++) + if (!assemble_emit(&a, &b->b_instr[j])) + goto error; + } + + if (_PyBytes_Resize(&a.a_lnotab, a.a_lnotab_off) < 0) + goto error; + if (_PyBytes_Resize(&a.a_bytecode, a.a_offset) < 0) + goto error; - co = makecode(c, &a); + co = makecode(c, &a); error: - assemble_free(&a); - return co; + assemble_free(&a); + return co; } Modified: python/branches/release31-maint/Python/dynload_aix.c ============================================================================== --- python/branches/release31-maint/Python/dynload_aix.c (original) +++ python/branches/release31-maint/Python/dynload_aix.c Sun May 9 18:14:21 2010 @@ -4,10 +4,10 @@ #include "Python.h" #include "importdl.h" -#include /* for isdigit() */ -#include /* for global errno */ -#include /* for strerror() */ -#include /* for malloc(), free() */ +#include /* for isdigit() */ +#include /* for global errno */ +#include /* for strerror() */ +#include /* for malloc(), free() */ #include @@ -22,85 +22,85 @@ extern char *Py_GetProgramName(void); typedef struct Module { - struct Module *next; - void *entry; + struct Module *next; + void *entry; } Module, *ModulePtr; const struct filedescr _PyImport_DynLoadFiletab[] = { - {".so", "rb", C_EXTENSION}, - {"module.so", "rb", C_EXTENSION}, - {0, 0} + {".so", "rb", C_EXTENSION}, + {"module.so", "rb", C_EXTENSION}, + {0, 0} }; static int aix_getoldmodules(void **modlistptr) { - register ModulePtr modptr, prevmodptr; - register struct ld_info *ldiptr; - register char *ldibuf; - register int errflag, bufsize = 1024; - register unsigned int offset; - char *progname = Py_GetProgramName(); - - /* - -- Get the list of loaded modules into ld_info structures. - */ - if ((ldibuf = malloc(bufsize)) == NULL) { - PyErr_SetString(PyExc_ImportError, strerror(errno)); - return -1; - } - while ((errflag = loadquery(L_GETINFO, ldibuf, bufsize)) == -1 - && errno == ENOMEM) { - free(ldibuf); - bufsize += 1024; - if ((ldibuf = malloc(bufsize)) == NULL) { - PyErr_SetString(PyExc_ImportError, strerror(errno)); - return -1; - } - } - if (errflag == -1) { - PyErr_SetString(PyExc_ImportError, strerror(errno)); - return -1; - } - /* - -- Make the modules list from the ld_info structures. - */ - ldiptr = (struct ld_info *)ldibuf; - prevmodptr = NULL; - do { - if (strstr(progname, ldiptr->ldinfo_filename) == NULL && - strstr(ldiptr->ldinfo_filename, "python") == NULL) { - /* - -- Extract only the modules belonging to the main - -- executable + those containing "python" as a - -- substring (like the "python[version]" binary or - -- "libpython[version].a" in case it's a shared lib). - */ - offset = (unsigned int)ldiptr->ldinfo_next; - ldiptr = (struct ld_info *)((char*)ldiptr + offset); - continue; - } - if ((modptr = (ModulePtr)malloc(sizeof(Module))) == NULL) { - PyErr_SetString(PyExc_ImportError, strerror(errno)); - while (*modlistptr) { - modptr = (ModulePtr)*modlistptr; - *modlistptr = (void *)modptr->next; - free(modptr); - } - return -1; - } - modptr->entry = ldiptr->ldinfo_dataorg; - modptr->next = NULL; - if (prevmodptr == NULL) - *modlistptr = (void *)modptr; - else - prevmodptr->next = modptr; - prevmodptr = modptr; - offset = (unsigned int)ldiptr->ldinfo_next; - ldiptr = (struct ld_info *)((char*)ldiptr + offset); - } while (offset); - free(ldibuf); - return 0; + register ModulePtr modptr, prevmodptr; + register struct ld_info *ldiptr; + register char *ldibuf; + register int errflag, bufsize = 1024; + register unsigned int offset; + char *progname = Py_GetProgramName(); + + /* + -- Get the list of loaded modules into ld_info structures. + */ + if ((ldibuf = malloc(bufsize)) == NULL) { + PyErr_SetString(PyExc_ImportError, strerror(errno)); + return -1; + } + while ((errflag = loadquery(L_GETINFO, ldibuf, bufsize)) == -1 + && errno == ENOMEM) { + free(ldibuf); + bufsize += 1024; + if ((ldibuf = malloc(bufsize)) == NULL) { + PyErr_SetString(PyExc_ImportError, strerror(errno)); + return -1; + } + } + if (errflag == -1) { + PyErr_SetString(PyExc_ImportError, strerror(errno)); + return -1; + } + /* + -- Make the modules list from the ld_info structures. + */ + ldiptr = (struct ld_info *)ldibuf; + prevmodptr = NULL; + do { + if (strstr(progname, ldiptr->ldinfo_filename) == NULL && + strstr(ldiptr->ldinfo_filename, "python") == NULL) { + /* + -- Extract only the modules belonging to the main + -- executable + those containing "python" as a + -- substring (like the "python[version]" binary or + -- "libpython[version].a" in case it's a shared lib). + */ + offset = (unsigned int)ldiptr->ldinfo_next; + ldiptr = (struct ld_info *)((char*)ldiptr + offset); + continue; + } + if ((modptr = (ModulePtr)malloc(sizeof(Module))) == NULL) { + PyErr_SetString(PyExc_ImportError, strerror(errno)); + while (*modlistptr) { + modptr = (ModulePtr)*modlistptr; + *modlistptr = (void *)modptr->next; + free(modptr); + } + return -1; + } + modptr->entry = ldiptr->ldinfo_dataorg; + modptr->next = NULL; + if (prevmodptr == NULL) + *modlistptr = (void *)modptr; + else + prevmodptr->next = modptr; + prevmodptr = modptr; + offset = (unsigned int)ldiptr->ldinfo_next; + ldiptr = (struct ld_info *)((char*)ldiptr + offset); + } while (offset); + free(ldibuf); + return 0; } @@ -108,76 +108,76 @@ aix_loaderror(const char *pathname) { - char *message[1024], errbuf[1024]; - register int i,j; + char *message[1024], errbuf[1024]; + register int i,j; - struct errtab { - int errNo; - char *errstr; - } load_errtab[] = { - {L_ERROR_TOOMANY, "too many errors, rest skipped."}, - {L_ERROR_NOLIB, "can't load library:"}, - {L_ERROR_UNDEF, "can't find symbol in library:"}, - {L_ERROR_RLDBAD, - "RLD index out of range or bad relocation type:"}, - {L_ERROR_FORMAT, "not a valid, executable xcoff file:"}, - {L_ERROR_MEMBER, - "file not an archive or does not contain requested member:"}, - {L_ERROR_TYPE, "symbol table mismatch:"}, - {L_ERROR_ALIGN, "text alignment in file is wrong."}, - {L_ERROR_SYSTEM, "System error:"}, - {L_ERROR_ERRNO, NULL} - }; + struct errtab { + int errNo; + char *errstr; + } load_errtab[] = { + {L_ERROR_TOOMANY, "too many errors, rest skipped."}, + {L_ERROR_NOLIB, "can't load library:"}, + {L_ERROR_UNDEF, "can't find symbol in library:"}, + {L_ERROR_RLDBAD, + "RLD index out of range or bad relocation type:"}, + {L_ERROR_FORMAT, "not a valid, executable xcoff file:"}, + {L_ERROR_MEMBER, + "file not an archive or does not contain requested member:"}, + {L_ERROR_TYPE, "symbol table mismatch:"}, + {L_ERROR_ALIGN, "text alignment in file is wrong."}, + {L_ERROR_SYSTEM, "System error:"}, + {L_ERROR_ERRNO, NULL} + }; -#define LOAD_ERRTAB_LEN (sizeof(load_errtab)/sizeof(load_errtab[0])) +#define LOAD_ERRTAB_LEN (sizeof(load_errtab)/sizeof(load_errtab[0])) #define ERRBUF_APPEND(s) strncat(errbuf, s, sizeof(errbuf)-strlen(errbuf)-1) - PyOS_snprintf(errbuf, sizeof(errbuf), "from module %.200s ", pathname); + PyOS_snprintf(errbuf, sizeof(errbuf), "from module %.200s ", pathname); - if (!loadquery(L_GETMESSAGES, &message[0], sizeof(message))) { - ERRBUF_APPEND(strerror(errno)); - ERRBUF_APPEND("\n"); - } - for(i = 0; message[i] && *message[i]; i++) { - int nerr = atoi(message[i]); - for (j=0; j const struct filedescr _PyImport_DynLoadFiletab[] = { - {".so", "rb", C_EXTENSION}, - {"module.so", "rb", C_EXTENSION}, - {0, 0} + {".so", "rb", C_EXTENSION}, + {"module.so", "rb", C_EXTENSION}, + {0, 0} }; /* @@ -29,86 +29,86 @@ #define LINKOPTIONS NSLINKMODULE_OPTION_BINDNOW|NSLINKMODULE_OPTION_RETURN_ON_ERROR #else #define LINKOPTIONS NSLINKMODULE_OPTION_BINDNOW| \ - NSLINKMODULE_OPTION_RETURN_ON_ERROR|NSLINKMODULE_OPTION_PRIVATE + NSLINKMODULE_OPTION_RETURN_ON_ERROR|NSLINKMODULE_OPTION_PRIVATE #endif dl_funcptr _PyImport_GetDynLoadFunc(const char *fqname, const char *shortname, - const char *pathname, FILE *fp) + const char *pathname, FILE *fp) { - dl_funcptr p = NULL; - char funcname[258]; - NSObjectFileImageReturnCode rc; - NSObjectFileImage image; - NSModule newModule; - NSSymbol theSym; - const char *errString; - char errBuf[512]; + dl_funcptr p = NULL; + char funcname[258]; + NSObjectFileImageReturnCode rc; + NSObjectFileImage image; + NSModule newModule; + NSSymbol theSym; + const char *errString; + char errBuf[512]; - PyOS_snprintf(funcname, sizeof(funcname), "_PyInit_%.200s", shortname); + PyOS_snprintf(funcname, sizeof(funcname), "_PyInit_%.200s", shortname); #ifdef USE_DYLD_GLOBAL_NAMESPACE - if (NSIsSymbolNameDefined(funcname)) { - theSym = NSLookupAndBindSymbol(funcname); - p = (dl_funcptr)NSAddressOfSymbol(theSym); - return p; - } + if (NSIsSymbolNameDefined(funcname)) { + theSym = NSLookupAndBindSymbol(funcname); + p = (dl_funcptr)NSAddressOfSymbol(theSym); + return p; + } #endif - rc = NSCreateObjectFileImageFromFile(pathname, &image); - switch(rc) { - default: - case NSObjectFileImageFailure: - case NSObjectFileImageFormat: - /* for these a message is printed on stderr by dyld */ - errString = "Can't create object file image"; - break; - case NSObjectFileImageSuccess: - errString = NULL; - break; - case NSObjectFileImageInappropriateFile: - errString = "Inappropriate file type for dynamic loading"; - break; - case NSObjectFileImageArch: - errString = "Wrong CPU type in object file"; - break; - case NSObjectFileImageAccess: - errString = "Can't read object file (no access)"; - break; - } - if (errString == NULL) { - newModule = NSLinkModule(image, pathname, LINKOPTIONS); - if (newModule == NULL) { - int errNo; - const char *fileName, *moreErrorStr; - NSLinkEditErrors c; - NSLinkEditError( &c, &errNo, &fileName, &moreErrorStr ); - PyOS_snprintf(errBuf, 512, "Failure linking new module: %s: %s", - fileName, moreErrorStr); - errString = errBuf; - } - } - if (errString != NULL) { - PyErr_SetString(PyExc_ImportError, errString); - return NULL; - } + rc = NSCreateObjectFileImageFromFile(pathname, &image); + switch(rc) { + default: + case NSObjectFileImageFailure: + case NSObjectFileImageFormat: + /* for these a message is printed on stderr by dyld */ + errString = "Can't create object file image"; + break; + case NSObjectFileImageSuccess: + errString = NULL; + break; + case NSObjectFileImageInappropriateFile: + errString = "Inappropriate file type for dynamic loading"; + break; + case NSObjectFileImageArch: + errString = "Wrong CPU type in object file"; + break; + case NSObjectFileImageAccess: + errString = "Can't read object file (no access)"; + break; + } + if (errString == NULL) { + newModule = NSLinkModule(image, pathname, LINKOPTIONS); + if (newModule == NULL) { + int errNo; + const char *fileName, *moreErrorStr; + NSLinkEditErrors c; + NSLinkEditError( &c, &errNo, &fileName, &moreErrorStr ); + PyOS_snprintf(errBuf, 512, "Failure linking new module: %s: %s", + fileName, moreErrorStr); + errString = errBuf; + } + } + if (errString != NULL) { + PyErr_SetString(PyExc_ImportError, errString); + return NULL; + } #ifdef USE_DYLD_GLOBAL_NAMESPACE - if (!NSIsSymbolNameDefined(funcname)) { - /* UnlinkModule() isn't implemented in current versions, but calling it does no harm */ - /* NSUnLinkModule(newModule, FALSE); removed: causes problems for ObjC code */ - PyErr_Format(PyExc_ImportError, - "Loaded module does not contain symbol %.200s", - funcname); - return NULL; - } - theSym = NSLookupAndBindSymbol(funcname); + if (!NSIsSymbolNameDefined(funcname)) { + /* UnlinkModule() isn't implemented in current versions, but calling it does no harm */ + /* NSUnLinkModule(newModule, FALSE); removed: causes problems for ObjC code */ + PyErr_Format(PyExc_ImportError, + "Loaded module does not contain symbol %.200s", + funcname); + return NULL; + } + theSym = NSLookupAndBindSymbol(funcname); #else - theSym = NSLookupSymbolInModule(newModule, funcname); - if ( theSym == NULL ) { - /* NSUnLinkModule(newModule, FALSE); removed: causes problems for ObjC code */ - PyErr_Format(PyExc_ImportError, - "Loaded module does not contain symbol %.200s", - funcname); - return NULL; - } + theSym = NSLookupSymbolInModule(newModule, funcname); + if ( theSym == NULL ) { + /* NSUnLinkModule(newModule, FALSE); removed: causes problems for ObjC code */ + PyErr_Format(PyExc_ImportError, + "Loaded module does not contain symbol %.200s", + funcname); + return NULL; + } #endif - p = (dl_funcptr)NSAddressOfSymbol(theSym); - return p; + p = (dl_funcptr)NSAddressOfSymbol(theSym); + return p; } Modified: python/branches/release31-maint/Python/dynload_os2.c ============================================================================== --- python/branches/release31-maint/Python/dynload_os2.c (original) +++ python/branches/release31-maint/Python/dynload_os2.c Sun May 9 18:14:21 2010 @@ -10,37 +10,37 @@ const struct filedescr _PyImport_DynLoadFiletab[] = { - {".pyd", "rb", C_EXTENSION}, - {".dll", "rb", C_EXTENSION}, - {0, 0} + {".pyd", "rb", C_EXTENSION}, + {".dll", "rb", C_EXTENSION}, + {0, 0} }; dl_funcptr _PyImport_GetDynLoadFunc(const char *fqname, const char *shortname, - const char *pathname, FILE *fp) + const char *pathname, FILE *fp) { - dl_funcptr p; - APIRET rc; - HMODULE hDLL; - char failreason[256]; - char funcname[258]; - - rc = DosLoadModule(failreason, - sizeof(failreason), - pathname, - &hDLL); - - if (rc != NO_ERROR) { - char errBuf[256]; - PyOS_snprintf(errBuf, sizeof(errBuf), - "DLL load failed, rc = %d: %.200s", - rc, failreason); - PyErr_SetString(PyExc_ImportError, errBuf); - return NULL; - } - - PyOS_snprintf(funcname, sizeof(funcname), "PyInit_%.200s", shortname); - rc = DosQueryProcAddr(hDLL, 0L, funcname, &p); - if (rc != NO_ERROR) - p = NULL; /* Signify Failure to Acquire Entrypoint */ - return p; + dl_funcptr p; + APIRET rc; + HMODULE hDLL; + char failreason[256]; + char funcname[258]; + + rc = DosLoadModule(failreason, + sizeof(failreason), + pathname, + &hDLL); + + if (rc != NO_ERROR) { + char errBuf[256]; + PyOS_snprintf(errBuf, sizeof(errBuf), + "DLL load failed, rc = %d: %.200s", + rc, failreason); + PyErr_SetString(PyExc_ImportError, errBuf); + return NULL; + } + + PyOS_snprintf(funcname, sizeof(funcname), "PyInit_%.200s", shortname); + rc = DosQueryProcAddr(hDLL, 0L, funcname, &p); + if (rc != NO_ERROR) + p = NULL; /* Signify Failure to Acquire Entrypoint */ + return p; } Modified: python/branches/release31-maint/Python/dynload_shlib.c ============================================================================== --- python/branches/release31-maint/Python/dynload_shlib.c (original) +++ python/branches/release31-maint/Python/dynload_shlib.c Sun May 9 18:14:21 2010 @@ -33,111 +33,111 @@ const struct filedescr _PyImport_DynLoadFiletab[] = { #ifdef __CYGWIN__ - {".dll", "rb", C_EXTENSION}, - {"module.dll", "rb", C_EXTENSION}, + {".dll", "rb", C_EXTENSION}, + {"module.dll", "rb", C_EXTENSION}, #else #if defined(PYOS_OS2) && defined(PYCC_GCC) - {".pyd", "rb", C_EXTENSION}, - {".dll", "rb", C_EXTENSION}, + {".pyd", "rb", C_EXTENSION}, + {".dll", "rb", C_EXTENSION}, #else #ifdef __VMS - {".exe", "rb", C_EXTENSION}, - {".EXE", "rb", C_EXTENSION}, - {"module.exe", "rb", C_EXTENSION}, - {"MODULE.EXE", "rb", C_EXTENSION}, + {".exe", "rb", C_EXTENSION}, + {".EXE", "rb", C_EXTENSION}, + {"module.exe", "rb", C_EXTENSION}, + {"MODULE.EXE", "rb", C_EXTENSION}, #else - {".so", "rb", C_EXTENSION}, - {"module.so", "rb", C_EXTENSION}, + {".so", "rb", C_EXTENSION}, + {"module.so", "rb", C_EXTENSION}, #endif #endif #endif - {0, 0} + {0, 0} }; static struct { - dev_t dev; + dev_t dev; #ifdef __VMS - ino_t ino[3]; + ino_t ino[3]; #else - ino_t ino; + ino_t ino; #endif - void *handle; + void *handle; } handles[128]; static int nhandles = 0; dl_funcptr _PyImport_GetDynLoadFunc(const char *fqname, const char *shortname, - const char *pathname, FILE *fp) + const char *pathname, FILE *fp) { - dl_funcptr p; - void *handle; - char funcname[258]; - char pathbuf[260]; - int dlopenflags=0; - - if (strchr(pathname, '/') == NULL) { - /* Prefix bare filename with "./" */ - PyOS_snprintf(pathbuf, sizeof(pathbuf), "./%-.255s", pathname); - pathname = pathbuf; - } - - PyOS_snprintf(funcname, sizeof(funcname), - LEAD_UNDERSCORE "PyInit_%.200s", shortname); - - if (fp != NULL) { - int i; - struct stat statb; - fstat(fileno(fp), &statb); - for (i = 0; i < nhandles; i++) { - if (statb.st_dev == handles[i].dev && - statb.st_ino == handles[i].ino) { - p = (dl_funcptr) dlsym(handles[i].handle, - funcname); - return p; - } - } - if (nhandles < 128) { - handles[nhandles].dev = statb.st_dev; + dl_funcptr p; + void *handle; + char funcname[258]; + char pathbuf[260]; + int dlopenflags=0; + + if (strchr(pathname, '/') == NULL) { + /* Prefix bare filename with "./" */ + PyOS_snprintf(pathbuf, sizeof(pathbuf), "./%-.255s", pathname); + pathname = pathbuf; + } + + PyOS_snprintf(funcname, sizeof(funcname), + LEAD_UNDERSCORE "PyInit_%.200s", shortname); + + if (fp != NULL) { + int i; + struct stat statb; + fstat(fileno(fp), &statb); + for (i = 0; i < nhandles; i++) { + if (statb.st_dev == handles[i].dev && + statb.st_ino == handles[i].ino) { + p = (dl_funcptr) dlsym(handles[i].handle, + funcname); + return p; + } + } + if (nhandles < 128) { + handles[nhandles].dev = statb.st_dev; #ifdef __VMS - handles[nhandles].ino[0] = statb.st_ino[0]; - handles[nhandles].ino[1] = statb.st_ino[1]; - handles[nhandles].ino[2] = statb.st_ino[2]; + handles[nhandles].ino[0] = statb.st_ino[0]; + handles[nhandles].ino[1] = statb.st_ino[1]; + handles[nhandles].ino[2] = statb.st_ino[2]; #else - handles[nhandles].ino = statb.st_ino; + handles[nhandles].ino = statb.st_ino; #endif - } - } + } + } #if !(defined(PYOS_OS2) && defined(PYCC_GCC)) - dlopenflags = PyThreadState_GET()->interp->dlopenflags; + dlopenflags = PyThreadState_GET()->interp->dlopenflags; #endif - if (Py_VerboseFlag) - PySys_WriteStderr("dlopen(\"%s\", %x);\n", pathname, - dlopenflags); + if (Py_VerboseFlag) + PySys_WriteStderr("dlopen(\"%s\", %x);\n", pathname, + dlopenflags); #ifdef __VMS - /* VMS currently don't allow a pathname, use a logical name instead */ - /* Concatenate 'python_module_' and shortname */ - /* so "import vms.bar" will use the logical python_module_bar */ - /* As C module use only one name space this is probably not a */ - /* important limitation */ - PyOS_snprintf(pathbuf, sizeof(pathbuf), "python_module_%-.200s", - shortname); - pathname = pathbuf; -#endif - - handle = dlopen(pathname, dlopenflags); - - if (handle == NULL) { - const char *error = dlerror(); - if (error == NULL) - error = "unknown dlopen() error"; - PyErr_SetString(PyExc_ImportError, error); - return NULL; - } - if (fp != NULL && nhandles < 128) - handles[nhandles++].handle = handle; - p = (dl_funcptr) dlsym(handle, funcname); - return p; + /* VMS currently don't allow a pathname, use a logical name instead */ + /* Concatenate 'python_module_' and shortname */ + /* so "import vms.bar" will use the logical python_module_bar */ + /* As C module use only one name space this is probably not a */ + /* important limitation */ + PyOS_snprintf(pathbuf, sizeof(pathbuf), "python_module_%-.200s", + shortname); + pathname = pathbuf; +#endif + + handle = dlopen(pathname, dlopenflags); + + if (handle == NULL) { + const char *error = dlerror(); + if (error == NULL) + error = "unknown dlopen() error"; + PyErr_SetString(PyExc_ImportError, error); + return NULL; + } + if (fp != NULL && nhandles < 128) + handles[nhandles++].handle = handle; + p = (dl_funcptr) dlsym(handle, funcname); + return p; } Modified: python/branches/release31-maint/Python/dynload_win.c ============================================================================== --- python/branches/release31-maint/Python/dynload_win.c (original) +++ python/branches/release31-maint/Python/dynload_win.c Sun May 9 18:14:21 2010 @@ -17,11 +17,11 @@ const struct filedescr _PyImport_DynLoadFiletab[] = { #ifdef _DEBUG - {"_d.pyd", "rb", C_EXTENSION}, + {"_d.pyd", "rb", C_EXTENSION}, #else - {".pyd", "rb", C_EXTENSION}, + {".pyd", "rb", C_EXTENSION}, #endif - {0, 0} + {0, 0} }; @@ -29,18 +29,18 @@ C RTL implementations */ static int strcasecmp (char *string1, char *string2) -{ - int first, second; +{ + int first, second; - do { - first = tolower(*string1); - second = tolower(*string2); - string1++; - string2++; - } while (first && first == second); + do { + first = tolower(*string1); + second = tolower(*string2); + string1++; + string2++; + } while (first && first == second); - return (first - second); -} + return (first - second); +} /* Function to return the name of the "python" DLL that the supplied module @@ -66,213 +66,213 @@ static char *GetPythonImport (HINSTANCE hModule) { - unsigned char *dllbase, *import_data, *import_name; - DWORD pe_offset, opt_offset; - WORD opt_magic; - int num_dict_off, import_off; - - /* Safety check input */ - if (hModule == NULL) { - return NULL; - } - - /* Module instance is also the base load address. First portion of - memory is the MS-DOS loader, which holds the offset to the PE - header (from the load base) at 0x3C */ - dllbase = (unsigned char *)hModule; - pe_offset = DWORD_AT(dllbase + 0x3C); - - /* The PE signature must be "PE\0\0" */ - if (memcmp(dllbase+pe_offset,"PE\0\0",4)) { - return NULL; - } - - /* Following the PE signature is the standard COFF header (20 - bytes) and then the optional header. The optional header starts - with a magic value of 0x10B for PE32 or 0x20B for PE32+ (PE32+ - uses 64-bits for some fields). It might also be 0x107 for a ROM - image, but we don't process that here. - - The optional header ends with a data dictionary that directly - points to certain types of data, among them the import entries - (in the second table entry). Based on the header type, we - determine offsets for the data dictionary count and the entry - within the dictionary pointing to the imports. */ - - opt_offset = pe_offset + 4 + 20; - opt_magic = WORD_AT(dllbase+opt_offset); - if (opt_magic == 0x10B) { - /* PE32 */ - num_dict_off = 92; - import_off = 104; - } else if (opt_magic == 0x20B) { - /* PE32+ */ - num_dict_off = 108; - import_off = 120; - } else { - /* Unsupported */ - return NULL; - } - - /* Now if an import table exists, offset to it and walk the list of - imports. The import table is an array (ending when an entry has - empty values) of structures (20 bytes each), which contains (at - offset 12) a relative address (to the module base) at which a - string constant holding the import name is located. */ - - if (DWORD_AT(dllbase + opt_offset + num_dict_off) >= 2) { - /* We have at least 2 tables - the import table is the second - one. But still it may be that the table size is zero */ - if (0 == DWORD_AT(dllbase + opt_offset + import_off + sizeof(DWORD))) - return NULL; - import_data = dllbase + DWORD_AT(dllbase + - opt_offset + - import_off); - while (DWORD_AT(import_data)) { - import_name = dllbase + DWORD_AT(import_data+12); - if (strlen(import_name) >= 6 && - !strncmp(import_name,"python",6)) { - char *pch; - - /* Ensure python prefix is followed only - by numbers to the end of the basename */ - pch = import_name + 6; + unsigned char *dllbase, *import_data, *import_name; + DWORD pe_offset, opt_offset; + WORD opt_magic; + int num_dict_off, import_off; + + /* Safety check input */ + if (hModule == NULL) { + return NULL; + } + + /* Module instance is also the base load address. First portion of + memory is the MS-DOS loader, which holds the offset to the PE + header (from the load base) at 0x3C */ + dllbase = (unsigned char *)hModule; + pe_offset = DWORD_AT(dllbase + 0x3C); + + /* The PE signature must be "PE\0\0" */ + if (memcmp(dllbase+pe_offset,"PE\0\0",4)) { + return NULL; + } + + /* Following the PE signature is the standard COFF header (20 + bytes) and then the optional header. The optional header starts + with a magic value of 0x10B for PE32 or 0x20B for PE32+ (PE32+ + uses 64-bits for some fields). It might also be 0x107 for a ROM + image, but we don't process that here. + + The optional header ends with a data dictionary that directly + points to certain types of data, among them the import entries + (in the second table entry). Based on the header type, we + determine offsets for the data dictionary count and the entry + within the dictionary pointing to the imports. */ + + opt_offset = pe_offset + 4 + 20; + opt_magic = WORD_AT(dllbase+opt_offset); + if (opt_magic == 0x10B) { + /* PE32 */ + num_dict_off = 92; + import_off = 104; + } else if (opt_magic == 0x20B) { + /* PE32+ */ + num_dict_off = 108; + import_off = 120; + } else { + /* Unsupported */ + return NULL; + } + + /* Now if an import table exists, offset to it and walk the list of + imports. The import table is an array (ending when an entry has + empty values) of structures (20 bytes each), which contains (at + offset 12) a relative address (to the module base) at which a + string constant holding the import name is located. */ + + if (DWORD_AT(dllbase + opt_offset + num_dict_off) >= 2) { + /* We have at least 2 tables - the import table is the second + one. But still it may be that the table size is zero */ + if (0 == DWORD_AT(dllbase + opt_offset + import_off + sizeof(DWORD))) + return NULL; + import_data = dllbase + DWORD_AT(dllbase + + opt_offset + + import_off); + while (DWORD_AT(import_data)) { + import_name = dllbase + DWORD_AT(import_data+12); + if (strlen(import_name) >= 6 && + !strncmp(import_name,"python",6)) { + char *pch; + + /* Ensure python prefix is followed only + by numbers to the end of the basename */ + pch = import_name + 6; #ifdef _DEBUG - while (*pch && pch[0] != '_' && pch[1] != 'd' && pch[2] != '.') { + while (*pch && pch[0] != '_' && pch[1] != 'd' && pch[2] != '.') { #else - while (*pch && *pch != '.') { + while (*pch && *pch != '.') { #endif - if (*pch >= '0' && *pch <= '9') { - pch++; - } else { - pch = NULL; - break; - } - } - - if (pch) { - /* Found it - return the name */ - return import_name; - } - } - import_data += 20; - } - } + if (*pch >= '0' && *pch <= '9') { + pch++; + } else { + pch = NULL; + break; + } + } + + if (pch) { + /* Found it - return the name */ + return import_name; + } + } + import_data += 20; + } + } - return NULL; + return NULL; } dl_funcptr _PyImport_GetDynLoadFunc(const char *fqname, const char *shortname, - const char *pathname, FILE *fp) + const char *pathname, FILE *fp) { - dl_funcptr p; - char funcname[258], *import_python; + dl_funcptr p; + char funcname[258], *import_python; - PyOS_snprintf(funcname, sizeof(funcname), "PyInit_%.200s", shortname); + PyOS_snprintf(funcname, sizeof(funcname), "PyInit_%.200s", shortname); - { - HINSTANCE hDLL = NULL; - char pathbuf[260]; - LPTSTR dummy; - unsigned int old_mode; - ULONG_PTR cookie = 0; - /* We use LoadLibraryEx so Windows looks for dependent DLLs - in directory of pathname first. However, Windows95 - can sometimes not work correctly unless the absolute - path is used. If GetFullPathName() fails, the LoadLibrary - will certainly fail too, so use its error code */ - - /* Don't display a message box when Python can't load a DLL */ - old_mode = SetErrorMode(SEM_FAILCRITICALERRORS); - - if (GetFullPathName(pathname, - sizeof(pathbuf), - pathbuf, - &dummy)) { - ULONG_PTR cookie = _Py_ActivateActCtx(); - /* XXX This call doesn't exist in Windows CE */ - hDLL = LoadLibraryEx(pathname, NULL, - LOAD_WITH_ALTERED_SEARCH_PATH); - _Py_DeactivateActCtx(cookie); - } - - /* restore old error mode settings */ - SetErrorMode(old_mode); - - if (hDLL==NULL){ - PyObject *message; - unsigned int errorCode; - - /* Get an error string from Win32 error code */ - wchar_t theInfo[256]; /* Pointer to error text - from system */ - int theLength; /* Length of error text */ - - errorCode = GetLastError(); - - theLength = FormatMessageW( - FORMAT_MESSAGE_FROM_SYSTEM | - FORMAT_MESSAGE_IGNORE_INSERTS, /* flags */ - NULL, /* message source */ - errorCode, /* the message (error) ID */ - MAKELANGID(LANG_NEUTRAL, - SUBLANG_DEFAULT), - /* Default language */ - theInfo, /* the buffer */ - sizeof(theInfo), /* the buffer size */ - NULL); /* no additional format args. */ - - /* Problem: could not get the error message. - This should not happen if called correctly. */ - if (theLength == 0) { - message = PyUnicode_FromFormat( - "DLL load failed with error code %d", - errorCode); - } else { - /* For some reason a \r\n - is appended to the text */ - if (theLength >= 2 && - theInfo[theLength-2] == '\r' && - theInfo[theLength-1] == '\n') { - theLength -= 2; - theInfo[theLength] = '\0'; - } - message = PyUnicode_FromString( - "DLL load failed: "); - - PyUnicode_AppendAndDel(&message, - PyUnicode_FromUnicode( - theInfo, - theLength)); - } - PyErr_SetObject(PyExc_ImportError, message); - Py_XDECREF(message); - return NULL; - } else { - char buffer[256]; + { + HINSTANCE hDLL = NULL; + char pathbuf[260]; + LPTSTR dummy; + unsigned int old_mode; + ULONG_PTR cookie = 0; + /* We use LoadLibraryEx so Windows looks for dependent DLLs + in directory of pathname first. However, Windows95 + can sometimes not work correctly unless the absolute + path is used. If GetFullPathName() fails, the LoadLibrary + will certainly fail too, so use its error code */ + + /* Don't display a message box when Python can't load a DLL */ + old_mode = SetErrorMode(SEM_FAILCRITICALERRORS); + + if (GetFullPathName(pathname, + sizeof(pathbuf), + pathbuf, + &dummy)) { + ULONG_PTR cookie = _Py_ActivateActCtx(); + /* XXX This call doesn't exist in Windows CE */ + hDLL = LoadLibraryEx(pathname, NULL, + LOAD_WITH_ALTERED_SEARCH_PATH); + _Py_DeactivateActCtx(cookie); + } + + /* restore old error mode settings */ + SetErrorMode(old_mode); + + if (hDLL==NULL){ + PyObject *message; + unsigned int errorCode; + + /* Get an error string from Win32 error code */ + wchar_t theInfo[256]; /* Pointer to error text + from system */ + int theLength; /* Length of error text */ + + errorCode = GetLastError(); + + theLength = FormatMessageW( + FORMAT_MESSAGE_FROM_SYSTEM | + FORMAT_MESSAGE_IGNORE_INSERTS, /* flags */ + NULL, /* message source */ + errorCode, /* the message (error) ID */ + MAKELANGID(LANG_NEUTRAL, + SUBLANG_DEFAULT), + /* Default language */ + theInfo, /* the buffer */ + sizeof(theInfo), /* the buffer size */ + NULL); /* no additional format args. */ + + /* Problem: could not get the error message. + This should not happen if called correctly. */ + if (theLength == 0) { + message = PyUnicode_FromFormat( + "DLL load failed with error code %d", + errorCode); + } else { + /* For some reason a \r\n + is appended to the text */ + if (theLength >= 2 && + theInfo[theLength-2] == '\r' && + theInfo[theLength-1] == '\n') { + theLength -= 2; + theInfo[theLength] = '\0'; + } + message = PyUnicode_FromString( + "DLL load failed: "); + + PyUnicode_AppendAndDel(&message, + PyUnicode_FromUnicode( + theInfo, + theLength)); + } + PyErr_SetObject(PyExc_ImportError, message); + Py_XDECREF(message); + return NULL; + } else { + char buffer[256]; #ifdef _DEBUG - PyOS_snprintf(buffer, sizeof(buffer), "python%d%d_d.dll", + PyOS_snprintf(buffer, sizeof(buffer), "python%d%d_d.dll", #else - PyOS_snprintf(buffer, sizeof(buffer), "python%d%d.dll", + PyOS_snprintf(buffer, sizeof(buffer), "python%d%d.dll", #endif - PY_MAJOR_VERSION,PY_MINOR_VERSION); - import_python = GetPythonImport(hDLL); + PY_MAJOR_VERSION,PY_MINOR_VERSION); + import_python = GetPythonImport(hDLL); - if (import_python && - strcasecmp(buffer,import_python)) { - PyOS_snprintf(buffer, sizeof(buffer), - "Module use of %.150s conflicts " - "with this version of Python.", - import_python); - PyErr_SetString(PyExc_ImportError,buffer); - FreeLibrary(hDLL); - return NULL; - } - } - p = GetProcAddress(hDLL, funcname); - } + if (import_python && + strcasecmp(buffer,import_python)) { + PyOS_snprintf(buffer, sizeof(buffer), + "Module use of %.150s conflicts " + "with this version of Python.", + import_python); + PyErr_SetString(PyExc_ImportError,buffer); + FreeLibrary(hDLL); + return NULL; + } + } + p = GetProcAddress(hDLL, funcname); + } - return p; + return p; } Modified: python/branches/release31-maint/Python/errors.c ============================================================================== --- python/branches/release31-maint/Python/errors.c (original) +++ python/branches/release31-maint/Python/errors.c Sun May 9 18:14:21 2010 @@ -24,166 +24,166 @@ void PyErr_Restore(PyObject *type, PyObject *value, PyObject *traceback) { - PyThreadState *tstate = PyThreadState_GET(); - PyObject *oldtype, *oldvalue, *oldtraceback; + PyThreadState *tstate = PyThreadState_GET(); + PyObject *oldtype, *oldvalue, *oldtraceback; - if (traceback != NULL && !PyTraceBack_Check(traceback)) { - /* XXX Should never happen -- fatal error instead? */ - /* Well, it could be None. */ - Py_DECREF(traceback); - traceback = NULL; - } - - /* Save these in locals to safeguard against recursive - invocation through Py_XDECREF */ - oldtype = tstate->curexc_type; - oldvalue = tstate->curexc_value; - oldtraceback = tstate->curexc_traceback; - - tstate->curexc_type = type; - tstate->curexc_value = value; - tstate->curexc_traceback = traceback; - - Py_XDECREF(oldtype); - Py_XDECREF(oldvalue); - Py_XDECREF(oldtraceback); + if (traceback != NULL && !PyTraceBack_Check(traceback)) { + /* XXX Should never happen -- fatal error instead? */ + /* Well, it could be None. */ + Py_DECREF(traceback); + traceback = NULL; + } + + /* Save these in locals to safeguard against recursive + invocation through Py_XDECREF */ + oldtype = tstate->curexc_type; + oldvalue = tstate->curexc_value; + oldtraceback = tstate->curexc_traceback; + + tstate->curexc_type = type; + tstate->curexc_value = value; + tstate->curexc_traceback = traceback; + + Py_XDECREF(oldtype); + Py_XDECREF(oldvalue); + Py_XDECREF(oldtraceback); } void PyErr_SetObject(PyObject *exception, PyObject *value) { - PyThreadState *tstate = PyThreadState_GET(); - PyObject *exc_value; - PyObject *tb = NULL; - - if (exception != NULL && - !PyExceptionClass_Check(exception)) { - PyErr_Format(PyExc_SystemError, - "exception %R not a BaseException subclass", - exception); - return; - } - Py_XINCREF(value); - exc_value = tstate->exc_value; - if (exc_value != NULL && exc_value != Py_None) { - /* Implicit exception chaining */ - Py_INCREF(exc_value); - if (value == NULL || !PyExceptionInstance_Check(value)) { - /* We must normalize the value right now */ - PyObject *args, *fixed_value; - if (value == NULL || value == Py_None) - args = PyTuple_New(0); - else if (PyTuple_Check(value)) { - Py_INCREF(value); - args = value; - } - else - args = PyTuple_Pack(1, value); - fixed_value = args ? - PyEval_CallObject(exception, args) : NULL; - Py_XDECREF(args); - Py_XDECREF(value); - if (fixed_value == NULL) - return; - value = fixed_value; - } - /* Avoid reference cycles through the context chain. - This is O(chain length) but context chains are - usually very short. Sensitive readers may try - to inline the call to PyException_GetContext. */ - if (exc_value != value) { - PyObject *o = exc_value, *context; - while ((context = PyException_GetContext(o))) { - Py_DECREF(context); - if (context == value) { - PyException_SetContext(o, NULL); - break; - } - o = context; - } - PyException_SetContext(value, exc_value); - } else { - Py_DECREF(exc_value); - } - } - if (value != NULL && PyExceptionInstance_Check(value)) - tb = PyException_GetTraceback(value); - Py_XINCREF(exception); - PyErr_Restore(exception, value, tb); + PyThreadState *tstate = PyThreadState_GET(); + PyObject *exc_value; + PyObject *tb = NULL; + + if (exception != NULL && + !PyExceptionClass_Check(exception)) { + PyErr_Format(PyExc_SystemError, + "exception %R not a BaseException subclass", + exception); + return; + } + Py_XINCREF(value); + exc_value = tstate->exc_value; + if (exc_value != NULL && exc_value != Py_None) { + /* Implicit exception chaining */ + Py_INCREF(exc_value); + if (value == NULL || !PyExceptionInstance_Check(value)) { + /* We must normalize the value right now */ + PyObject *args, *fixed_value; + if (value == NULL || value == Py_None) + args = PyTuple_New(0); + else if (PyTuple_Check(value)) { + Py_INCREF(value); + args = value; + } + else + args = PyTuple_Pack(1, value); + fixed_value = args ? + PyEval_CallObject(exception, args) : NULL; + Py_XDECREF(args); + Py_XDECREF(value); + if (fixed_value == NULL) + return; + value = fixed_value; + } + /* Avoid reference cycles through the context chain. + This is O(chain length) but context chains are + usually very short. Sensitive readers may try + to inline the call to PyException_GetContext. */ + if (exc_value != value) { + PyObject *o = exc_value, *context; + while ((context = PyException_GetContext(o))) { + Py_DECREF(context); + if (context == value) { + PyException_SetContext(o, NULL); + break; + } + o = context; + } + PyException_SetContext(value, exc_value); + } else { + Py_DECREF(exc_value); + } + } + if (value != NULL && PyExceptionInstance_Check(value)) + tb = PyException_GetTraceback(value); + Py_XINCREF(exception); + PyErr_Restore(exception, value, tb); } void PyErr_SetNone(PyObject *exception) { - PyErr_SetObject(exception, (PyObject *)NULL); + PyErr_SetObject(exception, (PyObject *)NULL); } void PyErr_SetString(PyObject *exception, const char *string) { - PyObject *value = PyUnicode_FromString(string); - PyErr_SetObject(exception, value); - Py_XDECREF(value); + PyObject *value = PyUnicode_FromString(string); + PyErr_SetObject(exception, value); + Py_XDECREF(value); } PyObject * PyErr_Occurred(void) { - PyThreadState *tstate = PyThreadState_GET(); + PyThreadState *tstate = PyThreadState_GET(); - return tstate->curexc_type; + return tstate->curexc_type; } int PyErr_GivenExceptionMatches(PyObject *err, PyObject *exc) { - if (err == NULL || exc == NULL) { - /* maybe caused by "import exceptions" that failed early on */ - return 0; - } - if (PyTuple_Check(exc)) { - Py_ssize_t i, n; - n = PyTuple_Size(exc); - for (i = 0; i < n; i++) { - /* Test recursively */ - if (PyErr_GivenExceptionMatches( - err, PyTuple_GET_ITEM(exc, i))) - { - return 1; - } - } - return 0; - } - /* err might be an instance, so check its class. */ - if (PyExceptionInstance_Check(err)) - err = PyExceptionInstance_Class(err); - - if (PyExceptionClass_Check(err) && PyExceptionClass_Check(exc)) { - int res = 0; - PyObject *exception, *value, *tb; - PyErr_Fetch(&exception, &value, &tb); - /* PyObject_IsSubclass() can recurse and therefore is - not safe (see test_bad_getattr in test.pickletester). */ - res = PyType_IsSubtype((PyTypeObject *)err, (PyTypeObject *)exc); - /* This function must not fail, so print the error here */ - if (res == -1) { - PyErr_WriteUnraisable(err); - res = 0; - } - PyErr_Restore(exception, value, tb); - return res; - } + if (err == NULL || exc == NULL) { + /* maybe caused by "import exceptions" that failed early on */ + return 0; + } + if (PyTuple_Check(exc)) { + Py_ssize_t i, n; + n = PyTuple_Size(exc); + for (i = 0; i < n; i++) { + /* Test recursively */ + if (PyErr_GivenExceptionMatches( + err, PyTuple_GET_ITEM(exc, i))) + { + return 1; + } + } + return 0; + } + /* err might be an instance, so check its class. */ + if (PyExceptionInstance_Check(err)) + err = PyExceptionInstance_Class(err); + + if (PyExceptionClass_Check(err) && PyExceptionClass_Check(exc)) { + int res = 0; + PyObject *exception, *value, *tb; + PyErr_Fetch(&exception, &value, &tb); + /* PyObject_IsSubclass() can recurse and therefore is + not safe (see test_bad_getattr in test.pickletester). */ + res = PyType_IsSubtype((PyTypeObject *)err, (PyTypeObject *)exc); + /* This function must not fail, so print the error here */ + if (res == -1) { + PyErr_WriteUnraisable(err); + res = 0; + } + PyErr_Restore(exception, value, tb); + return res; + } - return err == exc; + return err == exc; } int PyErr_ExceptionMatches(PyObject *exc) { - return PyErr_GivenExceptionMatches(PyErr_Occurred(), exc); + return PyErr_GivenExceptionMatches(PyErr_Occurred(), exc); } @@ -191,128 +191,128 @@ eval_code2(), do_raise(), and PyErr_Print() XXX: should PyErr_NormalizeException() also call - PyException_SetTraceback() with the resulting value and tb? + PyException_SetTraceback() with the resulting value and tb? */ void PyErr_NormalizeException(PyObject **exc, PyObject **val, PyObject **tb) { - PyObject *type = *exc; - PyObject *value = *val; - PyObject *inclass = NULL; - PyObject *initial_tb = NULL; - PyThreadState *tstate = NULL; - - if (type == NULL) { - /* There was no exception, so nothing to do. */ - return; - } - - /* If PyErr_SetNone() was used, the value will have been actually - set to NULL. - */ - if (!value) { - value = Py_None; - Py_INCREF(value); - } - - if (PyExceptionInstance_Check(value)) - inclass = PyExceptionInstance_Class(value); - - /* Normalize the exception so that if the type is a class, the - value will be an instance. - */ - if (PyExceptionClass_Check(type)) { - /* if the value was not an instance, or is not an instance - whose class is (or is derived from) type, then use the - value as an argument to instantiation of the type - class. - */ - if (!inclass || !PyObject_IsSubclass(inclass, type)) { - PyObject *args, *res; - - if (value == Py_None) - args = PyTuple_New(0); - else if (PyTuple_Check(value)) { - Py_INCREF(value); - args = value; - } - else - args = PyTuple_Pack(1, value); - - if (args == NULL) - goto finally; - res = PyEval_CallObject(type, args); - Py_DECREF(args); - if (res == NULL) - goto finally; - Py_DECREF(value); - value = res; - } - /* if the class of the instance doesn't exactly match the - class of the type, believe the instance - */ - else if (inclass != type) { - Py_DECREF(type); - type = inclass; - Py_INCREF(type); - } - } - *exc = type; - *val = value; - return; + PyObject *type = *exc; + PyObject *value = *val; + PyObject *inclass = NULL; + PyObject *initial_tb = NULL; + PyThreadState *tstate = NULL; + + if (type == NULL) { + /* There was no exception, so nothing to do. */ + return; + } + + /* If PyErr_SetNone() was used, the value will have been actually + set to NULL. + */ + if (!value) { + value = Py_None; + Py_INCREF(value); + } + + if (PyExceptionInstance_Check(value)) + inclass = PyExceptionInstance_Class(value); + + /* Normalize the exception so that if the type is a class, the + value will be an instance. + */ + if (PyExceptionClass_Check(type)) { + /* if the value was not an instance, or is not an instance + whose class is (or is derived from) type, then use the + value as an argument to instantiation of the type + class. + */ + if (!inclass || !PyObject_IsSubclass(inclass, type)) { + PyObject *args, *res; + + if (value == Py_None) + args = PyTuple_New(0); + else if (PyTuple_Check(value)) { + Py_INCREF(value); + args = value; + } + else + args = PyTuple_Pack(1, value); + + if (args == NULL) + goto finally; + res = PyEval_CallObject(type, args); + Py_DECREF(args); + if (res == NULL) + goto finally; + Py_DECREF(value); + value = res; + } + /* if the class of the instance doesn't exactly match the + class of the type, believe the instance + */ + else if (inclass != type) { + Py_DECREF(type); + type = inclass; + Py_INCREF(type); + } + } + *exc = type; + *val = value; + return; finally: - Py_DECREF(type); - Py_DECREF(value); - /* If the new exception doesn't set a traceback and the old - exception had a traceback, use the old traceback for the - new exception. It's better than nothing. - */ - initial_tb = *tb; - PyErr_Fetch(exc, val, tb); - if (initial_tb != NULL) { - if (*tb == NULL) - *tb = initial_tb; - else - Py_DECREF(initial_tb); - } - /* normalize recursively */ - tstate = PyThreadState_GET(); - if (++tstate->recursion_depth > Py_GetRecursionLimit()) { - --tstate->recursion_depth; - /* throw away the old exception... */ - Py_DECREF(*exc); - Py_DECREF(*val); - /* ... and use the recursion error instead */ - *exc = PyExc_RuntimeError; - *val = PyExc_RecursionErrorInst; - Py_INCREF(*exc); - Py_INCREF(*val); - /* just keeping the old traceback */ - return; - } - PyErr_NormalizeException(exc, val, tb); - --tstate->recursion_depth; + Py_DECREF(type); + Py_DECREF(value); + /* If the new exception doesn't set a traceback and the old + exception had a traceback, use the old traceback for the + new exception. It's better than nothing. + */ + initial_tb = *tb; + PyErr_Fetch(exc, val, tb); + if (initial_tb != NULL) { + if (*tb == NULL) + *tb = initial_tb; + else + Py_DECREF(initial_tb); + } + /* normalize recursively */ + tstate = PyThreadState_GET(); + if (++tstate->recursion_depth > Py_GetRecursionLimit()) { + --tstate->recursion_depth; + /* throw away the old exception... */ + Py_DECREF(*exc); + Py_DECREF(*val); + /* ... and use the recursion error instead */ + *exc = PyExc_RuntimeError; + *val = PyExc_RecursionErrorInst; + Py_INCREF(*exc); + Py_INCREF(*val); + /* just keeping the old traceback */ + return; + } + PyErr_NormalizeException(exc, val, tb); + --tstate->recursion_depth; } void PyErr_Fetch(PyObject **p_type, PyObject **p_value, PyObject **p_traceback) { - PyThreadState *tstate = PyThreadState_GET(); + PyThreadState *tstate = PyThreadState_GET(); - *p_type = tstate->curexc_type; - *p_value = tstate->curexc_value; - *p_traceback = tstate->curexc_traceback; - - tstate->curexc_type = NULL; - tstate->curexc_value = NULL; - tstate->curexc_traceback = NULL; + *p_type = tstate->curexc_type; + *p_value = tstate->curexc_value; + *p_traceback = tstate->curexc_traceback; + + tstate->curexc_type = NULL; + tstate->curexc_value = NULL; + tstate->curexc_traceback = NULL; } void PyErr_Clear(void) { - PyErr_Restore(NULL, NULL, NULL); + PyErr_Restore(NULL, NULL, NULL); } /* Convenience functions to set a type error exception and return 0 */ @@ -320,293 +320,293 @@ int PyErr_BadArgument(void) { - PyErr_SetString(PyExc_TypeError, - "bad argument type for built-in operation"); - return 0; + PyErr_SetString(PyExc_TypeError, + "bad argument type for built-in operation"); + return 0; } PyObject * PyErr_NoMemory(void) { - if (PyErr_ExceptionMatches(PyExc_MemoryError)) - /* already current */ - return NULL; - - /* raise the pre-allocated instance if it still exists */ - if (PyExc_MemoryErrorInst) - { - /* Clear the previous traceback, otherwise it will be appended - * to the current one. - * - * The following statement is not likely to raise any error; - * if it does, we simply discard it. - */ - PyException_SetTraceback(PyExc_MemoryErrorInst, Py_None); - - PyErr_SetObject(PyExc_MemoryError, PyExc_MemoryErrorInst); - } - else - /* this will probably fail since there's no memory and hee, - hee, we have to instantiate this class - */ - PyErr_SetNone(PyExc_MemoryError); + if (PyErr_ExceptionMatches(PyExc_MemoryError)) + /* already current */ + return NULL; + + /* raise the pre-allocated instance if it still exists */ + if (PyExc_MemoryErrorInst) + { + /* Clear the previous traceback, otherwise it will be appended + * to the current one. + * + * The following statement is not likely to raise any error; + * if it does, we simply discard it. + */ + PyException_SetTraceback(PyExc_MemoryErrorInst, Py_None); + + PyErr_SetObject(PyExc_MemoryError, PyExc_MemoryErrorInst); + } + else + /* this will probably fail since there's no memory and hee, + hee, we have to instantiate this class + */ + PyErr_SetNone(PyExc_MemoryError); - return NULL; + return NULL; } PyObject * PyErr_SetFromErrnoWithFilenameObject(PyObject *exc, PyObject *filenameObject) { - PyObject *message; - PyObject *v; - int i = errno; + PyObject *message; + PyObject *v; + int i = errno; #ifdef PLAN9 - char errbuf[ERRMAX]; + char errbuf[ERRMAX]; #else #ifndef MS_WINDOWS - char *s; + char *s; #else - WCHAR *s_buf = NULL; + WCHAR *s_buf = NULL; #endif /* Unix/Windows */ #endif /* PLAN 9*/ #ifdef EINTR - if (i == EINTR && PyErr_CheckSignals()) - return NULL; + if (i == EINTR && PyErr_CheckSignals()) + return NULL; #endif #ifdef PLAN9 - rerrstr(errbuf, sizeof errbuf); - message = PyUnicode_DecodeUTF8(errbuf, strlen(errbuf), "ignore"); + rerrstr(errbuf, sizeof errbuf); + message = PyUnicode_DecodeUTF8(errbuf, strlen(errbuf), "ignore"); #else #ifndef MS_WINDOWS - if (i == 0) - s = "Error"; /* Sometimes errno didn't get set */ - else - s = strerror(i); - message = PyUnicode_DecodeUTF8(s, strlen(s), "ignore"); + if (i == 0) + s = "Error"; /* Sometimes errno didn't get set */ + else + s = strerror(i); + message = PyUnicode_DecodeUTF8(s, strlen(s), "ignore"); #else - if (i == 0) - message = PyUnicode_FromString("Error"); /* Sometimes errno didn't get set */ - else - { - /* Note that the Win32 errors do not lineup with the - errno error. So if the error is in the MSVC error - table, we use it, otherwise we assume it really _is_ - a Win32 error code - */ - if (i > 0 && i < _sys_nerr) { - message = PyUnicode_FromString(_sys_errlist[i]); - } - else { - int len = FormatMessageW( - FORMAT_MESSAGE_ALLOCATE_BUFFER | - FORMAT_MESSAGE_FROM_SYSTEM | - FORMAT_MESSAGE_IGNORE_INSERTS, - NULL, /* no message source */ - i, - MAKELANGID(LANG_NEUTRAL, - SUBLANG_DEFAULT), - /* Default language */ - (LPWSTR) &s_buf, - 0, /* size not used */ - NULL); /* no args */ - if (len==0) { - /* Only ever seen this in out-of-mem - situations */ - s_buf = NULL; - message = PyUnicode_FromFormat("Windows Error 0x%X", i); - } else { - /* remove trailing cr/lf and dots */ - while (len > 0 && (s_buf[len-1] <= L' ' || s_buf[len-1] == L'.')) - s_buf[--len] = L'\0'; - message = PyUnicode_FromUnicode(s_buf, len); - } - } - } + if (i == 0) + message = PyUnicode_FromString("Error"); /* Sometimes errno didn't get set */ + else + { + /* Note that the Win32 errors do not lineup with the + errno error. So if the error is in the MSVC error + table, we use it, otherwise we assume it really _is_ + a Win32 error code + */ + if (i > 0 && i < _sys_nerr) { + message = PyUnicode_FromString(_sys_errlist[i]); + } + else { + int len = FormatMessageW( + FORMAT_MESSAGE_ALLOCATE_BUFFER | + FORMAT_MESSAGE_FROM_SYSTEM | + FORMAT_MESSAGE_IGNORE_INSERTS, + NULL, /* no message source */ + i, + MAKELANGID(LANG_NEUTRAL, + SUBLANG_DEFAULT), + /* Default language */ + (LPWSTR) &s_buf, + 0, /* size not used */ + NULL); /* no args */ + if (len==0) { + /* Only ever seen this in out-of-mem + situations */ + s_buf = NULL; + message = PyUnicode_FromFormat("Windows Error 0x%X", i); + } else { + /* remove trailing cr/lf and dots */ + while (len > 0 && (s_buf[len-1] <= L' ' || s_buf[len-1] == L'.')) + s_buf[--len] = L'\0'; + message = PyUnicode_FromUnicode(s_buf, len); + } + } + } #endif /* Unix/Windows */ #endif /* PLAN 9*/ - if (message == NULL) - { + if (message == NULL) + { #ifdef MS_WINDOWS - LocalFree(s_buf); + LocalFree(s_buf); #endif - return NULL; - } + return NULL; + } - if (filenameObject != NULL) - v = Py_BuildValue("(iOO)", i, message, filenameObject); - else - v = Py_BuildValue("(iO)", i, message); - Py_DECREF(message); - - if (v != NULL) { - PyErr_SetObject(exc, v); - Py_DECREF(v); - } + if (filenameObject != NULL) + v = Py_BuildValue("(iOO)", i, message, filenameObject); + else + v = Py_BuildValue("(iO)", i, message); + Py_DECREF(message); + + if (v != NULL) { + PyErr_SetObject(exc, v); + Py_DECREF(v); + } #ifdef MS_WINDOWS - LocalFree(s_buf); + LocalFree(s_buf); #endif - return NULL; + return NULL; } PyObject * PyErr_SetFromErrnoWithFilename(PyObject *exc, const char *filename) { - PyObject *name = filename ? PyUnicode_FromString(filename) : NULL; - PyObject *result = PyErr_SetFromErrnoWithFilenameObject(exc, name); - Py_XDECREF(name); - return result; + PyObject *name = filename ? PyUnicode_FromString(filename) : NULL; + PyObject *result = PyErr_SetFromErrnoWithFilenameObject(exc, name); + Py_XDECREF(name); + return result; } #ifdef MS_WINDOWS PyObject * PyErr_SetFromErrnoWithUnicodeFilename(PyObject *exc, const Py_UNICODE *filename) { - PyObject *name = filename ? - PyUnicode_FromUnicode(filename, wcslen(filename)) : - NULL; - PyObject *result = PyErr_SetFromErrnoWithFilenameObject(exc, name); - Py_XDECREF(name); - return result; + PyObject *name = filename ? + PyUnicode_FromUnicode(filename, wcslen(filename)) : + NULL; + PyObject *result = PyErr_SetFromErrnoWithFilenameObject(exc, name); + Py_XDECREF(name); + return result; } #endif /* MS_WINDOWS */ PyObject * PyErr_SetFromErrno(PyObject *exc) { - return PyErr_SetFromErrnoWithFilenameObject(exc, NULL); + return PyErr_SetFromErrnoWithFilenameObject(exc, NULL); } #ifdef MS_WINDOWS /* Windows specific error code handling */ PyObject *PyErr_SetExcFromWindowsErrWithFilenameObject( - PyObject *exc, - int ierr, - PyObject *filenameObject) -{ - int len; - WCHAR *s_buf = NULL; /* Free via LocalFree */ - PyObject *message; - PyObject *v; - DWORD err = (DWORD)ierr; - if (err==0) err = GetLastError(); - len = FormatMessageW( - /* Error API error */ - FORMAT_MESSAGE_ALLOCATE_BUFFER | - FORMAT_MESSAGE_FROM_SYSTEM | - FORMAT_MESSAGE_IGNORE_INSERTS, - NULL, /* no message source */ - err, - MAKELANGID(LANG_NEUTRAL, - SUBLANG_DEFAULT), /* Default language */ - (LPWSTR) &s_buf, - 0, /* size not used */ - NULL); /* no args */ - if (len==0) { - /* Only seen this in out of mem situations */ - message = PyUnicode_FromFormat("Windows Error 0x%X", err); - s_buf = NULL; - } else { - /* remove trailing cr/lf and dots */ - while (len > 0 && (s_buf[len-1] <= L' ' || s_buf[len-1] == L'.')) - s_buf[--len] = L'\0'; - message = PyUnicode_FromUnicode(s_buf, len); - } - - if (message == NULL) - { - LocalFree(s_buf); - return NULL; - } - - if (filenameObject != NULL) - v = Py_BuildValue("(iOO)", err, message, filenameObject); - else - v = Py_BuildValue("(iO)", err, message); - Py_DECREF(message); - - if (v != NULL) { - PyErr_SetObject(exc, v); - Py_DECREF(v); - } - LocalFree(s_buf); - return NULL; + PyObject *exc, + int ierr, + PyObject *filenameObject) +{ + int len; + WCHAR *s_buf = NULL; /* Free via LocalFree */ + PyObject *message; + PyObject *v; + DWORD err = (DWORD)ierr; + if (err==0) err = GetLastError(); + len = FormatMessageW( + /* Error API error */ + FORMAT_MESSAGE_ALLOCATE_BUFFER | + FORMAT_MESSAGE_FROM_SYSTEM | + FORMAT_MESSAGE_IGNORE_INSERTS, + NULL, /* no message source */ + err, + MAKELANGID(LANG_NEUTRAL, + SUBLANG_DEFAULT), /* Default language */ + (LPWSTR) &s_buf, + 0, /* size not used */ + NULL); /* no args */ + if (len==0) { + /* Only seen this in out of mem situations */ + message = PyUnicode_FromFormat("Windows Error 0x%X", err); + s_buf = NULL; + } else { + /* remove trailing cr/lf and dots */ + while (len > 0 && (s_buf[len-1] <= L' ' || s_buf[len-1] == L'.')) + s_buf[--len] = L'\0'; + message = PyUnicode_FromUnicode(s_buf, len); + } + + if (message == NULL) + { + LocalFree(s_buf); + return NULL; + } + + if (filenameObject != NULL) + v = Py_BuildValue("(iOO)", err, message, filenameObject); + else + v = Py_BuildValue("(iO)", err, message); + Py_DECREF(message); + + if (v != NULL) { + PyErr_SetObject(exc, v); + Py_DECREF(v); + } + LocalFree(s_buf); + return NULL; } PyObject *PyErr_SetExcFromWindowsErrWithFilename( - PyObject *exc, - int ierr, - const char *filename) -{ - PyObject *name = filename ? PyUnicode_FromString(filename) : NULL; - PyObject *ret = PyErr_SetExcFromWindowsErrWithFilenameObject(exc, - ierr, - name); - Py_XDECREF(name); - return ret; + PyObject *exc, + int ierr, + const char *filename) +{ + PyObject *name = filename ? PyUnicode_FromString(filename) : NULL; + PyObject *ret = PyErr_SetExcFromWindowsErrWithFilenameObject(exc, + ierr, + name); + Py_XDECREF(name); + return ret; } PyObject *PyErr_SetExcFromWindowsErrWithUnicodeFilename( - PyObject *exc, - int ierr, - const Py_UNICODE *filename) -{ - PyObject *name = filename ? - PyUnicode_FromUnicode(filename, wcslen(filename)) : - NULL; - PyObject *ret = PyErr_SetExcFromWindowsErrWithFilenameObject(exc, - ierr, - name); - Py_XDECREF(name); - return ret; + PyObject *exc, + int ierr, + const Py_UNICODE *filename) +{ + PyObject *name = filename ? + PyUnicode_FromUnicode(filename, wcslen(filename)) : + NULL; + PyObject *ret = PyErr_SetExcFromWindowsErrWithFilenameObject(exc, + ierr, + name); + Py_XDECREF(name); + return ret; } PyObject *PyErr_SetExcFromWindowsErr(PyObject *exc, int ierr) { - return PyErr_SetExcFromWindowsErrWithFilename(exc, ierr, NULL); + return PyErr_SetExcFromWindowsErrWithFilename(exc, ierr, NULL); } PyObject *PyErr_SetFromWindowsErr(int ierr) { - return PyErr_SetExcFromWindowsErrWithFilename(PyExc_WindowsError, - ierr, NULL); + return PyErr_SetExcFromWindowsErrWithFilename(PyExc_WindowsError, + ierr, NULL); } PyObject *PyErr_SetFromWindowsErrWithFilename( - int ierr, - const char *filename) + int ierr, + const char *filename) { - PyObject *name = filename ? PyUnicode_FromString(filename) : NULL; - PyObject *result = PyErr_SetExcFromWindowsErrWithFilenameObject( - PyExc_WindowsError, - ierr, name); - Py_XDECREF(name); - return result; + PyObject *name = filename ? PyUnicode_FromString(filename) : NULL; + PyObject *result = PyErr_SetExcFromWindowsErrWithFilenameObject( + PyExc_WindowsError, + ierr, name); + Py_XDECREF(name); + return result; } PyObject *PyErr_SetFromWindowsErrWithUnicodeFilename( - int ierr, - const Py_UNICODE *filename) + int ierr, + const Py_UNICODE *filename) { - PyObject *name = filename ? - PyUnicode_FromUnicode(filename, wcslen(filename)) : - NULL; - PyObject *result = PyErr_SetExcFromWindowsErrWithFilenameObject( - PyExc_WindowsError, - ierr, name); - Py_XDECREF(name); - return result; + PyObject *name = filename ? + PyUnicode_FromUnicode(filename, wcslen(filename)) : + NULL; + PyObject *result = PyErr_SetExcFromWindowsErrWithFilenameObject( + PyExc_WindowsError, + ierr, name); + Py_XDECREF(name); + return result; } #endif /* MS_WINDOWS */ void _PyErr_BadInternalCall(const char *filename, int lineno) { - PyErr_Format(PyExc_SystemError, - "%s:%d: bad argument to internal function", - filename, lineno); + PyErr_Format(PyExc_SystemError, + "%s:%d: bad argument to internal function", + filename, lineno); } /* Remove the preprocessor macro for PyErr_BadInternalCall() so that we can @@ -615,8 +615,8 @@ void PyErr_BadInternalCall(void) { - PyErr_Format(PyExc_SystemError, - "bad argument to internal function"); + PyErr_Format(PyExc_SystemError, + "bad argument to internal function"); } #define PyErr_BadInternalCall() _PyErr_BadInternalCall(__FILE__, __LINE__) @@ -625,20 +625,20 @@ PyObject * PyErr_Format(PyObject *exception, const char *format, ...) { - va_list vargs; - PyObject* string; + va_list vargs; + PyObject* string; #ifdef HAVE_STDARG_PROTOTYPES - va_start(vargs, format); + va_start(vargs, format); #else - va_start(vargs); + va_start(vargs); #endif - string = PyUnicode_FromFormatV(format, vargs); - PyErr_SetObject(exception, string); - Py_XDECREF(string); - va_end(vargs); - return NULL; + string = PyUnicode_FromFormatV(format, vargs); + PyErr_SetObject(exception, string); + Py_XDECREF(string); + va_end(vargs); + return NULL; } @@ -646,51 +646,51 @@ PyObject * PyErr_NewException(const char *name, PyObject *base, PyObject *dict) { - const char *dot; - PyObject *modulename = NULL; - PyObject *classname = NULL; - PyObject *mydict = NULL; - PyObject *bases = NULL; - PyObject *result = NULL; - dot = strrchr(name, '.'); - if (dot == NULL) { - PyErr_SetString(PyExc_SystemError, - "PyErr_NewException: name must be module.class"); - return NULL; - } - if (base == NULL) - base = PyExc_Exception; - if (dict == NULL) { - dict = mydict = PyDict_New(); - if (dict == NULL) - goto failure; - } - if (PyDict_GetItemString(dict, "__module__") == NULL) { - modulename = PyUnicode_FromStringAndSize(name, - (Py_ssize_t)(dot-name)); - if (modulename == NULL) - goto failure; - if (PyDict_SetItemString(dict, "__module__", modulename) != 0) - goto failure; - } - if (PyTuple_Check(base)) { - bases = base; - /* INCREF as we create a new ref in the else branch */ - Py_INCREF(bases); - } else { - bases = PyTuple_Pack(1, base); - if (bases == NULL) - goto failure; - } - /* Create a real new-style class. */ - result = PyObject_CallFunction((PyObject *)&PyType_Type, "UOO", - dot+1, bases, dict); + const char *dot; + PyObject *modulename = NULL; + PyObject *classname = NULL; + PyObject *mydict = NULL; + PyObject *bases = NULL; + PyObject *result = NULL; + dot = strrchr(name, '.'); + if (dot == NULL) { + PyErr_SetString(PyExc_SystemError, + "PyErr_NewException: name must be module.class"); + return NULL; + } + if (base == NULL) + base = PyExc_Exception; + if (dict == NULL) { + dict = mydict = PyDict_New(); + if (dict == NULL) + goto failure; + } + if (PyDict_GetItemString(dict, "__module__") == NULL) { + modulename = PyUnicode_FromStringAndSize(name, + (Py_ssize_t)(dot-name)); + if (modulename == NULL) + goto failure; + if (PyDict_SetItemString(dict, "__module__", modulename) != 0) + goto failure; + } + if (PyTuple_Check(base)) { + bases = base; + /* INCREF as we create a new ref in the else branch */ + Py_INCREF(bases); + } else { + bases = PyTuple_Pack(1, base); + if (bases == NULL) + goto failure; + } + /* Create a real new-style class. */ + result = PyObject_CallFunction((PyObject *)&PyType_Type, "UOO", + dot+1, bases, dict); failure: - Py_XDECREF(bases); - Py_XDECREF(mydict); - Py_XDECREF(classname); - Py_XDECREF(modulename); - return result; + Py_XDECREF(bases); + Py_XDECREF(mydict); + Py_XDECREF(classname); + Py_XDECREF(modulename); + return result; } /* Call when an exception has occurred but there is no way for Python @@ -698,52 +698,52 @@ void PyErr_WriteUnraisable(PyObject *obj) { - PyObject *f, *t, *v, *tb; - PyErr_Fetch(&t, &v, &tb); - f = PySys_GetObject("stderr"); - if (f != NULL && f != Py_None) { - PyFile_WriteString("Exception ", f); - if (t) { - PyObject* moduleName; - char* className; - assert(PyExceptionClass_Check(t)); - className = PyExceptionClass_Name(t); - if (className != NULL) { - char *dot = strrchr(className, '.'); - if (dot != NULL) - className = dot+1; - } - - moduleName = PyObject_GetAttrString(t, "__module__"); - if (moduleName == NULL) - PyFile_WriteString("", f); - else { - char* modstr = _PyUnicode_AsString(moduleName); - if (modstr && - strcmp(modstr, "builtins") != 0) - { - PyFile_WriteString(modstr, f); - PyFile_WriteString(".", f); - } - } - if (className == NULL) - PyFile_WriteString("", f); - else - PyFile_WriteString(className, f); - if (v && v != Py_None) { - PyFile_WriteString(": ", f); - PyFile_WriteObject(v, f, 0); - } - Py_XDECREF(moduleName); - } - PyFile_WriteString(" in ", f); - PyFile_WriteObject(obj, f, 0); - PyFile_WriteString(" ignored\n", f); - PyErr_Clear(); /* Just in case */ - } - Py_XDECREF(t); - Py_XDECREF(v); - Py_XDECREF(tb); + PyObject *f, *t, *v, *tb; + PyErr_Fetch(&t, &v, &tb); + f = PySys_GetObject("stderr"); + if (f != NULL && f != Py_None) { + PyFile_WriteString("Exception ", f); + if (t) { + PyObject* moduleName; + char* className; + assert(PyExceptionClass_Check(t)); + className = PyExceptionClass_Name(t); + if (className != NULL) { + char *dot = strrchr(className, '.'); + if (dot != NULL) + className = dot+1; + } + + moduleName = PyObject_GetAttrString(t, "__module__"); + if (moduleName == NULL) + PyFile_WriteString("", f); + else { + char* modstr = _PyUnicode_AsString(moduleName); + if (modstr && + strcmp(modstr, "builtins") != 0) + { + PyFile_WriteString(modstr, f); + PyFile_WriteString(".", f); + } + } + if (className == NULL) + PyFile_WriteString("", f); + else + PyFile_WriteString(className, f); + if (v && v != Py_None) { + PyFile_WriteString(": ", f); + PyFile_WriteObject(v, f, 0); + } + Py_XDECREF(moduleName); + } + PyFile_WriteString(" in ", f); + PyFile_WriteObject(obj, f, 0); + PyFile_WriteString(" ignored\n", f); + PyErr_Clear(); /* Just in case */ + } + Py_XDECREF(t); + Py_XDECREF(v); + Py_XDECREF(tb); } extern PyObject *PyModule_GetWarningsModule(void); @@ -756,59 +756,59 @@ void PyErr_SyntaxLocation(const char *filename, int lineno) { - PyObject *exc, *v, *tb, *tmp; + PyObject *exc, *v, *tb, *tmp; - /* add attributes for the line number and filename for the error */ - PyErr_Fetch(&exc, &v, &tb); - PyErr_NormalizeException(&exc, &v, &tb); - /* XXX check that it is, indeed, a syntax error. It might not - * be, though. */ - tmp = PyLong_FromLong(lineno); - if (tmp == NULL) - PyErr_Clear(); - else { - if (PyObject_SetAttrString(v, "lineno", tmp)) - PyErr_Clear(); - Py_DECREF(tmp); - } - if (filename != NULL) { - tmp = PyUnicode_FromString(filename); - if (tmp == NULL) - PyErr_Clear(); - else { - if (PyObject_SetAttrString(v, "filename", tmp)) - PyErr_Clear(); - Py_DECREF(tmp); - } - - tmp = PyErr_ProgramText(filename, lineno); - if (tmp) { - if (PyObject_SetAttrString(v, "text", tmp)) - PyErr_Clear(); - Py_DECREF(tmp); - } - } - if (PyObject_SetAttrString(v, "offset", Py_None)) { - PyErr_Clear(); - } - if (exc != PyExc_SyntaxError) { - if (!PyObject_HasAttrString(v, "msg")) { - tmp = PyObject_Str(v); - if (tmp) { - if (PyObject_SetAttrString(v, "msg", tmp)) - PyErr_Clear(); - Py_DECREF(tmp); - } else { - PyErr_Clear(); - } - } - if (!PyObject_HasAttrString(v, "print_file_and_line")) { - if (PyObject_SetAttrString(v, "print_file_and_line", - Py_None)) - PyErr_Clear(); - } - } - PyErr_Restore(exc, v, tb); + /* add attributes for the line number and filename for the error */ + PyErr_Fetch(&exc, &v, &tb); + PyErr_NormalizeException(&exc, &v, &tb); + /* XXX check that it is, indeed, a syntax error. It might not + * be, though. */ + tmp = PyLong_FromLong(lineno); + if (tmp == NULL) + PyErr_Clear(); + else { + if (PyObject_SetAttrString(v, "lineno", tmp)) + PyErr_Clear(); + Py_DECREF(tmp); + } + if (filename != NULL) { + tmp = PyUnicode_FromString(filename); + if (tmp == NULL) + PyErr_Clear(); + else { + if (PyObject_SetAttrString(v, "filename", tmp)) + PyErr_Clear(); + Py_DECREF(tmp); + } + + tmp = PyErr_ProgramText(filename, lineno); + if (tmp) { + if (PyObject_SetAttrString(v, "text", tmp)) + PyErr_Clear(); + Py_DECREF(tmp); + } + } + if (PyObject_SetAttrString(v, "offset", Py_None)) { + PyErr_Clear(); + } + if (exc != PyExc_SyntaxError) { + if (!PyObject_HasAttrString(v, "msg")) { + tmp = PyObject_Str(v); + if (tmp) { + if (PyObject_SetAttrString(v, "msg", tmp)) + PyErr_Clear(); + Py_DECREF(tmp); + } else { + PyErr_Clear(); + } + } + if (!PyObject_HasAttrString(v, "print_file_and_line")) { + if (PyObject_SetAttrString(v, "print_file_and_line", + Py_None)) + PyErr_Clear(); + } + } + PyErr_Restore(exc, v, tb); } /* Attempt to load the line of text that the exception refers to. If it @@ -820,41 +820,41 @@ PyObject * PyErr_ProgramText(const char *filename, int lineno) { - FILE *fp; - int i; - char linebuf[1000]; - - if (filename == NULL || *filename == '\0' || lineno <= 0) - return NULL; - fp = fopen(filename, "r" PY_STDIOTEXTMODE); - if (fp == NULL) - return NULL; - for (i = 0; i < lineno; i++) { - char *pLastChar = &linebuf[sizeof(linebuf) - 2]; - do { - *pLastChar = '\0'; - if (Py_UniversalNewlineFgets(linebuf, sizeof linebuf, - fp, NULL) == NULL) - break; - /* fgets read *something*; if it didn't get as - far as pLastChar, it must have found a newline - or hit the end of the file; if pLastChar is \n, - it obviously found a newline; else we haven't - yet seen a newline, so must continue */ - } while (*pLastChar != '\0' && *pLastChar != '\n'); - } - fclose(fp); - if (i == lineno) { - char *p = linebuf; - PyObject *res; - while (*p == ' ' || *p == '\t' || *p == '\014') - p++; - res = PyUnicode_FromString(p); - if (res == NULL) - PyErr_Clear(); - return res; - } - return NULL; + FILE *fp; + int i; + char linebuf[1000]; + + if (filename == NULL || *filename == '\0' || lineno <= 0) + return NULL; + fp = fopen(filename, "r" PY_STDIOTEXTMODE); + if (fp == NULL) + return NULL; + for (i = 0; i < lineno; i++) { + char *pLastChar = &linebuf[sizeof(linebuf) - 2]; + do { + *pLastChar = '\0'; + if (Py_UniversalNewlineFgets(linebuf, sizeof linebuf, + fp, NULL) == NULL) + break; + /* fgets read *something*; if it didn't get as + far as pLastChar, it must have found a newline + or hit the end of the file; if pLastChar is \n, + it obviously found a newline; else we haven't + yet seen a newline, so must continue */ + } while (*pLastChar != '\0' && *pLastChar != '\n'); + } + fclose(fp); + if (i == lineno) { + char *p = linebuf; + PyObject *res; + while (*p == ' ' || *p == '\t' || *p == '\014') + p++; + res = PyUnicode_FromString(p); + if (res == NULL) + PyErr_Clear(); + return res; + } + return NULL; } #ifdef __cplusplus Modified: python/branches/release31-maint/Python/frozen.c ============================================================================== --- python/branches/release31-maint/Python/frozen.c (original) +++ python/branches/release31-maint/Python/frozen.c Sun May 9 18:14:21 2010 @@ -12,25 +12,25 @@ the appropriate bytes from M___main__.c. */ static unsigned char M___hello__[] = { - 99,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0, - 0,64,0,0,0,115,10,0,0,0,100,1,0,90,1,0, - 100,0,0,83,40,2,0,0,0,78,84,40,2,0,0,0, - 117,4,0,0,0,84,114,117,101,117,11,0,0,0,105,110, - 105,116,105,97,108,105,122,101,100,40,0,0,0,0,40,0, - 0,0,0,40,0,0,0,0,117,7,0,0,0,102,108,97, - 103,46,112,121,117,8,0,0,0,60,109,111,100,117,108,101, - 62,1,0,0,0,115,0,0,0,0, + 99,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0, + 0,64,0,0,0,115,10,0,0,0,100,1,0,90,1,0, + 100,0,0,83,40,2,0,0,0,78,84,40,2,0,0,0, + 117,4,0,0,0,84,114,117,101,117,11,0,0,0,105,110, + 105,116,105,97,108,105,122,101,100,40,0,0,0,0,40,0, + 0,0,0,40,0,0,0,0,117,7,0,0,0,102,108,97, + 103,46,112,121,117,8,0,0,0,60,109,111,100,117,108,101, + 62,1,0,0,0,115,0,0,0,0, }; #define SIZE (int)sizeof(M___hello__) static struct _frozen _PyImport_FrozenModules[] = { - /* Test module */ - {"__hello__", M___hello__, SIZE}, - /* Test package (negative size indicates package-ness) */ - {"__phello__", M___hello__, -SIZE}, - {"__phello__.spam", M___hello__, SIZE}, - {0, 0, 0} /* sentinel */ + /* Test module */ + {"__hello__", M___hello__, SIZE}, + /* Test package (negative size indicates package-ness) */ + {"__phello__", M___hello__, -SIZE}, + {"__phello__.spam", M___hello__, SIZE}, + {0, 0, 0} /* sentinel */ }; /* Embedding apps may change this pointer to point to their favorite Modified: python/branches/release31-maint/Python/frozenmain.c ============================================================================== --- python/branches/release31-maint/Python/frozenmain.c (original) +++ python/branches/release31-maint/Python/frozenmain.c Sun May 9 18:14:21 2010 @@ -15,96 +15,96 @@ int Py_FrozenMain(int argc, char **argv) { - char *p; - int i, n, sts; - int inspect = 0; - int unbuffered = 0; - char *oldloc; - wchar_t **argv_copy = PyMem_Malloc(sizeof(wchar_t*)*argc); - /* We need a second copies, as Python might modify the first one. */ - wchar_t **argv_copy2 = PyMem_Malloc(sizeof(wchar_t*)*argc); - - Py_FrozenFlag = 1; /* Suppress errors from getpath.c */ - - if ((p = Py_GETENV("PYTHONINSPECT")) && *p != '\0') - inspect = 1; - if ((p = Py_GETENV("PYTHONUNBUFFERED")) && *p != '\0') - unbuffered = 1; - - if (unbuffered) { - setbuf(stdin, (char *)NULL); - setbuf(stdout, (char *)NULL); - setbuf(stderr, (char *)NULL); - } - - if (!argv_copy) { - fprintf(stderr, "out of memory\n"); - return 1; - } - - oldloc = setlocale(LC_ALL, NULL); - setlocale(LC_ALL, ""); - for (i = 0; i < argc; i++) { + char *p; + int i, n, sts; + int inspect = 0; + int unbuffered = 0; + char *oldloc; + wchar_t **argv_copy = PyMem_Malloc(sizeof(wchar_t*)*argc); + /* We need a second copies, as Python might modify the first one. */ + wchar_t **argv_copy2 = PyMem_Malloc(sizeof(wchar_t*)*argc); + + Py_FrozenFlag = 1; /* Suppress errors from getpath.c */ + + if ((p = Py_GETENV("PYTHONINSPECT")) && *p != '\0') + inspect = 1; + if ((p = Py_GETENV("PYTHONUNBUFFERED")) && *p != '\0') + unbuffered = 1; + + if (unbuffered) { + setbuf(stdin, (char *)NULL); + setbuf(stdout, (char *)NULL); + setbuf(stderr, (char *)NULL); + } + + if (!argv_copy) { + fprintf(stderr, "out of memory\n"); + return 1; + } + + oldloc = setlocale(LC_ALL, NULL); + setlocale(LC_ALL, ""); + for (i = 0; i < argc; i++) { #ifdef HAVE_BROKEN_MBSTOWCS - size_t argsize = strlen(argv[i]); + size_t argsize = strlen(argv[i]); #else - size_t argsize = mbstowcs(NULL, argv[i], 0); + size_t argsize = mbstowcs(NULL, argv[i], 0); #endif - size_t count; - if (argsize == (size_t)-1) { - fprintf(stderr, "Could not convert argument %d to string\n", i); - return 1; - } - argv_copy[i] = PyMem_Malloc((argsize+1)*sizeof(wchar_t)); - argv_copy2[i] = argv_copy[i]; - if (!argv_copy[i]) { - fprintf(stderr, "out of memory\n"); - return 1; - } - count = mbstowcs(argv_copy[i], argv[i], argsize+1); - if (count == (size_t)-1) { - fprintf(stderr, "Could not convert argument %d to string\n", i); - return 1; - } - } - setlocale(LC_ALL, oldloc); + size_t count; + if (argsize == (size_t)-1) { + fprintf(stderr, "Could not convert argument %d to string\n", i); + return 1; + } + argv_copy[i] = PyMem_Malloc((argsize+1)*sizeof(wchar_t)); + argv_copy2[i] = argv_copy[i]; + if (!argv_copy[i]) { + fprintf(stderr, "out of memory\n"); + return 1; + } + count = mbstowcs(argv_copy[i], argv[i], argsize+1); + if (count == (size_t)-1) { + fprintf(stderr, "Could not convert argument %d to string\n", i); + return 1; + } + } + setlocale(LC_ALL, oldloc); #ifdef MS_WINDOWS - PyInitFrozenExtensions(); + PyInitFrozenExtensions(); #endif /* MS_WINDOWS */ - Py_SetProgramName(argv_copy[0]); - Py_Initialize(); + Py_SetProgramName(argv_copy[0]); + Py_Initialize(); #ifdef MS_WINDOWS - PyWinFreeze_ExeInit(); + PyWinFreeze_ExeInit(); #endif - if (Py_VerboseFlag) - fprintf(stderr, "Python %s\n%s\n", - Py_GetVersion(), Py_GetCopyright()); - - PySys_SetArgv(argc, argv_copy); - - n = PyImport_ImportFrozenModule("__main__"); - if (n == 0) - Py_FatalError("__main__ not frozen"); - if (n < 0) { - PyErr_Print(); - sts = 1; - } - else - sts = 0; + if (Py_VerboseFlag) + fprintf(stderr, "Python %s\n%s\n", + Py_GetVersion(), Py_GetCopyright()); + + PySys_SetArgv(argc, argv_copy); + + n = PyImport_ImportFrozenModule("__main__"); + if (n == 0) + Py_FatalError("__main__ not frozen"); + if (n < 0) { + PyErr_Print(); + sts = 1; + } + else + sts = 0; - if (inspect && isatty((int)fileno(stdin))) - sts = PyRun_AnyFile(stdin, "") != 0; + if (inspect && isatty((int)fileno(stdin))) + sts = PyRun_AnyFile(stdin, "") != 0; #ifdef MS_WINDOWS - PyWinFreeze_ExeTerm(); + PyWinFreeze_ExeTerm(); #endif - Py_Finalize(); - for (i = 0; i < argc; i++) { - PyMem_Free(argv_copy2[i]); - } - PyMem_Free(argv_copy); - PyMem_Free(argv_copy2); - return sts; + Py_Finalize(); + for (i = 0; i < argc; i++) { + PyMem_Free(argv_copy2[i]); + } + PyMem_Free(argv_copy); + PyMem_Free(argv_copy2); + return sts; } Modified: python/branches/release31-maint/Python/future.c ============================================================================== --- python/branches/release31-maint/Python/future.c (original) +++ python/branches/release31-maint/Python/future.c Sun May 9 18:14:21 2010 @@ -14,131 +14,131 @@ static int future_check_features(PyFutureFeatures *ff, stmt_ty s, const char *filename) { - int i; - asdl_seq *names; + int i; + asdl_seq *names; - assert(s->kind == ImportFrom_kind); + assert(s->kind == ImportFrom_kind); - names = s->v.ImportFrom.names; - for (i = 0; i < asdl_seq_LEN(names); i++) { - alias_ty name = (alias_ty)asdl_seq_GET(names, i); - const char *feature = _PyUnicode_AsString(name->name); - if (!feature) - return 0; - if (strcmp(feature, FUTURE_NESTED_SCOPES) == 0) { - continue; - } else if (strcmp(feature, FUTURE_GENERATORS) == 0) { - continue; - } else if (strcmp(feature, FUTURE_DIVISION) == 0) { - continue; - } else if (strcmp(feature, FUTURE_ABSOLUTE_IMPORT) == 0) { - continue; - } else if (strcmp(feature, FUTURE_WITH_STATEMENT) == 0) { - continue; - } else if (strcmp(feature, FUTURE_PRINT_FUNCTION) == 0) { - continue; - } else if (strcmp(feature, FUTURE_UNICODE_LITERALS) == 0) { - continue; - } else if (strcmp(feature, FUTURE_BARRY_AS_BDFL) == 0) { - ff->ff_features |= CO_FUTURE_BARRY_AS_BDFL; - } else if (strcmp(feature, "braces") == 0) { - PyErr_SetString(PyExc_SyntaxError, - "not a chance"); - PyErr_SyntaxLocation(filename, s->lineno); - return 0; - } else { - PyErr_Format(PyExc_SyntaxError, - UNDEFINED_FUTURE_FEATURE, feature); - PyErr_SyntaxLocation(filename, s->lineno); - return 0; - } - } - return 1; + names = s->v.ImportFrom.names; + for (i = 0; i < asdl_seq_LEN(names); i++) { + alias_ty name = (alias_ty)asdl_seq_GET(names, i); + const char *feature = _PyUnicode_AsString(name->name); + if (!feature) + return 0; + if (strcmp(feature, FUTURE_NESTED_SCOPES) == 0) { + continue; + } else if (strcmp(feature, FUTURE_GENERATORS) == 0) { + continue; + } else if (strcmp(feature, FUTURE_DIVISION) == 0) { + continue; + } else if (strcmp(feature, FUTURE_ABSOLUTE_IMPORT) == 0) { + continue; + } else if (strcmp(feature, FUTURE_WITH_STATEMENT) == 0) { + continue; + } else if (strcmp(feature, FUTURE_PRINT_FUNCTION) == 0) { + continue; + } else if (strcmp(feature, FUTURE_UNICODE_LITERALS) == 0) { + continue; + } else if (strcmp(feature, FUTURE_BARRY_AS_BDFL) == 0) { + ff->ff_features |= CO_FUTURE_BARRY_AS_BDFL; + } else if (strcmp(feature, "braces") == 0) { + PyErr_SetString(PyExc_SyntaxError, + "not a chance"); + PyErr_SyntaxLocation(filename, s->lineno); + return 0; + } else { + PyErr_Format(PyExc_SyntaxError, + UNDEFINED_FUTURE_FEATURE, feature); + PyErr_SyntaxLocation(filename, s->lineno); + return 0; + } + } + return 1; } static int future_parse(PyFutureFeatures *ff, mod_ty mod, const char *filename) { - int i, found_docstring = 0, done = 0, prev_line = 0; + int i, found_docstring = 0, done = 0, prev_line = 0; - static PyObject *future; - if (!future) { - future = PyUnicode_InternFromString("__future__"); - if (!future) - return 0; - } - - if (!(mod->kind == Module_kind || mod->kind == Interactive_kind)) - return 1; - - /* A subsequent pass will detect future imports that don't - appear at the beginning of the file. There's one case, - however, that is easier to handle here: A series of imports - joined by semi-colons, where the first import is a future - statement but some subsequent import has the future form - but is preceded by a regular import. - */ - - - for (i = 0; i < asdl_seq_LEN(mod->v.Module.body); i++) { - stmt_ty s = (stmt_ty)asdl_seq_GET(mod->v.Module.body, i); - - if (done && s->lineno > prev_line) - return 1; - prev_line = s->lineno; - - /* The tests below will return from this function unless it is - still possible to find a future statement. The only things - that can precede a future statement are another future - statement and a doc string. - */ - - if (s->kind == ImportFrom_kind) { - if (s->v.ImportFrom.module == future) { - if (done) { - PyErr_SetString(PyExc_SyntaxError, - ERR_LATE_FUTURE); - PyErr_SyntaxLocation(filename, - s->lineno); - return 0; - } - if (!future_check_features(ff, s, filename)) - return 0; - ff->ff_lineno = s->lineno; - } - else - done = 1; - } - else if (s->kind == Expr_kind && !found_docstring) { - expr_ty e = s->v.Expr.value; - if (e->kind != Str_kind) - done = 1; - else - found_docstring = 1; - } - else - done = 1; - } - return 1; + static PyObject *future; + if (!future) { + future = PyUnicode_InternFromString("__future__"); + if (!future) + return 0; + } + + if (!(mod->kind == Module_kind || mod->kind == Interactive_kind)) + return 1; + + /* A subsequent pass will detect future imports that don't + appear at the beginning of the file. There's one case, + however, that is easier to handle here: A series of imports + joined by semi-colons, where the first import is a future + statement but some subsequent import has the future form + but is preceded by a regular import. + */ + + + for (i = 0; i < asdl_seq_LEN(mod->v.Module.body); i++) { + stmt_ty s = (stmt_ty)asdl_seq_GET(mod->v.Module.body, i); + + if (done && s->lineno > prev_line) + return 1; + prev_line = s->lineno; + + /* The tests below will return from this function unless it is + still possible to find a future statement. The only things + that can precede a future statement are another future + statement and a doc string. + */ + + if (s->kind == ImportFrom_kind) { + if (s->v.ImportFrom.module == future) { + if (done) { + PyErr_SetString(PyExc_SyntaxError, + ERR_LATE_FUTURE); + PyErr_SyntaxLocation(filename, + s->lineno); + return 0; + } + if (!future_check_features(ff, s, filename)) + return 0; + ff->ff_lineno = s->lineno; + } + else + done = 1; + } + else if (s->kind == Expr_kind && !found_docstring) { + expr_ty e = s->v.Expr.value; + if (e->kind != Str_kind) + done = 1; + else + found_docstring = 1; + } + else + done = 1; + } + return 1; } PyFutureFeatures * PyFuture_FromAST(mod_ty mod, const char *filename) { - PyFutureFeatures *ff; + PyFutureFeatures *ff; - ff = (PyFutureFeatures *)PyObject_Malloc(sizeof(PyFutureFeatures)); - if (ff == NULL) { - PyErr_NoMemory(); - return NULL; - } - ff->ff_features = 0; - ff->ff_lineno = -1; - - if (!future_parse(ff, mod, filename)) { - PyObject_Free(ff); - return NULL; - } - return ff; + ff = (PyFutureFeatures *)PyObject_Malloc(sizeof(PyFutureFeatures)); + if (ff == NULL) { + PyErr_NoMemory(); + return NULL; + } + ff->ff_features = 0; + ff->ff_lineno = -1; + + if (!future_parse(ff, mod, filename)) { + PyObject_Free(ff); + return NULL; + } + return ff; } Modified: python/branches/release31-maint/Python/getargs.c ============================================================================== --- python/branches/release31-maint/Python/getargs.c (original) +++ python/branches/release31-maint/Python/getargs.c Sun May 9 18:14:21 2010 @@ -14,9 +14,9 @@ int PyArg_VaParse(PyObject *, const char *, va_list); int PyArg_ParseTupleAndKeywords(PyObject *, PyObject *, - const char *, char **, ...); + const char *, char **, ...); int PyArg_VaParseTupleAndKeywords(PyObject *, PyObject *, - const char *, char **, va_list); + const char *, char **, va_list); #ifdef HAVE_DECLSPEC_DLL /* Export functions */ @@ -40,100 +40,100 @@ static char *convertitem(PyObject *, const char **, va_list *, int, int *, char *, size_t, PyObject **); static char *converttuple(PyObject *, const char **, va_list *, int, - int *, char *, size_t, int, PyObject **); + int *, char *, size_t, int, PyObject **); static char *convertsimple(PyObject *, const char **, va_list *, int, char *, - size_t, PyObject **); + size_t, PyObject **); static Py_ssize_t convertbuffer(PyObject *, void **p, char **); static int getbuffer(PyObject *, Py_buffer *, char**); static int vgetargskeywords(PyObject *, PyObject *, - const char *, char **, va_list *, int); + const char *, char **, va_list *, int); static char *skipitem(const char **, va_list *, int); int PyArg_Parse(PyObject *args, const char *format, ...) { - int retval; - va_list va; + int retval; + va_list va; - va_start(va, format); - retval = vgetargs1(args, format, &va, FLAG_COMPAT); - va_end(va); - return retval; + va_start(va, format); + retval = vgetargs1(args, format, &va, FLAG_COMPAT); + va_end(va); + return retval; } int _PyArg_Parse_SizeT(PyObject *args, char *format, ...) { - int retval; - va_list va; + int retval; + va_list va; - va_start(va, format); - retval = vgetargs1(args, format, &va, FLAG_COMPAT|FLAG_SIZE_T); - va_end(va); - return retval; + va_start(va, format); + retval = vgetargs1(args, format, &va, FLAG_COMPAT|FLAG_SIZE_T); + va_end(va); + return retval; } int PyArg_ParseTuple(PyObject *args, const char *format, ...) { - int retval; - va_list va; + int retval; + va_list va; - va_start(va, format); - retval = vgetargs1(args, format, &va, 0); - va_end(va); - return retval; + va_start(va, format); + retval = vgetargs1(args, format, &va, 0); + va_end(va); + return retval; } int _PyArg_ParseTuple_SizeT(PyObject *args, char *format, ...) { - int retval; - va_list va; + int retval; + va_list va; - va_start(va, format); - retval = vgetargs1(args, format, &va, FLAG_SIZE_T); - va_end(va); - return retval; + va_start(va, format); + retval = vgetargs1(args, format, &va, FLAG_SIZE_T); + va_end(va); + return retval; } int PyArg_VaParse(PyObject *args, const char *format, va_list va) { - va_list lva; + va_list lva; #ifdef VA_LIST_IS_ARRAY - memcpy(lva, va, sizeof(va_list)); + memcpy(lva, va, sizeof(va_list)); #else #ifdef __va_copy - __va_copy(lva, va); + __va_copy(lva, va); #else - lva = va; + lva = va; #endif #endif - return vgetargs1(args, format, &lva, 0); + return vgetargs1(args, format, &lva, 0); } int _PyArg_VaParse_SizeT(PyObject *args, char *format, va_list va) { - va_list lva; + va_list lva; #ifdef VA_LIST_IS_ARRAY - memcpy(lva, va, sizeof(va_list)); + memcpy(lva, va, sizeof(va_list)); #else #ifdef __va_copy - __va_copy(lva, va); + __va_copy(lva, va); #else - lva = va; + lva = va; #endif #endif - return vgetargs1(args, format, &lva, FLAG_SIZE_T); + return vgetargs1(args, format, &lva, FLAG_SIZE_T); } @@ -146,261 +146,261 @@ static void cleanup_ptr(PyObject *self) { - void *ptr = PyCapsule_GetPointer(self, GETARGS_CAPSULE_NAME_CLEANUP_PTR); - if (ptr) { - PyMem_FREE(ptr); - } + void *ptr = PyCapsule_GetPointer(self, GETARGS_CAPSULE_NAME_CLEANUP_PTR); + if (ptr) { + PyMem_FREE(ptr); + } } static void cleanup_buffer(PyObject *self) { - Py_buffer *ptr = (Py_buffer *)PyCapsule_GetPointer(self, GETARGS_CAPSULE_NAME_CLEANUP_BUFFER); - if (ptr) { - PyBuffer_Release(ptr); - } + Py_buffer *ptr = (Py_buffer *)PyCapsule_GetPointer(self, GETARGS_CAPSULE_NAME_CLEANUP_BUFFER); + if (ptr) { + PyBuffer_Release(ptr); + } } static int addcleanup(void *ptr, PyObject **freelist, PyCapsule_Destructor destr) { - PyObject *cobj; - const char *name; + PyObject *cobj; + const char *name; - if (!*freelist) { - *freelist = PyList_New(0); - if (!*freelist) { - destr(ptr); - return -1; - } - } - - if (destr == cleanup_ptr) { - name = GETARGS_CAPSULE_NAME_CLEANUP_PTR; - } else if (destr == cleanup_buffer) { - name = GETARGS_CAPSULE_NAME_CLEANUP_BUFFER; - } else { - return -1; - } - cobj = PyCapsule_New(ptr, name, destr); - if (!cobj) { - destr(ptr); - return -1; - } - if (PyList_Append(*freelist, cobj)) { - Py_DECREF(cobj); - return -1; - } + if (!*freelist) { + *freelist = PyList_New(0); + if (!*freelist) { + destr(ptr); + return -1; + } + } + + if (destr == cleanup_ptr) { + name = GETARGS_CAPSULE_NAME_CLEANUP_PTR; + } else if (destr == cleanup_buffer) { + name = GETARGS_CAPSULE_NAME_CLEANUP_BUFFER; + } else { + return -1; + } + cobj = PyCapsule_New(ptr, name, destr); + if (!cobj) { + destr(ptr); + return -1; + } + if (PyList_Append(*freelist, cobj)) { Py_DECREF(cobj); - return 0; + return -1; + } + Py_DECREF(cobj); + return 0; } static void cleanup_convert(PyObject *self) { - typedef int (*destr_t)(PyObject *, void *); - destr_t destr = (destr_t)PyCapsule_GetContext(self); - void *ptr = PyCapsule_GetPointer(self, - GETARGS_CAPSULE_NAME_CLEANUP_CONVERT); - if (ptr && destr) - destr(NULL, ptr); + typedef int (*destr_t)(PyObject *, void *); + destr_t destr = (destr_t)PyCapsule_GetContext(self); + void *ptr = PyCapsule_GetPointer(self, + GETARGS_CAPSULE_NAME_CLEANUP_CONVERT); + if (ptr && destr) + destr(NULL, ptr); } static int addcleanup_convert(void *ptr, PyObject **freelist, int (*destr)(PyObject*,void*)) { - PyObject *cobj; - if (!*freelist) { - *freelist = PyList_New(0); - if (!*freelist) { - destr(NULL, ptr); - return -1; - } - } - cobj = PyCapsule_New(ptr, GETARGS_CAPSULE_NAME_CLEANUP_CONVERT, - cleanup_convert); - if (!cobj) { - destr(NULL, ptr); - return -1; - } - if (PyCapsule_SetContext(cobj, destr) == -1) { - /* This really should not happen. */ - Py_FatalError("capsule refused setting of context."); - } - if (PyList_Append(*freelist, cobj)) { - Py_DECREF(cobj); /* This will also call destr. */ - return -1; - } - Py_DECREF(cobj); - return 0; + PyObject *cobj; + if (!*freelist) { + *freelist = PyList_New(0); + if (!*freelist) { + destr(NULL, ptr); + return -1; + } + } + cobj = PyCapsule_New(ptr, GETARGS_CAPSULE_NAME_CLEANUP_CONVERT, + cleanup_convert); + if (!cobj) { + destr(NULL, ptr); + return -1; + } + if (PyCapsule_SetContext(cobj, destr) == -1) { + /* This really should not happen. */ + Py_FatalError("capsule refused setting of context."); + } + if (PyList_Append(*freelist, cobj)) { + Py_DECREF(cobj); /* This will also call destr. */ + return -1; + } + Py_DECREF(cobj); + return 0; } static int cleanreturn(int retval, PyObject *freelist) { - if (freelist && retval != 0) { - /* We were successful, reset the destructors so that they - don't get called. */ - Py_ssize_t len = PyList_GET_SIZE(freelist), i; - for (i = 0; i < len; i++) - PyCapsule_SetDestructor(PyList_GET_ITEM(freelist, i), NULL); - } - Py_XDECREF(freelist); - return retval; + if (freelist && retval != 0) { + /* We were successful, reset the destructors so that they + don't get called. */ + Py_ssize_t len = PyList_GET_SIZE(freelist), i; + for (i = 0; i < len; i++) + PyCapsule_SetDestructor(PyList_GET_ITEM(freelist, i), NULL); + } + Py_XDECREF(freelist); + return retval; } static int vgetargs1(PyObject *args, const char *format, va_list *p_va, int flags) { - char msgbuf[256]; - int levels[32]; - const char *fname = NULL; - const char *message = NULL; - int min = -1; - int max = 0; - int level = 0; - int endfmt = 0; - const char *formatsave = format; - Py_ssize_t i, len; - char *msg; - PyObject *freelist = NULL; - int compat = flags & FLAG_COMPAT; - - assert(compat || (args != (PyObject*)NULL)); - flags = flags & ~FLAG_COMPAT; - - while (endfmt == 0) { - int c = *format++; - switch (c) { - case '(': - if (level == 0) - max++; - level++; - if (level >= 30) - Py_FatalError("too many tuple nesting levels " - "in argument format string"); - break; - case ')': - if (level == 0) - Py_FatalError("excess ')' in getargs format"); - else - level--; - break; - case '\0': - endfmt = 1; - break; - case ':': - fname = format; - endfmt = 1; - break; - case ';': - message = format; - endfmt = 1; - break; - default: - if (level == 0) { - if (c == 'O') - max++; - else if (isalpha(Py_CHARMASK(c))) { - if (c != 'e') /* skip encoded */ - max++; - } else if (c == '|') - min = max; - } - break; - } - } - - if (level != 0) - Py_FatalError(/* '(' */ "missing ')' in getargs format"); - - if (min < 0) - min = max; - - format = formatsave; - - if (compat) { - if (max == 0) { - if (args == NULL) - return 1; - PyOS_snprintf(msgbuf, sizeof(msgbuf), - "%.200s%s takes no arguments", - fname==NULL ? "function" : fname, - fname==NULL ? "" : "()"); - PyErr_SetString(PyExc_TypeError, msgbuf); - return 0; - } - else if (min == 1 && max == 1) { - if (args == NULL) { - PyOS_snprintf(msgbuf, sizeof(msgbuf), - "%.200s%s takes at least one argument", - fname==NULL ? "function" : fname, - fname==NULL ? "" : "()"); - PyErr_SetString(PyExc_TypeError, msgbuf); - return 0; - } - msg = convertitem(args, &format, p_va, flags, levels, - msgbuf, sizeof(msgbuf), &freelist); - if (msg == NULL) - return cleanreturn(1, freelist); - seterror(levels[0], msg, levels+1, fname, message); - return cleanreturn(0, freelist); - } - else { - PyErr_SetString(PyExc_SystemError, - "old style getargs format uses new features"); - return 0; - } - } - - if (!PyTuple_Check(args)) { - PyErr_SetString(PyExc_SystemError, - "new style getargs format but argument is not a tuple"); - return 0; - } - - len = PyTuple_GET_SIZE(args); - - if (len < min || max < len) { - if (message == NULL) { - PyOS_snprintf(msgbuf, sizeof(msgbuf), - "%.150s%s takes %s %d argument%s " - "(%ld given)", - fname==NULL ? "function" : fname, - fname==NULL ? "" : "()", - min==max ? "exactly" - : len < min ? "at least" : "at most", - len < min ? min : max, - (len < min ? min : max) == 1 ? "" : "s", - Py_SAFE_DOWNCAST(len, Py_ssize_t, long)); - message = msgbuf; - } - PyErr_SetString(PyExc_TypeError, message); - return 0; - } - - for (i = 0; i < len; i++) { - if (*format == '|') - format++; - msg = convertitem(PyTuple_GET_ITEM(args, i), &format, p_va, - flags, levels, msgbuf, - sizeof(msgbuf), &freelist); - if (msg) { - seterror(i+1, msg, levels, fname, msg); - return cleanreturn(0, freelist); - } - } - - if (*format != '\0' && !isalpha(Py_CHARMASK(*format)) && - *format != '(' && - *format != '|' && *format != ':' && *format != ';') { - PyErr_Format(PyExc_SystemError, - "bad format string: %.200s", formatsave); - return cleanreturn(0, freelist); - } + char msgbuf[256]; + int levels[32]; + const char *fname = NULL; + const char *message = NULL; + int min = -1; + int max = 0; + int level = 0; + int endfmt = 0; + const char *formatsave = format; + Py_ssize_t i, len; + char *msg; + PyObject *freelist = NULL; + int compat = flags & FLAG_COMPAT; + + assert(compat || (args != (PyObject*)NULL)); + flags = flags & ~FLAG_COMPAT; + + while (endfmt == 0) { + int c = *format++; + switch (c) { + case '(': + if (level == 0) + max++; + level++; + if (level >= 30) + Py_FatalError("too many tuple nesting levels " + "in argument format string"); + break; + case ')': + if (level == 0) + Py_FatalError("excess ')' in getargs format"); + else + level--; + break; + case '\0': + endfmt = 1; + break; + case ':': + fname = format; + endfmt = 1; + break; + case ';': + message = format; + endfmt = 1; + break; + default: + if (level == 0) { + if (c == 'O') + max++; + else if (isalpha(Py_CHARMASK(c))) { + if (c != 'e') /* skip encoded */ + max++; + } else if (c == '|') + min = max; + } + break; + } + } + + if (level != 0) + Py_FatalError(/* '(' */ "missing ')' in getargs format"); + + if (min < 0) + min = max; + + format = formatsave; + + if (compat) { + if (max == 0) { + if (args == NULL) + return 1; + PyOS_snprintf(msgbuf, sizeof(msgbuf), + "%.200s%s takes no arguments", + fname==NULL ? "function" : fname, + fname==NULL ? "" : "()"); + PyErr_SetString(PyExc_TypeError, msgbuf); + return 0; + } + else if (min == 1 && max == 1) { + if (args == NULL) { + PyOS_snprintf(msgbuf, sizeof(msgbuf), + "%.200s%s takes at least one argument", + fname==NULL ? "function" : fname, + fname==NULL ? "" : "()"); + PyErr_SetString(PyExc_TypeError, msgbuf); + return 0; + } + msg = convertitem(args, &format, p_va, flags, levels, + msgbuf, sizeof(msgbuf), &freelist); + if (msg == NULL) + return cleanreturn(1, freelist); + seterror(levels[0], msg, levels+1, fname, message); + return cleanreturn(0, freelist); + } + else { + PyErr_SetString(PyExc_SystemError, + "old style getargs format uses new features"); + return 0; + } + } + + if (!PyTuple_Check(args)) { + PyErr_SetString(PyExc_SystemError, + "new style getargs format but argument is not a tuple"); + return 0; + } + + len = PyTuple_GET_SIZE(args); + + if (len < min || max < len) { + if (message == NULL) { + PyOS_snprintf(msgbuf, sizeof(msgbuf), + "%.150s%s takes %s %d argument%s " + "(%ld given)", + fname==NULL ? "function" : fname, + fname==NULL ? "" : "()", + min==max ? "exactly" + : len < min ? "at least" : "at most", + len < min ? min : max, + (len < min ? min : max) == 1 ? "" : "s", + Py_SAFE_DOWNCAST(len, Py_ssize_t, long)); + message = msgbuf; + } + PyErr_SetString(PyExc_TypeError, message); + return 0; + } + + for (i = 0; i < len; i++) { + if (*format == '|') + format++; + msg = convertitem(PyTuple_GET_ITEM(args, i), &format, p_va, + flags, levels, msgbuf, + sizeof(msgbuf), &freelist); + if (msg) { + seterror(i+1, msg, levels, fname, msg); + return cleanreturn(0, freelist); + } + } + + if (*format != '\0' && !isalpha(Py_CHARMASK(*format)) && + *format != '(' && + *format != '|' && *format != ':' && *format != ';') { + PyErr_Format(PyExc_SystemError, + "bad format string: %.200s", formatsave); + return cleanreturn(0, freelist); + } - return cleanreturn(1, freelist); + return cleanreturn(1, freelist); } @@ -409,37 +409,37 @@ seterror(int iarg, const char *msg, int *levels, const char *fname, const char *message) { - char buf[512]; - int i; - char *p = buf; - - if (PyErr_Occurred()) - return; - else if (message == NULL) { - if (fname != NULL) { - PyOS_snprintf(p, sizeof(buf), "%.200s() ", fname); - p += strlen(p); - } - if (iarg != 0) { - PyOS_snprintf(p, sizeof(buf) - (p - buf), - "argument %d", iarg); - i = 0; - p += strlen(p); - while (levels[i] > 0 && i < 32 && (int)(p-buf) < 220) { - PyOS_snprintf(p, sizeof(buf) - (p - buf), - ", item %d", levels[i]-1); - p += strlen(p); - i++; - } - } - else { - PyOS_snprintf(p, sizeof(buf) - (p - buf), "argument"); - p += strlen(p); - } - PyOS_snprintf(p, sizeof(buf) - (p - buf), " %.256s", msg); - message = buf; - } - PyErr_SetString(PyExc_TypeError, message); + char buf[512]; + int i; + char *p = buf; + + if (PyErr_Occurred()) + return; + else if (message == NULL) { + if (fname != NULL) { + PyOS_snprintf(p, sizeof(buf), "%.200s() ", fname); + p += strlen(p); + } + if (iarg != 0) { + PyOS_snprintf(p, sizeof(buf) - (p - buf), + "argument %d", iarg); + i = 0; + p += strlen(p); + while (levels[i] > 0 && i < 32 && (int)(p-buf) < 220) { + PyOS_snprintf(p, sizeof(buf) - (p - buf), + ", item %d", levels[i]-1); + p += strlen(p); + i++; + } + } + else { + PyOS_snprintf(p, sizeof(buf) - (p - buf), "argument"); + p += strlen(p); + } + PyOS_snprintf(p, sizeof(buf) - (p - buf), " %.256s", msg); + message = buf; + } + PyErr_SetString(PyExc_TypeError, message); } @@ -455,9 +455,9 @@ *p_va is undefined, *levels is a 0-terminated list of item numbers, *msgbuf contains an error message, whose format is: - "must be , not ", where: - is the name of the expected type, and - is the name of the actual type, + "must be , not ", where: + is the name of the expected type, and + is the name of the actual type, and msgbuf is returned. */ @@ -466,72 +466,72 @@ int *levels, char *msgbuf, size_t bufsize, int toplevel, PyObject **freelist) { - int level = 0; - int n = 0; - const char *format = *p_format; - int i; - - for (;;) { - int c = *format++; - if (c == '(') { - if (level == 0) - n++; - level++; - } - else if (c == ')') { - if (level == 0) - break; - level--; - } - else if (c == ':' || c == ';' || c == '\0') - break; - else if (level == 0 && isalpha(Py_CHARMASK(c))) - n++; - } - - if (!PySequence_Check(arg) || PyBytes_Check(arg)) { - levels[0] = 0; - PyOS_snprintf(msgbuf, bufsize, - toplevel ? "expected %d arguments, not %.50s" : - "must be %d-item sequence, not %.50s", - n, - arg == Py_None ? "None" : arg->ob_type->tp_name); - return msgbuf; - } - - if ((i = PySequence_Size(arg)) != n) { - levels[0] = 0; - PyOS_snprintf(msgbuf, bufsize, - toplevel ? "expected %d arguments, not %d" : - "must be sequence of length %d, not %d", - n, i); - return msgbuf; - } - - format = *p_format; - for (i = 0; i < n; i++) { - char *msg; - PyObject *item; - item = PySequence_GetItem(arg, i); - if (item == NULL) { - PyErr_Clear(); - levels[0] = i+1; - levels[1] = 0; - strncpy(msgbuf, "is not retrievable", bufsize); - return msgbuf; - } - msg = convertitem(item, &format, p_va, flags, levels+1, - msgbuf, bufsize, freelist); - /* PySequence_GetItem calls tp->sq_item, which INCREFs */ - Py_XDECREF(item); - if (msg != NULL) { - levels[0] = i+1; - return msg; - } - } + int level = 0; + int n = 0; + const char *format = *p_format; + int i; + + for (;;) { + int c = *format++; + if (c == '(') { + if (level == 0) + n++; + level++; + } + else if (c == ')') { + if (level == 0) + break; + level--; + } + else if (c == ':' || c == ';' || c == '\0') + break; + else if (level == 0 && isalpha(Py_CHARMASK(c))) + n++; + } + + if (!PySequence_Check(arg) || PyBytes_Check(arg)) { + levels[0] = 0; + PyOS_snprintf(msgbuf, bufsize, + toplevel ? "expected %d arguments, not %.50s" : + "must be %d-item sequence, not %.50s", + n, + arg == Py_None ? "None" : arg->ob_type->tp_name); + return msgbuf; + } + + if ((i = PySequence_Size(arg)) != n) { + levels[0] = 0; + PyOS_snprintf(msgbuf, bufsize, + toplevel ? "expected %d arguments, not %d" : + "must be sequence of length %d, not %d", + n, i); + return msgbuf; + } + + format = *p_format; + for (i = 0; i < n; i++) { + char *msg; + PyObject *item; + item = PySequence_GetItem(arg, i); + if (item == NULL) { + PyErr_Clear(); + levels[0] = i+1; + levels[1] = 0; + strncpy(msgbuf, "is not retrievable", bufsize); + return msgbuf; + } + msg = convertitem(item, &format, p_va, flags, levels+1, + msgbuf, bufsize, freelist); + /* PySequence_GetItem calls tp->sq_item, which INCREFs */ + Py_XDECREF(item); + if (msg != NULL) { + levels[0] = i+1; + return msg; + } + } - *p_format = format; - return NULL; + *p_format = format; + return NULL; } @@ -541,43 +541,43 @@ convertitem(PyObject *arg, const char **p_format, va_list *p_va, int flags, int *levels, char *msgbuf, size_t bufsize, PyObject **freelist) { - char *msg; - const char *format = *p_format; + char *msg; + const char *format = *p_format; - if (*format == '(' /* ')' */) { - format++; - msg = converttuple(arg, &format, p_va, flags, levels, msgbuf, - bufsize, 0, freelist); - if (msg == NULL) - format++; - } - else { - msg = convertsimple(arg, &format, p_va, flags, - msgbuf, bufsize, freelist); - if (msg != NULL) - levels[0] = 0; - } - if (msg == NULL) - *p_format = format; - return msg; + if (*format == '(' /* ')' */) { + format++; + msg = converttuple(arg, &format, p_va, flags, levels, msgbuf, + bufsize, 0, freelist); + if (msg == NULL) + format++; + } + else { + msg = convertsimple(arg, &format, p_va, flags, + msgbuf, bufsize, freelist); + if (msg != NULL) + levels[0] = 0; + } + if (msg == NULL) + *p_format = format; + return msg; } #define UNICODE_DEFAULT_ENCODING(arg) \ - _PyUnicode_AsDefaultEncodedString(arg, NULL) + _PyUnicode_AsDefaultEncodedString(arg, NULL) /* Format an error message generated by convertsimple(). */ static char * converterr(const char *expected, PyObject *arg, char *msgbuf, size_t bufsize) { - assert(expected != NULL); - assert(arg != NULL); - PyOS_snprintf(msgbuf, bufsize, - "must be %.50s, not %.50s", expected, - arg == Py_None ? "None" : arg->ob_type->tp_name); - return msgbuf; + assert(expected != NULL); + assert(arg != NULL); + PyOS_snprintf(msgbuf, bufsize, + "must be %.50s, not %.50s", expected, + arg == Py_None ? "None" : arg->ob_type->tp_name); + return msgbuf; } #define CONV_UNICODE "(unicode conversion error)" @@ -587,13 +587,13 @@ static int float_argument_error(PyObject *arg) { - if (PyFloat_Check(arg)) { - PyErr_SetString(PyExc_TypeError, - "integer argument expected, got float" ); - return 1; - } - else - return 0; + if (PyFloat_Check(arg)) { + PyErr_SetString(PyExc_TypeError, + "integer argument expected, got float" ); + return 1; + } + else + return 0; } /* Convert a non-tuple argument. Return NULL if conversion went OK, @@ -609,836 +609,836 @@ convertsimple(PyObject *arg, const char **p_format, va_list *p_va, int flags, char *msgbuf, size_t bufsize, PyObject **freelist) { - /* For # codes */ -#define FETCH_SIZE int *q=NULL;Py_ssize_t *q2=NULL;\ - if (flags & FLAG_SIZE_T) q2=va_arg(*p_va, Py_ssize_t*); \ - else q=va_arg(*p_va, int*); + /* For # codes */ +#define FETCH_SIZE int *q=NULL;Py_ssize_t *q2=NULL;\ + if (flags & FLAG_SIZE_T) q2=va_arg(*p_va, Py_ssize_t*); \ + else q=va_arg(*p_va, int*); #define STORE_SIZE(s) if (flags & FLAG_SIZE_T) *q2=s; else *q=s; #define BUFFER_LEN ((flags & FLAG_SIZE_T) ? *q2:*q) - const char *format = *p_format; - char c = *format++; - PyObject *uarg; - - switch (c) { - - case 'b': { /* unsigned byte -- very short int */ - char *p = va_arg(*p_va, char *); - long ival; - if (float_argument_error(arg)) - return converterr("integer", arg, msgbuf, bufsize); - ival = PyLong_AsLong(arg); - if (ival == -1 && PyErr_Occurred()) - return converterr("integer", arg, msgbuf, bufsize); - else if (ival < 0) { - PyErr_SetString(PyExc_OverflowError, - "unsigned byte integer is less than minimum"); - return converterr("integer", arg, msgbuf, bufsize); - } - else if (ival > UCHAR_MAX) { - PyErr_SetString(PyExc_OverflowError, - "unsigned byte integer is greater than maximum"); - return converterr("integer", arg, msgbuf, bufsize); - } - else - *p = (unsigned char) ival; - break; - } - - case 'B': {/* byte sized bitfield - both signed and unsigned - values allowed */ - char *p = va_arg(*p_va, char *); - long ival; - if (float_argument_error(arg)) - return converterr("integer", arg, msgbuf, bufsize); - ival = PyLong_AsUnsignedLongMask(arg); - if (ival == -1 && PyErr_Occurred()) - return converterr("integer", arg, msgbuf, bufsize); - else - *p = (unsigned char) ival; - break; - } - - case 'h': {/* signed short int */ - short *p = va_arg(*p_va, short *); - long ival; - if (float_argument_error(arg)) - return converterr("integer", arg, msgbuf, bufsize); - ival = PyLong_AsLong(arg); - if (ival == -1 && PyErr_Occurred()) - return converterr("integer", arg, msgbuf, bufsize); - else if (ival < SHRT_MIN) { - PyErr_SetString(PyExc_OverflowError, - "signed short integer is less than minimum"); - return converterr("integer", arg, msgbuf, bufsize); - } - else if (ival > SHRT_MAX) { - PyErr_SetString(PyExc_OverflowError, - "signed short integer is greater than maximum"); - return converterr("integer", arg, msgbuf, bufsize); - } - else - *p = (short) ival; - break; - } - - case 'H': { /* short int sized bitfield, both signed and - unsigned allowed */ - unsigned short *p = va_arg(*p_va, unsigned short *); - long ival; - if (float_argument_error(arg)) - return converterr("integer", arg, msgbuf, bufsize); - ival = PyLong_AsUnsignedLongMask(arg); - if (ival == -1 && PyErr_Occurred()) - return converterr("integer", arg, msgbuf, bufsize); - else - *p = (unsigned short) ival; - break; - } - - case 'i': {/* signed int */ - int *p = va_arg(*p_va, int *); - long ival; - if (float_argument_error(arg)) - return converterr("integer", arg, msgbuf, bufsize); - ival = PyLong_AsLong(arg); - if (ival == -1 && PyErr_Occurred()) - return converterr("integer", arg, msgbuf, bufsize); - else if (ival > INT_MAX) { - PyErr_SetString(PyExc_OverflowError, - "signed integer is greater than maximum"); - return converterr("integer", arg, msgbuf, bufsize); - } - else if (ival < INT_MIN) { - PyErr_SetString(PyExc_OverflowError, - "signed integer is less than minimum"); - return converterr("integer", arg, msgbuf, bufsize); - } - else - *p = ival; - break; - } - - case 'I': { /* int sized bitfield, both signed and - unsigned allowed */ - unsigned int *p = va_arg(*p_va, unsigned int *); - unsigned int ival; - if (float_argument_error(arg)) - return converterr("integer", arg, msgbuf, bufsize); - ival = (unsigned int)PyLong_AsUnsignedLongMask(arg); - if (ival == (unsigned int)-1 && PyErr_Occurred()) - return converterr("integer", arg, msgbuf, bufsize); - else - *p = ival; - break; - } - - case 'n': /* Py_ssize_t */ - { - PyObject *iobj; - Py_ssize_t *p = va_arg(*p_va, Py_ssize_t *); - Py_ssize_t ival = -1; - if (float_argument_error(arg)) - return converterr("integer", arg, msgbuf, bufsize); - iobj = PyNumber_Index(arg); - if (iobj != NULL) { - ival = PyLong_AsSsize_t(iobj); - Py_DECREF(iobj); - } - if (ival == -1 && PyErr_Occurred()) - return converterr("integer", arg, msgbuf, bufsize); - *p = ival; - break; - } - case 'l': {/* long int */ - long *p = va_arg(*p_va, long *); - long ival; - if (float_argument_error(arg)) - return converterr("integer", arg, msgbuf, bufsize); - ival = PyLong_AsLong(arg); - if (ival == -1 && PyErr_Occurred()) - return converterr("integer", arg, msgbuf, bufsize); - else - *p = ival; - break; - } - - case 'k': { /* long sized bitfield */ - unsigned long *p = va_arg(*p_va, unsigned long *); - unsigned long ival; - if (PyLong_Check(arg)) - ival = PyLong_AsUnsignedLongMask(arg); - else - return converterr("integer", arg, msgbuf, bufsize); - *p = ival; - break; - } + const char *format = *p_format; + char c = *format++; + PyObject *uarg; + + switch (c) { + + case 'b': { /* unsigned byte -- very short int */ + char *p = va_arg(*p_va, char *); + long ival; + if (float_argument_error(arg)) + return converterr("integer", arg, msgbuf, bufsize); + ival = PyLong_AsLong(arg); + if (ival == -1 && PyErr_Occurred()) + return converterr("integer", arg, msgbuf, bufsize); + else if (ival < 0) { + PyErr_SetString(PyExc_OverflowError, + "unsigned byte integer is less than minimum"); + return converterr("integer", arg, msgbuf, bufsize); + } + else if (ival > UCHAR_MAX) { + PyErr_SetString(PyExc_OverflowError, + "unsigned byte integer is greater than maximum"); + return converterr("integer", arg, msgbuf, bufsize); + } + else + *p = (unsigned char) ival; + break; + } + + case 'B': {/* byte sized bitfield - both signed and unsigned + values allowed */ + char *p = va_arg(*p_va, char *); + long ival; + if (float_argument_error(arg)) + return converterr("integer", arg, msgbuf, bufsize); + ival = PyLong_AsUnsignedLongMask(arg); + if (ival == -1 && PyErr_Occurred()) + return converterr("integer", arg, msgbuf, bufsize); + else + *p = (unsigned char) ival; + break; + } + + case 'h': {/* signed short int */ + short *p = va_arg(*p_va, short *); + long ival; + if (float_argument_error(arg)) + return converterr("integer", arg, msgbuf, bufsize); + ival = PyLong_AsLong(arg); + if (ival == -1 && PyErr_Occurred()) + return converterr("integer", arg, msgbuf, bufsize); + else if (ival < SHRT_MIN) { + PyErr_SetString(PyExc_OverflowError, + "signed short integer is less than minimum"); + return converterr("integer", arg, msgbuf, bufsize); + } + else if (ival > SHRT_MAX) { + PyErr_SetString(PyExc_OverflowError, + "signed short integer is greater than maximum"); + return converterr("integer", arg, msgbuf, bufsize); + } + else + *p = (short) ival; + break; + } + + case 'H': { /* short int sized bitfield, both signed and + unsigned allowed */ + unsigned short *p = va_arg(*p_va, unsigned short *); + long ival; + if (float_argument_error(arg)) + return converterr("integer", arg, msgbuf, bufsize); + ival = PyLong_AsUnsignedLongMask(arg); + if (ival == -1 && PyErr_Occurred()) + return converterr("integer", arg, msgbuf, bufsize); + else + *p = (unsigned short) ival; + break; + } + + case 'i': {/* signed int */ + int *p = va_arg(*p_va, int *); + long ival; + if (float_argument_error(arg)) + return converterr("integer", arg, msgbuf, bufsize); + ival = PyLong_AsLong(arg); + if (ival == -1 && PyErr_Occurred()) + return converterr("integer", arg, msgbuf, bufsize); + else if (ival > INT_MAX) { + PyErr_SetString(PyExc_OverflowError, + "signed integer is greater than maximum"); + return converterr("integer", arg, msgbuf, bufsize); + } + else if (ival < INT_MIN) { + PyErr_SetString(PyExc_OverflowError, + "signed integer is less than minimum"); + return converterr("integer", arg, msgbuf, bufsize); + } + else + *p = ival; + break; + } + + case 'I': { /* int sized bitfield, both signed and + unsigned allowed */ + unsigned int *p = va_arg(*p_va, unsigned int *); + unsigned int ival; + if (float_argument_error(arg)) + return converterr("integer", arg, msgbuf, bufsize); + ival = (unsigned int)PyLong_AsUnsignedLongMask(arg); + if (ival == (unsigned int)-1 && PyErr_Occurred()) + return converterr("integer", arg, msgbuf, bufsize); + else + *p = ival; + break; + } + + case 'n': /* Py_ssize_t */ + { + PyObject *iobj; + Py_ssize_t *p = va_arg(*p_va, Py_ssize_t *); + Py_ssize_t ival = -1; + if (float_argument_error(arg)) + return converterr("integer", arg, msgbuf, bufsize); + iobj = PyNumber_Index(arg); + if (iobj != NULL) { + ival = PyLong_AsSsize_t(iobj); + Py_DECREF(iobj); + } + if (ival == -1 && PyErr_Occurred()) + return converterr("integer", arg, msgbuf, bufsize); + *p = ival; + break; + } + case 'l': {/* long int */ + long *p = va_arg(*p_va, long *); + long ival; + if (float_argument_error(arg)) + return converterr("integer", arg, msgbuf, bufsize); + ival = PyLong_AsLong(arg); + if (ival == -1 && PyErr_Occurred()) + return converterr("integer", arg, msgbuf, bufsize); + else + *p = ival; + break; + } + + case 'k': { /* long sized bitfield */ + unsigned long *p = va_arg(*p_va, unsigned long *); + unsigned long ival; + if (PyLong_Check(arg)) + ival = PyLong_AsUnsignedLongMask(arg); + else + return converterr("integer", arg, msgbuf, bufsize); + *p = ival; + break; + } #ifdef HAVE_LONG_LONG - case 'L': {/* PY_LONG_LONG */ - PY_LONG_LONG *p = va_arg( *p_va, PY_LONG_LONG * ); - PY_LONG_LONG ival = PyLong_AsLongLong( arg ); - if (ival == (PY_LONG_LONG)-1 && PyErr_Occurred() ) { - return converterr("long", arg, msgbuf, bufsize); - } else { - *p = ival; - } - break; - } - - case 'K': { /* long long sized bitfield */ - unsigned PY_LONG_LONG *p = va_arg(*p_va, unsigned PY_LONG_LONG *); - unsigned PY_LONG_LONG ival; - if (PyLong_Check(arg)) - ival = PyLong_AsUnsignedLongLongMask(arg); - else - return converterr("integer", arg, msgbuf, bufsize); - *p = ival; - break; - } + case 'L': {/* PY_LONG_LONG */ + PY_LONG_LONG *p = va_arg( *p_va, PY_LONG_LONG * ); + PY_LONG_LONG ival = PyLong_AsLongLong( arg ); + if (ival == (PY_LONG_LONG)-1 && PyErr_Occurred() ) { + return converterr("long", arg, msgbuf, bufsize); + } else { + *p = ival; + } + break; + } + + case 'K': { /* long long sized bitfield */ + unsigned PY_LONG_LONG *p = va_arg(*p_va, unsigned PY_LONG_LONG *); + unsigned PY_LONG_LONG ival; + if (PyLong_Check(arg)) + ival = PyLong_AsUnsignedLongLongMask(arg); + else + return converterr("integer", arg, msgbuf, bufsize); + *p = ival; + break; + } #endif - case 'f': {/* float */ - float *p = va_arg(*p_va, float *); - double dval = PyFloat_AsDouble(arg); - if (PyErr_Occurred()) - return converterr("float", arg, msgbuf, bufsize); - else - *p = (float) dval; - break; - } - - case 'd': {/* double */ - double *p = va_arg(*p_va, double *); - double dval = PyFloat_AsDouble(arg); - if (PyErr_Occurred()) - return converterr("float", arg, msgbuf, bufsize); - else - *p = dval; - break; - } + case 'f': {/* float */ + float *p = va_arg(*p_va, float *); + double dval = PyFloat_AsDouble(arg); + if (PyErr_Occurred()) + return converterr("float", arg, msgbuf, bufsize); + else + *p = (float) dval; + break; + } + + case 'd': {/* double */ + double *p = va_arg(*p_va, double *); + double dval = PyFloat_AsDouble(arg); + if (PyErr_Occurred()) + return converterr("float", arg, msgbuf, bufsize); + else + *p = dval; + break; + } #ifndef WITHOUT_COMPLEX - case 'D': {/* complex double */ - Py_complex *p = va_arg(*p_va, Py_complex *); - Py_complex cval; - cval = PyComplex_AsCComplex(arg); - if (PyErr_Occurred()) - return converterr("complex", arg, msgbuf, bufsize); - else - *p = cval; - break; - } + case 'D': {/* complex double */ + Py_complex *p = va_arg(*p_va, Py_complex *); + Py_complex cval; + cval = PyComplex_AsCComplex(arg); + if (PyErr_Occurred()) + return converterr("complex", arg, msgbuf, bufsize); + else + *p = cval; + break; + } #endif /* WITHOUT_COMPLEX */ - case 'c': {/* char */ - char *p = va_arg(*p_va, char *); - if (PyBytes_Check(arg) && PyBytes_Size(arg) == 1) - *p = PyBytes_AS_STRING(arg)[0]; - else - return converterr("a byte string of length 1", arg, msgbuf, bufsize); - break; - } - - case 'C': {/* unicode char */ - int *p = va_arg(*p_va, int *); - if (PyUnicode_Check(arg) && - PyUnicode_GET_SIZE(arg) == 1) - *p = PyUnicode_AS_UNICODE(arg)[0]; - else - return converterr("a unicode character", arg, msgbuf, bufsize); - break; - } - - /* XXX WAAAAH! 's', 'y', 'z', 'u', 'Z', 'e', 'w', 't' codes all - need to be cleaned up! */ - - case 's': {/* text string */ - if (*format == '*') { - Py_buffer *p = (Py_buffer *)va_arg(*p_va, Py_buffer *); - - if (PyUnicode_Check(arg)) { - uarg = UNICODE_DEFAULT_ENCODING(arg); - if (uarg == NULL) - return converterr(CONV_UNICODE, - arg, msgbuf, bufsize); - PyBuffer_FillInfo(p, arg, - PyBytes_AS_STRING(uarg), PyBytes_GET_SIZE(uarg), - 1, 0); - } - else { /* any buffer-like object */ - char *buf; - if (getbuffer(arg, p, &buf) < 0) - return converterr(buf, arg, msgbuf, bufsize); - } - if (addcleanup(p, freelist, cleanup_buffer)) { - return converterr( - "(cleanup problem)", - arg, msgbuf, bufsize); - } - format++; - } else if (*format == '#') { - void **p = (void **)va_arg(*p_va, char **); - FETCH_SIZE; - - if (PyUnicode_Check(arg)) { - uarg = UNICODE_DEFAULT_ENCODING(arg); - if (uarg == NULL) - return converterr(CONV_UNICODE, - arg, msgbuf, bufsize); - *p = PyBytes_AS_STRING(uarg); - STORE_SIZE(PyBytes_GET_SIZE(uarg)); - } - else { /* any buffer-like object */ - /* XXX Really? */ - char *buf; - Py_ssize_t count = convertbuffer(arg, p, &buf); - if (count < 0) - return converterr(buf, arg, msgbuf, bufsize); - STORE_SIZE(count); - } - format++; - } else { - char **p = va_arg(*p_va, char **); - - if (PyUnicode_Check(arg)) { - uarg = UNICODE_DEFAULT_ENCODING(arg); - if (uarg == NULL) - return converterr(CONV_UNICODE, - arg, msgbuf, bufsize); - *p = PyBytes_AS_STRING(uarg); - } - else - return converterr("string", arg, msgbuf, bufsize); - if ((Py_ssize_t) strlen(*p) != PyBytes_GET_SIZE(uarg)) - return converterr("string without null bytes", - arg, msgbuf, bufsize); - } - break; - } - - case 'y': {/* any buffer-like object, but not PyUnicode */ - void **p = (void **)va_arg(*p_va, char **); - char *buf; - Py_ssize_t count; - if (*format == '*') { - if (getbuffer(arg, (Py_buffer*)p, &buf) < 0) - return converterr(buf, arg, msgbuf, bufsize); - format++; - if (addcleanup(p, freelist, cleanup_buffer)) { - return converterr( - "(cleanup problem)", - arg, msgbuf, bufsize); - } - break; - } - count = convertbuffer(arg, p, &buf); - if (count < 0) - return converterr(buf, arg, msgbuf, bufsize); - else if (*format == '#') { - FETCH_SIZE; - STORE_SIZE(count); - format++; - } - break; - } - - case 'z': {/* like 's' or 's#', but None is okay, stored as NULL */ - if (*format == '*') { - Py_buffer *p = (Py_buffer *)va_arg(*p_va, Py_buffer *); - - if (arg == Py_None) - PyBuffer_FillInfo(p, NULL, NULL, 0, 1, 0); - else if (PyUnicode_Check(arg)) { - uarg = UNICODE_DEFAULT_ENCODING(arg); - if (uarg == NULL) - return converterr(CONV_UNICODE, - arg, msgbuf, bufsize); - PyBuffer_FillInfo(p, arg, - PyBytes_AS_STRING(uarg), PyBytes_GET_SIZE(uarg), - 1, 0); - } - else { /* any buffer-like object */ - char *buf; - if (getbuffer(arg, p, &buf) < 0) - return converterr(buf, arg, msgbuf, bufsize); - } - if (addcleanup(p, freelist, cleanup_buffer)) { - return converterr( - "(cleanup problem)", - arg, msgbuf, bufsize); - } - format++; - } else if (*format == '#') { /* any buffer-like object */ - void **p = (void **)va_arg(*p_va, char **); - FETCH_SIZE; - - if (arg == Py_None) { - *p = 0; - STORE_SIZE(0); - } - else if (PyUnicode_Check(arg)) { - uarg = UNICODE_DEFAULT_ENCODING(arg); - if (uarg == NULL) - return converterr(CONV_UNICODE, - arg, msgbuf, bufsize); - *p = PyBytes_AS_STRING(uarg); - STORE_SIZE(PyBytes_GET_SIZE(uarg)); - } - else { /* any buffer-like object */ - /* XXX Really? */ - char *buf; - Py_ssize_t count = convertbuffer(arg, p, &buf); - if (count < 0) - return converterr(buf, arg, msgbuf, bufsize); - STORE_SIZE(count); - } - format++; - } else { - char **p = va_arg(*p_va, char **); - uarg = NULL; - - if (arg == Py_None) - *p = 0; - else if (PyBytes_Check(arg)) { - /* Enable null byte check below */ - uarg = arg; - *p = PyBytes_AS_STRING(arg); - } - else if (PyUnicode_Check(arg)) { - uarg = UNICODE_DEFAULT_ENCODING(arg); - if (uarg == NULL) - return converterr(CONV_UNICODE, - arg, msgbuf, bufsize); - *p = PyBytes_AS_STRING(uarg); - } - else - return converterr("string or None", - arg, msgbuf, bufsize); - if (*format == '#') { - FETCH_SIZE; - assert(0); /* XXX redundant with if-case */ - if (arg == Py_None) { - STORE_SIZE(0); - } - else { - STORE_SIZE(PyBytes_Size(arg)); - } - format++; - } - else if (*p != NULL && uarg != NULL && - (Py_ssize_t) strlen(*p) != PyBytes_GET_SIZE(uarg)) - return converterr( - "string without null bytes or None", - arg, msgbuf, bufsize); - } - break; - } - - case 'Z': {/* unicode, may be NULL (None) */ - if (*format == '#') { /* any buffer-like object */ - Py_UNICODE **p = va_arg(*p_va, Py_UNICODE **); - FETCH_SIZE; - - if (arg == Py_None) { - *p = 0; - STORE_SIZE(0); - } - else if (PyUnicode_Check(arg)) { - *p = PyUnicode_AS_UNICODE(arg); - STORE_SIZE(PyUnicode_GET_SIZE(arg)); - } - format++; - } else { - Py_UNICODE **p = va_arg(*p_va, Py_UNICODE **); - - if (arg == Py_None) - *p = 0; - else if (PyUnicode_Check(arg)) - *p = PyUnicode_AS_UNICODE(arg); - else - return converterr("string or None", - arg, msgbuf, bufsize); - } - break; - } - - case 'e': {/* encoded string */ - char **buffer; - const char *encoding; - PyObject *s; - int recode_strings; - Py_ssize_t size; - const char *ptr; - - /* Get 'e' parameter: the encoding name */ - encoding = (const char *)va_arg(*p_va, const char *); - if (encoding == NULL) - encoding = PyUnicode_GetDefaultEncoding(); - - /* Get output buffer parameter: - 's' (recode all objects via Unicode) or - 't' (only recode non-string objects) - */ - if (*format == 's') - recode_strings = 1; - else if (*format == 't') - recode_strings = 0; - else - return converterr( - "(unknown parser marker combination)", - arg, msgbuf, bufsize); - buffer = (char **)va_arg(*p_va, char **); - format++; - if (buffer == NULL) - return converterr("(buffer is NULL)", - arg, msgbuf, bufsize); - - /* Encode object */ - if (!recode_strings && - (PyBytes_Check(arg) || PyByteArray_Check(arg))) { - s = arg; - Py_INCREF(s); - if (PyObject_AsCharBuffer(s, &ptr, &size) < 0) - return converterr("(AsCharBuffer failed)", - arg, msgbuf, bufsize); - } - else { - PyObject *u; - - /* Convert object to Unicode */ - u = PyUnicode_FromObject(arg); - if (u == NULL) - return converterr( - "string or unicode or text buffer", - arg, msgbuf, bufsize); - - /* Encode object; use default error handling */ - s = PyUnicode_AsEncodedString(u, - encoding, - NULL); - Py_DECREF(u); - if (s == NULL) - return converterr("(encoding failed)", - arg, msgbuf, bufsize); - if (!PyBytes_Check(s)) { - Py_DECREF(s); - return converterr( - "(encoder failed to return bytes)", - arg, msgbuf, bufsize); - } - size = PyBytes_GET_SIZE(s); - ptr = PyBytes_AS_STRING(s); - if (ptr == NULL) - ptr = ""; - } - - /* Write output; output is guaranteed to be 0-terminated */ - if (*format == '#') { - /* Using buffer length parameter '#': - - - if *buffer is NULL, a new buffer of the - needed size is allocated and the data - copied into it; *buffer is updated to point - to the new buffer; the caller is - responsible for PyMem_Free()ing it after - usage - - - if *buffer is not NULL, the data is - copied to *buffer; *buffer_len has to be - set to the size of the buffer on input; - buffer overflow is signalled with an error; - buffer has to provide enough room for the - encoded string plus the trailing 0-byte - - - in both cases, *buffer_len is updated to - the size of the buffer /excluding/ the - trailing 0-byte - - */ - FETCH_SIZE; - - format++; - if (q == NULL && q2 == NULL) { - Py_DECREF(s); - return converterr( - "(buffer_len is NULL)", - arg, msgbuf, bufsize); - } - if (*buffer == NULL) { - *buffer = PyMem_NEW(char, size + 1); - if (*buffer == NULL) { - Py_DECREF(s); - return converterr( - "(memory error)", - arg, msgbuf, bufsize); - } - if (addcleanup(*buffer, freelist, cleanup_ptr)) { - Py_DECREF(s); - return converterr( - "(cleanup problem)", - arg, msgbuf, bufsize); - } - } else { - if (size + 1 > BUFFER_LEN) { - Py_DECREF(s); - return converterr( - "(buffer overflow)", - arg, msgbuf, bufsize); - } - } - memcpy(*buffer, ptr, size+1); - STORE_SIZE(size); - } else { - /* Using a 0-terminated buffer: - - - the encoded string has to be 0-terminated - for this variant to work; if it is not, an - error raised - - - a new buffer of the needed size is - allocated and the data copied into it; - *buffer is updated to point to the new - buffer; the caller is responsible for - PyMem_Free()ing it after usage - - */ - if ((Py_ssize_t)strlen(ptr) != size) { - Py_DECREF(s); - return converterr( - "encoded string without NULL bytes", - arg, msgbuf, bufsize); - } - *buffer = PyMem_NEW(char, size + 1); - if (*buffer == NULL) { - Py_DECREF(s); - return converterr("(memory error)", - arg, msgbuf, bufsize); - } - if (addcleanup(*buffer, freelist, cleanup_ptr)) { - Py_DECREF(s); - return converterr("(cleanup problem)", - arg, msgbuf, bufsize); - } - memcpy(*buffer, ptr, size+1); - } - Py_DECREF(s); - break; - } - - case 'u': {/* raw unicode buffer (Py_UNICODE *) */ - Py_UNICODE **p = va_arg(*p_va, Py_UNICODE **); - if (!PyUnicode_Check(arg)) - return converterr("str", arg, msgbuf, bufsize); - *p = PyUnicode_AS_UNICODE(arg); - if (*format == '#') { /* store pointer and size */ - FETCH_SIZE; - STORE_SIZE(PyUnicode_GET_SIZE(arg)); - format++; - } - break; - } - - case 'S': { /* PyBytes object */ - PyObject **p = va_arg(*p_va, PyObject **); - if (PyBytes_Check(arg)) - *p = arg; - else - return converterr("bytes", arg, msgbuf, bufsize); - break; - } - - case 'Y': { /* PyByteArray object */ - PyObject **p = va_arg(*p_va, PyObject **); - if (PyByteArray_Check(arg)) - *p = arg; - else - return converterr("buffer", arg, msgbuf, bufsize); - break; - } - - case 'U': { /* PyUnicode object */ - PyObject **p = va_arg(*p_va, PyObject **); - if (PyUnicode_Check(arg)) - *p = arg; - else - return converterr("str", arg, msgbuf, bufsize); - break; - } - - case 'O': { /* object */ - PyTypeObject *type; - PyObject **p; - if (*format == '!') { - type = va_arg(*p_va, PyTypeObject*); - p = va_arg(*p_va, PyObject **); - format++; - if (PyType_IsSubtype(arg->ob_type, type)) - *p = arg; - else - return converterr(type->tp_name, arg, msgbuf, bufsize); - - } - else if (*format == '?') { - inquiry pred = va_arg(*p_va, inquiry); - p = va_arg(*p_va, PyObject **); - format++; - if ((*pred)(arg)) - *p = arg; - else - return converterr("(unspecified)", - arg, msgbuf, bufsize); - - } - else if (*format == '&') { - typedef int (*converter)(PyObject *, void *); - converter convert = va_arg(*p_va, converter); - void *addr = va_arg(*p_va, void *); - int res; - format++; - if (! (res = (*convert)(arg, addr))) - return converterr("(unspecified)", - arg, msgbuf, bufsize); - if (res == Py_CLEANUP_SUPPORTED && - addcleanup_convert(addr, freelist, convert) == -1) - return converterr("(cleanup problem)", - arg, msgbuf, bufsize); - } - else { - p = va_arg(*p_va, PyObject **); - *p = arg; - } - break; - } - - - case 'w': { /* memory buffer, read-write access */ - void **p = va_arg(*p_va, void **); - PyBufferProcs *pb = arg->ob_type->tp_as_buffer; - Py_ssize_t count; - int temp=-1; - Py_buffer view; - - if (pb && pb->bf_releasebuffer && *format != '*') - /* Buffer must be released, yet caller does not use - the Py_buffer protocol. */ - return converterr("pinned buffer", arg, msgbuf, bufsize); - - - if (pb && pb->bf_getbuffer && *format == '*') { - /* Caller is interested in Py_buffer, and the object - supports it directly. */ - format++; - if (PyObject_GetBuffer(arg, (Py_buffer*)p, PyBUF_WRITABLE) < 0) { - PyErr_Clear(); - return converterr("read-write buffer", arg, msgbuf, bufsize); - } - if (addcleanup(p, freelist, cleanup_buffer)) { - return converterr( - "(cleanup problem)", - arg, msgbuf, bufsize); - } - if (!PyBuffer_IsContiguous((Py_buffer*)p, 'C')) - return converterr("contiguous buffer", arg, msgbuf, bufsize); - break; - } - - /* Here we have processed w*, only w and w# remain. */ - if (pb == NULL || - pb->bf_getbuffer == NULL || - ((temp = PyObject_GetBuffer(arg, &view, - PyBUF_SIMPLE)) != 0) || - view.readonly == 1) { - if (temp==0) { - PyBuffer_Release(&view); - } - return converterr("single-segment read-write buffer", - arg, msgbuf, bufsize); + case 'c': {/* char */ + char *p = va_arg(*p_va, char *); + if (PyBytes_Check(arg) && PyBytes_Size(arg) == 1) + *p = PyBytes_AS_STRING(arg)[0]; + else + return converterr("a byte string of length 1", arg, msgbuf, bufsize); + break; + } + + case 'C': {/* unicode char */ + int *p = va_arg(*p_va, int *); + if (PyUnicode_Check(arg) && + PyUnicode_GET_SIZE(arg) == 1) + *p = PyUnicode_AS_UNICODE(arg)[0]; + else + return converterr("a unicode character", arg, msgbuf, bufsize); + break; + } + + /* XXX WAAAAH! 's', 'y', 'z', 'u', 'Z', 'e', 'w', 't' codes all + need to be cleaned up! */ + + case 's': {/* text string */ + if (*format == '*') { + Py_buffer *p = (Py_buffer *)va_arg(*p_va, Py_buffer *); + + if (PyUnicode_Check(arg)) { + uarg = UNICODE_DEFAULT_ENCODING(arg); + if (uarg == NULL) + return converterr(CONV_UNICODE, + arg, msgbuf, bufsize); + PyBuffer_FillInfo(p, arg, + PyBytes_AS_STRING(uarg), PyBytes_GET_SIZE(uarg), + 1, 0); + } + else { /* any buffer-like object */ + char *buf; + if (getbuffer(arg, p, &buf) < 0) + return converterr(buf, arg, msgbuf, bufsize); + } + if (addcleanup(p, freelist, cleanup_buffer)) { + return converterr( + "(cleanup problem)", + arg, msgbuf, bufsize); + } + format++; + } else if (*format == '#') { + void **p = (void **)va_arg(*p_va, char **); + FETCH_SIZE; + + if (PyUnicode_Check(arg)) { + uarg = UNICODE_DEFAULT_ENCODING(arg); + if (uarg == NULL) + return converterr(CONV_UNICODE, + arg, msgbuf, bufsize); + *p = PyBytes_AS_STRING(uarg); + STORE_SIZE(PyBytes_GET_SIZE(uarg)); + } + else { /* any buffer-like object */ + /* XXX Really? */ + char *buf; + Py_ssize_t count = convertbuffer(arg, p, &buf); + if (count < 0) + return converterr(buf, arg, msgbuf, bufsize); + STORE_SIZE(count); + } + format++; + } else { + char **p = va_arg(*p_va, char **); + + if (PyUnicode_Check(arg)) { + uarg = UNICODE_DEFAULT_ENCODING(arg); + if (uarg == NULL) + return converterr(CONV_UNICODE, + arg, msgbuf, bufsize); + *p = PyBytes_AS_STRING(uarg); + } + else + return converterr("string", arg, msgbuf, bufsize); + if ((Py_ssize_t) strlen(*p) != PyBytes_GET_SIZE(uarg)) + return converterr("string without null bytes", + arg, msgbuf, bufsize); + } + break; + } + + case 'y': {/* any buffer-like object, but not PyUnicode */ + void **p = (void **)va_arg(*p_va, char **); + char *buf; + Py_ssize_t count; + if (*format == '*') { + if (getbuffer(arg, (Py_buffer*)p, &buf) < 0) + return converterr(buf, arg, msgbuf, bufsize); + format++; + if (addcleanup(p, freelist, cleanup_buffer)) { + return converterr( + "(cleanup problem)", + arg, msgbuf, bufsize); + } + break; + } + count = convertbuffer(arg, p, &buf); + if (count < 0) + return converterr(buf, arg, msgbuf, bufsize); + else if (*format == '#') { + FETCH_SIZE; + STORE_SIZE(count); + format++; + } + break; + } + + case 'z': {/* like 's' or 's#', but None is okay, stored as NULL */ + if (*format == '*') { + Py_buffer *p = (Py_buffer *)va_arg(*p_va, Py_buffer *); + + if (arg == Py_None) + PyBuffer_FillInfo(p, NULL, NULL, 0, 1, 0); + else if (PyUnicode_Check(arg)) { + uarg = UNICODE_DEFAULT_ENCODING(arg); + if (uarg == NULL) + return converterr(CONV_UNICODE, + arg, msgbuf, bufsize); + PyBuffer_FillInfo(p, arg, + PyBytes_AS_STRING(uarg), PyBytes_GET_SIZE(uarg), + 1, 0); + } + else { /* any buffer-like object */ + char *buf; + if (getbuffer(arg, p, &buf) < 0) + return converterr(buf, arg, msgbuf, bufsize); + } + if (addcleanup(p, freelist, cleanup_buffer)) { + return converterr( + "(cleanup problem)", + arg, msgbuf, bufsize); + } + format++; + } else if (*format == '#') { /* any buffer-like object */ + void **p = (void **)va_arg(*p_va, char **); + FETCH_SIZE; + + if (arg == Py_None) { + *p = 0; + STORE_SIZE(0); + } + else if (PyUnicode_Check(arg)) { + uarg = UNICODE_DEFAULT_ENCODING(arg); + if (uarg == NULL) + return converterr(CONV_UNICODE, + arg, msgbuf, bufsize); + *p = PyBytes_AS_STRING(uarg); + STORE_SIZE(PyBytes_GET_SIZE(uarg)); + } + else { /* any buffer-like object */ + /* XXX Really? */ + char *buf; + Py_ssize_t count = convertbuffer(arg, p, &buf); + if (count < 0) + return converterr(buf, arg, msgbuf, bufsize); + STORE_SIZE(count); + } + format++; + } else { + char **p = va_arg(*p_va, char **); + uarg = NULL; + + if (arg == Py_None) + *p = 0; + else if (PyBytes_Check(arg)) { + /* Enable null byte check below */ + uarg = arg; + *p = PyBytes_AS_STRING(arg); + } + else if (PyUnicode_Check(arg)) { + uarg = UNICODE_DEFAULT_ENCODING(arg); + if (uarg == NULL) + return converterr(CONV_UNICODE, + arg, msgbuf, bufsize); + *p = PyBytes_AS_STRING(uarg); + } + else + return converterr("string or None", + arg, msgbuf, bufsize); + if (*format == '#') { + FETCH_SIZE; + assert(0); /* XXX redundant with if-case */ + if (arg == Py_None) { + STORE_SIZE(0); + } + else { + STORE_SIZE(PyBytes_Size(arg)); + } + format++; + } + else if (*p != NULL && uarg != NULL && + (Py_ssize_t) strlen(*p) != PyBytes_GET_SIZE(uarg)) + return converterr( + "string without null bytes or None", + arg, msgbuf, bufsize); + } + break; + } + + case 'Z': {/* unicode, may be NULL (None) */ + if (*format == '#') { /* any buffer-like object */ + Py_UNICODE **p = va_arg(*p_va, Py_UNICODE **); + FETCH_SIZE; + + if (arg == Py_None) { + *p = 0; + STORE_SIZE(0); + } + else if (PyUnicode_Check(arg)) { + *p = PyUnicode_AS_UNICODE(arg); + STORE_SIZE(PyUnicode_GET_SIZE(arg)); + } + format++; + } else { + Py_UNICODE **p = va_arg(*p_va, Py_UNICODE **); + + if (arg == Py_None) + *p = 0; + else if (PyUnicode_Check(arg)) + *p = PyUnicode_AS_UNICODE(arg); + else + return converterr("string or None", + arg, msgbuf, bufsize); + } + break; + } + + case 'e': {/* encoded string */ + char **buffer; + const char *encoding; + PyObject *s; + int recode_strings; + Py_ssize_t size; + const char *ptr; + + /* Get 'e' parameter: the encoding name */ + encoding = (const char *)va_arg(*p_va, const char *); + if (encoding == NULL) + encoding = PyUnicode_GetDefaultEncoding(); + + /* Get output buffer parameter: + 's' (recode all objects via Unicode) or + 't' (only recode non-string objects) + */ + if (*format == 's') + recode_strings = 1; + else if (*format == 't') + recode_strings = 0; + else + return converterr( + "(unknown parser marker combination)", + arg, msgbuf, bufsize); + buffer = (char **)va_arg(*p_va, char **); + format++; + if (buffer == NULL) + return converterr("(buffer is NULL)", + arg, msgbuf, bufsize); + + /* Encode object */ + if (!recode_strings && + (PyBytes_Check(arg) || PyByteArray_Check(arg))) { + s = arg; + Py_INCREF(s); + if (PyObject_AsCharBuffer(s, &ptr, &size) < 0) + return converterr("(AsCharBuffer failed)", + arg, msgbuf, bufsize); + } + else { + PyObject *u; + + /* Convert object to Unicode */ + u = PyUnicode_FromObject(arg); + if (u == NULL) + return converterr( + "string or unicode or text buffer", + arg, msgbuf, bufsize); + + /* Encode object; use default error handling */ + s = PyUnicode_AsEncodedString(u, + encoding, + NULL); + Py_DECREF(u); + if (s == NULL) + return converterr("(encoding failed)", + arg, msgbuf, bufsize); + if (!PyBytes_Check(s)) { + Py_DECREF(s); + return converterr( + "(encoder failed to return bytes)", + arg, msgbuf, bufsize); + } + size = PyBytes_GET_SIZE(s); + ptr = PyBytes_AS_STRING(s); + if (ptr == NULL) + ptr = ""; + } + + /* Write output; output is guaranteed to be 0-terminated */ + if (*format == '#') { + /* Using buffer length parameter '#': + + - if *buffer is NULL, a new buffer of the + needed size is allocated and the data + copied into it; *buffer is updated to point + to the new buffer; the caller is + responsible for PyMem_Free()ing it after + usage + + - if *buffer is not NULL, the data is + copied to *buffer; *buffer_len has to be + set to the size of the buffer on input; + buffer overflow is signalled with an error; + buffer has to provide enough room for the + encoded string plus the trailing 0-byte + + - in both cases, *buffer_len is updated to + the size of the buffer /excluding/ the + trailing 0-byte + + */ + FETCH_SIZE; + + format++; + if (q == NULL && q2 == NULL) { + Py_DECREF(s); + return converterr( + "(buffer_len is NULL)", + arg, msgbuf, bufsize); + } + if (*buffer == NULL) { + *buffer = PyMem_NEW(char, size + 1); + if (*buffer == NULL) { + Py_DECREF(s); + return converterr( + "(memory error)", + arg, msgbuf, bufsize); + } + if (addcleanup(*buffer, freelist, cleanup_ptr)) { + Py_DECREF(s); + return converterr( + "(cleanup problem)", + arg, msgbuf, bufsize); + } + } else { + if (size + 1 > BUFFER_LEN) { + Py_DECREF(s); + return converterr( + "(buffer overflow)", + arg, msgbuf, bufsize); } + } + memcpy(*buffer, ptr, size+1); + STORE_SIZE(size); + } else { + /* Using a 0-terminated buffer: + + - the encoded string has to be 0-terminated + for this variant to work; if it is not, an + error raised + + - a new buffer of the needed size is + allocated and the data copied into it; + *buffer is updated to point to the new + buffer; the caller is responsible for + PyMem_Free()ing it after usage + + */ + if ((Py_ssize_t)strlen(ptr) != size) { + Py_DECREF(s); + return converterr( + "encoded string without NULL bytes", + arg, msgbuf, bufsize); + } + *buffer = PyMem_NEW(char, size + 1); + if (*buffer == NULL) { + Py_DECREF(s); + return converterr("(memory error)", + arg, msgbuf, bufsize); + } + if (addcleanup(*buffer, freelist, cleanup_ptr)) { + Py_DECREF(s); + return converterr("(cleanup problem)", + arg, msgbuf, bufsize); + } + memcpy(*buffer, ptr, size+1); + } + Py_DECREF(s); + break; + } + + case 'u': {/* raw unicode buffer (Py_UNICODE *) */ + Py_UNICODE **p = va_arg(*p_va, Py_UNICODE **); + if (!PyUnicode_Check(arg)) + return converterr("str", arg, msgbuf, bufsize); + *p = PyUnicode_AS_UNICODE(arg); + if (*format == '#') { /* store pointer and size */ + FETCH_SIZE; + STORE_SIZE(PyUnicode_GET_SIZE(arg)); + format++; + } + break; + } + + case 'S': { /* PyBytes object */ + PyObject **p = va_arg(*p_va, PyObject **); + if (PyBytes_Check(arg)) + *p = arg; + else + return converterr("bytes", arg, msgbuf, bufsize); + break; + } + + case 'Y': { /* PyByteArray object */ + PyObject **p = va_arg(*p_va, PyObject **); + if (PyByteArray_Check(arg)) + *p = arg; + else + return converterr("buffer", arg, msgbuf, bufsize); + break; + } + + case 'U': { /* PyUnicode object */ + PyObject **p = va_arg(*p_va, PyObject **); + if (PyUnicode_Check(arg)) + *p = arg; + else + return converterr("str", arg, msgbuf, bufsize); + break; + } + + case 'O': { /* object */ + PyTypeObject *type; + PyObject **p; + if (*format == '!') { + type = va_arg(*p_va, PyTypeObject*); + p = va_arg(*p_va, PyObject **); + format++; + if (PyType_IsSubtype(arg->ob_type, type)) + *p = arg; + else + return converterr(type->tp_name, arg, msgbuf, bufsize); + + } + else if (*format == '?') { + inquiry pred = va_arg(*p_va, inquiry); + p = va_arg(*p_va, PyObject **); + format++; + if ((*pred)(arg)) + *p = arg; + else + return converterr("(unspecified)", + arg, msgbuf, bufsize); + + } + else if (*format == '&') { + typedef int (*converter)(PyObject *, void *); + converter convert = va_arg(*p_va, converter); + void *addr = va_arg(*p_va, void *); + int res; + format++; + if (! (res = (*convert)(arg, addr))) + return converterr("(unspecified)", + arg, msgbuf, bufsize); + if (res == Py_CLEANUP_SUPPORTED && + addcleanup_convert(addr, freelist, convert) == -1) + return converterr("(cleanup problem)", + arg, msgbuf, bufsize); + } + else { + p = va_arg(*p_va, PyObject **); + *p = arg; + } + break; + } + + + case 'w': { /* memory buffer, read-write access */ + void **p = va_arg(*p_va, void **); + PyBufferProcs *pb = arg->ob_type->tp_as_buffer; + Py_ssize_t count; + int temp=-1; + Py_buffer view; - if ((count = view.len) < 0) - return converterr("(unspecified)", arg, msgbuf, bufsize); - *p = view.buf; - if (*format == '#') { - FETCH_SIZE; - STORE_SIZE(count); - format++; - } - break; - } - - /*TEO: This can be eliminated --- here only for backward - compatibility */ - case 't': { /* 8-bit character buffer, read-only access */ - char **p = va_arg(*p_va, char **); - PyBufferProcs *pb = arg->ob_type->tp_as_buffer; - Py_ssize_t count; - Py_buffer view; - - if (*format++ != '#') - return converterr( - "invalid use of 't' format character", - arg, msgbuf, bufsize); - if (pb == NULL || pb->bf_getbuffer == NULL) - return converterr( - "bytes or read-only character buffer", - arg, msgbuf, bufsize); - - if (PyObject_GetBuffer(arg, &view, PyBUF_SIMPLE) != 0) - return converterr("string or single-segment read-only buffer", - arg, msgbuf, bufsize); - - count = view.len; - *p = view.buf; - if (pb->bf_releasebuffer) - return converterr( - "string or pinned buffer", - arg, msgbuf, bufsize); - - PyBuffer_Release(&view); - - if (count < 0) - return converterr("(unspecified)", arg, msgbuf, bufsize); - { - FETCH_SIZE; - STORE_SIZE(count); - } - break; - } + if (pb && pb->bf_releasebuffer && *format != '*') + /* Buffer must be released, yet caller does not use + the Py_buffer protocol. */ + return converterr("pinned buffer", arg, msgbuf, bufsize); + + + if (pb && pb->bf_getbuffer && *format == '*') { + /* Caller is interested in Py_buffer, and the object + supports it directly. */ + format++; + if (PyObject_GetBuffer(arg, (Py_buffer*)p, PyBUF_WRITABLE) < 0) { + PyErr_Clear(); + return converterr("read-write buffer", arg, msgbuf, bufsize); + } + if (addcleanup(p, freelist, cleanup_buffer)) { + return converterr( + "(cleanup problem)", + arg, msgbuf, bufsize); + } + if (!PyBuffer_IsContiguous((Py_buffer*)p, 'C')) + return converterr("contiguous buffer", arg, msgbuf, bufsize); + break; + } + + /* Here we have processed w*, only w and w# remain. */ + if (pb == NULL || + pb->bf_getbuffer == NULL || + ((temp = PyObject_GetBuffer(arg, &view, + PyBUF_SIMPLE)) != 0) || + view.readonly == 1) { + if (temp==0) { + PyBuffer_Release(&view); + } + return converterr("single-segment read-write buffer", + arg, msgbuf, bufsize); + } - default: - return converterr("impossible", arg, msgbuf, bufsize); + if ((count = view.len) < 0) + return converterr("(unspecified)", arg, msgbuf, bufsize); + *p = view.buf; + if (*format == '#') { + FETCH_SIZE; + STORE_SIZE(count); + format++; + } + break; + } + + /*TEO: This can be eliminated --- here only for backward + compatibility */ + case 't': { /* 8-bit character buffer, read-only access */ + char **p = va_arg(*p_va, char **); + PyBufferProcs *pb = arg->ob_type->tp_as_buffer; + Py_ssize_t count; + Py_buffer view; - } + if (*format++ != '#') + return converterr( + "invalid use of 't' format character", + arg, msgbuf, bufsize); + if (pb == NULL || pb->bf_getbuffer == NULL) + return converterr( + "bytes or read-only character buffer", + arg, msgbuf, bufsize); + + if (PyObject_GetBuffer(arg, &view, PyBUF_SIMPLE) != 0) + return converterr("string or single-segment read-only buffer", + arg, msgbuf, bufsize); - *p_format = format; - return NULL; + count = view.len; + *p = view.buf; + if (pb->bf_releasebuffer) + return converterr( + "string or pinned buffer", + arg, msgbuf, bufsize); + + PyBuffer_Release(&view); + + if (count < 0) + return converterr("(unspecified)", arg, msgbuf, bufsize); + { + FETCH_SIZE; + STORE_SIZE(count); + } + break; + } + + default: + return converterr("impossible", arg, msgbuf, bufsize); + + } + + *p_format = format; + return NULL; } static Py_ssize_t convertbuffer(PyObject *arg, void **p, char **errmsg) { - PyBufferProcs *pb = arg->ob_type->tp_as_buffer; - Py_ssize_t count; - Py_buffer view; - - *errmsg = NULL; - *p = NULL; - if (pb == NULL || - pb->bf_getbuffer == NULL || - pb->bf_releasebuffer != NULL) { - *errmsg = "bytes or read-only buffer"; - return -1; - } - - if (PyObject_GetBuffer(arg, &view, PyBUF_SIMPLE) != 0) { - *errmsg = "bytes or single-segment read-only buffer"; - return -1; - } - count = view.len; - *p = view.buf; - PyBuffer_Release(&view); - return count; + PyBufferProcs *pb = arg->ob_type->tp_as_buffer; + Py_ssize_t count; + Py_buffer view; + + *errmsg = NULL; + *p = NULL; + if (pb == NULL || + pb->bf_getbuffer == NULL || + pb->bf_releasebuffer != NULL) { + *errmsg = "bytes or read-only buffer"; + return -1; + } + + if (PyObject_GetBuffer(arg, &view, PyBUF_SIMPLE) != 0) { + *errmsg = "bytes or single-segment read-only buffer"; + return -1; + } + count = view.len; + *p = view.buf; + PyBuffer_Release(&view); + return count; } /* XXX for 3.x, getbuffer and convertbuffer can probably @@ -1446,32 +1446,32 @@ static int getbuffer(PyObject *arg, Py_buffer *view, char **errmsg) { - void *buf; - Py_ssize_t count; - PyBufferProcs *pb = arg->ob_type->tp_as_buffer; - if (pb == NULL) { - *errmsg = "bytes or buffer"; - return -1; - } - if (pb->bf_getbuffer) { - if (PyObject_GetBuffer(arg, view, 0) < 0) { - *errmsg = "convertible to a buffer"; - return -1; - } - if (!PyBuffer_IsContiguous(view, 'C')) { - *errmsg = "contiguous buffer"; - return -1; - } - return 0; - } - - count = convertbuffer(arg, &buf, errmsg); - if (count < 0) { - *errmsg = "convertible to a buffer"; - return count; - } - PyBuffer_FillInfo(view, NULL, buf, count, 1, 0); - return 0; + void *buf; + Py_ssize_t count; + PyBufferProcs *pb = arg->ob_type->tp_as_buffer; + if (pb == NULL) { + *errmsg = "bytes or buffer"; + return -1; + } + if (pb->bf_getbuffer) { + if (PyObject_GetBuffer(arg, view, 0) < 0) { + *errmsg = "convertible to a buffer"; + return -1; + } + if (!PyBuffer_IsContiguous(view, 'C')) { + *errmsg = "contiguous buffer"; + return -1; + } + return 0; + } + + count = convertbuffer(arg, &buf, errmsg); + if (count < 0) { + *errmsg = "convertible to a buffer"; + return count; + } + PyBuffer_FillInfo(view, NULL, buf, count, 1, 0); + return 0; } /* Support for keyword arguments donated by @@ -1480,51 +1480,51 @@ /* Return false (0) for error, else true. */ int PyArg_ParseTupleAndKeywords(PyObject *args, - PyObject *keywords, - const char *format, - char **kwlist, ...) -{ - int retval; - va_list va; - - if ((args == NULL || !PyTuple_Check(args)) || - (keywords != NULL && !PyDict_Check(keywords)) || - format == NULL || - kwlist == NULL) - { - PyErr_BadInternalCall(); - return 0; - } - - va_start(va, kwlist); - retval = vgetargskeywords(args, keywords, format, kwlist, &va, 0); - va_end(va); - return retval; + PyObject *keywords, + const char *format, + char **kwlist, ...) +{ + int retval; + va_list va; + + if ((args == NULL || !PyTuple_Check(args)) || + (keywords != NULL && !PyDict_Check(keywords)) || + format == NULL || + kwlist == NULL) + { + PyErr_BadInternalCall(); + return 0; + } + + va_start(va, kwlist); + retval = vgetargskeywords(args, keywords, format, kwlist, &va, 0); + va_end(va); + return retval; } int _PyArg_ParseTupleAndKeywords_SizeT(PyObject *args, - PyObject *keywords, - const char *format, - char **kwlist, ...) -{ - int retval; - va_list va; - - if ((args == NULL || !PyTuple_Check(args)) || - (keywords != NULL && !PyDict_Check(keywords)) || - format == NULL || - kwlist == NULL) - { - PyErr_BadInternalCall(); - return 0; - } - - va_start(va, kwlist); - retval = vgetargskeywords(args, keywords, format, - kwlist, &va, FLAG_SIZE_T); - va_end(va); - return retval; + PyObject *keywords, + const char *format, + char **kwlist, ...) +{ + int retval; + va_list va; + + if ((args == NULL || !PyTuple_Check(args)) || + (keywords != NULL && !PyDict_Check(keywords)) || + format == NULL || + kwlist == NULL) + { + PyErr_BadInternalCall(); + return 0; + } + + va_start(va, kwlist); + retval = vgetargskeywords(args, keywords, format, + kwlist, &va, FLAG_SIZE_T); + va_end(va); + return retval; } @@ -1534,419 +1534,419 @@ const char *format, char **kwlist, va_list va) { - int retval; - va_list lva; + int retval; + va_list lva; - if ((args == NULL || !PyTuple_Check(args)) || - (keywords != NULL && !PyDict_Check(keywords)) || - format == NULL || - kwlist == NULL) - { - PyErr_BadInternalCall(); - return 0; - } + if ((args == NULL || !PyTuple_Check(args)) || + (keywords != NULL && !PyDict_Check(keywords)) || + format == NULL || + kwlist == NULL) + { + PyErr_BadInternalCall(); + return 0; + } #ifdef VA_LIST_IS_ARRAY - memcpy(lva, va, sizeof(va_list)); + memcpy(lva, va, sizeof(va_list)); #else #ifdef __va_copy - __va_copy(lva, va); + __va_copy(lva, va); #else - lva = va; + lva = va; #endif #endif - retval = vgetargskeywords(args, keywords, format, kwlist, &lva, 0); - return retval; + retval = vgetargskeywords(args, keywords, format, kwlist, &lva, 0); + return retval; } int _PyArg_VaParseTupleAndKeywords_SizeT(PyObject *args, - PyObject *keywords, - const char *format, - char **kwlist, va_list va) -{ - int retval; - va_list lva; - - if ((args == NULL || !PyTuple_Check(args)) || - (keywords != NULL && !PyDict_Check(keywords)) || - format == NULL || - kwlist == NULL) - { - PyErr_BadInternalCall(); - return 0; - } + PyObject *keywords, + const char *format, + char **kwlist, va_list va) +{ + int retval; + va_list lva; + + if ((args == NULL || !PyTuple_Check(args)) || + (keywords != NULL && !PyDict_Check(keywords)) || + format == NULL || + kwlist == NULL) + { + PyErr_BadInternalCall(); + return 0; + } #ifdef VA_LIST_IS_ARRAY - memcpy(lva, va, sizeof(va_list)); + memcpy(lva, va, sizeof(va_list)); #else #ifdef __va_copy - __va_copy(lva, va); + __va_copy(lva, va); #else - lva = va; + lva = va; #endif #endif - retval = vgetargskeywords(args, keywords, format, - kwlist, &lva, FLAG_SIZE_T); - return retval; + retval = vgetargskeywords(args, keywords, format, + kwlist, &lva, FLAG_SIZE_T); + return retval; } #define IS_END_OF_FORMAT(c) (c == '\0' || c == ';' || c == ':') static int vgetargskeywords(PyObject *args, PyObject *keywords, const char *format, - char **kwlist, va_list *p_va, int flags) + char **kwlist, va_list *p_va, int flags) { - char msgbuf[512]; - int levels[32]; - const char *fname, *msg, *custom_msg, *keyword; - int min = INT_MAX; - int i, len, nargs, nkeywords; - PyObject *freelist = NULL, *current_arg; - - assert(args != NULL && PyTuple_Check(args)); - assert(keywords == NULL || PyDict_Check(keywords)); - assert(format != NULL); - assert(kwlist != NULL); - assert(p_va != NULL); - - /* grab the function name or custom error msg first (mutually exclusive) */ - fname = strchr(format, ':'); - if (fname) { - fname++; - custom_msg = NULL; - } - else { - custom_msg = strchr(format,';'); - if (custom_msg) - custom_msg++; - } - - /* scan kwlist and get greatest possible nbr of args */ - for (len=0; kwlist[len]; len++) - continue; - - nargs = PyTuple_GET_SIZE(args); - nkeywords = (keywords == NULL) ? 0 : PyDict_Size(keywords); - if (nargs + nkeywords > len) { - PyErr_Format(PyExc_TypeError, "%s%s takes at most %d " - "argument%s (%d given)", - (fname == NULL) ? "function" : fname, - (fname == NULL) ? "" : "()", - len, - (len == 1) ? "" : "s", - nargs + nkeywords); - return 0; - } - - /* convert tuple args and keyword args in same loop, using kwlist to drive process */ - for (i = 0; i < len; i++) { - keyword = kwlist[i]; - if (*format == '|') { - min = i; - format++; - } - if (IS_END_OF_FORMAT(*format)) { - PyErr_Format(PyExc_RuntimeError, - "More keyword list entries (%d) than " - "format specifiers (%d)", len, i); - return cleanreturn(0, freelist); - } - current_arg = NULL; - if (nkeywords) { - current_arg = PyDict_GetItemString(keywords, keyword); - } - if (current_arg) { - --nkeywords; - if (i < nargs) { - /* arg present in tuple and in dict */ - PyErr_Format(PyExc_TypeError, - "Argument given by name ('%s') " - "and position (%d)", - keyword, i+1); - return cleanreturn(0, freelist); - } - } - else if (nkeywords && PyErr_Occurred()) - return cleanreturn(0, freelist); - else if (i < nargs) - current_arg = PyTuple_GET_ITEM(args, i); - - if (current_arg) { - msg = convertitem(current_arg, &format, p_va, flags, - levels, msgbuf, sizeof(msgbuf), &freelist); - if (msg) { - seterror(i+1, msg, levels, fname, custom_msg); - return cleanreturn(0, freelist); - } - continue; - } - - if (i < min) { - PyErr_Format(PyExc_TypeError, "Required argument " - "'%s' (pos %d) not found", - keyword, i+1); - return cleanreturn(0, freelist); - } - /* current code reports success when all required args - * fulfilled and no keyword args left, with no further - * validation. XXX Maybe skip this in debug build ? - */ - if (!nkeywords) - return cleanreturn(1, freelist); - - /* We are into optional args, skip thru to any remaining - * keyword args */ - msg = skipitem(&format, p_va, flags); - if (msg) { - PyErr_Format(PyExc_RuntimeError, "%s: '%s'", msg, - format); - return cleanreturn(0, freelist); - } - } - - if (!IS_END_OF_FORMAT(*format) && *format != '|') { - PyErr_Format(PyExc_RuntimeError, - "more argument specifiers than keyword list entries " - "(remaining format:'%s')", format); - return cleanreturn(0, freelist); - } - - /* make sure there are no extraneous keyword arguments */ - if (nkeywords > 0) { - PyObject *key, *value; - Py_ssize_t pos = 0; - while (PyDict_Next(keywords, &pos, &key, &value)) { - int match = 0; - char *ks; - if (!PyUnicode_Check(key)) { - PyErr_SetString(PyExc_TypeError, - "keywords must be strings"); - return cleanreturn(0, freelist); - } - ks = _PyUnicode_AsString(key); - for (i = 0; i < len; i++) { - if (!strcmp(ks, kwlist[i])) { - match = 1; - break; - } - } - if (!match) { - PyErr_Format(PyExc_TypeError, - "'%s' is an invalid keyword " - "argument for this function", - ks); - return cleanreturn(0, freelist); - } - } - } + char msgbuf[512]; + int levels[32]; + const char *fname, *msg, *custom_msg, *keyword; + int min = INT_MAX; + int i, len, nargs, nkeywords; + PyObject *freelist = NULL, *current_arg; + + assert(args != NULL && PyTuple_Check(args)); + assert(keywords == NULL || PyDict_Check(keywords)); + assert(format != NULL); + assert(kwlist != NULL); + assert(p_va != NULL); + + /* grab the function name or custom error msg first (mutually exclusive) */ + fname = strchr(format, ':'); + if (fname) { + fname++; + custom_msg = NULL; + } + else { + custom_msg = strchr(format,';'); + if (custom_msg) + custom_msg++; + } + + /* scan kwlist and get greatest possible nbr of args */ + for (len=0; kwlist[len]; len++) + continue; + + nargs = PyTuple_GET_SIZE(args); + nkeywords = (keywords == NULL) ? 0 : PyDict_Size(keywords); + if (nargs + nkeywords > len) { + PyErr_Format(PyExc_TypeError, "%s%s takes at most %d " + "argument%s (%d given)", + (fname == NULL) ? "function" : fname, + (fname == NULL) ? "" : "()", + len, + (len == 1) ? "" : "s", + nargs + nkeywords); + return 0; + } + + /* convert tuple args and keyword args in same loop, using kwlist to drive process */ + for (i = 0; i < len; i++) { + keyword = kwlist[i]; + if (*format == '|') { + min = i; + format++; + } + if (IS_END_OF_FORMAT(*format)) { + PyErr_Format(PyExc_RuntimeError, + "More keyword list entries (%d) than " + "format specifiers (%d)", len, i); + return cleanreturn(0, freelist); + } + current_arg = NULL; + if (nkeywords) { + current_arg = PyDict_GetItemString(keywords, keyword); + } + if (current_arg) { + --nkeywords; + if (i < nargs) { + /* arg present in tuple and in dict */ + PyErr_Format(PyExc_TypeError, + "Argument given by name ('%s') " + "and position (%d)", + keyword, i+1); + return cleanreturn(0, freelist); + } + } + else if (nkeywords && PyErr_Occurred()) + return cleanreturn(0, freelist); + else if (i < nargs) + current_arg = PyTuple_GET_ITEM(args, i); + + if (current_arg) { + msg = convertitem(current_arg, &format, p_va, flags, + levels, msgbuf, sizeof(msgbuf), &freelist); + if (msg) { + seterror(i+1, msg, levels, fname, custom_msg); + return cleanreturn(0, freelist); + } + continue; + } + + if (i < min) { + PyErr_Format(PyExc_TypeError, "Required argument " + "'%s' (pos %d) not found", + keyword, i+1); + return cleanreturn(0, freelist); + } + /* current code reports success when all required args + * fulfilled and no keyword args left, with no further + * validation. XXX Maybe skip this in debug build ? + */ + if (!nkeywords) + return cleanreturn(1, freelist); + + /* We are into optional args, skip thru to any remaining + * keyword args */ + msg = skipitem(&format, p_va, flags); + if (msg) { + PyErr_Format(PyExc_RuntimeError, "%s: '%s'", msg, + format); + return cleanreturn(0, freelist); + } + } + + if (!IS_END_OF_FORMAT(*format) && *format != '|') { + PyErr_Format(PyExc_RuntimeError, + "more argument specifiers than keyword list entries " + "(remaining format:'%s')", format); + return cleanreturn(0, freelist); + } + + /* make sure there are no extraneous keyword arguments */ + if (nkeywords > 0) { + PyObject *key, *value; + Py_ssize_t pos = 0; + while (PyDict_Next(keywords, &pos, &key, &value)) { + int match = 0; + char *ks; + if (!PyUnicode_Check(key)) { + PyErr_SetString(PyExc_TypeError, + "keywords must be strings"); + return cleanreturn(0, freelist); + } + ks = _PyUnicode_AsString(key); + for (i = 0; i < len; i++) { + if (!strcmp(ks, kwlist[i])) { + match = 1; + break; + } + } + if (!match) { + PyErr_Format(PyExc_TypeError, + "'%s' is an invalid keyword " + "argument for this function", + ks); + return cleanreturn(0, freelist); + } + } + } - return cleanreturn(1, freelist); + return cleanreturn(1, freelist); } static char * skipitem(const char **p_format, va_list *p_va, int flags) { - const char *format = *p_format; - char c = *format++; + const char *format = *p_format; + char c = *format++; - switch (c) { + switch (c) { - /* simple codes - * The individual types (second arg of va_arg) are irrelevant */ + /* simple codes + * The individual types (second arg of va_arg) are irrelevant */ - case 'b': /* byte -- very short int */ - case 'B': /* byte as bitfield */ - case 'h': /* short int */ - case 'H': /* short int as bitfield */ - case 'i': /* int */ - case 'I': /* int sized bitfield */ - case 'l': /* long int */ - case 'k': /* long int sized bitfield */ + case 'b': /* byte -- very short int */ + case 'B': /* byte as bitfield */ + case 'h': /* short int */ + case 'H': /* short int as bitfield */ + case 'i': /* int */ + case 'I': /* int sized bitfield */ + case 'l': /* long int */ + case 'k': /* long int sized bitfield */ #ifdef HAVE_LONG_LONG - case 'L': /* PY_LONG_LONG */ - case 'K': /* PY_LONG_LONG sized bitfield */ + case 'L': /* PY_LONG_LONG */ + case 'K': /* PY_LONG_LONG sized bitfield */ #endif - case 'f': /* float */ - case 'd': /* double */ + case 'f': /* float */ + case 'd': /* double */ #ifndef WITHOUT_COMPLEX - case 'D': /* complex double */ + case 'D': /* complex double */ #endif - case 'c': /* char */ - case 'C': /* unicode char */ - { - (void) va_arg(*p_va, void *); - break; - } - - case 'n': /* Py_ssize_t */ - { - (void) va_arg(*p_va, Py_ssize_t *); - break; - } - - /* string codes */ - - case 'e': /* string with encoding */ - { - (void) va_arg(*p_va, const char *); - if (!(*format == 's' || *format == 't')) - /* after 'e', only 's' and 't' is allowed */ - goto err; - format++; - /* explicit fallthrough to string cases */ - } - - case 's': /* string */ - case 'z': /* string or None */ - case 'y': /* bytes */ - case 'u': /* unicode string */ - case 't': /* buffer, read-only */ - case 'w': /* buffer, read-write */ - { - (void) va_arg(*p_va, char **); - if (*format == '#') { - if (flags & FLAG_SIZE_T) - (void) va_arg(*p_va, Py_ssize_t *); - else - (void) va_arg(*p_va, int *); - format++; - } else if ((c == 's' || c == 'z' || c == 'y') && *format == '*') { - format++; - } - break; - } - - /* object codes */ - - case 'S': /* string object */ - case 'Y': /* string object */ - case 'U': /* unicode string object */ - { - (void) va_arg(*p_va, PyObject **); - break; - } - - case 'O': /* object */ - { - if (*format == '!') { - format++; - (void) va_arg(*p_va, PyTypeObject*); - (void) va_arg(*p_va, PyObject **); - } + case 'c': /* char */ + case 'C': /* unicode char */ + { + (void) va_arg(*p_va, void *); + break; + } + + case 'n': /* Py_ssize_t */ + { + (void) va_arg(*p_va, Py_ssize_t *); + break; + } + + /* string codes */ + + case 'e': /* string with encoding */ + { + (void) va_arg(*p_va, const char *); + if (!(*format == 's' || *format == 't')) + /* after 'e', only 's' and 't' is allowed */ + goto err; + format++; + /* explicit fallthrough to string cases */ + } + + case 's': /* string */ + case 'z': /* string or None */ + case 'y': /* bytes */ + case 'u': /* unicode string */ + case 't': /* buffer, read-only */ + case 'w': /* buffer, read-write */ + { + (void) va_arg(*p_va, char **); + if (*format == '#') { + if (flags & FLAG_SIZE_T) + (void) va_arg(*p_va, Py_ssize_t *); + else + (void) va_arg(*p_va, int *); + format++; + } else if ((c == 's' || c == 'z' || c == 'y') && *format == '*') { + format++; + } + break; + } + + /* object codes */ + + case 'S': /* string object */ + case 'Y': /* string object */ + case 'U': /* unicode string object */ + { + (void) va_arg(*p_va, PyObject **); + break; + } + + case 'O': /* object */ + { + if (*format == '!') { + format++; + (void) va_arg(*p_va, PyTypeObject*); + (void) va_arg(*p_va, PyObject **); + } #if 0 /* I don't know what this is for */ - else if (*format == '?') { - inquiry pred = va_arg(*p_va, inquiry); - format++; - if ((*pred)(arg)) { - (void) va_arg(*p_va, PyObject **); - } - } + else if (*format == '?') { + inquiry pred = va_arg(*p_va, inquiry); + format++; + if ((*pred)(arg)) { + (void) va_arg(*p_va, PyObject **); + } + } #endif - else if (*format == '&') { - typedef int (*converter)(PyObject *, void *); - (void) va_arg(*p_va, converter); - (void) va_arg(*p_va, void *); - format++; - } - else { - (void) va_arg(*p_va, PyObject **); - } - break; - } - - case '(': /* bypass tuple, not handled at all previously */ - { - char *msg; - for (;;) { - if (*format==')') - break; - if (IS_END_OF_FORMAT(*format)) - return "Unmatched left paren in format " - "string"; - msg = skipitem(&format, p_va, flags); - if (msg) - return msg; - } - format++; - break; - } + else if (*format == '&') { + typedef int (*converter)(PyObject *, void *); + (void) va_arg(*p_va, converter); + (void) va_arg(*p_va, void *); + format++; + } + else { + (void) va_arg(*p_va, PyObject **); + } + break; + } + + case '(': /* bypass tuple, not handled at all previously */ + { + char *msg; + for (;;) { + if (*format==')') + break; + if (IS_END_OF_FORMAT(*format)) + return "Unmatched left paren in format " + "string"; + msg = skipitem(&format, p_va, flags); + if (msg) + return msg; + } + format++; + break; + } - case ')': - return "Unmatched right paren in format string"; + case ')': + return "Unmatched right paren in format string"; - default: + default: err: - return "impossible"; + return "impossible"; - } + } - *p_format = format; - return NULL; + *p_format = format; + return NULL; } int PyArg_UnpackTuple(PyObject *args, const char *name, Py_ssize_t min, Py_ssize_t max, ...) { - Py_ssize_t i, l; - PyObject **o; - va_list vargs; + Py_ssize_t i, l; + PyObject **o; + va_list vargs; #ifdef HAVE_STDARG_PROTOTYPES - va_start(vargs, max); + va_start(vargs, max); #else - va_start(vargs); + va_start(vargs); #endif - assert(min >= 0); - assert(min <= max); - if (!PyTuple_Check(args)) { - PyErr_SetString(PyExc_SystemError, - "PyArg_UnpackTuple() argument list is not a tuple"); - return 0; - } - l = PyTuple_GET_SIZE(args); - if (l < min) { - if (name != NULL) - PyErr_Format( - PyExc_TypeError, - "%s expected %s%zd arguments, got %zd", - name, (min == max ? "" : "at least "), min, l); - else - PyErr_Format( - PyExc_TypeError, - "unpacked tuple should have %s%zd elements," - " but has %zd", - (min == max ? "" : "at least "), min, l); - va_end(vargs); - return 0; - } - if (l > max) { - if (name != NULL) - PyErr_Format( - PyExc_TypeError, - "%s expected %s%zd arguments, got %zd", - name, (min == max ? "" : "at most "), max, l); - else - PyErr_Format( - PyExc_TypeError, - "unpacked tuple should have %s%zd elements," - " but has %zd", - (min == max ? "" : "at most "), max, l); - va_end(vargs); - return 0; - } - for (i = 0; i < l; i++) { - o = va_arg(vargs, PyObject **); - *o = PyTuple_GET_ITEM(args, i); - } - va_end(vargs); - return 1; + assert(min >= 0); + assert(min <= max); + if (!PyTuple_Check(args)) { + PyErr_SetString(PyExc_SystemError, + "PyArg_UnpackTuple() argument list is not a tuple"); + return 0; + } + l = PyTuple_GET_SIZE(args); + if (l < min) { + if (name != NULL) + PyErr_Format( + PyExc_TypeError, + "%s expected %s%zd arguments, got %zd", + name, (min == max ? "" : "at least "), min, l); + else + PyErr_Format( + PyExc_TypeError, + "unpacked tuple should have %s%zd elements," + " but has %zd", + (min == max ? "" : "at least "), min, l); + va_end(vargs); + return 0; + } + if (l > max) { + if (name != NULL) + PyErr_Format( + PyExc_TypeError, + "%s expected %s%zd arguments, got %zd", + name, (min == max ? "" : "at most "), max, l); + else + PyErr_Format( + PyExc_TypeError, + "unpacked tuple should have %s%zd elements," + " but has %zd", + (min == max ? "" : "at most "), max, l); + va_end(vargs); + return 0; + } + for (i = 0; i < l; i++) { + o = va_arg(vargs, PyObject **); + *o = PyTuple_GET_ITEM(args, i); + } + va_end(vargs); + return 1; } @@ -1958,18 +1958,18 @@ int _PyArg_NoKeywords(const char *funcname, PyObject *kw) { - if (kw == NULL) - return 1; - if (!PyDict_CheckExact(kw)) { - PyErr_BadInternalCall(); - return 0; - } - if (PyDict_Size(kw) == 0) - return 1; - - PyErr_Format(PyExc_TypeError, "%s does not take keyword arguments", - funcname); - return 0; + if (kw == NULL) + return 1; + if (!PyDict_CheckExact(kw)) { + PyErr_BadInternalCall(); + return 0; + } + if (PyDict_Size(kw) == 0) + return 1; + + PyErr_Format(PyExc_TypeError, "%s does not take keyword arguments", + funcname); + return 0; } #ifdef __cplusplus }; Modified: python/branches/release31-maint/Python/getcwd.c ============================================================================== --- python/branches/release31-maint/Python/getcwd.c (original) +++ python/branches/release31-maint/Python/getcwd.c Sun May 9 18:14:21 2010 @@ -26,24 +26,24 @@ char * getcwd(char *buf, int size) { - char localbuf[MAXPATHLEN+1]; - char *ret; - - if (size <= 0) { - errno = EINVAL; - return NULL; - } - ret = getwd(localbuf); - if (ret != NULL && strlen(localbuf) >= (size_t)size) { - errno = ERANGE; - return NULL; - } - if (ret == NULL) { - errno = EACCES; /* Most likely error */ - return NULL; - } - strncpy(buf, localbuf, size); - return buf; + char localbuf[MAXPATHLEN+1]; + char *ret; + + if (size <= 0) { + errno = EINVAL; + return NULL; + } + ret = getwd(localbuf); + if (ret != NULL && strlen(localbuf) >= (size_t)size) { + errno = ERANGE; + return NULL; + } + if (ret == NULL) { + errno = EACCES; /* Most likely error */ + return NULL; + } + strncpy(buf, localbuf, size); + return buf; } #else /* !HAVE_GETWD */ @@ -57,27 +57,27 @@ char * getcwd(char *buf, int size) { - FILE *fp; - char *p; - int sts; - if (size <= 0) { - errno = EINVAL; - return NULL; - } - if ((fp = popen(PWD_CMD, "r")) == NULL) - return NULL; - if (fgets(buf, size, fp) == NULL || (sts = pclose(fp)) != 0) { - errno = EACCES; /* Most likely error */ - return NULL; - } - for (p = buf; *p != '\n'; p++) { - if (*p == '\0') { - errno = ERANGE; - return NULL; - } - } - *p = '\0'; - return buf; + FILE *fp; + char *p; + int sts; + if (size <= 0) { + errno = EINVAL; + return NULL; + } + if ((fp = popen(PWD_CMD, "r")) == NULL) + return NULL; + if (fgets(buf, size, fp) == NULL || (sts = pclose(fp)) != 0) { + errno = EACCES; /* Most likely error */ + return NULL; + } + for (p = buf; *p != '\n'; p++) { + if (*p == '\0') { + errno = ERANGE; + return NULL; + } + } + *p = '\0'; + return buf; } #endif /* !HAVE_GETWD */ Modified: python/branches/release31-maint/Python/getopt.c ============================================================================== --- python/branches/release31-maint/Python/getopt.c (original) +++ python/branches/release31-maint/Python/getopt.c Sun May 9 18:14:21 2010 @@ -7,8 +7,8 @@ * * All Rights Reserved * - * Permission to use, copy, modify, and distribute this software and its - * documentation for any purpose and without fee is hereby granted, + * 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, this permission notice and * the following disclaimer notice appear unmodified in all copies. * @@ -43,84 +43,84 @@ int _PyOS_GetOpt(int argc, wchar_t **argv, wchar_t *optstring) { - static wchar_t *opt_ptr = L""; - wchar_t *ptr; - wchar_t option; + static wchar_t *opt_ptr = L""; + wchar_t *ptr; + wchar_t option; - if (*opt_ptr == '\0') { + if (*opt_ptr == '\0') { - if (_PyOS_optind >= argc) - return -1; + if (_PyOS_optind >= argc) + return -1; #ifdef MS_WINDOWS - else if (wcscmp(argv[_PyOS_optind], L"/?") == 0) { - ++_PyOS_optind; - return 'h'; - } + else if (wcscmp(argv[_PyOS_optind], L"/?") == 0) { + ++_PyOS_optind; + return 'h'; + } #endif - else if (argv[_PyOS_optind][0] != L'-' || - argv[_PyOS_optind][1] == L'\0' /* lone dash */ ) - return -1; - - else if (wcscmp(argv[_PyOS_optind], L"--") == 0) { - ++_PyOS_optind; - return -1; - } - - else if (wcscmp(argv[_PyOS_optind], L"--help") == 0) { - ++_PyOS_optind; - return 'h'; - } - - else if (wcscmp(argv[_PyOS_optind], L"--version") == 0) { - ++_PyOS_optind; - return 'V'; - } - - - opt_ptr = &argv[_PyOS_optind++][1]; - } - - if ( (option = *opt_ptr++) == L'\0') - return -1; - - if (option == 'J') { - fprintf(stderr, "-J is reserved for Jython\n"); - return '_'; - } - - if (option == 'X') { - fprintf(stderr, - "-X is reserved for implementation-specific arguments\n"); - return '_'; - } - - if ((ptr = wcschr(optstring, option)) == NULL) { - if (_PyOS_opterr) - fprintf(stderr, "Unknown option: -%c\n", (char)option); - - return '_'; - } - - if (*(ptr + 1) == L':') { - if (*opt_ptr != L'\0') { - _PyOS_optarg = opt_ptr; - opt_ptr = L""; - } - - else { - if (_PyOS_optind >= argc) { - if (_PyOS_opterr) - fprintf(stderr, - "Argument expected for the -%c option\n", (char)option); - return '_'; - } - - _PyOS_optarg = argv[_PyOS_optind++]; - } - } + else if (argv[_PyOS_optind][0] != L'-' || + argv[_PyOS_optind][1] == L'\0' /* lone dash */ ) + return -1; + + else if (wcscmp(argv[_PyOS_optind], L"--") == 0) { + ++_PyOS_optind; + return -1; + } + + else if (wcscmp(argv[_PyOS_optind], L"--help") == 0) { + ++_PyOS_optind; + return 'h'; + } + + else if (wcscmp(argv[_PyOS_optind], L"--version") == 0) { + ++_PyOS_optind; + return 'V'; + } + + + opt_ptr = &argv[_PyOS_optind++][1]; + } + + if ( (option = *opt_ptr++) == L'\0') + return -1; + + if (option == 'J') { + fprintf(stderr, "-J is reserved for Jython\n"); + return '_'; + } + + if (option == 'X') { + fprintf(stderr, + "-X is reserved for implementation-specific arguments\n"); + return '_'; + } + + if ((ptr = wcschr(optstring, option)) == NULL) { + if (_PyOS_opterr) + fprintf(stderr, "Unknown option: -%c\n", (char)option); + + return '_'; + } + + if (*(ptr + 1) == L':') { + if (*opt_ptr != L'\0') { + _PyOS_optarg = opt_ptr; + opt_ptr = L""; + } + + else { + if (_PyOS_optind >= argc) { + if (_PyOS_opterr) + fprintf(stderr, + "Argument expected for the -%c option\n", (char)option); + return '_'; + } + + _PyOS_optarg = argv[_PyOS_optind++]; + } + } - return option; + return option; } #ifdef __cplusplus Modified: python/branches/release31-maint/Python/import.c ============================================================================== --- python/branches/release31-maint/Python/import.c (original) +++ python/branches/release31-maint/Python/import.c Sun May 9 18:14:21 2010 @@ -19,7 +19,7 @@ #include #endif #ifdef __cplusplus -extern "C" { +extern "C" { #endif #ifdef MS_WINDOWS @@ -67,28 +67,28 @@ Python 2.5b3: 62101 (fix wrong code: for x, in ...) Python 2.5b3: 62111 (fix wrong code: x += yield) Python 2.5c1: 62121 (fix wrong lnotab with for loops and - storing constants that should have been removed) + storing constants that should have been removed) Python 2.5c2: 62131 (fix wrong code: for x, in ... in listcomp/genexp) Python 2.6a0: 62151 (peephole optimizations and STORE_MAP opcode) Python 2.6a1: 62161 (WITH_CLEANUP optimization) Python 3000: 3000 - 3010 (removed UNARY_CONVERT) - 3020 (added BUILD_SET) - 3030 (added keyword-only parameters) - 3040 (added signature annotations) - 3050 (print becomes a function) - 3060 (PEP 3115 metaclass syntax) - 3070 (PEP 3109 raise changes) - 3080 (PEP 3137 make __file__ and __name__ unicode) - 3090 (kill str8 interning) - 3100 (merge from 2.6a0, see 62151) - 3102 (__file__ points to source file) + 3010 (removed UNARY_CONVERT) + 3020 (added BUILD_SET) + 3030 (added keyword-only parameters) + 3040 (added signature annotations) + 3050 (print becomes a function) + 3060 (PEP 3115 metaclass syntax) + 3070 (PEP 3109 raise changes) + 3080 (PEP 3137 make __file__ and __name__ unicode) + 3090 (kill str8 interning) + 3100 (merge from 2.6a0, see 62151) + 3102 (__file__ points to source file) Python 3.0a4: 3110 (WITH_CLEANUP optimization). Python 3.0a5: 3130 (lexical exception stacking, including POP_EXCEPT) Python 3.1a0: 3140 (optimize list, set and dict comprehensions: - change LIST_APPEND and SET_ADD, add MAP_ADD) + change LIST_APPEND and SET_ADD, add MAP_ADD) Python 3.1a0: 3150 (optimize conditional branches: - introduce POP_JUMP_IF_FALSE and POP_JUMP_IF_TRUE) + introduce POP_JUMP_IF_FALSE and POP_JUMP_IF_TRUE) */ #define MAGIC (3150 | ((long)'\r'<<16) | ((long)'\n'<<24)) @@ -112,12 +112,12 @@ struct filedescr * _PyImport_Filetab = NULL; static const struct filedescr _PyImport_StandardFiletab[] = { - {".py", "U", PY_SOURCE}, + {".py", "U", PY_SOURCE}, #ifdef MS_WINDOWS - {".pyw", "U", PY_SOURCE}, + {".pyw", "U", PY_SOURCE}, #endif - {".pyc", "rb", PY_COMPILED}, - {0, 0} + {".pyc", "rb", PY_COMPILED}, + {0, 0} }; @@ -126,126 +126,126 @@ void _PyImport_Init(void) { - const struct filedescr *scan; - struct filedescr *filetab; - int countD = 0; - int countS = 0; - - /* prepare _PyImport_Filetab: copy entries from - _PyImport_DynLoadFiletab and _PyImport_StandardFiletab. - */ + const struct filedescr *scan; + struct filedescr *filetab; + int countD = 0; + int countS = 0; + + /* prepare _PyImport_Filetab: copy entries from + _PyImport_DynLoadFiletab and _PyImport_StandardFiletab. + */ #ifdef HAVE_DYNAMIC_LOADING - for (scan = _PyImport_DynLoadFiletab; scan->suffix != NULL; ++scan) - ++countD; + for (scan = _PyImport_DynLoadFiletab; scan->suffix != NULL; ++scan) + ++countD; #endif - for (scan = _PyImport_StandardFiletab; scan->suffix != NULL; ++scan) - ++countS; - filetab = PyMem_NEW(struct filedescr, countD + countS + 1); - if (filetab == NULL) - Py_FatalError("Can't initialize import file table."); + for (scan = _PyImport_StandardFiletab; scan->suffix != NULL; ++scan) + ++countS; + filetab = PyMem_NEW(struct filedescr, countD + countS + 1); + if (filetab == NULL) + Py_FatalError("Can't initialize import file table."); #ifdef HAVE_DYNAMIC_LOADING - memcpy(filetab, _PyImport_DynLoadFiletab, - countD * sizeof(struct filedescr)); + memcpy(filetab, _PyImport_DynLoadFiletab, + countD * sizeof(struct filedescr)); #endif - memcpy(filetab + countD, _PyImport_StandardFiletab, - countS * sizeof(struct filedescr)); - filetab[countD + countS].suffix = NULL; - - _PyImport_Filetab = filetab; - - if (Py_OptimizeFlag) { - /* Replace ".pyc" with ".pyo" in _PyImport_Filetab */ - for (; filetab->suffix != NULL; filetab++) { - if (strcmp(filetab->suffix, ".pyc") == 0) - filetab->suffix = ".pyo"; - } - } - - { - /* Fix the pyc_magic so that byte compiled code created - using the all-Unicode method doesn't interfere with - code created in normal operation mode. */ - pyc_magic = MAGIC + 1; - } + memcpy(filetab + countD, _PyImport_StandardFiletab, + countS * sizeof(struct filedescr)); + filetab[countD + countS].suffix = NULL; + + _PyImport_Filetab = filetab; + + if (Py_OptimizeFlag) { + /* Replace ".pyc" with ".pyo" in _PyImport_Filetab */ + for (; filetab->suffix != NULL; filetab++) { + if (strcmp(filetab->suffix, ".pyc") == 0) + filetab->suffix = ".pyo"; + } + } + + { + /* Fix the pyc_magic so that byte compiled code created + using the all-Unicode method doesn't interfere with + code created in normal operation mode. */ + pyc_magic = MAGIC + 1; + } } void _PyImportHooks_Init(void) { - PyObject *v, *path_hooks = NULL, *zimpimport; - int err = 0; + PyObject *v, *path_hooks = NULL, *zimpimport; + int err = 0; - /* adding sys.path_hooks and sys.path_importer_cache, setting up - zipimport */ - if (PyType_Ready(&PyNullImporter_Type) < 0) - goto error; - - if (Py_VerboseFlag) - PySys_WriteStderr("# installing zipimport hook\n"); - - v = PyList_New(0); - if (v == NULL) - goto error; - err = PySys_SetObject("meta_path", v); - Py_DECREF(v); - if (err) - goto error; - v = PyDict_New(); - if (v == NULL) - goto error; - err = PySys_SetObject("path_importer_cache", v); - Py_DECREF(v); - if (err) - goto error; - path_hooks = PyList_New(0); - if (path_hooks == NULL) - goto error; - err = PySys_SetObject("path_hooks", path_hooks); - if (err) { + /* adding sys.path_hooks and sys.path_importer_cache, setting up + zipimport */ + if (PyType_Ready(&PyNullImporter_Type) < 0) + goto error; + + if (Py_VerboseFlag) + PySys_WriteStderr("# installing zipimport hook\n"); + + v = PyList_New(0); + if (v == NULL) + goto error; + err = PySys_SetObject("meta_path", v); + Py_DECREF(v); + if (err) + goto error; + v = PyDict_New(); + if (v == NULL) + goto error; + err = PySys_SetObject("path_importer_cache", v); + Py_DECREF(v); + if (err) + goto error; + path_hooks = PyList_New(0); + if (path_hooks == NULL) + goto error; + err = PySys_SetObject("path_hooks", path_hooks); + if (err) { error: - PyErr_Print(); - Py_FatalError("initializing sys.meta_path, sys.path_hooks, " - "path_importer_cache, or NullImporter failed" - ); - } - - zimpimport = PyImport_ImportModule("zipimport"); - if (zimpimport == NULL) { - PyErr_Clear(); /* No zip import module -- okay */ - if (Py_VerboseFlag) - PySys_WriteStderr("# can't import zipimport\n"); - } - else { - PyObject *zipimporter = PyObject_GetAttrString(zimpimport, - "zipimporter"); - Py_DECREF(zimpimport); - if (zipimporter == NULL) { - PyErr_Clear(); /* No zipimporter object -- okay */ - if (Py_VerboseFlag) - PySys_WriteStderr( - "# can't import zipimport.zipimporter\n"); - } - else { - /* sys.path_hooks.append(zipimporter) */ - err = PyList_Append(path_hooks, zipimporter); - Py_DECREF(zipimporter); - if (err) - goto error; - if (Py_VerboseFlag) - PySys_WriteStderr( - "# installed zipimport hook\n"); - } - } - Py_DECREF(path_hooks); + PyErr_Print(); + Py_FatalError("initializing sys.meta_path, sys.path_hooks, " + "path_importer_cache, or NullImporter failed" + ); + } + + zimpimport = PyImport_ImportModule("zipimport"); + if (zimpimport == NULL) { + PyErr_Clear(); /* No zip import module -- okay */ + if (Py_VerboseFlag) + PySys_WriteStderr("# can't import zipimport\n"); + } + else { + PyObject *zipimporter = PyObject_GetAttrString(zimpimport, + "zipimporter"); + Py_DECREF(zimpimport); + if (zipimporter == NULL) { + PyErr_Clear(); /* No zipimporter object -- okay */ + if (Py_VerboseFlag) + PySys_WriteStderr( + "# can't import zipimport.zipimporter\n"); + } + else { + /* sys.path_hooks.append(zipimporter) */ + err = PyList_Append(path_hooks, zipimporter); + Py_DECREF(zipimporter); + if (err) + goto error; + if (Py_VerboseFlag) + PySys_WriteStderr( + "# installed zipimport hook\n"); + } + } + Py_DECREF(path_hooks); } void _PyImport_Fini(void) { - Py_XDECREF(extensions); - extensions = NULL; - PyMem_DEL(_PyImport_Filetab); - _PyImport_Filetab = NULL; + Py_XDECREF(extensions); + extensions = NULL; + PyMem_DEL(_PyImport_Filetab); + _PyImport_Filetab = NULL; } @@ -264,42 +264,42 @@ void _PyImport_AcquireLock(void) { - long me = PyThread_get_thread_ident(); - if (me == -1) - return; /* Too bad */ - if (import_lock == NULL) { - import_lock = PyThread_allocate_lock(); - if (import_lock == NULL) - return; /* Nothing much we can do. */ - } - if (import_lock_thread == me) { - import_lock_level++; - return; - } - if (import_lock_thread != -1 || !PyThread_acquire_lock(import_lock, 0)) - { - PyThreadState *tstate = PyEval_SaveThread(); - PyThread_acquire_lock(import_lock, 1); - PyEval_RestoreThread(tstate); - } - import_lock_thread = me; - import_lock_level = 1; + long me = PyThread_get_thread_ident(); + if (me == -1) + return; /* Too bad */ + if (import_lock == NULL) { + import_lock = PyThread_allocate_lock(); + if (import_lock == NULL) + return; /* Nothing much we can do. */ + } + if (import_lock_thread == me) { + import_lock_level++; + return; + } + if (import_lock_thread != -1 || !PyThread_acquire_lock(import_lock, 0)) + { + PyThreadState *tstate = PyEval_SaveThread(); + PyThread_acquire_lock(import_lock, 1); + PyEval_RestoreThread(tstate); + } + import_lock_thread = me; + import_lock_level = 1; } int _PyImport_ReleaseLock(void) { - long me = PyThread_get_thread_ident(); - if (me == -1 || import_lock == NULL) - return 0; /* Too bad */ - if (import_lock_thread != me) - return -1; - import_lock_level--; - if (import_lock_level == 0) { - import_lock_thread = -1; - PyThread_release_lock(import_lock); - } - return 1; + long me = PyThread_get_thread_ident(); + if (me == -1 || import_lock == NULL) + return 0; /* Too bad */ + if (import_lock_thread != me) + return -1; + import_lock_level--; + if (import_lock_level == 0) { + import_lock_thread = -1; + PyThread_release_lock(import_lock); + } + return 1; } /* This function used to be called from PyOS_AfterFork to ensure that newly @@ -318,9 +318,9 @@ imp_lock_held(PyObject *self, PyObject *noargs) { #ifdef WITH_THREAD - return PyBool_FromLong(import_lock_thread != -1); + return PyBool_FromLong(import_lock_thread != -1); #else - return PyBool_FromLong(0); + return PyBool_FromLong(0); #endif } @@ -328,32 +328,32 @@ imp_acquire_lock(PyObject *self, PyObject *noargs) { #ifdef WITH_THREAD - _PyImport_AcquireLock(); + _PyImport_AcquireLock(); #endif - Py_INCREF(Py_None); - return Py_None; + Py_INCREF(Py_None); + return Py_None; } static PyObject * imp_release_lock(PyObject *self, PyObject *noargs) { #ifdef WITH_THREAD - if (_PyImport_ReleaseLock() < 0) { - PyErr_SetString(PyExc_RuntimeError, - "not holding the import lock"); - return NULL; - } + if (_PyImport_ReleaseLock() < 0) { + PyErr_SetString(PyExc_RuntimeError, + "not holding the import lock"); + return NULL; + } #endif - Py_INCREF(Py_None); - return Py_None; + Py_INCREF(Py_None); + return Py_None; } static void imp_modules_reloading_clear(void) { - PyInterpreterState *interp = PyThreadState_Get()->interp; - if (interp->modules_reloading != NULL) - PyDict_Clear(interp->modules_reloading); + PyInterpreterState *interp = PyThreadState_Get()->interp; + if (interp->modules_reloading != NULL) + PyDict_Clear(interp->modules_reloading); } /* Helper for sys */ @@ -361,28 +361,28 @@ PyObject * PyImport_GetModuleDict(void) { - PyInterpreterState *interp = PyThreadState_GET()->interp; - if (interp->modules == NULL) - Py_FatalError("PyImport_GetModuleDict: no module dictionary!"); - return interp->modules; + PyInterpreterState *interp = PyThreadState_GET()->interp; + if (interp->modules == NULL) + Py_FatalError("PyImport_GetModuleDict: no module dictionary!"); + return interp->modules; } /* List of names to clear in sys */ static char* sys_deletes[] = { - "path", "argv", "ps1", "ps2", - "last_type", "last_value", "last_traceback", - "path_hooks", "path_importer_cache", "meta_path", - /* misc stuff */ - "flags", "float_info", - NULL + "path", "argv", "ps1", "ps2", + "last_type", "last_value", "last_traceback", + "path_hooks", "path_importer_cache", "meta_path", + /* misc stuff */ + "flags", "float_info", + NULL }; static char* sys_files[] = { - "stdin", "__stdin__", - "stdout", "__stdout__", - "stderr", "__stderr__", - NULL + "stdin", "__stdin__", + "stdout", "__stdout__", + "stderr", "__stderr__", + NULL }; @@ -391,132 +391,132 @@ void PyImport_Cleanup(void) { - Py_ssize_t pos, ndone; - char *name; - PyObject *key, *value, *dict; - PyInterpreterState *interp = PyThreadState_GET()->interp; - PyObject *modules = interp->modules; - - if (modules == NULL) - return; /* Already done */ - - /* Delete some special variables first. These are common - places where user values hide and people complain when their - destructors fail. Since the modules containing them are - deleted *last* of all, they would come too late in the normal - destruction order. Sigh. */ - - value = PyDict_GetItemString(modules, "builtins"); - if (value != NULL && PyModule_Check(value)) { - dict = PyModule_GetDict(value); - if (Py_VerboseFlag) - PySys_WriteStderr("# clear builtins._\n"); - PyDict_SetItemString(dict, "_", Py_None); - } - value = PyDict_GetItemString(modules, "sys"); - if (value != NULL && PyModule_Check(value)) { - char **p; - PyObject *v; - dict = PyModule_GetDict(value); - for (p = sys_deletes; *p != NULL; p++) { - if (Py_VerboseFlag) - PySys_WriteStderr("# clear sys.%s\n", *p); - PyDict_SetItemString(dict, *p, Py_None); - } - for (p = sys_files; *p != NULL; p+=2) { - if (Py_VerboseFlag) - PySys_WriteStderr("# restore sys.%s\n", *p); - v = PyDict_GetItemString(dict, *(p+1)); - if (v == NULL) - v = Py_None; - PyDict_SetItemString(dict, *p, v); - } - } - - /* First, delete __main__ */ - value = PyDict_GetItemString(modules, "__main__"); - if (value != NULL && PyModule_Check(value)) { - if (Py_VerboseFlag) - PySys_WriteStderr("# cleanup __main__\n"); - _PyModule_Clear(value); - PyDict_SetItemString(modules, "__main__", Py_None); - } - - /* The special treatment of "builtins" here is because even - when it's not referenced as a module, its dictionary is - referenced by almost every module's __builtins__. Since - deleting a module clears its dictionary (even if there are - references left to it), we need to delete the "builtins" - module last. Likewise, we don't delete sys until the very - end because it is implicitly referenced (e.g. by print). - - Also note that we 'delete' modules by replacing their entry - in the modules dict with None, rather than really deleting - them; this avoids a rehash of the modules dictionary and - also marks them as "non existent" so they won't be - re-imported. */ - - /* Next, repeatedly delete modules with a reference count of - one (skipping builtins and sys) and delete them */ - do { - ndone = 0; - pos = 0; - while (PyDict_Next(modules, &pos, &key, &value)) { - if (value->ob_refcnt != 1) - continue; - if (PyUnicode_Check(key) && PyModule_Check(value)) { - name = _PyUnicode_AsString(key); - if (strcmp(name, "builtins") == 0) - continue; - if (strcmp(name, "sys") == 0) - continue; - if (Py_VerboseFlag) - PySys_WriteStderr( - "# cleanup[1] %s\n", name); - _PyModule_Clear(value); - PyDict_SetItem(modules, key, Py_None); - ndone++; - } - } - } while (ndone > 0); - - /* Next, delete all modules (still skipping builtins and sys) */ - pos = 0; - while (PyDict_Next(modules, &pos, &key, &value)) { - if (PyUnicode_Check(key) && PyModule_Check(value)) { - name = _PyUnicode_AsString(key); - if (strcmp(name, "builtins") == 0) - continue; - if (strcmp(name, "sys") == 0) - continue; - if (Py_VerboseFlag) - PySys_WriteStderr("# cleanup[2] %s\n", name); - _PyModule_Clear(value); - PyDict_SetItem(modules, key, Py_None); - } - } - - /* Next, delete sys and builtins (in that order) */ - value = PyDict_GetItemString(modules, "sys"); - if (value != NULL && PyModule_Check(value)) { - if (Py_VerboseFlag) - PySys_WriteStderr("# cleanup sys\n"); - _PyModule_Clear(value); - PyDict_SetItemString(modules, "sys", Py_None); - } - value = PyDict_GetItemString(modules, "builtins"); - if (value != NULL && PyModule_Check(value)) { - if (Py_VerboseFlag) - PySys_WriteStderr("# cleanup builtins\n"); - _PyModule_Clear(value); - PyDict_SetItemString(modules, "builtins", Py_None); - } - - /* Finally, clear and delete the modules directory */ - PyDict_Clear(modules); - interp->modules = NULL; - Py_DECREF(modules); - Py_CLEAR(interp->modules_reloading); + Py_ssize_t pos, ndone; + char *name; + PyObject *key, *value, *dict; + PyInterpreterState *interp = PyThreadState_GET()->interp; + PyObject *modules = interp->modules; + + if (modules == NULL) + return; /* Already done */ + + /* Delete some special variables first. These are common + places where user values hide and people complain when their + destructors fail. Since the modules containing them are + deleted *last* of all, they would come too late in the normal + destruction order. Sigh. */ + + value = PyDict_GetItemString(modules, "builtins"); + if (value != NULL && PyModule_Check(value)) { + dict = PyModule_GetDict(value); + if (Py_VerboseFlag) + PySys_WriteStderr("# clear builtins._\n"); + PyDict_SetItemString(dict, "_", Py_None); + } + value = PyDict_GetItemString(modules, "sys"); + if (value != NULL && PyModule_Check(value)) { + char **p; + PyObject *v; + dict = PyModule_GetDict(value); + for (p = sys_deletes; *p != NULL; p++) { + if (Py_VerboseFlag) + PySys_WriteStderr("# clear sys.%s\n", *p); + PyDict_SetItemString(dict, *p, Py_None); + } + for (p = sys_files; *p != NULL; p+=2) { + if (Py_VerboseFlag) + PySys_WriteStderr("# restore sys.%s\n", *p); + v = PyDict_GetItemString(dict, *(p+1)); + if (v == NULL) + v = Py_None; + PyDict_SetItemString(dict, *p, v); + } + } + + /* First, delete __main__ */ + value = PyDict_GetItemString(modules, "__main__"); + if (value != NULL && PyModule_Check(value)) { + if (Py_VerboseFlag) + PySys_WriteStderr("# cleanup __main__\n"); + _PyModule_Clear(value); + PyDict_SetItemString(modules, "__main__", Py_None); + } + + /* The special treatment of "builtins" here is because even + when it's not referenced as a module, its dictionary is + referenced by almost every module's __builtins__. Since + deleting a module clears its dictionary (even if there are + references left to it), we need to delete the "builtins" + module last. Likewise, we don't delete sys until the very + end because it is implicitly referenced (e.g. by print). + + Also note that we 'delete' modules by replacing their entry + in the modules dict with None, rather than really deleting + them; this avoids a rehash of the modules dictionary and + also marks them as "non existent" so they won't be + re-imported. */ + + /* Next, repeatedly delete modules with a reference count of + one (skipping builtins and sys) and delete them */ + do { + ndone = 0; + pos = 0; + while (PyDict_Next(modules, &pos, &key, &value)) { + if (value->ob_refcnt != 1) + continue; + if (PyUnicode_Check(key) && PyModule_Check(value)) { + name = _PyUnicode_AsString(key); + if (strcmp(name, "builtins") == 0) + continue; + if (strcmp(name, "sys") == 0) + continue; + if (Py_VerboseFlag) + PySys_WriteStderr( + "# cleanup[1] %s\n", name); + _PyModule_Clear(value); + PyDict_SetItem(modules, key, Py_None); + ndone++; + } + } + } while (ndone > 0); + + /* Next, delete all modules (still skipping builtins and sys) */ + pos = 0; + while (PyDict_Next(modules, &pos, &key, &value)) { + if (PyUnicode_Check(key) && PyModule_Check(value)) { + name = _PyUnicode_AsString(key); + if (strcmp(name, "builtins") == 0) + continue; + if (strcmp(name, "sys") == 0) + continue; + if (Py_VerboseFlag) + PySys_WriteStderr("# cleanup[2] %s\n", name); + _PyModule_Clear(value); + PyDict_SetItem(modules, key, Py_None); + } + } + + /* Next, delete sys and builtins (in that order) */ + value = PyDict_GetItemString(modules, "sys"); + if (value != NULL && PyModule_Check(value)) { + if (Py_VerboseFlag) + PySys_WriteStderr("# cleanup sys\n"); + _PyModule_Clear(value); + PyDict_SetItemString(modules, "sys", Py_None); + } + value = PyDict_GetItemString(modules, "builtins"); + if (value != NULL && PyModule_Check(value)) { + if (Py_VerboseFlag) + PySys_WriteStderr("# cleanup builtins\n"); + _PyModule_Clear(value); + PyDict_SetItemString(modules, "builtins", Py_None); + } + + /* Finally, clear and delete the modules directory */ + PyDict_Clear(modules); + interp->modules = NULL; + Py_DECREF(modules); + Py_CLEAR(interp->modules_reloading); } @@ -525,7 +525,7 @@ long PyImport_GetMagicNumber(void) { - return pyc_magic; + return pyc_magic; } @@ -537,7 +537,7 @@ dictionary is stored by calling _PyImport_FixupExtension() immediately after the module initialization function succeeds. A copy can be retrieved from there by calling - _PyImport_FindExtension(). + _PyImport_FindExtension(). Modules which do support multiple multiple initialization set their m_size field to a non-negative number (indicating the size @@ -548,90 +548,90 @@ int _PyImport_FixupExtension(PyObject *mod, char *name, char *filename) { - PyObject *modules, *dict; - struct PyModuleDef *def; - if (extensions == NULL) { - extensions = PyDict_New(); - if (extensions == NULL) - return -1; - } - if (mod == NULL || !PyModule_Check(mod)) { - PyErr_BadInternalCall(); - return -1; - } - def = PyModule_GetDef(mod); - if (!def) { - PyErr_BadInternalCall(); - return -1; - } - modules = PyImport_GetModuleDict(); - if (PyDict_SetItemString(modules, name, mod) < 0) - return -1; - if (_PyState_AddModule(mod, def) < 0) { - PyDict_DelItemString(modules, name); - return -1; - } - if (def->m_size == -1) { - if (def->m_base.m_copy) { - /* Somebody already imported the module, - likely under a different name. - XXX this should really not happen. */ - Py_DECREF(def->m_base.m_copy); - def->m_base.m_copy = NULL; - } - dict = PyModule_GetDict(mod); - if (dict == NULL) - return -1; - def->m_base.m_copy = PyDict_Copy(dict); - if (def->m_base.m_copy == NULL) - return -1; - } - PyDict_SetItemString(extensions, filename, (PyObject*)def); - return 0; + PyObject *modules, *dict; + struct PyModuleDef *def; + if (extensions == NULL) { + extensions = PyDict_New(); + if (extensions == NULL) + return -1; + } + if (mod == NULL || !PyModule_Check(mod)) { + PyErr_BadInternalCall(); + return -1; + } + def = PyModule_GetDef(mod); + if (!def) { + PyErr_BadInternalCall(); + return -1; + } + modules = PyImport_GetModuleDict(); + if (PyDict_SetItemString(modules, name, mod) < 0) + return -1; + if (_PyState_AddModule(mod, def) < 0) { + PyDict_DelItemString(modules, name); + return -1; + } + if (def->m_size == -1) { + if (def->m_base.m_copy) { + /* Somebody already imported the module, + likely under a different name. + XXX this should really not happen. */ + Py_DECREF(def->m_base.m_copy); + def->m_base.m_copy = NULL; + } + dict = PyModule_GetDict(mod); + if (dict == NULL) + return -1; + def->m_base.m_copy = PyDict_Copy(dict); + if (def->m_base.m_copy == NULL) + return -1; + } + PyDict_SetItemString(extensions, filename, (PyObject*)def); + return 0; } PyObject * _PyImport_FindExtension(char *name, char *filename) { - PyObject *mod, *mdict; - PyModuleDef* def; - if (extensions == NULL) - return NULL; - def = (PyModuleDef*)PyDict_GetItemString(extensions, filename); - if (def == NULL) - return NULL; - if (def->m_size == -1) { - /* Module does not support repeated initialization */ - if (def->m_base.m_copy == NULL) - return NULL; - mod = PyImport_AddModule(name); - if (mod == NULL) - return NULL; - mdict = PyModule_GetDict(mod); - if (mdict == NULL) - return NULL; - if (PyDict_Update(mdict, def->m_base.m_copy)) - return NULL; - } - else { - if (def->m_base.m_init == NULL) - return NULL; - mod = def->m_base.m_init(); - if (mod == NULL) - return NULL; - PyDict_SetItemString(PyImport_GetModuleDict(), name, mod); - Py_DECREF(mod); - } - if (_PyState_AddModule(mod, def) < 0) { - PyDict_DelItemString(PyImport_GetModuleDict(), name); - Py_DECREF(mod); - return NULL; - } - if (Py_VerboseFlag) - PySys_WriteStderr("import %s # previously loaded (%s)\n", - name, filename); - return mod; - + PyObject *mod, *mdict; + PyModuleDef* def; + if (extensions == NULL) + return NULL; + def = (PyModuleDef*)PyDict_GetItemString(extensions, filename); + if (def == NULL) + return NULL; + if (def->m_size == -1) { + /* Module does not support repeated initialization */ + if (def->m_base.m_copy == NULL) + return NULL; + mod = PyImport_AddModule(name); + if (mod == NULL) + return NULL; + mdict = PyModule_GetDict(mod); + if (mdict == NULL) + return NULL; + if (PyDict_Update(mdict, def->m_base.m_copy)) + return NULL; + } + else { + if (def->m_base.m_init == NULL) + return NULL; + mod = def->m_base.m_init(); + if (mod == NULL) + return NULL; + PyDict_SetItemString(PyImport_GetModuleDict(), name, mod); + Py_DECREF(mod); + } + if (_PyState_AddModule(mod, def) < 0) { + PyDict_DelItemString(PyImport_GetModuleDict(), name); + Py_DECREF(mod); + return NULL; + } + if (Py_VerboseFlag) + PySys_WriteStderr("import %s # previously loaded (%s)\n", + name, filename); + return mod; + } @@ -644,34 +644,34 @@ PyObject * PyImport_AddModule(const char *name) { - PyObject *modules = PyImport_GetModuleDict(); - PyObject *m; + PyObject *modules = PyImport_GetModuleDict(); + PyObject *m; - if ((m = PyDict_GetItemString(modules, name)) != NULL && - PyModule_Check(m)) - return m; - m = PyModule_New(name); - if (m == NULL) - return NULL; - if (PyDict_SetItemString(modules, name, m) != 0) { - Py_DECREF(m); - return NULL; - } - Py_DECREF(m); /* Yes, it still exists, in modules! */ + if ((m = PyDict_GetItemString(modules, name)) != NULL && + PyModule_Check(m)) + return m; + m = PyModule_New(name); + if (m == NULL) + return NULL; + if (PyDict_SetItemString(modules, name, m) != 0) { + Py_DECREF(m); + return NULL; + } + Py_DECREF(m); /* Yes, it still exists, in modules! */ - return m; + return m; } /* Remove name from sys.modules, if it's there. */ static void _RemoveModule(const char *name) { - PyObject *modules = PyImport_GetModuleDict(); - if (PyDict_GetItemString(modules, name) == NULL) - return; - if (PyDict_DelItemString(modules, name) < 0) - Py_FatalError("import: deleting existing key in" - "sys.modules failed"); + PyObject *modules = PyImport_GetModuleDict(); + if (PyDict_GetItemString(modules, name) == NULL) + return; + if (PyDict_DelItemString(modules, name) < 0) + Py_FatalError("import: deleting existing key in" + "sys.modules failed"); } static PyObject * get_sourcefile(const char *file); @@ -686,60 +686,60 @@ PyObject * PyImport_ExecCodeModule(char *name, PyObject *co) { - return PyImport_ExecCodeModuleEx(name, co, (char *)NULL); + return PyImport_ExecCodeModuleEx(name, co, (char *)NULL); } PyObject * PyImport_ExecCodeModuleEx(char *name, PyObject *co, char *pathname) { - PyObject *modules = PyImport_GetModuleDict(); - PyObject *m, *d, *v; + PyObject *modules = PyImport_GetModuleDict(); + PyObject *m, *d, *v; - m = PyImport_AddModule(name); - if (m == NULL) - return NULL; - /* If the module is being reloaded, we get the old module back - and re-use its dict to exec the new code. */ - d = PyModule_GetDict(m); - if (PyDict_GetItemString(d, "__builtins__") == NULL) { - if (PyDict_SetItemString(d, "__builtins__", - PyEval_GetBuiltins()) != 0) - goto error; - } - /* Remember the filename as the __file__ attribute */ - v = NULL; - if (pathname != NULL) { - v = get_sourcefile(pathname); - if (v == NULL) - PyErr_Clear(); - } - if (v == NULL) { - v = ((PyCodeObject *)co)->co_filename; - Py_INCREF(v); - } - if (PyDict_SetItemString(d, "__file__", v) != 0) - PyErr_Clear(); /* Not important enough to report */ - Py_DECREF(v); - - v = PyEval_EvalCode((PyCodeObject *)co, d, d); - if (v == NULL) - goto error; - Py_DECREF(v); - - if ((m = PyDict_GetItemString(modules, name)) == NULL) { - PyErr_Format(PyExc_ImportError, - "Loaded module %.200s not found in sys.modules", - name); - return NULL; - } + m = PyImport_AddModule(name); + if (m == NULL) + return NULL; + /* If the module is being reloaded, we get the old module back + and re-use its dict to exec the new code. */ + d = PyModule_GetDict(m); + if (PyDict_GetItemString(d, "__builtins__") == NULL) { + if (PyDict_SetItemString(d, "__builtins__", + PyEval_GetBuiltins()) != 0) + goto error; + } + /* Remember the filename as the __file__ attribute */ + v = NULL; + if (pathname != NULL) { + v = get_sourcefile(pathname); + if (v == NULL) + PyErr_Clear(); + } + if (v == NULL) { + v = ((PyCodeObject *)co)->co_filename; + Py_INCREF(v); + } + if (PyDict_SetItemString(d, "__file__", v) != 0) + PyErr_Clear(); /* Not important enough to report */ + Py_DECREF(v); + + v = PyEval_EvalCode((PyCodeObject *)co, d, d); + if (v == NULL) + goto error; + Py_DECREF(v); + + if ((m = PyDict_GetItemString(modules, name)) == NULL) { + PyErr_Format(PyExc_ImportError, + "Loaded module %.200s not found in sys.modules", + name); + return NULL; + } - Py_INCREF(m); + Py_INCREF(m); - return m; + return m; error: - _RemoveModule(name); - return NULL; + _RemoveModule(name); + return NULL; } @@ -751,21 +751,21 @@ static char * make_compiled_pathname(char *pathname, char *buf, size_t buflen) { - size_t len = strlen(pathname); - if (len+2 > buflen) - return NULL; + size_t len = strlen(pathname); + if (len+2 > buflen) + return NULL; #ifdef MS_WINDOWS - /* Treat .pyw as if it were .py. The case of ".pyw" must match - that used in _PyImport_StandardFiletab. */ - if (len >= 4 && strcmp(&pathname[len-4], ".pyw") == 0) - --len; /* pretend 'w' isn't there */ -#endif - memcpy(buf, pathname, len); - buf[len] = Py_OptimizeFlag ? 'o' : 'c'; - buf[len+1] = '\0'; + /* Treat .pyw as if it were .py. The case of ".pyw" must match + that used in _PyImport_StandardFiletab. */ + if (len >= 4 && strcmp(&pathname[len-4], ".pyw") == 0) + --len; /* pretend 'w' isn't there */ +#endif + memcpy(buf, pathname, len); + buf[len] = Py_OptimizeFlag ? 'o' : 'c'; + buf[len+1] = '\0'; - return buf; + return buf; } @@ -779,30 +779,30 @@ static FILE * check_compiled_module(char *pathname, time_t mtime, char *cpathname) { - FILE *fp; - long magic; - long pyc_mtime; - - fp = fopen(cpathname, "rb"); - if (fp == NULL) - return NULL; - magic = PyMarshal_ReadLongFromFile(fp); - if (magic != pyc_magic) { - if (Py_VerboseFlag) - PySys_WriteStderr("# %s has bad magic\n", cpathname); - fclose(fp); - return NULL; - } - pyc_mtime = PyMarshal_ReadLongFromFile(fp); - if (pyc_mtime != mtime) { - if (Py_VerboseFlag) - PySys_WriteStderr("# %s has bad mtime\n", cpathname); - fclose(fp); - return NULL; - } - if (Py_VerboseFlag) - PySys_WriteStderr("# %s matches %s\n", cpathname, pathname); - return fp; + FILE *fp; + long magic; + long pyc_mtime; + + fp = fopen(cpathname, "rb"); + if (fp == NULL) + return NULL; + magic = PyMarshal_ReadLongFromFile(fp); + if (magic != pyc_magic) { + if (Py_VerboseFlag) + PySys_WriteStderr("# %s has bad magic\n", cpathname); + fclose(fp); + return NULL; + } + pyc_mtime = PyMarshal_ReadLongFromFile(fp); + if (pyc_mtime != mtime) { + if (Py_VerboseFlag) + PySys_WriteStderr("# %s has bad mtime\n", cpathname); + fclose(fp); + return NULL; + } + if (Py_VerboseFlag) + PySys_WriteStderr("# %s matches %s\n", cpathname, pathname); + return fp; } @@ -811,18 +811,18 @@ static PyCodeObject * read_compiled_module(char *cpathname, FILE *fp) { - PyObject *co; + PyObject *co; - co = PyMarshal_ReadLastObjectFromFile(fp); - if (co == NULL) - return NULL; - if (!PyCode_Check(co)) { - PyErr_Format(PyExc_ImportError, - "Non-code object in %.200s", cpathname); - Py_DECREF(co); - return NULL; - } - return (PyCodeObject *)co; + co = PyMarshal_ReadLastObjectFromFile(fp); + if (co == NULL) + return NULL; + if (!PyCode_Check(co)) { + PyErr_Format(PyExc_ImportError, + "Non-code object in %.200s", cpathname); + Py_DECREF(co); + return NULL; + } + return (PyCodeObject *)co; } @@ -832,27 +832,27 @@ static PyObject * load_compiled_module(char *name, char *cpathname, FILE *fp) { - long magic; - PyCodeObject *co; - PyObject *m; - - magic = PyMarshal_ReadLongFromFile(fp); - if (magic != pyc_magic) { - PyErr_Format(PyExc_ImportError, - "Bad magic number in %.200s", cpathname); - return NULL; - } - (void) PyMarshal_ReadLongFromFile(fp); - co = read_compiled_module(cpathname, fp); - if (co == NULL) - return NULL; - if (Py_VerboseFlag) - PySys_WriteStderr("import %s # precompiled from %s\n", - name, cpathname); - m = PyImport_ExecCodeModuleEx(name, (PyObject *)co, cpathname); - Py_DECREF(co); + long magic; + PyCodeObject *co; + PyObject *m; + + magic = PyMarshal_ReadLongFromFile(fp); + if (magic != pyc_magic) { + PyErr_Format(PyExc_ImportError, + "Bad magic number in %.200s", cpathname); + return NULL; + } + (void) PyMarshal_ReadLongFromFile(fp); + co = read_compiled_module(cpathname, fp); + if (co == NULL) + return NULL; + if (Py_VerboseFlag) + PySys_WriteStderr("import %s # precompiled from %s\n", + name, cpathname); + m = PyImport_ExecCodeModuleEx(name, (PyObject *)co, cpathname); + Py_DECREF(co); - return m; + return m; } /* Parse a source file and return the corresponding code object */ @@ -860,22 +860,22 @@ static PyCodeObject * parse_source_module(const char *pathname, FILE *fp) { - PyCodeObject *co = NULL; - mod_ty mod; - PyCompilerFlags flags; - PyArena *arena = PyArena_New(); - if (arena == NULL) - return NULL; - - flags.cf_flags = 0; - mod = PyParser_ASTFromFile(fp, pathname, NULL, - Py_file_input, 0, 0, &flags, - NULL, arena); - if (mod) { - co = PyAST_Compile(mod, pathname, NULL, arena); - } - PyArena_Free(arena); - return co; + PyCodeObject *co = NULL; + mod_ty mod; + PyCompilerFlags flags; + PyArena *arena = PyArena_New(); + if (arena == NULL) + return NULL; + + flags.cf_flags = 0; + mod = PyParser_ASTFromFile(fp, pathname, NULL, + Py_file_input, 0, 0, &flags, + NULL, arena); + if (mod) { + co = PyAST_Compile(mod, pathname, NULL, arena); + } + PyArena_Free(arena); + return co; } @@ -885,30 +885,30 @@ open_exclusive(char *filename, mode_t mode) { #if defined(O_EXCL)&&defined(O_CREAT)&&defined(O_WRONLY)&&defined(O_TRUNC) - /* Use O_EXCL to avoid a race condition when another process tries to - write the same file. When that happens, our open() call fails, - which is just fine (since it's only a cache). - XXX If the file exists and is writable but the directory is not - writable, the file will never be written. Oh well. - */ - int fd; - (void) unlink(filename); - fd = open(filename, O_EXCL|O_CREAT|O_WRONLY|O_TRUNC + /* Use O_EXCL to avoid a race condition when another process tries to + write the same file. When that happens, our open() call fails, + which is just fine (since it's only a cache). + XXX If the file exists and is writable but the directory is not + writable, the file will never be written. Oh well. + */ + int fd; + (void) unlink(filename); + fd = open(filename, O_EXCL|O_CREAT|O_WRONLY|O_TRUNC #ifdef O_BINARY - |O_BINARY /* necessary for Windows */ + |O_BINARY /* necessary for Windows */ #endif #ifdef __VMS - , mode, "ctxt=bin", "shr=nil" + , mode, "ctxt=bin", "shr=nil" #else - , mode + , mode #endif - ); - if (fd < 0) - return NULL; - return fdopen(fd, "wb"); + ); + if (fd < 0) + return NULL; + return fdopen(fd, "wb"); #else - /* Best we can do -- on Windows this can't happen anyway */ - return fopen(filename, "wb"); + /* Best we can do -- on Windows this can't happen anyway */ + return fopen(filename, "wb"); #endif } @@ -921,87 +921,87 @@ static void write_compiled_module(PyCodeObject *co, char *cpathname, struct stat *srcstat) { - FILE *fp; - time_t mtime = srcstat->st_mtime; + FILE *fp; + time_t mtime = srcstat->st_mtime; #ifdef MS_WINDOWS /* since Windows uses different permissions */ - mode_t mode = srcstat->st_mode & ~S_IEXEC; + mode_t mode = srcstat->st_mode & ~S_IEXEC; #else - mode_t mode = srcstat->st_mode & ~S_IXUSR & ~S_IXGRP & ~S_IXOTH; -#endif + mode_t mode = srcstat->st_mode & ~S_IXUSR & ~S_IXGRP & ~S_IXOTH; +#endif - fp = open_exclusive(cpathname, mode); - if (fp == NULL) { - if (Py_VerboseFlag) - PySys_WriteStderr( - "# can't create %s\n", cpathname); - return; - } - PyMarshal_WriteLongToFile(pyc_magic, fp, Py_MARSHAL_VERSION); - /* First write a 0 for mtime */ - PyMarshal_WriteLongToFile(0L, fp, Py_MARSHAL_VERSION); - PyMarshal_WriteObjectToFile((PyObject *)co, fp, Py_MARSHAL_VERSION); - if (fflush(fp) != 0 || ferror(fp)) { - if (Py_VerboseFlag) - PySys_WriteStderr("# can't write %s\n", cpathname); - /* Don't keep partial file */ - fclose(fp); - (void) unlink(cpathname); - return; - } - /* Now write the true mtime */ - fseek(fp, 4L, 0); - assert(mtime < LONG_MAX); - PyMarshal_WriteLongToFile((long)mtime, fp, Py_MARSHAL_VERSION); - fflush(fp); - fclose(fp); - if (Py_VerboseFlag) - PySys_WriteStderr("# wrote %s\n", cpathname); + fp = open_exclusive(cpathname, mode); + if (fp == NULL) { + if (Py_VerboseFlag) + PySys_WriteStderr( + "# can't create %s\n", cpathname); + return; + } + PyMarshal_WriteLongToFile(pyc_magic, fp, Py_MARSHAL_VERSION); + /* First write a 0 for mtime */ + PyMarshal_WriteLongToFile(0L, fp, Py_MARSHAL_VERSION); + PyMarshal_WriteObjectToFile((PyObject *)co, fp, Py_MARSHAL_VERSION); + if (fflush(fp) != 0 || ferror(fp)) { + if (Py_VerboseFlag) + PySys_WriteStderr("# can't write %s\n", cpathname); + /* Don't keep partial file */ + fclose(fp); + (void) unlink(cpathname); + return; + } + /* Now write the true mtime */ + fseek(fp, 4L, 0); + assert(mtime < LONG_MAX); + PyMarshal_WriteLongToFile((long)mtime, fp, Py_MARSHAL_VERSION); + fflush(fp); + fclose(fp); + if (Py_VerboseFlag) + PySys_WriteStderr("# wrote %s\n", cpathname); } static void update_code_filenames(PyCodeObject *co, PyObject *oldname, PyObject *newname) { - PyObject *constants, *tmp; - Py_ssize_t i, n; + PyObject *constants, *tmp; + Py_ssize_t i, n; - if (PyUnicode_Compare(co->co_filename, oldname)) - return; + if (PyUnicode_Compare(co->co_filename, oldname)) + return; - tmp = co->co_filename; - co->co_filename = newname; - Py_INCREF(co->co_filename); - Py_DECREF(tmp); - - constants = co->co_consts; - n = PyTuple_GET_SIZE(constants); - for (i = 0; i < n; i++) { - tmp = PyTuple_GET_ITEM(constants, i); - if (PyCode_Check(tmp)) - update_code_filenames((PyCodeObject *)tmp, - oldname, newname); - } + tmp = co->co_filename; + co->co_filename = newname; + Py_INCREF(co->co_filename); + Py_DECREF(tmp); + + constants = co->co_consts; + n = PyTuple_GET_SIZE(constants); + for (i = 0; i < n; i++) { + tmp = PyTuple_GET_ITEM(constants, i); + if (PyCode_Check(tmp)) + update_code_filenames((PyCodeObject *)tmp, + oldname, newname); + } } static int update_compiled_module(PyCodeObject *co, char *pathname) { - PyObject *oldname, *newname; + PyObject *oldname, *newname; - newname = PyUnicode_DecodeFSDefault(pathname); - if (newname == NULL) - return -1; - - if (!PyUnicode_Compare(co->co_filename, newname)) { - Py_DECREF(newname); - return 0; - } - - oldname = co->co_filename; - Py_INCREF(oldname); - update_code_filenames(co, oldname, newname); - Py_DECREF(oldname); - Py_DECREF(newname); - return 1; + newname = PyUnicode_DecodeFSDefault(pathname); + if (newname == NULL) + return -1; + + if (!PyUnicode_Compare(co->co_filename, newname)) { + Py_DECREF(newname); + return 0; + } + + oldname = co->co_filename; + Py_INCREF(oldname); + update_code_filenames(co, oldname, newname); + Py_DECREF(oldname); + Py_DECREF(newname); + return 1; } /* Load a source module from a given file and return its module @@ -1011,62 +1011,62 @@ static PyObject * load_source_module(char *name, char *pathname, FILE *fp) { - struct stat st; - FILE *fpc; - char buf[MAXPATHLEN+1]; - char *cpathname; - PyCodeObject *co; - PyObject *m; - - if (fstat(fileno(fp), &st) != 0) { - PyErr_Format(PyExc_RuntimeError, - "unable to get file status from '%s'", - pathname); - return NULL; - } + struct stat st; + FILE *fpc; + char buf[MAXPATHLEN+1]; + char *cpathname; + PyCodeObject *co; + PyObject *m; + + if (fstat(fileno(fp), &st) != 0) { + PyErr_Format(PyExc_RuntimeError, + "unable to get file status from '%s'", + pathname); + return NULL; + } #if SIZEOF_TIME_T > 4 - /* Python's .pyc timestamp handling presumes that the timestamp fits - in 4 bytes. This will be fine until sometime in the year 2038, - when a 4-byte signed time_t will overflow. - */ - if (st.st_mtime >> 32) { - PyErr_SetString(PyExc_OverflowError, - "modification time overflows a 4 byte field"); - return NULL; - } -#endif - cpathname = make_compiled_pathname(pathname, buf, - (size_t)MAXPATHLEN + 1); - if (cpathname != NULL && - (fpc = check_compiled_module(pathname, st.st_mtime, cpathname))) { - co = read_compiled_module(cpathname, fpc); - fclose(fpc); - if (co == NULL) - return NULL; - if (update_compiled_module(co, pathname) < 0) - return NULL; - if (Py_VerboseFlag) - PySys_WriteStderr("import %s # precompiled from %s\n", - name, cpathname); - pathname = cpathname; - } - else { - co = parse_source_module(pathname, fp); - if (co == NULL) - return NULL; - if (Py_VerboseFlag) - PySys_WriteStderr("import %s # from %s\n", - name, pathname); - if (cpathname) { - PyObject *ro = PySys_GetObject("dont_write_bytecode"); - if (ro == NULL || !PyObject_IsTrue(ro)) - write_compiled_module(co, cpathname, &st); - } - } - m = PyImport_ExecCodeModuleEx(name, (PyObject *)co, pathname); - Py_DECREF(co); + /* Python's .pyc timestamp handling presumes that the timestamp fits + in 4 bytes. This will be fine until sometime in the year 2038, + when a 4-byte signed time_t will overflow. + */ + if (st.st_mtime >> 32) { + PyErr_SetString(PyExc_OverflowError, + "modification time overflows a 4 byte field"); + return NULL; + } +#endif + cpathname = make_compiled_pathname(pathname, buf, + (size_t)MAXPATHLEN + 1); + if (cpathname != NULL && + (fpc = check_compiled_module(pathname, st.st_mtime, cpathname))) { + co = read_compiled_module(cpathname, fpc); + fclose(fpc); + if (co == NULL) + return NULL; + if (update_compiled_module(co, pathname) < 0) + return NULL; + if (Py_VerboseFlag) + PySys_WriteStderr("import %s # precompiled from %s\n", + name, cpathname); + pathname = cpathname; + } + else { + co = parse_source_module(pathname, fp); + if (co == NULL) + return NULL; + if (Py_VerboseFlag) + PySys_WriteStderr("import %s # from %s\n", + name, pathname); + if (cpathname) { + PyObject *ro = PySys_GetObject("dont_write_bytecode"); + if (ro == NULL || !PyObject_IsTrue(ro)) + write_compiled_module(co, cpathname, &st); + } + } + m = PyImport_ExecCodeModuleEx(name, (PyObject *)co, pathname); + Py_DECREF(co); - return m; + return m; } /* Get source file -> unicode or None @@ -1075,37 +1075,37 @@ static PyObject * get_sourcefile(const char *file) { - char py[MAXPATHLEN + 1]; - Py_ssize_t len; - PyObject *u; - struct stat statbuf; - - if (!file || !*file) { - Py_RETURN_NONE; - } - - len = strlen(file); - /* match '*.py?' */ - if (len > MAXPATHLEN || PyOS_strnicmp(&file[len-4], ".py", 3) != 0) { - return PyUnicode_DecodeFSDefault(file); - } - - strncpy(py, file, len-1); - py[len-1] = '\0'; - if (stat(py, &statbuf) == 0 && - S_ISREG(statbuf.st_mode)) { - u = PyUnicode_DecodeFSDefault(py); - } - else { - u = PyUnicode_DecodeFSDefault(file); - } - return u; + char py[MAXPATHLEN + 1]; + Py_ssize_t len; + PyObject *u; + struct stat statbuf; + + if (!file || !*file) { + Py_RETURN_NONE; + } + + len = strlen(file); + /* match '*.py?' */ + if (len > MAXPATHLEN || PyOS_strnicmp(&file[len-4], ".py", 3) != 0) { + return PyUnicode_DecodeFSDefault(file); + } + + strncpy(py, file, len-1); + py[len-1] = '\0'; + if (stat(py, &statbuf) == 0 && + S_ISREG(statbuf.st_mode)) { + u = PyUnicode_DecodeFSDefault(py); + } + else { + u = PyUnicode_DecodeFSDefault(file); + } + return u; } /* Forward */ static PyObject *load_module(char *, FILE *, char *, int, PyObject *); static struct filedescr *find_module(char *, char *, PyObject *, - char *, size_t, FILE **, PyObject **); + char *, size_t, FILE **, PyObject **); static struct _frozen * find_frozen(char *); /* Load a package and return its module object WITH INCREMENTED @@ -1114,54 +1114,54 @@ static PyObject * load_package(char *name, char *pathname) { - PyObject *m, *d; - PyObject *file = NULL; - PyObject *path = NULL; - int err; - char buf[MAXPATHLEN+1]; - FILE *fp = NULL; - struct filedescr *fdp; - - m = PyImport_AddModule(name); - if (m == NULL) - return NULL; - if (Py_VerboseFlag) - PySys_WriteStderr("import %s # directory %s\n", - name, pathname); - d = PyModule_GetDict(m); - file = get_sourcefile(pathname); - if (file == NULL) - goto error; - path = Py_BuildValue("[O]", file); - if (path == NULL) - goto error; - err = PyDict_SetItemString(d, "__file__", file); - if (err == 0) - err = PyDict_SetItemString(d, "__path__", path); - if (err != 0) - goto error; - buf[0] = '\0'; - fdp = find_module(name, "__init__", path, buf, sizeof(buf), &fp, NULL); - if (fdp == NULL) { - if (PyErr_ExceptionMatches(PyExc_ImportError)) { - PyErr_Clear(); - Py_INCREF(m); - } - else - m = NULL; - goto cleanup; - } - m = load_module(name, fp, buf, fdp->type, NULL); - if (fp != NULL) - fclose(fp); - goto cleanup; + PyObject *m, *d; + PyObject *file = NULL; + PyObject *path = NULL; + int err; + char buf[MAXPATHLEN+1]; + FILE *fp = NULL; + struct filedescr *fdp; + + m = PyImport_AddModule(name); + if (m == NULL) + return NULL; + if (Py_VerboseFlag) + PySys_WriteStderr("import %s # directory %s\n", + name, pathname); + d = PyModule_GetDict(m); + file = get_sourcefile(pathname); + if (file == NULL) + goto error; + path = Py_BuildValue("[O]", file); + if (path == NULL) + goto error; + err = PyDict_SetItemString(d, "__file__", file); + if (err == 0) + err = PyDict_SetItemString(d, "__path__", path); + if (err != 0) + goto error; + buf[0] = '\0'; + fdp = find_module(name, "__init__", path, buf, sizeof(buf), &fp, NULL); + if (fdp == NULL) { + if (PyErr_ExceptionMatches(PyExc_ImportError)) { + PyErr_Clear(); + Py_INCREF(m); + } + else + m = NULL; + goto cleanup; + } + m = load_module(name, fp, buf, fdp->type, NULL); + if (fp != NULL) + fclose(fp); + goto cleanup; error: - m = NULL; + m = NULL; cleanup: - Py_XDECREF(path); - Py_XDECREF(file); - return m; + Py_XDECREF(path); + Py_XDECREF(file); + return m; } @@ -1170,16 +1170,16 @@ static int is_builtin(char *name) { - int i; - for (i = 0; PyImport_Inittab[i].name != NULL; i++) { - if (strcmp(name, PyImport_Inittab[i].name) == 0) { - if (PyImport_Inittab[i].initfunc == NULL) - return -1; - else - return 1; - } - } - return 0; + int i; + for (i = 0; PyImport_Inittab[i].name != NULL; i++) { + if (strcmp(name, PyImport_Inittab[i].name) == 0) { + if (PyImport_Inittab[i].initfunc == NULL) + return -1; + else + return 1; + } + } + return 0; } @@ -1193,72 +1193,72 @@ static PyObject * get_path_importer(PyObject *path_importer_cache, PyObject *path_hooks, - PyObject *p) + PyObject *p) { - PyObject *importer; - Py_ssize_t j, nhooks; + PyObject *importer; + Py_ssize_t j, nhooks; - /* These conditions are the caller's responsibility: */ - assert(PyList_Check(path_hooks)); - assert(PyDict_Check(path_importer_cache)); - - nhooks = PyList_Size(path_hooks); - if (nhooks < 0) - return NULL; /* Shouldn't happen */ - - importer = PyDict_GetItem(path_importer_cache, p); - if (importer != NULL) - return importer; - - /* set path_importer_cache[p] to None to avoid recursion */ - if (PyDict_SetItem(path_importer_cache, p, Py_None) != 0) - return NULL; - - for (j = 0; j < nhooks; j++) { - PyObject *hook = PyList_GetItem(path_hooks, j); - if (hook == NULL) - return NULL; - importer = PyObject_CallFunctionObjArgs(hook, p, NULL); - if (importer != NULL) - break; - - if (!PyErr_ExceptionMatches(PyExc_ImportError)) { - return NULL; - } - PyErr_Clear(); - } - if (importer == NULL) { - importer = PyObject_CallFunctionObjArgs( - (PyObject *)&PyNullImporter_Type, p, NULL - ); - if (importer == NULL) { - if (PyErr_ExceptionMatches(PyExc_ImportError)) { - PyErr_Clear(); - return Py_None; - } - } - } - if (importer != NULL) { - int err = PyDict_SetItem(path_importer_cache, p, importer); - Py_DECREF(importer); - if (err != 0) - return NULL; - } - return importer; + /* These conditions are the caller's responsibility: */ + assert(PyList_Check(path_hooks)); + assert(PyDict_Check(path_importer_cache)); + + nhooks = PyList_Size(path_hooks); + if (nhooks < 0) + return NULL; /* Shouldn't happen */ + + importer = PyDict_GetItem(path_importer_cache, p); + if (importer != NULL) + return importer; + + /* set path_importer_cache[p] to None to avoid recursion */ + if (PyDict_SetItem(path_importer_cache, p, Py_None) != 0) + return NULL; + + for (j = 0; j < nhooks; j++) { + PyObject *hook = PyList_GetItem(path_hooks, j); + if (hook == NULL) + return NULL; + importer = PyObject_CallFunctionObjArgs(hook, p, NULL); + if (importer != NULL) + break; + + if (!PyErr_ExceptionMatches(PyExc_ImportError)) { + return NULL; + } + PyErr_Clear(); + } + if (importer == NULL) { + importer = PyObject_CallFunctionObjArgs( + (PyObject *)&PyNullImporter_Type, p, NULL + ); + if (importer == NULL) { + if (PyErr_ExceptionMatches(PyExc_ImportError)) { + PyErr_Clear(); + return Py_None; + } + } + } + if (importer != NULL) { + int err = PyDict_SetItem(path_importer_cache, p, importer); + Py_DECREF(importer); + if (err != 0) + return NULL; + } + return importer; } PyAPI_FUNC(PyObject *) PyImport_GetImporter(PyObject *path) { - PyObject *importer=NULL, *path_importer_cache=NULL, *path_hooks=NULL; + PyObject *importer=NULL, *path_importer_cache=NULL, *path_hooks=NULL; - if ((path_importer_cache = PySys_GetObject("path_importer_cache"))) { - if ((path_hooks = PySys_GetObject("path_hooks"))) { - importer = get_path_importer(path_importer_cache, - path_hooks, path); - } - } - Py_XINCREF(importer); /* get_path_importer returns a borrowed reference */ - return importer; + if ((path_importer_cache = PySys_GetObject("path_importer_cache"))) { + if ((path_hooks = PySys_GetObject("path_hooks"))) { + importer = get_path_importer(path_importer_cache, + path_hooks, path); + } + } + Py_XINCREF(importer); /* get_path_importer returns a borrowed reference */ + return importer; } /* Search the path (default sys.path) for a module. Return the @@ -1267,7 +1267,7 @@ #ifdef MS_COREDLL extern FILE *PyWin_FindRegisteredModule(const char *, struct filedescr **, - char *, Py_ssize_t); + char *, Py_ssize_t); #endif static int case_ok(char *, Py_ssize_t, Py_ssize_t, char *); @@ -1276,276 +1276,276 @@ static struct filedescr * find_module(char *fullname, char *subname, PyObject *path, char *buf, - size_t buflen, FILE **p_fp, PyObject **p_loader) + size_t buflen, FILE **p_fp, PyObject **p_loader) { - Py_ssize_t i, npath; - size_t len, namelen; - struct filedescr *fdp = NULL; - char *filemode; - FILE *fp = NULL; - PyObject *path_hooks, *path_importer_cache; - struct stat statbuf; - static struct filedescr fd_frozen = {"", "", PY_FROZEN}; - static struct filedescr fd_builtin = {"", "", C_BUILTIN}; - static struct filedescr fd_package = {"", "", PKG_DIRECTORY}; - char name[MAXPATHLEN+1]; + Py_ssize_t i, npath; + size_t len, namelen; + struct filedescr *fdp = NULL; + char *filemode; + FILE *fp = NULL; + PyObject *path_hooks, *path_importer_cache; + struct stat statbuf; + static struct filedescr fd_frozen = {"", "", PY_FROZEN}; + static struct filedescr fd_builtin = {"", "", C_BUILTIN}; + static struct filedescr fd_package = {"", "", PKG_DIRECTORY}; + char name[MAXPATHLEN+1]; #if defined(PYOS_OS2) - size_t saved_len; - size_t saved_namelen; - char *saved_buf = NULL; -#endif - if (p_loader != NULL) - *p_loader = NULL; - - if (strlen(subname) > MAXPATHLEN) { - PyErr_SetString(PyExc_OverflowError, - "module name is too long"); - return NULL; - } - strcpy(name, subname); - - /* sys.meta_path import hook */ - if (p_loader != NULL) { - PyObject *meta_path; - - meta_path = PySys_GetObject("meta_path"); - if (meta_path == NULL || !PyList_Check(meta_path)) { - PyErr_SetString(PyExc_ImportError, - "sys.meta_path must be a list of " - "import hooks"); - return NULL; - } - Py_INCREF(meta_path); /* zap guard */ - npath = PyList_Size(meta_path); - for (i = 0; i < npath; i++) { - PyObject *loader; - PyObject *hook = PyList_GetItem(meta_path, i); - loader = PyObject_CallMethod(hook, "find_module", - "sO", fullname, - path != NULL ? - path : Py_None); - if (loader == NULL) { - Py_DECREF(meta_path); - return NULL; /* true error */ - } - if (loader != Py_None) { - /* a loader was found */ - *p_loader = loader; - Py_DECREF(meta_path); - return &importhookdescr; - } - Py_DECREF(loader); - } - Py_DECREF(meta_path); - } - - if (find_frozen(fullname) != NULL) { - strcpy(buf, fullname); - return &fd_frozen; - } - - if (path == NULL) { - if (is_builtin(name)) { - strcpy(buf, name); - return &fd_builtin; - } + size_t saved_len; + size_t saved_namelen; + char *saved_buf = NULL; +#endif + if (p_loader != NULL) + *p_loader = NULL; + + if (strlen(subname) > MAXPATHLEN) { + PyErr_SetString(PyExc_OverflowError, + "module name is too long"); + return NULL; + } + strcpy(name, subname); + + /* sys.meta_path import hook */ + if (p_loader != NULL) { + PyObject *meta_path; + + meta_path = PySys_GetObject("meta_path"); + if (meta_path == NULL || !PyList_Check(meta_path)) { + PyErr_SetString(PyExc_ImportError, + "sys.meta_path must be a list of " + "import hooks"); + return NULL; + } + Py_INCREF(meta_path); /* zap guard */ + npath = PyList_Size(meta_path); + for (i = 0; i < npath; i++) { + PyObject *loader; + PyObject *hook = PyList_GetItem(meta_path, i); + loader = PyObject_CallMethod(hook, "find_module", + "sO", fullname, + path != NULL ? + path : Py_None); + if (loader == NULL) { + Py_DECREF(meta_path); + return NULL; /* true error */ + } + if (loader != Py_None) { + /* a loader was found */ + *p_loader = loader; + Py_DECREF(meta_path); + return &importhookdescr; + } + Py_DECREF(loader); + } + Py_DECREF(meta_path); + } + + if (find_frozen(fullname) != NULL) { + strcpy(buf, fullname); + return &fd_frozen; + } + + if (path == NULL) { + if (is_builtin(name)) { + strcpy(buf, name); + return &fd_builtin; + } #ifdef MS_COREDLL - fp = PyWin_FindRegisteredModule(name, &fdp, buf, buflen); - if (fp != NULL) { - *p_fp = fp; - return fdp; - } -#endif - path = PySys_GetObject("path"); - } - - if (path == NULL || !PyList_Check(path)) { - PyErr_SetString(PyExc_ImportError, - "sys.path must be a list of directory names"); - return NULL; - } - - path_hooks = PySys_GetObject("path_hooks"); - if (path_hooks == NULL || !PyList_Check(path_hooks)) { - PyErr_SetString(PyExc_ImportError, - "sys.path_hooks must be a list of " - "import hooks"); - return NULL; - } - path_importer_cache = PySys_GetObject("path_importer_cache"); - if (path_importer_cache == NULL || - !PyDict_Check(path_importer_cache)) { - PyErr_SetString(PyExc_ImportError, - "sys.path_importer_cache must be a dict"); - return NULL; - } - - npath = PyList_Size(path); - namelen = strlen(name); - for (i = 0; i < npath; i++) { - PyObject *v = PyList_GetItem(path, i); - PyObject *origv = v; - const char *base; - Py_ssize_t size; - if (!v) - return NULL; - if (PyUnicode_Check(v)) { - v = PyUnicode_AsEncodedString(v, - Py_FileSystemDefaultEncoding, NULL); - if (v == NULL) - return NULL; - } - else if (!PyBytes_Check(v)) - continue; - else - Py_INCREF(v); - - base = PyBytes_AS_STRING(v); - size = PyBytes_GET_SIZE(v); - len = size; - if (len + 2 + namelen + MAXSUFFIXSIZE >= buflen) { - Py_DECREF(v); - continue; /* Too long */ - } - strcpy(buf, base); - Py_DECREF(v); - - if (strlen(buf) != len) { - continue; /* v contains '\0' */ - } - - /* sys.path_hooks import hook */ - if (p_loader != NULL) { - PyObject *importer; - - importer = get_path_importer(path_importer_cache, - path_hooks, origv); - if (importer == NULL) { - return NULL; - } - /* Note: importer is a borrowed reference */ - if (importer != Py_None) { - PyObject *loader; - loader = PyObject_CallMethod(importer, - "find_module", - "s", fullname); - if (loader == NULL) - return NULL; /* error */ - if (loader != Py_None) { - /* a loader was found */ - *p_loader = loader; - return &importhookdescr; - } - Py_DECREF(loader); - continue; - } - } - /* no hook was found, use builtin import */ + fp = PyWin_FindRegisteredModule(name, &fdp, buf, buflen); + if (fp != NULL) { + *p_fp = fp; + return fdp; + } +#endif + path = PySys_GetObject("path"); + } + + if (path == NULL || !PyList_Check(path)) { + PyErr_SetString(PyExc_ImportError, + "sys.path must be a list of directory names"); + return NULL; + } + + path_hooks = PySys_GetObject("path_hooks"); + if (path_hooks == NULL || !PyList_Check(path_hooks)) { + PyErr_SetString(PyExc_ImportError, + "sys.path_hooks must be a list of " + "import hooks"); + return NULL; + } + path_importer_cache = PySys_GetObject("path_importer_cache"); + if (path_importer_cache == NULL || + !PyDict_Check(path_importer_cache)) { + PyErr_SetString(PyExc_ImportError, + "sys.path_importer_cache must be a dict"); + return NULL; + } + + npath = PyList_Size(path); + namelen = strlen(name); + for (i = 0; i < npath; i++) { + PyObject *v = PyList_GetItem(path, i); + PyObject *origv = v; + const char *base; + Py_ssize_t size; + if (!v) + return NULL; + if (PyUnicode_Check(v)) { + v = PyUnicode_AsEncodedString(v, + Py_FileSystemDefaultEncoding, NULL); + if (v == NULL) + return NULL; + } + else if (!PyBytes_Check(v)) + continue; + else + Py_INCREF(v); + + base = PyBytes_AS_STRING(v); + size = PyBytes_GET_SIZE(v); + len = size; + if (len + 2 + namelen + MAXSUFFIXSIZE >= buflen) { + Py_DECREF(v); + continue; /* Too long */ + } + strcpy(buf, base); + Py_DECREF(v); + + if (strlen(buf) != len) { + continue; /* v contains '\0' */ + } + + /* sys.path_hooks import hook */ + if (p_loader != NULL) { + PyObject *importer; + + importer = get_path_importer(path_importer_cache, + path_hooks, origv); + if (importer == NULL) { + return NULL; + } + /* Note: importer is a borrowed reference */ + if (importer != Py_None) { + PyObject *loader; + loader = PyObject_CallMethod(importer, + "find_module", + "s", fullname); + if (loader == NULL) + return NULL; /* error */ + if (loader != Py_None) { + /* a loader was found */ + *p_loader = loader; + return &importhookdescr; + } + Py_DECREF(loader); + continue; + } + } + /* no hook was found, use builtin import */ - if (len > 0 && buf[len-1] != SEP + if (len > 0 && buf[len-1] != SEP #ifdef ALTSEP - && buf[len-1] != ALTSEP + && buf[len-1] != ALTSEP #endif - ) - buf[len++] = SEP; - strcpy(buf+len, name); - len += namelen; + ) + buf[len++] = SEP; + strcpy(buf+len, name); + len += namelen; - /* Check for package import (buf holds a directory name, - and there's an __init__ module in that directory */ + /* Check for package import (buf holds a directory name, + and there's an __init__ module in that directory */ #ifdef HAVE_STAT - if (stat(buf, &statbuf) == 0 && /* it exists */ - S_ISDIR(statbuf.st_mode) && /* it's a directory */ - case_ok(buf, len, namelen, name)) { /* case matches */ - if (find_init_module(buf)) { /* and has __init__.py */ - return &fd_package; - } - else { - char warnstr[MAXPATHLEN+80]; - sprintf(warnstr, "Not importing directory " - "'%.*s': missing __init__.py", - MAXPATHLEN, buf); - if (PyErr_WarnEx(PyExc_ImportWarning, - warnstr, 1)) { - return NULL; - } - } - } + if (stat(buf, &statbuf) == 0 && /* it exists */ + S_ISDIR(statbuf.st_mode) && /* it's a directory */ + case_ok(buf, len, namelen, name)) { /* case matches */ + if (find_init_module(buf)) { /* and has __init__.py */ + return &fd_package; + } + else { + char warnstr[MAXPATHLEN+80]; + sprintf(warnstr, "Not importing directory " + "'%.*s': missing __init__.py", + MAXPATHLEN, buf); + if (PyErr_WarnEx(PyExc_ImportWarning, + warnstr, 1)) { + return NULL; + } + } + } #endif #if defined(PYOS_OS2) - /* take a snapshot of the module spec for restoration - * after the 8 character DLL hackery - */ - saved_buf = strdup(buf); - saved_len = len; - saved_namelen = namelen; + /* take a snapshot of the module spec for restoration + * after the 8 character DLL hackery + */ + saved_buf = strdup(buf); + saved_len = len; + saved_namelen = namelen; #endif /* PYOS_OS2 */ - for (fdp = _PyImport_Filetab; fdp->suffix != NULL; fdp++) { + for (fdp = _PyImport_Filetab; fdp->suffix != NULL; fdp++) { #if defined(PYOS_OS2) && defined(HAVE_DYNAMIC_LOADING) - /* OS/2 limits DLLs to 8 character names (w/o - extension) - * so if the name is longer than that and its a - * dynamically loaded module we're going to try, - * truncate the name before trying - */ - if (strlen(subname) > 8) { - /* is this an attempt to load a C extension? */ - const struct filedescr *scan; - scan = _PyImport_DynLoadFiletab; - while (scan->suffix != NULL) { - if (!strcmp(scan->suffix, fdp->suffix)) - break; - else - scan++; - } - if (scan->suffix != NULL) { - /* yes, so truncate the name */ - namelen = 8; - len -= strlen(subname) - namelen; - buf[len] = '\0'; - } - } + /* OS/2 limits DLLs to 8 character names (w/o + extension) + * so if the name is longer than that and its a + * dynamically loaded module we're going to try, + * truncate the name before trying + */ + if (strlen(subname) > 8) { + /* is this an attempt to load a C extension? */ + const struct filedescr *scan; + scan = _PyImport_DynLoadFiletab; + while (scan->suffix != NULL) { + if (!strcmp(scan->suffix, fdp->suffix)) + break; + else + scan++; + } + if (scan->suffix != NULL) { + /* yes, so truncate the name */ + namelen = 8; + len -= strlen(subname) - namelen; + buf[len] = '\0'; + } + } #endif /* PYOS_OS2 */ - strcpy(buf+len, fdp->suffix); - if (Py_VerboseFlag > 1) - PySys_WriteStderr("# trying %s\n", buf); - filemode = fdp->mode; - if (filemode[0] == 'U') - filemode = "r" PY_STDIOTEXTMODE; - fp = fopen(buf, filemode); - if (fp != NULL) { - if (case_ok(buf, len, namelen, name)) - break; - else { /* continue search */ - fclose(fp); - fp = NULL; - } - } + strcpy(buf+len, fdp->suffix); + if (Py_VerboseFlag > 1) + PySys_WriteStderr("# trying %s\n", buf); + filemode = fdp->mode; + if (filemode[0] == 'U') + filemode = "r" PY_STDIOTEXTMODE; + fp = fopen(buf, filemode); + if (fp != NULL) { + if (case_ok(buf, len, namelen, name)) + break; + else { /* continue search */ + fclose(fp); + fp = NULL; + } + } #if defined(PYOS_OS2) - /* restore the saved snapshot */ - strcpy(buf, saved_buf); - len = saved_len; - namelen = saved_namelen; + /* restore the saved snapshot */ + strcpy(buf, saved_buf); + len = saved_len; + namelen = saved_namelen; #endif - } + } #if defined(PYOS_OS2) - /* don't need/want the module name snapshot anymore */ - if (saved_buf) - { - free(saved_buf); - saved_buf = NULL; - } -#endif - if (fp != NULL) - break; - } - if (fp == NULL) { - PyErr_Format(PyExc_ImportError, - "No module named %.200s", name); - return NULL; - } - *p_fp = fp; - return fdp; + /* don't need/want the module name snapshot anymore */ + if (saved_buf) + { + free(saved_buf); + saved_buf = NULL; + } +#endif + if (fp != NULL) + break; + } + if (fp == NULL) { + PyErr_Format(PyExc_ImportError, + "No module named %.200s", name); + return NULL; + } + *p_fp = fp; + return fdp; } /* Helpers for main.c @@ -1553,15 +1553,15 @@ */ struct filedescr * _PyImport_FindModule(const char *name, PyObject *path, char *buf, - size_t buflen, FILE **p_fp, PyObject **p_loader) + size_t buflen, FILE **p_fp, PyObject **p_loader) { - return find_module((char *) name, (char *) name, path, - buf, buflen, p_fp, p_loader); + return find_module((char *) name, (char *) name, path, + buf, buflen, p_fp, p_loader); } PyAPI_FUNC(int) _PyImport_IsScript(struct filedescr * fd) { - return fd->type == PY_SOURCE || fd->type == PY_COMPILED; + return fd->type == PY_SOURCE || fd->type == PY_COMPILED; } /* case_ok(char* buf, Py_ssize_t len, Py_ssize_t namelen, char* name) @@ -1617,103 +1617,103 @@ /* MS_WINDOWS */ #if defined(MS_WINDOWS) - WIN32_FIND_DATA data; - HANDLE h; + WIN32_FIND_DATA data; + HANDLE h; - if (Py_GETENV("PYTHONCASEOK") != NULL) - return 1; + if (Py_GETENV("PYTHONCASEOK") != NULL) + return 1; - h = FindFirstFile(buf, &data); - if (h == INVALID_HANDLE_VALUE) { - PyErr_Format(PyExc_NameError, - "Can't find file for module %.100s\n(filename %.300s)", - name, buf); - return 0; - } - FindClose(h); - return strncmp(data.cFileName, name, namelen) == 0; + h = FindFirstFile(buf, &data); + if (h == INVALID_HANDLE_VALUE) { + PyErr_Format(PyExc_NameError, + "Can't find file for module %.100s\n(filename %.300s)", + name, buf); + return 0; + } + FindClose(h); + return strncmp(data.cFileName, name, namelen) == 0; /* DJGPP */ #elif defined(DJGPP) - struct ffblk ffblk; - int done; + struct ffblk ffblk; + int done; - if (Py_GETENV("PYTHONCASEOK") != NULL) - return 1; + if (Py_GETENV("PYTHONCASEOK") != NULL) + return 1; - done = findfirst(buf, &ffblk, FA_ARCH|FA_RDONLY|FA_HIDDEN|FA_DIREC); - if (done) { - PyErr_Format(PyExc_NameError, - "Can't find file for module %.100s\n(filename %.300s)", - name, buf); - return 0; - } - return strncmp(ffblk.ff_name, name, namelen) == 0; + done = findfirst(buf, &ffblk, FA_ARCH|FA_RDONLY|FA_HIDDEN|FA_DIREC); + if (done) { + PyErr_Format(PyExc_NameError, + "Can't find file for module %.100s\n(filename %.300s)", + name, buf); + return 0; + } + return strncmp(ffblk.ff_name, name, namelen) == 0; /* new-fangled macintosh (macosx) or Cygwin */ #elif (defined(__MACH__) && defined(__APPLE__) || defined(__CYGWIN__)) && defined(HAVE_DIRENT_H) - DIR *dirp; - struct dirent *dp; - char dirname[MAXPATHLEN + 1]; - const int dirlen = len - namelen - 1; /* don't want trailing SEP */ - - if (Py_GETENV("PYTHONCASEOK") != NULL) - return 1; - - /* Copy the dir component into dirname; substitute "." if empty */ - if (dirlen <= 0) { - dirname[0] = '.'; - dirname[1] = '\0'; - } - else { - assert(dirlen <= MAXPATHLEN); - memcpy(dirname, buf, dirlen); - dirname[dirlen] = '\0'; - } - /* Open the directory and search the entries for an exact match. */ - dirp = opendir(dirname); - if (dirp) { - char *nameWithExt = buf + len - namelen; - while ((dp = readdir(dirp)) != NULL) { - const int thislen = + DIR *dirp; + struct dirent *dp; + char dirname[MAXPATHLEN + 1]; + const int dirlen = len - namelen - 1; /* don't want trailing SEP */ + + if (Py_GETENV("PYTHONCASEOK") != NULL) + return 1; + + /* Copy the dir component into dirname; substitute "." if empty */ + if (dirlen <= 0) { + dirname[0] = '.'; + dirname[1] = '\0'; + } + else { + assert(dirlen <= MAXPATHLEN); + memcpy(dirname, buf, dirlen); + dirname[dirlen] = '\0'; + } + /* Open the directory and search the entries for an exact match. */ + dirp = opendir(dirname); + if (dirp) { + char *nameWithExt = buf + len - namelen; + while ((dp = readdir(dirp)) != NULL) { + const int thislen = #ifdef _DIRENT_HAVE_D_NAMELEN - dp->d_namlen; + dp->d_namlen; #else - strlen(dp->d_name); + strlen(dp->d_name); #endif - if (thislen >= namelen && - strcmp(dp->d_name, nameWithExt) == 0) { - (void)closedir(dirp); - return 1; /* Found */ - } - } - (void)closedir(dirp); - } - return 0 ; /* Not found */ + if (thislen >= namelen && + strcmp(dp->d_name, nameWithExt) == 0) { + (void)closedir(dirp); + return 1; /* Found */ + } + } + (void)closedir(dirp); + } + return 0 ; /* Not found */ /* OS/2 */ #elif defined(PYOS_OS2) - HDIR hdir = 1; - ULONG srchcnt = 1; - FILEFINDBUF3 ffbuf; - APIRET rc; - - if (Py_GETENV("PYTHONCASEOK") != NULL) - return 1; - - rc = DosFindFirst(buf, - &hdir, - FILE_READONLY | FILE_HIDDEN | FILE_SYSTEM | FILE_DIRECTORY, - &ffbuf, sizeof(ffbuf), - &srchcnt, - FIL_STANDARD); - if (rc != NO_ERROR) - return 0; - return strncmp(ffbuf.achName, name, namelen) == 0; + HDIR hdir = 1; + ULONG srchcnt = 1; + FILEFINDBUF3 ffbuf; + APIRET rc; + + if (Py_GETENV("PYTHONCASEOK") != NULL) + return 1; + + rc = DosFindFirst(buf, + &hdir, + FILE_READONLY | FILE_HIDDEN | FILE_SYSTEM | FILE_DIRECTORY, + &ffbuf, sizeof(ffbuf), + &srchcnt, + FIL_STANDARD); + if (rc != NO_ERROR) + return 0; + return strncmp(ffbuf.achName, name, namelen) == 0; /* assuming it's a case-sensitive filesystem, so there's nothing to do! */ #else - return 1; + return 1; #endif } @@ -1724,46 +1724,46 @@ static int find_init_module(char *buf) { - const size_t save_len = strlen(buf); - size_t i = save_len; - char *pname; /* pointer to start of __init__ */ - struct stat statbuf; - -/* For calling case_ok(buf, len, namelen, name): - * /a/b/c/d/e/f/g/h/i/j/k/some_long_module_name.py\0 - * ^ ^ ^ ^ - * |--------------------- buf ---------------------| - * |------------------- len ------------------| - * |------ name -------| - * |----- namelen -----| + const size_t save_len = strlen(buf); + size_t i = save_len; + char *pname; /* pointer to start of __init__ */ + struct stat statbuf; + +/* For calling case_ok(buf, len, namelen, name): + * /a/b/c/d/e/f/g/h/i/j/k/some_long_module_name.py\0 + * ^ ^ ^ ^ + * |--------------------- buf ---------------------| + * |------------------- len ------------------| + * |------ name -------| + * |----- namelen -----| */ - if (save_len + 13 >= MAXPATHLEN) - return 0; - buf[i++] = SEP; - pname = buf + i; - strcpy(pname, "__init__.py"); - if (stat(buf, &statbuf) == 0) { - if (case_ok(buf, - save_len + 9, /* len("/__init__") */ - 8, /* len("__init__") */ - pname)) { - buf[save_len] = '\0'; - return 1; - } - } - i += strlen(pname); - strcpy(buf+i, Py_OptimizeFlag ? "o" : "c"); - if (stat(buf, &statbuf) == 0) { - if (case_ok(buf, - save_len + 9, /* len("/__init__") */ - 8, /* len("__init__") */ - pname)) { - buf[save_len] = '\0'; - return 1; - } - } - buf[save_len] = '\0'; - return 0; + if (save_len + 13 >= MAXPATHLEN) + return 0; + buf[i++] = SEP; + pname = buf + i; + strcpy(pname, "__init__.py"); + if (stat(buf, &statbuf) == 0) { + if (case_ok(buf, + save_len + 9, /* len("/__init__") */ + 8, /* len("__init__") */ + pname)) { + buf[save_len] = '\0'; + return 1; + } + } + i += strlen(pname); + strcpy(buf+i, Py_OptimizeFlag ? "o" : "c"); + if (stat(buf, &statbuf) == 0) { + if (case_ok(buf, + save_len + 9, /* len("/__init__") */ + 8, /* len("__init__") */ + pname)) { + buf[save_len] = '\0'; + return 1; + } + } + buf[save_len] = '\0'; + return 0; } #endif /* HAVE_STAT */ @@ -1777,93 +1777,93 @@ static PyObject * load_module(char *name, FILE *fp, char *pathname, int type, PyObject *loader) { - PyObject *modules; - PyObject *m; - int err; - - /* First check that there's an open file (if we need one) */ - switch (type) { - case PY_SOURCE: - case PY_COMPILED: - if (fp == NULL) { - PyErr_Format(PyExc_ValueError, - "file object required for import (type code %d)", - type); - return NULL; - } - } - - switch (type) { - - case PY_SOURCE: - m = load_source_module(name, pathname, fp); - break; - - case PY_COMPILED: - m = load_compiled_module(name, pathname, fp); - break; + PyObject *modules; + PyObject *m; + int err; + + /* First check that there's an open file (if we need one) */ + switch (type) { + case PY_SOURCE: + case PY_COMPILED: + if (fp == NULL) { + PyErr_Format(PyExc_ValueError, + "file object required for import (type code %d)", + type); + return NULL; + } + } + + switch (type) { + + case PY_SOURCE: + m = load_source_module(name, pathname, fp); + break; + + case PY_COMPILED: + m = load_compiled_module(name, pathname, fp); + break; #ifdef HAVE_DYNAMIC_LOADING - case C_EXTENSION: - m = _PyImport_LoadDynamicModule(name, pathname, fp); - break; -#endif - - case PKG_DIRECTORY: - m = load_package(name, pathname); - break; - - case C_BUILTIN: - case PY_FROZEN: - if (pathname != NULL && pathname[0] != '\0') - name = pathname; - if (type == C_BUILTIN) - err = init_builtin(name); - else - err = PyImport_ImportFrozenModule(name); - if (err < 0) - return NULL; - if (err == 0) { - PyErr_Format(PyExc_ImportError, - "Purported %s module %.200s not found", - type == C_BUILTIN ? - "builtin" : "frozen", - name); - return NULL; - } - modules = PyImport_GetModuleDict(); - m = PyDict_GetItemString(modules, name); - if (m == NULL) { - PyErr_Format( - PyExc_ImportError, - "%s module %.200s not properly initialized", - type == C_BUILTIN ? - "builtin" : "frozen", - name); - return NULL; - } - Py_INCREF(m); - break; - - case IMP_HOOK: { - if (loader == NULL) { - PyErr_SetString(PyExc_ImportError, - "import hook without loader"); - return NULL; - } - m = PyObject_CallMethod(loader, "load_module", "s", name); - break; - } - - default: - PyErr_Format(PyExc_ImportError, - "Don't know how to import %.200s (type code %d)", - name, type); - m = NULL; + case C_EXTENSION: + m = _PyImport_LoadDynamicModule(name, pathname, fp); + break; +#endif + + case PKG_DIRECTORY: + m = load_package(name, pathname); + break; + + case C_BUILTIN: + case PY_FROZEN: + if (pathname != NULL && pathname[0] != '\0') + name = pathname; + if (type == C_BUILTIN) + err = init_builtin(name); + else + err = PyImport_ImportFrozenModule(name); + if (err < 0) + return NULL; + if (err == 0) { + PyErr_Format(PyExc_ImportError, + "Purported %s module %.200s not found", + type == C_BUILTIN ? + "builtin" : "frozen", + name); + return NULL; + } + modules = PyImport_GetModuleDict(); + m = PyDict_GetItemString(modules, name); + if (m == NULL) { + PyErr_Format( + PyExc_ImportError, + "%s module %.200s not properly initialized", + type == C_BUILTIN ? + "builtin" : "frozen", + name); + return NULL; + } + Py_INCREF(m); + break; + + case IMP_HOOK: { + if (loader == NULL) { + PyErr_SetString(PyExc_ImportError, + "import hook without loader"); + return NULL; + } + m = PyObject_CallMethod(loader, "load_module", "s", name); + break; + } + + default: + PyErr_Format(PyExc_ImportError, + "Don't know how to import %.200s (type code %d)", + name, type); + m = NULL; - } + } - return m; + return m; } @@ -1874,34 +1874,34 @@ static int init_builtin(char *name) { - struct _inittab *p; + struct _inittab *p; - if (_PyImport_FindExtension(name, name) != NULL) - return 1; + if (_PyImport_FindExtension(name, name) != NULL) + return 1; - for (p = PyImport_Inittab; p->name != NULL; p++) { - PyObject *mod; - if (strcmp(name, p->name) == 0) { - if (p->initfunc == NULL) { - PyErr_Format(PyExc_ImportError, - "Cannot re-init internal module %.200s", - name); - return -1; - } - if (Py_VerboseFlag) - PySys_WriteStderr("import %s # builtin\n", name); - mod = (*p->initfunc)(); - if (mod == 0) - return -1; - if (_PyImport_FixupExtension(mod, name, name) < 0) - return -1; - /* FixupExtension has put the module into sys.modules, - so we can release our own reference. */ - Py_DECREF(mod); - return 1; - } - } - return 0; + for (p = PyImport_Inittab; p->name != NULL; p++) { + PyObject *mod; + if (strcmp(name, p->name) == 0) { + if (p->initfunc == NULL) { + PyErr_Format(PyExc_ImportError, + "Cannot re-init internal module %.200s", + name); + return -1; + } + if (Py_VerboseFlag) + PySys_WriteStderr("import %s # builtin\n", name); + mod = (*p->initfunc)(); + if (mod == 0) + return -1; + if (_PyImport_FixupExtension(mod, name, name) < 0) + return -1; + /* FixupExtension has put the module into sys.modules, + so we can release our own reference. */ + Py_DECREF(mod); + return 1; + } + } + return 0; } @@ -1910,63 +1910,63 @@ static struct _frozen * find_frozen(char *name) { - struct _frozen *p; + struct _frozen *p; - if (!name) - return NULL; + if (!name) + return NULL; - for (p = PyImport_FrozenModules; ; p++) { - if (p->name == NULL) - return NULL; - if (strcmp(p->name, name) == 0) - break; - } - return p; + for (p = PyImport_FrozenModules; ; p++) { + if (p->name == NULL) + return NULL; + if (strcmp(p->name, name) == 0) + break; + } + return p; } static PyObject * get_frozen_object(char *name) { - struct _frozen *p = find_frozen(name); - int size; + struct _frozen *p = find_frozen(name); + int size; - if (p == NULL) { - PyErr_Format(PyExc_ImportError, - "No such frozen object named %.200s", - name); - return NULL; - } - if (p->code == NULL) { - PyErr_Format(PyExc_ImportError, - "Excluded frozen object named %.200s", - name); - return NULL; - } - size = p->size; - if (size < 0) - size = -size; - return PyMarshal_ReadObjectFromString((char *)p->code, size); + if (p == NULL) { + PyErr_Format(PyExc_ImportError, + "No such frozen object named %.200s", + name); + return NULL; + } + if (p->code == NULL) { + PyErr_Format(PyExc_ImportError, + "Excluded frozen object named %.200s", + name); + return NULL; + } + size = p->size; + if (size < 0) + size = -size; + return PyMarshal_ReadObjectFromString((char *)p->code, size); } static PyObject * is_frozen_package(char *name) { - struct _frozen *p = find_frozen(name); - int size; + struct _frozen *p = find_frozen(name); + int size; - if (p == NULL) { - PyErr_Format(PyExc_ImportError, - "No such frozen object named %.200s", - name); - return NULL; - } - - size = p->size; - - if (size < 0) - Py_RETURN_TRUE; - else - Py_RETURN_FALSE; + if (p == NULL) { + PyErr_Format(PyExc_ImportError, + "No such frozen object named %.200s", + name); + return NULL; + } + + size = p->size; + + if (size < 0) + Py_RETURN_TRUE; + else + Py_RETURN_FALSE; } @@ -1978,67 +1978,67 @@ int PyImport_ImportFrozenModule(char *name) { - struct _frozen *p = find_frozen(name); - PyObject *co; - PyObject *m; - int ispackage; - int size; - - if (p == NULL) - return 0; - if (p->code == NULL) { - PyErr_Format(PyExc_ImportError, - "Excluded frozen object named %.200s", - name); - return -1; - } - size = p->size; - ispackage = (size < 0); - if (ispackage) - size = -size; - if (Py_VerboseFlag) - PySys_WriteStderr("import %s # frozen%s\n", - name, ispackage ? " package" : ""); - co = PyMarshal_ReadObjectFromString((char *)p->code, size); - if (co == NULL) - return -1; - if (!PyCode_Check(co)) { - PyErr_Format(PyExc_TypeError, - "frozen object %.200s is not a code object", - name); - goto err_return; - } - if (ispackage) { - /* Set __path__ to the package name */ - PyObject *d, *s, *l; - int err; - m = PyImport_AddModule(name); - if (m == NULL) - goto err_return; - d = PyModule_GetDict(m); - s = PyUnicode_InternFromString(name); - if (s == NULL) - goto err_return; - l = PyList_New(1); - if (l == NULL) { - Py_DECREF(s); - goto err_return; - } - PyList_SET_ITEM(l, 0, s); - err = PyDict_SetItemString(d, "__path__", l); - Py_DECREF(l); - if (err != 0) - goto err_return; - } - m = PyImport_ExecCodeModuleEx(name, co, ""); - if (m == NULL) - goto err_return; - Py_DECREF(co); - Py_DECREF(m); - return 1; + struct _frozen *p = find_frozen(name); + PyObject *co; + PyObject *m; + int ispackage; + int size; + + if (p == NULL) + return 0; + if (p->code == NULL) { + PyErr_Format(PyExc_ImportError, + "Excluded frozen object named %.200s", + name); + return -1; + } + size = p->size; + ispackage = (size < 0); + if (ispackage) + size = -size; + if (Py_VerboseFlag) + PySys_WriteStderr("import %s # frozen%s\n", + name, ispackage ? " package" : ""); + co = PyMarshal_ReadObjectFromString((char *)p->code, size); + if (co == NULL) + return -1; + if (!PyCode_Check(co)) { + PyErr_Format(PyExc_TypeError, + "frozen object %.200s is not a code object", + name); + goto err_return; + } + if (ispackage) { + /* Set __path__ to the package name */ + PyObject *d, *s, *l; + int err; + m = PyImport_AddModule(name); + if (m == NULL) + goto err_return; + d = PyModule_GetDict(m); + s = PyUnicode_InternFromString(name); + if (s == NULL) + goto err_return; + l = PyList_New(1); + if (l == NULL) { + Py_DECREF(s); + goto err_return; + } + PyList_SET_ITEM(l, 0, s); + err = PyDict_SetItemString(d, "__path__", l); + Py_DECREF(l); + if (err != 0) + goto err_return; + } + m = PyImport_ExecCodeModuleEx(name, co, ""); + if (m == NULL) + goto err_return; + Py_DECREF(co); + Py_DECREF(m); + return 1; err_return: - Py_DECREF(co); - return -1; + Py_DECREF(co); + return -1; } @@ -2048,15 +2048,15 @@ PyObject * PyImport_ImportModule(const char *name) { - PyObject *pname; - PyObject *result; + PyObject *pname; + PyObject *result; - pname = PyUnicode_FromString(name); - if (pname == NULL) - return NULL; - result = PyImport_Import(pname); - Py_DECREF(pname); - return result; + pname = PyUnicode_FromString(name); + if (pname == NULL) + return NULL; + result = PyImport_Import(pname); + Py_DECREF(pname); + return result; } /* Import a module without blocking @@ -2071,137 +2071,137 @@ PyObject * PyImport_ImportModuleNoBlock(const char *name) { - PyObject *result; - PyObject *modules; - long me; - - /* Try to get the module from sys.modules[name] */ - modules = PyImport_GetModuleDict(); - if (modules == NULL) - return NULL; - - result = PyDict_GetItemString(modules, name); - if (result != NULL) { - Py_INCREF(result); - return result; - } - else { - PyErr_Clear(); - } + PyObject *result; + PyObject *modules; + long me; + + /* Try to get the module from sys.modules[name] */ + modules = PyImport_GetModuleDict(); + if (modules == NULL) + return NULL; + + result = PyDict_GetItemString(modules, name); + if (result != NULL) { + Py_INCREF(result); + return result; + } + else { + PyErr_Clear(); + } #ifdef WITH_THREAD - /* check the import lock - * me might be -1 but I ignore the error here, the lock function - * takes care of the problem */ - me = PyThread_get_thread_ident(); - if (import_lock_thread == -1 || import_lock_thread == me) { - /* no thread or me is holding the lock */ - return PyImport_ImportModule(name); - } - else { - PyErr_Format(PyExc_ImportError, - "Failed to import %.200s because the import lock" - "is held by another thread.", - name); - return NULL; - } + /* check the import lock + * me might be -1 but I ignore the error here, the lock function + * takes care of the problem */ + me = PyThread_get_thread_ident(); + if (import_lock_thread == -1 || import_lock_thread == me) { + /* no thread or me is holding the lock */ + return PyImport_ImportModule(name); + } + else { + PyErr_Format(PyExc_ImportError, + "Failed to import %.200s because the import lock" + "is held by another thread.", + name); + return NULL; + } #else - return PyImport_ImportModule(name); + return PyImport_ImportModule(name); #endif } /* Forward declarations for helper routines */ static PyObject *get_parent(PyObject *globals, char *buf, - Py_ssize_t *p_buflen, int level); + Py_ssize_t *p_buflen, int level); static PyObject *load_next(PyObject *mod, PyObject *altmod, - char **p_name, char *buf, Py_ssize_t *p_buflen); + char **p_name, char *buf, Py_ssize_t *p_buflen); static int mark_miss(char *name); static int ensure_fromlist(PyObject *mod, PyObject *fromlist, - char *buf, Py_ssize_t buflen, int recursive); + char *buf, Py_ssize_t buflen, int recursive); static PyObject * import_submodule(PyObject *mod, char *name, char *fullname); /* The Magnum Opus of dotted-name import :-) */ static PyObject * import_module_level(char *name, PyObject *globals, PyObject *locals, - PyObject *fromlist, int level) + PyObject *fromlist, int level) { - char buf[MAXPATHLEN+1]; - Py_ssize_t buflen = 0; - PyObject *parent, *head, *next, *tail; + char buf[MAXPATHLEN+1]; + Py_ssize_t buflen = 0; + PyObject *parent, *head, *next, *tail; - if (strchr(name, '/') != NULL + if (strchr(name, '/') != NULL #ifdef MS_WINDOWS - || strchr(name, '\\') != NULL + || strchr(name, '\\') != NULL #endif - ) { - PyErr_SetString(PyExc_ImportError, - "Import by filename is not supported."); - return NULL; - } - - parent = get_parent(globals, buf, &buflen, level); - if (parent == NULL) - return NULL; - - head = load_next(parent, Py_None, &name, buf, &buflen); - if (head == NULL) - return NULL; - - tail = head; - Py_INCREF(tail); - while (name) { - next = load_next(tail, tail, &name, buf, &buflen); - Py_DECREF(tail); - if (next == NULL) { - Py_DECREF(head); - return NULL; - } - tail = next; - } - if (tail == Py_None) { - /* If tail is Py_None, both get_parent and load_next found - an empty module name: someone called __import__("") or - doctored faulty bytecode */ - Py_DECREF(tail); - Py_DECREF(head); - PyErr_SetString(PyExc_ValueError, - "Empty module name"); - return NULL; - } - - if (fromlist != NULL) { - if (fromlist == Py_None || !PyObject_IsTrue(fromlist)) - fromlist = NULL; - } - - if (fromlist == NULL) { - Py_DECREF(tail); - return head; - } - - Py_DECREF(head); - if (!ensure_fromlist(tail, fromlist, buf, buflen, 0)) { - Py_DECREF(tail); - return NULL; - } + ) { + PyErr_SetString(PyExc_ImportError, + "Import by filename is not supported."); + return NULL; + } + + parent = get_parent(globals, buf, &buflen, level); + if (parent == NULL) + return NULL; + + head = load_next(parent, Py_None, &name, buf, &buflen); + if (head == NULL) + return NULL; + + tail = head; + Py_INCREF(tail); + while (name) { + next = load_next(tail, tail, &name, buf, &buflen); + Py_DECREF(tail); + if (next == NULL) { + Py_DECREF(head); + return NULL; + } + tail = next; + } + if (tail == Py_None) { + /* If tail is Py_None, both get_parent and load_next found + an empty module name: someone called __import__("") or + doctored faulty bytecode */ + Py_DECREF(tail); + Py_DECREF(head); + PyErr_SetString(PyExc_ValueError, + "Empty module name"); + return NULL; + } + + if (fromlist != NULL) { + if (fromlist == Py_None || !PyObject_IsTrue(fromlist)) + fromlist = NULL; + } + + if (fromlist == NULL) { + Py_DECREF(tail); + return head; + } + + Py_DECREF(head); + if (!ensure_fromlist(tail, fromlist, buf, buflen, 0)) { + Py_DECREF(tail); + return NULL; + } - return tail; + return tail; } PyObject * PyImport_ImportModuleLevel(char *name, PyObject *globals, PyObject *locals, - PyObject *fromlist, int level) + PyObject *fromlist, int level) { - PyObject *result; - _PyImport_AcquireLock(); - result = import_module_level(name, globals, locals, fromlist, level); - if (_PyImport_ReleaseLock() < 0) { - Py_XDECREF(result); - PyErr_SetString(PyExc_RuntimeError, - "not holding the import lock"); - return NULL; - } - return result; + PyObject *result; + _PyImport_AcquireLock(); + result = import_module_level(name, globals, locals, fromlist, level); + if (_PyImport_ReleaseLock() < 0) { + Py_XDECREF(result); + PyErr_SetString(PyExc_RuntimeError, + "not holding the import lock"); + return NULL; + } + return result; } /* Return the package that an import is being performed in. If globals comes @@ -2218,420 +2218,420 @@ static PyObject * get_parent(PyObject *globals, char *buf, Py_ssize_t *p_buflen, int level) { - static PyObject *namestr = NULL; - static PyObject *pathstr = NULL; - static PyObject *pkgstr = NULL; - PyObject *pkgname, *modname, *modpath, *modules, *parent; - int orig_level = level; - - if (globals == NULL || !PyDict_Check(globals) || !level) - return Py_None; - - if (namestr == NULL) { - namestr = PyUnicode_InternFromString("__name__"); - if (namestr == NULL) - return NULL; - } - if (pathstr == NULL) { - pathstr = PyUnicode_InternFromString("__path__"); - if (pathstr == NULL) - return NULL; - } - if (pkgstr == NULL) { - pkgstr = PyUnicode_InternFromString("__package__"); - if (pkgstr == NULL) - return NULL; - } - - *buf = '\0'; - *p_buflen = 0; - pkgname = PyDict_GetItem(globals, pkgstr); - - if ((pkgname != NULL) && (pkgname != Py_None)) { - /* __package__ is set, so use it */ - char *pkgname_str; - Py_ssize_t len; - - if (!PyUnicode_Check(pkgname)) { - PyErr_SetString(PyExc_ValueError, - "__package__ set to non-string"); - return NULL; - } - pkgname_str = _PyUnicode_AsStringAndSize(pkgname, &len); - if (len == 0) { - if (level > 0) { - PyErr_SetString(PyExc_ValueError, - "Attempted relative import in non-package"); - return NULL; - } - return Py_None; - } - if (len > MAXPATHLEN) { - PyErr_SetString(PyExc_ValueError, - "Package name too long"); - return NULL; - } - strcpy(buf, pkgname_str); - } else { - /* __package__ not set, so figure it out and set it */ - modname = PyDict_GetItem(globals, namestr); - if (modname == NULL || !PyUnicode_Check(modname)) - return Py_None; - - modpath = PyDict_GetItem(globals, pathstr); - if (modpath != NULL) { - /* __path__ is set, so modname is already the package name */ - char *modname_str; - Py_ssize_t len; - int error; - - modname_str = _PyUnicode_AsStringAndSize(modname, &len); - if (len > MAXPATHLEN) { - PyErr_SetString(PyExc_ValueError, - "Module name too long"); - return NULL; - } - strcpy(buf, modname_str); - error = PyDict_SetItem(globals, pkgstr, modname); - if (error) { - PyErr_SetString(PyExc_ValueError, - "Could not set __package__"); - return NULL; - } - } else { - /* Normal module, so work out the package name if any */ - char *start = _PyUnicode_AsString(modname); - char *lastdot = strrchr(start, '.'); - size_t len; - int error; - if (lastdot == NULL && level > 0) { - PyErr_SetString(PyExc_ValueError, - "Attempted relative import in non-package"); - return NULL; - } - if (lastdot == NULL) { - error = PyDict_SetItem(globals, pkgstr, Py_None); - if (error) { - PyErr_SetString(PyExc_ValueError, - "Could not set __package__"); - return NULL; - } - return Py_None; - } - len = lastdot - start; - if (len >= MAXPATHLEN) { - PyErr_SetString(PyExc_ValueError, - "Module name too long"); - return NULL; - } - strncpy(buf, start, len); - buf[len] = '\0'; - pkgname = PyUnicode_FromString(buf); - if (pkgname == NULL) { - return NULL; - } - error = PyDict_SetItem(globals, pkgstr, pkgname); - Py_DECREF(pkgname); - if (error) { - PyErr_SetString(PyExc_ValueError, - "Could not set __package__"); - return NULL; - } - } - } - while (--level > 0) { - char *dot = strrchr(buf, '.'); - if (dot == NULL) { - PyErr_SetString(PyExc_ValueError, - "Attempted relative import beyond " - "toplevel package"); - return NULL; - } - *dot = '\0'; - } - *p_buflen = strlen(buf); - - modules = PyImport_GetModuleDict(); - parent = PyDict_GetItemString(modules, buf); - if (parent == NULL) { - if (orig_level < 1) { - PyObject *err_msg = PyBytes_FromFormat( - "Parent module '%.200s' not found " - "while handling absolute import", buf); - if (err_msg == NULL) { - return NULL; - } - if (!PyErr_WarnEx(PyExc_RuntimeWarning, - PyBytes_AsString(err_msg), 1)) { - *buf = '\0'; - *p_buflen = 0; - parent = Py_None; - } - Py_DECREF(err_msg); - } else { - PyErr_Format(PyExc_SystemError, - "Parent module '%.200s' not loaded, " - "cannot perform relative import", buf); - } - } - return parent; - /* We expect, but can't guarantee, if parent != None, that: - - parent.__name__ == buf - - parent.__dict__ is globals - If this is violated... Who cares? */ + static PyObject *namestr = NULL; + static PyObject *pathstr = NULL; + static PyObject *pkgstr = NULL; + PyObject *pkgname, *modname, *modpath, *modules, *parent; + int orig_level = level; + + if (globals == NULL || !PyDict_Check(globals) || !level) + return Py_None; + + if (namestr == NULL) { + namestr = PyUnicode_InternFromString("__name__"); + if (namestr == NULL) + return NULL; + } + if (pathstr == NULL) { + pathstr = PyUnicode_InternFromString("__path__"); + if (pathstr == NULL) + return NULL; + } + if (pkgstr == NULL) { + pkgstr = PyUnicode_InternFromString("__package__"); + if (pkgstr == NULL) + return NULL; + } + + *buf = '\0'; + *p_buflen = 0; + pkgname = PyDict_GetItem(globals, pkgstr); + + if ((pkgname != NULL) && (pkgname != Py_None)) { + /* __package__ is set, so use it */ + char *pkgname_str; + Py_ssize_t len; + + if (!PyUnicode_Check(pkgname)) { + PyErr_SetString(PyExc_ValueError, + "__package__ set to non-string"); + return NULL; + } + pkgname_str = _PyUnicode_AsStringAndSize(pkgname, &len); + if (len == 0) { + if (level > 0) { + PyErr_SetString(PyExc_ValueError, + "Attempted relative import in non-package"); + return NULL; + } + return Py_None; + } + if (len > MAXPATHLEN) { + PyErr_SetString(PyExc_ValueError, + "Package name too long"); + return NULL; + } + strcpy(buf, pkgname_str); + } else { + /* __package__ not set, so figure it out and set it */ + modname = PyDict_GetItem(globals, namestr); + if (modname == NULL || !PyUnicode_Check(modname)) + return Py_None; + + modpath = PyDict_GetItem(globals, pathstr); + if (modpath != NULL) { + /* __path__ is set, so modname is already the package name */ + char *modname_str; + Py_ssize_t len; + int error; + + modname_str = _PyUnicode_AsStringAndSize(modname, &len); + if (len > MAXPATHLEN) { + PyErr_SetString(PyExc_ValueError, + "Module name too long"); + return NULL; + } + strcpy(buf, modname_str); + error = PyDict_SetItem(globals, pkgstr, modname); + if (error) { + PyErr_SetString(PyExc_ValueError, + "Could not set __package__"); + return NULL; + } + } else { + /* Normal module, so work out the package name if any */ + char *start = _PyUnicode_AsString(modname); + char *lastdot = strrchr(start, '.'); + size_t len; + int error; + if (lastdot == NULL && level > 0) { + PyErr_SetString(PyExc_ValueError, + "Attempted relative import in non-package"); + return NULL; + } + if (lastdot == NULL) { + error = PyDict_SetItem(globals, pkgstr, Py_None); + if (error) { + PyErr_SetString(PyExc_ValueError, + "Could not set __package__"); + return NULL; + } + return Py_None; + } + len = lastdot - start; + if (len >= MAXPATHLEN) { + PyErr_SetString(PyExc_ValueError, + "Module name too long"); + return NULL; + } + strncpy(buf, start, len); + buf[len] = '\0'; + pkgname = PyUnicode_FromString(buf); + if (pkgname == NULL) { + return NULL; + } + error = PyDict_SetItem(globals, pkgstr, pkgname); + Py_DECREF(pkgname); + if (error) { + PyErr_SetString(PyExc_ValueError, + "Could not set __package__"); + return NULL; + } + } + } + while (--level > 0) { + char *dot = strrchr(buf, '.'); + if (dot == NULL) { + PyErr_SetString(PyExc_ValueError, + "Attempted relative import beyond " + "toplevel package"); + return NULL; + } + *dot = '\0'; + } + *p_buflen = strlen(buf); + + modules = PyImport_GetModuleDict(); + parent = PyDict_GetItemString(modules, buf); + if (parent == NULL) { + if (orig_level < 1) { + PyObject *err_msg = PyBytes_FromFormat( + "Parent module '%.200s' not found " + "while handling absolute import", buf); + if (err_msg == NULL) { + return NULL; + } + if (!PyErr_WarnEx(PyExc_RuntimeWarning, + PyBytes_AsString(err_msg), 1)) { + *buf = '\0'; + *p_buflen = 0; + parent = Py_None; + } + Py_DECREF(err_msg); + } else { + PyErr_Format(PyExc_SystemError, + "Parent module '%.200s' not loaded, " + "cannot perform relative import", buf); + } + } + return parent; + /* We expect, but can't guarantee, if parent != None, that: + - parent.__name__ == buf + - parent.__dict__ is globals + If this is violated... Who cares? */ } /* altmod is either None or same as mod */ static PyObject * load_next(PyObject *mod, PyObject *altmod, char **p_name, char *buf, - Py_ssize_t *p_buflen) + Py_ssize_t *p_buflen) { - char *name = *p_name; - char *dot = strchr(name, '.'); - size_t len; - char *p; - PyObject *result; - - if (strlen(name) == 0) { - /* completely empty module name should only happen in - 'from . import' (or '__import__("")')*/ - Py_INCREF(mod); - *p_name = NULL; - return mod; - } - - if (dot == NULL) { - *p_name = NULL; - len = strlen(name); - } - else { - *p_name = dot+1; - len = dot-name; - } - if (len == 0) { - PyErr_SetString(PyExc_ValueError, - "Empty module name"); - return NULL; - } - - p = buf + *p_buflen; - if (p != buf) - *p++ = '.'; - if (p+len-buf >= MAXPATHLEN) { - PyErr_SetString(PyExc_ValueError, - "Module name too long"); - return NULL; - } - strncpy(p, name, len); - p[len] = '\0'; - *p_buflen = p+len-buf; - - result = import_submodule(mod, p, buf); - if (result == Py_None && altmod != mod) { - Py_DECREF(result); - /* Here, altmod must be None and mod must not be None */ - result = import_submodule(altmod, p, p); - if (result != NULL && result != Py_None) { - if (mark_miss(buf) != 0) { - Py_DECREF(result); - return NULL; - } - strncpy(buf, name, len); - buf[len] = '\0'; - *p_buflen = len; - } - } - if (result == NULL) - return NULL; - - if (result == Py_None) { - Py_DECREF(result); - PyErr_Format(PyExc_ImportError, - "No module named %.200s", name); - return NULL; - } + char *name = *p_name; + char *dot = strchr(name, '.'); + size_t len; + char *p; + PyObject *result; + + if (strlen(name) == 0) { + /* completely empty module name should only happen in + 'from . import' (or '__import__("")')*/ + Py_INCREF(mod); + *p_name = NULL; + return mod; + } + + if (dot == NULL) { + *p_name = NULL; + len = strlen(name); + } + else { + *p_name = dot+1; + len = dot-name; + } + if (len == 0) { + PyErr_SetString(PyExc_ValueError, + "Empty module name"); + return NULL; + } + + p = buf + *p_buflen; + if (p != buf) + *p++ = '.'; + if (p+len-buf >= MAXPATHLEN) { + PyErr_SetString(PyExc_ValueError, + "Module name too long"); + return NULL; + } + strncpy(p, name, len); + p[len] = '\0'; + *p_buflen = p+len-buf; + + result = import_submodule(mod, p, buf); + if (result == Py_None && altmod != mod) { + Py_DECREF(result); + /* Here, altmod must be None and mod must not be None */ + result = import_submodule(altmod, p, p); + if (result != NULL && result != Py_None) { + if (mark_miss(buf) != 0) { + Py_DECREF(result); + return NULL; + } + strncpy(buf, name, len); + buf[len] = '\0'; + *p_buflen = len; + } + } + if (result == NULL) + return NULL; + + if (result == Py_None) { + Py_DECREF(result); + PyErr_Format(PyExc_ImportError, + "No module named %.200s", name); + return NULL; + } - return result; + return result; } static int mark_miss(char *name) { - PyObject *modules = PyImport_GetModuleDict(); - return PyDict_SetItemString(modules, name, Py_None); + PyObject *modules = PyImport_GetModuleDict(); + return PyDict_SetItemString(modules, name, Py_None); } static int ensure_fromlist(PyObject *mod, PyObject *fromlist, char *buf, Py_ssize_t buflen, - int recursive) + int recursive) { - int i; + int i; - if (!PyObject_HasAttrString(mod, "__path__")) - return 1; + if (!PyObject_HasAttrString(mod, "__path__")) + return 1; - for (i = 0; ; i++) { - PyObject *item = PySequence_GetItem(fromlist, i); - int hasit; - if (item == NULL) { - if (PyErr_ExceptionMatches(PyExc_IndexError)) { - PyErr_Clear(); - return 1; - } - return 0; - } - if (!PyUnicode_Check(item)) { - PyErr_SetString(PyExc_TypeError, - "Item in ``from list'' not a string"); - Py_DECREF(item); - return 0; - } - if (PyUnicode_AS_UNICODE(item)[0] == '*') { - PyObject *all; - Py_DECREF(item); - /* See if the package defines __all__ */ - if (recursive) - continue; /* Avoid endless recursion */ - all = PyObject_GetAttrString(mod, "__all__"); - if (all == NULL) - PyErr_Clear(); - else { - int ret = ensure_fromlist(mod, all, buf, buflen, 1); - Py_DECREF(all); - if (!ret) - return 0; - } - continue; - } - hasit = PyObject_HasAttr(mod, item); - if (!hasit) { - PyObject *item8; - char *subname; - PyObject *submod; - char *p; - if (!Py_FileSystemDefaultEncoding) { - item8 = PyUnicode_EncodeASCII(PyUnicode_AsUnicode(item), - PyUnicode_GetSize(item), - NULL); - } else { - item8 = PyUnicode_AsEncodedString(item, - Py_FileSystemDefaultEncoding, NULL); - } - if (!item8) { - PyErr_SetString(PyExc_ValueError, "Cannot encode path item"); - return 0; - } - subname = PyBytes_AS_STRING(item8); - if (buflen + strlen(subname) >= MAXPATHLEN) { - PyErr_SetString(PyExc_ValueError, - "Module name too long"); - Py_DECREF(item); - return 0; - } - p = buf + buflen; - *p++ = '.'; - strcpy(p, subname); - submod = import_submodule(mod, subname, buf); - Py_DECREF(item8); - Py_XDECREF(submod); - if (submod == NULL) { - Py_DECREF(item); - return 0; - } - } - Py_DECREF(item); - } + for (i = 0; ; i++) { + PyObject *item = PySequence_GetItem(fromlist, i); + int hasit; + if (item == NULL) { + if (PyErr_ExceptionMatches(PyExc_IndexError)) { + PyErr_Clear(); + return 1; + } + return 0; + } + if (!PyUnicode_Check(item)) { + PyErr_SetString(PyExc_TypeError, + "Item in ``from list'' not a string"); + Py_DECREF(item); + return 0; + } + if (PyUnicode_AS_UNICODE(item)[0] == '*') { + PyObject *all; + Py_DECREF(item); + /* See if the package defines __all__ */ + if (recursive) + continue; /* Avoid endless recursion */ + all = PyObject_GetAttrString(mod, "__all__"); + if (all == NULL) + PyErr_Clear(); + else { + int ret = ensure_fromlist(mod, all, buf, buflen, 1); + Py_DECREF(all); + if (!ret) + return 0; + } + continue; + } + hasit = PyObject_HasAttr(mod, item); + if (!hasit) { + PyObject *item8; + char *subname; + PyObject *submod; + char *p; + if (!Py_FileSystemDefaultEncoding) { + item8 = PyUnicode_EncodeASCII(PyUnicode_AsUnicode(item), + PyUnicode_GetSize(item), + NULL); + } else { + item8 = PyUnicode_AsEncodedString(item, + Py_FileSystemDefaultEncoding, NULL); + } + if (!item8) { + PyErr_SetString(PyExc_ValueError, "Cannot encode path item"); + return 0; + } + subname = PyBytes_AS_STRING(item8); + if (buflen + strlen(subname) >= MAXPATHLEN) { + PyErr_SetString(PyExc_ValueError, + "Module name too long"); + Py_DECREF(item); + return 0; + } + p = buf + buflen; + *p++ = '.'; + strcpy(p, subname); + submod = import_submodule(mod, subname, buf); + Py_DECREF(item8); + Py_XDECREF(submod); + if (submod == NULL) { + Py_DECREF(item); + return 0; + } + } + Py_DECREF(item); + } - /* NOTREACHED */ + /* NOTREACHED */ } static int add_submodule(PyObject *mod, PyObject *submod, char *fullname, char *subname, - PyObject *modules) + PyObject *modules) { - if (mod == Py_None) - return 1; - /* Irrespective of the success of this load, make a - reference to it in the parent package module. A copy gets - saved in the modules dictionary under the full name, so get a - reference from there, if need be. (The exception is when the - load failed with a SyntaxError -- then there's no trace in - sys.modules. In that case, of course, do nothing extra.) */ - if (submod == NULL) { - submod = PyDict_GetItemString(modules, fullname); - if (submod == NULL) - return 1; - } - if (PyModule_Check(mod)) { - /* We can't use setattr here since it can give a - * spurious warning if the submodule name shadows a - * builtin name */ - PyObject *dict = PyModule_GetDict(mod); - if (!dict) - return 0; - if (PyDict_SetItemString(dict, subname, submod) < 0) - return 0; - } - else { - if (PyObject_SetAttrString(mod, subname, submod) < 0) - return 0; - } - return 1; + if (mod == Py_None) + return 1; + /* Irrespective of the success of this load, make a + reference to it in the parent package module. A copy gets + saved in the modules dictionary under the full name, so get a + reference from there, if need be. (The exception is when the + load failed with a SyntaxError -- then there's no trace in + sys.modules. In that case, of course, do nothing extra.) */ + if (submod == NULL) { + submod = PyDict_GetItemString(modules, fullname); + if (submod == NULL) + return 1; + } + if (PyModule_Check(mod)) { + /* We can't use setattr here since it can give a + * spurious warning if the submodule name shadows a + * builtin name */ + PyObject *dict = PyModule_GetDict(mod); + if (!dict) + return 0; + if (PyDict_SetItemString(dict, subname, submod) < 0) + return 0; + } + else { + if (PyObject_SetAttrString(mod, subname, submod) < 0) + return 0; + } + return 1; } static PyObject * import_submodule(PyObject *mod, char *subname, char *fullname) { - PyObject *modules = PyImport_GetModuleDict(); - PyObject *m = NULL; + PyObject *modules = PyImport_GetModuleDict(); + PyObject *m = NULL; - /* Require: - if mod == None: subname == fullname - else: mod.__name__ + "." + subname == fullname - */ - - if ((m = PyDict_GetItemString(modules, fullname)) != NULL) { - Py_INCREF(m); - } - else { - PyObject *path, *loader = NULL; - char buf[MAXPATHLEN+1]; - struct filedescr *fdp; - FILE *fp = NULL; - - if (mod == Py_None) - path = NULL; - else { - path = PyObject_GetAttrString(mod, "__path__"); - if (path == NULL) { - PyErr_Clear(); - Py_INCREF(Py_None); - return Py_None; - } - } - - buf[0] = '\0'; - fdp = find_module(fullname, subname, path, buf, MAXPATHLEN+1, - &fp, &loader); - Py_XDECREF(path); - if (fdp == NULL) { - if (!PyErr_ExceptionMatches(PyExc_ImportError)) - return NULL; - PyErr_Clear(); - Py_INCREF(Py_None); - return Py_None; - } - m = load_module(fullname, fp, buf, fdp->type, loader); - Py_XDECREF(loader); - if (fp) - fclose(fp); - if (!add_submodule(mod, m, fullname, subname, modules)) { - Py_XDECREF(m); - m = NULL; - } - } + /* Require: + if mod == None: subname == fullname + else: mod.__name__ + "." + subname == fullname + */ + + if ((m = PyDict_GetItemString(modules, fullname)) != NULL) { + Py_INCREF(m); + } + else { + PyObject *path, *loader = NULL; + char buf[MAXPATHLEN+1]; + struct filedescr *fdp; + FILE *fp = NULL; + + if (mod == Py_None) + path = NULL; + else { + path = PyObject_GetAttrString(mod, "__path__"); + if (path == NULL) { + PyErr_Clear(); + Py_INCREF(Py_None); + return Py_None; + } + } + + buf[0] = '\0'; + fdp = find_module(fullname, subname, path, buf, MAXPATHLEN+1, + &fp, &loader); + Py_XDECREF(path); + if (fdp == NULL) { + if (!PyErr_ExceptionMatches(PyExc_ImportError)) + return NULL; + PyErr_Clear(); + Py_INCREF(Py_None); + return Py_None; + } + m = load_module(fullname, fp, buf, fdp->type, loader); + Py_XDECREF(loader); + if (fp) + fclose(fp); + if (!add_submodule(mod, m, fullname, subname, modules)) { + Py_XDECREF(m); + m = NULL; + } + } - return m; + return m; } @@ -2641,96 +2641,96 @@ PyObject * PyImport_ReloadModule(PyObject *m) { - PyInterpreterState *interp = PyThreadState_Get()->interp; - PyObject *modules_reloading = interp->modules_reloading; - PyObject *modules = PyImport_GetModuleDict(); - PyObject *path = NULL, *loader = NULL, *existing_m = NULL; - char *name, *subname; - char buf[MAXPATHLEN+1]; - struct filedescr *fdp; - FILE *fp = NULL; - PyObject *newm; - - if (modules_reloading == NULL) { - Py_FatalError("PyImport_ReloadModule: " - "no modules_reloading dictionary!"); - return NULL; - } - - if (m == NULL || !PyModule_Check(m)) { - PyErr_SetString(PyExc_TypeError, - "reload() argument must be module"); - return NULL; - } - name = (char*)PyModule_GetName(m); - if (name == NULL) - return NULL; - if (m != PyDict_GetItemString(modules, name)) { - PyErr_Format(PyExc_ImportError, - "reload(): module %.200s not in sys.modules", - name); - return NULL; - } - existing_m = PyDict_GetItemString(modules_reloading, name); - if (existing_m != NULL) { - /* Due to a recursive reload, this module is already - being reloaded. */ - Py_INCREF(existing_m); - return existing_m; - } - if (PyDict_SetItemString(modules_reloading, name, m) < 0) - return NULL; - - subname = strrchr(name, '.'); - if (subname == NULL) - subname = name; - else { - PyObject *parentname, *parent; - parentname = PyUnicode_FromStringAndSize(name, (subname-name)); - if (parentname == NULL) { - imp_modules_reloading_clear(); - return NULL; - } - parent = PyDict_GetItem(modules, parentname); - if (parent == NULL) { - PyErr_Format(PyExc_ImportError, - "reload(): parent %U not in sys.modules", - parentname); - Py_DECREF(parentname); - imp_modules_reloading_clear(); - return NULL; - } - Py_DECREF(parentname); - subname++; - path = PyObject_GetAttrString(parent, "__path__"); - if (path == NULL) - PyErr_Clear(); - } - buf[0] = '\0'; - fdp = find_module(name, subname, path, buf, MAXPATHLEN+1, &fp, &loader); - Py_XDECREF(path); - - if (fdp == NULL) { - Py_XDECREF(loader); - imp_modules_reloading_clear(); - return NULL; - } - - newm = load_module(name, fp, buf, fdp->type, loader); - Py_XDECREF(loader); - - if (fp) - fclose(fp); - if (newm == NULL) { - /* load_module probably removed name from modules because of - * the error. Put back the original module object. We're - * going to return NULL in this case regardless of whether - * replacing name succeeds, so the return value is ignored. - */ - PyDict_SetItemString(modules, name, m); - } - imp_modules_reloading_clear(); - return newm; + PyInterpreterState *interp = PyThreadState_Get()->interp; + PyObject *modules_reloading = interp->modules_reloading; + PyObject *modules = PyImport_GetModuleDict(); + PyObject *path = NULL, *loader = NULL, *existing_m = NULL; + char *name, *subname; + char buf[MAXPATHLEN+1]; + struct filedescr *fdp; + FILE *fp = NULL; + PyObject *newm; + + if (modules_reloading == NULL) { + Py_FatalError("PyImport_ReloadModule: " + "no modules_reloading dictionary!"); + return NULL; + } + + if (m == NULL || !PyModule_Check(m)) { + PyErr_SetString(PyExc_TypeError, + "reload() argument must be module"); + return NULL; + } + name = (char*)PyModule_GetName(m); + if (name == NULL) + return NULL; + if (m != PyDict_GetItemString(modules, name)) { + PyErr_Format(PyExc_ImportError, + "reload(): module %.200s not in sys.modules", + name); + return NULL; + } + existing_m = PyDict_GetItemString(modules_reloading, name); + if (existing_m != NULL) { + /* Due to a recursive reload, this module is already + being reloaded. */ + Py_INCREF(existing_m); + return existing_m; + } + if (PyDict_SetItemString(modules_reloading, name, m) < 0) + return NULL; + + subname = strrchr(name, '.'); + if (subname == NULL) + subname = name; + else { + PyObject *parentname, *parent; + parentname = PyUnicode_FromStringAndSize(name, (subname-name)); + if (parentname == NULL) { + imp_modules_reloading_clear(); + return NULL; + } + parent = PyDict_GetItem(modules, parentname); + if (parent == NULL) { + PyErr_Format(PyExc_ImportError, + "reload(): parent %U not in sys.modules", + parentname); + Py_DECREF(parentname); + imp_modules_reloading_clear(); + return NULL; + } + Py_DECREF(parentname); + subname++; + path = PyObject_GetAttrString(parent, "__path__"); + if (path == NULL) + PyErr_Clear(); + } + buf[0] = '\0'; + fdp = find_module(name, subname, path, buf, MAXPATHLEN+1, &fp, &loader); + Py_XDECREF(path); + + if (fdp == NULL) { + Py_XDECREF(loader); + imp_modules_reloading_clear(); + return NULL; + } + + newm = load_module(name, fp, buf, fdp->type, loader); + Py_XDECREF(loader); + + if (fp) + fclose(fp); + if (newm == NULL) { + /* load_module probably removed name from modules because of + * the error. Put back the original module object. We're + * going to return NULL in this case regardless of whether + * replacing name succeeds, so the return value is ignored. + */ + PyDict_SetItemString(modules, name, m); + } + imp_modules_reloading_clear(); + return newm; } @@ -2746,68 +2746,68 @@ PyObject * PyImport_Import(PyObject *module_name) { - static PyObject *silly_list = NULL; - static PyObject *builtins_str = NULL; - static PyObject *import_str = NULL; - PyObject *globals = NULL; - PyObject *import = NULL; - PyObject *builtins = NULL; - PyObject *r = NULL; - - /* Initialize constant string objects */ - if (silly_list == NULL) { - import_str = PyUnicode_InternFromString("__import__"); - if (import_str == NULL) - return NULL; - builtins_str = PyUnicode_InternFromString("__builtins__"); - if (builtins_str == NULL) - return NULL; - silly_list = Py_BuildValue("[s]", "__doc__"); - if (silly_list == NULL) - return NULL; - } - - /* Get the builtins from current globals */ - globals = PyEval_GetGlobals(); - if (globals != NULL) { - Py_INCREF(globals); - builtins = PyObject_GetItem(globals, builtins_str); - if (builtins == NULL) - goto err; - } - else { - /* No globals -- use standard builtins, and fake globals */ - builtins = PyImport_ImportModuleLevel("builtins", - NULL, NULL, NULL, 0); - if (builtins == NULL) - return NULL; - globals = Py_BuildValue("{OO}", builtins_str, builtins); - if (globals == NULL) - goto err; - } - - /* Get the __import__ function from the builtins */ - if (PyDict_Check(builtins)) { - import = PyObject_GetItem(builtins, import_str); - if (import == NULL) - PyErr_SetObject(PyExc_KeyError, import_str); - } - else - import = PyObject_GetAttr(builtins, import_str); - if (import == NULL) - goto err; - - /* Call the __import__ function with the proper argument list - * Always use absolute import here. */ - r = PyObject_CallFunction(import, "OOOOi", module_name, globals, - globals, silly_list, 0, NULL); + static PyObject *silly_list = NULL; + static PyObject *builtins_str = NULL; + static PyObject *import_str = NULL; + PyObject *globals = NULL; + PyObject *import = NULL; + PyObject *builtins = NULL; + PyObject *r = NULL; + + /* Initialize constant string objects */ + if (silly_list == NULL) { + import_str = PyUnicode_InternFromString("__import__"); + if (import_str == NULL) + return NULL; + builtins_str = PyUnicode_InternFromString("__builtins__"); + if (builtins_str == NULL) + return NULL; + silly_list = Py_BuildValue("[s]", "__doc__"); + if (silly_list == NULL) + return NULL; + } + + /* Get the builtins from current globals */ + globals = PyEval_GetGlobals(); + if (globals != NULL) { + Py_INCREF(globals); + builtins = PyObject_GetItem(globals, builtins_str); + if (builtins == NULL) + goto err; + } + else { + /* No globals -- use standard builtins, and fake globals */ + builtins = PyImport_ImportModuleLevel("builtins", + NULL, NULL, NULL, 0); + if (builtins == NULL) + return NULL; + globals = Py_BuildValue("{OO}", builtins_str, builtins); + if (globals == NULL) + goto err; + } + + /* Get the __import__ function from the builtins */ + if (PyDict_Check(builtins)) { + import = PyObject_GetItem(builtins, import_str); + if (import == NULL) + PyErr_SetObject(PyExc_KeyError, import_str); + } + else + import = PyObject_GetAttr(builtins, import_str); + if (import == NULL) + goto err; + + /* Call the __import__ function with the proper argument list + * Always use absolute import here. */ + r = PyObject_CallFunction(import, "OOOOi", module_name, globals, + globals, silly_list, 0, NULL); err: - Py_XDECREF(globals); - Py_XDECREF(builtins); - Py_XDECREF(import); + Py_XDECREF(globals); + Py_XDECREF(builtins); + Py_XDECREF(import); - return r; + return r; } @@ -2818,245 +2818,245 @@ static PyObject * imp_get_magic(PyObject *self, PyObject *noargs) { - char buf[4]; + char buf[4]; - buf[0] = (char) ((pyc_magic >> 0) & 0xff); - buf[1] = (char) ((pyc_magic >> 8) & 0xff); - buf[2] = (char) ((pyc_magic >> 16) & 0xff); - buf[3] = (char) ((pyc_magic >> 24) & 0xff); + buf[0] = (char) ((pyc_magic >> 0) & 0xff); + buf[1] = (char) ((pyc_magic >> 8) & 0xff); + buf[2] = (char) ((pyc_magic >> 16) & 0xff); + buf[3] = (char) ((pyc_magic >> 24) & 0xff); - return PyBytes_FromStringAndSize(buf, 4); + return PyBytes_FromStringAndSize(buf, 4); } static PyObject * imp_get_suffixes(PyObject *self, PyObject *noargs) { - PyObject *list; - struct filedescr *fdp; + PyObject *list; + struct filedescr *fdp; - list = PyList_New(0); - if (list == NULL) - return NULL; - for (fdp = _PyImport_Filetab; fdp->suffix != NULL; fdp++) { - PyObject *item = Py_BuildValue("ssi", - fdp->suffix, fdp->mode, fdp->type); - if (item == NULL) { - Py_DECREF(list); - return NULL; - } - if (PyList_Append(list, item) < 0) { - Py_DECREF(list); - Py_DECREF(item); - return NULL; - } - Py_DECREF(item); - } - return list; + list = PyList_New(0); + if (list == NULL) + return NULL; + for (fdp = _PyImport_Filetab; fdp->suffix != NULL; fdp++) { + PyObject *item = Py_BuildValue("ssi", + fdp->suffix, fdp->mode, fdp->type); + if (item == NULL) { + Py_DECREF(list); + return NULL; + } + if (PyList_Append(list, item) < 0) { + Py_DECREF(list); + Py_DECREF(item); + return NULL; + } + Py_DECREF(item); + } + return list; } static PyObject * call_find_module(char *name, PyObject *path) { - extern int fclose(FILE *); - PyObject *fob, *ret; - PyObject *pathobj; - struct filedescr *fdp; - char pathname[MAXPATHLEN+1]; - FILE *fp = NULL; - int fd = -1; - char *found_encoding = NULL; - char *encoding = NULL; - - pathname[0] = '\0'; - if (path == Py_None) - path = NULL; - fdp = find_module(NULL, name, path, pathname, MAXPATHLEN+1, &fp, NULL); - if (fdp == NULL) - return NULL; - if (fp != NULL) { - fd = fileno(fp); - if (fd != -1) - fd = dup(fd); - fclose(fp); - fp = NULL; - } - if (fd != -1) { - if (strchr(fdp->mode, 'b') == NULL) { - /* PyTokenizer_FindEncoding() returns PyMem_MALLOC'ed - memory. */ - found_encoding = PyTokenizer_FindEncoding(fd); - lseek(fd, 0, 0); /* Reset position */ - if (found_encoding == NULL && PyErr_Occurred()) - return NULL; - encoding = (found_encoding != NULL) ? found_encoding : - (char*)PyUnicode_GetDefaultEncoding(); - } - fob = PyFile_FromFd(fd, pathname, fdp->mode, -1, - (char*)encoding, NULL, NULL, 1); - if (fob == NULL) { - close(fd); - PyMem_FREE(found_encoding); - return NULL; - } - } - else { - fob = Py_None; - Py_INCREF(fob); - } - pathobj = PyUnicode_DecodeFSDefault(pathname); - ret = Py_BuildValue("NN(ssi)", - fob, pathobj, fdp->suffix, fdp->mode, fdp->type); - PyMem_FREE(found_encoding); + extern int fclose(FILE *); + PyObject *fob, *ret; + PyObject *pathobj; + struct filedescr *fdp; + char pathname[MAXPATHLEN+1]; + FILE *fp = NULL; + int fd = -1; + char *found_encoding = NULL; + char *encoding = NULL; + + pathname[0] = '\0'; + if (path == Py_None) + path = NULL; + fdp = find_module(NULL, name, path, pathname, MAXPATHLEN+1, &fp, NULL); + if (fdp == NULL) + return NULL; + if (fp != NULL) { + fd = fileno(fp); + if (fd != -1) + fd = dup(fd); + fclose(fp); + fp = NULL; + } + if (fd != -1) { + if (strchr(fdp->mode, 'b') == NULL) { + /* PyTokenizer_FindEncoding() returns PyMem_MALLOC'ed + memory. */ + found_encoding = PyTokenizer_FindEncoding(fd); + lseek(fd, 0, 0); /* Reset position */ + if (found_encoding == NULL && PyErr_Occurred()) + return NULL; + encoding = (found_encoding != NULL) ? found_encoding : + (char*)PyUnicode_GetDefaultEncoding(); + } + fob = PyFile_FromFd(fd, pathname, fdp->mode, -1, + (char*)encoding, NULL, NULL, 1); + if (fob == NULL) { + close(fd); + PyMem_FREE(found_encoding); + return NULL; + } + } + else { + fob = Py_None; + Py_INCREF(fob); + } + pathobj = PyUnicode_DecodeFSDefault(pathname); + ret = Py_BuildValue("NN(ssi)", + fob, pathobj, fdp->suffix, fdp->mode, fdp->type); + PyMem_FREE(found_encoding); - return ret; + return ret; } static PyObject * imp_find_module(PyObject *self, PyObject *args) { - char *name; - PyObject *ret, *path = NULL; - if (!PyArg_ParseTuple(args, "es|O:find_module", - Py_FileSystemDefaultEncoding, &name, - &path)) - return NULL; - ret = call_find_module(name, path); - PyMem_Free(name); - return ret; + char *name; + PyObject *ret, *path = NULL; + if (!PyArg_ParseTuple(args, "es|O:find_module", + Py_FileSystemDefaultEncoding, &name, + &path)) + return NULL; + ret = call_find_module(name, path); + PyMem_Free(name); + return ret; } static PyObject * imp_init_builtin(PyObject *self, PyObject *args) { - char *name; - int ret; - PyObject *m; - if (!PyArg_ParseTuple(args, "s:init_builtin", &name)) - return NULL; - ret = init_builtin(name); - if (ret < 0) - return NULL; - if (ret == 0) { - Py_INCREF(Py_None); - return Py_None; - } - m = PyImport_AddModule(name); - Py_XINCREF(m); - return m; + char *name; + int ret; + PyObject *m; + if (!PyArg_ParseTuple(args, "s:init_builtin", &name)) + return NULL; + ret = init_builtin(name); + if (ret < 0) + return NULL; + if (ret == 0) { + Py_INCREF(Py_None); + return Py_None; + } + m = PyImport_AddModule(name); + Py_XINCREF(m); + return m; } static PyObject * imp_init_frozen(PyObject *self, PyObject *args) { - char *name; - int ret; - PyObject *m; - if (!PyArg_ParseTuple(args, "s:init_frozen", &name)) - return NULL; - ret = PyImport_ImportFrozenModule(name); - if (ret < 0) - return NULL; - if (ret == 0) { - Py_INCREF(Py_None); - return Py_None; - } - m = PyImport_AddModule(name); - Py_XINCREF(m); - return m; + char *name; + int ret; + PyObject *m; + if (!PyArg_ParseTuple(args, "s:init_frozen", &name)) + return NULL; + ret = PyImport_ImportFrozenModule(name); + if (ret < 0) + return NULL; + if (ret == 0) { + Py_INCREF(Py_None); + return Py_None; + } + m = PyImport_AddModule(name); + Py_XINCREF(m); + return m; } static PyObject * imp_get_frozen_object(PyObject *self, PyObject *args) { - char *name; + char *name; - if (!PyArg_ParseTuple(args, "s:get_frozen_object", &name)) - return NULL; - return get_frozen_object(name); + if (!PyArg_ParseTuple(args, "s:get_frozen_object", &name)) + return NULL; + return get_frozen_object(name); } static PyObject * imp_is_frozen_package(PyObject *self, PyObject *args) { - char *name; + char *name; - if (!PyArg_ParseTuple(args, "s:is_frozen_package", &name)) - return NULL; - return is_frozen_package(name); + if (!PyArg_ParseTuple(args, "s:is_frozen_package", &name)) + return NULL; + return is_frozen_package(name); } static PyObject * imp_is_builtin(PyObject *self, PyObject *args) { - char *name; - if (!PyArg_ParseTuple(args, "s:is_builtin", &name)) - return NULL; - return PyLong_FromLong(is_builtin(name)); + char *name; + if (!PyArg_ParseTuple(args, "s:is_builtin", &name)) + return NULL; + return PyLong_FromLong(is_builtin(name)); } static PyObject * imp_is_frozen(PyObject *self, PyObject *args) { - char *name; - struct _frozen *p; - if (!PyArg_ParseTuple(args, "s:is_frozen", &name)) - return NULL; - p = find_frozen(name); - return PyBool_FromLong((long) (p == NULL ? 0 : p->size)); + char *name; + struct _frozen *p; + if (!PyArg_ParseTuple(args, "s:is_frozen", &name)) + return NULL; + p = find_frozen(name); + return PyBool_FromLong((long) (p == NULL ? 0 : p->size)); } static FILE * get_file(char *pathname, PyObject *fob, char *mode) { - FILE *fp; - if (mode[0] == 'U') - mode = "r" PY_STDIOTEXTMODE; - if (fob == NULL) { - fp = fopen(pathname, mode); - } - else { - int fd = PyObject_AsFileDescriptor(fob); - if (fd == -1) - return NULL; - if (!_PyVerify_fd(fd)) - goto error; - /* the FILE struct gets a new fd, so that it can be closed - * independently of the file descriptor given - */ - fd = dup(fd); - if (fd == -1) - goto error; - fp = fdopen(fd, mode); - } - if (fp) - return fp; + FILE *fp; + if (mode[0] == 'U') + mode = "r" PY_STDIOTEXTMODE; + if (fob == NULL) { + fp = fopen(pathname, mode); + } + else { + int fd = PyObject_AsFileDescriptor(fob); + if (fd == -1) + return NULL; + if (!_PyVerify_fd(fd)) + goto error; + /* the FILE struct gets a new fd, so that it can be closed + * independently of the file descriptor given + */ + fd = dup(fd); + if (fd == -1) + goto error; + fp = fdopen(fd, mode); + } + if (fp) + return fp; error: - PyErr_SetFromErrno(PyExc_IOError); - return NULL; + PyErr_SetFromErrno(PyExc_IOError); + return NULL; } static PyObject * imp_load_compiled(PyObject *self, PyObject *args) { - char *name; - char *pathname; - PyObject *fob = NULL; - PyObject *m; - FILE *fp; - if (!PyArg_ParseTuple(args, "ses|O:load_compiled", - &name, - Py_FileSystemDefaultEncoding, &pathname, - &fob)) - return NULL; - fp = get_file(pathname, fob, "rb"); - if (fp == NULL) { - PyMem_Free(pathname); - return NULL; - } - m = load_compiled_module(name, pathname, fp); - fclose(fp); - PyMem_Free(pathname); - return m; + char *name; + char *pathname; + PyObject *fob = NULL; + PyObject *m; + FILE *fp; + if (!PyArg_ParseTuple(args, "ses|O:load_compiled", + &name, + Py_FileSystemDefaultEncoding, &pathname, + &fob)) + return NULL; + fp = get_file(pathname, fob, "rb"); + if (fp == NULL) { + PyMem_Free(pathname); + return NULL; + } + m = load_compiled_module(name, pathname, fp); + fclose(fp); + PyMem_Free(pathname); + return m; } #ifdef HAVE_DYNAMIC_LOADING @@ -3064,28 +3064,28 @@ static PyObject * imp_load_dynamic(PyObject *self, PyObject *args) { - char *name; - char *pathname; - PyObject *fob = NULL; - PyObject *m; - FILE *fp = NULL; - if (!PyArg_ParseTuple(args, "ses|O:load_dynamic", - &name, - Py_FileSystemDefaultEncoding, &pathname, - &fob)) - return NULL; - if (fob) { - fp = get_file(pathname, fob, "r"); - if (fp == NULL) { - PyMem_Free(pathname); - return NULL; - } - } - m = _PyImport_LoadDynamicModule(name, pathname, fp); - PyMem_Free(pathname); - if (fp) - fclose(fp); - return m; + char *name; + char *pathname; + PyObject *fob = NULL; + PyObject *m; + FILE *fp = NULL; + if (!PyArg_ParseTuple(args, "ses|O:load_dynamic", + &name, + Py_FileSystemDefaultEncoding, &pathname, + &fob)) + return NULL; + if (fob) { + fp = get_file(pathname, fob, "r"); + if (fp == NULL) { + PyMem_Free(pathname); + return NULL; + } + } + m = _PyImport_LoadDynamicModule(name, pathname, fp); + PyMem_Free(pathname); + if (fp) + fclose(fp); + return m; } #endif /* HAVE_DYNAMIC_LOADING */ @@ -3093,99 +3093,99 @@ static PyObject * imp_load_source(PyObject *self, PyObject *args) { - char *name; - char *pathname; - PyObject *fob = NULL; - PyObject *m; - FILE *fp; - if (!PyArg_ParseTuple(args, "ses|O:load_source", - &name, - Py_FileSystemDefaultEncoding, &pathname, - &fob)) - return NULL; - fp = get_file(pathname, fob, "r"); - if (fp == NULL) { - PyMem_Free(pathname); - return NULL; - } - m = load_source_module(name, pathname, fp); - PyMem_Free(pathname); - fclose(fp); - return m; + char *name; + char *pathname; + PyObject *fob = NULL; + PyObject *m; + FILE *fp; + if (!PyArg_ParseTuple(args, "ses|O:load_source", + &name, + Py_FileSystemDefaultEncoding, &pathname, + &fob)) + return NULL; + fp = get_file(pathname, fob, "r"); + if (fp == NULL) { + PyMem_Free(pathname); + return NULL; + } + m = load_source_module(name, pathname, fp); + PyMem_Free(pathname); + fclose(fp); + return m; } static PyObject * imp_load_module(PyObject *self, PyObject *args) { - char *name; - PyObject *fob; - char *pathname; - PyObject * ret; - char *suffix; /* Unused */ - char *mode; - int type; - FILE *fp; - - if (!PyArg_ParseTuple(args, "sOes(ssi):load_module", - &name, &fob, - Py_FileSystemDefaultEncoding, &pathname, - &suffix, &mode, &type)) - return NULL; - if (*mode) { - /* Mode must start with 'r' or 'U' and must not contain '+'. - Implicit in this test is the assumption that the mode - may contain other modifiers like 'b' or 't'. */ - - if (!(*mode == 'r' || *mode == 'U') || strchr(mode, '+')) { - PyErr_Format(PyExc_ValueError, - "invalid file open mode %.200s", mode); - PyMem_Free(pathname); - return NULL; - } - } - if (fob == Py_None) - fp = NULL; - else { - fp = get_file(NULL, fob, mode); - if (fp == NULL) { - PyMem_Free(pathname); - return NULL; - } - } - ret = load_module(name, fp, pathname, type, NULL); - PyMem_Free(pathname); - if (fp) - fclose(fp); - return ret; + char *name; + PyObject *fob; + char *pathname; + PyObject * ret; + char *suffix; /* Unused */ + char *mode; + int type; + FILE *fp; + + if (!PyArg_ParseTuple(args, "sOes(ssi):load_module", + &name, &fob, + Py_FileSystemDefaultEncoding, &pathname, + &suffix, &mode, &type)) + return NULL; + if (*mode) { + /* Mode must start with 'r' or 'U' and must not contain '+'. + Implicit in this test is the assumption that the mode + may contain other modifiers like 'b' or 't'. */ + + if (!(*mode == 'r' || *mode == 'U') || strchr(mode, '+')) { + PyErr_Format(PyExc_ValueError, + "invalid file open mode %.200s", mode); + PyMem_Free(pathname); + return NULL; + } + } + if (fob == Py_None) + fp = NULL; + else { + fp = get_file(NULL, fob, mode); + if (fp == NULL) { + PyMem_Free(pathname); + return NULL; + } + } + ret = load_module(name, fp, pathname, type, NULL); + PyMem_Free(pathname); + if (fp) + fclose(fp); + return ret; } static PyObject * imp_load_package(PyObject *self, PyObject *args) { - char *name; - char *pathname; - PyObject * ret; - if (!PyArg_ParseTuple(args, "ses:load_package", - &name, Py_FileSystemDefaultEncoding, &pathname)) - return NULL; - ret = load_package(name, pathname); - PyMem_Free(pathname); - return ret; + char *name; + char *pathname; + PyObject * ret; + if (!PyArg_ParseTuple(args, "ses:load_package", + &name, Py_FileSystemDefaultEncoding, &pathname)) + return NULL; + ret = load_package(name, pathname); + PyMem_Free(pathname); + return ret; } static PyObject * imp_new_module(PyObject *self, PyObject *args) { - char *name; - if (!PyArg_ParseTuple(args, "s:new_module", &name)) - return NULL; - return PyModule_New(name); + char *name; + if (!PyArg_ParseTuple(args, "s:new_module", &name)) + return NULL; + return PyModule_New(name); } static PyObject * imp_reload(PyObject *self, PyObject *v) { - return PyImport_ReloadModule(v); + return PyImport_ReloadModule(v); } PyDoc_STRVAR(doc_reload, @@ -3243,41 +3243,41 @@ On platforms without threads, this function does nothing."); static PyMethodDef imp_methods[] = { - {"find_module", imp_find_module, METH_VARARGS, doc_find_module}, - {"get_magic", imp_get_magic, METH_NOARGS, doc_get_magic}, - {"get_suffixes", imp_get_suffixes, METH_NOARGS, doc_get_suffixes}, - {"load_module", imp_load_module, METH_VARARGS, doc_load_module}, - {"new_module", imp_new_module, METH_VARARGS, doc_new_module}, - {"lock_held", imp_lock_held, METH_NOARGS, doc_lock_held}, - {"acquire_lock", imp_acquire_lock, METH_NOARGS, doc_acquire_lock}, - {"release_lock", imp_release_lock, METH_NOARGS, doc_release_lock}, - {"reload", imp_reload, METH_O, doc_reload}, - /* The rest are obsolete */ - {"get_frozen_object", imp_get_frozen_object, METH_VARARGS}, - {"is_frozen_package", imp_is_frozen_package, METH_VARARGS}, - {"init_builtin", imp_init_builtin, METH_VARARGS}, - {"init_frozen", imp_init_frozen, METH_VARARGS}, - {"is_builtin", imp_is_builtin, METH_VARARGS}, - {"is_frozen", imp_is_frozen, METH_VARARGS}, - {"load_compiled", imp_load_compiled, METH_VARARGS}, + {"find_module", imp_find_module, METH_VARARGS, doc_find_module}, + {"get_magic", imp_get_magic, METH_NOARGS, doc_get_magic}, + {"get_suffixes", imp_get_suffixes, METH_NOARGS, doc_get_suffixes}, + {"load_module", imp_load_module, METH_VARARGS, doc_load_module}, + {"new_module", imp_new_module, METH_VARARGS, doc_new_module}, + {"lock_held", imp_lock_held, METH_NOARGS, doc_lock_held}, + {"acquire_lock", imp_acquire_lock, METH_NOARGS, doc_acquire_lock}, + {"release_lock", imp_release_lock, METH_NOARGS, doc_release_lock}, + {"reload", imp_reload, METH_O, doc_reload}, + /* The rest are obsolete */ + {"get_frozen_object", imp_get_frozen_object, METH_VARARGS}, + {"is_frozen_package", imp_is_frozen_package, METH_VARARGS}, + {"init_builtin", imp_init_builtin, METH_VARARGS}, + {"init_frozen", imp_init_frozen, METH_VARARGS}, + {"is_builtin", imp_is_builtin, METH_VARARGS}, + {"is_frozen", imp_is_frozen, METH_VARARGS}, + {"load_compiled", imp_load_compiled, METH_VARARGS}, #ifdef HAVE_DYNAMIC_LOADING - {"load_dynamic", imp_load_dynamic, METH_VARARGS}, + {"load_dynamic", imp_load_dynamic, METH_VARARGS}, #endif - {"load_package", imp_load_package, METH_VARARGS}, - {"load_source", imp_load_source, METH_VARARGS}, - {NULL, NULL} /* sentinel */ + {"load_package", imp_load_package, METH_VARARGS}, + {"load_source", imp_load_source, METH_VARARGS}, + {NULL, NULL} /* sentinel */ }; static int setint(PyObject *d, char *name, int value) { - PyObject *v; - int err; + PyObject *v; + int err; - v = PyLong_FromLong((long)value); - err = PyDict_SetItemString(d, name, v); - Py_XDECREF(v); - return err; + v = PyLong_FromLong((long)value); + err = PyDict_SetItemString(d, name, v); + Py_XDECREF(v); + return err; } typedef struct { @@ -3287,158 +3287,158 @@ static int NullImporter_init(NullImporter *self, PyObject *args, PyObject *kwds) { - char *path; - Py_ssize_t pathlen; + char *path; + Py_ssize_t pathlen; - if (!_PyArg_NoKeywords("NullImporter()", kwds)) - return -1; + if (!_PyArg_NoKeywords("NullImporter()", kwds)) + return -1; - if (!PyArg_ParseTuple(args, "es:NullImporter", - Py_FileSystemDefaultEncoding, &path)) - return -1; - - pathlen = strlen(path); - if (pathlen == 0) { - PyMem_Free(path); - PyErr_SetString(PyExc_ImportError, "empty pathname"); - return -1; - } else { + if (!PyArg_ParseTuple(args, "es:NullImporter", + Py_FileSystemDefaultEncoding, &path)) + return -1; + + pathlen = strlen(path); + if (pathlen == 0) { + PyMem_Free(path); + PyErr_SetString(PyExc_ImportError, "empty pathname"); + return -1; + } else { #ifndef MS_WINDOWS - struct stat statbuf; - int rv; + struct stat statbuf; + int rv; - rv = stat(path, &statbuf); - PyMem_Free(path); - if (rv == 0) { - /* it exists */ - if (S_ISDIR(statbuf.st_mode)) { - /* it's a directory */ - PyErr_SetString(PyExc_ImportError, - "existing directory"); - return -1; - } - } + rv = stat(path, &statbuf); + PyMem_Free(path); + if (rv == 0) { + /* it exists */ + if (S_ISDIR(statbuf.st_mode)) { + /* it's a directory */ + PyErr_SetString(PyExc_ImportError, + "existing directory"); + return -1; + } + } #else /* MS_WINDOWS */ - DWORD rv; - /* see issue1293 and issue3677: - * stat() on Windows doesn't recognise paths like - * "e:\\shared\\" and "\\\\whiterab-c2znlh\\shared" as dirs. - */ - rv = GetFileAttributesA(path); - PyMem_Free(path); - if (rv != INVALID_FILE_ATTRIBUTES) { - /* it exists */ - if (rv & FILE_ATTRIBUTE_DIRECTORY) { - /* it's a directory */ - PyErr_SetString(PyExc_ImportError, - "existing directory"); - return -1; - } - } + DWORD rv; + /* see issue1293 and issue3677: + * stat() on Windows doesn't recognise paths like + * "e:\\shared\\" and "\\\\whiterab-c2znlh\\shared" as dirs. + */ + rv = GetFileAttributesA(path); + PyMem_Free(path); + if (rv != INVALID_FILE_ATTRIBUTES) { + /* it exists */ + if (rv & FILE_ATTRIBUTE_DIRECTORY) { + /* it's a directory */ + PyErr_SetString(PyExc_ImportError, + "existing directory"); + return -1; + } + } #endif - } - return 0; + } + return 0; } static PyObject * NullImporter_find_module(NullImporter *self, PyObject *args) { - Py_RETURN_NONE; + Py_RETURN_NONE; } static PyMethodDef NullImporter_methods[] = { - {"find_module", (PyCFunction)NullImporter_find_module, METH_VARARGS, - "Always return None" - }, - {NULL} /* Sentinel */ + {"find_module", (PyCFunction)NullImporter_find_module, METH_VARARGS, + "Always return None" + }, + {NULL} /* Sentinel */ }; PyTypeObject PyNullImporter_Type = { - PyVarObject_HEAD_INIT(NULL, 0) - "imp.NullImporter", /*tp_name*/ - sizeof(NullImporter), /*tp_basicsize*/ - 0, /*tp_itemsize*/ - 0, /*tp_dealloc*/ - 0, /*tp_print*/ - 0, /*tp_getattr*/ - 0, /*tp_setattr*/ - 0, /*tp_reserved*/ - 0, /*tp_repr*/ - 0, /*tp_as_number*/ - 0, /*tp_as_sequence*/ - 0, /*tp_as_mapping*/ - 0, /*tp_hash */ - 0, /*tp_call*/ - 0, /*tp_str*/ - 0, /*tp_getattro*/ - 0, /*tp_setattro*/ - 0, /*tp_as_buffer*/ - Py_TPFLAGS_DEFAULT, /*tp_flags*/ - "Null importer object", /* tp_doc */ - 0, /* tp_traverse */ - 0, /* tp_clear */ - 0, /* tp_richcompare */ - 0, /* tp_weaklistoffset */ - 0, /* tp_iter */ - 0, /* tp_iternext */ - NullImporter_methods, /* tp_methods */ - 0, /* tp_members */ - 0, /* tp_getset */ - 0, /* tp_base */ - 0, /* tp_dict */ - 0, /* tp_descr_get */ - 0, /* tp_descr_set */ - 0, /* tp_dictoffset */ - (initproc)NullImporter_init, /* tp_init */ - 0, /* tp_alloc */ - PyType_GenericNew /* tp_new */ + PyVarObject_HEAD_INIT(NULL, 0) + "imp.NullImporter", /*tp_name*/ + sizeof(NullImporter), /*tp_basicsize*/ + 0, /*tp_itemsize*/ + 0, /*tp_dealloc*/ + 0, /*tp_print*/ + 0, /*tp_getattr*/ + 0, /*tp_setattr*/ + 0, /*tp_reserved*/ + 0, /*tp_repr*/ + 0, /*tp_as_number*/ + 0, /*tp_as_sequence*/ + 0, /*tp_as_mapping*/ + 0, /*tp_hash */ + 0, /*tp_call*/ + 0, /*tp_str*/ + 0, /*tp_getattro*/ + 0, /*tp_setattro*/ + 0, /*tp_as_buffer*/ + Py_TPFLAGS_DEFAULT, /*tp_flags*/ + "Null importer object", /* tp_doc */ + 0, /* tp_traverse */ + 0, /* tp_clear */ + 0, /* tp_richcompare */ + 0, /* tp_weaklistoffset */ + 0, /* tp_iter */ + 0, /* tp_iternext */ + NullImporter_methods, /* tp_methods */ + 0, /* tp_members */ + 0, /* tp_getset */ + 0, /* tp_base */ + 0, /* tp_dict */ + 0, /* tp_descr_get */ + 0, /* tp_descr_set */ + 0, /* tp_dictoffset */ + (initproc)NullImporter_init, /* tp_init */ + 0, /* tp_alloc */ + PyType_GenericNew /* tp_new */ }; static struct PyModuleDef impmodule = { - PyModuleDef_HEAD_INIT, - "imp", - doc_imp, - 0, - imp_methods, - NULL, - NULL, - NULL, - NULL + PyModuleDef_HEAD_INIT, + "imp", + doc_imp, + 0, + imp_methods, + NULL, + NULL, + NULL, + NULL }; PyMODINIT_FUNC PyInit_imp(void) { - PyObject *m, *d; + PyObject *m, *d; - if (PyType_Ready(&PyNullImporter_Type) < 0) - return NULL; + if (PyType_Ready(&PyNullImporter_Type) < 0) + return NULL; - m = PyModule_Create(&impmodule); - if (m == NULL) - goto failure; - d = PyModule_GetDict(m); - if (d == NULL) - goto failure; - - if (setint(d, "SEARCH_ERROR", SEARCH_ERROR) < 0) goto failure; - if (setint(d, "PY_SOURCE", PY_SOURCE) < 0) goto failure; - if (setint(d, "PY_COMPILED", PY_COMPILED) < 0) goto failure; - if (setint(d, "C_EXTENSION", C_EXTENSION) < 0) goto failure; - if (setint(d, "PY_RESOURCE", PY_RESOURCE) < 0) goto failure; - if (setint(d, "PKG_DIRECTORY", PKG_DIRECTORY) < 0) goto failure; - if (setint(d, "C_BUILTIN", C_BUILTIN) < 0) goto failure; - if (setint(d, "PY_FROZEN", PY_FROZEN) < 0) goto failure; - if (setint(d, "PY_CODERESOURCE", PY_CODERESOURCE) < 0) goto failure; - if (setint(d, "IMP_HOOK", IMP_HOOK) < 0) goto failure; - - Py_INCREF(&PyNullImporter_Type); - PyModule_AddObject(m, "NullImporter", (PyObject *)&PyNullImporter_Type); - return m; + m = PyModule_Create(&impmodule); + if (m == NULL) + goto failure; + d = PyModule_GetDict(m); + if (d == NULL) + goto failure; + + if (setint(d, "SEARCH_ERROR", SEARCH_ERROR) < 0) goto failure; + if (setint(d, "PY_SOURCE", PY_SOURCE) < 0) goto failure; + if (setint(d, "PY_COMPILED", PY_COMPILED) < 0) goto failure; + if (setint(d, "C_EXTENSION", C_EXTENSION) < 0) goto failure; + if (setint(d, "PY_RESOURCE", PY_RESOURCE) < 0) goto failure; + if (setint(d, "PKG_DIRECTORY", PKG_DIRECTORY) < 0) goto failure; + if (setint(d, "C_BUILTIN", C_BUILTIN) < 0) goto failure; + if (setint(d, "PY_FROZEN", PY_FROZEN) < 0) goto failure; + if (setint(d, "PY_CODERESOURCE", PY_CODERESOURCE) < 0) goto failure; + if (setint(d, "IMP_HOOK", IMP_HOOK) < 0) goto failure; + + Py_INCREF(&PyNullImporter_Type); + PyModule_AddObject(m, "NullImporter", (PyObject *)&PyNullImporter_Type); + return m; failure: - Py_XDECREF(m); - return NULL; + Py_XDECREF(m); + return NULL; } @@ -3453,31 +3453,31 @@ int PyImport_ExtendInittab(struct _inittab *newtab) { - static struct _inittab *our_copy = NULL; - struct _inittab *p; - int i, n; - - /* Count the number of entries in both tables */ - for (n = 0; newtab[n].name != NULL; n++) - ; - if (n == 0) - return 0; /* Nothing to do */ - for (i = 0; PyImport_Inittab[i].name != NULL; i++) - ; - - /* Allocate new memory for the combined table */ - p = our_copy; - PyMem_RESIZE(p, struct _inittab, i+n+1); - if (p == NULL) - return -1; - - /* Copy the tables into the new memory */ - if (our_copy != PyImport_Inittab) - memcpy(p, PyImport_Inittab, (i+1) * sizeof(struct _inittab)); - PyImport_Inittab = our_copy = p; - memcpy(p+i, newtab, (n+1) * sizeof(struct _inittab)); + static struct _inittab *our_copy = NULL; + struct _inittab *p; + int i, n; + + /* Count the number of entries in both tables */ + for (n = 0; newtab[n].name != NULL; n++) + ; + if (n == 0) + return 0; /* Nothing to do */ + for (i = 0; PyImport_Inittab[i].name != NULL; i++) + ; + + /* Allocate new memory for the combined table */ + p = our_copy; + PyMem_RESIZE(p, struct _inittab, i+n+1); + if (p == NULL) + return -1; + + /* Copy the tables into the new memory */ + if (our_copy != PyImport_Inittab) + memcpy(p, PyImport_Inittab, (i+1) * sizeof(struct _inittab)); + PyImport_Inittab = our_copy = p; + memcpy(p+i, newtab, (n+1) * sizeof(struct _inittab)); - return 0; + return 0; } /* Shorthand to add a single entry given a name and a function */ @@ -3485,14 +3485,14 @@ int PyImport_AppendInittab(const char *name, PyObject* (*initfunc)(void)) { - struct _inittab newtab[2]; + struct _inittab newtab[2]; - memset(newtab, '\0', sizeof newtab); + memset(newtab, '\0', sizeof newtab); - newtab[0].name = (char *)name; - newtab[0].initfunc = initfunc; + newtab[0].name = (char *)name; + newtab[0].initfunc = initfunc; - return PyImport_ExtendInittab(newtab); + return PyImport_ExtendInittab(newtab); } #ifdef __cplusplus Modified: python/branches/release31-maint/Python/importdl.c ============================================================================== --- python/branches/release31-maint/Python/importdl.c (original) +++ python/branches/release31-maint/Python/importdl.c Sun May 9 18:14:21 2010 @@ -13,76 +13,76 @@ #include "importdl.h" extern dl_funcptr _PyImport_GetDynLoadFunc(const char *name, - const char *shortname, - const char *pathname, FILE *fp); + const char *shortname, + const char *pathname, FILE *fp); PyObject * _PyImport_LoadDynamicModule(char *name, char *pathname, FILE *fp) { - PyObject *m; - PyObject *path; - char *lastdot, *shortname, *packagecontext, *oldcontext; - dl_funcptr p0; - PyObject* (*p)(void); - struct PyModuleDef *def; - - if ((m = _PyImport_FindExtension(name, pathname)) != NULL) { - Py_INCREF(m); - return m; - } - lastdot = strrchr(name, '.'); - if (lastdot == NULL) { - packagecontext = NULL; - shortname = name; - } - else { - packagecontext = name; - shortname = lastdot+1; - } - - p0 = _PyImport_GetDynLoadFunc(name, shortname, pathname, fp); - p = (PyObject*(*)(void))p0; - if (PyErr_Occurred()) - return NULL; - if (p == NULL) { - PyErr_Format(PyExc_ImportError, - "dynamic module does not define init function (PyInit_%.200s)", - shortname); - return NULL; - } - oldcontext = _Py_PackageContext; - _Py_PackageContext = packagecontext; - m = (*p)(); - _Py_PackageContext = oldcontext; - if (m == NULL) - return NULL; - - if (PyErr_Occurred()) { - Py_DECREF(m); - PyErr_Format(PyExc_SystemError, - "initialization of %s raised unreported exception", - shortname); - return NULL; - } - - /* Remember pointer to module init function. */ - def = PyModule_GetDef(m); - def->m_base.m_init = p; - - /* Remember the filename as the __file__ attribute */ - path = PyUnicode_DecodeFSDefault(pathname); - if (PyModule_AddObject(m, "__file__", path) < 0) - PyErr_Clear(); /* Not important enough to report */ - - if (_PyImport_FixupExtension(m, name, pathname) < 0) - return NULL; - if (Py_VerboseFlag) - PySys_WriteStderr( - "import %s # dynamically loaded from %s\n", - name, pathname); - return m; + PyObject *m; + PyObject *path; + char *lastdot, *shortname, *packagecontext, *oldcontext; + dl_funcptr p0; + PyObject* (*p)(void); + struct PyModuleDef *def; + + if ((m = _PyImport_FindExtension(name, pathname)) != NULL) { + Py_INCREF(m); + return m; + } + lastdot = strrchr(name, '.'); + if (lastdot == NULL) { + packagecontext = NULL; + shortname = name; + } + else { + packagecontext = name; + shortname = lastdot+1; + } + + p0 = _PyImport_GetDynLoadFunc(name, shortname, pathname, fp); + p = (PyObject*(*)(void))p0; + if (PyErr_Occurred()) + return NULL; + if (p == NULL) { + PyErr_Format(PyExc_ImportError, + "dynamic module does not define init function (PyInit_%.200s)", + shortname); + return NULL; + } + oldcontext = _Py_PackageContext; + _Py_PackageContext = packagecontext; + m = (*p)(); + _Py_PackageContext = oldcontext; + if (m == NULL) + return NULL; + + if (PyErr_Occurred()) { + Py_DECREF(m); + PyErr_Format(PyExc_SystemError, + "initialization of %s raised unreported exception", + shortname); + return NULL; + } + + /* Remember pointer to module init function. */ + def = PyModule_GetDef(m); + def->m_base.m_init = p; + + /* Remember the filename as the __file__ attribute */ + path = PyUnicode_DecodeFSDefault(pathname); + if (PyModule_AddObject(m, "__file__", path) < 0) + PyErr_Clear(); /* Not important enough to report */ + + if (_PyImport_FixupExtension(m, name, pathname) < 0) + return NULL; + if (Py_VerboseFlag) + PySys_WriteStderr( + "import %s # dynamically loaded from %s\n", + name, pathname); + return m; } #endif /* HAVE_DYNAMIC_LOADING */ Modified: python/branches/release31-maint/Python/importdl.h ============================================================================== --- python/branches/release31-maint/Python/importdl.h (original) +++ python/branches/release31-maint/Python/importdl.h Sun May 9 18:14:21 2010 @@ -8,28 +8,28 @@ /* Definitions for dynamic loading of extension modules */ enum filetype { - SEARCH_ERROR, - PY_SOURCE, - PY_COMPILED, - C_EXTENSION, - PY_RESOURCE, /* Mac only */ - PKG_DIRECTORY, - C_BUILTIN, - PY_FROZEN, - PY_CODERESOURCE, /* Mac only */ - IMP_HOOK + SEARCH_ERROR, + PY_SOURCE, + PY_COMPILED, + C_EXTENSION, + PY_RESOURCE, /* Mac only */ + PKG_DIRECTORY, + C_BUILTIN, + PY_FROZEN, + PY_CODERESOURCE, /* Mac only */ + IMP_HOOK }; struct filedescr { - char *suffix; - char *mode; - enum filetype type; + char *suffix; + char *mode; + enum filetype type; }; extern struct filedescr * _PyImport_Filetab; extern const struct filedescr _PyImport_DynLoadFiletab[]; extern PyObject *_PyImport_LoadDynamicModule(char *name, char *pathname, - FILE *); + FILE *); /* Max length of module suffix searched for -- accommodates "module.slb" */ #define MAXSUFFIXSIZE 12 Modified: python/branches/release31-maint/Python/makeopcodetargets.py ============================================================================== --- python/branches/release31-maint/Python/makeopcodetargets.py (original) +++ python/branches/release31-maint/Python/makeopcodetargets.py Sun May 9 18:14:21 2010 @@ -28,7 +28,7 @@ continue targets[op] = "TARGET_%s" % opname f.write("static void *opcode_targets[256] = {\n") - f.write(",\n".join(["\t&&%s" % s for s in targets])) + f.write(",\n".join([" &&%s" % s for s in targets])) f.write("\n};\n") Modified: python/branches/release31-maint/Python/marshal.c ============================================================================== --- python/branches/release31-maint/Python/marshal.c (original) +++ python/branches/release31-maint/Python/marshal.c Sun May 9 18:14:21 2010 @@ -24,28 +24,28 @@ #define MAX_MARSHAL_STACK_DEPTH 2000 #endif -#define TYPE_NULL '0' -#define TYPE_NONE 'N' -#define TYPE_FALSE 'F' -#define TYPE_TRUE 'T' -#define TYPE_STOPITER 'S' -#define TYPE_ELLIPSIS '.' -#define TYPE_INT 'i' -#define TYPE_INT64 'I' -#define TYPE_FLOAT 'f' -#define TYPE_BINARY_FLOAT 'g' -#define TYPE_COMPLEX 'x' -#define TYPE_BINARY_COMPLEX 'y' -#define TYPE_LONG 'l' -#define TYPE_STRING 's' -#define TYPE_TUPLE '(' -#define TYPE_LIST '[' -#define TYPE_DICT '{' -#define TYPE_CODE 'c' -#define TYPE_UNICODE 'u' -#define TYPE_UNKNOWN '?' -#define TYPE_SET '<' -#define TYPE_FROZENSET '>' +#define TYPE_NULL '0' +#define TYPE_NONE 'N' +#define TYPE_FALSE 'F' +#define TYPE_TRUE 'T' +#define TYPE_STOPITER 'S' +#define TYPE_ELLIPSIS '.' +#define TYPE_INT 'i' +#define TYPE_INT64 'I' +#define TYPE_FLOAT 'f' +#define TYPE_BINARY_FLOAT 'g' +#define TYPE_COMPLEX 'x' +#define TYPE_BINARY_COMPLEX 'y' +#define TYPE_LONG 'l' +#define TYPE_STRING 's' +#define TYPE_TUPLE '(' +#define TYPE_LIST '[' +#define TYPE_DICT '{' +#define TYPE_CODE 'c' +#define TYPE_UNICODE 'u' +#define TYPE_UNKNOWN '?' +#define TYPE_SET '<' +#define TYPE_FROZENSET '>' #define WFERR_OK 0 #define WFERR_UNMARSHALLABLE 1 @@ -53,79 +53,79 @@ #define WFERR_NOMEMORY 3 typedef struct { - FILE *fp; - int error; /* see WFERR_* values */ - int depth; - /* If fp == NULL, the following are valid: */ - PyObject *str; - char *ptr; - char *end; - PyObject *strings; /* dict on marshal, list on unmarshal */ - int version; + FILE *fp; + int error; /* see WFERR_* values */ + int depth; + /* If fp == NULL, the following are valid: */ + PyObject *str; + char *ptr; + char *end; + PyObject *strings; /* dict on marshal, list on unmarshal */ + int version; } WFILE; #define w_byte(c, p) if (((p)->fp)) putc((c), (p)->fp); \ - else if ((p)->ptr != (p)->end) *(p)->ptr++ = (c); \ - else w_more(c, p) + else if ((p)->ptr != (p)->end) *(p)->ptr++ = (c); \ + else w_more(c, p) static void w_more(int c, WFILE *p) { - Py_ssize_t size, newsize; - if (p->str == NULL) - return; /* An error already occurred */ - size = PyBytes_Size(p->str); - newsize = size + size + 1024; - if (newsize > 32*1024*1024) { - newsize = size + (size >> 3); /* 12.5% overallocation */ - } - if (_PyBytes_Resize(&p->str, newsize) != 0) { - p->ptr = p->end = NULL; - } - else { - p->ptr = PyBytes_AS_STRING((PyBytesObject *)p->str) + size; - p->end = - PyBytes_AS_STRING((PyBytesObject *)p->str) + newsize; - *p->ptr++ = Py_SAFE_DOWNCAST(c, int, char); - } + Py_ssize_t size, newsize; + if (p->str == NULL) + return; /* An error already occurred */ + size = PyBytes_Size(p->str); + newsize = size + size + 1024; + if (newsize > 32*1024*1024) { + newsize = size + (size >> 3); /* 12.5% overallocation */ + } + if (_PyBytes_Resize(&p->str, newsize) != 0) { + p->ptr = p->end = NULL; + } + else { + p->ptr = PyBytes_AS_STRING((PyBytesObject *)p->str) + size; + p->end = + PyBytes_AS_STRING((PyBytesObject *)p->str) + newsize; + *p->ptr++ = Py_SAFE_DOWNCAST(c, int, char); + } } static void w_string(char *s, int n, WFILE *p) { - if (p->fp != NULL) { - fwrite(s, 1, n, p->fp); - } - else { - while (--n >= 0) { - w_byte(*s, p); - s++; - } - } + if (p->fp != NULL) { + fwrite(s, 1, n, p->fp); + } + else { + while (--n >= 0) { + w_byte(*s, p); + s++; + } + } } static void w_short(int x, WFILE *p) { - w_byte((char)( x & 0xff), p); - w_byte((char)((x>> 8) & 0xff), p); + w_byte((char)( x & 0xff), p); + w_byte((char)((x>> 8) & 0xff), p); } static void w_long(long x, WFILE *p) { - w_byte((char)( x & 0xff), p); - w_byte((char)((x>> 8) & 0xff), p); - w_byte((char)((x>>16) & 0xff), p); - w_byte((char)((x>>24) & 0xff), p); + w_byte((char)( x & 0xff), p); + w_byte((char)((x>> 8) & 0xff), p); + w_byte((char)((x>>16) & 0xff), p); + w_byte((char)((x>>24) & 0xff), p); } #if SIZEOF_LONG > 4 static void w_long64(long x, WFILE *p) { - w_long(x, p); - w_long(x>>32, p); + w_long(x, p); + w_long(x>>32, p); } #endif @@ -144,324 +144,324 @@ static void w_PyLong(const PyLongObject *ob, WFILE *p) { - Py_ssize_t i, j, n, l; - digit d; + Py_ssize_t i, j, n, l; + digit d; - w_byte(TYPE_LONG, p); - if (Py_SIZE(ob) == 0) { - w_long((long)0, p); - return; - } - - /* set l to number of base PyLong_MARSHAL_BASE digits */ - n = ABS(Py_SIZE(ob)); - l = (n-1) * PyLong_MARSHAL_RATIO; - d = ob->ob_digit[n-1]; - assert(d != 0); /* a PyLong is always normalized */ - do { - d >>= PyLong_MARSHAL_SHIFT; - l++; - } while (d != 0); - w_long((long)(Py_SIZE(ob) > 0 ? l : -l), p); - - for (i=0; i < n-1; i++) { - d = ob->ob_digit[i]; - for (j=0; j < PyLong_MARSHAL_RATIO; j++) { - w_short(d & PyLong_MARSHAL_MASK, p); - d >>= PyLong_MARSHAL_SHIFT; - } - assert (d == 0); - } - d = ob->ob_digit[n-1]; - do { - w_short(d & PyLong_MARSHAL_MASK, p); - d >>= PyLong_MARSHAL_SHIFT; - } while (d != 0); + w_byte(TYPE_LONG, p); + if (Py_SIZE(ob) == 0) { + w_long((long)0, p); + return; + } + + /* set l to number of base PyLong_MARSHAL_BASE digits */ + n = ABS(Py_SIZE(ob)); + l = (n-1) * PyLong_MARSHAL_RATIO; + d = ob->ob_digit[n-1]; + assert(d != 0); /* a PyLong is always normalized */ + do { + d >>= PyLong_MARSHAL_SHIFT; + l++; + } while (d != 0); + w_long((long)(Py_SIZE(ob) > 0 ? l : -l), p); + + for (i=0; i < n-1; i++) { + d = ob->ob_digit[i]; + for (j=0; j < PyLong_MARSHAL_RATIO; j++) { + w_short(d & PyLong_MARSHAL_MASK, p); + d >>= PyLong_MARSHAL_SHIFT; + } + assert (d == 0); + } + d = ob->ob_digit[n-1]; + do { + w_short(d & PyLong_MARSHAL_MASK, p); + d >>= PyLong_MARSHAL_SHIFT; + } while (d != 0); } static void w_object(PyObject *v, WFILE *p) { - Py_ssize_t i, n; + Py_ssize_t i, n; - p->depth++; + p->depth++; - if (p->depth > MAX_MARSHAL_STACK_DEPTH) { - p->error = WFERR_NESTEDTOODEEP; - } - else if (v == NULL) { - w_byte(TYPE_NULL, p); - } - else if (v == Py_None) { - w_byte(TYPE_NONE, p); - } - else if (v == PyExc_StopIteration) { - w_byte(TYPE_STOPITER, p); - } - else if (v == Py_Ellipsis) { - w_byte(TYPE_ELLIPSIS, p); - } - else if (v == Py_False) { - w_byte(TYPE_FALSE, p); - } - else if (v == Py_True) { - w_byte(TYPE_TRUE, p); - } - else if (PyLong_CheckExact(v)) { - long x = PyLong_AsLong(v); - if ((x == -1) && PyErr_Occurred()) { - PyLongObject *ob = (PyLongObject *)v; - PyErr_Clear(); - w_PyLong(ob, p); - } - else { + if (p->depth > MAX_MARSHAL_STACK_DEPTH) { + p->error = WFERR_NESTEDTOODEEP; + } + else if (v == NULL) { + w_byte(TYPE_NULL, p); + } + else if (v == Py_None) { + w_byte(TYPE_NONE, p); + } + else if (v == PyExc_StopIteration) { + w_byte(TYPE_STOPITER, p); + } + else if (v == Py_Ellipsis) { + w_byte(TYPE_ELLIPSIS, p); + } + else if (v == Py_False) { + w_byte(TYPE_FALSE, p); + } + else if (v == Py_True) { + w_byte(TYPE_TRUE, p); + } + else if (PyLong_CheckExact(v)) { + long x = PyLong_AsLong(v); + if ((x == -1) && PyErr_Occurred()) { + PyLongObject *ob = (PyLongObject *)v; + PyErr_Clear(); + w_PyLong(ob, p); + } + else { #if SIZEOF_LONG > 4 - long y = Py_ARITHMETIC_RIGHT_SHIFT(long, x, 31); - if (y && y != -1) { - w_byte(TYPE_INT64, p); - w_long64(x, p); - } - else + long y = Py_ARITHMETIC_RIGHT_SHIFT(long, x, 31); + if (y && y != -1) { + w_byte(TYPE_INT64, p); + w_long64(x, p); + } + else #endif - { - w_byte(TYPE_INT, p); - w_long(x, p); - } - } - } - else if (PyFloat_CheckExact(v)) { - if (p->version > 1) { - unsigned char buf[8]; - if (_PyFloat_Pack8(PyFloat_AsDouble(v), - buf, 1) < 0) { - p->error = WFERR_UNMARSHALLABLE; - return; - } - w_byte(TYPE_BINARY_FLOAT, p); - w_string((char*)buf, 8, p); - } - else { - char *buf = PyOS_double_to_string(PyFloat_AS_DOUBLE(v), - 'g', 17, 0, NULL); - if (!buf) { - p->error = WFERR_NOMEMORY; - return; - } - n = strlen(buf); - w_byte(TYPE_FLOAT, p); - w_byte((int)n, p); - w_string(buf, (int)n, p); - PyMem_Free(buf); - } - } + { + w_byte(TYPE_INT, p); + w_long(x, p); + } + } + } + else if (PyFloat_CheckExact(v)) { + if (p->version > 1) { + unsigned char buf[8]; + if (_PyFloat_Pack8(PyFloat_AsDouble(v), + buf, 1) < 0) { + p->error = WFERR_UNMARSHALLABLE; + return; + } + w_byte(TYPE_BINARY_FLOAT, p); + w_string((char*)buf, 8, p); + } + else { + char *buf = PyOS_double_to_string(PyFloat_AS_DOUBLE(v), + 'g', 17, 0, NULL); + if (!buf) { + p->error = WFERR_NOMEMORY; + return; + } + n = strlen(buf); + w_byte(TYPE_FLOAT, p); + w_byte((int)n, p); + w_string(buf, (int)n, p); + PyMem_Free(buf); + } + } #ifndef WITHOUT_COMPLEX - else if (PyComplex_CheckExact(v)) { - if (p->version > 1) { - unsigned char buf[8]; - if (_PyFloat_Pack8(PyComplex_RealAsDouble(v), - buf, 1) < 0) { - p->error = WFERR_UNMARSHALLABLE; - return; - } - w_byte(TYPE_BINARY_COMPLEX, p); - w_string((char*)buf, 8, p); - if (_PyFloat_Pack8(PyComplex_ImagAsDouble(v), - buf, 1) < 0) { - p->error = WFERR_UNMARSHALLABLE; - return; - } - w_string((char*)buf, 8, p); - } - else { - char *buf; - w_byte(TYPE_COMPLEX, p); - buf = PyOS_double_to_string(PyComplex_RealAsDouble(v), - 'g', 17, 0, NULL); - if (!buf) { - p->error = WFERR_NOMEMORY; - return; - } - n = strlen(buf); - w_byte((int)n, p); - w_string(buf, (int)n, p); - PyMem_Free(buf); - buf = PyOS_double_to_string(PyComplex_ImagAsDouble(v), - 'g', 17, 0, NULL); - if (!buf) { - p->error = WFERR_NOMEMORY; - return; - } - n = strlen(buf); - w_byte((int)n, p); - w_string(buf, (int)n, p); - PyMem_Free(buf); - } - } + else if (PyComplex_CheckExact(v)) { + if (p->version > 1) { + unsigned char buf[8]; + if (_PyFloat_Pack8(PyComplex_RealAsDouble(v), + buf, 1) < 0) { + p->error = WFERR_UNMARSHALLABLE; + return; + } + w_byte(TYPE_BINARY_COMPLEX, p); + w_string((char*)buf, 8, p); + if (_PyFloat_Pack8(PyComplex_ImagAsDouble(v), + buf, 1) < 0) { + p->error = WFERR_UNMARSHALLABLE; + return; + } + w_string((char*)buf, 8, p); + } + else { + char *buf; + w_byte(TYPE_COMPLEX, p); + buf = PyOS_double_to_string(PyComplex_RealAsDouble(v), + 'g', 17, 0, NULL); + if (!buf) { + p->error = WFERR_NOMEMORY; + return; + } + n = strlen(buf); + w_byte((int)n, p); + w_string(buf, (int)n, p); + PyMem_Free(buf); + buf = PyOS_double_to_string(PyComplex_ImagAsDouble(v), + 'g', 17, 0, NULL); + if (!buf) { + p->error = WFERR_NOMEMORY; + return; + } + n = strlen(buf); + w_byte((int)n, p); + w_string(buf, (int)n, p); + PyMem_Free(buf); + } + } #endif - else if (PyBytes_CheckExact(v)) { - w_byte(TYPE_STRING, p); - n = PyBytes_GET_SIZE(v); - if (n > INT_MAX) { - /* huge strings are not supported */ - p->depth--; - p->error = WFERR_UNMARSHALLABLE; - return; - } - w_long((long)n, p); - w_string(PyBytes_AS_STRING(v), (int)n, p); - } - else if (PyUnicode_CheckExact(v)) { - PyObject *utf8; - utf8 = PyUnicode_EncodeUTF8(PyUnicode_AS_UNICODE(v), - PyUnicode_GET_SIZE(v), - "surrogatepass"); - if (utf8 == NULL) { - p->depth--; - p->error = WFERR_UNMARSHALLABLE; - return; - } - w_byte(TYPE_UNICODE, p); - n = PyBytes_GET_SIZE(utf8); - if (n > INT_MAX) { - p->depth--; - p->error = WFERR_UNMARSHALLABLE; - return; - } - w_long((long)n, p); - w_string(PyBytes_AS_STRING(utf8), (int)n, p); - Py_DECREF(utf8); - } - else if (PyTuple_CheckExact(v)) { - w_byte(TYPE_TUPLE, p); - n = PyTuple_Size(v); - w_long((long)n, p); - for (i = 0; i < n; i++) { - w_object(PyTuple_GET_ITEM(v, i), p); - } - } - else if (PyList_CheckExact(v)) { - w_byte(TYPE_LIST, p); - n = PyList_GET_SIZE(v); - w_long((long)n, p); - for (i = 0; i < n; i++) { - w_object(PyList_GET_ITEM(v, i), p); - } - } - else if (PyDict_CheckExact(v)) { - Py_ssize_t pos; - PyObject *key, *value; - w_byte(TYPE_DICT, p); - /* This one is NULL object terminated! */ - pos = 0; - while (PyDict_Next(v, &pos, &key, &value)) { - w_object(key, p); - w_object(value, p); - } - w_object((PyObject *)NULL, p); - } - else if (PyAnySet_CheckExact(v)) { - PyObject *value, *it; - - if (PyObject_TypeCheck(v, &PySet_Type)) - w_byte(TYPE_SET, p); - else - w_byte(TYPE_FROZENSET, p); - n = PyObject_Size(v); - if (n == -1) { - p->depth--; - p->error = WFERR_UNMARSHALLABLE; - return; - } - w_long((long)n, p); - it = PyObject_GetIter(v); - if (it == NULL) { - p->depth--; - p->error = WFERR_UNMARSHALLABLE; - return; - } - while ((value = PyIter_Next(it)) != NULL) { - w_object(value, p); - Py_DECREF(value); - } - Py_DECREF(it); - if (PyErr_Occurred()) { - p->depth--; - p->error = WFERR_UNMARSHALLABLE; - return; - } - } - else if (PyCode_Check(v)) { - PyCodeObject *co = (PyCodeObject *)v; - w_byte(TYPE_CODE, p); - w_long(co->co_argcount, p); - w_long(co->co_kwonlyargcount, p); - w_long(co->co_nlocals, p); - w_long(co->co_stacksize, p); - w_long(co->co_flags, p); - w_object(co->co_code, p); - w_object(co->co_consts, p); - w_object(co->co_names, p); - w_object(co->co_varnames, p); - w_object(co->co_freevars, p); - w_object(co->co_cellvars, p); - w_object(co->co_filename, p); - w_object(co->co_name, p); - w_long(co->co_firstlineno, p); - w_object(co->co_lnotab, p); - } - else if (PyObject_CheckBuffer(v)) { - /* Write unknown buffer-style objects as a string */ - char *s; - PyBufferProcs *pb = v->ob_type->tp_as_buffer; - Py_buffer view; - if ((*pb->bf_getbuffer)(v, &view, PyBUF_SIMPLE) != 0) { - w_byte(TYPE_UNKNOWN, p); - p->error = WFERR_UNMARSHALLABLE; - } - w_byte(TYPE_STRING, p); - n = view.len; - s = view.buf; - if (n > INT_MAX) { - p->depth--; - p->error = WFERR_UNMARSHALLABLE; - return; - } - w_long((long)n, p); - w_string(s, (int)n, p); - if (pb->bf_releasebuffer != NULL) - (*pb->bf_releasebuffer)(v, &view); - } - else { - w_byte(TYPE_UNKNOWN, p); - p->error = WFERR_UNMARSHALLABLE; - } - p->depth--; + else if (PyBytes_CheckExact(v)) { + w_byte(TYPE_STRING, p); + n = PyBytes_GET_SIZE(v); + if (n > INT_MAX) { + /* huge strings are not supported */ + p->depth--; + p->error = WFERR_UNMARSHALLABLE; + return; + } + w_long((long)n, p); + w_string(PyBytes_AS_STRING(v), (int)n, p); + } + else if (PyUnicode_CheckExact(v)) { + PyObject *utf8; + utf8 = PyUnicode_EncodeUTF8(PyUnicode_AS_UNICODE(v), + PyUnicode_GET_SIZE(v), + "surrogatepass"); + if (utf8 == NULL) { + p->depth--; + p->error = WFERR_UNMARSHALLABLE; + return; + } + w_byte(TYPE_UNICODE, p); + n = PyBytes_GET_SIZE(utf8); + if (n > INT_MAX) { + p->depth--; + p->error = WFERR_UNMARSHALLABLE; + return; + } + w_long((long)n, p); + w_string(PyBytes_AS_STRING(utf8), (int)n, p); + Py_DECREF(utf8); + } + else if (PyTuple_CheckExact(v)) { + w_byte(TYPE_TUPLE, p); + n = PyTuple_Size(v); + w_long((long)n, p); + for (i = 0; i < n; i++) { + w_object(PyTuple_GET_ITEM(v, i), p); + } + } + else if (PyList_CheckExact(v)) { + w_byte(TYPE_LIST, p); + n = PyList_GET_SIZE(v); + w_long((long)n, p); + for (i = 0; i < n; i++) { + w_object(PyList_GET_ITEM(v, i), p); + } + } + else if (PyDict_CheckExact(v)) { + Py_ssize_t pos; + PyObject *key, *value; + w_byte(TYPE_DICT, p); + /* This one is NULL object terminated! */ + pos = 0; + while (PyDict_Next(v, &pos, &key, &value)) { + w_object(key, p); + w_object(value, p); + } + w_object((PyObject *)NULL, p); + } + else if (PyAnySet_CheckExact(v)) { + PyObject *value, *it; + + if (PyObject_TypeCheck(v, &PySet_Type)) + w_byte(TYPE_SET, p); + else + w_byte(TYPE_FROZENSET, p); + n = PyObject_Size(v); + if (n == -1) { + p->depth--; + p->error = WFERR_UNMARSHALLABLE; + return; + } + w_long((long)n, p); + it = PyObject_GetIter(v); + if (it == NULL) { + p->depth--; + p->error = WFERR_UNMARSHALLABLE; + return; + } + while ((value = PyIter_Next(it)) != NULL) { + w_object(value, p); + Py_DECREF(value); + } + Py_DECREF(it); + if (PyErr_Occurred()) { + p->depth--; + p->error = WFERR_UNMARSHALLABLE; + return; + } + } + else if (PyCode_Check(v)) { + PyCodeObject *co = (PyCodeObject *)v; + w_byte(TYPE_CODE, p); + w_long(co->co_argcount, p); + w_long(co->co_kwonlyargcount, p); + w_long(co->co_nlocals, p); + w_long(co->co_stacksize, p); + w_long(co->co_flags, p); + w_object(co->co_code, p); + w_object(co->co_consts, p); + w_object(co->co_names, p); + w_object(co->co_varnames, p); + w_object(co->co_freevars, p); + w_object(co->co_cellvars, p); + w_object(co->co_filename, p); + w_object(co->co_name, p); + w_long(co->co_firstlineno, p); + w_object(co->co_lnotab, p); + } + else if (PyObject_CheckBuffer(v)) { + /* Write unknown buffer-style objects as a string */ + char *s; + PyBufferProcs *pb = v->ob_type->tp_as_buffer; + Py_buffer view; + if ((*pb->bf_getbuffer)(v, &view, PyBUF_SIMPLE) != 0) { + w_byte(TYPE_UNKNOWN, p); + p->error = WFERR_UNMARSHALLABLE; + } + w_byte(TYPE_STRING, p); + n = view.len; + s = view.buf; + if (n > INT_MAX) { + p->depth--; + p->error = WFERR_UNMARSHALLABLE; + return; + } + w_long((long)n, p); + w_string(s, (int)n, p); + if (pb->bf_releasebuffer != NULL) + (*pb->bf_releasebuffer)(v, &view); + } + else { + w_byte(TYPE_UNKNOWN, p); + p->error = WFERR_UNMARSHALLABLE; + } + p->depth--; } /* version currently has no effect for writing longs. */ void PyMarshal_WriteLongToFile(long x, FILE *fp, int version) { - WFILE wf; - wf.fp = fp; - wf.error = WFERR_OK; - wf.depth = 0; - wf.strings = NULL; - wf.version = version; - w_long(x, &wf); + WFILE wf; + wf.fp = fp; + wf.error = WFERR_OK; + wf.depth = 0; + wf.strings = NULL; + wf.version = version; + w_long(x, &wf); } void PyMarshal_WriteObjectToFile(PyObject *x, FILE *fp, int version) { - WFILE wf; - wf.fp = fp; - wf.error = WFERR_OK; - wf.depth = 0; - wf.strings = (version > 0) ? PyDict_New() : NULL; - wf.version = version; - w_object(x, &wf); - Py_XDECREF(wf.strings); + WFILE wf; + wf.fp = fp; + wf.error = WFERR_OK; + wf.depth = 0; + wf.strings = (version > 0) ? PyDict_New() : NULL; + wf.version = version; + w_object(x, &wf); + Py_XDECREF(wf.strings); } typedef WFILE RFILE; /* Same struct with different invariants */ @@ -473,49 +473,49 @@ static int r_string(char *s, int n, RFILE *p) { - if (p->fp != NULL) - /* The result fits into int because it must be <=n. */ - return (int)fread(s, 1, n, p->fp); - if (p->end - p->ptr < n) - n = (int)(p->end - p->ptr); - memcpy(s, p->ptr, n); - p->ptr += n; - return n; + if (p->fp != NULL) + /* The result fits into int because it must be <=n. */ + return (int)fread(s, 1, n, p->fp); + if (p->end - p->ptr < n) + n = (int)(p->end - p->ptr); + memcpy(s, p->ptr, n); + p->ptr += n; + return n; } static int r_short(RFILE *p) { - register short x; - x = r_byte(p); - x |= r_byte(p) << 8; - /* Sign-extension, in case short greater than 16 bits */ - x |= -(x & 0x8000); - return x; + register short x; + x = r_byte(p); + x |= r_byte(p) << 8; + /* Sign-extension, in case short greater than 16 bits */ + x |= -(x & 0x8000); + return x; } static long r_long(RFILE *p) { - register long x; - register FILE *fp = p->fp; - if (fp) { - x = getc(fp); - x |= (long)getc(fp) << 8; - x |= (long)getc(fp) << 16; - x |= (long)getc(fp) << 24; - } - else { - x = rs_byte(p); - x |= (long)rs_byte(p) << 8; - x |= (long)rs_byte(p) << 16; - x |= (long)rs_byte(p) << 24; - } + register long x; + register FILE *fp = p->fp; + if (fp) { + x = getc(fp); + x |= (long)getc(fp) << 8; + x |= (long)getc(fp) << 16; + x |= (long)getc(fp) << 24; + } + else { + x = rs_byte(p); + x |= (long)rs_byte(p) << 8; + x |= (long)rs_byte(p) << 16; + x |= (long)rs_byte(p) << 24; + } #if SIZEOF_LONG > 4 - /* Sign extension for 64-bit machines */ - x |= -(x & 0x80000000L); + /* Sign extension for 64-bit machines */ + x |= -(x & 0x80000000L); #endif - return x; + return x; } /* r_long64 deals with the TYPE_INT64 code. On a machine with @@ -528,536 +528,536 @@ static PyObject * r_long64(RFILE *p) { - long lo4 = r_long(p); - long hi4 = r_long(p); + long lo4 = r_long(p); + long hi4 = r_long(p); #if SIZEOF_LONG > 4 - long x = (hi4 << 32) | (lo4 & 0xFFFFFFFFL); - return PyLong_FromLong(x); + long x = (hi4 << 32) | (lo4 & 0xFFFFFFFFL); + return PyLong_FromLong(x); #else - unsigned char buf[8]; - int one = 1; - int is_little_endian = (int)*(char*)&one; - if (is_little_endian) { - memcpy(buf, &lo4, 4); - memcpy(buf+4, &hi4, 4); - } - else { - memcpy(buf, &hi4, 4); - memcpy(buf+4, &lo4, 4); - } - return _PyLong_FromByteArray(buf, 8, is_little_endian, 1); + unsigned char buf[8]; + int one = 1; + int is_little_endian = (int)*(char*)&one; + if (is_little_endian) { + memcpy(buf, &lo4, 4); + memcpy(buf+4, &hi4, 4); + } + else { + memcpy(buf, &hi4, 4); + memcpy(buf+4, &lo4, 4); + } + return _PyLong_FromByteArray(buf, 8, is_little_endian, 1); #endif } static PyObject * r_PyLong(RFILE *p) { - PyLongObject *ob; - int size, i, j, md, shorts_in_top_digit; - long n; - digit d; - - n = r_long(p); - if (n == 0) - return (PyObject *)_PyLong_New(0); - if (n < -INT_MAX || n > INT_MAX) { - PyErr_SetString(PyExc_ValueError, - "bad marshal data (long size out of range)"); - return NULL; - } - - size = 1 + (ABS(n) - 1) / PyLong_MARSHAL_RATIO; - shorts_in_top_digit = 1 + (ABS(n) - 1) % PyLong_MARSHAL_RATIO; - ob = _PyLong_New(size); - if (ob == NULL) - return NULL; - Py_SIZE(ob) = n > 0 ? size : -size; - - for (i = 0; i < size-1; i++) { - d = 0; - for (j=0; j < PyLong_MARSHAL_RATIO; j++) { - md = r_short(p); - if (md < 0 || md > PyLong_MARSHAL_BASE) - goto bad_digit; - d += (digit)md << j*PyLong_MARSHAL_SHIFT; - } - ob->ob_digit[i] = d; - } - d = 0; - for (j=0; j < shorts_in_top_digit; j++) { - md = r_short(p); - if (md < 0 || md > PyLong_MARSHAL_BASE) - goto bad_digit; - /* topmost marshal digit should be nonzero */ - if (md == 0 && j == shorts_in_top_digit - 1) { - Py_DECREF(ob); - PyErr_SetString(PyExc_ValueError, - "bad marshal data (unnormalized long data)"); - return NULL; - } - d += (digit)md << j*PyLong_MARSHAL_SHIFT; - } - /* top digit should be nonzero, else the resulting PyLong won't be - normalized */ - ob->ob_digit[size-1] = d; - return (PyObject *)ob; + PyLongObject *ob; + int size, i, j, md, shorts_in_top_digit; + long n; + digit d; + + n = r_long(p); + if (n == 0) + return (PyObject *)_PyLong_New(0); + if (n < -INT_MAX || n > INT_MAX) { + PyErr_SetString(PyExc_ValueError, + "bad marshal data (long size out of range)"); + return NULL; + } + + size = 1 + (ABS(n) - 1) / PyLong_MARSHAL_RATIO; + shorts_in_top_digit = 1 + (ABS(n) - 1) % PyLong_MARSHAL_RATIO; + ob = _PyLong_New(size); + if (ob == NULL) + return NULL; + Py_SIZE(ob) = n > 0 ? size : -size; + + for (i = 0; i < size-1; i++) { + d = 0; + for (j=0; j < PyLong_MARSHAL_RATIO; j++) { + md = r_short(p); + if (md < 0 || md > PyLong_MARSHAL_BASE) + goto bad_digit; + d += (digit)md << j*PyLong_MARSHAL_SHIFT; + } + ob->ob_digit[i] = d; + } + d = 0; + for (j=0; j < shorts_in_top_digit; j++) { + md = r_short(p); + if (md < 0 || md > PyLong_MARSHAL_BASE) + goto bad_digit; + /* topmost marshal digit should be nonzero */ + if (md == 0 && j == shorts_in_top_digit - 1) { + Py_DECREF(ob); + PyErr_SetString(PyExc_ValueError, + "bad marshal data (unnormalized long data)"); + return NULL; + } + d += (digit)md << j*PyLong_MARSHAL_SHIFT; + } + /* top digit should be nonzero, else the resulting PyLong won't be + normalized */ + ob->ob_digit[size-1] = d; + return (PyObject *)ob; bad_digit: - Py_DECREF(ob); - PyErr_SetString(PyExc_ValueError, - "bad marshal data (digit out of range in long)"); - return NULL; + Py_DECREF(ob); + PyErr_SetString(PyExc_ValueError, + "bad marshal data (digit out of range in long)"); + return NULL; } static PyObject * r_object(RFILE *p) { - /* NULL is a valid return value, it does not necessarily means that - an exception is set. */ - PyObject *v, *v2; - long i, n; - int type = r_byte(p); - PyObject *retval; - - p->depth++; - - if (p->depth > MAX_MARSHAL_STACK_DEPTH) { - p->depth--; - PyErr_SetString(PyExc_ValueError, "recursion limit exceeded"); - return NULL; - } - - switch (type) { - - case EOF: - PyErr_SetString(PyExc_EOFError, - "EOF read where object expected"); - retval = NULL; - break; - - case TYPE_NULL: - retval = NULL; - break; - - case TYPE_NONE: - Py_INCREF(Py_None); - retval = Py_None; - break; - - case TYPE_STOPITER: - Py_INCREF(PyExc_StopIteration); - retval = PyExc_StopIteration; - break; - - case TYPE_ELLIPSIS: - Py_INCREF(Py_Ellipsis); - retval = Py_Ellipsis; - break; - - case TYPE_FALSE: - Py_INCREF(Py_False); - retval = Py_False; - break; - - case TYPE_TRUE: - Py_INCREF(Py_True); - retval = Py_True; - break; - - case TYPE_INT: - retval = PyLong_FromLong(r_long(p)); - break; - - case TYPE_INT64: - retval = r_long64(p); - break; - - case TYPE_LONG: - retval = r_PyLong(p); - break; - - case TYPE_FLOAT: - { - char buf[256]; - double dx; - retval = NULL; - n = r_byte(p); - if (n == EOF || r_string(buf, (int)n, p) != n) { - PyErr_SetString(PyExc_EOFError, - "EOF read where object expected"); - break; - } - buf[n] = '\0'; - dx = PyOS_string_to_double(buf, NULL, NULL); - if (dx == -1.0 && PyErr_Occurred()) - break; - retval = PyFloat_FromDouble(dx); - break; - } - - case TYPE_BINARY_FLOAT: - { - unsigned char buf[8]; - double x; - if (r_string((char*)buf, 8, p) != 8) { - PyErr_SetString(PyExc_EOFError, - "EOF read where object expected"); - retval = NULL; - break; - } - x = _PyFloat_Unpack8(buf, 1); - if (x == -1.0 && PyErr_Occurred()) { - retval = NULL; - break; - } - retval = PyFloat_FromDouble(x); - break; - } + /* NULL is a valid return value, it does not necessarily means that + an exception is set. */ + PyObject *v, *v2; + long i, n; + int type = r_byte(p); + PyObject *retval; + + p->depth++; + + if (p->depth > MAX_MARSHAL_STACK_DEPTH) { + p->depth--; + PyErr_SetString(PyExc_ValueError, "recursion limit exceeded"); + return NULL; + } + + switch (type) { + + case EOF: + PyErr_SetString(PyExc_EOFError, + "EOF read where object expected"); + retval = NULL; + break; + + case TYPE_NULL: + retval = NULL; + break; + + case TYPE_NONE: + Py_INCREF(Py_None); + retval = Py_None; + break; + + case TYPE_STOPITER: + Py_INCREF(PyExc_StopIteration); + retval = PyExc_StopIteration; + break; + + case TYPE_ELLIPSIS: + Py_INCREF(Py_Ellipsis); + retval = Py_Ellipsis; + break; + + case TYPE_FALSE: + Py_INCREF(Py_False); + retval = Py_False; + break; + + case TYPE_TRUE: + Py_INCREF(Py_True); + retval = Py_True; + break; + + case TYPE_INT: + retval = PyLong_FromLong(r_long(p)); + break; + + case TYPE_INT64: + retval = r_long64(p); + break; + + case TYPE_LONG: + retval = r_PyLong(p); + break; + + case TYPE_FLOAT: + { + char buf[256]; + double dx; + retval = NULL; + n = r_byte(p); + if (n == EOF || r_string(buf, (int)n, p) != n) { + PyErr_SetString(PyExc_EOFError, + "EOF read where object expected"); + break; + } + buf[n] = '\0'; + dx = PyOS_string_to_double(buf, NULL, NULL); + if (dx == -1.0 && PyErr_Occurred()) + break; + retval = PyFloat_FromDouble(dx); + break; + } + + case TYPE_BINARY_FLOAT: + { + unsigned char buf[8]; + double x; + if (r_string((char*)buf, 8, p) != 8) { + PyErr_SetString(PyExc_EOFError, + "EOF read where object expected"); + retval = NULL; + break; + } + x = _PyFloat_Unpack8(buf, 1); + if (x == -1.0 && PyErr_Occurred()) { + retval = NULL; + break; + } + retval = PyFloat_FromDouble(x); + break; + } #ifndef WITHOUT_COMPLEX - case TYPE_COMPLEX: - { - char buf[256]; - Py_complex c; - retval = NULL; - n = r_byte(p); - if (n == EOF || r_string(buf, (int)n, p) != n) { - PyErr_SetString(PyExc_EOFError, - "EOF read where object expected"); - break; - } - buf[n] = '\0'; - c.real = PyOS_string_to_double(buf, NULL, NULL); - if (c.real == -1.0 && PyErr_Occurred()) - break; - n = r_byte(p); - if (n == EOF || r_string(buf, (int)n, p) != n) { - PyErr_SetString(PyExc_EOFError, - "EOF read where object expected"); - break; - } - buf[n] = '\0'; - c.imag = PyOS_string_to_double(buf, NULL, NULL); - if (c.imag == -1.0 && PyErr_Occurred()) - break; - retval = PyComplex_FromCComplex(c); - break; - } - - case TYPE_BINARY_COMPLEX: - { - unsigned char buf[8]; - Py_complex c; - if (r_string((char*)buf, 8, p) != 8) { - PyErr_SetString(PyExc_EOFError, - "EOF read where object expected"); - retval = NULL; - break; - } - c.real = _PyFloat_Unpack8(buf, 1); - if (c.real == -1.0 && PyErr_Occurred()) { - retval = NULL; - break; - } - if (r_string((char*)buf, 8, p) != 8) { - PyErr_SetString(PyExc_EOFError, - "EOF read where object expected"); - retval = NULL; - break; - } - c.imag = _PyFloat_Unpack8(buf, 1); - if (c.imag == -1.0 && PyErr_Occurred()) { - retval = NULL; - break; - } - retval = PyComplex_FromCComplex(c); - break; - } + case TYPE_COMPLEX: + { + char buf[256]; + Py_complex c; + retval = NULL; + n = r_byte(p); + if (n == EOF || r_string(buf, (int)n, p) != n) { + PyErr_SetString(PyExc_EOFError, + "EOF read where object expected"); + break; + } + buf[n] = '\0'; + c.real = PyOS_string_to_double(buf, NULL, NULL); + if (c.real == -1.0 && PyErr_Occurred()) + break; + n = r_byte(p); + if (n == EOF || r_string(buf, (int)n, p) != n) { + PyErr_SetString(PyExc_EOFError, + "EOF read where object expected"); + break; + } + buf[n] = '\0'; + c.imag = PyOS_string_to_double(buf, NULL, NULL); + if (c.imag == -1.0 && PyErr_Occurred()) + break; + retval = PyComplex_FromCComplex(c); + break; + } + + case TYPE_BINARY_COMPLEX: + { + unsigned char buf[8]; + Py_complex c; + if (r_string((char*)buf, 8, p) != 8) { + PyErr_SetString(PyExc_EOFError, + "EOF read where object expected"); + retval = NULL; + break; + } + c.real = _PyFloat_Unpack8(buf, 1); + if (c.real == -1.0 && PyErr_Occurred()) { + retval = NULL; + break; + } + if (r_string((char*)buf, 8, p) != 8) { + PyErr_SetString(PyExc_EOFError, + "EOF read where object expected"); + retval = NULL; + break; + } + c.imag = _PyFloat_Unpack8(buf, 1); + if (c.imag == -1.0 && PyErr_Occurred()) { + retval = NULL; + break; + } + retval = PyComplex_FromCComplex(c); + break; + } #endif - case TYPE_STRING: - n = r_long(p); - if (n < 0 || n > INT_MAX) { - PyErr_SetString(PyExc_ValueError, "bad marshal data (string size out of range)"); - retval = NULL; - break; - } - v = PyBytes_FromStringAndSize((char *)NULL, n); - if (v == NULL) { - retval = NULL; - break; - } - if (r_string(PyBytes_AS_STRING(v), (int)n, p) != n) { - Py_DECREF(v); - PyErr_SetString(PyExc_EOFError, - "EOF read where object expected"); - retval = NULL; - break; - } - retval = v; - break; - - case TYPE_UNICODE: - { - char *buffer; - - n = r_long(p); - if (n < 0 || n > INT_MAX) { - PyErr_SetString(PyExc_ValueError, "bad marshal data (unicode size out of range)"); - retval = NULL; - break; - } - buffer = PyMem_NEW(char, n); - if (buffer == NULL) { - retval = PyErr_NoMemory(); - break; - } - if (r_string(buffer, (int)n, p) != n) { - PyMem_DEL(buffer); - PyErr_SetString(PyExc_EOFError, - "EOF read where object expected"); - retval = NULL; - break; - } - v = PyUnicode_DecodeUTF8(buffer, n, "surrogatepass"); - PyMem_DEL(buffer); - retval = v; - break; - } - - case TYPE_TUPLE: - n = r_long(p); - if (n < 0 || n > INT_MAX) { - PyErr_SetString(PyExc_ValueError, "bad marshal data (tuple size out of range)"); - retval = NULL; - break; - } - v = PyTuple_New((int)n); - if (v == NULL) { - retval = NULL; - break; - } - for (i = 0; i < n; i++) { - v2 = r_object(p); - if ( v2 == NULL ) { - if (!PyErr_Occurred()) - PyErr_SetString(PyExc_TypeError, - "NULL object in marshal data for tuple"); - Py_DECREF(v); - v = NULL; - break; - } - PyTuple_SET_ITEM(v, (int)i, v2); - } - retval = v; - break; - - case TYPE_LIST: - n = r_long(p); - if (n < 0 || n > INT_MAX) { - PyErr_SetString(PyExc_ValueError, "bad marshal data (list size out of range)"); - retval = NULL; - break; - } - v = PyList_New((int)n); - if (v == NULL) { - retval = NULL; - break; - } - for (i = 0; i < n; i++) { - v2 = r_object(p); - if ( v2 == NULL ) { - if (!PyErr_Occurred()) - PyErr_SetString(PyExc_TypeError, - "NULL object in marshal data for list"); - Py_DECREF(v); - v = NULL; - break; - } - PyList_SET_ITEM(v, (int)i, v2); - } - retval = v; - break; - - case TYPE_DICT: - v = PyDict_New(); - if (v == NULL) { - retval = NULL; - break; - } - for (;;) { - PyObject *key, *val; - key = r_object(p); - if (key == NULL) - break; - val = r_object(p); - if (val != NULL) - PyDict_SetItem(v, key, val); - Py_DECREF(key); - Py_XDECREF(val); - } - if (PyErr_Occurred()) { - Py_DECREF(v); - v = NULL; - } - retval = v; - break; - - case TYPE_SET: - case TYPE_FROZENSET: - n = r_long(p); - if (n < 0 || n > INT_MAX) { - PyErr_SetString(PyExc_ValueError, "bad marshal data (set size out of range)"); - retval = NULL; - break; - } - v = (type == TYPE_SET) ? PySet_New(NULL) : PyFrozenSet_New(NULL); - if (v == NULL) { - retval = NULL; - break; - } - for (i = 0; i < n; i++) { - v2 = r_object(p); - if ( v2 == NULL ) { - if (!PyErr_Occurred()) - PyErr_SetString(PyExc_TypeError, - "NULL object in marshal data for set"); - Py_DECREF(v); - v = NULL; - break; - } - if (PySet_Add(v, v2) == -1) { - Py_DECREF(v); - Py_DECREF(v2); - v = NULL; - break; - } - Py_DECREF(v2); - } - retval = v; - break; - - case TYPE_CODE: - { - int argcount; - int kwonlyargcount; - int nlocals; - int stacksize; - int flags; - PyObject *code = NULL; - PyObject *consts = NULL; - PyObject *names = NULL; - PyObject *varnames = NULL; - PyObject *freevars = NULL; - PyObject *cellvars = NULL; - PyObject *filename = NULL; - PyObject *name = NULL; - int firstlineno; - PyObject *lnotab = NULL; - - v = NULL; - - /* XXX ignore long->int overflows for now */ - argcount = (int)r_long(p); - kwonlyargcount = (int)r_long(p); - nlocals = (int)r_long(p); - stacksize = (int)r_long(p); - flags = (int)r_long(p); - code = r_object(p); - if (code == NULL) - goto code_error; - consts = r_object(p); - if (consts == NULL) - goto code_error; - names = r_object(p); - if (names == NULL) - goto code_error; - varnames = r_object(p); - if (varnames == NULL) - goto code_error; - freevars = r_object(p); - if (freevars == NULL) - goto code_error; - cellvars = r_object(p); - if (cellvars == NULL) - goto code_error; - filename = r_object(p); - if (filename == NULL) - goto code_error; - name = r_object(p); - if (name == NULL) - goto code_error; - firstlineno = (int)r_long(p); - lnotab = r_object(p); - if (lnotab == NULL) - goto code_error; - - v = (PyObject *) PyCode_New( - argcount, kwonlyargcount, - nlocals, stacksize, flags, - code, consts, names, varnames, - freevars, cellvars, filename, name, - firstlineno, lnotab); - - code_error: - Py_XDECREF(code); - Py_XDECREF(consts); - Py_XDECREF(names); - Py_XDECREF(varnames); - Py_XDECREF(freevars); - Py_XDECREF(cellvars); - Py_XDECREF(filename); - Py_XDECREF(name); - Py_XDECREF(lnotab); - } - retval = v; - break; - - default: - /* Bogus data got written, which isn't ideal. - This will let you keep working and recover. */ - PyErr_SetString(PyExc_ValueError, "bad marshal data (unknown type code)"); - retval = NULL; - break; - - } - p->depth--; - return retval; + case TYPE_STRING: + n = r_long(p); + if (n < 0 || n > INT_MAX) { + PyErr_SetString(PyExc_ValueError, "bad marshal data (string size out of range)"); + retval = NULL; + break; + } + v = PyBytes_FromStringAndSize((char *)NULL, n); + if (v == NULL) { + retval = NULL; + break; + } + if (r_string(PyBytes_AS_STRING(v), (int)n, p) != n) { + Py_DECREF(v); + PyErr_SetString(PyExc_EOFError, + "EOF read where object expected"); + retval = NULL; + break; + } + retval = v; + break; + + case TYPE_UNICODE: + { + char *buffer; + + n = r_long(p); + if (n < 0 || n > INT_MAX) { + PyErr_SetString(PyExc_ValueError, "bad marshal data (unicode size out of range)"); + retval = NULL; + break; + } + buffer = PyMem_NEW(char, n); + if (buffer == NULL) { + retval = PyErr_NoMemory(); + break; + } + if (r_string(buffer, (int)n, p) != n) { + PyMem_DEL(buffer); + PyErr_SetString(PyExc_EOFError, + "EOF read where object expected"); + retval = NULL; + break; + } + v = PyUnicode_DecodeUTF8(buffer, n, "surrogatepass"); + PyMem_DEL(buffer); + retval = v; + break; + } + + case TYPE_TUPLE: + n = r_long(p); + if (n < 0 || n > INT_MAX) { + PyErr_SetString(PyExc_ValueError, "bad marshal data (tuple size out of range)"); + retval = NULL; + break; + } + v = PyTuple_New((int)n); + if (v == NULL) { + retval = NULL; + break; + } + for (i = 0; i < n; i++) { + v2 = r_object(p); + if ( v2 == NULL ) { + if (!PyErr_Occurred()) + PyErr_SetString(PyExc_TypeError, + "NULL object in marshal data for tuple"); + Py_DECREF(v); + v = NULL; + break; + } + PyTuple_SET_ITEM(v, (int)i, v2); + } + retval = v; + break; + + case TYPE_LIST: + n = r_long(p); + if (n < 0 || n > INT_MAX) { + PyErr_SetString(PyExc_ValueError, "bad marshal data (list size out of range)"); + retval = NULL; + break; + } + v = PyList_New((int)n); + if (v == NULL) { + retval = NULL; + break; + } + for (i = 0; i < n; i++) { + v2 = r_object(p); + if ( v2 == NULL ) { + if (!PyErr_Occurred()) + PyErr_SetString(PyExc_TypeError, + "NULL object in marshal data for list"); + Py_DECREF(v); + v = NULL; + break; + } + PyList_SET_ITEM(v, (int)i, v2); + } + retval = v; + break; + + case TYPE_DICT: + v = PyDict_New(); + if (v == NULL) { + retval = NULL; + break; + } + for (;;) { + PyObject *key, *val; + key = r_object(p); + if (key == NULL) + break; + val = r_object(p); + if (val != NULL) + PyDict_SetItem(v, key, val); + Py_DECREF(key); + Py_XDECREF(val); + } + if (PyErr_Occurred()) { + Py_DECREF(v); + v = NULL; + } + retval = v; + break; + + case TYPE_SET: + case TYPE_FROZENSET: + n = r_long(p); + if (n < 0 || n > INT_MAX) { + PyErr_SetString(PyExc_ValueError, "bad marshal data (set size out of range)"); + retval = NULL; + break; + } + v = (type == TYPE_SET) ? PySet_New(NULL) : PyFrozenSet_New(NULL); + if (v == NULL) { + retval = NULL; + break; + } + for (i = 0; i < n; i++) { + v2 = r_object(p); + if ( v2 == NULL ) { + if (!PyErr_Occurred()) + PyErr_SetString(PyExc_TypeError, + "NULL object in marshal data for set"); + Py_DECREF(v); + v = NULL; + break; + } + if (PySet_Add(v, v2) == -1) { + Py_DECREF(v); + Py_DECREF(v2); + v = NULL; + break; + } + Py_DECREF(v2); + } + retval = v; + break; + + case TYPE_CODE: + { + int argcount; + int kwonlyargcount; + int nlocals; + int stacksize; + int flags; + PyObject *code = NULL; + PyObject *consts = NULL; + PyObject *names = NULL; + PyObject *varnames = NULL; + PyObject *freevars = NULL; + PyObject *cellvars = NULL; + PyObject *filename = NULL; + PyObject *name = NULL; + int firstlineno; + PyObject *lnotab = NULL; + + v = NULL; + + /* XXX ignore long->int overflows for now */ + argcount = (int)r_long(p); + kwonlyargcount = (int)r_long(p); + nlocals = (int)r_long(p); + stacksize = (int)r_long(p); + flags = (int)r_long(p); + code = r_object(p); + if (code == NULL) + goto code_error; + consts = r_object(p); + if (consts == NULL) + goto code_error; + names = r_object(p); + if (names == NULL) + goto code_error; + varnames = r_object(p); + if (varnames == NULL) + goto code_error; + freevars = r_object(p); + if (freevars == NULL) + goto code_error; + cellvars = r_object(p); + if (cellvars == NULL) + goto code_error; + filename = r_object(p); + if (filename == NULL) + goto code_error; + name = r_object(p); + if (name == NULL) + goto code_error; + firstlineno = (int)r_long(p); + lnotab = r_object(p); + if (lnotab == NULL) + goto code_error; + + v = (PyObject *) PyCode_New( + argcount, kwonlyargcount, + nlocals, stacksize, flags, + code, consts, names, varnames, + freevars, cellvars, filename, name, + firstlineno, lnotab); + + code_error: + Py_XDECREF(code); + Py_XDECREF(consts); + Py_XDECREF(names); + Py_XDECREF(varnames); + Py_XDECREF(freevars); + Py_XDECREF(cellvars); + Py_XDECREF(filename); + Py_XDECREF(name); + Py_XDECREF(lnotab); + } + retval = v; + break; + + default: + /* Bogus data got written, which isn't ideal. + This will let you keep working and recover. */ + PyErr_SetString(PyExc_ValueError, "bad marshal data (unknown type code)"); + retval = NULL; + break; + + } + p->depth--; + return retval; } static PyObject * read_object(RFILE *p) { - PyObject *v; - if (PyErr_Occurred()) { - fprintf(stderr, "XXX readobject called with exception set\n"); - return NULL; - } - v = r_object(p); - if (v == NULL && !PyErr_Occurred()) - PyErr_SetString(PyExc_TypeError, "NULL object in marshal data for object"); - return v; + PyObject *v; + if (PyErr_Occurred()) { + fprintf(stderr, "XXX readobject called with exception set\n"); + return NULL; + } + v = r_object(p); + if (v == NULL && !PyErr_Occurred()) + PyErr_SetString(PyExc_TypeError, "NULL object in marshal data for object"); + return v; } int PyMarshal_ReadShortFromFile(FILE *fp) { - RFILE rf; - assert(fp); - rf.fp = fp; - rf.strings = NULL; - rf.end = rf.ptr = NULL; - return r_short(&rf); + RFILE rf; + assert(fp); + rf.fp = fp; + rf.strings = NULL; + rf.end = rf.ptr = NULL; + return r_short(&rf); } long PyMarshal_ReadLongFromFile(FILE *fp) { - RFILE rf; - rf.fp = fp; - rf.strings = NULL; - rf.ptr = rf.end = NULL; - return r_long(&rf); + RFILE rf; + rf.fp = fp; + rf.strings = NULL; + rf.ptr = rf.end = NULL; + return r_long(&rf); } #ifdef HAVE_FSTAT @@ -1065,11 +1065,11 @@ static off_t getfilesize(FILE *fp) { - struct stat st; - if (fstat(fileno(fp), &st) != 0) - return -1; - else - return st.st_size; + struct stat st; + if (fstat(fileno(fp), &st) != 0) + return -1; + else + return st.st_size; } #endif @@ -1088,35 +1088,35 @@ #define SMALL_FILE_LIMIT (1L << 14) #define REASONABLE_FILE_LIMIT (1L << 18) #ifdef HAVE_FSTAT - off_t filesize; + off_t filesize; #endif #ifdef HAVE_FSTAT - filesize = getfilesize(fp); - if (filesize > 0) { - char buf[SMALL_FILE_LIMIT]; - char* pBuf = NULL; - if (filesize <= SMALL_FILE_LIMIT) - pBuf = buf; - else if (filesize <= REASONABLE_FILE_LIMIT) - pBuf = (char *)PyMem_MALLOC(filesize); - if (pBuf != NULL) { - PyObject* v; - size_t n; - /* filesize must fit into an int, because it - is smaller than REASONABLE_FILE_LIMIT */ - n = fread(pBuf, 1, (int)filesize, fp); - v = PyMarshal_ReadObjectFromString(pBuf, n); - if (pBuf != buf) - PyMem_FREE(pBuf); - return v; - } + filesize = getfilesize(fp); + if (filesize > 0) { + char buf[SMALL_FILE_LIMIT]; + char* pBuf = NULL; + if (filesize <= SMALL_FILE_LIMIT) + pBuf = buf; + else if (filesize <= REASONABLE_FILE_LIMIT) + pBuf = (char *)PyMem_MALLOC(filesize); + if (pBuf != NULL) { + PyObject* v; + size_t n; + /* filesize must fit into an int, because it + is smaller than REASONABLE_FILE_LIMIT */ + n = fread(pBuf, 1, (int)filesize, fp); + v = PyMarshal_ReadObjectFromString(pBuf, n); + if (pBuf != buf) + PyMem_FREE(pBuf); + return v; + } - } + } #endif - /* We don't have fstat, or we do but the file is larger than - * REASONABLE_FILE_LIMIT or malloc failed -- read a byte at a time. - */ - return PyMarshal_ReadObjectFromFile(fp); + /* We don't have fstat, or we do but the file is larger than + * REASONABLE_FILE_LIMIT or malloc failed -- read a byte at a time. + */ + return PyMarshal_ReadObjectFromFile(fp); #undef SMALL_FILE_LIMIT #undef REASONABLE_FILE_LIMIT @@ -1125,77 +1125,77 @@ PyObject * PyMarshal_ReadObjectFromFile(FILE *fp) { - RFILE rf; - PyObject *result; - rf.fp = fp; - rf.strings = PyList_New(0); - rf.depth = 0; - rf.ptr = rf.end = NULL; - result = r_object(&rf); - Py_DECREF(rf.strings); - return result; + RFILE rf; + PyObject *result; + rf.fp = fp; + rf.strings = PyList_New(0); + rf.depth = 0; + rf.ptr = rf.end = NULL; + result = r_object(&rf); + Py_DECREF(rf.strings); + return result; } PyObject * PyMarshal_ReadObjectFromString(char *str, Py_ssize_t len) { - RFILE rf; - PyObject *result; - rf.fp = NULL; - rf.ptr = str; - rf.end = str + len; - rf.strings = PyList_New(0); - rf.depth = 0; - result = r_object(&rf); - Py_DECREF(rf.strings); - return result; + RFILE rf; + PyObject *result; + rf.fp = NULL; + rf.ptr = str; + rf.end = str + len; + rf.strings = PyList_New(0); + rf.depth = 0; + result = r_object(&rf); + Py_DECREF(rf.strings); + return result; } PyObject * PyMarshal_WriteObjectToString(PyObject *x, int version) { - WFILE wf; - PyObject *res = NULL; + WFILE wf; + PyObject *res = NULL; - wf.fp = NULL; - wf.str = PyBytes_FromStringAndSize((char *)NULL, 50); - if (wf.str == NULL) - return NULL; - wf.ptr = PyBytes_AS_STRING((PyBytesObject *)wf.str); - wf.end = wf.ptr + PyBytes_Size(wf.str); - wf.error = WFERR_OK; - wf.depth = 0; - wf.version = version; - wf.strings = (version > 0) ? PyDict_New() : NULL; - w_object(x, &wf); - Py_XDECREF(wf.strings); - if (wf.str != NULL) { - char *base = PyBytes_AS_STRING((PyBytesObject *)wf.str); - if (wf.ptr - base > PY_SSIZE_T_MAX) { - Py_DECREF(wf.str); - PyErr_SetString(PyExc_OverflowError, - "too much marshal data for a string"); - return NULL; - } - if (_PyBytes_Resize(&wf.str, (Py_ssize_t)(wf.ptr - base)) < 0) - return NULL; - } - if (wf.error != WFERR_OK) { - Py_XDECREF(wf.str); - if (wf.error == WFERR_NOMEMORY) - PyErr_NoMemory(); - else - PyErr_SetString(PyExc_ValueError, - (wf.error==WFERR_UNMARSHALLABLE)?"unmarshallable object" - :"object too deeply nested to marshal"); - return NULL; - } - if (wf.str != NULL) { - /* XXX Quick hack -- need to do this differently */ - res = PyBytes_FromObject(wf.str); - Py_DECREF(wf.str); - } - return res; + wf.fp = NULL; + wf.str = PyBytes_FromStringAndSize((char *)NULL, 50); + if (wf.str == NULL) + return NULL; + wf.ptr = PyBytes_AS_STRING((PyBytesObject *)wf.str); + wf.end = wf.ptr + PyBytes_Size(wf.str); + wf.error = WFERR_OK; + wf.depth = 0; + wf.version = version; + wf.strings = (version > 0) ? PyDict_New() : NULL; + w_object(x, &wf); + Py_XDECREF(wf.strings); + if (wf.str != NULL) { + char *base = PyBytes_AS_STRING((PyBytesObject *)wf.str); + if (wf.ptr - base > PY_SSIZE_T_MAX) { + Py_DECREF(wf.str); + PyErr_SetString(PyExc_OverflowError, + "too much marshal data for a string"); + return NULL; + } + if (_PyBytes_Resize(&wf.str, (Py_ssize_t)(wf.ptr - base)) < 0) + return NULL; + } + if (wf.error != WFERR_OK) { + Py_XDECREF(wf.str); + if (wf.error == WFERR_NOMEMORY) + PyErr_NoMemory(); + else + PyErr_SetString(PyExc_ValueError, + (wf.error==WFERR_UNMARSHALLABLE)?"unmarshallable object" + :"object too deeply nested to marshal"); + return NULL; + } + if (wf.str != NULL) { + /* XXX Quick hack -- need to do this differently */ + res = PyBytes_FromObject(wf.str); + Py_DECREF(wf.str); + } + return res; } /* And an interface for Python programs... */ @@ -1203,20 +1203,20 @@ static PyObject * marshal_dump(PyObject *self, PyObject *args) { - /* XXX Quick hack -- need to do this differently */ - PyObject *x; - PyObject *f; - int version = Py_MARSHAL_VERSION; - PyObject *s; - PyObject *res; - if (!PyArg_ParseTuple(args, "OO|i:dump", &x, &f, &version)) - return NULL; - s = PyMarshal_WriteObjectToString(x, version); - if (s == NULL) - return NULL; - res = PyObject_CallMethod(f, "write", "O", s); - Py_DECREF(s); - return res; + /* XXX Quick hack -- need to do this differently */ + PyObject *x; + PyObject *f; + int version = Py_MARSHAL_VERSION; + PyObject *s; + PyObject *res; + if (!PyArg_ParseTuple(args, "OO|i:dump", &x, &f, &version)) + return NULL; + s = PyMarshal_WriteObjectToString(x, version); + if (s == NULL) + return NULL; + res = PyObject_CallMethod(f, "write", "O", s); + Py_DECREF(s); + return res; } PyDoc_STRVAR(dump_doc, @@ -1235,35 +1235,35 @@ static PyObject * marshal_load(PyObject *self, PyObject *f) { - /* XXX Quick hack -- need to do this differently */ - PyObject *data, *result; - RFILE rf; - data = PyObject_CallMethod(f, "read", ""); - if (data == NULL) - return NULL; - rf.fp = NULL; - if (PyBytes_Check(data)) { - rf.ptr = PyBytes_AS_STRING(data); - rf.end = rf.ptr + PyBytes_GET_SIZE(data); - } - else if (PyBytes_Check(data)) { - rf.ptr = PyBytes_AS_STRING(data); - rf.end = rf.ptr + PyBytes_GET_SIZE(data); - } - else { - PyErr_Format(PyExc_TypeError, - "f.read() returned neither string " - "nor bytes but %.100s", - data->ob_type->tp_name); - Py_DECREF(data); - return NULL; - } - rf.strings = PyList_New(0); - rf.depth = 0; - result = read_object(&rf); - Py_DECREF(rf.strings); - Py_DECREF(data); - return result; + /* XXX Quick hack -- need to do this differently */ + PyObject *data, *result; + RFILE rf; + data = PyObject_CallMethod(f, "read", ""); + if (data == NULL) + return NULL; + rf.fp = NULL; + if (PyBytes_Check(data)) { + rf.ptr = PyBytes_AS_STRING(data); + rf.end = rf.ptr + PyBytes_GET_SIZE(data); + } + else if (PyBytes_Check(data)) { + rf.ptr = PyBytes_AS_STRING(data); + rf.end = rf.ptr + PyBytes_GET_SIZE(data); + } + else { + PyErr_Format(PyExc_TypeError, + "f.read() returned neither string " + "nor bytes but %.100s", + data->ob_type->tp_name); + Py_DECREF(data); + return NULL; + } + rf.strings = PyList_New(0); + rf.depth = 0; + result = read_object(&rf); + Py_DECREF(rf.strings); + Py_DECREF(data); + return result; } PyDoc_STRVAR(load_doc, @@ -1282,11 +1282,11 @@ static PyObject * marshal_dumps(PyObject *self, PyObject *args) { - PyObject *x; - int version = Py_MARSHAL_VERSION; - if (!PyArg_ParseTuple(args, "O|i:dumps", &x, &version)) - return NULL; - return PyMarshal_WriteObjectToString(x, version); + PyObject *x; + int version = Py_MARSHAL_VERSION; + if (!PyArg_ParseTuple(args, "O|i:dumps", &x, &version)) + return NULL; + return PyMarshal_WriteObjectToString(x, version); } PyDoc_STRVAR(dumps_doc, @@ -1302,24 +1302,24 @@ static PyObject * marshal_loads(PyObject *self, PyObject *args) { - RFILE rf; - Py_buffer p; - char *s; - Py_ssize_t n; - PyObject* result; - if (!PyArg_ParseTuple(args, "s*:loads", &p)) - return NULL; - s = p.buf; - n = p.len; - rf.fp = NULL; - rf.ptr = s; - rf.end = s + n; - rf.strings = PyList_New(0); - rf.depth = 0; - result = read_object(&rf); - Py_DECREF(rf.strings); - PyBuffer_Release(&p); - return result; + RFILE rf; + Py_buffer p; + char *s; + Py_ssize_t n; + PyObject* result; + if (!PyArg_ParseTuple(args, "s*:loads", &p)) + return NULL; + s = p.buf; + n = p.len; + rf.fp = NULL; + rf.ptr = s; + rf.end = s + n; + rf.strings = PyList_New(0); + rf.depth = 0; + result = read_object(&rf); + Py_DECREF(rf.strings); + PyBuffer_Release(&p); + return result; } PyDoc_STRVAR(loads_doc, @@ -1330,11 +1330,11 @@ ignored."); static PyMethodDef marshal_methods[] = { - {"dump", marshal_dump, METH_VARARGS, dump_doc}, - {"load", marshal_load, METH_O, load_doc}, - {"dumps", marshal_dumps, METH_VARARGS, dumps_doc}, - {"loads", marshal_loads, METH_VARARGS, loads_doc}, - {NULL, NULL} /* sentinel */ + {"dump", marshal_dump, METH_VARARGS, dump_doc}, + {"load", marshal_load, METH_O, load_doc}, + {"dumps", marshal_dumps, METH_VARARGS, dumps_doc}, + {"loads", marshal_loads, METH_VARARGS, loads_doc}, + {NULL, NULL} /* sentinel */ }; @@ -1369,23 +1369,23 @@ static struct PyModuleDef marshalmodule = { - PyModuleDef_HEAD_INIT, - "marshal", - module_doc, - 0, - marshal_methods, - NULL, - NULL, - NULL, - NULL + PyModuleDef_HEAD_INIT, + "marshal", + module_doc, + 0, + marshal_methods, + NULL, + NULL, + NULL, + NULL }; PyMODINIT_FUNC PyMarshal_Init(void) { - PyObject *mod = PyModule_Create(&marshalmodule); - if (mod == NULL) - return NULL; - PyModule_AddIntConstant(mod, "version", Py_MARSHAL_VERSION); - return mod; + PyObject *mod = PyModule_Create(&marshalmodule); + if (mod == NULL) + return NULL; + PyModule_AddIntConstant(mod, "version", Py_MARSHAL_VERSION); + return mod; } Modified: python/branches/release31-maint/Python/modsupport.c ============================================================================== --- python/branches/release31-maint/Python/modsupport.c (original) +++ python/branches/release31-maint/Python/modsupport.c Sun May 9 18:14:21 2010 @@ -16,41 +16,41 @@ static int countformat(const char *format, int endchar) { - int count = 0; - int level = 0; - while (level > 0 || *format != endchar) { - switch (*format) { - case '\0': - /* Premature end */ - PyErr_SetString(PyExc_SystemError, - "unmatched paren in format"); - return -1; - case '(': - case '[': - case '{': - if (level == 0) - count++; - level++; - break; - case ')': - case ']': - case '}': - level--; - break; - case '#': - case '&': - case ',': - case ':': - case ' ': - case '\t': - break; - default: - if (level == 0) - count++; - } - format++; - } - return count; + int count = 0; + int level = 0; + while (level > 0 || *format != endchar) { + switch (*format) { + case '\0': + /* Premature end */ + PyErr_SetString(PyExc_SystemError, + "unmatched paren in format"); + return -1; + case '(': + case '[': + case '{': + if (level == 0) + count++; + level++; + break; + case ')': + case ']': + case '}': + level--; + break; + case '#': + case '&': + case ',': + case ':': + case ' ': + case '\t': + break; + default: + if (level == 0) + count++; + } + format++; + } + return count; } @@ -66,552 +66,552 @@ static PyObject * do_mkdict(const char **p_format, va_list *p_va, int endchar, int n, int flags) { - PyObject *d; - int i; - int itemfailed = 0; - if (n < 0) - return NULL; - if ((d = PyDict_New()) == NULL) - return NULL; - /* Note that we can't bail immediately on error as this will leak - refcounts on any 'N' arguments. */ - for (i = 0; i < n; i+= 2) { - PyObject *k, *v; - int err; - k = do_mkvalue(p_format, p_va, flags); - if (k == NULL) { - itemfailed = 1; - Py_INCREF(Py_None); - k = Py_None; - } - v = do_mkvalue(p_format, p_va, flags); - if (v == NULL) { - itemfailed = 1; - Py_INCREF(Py_None); - v = Py_None; - } - err = PyDict_SetItem(d, k, v); - Py_DECREF(k); - Py_DECREF(v); - if (err < 0 || itemfailed) { - Py_DECREF(d); - return NULL; - } - } - if (d != NULL && **p_format != endchar) { - Py_DECREF(d); - d = NULL; - PyErr_SetString(PyExc_SystemError, - "Unmatched paren in format"); - } - else if (endchar) - ++*p_format; - return d; + PyObject *d; + int i; + int itemfailed = 0; + if (n < 0) + return NULL; + if ((d = PyDict_New()) == NULL) + return NULL; + /* Note that we can't bail immediately on error as this will leak + refcounts on any 'N' arguments. */ + for (i = 0; i < n; i+= 2) { + PyObject *k, *v; + int err; + k = do_mkvalue(p_format, p_va, flags); + if (k == NULL) { + itemfailed = 1; + Py_INCREF(Py_None); + k = Py_None; + } + v = do_mkvalue(p_format, p_va, flags); + if (v == NULL) { + itemfailed = 1; + Py_INCREF(Py_None); + v = Py_None; + } + err = PyDict_SetItem(d, k, v); + Py_DECREF(k); + Py_DECREF(v); + if (err < 0 || itemfailed) { + Py_DECREF(d); + return NULL; + } + } + if (d != NULL && **p_format != endchar) { + Py_DECREF(d); + d = NULL; + PyErr_SetString(PyExc_SystemError, + "Unmatched paren in format"); + } + else if (endchar) + ++*p_format; + return d; } static PyObject * do_mklist(const char **p_format, va_list *p_va, int endchar, int n, int flags) { - PyObject *v; - int i; - int itemfailed = 0; - if (n < 0) - return NULL; - v = PyList_New(n); - if (v == NULL) - return NULL; - /* Note that we can't bail immediately on error as this will leak - refcounts on any 'N' arguments. */ - for (i = 0; i < n; i++) { - PyObject *w = do_mkvalue(p_format, p_va, flags); - if (w == NULL) { - itemfailed = 1; - Py_INCREF(Py_None); - w = Py_None; - } - PyList_SET_ITEM(v, i, w); - } - - if (itemfailed) { - /* do_mkvalue() should have already set an error */ - Py_DECREF(v); - return NULL; - } - if (**p_format != endchar) { - Py_DECREF(v); - PyErr_SetString(PyExc_SystemError, - "Unmatched paren in format"); - return NULL; - } - if (endchar) - ++*p_format; - return v; + PyObject *v; + int i; + int itemfailed = 0; + if (n < 0) + return NULL; + v = PyList_New(n); + if (v == NULL) + return NULL; + /* Note that we can't bail immediately on error as this will leak + refcounts on any 'N' arguments. */ + for (i = 0; i < n; i++) { + PyObject *w = do_mkvalue(p_format, p_va, flags); + if (w == NULL) { + itemfailed = 1; + Py_INCREF(Py_None); + w = Py_None; + } + PyList_SET_ITEM(v, i, w); + } + + if (itemfailed) { + /* do_mkvalue() should have already set an error */ + Py_DECREF(v); + return NULL; + } + if (**p_format != endchar) { + Py_DECREF(v); + PyErr_SetString(PyExc_SystemError, + "Unmatched paren in format"); + return NULL; + } + if (endchar) + ++*p_format; + return v; } static int _ustrlen(Py_UNICODE *u) { - int i = 0; - Py_UNICODE *v = u; - while (*v != 0) { i++; v++; } - return i; + int i = 0; + Py_UNICODE *v = u; + while (*v != 0) { i++; v++; } + return i; } static PyObject * do_mktuple(const char **p_format, va_list *p_va, int endchar, int n, int flags) { - PyObject *v; - int i; - int itemfailed = 0; - if (n < 0) - return NULL; - if ((v = PyTuple_New(n)) == NULL) - return NULL; - /* Note that we can't bail immediately on error as this will leak - refcounts on any 'N' arguments. */ - for (i = 0; i < n; i++) { - PyObject *w = do_mkvalue(p_format, p_va, flags); - if (w == NULL) { - itemfailed = 1; - Py_INCREF(Py_None); - w = Py_None; - } - PyTuple_SET_ITEM(v, i, w); - } - if (itemfailed) { - /* do_mkvalue() should have already set an error */ - Py_DECREF(v); - return NULL; - } - if (**p_format != endchar) { - Py_DECREF(v); - PyErr_SetString(PyExc_SystemError, - "Unmatched paren in format"); - return NULL; - } - if (endchar) - ++*p_format; - return v; + PyObject *v; + int i; + int itemfailed = 0; + if (n < 0) + return NULL; + if ((v = PyTuple_New(n)) == NULL) + return NULL; + /* Note that we can't bail immediately on error as this will leak + refcounts on any 'N' arguments. */ + for (i = 0; i < n; i++) { + PyObject *w = do_mkvalue(p_format, p_va, flags); + if (w == NULL) { + itemfailed = 1; + Py_INCREF(Py_None); + w = Py_None; + } + PyTuple_SET_ITEM(v, i, w); + } + if (itemfailed) { + /* do_mkvalue() should have already set an error */ + Py_DECREF(v); + return NULL; + } + if (**p_format != endchar) { + Py_DECREF(v); + PyErr_SetString(PyExc_SystemError, + "Unmatched paren in format"); + return NULL; + } + if (endchar) + ++*p_format; + return v; } static PyObject * do_mkvalue(const char **p_format, va_list *p_va, int flags) { - for (;;) { - switch (*(*p_format)++) { - case '(': - return do_mktuple(p_format, p_va, ')', - countformat(*p_format, ')'), flags); - - case '[': - return do_mklist(p_format, p_va, ']', - countformat(*p_format, ']'), flags); - - case '{': - return do_mkdict(p_format, p_va, '}', - countformat(*p_format, '}'), flags); - - case 'b': - case 'B': - case 'h': - case 'i': - return PyLong_FromLong((long)va_arg(*p_va, int)); - - case 'H': - return PyLong_FromLong((long)va_arg(*p_va, unsigned int)); - - case 'I': - { - unsigned int n; - n = va_arg(*p_va, unsigned int); - return PyLong_FromUnsignedLong(n); - } - - case 'n': + for (;;) { + switch (*(*p_format)++) { + case '(': + return do_mktuple(p_format, p_va, ')', + countformat(*p_format, ')'), flags); + + case '[': + return do_mklist(p_format, p_va, ']', + countformat(*p_format, ']'), flags); + + case '{': + return do_mkdict(p_format, p_va, '}', + countformat(*p_format, '}'), flags); + + case 'b': + case 'B': + case 'h': + case 'i': + return PyLong_FromLong((long)va_arg(*p_va, int)); + + case 'H': + return PyLong_FromLong((long)va_arg(*p_va, unsigned int)); + + case 'I': + { + unsigned int n; + n = va_arg(*p_va, unsigned int); + return PyLong_FromUnsignedLong(n); + } + + case 'n': #if SIZEOF_SIZE_T!=SIZEOF_LONG - return PyLong_FromSsize_t(va_arg(*p_va, Py_ssize_t)); + return PyLong_FromSsize_t(va_arg(*p_va, Py_ssize_t)); #endif - /* Fall through from 'n' to 'l' if Py_ssize_t is long */ - case 'l': - return PyLong_FromLong(va_arg(*p_va, long)); - - case 'k': - { - unsigned long n; - n = va_arg(*p_va, unsigned long); - return PyLong_FromUnsignedLong(n); - } + /* Fall through from 'n' to 'l' if Py_ssize_t is long */ + case 'l': + return PyLong_FromLong(va_arg(*p_va, long)); + + case 'k': + { + unsigned long n; + n = va_arg(*p_va, unsigned long); + return PyLong_FromUnsignedLong(n); + } #ifdef HAVE_LONG_LONG - case 'L': - return PyLong_FromLongLong((PY_LONG_LONG)va_arg(*p_va, PY_LONG_LONG)); + case 'L': + return PyLong_FromLongLong((PY_LONG_LONG)va_arg(*p_va, PY_LONG_LONG)); - case 'K': - return PyLong_FromUnsignedLongLong((PY_LONG_LONG)va_arg(*p_va, unsigned PY_LONG_LONG)); + case 'K': + return PyLong_FromUnsignedLongLong((PY_LONG_LONG)va_arg(*p_va, unsigned PY_LONG_LONG)); #endif - case 'u': - { - PyObject *v; - Py_UNICODE *u = va_arg(*p_va, Py_UNICODE *); - Py_ssize_t n; - if (**p_format == '#') { - ++*p_format; - if (flags & FLAG_SIZE_T) - n = va_arg(*p_va, Py_ssize_t); - else - n = va_arg(*p_va, int); - } - else - n = -1; - if (u == NULL) { - v = Py_None; - Py_INCREF(v); - } - else { - if (n < 0) - n = _ustrlen(u); - v = PyUnicode_FromUnicode(u, n); - } - return v; - } - case 'f': - case 'd': - return PyFloat_FromDouble( - (double)va_arg(*p_va, va_double)); + case 'u': + { + PyObject *v; + Py_UNICODE *u = va_arg(*p_va, Py_UNICODE *); + Py_ssize_t n; + if (**p_format == '#') { + ++*p_format; + if (flags & FLAG_SIZE_T) + n = va_arg(*p_va, Py_ssize_t); + else + n = va_arg(*p_va, int); + } + else + n = -1; + if (u == NULL) { + v = Py_None; + Py_INCREF(v); + } + else { + if (n < 0) + n = _ustrlen(u); + v = PyUnicode_FromUnicode(u, n); + } + return v; + } + case 'f': + case 'd': + return PyFloat_FromDouble( + (double)va_arg(*p_va, va_double)); #ifndef WITHOUT_COMPLEX - case 'D': - return PyComplex_FromCComplex( - *((Py_complex *)va_arg(*p_va, Py_complex *))); + case 'D': + return PyComplex_FromCComplex( + *((Py_complex *)va_arg(*p_va, Py_complex *))); #endif /* WITHOUT_COMPLEX */ - case 'c': - { - char p[1]; - p[0] = (char)va_arg(*p_va, int); - return PyBytes_FromStringAndSize(p, 1); - } - case 'C': - { - int i = va_arg(*p_va, int); - if (i < 0 || i > PyUnicode_GetMax()) { - PyErr_SetString(PyExc_OverflowError, - "%c arg not in range(0x110000)"); - return NULL; - } - return PyUnicode_FromOrdinal(i); - } - - case 's': - case 'z': - { - PyObject *v; - char *str = va_arg(*p_va, char *); - Py_ssize_t n; - if (**p_format == '#') { - ++*p_format; - if (flags & FLAG_SIZE_T) - n = va_arg(*p_va, Py_ssize_t); - else - n = va_arg(*p_va, int); - } - else - n = -1; - if (str == NULL) { - v = Py_None; - Py_INCREF(v); - } - else { - if (n < 0) { - size_t m = strlen(str); - if (m > PY_SSIZE_T_MAX) { - PyErr_SetString(PyExc_OverflowError, - "string too long for Python string"); - return NULL; - } - n = (Py_ssize_t)m; - } - v = PyUnicode_FromStringAndSize(str, n); - } - return v; - } - - case 'U': - { - PyObject *v; - char *str = va_arg(*p_va, char *); - Py_ssize_t n; - if (**p_format == '#') { - ++*p_format; - if (flags & FLAG_SIZE_T) - n = va_arg(*p_va, Py_ssize_t); - else - n = va_arg(*p_va, int); - } - else - n = -1; - if (str == NULL) { - v = Py_None; - Py_INCREF(v); - } - else { - if (n < 0) { - size_t m = strlen(str); - if (m > PY_SSIZE_T_MAX) { - PyErr_SetString(PyExc_OverflowError, - "string too long for Python string"); - return NULL; - } - n = (Py_ssize_t)m; - } - v = PyUnicode_FromStringAndSize(str, n); - } - return v; - } - - case 'y': - { - PyObject *v; - char *str = va_arg(*p_va, char *); - Py_ssize_t n; - if (**p_format == '#') { - ++*p_format; - if (flags & FLAG_SIZE_T) - n = va_arg(*p_va, Py_ssize_t); - else - n = va_arg(*p_va, int); - } - else - n = -1; - if (str == NULL) { - v = Py_None; - Py_INCREF(v); - } - else { - if (n < 0) { - size_t m = strlen(str); - if (m > PY_SSIZE_T_MAX) { - PyErr_SetString(PyExc_OverflowError, - "string too long for Python bytes"); - return NULL; - } - n = (Py_ssize_t)m; - } - v = PyBytes_FromStringAndSize(str, n); - } - return v; - } - - case 'N': - case 'S': - case 'O': - if (**p_format == '&') { - typedef PyObject *(*converter)(void *); - converter func = va_arg(*p_va, converter); - void *arg = va_arg(*p_va, void *); - ++*p_format; - return (*func)(arg); - } - else { - PyObject *v; - v = va_arg(*p_va, PyObject *); - if (v != NULL) { - if (*(*p_format - 1) != 'N') - Py_INCREF(v); - } - else if (!PyErr_Occurred()) - /* If a NULL was passed - * because a call that should - * have constructed a value - * failed, that's OK, and we - * pass the error on; but if - * no error occurred it's not - * clear that the caller knew - * what she was doing. */ - PyErr_SetString(PyExc_SystemError, - "NULL object passed to Py_BuildValue"); - return v; - } - - case ':': - case ',': - case ' ': - case '\t': - break; - - default: - PyErr_SetString(PyExc_SystemError, - "bad format char passed to Py_BuildValue"); - return NULL; + case 'c': + { + char p[1]; + p[0] = (char)va_arg(*p_va, int); + return PyBytes_FromStringAndSize(p, 1); + } + case 'C': + { + int i = va_arg(*p_va, int); + if (i < 0 || i > PyUnicode_GetMax()) { + PyErr_SetString(PyExc_OverflowError, + "%c arg not in range(0x110000)"); + return NULL; + } + return PyUnicode_FromOrdinal(i); + } + + case 's': + case 'z': + { + PyObject *v; + char *str = va_arg(*p_va, char *); + Py_ssize_t n; + if (**p_format == '#') { + ++*p_format; + if (flags & FLAG_SIZE_T) + n = va_arg(*p_va, Py_ssize_t); + else + n = va_arg(*p_va, int); + } + else + n = -1; + if (str == NULL) { + v = Py_None; + Py_INCREF(v); + } + else { + if (n < 0) { + size_t m = strlen(str); + if (m > PY_SSIZE_T_MAX) { + PyErr_SetString(PyExc_OverflowError, + "string too long for Python string"); + return NULL; + } + n = (Py_ssize_t)m; + } + v = PyUnicode_FromStringAndSize(str, n); + } + return v; + } + + case 'U': + { + PyObject *v; + char *str = va_arg(*p_va, char *); + Py_ssize_t n; + if (**p_format == '#') { + ++*p_format; + if (flags & FLAG_SIZE_T) + n = va_arg(*p_va, Py_ssize_t); + else + n = va_arg(*p_va, int); + } + else + n = -1; + if (str == NULL) { + v = Py_None; + Py_INCREF(v); + } + else { + if (n < 0) { + size_t m = strlen(str); + if (m > PY_SSIZE_T_MAX) { + PyErr_SetString(PyExc_OverflowError, + "string too long for Python string"); + return NULL; + } + n = (Py_ssize_t)m; + } + v = PyUnicode_FromStringAndSize(str, n); + } + return v; + } + + case 'y': + { + PyObject *v; + char *str = va_arg(*p_va, char *); + Py_ssize_t n; + if (**p_format == '#') { + ++*p_format; + if (flags & FLAG_SIZE_T) + n = va_arg(*p_va, Py_ssize_t); + else + n = va_arg(*p_va, int); + } + else + n = -1; + if (str == NULL) { + v = Py_None; + Py_INCREF(v); + } + else { + if (n < 0) { + size_t m = strlen(str); + if (m > PY_SSIZE_T_MAX) { + PyErr_SetString(PyExc_OverflowError, + "string too long for Python bytes"); + return NULL; + } + n = (Py_ssize_t)m; + } + v = PyBytes_FromStringAndSize(str, n); + } + return v; + } + + case 'N': + case 'S': + case 'O': + if (**p_format == '&') { + typedef PyObject *(*converter)(void *); + converter func = va_arg(*p_va, converter); + void *arg = va_arg(*p_va, void *); + ++*p_format; + return (*func)(arg); + } + else { + PyObject *v; + v = va_arg(*p_va, PyObject *); + if (v != NULL) { + if (*(*p_format - 1) != 'N') + Py_INCREF(v); + } + else if (!PyErr_Occurred()) + /* If a NULL was passed + * because a call that should + * have constructed a value + * failed, that's OK, and we + * pass the error on; but if + * no error occurred it's not + * clear that the caller knew + * what she was doing. */ + PyErr_SetString(PyExc_SystemError, + "NULL object passed to Py_BuildValue"); + return v; + } + + case ':': + case ',': + case ' ': + case '\t': + break; + + default: + PyErr_SetString(PyExc_SystemError, + "bad format char passed to Py_BuildValue"); + return NULL; - } - } + } + } } PyObject * Py_BuildValue(const char *format, ...) { - va_list va; - PyObject* retval; - va_start(va, format); - retval = va_build_value(format, va, 0); - va_end(va); - return retval; + va_list va; + PyObject* retval; + va_start(va, format); + retval = va_build_value(format, va, 0); + va_end(va); + return retval; } PyObject * _Py_BuildValue_SizeT(const char *format, ...) { - va_list va; - PyObject* retval; - va_start(va, format); - retval = va_build_value(format, va, FLAG_SIZE_T); - va_end(va); - return retval; + va_list va; + PyObject* retval; + va_start(va, format); + retval = va_build_value(format, va, FLAG_SIZE_T); + va_end(va); + return retval; } PyObject * Py_VaBuildValue(const char *format, va_list va) { - return va_build_value(format, va, 0); + return va_build_value(format, va, 0); } PyObject * _Py_VaBuildValue_SizeT(const char *format, va_list va) { - return va_build_value(format, va, FLAG_SIZE_T); + return va_build_value(format, va, FLAG_SIZE_T); } static PyObject * va_build_value(const char *format, va_list va, int flags) { - const char *f = format; - int n = countformat(f, '\0'); - va_list lva; + const char *f = format; + int n = countformat(f, '\0'); + va_list lva; #ifdef VA_LIST_IS_ARRAY - memcpy(lva, va, sizeof(va_list)); + memcpy(lva, va, sizeof(va_list)); #else #ifdef __va_copy - __va_copy(lva, va); + __va_copy(lva, va); #else - lva = va; + lva = va; #endif #endif - if (n < 0) - return NULL; - if (n == 0) { - Py_INCREF(Py_None); - return Py_None; - } - if (n == 1) - return do_mkvalue(&f, &lva, flags); - return do_mktuple(&f, &lva, '\0', n, flags); + if (n < 0) + return NULL; + if (n == 0) { + Py_INCREF(Py_None); + return Py_None; + } + if (n == 1) + return do_mkvalue(&f, &lva, flags); + return do_mktuple(&f, &lva, '\0', n, flags); } PyObject * PyEval_CallFunction(PyObject *obj, const char *format, ...) { - va_list vargs; - PyObject *args; - PyObject *res; + va_list vargs; + PyObject *args; + PyObject *res; - va_start(vargs, format); + va_start(vargs, format); - args = Py_VaBuildValue(format, vargs); - va_end(vargs); + args = Py_VaBuildValue(format, vargs); + va_end(vargs); - if (args == NULL) - return NULL; + if (args == NULL) + return NULL; - res = PyEval_CallObject(obj, args); - Py_DECREF(args); + res = PyEval_CallObject(obj, args); + Py_DECREF(args); - return res; + return res; } PyObject * PyEval_CallMethod(PyObject *obj, const char *methodname, const char *format, ...) { - va_list vargs; - PyObject *meth; - PyObject *args; - PyObject *res; - - meth = PyObject_GetAttrString(obj, methodname); - if (meth == NULL) - return NULL; - - va_start(vargs, format); - - args = Py_VaBuildValue(format, vargs); - va_end(vargs); - - if (args == NULL) { - Py_DECREF(meth); - return NULL; - } - - res = PyEval_CallObject(meth, args); - Py_DECREF(meth); - Py_DECREF(args); + va_list vargs; + PyObject *meth; + PyObject *args; + PyObject *res; + + meth = PyObject_GetAttrString(obj, methodname); + if (meth == NULL) + return NULL; + + va_start(vargs, format); + + args = Py_VaBuildValue(format, vargs); + va_end(vargs); + + if (args == NULL) { + Py_DECREF(meth); + return NULL; + } + + res = PyEval_CallObject(meth, args); + Py_DECREF(meth); + Py_DECREF(args); - return res; + return res; } int PyModule_AddObject(PyObject *m, const char *name, PyObject *o) { - PyObject *dict; - if (!PyModule_Check(m)) { - PyErr_SetString(PyExc_TypeError, - "PyModule_AddObject() needs module as first arg"); - return -1; - } - if (!o) { - if (!PyErr_Occurred()) - PyErr_SetString(PyExc_TypeError, - "PyModule_AddObject() needs non-NULL value"); - return -1; - } - - dict = PyModule_GetDict(m); - if (dict == NULL) { - /* Internal error -- modules must have a dict! */ - PyErr_Format(PyExc_SystemError, "module '%s' has no __dict__", - PyModule_GetName(m)); - return -1; - } - if (PyDict_SetItemString(dict, name, o)) - return -1; - Py_DECREF(o); - return 0; + PyObject *dict; + if (!PyModule_Check(m)) { + PyErr_SetString(PyExc_TypeError, + "PyModule_AddObject() needs module as first arg"); + return -1; + } + if (!o) { + if (!PyErr_Occurred()) + PyErr_SetString(PyExc_TypeError, + "PyModule_AddObject() needs non-NULL value"); + return -1; + } + + dict = PyModule_GetDict(m); + if (dict == NULL) { + /* Internal error -- modules must have a dict! */ + PyErr_Format(PyExc_SystemError, "module '%s' has no __dict__", + PyModule_GetName(m)); + return -1; + } + if (PyDict_SetItemString(dict, name, o)) + return -1; + Py_DECREF(o); + return 0; } -int +int PyModule_AddIntConstant(PyObject *m, const char *name, long value) { - PyObject *o = PyLong_FromLong(value); - if (!o) - return -1; - if (PyModule_AddObject(m, name, o) == 0) - return 0; - Py_DECREF(o); - return -1; + PyObject *o = PyLong_FromLong(value); + if (!o) + return -1; + if (PyModule_AddObject(m, name, o) == 0) + return 0; + Py_DECREF(o); + return -1; } -int +int PyModule_AddStringConstant(PyObject *m, const char *name, const char *value) { - PyObject *o = PyUnicode_FromString(value); - if (!o) - return -1; - if (PyModule_AddObject(m, name, o) == 0) - return 0; - Py_DECREF(o); - return -1; + PyObject *o = PyUnicode_FromString(value); + if (!o) + return -1; + if (PyModule_AddObject(m, name, o) == 0) + return 0; + Py_DECREF(o); + return -1; } Modified: python/branches/release31-maint/Python/mysnprintf.c ============================================================================== --- python/branches/release31-maint/Python/mysnprintf.c (original) +++ python/branches/release31-maint/Python/mysnprintf.c Sun May 9 18:14:21 2010 @@ -19,20 +19,20 @@ Return value (rv): - When 0 <= rv < size, the output conversion was unexceptional, and - rv characters were written to str (excluding a trailing \0 byte at - str[rv]). - - When rv >= size, output conversion was truncated, and a buffer of - size rv+1 would have been needed to avoid truncation. str[size-1] - is \0 in this case. - - When rv < 0, "something bad happened". str[size-1] is \0 in this - case too, but the rest of str is unreliable. It could be that - an error in format codes was detected by libc, or on platforms - with a non-C99 vsnprintf simply that the buffer wasn't big enough - to avoid truncation, or on platforms without any vsnprintf that - PyMem_Malloc couldn't obtain space for a temp buffer. + When 0 <= rv < size, the output conversion was unexceptional, and + rv characters were written to str (excluding a trailing \0 byte at + str[rv]). + + When rv >= size, output conversion was truncated, and a buffer of + size rv+1 would have been needed to avoid truncation. str[size-1] + is \0 in this case. + + When rv < 0, "something bad happened". str[size-1] is \0 in this + case too, but the rest of str is unreliable. It could be that + an error in format codes was detected by libc, or on platforms + with a non-C99 vsnprintf simply that the buffer wasn't big enough + to avoid truncation, or on platforms without any vsnprintf that + PyMem_Malloc couldn't obtain space for a temp buffer. CAUTION: Unlike C99, str != NULL and size > 0 are required. */ @@ -40,65 +40,65 @@ int PyOS_snprintf(char *str, size_t size, const char *format, ...) { - int rc; - va_list va; + int rc; + va_list va; - va_start(va, format); - rc = PyOS_vsnprintf(str, size, format, va); - va_end(va); - return rc; + va_start(va, format); + rc = PyOS_vsnprintf(str, size, format, va); + va_end(va); + return rc; } int PyOS_vsnprintf(char *str, size_t size, const char *format, va_list va) { - int len; /* # bytes written, excluding \0 */ + int len; /* # bytes written, excluding \0 */ #ifdef HAVE_SNPRINTF #define _PyOS_vsnprintf_EXTRA_SPACE 1 #else #define _PyOS_vsnprintf_EXTRA_SPACE 512 - char *buffer; + char *buffer; #endif - assert(str != NULL); - assert(size > 0); - assert(format != NULL); - /* We take a size_t as input but return an int. Sanity check - * our input so that it won't cause an overflow in the - * vsnprintf return value or the buffer malloc size. */ - if (size > INT_MAX - _PyOS_vsnprintf_EXTRA_SPACE) { - len = -666; - goto Done; - } + assert(str != NULL); + assert(size > 0); + assert(format != NULL); + /* We take a size_t as input but return an int. Sanity check + * our input so that it won't cause an overflow in the + * vsnprintf return value or the buffer malloc size. */ + if (size > INT_MAX - _PyOS_vsnprintf_EXTRA_SPACE) { + len = -666; + goto Done; + } #ifdef HAVE_SNPRINTF - len = vsnprintf(str, size, format, va); + len = vsnprintf(str, size, format, va); #else - /* Emulate it. */ - buffer = PyMem_MALLOC(size + _PyOS_vsnprintf_EXTRA_SPACE); - if (buffer == NULL) { - len = -666; - goto Done; - } - - len = vsprintf(buffer, format, va); - if (len < 0) - /* ignore the error */; - - else if ((size_t)len >= size + _PyOS_vsnprintf_EXTRA_SPACE) - Py_FatalError("Buffer overflow in PyOS_snprintf/PyOS_vsnprintf"); - - else { - const size_t to_copy = (size_t)len < size ? - (size_t)len : size - 1; - assert(to_copy < size); - memcpy(str, buffer, to_copy); - str[to_copy] = '\0'; - } - PyMem_FREE(buffer); + /* Emulate it. */ + buffer = PyMem_MALLOC(size + _PyOS_vsnprintf_EXTRA_SPACE); + if (buffer == NULL) { + len = -666; + goto Done; + } + + len = vsprintf(buffer, format, va); + if (len < 0) + /* ignore the error */; + + else if ((size_t)len >= size + _PyOS_vsnprintf_EXTRA_SPACE) + Py_FatalError("Buffer overflow in PyOS_snprintf/PyOS_vsnprintf"); + + else { + const size_t to_copy = (size_t)len < size ? + (size_t)len : size - 1; + assert(to_copy < size); + memcpy(str, buffer, to_copy); + str[to_copy] = '\0'; + } + PyMem_FREE(buffer); #endif Done: - if (size > 0) - str[size-1] = '\0'; - return len; + if (size > 0) + str[size-1] = '\0'; + return len; #undef _PyOS_vsnprintf_EXTRA_SPACE } Modified: python/branches/release31-maint/Python/mystrtoul.c ============================================================================== --- python/branches/release31-maint/Python/mystrtoul.c (original) +++ python/branches/release31-maint/Python/mystrtoul.c Sun May 9 18:14:21 2010 @@ -18,43 +18,43 @@ * i * base doesn't overflow unsigned long. */ static unsigned long smallmax[] = { - 0, /* bases 0 and 1 are invalid */ - 0, - ULONG_MAX / 2, - ULONG_MAX / 3, - ULONG_MAX / 4, - ULONG_MAX / 5, - ULONG_MAX / 6, - ULONG_MAX / 7, - ULONG_MAX / 8, - ULONG_MAX / 9, - ULONG_MAX / 10, - ULONG_MAX / 11, - ULONG_MAX / 12, - ULONG_MAX / 13, - ULONG_MAX / 14, - ULONG_MAX / 15, - ULONG_MAX / 16, - ULONG_MAX / 17, - ULONG_MAX / 18, - ULONG_MAX / 19, - ULONG_MAX / 20, - ULONG_MAX / 21, - ULONG_MAX / 22, - ULONG_MAX / 23, - ULONG_MAX / 24, - ULONG_MAX / 25, - ULONG_MAX / 26, - ULONG_MAX / 27, - ULONG_MAX / 28, - ULONG_MAX / 29, - ULONG_MAX / 30, - ULONG_MAX / 31, - ULONG_MAX / 32, - ULONG_MAX / 33, - ULONG_MAX / 34, - ULONG_MAX / 35, - ULONG_MAX / 36, + 0, /* bases 0 and 1 are invalid */ + 0, + ULONG_MAX / 2, + ULONG_MAX / 3, + ULONG_MAX / 4, + ULONG_MAX / 5, + ULONG_MAX / 6, + ULONG_MAX / 7, + ULONG_MAX / 8, + ULONG_MAX / 9, + ULONG_MAX / 10, + ULONG_MAX / 11, + ULONG_MAX / 12, + ULONG_MAX / 13, + ULONG_MAX / 14, + ULONG_MAX / 15, + ULONG_MAX / 16, + ULONG_MAX / 17, + ULONG_MAX / 18, + ULONG_MAX / 19, + ULONG_MAX / 20, + ULONG_MAX / 21, + ULONG_MAX / 22, + ULONG_MAX / 23, + ULONG_MAX / 24, + ULONG_MAX / 25, + ULONG_MAX / 26, + ULONG_MAX / 27, + ULONG_MAX / 28, + ULONG_MAX / 29, + ULONG_MAX / 30, + ULONG_MAX / 31, + ULONG_MAX / 32, + ULONG_MAX / 33, + ULONG_MAX / 34, + ULONG_MAX / 35, + ULONG_MAX / 36, }; /* maximum digits that can't ever overflow for bases 2 through 36, @@ -63,229 +63,229 @@ */ #if SIZEOF_LONG == 4 static int digitlimit[] = { - 0, 0, 32, 20, 16, 13, 12, 11, 10, 10, /* 0 - 9 */ - 9, 9, 8, 8, 8, 8, 8, 7, 7, 7, /* 10 - 19 */ - 7, 7, 7, 7, 6, 6, 6, 6, 6, 6, /* 20 - 29 */ - 6, 6, 6, 6, 6, 6, 6}; /* 30 - 36 */ + 0, 0, 32, 20, 16, 13, 12, 11, 10, 10, /* 0 - 9 */ + 9, 9, 8, 8, 8, 8, 8, 7, 7, 7, /* 10 - 19 */ + 7, 7, 7, 7, 6, 6, 6, 6, 6, 6, /* 20 - 29 */ + 6, 6, 6, 6, 6, 6, 6}; /* 30 - 36 */ #elif SIZEOF_LONG == 8 /* [int(math.floor(math.log(2**64, i))) for i in range(2, 37)] */ static int digitlimit[] = { - 0, 0, 64, 40, 32, 27, 24, 22, 21, 20, /* 0 - 9 */ - 19, 18, 17, 17, 16, 16, 16, 15, 15, 15, /* 10 - 19 */ - 14, 14, 14, 14, 13, 13, 13, 13, 13, 13, /* 20 - 29 */ - 13, 12, 12, 12, 12, 12, 12}; /* 30 - 36 */ + 0, 0, 64, 40, 32, 27, 24, 22, 21, 20, /* 0 - 9 */ + 19, 18, 17, 17, 16, 16, 16, 15, 15, 15, /* 10 - 19 */ + 14, 14, 14, 14, 13, 13, 13, 13, 13, 13, /* 20 - 29 */ + 13, 12, 12, 12, 12, 12, 12}; /* 30 - 36 */ #else #error "Need table for SIZEOF_LONG" #endif /* -** strtoul -** This is a general purpose routine for converting -** an ascii string to an integer in an arbitrary base. -** Leading white space is ignored. If 'base' is zero -** it looks for a leading 0b, 0o or 0x to tell which -** base. If these are absent it defaults to 10. -** Base must be 0 or between 2 and 36 (inclusive). -** If 'ptr' is non-NULL it will contain a pointer to -** the end of the scan. -** Errors due to bad pointers will probably result in -** exceptions - we don't check for them. +** strtoul +** This is a general purpose routine for converting +** an ascii string to an integer in an arbitrary base. +** Leading white space is ignored. If 'base' is zero +** it looks for a leading 0b, 0o or 0x to tell which +** base. If these are absent it defaults to 10. +** Base must be 0 or between 2 and 36 (inclusive). +** If 'ptr' is non-NULL it will contain a pointer to +** the end of the scan. +** Errors due to bad pointers will probably result in +** exceptions - we don't check for them. */ unsigned long PyOS_strtoul(register char *str, char **ptr, int base) { - register unsigned long result = 0; /* return value of the function */ - register int c; /* current input character */ - register int ovlimit; /* required digits to overflow */ - - /* skip leading white space */ - while (*str && isspace(Py_CHARMASK(*str))) - ++str; - - /* check for leading 0b, 0o or 0x for auto-base or base 16 */ - switch (base) { - case 0: /* look for leading 0b, 0o or 0x */ - if (*str == '0') { - ++str; - if (*str == 'x' || *str == 'X') { - /* there must be at least one digit after 0x */ - if (_PyLong_DigitValue[Py_CHARMASK(str[1])] >= 16) { - if (ptr) - *ptr = str; - return 0; - } - ++str; - base = 16; - } else if (*str == 'o' || *str == 'O') { - /* there must be at least one digit after 0o */ - if (_PyLong_DigitValue[Py_CHARMASK(str[1])] >= 8) { - if (ptr) - *ptr = str; - return 0; - } - ++str; - base = 8; - } else if (*str == 'b' || *str == 'B') { - /* there must be at least one digit after 0b */ - if (_PyLong_DigitValue[Py_CHARMASK(str[1])] >= 2) { - if (ptr) - *ptr = str; - return 0; - } - ++str; - base = 2; - } else { - /* skip all zeroes... */ - while (*str == '0') - ++str; - while (isspace(Py_CHARMASK(*str))) - ++str; - if (ptr) - *ptr = str; - return 0; - } - } - else - base = 10; - break; - - /* even with explicit base, skip leading 0? prefix */ - case 16: - if (*str == '0') { - ++str; - if (*str == 'x' || *str == 'X') { - /* there must be at least one digit after 0x */ - if (_PyLong_DigitValue[Py_CHARMASK(str[1])] >= 16) { - if (ptr) - *ptr = str; - return 0; - } - ++str; - } - } - break; - case 8: - if (*str == '0') { - ++str; - if (*str == 'o' || *str == 'O') { - /* there must be at least one digit after 0o */ - if (_PyLong_DigitValue[Py_CHARMASK(str[1])] >= 8) { - if (ptr) - *ptr = str; - return 0; - } - ++str; - } - } - break; - case 2: - if(*str == '0') { - ++str; - if (*str == 'b' || *str == 'B') { - /* there must be at least one digit after 0b */ - if (_PyLong_DigitValue[Py_CHARMASK(str[1])] >= 2) { - if (ptr) - *ptr = str; - return 0; - } - ++str; - } - } - break; - } - - /* catch silly bases */ - if (base < 2 || base > 36) { - if (ptr) - *ptr = str; - return 0; - } - - /* skip leading zeroes */ - while (*str == '0') - ++str; - - /* base is guaranteed to be in [2, 36] at this point */ - ovlimit = digitlimit[base]; - - /* do the conversion until non-digit character encountered */ - while ((c = _PyLong_DigitValue[Py_CHARMASK(*str)]) < base) { - if (ovlimit > 0) /* no overflow check required */ - result = result * base + c; - else { /* requires overflow check */ - register unsigned long temp_result; - - if (ovlimit < 0) /* guaranteed overflow */ - goto overflowed; - - /* there could be an overflow */ - /* check overflow just from shifting */ - if (result > smallmax[base]) - goto overflowed; - - result *= base; - - /* check overflow from the digit's value */ - temp_result = result + c; - if (temp_result < result) - goto overflowed; - - result = temp_result; - } - - ++str; - --ovlimit; - } - - /* set pointer to point to the last character scanned */ - if (ptr) - *ptr = str; + register unsigned long result = 0; /* return value of the function */ + register int c; /* current input character */ + register int ovlimit; /* required digits to overflow */ + + /* skip leading white space */ + while (*str && isspace(Py_CHARMASK(*str))) + ++str; + + /* check for leading 0b, 0o or 0x for auto-base or base 16 */ + switch (base) { + case 0: /* look for leading 0b, 0o or 0x */ + if (*str == '0') { + ++str; + if (*str == 'x' || *str == 'X') { + /* there must be at least one digit after 0x */ + if (_PyLong_DigitValue[Py_CHARMASK(str[1])] >= 16) { + if (ptr) + *ptr = str; + return 0; + } + ++str; + base = 16; + } else if (*str == 'o' || *str == 'O') { + /* there must be at least one digit after 0o */ + if (_PyLong_DigitValue[Py_CHARMASK(str[1])] >= 8) { + if (ptr) + *ptr = str; + return 0; + } + ++str; + base = 8; + } else if (*str == 'b' || *str == 'B') { + /* there must be at least one digit after 0b */ + if (_PyLong_DigitValue[Py_CHARMASK(str[1])] >= 2) { + if (ptr) + *ptr = str; + return 0; + } + ++str; + base = 2; + } else { + /* skip all zeroes... */ + while (*str == '0') + ++str; + while (isspace(Py_CHARMASK(*str))) + ++str; + if (ptr) + *ptr = str; + return 0; + } + } + else + base = 10; + break; + + /* even with explicit base, skip leading 0? prefix */ + case 16: + if (*str == '0') { + ++str; + if (*str == 'x' || *str == 'X') { + /* there must be at least one digit after 0x */ + if (_PyLong_DigitValue[Py_CHARMASK(str[1])] >= 16) { + if (ptr) + *ptr = str; + return 0; + } + ++str; + } + } + break; + case 8: + if (*str == '0') { + ++str; + if (*str == 'o' || *str == 'O') { + /* there must be at least one digit after 0o */ + if (_PyLong_DigitValue[Py_CHARMASK(str[1])] >= 8) { + if (ptr) + *ptr = str; + return 0; + } + ++str; + } + } + break; + case 2: + if(*str == '0') { + ++str; + if (*str == 'b' || *str == 'B') { + /* there must be at least one digit after 0b */ + if (_PyLong_DigitValue[Py_CHARMASK(str[1])] >= 2) { + if (ptr) + *ptr = str; + return 0; + } + ++str; + } + } + break; + } + + /* catch silly bases */ + if (base < 2 || base > 36) { + if (ptr) + *ptr = str; + return 0; + } + + /* skip leading zeroes */ + while (*str == '0') + ++str; + + /* base is guaranteed to be in [2, 36] at this point */ + ovlimit = digitlimit[base]; + + /* do the conversion until non-digit character encountered */ + while ((c = _PyLong_DigitValue[Py_CHARMASK(*str)]) < base) { + if (ovlimit > 0) /* no overflow check required */ + result = result * base + c; + else { /* requires overflow check */ + register unsigned long temp_result; + + if (ovlimit < 0) /* guaranteed overflow */ + goto overflowed; + + /* there could be an overflow */ + /* check overflow just from shifting */ + if (result > smallmax[base]) + goto overflowed; + + result *= base; + + /* check overflow from the digit's value */ + temp_result = result + c; + if (temp_result < result) + goto overflowed; + + result = temp_result; + } + + ++str; + --ovlimit; + } + + /* set pointer to point to the last character scanned */ + if (ptr) + *ptr = str; - return result; + return result; overflowed: - if (ptr) { - /* spool through remaining digit characters */ - while (_PyLong_DigitValue[Py_CHARMASK(*str)] < base) - ++str; - *ptr = str; - } - errno = ERANGE; - return (unsigned long)-1; + if (ptr) { + /* spool through remaining digit characters */ + while (_PyLong_DigitValue[Py_CHARMASK(*str)] < base) + ++str; + *ptr = str; + } + errno = ERANGE; + return (unsigned long)-1; } /* Checking for overflow in PyOS_strtol is a PITA; see comments * about PY_ABS_LONG_MIN in longobject.c. */ -#define PY_ABS_LONG_MIN (0-(unsigned long)LONG_MIN) +#define PY_ABS_LONG_MIN (0-(unsigned long)LONG_MIN) long PyOS_strtol(char *str, char **ptr, int base) { - long result; - unsigned long uresult; - char sign; - - while (*str && isspace(Py_CHARMASK(*str))) - str++; - - sign = *str; - if (sign == '+' || sign == '-') - str++; - - uresult = PyOS_strtoul(str, ptr, base); - - if (uresult <= (unsigned long)LONG_MAX) { - result = (long)uresult; - if (sign == '-') - result = -result; - } - else if (sign == '-' && uresult == PY_ABS_LONG_MIN) { - result = LONG_MIN; - } - else { - errno = ERANGE; - result = LONG_MAX; - } - return result; + long result; + unsigned long uresult; + char sign; + + while (*str && isspace(Py_CHARMASK(*str))) + str++; + + sign = *str; + if (sign == '+' || sign == '-') + str++; + + uresult = PyOS_strtoul(str, ptr, base); + + if (uresult <= (unsigned long)LONG_MAX) { + result = (long)uresult; + if (sign == '-') + result = -result; + } + else if (sign == '-' && uresult == PY_ABS_LONG_MIN) { + result = LONG_MIN; + } + else { + errno = ERANGE; + result = LONG_MAX; + } + return result; } Modified: python/branches/release31-maint/Python/opcode_targets.h ============================================================================== --- python/branches/release31-maint/Python/opcode_targets.h (original) +++ python/branches/release31-maint/Python/opcode_targets.h Sun May 9 18:14:21 2010 @@ -1,258 +1,258 @@ static void *opcode_targets[256] = { - &&_unknown_opcode, - &&TARGET_POP_TOP, - &&TARGET_ROT_TWO, - &&TARGET_ROT_THREE, - &&TARGET_DUP_TOP, - &&TARGET_ROT_FOUR, - &&_unknown_opcode, - &&_unknown_opcode, - &&_unknown_opcode, - &&TARGET_NOP, - &&TARGET_UNARY_POSITIVE, - &&TARGET_UNARY_NEGATIVE, - &&TARGET_UNARY_NOT, - &&_unknown_opcode, - &&_unknown_opcode, - &&TARGET_UNARY_INVERT, - &&_unknown_opcode, - &&_unknown_opcode, - &&_unknown_opcode, - &&TARGET_BINARY_POWER, - &&TARGET_BINARY_MULTIPLY, - &&_unknown_opcode, - &&TARGET_BINARY_MODULO, - &&TARGET_BINARY_ADD, - &&TARGET_BINARY_SUBTRACT, - &&TARGET_BINARY_SUBSCR, - &&TARGET_BINARY_FLOOR_DIVIDE, - &&TARGET_BINARY_TRUE_DIVIDE, - &&TARGET_INPLACE_FLOOR_DIVIDE, - &&TARGET_INPLACE_TRUE_DIVIDE, - &&_unknown_opcode, - &&_unknown_opcode, - &&_unknown_opcode, - &&_unknown_opcode, - &&_unknown_opcode, - &&_unknown_opcode, - &&_unknown_opcode, - &&_unknown_opcode, - &&_unknown_opcode, - &&_unknown_opcode, - &&_unknown_opcode, - &&_unknown_opcode, - &&_unknown_opcode, - &&_unknown_opcode, - &&_unknown_opcode, - &&_unknown_opcode, - &&_unknown_opcode, - &&_unknown_opcode, - &&_unknown_opcode, - &&_unknown_opcode, - &&_unknown_opcode, - &&_unknown_opcode, - &&_unknown_opcode, - &&_unknown_opcode, - &&TARGET_STORE_MAP, - &&TARGET_INPLACE_ADD, - &&TARGET_INPLACE_SUBTRACT, - &&TARGET_INPLACE_MULTIPLY, - &&_unknown_opcode, - &&TARGET_INPLACE_MODULO, - &&TARGET_STORE_SUBSCR, - &&TARGET_DELETE_SUBSCR, - &&TARGET_BINARY_LSHIFT, - &&TARGET_BINARY_RSHIFT, - &&TARGET_BINARY_AND, - &&TARGET_BINARY_XOR, - &&TARGET_BINARY_OR, - &&TARGET_INPLACE_POWER, - &&TARGET_GET_ITER, - &&TARGET_STORE_LOCALS, - &&TARGET_PRINT_EXPR, - &&TARGET_LOAD_BUILD_CLASS, - &&_unknown_opcode, - &&_unknown_opcode, - &&_unknown_opcode, - &&TARGET_INPLACE_LSHIFT, - &&TARGET_INPLACE_RSHIFT, - &&TARGET_INPLACE_AND, - &&TARGET_INPLACE_XOR, - &&TARGET_INPLACE_OR, - &&TARGET_BREAK_LOOP, - &&TARGET_WITH_CLEANUP, - &&_unknown_opcode, - &&TARGET_RETURN_VALUE, - &&TARGET_IMPORT_STAR, - &&_unknown_opcode, - &&TARGET_YIELD_VALUE, - &&TARGET_POP_BLOCK, - &&TARGET_END_FINALLY, - &&TARGET_POP_EXCEPT, - &&TARGET_STORE_NAME, - &&TARGET_DELETE_NAME, - &&TARGET_UNPACK_SEQUENCE, - &&TARGET_FOR_ITER, - &&TARGET_UNPACK_EX, - &&TARGET_STORE_ATTR, - &&TARGET_DELETE_ATTR, - &&TARGET_STORE_GLOBAL, - &&TARGET_DELETE_GLOBAL, - &&TARGET_DUP_TOPX, - &&TARGET_LOAD_CONST, - &&TARGET_LOAD_NAME, - &&TARGET_BUILD_TUPLE, - &&TARGET_BUILD_LIST, - &&TARGET_BUILD_SET, - &&TARGET_BUILD_MAP, - &&TARGET_LOAD_ATTR, - &&TARGET_COMPARE_OP, - &&TARGET_IMPORT_NAME, - &&TARGET_IMPORT_FROM, - &&TARGET_JUMP_FORWARD, - &&TARGET_JUMP_IF_FALSE_OR_POP, - &&TARGET_JUMP_IF_TRUE_OR_POP, - &&TARGET_JUMP_ABSOLUTE, - &&TARGET_POP_JUMP_IF_FALSE, - &&TARGET_POP_JUMP_IF_TRUE, - &&TARGET_LOAD_GLOBAL, - &&_unknown_opcode, - &&_unknown_opcode, - &&TARGET_CONTINUE_LOOP, - &&TARGET_SETUP_LOOP, - &&TARGET_SETUP_EXCEPT, - &&TARGET_SETUP_FINALLY, - &&_unknown_opcode, - &&TARGET_LOAD_FAST, - &&TARGET_STORE_FAST, - &&TARGET_DELETE_FAST, - &&_unknown_opcode, - &&_unknown_opcode, - &&_unknown_opcode, - &&TARGET_RAISE_VARARGS, - &&TARGET_CALL_FUNCTION, - &&TARGET_MAKE_FUNCTION, - &&TARGET_BUILD_SLICE, - &&TARGET_MAKE_CLOSURE, - &&TARGET_LOAD_CLOSURE, - &&TARGET_LOAD_DEREF, - &&TARGET_STORE_DEREF, - &&_unknown_opcode, - &&_unknown_opcode, - &&TARGET_CALL_FUNCTION_VAR, - &&TARGET_CALL_FUNCTION_KW, - &&TARGET_CALL_FUNCTION_VAR_KW, - &&TARGET_EXTENDED_ARG, - &&_unknown_opcode, - &&TARGET_LIST_APPEND, - &&TARGET_SET_ADD, - &&TARGET_MAP_ADD, - &&_unknown_opcode, - &&_unknown_opcode, - &&_unknown_opcode, - &&_unknown_opcode, - &&_unknown_opcode, - &&_unknown_opcode, - &&_unknown_opcode, - &&_unknown_opcode, - &&_unknown_opcode, - &&_unknown_opcode, - &&_unknown_opcode, - &&_unknown_opcode, - &&_unknown_opcode, - &&_unknown_opcode, - &&_unknown_opcode, - &&_unknown_opcode, - &&_unknown_opcode, - &&_unknown_opcode, - &&_unknown_opcode, - &&_unknown_opcode, - &&_unknown_opcode, - &&_unknown_opcode, - &&_unknown_opcode, - &&_unknown_opcode, - &&_unknown_opcode, - &&_unknown_opcode, - &&_unknown_opcode, - &&_unknown_opcode, - &&_unknown_opcode, - &&_unknown_opcode, - &&_unknown_opcode, - &&_unknown_opcode, - &&_unknown_opcode, - &&_unknown_opcode, - &&_unknown_opcode, - &&_unknown_opcode, - &&_unknown_opcode, - &&_unknown_opcode, - &&_unknown_opcode, - &&_unknown_opcode, - &&_unknown_opcode, - &&_unknown_opcode, - &&_unknown_opcode, - &&_unknown_opcode, - &&_unknown_opcode, - &&_unknown_opcode, - &&_unknown_opcode, - &&_unknown_opcode, - &&_unknown_opcode, - &&_unknown_opcode, - &&_unknown_opcode, - &&_unknown_opcode, - &&_unknown_opcode, - &&_unknown_opcode, - &&_unknown_opcode, - &&_unknown_opcode, - &&_unknown_opcode, - &&_unknown_opcode, - &&_unknown_opcode, - &&_unknown_opcode, - &&_unknown_opcode, - &&_unknown_opcode, - &&_unknown_opcode, - &&_unknown_opcode, - &&_unknown_opcode, - &&_unknown_opcode, - &&_unknown_opcode, - &&_unknown_opcode, - &&_unknown_opcode, - &&_unknown_opcode, - &&_unknown_opcode, - &&_unknown_opcode, - &&_unknown_opcode, - &&_unknown_opcode, - &&_unknown_opcode, - &&_unknown_opcode, - &&_unknown_opcode, - &&_unknown_opcode, - &&_unknown_opcode, - &&_unknown_opcode, - &&_unknown_opcode, - &&_unknown_opcode, - &&_unknown_opcode, - &&_unknown_opcode, - &&_unknown_opcode, - &&_unknown_opcode, - &&_unknown_opcode, - &&_unknown_opcode, - &&_unknown_opcode, - &&_unknown_opcode, - &&_unknown_opcode, - &&_unknown_opcode, - &&_unknown_opcode, - &&_unknown_opcode, - &&_unknown_opcode, - &&_unknown_opcode, - &&_unknown_opcode, - &&_unknown_opcode, - &&_unknown_opcode, - &&_unknown_opcode, - &&_unknown_opcode, - &&_unknown_opcode, - &&_unknown_opcode, - &&_unknown_opcode, - &&_unknown_opcode, - &&_unknown_opcode, - &&_unknown_opcode, - &&_unknown_opcode + &&_unknown_opcode, + &&TARGET_POP_TOP, + &&TARGET_ROT_TWO, + &&TARGET_ROT_THREE, + &&TARGET_DUP_TOP, + &&TARGET_ROT_FOUR, + &&_unknown_opcode, + &&_unknown_opcode, + &&_unknown_opcode, + &&TARGET_NOP, + &&TARGET_UNARY_POSITIVE, + &&TARGET_UNARY_NEGATIVE, + &&TARGET_UNARY_NOT, + &&_unknown_opcode, + &&_unknown_opcode, + &&TARGET_UNARY_INVERT, + &&_unknown_opcode, + &&_unknown_opcode, + &&_unknown_opcode, + &&TARGET_BINARY_POWER, + &&TARGET_BINARY_MULTIPLY, + &&_unknown_opcode, + &&TARGET_BINARY_MODULO, + &&TARGET_BINARY_ADD, + &&TARGET_BINARY_SUBTRACT, + &&TARGET_BINARY_SUBSCR, + &&TARGET_BINARY_FLOOR_DIVIDE, + &&TARGET_BINARY_TRUE_DIVIDE, + &&TARGET_INPLACE_FLOOR_DIVIDE, + &&TARGET_INPLACE_TRUE_DIVIDE, + &&_unknown_opcode, + &&_unknown_opcode, + &&_unknown_opcode, + &&_unknown_opcode, + &&_unknown_opcode, + &&_unknown_opcode, + &&_unknown_opcode, + &&_unknown_opcode, + &&_unknown_opcode, + &&_unknown_opcode, + &&_unknown_opcode, + &&_unknown_opcode, + &&_unknown_opcode, + &&_unknown_opcode, + &&_unknown_opcode, + &&_unknown_opcode, + &&_unknown_opcode, + &&_unknown_opcode, + &&_unknown_opcode, + &&_unknown_opcode, + &&_unknown_opcode, + &&_unknown_opcode, + &&_unknown_opcode, + &&_unknown_opcode, + &&TARGET_STORE_MAP, + &&TARGET_INPLACE_ADD, + &&TARGET_INPLACE_SUBTRACT, + &&TARGET_INPLACE_MULTIPLY, + &&_unknown_opcode, + &&TARGET_INPLACE_MODULO, + &&TARGET_STORE_SUBSCR, + &&TARGET_DELETE_SUBSCR, + &&TARGET_BINARY_LSHIFT, + &&TARGET_BINARY_RSHIFT, + &&TARGET_BINARY_AND, + &&TARGET_BINARY_XOR, + &&TARGET_BINARY_OR, + &&TARGET_INPLACE_POWER, + &&TARGET_GET_ITER, + &&TARGET_STORE_LOCALS, + &&TARGET_PRINT_EXPR, + &&TARGET_LOAD_BUILD_CLASS, + &&_unknown_opcode, + &&_unknown_opcode, + &&_unknown_opcode, + &&TARGET_INPLACE_LSHIFT, + &&TARGET_INPLACE_RSHIFT, + &&TARGET_INPLACE_AND, + &&TARGET_INPLACE_XOR, + &&TARGET_INPLACE_OR, + &&TARGET_BREAK_LOOP, + &&TARGET_WITH_CLEANUP, + &&_unknown_opcode, + &&TARGET_RETURN_VALUE, + &&TARGET_IMPORT_STAR, + &&_unknown_opcode, + &&TARGET_YIELD_VALUE, + &&TARGET_POP_BLOCK, + &&TARGET_END_FINALLY, + &&TARGET_POP_EXCEPT, + &&TARGET_STORE_NAME, + &&TARGET_DELETE_NAME, + &&TARGET_UNPACK_SEQUENCE, + &&TARGET_FOR_ITER, + &&TARGET_UNPACK_EX, + &&TARGET_STORE_ATTR, + &&TARGET_DELETE_ATTR, + &&TARGET_STORE_GLOBAL, + &&TARGET_DELETE_GLOBAL, + &&TARGET_DUP_TOPX, + &&TARGET_LOAD_CONST, + &&TARGET_LOAD_NAME, + &&TARGET_BUILD_TUPLE, + &&TARGET_BUILD_LIST, + &&TARGET_BUILD_SET, + &&TARGET_BUILD_MAP, + &&TARGET_LOAD_ATTR, + &&TARGET_COMPARE_OP, + &&TARGET_IMPORT_NAME, + &&TARGET_IMPORT_FROM, + &&TARGET_JUMP_FORWARD, + &&TARGET_JUMP_IF_FALSE_OR_POP, + &&TARGET_JUMP_IF_TRUE_OR_POP, + &&TARGET_JUMP_ABSOLUTE, + &&TARGET_POP_JUMP_IF_FALSE, + &&TARGET_POP_JUMP_IF_TRUE, + &&TARGET_LOAD_GLOBAL, + &&_unknown_opcode, + &&_unknown_opcode, + &&TARGET_CONTINUE_LOOP, + &&TARGET_SETUP_LOOP, + &&TARGET_SETUP_EXCEPT, + &&TARGET_SETUP_FINALLY, + &&_unknown_opcode, + &&TARGET_LOAD_FAST, + &&TARGET_STORE_FAST, + &&TARGET_DELETE_FAST, + &&_unknown_opcode, + &&_unknown_opcode, + &&_unknown_opcode, + &&TARGET_RAISE_VARARGS, + &&TARGET_CALL_FUNCTION, + &&TARGET_MAKE_FUNCTION, + &&TARGET_BUILD_SLICE, + &&TARGET_MAKE_CLOSURE, + &&TARGET_LOAD_CLOSURE, + &&TARGET_LOAD_DEREF, + &&TARGET_STORE_DEREF, + &&_unknown_opcode, + &&_unknown_opcode, + &&TARGET_CALL_FUNCTION_VAR, + &&TARGET_CALL_FUNCTION_KW, + &&TARGET_CALL_FUNCTION_VAR_KW, + &&TARGET_EXTENDED_ARG, + &&_unknown_opcode, + &&TARGET_LIST_APPEND, + &&TARGET_SET_ADD, + &&TARGET_MAP_ADD, + &&_unknown_opcode, + &&_unknown_opcode, + &&_unknown_opcode, + &&_unknown_opcode, + &&_unknown_opcode, + &&_unknown_opcode, + &&_unknown_opcode, + &&_unknown_opcode, + &&_unknown_opcode, + &&_unknown_opcode, + &&_unknown_opcode, + &&_unknown_opcode, + &&_unknown_opcode, + &&_unknown_opcode, + &&_unknown_opcode, + &&_unknown_opcode, + &&_unknown_opcode, + &&_unknown_opcode, + &&_unknown_opcode, + &&_unknown_opcode, + &&_unknown_opcode, + &&_unknown_opcode, + &&_unknown_opcode, + &&_unknown_opcode, + &&_unknown_opcode, + &&_unknown_opcode, + &&_unknown_opcode, + &&_unknown_opcode, + &&_unknown_opcode, + &&_unknown_opcode, + &&_unknown_opcode, + &&_unknown_opcode, + &&_unknown_opcode, + &&_unknown_opcode, + &&_unknown_opcode, + &&_unknown_opcode, + &&_unknown_opcode, + &&_unknown_opcode, + &&_unknown_opcode, + &&_unknown_opcode, + &&_unknown_opcode, + &&_unknown_opcode, + &&_unknown_opcode, + &&_unknown_opcode, + &&_unknown_opcode, + &&_unknown_opcode, + &&_unknown_opcode, + &&_unknown_opcode, + &&_unknown_opcode, + &&_unknown_opcode, + &&_unknown_opcode, + &&_unknown_opcode, + &&_unknown_opcode, + &&_unknown_opcode, + &&_unknown_opcode, + &&_unknown_opcode, + &&_unknown_opcode, + &&_unknown_opcode, + &&_unknown_opcode, + &&_unknown_opcode, + &&_unknown_opcode, + &&_unknown_opcode, + &&_unknown_opcode, + &&_unknown_opcode, + &&_unknown_opcode, + &&_unknown_opcode, + &&_unknown_opcode, + &&_unknown_opcode, + &&_unknown_opcode, + &&_unknown_opcode, + &&_unknown_opcode, + &&_unknown_opcode, + &&_unknown_opcode, + &&_unknown_opcode, + &&_unknown_opcode, + &&_unknown_opcode, + &&_unknown_opcode, + &&_unknown_opcode, + &&_unknown_opcode, + &&_unknown_opcode, + &&_unknown_opcode, + &&_unknown_opcode, + &&_unknown_opcode, + &&_unknown_opcode, + &&_unknown_opcode, + &&_unknown_opcode, + &&_unknown_opcode, + &&_unknown_opcode, + &&_unknown_opcode, + &&_unknown_opcode, + &&_unknown_opcode, + &&_unknown_opcode, + &&_unknown_opcode, + &&_unknown_opcode, + &&_unknown_opcode, + &&_unknown_opcode, + &&_unknown_opcode, + &&_unknown_opcode, + &&_unknown_opcode, + &&_unknown_opcode, + &&_unknown_opcode, + &&_unknown_opcode, + &&_unknown_opcode, + &&_unknown_opcode, + &&_unknown_opcode, + &&_unknown_opcode, + &&_unknown_opcode, + &&_unknown_opcode }; Modified: python/branches/release31-maint/Python/peephole.c ============================================================================== --- python/branches/release31-maint/Python/peephole.c (original) +++ python/branches/release31-maint/Python/peephole.c Sun May 9 18:14:21 2010 @@ -12,256 +12,256 @@ #include "opcode.h" #define GETARG(arr, i) ((int)((arr[i+2]<<8) + arr[i+1])) -#define UNCONDITIONAL_JUMP(op) (op==JUMP_ABSOLUTE || op==JUMP_FORWARD) +#define UNCONDITIONAL_JUMP(op) (op==JUMP_ABSOLUTE || op==JUMP_FORWARD) #define CONDITIONAL_JUMP(op) (op==POP_JUMP_IF_FALSE || op==POP_JUMP_IF_TRUE \ - || op==JUMP_IF_FALSE_OR_POP || op==JUMP_IF_TRUE_OR_POP) + || op==JUMP_IF_FALSE_OR_POP || op==JUMP_IF_TRUE_OR_POP) #define ABSOLUTE_JUMP(op) (op==JUMP_ABSOLUTE || op==CONTINUE_LOOP \ - || op==POP_JUMP_IF_FALSE || op==POP_JUMP_IF_TRUE \ - || op==JUMP_IF_FALSE_OR_POP || op==JUMP_IF_TRUE_OR_POP) + || op==POP_JUMP_IF_FALSE || op==POP_JUMP_IF_TRUE \ + || op==JUMP_IF_FALSE_OR_POP || op==JUMP_IF_TRUE_OR_POP) #define JUMPS_ON_TRUE(op) (op==POP_JUMP_IF_TRUE || op==JUMP_IF_TRUE_OR_POP) #define GETJUMPTGT(arr, i) (GETARG(arr,i) + (ABSOLUTE_JUMP(arr[i]) ? 0 : i+3)) #define SETARG(arr, i, val) arr[i+2] = val>>8; arr[i+1] = val & 255 #define CODESIZE(op) (HAS_ARG(op) ? 3 : 1) #define ISBASICBLOCK(blocks, start, bytes) \ - (blocks[start]==blocks[start+bytes-1]) + (blocks[start]==blocks[start+bytes-1]) /* Replace LOAD_CONST c1. LOAD_CONST c2 ... LOAD_CONST cn BUILD_TUPLE n - with LOAD_CONST (c1, c2, ... cn). + with LOAD_CONST (c1, c2, ... cn). The consts table must still be in list form so that the new constant (c1, c2, ... cn) can be appended. Called with codestr pointing to the first LOAD_CONST. - Bails out with no change if one or more of the LOAD_CONSTs is missing. + Bails out with no change if one or more of the LOAD_CONSTs is missing. Also works for BUILD_LIST when followed by an "in" or "not in" test. */ static int tuple_of_constants(unsigned char *codestr, Py_ssize_t n, PyObject *consts) { - PyObject *newconst, *constant; - Py_ssize_t i, arg, len_consts; + PyObject *newconst, *constant; + Py_ssize_t i, arg, len_consts; - /* Pre-conditions */ - assert(PyList_CheckExact(consts)); - assert(codestr[n*3] == BUILD_TUPLE || codestr[n*3] == BUILD_LIST); - assert(GETARG(codestr, (n*3)) == n); - for (i=0 ; i 20) { - Py_DECREF(newconst); - return 0; - } - - /* Append folded constant into consts table */ - len_consts = PyList_GET_SIZE(consts); - if (PyList_Append(consts, newconst)) { - Py_DECREF(newconst); - return 0; - } - Py_DECREF(newconst); - - /* Write NOP NOP NOP NOP LOAD_CONST newconst */ - memset(codestr, NOP, 4); - codestr[4] = LOAD_CONST; - SETARG(codestr, 4, len_consts); - return 1; + PyObject *newconst, *v, *w; + Py_ssize_t len_consts, size; + int opcode; + + /* Pre-conditions */ + assert(PyList_CheckExact(consts)); + assert(codestr[0] == LOAD_CONST); + assert(codestr[3] == LOAD_CONST); + + /* Create new constant */ + v = PyList_GET_ITEM(consts, GETARG(codestr, 0)); + w = PyList_GET_ITEM(consts, GETARG(codestr, 3)); + opcode = codestr[6]; + switch (opcode) { + case BINARY_POWER: + newconst = PyNumber_Power(v, w, Py_None); + break; + case BINARY_MULTIPLY: + newconst = PyNumber_Multiply(v, w); + break; + case BINARY_TRUE_DIVIDE: + newconst = PyNumber_TrueDivide(v, w); + break; + case BINARY_FLOOR_DIVIDE: + newconst = PyNumber_FloorDivide(v, w); + break; + case BINARY_MODULO: + newconst = PyNumber_Remainder(v, w); + break; + case BINARY_ADD: + newconst = PyNumber_Add(v, w); + break; + case BINARY_SUBTRACT: + newconst = PyNumber_Subtract(v, w); + break; + case BINARY_SUBSCR: + newconst = PyObject_GetItem(v, w); + break; + case BINARY_LSHIFT: + newconst = PyNumber_Lshift(v, w); + break; + case BINARY_RSHIFT: + newconst = PyNumber_Rshift(v, w); + break; + case BINARY_AND: + newconst = PyNumber_And(v, w); + break; + case BINARY_XOR: + newconst = PyNumber_Xor(v, w); + break; + case BINARY_OR: + newconst = PyNumber_Or(v, w); + break; + default: + /* Called with an unknown opcode */ + PyErr_Format(PyExc_SystemError, + "unexpected binary operation %d on a constant", + opcode); + return 0; + } + if (newconst == NULL) { + PyErr_Clear(); + return 0; + } + size = PyObject_Size(newconst); + if (size == -1) + PyErr_Clear(); + else if (size > 20) { + Py_DECREF(newconst); + return 0; + } + + /* Append folded constant into consts table */ + len_consts = PyList_GET_SIZE(consts); + if (PyList_Append(consts, newconst)) { + Py_DECREF(newconst); + return 0; + } + Py_DECREF(newconst); + + /* Write NOP NOP NOP NOP LOAD_CONST newconst */ + memset(codestr, NOP, 4); + codestr[4] = LOAD_CONST; + SETARG(codestr, 4, len_consts); + return 1; } static int fold_unaryops_on_constants(unsigned char *codestr, PyObject *consts) { - PyObject *newconst=NULL, *v; - Py_ssize_t len_consts; - int opcode; - - /* Pre-conditions */ - assert(PyList_CheckExact(consts)); - assert(codestr[0] == LOAD_CONST); - - /* Create new constant */ - v = PyList_GET_ITEM(consts, GETARG(codestr, 0)); - opcode = codestr[3]; - switch (opcode) { - case UNARY_NEGATIVE: - /* Preserve the sign of -0.0 */ - if (PyObject_IsTrue(v) == 1) - newconst = PyNumber_Negative(v); - break; - case UNARY_INVERT: - newconst = PyNumber_Invert(v); - break; - default: - /* Called with an unknown opcode */ - PyErr_Format(PyExc_SystemError, - "unexpected unary operation %d on a constant", - opcode); - return 0; - } - if (newconst == NULL) { - PyErr_Clear(); - return 0; - } - - /* Append folded constant into consts table */ - len_consts = PyList_GET_SIZE(consts); - if (PyList_Append(consts, newconst)) { - Py_DECREF(newconst); - return 0; - } - Py_DECREF(newconst); - - /* Write NOP LOAD_CONST newconst */ - codestr[0] = NOP; - codestr[1] = LOAD_CONST; - SETARG(codestr, 1, len_consts); - return 1; + PyObject *newconst=NULL, *v; + Py_ssize_t len_consts; + int opcode; + + /* Pre-conditions */ + assert(PyList_CheckExact(consts)); + assert(codestr[0] == LOAD_CONST); + + /* Create new constant */ + v = PyList_GET_ITEM(consts, GETARG(codestr, 0)); + opcode = codestr[3]; + switch (opcode) { + case UNARY_NEGATIVE: + /* Preserve the sign of -0.0 */ + if (PyObject_IsTrue(v) == 1) + newconst = PyNumber_Negative(v); + break; + case UNARY_INVERT: + newconst = PyNumber_Invert(v); + break; + default: + /* Called with an unknown opcode */ + PyErr_Format(PyExc_SystemError, + "unexpected unary operation %d on a constant", + opcode); + return 0; + } + if (newconst == NULL) { + PyErr_Clear(); + return 0; + } + + /* Append folded constant into consts table */ + len_consts = PyList_GET_SIZE(consts); + if (PyList_Append(consts, newconst)) { + Py_DECREF(newconst); + return 0; + } + Py_DECREF(newconst); + + /* Write NOP LOAD_CONST newconst */ + codestr[0] = NOP; + codestr[1] = LOAD_CONST; + SETARG(codestr, 1, len_consts); + return 1; } static unsigned int * markblocks(unsigned char *code, Py_ssize_t len) { - unsigned int *blocks = (unsigned int *)PyMem_Malloc(len*sizeof(int)); - int i,j, opcode, blockcnt = 0; + unsigned int *blocks = (unsigned int *)PyMem_Malloc(len*sizeof(int)); + int i,j, opcode, blockcnt = 0; - if (blocks == NULL) { - PyErr_NoMemory(); - return NULL; - } - memset(blocks, 0, len*sizeof(int)); - - /* Mark labels in the first pass */ - for (i=0 ; i= 255. EXTENDED_ARG can appear before MAKE_FUNCTION; in this case both opcodes are skipped. EXTENDED_ARG preceding any other opcode causes the optimizer to bail. Optimizations are restricted to simple transformations occuring within a - single basic block. All transformations keep the code size the same or - smaller. For those that reduce size, the gaps are initially filled with - NOPs. Later those NOPs are removed and the jump addresses retargeted in + single basic block. All transformations keep the code size the same or + smaller. For those that reduce size, the gaps are initially filled with + NOPs. Later those NOPs are removed and the jump addresses retargeted in a single pass. Line numbering is adjusted accordingly. */ PyObject * PyCode_Optimize(PyObject *code, PyObject* consts, PyObject *names, PyObject *lineno_obj) { - Py_ssize_t i, j, codelen; - int nops, h, adj; - int tgt, tgttgt, opcode; - unsigned char *codestr = NULL; - unsigned char *lineno; - int *addrmap = NULL; - int new_line, cum_orig_line, last_line, tabsiz; - int cumlc=0, lastlc=0; /* Count runs of consecutive LOAD_CONSTs */ - unsigned int *blocks = NULL; - char *name; - - /* Bail out if an exception is set */ - if (PyErr_Occurred()) - goto exitError; - - /* Bypass optimization when the lineno table is too complex */ - assert(PyBytes_Check(lineno_obj)); - lineno = (unsigned char*)PyBytes_AS_STRING(lineno_obj); - tabsiz = PyBytes_GET_SIZE(lineno_obj); - if (memchr(lineno, 255, tabsiz) != NULL) - goto exitUnchanged; - - /* Avoid situations where jump retargeting could overflow */ - assert(PyBytes_Check(code)); - codelen = PyBytes_GET_SIZE(code); - if (codelen > 32700) - goto exitUnchanged; - - /* Make a modifiable copy of the code string */ - codestr = (unsigned char *)PyMem_Malloc(codelen); - if (codestr == NULL) - goto exitError; - codestr = (unsigned char *)memcpy(codestr, - PyBytes_AS_STRING(code), codelen); - - /* Verify that RETURN_VALUE terminates the codestring. This allows - the various transformation patterns to look ahead several - instructions without additional checks to make sure they are not - looking beyond the end of the code string. - */ - if (codestr[codelen-1] != RETURN_VALUE) - goto exitUnchanged; - - /* Mapping to new jump targets after NOPs are removed */ - addrmap = (int *)PyMem_Malloc(codelen * sizeof(int)); - if (addrmap == NULL) - goto exitError; - - blocks = markblocks(codestr, codelen); - if (blocks == NULL) - goto exitError; - assert(PyList_Check(consts)); - - for (i=0 ; i a is not b - not a in b --> a not in b - not a is not b --> a is b - not a not in b --> a in b - */ - case COMPARE_OP: - j = GETARG(codestr, i); - if (j < 6 || j > 9 || - codestr[i+3] != UNARY_NOT || - !ISBASICBLOCK(blocks,i,4)) - continue; - SETARG(codestr, i, (j^1)); - codestr[i+3] = NOP; - break; - - /* Replace LOAD_GLOBAL/LOAD_NAME None/True/False - with LOAD_CONST None/True/False */ - case LOAD_NAME: - case LOAD_GLOBAL: - j = GETARG(codestr, i); - name = _PyUnicode_AsString(PyTuple_GET_ITEM(names, j)); - h = load_global(codestr, i, name, consts); - if (h < 0) - goto exitError; - else if (h == 0) - continue; - cumlc = lastlc + 1; - break; - - /* Skip over LOAD_CONST trueconst - POP_JUMP_IF_FALSE xx. This improves - "while 1" performance. */ - case LOAD_CONST: - cumlc = lastlc + 1; - j = GETARG(codestr, i); - if (codestr[i+3] != POP_JUMP_IF_FALSE || - !ISBASICBLOCK(blocks,i,6) || - !PyObject_IsTrue(PyList_GET_ITEM(consts, j))) - continue; - memset(codestr+i, NOP, 6); - cumlc = 0; - break; - - /* Try to fold tuples of constants (includes a case for lists - which are only used for "in" and "not in" tests). - Skip over BUILD_SEQN 1 UNPACK_SEQN 1. - Replace BUILD_SEQN 2 UNPACK_SEQN 2 with ROT2. - Replace BUILD_SEQN 3 UNPACK_SEQN 3 with ROT3 ROT2. */ - case BUILD_TUPLE: - case BUILD_LIST: - j = GETARG(codestr, i); - h = i - 3 * j; - if (h >= 0 && - j <= lastlc && - ((opcode == BUILD_TUPLE && - ISBASICBLOCK(blocks, h, 3*(j+1))) || - (opcode == BUILD_LIST && - codestr[i+3]==COMPARE_OP && - ISBASICBLOCK(blocks, h, 3*(j+2)) && - (GETARG(codestr,i+3)==6 || - GETARG(codestr,i+3)==7))) && - tuple_of_constants(&codestr[h], j, consts)) { - assert(codestr[i] == LOAD_CONST); - cumlc = 1; - break; - } - if (codestr[i+3] != UNPACK_SEQUENCE || - !ISBASICBLOCK(blocks,i,6) || - j != GETARG(codestr, i+3)) - continue; - if (j == 1) { - memset(codestr+i, NOP, 6); - } else if (j == 2) { - codestr[i] = ROT_TWO; - memset(codestr+i+1, NOP, 5); - } else if (j == 3) { - codestr[i] = ROT_THREE; - codestr[i+1] = ROT_TWO; - memset(codestr+i+2, NOP, 4); - } - break; - - /* Fold binary ops on constants. - LOAD_CONST c1 LOAD_CONST c2 BINOP --> LOAD_CONST binop(c1,c2) */ - case BINARY_POWER: - case BINARY_MULTIPLY: - case BINARY_TRUE_DIVIDE: - case BINARY_FLOOR_DIVIDE: - case BINARY_MODULO: - case BINARY_ADD: - case BINARY_SUBTRACT: - case BINARY_SUBSCR: - case BINARY_LSHIFT: - case BINARY_RSHIFT: - case BINARY_AND: - case BINARY_XOR: - case BINARY_OR: - if (lastlc >= 2 && - ISBASICBLOCK(blocks, i-6, 7) && - fold_binops_on_constants(&codestr[i-6], consts)) { - i -= 2; - assert(codestr[i] == LOAD_CONST); - cumlc = 1; - } - break; - - /* Fold unary ops on constants. - LOAD_CONST c1 UNARY_OP --> LOAD_CONST unary_op(c) */ - case UNARY_NEGATIVE: - case UNARY_INVERT: - if (lastlc >= 1 && - ISBASICBLOCK(blocks, i-3, 4) && - fold_unaryops_on_constants(&codestr[i-3], consts)) { - i -= 2; - assert(codestr[i] == LOAD_CONST); - cumlc = 1; - } - break; - - /* Simplify conditional jump to conditional jump where the - result of the first test implies the success of a similar - test or the failure of the opposite test. - Arises in code like: - "if a and b:" - "if a or b:" - "a and b or c" - "(a and b) and c" - x:JUMP_IF_FALSE_OR_POP y y:JUMP_IF_FALSE_OR_POP z - --> x:JUMP_IF_FALSE_OR_POP z - x:JUMP_IF_FALSE_OR_POP y y:JUMP_IF_TRUE_OR_POP z - --> x:POP_JUMP_IF_FALSE y+3 - where y+3 is the instruction following the second test. - */ - case JUMP_IF_FALSE_OR_POP: - case JUMP_IF_TRUE_OR_POP: - tgt = GETJUMPTGT(codestr, i); - j = codestr[tgt]; - if (CONDITIONAL_JUMP(j)) { - /* NOTE: all possible jumps here are - absolute! */ - if (JUMPS_ON_TRUE(j) == JUMPS_ON_TRUE(opcode)) { - /* The second jump will be - taken iff the first is. */ - tgttgt = GETJUMPTGT(codestr, tgt); - /* The current opcode inherits - its target's stack behaviour */ - codestr[i] = j; - SETARG(codestr, i, tgttgt); - goto reoptimize_current; - } else { - /* The second jump is not taken - if the first is (so jump past - it), and all conditional - jumps pop their argument when - they're not taken (so change - the first jump to pop its - argument when it's taken). */ - if (JUMPS_ON_TRUE(opcode)) - codestr[i] = POP_JUMP_IF_TRUE; - else - codestr[i] = POP_JUMP_IF_FALSE; - SETARG(codestr, i, (tgt + 3)); - goto reoptimize_current; - } - } - /* Intentional fallthrough */ - - /* Replace jumps to unconditional jumps */ - case POP_JUMP_IF_FALSE: - case POP_JUMP_IF_TRUE: - case FOR_ITER: - case JUMP_FORWARD: - case JUMP_ABSOLUTE: - case CONTINUE_LOOP: - case SETUP_LOOP: - case SETUP_EXCEPT: - case SETUP_FINALLY: - tgt = GETJUMPTGT(codestr, i); - /* Replace JUMP_* to a RETURN into just a RETURN */ - if (UNCONDITIONAL_JUMP(opcode) && - codestr[tgt] == RETURN_VALUE) { - codestr[i] = RETURN_VALUE; - memset(codestr+i+1, NOP, 2); - continue; - } - if (!UNCONDITIONAL_JUMP(codestr[tgt])) - continue; - tgttgt = GETJUMPTGT(codestr, tgt); - if (opcode == JUMP_FORWARD) /* JMP_ABS can go backwards */ - opcode = JUMP_ABSOLUTE; - if (!ABSOLUTE_JUMP(opcode)) - tgttgt -= i + 3; /* Calc relative jump addr */ - if (tgttgt < 0) /* No backward relative jumps */ - continue; - codestr[i] = opcode; - SETARG(codestr, i, tgttgt); - break; - - case EXTENDED_ARG: - if (codestr[i+3] != MAKE_FUNCTION) - goto exitUnchanged; - /* don't visit MAKE_FUNCTION as GETARG will be wrong */ - i += 3; - break; - - /* Replace RETURN LOAD_CONST None RETURN with just RETURN */ - /* Remove unreachable JUMPs after RETURN */ - case RETURN_VALUE: - if (i+4 >= codelen) - continue; - if (codestr[i+4] == RETURN_VALUE && - ISBASICBLOCK(blocks,i,5)) - memset(codestr+i+1, NOP, 4); - else if (UNCONDITIONAL_JUMP(codestr[i+1]) && - ISBASICBLOCK(blocks,i,4)) - memset(codestr+i+1, NOP, 3); - break; - } - } - - /* Fixup linenotab */ - for (i=0, nops=0 ; i 32700) + goto exitUnchanged; + + /* Make a modifiable copy of the code string */ + codestr = (unsigned char *)PyMem_Malloc(codelen); + if (codestr == NULL) + goto exitError; + codestr = (unsigned char *)memcpy(codestr, + PyBytes_AS_STRING(code), codelen); + + /* Verify that RETURN_VALUE terminates the codestring. This allows + the various transformation patterns to look ahead several + instructions without additional checks to make sure they are not + looking beyond the end of the code string. + */ + if (codestr[codelen-1] != RETURN_VALUE) + goto exitUnchanged; + + /* Mapping to new jump targets after NOPs are removed */ + addrmap = (int *)PyMem_Malloc(codelen * sizeof(int)); + if (addrmap == NULL) + goto exitError; + + blocks = markblocks(codestr, codelen); + if (blocks == NULL) + goto exitError; + assert(PyList_Check(consts)); + + for (i=0 ; i a is not b + not a in b --> a not in b + not a is not b --> a is b + not a not in b --> a in b + */ + case COMPARE_OP: + j = GETARG(codestr, i); + if (j < 6 || j > 9 || + codestr[i+3] != UNARY_NOT || + !ISBASICBLOCK(blocks,i,4)) + continue; + SETARG(codestr, i, (j^1)); + codestr[i+3] = NOP; + break; + + /* Replace LOAD_GLOBAL/LOAD_NAME None/True/False + with LOAD_CONST None/True/False */ + case LOAD_NAME: + case LOAD_GLOBAL: + j = GETARG(codestr, i); + name = _PyUnicode_AsString(PyTuple_GET_ITEM(names, j)); + h = load_global(codestr, i, name, consts); + if (h < 0) + goto exitError; + else if (h == 0) + continue; + cumlc = lastlc + 1; + break; + + /* Skip over LOAD_CONST trueconst + POP_JUMP_IF_FALSE xx. This improves + "while 1" performance. */ + case LOAD_CONST: + cumlc = lastlc + 1; + j = GETARG(codestr, i); + if (codestr[i+3] != POP_JUMP_IF_FALSE || + !ISBASICBLOCK(blocks,i,6) || + !PyObject_IsTrue(PyList_GET_ITEM(consts, j))) + continue; + memset(codestr+i, NOP, 6); + cumlc = 0; + break; + + /* Try to fold tuples of constants (includes a case for lists + which are only used for "in" and "not in" tests). + Skip over BUILD_SEQN 1 UNPACK_SEQN 1. + Replace BUILD_SEQN 2 UNPACK_SEQN 2 with ROT2. + Replace BUILD_SEQN 3 UNPACK_SEQN 3 with ROT3 ROT2. */ + case BUILD_TUPLE: + case BUILD_LIST: + j = GETARG(codestr, i); + h = i - 3 * j; + if (h >= 0 && + j <= lastlc && + ((opcode == BUILD_TUPLE && + ISBASICBLOCK(blocks, h, 3*(j+1))) || + (opcode == BUILD_LIST && + codestr[i+3]==COMPARE_OP && + ISBASICBLOCK(blocks, h, 3*(j+2)) && + (GETARG(codestr,i+3)==6 || + GETARG(codestr,i+3)==7))) && + tuple_of_constants(&codestr[h], j, consts)) { + assert(codestr[i] == LOAD_CONST); + cumlc = 1; + break; + } + if (codestr[i+3] != UNPACK_SEQUENCE || + !ISBASICBLOCK(blocks,i,6) || + j != GETARG(codestr, i+3)) + continue; + if (j == 1) { + memset(codestr+i, NOP, 6); + } else if (j == 2) { + codestr[i] = ROT_TWO; + memset(codestr+i+1, NOP, 5); + } else if (j == 3) { + codestr[i] = ROT_THREE; + codestr[i+1] = ROT_TWO; + memset(codestr+i+2, NOP, 4); + } + break; + + /* Fold binary ops on constants. + LOAD_CONST c1 LOAD_CONST c2 BINOP --> LOAD_CONST binop(c1,c2) */ + case BINARY_POWER: + case BINARY_MULTIPLY: + case BINARY_TRUE_DIVIDE: + case BINARY_FLOOR_DIVIDE: + case BINARY_MODULO: + case BINARY_ADD: + case BINARY_SUBTRACT: + case BINARY_SUBSCR: + case BINARY_LSHIFT: + case BINARY_RSHIFT: + case BINARY_AND: + case BINARY_XOR: + case BINARY_OR: + if (lastlc >= 2 && + ISBASICBLOCK(blocks, i-6, 7) && + fold_binops_on_constants(&codestr[i-6], consts)) { + i -= 2; + assert(codestr[i] == LOAD_CONST); + cumlc = 1; + } + break; + + /* Fold unary ops on constants. + LOAD_CONST c1 UNARY_OP --> LOAD_CONST unary_op(c) */ + case UNARY_NEGATIVE: + case UNARY_INVERT: + if (lastlc >= 1 && + ISBASICBLOCK(blocks, i-3, 4) && + fold_unaryops_on_constants(&codestr[i-3], consts)) { + i -= 2; + assert(codestr[i] == LOAD_CONST); + cumlc = 1; + } + break; + + /* Simplify conditional jump to conditional jump where the + result of the first test implies the success of a similar + test or the failure of the opposite test. + Arises in code like: + "if a and b:" + "if a or b:" + "a and b or c" + "(a and b) and c" + x:JUMP_IF_FALSE_OR_POP y y:JUMP_IF_FALSE_OR_POP z + --> x:JUMP_IF_FALSE_OR_POP z + x:JUMP_IF_FALSE_OR_POP y y:JUMP_IF_TRUE_OR_POP z + --> x:POP_JUMP_IF_FALSE y+3 + where y+3 is the instruction following the second test. + */ + case JUMP_IF_FALSE_OR_POP: + case JUMP_IF_TRUE_OR_POP: + tgt = GETJUMPTGT(codestr, i); + j = codestr[tgt]; + if (CONDITIONAL_JUMP(j)) { + /* NOTE: all possible jumps here are + absolute! */ + if (JUMPS_ON_TRUE(j) == JUMPS_ON_TRUE(opcode)) { + /* The second jump will be + taken iff the first is. */ + tgttgt = GETJUMPTGT(codestr, tgt); + /* The current opcode inherits + its target's stack behaviour */ + codestr[i] = j; + SETARG(codestr, i, tgttgt); + goto reoptimize_current; + } else { + /* The second jump is not taken + if the first is (so jump past + it), and all conditional + jumps pop their argument when + they're not taken (so change + the first jump to pop its + argument when it's taken). */ + if (JUMPS_ON_TRUE(opcode)) + codestr[i] = POP_JUMP_IF_TRUE; + else + codestr[i] = POP_JUMP_IF_FALSE; + SETARG(codestr, i, (tgt + 3)); + goto reoptimize_current; + } + } + /* Intentional fallthrough */ + + /* Replace jumps to unconditional jumps */ + case POP_JUMP_IF_FALSE: + case POP_JUMP_IF_TRUE: + case FOR_ITER: + case JUMP_FORWARD: + case JUMP_ABSOLUTE: + case CONTINUE_LOOP: + case SETUP_LOOP: + case SETUP_EXCEPT: + case SETUP_FINALLY: + tgt = GETJUMPTGT(codestr, i); + /* Replace JUMP_* to a RETURN into just a RETURN */ + if (UNCONDITIONAL_JUMP(opcode) && + codestr[tgt] == RETURN_VALUE) { + codestr[i] = RETURN_VALUE; + memset(codestr+i+1, NOP, 2); + continue; + } + if (!UNCONDITIONAL_JUMP(codestr[tgt])) + continue; + tgttgt = GETJUMPTGT(codestr, tgt); + if (opcode == JUMP_FORWARD) /* JMP_ABS can go backwards */ + opcode = JUMP_ABSOLUTE; + if (!ABSOLUTE_JUMP(opcode)) + tgttgt -= i + 3; /* Calc relative jump addr */ + if (tgttgt < 0) /* No backward relative jumps */ + continue; + codestr[i] = opcode; + SETARG(codestr, i, tgttgt); + break; + + case EXTENDED_ARG: + if (codestr[i+3] != MAKE_FUNCTION) + goto exitUnchanged; + /* don't visit MAKE_FUNCTION as GETARG will be wrong */ + i += 3; + break; + + /* Replace RETURN LOAD_CONST None RETURN with just RETURN */ + /* Remove unreachable JUMPs after RETURN */ + case RETURN_VALUE: + if (i+4 >= codelen) + continue; + if (codestr[i+4] == RETURN_VALUE && + ISBASICBLOCK(blocks,i,5)) + memset(codestr+i+1, NOP, 4); + else if (UNCONDITIONAL_JUMP(codestr[i+1]) && + ISBASICBLOCK(blocks,i,4)) + memset(codestr+i+1, NOP, 3); + break; + } + } + + /* Fixup linenotab */ + for (i=0, nops=0 ; iab_size = size; - b->ab_mem = (void *)(b + 1); - b->ab_next = NULL; - b->ab_offset = ROUNDUP((Py_uintptr_t)(b->ab_mem)) - - (Py_uintptr_t)(b->ab_mem); - return b; + /* Allocate header and block as one unit. + ab_mem points just past header. */ + block *b = (block *)malloc(sizeof(block) + size); + if (!b) + return NULL; + b->ab_size = size; + b->ab_mem = (void *)(b + 1); + b->ab_next = NULL; + b->ab_offset = ROUNDUP((Py_uintptr_t)(b->ab_mem)) - + (Py_uintptr_t)(b->ab_mem); + return b; } static void block_free(block *b) { - while (b) { - block *next = b->ab_next; - free(b); - b = next; - } + while (b) { + block *next = b->ab_next; + free(b); + b = next; + } } static void * block_alloc(block *b, size_t size) { - void *p; - assert(b); - size = ROUNDUP(size); - if (b->ab_offset + size > b->ab_size) { - /* If we need to allocate more memory than will fit in - the default block, allocate a one-off block that is - exactly the right size. */ - /* TODO(jhylton): Think about space waste at end of block */ - block *newbl = block_new( - size < DEFAULT_BLOCK_SIZE ? - DEFAULT_BLOCK_SIZE : size); - if (!newbl) - return NULL; - assert(!b->ab_next); - b->ab_next = newbl; - b = newbl; - } - - assert(b->ab_offset + size <= b->ab_size); - p = (void *)(((char *)b->ab_mem) + b->ab_offset); - b->ab_offset += size; - return p; + void *p; + assert(b); + size = ROUNDUP(size); + if (b->ab_offset + size > b->ab_size) { + /* If we need to allocate more memory than will fit in + the default block, allocate a one-off block that is + exactly the right size. */ + /* TODO(jhylton): Think about space waste at end of block */ + block *newbl = block_new( + size < DEFAULT_BLOCK_SIZE ? + DEFAULT_BLOCK_SIZE : size); + if (!newbl) + return NULL; + assert(!b->ab_next); + b->ab_next = newbl; + b = newbl; + } + + assert(b->ab_offset + size <= b->ab_size); + p = (void *)(((char *)b->ab_mem) + b->ab_offset); + b->ab_offset += size; + return p; } PyArena * PyArena_New() { - PyArena* arena = (PyArena *)malloc(sizeof(PyArena)); - if (!arena) - return (PyArena*)PyErr_NoMemory(); - - arena->a_head = block_new(DEFAULT_BLOCK_SIZE); - arena->a_cur = arena->a_head; - if (!arena->a_head) { - free((void *)arena); - return (PyArena*)PyErr_NoMemory(); - } - arena->a_objects = PyList_New(0); - if (!arena->a_objects) { - block_free(arena->a_head); - free((void *)arena); - return (PyArena*)PyErr_NoMemory(); - } + PyArena* arena = (PyArena *)malloc(sizeof(PyArena)); + if (!arena) + return (PyArena*)PyErr_NoMemory(); + + arena->a_head = block_new(DEFAULT_BLOCK_SIZE); + arena->a_cur = arena->a_head; + if (!arena->a_head) { + free((void *)arena); + return (PyArena*)PyErr_NoMemory(); + } + arena->a_objects = PyList_New(0); + if (!arena->a_objects) { + block_free(arena->a_head); + free((void *)arena); + return (PyArena*)PyErr_NoMemory(); + } #if defined(Py_DEBUG) - arena->total_allocs = 0; - arena->total_size = 0; - arena->total_blocks = 1; - arena->total_block_size = DEFAULT_BLOCK_SIZE; - arena->total_big_blocks = 0; + arena->total_allocs = 0; + arena->total_size = 0; + arena->total_blocks = 1; + arena->total_block_size = DEFAULT_BLOCK_SIZE; + arena->total_big_blocks = 0; #endif - return arena; + return arena; } void PyArena_Free(PyArena *arena) { - int r; - assert(arena); + int r; + assert(arena); #if defined(Py_DEBUG) - /* - fprintf(stderr, - "alloc=%d size=%d blocks=%d block_size=%d big=%d objects=%d\n", - arena->total_allocs, arena->total_size, arena->total_blocks, - arena->total_block_size, arena->total_big_blocks, - PyList_Size(arena->a_objects)); - */ + /* + fprintf(stderr, + "alloc=%d size=%d blocks=%d block_size=%d big=%d objects=%d\n", + arena->total_allocs, arena->total_size, arena->total_blocks, + arena->total_block_size, arena->total_big_blocks, + PyList_Size(arena->a_objects)); + */ #endif - block_free(arena->a_head); - /* This property normally holds, except when the code being compiled - is sys.getobjects(0), in which case there will be two references. - assert(arena->a_objects->ob_refcnt == 1); - */ - - /* Clear all the elements from the list. This is necessary - to guarantee that they will be DECREFed. */ - r = PyList_SetSlice(arena->a_objects, - 0, PyList_GET_SIZE(arena->a_objects), NULL); - assert(r == 0); - assert(PyList_GET_SIZE(arena->a_objects) == 0); - Py_DECREF(arena->a_objects); - free(arena); + block_free(arena->a_head); + /* This property normally holds, except when the code being compiled + is sys.getobjects(0), in which case there will be two references. + assert(arena->a_objects->ob_refcnt == 1); + */ + + /* Clear all the elements from the list. This is necessary + to guarantee that they will be DECREFed. */ + r = PyList_SetSlice(arena->a_objects, + 0, PyList_GET_SIZE(arena->a_objects), NULL); + assert(r == 0); + assert(PyList_GET_SIZE(arena->a_objects) == 0); + Py_DECREF(arena->a_objects); + free(arena); } void * PyArena_Malloc(PyArena *arena, size_t size) { - void *p = block_alloc(arena->a_cur, size); - if (!p) - return PyErr_NoMemory(); + void *p = block_alloc(arena->a_cur, size); + if (!p) + return PyErr_NoMemory(); #if defined(Py_DEBUG) - arena->total_allocs++; - arena->total_size += size; + arena->total_allocs++; + arena->total_size += size; #endif - /* Reset cur if we allocated a new block. */ - if (arena->a_cur->ab_next) { - arena->a_cur = arena->a_cur->ab_next; + /* Reset cur if we allocated a new block. */ + if (arena->a_cur->ab_next) { + arena->a_cur = arena->a_cur->ab_next; #if defined(Py_DEBUG) - arena->total_blocks++; - arena->total_block_size += arena->a_cur->ab_size; - if (arena->a_cur->ab_size > DEFAULT_BLOCK_SIZE) - ++arena->total_big_blocks; + arena->total_blocks++; + arena->total_block_size += arena->a_cur->ab_size; + if (arena->a_cur->ab_size > DEFAULT_BLOCK_SIZE) + ++arena->total_big_blocks; #endif - } - return p; + } + return p; } int PyArena_AddPyObject(PyArena *arena, PyObject *obj) { - int r = PyList_Append(arena->a_objects, obj); - if (r >= 0) { - Py_DECREF(obj); - } - return r; + int r = PyList_Append(arena->a_objects, obj); + if (r >= 0) { + Py_DECREF(obj); + } + return r; } Modified: python/branches/release31-maint/Python/pymath.c ============================================================================== --- python/branches/release31-maint/Python/pymath.c (original) +++ python/branches/release31-maint/Python/pymath.c Sun May 9 18:14:21 2010 @@ -7,9 +7,9 @@ thus rounding from extended precision to double precision. */ double _Py_force_double(double x) { - volatile double y; - y = x; - return y; + volatile double y; + y = x; + return y; } #endif @@ -34,21 +34,21 @@ #ifndef HAVE_HYPOT double hypot(double x, double y) { - double yx; + double yx; - x = fabs(x); - y = fabs(y); - if (x < y) { - double temp = x; - x = y; - y = temp; - } - if (x == 0.) - return 0.; - else { - yx = y/x; - return x*sqrt(1.+yx*yx); - } + x = fabs(x); + y = fabs(y); + if (x < y) { + double temp = x; + x = y; + y = temp; + } + if (x == 0.) + return 0.; + else { + yx = y/x; + return x*sqrt(1.+yx*yx); + } } #endif /* HAVE_HYPOT */ @@ -56,12 +56,12 @@ double copysign(double x, double y) { - /* use atan2 to distinguish -0. from 0. */ - if (y > 0. || (y == 0. && atan2(y, -1.) > 0.)) { - return fabs(x); - } else { - return -fabs(x); - } + /* use atan2 to distinguish -0. from 0. */ + if (y > 0. || (y == 0. && atan2(y, -1.) > 0.)) { + return fabs(x); + } else { + return -fabs(x); + } } #endif /* HAVE_COPYSIGN */ @@ -73,7 +73,7 @@ absx = fabs(x); y = floor(absx); if (absx - y >= 0.5) - y += 1.0; + y += 1.0; return copysign(y, x); } #endif /* HAVE_ROUND */ @@ -84,41 +84,41 @@ double log1p(double x) { - /* For x small, we use the following approach. Let y be the nearest - float to 1+x, then + /* For x small, we use the following approach. Let y be the nearest + float to 1+x, then - 1+x = y * (1 - (y-1-x)/y) + 1+x = y * (1 - (y-1-x)/y) - so log(1+x) = log(y) + log(1-(y-1-x)/y). Since (y-1-x)/y is tiny, - the second term is well approximated by (y-1-x)/y. If abs(x) >= - DBL_EPSILON/2 or the rounding-mode is some form of round-to-nearest - then y-1-x will be exactly representable, and is computed exactly - by (y-1)-x. - - If abs(x) < DBL_EPSILON/2 and the rounding mode is not known to be - round-to-nearest then this method is slightly dangerous: 1+x could - be rounded up to 1+DBL_EPSILON instead of down to 1, and in that - case y-1-x will not be exactly representable any more and the - result can be off by many ulps. But this is easily fixed: for a - floating-point number |x| < DBL_EPSILON/2., the closest - floating-point number to log(1+x) is exactly x. - */ - - double y; - if (fabs(x) < DBL_EPSILON/2.) { - return x; - } else if (-0.5 <= x && x <= 1.) { - /* WARNING: it's possible than an overeager compiler - will incorrectly optimize the following two lines - to the equivalent of "return log(1.+x)". If this - happens, then results from log1p will be inaccurate - for small x. */ - y = 1.+x; - return log(y)-((y-1.)-x)/y; - } else { - /* NaNs and infinities should end up here */ - return log(1.+x); - } + so log(1+x) = log(y) + log(1-(y-1-x)/y). Since (y-1-x)/y is tiny, + the second term is well approximated by (y-1-x)/y. If abs(x) >= + DBL_EPSILON/2 or the rounding-mode is some form of round-to-nearest + then y-1-x will be exactly representable, and is computed exactly + by (y-1)-x. + + If abs(x) < DBL_EPSILON/2 and the rounding mode is not known to be + round-to-nearest then this method is slightly dangerous: 1+x could + be rounded up to 1+DBL_EPSILON instead of down to 1, and in that + case y-1-x will not be exactly representable any more and the + result can be off by many ulps. But this is easily fixed: for a + floating-point number |x| < DBL_EPSILON/2., the closest + floating-point number to log(1+x) is exactly x. + */ + + double y; + if (fabs(x) < DBL_EPSILON/2.) { + return x; + } else if (-0.5 <= x && x <= 1.) { + /* WARNING: it's possible than an overeager compiler + will incorrectly optimize the following two lines + to the equivalent of "return log(1.+x)". If this + happens, then results from log1p will be inaccurate + for small x. */ + y = 1.+x; + return log(y)-((y-1.)-x)/y; + } else { + /* NaNs and infinities should end up here */ + return log(1.+x); + } } #endif /* HAVE_LOG1P */ @@ -128,7 +128,7 @@ * * Developed at SunPro, a Sun Microsystems, Inc. business. * Permission to use, copy, modify, and distribute this - * software is freely granted, provided that this notice + * software is freely granted, provided that this notice * is preserved. * ==================================================== */ @@ -140,51 +140,51 @@ /* asinh(x) * Method : - * Based on - * asinh(x) = sign(x) * log [ |x| + sqrt(x*x+1) ] - * we have - * asinh(x) := x if 1+x*x=1, - * := sign(x)*(log(x)+ln2)) for large |x|, else - * := sign(x)*log(2|x|+1/(|x|+sqrt(x*x+1))) if|x|>2, else - * := sign(x)*log1p(|x| + x^2/(1 + sqrt(1+x^2))) + * Based on + * asinh(x) = sign(x) * log [ |x| + sqrt(x*x+1) ] + * we have + * asinh(x) := x if 1+x*x=1, + * := sign(x)*(log(x)+ln2)) for large |x|, else + * := sign(x)*log(2|x|+1/(|x|+sqrt(x*x+1))) if|x|>2, else + * := sign(x)*log1p(|x| + x^2/(1 + sqrt(1+x^2))) */ #ifndef HAVE_ASINH double asinh(double x) -{ - double w; - double absx = fabs(x); - - if (Py_IS_NAN(x) || Py_IS_INFINITY(x)) { - return x+x; - } - if (absx < two_pow_m28) { /* |x| < 2**-28 */ - return x; /* return x inexact except 0 */ - } - if (absx > two_pow_p28) { /* |x| > 2**28 */ - w = log(absx)+ln2; - } - else if (absx > 2.0) { /* 2 < |x| < 2**28 */ - w = log(2.0*absx + 1.0 / (sqrt(x*x + 1.0) + absx)); - } - else { /* 2**-28 <= |x| < 2= */ - double t = x*x; - w = log1p(absx + t / (1.0 + sqrt(1.0 + t))); - } - return copysign(w, x); - +{ + double w; + double absx = fabs(x); + + if (Py_IS_NAN(x) || Py_IS_INFINITY(x)) { + return x+x; + } + if (absx < two_pow_m28) { /* |x| < 2**-28 */ + return x; /* return x inexact except 0 */ + } + if (absx > two_pow_p28) { /* |x| > 2**28 */ + w = log(absx)+ln2; + } + else if (absx > 2.0) { /* 2 < |x| < 2**28 */ + w = log(2.0*absx + 1.0 / (sqrt(x*x + 1.0) + absx)); + } + else { /* 2**-28 <= |x| < 2= */ + double t = x*x; + w = log1p(absx + t / (1.0 + sqrt(1.0 + t))); + } + return copysign(w, x); + } #endif /* HAVE_ASINH */ /* acosh(x) * Method : * Based on - * acosh(x) = log [ x + sqrt(x*x-1) ] + * acosh(x) = log [ x + sqrt(x*x-1) ] * we have - * acosh(x) := log(x)+ln2, if x is large; else - * acosh(x) := log(2x-1/(sqrt(x*x-1)+x)) if x>2; else - * acosh(x) := log1p(t+sqrt(2.0*t+t*t)); where t=x-1. + * acosh(x) := log(x)+ln2, if x is large; else + * acosh(x) := log(2x-1/(sqrt(x*x-1)+x)) if x>2; else + * acosh(x) := log1p(t+sqrt(2.0*t+t*t)); where t=x-1. * * Special cases: * acosh(x) is NaN with signal if x<1. @@ -195,35 +195,35 @@ double acosh(double x) { - if (Py_IS_NAN(x)) { - return x+x; - } - if (x < 1.) { /* x < 1; return a signaling NaN */ - errno = EDOM; + if (Py_IS_NAN(x)) { + return x+x; + } + if (x < 1.) { /* x < 1; return a signaling NaN */ + errno = EDOM; #ifdef Py_NAN - return Py_NAN; + return Py_NAN; #else - return (x-x)/(x-x); + return (x-x)/(x-x); #endif - } - else if (x >= two_pow_p28) { /* x > 2**28 */ - if (Py_IS_INFINITY(x)) { - return x+x; - } else { - return log(x)+ln2; /* acosh(huge)=log(2x) */ - } - } - else if (x == 1.) { - return 0.0; /* acosh(1) = 0 */ - } - else if (x > 2.) { /* 2 < x < 2**28 */ - double t = x*x; - return log(2.0*x - 1.0 / (x + sqrt(t - 1.0))); - } - else { /* 1 < x <= 2 */ - double t = x - 1.0; - return log1p(t + sqrt(2.0*t + t*t)); - } + } + else if (x >= two_pow_p28) { /* x > 2**28 */ + if (Py_IS_INFINITY(x)) { + return x+x; + } else { + return log(x)+ln2; /* acosh(huge)=log(2x) */ + } + } + else if (x == 1.) { + return 0.0; /* acosh(1) = 0 */ + } + else if (x > 2.) { /* 2 < x < 2**28 */ + double t = x*x; + return log(2.0*x - 1.0 / (x + sqrt(t - 1.0))); + } + else { /* 1 < x <= 2 */ + double t = x - 1.0; + return log1p(t + sqrt(2.0*t + t*t)); + } } #endif /* HAVE_ACOSH */ @@ -231,9 +231,9 @@ * Method : * 1.Reduced x to positive by atanh(-x) = -atanh(x) * 2.For x>=0.5 - * 1 2x x + * 1 2x x * atanh(x) = --- * log(1 + -------) = 0.5 * log1p(2 * --------) - * 2 1 - x 1 - x + * 2 1 - x 1 - x * * For x<0.5 * atanh(x) = 0.5*log1p(2x+2x*x/(1-x)) @@ -248,31 +248,31 @@ double atanh(double x) { - double absx; - double t; + double absx; + double t; - if (Py_IS_NAN(x)) { - return x+x; - } - absx = fabs(x); - if (absx >= 1.) { /* |x| >= 1 */ - errno = EDOM; + if (Py_IS_NAN(x)) { + return x+x; + } + absx = fabs(x); + if (absx >= 1.) { /* |x| >= 1 */ + errno = EDOM; #ifdef Py_NAN - return Py_NAN; + return Py_NAN; #else - return x/zero; + return x/zero; #endif - } - if (absx < two_pow_m28) { /* |x| < 2**-28 */ - return x; - } - if (absx < 0.5) { /* |x| < 0.5 */ - t = absx+absx; - t = 0.5 * log1p(t + t*absx / (1.0 - absx)); - } - else { /* 0.5 <= |x| <= 1.0 */ - t = 0.5 * log1p((absx + absx) / (1.0 - absx)); - } - return copysign(t, x); + } + if (absx < two_pow_m28) { /* |x| < 2**-28 */ + return x; + } + if (absx < 0.5) { /* |x| < 0.5 */ + t = absx+absx; + t = 0.5 * log1p(t + t*absx / (1.0 - absx)); + } + else { /* 0.5 <= |x| <= 1.0 */ + t = 0.5 * log1p((absx + absx) / (1.0 - absx)); + } + return copysign(t, x); } #endif /* HAVE_ATANH */ Modified: python/branches/release31-maint/Python/pystate.c ============================================================================== --- python/branches/release31-maint/Python/pystate.c (original) +++ python/branches/release31-maint/Python/pystate.c Sun May 9 18:14:21 2010 @@ -58,95 +58,95 @@ PyInterpreterState * PyInterpreterState_New(void) { - PyInterpreterState *interp = (PyInterpreterState *) - malloc(sizeof(PyInterpreterState)); + PyInterpreterState *interp = (PyInterpreterState *) + malloc(sizeof(PyInterpreterState)); - if (interp != NULL) { - HEAD_INIT(); + if (interp != NULL) { + HEAD_INIT(); #ifdef WITH_THREAD - if (head_mutex == NULL) - Py_FatalError("Can't initialize threads for interpreter"); + if (head_mutex == NULL) + Py_FatalError("Can't initialize threads for interpreter"); #endif - interp->modules = NULL; - interp->modules_reloading = NULL; - interp->modules_by_index = NULL; - interp->sysdict = NULL; - interp->builtins = NULL; - interp->tstate_head = NULL; - interp->codec_search_path = NULL; - interp->codec_search_cache = NULL; - interp->codec_error_registry = NULL; - interp->codecs_initialized = 0; + interp->modules = NULL; + interp->modules_reloading = NULL; + interp->modules_by_index = NULL; + interp->sysdict = NULL; + interp->builtins = NULL; + interp->tstate_head = NULL; + interp->codec_search_path = NULL; + interp->codec_search_cache = NULL; + interp->codec_error_registry = NULL; + interp->codecs_initialized = 0; #ifdef HAVE_DLOPEN #ifdef RTLD_NOW - interp->dlopenflags = RTLD_NOW; + interp->dlopenflags = RTLD_NOW; #else - interp->dlopenflags = RTLD_LAZY; + interp->dlopenflags = RTLD_LAZY; #endif #endif #ifdef WITH_TSC - interp->tscdump = 0; + interp->tscdump = 0; #endif - HEAD_LOCK(); - interp->next = interp_head; - interp_head = interp; - HEAD_UNLOCK(); - } + HEAD_LOCK(); + interp->next = interp_head; + interp_head = interp; + HEAD_UNLOCK(); + } - return interp; + return interp; } void PyInterpreterState_Clear(PyInterpreterState *interp) { - PyThreadState *p; - HEAD_LOCK(); - for (p = interp->tstate_head; p != NULL; p = p->next) - PyThreadState_Clear(p); - HEAD_UNLOCK(); - Py_CLEAR(interp->codec_search_path); - Py_CLEAR(interp->codec_search_cache); - Py_CLEAR(interp->codec_error_registry); - Py_CLEAR(interp->modules); - Py_CLEAR(interp->modules_by_index); - Py_CLEAR(interp->modules_reloading); - Py_CLEAR(interp->sysdict); - Py_CLEAR(interp->builtins); + PyThreadState *p; + HEAD_LOCK(); + for (p = interp->tstate_head; p != NULL; p = p->next) + PyThreadState_Clear(p); + HEAD_UNLOCK(); + Py_CLEAR(interp->codec_search_path); + Py_CLEAR(interp->codec_search_cache); + Py_CLEAR(interp->codec_error_registry); + Py_CLEAR(interp->modules); + Py_CLEAR(interp->modules_by_index); + Py_CLEAR(interp->modules_reloading); + Py_CLEAR(interp->sysdict); + Py_CLEAR(interp->builtins); } static void zapthreads(PyInterpreterState *interp) { - PyThreadState *p; - /* No need to lock the mutex here because this should only happen - when the threads are all really dead (XXX famous last words). */ - while ((p = interp->tstate_head) != NULL) { - PyThreadState_Delete(p); - } + PyThreadState *p; + /* No need to lock the mutex here because this should only happen + when the threads are all really dead (XXX famous last words). */ + while ((p = interp->tstate_head) != NULL) { + PyThreadState_Delete(p); + } } void PyInterpreterState_Delete(PyInterpreterState *interp) { - PyInterpreterState **p; - zapthreads(interp); - HEAD_LOCK(); - for (p = &interp_head; ; p = &(*p)->next) { - if (*p == NULL) - Py_FatalError( - "PyInterpreterState_Delete: invalid interp"); - if (*p == interp) - break; - } - if (interp->tstate_head != NULL) - Py_FatalError("PyInterpreterState_Delete: remaining threads"); - *p = interp->next; - HEAD_UNLOCK(); - free(interp); + PyInterpreterState **p; + zapthreads(interp); + HEAD_LOCK(); + for (p = &interp_head; ; p = &(*p)->next) { + if (*p == NULL) + Py_FatalError( + "PyInterpreterState_Delete: invalid interp"); + if (*p == interp) + break; + } + if (interp->tstate_head != NULL) + Py_FatalError("PyInterpreterState_Delete: remaining threads"); + *p = interp->next; + HEAD_UNLOCK(); + free(interp); } @@ -154,141 +154,141 @@ static struct _frame * threadstate_getframe(PyThreadState *self) { - return self->frame; + return self->frame; } static PyThreadState * new_threadstate(PyInterpreterState *interp, int init) { - PyThreadState *tstate = (PyThreadState *)malloc(sizeof(PyThreadState)); + PyThreadState *tstate = (PyThreadState *)malloc(sizeof(PyThreadState)); - if (_PyThreadState_GetFrame == NULL) - _PyThreadState_GetFrame = threadstate_getframe; + if (_PyThreadState_GetFrame == NULL) + _PyThreadState_GetFrame = threadstate_getframe; - if (tstate != NULL) { - tstate->interp = interp; + if (tstate != NULL) { + tstate->interp = interp; - tstate->frame = NULL; - tstate->recursion_depth = 0; - tstate->overflowed = 0; - tstate->recursion_critical = 0; - tstate->tracing = 0; - tstate->use_tracing = 0; - tstate->tick_counter = 0; - tstate->gilstate_counter = 0; - tstate->async_exc = NULL; + tstate->frame = NULL; + tstate->recursion_depth = 0; + tstate->overflowed = 0; + tstate->recursion_critical = 0; + tstate->tracing = 0; + tstate->use_tracing = 0; + tstate->tick_counter = 0; + tstate->gilstate_counter = 0; + tstate->async_exc = NULL; #ifdef WITH_THREAD - tstate->thread_id = PyThread_get_thread_ident(); + tstate->thread_id = PyThread_get_thread_ident(); #else - tstate->thread_id = 0; + tstate->thread_id = 0; #endif - tstate->dict = NULL; + tstate->dict = NULL; - tstate->curexc_type = NULL; - tstate->curexc_value = NULL; - tstate->curexc_traceback = NULL; - - tstate->exc_type = NULL; - tstate->exc_value = NULL; - tstate->exc_traceback = NULL; - - tstate->c_profilefunc = NULL; - tstate->c_tracefunc = NULL; - tstate->c_profileobj = NULL; - tstate->c_traceobj = NULL; - - if (init) - _PyThreadState_Init(tstate); - - HEAD_LOCK(); - tstate->next = interp->tstate_head; - interp->tstate_head = tstate; - HEAD_UNLOCK(); - } + tstate->curexc_type = NULL; + tstate->curexc_value = NULL; + tstate->curexc_traceback = NULL; + + tstate->exc_type = NULL; + tstate->exc_value = NULL; + tstate->exc_traceback = NULL; + + tstate->c_profilefunc = NULL; + tstate->c_tracefunc = NULL; + tstate->c_profileobj = NULL; + tstate->c_traceobj = NULL; + + if (init) + _PyThreadState_Init(tstate); + + HEAD_LOCK(); + tstate->next = interp->tstate_head; + interp->tstate_head = tstate; + HEAD_UNLOCK(); + } - return tstate; + return tstate; } PyThreadState * PyThreadState_New(PyInterpreterState *interp) { - return new_threadstate(interp, 1); + return new_threadstate(interp, 1); } PyThreadState * _PyThreadState_Prealloc(PyInterpreterState *interp) { - return new_threadstate(interp, 0); + return new_threadstate(interp, 0); } void _PyThreadState_Init(PyThreadState *tstate) { #ifdef WITH_THREAD - _PyGILState_NoteThreadState(tstate); + _PyGILState_NoteThreadState(tstate); #endif } PyObject* PyState_FindModule(struct PyModuleDef* m) { - Py_ssize_t index = m->m_base.m_index; - PyInterpreterState *state = PyThreadState_GET()->interp; - PyObject *res; - if (index == 0) - return NULL; - if (state->modules_by_index == NULL) - return NULL; - if (index > PyList_GET_SIZE(state->modules_by_index)) - return NULL; - res = PyList_GET_ITEM(state->modules_by_index, index); - return res==Py_None ? NULL : res; + Py_ssize_t index = m->m_base.m_index; + PyInterpreterState *state = PyThreadState_GET()->interp; + PyObject *res; + if (index == 0) + return NULL; + if (state->modules_by_index == NULL) + return NULL; + if (index > PyList_GET_SIZE(state->modules_by_index)) + return NULL; + res = PyList_GET_ITEM(state->modules_by_index, index); + return res==Py_None ? NULL : res; } int _PyState_AddModule(PyObject* module, struct PyModuleDef* def) { - PyInterpreterState *state = PyThreadState_GET()->interp; - if (!def) - return -1; - if (!state->modules_by_index) { - state->modules_by_index = PyList_New(0); - if (!state->modules_by_index) - return -1; - } - while(PyList_GET_SIZE(state->modules_by_index) <= def->m_base.m_index) - if (PyList_Append(state->modules_by_index, Py_None) < 0) - return -1; - Py_INCREF(module); - return PyList_SetItem(state->modules_by_index, - def->m_base.m_index, module); + PyInterpreterState *state = PyThreadState_GET()->interp; + if (!def) + return -1; + if (!state->modules_by_index) { + state->modules_by_index = PyList_New(0); + if (!state->modules_by_index) + return -1; + } + while(PyList_GET_SIZE(state->modules_by_index) <= def->m_base.m_index) + if (PyList_Append(state->modules_by_index, Py_None) < 0) + return -1; + Py_INCREF(module); + return PyList_SetItem(state->modules_by_index, + def->m_base.m_index, module); } void PyThreadState_Clear(PyThreadState *tstate) { - if (Py_VerboseFlag && tstate->frame != NULL) - fprintf(stderr, - "PyThreadState_Clear: warning: thread still has a frame\n"); - - Py_CLEAR(tstate->frame); - - Py_CLEAR(tstate->dict); - Py_CLEAR(tstate->async_exc); - - Py_CLEAR(tstate->curexc_type); - Py_CLEAR(tstate->curexc_value); - Py_CLEAR(tstate->curexc_traceback); - - Py_CLEAR(tstate->exc_type); - Py_CLEAR(tstate->exc_value); - Py_CLEAR(tstate->exc_traceback); - - tstate->c_profilefunc = NULL; - tstate->c_tracefunc = NULL; - Py_CLEAR(tstate->c_profileobj); - Py_CLEAR(tstate->c_traceobj); + if (Py_VerboseFlag && tstate->frame != NULL) + fprintf(stderr, + "PyThreadState_Clear: warning: thread still has a frame\n"); + + Py_CLEAR(tstate->frame); + + Py_CLEAR(tstate->dict); + Py_CLEAR(tstate->async_exc); + + Py_CLEAR(tstate->curexc_type); + Py_CLEAR(tstate->curexc_value); + Py_CLEAR(tstate->curexc_traceback); + + Py_CLEAR(tstate->exc_type); + Py_CLEAR(tstate->exc_value); + Py_CLEAR(tstate->exc_traceback); + + tstate->c_profilefunc = NULL; + tstate->c_tracefunc = NULL; + Py_CLEAR(tstate->c_profileobj); + Py_CLEAR(tstate->c_traceobj); } @@ -296,50 +296,50 @@ static void tstate_delete_common(PyThreadState *tstate) { - PyInterpreterState *interp; - PyThreadState **p; - PyThreadState *prev_p = NULL; - if (tstate == NULL) - Py_FatalError("PyThreadState_Delete: NULL tstate"); - interp = tstate->interp; - if (interp == NULL) - Py_FatalError("PyThreadState_Delete: NULL interp"); - HEAD_LOCK(); - for (p = &interp->tstate_head; ; p = &(*p)->next) { - if (*p == NULL) - Py_FatalError( - "PyThreadState_Delete: invalid tstate"); - if (*p == tstate) - break; - /* Sanity check. These states should never happen but if - * they do we must abort. Otherwise we'll end up spinning in - * in a tight loop with the lock held. A similar check is done - * in thread.c find_key(). */ - if (*p == prev_p) - Py_FatalError( - "PyThreadState_Delete: small circular list(!)" - " and tstate not found."); - prev_p = *p; - if ((*p)->next == interp->tstate_head) - Py_FatalError( - "PyThreadState_Delete: circular list(!) and" - " tstate not found."); - } - *p = tstate->next; - HEAD_UNLOCK(); - free(tstate); + PyInterpreterState *interp; + PyThreadState **p; + PyThreadState *prev_p = NULL; + if (tstate == NULL) + Py_FatalError("PyThreadState_Delete: NULL tstate"); + interp = tstate->interp; + if (interp == NULL) + Py_FatalError("PyThreadState_Delete: NULL interp"); + HEAD_LOCK(); + for (p = &interp->tstate_head; ; p = &(*p)->next) { + if (*p == NULL) + Py_FatalError( + "PyThreadState_Delete: invalid tstate"); + if (*p == tstate) + break; + /* Sanity check. These states should never happen but if + * they do we must abort. Otherwise we'll end up spinning in + * in a tight loop with the lock held. A similar check is done + * in thread.c find_key(). */ + if (*p == prev_p) + Py_FatalError( + "PyThreadState_Delete: small circular list(!)" + " and tstate not found."); + prev_p = *p; + if ((*p)->next == interp->tstate_head) + Py_FatalError( + "PyThreadState_Delete: circular list(!) and" + " tstate not found."); + } + *p = tstate->next; + HEAD_UNLOCK(); + free(tstate); } void PyThreadState_Delete(PyThreadState *tstate) { - if (tstate == _PyThreadState_Current) - Py_FatalError("PyThreadState_Delete: tstate is still current"); - tstate_delete_common(tstate); + if (tstate == _PyThreadState_Current) + Py_FatalError("PyThreadState_Delete: tstate is still current"); + tstate_delete_common(tstate); #ifdef WITH_THREAD - if (autoTLSkey && PyThread_get_key_value(autoTLSkey) == tstate) - PyThread_delete_key_value(autoTLSkey); + if (autoTLSkey && PyThread_get_key_value(autoTLSkey) == tstate) + PyThread_delete_key_value(autoTLSkey); #endif /* WITH_THREAD */ } @@ -348,15 +348,15 @@ void PyThreadState_DeleteCurrent() { - PyThreadState *tstate = _PyThreadState_Current; - if (tstate == NULL) - Py_FatalError( - "PyThreadState_DeleteCurrent: no current tstate"); - _PyThreadState_Current = NULL; - tstate_delete_common(tstate); - if (autoTLSkey && PyThread_get_key_value(autoTLSkey) == tstate) - PyThread_delete_key_value(autoTLSkey); - PyEval_ReleaseLock(); + PyThreadState *tstate = _PyThreadState_Current; + if (tstate == NULL) + Py_FatalError( + "PyThreadState_DeleteCurrent: no current tstate"); + _PyThreadState_Current = NULL; + tstate_delete_common(tstate); + if (autoTLSkey && PyThread_get_key_value(autoTLSkey) == tstate) + PyThread_delete_key_value(autoTLSkey); + PyEval_ReleaseLock(); } #endif /* WITH_THREAD */ @@ -364,36 +364,36 @@ PyThreadState * PyThreadState_Get(void) { - if (_PyThreadState_Current == NULL) - Py_FatalError("PyThreadState_Get: no current thread"); + if (_PyThreadState_Current == NULL) + Py_FatalError("PyThreadState_Get: no current thread"); - return _PyThreadState_Current; + return _PyThreadState_Current; } PyThreadState * PyThreadState_Swap(PyThreadState *newts) { - PyThreadState *oldts = _PyThreadState_Current; + PyThreadState *oldts = _PyThreadState_Current; - _PyThreadState_Current = newts; - /* It should not be possible for more than one thread state - to be used for a thread. Check this the best we can in debug - builds. - */ + _PyThreadState_Current = newts; + /* It should not be possible for more than one thread state + to be used for a thread. Check this the best we can in debug + builds. + */ #if defined(Py_DEBUG) && defined(WITH_THREAD) - if (newts) { - /* This can be called from PyEval_RestoreThread(). Similar - to it, we need to ensure errno doesn't change. - */ - int err = errno; - PyThreadState *check = PyGILState_GetThisThreadState(); - if (check && check->interp == newts->interp && check != newts) - Py_FatalError("Invalid thread state for this thread"); - errno = err; - } + if (newts) { + /* This can be called from PyEval_RestoreThread(). Similar + to it, we need to ensure errno doesn't change. + */ + int err = errno; + PyThreadState *check = PyGILState_GetThisThreadState(); + if (check && check->interp == newts->interp && check != newts) + Py_FatalError("Invalid thread state for this thread"); + errno = err; + } #endif - return oldts; + return oldts; } /* An extension mechanism to store arbitrary additional per-thread state. @@ -405,16 +405,16 @@ PyObject * PyThreadState_GetDict(void) { - if (_PyThreadState_Current == NULL) - return NULL; + if (_PyThreadState_Current == NULL) + return NULL; - if (_PyThreadState_Current->dict == NULL) { - PyObject *d; - _PyThreadState_Current->dict = d = PyDict_New(); - if (d == NULL) - PyErr_Clear(); - } - return _PyThreadState_Current->dict; + if (_PyThreadState_Current->dict == NULL) { + PyObject *d; + _PyThreadState_Current->dict = d = PyDict_New(); + if (d == NULL) + PyErr_Clear(); + } + return _PyThreadState_Current->dict; } @@ -428,36 +428,36 @@ int PyThreadState_SetAsyncExc(long id, PyObject *exc) { - PyThreadState *tstate = PyThreadState_GET(); - PyInterpreterState *interp = tstate->interp; - PyThreadState *p; - - /* Although the GIL is held, a few C API functions can be called - * without the GIL held, and in particular some that create and - * destroy thread and interpreter states. Those can mutate the - * list of thread states we're traversing, so to prevent that we lock - * head_mutex for the duration. - */ - HEAD_LOCK(); - for (p = interp->tstate_head; p != NULL; p = p->next) { - if (p->thread_id == id) { - /* Tricky: we need to decref the current value - * (if any) in p->async_exc, but that can in turn - * allow arbitrary Python code to run, including - * perhaps calls to this function. To prevent - * deadlock, we need to release head_mutex before - * the decref. - */ - PyObject *old_exc = p->async_exc; - Py_XINCREF(exc); - p->async_exc = exc; - HEAD_UNLOCK(); - Py_XDECREF(old_exc); - return 1; - } - } - HEAD_UNLOCK(); - return 0; + PyThreadState *tstate = PyThreadState_GET(); + PyInterpreterState *interp = tstate->interp; + PyThreadState *p; + + /* Although the GIL is held, a few C API functions can be called + * without the GIL held, and in particular some that create and + * destroy thread and interpreter states. Those can mutate the + * list of thread states we're traversing, so to prevent that we lock + * head_mutex for the duration. + */ + HEAD_LOCK(); + for (p = interp->tstate_head; p != NULL; p = p->next) { + if (p->thread_id == id) { + /* Tricky: we need to decref the current value + * (if any) in p->async_exc, but that can in turn + * allow arbitrary Python code to run, including + * perhaps calls to this function. To prevent + * deadlock, we need to release head_mutex before + * the decref. + */ + PyObject *old_exc = p->async_exc; + Py_XINCREF(exc); + p->async_exc = exc; + HEAD_UNLOCK(); + Py_XDECREF(old_exc); + return 1; + } + } + HEAD_UNLOCK(); + return 0; } @@ -467,22 +467,22 @@ PyInterpreterState * PyInterpreterState_Head(void) { - return interp_head; + return interp_head; } PyInterpreterState * PyInterpreterState_Next(PyInterpreterState *interp) { - return interp->next; + return interp->next; } PyThreadState * PyInterpreterState_ThreadHead(PyInterpreterState *interp) { - return interp->tstate_head; + return interp->tstate_head; } PyThreadState * PyThreadState_Next(PyThreadState *tstate) { - return tstate->next; + return tstate->next; } /* The implementation of sys._current_frames(). This is intended to be @@ -493,44 +493,44 @@ PyObject * _PyThread_CurrentFrames(void) { - PyObject *result; - PyInterpreterState *i; + PyObject *result; + PyInterpreterState *i; - result = PyDict_New(); - if (result == NULL) - return NULL; - - /* for i in all interpreters: - * for t in all of i's thread states: - * if t's frame isn't NULL, map t's id to its frame - * Because these lists can mutute even when the GIL is held, we - * need to grab head_mutex for the duration. - */ - HEAD_LOCK(); - for (i = interp_head; i != NULL; i = i->next) { - PyThreadState *t; - for (t = i->tstate_head; t != NULL; t = t->next) { - PyObject *id; - int stat; - struct _frame *frame = t->frame; - if (frame == NULL) - continue; - id = PyLong_FromLong(t->thread_id); - if (id == NULL) - goto Fail; - stat = PyDict_SetItem(result, id, (PyObject *)frame); - Py_DECREF(id); - if (stat < 0) - goto Fail; - } - } - HEAD_UNLOCK(); - return result; + result = PyDict_New(); + if (result == NULL) + return NULL; + + /* for i in all interpreters: + * for t in all of i's thread states: + * if t's frame isn't NULL, map t's id to its frame + * Because these lists can mutute even when the GIL is held, we + * need to grab head_mutex for the duration. + */ + HEAD_LOCK(); + for (i = interp_head; i != NULL; i = i->next) { + PyThreadState *t; + for (t = i->tstate_head; t != NULL; t = t->next) { + PyObject *id; + int stat; + struct _frame *frame = t->frame; + if (frame == NULL) + continue; + id = PyLong_FromLong(t->thread_id); + if (id == NULL) + goto Fail; + stat = PyDict_SetItem(result, id, (PyObject *)frame); + Py_DECREF(id); + if (stat < 0) + goto Fail; + } + } + HEAD_UNLOCK(); + return result; Fail: - HEAD_UNLOCK(); - Py_DECREF(result); - return NULL; + HEAD_UNLOCK(); + Py_DECREF(result); + return NULL; } /* Python "auto thread state" API. */ @@ -547,12 +547,12 @@ static int PyThreadState_IsCurrent(PyThreadState *tstate) { - /* Must be the tstate for this thread */ - assert(PyGILState_GetThisThreadState()==tstate); - /* On Windows at least, simple reads and writes to 32 bit values - are atomic. - */ - return tstate == _PyThreadState_Current; + /* Must be the tstate for this thread */ + assert(PyGILState_GetThisThreadState()==tstate); + /* On Windows at least, simple reads and writes to 32 bit values + are atomic. + */ + return tstate == _PyThreadState_Current; } /* Internal initialization/finalization functions called by @@ -561,21 +561,21 @@ void _PyGILState_Init(PyInterpreterState *i, PyThreadState *t) { - assert(i && t); /* must init with valid states */ - autoTLSkey = PyThread_create_key(); - autoInterpreterState = i; - assert(PyThread_get_key_value(autoTLSkey) == NULL); - assert(t->gilstate_counter == 0); + assert(i && t); /* must init with valid states */ + autoTLSkey = PyThread_create_key(); + autoInterpreterState = i; + assert(PyThread_get_key_value(autoTLSkey) == NULL); + assert(t->gilstate_counter == 0); - _PyGILState_NoteThreadState(t); + _PyGILState_NoteThreadState(t); } void _PyGILState_Fini(void) { - PyThread_delete_key(autoTLSkey); - autoTLSkey = 0; - autoInterpreterState = NULL; + PyThread_delete_key(autoTLSkey); + autoTLSkey = 0; + autoInterpreterState = NULL; } /* When a thread state is created for a thread by some mechanism other than @@ -586,113 +586,113 @@ static void _PyGILState_NoteThreadState(PyThreadState* tstate) { - /* If autoTLSkey is 0, this must be the very first threadstate created - in Py_Initialize(). Don't do anything for now (we'll be back here - when _PyGILState_Init is called). */ - if (!autoTLSkey) - return; - - /* Stick the thread state for this thread in thread local storage. - - The only situation where you can legitimately have more than one - thread state for an OS level thread is when there are multiple - interpreters, when: - - a) You shouldn't really be using the PyGILState_ APIs anyway, - and: - - b) The slightly odd way PyThread_set_key_value works (see - comments by its implementation) means that the first thread - state created for that given OS level thread will "win", - which seems reasonable behaviour. - */ - if (PyThread_set_key_value(autoTLSkey, (void *)tstate) < 0) - Py_FatalError("Couldn't create autoTLSkey mapping"); + /* If autoTLSkey is 0, this must be the very first threadstate created + in Py_Initialize(). Don't do anything for now (we'll be back here + when _PyGILState_Init is called). */ + if (!autoTLSkey) + return; + + /* Stick the thread state for this thread in thread local storage. + + The only situation where you can legitimately have more than one + thread state for an OS level thread is when there are multiple + interpreters, when: + + a) You shouldn't really be using the PyGILState_ APIs anyway, + and: + + b) The slightly odd way PyThread_set_key_value works (see + comments by its implementation) means that the first thread + state created for that given OS level thread will "win", + which seems reasonable behaviour. + */ + if (PyThread_set_key_value(autoTLSkey, (void *)tstate) < 0) + Py_FatalError("Couldn't create autoTLSkey mapping"); - /* PyGILState_Release must not try to delete this thread state. */ - tstate->gilstate_counter = 1; + /* PyGILState_Release must not try to delete this thread state. */ + tstate->gilstate_counter = 1; } /* The public functions */ PyThreadState * PyGILState_GetThisThreadState(void) { - if (autoInterpreterState == NULL || autoTLSkey == 0) - return NULL; - return (PyThreadState *)PyThread_get_key_value(autoTLSkey); + if (autoInterpreterState == NULL || autoTLSkey == 0) + return NULL; + return (PyThreadState *)PyThread_get_key_value(autoTLSkey); } PyGILState_STATE PyGILState_Ensure(void) { - int current; - PyThreadState *tcur; - /* Note that we do not auto-init Python here - apart from - potential races with 2 threads auto-initializing, pep-311 - spells out other issues. Embedders are expected to have - called Py_Initialize() and usually PyEval_InitThreads(). - */ - assert(autoInterpreterState); /* Py_Initialize() hasn't been called! */ - tcur = (PyThreadState *)PyThread_get_key_value(autoTLSkey); - if (tcur == NULL) { - /* Create a new thread state for this thread */ - tcur = PyThreadState_New(autoInterpreterState); - if (tcur == NULL) - Py_FatalError("Couldn't create thread-state for new thread"); - /* This is our thread state! We'll need to delete it in the - matching call to PyGILState_Release(). */ - tcur->gilstate_counter = 0; - current = 0; /* new thread state is never current */ - } - else - current = PyThreadState_IsCurrent(tcur); - if (current == 0) - PyEval_RestoreThread(tcur); - /* Update our counter in the thread-state - no need for locks: - - tcur will remain valid as we hold the GIL. - - the counter is safe as we are the only thread "allowed" - to modify this value - */ - ++tcur->gilstate_counter; - return current ? PyGILState_LOCKED : PyGILState_UNLOCKED; + int current; + PyThreadState *tcur; + /* Note that we do not auto-init Python here - apart from + potential races with 2 threads auto-initializing, pep-311 + spells out other issues. Embedders are expected to have + called Py_Initialize() and usually PyEval_InitThreads(). + */ + assert(autoInterpreterState); /* Py_Initialize() hasn't been called! */ + tcur = (PyThreadState *)PyThread_get_key_value(autoTLSkey); + if (tcur == NULL) { + /* Create a new thread state for this thread */ + tcur = PyThreadState_New(autoInterpreterState); + if (tcur == NULL) + Py_FatalError("Couldn't create thread-state for new thread"); + /* This is our thread state! We'll need to delete it in the + matching call to PyGILState_Release(). */ + tcur->gilstate_counter = 0; + current = 0; /* new thread state is never current */ + } + else + current = PyThreadState_IsCurrent(tcur); + if (current == 0) + PyEval_RestoreThread(tcur); + /* Update our counter in the thread-state - no need for locks: + - tcur will remain valid as we hold the GIL. + - the counter is safe as we are the only thread "allowed" + to modify this value + */ + ++tcur->gilstate_counter; + return current ? PyGILState_LOCKED : PyGILState_UNLOCKED; } void PyGILState_Release(PyGILState_STATE oldstate) { - PyThreadState *tcur = (PyThreadState *)PyThread_get_key_value( - autoTLSkey); - if (tcur == NULL) - Py_FatalError("auto-releasing thread-state, " - "but no thread-state for this thread"); - /* We must hold the GIL and have our thread state current */ - /* XXX - remove the check - the assert should be fine, - but while this is very new (April 2003), the extra check - by release-only users can't hurt. - */ - if (! PyThreadState_IsCurrent(tcur)) - Py_FatalError("This thread state must be current when releasing"); - assert(PyThreadState_IsCurrent(tcur)); - --tcur->gilstate_counter; - assert(tcur->gilstate_counter >= 0); /* illegal counter value */ - - /* If we're going to destroy this thread-state, we must - * clear it while the GIL is held, as destructors may run. - */ - if (tcur->gilstate_counter == 0) { - /* can't have been locked when we created it */ - assert(oldstate == PyGILState_UNLOCKED); - PyThreadState_Clear(tcur); - /* Delete the thread-state. Note this releases the GIL too! - * It's vital that the GIL be held here, to avoid shutdown - * races; see bugs 225673 and 1061968 (that nasty bug has a - * habit of coming back). - */ - PyThreadState_DeleteCurrent(); - } - /* Release the lock if necessary */ - else if (oldstate == PyGILState_UNLOCKED) - PyEval_SaveThread(); + PyThreadState *tcur = (PyThreadState *)PyThread_get_key_value( + autoTLSkey); + if (tcur == NULL) + Py_FatalError("auto-releasing thread-state, " + "but no thread-state for this thread"); + /* We must hold the GIL and have our thread state current */ + /* XXX - remove the check - the assert should be fine, + but while this is very new (April 2003), the extra check + by release-only users can't hurt. + */ + if (! PyThreadState_IsCurrent(tcur)) + Py_FatalError("This thread state must be current when releasing"); + assert(PyThreadState_IsCurrent(tcur)); + --tcur->gilstate_counter; + assert(tcur->gilstate_counter >= 0); /* illegal counter value */ + + /* If we're going to destroy this thread-state, we must + * clear it while the GIL is held, as destructors may run. + */ + if (tcur->gilstate_counter == 0) { + /* can't have been locked when we created it */ + assert(oldstate == PyGILState_UNLOCKED); + PyThreadState_Clear(tcur); + /* Delete the thread-state. Note this releases the GIL too! + * It's vital that the GIL be held here, to avoid shutdown + * races; see bugs 225673 and 1061968 (that nasty bug has a + * habit of coming back). + */ + PyThreadState_DeleteCurrent(); + } + /* Release the lock if necessary */ + else if (oldstate == PyGILState_UNLOCKED) + PyEval_SaveThread(); } #ifdef __cplusplus Modified: python/branches/release31-maint/Python/pystrcmp.c ============================================================================== --- python/branches/release31-maint/Python/pystrcmp.c (original) +++ python/branches/release31-maint/Python/pystrcmp.c Sun May 9 18:14:21 2010 @@ -6,21 +6,21 @@ int PyOS_mystrnicmp(const char *s1, const char *s2, Py_ssize_t size) { - if (size == 0) - return 0; - while ((--size > 0) && - (tolower((unsigned)*s1) == tolower((unsigned)*s2))) { - if (!*s1++ || !*s2++) - break; - } - return tolower((unsigned)*s1) - tolower((unsigned)*s2); + if (size == 0) + return 0; + while ((--size > 0) && + (tolower((unsigned)*s1) == tolower((unsigned)*s2))) { + if (!*s1++ || !*s2++) + break; + } + return tolower((unsigned)*s1) - tolower((unsigned)*s2); } int PyOS_mystricmp(const char *s1, const char *s2) { - while (*s1 && (tolower((unsigned)*s1++) == tolower((unsigned)*s2++))) { - ; - } - return (tolower((unsigned)*s1) - tolower((unsigned)*s2)); + while (*s1 && (tolower((unsigned)*s1++) == tolower((unsigned)*s2++))) { + ; + } + return (tolower((unsigned)*s1) - tolower((unsigned)*s2)); } Modified: python/branches/release31-maint/Python/pystrtod.c ============================================================================== --- python/branches/release31-maint/Python/pystrtod.c (original) +++ python/branches/release31-maint/Python/pystrtod.c Sun May 9 18:14:21 2010 @@ -12,46 +12,46 @@ static int case_insensitive_match(const char *s, const char *t) { - while(*t && Py_TOLOWER(*s) == *t) { - s++; - t++; - } - return *t ? 0 : 1; + while(*t && Py_TOLOWER(*s) == *t) { + s++; + t++; + } + return *t ? 0 : 1; } double _Py_parse_inf_or_nan(const char *p, char **endptr) { - double retval; - const char *s; - int negate = 0; - - s = p; - if (*s == '-') { - negate = 1; - s++; - } - else if (*s == '+') { - s++; - } - if (case_insensitive_match(s, "inf")) { - s += 3; - if (case_insensitive_match(s, "inity")) - s += 5; - retval = negate ? -Py_HUGE_VAL : Py_HUGE_VAL; - } + double retval; + const char *s; + int negate = 0; + + s = p; + if (*s == '-') { + negate = 1; + s++; + } + else if (*s == '+') { + s++; + } + if (case_insensitive_match(s, "inf")) { + s += 3; + if (case_insensitive_match(s, "inity")) + s += 5; + retval = negate ? -Py_HUGE_VAL : Py_HUGE_VAL; + } #ifdef Py_NAN - else if (case_insensitive_match(s, "nan")) { - s += 3; - retval = negate ? -Py_NAN : Py_NAN; - } + else if (case_insensitive_match(s, "nan")) { + s += 3; + retval = negate ? -Py_NAN : Py_NAN; + } #endif - else { - s = p; - retval = -1.0; - } - *endptr = (char *)s; - return retval; + else { + s = p; + retval = -1.0; + } + *endptr = (char *)s; + return retval; } /** @@ -59,7 +59,7 @@ * @nptr: the string to convert to a numeric value. * @endptr: if non-%NULL, it returns the character after * the last character used in the conversion. - * + * * Converts a string to a #gdouble value. * This function behaves like the standard strtod() function * does in the C locale. It does this without actually @@ -76,7 +76,7 @@ * stored in %errno. If the correct value would cause underflow, * zero is returned and %ERANGE is stored in %errno. * If memory allocation fails, %ENOMEM is stored in %errno. - * + * * This function resets %errno before calling strtod() so that * you can reliably detect overflow and underflow. * @@ -88,23 +88,23 @@ double _PyOS_ascii_strtod(const char *nptr, char **endptr) { - double result; - _Py_SET_53BIT_PRECISION_HEADER; + double result; + _Py_SET_53BIT_PRECISION_HEADER; - assert(nptr != NULL); - /* Set errno to zero, so that we can distinguish zero results - and underflows */ - errno = 0; - - _Py_SET_53BIT_PRECISION_START; - result = _Py_dg_strtod(nptr, endptr); - _Py_SET_53BIT_PRECISION_END; - - if (*endptr == nptr) - /* string might represent an inf or nan */ - result = _Py_parse_inf_or_nan(nptr, endptr); + assert(nptr != NULL); + /* Set errno to zero, so that we can distinguish zero results + and underflows */ + errno = 0; + + _Py_SET_53BIT_PRECISION_START; + result = _Py_dg_strtod(nptr, endptr); + _Py_SET_53BIT_PRECISION_END; + + if (*endptr == nptr) + /* string might represent an inf or nan */ + result = _Py_parse_inf_or_nan(nptr, endptr); - return result; + return result; } @@ -121,148 +121,148 @@ double _PyOS_ascii_strtod(const char *nptr, char **endptr) { - char *fail_pos; - double val = -1.0; - struct lconv *locale_data; - const char *decimal_point; - size_t decimal_point_len; - const char *p, *decimal_point_pos; - const char *end = NULL; /* Silence gcc */ - const char *digits_pos = NULL; - int negate = 0; - - assert(nptr != NULL); - - fail_pos = NULL; - - locale_data = localeconv(); - decimal_point = locale_data->decimal_point; - decimal_point_len = strlen(decimal_point); - - assert(decimal_point_len != 0); - - decimal_point_pos = NULL; - - /* Parse infinities and nans */ - val = _Py_parse_inf_or_nan(nptr, endptr); - if (*endptr != nptr) - return val; - - /* Set errno to zero, so that we can distinguish zero results - and underflows */ - errno = 0; - - /* We process the optional sign manually, then pass the remainder to - the system strtod. This ensures that the result of an underflow - has the correct sign. (bug #1725) */ - p = nptr; - /* Process leading sign, if present */ - if (*p == '-') { - negate = 1; - p++; - } - else if (*p == '+') { - p++; - } - - /* Some platform strtods accept hex floats; Python shouldn't (at the - moment), so we check explicitly for strings starting with '0x'. */ - if (*p == '0' && (*(p+1) == 'x' || *(p+1) == 'X')) - goto invalid_string; - - /* Check that what's left begins with a digit or decimal point */ - if (!Py_ISDIGIT(*p) && *p != '.') - goto invalid_string; - - digits_pos = p; - if (decimal_point[0] != '.' || - decimal_point[1] != 0) - { - /* Look for a '.' in the input; if present, it'll need to be - swapped for the current locale's decimal point before we - call strtod. On the other hand, if we find the current - locale's decimal point then the input is invalid. */ - while (Py_ISDIGIT(*p)) - p++; - - if (*p == '.') - { - decimal_point_pos = p++; - - /* locate end of number */ - while (Py_ISDIGIT(*p)) - p++; - - if (*p == 'e' || *p == 'E') - p++; - if (*p == '+' || *p == '-') - p++; - while (Py_ISDIGIT(*p)) - p++; - end = p; - } - else if (strncmp(p, decimal_point, decimal_point_len) == 0) - /* Python bug #1417699 */ - goto invalid_string; - /* For the other cases, we need not convert the decimal - point */ - } - - if (decimal_point_pos) { - char *copy, *c; - /* Create a copy of the input, with the '.' converted to the - locale-specific decimal point */ - copy = (char *)PyMem_MALLOC(end - digits_pos + - 1 + decimal_point_len); - if (copy == NULL) { - *endptr = (char *)nptr; - errno = ENOMEM; - return val; - } - - c = copy; - memcpy(c, digits_pos, decimal_point_pos - digits_pos); - c += decimal_point_pos - digits_pos; - memcpy(c, decimal_point, decimal_point_len); - c += decimal_point_len; - memcpy(c, decimal_point_pos + 1, - end - (decimal_point_pos + 1)); - c += end - (decimal_point_pos + 1); - *c = 0; - - val = strtod(copy, &fail_pos); - - if (fail_pos) - { - if (fail_pos > decimal_point_pos) - fail_pos = (char *)digits_pos + - (fail_pos - copy) - - (decimal_point_len - 1); - else - fail_pos = (char *)digits_pos + - (fail_pos - copy); - } - - PyMem_FREE(copy); - - } - else { - val = strtod(digits_pos, &fail_pos); - } - - if (fail_pos == digits_pos) - goto invalid_string; - - if (negate && fail_pos != nptr) - val = -val; - *endptr = fail_pos; + char *fail_pos; + double val = -1.0; + struct lconv *locale_data; + const char *decimal_point; + size_t decimal_point_len; + const char *p, *decimal_point_pos; + const char *end = NULL; /* Silence gcc */ + const char *digits_pos = NULL; + int negate = 0; + + assert(nptr != NULL); + + fail_pos = NULL; + + locale_data = localeconv(); + decimal_point = locale_data->decimal_point; + decimal_point_len = strlen(decimal_point); + + assert(decimal_point_len != 0); + + decimal_point_pos = NULL; + + /* Parse infinities and nans */ + val = _Py_parse_inf_or_nan(nptr, endptr); + if (*endptr != nptr) + return val; + + /* Set errno to zero, so that we can distinguish zero results + and underflows */ + errno = 0; + + /* We process the optional sign manually, then pass the remainder to + the system strtod. This ensures that the result of an underflow + has the correct sign. (bug #1725) */ + p = nptr; + /* Process leading sign, if present */ + if (*p == '-') { + negate = 1; + p++; + } + else if (*p == '+') { + p++; + } + + /* Some platform strtods accept hex floats; Python shouldn't (at the + moment), so we check explicitly for strings starting with '0x'. */ + if (*p == '0' && (*(p+1) == 'x' || *(p+1) == 'X')) + goto invalid_string; + + /* Check that what's left begins with a digit or decimal point */ + if (!Py_ISDIGIT(*p) && *p != '.') + goto invalid_string; + + digits_pos = p; + if (decimal_point[0] != '.' || + decimal_point[1] != 0) + { + /* Look for a '.' in the input; if present, it'll need to be + swapped for the current locale's decimal point before we + call strtod. On the other hand, if we find the current + locale's decimal point then the input is invalid. */ + while (Py_ISDIGIT(*p)) + p++; + + if (*p == '.') + { + decimal_point_pos = p++; + + /* locate end of number */ + while (Py_ISDIGIT(*p)) + p++; + + if (*p == 'e' || *p == 'E') + p++; + if (*p == '+' || *p == '-') + p++; + while (Py_ISDIGIT(*p)) + p++; + end = p; + } + else if (strncmp(p, decimal_point, decimal_point_len) == 0) + /* Python bug #1417699 */ + goto invalid_string; + /* For the other cases, we need not convert the decimal + point */ + } + + if (decimal_point_pos) { + char *copy, *c; + /* Create a copy of the input, with the '.' converted to the + locale-specific decimal point */ + copy = (char *)PyMem_MALLOC(end - digits_pos + + 1 + decimal_point_len); + if (copy == NULL) { + *endptr = (char *)nptr; + errno = ENOMEM; + return val; + } + + c = copy; + memcpy(c, digits_pos, decimal_point_pos - digits_pos); + c += decimal_point_pos - digits_pos; + memcpy(c, decimal_point, decimal_point_len); + c += decimal_point_len; + memcpy(c, decimal_point_pos + 1, + end - (decimal_point_pos + 1)); + c += end - (decimal_point_pos + 1); + *c = 0; + + val = strtod(copy, &fail_pos); + + if (fail_pos) + { + if (fail_pos > decimal_point_pos) + fail_pos = (char *)digits_pos + + (fail_pos - copy) - + (decimal_point_len - 1); + else + fail_pos = (char *)digits_pos + + (fail_pos - copy); + } + + PyMem_FREE(copy); + + } + else { + val = strtod(digits_pos, &fail_pos); + } + + if (fail_pos == digits_pos) + goto invalid_string; + + if (negate && fail_pos != nptr) + val = -val; + *endptr = fail_pos; - return val; + return val; invalid_string: - *endptr = (char*)nptr; - errno = EINVAL; - return -1.0; + *endptr = (char*)nptr; + errno = EINVAL; + return -1.0; } #endif @@ -272,27 +272,27 @@ double PyOS_ascii_strtod(const char *nptr, char **endptr) { - char *fail_pos; - const char *p; - double x; - - if (PyErr_WarnEx(PyExc_DeprecationWarning, - "PyOS_ascii_strtod and PyOS_ascii_atof are " - "deprecated. Use PyOS_string_to_double " - "instead.", 1) < 0) - return -1.0; - - /* _PyOS_ascii_strtod already does everything that we want, - except that it doesn't parse leading whitespace */ - p = nptr; - while (Py_ISSPACE(*p)) - p++; - x = _PyOS_ascii_strtod(p, &fail_pos); - if (fail_pos == p) - fail_pos = (char *)nptr; - if (endptr) - *endptr = (char *)fail_pos; - return x; + char *fail_pos; + const char *p; + double x; + + if (PyErr_WarnEx(PyExc_DeprecationWarning, + "PyOS_ascii_strtod and PyOS_ascii_atof are " + "deprecated. Use PyOS_string_to_double " + "instead.", 1) < 0) + return -1.0; + + /* _PyOS_ascii_strtod already does everything that we want, + except that it doesn't parse leading whitespace */ + p = nptr; + while (Py_ISSPACE(*p)) + p++; + x = _PyOS_ascii_strtod(p, &fail_pos); + if (fail_pos == p) + fail_pos = (char *)nptr; + if (endptr) + *endptr = (char *)fail_pos; + return x; } /* PyOS_ascii_strtod is DEPRECATED in Python 3.1 */ @@ -300,7 +300,7 @@ double PyOS_ascii_atof(const char *nptr) { - return PyOS_ascii_strtod(nptr, NULL); + return PyOS_ascii_strtod(nptr, NULL); } /* PyOS_string_to_double is the recommended replacement for the deprecated @@ -331,39 +331,39 @@ double PyOS_string_to_double(const char *s, - char **endptr, - PyObject *overflow_exception) + char **endptr, + PyObject *overflow_exception) { - double x, result=-1.0; - char *fail_pos; + double x, result=-1.0; + char *fail_pos; - errno = 0; - PyFPE_START_PROTECT("PyOS_string_to_double", return -1.0) - x = _PyOS_ascii_strtod(s, &fail_pos); - PyFPE_END_PROTECT(x) - - if (errno == ENOMEM) { - PyErr_NoMemory(); - fail_pos = (char *)s; - } - else if (!endptr && (fail_pos == s || *fail_pos != '\0')) - PyErr_Format(PyExc_ValueError, - "could not convert string to float: " - "%.200s", s); - else if (fail_pos == s) - PyErr_Format(PyExc_ValueError, - "could not convert string to float: " - "%.200s", s); - else if (errno == ERANGE && fabs(x) >= 1.0 && overflow_exception) - PyErr_Format(overflow_exception, - "value too large to convert to float: " - "%.200s", s); - else - result = x; - - if (endptr != NULL) - *endptr = fail_pos; - return result; + errno = 0; + PyFPE_START_PROTECT("PyOS_string_to_double", return -1.0) + x = _PyOS_ascii_strtod(s, &fail_pos); + PyFPE_END_PROTECT(x) + + if (errno == ENOMEM) { + PyErr_NoMemory(); + fail_pos = (char *)s; + } + else if (!endptr && (fail_pos == s || *fail_pos != '\0')) + PyErr_Format(PyExc_ValueError, + "could not convert string to float: " + "%.200s", s); + else if (fail_pos == s) + PyErr_Format(PyExc_ValueError, + "could not convert string to float: " + "%.200s", s); + else if (errno == ERANGE && fabs(x) >= 1.0 && overflow_exception) + PyErr_Format(overflow_exception, + "value too large to convert to float: " + "%.200s", s); + else + result = x; + + if (endptr != NULL) + *endptr = fail_pos; + return result; } /* Given a string that may have a decimal point in the current @@ -372,30 +372,30 @@ Py_LOCAL_INLINE(void) change_decimal_from_locale_to_dot(char* buffer) { - struct lconv *locale_data = localeconv(); - const char *decimal_point = locale_data->decimal_point; + struct lconv *locale_data = localeconv(); + const char *decimal_point = locale_data->decimal_point; - if (decimal_point[0] != '.' || decimal_point[1] != 0) { - size_t decimal_point_len = strlen(decimal_point); + if (decimal_point[0] != '.' || decimal_point[1] != 0) { + size_t decimal_point_len = strlen(decimal_point); - if (*buffer == '+' || *buffer == '-') - buffer++; - while (Py_ISDIGIT(*buffer)) - buffer++; - if (strncmp(buffer, decimal_point, decimal_point_len) == 0) { - *buffer = '.'; - buffer++; - if (decimal_point_len > 1) { - /* buffer needs to get smaller */ - size_t rest_len = strlen(buffer + - (decimal_point_len - 1)); - memmove(buffer, - buffer + (decimal_point_len - 1), - rest_len); - buffer[rest_len] = 0; - } - } - } + if (*buffer == '+' || *buffer == '-') + buffer++; + while (Py_ISDIGIT(*buffer)) + buffer++; + if (strncmp(buffer, decimal_point, decimal_point_len) == 0) { + *buffer = '.'; + buffer++; + if (decimal_point_len > 1) { + /* buffer needs to get smaller */ + size_t rest_len = strlen(buffer + + (decimal_point_len - 1)); + memmove(buffer, + buffer + (decimal_point_len - 1), + rest_len); + buffer[rest_len] = 0; + } + } + } } @@ -410,65 +410,65 @@ Py_LOCAL_INLINE(void) ensure_minimum_exponent_length(char* buffer, size_t buf_size) { - char *p = strpbrk(buffer, "eE"); - if (p && (*(p + 1) == '-' || *(p + 1) == '+')) { - char *start = p + 2; - int exponent_digit_cnt = 0; - int leading_zero_cnt = 0; - int in_leading_zeros = 1; - int significant_digit_cnt; - - /* Skip over the exponent and the sign. */ - p += 2; - - /* Find the end of the exponent, keeping track of leading - zeros. */ - while (*p && Py_ISDIGIT(*p)) { - if (in_leading_zeros && *p == '0') - ++leading_zero_cnt; - if (*p != '0') - in_leading_zeros = 0; - ++p; - ++exponent_digit_cnt; - } - - significant_digit_cnt = exponent_digit_cnt - leading_zero_cnt; - if (exponent_digit_cnt == MIN_EXPONENT_DIGITS) { - /* If there are 2 exactly digits, we're done, - regardless of what they contain */ - } - else if (exponent_digit_cnt > MIN_EXPONENT_DIGITS) { - int extra_zeros_cnt; - - /* There are more than 2 digits in the exponent. See - if we can delete some of the leading zeros */ - if (significant_digit_cnt < MIN_EXPONENT_DIGITS) - significant_digit_cnt = MIN_EXPONENT_DIGITS; - extra_zeros_cnt = exponent_digit_cnt - - significant_digit_cnt; - - /* Delete extra_zeros_cnt worth of characters from the - front of the exponent */ - assert(extra_zeros_cnt >= 0); - - /* Add one to significant_digit_cnt to copy the - trailing 0 byte, thus setting the length */ - memmove(start, - start + extra_zeros_cnt, - significant_digit_cnt + 1); - } - else { - /* If there are fewer than 2 digits, add zeros - until there are 2, if there's enough room */ - int zeros = MIN_EXPONENT_DIGITS - exponent_digit_cnt; - if (start + zeros + exponent_digit_cnt + 1 - < buffer + buf_size) { - memmove(start + zeros, start, - exponent_digit_cnt + 1); - memset(start, '0', zeros); - } - } - } + char *p = strpbrk(buffer, "eE"); + if (p && (*(p + 1) == '-' || *(p + 1) == '+')) { + char *start = p + 2; + int exponent_digit_cnt = 0; + int leading_zero_cnt = 0; + int in_leading_zeros = 1; + int significant_digit_cnt; + + /* Skip over the exponent and the sign. */ + p += 2; + + /* Find the end of the exponent, keeping track of leading + zeros. */ + while (*p && Py_ISDIGIT(*p)) { + if (in_leading_zeros && *p == '0') + ++leading_zero_cnt; + if (*p != '0') + in_leading_zeros = 0; + ++p; + ++exponent_digit_cnt; + } + + significant_digit_cnt = exponent_digit_cnt - leading_zero_cnt; + if (exponent_digit_cnt == MIN_EXPONENT_DIGITS) { + /* If there are 2 exactly digits, we're done, + regardless of what they contain */ + } + else if (exponent_digit_cnt > MIN_EXPONENT_DIGITS) { + int extra_zeros_cnt; + + /* There are more than 2 digits in the exponent. See + if we can delete some of the leading zeros */ + if (significant_digit_cnt < MIN_EXPONENT_DIGITS) + significant_digit_cnt = MIN_EXPONENT_DIGITS; + extra_zeros_cnt = exponent_digit_cnt - + significant_digit_cnt; + + /* Delete extra_zeros_cnt worth of characters from the + front of the exponent */ + assert(extra_zeros_cnt >= 0); + + /* Add one to significant_digit_cnt to copy the + trailing 0 byte, thus setting the length */ + memmove(start, + start + extra_zeros_cnt, + significant_digit_cnt + 1); + } + else { + /* If there are fewer than 2 digits, add zeros + until there are 2, if there's enough room */ + int zeros = MIN_EXPONENT_DIGITS - exponent_digit_cnt; + if (start + zeros + exponent_digit_cnt + 1 + < buffer + buf_size) { + memmove(start + zeros, start, + exponent_digit_cnt + 1); + memset(start, '0', zeros); + } + } + } } /* Remove trailing zeros after the decimal point from a numeric string; also @@ -478,40 +478,40 @@ Py_LOCAL_INLINE(void) remove_trailing_zeros(char *buffer) { - char *old_fraction_end, *new_fraction_end, *end, *p; + char *old_fraction_end, *new_fraction_end, *end, *p; - p = buffer; - if (*p == '-' || *p == '+') - /* Skip leading sign, if present */ - ++p; - while (Py_ISDIGIT(*p)) - ++p; - - /* if there's no decimal point there's nothing to do */ - if (*p++ != '.') - return; - - /* scan any digits after the point */ - while (Py_ISDIGIT(*p)) - ++p; - old_fraction_end = p; - - /* scan up to ending '\0' */ - while (*p != '\0') - p++; - /* +1 to make sure that we move the null byte as well */ - end = p+1; - - /* scan back from fraction_end, looking for removable zeros */ - p = old_fraction_end; - while (*(p-1) == '0') - --p; - /* and remove point if we've got that far */ - if (*(p-1) == '.') - --p; - new_fraction_end = p; + p = buffer; + if (*p == '-' || *p == '+') + /* Skip leading sign, if present */ + ++p; + while (Py_ISDIGIT(*p)) + ++p; + + /* if there's no decimal point there's nothing to do */ + if (*p++ != '.') + return; + + /* scan any digits after the point */ + while (Py_ISDIGIT(*p)) + ++p; + old_fraction_end = p; + + /* scan up to ending '\0' */ + while (*p != '\0') + p++; + /* +1 to make sure that we move the null byte as well */ + end = p+1; + + /* scan back from fraction_end, looking for removable zeros */ + p = old_fraction_end; + while (*(p-1) == '0') + --p; + /* and remove point if we've got that far */ + if (*(p-1) == '.') + --p; + new_fraction_end = p; - memmove(new_fraction_end, old_fraction_end, end-old_fraction_end); + memmove(new_fraction_end, old_fraction_end, end-old_fraction_end); } /* Ensure that buffer has a decimal point in it. The decimal point will not @@ -524,91 +524,91 @@ Py_LOCAL_INLINE(char *) ensure_decimal_point(char* buffer, size_t buf_size, int precision) { - int digit_count, insert_count = 0, convert_to_exp = 0; - char *chars_to_insert, *digits_start; + int digit_count, insert_count = 0, convert_to_exp = 0; + char *chars_to_insert, *digits_start; - /* search for the first non-digit character */ - char *p = buffer; - if (*p == '-' || *p == '+') - /* Skip leading sign, if present. I think this could only - ever be '-', but it can't hurt to check for both. */ - ++p; - digits_start = p; - while (*p && Py_ISDIGIT(*p)) - ++p; - digit_count = Py_SAFE_DOWNCAST(p - digits_start, Py_ssize_t, int); - - if (*p == '.') { - if (Py_ISDIGIT(*(p+1))) { - /* Nothing to do, we already have a decimal - point and a digit after it */ - } - else { - /* We have a decimal point, but no following - digit. Insert a zero after the decimal. */ - /* can't ever get here via PyOS_double_to_string */ - assert(precision == -1); - ++p; - chars_to_insert = "0"; - insert_count = 1; - } - } - else if (!(*p == 'e' || *p == 'E')) { - /* Don't add ".0" if we have an exponent. */ - if (digit_count == precision) { - /* issue 5864: don't add a trailing .0 in the case - where the '%g'-formatted result already has as many - significant digits as were requested. Switch to - exponential notation instead. */ - convert_to_exp = 1; - /* no exponent, no point, and we shouldn't land here - for infs and nans, so we must be at the end of the - string. */ - assert(*p == '\0'); - } - else { - assert(precision == -1 || digit_count < precision); - chars_to_insert = ".0"; - insert_count = 2; - } - } - if (insert_count) { - size_t buf_len = strlen(buffer); - if (buf_len + insert_count + 1 >= buf_size) { - /* If there is not enough room in the buffer - for the additional text, just skip it. It's - not worth generating an error over. */ - } - else { - memmove(p + insert_count, p, - buffer + strlen(buffer) - p + 1); - memcpy(p, chars_to_insert, insert_count); - } - } - if (convert_to_exp) { - int written; - size_t buf_avail; - p = digits_start; - /* insert decimal point */ - assert(digit_count >= 1); - memmove(p+2, p+1, digit_count); /* safe, but overwrites nul */ - p[1] = '.'; - p += digit_count+1; - assert(p <= buf_size+buffer); - buf_avail = buf_size+buffer-p; - if (buf_avail == 0) - return NULL; - /* Add exponent. It's okay to use lower case 'e': we only - arrive here as a result of using the empty format code or - repr/str builtins and those never want an upper case 'E' */ - written = PyOS_snprintf(p, buf_avail, "e%+.02d", digit_count-1); - if (!(0 <= written && - written < Py_SAFE_DOWNCAST(buf_avail, size_t, int))) - /* output truncated, or something else bad happened */ - return NULL; - remove_trailing_zeros(buffer); - } - return buffer; + /* search for the first non-digit character */ + char *p = buffer; + if (*p == '-' || *p == '+') + /* Skip leading sign, if present. I think this could only + ever be '-', but it can't hurt to check for both. */ + ++p; + digits_start = p; + while (*p && Py_ISDIGIT(*p)) + ++p; + digit_count = Py_SAFE_DOWNCAST(p - digits_start, Py_ssize_t, int); + + if (*p == '.') { + if (Py_ISDIGIT(*(p+1))) { + /* Nothing to do, we already have a decimal + point and a digit after it */ + } + else { + /* We have a decimal point, but no following + digit. Insert a zero after the decimal. */ + /* can't ever get here via PyOS_double_to_string */ + assert(precision == -1); + ++p; + chars_to_insert = "0"; + insert_count = 1; + } + } + else if (!(*p == 'e' || *p == 'E')) { + /* Don't add ".0" if we have an exponent. */ + if (digit_count == precision) { + /* issue 5864: don't add a trailing .0 in the case + where the '%g'-formatted result already has as many + significant digits as were requested. Switch to + exponential notation instead. */ + convert_to_exp = 1; + /* no exponent, no point, and we shouldn't land here + for infs and nans, so we must be at the end of the + string. */ + assert(*p == '\0'); + } + else { + assert(precision == -1 || digit_count < precision); + chars_to_insert = ".0"; + insert_count = 2; + } + } + if (insert_count) { + size_t buf_len = strlen(buffer); + if (buf_len + insert_count + 1 >= buf_size) { + /* If there is not enough room in the buffer + for the additional text, just skip it. It's + not worth generating an error over. */ + } + else { + memmove(p + insert_count, p, + buffer + strlen(buffer) - p + 1); + memcpy(p, chars_to_insert, insert_count); + } + } + if (convert_to_exp) { + int written; + size_t buf_avail; + p = digits_start; + /* insert decimal point */ + assert(digit_count >= 1); + memmove(p+2, p+1, digit_count); /* safe, but overwrites nul */ + p[1] = '.'; + p += digit_count+1; + assert(p <= buf_size+buffer); + buf_avail = buf_size+buffer-p; + if (buf_avail == 0) + return NULL; + /* Add exponent. It's okay to use lower case 'e': we only + arrive here as a result of using the empty format code or + repr/str builtins and those never want an upper case 'E' */ + written = PyOS_snprintf(p, buf_avail, "e%+.02d", digit_count-1); + if (!(0 <= written && + written < Py_SAFE_DOWNCAST(buf_avail, size_t, int))) + /* output truncated, or something else bad happened */ + return NULL; + remove_trailing_zeros(buffer); + } + return buffer; } /* see FORMATBUFLEN in unicodeobject.c */ @@ -619,14 +619,14 @@ * @buffer: A buffer to place the resulting string in * @buf_size: The length of the buffer. * @format: The printf()-style format to use for the - * code to use for converting. + * code to use for converting. * @d: The #gdouble to convert * * Converts a #gdouble to a string, using the '.' as * decimal point. To format the number you pass in * a printf()-style format string. Allowed conversion * specifiers are 'e', 'E', 'f', 'F', 'g', 'G', and 'Z'. - * + * * 'Z' is the same as 'g', except it always has a decimal and * at least one digit after the decimal. * @@ -634,97 +634,97 @@ * On failure returns NULL but does not set any Python exception. **/ char * -_PyOS_ascii_formatd(char *buffer, - size_t buf_size, - const char *format, - double d, - int precision) +_PyOS_ascii_formatd(char *buffer, + size_t buf_size, + const char *format, + double d, + int precision) { - char format_char; - size_t format_len = strlen(format); + char format_char; + size_t format_len = strlen(format); - /* Issue 2264: code 'Z' requires copying the format. 'Z' is 'g', but - also with at least one character past the decimal. */ - char tmp_format[FLOAT_FORMATBUFLEN]; - - /* The last character in the format string must be the format char */ - format_char = format[format_len - 1]; - - if (format[0] != '%') - return NULL; - - /* I'm not sure why this test is here. It's ensuring that the format - string after the first character doesn't have a single quote, a - lowercase l, or a percent. This is the reverse of the commented-out - test about 10 lines ago. */ - if (strpbrk(format + 1, "'l%")) - return NULL; - - /* Also curious about this function is that it accepts format strings - like "%xg", which are invalid for floats. In general, the - interface to this function is not very good, but changing it is - difficult because it's a public API. */ - - if (!(format_char == 'e' || format_char == 'E' || - format_char == 'f' || format_char == 'F' || - format_char == 'g' || format_char == 'G' || - format_char == 'Z')) - return NULL; - - /* Map 'Z' format_char to 'g', by copying the format string and - replacing the final char with a 'g' */ - if (format_char == 'Z') { - if (format_len + 1 >= sizeof(tmp_format)) { - /* The format won't fit in our copy. Error out. In - practice, this will never happen and will be - detected by returning NULL */ - return NULL; - } - strcpy(tmp_format, format); - tmp_format[format_len - 1] = 'g'; - format = tmp_format; - } - - - /* Have PyOS_snprintf do the hard work */ - PyOS_snprintf(buffer, buf_size, format, d); - - /* Do various fixups on the return string */ - - /* Get the current locale, and find the decimal point string. - Convert that string back to a dot. */ - change_decimal_from_locale_to_dot(buffer); - - /* If an exponent exists, ensure that the exponent is at least - MIN_EXPONENT_DIGITS digits, providing the buffer is large enough - for the extra zeros. Also, if there are more than - MIN_EXPONENT_DIGITS, remove as many zeros as possible until we get - back to MIN_EXPONENT_DIGITS */ - ensure_minimum_exponent_length(buffer, buf_size); - - /* If format_char is 'Z', make sure we have at least one character - after the decimal point (and make sure we have a decimal point); - also switch to exponential notation in some edge cases where the - extra character would produce more significant digits that we - really want. */ - if (format_char == 'Z') - buffer = ensure_decimal_point(buffer, buf_size, precision); + /* Issue 2264: code 'Z' requires copying the format. 'Z' is 'g', but + also with at least one character past the decimal. */ + char tmp_format[FLOAT_FORMATBUFLEN]; + + /* The last character in the format string must be the format char */ + format_char = format[format_len - 1]; + + if (format[0] != '%') + return NULL; + + /* I'm not sure why this test is here. It's ensuring that the format + string after the first character doesn't have a single quote, a + lowercase l, or a percent. This is the reverse of the commented-out + test about 10 lines ago. */ + if (strpbrk(format + 1, "'l%")) + return NULL; + + /* Also curious about this function is that it accepts format strings + like "%xg", which are invalid for floats. In general, the + interface to this function is not very good, but changing it is + difficult because it's a public API. */ + + if (!(format_char == 'e' || format_char == 'E' || + format_char == 'f' || format_char == 'F' || + format_char == 'g' || format_char == 'G' || + format_char == 'Z')) + return NULL; + + /* Map 'Z' format_char to 'g', by copying the format string and + replacing the final char with a 'g' */ + if (format_char == 'Z') { + if (format_len + 1 >= sizeof(tmp_format)) { + /* The format won't fit in our copy. Error out. In + practice, this will never happen and will be + detected by returning NULL */ + return NULL; + } + strcpy(tmp_format, format); + tmp_format[format_len - 1] = 'g'; + format = tmp_format; + } + + + /* Have PyOS_snprintf do the hard work */ + PyOS_snprintf(buffer, buf_size, format, d); + + /* Do various fixups on the return string */ + + /* Get the current locale, and find the decimal point string. + Convert that string back to a dot. */ + change_decimal_from_locale_to_dot(buffer); + + /* If an exponent exists, ensure that the exponent is at least + MIN_EXPONENT_DIGITS digits, providing the buffer is large enough + for the extra zeros. Also, if there are more than + MIN_EXPONENT_DIGITS, remove as many zeros as possible until we get + back to MIN_EXPONENT_DIGITS */ + ensure_minimum_exponent_length(buffer, buf_size); + + /* If format_char is 'Z', make sure we have at least one character + after the decimal point (and make sure we have a decimal point); + also switch to exponential notation in some edge cases where the + extra character would produce more significant digits that we + really want. */ + if (format_char == 'Z') + buffer = ensure_decimal_point(buffer, buf_size, precision); - return buffer; + return buffer; } char * -PyOS_ascii_formatd(char *buffer, - size_t buf_size, - const char *format, - double d) +PyOS_ascii_formatd(char *buffer, + size_t buf_size, + const char *format, + double d) { - if (PyErr_WarnEx(PyExc_DeprecationWarning, - "PyOS_ascii_formatd is deprecated, " - "use PyOS_double_to_string instead", 1) < 0) - return NULL; + if (PyErr_WarnEx(PyExc_DeprecationWarning, + "PyOS_ascii_formatd is deprecated, " + "use PyOS_double_to_string instead", 1) < 0) + return NULL; - return _PyOS_ascii_formatd(buffer, buf_size, format, d, -1); + return _PyOS_ascii_formatd(buffer, buf_size, format, d, -1); } #ifdef PY_NO_SHORT_FLOAT_REPR @@ -737,146 +737,146 @@ int flags, int *type) { - char format[32]; - Py_ssize_t bufsize; - char *buf; - int t, exp; - int upper = 0; - - /* Validate format_code, and map upper and lower case */ - switch (format_code) { - case 'e': /* exponent */ - case 'f': /* fixed */ - case 'g': /* general */ - break; - case 'E': - upper = 1; - format_code = 'e'; - break; - case 'F': - upper = 1; - format_code = 'f'; - break; - case 'G': - upper = 1; - format_code = 'g'; - break; - case 'r': /* repr format */ - /* Supplied precision is unused, must be 0. */ - if (precision != 0) { - PyErr_BadInternalCall(); - return NULL; - } - /* The repr() precision (17 significant decimal digits) is the - minimal number that is guaranteed to have enough precision - so that if the number is read back in the exact same binary - value is recreated. This is true for IEEE floating point - by design, and also happens to work for all other modern - hardware. */ - precision = 17; - format_code = 'g'; - break; - default: - PyErr_BadInternalCall(); - return NULL; - } - - /* Here's a quick-and-dirty calculation to figure out how big a buffer - we need. In general, for a finite float we need: - - 1 byte for each digit of the decimal significand, and - - 1 for a possible sign - 1 for a possible decimal point - 2 for a possible [eE][+-] - 1 for each digit of the exponent; if we allow 19 digits - total then we're safe up to exponents of 2**63. - 1 for the trailing nul byte - - This gives a total of 24 + the number of digits in the significand, - and the number of digits in the significand is: - - for 'g' format: at most precision, except possibly - when precision == 0, when it's 1. - for 'e' format: precision+1 - for 'f' format: precision digits after the point, at least 1 - before. To figure out how many digits appear before the point - we have to examine the size of the number. If fabs(val) < 1.0 - then there will be only one digit before the point. If - fabs(val) >= 1.0, then there are at most - - 1+floor(log10(ceiling(fabs(val)))) - - digits before the point (where the 'ceiling' allows for the - possibility that the rounding rounds the integer part of val - up). A safe upper bound for the above quantity is - 1+floor(exp/3), where exp is the unique integer such that 0.5 - <= fabs(val)/2**exp < 1.0. This exp can be obtained from - frexp. - - So we allow room for precision+1 digits for all formats, plus an - extra floor(exp/3) digits for 'f' format. - - */ - - if (Py_IS_NAN(val) || Py_IS_INFINITY(val)) - /* 3 for 'inf'/'nan', 1 for sign, 1 for '\0' */ - bufsize = 5; - else { - bufsize = 25 + precision; - if (format_code == 'f' && fabs(val) >= 1.0) { - frexp(val, &exp); - bufsize += exp/3; - } - } - - buf = PyMem_Malloc(bufsize); - if (buf == NULL) { - PyErr_NoMemory(); - return NULL; - } - - /* Handle nan and inf. */ - if (Py_IS_NAN(val)) { - strcpy(buf, "nan"); - t = Py_DTST_NAN; - } else if (Py_IS_INFINITY(val)) { - if (copysign(1., val) == 1.) - strcpy(buf, "inf"); - else - strcpy(buf, "-inf"); - t = Py_DTST_INFINITE; - } else { - t = Py_DTST_FINITE; - if (flags & Py_DTSF_ADD_DOT_0) - format_code = 'Z'; - - PyOS_snprintf(format, sizeof(format), "%%%s.%i%c", - (flags & Py_DTSF_ALT ? "#" : ""), precision, - format_code); - _PyOS_ascii_formatd(buf, bufsize, format, val, precision); - } - - /* Add sign when requested. It's convenient (esp. when formatting - complex numbers) to include a sign even for inf and nan. */ - if (flags & Py_DTSF_SIGN && buf[0] != '-') { - size_t len = strlen(buf); - /* the bufsize calculations above should ensure that we've got - space to add a sign */ - assert((size_t)bufsize >= len+2); - memmove(buf+1, buf, len+1); - buf[0] = '+'; - } - if (upper) { - /* Convert to upper case. */ - char *p1; - for (p1 = buf; *p1; p1++) - *p1 = Py_TOUPPER(*p1); - } - - if (type) - *type = t; - return buf; + char format[32]; + Py_ssize_t bufsize; + char *buf; + int t, exp; + int upper = 0; + + /* Validate format_code, and map upper and lower case */ + switch (format_code) { + case 'e': /* exponent */ + case 'f': /* fixed */ + case 'g': /* general */ + break; + case 'E': + upper = 1; + format_code = 'e'; + break; + case 'F': + upper = 1; + format_code = 'f'; + break; + case 'G': + upper = 1; + format_code = 'g'; + break; + case 'r': /* repr format */ + /* Supplied precision is unused, must be 0. */ + if (precision != 0) { + PyErr_BadInternalCall(); + return NULL; + } + /* The repr() precision (17 significant decimal digits) is the + minimal number that is guaranteed to have enough precision + so that if the number is read back in the exact same binary + value is recreated. This is true for IEEE floating point + by design, and also happens to work for all other modern + hardware. */ + precision = 17; + format_code = 'g'; + break; + default: + PyErr_BadInternalCall(); + return NULL; + } + + /* Here's a quick-and-dirty calculation to figure out how big a buffer + we need. In general, for a finite float we need: + + 1 byte for each digit of the decimal significand, and + + 1 for a possible sign + 1 for a possible decimal point + 2 for a possible [eE][+-] + 1 for each digit of the exponent; if we allow 19 digits + total then we're safe up to exponents of 2**63. + 1 for the trailing nul byte + + This gives a total of 24 + the number of digits in the significand, + and the number of digits in the significand is: + + for 'g' format: at most precision, except possibly + when precision == 0, when it's 1. + for 'e' format: precision+1 + for 'f' format: precision digits after the point, at least 1 + before. To figure out how many digits appear before the point + we have to examine the size of the number. If fabs(val) < 1.0 + then there will be only one digit before the point. If + fabs(val) >= 1.0, then there are at most + + 1+floor(log10(ceiling(fabs(val)))) + + digits before the point (where the 'ceiling' allows for the + possibility that the rounding rounds the integer part of val + up). A safe upper bound for the above quantity is + 1+floor(exp/3), where exp is the unique integer such that 0.5 + <= fabs(val)/2**exp < 1.0. This exp can be obtained from + frexp. + + So we allow room for precision+1 digits for all formats, plus an + extra floor(exp/3) digits for 'f' format. + + */ + + if (Py_IS_NAN(val) || Py_IS_INFINITY(val)) + /* 3 for 'inf'/'nan', 1 for sign, 1 for '\0' */ + bufsize = 5; + else { + bufsize = 25 + precision; + if (format_code == 'f' && fabs(val) >= 1.0) { + frexp(val, &exp); + bufsize += exp/3; + } + } + + buf = PyMem_Malloc(bufsize); + if (buf == NULL) { + PyErr_NoMemory(); + return NULL; + } + + /* Handle nan and inf. */ + if (Py_IS_NAN(val)) { + strcpy(buf, "nan"); + t = Py_DTST_NAN; + } else if (Py_IS_INFINITY(val)) { + if (copysign(1., val) == 1.) + strcpy(buf, "inf"); + else + strcpy(buf, "-inf"); + t = Py_DTST_INFINITE; + } else { + t = Py_DTST_FINITE; + if (flags & Py_DTSF_ADD_DOT_0) + format_code = 'Z'; + + PyOS_snprintf(format, sizeof(format), "%%%s.%i%c", + (flags & Py_DTSF_ALT ? "#" : ""), precision, + format_code); + _PyOS_ascii_formatd(buf, bufsize, format, val, precision); + } + + /* Add sign when requested. It's convenient (esp. when formatting + complex numbers) to include a sign even for inf and nan. */ + if (flags & Py_DTSF_SIGN && buf[0] != '-') { + size_t len = strlen(buf); + /* the bufsize calculations above should ensure that we've got + space to add a sign */ + assert((size_t)bufsize >= len+2); + memmove(buf+1, buf, len+1); + buf[0] = '+'; + } + if (upper) { + /* Convert to upper case. */ + char *p1; + for (p1 = buf; *p1; p1++) + *p1 = Py_TOUPPER(*p1); + } + + if (type) + *type = t; + return buf; } #else @@ -891,14 +891,14 @@ /* The lengths of these are known to the code below, so don't change them */ static char *lc_float_strings[] = { - "inf", - "nan", - "e", + "inf", + "nan", + "e", }; static char *uc_float_strings[] = { - "INF", - "NAN", - "E", + "INF", + "NAN", + "E", }; @@ -922,9 +922,9 @@ be nonzero. type, if non-NULL, will be set to one of these constants to identify the type of the 'd' argument: - Py_DTST_FINITE - Py_DTST_INFINITE - Py_DTST_NAN + Py_DTST_FINITE + Py_DTST_INFINITE + Py_DTST_NAN Returns a PyMem_Malloc'd block of memory containing the resulting string, or NULL on error. If NULL is returned, the Python error has been set. @@ -932,315 +932,315 @@ static char * format_float_short(double d, char format_code, - int mode, Py_ssize_t precision, - int always_add_sign, int add_dot_0_if_integer, - int use_alt_formatting, char **float_strings, int *type) + int mode, Py_ssize_t precision, + int always_add_sign, int add_dot_0_if_integer, + int use_alt_formatting, char **float_strings, int *type) { - char *buf = NULL; - char *p = NULL; - Py_ssize_t bufsize = 0; - char *digits, *digits_end; - int decpt_as_int, sign, exp_len, exp = 0, use_exp = 0; - Py_ssize_t decpt, digits_len, vdigits_start, vdigits_end; - _Py_SET_53BIT_PRECISION_HEADER; - - /* _Py_dg_dtoa returns a digit string (no decimal point or exponent). - Must be matched by a call to _Py_dg_freedtoa. */ - _Py_SET_53BIT_PRECISION_START; - digits = _Py_dg_dtoa(d, mode, precision, &decpt_as_int, &sign, - &digits_end); - _Py_SET_53BIT_PRECISION_END; - - decpt = (Py_ssize_t)decpt_as_int; - if (digits == NULL) { - /* The only failure mode is no memory. */ - PyErr_NoMemory(); - goto exit; - } - assert(digits_end != NULL && digits_end >= digits); - digits_len = digits_end - digits; - - if (digits_len && !Py_ISDIGIT(digits[0])) { - /* Infinities and nans here; adapt Gay's output, - so convert Infinity to inf and NaN to nan, and - ignore sign of nan. Then return. */ - - /* ignore the actual sign of a nan */ - if (digits[0] == 'n' || digits[0] == 'N') - sign = 0; - - /* We only need 5 bytes to hold the result "+inf\0" . */ - bufsize = 5; /* Used later in an assert. */ - buf = (char *)PyMem_Malloc(bufsize); - if (buf == NULL) { - PyErr_NoMemory(); - goto exit; - } - p = buf; - - if (sign == 1) { - *p++ = '-'; - } - else if (always_add_sign) { - *p++ = '+'; - } - if (digits[0] == 'i' || digits[0] == 'I') { - strncpy(p, float_strings[OFS_INF], 3); - p += 3; - - if (type) - *type = Py_DTST_INFINITE; - } - else if (digits[0] == 'n' || digits[0] == 'N') { - strncpy(p, float_strings[OFS_NAN], 3); - p += 3; - - if (type) - *type = Py_DTST_NAN; - } - else { - /* shouldn't get here: Gay's code should always return - something starting with a digit, an 'I', or 'N' */ - strncpy(p, "ERR", 3); - p += 3; - assert(0); - } - goto exit; - } - - /* The result must be finite (not inf or nan). */ - if (type) - *type = Py_DTST_FINITE; - - - /* We got digits back, format them. We may need to pad 'digits' - either on the left or right (or both) with extra zeros, so in - general the resulting string has the form - - [][] - - where either of the pieces could be empty, and there's a - decimal point that could appear either in or in the - leading or trailing . - - Imagine an infinite 'virtual' string vdigits, consisting of the - string 'digits' (starting at index 0) padded on both the left and - right with infinite strings of zeros. We want to output a slice - - vdigits[vdigits_start : vdigits_end] - - of this virtual string. Thus if vdigits_start < 0 then we'll end - up producing some leading zeros; if vdigits_end > digits_len there - will be trailing zeros in the output. The next section of code - determines whether to use an exponent or not, figures out the - position 'decpt' of the decimal point, and computes 'vdigits_start' - and 'vdigits_end'. */ - vdigits_end = digits_len; - switch (format_code) { - case 'e': - use_exp = 1; - vdigits_end = precision; - break; - case 'f': - vdigits_end = decpt + precision; - break; - case 'g': - if (decpt <= -4 || decpt > - (add_dot_0_if_integer ? precision-1 : precision)) - use_exp = 1; - if (use_alt_formatting) - vdigits_end = precision; - break; - case 'r': - /* convert to exponential format at 1e16. We used to convert - at 1e17, but that gives odd-looking results for some values - when a 16-digit 'shortest' repr is padded with bogus zeros. - For example, repr(2e16+8) would give 20000000000000010.0; - the true value is 20000000000000008.0. */ - if (decpt <= -4 || decpt > 16) - use_exp = 1; - break; - default: - PyErr_BadInternalCall(); - goto exit; - } - - /* if using an exponent, reset decimal point position to 1 and adjust - exponent accordingly.*/ - if (use_exp) { - exp = decpt - 1; - decpt = 1; - } - /* ensure vdigits_start < decpt <= vdigits_end, or vdigits_start < - decpt < vdigits_end if add_dot_0_if_integer and no exponent */ - vdigits_start = decpt <= 0 ? decpt-1 : 0; - if (!use_exp && add_dot_0_if_integer) - vdigits_end = vdigits_end > decpt ? vdigits_end : decpt + 1; - else - vdigits_end = vdigits_end > decpt ? vdigits_end : decpt; - - /* double check inequalities */ - assert(vdigits_start <= 0 && - 0 <= digits_len && - digits_len <= vdigits_end); - /* decimal point should be in (vdigits_start, vdigits_end] */ - assert(vdigits_start < decpt && decpt <= vdigits_end); - - /* Compute an upper bound how much memory we need. This might be a few - chars too long, but no big deal. */ - bufsize = - /* sign, decimal point and trailing 0 byte */ - 3 + - - /* total digit count (including zero padding on both sides) */ - (vdigits_end - vdigits_start) + - - /* exponent "e+100", max 3 numerical digits */ - (use_exp ? 5 : 0); - - /* Now allocate the memory and initialize p to point to the start of - it. */ - buf = (char *)PyMem_Malloc(bufsize); - if (buf == NULL) { - PyErr_NoMemory(); - goto exit; - } - p = buf; - - /* Add a negative sign if negative, and a plus sign if non-negative - and always_add_sign is true. */ - if (sign == 1) - *p++ = '-'; - else if (always_add_sign) - *p++ = '+'; - - /* note that exactly one of the three 'if' conditions is true, - so we include exactly one decimal point */ - /* Zero padding on left of digit string */ - if (decpt <= 0) { - memset(p, '0', decpt-vdigits_start); - p += decpt - vdigits_start; - *p++ = '.'; - memset(p, '0', 0-decpt); - p += 0-decpt; - } - else { - memset(p, '0', 0-vdigits_start); - p += 0 - vdigits_start; - } - - /* Digits, with included decimal point */ - if (0 < decpt && decpt <= digits_len) { - strncpy(p, digits, decpt-0); - p += decpt-0; - *p++ = '.'; - strncpy(p, digits+decpt, digits_len-decpt); - p += digits_len-decpt; - } - else { - strncpy(p, digits, digits_len); - p += digits_len; - } - - /* And zeros on the right */ - if (digits_len < decpt) { - memset(p, '0', decpt-digits_len); - p += decpt-digits_len; - *p++ = '.'; - memset(p, '0', vdigits_end-decpt); - p += vdigits_end-decpt; - } - else { - memset(p, '0', vdigits_end-digits_len); - p += vdigits_end-digits_len; - } - - /* Delete a trailing decimal pt unless using alternative formatting. */ - if (p[-1] == '.' && !use_alt_formatting) - p--; - - /* Now that we've done zero padding, add an exponent if needed. */ - if (use_exp) { - *p++ = float_strings[OFS_E][0]; - exp_len = sprintf(p, "%+.02d", exp); - p += exp_len; - } + char *buf = NULL; + char *p = NULL; + Py_ssize_t bufsize = 0; + char *digits, *digits_end; + int decpt_as_int, sign, exp_len, exp = 0, use_exp = 0; + Py_ssize_t decpt, digits_len, vdigits_start, vdigits_end; + _Py_SET_53BIT_PRECISION_HEADER; + + /* _Py_dg_dtoa returns a digit string (no decimal point or exponent). + Must be matched by a call to _Py_dg_freedtoa. */ + _Py_SET_53BIT_PRECISION_START; + digits = _Py_dg_dtoa(d, mode, precision, &decpt_as_int, &sign, + &digits_end); + _Py_SET_53BIT_PRECISION_END; + + decpt = (Py_ssize_t)decpt_as_int; + if (digits == NULL) { + /* The only failure mode is no memory. */ + PyErr_NoMemory(); + goto exit; + } + assert(digits_end != NULL && digits_end >= digits); + digits_len = digits_end - digits; + + if (digits_len && !Py_ISDIGIT(digits[0])) { + /* Infinities and nans here; adapt Gay's output, + so convert Infinity to inf and NaN to nan, and + ignore sign of nan. Then return. */ + + /* ignore the actual sign of a nan */ + if (digits[0] == 'n' || digits[0] == 'N') + sign = 0; + + /* We only need 5 bytes to hold the result "+inf\0" . */ + bufsize = 5; /* Used later in an assert. */ + buf = (char *)PyMem_Malloc(bufsize); + if (buf == NULL) { + PyErr_NoMemory(); + goto exit; + } + p = buf; + + if (sign == 1) { + *p++ = '-'; + } + else if (always_add_sign) { + *p++ = '+'; + } + if (digits[0] == 'i' || digits[0] == 'I') { + strncpy(p, float_strings[OFS_INF], 3); + p += 3; + + if (type) + *type = Py_DTST_INFINITE; + } + else if (digits[0] == 'n' || digits[0] == 'N') { + strncpy(p, float_strings[OFS_NAN], 3); + p += 3; + + if (type) + *type = Py_DTST_NAN; + } + else { + /* shouldn't get here: Gay's code should always return + something starting with a digit, an 'I', or 'N' */ + strncpy(p, "ERR", 3); + p += 3; + assert(0); + } + goto exit; + } + + /* The result must be finite (not inf or nan). */ + if (type) + *type = Py_DTST_FINITE; + + + /* We got digits back, format them. We may need to pad 'digits' + either on the left or right (or both) with extra zeros, so in + general the resulting string has the form + + [][] + + where either of the pieces could be empty, and there's a + decimal point that could appear either in or in the + leading or trailing . + + Imagine an infinite 'virtual' string vdigits, consisting of the + string 'digits' (starting at index 0) padded on both the left and + right with infinite strings of zeros. We want to output a slice + + vdigits[vdigits_start : vdigits_end] + + of this virtual string. Thus if vdigits_start < 0 then we'll end + up producing some leading zeros; if vdigits_end > digits_len there + will be trailing zeros in the output. The next section of code + determines whether to use an exponent or not, figures out the + position 'decpt' of the decimal point, and computes 'vdigits_start' + and 'vdigits_end'. */ + vdigits_end = digits_len; + switch (format_code) { + case 'e': + use_exp = 1; + vdigits_end = precision; + break; + case 'f': + vdigits_end = decpt + precision; + break; + case 'g': + if (decpt <= -4 || decpt > + (add_dot_0_if_integer ? precision-1 : precision)) + use_exp = 1; + if (use_alt_formatting) + vdigits_end = precision; + break; + case 'r': + /* convert to exponential format at 1e16. We used to convert + at 1e17, but that gives odd-looking results for some values + when a 16-digit 'shortest' repr is padded with bogus zeros. + For example, repr(2e16+8) would give 20000000000000010.0; + the true value is 20000000000000008.0. */ + if (decpt <= -4 || decpt > 16) + use_exp = 1; + break; + default: + PyErr_BadInternalCall(); + goto exit; + } + + /* if using an exponent, reset decimal point position to 1 and adjust + exponent accordingly.*/ + if (use_exp) { + exp = decpt - 1; + decpt = 1; + } + /* ensure vdigits_start < decpt <= vdigits_end, or vdigits_start < + decpt < vdigits_end if add_dot_0_if_integer and no exponent */ + vdigits_start = decpt <= 0 ? decpt-1 : 0; + if (!use_exp && add_dot_0_if_integer) + vdigits_end = vdigits_end > decpt ? vdigits_end : decpt + 1; + else + vdigits_end = vdigits_end > decpt ? vdigits_end : decpt; + + /* double check inequalities */ + assert(vdigits_start <= 0 && + 0 <= digits_len && + digits_len <= vdigits_end); + /* decimal point should be in (vdigits_start, vdigits_end] */ + assert(vdigits_start < decpt && decpt <= vdigits_end); + + /* Compute an upper bound how much memory we need. This might be a few + chars too long, but no big deal. */ + bufsize = + /* sign, decimal point and trailing 0 byte */ + 3 + + + /* total digit count (including zero padding on both sides) */ + (vdigits_end - vdigits_start) + + + /* exponent "e+100", max 3 numerical digits */ + (use_exp ? 5 : 0); + + /* Now allocate the memory and initialize p to point to the start of + it. */ + buf = (char *)PyMem_Malloc(bufsize); + if (buf == NULL) { + PyErr_NoMemory(); + goto exit; + } + p = buf; + + /* Add a negative sign if negative, and a plus sign if non-negative + and always_add_sign is true. */ + if (sign == 1) + *p++ = '-'; + else if (always_add_sign) + *p++ = '+'; + + /* note that exactly one of the three 'if' conditions is true, + so we include exactly one decimal point */ + /* Zero padding on left of digit string */ + if (decpt <= 0) { + memset(p, '0', decpt-vdigits_start); + p += decpt - vdigits_start; + *p++ = '.'; + memset(p, '0', 0-decpt); + p += 0-decpt; + } + else { + memset(p, '0', 0-vdigits_start); + p += 0 - vdigits_start; + } + + /* Digits, with included decimal point */ + if (0 < decpt && decpt <= digits_len) { + strncpy(p, digits, decpt-0); + p += decpt-0; + *p++ = '.'; + strncpy(p, digits+decpt, digits_len-decpt); + p += digits_len-decpt; + } + else { + strncpy(p, digits, digits_len); + p += digits_len; + } + + /* And zeros on the right */ + if (digits_len < decpt) { + memset(p, '0', decpt-digits_len); + p += decpt-digits_len; + *p++ = '.'; + memset(p, '0', vdigits_end-decpt); + p += vdigits_end-decpt; + } + else { + memset(p, '0', vdigits_end-digits_len); + p += vdigits_end-digits_len; + } + + /* Delete a trailing decimal pt unless using alternative formatting. */ + if (p[-1] == '.' && !use_alt_formatting) + p--; + + /* Now that we've done zero padding, add an exponent if needed. */ + if (use_exp) { + *p++ = float_strings[OFS_E][0]; + exp_len = sprintf(p, "%+.02d", exp); + p += exp_len; + } exit: - if (buf) { - *p = '\0'; - /* It's too late if this fails, as we've already stepped on - memory that isn't ours. But it's an okay debugging test. */ - assert(p-buf < bufsize); - } - if (digits) - _Py_dg_freedtoa(digits); + if (buf) { + *p = '\0'; + /* It's too late if this fails, as we've already stepped on + memory that isn't ours. But it's an okay debugging test. */ + assert(p-buf < bufsize); + } + if (digits) + _Py_dg_freedtoa(digits); - return buf; + return buf; } PyAPI_FUNC(char *) PyOS_double_to_string(double val, - char format_code, - int precision, - int flags, - int *type) + char format_code, + int precision, + int flags, + int *type) { - char **float_strings = lc_float_strings; - int mode; + char **float_strings = lc_float_strings; + int mode; - /* Validate format_code, and map upper and lower case. Compute the - mode and make any adjustments as needed. */ - switch (format_code) { - /* exponent */ - case 'E': - float_strings = uc_float_strings; - format_code = 'e'; - /* Fall through. */ - case 'e': - mode = 2; - precision++; - break; - - /* fixed */ - case 'F': - float_strings = uc_float_strings; - format_code = 'f'; - /* Fall through. */ - case 'f': - mode = 3; - break; - - /* general */ - case 'G': - float_strings = uc_float_strings; - format_code = 'g'; - /* Fall through. */ - case 'g': - mode = 2; - /* precision 0 makes no sense for 'g' format; interpret as 1 */ - if (precision == 0) - precision = 1; - break; - - /* repr format */ - case 'r': - mode = 0; - /* Supplied precision is unused, must be 0. */ - if (precision != 0) { - PyErr_BadInternalCall(); - return NULL; - } - break; - - default: - PyErr_BadInternalCall(); - return NULL; - } - - return format_float_short(val, format_code, mode, precision, - flags & Py_DTSF_SIGN, - flags & Py_DTSF_ADD_DOT_0, - flags & Py_DTSF_ALT, - float_strings, type); + /* Validate format_code, and map upper and lower case. Compute the + mode and make any adjustments as needed. */ + switch (format_code) { + /* exponent */ + case 'E': + float_strings = uc_float_strings; + format_code = 'e'; + /* Fall through. */ + case 'e': + mode = 2; + precision++; + break; + + /* fixed */ + case 'F': + float_strings = uc_float_strings; + format_code = 'f'; + /* Fall through. */ + case 'f': + mode = 3; + break; + + /* general */ + case 'G': + float_strings = uc_float_strings; + format_code = 'g'; + /* Fall through. */ + case 'g': + mode = 2; + /* precision 0 makes no sense for 'g' format; interpret as 1 */ + if (precision == 0) + precision = 1; + break; + + /* repr format */ + case 'r': + mode = 0; + /* Supplied precision is unused, must be 0. */ + if (precision != 0) { + PyErr_BadInternalCall(); + return NULL; + } + break; + + default: + PyErr_BadInternalCall(); + return NULL; + } + + return format_float_short(val, format_code, mode, precision, + flags & Py_DTSF_SIGN, + flags & Py_DTSF_ADD_DOT_0, + flags & Py_DTSF_ALT, + float_strings, type); } #endif /* ifdef PY_NO_SHORT_FLOAT_REPR */ Modified: python/branches/release31-maint/Python/pythonrun.c ============================================================================== --- python/branches/release31-maint/Python/pythonrun.c (original) +++ python/branches/release31-maint/Python/pythonrun.c Sun May 9 18:14:21 2010 @@ -42,9 +42,9 @@ #ifndef Py_REF_DEBUG #define PRINT_TOTAL_REFS() #else /* Py_REF_DEBUG */ -#define PRINT_TOTAL_REFS() fprintf(stderr, \ - "[%" PY_FORMAT_SIZE_T "d refs]\n", \ - _Py_GetRefTotal()) +#define PRINT_TOTAL_REFS() fprintf(stderr, \ + "[%" PY_FORMAT_SIZE_T "d refs]\n", \ + _Py_GetRefTotal()) #endif #ifdef __cplusplus @@ -61,9 +61,9 @@ static int initstdio(void); static void flush_io(void); static PyObject *run_mod(mod_ty, const char *, PyObject *, PyObject *, - PyCompilerFlags *, PyArena *); + PyCompilerFlags *, PyArena *); static PyObject *run_pyc_file(FILE *, const char *, PyObject *, PyObject *, - PyCompilerFlags *); + PyCompilerFlags *); static void err_input(perrdetail *); static void initsigs(void); static void call_py_exitfuncs(void); @@ -97,7 +97,7 @@ PyObject * PyModule_GetWarningsModule(void) { - return PyImport_ImportModule("warnings"); + return PyImport_ImportModule("warnings"); } static int initialized = 0; @@ -107,7 +107,7 @@ int Py_IsInitialized(void) { - return initialized; + return initialized; } /* Global initializations. Can be undone by Py_Finalize(). Don't @@ -125,191 +125,191 @@ static int add_flag(int flag, const char *envs) { - int env = atoi(envs); - if (flag < env) - flag = env; - if (flag < 1) - flag = 1; - return flag; + int env = atoi(envs); + if (flag < env) + flag = env; + if (flag < 1) + flag = 1; + return flag; } #if defined(HAVE_LANGINFO_H) && defined(CODESET) static char* get_codeset(void) { - char* codeset; - PyObject *codec, *name; + char* codeset; + PyObject *codec, *name; - codeset = nl_langinfo(CODESET); - if (!codeset || codeset[0] == '\0') - return NULL; - - codec = _PyCodec_Lookup(codeset); - if (!codec) - goto error; - - name = PyObject_GetAttrString(codec, "name"); - Py_CLEAR(codec); - if (!name) - goto error; - - codeset = strdup(_PyUnicode_AsString(name)); - Py_DECREF(name); - return codeset; + codeset = nl_langinfo(CODESET); + if (!codeset || codeset[0] == '\0') + return NULL; + + codec = _PyCodec_Lookup(codeset); + if (!codec) + goto error; + + name = PyObject_GetAttrString(codec, "name"); + Py_CLEAR(codec); + if (!name) + goto error; + + codeset = strdup(_PyUnicode_AsString(name)); + Py_DECREF(name); + return codeset; error: - Py_XDECREF(codec); - PyErr_Clear(); - return NULL; + Py_XDECREF(codec); + PyErr_Clear(); + return NULL; } #endif void Py_InitializeEx(int install_sigs) { - PyInterpreterState *interp; - PyThreadState *tstate; - PyObject *bimod, *sysmod, *pstderr; - char *p; + PyInterpreterState *interp; + PyThreadState *tstate; + PyObject *bimod, *sysmod, *pstderr; + char *p; #if defined(HAVE_LANGINFO_H) && defined(CODESET) - char *codeset; + char *codeset; #endif - extern void _Py_ReadyTypes(void); + extern void _Py_ReadyTypes(void); - if (initialized) - return; - initialized = 1; + if (initialized) + return; + initialized = 1; #ifdef HAVE_SETLOCALE - /* Set up the LC_CTYPE locale, so we can obtain - the locale's charset without having to switch - locales. */ - setlocale(LC_CTYPE, ""); -#endif - - if ((p = Py_GETENV("PYTHONDEBUG")) && *p != '\0') - Py_DebugFlag = add_flag(Py_DebugFlag, p); - if ((p = Py_GETENV("PYTHONVERBOSE")) && *p != '\0') - Py_VerboseFlag = add_flag(Py_VerboseFlag, p); - if ((p = Py_GETENV("PYTHONOPTIMIZE")) && *p != '\0') - Py_OptimizeFlag = add_flag(Py_OptimizeFlag, p); - if ((p = Py_GETENV("PYTHONDONTWRITEBYTECODE")) && *p != '\0') - Py_DontWriteBytecodeFlag = add_flag(Py_DontWriteBytecodeFlag, p); - - interp = PyInterpreterState_New(); - if (interp == NULL) - Py_FatalError("Py_Initialize: can't make first interpreter"); - - tstate = PyThreadState_New(interp); - if (tstate == NULL) - Py_FatalError("Py_Initialize: can't make first thread"); - (void) PyThreadState_Swap(tstate); - - _Py_ReadyTypes(); - - if (!_PyFrame_Init()) - Py_FatalError("Py_Initialize: can't init frames"); - - if (!_PyLong_Init()) - Py_FatalError("Py_Initialize: can't init longs"); - - if (!PyByteArray_Init()) - Py_FatalError("Py_Initialize: can't init bytearray"); - - _PyFloat_Init(); - - interp->modules = PyDict_New(); - if (interp->modules == NULL) - Py_FatalError("Py_Initialize: can't make modules dictionary"); - interp->modules_reloading = PyDict_New(); - if (interp->modules_reloading == NULL) - Py_FatalError("Py_Initialize: can't make modules_reloading dictionary"); - - /* Init Unicode implementation; relies on the codec registry */ - _PyUnicode_Init(); - - bimod = _PyBuiltin_Init(); - if (bimod == NULL) - Py_FatalError("Py_Initialize: can't initialize builtins modules"); - _PyImport_FixupExtension(bimod, "builtins", "builtins"); - interp->builtins = PyModule_GetDict(bimod); - if (interp->builtins == NULL) - Py_FatalError("Py_Initialize: can't initialize builtins dict"); - Py_INCREF(interp->builtins); - - /* initialize builtin exceptions */ - _PyExc_Init(); - - sysmod = _PySys_Init(); - if (sysmod == NULL) - Py_FatalError("Py_Initialize: can't initialize sys"); - interp->sysdict = PyModule_GetDict(sysmod); - if (interp->sysdict == NULL) - Py_FatalError("Py_Initialize: can't initialize sys dict"); - Py_INCREF(interp->sysdict); - _PyImport_FixupExtension(sysmod, "sys", "sys"); - PySys_SetPath(Py_GetPath()); - PyDict_SetItemString(interp->sysdict, "modules", - interp->modules); - - /* Set up a preliminary stderr printer until we have enough - infrastructure for the io module in place. */ - pstderr = PyFile_NewStdPrinter(fileno(stderr)); - if (pstderr == NULL) - Py_FatalError("Py_Initialize: can't set preliminary stderr"); - PySys_SetObject("stderr", pstderr); - PySys_SetObject("__stderr__", pstderr); + /* Set up the LC_CTYPE locale, so we can obtain + the locale's charset without having to switch + locales. */ + setlocale(LC_CTYPE, ""); +#endif + + if ((p = Py_GETENV("PYTHONDEBUG")) && *p != '\0') + Py_DebugFlag = add_flag(Py_DebugFlag, p); + if ((p = Py_GETENV("PYTHONVERBOSE")) && *p != '\0') + Py_VerboseFlag = add_flag(Py_VerboseFlag, p); + if ((p = Py_GETENV("PYTHONOPTIMIZE")) && *p != '\0') + Py_OptimizeFlag = add_flag(Py_OptimizeFlag, p); + if ((p = Py_GETENV("PYTHONDONTWRITEBYTECODE")) && *p != '\0') + Py_DontWriteBytecodeFlag = add_flag(Py_DontWriteBytecodeFlag, p); + + interp = PyInterpreterState_New(); + if (interp == NULL) + Py_FatalError("Py_Initialize: can't make first interpreter"); + + tstate = PyThreadState_New(interp); + if (tstate == NULL) + Py_FatalError("Py_Initialize: can't make first thread"); + (void) PyThreadState_Swap(tstate); + + _Py_ReadyTypes(); + + if (!_PyFrame_Init()) + Py_FatalError("Py_Initialize: can't init frames"); + + if (!_PyLong_Init()) + Py_FatalError("Py_Initialize: can't init longs"); + + if (!PyByteArray_Init()) + Py_FatalError("Py_Initialize: can't init bytearray"); + + _PyFloat_Init(); + + interp->modules = PyDict_New(); + if (interp->modules == NULL) + Py_FatalError("Py_Initialize: can't make modules dictionary"); + interp->modules_reloading = PyDict_New(); + if (interp->modules_reloading == NULL) + Py_FatalError("Py_Initialize: can't make modules_reloading dictionary"); + + /* Init Unicode implementation; relies on the codec registry */ + _PyUnicode_Init(); + + bimod = _PyBuiltin_Init(); + if (bimod == NULL) + Py_FatalError("Py_Initialize: can't initialize builtins modules"); + _PyImport_FixupExtension(bimod, "builtins", "builtins"); + interp->builtins = PyModule_GetDict(bimod); + if (interp->builtins == NULL) + Py_FatalError("Py_Initialize: can't initialize builtins dict"); + Py_INCREF(interp->builtins); + + /* initialize builtin exceptions */ + _PyExc_Init(); + + sysmod = _PySys_Init(); + if (sysmod == NULL) + Py_FatalError("Py_Initialize: can't initialize sys"); + interp->sysdict = PyModule_GetDict(sysmod); + if (interp->sysdict == NULL) + Py_FatalError("Py_Initialize: can't initialize sys dict"); + Py_INCREF(interp->sysdict); + _PyImport_FixupExtension(sysmod, "sys", "sys"); + PySys_SetPath(Py_GetPath()); + PyDict_SetItemString(interp->sysdict, "modules", + interp->modules); + + /* Set up a preliminary stderr printer until we have enough + infrastructure for the io module in place. */ + pstderr = PyFile_NewStdPrinter(fileno(stderr)); + if (pstderr == NULL) + Py_FatalError("Py_Initialize: can't set preliminary stderr"); + PySys_SetObject("stderr", pstderr); + PySys_SetObject("__stderr__", pstderr); - _PyImport_Init(); + _PyImport_Init(); - _PyImportHooks_Init(); + _PyImportHooks_Init(); #if defined(HAVE_LANGINFO_H) && defined(CODESET) - /* On Unix, set the file system encoding according to the - user's preference, if the CODESET names a well-known - Python codec, and Py_FileSystemDefaultEncoding isn't - initialized by other means. Also set the encoding of - stdin and stdout if these are terminals. */ - - codeset = get_codeset(); - if (codeset) { - if (!Py_FileSystemDefaultEncoding) - Py_FileSystemDefaultEncoding = codeset; - else - free(codeset); - } -#endif - - if (install_sigs) - initsigs(); /* Signal handling stuff, including initintr() */ - - /* Initialize warnings. */ - _PyWarnings_Init(); - if (PySys_HasWarnOptions()) { - PyObject *warnings_module = PyImport_ImportModule("warnings"); - if (!warnings_module) - PyErr_Clear(); - Py_XDECREF(warnings_module); - } - - initmain(); /* Module __main__ */ - if (initstdio() < 0) - Py_FatalError( - "Py_Initialize: can't initialize sys standard streams"); + /* On Unix, set the file system encoding according to the + user's preference, if the CODESET names a well-known + Python codec, and Py_FileSystemDefaultEncoding isn't + initialized by other means. Also set the encoding of + stdin and stdout if these are terminals. */ + + codeset = get_codeset(); + if (codeset) { + if (!Py_FileSystemDefaultEncoding) + Py_FileSystemDefaultEncoding = codeset; + else + free(codeset); + } +#endif + + if (install_sigs) + initsigs(); /* Signal handling stuff, including initintr() */ + + /* Initialize warnings. */ + _PyWarnings_Init(); + if (PySys_HasWarnOptions()) { + PyObject *warnings_module = PyImport_ImportModule("warnings"); + if (!warnings_module) + PyErr_Clear(); + Py_XDECREF(warnings_module); + } + + initmain(); /* Module __main__ */ + if (initstdio() < 0) + Py_FatalError( + "Py_Initialize: can't initialize sys standard streams"); - /* auto-thread-state API, if available */ + /* auto-thread-state API, if available */ #ifdef WITH_THREAD - _PyGILState_Init(interp, tstate); + _PyGILState_Init(interp, tstate); #endif /* WITH_THREAD */ - if (!Py_NoSiteFlag) - initsite(); /* Module site */ + if (!Py_NoSiteFlag) + initsite(); /* Module site */ } void Py_Initialize(void) { - Py_InitializeEx(1); + Py_InitializeEx(1); } @@ -322,25 +322,25 @@ static void flush_std_files(void) { - PyObject *fout = PySys_GetObject("stdout"); - PyObject *ferr = PySys_GetObject("stderr"); - PyObject *tmp; - - if (fout != NULL && fout != Py_None) { - tmp = PyObject_CallMethod(fout, "flush", ""); - if (tmp == NULL) - PyErr_Clear(); - else - Py_DECREF(tmp); - } - - if (ferr != NULL || ferr != Py_None) { - tmp = PyObject_CallMethod(ferr, "flush", ""); - if (tmp == NULL) - PyErr_Clear(); - else - Py_DECREF(tmp); - } + PyObject *fout = PySys_GetObject("stdout"); + PyObject *ferr = PySys_GetObject("stderr"); + PyObject *tmp; + + if (fout != NULL && fout != Py_None) { + tmp = PyObject_CallMethod(fout, "flush", ""); + if (tmp == NULL) + PyErr_Clear(); + else + Py_DECREF(tmp); + } + + if (ferr != NULL || ferr != Py_None) { + tmp = PyObject_CallMethod(ferr, "flush", ""); + if (tmp == NULL) + PyErr_Clear(); + else + Py_DECREF(tmp); + } } /* Undo the effect of Py_Initialize(). @@ -360,169 +360,169 @@ void Py_Finalize(void) { - PyInterpreterState *interp; - PyThreadState *tstate; + PyInterpreterState *interp; + PyThreadState *tstate; - if (!initialized) - return; + if (!initialized) + return; - wait_for_thread_shutdown(); + wait_for_thread_shutdown(); - /* The interpreter is still entirely intact at this point, and the - * exit funcs may be relying on that. In particular, if some thread - * or exit func is still waiting to do an import, the import machinery - * expects Py_IsInitialized() to return true. So don't say the - * interpreter is uninitialized until after the exit funcs have run. - * Note that Threading.py uses an exit func to do a join on all the - * threads created thru it, so this also protects pending imports in - * the threads created via Threading. - */ - call_py_exitfuncs(); - initialized = 0; - - /* Flush stdout+stderr */ - flush_std_files(); - - /* Get current thread state and interpreter pointer */ - tstate = PyThreadState_GET(); - interp = tstate->interp; - - /* Disable signal handling */ - PyOS_FiniInterrupts(); - - /* Clear type lookup cache */ - PyType_ClearCache(); - - /* Collect garbage. This may call finalizers; it's nice to call these - * before all modules are destroyed. - * XXX If a __del__ or weakref callback is triggered here, and tries to - * XXX import a module, bad things can happen, because Python no - * XXX longer believes it's initialized. - * XXX Fatal Python error: Interpreter not initialized (version mismatch?) - * XXX is easy to provoke that way. I've also seen, e.g., - * XXX Exception exceptions.ImportError: 'No module named sha' - * XXX in ignored - * XXX but I'm unclear on exactly how that one happens. In any case, - * XXX I haven't seen a real-life report of either of these. - */ - PyGC_Collect(); + /* The interpreter is still entirely intact at this point, and the + * exit funcs may be relying on that. In particular, if some thread + * or exit func is still waiting to do an import, the import machinery + * expects Py_IsInitialized() to return true. So don't say the + * interpreter is uninitialized until after the exit funcs have run. + * Note that Threading.py uses an exit func to do a join on all the + * threads created thru it, so this also protects pending imports in + * the threads created via Threading. + */ + call_py_exitfuncs(); + initialized = 0; + + /* Flush stdout+stderr */ + flush_std_files(); + + /* Get current thread state and interpreter pointer */ + tstate = PyThreadState_GET(); + interp = tstate->interp; + + /* Disable signal handling */ + PyOS_FiniInterrupts(); + + /* Clear type lookup cache */ + PyType_ClearCache(); + + /* Collect garbage. This may call finalizers; it's nice to call these + * before all modules are destroyed. + * XXX If a __del__ or weakref callback is triggered here, and tries to + * XXX import a module, bad things can happen, because Python no + * XXX longer believes it's initialized. + * XXX Fatal Python error: Interpreter not initialized (version mismatch?) + * XXX is easy to provoke that way. I've also seen, e.g., + * XXX Exception exceptions.ImportError: 'No module named sha' + * XXX in ignored + * XXX but I'm unclear on exactly how that one happens. In any case, + * XXX I haven't seen a real-life report of either of these. + */ + PyGC_Collect(); #ifdef COUNT_ALLOCS - /* With COUNT_ALLOCS, it helps to run GC multiple times: - each collection might release some types from the type - list, so they become garbage. */ - while (PyGC_Collect() > 0) - /* nothing */; -#endif - - /* Destroy all modules */ - PyImport_Cleanup(); - - /* Flush stdout+stderr (again, in case more was printed) */ - flush_std_files(); - - /* Collect final garbage. This disposes of cycles created by - * new-style class definitions, for example. - * XXX This is disabled because it caused too many problems. If - * XXX a __del__ or weakref callback triggers here, Python code has - * XXX a hard time running, because even the sys module has been - * XXX cleared out (sys.stdout is gone, sys.excepthook is gone, etc). - * XXX One symptom is a sequence of information-free messages - * XXX coming from threads (if a __del__ or callback is invoked, - * XXX other threads can execute too, and any exception they encounter - * XXX triggers a comedy of errors as subsystem after subsystem - * XXX fails to find what it *expects* to find in sys to help report - * XXX the exception and consequent unexpected failures). I've also - * XXX seen segfaults then, after adding print statements to the - * XXX Python code getting called. - */ + /* With COUNT_ALLOCS, it helps to run GC multiple times: + each collection might release some types from the type + list, so they become garbage. */ + while (PyGC_Collect() > 0) + /* nothing */; +#endif + + /* Destroy all modules */ + PyImport_Cleanup(); + + /* Flush stdout+stderr (again, in case more was printed) */ + flush_std_files(); + + /* Collect final garbage. This disposes of cycles created by + * new-style class definitions, for example. + * XXX This is disabled because it caused too many problems. If + * XXX a __del__ or weakref callback triggers here, Python code has + * XXX a hard time running, because even the sys module has been + * XXX cleared out (sys.stdout is gone, sys.excepthook is gone, etc). + * XXX One symptom is a sequence of information-free messages + * XXX coming from threads (if a __del__ or callback is invoked, + * XXX other threads can execute too, and any exception they encounter + * XXX triggers a comedy of errors as subsystem after subsystem + * XXX fails to find what it *expects* to find in sys to help report + * XXX the exception and consequent unexpected failures). I've also + * XXX seen segfaults then, after adding print statements to the + * XXX Python code getting called. + */ #if 0 - PyGC_Collect(); + PyGC_Collect(); #endif - /* Destroy the database used by _PyImport_{Fixup,Find}Extension */ - _PyImport_Fini(); + /* Destroy the database used by _PyImport_{Fixup,Find}Extension */ + _PyImport_Fini(); - /* Debugging stuff */ + /* Debugging stuff */ #ifdef COUNT_ALLOCS - dump_counts(stdout); + dump_counts(stdout); #endif - PRINT_TOTAL_REFS(); + PRINT_TOTAL_REFS(); #ifdef Py_TRACE_REFS - /* Display all objects still alive -- this can invoke arbitrary - * __repr__ overrides, so requires a mostly-intact interpreter. - * Alas, a lot of stuff may still be alive now that will be cleaned - * up later. - */ - if (Py_GETENV("PYTHONDUMPREFS")) - _Py_PrintReferences(stderr); + /* Display all objects still alive -- this can invoke arbitrary + * __repr__ overrides, so requires a mostly-intact interpreter. + * Alas, a lot of stuff may still be alive now that will be cleaned + * up later. + */ + if (Py_GETENV("PYTHONDUMPREFS")) + _Py_PrintReferences(stderr); #endif /* Py_TRACE_REFS */ - /* Clear interpreter state */ - PyInterpreterState_Clear(interp); + /* Clear interpreter state */ + PyInterpreterState_Clear(interp); - /* Now we decref the exception classes. After this point nothing - can raise an exception. That's okay, because each Fini() method - below has been checked to make sure no exceptions are ever - raised. - */ + /* Now we decref the exception classes. After this point nothing + can raise an exception. That's okay, because each Fini() method + below has been checked to make sure no exceptions are ever + raised. + */ - _PyExc_Fini(); + _PyExc_Fini(); - /* Cleanup auto-thread-state */ + /* Cleanup auto-thread-state */ #ifdef WITH_THREAD - _PyGILState_Fini(); + _PyGILState_Fini(); #endif /* WITH_THREAD */ - /* Delete current thread */ - PyThreadState_Swap(NULL); - PyInterpreterState_Delete(interp); - - /* Sundry finalizers */ - PyMethod_Fini(); - PyFrame_Fini(); - PyCFunction_Fini(); - PyTuple_Fini(); - PyList_Fini(); - PySet_Fini(); - PyBytes_Fini(); - PyByteArray_Fini(); - PyLong_Fini(); - PyFloat_Fini(); - PyDict_Fini(); - - /* Cleanup Unicode implementation */ - _PyUnicode_Fini(); - - /* reset file system default encoding */ - if (!Py_HasFileSystemDefaultEncoding) { - free((char*)Py_FileSystemDefaultEncoding); - Py_FileSystemDefaultEncoding = NULL; - } - - /* XXX Still allocated: - - various static ad-hoc pointers to interned strings - - int and float free list blocks - - whatever various modules and libraries allocate - */ + /* Delete current thread */ + PyThreadState_Swap(NULL); + PyInterpreterState_Delete(interp); + + /* Sundry finalizers */ + PyMethod_Fini(); + PyFrame_Fini(); + PyCFunction_Fini(); + PyTuple_Fini(); + PyList_Fini(); + PySet_Fini(); + PyBytes_Fini(); + PyByteArray_Fini(); + PyLong_Fini(); + PyFloat_Fini(); + PyDict_Fini(); + + /* Cleanup Unicode implementation */ + _PyUnicode_Fini(); + + /* reset file system default encoding */ + if (!Py_HasFileSystemDefaultEncoding) { + free((char*)Py_FileSystemDefaultEncoding); + Py_FileSystemDefaultEncoding = NULL; + } + + /* XXX Still allocated: + - various static ad-hoc pointers to interned strings + - int and float free list blocks + - whatever various modules and libraries allocate + */ - PyGrammar_RemoveAccelerators(&_PyParser_Grammar); + PyGrammar_RemoveAccelerators(&_PyParser_Grammar); #ifdef Py_TRACE_REFS - /* Display addresses (& refcnts) of all objects still alive. - * An address can be used to find the repr of the object, printed - * above by _Py_PrintReferences. - */ - if (Py_GETENV("PYTHONDUMPREFS")) - _Py_PrintReferenceAddresses(stderr); + /* Display addresses (& refcnts) of all objects still alive. + * An address can be used to find the repr of the object, printed + * above by _Py_PrintReferences. + */ + if (Py_GETENV("PYTHONDUMPREFS")) + _Py_PrintReferenceAddresses(stderr); #endif /* Py_TRACE_REFS */ #ifdef PYMALLOC_DEBUG - if (Py_GETENV("PYTHONMALLOCSTATS")) - _PyObject_DebugMallocStats(); + if (Py_GETENV("PYTHONMALLOCSTATS")) + _PyObject_DebugMallocStats(); #endif - call_ll_exitfuncs(); + call_ll_exitfuncs(); } /* Create and initialize a new interpreter and thread, and return the @@ -541,81 +541,81 @@ PyThreadState * Py_NewInterpreter(void) { - PyInterpreterState *interp; - PyThreadState *tstate, *save_tstate; - PyObject *bimod, *sysmod; - - if (!initialized) - Py_FatalError("Py_NewInterpreter: call Py_Initialize first"); - - interp = PyInterpreterState_New(); - if (interp == NULL) - return NULL; - - tstate = PyThreadState_New(interp); - if (tstate == NULL) { - PyInterpreterState_Delete(interp); - return NULL; - } - - save_tstate = PyThreadState_Swap(tstate); - - /* XXX The following is lax in error checking */ - - interp->modules = PyDict_New(); - interp->modules_reloading = PyDict_New(); - - bimod = _PyImport_FindExtension("builtins", "builtins"); - if (bimod != NULL) { - interp->builtins = PyModule_GetDict(bimod); - if (interp->builtins == NULL) - goto handle_error; - Py_INCREF(interp->builtins); - } - - /* initialize builtin exceptions */ - _PyExc_Init(); - - sysmod = _PyImport_FindExtension("sys", "sys"); - if (bimod != NULL && sysmod != NULL) { - PyObject *pstderr; - interp->sysdict = PyModule_GetDict(sysmod); - if (interp->sysdict == NULL) - goto handle_error; - Py_INCREF(interp->sysdict); - PySys_SetPath(Py_GetPath()); - PyDict_SetItemString(interp->sysdict, "modules", - interp->modules); - /* Set up a preliminary stderr printer until we have enough - infrastructure for the io module in place. */ - pstderr = PyFile_NewStdPrinter(fileno(stderr)); - if (pstderr == NULL) - Py_FatalError("Py_Initialize: can't set preliminary stderr"); - PySys_SetObject("stderr", pstderr); - PySys_SetObject("__stderr__", pstderr); - - _PyImportHooks_Init(); - if (initstdio() < 0) - Py_FatalError( - "Py_Initialize: can't initialize sys standard streams"); - initmain(); - if (!Py_NoSiteFlag) - initsite(); - } + PyInterpreterState *interp; + PyThreadState *tstate, *save_tstate; + PyObject *bimod, *sysmod; + + if (!initialized) + Py_FatalError("Py_NewInterpreter: call Py_Initialize first"); + + interp = PyInterpreterState_New(); + if (interp == NULL) + return NULL; + + tstate = PyThreadState_New(interp); + if (tstate == NULL) { + PyInterpreterState_Delete(interp); + return NULL; + } + + save_tstate = PyThreadState_Swap(tstate); + + /* XXX The following is lax in error checking */ + + interp->modules = PyDict_New(); + interp->modules_reloading = PyDict_New(); + + bimod = _PyImport_FindExtension("builtins", "builtins"); + if (bimod != NULL) { + interp->builtins = PyModule_GetDict(bimod); + if (interp->builtins == NULL) + goto handle_error; + Py_INCREF(interp->builtins); + } + + /* initialize builtin exceptions */ + _PyExc_Init(); + + sysmod = _PyImport_FindExtension("sys", "sys"); + if (bimod != NULL && sysmod != NULL) { + PyObject *pstderr; + interp->sysdict = PyModule_GetDict(sysmod); + if (interp->sysdict == NULL) + goto handle_error; + Py_INCREF(interp->sysdict); + PySys_SetPath(Py_GetPath()); + PyDict_SetItemString(interp->sysdict, "modules", + interp->modules); + /* Set up a preliminary stderr printer until we have enough + infrastructure for the io module in place. */ + pstderr = PyFile_NewStdPrinter(fileno(stderr)); + if (pstderr == NULL) + Py_FatalError("Py_Initialize: can't set preliminary stderr"); + PySys_SetObject("stderr", pstderr); + PySys_SetObject("__stderr__", pstderr); + + _PyImportHooks_Init(); + if (initstdio() < 0) + Py_FatalError( + "Py_Initialize: can't initialize sys standard streams"); + initmain(); + if (!Py_NoSiteFlag) + initsite(); + } - if (!PyErr_Occurred()) - return tstate; + if (!PyErr_Occurred()) + return tstate; handle_error: - /* Oops, it didn't work. Undo it all. */ + /* Oops, it didn't work. Undo it all. */ - PyErr_Print(); - PyThreadState_Clear(tstate); - PyThreadState_Swap(save_tstate); - PyThreadState_Delete(tstate); - PyInterpreterState_Delete(interp); + PyErr_Print(); + PyThreadState_Clear(tstate); + PyThreadState_Swap(save_tstate); + PyThreadState_Delete(tstate); + PyInterpreterState_Delete(interp); - return NULL; + return NULL; } /* Delete an interpreter and its last thread. This requires that the @@ -633,19 +633,19 @@ void Py_EndInterpreter(PyThreadState *tstate) { - PyInterpreterState *interp = tstate->interp; + PyInterpreterState *interp = tstate->interp; - if (tstate != PyThreadState_GET()) - Py_FatalError("Py_EndInterpreter: thread is not current"); - if (tstate->frame != NULL) - Py_FatalError("Py_EndInterpreter: thread still has a frame"); - if (tstate != interp->tstate_head || tstate->next != NULL) - Py_FatalError("Py_EndInterpreter: not the last thread"); - - PyImport_Cleanup(); - PyInterpreterState_Clear(interp); - PyThreadState_Swap(NULL); - PyInterpreterState_Delete(interp); + if (tstate != PyThreadState_GET()) + Py_FatalError("Py_EndInterpreter: thread is not current"); + if (tstate->frame != NULL) + Py_FatalError("Py_EndInterpreter: thread still has a frame"); + if (tstate != interp->tstate_head || tstate->next != NULL) + Py_FatalError("Py_EndInterpreter: not the last thread"); + + PyImport_Cleanup(); + PyInterpreterState_Clear(interp); + PyThreadState_Swap(NULL); + PyInterpreterState_Delete(interp); } static wchar_t *progname = L"python"; @@ -653,14 +653,14 @@ void Py_SetProgramName(wchar_t *pn) { - if (pn && *pn) - progname = pn; + if (pn && *pn) + progname = pn; } wchar_t * Py_GetProgramName(void) { - return progname; + return progname; } static wchar_t *default_home = NULL; @@ -669,23 +669,23 @@ void Py_SetPythonHome(wchar_t *home) { - default_home = home; + default_home = home; } wchar_t * Py_GetPythonHome(void) { - wchar_t *home = default_home; - if (home == NULL && !Py_IgnoreEnvironmentFlag) { - char* chome = Py_GETENV("PYTHONHOME"); - if (chome) { - size_t r = mbstowcs(env_home, chome, PATH_MAX+1); - if (r != (size_t)-1 && r <= PATH_MAX) - home = env_home; - } + wchar_t *home = default_home; + if (home == NULL && !Py_IgnoreEnvironmentFlag) { + char* chome = Py_GETENV("PYTHONHOME"); + if (chome) { + size_t r = mbstowcs(env_home, chome, PATH_MAX+1); + if (r != (size_t)-1 && r <= PATH_MAX) + home = env_home; + } - } - return home; + } + return home; } /* Create __main__ module */ @@ -693,18 +693,18 @@ static void initmain(void) { - PyObject *m, *d; - m = PyImport_AddModule("__main__"); - if (m == NULL) - Py_FatalError("can't create __main__ module"); - d = PyModule_GetDict(m); - if (PyDict_GetItemString(d, "__builtins__") == NULL) { - PyObject *bimod = PyImport_ImportModule("builtins"); - if (bimod == NULL || - PyDict_SetItemString(d, "__builtins__", bimod) != 0) - Py_FatalError("can't add __builtins__ to __main__"); - Py_DECREF(bimod); - } + PyObject *m, *d; + m = PyImport_AddModule("__main__"); + if (m == NULL) + Py_FatalError("can't create __main__ module"); + d = PyModule_GetDict(m); + if (PyDict_GetItemString(d, "__builtins__") == NULL) { + PyObject *bimod = PyImport_ImportModule("builtins"); + if (bimod == NULL || + PyDict_SetItemString(d, "__builtins__", bimod) != 0) + Py_FatalError("can't add __builtins__ to __main__"); + Py_DECREF(bimod); + } } /* Import the site module (not into __main__ though) */ @@ -712,396 +712,396 @@ static void initsite(void) { - PyObject *m, *f; - m = PyImport_ImportModule("site"); - if (m == NULL) { - f = PySys_GetObject("stderr"); - if (f == NULL || f == Py_None) - return; - if (Py_VerboseFlag) { - PyFile_WriteString( - "'import site' failed; traceback:\n", f); - PyErr_Print(); - } - else { - PyFile_WriteString( - "'import site' failed; use -v for traceback\n", f); - PyErr_Clear(); - } - } - else { - Py_DECREF(m); - } + PyObject *m, *f; + m = PyImport_ImportModule("site"); + if (m == NULL) { + f = PySys_GetObject("stderr"); + if (f == NULL || f == Py_None) + return; + if (Py_VerboseFlag) { + PyFile_WriteString( + "'import site' failed; traceback:\n", f); + PyErr_Print(); + } + else { + PyFile_WriteString( + "'import site' failed; use -v for traceback\n", f); + PyErr_Clear(); + } + } + else { + Py_DECREF(m); + } } static PyObject* create_stdio(PyObject* io, - int fd, int write_mode, char* name, - char* encoding, char* errors) + int fd, int write_mode, char* name, + char* encoding, char* errors) { - PyObject *buf = NULL, *stream = NULL, *text = NULL, *raw = NULL, *res; - const char* mode; - PyObject *line_buffering; - int buffering, isatty; - - /* stdin is always opened in buffered mode, first because it shouldn't - make a difference in common use cases, second because TextIOWrapper - depends on the presence of a read1() method which only exists on - buffered streams. - */ - if (Py_UnbufferedStdioFlag && write_mode) - buffering = 0; - else - buffering = -1; - if (write_mode) - mode = "wb"; - else - mode = "rb"; - buf = PyObject_CallMethod(io, "open", "isiOOOi", - fd, mode, buffering, - Py_None, Py_None, Py_None, 0); - if (buf == NULL) - goto error; - - if (buffering) { - raw = PyObject_GetAttrString(buf, "raw"); - if (raw == NULL) - goto error; - } - else { - raw = buf; - Py_INCREF(raw); - } - - text = PyUnicode_FromString(name); - if (text == NULL || PyObject_SetAttrString(raw, "name", text) < 0) - goto error; - res = PyObject_CallMethod(raw, "isatty", ""); - if (res == NULL) - goto error; - isatty = PyObject_IsTrue(res); - Py_DECREF(res); - if (isatty == -1) - goto error; - if (isatty || Py_UnbufferedStdioFlag) - line_buffering = Py_True; - else - line_buffering = Py_False; - - Py_CLEAR(raw); - Py_CLEAR(text); - - stream = PyObject_CallMethod(io, "TextIOWrapper", "OsssO", - buf, encoding, errors, - "\n", line_buffering); - Py_CLEAR(buf); - if (stream == NULL) - goto error; - - if (write_mode) - mode = "w"; - else - mode = "r"; - text = PyUnicode_FromString(mode); - if (!text || PyObject_SetAttrString(stream, "mode", text) < 0) - goto error; - Py_CLEAR(text); - return stream; + PyObject *buf = NULL, *stream = NULL, *text = NULL, *raw = NULL, *res; + const char* mode; + PyObject *line_buffering; + int buffering, isatty; + + /* stdin is always opened in buffered mode, first because it shouldn't + make a difference in common use cases, second because TextIOWrapper + depends on the presence of a read1() method which only exists on + buffered streams. + */ + if (Py_UnbufferedStdioFlag && write_mode) + buffering = 0; + else + buffering = -1; + if (write_mode) + mode = "wb"; + else + mode = "rb"; + buf = PyObject_CallMethod(io, "open", "isiOOOi", + fd, mode, buffering, + Py_None, Py_None, Py_None, 0); + if (buf == NULL) + goto error; + + if (buffering) { + raw = PyObject_GetAttrString(buf, "raw"); + if (raw == NULL) + goto error; + } + else { + raw = buf; + Py_INCREF(raw); + } + + text = PyUnicode_FromString(name); + if (text == NULL || PyObject_SetAttrString(raw, "name", text) < 0) + goto error; + res = PyObject_CallMethod(raw, "isatty", ""); + if (res == NULL) + goto error; + isatty = PyObject_IsTrue(res); + Py_DECREF(res); + if (isatty == -1) + goto error; + if (isatty || Py_UnbufferedStdioFlag) + line_buffering = Py_True; + else + line_buffering = Py_False; + + Py_CLEAR(raw); + Py_CLEAR(text); + + stream = PyObject_CallMethod(io, "TextIOWrapper", "OsssO", + buf, encoding, errors, + "\n", line_buffering); + Py_CLEAR(buf); + if (stream == NULL) + goto error; + + if (write_mode) + mode = "w"; + else + mode = "r"; + text = PyUnicode_FromString(mode); + if (!text || PyObject_SetAttrString(stream, "mode", text) < 0) + goto error; + Py_CLEAR(text); + return stream; error: - Py_XDECREF(buf); - Py_XDECREF(stream); - Py_XDECREF(text); - Py_XDECREF(raw); - return NULL; + Py_XDECREF(buf); + Py_XDECREF(stream); + Py_XDECREF(text); + Py_XDECREF(raw); + return NULL; } /* Initialize sys.stdin, stdout, stderr and builtins.open */ static int initstdio(void) { - PyObject *iomod = NULL, *wrapper; - PyObject *bimod = NULL; - PyObject *m; - PyObject *std = NULL; - int status = 0, fd; - PyObject * encoding_attr; - char *encoding = NULL, *errors; - - /* Hack to avoid a nasty recursion issue when Python is invoked - in verbose mode: pre-import the Latin-1 and UTF-8 codecs */ - if ((m = PyImport_ImportModule("encodings.utf_8")) == NULL) { - goto error; - } - Py_DECREF(m); - - if (!(m = PyImport_ImportModule("encodings.latin_1"))) { - goto error; - } - Py_DECREF(m); - - if (!(bimod = PyImport_ImportModule("builtins"))) { - goto error; - } - - if (!(iomod = PyImport_ImportModule("io"))) { - goto error; - } - if (!(wrapper = PyObject_GetAttrString(iomod, "OpenWrapper"))) { - goto error; - } - - /* Set builtins.open */ - if (PyObject_SetAttrString(bimod, "open", wrapper) == -1) { - goto error; - } - - encoding = Py_GETENV("PYTHONIOENCODING"); - errors = NULL; - if (encoding) { - encoding = strdup(encoding); - errors = strchr(encoding, ':'); - if (errors) { - *errors = '\0'; - errors++; - } - } - - /* Set sys.stdin */ - fd = fileno(stdin); - /* Under some conditions stdin, stdout and stderr may not be connected - * and fileno() may point to an invalid file descriptor. For example - * GUI apps don't have valid standard streams by default. - */ - if (fd < 0) { + PyObject *iomod = NULL, *wrapper; + PyObject *bimod = NULL; + PyObject *m; + PyObject *std = NULL; + int status = 0, fd; + PyObject * encoding_attr; + char *encoding = NULL, *errors; + + /* Hack to avoid a nasty recursion issue when Python is invoked + in verbose mode: pre-import the Latin-1 and UTF-8 codecs */ + if ((m = PyImport_ImportModule("encodings.utf_8")) == NULL) { + goto error; + } + Py_DECREF(m); + + if (!(m = PyImport_ImportModule("encodings.latin_1"))) { + goto error; + } + Py_DECREF(m); + + if (!(bimod = PyImport_ImportModule("builtins"))) { + goto error; + } + + if (!(iomod = PyImport_ImportModule("io"))) { + goto error; + } + if (!(wrapper = PyObject_GetAttrString(iomod, "OpenWrapper"))) { + goto error; + } + + /* Set builtins.open */ + if (PyObject_SetAttrString(bimod, "open", wrapper) == -1) { + goto error; + } + + encoding = Py_GETENV("PYTHONIOENCODING"); + errors = NULL; + if (encoding) { + encoding = strdup(encoding); + errors = strchr(encoding, ':'); + if (errors) { + *errors = '\0'; + errors++; + } + } + + /* Set sys.stdin */ + fd = fileno(stdin); + /* Under some conditions stdin, stdout and stderr may not be connected + * and fileno() may point to an invalid file descriptor. For example + * GUI apps don't have valid standard streams by default. + */ + if (fd < 0) { #ifdef MS_WINDOWS - std = Py_None; - Py_INCREF(std); + std = Py_None; + Py_INCREF(std); #else - goto error; + goto error; #endif - } - else { - std = create_stdio(iomod, fd, 0, "", encoding, errors); - if (std == NULL) - goto error; - } /* if (fd < 0) */ - PySys_SetObject("__stdin__", std); - PySys_SetObject("stdin", std); - Py_DECREF(std); - - /* Set sys.stdout */ - fd = fileno(stdout); - if (fd < 0) { + } + else { + std = create_stdio(iomod, fd, 0, "", encoding, errors); + if (std == NULL) + goto error; + } /* if (fd < 0) */ + PySys_SetObject("__stdin__", std); + PySys_SetObject("stdin", std); + Py_DECREF(std); + + /* Set sys.stdout */ + fd = fileno(stdout); + if (fd < 0) { #ifdef MS_WINDOWS - std = Py_None; - Py_INCREF(std); + std = Py_None; + Py_INCREF(std); #else - goto error; + goto error; #endif - } - else { - std = create_stdio(iomod, fd, 1, "", encoding, errors); - if (std == NULL) - goto error; - } /* if (fd < 0) */ - PySys_SetObject("__stdout__", std); - PySys_SetObject("stdout", std); - Py_DECREF(std); + } + else { + std = create_stdio(iomod, fd, 1, "", encoding, errors); + if (std == NULL) + goto error; + } /* if (fd < 0) */ + PySys_SetObject("__stdout__", std); + PySys_SetObject("stdout", std); + Py_DECREF(std); #if 1 /* Disable this if you have trouble debugging bootstrap stuff */ - /* Set sys.stderr, replaces the preliminary stderr */ - fd = fileno(stderr); - if (fd < 0) { + /* Set sys.stderr, replaces the preliminary stderr */ + fd = fileno(stderr); + if (fd < 0) { #ifdef MS_WINDOWS - std = Py_None; - Py_INCREF(std); + std = Py_None; + Py_INCREF(std); #else - goto error; + goto error; #endif - } - else { - std = create_stdio(iomod, fd, 1, "", encoding, "backslashreplace"); - if (std == NULL) - goto error; - } /* if (fd < 0) */ - - /* Same as hack above, pre-import stderr's codec to avoid recursion - when import.c tries to write to stderr in verbose mode. */ - encoding_attr = PyObject_GetAttrString(std, "encoding"); - if (encoding_attr != NULL) { - const char * encoding; - encoding = _PyUnicode_AsString(encoding_attr); - if (encoding != NULL) { - _PyCodec_Lookup(encoding); - } - } - PyErr_Clear(); /* Not a fatal error if codec isn't available */ - - PySys_SetObject("__stderr__", std); - PySys_SetObject("stderr", std); - Py_DECREF(std); + } + else { + std = create_stdio(iomod, fd, 1, "", encoding, "backslashreplace"); + if (std == NULL) + goto error; + } /* if (fd < 0) */ + + /* Same as hack above, pre-import stderr's codec to avoid recursion + when import.c tries to write to stderr in verbose mode. */ + encoding_attr = PyObject_GetAttrString(std, "encoding"); + if (encoding_attr != NULL) { + const char * encoding; + encoding = _PyUnicode_AsString(encoding_attr); + if (encoding != NULL) { + _PyCodec_Lookup(encoding); + } + } + PyErr_Clear(); /* Not a fatal error if codec isn't available */ + + PySys_SetObject("__stderr__", std); + PySys_SetObject("stderr", std); + Py_DECREF(std); #endif - if (0) { + if (0) { error: - status = -1; - } + status = -1; + } - if (encoding) - free(encoding); - Py_XDECREF(bimod); - Py_XDECREF(iomod); - return status; + if (encoding) + free(encoding); + Py_XDECREF(bimod); + Py_XDECREF(iomod); + return status; } /* Parse input from a file and execute it */ int PyRun_AnyFileExFlags(FILE *fp, const char *filename, int closeit, - PyCompilerFlags *flags) + PyCompilerFlags *flags) { - if (filename == NULL) - filename = "???"; - if (Py_FdIsInteractive(fp, filename)) { - int err = PyRun_InteractiveLoopFlags(fp, filename, flags); - if (closeit) - fclose(fp); - return err; - } - else - return PyRun_SimpleFileExFlags(fp, filename, closeit, flags); + if (filename == NULL) + filename = "???"; + if (Py_FdIsInteractive(fp, filename)) { + int err = PyRun_InteractiveLoopFlags(fp, filename, flags); + if (closeit) + fclose(fp); + return err; + } + else + return PyRun_SimpleFileExFlags(fp, filename, closeit, flags); } int PyRun_InteractiveLoopFlags(FILE *fp, const char *filename, PyCompilerFlags *flags) { - PyObject *v; - int ret; - PyCompilerFlags local_flags; - - if (flags == NULL) { - flags = &local_flags; - local_flags.cf_flags = 0; - } - v = PySys_GetObject("ps1"); - if (v == NULL) { - PySys_SetObject("ps1", v = PyUnicode_FromString(">>> ")); - Py_XDECREF(v); - } - v = PySys_GetObject("ps2"); - if (v == NULL) { - PySys_SetObject("ps2", v = PyUnicode_FromString("... ")); - Py_XDECREF(v); - } - for (;;) { - ret = PyRun_InteractiveOneFlags(fp, filename, flags); - PRINT_TOTAL_REFS(); - if (ret == E_EOF) - return 0; - /* - if (ret == E_NOMEM) - return -1; - */ - } + PyObject *v; + int ret; + PyCompilerFlags local_flags; + + if (flags == NULL) { + flags = &local_flags; + local_flags.cf_flags = 0; + } + v = PySys_GetObject("ps1"); + if (v == NULL) { + PySys_SetObject("ps1", v = PyUnicode_FromString(">>> ")); + Py_XDECREF(v); + } + v = PySys_GetObject("ps2"); + if (v == NULL) { + PySys_SetObject("ps2", v = PyUnicode_FromString("... ")); + Py_XDECREF(v); + } + for (;;) { + ret = PyRun_InteractiveOneFlags(fp, filename, flags); + PRINT_TOTAL_REFS(); + if (ret == E_EOF) + return 0; + /* + if (ret == E_NOMEM) + return -1; + */ + } } /* compute parser flags based on compiler flags */ static int PARSER_FLAGS(PyCompilerFlags *flags) { - int parser_flags = 0; - if (!flags) - return 0; - if (flags->cf_flags & PyCF_DONT_IMPLY_DEDENT) - parser_flags |= PyPARSE_DONT_IMPLY_DEDENT; - if (flags->cf_flags & PyCF_IGNORE_COOKIE) - parser_flags |= PyPARSE_IGNORE_COOKIE; - if (flags->cf_flags & CO_FUTURE_BARRY_AS_BDFL) - parser_flags |= PyPARSE_BARRY_AS_BDFL; - return parser_flags; + int parser_flags = 0; + if (!flags) + return 0; + if (flags->cf_flags & PyCF_DONT_IMPLY_DEDENT) + parser_flags |= PyPARSE_DONT_IMPLY_DEDENT; + if (flags->cf_flags & PyCF_IGNORE_COOKIE) + parser_flags |= PyPARSE_IGNORE_COOKIE; + if (flags->cf_flags & CO_FUTURE_BARRY_AS_BDFL) + parser_flags |= PyPARSE_BARRY_AS_BDFL; + return parser_flags; } #if 0 /* Keep an example of flags with future keyword support. */ #define PARSER_FLAGS(flags) \ - ((flags) ? ((((flags)->cf_flags & PyCF_DONT_IMPLY_DEDENT) ? \ - PyPARSE_DONT_IMPLY_DEDENT : 0) \ - | ((flags)->cf_flags & CO_FUTURE_WITH_STATEMENT ? \ - PyPARSE_WITH_IS_KEYWORD : 0)) : 0) + ((flags) ? ((((flags)->cf_flags & PyCF_DONT_IMPLY_DEDENT) ? \ + PyPARSE_DONT_IMPLY_DEDENT : 0) \ + | ((flags)->cf_flags & CO_FUTURE_WITH_STATEMENT ? \ + PyPARSE_WITH_IS_KEYWORD : 0)) : 0) #endif int PyRun_InteractiveOneFlags(FILE *fp, const char *filename, PyCompilerFlags *flags) { - PyObject *m, *d, *v, *w, *oenc = NULL; - mod_ty mod; - PyArena *arena; - char *ps1 = "", *ps2 = "", *enc = NULL; - int errcode = 0; - - if (fp == stdin) { - /* Fetch encoding from sys.stdin */ - v = PySys_GetObject("stdin"); - if (v == NULL || v == Py_None) - return -1; - oenc = PyObject_GetAttrString(v, "encoding"); - if (!oenc) - return -1; - enc = _PyUnicode_AsString(oenc); - } - v = PySys_GetObject("ps1"); - if (v != NULL) { - v = PyObject_Str(v); - if (v == NULL) - PyErr_Clear(); - else if (PyUnicode_Check(v)) - ps1 = _PyUnicode_AsString(v); - } - w = PySys_GetObject("ps2"); - if (w != NULL) { - w = PyObject_Str(w); - if (w == NULL) - PyErr_Clear(); - else if (PyUnicode_Check(w)) - ps2 = _PyUnicode_AsString(w); - } - arena = PyArena_New(); - if (arena == NULL) { - Py_XDECREF(v); - Py_XDECREF(w); - Py_XDECREF(oenc); - return -1; - } - mod = PyParser_ASTFromFile(fp, filename, enc, - Py_single_input, ps1, ps2, - flags, &errcode, arena); - Py_XDECREF(v); - Py_XDECREF(w); - Py_XDECREF(oenc); - if (mod == NULL) { - PyArena_Free(arena); - if (errcode == E_EOF) { - PyErr_Clear(); - return E_EOF; - } - PyErr_Print(); - return -1; - } - m = PyImport_AddModule("__main__"); - if (m == NULL) { - PyArena_Free(arena); - return -1; - } - d = PyModule_GetDict(m); - v = run_mod(mod, filename, d, d, flags, arena); - PyArena_Free(arena); - flush_io(); - if (v == NULL) { - PyErr_Print(); - return -1; - } - Py_DECREF(v); - return 0; + PyObject *m, *d, *v, *w, *oenc = NULL; + mod_ty mod; + PyArena *arena; + char *ps1 = "", *ps2 = "", *enc = NULL; + int errcode = 0; + + if (fp == stdin) { + /* Fetch encoding from sys.stdin */ + v = PySys_GetObject("stdin"); + if (v == NULL || v == Py_None) + return -1; + oenc = PyObject_GetAttrString(v, "encoding"); + if (!oenc) + return -1; + enc = _PyUnicode_AsString(oenc); + } + v = PySys_GetObject("ps1"); + if (v != NULL) { + v = PyObject_Str(v); + if (v == NULL) + PyErr_Clear(); + else if (PyUnicode_Check(v)) + ps1 = _PyUnicode_AsString(v); + } + w = PySys_GetObject("ps2"); + if (w != NULL) { + w = PyObject_Str(w); + if (w == NULL) + PyErr_Clear(); + else if (PyUnicode_Check(w)) + ps2 = _PyUnicode_AsString(w); + } + arena = PyArena_New(); + if (arena == NULL) { + Py_XDECREF(v); + Py_XDECREF(w); + Py_XDECREF(oenc); + return -1; + } + mod = PyParser_ASTFromFile(fp, filename, enc, + Py_single_input, ps1, ps2, + flags, &errcode, arena); + Py_XDECREF(v); + Py_XDECREF(w); + Py_XDECREF(oenc); + if (mod == NULL) { + PyArena_Free(arena); + if (errcode == E_EOF) { + PyErr_Clear(); + return E_EOF; + } + PyErr_Print(); + return -1; + } + m = PyImport_AddModule("__main__"); + if (m == NULL) { + PyArena_Free(arena); + return -1; + } + d = PyModule_GetDict(m); + v = run_mod(mod, filename, d, d, flags, arena); + PyArena_Free(arena); + flush_io(); + if (v == NULL) { + PyErr_Print(); + return -1; + } + Py_DECREF(v); + return 0; } /* Check whether a file maybe a pyc file: Look at the extension, @@ -1110,737 +1110,737 @@ static int maybe_pyc_file(FILE *fp, const char* filename, const char* ext, int closeit) { - if (strcmp(ext, ".pyc") == 0 || strcmp(ext, ".pyo") == 0) - return 1; + if (strcmp(ext, ".pyc") == 0 || strcmp(ext, ".pyo") == 0) + return 1; - /* Only look into the file if we are allowed to close it, since - it then should also be seekable. */ - if (closeit) { - /* Read only two bytes of the magic. If the file was opened in - text mode, the bytes 3 and 4 of the magic (\r\n) might not - be read as they are on disk. */ - unsigned int halfmagic = PyImport_GetMagicNumber() & 0xFFFF; - unsigned char buf[2]; - /* Mess: In case of -x, the stream is NOT at its start now, - and ungetc() was used to push back the first newline, - which makes the current stream position formally undefined, - and a x-platform nightmare. - Unfortunately, we have no direct way to know whether -x - was specified. So we use a terrible hack: if the current - stream position is not 0, we assume -x was specified, and - give up. Bug 132850 on SourceForge spells out the - hopelessness of trying anything else (fseek and ftell - don't work predictably x-platform for text-mode files). - */ - int ispyc = 0; - if (ftell(fp) == 0) { - if (fread(buf, 1, 2, fp) == 2 && - ((unsigned int)buf[1]<<8 | buf[0]) == halfmagic) - ispyc = 1; - rewind(fp); - } - return ispyc; - } - return 0; + /* Only look into the file if we are allowed to close it, since + it then should also be seekable. */ + if (closeit) { + /* Read only two bytes of the magic. If the file was opened in + text mode, the bytes 3 and 4 of the magic (\r\n) might not + be read as they are on disk. */ + unsigned int halfmagic = PyImport_GetMagicNumber() & 0xFFFF; + unsigned char buf[2]; + /* Mess: In case of -x, the stream is NOT at its start now, + and ungetc() was used to push back the first newline, + which makes the current stream position formally undefined, + and a x-platform nightmare. + Unfortunately, we have no direct way to know whether -x + was specified. So we use a terrible hack: if the current + stream position is not 0, we assume -x was specified, and + give up. Bug 132850 on SourceForge spells out the + hopelessness of trying anything else (fseek and ftell + don't work predictably x-platform for text-mode files). + */ + int ispyc = 0; + if (ftell(fp) == 0) { + if (fread(buf, 1, 2, fp) == 2 && + ((unsigned int)buf[1]<<8 | buf[0]) == halfmagic) + ispyc = 1; + rewind(fp); + } + return ispyc; + } + return 0; } int PyRun_SimpleFileExFlags(FILE *fp, const char *filename, int closeit, - PyCompilerFlags *flags) + PyCompilerFlags *flags) { - PyObject *m, *d, *v; - const char *ext; - int set_file_name = 0, ret, len; - - m = PyImport_AddModule("__main__"); - if (m == NULL) - return -1; - d = PyModule_GetDict(m); - if (PyDict_GetItemString(d, "__file__") == NULL) { - PyObject *f; - f = PyUnicode_DecodeFSDefault(filename); - if (f == NULL) - return -1; - if (PyDict_SetItemString(d, "__file__", f) < 0) { - Py_DECREF(f); - return -1; - } - set_file_name = 1; - Py_DECREF(f); - } - len = strlen(filename); - ext = filename + len - (len > 4 ? 4 : 0); - if (maybe_pyc_file(fp, filename, ext, closeit)) { - /* Try to run a pyc file. First, re-open in binary */ - if (closeit) - fclose(fp); - if ((fp = fopen(filename, "rb")) == NULL) { - fprintf(stderr, "python: Can't reopen .pyc file\n"); - ret = -1; - goto done; - } - /* Turn on optimization if a .pyo file is given */ - if (strcmp(ext, ".pyo") == 0) - Py_OptimizeFlag = 1; - v = run_pyc_file(fp, filename, d, d, flags); - } else { - v = PyRun_FileExFlags(fp, filename, Py_file_input, d, d, - closeit, flags); - } - flush_io(); - if (v == NULL) { - PyErr_Print(); - ret = -1; - goto done; - } - Py_DECREF(v); - ret = 0; + PyObject *m, *d, *v; + const char *ext; + int set_file_name = 0, ret, len; + + m = PyImport_AddModule("__main__"); + if (m == NULL) + return -1; + d = PyModule_GetDict(m); + if (PyDict_GetItemString(d, "__file__") == NULL) { + PyObject *f; + f = PyUnicode_DecodeFSDefault(filename); + if (f == NULL) + return -1; + if (PyDict_SetItemString(d, "__file__", f) < 0) { + Py_DECREF(f); + return -1; + } + set_file_name = 1; + Py_DECREF(f); + } + len = strlen(filename); + ext = filename + len - (len > 4 ? 4 : 0); + if (maybe_pyc_file(fp, filename, ext, closeit)) { + /* Try to run a pyc file. First, re-open in binary */ + if (closeit) + fclose(fp); + if ((fp = fopen(filename, "rb")) == NULL) { + fprintf(stderr, "python: Can't reopen .pyc file\n"); + ret = -1; + goto done; + } + /* Turn on optimization if a .pyo file is given */ + if (strcmp(ext, ".pyo") == 0) + Py_OptimizeFlag = 1; + v = run_pyc_file(fp, filename, d, d, flags); + } else { + v = PyRun_FileExFlags(fp, filename, Py_file_input, d, d, + closeit, flags); + } + flush_io(); + if (v == NULL) { + PyErr_Print(); + ret = -1; + goto done; + } + Py_DECREF(v); + ret = 0; done: - if (set_file_name && PyDict_DelItemString(d, "__file__")) - PyErr_Clear(); - return ret; + if (set_file_name && PyDict_DelItemString(d, "__file__")) + PyErr_Clear(); + return ret; } int PyRun_SimpleStringFlags(const char *command, PyCompilerFlags *flags) { - PyObject *m, *d, *v; - m = PyImport_AddModule("__main__"); - if (m == NULL) - return -1; - d = PyModule_GetDict(m); - v = PyRun_StringFlags(command, Py_file_input, d, d, flags); - if (v == NULL) { - PyErr_Print(); - return -1; - } - Py_DECREF(v); - return 0; + PyObject *m, *d, *v; + m = PyImport_AddModule("__main__"); + if (m == NULL) + return -1; + d = PyModule_GetDict(m); + v = PyRun_StringFlags(command, Py_file_input, d, d, flags); + if (v == NULL) { + PyErr_Print(); + return -1; + } + Py_DECREF(v); + return 0; } static int parse_syntax_error(PyObject *err, PyObject **message, const char **filename, - int *lineno, int *offset, const char **text) + int *lineno, int *offset, const char **text) { - long hold; - PyObject *v; + long hold; + PyObject *v; - /* old style errors */ - if (PyTuple_Check(err)) - return PyArg_ParseTuple(err, "O(ziiz)", message, filename, - lineno, offset, text); - - /* new style errors. `err' is an instance */ - - if (! (v = PyObject_GetAttrString(err, "msg"))) - goto finally; - *message = v; - - if (!(v = PyObject_GetAttrString(err, "filename"))) - goto finally; - if (v == Py_None) - *filename = NULL; - else if (! (*filename = _PyUnicode_AsString(v))) - goto finally; - - Py_DECREF(v); - if (!(v = PyObject_GetAttrString(err, "lineno"))) - goto finally; - hold = PyLong_AsLong(v); - Py_DECREF(v); - v = NULL; - if (hold < 0 && PyErr_Occurred()) - goto finally; - *lineno = (int)hold; - - if (!(v = PyObject_GetAttrString(err, "offset"))) - goto finally; - if (v == Py_None) { - *offset = -1; - Py_DECREF(v); - v = NULL; - } else { - hold = PyLong_AsLong(v); - Py_DECREF(v); - v = NULL; - if (hold < 0 && PyErr_Occurred()) - goto finally; - *offset = (int)hold; - } - - if (!(v = PyObject_GetAttrString(err, "text"))) - goto finally; - if (v == Py_None) - *text = NULL; - else if (!PyUnicode_Check(v) || - !(*text = _PyUnicode_AsString(v))) - goto finally; - Py_DECREF(v); - return 1; + /* old style errors */ + if (PyTuple_Check(err)) + return PyArg_ParseTuple(err, "O(ziiz)", message, filename, + lineno, offset, text); + + /* new style errors. `err' is an instance */ + + if (! (v = PyObject_GetAttrString(err, "msg"))) + goto finally; + *message = v; + + if (!(v = PyObject_GetAttrString(err, "filename"))) + goto finally; + if (v == Py_None) + *filename = NULL; + else if (! (*filename = _PyUnicode_AsString(v))) + goto finally; + + Py_DECREF(v); + if (!(v = PyObject_GetAttrString(err, "lineno"))) + goto finally; + hold = PyLong_AsLong(v); + Py_DECREF(v); + v = NULL; + if (hold < 0 && PyErr_Occurred()) + goto finally; + *lineno = (int)hold; + + if (!(v = PyObject_GetAttrString(err, "offset"))) + goto finally; + if (v == Py_None) { + *offset = -1; + Py_DECREF(v); + v = NULL; + } else { + hold = PyLong_AsLong(v); + Py_DECREF(v); + v = NULL; + if (hold < 0 && PyErr_Occurred()) + goto finally; + *offset = (int)hold; + } + + if (!(v = PyObject_GetAttrString(err, "text"))) + goto finally; + if (v == Py_None) + *text = NULL; + else if (!PyUnicode_Check(v) || + !(*text = _PyUnicode_AsString(v))) + goto finally; + Py_DECREF(v); + return 1; finally: - Py_XDECREF(v); - return 0; + Py_XDECREF(v); + return 0; } void PyErr_Print(void) { - PyErr_PrintEx(1); + PyErr_PrintEx(1); } static void print_error_text(PyObject *f, int offset, const char *text) { - char *nl; - if (offset >= 0) { - if (offset > 0 && offset == (int)strlen(text)) - offset--; - for (;;) { - nl = strchr(text, '\n'); - if (nl == NULL || nl-text >= offset) - break; - offset -= (int)(nl+1-text); - text = nl+1; - } - while (*text == ' ' || *text == '\t') { - text++; - offset--; - } - } - PyFile_WriteString(" ", f); - PyFile_WriteString(text, f); - if (*text == '\0' || text[strlen(text)-1] != '\n') - PyFile_WriteString("\n", f); - if (offset == -1) - return; - PyFile_WriteString(" ", f); - offset--; - while (offset > 0) { - PyFile_WriteString(" ", f); - offset--; - } - PyFile_WriteString("^\n", f); + char *nl; + if (offset >= 0) { + if (offset > 0 && offset == (int)strlen(text)) + offset--; + for (;;) { + nl = strchr(text, '\n'); + if (nl == NULL || nl-text >= offset) + break; + offset -= (int)(nl+1-text); + text = nl+1; + } + while (*text == ' ' || *text == '\t') { + text++; + offset--; + } + } + PyFile_WriteString(" ", f); + PyFile_WriteString(text, f); + if (*text == '\0' || text[strlen(text)-1] != '\n') + PyFile_WriteString("\n", f); + if (offset == -1) + return; + PyFile_WriteString(" ", f); + offset--; + while (offset > 0) { + PyFile_WriteString(" ", f); + offset--; + } + PyFile_WriteString("^\n", f); } static void handle_system_exit(void) { - PyObject *exception, *value, *tb; - int exitcode = 0; + PyObject *exception, *value, *tb; + int exitcode = 0; - if (Py_InspectFlag) - /* Don't exit if -i flag was given. This flag is set to 0 - * when entering interactive mode for inspecting. */ - return; - - PyErr_Fetch(&exception, &value, &tb); - fflush(stdout); - if (value == NULL || value == Py_None) - goto done; - if (PyExceptionInstance_Check(value)) { - /* The error code should be in the `code' attribute. */ - PyObject *code = PyObject_GetAttrString(value, "code"); - if (code) { - Py_DECREF(value); - value = code; - if (value == Py_None) - goto done; - } - /* If we failed to dig out the 'code' attribute, - just let the else clause below print the error. */ - } - if (PyLong_Check(value)) - exitcode = (int)PyLong_AsLong(value); - else { - PyObject_Print(value, stderr, Py_PRINT_RAW); - PySys_WriteStderr("\n"); - exitcode = 1; - } + if (Py_InspectFlag) + /* Don't exit if -i flag was given. This flag is set to 0 + * when entering interactive mode for inspecting. */ + return; + + PyErr_Fetch(&exception, &value, &tb); + fflush(stdout); + if (value == NULL || value == Py_None) + goto done; + if (PyExceptionInstance_Check(value)) { + /* The error code should be in the `code' attribute. */ + PyObject *code = PyObject_GetAttrString(value, "code"); + if (code) { + Py_DECREF(value); + value = code; + if (value == Py_None) + goto done; + } + /* If we failed to dig out the 'code' attribute, + just let the else clause below print the error. */ + } + if (PyLong_Check(value)) + exitcode = (int)PyLong_AsLong(value); + else { + PyObject_Print(value, stderr, Py_PRINT_RAW); + PySys_WriteStderr("\n"); + exitcode = 1; + } done: - /* Restore and clear the exception info, in order to properly decref - * the exception, value, and traceback. If we just exit instead, - * these leak, which confuses PYTHONDUMPREFS output, and may prevent - * some finalizers from running. - */ - PyErr_Restore(exception, value, tb); - PyErr_Clear(); - Py_Exit(exitcode); - /* NOTREACHED */ + /* Restore and clear the exception info, in order to properly decref + * the exception, value, and traceback. If we just exit instead, + * these leak, which confuses PYTHONDUMPREFS output, and may prevent + * some finalizers from running. + */ + PyErr_Restore(exception, value, tb); + PyErr_Clear(); + Py_Exit(exitcode); + /* NOTREACHED */ } void PyErr_PrintEx(int set_sys_last_vars) { - PyObject *exception, *v, *tb, *hook; + PyObject *exception, *v, *tb, *hook; - if (PyErr_ExceptionMatches(PyExc_SystemExit)) { - handle_system_exit(); - } - PyErr_Fetch(&exception, &v, &tb); - if (exception == NULL) - return; - PyErr_NormalizeException(&exception, &v, &tb); - if (tb == NULL) { - tb = Py_None; - Py_INCREF(tb); - } - PyException_SetTraceback(v, tb); - if (exception == NULL) - return; - /* Now we know v != NULL too */ - if (set_sys_last_vars) { - PySys_SetObject("last_type", exception); - PySys_SetObject("last_value", v); - PySys_SetObject("last_traceback", tb); - } - hook = PySys_GetObject("excepthook"); - if (hook) { - PyObject *args = PyTuple_Pack(3, exception, v, tb); - PyObject *result = PyEval_CallObject(hook, args); - if (result == NULL) { - PyObject *exception2, *v2, *tb2; - if (PyErr_ExceptionMatches(PyExc_SystemExit)) { - handle_system_exit(); - } - PyErr_Fetch(&exception2, &v2, &tb2); - PyErr_NormalizeException(&exception2, &v2, &tb2); - /* It should not be possible for exception2 or v2 - to be NULL. However PyErr_Display() can't - tolerate NULLs, so just be safe. */ - if (exception2 == NULL) { - exception2 = Py_None; - Py_INCREF(exception2); - } - if (v2 == NULL) { - v2 = Py_None; - Py_INCREF(v2); - } - fflush(stdout); - PySys_WriteStderr("Error in sys.excepthook:\n"); - PyErr_Display(exception2, v2, tb2); - PySys_WriteStderr("\nOriginal exception was:\n"); - PyErr_Display(exception, v, tb); - Py_DECREF(exception2); - Py_DECREF(v2); - Py_XDECREF(tb2); - } - Py_XDECREF(result); - Py_XDECREF(args); - } else { - PySys_WriteStderr("sys.excepthook is missing\n"); - PyErr_Display(exception, v, tb); - } - Py_XDECREF(exception); - Py_XDECREF(v); - Py_XDECREF(tb); + if (PyErr_ExceptionMatches(PyExc_SystemExit)) { + handle_system_exit(); + } + PyErr_Fetch(&exception, &v, &tb); + if (exception == NULL) + return; + PyErr_NormalizeException(&exception, &v, &tb); + if (tb == NULL) { + tb = Py_None; + Py_INCREF(tb); + } + PyException_SetTraceback(v, tb); + if (exception == NULL) + return; + /* Now we know v != NULL too */ + if (set_sys_last_vars) { + PySys_SetObject("last_type", exception); + PySys_SetObject("last_value", v); + PySys_SetObject("last_traceback", tb); + } + hook = PySys_GetObject("excepthook"); + if (hook) { + PyObject *args = PyTuple_Pack(3, exception, v, tb); + PyObject *result = PyEval_CallObject(hook, args); + if (result == NULL) { + PyObject *exception2, *v2, *tb2; + if (PyErr_ExceptionMatches(PyExc_SystemExit)) { + handle_system_exit(); + } + PyErr_Fetch(&exception2, &v2, &tb2); + PyErr_NormalizeException(&exception2, &v2, &tb2); + /* It should not be possible for exception2 or v2 + to be NULL. However PyErr_Display() can't + tolerate NULLs, so just be safe. */ + if (exception2 == NULL) { + exception2 = Py_None; + Py_INCREF(exception2); + } + if (v2 == NULL) { + v2 = Py_None; + Py_INCREF(v2); + } + fflush(stdout); + PySys_WriteStderr("Error in sys.excepthook:\n"); + PyErr_Display(exception2, v2, tb2); + PySys_WriteStderr("\nOriginal exception was:\n"); + PyErr_Display(exception, v, tb); + Py_DECREF(exception2); + Py_DECREF(v2); + Py_XDECREF(tb2); + } + Py_XDECREF(result); + Py_XDECREF(args); + } else { + PySys_WriteStderr("sys.excepthook is missing\n"); + PyErr_Display(exception, v, tb); + } + Py_XDECREF(exception); + Py_XDECREF(v); + Py_XDECREF(tb); } static void print_exception(PyObject *f, PyObject *value) { - int err = 0; - PyObject *type, *tb; + int err = 0; + PyObject *type, *tb; - if (!PyExceptionInstance_Check(value)) { - PyFile_WriteString("TypeError: print_exception(): Exception expected for value, ", f); - PyFile_WriteString(Py_TYPE(value)->tp_name, f); - PyFile_WriteString(" found\n", f); - return; - } - - Py_INCREF(value); - fflush(stdout); - type = (PyObject *) Py_TYPE(value); - tb = PyException_GetTraceback(value); - if (tb && tb != Py_None) - err = PyTraceBack_Print(tb, f); - if (err == 0 && - PyObject_HasAttrString(value, "print_file_and_line")) - { - PyObject *message; - const char *filename, *text; - int lineno, offset; - if (!parse_syntax_error(value, &message, &filename, - &lineno, &offset, &text)) - PyErr_Clear(); - else { - char buf[10]; - PyFile_WriteString(" File \"", f); - if (filename == NULL) - PyFile_WriteString("", f); - else - PyFile_WriteString(filename, f); - PyFile_WriteString("\", line ", f); - PyOS_snprintf(buf, sizeof(buf), "%d", lineno); - PyFile_WriteString(buf, f); - PyFile_WriteString("\n", f); - if (text != NULL) - print_error_text(f, offset, text); - Py_DECREF(value); - value = message; - /* Can't be bothered to check all those - PyFile_WriteString() calls */ - if (PyErr_Occurred()) - err = -1; - } - } - if (err) { - /* Don't do anything else */ - } - else { - PyObject* moduleName; - char* className; - assert(PyExceptionClass_Check(type)); - className = PyExceptionClass_Name(type); - if (className != NULL) { - char *dot = strrchr(className, '.'); - if (dot != NULL) - className = dot+1; - } - - moduleName = PyObject_GetAttrString(type, "__module__"); - if (moduleName == NULL || !PyUnicode_Check(moduleName)) - { - Py_DECREF(moduleName); - err = PyFile_WriteString("", f); - } - else { - char* modstr = _PyUnicode_AsString(moduleName); - if (modstr && strcmp(modstr, "builtins")) - { - err = PyFile_WriteString(modstr, f); - err += PyFile_WriteString(".", f); - } - Py_DECREF(moduleName); - } - if (err == 0) { - if (className == NULL) - err = PyFile_WriteString("", f); - else - err = PyFile_WriteString(className, f); - } - } - if (err == 0 && (value != Py_None)) { - PyObject *s = PyObject_Str(value); - /* only print colon if the str() of the - object is not the empty string - */ - if (s == NULL) - err = -1; - else if (!PyUnicode_Check(s) || - PyUnicode_GetSize(s) != 0) - err = PyFile_WriteString(": ", f); - if (err == 0) - err = PyFile_WriteObject(s, f, Py_PRINT_RAW); - Py_XDECREF(s); - } - /* try to write a newline in any case */ - err += PyFile_WriteString("\n", f); - Py_XDECREF(tb); - Py_DECREF(value); - /* If an error happened here, don't show it. - XXX This is wrong, but too many callers rely on this behavior. */ - if (err != 0) - PyErr_Clear(); + if (!PyExceptionInstance_Check(value)) { + PyFile_WriteString("TypeError: print_exception(): Exception expected for value, ", f); + PyFile_WriteString(Py_TYPE(value)->tp_name, f); + PyFile_WriteString(" found\n", f); + return; + } + + Py_INCREF(value); + fflush(stdout); + type = (PyObject *) Py_TYPE(value); + tb = PyException_GetTraceback(value); + if (tb && tb != Py_None) + err = PyTraceBack_Print(tb, f); + if (err == 0 && + PyObject_HasAttrString(value, "print_file_and_line")) + { + PyObject *message; + const char *filename, *text; + int lineno, offset; + if (!parse_syntax_error(value, &message, &filename, + &lineno, &offset, &text)) + PyErr_Clear(); + else { + char buf[10]; + PyFile_WriteString(" File \"", f); + if (filename == NULL) + PyFile_WriteString("", f); + else + PyFile_WriteString(filename, f); + PyFile_WriteString("\", line ", f); + PyOS_snprintf(buf, sizeof(buf), "%d", lineno); + PyFile_WriteString(buf, f); + PyFile_WriteString("\n", f); + if (text != NULL) + print_error_text(f, offset, text); + Py_DECREF(value); + value = message; + /* Can't be bothered to check all those + PyFile_WriteString() calls */ + if (PyErr_Occurred()) + err = -1; + } + } + if (err) { + /* Don't do anything else */ + } + else { + PyObject* moduleName; + char* className; + assert(PyExceptionClass_Check(type)); + className = PyExceptionClass_Name(type); + if (className != NULL) { + char *dot = strrchr(className, '.'); + if (dot != NULL) + className = dot+1; + } + + moduleName = PyObject_GetAttrString(type, "__module__"); + if (moduleName == NULL || !PyUnicode_Check(moduleName)) + { + Py_DECREF(moduleName); + err = PyFile_WriteString("", f); + } + else { + char* modstr = _PyUnicode_AsString(moduleName); + if (modstr && strcmp(modstr, "builtins")) + { + err = PyFile_WriteString(modstr, f); + err += PyFile_WriteString(".", f); + } + Py_DECREF(moduleName); + } + if (err == 0) { + if (className == NULL) + err = PyFile_WriteString("", f); + else + err = PyFile_WriteString(className, f); + } + } + if (err == 0 && (value != Py_None)) { + PyObject *s = PyObject_Str(value); + /* only print colon if the str() of the + object is not the empty string + */ + if (s == NULL) + err = -1; + else if (!PyUnicode_Check(s) || + PyUnicode_GetSize(s) != 0) + err = PyFile_WriteString(": ", f); + if (err == 0) + err = PyFile_WriteObject(s, f, Py_PRINT_RAW); + Py_XDECREF(s); + } + /* try to write a newline in any case */ + err += PyFile_WriteString("\n", f); + Py_XDECREF(tb); + Py_DECREF(value); + /* If an error happened here, don't show it. + XXX This is wrong, but too many callers rely on this behavior. */ + if (err != 0) + PyErr_Clear(); } static const char *cause_message = - "\nThe above exception was the direct cause " - "of the following exception:\n\n"; + "\nThe above exception was the direct cause " + "of the following exception:\n\n"; static const char *context_message = - "\nDuring handling of the above exception, " - "another exception occurred:\n\n"; + "\nDuring handling of the above exception, " + "another exception occurred:\n\n"; static void print_exception_recursive(PyObject *f, PyObject *value, PyObject *seen) { - int err = 0, res; - PyObject *cause, *context; + int err = 0, res; + PyObject *cause, *context; - if (seen != NULL) { - /* Exception chaining */ - if (PySet_Add(seen, value) == -1) - PyErr_Clear(); - else if (PyExceptionInstance_Check(value)) { - cause = PyException_GetCause(value); - context = PyException_GetContext(value); - if (cause) { - res = PySet_Contains(seen, cause); - if (res == -1) - PyErr_Clear(); - if (res == 0) { - print_exception_recursive( - f, cause, seen); - err |= PyFile_WriteString( - cause_message, f); - } - } - else if (context) { - res = PySet_Contains(seen, context); - if (res == -1) - PyErr_Clear(); - if (res == 0) { - print_exception_recursive( - f, context, seen); - err |= PyFile_WriteString( - context_message, f); - } - } - Py_XDECREF(context); - Py_XDECREF(cause); - } - } - print_exception(f, value); - if (err != 0) - PyErr_Clear(); + if (seen != NULL) { + /* Exception chaining */ + if (PySet_Add(seen, value) == -1) + PyErr_Clear(); + else if (PyExceptionInstance_Check(value)) { + cause = PyException_GetCause(value); + context = PyException_GetContext(value); + if (cause) { + res = PySet_Contains(seen, cause); + if (res == -1) + PyErr_Clear(); + if (res == 0) { + print_exception_recursive( + f, cause, seen); + err |= PyFile_WriteString( + cause_message, f); + } + } + else if (context) { + res = PySet_Contains(seen, context); + if (res == -1) + PyErr_Clear(); + if (res == 0) { + print_exception_recursive( + f, context, seen); + err |= PyFile_WriteString( + context_message, f); + } + } + Py_XDECREF(context); + Py_XDECREF(cause); + } + } + print_exception(f, value); + if (err != 0) + PyErr_Clear(); } void PyErr_Display(PyObject *exception, PyObject *value, PyObject *tb) { - PyObject *seen; - PyObject *f = PySys_GetObject("stderr"); - if (f == Py_None) { - /* pass */ - } - else if (f == NULL) { - _PyObject_Dump(value); - fprintf(stderr, "lost sys.stderr\n"); - } - else { - /* We choose to ignore seen being possibly NULL, and report - at least the main exception (it could be a MemoryError). - */ - seen = PySet_New(NULL); - if (seen == NULL) - PyErr_Clear(); - print_exception_recursive(f, value, seen); - Py_XDECREF(seen); - } + PyObject *seen; + PyObject *f = PySys_GetObject("stderr"); + if (f == Py_None) { + /* pass */ + } + else if (f == NULL) { + _PyObject_Dump(value); + fprintf(stderr, "lost sys.stderr\n"); + } + else { + /* We choose to ignore seen being possibly NULL, and report + at least the main exception (it could be a MemoryError). + */ + seen = PySet_New(NULL); + if (seen == NULL) + PyErr_Clear(); + print_exception_recursive(f, value, seen); + Py_XDECREF(seen); + } } PyObject * PyRun_StringFlags(const char *str, int start, PyObject *globals, - PyObject *locals, PyCompilerFlags *flags) + PyObject *locals, PyCompilerFlags *flags) { - PyObject *ret = NULL; - mod_ty mod; - PyArena *arena = PyArena_New(); - if (arena == NULL) - return NULL; - - mod = PyParser_ASTFromString(str, "", start, flags, arena); - if (mod != NULL) - ret = run_mod(mod, "", globals, locals, flags, arena); - PyArena_Free(arena); - return ret; + PyObject *ret = NULL; + mod_ty mod; + PyArena *arena = PyArena_New(); + if (arena == NULL) + return NULL; + + mod = PyParser_ASTFromString(str, "", start, flags, arena); + if (mod != NULL) + ret = run_mod(mod, "", globals, locals, flags, arena); + PyArena_Free(arena); + return ret; } PyObject * PyRun_FileExFlags(FILE *fp, const char *filename, int start, PyObject *globals, - PyObject *locals, int closeit, PyCompilerFlags *flags) + PyObject *locals, int closeit, PyCompilerFlags *flags) { - PyObject *ret; - mod_ty mod; - PyArena *arena = PyArena_New(); - if (arena == NULL) - return NULL; - - mod = PyParser_ASTFromFile(fp, filename, NULL, start, 0, 0, - flags, NULL, arena); - if (closeit) - fclose(fp); - if (mod == NULL) { - PyArena_Free(arena); - return NULL; - } - ret = run_mod(mod, filename, globals, locals, flags, arena); - PyArena_Free(arena); - return ret; + PyObject *ret; + mod_ty mod; + PyArena *arena = PyArena_New(); + if (arena == NULL) + return NULL; + + mod = PyParser_ASTFromFile(fp, filename, NULL, start, 0, 0, + flags, NULL, arena); + if (closeit) + fclose(fp); + if (mod == NULL) { + PyArena_Free(arena); + return NULL; + } + ret = run_mod(mod, filename, globals, locals, flags, arena); + PyArena_Free(arena); + return ret; } static void flush_io(void) { - PyObject *f, *r; - PyObject *type, *value, *traceback; + PyObject *f, *r; + PyObject *type, *value, *traceback; - /* Save the current exception */ - PyErr_Fetch(&type, &value, &traceback); + /* Save the current exception */ + PyErr_Fetch(&type, &value, &traceback); - f = PySys_GetObject("stderr"); - if (f != NULL) { - r = PyObject_CallMethod(f, "flush", ""); - if (r) - Py_DECREF(r); - else - PyErr_Clear(); - } - f = PySys_GetObject("stdout"); - if (f != NULL) { - r = PyObject_CallMethod(f, "flush", ""); - if (r) - Py_DECREF(r); - else - PyErr_Clear(); - } + f = PySys_GetObject("stderr"); + if (f != NULL) { + r = PyObject_CallMethod(f, "flush", ""); + if (r) + Py_DECREF(r); + else + PyErr_Clear(); + } + f = PySys_GetObject("stdout"); + if (f != NULL) { + r = PyObject_CallMethod(f, "flush", ""); + if (r) + Py_DECREF(r); + else + PyErr_Clear(); + } - PyErr_Restore(type, value, traceback); + PyErr_Restore(type, value, traceback); } static PyObject * run_mod(mod_ty mod, const char *filename, PyObject *globals, PyObject *locals, - PyCompilerFlags *flags, PyArena *arena) + PyCompilerFlags *flags, PyArena *arena) { - PyCodeObject *co; - PyObject *v; - co = PyAST_Compile(mod, filename, flags, arena); - if (co == NULL) - return NULL; - v = PyEval_EvalCode(co, globals, locals); - Py_DECREF(co); - return v; + PyCodeObject *co; + PyObject *v; + co = PyAST_Compile(mod, filename, flags, arena); + if (co == NULL) + return NULL; + v = PyEval_EvalCode(co, globals, locals); + Py_DECREF(co); + return v; } static PyObject * run_pyc_file(FILE *fp, const char *filename, PyObject *globals, - PyObject *locals, PyCompilerFlags *flags) + PyObject *locals, PyCompilerFlags *flags) { - PyCodeObject *co; - PyObject *v; - long magic; - long PyImport_GetMagicNumber(void); - - magic = PyMarshal_ReadLongFromFile(fp); - if (magic != PyImport_GetMagicNumber()) { - PyErr_SetString(PyExc_RuntimeError, - "Bad magic number in .pyc file"); - return NULL; - } - (void) PyMarshal_ReadLongFromFile(fp); - v = PyMarshal_ReadLastObjectFromFile(fp); - fclose(fp); - if (v == NULL || !PyCode_Check(v)) { - Py_XDECREF(v); - PyErr_SetString(PyExc_RuntimeError, - "Bad code object in .pyc file"); - return NULL; - } - co = (PyCodeObject *)v; - v = PyEval_EvalCode(co, globals, locals); - if (v && flags) - flags->cf_flags |= (co->co_flags & PyCF_MASK); - Py_DECREF(co); - return v; + PyCodeObject *co; + PyObject *v; + long magic; + long PyImport_GetMagicNumber(void); + + magic = PyMarshal_ReadLongFromFile(fp); + if (magic != PyImport_GetMagicNumber()) { + PyErr_SetString(PyExc_RuntimeError, + "Bad magic number in .pyc file"); + return NULL; + } + (void) PyMarshal_ReadLongFromFile(fp); + v = PyMarshal_ReadLastObjectFromFile(fp); + fclose(fp); + if (v == NULL || !PyCode_Check(v)) { + Py_XDECREF(v); + PyErr_SetString(PyExc_RuntimeError, + "Bad code object in .pyc file"); + return NULL; + } + co = (PyCodeObject *)v; + v = PyEval_EvalCode(co, globals, locals); + if (v && flags) + flags->cf_flags |= (co->co_flags & PyCF_MASK); + Py_DECREF(co); + return v; } PyObject * Py_CompileStringFlags(const char *str, const char *filename, int start, - PyCompilerFlags *flags) + PyCompilerFlags *flags) { - PyCodeObject *co; - mod_ty mod; - PyArena *arena = PyArena_New(); - if (arena == NULL) - return NULL; - - mod = PyParser_ASTFromString(str, filename, start, flags, arena); - if (mod == NULL) { - PyArena_Free(arena); - return NULL; - } - if (flags && (flags->cf_flags & PyCF_ONLY_AST)) { - PyObject *result = PyAST_mod2obj(mod); - PyArena_Free(arena); - return result; - } - co = PyAST_Compile(mod, filename, flags, arena); - PyArena_Free(arena); - return (PyObject *)co; + PyCodeObject *co; + mod_ty mod; + PyArena *arena = PyArena_New(); + if (arena == NULL) + return NULL; + + mod = PyParser_ASTFromString(str, filename, start, flags, arena); + if (mod == NULL) { + PyArena_Free(arena); + return NULL; + } + if (flags && (flags->cf_flags & PyCF_ONLY_AST)) { + PyObject *result = PyAST_mod2obj(mod); + PyArena_Free(arena); + return result; + } + co = PyAST_Compile(mod, filename, flags, arena); + PyArena_Free(arena); + return (PyObject *)co; } struct symtable * Py_SymtableString(const char *str, const char *filename, int start) { - struct symtable *st; - mod_ty mod; - PyCompilerFlags flags; - PyArena *arena = PyArena_New(); - if (arena == NULL) - return NULL; - - flags.cf_flags = 0; - mod = PyParser_ASTFromString(str, filename, start, &flags, arena); - if (mod == NULL) { - PyArena_Free(arena); - return NULL; - } - st = PySymtable_Build(mod, filename, 0); - PyArena_Free(arena); - return st; + struct symtable *st; + mod_ty mod; + PyCompilerFlags flags; + PyArena *arena = PyArena_New(); + if (arena == NULL) + return NULL; + + flags.cf_flags = 0; + mod = PyParser_ASTFromString(str, filename, start, &flags, arena); + if (mod == NULL) { + PyArena_Free(arena); + return NULL; + } + st = PySymtable_Build(mod, filename, 0); + PyArena_Free(arena); + return st; } /* Preferred access to parser is through AST. */ mod_ty PyParser_ASTFromString(const char *s, const char *filename, int start, - PyCompilerFlags *flags, PyArena *arena) + PyCompilerFlags *flags, PyArena *arena) { - mod_ty mod; - PyCompilerFlags localflags; - perrdetail err; - int iflags = PARSER_FLAGS(flags); - - node *n = PyParser_ParseStringFlagsFilenameEx(s, filename, - &_PyParser_Grammar, start, &err, - &iflags); - if (flags == NULL) { - localflags.cf_flags = 0; - flags = &localflags; - } - if (n) { - flags->cf_flags |= iflags & PyCF_MASK; - mod = PyAST_FromNode(n, flags, filename, arena); - PyNode_Free(n); - return mod; - } - else { - err_input(&err); - return NULL; - } + mod_ty mod; + PyCompilerFlags localflags; + perrdetail err; + int iflags = PARSER_FLAGS(flags); + + node *n = PyParser_ParseStringFlagsFilenameEx(s, filename, + &_PyParser_Grammar, start, &err, + &iflags); + if (flags == NULL) { + localflags.cf_flags = 0; + flags = &localflags; + } + if (n) { + flags->cf_flags |= iflags & PyCF_MASK; + mod = PyAST_FromNode(n, flags, filename, arena); + PyNode_Free(n); + return mod; + } + else { + err_input(&err); + return NULL; + } } mod_ty PyParser_ASTFromFile(FILE *fp, const char *filename, const char* enc, - int start, char *ps1, - char *ps2, PyCompilerFlags *flags, int *errcode, - PyArena *arena) -{ - mod_ty mod; - PyCompilerFlags localflags; - perrdetail err; - int iflags = PARSER_FLAGS(flags); - - node *n = PyParser_ParseFileFlagsEx(fp, filename, enc, - &_PyParser_Grammar, - start, ps1, ps2, &err, &iflags); - if (flags == NULL) { - localflags.cf_flags = 0; - flags = &localflags; - } - if (n) { - flags->cf_flags |= iflags & PyCF_MASK; - mod = PyAST_FromNode(n, flags, filename, arena); - PyNode_Free(n); - return mod; - } - else { - err_input(&err); - if (errcode) - *errcode = err.error; - return NULL; - } + int start, char *ps1, + char *ps2, PyCompilerFlags *flags, int *errcode, + PyArena *arena) +{ + mod_ty mod; + PyCompilerFlags localflags; + perrdetail err; + int iflags = PARSER_FLAGS(flags); + + node *n = PyParser_ParseFileFlagsEx(fp, filename, enc, + &_PyParser_Grammar, + start, ps1, ps2, &err, &iflags); + if (flags == NULL) { + localflags.cf_flags = 0; + flags = &localflags; + } + if (n) { + flags->cf_flags |= iflags & PyCF_MASK; + mod = PyAST_FromNode(n, flags, filename, arena); + PyNode_Free(n); + return mod; + } + else { + err_input(&err); + if (errcode) + *errcode = err.error; + return NULL; + } } /* Simplified interface to parsefile -- return node or set exception */ @@ -1848,14 +1848,14 @@ node * PyParser_SimpleParseFileFlags(FILE *fp, const char *filename, int start, int flags) { - perrdetail err; - node *n = PyParser_ParseFileFlags(fp, filename, NULL, - &_PyParser_Grammar, - start, NULL, NULL, &err, flags); - if (n == NULL) - err_input(&err); + perrdetail err; + node *n = PyParser_ParseFileFlags(fp, filename, NULL, + &_PyParser_Grammar, + start, NULL, NULL, &err, flags); + if (n == NULL) + err_input(&err); - return n; + return n; } /* Simplified interface to parsestring -- return node or set exception */ @@ -1863,30 +1863,30 @@ node * PyParser_SimpleParseStringFlags(const char *str, int start, int flags) { - perrdetail err; - node *n = PyParser_ParseStringFlags(str, &_PyParser_Grammar, - start, &err, flags); - if (n == NULL) - err_input(&err); - return n; + perrdetail err; + node *n = PyParser_ParseStringFlags(str, &_PyParser_Grammar, + start, &err, flags); + if (n == NULL) + err_input(&err); + return n; } node * PyParser_SimpleParseStringFlagsFilename(const char *str, const char *filename, - int start, int flags) + int start, int flags) { - perrdetail err; - node *n = PyParser_ParseStringFlagsFilename(str, filename, - &_PyParser_Grammar, start, &err, flags); - if (n == NULL) - err_input(&err); - return n; + perrdetail err; + node *n = PyParser_ParseStringFlagsFilename(str, filename, + &_PyParser_Grammar, start, &err, flags); + if (n == NULL) + err_input(&err); + return n; } node * PyParser_SimpleParseStringFilename(const char *str, const char *filename, int start) { - return PyParser_SimpleParseStringFlagsFilename(str, filename, start, 0); + return PyParser_SimpleParseStringFlagsFilename(str, filename, start, 0); } /* May want to move a more generalized form of this to parsetok.c or @@ -1895,7 +1895,7 @@ void PyParser_SetError(perrdetail *err) { - err_input(err); + err_input(err); } /* Set the error appropriate to the given input error code (see errcode.h) */ @@ -1903,111 +1903,111 @@ static void err_input(perrdetail *err) { - PyObject *v, *w, *errtype, *errtext; - PyObject* u = NULL; - char *msg = NULL; - errtype = PyExc_SyntaxError; - switch (err->error) { - case E_ERROR: - return; - case E_SYNTAX: - errtype = PyExc_IndentationError; - if (err->expected == INDENT) - msg = "expected an indented block"; - else if (err->token == INDENT) - msg = "unexpected indent"; - else if (err->token == DEDENT) - msg = "unexpected unindent"; - else { - errtype = PyExc_SyntaxError; - msg = "invalid syntax"; - } - break; - case E_TOKEN: - msg = "invalid token"; - break; - case E_EOFS: - msg = "EOF while scanning triple-quoted string literal"; - break; - case E_EOLS: - msg = "EOL while scanning string literal"; - break; - case E_INTR: - if (!PyErr_Occurred()) - PyErr_SetNone(PyExc_KeyboardInterrupt); - goto cleanup; - case E_NOMEM: - PyErr_NoMemory(); - goto cleanup; - case E_EOF: - msg = "unexpected EOF while parsing"; - break; - case E_TABSPACE: - errtype = PyExc_TabError; - msg = "inconsistent use of tabs and spaces in indentation"; - break; - case E_OVERFLOW: - msg = "expression too long"; - break; - case E_DEDENT: - errtype = PyExc_IndentationError; - msg = "unindent does not match any outer indentation level"; - break; - case E_TOODEEP: - errtype = PyExc_IndentationError; - msg = "too many levels of indentation"; - break; - case E_DECODE: { - PyObject *type, *value, *tb; - PyErr_Fetch(&type, &value, &tb); - if (value != NULL) { - u = PyObject_Str(value); - if (u != NULL) { - msg = _PyUnicode_AsString(u); - } - } - if (msg == NULL) - msg = "unknown decode error"; - Py_XDECREF(type); - Py_XDECREF(value); - Py_XDECREF(tb); - break; - } - case E_LINECONT: - msg = "unexpected character after line continuation character"; - break; - - case E_IDENTIFIER: - msg = "invalid character in identifier"; - break; - default: - fprintf(stderr, "error=%d\n", err->error); - msg = "unknown parsing error"; - break; - } - /* err->text may not be UTF-8 in case of decoding errors. - Explicitly convert to an object. */ - if (!err->text) { - errtext = Py_None; - Py_INCREF(Py_None); - } else { - errtext = PyUnicode_DecodeUTF8(err->text, strlen(err->text), - "replace"); - } - v = Py_BuildValue("(ziiN)", err->filename, - err->lineno, err->offset, errtext); - w = NULL; - if (v != NULL) - w = Py_BuildValue("(sO)", msg, v); - Py_XDECREF(u); - Py_XDECREF(v); - PyErr_SetObject(errtype, w); - Py_XDECREF(w); + PyObject *v, *w, *errtype, *errtext; + PyObject* u = NULL; + char *msg = NULL; + errtype = PyExc_SyntaxError; + switch (err->error) { + case E_ERROR: + return; + case E_SYNTAX: + errtype = PyExc_IndentationError; + if (err->expected == INDENT) + msg = "expected an indented block"; + else if (err->token == INDENT) + msg = "unexpected indent"; + else if (err->token == DEDENT) + msg = "unexpected unindent"; + else { + errtype = PyExc_SyntaxError; + msg = "invalid syntax"; + } + break; + case E_TOKEN: + msg = "invalid token"; + break; + case E_EOFS: + msg = "EOF while scanning triple-quoted string literal"; + break; + case E_EOLS: + msg = "EOL while scanning string literal"; + break; + case E_INTR: + if (!PyErr_Occurred()) + PyErr_SetNone(PyExc_KeyboardInterrupt); + goto cleanup; + case E_NOMEM: + PyErr_NoMemory(); + goto cleanup; + case E_EOF: + msg = "unexpected EOF while parsing"; + break; + case E_TABSPACE: + errtype = PyExc_TabError; + msg = "inconsistent use of tabs and spaces in indentation"; + break; + case E_OVERFLOW: + msg = "expression too long"; + break; + case E_DEDENT: + errtype = PyExc_IndentationError; + msg = "unindent does not match any outer indentation level"; + break; + case E_TOODEEP: + errtype = PyExc_IndentationError; + msg = "too many levels of indentation"; + break; + case E_DECODE: { + PyObject *type, *value, *tb; + PyErr_Fetch(&type, &value, &tb); + if (value != NULL) { + u = PyObject_Str(value); + if (u != NULL) { + msg = _PyUnicode_AsString(u); + } + } + if (msg == NULL) + msg = "unknown decode error"; + Py_XDECREF(type); + Py_XDECREF(value); + Py_XDECREF(tb); + break; + } + case E_LINECONT: + msg = "unexpected character after line continuation character"; + break; + + case E_IDENTIFIER: + msg = "invalid character in identifier"; + break; + default: + fprintf(stderr, "error=%d\n", err->error); + msg = "unknown parsing error"; + break; + } + /* err->text may not be UTF-8 in case of decoding errors. + Explicitly convert to an object. */ + if (!err->text) { + errtext = Py_None; + Py_INCREF(Py_None); + } else { + errtext = PyUnicode_DecodeUTF8(err->text, strlen(err->text), + "replace"); + } + v = Py_BuildValue("(ziiN)", err->filename, + err->lineno, err->offset, errtext); + w = NULL; + if (v != NULL) + w = Py_BuildValue("(sO)", msg, v); + Py_XDECREF(u); + Py_XDECREF(v); + PyErr_SetObject(errtype, w); + Py_XDECREF(w); cleanup: - if (err->text != NULL) { - PyObject_FREE(err->text); - err->text = NULL; - } + if (err->text != NULL) { + PyObject_FREE(err->text); + err->text = NULL; + } } /* Print fatal error message and abort */ @@ -2015,32 +2015,32 @@ void Py_FatalError(const char *msg) { - fprintf(stderr, "Fatal Python error: %s\n", msg); - fflush(stderr); /* it helps in Windows debug build */ - if (PyErr_Occurred()) { - PyErr_Print(); - } + fprintf(stderr, "Fatal Python error: %s\n", msg); + fflush(stderr); /* it helps in Windows debug build */ + if (PyErr_Occurred()) { + PyErr_Print(); + } #ifdef MS_WINDOWS - { - size_t len = strlen(msg); - WCHAR* buffer; - size_t i; - - /* Convert the message to wchar_t. This uses a simple one-to-one - conversion, assuming that the this error message actually uses ASCII - only. If this ceases to be true, we will have to convert. */ - buffer = alloca( (len+1) * (sizeof *buffer)); - for( i=0; i<=len; ++i) - buffer[i] = msg[i]; - OutputDebugStringW(L"Fatal Python error: "); - OutputDebugStringW(buffer); - OutputDebugStringW(L"\n"); - } + { + size_t len = strlen(msg); + WCHAR* buffer; + size_t i; + + /* Convert the message to wchar_t. This uses a simple one-to-one + conversion, assuming that the this error message actually uses ASCII + only. If this ceases to be true, we will have to convert. */ + buffer = alloca( (len+1) * (sizeof *buffer)); + for( i=0; i<=len; ++i) + buffer[i] = msg[i]; + OutputDebugStringW(L"Fatal Python error: "); + OutputDebugStringW(buffer); + OutputDebugStringW(L"\n"); + } #ifdef _DEBUG - DebugBreak(); + DebugBreak(); #endif #endif /* MS_WINDOWS */ - abort(); + abort(); } /* Clean up and exit */ @@ -2053,17 +2053,17 @@ /* For the atexit module. */ void _Py_PyAtExit(void (*func)(void)) { - pyexitfunc = func; + pyexitfunc = func; } static void call_py_exitfuncs(void) { - if (pyexitfunc == NULL) - return; + if (pyexitfunc == NULL) + return; - (*pyexitfunc)(); - PyErr_Clear(); + (*pyexitfunc)(); + PyErr_Clear(); } /* Wait until threading._shutdown completes, provided @@ -2074,23 +2074,23 @@ wait_for_thread_shutdown(void) { #ifdef WITH_THREAD - PyObject *result; - PyThreadState *tstate = PyThreadState_GET(); - PyObject *threading = PyMapping_GetItemString(tstate->interp->modules, - "threading"); - if (threading == NULL) { - /* threading not imported */ - PyErr_Clear(); - return; - } - result = PyObject_CallMethod(threading, "_shutdown", ""); - if (result == NULL) { - PyErr_WriteUnraisable(threading); - } - else { - Py_DECREF(result); - } - Py_DECREF(threading); + PyObject *result; + PyThreadState *tstate = PyThreadState_GET(); + PyObject *threading = PyMapping_GetItemString(tstate->interp->modules, + "threading"); + if (threading == NULL) { + /* threading not imported */ + PyErr_Clear(); + return; + } + result = PyObject_CallMethod(threading, "_shutdown", ""); + if (result == NULL) { + PyErr_WriteUnraisable(threading); + } + else { + Py_DECREF(result); + } + Py_DECREF(threading); #endif } @@ -2100,43 +2100,43 @@ int Py_AtExit(void (*func)(void)) { - if (nexitfuncs >= NEXITFUNCS) - return -1; - exitfuncs[nexitfuncs++] = func; - return 0; + if (nexitfuncs >= NEXITFUNCS) + return -1; + exitfuncs[nexitfuncs++] = func; + return 0; } static void call_ll_exitfuncs(void) { - while (nexitfuncs > 0) - (*exitfuncs[--nexitfuncs])(); + while (nexitfuncs > 0) + (*exitfuncs[--nexitfuncs])(); - fflush(stdout); - fflush(stderr); + fflush(stdout); + fflush(stderr); } void Py_Exit(int sts) { - Py_Finalize(); + Py_Finalize(); - exit(sts); + exit(sts); } static void initsigs(void) { #ifdef SIGPIPE - PyOS_setsig(SIGPIPE, SIG_IGN); + PyOS_setsig(SIGPIPE, SIG_IGN); #endif #ifdef SIGXFZ - PyOS_setsig(SIGXFZ, SIG_IGN); + PyOS_setsig(SIGXFZ, SIG_IGN); #endif #ifdef SIGXFSZ - PyOS_setsig(SIGXFSZ, SIG_IGN); + PyOS_setsig(SIGXFSZ, SIG_IGN); #endif - PyOS_InitInterrupts(); /* May imply initsignal() */ + PyOS_InitInterrupts(); /* May imply initsignal() */ } @@ -2149,13 +2149,13 @@ int Py_FdIsInteractive(FILE *fp, const char *filename) { - if (isatty((int)fileno(fp))) - return 1; - if (!Py_InteractiveFlag) - return 0; - return (filename == NULL) || - (strcmp(filename, "") == 0) || - (strcmp(filename, "???") == 0); + if (isatty((int)fileno(fp))) + return 1; + if (!Py_InteractiveFlag) + return 0; + return (filename == NULL) || + (strcmp(filename, "") == 0) || + (strcmp(filename, "???") == 0); } @@ -2173,21 +2173,21 @@ int PyOS_CheckStack(void) { - __try { - /* alloca throws a stack overflow exception if there's - not enough space left on the stack */ - alloca(PYOS_STACK_MARGIN * sizeof(void*)); - return 0; - } __except (GetExceptionCode() == STATUS_STACK_OVERFLOW ? - EXCEPTION_EXECUTE_HANDLER : - EXCEPTION_CONTINUE_SEARCH) { - int errcode = _resetstkoflw(); - if (errcode == 0) - { - Py_FatalError("Could not reset the stack!"); - } - } - return 1; + __try { + /* alloca throws a stack overflow exception if there's + not enough space left on the stack */ + alloca(PYOS_STACK_MARGIN * sizeof(void*)); + return 0; + } __except (GetExceptionCode() == STATUS_STACK_OVERFLOW ? + EXCEPTION_EXECUTE_HANDLER : + EXCEPTION_CONTINUE_SEARCH) { + int errcode = _resetstkoflw(); + if (errcode == 0) + { + Py_FatalError("Could not reset the stack!"); + } + } + return 1; } #endif /* WIN32 && _MSC_VER */ @@ -2203,33 +2203,33 @@ PyOS_getsig(int sig) { #ifdef HAVE_SIGACTION - struct sigaction context; - if (sigaction(sig, NULL, &context) == -1) - return SIG_ERR; - return context.sa_handler; + struct sigaction context; + if (sigaction(sig, NULL, &context) == -1) + return SIG_ERR; + return context.sa_handler; #else - PyOS_sighandler_t handler; + PyOS_sighandler_t handler; /* Special signal handling for the secure CRT in Visual Studio 2005 */ #if defined(_MSC_VER) && _MSC_VER >= 1400 - switch (sig) { - /* Only these signals are valid */ - case SIGINT: - case SIGILL: - case SIGFPE: - case SIGSEGV: - case SIGTERM: - case SIGBREAK: - case SIGABRT: - break; - /* Don't call signal() with other values or it will assert */ - default: - return SIG_ERR; - } + switch (sig) { + /* Only these signals are valid */ + case SIGINT: + case SIGILL: + case SIGFPE: + case SIGSEGV: + case SIGTERM: + case SIGBREAK: + case SIGABRT: + break; + /* Don't call signal() with other values or it will assert */ + default: + return SIG_ERR; + } #endif /* _MSC_VER && _MSC_VER >= 1400 */ - handler = signal(sig, SIG_IGN); - if (handler != SIG_ERR) - signal(sig, handler); - return handler; + handler = signal(sig, SIG_IGN); + if (handler != SIG_ERR) + signal(sig, handler); + return handler; #endif } @@ -2237,24 +2237,24 @@ PyOS_setsig(int sig, PyOS_sighandler_t handler) { #ifdef HAVE_SIGACTION - /* Some code in Modules/signalmodule.c depends on sigaction() being - * used here if HAVE_SIGACTION is defined. Fix that if this code - * changes to invalidate that assumption. - */ - struct sigaction context, ocontext; - context.sa_handler = handler; - sigemptyset(&context.sa_mask); - context.sa_flags = 0; - if (sigaction(sig, &context, &ocontext) == -1) - return SIG_ERR; - return ocontext.sa_handler; + /* Some code in Modules/signalmodule.c depends on sigaction() being + * used here if HAVE_SIGACTION is defined. Fix that if this code + * changes to invalidate that assumption. + */ + struct sigaction context, ocontext; + context.sa_handler = handler; + sigemptyset(&context.sa_mask); + context.sa_flags = 0; + if (sigaction(sig, &context, &ocontext) == -1) + return SIG_ERR; + return ocontext.sa_handler; #else - PyOS_sighandler_t oldhandler; - oldhandler = signal(sig, handler); + PyOS_sighandler_t oldhandler; + oldhandler = signal(sig, handler); #ifdef HAVE_SIGINTERRUPT - siginterrupt(sig, 1); + siginterrupt(sig, 1); #endif - return oldhandler; + return oldhandler; #endif } @@ -2264,71 +2264,71 @@ PyAPI_FUNC(node *) PyParser_SimpleParseFile(FILE *fp, const char *filename, int start) { - return PyParser_SimpleParseFileFlags(fp, filename, start, 0); + return PyParser_SimpleParseFileFlags(fp, filename, start, 0); } #undef PyParser_SimpleParseString PyAPI_FUNC(node *) PyParser_SimpleParseString(const char *str, int start) { - return PyParser_SimpleParseStringFlags(str, start, 0); + return PyParser_SimpleParseStringFlags(str, start, 0); } #undef PyRun_AnyFile PyAPI_FUNC(int) PyRun_AnyFile(FILE *fp, const char *name) { - return PyRun_AnyFileExFlags(fp, name, 0, NULL); + return PyRun_AnyFileExFlags(fp, name, 0, NULL); } #undef PyRun_AnyFileEx PyAPI_FUNC(int) PyRun_AnyFileEx(FILE *fp, const char *name, int closeit) { - return PyRun_AnyFileExFlags(fp, name, closeit, NULL); + return PyRun_AnyFileExFlags(fp, name, closeit, NULL); } #undef PyRun_AnyFileFlags PyAPI_FUNC(int) PyRun_AnyFileFlags(FILE *fp, const char *name, PyCompilerFlags *flags) { - return PyRun_AnyFileExFlags(fp, name, 0, flags); + return PyRun_AnyFileExFlags(fp, name, 0, flags); } #undef PyRun_File PyAPI_FUNC(PyObject *) PyRun_File(FILE *fp, const char *p, int s, PyObject *g, PyObject *l) { - return PyRun_FileExFlags(fp, p, s, g, l, 0, NULL); + return PyRun_FileExFlags(fp, p, s, g, l, 0, NULL); } #undef PyRun_FileEx PyAPI_FUNC(PyObject *) PyRun_FileEx(FILE *fp, const char *p, int s, PyObject *g, PyObject *l, int c) { - return PyRun_FileExFlags(fp, p, s, g, l, c, NULL); + return PyRun_FileExFlags(fp, p, s, g, l, c, NULL); } #undef PyRun_FileFlags PyAPI_FUNC(PyObject *) PyRun_FileFlags(FILE *fp, const char *p, int s, PyObject *g, PyObject *l, - PyCompilerFlags *flags) + PyCompilerFlags *flags) { - return PyRun_FileExFlags(fp, p, s, g, l, 0, flags); + return PyRun_FileExFlags(fp, p, s, g, l, 0, flags); } #undef PyRun_SimpleFile PyAPI_FUNC(int) PyRun_SimpleFile(FILE *f, const char *p) { - return PyRun_SimpleFileExFlags(f, p, 0, NULL); + return PyRun_SimpleFileExFlags(f, p, 0, NULL); } #undef PyRun_SimpleFileEx PyAPI_FUNC(int) PyRun_SimpleFileEx(FILE *f, const char *p, int c) { - return PyRun_SimpleFileExFlags(f, p, c, NULL); + return PyRun_SimpleFileExFlags(f, p, c, NULL); } @@ -2336,35 +2336,35 @@ PyAPI_FUNC(PyObject *) PyRun_String(const char *str, int s, PyObject *g, PyObject *l) { - return PyRun_StringFlags(str, s, g, l, NULL); + return PyRun_StringFlags(str, s, g, l, NULL); } #undef PyRun_SimpleString PyAPI_FUNC(int) PyRun_SimpleString(const char *s) { - return PyRun_SimpleStringFlags(s, NULL); + return PyRun_SimpleStringFlags(s, NULL); } #undef Py_CompileString PyAPI_FUNC(PyObject *) Py_CompileString(const char *str, const char *p, int s) { - return Py_CompileStringFlags(str, p, s, NULL); + return Py_CompileStringFlags(str, p, s, NULL); } #undef PyRun_InteractiveOne PyAPI_FUNC(int) PyRun_InteractiveOne(FILE *f, const char *p) { - return PyRun_InteractiveOneFlags(f, p, NULL); + return PyRun_InteractiveOneFlags(f, p, NULL); } #undef PyRun_InteractiveLoop PyAPI_FUNC(int) PyRun_InteractiveLoop(FILE *f, const char *p) { - return PyRun_InteractiveLoopFlags(f, p, NULL); + return PyRun_InteractiveLoopFlags(f, p, NULL); } #ifdef __cplusplus Modified: python/branches/release31-maint/Python/structmember.c ============================================================================== --- python/branches/release31-maint/Python/structmember.c (original) +++ python/branches/release31-maint/Python/structmember.c Sun May 9 18:14:21 2010 @@ -8,293 +8,293 @@ PyObject * PyMember_GetOne(const char *addr, PyMemberDef *l) { - PyObject *v; + PyObject *v; - addr += l->offset; - switch (l->type) { - case T_BOOL: - v = PyBool_FromLong(*(char*)addr); - break; - case T_BYTE: - v = PyLong_FromLong(*(char*)addr); - break; - case T_UBYTE: - v = PyLong_FromUnsignedLong(*(unsigned char*)addr); - break; - case T_SHORT: - v = PyLong_FromLong(*(short*)addr); - break; - case T_USHORT: - v = PyLong_FromUnsignedLong(*(unsigned short*)addr); - break; - case T_INT: - v = PyLong_FromLong(*(int*)addr); - break; - case T_UINT: - v = PyLong_FromUnsignedLong(*(unsigned int*)addr); - break; - case T_LONG: - v = PyLong_FromLong(*(long*)addr); - break; - case T_ULONG: - v = PyLong_FromUnsignedLong(*(unsigned long*)addr); - break; - case T_PYSSIZET: - v = PyLong_FromSsize_t(*(Py_ssize_t*)addr); - break; - case T_FLOAT: - v = PyFloat_FromDouble((double)*(float*)addr); - break; - case T_DOUBLE: - v = PyFloat_FromDouble(*(double*)addr); - break; - case T_STRING: - if (*(char**)addr == NULL) { - Py_INCREF(Py_None); - v = Py_None; - } - else - v = PyUnicode_FromString(*(char**)addr); - break; - case T_STRING_INPLACE: - v = PyUnicode_FromString((char*)addr); - break; - case T_CHAR: - v = PyUnicode_FromStringAndSize((char*)addr, 1); - break; - case T_OBJECT: - v = *(PyObject **)addr; - if (v == NULL) - v = Py_None; - Py_INCREF(v); - break; - case T_OBJECT_EX: - v = *(PyObject **)addr; - if (v == NULL) - PyErr_SetString(PyExc_AttributeError, l->name); - Py_XINCREF(v); - break; + addr += l->offset; + switch (l->type) { + case T_BOOL: + v = PyBool_FromLong(*(char*)addr); + break; + case T_BYTE: + v = PyLong_FromLong(*(char*)addr); + break; + case T_UBYTE: + v = PyLong_FromUnsignedLong(*(unsigned char*)addr); + break; + case T_SHORT: + v = PyLong_FromLong(*(short*)addr); + break; + case T_USHORT: + v = PyLong_FromUnsignedLong(*(unsigned short*)addr); + break; + case T_INT: + v = PyLong_FromLong(*(int*)addr); + break; + case T_UINT: + v = PyLong_FromUnsignedLong(*(unsigned int*)addr); + break; + case T_LONG: + v = PyLong_FromLong(*(long*)addr); + break; + case T_ULONG: + v = PyLong_FromUnsignedLong(*(unsigned long*)addr); + break; + case T_PYSSIZET: + v = PyLong_FromSsize_t(*(Py_ssize_t*)addr); + break; + case T_FLOAT: + v = PyFloat_FromDouble((double)*(float*)addr); + break; + case T_DOUBLE: + v = PyFloat_FromDouble(*(double*)addr); + break; + case T_STRING: + if (*(char**)addr == NULL) { + Py_INCREF(Py_None); + v = Py_None; + } + else + v = PyUnicode_FromString(*(char**)addr); + break; + case T_STRING_INPLACE: + v = PyUnicode_FromString((char*)addr); + break; + case T_CHAR: + v = PyUnicode_FromStringAndSize((char*)addr, 1); + break; + case T_OBJECT: + v = *(PyObject **)addr; + if (v == NULL) + v = Py_None; + Py_INCREF(v); + break; + case T_OBJECT_EX: + v = *(PyObject **)addr; + if (v == NULL) + PyErr_SetString(PyExc_AttributeError, l->name); + Py_XINCREF(v); + break; #ifdef HAVE_LONG_LONG - case T_LONGLONG: - v = PyLong_FromLongLong(*(PY_LONG_LONG *)addr); - break; - case T_ULONGLONG: - v = PyLong_FromUnsignedLongLong(*(unsigned PY_LONG_LONG *)addr); - break; + case T_LONGLONG: + v = PyLong_FromLongLong(*(PY_LONG_LONG *)addr); + break; + case T_ULONGLONG: + v = PyLong_FromUnsignedLongLong(*(unsigned PY_LONG_LONG *)addr); + break; #endif /* HAVE_LONG_LONG */ - case T_NONE: - v = Py_None; - Py_INCREF(v); - break; - default: - PyErr_SetString(PyExc_SystemError, "bad memberdescr type"); - v = NULL; - } - return v; + case T_NONE: + v = Py_None; + Py_INCREF(v); + break; + default: + PyErr_SetString(PyExc_SystemError, "bad memberdescr type"); + v = NULL; + } + return v; } -#define WARN(msg) \ - do { \ - if (PyErr_WarnEx(PyExc_RuntimeWarning, msg, 1) < 0) \ - return -1; \ +#define WARN(msg) \ + do { \ + if (PyErr_WarnEx(PyExc_RuntimeWarning, msg, 1) < 0) \ + return -1; \ } while (0) int PyMember_SetOne(char *addr, PyMemberDef *l, PyObject *v) { - PyObject *oldv; + PyObject *oldv; - addr += l->offset; + addr += l->offset; - if ((l->flags & READONLY)) - { - PyErr_SetString(PyExc_AttributeError, "readonly attribute"); - return -1; - } - if (v == NULL) { - if (l->type == T_OBJECT_EX) { - /* Check if the attribute is set. */ - if (*(PyObject **)addr == NULL) { - PyErr_SetString(PyExc_AttributeError, l->name); - return -1; - } - } - else if (l->type != T_OBJECT) { - PyErr_SetString(PyExc_TypeError, - "can't delete numeric/char attribute"); - return -1; - } - } - switch (l->type) { - case T_BOOL:{ - if (!PyBool_Check(v)) { - PyErr_SetString(PyExc_TypeError, - "attribute value type must be bool"); - return -1; - } - if (v == Py_True) - *(char*)addr = (char) 1; - else - *(char*)addr = (char) 0; - break; - } - case T_BYTE:{ - long long_val = PyLong_AsLong(v); - if ((long_val == -1) && PyErr_Occurred()) - return -1; - *(char*)addr = (char)long_val; - /* XXX: For compatibility, only warn about truncations - for now. */ - if ((long_val > CHAR_MAX) || (long_val < CHAR_MIN)) - WARN("Truncation of value to char"); - break; - } - case T_UBYTE:{ - long long_val = PyLong_AsLong(v); - if ((long_val == -1) && PyErr_Occurred()) - return -1; - *(unsigned char*)addr = (unsigned char)long_val; - if ((long_val > UCHAR_MAX) || (long_val < 0)) - WARN("Truncation of value to unsigned char"); - break; - } - case T_SHORT:{ - long long_val = PyLong_AsLong(v); - if ((long_val == -1) && PyErr_Occurred()) - return -1; - *(short*)addr = (short)long_val; - if ((long_val > SHRT_MAX) || (long_val < SHRT_MIN)) - WARN("Truncation of value to short"); - break; - } - case T_USHORT:{ - long long_val = PyLong_AsLong(v); - if ((long_val == -1) && PyErr_Occurred()) - return -1; - *(unsigned short*)addr = (unsigned short)long_val; - if ((long_val > USHRT_MAX) || (long_val < 0)) - WARN("Truncation of value to unsigned short"); - break; - } - case T_INT:{ - long long_val = PyLong_AsLong(v); - if ((long_val == -1) && PyErr_Occurred()) - return -1; - *(int *)addr = (int)long_val; - if ((long_val > INT_MAX) || (long_val < INT_MIN)) - WARN("Truncation of value to int"); - break; - } - case T_UINT:{ - unsigned long ulong_val = PyLong_AsUnsignedLong(v); - if ((ulong_val == (unsigned long)-1) && PyErr_Occurred()) { - /* XXX: For compatibility, accept negative int values - as well. */ - PyErr_Clear(); - ulong_val = PyLong_AsLong(v); - if ((ulong_val == (unsigned long)-1) && - PyErr_Occurred()) - return -1; - *(unsigned int *)addr = (unsigned int)ulong_val; - WARN("Writing negative value into unsigned field"); - } else - *(unsigned int *)addr = (unsigned int)ulong_val; - if (ulong_val > UINT_MAX) - WARN("Truncation of value to unsigned int"); - break; - } - case T_LONG:{ - *(long*)addr = PyLong_AsLong(v); - if ((*(long*)addr == -1) && PyErr_Occurred()) - return -1; - break; - } - case T_ULONG:{ - *(unsigned long*)addr = PyLong_AsUnsignedLong(v); - if ((*(unsigned long*)addr == (unsigned long)-1) - && PyErr_Occurred()) { - /* XXX: For compatibility, accept negative int values - as well. */ - PyErr_Clear(); - *(unsigned long*)addr = PyLong_AsLong(v); - if ((*(unsigned long*)addr == (unsigned long)-1) - && PyErr_Occurred()) - return -1; - WARN("Writing negative value into unsigned field"); - } - break; - } - case T_PYSSIZET:{ - *(Py_ssize_t*)addr = PyLong_AsSsize_t(v); - if ((*(Py_ssize_t*)addr == (Py_ssize_t)-1) - && PyErr_Occurred()) - return -1; - break; - } - case T_FLOAT:{ - double double_val = PyFloat_AsDouble(v); - if ((double_val == -1) && PyErr_Occurred()) - return -1; - *(float*)addr = (float)double_val; - break; - } - case T_DOUBLE: - *(double*)addr = PyFloat_AsDouble(v); - if ((*(double*)addr == -1) && PyErr_Occurred()) - return -1; - break; - case T_OBJECT: - case T_OBJECT_EX: - Py_XINCREF(v); - oldv = *(PyObject **)addr; - *(PyObject **)addr = v; - Py_XDECREF(oldv); - break; - case T_CHAR: { - char *string; - Py_ssize_t len; + if ((l->flags & READONLY)) + { + PyErr_SetString(PyExc_AttributeError, "readonly attribute"); + return -1; + } + if (v == NULL) { + if (l->type == T_OBJECT_EX) { + /* Check if the attribute is set. */ + if (*(PyObject **)addr == NULL) { + PyErr_SetString(PyExc_AttributeError, l->name); + return -1; + } + } + else if (l->type != T_OBJECT) { + PyErr_SetString(PyExc_TypeError, + "can't delete numeric/char attribute"); + return -1; + } + } + switch (l->type) { + case T_BOOL:{ + if (!PyBool_Check(v)) { + PyErr_SetString(PyExc_TypeError, + "attribute value type must be bool"); + return -1; + } + if (v == Py_True) + *(char*)addr = (char) 1; + else + *(char*)addr = (char) 0; + break; + } + case T_BYTE:{ + long long_val = PyLong_AsLong(v); + if ((long_val == -1) && PyErr_Occurred()) + return -1; + *(char*)addr = (char)long_val; + /* XXX: For compatibility, only warn about truncations + for now. */ + if ((long_val > CHAR_MAX) || (long_val < CHAR_MIN)) + WARN("Truncation of value to char"); + break; + } + case T_UBYTE:{ + long long_val = PyLong_AsLong(v); + if ((long_val == -1) && PyErr_Occurred()) + return -1; + *(unsigned char*)addr = (unsigned char)long_val; + if ((long_val > UCHAR_MAX) || (long_val < 0)) + WARN("Truncation of value to unsigned char"); + break; + } + case T_SHORT:{ + long long_val = PyLong_AsLong(v); + if ((long_val == -1) && PyErr_Occurred()) + return -1; + *(short*)addr = (short)long_val; + if ((long_val > SHRT_MAX) || (long_val < SHRT_MIN)) + WARN("Truncation of value to short"); + break; + } + case T_USHORT:{ + long long_val = PyLong_AsLong(v); + if ((long_val == -1) && PyErr_Occurred()) + return -1; + *(unsigned short*)addr = (unsigned short)long_val; + if ((long_val > USHRT_MAX) || (long_val < 0)) + WARN("Truncation of value to unsigned short"); + break; + } + case T_INT:{ + long long_val = PyLong_AsLong(v); + if ((long_val == -1) && PyErr_Occurred()) + return -1; + *(int *)addr = (int)long_val; + if ((long_val > INT_MAX) || (long_val < INT_MIN)) + WARN("Truncation of value to int"); + break; + } + case T_UINT:{ + unsigned long ulong_val = PyLong_AsUnsignedLong(v); + if ((ulong_val == (unsigned long)-1) && PyErr_Occurred()) { + /* XXX: For compatibility, accept negative int values + as well. */ + PyErr_Clear(); + ulong_val = PyLong_AsLong(v); + if ((ulong_val == (unsigned long)-1) && + PyErr_Occurred()) + return -1; + *(unsigned int *)addr = (unsigned int)ulong_val; + WARN("Writing negative value into unsigned field"); + } else + *(unsigned int *)addr = (unsigned int)ulong_val; + if (ulong_val > UINT_MAX) + WARN("Truncation of value to unsigned int"); + break; + } + case T_LONG:{ + *(long*)addr = PyLong_AsLong(v); + if ((*(long*)addr == -1) && PyErr_Occurred()) + return -1; + break; + } + case T_ULONG:{ + *(unsigned long*)addr = PyLong_AsUnsignedLong(v); + if ((*(unsigned long*)addr == (unsigned long)-1) + && PyErr_Occurred()) { + /* XXX: For compatibility, accept negative int values + as well. */ + PyErr_Clear(); + *(unsigned long*)addr = PyLong_AsLong(v); + if ((*(unsigned long*)addr == (unsigned long)-1) + && PyErr_Occurred()) + return -1; + WARN("Writing negative value into unsigned field"); + } + break; + } + case T_PYSSIZET:{ + *(Py_ssize_t*)addr = PyLong_AsSsize_t(v); + if ((*(Py_ssize_t*)addr == (Py_ssize_t)-1) + && PyErr_Occurred()) + return -1; + break; + } + case T_FLOAT:{ + double double_val = PyFloat_AsDouble(v); + if ((double_val == -1) && PyErr_Occurred()) + return -1; + *(float*)addr = (float)double_val; + break; + } + case T_DOUBLE: + *(double*)addr = PyFloat_AsDouble(v); + if ((*(double*)addr == -1) && PyErr_Occurred()) + return -1; + break; + case T_OBJECT: + case T_OBJECT_EX: + Py_XINCREF(v); + oldv = *(PyObject **)addr; + *(PyObject **)addr = v; + Py_XDECREF(oldv); + break; + case T_CHAR: { + char *string; + Py_ssize_t len; - if (!PyUnicode_Check(v)) { - PyErr_BadArgument(); - return -1; - } - string = _PyUnicode_AsStringAndSize(v, &len); - if (len != 1) { - PyErr_BadArgument(); - return -1; - } - *(char*)addr = string[0]; - break; - } - case T_STRING: - case T_STRING_INPLACE: - PyErr_SetString(PyExc_TypeError, "readonly attribute"); - return -1; + if (!PyUnicode_Check(v)) { + PyErr_BadArgument(); + return -1; + } + string = _PyUnicode_AsStringAndSize(v, &len); + if (len != 1) { + PyErr_BadArgument(); + return -1; + } + *(char*)addr = string[0]; + break; + } + case T_STRING: + case T_STRING_INPLACE: + PyErr_SetString(PyExc_TypeError, "readonly attribute"); + return -1; #ifdef HAVE_LONG_LONG - case T_LONGLONG:{ - PY_LONG_LONG value; - *(PY_LONG_LONG*)addr = value = PyLong_AsLongLong(v); - if ((value == -1) && PyErr_Occurred()) - return -1; - break; - } - case T_ULONGLONG:{ - unsigned PY_LONG_LONG value; - /* ??? PyLong_AsLongLong accepts an int, but PyLong_AsUnsignedLongLong - doesn't ??? */ - if (PyLong_Check(v)) - *(unsigned PY_LONG_LONG*)addr = value = PyLong_AsUnsignedLongLong(v); - else - *(unsigned PY_LONG_LONG*)addr = value = PyLong_AsLong(v); - if ((value == (unsigned PY_LONG_LONG)-1) && PyErr_Occurred()) - return -1; - break; - } + case T_LONGLONG:{ + PY_LONG_LONG value; + *(PY_LONG_LONG*)addr = value = PyLong_AsLongLong(v); + if ((value == -1) && PyErr_Occurred()) + return -1; + break; + } + case T_ULONGLONG:{ + unsigned PY_LONG_LONG value; + /* ??? PyLong_AsLongLong accepts an int, but PyLong_AsUnsignedLongLong + doesn't ??? */ + if (PyLong_Check(v)) + *(unsigned PY_LONG_LONG*)addr = value = PyLong_AsUnsignedLongLong(v); + else + *(unsigned PY_LONG_LONG*)addr = value = PyLong_AsLong(v); + if ((value == (unsigned PY_LONG_LONG)-1) && PyErr_Occurred()) + return -1; + break; + } #endif /* HAVE_LONG_LONG */ - default: - PyErr_Format(PyExc_SystemError, - "bad memberdescr type for %s", l->name); - return -1; - } - return 0; + default: + PyErr_Format(PyExc_SystemError, + "bad memberdescr type for %s", l->name); + return -1; + } + return 0; } Modified: python/branches/release31-maint/Python/symtable.c ============================================================================== --- python/branches/release31-maint/Python/symtable.c (original) +++ python/branches/release31-maint/Python/symtable.c Sun May 9 18:14:21 2010 @@ -25,147 +25,147 @@ static PySTEntryObject * ste_new(struct symtable *st, identifier name, _Py_block_ty block, - void *key, int lineno) + void *key, int lineno) { - PySTEntryObject *ste = NULL; - PyObject *k; + PySTEntryObject *ste = NULL; + PyObject *k; - k = PyLong_FromVoidPtr(key); - if (k == NULL) - goto fail; - ste = PyObject_New(PySTEntryObject, &PySTEntry_Type); - if (ste == NULL) - goto fail; - ste->ste_table = st; - ste->ste_id = k; - ste->ste_tmpname = 0; - - ste->ste_name = name; - Py_INCREF(name); - - ste->ste_symbols = NULL; - ste->ste_varnames = NULL; - ste->ste_children = NULL; - - ste->ste_symbols = PyDict_New(); - if (ste->ste_symbols == NULL) - goto fail; - - ste->ste_varnames = PyList_New(0); - if (ste->ste_varnames == NULL) - goto fail; - - ste->ste_children = PyList_New(0); - if (ste->ste_children == NULL) - goto fail; - - ste->ste_type = block; - ste->ste_unoptimized = 0; - ste->ste_nested = 0; - ste->ste_free = 0; - ste->ste_varargs = 0; - ste->ste_varkeywords = 0; - ste->ste_opt_lineno = 0; - ste->ste_tmpname = 0; - ste->ste_lineno = lineno; - - if (st->st_cur != NULL && - (st->st_cur->ste_nested || - st->st_cur->ste_type == FunctionBlock)) - ste->ste_nested = 1; - ste->ste_child_free = 0; - ste->ste_generator = 0; - ste->ste_returns_value = 0; - - if (PyDict_SetItem(st->st_blocks, ste->ste_id, (PyObject *)ste) < 0) - goto fail; - - return ste; + k = PyLong_FromVoidPtr(key); + if (k == NULL) + goto fail; + ste = PyObject_New(PySTEntryObject, &PySTEntry_Type); + if (ste == NULL) + goto fail; + ste->ste_table = st; + ste->ste_id = k; + ste->ste_tmpname = 0; + + ste->ste_name = name; + Py_INCREF(name); + + ste->ste_symbols = NULL; + ste->ste_varnames = NULL; + ste->ste_children = NULL; + + ste->ste_symbols = PyDict_New(); + if (ste->ste_symbols == NULL) + goto fail; + + ste->ste_varnames = PyList_New(0); + if (ste->ste_varnames == NULL) + goto fail; + + ste->ste_children = PyList_New(0); + if (ste->ste_children == NULL) + goto fail; + + ste->ste_type = block; + ste->ste_unoptimized = 0; + ste->ste_nested = 0; + ste->ste_free = 0; + ste->ste_varargs = 0; + ste->ste_varkeywords = 0; + ste->ste_opt_lineno = 0; + ste->ste_tmpname = 0; + ste->ste_lineno = lineno; + + if (st->st_cur != NULL && + (st->st_cur->ste_nested || + st->st_cur->ste_type == FunctionBlock)) + ste->ste_nested = 1; + ste->ste_child_free = 0; + ste->ste_generator = 0; + ste->ste_returns_value = 0; + + if (PyDict_SetItem(st->st_blocks, ste->ste_id, (PyObject *)ste) < 0) + goto fail; + + return ste; fail: - Py_XDECREF(ste); - return NULL; + Py_XDECREF(ste); + return NULL; } static PyObject * ste_repr(PySTEntryObject *ste) { - return PyUnicode_FromFormat("", - ste->ste_name, - PyLong_AS_LONG(ste->ste_id), ste->ste_lineno); + return PyUnicode_FromFormat("", + ste->ste_name, + PyLong_AS_LONG(ste->ste_id), ste->ste_lineno); } static void ste_dealloc(PySTEntryObject *ste) { - ste->ste_table = NULL; - Py_XDECREF(ste->ste_id); - Py_XDECREF(ste->ste_name); - Py_XDECREF(ste->ste_symbols); - Py_XDECREF(ste->ste_varnames); - Py_XDECREF(ste->ste_children); - PyObject_Del(ste); + ste->ste_table = NULL; + Py_XDECREF(ste->ste_id); + Py_XDECREF(ste->ste_name); + Py_XDECREF(ste->ste_symbols); + Py_XDECREF(ste->ste_varnames); + Py_XDECREF(ste->ste_children); + PyObject_Del(ste); } #define OFF(x) offsetof(PySTEntryObject, x) static PyMemberDef ste_memberlist[] = { - {"id", T_OBJECT, OFF(ste_id), READONLY}, - {"name", T_OBJECT, OFF(ste_name), READONLY}, - {"symbols", T_OBJECT, OFF(ste_symbols), READONLY}, - {"varnames", T_OBJECT, OFF(ste_varnames), READONLY}, - {"children", T_OBJECT, OFF(ste_children), READONLY}, - {"optimized",T_INT, OFF(ste_unoptimized), READONLY}, - {"nested", T_INT, OFF(ste_nested), READONLY}, - {"type", T_INT, OFF(ste_type), READONLY}, - {"lineno", T_INT, OFF(ste_lineno), READONLY}, - {NULL} + {"id", T_OBJECT, OFF(ste_id), READONLY}, + {"name", T_OBJECT, OFF(ste_name), READONLY}, + {"symbols", T_OBJECT, OFF(ste_symbols), READONLY}, + {"varnames", T_OBJECT, OFF(ste_varnames), READONLY}, + {"children", T_OBJECT, OFF(ste_children), READONLY}, + {"optimized",T_INT, OFF(ste_unoptimized), READONLY}, + {"nested", T_INT, OFF(ste_nested), READONLY}, + {"type", T_INT, OFF(ste_type), READONLY}, + {"lineno", T_INT, OFF(ste_lineno), READONLY}, + {NULL} }; PyTypeObject PySTEntry_Type = { - PyVarObject_HEAD_INIT(&PyType_Type, 0) - "symtable entry", - sizeof(PySTEntryObject), - 0, - (destructor)ste_dealloc, /* tp_dealloc */ - 0, /* tp_print */ - 0, /* tp_getattr */ - 0, /* tp_setattr */ - 0, /* tp_reserved */ - (reprfunc)ste_repr, /* tp_repr */ - 0, /* tp_as_number */ - 0, /* tp_as_sequence */ - 0, /* tp_as_mapping */ - 0, /* tp_hash */ - 0, /* tp_call */ - 0, /* tp_str */ - PyObject_GenericGetAttr, /* tp_getattro */ - 0, /* tp_setattro */ - 0, /* tp_as_buffer */ - Py_TPFLAGS_DEFAULT, /* tp_flags */ - 0, /* tp_doc */ - 0, /* tp_traverse */ - 0, /* tp_clear */ - 0, /* tp_richcompare */ - 0, /* tp_weaklistoffset */ - 0, /* tp_iter */ - 0, /* tp_iternext */ - 0, /* tp_methods */ - ste_memberlist, /* tp_members */ - 0, /* tp_getset */ - 0, /* tp_base */ - 0, /* tp_dict */ - 0, /* tp_descr_get */ - 0, /* tp_descr_set */ - 0, /* tp_dictoffset */ - 0, /* tp_init */ - 0, /* tp_alloc */ - 0, /* tp_new */ + PyVarObject_HEAD_INIT(&PyType_Type, 0) + "symtable entry", + sizeof(PySTEntryObject), + 0, + (destructor)ste_dealloc, /* tp_dealloc */ + 0, /* tp_print */ + 0, /* tp_getattr */ + 0, /* tp_setattr */ + 0, /* tp_reserved */ + (reprfunc)ste_repr, /* tp_repr */ + 0, /* tp_as_number */ + 0, /* tp_as_sequence */ + 0, /* tp_as_mapping */ + 0, /* tp_hash */ + 0, /* tp_call */ + 0, /* tp_str */ + PyObject_GenericGetAttr, /* tp_getattro */ + 0, /* tp_setattro */ + 0, /* tp_as_buffer */ + Py_TPFLAGS_DEFAULT, /* tp_flags */ + 0, /* tp_doc */ + 0, /* tp_traverse */ + 0, /* tp_clear */ + 0, /* tp_richcompare */ + 0, /* tp_weaklistoffset */ + 0, /* tp_iter */ + 0, /* tp_iternext */ + 0, /* tp_methods */ + ste_memberlist, /* tp_members */ + 0, /* tp_getset */ + 0, /* tp_base */ + 0, /* tp_dict */ + 0, /* tp_descr_get */ + 0, /* tp_descr_set */ + 0, /* tp_dictoffset */ + 0, /* tp_init */ + 0, /* tp_alloc */ + 0, /* tp_new */ }; static int symtable_analyze(struct symtable *st); static int symtable_warn(struct symtable *st, char *msg, int lineno); -static int symtable_enter_block(struct symtable *st, identifier name, - _Py_block_ty block, void *ast, int lineno); +static int symtable_enter_block(struct symtable *st, identifier name, + _Py_block_ty block, void *ast, int lineno); static int symtable_exit_block(struct symtable *st, void *ast); static int symtable_visit_stmt(struct symtable *st, stmt_ty s); static int symtable_visit_expr(struct symtable *st, expr_ty s); @@ -186,11 +186,11 @@ static identifier top = NULL, lambda = NULL, genexpr = NULL, - listcomp = NULL, setcomp = NULL, dictcomp = NULL, - __class__ = NULL, __locals__ = NULL; + listcomp = NULL, setcomp = NULL, dictcomp = NULL, + __class__ = NULL, __locals__ = NULL; #define GET_IDENTIFIER(VAR) \ - ((VAR) ? (VAR) : ((VAR) = PyUnicode_InternFromString(# VAR))) + ((VAR) ? (VAR) : ((VAR) = PyUnicode_InternFromString(# VAR))) #define DUPLICATE_ARGUMENT \ "duplicate argument '%U' in function definition" @@ -198,135 +198,135 @@ static struct symtable * symtable_new(void) { - struct symtable *st; + struct symtable *st; - st = (struct symtable *)PyMem_Malloc(sizeof(struct symtable)); - if (st == NULL) - return NULL; - - st->st_filename = NULL; - st->st_blocks = NULL; - - if ((st->st_stack = PyList_New(0)) == NULL) - goto fail; - if ((st->st_blocks = PyDict_New()) == NULL) - goto fail; - st->st_cur = NULL; - st->st_private = NULL; - return st; + st = (struct symtable *)PyMem_Malloc(sizeof(struct symtable)); + if (st == NULL) + return NULL; + + st->st_filename = NULL; + st->st_blocks = NULL; + + if ((st->st_stack = PyList_New(0)) == NULL) + goto fail; + if ((st->st_blocks = PyDict_New()) == NULL) + goto fail; + st->st_cur = NULL; + st->st_private = NULL; + return st; fail: - PySymtable_Free(st); - return NULL; + PySymtable_Free(st); + return NULL; } struct symtable * PySymtable_Build(mod_ty mod, const char *filename, PyFutureFeatures *future) { - struct symtable *st = symtable_new(); - asdl_seq *seq; - int i; - - if (st == NULL) - return st; - st->st_filename = filename; - st->st_future = future; - /* Make the initial symbol information gathering pass */ - if (!GET_IDENTIFIER(top) || - !symtable_enter_block(st, top, ModuleBlock, (void *)mod, 0)) { - PySymtable_Free(st); - return NULL; - } - - st->st_top = st->st_cur; - st->st_cur->ste_unoptimized = OPT_TOPLEVEL; - switch (mod->kind) { - case Module_kind: - seq = mod->v.Module.body; - for (i = 0; i < asdl_seq_LEN(seq); i++) - if (!symtable_visit_stmt(st, - (stmt_ty)asdl_seq_GET(seq, i))) - goto error; - break; - case Expression_kind: - if (!symtable_visit_expr(st, mod->v.Expression.body)) - goto error; - break; - case Interactive_kind: - seq = mod->v.Interactive.body; - for (i = 0; i < asdl_seq_LEN(seq); i++) - if (!symtable_visit_stmt(st, - (stmt_ty)asdl_seq_GET(seq, i))) - goto error; - break; - case Suite_kind: - PyErr_SetString(PyExc_RuntimeError, - "this compiler does not handle Suites"); - goto error; - } - if (!symtable_exit_block(st, (void *)mod)) { - PySymtable_Free(st); - return NULL; - } - /* Make the second symbol analysis pass */ - if (symtable_analyze(st)) - return st; - PySymtable_Free(st); - return NULL; + struct symtable *st = symtable_new(); + asdl_seq *seq; + int i; + + if (st == NULL) + return st; + st->st_filename = filename; + st->st_future = future; + /* Make the initial symbol information gathering pass */ + if (!GET_IDENTIFIER(top) || + !symtable_enter_block(st, top, ModuleBlock, (void *)mod, 0)) { + PySymtable_Free(st); + return NULL; + } + + st->st_top = st->st_cur; + st->st_cur->ste_unoptimized = OPT_TOPLEVEL; + switch (mod->kind) { + case Module_kind: + seq = mod->v.Module.body; + for (i = 0; i < asdl_seq_LEN(seq); i++) + if (!symtable_visit_stmt(st, + (stmt_ty)asdl_seq_GET(seq, i))) + goto error; + break; + case Expression_kind: + if (!symtable_visit_expr(st, mod->v.Expression.body)) + goto error; + break; + case Interactive_kind: + seq = mod->v.Interactive.body; + for (i = 0; i < asdl_seq_LEN(seq); i++) + if (!symtable_visit_stmt(st, + (stmt_ty)asdl_seq_GET(seq, i))) + goto error; + break; + case Suite_kind: + PyErr_SetString(PyExc_RuntimeError, + "this compiler does not handle Suites"); + goto error; + } + if (!symtable_exit_block(st, (void *)mod)) { + PySymtable_Free(st); + return NULL; + } + /* Make the second symbol analysis pass */ + if (symtable_analyze(st)) + return st; + PySymtable_Free(st); + return NULL; error: - (void) symtable_exit_block(st, (void *)mod); - PySymtable_Free(st); - return NULL; + (void) symtable_exit_block(st, (void *)mod); + PySymtable_Free(st); + return NULL; } void PySymtable_Free(struct symtable *st) { - Py_XDECREF(st->st_blocks); - Py_XDECREF(st->st_stack); - PyMem_Free((void *)st); + Py_XDECREF(st->st_blocks); + Py_XDECREF(st->st_stack); + PyMem_Free((void *)st); } PySTEntryObject * PySymtable_Lookup(struct symtable *st, void *key) { - PyObject *k, *v; + PyObject *k, *v; - k = PyLong_FromVoidPtr(key); - if (k == NULL) - return NULL; - v = PyDict_GetItem(st->st_blocks, k); - if (v) { - assert(PySTEntry_Check(v)); - Py_INCREF(v); - } - else { - PyErr_SetString(PyExc_KeyError, - "unknown symbol table entry"); - } + k = PyLong_FromVoidPtr(key); + if (k == NULL) + return NULL; + v = PyDict_GetItem(st->st_blocks, k); + if (v) { + assert(PySTEntry_Check(v)); + Py_INCREF(v); + } + else { + PyErr_SetString(PyExc_KeyError, + "unknown symbol table entry"); + } - Py_DECREF(k); - return (PySTEntryObject *)v; + Py_DECREF(k); + return (PySTEntryObject *)v; } -int +int PyST_GetScope(PySTEntryObject *ste, PyObject *name) { - PyObject *v = PyDict_GetItem(ste->ste_symbols, name); - if (!v) - return 0; - assert(PyLong_Check(v)); - return (PyLong_AS_LONG(v) >> SCOPE_OFFSET) & SCOPE_MASK; + PyObject *v = PyDict_GetItem(ste->ste_symbols, name); + if (!v) + return 0; + assert(PyLong_Check(v)); + return (PyLong_AS_LONG(v) >> SCOPE_OFFSET) & SCOPE_MASK; } /* Analyze raw symbol information to determine scope of each name. The next several functions are helpers for symtable_analyze(), - which determines whether a name is local, global, or free. In addition, + which determines whether a name is local, global, or free. In addition, it determines which local variables are cell variables; they provide - bindings that are used for free variables in enclosed blocks. + bindings that are used for free variables in enclosed blocks. - There are also two kinds of global variables, implicit and explicit. An + There are also two kinds of global variables, implicit and explicit. An explicit global is declared with the global statement. An implicit global is a free variable for which the compiler has found no binding in an enclosing function scope. The implicit global is either a global @@ -342,7 +342,7 @@ PySTEntryObjects created during pass 1. When a function is entered during the second pass, the parent passes - the set of all name bindings visible to its children. These bindings + the set of all name bindings visible to its children. These bindings are used to determine if non-local variables are free or implicit globals. Names which are explicitly declared nonlocal must exist in this set of visible names - if they do not, a syntax error is raised. After doing @@ -365,14 +365,14 @@ */ #define SET_SCOPE(DICT, NAME, I) { \ - PyObject *o = PyLong_FromLong(I); \ - if (!o) \ - return 0; \ - if (PyDict_SetItem((DICT), (NAME), o) < 0) { \ - Py_DECREF(o); \ - return 0; \ - } \ - Py_DECREF(o); \ + PyObject *o = PyLong_FromLong(I); \ + if (!o) \ + return 0; \ + if (PyDict_SetItem((DICT), (NAME), o) < 0) { \ + Py_DECREF(o); \ + return 0; \ + } \ + Py_DECREF(o); \ } /* Decide on scope of name, given flags. @@ -382,86 +382,86 @@ global. A name that was global can be changed to local. */ -static int +static int analyze_name(PySTEntryObject *ste, PyObject *scopes, PyObject *name, long flags, - PyObject *bound, PyObject *local, PyObject *free, - PyObject *global) + PyObject *bound, PyObject *local, PyObject *free, + PyObject *global) { - if (flags & DEF_GLOBAL) { - if (flags & DEF_PARAM) { - PyErr_Format(PyExc_SyntaxError, - "name '%U' is parameter and global", - name); - PyErr_SyntaxLocation(ste->ste_table->st_filename, - ste->ste_lineno); - - return 0; - } - if (flags & DEF_NONLOCAL) { - PyErr_Format(PyExc_SyntaxError, - "name '%U' is nonlocal and global", - name); - return 0; - } - SET_SCOPE(scopes, name, GLOBAL_EXPLICIT); - if (PySet_Add(global, name) < 0) - return 0; - if (bound && (PySet_Discard(bound, name) < 0)) - return 0; - return 1; - } + if (flags & DEF_GLOBAL) { + if (flags & DEF_PARAM) { + PyErr_Format(PyExc_SyntaxError, + "name '%U' is parameter and global", + name); + PyErr_SyntaxLocation(ste->ste_table->st_filename, + ste->ste_lineno); + + return 0; + } if (flags & DEF_NONLOCAL) { - if (flags & DEF_PARAM) { - PyErr_Format(PyExc_SyntaxError, - "name '%U' is parameter and nonlocal", - name); - return 0; - } - if (!bound) { - PyErr_Format(PyExc_SyntaxError, - "nonlocal declaration not allowed at module level"); - return 0; - } - if (!PySet_Contains(bound, name)) { - PyErr_Format(PyExc_SyntaxError, - "no binding for nonlocal '%U' found", - name); - - return 0; - } - SET_SCOPE(scopes, name, FREE); - ste->ste_free = 1; - return PySet_Add(free, name) >= 0; - } - if (flags & DEF_BOUND) { - SET_SCOPE(scopes, name, LOCAL); - if (PySet_Add(local, name) < 0) - return 0; - if (PySet_Discard(global, name) < 0) - return 0; - return 1; - } - /* If an enclosing block has a binding for this name, it - is a free variable rather than a global variable. - Note that having a non-NULL bound implies that the block - is nested. - */ - if (bound && PySet_Contains(bound, name)) { - SET_SCOPE(scopes, name, FREE); - ste->ste_free = 1; - return PySet_Add(free, name) >= 0; - } - /* If a parent has a global statement, then call it global - explicit? It could also be global implicit. - */ - if (global && PySet_Contains(global, name)) { - SET_SCOPE(scopes, name, GLOBAL_IMPLICIT); - return 1; - } - if (ste->ste_nested) - ste->ste_free = 1; - SET_SCOPE(scopes, name, GLOBAL_IMPLICIT); - return 1; + PyErr_Format(PyExc_SyntaxError, + "name '%U' is nonlocal and global", + name); + return 0; + } + SET_SCOPE(scopes, name, GLOBAL_EXPLICIT); + if (PySet_Add(global, name) < 0) + return 0; + if (bound && (PySet_Discard(bound, name) < 0)) + return 0; + return 1; + } + if (flags & DEF_NONLOCAL) { + if (flags & DEF_PARAM) { + PyErr_Format(PyExc_SyntaxError, + "name '%U' is parameter and nonlocal", + name); + return 0; + } + if (!bound) { + PyErr_Format(PyExc_SyntaxError, + "nonlocal declaration not allowed at module level"); + return 0; + } + if (!PySet_Contains(bound, name)) { + PyErr_Format(PyExc_SyntaxError, + "no binding for nonlocal '%U' found", + name); + + return 0; + } + SET_SCOPE(scopes, name, FREE); + ste->ste_free = 1; + return PySet_Add(free, name) >= 0; + } + if (flags & DEF_BOUND) { + SET_SCOPE(scopes, name, LOCAL); + if (PySet_Add(local, name) < 0) + return 0; + if (PySet_Discard(global, name) < 0) + return 0; + return 1; + } + /* If an enclosing block has a binding for this name, it + is a free variable rather than a global variable. + Note that having a non-NULL bound implies that the block + is nested. + */ + if (bound && PySet_Contains(bound, name)) { + SET_SCOPE(scopes, name, FREE); + ste->ste_free = 1; + return PySet_Add(free, name) >= 0; + } + /* If a parent has a global statement, then call it global + explicit? It could also be global implicit. + */ + if (global && PySet_Contains(global, name)) { + SET_SCOPE(scopes, name, GLOBAL_IMPLICIT); + return 1; + } + if (ste->ste_nested) + ste->ste_free = 1; + SET_SCOPE(scopes, name, GLOBAL_IMPLICIT); + return 1; } #undef SET_SCOPE @@ -480,153 +480,153 @@ static int analyze_cells(PyObject *scopes, PyObject *free, const char *restricted) { - PyObject *name, *v, *v_cell; - int success = 0; - Py_ssize_t pos = 0; - - v_cell = PyLong_FromLong(CELL); - if (!v_cell) - return 0; - while (PyDict_Next(scopes, &pos, &name, &v)) { - long scope; - assert(PyLong_Check(v)); - scope = PyLong_AS_LONG(v); - if (scope != LOCAL) - continue; - if (!PySet_Contains(free, name)) - continue; - if (restricted != NULL && - PyUnicode_CompareWithASCIIString(name, restricted)) - continue; - /* Replace LOCAL with CELL for this name, and remove - from free. It is safe to replace the value of name - in the dict, because it will not cause a resize. - */ - if (PyDict_SetItem(scopes, name, v_cell) < 0) - goto error; - if (PySet_Discard(free, name) < 0) - goto error; - } - success = 1; + PyObject *name, *v, *v_cell; + int success = 0; + Py_ssize_t pos = 0; + + v_cell = PyLong_FromLong(CELL); + if (!v_cell) + return 0; + while (PyDict_Next(scopes, &pos, &name, &v)) { + long scope; + assert(PyLong_Check(v)); + scope = PyLong_AS_LONG(v); + if (scope != LOCAL) + continue; + if (!PySet_Contains(free, name)) + continue; + if (restricted != NULL && + PyUnicode_CompareWithASCIIString(name, restricted)) + continue; + /* Replace LOCAL with CELL for this name, and remove + from free. It is safe to replace the value of name + in the dict, because it will not cause a resize. + */ + if (PyDict_SetItem(scopes, name, v_cell) < 0) + goto error; + if (PySet_Discard(free, name) < 0) + goto error; + } + success = 1; error: - Py_DECREF(v_cell); - return success; + Py_DECREF(v_cell); + return success; } /* Check for illegal statements in unoptimized namespaces */ static int check_unoptimized(const PySTEntryObject* ste) { - const char* trailer; + const char* trailer; - if (ste->ste_type != FunctionBlock || !ste->ste_unoptimized - || !(ste->ste_free || ste->ste_child_free)) - return 1; - - trailer = (ste->ste_child_free ? - "contains a nested function with free variables" : - "is a nested function"); - - switch (ste->ste_unoptimized) { - case OPT_TOPLEVEL: /* import * at top-level is fine */ - return 1; - case OPT_IMPORT_STAR: - PyErr_Format(PyExc_SyntaxError, - "import * is not allowed in function '%U' because it %s", - ste->ste_name, trailer); - break; - } - - PyErr_SyntaxLocation(ste->ste_table->st_filename, - ste->ste_opt_lineno); - return 0; + if (ste->ste_type != FunctionBlock || !ste->ste_unoptimized + || !(ste->ste_free || ste->ste_child_free)) + return 1; + + trailer = (ste->ste_child_free ? + "contains a nested function with free variables" : + "is a nested function"); + + switch (ste->ste_unoptimized) { + case OPT_TOPLEVEL: /* import * at top-level is fine */ + return 1; + case OPT_IMPORT_STAR: + PyErr_Format(PyExc_SyntaxError, + "import * is not allowed in function '%U' because it %s", + ste->ste_name, trailer); + break; + } + + PyErr_SyntaxLocation(ste->ste_table->st_filename, + ste->ste_opt_lineno); + return 0; } -/* Enter the final scope information into the ste_symbols dict. - * +/* Enter the final scope information into the ste_symbols dict. + * * All arguments are dicts. Modifies symbols, others are read-only. */ static int -update_symbols(PyObject *symbols, PyObject *scopes, +update_symbols(PyObject *symbols, PyObject *scopes, PyObject *bound, PyObject *free, int classflag) { - PyObject *name = NULL, *itr = NULL; - PyObject *v = NULL, *v_scope = NULL, *v_new = NULL, *v_free = NULL; - Py_ssize_t pos = 0; - - /* Update scope information for all symbols in this scope */ - while (PyDict_Next(symbols, &pos, &name, &v)) { - long scope, flags; - assert(PyLong_Check(v)); - flags = PyLong_AS_LONG(v); - v_scope = PyDict_GetItem(scopes, name); - assert(v_scope && PyLong_Check(v_scope)); - scope = PyLong_AS_LONG(v_scope); - flags |= (scope << SCOPE_OFFSET); - v_new = PyLong_FromLong(flags); - if (!v_new) - return 0; - if (PyDict_SetItem(symbols, name, v_new) < 0) { - Py_DECREF(v_new); - return 0; - } - Py_DECREF(v_new); - } - - /* Record not yet resolved free variables from children (if any) */ - v_free = PyLong_FromLong(FREE << SCOPE_OFFSET); - if (!v_free) - return 0; - - itr = PyObject_GetIter(free); - if (!itr) - goto error; - - while ((name = PyIter_Next(itr))) { - v = PyDict_GetItem(symbols, name); - - /* Handle symbol that already exists in this scope */ - if (v) { - /* Handle a free variable in a method of - the class that has the same name as a local - or global in the class scope. - */ - if (classflag && - PyLong_AS_LONG(v) & (DEF_BOUND | DEF_GLOBAL)) { - long flags = PyLong_AS_LONG(v) | DEF_FREE_CLASS; - v_new = PyLong_FromLong(flags); - if (!v_new) { - goto error; - } - if (PyDict_SetItem(symbols, name, v_new) < 0) { - Py_DECREF(v_new); - goto error; - } - Py_DECREF(v_new); - } - /* It's a cell, or already free in this scope */ - Py_DECREF(name); - continue; - } - /* Handle global symbol */ - if (!PySet_Contains(bound, name)) { - Py_DECREF(name); - continue; /* it's a global */ - } - /* Propagate new free symbol up the lexical stack */ - if (PyDict_SetItem(symbols, name, v_free) < 0) { - goto error; - } - Py_DECREF(name); - } - Py_DECREF(itr); - Py_DECREF(v_free); - return 1; + PyObject *name = NULL, *itr = NULL; + PyObject *v = NULL, *v_scope = NULL, *v_new = NULL, *v_free = NULL; + Py_ssize_t pos = 0; + + /* Update scope information for all symbols in this scope */ + while (PyDict_Next(symbols, &pos, &name, &v)) { + long scope, flags; + assert(PyLong_Check(v)); + flags = PyLong_AS_LONG(v); + v_scope = PyDict_GetItem(scopes, name); + assert(v_scope && PyLong_Check(v_scope)); + scope = PyLong_AS_LONG(v_scope); + flags |= (scope << SCOPE_OFFSET); + v_new = PyLong_FromLong(flags); + if (!v_new) + return 0; + if (PyDict_SetItem(symbols, name, v_new) < 0) { + Py_DECREF(v_new); + return 0; + } + Py_DECREF(v_new); + } + + /* Record not yet resolved free variables from children (if any) */ + v_free = PyLong_FromLong(FREE << SCOPE_OFFSET); + if (!v_free) + return 0; + + itr = PyObject_GetIter(free); + if (!itr) + goto error; + + while ((name = PyIter_Next(itr))) { + v = PyDict_GetItem(symbols, name); + + /* Handle symbol that already exists in this scope */ + if (v) { + /* Handle a free variable in a method of + the class that has the same name as a local + or global in the class scope. + */ + if (classflag && + PyLong_AS_LONG(v) & (DEF_BOUND | DEF_GLOBAL)) { + long flags = PyLong_AS_LONG(v) | DEF_FREE_CLASS; + v_new = PyLong_FromLong(flags); + if (!v_new) { + goto error; + } + if (PyDict_SetItem(symbols, name, v_new) < 0) { + Py_DECREF(v_new); + goto error; + } + Py_DECREF(v_new); + } + /* It's a cell, or already free in this scope */ + Py_DECREF(name); + continue; + } + /* Handle global symbol */ + if (!PySet_Contains(bound, name)) { + Py_DECREF(name); + continue; /* it's a global */ + } + /* Propagate new free symbol up the lexical stack */ + if (PyDict_SetItem(symbols, name, v_free) < 0) { + goto error; + } + Py_DECREF(name); + } + Py_DECREF(itr); + Py_DECREF(v_free); + return 1; error: - Py_XDECREF(v_free); - Py_XDECREF(itr); - Py_XDECREF(name); - return 0; -} + Py_XDECREF(v_free); + Py_XDECREF(itr); + Py_XDECREF(name); + return 0; +} /* Make final symbol table decisions for block of ste. @@ -649,238 +649,238 @@ */ static int -analyze_child_block(PySTEntryObject *entry, PyObject *bound, PyObject *free, - PyObject *global, PyObject* child_free); +analyze_child_block(PySTEntryObject *entry, PyObject *bound, PyObject *free, + PyObject *global, PyObject* child_free); static int -analyze_block(PySTEntryObject *ste, PyObject *bound, PyObject *free, - PyObject *global) +analyze_block(PySTEntryObject *ste, PyObject *bound, PyObject *free, + PyObject *global) { - PyObject *name, *v, *local = NULL, *scopes = NULL, *newbound = NULL; - PyObject *newglobal = NULL, *newfree = NULL, *allfree = NULL; - PyObject *temp; - int i, success = 0; - Py_ssize_t pos = 0; - - local = PySet_New(NULL); /* collect new names bound in block */ - if (!local) - goto error; - scopes = PyDict_New(); /* collect scopes defined for each name */ - if (!scopes) - goto error; - - /* Allocate new global and bound variable dictionaries. These - dictionaries hold the names visible in nested blocks. For - ClassBlocks, the bound and global names are initialized - before analyzing names, because class bindings aren't - visible in methods. For other blocks, they are initialized - after names are analyzed. - */ - - /* TODO(jhylton): Package these dicts in a struct so that we - can write reasonable helper functions? - */ - newglobal = PySet_New(NULL); - if (!newglobal) - goto error; - newfree = PySet_New(NULL); - if (!newfree) - goto error; - newbound = PySet_New(NULL); - if (!newbound) - goto error; - - /* Class namespace has no effect on names visible in - nested functions, so populate the global and bound - sets to be passed to child blocks before analyzing - this one. - */ - if (ste->ste_type == ClassBlock) { - /* Pass down known globals */ - temp = PyNumber_InPlaceOr(newglobal, global); - if (!temp) - goto error; - Py_DECREF(temp); - /* Pass down previously bound symbols */ - if (bound) { - temp = PyNumber_InPlaceOr(newbound, bound); - if (!temp) - goto error; - Py_DECREF(temp); - } - } - - while (PyDict_Next(ste->ste_symbols, &pos, &name, &v)) { - long flags = PyLong_AS_LONG(v); - if (!analyze_name(ste, scopes, name, flags, - bound, local, free, global)) - goto error; - } - - /* Populate global and bound sets to be passed to children. */ - if (ste->ste_type != ClassBlock) { - /* Add function locals to bound set */ - if (ste->ste_type == FunctionBlock) { - temp = PyNumber_InPlaceOr(newbound, local); - if (!temp) - goto error; - Py_DECREF(temp); - } - /* Pass down previously bound symbols */ - if (bound) { - temp = PyNumber_InPlaceOr(newbound, bound); - if (!temp) - goto error; - Py_DECREF(temp); - } - /* Pass down known globals */ - temp = PyNumber_InPlaceOr(newglobal, global); - if (!temp) - goto error; - Py_DECREF(temp); - } - else { - /* Special-case __class__ */ - if (!GET_IDENTIFIER(__class__)) - goto error; - assert(PySet_Contains(local, __class__) == 1); - if (PySet_Add(newbound, __class__) < 0) - goto error; - } - - /* Recursively call analyze_block() on each child block. - - newbound, newglobal now contain the names visible in - nested blocks. The free variables in the children will - be collected in allfree. - */ - allfree = PySet_New(NULL); - if (!allfree) - goto error; - for (i = 0; i < PyList_GET_SIZE(ste->ste_children); ++i) { - PyObject *c = PyList_GET_ITEM(ste->ste_children, i); - PySTEntryObject* entry; - assert(c && PySTEntry_Check(c)); - entry = (PySTEntryObject*)c; - if (!analyze_child_block(entry, newbound, newfree, newglobal, - allfree)) - goto error; - /* Check if any children have free variables */ - if (entry->ste_free || entry->ste_child_free) - ste->ste_child_free = 1; - } - - temp = PyNumber_InPlaceOr(newfree, allfree); - if (!temp) - goto error; - Py_DECREF(temp); - - /* Check if any local variables must be converted to cell variables */ - if (ste->ste_type == FunctionBlock && !analyze_cells(scopes, newfree, - NULL)) - goto error; - else if (ste->ste_type == ClassBlock && !analyze_cells(scopes, newfree, - "__class__")) - goto error; - /* Records the results of the analysis in the symbol table entry */ - if (!update_symbols(ste->ste_symbols, scopes, bound, newfree, - ste->ste_type == ClassBlock)) - goto error; - if (!check_unoptimized(ste)) - goto error; - - temp = PyNumber_InPlaceOr(free, newfree); - if (!temp) - goto error; - Py_DECREF(temp); - success = 1; + PyObject *name, *v, *local = NULL, *scopes = NULL, *newbound = NULL; + PyObject *newglobal = NULL, *newfree = NULL, *allfree = NULL; + PyObject *temp; + int i, success = 0; + Py_ssize_t pos = 0; + + local = PySet_New(NULL); /* collect new names bound in block */ + if (!local) + goto error; + scopes = PyDict_New(); /* collect scopes defined for each name */ + if (!scopes) + goto error; + + /* Allocate new global and bound variable dictionaries. These + dictionaries hold the names visible in nested blocks. For + ClassBlocks, the bound and global names are initialized + before analyzing names, because class bindings aren't + visible in methods. For other blocks, they are initialized + after names are analyzed. + */ + + /* TODO(jhylton): Package these dicts in a struct so that we + can write reasonable helper functions? + */ + newglobal = PySet_New(NULL); + if (!newglobal) + goto error; + newfree = PySet_New(NULL); + if (!newfree) + goto error; + newbound = PySet_New(NULL); + if (!newbound) + goto error; + + /* Class namespace has no effect on names visible in + nested functions, so populate the global and bound + sets to be passed to child blocks before analyzing + this one. + */ + if (ste->ste_type == ClassBlock) { + /* Pass down known globals */ + temp = PyNumber_InPlaceOr(newglobal, global); + if (!temp) + goto error; + Py_DECREF(temp); + /* Pass down previously bound symbols */ + if (bound) { + temp = PyNumber_InPlaceOr(newbound, bound); + if (!temp) + goto error; + Py_DECREF(temp); + } + } + + while (PyDict_Next(ste->ste_symbols, &pos, &name, &v)) { + long flags = PyLong_AS_LONG(v); + if (!analyze_name(ste, scopes, name, flags, + bound, local, free, global)) + goto error; + } + + /* Populate global and bound sets to be passed to children. */ + if (ste->ste_type != ClassBlock) { + /* Add function locals to bound set */ + if (ste->ste_type == FunctionBlock) { + temp = PyNumber_InPlaceOr(newbound, local); + if (!temp) + goto error; + Py_DECREF(temp); + } + /* Pass down previously bound symbols */ + if (bound) { + temp = PyNumber_InPlaceOr(newbound, bound); + if (!temp) + goto error; + Py_DECREF(temp); + } + /* Pass down known globals */ + temp = PyNumber_InPlaceOr(newglobal, global); + if (!temp) + goto error; + Py_DECREF(temp); + } + else { + /* Special-case __class__ */ + if (!GET_IDENTIFIER(__class__)) + goto error; + assert(PySet_Contains(local, __class__) == 1); + if (PySet_Add(newbound, __class__) < 0) + goto error; + } + + /* Recursively call analyze_block() on each child block. + + newbound, newglobal now contain the names visible in + nested blocks. The free variables in the children will + be collected in allfree. + */ + allfree = PySet_New(NULL); + if (!allfree) + goto error; + for (i = 0; i < PyList_GET_SIZE(ste->ste_children); ++i) { + PyObject *c = PyList_GET_ITEM(ste->ste_children, i); + PySTEntryObject* entry; + assert(c && PySTEntry_Check(c)); + entry = (PySTEntryObject*)c; + if (!analyze_child_block(entry, newbound, newfree, newglobal, + allfree)) + goto error; + /* Check if any children have free variables */ + if (entry->ste_free || entry->ste_child_free) + ste->ste_child_free = 1; + } + + temp = PyNumber_InPlaceOr(newfree, allfree); + if (!temp) + goto error; + Py_DECREF(temp); + + /* Check if any local variables must be converted to cell variables */ + if (ste->ste_type == FunctionBlock && !analyze_cells(scopes, newfree, + NULL)) + goto error; + else if (ste->ste_type == ClassBlock && !analyze_cells(scopes, newfree, + "__class__")) + goto error; + /* Records the results of the analysis in the symbol table entry */ + if (!update_symbols(ste->ste_symbols, scopes, bound, newfree, + ste->ste_type == ClassBlock)) + goto error; + if (!check_unoptimized(ste)) + goto error; + + temp = PyNumber_InPlaceOr(free, newfree); + if (!temp) + goto error; + Py_DECREF(temp); + success = 1; error: - Py_XDECREF(scopes); - Py_XDECREF(local); - Py_XDECREF(newbound); - Py_XDECREF(newglobal); - Py_XDECREF(newfree); - Py_XDECREF(allfree); - if (!success) - assert(PyErr_Occurred()); - return success; + Py_XDECREF(scopes); + Py_XDECREF(local); + Py_XDECREF(newbound); + Py_XDECREF(newglobal); + Py_XDECREF(newfree); + Py_XDECREF(allfree); + if (!success) + assert(PyErr_Occurred()); + return success; } static int -analyze_child_block(PySTEntryObject *entry, PyObject *bound, PyObject *free, - PyObject *global, PyObject* child_free) -{ - PyObject *temp_bound = NULL, *temp_global = NULL, *temp_free = NULL; - PyObject *temp; - - /* Copy the bound and global dictionaries. - - These dictionary are used by all blocks enclosed by the - current block. The analyze_block() call modifies these - dictionaries. - - */ - temp_bound = PySet_New(bound); - if (!temp_bound) - goto error; - temp_free = PySet_New(free); - if (!temp_free) - goto error; - temp_global = PySet_New(global); - if (!temp_global) - goto error; - - if (!analyze_block(entry, temp_bound, temp_free, temp_global)) - goto error; - temp = PyNumber_InPlaceOr(child_free, temp_free); - if (!temp) - goto error; - Py_DECREF(temp); - Py_DECREF(temp_bound); - Py_DECREF(temp_free); - Py_DECREF(temp_global); - return 1; +analyze_child_block(PySTEntryObject *entry, PyObject *bound, PyObject *free, + PyObject *global, PyObject* child_free) +{ + PyObject *temp_bound = NULL, *temp_global = NULL, *temp_free = NULL; + PyObject *temp; + + /* Copy the bound and global dictionaries. + + These dictionary are used by all blocks enclosed by the + current block. The analyze_block() call modifies these + dictionaries. + + */ + temp_bound = PySet_New(bound); + if (!temp_bound) + goto error; + temp_free = PySet_New(free); + if (!temp_free) + goto error; + temp_global = PySet_New(global); + if (!temp_global) + goto error; + + if (!analyze_block(entry, temp_bound, temp_free, temp_global)) + goto error; + temp = PyNumber_InPlaceOr(child_free, temp_free); + if (!temp) + goto error; + Py_DECREF(temp); + Py_DECREF(temp_bound); + Py_DECREF(temp_free); + Py_DECREF(temp_global); + return 1; error: - Py_XDECREF(temp_bound); - Py_XDECREF(temp_free); - Py_XDECREF(temp_global); - return 0; + Py_XDECREF(temp_bound); + Py_XDECREF(temp_free); + Py_XDECREF(temp_global); + return 0; } static int symtable_analyze(struct symtable *st) { - PyObject *free, *global; - int r; + PyObject *free, *global; + int r; - free = PySet_New(NULL); - if (!free) - return 0; - global = PySet_New(NULL); - if (!global) { - Py_DECREF(free); - return 0; - } - r = analyze_block(st->st_top, NULL, free, global); - Py_DECREF(free); - Py_DECREF(global); - return r; + free = PySet_New(NULL); + if (!free) + return 0; + global = PySet_New(NULL); + if (!global) { + Py_DECREF(free); + return 0; + } + r = analyze_block(st->st_top, NULL, free, global); + Py_DECREF(free); + Py_DECREF(global); + return r; } static int symtable_warn(struct symtable *st, char *msg, int lineno) { - if (PyErr_WarnExplicit(PyExc_SyntaxWarning, msg, st->st_filename, - lineno, NULL, NULL) < 0) { - if (PyErr_ExceptionMatches(PyExc_SyntaxWarning)) { - PyErr_SetString(PyExc_SyntaxError, msg); - PyErr_SyntaxLocation(st->st_filename, - st->st_cur->ste_lineno); - } - return 0; - } - return 1; + if (PyErr_WarnExplicit(PyExc_SyntaxWarning, msg, st->st_filename, + lineno, NULL, NULL) < 0) { + if (PyErr_ExceptionMatches(PyExc_SyntaxWarning)) { + PyErr_SetString(PyExc_SyntaxError, msg); + PyErr_SyntaxLocation(st->st_filename, + st->st_cur->ste_lineno); + } + return 0; + } + return 1; } /* symtable_enter_block() gets a reference via ste_new. @@ -891,211 +891,211 @@ static int symtable_exit_block(struct symtable *st, void *ast) { - Py_ssize_t end; + Py_ssize_t end; - Py_CLEAR(st->st_cur); - end = PyList_GET_SIZE(st->st_stack) - 1; - if (end >= 0) { - st->st_cur = (PySTEntryObject *)PyList_GET_ITEM(st->st_stack, - end); - if (st->st_cur == NULL) - return 0; - Py_INCREF(st->st_cur); - if (PySequence_DelItem(st->st_stack, end) < 0) - return 0; - } - return 1; + Py_CLEAR(st->st_cur); + end = PyList_GET_SIZE(st->st_stack) - 1; + if (end >= 0) { + st->st_cur = (PySTEntryObject *)PyList_GET_ITEM(st->st_stack, + end); + if (st->st_cur == NULL) + return 0; + Py_INCREF(st->st_cur); + if (PySequence_DelItem(st->st_stack, end) < 0) + return 0; + } + return 1; } static int -symtable_enter_block(struct symtable *st, identifier name, _Py_block_ty block, - void *ast, int lineno) -{ - PySTEntryObject *prev = NULL; - - if (st->st_cur) { - prev = st->st_cur; - if (PyList_Append(st->st_stack, (PyObject *)st->st_cur) < 0) { - return 0; - } - Py_DECREF(st->st_cur); - } - st->st_cur = ste_new(st, name, block, ast, lineno); - if (st->st_cur == NULL) - return 0; - if (name == GET_IDENTIFIER(top)) - st->st_global = st->st_cur->ste_symbols; - if (prev) { - if (PyList_Append(prev->ste_children, - (PyObject *)st->st_cur) < 0) { - return 0; - } - } - return 1; +symtable_enter_block(struct symtable *st, identifier name, _Py_block_ty block, + void *ast, int lineno) +{ + PySTEntryObject *prev = NULL; + + if (st->st_cur) { + prev = st->st_cur; + if (PyList_Append(st->st_stack, (PyObject *)st->st_cur) < 0) { + return 0; + } + Py_DECREF(st->st_cur); + } + st->st_cur = ste_new(st, name, block, ast, lineno); + if (st->st_cur == NULL) + return 0; + if (name == GET_IDENTIFIER(top)) + st->st_global = st->st_cur->ste_symbols; + if (prev) { + if (PyList_Append(prev->ste_children, + (PyObject *)st->st_cur) < 0) { + return 0; + } + } + return 1; } static long symtable_lookup(struct symtable *st, PyObject *name) { - PyObject *o; - PyObject *mangled = _Py_Mangle(st->st_private, name); - if (!mangled) - return 0; - o = PyDict_GetItem(st->st_cur->ste_symbols, mangled); - Py_DECREF(mangled); - if (!o) - return 0; - return PyLong_AsLong(o); + PyObject *o; + PyObject *mangled = _Py_Mangle(st->st_private, name); + if (!mangled) + return 0; + o = PyDict_GetItem(st->st_cur->ste_symbols, mangled); + Py_DECREF(mangled); + if (!o) + return 0; + return PyLong_AsLong(o); } static int -symtable_add_def(struct symtable *st, PyObject *name, int flag) -{ - PyObject *o; - PyObject *dict; - long val; - PyObject *mangled = _Py_Mangle(st->st_private, name); - - - if (!mangled) - return 0; - dict = st->st_cur->ste_symbols; - if ((o = PyDict_GetItem(dict, mangled))) { - val = PyLong_AS_LONG(o); - if ((flag & DEF_PARAM) && (val & DEF_PARAM)) { - /* Is it better to use 'mangled' or 'name' here? */ - PyErr_Format(PyExc_SyntaxError, DUPLICATE_ARGUMENT, name); - PyErr_SyntaxLocation(st->st_filename, - st->st_cur->ste_lineno); - goto error; - } - val |= flag; - } else - val = flag; - o = PyLong_FromLong(val); +symtable_add_def(struct symtable *st, PyObject *name, int flag) +{ + PyObject *o; + PyObject *dict; + long val; + PyObject *mangled = _Py_Mangle(st->st_private, name); + + + if (!mangled) + return 0; + dict = st->st_cur->ste_symbols; + if ((o = PyDict_GetItem(dict, mangled))) { + val = PyLong_AS_LONG(o); + if ((flag & DEF_PARAM) && (val & DEF_PARAM)) { + /* Is it better to use 'mangled' or 'name' here? */ + PyErr_Format(PyExc_SyntaxError, DUPLICATE_ARGUMENT, name); + PyErr_SyntaxLocation(st->st_filename, + st->st_cur->ste_lineno); + goto error; + } + val |= flag; + } else + val = flag; + o = PyLong_FromLong(val); + if (o == NULL) + goto error; + if (PyDict_SetItem(dict, mangled, o) < 0) { + Py_DECREF(o); + goto error; + } + Py_DECREF(o); + + if (flag & DEF_PARAM) { + if (PyList_Append(st->st_cur->ste_varnames, mangled) < 0) + goto error; + } else if (flag & DEF_GLOBAL) { + /* XXX need to update DEF_GLOBAL for other flags too; + perhaps only DEF_FREE_GLOBAL */ + val = flag; + if ((o = PyDict_GetItem(st->st_global, mangled))) { + val |= PyLong_AS_LONG(o); + } + o = PyLong_FromLong(val); if (o == NULL) - goto error; - if (PyDict_SetItem(dict, mangled, o) < 0) { - Py_DECREF(o); - goto error; - } - Py_DECREF(o); - - if (flag & DEF_PARAM) { - if (PyList_Append(st->st_cur->ste_varnames, mangled) < 0) - goto error; - } else if (flag & DEF_GLOBAL) { - /* XXX need to update DEF_GLOBAL for other flags too; - perhaps only DEF_FREE_GLOBAL */ - val = flag; - if ((o = PyDict_GetItem(st->st_global, mangled))) { - val |= PyLong_AS_LONG(o); - } - o = PyLong_FromLong(val); - if (o == NULL) - goto error; - if (PyDict_SetItem(st->st_global, mangled, o) < 0) { - Py_DECREF(o); - goto error; - } - Py_DECREF(o); - } - Py_DECREF(mangled); - return 1; + goto error; + if (PyDict_SetItem(st->st_global, mangled, o) < 0) { + Py_DECREF(o); + goto error; + } + Py_DECREF(o); + } + Py_DECREF(mangled); + return 1; error: - Py_DECREF(mangled); - return 0; + Py_DECREF(mangled); + return 0; } /* VISIT, VISIT_SEQ and VIST_SEQ_TAIL take an ASDL type as their second argument. They use the ASDL name to synthesize the name of the C type and the visit - function. - + function. + VISIT_SEQ_TAIL permits the start of an ASDL sequence to be skipped, which is useful if the first node in the sequence requires special treatment. */ #define VISIT(ST, TYPE, V) \ - if (!symtable_visit_ ## TYPE((ST), (V))) \ - return 0; + if (!symtable_visit_ ## TYPE((ST), (V))) \ + return 0; #define VISIT_IN_BLOCK(ST, TYPE, V, S) \ - if (!symtable_visit_ ## TYPE((ST), (V))) { \ - symtable_exit_block((ST), (S)); \ - return 0; \ - } + if (!symtable_visit_ ## TYPE((ST), (V))) { \ + symtable_exit_block((ST), (S)); \ + return 0; \ + } #define VISIT_SEQ(ST, TYPE, SEQ) { \ - int i; \ - asdl_seq *seq = (SEQ); /* avoid variable capture */ \ - for (i = 0; i < asdl_seq_LEN(seq); i++) { \ - TYPE ## _ty elt = (TYPE ## _ty)asdl_seq_GET(seq, i); \ - if (!symtable_visit_ ## TYPE((ST), elt)) \ - return 0; \ - } \ + int i; \ + asdl_seq *seq = (SEQ); /* avoid variable capture */ \ + for (i = 0; i < asdl_seq_LEN(seq); i++) { \ + TYPE ## _ty elt = (TYPE ## _ty)asdl_seq_GET(seq, i); \ + if (!symtable_visit_ ## TYPE((ST), elt)) \ + return 0; \ + } \ } #define VISIT_SEQ_IN_BLOCK(ST, TYPE, SEQ, S) { \ - int i; \ - asdl_seq *seq = (SEQ); /* avoid variable capture */ \ - for (i = 0; i < asdl_seq_LEN(seq); i++) { \ - TYPE ## _ty elt = (TYPE ## _ty)asdl_seq_GET(seq, i); \ - if (!symtable_visit_ ## TYPE((ST), elt)) { \ - symtable_exit_block((ST), (S)); \ - return 0; \ - } \ - } \ + int i; \ + asdl_seq *seq = (SEQ); /* avoid variable capture */ \ + for (i = 0; i < asdl_seq_LEN(seq); i++) { \ + TYPE ## _ty elt = (TYPE ## _ty)asdl_seq_GET(seq, i); \ + if (!symtable_visit_ ## TYPE((ST), elt)) { \ + symtable_exit_block((ST), (S)); \ + return 0; \ + } \ + } \ } #define VISIT_SEQ_TAIL(ST, TYPE, SEQ, START) { \ - int i; \ - asdl_seq *seq = (SEQ); /* avoid variable capture */ \ - for (i = (START); i < asdl_seq_LEN(seq); i++) { \ - TYPE ## _ty elt = (TYPE ## _ty)asdl_seq_GET(seq, i); \ - if (!symtable_visit_ ## TYPE((ST), elt)) \ - return 0; \ - } \ + int i; \ + asdl_seq *seq = (SEQ); /* avoid variable capture */ \ + for (i = (START); i < asdl_seq_LEN(seq); i++) { \ + TYPE ## _ty elt = (TYPE ## _ty)asdl_seq_GET(seq, i); \ + if (!symtable_visit_ ## TYPE((ST), elt)) \ + return 0; \ + } \ } #define VISIT_SEQ_TAIL_IN_BLOCK(ST, TYPE, SEQ, START, S) { \ - int i; \ - asdl_seq *seq = (SEQ); /* avoid variable capture */ \ - for (i = (START); i < asdl_seq_LEN(seq); i++) { \ - TYPE ## _ty elt = (TYPE ## _ty)asdl_seq_GET(seq, i); \ - if (!symtable_visit_ ## TYPE((ST), elt)) { \ - symtable_exit_block((ST), (S)); \ - return 0; \ - } \ - } \ + int i; \ + asdl_seq *seq = (SEQ); /* avoid variable capture */ \ + for (i = (START); i < asdl_seq_LEN(seq); i++) { \ + TYPE ## _ty elt = (TYPE ## _ty)asdl_seq_GET(seq, i); \ + if (!symtable_visit_ ## TYPE((ST), elt)) { \ + symtable_exit_block((ST), (S)); \ + return 0; \ + } \ + } \ } #define VISIT_KWONLYDEFAULTS(ST, KW_DEFAULTS) { \ - int i = 0; \ - asdl_seq *seq = (KW_DEFAULTS); /* avoid variable capture */ \ - for (i = 0; i < asdl_seq_LEN(seq); i++) { \ - expr_ty elt = (expr_ty)asdl_seq_GET(seq, i); \ - if (!elt) continue; /* can be NULL */ \ - if (!symtable_visit_expr((ST), elt)) \ - return 0; \ - } \ + int i = 0; \ + asdl_seq *seq = (KW_DEFAULTS); /* avoid variable capture */ \ + for (i = 0; i < asdl_seq_LEN(seq); i++) { \ + expr_ty elt = (expr_ty)asdl_seq_GET(seq, i); \ + if (!elt) continue; /* can be NULL */ \ + if (!symtable_visit_expr((ST), elt)) \ + return 0; \ + } \ } static int symtable_new_tmpname(struct symtable *st) { - char tmpname[256]; - identifier tmp; + char tmpname[256]; + identifier tmp; - PyOS_snprintf(tmpname, sizeof(tmpname), "_[%d]", - ++st->st_cur->ste_tmpname); - tmp = PyUnicode_InternFromString(tmpname); - if (!tmp) - return 0; - if (!symtable_add_def(st, tmp, DEF_LOCAL)) - return 0; - Py_DECREF(tmp); - return 1; + PyOS_snprintf(tmpname, sizeof(tmpname), "_[%d]", + ++st->st_cur->ste_tmpname); + tmp = PyUnicode_InternFromString(tmpname); + if (!tmp) + return 0; + if (!symtable_add_def(st, tmp, DEF_LOCAL)) + return 0; + Py_DECREF(tmp); + return 1; } @@ -1103,586 +1103,586 @@ static int symtable_visit_stmt(struct symtable *st, stmt_ty s) { - switch (s->kind) { - case FunctionDef_kind: - if (!symtable_add_def(st, s->v.FunctionDef.name, DEF_LOCAL)) - return 0; - if (s->v.FunctionDef.args->defaults) - VISIT_SEQ(st, expr, s->v.FunctionDef.args->defaults); - if (s->v.FunctionDef.args->kw_defaults) - VISIT_KWONLYDEFAULTS(st, - s->v.FunctionDef.args->kw_defaults); - if (!symtable_visit_annotations(st, s)) - return 0; - if (s->v.FunctionDef.decorator_list) - VISIT_SEQ(st, expr, s->v.FunctionDef.decorator_list); - if (!symtable_enter_block(st, s->v.FunctionDef.name, - FunctionBlock, (void *)s, s->lineno)) - return 0; - VISIT_IN_BLOCK(st, arguments, s->v.FunctionDef.args, s); - VISIT_SEQ_IN_BLOCK(st, stmt, s->v.FunctionDef.body, s); - if (!symtable_exit_block(st, s)) - return 0; - break; - case ClassDef_kind: { - PyObject *tmp; - if (!symtable_add_def(st, s->v.ClassDef.name, DEF_LOCAL)) - return 0; - VISIT_SEQ(st, expr, s->v.ClassDef.bases); - VISIT_SEQ(st, keyword, s->v.ClassDef.keywords); - if (s->v.ClassDef.starargs) - VISIT(st, expr, s->v.ClassDef.starargs); - if (s->v.ClassDef.kwargs) - VISIT(st, expr, s->v.ClassDef.kwargs); - if (s->v.ClassDef.decorator_list) - VISIT_SEQ(st, expr, s->v.ClassDef.decorator_list); - if (!symtable_enter_block(st, s->v.ClassDef.name, ClassBlock, - (void *)s, s->lineno)) - return 0; - if (!GET_IDENTIFIER(__class__) || - !symtable_add_def(st, __class__, DEF_LOCAL) || - !GET_IDENTIFIER(__locals__) || - !symtable_add_def(st, __locals__, DEF_PARAM)) { - symtable_exit_block(st, s); - return 0; - } - tmp = st->st_private; - st->st_private = s->v.ClassDef.name; - VISIT_SEQ_IN_BLOCK(st, stmt, s->v.ClassDef.body, s); - st->st_private = tmp; - if (!symtable_exit_block(st, s)) - return 0; - break; - } - case Return_kind: - if (s->v.Return.value) { - VISIT(st, expr, s->v.Return.value); - st->st_cur->ste_returns_value = 1; - if (st->st_cur->ste_generator) { - PyErr_SetString(PyExc_SyntaxError, - RETURN_VAL_IN_GENERATOR); - PyErr_SyntaxLocation(st->st_filename, - s->lineno); - return 0; - } - } - break; - case Delete_kind: - VISIT_SEQ(st, expr, s->v.Delete.targets); - break; - case Assign_kind: - VISIT_SEQ(st, expr, s->v.Assign.targets); - VISIT(st, expr, s->v.Assign.value); - break; - case AugAssign_kind: - VISIT(st, expr, s->v.AugAssign.target); - VISIT(st, expr, s->v.AugAssign.value); - break; - case For_kind: - VISIT(st, expr, s->v.For.target); - VISIT(st, expr, s->v.For.iter); - VISIT_SEQ(st, stmt, s->v.For.body); - if (s->v.For.orelse) - VISIT_SEQ(st, stmt, s->v.For.orelse); - break; - case While_kind: - VISIT(st, expr, s->v.While.test); - VISIT_SEQ(st, stmt, s->v.While.body); - if (s->v.While.orelse) - VISIT_SEQ(st, stmt, s->v.While.orelse); - break; - case If_kind: - /* XXX if 0: and lookup_yield() hacks */ - VISIT(st, expr, s->v.If.test); - VISIT_SEQ(st, stmt, s->v.If.body); - if (s->v.If.orelse) - VISIT_SEQ(st, stmt, s->v.If.orelse); - break; - case Raise_kind: - if (s->v.Raise.exc) { - VISIT(st, expr, s->v.Raise.exc); - if (s->v.Raise.cause) { - VISIT(st, expr, s->v.Raise.cause); + switch (s->kind) { + case FunctionDef_kind: + if (!symtable_add_def(st, s->v.FunctionDef.name, DEF_LOCAL)) + return 0; + if (s->v.FunctionDef.args->defaults) + VISIT_SEQ(st, expr, s->v.FunctionDef.args->defaults); + if (s->v.FunctionDef.args->kw_defaults) + VISIT_KWONLYDEFAULTS(st, + s->v.FunctionDef.args->kw_defaults); + if (!symtable_visit_annotations(st, s)) + return 0; + if (s->v.FunctionDef.decorator_list) + VISIT_SEQ(st, expr, s->v.FunctionDef.decorator_list); + if (!symtable_enter_block(st, s->v.FunctionDef.name, + FunctionBlock, (void *)s, s->lineno)) + return 0; + VISIT_IN_BLOCK(st, arguments, s->v.FunctionDef.args, s); + VISIT_SEQ_IN_BLOCK(st, stmt, s->v.FunctionDef.body, s); + if (!symtable_exit_block(st, s)) + return 0; + break; + case ClassDef_kind: { + PyObject *tmp; + if (!symtable_add_def(st, s->v.ClassDef.name, DEF_LOCAL)) + return 0; + VISIT_SEQ(st, expr, s->v.ClassDef.bases); + VISIT_SEQ(st, keyword, s->v.ClassDef.keywords); + if (s->v.ClassDef.starargs) + VISIT(st, expr, s->v.ClassDef.starargs); + if (s->v.ClassDef.kwargs) + VISIT(st, expr, s->v.ClassDef.kwargs); + if (s->v.ClassDef.decorator_list) + VISIT_SEQ(st, expr, s->v.ClassDef.decorator_list); + if (!symtable_enter_block(st, s->v.ClassDef.name, ClassBlock, + (void *)s, s->lineno)) + return 0; + if (!GET_IDENTIFIER(__class__) || + !symtable_add_def(st, __class__, DEF_LOCAL) || + !GET_IDENTIFIER(__locals__) || + !symtable_add_def(st, __locals__, DEF_PARAM)) { + symtable_exit_block(st, s); + return 0; + } + tmp = st->st_private; + st->st_private = s->v.ClassDef.name; + VISIT_SEQ_IN_BLOCK(st, stmt, s->v.ClassDef.body, s); + st->st_private = tmp; + if (!symtable_exit_block(st, s)) + return 0; + break; + } + case Return_kind: + if (s->v.Return.value) { + VISIT(st, expr, s->v.Return.value); + st->st_cur->ste_returns_value = 1; + if (st->st_cur->ste_generator) { + PyErr_SetString(PyExc_SyntaxError, + RETURN_VAL_IN_GENERATOR); + PyErr_SyntaxLocation(st->st_filename, + s->lineno); + return 0; } - } - break; - case TryExcept_kind: - VISIT_SEQ(st, stmt, s->v.TryExcept.body); - VISIT_SEQ(st, stmt, s->v.TryExcept.orelse); - VISIT_SEQ(st, excepthandler, s->v.TryExcept.handlers); - break; - case TryFinally_kind: - VISIT_SEQ(st, stmt, s->v.TryFinally.body); - VISIT_SEQ(st, stmt, s->v.TryFinally.finalbody); - break; - case Assert_kind: - VISIT(st, expr, s->v.Assert.test); - if (s->v.Assert.msg) - VISIT(st, expr, s->v.Assert.msg); - break; - case Import_kind: - VISIT_SEQ(st, alias, s->v.Import.names); - /* XXX Don't have the lineno available inside - visit_alias */ - if (st->st_cur->ste_unoptimized && !st->st_cur->ste_opt_lineno) - st->st_cur->ste_opt_lineno = s->lineno; - break; - case ImportFrom_kind: - VISIT_SEQ(st, alias, s->v.ImportFrom.names); - /* XXX Don't have the lineno available inside - visit_alias */ - if (st->st_cur->ste_unoptimized && !st->st_cur->ste_opt_lineno) - st->st_cur->ste_opt_lineno = s->lineno; - break; - case Global_kind: { - int i; - asdl_seq *seq = s->v.Global.names; - for (i = 0; i < asdl_seq_LEN(seq); i++) { - identifier name = (identifier)asdl_seq_GET(seq, i); - char *c_name = _PyUnicode_AsString(name); - long cur = symtable_lookup(st, name); - if (cur < 0) - return 0; - if (cur & (DEF_LOCAL | USE)) { - char buf[256]; - if (cur & DEF_LOCAL) - PyOS_snprintf(buf, sizeof(buf), - GLOBAL_AFTER_ASSIGN, - c_name); - else - PyOS_snprintf(buf, sizeof(buf), - GLOBAL_AFTER_USE, - c_name); - if (!symtable_warn(st, buf, s->lineno)) - return 0; - } - if (!symtable_add_def(st, name, DEF_GLOBAL)) - return 0; - } - break; - } - case Nonlocal_kind: { - int i; - asdl_seq *seq = s->v.Nonlocal.names; - for (i = 0; i < asdl_seq_LEN(seq); i++) { - identifier name = (identifier)asdl_seq_GET(seq, i); - char *c_name = _PyUnicode_AsString(name); - long cur = symtable_lookup(st, name); - if (cur < 0) - return 0; - if (cur & (DEF_LOCAL | USE)) { - char buf[256]; - if (cur & DEF_LOCAL) - PyOS_snprintf(buf, sizeof(buf), - NONLOCAL_AFTER_ASSIGN, - c_name); - else - PyOS_snprintf(buf, sizeof(buf), - NONLOCAL_AFTER_USE, - c_name); - if (!symtable_warn(st, buf, s->lineno)) - return 0; - } - if (!symtable_add_def(st, name, DEF_NONLOCAL)) - return 0; - } - break; - } - case Expr_kind: - VISIT(st, expr, s->v.Expr.value); - break; - case Pass_kind: - case Break_kind: - case Continue_kind: - /* nothing to do here */ - break; - case With_kind: - if (!symtable_new_tmpname(st)) - return 0; - VISIT(st, expr, s->v.With.context_expr); - if (s->v.With.optional_vars) { - if (!symtable_new_tmpname(st)) - return 0; - VISIT(st, expr, s->v.With.optional_vars); - } - VISIT_SEQ(st, stmt, s->v.With.body); - break; - } - return 1; + } + break; + case Delete_kind: + VISIT_SEQ(st, expr, s->v.Delete.targets); + break; + case Assign_kind: + VISIT_SEQ(st, expr, s->v.Assign.targets); + VISIT(st, expr, s->v.Assign.value); + break; + case AugAssign_kind: + VISIT(st, expr, s->v.AugAssign.target); + VISIT(st, expr, s->v.AugAssign.value); + break; + case For_kind: + VISIT(st, expr, s->v.For.target); + VISIT(st, expr, s->v.For.iter); + VISIT_SEQ(st, stmt, s->v.For.body); + if (s->v.For.orelse) + VISIT_SEQ(st, stmt, s->v.For.orelse); + break; + case While_kind: + VISIT(st, expr, s->v.While.test); + VISIT_SEQ(st, stmt, s->v.While.body); + if (s->v.While.orelse) + VISIT_SEQ(st, stmt, s->v.While.orelse); + break; + case If_kind: + /* XXX if 0: and lookup_yield() hacks */ + VISIT(st, expr, s->v.If.test); + VISIT_SEQ(st, stmt, s->v.If.body); + if (s->v.If.orelse) + VISIT_SEQ(st, stmt, s->v.If.orelse); + break; + case Raise_kind: + if (s->v.Raise.exc) { + VISIT(st, expr, s->v.Raise.exc); + if (s->v.Raise.cause) { + VISIT(st, expr, s->v.Raise.cause); + } + } + break; + case TryExcept_kind: + VISIT_SEQ(st, stmt, s->v.TryExcept.body); + VISIT_SEQ(st, stmt, s->v.TryExcept.orelse); + VISIT_SEQ(st, excepthandler, s->v.TryExcept.handlers); + break; + case TryFinally_kind: + VISIT_SEQ(st, stmt, s->v.TryFinally.body); + VISIT_SEQ(st, stmt, s->v.TryFinally.finalbody); + break; + case Assert_kind: + VISIT(st, expr, s->v.Assert.test); + if (s->v.Assert.msg) + VISIT(st, expr, s->v.Assert.msg); + break; + case Import_kind: + VISIT_SEQ(st, alias, s->v.Import.names); + /* XXX Don't have the lineno available inside + visit_alias */ + if (st->st_cur->ste_unoptimized && !st->st_cur->ste_opt_lineno) + st->st_cur->ste_opt_lineno = s->lineno; + break; + case ImportFrom_kind: + VISIT_SEQ(st, alias, s->v.ImportFrom.names); + /* XXX Don't have the lineno available inside + visit_alias */ + if (st->st_cur->ste_unoptimized && !st->st_cur->ste_opt_lineno) + st->st_cur->ste_opt_lineno = s->lineno; + break; + case Global_kind: { + int i; + asdl_seq *seq = s->v.Global.names; + for (i = 0; i < asdl_seq_LEN(seq); i++) { + identifier name = (identifier)asdl_seq_GET(seq, i); + char *c_name = _PyUnicode_AsString(name); + long cur = symtable_lookup(st, name); + if (cur < 0) + return 0; + if (cur & (DEF_LOCAL | USE)) { + char buf[256]; + if (cur & DEF_LOCAL) + PyOS_snprintf(buf, sizeof(buf), + GLOBAL_AFTER_ASSIGN, + c_name); + else + PyOS_snprintf(buf, sizeof(buf), + GLOBAL_AFTER_USE, + c_name); + if (!symtable_warn(st, buf, s->lineno)) + return 0; + } + if (!symtable_add_def(st, name, DEF_GLOBAL)) + return 0; + } + break; + } + case Nonlocal_kind: { + int i; + asdl_seq *seq = s->v.Nonlocal.names; + for (i = 0; i < asdl_seq_LEN(seq); i++) { + identifier name = (identifier)asdl_seq_GET(seq, i); + char *c_name = _PyUnicode_AsString(name); + long cur = symtable_lookup(st, name); + if (cur < 0) + return 0; + if (cur & (DEF_LOCAL | USE)) { + char buf[256]; + if (cur & DEF_LOCAL) + PyOS_snprintf(buf, sizeof(buf), + NONLOCAL_AFTER_ASSIGN, + c_name); + else + PyOS_snprintf(buf, sizeof(buf), + NONLOCAL_AFTER_USE, + c_name); + if (!symtable_warn(st, buf, s->lineno)) + return 0; + } + if (!symtable_add_def(st, name, DEF_NONLOCAL)) + return 0; + } + break; + } + case Expr_kind: + VISIT(st, expr, s->v.Expr.value); + break; + case Pass_kind: + case Break_kind: + case Continue_kind: + /* nothing to do here */ + break; + case With_kind: + if (!symtable_new_tmpname(st)) + return 0; + VISIT(st, expr, s->v.With.context_expr); + if (s->v.With.optional_vars) { + if (!symtable_new_tmpname(st)) + return 0; + VISIT(st, expr, s->v.With.optional_vars); + } + VISIT_SEQ(st, stmt, s->v.With.body); + break; + } + return 1; } -static int +static int symtable_visit_expr(struct symtable *st, expr_ty e) { - switch (e->kind) { - case BoolOp_kind: - VISIT_SEQ(st, expr, e->v.BoolOp.values); - break; - case BinOp_kind: - VISIT(st, expr, e->v.BinOp.left); - VISIT(st, expr, e->v.BinOp.right); - break; - case UnaryOp_kind: - VISIT(st, expr, e->v.UnaryOp.operand); - break; - case Lambda_kind: { - if (!GET_IDENTIFIER(lambda) || - !symtable_add_def(st, lambda, DEF_LOCAL)) - return 0; - if (e->v.Lambda.args->defaults) - VISIT_SEQ(st, expr, e->v.Lambda.args->defaults); - if (!symtable_enter_block(st, lambda, - FunctionBlock, (void *)e, e->lineno)) - return 0; - VISIT_IN_BLOCK(st, arguments, e->v.Lambda.args, (void*)e); - VISIT_IN_BLOCK(st, expr, e->v.Lambda.body, (void*)e); - if (!symtable_exit_block(st, (void *)e)) - return 0; - break; - } - case IfExp_kind: - VISIT(st, expr, e->v.IfExp.test); - VISIT(st, expr, e->v.IfExp.body); - VISIT(st, expr, e->v.IfExp.orelse); - break; - case Dict_kind: - VISIT_SEQ(st, expr, e->v.Dict.keys); - VISIT_SEQ(st, expr, e->v.Dict.values); - break; - case Set_kind: - VISIT_SEQ(st, expr, e->v.Set.elts); - break; - case GeneratorExp_kind: - if (!symtable_visit_genexp(st, e)) - return 0; - break; - case ListComp_kind: - if (!symtable_visit_listcomp(st, e)) - return 0; - break; - case SetComp_kind: - if (!symtable_visit_setcomp(st, e)) - return 0; - break; - case DictComp_kind: - if (!symtable_visit_dictcomp(st, e)) - return 0; - break; - case Yield_kind: - if (e->v.Yield.value) - VISIT(st, expr, e->v.Yield.value); - st->st_cur->ste_generator = 1; - if (st->st_cur->ste_returns_value) { - PyErr_SetString(PyExc_SyntaxError, - RETURN_VAL_IN_GENERATOR); - PyErr_SyntaxLocation(st->st_filename, - e->lineno); - return 0; - } - break; - case Compare_kind: - VISIT(st, expr, e->v.Compare.left); - VISIT_SEQ(st, expr, e->v.Compare.comparators); - break; - case Call_kind: - VISIT(st, expr, e->v.Call.func); - VISIT_SEQ(st, expr, e->v.Call.args); - VISIT_SEQ(st, keyword, e->v.Call.keywords); - if (e->v.Call.starargs) - VISIT(st, expr, e->v.Call.starargs); - if (e->v.Call.kwargs) - VISIT(st, expr, e->v.Call.kwargs); - break; - case Num_kind: - case Str_kind: - case Bytes_kind: - case Ellipsis_kind: - /* Nothing to do here. */ - break; - /* The following exprs can be assignment targets. */ - case Attribute_kind: - VISIT(st, expr, e->v.Attribute.value); - break; - case Subscript_kind: - VISIT(st, expr, e->v.Subscript.value); - VISIT(st, slice, e->v.Subscript.slice); - break; - case Starred_kind: - VISIT(st, expr, e->v.Starred.value); - break; - case Name_kind: - if (!symtable_add_def(st, e->v.Name.id, - e->v.Name.ctx == Load ? USE : DEF_LOCAL)) - return 0; - /* Special-case super: it counts as a use of __class__ */ - if (e->v.Name.ctx == Load && - st->st_cur->ste_type == FunctionBlock && - !PyUnicode_CompareWithASCIIString(e->v.Name.id, "super")) { - if (!GET_IDENTIFIER(__class__) || - !symtable_add_def(st, __class__, USE)) - return 0; - } - break; - /* child nodes of List and Tuple will have expr_context set */ - case List_kind: - VISIT_SEQ(st, expr, e->v.List.elts); - break; - case Tuple_kind: - VISIT_SEQ(st, expr, e->v.Tuple.elts); - break; - } - return 1; + switch (e->kind) { + case BoolOp_kind: + VISIT_SEQ(st, expr, e->v.BoolOp.values); + break; + case BinOp_kind: + VISIT(st, expr, e->v.BinOp.left); + VISIT(st, expr, e->v.BinOp.right); + break; + case UnaryOp_kind: + VISIT(st, expr, e->v.UnaryOp.operand); + break; + case Lambda_kind: { + if (!GET_IDENTIFIER(lambda) || + !symtable_add_def(st, lambda, DEF_LOCAL)) + return 0; + if (e->v.Lambda.args->defaults) + VISIT_SEQ(st, expr, e->v.Lambda.args->defaults); + if (!symtable_enter_block(st, lambda, + FunctionBlock, (void *)e, e->lineno)) + return 0; + VISIT_IN_BLOCK(st, arguments, e->v.Lambda.args, (void*)e); + VISIT_IN_BLOCK(st, expr, e->v.Lambda.body, (void*)e); + if (!symtable_exit_block(st, (void *)e)) + return 0; + break; + } + case IfExp_kind: + VISIT(st, expr, e->v.IfExp.test); + VISIT(st, expr, e->v.IfExp.body); + VISIT(st, expr, e->v.IfExp.orelse); + break; + case Dict_kind: + VISIT_SEQ(st, expr, e->v.Dict.keys); + VISIT_SEQ(st, expr, e->v.Dict.values); + break; + case Set_kind: + VISIT_SEQ(st, expr, e->v.Set.elts); + break; + case GeneratorExp_kind: + if (!symtable_visit_genexp(st, e)) + return 0; + break; + case ListComp_kind: + if (!symtable_visit_listcomp(st, e)) + return 0; + break; + case SetComp_kind: + if (!symtable_visit_setcomp(st, e)) + return 0; + break; + case DictComp_kind: + if (!symtable_visit_dictcomp(st, e)) + return 0; + break; + case Yield_kind: + if (e->v.Yield.value) + VISIT(st, expr, e->v.Yield.value); + st->st_cur->ste_generator = 1; + if (st->st_cur->ste_returns_value) { + PyErr_SetString(PyExc_SyntaxError, + RETURN_VAL_IN_GENERATOR); + PyErr_SyntaxLocation(st->st_filename, + e->lineno); + return 0; + } + break; + case Compare_kind: + VISIT(st, expr, e->v.Compare.left); + VISIT_SEQ(st, expr, e->v.Compare.comparators); + break; + case Call_kind: + VISIT(st, expr, e->v.Call.func); + VISIT_SEQ(st, expr, e->v.Call.args); + VISIT_SEQ(st, keyword, e->v.Call.keywords); + if (e->v.Call.starargs) + VISIT(st, expr, e->v.Call.starargs); + if (e->v.Call.kwargs) + VISIT(st, expr, e->v.Call.kwargs); + break; + case Num_kind: + case Str_kind: + case Bytes_kind: + case Ellipsis_kind: + /* Nothing to do here. */ + break; + /* The following exprs can be assignment targets. */ + case Attribute_kind: + VISIT(st, expr, e->v.Attribute.value); + break; + case Subscript_kind: + VISIT(st, expr, e->v.Subscript.value); + VISIT(st, slice, e->v.Subscript.slice); + break; + case Starred_kind: + VISIT(st, expr, e->v.Starred.value); + break; + case Name_kind: + if (!symtable_add_def(st, e->v.Name.id, + e->v.Name.ctx == Load ? USE : DEF_LOCAL)) + return 0; + /* Special-case super: it counts as a use of __class__ */ + if (e->v.Name.ctx == Load && + st->st_cur->ste_type == FunctionBlock && + !PyUnicode_CompareWithASCIIString(e->v.Name.id, "super")) { + if (!GET_IDENTIFIER(__class__) || + !symtable_add_def(st, __class__, USE)) + return 0; + } + break; + /* child nodes of List and Tuple will have expr_context set */ + case List_kind: + VISIT_SEQ(st, expr, e->v.List.elts); + break; + case Tuple_kind: + VISIT_SEQ(st, expr, e->v.Tuple.elts); + break; + } + return 1; } static int symtable_implicit_arg(struct symtable *st, int pos) { - PyObject *id = PyUnicode_FromFormat(".%d", pos); - if (id == NULL) - return 0; - if (!symtable_add_def(st, id, DEF_PARAM)) { - Py_DECREF(id); - return 0; - } - Py_DECREF(id); - return 1; + PyObject *id = PyUnicode_FromFormat(".%d", pos); + if (id == NULL) + return 0; + if (!symtable_add_def(st, id, DEF_PARAM)) { + Py_DECREF(id); + return 0; + } + Py_DECREF(id); + return 1; } -static int +static int symtable_visit_params(struct symtable *st, asdl_seq *args) { - int i; + int i; - if (!args) - return -1; - - for (i = 0; i < asdl_seq_LEN(args); i++) { - arg_ty arg = (arg_ty)asdl_seq_GET(args, i); - if (!symtable_add_def(st, arg->arg, DEF_PARAM)) - return 0; - } + if (!args) + return -1; - return 1; + for (i = 0; i < asdl_seq_LEN(args); i++) { + arg_ty arg = (arg_ty)asdl_seq_GET(args, i); + if (!symtable_add_def(st, arg->arg, DEF_PARAM)) + return 0; + } + + return 1; } -static int +static int symtable_visit_argannotations(struct symtable *st, asdl_seq *args) { - int i; + int i; - if (!args) - return -1; - - for (i = 0; i < asdl_seq_LEN(args); i++) { - arg_ty arg = (arg_ty)asdl_seq_GET(args, i); - if (arg->annotation) - VISIT(st, expr, arg->annotation); - } + if (!args) + return -1; - return 1; + for (i = 0; i < asdl_seq_LEN(args); i++) { + arg_ty arg = (arg_ty)asdl_seq_GET(args, i); + if (arg->annotation) + VISIT(st, expr, arg->annotation); + } + + return 1; } static int symtable_visit_annotations(struct symtable *st, stmt_ty s) { - arguments_ty a = s->v.FunctionDef.args; - - if (a->args && !symtable_visit_argannotations(st, a->args)) - return 0; - if (a->varargannotation) - VISIT(st, expr, a->varargannotation); - if (a->kwargannotation) - VISIT(st, expr, a->kwargannotation); - if (a->kwonlyargs && !symtable_visit_argannotations(st, a->kwonlyargs)) - return 0; - if (s->v.FunctionDef.returns) - VISIT(st, expr, s->v.FunctionDef.returns); - return 1; + arguments_ty a = s->v.FunctionDef.args; + + if (a->args && !symtable_visit_argannotations(st, a->args)) + return 0; + if (a->varargannotation) + VISIT(st, expr, a->varargannotation); + if (a->kwargannotation) + VISIT(st, expr, a->kwargannotation); + if (a->kwonlyargs && !symtable_visit_argannotations(st, a->kwonlyargs)) + return 0; + if (s->v.FunctionDef.returns) + VISIT(st, expr, s->v.FunctionDef.returns); + return 1; } -static int +static int symtable_visit_arguments(struct symtable *st, arguments_ty a) { - /* skip default arguments inside function block - XXX should ast be different? - */ - if (a->args && !symtable_visit_params(st, a->args)) - return 0; - if (a->kwonlyargs && !symtable_visit_params(st, a->kwonlyargs)) - return 0; - if (a->vararg) { - if (!symtable_add_def(st, a->vararg, DEF_PARAM)) - return 0; - st->st_cur->ste_varargs = 1; - } - if (a->kwarg) { - if (!symtable_add_def(st, a->kwarg, DEF_PARAM)) - return 0; - st->st_cur->ste_varkeywords = 1; - } - return 1; + /* skip default arguments inside function block + XXX should ast be different? + */ + if (a->args && !symtable_visit_params(st, a->args)) + return 0; + if (a->kwonlyargs && !symtable_visit_params(st, a->kwonlyargs)) + return 0; + if (a->vararg) { + if (!symtable_add_def(st, a->vararg, DEF_PARAM)) + return 0; + st->st_cur->ste_varargs = 1; + } + if (a->kwarg) { + if (!symtable_add_def(st, a->kwarg, DEF_PARAM)) + return 0; + st->st_cur->ste_varkeywords = 1; + } + return 1; } -static int +static int symtable_visit_excepthandler(struct symtable *st, excepthandler_ty eh) { - if (eh->v.ExceptHandler.type) - VISIT(st, expr, eh->v.ExceptHandler.type); - if (eh->v.ExceptHandler.name) - if (!symtable_add_def(st, eh->v.ExceptHandler.name, DEF_LOCAL)) - return 0; - VISIT_SEQ(st, stmt, eh->v.ExceptHandler.body); - return 1; + if (eh->v.ExceptHandler.type) + VISIT(st, expr, eh->v.ExceptHandler.type); + if (eh->v.ExceptHandler.name) + if (!symtable_add_def(st, eh->v.ExceptHandler.name, DEF_LOCAL)) + return 0; + VISIT_SEQ(st, stmt, eh->v.ExceptHandler.body); + return 1; } -static int +static int symtable_visit_alias(struct symtable *st, alias_ty a) { - /* Compute store_name, the name actually bound by the import - operation. It is diferent than a->name when a->name is a - dotted package name (e.g. spam.eggs) - */ - PyObject *store_name; - PyObject *name = (a->asname == NULL) ? a->name : a->asname; - const Py_UNICODE *base = PyUnicode_AS_UNICODE(name); - Py_UNICODE *dot = Py_UNICODE_strchr(base, '.'); - if (dot) { - store_name = PyUnicode_FromUnicode(base, dot - base); - if (!store_name) - return 0; - } - else { - store_name = name; - Py_INCREF(store_name); - } - if (PyUnicode_CompareWithASCIIString(name, "*")) { - int r = symtable_add_def(st, store_name, DEF_IMPORT); - Py_DECREF(store_name); - return r; - } - else { - if (st->st_cur->ste_type != ModuleBlock) { - int lineno = st->st_cur->ste_lineno; - PyErr_SetString(PyExc_SyntaxError, IMPORT_STAR_WARNING); - PyErr_SyntaxLocation(st->st_filename, lineno); - Py_DECREF(store_name); - return 0; - } - st->st_cur->ste_unoptimized |= OPT_IMPORT_STAR; - Py_DECREF(store_name); - return 1; - } + /* Compute store_name, the name actually bound by the import + operation. It is diferent than a->name when a->name is a + dotted package name (e.g. spam.eggs) + */ + PyObject *store_name; + PyObject *name = (a->asname == NULL) ? a->name : a->asname; + const Py_UNICODE *base = PyUnicode_AS_UNICODE(name); + Py_UNICODE *dot = Py_UNICODE_strchr(base, '.'); + if (dot) { + store_name = PyUnicode_FromUnicode(base, dot - base); + if (!store_name) + return 0; + } + else { + store_name = name; + Py_INCREF(store_name); + } + if (PyUnicode_CompareWithASCIIString(name, "*")) { + int r = symtable_add_def(st, store_name, DEF_IMPORT); + Py_DECREF(store_name); + return r; + } + else { + if (st->st_cur->ste_type != ModuleBlock) { + int lineno = st->st_cur->ste_lineno; + PyErr_SetString(PyExc_SyntaxError, IMPORT_STAR_WARNING); + PyErr_SyntaxLocation(st->st_filename, lineno); + Py_DECREF(store_name); + return 0; + } + st->st_cur->ste_unoptimized |= OPT_IMPORT_STAR; + Py_DECREF(store_name); + return 1; + } } -static int +static int symtable_visit_comprehension(struct symtable *st, comprehension_ty lc) { - VISIT(st, expr, lc->target); - VISIT(st, expr, lc->iter); - VISIT_SEQ(st, expr, lc->ifs); - return 1; + VISIT(st, expr, lc->target); + VISIT(st, expr, lc->iter); + VISIT_SEQ(st, expr, lc->ifs); + return 1; } -static int +static int symtable_visit_keyword(struct symtable *st, keyword_ty k) { - VISIT(st, expr, k->value); - return 1; + VISIT(st, expr, k->value); + return 1; } -static int +static int symtable_visit_slice(struct symtable *st, slice_ty s) { - switch (s->kind) { - case Slice_kind: - if (s->v.Slice.lower) - VISIT(st, expr, s->v.Slice.lower) - if (s->v.Slice.upper) - VISIT(st, expr, s->v.Slice.upper) - if (s->v.Slice.step) - VISIT(st, expr, s->v.Slice.step) - break; - case ExtSlice_kind: - VISIT_SEQ(st, slice, s->v.ExtSlice.dims) - break; - case Index_kind: - VISIT(st, expr, s->v.Index.value) - break; - } - return 1; + switch (s->kind) { + case Slice_kind: + if (s->v.Slice.lower) + VISIT(st, expr, s->v.Slice.lower) + if (s->v.Slice.upper) + VISIT(st, expr, s->v.Slice.upper) + if (s->v.Slice.step) + VISIT(st, expr, s->v.Slice.step) + break; + case ExtSlice_kind: + VISIT_SEQ(st, slice, s->v.ExtSlice.dims) + break; + case Index_kind: + VISIT(st, expr, s->v.Index.value) + break; + } + return 1; } -static int +static int symtable_handle_comprehension(struct symtable *st, expr_ty e, identifier scope_name, asdl_seq *generators, expr_ty elt, expr_ty value) { - int is_generator = (e->kind == GeneratorExp_kind); - int needs_tmp = !is_generator; - comprehension_ty outermost = ((comprehension_ty) - asdl_seq_GET(generators, 0)); - /* Outermost iterator is evaluated in current scope */ - VISIT(st, expr, outermost->iter); - /* Create comprehension scope for the rest */ - if (!scope_name || - !symtable_enter_block(st, scope_name, FunctionBlock, (void *)e, e->lineno)) { - return 0; - } - st->st_cur->ste_generator = is_generator; - /* Outermost iter is received as an argument */ - if (!symtable_implicit_arg(st, 0)) { - symtable_exit_block(st, (void *)e); - return 0; - } - /* Allocate temporary name if needed */ - if (needs_tmp && !symtable_new_tmpname(st)) { - symtable_exit_block(st, (void *)e); - return 0; - } - VISIT_IN_BLOCK(st, expr, outermost->target, (void*)e); - VISIT_SEQ_IN_BLOCK(st, expr, outermost->ifs, (void*)e); - VISIT_SEQ_TAIL_IN_BLOCK(st, comprehension, - generators, 1, (void*)e); - if (value) - VISIT_IN_BLOCK(st, expr, value, (void*)e); - VISIT_IN_BLOCK(st, expr, elt, (void*)e); - return symtable_exit_block(st, (void *)e); + int is_generator = (e->kind == GeneratorExp_kind); + int needs_tmp = !is_generator; + comprehension_ty outermost = ((comprehension_ty) + asdl_seq_GET(generators, 0)); + /* Outermost iterator is evaluated in current scope */ + VISIT(st, expr, outermost->iter); + /* Create comprehension scope for the rest */ + if (!scope_name || + !symtable_enter_block(st, scope_name, FunctionBlock, (void *)e, e->lineno)) { + return 0; + } + st->st_cur->ste_generator = is_generator; + /* Outermost iter is received as an argument */ + if (!symtable_implicit_arg(st, 0)) { + symtable_exit_block(st, (void *)e); + return 0; + } + /* Allocate temporary name if needed */ + if (needs_tmp && !symtable_new_tmpname(st)) { + symtable_exit_block(st, (void *)e); + return 0; + } + VISIT_IN_BLOCK(st, expr, outermost->target, (void*)e); + VISIT_SEQ_IN_BLOCK(st, expr, outermost->ifs, (void*)e); + VISIT_SEQ_TAIL_IN_BLOCK(st, comprehension, + generators, 1, (void*)e); + if (value) + VISIT_IN_BLOCK(st, expr, value, (void*)e); + VISIT_IN_BLOCK(st, expr, elt, (void*)e); + return symtable_exit_block(st, (void *)e); } -static int +static int symtable_visit_genexp(struct symtable *st, expr_ty e) { - return symtable_handle_comprehension(st, e, GET_IDENTIFIER(genexpr), - e->v.GeneratorExp.generators, - e->v.GeneratorExp.elt, NULL); + return symtable_handle_comprehension(st, e, GET_IDENTIFIER(genexpr), + e->v.GeneratorExp.generators, + e->v.GeneratorExp.elt, NULL); } -static int +static int symtable_visit_listcomp(struct symtable *st, expr_ty e) { - return symtable_handle_comprehension(st, e, GET_IDENTIFIER(listcomp), - e->v.ListComp.generators, - e->v.ListComp.elt, NULL); + return symtable_handle_comprehension(st, e, GET_IDENTIFIER(listcomp), + e->v.ListComp.generators, + e->v.ListComp.elt, NULL); } static int symtable_visit_setcomp(struct symtable *st, expr_ty e) { - return symtable_handle_comprehension(st, e, GET_IDENTIFIER(setcomp), - e->v.SetComp.generators, - e->v.SetComp.elt, NULL); + return symtable_handle_comprehension(st, e, GET_IDENTIFIER(setcomp), + e->v.SetComp.generators, + e->v.SetComp.elt, NULL); } static int symtable_visit_dictcomp(struct symtable *st, expr_ty e) { - return symtable_handle_comprehension(st, e, GET_IDENTIFIER(dictcomp), - e->v.DictComp.generators, - e->v.DictComp.key, - e->v.DictComp.value); + return symtable_handle_comprehension(st, e, GET_IDENTIFIER(dictcomp), + e->v.DictComp.generators, + e->v.DictComp.key, + e->v.DictComp.value); } Modified: python/branches/release31-maint/Python/sysmodule.c ============================================================================== --- python/branches/release31-maint/Python/sysmodule.c (original) +++ python/branches/release31-maint/Python/sysmodule.c Sun May 9 18:14:21 2010 @@ -45,63 +45,63 @@ PyObject * PySys_GetObject(const char *name) { - PyThreadState *tstate = PyThreadState_GET(); - PyObject *sd = tstate->interp->sysdict; - if (sd == NULL) - return NULL; - return PyDict_GetItemString(sd, name); + PyThreadState *tstate = PyThreadState_GET(); + PyObject *sd = tstate->interp->sysdict; + if (sd == NULL) + return NULL; + return PyDict_GetItemString(sd, name); } int PySys_SetObject(const char *name, PyObject *v) { - PyThreadState *tstate = PyThreadState_GET(); - PyObject *sd = tstate->interp->sysdict; - if (v == NULL) { - if (PyDict_GetItemString(sd, name) == NULL) - return 0; - else - return PyDict_DelItemString(sd, name); - } - else - return PyDict_SetItemString(sd, name, v); + PyThreadState *tstate = PyThreadState_GET(); + PyObject *sd = tstate->interp->sysdict; + if (v == NULL) { + if (PyDict_GetItemString(sd, name) == NULL) + return 0; + else + return PyDict_DelItemString(sd, name); + } + else + return PyDict_SetItemString(sd, name, v); } static PyObject * sys_displayhook(PyObject *self, PyObject *o) { - PyObject *outf; - PyInterpreterState *interp = PyThreadState_GET()->interp; - PyObject *modules = interp->modules; - PyObject *builtins = PyDict_GetItemString(modules, "builtins"); - - if (builtins == NULL) { - PyErr_SetString(PyExc_RuntimeError, "lost builtins module"); - return NULL; - } - - /* Print value except if None */ - /* After printing, also assign to '_' */ - /* Before, set '_' to None to avoid recursion */ - if (o == Py_None) { - Py_INCREF(Py_None); - return Py_None; - } - if (PyObject_SetAttrString(builtins, "_", Py_None) != 0) - return NULL; - outf = PySys_GetObject("stdout"); - if (outf == NULL || outf == Py_None) { - PyErr_SetString(PyExc_RuntimeError, "lost sys.stdout"); - return NULL; - } - if (PyFile_WriteObject(o, outf, 0) != 0) - return NULL; - if (PyFile_WriteString("\n", outf) != 0) - return NULL; - if (PyObject_SetAttrString(builtins, "_", o) != 0) - return NULL; - Py_INCREF(Py_None); - return Py_None; + PyObject *outf; + PyInterpreterState *interp = PyThreadState_GET()->interp; + PyObject *modules = interp->modules; + PyObject *builtins = PyDict_GetItemString(modules, "builtins"); + + if (builtins == NULL) { + PyErr_SetString(PyExc_RuntimeError, "lost builtins module"); + return NULL; + } + + /* Print value except if None */ + /* After printing, also assign to '_' */ + /* Before, set '_' to None to avoid recursion */ + if (o == Py_None) { + Py_INCREF(Py_None); + return Py_None; + } + if (PyObject_SetAttrString(builtins, "_", Py_None) != 0) + return NULL; + outf = PySys_GetObject("stdout"); + if (outf == NULL || outf == Py_None) { + PyErr_SetString(PyExc_RuntimeError, "lost sys.stdout"); + return NULL; + } + if (PyFile_WriteObject(o, outf, 0) != 0) + return NULL; + if (PyFile_WriteString("\n", outf) != 0) + return NULL; + if (PyObject_SetAttrString(builtins, "_", o) != 0) + return NULL; + Py_INCREF(Py_None); + return Py_None; } PyDoc_STRVAR(displayhook_doc, @@ -113,12 +113,12 @@ static PyObject * sys_excepthook(PyObject* self, PyObject* args) { - PyObject *exc, *value, *tb; - if (!PyArg_UnpackTuple(args, "excepthook", 3, 3, &exc, &value, &tb)) - return NULL; - PyErr_Display(exc, value, tb); - Py_INCREF(Py_None); - return Py_None; + PyObject *exc, *value, *tb; + if (!PyArg_UnpackTuple(args, "excepthook", 3, 3, &exc, &value, &tb)) + return NULL; + PyErr_Display(exc, value, tb); + Py_INCREF(Py_None); + return Py_None; } PyDoc_STRVAR(excepthook_doc, @@ -130,14 +130,14 @@ static PyObject * sys_exc_info(PyObject *self, PyObject *noargs) { - PyThreadState *tstate; - tstate = PyThreadState_GET(); - return Py_BuildValue( - "(OOO)", - tstate->exc_type != NULL ? tstate->exc_type : Py_None, - tstate->exc_value != NULL ? tstate->exc_value : Py_None, - tstate->exc_traceback != NULL ? - tstate->exc_traceback : Py_None); + PyThreadState *tstate; + tstate = PyThreadState_GET(); + return Py_BuildValue( + "(OOO)", + tstate->exc_type != NULL ? tstate->exc_type : Py_None, + tstate->exc_value != NULL ? tstate->exc_value : Py_None, + tstate->exc_traceback != NULL ? + tstate->exc_traceback : Py_None); } PyDoc_STRVAR(exc_info_doc, @@ -150,12 +150,12 @@ static PyObject * sys_exit(PyObject *self, PyObject *args) { - PyObject *exit_code = 0; - if (!PyArg_UnpackTuple(args, "exit", 0, 1, &exit_code)) - return NULL; - /* Raise SystemExit so callers may catch it or clean up. */ - PyErr_SetObject(PyExc_SystemExit, exit_code); - return NULL; + PyObject *exit_code = 0; + if (!PyArg_UnpackTuple(args, "exit", 0, 1, &exit_code)) + return NULL; + /* Raise SystemExit so callers may catch it or clean up. */ + PyErr_SetObject(PyExc_SystemExit, exit_code); + return NULL; } PyDoc_STRVAR(exit_doc, @@ -172,7 +172,7 @@ static PyObject * sys_getdefaultencoding(PyObject *self) { - return PyUnicode_FromString(PyUnicode_GetDefaultEncoding()); + return PyUnicode_FromString(PyUnicode_GetDefaultEncoding()); } PyDoc_STRVAR(getdefaultencoding_doc, @@ -185,13 +185,13 @@ static PyObject * sys_setdefaultencoding(PyObject *self, PyObject *args) { - char *encoding; - if (!PyArg_ParseTuple(args, "s:setdefaultencoding", &encoding)) - return NULL; - if (PyUnicode_SetDefaultEncoding(encoding)) - return NULL; - Py_INCREF(Py_None); - return Py_None; + char *encoding; + if (!PyArg_ParseTuple(args, "s:setdefaultencoding", &encoding)) + return NULL; + if (PyUnicode_SetDefaultEncoding(encoding)) + return NULL; + Py_INCREF(Py_None); + return Py_None; } PyDoc_STRVAR(setdefaultencoding_doc, @@ -203,10 +203,10 @@ static PyObject * sys_getfilesystemencoding(PyObject *self) { - if (Py_FileSystemDefaultEncoding) - return PyUnicode_FromString(Py_FileSystemDefaultEncoding); - Py_INCREF(Py_None); - return Py_None; + if (Py_FileSystemDefaultEncoding) + return PyUnicode_FromString(Py_FileSystemDefaultEncoding); + Py_INCREF(Py_None); + return Py_None; } PyDoc_STRVAR(getfilesystemencoding_doc, @@ -219,13 +219,13 @@ static PyObject * sys_setfilesystemencoding(PyObject *self, PyObject *args) { - PyObject *new_encoding; - if (!PyArg_ParseTuple(args, "U:setfilesystemencoding", &new_encoding)) - return NULL; - if (_Py_SetFileSystemEncoding(new_encoding)) - return NULL; - Py_INCREF(Py_None); - return Py_None; + PyObject *new_encoding; + if (!PyArg_ParseTuple(args, "U:setfilesystemencoding", &new_encoding)) + return NULL; + if (_Py_SetFileSystemEncoding(new_encoding)) + return NULL; + Py_INCREF(Py_None); + return Py_None; } PyDoc_STRVAR(setfilesystemencoding_doc, @@ -238,19 +238,19 @@ static PyObject * sys_intern(PyObject *self, PyObject *args) { - PyObject *s; - if (!PyArg_ParseTuple(args, "U:intern", &s)) - return NULL; - if (PyUnicode_CheckExact(s)) { - Py_INCREF(s); - PyUnicode_InternInPlace(&s); - return s; - } - else { - PyErr_Format(PyExc_TypeError, - "can't intern %.400s", s->ob_type->tp_name); - return NULL; - } + PyObject *s; + if (!PyArg_ParseTuple(args, "U:intern", &s)) + return NULL; + if (PyUnicode_CheckExact(s)) { + Py_INCREF(s); + PyUnicode_InternInPlace(&s); + return s; + } + else { + PyErr_Format(PyExc_TypeError, + "can't intern %.400s", s->ob_type->tp_name); + return NULL; + } } PyDoc_STRVAR(intern_doc, @@ -271,116 +271,116 @@ static int trace_init(void) { - static char *whatnames[7] = {"call", "exception", "line", "return", - "c_call", "c_exception", "c_return"}; - PyObject *name; - int i; - for (i = 0; i < 7; ++i) { - if (whatstrings[i] == NULL) { - name = PyUnicode_InternFromString(whatnames[i]); - if (name == NULL) - return -1; - whatstrings[i] = name; - } - } - return 0; + static char *whatnames[7] = {"call", "exception", "line", "return", + "c_call", "c_exception", "c_return"}; + PyObject *name; + int i; + for (i = 0; i < 7; ++i) { + if (whatstrings[i] == NULL) { + name = PyUnicode_InternFromString(whatnames[i]); + if (name == NULL) + return -1; + whatstrings[i] = name; + } + } + return 0; } static PyObject * call_trampoline(PyThreadState *tstate, PyObject* callback, - PyFrameObject *frame, int what, PyObject *arg) + PyFrameObject *frame, int what, PyObject *arg) { - PyObject *args = PyTuple_New(3); - PyObject *whatstr; - PyObject *result; - - if (args == NULL) - return NULL; - Py_INCREF(frame); - whatstr = whatstrings[what]; - Py_INCREF(whatstr); - if (arg == NULL) - arg = Py_None; - Py_INCREF(arg); - PyTuple_SET_ITEM(args, 0, (PyObject *)frame); - PyTuple_SET_ITEM(args, 1, whatstr); - PyTuple_SET_ITEM(args, 2, arg); - - /* call the Python-level function */ - PyFrame_FastToLocals(frame); - result = PyEval_CallObject(callback, args); - PyFrame_LocalsToFast(frame, 1); - if (result == NULL) - PyTraceBack_Here(frame); - - /* cleanup */ - Py_DECREF(args); - return result; + PyObject *args = PyTuple_New(3); + PyObject *whatstr; + PyObject *result; + + if (args == NULL) + return NULL; + Py_INCREF(frame); + whatstr = whatstrings[what]; + Py_INCREF(whatstr); + if (arg == NULL) + arg = Py_None; + Py_INCREF(arg); + PyTuple_SET_ITEM(args, 0, (PyObject *)frame); + PyTuple_SET_ITEM(args, 1, whatstr); + PyTuple_SET_ITEM(args, 2, arg); + + /* call the Python-level function */ + PyFrame_FastToLocals(frame); + result = PyEval_CallObject(callback, args); + PyFrame_LocalsToFast(frame, 1); + if (result == NULL) + PyTraceBack_Here(frame); + + /* cleanup */ + Py_DECREF(args); + return result; } static int profile_trampoline(PyObject *self, PyFrameObject *frame, - int what, PyObject *arg) + int what, PyObject *arg) { - PyThreadState *tstate = frame->f_tstate; - PyObject *result; + PyThreadState *tstate = frame->f_tstate; + PyObject *result; - if (arg == NULL) - arg = Py_None; - result = call_trampoline(tstate, self, frame, what, arg); - if (result == NULL) { - PyEval_SetProfile(NULL, NULL); - return -1; - } - Py_DECREF(result); - return 0; + if (arg == NULL) + arg = Py_None; + result = call_trampoline(tstate, self, frame, what, arg); + if (result == NULL) { + PyEval_SetProfile(NULL, NULL); + return -1; + } + Py_DECREF(result); + return 0; } static int trace_trampoline(PyObject *self, PyFrameObject *frame, - int what, PyObject *arg) + int what, PyObject *arg) { - PyThreadState *tstate = frame->f_tstate; - PyObject *callback; - PyObject *result; - - if (what == PyTrace_CALL) - callback = self; - else - callback = frame->f_trace; - if (callback == NULL) - return 0; - result = call_trampoline(tstate, callback, frame, what, arg); - if (result == NULL) { - PyEval_SetTrace(NULL, NULL); - Py_XDECREF(frame->f_trace); - frame->f_trace = NULL; - return -1; - } - if (result != Py_None) { - PyObject *temp = frame->f_trace; - frame->f_trace = NULL; - Py_XDECREF(temp); - frame->f_trace = result; - } - else { - Py_DECREF(result); - } - return 0; + PyThreadState *tstate = frame->f_tstate; + PyObject *callback; + PyObject *result; + + if (what == PyTrace_CALL) + callback = self; + else + callback = frame->f_trace; + if (callback == NULL) + return 0; + result = call_trampoline(tstate, callback, frame, what, arg); + if (result == NULL) { + PyEval_SetTrace(NULL, NULL); + Py_XDECREF(frame->f_trace); + frame->f_trace = NULL; + return -1; + } + if (result != Py_None) { + PyObject *temp = frame->f_trace; + frame->f_trace = NULL; + Py_XDECREF(temp); + frame->f_trace = result; + } + else { + Py_DECREF(result); + } + return 0; } static PyObject * sys_settrace(PyObject *self, PyObject *args) { - if (trace_init() == -1) - return NULL; - if (args == Py_None) - PyEval_SetTrace(NULL, NULL); - else - PyEval_SetTrace(trace_trampoline, args); - Py_INCREF(Py_None); - return Py_None; + if (trace_init() == -1) + return NULL; + if (args == Py_None) + PyEval_SetTrace(NULL, NULL); + else + PyEval_SetTrace(trace_trampoline, args); + Py_INCREF(Py_None); + return Py_None; } PyDoc_STRVAR(settrace_doc, @@ -393,13 +393,13 @@ static PyObject * sys_gettrace(PyObject *self, PyObject *args) { - PyThreadState *tstate = PyThreadState_GET(); - PyObject *temp = tstate->c_traceobj; + PyThreadState *tstate = PyThreadState_GET(); + PyObject *temp = tstate->c_traceobj; - if (temp == NULL) - temp = Py_None; - Py_INCREF(temp); - return temp; + if (temp == NULL) + temp = Py_None; + Py_INCREF(temp); + return temp; } PyDoc_STRVAR(gettrace_doc, @@ -412,14 +412,14 @@ static PyObject * sys_setprofile(PyObject *self, PyObject *args) { - if (trace_init() == -1) - return NULL; - if (args == Py_None) - PyEval_SetProfile(NULL, NULL); - else - PyEval_SetProfile(profile_trampoline, args); - Py_INCREF(Py_None); - return Py_None; + if (trace_init() == -1) + return NULL; + if (args == Py_None) + PyEval_SetProfile(NULL, NULL); + else + PyEval_SetProfile(profile_trampoline, args); + Py_INCREF(Py_None); + return Py_None; } PyDoc_STRVAR(setprofile_doc, @@ -432,13 +432,13 @@ static PyObject * sys_getprofile(PyObject *self, PyObject *args) { - PyThreadState *tstate = PyThreadState_GET(); - PyObject *temp = tstate->c_profileobj; + PyThreadState *tstate = PyThreadState_GET(); + PyObject *temp = tstate->c_profileobj; - if (temp == NULL) - temp = Py_None; - Py_INCREF(temp); - return temp; + if (temp == NULL) + temp = Py_None; + Py_INCREF(temp); + return temp; } PyDoc_STRVAR(getprofile_doc, @@ -451,10 +451,10 @@ static PyObject * sys_setcheckinterval(PyObject *self, PyObject *args) { - if (!PyArg_ParseTuple(args, "i:setcheckinterval", &_Py_CheckInterval)) - return NULL; - Py_INCREF(Py_None); - return Py_None; + if (!PyArg_ParseTuple(args, "i:setcheckinterval", &_Py_CheckInterval)) + return NULL; + Py_INCREF(Py_None); + return Py_None; } PyDoc_STRVAR(setcheckinterval_doc, @@ -467,7 +467,7 @@ static PyObject * sys_getcheckinterval(PyObject *self, PyObject *args) { - return PyLong_FromLong(_Py_CheckInterval); + return PyLong_FromLong(_Py_CheckInterval); } PyDoc_STRVAR(getcheckinterval_doc, @@ -478,17 +478,17 @@ static PyObject * sys_settscdump(PyObject *self, PyObject *args) { - int bool; - PyThreadState *tstate = PyThreadState_Get(); + int bool; + PyThreadState *tstate = PyThreadState_Get(); - if (!PyArg_ParseTuple(args, "i:settscdump", &bool)) - return NULL; - if (bool) - tstate->interp->tscdump = 1; - else - tstate->interp->tscdump = 0; - Py_INCREF(Py_None); - return Py_None; + if (!PyArg_ParseTuple(args, "i:settscdump", &bool)) + return NULL; + if (bool) + tstate->interp->tscdump = 1; + else + tstate->interp->tscdump = 0; + Py_INCREF(Py_None); + return Py_None; } @@ -504,17 +504,17 @@ static PyObject * sys_setrecursionlimit(PyObject *self, PyObject *args) { - int new_limit; - if (!PyArg_ParseTuple(args, "i:setrecursionlimit", &new_limit)) - return NULL; - if (new_limit <= 0) { - PyErr_SetString(PyExc_ValueError, - "recursion limit must be positive"); - return NULL; - } - Py_SetRecursionLimit(new_limit); - Py_INCREF(Py_None); - return Py_None; + int new_limit; + if (!PyArg_ParseTuple(args, "i:setrecursionlimit", &new_limit)) + return NULL; + if (new_limit <= 0) { + PyErr_SetString(PyExc_ValueError, + "recursion limit must be positive"); + return NULL; + } + Py_SetRecursionLimit(new_limit); + Py_INCREF(Py_None); + return Py_None; } PyDoc_STRVAR(setrecursionlimit_doc, @@ -529,7 +529,7 @@ static PyObject * sys_getrecursionlimit(PyObject *self) { - return PyLong_FromLong(Py_GetRecursionLimit()); + return PyLong_FromLong(Py_GetRecursionLimit()); } PyDoc_STRVAR(getrecursionlimit_doc, @@ -554,16 +554,16 @@ static PyObject * sys_getwindowsversion(PyObject *self) { - OSVERSIONINFO ver; - ver.dwOSVersionInfoSize = sizeof(ver); - if (!GetVersionEx(&ver)) - return PyErr_SetFromWindowsErr(0); - return Py_BuildValue("HHHHs", - ver.dwMajorVersion, - ver.dwMinorVersion, - ver.dwBuildNumber, - ver.dwPlatformId, - ver.szCSDVersion); + OSVERSIONINFO ver; + ver.dwOSVersionInfoSize = sizeof(ver); + if (!GetVersionEx(&ver)) + return PyErr_SetFromWindowsErr(0); + return Py_BuildValue("HHHHs", + ver.dwMajorVersion, + ver.dwMinorVersion, + ver.dwBuildNumber, + ver.dwPlatformId, + ver.szCSDVersion); } #endif /* MS_WINDOWS */ @@ -572,15 +572,15 @@ static PyObject * sys_setdlopenflags(PyObject *self, PyObject *args) { - int new_val; - PyThreadState *tstate = PyThreadState_GET(); - if (!PyArg_ParseTuple(args, "i:setdlopenflags", &new_val)) - return NULL; - if (!tstate) - return NULL; - tstate->interp->dlopenflags = new_val; - Py_INCREF(Py_None); - return Py_None; + int new_val; + PyThreadState *tstate = PyThreadState_GET(); + if (!PyArg_ParseTuple(args, "i:setdlopenflags", &new_val)) + return NULL; + if (!tstate) + return NULL; + tstate->interp->dlopenflags = new_val; + Py_INCREF(Py_None); + return Py_None; } PyDoc_STRVAR(setdlopenflags_doc, @@ -598,10 +598,10 @@ static PyObject * sys_getdlopenflags(PyObject *self, PyObject *args) { - PyThreadState *tstate = PyThreadState_GET(); - if (!tstate) - return NULL; - return PyLong_FromLong(tstate->interp->dlopenflags); + PyThreadState *tstate = PyThreadState_GET(); + if (!tstate) + return NULL; + return PyLong_FromLong(tstate->interp->dlopenflags); } PyDoc_STRVAR(getdlopenflags_doc, @@ -610,7 +610,7 @@ Return the current value of the flags that are used for dlopen calls.\n\ The flag constants are defined in the ctypes and DLFCN modules."); -#endif /* HAVE_DLOPEN */ +#endif /* HAVE_DLOPEN */ #ifdef USE_MALLOPT /* Link with -lmalloc (or -lmpc) on an SGI */ @@ -619,70 +619,70 @@ static PyObject * sys_mdebug(PyObject *self, PyObject *args) { - int flag; - if (!PyArg_ParseTuple(args, "i:mdebug", &flag)) - return NULL; - mallopt(M_DEBUG, flag); - Py_INCREF(Py_None); - return Py_None; + int flag; + if (!PyArg_ParseTuple(args, "i:mdebug", &flag)) + return NULL; + mallopt(M_DEBUG, flag); + Py_INCREF(Py_None); + return Py_None; } #endif /* USE_MALLOPT */ static PyObject * sys_getsizeof(PyObject *self, PyObject *args, PyObject *kwds) { - PyObject *res = NULL; - static PyObject *str__sizeof__ = NULL, *gc_head_size = NULL; - static char *kwlist[] = {"object", "default", 0}; - PyObject *o, *dflt = NULL; - PyObject *method; - - if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|O:getsizeof", - kwlist, &o, &dflt)) - return NULL; - - /* Initialize static variable for GC head size */ - if (gc_head_size == NULL) { - gc_head_size = PyLong_FromSsize_t(sizeof(PyGC_Head)); - if (gc_head_size == NULL) - return NULL; - } - - /* Make sure the type is initialized. float gets initialized late */ - if (PyType_Ready(Py_TYPE(o)) < 0) - return NULL; - - method = _PyObject_LookupSpecial(o, "__sizeof__", - &str__sizeof__); - if (method == NULL) { - if (!PyErr_Occurred()) - PyErr_Format(PyExc_TypeError, - "Type %.100s doesn't define __sizeof__", - Py_TYPE(o)->tp_name); - } - else { - res = PyObject_CallFunctionObjArgs(method, NULL); - Py_DECREF(method); - } - - /* Has a default value been given */ - if ((res == NULL) && (dflt != NULL) && - PyErr_ExceptionMatches(PyExc_TypeError)) - { - PyErr_Clear(); - Py_INCREF(dflt); - return dflt; - } - else if (res == NULL) - return res; - - /* add gc_head size */ - if (PyObject_IS_GC(o)) { - PyObject *tmp = res; - res = PyNumber_Add(tmp, gc_head_size); - Py_DECREF(tmp); - } - return res; + PyObject *res = NULL; + static PyObject *str__sizeof__ = NULL, *gc_head_size = NULL; + static char *kwlist[] = {"object", "default", 0}; + PyObject *o, *dflt = NULL; + PyObject *method; + + if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|O:getsizeof", + kwlist, &o, &dflt)) + return NULL; + + /* Initialize static variable for GC head size */ + if (gc_head_size == NULL) { + gc_head_size = PyLong_FromSsize_t(sizeof(PyGC_Head)); + if (gc_head_size == NULL) + return NULL; + } + + /* Make sure the type is initialized. float gets initialized late */ + if (PyType_Ready(Py_TYPE(o)) < 0) + return NULL; + + method = _PyObject_LookupSpecial(o, "__sizeof__", + &str__sizeof__); + if (method == NULL) { + if (!PyErr_Occurred()) + PyErr_Format(PyExc_TypeError, + "Type %.100s doesn't define __sizeof__", + Py_TYPE(o)->tp_name); + } + else { + res = PyObject_CallFunctionObjArgs(method, NULL); + Py_DECREF(method); + } + + /* Has a default value been given */ + if ((res == NULL) && (dflt != NULL) && + PyErr_ExceptionMatches(PyExc_TypeError)) + { + PyErr_Clear(); + Py_INCREF(dflt); + return dflt; + } + else if (res == NULL) + return res; + + /* add gc_head size */ + if (PyObject_IS_GC(o)) { + PyObject *tmp = res; + res = PyNumber_Add(tmp, gc_head_size); + Py_DECREF(tmp); + } + return res; } PyDoc_STRVAR(getsizeof_doc, @@ -693,14 +693,14 @@ static PyObject * sys_getrefcount(PyObject *self, PyObject *arg) { - return PyLong_FromSsize_t(arg->ob_refcnt); + return PyLong_FromSsize_t(arg->ob_refcnt); } #ifdef Py_REF_DEBUG static PyObject * sys_gettotalrefcount(PyObject *self) { - return PyLong_FromSsize_t(_Py_GetRefTotal()); + return PyLong_FromSsize_t(_Py_GetRefTotal()); } #endif /* Py_REF_DEBUG */ @@ -716,9 +716,9 @@ static PyObject * sys_getcounts(PyObject *self) { - extern PyObject *get_counts(void); + extern PyObject *get_counts(void); - return get_counts(); + return get_counts(); } #endif @@ -737,23 +737,23 @@ static PyObject * sys_getframe(PyObject *self, PyObject *args) { - PyFrameObject *f = PyThreadState_GET()->frame; - int depth = -1; + PyFrameObject *f = PyThreadState_GET()->frame; + int depth = -1; - if (!PyArg_ParseTuple(args, "|i:_getframe", &depth)) - return NULL; + if (!PyArg_ParseTuple(args, "|i:_getframe", &depth)) + return NULL; - while (depth > 0 && f != NULL) { - f = f->f_back; - --depth; - } - if (f == NULL) { - PyErr_SetString(PyExc_ValueError, - "call stack is not deep enough"); - return NULL; - } - Py_INCREF(f); - return (PyObject*)f; + while (depth > 0 && f != NULL) { + f = f->f_back; + --depth; + } + if (f == NULL) { + PyErr_SetString(PyExc_ValueError, + "call stack is not deep enough"); + return NULL; + } + Py_INCREF(f); + return (PyObject*)f; } PyDoc_STRVAR(current_frames_doc, @@ -768,7 +768,7 @@ static PyObject * sys_current_frames(PyObject *self, PyObject *noargs) { - return _PyThread_CurrentFrames(); + return _PyThread_CurrentFrames(); } PyDoc_STRVAR(call_tracing_doc, @@ -782,10 +782,10 @@ static PyObject * sys_call_tracing(PyObject *self, PyObject *args) { - PyObject *func, *funcargs; - if (!PyArg_ParseTuple(args, "OO!:call_tracing", &func, &PyTuple_Type, &funcargs)) - return NULL; - return _PyEval_CallTracing(func, funcargs); + PyObject *func, *funcargs; + if (!PyArg_ParseTuple(args, "OO!:call_tracing", &func, &PyTuple_Type, &funcargs)) + return NULL; + return _PyEval_CallTracing(func, funcargs); } PyDoc_STRVAR(callstats_doc, @@ -832,8 +832,8 @@ static PyObject * sys_clear_type_cache(PyObject* self, PyObject* args) { - PyType_ClearCache(); - Py_RETURN_NONE; + PyType_ClearCache(); + Py_RETURN_NONE; } PyDoc_STRVAR(sys_clear_type_cache__doc__, @@ -842,101 +842,101 @@ static PyMethodDef sys_methods[] = { - /* Might as well keep this in alphabetic order */ - {"callstats", (PyCFunction)PyEval_GetCallStats, METH_NOARGS, - callstats_doc}, - {"_clear_type_cache", sys_clear_type_cache, METH_NOARGS, - sys_clear_type_cache__doc__}, - {"_current_frames", sys_current_frames, METH_NOARGS, - current_frames_doc}, - {"displayhook", sys_displayhook, METH_O, displayhook_doc}, - {"exc_info", sys_exc_info, METH_NOARGS, exc_info_doc}, - {"excepthook", sys_excepthook, METH_VARARGS, excepthook_doc}, - {"exit", sys_exit, METH_VARARGS, exit_doc}, - {"getdefaultencoding", (PyCFunction)sys_getdefaultencoding, - METH_NOARGS, getdefaultencoding_doc}, + /* Might as well keep this in alphabetic order */ + {"callstats", (PyCFunction)PyEval_GetCallStats, METH_NOARGS, + callstats_doc}, + {"_clear_type_cache", sys_clear_type_cache, METH_NOARGS, + sys_clear_type_cache__doc__}, + {"_current_frames", sys_current_frames, METH_NOARGS, + current_frames_doc}, + {"displayhook", sys_displayhook, METH_O, displayhook_doc}, + {"exc_info", sys_exc_info, METH_NOARGS, exc_info_doc}, + {"excepthook", sys_excepthook, METH_VARARGS, excepthook_doc}, + {"exit", sys_exit, METH_VARARGS, exit_doc}, + {"getdefaultencoding", (PyCFunction)sys_getdefaultencoding, + METH_NOARGS, getdefaultencoding_doc}, #ifdef HAVE_DLOPEN - {"getdlopenflags", (PyCFunction)sys_getdlopenflags, METH_NOARGS, - getdlopenflags_doc}, + {"getdlopenflags", (PyCFunction)sys_getdlopenflags, METH_NOARGS, + getdlopenflags_doc}, #endif #ifdef COUNT_ALLOCS - {"getcounts", (PyCFunction)sys_getcounts, METH_NOARGS}, + {"getcounts", (PyCFunction)sys_getcounts, METH_NOARGS}, #endif #ifdef DYNAMIC_EXECUTION_PROFILE - {"getdxp", _Py_GetDXProfile, METH_VARARGS}, + {"getdxp", _Py_GetDXProfile, METH_VARARGS}, #endif - {"getfilesystemencoding", (PyCFunction)sys_getfilesystemencoding, - METH_NOARGS, getfilesystemencoding_doc}, + {"getfilesystemencoding", (PyCFunction)sys_getfilesystemencoding, + METH_NOARGS, getfilesystemencoding_doc}, #ifdef Py_TRACE_REFS - {"getobjects", _Py_GetObjects, METH_VARARGS}, + {"getobjects", _Py_GetObjects, METH_VARARGS}, #endif #ifdef Py_REF_DEBUG - {"gettotalrefcount", (PyCFunction)sys_gettotalrefcount, METH_NOARGS}, + {"gettotalrefcount", (PyCFunction)sys_gettotalrefcount, METH_NOARGS}, #endif - {"getrefcount", (PyCFunction)sys_getrefcount, METH_O, getrefcount_doc}, - {"getrecursionlimit", (PyCFunction)sys_getrecursionlimit, METH_NOARGS, - getrecursionlimit_doc}, - {"getsizeof", (PyCFunction)sys_getsizeof, - METH_VARARGS | METH_KEYWORDS, getsizeof_doc}, - {"_getframe", sys_getframe, METH_VARARGS, getframe_doc}, + {"getrefcount", (PyCFunction)sys_getrefcount, METH_O, getrefcount_doc}, + {"getrecursionlimit", (PyCFunction)sys_getrecursionlimit, METH_NOARGS, + getrecursionlimit_doc}, + {"getsizeof", (PyCFunction)sys_getsizeof, + METH_VARARGS | METH_KEYWORDS, getsizeof_doc}, + {"_getframe", sys_getframe, METH_VARARGS, getframe_doc}, #ifdef MS_WINDOWS - {"getwindowsversion", (PyCFunction)sys_getwindowsversion, METH_NOARGS, - getwindowsversion_doc}, + {"getwindowsversion", (PyCFunction)sys_getwindowsversion, METH_NOARGS, + getwindowsversion_doc}, #endif /* MS_WINDOWS */ - {"intern", sys_intern, METH_VARARGS, intern_doc}, + {"intern", sys_intern, METH_VARARGS, intern_doc}, #ifdef USE_MALLOPT - {"mdebug", sys_mdebug, METH_VARARGS}, + {"mdebug", sys_mdebug, METH_VARARGS}, #endif - {"setdefaultencoding", sys_setdefaultencoding, METH_VARARGS, - setdefaultencoding_doc}, - {"setfilesystemencoding", sys_setfilesystemencoding, METH_VARARGS, - setfilesystemencoding_doc}, - {"setcheckinterval", sys_setcheckinterval, METH_VARARGS, - setcheckinterval_doc}, - {"getcheckinterval", sys_getcheckinterval, METH_NOARGS, - getcheckinterval_doc}, + {"setdefaultencoding", sys_setdefaultencoding, METH_VARARGS, + setdefaultencoding_doc}, + {"setfilesystemencoding", sys_setfilesystemencoding, METH_VARARGS, + setfilesystemencoding_doc}, + {"setcheckinterval", sys_setcheckinterval, METH_VARARGS, + setcheckinterval_doc}, + {"getcheckinterval", sys_getcheckinterval, METH_NOARGS, + getcheckinterval_doc}, #ifdef HAVE_DLOPEN - {"setdlopenflags", sys_setdlopenflags, METH_VARARGS, - setdlopenflags_doc}, + {"setdlopenflags", sys_setdlopenflags, METH_VARARGS, + setdlopenflags_doc}, #endif - {"setprofile", sys_setprofile, METH_O, setprofile_doc}, - {"getprofile", sys_getprofile, METH_NOARGS, getprofile_doc}, - {"setrecursionlimit", sys_setrecursionlimit, METH_VARARGS, - setrecursionlimit_doc}, + {"setprofile", sys_setprofile, METH_O, setprofile_doc}, + {"getprofile", sys_getprofile, METH_NOARGS, getprofile_doc}, + {"setrecursionlimit", sys_setrecursionlimit, METH_VARARGS, + setrecursionlimit_doc}, #ifdef WITH_TSC - {"settscdump", sys_settscdump, METH_VARARGS, settscdump_doc}, + {"settscdump", sys_settscdump, METH_VARARGS, settscdump_doc}, #endif - {"settrace", sys_settrace, METH_O, settrace_doc}, - {"gettrace", sys_gettrace, METH_NOARGS, gettrace_doc}, - {"call_tracing", sys_call_tracing, METH_VARARGS, call_tracing_doc}, - {NULL, NULL} /* sentinel */ + {"settrace", sys_settrace, METH_O, settrace_doc}, + {"gettrace", sys_gettrace, METH_NOARGS, gettrace_doc}, + {"call_tracing", sys_call_tracing, METH_VARARGS, call_tracing_doc}, + {NULL, NULL} /* sentinel */ }; static PyObject * list_builtin_module_names(void) { - PyObject *list = PyList_New(0); - int i; - if (list == NULL) - return NULL; - for (i = 0; PyImport_Inittab[i].name != NULL; i++) { - PyObject *name = PyUnicode_FromString( - PyImport_Inittab[i].name); - if (name == NULL) - break; - PyList_Append(list, name); - Py_DECREF(name); - } - if (PyList_Sort(list) != 0) { - Py_DECREF(list); - list = NULL; - } - if (list) { - PyObject *v = PyList_AsTuple(list); - Py_DECREF(list); - list = v; - } - return list; + PyObject *list = PyList_New(0); + int i; + if (list == NULL) + return NULL; + for (i = 0; PyImport_Inittab[i].name != NULL; i++) { + PyObject *name = PyUnicode_FromString( + PyImport_Inittab[i].name); + if (name == NULL) + break; + PyList_Append(list, name); + Py_DECREF(name); + } + if (PyList_Sort(list) != 0) { + Py_DECREF(list); + list = NULL; + } + if (list) { + PyObject *v = PyList_AsTuple(list); + Py_DECREF(list); + list = v; + } + return list; } static PyObject *warnoptions = NULL; @@ -944,27 +944,27 @@ void PySys_ResetWarnOptions(void) { - if (warnoptions == NULL || !PyList_Check(warnoptions)) - return; - PyList_SetSlice(warnoptions, 0, PyList_GET_SIZE(warnoptions), NULL); + if (warnoptions == NULL || !PyList_Check(warnoptions)) + return; + PyList_SetSlice(warnoptions, 0, PyList_GET_SIZE(warnoptions), NULL); } void PySys_AddWarnOption(const wchar_t *s) { - PyObject *str; + PyObject *str; - if (warnoptions == NULL || !PyList_Check(warnoptions)) { - Py_XDECREF(warnoptions); - warnoptions = PyList_New(0); - if (warnoptions == NULL) - return; - } - str = PyUnicode_FromWideChar(s, -1); - if (str != NULL) { - PyList_Append(warnoptions, str); - Py_DECREF(str); - } + if (warnoptions == NULL || !PyList_Check(warnoptions)) { + Py_XDECREF(warnoptions); + warnoptions = PyList_New(0); + if (warnoptions == NULL) + return; + } + str = PyUnicode_FromWideChar(s, -1); + if (str != NULL) { + PyList_Append(warnoptions, str); + Py_DECREF(str); + } } int @@ -1076,64 +1076,64 @@ static void svnversion_init(void) { - const char *python, *br_start, *br_end, *br_end2, *svnversion; - Py_ssize_t len; - int istag = 0; - - if (svn_initialized) - return; - - python = strstr(headurl, "/python/"); - if (!python) { - strcpy(branch, "unknown branch"); - strcpy(shortbranch, "unknown"); - } - else { - br_start = python + 8; - br_end = strchr(br_start, '/'); - assert(br_end); - - /* Works even for trunk, - as we are in trunk/Python/sysmodule.c */ - br_end2 = strchr(br_end+1, '/'); - - istag = strncmp(br_start, "tags", 4) == 0; - if (strncmp(br_start, "trunk", 5) == 0) { - strcpy(branch, "trunk"); - strcpy(shortbranch, "trunk"); - } - else if (istag || strncmp(br_start, "branches", 8) == 0) { - len = br_end2 - br_start; - strncpy(branch, br_start, len); - branch[len] = '\0'; - - len = br_end2 - (br_end + 1); - strncpy(shortbranch, br_end + 1, len); - shortbranch[len] = '\0'; - } - else { - Py_FatalError("bad HeadURL"); - return; - } - } - - - svnversion = _Py_svnversion(); - if (strcmp(svnversion, "Unversioned directory") != 0 && strcmp(svnversion, "exported") != 0) - svn_revision = svnversion; - else if (istag) { - len = strlen(_patchlevel_revision); - assert(len >= 13); - assert(len < (sizeof(patchlevel_revision) + 13)); - strncpy(patchlevel_revision, _patchlevel_revision + 11, - len - 13); - patchlevel_revision[len - 13] = '\0'; - svn_revision = patchlevel_revision; - } - else - svn_revision = ""; + const char *python, *br_start, *br_end, *br_end2, *svnversion; + Py_ssize_t len; + int istag = 0; + + if (svn_initialized) + return; + + python = strstr(headurl, "/python/"); + if (!python) { + strcpy(branch, "unknown branch"); + strcpy(shortbranch, "unknown"); + } + else { + br_start = python + 8; + br_end = strchr(br_start, '/'); + assert(br_end); + + /* Works even for trunk, + as we are in trunk/Python/sysmodule.c */ + br_end2 = strchr(br_end+1, '/'); + + istag = strncmp(br_start, "tags", 4) == 0; + if (strncmp(br_start, "trunk", 5) == 0) { + strcpy(branch, "trunk"); + strcpy(shortbranch, "trunk"); + } + else if (istag || strncmp(br_start, "branches", 8) == 0) { + len = br_end2 - br_start; + strncpy(branch, br_start, len); + branch[len] = '\0'; + + len = br_end2 - (br_end + 1); + strncpy(shortbranch, br_end + 1, len); + shortbranch[len] = '\0'; + } + else { + Py_FatalError("bad HeadURL"); + return; + } + } + + + svnversion = _Py_svnversion(); + if (strcmp(svnversion, "Unversioned directory") != 0 && strcmp(svnversion, "exported") != 0) + svn_revision = svnversion; + else if (istag) { + len = strlen(_patchlevel_revision); + assert(len >= 13); + assert(len < (sizeof(patchlevel_revision) + 13)); + strncpy(patchlevel_revision, _patchlevel_revision + 11, + len - 13); + patchlevel_revision[len - 13] = '\0'; + svn_revision = patchlevel_revision; + } + else + svn_revision = ""; - svn_initialized = 1; + svn_initialized = 1; } /* Return svnversion output if available. @@ -1142,15 +1142,15 @@ const char* Py_SubversionRevision() { - svnversion_init(); - return svn_revision; + svnversion_init(); + return svn_revision; } const char* Py_SubversionShortBranch() { - svnversion_init(); - return shortbranch; + svnversion_init(); + return shortbranch; } @@ -1162,71 +1162,71 @@ static PyTypeObject FlagsType; static PyStructSequence_Field flags_fields[] = { - {"debug", "-d"}, - {"division_warning", "-Q"}, - {"inspect", "-i"}, - {"interactive", "-i"}, - {"optimize", "-O or -OO"}, - {"dont_write_bytecode", "-B"}, - {"no_user_site", "-s"}, - {"no_site", "-S"}, - {"ignore_environment", "-E"}, - {"verbose", "-v"}, + {"debug", "-d"}, + {"division_warning", "-Q"}, + {"inspect", "-i"}, + {"interactive", "-i"}, + {"optimize", "-O or -OO"}, + {"dont_write_bytecode", "-B"}, + {"no_user_site", "-s"}, + {"no_site", "-S"}, + {"ignore_environment", "-E"}, + {"verbose", "-v"}, #ifdef RISCOS - {"riscos_wimp", "???"}, + {"riscos_wimp", "???"}, #endif - /* {"unbuffered", "-u"}, */ - /* {"skip_first", "-x"}, */ - {"bytes_warning", "-b"}, - {0} + /* {"unbuffered", "-u"}, */ + /* {"skip_first", "-x"}, */ + {"bytes_warning", "-b"}, + {0} }; static PyStructSequence_Desc flags_desc = { - "sys.flags", /* name */ - flags__doc__, /* doc */ - flags_fields, /* fields */ + "sys.flags", /* name */ + flags__doc__, /* doc */ + flags_fields, /* fields */ #ifdef RISCOS - 12 + 12 #else - 11 + 11 #endif }; static PyObject* make_flags(void) { - int pos = 0; - PyObject *seq; + int pos = 0; + PyObject *seq; - seq = PyStructSequence_New(&FlagsType); - if (seq == NULL) - return NULL; + seq = PyStructSequence_New(&FlagsType); + if (seq == NULL) + return NULL; #define SetFlag(flag) \ - PyStructSequence_SET_ITEM(seq, pos++, PyLong_FromLong(flag)) + PyStructSequence_SET_ITEM(seq, pos++, PyLong_FromLong(flag)) - SetFlag(Py_DebugFlag); - SetFlag(Py_DivisionWarningFlag); - SetFlag(Py_InspectFlag); - SetFlag(Py_InteractiveFlag); - SetFlag(Py_OptimizeFlag); - SetFlag(Py_DontWriteBytecodeFlag); - SetFlag(Py_NoUserSiteDirectory); - SetFlag(Py_NoSiteFlag); - SetFlag(Py_IgnoreEnvironmentFlag); - SetFlag(Py_VerboseFlag); + SetFlag(Py_DebugFlag); + SetFlag(Py_DivisionWarningFlag); + SetFlag(Py_InspectFlag); + SetFlag(Py_InteractiveFlag); + SetFlag(Py_OptimizeFlag); + SetFlag(Py_DontWriteBytecodeFlag); + SetFlag(Py_NoUserSiteDirectory); + SetFlag(Py_NoSiteFlag); + SetFlag(Py_IgnoreEnvironmentFlag); + SetFlag(Py_VerboseFlag); #ifdef RISCOS - SetFlag(Py_RISCOSWimpFlag); + SetFlag(Py_RISCOSWimpFlag); #endif - /* SetFlag(saw_unbuffered_flag); */ - /* SetFlag(skipfirstline); */ + /* SetFlag(saw_unbuffered_flag); */ + /* SetFlag(skipfirstline); */ SetFlag(Py_BytesWarningFlag); #undef SetFlag - if (PyErr_Occurred()) { - return NULL; - } - return seq; + if (PyErr_Occurred()) { + return NULL; + } + return seq; } PyDoc_STRVAR(version_info__doc__, @@ -1237,320 +1237,320 @@ static PyTypeObject VersionInfoType; static PyStructSequence_Field version_info_fields[] = { - {"major", "Major release number"}, - {"minor", "Minor release number"}, - {"micro", "Patch release number"}, - {"releaselevel", "'alpha', 'beta', 'candidate', or 'release'"}, - {"serial", "Serial release number"}, - {0} + {"major", "Major release number"}, + {"minor", "Minor release number"}, + {"micro", "Patch release number"}, + {"releaselevel", "'alpha', 'beta', 'candidate', or 'release'"}, + {"serial", "Serial release number"}, + {0} }; static PyStructSequence_Desc version_info_desc = { - "sys.version_info", /* name */ - version_info__doc__, /* doc */ - version_info_fields, /* fields */ - 5 + "sys.version_info", /* name */ + version_info__doc__, /* doc */ + version_info_fields, /* fields */ + 5 }; static PyObject * make_version_info(void) { - PyObject *version_info; - char *s; - int pos = 0; - - version_info = PyStructSequence_New(&VersionInfoType); - if (version_info == NULL) { - return NULL; - } - - /* - * These release level checks are mutually exclusive and cover - * the field, so don't get too fancy with the pre-processor! - */ + PyObject *version_info; + char *s; + int pos = 0; + + version_info = PyStructSequence_New(&VersionInfoType); + if (version_info == NULL) { + return NULL; + } + + /* + * These release level checks are mutually exclusive and cover + * the field, so don't get too fancy with the pre-processor! + */ #if PY_RELEASE_LEVEL == PY_RELEASE_LEVEL_ALPHA - s = "alpha"; + s = "alpha"; #elif PY_RELEASE_LEVEL == PY_RELEASE_LEVEL_BETA - s = "beta"; + s = "beta"; #elif PY_RELEASE_LEVEL == PY_RELEASE_LEVEL_GAMMA - s = "candidate"; + s = "candidate"; #elif PY_RELEASE_LEVEL == PY_RELEASE_LEVEL_FINAL - s = "final"; + s = "final"; #endif #define SetIntItem(flag) \ - PyStructSequence_SET_ITEM(version_info, pos++, PyLong_FromLong(flag)) + PyStructSequence_SET_ITEM(version_info, pos++, PyLong_FromLong(flag)) #define SetStrItem(flag) \ - PyStructSequence_SET_ITEM(version_info, pos++, PyUnicode_FromString(flag)) + PyStructSequence_SET_ITEM(version_info, pos++, PyUnicode_FromString(flag)) - SetIntItem(PY_MAJOR_VERSION); - SetIntItem(PY_MINOR_VERSION); - SetIntItem(PY_MICRO_VERSION); - SetStrItem(s); - SetIntItem(PY_RELEASE_SERIAL); + SetIntItem(PY_MAJOR_VERSION); + SetIntItem(PY_MINOR_VERSION); + SetIntItem(PY_MICRO_VERSION); + SetStrItem(s); + SetIntItem(PY_RELEASE_SERIAL); #undef SetIntItem #undef SetStrItem - if (PyErr_Occurred()) { - Py_CLEAR(version_info); - return NULL; - } - return version_info; + if (PyErr_Occurred()) { + Py_CLEAR(version_info); + return NULL; + } + return version_info; } static struct PyModuleDef sysmodule = { - PyModuleDef_HEAD_INIT, - "sys", - sys_doc, - -1, /* multiple "initialization" just copies the module dict. */ - sys_methods, - NULL, - NULL, - NULL, - NULL + PyModuleDef_HEAD_INIT, + "sys", + sys_doc, + -1, /* multiple "initialization" just copies the module dict. */ + sys_methods, + NULL, + NULL, + NULL, + NULL }; PyObject * _PySys_Init(void) { - PyObject *m, *v, *sysdict; - char *s; + PyObject *m, *v, *sysdict; + char *s; - m = PyModule_Create(&sysmodule); - if (m == NULL) - return NULL; - sysdict = PyModule_GetDict(m); -#define SET_SYS_FROM_STRING(key, value) \ - v = value; \ - if (v != NULL) \ - PyDict_SetItemString(sysdict, key, v); \ - Py_XDECREF(v) - - /* Check that stdin is not a directory - Using shell redirection, you can redirect stdin to a directory, - crashing the Python interpreter. Catch this common mistake here - and output a useful error message. Note that under MS Windows, - the shell already prevents that. */ + m = PyModule_Create(&sysmodule); + if (m == NULL) + return NULL; + sysdict = PyModule_GetDict(m); +#define SET_SYS_FROM_STRING(key, value) \ + v = value; \ + if (v != NULL) \ + PyDict_SetItemString(sysdict, key, v); \ + Py_XDECREF(v) + + /* Check that stdin is not a directory + Using shell redirection, you can redirect stdin to a directory, + crashing the Python interpreter. Catch this common mistake here + and output a useful error message. Note that under MS Windows, + the shell already prevents that. */ #if !defined(MS_WINDOWS) - { - struct stat sb; - if (fstat(fileno(stdin), &sb) == 0 && - S_ISDIR(sb.st_mode)) { - /* There's nothing more we can do. */ - /* Py_FatalError() will core dump, so just exit. */ - PySys_WriteStderr("Python error: is a directory, cannot continue\n"); - exit(EXIT_FAILURE); - } - } -#endif - - /* stdin/stdout/stderr are now set by pythonrun.c */ - - PyDict_SetItemString(sysdict, "__displayhook__", - PyDict_GetItemString(sysdict, "displayhook")); - PyDict_SetItemString(sysdict, "__excepthook__", - PyDict_GetItemString(sysdict, "excepthook")); - SET_SYS_FROM_STRING("version", - PyUnicode_FromString(Py_GetVersion())); - SET_SYS_FROM_STRING("hexversion", - PyLong_FromLong(PY_VERSION_HEX)); - svnversion_init(); - SET_SYS_FROM_STRING("subversion", - Py_BuildValue("(UUU)", "CPython", branch, - svn_revision)); - SET_SYS_FROM_STRING("dont_write_bytecode", - PyBool_FromLong(Py_DontWriteBytecodeFlag)); - SET_SYS_FROM_STRING("api_version", - PyLong_FromLong(PYTHON_API_VERSION)); - SET_SYS_FROM_STRING("copyright", - PyUnicode_FromString(Py_GetCopyright())); - SET_SYS_FROM_STRING("platform", - PyUnicode_FromString(Py_GetPlatform())); - SET_SYS_FROM_STRING("executable", - PyUnicode_FromWideChar( - Py_GetProgramFullPath(), -1)); - SET_SYS_FROM_STRING("prefix", - PyUnicode_FromWideChar(Py_GetPrefix(), -1)); - SET_SYS_FROM_STRING("exec_prefix", - PyUnicode_FromWideChar(Py_GetExecPrefix(), -1)); - SET_SYS_FROM_STRING("maxsize", - PyLong_FromSsize_t(PY_SSIZE_T_MAX)); - SET_SYS_FROM_STRING("float_info", - PyFloat_GetInfo()); - SET_SYS_FROM_STRING("int_info", - PyLong_GetInfo()); - SET_SYS_FROM_STRING("maxunicode", - PyLong_FromLong(PyUnicode_GetMax())); - SET_SYS_FROM_STRING("builtin_module_names", - list_builtin_module_names()); - { - /* Assumes that longs are at least 2 bytes long. - Should be safe! */ - unsigned long number = 1; - char *value; - - s = (char *) &number; - if (s[0] == 0) - value = "big"; - else - value = "little"; - SET_SYS_FROM_STRING("byteorder", - PyUnicode_FromString(value)); - } + { + struct stat sb; + if (fstat(fileno(stdin), &sb) == 0 && + S_ISDIR(sb.st_mode)) { + /* There's nothing more we can do. */ + /* Py_FatalError() will core dump, so just exit. */ + PySys_WriteStderr("Python error: is a directory, cannot continue\n"); + exit(EXIT_FAILURE); + } + } +#endif + + /* stdin/stdout/stderr are now set by pythonrun.c */ + + PyDict_SetItemString(sysdict, "__displayhook__", + PyDict_GetItemString(sysdict, "displayhook")); + PyDict_SetItemString(sysdict, "__excepthook__", + PyDict_GetItemString(sysdict, "excepthook")); + SET_SYS_FROM_STRING("version", + PyUnicode_FromString(Py_GetVersion())); + SET_SYS_FROM_STRING("hexversion", + PyLong_FromLong(PY_VERSION_HEX)); + svnversion_init(); + SET_SYS_FROM_STRING("subversion", + Py_BuildValue("(UUU)", "CPython", branch, + svn_revision)); + SET_SYS_FROM_STRING("dont_write_bytecode", + PyBool_FromLong(Py_DontWriteBytecodeFlag)); + SET_SYS_FROM_STRING("api_version", + PyLong_FromLong(PYTHON_API_VERSION)); + SET_SYS_FROM_STRING("copyright", + PyUnicode_FromString(Py_GetCopyright())); + SET_SYS_FROM_STRING("platform", + PyUnicode_FromString(Py_GetPlatform())); + SET_SYS_FROM_STRING("executable", + PyUnicode_FromWideChar( + Py_GetProgramFullPath(), -1)); + SET_SYS_FROM_STRING("prefix", + PyUnicode_FromWideChar(Py_GetPrefix(), -1)); + SET_SYS_FROM_STRING("exec_prefix", + PyUnicode_FromWideChar(Py_GetExecPrefix(), -1)); + SET_SYS_FROM_STRING("maxsize", + PyLong_FromSsize_t(PY_SSIZE_T_MAX)); + SET_SYS_FROM_STRING("float_info", + PyFloat_GetInfo()); + SET_SYS_FROM_STRING("int_info", + PyLong_GetInfo()); + SET_SYS_FROM_STRING("maxunicode", + PyLong_FromLong(PyUnicode_GetMax())); + SET_SYS_FROM_STRING("builtin_module_names", + list_builtin_module_names()); + { + /* Assumes that longs are at least 2 bytes long. + Should be safe! */ + unsigned long number = 1; + char *value; + + s = (char *) &number; + if (s[0] == 0) + value = "big"; + else + value = "little"; + SET_SYS_FROM_STRING("byteorder", + PyUnicode_FromString(value)); + } #ifdef MS_COREDLL - SET_SYS_FROM_STRING("dllhandle", - PyLong_FromVoidPtr(PyWin_DLLhModule)); - SET_SYS_FROM_STRING("winver", - PyUnicode_FromString(PyWin_DLLVersionString)); -#endif - if (warnoptions == NULL) { - warnoptions = PyList_New(0); - } - else { - Py_INCREF(warnoptions); - } - if (warnoptions != NULL) { - PyDict_SetItemString(sysdict, "warnoptions", warnoptions); - } - - /* version_info */ - if (VersionInfoType.tp_name == 0) - PyStructSequence_InitType(&VersionInfoType, &version_info_desc); - SET_SYS_FROM_STRING("version_info", make_version_info()); - /* prevent user from creating new instances */ - VersionInfoType.tp_init = NULL; - VersionInfoType.tp_new = NULL; - - /* flags */ - if (FlagsType.tp_name == 0) - PyStructSequence_InitType(&FlagsType, &flags_desc); - SET_SYS_FROM_STRING("flags", make_flags()); - /* prevent user from creating new instances */ - FlagsType.tp_init = NULL; - FlagsType.tp_new = NULL; + SET_SYS_FROM_STRING("dllhandle", + PyLong_FromVoidPtr(PyWin_DLLhModule)); + SET_SYS_FROM_STRING("winver", + PyUnicode_FromString(PyWin_DLLVersionString)); +#endif + if (warnoptions == NULL) { + warnoptions = PyList_New(0); + } + else { + Py_INCREF(warnoptions); + } + if (warnoptions != NULL) { + PyDict_SetItemString(sysdict, "warnoptions", warnoptions); + } + + /* version_info */ + if (VersionInfoType.tp_name == 0) + PyStructSequence_InitType(&VersionInfoType, &version_info_desc); + SET_SYS_FROM_STRING("version_info", make_version_info()); + /* prevent user from creating new instances */ + VersionInfoType.tp_init = NULL; + VersionInfoType.tp_new = NULL; + + /* flags */ + if (FlagsType.tp_name == 0) + PyStructSequence_InitType(&FlagsType, &flags_desc); + SET_SYS_FROM_STRING("flags", make_flags()); + /* prevent user from creating new instances */ + FlagsType.tp_init = NULL; + FlagsType.tp_new = NULL; - /* float repr style: 0.03 (short) vs 0.029999999999999999 (legacy) */ + /* float repr style: 0.03 (short) vs 0.029999999999999999 (legacy) */ #ifndef PY_NO_SHORT_FLOAT_REPR - SET_SYS_FROM_STRING("float_repr_style", - PyUnicode_FromString("short")); + SET_SYS_FROM_STRING("float_repr_style", + PyUnicode_FromString("short")); #else - SET_SYS_FROM_STRING("float_repr_style", - PyUnicode_FromString("legacy")); + SET_SYS_FROM_STRING("float_repr_style", + PyUnicode_FromString("legacy")); #endif #undef SET_SYS_FROM_STRING - if (PyErr_Occurred()) - return NULL; - return m; + if (PyErr_Occurred()) + return NULL; + return m; } static PyObject * makepathobject(const wchar_t *path, wchar_t delim) { - int i, n; - const wchar_t *p; - PyObject *v, *w; - - n = 1; - p = path; - while ((p = wcschr(p, delim)) != NULL) { - n++; - p++; - } - v = PyList_New(n); - if (v == NULL) - return NULL; - for (i = 0; ; i++) { - p = wcschr(path, delim); - if (p == NULL) - p = path + wcslen(path); /* End of string */ - w = PyUnicode_FromWideChar(path, (Py_ssize_t)(p - path)); - if (w == NULL) { - Py_DECREF(v); - return NULL; - } - PyList_SetItem(v, i, w); - if (*p == '\0') - break; - path = p+1; - } - return v; + int i, n; + const wchar_t *p; + PyObject *v, *w; + + n = 1; + p = path; + while ((p = wcschr(p, delim)) != NULL) { + n++; + p++; + } + v = PyList_New(n); + if (v == NULL) + return NULL; + for (i = 0; ; i++) { + p = wcschr(path, delim); + if (p == NULL) + p = path + wcslen(path); /* End of string */ + w = PyUnicode_FromWideChar(path, (Py_ssize_t)(p - path)); + if (w == NULL) { + Py_DECREF(v); + return NULL; + } + PyList_SetItem(v, i, w); + if (*p == '\0') + break; + path = p+1; + } + return v; } void PySys_SetPath(const wchar_t *path) { - PyObject *v; - if ((v = makepathobject(path, DELIM)) == NULL) - Py_FatalError("can't create sys.path"); - if (PySys_SetObject("path", v) != 0) - Py_FatalError("can't assign sys.path"); - Py_DECREF(v); + PyObject *v; + if ((v = makepathobject(path, DELIM)) == NULL) + Py_FatalError("can't create sys.path"); + if (PySys_SetObject("path", v) != 0) + Py_FatalError("can't assign sys.path"); + Py_DECREF(v); } static PyObject * makeargvobject(int argc, wchar_t **argv) { - PyObject *av; - if (argc <= 0 || argv == NULL) { - /* Ensure at least one (empty) argument is seen */ - static wchar_t *empty_argv[1] = {L""}; - argv = empty_argv; - argc = 1; - } - av = PyList_New(argc); - if (av != NULL) { - int i; - for (i = 0; i < argc; i++) { + PyObject *av; + if (argc <= 0 || argv == NULL) { + /* Ensure at least one (empty) argument is seen */ + static wchar_t *empty_argv[1] = {L""}; + argv = empty_argv; + argc = 1; + } + av = PyList_New(argc); + if (av != NULL) { + int i; + for (i = 0; i < argc; i++) { #ifdef __VMS - PyObject *v; + PyObject *v; - /* argv[0] is the script pathname if known */ - if (i == 0) { - char* fn = decc$translate_vms(argv[0]); - if ((fn == (char *)0) || fn == (char *)-1) - v = PyUnicode_FromString(argv[0]); - else - v = PyUnicode_FromString( - decc$translate_vms(argv[0])); - } else - v = PyUnicode_FromString(argv[i]); + /* argv[0] is the script pathname if known */ + if (i == 0) { + char* fn = decc$translate_vms(argv[0]); + if ((fn == (char *)0) || fn == (char *)-1) + v = PyUnicode_FromString(argv[0]); + else + v = PyUnicode_FromString( + decc$translate_vms(argv[0])); + } else + v = PyUnicode_FromString(argv[i]); #else - PyObject *v = PyUnicode_FromWideChar(argv[i], -1); + PyObject *v = PyUnicode_FromWideChar(argv[i], -1); #endif - if (v == NULL) { - Py_DECREF(av); - av = NULL; - break; - } - PyList_SetItem(av, i, v); - } - } - return av; + if (v == NULL) { + Py_DECREF(av); + av = NULL; + break; + } + PyList_SetItem(av, i, v); + } + } + return av; } #ifdef HAVE_REALPATH static wchar_t* _wrealpath(const wchar_t *path, wchar_t *resolved_path) { - char cpath[PATH_MAX]; - char cresolved_path[PATH_MAX]; - char *res; - size_t r; - r = wcstombs(cpath, path, PATH_MAX); - if (r == (size_t)-1 || r >= PATH_MAX) { - errno = EINVAL; - return NULL; - } - res = realpath(cpath, cresolved_path); - if (res == NULL) - return NULL; - r = mbstowcs(resolved_path, cresolved_path, PATH_MAX); - if (r == (size_t)-1 || r >= PATH_MAX) { - errno = EINVAL; - return NULL; - } - return resolved_path; + char cpath[PATH_MAX]; + char cresolved_path[PATH_MAX]; + char *res; + size_t r; + r = wcstombs(cpath, path, PATH_MAX); + if (r == (size_t)-1 || r >= PATH_MAX) { + errno = EINVAL; + return NULL; + } + res = realpath(cpath, cresolved_path); + if (res == NULL) + return NULL; + r = mbstowcs(resolved_path, cresolved_path, PATH_MAX); + if (r == (size_t)-1 || r >= PATH_MAX) { + errno = EINVAL; + return NULL; + } + return resolved_path; } #endif @@ -1558,101 +1558,101 @@ PySys_SetArgv(int argc, wchar_t **argv) { #if defined(HAVE_REALPATH) - wchar_t fullpath[MAXPATHLEN]; + wchar_t fullpath[MAXPATHLEN]; #elif defined(MS_WINDOWS) && !defined(MS_WINCE) - wchar_t fullpath[MAX_PATH]; + wchar_t fullpath[MAX_PATH]; #endif - PyObject *av = makeargvobject(argc, argv); - PyObject *path = PySys_GetObject("path"); - if (av == NULL) - Py_FatalError("no mem for sys.argv"); - if (PySys_SetObject("argv", av) != 0) - Py_FatalError("can't assign sys.argv"); - if (path != NULL) { - wchar_t *argv0 = argv[0]; - wchar_t *p = NULL; - Py_ssize_t n = 0; - PyObject *a; - extern int _Py_wreadlink(const wchar_t *, wchar_t *, size_t); + PyObject *av = makeargvobject(argc, argv); + PyObject *path = PySys_GetObject("path"); + if (av == NULL) + Py_FatalError("no mem for sys.argv"); + if (PySys_SetObject("argv", av) != 0) + Py_FatalError("can't assign sys.argv"); + if (path != NULL) { + wchar_t *argv0 = argv[0]; + wchar_t *p = NULL; + Py_ssize_t n = 0; + PyObject *a; + extern int _Py_wreadlink(const wchar_t *, wchar_t *, size_t); #ifdef HAVE_READLINK - wchar_t link[MAXPATHLEN+1]; - wchar_t argv0copy[2*MAXPATHLEN+1]; - int nr = 0; - if (argc > 0 && argv0 != NULL && wcscmp(argv0, L"-c") != 0) - nr = _Py_wreadlink(argv0, link, MAXPATHLEN); - if (nr > 0) { - /* It's a symlink */ - link[nr] = '\0'; - if (link[0] == SEP) - argv0 = link; /* Link to absolute path */ - else if (wcschr(link, SEP) == NULL) - ; /* Link without path */ - else { - /* Must join(dirname(argv0), link) */ - wchar_t *q = wcsrchr(argv0, SEP); - if (q == NULL) - argv0 = link; /* argv0 without path */ - else { - /* Must make a copy */ - wcscpy(argv0copy, argv0); - q = wcsrchr(argv0copy, SEP); - wcscpy(q+1, link); - argv0 = argv0copy; - } - } - } + wchar_t link[MAXPATHLEN+1]; + wchar_t argv0copy[2*MAXPATHLEN+1]; + int nr = 0; + if (argc > 0 && argv0 != NULL && wcscmp(argv0, L"-c") != 0) + nr = _Py_wreadlink(argv0, link, MAXPATHLEN); + if (nr > 0) { + /* It's a symlink */ + link[nr] = '\0'; + if (link[0] == SEP) + argv0 = link; /* Link to absolute path */ + else if (wcschr(link, SEP) == NULL) + ; /* Link without path */ + else { + /* Must join(dirname(argv0), link) */ + wchar_t *q = wcsrchr(argv0, SEP); + if (q == NULL) + argv0 = link; /* argv0 without path */ + else { + /* Must make a copy */ + wcscpy(argv0copy, argv0); + q = wcsrchr(argv0copy, SEP); + wcscpy(q+1, link); + argv0 = argv0copy; + } + } + } #endif /* HAVE_READLINK */ #if SEP == '\\' /* Special case for MS filename syntax */ - if (argc > 0 && argv0 != NULL && wcscmp(argv0, L"-c") != 0) { - wchar_t *q; + if (argc > 0 && argv0 != NULL && wcscmp(argv0, L"-c") != 0) { + wchar_t *q; #if defined(MS_WINDOWS) && !defined(MS_WINCE) - /* This code here replaces the first element in argv with the full - path that it represents. Under CE, there are no relative paths so - the argument must be the full path anyway. */ - wchar_t *ptemp; - if (GetFullPathNameW(argv0, - sizeof(fullpath)/sizeof(fullpath[0]), - fullpath, - &ptemp)) { - argv0 = fullpath; - } -#endif - p = wcsrchr(argv0, SEP); - /* Test for alternate separator */ - q = wcsrchr(p ? p : argv0, '/'); - if (q != NULL) - p = q; - if (p != NULL) { - n = p + 1 - argv0; - if (n > 1 && p[-1] != ':') - n--; /* Drop trailing separator */ - } - } + /* This code here replaces the first element in argv with the full + path that it represents. Under CE, there are no relative paths so + the argument must be the full path anyway. */ + wchar_t *ptemp; + if (GetFullPathNameW(argv0, + sizeof(fullpath)/sizeof(fullpath[0]), + fullpath, + &ptemp)) { + argv0 = fullpath; + } +#endif + p = wcsrchr(argv0, SEP); + /* Test for alternate separator */ + q = wcsrchr(p ? p : argv0, '/'); + if (q != NULL) + p = q; + if (p != NULL) { + n = p + 1 - argv0; + if (n > 1 && p[-1] != ':') + n--; /* Drop trailing separator */ + } + } #else /* All other filename syntaxes */ - if (argc > 0 && argv0 != NULL && wcscmp(argv0, L"-c") != 0) { + if (argc > 0 && argv0 != NULL && wcscmp(argv0, L"-c") != 0) { #if defined(HAVE_REALPATH) - if (_wrealpath(argv0, fullpath)) { - argv0 = fullpath; - } -#endif - p = wcsrchr(argv0, SEP); - } - if (p != NULL) { - n = p + 1 - argv0; + if (_wrealpath(argv0, fullpath)) { + argv0 = fullpath; + } +#endif + p = wcsrchr(argv0, SEP); + } + if (p != NULL) { + n = p + 1 - argv0; #if SEP == '/' /* Special case for Unix filename syntax */ - if (n > 1) - n--; /* Drop trailing separator */ + if (n > 1) + n--; /* Drop trailing separator */ #endif /* Unix */ - } + } #endif /* All others */ - a = PyUnicode_FromWideChar(argv0, n); - if (a == NULL) - Py_FatalError("no mem for sys.path insertion"); - if (PyList_Insert(path, 0, a) < 0) - Py_FatalError("sys.path.insert(0) failed"); - Py_DECREF(a); - } - Py_DECREF(av); + a = PyUnicode_FromWideChar(argv0, n); + if (a == NULL) + Py_FatalError("no mem for sys.path insertion"); + if (PyList_Insert(path, 0, a) < 0) + Py_FatalError("sys.path.insert(0) failed"); + Py_DECREF(a); + } + Py_DECREF(av); } /* Reimplementation of PyFile_WriteString() no calling indirectly @@ -1661,37 +1661,37 @@ static int sys_pyfile_write(const char *text, PyObject *file) { - PyObject *unicode = NULL, *writer = NULL, *args = NULL, *result = NULL; - int err; + PyObject *unicode = NULL, *writer = NULL, *args = NULL, *result = NULL; + int err; - unicode = PyUnicode_FromString(text); - if (unicode == NULL) - goto error; - - writer = PyObject_GetAttrString(file, "write"); - if (writer == NULL) - goto error; - - args = PyTuple_Pack(1, unicode); - if (args == NULL) - goto error; - - result = PyEval_CallObject(writer, args); - if (result == NULL) { - goto error; - } else { - err = 0; - goto finally; - } + unicode = PyUnicode_FromString(text); + if (unicode == NULL) + goto error; + + writer = PyObject_GetAttrString(file, "write"); + if (writer == NULL) + goto error; + + args = PyTuple_Pack(1, unicode); + if (args == NULL) + goto error; + + result = PyEval_CallObject(writer, args); + if (result == NULL) { + goto error; + } else { + err = 0; + goto finally; + } error: - err = -1; + err = -1; finally: - Py_XDECREF(unicode); - Py_XDECREF(writer); - Py_XDECREF(args); - Py_XDECREF(result); - return err; + Py_XDECREF(unicode); + Py_XDECREF(writer); + Py_XDECREF(args); + Py_XDECREF(result); + return err; } @@ -1726,44 +1726,44 @@ static void mywrite(char *name, FILE *fp, const char *format, va_list va) { - PyObject *file; - PyObject *error_type, *error_value, *error_traceback; - char buffer[1001]; - int written; - - PyErr_Fetch(&error_type, &error_value, &error_traceback); - file = PySys_GetObject(name); - written = PyOS_vsnprintf(buffer, sizeof(buffer), format, va); - if (sys_pyfile_write(buffer, file) != 0) { - PyErr_Clear(); - fputs(buffer, fp); - } - if (written < 0 || (size_t)written >= sizeof(buffer)) { - const char *truncated = "... truncated"; - if (sys_pyfile_write(truncated, file) != 0) { - PyErr_Clear(); - fputs(truncated, fp); - } - } - PyErr_Restore(error_type, error_value, error_traceback); + PyObject *file; + PyObject *error_type, *error_value, *error_traceback; + char buffer[1001]; + int written; + + PyErr_Fetch(&error_type, &error_value, &error_traceback); + file = PySys_GetObject(name); + written = PyOS_vsnprintf(buffer, sizeof(buffer), format, va); + if (sys_pyfile_write(buffer, file) != 0) { + PyErr_Clear(); + fputs(buffer, fp); + } + if (written < 0 || (size_t)written >= sizeof(buffer)) { + const char *truncated = "... truncated"; + if (sys_pyfile_write(truncated, file) != 0) { + PyErr_Clear(); + fputs(truncated, fp); + } + } + PyErr_Restore(error_type, error_value, error_traceback); } void PySys_WriteStdout(const char *format, ...) { - va_list va; + va_list va; - va_start(va, format); - mywrite("stdout", stdout, format, va); - va_end(va); + va_start(va, format); + mywrite("stdout", stdout, format, va); + va_end(va); } void PySys_WriteStderr(const char *format, ...) { - va_list va; + va_list va; - va_start(va, format); - mywrite("stderr", stderr, format, va); - va_end(va); + va_start(va, format); + mywrite("stderr", stderr, format, va); + va_end(va); } Modified: python/branches/release31-maint/Python/thread.c ============================================================================== --- python/branches/release31-maint/Python/thread.c (original) +++ python/branches/release31-maint/Python/thread.c Sun May 9 18:14:21 2010 @@ -46,7 +46,7 @@ #endif /* Check if we're running on HP-UX and _SC_THREADS is defined. If so, then - enough of the Posix threads package is implimented to support python + enough of the Posix threads package is implimented to support python threads. This is valid for HP-UX 11.23 running on an ia64 system. If needed, add @@ -64,8 +64,8 @@ #ifdef Py_DEBUG static int thread_debug = 0; -#define dprintf(args) (void)((thread_debug & 1) && printf args) -#define d2printf(args) ((thread_debug & 8) && printf args) +#define dprintf(args) (void)((thread_debug & 1) && printf args) +#define d2printf(args) ((thread_debug & 8) && printf args) #else #define dprintf(args) #define d2printf(args) @@ -79,20 +79,20 @@ PyThread_init_thread(void) { #ifdef Py_DEBUG - char *p = Py_GETENV("PYTHONTHREADDEBUG"); + char *p = Py_GETENV("PYTHONTHREADDEBUG"); - if (p) { - if (*p) - thread_debug = atoi(p); - else - thread_debug = 1; - } + if (p) { + if (*p) + thread_debug = atoi(p); + else + thread_debug = 1; + } #endif /* Py_DEBUG */ - if (initialized) - return; - initialized = 1; - dprintf(("PyThread_init_thread called\n")); - PyThread__init_thread(); + if (initialized) + return; + initialized = 1; + dprintf(("PyThread_init_thread called\n")); + PyThread__init_thread(); } /* Support for runtime thread stack size tuning. @@ -151,21 +151,21 @@ size_t PyThread_get_stacksize(void) { - return _pythread_stacksize; + return _pythread_stacksize; } /* Only platforms defining a THREAD_SET_STACKSIZE() macro in thread_.h support changing the stack size. Return 0 if stack size is valid, - -1 if stack size value is invalid, - -2 if setting stack size is not supported. */ + -1 if stack size value is invalid, + -2 if setting stack size is not supported. */ int PyThread_set_stacksize(size_t size) { #if defined(THREAD_SET_STACKSIZE) - return THREAD_SET_STACKSIZE(size); + return THREAD_SET_STACKSIZE(size); #else - return -2; + return -2; #endif } @@ -217,15 +217,15 @@ * to enforce exclusion internally. */ struct key { - /* Next record in the list, or NULL if this is the last record. */ - struct key *next; + /* Next record in the list, or NULL if this is the last record. */ + struct key *next; - /* The thread id, according to PyThread_get_thread_ident(). */ - long id; + /* The thread id, according to PyThread_get_thread_ident(). */ + long id; - /* The key and its associated value. */ - int key; - void *value; + /* The key and its associated value. */ + int key; + void *value; }; static struct key *keyhead = NULL; @@ -256,41 +256,41 @@ static struct key * find_key(int key, void *value) { - struct key *p, *prev_p; - long id = PyThread_get_thread_ident(); + struct key *p, *prev_p; + long id = PyThread_get_thread_ident(); - if (!keymutex) - return NULL; - PyThread_acquire_lock(keymutex, 1); - prev_p = NULL; - for (p = keyhead; p != NULL; p = p->next) { - if (p->id == id && p->key == key) - goto Done; - /* Sanity check. These states should never happen but if - * they do we must abort. Otherwise we'll end up spinning in - * in a tight loop with the lock held. A similar check is done - * in pystate.c tstate_delete_common(). */ - if (p == prev_p) - Py_FatalError("tls find_key: small circular list(!)"); - prev_p = p; - if (p->next == keyhead) - Py_FatalError("tls find_key: circular list(!)"); - } - if (value == NULL) { - assert(p == NULL); - goto Done; - } - p = (struct key *)malloc(sizeof(struct key)); - if (p != NULL) { - p->id = id; - p->key = key; - p->value = value; - p->next = keyhead; - keyhead = p; - } + if (!keymutex) + return NULL; + PyThread_acquire_lock(keymutex, 1); + prev_p = NULL; + for (p = keyhead; p != NULL; p = p->next) { + if (p->id == id && p->key == key) + goto Done; + /* Sanity check. These states should never happen but if + * they do we must abort. Otherwise we'll end up spinning in + * in a tight loop with the lock held. A similar check is done + * in pystate.c tstate_delete_common(). */ + if (p == prev_p) + Py_FatalError("tls find_key: small circular list(!)"); + prev_p = p; + if (p->next == keyhead) + Py_FatalError("tls find_key: circular list(!)"); + } + if (value == NULL) { + assert(p == NULL); + goto Done; + } + p = (struct key *)malloc(sizeof(struct key)); + if (p != NULL) { + p->id = id; + p->key = key; + p->value = value; + p->next = keyhead; + keyhead = p; + } Done: - PyThread_release_lock(keymutex); - return p; + PyThread_release_lock(keymutex); + return p; } /* Return a new key. This must be called before any other functions in @@ -300,32 +300,32 @@ int PyThread_create_key(void) { - /* All parts of this function are wrong if it's called by multiple - * threads simultaneously. - */ - if (keymutex == NULL) - keymutex = PyThread_allocate_lock(); - return ++nkeys; + /* All parts of this function are wrong if it's called by multiple + * threads simultaneously. + */ + if (keymutex == NULL) + keymutex = PyThread_allocate_lock(); + return ++nkeys; } /* Forget the associations for key across *all* threads. */ void PyThread_delete_key(int key) { - struct key *p, **q; + struct key *p, **q; - PyThread_acquire_lock(keymutex, 1); - q = &keyhead; - while ((p = *q) != NULL) { - if (p->key == key) { - *q = p->next; - free((void *)p); - /* NB This does *not* free p->value! */ - } - else - q = &p->next; - } - PyThread_release_lock(keymutex); + PyThread_acquire_lock(keymutex, 1); + q = &keyhead; + while ((p = *q) != NULL) { + if (p->key == key) { + *q = p->next; + free((void *)p); + /* NB This does *not* free p->value! */ + } + else + q = &p->next; + } + PyThread_release_lock(keymutex); } /* Confusing: If the current thread has an association for key, @@ -337,14 +337,14 @@ int PyThread_set_key_value(int key, void *value) { - struct key *p; + struct key *p; - assert(value != NULL); - p = find_key(key, value); - if (p == NULL) - return -1; - else - return 0; + assert(value != NULL); + p = find_key(key, value); + if (p == NULL) + return -1; + else + return 0; } /* Retrieve the value associated with key in the current thread, or NULL @@ -353,34 +353,34 @@ void * PyThread_get_key_value(int key) { - struct key *p = find_key(key, NULL); + struct key *p = find_key(key, NULL); - if (p == NULL) - return NULL; - else - return p->value; + if (p == NULL) + return NULL; + else + return p->value; } /* Forget the current thread's association for key, if any. */ void PyThread_delete_key_value(int key) { - long id = PyThread_get_thread_ident(); - struct key *p, **q; + long id = PyThread_get_thread_ident(); + struct key *p, **q; - PyThread_acquire_lock(keymutex, 1); - q = &keyhead; - while ((p = *q) != NULL) { - if (p->key == key && p->id == id) { - *q = p->next; - free((void *)p); - /* NB This does *not* free p->value! */ - break; - } - else - q = &p->next; - } - PyThread_release_lock(keymutex); + PyThread_acquire_lock(keymutex, 1); + q = &keyhead; + while ((p = *q) != NULL) { + if (p->key == key && p->id == id) { + *q = p->next; + free((void *)p); + /* NB This does *not* free p->value! */ + break; + } + else + q = &p->next; + } + PyThread_release_lock(keymutex); } /* Forget everything not associated with the current thread id. @@ -391,27 +391,27 @@ void PyThread_ReInitTLS(void) { - long id = PyThread_get_thread_ident(); - struct key *p, **q; + long id = PyThread_get_thread_ident(); + struct key *p, **q; - if (!keymutex) - return; - - /* As with interpreter_lock in PyEval_ReInitThreads() - we just create a new lock without freeing the old one */ - keymutex = PyThread_allocate_lock(); - - /* Delete all keys which do not match the current thread id */ - q = &keyhead; - while ((p = *q) != NULL) { - if (p->id != id) { - *q = p->next; - free((void *)p); - /* NB This does *not* free p->value! */ - } - else - q = &p->next; - } + if (!keymutex) + return; + + /* As with interpreter_lock in PyEval_ReInitThreads() + we just create a new lock without freeing the old one */ + keymutex = PyThread_allocate_lock(); + + /* Delete all keys which do not match the current thread id */ + q = &keyhead; + while ((p = *q) != NULL) { + if (p->id != id) { + *q = p->next; + free((void *)p); + /* NB This does *not* free p->value! */ + } + else + q = &p->next; + } } #endif /* Py_HAVE_NATIVE_TLS */ Modified: python/branches/release31-maint/Python/thread_atheos.h ============================================================================== --- python/branches/release31-maint/Python/thread_atheos.h (original) +++ python/branches/release31-maint/Python/thread_atheos.h Sun May 9 18:14:21 2010 @@ -19,8 +19,8 @@ /* Use an atomic counter and a semaphore for maximum speed. */ typedef struct fastmutex { - sem_id sem; - atomic_t count; + sem_id sem; + atomic_t count; } fastmutex_t; @@ -33,49 +33,49 @@ static int fastmutex_create(const char *name, fastmutex_t * mutex) { - mutex->count = 0; - mutex->sem = create_semaphore(name, 0, 0); - return (mutex->sem < 0) ? -1 : 0; + mutex->count = 0; + mutex->sem = create_semaphore(name, 0, 0); + return (mutex->sem < 0) ? -1 : 0; } static int fastmutex_destroy(fastmutex_t * mutex) { - if (fastmutex_timedlock(mutex, 0) == 0 || errno == EWOULDBLOCK) { - return delete_semaphore(mutex->sem); - } - return 0; + if (fastmutex_timedlock(mutex, 0) == 0 || errno == EWOULDBLOCK) { + return delete_semaphore(mutex->sem); + } + return 0; } static int fastmutex_lock(fastmutex_t * mutex) { - atomic_t prev = atomic_add(&mutex->count, 1); - if (prev > 0) - return lock_semaphore(mutex->sem); - return 0; + atomic_t prev = atomic_add(&mutex->count, 1); + if (prev > 0) + return lock_semaphore(mutex->sem); + return 0; } static int fastmutex_timedlock(fastmutex_t * mutex, bigtime_t timeout) { - atomic_t prev = atomic_add(&mutex->count, 1); - if (prev > 0) - return lock_semaphore_x(mutex->sem, 1, 0, timeout); - return 0; + atomic_t prev = atomic_add(&mutex->count, 1); + if (prev > 0) + return lock_semaphore_x(mutex->sem, 1, 0, timeout); + return 0; } static int fastmutex_unlock(fastmutex_t * mutex) { - atomic_t prev = atomic_add(&mutex->count, -1); - if (prev > 1) - return unlock_semaphore(mutex->sem); - return 0; + atomic_t prev = atomic_add(&mutex->count, -1); + if (prev > 1) + return unlock_semaphore(mutex->sem); + return 0; } -#endif /* FASTLOCK */ +#endif /* FASTLOCK */ /* @@ -84,8 +84,8 @@ */ static void PyThread__init_thread(void) { - /* Do nothing. */ - return; + /* Do nothing. */ + return; } @@ -98,90 +98,90 @@ long PyThread_start_new_thread(void (*func) (void *), void *arg) { - status_t success = -1; - thread_id tid; - char name[OS_NAME_LENGTH]; - atomic_t this_thread; - - dprintf(("PyThread_start_new_thread called\n")); - - this_thread = atomic_add(&thread_count, 1); - PyOS_snprintf(name, sizeof(name), "python thread (%d)", this_thread); - - tid = spawn_thread(name, func, NORMAL_PRIORITY, 0, arg); - if (tid < 0) { - dprintf(("PyThread_start_new_thread spawn_thread failed: %s\n", strerror(errno))); - } else { - success = resume_thread(tid); - if (success < 0) { - dprintf(("PyThread_start_new_thread resume_thread failed: %s\n", strerror(errno))); - } - } + status_t success = -1; + thread_id tid; + char name[OS_NAME_LENGTH]; + atomic_t this_thread; + + dprintf(("PyThread_start_new_thread called\n")); + + this_thread = atomic_add(&thread_count, 1); + PyOS_snprintf(name, sizeof(name), "python thread (%d)", this_thread); + + tid = spawn_thread(name, func, NORMAL_PRIORITY, 0, arg); + if (tid < 0) { + dprintf(("PyThread_start_new_thread spawn_thread failed: %s\n", strerror(errno))); + } else { + success = resume_thread(tid); + if (success < 0) { + dprintf(("PyThread_start_new_thread resume_thread failed: %s\n", strerror(errno))); + } + } - return (success < 0 ? -1 : tid); + return (success < 0 ? -1 : tid); } long PyThread_get_thread_ident(void) { - return get_thread_id(NULL); + return get_thread_id(NULL); } static void do_PyThread_exit_thread(int no_cleanup) { - dprintf(("PyThread_exit_thread called\n")); + dprintf(("PyThread_exit_thread called\n")); - /* Thread-safe way to read a variable without a mutex: */ - if (atomic_add(&thread_count, 0) == 0) { - /* No threads around, so exit main(). */ - if (no_cleanup) - _exit(0); - else - exit(0); - } else { - /* We're a thread */ - exit_thread(0); - } + /* Thread-safe way to read a variable without a mutex: */ + if (atomic_add(&thread_count, 0) == 0) { + /* No threads around, so exit main(). */ + if (no_cleanup) + _exit(0); + else + exit(0); + } else { + /* We're a thread */ + exit_thread(0); + } } void PyThread_exit_thread(void) { - do_PyThread_exit_thread(0); + do_PyThread_exit_thread(0); } void PyThread__exit_thread(void) { - do_PyThread_exit_thread(1); + do_PyThread_exit_thread(1); } #ifndef NO_EXIT_PROG static void do_PyThread_exit_prog(int status, int no_cleanup) { - dprintf(("PyThread_exit_prog(%d) called\n", status)); + dprintf(("PyThread_exit_prog(%d) called\n", status)); - /* No need to do anything, the threads get torn down if main()exits. */ - if (no_cleanup) - _exit(status); - else - exit(status); + /* No need to do anything, the threads get torn down if main()exits. */ + if (no_cleanup) + _exit(status); + else + exit(status); } void PyThread_exit_prog(int status) { - do_PyThread_exit_prog(status, 0); + do_PyThread_exit_prog(status, 0); } void PyThread__exit_prog(int status) { - do_PyThread_exit_prog(status, 1); + do_PyThread_exit_prog(status, 1); } -#endif /* NO_EXIT_PROG */ +#endif /* NO_EXIT_PROG */ /* @@ -194,107 +194,107 @@ PyThread_type_lock PyThread_allocate_lock(void) { #ifdef FASTLOCK - fastmutex_t *lock; + fastmutex_t *lock; #else - sem_id sema; + sem_id sema; #endif - char name[OS_NAME_LENGTH]; - atomic_t this_lock; + char name[OS_NAME_LENGTH]; + atomic_t this_lock; - dprintf(("PyThread_allocate_lock called\n")); + dprintf(("PyThread_allocate_lock called\n")); #ifdef FASTLOCK - lock = (fastmutex_t *) malloc(sizeof(fastmutex_t)); - if (lock == NULL) { - dprintf(("PyThread_allocate_lock failed: out of memory\n")); - return (PyThread_type_lock) NULL; - } + lock = (fastmutex_t *) malloc(sizeof(fastmutex_t)); + if (lock == NULL) { + dprintf(("PyThread_allocate_lock failed: out of memory\n")); + return (PyThread_type_lock) NULL; + } #endif - this_lock = atomic_add(&lock_count, 1); - PyOS_snprintf(name, sizeof(name), "python lock (%d)", this_lock); + this_lock = atomic_add(&lock_count, 1); + PyOS_snprintf(name, sizeof(name), "python lock (%d)", this_lock); #ifdef FASTLOCK - if (fastmutex_create(name, lock) < 0) { - dprintf(("PyThread_allocate_lock failed: %s\n", - strerror(errno))); - free(lock); - lock = NULL; - } - dprintf(("PyThread_allocate_lock()-> %p\n", lock)); - return (PyThread_type_lock) lock; + if (fastmutex_create(name, lock) < 0) { + dprintf(("PyThread_allocate_lock failed: %s\n", + strerror(errno))); + free(lock); + lock = NULL; + } + dprintf(("PyThread_allocate_lock()-> %p\n", lock)); + return (PyThread_type_lock) lock; #else - sema = create_semaphore(name, 1, 0); - if (sema < 0) { - dprintf(("PyThread_allocate_lock failed: %s\n", - strerror(errno))); - sema = 0; - } - dprintf(("PyThread_allocate_lock()-> %p\n", sema)); - return (PyThread_type_lock) sema; + sema = create_semaphore(name, 1, 0); + if (sema < 0) { + dprintf(("PyThread_allocate_lock failed: %s\n", + strerror(errno))); + sema = 0; + } + dprintf(("PyThread_allocate_lock()-> %p\n", sema)); + return (PyThread_type_lock) sema; #endif } void PyThread_free_lock(PyThread_type_lock lock) { - dprintf(("PyThread_free_lock(%p) called\n", lock)); + dprintf(("PyThread_free_lock(%p) called\n", lock)); #ifdef FASTLOCK - if (fastmutex_destroy((fastmutex_t *) lock) < 0) { - dprintf(("PyThread_free_lock(%p) failed: %s\n", lock, - strerror(errno))); - } - free(lock); + if (fastmutex_destroy((fastmutex_t *) lock) < 0) { + dprintf(("PyThread_free_lock(%p) failed: %s\n", lock, + strerror(errno))); + } + free(lock); #else - if (delete_semaphore((sem_id) lock) < 0) { - dprintf(("PyThread_free_lock(%p) failed: %s\n", lock, - strerror(errno))); - } + if (delete_semaphore((sem_id) lock) < 0) { + dprintf(("PyThread_free_lock(%p) failed: %s\n", lock, + strerror(errno))); + } #endif } int PyThread_acquire_lock(PyThread_type_lock lock, int waitflag) { - int retval; + int retval; - dprintf(("PyThread_acquire_lock(%p, %d) called\n", lock, - waitflag)); + dprintf(("PyThread_acquire_lock(%p, %d) called\n", lock, + waitflag)); #ifdef FASTLOCK - if (waitflag) - retval = fastmutex_lock((fastmutex_t *) lock); - else - retval = fastmutex_timedlock((fastmutex_t *) lock, 0); + if (waitflag) + retval = fastmutex_lock((fastmutex_t *) lock); + else + retval = fastmutex_timedlock((fastmutex_t *) lock, 0); #else - if (waitflag) - retval = lock_semaphore((sem_id) lock); - else - retval = lock_semaphore_x((sem_id) lock, 1, 0, 0); + if (waitflag) + retval = lock_semaphore((sem_id) lock); + else + retval = lock_semaphore_x((sem_id) lock, 1, 0, 0); #endif - if (retval < 0) { - dprintf(("PyThread_acquire_lock(%p, %d) failed: %s\n", - lock, waitflag, strerror(errno))); - } - dprintf(("PyThread_acquire_lock(%p, %d)-> %d\n", lock, waitflag, - retval)); - return retval < 0 ? 0 : 1; + if (retval < 0) { + dprintf(("PyThread_acquire_lock(%p, %d) failed: %s\n", + lock, waitflag, strerror(errno))); + } + dprintf(("PyThread_acquire_lock(%p, %d)-> %d\n", lock, waitflag, + retval)); + return retval < 0 ? 0 : 1; } void PyThread_release_lock(PyThread_type_lock lock) { - dprintf(("PyThread_release_lock(%p) called\n", lock)); + dprintf(("PyThread_release_lock(%p) called\n", lock)); #ifdef FASTLOCK - if (fastmutex_unlock((fastmutex_t *) lock) < 0) { - dprintf(("PyThread_release_lock(%p) failed: %s\n", lock, - strerror(errno))); - } + if (fastmutex_unlock((fastmutex_t *) lock) < 0) { + dprintf(("PyThread_release_lock(%p) failed: %s\n", lock, + strerror(errno))); + } #else - if (unlock_semaphore((sem_id) lock) < 0) { - dprintf(("PyThread_release_lock(%p) failed: %s\n", lock, - strerror(errno))); - } + if (unlock_semaphore((sem_id) lock) < 0) { + dprintf(("PyThread_release_lock(%p) failed: %s\n", lock, + strerror(errno))); + } #endif } Modified: python/branches/release31-maint/Python/thread_cthread.h ============================================================================== --- python/branches/release31-maint/Python/thread_cthread.h (original) +++ python/branches/release31-maint/Python/thread_cthread.h Sun May 9 18:14:21 2010 @@ -14,12 +14,12 @@ PyThread__init_thread(void) { #ifndef HURD_C_THREADS - /* Roland McGrath said this should not be used since this is - done while linking to threads */ - cthread_init(); + /* Roland McGrath said this should not be used since this is + done while linking to threads */ + cthread_init(); #else /* do nothing */ - ; + ; #endif } @@ -29,77 +29,77 @@ long PyThread_start_new_thread(void (*func)(void *), void *arg) { - int success = 0; /* init not needed when SOLARIS_THREADS and */ - /* C_THREADS implemented properly */ + int success = 0; /* init not needed when SOLARIS_THREADS and */ + /* C_THREADS implemented properly */ - dprintf(("PyThread_start_new_thread called\n")); - if (!initialized) - PyThread_init_thread(); - /* looks like solaris detaches the thread to never rejoin - * so well do it here - */ - cthread_detach(cthread_fork((cthread_fn_t) func, arg)); - return success < 0 ? -1 : 0; + dprintf(("PyThread_start_new_thread called\n")); + if (!initialized) + PyThread_init_thread(); + /* looks like solaris detaches the thread to never rejoin + * so well do it here + */ + cthread_detach(cthread_fork((cthread_fn_t) func, arg)); + return success < 0 ? -1 : 0; } long PyThread_get_thread_ident(void) { - if (!initialized) - PyThread_init_thread(); - return (long) cthread_self(); + if (!initialized) + PyThread_init_thread(); + return (long) cthread_self(); } static void do_PyThread_exit_thread(int no_cleanup) { - dprintf(("PyThread_exit_thread called\n")); - if (!initialized) - if (no_cleanup) - _exit(0); - else - exit(0); - cthread_exit(0); + dprintf(("PyThread_exit_thread called\n")); + if (!initialized) + if (no_cleanup) + _exit(0); + else + exit(0); + cthread_exit(0); } void PyThread_exit_thread(void) { - do_PyThread_exit_thread(0); + do_PyThread_exit_thread(0); } void PyThread__exit_thread(void) { - do_PyThread_exit_thread(1); + do_PyThread_exit_thread(1); } #ifndef NO_EXIT_PROG static void do_PyThread_exit_prog(int status, int no_cleanup) { - dprintf(("PyThread_exit_prog(%d) called\n", status)); - if (!initialized) - if (no_cleanup) - _exit(status); - else - exit(status); - if (no_cleanup) - _exit(status); - else - exit(status); + dprintf(("PyThread_exit_prog(%d) called\n", status)); + if (!initialized) + if (no_cleanup) + _exit(status); + else + exit(status); + if (no_cleanup) + _exit(status); + else + exit(status); } void PyThread_exit_prog(int status) { - do_PyThread_exit_prog(status, 0); + do_PyThread_exit_prog(status, 0); } void PyThread__exit_prog(int status) { - do_PyThread_exit_prog(status, 1); + do_PyThread_exit_prog(status, 1); } #endif /* NO_EXIT_PROG */ @@ -109,48 +109,48 @@ PyThread_type_lock PyThread_allocate_lock(void) { - mutex_t lock; + mutex_t lock; - dprintf(("PyThread_allocate_lock called\n")); - if (!initialized) - PyThread_init_thread(); - - lock = mutex_alloc(); - if (mutex_init(lock)) { - perror("mutex_init"); - free((void *) lock); - lock = 0; - } - dprintf(("PyThread_allocate_lock() -> %p\n", lock)); - return (PyThread_type_lock) lock; + dprintf(("PyThread_allocate_lock called\n")); + if (!initialized) + PyThread_init_thread(); + + lock = mutex_alloc(); + if (mutex_init(lock)) { + perror("mutex_init"); + free((void *) lock); + lock = 0; + } + dprintf(("PyThread_allocate_lock() -> %p\n", lock)); + return (PyThread_type_lock) lock; } void PyThread_free_lock(PyThread_type_lock lock) { - dprintf(("PyThread_free_lock(%p) called\n", lock)); - mutex_free(lock); + dprintf(("PyThread_free_lock(%p) called\n", lock)); + mutex_free(lock); } int PyThread_acquire_lock(PyThread_type_lock lock, int waitflag) { - int success = FALSE; + int success = FALSE; - dprintf(("PyThread_acquire_lock(%p, %d) called\n", lock, waitflag)); - if (waitflag) { /* blocking */ - mutex_lock((mutex_t)lock); - success = TRUE; - } else { /* non blocking */ - success = mutex_try_lock((mutex_t)lock); - } - dprintf(("PyThread_acquire_lock(%p, %d) -> %d\n", lock, waitflag, success)); - return success; + dprintf(("PyThread_acquire_lock(%p, %d) called\n", lock, waitflag)); + if (waitflag) { /* blocking */ + mutex_lock((mutex_t)lock); + success = TRUE; + } else { /* non blocking */ + success = mutex_try_lock((mutex_t)lock); + } + dprintf(("PyThread_acquire_lock(%p, %d) -> %d\n", lock, waitflag, success)); + return success; } void PyThread_release_lock(PyThread_type_lock lock) { - dprintf(("PyThread_release_lock(%p) called\n", lock)); - mutex_unlock((mutex_t )lock); + dprintf(("PyThread_release_lock(%p) called\n", lock)); + mutex_unlock((mutex_t )lock); } Modified: python/branches/release31-maint/Python/thread_foobar.h ============================================================================== --- python/branches/release31-maint/Python/thread_foobar.h (original) +++ python/branches/release31-maint/Python/thread_foobar.h Sun May 9 18:14:21 2010 @@ -13,67 +13,67 @@ long PyThread_start_new_thread(void (*func)(void *), void *arg) { - int success = 0; /* init not needed when SOLARIS_THREADS and */ - /* C_THREADS implemented properly */ + int success = 0; /* init not needed when SOLARIS_THREADS and */ + /* C_THREADS implemented properly */ - dprintf(("PyThread_start_new_thread called\n")); - if (!initialized) - PyThread_init_thread(); - return success < 0 ? -1 : 0; + dprintf(("PyThread_start_new_thread called\n")); + if (!initialized) + PyThread_init_thread(); + return success < 0 ? -1 : 0; } long PyThread_get_thread_ident(void) { - if (!initialized) - PyThread_init_thread(); + if (!initialized) + PyThread_init_thread(); } static void do_PyThread_exit_thread(int no_cleanup) { - dprintf(("PyThread_exit_thread called\n")); - if (!initialized) - if (no_cleanup) - _exit(0); - else - exit(0); + dprintf(("PyThread_exit_thread called\n")); + if (!initialized) + if (no_cleanup) + _exit(0); + else + exit(0); } void PyThread_exit_thread(void) { - do_PyThread_exit_thread(0); + do_PyThread_exit_thread(0); } void PyThread__exit_thread(void) { - do_PyThread_exit_thread(1); + do_PyThread_exit_thread(1); } #ifndef NO_EXIT_PROG static void do_PyThread_exit_prog(int status, int no_cleanup) { - dprintf(("PyThread_exit_prog(%d) called\n", status)); - if (!initialized) - if (no_cleanup) - _exit(status); - else - exit(status); + dprintf(("PyThread_exit_prog(%d) called\n", status)); + if (!initialized) + if (no_cleanup) + _exit(status); + else + exit(status); } void PyThread_exit_prog(int status) { - do_PyThread_exit_prog(status, 0); + do_PyThread_exit_prog(status, 0); } void PyThread__exit_prog(int status) { - do_PyThread_exit_prog(status, 1); + do_PyThread_exit_prog(status, 1); } #endif /* NO_EXIT_PROG */ @@ -84,32 +84,32 @@ PyThread_allocate_lock(void) { - dprintf(("PyThread_allocate_lock called\n")); - if (!initialized) - PyThread_init_thread(); + dprintf(("PyThread_allocate_lock called\n")); + if (!initialized) + PyThread_init_thread(); - dprintf(("PyThread_allocate_lock() -> %p\n", lock)); - return (PyThread_type_lock) lock; + dprintf(("PyThread_allocate_lock() -> %p\n", lock)); + return (PyThread_type_lock) lock; } void PyThread_free_lock(PyThread_type_lock lock) { - dprintf(("PyThread_free_lock(%p) called\n", lock)); + dprintf(("PyThread_free_lock(%p) called\n", lock)); } int PyThread_acquire_lock(PyThread_type_lock lock, int waitflag) { - int success; + int success; - dprintf(("PyThread_acquire_lock(%p, %d) called\n", lock, waitflag)); - dprintf(("PyThread_acquire_lock(%p, %d) -> %d\n", lock, waitflag, success)); - return success; + dprintf(("PyThread_acquire_lock(%p, %d) called\n", lock, waitflag)); + dprintf(("PyThread_acquire_lock(%p, %d) -> %d\n", lock, waitflag, success)); + return success; } void PyThread_release_lock(PyThread_type_lock lock) { - dprintf(("PyThread_release_lock(%p) called\n", lock)); + dprintf(("PyThread_release_lock(%p) called\n", lock)); } Modified: python/branches/release31-maint/Python/thread_lwp.h ============================================================================== --- python/branches/release31-maint/Python/thread_lwp.h (original) +++ python/branches/release31-maint/Python/thread_lwp.h Sun May 9 18:14:21 2010 @@ -3,13 +3,13 @@ #include #include -#define STACKSIZE 1000 /* stacksize for a thread */ -#define NSTACKS 2 /* # stacks to be put in cache initially */ +#define STACKSIZE 1000 /* stacksize for a thread */ +#define NSTACKS 2 /* # stacks to be put in cache initially */ struct lock { - int lock_locked; - cv_t lock_condvar; - mon_t lock_monitor; + int lock_locked; + cv_t lock_condvar; + mon_t lock_monitor; }; @@ -18,7 +18,7 @@ */ static void PyThread__init_thread(void) { - lwp_setstkcache(STACKSIZE, NSTACKS); + lwp_setstkcache(STACKSIZE, NSTACKS); } /* @@ -28,66 +28,66 @@ long PyThread_start_new_thread(void (*func)(void *), void *arg) { - thread_t tid; - int success; - dprintf(("PyThread_start_new_thread called\n")); - if (!initialized) - PyThread_init_thread(); - success = lwp_create(&tid, func, MINPRIO, 0, lwp_newstk(), 1, arg); - return success < 0 ? -1 : 0; + thread_t tid; + int success; + dprintf(("PyThread_start_new_thread called\n")); + if (!initialized) + PyThread_init_thread(); + success = lwp_create(&tid, func, MINPRIO, 0, lwp_newstk(), 1, arg); + return success < 0 ? -1 : 0; } long PyThread_get_thread_ident(void) { - thread_t tid; - if (!initialized) - PyThread_init_thread(); - if (lwp_self(&tid) < 0) - return -1; - return tid.thread_id; + thread_t tid; + if (!initialized) + PyThread_init_thread(); + if (lwp_self(&tid) < 0) + return -1; + return tid.thread_id; } static void do_PyThread_exit_thread(int no_cleanup) { - dprintf(("PyThread_exit_thread called\n")); - if (!initialized) - if (no_cleanup) - _exit(0); - else - exit(0); - lwp_destroy(SELF); + dprintf(("PyThread_exit_thread called\n")); + if (!initialized) + if (no_cleanup) + _exit(0); + else + exit(0); + lwp_destroy(SELF); } void PyThread_exit_thread(void) { - do_PyThread_exit_thread(0); + do_PyThread_exit_thread(0); } void PyThread__exit_thread(void) { - do_PyThread_exit_thread(1); + do_PyThread_exit_thread(1); } #ifndef NO_EXIT_PROG static void do_PyThread_exit_prog(int status, int no_cleanup) { - dprintf(("PyThread_exit_prog(%d) called\n", status)); - if (!initialized) - if (no_cleanup) - _exit(status); - else - exit(status); - pod_exit(status); + dprintf(("PyThread_exit_prog(%d) called\n", status)); + if (!initialized) + if (no_cleanup) + _exit(status); + else + exit(status); + pod_exit(status); } void PyThread_exit_prog(int status) { - do_PyThread_exit_prog(status, 0); + do_PyThread_exit_prog(status, 0); } void PyThread__exit_prog(int status) { - do_PyThread_exit_prog(status, 1); + do_PyThread_exit_prog(status, 1); } #endif /* NO_EXIT_PROG */ @@ -96,54 +96,54 @@ */ PyThread_type_lock PyThread_allocate_lock(void) { - struct lock *lock; - extern char *malloc(size_t); + struct lock *lock; + extern char *malloc(size_t); - dprintf(("PyThread_allocate_lock called\n")); - if (!initialized) - PyThread_init_thread(); - - lock = (struct lock *) malloc(sizeof(struct lock)); - lock->lock_locked = 0; - (void) mon_create(&lock->lock_monitor); - (void) cv_create(&lock->lock_condvar, lock->lock_monitor); - dprintf(("PyThread_allocate_lock() -> %p\n", lock)); - return (PyThread_type_lock) lock; + dprintf(("PyThread_allocate_lock called\n")); + if (!initialized) + PyThread_init_thread(); + + lock = (struct lock *) malloc(sizeof(struct lock)); + lock->lock_locked = 0; + (void) mon_create(&lock->lock_monitor); + (void) cv_create(&lock->lock_condvar, lock->lock_monitor); + dprintf(("PyThread_allocate_lock() -> %p\n", lock)); + return (PyThread_type_lock) lock; } void PyThread_free_lock(PyThread_type_lock lock) { - dprintf(("PyThread_free_lock(%p) called\n", lock)); - mon_destroy(((struct lock *) lock)->lock_monitor); - free((char *) lock); + dprintf(("PyThread_free_lock(%p) called\n", lock)); + mon_destroy(((struct lock *) lock)->lock_monitor); + free((char *) lock); } int PyThread_acquire_lock(PyThread_type_lock lock, int waitflag) { - int success; + int success; - dprintf(("PyThread_acquire_lock(%p, %d) called\n", lock, waitflag)); - success = 0; + dprintf(("PyThread_acquire_lock(%p, %d) called\n", lock, waitflag)); + success = 0; - (void) mon_enter(((struct lock *) lock)->lock_monitor); - if (waitflag) - while (((struct lock *) lock)->lock_locked) - cv_wait(((struct lock *) lock)->lock_condvar); - if (!((struct lock *) lock)->lock_locked) { - success = 1; - ((struct lock *) lock)->lock_locked = 1; - } - cv_broadcast(((struct lock *) lock)->lock_condvar); - mon_exit(((struct lock *) lock)->lock_monitor); - dprintf(("PyThread_acquire_lock(%p, %d) -> %d\n", lock, waitflag, success)); - return success; + (void) mon_enter(((struct lock *) lock)->lock_monitor); + if (waitflag) + while (((struct lock *) lock)->lock_locked) + cv_wait(((struct lock *) lock)->lock_condvar); + if (!((struct lock *) lock)->lock_locked) { + success = 1; + ((struct lock *) lock)->lock_locked = 1; + } + cv_broadcast(((struct lock *) lock)->lock_condvar); + mon_exit(((struct lock *) lock)->lock_monitor); + dprintf(("PyThread_acquire_lock(%p, %d) -> %d\n", lock, waitflag, success)); + return success; } void PyThread_release_lock(PyThread_type_lock lock) { - dprintf(("PyThread_release_lock(%p) called\n", lock)); - (void) mon_enter(((struct lock *) lock)->lock_monitor); - ((struct lock *) lock)->lock_locked = 0; - cv_broadcast(((struct lock *) lock)->lock_condvar); - mon_exit(((struct lock *) lock)->lock_monitor); + dprintf(("PyThread_release_lock(%p) called\n", lock)); + (void) mon_enter(((struct lock *) lock)->lock_monitor); + ((struct lock *) lock)->lock_locked = 0; + cv_broadcast(((struct lock *) lock)->lock_condvar); + mon_exit(((struct lock *) lock)->lock_monitor); } Modified: python/branches/release31-maint/Python/thread_nt.h ============================================================================== --- python/branches/release31-maint/Python/thread_nt.h (original) +++ python/branches/release31-maint/Python/thread_nt.h Sun May 9 18:14:21 2010 @@ -10,81 +10,81 @@ #endif typedef struct NRMUTEX { - LONG owned ; - DWORD thread_id ; - HANDLE hevent ; + LONG owned ; + DWORD thread_id ; + HANDLE hevent ; } NRMUTEX, *PNRMUTEX ; BOOL InitializeNonRecursiveMutex(PNRMUTEX mutex) { - mutex->owned = -1 ; /* No threads have entered NonRecursiveMutex */ - mutex->thread_id = 0 ; - mutex->hevent = CreateEvent(NULL, FALSE, FALSE, NULL) ; - return mutex->hevent != NULL ; /* TRUE if the mutex is created */ + mutex->owned = -1 ; /* No threads have entered NonRecursiveMutex */ + mutex->thread_id = 0 ; + mutex->hevent = CreateEvent(NULL, FALSE, FALSE, NULL) ; + return mutex->hevent != NULL ; /* TRUE if the mutex is created */ } VOID DeleteNonRecursiveMutex(PNRMUTEX mutex) { - /* No in-use check */ - CloseHandle(mutex->hevent) ; - mutex->hevent = NULL ; /* Just in case */ + /* No in-use check */ + CloseHandle(mutex->hevent) ; + mutex->hevent = NULL ; /* Just in case */ } DWORD EnterNonRecursiveMutex(PNRMUTEX mutex, BOOL wait) { - /* Assume that the thread waits successfully */ - DWORD ret ; + /* Assume that the thread waits successfully */ + DWORD ret ; - /* InterlockedIncrement(&mutex->owned) == 0 means that no thread currently owns the mutex */ - if (!wait) - { - if (InterlockedCompareExchange(&mutex->owned, 0, -1) != -1) - return WAIT_TIMEOUT ; - ret = WAIT_OBJECT_0 ; - } - else - ret = InterlockedIncrement(&mutex->owned) ? - /* Some thread owns the mutex, let's wait... */ - WaitForSingleObject(mutex->hevent, INFINITE) : WAIT_OBJECT_0 ; + /* InterlockedIncrement(&mutex->owned) == 0 means that no thread currently owns the mutex */ + if (!wait) + { + if (InterlockedCompareExchange(&mutex->owned, 0, -1) != -1) + return WAIT_TIMEOUT ; + ret = WAIT_OBJECT_0 ; + } + else + ret = InterlockedIncrement(&mutex->owned) ? + /* Some thread owns the mutex, let's wait... */ + WaitForSingleObject(mutex->hevent, INFINITE) : WAIT_OBJECT_0 ; - mutex->thread_id = GetCurrentThreadId() ; /* We own it */ - return ret ; + mutex->thread_id = GetCurrentThreadId() ; /* We own it */ + return ret ; } BOOL LeaveNonRecursiveMutex(PNRMUTEX mutex) { - /* We don't own the mutex */ - mutex->thread_id = 0 ; - return - InterlockedDecrement(&mutex->owned) < 0 || - SetEvent(mutex->hevent) ; /* Other threads are waiting, wake one on them up */ + /* We don't own the mutex */ + mutex->thread_id = 0 ; + return + InterlockedDecrement(&mutex->owned) < 0 || + SetEvent(mutex->hevent) ; /* Other threads are waiting, wake one on them up */ } PNRMUTEX AllocNonRecursiveMutex(void) { - PNRMUTEX mutex = (PNRMUTEX)malloc(sizeof(NRMUTEX)) ; - if (mutex && !InitializeNonRecursiveMutex(mutex)) - { - free(mutex) ; - mutex = NULL ; - } - return mutex ; + PNRMUTEX mutex = (PNRMUTEX)malloc(sizeof(NRMUTEX)) ; + if (mutex && !InitializeNonRecursiveMutex(mutex)) + { + free(mutex) ; + mutex = NULL ; + } + return mutex ; } void FreeNonRecursiveMutex(PNRMUTEX mutex) { - if (mutex) - { - DeleteNonRecursiveMutex(mutex) ; - free(mutex) ; - } + if (mutex) + { + DeleteNonRecursiveMutex(mutex) ; + free(mutex) ; + } } long PyThread_get_thread_ident(void); @@ -102,8 +102,8 @@ */ typedef struct { - void (*func)(void*); - void *arg; + void (*func)(void*); + void *arg; } callobj; /* thunker to call adapt between the function type used by the system's @@ -115,66 +115,66 @@ #endif bootstrap(void *call) { - callobj *obj = (callobj*)call; - void (*func)(void*) = obj->func; - void *arg = obj->arg; - HeapFree(GetProcessHeap(), 0, obj); - func(arg); - return 0; + callobj *obj = (callobj*)call; + void (*func)(void*) = obj->func; + void *arg = obj->arg; + HeapFree(GetProcessHeap(), 0, obj); + func(arg); + return 0; } long PyThread_start_new_thread(void (*func)(void *), void *arg) { - HANDLE hThread; - unsigned threadID; - callobj *obj; - - dprintf(("%ld: PyThread_start_new_thread called\n", - PyThread_get_thread_ident())); - if (!initialized) - PyThread_init_thread(); - - obj = (callobj*)HeapAlloc(GetProcessHeap(), 0, sizeof(*obj)); - if (!obj) - return -1; - obj->func = func; - obj->arg = arg; + HANDLE hThread; + unsigned threadID; + callobj *obj; + + dprintf(("%ld: PyThread_start_new_thread called\n", + PyThread_get_thread_ident())); + if (!initialized) + PyThread_init_thread(); + + obj = (callobj*)HeapAlloc(GetProcessHeap(), 0, sizeof(*obj)); + if (!obj) + return -1; + obj->func = func; + obj->arg = arg; #if defined(MS_WINCE) - hThread = CreateThread(NULL, - Py_SAFE_DOWNCAST(_pythread_stacksize, Py_ssize_t, SIZE_T), - bootstrap, obj, 0, &threadID); + hThread = CreateThread(NULL, + Py_SAFE_DOWNCAST(_pythread_stacksize, Py_ssize_t, SIZE_T), + bootstrap, obj, 0, &threadID); #else - hThread = (HANDLE)_beginthreadex(0, - Py_SAFE_DOWNCAST(_pythread_stacksize, - Py_ssize_t, unsigned int), - bootstrap, obj, - 0, &threadID); + hThread = (HANDLE)_beginthreadex(0, + Py_SAFE_DOWNCAST(_pythread_stacksize, + Py_ssize_t, unsigned int), + bootstrap, obj, + 0, &threadID); #endif - if (hThread == 0) { + if (hThread == 0) { #if defined(MS_WINCE) - /* Save error in variable, to prevent PyThread_get_thread_ident - from clobbering it. */ - unsigned e = GetLastError(); - dprintf(("%ld: PyThread_start_new_thread failed, win32 error code %u\n", - PyThread_get_thread_ident(), e)); + /* Save error in variable, to prevent PyThread_get_thread_ident + from clobbering it. */ + unsigned e = GetLastError(); + dprintf(("%ld: PyThread_start_new_thread failed, win32 error code %u\n", + PyThread_get_thread_ident(), e)); #else - /* I've seen errno == EAGAIN here, which means "there are - * too many threads". - */ - int e = errno; - dprintf(("%ld: PyThread_start_new_thread failed, errno %d\n", - PyThread_get_thread_ident(), e)); + /* I've seen errno == EAGAIN here, which means "there are + * too many threads". + */ + int e = errno; + dprintf(("%ld: PyThread_start_new_thread failed, errno %d\n", + PyThread_get_thread_ident(), e)); #endif - threadID = (unsigned)-1; - HeapFree(GetProcessHeap(), 0, obj); - } - else { - dprintf(("%ld: PyThread_start_new_thread succeeded: %p\n", - PyThread_get_thread_ident(), (void*)hThread)); - CloseHandle(hThread); - } - return (long) threadID; + threadID = (unsigned)-1; + HeapFree(GetProcessHeap(), 0, obj); + } + else { + dprintf(("%ld: PyThread_start_new_thread succeeded: %p\n", + PyThread_get_thread_ident(), (void*)hThread)); + CloseHandle(hThread); + } + return (long) threadID; } /* @@ -184,22 +184,22 @@ long PyThread_get_thread_ident(void) { - if (!initialized) - PyThread_init_thread(); + if (!initialized) + PyThread_init_thread(); - return GetCurrentThreadId(); + return GetCurrentThreadId(); } void PyThread_exit_thread(void) { - dprintf(("%ld: PyThread_exit_thread called\n", PyThread_get_thread_ident())); - if (!initialized) - exit(0); + dprintf(("%ld: PyThread_exit_thread called\n", PyThread_get_thread_ident())); + if (!initialized) + exit(0); #if defined(MS_WINCE) - ExitThread(0); + ExitThread(0); #else - _endthreadex(0); + _endthreadex(0); #endif } @@ -207,9 +207,9 @@ void PyThread_exit_prog(int status) { - dprintf(("PyThread_exit_prog(%d) called\n", status)); - if (!initialized) - exit(status); + dprintf(("PyThread_exit_prog(%d) called\n", status)); + if (!initialized) + exit(status); } #endif /* NO_EXIT_PROG */ @@ -221,25 +221,25 @@ PyThread_type_lock PyThread_allocate_lock(void) { - PNRMUTEX aLock; + PNRMUTEX aLock; - dprintf(("PyThread_allocate_lock called\n")); - if (!initialized) - PyThread_init_thread(); + dprintf(("PyThread_allocate_lock called\n")); + if (!initialized) + PyThread_init_thread(); - aLock = AllocNonRecursiveMutex() ; + aLock = AllocNonRecursiveMutex() ; - dprintf(("%ld: PyThread_allocate_lock() -> %p\n", PyThread_get_thread_ident(), aLock)); + dprintf(("%ld: PyThread_allocate_lock() -> %p\n", PyThread_get_thread_ident(), aLock)); - return (PyThread_type_lock) aLock; + return (PyThread_type_lock) aLock; } void PyThread_free_lock(PyThread_type_lock aLock) { - dprintf(("%ld: PyThread_free_lock(%p) called\n", PyThread_get_thread_ident(),aLock)); + dprintf(("%ld: PyThread_free_lock(%p) called\n", PyThread_get_thread_ident(),aLock)); - FreeNonRecursiveMutex(aLock) ; + FreeNonRecursiveMutex(aLock) ; } /* @@ -251,29 +251,29 @@ int PyThread_acquire_lock(PyThread_type_lock aLock, int waitflag) { - int success ; + int success ; - dprintf(("%ld: PyThread_acquire_lock(%p, %d) called\n", PyThread_get_thread_ident(),aLock, waitflag)); + dprintf(("%ld: PyThread_acquire_lock(%p, %d) called\n", PyThread_get_thread_ident(),aLock, waitflag)); - success = aLock && EnterNonRecursiveMutex((PNRMUTEX) aLock, (waitflag ? INFINITE : 0)) == WAIT_OBJECT_0 ; + success = aLock && EnterNonRecursiveMutex((PNRMUTEX) aLock, (waitflag ? INFINITE : 0)) == WAIT_OBJECT_0 ; - dprintf(("%ld: PyThread_acquire_lock(%p, %d) -> %d\n", PyThread_get_thread_ident(),aLock, waitflag, success)); + dprintf(("%ld: PyThread_acquire_lock(%p, %d) -> %d\n", PyThread_get_thread_ident(),aLock, waitflag, success)); - return success; + return success; } void PyThread_release_lock(PyThread_type_lock aLock) { - dprintf(("%ld: PyThread_release_lock(%p) called\n", PyThread_get_thread_ident(),aLock)); + dprintf(("%ld: PyThread_release_lock(%p) called\n", PyThread_get_thread_ident(),aLock)); - if (!(aLock && LeaveNonRecursiveMutex((PNRMUTEX) aLock))) - dprintf(("%ld: Could not PyThread_release_lock(%p) error: %ld\n", PyThread_get_thread_ident(), aLock, GetLastError())); + if (!(aLock && LeaveNonRecursiveMutex((PNRMUTEX) aLock))) + dprintf(("%ld: Could not PyThread_release_lock(%p) error: %ld\n", PyThread_get_thread_ident(), aLock, GetLastError())); } /* minimum/maximum thread stack sizes supported */ -#define THREAD_MIN_STACKSIZE 0x8000 /* 32kB */ -#define THREAD_MAX_STACKSIZE 0x10000000 /* 256MB */ +#define THREAD_MIN_STACKSIZE 0x8000 /* 32kB */ +#define THREAD_MAX_STACKSIZE 0x10000000 /* 256MB */ /* set the thread stack size. * Return 0 if size is valid, -1 otherwise. @@ -281,22 +281,22 @@ static int _pythread_nt_set_stacksize(size_t size) { - /* set to default */ - if (size == 0) { - _pythread_stacksize = 0; - return 0; - } - - /* valid range? */ - if (size >= THREAD_MIN_STACKSIZE && size < THREAD_MAX_STACKSIZE) { - _pythread_stacksize = size; - return 0; - } + /* set to default */ + if (size == 0) { + _pythread_stacksize = 0; + return 0; + } + + /* valid range? */ + if (size >= THREAD_MIN_STACKSIZE && size < THREAD_MAX_STACKSIZE) { + _pythread_stacksize = size; + return 0; + } - return -1; + return -1; } -#define THREAD_SET_STACKSIZE(x) _pythread_nt_set_stacksize(x) +#define THREAD_SET_STACKSIZE(x) _pythread_nt_set_stacksize(x) /* use native Windows TLS functions */ @@ -306,13 +306,13 @@ int PyThread_create_key(void) { - return (int) TlsAlloc(); + return (int) TlsAlloc(); } void PyThread_delete_key(int key) { - TlsFree(key); + TlsFree(key); } /* We must be careful to emulate the strange semantics implemented in thread.c, @@ -321,42 +321,42 @@ int PyThread_set_key_value(int key, void *value) { - BOOL ok; - void *oldvalue; + BOOL ok; + void *oldvalue; - assert(value != NULL); - oldvalue = TlsGetValue(key); - if (oldvalue != NULL) - /* ignore value if already set */ - return 0; - ok = TlsSetValue(key, value); - if (!ok) - return -1; - return 0; + assert(value != NULL); + oldvalue = TlsGetValue(key); + if (oldvalue != NULL) + /* ignore value if already set */ + return 0; + ok = TlsSetValue(key, value); + if (!ok) + return -1; + return 0; } void * PyThread_get_key_value(int key) { - /* because TLS is used in the Py_END_ALLOW_THREAD macro, - * it is necessary to preserve the windows error state, because - * it is assumed to be preserved across the call to the macro. - * Ideally, the macro should be fixed, but it is simpler to - * do it here. - */ - DWORD error = GetLastError(); - void *result = TlsGetValue(key); - SetLastError(error); - return result; + /* because TLS is used in the Py_END_ALLOW_THREAD macro, + * it is necessary to preserve the windows error state, because + * it is assumed to be preserved across the call to the macro. + * Ideally, the macro should be fixed, but it is simpler to + * do it here. + */ + DWORD error = GetLastError(); + void *result = TlsGetValue(key); + SetLastError(error); + return result; } void PyThread_delete_key_value(int key) { - /* NULL is used as "key missing", and it is also the default - * given by TlsGetValue() if nothing has been set yet. - */ - TlsSetValue(key, NULL); + /* NULL is used as "key missing", and it is also the default + * given by TlsGetValue() if nothing has been set yet. + */ + TlsSetValue(key, NULL); } /* reinitialization of TLS is not necessary after fork when using Modified: python/branches/release31-maint/Python/thread_os2.h ============================================================================== --- python/branches/release31-maint/Python/thread_os2.h (original) +++ python/branches/release31-maint/Python/thread_os2.h Sun May 9 18:14:21 2010 @@ -16,10 +16,10 @@ /* default thread stack size of 64kB */ #if !defined(THREAD_STACK_SIZE) -#define THREAD_STACK_SIZE 0x10000 +#define THREAD_STACK_SIZE 0x10000 #endif -#define OS2_STACKSIZE(x) (x ? x : THREAD_STACK_SIZE) +#define OS2_STACKSIZE(x) (x ? x : THREAD_STACK_SIZE) /* * Initialization of the C package, should not be needed. @@ -35,153 +35,153 @@ long PyThread_start_new_thread(void (*func)(void *), void *arg) { - int thread_id; + int thread_id; - thread_id = _beginthread(func, - NULL, - OS2_STACKSIZE(_pythread_stacksize), - arg); - - if (thread_id == -1) { - dprintf(("_beginthread failed. return %ld\n", errno)); - } + thread_id = _beginthread(func, + NULL, + OS2_STACKSIZE(_pythread_stacksize), + arg); + + if (thread_id == -1) { + dprintf(("_beginthread failed. return %ld\n", errno)); + } - return thread_id; + return thread_id; } long PyThread_get_thread_ident(void) { #if !defined(PYCC_GCC) - PPIB pib; - PTIB tib; + PPIB pib; + PTIB tib; #endif - if (!initialized) - PyThread_init_thread(); + if (!initialized) + PyThread_init_thread(); #if defined(PYCC_GCC) - return _gettid(); + return _gettid(); #else - DosGetInfoBlocks(&tib, &pib); - return tib->tib_ptib2->tib2_ultid; + DosGetInfoBlocks(&tib, &pib); + return tib->tib_ptib2->tib2_ultid; #endif } static void do_PyThread_exit_thread(int no_cleanup) { - dprintf(("%ld: PyThread_exit_thread called\n", - PyThread_get_thread_ident())); - if (!initialized) - if (no_cleanup) - _exit(0); - else - exit(0); - _endthread(); + dprintf(("%ld: PyThread_exit_thread called\n", + PyThread_get_thread_ident())); + if (!initialized) + if (no_cleanup) + _exit(0); + else + exit(0); + _endthread(); } -void +void PyThread_exit_thread(void) { - do_PyThread_exit_thread(0); + do_PyThread_exit_thread(0); } -void +void PyThread__exit_thread(void) { - do_PyThread_exit_thread(1); + do_PyThread_exit_thread(1); } #ifndef NO_EXIT_PROG -static void +static void do_PyThread_exit_prog(int status, int no_cleanup) { - dprintf(("PyThread_exit_prog(%d) called\n", status)); - if (!initialized) - if (no_cleanup) - _exit(status); - else - exit(status); + dprintf(("PyThread_exit_prog(%d) called\n", status)); + if (!initialized) + if (no_cleanup) + _exit(status); + else + exit(status); } -void +void PyThread_exit_prog(int status) { - do_PyThread_exit_prog(status, 0); + do_PyThread_exit_prog(status, 0); } -void +void PyThread__exit_prog(int status) { - do_PyThread_exit_prog(status, 1); + do_PyThread_exit_prog(status, 1); } #endif /* NO_EXIT_PROG */ /* * Lock support. This is implemented with an event semaphore and critical - * sections to make it behave more like a posix mutex than its OS/2 + * sections to make it behave more like a posix mutex than its OS/2 * counterparts. */ typedef struct os2_lock_t { - int is_set; - HEV changed; + int is_set; + HEV changed; } *type_os2_lock; -PyThread_type_lock +PyThread_type_lock PyThread_allocate_lock(void) { #if defined(PYCC_GCC) - _fmutex *sem = malloc(sizeof(_fmutex)); - if (!initialized) - PyThread_init_thread(); - dprintf(("%ld: PyThread_allocate_lock() -> %lx\n", - PyThread_get_thread_ident(), - (long)sem)); - if (_fmutex_create(sem, 0)) { - free(sem); - sem = NULL; - } - return (PyThread_type_lock)sem; + _fmutex *sem = malloc(sizeof(_fmutex)); + if (!initialized) + PyThread_init_thread(); + dprintf(("%ld: PyThread_allocate_lock() -> %lx\n", + PyThread_get_thread_ident(), + (long)sem)); + if (_fmutex_create(sem, 0)) { + free(sem); + sem = NULL; + } + return (PyThread_type_lock)sem; #else - APIRET rc; - type_os2_lock lock = (type_os2_lock)malloc(sizeof(struct os2_lock_t)); + APIRET rc; + type_os2_lock lock = (type_os2_lock)malloc(sizeof(struct os2_lock_t)); - dprintf(("PyThread_allocate_lock called\n")); - if (!initialized) - PyThread_init_thread(); + dprintf(("PyThread_allocate_lock called\n")); + if (!initialized) + PyThread_init_thread(); - lock->is_set = 0; + lock->is_set = 0; - DosCreateEventSem(NULL, &lock->changed, 0, 0); + DosCreateEventSem(NULL, &lock->changed, 0, 0); - dprintf(("%ld: PyThread_allocate_lock() -> %p\n", - PyThread_get_thread_ident(), - lock->changed)); + dprintf(("%ld: PyThread_allocate_lock() -> %p\n", + PyThread_get_thread_ident(), + lock->changed)); - return (PyThread_type_lock)lock; + return (PyThread_type_lock)lock; #endif } -void +void PyThread_free_lock(PyThread_type_lock aLock) { #if !defined(PYCC_GCC) - type_os2_lock lock = (type_os2_lock)aLock; + type_os2_lock lock = (type_os2_lock)aLock; #endif - dprintf(("%ld: PyThread_free_lock(%p) called\n", - PyThread_get_thread_ident(),aLock)); + dprintf(("%ld: PyThread_free_lock(%p) called\n", + PyThread_get_thread_ident(),aLock)); #if defined(PYCC_GCC) - if (aLock) { - _fmutex_close((_fmutex *)aLock); - free((_fmutex *)aLock); - } + if (aLock) { + _fmutex_close((_fmutex *)aLock); + free((_fmutex *)aLock); + } #else - DosCloseEventSem(lock->changed); - free(aLock); + DosCloseEventSem(lock->changed); + free(aLock); #endif } @@ -190,98 +190,98 @@ * * and 0 if the lock was not acquired. */ -int +int PyThread_acquire_lock(PyThread_type_lock aLock, int waitflag) { #if !defined(PYCC_GCC) - int done = 0; - ULONG count; - PID pid = 0; - TID tid = 0; - type_os2_lock lock = (type_os2_lock)aLock; + int done = 0; + ULONG count; + PID pid = 0; + TID tid = 0; + type_os2_lock lock = (type_os2_lock)aLock; #endif - dprintf(("%ld: PyThread_acquire_lock(%p, %d) called\n", - PyThread_get_thread_ident(), - aLock, - waitflag)); + dprintf(("%ld: PyThread_acquire_lock(%p, %d) called\n", + PyThread_get_thread_ident(), + aLock, + waitflag)); #if defined(PYCC_GCC) - /* always successful if the lock doesn't exist */ - if (aLock && - _fmutex_request((_fmutex *)aLock, waitflag ? 0 : _FMR_NOWAIT)) - return 0; + /* always successful if the lock doesn't exist */ + if (aLock && + _fmutex_request((_fmutex *)aLock, waitflag ? 0 : _FMR_NOWAIT)) + return 0; #else - while (!done) { - /* if the lock is currently set, we have to wait for - * the state to change - */ - if (lock->is_set) { - if (!waitflag) - return 0; - DosWaitEventSem(lock->changed, SEM_INDEFINITE_WAIT); - } - - /* enter a critical section and try to get the semaphore. If - * it is still locked, we will try again. - */ - if (DosEnterCritSec()) - return 0; - - if (!lock->is_set) { - lock->is_set = 1; - DosResetEventSem(lock->changed, &count); - done = 1; - } + while (!done) { + /* if the lock is currently set, we have to wait for + * the state to change + */ + if (lock->is_set) { + if (!waitflag) + return 0; + DosWaitEventSem(lock->changed, SEM_INDEFINITE_WAIT); + } + + /* enter a critical section and try to get the semaphore. If + * it is still locked, we will try again. + */ + if (DosEnterCritSec()) + return 0; + + if (!lock->is_set) { + lock->is_set = 1; + DosResetEventSem(lock->changed, &count); + done = 1; + } - DosExitCritSec(); - } + DosExitCritSec(); + } #endif - return 1; + return 1; } void PyThread_release_lock(PyThread_type_lock aLock) { #if !defined(PYCC_GCC) - type_os2_lock lock = (type_os2_lock)aLock; + type_os2_lock lock = (type_os2_lock)aLock; #endif - dprintf(("%ld: PyThread_release_lock(%p) called\n", - PyThread_get_thread_ident(), - aLock)); + dprintf(("%ld: PyThread_release_lock(%p) called\n", + PyThread_get_thread_ident(), + aLock)); #if defined(PYCC_GCC) - if (aLock) - _fmutex_release((_fmutex *)aLock); + if (aLock) + _fmutex_release((_fmutex *)aLock); #else - if (!lock->is_set) { - dprintf(("%ld: Could not PyThread_release_lock(%p) error: %l\n", - PyThread_get_thread_ident(), - aLock, - GetLastError())); - return; - } - - if (DosEnterCritSec()) { - dprintf(("%ld: Could not PyThread_release_lock(%p) error: %l\n", - PyThread_get_thread_ident(), - aLock, - GetLastError())); - return; - } + if (!lock->is_set) { + dprintf(("%ld: Could not PyThread_release_lock(%p) error: %l\n", + PyThread_get_thread_ident(), + aLock, + GetLastError())); + return; + } + + if (DosEnterCritSec()) { + dprintf(("%ld: Could not PyThread_release_lock(%p) error: %l\n", + PyThread_get_thread_ident(), + aLock, + GetLastError())); + return; + } - lock->is_set = 0; - DosPostEventSem(lock->changed); + lock->is_set = 0; + DosPostEventSem(lock->changed); - DosExitCritSec(); + DosExitCritSec(); #endif } /* minimum/maximum thread stack sizes supported */ -#define THREAD_MIN_STACKSIZE 0x8000 /* 32kB */ -#define THREAD_MAX_STACKSIZE 0x2000000 /* 32MB */ +#define THREAD_MIN_STACKSIZE 0x8000 /* 32kB */ +#define THREAD_MAX_STACKSIZE 0x2000000 /* 32MB */ /* set the thread stack size. * Return 0 if size is valid, -1 otherwise. @@ -289,19 +289,19 @@ static int _pythread_os2_set_stacksize(size_t size) { - /* set to default */ - if (size == 0) { - _pythread_stacksize = 0; - return 0; - } - - /* valid range? */ - if (size >= THREAD_MIN_STACKSIZE && size < THREAD_MAX_STACKSIZE) { - _pythread_stacksize = size; - return 0; - } + /* set to default */ + if (size == 0) { + _pythread_stacksize = 0; + return 0; + } + + /* valid range? */ + if (size >= THREAD_MIN_STACKSIZE && size < THREAD_MAX_STACKSIZE) { + _pythread_stacksize = size; + return 0; + } - return -1; + return -1; } -#define THREAD_SET_STACKSIZE(x) _pythread_os2_set_stacksize(x) +#define THREAD_SET_STACKSIZE(x) _pythread_os2_set_stacksize(x) Modified: python/branches/release31-maint/Python/thread_pth.h ============================================================================== --- python/branches/release31-maint/Python/thread_pth.h (original) +++ python/branches/release31-maint/Python/thread_pth.h Sun May 9 18:14:21 2010 @@ -3,7 +3,7 @@ http://www.gnu.org/software/pth 2000-05-03 Andy Dustman - Adapted from Posix threads interface + Adapted from Posix threads interface 12 May 1997 -- david arnold */ @@ -22,10 +22,10 @@ */ typedef struct { - char locked; /* 0=unlocked, 1=locked */ - /* a pair to handle an acquire of a locked lock */ - pth_cond_t lock_released; - pth_mutex_t mut; + char locked; /* 0=unlocked, 1=locked */ + /* a pair to handle an acquire of a locked lock */ + pth_cond_t lock_released; + pth_mutex_t mut; } pth_lock; #define CHECK_STATUS(name) if (status == -1) { printf("%d ", status); perror(name); error = 1; } @@ -38,10 +38,10 @@ static void PyThread__init_thread(void) { - pth_init(); - PyThread_attr = pth_attr_new(); - pth_attr_set(PyThread_attr, PTH_ATTR_STACK_SIZE, 1<<18); - pth_attr_set(PyThread_attr, PTH_ATTR_JOINABLE, FALSE); + pth_init(); + PyThread_attr = pth_attr_new(); + pth_attr_set(PyThread_attr, PTH_ATTR_STACK_SIZE, 1<<18); + pth_attr_set(PyThread_attr, PTH_ATTR_JOINABLE, FALSE); } /* @@ -51,69 +51,69 @@ long PyThread_start_new_thread(void (*func)(void *), void *arg) { - pth_t th; - dprintf(("PyThread_start_new_thread called\n")); - if (!initialized) - PyThread_init_thread(); - - th = pth_spawn(PyThread_attr, - (void* (*)(void *))func, - (void *)arg - ); + pth_t th; + dprintf(("PyThread_start_new_thread called\n")); + if (!initialized) + PyThread_init_thread(); + + th = pth_spawn(PyThread_attr, + (void* (*)(void *))func, + (void *)arg + ); - return th; + return th; } long PyThread_get_thread_ident(void) { - volatile pth_t threadid; - if (!initialized) - PyThread_init_thread(); - /* Jump through some hoops for Alpha OSF/1 */ - threadid = pth_self(); - return (long) *(long *) &threadid; + volatile pth_t threadid; + if (!initialized) + PyThread_init_thread(); + /* Jump through some hoops for Alpha OSF/1 */ + threadid = pth_self(); + return (long) *(long *) &threadid; } static void do_PyThread_exit_thread(int no_cleanup) { - dprintf(("PyThread_exit_thread called\n")); - if (!initialized) { - if (no_cleanup) - _exit(0); - else - exit(0); - } + dprintf(("PyThread_exit_thread called\n")); + if (!initialized) { + if (no_cleanup) + _exit(0); + else + exit(0); + } } void PyThread_exit_thread(void) { - do_PyThread_exit_thread(0); + do_PyThread_exit_thread(0); } void PyThread__exit_thread(void) { - do_PyThread_exit_thread(1); + do_PyThread_exit_thread(1); } #ifndef NO_EXIT_PROG static void do_PyThread_exit_prog(int status, int no_cleanup) { - dprintf(("PyThread_exit_prog(%d) called\n", status)); - if (!initialized) - if (no_cleanup) - _exit(status); - else - exit(status); + dprintf(("PyThread_exit_prog(%d) called\n", status)); + if (!initialized) + if (no_cleanup) + _exit(status); + else + exit(status); } void PyThread_exit_prog(int status) { - do_PyThread_exit_prog(status, 0); + do_PyThread_exit_prog(status, 0); } void PyThread__exit_prog(int status) { - do_PyThread_exit_prog(status, 1); + do_PyThread_exit_prog(status, 1); } #endif /* NO_EXIT_PROG */ @@ -122,92 +122,92 @@ */ PyThread_type_lock PyThread_allocate_lock(void) { - pth_lock *lock; - int status, error = 0; + pth_lock *lock; + int status, error = 0; - dprintf(("PyThread_allocate_lock called\n")); - if (!initialized) - PyThread_init_thread(); - - lock = (pth_lock *) malloc(sizeof(pth_lock)); - memset((void *)lock, '\0', sizeof(pth_lock)); - if (lock) { - lock->locked = 0; - status = pth_mutex_init(&lock->mut); - CHECK_STATUS("pth_mutex_init"); - status = pth_cond_init(&lock->lock_released); - CHECK_STATUS("pth_cond_init"); - if (error) { - free((void *)lock); - lock = NULL; - } - } - dprintf(("PyThread_allocate_lock() -> %p\n", lock)); - return (PyThread_type_lock) lock; + dprintf(("PyThread_allocate_lock called\n")); + if (!initialized) + PyThread_init_thread(); + + lock = (pth_lock *) malloc(sizeof(pth_lock)); + memset((void *)lock, '\0', sizeof(pth_lock)); + if (lock) { + lock->locked = 0; + status = pth_mutex_init(&lock->mut); + CHECK_STATUS("pth_mutex_init"); + status = pth_cond_init(&lock->lock_released); + CHECK_STATUS("pth_cond_init"); + if (error) { + free((void *)lock); + lock = NULL; + } + } + dprintf(("PyThread_allocate_lock() -> %p\n", lock)); + return (PyThread_type_lock) lock; } void PyThread_free_lock(PyThread_type_lock lock) { - pth_lock *thelock = (pth_lock *)lock; + pth_lock *thelock = (pth_lock *)lock; - dprintf(("PyThread_free_lock(%p) called\n", lock)); + dprintf(("PyThread_free_lock(%p) called\n", lock)); - free((void *)thelock); + free((void *)thelock); } int PyThread_acquire_lock(PyThread_type_lock lock, int waitflag) { - int success; - pth_lock *thelock = (pth_lock *)lock; - int status, error = 0; - - dprintf(("PyThread_acquire_lock(%p, %d) called\n", lock, waitflag)); - - status = pth_mutex_acquire(&thelock->mut, !waitflag, NULL); - CHECK_STATUS("pth_mutex_acquire[1]"); - success = thelock->locked == 0; - if (success) thelock->locked = 1; - status = pth_mutex_release( &thelock->mut ); - CHECK_STATUS("pth_mutex_release[1]"); - - if ( !success && waitflag ) { - /* continue trying until we get the lock */ - - /* mut must be locked by me -- part of the condition - * protocol */ - status = pth_mutex_acquire( &thelock->mut, !waitflag, NULL ); - CHECK_STATUS("pth_mutex_acquire[2]"); - while ( thelock->locked ) { - status = pth_cond_await(&thelock->lock_released, - &thelock->mut, NULL); - CHECK_STATUS("pth_cond_await"); - } - thelock->locked = 1; - status = pth_mutex_release( &thelock->mut ); - CHECK_STATUS("pth_mutex_release[2]"); - success = 1; + int success; + pth_lock *thelock = (pth_lock *)lock; + int status, error = 0; + + dprintf(("PyThread_acquire_lock(%p, %d) called\n", lock, waitflag)); + + status = pth_mutex_acquire(&thelock->mut, !waitflag, NULL); + CHECK_STATUS("pth_mutex_acquire[1]"); + success = thelock->locked == 0; + if (success) thelock->locked = 1; + status = pth_mutex_release( &thelock->mut ); + CHECK_STATUS("pth_mutex_release[1]"); + + if ( !success && waitflag ) { + /* continue trying until we get the lock */ + + /* mut must be locked by me -- part of the condition + * protocol */ + status = pth_mutex_acquire( &thelock->mut, !waitflag, NULL ); + CHECK_STATUS("pth_mutex_acquire[2]"); + while ( thelock->locked ) { + status = pth_cond_await(&thelock->lock_released, + &thelock->mut, NULL); + CHECK_STATUS("pth_cond_await"); } - if (error) success = 0; - dprintf(("PyThread_acquire_lock(%p, %d) -> %d\n", lock, waitflag, success)); - return success; + thelock->locked = 1; + status = pth_mutex_release( &thelock->mut ); + CHECK_STATUS("pth_mutex_release[2]"); + success = 1; + } + if (error) success = 0; + dprintf(("PyThread_acquire_lock(%p, %d) -> %d\n", lock, waitflag, success)); + return success; } void PyThread_release_lock(PyThread_type_lock lock) { - pth_lock *thelock = (pth_lock *)lock; - int status, error = 0; + pth_lock *thelock = (pth_lock *)lock; + int status, error = 0; - dprintf(("PyThread_release_lock(%p) called\n", lock)); + dprintf(("PyThread_release_lock(%p) called\n", lock)); - status = pth_mutex_acquire( &thelock->mut, 0, NULL ); - CHECK_STATUS("pth_mutex_acquire[3]"); + status = pth_mutex_acquire( &thelock->mut, 0, NULL ); + CHECK_STATUS("pth_mutex_acquire[3]"); - thelock->locked = 0; + thelock->locked = 0; - status = pth_mutex_release( &thelock->mut ); - CHECK_STATUS("pth_mutex_release[3]"); + status = pth_mutex_release( &thelock->mut ); + CHECK_STATUS("pth_mutex_release[3]"); - /* wake up someone (anyone, if any) waiting on the lock */ - status = pth_cond_notify( &thelock->lock_released, 0 ); - CHECK_STATUS("pth_cond_notify"); + /* wake up someone (anyone, if any) waiting on the lock */ + status = pth_cond_notify( &thelock->lock_released, 0 ); + CHECK_STATUS("pth_cond_notify"); } Modified: python/branches/release31-maint/Python/thread_pthread.h ============================================================================== --- python/branches/release31-maint/Python/thread_pthread.h (original) +++ python/branches/release31-maint/Python/thread_pthread.h Sun May 9 18:14:21 2010 @@ -16,10 +16,10 @@ be conditional on _POSIX_THREAD_ATTR_STACKSIZE being defined. */ #ifdef _POSIX_THREAD_ATTR_STACKSIZE #ifndef THREAD_STACK_SIZE -#define THREAD_STACK_SIZE 0 /* use default stack size */ +#define THREAD_STACK_SIZE 0 /* use default stack size */ #endif /* for safety, ensure a viable minimum stacksize */ -#define THREAD_STACK_MIN 0x8000 /* 32kB */ +#define THREAD_STACK_MIN 0x8000 /* 32kB */ #else /* !_POSIX_THREAD_ATTR_STACKSIZE */ #ifdef THREAD_STACK_SIZE #error "THREAD_STACK_SIZE defined but _POSIX_THREAD_ATTR_STACKSIZE undefined" @@ -28,9 +28,9 @@ /* The POSIX spec says that implementations supporting the sem_* family of functions must indicate this by defining - _POSIX_SEMAPHORES. */ + _POSIX_SEMAPHORES. */ #ifdef _POSIX_SEMAPHORES -/* On FreeBSD 4.x, _POSIX_SEMAPHORES is defined empty, so +/* On FreeBSD 4.x, _POSIX_SEMAPHORES is defined empty, so we need to add 0 to make it work there as well. */ #if (_POSIX_SEMAPHORES+0) == -1 #define HAVE_BROKEN_POSIX_SEMAPHORES @@ -99,10 +99,10 @@ */ typedef struct { - char locked; /* 0=unlocked, 1=locked */ - /* a pair to handle an acquire of a locked lock */ - pthread_cond_t lock_released; - pthread_mutex_t mut; + char locked; /* 0=unlocked, 1=locked */ + /* a pair to handle an acquire of a locked lock */ + pthread_cond_t lock_released; + pthread_mutex_t mut; } pthread_lock; #define CHECK_STATUS(name) if (status != 0) { perror(name); error = 1; } @@ -120,11 +120,11 @@ static void PyThread__init_thread(void) { - /* DO AN INIT BY STARTING THE THREAD */ - static int dummy = 0; - pthread_t thread1; - pthread_create(&thread1, NULL, (void *) _noop, &dummy); - pthread_join(thread1, NULL); + /* DO AN INIT BY STARTING THE THREAD */ + static int dummy = 0; + pthread_t thread1; + pthread_create(&thread1, NULL, (void *) _noop, &dummy); + pthread_join(thread1, NULL); } #else /* !_HAVE_BSDI */ @@ -133,7 +133,7 @@ PyThread__init_thread(void) { #if defined(_AIX) && defined(__GNUC__) - pthread_init(); + pthread_init(); #endif } @@ -147,59 +147,59 @@ long PyThread_start_new_thread(void (*func)(void *), void *arg) { - pthread_t th; - int status; + pthread_t th; + int status; #if defined(THREAD_STACK_SIZE) || defined(PTHREAD_SYSTEM_SCHED_SUPPORTED) - pthread_attr_t attrs; + pthread_attr_t attrs; #endif #if defined(THREAD_STACK_SIZE) - size_t tss; + size_t tss; #endif - dprintf(("PyThread_start_new_thread called\n")); - if (!initialized) - PyThread_init_thread(); + dprintf(("PyThread_start_new_thread called\n")); + if (!initialized) + PyThread_init_thread(); #if defined(THREAD_STACK_SIZE) || defined(PTHREAD_SYSTEM_SCHED_SUPPORTED) - if (pthread_attr_init(&attrs) != 0) - return -1; + if (pthread_attr_init(&attrs) != 0) + return -1; #endif #if defined(THREAD_STACK_SIZE) - tss = (_pythread_stacksize != 0) ? _pythread_stacksize - : THREAD_STACK_SIZE; - if (tss != 0) { - if (pthread_attr_setstacksize(&attrs, tss) != 0) { - pthread_attr_destroy(&attrs); - return -1; - } - } + tss = (_pythread_stacksize != 0) ? _pythread_stacksize + : THREAD_STACK_SIZE; + if (tss != 0) { + if (pthread_attr_setstacksize(&attrs, tss) != 0) { + pthread_attr_destroy(&attrs); + return -1; + } + } #endif #if defined(PTHREAD_SYSTEM_SCHED_SUPPORTED) - pthread_attr_setscope(&attrs, PTHREAD_SCOPE_SYSTEM); + pthread_attr_setscope(&attrs, PTHREAD_SCOPE_SYSTEM); #endif - status = pthread_create(&th, + status = pthread_create(&th, #if defined(THREAD_STACK_SIZE) || defined(PTHREAD_SYSTEM_SCHED_SUPPORTED) - &attrs, + &attrs, #else - (pthread_attr_t*)NULL, + (pthread_attr_t*)NULL, #endif - (void* (*)(void *))func, - (void *)arg - ); + (void* (*)(void *))func, + (void *)arg + ); #if defined(THREAD_STACK_SIZE) || defined(PTHREAD_SYSTEM_SCHED_SUPPORTED) - pthread_attr_destroy(&attrs); + pthread_attr_destroy(&attrs); #endif - if (status != 0) - return -1; + if (status != 0) + return -1; - pthread_detach(th); + pthread_detach(th); #if SIZEOF_PTHREAD_T <= SIZEOF_LONG - return (long) th; + return (long) th; #else - return (long) *(long *) &th; + return (long) *(long *) &th; #endif } @@ -210,67 +210,67 @@ - It is not clear that the 'volatile' (for AIX?) and ugly casting in the latter return statement (for Alpha OSF/1) are any longer necessary. */ -long +long PyThread_get_thread_ident(void) { - volatile pthread_t threadid; - if (!initialized) - PyThread_init_thread(); - /* Jump through some hoops for Alpha OSF/1 */ - threadid = pthread_self(); + volatile pthread_t threadid; + if (!initialized) + PyThread_init_thread(); + /* Jump through some hoops for Alpha OSF/1 */ + threadid = pthread_self(); #if SIZEOF_PTHREAD_T <= SIZEOF_LONG - return (long) threadid; + return (long) threadid; #else - return (long) *(long *) &threadid; + return (long) *(long *) &threadid; #endif } -static void +static void do_PyThread_exit_thread(int no_cleanup) { - dprintf(("PyThread_exit_thread called\n")); - if (!initialized) { - if (no_cleanup) - _exit(0); - else - exit(0); - } + dprintf(("PyThread_exit_thread called\n")); + if (!initialized) { + if (no_cleanup) + _exit(0); + else + exit(0); + } } -void +void PyThread_exit_thread(void) { - do_PyThread_exit_thread(0); + do_PyThread_exit_thread(0); } -void +void PyThread__exit_thread(void) { - do_PyThread_exit_thread(1); + do_PyThread_exit_thread(1); } #ifndef NO_EXIT_PROG -static void +static void do_PyThread_exit_prog(int status, int no_cleanup) { - dprintf(("PyThread_exit_prog(%d) called\n", status)); - if (!initialized) - if (no_cleanup) - _exit(status); - else - exit(status); + dprintf(("PyThread_exit_prog(%d) called\n", status)); + if (!initialized) + if (no_cleanup) + _exit(status); + else + exit(status); } -void +void PyThread_exit_prog(int status) { - do_PyThread_exit_prog(status, 0); + do_PyThread_exit_prog(status, 0); } -void +void PyThread__exit_prog(int status) { - do_PyThread_exit_prog(status, 1); + do_PyThread_exit_prog(status, 1); } #endif /* NO_EXIT_PROG */ @@ -280,47 +280,47 @@ * Lock support. */ -PyThread_type_lock +PyThread_type_lock PyThread_allocate_lock(void) { - sem_t *lock; - int status, error = 0; + sem_t *lock; + int status, error = 0; - dprintf(("PyThread_allocate_lock called\n")); - if (!initialized) - PyThread_init_thread(); + dprintf(("PyThread_allocate_lock called\n")); + if (!initialized) + PyThread_init_thread(); - lock = (sem_t *)malloc(sizeof(sem_t)); + lock = (sem_t *)malloc(sizeof(sem_t)); - if (lock) { - status = sem_init(lock,0,1); - CHECK_STATUS("sem_init"); + if (lock) { + status = sem_init(lock,0,1); + CHECK_STATUS("sem_init"); - if (error) { - free((void *)lock); - lock = NULL; - } - } + if (error) { + free((void *)lock); + lock = NULL; + } + } - dprintf(("PyThread_allocate_lock() -> %p\n", lock)); - return (PyThread_type_lock)lock; + dprintf(("PyThread_allocate_lock() -> %p\n", lock)); + return (PyThread_type_lock)lock; } -void +void PyThread_free_lock(PyThread_type_lock lock) { - sem_t *thelock = (sem_t *)lock; - int status, error = 0; + sem_t *thelock = (sem_t *)lock; + int status, error = 0; - dprintf(("PyThread_free_lock(%p) called\n", lock)); + dprintf(("PyThread_free_lock(%p) called\n", lock)); - if (!thelock) - return; + if (!thelock) + return; - status = sem_destroy(thelock); - CHECK_STATUS("sem_destroy"); + status = sem_destroy(thelock); + CHECK_STATUS("sem_destroy"); - free((void *)thelock); + free((void *)thelock); } /* @@ -332,47 +332,47 @@ static int fix_status(int status) { - return (status == -1) ? errno : status; + return (status == -1) ? errno : status; } -int +int PyThread_acquire_lock(PyThread_type_lock lock, int waitflag) { - int success; - sem_t *thelock = (sem_t *)lock; - int status, error = 0; - - dprintf(("PyThread_acquire_lock(%p, %d) called\n", lock, waitflag)); - - do { - if (waitflag) - status = fix_status(sem_wait(thelock)); - else - status = fix_status(sem_trywait(thelock)); - } while (status == EINTR); /* Retry if interrupted by a signal */ - - if (waitflag) { - CHECK_STATUS("sem_wait"); - } else if (status != EAGAIN) { - CHECK_STATUS("sem_trywait"); - } - - success = (status == 0) ? 1 : 0; + int success; + sem_t *thelock = (sem_t *)lock; + int status, error = 0; + + dprintf(("PyThread_acquire_lock(%p, %d) called\n", lock, waitflag)); + + do { + if (waitflag) + status = fix_status(sem_wait(thelock)); + else + status = fix_status(sem_trywait(thelock)); + } while (status == EINTR); /* Retry if interrupted by a signal */ + + if (waitflag) { + CHECK_STATUS("sem_wait"); + } else if (status != EAGAIN) { + CHECK_STATUS("sem_trywait"); + } + + success = (status == 0) ? 1 : 0; - dprintf(("PyThread_acquire_lock(%p, %d) -> %d\n", lock, waitflag, success)); - return success; + dprintf(("PyThread_acquire_lock(%p, %d) -> %d\n", lock, waitflag, success)); + return success; } -void +void PyThread_release_lock(PyThread_type_lock lock) { - sem_t *thelock = (sem_t *)lock; - int status, error = 0; + sem_t *thelock = (sem_t *)lock; + int status, error = 0; - dprintf(("PyThread_release_lock(%p) called\n", lock)); + dprintf(("PyThread_release_lock(%p) called\n", lock)); - status = sem_post(thelock); - CHECK_STATUS("sem_post"); + status = sem_post(thelock); + CHECK_STATUS("sem_post"); } #else /* USE_SEMAPHORES */ @@ -380,109 +380,109 @@ /* * Lock support. */ -PyThread_type_lock +PyThread_type_lock PyThread_allocate_lock(void) { - pthread_lock *lock; - int status, error = 0; + pthread_lock *lock; + int status, error = 0; - dprintf(("PyThread_allocate_lock called\n")); - if (!initialized) - PyThread_init_thread(); + dprintf(("PyThread_allocate_lock called\n")); + if (!initialized) + PyThread_init_thread(); - lock = (pthread_lock *) malloc(sizeof(pthread_lock)); - if (lock) { - memset((void *)lock, '\0', sizeof(pthread_lock)); - lock->locked = 0; + lock = (pthread_lock *) malloc(sizeof(pthread_lock)); + if (lock) { + memset((void *)lock, '\0', sizeof(pthread_lock)); + lock->locked = 0; - status = pthread_mutex_init(&lock->mut, - pthread_mutexattr_default); - CHECK_STATUS("pthread_mutex_init"); + status = pthread_mutex_init(&lock->mut, + pthread_mutexattr_default); + CHECK_STATUS("pthread_mutex_init"); - status = pthread_cond_init(&lock->lock_released, - pthread_condattr_default); - CHECK_STATUS("pthread_cond_init"); + status = pthread_cond_init(&lock->lock_released, + pthread_condattr_default); + CHECK_STATUS("pthread_cond_init"); - if (error) { - free((void *)lock); - lock = 0; - } - } + if (error) { + free((void *)lock); + lock = 0; + } + } - dprintf(("PyThread_allocate_lock() -> %p\n", lock)); - return (PyThread_type_lock) lock; + dprintf(("PyThread_allocate_lock() -> %p\n", lock)); + return (PyThread_type_lock) lock; } -void +void PyThread_free_lock(PyThread_type_lock lock) { - pthread_lock *thelock = (pthread_lock *)lock; - int status, error = 0; + pthread_lock *thelock = (pthread_lock *)lock; + int status, error = 0; - dprintf(("PyThread_free_lock(%p) called\n", lock)); + dprintf(("PyThread_free_lock(%p) called\n", lock)); - status = pthread_mutex_destroy( &thelock->mut ); - CHECK_STATUS("pthread_mutex_destroy"); + status = pthread_mutex_destroy( &thelock->mut ); + CHECK_STATUS("pthread_mutex_destroy"); - status = pthread_cond_destroy( &thelock->lock_released ); - CHECK_STATUS("pthread_cond_destroy"); + status = pthread_cond_destroy( &thelock->lock_released ); + CHECK_STATUS("pthread_cond_destroy"); - free((void *)thelock); + free((void *)thelock); } -int +int PyThread_acquire_lock(PyThread_type_lock lock, int waitflag) { - int success; - pthread_lock *thelock = (pthread_lock *)lock; - int status, error = 0; - - dprintf(("PyThread_acquire_lock(%p, %d) called\n", lock, waitflag)); - - status = pthread_mutex_lock( &thelock->mut ); - CHECK_STATUS("pthread_mutex_lock[1]"); - success = thelock->locked == 0; - - if ( !success && waitflag ) { - /* continue trying until we get the lock */ - - /* mut must be locked by me -- part of the condition - * protocol */ - while ( thelock->locked ) { - status = pthread_cond_wait(&thelock->lock_released, - &thelock->mut); - CHECK_STATUS("pthread_cond_wait"); - } - success = 1; - } - if (success) thelock->locked = 1; - status = pthread_mutex_unlock( &thelock->mut ); - CHECK_STATUS("pthread_mutex_unlock[1]"); - - if (error) success = 0; - dprintf(("PyThread_acquire_lock(%p, %d) -> %d\n", lock, waitflag, success)); - return success; + int success; + pthread_lock *thelock = (pthread_lock *)lock; + int status, error = 0; + + dprintf(("PyThread_acquire_lock(%p, %d) called\n", lock, waitflag)); + + status = pthread_mutex_lock( &thelock->mut ); + CHECK_STATUS("pthread_mutex_lock[1]"); + success = thelock->locked == 0; + + if ( !success && waitflag ) { + /* continue trying until we get the lock */ + + /* mut must be locked by me -- part of the condition + * protocol */ + while ( thelock->locked ) { + status = pthread_cond_wait(&thelock->lock_released, + &thelock->mut); + CHECK_STATUS("pthread_cond_wait"); + } + success = 1; + } + if (success) thelock->locked = 1; + status = pthread_mutex_unlock( &thelock->mut ); + CHECK_STATUS("pthread_mutex_unlock[1]"); + + if (error) success = 0; + dprintf(("PyThread_acquire_lock(%p, %d) -> %d\n", lock, waitflag, success)); + return success; } -void +void PyThread_release_lock(PyThread_type_lock lock) { - pthread_lock *thelock = (pthread_lock *)lock; - int status, error = 0; + pthread_lock *thelock = (pthread_lock *)lock; + int status, error = 0; - dprintf(("PyThread_release_lock(%p) called\n", lock)); + dprintf(("PyThread_release_lock(%p) called\n", lock)); - status = pthread_mutex_lock( &thelock->mut ); - CHECK_STATUS("pthread_mutex_lock[3]"); + status = pthread_mutex_lock( &thelock->mut ); + CHECK_STATUS("pthread_mutex_lock[3]"); - thelock->locked = 0; + thelock->locked = 0; - status = pthread_mutex_unlock( &thelock->mut ); - CHECK_STATUS("pthread_mutex_unlock[3]"); + status = pthread_mutex_unlock( &thelock->mut ); + CHECK_STATUS("pthread_mutex_unlock[3]"); - /* wake up someone (anyone, if any) waiting on the lock */ - status = pthread_cond_signal( &thelock->lock_released ); - CHECK_STATUS("pthread_cond_signal"); + /* wake up someone (anyone, if any) waiting on the lock */ + status = pthread_cond_signal( &thelock->lock_released ); + CHECK_STATUS("pthread_cond_signal"); } #endif /* USE_SEMAPHORES */ @@ -495,39 +495,39 @@ _pythread_pthread_set_stacksize(size_t size) { #if defined(THREAD_STACK_SIZE) - pthread_attr_t attrs; - size_t tss_min; - int rc = 0; + pthread_attr_t attrs; + size_t tss_min; + int rc = 0; #endif - /* set to default */ - if (size == 0) { - _pythread_stacksize = 0; - return 0; - } + /* set to default */ + if (size == 0) { + _pythread_stacksize = 0; + return 0; + } #if defined(THREAD_STACK_SIZE) #if defined(PTHREAD_STACK_MIN) - tss_min = PTHREAD_STACK_MIN > THREAD_STACK_MIN ? PTHREAD_STACK_MIN - : THREAD_STACK_MIN; + tss_min = PTHREAD_STACK_MIN > THREAD_STACK_MIN ? PTHREAD_STACK_MIN + : THREAD_STACK_MIN; #else - tss_min = THREAD_STACK_MIN; + tss_min = THREAD_STACK_MIN; #endif - if (size >= tss_min) { - /* validate stack size by setting thread attribute */ - if (pthread_attr_init(&attrs) == 0) { - rc = pthread_attr_setstacksize(&attrs, size); - pthread_attr_destroy(&attrs); - if (rc == 0) { - _pythread_stacksize = size; - return 0; - } - } - } - return -1; + if (size >= tss_min) { + /* validate stack size by setting thread attribute */ + if (pthread_attr_init(&attrs) == 0) { + rc = pthread_attr_setstacksize(&attrs, size); + pthread_attr_destroy(&attrs); + if (rc == 0) { + _pythread_stacksize = size; + return 0; + } + } + } + return -1; #else - return -2; + return -2; #endif } -#define THREAD_SET_STACKSIZE(x) _pythread_pthread_set_stacksize(x) +#define THREAD_SET_STACKSIZE(x) _pythread_pthread_set_stacksize(x) Modified: python/branches/release31-maint/Python/thread_sgi.h ============================================================================== --- python/branches/release31-maint/Python/thread_sgi.h (original) +++ python/branches/release31-maint/Python/thread_sgi.h Sun May 9 18:14:21 2010 @@ -8,25 +8,25 @@ #include #include -#define HDR_SIZE 2680 /* sizeof(ushdr_t) */ -#define MAXPROC 100 /* max # of threads that can be started */ +#define HDR_SIZE 2680 /* sizeof(ushdr_t) */ +#define MAXPROC 100 /* max # of threads that can be started */ static usptr_t *shared_arena; -static ulock_t count_lock; /* protection for some variables */ -static ulock_t wait_lock; /* lock used to wait for other threads */ -static int waiting_for_threads; /* protected by count_lock */ -static int nthreads; /* protected by count_lock */ +static ulock_t count_lock; /* protection for some variables */ +static ulock_t wait_lock; /* lock used to wait for other threads */ +static int waiting_for_threads; /* protected by count_lock */ +static int nthreads; /* protected by count_lock */ static int exit_status; #ifndef NO_EXIT_PROG -static int do_exit; /* indicates that the program is to exit */ +static int do_exit; /* indicates that the program is to exit */ #endif -static int exiting; /* we're already exiting (for maybe_exit) */ -static pid_t my_pid; /* PID of main thread */ +static int exiting; /* we're already exiting (for maybe_exit) */ +static pid_t my_pid; /* PID of main thread */ static struct pidlist { - pid_t parent; - pid_t child; -} pidlist[MAXPROC]; /* PIDs of other threads; protected by count_lock */ -static int maxpidindex; /* # of PIDs in pidlist */ + pid_t parent; + pid_t child; +} pidlist[MAXPROC]; /* PIDs of other threads; protected by count_lock */ +static int maxpidindex; /* # of PIDs in pidlist */ #ifndef NO_EXIT_PROG /* @@ -36,19 +36,19 @@ */ static void exit_sig(void) { - d2printf(("exit_sig called\n")); - if (exiting && getpid() == my_pid) { - d2printf(("already exiting\n")); - return; - } - if (do_exit) { - d2printf(("exiting in exit_sig\n")); + d2printf(("exit_sig called\n")); + if (exiting && getpid() == my_pid) { + d2printf(("already exiting\n")); + return; + } + if (do_exit) { + d2printf(("exiting in exit_sig\n")); #ifdef Py_DEBUG - if ((thread_debug & 8) == 0) - thread_debug &= ~1; /* don't produce debug messages */ + if ((thread_debug & 8) == 0) + thread_debug &= ~1; /* don't produce debug messages */ #endif - PyThread_exit_thread(); - } + PyThread_exit_thread(); + } } /* @@ -57,12 +57,12 @@ */ static void maybe_exit(void) { - dprintf(("maybe_exit called\n")); - if (exiting) { - dprintf(("already exiting\n")); - return; - } - PyThread_exit_prog(0); + dprintf(("maybe_exit called\n")); + if (exiting) { + dprintf(("already exiting\n")); + return; + } + PyThread_exit_prog(0); } #endif /* NO_EXIT_PROG */ @@ -72,58 +72,58 @@ static void PyThread__init_thread(void) { #ifndef NO_EXIT_PROG - struct sigaction s; + struct sigaction s; #endif /* NO_EXIT_PROG */ #ifdef USE_DL - long addr, size; + long addr, size; #endif /* USE_DL */ #ifdef USE_DL - if ((size = usconfig(CONF_INITSIZE, 64*1024)) < 0) - perror("usconfig - CONF_INITSIZE (check)"); - if (usconfig(CONF_INITSIZE, size) < 0) - perror("usconfig - CONF_INITSIZE (reset)"); - addr = (long) dl_getrange(size + HDR_SIZE); - dprintf(("trying to use addr %p-%p for shared arena\n", addr, addr+size)); - errno = 0; - if ((addr = usconfig(CONF_ATTACHADDR, addr)) < 0 && errno != 0) - perror("usconfig - CONF_ATTACHADDR (set)"); + if ((size = usconfig(CONF_INITSIZE, 64*1024)) < 0) + perror("usconfig - CONF_INITSIZE (check)"); + if (usconfig(CONF_INITSIZE, size) < 0) + perror("usconfig - CONF_INITSIZE (reset)"); + addr = (long) dl_getrange(size + HDR_SIZE); + dprintf(("trying to use addr %p-%p for shared arena\n", addr, addr+size)); + errno = 0; + if ((addr = usconfig(CONF_ATTACHADDR, addr)) < 0 && errno != 0) + perror("usconfig - CONF_ATTACHADDR (set)"); #endif /* USE_DL */ - if (usconfig(CONF_INITUSERS, 16) < 0) - perror("usconfig - CONF_INITUSERS"); - my_pid = getpid(); /* so that we know which is the main thread */ + if (usconfig(CONF_INITUSERS, 16) < 0) + perror("usconfig - CONF_INITUSERS"); + my_pid = getpid(); /* so that we know which is the main thread */ #ifndef NO_EXIT_PROG - atexit(maybe_exit); - s.sa_handler = exit_sig; - sigemptyset(&s.sa_mask); - /*sigaddset(&s.sa_mask, SIGUSR1);*/ - s.sa_flags = 0; - sigaction(SIGUSR1, &s, 0); - if (prctl(PR_SETEXITSIG, SIGUSR1) < 0) - perror("prctl - PR_SETEXITSIG"); + atexit(maybe_exit); + s.sa_handler = exit_sig; + sigemptyset(&s.sa_mask); + /*sigaddset(&s.sa_mask, SIGUSR1);*/ + s.sa_flags = 0; + sigaction(SIGUSR1, &s, 0); + if (prctl(PR_SETEXITSIG, SIGUSR1) < 0) + perror("prctl - PR_SETEXITSIG"); #endif /* NO_EXIT_PROG */ - if (usconfig(CONF_ARENATYPE, US_SHAREDONLY) < 0) - perror("usconfig - CONF_ARENATYPE"); - usconfig(CONF_LOCKTYPE, US_DEBUG); /* XXX */ + if (usconfig(CONF_ARENATYPE, US_SHAREDONLY) < 0) + perror("usconfig - CONF_ARENATYPE"); + usconfig(CONF_LOCKTYPE, US_DEBUG); /* XXX */ #ifdef Py_DEBUG - if (thread_debug & 4) - usconfig(CONF_LOCKTYPE, US_DEBUGPLUS); - else if (thread_debug & 2) - usconfig(CONF_LOCKTYPE, US_DEBUG); + if (thread_debug & 4) + usconfig(CONF_LOCKTYPE, US_DEBUGPLUS); + else if (thread_debug & 2) + usconfig(CONF_LOCKTYPE, US_DEBUG); #endif /* Py_DEBUG */ - if ((shared_arena = usinit(tmpnam(0))) == 0) - perror("usinit"); + if ((shared_arena = usinit(tmpnam(0))) == 0) + perror("usinit"); #ifdef USE_DL - if (usconfig(CONF_ATTACHADDR, addr) < 0) /* reset address */ - perror("usconfig - CONF_ATTACHADDR (reset)"); + if (usconfig(CONF_ATTACHADDR, addr) < 0) /* reset address */ + perror("usconfig - CONF_ATTACHADDR (reset)"); #endif /* USE_DL */ - if ((count_lock = usnewlock(shared_arena)) == NULL) - perror("usnewlock (count_lock)"); - (void) usinitlock(count_lock); - if ((wait_lock = usnewlock(shared_arena)) == NULL) - perror("usnewlock (wait_lock)"); - dprintf(("arena start: %p, arena size: %ld\n", shared_arena, (long) usconfig(CONF_GETSIZE, shared_arena))); + if ((count_lock = usnewlock(shared_arena)) == NULL) + perror("usnewlock (count_lock)"); + (void) usinitlock(count_lock); + if ((wait_lock = usnewlock(shared_arena)) == NULL) + perror("usnewlock (wait_lock)"); + dprintf(("arena start: %p, arena size: %ld\n", shared_arena, (long) usconfig(CONF_GETSIZE, shared_arena))); } /* @@ -132,198 +132,198 @@ static void clean_threads(void) { - int i, j; - pid_t mypid, pid; + int i, j; + pid_t mypid, pid; - /* clean up any exited threads */ - mypid = getpid(); - i = 0; - while (i < maxpidindex) { - if (pidlist[i].parent == mypid && (pid = pidlist[i].child) > 0) { - pid = waitpid(pid, 0, WNOHANG); - if (pid > 0) { - /* a thread has exited */ - pidlist[i] = pidlist[--maxpidindex]; - /* remove references to children of dead proc */ - for (j = 0; j < maxpidindex; j++) - if (pidlist[j].parent == pid) - pidlist[j].child = -1; - continue; /* don't increment i */ - } - } - i++; - } - /* clean up the list */ - i = 0; - while (i < maxpidindex) { - if (pidlist[i].child == -1) { - pidlist[i] = pidlist[--maxpidindex]; - continue; /* don't increment i */ - } - i++; - } + /* clean up any exited threads */ + mypid = getpid(); + i = 0; + while (i < maxpidindex) { + if (pidlist[i].parent == mypid && (pid = pidlist[i].child) > 0) { + pid = waitpid(pid, 0, WNOHANG); + if (pid > 0) { + /* a thread has exited */ + pidlist[i] = pidlist[--maxpidindex]; + /* remove references to children of dead proc */ + for (j = 0; j < maxpidindex; j++) + if (pidlist[j].parent == pid) + pidlist[j].child = -1; + continue; /* don't increment i */ + } + } + i++; + } + /* clean up the list */ + i = 0; + while (i < maxpidindex) { + if (pidlist[i].child == -1) { + pidlist[i] = pidlist[--maxpidindex]; + continue; /* don't increment i */ + } + i++; + } } long PyThread_start_new_thread(void (*func)(void *), void *arg) { #ifdef USE_DL - long addr, size; - static int local_initialized = 0; + long addr, size; + static int local_initialized = 0; #endif /* USE_DL */ - int success = 0; /* init not needed when SOLARIS_THREADS and */ - /* C_THREADS implemented properly */ + int success = 0; /* init not needed when SOLARIS_THREADS and */ + /* C_THREADS implemented properly */ - dprintf(("PyThread_start_new_thread called\n")); - if (!initialized) - PyThread_init_thread(); - switch (ussetlock(count_lock)) { - case 0: return 0; - case -1: perror("ussetlock (count_lock)"); - } - if (maxpidindex >= MAXPROC) - success = -1; - else { + dprintf(("PyThread_start_new_thread called\n")); + if (!initialized) + PyThread_init_thread(); + switch (ussetlock(count_lock)) { + case 0: return 0; + case -1: perror("ussetlock (count_lock)"); + } + if (maxpidindex >= MAXPROC) + success = -1; + else { #ifdef USE_DL - if (!local_initialized) { - if ((size = usconfig(CONF_INITSIZE, 64*1024)) < 0) - perror("usconfig - CONF_INITSIZE (check)"); - if (usconfig(CONF_INITSIZE, size) < 0) - perror("usconfig - CONF_INITSIZE (reset)"); - addr = (long) dl_getrange(size + HDR_SIZE); - dprintf(("trying to use addr %p-%p for sproc\n", - addr, addr+size)); - errno = 0; - if ((addr = usconfig(CONF_ATTACHADDR, addr)) < 0 && - errno != 0) - perror("usconfig - CONF_ATTACHADDR (set)"); - } + if (!local_initialized) { + if ((size = usconfig(CONF_INITSIZE, 64*1024)) < 0) + perror("usconfig - CONF_INITSIZE (check)"); + if (usconfig(CONF_INITSIZE, size) < 0) + perror("usconfig - CONF_INITSIZE (reset)"); + addr = (long) dl_getrange(size + HDR_SIZE); + dprintf(("trying to use addr %p-%p for sproc\n", + addr, addr+size)); + errno = 0; + if ((addr = usconfig(CONF_ATTACHADDR, addr)) < 0 && + errno != 0) + perror("usconfig - CONF_ATTACHADDR (set)"); + } #endif /* USE_DL */ - clean_threads(); - if ((success = sproc(func, PR_SALL, arg)) < 0) - perror("sproc"); + clean_threads(); + if ((success = sproc(func, PR_SALL, arg)) < 0) + perror("sproc"); #ifdef USE_DL - if (!local_initialized) { - if (usconfig(CONF_ATTACHADDR, addr) < 0) - /* reset address */ - perror("usconfig - CONF_ATTACHADDR (reset)"); - local_initialized = 1; - } + if (!local_initialized) { + if (usconfig(CONF_ATTACHADDR, addr) < 0) + /* reset address */ + perror("usconfig - CONF_ATTACHADDR (reset)"); + local_initialized = 1; + } #endif /* USE_DL */ - if (success >= 0) { - nthreads++; - pidlist[maxpidindex].parent = getpid(); - pidlist[maxpidindex++].child = success; - dprintf(("pidlist[%d] = %d\n", - maxpidindex-1, success)); - } - } - if (usunsetlock(count_lock) < 0) - perror("usunsetlock (count_lock)"); - return success; + if (success >= 0) { + nthreads++; + pidlist[maxpidindex].parent = getpid(); + pidlist[maxpidindex++].child = success; + dprintf(("pidlist[%d] = %d\n", + maxpidindex-1, success)); + } + } + if (usunsetlock(count_lock) < 0) + perror("usunsetlock (count_lock)"); + return success; } long PyThread_get_thread_ident(void) { - return getpid(); + return getpid(); } static void do_PyThread_exit_thread(int no_cleanup) { - dprintf(("PyThread_exit_thread called\n")); - if (!initialized) - if (no_cleanup) - _exit(0); - else - exit(0); - if (ussetlock(count_lock) < 0) - perror("ussetlock (count_lock)"); - nthreads--; - if (getpid() == my_pid) { - /* main thread; wait for other threads to exit */ - exiting = 1; + dprintf(("PyThread_exit_thread called\n")); + if (!initialized) + if (no_cleanup) + _exit(0); + else + exit(0); + if (ussetlock(count_lock) < 0) + perror("ussetlock (count_lock)"); + nthreads--; + if (getpid() == my_pid) { + /* main thread; wait for other threads to exit */ + exiting = 1; #ifndef NO_EXIT_PROG - if (do_exit) { - int i; + if (do_exit) { + int i; - /* notify other threads */ - clean_threads(); - if (nthreads >= 0) { - dprintf(("kill other threads\n")); - for (i = 0; i < maxpidindex; i++) - if (pidlist[i].child > 0) - (void) kill(pidlist[i].child, - SIGKILL); - _exit(exit_status); - } - } + /* notify other threads */ + clean_threads(); + if (nthreads >= 0) { + dprintf(("kill other threads\n")); + for (i = 0; i < maxpidindex; i++) + if (pidlist[i].child > 0) + (void) kill(pidlist[i].child, + SIGKILL); + _exit(exit_status); + } + } #endif /* NO_EXIT_PROG */ - waiting_for_threads = 1; - if (ussetlock(wait_lock) < 0) - perror("ussetlock (wait_lock)"); - for (;;) { - if (nthreads < 0) { - dprintf(("really exit (%d)\n", exit_status)); - if (no_cleanup) - _exit(exit_status); - else - exit(exit_status); - } - if (usunsetlock(count_lock) < 0) - perror("usunsetlock (count_lock)"); - dprintf(("waiting for other threads (%d)\n", nthreads)); - if (ussetlock(wait_lock) < 0) - perror("ussetlock (wait_lock)"); - if (ussetlock(count_lock) < 0) - perror("ussetlock (count_lock)"); - } - } - /* not the main thread */ - if (waiting_for_threads) { - dprintf(("main thread is waiting\n")); - if (usunsetlock(wait_lock) < 0) - perror("usunsetlock (wait_lock)"); - } + waiting_for_threads = 1; + if (ussetlock(wait_lock) < 0) + perror("ussetlock (wait_lock)"); + for (;;) { + if (nthreads < 0) { + dprintf(("really exit (%d)\n", exit_status)); + if (no_cleanup) + _exit(exit_status); + else + exit(exit_status); + } + if (usunsetlock(count_lock) < 0) + perror("usunsetlock (count_lock)"); + dprintf(("waiting for other threads (%d)\n", nthreads)); + if (ussetlock(wait_lock) < 0) + perror("ussetlock (wait_lock)"); + if (ussetlock(count_lock) < 0) + perror("ussetlock (count_lock)"); + } + } + /* not the main thread */ + if (waiting_for_threads) { + dprintf(("main thread is waiting\n")); + if (usunsetlock(wait_lock) < 0) + perror("usunsetlock (wait_lock)"); + } #ifndef NO_EXIT_PROG - else if (do_exit) - (void) kill(my_pid, SIGUSR1); + else if (do_exit) + (void) kill(my_pid, SIGUSR1); #endif /* NO_EXIT_PROG */ - if (usunsetlock(count_lock) < 0) - perror("usunsetlock (count_lock)"); - _exit(0); + if (usunsetlock(count_lock) < 0) + perror("usunsetlock (count_lock)"); + _exit(0); } void PyThread_exit_thread(void) { - do_PyThread_exit_thread(0); + do_PyThread_exit_thread(0); } void PyThread__exit_thread(void) { - do_PyThread_exit_thread(1); + do_PyThread_exit_thread(1); } #ifndef NO_EXIT_PROG static void do_PyThread_exit_prog(int status, int no_cleanup) { - dprintf(("PyThread_exit_prog(%d) called\n", status)); - if (!initialized) - if (no_cleanup) - _exit(status); - else - exit(status); - do_exit = 1; - exit_status = status; - do_PyThread_exit_thread(no_cleanup); + dprintf(("PyThread_exit_prog(%d) called\n", status)); + if (!initialized) + if (no_cleanup) + _exit(status); + else + exit(status); + do_exit = 1; + exit_status = status; + do_PyThread_exit_thread(no_cleanup); } void PyThread_exit_prog(int status) { - do_PyThread_exit_prog(status, 0); + do_PyThread_exit_prog(status, 0); } void PyThread__exit_prog(int status) { - do_PyThread_exit_prog(status, 1); + do_PyThread_exit_prog(status, 1); } #endif /* NO_EXIT_PROG */ @@ -332,44 +332,44 @@ */ PyThread_type_lock PyThread_allocate_lock(void) { - ulock_t lock; + ulock_t lock; - dprintf(("PyThread_allocate_lock called\n")); - if (!initialized) - PyThread_init_thread(); - - if ((lock = usnewlock(shared_arena)) == NULL) - perror("usnewlock"); - (void) usinitlock(lock); - dprintf(("PyThread_allocate_lock() -> %p\n", lock)); - return (PyThread_type_lock) lock; + dprintf(("PyThread_allocate_lock called\n")); + if (!initialized) + PyThread_init_thread(); + + if ((lock = usnewlock(shared_arena)) == NULL) + perror("usnewlock"); + (void) usinitlock(lock); + dprintf(("PyThread_allocate_lock() -> %p\n", lock)); + return (PyThread_type_lock) lock; } void PyThread_free_lock(PyThread_type_lock lock) { - dprintf(("PyThread_free_lock(%p) called\n", lock)); - usfreelock((ulock_t) lock, shared_arena); + dprintf(("PyThread_free_lock(%p) called\n", lock)); + usfreelock((ulock_t) lock, shared_arena); } int PyThread_acquire_lock(PyThread_type_lock lock, int waitflag) { - int success; + int success; - dprintf(("PyThread_acquire_lock(%p, %d) called\n", lock, waitflag)); - errno = 0; /* clear it just in case */ - if (waitflag) - success = ussetlock((ulock_t) lock); - else - success = uscsetlock((ulock_t) lock, 1); /* Try it once */ - if (success < 0) - perror(waitflag ? "ussetlock" : "uscsetlock"); - dprintf(("PyThread_acquire_lock(%p, %d) -> %d\n", lock, waitflag, success)); - return success; + dprintf(("PyThread_acquire_lock(%p, %d) called\n", lock, waitflag)); + errno = 0; /* clear it just in case */ + if (waitflag) + success = ussetlock((ulock_t) lock); + else + success = uscsetlock((ulock_t) lock, 1); /* Try it once */ + if (success < 0) + perror(waitflag ? "ussetlock" : "uscsetlock"); + dprintf(("PyThread_acquire_lock(%p, %d) -> %d\n", lock, waitflag, success)); + return success; } void PyThread_release_lock(PyThread_type_lock lock) { - dprintf(("PyThread_release_lock(%p) called\n", lock)); - if (usunsetlock((ulock_t) lock) < 0) - perror("usunsetlock"); + dprintf(("PyThread_release_lock(%p) called\n", lock)); + if (usunsetlock((ulock_t) lock) < 0) + perror("usunsetlock"); } Modified: python/branches/release31-maint/Python/thread_solaris.h ============================================================================== --- python/branches/release31-maint/Python/thread_solaris.h (original) +++ python/branches/release31-maint/Python/thread_solaris.h Sun May 9 18:14:21 2010 @@ -17,158 +17,158 @@ * Thread support. */ struct func_arg { - void (*func)(void *); - void *arg; + void (*func)(void *); + void *arg; }; static void * new_func(void *funcarg) { - void (*func)(void *); - void *arg; + void (*func)(void *); + void *arg; - func = ((struct func_arg *) funcarg)->func; - arg = ((struct func_arg *) funcarg)->arg; - free(funcarg); - (*func)(arg); - return 0; + func = ((struct func_arg *) funcarg)->func; + arg = ((struct func_arg *) funcarg)->arg; + free(funcarg); + (*func)(arg); + return 0; } long PyThread_start_new_thread(void (*func)(void *), void *arg) { - thread_t tid; - struct func_arg *funcarg; + thread_t tid; + struct func_arg *funcarg; - dprintf(("PyThread_start_new_thread called\n")); - if (!initialized) - PyThread_init_thread(); - funcarg = (struct func_arg *) malloc(sizeof(struct func_arg)); - funcarg->func = func; - funcarg->arg = arg; - if (thr_create(0, 0, new_func, funcarg, - THR_DETACHED | THR_NEW_LWP, &tid)) { - perror("thr_create"); - free((void *) funcarg); - return -1; - } - return tid; + dprintf(("PyThread_start_new_thread called\n")); + if (!initialized) + PyThread_init_thread(); + funcarg = (struct func_arg *) malloc(sizeof(struct func_arg)); + funcarg->func = func; + funcarg->arg = arg; + if (thr_create(0, 0, new_func, funcarg, + THR_DETACHED | THR_NEW_LWP, &tid)) { + perror("thr_create"); + free((void *) funcarg); + return -1; + } + return tid; } long PyThread_get_thread_ident(void) { - if (!initialized) - PyThread_init_thread(); - return thr_self(); + if (!initialized) + PyThread_init_thread(); + return thr_self(); } -static void +static void do_PyThread_exit_thread(int no_cleanup) { - dprintf(("PyThread_exit_thread called\n")); - if (!initialized) - if (no_cleanup) - _exit(0); - else - exit(0); - thr_exit(0); + dprintf(("PyThread_exit_thread called\n")); + if (!initialized) + if (no_cleanup) + _exit(0); + else + exit(0); + thr_exit(0); } -void +void PyThread_exit_thread(void) { - do_PyThread_exit_thread(0); + do_PyThread_exit_thread(0); } -void +void PyThread__exit_thread(void) { - do_PyThread_exit_thread(1); + do_PyThread_exit_thread(1); } #ifndef NO_EXIT_PROG -static void +static void do_PyThread_exit_prog(int status, int no_cleanup) { - dprintf(("PyThread_exit_prog(%d) called\n", status)); - if (!initialized) - if (no_cleanup) - _exit(status); - else - exit(status); - if (no_cleanup) - _exit(status); - else - exit(status); + dprintf(("PyThread_exit_prog(%d) called\n", status)); + if (!initialized) + if (no_cleanup) + _exit(status); + else + exit(status); + if (no_cleanup) + _exit(status); + else + exit(status); } -void +void PyThread_exit_prog(int status) { - do_PyThread_exit_prog(status, 0); + do_PyThread_exit_prog(status, 0); } -void +void PyThread__exit_prog(int status) { - do_PyThread_exit_prog(status, 1); + do_PyThread_exit_prog(status, 1); } #endif /* NO_EXIT_PROG */ /* * Lock support. */ -PyThread_type_lock +PyThread_type_lock PyThread_allocate_lock(void) { - mutex_t *lock; + mutex_t *lock; - dprintf(("PyThread_allocate_lock called\n")); - if (!initialized) - PyThread_init_thread(); - - lock = (mutex_t *) malloc(sizeof(mutex_t)); - if (mutex_init(lock, USYNC_THREAD, 0)) { - perror("mutex_init"); - free((void *) lock); - lock = 0; - } - dprintf(("PyThread_allocate_lock() -> %p\n", lock)); - return (PyThread_type_lock) lock; + dprintf(("PyThread_allocate_lock called\n")); + if (!initialized) + PyThread_init_thread(); + + lock = (mutex_t *) malloc(sizeof(mutex_t)); + if (mutex_init(lock, USYNC_THREAD, 0)) { + perror("mutex_init"); + free((void *) lock); + lock = 0; + } + dprintf(("PyThread_allocate_lock() -> %p\n", lock)); + return (PyThread_type_lock) lock; } -void +void PyThread_free_lock(PyThread_type_lock lock) { - dprintf(("PyThread_free_lock(%p) called\n", lock)); - mutex_destroy((mutex_t *) lock); - free((void *) lock); + dprintf(("PyThread_free_lock(%p) called\n", lock)); + mutex_destroy((mutex_t *) lock); + free((void *) lock); } -int +int PyThread_acquire_lock(PyThread_type_lock lock, int waitflag) { - int success; + int success; - dprintf(("PyThread_acquire_lock(%p, %d) called\n", lock, waitflag)); - if (waitflag) - success = mutex_lock((mutex_t *) lock); - else - success = mutex_trylock((mutex_t *) lock); - if (success < 0) - perror(waitflag ? "mutex_lock" : "mutex_trylock"); - else - success = !success; /* solaris does it the other way round */ - dprintf(("PyThread_acquire_lock(%p, %d) -> %d\n", lock, waitflag, success)); - return success; + dprintf(("PyThread_acquire_lock(%p, %d) called\n", lock, waitflag)); + if (waitflag) + success = mutex_lock((mutex_t *) lock); + else + success = mutex_trylock((mutex_t *) lock); + if (success < 0) + perror(waitflag ? "mutex_lock" : "mutex_trylock"); + else + success = !success; /* solaris does it the other way round */ + dprintf(("PyThread_acquire_lock(%p, %d) -> %d\n", lock, waitflag, success)); + return success; } -void +void PyThread_release_lock(PyThread_type_lock lock) { - dprintf(("PyThread_release_lock(%p) called\n", lock)); - if (mutex_unlock((mutex_t *) lock)) - perror("mutex_unlock"); + dprintf(("PyThread_release_lock(%p) called\n", lock)); + if (mutex_unlock((mutex_t *) lock)) + perror("mutex_unlock"); } Modified: python/branches/release31-maint/Python/thread_wince.h ============================================================================== --- python/branches/release31-maint/Python/thread_wince.h (original) +++ python/branches/release31-maint/Python/thread_wince.h Sun May 9 18:14:21 2010 @@ -24,21 +24,21 @@ */ long PyThread_start_new_thread(void (*func)(void *), void *arg) { - long rv; - int success = -1; + long rv; + int success = -1; - dprintf(("%ld: PyThread_start_new_thread called\n", PyThread_get_thread_ident())); - if (!initialized) - PyThread_init_thread(); - - rv = _beginthread(func, 0, arg); /* use default stack size */ - - if (rv != -1) { - success = 0; - dprintf(("%ld: PyThread_start_new_thread succeeded:\n", PyThread_get_thread_ident())); - } + dprintf(("%ld: PyThread_start_new_thread called\n", PyThread_get_thread_ident())); + if (!initialized) + PyThread_init_thread(); + + rv = _beginthread(func, 0, arg); /* use default stack size */ - return success; + if (rv != -1) { + success = 0; + dprintf(("%ld: PyThread_start_new_thread succeeded:\n", PyThread_get_thread_ident())); + } + + return success; } /* @@ -47,52 +47,52 @@ */ long PyThread_get_thread_ident(void) { - if (!initialized) - PyThread_init_thread(); - - return GetCurrentThreadId(); + if (!initialized) + PyThread_init_thread(); + + return GetCurrentThreadId(); } static void do_PyThread_exit_thread(int no_cleanup) { - dprintf(("%ld: do_PyThread_exit_thread called\n", PyThread_get_thread_ident())); - if (!initialized) - if (no_cleanup) - exit(0); /* XXX - was _exit()!! */ - else - exit(0); - _endthread(); + dprintf(("%ld: do_PyThread_exit_thread called\n", PyThread_get_thread_ident())); + if (!initialized) + if (no_cleanup) + exit(0); /* XXX - was _exit()!! */ + else + exit(0); + _endthread(); } void PyThread_exit_thread(void) { - do_PyThread_exit_thread(0); + do_PyThread_exit_thread(0); } void PyThread__exit_thread(void) { - do_PyThread_exit_thread(1); + do_PyThread_exit_thread(1); } #ifndef NO_EXIT_PROG static void do_PyThread_exit_prog(int status, int no_cleanup) { - dprintf(("PyThread_exit_prog(%d) called\n", status)); - if (!initialized) - if (no_cleanup) - _exit(status); - else - exit(status); + dprintf(("PyThread_exit_prog(%d) called\n", status)); + if (!initialized) + if (no_cleanup) + _exit(status); + else + exit(status); } void PyThread_exit_prog(int status) { - do_PyThread_exit_prog(status, 0); + do_PyThread_exit_prog(status, 0); } void PyThread__exit_prog(int status) { - do_PyThread_exit_prog(status, 1); + do_PyThread_exit_prog(status, 1); } #endif /* NO_EXIT_PROG */ @@ -107,12 +107,12 @@ dprintf(("PyThread_allocate_lock called\n")); if (!initialized) - PyThread_init_thread(); + PyThread_init_thread(); aLock = CreateEvent(NULL, /* Security attributes */ - 0, /* Manual-Reset */ - 1, /* Is initially signalled */ - NULL); /* Name of event */ + 0, /* Manual-Reset */ + 1, /* Is initially signalled */ + NULL); /* Name of event */ dprintf(("%ld: PyThread_allocate_lock() -> %p\n", PyThread_get_thread_ident(), aLock)); @@ -142,22 +142,22 @@ #ifndef DEBUG waitResult = WaitForSingleObject(aLock, (waitflag ? INFINITE : 0)); #else - /* To aid in debugging, we regularly wake up. This allows us to - break into the debugger */ - while (TRUE) { - waitResult = WaitForSingleObject(aLock, waitflag ? 3000 : 0); - if (waitflag==0 || (waitflag && waitResult == WAIT_OBJECT_0)) - break; - } + /* To aid in debugging, we regularly wake up. This allows us to + break into the debugger */ + while (TRUE) { + waitResult = WaitForSingleObject(aLock, waitflag ? 3000 : 0); + if (waitflag==0 || (waitflag && waitResult == WAIT_OBJECT_0)) + break; + } #endif if (waitResult != WAIT_OBJECT_0) { - success = 0; /* We failed */ + success = 0; /* We failed */ } - dprintf(("%ld: PyThread_acquire_lock(%p, %d) -> %d\n", PyThread_get_thread_ident(),aLock, waitflag, success)); + dprintf(("%ld: PyThread_acquire_lock(%p, %d) -> %d\n", PyThread_get_thread_ident(),aLock, waitflag, success)); - return success; + return success; } void PyThread_release_lock(PyThread_type_lock aLock) @@ -165,7 +165,7 @@ dprintf(("%ld: PyThread_release_lock(%p) called\n", PyThread_get_thread_ident(),aLock)); if (!SetEvent(aLock)) - dprintf(("%ld: Could not PyThread_release_lock(%p) error: %l\n", PyThread_get_thread_ident(), aLock, GetLastError())); + dprintf(("%ld: Could not PyThread_release_lock(%p) error: %l\n", PyThread_get_thread_ident(), aLock, GetLastError())); } Modified: python/branches/release31-maint/Python/traceback.c ============================================================================== --- python/branches/release31-maint/Python/traceback.c (original) +++ python/branches/release31-maint/Python/traceback.c Sun May 9 18:14:21 2010 @@ -30,304 +30,304 @@ }; static PyMemberDef tb_memberlist[] = { - {"tb_next", T_OBJECT, OFF(tb_next), READONLY}, - {"tb_frame", T_OBJECT, OFF(tb_frame), READONLY}, - {"tb_lasti", T_INT, OFF(tb_lasti), READONLY}, - {"tb_lineno", T_INT, OFF(tb_lineno), READONLY}, - {NULL} /* Sentinel */ + {"tb_next", T_OBJECT, OFF(tb_next), READONLY}, + {"tb_frame", T_OBJECT, OFF(tb_frame), READONLY}, + {"tb_lasti", T_INT, OFF(tb_lasti), READONLY}, + {"tb_lineno", T_INT, OFF(tb_lineno), READONLY}, + {NULL} /* Sentinel */ }; static void tb_dealloc(PyTracebackObject *tb) { - PyObject_GC_UnTrack(tb); - Py_TRASHCAN_SAFE_BEGIN(tb) - Py_XDECREF(tb->tb_next); - Py_XDECREF(tb->tb_frame); - PyObject_GC_Del(tb); - Py_TRASHCAN_SAFE_END(tb) + PyObject_GC_UnTrack(tb); + Py_TRASHCAN_SAFE_BEGIN(tb) + Py_XDECREF(tb->tb_next); + Py_XDECREF(tb->tb_frame); + PyObject_GC_Del(tb); + Py_TRASHCAN_SAFE_END(tb) } static int tb_traverse(PyTracebackObject *tb, visitproc visit, void *arg) { - Py_VISIT(tb->tb_next); - Py_VISIT(tb->tb_frame); - return 0; + Py_VISIT(tb->tb_next); + Py_VISIT(tb->tb_frame); + return 0; } static void tb_clear(PyTracebackObject *tb) { - Py_CLEAR(tb->tb_next); - Py_CLEAR(tb->tb_frame); + Py_CLEAR(tb->tb_next); + Py_CLEAR(tb->tb_frame); } PyTypeObject PyTraceBack_Type = { - PyVarObject_HEAD_INIT(&PyType_Type, 0) - "traceback", - sizeof(PyTracebackObject), - 0, - (destructor)tb_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)tb_traverse, /* tp_traverse */ - (inquiry)tb_clear, /* tp_clear */ - 0, /* tp_richcompare */ - 0, /* tp_weaklistoffset */ - 0, /* tp_iter */ - 0, /* tp_iternext */ - tb_methods, /* tp_methods */ - tb_memberlist, /* tp_members */ - 0, /* tp_getset */ - 0, /* tp_base */ - 0, /* tp_dict */ + PyVarObject_HEAD_INIT(&PyType_Type, 0) + "traceback", + sizeof(PyTracebackObject), + 0, + (destructor)tb_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)tb_traverse, /* tp_traverse */ + (inquiry)tb_clear, /* tp_clear */ + 0, /* tp_richcompare */ + 0, /* tp_weaklistoffset */ + 0, /* tp_iter */ + 0, /* tp_iternext */ + tb_methods, /* tp_methods */ + tb_memberlist, /* tp_members */ + 0, /* tp_getset */ + 0, /* tp_base */ + 0, /* tp_dict */ }; static PyTracebackObject * newtracebackobject(PyTracebackObject *next, PyFrameObject *frame) { - PyTracebackObject *tb; - if ((next != NULL && !PyTraceBack_Check(next)) || - frame == NULL || !PyFrame_Check(frame)) { - PyErr_BadInternalCall(); - return NULL; - } - tb = PyObject_GC_New(PyTracebackObject, &PyTraceBack_Type); - if (tb != NULL) { - Py_XINCREF(next); - tb->tb_next = next; - Py_XINCREF(frame); - tb->tb_frame = frame; - tb->tb_lasti = frame->f_lasti; - tb->tb_lineno = PyCode_Addr2Line(frame->f_code, - frame->f_lasti); - PyObject_GC_Track(tb); - } - return tb; + PyTracebackObject *tb; + if ((next != NULL && !PyTraceBack_Check(next)) || + frame == NULL || !PyFrame_Check(frame)) { + PyErr_BadInternalCall(); + return NULL; + } + tb = PyObject_GC_New(PyTracebackObject, &PyTraceBack_Type); + if (tb != NULL) { + Py_XINCREF(next); + tb->tb_next = next; + Py_XINCREF(frame); + tb->tb_frame = frame; + tb->tb_lasti = frame->f_lasti; + tb->tb_lineno = PyCode_Addr2Line(frame->f_code, + frame->f_lasti); + PyObject_GC_Track(tb); + } + return tb; } int PyTraceBack_Here(PyFrameObject *frame) { - PyThreadState *tstate = PyThreadState_GET(); - PyTracebackObject *oldtb = (PyTracebackObject *) tstate->curexc_traceback; - PyTracebackObject *tb = newtracebackobject(oldtb, frame); - if (tb == NULL) - return -1; - tstate->curexc_traceback = (PyObject *)tb; - Py_XDECREF(oldtb); - return 0; + PyThreadState *tstate = PyThreadState_GET(); + PyTracebackObject *oldtb = (PyTracebackObject *) tstate->curexc_traceback; + PyTracebackObject *tb = newtracebackobject(oldtb, frame); + if (tb == NULL) + return -1; + tstate->curexc_traceback = (PyObject *)tb; + Py_XDECREF(oldtb); + return 0; } static int _Py_FindSourceFile(const char* filename, char* namebuf, size_t namelen, int open_flags) { - int i; - int fd = -1; - PyObject *v; - Py_ssize_t _npath; - int npath; - size_t taillen; - PyObject *syspath; - const char* path; - const char* tail; - Py_ssize_t len; - - /* Search tail of filename in sys.path before giving up */ - tail = strrchr(filename, SEP); - if (tail == NULL) - tail = filename; - else - tail++; - taillen = strlen(tail); - - syspath = PySys_GetObject("path"); - if (syspath == NULL || !PyList_Check(syspath)) - return -1; - _npath = PyList_Size(syspath); - npath = Py_SAFE_DOWNCAST(_npath, Py_ssize_t, int); - - for (i = 0; i < npath; i++) { - v = PyList_GetItem(syspath, i); - if (v == NULL) { - PyErr_Clear(); - break; - } - if (!PyUnicode_Check(v)) - continue; - path = _PyUnicode_AsStringAndSize(v, &len); - if (len + 1 + (Py_ssize_t)taillen >= (Py_ssize_t)namelen - 1) - continue; /* Too long */ - strcpy(namebuf, path); - if (strlen(namebuf) != len) - continue; /* v contains '\0' */ - if (len > 0 && namebuf[len-1] != SEP) - namebuf[len++] = SEP; - strcpy(namebuf+len, tail); - Py_BEGIN_ALLOW_THREADS - fd = open(namebuf, open_flags); - Py_END_ALLOW_THREADS - if (0 <= fd) { - return fd; - } - } - return -1; + int i; + int fd = -1; + PyObject *v; + Py_ssize_t _npath; + int npath; + size_t taillen; + PyObject *syspath; + const char* path; + const char* tail; + Py_ssize_t len; + + /* Search tail of filename in sys.path before giving up */ + tail = strrchr(filename, SEP); + if (tail == NULL) + tail = filename; + else + tail++; + taillen = strlen(tail); + + syspath = PySys_GetObject("path"); + if (syspath == NULL || !PyList_Check(syspath)) + return -1; + _npath = PyList_Size(syspath); + npath = Py_SAFE_DOWNCAST(_npath, Py_ssize_t, int); + + for (i = 0; i < npath; i++) { + v = PyList_GetItem(syspath, i); + if (v == NULL) { + PyErr_Clear(); + break; + } + if (!PyUnicode_Check(v)) + continue; + path = _PyUnicode_AsStringAndSize(v, &len); + if (len + 1 + (Py_ssize_t)taillen >= (Py_ssize_t)namelen - 1) + continue; /* Too long */ + strcpy(namebuf, path); + if (strlen(namebuf) != len) + continue; /* v contains '\0' */ + if (len > 0 && namebuf[len-1] != SEP) + namebuf[len++] = SEP; + strcpy(namebuf+len, tail); + Py_BEGIN_ALLOW_THREADS + fd = open(namebuf, open_flags); + Py_END_ALLOW_THREADS + if (0 <= fd) { + return fd; + } + } + return -1; } int _Py_DisplaySourceLine(PyObject *f, const char *filename, int lineno, int indent) { - int err = 0; - int fd; - int i; - char *found_encoding; - char *encoding; - PyObject *fob = NULL; - PyObject *lineobj = NULL; + int err = 0; + int fd; + int i; + char *found_encoding; + char *encoding; + PyObject *fob = NULL; + PyObject *lineobj = NULL; #ifdef O_BINARY - const int open_flags = O_RDONLY | O_BINARY; /* necessary for Windows */ + const int open_flags = O_RDONLY | O_BINARY; /* necessary for Windows */ #else - const int open_flags = O_RDONLY; + const int open_flags = O_RDONLY; #endif - char buf[MAXPATHLEN+1]; - Py_UNICODE *u, *p; - Py_ssize_t len; - - /* open the file */ - if (filename == NULL) - return 0; - Py_BEGIN_ALLOW_THREADS - fd = open(filename, open_flags); - Py_END_ALLOW_THREADS - if (fd < 0) { - fd = _Py_FindSourceFile(filename, buf, sizeof(buf), open_flags); - if (fd < 0) - return 0; - filename = buf; - } - - /* use the right encoding to decode the file as unicode */ - found_encoding = PyTokenizer_FindEncoding(fd); - encoding = (found_encoding != NULL) ? found_encoding : - (char*)PyUnicode_GetDefaultEncoding(); - lseek(fd, 0, 0); /* Reset position */ - fob = PyFile_FromFd(fd, (char*)filename, "r", -1, (char*)encoding, - NULL, NULL, 1); - PyMem_FREE(found_encoding); - if (fob == NULL) { - PyErr_Clear(); - close(fd); - return 0; - } - - /* get the line number lineno */ - for (i = 0; i < lineno; i++) { - Py_XDECREF(lineobj); - lineobj = PyFile_GetLine(fob, -1); - if (!lineobj) { - err = -1; - break; - } - } - Py_DECREF(fob); - if (!lineobj || !PyUnicode_Check(lineobj)) { - Py_XDECREF(lineobj); - return err; - } - - /* remove the indentation of the line */ - u = PyUnicode_AS_UNICODE(lineobj); - len = PyUnicode_GET_SIZE(lineobj); - for (p=u; *p == ' ' || *p == '\t' || *p == '\014'; p++) - len--; - if (u != p) { - PyObject *truncated; - truncated = PyUnicode_FromUnicode(p, len); - if (truncated) { - Py_DECREF(lineobj); - lineobj = truncated; - } else { - PyErr_Clear(); - } - } - - /* Write some spaces before the line */ - strcpy(buf, " "); - assert (strlen(buf) == 10); - while (indent > 0) { - if(indent < 10) - buf[indent] = '\0'; - err = PyFile_WriteString(buf, f); - if (err != 0) - break; - indent -= 10; - } - - /* finally display the line */ - if (err == 0) - err = PyFile_WriteObject(lineobj, f, Py_PRINT_RAW); - Py_DECREF(lineobj); - if (err == 0) - err = PyFile_WriteString("\n", f); - return err; + char buf[MAXPATHLEN+1]; + Py_UNICODE *u, *p; + Py_ssize_t len; + + /* open the file */ + if (filename == NULL) + return 0; + Py_BEGIN_ALLOW_THREADS + fd = open(filename, open_flags); + Py_END_ALLOW_THREADS + if (fd < 0) { + fd = _Py_FindSourceFile(filename, buf, sizeof(buf), open_flags); + if (fd < 0) + return 0; + filename = buf; + } + + /* use the right encoding to decode the file as unicode */ + found_encoding = PyTokenizer_FindEncoding(fd); + encoding = (found_encoding != NULL) ? found_encoding : + (char*)PyUnicode_GetDefaultEncoding(); + lseek(fd, 0, 0); /* Reset position */ + fob = PyFile_FromFd(fd, (char*)filename, "r", -1, (char*)encoding, + NULL, NULL, 1); + PyMem_FREE(found_encoding); + if (fob == NULL) { + PyErr_Clear(); + close(fd); + return 0; + } + + /* get the line number lineno */ + for (i = 0; i < lineno; i++) { + Py_XDECREF(lineobj); + lineobj = PyFile_GetLine(fob, -1); + if (!lineobj) { + err = -1; + break; + } + } + Py_DECREF(fob); + if (!lineobj || !PyUnicode_Check(lineobj)) { + Py_XDECREF(lineobj); + return err; + } + + /* remove the indentation of the line */ + u = PyUnicode_AS_UNICODE(lineobj); + len = PyUnicode_GET_SIZE(lineobj); + for (p=u; *p == ' ' || *p == '\t' || *p == '\014'; p++) + len--; + if (u != p) { + PyObject *truncated; + truncated = PyUnicode_FromUnicode(p, len); + if (truncated) { + Py_DECREF(lineobj); + lineobj = truncated; + } else { + PyErr_Clear(); + } + } + + /* Write some spaces before the line */ + strcpy(buf, " "); + assert (strlen(buf) == 10); + while (indent > 0) { + if(indent < 10) + buf[indent] = '\0'; + err = PyFile_WriteString(buf, f); + if (err != 0) + break; + indent -= 10; + } + + /* finally display the line */ + if (err == 0) + err = PyFile_WriteObject(lineobj, f, Py_PRINT_RAW); + Py_DECREF(lineobj); + if (err == 0) + err = PyFile_WriteString("\n", f); + return err; } static int tb_displayline(PyObject *f, const char *filename, int lineno, const char *name) { - int err = 0; - char linebuf[2000]; + int err = 0; + char linebuf[2000]; - if (filename == NULL || name == NULL) - return -1; - /* This is needed by Emacs' compile command */ + if (filename == NULL || name == NULL) + return -1; + /* This is needed by Emacs' compile command */ #define FMT " File \"%.500s\", line %d, in %.500s\n" - PyOS_snprintf(linebuf, sizeof(linebuf), FMT, filename, lineno, name); - err = PyFile_WriteString(linebuf, f); - if (err != 0) - return err; - return _Py_DisplaySourceLine(f, filename, lineno, 4); + PyOS_snprintf(linebuf, sizeof(linebuf), FMT, filename, lineno, name); + err = PyFile_WriteString(linebuf, f); + if (err != 0) + return err; + return _Py_DisplaySourceLine(f, filename, lineno, 4); } static int tb_printinternal(PyTracebackObject *tb, PyObject *f, long limit) { - int err = 0; - long depth = 0; - PyTracebackObject *tb1 = tb; - while (tb1 != NULL) { - depth++; - tb1 = tb1->tb_next; - } - while (tb != NULL && err == 0) { - if (depth <= limit) { - err = tb_displayline(f, - _PyUnicode_AsString( - tb->tb_frame->f_code->co_filename), - tb->tb_lineno, - _PyUnicode_AsString(tb->tb_frame->f_code->co_name)); - } - depth--; - tb = tb->tb_next; - if (err == 0) - err = PyErr_CheckSignals(); - } - return err; + int err = 0; + long depth = 0; + PyTracebackObject *tb1 = tb; + while (tb1 != NULL) { + depth++; + tb1 = tb1->tb_next; + } + while (tb != NULL && err == 0) { + if (depth <= limit) { + err = tb_displayline(f, + _PyUnicode_AsString( + tb->tb_frame->f_code->co_filename), + tb->tb_lineno, + _PyUnicode_AsString(tb->tb_frame->f_code->co_name)); + } + depth--; + tb = tb->tb_next; + if (err == 0) + err = PyErr_CheckSignals(); + } + return err; } #define PyTraceBack_LIMIT 1000 @@ -335,40 +335,40 @@ int PyTraceBack_Print(PyObject *v, PyObject *f) { - int err; - PyObject *limitv; - long limit = PyTraceBack_LIMIT; - - if (v == NULL) - return 0; - if (!PyTraceBack_Check(v)) { - PyErr_BadInternalCall(); - return -1; - } - limitv = PySys_GetObject("tracebacklimit"); - if (limitv) { - PyObject *exc_type, *exc_value, *exc_tb; - - PyErr_Fetch(&exc_type, &exc_value, &exc_tb); - limit = PyLong_AsLong(limitv); - if (limit == -1 && PyErr_Occurred()) { - if (PyErr_ExceptionMatches(PyExc_OverflowError)) { - limit = PyTraceBack_LIMIT; - } - else { - Py_XDECREF(exc_type); - Py_XDECREF(exc_value); - Py_XDECREF(exc_tb); - return 0; - } - } - else if (limit <= 0) { - limit = PyTraceBack_LIMIT; - } - PyErr_Restore(exc_type, exc_value, exc_tb); - } - err = PyFile_WriteString("Traceback (most recent call last):\n", f); - if (!err) - err = tb_printinternal((PyTracebackObject *)v, f, limit); - return err; + int err; + PyObject *limitv; + long limit = PyTraceBack_LIMIT; + + if (v == NULL) + return 0; + if (!PyTraceBack_Check(v)) { + PyErr_BadInternalCall(); + return -1; + } + limitv = PySys_GetObject("tracebacklimit"); + if (limitv) { + PyObject *exc_type, *exc_value, *exc_tb; + + PyErr_Fetch(&exc_type, &exc_value, &exc_tb); + limit = PyLong_AsLong(limitv); + if (limit == -1 && PyErr_Occurred()) { + if (PyErr_ExceptionMatches(PyExc_OverflowError)) { + limit = PyTraceBack_LIMIT; + } + else { + Py_XDECREF(exc_type); + Py_XDECREF(exc_value); + Py_XDECREF(exc_tb); + return 0; + } + } + else if (limit <= 0) { + limit = PyTraceBack_LIMIT; + } + PyErr_Restore(exc_type, exc_value, exc_tb); + } + err = PyFile_WriteString("Traceback (most recent call last):\n", f); + if (!err) + err = tb_printinternal((PyTracebackObject *)v, f, limit); + return err; } Modified: python/branches/release31-maint/Tools/msi/msisupport.c ============================================================================== --- python/branches/release31-maint/Tools/msi/msisupport.c (original) +++ python/branches/release31-maint/Tools/msi/msisupport.c Sun May 9 18:14:21 2010 @@ -7,13 +7,13 @@ */ static UINT debug(MSIHANDLE hInstall, LPCSTR msg) { - MSIHANDLE hRec = MsiCreateRecord(1); - if (!hRec || MsiRecordSetStringA(hRec, 1, msg) != ERROR_SUCCESS) { - return ERROR_INSTALL_FAILURE; - } - MsiProcessMessage(hInstall, INSTALLMESSAGE_INFO, hRec); - MsiCloseHandle(hRec); - return ERROR_SUCCESS; + MSIHANDLE hRec = MsiCreateRecord(1); + if (!hRec || MsiRecordSetStringA(hRec, 1, msg) != ERROR_SUCCESS) { + return ERROR_INSTALL_FAILURE; + } + MsiProcessMessage(hInstall, INSTALLMESSAGE_INFO, hRec); + MsiCloseHandle(hRec); + return ERROR_SUCCESS; } /* Check whether the TARGETDIR exists and is a directory. @@ -22,27 +22,27 @@ UINT __declspec(dllexport) __stdcall CheckDir(MSIHANDLE hInstall) { #define PSIZE 1024 - WCHAR wpath[PSIZE]; - char path[PSIZE]; - UINT result; - DWORD size = PSIZE; - DWORD attributes; - - - result = MsiGetPropertyW(hInstall, L"TARGETDIR", wpath, &size); - if (result != ERROR_SUCCESS) - return result; - wpath[size] = L'\0'; - path[size] = L'\0'; - - attributes = GetFileAttributesW(wpath); - if (attributes == INVALID_FILE_ATTRIBUTES || - !(attributes & FILE_ATTRIBUTE_DIRECTORY)) - { - return MsiSetPropertyA(hInstall, "TargetExists", "0"); - } else { - return MsiSetPropertyA(hInstall, "TargetExists", "1"); - } + WCHAR wpath[PSIZE]; + char path[PSIZE]; + UINT result; + DWORD size = PSIZE; + DWORD attributes; + + + result = MsiGetPropertyW(hInstall, L"TARGETDIR", wpath, &size); + if (result != ERROR_SUCCESS) + return result; + wpath[size] = L'\0'; + path[size] = L'\0'; + + attributes = GetFileAttributesW(wpath); + if (attributes == INVALID_FILE_ATTRIBUTES || + !(attributes & FILE_ATTRIBUTE_DIRECTORY)) + { + return MsiSetPropertyA(hInstall, "TargetExists", "0"); + } else { + return MsiSetPropertyA(hInstall, "TargetExists", "1"); + } } /* Update the state of the REGISTRY.tcl component according to the @@ -51,41 +51,41 @@ */ UINT __declspec(dllexport) __stdcall UpdateEditIDLE(MSIHANDLE hInstall) { - INSTALLSTATE ext_old, ext_new, tcl_old, tcl_new, reg_new; - UINT result; + INSTALLSTATE ext_old, ext_new, tcl_old, tcl_new, reg_new; + UINT result; - result = MsiGetFeatureStateA(hInstall, "Extensions", &ext_old, &ext_new); - if (result != ERROR_SUCCESS) - return result; - result = MsiGetFeatureStateA(hInstall, "TclTk", &tcl_old, &tcl_new); - if (result != ERROR_SUCCESS) - return result; - - /* If the current state is Absent, and the user did not select - the feature in the UI, Installer apparently sets the "selected" - state to unknown. Update it to the current value, then. */ - if (ext_new == INSTALLSTATE_UNKNOWN) - ext_new = ext_old; - if (tcl_new == INSTALLSTATE_UNKNOWN) - tcl_new = tcl_old; - - // XXX consider current state of REGISTRY.tcl? - if (((tcl_new == INSTALLSTATE_LOCAL) || - (tcl_new == INSTALLSTATE_SOURCE) || - (tcl_new == INSTALLSTATE_DEFAULT)) && - ((ext_new == INSTALLSTATE_LOCAL) || - (ext_new == INSTALLSTATE_SOURCE) || - (ext_new == INSTALLSTATE_DEFAULT))) { - reg_new = INSTALLSTATE_SOURCE; - } else { - reg_new = INSTALLSTATE_ABSENT; - } - result = MsiSetComponentStateA(hInstall, "REGISTRY.tcl", reg_new); - return result; + result = MsiGetFeatureStateA(hInstall, "Extensions", &ext_old, &ext_new); + if (result != ERROR_SUCCESS) + return result; + result = MsiGetFeatureStateA(hInstall, "TclTk", &tcl_old, &tcl_new); + if (result != ERROR_SUCCESS) + return result; + + /* If the current state is Absent, and the user did not select + the feature in the UI, Installer apparently sets the "selected" + state to unknown. Update it to the current value, then. */ + if (ext_new == INSTALLSTATE_UNKNOWN) + ext_new = ext_old; + if (tcl_new == INSTALLSTATE_UNKNOWN) + tcl_new = tcl_old; + + // XXX consider current state of REGISTRY.tcl? + if (((tcl_new == INSTALLSTATE_LOCAL) || + (tcl_new == INSTALLSTATE_SOURCE) || + (tcl_new == INSTALLSTATE_DEFAULT)) && + ((ext_new == INSTALLSTATE_LOCAL) || + (ext_new == INSTALLSTATE_SOURCE) || + (ext_new == INSTALLSTATE_DEFAULT))) { + reg_new = INSTALLSTATE_SOURCE; + } else { + reg_new = INSTALLSTATE_ABSENT; + } + result = MsiSetComponentStateA(hInstall, "REGISTRY.tcl", reg_new); + return result; } -BOOL APIENTRY DllMain(HANDLE hModule, - DWORD ul_reason_for_call, +BOOL APIENTRY DllMain(HANDLE hModule, + DWORD ul_reason_for_call, LPVOID lpReserved) { return TRUE; From python-checkins at python.org Sun May 9 20:28:43 2010 From: python-checkins at python.org (antoine.pitrou) Date: Sun, 9 May 2010 20:28:43 +0200 (CEST) Subject: [Python-checkins] r81034 - peps/trunk/pep-0007.txt Message-ID: <20100509182843.8B0C9EE9E3@mail.python.org> Author: antoine.pitrou Date: Sun May 9 20:28:43 2010 New Revision: 81034 Log: Update PEP 7. All C files should now use 4-space indents. Modified: peps/trunk/pep-0007.txt Modified: peps/trunk/pep-0007.txt ============================================================================== --- peps/trunk/pep-0007.txt (original) +++ peps/trunk/pep-0007.txt Sun May 9 20:28:43 2010 @@ -46,13 +46,7 @@ Code lay-out - - Use single-tab indents, where a tab is worth 8 spaces, in files - that already use tabs. In new source files, and the few files - that were created after this rule was introduced, use 4-space - indents and no tabs at all. - - At some point, the whole codebase may be converted to use only - 4-space indents. + - Use 4-space indents and no tabs at all. - No line should be longer than 79 characters. If this and the previous rule together don't give you enough room to code, your From python-checkins at python.org Sun May 9 20:32:48 2010 From: python-checkins at python.org (antoine.pitrou) Date: Sun, 9 May 2010 20:32:48 +0200 (CEST) Subject: [Python-checkins] r81035 - python/trunk/Misc/NEWS Message-ID: <20100509183248.36ABBEE995@mail.python.org> Author: antoine.pitrou Date: Sun May 9 20:32:48 2010 New Revision: 81035 Log: Remove spurious newlines, and add version number. Modified: python/trunk/Misc/NEWS Modified: python/trunk/Misc/NEWS ============================================================================== --- python/trunk/Misc/NEWS (original) +++ python/trunk/Misc/NEWS Sun May 9 20:32:48 2010 @@ -4,8 +4,8 @@ (editors: check NEWS.help for information about editing NEWS using ReST.) -What's New in Python Release Candidate 1? -========================================= +What's New in Python 2.7 Release Candidate 1? +============================================= *Release date: XXXX-XX-XX* @@ -54,8 +54,6 @@ builds on MacOS X. That is, "python setup.py install --user" will install into "~/Library/Python/2.7" instead of "~/.local". - - Library ------- From python-checkins at python.org Sun May 9 22:30:29 2010 From: python-checkins at python.org (mark.dickinson) Date: Sun, 9 May 2010 22:30:29 +0200 (CEST) Subject: [Python-checkins] r81036 - python/trunk/Objects/longobject.c Message-ID: <20100509203029.5C430EE995@mail.python.org> Author: mark.dickinson Date: Sun May 9 22:30:29 2010 New Revision: 81036 Log: Post-detabification cleanup: whitespace fixes and long line rewraps only. Modified: python/trunk/Objects/longobject.c Modified: python/trunk/Objects/longobject.c ============================================================================== --- python/trunk/Objects/longobject.c (original) +++ python/trunk/Objects/longobject.c Sun May 9 22:30:29 2010 @@ -1,5 +1,3 @@ - - /* Long (arbitrary precision) integer object implementation */ /* XXX The functional organization of this file is terrible */ @@ -177,12 +175,12 @@ neg = 0; if (Py_IS_INFINITY(dval)) { PyErr_SetString(PyExc_OverflowError, - "cannot convert float infinity to integer"); + "cannot convert float infinity to integer"); return NULL; } if (Py_IS_NAN(dval)) { PyErr_SetString(PyExc_ValueError, - "cannot convert float NaN to integer"); + "cannot convert float NaN to integer"); return NULL; } if (dval < 0.0) { @@ -315,7 +313,7 @@ /* res is already set to -1 */ } } - exit: + exit: if (do_decref) { Py_DECREF(vv); } @@ -378,7 +376,7 @@ } /* else overflow */ - overflow: + overflow: PyErr_SetString(PyExc_OverflowError, "long int too large to convert to int"); return -1; @@ -399,7 +397,8 @@ long val = PyInt_AsLong(vv); if (val < 0) { PyErr_SetString(PyExc_OverflowError, - "can't convert negative value to unsigned long"); + "can't convert negative value " + "to unsigned long"); return (unsigned long) -1; } return val; @@ -412,7 +411,7 @@ x = 0; if (i < 0) { PyErr_SetString(PyExc_OverflowError, - "can't convert negative value to unsigned long"); + "can't convert negative value to unsigned long"); return (unsigned long) -1; } while (--i >= 0) { @@ -420,7 +419,7 @@ x = (x << PyLong_SHIFT) | v->ob_digit[i]; if ((x >> PyLong_SHIFT) != prev) { PyErr_SetString(PyExc_OverflowError, - "long int too large to convert"); + "long int too large to convert"); return (unsigned long) -1; } } @@ -495,7 +494,7 @@ } return result; -Overflow: + Overflow: PyErr_SetString(PyExc_OverflowError, "long has too many bits " "to express in a platform size_t"); return (size_t)-1; @@ -505,7 +504,7 @@ _PyLong_FromByteArray(const unsigned char* bytes, size_t n, int little_endian, int is_signed) { - const unsigned char* pstartbyte;/* LSB of bytes */ + const unsigned char* pstartbyte; /* LSB of bytes */ int incr; /* direction to move pstartbyte */ const unsigned char* pendbyte; /* MSB of bytes */ size_t numsignificantbytes; /* number of bytes that matter */ @@ -593,8 +592,7 @@ if (accumbits >= PyLong_SHIFT) { /* There's enough to fill a Python digit. */ assert(idigit < ndigits); - v->ob_digit[idigit] = (digit)(accum & - PyLong_MASK); + v->ob_digit[idigit] = (digit)(accum & PyLong_MASK); ++idigit; accum >>= PyLong_SHIFT; accumbits -= PyLong_SHIFT; @@ -619,9 +617,9 @@ int little_endian, int is_signed) { Py_ssize_t i; /* index into v->ob_digit */ - Py_ssize_t ndigits; /* |v->ob_size| */ + Py_ssize_t ndigits; /* |v->ob_size| */ twodigits accum; /* sliding register */ - unsigned int accumbits; /* # bits in accum */ + unsigned int accumbits; /* # bits in accum */ int do_twos_comp; /* store 2's-comp? is_signed and v < 0 */ digit carry; /* for computing 2's-comp */ size_t j; /* # bytes filled */ @@ -634,7 +632,7 @@ ndigits = -(Py_SIZE(v)); if (!is_signed) { PyErr_SetString(PyExc_OverflowError, - "can't convert negative long to unsigned"); + "can't convert negative long to unsigned"); return -1; } do_twos_comp = 1; @@ -680,8 +678,7 @@ /* Count # of sign bits -- they needn't be stored, * although for signed conversion we need later to * make sure at least one sign bit gets stored. */ - digit s = do_twos_comp ? thisdigit ^ PyLong_MASK : - thisdigit; + digit s = do_twos_comp ? thisdigit ^ PyLong_MASK : thisdigit; while (s != 0) { s >>= 1; accumbits++; @@ -741,7 +738,7 @@ return 0; -Overflow: + Overflow: PyErr_SetString(PyExc_OverflowError, "long too big to convert"); return -1; @@ -821,7 +818,7 @@ */ #define IS_LITTLE_ENDIAN (int)*(unsigned char*)&one -#define PY_ABS_LLONG_MIN (0-(unsigned PY_LONG_LONG)PY_LLONG_MIN) +#define PY_ABS_LLONG_MIN (0-(unsigned PY_LONG_LONG)PY_LLONG_MIN) /* Create a new long int object from a C PY_LONG_LONG int. */ @@ -900,9 +897,8 @@ { Py_ssize_t bytes = ival; int one = 1; - return _PyLong_FromByteArray( - (unsigned char *)&bytes, - SIZEOF_SIZE_T, IS_LITTLE_ENDIAN, 1); + return _PyLong_FromByteArray((unsigned char *)&bytes, + SIZEOF_SIZE_T, IS_LITTLE_ENDIAN, 1); } /* Create a new long int object from a C size_t. */ @@ -912,9 +908,8 @@ { size_t bytes = ival; int one = 1; - return _PyLong_FromByteArray( - (unsigned char *)&bytes, - SIZEOF_SIZE_T, IS_LITTLE_ENDIAN, 0); + return _PyLong_FromByteArray((unsigned char *)&bytes, + SIZEOF_SIZE_T, IS_LITTLE_ENDIAN, 0); } /* Get a C PY_LONG_LONG int from a long int object. @@ -959,9 +954,8 @@ return -1; } - res = _PyLong_AsByteArray( - (PyLongObject *)vv, (unsigned char *)&bytes, - SIZEOF_LONG_LONG, IS_LITTLE_ENDIAN, 1); + res = _PyLong_AsByteArray((PyLongObject *)vv, (unsigned char *)&bytes, + SIZEOF_LONG_LONG, IS_LITTLE_ENDIAN, 1); /* Plan 9 can't handle PY_LONG_LONG in ? : expressions */ if (res < 0) @@ -985,9 +979,8 @@ return (unsigned PY_LONG_LONG)-1; } - res = _PyLong_AsByteArray( - (PyLongObject *)vv, (unsigned char *)&bytes, - SIZEOF_LONG_LONG, IS_LITTLE_ENDIAN, 0); + res = _PyLong_AsByteArray((PyLongObject *)vv, (unsigned char *)&bytes, + SIZEOF_LONG_LONG, IS_LITTLE_ENDIAN, 0); /* Plan 9 can't handle PY_LONG_LONG in ? : expressions */ if (res < 0) @@ -1120,7 +1113,7 @@ /* res is already set to -1 */ } } - exit: + exit: if (do_decref) { Py_DECREF(vv); } @@ -1376,9 +1369,9 @@ } /* check for keyboard interrupt */ SIGCHECK({ - Py_DECREF(scratch); - return NULL; - }) + Py_DECREF(scratch); + return NULL; + }) } /* pout should have at least one digit, so that the case when a = 0 works correctly */ @@ -1506,8 +1499,7 @@ *--p = cdigit; accumbits -= basebits; accum >>= basebits; - } while (i < size_a-1 ? accumbits >= basebits : - accum > 0); + } while (i < size_a-1 ? accumbits >= basebits : accum > 0); } } else { @@ -1540,15 +1532,15 @@ do { int ntostore = power; digit rem = inplace_divrem1(scratch->ob_digit, - pin, size, powbase); + pin, size, powbase); pin = scratch->ob_digit; /* no need to use a again */ if (pin[size - 1] == 0) --size; SIGCHECK({ - Py_DECREF(scratch); - Py_DECREF(str); - return NULL; - }) + Py_DECREF(scratch); + Py_DECREF(str); + return NULL; + }) /* Break rem into digits. */ assert(ntostore > 0); @@ -1762,14 +1754,15 @@ PyLong_BASE**n >= B**N [taking logs to base PyLong_BASE] n >= log(B**N)/log(PyLong_BASE) = N * log(B)/log(PyLong_BASE) -The static array log_base_PyLong_BASE[base] == log(base)/log(PyLong_BASE) so we can compute -this quickly. A Python long with that much space is reserved near the start, -and the result is computed into it. +The static array log_base_PyLong_BASE[base] == log(base)/log(PyLong_BASE) so +we can compute this quickly. A Python long with that much space is reserved +near the start, and the result is computed into it. The input string is actually treated as being in base base**i (i.e., i digits are processed at a time), where two more static arrays hold: - convwidth_base[base] = the largest integer i such that base**i <= PyLong_BASE + convwidth_base[base] = the largest integer i such that + base**i <= PyLong_BASE convmultmax_base[base] = base ** convwidth_base[base] The first of these is the largest i such that i consecutive input digits @@ -1793,33 +1786,34 @@ size_z = (Py_ssize_t)((scan - str) * log_base_PyLong_BASE[base]) + 1; below. Two numeric concerns are how much space this can waste, and whether -the computed result can be too small. To be concrete, assume PyLong_BASE = 2**15, -which is the default (and it's unlikely anyone changes that). +the computed result can be too small. To be concrete, assume PyLong_BASE = +2**15, which is the default (and it's unlikely anyone changes that). -Waste isn't a problem: provided the first input digit isn't 0, the difference +Waste isn't a problem: provided the first input digit isn't 0, the difference between the worst-case input with N digits and the smallest input with N -digits is about a factor of B, but B is small compared to PyLong_BASE so at most -one allocated Python digit can remain unused on that count. If -N*log(B)/log(PyLong_BASE) is mathematically an exact integer, then truncating that -and adding 1 returns a result 1 larger than necessary. However, that can't -happen: whenever B is a power of 2, long_from_binary_base() is called -instead, and it's impossible for B**i to be an integer power of 2**15 when -B is not a power of 2 (i.e., it's impossible for N*log(B)/log(PyLong_BASE) to be +digits is about a factor of B, but B is small compared to PyLong_BASE so at +most one allocated Python digit can remain unused on that count. If +N*log(B)/log(PyLong_BASE) is mathematically an exact integer, then truncating +that and adding 1 returns a result 1 larger than necessary. However, that +can't happen: whenever B is a power of 2, long_from_binary_base() is called +instead, and it's impossible for B**i to be an integer power of 2**15 when B +is not a power of 2 (i.e., it's impossible for N*log(B)/log(PyLong_BASE) to be an exact integer when B is not a power of 2, since B**i has a prime factor other than 2 in that case, but (2**15)**j's only prime factor is 2). -The computed result can be too small if the true value of N*log(B)/log(PyLong_BASE) -is a little bit larger than an exact integer, but due to roundoff errors (in -computing log(B), log(PyLong_BASE), their quotient, and/or multiplying that by N) -yields a numeric result a little less than that integer. Unfortunately, "how -close can a transcendental function get to an integer over some range?" -questions are generally theoretically intractable. Computer analysis via -continued fractions is practical: expand log(B)/log(PyLong_BASE) via continued -fractions, giving a sequence i/j of "the best" rational approximations. Then -j*log(B)/log(PyLong_BASE) is approximately equal to (the integer) i. This shows that -we can get very close to being in trouble, but very rarely. For example, -76573 is a denominator in one of the continued-fraction approximations to -log(10)/log(2**15), and indeed: +The computed result can be too small if the true value of +N*log(B)/log(PyLong_BASE) is a little bit larger than an exact integer, but +due to roundoff errors (in computing log(B), log(PyLong_BASE), their quotient, +and/or multiplying that by N) yields a numeric result a little less than that +integer. Unfortunately, "how close can a transcendental function get to an +integer over some range?" questions are generally theoretically intractable. +Computer analysis via continued fractions is practical: expand +log(B)/log(PyLong_BASE) via continued fractions, giving a sequence i/j of "the +best" rational approximations. Then j*log(B)/log(PyLong_BASE) is +approximately equal to (the integer) i. This shows that we can get very close +to being in trouble, but very rarely. For example, 76573 is a denominator in +one of the continued-fraction approximations to log(10)/log(2**15), and +indeed: >>> log(10)/log(2**15)*76573 16958.000000654003 @@ -1850,8 +1844,8 @@ twodigits convmax = base; int i = 1; - log_base_PyLong_BASE[base] = log((double)base) / - log((double)PyLong_BASE); + log_base_PyLong_BASE[base] = (log((double)base) / + log((double)PyLong_BASE)); for (;;) { twodigits next = convmax * base; if (next > PyLong_BASE) @@ -1895,7 +1889,7 @@ c = (digit)_PyLong_DigitValue[Py_CHARMASK(*str++)]; for (i = 1; i < convwidth && str != scan; ++i, ++str) { c = (twodigits)(c * base + - _PyLong_DigitValue[Py_CHARMASK(*str)]); + _PyLong_DigitValue[Py_CHARMASK(*str)]); assert(c < PyLong_BASE); } @@ -1960,7 +1954,7 @@ *pend = str; return (PyObject *) z; - onError: + onError: Py_XDECREF(z); slen = strlen(orig_str) < 200 ? strlen(orig_str) : 200; strobj = PyString_FromStringAndSize(orig_str, slen); @@ -2122,12 +2116,12 @@ single-digit quotient q, remainder in vk[0:size_w]. */ SIGCHECK({ - Py_DECREF(a); - Py_DECREF(w); - Py_DECREF(v); - *prem = NULL; - return NULL; - }) + Py_DECREF(a); + Py_DECREF(w); + Py_DECREF(v); + *prem = NULL; + return NULL; + }) /* estimate quotient digit q; may overestimate by 1 (rare) */ vtop = vk[size_w]; @@ -2153,7 +2147,7 @@ (stwodigits)q * (stwodigits)w0[i]; vk[i] = (digit)z & PyLong_MASK; zhi = (sdigit)Py_ARITHMETIC_RIGHT_SHIFT(stwodigits, - z, PyLong_SHIFT); + z, PyLong_SHIFT); } /* add w back if q was too large (this branch taken rarely) */ @@ -2220,7 +2214,7 @@ if (a_size >= (PY_SSIZE_T_MAX - 1) / PyLong_SHIFT + 1 && (a_size > (PY_SSIZE_T_MAX - 1) / PyLong_SHIFT + 1 || a_bits > (PY_SSIZE_T_MAX - 1) % PyLong_SHIFT + 1)) - goto overflow; + goto overflow; a_bits = (a_size - 1) * PyLong_SHIFT + a_bits; /* Shift the first DBL_MANT_DIG + 2 bits of a into x_digits[0:x_size] @@ -2278,7 +2272,8 @@ break; } } - assert(1 <= x_size && x_size <= (Py_ssize_t)(sizeof(x_digits)/sizeof(digit))); + assert(1 <= x_size && + x_size <= (Py_ssize_t)(sizeof(x_digits)/sizeof(digit))); /* Round, and convert to double. */ x_digits[0] += half_even_correction[x_digits[0] & 7]; @@ -2422,8 +2417,8 @@ if (size_a < size_b) { { PyLongObject *temp = a; a = b; b = temp; } { Py_ssize_t size_temp = size_a; - size_a = size_b; - size_b = size_temp; } + size_a = size_b; + size_b = size_temp; } } z = _PyLong_New(size_a+1); if (z == NULL) @@ -2458,8 +2453,8 @@ sign = -1; { PyLongObject *temp = a; a = b; b = temp; } { Py_ssize_t size_temp = size_a; - size_a = size_b; - size_b = size_temp; } + size_a = size_b; + size_b = size_temp; } } else if (size_a == size_b) { /* Find highest digit where a and b differ: */ @@ -2581,9 +2576,9 @@ digit *paend = a->ob_digit + size_a; SIGCHECK({ - Py_DECREF(z); - return NULL; - }) + Py_DECREF(z); + return NULL; + }) carry = *pz + f * f; *pz++ = (digit)(carry & PyLong_MASK); @@ -2619,9 +2614,9 @@ digit *pbend = b->ob_digit + size_b; SIGCHECK({ - Py_DECREF(z); - return NULL; - }) + Py_DECREF(z); + return NULL; + }) while (pb < pbend) { carry += *pz + *pb++ * f; @@ -2645,7 +2640,10 @@ Returns 0 on success, -1 on failure. */ static int -kmul_split(PyLongObject *n, Py_ssize_t size, PyLongObject **high, PyLongObject **low) +kmul_split(PyLongObject *n, + Py_ssize_t size, + PyLongObject **high, + PyLongObject **low) { PyLongObject *hi, *lo; Py_ssize_t size_lo, size_hi; @@ -2834,7 +2832,7 @@ return long_normalize(ret); - fail: + fail: Py_XDECREF(ret); Py_XDECREF(ah); Py_XDECREF(al); @@ -2944,7 +2942,7 @@ Py_DECREF(bslice); return long_normalize(ret); - fail: + fail: Py_DECREF(ret); Py_XDECREF(bslice); return NULL; @@ -3232,7 +3230,7 @@ here. Both a and b would have to be enormous, using close to SIZE_T_MAX bytes of memory each. */ PyErr_SetString(PyExc_OverflowError, - "intermediate overflow during division"); + "intermediate overflow during division"); goto error; } x = _PyLong_New(a_size + shift_digits + 1); @@ -3411,7 +3409,7 @@ if (Py_SIZE(b) < 0) { /* if exponent is negative */ if (c) { PyErr_SetString(PyExc_TypeError, "pow() 2nd argument " - "cannot be negative when 3rd argument specified"); + "cannot be negative when 3rd argument specified"); goto Error; } else { @@ -3541,13 +3539,13 @@ } goto Done; - Error: + Error: if (z != NULL) { Py_DECREF(z); z = NULL; } /* fall through */ - Done: + Done: if (Py_SIZE(b) > FIVEARY_CUTOFF) { for (i = 0; i < 32; ++i) Py_XDECREF(table[i]); @@ -3658,12 +3656,11 @@ for (i = 0, j = wordshift; i < newsize; i++, j++) { z->ob_digit[i] = (a->ob_digit[j] >> loshift) & lomask; if (i+1 < newsize) - z->ob_digit[i] |= - (a->ob_digit[j+1] << hishift) & himask; + z->ob_digit[i] |= (a->ob_digit[j+1] << hishift) & himask; } z = long_normalize(z); } -rshift_error: + rshift_error: Py_DECREF(a); Py_DECREF(b); return (PyObject *) z; @@ -3714,7 +3711,7 @@ else assert(!accum); z = long_normalize(z); -lshift_error: + lshift_error: Py_DECREF(a); Py_DECREF(b); return (PyObject *) z; @@ -3742,7 +3739,7 @@ static PyObject * long_bitwise(PyLongObject *a, int op, /* '&', '|', '^' */ - PyLongObject *b) + PyLongObject *b) { int nega, negb, negz; Py_ssize_t size_a, size_b, size_z, i; @@ -3933,13 +3930,13 @@ x = PyLong_AsLong(v); if (PyErr_Occurred()) { if (PyErr_ExceptionMatches(PyExc_OverflowError)) { - PyErr_Clear(); - if (PyLong_CheckExact(v)) { - Py_INCREF(v); - return v; - } - else - return _PyLong_Copy((PyLongObject *)v); + PyErr_Clear(); + if (PyLong_CheckExact(v)) { + Py_INCREF(v); + return v; + } + else + return _PyLong_Copy((PyLongObject *)v); } else return NULL; @@ -4000,8 +3997,8 @@ if (srepr == NULL) return NULL; PyErr_Format(PyExc_ValueError, - "invalid literal for long() with base %d: %s", - base, PyString_AS_STRING(srepr)); + "invalid literal for long() with base %d: %s", + base, PyString_AS_STRING(srepr)); Py_DECREF(srepr); return NULL; } @@ -4015,7 +4012,7 @@ #endif else { PyErr_SetString(PyExc_TypeError, - "long() can't convert non-string with explicit base"); + "long() can't convert non-string with explicit base"); return NULL; } } @@ -4157,7 +4154,7 @@ return (PyObject *)result; -error: + error: Py_DECREF(result); return NULL; } @@ -4227,45 +4224,45 @@ converting a non-string."); static PyNumberMethods long_as_number = { - (binaryfunc) long_add, /*nb_add*/ - (binaryfunc) long_sub, /*nb_subtract*/ - (binaryfunc) long_mul, /*nb_multiply*/ - long_classic_div, /*nb_divide*/ - long_mod, /*nb_remainder*/ - long_divmod, /*nb_divmod*/ - long_pow, /*nb_power*/ - (unaryfunc) long_neg, /*nb_negative*/ - (unaryfunc) long_long, /*tp_positive*/ - (unaryfunc) long_abs, /*tp_absolute*/ - (inquiry) long_nonzero, /*tp_nonzero*/ - (unaryfunc) long_invert, /*nb_invert*/ - long_lshift, /*nb_lshift*/ - (binaryfunc) long_rshift, /*nb_rshift*/ - long_and, /*nb_and*/ - long_xor, /*nb_xor*/ - long_or, /*nb_or*/ - long_coerce, /*nb_coerce*/ - long_int, /*nb_int*/ - long_long, /*nb_long*/ - long_float, /*nb_float*/ - long_oct, /*nb_oct*/ - long_hex, /*nb_hex*/ - 0, /* nb_inplace_add */ - 0, /* nb_inplace_subtract */ - 0, /* nb_inplace_multiply */ - 0, /* nb_inplace_divide */ - 0, /* nb_inplace_remainder */ - 0, /* nb_inplace_power */ - 0, /* nb_inplace_lshift */ - 0, /* nb_inplace_rshift */ - 0, /* nb_inplace_and */ - 0, /* nb_inplace_xor */ - 0, /* nb_inplace_or */ - long_div, /* nb_floor_divide */ - long_true_divide, /* nb_true_divide */ - 0, /* nb_inplace_floor_divide */ - 0, /* nb_inplace_true_divide */ - long_long, /* nb_index */ + (binaryfunc)long_add, /*nb_add*/ + (binaryfunc)long_sub, /*nb_subtract*/ + (binaryfunc)long_mul, /*nb_multiply*/ + long_classic_div, /*nb_divide*/ + long_mod, /*nb_remainder*/ + long_divmod, /*nb_divmod*/ + long_pow, /*nb_power*/ + (unaryfunc)long_neg, /*nb_negative*/ + (unaryfunc)long_long, /*tp_positive*/ + (unaryfunc)long_abs, /*tp_absolute*/ + (inquiry)long_nonzero, /*tp_nonzero*/ + (unaryfunc)long_invert, /*nb_invert*/ + long_lshift, /*nb_lshift*/ + (binaryfunc)long_rshift, /*nb_rshift*/ + long_and, /*nb_and*/ + long_xor, /*nb_xor*/ + long_or, /*nb_or*/ + long_coerce, /*nb_coerce*/ + long_int, /*nb_int*/ + long_long, /*nb_long*/ + long_float, /*nb_float*/ + long_oct, /*nb_oct*/ + long_hex, /*nb_hex*/ + 0, /* nb_inplace_add */ + 0, /* nb_inplace_subtract */ + 0, /* nb_inplace_multiply */ + 0, /* nb_inplace_divide */ + 0, /* nb_inplace_remainder */ + 0, /* nb_inplace_power */ + 0, /* nb_inplace_lshift */ + 0, /* nb_inplace_rshift */ + 0, /* nb_inplace_and */ + 0, /* nb_inplace_xor */ + 0, /* nb_inplace_or */ + long_div, /* nb_floor_divide */ + long_true_divide, /* nb_true_divide */ + 0, /* nb_inplace_floor_divide */ + 0, /* nb_inplace_true_divide */ + long_long, /* nb_index */ }; PyTypeObject PyLong_Type = { @@ -4290,7 +4287,7 @@ 0, /* tp_setattro */ 0, /* tp_as_buffer */ Py_TPFLAGS_DEFAULT | Py_TPFLAGS_CHECKTYPES | - Py_TPFLAGS_BASETYPE | Py_TPFLAGS_LONG_SUBCLASS, /* tp_flags */ + Py_TPFLAGS_BASETYPE | Py_TPFLAGS_LONG_SUBCLASS, /* tp_flags */ long_doc, /* tp_doc */ 0, /* tp_traverse */ 0, /* tp_clear */ @@ -4309,7 +4306,7 @@ 0, /* tp_init */ 0, /* tp_alloc */ long_new, /* tp_new */ - PyObject_Del, /* tp_free */ + PyObject_Del, /* tp_free */ }; static PyTypeObject Long_InfoType; @@ -4322,8 +4319,7 @@ static PyStructSequence_Field long_info_fields[] = { {"bits_per_digit", "size of a digit in bits"}, - {"sizeof_digit", "size in bytes of the C type used to " - "represent a digit"}, + {"sizeof_digit", "size in bytes of the C type used to represent a digit"}, {NULL, NULL} }; @@ -4331,7 +4327,7 @@ "sys.long_info", /* name */ long_info__doc__, /* doc */ long_info_fields, /* fields */ - 2 /* number of fields */ + 2 /* number of fields */ }; PyObject * From python-checkins at python.org Sun May 9 22:42:09 2010 From: python-checkins at python.org (mark.dickinson) Date: Sun, 9 May 2010 22:42:09 +0200 (CEST) Subject: [Python-checkins] r81037 - python/trunk/Objects/longobject.c Message-ID: <20100509204209.DF3B2EDF8@mail.python.org> Author: mark.dickinson Date: Sun May 9 22:42:09 2010 New Revision: 81037 Log: Wrap multiline macros in a 'do {} while(0)', for safety. Modified: python/trunk/Objects/longobject.c Modified: python/trunk/Objects/longobject.c ============================================================================== --- python/trunk/Objects/longobject.c (original) +++ python/trunk/Objects/longobject.c Sun May 9 22:42:09 2010 @@ -31,11 +31,13 @@ #define MAX(x, y) ((x) < (y) ? (y) : (x)) #define MIN(x, y) ((x) > (y) ? (y) : (x)) -#define SIGCHECK(PyTryBlock) \ - if (--_Py_Ticker < 0) { \ - _Py_Ticker = _Py_CheckInterval; \ - if (PyErr_CheckSignals()) PyTryBlock \ - } +#define SIGCHECK(PyTryBlock) \ + do { \ + if (--_Py_Ticker < 0) { \ + _Py_Ticker = _Py_CheckInterval; \ + if (PyErr_CheckSignals()) PyTryBlock \ + } \ + } while(0) /* Normalize (remove leading zeros from) a long int object. Doesn't attempt to free the storage--in most cases, due to the nature @@ -1151,11 +1153,13 @@ return 1; } -#define CONVERT_BINOP(v, w, a, b) \ - if (!convert_binop(v, w, a, b)) { \ - Py_INCREF(Py_NotImplemented); \ - return Py_NotImplemented; \ - } +#define CONVERT_BINOP(v, w, a, b) \ + do { \ + if (!convert_binop(v, w, a, b)) { \ + Py_INCREF(Py_NotImplemented); \ + return Py_NotImplemented; \ + } \ + } while(0) \ /* bits_in_digit(d) returns the unique integer k such that 2**(k-1) <= d < 2**k if d is nonzero, else 0. */ @@ -1371,7 +1375,7 @@ SIGCHECK({ Py_DECREF(scratch); return NULL; - }) + }); } /* pout should have at least one digit, so that the case when a = 0 works correctly */ @@ -1540,7 +1544,7 @@ Py_DECREF(scratch); Py_DECREF(str); return NULL; - }) + }); /* Break rem into digits. */ assert(ntostore > 0); @@ -2121,7 +2125,7 @@ Py_DECREF(v); *prem = NULL; return NULL; - }) + }); /* estimate quotient digit q; may overestimate by 1 (rare) */ vtop = vk[size_w]; @@ -2578,7 +2582,7 @@ SIGCHECK({ Py_DECREF(z); return NULL; - }) + }); carry = *pz + f * f; *pz++ = (digit)(carry & PyLong_MASK); @@ -2616,7 +2620,7 @@ SIGCHECK({ Py_DECREF(z); return NULL; - }) + }); while (pb < pbend) { carry += *pz + *pb++ * f; @@ -3475,26 +3479,28 @@ * is NULL. */ #define REDUCE(X) \ - if (c != NULL) { \ - if (l_divmod(X, c, NULL, &temp) < 0) \ - goto Error; \ - Py_XDECREF(X); \ - X = temp; \ - temp = NULL; \ - } + do { \ + if (c != NULL) { \ + if (l_divmod(X, c, NULL, &temp) < 0) \ + goto Error; \ + Py_XDECREF(X); \ + X = temp; \ + temp = NULL; \ + } \ + } while(0) /* Multiply two values, then reduce the result: result = X*Y % c. If c is NULL, skip the mod. */ -#define MULT(X, Y, result) \ -{ \ - temp = (PyLongObject *)long_mul(X, Y); \ - if (temp == NULL) \ - goto Error; \ - Py_XDECREF(result); \ - result = temp; \ - temp = NULL; \ - REDUCE(result) \ -} +#define MULT(X, Y, result) \ + do { \ + temp = (PyLongObject *)long_mul(X, Y); \ + if (temp == NULL) \ + goto Error; \ + Py_XDECREF(result); \ + result = temp; \ + temp = NULL; \ + REDUCE(result); \ + } while(0) if (Py_SIZE(b) <= FIVEARY_CUTOFF) { /* Left-to-right binary exponentiation (HAC Algorithm 14.79) */ @@ -3503,9 +3509,9 @@ digit bi = b->ob_digit[i]; for (j = (digit)1 << (PyLong_SHIFT-1); j != 0; j >>= 1) { - MULT(z, z, z) + MULT(z, z, z); if (bi & j) - MULT(z, a, z) + MULT(z, a, z); } } } @@ -3514,7 +3520,7 @@ Py_INCREF(z); /* still holds 1L */ table[0] = z; for (i = 1; i < 32; ++i) - MULT(table[i-1], a, table[i]) + MULT(table[i-1], a, table[i]); for (i = Py_SIZE(b) - 1; i >= 0; --i) { const digit bi = b->ob_digit[i]; @@ -3522,9 +3528,9 @@ for (j = PyLong_SHIFT - 5; j >= 0; j -= 5) { const int index = (bi >> j) & 0x1f; for (k = 0; k < 5; ++k) - MULT(z, z, z) + MULT(z, z, z); if (index) - MULT(z, table[index], z) + MULT(z, table[index], z); } } } From python-checkins at python.org Sun May 9 23:09:41 2010 From: python-checkins at python.org (benjamin.peterson) Date: Sun, 9 May 2010 23:09:41 +0200 (CEST) Subject: [Python-checkins] r81038 - python/trunk/Doc/whatsnew/2.7.rst Message-ID: <20100509210941.08783EE9C2@mail.python.org> Author: benjamin.peterson Date: Sun May 9 23:09:40 2010 New Revision: 81038 Log: finish clause Modified: python/trunk/Doc/whatsnew/2.7.rst Modified: python/trunk/Doc/whatsnew/2.7.rst ============================================================================== --- python/trunk/Doc/whatsnew/2.7.rst (original) +++ python/trunk/Doc/whatsnew/2.7.rst Sun May 9 23:09:40 2010 @@ -136,7 +136,7 @@ * The syntax for set literals (``{1,2,3}`` is a mutable set). * Dictionary and set comprehensions (``{ i: i*2 for i in range(3)}``). -* Multiple context managers in +* Multiple context managers in a single :stmt:`with` statement. * A new version of the :mod:`io` library, rewritten in C for performance. * The ordered-dictionary type described in :ref:`pep-0372`. * The new format specifier described in :ref:`pep-0378`. From solipsis at pitrou.net Mon May 10 01:22:20 2010 From: solipsis at pitrou.net (solipsis at pitrou.net) Date: Mon, 10 May 2010 01:22:20 +0200 (CEST) Subject: [Python-checkins] Daily py3k reference leaks (r81032): sum=0 Message-ID: <20100509232220.DF7201770A@ns6635.ovh.net> py3k results for svn r81032 (hg cset 450e3e57508b) -------------------------------------------------- Command line was: ['./python', '-m', 'test.regrtest', '-uall', '-R', '3:3:/home/antoine/py3k/refleaks/reflog31ZOgi', '-x'] From python-checkins at python.org Mon May 10 16:18:27 2010 From: python-checkins at python.org (andrew.kuchling) Date: Mon, 10 May 2010 16:18:27 +0200 (CEST) Subject: [Python-checkins] r81039 - python/trunk/Doc/whatsnew/2.7.rst Message-ID: <20100510141827.994D7EDF8@mail.python.org> Author: andrew.kuchling Date: Mon May 10 16:18:27 2010 New Revision: 81039 Log: Markup fix; re-word a sentence Modified: python/trunk/Doc/whatsnew/2.7.rst Modified: python/trunk/Doc/whatsnew/2.7.rst ============================================================================== --- python/trunk/Doc/whatsnew/2.7.rst (original) +++ python/trunk/Doc/whatsnew/2.7.rst Mon May 10 16:18:27 2010 @@ -136,7 +136,7 @@ * The syntax for set literals (``{1,2,3}`` is a mutable set). * Dictionary and set comprehensions (``{ i: i*2 for i in range(3)}``). -* Multiple context managers in a single :stmt:`with` statement. +* Multiple context managers in a single :keyword:`with` statement. * A new version of the :mod:`io` library, rewritten in C for performance. * The ordered-dictionary type described in :ref:`pep-0372`. * The new format specifier described in :ref:`pep-0378`. @@ -146,7 +146,7 @@ results more correctly. And :func:`repr` of a floating-point number *x* returns a result that's guaranteed to round back to the same number when converted back to a string. -* The :ctype:`PyCapsule` type, used to provide a C API for an extension module. +* The :ctype:`PyCapsule` type, used to provide a C API for extension modules. * The :cfunc:`PyLong_AsLongAndOverflow` C API function. One porting change: the :option:`-3` switch now automatically From python-checkins at python.org Mon May 10 16:20:13 2010 From: python-checkins at python.org (andrew.kuchling) Date: Mon, 10 May 2010 16:20:13 +0200 (CEST) Subject: [Python-checkins] r81040 - python/trunk/Doc/whatsnew/2.7.rst Message-ID: <20100510142013.1279CC70A@mail.python.org> Author: andrew.kuchling Date: Mon May 10 16:20:12 2010 New Revision: 81040 Log: Use title case Modified: python/trunk/Doc/whatsnew/2.7.rst Modified: python/trunk/Doc/whatsnew/2.7.rst ============================================================================== --- python/trunk/Doc/whatsnew/2.7.rst (original) +++ python/trunk/Doc/whatsnew/2.7.rst Mon May 10 16:20:12 2010 @@ -164,7 +164,7 @@ .. _pep-0372: -PEP 372: Adding an ordered dictionary to collections +PEP 372: Adding an Ordered Dictionary to collections ==================================================== Regular Python dictionaries iterate over key/value pairs in arbitrary order. From python-checkins at python.org Mon May 10 16:53:29 2010 From: python-checkins at python.org (giampaolo.rodola) Date: Mon, 10 May 2010 16:53:29 +0200 (CEST) Subject: [Python-checkins] r81041 - in python/branches/py3k: Doc/library/ftplib.rst Doc/whatsnew/3.2.rst Lib/ftplib.py Lib/test/test_ftplib.py Misc/NEWS Message-ID: <20100510145329.83E70EE9DF@mail.python.org> Author: giampaolo.rodola Date: Mon May 10 16:53:29 2010 New Revision: 81041 Log: Fix issue #4972: adds ftplib.FTP context manager protocol Modified: python/branches/py3k/Doc/library/ftplib.rst python/branches/py3k/Doc/whatsnew/3.2.rst python/branches/py3k/Lib/ftplib.py python/branches/py3k/Lib/test/test_ftplib.py python/branches/py3k/Misc/NEWS Modified: python/branches/py3k/Doc/library/ftplib.rst ============================================================================== --- python/branches/py3k/Doc/library/ftplib.rst (original) +++ python/branches/py3k/Doc/library/ftplib.rst Mon May 10 16:53:29 2010 @@ -46,6 +46,25 @@ connection attempt (if is not specified, the global default timeout setting will be used). + :class:`FTP` class supports the :keyword:`with` statement. Here is a sample + on how using it: + + >>> from ftplib import FTP + >>> with FTP("ftp1.at.proftpd.org") as ftp: + ... ftp.login() + ... ftp.dir() + ... + '230 Anonymous login ok, restrictions apply.' + dr-xr-xr-x 9 ftp ftp 154 May 6 10:43 . + dr-xr-xr-x 9 ftp ftp 154 May 6 10:43 .. + dr-xr-xr-x 5 ftp ftp 4096 May 6 10:43 CentOS + dr-xr-xr-x 3 ftp ftp 18 Jul 10 2008 Fedora + >>> + + .. versionchanged:: 3.2 + Support for the :keyword:`with` statement was added. + + .. class:: FTP_TLS(host='', user='', passwd='', acct='', [keyfile[, certfile[, timeout]]]) A :class:`FTP` subclass which adds TLS support to FTP as described in Modified: python/branches/py3k/Doc/whatsnew/3.2.rst ============================================================================== --- python/branches/py3k/Doc/whatsnew/3.2.rst (original) +++ python/branches/py3k/Doc/whatsnew/3.2.rst Mon May 10 16:53:29 2010 @@ -66,6 +66,9 @@ New, Improved, and Deprecated Modules ===================================== +* The :class:`ftplib.FTP` class now supports the context manager protocol + (Contributed by Tarek Ziad? and Giampaolo Rodol?; :issue:`4972`.) + * The previously deprecated :func:`string.maketrans` function has been removed in favor of the static methods, :meth:`bytes.maketrans` and :meth:`bytearray.maketrans`. This change solves the confusion around which Modified: python/branches/py3k/Lib/ftplib.py ============================================================================== --- python/branches/py3k/Lib/ftplib.py (original) +++ python/branches/py3k/Lib/ftplib.py Mon May 10 16:53:29 2010 @@ -120,6 +120,20 @@ if user: self.login(user, passwd, acct) + def __enter__(self): + return self + + # Context management protocol: try to quit() if active + def __exit__(self, *args): + if self.sock is not None: + try: + self.quit() + except (socket.error, EOFError): + pass + finally: + if self.sock is not None: + self.close() + def connect(self, host='', port=0, timeout=-999): '''Connect to host. Arguments are: - host: hostname to connect to (string, default previous host) Modified: python/branches/py3k/Lib/test/test_ftplib.py ============================================================================== --- python/branches/py3k/Lib/test/test_ftplib.py (original) +++ python/branches/py3k/Lib/test/test_ftplib.py Mon May 10 16:53:29 2010 @@ -10,6 +10,7 @@ import io import errno import os +import time try: import ssl except ImportError: @@ -137,6 +138,9 @@ # sends back the received string (used by the test suite) self.push(arg) + def cmd_noop(self, arg): + self.push('200 noop ok') + def cmd_user(self, arg): self.push('331 username ok') @@ -218,6 +222,7 @@ self.active = False self.active_lock = threading.Lock() self.host, self.port = self.socket.getsockname()[:2] + self.handler_instance = None def start(self): assert not self.active @@ -241,8 +246,7 @@ def handle_accept(self): conn, addr = self.accept() - self.handler = self.handler(conn) - self.close() + self.handler_instance = self.handler(conn) def handle_connect(self): self.close() @@ -459,12 +463,12 @@ def test_rename(self): self.client.rename('a', 'b') - self.server.handler.next_response = '200' + self.server.handler_instance.next_response = '200' self.assertRaises(ftplib.error_reply, self.client.rename, 'a', 'b') def test_delete(self): self.client.delete('foo') - self.server.handler.next_response = '199' + self.server.handler_instance.next_response = '199' self.assertRaises(ftplib.error_reply, self.client.delete, 'foo') def test_size(self): @@ -512,7 +516,7 @@ def test_storbinary(self): f = io.BytesIO(RETR_DATA.encode('ascii')) self.client.storbinary('stor', f) - self.assertEqual(self.server.handler.last_received_data, RETR_DATA) + self.assertEqual(self.server.handler_instance.last_received_data, RETR_DATA) # test new callback arg flag = [] f.seek(0) @@ -524,12 +528,12 @@ for r in (30, '30'): f.seek(0) self.client.storbinary('stor', f, rest=r) - self.assertEqual(self.server.handler.rest, str(r)) + self.assertEqual(self.server.handler_instance.rest, str(r)) def test_storlines(self): f = io.BytesIO(RETR_DATA.replace('\r\n', '\n').encode('ascii')) self.client.storlines('stor', f) - self.assertEqual(self.server.handler.last_received_data, RETR_DATA) + self.assertEqual(self.server.handler_instance.last_received_data, RETR_DATA) # test new callback arg flag = [] f.seek(0) @@ -548,14 +552,59 @@ def test_makeport(self): self.client.makeport() # IPv4 is in use, just make sure send_eprt has not been used - self.assertEqual(self.server.handler.last_received_cmd, 'port') + self.assertEqual(self.server.handler_instance.last_received_cmd, 'port') def test_makepasv(self): host, port = self.client.makepasv() conn = socket.create_connection((host, port), 2) conn.close() # IPv4 is in use, just make sure send_epsv has not been used - self.assertEqual(self.server.handler.last_received_cmd, 'pasv') + self.assertEqual(self.server.handler_instance.last_received_cmd, 'pasv') + + def test_with_statement(self): + self.client.quit() + + def is_client_connected(): + if self.client.sock is None: + return False + try: + self.client.sendcmd('noop') + except (socket.error, EOFError): + return False + return True + + # base test + with ftplib.FTP(timeout=2) as self.client: + self.client.connect(self.server.host, self.server.port) + self.client.sendcmd('noop') + self.assertTrue(is_client_connected()) + self.assertEqual(self.server.handler_instance.last_received_cmd, 'quit') + self.assertFalse(is_client_connected()) + + # QUIT sent inside the with block + with ftplib.FTP(timeout=2) as self.client: + self.client.connect(self.server.host, self.server.port) + self.client.sendcmd('noop') + self.client.quit() + self.assertEqual(self.server.handler_instance.last_received_cmd, 'quit') + self.assertFalse(is_client_connected()) + + # force a wrong response code to be sent on QUIT: error_perm + # is expected and the connection is supposed to be closed + try: + with ftplib.FTP(timeout=2) as self.client: + self.client.connect(self.server.host, self.server.port) + self.client.sendcmd('noop') + self.server.handler_instance.next_response = '550 error on quit' + except ftplib.error_perm as err: + self.assertEqual(str(err), '550 error on quit') + else: + self.fail('Exception not raised') + # needed to give the threaded server some time to set the attribute + # which otherwise would still be == 'noop' + time.sleep(0.1) + self.assertEqual(self.server.handler_instance.last_received_cmd, 'quit') + self.assertFalse(is_client_connected()) class TestIPv6Environment(TestCase): @@ -575,13 +624,13 @@ def test_makeport(self): self.client.makeport() - self.assertEqual(self.server.handler.last_received_cmd, 'eprt') + self.assertEqual(self.server.handler_instance.last_received_cmd, 'eprt') def test_makepasv(self): host, port = self.client.makepasv() conn = socket.create_connection((host, port), 2) conn.close() - self.assertEqual(self.server.handler.last_received_cmd, 'epsv') + self.assertEqual(self.server.handler_instance.last_received_cmd, 'epsv') def test_transfer(self): def retr(): Modified: python/branches/py3k/Misc/NEWS ============================================================================== --- python/branches/py3k/Misc/NEWS (original) +++ python/branches/py3k/Misc/NEWS Mon May 10 16:53:29 2010 @@ -351,6 +351,9 @@ Library ------- +- Issue #4972: Add support for the context manager protocol to the ftplib.FTP + class. + - Issue #8664: In py_compile, create __pycache__ when the compiled path is given. From python-checkins at python.org Mon May 10 17:03:36 2010 From: python-checkins at python.org (andrew.kuchling) Date: Mon, 10 May 2010 17:03:36 +0200 (CEST) Subject: [Python-checkins] r81042 - python/trunk/Doc/whatsnew/2.7.rst Message-ID: <20100510150336.17560EE9B5@mail.python.org> Author: andrew.kuchling Date: Mon May 10 17:03:35 2010 New Revision: 81042 Log: Link to unittest2 article Modified: python/trunk/Doc/whatsnew/2.7.rst Modified: python/trunk/Doc/whatsnew/2.7.rst ============================================================================== --- python/trunk/Doc/whatsnew/2.7.rst (original) +++ python/trunk/Doc/whatsnew/2.7.rst Mon May 10 17:03:35 2010 @@ -1904,6 +1904,11 @@ several files (by Benjamin Peterson). This doesn't affect how the module is imported or used. +.. seealso:: + + http://www.voidspace.org.uk/python/articles/unittest2.shtml + Describes the new features, how to use them, and the + rationale for various design decisions. (By Michael Foord.) .. _elementtree-section: From python-checkins at python.org Mon May 10 17:33:22 2010 From: python-checkins at python.org (giampaolo.rodola) Date: Mon, 10 May 2010 17:33:22 +0200 (CEST) Subject: [Python-checkins] r81043 - in python/trunk: Lib/test/test_asyncore.py Misc/NEWS Message-ID: <20100510153322.9F9E1F95A@mail.python.org> Author: giampaolo.rodola Date: Mon May 10 17:33:22 2010 New Revision: 81043 Log: Issue #8490: adds a more solid test suite for asyncore Modified: python/trunk/Lib/test/test_asyncore.py python/trunk/Misc/NEWS Modified: python/trunk/Lib/test/test_asyncore.py ============================================================================== --- python/trunk/Lib/test/test_asyncore.py (original) +++ python/trunk/Lib/test/test_asyncore.py Mon May 10 17:33:22 2010 @@ -418,11 +418,285 @@ self.assertEqual(file(TESTFN).read(), self.d + d1 + d2) +class BaseTestHandler(asyncore.dispatcher): + + def __init__(self, sock=None): + asyncore.dispatcher.__init__(self, sock) + self.flag = False + + def handle_accept(self): + raise Exception("handle_accept not supposed to be called") + + def handle_connect(self): + raise Exception("handle_connect not supposed to be called") + + def handle_expt(self): + raise Exception("handle_expt not supposed to be called") + + def handle_close(self): + raise Exception("handle_close not supposed to be called") + + def handle_error(self): + raise + + +class TCPServer(asyncore.dispatcher): + """A server which listens on an address and dispatches the + connection to a handler. + """ + + def __init__(self, handler=BaseTestHandler, host=HOST, port=0): + asyncore.dispatcher.__init__(self) + self.create_socket(socket.AF_INET, socket.SOCK_STREAM) + self.set_reuse_addr() + self.bind((host, port)) + self.listen(5) + self.handler = handler + + @property + def address(self): + return self.socket.getsockname()[:2] + + def handle_accept(self): + sock, addr = self.accept() + self.handler(sock) + + def handle_error(self): + raise + + +class BaseClient(BaseTestHandler): + + def __init__(self, address): + BaseTestHandler.__init__(self) + self.create_socket(socket.AF_INET, socket.SOCK_STREAM) + self.connect(address) + + def handle_connect(self): + pass + + +class BaseTestAPI(unittest.TestCase): + + def tearDown(self): + asyncore.close_all() + + def loop_waiting_for_flag(self, instance, timeout=5): + timeout = float(timeout) / 100 + count = 100 + while asyncore.socket_map and count > 0: + asyncore.loop(timeout=0.01, count=1, use_poll=self.use_poll) + if instance.flag: + return + count -= 1 + time.sleep(timeout) + self.fail("flag not set") + + def test_handle_connect(self): + # make sure handle_connect is called on connect() + + class TestClient(BaseClient): + def handle_connect(self): + self.flag = True + + server = TCPServer() + client = TestClient(server.address) + self.loop_waiting_for_flag(client) + + def test_handle_accept(self): + # make sure handle_accept() is called when a client connects + + class TestListener(BaseTestHandler): + + def __init__(self): + BaseTestHandler.__init__(self) + self.create_socket(socket.AF_INET, socket.SOCK_STREAM) + self.bind((HOST, 0)) + self.listen(5) + self.address = self.socket.getsockname()[:2] + + def handle_accept(self): + self.flag = True + + server = TestListener() + client = BaseClient(server.address) + self.loop_waiting_for_flag(server) + + def test_handle_read(self): + # make sure handle_read is called on data received + + class TestClient(BaseClient): + def handle_read(self): + self.flag = True + + class TestHandler(BaseTestHandler): + def __init__(self, conn): + BaseTestHandler.__init__(self, conn) + self.send('x' * 1024) + + server = TCPServer(TestHandler) + client = TestClient(server.address) + self.loop_waiting_for_flag(client) + + def test_handle_write(self): + # make sure handle_write is called + + class TestClient(BaseClient): + def handle_write(self): + self.flag = True + + server = TCPServer() + client = TestClient(server.address) + self.loop_waiting_for_flag(client) + + def test_handle_close(self): + # make sure handle_close is called when the other end closes + # the connection + + class TestClient(BaseClient): + + def handle_read(self): + # in order to make handle_close be called we are supposed + # to make at least one recv() call + self.recv(1024) + + def handle_close(self): + self.flag = True + self.close() + + class TestHandler(BaseTestHandler): + def __init__(self, conn): + BaseTestHandler.__init__(self, conn) + self.close() + + server = TCPServer(TestHandler) + client = TestClient(server.address) + self.loop_waiting_for_flag(client) + + @unittest.skipIf(sys.platform.startswith("sunos"), + "OOB support is broken on Solaris") + def test_handle_expt(self): + # Make sure handle_expt is called on OOB data received. + # Note: this might fail on some platforms as OOB data is + # tenuously supported and rarely used. + + class TestClient(BaseClient): + def handle_expt(self): + self.flag = True + + class TestHandler(BaseTestHandler): + def __init__(self, conn): + BaseTestHandler.__init__(self, conn) + self.socket.send(chr(244), socket.MSG_OOB) + + server = TCPServer(TestHandler) + client = TestClient(server.address) + self.loop_waiting_for_flag(client) + + def test_handle_error(self): + + class TestClient(BaseClient): + def handle_write(self): + 1.0 / 0 + def handle_error(self): + self.flag = True + try: + raise + except ZeroDivisionError: + pass + else: + raise Exception("exception not raised") + + server = TCPServer() + client = TestClient(server.address) + self.loop_waiting_for_flag(client) + + def test_connection_attributes(self): + server = TCPServer() + client = BaseClient(server.address) + + # we start disconnected + self.assertFalse(server.connected) + self.assertTrue(server.accepting) + # XXX - Solaris seems to connect() immediately even without + # starting the poller. This is something which should be + # fixed as handle_connect() gets called immediately even if + # no connection actually took place (see issue #8490). + if not sys.platform.startswith("sunos"): + self.assertFalse(client.connected) + self.assertFalse(client.accepting) + + # execute some loops so that client connects to server + asyncore.loop(timeout=0.01, use_poll=self.use_poll, count=100) + self.assertFalse(server.connected) + self.assertTrue(server.accepting) + self.assertTrue(client.connected) + self.assertFalse(client.accepting) + + # disconnect the client + client.close() + self.assertFalse(server.connected) + self.assertTrue(server.accepting) + self.assertFalse(client.connected) + self.assertFalse(client.accepting) + + # stop serving + server.close() + self.assertFalse(server.connected) + self.assertFalse(server.accepting) + + def test_create_socket(self): + s = asyncore.dispatcher() + s.create_socket(socket.AF_INET, socket.SOCK_STREAM) + self.assertEqual(s.socket.family, socket.AF_INET) + self.assertEqual(s.socket.type, socket.SOCK_STREAM) + + def test_bind(self): + s1 = asyncore.dispatcher() + s1.create_socket(socket.AF_INET, socket.SOCK_STREAM) + s1.bind((HOST, 0)) + s1.listen(5) + port = s1.socket.getsockname()[1] + + s2 = asyncore.dispatcher() + s2.create_socket(socket.AF_INET, socket.SOCK_STREAM) + # EADDRINUSE indicates the socket was correctly bound + self.assertRaises(socket.error, s2.bind, (HOST, port)) + + def test_set_reuse_addr(self): + sock = socket.socket() + try: + sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) + except socket.error: + unittest.skip("SO_REUSEADDR not supported on this platform") + else: + # if SO_REUSEADDR succeeded for sock we expect asyncore + # to do the same + s = asyncore.dispatcher(socket.socket()) + self.assertFalse(s.socket.getsockopt(socket.SOL_SOCKET, + socket.SO_REUSEADDR)) + s.create_socket(socket.AF_INET, socket.SOCK_STREAM) + s.set_reuse_addr() + self.assertTrue(s.socket.getsockopt(socket.SOL_SOCKET, + socket.SO_REUSEADDR)) + finally: + sock.close() + + +class TestAPI_UseSelect(BaseTestAPI): + use_poll = False + +class TestAPI_UsePoll(BaseTestAPI): + use_poll = True + + def test_main(): tests = [HelperFunctionTests, DispatcherTests, DispatcherWithSendTests, - DispatcherWithSendTests_UsePoll] + DispatcherWithSendTests_UsePoll, TestAPI_UseSelect] if hasattr(asyncore, 'file_wrapper'): tests.append(FileWrapperTest) + if hasattr(select, 'poll'): + tests.append(TestAPI_UsePoll) run_unittest(*tests) Modified: python/trunk/Misc/NEWS ============================================================================== --- python/trunk/Misc/NEWS (original) +++ python/trunk/Misc/NEWS Mon May 10 17:33:22 2010 @@ -211,6 +211,9 @@ Tests ----- +- Issue #8490: asyncore now has a more solid test suite which actually tests + its API. + - Issue #8576: Remove use of find_unused_port() in test_smtplib and test_multiprocessing. Patch by Paul Moore. From python-checkins at python.org Mon May 10 17:40:50 2010 From: python-checkins at python.org (giampaolo.rodola) Date: Mon, 10 May 2010 17:40:50 +0200 (CEST) Subject: [Python-checkins] r81044 - in python/branches/py3k: Lib/test/test_asyncore.py Message-ID: <20100510154050.08BD4EE9E5@mail.python.org> Author: giampaolo.rodola Date: Mon May 10 17:40:49 2010 New Revision: 81044 Log: Merged revisions 81043 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r81043 | giampaolo.rodola | 2010-05-10 17:33:22 +0200 (lun, 10 mag 2010) | 1 line Issue #8490: adds a more solid test suite for asyncore ........ Modified: python/branches/py3k/ (props changed) python/branches/py3k/Lib/test/test_asyncore.py Modified: python/branches/py3k/Lib/test/test_asyncore.py ============================================================================== --- python/branches/py3k/Lib/test/test_asyncore.py (original) +++ python/branches/py3k/Lib/test/test_asyncore.py Mon May 10 17:40:49 2010 @@ -419,11 +419,285 @@ self.assertEqual(open(TESTFN, 'rb').read(), self.d + d1 + d2) +class BaseTestHandler(asyncore.dispatcher): + + def __init__(self, sock=None): + asyncore.dispatcher.__init__(self, sock) + self.flag = False + + def handle_accept(self): + raise Exception("handle_accept not supposed to be called") + + def handle_connect(self): + raise Exception("handle_connect not supposed to be called") + + def handle_expt(self): + raise Exception("handle_expt not supposed to be called") + + def handle_close(self): + raise Exception("handle_close not supposed to be called") + + def handle_error(self): + raise + + +class TCPServer(asyncore.dispatcher): + """A server which listens on an address and dispatches the + connection to a handler. + """ + + def __init__(self, handler=BaseTestHandler, host=HOST, port=0): + asyncore.dispatcher.__init__(self) + self.create_socket(socket.AF_INET, socket.SOCK_STREAM) + self.set_reuse_addr() + self.bind((host, port)) + self.listen(5) + self.handler = handler + + @property + def address(self): + return self.socket.getsockname()[:2] + + def handle_accept(self): + sock, addr = self.accept() + self.handler(sock) + + def handle_error(self): + raise + + +class BaseClient(BaseTestHandler): + + def __init__(self, address): + BaseTestHandler.__init__(self) + self.create_socket(socket.AF_INET, socket.SOCK_STREAM) + self.connect(address) + + def handle_connect(self): + pass + + +class BaseTestAPI(unittest.TestCase): + + def tearDown(self): + asyncore.close_all() + + def loop_waiting_for_flag(self, instance, timeout=5): + timeout = float(timeout) / 100 + count = 100 + while asyncore.socket_map and count > 0: + asyncore.loop(timeout=0.01, count=1, use_poll=self.use_poll) + if instance.flag: + return + count -= 1 + time.sleep(timeout) + self.fail("flag not set") + + def test_handle_connect(self): + # make sure handle_connect is called on connect() + + class TestClient(BaseClient): + def handle_connect(self): + self.flag = True + + server = TCPServer() + client = TestClient(server.address) + self.loop_waiting_for_flag(client) + + def test_handle_accept(self): + # make sure handle_accept() is called when a client connects + + class TestListener(BaseTestHandler): + + def __init__(self): + BaseTestHandler.__init__(self) + self.create_socket(socket.AF_INET, socket.SOCK_STREAM) + self.bind((HOST, 0)) + self.listen(5) + self.address = self.socket.getsockname()[:2] + + def handle_accept(self): + self.flag = True + + server = TestListener() + client = BaseClient(server.address) + self.loop_waiting_for_flag(server) + + def test_handle_read(self): + # make sure handle_read is called on data received + + class TestClient(BaseClient): + def handle_read(self): + self.flag = True + + class TestHandler(BaseTestHandler): + def __init__(self, conn): + BaseTestHandler.__init__(self, conn) + self.send(b'x' * 1024) + + server = TCPServer(TestHandler) + client = TestClient(server.address) + self.loop_waiting_for_flag(client) + + def test_handle_write(self): + # make sure handle_write is called + + class TestClient(BaseClient): + def handle_write(self): + self.flag = True + + server = TCPServer() + client = TestClient(server.address) + self.loop_waiting_for_flag(client) + + def test_handle_close(self): + # make sure handle_close is called when the other end closes + # the connection + + class TestClient(BaseClient): + + def handle_read(self): + # in order to make handle_close be called we are supposed + # to make at least one recv() call + self.recv(1024) + + def handle_close(self): + self.flag = True + self.close() + + class TestHandler(BaseTestHandler): + def __init__(self, conn): + BaseTestHandler.__init__(self, conn) + self.close() + + server = TCPServer(TestHandler) + client = TestClient(server.address) + self.loop_waiting_for_flag(client) + + @unittest.skipIf(sys.platform.startswith("sunos"), + "OOB support is broken on Solaris") + def test_handle_expt(self): + # Make sure handle_expt is called on OOB data received. + # Note: this might fail on some platforms as OOB data is + # tenuously supported and rarely used. + + class TestClient(BaseClient): + def handle_expt(self): + self.flag = True + + class TestHandler(BaseTestHandler): + def __init__(self, conn): + BaseTestHandler.__init__(self, conn) + self.socket.send(bytes(chr(244), 'latin-1'), socket.MSG_OOB) + + server = TCPServer(TestHandler) + client = TestClient(server.address) + self.loop_waiting_for_flag(client) + + def test_handle_error(self): + + class TestClient(BaseClient): + def handle_write(self): + 1.0 / 0 + def handle_error(self): + self.flag = True + try: + raise + except ZeroDivisionError: + pass + else: + raise Exception("exception not raised") + + server = TCPServer() + client = TestClient(server.address) + self.loop_waiting_for_flag(client) + + def test_connection_attributes(self): + server = TCPServer() + client = BaseClient(server.address) + + # we start disconnected + self.assertFalse(server.connected) + self.assertTrue(server.accepting) + # XXX - Solaris seems to connect() immediately even without + # starting the poller. This is something which should be + # fixed as handle_connect() gets called immediately even if + # no connection actually took place (see issue #8490). + if not sys.platform.startswith("sunos"): + self.assertFalse(client.connected) + self.assertFalse(client.accepting) + + # execute some loops so that client connects to server + asyncore.loop(timeout=0.01, use_poll=self.use_poll, count=100) + self.assertFalse(server.connected) + self.assertTrue(server.accepting) + self.assertTrue(client.connected) + self.assertFalse(client.accepting) + + # disconnect the client + client.close() + self.assertFalse(server.connected) + self.assertTrue(server.accepting) + self.assertFalse(client.connected) + self.assertFalse(client.accepting) + + # stop serving + server.close() + self.assertFalse(server.connected) + self.assertFalse(server.accepting) + + def test_create_socket(self): + s = asyncore.dispatcher() + s.create_socket(socket.AF_INET, socket.SOCK_STREAM) + self.assertEqual(s.socket.family, socket.AF_INET) + self.assertEqual(s.socket.type, socket.SOCK_STREAM) + + def test_bind(self): + s1 = asyncore.dispatcher() + s1.create_socket(socket.AF_INET, socket.SOCK_STREAM) + s1.bind((HOST, 0)) + s1.listen(5) + port = s1.socket.getsockname()[1] + + s2 = asyncore.dispatcher() + s2.create_socket(socket.AF_INET, socket.SOCK_STREAM) + # EADDRINUSE indicates the socket was correctly bound + self.assertRaises(socket.error, s2.bind, (HOST, port)) + + def test_set_reuse_addr(self): + sock = socket.socket() + try: + sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) + except socket.error: + unittest.skip("SO_REUSEADDR not supported on this platform") + else: + # if SO_REUSEADDR succeeded for sock we expect asyncore + # to do the same + s = asyncore.dispatcher(socket.socket()) + self.assertFalse(s.socket.getsockopt(socket.SOL_SOCKET, + socket.SO_REUSEADDR)) + s.create_socket(socket.AF_INET, socket.SOCK_STREAM) + s.set_reuse_addr() + self.assertTrue(s.socket.getsockopt(socket.SOL_SOCKET, + socket.SO_REUSEADDR)) + finally: + sock.close() + + +class TestAPI_UseSelect(BaseTestAPI): + use_poll = False + +class TestAPI_UsePoll(BaseTestAPI): + use_poll = True + + def test_main(): tests = [HelperFunctionTests, DispatcherTests, DispatcherWithSendTests, - DispatcherWithSendTests_UsePoll] + DispatcherWithSendTests_UsePoll, TestAPI_UseSelect] if hasattr(asyncore, 'file_wrapper'): tests.append(FileWrapperTest) + if hasattr(select, 'poll'): + tests.append(TestAPI_UsePoll) run_unittest(*tests) From python-checkins at python.org Mon May 10 18:07:42 2010 From: python-checkins at python.org (mark.dickinson) Date: Mon, 10 May 2010 18:07:42 +0200 (CEST) Subject: [Python-checkins] r81045 - in python/trunk: Misc/ACKS Misc/NEWS Modules/audioop.c Message-ID: <20100510160742.86393EE994@mail.python.org> Author: mark.dickinson Date: Mon May 10 18:07:42 2010 New Revision: 81045 Log: Issue #8674: Fix incorrect and UB-inducing overflow checks in audioop module. Thanks Tomas Hoger for the patch. Modified: python/trunk/Misc/ACKS python/trunk/Misc/NEWS python/trunk/Modules/audioop.c Modified: python/trunk/Misc/ACKS ============================================================================== --- python/trunk/Misc/ACKS (original) +++ python/trunk/Misc/ACKS Mon May 10 18:07:42 2010 @@ -339,6 +339,7 @@ Gregor Hoffleit Chris Hoffman Albert Hofkamp +Tomas Hoger Jonathan Hogg Gerrit Holl Shane Holloway Modified: python/trunk/Misc/NEWS ============================================================================== --- python/trunk/Misc/NEWS (original) +++ python/trunk/Misc/NEWS Mon May 10 18:07:42 2010 @@ -15,6 +15,11 @@ Library ------- +Extension Modules +----------------- + +- Issue #8674: Fixed a number of incorrect or undefined-behaviour-inducing + overflow checks in the audioop module. What's New in Python 2.7 beta 2? ================================ Modified: python/trunk/Modules/audioop.c ============================================================================== --- python/trunk/Modules/audioop.c (original) +++ python/trunk/Modules/audioop.c Mon May 10 18:07:42 2010 @@ -827,7 +827,7 @@ audioop_tostereo(PyObject *self, PyObject *args) { signed char *cp, *ncp; - int len, new_len, size, val1, val2, val = 0; + int len, size, val1, val2, val = 0; double fac1, fac2, fval, maxval; PyObject *rv; int i; @@ -844,14 +844,13 @@ return 0; } - new_len = len*2; - if (new_len < 0) { + if (len > INT_MAX/2) { PyErr_SetString(PyExc_MemoryError, "not enough memory for output buffer"); return 0; } - rv = PyString_FromStringAndSize(NULL, new_len); + rv = PyString_FromStringAndSize(NULL, len*2); if ( rv == 0 ) return 0; ncp = (signed char *)PyString_AsString(rv); @@ -1014,7 +1013,7 @@ { signed char *cp; unsigned char *ncp; - int len, new_len, size, size2, val = 0; + int len, size, size2, val = 0; PyObject *rv; int i, j; @@ -1028,13 +1027,12 @@ return 0; } - new_len = (len/size)*size2; - if (new_len < 0) { + if (len/size > INT_MAX/size2) { PyErr_SetString(PyExc_MemoryError, "not enough memory for output buffer"); return 0; } - rv = PyString_FromStringAndSize(NULL, new_len); + rv = PyString_FromStringAndSize(NULL, (len/size)*size2); if ( rv == 0 ) return 0; ncp = (unsigned char *)PyString_AsString(rv); @@ -1070,7 +1068,6 @@ int chan, d, *prev_i, *cur_i, cur_o; PyObject *state, *samps, *str, *rv = NULL; int bytes_per_frame; - size_t alloc_size; weightA = 1; weightB = 0; @@ -1113,14 +1110,13 @@ inrate /= d; outrate /= d; - alloc_size = sizeof(int) * (unsigned)nchannels; - if (alloc_size < (unsigned)nchannels) { + if ((size_t)nchannels > PY_SIZE_MAX/sizeof(int)) { PyErr_SetString(PyExc_MemoryError, "not enough memory for output buffer"); return 0; } - prev_i = (int *) malloc(alloc_size); - cur_i = (int *) malloc(alloc_size); + prev_i = (int *) malloc(nchannels * sizeof(int)); + cur_i = (int *) malloc(nchannels * sizeof(int)); if (prev_i == NULL || cur_i == NULL) { (void) PyErr_NoMemory(); goto exit; @@ -1294,7 +1290,7 @@ unsigned char *cp; unsigned char cval; signed char *ncp; - int len, new_len, size, val; + int len, size, val; PyObject *rv; int i; @@ -1307,18 +1303,17 @@ return 0; } - new_len = len*size; - if (new_len < 0) { + if (len > INT_MAX/size) { PyErr_SetString(PyExc_MemoryError, "not enough memory for output buffer"); return 0; } - rv = PyString_FromStringAndSize(NULL, new_len); + rv = PyString_FromStringAndSize(NULL, len*size); if ( rv == 0 ) return 0; ncp = (signed char *)PyString_AsString(rv); - for ( i=0; i < new_len; i += size ) { + for ( i=0; i < len*size; i += size ) { cval = *cp++; val = st_ulaw2linear16(cval); @@ -1368,7 +1363,7 @@ unsigned char *cp; unsigned char cval; signed char *ncp; - int len, new_len, size, val; + int len, size, val; PyObject *rv; int i; @@ -1381,18 +1376,17 @@ return 0; } - new_len = len*size; - if (new_len < 0) { + if (len > INT_MAX/size) { PyErr_SetString(PyExc_MemoryError, "not enough memory for output buffer"); return 0; } - rv = PyString_FromStringAndSize(NULL, new_len); + rv = PyString_FromStringAndSize(NULL, len*size); if ( rv == 0 ) return 0; ncp = (signed char *)PyString_AsString(rv); - for ( i=0; i < new_len; i += size ) { + for ( i=0; i < len*size; i += size ) { cval = *cp++; val = st_alaw2linear16(cval); @@ -1516,7 +1510,7 @@ { signed char *cp; signed char *ncp; - int len, new_len, size, valpred, step, delta, index, sign, vpdiff; + int len, size, valpred, step, delta, index, sign, vpdiff; PyObject *rv, *str, *state; int i, inputbuffer = 0, bufferstep; @@ -1537,13 +1531,12 @@ } else if ( !PyArg_ParseTuple(state, "ii", &valpred, &index) ) return 0; - new_len = len*size*2; - if (new_len < 0) { + if (len > (INT_MAX/2)/size) { PyErr_SetString(PyExc_MemoryError, "not enough memory for output buffer"); return 0; } - str = PyString_FromStringAndSize(NULL, new_len); + str = PyString_FromStringAndSize(NULL, len*size*2); if ( str == 0 ) return 0; ncp = (signed char *)PyString_AsString(str); @@ -1551,7 +1544,7 @@ step = stepsizeTable[index]; bufferstep = 0; - for ( i=0; i < new_len; i += size ) { + for ( i=0; i < len*size*2; i += size ) { /* Step 1 - get the delta value and compute next index */ if ( bufferstep ) { delta = inputbuffer & 0xf; From python-checkins at python.org Mon May 10 18:16:52 2010 From: python-checkins at python.org (mark.dickinson) Date: Mon, 10 May 2010 18:16:52 +0200 (CEST) Subject: [Python-checkins] r81046 - in python/branches/release26-maint: Misc/ACKS Misc/NEWS Modules/audioop.c Message-ID: <20100510161652.5BB42EE989@mail.python.org> Author: mark.dickinson Date: Mon May 10 18:16:52 2010 New Revision: 81046 Log: Merged revisions 81045 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r81045 | mark.dickinson | 2010-05-10 17:07:42 +0100 (Mon, 10 May 2010) | 3 lines Issue #8674: Fix incorrect and UB-inducing overflow checks in audioop module. Thanks Tomas Hoger for the patch. ........ Modified: python/branches/release26-maint/ (props changed) python/branches/release26-maint/Misc/ACKS python/branches/release26-maint/Misc/NEWS python/branches/release26-maint/Modules/audioop.c Modified: python/branches/release26-maint/Misc/ACKS ============================================================================== --- python/branches/release26-maint/Misc/ACKS (original) +++ python/branches/release26-maint/Misc/ACKS Mon May 10 18:16:52 2010 @@ -315,6 +315,7 @@ Gregor Hoffleit Chris Hoffman Albert Hofkamp +Tomas Hoger Jonathan Hogg Gerrit Holl Shane Holloway Modified: python/branches/release26-maint/Misc/NEWS ============================================================================== --- python/branches/release26-maint/Misc/NEWS (original) +++ python/branches/release26-maint/Misc/NEWS Mon May 10 18:16:52 2010 @@ -39,6 +39,9 @@ Library ------- +- Issue #8674: Fixed a number of incorrect or undefined-behaviour-inducing + overflow checks in the audioop module. + - Issue #8571: Fix an internal error when compressing or decompressing a chunk larger than 1GB with the zlib module's compressor and decompressor objects. Modified: python/branches/release26-maint/Modules/audioop.c ============================================================================== --- python/branches/release26-maint/Modules/audioop.c (original) +++ python/branches/release26-maint/Modules/audioop.c Mon May 10 18:16:52 2010 @@ -829,7 +829,7 @@ audioop_tostereo(PyObject *self, PyObject *args) { signed char *cp, *ncp; - int len, new_len, size, val1, val2, val = 0; + int len, size, val1, val2, val = 0; double fac1, fac2, fval, maxval; PyObject *rv; int i; @@ -846,14 +846,13 @@ return 0; } - new_len = len*2; - if (new_len < 0) { + if (len > INT_MAX/2) { PyErr_SetString(PyExc_MemoryError, "not enough memory for output buffer"); return 0; } - rv = PyString_FromStringAndSize(NULL, new_len); + rv = PyString_FromStringAndSize(NULL, len*2); if ( rv == 0 ) return 0; ncp = (signed char *)PyString_AsString(rv); @@ -1016,7 +1015,7 @@ { signed char *cp; unsigned char *ncp; - int len, new_len, size, size2, val = 0; + int len, size, size2, val = 0; PyObject *rv; int i, j; @@ -1030,13 +1029,12 @@ return 0; } - new_len = (len/size)*size2; - if (new_len < 0) { + if (len/size > INT_MAX/size2) { PyErr_SetString(PyExc_MemoryError, "not enough memory for output buffer"); return 0; } - rv = PyString_FromStringAndSize(NULL, new_len); + rv = PyString_FromStringAndSize(NULL, (len/size)*size2); if ( rv == 0 ) return 0; ncp = (unsigned char *)PyString_AsString(rv); @@ -1072,7 +1070,6 @@ int chan, d, *prev_i, *cur_i, cur_o; PyObject *state, *samps, *str, *rv = NULL; int bytes_per_frame; - size_t alloc_size; weightA = 1; weightB = 0; @@ -1115,14 +1112,13 @@ inrate /= d; outrate /= d; - alloc_size = sizeof(int) * (unsigned)nchannels; - if (alloc_size < nchannels) { + if ((size_t)nchannels > PY_SIZE_MAX/sizeof(int)) { PyErr_SetString(PyExc_MemoryError, "not enough memory for output buffer"); return 0; } - prev_i = (int *) malloc(alloc_size); - cur_i = (int *) malloc(alloc_size); + prev_i = (int *) malloc(nchannels * sizeof(int)); + cur_i = (int *) malloc(nchannels * sizeof(int)); if (prev_i == NULL || cur_i == NULL) { (void) PyErr_NoMemory(); goto exit; @@ -1296,7 +1292,7 @@ unsigned char *cp; unsigned char cval; signed char *ncp; - int len, new_len, size, val; + int len, size, val; PyObject *rv; int i; @@ -1309,18 +1305,17 @@ return 0; } - new_len = len*size; - if (new_len < 0) { + if (len > INT_MAX/size) { PyErr_SetString(PyExc_MemoryError, "not enough memory for output buffer"); return 0; } - rv = PyString_FromStringAndSize(NULL, new_len); + rv = PyString_FromStringAndSize(NULL, len*size); if ( rv == 0 ) return 0; ncp = (signed char *)PyString_AsString(rv); - for ( i=0; i < new_len; i += size ) { + for ( i=0; i < len*size; i += size ) { cval = *cp++; val = st_ulaw2linear16(cval); @@ -1370,7 +1365,7 @@ unsigned char *cp; unsigned char cval; signed char *ncp; - int len, new_len, size, val; + int len, size, val; PyObject *rv; int i; @@ -1383,18 +1378,17 @@ return 0; } - new_len = len*size; - if (new_len < 0) { + if (len > INT_MAX/size) { PyErr_SetString(PyExc_MemoryError, "not enough memory for output buffer"); return 0; } - rv = PyString_FromStringAndSize(NULL, new_len); + rv = PyString_FromStringAndSize(NULL, len*size); if ( rv == 0 ) return 0; ncp = (signed char *)PyString_AsString(rv); - for ( i=0; i < new_len; i += size ) { + for ( i=0; i < len*size; i += size ) { cval = *cp++; val = st_alaw2linear16(cval); @@ -1519,7 +1513,7 @@ { signed char *cp; signed char *ncp; - int len, new_len, size, valpred, step, delta, index, sign, vpdiff; + int len, size, valpred, step, delta, index, sign, vpdiff; PyObject *rv, *str, *state; int i, inputbuffer = 0, bufferstep; @@ -1541,13 +1535,12 @@ } else if ( !PyArg_ParseTuple(state, "ii", &valpred, &index) ) return 0; - new_len = len*size*2; - if (new_len < 0) { + if (len > (INT_MAX/2)/size) { PyErr_SetString(PyExc_MemoryError, "not enough memory for output buffer"); return 0; } - str = PyString_FromStringAndSize(NULL, new_len); + str = PyString_FromStringAndSize(NULL, len*size*2); if ( str == 0 ) return 0; ncp = (signed char *)PyString_AsString(str); @@ -1555,7 +1548,7 @@ step = stepsizeTable[index]; bufferstep = 0; - for ( i=0; i < new_len; i += size ) { + for ( i=0; i < len*size*2; i += size ) { /* Step 1 - get the delta value and compute next index */ if ( bufferstep ) { delta = inputbuffer & 0xf; From python-checkins at python.org Mon May 10 18:27:45 2010 From: python-checkins at python.org (mark.dickinson) Date: Mon, 10 May 2010 18:27:45 +0200 (CEST) Subject: [Python-checkins] r81047 - in python/branches/py3k: Misc/ACKS Misc/NEWS Modules/audioop.c Message-ID: <20100510162745.EC55AC93C@mail.python.org> Author: mark.dickinson Date: Mon May 10 18:27:45 2010 New Revision: 81047 Log: Merged revisions 81045 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r81045 | mark.dickinson | 2010-05-10 17:07:42 +0100 (Mon, 10 May 2010) | 3 lines Issue #8674: Fix incorrect and UB-inducing overflow checks in audioop module. Thanks Tomas Hoger for the patch. ........ Modified: python/branches/py3k/ (props changed) python/branches/py3k/Misc/ACKS python/branches/py3k/Misc/NEWS python/branches/py3k/Modules/audioop.c Modified: python/branches/py3k/Misc/ACKS ============================================================================== --- python/branches/py3k/Misc/ACKS (original) +++ python/branches/py3k/Misc/ACKS Mon May 10 18:27:45 2010 @@ -340,6 +340,7 @@ Gregor Hoffleit Chris Hoffman Albert Hofkamp +Tomas Hoger Jonathan Hogg Gerrit Holl Shane Holloway Modified: python/branches/py3k/Misc/NEWS ============================================================================== --- python/branches/py3k/Misc/NEWS (original) +++ python/branches/py3k/Misc/NEWS Mon May 10 18:27:45 2010 @@ -1114,6 +1114,9 @@ Extension Modules ----------------- +- Issue #8674: Fixed a number of incorrect or undefined-behaviour-inducing + overflow checks in the audioop module. + - Issue #8644: The accuracy of td.total_seconds() has been improved (by calculating with integer arithmetic instead of float arithmetic internally): the result is now always correctly rounded, and is equivalent to td / Modified: python/branches/py3k/Modules/audioop.c ============================================================================== --- python/branches/py3k/Modules/audioop.c (original) +++ python/branches/py3k/Modules/audioop.c Mon May 10 18:27:45 2010 @@ -834,7 +834,7 @@ audioop_tostereo(PyObject *self, PyObject *args) { signed char *cp, *ncp; - int len, new_len, size, val1, val2, val = 0; + int len, size, val1, val2, val = 0; double fac1, fac2, fval, maxval; PyObject *rv; int i; @@ -851,14 +851,13 @@ return 0; } - new_len = len*2; - if (new_len < 0) { + if (len > INT_MAX/2) { PyErr_SetString(PyExc_MemoryError, "not enough memory for output buffer"); return 0; } - rv = PyBytes_FromStringAndSize(NULL, new_len); + rv = PyBytes_FromStringAndSize(NULL, len*2); if ( rv == 0 ) return 0; ncp = (signed char *)PyBytes_AsString(rv); @@ -1021,7 +1020,7 @@ { signed char *cp; unsigned char *ncp; - int len, new_len, size, size2, val = 0; + int len, size, size2, val = 0; PyObject *rv; int i, j; @@ -1035,13 +1034,12 @@ return 0; } - new_len = (len/size)*size2; - if (new_len < 0) { + if (len/size > INT_MAX/size2) { PyErr_SetString(PyExc_MemoryError, "not enough memory for output buffer"); return 0; } - rv = PyBytes_FromStringAndSize(NULL, new_len); + rv = PyBytes_FromStringAndSize(NULL, (len/size)*size2); if ( rv == 0 ) return 0; ncp = (unsigned char *)PyBytes_AsString(rv); @@ -1077,7 +1075,6 @@ int chan, d, *prev_i, *cur_i, cur_o; PyObject *state, *samps, *str, *rv = NULL; int bytes_per_frame; - size_t alloc_size; weightA = 1; weightB = 0; @@ -1120,14 +1117,13 @@ inrate /= d; outrate /= d; - alloc_size = sizeof(int) * (unsigned)nchannels; - if (alloc_size < (unsigned)nchannels) { + if ((size_t)nchannels > PY_SIZE_MAX/sizeof(int)) { PyErr_SetString(PyExc_MemoryError, "not enough memory for output buffer"); return 0; } - prev_i = (int *) malloc(alloc_size); - cur_i = (int *) malloc(alloc_size); + prev_i = (int *) malloc(nchannels * sizeof(int)); + cur_i = (int *) malloc(nchannels * sizeof(int)); if (prev_i == NULL || cur_i == NULL) { (void) PyErr_NoMemory(); goto exit; @@ -1300,7 +1296,7 @@ unsigned char *cp; unsigned char cval; signed char *ncp; - int len, new_len, size, val; + int len, size, val; PyObject *rv; int i; @@ -1313,18 +1309,17 @@ return 0; } - new_len = len*size; - if (new_len < 0) { + if (len > INT_MAX/size) { PyErr_SetString(PyExc_MemoryError, "not enough memory for output buffer"); return 0; } - rv = PyBytes_FromStringAndSize(NULL, new_len); + rv = PyBytes_FromStringAndSize(NULL, len*size); if ( rv == 0 ) return 0; ncp = (signed char *)PyBytes_AsString(rv); - for ( i=0; i < new_len; i += size ) { + for ( i=0; i < len*size; i += size ) { cval = *cp++; val = st_ulaw2linear16(cval); @@ -1374,7 +1369,7 @@ unsigned char *cp; unsigned char cval; signed char *ncp; - int len, new_len, size, val; + int len, size, val; PyObject *rv; int i; @@ -1387,18 +1382,17 @@ return 0; } - new_len = len*size; - if (new_len < 0) { + if (len > INT_MAX/size) { PyErr_SetString(PyExc_MemoryError, "not enough memory for output buffer"); return 0; } - rv = PyBytes_FromStringAndSize(NULL, new_len); + rv = PyBytes_FromStringAndSize(NULL, len*size); if ( rv == 0 ) return 0; ncp = (signed char *)PyBytes_AsString(rv); - for ( i=0; i < new_len; i += size ) { + for ( i=0; i < len*size; i += size ) { cval = *cp++; val = st_alaw2linear16(cval); @@ -1523,7 +1517,7 @@ { signed char *cp; signed char *ncp; - int len, new_len, size, valpred, step, delta, index, sign, vpdiff; + int len, size, valpred, step, delta, index, sign, vpdiff; PyObject *rv, *str, *state; int i, inputbuffer = 0, bufferstep; @@ -1545,13 +1539,12 @@ } else if ( !PyArg_ParseTuple(state, "ii", &valpred, &index) ) return 0; - new_len = len*size*2; - if (new_len < 0) { + if (len > (INT_MAX/2)/size) { PyErr_SetString(PyExc_MemoryError, "not enough memory for output buffer"); return 0; } - str = PyBytes_FromStringAndSize(NULL, new_len); + str = PyBytes_FromStringAndSize(NULL, len*size*2); if ( str == 0 ) return 0; ncp = (signed char *)PyBytes_AsString(str); @@ -1559,7 +1552,7 @@ step = stepsizeTable[index]; bufferstep = 0; - for ( i=0; i < new_len; i += size ) { + for ( i=0; i < len*size*2; i += size ) { /* Step 1 - get the delta value and compute next index */ if ( bufferstep ) { delta = inputbuffer & 0xf; From python-checkins at python.org Mon May 10 18:39:55 2010 From: python-checkins at python.org (mark.dickinson) Date: Mon, 10 May 2010 18:39:55 +0200 (CEST) Subject: [Python-checkins] r81048 - in python/branches/release31-maint: Misc/ACKS Misc/NEWS Modules/audioop.c Message-ID: <20100510163955.4995DEE9C5@mail.python.org> Author: mark.dickinson Date: Mon May 10 18:39:55 2010 New Revision: 81048 Log: Merged revisions 81047 via svnmerge from svn+ssh://pythondev at svn.python.org/python/branches/py3k ................ r81047 | mark.dickinson | 2010-05-10 17:27:45 +0100 (Mon, 10 May 2010) | 10 lines Merged revisions 81045 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r81045 | mark.dickinson | 2010-05-10 17:07:42 +0100 (Mon, 10 May 2010) | 3 lines Issue #8674: Fix incorrect and UB-inducing overflow checks in audioop module. Thanks Tomas Hoger for the patch. ........ ................ Modified: python/branches/release31-maint/ (props changed) python/branches/release31-maint/Misc/ACKS python/branches/release31-maint/Misc/NEWS python/branches/release31-maint/Modules/audioop.c Modified: python/branches/release31-maint/Misc/ACKS ============================================================================== --- python/branches/release31-maint/Misc/ACKS (original) +++ python/branches/release31-maint/Misc/ACKS Mon May 10 18:39:55 2010 @@ -328,6 +328,7 @@ Gregor Hoffleit Chris Hoffman Albert Hofkamp +Tomas Hoger Jonathan Hogg Gerrit Holl Shane Holloway Modified: python/branches/release31-maint/Misc/NEWS ============================================================================== --- python/branches/release31-maint/Misc/NEWS (original) +++ python/branches/release31-maint/Misc/NEWS Mon May 10 18:39:55 2010 @@ -40,6 +40,9 @@ Library ------- +- Issue #8674: Fixed a number of incorrect or undefined-behaviour-inducing + overflow checks in the audioop module. + - Issue #8571: Fix an internal error when compressing or decompressing a chunk larger than 1GB with the zlib module's compressor and decompressor objects. Modified: python/branches/release31-maint/Modules/audioop.c ============================================================================== --- python/branches/release31-maint/Modules/audioop.c (original) +++ python/branches/release31-maint/Modules/audioop.c Mon May 10 18:39:55 2010 @@ -834,7 +834,7 @@ audioop_tostereo(PyObject *self, PyObject *args) { signed char *cp, *ncp; - int len, new_len, size, val1, val2, val = 0; + int len, size, val1, val2, val = 0; double fac1, fac2, fval, maxval; PyObject *rv; int i; @@ -851,14 +851,13 @@ return 0; } - new_len = len*2; - if (new_len < 0) { + if (len > INT_MAX/2) { PyErr_SetString(PyExc_MemoryError, "not enough memory for output buffer"); return 0; } - rv = PyBytes_FromStringAndSize(NULL, new_len); + rv = PyBytes_FromStringAndSize(NULL, len*2); if ( rv == 0 ) return 0; ncp = (signed char *)PyBytes_AsString(rv); @@ -1021,7 +1020,7 @@ { signed char *cp; unsigned char *ncp; - int len, new_len, size, size2, val = 0; + int len, size, size2, val = 0; PyObject *rv; int i, j; @@ -1035,13 +1034,12 @@ return 0; } - new_len = (len/size)*size2; - if (new_len < 0) { + if (len/size > INT_MAX/size2) { PyErr_SetString(PyExc_MemoryError, "not enough memory for output buffer"); return 0; } - rv = PyBytes_FromStringAndSize(NULL, new_len); + rv = PyBytes_FromStringAndSize(NULL, (len/size)*size2); if ( rv == 0 ) return 0; ncp = (unsigned char *)PyBytes_AsString(rv); @@ -1077,7 +1075,6 @@ int chan, d, *prev_i, *cur_i, cur_o; PyObject *state, *samps, *str, *rv = NULL; int bytes_per_frame; - size_t alloc_size; weightA = 1; weightB = 0; @@ -1120,14 +1117,13 @@ inrate /= d; outrate /= d; - alloc_size = sizeof(int) * (unsigned)nchannels; - if (alloc_size < (unsigned)nchannels) { + if ((size_t)nchannels > PY_SIZE_MAX/sizeof(int)) { PyErr_SetString(PyExc_MemoryError, "not enough memory for output buffer"); return 0; } - prev_i = (int *) malloc(alloc_size); - cur_i = (int *) malloc(alloc_size); + prev_i = (int *) malloc(nchannels * sizeof(int)); + cur_i = (int *) malloc(nchannels * sizeof(int)); if (prev_i == NULL || cur_i == NULL) { (void) PyErr_NoMemory(); goto exit; @@ -1300,7 +1296,7 @@ unsigned char *cp; unsigned char cval; signed char *ncp; - int len, new_len, size, val; + int len, size, val; PyObject *rv; int i; @@ -1313,18 +1309,17 @@ return 0; } - new_len = len*size; - if (new_len < 0) { + if (len > INT_MAX/size) { PyErr_SetString(PyExc_MemoryError, "not enough memory for output buffer"); return 0; } - rv = PyBytes_FromStringAndSize(NULL, new_len); + rv = PyBytes_FromStringAndSize(NULL, len*size); if ( rv == 0 ) return 0; ncp = (signed char *)PyBytes_AsString(rv); - for ( i=0; i < new_len; i += size ) { + for ( i=0; i < len*size; i += size ) { cval = *cp++; val = st_ulaw2linear16(cval); @@ -1374,7 +1369,7 @@ unsigned char *cp; unsigned char cval; signed char *ncp; - int len, new_len, size, val; + int len, size, val; PyObject *rv; int i; @@ -1387,18 +1382,17 @@ return 0; } - new_len = len*size; - if (new_len < 0) { + if (len > INT_MAX/size) { PyErr_SetString(PyExc_MemoryError, "not enough memory for output buffer"); return 0; } - rv = PyBytes_FromStringAndSize(NULL, new_len); + rv = PyBytes_FromStringAndSize(NULL, len*size); if ( rv == 0 ) return 0; ncp = (signed char *)PyBytes_AsString(rv); - for ( i=0; i < new_len; i += size ) { + for ( i=0; i < len*size; i += size ) { cval = *cp++; val = st_alaw2linear16(cval); @@ -1523,7 +1517,7 @@ { signed char *cp; signed char *ncp; - int len, new_len, size, valpred, step, delta, index, sign, vpdiff; + int len, size, valpred, step, delta, index, sign, vpdiff; PyObject *rv, *str, *state; int i, inputbuffer = 0, bufferstep; @@ -1545,13 +1539,12 @@ } else if ( !PyArg_ParseTuple(state, "ii", &valpred, &index) ) return 0; - new_len = len*size*2; - if (new_len < 0) { + if (len > (INT_MAX/2)/size) { PyErr_SetString(PyExc_MemoryError, "not enough memory for output buffer"); return 0; } - str = PyBytes_FromStringAndSize(NULL, new_len); + str = PyBytes_FromStringAndSize(NULL, len*size*2); if ( str == 0 ) return 0; ncp = (signed char *)PyBytes_AsString(str); @@ -1559,7 +1552,7 @@ step = stepsizeTable[index]; bufferstep = 0; - for ( i=0; i < new_len; i += size ) { + for ( i=0; i < len*size*2; i += size ) { /* Step 1 - get the delta value and compute next index */ if ( bufferstep ) { delta = inputbuffer & 0xf; From python-checkins at python.org Mon May 10 19:18:25 2010 From: python-checkins at python.org (andrew.kuchling) Date: Mon, 10 May 2010 19:18:25 +0200 (CEST) Subject: [Python-checkins] r81049 - python/trunk/Modules/_cursesmodule.c Message-ID: <20100510171825.84C61EE994@mail.python.org> Author: andrew.kuchling Date: Mon May 10 19:18:25 2010 New Revision: 81049 Log: Move { out of #if...#else block; this confuses Emacs' C-mode Modified: python/trunk/Modules/_cursesmodule.c Modified: python/trunk/Modules/_cursesmodule.c ============================================================================== --- python/trunk/Modules/_cursesmodule.c (original) +++ python/trunk/Modules/_cursesmodule.c Mon May 10 19:18:25 2010 @@ -1226,10 +1226,11 @@ int rtn; #ifndef WINDOW_HAS_FLAGS - if (0) { + if (0) #else - if (self->win->_flags & _ISPAD) { + if (self->win->_flags & _ISPAD) #endif + { switch(PyTuple_Size(args)) { case 6: if (!PyArg_ParseTuple(args, @@ -1368,10 +1369,11 @@ int rtn; #ifndef WINDOW_HAS_FLAGS - if (0) { + if (0) #else - if (self->win->_flags & _ISPAD) { + if (self->win->_flags & _ISPAD) #endif + { switch(PyTuple_Size(args)) { case 6: if (!PyArg_ParseTuple(args, From python-checkins at python.org Mon May 10 21:50:45 2010 From: python-checkins at python.org (andrew.kuchling) Date: Mon, 10 May 2010 21:50:45 +0200 (CEST) Subject: [Python-checkins] r81050 - in sandbox/trunk/curses: _cursesmodule.c Message-ID: <20100510195045.CA8F3EE9A7@mail.python.org> Author: andrew.kuchling Date: Mon May 10 21:50:45 2010 New Revision: 81050 Log: Make copy of _cursesmodule.c Added: sandbox/trunk/curses/ sandbox/trunk/curses/_cursesmodule.c Added: sandbox/trunk/curses/_cursesmodule.c ============================================================================== --- (empty file) +++ sandbox/trunk/curses/_cursesmodule.c Mon May 10 21:50:45 2010 @@ -0,0 +1,2885 @@ +/* + * This is a curses module for Python. + * + * Based on prior work by Lance Ellinghaus and Oliver Andrich + * Version 1.2 of this module: Copyright 1994 by Lance Ellinghouse, + * Cathedral City, California Republic, United States of America. + * + * Version 1.5b1, heavily extended for ncurses by Oliver Andrich: + * Copyright 1996,1997 by Oliver Andrich, Koblenz, Germany. + * + * Tidied for Python 1.6, and currently maintained by . + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this source file to use, copy, modify, merge, or publish it + * subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included + * in all copies or in any new file that contains a substantial portion of + * this file. + * + * THE AUTHOR MAKES NO REPRESENTATIONS ABOUT THE SUITABILITY OF + * THE SOFTWARE FOR ANY PURPOSE. IT IS PROVIDED "AS IS" WITHOUT + * EXPRESS OR IMPLIED WARRANTY. THE AUTHOR DISCLAIMS ALL WARRANTIES + * WITH REGARD TO THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES + * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NON-INFRINGEMENT OF THIRD PARTY RIGHTS. IN NO EVENT SHALL THE + * AUTHOR BE LIABLE TO YOU OR ANY OTHER PARTY FOR ANY SPECIAL, + * INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER + * WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE, STRICT LIABILITY OR + * ANY OTHER ACTION ARISING OUT OF OR IN CONNECTION WITH THE USE OR + * PERFORMANCE OF THIS SOFTWARE. + */ + +/* + +A number of SysV or ncurses functions don't have wrappers yet; if you +need a given function, add it and send a patch. See +http://www.python.org/dev/patches/ for instructions on how to submit +patches to Python. + +Here's a list of currently unsupported functions: + + addchnstr addchstr color_set define_key + del_curterm delscreen dupwin inchnstr inchstr innstr keyok + mcprint mvaddchnstr mvaddchstr mvcur mvinchnstr + mvinchstr mvinnstr mmvwaddchnstr mvwaddchstr + mvwinchnstr mvwinchstr mvwinnstr newterm + restartterm ripoffline scr_dump + scr_init scr_restore scr_set scrl set_curterm set_term setterm + tgetent tgetflag tgetnum tgetstr tgoto timeout tputs + vidattr vidputs waddchnstr waddchstr + wcolor_set winchnstr winchstr winnstr wmouse_trafo wscrl + +Low-priority: + slk_attr slk_attr_off slk_attr_on slk_attr_set slk_attroff + slk_attron slk_attrset slk_clear slk_color slk_init slk_label + slk_noutrefresh slk_refresh slk_restore slk_set slk_touch + +Menu extension (ncurses and probably SYSV): + current_item free_item free_menu item_count item_description + item_index item_init item_name item_opts item_opts_off + item_opts_on item_term item_userptr item_value item_visible + menu_back menu_driver menu_fore menu_format menu_grey + menu_init menu_items menu_mark menu_opts menu_opts_off + menu_opts_on menu_pad menu_pattern menu_request_by_name + menu_request_name menu_spacing menu_sub menu_term menu_userptr + menu_win new_item new_menu pos_menu_cursor post_menu + scale_menu set_current_item set_item_init set_item_opts + set_item_term set_item_userptr set_item_value set_menu_back + set_menu_fore set_menu_format set_menu_grey set_menu_init + set_menu_items set_menu_mark set_menu_opts set_menu_pad + set_menu_pattern set_menu_spacing set_menu_sub set_menu_term + set_menu_userptr set_menu_win set_top_row top_row unpost_menu + +Form extension (ncurses and probably SYSV): + current_field data_ahead data_behind dup_field + dynamic_fieldinfo field_arg field_back field_buffer + field_count field_fore field_index field_info field_init + field_just field_opts field_opts_off field_opts_on field_pad + field_status field_term field_type field_userptr form_driver + form_fields form_init form_opts form_opts_off form_opts_on + form_page form_request_by_name form_request_name form_sub + form_term form_userptr form_win free_field free_form + link_field link_fieldtype move_field new_field new_form + new_page pos_form_cursor post_form scale_form + set_current_field set_field_back set_field_buffer + set_field_fore set_field_init set_field_just set_field_opts + set_field_pad set_field_status set_field_term set_field_type + set_field_userptr set_fieldtype_arg set_fieldtype_choice + set_form_fields set_form_init set_form_opts set_form_page + set_form_sub set_form_term set_form_userptr set_form_win + set_max_field set_new_page unpost_form + + + */ + +/* Release Number */ + +char *PyCursesVersion = "2.2"; + +/* Includes */ + +#include "Python.h" + +#ifdef __osf__ +#define STRICT_SYSV_CURSES /* Don't use ncurses extensions */ +#endif + +#ifdef __hpux +#define STRICT_SYSV_CURSES +#endif + +#define CURSES_MODULE +#include "py_curses.h" + +/* These prototypes are in , but including this header + #defines many common symbols (such as "lines") which breaks the + curses module in other ways. So the code will just specify + explicit prototypes here. */ +extern int setupterm(char *,int,int *); +#ifdef __sgi +#include +#endif + +#if !defined(HAVE_NCURSES_H) && (defined(sgi) || defined(__sun) || defined(SCO5)) +#define STRICT_SYSV_CURSES /* Don't use ncurses extensions */ +typedef chtype attr_t; /* No attr_t type is available */ +#endif + +#if defined(_AIX) +#define STRICT_SYSV_CURSES +#endif + +/* Definition of exception curses.error */ + +static PyObject *PyCursesError; + +/* Tells whether setupterm() has been called to initialise terminfo. */ +static int initialised_setupterm = FALSE; + +/* Tells whether initscr() has been called to initialise curses. */ +static int initialised = FALSE; + +/* Tells whether start_color() has been called to initialise color usage. */ +static int initialisedcolors = FALSE; + +/* Utility Macros */ +#define PyCursesSetupTermCalled \ + if (initialised_setupterm != TRUE) { \ + PyErr_SetString(PyCursesError, \ + "must call (at least) setupterm() first"); \ + return 0; } + +#define PyCursesInitialised \ + if (initialised != TRUE) { \ + PyErr_SetString(PyCursesError, \ + "must call initscr() first"); \ + return 0; } + +#define PyCursesInitialisedColor \ + if (initialisedcolors != TRUE) { \ + PyErr_SetString(PyCursesError, \ + "must call start_color() first"); \ + return 0; } + +#ifndef MIN +#define MIN(x,y) ((x) < (y) ? (x) : (y)) +#endif + +/* Utility Functions */ + +/* + * Check the return code from a curses function and return None + * or raise an exception as appropriate. These are exported using the + * capsule API. + */ + +static PyObject * +PyCursesCheckERR(int code, char *fname) +{ + if (code != ERR) { + Py_INCREF(Py_None); + return Py_None; + } else { + if (fname == NULL) { + PyErr_SetString(PyCursesError, catchall_ERR); + } else { + PyErr_Format(PyCursesError, "%s() returned ERR", fname); + } + return NULL; + } +} + +static int +PyCurses_ConvertToChtype(PyObject *obj, chtype *ch) +{ + if (PyInt_Check(obj)) { + *ch = (chtype) PyInt_AsLong(obj); + } else if(PyString_Check(obj) + && (PyString_Size(obj) == 1)) { + *ch = (chtype) *PyString_AsString(obj); + } else { + return 0; + } + return 1; +} + +/* Function versions of the 3 functions for testing whether curses has been + initialised or not. */ + +static int func_PyCursesSetupTermCalled(void) +{ + PyCursesSetupTermCalled; + return 1; +} + +static int func_PyCursesInitialised(void) +{ + PyCursesInitialised; + return 1; +} + +static int func_PyCursesInitialisedColor(void) +{ + PyCursesInitialisedColor; + return 1; +} + +/***************************************************************************** + The Window Object +******************************************************************************/ + +/* Definition of the window type */ + +PyTypeObject PyCursesWindow_Type; + +/* Function prototype macros for Window object + + X - function name + TYPE - parameter Type + ERGSTR - format string for construction of the return value + PARSESTR - format string for argument parsing + */ + +#define Window_NoArgNoReturnFunction(X) \ +static PyObject *PyCursesWindow_ ## X (PyCursesWindowObject *self, PyObject *args) \ +{ return PyCursesCheckERR(X(self->win), # X); } + +#define Window_NoArgTrueFalseFunction(X) \ +static PyObject * PyCursesWindow_ ## X (PyCursesWindowObject *self) \ +{ \ + if (X (self->win) == FALSE) { Py_INCREF(Py_False); return Py_False; } \ + else { Py_INCREF(Py_True); return Py_True; } } + +#define Window_NoArgNoReturnVoidFunction(X) \ +static PyObject * PyCursesWindow_ ## X (PyCursesWindowObject *self) \ +{ \ + X(self->win); Py_INCREF(Py_None); return Py_None; } + +#define Window_NoArg2TupleReturnFunction(X, TYPE, ERGSTR) \ +static PyObject * PyCursesWindow_ ## X (PyCursesWindowObject *self) \ +{ \ + TYPE arg1, arg2; \ + X(self->win,arg1,arg2); return Py_BuildValue(ERGSTR, arg1, arg2); } + +#define Window_OneArgNoReturnVoidFunction(X, TYPE, PARSESTR) \ +static PyObject * PyCursesWindow_ ## X (PyCursesWindowObject *self, PyObject *args) \ +{ \ + TYPE arg1; \ + if (!PyArg_ParseTuple(args, PARSESTR, &arg1)) return NULL; \ + X(self->win,arg1); Py_INCREF(Py_None); return Py_None; } + +#define Window_OneArgNoReturnFunction(X, TYPE, PARSESTR) \ +static PyObject * PyCursesWindow_ ## X (PyCursesWindowObject *self, PyObject *args) \ +{ \ + TYPE arg1; \ + if (!PyArg_ParseTuple(args,PARSESTR, &arg1)) return NULL; \ + return PyCursesCheckERR(X(self->win, arg1), # X); } + +#define Window_TwoArgNoReturnFunction(X, TYPE, PARSESTR) \ +static PyObject * PyCursesWindow_ ## X (PyCursesWindowObject *self, PyObject *args) \ +{ \ + TYPE arg1, arg2; \ + if (!PyArg_ParseTuple(args,PARSESTR, &arg1, &arg2)) return NULL; \ + return PyCursesCheckERR(X(self->win, arg1, arg2), # X); } + +/* ------------- WINDOW routines --------------- */ + +Window_NoArgNoReturnFunction(untouchwin) +Window_NoArgNoReturnFunction(touchwin) +Window_NoArgNoReturnFunction(redrawwin) +Window_NoArgNoReturnFunction(winsertln) +Window_NoArgNoReturnFunction(werase) +Window_NoArgNoReturnFunction(wdeleteln) + +Window_NoArgTrueFalseFunction(is_wintouched) + +Window_NoArgNoReturnVoidFunction(wsyncup) +Window_NoArgNoReturnVoidFunction(wsyncdown) +Window_NoArgNoReturnVoidFunction(wstandend) +Window_NoArgNoReturnVoidFunction(wstandout) +Window_NoArgNoReturnVoidFunction(wcursyncup) +Window_NoArgNoReturnVoidFunction(wclrtoeol) +Window_NoArgNoReturnVoidFunction(wclrtobot) +Window_NoArgNoReturnVoidFunction(wclear) + +Window_OneArgNoReturnVoidFunction(idcok, int, "i;True(1) or False(0)") +Window_OneArgNoReturnVoidFunction(immedok, int, "i;True(1) or False(0)") +Window_OneArgNoReturnVoidFunction(wtimeout, int, "i;delay") + +Window_NoArg2TupleReturnFunction(getyx, int, "ii") +Window_NoArg2TupleReturnFunction(getbegyx, int, "ii") +Window_NoArg2TupleReturnFunction(getmaxyx, int, "ii") +Window_NoArg2TupleReturnFunction(getparyx, int, "ii") + +Window_OneArgNoReturnFunction(clearok, int, "i;True(1) or False(0)") +Window_OneArgNoReturnFunction(idlok, int, "i;True(1) or False(0)") +#if defined(__NetBSD__) +Window_OneArgNoReturnVoidFunction(keypad, int, "i;True(1) or False(0)") +#else +Window_OneArgNoReturnFunction(keypad, int, "i;True(1) or False(0)") +#endif +Window_OneArgNoReturnFunction(leaveok, int, "i;True(1) or False(0)") +#if defined(__NetBSD__) +Window_OneArgNoReturnVoidFunction(nodelay, int, "i;True(1) or False(0)") +#else +Window_OneArgNoReturnFunction(nodelay, int, "i;True(1) or False(0)") +#endif +Window_OneArgNoReturnFunction(notimeout, int, "i;True(1) or False(0)") +Window_OneArgNoReturnFunction(scrollok, int, "i;True(1) or False(0)") +Window_OneArgNoReturnFunction(winsdelln, int, "i;nlines") +Window_OneArgNoReturnFunction(syncok, int, "i;True(1) or False(0)") + +Window_TwoArgNoReturnFunction(mvwin, int, "ii;y,x") +Window_TwoArgNoReturnFunction(mvderwin, int, "ii;y,x") +Window_TwoArgNoReturnFunction(wmove, int, "ii;y,x") +#ifndef STRICT_SYSV_CURSES +Window_TwoArgNoReturnFunction(wresize, int, "ii;lines,columns") +#endif + +/* Allocation and deallocation of Window Objects */ + +static PyObject * +PyCursesWindow_New(WINDOW *win) +{ + PyCursesWindowObject *wo; + + wo = PyObject_NEW(PyCursesWindowObject, &PyCursesWindow_Type); + if (wo == NULL) return NULL; + wo->win = win; + return (PyObject *)wo; +} + +static void +PyCursesWindow_Dealloc(PyCursesWindowObject *wo) +{ + if (wo->win != stdscr) delwin(wo->win); + PyObject_DEL(wo); +} + +/* Addch, Addstr, Addnstr */ + +static PyObject * +PyCursesWindow_AddCh(PyCursesWindowObject *self, PyObject *args) +{ + int rtn, x, y, use_xy = FALSE; + PyObject *temp; + chtype ch = 0; + attr_t attr = A_NORMAL; + long lattr; + + switch (PyTuple_Size(args)) { + case 1: + if (!PyArg_ParseTuple(args, "O;ch or int", &temp)) + return NULL; + break; + case 2: + if (!PyArg_ParseTuple(args, "Ol;ch or int,attr", &temp, &lattr)) + return NULL; + attr = lattr; + break; + case 3: + if (!PyArg_ParseTuple(args,"iiO;y,x,ch or int", &y, &x, &temp)) + return NULL; + use_xy = TRUE; + break; + case 4: + if (!PyArg_ParseTuple(args,"iiOl;y,x,ch or int, attr", + &y, &x, &temp, &lattr)) + return NULL; + attr = lattr; + use_xy = TRUE; + break; + default: + PyErr_SetString(PyExc_TypeError, "addch requires 1 to 4 arguments"); + return NULL; + } + + if (!PyCurses_ConvertToChtype(temp, &ch)) { + PyErr_SetString(PyExc_TypeError, "argument 1 or 3 must be a ch or an int"); + return NULL; + } + + if (use_xy == TRUE) + rtn = mvwaddch(self->win,y,x, ch | attr); + else { + rtn = waddch(self->win, ch | attr); + } + return PyCursesCheckERR(rtn, "addch"); +} + +static PyObject * +PyCursesWindow_AddStr(PyCursesWindowObject *self, PyObject *args) +{ + int rtn; + int x, y; + char *str; + attr_t attr = A_NORMAL , attr_old = A_NORMAL; + long lattr; + int use_xy = FALSE, use_attr = FALSE; + + switch (PyTuple_Size(args)) { + case 1: + if (!PyArg_ParseTuple(args,"s;str", &str)) + return NULL; + break; + case 2: + if (!PyArg_ParseTuple(args,"sl;str,attr", &str, &lattr)) + return NULL; + attr = lattr; + use_attr = TRUE; + break; + case 3: + if (!PyArg_ParseTuple(args,"iis;int,int,str", &y, &x, &str)) + return NULL; + use_xy = TRUE; + break; + case 4: + if (!PyArg_ParseTuple(args,"iisl;int,int,str,attr", &y, &x, &str, &lattr)) + return NULL; + attr = lattr; + use_xy = use_attr = TRUE; + break; + default: + PyErr_SetString(PyExc_TypeError, "addstr requires 1 to 4 arguments"); + return NULL; + } + + if (use_attr == TRUE) { + attr_old = getattrs(self->win); + (void)wattrset(self->win,attr); + } + if (use_xy == TRUE) + rtn = mvwaddstr(self->win,y,x,str); + else + rtn = waddstr(self->win,str); + if (use_attr == TRUE) + (void)wattrset(self->win,attr_old); + return PyCursesCheckERR(rtn, "addstr"); +} + +static PyObject * +PyCursesWindow_AddNStr(PyCursesWindowObject *self, PyObject *args) +{ + int rtn, x, y, n; + char *str; + attr_t attr = A_NORMAL , attr_old = A_NORMAL; + long lattr; + int use_xy = FALSE, use_attr = FALSE; + + switch (PyTuple_Size(args)) { + case 2: + if (!PyArg_ParseTuple(args,"si;str,n", &str, &n)) + return NULL; + break; + case 3: + if (!PyArg_ParseTuple(args,"sil;str,n,attr", &str, &n, &lattr)) + return NULL; + attr = lattr; + use_attr = TRUE; + break; + case 4: + if (!PyArg_ParseTuple(args,"iisi;y,x,str,n", &y, &x, &str, &n)) + return NULL; + use_xy = TRUE; + break; + case 5: + if (!PyArg_ParseTuple(args,"iisil;y,x,str,n,attr", &y, &x, &str, &n, &lattr)) + return NULL; + attr = lattr; + use_xy = use_attr = TRUE; + break; + default: + PyErr_SetString(PyExc_TypeError, "addnstr requires 2 to 5 arguments"); + return NULL; + } + + if (use_attr == TRUE) { + attr_old = getattrs(self->win); + (void)wattrset(self->win,attr); + } + if (use_xy == TRUE) + rtn = mvwaddnstr(self->win,y,x,str,n); + else + rtn = waddnstr(self->win,str,n); + if (use_attr == TRUE) + (void)wattrset(self->win,attr_old); + return PyCursesCheckERR(rtn, "addnstr"); +} + +static PyObject * +PyCursesWindow_Bkgd(PyCursesWindowObject *self, PyObject *args) +{ + PyObject *temp; + chtype bkgd; + attr_t attr = A_NORMAL; + long lattr; + + switch (PyTuple_Size(args)) { + case 1: + if (!PyArg_ParseTuple(args, "O;ch or int", &temp)) + return NULL; + break; + case 2: + if (!PyArg_ParseTuple(args,"Ol;ch or int,attr", &temp, &lattr)) + return NULL; + attr = lattr; + break; + default: + PyErr_SetString(PyExc_TypeError, "bkgd requires 1 or 2 arguments"); + return NULL; + } + + if (!PyCurses_ConvertToChtype(temp, &bkgd)) { + PyErr_SetString(PyExc_TypeError, "argument 1 or 3 must be a ch or an int"); + return NULL; + } + + return PyCursesCheckERR(wbkgd(self->win, bkgd | attr), "bkgd"); +} + +static PyObject * +PyCursesWindow_AttrOff(PyCursesWindowObject *self, PyObject *args) +{ + long lattr; + if (!PyArg_ParseTuple(args,"l;attr", &lattr)) + return NULL; + return PyCursesCheckERR(wattroff(self->win, (attr_t)lattr), "attroff"); +} + +static PyObject * +PyCursesWindow_AttrOn(PyCursesWindowObject *self, PyObject *args) +{ + long lattr; + if (!PyArg_ParseTuple(args,"l;attr", &lattr)) + return NULL; + return PyCursesCheckERR(wattron(self->win, (attr_t)lattr), "attron"); +} + +static PyObject * +PyCursesWindow_AttrSet(PyCursesWindowObject *self, PyObject *args) +{ + long lattr; + if (!PyArg_ParseTuple(args,"l;attr", &lattr)) + return NULL; + return PyCursesCheckERR(wattrset(self->win, (attr_t)lattr), "attrset"); +} + +static PyObject * +PyCursesWindow_BkgdSet(PyCursesWindowObject *self, PyObject *args) +{ + PyObject *temp; + chtype bkgd; + attr_t attr = A_NORMAL; + long lattr; + + switch (PyTuple_Size(args)) { + case 1: + if (!PyArg_ParseTuple(args, "O;ch or int", &temp)) + return NULL; + break; + case 2: + if (!PyArg_ParseTuple(args,"Ol;ch or int,attr", &temp, &lattr)) + return NULL; + attr = lattr; + break; + default: + PyErr_SetString(PyExc_TypeError, "bkgdset requires 1 or 2 arguments"); + return NULL; + } + + if (!PyCurses_ConvertToChtype(temp, &bkgd)) { + PyErr_SetString(PyExc_TypeError, "argument 1 must be a ch or an int"); + return NULL; + } + + wbkgdset(self->win, bkgd | attr); + return PyCursesCheckERR(0, "bkgdset"); +} + +static PyObject * +PyCursesWindow_Border(PyCursesWindowObject *self, PyObject *args) +{ + PyObject *temp[8]; + chtype ch[8]; + int i; + + /* Clear the array of parameters */ + for(i=0; i<8; i++) { + temp[i] = NULL; + ch[i] = 0; + } + + if (!PyArg_ParseTuple(args,"|OOOOOOOO;ls,rs,ts,bs,tl,tr,bl,br", + &temp[0], &temp[1], &temp[2], &temp[3], + &temp[4], &temp[5], &temp[6], &temp[7])) + return NULL; + + for(i=0; i<8; i++) { + if (temp[i] != NULL && !PyCurses_ConvertToChtype(temp[i], &ch[i])) { + PyErr_Format(PyExc_TypeError, + "argument %i must be a ch or an int", i+1); + return NULL; + } + } + + wborder(self->win, + ch[0], ch[1], ch[2], ch[3], + ch[4], ch[5], ch[6], ch[7]); + Py_INCREF(Py_None); + return Py_None; +} + +static PyObject * +PyCursesWindow_Box(PyCursesWindowObject *self, PyObject *args) +{ + chtype ch1=0,ch2=0; + switch(PyTuple_Size(args)){ + case 0: break; + default: + if (!PyArg_ParseTuple(args,"ll;vertint,horint", &ch1, &ch2)) + return NULL; + } + box(self->win,ch1,ch2); + Py_INCREF(Py_None); + return Py_None; +} + +#if defined(HAVE_NCURSES_H) || defined(MVWDELCH_IS_EXPRESSION) +#define py_mvwdelch mvwdelch +#else +int py_mvwdelch(WINDOW *w, int y, int x) +{ + mvwdelch(w,y,x); + /* On HP/UX, mvwdelch already returns. On other systems, + we may well run into this return statement. */ + return 0; +} +#endif + +/* chgat, added by Fabian Kreutz */ + +static PyObject * +PyCursesWindow_ChgAt(PyCursesWindowObject *self, PyObject *args) +{ + int rtn; + int x, y; + int num = -1; + short color; + attr_t attr = A_NORMAL; + long lattr; + int use_xy = FALSE; + + switch (PyTuple_Size(args)) { + case 1: + if (!PyArg_ParseTuple(args,"l;attr", &lattr)) + return NULL; + attr = lattr; + break; + case 2: + if (!PyArg_ParseTuple(args,"il;n,attr", &num, &lattr)) + return NULL; + attr = lattr; + break; + case 3: + if (!PyArg_ParseTuple(args,"iil;int,int,attr", &y, &x, &lattr)) + return NULL; + attr = lattr; + use_xy = TRUE; + break; + case 4: + if (!PyArg_ParseTuple(args,"iiil;int,int,n,attr", &y, &x, &num, &lattr)) + return NULL; + attr = lattr; + use_xy = TRUE; + break; + default: + PyErr_SetString(PyExc_TypeError, "chgat requires 1 to 4 arguments"); + return NULL; + } + + color = (short)((attr >> 8) & 0xff); + attr = attr - (color << 8); + + if (use_xy == TRUE) { + rtn = mvwchgat(self->win,y,x,num,attr,color,NULL); + touchline(self->win,y,1); + } else { + getyx(self->win,y,x); + rtn = wchgat(self->win,num,attr,color,NULL); + touchline(self->win,y,1); + } + return PyCursesCheckERR(rtn, "chgat"); +} + + +static PyObject * +PyCursesWindow_DelCh(PyCursesWindowObject *self, PyObject *args) +{ + int rtn; + int x, y; + + switch (PyTuple_Size(args)) { + case 0: + rtn = wdelch(self->win); + break; + case 2: + if (!PyArg_ParseTuple(args,"ii;y,x", &y, &x)) + return NULL; + rtn = py_mvwdelch(self->win,y,x); + break; + default: + PyErr_SetString(PyExc_TypeError, "delch requires 0 or 2 arguments"); + return NULL; + } + return PyCursesCheckERR(rtn, "[mv]wdelch"); +} + +static PyObject * +PyCursesWindow_DerWin(PyCursesWindowObject *self, PyObject *args) +{ + WINDOW *win; + int nlines, ncols, begin_y, begin_x; + + nlines = 0; + ncols = 0; + switch (PyTuple_Size(args)) { + case 2: + if (!PyArg_ParseTuple(args,"ii;begin_y,begin_x",&begin_y,&begin_x)) + return NULL; + break; + case 4: + if (!PyArg_ParseTuple(args, "iiii;nlines,ncols,begin_y,begin_x", + &nlines,&ncols,&begin_y,&begin_x)) + return NULL; + break; + default: + PyErr_SetString(PyExc_TypeError, "derwin requires 2 or 4 arguments"); + return NULL; + } + + win = derwin(self->win,nlines,ncols,begin_y,begin_x); + + if (win == NULL) { + PyErr_SetString(PyCursesError, catchall_NULL); + return NULL; + } + + return (PyObject *)PyCursesWindow_New(win); +} + +static PyObject * +PyCursesWindow_EchoChar(PyCursesWindowObject *self, PyObject *args) +{ + PyObject *temp; + chtype ch; + attr_t attr = A_NORMAL; + long lattr; + + switch (PyTuple_Size(args)) { + case 1: + if (!PyArg_ParseTuple(args,"O;ch or int", &temp)) + return NULL; + break; + case 2: + if (!PyArg_ParseTuple(args,"Ol;ch or int,attr", &temp, &lattr)) + return NULL; + attr = lattr; + break; + default: + PyErr_SetString(PyExc_TypeError, "echochar requires 1 or 2 arguments"); + + + return NULL; + } + + if (!PyCurses_ConvertToChtype(temp, &ch)) { + PyErr_SetString(PyExc_TypeError, "argument 1 must be a ch or an int"); + return NULL; + } + +#ifdef WINDOW_HAS_FLAGS + if (self->win->_flags & _ISPAD) + return PyCursesCheckERR(pechochar(self->win, ch | attr), + "echochar"); + else +#endif + return PyCursesCheckERR(wechochar(self->win, ch | attr), + "echochar"); +} + +#ifdef NCURSES_MOUSE_VERSION +static PyObject * +PyCursesWindow_Enclose(PyCursesWindowObject *self, PyObject *args) +{ + int x, y; + if (!PyArg_ParseTuple(args,"ii;y,x", &y, &x)) + return NULL; + + return PyInt_FromLong( wenclose(self->win,y,x) ); +} +#endif + +static PyObject * +PyCursesWindow_GetBkgd(PyCursesWindowObject *self) +{ + return PyInt_FromLong((long) getbkgd(self->win)); +} + +static PyObject * +PyCursesWindow_GetCh(PyCursesWindowObject *self, PyObject *args) +{ + int x, y; + int rtn; + + switch (PyTuple_Size(args)) { + case 0: + Py_BEGIN_ALLOW_THREADS + rtn = wgetch(self->win); + Py_END_ALLOW_THREADS + break; + case 2: + if (!PyArg_ParseTuple(args,"ii;y,x",&y,&x)) + return NULL; + Py_BEGIN_ALLOW_THREADS + rtn = mvwgetch(self->win,y,x); + Py_END_ALLOW_THREADS + break; + default: + PyErr_SetString(PyExc_TypeError, "getch requires 0 or 2 arguments"); + return NULL; + } + return PyInt_FromLong((long)rtn); +} + +static PyObject * +PyCursesWindow_GetKey(PyCursesWindowObject *self, PyObject *args) +{ + int x, y; + int rtn; + + switch (PyTuple_Size(args)) { + case 0: + Py_BEGIN_ALLOW_THREADS + rtn = wgetch(self->win); + Py_END_ALLOW_THREADS + break; + case 2: + if (!PyArg_ParseTuple(args,"ii;y,x",&y,&x)) + return NULL; + Py_BEGIN_ALLOW_THREADS + rtn = mvwgetch(self->win,y,x); + Py_END_ALLOW_THREADS + break; + default: + PyErr_SetString(PyExc_TypeError, "getkey requires 0 or 2 arguments"); + return NULL; + } + if (rtn == ERR) { + /* getch() returns ERR in nodelay mode */ + PyErr_SetString(PyCursesError, "no input"); + return NULL; + } else if (rtn<=255) { + return Py_BuildValue("c", rtn); + } else { + const char *knp; +#if defined(__NetBSD__) + knp = unctrl(rtn); +#else + knp = keyname(rtn); +#endif + return PyString_FromString((knp == NULL) ? "" : knp); + } +} + +static PyObject * +PyCursesWindow_GetStr(PyCursesWindowObject *self, PyObject *args) +{ + int x, y, n; + char rtn[1024]; /* This should be big enough.. I hope */ + int rtn2; + + switch (PyTuple_Size(args)) { + case 0: + Py_BEGIN_ALLOW_THREADS + rtn2 = wgetnstr(self->win,rtn, 1023); + Py_END_ALLOW_THREADS + break; + case 1: + if (!PyArg_ParseTuple(args,"i;n", &n)) + return NULL; + Py_BEGIN_ALLOW_THREADS + rtn2 = wgetnstr(self->win,rtn,MIN(n, 1023)); + Py_END_ALLOW_THREADS + break; + case 2: + if (!PyArg_ParseTuple(args,"ii;y,x",&y,&x)) + return NULL; + Py_BEGIN_ALLOW_THREADS +#ifdef STRICT_SYSV_CURSES + rtn2 = wmove(self->win,y,x)==ERR ? ERR : wgetnstr(self->win, rtn, 1023); +#else + rtn2 = mvwgetnstr(self->win,y,x,rtn, 1023); +#endif + Py_END_ALLOW_THREADS + break; + case 3: + if (!PyArg_ParseTuple(args,"iii;y,x,n", &y, &x, &n)) + return NULL; +#ifdef STRICT_SYSV_CURSES + Py_BEGIN_ALLOW_THREADS + rtn2 = wmove(self->win,y,x)==ERR ? ERR : + wgetnstr(self->win, rtn, MIN(n, 1023)); + Py_END_ALLOW_THREADS +#else + Py_BEGIN_ALLOW_THREADS + rtn2 = mvwgetnstr(self->win, y, x, rtn, MIN(n, 1023)); + Py_END_ALLOW_THREADS +#endif + break; + default: + PyErr_SetString(PyExc_TypeError, "getstr requires 0 to 3 arguments"); + return NULL; + } + if (rtn2 == ERR) + rtn[0] = 0; + return PyString_FromString(rtn); +} + +static PyObject * +PyCursesWindow_Hline(PyCursesWindowObject *self, PyObject *args) +{ + PyObject *temp; + chtype ch; + int n, x, y, code = OK; + attr_t attr = A_NORMAL; + long lattr; + + switch (PyTuple_Size(args)) { + case 2: + if (!PyArg_ParseTuple(args, "Oi;ch or int,n", &temp, &n)) + return NULL; + break; + case 3: + if (!PyArg_ParseTuple(args, "Oil;ch or int,n,attr", &temp, &n, &lattr)) + return NULL; + attr = lattr; + break; + case 4: + if (!PyArg_ParseTuple(args, "iiOi;y,x,ch or int,n", &y, &x, &temp, &n)) + return NULL; + code = wmove(self->win, y, x); + break; + case 5: + if (!PyArg_ParseTuple(args, "iiOil; y,x,ch or int,n,attr", + &y, &x, &temp, &n, &lattr)) + return NULL; + attr = lattr; + code = wmove(self->win, y, x); + break; + default: + PyErr_SetString(PyExc_TypeError, "hline requires 2 to 5 arguments"); + return NULL; + } + + if (code != ERR) { + if (!PyCurses_ConvertToChtype(temp, &ch)) { + PyErr_SetString(PyExc_TypeError, + "argument 1 or 3 must be a ch or an int"); + return NULL; + } + return PyCursesCheckERR(whline(self->win, ch | attr, n), "hline"); + } else + return PyCursesCheckERR(code, "wmove"); +} + +static PyObject * +PyCursesWindow_InsCh(PyCursesWindowObject *self, PyObject *args) +{ + int rtn, x, y, use_xy = FALSE; + PyObject *temp; + chtype ch = 0; + attr_t attr = A_NORMAL; + long lattr; + + switch (PyTuple_Size(args)) { + case 1: + if (!PyArg_ParseTuple(args, "O;ch or int", &temp)) + return NULL; + break; + case 2: + if (!PyArg_ParseTuple(args, "Ol;ch or int,attr", &temp, &lattr)) + return NULL; + attr = lattr; + break; + case 3: + if (!PyArg_ParseTuple(args,"iiO;y,x,ch or int", &y, &x, &temp)) + return NULL; + use_xy = TRUE; + break; + case 4: + if (!PyArg_ParseTuple(args,"iiOl;y,x,ch or int, attr", &y, &x, &temp, &lattr)) + return NULL; + attr = lattr; + use_xy = TRUE; + break; + default: + PyErr_SetString(PyExc_TypeError, "insch requires 1 or 4 arguments"); + return NULL; + } + + if (!PyCurses_ConvertToChtype(temp, &ch)) { + PyErr_SetString(PyExc_TypeError, + "argument 1 or 3 must be a ch or an int"); + return NULL; + } + + if (use_xy == TRUE) + rtn = mvwinsch(self->win,y,x, ch | attr); + else { + rtn = winsch(self->win, ch | attr); + } + return PyCursesCheckERR(rtn, "insch"); +} + +static PyObject * +PyCursesWindow_InCh(PyCursesWindowObject *self, PyObject *args) +{ + int x, y, rtn; + + switch (PyTuple_Size(args)) { + case 0: + rtn = winch(self->win); + break; + case 2: + if (!PyArg_ParseTuple(args,"ii;y,x",&y,&x)) + return NULL; + rtn = mvwinch(self->win,y,x); + break; + default: + PyErr_SetString(PyExc_TypeError, "inch requires 0 or 2 arguments"); + return NULL; + } + return PyInt_FromLong((long) rtn); +} + +static PyObject * +PyCursesWindow_InStr(PyCursesWindowObject *self, PyObject *args) +{ + int x, y, n; + char rtn[1024]; /* This should be big enough.. I hope */ + int rtn2; + + switch (PyTuple_Size(args)) { + case 0: + rtn2 = winnstr(self->win,rtn, 1023); + break; + case 1: + if (!PyArg_ParseTuple(args,"i;n", &n)) + return NULL; + rtn2 = winnstr(self->win,rtn,MIN(n,1023)); + break; + case 2: + if (!PyArg_ParseTuple(args,"ii;y,x",&y,&x)) + return NULL; + rtn2 = mvwinnstr(self->win,y,x,rtn,1023); + break; + case 3: + if (!PyArg_ParseTuple(args, "iii;y,x,n", &y, &x, &n)) + return NULL; + rtn2 = mvwinnstr(self->win, y, x, rtn, MIN(n,1023)); + break; + default: + PyErr_SetString(PyExc_TypeError, "instr requires 0 or 3 arguments"); + return NULL; + } + if (rtn2 == ERR) + rtn[0] = 0; + return PyString_FromString(rtn); +} + +static PyObject * +PyCursesWindow_InsStr(PyCursesWindowObject *self, PyObject *args) +{ + int rtn; + int x, y; + char *str; + attr_t attr = A_NORMAL , attr_old = A_NORMAL; + long lattr; + int use_xy = FALSE, use_attr = FALSE; + + switch (PyTuple_Size(args)) { + case 1: + if (!PyArg_ParseTuple(args,"s;str", &str)) + return NULL; + break; + case 2: + if (!PyArg_ParseTuple(args,"sl;str,attr", &str, &lattr)) + return NULL; + attr = lattr; + use_attr = TRUE; + break; + case 3: + if (!PyArg_ParseTuple(args,"iis;y,x,str", &y, &x, &str)) + return NULL; + use_xy = TRUE; + break; + case 4: + if (!PyArg_ParseTuple(args,"iisl;y,x,str,attr", &y, &x, &str, &lattr)) + return NULL; + attr = lattr; + use_xy = use_attr = TRUE; + break; + default: + PyErr_SetString(PyExc_TypeError, "insstr requires 1 to 4 arguments"); + return NULL; + } + + if (use_attr == TRUE) { + attr_old = getattrs(self->win); + (void)wattrset(self->win,attr); + } + if (use_xy == TRUE) + rtn = mvwinsstr(self->win,y,x,str); + else + rtn = winsstr(self->win,str); + if (use_attr == TRUE) + (void)wattrset(self->win,attr_old); + return PyCursesCheckERR(rtn, "insstr"); +} + +static PyObject * +PyCursesWindow_InsNStr(PyCursesWindowObject *self, PyObject *args) +{ + int rtn, x, y, n; + char *str; + attr_t attr = A_NORMAL , attr_old = A_NORMAL; + long lattr; + int use_xy = FALSE, use_attr = FALSE; + + switch (PyTuple_Size(args)) { + case 2: + if (!PyArg_ParseTuple(args,"si;str,n", &str, &n)) + return NULL; + break; + case 3: + if (!PyArg_ParseTuple(args,"sil;str,n,attr", &str, &n, &lattr)) + return NULL; + attr = lattr; + use_attr = TRUE; + break; + case 4: + if (!PyArg_ParseTuple(args,"iisi;y,x,str,n", &y, &x, &str, &n)) + return NULL; + use_xy = TRUE; + break; + case 5: + if (!PyArg_ParseTuple(args,"iisil;y,x,str,n,attr", &y, &x, &str, &n, &lattr)) + return NULL; + attr = lattr; + use_xy = use_attr = TRUE; + break; + default: + PyErr_SetString(PyExc_TypeError, "insnstr requires 2 to 5 arguments"); + return NULL; + } + + if (use_attr == TRUE) { + attr_old = getattrs(self->win); + (void)wattrset(self->win,attr); + } + if (use_xy == TRUE) + rtn = mvwinsnstr(self->win,y,x,str,n); + else + rtn = winsnstr(self->win,str,n); + if (use_attr == TRUE) + (void)wattrset(self->win,attr_old); + return PyCursesCheckERR(rtn, "insnstr"); +} + +static PyObject * +PyCursesWindow_Is_LineTouched(PyCursesWindowObject *self, PyObject *args) +{ + int line, erg; + if (!PyArg_ParseTuple(args,"i;line", &line)) + return NULL; + erg = is_linetouched(self->win, line); + if (erg == ERR) { + PyErr_SetString(PyExc_TypeError, + "is_linetouched: line number outside of boundaries"); + return NULL; + } else + if (erg == FALSE) { + Py_INCREF(Py_False); + return Py_False; + } else { + Py_INCREF(Py_True); + return Py_True; + } +} + +static PyObject * +PyCursesWindow_NoOutRefresh(PyCursesWindowObject *self, PyObject *args) +{ + int pminrow,pmincol,sminrow,smincol,smaxrow,smaxcol; + int rtn; + +#ifndef WINDOW_HAS_FLAGS + if (0) +#else + if (self->win->_flags & _ISPAD) +#endif + { + switch(PyTuple_Size(args)) { + case 6: + if (!PyArg_ParseTuple(args, + "iiiiii;" \ + "pminrow,pmincol,sminrow,smincol,smaxrow,smaxcol", + &pminrow, &pmincol, &sminrow, + &smincol, &smaxrow, &smaxcol)) + return NULL; + Py_BEGIN_ALLOW_THREADS + rtn = pnoutrefresh(self->win, + pminrow, pmincol, sminrow, + smincol, smaxrow, smaxcol); + Py_END_ALLOW_THREADS + return PyCursesCheckERR(rtn, "pnoutrefresh"); + default: + PyErr_SetString(PyCursesError, + "noutrefresh() called for a pad " + "requires 6 arguments"); + return NULL; + } + } else { + if (!PyArg_ParseTuple(args, ":noutrefresh")) + return NULL; + + Py_BEGIN_ALLOW_THREADS + rtn = wnoutrefresh(self->win); + Py_END_ALLOW_THREADS + return PyCursesCheckERR(rtn, "wnoutrefresh"); + } +} + +static PyObject * +PyCursesWindow_Overlay(PyCursesWindowObject *self, PyObject *args) +{ + PyCursesWindowObject *temp; + int use_copywin = FALSE; + int sminrow, smincol, dminrow, dmincol, dmaxrow, dmaxcol; + int rtn; + + switch (PyTuple_Size(args)) { + case 1: + if (!PyArg_ParseTuple(args, "O!;window object", + &PyCursesWindow_Type, &temp)) + return NULL; + break; + case 7: + if (!PyArg_ParseTuple(args, "O!iiiiii;window object, int, int, int, int, int, int", + &PyCursesWindow_Type, &temp, &sminrow, &smincol, + &dminrow, &dmincol, &dmaxrow, &dmaxcol)) + return NULL; + use_copywin = TRUE; + break; + default: + PyErr_SetString(PyExc_TypeError, + "overlay requires one or seven arguments"); + return NULL; + } + + if (use_copywin == TRUE) { + rtn = copywin(self->win, temp->win, sminrow, smincol, + dminrow, dmincol, dmaxrow, dmaxcol, TRUE); + return PyCursesCheckERR(rtn, "copywin"); + } + else { + rtn = overlay(self->win, temp->win); + return PyCursesCheckERR(rtn, "overlay"); + } +} + +static PyObject * +PyCursesWindow_Overwrite(PyCursesWindowObject *self, PyObject *args) +{ + PyCursesWindowObject *temp; + int use_copywin = FALSE; + int sminrow, smincol, dminrow, dmincol, dmaxrow, dmaxcol; + int rtn; + + switch (PyTuple_Size(args)) { + case 1: + if (!PyArg_ParseTuple(args, "O!;window object", + &PyCursesWindow_Type, &temp)) + return NULL; + break; + case 7: + if (!PyArg_ParseTuple(args, "O!iiiiii;window object, int, int, int, int, int, int", + &PyCursesWindow_Type, &temp, &sminrow, &smincol, + &dminrow, &dmincol, &dmaxrow, &dmaxcol)) + return NULL; + use_copywin = TRUE; + break; + default: + PyErr_SetString(PyExc_TypeError, + "overwrite requires one or seven arguments"); + return NULL; + } + + if (use_copywin == TRUE) { + rtn = copywin(self->win, temp->win, sminrow, smincol, + dminrow, dmincol, dmaxrow, dmaxcol, FALSE); + return PyCursesCheckERR(rtn, "copywin"); + } + else { + rtn = overwrite(self->win, temp->win); + return PyCursesCheckERR(rtn, "overwrite"); + } +} + +static PyObject * +PyCursesWindow_PutWin(PyCursesWindowObject *self, PyObject *args) +{ + PyObject *temp; + + if (!PyArg_ParseTuple(args, "O;fileobj", &temp)) + return NULL; + if (!PyFile_Check(temp)) { + PyErr_SetString(PyExc_TypeError, "argument must be a file object"); + return NULL; + } + return PyCursesCheckERR(putwin(self->win, PyFile_AsFile(temp)), + "putwin"); +} + +static PyObject * +PyCursesWindow_RedrawLine(PyCursesWindowObject *self, PyObject *args) +{ + int beg, num; + if (!PyArg_ParseTuple(args, "ii;beg,num", &beg, &num)) + return NULL; + return PyCursesCheckERR(wredrawln(self->win,beg,num), "redrawln"); +} + +static PyObject * +PyCursesWindow_Refresh(PyCursesWindowObject *self, PyObject *args) +{ + int pminrow,pmincol,sminrow,smincol,smaxrow,smaxcol; + int rtn; + +#ifndef WINDOW_HAS_FLAGS + if (0) +#else + if (self->win->_flags & _ISPAD) +#endif + { + switch(PyTuple_Size(args)) { + case 6: + if (!PyArg_ParseTuple(args, + "iiiiii;" \ + "pminrow,pmincol,sminrow,smincol,smaxrow,smaxcol", + &pminrow, &pmincol, &sminrow, + &smincol, &smaxrow, &smaxcol)) + return NULL; + + Py_BEGIN_ALLOW_THREADS + rtn = prefresh(self->win, + pminrow, pmincol, sminrow, + smincol, smaxrow, smaxcol); + Py_END_ALLOW_THREADS + return PyCursesCheckERR(rtn, "prefresh"); + default: + PyErr_SetString(PyCursesError, + "refresh() for a pad requires 6 arguments"); + return NULL; + } + } else { + if (!PyArg_ParseTuple(args, ":refresh")) + return NULL; + Py_BEGIN_ALLOW_THREADS + rtn = wrefresh(self->win); + Py_END_ALLOW_THREADS + return PyCursesCheckERR(rtn, "prefresh"); + } +} + +static PyObject * +PyCursesWindow_SetScrollRegion(PyCursesWindowObject *self, PyObject *args) +{ + int x, y; + if (!PyArg_ParseTuple(args,"ii;top, bottom",&y,&x)) + return NULL; + return PyCursesCheckERR(wsetscrreg(self->win,y,x), "wsetscrreg"); +} + +static PyObject * +PyCursesWindow_SubWin(PyCursesWindowObject *self, PyObject *args) +{ + WINDOW *win; + int nlines, ncols, begin_y, begin_x; + + nlines = 0; + ncols = 0; + switch (PyTuple_Size(args)) { + case 2: + if (!PyArg_ParseTuple(args,"ii;begin_y,begin_x",&begin_y,&begin_x)) + return NULL; + break; + case 4: + if (!PyArg_ParseTuple(args, "iiii;nlines,ncols,begin_y,begin_x", + &nlines,&ncols,&begin_y,&begin_x)) + return NULL; + break; + default: + PyErr_SetString(PyExc_TypeError, "subwin requires 2 or 4 arguments"); + return NULL; + } + + /* printf("Subwin: %i %i %i %i \n", nlines, ncols, begin_y, begin_x); */ +#ifdef WINDOW_HAS_FLAGS + if (self->win->_flags & _ISPAD) + win = subpad(self->win, nlines, ncols, begin_y, begin_x); + else +#endif + win = subwin(self->win, nlines, ncols, begin_y, begin_x); + + if (win == NULL) { + PyErr_SetString(PyCursesError, catchall_NULL); + return NULL; + } + + return (PyObject *)PyCursesWindow_New(win); +} + +static PyObject * +PyCursesWindow_Scroll(PyCursesWindowObject *self, PyObject *args) +{ + int nlines; + switch(PyTuple_Size(args)) { + case 0: + return PyCursesCheckERR(scroll(self->win), "scroll"); + case 1: + if (!PyArg_ParseTuple(args, "i;nlines", &nlines)) + return NULL; + return PyCursesCheckERR(wscrl(self->win, nlines), "scroll"); + default: + PyErr_SetString(PyExc_TypeError, "scroll requires 0 or 1 arguments"); + return NULL; + } +} + +static PyObject * +PyCursesWindow_TouchLine(PyCursesWindowObject *self, PyObject *args) +{ + int st, cnt, val; + switch (PyTuple_Size(args)) { + case 2: + if (!PyArg_ParseTuple(args,"ii;start,count",&st,&cnt)) + return NULL; + return PyCursesCheckERR(touchline(self->win,st,cnt), "touchline"); + case 3: + if (!PyArg_ParseTuple(args, "iii;start,count,val", &st, &cnt, &val)) + return NULL; + return PyCursesCheckERR(wtouchln(self->win, st, cnt, val), "touchline"); + default: + PyErr_SetString(PyExc_TypeError, "touchline requires 2 or 3 arguments"); + return NULL; + } +} + +static PyObject * +PyCursesWindow_Vline(PyCursesWindowObject *self, PyObject *args) +{ + PyObject *temp; + chtype ch; + int n, x, y, code = OK; + attr_t attr = A_NORMAL; + long lattr; + + switch (PyTuple_Size(args)) { + case 2: + if (!PyArg_ParseTuple(args, "Oi;ch or int,n", &temp, &n)) + return NULL; + break; + case 3: + if (!PyArg_ParseTuple(args, "Oil;ch or int,n,attr", &temp, &n, &lattr)) + return NULL; + attr = lattr; + break; + case 4: + if (!PyArg_ParseTuple(args, "iiOi;y,x,ch or int,n", &y, &x, &temp, &n)) + return NULL; + code = wmove(self->win, y, x); + break; + case 5: + if (!PyArg_ParseTuple(args, "iiOil; y,x,ch or int,n,attr", + &y, &x, &temp, &n, &lattr)) + return NULL; + attr = lattr; + code = wmove(self->win, y, x); + break; + default: + PyErr_SetString(PyExc_TypeError, "vline requires 2 to 5 arguments"); + return NULL; + } + + if (code != ERR) { + if (!PyCurses_ConvertToChtype(temp, &ch)) { + PyErr_SetString(PyExc_TypeError, + "argument 1 or 3 must be a ch or an int"); + return NULL; + } + return PyCursesCheckERR(wvline(self->win, ch | attr, n), "vline"); + } else + return PyCursesCheckERR(code, "wmove"); +} + +static PyMethodDef PyCursesWindow_Methods[] = { + {"addch", (PyCFunction)PyCursesWindow_AddCh, METH_VARARGS}, + {"addnstr", (PyCFunction)PyCursesWindow_AddNStr, METH_VARARGS}, + {"addstr", (PyCFunction)PyCursesWindow_AddStr, METH_VARARGS}, + {"attroff", (PyCFunction)PyCursesWindow_AttrOff, METH_VARARGS}, + {"attron", (PyCFunction)PyCursesWindow_AttrOn, METH_VARARGS}, + {"attrset", (PyCFunction)PyCursesWindow_AttrSet, METH_VARARGS}, + {"bkgd", (PyCFunction)PyCursesWindow_Bkgd, METH_VARARGS}, + {"chgat", (PyCFunction)PyCursesWindow_ChgAt, METH_VARARGS}, + {"bkgdset", (PyCFunction)PyCursesWindow_BkgdSet, METH_VARARGS}, + {"border", (PyCFunction)PyCursesWindow_Border, METH_VARARGS}, + {"box", (PyCFunction)PyCursesWindow_Box, METH_VARARGS}, + {"clear", (PyCFunction)PyCursesWindow_wclear, METH_NOARGS}, + {"clearok", (PyCFunction)PyCursesWindow_clearok, METH_VARARGS}, + {"clrtobot", (PyCFunction)PyCursesWindow_wclrtobot, METH_NOARGS}, + {"clrtoeol", (PyCFunction)PyCursesWindow_wclrtoeol, METH_NOARGS}, + {"cursyncup", (PyCFunction)PyCursesWindow_wcursyncup, METH_NOARGS}, + {"delch", (PyCFunction)PyCursesWindow_DelCh, METH_VARARGS}, + {"deleteln", (PyCFunction)PyCursesWindow_wdeleteln, METH_NOARGS}, + {"derwin", (PyCFunction)PyCursesWindow_DerWin, METH_VARARGS}, + {"echochar", (PyCFunction)PyCursesWindow_EchoChar, METH_VARARGS}, +#ifdef NCURSES_MOUSE_VERSION + {"enclose", (PyCFunction)PyCursesWindow_Enclose, METH_VARARGS}, +#endif + {"erase", (PyCFunction)PyCursesWindow_werase, METH_NOARGS}, + {"getbegyx", (PyCFunction)PyCursesWindow_getbegyx, METH_NOARGS}, + {"getbkgd", (PyCFunction)PyCursesWindow_GetBkgd, METH_NOARGS}, + {"getch", (PyCFunction)PyCursesWindow_GetCh, METH_VARARGS}, + {"getkey", (PyCFunction)PyCursesWindow_GetKey, METH_VARARGS}, + {"getmaxyx", (PyCFunction)PyCursesWindow_getmaxyx, METH_NOARGS}, + {"getparyx", (PyCFunction)PyCursesWindow_getparyx, METH_NOARGS}, + {"getstr", (PyCFunction)PyCursesWindow_GetStr, METH_VARARGS}, + {"getyx", (PyCFunction)PyCursesWindow_getyx, METH_NOARGS}, + {"hline", (PyCFunction)PyCursesWindow_Hline, METH_VARARGS}, + {"idcok", (PyCFunction)PyCursesWindow_idcok, METH_VARARGS}, + {"idlok", (PyCFunction)PyCursesWindow_idlok, METH_VARARGS}, + {"immedok", (PyCFunction)PyCursesWindow_immedok, METH_VARARGS}, + {"inch", (PyCFunction)PyCursesWindow_InCh, METH_VARARGS}, + {"insch", (PyCFunction)PyCursesWindow_InsCh, METH_VARARGS}, + {"insdelln", (PyCFunction)PyCursesWindow_winsdelln, METH_VARARGS}, + {"insertln", (PyCFunction)PyCursesWindow_winsertln, METH_NOARGS}, + {"insnstr", (PyCFunction)PyCursesWindow_InsNStr, METH_VARARGS}, + {"insstr", (PyCFunction)PyCursesWindow_InsStr, METH_VARARGS}, + {"instr", (PyCFunction)PyCursesWindow_InStr, METH_VARARGS}, + {"is_linetouched", (PyCFunction)PyCursesWindow_Is_LineTouched, METH_VARARGS}, + {"is_wintouched", (PyCFunction)PyCursesWindow_is_wintouched, METH_NOARGS}, + {"keypad", (PyCFunction)PyCursesWindow_keypad, METH_VARARGS}, + {"leaveok", (PyCFunction)PyCursesWindow_leaveok, METH_VARARGS}, + {"move", (PyCFunction)PyCursesWindow_wmove, METH_VARARGS}, + {"mvderwin", (PyCFunction)PyCursesWindow_mvderwin, METH_VARARGS}, + {"mvwin", (PyCFunction)PyCursesWindow_mvwin, METH_VARARGS}, + {"nodelay", (PyCFunction)PyCursesWindow_nodelay, METH_VARARGS}, + {"notimeout", (PyCFunction)PyCursesWindow_notimeout, METH_VARARGS}, + {"noutrefresh", (PyCFunction)PyCursesWindow_NoOutRefresh, METH_VARARGS}, + /* Backward compatibility alias -- remove in Python 2.3 */ + {"nooutrefresh", (PyCFunction)PyCursesWindow_NoOutRefresh, METH_VARARGS}, + {"overlay", (PyCFunction)PyCursesWindow_Overlay, METH_VARARGS}, + {"overwrite", (PyCFunction)PyCursesWindow_Overwrite, + METH_VARARGS}, + {"putwin", (PyCFunction)PyCursesWindow_PutWin, METH_VARARGS}, + {"redrawln", (PyCFunction)PyCursesWindow_RedrawLine, METH_VARARGS}, + {"redrawwin", (PyCFunction)PyCursesWindow_redrawwin, METH_NOARGS}, + {"refresh", (PyCFunction)PyCursesWindow_Refresh, METH_VARARGS}, +#ifndef STRICT_SYSV_CURSES + {"resize", (PyCFunction)PyCursesWindow_wresize, METH_VARARGS}, +#endif + {"scroll", (PyCFunction)PyCursesWindow_Scroll, METH_VARARGS}, + {"scrollok", (PyCFunction)PyCursesWindow_scrollok, METH_VARARGS}, + {"setscrreg", (PyCFunction)PyCursesWindow_SetScrollRegion, METH_VARARGS}, + {"standend", (PyCFunction)PyCursesWindow_wstandend, METH_NOARGS}, + {"standout", (PyCFunction)PyCursesWindow_wstandout, METH_NOARGS}, + {"subpad", (PyCFunction)PyCursesWindow_SubWin, METH_VARARGS}, + {"subwin", (PyCFunction)PyCursesWindow_SubWin, METH_VARARGS}, + {"syncdown", (PyCFunction)PyCursesWindow_wsyncdown, METH_NOARGS}, + {"syncok", (PyCFunction)PyCursesWindow_syncok, METH_VARARGS}, + {"syncup", (PyCFunction)PyCursesWindow_wsyncup, METH_NOARGS}, + {"timeout", (PyCFunction)PyCursesWindow_wtimeout, METH_VARARGS}, + {"touchline", (PyCFunction)PyCursesWindow_TouchLine, METH_VARARGS}, + {"touchwin", (PyCFunction)PyCursesWindow_touchwin, METH_NOARGS}, + {"untouchwin", (PyCFunction)PyCursesWindow_untouchwin, METH_NOARGS}, + {"vline", (PyCFunction)PyCursesWindow_Vline, METH_VARARGS}, + {NULL, NULL} /* sentinel */ +}; + +static PyObject * +PyCursesWindow_GetAttr(PyCursesWindowObject *self, char *name) +{ + return Py_FindMethod(PyCursesWindow_Methods, (PyObject *)self, name); +} + +/* -------------------------------------------------------*/ + +PyTypeObject PyCursesWindow_Type = { + PyVarObject_HEAD_INIT(NULL, 0) + "_curses.curses window", /*tp_name*/ + sizeof(PyCursesWindowObject), /*tp_basicsize*/ + 0, /*tp_itemsize*/ + /* methods */ + (destructor)PyCursesWindow_Dealloc, /*tp_dealloc*/ + 0, /*tp_print*/ + (getattrfunc)PyCursesWindow_GetAttr, /*tp_getattr*/ + (setattrfunc)0, /*tp_setattr*/ + 0, /*tp_compare*/ + 0, /*tp_repr*/ + 0, /*tp_as_number*/ + 0, /*tp_as_sequence*/ + 0, /*tp_as_mapping*/ + 0, /*tp_hash*/ +}; + +/********************************************************************* + Global Functions +**********************************************************************/ + +NoArgNoReturnFunction(beep) +NoArgNoReturnFunction(def_prog_mode) +NoArgNoReturnFunction(def_shell_mode) +NoArgNoReturnFunction(doupdate) +NoArgNoReturnFunction(endwin) +NoArgNoReturnFunction(flash) +NoArgNoReturnFunction(nocbreak) +NoArgNoReturnFunction(noecho) +NoArgNoReturnFunction(nonl) +NoArgNoReturnFunction(noraw) +NoArgNoReturnFunction(reset_prog_mode) +NoArgNoReturnFunction(reset_shell_mode) +NoArgNoReturnFunction(resetty) +NoArgNoReturnFunction(savetty) + +NoArgOrFlagNoReturnFunction(cbreak) +NoArgOrFlagNoReturnFunction(echo) +NoArgOrFlagNoReturnFunction(nl) +NoArgOrFlagNoReturnFunction(raw) + +NoArgReturnIntFunction(baudrate) +NoArgReturnIntFunction(termattrs) + +NoArgReturnStringFunction(termname) +NoArgReturnStringFunction(longname) + +NoArgTrueFalseFunction(can_change_color) +NoArgTrueFalseFunction(has_colors) +NoArgTrueFalseFunction(has_ic) +NoArgTrueFalseFunction(has_il) +NoArgTrueFalseFunction(isendwin) +NoArgNoReturnVoidFunction(flushinp) +NoArgNoReturnVoidFunction(noqiflush) + +static PyObject * +PyCurses_filter(PyObject *self) +{ + /* not checking for PyCursesInitialised here since filter() must + be called before initscr() */ + filter(); + Py_INCREF(Py_None); + return Py_None; +} + +static PyObject * +PyCurses_Color_Content(PyObject *self, PyObject *args) +{ + short color,r,g,b; + + PyCursesInitialised + PyCursesInitialisedColor + + if (!PyArg_ParseTuple(args, "h:color_content", &color)) return NULL; + + if (color_content(color, &r, &g, &b) != ERR) + return Py_BuildValue("(iii)", r, g, b); + else { + PyErr_SetString(PyCursesError, + "Argument 1 was out of range. Check value of COLORS."); + return NULL; + } +} + +static PyObject * +PyCurses_color_pair(PyObject *self, PyObject *args) +{ + int n; + + PyCursesInitialised + PyCursesInitialisedColor + + if (!PyArg_ParseTuple(args, "i:color_pair", &n)) return NULL; + return PyInt_FromLong((long) (n << 8)); +} + +static PyObject * +PyCurses_Curs_Set(PyObject *self, PyObject *args) +{ + int vis,erg; + + PyCursesInitialised + + if (!PyArg_ParseTuple(args, "i:curs_set", &vis)) return NULL; + + erg = curs_set(vis); + if (erg == ERR) return PyCursesCheckERR(erg, "curs_set"); + + return PyInt_FromLong((long) erg); +} + +static PyObject * +PyCurses_Delay_Output(PyObject *self, PyObject *args) +{ + int ms; + + PyCursesInitialised + + if (!PyArg_ParseTuple(args, "i:delay_output", &ms)) return NULL; + + return PyCursesCheckERR(delay_output(ms), "delay_output"); +} + +static PyObject * +PyCurses_EraseChar(PyObject *self) +{ + char ch; + + PyCursesInitialised + + ch = erasechar(); + + return PyString_FromStringAndSize(&ch, 1); +} + +static PyObject * +PyCurses_getsyx(PyObject *self) +{ + int x = 0; + int y = 0; + + PyCursesInitialised + + getsyx(y, x); + + return Py_BuildValue("(ii)", y, x); +} + +#ifdef NCURSES_MOUSE_VERSION +static PyObject * +PyCurses_GetMouse(PyObject *self) +{ + int rtn; + MEVENT event; + + PyCursesInitialised + + rtn = getmouse( &event ); + if (rtn == ERR) { + PyErr_SetString(PyCursesError, "getmouse() returned ERR"); + return NULL; + } + return Py_BuildValue("(hiiil)", + (short)event.id, + event.x, event.y, event.z, + (long) event.bstate); +} + +static PyObject * +PyCurses_UngetMouse(PyObject *self, PyObject *args) +{ + MEVENT event; + + PyCursesInitialised + if (!PyArg_ParseTuple(args, "hiiil", + &event.id, + &event.x, &event.y, &event.z, + (int *) &event.bstate)) + return NULL; + + return PyCursesCheckERR(ungetmouse(&event), "ungetmouse"); +} +#endif + +static PyObject * +PyCurses_GetWin(PyCursesWindowObject *self, PyObject *temp) +{ + WINDOW *win; + + PyCursesInitialised + + if (!PyFile_Check(temp)) { + PyErr_SetString(PyExc_TypeError, "argument must be a file object"); + return NULL; + } + + win = getwin(PyFile_AsFile(temp)); + + if (win == NULL) { + PyErr_SetString(PyCursesError, catchall_NULL); + return NULL; + } + + return PyCursesWindow_New(win); +} + +static PyObject * +PyCurses_HalfDelay(PyObject *self, PyObject *args) +{ + unsigned char tenths; + + PyCursesInitialised + + if (!PyArg_ParseTuple(args, "b:halfdelay", &tenths)) return NULL; + + return PyCursesCheckERR(halfdelay(tenths), "halfdelay"); +} + +#ifndef STRICT_SYSV_CURSES + /* No has_key! */ +static PyObject * PyCurses_has_key(PyObject *self, PyObject *args) +{ + int ch; + + PyCursesInitialised + + if (!PyArg_ParseTuple(args,"i",&ch)) return NULL; + + if (has_key(ch) == FALSE) { + Py_INCREF(Py_False); + return Py_False; + } + Py_INCREF(Py_True); + return Py_True; +} +#endif /* STRICT_SYSV_CURSES */ + +static PyObject * +PyCurses_Init_Color(PyObject *self, PyObject *args) +{ + short color, r, g, b; + + PyCursesInitialised + PyCursesInitialisedColor + + switch(PyTuple_Size(args)) { + case 4: + if (!PyArg_ParseTuple(args, "hhhh;color,r,g,b", &color, &r, &g, &b)) return NULL; + break; + default: + PyErr_SetString(PyExc_TypeError, "init_color requires 4 arguments"); + return NULL; + } + + return PyCursesCheckERR(init_color(color, r, g, b), "init_color"); +} + +static PyObject * +PyCurses_Init_Pair(PyObject *self, PyObject *args) +{ + short pair, f, b; + + PyCursesInitialised + PyCursesInitialisedColor + + if (PyTuple_Size(args) != 3) { + PyErr_SetString(PyExc_TypeError, "init_pair requires 3 arguments"); + return NULL; + } + + if (!PyArg_ParseTuple(args, "hhh;pair, f, b", &pair, &f, &b)) return NULL; + + return PyCursesCheckERR(init_pair(pair, f, b), "init_pair"); +} + +static PyObject *ModDict; + +static PyObject * +PyCurses_InitScr(PyObject *self) +{ + WINDOW *win; + + if (initialised == TRUE) { + wrefresh(stdscr); + return (PyObject *)PyCursesWindow_New(stdscr); + } + + win = initscr(); + + if (win == NULL) { + PyErr_SetString(PyCursesError, catchall_NULL); + return NULL; + } + + initialised = initialised_setupterm = TRUE; + +/* This was moved from initcurses() because it core dumped on SGI, + where they're not defined until you've called initscr() */ +#define SetDictInt(string,ch) \ + do { \ + PyObject *o = PyInt_FromLong((long) (ch)); \ + if (o && PyDict_SetItemString(ModDict, string, o) == 0) { \ + Py_DECREF(o); \ + } \ + } while (0) + + /* Here are some graphic symbols you can use */ + SetDictInt("ACS_ULCORNER", (ACS_ULCORNER)); + SetDictInt("ACS_LLCORNER", (ACS_LLCORNER)); + SetDictInt("ACS_URCORNER", (ACS_URCORNER)); + SetDictInt("ACS_LRCORNER", (ACS_LRCORNER)); + SetDictInt("ACS_LTEE", (ACS_LTEE)); + SetDictInt("ACS_RTEE", (ACS_RTEE)); + SetDictInt("ACS_BTEE", (ACS_BTEE)); + SetDictInt("ACS_TTEE", (ACS_TTEE)); + SetDictInt("ACS_HLINE", (ACS_HLINE)); + SetDictInt("ACS_VLINE", (ACS_VLINE)); + SetDictInt("ACS_PLUS", (ACS_PLUS)); +#if !defined(__hpux) || defined(HAVE_NCURSES_H) + /* On HP/UX 11, these are of type cchar_t, which is not an + integral type. If this is a problem on more platforms, a + configure test should be added to determine whether ACS_S1 + is of integral type. */ + SetDictInt("ACS_S1", (ACS_S1)); + SetDictInt("ACS_S9", (ACS_S9)); + SetDictInt("ACS_DIAMOND", (ACS_DIAMOND)); + SetDictInt("ACS_CKBOARD", (ACS_CKBOARD)); + SetDictInt("ACS_DEGREE", (ACS_DEGREE)); + SetDictInt("ACS_PLMINUS", (ACS_PLMINUS)); + SetDictInt("ACS_BULLET", (ACS_BULLET)); + SetDictInt("ACS_LARROW", (ACS_LARROW)); + SetDictInt("ACS_RARROW", (ACS_RARROW)); + SetDictInt("ACS_DARROW", (ACS_DARROW)); + SetDictInt("ACS_UARROW", (ACS_UARROW)); + SetDictInt("ACS_BOARD", (ACS_BOARD)); + SetDictInt("ACS_LANTERN", (ACS_LANTERN)); + SetDictInt("ACS_BLOCK", (ACS_BLOCK)); +#endif + SetDictInt("ACS_BSSB", (ACS_ULCORNER)); + SetDictInt("ACS_SSBB", (ACS_LLCORNER)); + SetDictInt("ACS_BBSS", (ACS_URCORNER)); + SetDictInt("ACS_SBBS", (ACS_LRCORNER)); + SetDictInt("ACS_SBSS", (ACS_RTEE)); + SetDictInt("ACS_SSSB", (ACS_LTEE)); + SetDictInt("ACS_SSBS", (ACS_BTEE)); + SetDictInt("ACS_BSSS", (ACS_TTEE)); + SetDictInt("ACS_BSBS", (ACS_HLINE)); + SetDictInt("ACS_SBSB", (ACS_VLINE)); + SetDictInt("ACS_SSSS", (ACS_PLUS)); + + /* The following are never available with strict SYSV curses */ +#ifdef ACS_S3 + SetDictInt("ACS_S3", (ACS_S3)); +#endif +#ifdef ACS_S7 + SetDictInt("ACS_S7", (ACS_S7)); +#endif +#ifdef ACS_LEQUAL + SetDictInt("ACS_LEQUAL", (ACS_LEQUAL)); +#endif +#ifdef ACS_GEQUAL + SetDictInt("ACS_GEQUAL", (ACS_GEQUAL)); +#endif +#ifdef ACS_PI + SetDictInt("ACS_PI", (ACS_PI)); +#endif +#ifdef ACS_NEQUAL + SetDictInt("ACS_NEQUAL", (ACS_NEQUAL)); +#endif +#ifdef ACS_STERLING + SetDictInt("ACS_STERLING", (ACS_STERLING)); +#endif + + SetDictInt("LINES", LINES); + SetDictInt("COLS", COLS); + + return (PyObject *)PyCursesWindow_New(win); +} + +static PyObject * +PyCurses_setupterm(PyObject* self, PyObject *args, PyObject* keywds) +{ + int fd = -1; + int err; + char* termstr = NULL; + + static char *kwlist[] = {"term", "fd", NULL}; + + if (!PyArg_ParseTupleAndKeywords( + args, keywds, "|zi:setupterm", kwlist, &termstr, &fd)) { + return NULL; + } + + if (fd == -1) { + PyObject* sys_stdout; + + sys_stdout = PySys_GetObject("stdout"); + + if (sys_stdout == NULL) { + PyErr_SetString( + PyCursesError, + "lost sys.stdout"); + return NULL; + } + + fd = PyObject_AsFileDescriptor(sys_stdout); + + if (fd == -1) { + return NULL; + } + } + + if (setupterm(termstr,fd,&err) == ERR) { + char* s = "setupterm: unknown error"; + + if (err == 0) { + s = "setupterm: could not find terminal"; + } else if (err == -1) { + s = "setupterm: could not find terminfo database"; + } + + PyErr_SetString(PyCursesError,s); + return NULL; + } + + initialised_setupterm = TRUE; + + Py_INCREF(Py_None); + return Py_None; +} + +static PyObject * +PyCurses_IntrFlush(PyObject *self, PyObject *args) +{ + int ch; + + PyCursesInitialised + + switch(PyTuple_Size(args)) { + case 1: + if (!PyArg_ParseTuple(args,"i;True(1), False(0)",&ch)) return NULL; + break; + default: + PyErr_SetString(PyExc_TypeError, "intrflush requires 1 argument"); + return NULL; + } + + return PyCursesCheckERR(intrflush(NULL,ch), "intrflush"); +} + +#ifdef HAVE_CURSES_IS_TERM_RESIZED +static PyObject * +PyCurses_Is_Term_Resized(PyObject *self, PyObject *args) +{ + int lines; + int columns; + int result; + + PyCursesInitialised + + if (!PyArg_ParseTuple(args,"ii:is_term_resized", &lines, &columns)) + return NULL; + result = is_term_resized(lines, columns); + if (result == TRUE) { + Py_INCREF(Py_True); + return Py_True; + } else { + Py_INCREF(Py_False); + return Py_False; + } +} +#endif /* HAVE_CURSES_IS_TERM_RESIZED */ + +#if !defined(__NetBSD__) +static PyObject * +PyCurses_KeyName(PyObject *self, PyObject *args) +{ + const char *knp; + int ch; + + PyCursesInitialised + + if (!PyArg_ParseTuple(args,"i",&ch)) return NULL; + + if (ch < 0) { + PyErr_SetString(PyExc_ValueError, "invalid key number"); + return NULL; + } + knp = keyname(ch); + + return PyString_FromString((knp == NULL) ? "" : (char *)knp); +} +#endif + +static PyObject * +PyCurses_KillChar(PyObject *self) +{ + char ch; + + ch = killchar(); + + return PyString_FromStringAndSize(&ch, 1); +} + +static PyObject * +PyCurses_Meta(PyObject *self, PyObject *args) +{ + int ch; + + PyCursesInitialised + + switch(PyTuple_Size(args)) { + case 1: + if (!PyArg_ParseTuple(args,"i;True(1), False(0)",&ch)) return NULL; + break; + default: + PyErr_SetString(PyExc_TypeError, "meta requires 1 argument"); + return NULL; + } + + return PyCursesCheckERR(meta(stdscr, ch), "meta"); +} + +#ifdef NCURSES_MOUSE_VERSION +static PyObject * +PyCurses_MouseInterval(PyObject *self, PyObject *args) +{ + int interval; + PyCursesInitialised + + if (!PyArg_ParseTuple(args,"i;interval",&interval)) + return NULL; + return PyCursesCheckERR(mouseinterval(interval), "mouseinterval"); +} + +static PyObject * +PyCurses_MouseMask(PyObject *self, PyObject *args) +{ + int newmask; + mmask_t oldmask, availmask; + + PyCursesInitialised + if (!PyArg_ParseTuple(args,"i;mousemask",&newmask)) + return NULL; + availmask = mousemask(newmask, &oldmask); + return Py_BuildValue("(ll)", (long)availmask, (long)oldmask); +} +#endif + +static PyObject * +PyCurses_Napms(PyObject *self, PyObject *args) +{ + int ms; + + PyCursesInitialised + if (!PyArg_ParseTuple(args, "i;ms", &ms)) return NULL; + + return Py_BuildValue("i", napms(ms)); +} + + +static PyObject * +PyCurses_NewPad(PyObject *self, PyObject *args) +{ + WINDOW *win; + int nlines, ncols; + + PyCursesInitialised + + if (!PyArg_ParseTuple(args,"ii;nlines,ncols",&nlines,&ncols)) return NULL; + + win = newpad(nlines, ncols); + + if (win == NULL) { + PyErr_SetString(PyCursesError, catchall_NULL); + return NULL; + } + + return (PyObject *)PyCursesWindow_New(win); +} + +static PyObject * +PyCurses_NewWindow(PyObject *self, PyObject *args) +{ + WINDOW *win; + int nlines, ncols, begin_y=0, begin_x=0; + + PyCursesInitialised + + switch (PyTuple_Size(args)) { + case 2: + if (!PyArg_ParseTuple(args,"ii;nlines,ncols",&nlines,&ncols)) + return NULL; + break; + case 4: + if (!PyArg_ParseTuple(args, "iiii;nlines,ncols,begin_y,begin_x", + &nlines,&ncols,&begin_y,&begin_x)) + return NULL; + break; + default: + PyErr_SetString(PyExc_TypeError, "newwin requires 2 or 4 arguments"); + return NULL; + } + + win = newwin(nlines,ncols,begin_y,begin_x); + if (win == NULL) { + PyErr_SetString(PyCursesError, catchall_NULL); + return NULL; + } + + return (PyObject *)PyCursesWindow_New(win); +} + +static PyObject * +PyCurses_Pair_Content(PyObject *self, PyObject *args) +{ + short pair,f,b; + + PyCursesInitialised + PyCursesInitialisedColor + + switch(PyTuple_Size(args)) { + case 1: + if (!PyArg_ParseTuple(args, "h;pair", &pair)) return NULL; + break; + default: + PyErr_SetString(PyExc_TypeError, "pair_content requires 1 argument"); + return NULL; + } + + if (pair_content(pair, &f, &b)==ERR) { + PyErr_SetString(PyCursesError, + "Argument 1 was out of range. (1..COLOR_PAIRS-1)"); + return NULL; + } + + return Py_BuildValue("(ii)", f, b); +} + +static PyObject * +PyCurses_pair_number(PyObject *self, PyObject *args) +{ + int n; + + PyCursesInitialised + PyCursesInitialisedColor + + switch(PyTuple_Size(args)) { + case 1: + if (!PyArg_ParseTuple(args, "i;pairvalue", &n)) return NULL; + break; + default: + PyErr_SetString(PyExc_TypeError, + "pair_number requires 1 argument"); + return NULL; + } + + return PyInt_FromLong((long) ((n & A_COLOR) >> 8)); +} + +static PyObject * +PyCurses_Putp(PyObject *self, PyObject *args) +{ + char *str; + + if (!PyArg_ParseTuple(args,"s;str", &str)) return NULL; + return PyCursesCheckERR(putp(str), "putp"); +} + +static PyObject * +PyCurses_QiFlush(PyObject *self, PyObject *args) +{ + int flag = 0; + + PyCursesInitialised + + switch(PyTuple_Size(args)) { + case 0: + qiflush(); + Py_INCREF(Py_None); + return Py_None; + case 1: + if (!PyArg_ParseTuple(args, "i;True(1) or False(0)", &flag)) return NULL; + if (flag) qiflush(); + else noqiflush(); + Py_INCREF(Py_None); + return Py_None; + default: + PyErr_SetString(PyExc_TypeError, "qiflush requires 0 or 1 arguments"); + return NULL; + } +} + +/* Internal helper used for updating curses.LINES, curses.COLS, _curses.LINES + * and _curses.COLS */ +#if defined(HAVE_CURSES_RESIZETERM) || defined(HAVE_CURSES_RESIZE_TERM) +static int +update_lines_cols(void) +{ + PyObject *o; + PyObject *m = PyImport_ImportModuleNoBlock("curses"); + + if (!m) + return 0; + + o = PyInt_FromLong(LINES); + if (!o) { + Py_DECREF(m); + return 0; + } + if (PyObject_SetAttrString(m, "LINES", o)) { + Py_DECREF(m); + Py_DECREF(o); + return 0; + } + if (PyDict_SetItemString(ModDict, "LINES", o)) { + Py_DECREF(m); + Py_DECREF(o); + return 0; + } + Py_DECREF(o); + o = PyInt_FromLong(COLS); + if (!o) { + Py_DECREF(m); + return 0; + } + if (PyObject_SetAttrString(m, "COLS", o)) { + Py_DECREF(m); + Py_DECREF(o); + return 0; + } + if (PyDict_SetItemString(ModDict, "COLS", o)) { + Py_DECREF(m); + Py_DECREF(o); + return 0; + } + Py_DECREF(o); + Py_DECREF(m); + return 1; +} +#endif + +#ifdef HAVE_CURSES_RESIZETERM +static PyObject * +PyCurses_ResizeTerm(PyObject *self, PyObject *args) +{ + int lines; + int columns; + PyObject *result; + + PyCursesInitialised + + if (!PyArg_ParseTuple(args,"ii:resizeterm", &lines, &columns)) + return NULL; + + result = PyCursesCheckERR(resizeterm(lines, columns), "resizeterm"); + if (!result) + return NULL; + if (!update_lines_cols()) + return NULL; + return result; +} + +#endif + +#ifdef HAVE_CURSES_RESIZE_TERM +static PyObject * +PyCurses_Resize_Term(PyObject *self, PyObject *args) +{ + int lines; + int columns; + + PyObject *result; + + PyCursesInitialised + + if (!PyArg_ParseTuple(args,"ii:resize_term", &lines, &columns)) + return NULL; + + result = PyCursesCheckERR(resize_term(lines, columns), "resize_term"); + if (!result) + return NULL; + if (!update_lines_cols()) + return NULL; + return result; +} +#endif /* HAVE_CURSES_RESIZE_TERM */ + +static PyObject * +PyCurses_setsyx(PyObject *self, PyObject *args) +{ + int y,x; + + PyCursesInitialised + + if (PyTuple_Size(args)!=2) { + PyErr_SetString(PyExc_TypeError, "setsyx requires 2 arguments"); + return NULL; + } + + if (!PyArg_ParseTuple(args, "ii;y, x", &y, &x)) return NULL; + + setsyx(y,x); + + Py_INCREF(Py_None); + return Py_None; +} + +static PyObject * +PyCurses_Start_Color(PyObject *self) +{ + int code; + PyObject *c, *cp; + + PyCursesInitialised + + code = start_color(); + if (code != ERR) { + initialisedcolors = TRUE; + c = PyInt_FromLong((long) COLORS); + PyDict_SetItemString(ModDict, "COLORS", c); + Py_DECREF(c); + cp = PyInt_FromLong((long) COLOR_PAIRS); + PyDict_SetItemString(ModDict, "COLOR_PAIRS", cp); + Py_DECREF(cp); + Py_INCREF(Py_None); + return Py_None; + } else { + PyErr_SetString(PyCursesError, "start_color() returned ERR"); + return NULL; + } +} + +static PyObject * +PyCurses_tigetflag(PyObject *self, PyObject *args) +{ + char *capname; + + PyCursesSetupTermCalled; + + if (!PyArg_ParseTuple(args, "s", &capname)) + return NULL; + + return PyInt_FromLong( (long) tigetflag( capname ) ); +} + +static PyObject * +PyCurses_tigetnum(PyObject *self, PyObject *args) +{ + char *capname; + + PyCursesSetupTermCalled; + + if (!PyArg_ParseTuple(args, "s", &capname)) + return NULL; + + return PyInt_FromLong( (long) tigetnum( capname ) ); +} + +static PyObject * +PyCurses_tigetstr(PyObject *self, PyObject *args) +{ + char *capname; + + PyCursesSetupTermCalled; + + if (!PyArg_ParseTuple(args, "s", &capname)) + return NULL; + + capname = tigetstr( capname ); + if (capname == 0 || capname == (char*) -1) { + Py_INCREF(Py_None); + return Py_None; + } + return PyString_FromString( capname ); +} + +static PyObject * +PyCurses_tparm(PyObject *self, PyObject *args) +{ + char* fmt; + char* result = NULL; + int i1=0,i2=0,i3=0,i4=0,i5=0,i6=0,i7=0,i8=0,i9=0; + + PyCursesSetupTermCalled; + + if (!PyArg_ParseTuple(args, "s|iiiiiiiii:tparm", + &fmt, &i1, &i2, &i3, &i4, + &i5, &i6, &i7, &i8, &i9)) { + return NULL; + } + + result = tparm(fmt,i1,i2,i3,i4,i5,i6,i7,i8,i9); + if (!result) { + PyErr_SetString(PyCursesError, "tparm() returned NULL"); + return NULL; + } + + return PyString_FromString(result); +} + +static PyObject * +PyCurses_TypeAhead(PyObject *self, PyObject *args) +{ + int fd; + + PyCursesInitialised + + if (!PyArg_ParseTuple(args,"i;fd",&fd)) return NULL; + + return PyCursesCheckERR(typeahead( fd ), "typeahead"); +} + +static PyObject * +PyCurses_UnCtrl(PyObject *self, PyObject *args) +{ + PyObject *temp; + chtype ch; + + PyCursesInitialised + + if (!PyArg_ParseTuple(args,"O;ch or int",&temp)) return NULL; + + if (PyInt_Check(temp)) + ch = (chtype) PyInt_AsLong(temp); + else if (PyString_Check(temp)) + ch = (chtype) *PyString_AsString(temp); + else { + PyErr_SetString(PyExc_TypeError, "argument must be a ch or an int"); + return NULL; + } + + return PyString_FromString(unctrl(ch)); +} + +static PyObject * +PyCurses_UngetCh(PyObject *self, PyObject *args) +{ + PyObject *temp; + int ch; + + PyCursesInitialised + + if (!PyArg_ParseTuple(args,"O;ch or int",&temp)) return NULL; + + if (PyInt_Check(temp)) + ch = (int) PyInt_AsLong(temp); + else if (PyString_Check(temp)) + ch = (int) *PyString_AsString(temp); + else { + PyErr_SetString(PyExc_TypeError, "argument must be a ch or an int"); + return NULL; + } + + return PyCursesCheckERR(ungetch(ch), "ungetch"); +} + +static PyObject * +PyCurses_Use_Env(PyObject *self, PyObject *args) +{ + int flag; + + switch(PyTuple_Size(args)) { + case 1: + if (!PyArg_ParseTuple(args,"i;True(1), False(0)",&flag)) + return NULL; + break; + default: + PyErr_SetString(PyExc_TypeError, "use_env requires 1 argument"); + return NULL; + } + use_env(flag); + Py_INCREF(Py_None); + return Py_None; +} + +#ifndef STRICT_SYSV_CURSES +static PyObject * +PyCurses_Use_Default_Colors(PyObject *self) +{ + int code; + + PyCursesInitialised + PyCursesInitialisedColor + + code = use_default_colors(); + if (code != ERR) { + Py_INCREF(Py_None); + return Py_None; + } else { + PyErr_SetString(PyCursesError, "use_default_colors() returned ERR"); + return NULL; + } +} +#endif /* STRICT_SYSV_CURSES */ + +/* List of functions defined in the module */ + +static PyMethodDef PyCurses_methods[] = { + {"baudrate", (PyCFunction)PyCurses_baudrate, METH_NOARGS}, + {"beep", (PyCFunction)PyCurses_beep, METH_NOARGS}, + {"can_change_color", (PyCFunction)PyCurses_can_change_color, METH_NOARGS}, + {"cbreak", (PyCFunction)PyCurses_cbreak, METH_VARARGS}, + {"color_content", (PyCFunction)PyCurses_Color_Content, METH_VARARGS}, + {"color_pair", (PyCFunction)PyCurses_color_pair, METH_VARARGS}, + {"curs_set", (PyCFunction)PyCurses_Curs_Set, METH_VARARGS}, + {"def_prog_mode", (PyCFunction)PyCurses_def_prog_mode, METH_NOARGS}, + {"def_shell_mode", (PyCFunction)PyCurses_def_shell_mode, METH_NOARGS}, + {"delay_output", (PyCFunction)PyCurses_Delay_Output, METH_VARARGS}, + {"doupdate", (PyCFunction)PyCurses_doupdate, METH_NOARGS}, + {"echo", (PyCFunction)PyCurses_echo, METH_VARARGS}, + {"endwin", (PyCFunction)PyCurses_endwin, METH_NOARGS}, + {"erasechar", (PyCFunction)PyCurses_EraseChar, METH_NOARGS}, + {"filter", (PyCFunction)PyCurses_filter, METH_NOARGS}, + {"flash", (PyCFunction)PyCurses_flash, METH_NOARGS}, + {"flushinp", (PyCFunction)PyCurses_flushinp, METH_NOARGS}, +#ifdef NCURSES_MOUSE_VERSION + {"getmouse", (PyCFunction)PyCurses_GetMouse, METH_NOARGS}, + {"ungetmouse", (PyCFunction)PyCurses_UngetMouse, METH_VARARGS}, +#endif + {"getsyx", (PyCFunction)PyCurses_getsyx, METH_NOARGS}, + {"getwin", (PyCFunction)PyCurses_GetWin, METH_O}, + {"has_colors", (PyCFunction)PyCurses_has_colors, METH_NOARGS}, + {"has_ic", (PyCFunction)PyCurses_has_ic, METH_NOARGS}, + {"has_il", (PyCFunction)PyCurses_has_il, METH_NOARGS}, +#ifndef STRICT_SYSV_CURSES + {"has_key", (PyCFunction)PyCurses_has_key, METH_VARARGS}, +#endif + {"halfdelay", (PyCFunction)PyCurses_HalfDelay, METH_VARARGS}, + {"init_color", (PyCFunction)PyCurses_Init_Color, METH_VARARGS}, + {"init_pair", (PyCFunction)PyCurses_Init_Pair, METH_VARARGS}, + {"initscr", (PyCFunction)PyCurses_InitScr, METH_NOARGS}, + {"intrflush", (PyCFunction)PyCurses_IntrFlush, METH_VARARGS}, + {"isendwin", (PyCFunction)PyCurses_isendwin, METH_NOARGS}, +#ifdef HAVE_CURSES_IS_TERM_RESIZED + {"is_term_resized", (PyCFunction)PyCurses_Is_Term_Resized, METH_VARARGS}, +#endif +#if !defined(__NetBSD__) + {"keyname", (PyCFunction)PyCurses_KeyName, METH_VARARGS}, +#endif + {"killchar", (PyCFunction)PyCurses_KillChar, METH_NOARGS}, + {"longname", (PyCFunction)PyCurses_longname, METH_NOARGS}, + {"meta", (PyCFunction)PyCurses_Meta, METH_VARARGS}, +#ifdef NCURSES_MOUSE_VERSION + {"mouseinterval", (PyCFunction)PyCurses_MouseInterval, METH_VARARGS}, + {"mousemask", (PyCFunction)PyCurses_MouseMask, METH_VARARGS}, +#endif + {"napms", (PyCFunction)PyCurses_Napms, METH_VARARGS}, + {"newpad", (PyCFunction)PyCurses_NewPad, METH_VARARGS}, + {"newwin", (PyCFunction)PyCurses_NewWindow, METH_VARARGS}, + {"nl", (PyCFunction)PyCurses_nl, METH_VARARGS}, + {"nocbreak", (PyCFunction)PyCurses_nocbreak, METH_NOARGS}, + {"noecho", (PyCFunction)PyCurses_noecho, METH_NOARGS}, + {"nonl", (PyCFunction)PyCurses_nonl, METH_NOARGS}, + {"noqiflush", (PyCFunction)PyCurses_noqiflush, METH_NOARGS}, + {"noraw", (PyCFunction)PyCurses_noraw, METH_NOARGS}, + {"pair_content", (PyCFunction)PyCurses_Pair_Content, METH_VARARGS}, + {"pair_number", (PyCFunction)PyCurses_pair_number, METH_VARARGS}, + {"putp", (PyCFunction)PyCurses_Putp, METH_VARARGS}, + {"qiflush", (PyCFunction)PyCurses_QiFlush, METH_VARARGS}, + {"raw", (PyCFunction)PyCurses_raw, METH_VARARGS}, + {"reset_prog_mode", (PyCFunction)PyCurses_reset_prog_mode, METH_NOARGS}, + {"reset_shell_mode", (PyCFunction)PyCurses_reset_shell_mode, METH_NOARGS}, + {"resetty", (PyCFunction)PyCurses_resetty, METH_NOARGS}, +#ifdef HAVE_CURSES_RESIZETERM + {"resizeterm", (PyCFunction)PyCurses_ResizeTerm, METH_VARARGS}, +#endif +#ifdef HAVE_CURSES_RESIZE_TERM + {"resize_term", (PyCFunction)PyCurses_Resize_Term, METH_VARARGS}, +#endif + {"savetty", (PyCFunction)PyCurses_savetty, METH_NOARGS}, + {"setsyx", (PyCFunction)PyCurses_setsyx, METH_VARARGS}, + {"setupterm", (PyCFunction)PyCurses_setupterm, + METH_VARARGS|METH_KEYWORDS}, + {"start_color", (PyCFunction)PyCurses_Start_Color, METH_NOARGS}, + {"termattrs", (PyCFunction)PyCurses_termattrs, METH_NOARGS}, + {"termname", (PyCFunction)PyCurses_termname, METH_NOARGS}, + {"tigetflag", (PyCFunction)PyCurses_tigetflag, METH_VARARGS}, + {"tigetnum", (PyCFunction)PyCurses_tigetnum, METH_VARARGS}, + {"tigetstr", (PyCFunction)PyCurses_tigetstr, METH_VARARGS}, + {"tparm", (PyCFunction)PyCurses_tparm, METH_VARARGS}, + {"typeahead", (PyCFunction)PyCurses_TypeAhead, METH_VARARGS}, + {"unctrl", (PyCFunction)PyCurses_UnCtrl, METH_VARARGS}, + {"ungetch", (PyCFunction)PyCurses_UngetCh, METH_VARARGS}, + {"use_env", (PyCFunction)PyCurses_Use_Env, METH_VARARGS}, +#ifndef STRICT_SYSV_CURSES + {"use_default_colors", (PyCFunction)PyCurses_Use_Default_Colors, METH_NOARGS}, +#endif + {NULL, NULL} /* sentinel */ +}; + +/* Initialization function for the module */ + +PyMODINIT_FUNC +init_curses(void) +{ + PyObject *m, *d, *v, *c_api_object; + static void *PyCurses_API[PyCurses_API_pointers]; + + /* Initialize object type */ + Py_TYPE(&PyCursesWindow_Type) = &PyType_Type; + + /* Initialize the C API pointer array */ + PyCurses_API[0] = (void *)&PyCursesWindow_Type; + PyCurses_API[1] = (void *)func_PyCursesSetupTermCalled; + PyCurses_API[2] = (void *)func_PyCursesInitialised; + PyCurses_API[3] = (void *)func_PyCursesInitialisedColor; + + /* Create the module and add the functions */ + m = Py_InitModule("_curses", PyCurses_methods); + if (m == NULL) + return; + + /* Add some symbolic constants to the module */ + d = PyModule_GetDict(m); + if (d == NULL) + return; + ModDict = d; /* For PyCurses_InitScr to use later */ + + /* Add a capsule for the C API */ + c_api_object = PyCapsule_New(PyCurses_API, PyCurses_CAPSULE_NAME, NULL); + PyDict_SetItemString(d, "_C_API", c_api_object); + Py_DECREF(c_api_object); + + /* For exception curses.error */ + PyCursesError = PyErr_NewException("_curses.error", NULL, NULL); + PyDict_SetItemString(d, "error", PyCursesError); + + /* Make the version available */ + v = PyString_FromString(PyCursesVersion); + PyDict_SetItemString(d, "version", v); + PyDict_SetItemString(d, "__version__", v); + Py_DECREF(v); + + SetDictInt("ERR", ERR); + SetDictInt("OK", OK); + + /* Here are some attributes you can add to chars to print */ + + SetDictInt("A_ATTRIBUTES", A_ATTRIBUTES); + SetDictInt("A_NORMAL", A_NORMAL); + SetDictInt("A_STANDOUT", A_STANDOUT); + SetDictInt("A_UNDERLINE", A_UNDERLINE); + SetDictInt("A_REVERSE", A_REVERSE); + SetDictInt("A_BLINK", A_BLINK); + SetDictInt("A_DIM", A_DIM); + SetDictInt("A_BOLD", A_BOLD); + SetDictInt("A_ALTCHARSET", A_ALTCHARSET); +#if !defined(__NetBSD__) + SetDictInt("A_INVIS", A_INVIS); +#endif + SetDictInt("A_PROTECT", A_PROTECT); + SetDictInt("A_CHARTEXT", A_CHARTEXT); + SetDictInt("A_COLOR", A_COLOR); + + /* The following are never available with strict SYSV curses */ +#ifdef A_HORIZONTAL + SetDictInt("A_HORIZONTAL", A_HORIZONTAL); +#endif +#ifdef A_LEFT + SetDictInt("A_LEFT", A_LEFT); +#endif +#ifdef A_LOW + SetDictInt("A_LOW", A_LOW); +#endif +#ifdef A_RIGHT + SetDictInt("A_RIGHT", A_RIGHT); +#endif +#ifdef A_TOP + SetDictInt("A_TOP", A_TOP); +#endif +#ifdef A_VERTICAL + SetDictInt("A_VERTICAL", A_VERTICAL); +#endif + + SetDictInt("COLOR_BLACK", COLOR_BLACK); + SetDictInt("COLOR_RED", COLOR_RED); + SetDictInt("COLOR_GREEN", COLOR_GREEN); + SetDictInt("COLOR_YELLOW", COLOR_YELLOW); + SetDictInt("COLOR_BLUE", COLOR_BLUE); + SetDictInt("COLOR_MAGENTA", COLOR_MAGENTA); + SetDictInt("COLOR_CYAN", COLOR_CYAN); + SetDictInt("COLOR_WHITE", COLOR_WHITE); + +#ifdef NCURSES_MOUSE_VERSION + /* Mouse-related constants */ + SetDictInt("BUTTON1_PRESSED", BUTTON1_PRESSED); + SetDictInt("BUTTON1_RELEASED", BUTTON1_RELEASED); + SetDictInt("BUTTON1_CLICKED", BUTTON1_CLICKED); + SetDictInt("BUTTON1_DOUBLE_CLICKED", BUTTON1_DOUBLE_CLICKED); + SetDictInt("BUTTON1_TRIPLE_CLICKED", BUTTON1_TRIPLE_CLICKED); + + SetDictInt("BUTTON2_PRESSED", BUTTON2_PRESSED); + SetDictInt("BUTTON2_RELEASED", BUTTON2_RELEASED); + SetDictInt("BUTTON2_CLICKED", BUTTON2_CLICKED); + SetDictInt("BUTTON2_DOUBLE_CLICKED", BUTTON2_DOUBLE_CLICKED); + SetDictInt("BUTTON2_TRIPLE_CLICKED", BUTTON2_TRIPLE_CLICKED); + + SetDictInt("BUTTON3_PRESSED", BUTTON3_PRESSED); + SetDictInt("BUTTON3_RELEASED", BUTTON3_RELEASED); + SetDictInt("BUTTON3_CLICKED", BUTTON3_CLICKED); + SetDictInt("BUTTON3_DOUBLE_CLICKED", BUTTON3_DOUBLE_CLICKED); + SetDictInt("BUTTON3_TRIPLE_CLICKED", BUTTON3_TRIPLE_CLICKED); + + SetDictInt("BUTTON4_PRESSED", BUTTON4_PRESSED); + SetDictInt("BUTTON4_RELEASED", BUTTON4_RELEASED); + SetDictInt("BUTTON4_CLICKED", BUTTON4_CLICKED); + SetDictInt("BUTTON4_DOUBLE_CLICKED", BUTTON4_DOUBLE_CLICKED); + SetDictInt("BUTTON4_TRIPLE_CLICKED", BUTTON4_TRIPLE_CLICKED); + + SetDictInt("BUTTON_SHIFT", BUTTON_SHIFT); + SetDictInt("BUTTON_CTRL", BUTTON_CTRL); + SetDictInt("BUTTON_ALT", BUTTON_ALT); + + SetDictInt("ALL_MOUSE_EVENTS", ALL_MOUSE_EVENTS); + SetDictInt("REPORT_MOUSE_POSITION", REPORT_MOUSE_POSITION); +#endif + /* Now set everything up for KEY_ variables */ + { + int key; + char *key_n; + char *key_n2; +#if !defined(__NetBSD__) + for (key=KEY_MIN;key < KEY_MAX; key++) { + key_n = (char *)keyname(key); + if (key_n == NULL || strcmp(key_n,"UNKNOWN KEY")==0) + continue; + if (strncmp(key_n,"KEY_F(",6)==0) { + char *p1, *p2; + key_n2 = malloc(strlen(key_n)+1); + if (!key_n2) { + PyErr_NoMemory(); + break; + } + p1 = key_n; + p2 = key_n2; + while (*p1) { + if (*p1 != '(' && *p1 != ')') { + *p2 = *p1; + p2++; + } + p1++; + } + *p2 = (char)0; + } else + key_n2 = key_n; + SetDictInt(key_n2,key); + if (key_n2 != key_n) + free(key_n2); + } +#endif + SetDictInt("KEY_MIN", KEY_MIN); + SetDictInt("KEY_MAX", KEY_MAX); + } +} From python-checkins at python.org Mon May 10 21:53:43 2010 From: python-checkins at python.org (andrew.kuchling) Date: Mon, 10 May 2010 21:53:43 +0200 (CEST) Subject: [Python-checkins] r81051 - sandbox/trunk/curses/_cursesmodule.c Message-ID: <20100510195343.4DED8EE983@mail.python.org> Author: andrew.kuchling Date: Mon May 10 21:53:43 2010 New Revision: 81051 Log: Use ';' after initialization macros to avoid confusing re-indenters Modified: sandbox/trunk/curses/_cursesmodule.c Modified: sandbox/trunk/curses/_cursesmodule.c ============================================================================== --- sandbox/trunk/curses/_cursesmodule.c (original) +++ sandbox/trunk/curses/_cursesmodule.c Mon May 10 21:53:43 2010 @@ -1698,8 +1698,8 @@ { short color,r,g,b; - PyCursesInitialised - PyCursesInitialisedColor + PyCursesInitialised; + PyCursesInitialisedColor; if (!PyArg_ParseTuple(args, "h:color_content", &color)) return NULL; @@ -1717,8 +1717,8 @@ { int n; - PyCursesInitialised - PyCursesInitialisedColor + PyCursesInitialised; + PyCursesInitialisedColor; if (!PyArg_ParseTuple(args, "i:color_pair", &n)) return NULL; return PyInt_FromLong((long) (n << 8)); @@ -1729,7 +1729,7 @@ { int vis,erg; - PyCursesInitialised + PyCursesInitialised; if (!PyArg_ParseTuple(args, "i:curs_set", &vis)) return NULL; @@ -1744,7 +1744,7 @@ { int ms; - PyCursesInitialised + PyCursesInitialised; if (!PyArg_ParseTuple(args, "i:delay_output", &ms)) return NULL; @@ -1756,7 +1756,7 @@ { char ch; - PyCursesInitialised + PyCursesInitialised; ch = erasechar(); @@ -1769,7 +1769,7 @@ int x = 0; int y = 0; - PyCursesInitialised + PyCursesInitialised; getsyx(y, x); @@ -1783,7 +1783,7 @@ int rtn; MEVENT event; - PyCursesInitialised + PyCursesInitialised; rtn = getmouse( &event ); if (rtn == ERR) { @@ -1801,7 +1801,7 @@ { MEVENT event; - PyCursesInitialised + PyCursesInitialised; if (!PyArg_ParseTuple(args, "hiiil", &event.id, &event.x, &event.y, &event.z, @@ -1817,7 +1817,7 @@ { WINDOW *win; - PyCursesInitialised + PyCursesInitialised; if (!PyFile_Check(temp)) { PyErr_SetString(PyExc_TypeError, "argument must be a file object"); @@ -1839,7 +1839,7 @@ { unsigned char tenths; - PyCursesInitialised + PyCursesInitialised; if (!PyArg_ParseTuple(args, "b:halfdelay", &tenths)) return NULL; @@ -1852,7 +1852,7 @@ { int ch; - PyCursesInitialised + PyCursesInitialised; if (!PyArg_ParseTuple(args,"i",&ch)) return NULL; @@ -1870,8 +1870,8 @@ { short color, r, g, b; - PyCursesInitialised - PyCursesInitialisedColor + PyCursesInitialised; + PyCursesInitialisedColor; switch(PyTuple_Size(args)) { case 4: @@ -1890,8 +1890,8 @@ { short pair, f, b; - PyCursesInitialised - PyCursesInitialisedColor + PyCursesInitialised; + PyCursesInitialisedColor; if (PyTuple_Size(args) != 3) { PyErr_SetString(PyExc_TypeError, "init_pair requires 3 arguments"); @@ -2064,7 +2064,7 @@ { int ch; - PyCursesInitialised + PyCursesInitialised; switch(PyTuple_Size(args)) { case 1: @@ -2086,7 +2086,7 @@ int columns; int result; - PyCursesInitialised + PyCursesInitialised; if (!PyArg_ParseTuple(args,"ii:is_term_resized", &lines, &columns)) return NULL; @@ -2108,7 +2108,7 @@ const char *knp; int ch; - PyCursesInitialised + PyCursesInitialised; if (!PyArg_ParseTuple(args,"i",&ch)) return NULL; @@ -2137,7 +2137,7 @@ { int ch; - PyCursesInitialised + PyCursesInitialised; switch(PyTuple_Size(args)) { case 1: @@ -2156,7 +2156,7 @@ PyCurses_MouseInterval(PyObject *self, PyObject *args) { int interval; - PyCursesInitialised + PyCursesInitialised; if (!PyArg_ParseTuple(args,"i;interval",&interval)) return NULL; @@ -2169,7 +2169,7 @@ int newmask; mmask_t oldmask, availmask; - PyCursesInitialised + PyCursesInitialised; if (!PyArg_ParseTuple(args,"i;mousemask",&newmask)) return NULL; availmask = mousemask(newmask, &oldmask); @@ -2182,7 +2182,7 @@ { int ms; - PyCursesInitialised + PyCursesInitialised; if (!PyArg_ParseTuple(args, "i;ms", &ms)) return NULL; return Py_BuildValue("i", napms(ms)); @@ -2195,7 +2195,7 @@ WINDOW *win; int nlines, ncols; - PyCursesInitialised + PyCursesInitialised; if (!PyArg_ParseTuple(args,"ii;nlines,ncols",&nlines,&ncols)) return NULL; @@ -2215,7 +2215,7 @@ WINDOW *win; int nlines, ncols, begin_y=0, begin_x=0; - PyCursesInitialised + PyCursesInitialised; switch (PyTuple_Size(args)) { case 2: @@ -2246,8 +2246,8 @@ { short pair,f,b; - PyCursesInitialised - PyCursesInitialisedColor + PyCursesInitialised; + PyCursesInitialisedColor; switch(PyTuple_Size(args)) { case 1: @@ -2272,8 +2272,8 @@ { int n; - PyCursesInitialised - PyCursesInitialisedColor + PyCursesInitialised; + PyCursesInitialisedColor; switch(PyTuple_Size(args)) { case 1: @@ -2302,7 +2302,7 @@ { int flag = 0; - PyCursesInitialised + PyCursesInitialised; switch(PyTuple_Size(args)) { case 0: @@ -2378,7 +2378,7 @@ int columns; PyObject *result; - PyCursesInitialised + PyCursesInitialised; if (!PyArg_ParseTuple(args,"ii:resizeterm", &lines, &columns)) return NULL; @@ -2402,7 +2402,7 @@ PyObject *result; - PyCursesInitialised + PyCursesInitialised; if (!PyArg_ParseTuple(args,"ii:resize_term", &lines, &columns)) return NULL; @@ -2421,7 +2421,7 @@ { int y,x; - PyCursesInitialised + PyCursesInitialised; if (PyTuple_Size(args)!=2) { PyErr_SetString(PyExc_TypeError, "setsyx requires 2 arguments"); @@ -2442,7 +2442,7 @@ int code; PyObject *c, *cp; - PyCursesInitialised + PyCursesInitialised; code = start_color(); if (code != ERR) { @@ -2534,7 +2534,7 @@ { int fd; - PyCursesInitialised + PyCursesInitialised; if (!PyArg_ParseTuple(args,"i;fd",&fd)) return NULL; @@ -2547,7 +2547,7 @@ PyObject *temp; chtype ch; - PyCursesInitialised + PyCursesInitialised; if (!PyArg_ParseTuple(args,"O;ch or int",&temp)) return NULL; @@ -2569,7 +2569,7 @@ PyObject *temp; int ch; - PyCursesInitialised + PyCursesInitialised; if (!PyArg_ParseTuple(args,"O;ch or int",&temp)) return NULL; @@ -2610,8 +2610,8 @@ { int code; - PyCursesInitialised - PyCursesInitialisedColor + PyCursesInitialised; + PyCursesInitialisedColor; code = use_default_colors(); if (code != ERR) { From python-checkins at python.org Mon May 10 21:57:39 2010 From: python-checkins at python.org (andrew.kuchling) Date: Mon, 10 May 2010 21:57:39 +0200 (CEST) Subject: [Python-checkins] r81052 - sandbox/trunk/curses/_cursesmodule.c Message-ID: <20100510195739.BD2B3EAE0@mail.python.org> Author: andrew.kuchling Date: Mon May 10 21:57:39 2010 New Revision: 81052 Log: Break long line in macro Modified: sandbox/trunk/curses/_cursesmodule.c Modified: sandbox/trunk/curses/_cursesmodule.c ============================================================================== --- sandbox/trunk/curses/_cursesmodule.c (original) +++ sandbox/trunk/curses/_cursesmodule.c Mon May 10 21:57:39 2010 @@ -243,42 +243,49 @@ */ #define Window_NoArgNoReturnFunction(X) \ -static PyObject *PyCursesWindow_ ## X (PyCursesWindowObject *self, PyObject *args) \ +static PyObject *PyCursesWindow_ ## X \ +(PyCursesWindowObject *self, PyObject *args) \ { return PyCursesCheckERR(X(self->win), # X); } #define Window_NoArgTrueFalseFunction(X) \ -static PyObject * PyCursesWindow_ ## X (PyCursesWindowObject *self) \ +static PyObject * PyCursesWindow_ ## X \ +(PyCursesWindowObject *self) \ { \ if (X (self->win) == FALSE) { Py_INCREF(Py_False); return Py_False; } \ else { Py_INCREF(Py_True); return Py_True; } } #define Window_NoArgNoReturnVoidFunction(X) \ -static PyObject * PyCursesWindow_ ## X (PyCursesWindowObject *self) \ +static PyObject * PyCursesWindow_ ## X \ +(PyCursesWindowObject *self) \ { \ X(self->win); Py_INCREF(Py_None); return Py_None; } #define Window_NoArg2TupleReturnFunction(X, TYPE, ERGSTR) \ -static PyObject * PyCursesWindow_ ## X (PyCursesWindowObject *self) \ +static PyObject * PyCursesWindow_ ## X \ +(PyCursesWindowObject *self) \ { \ TYPE arg1, arg2; \ X(self->win,arg1,arg2); return Py_BuildValue(ERGSTR, arg1, arg2); } #define Window_OneArgNoReturnVoidFunction(X, TYPE, PARSESTR) \ -static PyObject * PyCursesWindow_ ## X (PyCursesWindowObject *self, PyObject *args) \ +static PyObject * PyCursesWindow_ ## X \ +(PyCursesWindowObject *self, PyObject *args) \ { \ TYPE arg1; \ if (!PyArg_ParseTuple(args, PARSESTR, &arg1)) return NULL; \ X(self->win,arg1); Py_INCREF(Py_None); return Py_None; } #define Window_OneArgNoReturnFunction(X, TYPE, PARSESTR) \ -static PyObject * PyCursesWindow_ ## X (PyCursesWindowObject *self, PyObject *args) \ +static PyObject * PyCursesWindow_ ## X \ +(PyCursesWindowObject *self, PyObject *args) \ { \ TYPE arg1; \ if (!PyArg_ParseTuple(args,PARSESTR, &arg1)) return NULL; \ return PyCursesCheckERR(X(self->win, arg1), # X); } #define Window_TwoArgNoReturnFunction(X, TYPE, PARSESTR) \ -static PyObject * PyCursesWindow_ ## X (PyCursesWindowObject *self, PyObject *args) \ +static PyObject * PyCursesWindow_ ## X \ +(PyCursesWindowObject *self, PyObject *args) \ { \ TYPE arg1, arg2; \ if (!PyArg_ParseTuple(args,PARSESTR, &arg1, &arg2)) return NULL; \ From python-checkins at python.org Mon May 10 21:59:22 2010 From: python-checkins at python.org (florent.xicluna) Date: Mon, 10 May 2010 21:59:22 +0200 (CEST) Subject: [Python-checkins] r81053 - python/trunk/Doc/library/stdtypes.rst Message-ID: <20100510195922.E86BCEE9F4@mail.python.org> Author: florent.xicluna Date: Mon May 10 21:59:22 2010 New Revision: 81053 Log: Add a link on maketrans(). Modified: python/trunk/Doc/library/stdtypes.rst Modified: python/trunk/Doc/library/stdtypes.rst ============================================================================== --- python/trunk/Doc/library/stdtypes.rst (original) +++ python/trunk/Doc/library/stdtypes.rst Mon May 10 21:59:22 2010 @@ -1220,9 +1220,9 @@ mapped through the given translation table, which must be a string of length 256. - You can use the :func:`maketrans` helper function in the :mod:`string` module to - create a translation table. For string objects, set the *table* argument to - ``None`` for translations that only delete characters: + You can use the :func:`~string.maketrans` helper function in the :mod:`string` + module to create a translation table. For string objects, set the *table* + argument to ``None`` for translations that only delete characters: >>> 'read this short text'.translate(None, 'aeiou') 'rd ths shrt txt' From python-checkins at python.org Mon May 10 22:09:50 2010 From: python-checkins at python.org (andrew.kuchling) Date: Mon, 10 May 2010 22:09:50 +0200 (CEST) Subject: [Python-checkins] r81054 - sandbox/trunk/curses/_cursesmodule.c Message-ID: <20100510200950.9058EC83B@mail.python.org> Author: andrew.kuchling Date: Mon May 10 22:09:50 2010 New Revision: 81054 Log: Re-indent using Emacs c-mode with Barry's suggested change; delete trailing whitespace; untabify Modified: sandbox/trunk/curses/_cursesmodule.c Modified: sandbox/trunk/curses/_cursesmodule.c ============================================================================== --- sandbox/trunk/curses/_cursesmodule.c (original) +++ sandbox/trunk/curses/_cursesmodule.c Mon May 10 22:09:50 2010 @@ -40,56 +40,56 @@ Here's a list of currently unsupported functions: - addchnstr addchstr color_set define_key - del_curterm delscreen dupwin inchnstr inchstr innstr keyok - mcprint mvaddchnstr mvaddchstr mvcur mvinchnstr - mvinchstr mvinnstr mmvwaddchnstr mvwaddchstr - mvwinchnstr mvwinchstr mvwinnstr newterm - restartterm ripoffline scr_dump - scr_init scr_restore scr_set scrl set_curterm set_term setterm - tgetent tgetflag tgetnum tgetstr tgoto timeout tputs - vidattr vidputs waddchnstr waddchstr - wcolor_set winchnstr winchstr winnstr wmouse_trafo wscrl - -Low-priority: - slk_attr slk_attr_off slk_attr_on slk_attr_set slk_attroff - slk_attron slk_attrset slk_clear slk_color slk_init slk_label - slk_noutrefresh slk_refresh slk_restore slk_set slk_touch + addchnstr addchstr color_set define_key + del_curterm delscreen dupwin inchnstr inchstr innstr keyok + mcprint mvaddchnstr mvaddchstr mvcur mvinchnstr + mvinchstr mvinnstr mmvwaddchnstr mvwaddchstr + mvwinchnstr mvwinchstr mvwinnstr newterm + restartterm ripoffline scr_dump + scr_init scr_restore scr_set scrl set_curterm set_term setterm + tgetent tgetflag tgetnum tgetstr tgoto timeout tputs + vidattr vidputs waddchnstr waddchstr + wcolor_set winchnstr winchstr winnstr wmouse_trafo wscrl + +Low-priority: + slk_attr slk_attr_off slk_attr_on slk_attr_set slk_attroff + slk_attron slk_attrset slk_clear slk_color slk_init slk_label + slk_noutrefresh slk_refresh slk_restore slk_set slk_touch Menu extension (ncurses and probably SYSV): - current_item free_item free_menu item_count item_description - item_index item_init item_name item_opts item_opts_off - item_opts_on item_term item_userptr item_value item_visible - menu_back menu_driver menu_fore menu_format menu_grey - menu_init menu_items menu_mark menu_opts menu_opts_off - menu_opts_on menu_pad menu_pattern menu_request_by_name - menu_request_name menu_spacing menu_sub menu_term menu_userptr - menu_win new_item new_menu pos_menu_cursor post_menu - scale_menu set_current_item set_item_init set_item_opts - set_item_term set_item_userptr set_item_value set_menu_back - set_menu_fore set_menu_format set_menu_grey set_menu_init - set_menu_items set_menu_mark set_menu_opts set_menu_pad - set_menu_pattern set_menu_spacing set_menu_sub set_menu_term - set_menu_userptr set_menu_win set_top_row top_row unpost_menu + current_item free_item free_menu item_count item_description + item_index item_init item_name item_opts item_opts_off + item_opts_on item_term item_userptr item_value item_visible + menu_back menu_driver menu_fore menu_format menu_grey + menu_init menu_items menu_mark menu_opts menu_opts_off + menu_opts_on menu_pad menu_pattern menu_request_by_name + menu_request_name menu_spacing menu_sub menu_term menu_userptr + menu_win new_item new_menu pos_menu_cursor post_menu + scale_menu set_current_item set_item_init set_item_opts + set_item_term set_item_userptr set_item_value set_menu_back + set_menu_fore set_menu_format set_menu_grey set_menu_init + set_menu_items set_menu_mark set_menu_opts set_menu_pad + set_menu_pattern set_menu_spacing set_menu_sub set_menu_term + set_menu_userptr set_menu_win set_top_row top_row unpost_menu Form extension (ncurses and probably SYSV): - current_field data_ahead data_behind dup_field - dynamic_fieldinfo field_arg field_back field_buffer - field_count field_fore field_index field_info field_init - field_just field_opts field_opts_off field_opts_on field_pad - field_status field_term field_type field_userptr form_driver - form_fields form_init form_opts form_opts_off form_opts_on - form_page form_request_by_name form_request_name form_sub - form_term form_userptr form_win free_field free_form - link_field link_fieldtype move_field new_field new_form - new_page pos_form_cursor post_form scale_form - set_current_field set_field_back set_field_buffer - set_field_fore set_field_init set_field_just set_field_opts - set_field_pad set_field_status set_field_term set_field_type - set_field_userptr set_fieldtype_arg set_fieldtype_choice - set_form_fields set_form_init set_form_opts set_form_page - set_form_sub set_form_term set_form_userptr set_form_win - set_max_field set_new_page unpost_form + current_field data_ahead data_behind dup_field + dynamic_fieldinfo field_arg field_back field_buffer + field_count field_fore field_index field_info field_init + field_just field_opts field_opts_off field_opts_on field_pad + field_status field_term field_type field_userptr form_driver + form_fields form_init form_opts form_opts_off form_opts_on + form_page form_request_by_name form_request_name form_sub + form_term form_userptr form_win free_field free_form + link_field link_fieldtype move_field new_field new_form + new_page pos_form_cursor post_form scale_form + set_current_field set_field_back set_field_buffer + set_field_fore set_field_init set_field_just set_field_opts + set_field_pad set_field_status set_field_term set_field_type + set_field_userptr set_fieldtype_arg set_fieldtype_choice + set_form_fields set_form_init set_form_opts set_form_page + set_form_sub set_form_term set_form_userptr set_form_win + set_max_field set_new_page unpost_form */ @@ -113,9 +113,9 @@ #define CURSES_MODULE #include "py_curses.h" -/* These prototypes are in , but including this header - #defines many common symbols (such as "lines") which breaks the - curses module in other ways. So the code will just specify +/* These prototypes are in , but including this header + #defines many common symbols (such as "lines") which breaks the + curses module in other ways. So the code will just specify explicit prototypes here. */ extern int setupterm(char *,int,int *); #ifdef __sgi @@ -145,23 +145,23 @@ static int initialisedcolors = FALSE; /* Utility Macros */ -#define PyCursesSetupTermCalled \ - if (initialised_setupterm != TRUE) { \ - PyErr_SetString(PyCursesError, \ - "must call (at least) setupterm() first"); \ - return 0; } - -#define PyCursesInitialised \ - if (initialised != TRUE) { \ - PyErr_SetString(PyCursesError, \ - "must call initscr() first"); \ - return 0; } - -#define PyCursesInitialisedColor \ - if (initialisedcolors != TRUE) { \ - PyErr_SetString(PyCursesError, \ - "must call start_color() first"); \ - return 0; } +#define PyCursesSetupTermCalled \ + if (initialised_setupterm != TRUE) { \ + PyErr_SetString(PyCursesError, \ + "must call (at least) setupterm() first"); \ + return 0; } + +#define PyCursesInitialised \ + if (initialised != TRUE) { \ + PyErr_SetString(PyCursesError, \ + "must call initscr() first"); \ + return 0; } + +#define PyCursesInitialisedColor \ + if (initialisedcolors != TRUE) { \ + PyErr_SetString(PyCursesError, \ + "must call start_color() first"); \ + return 0; } #ifndef MIN #define MIN(x,y) ((x) < (y) ? (x) : (y)) @@ -170,7 +170,7 @@ /* Utility Functions */ /* - * Check the return code from a curses function and return None + * Check the return code from a curses function and return None * or raise an exception as appropriate. These are exported using the * capsule API. */ @@ -178,36 +178,36 @@ static PyObject * PyCursesCheckERR(int code, char *fname) { - if (code != ERR) { - Py_INCREF(Py_None); - return Py_None; - } else { - if (fname == NULL) { - PyErr_SetString(PyCursesError, catchall_ERR); + if (code != ERR) { + Py_INCREF(Py_None); + return Py_None; } else { - PyErr_Format(PyCursesError, "%s() returned ERR", fname); + if (fname == NULL) { + PyErr_SetString(PyCursesError, catchall_ERR); + } else { + PyErr_Format(PyCursesError, "%s() returned ERR", fname); + } + return NULL; } - return NULL; - } } -static int +static int PyCurses_ConvertToChtype(PyObject *obj, chtype *ch) { - if (PyInt_Check(obj)) { - *ch = (chtype) PyInt_AsLong(obj); - } else if(PyString_Check(obj) - && (PyString_Size(obj) == 1)) { - *ch = (chtype) *PyString_AsString(obj); - } else { - return 0; - } - return 1; + if (PyInt_Check(obj)) { + *ch = (chtype) PyInt_AsLong(obj); + } else if(PyString_Check(obj) + && (PyString_Size(obj) == 1)) { + *ch = (chtype) *PyString_AsString(obj); + } else { + return 0; + } + return 1; } /* Function versions of the 3 functions for testing whether curses has been initialised or not. */ - + static int func_PyCursesSetupTermCalled(void) { PyCursesSetupTermCalled; @@ -242,54 +242,54 @@ PARSESTR - format string for argument parsing */ -#define Window_NoArgNoReturnFunction(X) \ -static PyObject *PyCursesWindow_ ## X \ -(PyCursesWindowObject *self, PyObject *args) \ -{ return PyCursesCheckERR(X(self->win), # X); } - -#define Window_NoArgTrueFalseFunction(X) \ -static PyObject * PyCursesWindow_ ## X \ -(PyCursesWindowObject *self) \ -{ \ - if (X (self->win) == FALSE) { Py_INCREF(Py_False); return Py_False; } \ - else { Py_INCREF(Py_True); return Py_True; } } - -#define Window_NoArgNoReturnVoidFunction(X) \ -static PyObject * PyCursesWindow_ ## X \ -(PyCursesWindowObject *self) \ -{ \ - X(self->win); Py_INCREF(Py_None); return Py_None; } - -#define Window_NoArg2TupleReturnFunction(X, TYPE, ERGSTR) \ -static PyObject * PyCursesWindow_ ## X \ -(PyCursesWindowObject *self) \ -{ \ - TYPE arg1, arg2; \ - X(self->win,arg1,arg2); return Py_BuildValue(ERGSTR, arg1, arg2); } - -#define Window_OneArgNoReturnVoidFunction(X, TYPE, PARSESTR) \ -static PyObject * PyCursesWindow_ ## X \ -(PyCursesWindowObject *self, PyObject *args) \ -{ \ - TYPE arg1; \ - if (!PyArg_ParseTuple(args, PARSESTR, &arg1)) return NULL; \ - X(self->win,arg1); Py_INCREF(Py_None); return Py_None; } - -#define Window_OneArgNoReturnFunction(X, TYPE, PARSESTR) \ -static PyObject * PyCursesWindow_ ## X \ -(PyCursesWindowObject *self, PyObject *args) \ -{ \ - TYPE arg1; \ - if (!PyArg_ParseTuple(args,PARSESTR, &arg1)) return NULL; \ - return PyCursesCheckERR(X(self->win, arg1), # X); } - -#define Window_TwoArgNoReturnFunction(X, TYPE, PARSESTR) \ -static PyObject * PyCursesWindow_ ## X \ -(PyCursesWindowObject *self, PyObject *args) \ -{ \ - TYPE arg1, arg2; \ - if (!PyArg_ParseTuple(args,PARSESTR, &arg1, &arg2)) return NULL; \ - return PyCursesCheckERR(X(self->win, arg1, arg2), # X); } +#define Window_NoArgNoReturnFunction(X) \ + static PyObject *PyCursesWindow_ ## X \ + (PyCursesWindowObject *self, PyObject *args) \ + { return PyCursesCheckERR(X(self->win), # X); } + +#define Window_NoArgTrueFalseFunction(X) \ + static PyObject * PyCursesWindow_ ## X \ + (PyCursesWindowObject *self) \ + { \ + if (X (self->win) == FALSE) { Py_INCREF(Py_False); return Py_False; } \ + else { Py_INCREF(Py_True); return Py_True; } } + +#define Window_NoArgNoReturnVoidFunction(X) \ + static PyObject * PyCursesWindow_ ## X \ + (PyCursesWindowObject *self) \ + { \ + X(self->win); Py_INCREF(Py_None); return Py_None; } + +#define Window_NoArg2TupleReturnFunction(X, TYPE, ERGSTR) \ + static PyObject * PyCursesWindow_ ## X \ + (PyCursesWindowObject *self) \ + { \ + TYPE arg1, arg2; \ + X(self->win,arg1,arg2); return Py_BuildValue(ERGSTR, arg1, arg2); } + +#define Window_OneArgNoReturnVoidFunction(X, TYPE, PARSESTR) \ + static PyObject * PyCursesWindow_ ## X \ + (PyCursesWindowObject *self, PyObject *args) \ + { \ + TYPE arg1; \ + if (!PyArg_ParseTuple(args, PARSESTR, &arg1)) return NULL; \ + X(self->win,arg1); Py_INCREF(Py_None); return Py_None; } + +#define Window_OneArgNoReturnFunction(X, TYPE, PARSESTR) \ + static PyObject * PyCursesWindow_ ## X \ + (PyCursesWindowObject *self, PyObject *args) \ + { \ + TYPE arg1; \ + if (!PyArg_ParseTuple(args,PARSESTR, &arg1)) return NULL; \ + return PyCursesCheckERR(X(self->win, arg1), # X); } + +#define Window_TwoArgNoReturnFunction(X, TYPE, PARSESTR) \ + static PyObject * PyCursesWindow_ ## X \ + (PyCursesWindowObject *self, PyObject *args) \ + { \ + TYPE arg1, arg2; \ + if (!PyArg_ParseTuple(args,PARSESTR, &arg1, &arg2)) return NULL; \ + return PyCursesCheckERR(X(self->win, arg1, arg2), # X); } /* ------------- WINDOW routines --------------- */ @@ -350,19 +350,19 @@ static PyObject * PyCursesWindow_New(WINDOW *win) { - PyCursesWindowObject *wo; + PyCursesWindowObject *wo; - wo = PyObject_NEW(PyCursesWindowObject, &PyCursesWindow_Type); - if (wo == NULL) return NULL; - wo->win = win; - return (PyObject *)wo; + wo = PyObject_NEW(PyCursesWindowObject, &PyCursesWindow_Type); + if (wo == NULL) return NULL; + wo->win = win; + return (PyObject *)wo; } static void PyCursesWindow_Dealloc(PyCursesWindowObject *wo) { - if (wo->win != stdscr) delwin(wo->win); - PyObject_DEL(wo); + if (wo->win != stdscr) delwin(wo->win); + PyObject_DEL(wo); } /* Addch, Addstr, Addnstr */ @@ -370,287 +370,287 @@ static PyObject * PyCursesWindow_AddCh(PyCursesWindowObject *self, PyObject *args) { - int rtn, x, y, use_xy = FALSE; - PyObject *temp; - chtype ch = 0; - attr_t attr = A_NORMAL; - long lattr; - - switch (PyTuple_Size(args)) { - case 1: - if (!PyArg_ParseTuple(args, "O;ch or int", &temp)) - return NULL; - break; - case 2: - if (!PyArg_ParseTuple(args, "Ol;ch or int,attr", &temp, &lattr)) - return NULL; - attr = lattr; - break; - case 3: - if (!PyArg_ParseTuple(args,"iiO;y,x,ch or int", &y, &x, &temp)) - return NULL; - use_xy = TRUE; - break; - case 4: - if (!PyArg_ParseTuple(args,"iiOl;y,x,ch or int, attr", - &y, &x, &temp, &lattr)) - return NULL; - attr = lattr; - use_xy = TRUE; - break; - default: - PyErr_SetString(PyExc_TypeError, "addch requires 1 to 4 arguments"); - return NULL; - } - - if (!PyCurses_ConvertToChtype(temp, &ch)) { - PyErr_SetString(PyExc_TypeError, "argument 1 or 3 must be a ch or an int"); - return NULL; - } - - if (use_xy == TRUE) - rtn = mvwaddch(self->win,y,x, ch | attr); - else { - rtn = waddch(self->win, ch | attr); - } - return PyCursesCheckERR(rtn, "addch"); + int rtn, x, y, use_xy = FALSE; + PyObject *temp; + chtype ch = 0; + attr_t attr = A_NORMAL; + long lattr; + + switch (PyTuple_Size(args)) { + case 1: + if (!PyArg_ParseTuple(args, "O;ch or int", &temp)) + return NULL; + break; + case 2: + if (!PyArg_ParseTuple(args, "Ol;ch or int,attr", &temp, &lattr)) + return NULL; + attr = lattr; + break; + case 3: + if (!PyArg_ParseTuple(args,"iiO;y,x,ch or int", &y, &x, &temp)) + return NULL; + use_xy = TRUE; + break; + case 4: + if (!PyArg_ParseTuple(args,"iiOl;y,x,ch or int, attr", + &y, &x, &temp, &lattr)) + return NULL; + attr = lattr; + use_xy = TRUE; + break; + default: + PyErr_SetString(PyExc_TypeError, "addch requires 1 to 4 arguments"); + return NULL; + } + + if (!PyCurses_ConvertToChtype(temp, &ch)) { + PyErr_SetString(PyExc_TypeError, "argument 1 or 3 must be a ch or an int"); + return NULL; + } + + if (use_xy == TRUE) + rtn = mvwaddch(self->win,y,x, ch | attr); + else { + rtn = waddch(self->win, ch | attr); + } + return PyCursesCheckERR(rtn, "addch"); } static PyObject * PyCursesWindow_AddStr(PyCursesWindowObject *self, PyObject *args) { - int rtn; - int x, y; - char *str; - attr_t attr = A_NORMAL , attr_old = A_NORMAL; - long lattr; - int use_xy = FALSE, use_attr = FALSE; - - switch (PyTuple_Size(args)) { - case 1: - if (!PyArg_ParseTuple(args,"s;str", &str)) - return NULL; - break; - case 2: - if (!PyArg_ParseTuple(args,"sl;str,attr", &str, &lattr)) - return NULL; - attr = lattr; - use_attr = TRUE; - break; - case 3: - if (!PyArg_ParseTuple(args,"iis;int,int,str", &y, &x, &str)) - return NULL; - use_xy = TRUE; - break; - case 4: - if (!PyArg_ParseTuple(args,"iisl;int,int,str,attr", &y, &x, &str, &lattr)) - return NULL; - attr = lattr; - use_xy = use_attr = TRUE; - break; - default: - PyErr_SetString(PyExc_TypeError, "addstr requires 1 to 4 arguments"); - return NULL; - } - - if (use_attr == TRUE) { - attr_old = getattrs(self->win); - (void)wattrset(self->win,attr); - } - if (use_xy == TRUE) - rtn = mvwaddstr(self->win,y,x,str); - else - rtn = waddstr(self->win,str); - if (use_attr == TRUE) - (void)wattrset(self->win,attr_old); - return PyCursesCheckERR(rtn, "addstr"); + int rtn; + int x, y; + char *str; + attr_t attr = A_NORMAL , attr_old = A_NORMAL; + long lattr; + int use_xy = FALSE, use_attr = FALSE; + + switch (PyTuple_Size(args)) { + case 1: + if (!PyArg_ParseTuple(args,"s;str", &str)) + return NULL; + break; + case 2: + if (!PyArg_ParseTuple(args,"sl;str,attr", &str, &lattr)) + return NULL; + attr = lattr; + use_attr = TRUE; + break; + case 3: + if (!PyArg_ParseTuple(args,"iis;int,int,str", &y, &x, &str)) + return NULL; + use_xy = TRUE; + break; + case 4: + if (!PyArg_ParseTuple(args,"iisl;int,int,str,attr", &y, &x, &str, &lattr)) + return NULL; + attr = lattr; + use_xy = use_attr = TRUE; + break; + default: + PyErr_SetString(PyExc_TypeError, "addstr requires 1 to 4 arguments"); + return NULL; + } + + if (use_attr == TRUE) { + attr_old = getattrs(self->win); + (void)wattrset(self->win,attr); + } + if (use_xy == TRUE) + rtn = mvwaddstr(self->win,y,x,str); + else + rtn = waddstr(self->win,str); + if (use_attr == TRUE) + (void)wattrset(self->win,attr_old); + return PyCursesCheckERR(rtn, "addstr"); } static PyObject * PyCursesWindow_AddNStr(PyCursesWindowObject *self, PyObject *args) { - int rtn, x, y, n; - char *str; - attr_t attr = A_NORMAL , attr_old = A_NORMAL; - long lattr; - int use_xy = FALSE, use_attr = FALSE; - - switch (PyTuple_Size(args)) { - case 2: - if (!PyArg_ParseTuple(args,"si;str,n", &str, &n)) - return NULL; - break; - case 3: - if (!PyArg_ParseTuple(args,"sil;str,n,attr", &str, &n, &lattr)) - return NULL; - attr = lattr; - use_attr = TRUE; - break; - case 4: - if (!PyArg_ParseTuple(args,"iisi;y,x,str,n", &y, &x, &str, &n)) - return NULL; - use_xy = TRUE; - break; - case 5: - if (!PyArg_ParseTuple(args,"iisil;y,x,str,n,attr", &y, &x, &str, &n, &lattr)) - return NULL; - attr = lattr; - use_xy = use_attr = TRUE; - break; - default: - PyErr_SetString(PyExc_TypeError, "addnstr requires 2 to 5 arguments"); - return NULL; - } - - if (use_attr == TRUE) { - attr_old = getattrs(self->win); - (void)wattrset(self->win,attr); - } - if (use_xy == TRUE) - rtn = mvwaddnstr(self->win,y,x,str,n); - else - rtn = waddnstr(self->win,str,n); - if (use_attr == TRUE) - (void)wattrset(self->win,attr_old); - return PyCursesCheckERR(rtn, "addnstr"); + int rtn, x, y, n; + char *str; + attr_t attr = A_NORMAL , attr_old = A_NORMAL; + long lattr; + int use_xy = FALSE, use_attr = FALSE; + + switch (PyTuple_Size(args)) { + case 2: + if (!PyArg_ParseTuple(args,"si;str,n", &str, &n)) + return NULL; + break; + case 3: + if (!PyArg_ParseTuple(args,"sil;str,n,attr", &str, &n, &lattr)) + return NULL; + attr = lattr; + use_attr = TRUE; + break; + case 4: + if (!PyArg_ParseTuple(args,"iisi;y,x,str,n", &y, &x, &str, &n)) + return NULL; + use_xy = TRUE; + break; + case 5: + if (!PyArg_ParseTuple(args,"iisil;y,x,str,n,attr", &y, &x, &str, &n, &lattr)) + return NULL; + attr = lattr; + use_xy = use_attr = TRUE; + break; + default: + PyErr_SetString(PyExc_TypeError, "addnstr requires 2 to 5 arguments"); + return NULL; + } + + if (use_attr == TRUE) { + attr_old = getattrs(self->win); + (void)wattrset(self->win,attr); + } + if (use_xy == TRUE) + rtn = mvwaddnstr(self->win,y,x,str,n); + else + rtn = waddnstr(self->win,str,n); + if (use_attr == TRUE) + (void)wattrset(self->win,attr_old); + return PyCursesCheckERR(rtn, "addnstr"); } static PyObject * PyCursesWindow_Bkgd(PyCursesWindowObject *self, PyObject *args) { - PyObject *temp; - chtype bkgd; - attr_t attr = A_NORMAL; - long lattr; + PyObject *temp; + chtype bkgd; + attr_t attr = A_NORMAL; + long lattr; - switch (PyTuple_Size(args)) { + switch (PyTuple_Size(args)) { case 1: - if (!PyArg_ParseTuple(args, "O;ch or int", &temp)) - return NULL; - break; + if (!PyArg_ParseTuple(args, "O;ch or int", &temp)) + return NULL; + break; case 2: - if (!PyArg_ParseTuple(args,"Ol;ch or int,attr", &temp, &lattr)) - return NULL; - attr = lattr; - break; + if (!PyArg_ParseTuple(args,"Ol;ch or int,attr", &temp, &lattr)) + return NULL; + attr = lattr; + break; default: - PyErr_SetString(PyExc_TypeError, "bkgd requires 1 or 2 arguments"); - return NULL; - } + PyErr_SetString(PyExc_TypeError, "bkgd requires 1 or 2 arguments"); + return NULL; + } - if (!PyCurses_ConvertToChtype(temp, &bkgd)) { - PyErr_SetString(PyExc_TypeError, "argument 1 or 3 must be a ch or an int"); - return NULL; - } + if (!PyCurses_ConvertToChtype(temp, &bkgd)) { + PyErr_SetString(PyExc_TypeError, "argument 1 or 3 must be a ch or an int"); + return NULL; + } - return PyCursesCheckERR(wbkgd(self->win, bkgd | attr), "bkgd"); + return PyCursesCheckERR(wbkgd(self->win, bkgd | attr), "bkgd"); } static PyObject * PyCursesWindow_AttrOff(PyCursesWindowObject *self, PyObject *args) { - long lattr; - if (!PyArg_ParseTuple(args,"l;attr", &lattr)) - return NULL; - return PyCursesCheckERR(wattroff(self->win, (attr_t)lattr), "attroff"); + long lattr; + if (!PyArg_ParseTuple(args,"l;attr", &lattr)) + return NULL; + return PyCursesCheckERR(wattroff(self->win, (attr_t)lattr), "attroff"); } static PyObject * PyCursesWindow_AttrOn(PyCursesWindowObject *self, PyObject *args) { - long lattr; - if (!PyArg_ParseTuple(args,"l;attr", &lattr)) - return NULL; - return PyCursesCheckERR(wattron(self->win, (attr_t)lattr), "attron"); + long lattr; + if (!PyArg_ParseTuple(args,"l;attr", &lattr)) + return NULL; + return PyCursesCheckERR(wattron(self->win, (attr_t)lattr), "attron"); } static PyObject * PyCursesWindow_AttrSet(PyCursesWindowObject *self, PyObject *args) { - long lattr; - if (!PyArg_ParseTuple(args,"l;attr", &lattr)) - return NULL; - return PyCursesCheckERR(wattrset(self->win, (attr_t)lattr), "attrset"); + long lattr; + if (!PyArg_ParseTuple(args,"l;attr", &lattr)) + return NULL; + return PyCursesCheckERR(wattrset(self->win, (attr_t)lattr), "attrset"); } static PyObject * PyCursesWindow_BkgdSet(PyCursesWindowObject *self, PyObject *args) { - PyObject *temp; - chtype bkgd; - attr_t attr = A_NORMAL; - long lattr; + PyObject *temp; + chtype bkgd; + attr_t attr = A_NORMAL; + long lattr; - switch (PyTuple_Size(args)) { + switch (PyTuple_Size(args)) { case 1: - if (!PyArg_ParseTuple(args, "O;ch or int", &temp)) - return NULL; - break; + if (!PyArg_ParseTuple(args, "O;ch or int", &temp)) + return NULL; + break; case 2: - if (!PyArg_ParseTuple(args,"Ol;ch or int,attr", &temp, &lattr)) - return NULL; - attr = lattr; - break; + if (!PyArg_ParseTuple(args,"Ol;ch or int,attr", &temp, &lattr)) + return NULL; + attr = lattr; + break; default: - PyErr_SetString(PyExc_TypeError, "bkgdset requires 1 or 2 arguments"); - return NULL; - } + PyErr_SetString(PyExc_TypeError, "bkgdset requires 1 or 2 arguments"); + return NULL; + } - if (!PyCurses_ConvertToChtype(temp, &bkgd)) { - PyErr_SetString(PyExc_TypeError, "argument 1 must be a ch or an int"); - return NULL; - } + if (!PyCurses_ConvertToChtype(temp, &bkgd)) { + PyErr_SetString(PyExc_TypeError, "argument 1 must be a ch or an int"); + return NULL; + } - wbkgdset(self->win, bkgd | attr); - return PyCursesCheckERR(0, "bkgdset"); + wbkgdset(self->win, bkgd | attr); + return PyCursesCheckERR(0, "bkgdset"); } static PyObject * PyCursesWindow_Border(PyCursesWindowObject *self, PyObject *args) { - PyObject *temp[8]; - chtype ch[8]; - int i; - - /* Clear the array of parameters */ - for(i=0; i<8; i++) { - temp[i] = NULL; - ch[i] = 0; - } - - if (!PyArg_ParseTuple(args,"|OOOOOOOO;ls,rs,ts,bs,tl,tr,bl,br", - &temp[0], &temp[1], &temp[2], &temp[3], - &temp[4], &temp[5], &temp[6], &temp[7])) - return NULL; - - for(i=0; i<8; i++) { - if (temp[i] != NULL && !PyCurses_ConvertToChtype(temp[i], &ch[i])) { - PyErr_Format(PyExc_TypeError, - "argument %i must be a ch or an int", i+1); - return NULL; - } - } - - wborder(self->win, - ch[0], ch[1], ch[2], ch[3], - ch[4], ch[5], ch[6], ch[7]); - Py_INCREF(Py_None); - return Py_None; + PyObject *temp[8]; + chtype ch[8]; + int i; + + /* Clear the array of parameters */ + for(i=0; i<8; i++) { + temp[i] = NULL; + ch[i] = 0; + } + + if (!PyArg_ParseTuple(args,"|OOOOOOOO;ls,rs,ts,bs,tl,tr,bl,br", + &temp[0], &temp[1], &temp[2], &temp[3], + &temp[4], &temp[5], &temp[6], &temp[7])) + return NULL; + + for(i=0; i<8; i++) { + if (temp[i] != NULL && !PyCurses_ConvertToChtype(temp[i], &ch[i])) { + PyErr_Format(PyExc_TypeError, + "argument %i must be a ch or an int", i+1); + return NULL; + } + } + + wborder(self->win, + ch[0], ch[1], ch[2], ch[3], + ch[4], ch[5], ch[6], ch[7]); + Py_INCREF(Py_None); + return Py_None; } static PyObject * PyCursesWindow_Box(PyCursesWindowObject *self, PyObject *args) { - chtype ch1=0,ch2=0; - switch(PyTuple_Size(args)){ - case 0: break; - default: - if (!PyArg_ParseTuple(args,"ll;vertint,horint", &ch1, &ch2)) - return NULL; - } - box(self->win,ch1,ch2); - Py_INCREF(Py_None); - return Py_None; + chtype ch1=0,ch2=0; + switch(PyTuple_Size(args)){ + case 0: break; + default: + if (!PyArg_ParseTuple(args,"ll;vertint,horint", &ch1, &ch2)) + return NULL; + } + box(self->win,ch1,ch2); + Py_INCREF(Py_None); + return Py_None; } #if defined(HAVE_NCURSES_H) || defined(MVWDELCH_IS_EXPRESSION) @@ -658,10 +658,10 @@ #else int py_mvwdelch(WINDOW *w, int y, int x) { - mvwdelch(w,y,x); - /* On HP/UX, mvwdelch already returns. On other systems, - we may well run into this return statement. */ - return 0; + mvwdelch(w,y,x); + /* On HP/UX, mvwdelch already returns. On other systems, + we may well run into this return statement. */ + return 0; } #endif @@ -670,603 +670,603 @@ static PyObject * PyCursesWindow_ChgAt(PyCursesWindowObject *self, PyObject *args) { - int rtn; - int x, y; - int num = -1; - short color; - attr_t attr = A_NORMAL; - long lattr; - int use_xy = FALSE; + int rtn; + int x, y; + int num = -1; + short color; + attr_t attr = A_NORMAL; + long lattr; + int use_xy = FALSE; - switch (PyTuple_Size(args)) { - case 1: - if (!PyArg_ParseTuple(args,"l;attr", &lattr)) - return NULL; - attr = lattr; - break; - case 2: - if (!PyArg_ParseTuple(args,"il;n,attr", &num, &lattr)) - return NULL; - attr = lattr; - break; - case 3: - if (!PyArg_ParseTuple(args,"iil;int,int,attr", &y, &x, &lattr)) - return NULL; - attr = lattr; - use_xy = TRUE; - break; - case 4: - if (!PyArg_ParseTuple(args,"iiil;int,int,n,attr", &y, &x, &num, &lattr)) - return NULL; - attr = lattr; - use_xy = TRUE; - break; - default: - PyErr_SetString(PyExc_TypeError, "chgat requires 1 to 4 arguments"); - return NULL; - } - - color = (short)((attr >> 8) & 0xff); - attr = attr - (color << 8); - - if (use_xy == TRUE) { - rtn = mvwchgat(self->win,y,x,num,attr,color,NULL); - touchline(self->win,y,1); - } else { - getyx(self->win,y,x); - rtn = wchgat(self->win,num,attr,color,NULL); - touchline(self->win,y,1); - } - return PyCursesCheckERR(rtn, "chgat"); + switch (PyTuple_Size(args)) { + case 1: + if (!PyArg_ParseTuple(args,"l;attr", &lattr)) + return NULL; + attr = lattr; + break; + case 2: + if (!PyArg_ParseTuple(args,"il;n,attr", &num, &lattr)) + return NULL; + attr = lattr; + break; + case 3: + if (!PyArg_ParseTuple(args,"iil;int,int,attr", &y, &x, &lattr)) + return NULL; + attr = lattr; + use_xy = TRUE; + break; + case 4: + if (!PyArg_ParseTuple(args,"iiil;int,int,n,attr", &y, &x, &num, &lattr)) + return NULL; + attr = lattr; + use_xy = TRUE; + break; + default: + PyErr_SetString(PyExc_TypeError, "chgat requires 1 to 4 arguments"); + return NULL; + } + + color = (short)((attr >> 8) & 0xff); + attr = attr - (color << 8); + + if (use_xy == TRUE) { + rtn = mvwchgat(self->win,y,x,num,attr,color,NULL); + touchline(self->win,y,1); + } else { + getyx(self->win,y,x); + rtn = wchgat(self->win,num,attr,color,NULL); + touchline(self->win,y,1); + } + return PyCursesCheckERR(rtn, "chgat"); } static PyObject * PyCursesWindow_DelCh(PyCursesWindowObject *self, PyObject *args) { - int rtn; - int x, y; + int rtn; + int x, y; - switch (PyTuple_Size(args)) { - case 0: - rtn = wdelch(self->win); - break; - case 2: - if (!PyArg_ParseTuple(args,"ii;y,x", &y, &x)) - return NULL; - rtn = py_mvwdelch(self->win,y,x); - break; - default: - PyErr_SetString(PyExc_TypeError, "delch requires 0 or 2 arguments"); - return NULL; - } - return PyCursesCheckERR(rtn, "[mv]wdelch"); + switch (PyTuple_Size(args)) { + case 0: + rtn = wdelch(self->win); + break; + case 2: + if (!PyArg_ParseTuple(args,"ii;y,x", &y, &x)) + return NULL; + rtn = py_mvwdelch(self->win,y,x); + break; + default: + PyErr_SetString(PyExc_TypeError, "delch requires 0 or 2 arguments"); + return NULL; + } + return PyCursesCheckERR(rtn, "[mv]wdelch"); } static PyObject * PyCursesWindow_DerWin(PyCursesWindowObject *self, PyObject *args) { - WINDOW *win; - int nlines, ncols, begin_y, begin_x; + WINDOW *win; + int nlines, ncols, begin_y, begin_x; - nlines = 0; - ncols = 0; - switch (PyTuple_Size(args)) { - case 2: - if (!PyArg_ParseTuple(args,"ii;begin_y,begin_x",&begin_y,&begin_x)) - return NULL; - break; - case 4: - if (!PyArg_ParseTuple(args, "iiii;nlines,ncols,begin_y,begin_x", - &nlines,&ncols,&begin_y,&begin_x)) - return NULL; - break; - default: - PyErr_SetString(PyExc_TypeError, "derwin requires 2 or 4 arguments"); - return NULL; - } - - win = derwin(self->win,nlines,ncols,begin_y,begin_x); - - if (win == NULL) { - PyErr_SetString(PyCursesError, catchall_NULL); - return NULL; - } + nlines = 0; + ncols = 0; + switch (PyTuple_Size(args)) { + case 2: + if (!PyArg_ParseTuple(args,"ii;begin_y,begin_x",&begin_y,&begin_x)) + return NULL; + break; + case 4: + if (!PyArg_ParseTuple(args, "iiii;nlines,ncols,begin_y,begin_x", + &nlines,&ncols,&begin_y,&begin_x)) + return NULL; + break; + default: + PyErr_SetString(PyExc_TypeError, "derwin requires 2 or 4 arguments"); + return NULL; + } - return (PyObject *)PyCursesWindow_New(win); + win = derwin(self->win,nlines,ncols,begin_y,begin_x); + + if (win == NULL) { + PyErr_SetString(PyCursesError, catchall_NULL); + return NULL; + } + + return (PyObject *)PyCursesWindow_New(win); } static PyObject * PyCursesWindow_EchoChar(PyCursesWindowObject *self, PyObject *args) { - PyObject *temp; - chtype ch; - attr_t attr = A_NORMAL; - long lattr; - - switch (PyTuple_Size(args)) { - case 1: - if (!PyArg_ParseTuple(args,"O;ch or int", &temp)) - return NULL; - break; - case 2: - if (!PyArg_ParseTuple(args,"Ol;ch or int,attr", &temp, &lattr)) - return NULL; - attr = lattr; - break; - default: - PyErr_SetString(PyExc_TypeError, "echochar requires 1 or 2 arguments"); - - - return NULL; - } - - if (!PyCurses_ConvertToChtype(temp, &ch)) { - PyErr_SetString(PyExc_TypeError, "argument 1 must be a ch or an int"); - return NULL; - } - + PyObject *temp; + chtype ch; + attr_t attr = A_NORMAL; + long lattr; + + switch (PyTuple_Size(args)) { + case 1: + if (!PyArg_ParseTuple(args,"O;ch or int", &temp)) + return NULL; + break; + case 2: + if (!PyArg_ParseTuple(args,"Ol;ch or int,attr", &temp, &lattr)) + return NULL; + attr = lattr; + break; + default: + PyErr_SetString(PyExc_TypeError, "echochar requires 1 or 2 arguments"); + + + return NULL; + } + + if (!PyCurses_ConvertToChtype(temp, &ch)) { + PyErr_SetString(PyExc_TypeError, "argument 1 must be a ch or an int"); + return NULL; + } + #ifdef WINDOW_HAS_FLAGS - if (self->win->_flags & _ISPAD) - return PyCursesCheckERR(pechochar(self->win, ch | attr), - "echochar"); - else + if (self->win->_flags & _ISPAD) + return PyCursesCheckERR(pechochar(self->win, ch | attr), + "echochar"); + else #endif - return PyCursesCheckERR(wechochar(self->win, ch | attr), - "echochar"); + return PyCursesCheckERR(wechochar(self->win, ch | attr), + "echochar"); } #ifdef NCURSES_MOUSE_VERSION static PyObject * PyCursesWindow_Enclose(PyCursesWindowObject *self, PyObject *args) { - int x, y; - if (!PyArg_ParseTuple(args,"ii;y,x", &y, &x)) - return NULL; + int x, y; + if (!PyArg_ParseTuple(args,"ii;y,x", &y, &x)) + return NULL; - return PyInt_FromLong( wenclose(self->win,y,x) ); + return PyInt_FromLong( wenclose(self->win,y,x) ); } #endif static PyObject * PyCursesWindow_GetBkgd(PyCursesWindowObject *self) { - return PyInt_FromLong((long) getbkgd(self->win)); + return PyInt_FromLong((long) getbkgd(self->win)); } static PyObject * PyCursesWindow_GetCh(PyCursesWindowObject *self, PyObject *args) { - int x, y; - int rtn; + int x, y; + int rtn; - switch (PyTuple_Size(args)) { - case 0: - Py_BEGIN_ALLOW_THREADS - rtn = wgetch(self->win); - Py_END_ALLOW_THREADS - break; - case 2: - if (!PyArg_ParseTuple(args,"ii;y,x",&y,&x)) - return NULL; - Py_BEGIN_ALLOW_THREADS - rtn = mvwgetch(self->win,y,x); - Py_END_ALLOW_THREADS - break; - default: - PyErr_SetString(PyExc_TypeError, "getch requires 0 or 2 arguments"); - return NULL; - } - return PyInt_FromLong((long)rtn); + switch (PyTuple_Size(args)) { + case 0: + Py_BEGIN_ALLOW_THREADS + rtn = wgetch(self->win); + Py_END_ALLOW_THREADS + break; + case 2: + if (!PyArg_ParseTuple(args,"ii;y,x",&y,&x)) + return NULL; + Py_BEGIN_ALLOW_THREADS + rtn = mvwgetch(self->win,y,x); + Py_END_ALLOW_THREADS + break; + default: + PyErr_SetString(PyExc_TypeError, "getch requires 0 or 2 arguments"); + return NULL; + } + return PyInt_FromLong((long)rtn); } static PyObject * PyCursesWindow_GetKey(PyCursesWindowObject *self, PyObject *args) { - int x, y; - int rtn; + int x, y; + int rtn; - switch (PyTuple_Size(args)) { - case 0: - Py_BEGIN_ALLOW_THREADS - rtn = wgetch(self->win); - Py_END_ALLOW_THREADS - break; - case 2: - if (!PyArg_ParseTuple(args,"ii;y,x",&y,&x)) - return NULL; - Py_BEGIN_ALLOW_THREADS - rtn = mvwgetch(self->win,y,x); - Py_END_ALLOW_THREADS - break; - default: - PyErr_SetString(PyExc_TypeError, "getkey requires 0 or 2 arguments"); - return NULL; - } - if (rtn == ERR) { - /* getch() returns ERR in nodelay mode */ - PyErr_SetString(PyCursesError, "no input"); - return NULL; - } else if (rtn<=255) { - return Py_BuildValue("c", rtn); - } else { - const char *knp; + switch (PyTuple_Size(args)) { + case 0: + Py_BEGIN_ALLOW_THREADS + rtn = wgetch(self->win); + Py_END_ALLOW_THREADS + break; + case 2: + if (!PyArg_ParseTuple(args,"ii;y,x",&y,&x)) + return NULL; + Py_BEGIN_ALLOW_THREADS + rtn = mvwgetch(self->win,y,x); + Py_END_ALLOW_THREADS + break; + default: + PyErr_SetString(PyExc_TypeError, "getkey requires 0 or 2 arguments"); + return NULL; + } + if (rtn == ERR) { + /* getch() returns ERR in nodelay mode */ + PyErr_SetString(PyCursesError, "no input"); + return NULL; + } else if (rtn<=255) { + return Py_BuildValue("c", rtn); + } else { + const char *knp; #if defined(__NetBSD__) - knp = unctrl(rtn); + knp = unctrl(rtn); #else - knp = keyname(rtn); + knp = keyname(rtn); #endif - return PyString_FromString((knp == NULL) ? "" : knp); - } + return PyString_FromString((knp == NULL) ? "" : knp); + } } static PyObject * PyCursesWindow_GetStr(PyCursesWindowObject *self, PyObject *args) { - int x, y, n; - char rtn[1024]; /* This should be big enough.. I hope */ - int rtn2; - - switch (PyTuple_Size(args)) { - case 0: - Py_BEGIN_ALLOW_THREADS - rtn2 = wgetnstr(self->win,rtn, 1023); - Py_END_ALLOW_THREADS - break; - case 1: - if (!PyArg_ParseTuple(args,"i;n", &n)) - return NULL; - Py_BEGIN_ALLOW_THREADS - rtn2 = wgetnstr(self->win,rtn,MIN(n, 1023)); - Py_END_ALLOW_THREADS - break; - case 2: - if (!PyArg_ParseTuple(args,"ii;y,x",&y,&x)) - return NULL; - Py_BEGIN_ALLOW_THREADS + int x, y, n; + char rtn[1024]; /* This should be big enough.. I hope */ + int rtn2; + + switch (PyTuple_Size(args)) { + case 0: + Py_BEGIN_ALLOW_THREADS + rtn2 = wgetnstr(self->win,rtn, 1023); + Py_END_ALLOW_THREADS + break; + case 1: + if (!PyArg_ParseTuple(args,"i;n", &n)) + return NULL; + Py_BEGIN_ALLOW_THREADS + rtn2 = wgetnstr(self->win,rtn,MIN(n, 1023)); + Py_END_ALLOW_THREADS + break; + case 2: + if (!PyArg_ParseTuple(args,"ii;y,x",&y,&x)) + return NULL; + Py_BEGIN_ALLOW_THREADS #ifdef STRICT_SYSV_CURSES - rtn2 = wmove(self->win,y,x)==ERR ? ERR : wgetnstr(self->win, rtn, 1023); + rtn2 = wmove(self->win,y,x)==ERR ? ERR : wgetnstr(self->win, rtn, 1023); #else - rtn2 = mvwgetnstr(self->win,y,x,rtn, 1023); + rtn2 = mvwgetnstr(self->win,y,x,rtn, 1023); #endif - Py_END_ALLOW_THREADS - break; - case 3: - if (!PyArg_ParseTuple(args,"iii;y,x,n", &y, &x, &n)) - return NULL; + Py_END_ALLOW_THREADS + break; + case 3: + if (!PyArg_ParseTuple(args,"iii;y,x,n", &y, &x, &n)) + return NULL; #ifdef STRICT_SYSV_CURSES - Py_BEGIN_ALLOW_THREADS - rtn2 = wmove(self->win,y,x)==ERR ? ERR : - wgetnstr(self->win, rtn, MIN(n, 1023)); - Py_END_ALLOW_THREADS + Py_BEGIN_ALLOW_THREADS + rtn2 = wmove(self->win,y,x)==ERR ? ERR : + wgetnstr(self->win, rtn, MIN(n, 1023)); + Py_END_ALLOW_THREADS #else - Py_BEGIN_ALLOW_THREADS - rtn2 = mvwgetnstr(self->win, y, x, rtn, MIN(n, 1023)); - Py_END_ALLOW_THREADS -#endif - break; - default: - PyErr_SetString(PyExc_TypeError, "getstr requires 0 to 3 arguments"); - return NULL; - } - if (rtn2 == ERR) - rtn[0] = 0; - return PyString_FromString(rtn); + Py_BEGIN_ALLOW_THREADS + rtn2 = mvwgetnstr(self->win, y, x, rtn, MIN(n, 1023)); + Py_END_ALLOW_THREADS +#endif + break; + default: + PyErr_SetString(PyExc_TypeError, "getstr requires 0 to 3 arguments"); + return NULL; + } + if (rtn2 == ERR) + rtn[0] = 0; + return PyString_FromString(rtn); } static PyObject * PyCursesWindow_Hline(PyCursesWindowObject *self, PyObject *args) { - PyObject *temp; - chtype ch; - int n, x, y, code = OK; - attr_t attr = A_NORMAL; - long lattr; - - switch (PyTuple_Size(args)) { - case 2: - if (!PyArg_ParseTuple(args, "Oi;ch or int,n", &temp, &n)) - return NULL; - break; - case 3: - if (!PyArg_ParseTuple(args, "Oil;ch or int,n,attr", &temp, &n, &lattr)) - return NULL; - attr = lattr; - break; - case 4: - if (!PyArg_ParseTuple(args, "iiOi;y,x,ch or int,n", &y, &x, &temp, &n)) - return NULL; - code = wmove(self->win, y, x); - break; - case 5: - if (!PyArg_ParseTuple(args, "iiOil; y,x,ch or int,n,attr", - &y, &x, &temp, &n, &lattr)) - return NULL; - attr = lattr; - code = wmove(self->win, y, x); - break; - default: - PyErr_SetString(PyExc_TypeError, "hline requires 2 to 5 arguments"); - return NULL; - } + PyObject *temp; + chtype ch; + int n, x, y, code = OK; + attr_t attr = A_NORMAL; + long lattr; - if (code != ERR) { - if (!PyCurses_ConvertToChtype(temp, &ch)) { - PyErr_SetString(PyExc_TypeError, - "argument 1 or 3 must be a ch or an int"); - return NULL; - } - return PyCursesCheckERR(whline(self->win, ch | attr, n), "hline"); - } else - return PyCursesCheckERR(code, "wmove"); + switch (PyTuple_Size(args)) { + case 2: + if (!PyArg_ParseTuple(args, "Oi;ch or int,n", &temp, &n)) + return NULL; + break; + case 3: + if (!PyArg_ParseTuple(args, "Oil;ch or int,n,attr", &temp, &n, &lattr)) + return NULL; + attr = lattr; + break; + case 4: + if (!PyArg_ParseTuple(args, "iiOi;y,x,ch or int,n", &y, &x, &temp, &n)) + return NULL; + code = wmove(self->win, y, x); + break; + case 5: + if (!PyArg_ParseTuple(args, "iiOil; y,x,ch or int,n,attr", + &y, &x, &temp, &n, &lattr)) + return NULL; + attr = lattr; + code = wmove(self->win, y, x); + break; + default: + PyErr_SetString(PyExc_TypeError, "hline requires 2 to 5 arguments"); + return NULL; + } + + if (code != ERR) { + if (!PyCurses_ConvertToChtype(temp, &ch)) { + PyErr_SetString(PyExc_TypeError, + "argument 1 or 3 must be a ch or an int"); + return NULL; + } + return PyCursesCheckERR(whline(self->win, ch | attr, n), "hline"); + } else + return PyCursesCheckERR(code, "wmove"); } static PyObject * PyCursesWindow_InsCh(PyCursesWindowObject *self, PyObject *args) { - int rtn, x, y, use_xy = FALSE; - PyObject *temp; - chtype ch = 0; - attr_t attr = A_NORMAL; - long lattr; - - switch (PyTuple_Size(args)) { - case 1: - if (!PyArg_ParseTuple(args, "O;ch or int", &temp)) - return NULL; - break; - case 2: - if (!PyArg_ParseTuple(args, "Ol;ch or int,attr", &temp, &lattr)) - return NULL; - attr = lattr; - break; - case 3: - if (!PyArg_ParseTuple(args,"iiO;y,x,ch or int", &y, &x, &temp)) - return NULL; - use_xy = TRUE; - break; - case 4: - if (!PyArg_ParseTuple(args,"iiOl;y,x,ch or int, attr", &y, &x, &temp, &lattr)) - return NULL; - attr = lattr; - use_xy = TRUE; - break; - default: - PyErr_SetString(PyExc_TypeError, "insch requires 1 or 4 arguments"); - return NULL; - } - - if (!PyCurses_ConvertToChtype(temp, &ch)) { - PyErr_SetString(PyExc_TypeError, - "argument 1 or 3 must be a ch or an int"); - return NULL; - } - - if (use_xy == TRUE) - rtn = mvwinsch(self->win,y,x, ch | attr); - else { - rtn = winsch(self->win, ch | attr); - } - return PyCursesCheckERR(rtn, "insch"); + int rtn, x, y, use_xy = FALSE; + PyObject *temp; + chtype ch = 0; + attr_t attr = A_NORMAL; + long lattr; + + switch (PyTuple_Size(args)) { + case 1: + if (!PyArg_ParseTuple(args, "O;ch or int", &temp)) + return NULL; + break; + case 2: + if (!PyArg_ParseTuple(args, "Ol;ch or int,attr", &temp, &lattr)) + return NULL; + attr = lattr; + break; + case 3: + if (!PyArg_ParseTuple(args,"iiO;y,x,ch or int", &y, &x, &temp)) + return NULL; + use_xy = TRUE; + break; + case 4: + if (!PyArg_ParseTuple(args,"iiOl;y,x,ch or int, attr", &y, &x, &temp, &lattr)) + return NULL; + attr = lattr; + use_xy = TRUE; + break; + default: + PyErr_SetString(PyExc_TypeError, "insch requires 1 or 4 arguments"); + return NULL; + } + + if (!PyCurses_ConvertToChtype(temp, &ch)) { + PyErr_SetString(PyExc_TypeError, + "argument 1 or 3 must be a ch or an int"); + return NULL; + } + + if (use_xy == TRUE) + rtn = mvwinsch(self->win,y,x, ch | attr); + else { + rtn = winsch(self->win, ch | attr); + } + return PyCursesCheckERR(rtn, "insch"); } static PyObject * PyCursesWindow_InCh(PyCursesWindowObject *self, PyObject *args) { - int x, y, rtn; + int x, y, rtn; - switch (PyTuple_Size(args)) { - case 0: - rtn = winch(self->win); - break; - case 2: - if (!PyArg_ParseTuple(args,"ii;y,x",&y,&x)) - return NULL; - rtn = mvwinch(self->win,y,x); - break; - default: - PyErr_SetString(PyExc_TypeError, "inch requires 0 or 2 arguments"); - return NULL; - } - return PyInt_FromLong((long) rtn); + switch (PyTuple_Size(args)) { + case 0: + rtn = winch(self->win); + break; + case 2: + if (!PyArg_ParseTuple(args,"ii;y,x",&y,&x)) + return NULL; + rtn = mvwinch(self->win,y,x); + break; + default: + PyErr_SetString(PyExc_TypeError, "inch requires 0 or 2 arguments"); + return NULL; + } + return PyInt_FromLong((long) rtn); } static PyObject * PyCursesWindow_InStr(PyCursesWindowObject *self, PyObject *args) { - int x, y, n; - char rtn[1024]; /* This should be big enough.. I hope */ - int rtn2; - - switch (PyTuple_Size(args)) { - case 0: - rtn2 = winnstr(self->win,rtn, 1023); - break; - case 1: - if (!PyArg_ParseTuple(args,"i;n", &n)) - return NULL; - rtn2 = winnstr(self->win,rtn,MIN(n,1023)); - break; - case 2: - if (!PyArg_ParseTuple(args,"ii;y,x",&y,&x)) - return NULL; - rtn2 = mvwinnstr(self->win,y,x,rtn,1023); - break; - case 3: - if (!PyArg_ParseTuple(args, "iii;y,x,n", &y, &x, &n)) - return NULL; - rtn2 = mvwinnstr(self->win, y, x, rtn, MIN(n,1023)); - break; - default: - PyErr_SetString(PyExc_TypeError, "instr requires 0 or 3 arguments"); - return NULL; - } - if (rtn2 == ERR) - rtn[0] = 0; - return PyString_FromString(rtn); + int x, y, n; + char rtn[1024]; /* This should be big enough.. I hope */ + int rtn2; + + switch (PyTuple_Size(args)) { + case 0: + rtn2 = winnstr(self->win,rtn, 1023); + break; + case 1: + if (!PyArg_ParseTuple(args,"i;n", &n)) + return NULL; + rtn2 = winnstr(self->win,rtn,MIN(n,1023)); + break; + case 2: + if (!PyArg_ParseTuple(args,"ii;y,x",&y,&x)) + return NULL; + rtn2 = mvwinnstr(self->win,y,x,rtn,1023); + break; + case 3: + if (!PyArg_ParseTuple(args, "iii;y,x,n", &y, &x, &n)) + return NULL; + rtn2 = mvwinnstr(self->win, y, x, rtn, MIN(n,1023)); + break; + default: + PyErr_SetString(PyExc_TypeError, "instr requires 0 or 3 arguments"); + return NULL; + } + if (rtn2 == ERR) + rtn[0] = 0; + return PyString_FromString(rtn); } static PyObject * PyCursesWindow_InsStr(PyCursesWindowObject *self, PyObject *args) { - int rtn; - int x, y; - char *str; - attr_t attr = A_NORMAL , attr_old = A_NORMAL; - long lattr; - int use_xy = FALSE, use_attr = FALSE; - - switch (PyTuple_Size(args)) { - case 1: - if (!PyArg_ParseTuple(args,"s;str", &str)) - return NULL; - break; - case 2: - if (!PyArg_ParseTuple(args,"sl;str,attr", &str, &lattr)) - return NULL; - attr = lattr; - use_attr = TRUE; - break; - case 3: - if (!PyArg_ParseTuple(args,"iis;y,x,str", &y, &x, &str)) - return NULL; - use_xy = TRUE; - break; - case 4: - if (!PyArg_ParseTuple(args,"iisl;y,x,str,attr", &y, &x, &str, &lattr)) - return NULL; - attr = lattr; - use_xy = use_attr = TRUE; - break; - default: - PyErr_SetString(PyExc_TypeError, "insstr requires 1 to 4 arguments"); - return NULL; - } - - if (use_attr == TRUE) { - attr_old = getattrs(self->win); - (void)wattrset(self->win,attr); - } - if (use_xy == TRUE) - rtn = mvwinsstr(self->win,y,x,str); - else - rtn = winsstr(self->win,str); - if (use_attr == TRUE) - (void)wattrset(self->win,attr_old); - return PyCursesCheckERR(rtn, "insstr"); + int rtn; + int x, y; + char *str; + attr_t attr = A_NORMAL , attr_old = A_NORMAL; + long lattr; + int use_xy = FALSE, use_attr = FALSE; + + switch (PyTuple_Size(args)) { + case 1: + if (!PyArg_ParseTuple(args,"s;str", &str)) + return NULL; + break; + case 2: + if (!PyArg_ParseTuple(args,"sl;str,attr", &str, &lattr)) + return NULL; + attr = lattr; + use_attr = TRUE; + break; + case 3: + if (!PyArg_ParseTuple(args,"iis;y,x,str", &y, &x, &str)) + return NULL; + use_xy = TRUE; + break; + case 4: + if (!PyArg_ParseTuple(args,"iisl;y,x,str,attr", &y, &x, &str, &lattr)) + return NULL; + attr = lattr; + use_xy = use_attr = TRUE; + break; + default: + PyErr_SetString(PyExc_TypeError, "insstr requires 1 to 4 arguments"); + return NULL; + } + + if (use_attr == TRUE) { + attr_old = getattrs(self->win); + (void)wattrset(self->win,attr); + } + if (use_xy == TRUE) + rtn = mvwinsstr(self->win,y,x,str); + else + rtn = winsstr(self->win,str); + if (use_attr == TRUE) + (void)wattrset(self->win,attr_old); + return PyCursesCheckERR(rtn, "insstr"); } static PyObject * PyCursesWindow_InsNStr(PyCursesWindowObject *self, PyObject *args) { - int rtn, x, y, n; - char *str; - attr_t attr = A_NORMAL , attr_old = A_NORMAL; - long lattr; - int use_xy = FALSE, use_attr = FALSE; - - switch (PyTuple_Size(args)) { - case 2: - if (!PyArg_ParseTuple(args,"si;str,n", &str, &n)) - return NULL; - break; - case 3: - if (!PyArg_ParseTuple(args,"sil;str,n,attr", &str, &n, &lattr)) - return NULL; - attr = lattr; - use_attr = TRUE; - break; - case 4: - if (!PyArg_ParseTuple(args,"iisi;y,x,str,n", &y, &x, &str, &n)) - return NULL; - use_xy = TRUE; - break; - case 5: - if (!PyArg_ParseTuple(args,"iisil;y,x,str,n,attr", &y, &x, &str, &n, &lattr)) - return NULL; - attr = lattr; - use_xy = use_attr = TRUE; - break; - default: - PyErr_SetString(PyExc_TypeError, "insnstr requires 2 to 5 arguments"); - return NULL; - } - - if (use_attr == TRUE) { - attr_old = getattrs(self->win); - (void)wattrset(self->win,attr); - } - if (use_xy == TRUE) - rtn = mvwinsnstr(self->win,y,x,str,n); - else - rtn = winsnstr(self->win,str,n); - if (use_attr == TRUE) - (void)wattrset(self->win,attr_old); - return PyCursesCheckERR(rtn, "insnstr"); + int rtn, x, y, n; + char *str; + attr_t attr = A_NORMAL , attr_old = A_NORMAL; + long lattr; + int use_xy = FALSE, use_attr = FALSE; + + switch (PyTuple_Size(args)) { + case 2: + if (!PyArg_ParseTuple(args,"si;str,n", &str, &n)) + return NULL; + break; + case 3: + if (!PyArg_ParseTuple(args,"sil;str,n,attr", &str, &n, &lattr)) + return NULL; + attr = lattr; + use_attr = TRUE; + break; + case 4: + if (!PyArg_ParseTuple(args,"iisi;y,x,str,n", &y, &x, &str, &n)) + return NULL; + use_xy = TRUE; + break; + case 5: + if (!PyArg_ParseTuple(args,"iisil;y,x,str,n,attr", &y, &x, &str, &n, &lattr)) + return NULL; + attr = lattr; + use_xy = use_attr = TRUE; + break; + default: + PyErr_SetString(PyExc_TypeError, "insnstr requires 2 to 5 arguments"); + return NULL; + } + + if (use_attr == TRUE) { + attr_old = getattrs(self->win); + (void)wattrset(self->win,attr); + } + if (use_xy == TRUE) + rtn = mvwinsnstr(self->win,y,x,str,n); + else + rtn = winsnstr(self->win,str,n); + if (use_attr == TRUE) + (void)wattrset(self->win,attr_old); + return PyCursesCheckERR(rtn, "insnstr"); } static PyObject * PyCursesWindow_Is_LineTouched(PyCursesWindowObject *self, PyObject *args) { - int line, erg; - if (!PyArg_ParseTuple(args,"i;line", &line)) - return NULL; - erg = is_linetouched(self->win, line); - if (erg == ERR) { - PyErr_SetString(PyExc_TypeError, - "is_linetouched: line number outside of boundaries"); - return NULL; - } else - if (erg == FALSE) { - Py_INCREF(Py_False); - return Py_False; - } else { - Py_INCREF(Py_True); - return Py_True; - } + int line, erg; + if (!PyArg_ParseTuple(args,"i;line", &line)) + return NULL; + erg = is_linetouched(self->win, line); + if (erg == ERR) { + PyErr_SetString(PyExc_TypeError, + "is_linetouched: line number outside of boundaries"); + return NULL; + } else + if (erg == FALSE) { + Py_INCREF(Py_False); + return Py_False; + } else { + Py_INCREF(Py_True); + return Py_True; + } } static PyObject * PyCursesWindow_NoOutRefresh(PyCursesWindowObject *self, PyObject *args) { - int pminrow,pmincol,sminrow,smincol,smaxrow,smaxcol; - int rtn; + int pminrow,pmincol,sminrow,smincol,smaxrow,smaxcol; + int rtn; #ifndef WINDOW_HAS_FLAGS - if (0) + if (0) #else - if (self->win->_flags & _ISPAD) + if (self->win->_flags & _ISPAD) #endif - { - switch(PyTuple_Size(args)) { - case 6: - if (!PyArg_ParseTuple(args, - "iiiiii;" \ - "pminrow,pmincol,sminrow,smincol,smaxrow,smaxcol", - &pminrow, &pmincol, &sminrow, - &smincol, &smaxrow, &smaxcol)) - return NULL; - Py_BEGIN_ALLOW_THREADS - rtn = pnoutrefresh(self->win, - pminrow, pmincol, sminrow, - smincol, smaxrow, smaxcol); - Py_END_ALLOW_THREADS - return PyCursesCheckERR(rtn, "pnoutrefresh"); - default: - PyErr_SetString(PyCursesError, - "noutrefresh() called for a pad " - "requires 6 arguments"); - return NULL; - } - } else { - if (!PyArg_ParseTuple(args, ":noutrefresh")) - return NULL; - - Py_BEGIN_ALLOW_THREADS - rtn = wnoutrefresh(self->win); - Py_END_ALLOW_THREADS - return PyCursesCheckERR(rtn, "wnoutrefresh"); - } + { + switch(PyTuple_Size(args)) { + case 6: + if (!PyArg_ParseTuple(args, + "iiiiii;" \ + "pminrow,pmincol,sminrow,smincol,smaxrow,smaxcol", + &pminrow, &pmincol, &sminrow, + &smincol, &smaxrow, &smaxcol)) + return NULL; + Py_BEGIN_ALLOW_THREADS + rtn = pnoutrefresh(self->win, + pminrow, pmincol, sminrow, + smincol, smaxrow, smaxcol); + Py_END_ALLOW_THREADS + return PyCursesCheckERR(rtn, "pnoutrefresh"); + default: + PyErr_SetString(PyCursesError, + "noutrefresh() called for a pad " + "requires 6 arguments"); + return NULL; + } + } else { + if (!PyArg_ParseTuple(args, ":noutrefresh")) + return NULL; + + Py_BEGIN_ALLOW_THREADS + rtn = wnoutrefresh(self->win); + Py_END_ALLOW_THREADS + return PyCursesCheckERR(rtn, "wnoutrefresh"); + } } static PyObject * @@ -1276,34 +1276,34 @@ int use_copywin = FALSE; int sminrow, smincol, dminrow, dmincol, dmaxrow, dmaxcol; int rtn; - + switch (PyTuple_Size(args)) { case 1: - if (!PyArg_ParseTuple(args, "O!;window object", - &PyCursesWindow_Type, &temp)) - return NULL; - break; + if (!PyArg_ParseTuple(args, "O!;window object", + &PyCursesWindow_Type, &temp)) + return NULL; + break; case 7: - if (!PyArg_ParseTuple(args, "O!iiiiii;window object, int, int, int, int, int, int", - &PyCursesWindow_Type, &temp, &sminrow, &smincol, - &dminrow, &dmincol, &dmaxrow, &dmaxcol)) - return NULL; - use_copywin = TRUE; - break; - default: - PyErr_SetString(PyExc_TypeError, - "overlay requires one or seven arguments"); - return NULL; + if (!PyArg_ParseTuple(args, "O!iiiiii;window object, int, int, int, int, int, int", + &PyCursesWindow_Type, &temp, &sminrow, &smincol, + &dminrow, &dmincol, &dmaxrow, &dmaxcol)) + return NULL; + use_copywin = TRUE; + break; + default: + PyErr_SetString(PyExc_TypeError, + "overlay requires one or seven arguments"); + return NULL; } if (use_copywin == TRUE) { - rtn = copywin(self->win, temp->win, sminrow, smincol, - dminrow, dmincol, dmaxrow, dmaxcol, TRUE); - return PyCursesCheckERR(rtn, "copywin"); + rtn = copywin(self->win, temp->win, sminrow, smincol, + dminrow, dmincol, dmaxrow, dmaxcol, TRUE); + return PyCursesCheckERR(rtn, "copywin"); } else { - rtn = overlay(self->win, temp->win); - return PyCursesCheckERR(rtn, "overlay"); + rtn = overlay(self->win, temp->win); + return PyCursesCheckERR(rtn, "overlay"); } } @@ -1314,342 +1314,342 @@ int use_copywin = FALSE; int sminrow, smincol, dminrow, dmincol, dmaxrow, dmaxcol; int rtn; - + switch (PyTuple_Size(args)) { case 1: - if (!PyArg_ParseTuple(args, "O!;window object", - &PyCursesWindow_Type, &temp)) - return NULL; - break; + if (!PyArg_ParseTuple(args, "O!;window object", + &PyCursesWindow_Type, &temp)) + return NULL; + break; case 7: - if (!PyArg_ParseTuple(args, "O!iiiiii;window object, int, int, int, int, int, int", - &PyCursesWindow_Type, &temp, &sminrow, &smincol, - &dminrow, &dmincol, &dmaxrow, &dmaxcol)) - return NULL; - use_copywin = TRUE; - break; - default: - PyErr_SetString(PyExc_TypeError, - "overwrite requires one or seven arguments"); - return NULL; + if (!PyArg_ParseTuple(args, "O!iiiiii;window object, int, int, int, int, int, int", + &PyCursesWindow_Type, &temp, &sminrow, &smincol, + &dminrow, &dmincol, &dmaxrow, &dmaxcol)) + return NULL; + use_copywin = TRUE; + break; + default: + PyErr_SetString(PyExc_TypeError, + "overwrite requires one or seven arguments"); + return NULL; } if (use_copywin == TRUE) { - rtn = copywin(self->win, temp->win, sminrow, smincol, - dminrow, dmincol, dmaxrow, dmaxcol, FALSE); + rtn = copywin(self->win, temp->win, sminrow, smincol, + dminrow, dmincol, dmaxrow, dmaxcol, FALSE); return PyCursesCheckERR(rtn, "copywin"); } else { - rtn = overwrite(self->win, temp->win); - return PyCursesCheckERR(rtn, "overwrite"); + rtn = overwrite(self->win, temp->win); + return PyCursesCheckERR(rtn, "overwrite"); } } static PyObject * PyCursesWindow_PutWin(PyCursesWindowObject *self, PyObject *args) { - PyObject *temp; - - if (!PyArg_ParseTuple(args, "O;fileobj", &temp)) - return NULL; - if (!PyFile_Check(temp)) { - PyErr_SetString(PyExc_TypeError, "argument must be a file object"); - return NULL; - } - return PyCursesCheckERR(putwin(self->win, PyFile_AsFile(temp)), - "putwin"); + PyObject *temp; + + if (!PyArg_ParseTuple(args, "O;fileobj", &temp)) + return NULL; + if (!PyFile_Check(temp)) { + PyErr_SetString(PyExc_TypeError, "argument must be a file object"); + return NULL; + } + return PyCursesCheckERR(putwin(self->win, PyFile_AsFile(temp)), + "putwin"); } static PyObject * PyCursesWindow_RedrawLine(PyCursesWindowObject *self, PyObject *args) { - int beg, num; - if (!PyArg_ParseTuple(args, "ii;beg,num", &beg, &num)) - return NULL; - return PyCursesCheckERR(wredrawln(self->win,beg,num), "redrawln"); + int beg, num; + if (!PyArg_ParseTuple(args, "ii;beg,num", &beg, &num)) + return NULL; + return PyCursesCheckERR(wredrawln(self->win,beg,num), "redrawln"); } static PyObject * PyCursesWindow_Refresh(PyCursesWindowObject *self, PyObject *args) { - int pminrow,pmincol,sminrow,smincol,smaxrow,smaxcol; - int rtn; - + int pminrow,pmincol,sminrow,smincol,smaxrow,smaxcol; + int rtn; + #ifndef WINDOW_HAS_FLAGS - if (0) + if (0) #else - if (self->win->_flags & _ISPAD) + if (self->win->_flags & _ISPAD) #endif - { - switch(PyTuple_Size(args)) { - case 6: - if (!PyArg_ParseTuple(args, - "iiiiii;" \ - "pminrow,pmincol,sminrow,smincol,smaxrow,smaxcol", - &pminrow, &pmincol, &sminrow, - &smincol, &smaxrow, &smaxcol)) - return NULL; - - Py_BEGIN_ALLOW_THREADS - rtn = prefresh(self->win, - pminrow, pmincol, sminrow, - smincol, smaxrow, smaxcol); - Py_END_ALLOW_THREADS - return PyCursesCheckERR(rtn, "prefresh"); - default: - PyErr_SetString(PyCursesError, - "refresh() for a pad requires 6 arguments"); - return NULL; - } - } else { - if (!PyArg_ParseTuple(args, ":refresh")) - return NULL; - Py_BEGIN_ALLOW_THREADS - rtn = wrefresh(self->win); - Py_END_ALLOW_THREADS - return PyCursesCheckERR(rtn, "prefresh"); - } + { + switch(PyTuple_Size(args)) { + case 6: + if (!PyArg_ParseTuple(args, + "iiiiii;" \ + "pminrow,pmincol,sminrow,smincol,smaxrow,smaxcol", + &pminrow, &pmincol, &sminrow, + &smincol, &smaxrow, &smaxcol)) + return NULL; + + Py_BEGIN_ALLOW_THREADS + rtn = prefresh(self->win, + pminrow, pmincol, sminrow, + smincol, smaxrow, smaxcol); + Py_END_ALLOW_THREADS + return PyCursesCheckERR(rtn, "prefresh"); + default: + PyErr_SetString(PyCursesError, + "refresh() for a pad requires 6 arguments"); + return NULL; + } + } else { + if (!PyArg_ParseTuple(args, ":refresh")) + return NULL; + Py_BEGIN_ALLOW_THREADS + rtn = wrefresh(self->win); + Py_END_ALLOW_THREADS + return PyCursesCheckERR(rtn, "prefresh"); + } } static PyObject * PyCursesWindow_SetScrollRegion(PyCursesWindowObject *self, PyObject *args) { - int x, y; - if (!PyArg_ParseTuple(args,"ii;top, bottom",&y,&x)) - return NULL; - return PyCursesCheckERR(wsetscrreg(self->win,y,x), "wsetscrreg"); + int x, y; + if (!PyArg_ParseTuple(args,"ii;top, bottom",&y,&x)) + return NULL; + return PyCursesCheckERR(wsetscrreg(self->win,y,x), "wsetscrreg"); } static PyObject * PyCursesWindow_SubWin(PyCursesWindowObject *self, PyObject *args) { - WINDOW *win; - int nlines, ncols, begin_y, begin_x; + WINDOW *win; + int nlines, ncols, begin_y, begin_x; - nlines = 0; - ncols = 0; - switch (PyTuple_Size(args)) { - case 2: - if (!PyArg_ParseTuple(args,"ii;begin_y,begin_x",&begin_y,&begin_x)) - return NULL; - break; - case 4: - if (!PyArg_ParseTuple(args, "iiii;nlines,ncols,begin_y,begin_x", - &nlines,&ncols,&begin_y,&begin_x)) - return NULL; - break; - default: - PyErr_SetString(PyExc_TypeError, "subwin requires 2 or 4 arguments"); - return NULL; - } + nlines = 0; + ncols = 0; + switch (PyTuple_Size(args)) { + case 2: + if (!PyArg_ParseTuple(args,"ii;begin_y,begin_x",&begin_y,&begin_x)) + return NULL; + break; + case 4: + if (!PyArg_ParseTuple(args, "iiii;nlines,ncols,begin_y,begin_x", + &nlines,&ncols,&begin_y,&begin_x)) + return NULL; + break; + default: + PyErr_SetString(PyExc_TypeError, "subwin requires 2 or 4 arguments"); + return NULL; + } - /* printf("Subwin: %i %i %i %i \n", nlines, ncols, begin_y, begin_x); */ + /* printf("Subwin: %i %i %i %i \n", nlines, ncols, begin_y, begin_x); */ #ifdef WINDOW_HAS_FLAGS - if (self->win->_flags & _ISPAD) - win = subpad(self->win, nlines, ncols, begin_y, begin_x); - else -#endif - win = subwin(self->win, nlines, ncols, begin_y, begin_x); - - if (win == NULL) { - PyErr_SetString(PyCursesError, catchall_NULL); - return NULL; - } - - return (PyObject *)PyCursesWindow_New(win); + if (self->win->_flags & _ISPAD) + win = subpad(self->win, nlines, ncols, begin_y, begin_x); + else +#endif + win = subwin(self->win, nlines, ncols, begin_y, begin_x); + + if (win == NULL) { + PyErr_SetString(PyCursesError, catchall_NULL); + return NULL; + } + + return (PyObject *)PyCursesWindow_New(win); } static PyObject * PyCursesWindow_Scroll(PyCursesWindowObject *self, PyObject *args) { - int nlines; - switch(PyTuple_Size(args)) { - case 0: - return PyCursesCheckERR(scroll(self->win), "scroll"); - case 1: - if (!PyArg_ParseTuple(args, "i;nlines", &nlines)) - return NULL; - return PyCursesCheckERR(wscrl(self->win, nlines), "scroll"); - default: - PyErr_SetString(PyExc_TypeError, "scroll requires 0 or 1 arguments"); - return NULL; - } + int nlines; + switch(PyTuple_Size(args)) { + case 0: + return PyCursesCheckERR(scroll(self->win), "scroll"); + case 1: + if (!PyArg_ParseTuple(args, "i;nlines", &nlines)) + return NULL; + return PyCursesCheckERR(wscrl(self->win, nlines), "scroll"); + default: + PyErr_SetString(PyExc_TypeError, "scroll requires 0 or 1 arguments"); + return NULL; + } } static PyObject * PyCursesWindow_TouchLine(PyCursesWindowObject *self, PyObject *args) { - int st, cnt, val; - switch (PyTuple_Size(args)) { - case 2: - if (!PyArg_ParseTuple(args,"ii;start,count",&st,&cnt)) - return NULL; - return PyCursesCheckERR(touchline(self->win,st,cnt), "touchline"); - case 3: - if (!PyArg_ParseTuple(args, "iii;start,count,val", &st, &cnt, &val)) - return NULL; - return PyCursesCheckERR(wtouchln(self->win, st, cnt, val), "touchline"); - default: - PyErr_SetString(PyExc_TypeError, "touchline requires 2 or 3 arguments"); - return NULL; - } + int st, cnt, val; + switch (PyTuple_Size(args)) { + case 2: + if (!PyArg_ParseTuple(args,"ii;start,count",&st,&cnt)) + return NULL; + return PyCursesCheckERR(touchline(self->win,st,cnt), "touchline"); + case 3: + if (!PyArg_ParseTuple(args, "iii;start,count,val", &st, &cnt, &val)) + return NULL; + return PyCursesCheckERR(wtouchln(self->win, st, cnt, val), "touchline"); + default: + PyErr_SetString(PyExc_TypeError, "touchline requires 2 or 3 arguments"); + return NULL; + } } static PyObject * PyCursesWindow_Vline(PyCursesWindowObject *self, PyObject *args) { - PyObject *temp; - chtype ch; - int n, x, y, code = OK; - attr_t attr = A_NORMAL; - long lattr; - - switch (PyTuple_Size(args)) { - case 2: - if (!PyArg_ParseTuple(args, "Oi;ch or int,n", &temp, &n)) - return NULL; - break; - case 3: - if (!PyArg_ParseTuple(args, "Oil;ch or int,n,attr", &temp, &n, &lattr)) - return NULL; - attr = lattr; - break; - case 4: - if (!PyArg_ParseTuple(args, "iiOi;y,x,ch or int,n", &y, &x, &temp, &n)) - return NULL; - code = wmove(self->win, y, x); - break; - case 5: - if (!PyArg_ParseTuple(args, "iiOil; y,x,ch or int,n,attr", - &y, &x, &temp, &n, &lattr)) - return NULL; - attr = lattr; - code = wmove(self->win, y, x); - break; - default: - PyErr_SetString(PyExc_TypeError, "vline requires 2 to 5 arguments"); - return NULL; - } + PyObject *temp; + chtype ch; + int n, x, y, code = OK; + attr_t attr = A_NORMAL; + long lattr; - if (code != ERR) { - if (!PyCurses_ConvertToChtype(temp, &ch)) { - PyErr_SetString(PyExc_TypeError, - "argument 1 or 3 must be a ch or an int"); - return NULL; - } - return PyCursesCheckERR(wvline(self->win, ch | attr, n), "vline"); - } else - return PyCursesCheckERR(code, "wmove"); + switch (PyTuple_Size(args)) { + case 2: + if (!PyArg_ParseTuple(args, "Oi;ch or int,n", &temp, &n)) + return NULL; + break; + case 3: + if (!PyArg_ParseTuple(args, "Oil;ch or int,n,attr", &temp, &n, &lattr)) + return NULL; + attr = lattr; + break; + case 4: + if (!PyArg_ParseTuple(args, "iiOi;y,x,ch or int,n", &y, &x, &temp, &n)) + return NULL; + code = wmove(self->win, y, x); + break; + case 5: + if (!PyArg_ParseTuple(args, "iiOil; y,x,ch or int,n,attr", + &y, &x, &temp, &n, &lattr)) + return NULL; + attr = lattr; + code = wmove(self->win, y, x); + break; + default: + PyErr_SetString(PyExc_TypeError, "vline requires 2 to 5 arguments"); + return NULL; + } + + if (code != ERR) { + if (!PyCurses_ConvertToChtype(temp, &ch)) { + PyErr_SetString(PyExc_TypeError, + "argument 1 or 3 must be a ch or an int"); + return NULL; + } + return PyCursesCheckERR(wvline(self->win, ch | attr, n), "vline"); + } else + return PyCursesCheckERR(code, "wmove"); } static PyMethodDef PyCursesWindow_Methods[] = { - {"addch", (PyCFunction)PyCursesWindow_AddCh, METH_VARARGS}, - {"addnstr", (PyCFunction)PyCursesWindow_AddNStr, METH_VARARGS}, - {"addstr", (PyCFunction)PyCursesWindow_AddStr, METH_VARARGS}, - {"attroff", (PyCFunction)PyCursesWindow_AttrOff, METH_VARARGS}, - {"attron", (PyCFunction)PyCursesWindow_AttrOn, METH_VARARGS}, - {"attrset", (PyCFunction)PyCursesWindow_AttrSet, METH_VARARGS}, - {"bkgd", (PyCFunction)PyCursesWindow_Bkgd, METH_VARARGS}, - {"chgat", (PyCFunction)PyCursesWindow_ChgAt, METH_VARARGS}, - {"bkgdset", (PyCFunction)PyCursesWindow_BkgdSet, METH_VARARGS}, - {"border", (PyCFunction)PyCursesWindow_Border, METH_VARARGS}, - {"box", (PyCFunction)PyCursesWindow_Box, METH_VARARGS}, - {"clear", (PyCFunction)PyCursesWindow_wclear, METH_NOARGS}, - {"clearok", (PyCFunction)PyCursesWindow_clearok, METH_VARARGS}, - {"clrtobot", (PyCFunction)PyCursesWindow_wclrtobot, METH_NOARGS}, - {"clrtoeol", (PyCFunction)PyCursesWindow_wclrtoeol, METH_NOARGS}, - {"cursyncup", (PyCFunction)PyCursesWindow_wcursyncup, METH_NOARGS}, - {"delch", (PyCFunction)PyCursesWindow_DelCh, METH_VARARGS}, - {"deleteln", (PyCFunction)PyCursesWindow_wdeleteln, METH_NOARGS}, - {"derwin", (PyCFunction)PyCursesWindow_DerWin, METH_VARARGS}, - {"echochar", (PyCFunction)PyCursesWindow_EchoChar, METH_VARARGS}, + {"addch", (PyCFunction)PyCursesWindow_AddCh, METH_VARARGS}, + {"addnstr", (PyCFunction)PyCursesWindow_AddNStr, METH_VARARGS}, + {"addstr", (PyCFunction)PyCursesWindow_AddStr, METH_VARARGS}, + {"attroff", (PyCFunction)PyCursesWindow_AttrOff, METH_VARARGS}, + {"attron", (PyCFunction)PyCursesWindow_AttrOn, METH_VARARGS}, + {"attrset", (PyCFunction)PyCursesWindow_AttrSet, METH_VARARGS}, + {"bkgd", (PyCFunction)PyCursesWindow_Bkgd, METH_VARARGS}, + {"chgat", (PyCFunction)PyCursesWindow_ChgAt, METH_VARARGS}, + {"bkgdset", (PyCFunction)PyCursesWindow_BkgdSet, METH_VARARGS}, + {"border", (PyCFunction)PyCursesWindow_Border, METH_VARARGS}, + {"box", (PyCFunction)PyCursesWindow_Box, METH_VARARGS}, + {"clear", (PyCFunction)PyCursesWindow_wclear, METH_NOARGS}, + {"clearok", (PyCFunction)PyCursesWindow_clearok, METH_VARARGS}, + {"clrtobot", (PyCFunction)PyCursesWindow_wclrtobot, METH_NOARGS}, + {"clrtoeol", (PyCFunction)PyCursesWindow_wclrtoeol, METH_NOARGS}, + {"cursyncup", (PyCFunction)PyCursesWindow_wcursyncup, METH_NOARGS}, + {"delch", (PyCFunction)PyCursesWindow_DelCh, METH_VARARGS}, + {"deleteln", (PyCFunction)PyCursesWindow_wdeleteln, METH_NOARGS}, + {"derwin", (PyCFunction)PyCursesWindow_DerWin, METH_VARARGS}, + {"echochar", (PyCFunction)PyCursesWindow_EchoChar, METH_VARARGS}, #ifdef NCURSES_MOUSE_VERSION - {"enclose", (PyCFunction)PyCursesWindow_Enclose, METH_VARARGS}, + {"enclose", (PyCFunction)PyCursesWindow_Enclose, METH_VARARGS}, #endif - {"erase", (PyCFunction)PyCursesWindow_werase, METH_NOARGS}, - {"getbegyx", (PyCFunction)PyCursesWindow_getbegyx, METH_NOARGS}, - {"getbkgd", (PyCFunction)PyCursesWindow_GetBkgd, METH_NOARGS}, - {"getch", (PyCFunction)PyCursesWindow_GetCh, METH_VARARGS}, - {"getkey", (PyCFunction)PyCursesWindow_GetKey, METH_VARARGS}, - {"getmaxyx", (PyCFunction)PyCursesWindow_getmaxyx, METH_NOARGS}, - {"getparyx", (PyCFunction)PyCursesWindow_getparyx, METH_NOARGS}, - {"getstr", (PyCFunction)PyCursesWindow_GetStr, METH_VARARGS}, - {"getyx", (PyCFunction)PyCursesWindow_getyx, METH_NOARGS}, - {"hline", (PyCFunction)PyCursesWindow_Hline, METH_VARARGS}, - {"idcok", (PyCFunction)PyCursesWindow_idcok, METH_VARARGS}, - {"idlok", (PyCFunction)PyCursesWindow_idlok, METH_VARARGS}, - {"immedok", (PyCFunction)PyCursesWindow_immedok, METH_VARARGS}, - {"inch", (PyCFunction)PyCursesWindow_InCh, METH_VARARGS}, - {"insch", (PyCFunction)PyCursesWindow_InsCh, METH_VARARGS}, - {"insdelln", (PyCFunction)PyCursesWindow_winsdelln, METH_VARARGS}, - {"insertln", (PyCFunction)PyCursesWindow_winsertln, METH_NOARGS}, - {"insnstr", (PyCFunction)PyCursesWindow_InsNStr, METH_VARARGS}, - {"insstr", (PyCFunction)PyCursesWindow_InsStr, METH_VARARGS}, - {"instr", (PyCFunction)PyCursesWindow_InStr, METH_VARARGS}, - {"is_linetouched", (PyCFunction)PyCursesWindow_Is_LineTouched, METH_VARARGS}, - {"is_wintouched", (PyCFunction)PyCursesWindow_is_wintouched, METH_NOARGS}, - {"keypad", (PyCFunction)PyCursesWindow_keypad, METH_VARARGS}, - {"leaveok", (PyCFunction)PyCursesWindow_leaveok, METH_VARARGS}, - {"move", (PyCFunction)PyCursesWindow_wmove, METH_VARARGS}, - {"mvderwin", (PyCFunction)PyCursesWindow_mvderwin, METH_VARARGS}, - {"mvwin", (PyCFunction)PyCursesWindow_mvwin, METH_VARARGS}, - {"nodelay", (PyCFunction)PyCursesWindow_nodelay, METH_VARARGS}, - {"notimeout", (PyCFunction)PyCursesWindow_notimeout, METH_VARARGS}, - {"noutrefresh", (PyCFunction)PyCursesWindow_NoOutRefresh, METH_VARARGS}, - /* Backward compatibility alias -- remove in Python 2.3 */ - {"nooutrefresh", (PyCFunction)PyCursesWindow_NoOutRefresh, METH_VARARGS}, - {"overlay", (PyCFunction)PyCursesWindow_Overlay, METH_VARARGS}, - {"overwrite", (PyCFunction)PyCursesWindow_Overwrite, - METH_VARARGS}, - {"putwin", (PyCFunction)PyCursesWindow_PutWin, METH_VARARGS}, - {"redrawln", (PyCFunction)PyCursesWindow_RedrawLine, METH_VARARGS}, - {"redrawwin", (PyCFunction)PyCursesWindow_redrawwin, METH_NOARGS}, - {"refresh", (PyCFunction)PyCursesWindow_Refresh, METH_VARARGS}, + {"erase", (PyCFunction)PyCursesWindow_werase, METH_NOARGS}, + {"getbegyx", (PyCFunction)PyCursesWindow_getbegyx, METH_NOARGS}, + {"getbkgd", (PyCFunction)PyCursesWindow_GetBkgd, METH_NOARGS}, + {"getch", (PyCFunction)PyCursesWindow_GetCh, METH_VARARGS}, + {"getkey", (PyCFunction)PyCursesWindow_GetKey, METH_VARARGS}, + {"getmaxyx", (PyCFunction)PyCursesWindow_getmaxyx, METH_NOARGS}, + {"getparyx", (PyCFunction)PyCursesWindow_getparyx, METH_NOARGS}, + {"getstr", (PyCFunction)PyCursesWindow_GetStr, METH_VARARGS}, + {"getyx", (PyCFunction)PyCursesWindow_getyx, METH_NOARGS}, + {"hline", (PyCFunction)PyCursesWindow_Hline, METH_VARARGS}, + {"idcok", (PyCFunction)PyCursesWindow_idcok, METH_VARARGS}, + {"idlok", (PyCFunction)PyCursesWindow_idlok, METH_VARARGS}, + {"immedok", (PyCFunction)PyCursesWindow_immedok, METH_VARARGS}, + {"inch", (PyCFunction)PyCursesWindow_InCh, METH_VARARGS}, + {"insch", (PyCFunction)PyCursesWindow_InsCh, METH_VARARGS}, + {"insdelln", (PyCFunction)PyCursesWindow_winsdelln, METH_VARARGS}, + {"insertln", (PyCFunction)PyCursesWindow_winsertln, METH_NOARGS}, + {"insnstr", (PyCFunction)PyCursesWindow_InsNStr, METH_VARARGS}, + {"insstr", (PyCFunction)PyCursesWindow_InsStr, METH_VARARGS}, + {"instr", (PyCFunction)PyCursesWindow_InStr, METH_VARARGS}, + {"is_linetouched", (PyCFunction)PyCursesWindow_Is_LineTouched, METH_VARARGS}, + {"is_wintouched", (PyCFunction)PyCursesWindow_is_wintouched, METH_NOARGS}, + {"keypad", (PyCFunction)PyCursesWindow_keypad, METH_VARARGS}, + {"leaveok", (PyCFunction)PyCursesWindow_leaveok, METH_VARARGS}, + {"move", (PyCFunction)PyCursesWindow_wmove, METH_VARARGS}, + {"mvderwin", (PyCFunction)PyCursesWindow_mvderwin, METH_VARARGS}, + {"mvwin", (PyCFunction)PyCursesWindow_mvwin, METH_VARARGS}, + {"nodelay", (PyCFunction)PyCursesWindow_nodelay, METH_VARARGS}, + {"notimeout", (PyCFunction)PyCursesWindow_notimeout, METH_VARARGS}, + {"noutrefresh", (PyCFunction)PyCursesWindow_NoOutRefresh, METH_VARARGS}, + /* Backward compatibility alias -- remove in Python 2.3 */ + {"nooutrefresh", (PyCFunction)PyCursesWindow_NoOutRefresh, METH_VARARGS}, + {"overlay", (PyCFunction)PyCursesWindow_Overlay, METH_VARARGS}, + {"overwrite", (PyCFunction)PyCursesWindow_Overwrite, + METH_VARARGS}, + {"putwin", (PyCFunction)PyCursesWindow_PutWin, METH_VARARGS}, + {"redrawln", (PyCFunction)PyCursesWindow_RedrawLine, METH_VARARGS}, + {"redrawwin", (PyCFunction)PyCursesWindow_redrawwin, METH_NOARGS}, + {"refresh", (PyCFunction)PyCursesWindow_Refresh, METH_VARARGS}, #ifndef STRICT_SYSV_CURSES - {"resize", (PyCFunction)PyCursesWindow_wresize, METH_VARARGS}, + {"resize", (PyCFunction)PyCursesWindow_wresize, METH_VARARGS}, #endif - {"scroll", (PyCFunction)PyCursesWindow_Scroll, METH_VARARGS}, - {"scrollok", (PyCFunction)PyCursesWindow_scrollok, METH_VARARGS}, - {"setscrreg", (PyCFunction)PyCursesWindow_SetScrollRegion, METH_VARARGS}, - {"standend", (PyCFunction)PyCursesWindow_wstandend, METH_NOARGS}, - {"standout", (PyCFunction)PyCursesWindow_wstandout, METH_NOARGS}, - {"subpad", (PyCFunction)PyCursesWindow_SubWin, METH_VARARGS}, - {"subwin", (PyCFunction)PyCursesWindow_SubWin, METH_VARARGS}, - {"syncdown", (PyCFunction)PyCursesWindow_wsyncdown, METH_NOARGS}, - {"syncok", (PyCFunction)PyCursesWindow_syncok, METH_VARARGS}, - {"syncup", (PyCFunction)PyCursesWindow_wsyncup, METH_NOARGS}, - {"timeout", (PyCFunction)PyCursesWindow_wtimeout, METH_VARARGS}, - {"touchline", (PyCFunction)PyCursesWindow_TouchLine, METH_VARARGS}, - {"touchwin", (PyCFunction)PyCursesWindow_touchwin, METH_NOARGS}, - {"untouchwin", (PyCFunction)PyCursesWindow_untouchwin, METH_NOARGS}, - {"vline", (PyCFunction)PyCursesWindow_Vline, METH_VARARGS}, - {NULL, NULL} /* sentinel */ + {"scroll", (PyCFunction)PyCursesWindow_Scroll, METH_VARARGS}, + {"scrollok", (PyCFunction)PyCursesWindow_scrollok, METH_VARARGS}, + {"setscrreg", (PyCFunction)PyCursesWindow_SetScrollRegion, METH_VARARGS}, + {"standend", (PyCFunction)PyCursesWindow_wstandend, METH_NOARGS}, + {"standout", (PyCFunction)PyCursesWindow_wstandout, METH_NOARGS}, + {"subpad", (PyCFunction)PyCursesWindow_SubWin, METH_VARARGS}, + {"subwin", (PyCFunction)PyCursesWindow_SubWin, METH_VARARGS}, + {"syncdown", (PyCFunction)PyCursesWindow_wsyncdown, METH_NOARGS}, + {"syncok", (PyCFunction)PyCursesWindow_syncok, METH_VARARGS}, + {"syncup", (PyCFunction)PyCursesWindow_wsyncup, METH_NOARGS}, + {"timeout", (PyCFunction)PyCursesWindow_wtimeout, METH_VARARGS}, + {"touchline", (PyCFunction)PyCursesWindow_TouchLine, METH_VARARGS}, + {"touchwin", (PyCFunction)PyCursesWindow_touchwin, METH_NOARGS}, + {"untouchwin", (PyCFunction)PyCursesWindow_untouchwin, METH_NOARGS}, + {"vline", (PyCFunction)PyCursesWindow_Vline, METH_VARARGS}, + {NULL, NULL} /* sentinel */ }; static PyObject * PyCursesWindow_GetAttr(PyCursesWindowObject *self, char *name) { - return Py_FindMethod(PyCursesWindow_Methods, (PyObject *)self, name); + return Py_FindMethod(PyCursesWindow_Methods, (PyObject *)self, name); } /* -------------------------------------------------------*/ PyTypeObject PyCursesWindow_Type = { - PyVarObject_HEAD_INIT(NULL, 0) - "_curses.curses window", /*tp_name*/ - sizeof(PyCursesWindowObject), /*tp_basicsize*/ - 0, /*tp_itemsize*/ - /* methods */ - (destructor)PyCursesWindow_Dealloc, /*tp_dealloc*/ - 0, /*tp_print*/ - (getattrfunc)PyCursesWindow_GetAttr, /*tp_getattr*/ - (setattrfunc)0, /*tp_setattr*/ - 0, /*tp_compare*/ - 0, /*tp_repr*/ - 0, /*tp_as_number*/ - 0, /*tp_as_sequence*/ - 0, /*tp_as_mapping*/ - 0, /*tp_hash*/ + PyVarObject_HEAD_INIT(NULL, 0) + "_curses.curses window", /*tp_name*/ + sizeof(PyCursesWindowObject), /*tp_basicsize*/ + 0, /*tp_itemsize*/ + /* methods */ + (destructor)PyCursesWindow_Dealloc, /*tp_dealloc*/ + 0, /*tp_print*/ + (getattrfunc)PyCursesWindow_GetAttr, /*tp_getattr*/ + (setattrfunc)0, /*tp_setattr*/ + 0, /*tp_compare*/ + 0, /*tp_repr*/ + 0, /*tp_as_number*/ + 0, /*tp_as_sequence*/ + 0, /*tp_as_mapping*/ + 0, /*tp_hash*/ }; /********************************************************************* @@ -1693,418 +1693,418 @@ static PyObject * PyCurses_filter(PyObject *self) { - /* not checking for PyCursesInitialised here since filter() must - be called before initscr() */ - filter(); - Py_INCREF(Py_None); - return Py_None; + /* not checking for PyCursesInitialised here since filter() must + be called before initscr() */ + filter(); + Py_INCREF(Py_None); + return Py_None; } static PyObject * PyCurses_Color_Content(PyObject *self, PyObject *args) { - short color,r,g,b; + short color,r,g,b; - PyCursesInitialised; - PyCursesInitialisedColor; + PyCursesInitialised; + PyCursesInitialisedColor; - if (!PyArg_ParseTuple(args, "h:color_content", &color)) return NULL; + if (!PyArg_ParseTuple(args, "h:color_content", &color)) return NULL; - if (color_content(color, &r, &g, &b) != ERR) - return Py_BuildValue("(iii)", r, g, b); - else { - PyErr_SetString(PyCursesError, - "Argument 1 was out of range. Check value of COLORS."); - return NULL; - } + if (color_content(color, &r, &g, &b) != ERR) + return Py_BuildValue("(iii)", r, g, b); + else { + PyErr_SetString(PyCursesError, + "Argument 1 was out of range. Check value of COLORS."); + return NULL; + } } static PyObject * PyCurses_color_pair(PyObject *self, PyObject *args) { - int n; + int n; - PyCursesInitialised; - PyCursesInitialisedColor; + PyCursesInitialised; + PyCursesInitialisedColor; - if (!PyArg_ParseTuple(args, "i:color_pair", &n)) return NULL; - return PyInt_FromLong((long) (n << 8)); + if (!PyArg_ParseTuple(args, "i:color_pair", &n)) return NULL; + return PyInt_FromLong((long) (n << 8)); } static PyObject * PyCurses_Curs_Set(PyObject *self, PyObject *args) { - int vis,erg; + int vis,erg; - PyCursesInitialised; + PyCursesInitialised; - if (!PyArg_ParseTuple(args, "i:curs_set", &vis)) return NULL; + if (!PyArg_ParseTuple(args, "i:curs_set", &vis)) return NULL; - erg = curs_set(vis); - if (erg == ERR) return PyCursesCheckERR(erg, "curs_set"); + erg = curs_set(vis); + if (erg == ERR) return PyCursesCheckERR(erg, "curs_set"); - return PyInt_FromLong((long) erg); + return PyInt_FromLong((long) erg); } static PyObject * PyCurses_Delay_Output(PyObject *self, PyObject *args) { - int ms; + int ms; - PyCursesInitialised; + PyCursesInitialised; - if (!PyArg_ParseTuple(args, "i:delay_output", &ms)) return NULL; + if (!PyArg_ParseTuple(args, "i:delay_output", &ms)) return NULL; - return PyCursesCheckERR(delay_output(ms), "delay_output"); + return PyCursesCheckERR(delay_output(ms), "delay_output"); } static PyObject * PyCurses_EraseChar(PyObject *self) { - char ch; + char ch; - PyCursesInitialised; + PyCursesInitialised; - ch = erasechar(); + ch = erasechar(); - return PyString_FromStringAndSize(&ch, 1); + return PyString_FromStringAndSize(&ch, 1); } static PyObject * PyCurses_getsyx(PyObject *self) { - int x = 0; - int y = 0; + int x = 0; + int y = 0; - PyCursesInitialised; + PyCursesInitialised; - getsyx(y, x); + getsyx(y, x); - return Py_BuildValue("(ii)", y, x); + return Py_BuildValue("(ii)", y, x); } #ifdef NCURSES_MOUSE_VERSION static PyObject * PyCurses_GetMouse(PyObject *self) { - int rtn; - MEVENT event; + int rtn; + MEVENT event; - PyCursesInitialised; + PyCursesInitialised; - rtn = getmouse( &event ); - if (rtn == ERR) { - PyErr_SetString(PyCursesError, "getmouse() returned ERR"); - return NULL; - } - return Py_BuildValue("(hiiil)", - (short)event.id, - event.x, event.y, event.z, - (long) event.bstate); + rtn = getmouse( &event ); + if (rtn == ERR) { + PyErr_SetString(PyCursesError, "getmouse() returned ERR"); + return NULL; + } + return Py_BuildValue("(hiiil)", + (short)event.id, + event.x, event.y, event.z, + (long) event.bstate); } static PyObject * PyCurses_UngetMouse(PyObject *self, PyObject *args) { - MEVENT event; + MEVENT event; - PyCursesInitialised; - if (!PyArg_ParseTuple(args, "hiiil", - &event.id, - &event.x, &event.y, &event.z, - (int *) &event.bstate)) - return NULL; + PyCursesInitialised; + if (!PyArg_ParseTuple(args, "hiiil", + &event.id, + &event.x, &event.y, &event.z, + (int *) &event.bstate)) + return NULL; - return PyCursesCheckERR(ungetmouse(&event), "ungetmouse"); + return PyCursesCheckERR(ungetmouse(&event), "ungetmouse"); } #endif static PyObject * PyCurses_GetWin(PyCursesWindowObject *self, PyObject *temp) { - WINDOW *win; + WINDOW *win; - PyCursesInitialised; + PyCursesInitialised; - if (!PyFile_Check(temp)) { - PyErr_SetString(PyExc_TypeError, "argument must be a file object"); - return NULL; - } + if (!PyFile_Check(temp)) { + PyErr_SetString(PyExc_TypeError, "argument must be a file object"); + return NULL; + } - win = getwin(PyFile_AsFile(temp)); + win = getwin(PyFile_AsFile(temp)); - if (win == NULL) { - PyErr_SetString(PyCursesError, catchall_NULL); - return NULL; - } + if (win == NULL) { + PyErr_SetString(PyCursesError, catchall_NULL); + return NULL; + } - return PyCursesWindow_New(win); + return PyCursesWindow_New(win); } static PyObject * PyCurses_HalfDelay(PyObject *self, PyObject *args) { - unsigned char tenths; + unsigned char tenths; - PyCursesInitialised; + PyCursesInitialised; - if (!PyArg_ParseTuple(args, "b:halfdelay", &tenths)) return NULL; + if (!PyArg_ParseTuple(args, "b:halfdelay", &tenths)) return NULL; - return PyCursesCheckERR(halfdelay(tenths), "halfdelay"); + return PyCursesCheckERR(halfdelay(tenths), "halfdelay"); } #ifndef STRICT_SYSV_CURSES - /* No has_key! */ +/* No has_key! */ static PyObject * PyCurses_has_key(PyObject *self, PyObject *args) { - int ch; + int ch; - PyCursesInitialised; + PyCursesInitialised; - if (!PyArg_ParseTuple(args,"i",&ch)) return NULL; + if (!PyArg_ParseTuple(args,"i",&ch)) return NULL; - if (has_key(ch) == FALSE) { - Py_INCREF(Py_False); - return Py_False; - } - Py_INCREF(Py_True); - return Py_True; + if (has_key(ch) == FALSE) { + Py_INCREF(Py_False); + return Py_False; + } + Py_INCREF(Py_True); + return Py_True; } #endif /* STRICT_SYSV_CURSES */ static PyObject * PyCurses_Init_Color(PyObject *self, PyObject *args) { - short color, r, g, b; + short color, r, g, b; - PyCursesInitialised; - PyCursesInitialisedColor; + PyCursesInitialised; + PyCursesInitialisedColor; - switch(PyTuple_Size(args)) { - case 4: - if (!PyArg_ParseTuple(args, "hhhh;color,r,g,b", &color, &r, &g, &b)) return NULL; - break; - default: - PyErr_SetString(PyExc_TypeError, "init_color requires 4 arguments"); - return NULL; - } + switch(PyTuple_Size(args)) { + case 4: + if (!PyArg_ParseTuple(args, "hhhh;color,r,g,b", &color, &r, &g, &b)) return NULL; + break; + default: + PyErr_SetString(PyExc_TypeError, "init_color requires 4 arguments"); + return NULL; + } - return PyCursesCheckERR(init_color(color, r, g, b), "init_color"); + return PyCursesCheckERR(init_color(color, r, g, b), "init_color"); } static PyObject * PyCurses_Init_Pair(PyObject *self, PyObject *args) { - short pair, f, b; + short pair, f, b; - PyCursesInitialised; - PyCursesInitialisedColor; + PyCursesInitialised; + PyCursesInitialisedColor; - if (PyTuple_Size(args) != 3) { - PyErr_SetString(PyExc_TypeError, "init_pair requires 3 arguments"); - return NULL; - } + if (PyTuple_Size(args) != 3) { + PyErr_SetString(PyExc_TypeError, "init_pair requires 3 arguments"); + return NULL; + } - if (!PyArg_ParseTuple(args, "hhh;pair, f, b", &pair, &f, &b)) return NULL; + if (!PyArg_ParseTuple(args, "hhh;pair, f, b", &pair, &f, &b)) return NULL; - return PyCursesCheckERR(init_pair(pair, f, b), "init_pair"); + return PyCursesCheckERR(init_pair(pair, f, b), "init_pair"); } static PyObject *ModDict; -static PyObject * +static PyObject * PyCurses_InitScr(PyObject *self) { - WINDOW *win; + WINDOW *win; - if (initialised == TRUE) { - wrefresh(stdscr); - return (PyObject *)PyCursesWindow_New(stdscr); - } + if (initialised == TRUE) { + wrefresh(stdscr); + return (PyObject *)PyCursesWindow_New(stdscr); + } - win = initscr(); + win = initscr(); - if (win == NULL) { - PyErr_SetString(PyCursesError, catchall_NULL); - return NULL; - } + if (win == NULL) { + PyErr_SetString(PyCursesError, catchall_NULL); + return NULL; + } - initialised = initialised_setupterm = TRUE; + initialised = initialised_setupterm = TRUE; /* This was moved from initcurses() because it core dumped on SGI, where they're not defined until you've called initscr() */ -#define SetDictInt(string,ch) \ - do { \ - PyObject *o = PyInt_FromLong((long) (ch)); \ - if (o && PyDict_SetItemString(ModDict, string, o) == 0) { \ - Py_DECREF(o); \ - } \ +#define SetDictInt(string,ch) \ + do { \ + PyObject *o = PyInt_FromLong((long) (ch)); \ + if (o && PyDict_SetItemString(ModDict, string, o) == 0) { \ + Py_DECREF(o); \ + } \ } while (0) - /* Here are some graphic symbols you can use */ - SetDictInt("ACS_ULCORNER", (ACS_ULCORNER)); - SetDictInt("ACS_LLCORNER", (ACS_LLCORNER)); - SetDictInt("ACS_URCORNER", (ACS_URCORNER)); - SetDictInt("ACS_LRCORNER", (ACS_LRCORNER)); - SetDictInt("ACS_LTEE", (ACS_LTEE)); - SetDictInt("ACS_RTEE", (ACS_RTEE)); - SetDictInt("ACS_BTEE", (ACS_BTEE)); - SetDictInt("ACS_TTEE", (ACS_TTEE)); - SetDictInt("ACS_HLINE", (ACS_HLINE)); - SetDictInt("ACS_VLINE", (ACS_VLINE)); - SetDictInt("ACS_PLUS", (ACS_PLUS)); + /* Here are some graphic symbols you can use */ + SetDictInt("ACS_ULCORNER", (ACS_ULCORNER)); + SetDictInt("ACS_LLCORNER", (ACS_LLCORNER)); + SetDictInt("ACS_URCORNER", (ACS_URCORNER)); + SetDictInt("ACS_LRCORNER", (ACS_LRCORNER)); + SetDictInt("ACS_LTEE", (ACS_LTEE)); + SetDictInt("ACS_RTEE", (ACS_RTEE)); + SetDictInt("ACS_BTEE", (ACS_BTEE)); + SetDictInt("ACS_TTEE", (ACS_TTEE)); + SetDictInt("ACS_HLINE", (ACS_HLINE)); + SetDictInt("ACS_VLINE", (ACS_VLINE)); + SetDictInt("ACS_PLUS", (ACS_PLUS)); #if !defined(__hpux) || defined(HAVE_NCURSES_H) - /* On HP/UX 11, these are of type cchar_t, which is not an - integral type. If this is a problem on more platforms, a - configure test should be added to determine whether ACS_S1 - is of integral type. */ - SetDictInt("ACS_S1", (ACS_S1)); - SetDictInt("ACS_S9", (ACS_S9)); - SetDictInt("ACS_DIAMOND", (ACS_DIAMOND)); - SetDictInt("ACS_CKBOARD", (ACS_CKBOARD)); - SetDictInt("ACS_DEGREE", (ACS_DEGREE)); - SetDictInt("ACS_PLMINUS", (ACS_PLMINUS)); - SetDictInt("ACS_BULLET", (ACS_BULLET)); - SetDictInt("ACS_LARROW", (ACS_LARROW)); - SetDictInt("ACS_RARROW", (ACS_RARROW)); - SetDictInt("ACS_DARROW", (ACS_DARROW)); - SetDictInt("ACS_UARROW", (ACS_UARROW)); - SetDictInt("ACS_BOARD", (ACS_BOARD)); - SetDictInt("ACS_LANTERN", (ACS_LANTERN)); - SetDictInt("ACS_BLOCK", (ACS_BLOCK)); -#endif - SetDictInt("ACS_BSSB", (ACS_ULCORNER)); - SetDictInt("ACS_SSBB", (ACS_LLCORNER)); - SetDictInt("ACS_BBSS", (ACS_URCORNER)); - SetDictInt("ACS_SBBS", (ACS_LRCORNER)); - SetDictInt("ACS_SBSS", (ACS_RTEE)); - SetDictInt("ACS_SSSB", (ACS_LTEE)); - SetDictInt("ACS_SSBS", (ACS_BTEE)); - SetDictInt("ACS_BSSS", (ACS_TTEE)); - SetDictInt("ACS_BSBS", (ACS_HLINE)); - SetDictInt("ACS_SBSB", (ACS_VLINE)); - SetDictInt("ACS_SSSS", (ACS_PLUS)); + /* On HP/UX 11, these are of type cchar_t, which is not an + integral type. If this is a problem on more platforms, a + configure test should be added to determine whether ACS_S1 + is of integral type. */ + SetDictInt("ACS_S1", (ACS_S1)); + SetDictInt("ACS_S9", (ACS_S9)); + SetDictInt("ACS_DIAMOND", (ACS_DIAMOND)); + SetDictInt("ACS_CKBOARD", (ACS_CKBOARD)); + SetDictInt("ACS_DEGREE", (ACS_DEGREE)); + SetDictInt("ACS_PLMINUS", (ACS_PLMINUS)); + SetDictInt("ACS_BULLET", (ACS_BULLET)); + SetDictInt("ACS_LARROW", (ACS_LARROW)); + SetDictInt("ACS_RARROW", (ACS_RARROW)); + SetDictInt("ACS_DARROW", (ACS_DARROW)); + SetDictInt("ACS_UARROW", (ACS_UARROW)); + SetDictInt("ACS_BOARD", (ACS_BOARD)); + SetDictInt("ACS_LANTERN", (ACS_LANTERN)); + SetDictInt("ACS_BLOCK", (ACS_BLOCK)); +#endif + SetDictInt("ACS_BSSB", (ACS_ULCORNER)); + SetDictInt("ACS_SSBB", (ACS_LLCORNER)); + SetDictInt("ACS_BBSS", (ACS_URCORNER)); + SetDictInt("ACS_SBBS", (ACS_LRCORNER)); + SetDictInt("ACS_SBSS", (ACS_RTEE)); + SetDictInt("ACS_SSSB", (ACS_LTEE)); + SetDictInt("ACS_SSBS", (ACS_BTEE)); + SetDictInt("ACS_BSSS", (ACS_TTEE)); + SetDictInt("ACS_BSBS", (ACS_HLINE)); + SetDictInt("ACS_SBSB", (ACS_VLINE)); + SetDictInt("ACS_SSSS", (ACS_PLUS)); - /* The following are never available with strict SYSV curses */ + /* The following are never available with strict SYSV curses */ #ifdef ACS_S3 - SetDictInt("ACS_S3", (ACS_S3)); + SetDictInt("ACS_S3", (ACS_S3)); #endif #ifdef ACS_S7 - SetDictInt("ACS_S7", (ACS_S7)); + SetDictInt("ACS_S7", (ACS_S7)); #endif #ifdef ACS_LEQUAL - SetDictInt("ACS_LEQUAL", (ACS_LEQUAL)); + SetDictInt("ACS_LEQUAL", (ACS_LEQUAL)); #endif #ifdef ACS_GEQUAL - SetDictInt("ACS_GEQUAL", (ACS_GEQUAL)); + SetDictInt("ACS_GEQUAL", (ACS_GEQUAL)); #endif #ifdef ACS_PI - SetDictInt("ACS_PI", (ACS_PI)); + SetDictInt("ACS_PI", (ACS_PI)); #endif #ifdef ACS_NEQUAL - SetDictInt("ACS_NEQUAL", (ACS_NEQUAL)); + SetDictInt("ACS_NEQUAL", (ACS_NEQUAL)); #endif #ifdef ACS_STERLING - SetDictInt("ACS_STERLING", (ACS_STERLING)); + SetDictInt("ACS_STERLING", (ACS_STERLING)); #endif - SetDictInt("LINES", LINES); - SetDictInt("COLS", COLS); + SetDictInt("LINES", LINES); + SetDictInt("COLS", COLS); - return (PyObject *)PyCursesWindow_New(win); + return (PyObject *)PyCursesWindow_New(win); } static PyObject * PyCurses_setupterm(PyObject* self, PyObject *args, PyObject* keywds) { - int fd = -1; - int err; - char* termstr = NULL; - - static char *kwlist[] = {"term", "fd", NULL}; - - if (!PyArg_ParseTupleAndKeywords( - args, keywds, "|zi:setupterm", kwlist, &termstr, &fd)) { - return NULL; - } - - if (fd == -1) { - PyObject* sys_stdout; - - sys_stdout = PySys_GetObject("stdout"); - - if (sys_stdout == NULL) { - PyErr_SetString( - PyCursesError, - "lost sys.stdout"); - return NULL; - } - - fd = PyObject_AsFileDescriptor(sys_stdout); - - if (fd == -1) { - return NULL; - } - } - - if (setupterm(termstr,fd,&err) == ERR) { - char* s = "setupterm: unknown error"; - - if (err == 0) { - s = "setupterm: could not find terminal"; - } else if (err == -1) { - s = "setupterm: could not find terminfo database"; - } - - PyErr_SetString(PyCursesError,s); - return NULL; - } + int fd = -1; + int err; + char* termstr = NULL; + + static char *kwlist[] = {"term", "fd", NULL}; + + if (!PyArg_ParseTupleAndKeywords( + args, keywds, "|zi:setupterm", kwlist, &termstr, &fd)) { + return NULL; + } + + if (fd == -1) { + PyObject* sys_stdout; + + sys_stdout = PySys_GetObject("stdout"); + + if (sys_stdout == NULL) { + PyErr_SetString( + PyCursesError, + "lost sys.stdout"); + return NULL; + } + + fd = PyObject_AsFileDescriptor(sys_stdout); + + if (fd == -1) { + return NULL; + } + } + + if (setupterm(termstr,fd,&err) == ERR) { + char* s = "setupterm: unknown error"; - initialised_setupterm = TRUE; + if (err == 0) { + s = "setupterm: could not find terminal"; + } else if (err == -1) { + s = "setupterm: could not find terminfo database"; + } - Py_INCREF(Py_None); - return Py_None; + PyErr_SetString(PyCursesError,s); + return NULL; + } + + initialised_setupterm = TRUE; + + Py_INCREF(Py_None); + return Py_None; } static PyObject * PyCurses_IntrFlush(PyObject *self, PyObject *args) { - int ch; + int ch; - PyCursesInitialised; + PyCursesInitialised; - switch(PyTuple_Size(args)) { - case 1: - if (!PyArg_ParseTuple(args,"i;True(1), False(0)",&ch)) return NULL; - break; - default: - PyErr_SetString(PyExc_TypeError, "intrflush requires 1 argument"); - return NULL; - } + switch(PyTuple_Size(args)) { + case 1: + if (!PyArg_ParseTuple(args,"i;True(1), False(0)",&ch)) return NULL; + break; + default: + PyErr_SetString(PyExc_TypeError, "intrflush requires 1 argument"); + return NULL; + } - return PyCursesCheckERR(intrflush(NULL,ch), "intrflush"); + return PyCursesCheckERR(intrflush(NULL,ch), "intrflush"); } #ifdef HAVE_CURSES_IS_TERM_RESIZED static PyObject * PyCurses_Is_Term_Resized(PyObject *self, PyObject *args) { - int lines; - int columns; - int result; - - PyCursesInitialised; - - if (!PyArg_ParseTuple(args,"ii:is_term_resized", &lines, &columns)) - return NULL; - result = is_term_resized(lines, columns); - if (result == TRUE) { - Py_INCREF(Py_True); - return Py_True; - } else { - Py_INCREF(Py_False); - return Py_False; - } + int lines; + int columns; + int result; + + PyCursesInitialised; + + if (!PyArg_ParseTuple(args,"ii:is_term_resized", &lines, &columns)) + return NULL; + result = is_term_resized(lines, columns); + if (result == TRUE) { + Py_INCREF(Py_True); + return Py_True; + } else { + Py_INCREF(Py_False); + return Py_False; + } } #endif /* HAVE_CURSES_IS_TERM_RESIZED */ @@ -2112,75 +2112,75 @@ static PyObject * PyCurses_KeyName(PyObject *self, PyObject *args) { - const char *knp; - int ch; + const char *knp; + int ch; - PyCursesInitialised; + PyCursesInitialised; - if (!PyArg_ParseTuple(args,"i",&ch)) return NULL; + if (!PyArg_ParseTuple(args,"i",&ch)) return NULL; - if (ch < 0) { - PyErr_SetString(PyExc_ValueError, "invalid key number"); - return NULL; - } - knp = keyname(ch); + if (ch < 0) { + PyErr_SetString(PyExc_ValueError, "invalid key number"); + return NULL; + } + knp = keyname(ch); - return PyString_FromString((knp == NULL) ? "" : (char *)knp); + return PyString_FromString((knp == NULL) ? "" : (char *)knp); } #endif -static PyObject * -PyCurses_KillChar(PyObject *self) -{ - char ch; +static PyObject * +PyCurses_KillChar(PyObject *self) +{ + char ch; - ch = killchar(); + ch = killchar(); - return PyString_FromStringAndSize(&ch, 1); -} + return PyString_FromStringAndSize(&ch, 1); +} static PyObject * PyCurses_Meta(PyObject *self, PyObject *args) { - int ch; + int ch; - PyCursesInitialised; + PyCursesInitialised; - switch(PyTuple_Size(args)) { - case 1: - if (!PyArg_ParseTuple(args,"i;True(1), False(0)",&ch)) return NULL; - break; - default: - PyErr_SetString(PyExc_TypeError, "meta requires 1 argument"); - return NULL; - } + switch(PyTuple_Size(args)) { + case 1: + if (!PyArg_ParseTuple(args,"i;True(1), False(0)",&ch)) return NULL; + break; + default: + PyErr_SetString(PyExc_TypeError, "meta requires 1 argument"); + return NULL; + } - return PyCursesCheckERR(meta(stdscr, ch), "meta"); + return PyCursesCheckERR(meta(stdscr, ch), "meta"); } #ifdef NCURSES_MOUSE_VERSION static PyObject * PyCurses_MouseInterval(PyObject *self, PyObject *args) { - int interval; - PyCursesInitialised; + int interval; + PyCursesInitialised; - if (!PyArg_ParseTuple(args,"i;interval",&interval)) - return NULL; - return PyCursesCheckERR(mouseinterval(interval), "mouseinterval"); + if (!PyArg_ParseTuple(args,"i;interval",&interval)) + return NULL; + return PyCursesCheckERR(mouseinterval(interval), "mouseinterval"); } static PyObject * PyCurses_MouseMask(PyObject *self, PyObject *args) { - int newmask; - mmask_t oldmask, availmask; + int newmask; + mmask_t oldmask, availmask; - PyCursesInitialised; - if (!PyArg_ParseTuple(args,"i;mousemask",&newmask)) - return NULL; - availmask = mousemask(newmask, &oldmask); - return Py_BuildValue("(ll)", (long)availmask, (long)oldmask); + PyCursesInitialised; + if (!PyArg_ParseTuple(args,"i;mousemask",&newmask)) + return NULL; + availmask = mousemask(newmask, &oldmask); + return Py_BuildValue("(ll)", (long)availmask, (long)oldmask); } #endif @@ -2199,133 +2199,133 @@ static PyObject * PyCurses_NewPad(PyObject *self, PyObject *args) { - WINDOW *win; - int nlines, ncols; + WINDOW *win; + int nlines, ncols; - PyCursesInitialised; + PyCursesInitialised; - if (!PyArg_ParseTuple(args,"ii;nlines,ncols",&nlines,&ncols)) return NULL; + if (!PyArg_ParseTuple(args,"ii;nlines,ncols",&nlines,&ncols)) return NULL; - win = newpad(nlines, ncols); - - if (win == NULL) { - PyErr_SetString(PyCursesError, catchall_NULL); - return NULL; - } + win = newpad(nlines, ncols); - return (PyObject *)PyCursesWindow_New(win); + if (win == NULL) { + PyErr_SetString(PyCursesError, catchall_NULL); + return NULL; + } + + return (PyObject *)PyCursesWindow_New(win); } static PyObject * PyCurses_NewWindow(PyObject *self, PyObject *args) { - WINDOW *win; - int nlines, ncols, begin_y=0, begin_x=0; + WINDOW *win; + int nlines, ncols, begin_y=0, begin_x=0; - PyCursesInitialised; + PyCursesInitialised; + + switch (PyTuple_Size(args)) { + case 2: + if (!PyArg_ParseTuple(args,"ii;nlines,ncols",&nlines,&ncols)) + return NULL; + break; + case 4: + if (!PyArg_ParseTuple(args, "iiii;nlines,ncols,begin_y,begin_x", + &nlines,&ncols,&begin_y,&begin_x)) + return NULL; + break; + default: + PyErr_SetString(PyExc_TypeError, "newwin requires 2 or 4 arguments"); + return NULL; + } - switch (PyTuple_Size(args)) { - case 2: - if (!PyArg_ParseTuple(args,"ii;nlines,ncols",&nlines,&ncols)) - return NULL; - break; - case 4: - if (!PyArg_ParseTuple(args, "iiii;nlines,ncols,begin_y,begin_x", - &nlines,&ncols,&begin_y,&begin_x)) - return NULL; - break; - default: - PyErr_SetString(PyExc_TypeError, "newwin requires 2 or 4 arguments"); - return NULL; - } - - win = newwin(nlines,ncols,begin_y,begin_x); - if (win == NULL) { - PyErr_SetString(PyCursesError, catchall_NULL); - return NULL; - } + win = newwin(nlines,ncols,begin_y,begin_x); + if (win == NULL) { + PyErr_SetString(PyCursesError, catchall_NULL); + return NULL; + } - return (PyObject *)PyCursesWindow_New(win); + return (PyObject *)PyCursesWindow_New(win); } static PyObject * PyCurses_Pair_Content(PyObject *self, PyObject *args) { - short pair,f,b; + short pair,f,b; + + PyCursesInitialised; + PyCursesInitialisedColor; - PyCursesInitialised; - PyCursesInitialisedColor; + switch(PyTuple_Size(args)) { + case 1: + if (!PyArg_ParseTuple(args, "h;pair", &pair)) return NULL; + break; + default: + PyErr_SetString(PyExc_TypeError, "pair_content requires 1 argument"); + return NULL; + } - switch(PyTuple_Size(args)) { - case 1: - if (!PyArg_ParseTuple(args, "h;pair", &pair)) return NULL; - break; - default: - PyErr_SetString(PyExc_TypeError, "pair_content requires 1 argument"); - return NULL; - } - - if (pair_content(pair, &f, &b)==ERR) { - PyErr_SetString(PyCursesError, - "Argument 1 was out of range. (1..COLOR_PAIRS-1)"); - return NULL; - } + if (pair_content(pair, &f, &b)==ERR) { + PyErr_SetString(PyCursesError, + "Argument 1 was out of range. (1..COLOR_PAIRS-1)"); + return NULL; + } - return Py_BuildValue("(ii)", f, b); + return Py_BuildValue("(ii)", f, b); } static PyObject * PyCurses_pair_number(PyObject *self, PyObject *args) { - int n; + int n; - PyCursesInitialised; - PyCursesInitialisedColor; + PyCursesInitialised; + PyCursesInitialisedColor; - switch(PyTuple_Size(args)) { - case 1: - if (!PyArg_ParseTuple(args, "i;pairvalue", &n)) return NULL; - break; - default: - PyErr_SetString(PyExc_TypeError, - "pair_number requires 1 argument"); - return NULL; - } + switch(PyTuple_Size(args)) { + case 1: + if (!PyArg_ParseTuple(args, "i;pairvalue", &n)) return NULL; + break; + default: + PyErr_SetString(PyExc_TypeError, + "pair_number requires 1 argument"); + return NULL; + } - return PyInt_FromLong((long) ((n & A_COLOR) >> 8)); + return PyInt_FromLong((long) ((n & A_COLOR) >> 8)); } static PyObject * PyCurses_Putp(PyObject *self, PyObject *args) { - char *str; + char *str; - if (!PyArg_ParseTuple(args,"s;str", &str)) return NULL; - return PyCursesCheckERR(putp(str), "putp"); + if (!PyArg_ParseTuple(args,"s;str", &str)) return NULL; + return PyCursesCheckERR(putp(str), "putp"); } static PyObject * PyCurses_QiFlush(PyObject *self, PyObject *args) { - int flag = 0; + int flag = 0; - PyCursesInitialised; + PyCursesInitialised; - switch(PyTuple_Size(args)) { - case 0: - qiflush(); - Py_INCREF(Py_None); - return Py_None; - case 1: - if (!PyArg_ParseTuple(args, "i;True(1) or False(0)", &flag)) return NULL; - if (flag) qiflush(); - else noqiflush(); - Py_INCREF(Py_None); - return Py_None; - default: - PyErr_SetString(PyExc_TypeError, "qiflush requires 0 or 1 arguments"); - return NULL; - } + switch(PyTuple_Size(args)) { + case 0: + qiflush(); + Py_INCREF(Py_None); + return Py_None; + case 1: + if (!PyArg_ParseTuple(args, "i;True(1) or False(0)", &flag)) return NULL; + if (flag) qiflush(); + else noqiflush(); + Py_INCREF(Py_None); + return Py_None; + default: + PyErr_SetString(PyExc_TypeError, "qiflush requires 0 or 1 arguments"); + return NULL; + } } /* Internal helper used for updating curses.LINES, curses.COLS, _curses.LINES @@ -2334,46 +2334,46 @@ static int update_lines_cols(void) { - PyObject *o; - PyObject *m = PyImport_ImportModuleNoBlock("curses"); + PyObject *o; + PyObject *m = PyImport_ImportModuleNoBlock("curses"); - if (!m) - return 0; + if (!m) + return 0; - o = PyInt_FromLong(LINES); - if (!o) { - Py_DECREF(m); - return 0; - } - if (PyObject_SetAttrString(m, "LINES", o)) { - Py_DECREF(m); - Py_DECREF(o); - return 0; - } - if (PyDict_SetItemString(ModDict, "LINES", o)) { - Py_DECREF(m); + o = PyInt_FromLong(LINES); + if (!o) { + Py_DECREF(m); + return 0; + } + if (PyObject_SetAttrString(m, "LINES", o)) { + Py_DECREF(m); + Py_DECREF(o); + return 0; + } + if (PyDict_SetItemString(ModDict, "LINES", o)) { + Py_DECREF(m); + Py_DECREF(o); + return 0; + } Py_DECREF(o); - return 0; - } - Py_DECREF(o); - o = PyInt_FromLong(COLS); - if (!o) { - Py_DECREF(m); - return 0; - } - if (PyObject_SetAttrString(m, "COLS", o)) { - Py_DECREF(m); + o = PyInt_FromLong(COLS); + if (!o) { + Py_DECREF(m); + return 0; + } + if (PyObject_SetAttrString(m, "COLS", o)) { + Py_DECREF(m); + Py_DECREF(o); + return 0; + } + if (PyDict_SetItemString(ModDict, "COLS", o)) { + Py_DECREF(m); + Py_DECREF(o); + return 0; + } Py_DECREF(o); - return 0; - } - if (PyDict_SetItemString(ModDict, "COLS", o)) { Py_DECREF(m); - Py_DECREF(o); - return 0; - } - Py_DECREF(o); - Py_DECREF(m); - return 1; + return 1; } #endif @@ -2381,21 +2381,21 @@ static PyObject * PyCurses_ResizeTerm(PyObject *self, PyObject *args) { - int lines; - int columns; - PyObject *result; - - PyCursesInitialised; - - if (!PyArg_ParseTuple(args,"ii:resizeterm", &lines, &columns)) - return NULL; - - result = PyCursesCheckERR(resizeterm(lines, columns), "resizeterm"); - if (!result) - return NULL; - if (!update_lines_cols()) - return NULL; - return result; + int lines; + int columns; + PyObject *result; + + PyCursesInitialised; + + if (!PyArg_ParseTuple(args,"ii:resizeterm", &lines, &columns)) + return NULL; + + result = PyCursesCheckERR(resizeterm(lines, columns), "resizeterm"); + if (!result) + return NULL; + if (!update_lines_cols()) + return NULL; + return result; } #endif @@ -2404,326 +2404,326 @@ static PyObject * PyCurses_Resize_Term(PyObject *self, PyObject *args) { - int lines; - int columns; + int lines; + int columns; - PyObject *result; + PyObject *result; - PyCursesInitialised; + PyCursesInitialised; - if (!PyArg_ParseTuple(args,"ii:resize_term", &lines, &columns)) - return NULL; - - result = PyCursesCheckERR(resize_term(lines, columns), "resize_term"); - if (!result) - return NULL; - if (!update_lines_cols()) - return NULL; - return result; + if (!PyArg_ParseTuple(args,"ii:resize_term", &lines, &columns)) + return NULL; + + result = PyCursesCheckERR(resize_term(lines, columns), "resize_term"); + if (!result) + return NULL; + if (!update_lines_cols()) + return NULL; + return result; } #endif /* HAVE_CURSES_RESIZE_TERM */ static PyObject * PyCurses_setsyx(PyObject *self, PyObject *args) { - int y,x; + int y,x; - PyCursesInitialised; + PyCursesInitialised; - if (PyTuple_Size(args)!=2) { - PyErr_SetString(PyExc_TypeError, "setsyx requires 2 arguments"); - return NULL; - } + if (PyTuple_Size(args)!=2) { + PyErr_SetString(PyExc_TypeError, "setsyx requires 2 arguments"); + return NULL; + } - if (!PyArg_ParseTuple(args, "ii;y, x", &y, &x)) return NULL; + if (!PyArg_ParseTuple(args, "ii;y, x", &y, &x)) return NULL; - setsyx(y,x); + setsyx(y,x); - Py_INCREF(Py_None); - return Py_None; + Py_INCREF(Py_None); + return Py_None; } static PyObject * PyCurses_Start_Color(PyObject *self) { - int code; - PyObject *c, *cp; + int code; + PyObject *c, *cp; - PyCursesInitialised; + PyCursesInitialised; - code = start_color(); - if (code != ERR) { - initialisedcolors = TRUE; - c = PyInt_FromLong((long) COLORS); - PyDict_SetItemString(ModDict, "COLORS", c); - Py_DECREF(c); - cp = PyInt_FromLong((long) COLOR_PAIRS); - PyDict_SetItemString(ModDict, "COLOR_PAIRS", cp); - Py_DECREF(cp); - Py_INCREF(Py_None); - return Py_None; - } else { - PyErr_SetString(PyCursesError, "start_color() returned ERR"); - return NULL; - } + code = start_color(); + if (code != ERR) { + initialisedcolors = TRUE; + c = PyInt_FromLong((long) COLORS); + PyDict_SetItemString(ModDict, "COLORS", c); + Py_DECREF(c); + cp = PyInt_FromLong((long) COLOR_PAIRS); + PyDict_SetItemString(ModDict, "COLOR_PAIRS", cp); + Py_DECREF(cp); + Py_INCREF(Py_None); + return Py_None; + } else { + PyErr_SetString(PyCursesError, "start_color() returned ERR"); + return NULL; + } } static PyObject * PyCurses_tigetflag(PyObject *self, PyObject *args) { - char *capname; + char *capname; - PyCursesSetupTermCalled; - - if (!PyArg_ParseTuple(args, "s", &capname)) - return NULL; + PyCursesSetupTermCalled; - return PyInt_FromLong( (long) tigetflag( capname ) ); + if (!PyArg_ParseTuple(args, "s", &capname)) + return NULL; + + return PyInt_FromLong( (long) tigetflag( capname ) ); } static PyObject * PyCurses_tigetnum(PyObject *self, PyObject *args) { - char *capname; + char *capname; - PyCursesSetupTermCalled; - - if (!PyArg_ParseTuple(args, "s", &capname)) - return NULL; + PyCursesSetupTermCalled; - return PyInt_FromLong( (long) tigetnum( capname ) ); + if (!PyArg_ParseTuple(args, "s", &capname)) + return NULL; + + return PyInt_FromLong( (long) tigetnum( capname ) ); } static PyObject * PyCurses_tigetstr(PyObject *self, PyObject *args) { - char *capname; + char *capname; + + PyCursesSetupTermCalled; - PyCursesSetupTermCalled; - - if (!PyArg_ParseTuple(args, "s", &capname)) - return NULL; - - capname = tigetstr( capname ); - if (capname == 0 || capname == (char*) -1) { - Py_INCREF(Py_None); - return Py_None; - } - return PyString_FromString( capname ); + if (!PyArg_ParseTuple(args, "s", &capname)) + return NULL; + + capname = tigetstr( capname ); + if (capname == 0 || capname == (char*) -1) { + Py_INCREF(Py_None); + return Py_None; + } + return PyString_FromString( capname ); } static PyObject * PyCurses_tparm(PyObject *self, PyObject *args) { - char* fmt; - char* result = NULL; - int i1=0,i2=0,i3=0,i4=0,i5=0,i6=0,i7=0,i8=0,i9=0; - - PyCursesSetupTermCalled; - - if (!PyArg_ParseTuple(args, "s|iiiiiiiii:tparm", - &fmt, &i1, &i2, &i3, &i4, - &i5, &i6, &i7, &i8, &i9)) { - return NULL; - } - - result = tparm(fmt,i1,i2,i3,i4,i5,i6,i7,i8,i9); - if (!result) { - PyErr_SetString(PyCursesError, "tparm() returned NULL"); - return NULL; - } + char* fmt; + char* result = NULL; + int i1=0,i2=0,i3=0,i4=0,i5=0,i6=0,i7=0,i8=0,i9=0; + + PyCursesSetupTermCalled; + + if (!PyArg_ParseTuple(args, "s|iiiiiiiii:tparm", + &fmt, &i1, &i2, &i3, &i4, + &i5, &i6, &i7, &i8, &i9)) { + return NULL; + } + + result = tparm(fmt,i1,i2,i3,i4,i5,i6,i7,i8,i9); + if (!result) { + PyErr_SetString(PyCursesError, "tparm() returned NULL"); + return NULL; + } - return PyString_FromString(result); + return PyString_FromString(result); } static PyObject * PyCurses_TypeAhead(PyObject *self, PyObject *args) { - int fd; + int fd; - PyCursesInitialised; + PyCursesInitialised; - if (!PyArg_ParseTuple(args,"i;fd",&fd)) return NULL; + if (!PyArg_ParseTuple(args,"i;fd",&fd)) return NULL; - return PyCursesCheckERR(typeahead( fd ), "typeahead"); + return PyCursesCheckERR(typeahead( fd ), "typeahead"); } static PyObject * PyCurses_UnCtrl(PyObject *self, PyObject *args) { - PyObject *temp; - chtype ch; + PyObject *temp; + chtype ch; - PyCursesInitialised; + PyCursesInitialised; - if (!PyArg_ParseTuple(args,"O;ch or int",&temp)) return NULL; + if (!PyArg_ParseTuple(args,"O;ch or int",&temp)) return NULL; - if (PyInt_Check(temp)) - ch = (chtype) PyInt_AsLong(temp); - else if (PyString_Check(temp)) - ch = (chtype) *PyString_AsString(temp); - else { - PyErr_SetString(PyExc_TypeError, "argument must be a ch or an int"); - return NULL; - } + if (PyInt_Check(temp)) + ch = (chtype) PyInt_AsLong(temp); + else if (PyString_Check(temp)) + ch = (chtype) *PyString_AsString(temp); + else { + PyErr_SetString(PyExc_TypeError, "argument must be a ch or an int"); + return NULL; + } - return PyString_FromString(unctrl(ch)); + return PyString_FromString(unctrl(ch)); } static PyObject * PyCurses_UngetCh(PyObject *self, PyObject *args) { - PyObject *temp; - int ch; + PyObject *temp; + int ch; - PyCursesInitialised; + PyCursesInitialised; - if (!PyArg_ParseTuple(args,"O;ch or int",&temp)) return NULL; + if (!PyArg_ParseTuple(args,"O;ch or int",&temp)) return NULL; - if (PyInt_Check(temp)) - ch = (int) PyInt_AsLong(temp); - else if (PyString_Check(temp)) - ch = (int) *PyString_AsString(temp); - else { - PyErr_SetString(PyExc_TypeError, "argument must be a ch or an int"); - return NULL; - } + if (PyInt_Check(temp)) + ch = (int) PyInt_AsLong(temp); + else if (PyString_Check(temp)) + ch = (int) *PyString_AsString(temp); + else { + PyErr_SetString(PyExc_TypeError, "argument must be a ch or an int"); + return NULL; + } - return PyCursesCheckERR(ungetch(ch), "ungetch"); + return PyCursesCheckERR(ungetch(ch), "ungetch"); } static PyObject * PyCurses_Use_Env(PyObject *self, PyObject *args) { - int flag; + int flag; - switch(PyTuple_Size(args)) { - case 1: - if (!PyArg_ParseTuple(args,"i;True(1), False(0)",&flag)) - return NULL; - break; - default: - PyErr_SetString(PyExc_TypeError, "use_env requires 1 argument"); - return NULL; - } - use_env(flag); - Py_INCREF(Py_None); - return Py_None; + switch(PyTuple_Size(args)) { + case 1: + if (!PyArg_ParseTuple(args,"i;True(1), False(0)",&flag)) + return NULL; + break; + default: + PyErr_SetString(PyExc_TypeError, "use_env requires 1 argument"); + return NULL; + } + use_env(flag); + Py_INCREF(Py_None); + return Py_None; } #ifndef STRICT_SYSV_CURSES static PyObject * PyCurses_Use_Default_Colors(PyObject *self) { - int code; + int code; - PyCursesInitialised; - PyCursesInitialisedColor; + PyCursesInitialised; + PyCursesInitialisedColor; - code = use_default_colors(); - if (code != ERR) { - Py_INCREF(Py_None); - return Py_None; - } else { - PyErr_SetString(PyCursesError, "use_default_colors() returned ERR"); - return NULL; - } + code = use_default_colors(); + if (code != ERR) { + Py_INCREF(Py_None); + return Py_None; + } else { + PyErr_SetString(PyCursesError, "use_default_colors() returned ERR"); + return NULL; + } } #endif /* STRICT_SYSV_CURSES */ /* List of functions defined in the module */ static PyMethodDef PyCurses_methods[] = { - {"baudrate", (PyCFunction)PyCurses_baudrate, METH_NOARGS}, - {"beep", (PyCFunction)PyCurses_beep, METH_NOARGS}, - {"can_change_color", (PyCFunction)PyCurses_can_change_color, METH_NOARGS}, - {"cbreak", (PyCFunction)PyCurses_cbreak, METH_VARARGS}, - {"color_content", (PyCFunction)PyCurses_Color_Content, METH_VARARGS}, - {"color_pair", (PyCFunction)PyCurses_color_pair, METH_VARARGS}, - {"curs_set", (PyCFunction)PyCurses_Curs_Set, METH_VARARGS}, - {"def_prog_mode", (PyCFunction)PyCurses_def_prog_mode, METH_NOARGS}, - {"def_shell_mode", (PyCFunction)PyCurses_def_shell_mode, METH_NOARGS}, - {"delay_output", (PyCFunction)PyCurses_Delay_Output, METH_VARARGS}, - {"doupdate", (PyCFunction)PyCurses_doupdate, METH_NOARGS}, - {"echo", (PyCFunction)PyCurses_echo, METH_VARARGS}, - {"endwin", (PyCFunction)PyCurses_endwin, METH_NOARGS}, - {"erasechar", (PyCFunction)PyCurses_EraseChar, METH_NOARGS}, - {"filter", (PyCFunction)PyCurses_filter, METH_NOARGS}, - {"flash", (PyCFunction)PyCurses_flash, METH_NOARGS}, - {"flushinp", (PyCFunction)PyCurses_flushinp, METH_NOARGS}, + {"baudrate", (PyCFunction)PyCurses_baudrate, METH_NOARGS}, + {"beep", (PyCFunction)PyCurses_beep, METH_NOARGS}, + {"can_change_color", (PyCFunction)PyCurses_can_change_color, METH_NOARGS}, + {"cbreak", (PyCFunction)PyCurses_cbreak, METH_VARARGS}, + {"color_content", (PyCFunction)PyCurses_Color_Content, METH_VARARGS}, + {"color_pair", (PyCFunction)PyCurses_color_pair, METH_VARARGS}, + {"curs_set", (PyCFunction)PyCurses_Curs_Set, METH_VARARGS}, + {"def_prog_mode", (PyCFunction)PyCurses_def_prog_mode, METH_NOARGS}, + {"def_shell_mode", (PyCFunction)PyCurses_def_shell_mode, METH_NOARGS}, + {"delay_output", (PyCFunction)PyCurses_Delay_Output, METH_VARARGS}, + {"doupdate", (PyCFunction)PyCurses_doupdate, METH_NOARGS}, + {"echo", (PyCFunction)PyCurses_echo, METH_VARARGS}, + {"endwin", (PyCFunction)PyCurses_endwin, METH_NOARGS}, + {"erasechar", (PyCFunction)PyCurses_EraseChar, METH_NOARGS}, + {"filter", (PyCFunction)PyCurses_filter, METH_NOARGS}, + {"flash", (PyCFunction)PyCurses_flash, METH_NOARGS}, + {"flushinp", (PyCFunction)PyCurses_flushinp, METH_NOARGS}, #ifdef NCURSES_MOUSE_VERSION - {"getmouse", (PyCFunction)PyCurses_GetMouse, METH_NOARGS}, - {"ungetmouse", (PyCFunction)PyCurses_UngetMouse, METH_VARARGS}, + {"getmouse", (PyCFunction)PyCurses_GetMouse, METH_NOARGS}, + {"ungetmouse", (PyCFunction)PyCurses_UngetMouse, METH_VARARGS}, #endif - {"getsyx", (PyCFunction)PyCurses_getsyx, METH_NOARGS}, - {"getwin", (PyCFunction)PyCurses_GetWin, METH_O}, - {"has_colors", (PyCFunction)PyCurses_has_colors, METH_NOARGS}, - {"has_ic", (PyCFunction)PyCurses_has_ic, METH_NOARGS}, - {"has_il", (PyCFunction)PyCurses_has_il, METH_NOARGS}, + {"getsyx", (PyCFunction)PyCurses_getsyx, METH_NOARGS}, + {"getwin", (PyCFunction)PyCurses_GetWin, METH_O}, + {"has_colors", (PyCFunction)PyCurses_has_colors, METH_NOARGS}, + {"has_ic", (PyCFunction)PyCurses_has_ic, METH_NOARGS}, + {"has_il", (PyCFunction)PyCurses_has_il, METH_NOARGS}, #ifndef STRICT_SYSV_CURSES - {"has_key", (PyCFunction)PyCurses_has_key, METH_VARARGS}, + {"has_key", (PyCFunction)PyCurses_has_key, METH_VARARGS}, #endif - {"halfdelay", (PyCFunction)PyCurses_HalfDelay, METH_VARARGS}, - {"init_color", (PyCFunction)PyCurses_Init_Color, METH_VARARGS}, - {"init_pair", (PyCFunction)PyCurses_Init_Pair, METH_VARARGS}, - {"initscr", (PyCFunction)PyCurses_InitScr, METH_NOARGS}, - {"intrflush", (PyCFunction)PyCurses_IntrFlush, METH_VARARGS}, - {"isendwin", (PyCFunction)PyCurses_isendwin, METH_NOARGS}, + {"halfdelay", (PyCFunction)PyCurses_HalfDelay, METH_VARARGS}, + {"init_color", (PyCFunction)PyCurses_Init_Color, METH_VARARGS}, + {"init_pair", (PyCFunction)PyCurses_Init_Pair, METH_VARARGS}, + {"initscr", (PyCFunction)PyCurses_InitScr, METH_NOARGS}, + {"intrflush", (PyCFunction)PyCurses_IntrFlush, METH_VARARGS}, + {"isendwin", (PyCFunction)PyCurses_isendwin, METH_NOARGS}, #ifdef HAVE_CURSES_IS_TERM_RESIZED - {"is_term_resized", (PyCFunction)PyCurses_Is_Term_Resized, METH_VARARGS}, + {"is_term_resized", (PyCFunction)PyCurses_Is_Term_Resized, METH_VARARGS}, #endif #if !defined(__NetBSD__) - {"keyname", (PyCFunction)PyCurses_KeyName, METH_VARARGS}, + {"keyname", (PyCFunction)PyCurses_KeyName, METH_VARARGS}, #endif - {"killchar", (PyCFunction)PyCurses_KillChar, METH_NOARGS}, - {"longname", (PyCFunction)PyCurses_longname, METH_NOARGS}, - {"meta", (PyCFunction)PyCurses_Meta, METH_VARARGS}, + {"killchar", (PyCFunction)PyCurses_KillChar, METH_NOARGS}, + {"longname", (PyCFunction)PyCurses_longname, METH_NOARGS}, + {"meta", (PyCFunction)PyCurses_Meta, METH_VARARGS}, #ifdef NCURSES_MOUSE_VERSION - {"mouseinterval", (PyCFunction)PyCurses_MouseInterval, METH_VARARGS}, - {"mousemask", (PyCFunction)PyCurses_MouseMask, METH_VARARGS}, + {"mouseinterval", (PyCFunction)PyCurses_MouseInterval, METH_VARARGS}, + {"mousemask", (PyCFunction)PyCurses_MouseMask, METH_VARARGS}, #endif - {"napms", (PyCFunction)PyCurses_Napms, METH_VARARGS}, - {"newpad", (PyCFunction)PyCurses_NewPad, METH_VARARGS}, - {"newwin", (PyCFunction)PyCurses_NewWindow, METH_VARARGS}, - {"nl", (PyCFunction)PyCurses_nl, METH_VARARGS}, - {"nocbreak", (PyCFunction)PyCurses_nocbreak, METH_NOARGS}, - {"noecho", (PyCFunction)PyCurses_noecho, METH_NOARGS}, - {"nonl", (PyCFunction)PyCurses_nonl, METH_NOARGS}, - {"noqiflush", (PyCFunction)PyCurses_noqiflush, METH_NOARGS}, - {"noraw", (PyCFunction)PyCurses_noraw, METH_NOARGS}, - {"pair_content", (PyCFunction)PyCurses_Pair_Content, METH_VARARGS}, - {"pair_number", (PyCFunction)PyCurses_pair_number, METH_VARARGS}, - {"putp", (PyCFunction)PyCurses_Putp, METH_VARARGS}, - {"qiflush", (PyCFunction)PyCurses_QiFlush, METH_VARARGS}, - {"raw", (PyCFunction)PyCurses_raw, METH_VARARGS}, - {"reset_prog_mode", (PyCFunction)PyCurses_reset_prog_mode, METH_NOARGS}, - {"reset_shell_mode", (PyCFunction)PyCurses_reset_shell_mode, METH_NOARGS}, - {"resetty", (PyCFunction)PyCurses_resetty, METH_NOARGS}, + {"napms", (PyCFunction)PyCurses_Napms, METH_VARARGS}, + {"newpad", (PyCFunction)PyCurses_NewPad, METH_VARARGS}, + {"newwin", (PyCFunction)PyCurses_NewWindow, METH_VARARGS}, + {"nl", (PyCFunction)PyCurses_nl, METH_VARARGS}, + {"nocbreak", (PyCFunction)PyCurses_nocbreak, METH_NOARGS}, + {"noecho", (PyCFunction)PyCurses_noecho, METH_NOARGS}, + {"nonl", (PyCFunction)PyCurses_nonl, METH_NOARGS}, + {"noqiflush", (PyCFunction)PyCurses_noqiflush, METH_NOARGS}, + {"noraw", (PyCFunction)PyCurses_noraw, METH_NOARGS}, + {"pair_content", (PyCFunction)PyCurses_Pair_Content, METH_VARARGS}, + {"pair_number", (PyCFunction)PyCurses_pair_number, METH_VARARGS}, + {"putp", (PyCFunction)PyCurses_Putp, METH_VARARGS}, + {"qiflush", (PyCFunction)PyCurses_QiFlush, METH_VARARGS}, + {"raw", (PyCFunction)PyCurses_raw, METH_VARARGS}, + {"reset_prog_mode", (PyCFunction)PyCurses_reset_prog_mode, METH_NOARGS}, + {"reset_shell_mode", (PyCFunction)PyCurses_reset_shell_mode, METH_NOARGS}, + {"resetty", (PyCFunction)PyCurses_resetty, METH_NOARGS}, #ifdef HAVE_CURSES_RESIZETERM - {"resizeterm", (PyCFunction)PyCurses_ResizeTerm, METH_VARARGS}, + {"resizeterm", (PyCFunction)PyCurses_ResizeTerm, METH_VARARGS}, #endif #ifdef HAVE_CURSES_RESIZE_TERM - {"resize_term", (PyCFunction)PyCurses_Resize_Term, METH_VARARGS}, + {"resize_term", (PyCFunction)PyCurses_Resize_Term, METH_VARARGS}, #endif - {"savetty", (PyCFunction)PyCurses_savetty, METH_NOARGS}, - {"setsyx", (PyCFunction)PyCurses_setsyx, METH_VARARGS}, - {"setupterm", (PyCFunction)PyCurses_setupterm, - METH_VARARGS|METH_KEYWORDS}, - {"start_color", (PyCFunction)PyCurses_Start_Color, METH_NOARGS}, - {"termattrs", (PyCFunction)PyCurses_termattrs, METH_NOARGS}, - {"termname", (PyCFunction)PyCurses_termname, METH_NOARGS}, - {"tigetflag", (PyCFunction)PyCurses_tigetflag, METH_VARARGS}, - {"tigetnum", (PyCFunction)PyCurses_tigetnum, METH_VARARGS}, - {"tigetstr", (PyCFunction)PyCurses_tigetstr, METH_VARARGS}, - {"tparm", (PyCFunction)PyCurses_tparm, METH_VARARGS}, - {"typeahead", (PyCFunction)PyCurses_TypeAhead, METH_VARARGS}, - {"unctrl", (PyCFunction)PyCurses_UnCtrl, METH_VARARGS}, - {"ungetch", (PyCFunction)PyCurses_UngetCh, METH_VARARGS}, - {"use_env", (PyCFunction)PyCurses_Use_Env, METH_VARARGS}, + {"savetty", (PyCFunction)PyCurses_savetty, METH_NOARGS}, + {"setsyx", (PyCFunction)PyCurses_setsyx, METH_VARARGS}, + {"setupterm", (PyCFunction)PyCurses_setupterm, + METH_VARARGS|METH_KEYWORDS}, + {"start_color", (PyCFunction)PyCurses_Start_Color, METH_NOARGS}, + {"termattrs", (PyCFunction)PyCurses_termattrs, METH_NOARGS}, + {"termname", (PyCFunction)PyCurses_termname, METH_NOARGS}, + {"tigetflag", (PyCFunction)PyCurses_tigetflag, METH_VARARGS}, + {"tigetnum", (PyCFunction)PyCurses_tigetnum, METH_VARARGS}, + {"tigetstr", (PyCFunction)PyCurses_tigetstr, METH_VARARGS}, + {"tparm", (PyCFunction)PyCurses_tparm, METH_VARARGS}, + {"typeahead", (PyCFunction)PyCurses_TypeAhead, METH_VARARGS}, + {"unctrl", (PyCFunction)PyCurses_UnCtrl, METH_VARARGS}, + {"ungetch", (PyCFunction)PyCurses_UngetCh, METH_VARARGS}, + {"use_env", (PyCFunction)PyCurses_Use_Env, METH_VARARGS}, #ifndef STRICT_SYSV_CURSES - {"use_default_colors", (PyCFunction)PyCurses_Use_Default_Colors, METH_NOARGS}, + {"use_default_colors", (PyCFunction)PyCurses_Use_Default_Colors, METH_NOARGS}, #endif - {NULL, NULL} /* sentinel */ + {NULL, NULL} /* sentinel */ }; /* Initialization function for the module */ @@ -2731,162 +2731,162 @@ PyMODINIT_FUNC init_curses(void) { - PyObject *m, *d, *v, *c_api_object; - static void *PyCurses_API[PyCurses_API_pointers]; + PyObject *m, *d, *v, *c_api_object; + static void *PyCurses_API[PyCurses_API_pointers]; - /* Initialize object type */ - Py_TYPE(&PyCursesWindow_Type) = &PyType_Type; + /* Initialize object type */ + Py_TYPE(&PyCursesWindow_Type) = &PyType_Type; - /* Initialize the C API pointer array */ - PyCurses_API[0] = (void *)&PyCursesWindow_Type; - PyCurses_API[1] = (void *)func_PyCursesSetupTermCalled; - PyCurses_API[2] = (void *)func_PyCursesInitialised; - PyCurses_API[3] = (void *)func_PyCursesInitialisedColor; - - /* Create the module and add the functions */ - m = Py_InitModule("_curses", PyCurses_methods); - if (m == NULL) - return; - - /* Add some symbolic constants to the module */ - d = PyModule_GetDict(m); - if (d == NULL) - return; - ModDict = d; /* For PyCurses_InitScr to use later */ - - /* Add a capsule for the C API */ - c_api_object = PyCapsule_New(PyCurses_API, PyCurses_CAPSULE_NAME, NULL); - PyDict_SetItemString(d, "_C_API", c_api_object); - Py_DECREF(c_api_object); - - /* For exception curses.error */ - PyCursesError = PyErr_NewException("_curses.error", NULL, NULL); - PyDict_SetItemString(d, "error", PyCursesError); - - /* Make the version available */ - v = PyString_FromString(PyCursesVersion); - PyDict_SetItemString(d, "version", v); - PyDict_SetItemString(d, "__version__", v); - Py_DECREF(v); - - SetDictInt("ERR", ERR); - SetDictInt("OK", OK); - - /* Here are some attributes you can add to chars to print */ - - SetDictInt("A_ATTRIBUTES", A_ATTRIBUTES); - SetDictInt("A_NORMAL", A_NORMAL); - SetDictInt("A_STANDOUT", A_STANDOUT); - SetDictInt("A_UNDERLINE", A_UNDERLINE); - SetDictInt("A_REVERSE", A_REVERSE); - SetDictInt("A_BLINK", A_BLINK); - SetDictInt("A_DIM", A_DIM); - SetDictInt("A_BOLD", A_BOLD); - SetDictInt("A_ALTCHARSET", A_ALTCHARSET); + /* Initialize the C API pointer array */ + PyCurses_API[0] = (void *)&PyCursesWindow_Type; + PyCurses_API[1] = (void *)func_PyCursesSetupTermCalled; + PyCurses_API[2] = (void *)func_PyCursesInitialised; + PyCurses_API[3] = (void *)func_PyCursesInitialisedColor; + + /* Create the module and add the functions */ + m = Py_InitModule("_curses", PyCurses_methods); + if (m == NULL) + return; + + /* Add some symbolic constants to the module */ + d = PyModule_GetDict(m); + if (d == NULL) + return; + ModDict = d; /* For PyCurses_InitScr to use later */ + + /* Add a capsule for the C API */ + c_api_object = PyCapsule_New(PyCurses_API, PyCurses_CAPSULE_NAME, NULL); + PyDict_SetItemString(d, "_C_API", c_api_object); + Py_DECREF(c_api_object); + + /* For exception curses.error */ + PyCursesError = PyErr_NewException("_curses.error", NULL, NULL); + PyDict_SetItemString(d, "error", PyCursesError); + + /* Make the version available */ + v = PyString_FromString(PyCursesVersion); + PyDict_SetItemString(d, "version", v); + PyDict_SetItemString(d, "__version__", v); + Py_DECREF(v); + + SetDictInt("ERR", ERR); + SetDictInt("OK", OK); + + /* Here are some attributes you can add to chars to print */ + + SetDictInt("A_ATTRIBUTES", A_ATTRIBUTES); + SetDictInt("A_NORMAL", A_NORMAL); + SetDictInt("A_STANDOUT", A_STANDOUT); + SetDictInt("A_UNDERLINE", A_UNDERLINE); + SetDictInt("A_REVERSE", A_REVERSE); + SetDictInt("A_BLINK", A_BLINK); + SetDictInt("A_DIM", A_DIM); + SetDictInt("A_BOLD", A_BOLD); + SetDictInt("A_ALTCHARSET", A_ALTCHARSET); #if !defined(__NetBSD__) - SetDictInt("A_INVIS", A_INVIS); + SetDictInt("A_INVIS", A_INVIS); #endif - SetDictInt("A_PROTECT", A_PROTECT); - SetDictInt("A_CHARTEXT", A_CHARTEXT); - SetDictInt("A_COLOR", A_COLOR); + SetDictInt("A_PROTECT", A_PROTECT); + SetDictInt("A_CHARTEXT", A_CHARTEXT); + SetDictInt("A_COLOR", A_COLOR); - /* The following are never available with strict SYSV curses */ + /* The following are never available with strict SYSV curses */ #ifdef A_HORIZONTAL - SetDictInt("A_HORIZONTAL", A_HORIZONTAL); + SetDictInt("A_HORIZONTAL", A_HORIZONTAL); #endif #ifdef A_LEFT - SetDictInt("A_LEFT", A_LEFT); + SetDictInt("A_LEFT", A_LEFT); #endif #ifdef A_LOW - SetDictInt("A_LOW", A_LOW); + SetDictInt("A_LOW", A_LOW); #endif #ifdef A_RIGHT - SetDictInt("A_RIGHT", A_RIGHT); + SetDictInt("A_RIGHT", A_RIGHT); #endif #ifdef A_TOP - SetDictInt("A_TOP", A_TOP); + SetDictInt("A_TOP", A_TOP); #endif #ifdef A_VERTICAL - SetDictInt("A_VERTICAL", A_VERTICAL); + SetDictInt("A_VERTICAL", A_VERTICAL); #endif - SetDictInt("COLOR_BLACK", COLOR_BLACK); - SetDictInt("COLOR_RED", COLOR_RED); - SetDictInt("COLOR_GREEN", COLOR_GREEN); - SetDictInt("COLOR_YELLOW", COLOR_YELLOW); - SetDictInt("COLOR_BLUE", COLOR_BLUE); - SetDictInt("COLOR_MAGENTA", COLOR_MAGENTA); - SetDictInt("COLOR_CYAN", COLOR_CYAN); - SetDictInt("COLOR_WHITE", COLOR_WHITE); + SetDictInt("COLOR_BLACK", COLOR_BLACK); + SetDictInt("COLOR_RED", COLOR_RED); + SetDictInt("COLOR_GREEN", COLOR_GREEN); + SetDictInt("COLOR_YELLOW", COLOR_YELLOW); + SetDictInt("COLOR_BLUE", COLOR_BLUE); + SetDictInt("COLOR_MAGENTA", COLOR_MAGENTA); + SetDictInt("COLOR_CYAN", COLOR_CYAN); + SetDictInt("COLOR_WHITE", COLOR_WHITE); #ifdef NCURSES_MOUSE_VERSION - /* Mouse-related constants */ - SetDictInt("BUTTON1_PRESSED", BUTTON1_PRESSED); - SetDictInt("BUTTON1_RELEASED", BUTTON1_RELEASED); - SetDictInt("BUTTON1_CLICKED", BUTTON1_CLICKED); - SetDictInt("BUTTON1_DOUBLE_CLICKED", BUTTON1_DOUBLE_CLICKED); - SetDictInt("BUTTON1_TRIPLE_CLICKED", BUTTON1_TRIPLE_CLICKED); - - SetDictInt("BUTTON2_PRESSED", BUTTON2_PRESSED); - SetDictInt("BUTTON2_RELEASED", BUTTON2_RELEASED); - SetDictInt("BUTTON2_CLICKED", BUTTON2_CLICKED); - SetDictInt("BUTTON2_DOUBLE_CLICKED", BUTTON2_DOUBLE_CLICKED); - SetDictInt("BUTTON2_TRIPLE_CLICKED", BUTTON2_TRIPLE_CLICKED); - - SetDictInt("BUTTON3_PRESSED", BUTTON3_PRESSED); - SetDictInt("BUTTON3_RELEASED", BUTTON3_RELEASED); - SetDictInt("BUTTON3_CLICKED", BUTTON3_CLICKED); - SetDictInt("BUTTON3_DOUBLE_CLICKED", BUTTON3_DOUBLE_CLICKED); - SetDictInt("BUTTON3_TRIPLE_CLICKED", BUTTON3_TRIPLE_CLICKED); - - SetDictInt("BUTTON4_PRESSED", BUTTON4_PRESSED); - SetDictInt("BUTTON4_RELEASED", BUTTON4_RELEASED); - SetDictInt("BUTTON4_CLICKED", BUTTON4_CLICKED); - SetDictInt("BUTTON4_DOUBLE_CLICKED", BUTTON4_DOUBLE_CLICKED); - SetDictInt("BUTTON4_TRIPLE_CLICKED", BUTTON4_TRIPLE_CLICKED); - - SetDictInt("BUTTON_SHIFT", BUTTON_SHIFT); - SetDictInt("BUTTON_CTRL", BUTTON_CTRL); - SetDictInt("BUTTON_ALT", BUTTON_ALT); - - SetDictInt("ALL_MOUSE_EVENTS", ALL_MOUSE_EVENTS); - SetDictInt("REPORT_MOUSE_POSITION", REPORT_MOUSE_POSITION); -#endif - /* Now set everything up for KEY_ variables */ - { - int key; - char *key_n; - char *key_n2; + /* Mouse-related constants */ + SetDictInt("BUTTON1_PRESSED", BUTTON1_PRESSED); + SetDictInt("BUTTON1_RELEASED", BUTTON1_RELEASED); + SetDictInt("BUTTON1_CLICKED", BUTTON1_CLICKED); + SetDictInt("BUTTON1_DOUBLE_CLICKED", BUTTON1_DOUBLE_CLICKED); + SetDictInt("BUTTON1_TRIPLE_CLICKED", BUTTON1_TRIPLE_CLICKED); + + SetDictInt("BUTTON2_PRESSED", BUTTON2_PRESSED); + SetDictInt("BUTTON2_RELEASED", BUTTON2_RELEASED); + SetDictInt("BUTTON2_CLICKED", BUTTON2_CLICKED); + SetDictInt("BUTTON2_DOUBLE_CLICKED", BUTTON2_DOUBLE_CLICKED); + SetDictInt("BUTTON2_TRIPLE_CLICKED", BUTTON2_TRIPLE_CLICKED); + + SetDictInt("BUTTON3_PRESSED", BUTTON3_PRESSED); + SetDictInt("BUTTON3_RELEASED", BUTTON3_RELEASED); + SetDictInt("BUTTON3_CLICKED", BUTTON3_CLICKED); + SetDictInt("BUTTON3_DOUBLE_CLICKED", BUTTON3_DOUBLE_CLICKED); + SetDictInt("BUTTON3_TRIPLE_CLICKED", BUTTON3_TRIPLE_CLICKED); + + SetDictInt("BUTTON4_PRESSED", BUTTON4_PRESSED); + SetDictInt("BUTTON4_RELEASED", BUTTON4_RELEASED); + SetDictInt("BUTTON4_CLICKED", BUTTON4_CLICKED); + SetDictInt("BUTTON4_DOUBLE_CLICKED", BUTTON4_DOUBLE_CLICKED); + SetDictInt("BUTTON4_TRIPLE_CLICKED", BUTTON4_TRIPLE_CLICKED); + + SetDictInt("BUTTON_SHIFT", BUTTON_SHIFT); + SetDictInt("BUTTON_CTRL", BUTTON_CTRL); + SetDictInt("BUTTON_ALT", BUTTON_ALT); + + SetDictInt("ALL_MOUSE_EVENTS", ALL_MOUSE_EVENTS); + SetDictInt("REPORT_MOUSE_POSITION", REPORT_MOUSE_POSITION); +#endif + /* Now set everything up for KEY_ variables */ + { + int key; + char *key_n; + char *key_n2; #if !defined(__NetBSD__) - for (key=KEY_MIN;key < KEY_MAX; key++) { - key_n = (char *)keyname(key); - if (key_n == NULL || strcmp(key_n,"UNKNOWN KEY")==0) - continue; - if (strncmp(key_n,"KEY_F(",6)==0) { - char *p1, *p2; - key_n2 = malloc(strlen(key_n)+1); - if (!key_n2) { - PyErr_NoMemory(); - break; - } - p1 = key_n; - p2 = key_n2; - while (*p1) { - if (*p1 != '(' && *p1 != ')') { - *p2 = *p1; - p2++; - } - p1++; - } - *p2 = (char)0; - } else - key_n2 = key_n; - SetDictInt(key_n2,key); - if (key_n2 != key_n) - free(key_n2); - } -#endif - SetDictInt("KEY_MIN", KEY_MIN); - SetDictInt("KEY_MAX", KEY_MAX); - } + for (key=KEY_MIN;key < KEY_MAX; key++) { + key_n = (char *)keyname(key); + if (key_n == NULL || strcmp(key_n,"UNKNOWN KEY")==0) + continue; + if (strncmp(key_n,"KEY_F(",6)==0) { + char *p1, *p2; + key_n2 = malloc(strlen(key_n)+1); + if (!key_n2) { + PyErr_NoMemory(); + break; + } + p1 = key_n; + p2 = key_n2; + while (*p1) { + if (*p1 != '(' && *p1 != ')') { + *p2 = *p1; + p2++; + } + p1++; + } + *p2 = (char)0; + } else + key_n2 = key_n; + SetDictInt(key_n2,key); + if (key_n2 != key_n) + free(key_n2); + } +#endif + SetDictInt("KEY_MIN", KEY_MIN); + SetDictInt("KEY_MAX", KEY_MAX); + } } From python-checkins at python.org Mon May 10 22:21:17 2010 From: python-checkins at python.org (michael.foord) Date: Mon, 10 May 2010 22:21:17 +0200 (CEST) Subject: [Python-checkins] r81055 - in python/trunk/Lib/unittest: __main__.py main.py Message-ID: <20100510202117.04E62EE9A7@mail.python.org> Author: michael.foord Date: Mon May 10 22:21:16 2010 New Revision: 81055 Log: Improving help message for python -m unittest. Issue 8303. Modified: python/trunk/Lib/unittest/__main__.py python/trunk/Lib/unittest/main.py Modified: python/trunk/Lib/unittest/__main__.py ============================================================================== --- python/trunk/Lib/unittest/__main__.py (original) +++ python/trunk/Lib/unittest/__main__.py Mon May 10 22:21:16 2010 @@ -2,7 +2,7 @@ import sys if sys.argv[0].endswith("__main__.py"): - sys.argv[0] = "unittest" + sys.argv[0] = "python -m unittest" __unittest = True Modified: python/trunk/Lib/unittest/main.py ============================================================================== --- python/trunk/Lib/unittest/main.py (original) +++ python/trunk/Lib/unittest/main.py Mon May 10 22:21:16 2010 @@ -22,10 +22,9 @@ -q, --quiet Minimal output %(failfast)s%(catchbreak)s%(buffer)s Examples: - %(progName)s test_module - run tests from test_module - %(progName)s test_module.TestClass - run tests from - test_module.TestClass - %(progName)s test_module.TestClass.test_method - run specified test method + %(progName)s test_module - run tests from test_module + %(progName)s module.TestClass - run tests from module.TestClass + %(progName)s module.Class.test_method - run specified test method [tests] can be a list of any number of test modules, classes and test methods. @@ -68,7 +67,7 @@ USAGE = USAGE_FROM_MODULE # defaults for testing - failfast = catchbreak = buffer = None + failfast = catchbreak = buffer = progName = None def __init__(self, module='__main__', defaultTest=None, argv=None, testRunner=None, testLoader=loader.defaultTestLoader, @@ -160,8 +159,10 @@ def _do_discovery(self, argv, Loader=loader.TestLoader): # handle command line args for test discovery + self.progName = '%s discover' % self.progName import optparse parser = optparse.OptionParser() + parser.prog = self.progName parser.add_option('-v', '--verbose', dest='verbose', default=False, help='Verbose output', action='store_true') if self.failfast != False: From python-checkins at python.org Mon May 10 22:23:58 2010 From: python-checkins at python.org (michael.foord) Date: Mon, 10 May 2010 22:23:58 +0200 (CEST) Subject: [Python-checkins] r81056 - in python/branches/py3k: Lib/unittest/__main__.py Lib/unittest/main.py Message-ID: <20100510202358.2F4DFE308@mail.python.org> Author: michael.foord Date: Mon May 10 22:23:58 2010 New Revision: 81056 Log: Merged revisions 81055 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r81055 | michael.foord | 2010-05-10 21:21:16 +0100 (Mon, 10 May 2010) | 1 line Improving help message for python -m unittest. Issue 8303. ........ Modified: python/branches/py3k/ (props changed) python/branches/py3k/Lib/unittest/__main__.py python/branches/py3k/Lib/unittest/main.py Modified: python/branches/py3k/Lib/unittest/__main__.py ============================================================================== --- python/branches/py3k/Lib/unittest/__main__.py (original) +++ python/branches/py3k/Lib/unittest/__main__.py Mon May 10 22:23:58 2010 @@ -2,7 +2,7 @@ import sys if sys.argv[0].endswith("__main__.py"): - sys.argv[0] = "unittest" + sys.argv[0] = "python -m unittest" __unittest = True Modified: python/branches/py3k/Lib/unittest/main.py ============================================================================== --- python/branches/py3k/Lib/unittest/main.py (original) +++ python/branches/py3k/Lib/unittest/main.py Mon May 10 22:23:58 2010 @@ -22,10 +22,9 @@ -q, --quiet Minimal output %(failfast)s%(catchbreak)s%(buffer)s Examples: - %(progName)s test_module - run tests from test_module - %(progName)s test_module.TestClass - run tests from - test_module.TestClass - %(progName)s test_module.TestClass.test_method - run specified test method + %(progName)s test_module - run tests from test_module + %(progName)s module.TestClass - run tests from module.TestClass + %(progName)s module.Class.test_method - run specified test method [tests] can be a list of any number of test modules, classes and test methods. @@ -68,7 +67,7 @@ USAGE = USAGE_FROM_MODULE # defaults for testing - failfast = catchbreak = buffer = None + failfast = catchbreak = buffer = progName = None def __init__(self, module='__main__', defaultTest=None, argv=None, testRunner=None, testLoader=loader.defaultTestLoader, @@ -160,8 +159,10 @@ def _do_discovery(self, argv, Loader=loader.TestLoader): # handle command line args for test discovery + self.progName = '%s discover' % self.progName import optparse parser = optparse.OptionParser() + parser.prog = self.progName parser.add_option('-v', '--verbose', dest='verbose', default=False, help='Verbose output', action='store_true') if self.failfast != False: From python-checkins at python.org Mon May 10 22:49:20 2010 From: python-checkins at python.org (benjamin.peterson) Date: Mon, 10 May 2010 22:49:20 +0200 (CEST) Subject: [Python-checkins] r81057 - python/branches/py3k/Doc/library/exceptions.rst Message-ID: <20100510204920.83324EBF9@mail.python.org> Author: benjamin.peterson Date: Mon May 10 22:49:20 2010 New Revision: 81057 Log: remove reference to second argument to raise #8676 Modified: python/branches/py3k/Doc/library/exceptions.rst Modified: python/branches/py3k/Doc/library/exceptions.rst ============================================================================== --- python/branches/py3k/Doc/library/exceptions.rst (original) +++ python/branches/py3k/Doc/library/exceptions.rst Mon May 10 22:49:20 2010 @@ -20,10 +20,10 @@ built-in functions. Except where mentioned, they have an "associated value" indicating the detailed cause of the error. This may be a string or a tuple containing several items of information (e.g., an error code and a string -explaining the code). The associated value is the second argument to the -:keyword:`raise` statement. If the exception class is derived from the standard -root class :exc:`BaseException`, the associated value is present as the -exception instance's :attr:`args` attribute. +explaining the code). The associated value is usually passed to the exception +class's constructor. If the exception class is derived from the standard root +class :exc:`BaseException`, the associated value is present as the exception +instance's :attr:`args` attribute. User code can raise built-in exceptions. This can be used to test an exception handler or to report an error condition "just like" the situation in which the From python-checkins at python.org Mon May 10 22:52:35 2010 From: python-checkins at python.org (benjamin.peterson) Date: Mon, 10 May 2010 22:52:35 +0200 (CEST) Subject: [Python-checkins] r81058 - in python/branches/release31-maint: Doc/library/exceptions.rst Message-ID: <20100510205235.362C8EC01@mail.python.org> Author: benjamin.peterson Date: Mon May 10 22:52:35 2010 New Revision: 81058 Log: Merged revisions 81057 via svnmerge from svn+ssh://pythondev at svn.python.org/python/branches/py3k ........ r81057 | benjamin.peterson | 2010-05-10 15:49:20 -0500 (Mon, 10 May 2010) | 1 line remove reference to second argument to raise #8676 ........ Modified: python/branches/release31-maint/ (props changed) python/branches/release31-maint/Doc/library/exceptions.rst Modified: python/branches/release31-maint/Doc/library/exceptions.rst ============================================================================== --- python/branches/release31-maint/Doc/library/exceptions.rst (original) +++ python/branches/release31-maint/Doc/library/exceptions.rst Mon May 10 22:52:35 2010 @@ -28,10 +28,10 @@ built-in functions. Except where mentioned, they have an "associated value" indicating the detailed cause of the error. This may be a string or a tuple containing several items of information (e.g., an error code and a string -explaining the code). The associated value is the second argument to the -:keyword:`raise` statement. If the exception class is derived from the standard -root class :exc:`BaseException`, the associated value is present as the -exception instance's :attr:`args` attribute. +explaining the code). The associated value is usually passed to the exception +class's constructor. If the exception class is derived from the standard root +class :exc:`BaseException`, the associated value is present as the exception +instance's :attr:`args` attribute. User code can raise built-in exceptions. This can be used to test an exception handler or to report an error condition "just like" the situation in which the From python-checkins at python.org Mon May 10 23:02:51 2010 From: python-checkins at python.org (georg.brandl) Date: Mon, 10 May 2010 23:02:51 +0200 (CEST) Subject: [Python-checkins] r81059 - python/trunk/Doc/library/json.rst Message-ID: <20100510210251.90848EC24@mail.python.org> Author: georg.brandl Date: Mon May 10 23:02:51 2010 New Revision: 81059 Log: #8642: fix wrong function name. Modified: python/trunk/Doc/library/json.rst Modified: python/trunk/Doc/library/json.rst ============================================================================== --- python/trunk/Doc/library/json.rst (original) +++ python/trunk/Doc/library/json.rst Mon May 10 23:02:51 2010 @@ -223,7 +223,7 @@ specified. Encodings that are not ASCII based (such as UCS-2) are not allowed and should be decoded to :class:`unicode` first. - The other arguments have the same meaning as in :func:`dump`. + The other arguments have the same meaning as in :func:`load`. Encoders and decoders From python-checkins at python.org Mon May 10 23:12:44 2010 From: python-checkins at python.org (georg.brandl) Date: Mon, 10 May 2010 23:12:44 +0200 (CEST) Subject: [Python-checkins] r81060 - in python/branches/release26-maint: Doc/library/sqlite3.rst Message-ID: <20100510211244.570C0ECA3@mail.python.org> Author: georg.brandl Date: Mon May 10 23:12:44 2010 New Revision: 81060 Log: Merged revisions 78581 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r78581 | michael.foord | 2010-03-02 15:22:15 +0100 (Di, 02 M?r 2010) | 1 line Link correction in documentation. ........ Modified: python/branches/release26-maint/ (props changed) python/branches/release26-maint/Doc/library/sqlite3.rst Modified: python/branches/release26-maint/Doc/library/sqlite3.rst ============================================================================== --- python/branches/release26-maint/Doc/library/sqlite3.rst (original) +++ python/branches/release26-maint/Doc/library/sqlite3.rst Mon May 10 23:12:44 2010 @@ -92,7 +92,7 @@ .. seealso:: - http://www.pysqlite.org + http://code.google.com/p/pysqlite/ The pysqlite web page -- sqlite3 is developed externally under the name "pysqlite". From python-checkins at python.org Mon May 10 23:17:00 2010 From: python-checkins at python.org (georg.brandl) Date: Mon, 10 May 2010 23:17:00 +0200 (CEST) Subject: [Python-checkins] r81061 - python/branches/py3k/Doc/reference/lexical_analysis.rst Message-ID: <20100510211700.423F1EE9C4@mail.python.org> Author: georg.brandl Date: Mon May 10 23:17:00 2010 New Revision: 81061 Log: Fix nits in the lexical analysis section: \u requires four digits, backtick is not allowed in source in 3.x. Modified: python/branches/py3k/Doc/reference/lexical_analysis.rst Modified: python/branches/py3k/Doc/reference/lexical_analysis.rst ============================================================================== --- python/branches/py3k/Doc/reference/lexical_analysis.rst (original) +++ python/branches/py3k/Doc/reference/lexical_analysis.rst Mon May 10 23:17:00 2010 @@ -512,13 +512,13 @@ (4) Individual code units which form parts of a surrogate pair can be encoded using - this escape sequence. Unlike in Standard C, exactly two hex digits are required. + this escape sequence. Exactly four hex digits are required. (5) Any Unicode character can be encoded this way, but characters outside the Basic Multilingual Plane (BMP) will be encoded using a surrogate pair if Python is - compiled to use 16-bit code units (the default). Individual code units which - form parts of a surrogate pair can be encoded using this escape sequence. + compiled to use 16-bit code units (the default). Exactly eight hex digits + are required. .. index:: unrecognized escape sequence @@ -700,4 +700,4 @@ The following printing ASCII characters are not used in Python. Their occurrence outside string literals and comments is an unconditional error:: - $ ? + $ ? ` From python-checkins at python.org Mon May 10 23:19:58 2010 From: python-checkins at python.org (jeffrey.yasskin) Date: Mon, 10 May 2010 23:19:58 +0200 (CEST) Subject: [Python-checkins] r81062 - in python/branches/py3k-jit: Doc/library/_dummy_thread.rst Doc/library/_thread.rst Doc/library/datetime.rst Doc/library/html.parser.rst Doc/library/http.client.rst Doc/library/http.cookiejar.rst Doc/library/http.cookies.rst Doc/library/http.server.rst Doc/library/os.path.rst Doc/library/os.rst Doc/library/posix.rst Doc/library/tkinter.scrolledtext.rst Doc/library/tkinter.tix.rst Doc/library/tkinter.ttk.rst Doc/library/turtle.rst Doc/library/unittest.rst Doc/library/weakref.rst Doc/library/winreg.rst Doc/library/xmlrpc.client.rst Doc/library/xmlrpc.server.rst Include/unicodeobject.h Lib/_dummy_thread.py Lib/compileall.py Lib/dbm/dumb.py Lib/email/test/test_email_codecs.py Lib/http/client.py Lib/http/cookiejar.py Lib/http/cookies.py Lib/http/server.py Lib/lib2to3/fixes/fix_import.py Lib/lib2to3/fixes/fix_operator.py Lib/lib2to3/fixes/fix_reduce.py Lib/lib2to3/fixes/fix_tuple_params.py Lib/lib2to3/fixes/fix_xrange.py Lib/lib2to3/main.py Lib/lib2to3/pgen2/tokenize.py Lib/lib2to3/pytree.py Lib/lib2to3/refactor.py Lib/lib2to3/tests/test_fixers.py Lib/lib2to3/tests/test_parser.py Lib/lib2to3/tests/test_pytree.py Lib/lib2to3/tests/test_refactor.py Lib/os.py Lib/py_compile.py Lib/site.py Lib/subprocess.py Lib/sysconfig.py Lib/test/regrtest.py Lib/test/test_datetime.py Lib/test/test_dbm.py Lib/test/test_dbm_dumb.py Lib/test/test_dbm_gnu.py Lib/test/test_dbm_ndbm.py Lib/test/test_enumerate.py Lib/test/test_http_cookiejar.py Lib/test/test_http_cookies.py Lib/test/test_os.py Lib/test/test_posix.py Lib/test/test_signal.py Lib/test/test_subprocess.py Lib/test/test_sysconfig.py Lib/test/test_ttk_guionly.py Lib/test/test_ttk_textonly.py Lib/test/test_urllib2.py Lib/test/test_urlparse.py Lib/test/test_zlib.py Lib/tkinter/__init__.py Lib/tkinter/_fix.py Lib/tkinter/colorchooser.py Lib/tkinter/commondialog.py Lib/tkinter/constants.py Lib/tkinter/dialog.py Lib/tkinter/dnd.py Lib/tkinter/filedialog.py Lib/tkinter/font.py Lib/tkinter/messagebox.py Lib/tkinter/scrolledtext.py Lib/tkinter/simpledialog.py Lib/tkinter/test/support.py Lib/tkinter/tix.py Lib/turtle.py Lib/unittest/case.py Lib/unittest/loader.py Lib/unittest/main.py Lib/unittest/suite.py Lib/unittest/test/test_discovery.py Lib/unittest/test/test_program.py Lib/unittest/test/test_runner.py Lib/unittest/test/test_suite.py Lib/urllib/request.py Lib/xmlrpc/client.py Lib/xmlrpc/server.py Misc/NEWS Modules/_dbmmodule.c Modules/_gdbmmodule.c Modules/_io/_iomodule.c Modules/_io/_iomodule.h Modules/_io/bufferedio.c Modules/_io/bytesio.c Modules/_io/fileio.c Modules/_io/iobase.c Modules/_io/stringio.c Modules/_io/textio.c Modules/_threadmodule.c Modules/datetimemodule.c Modules/grpmodule.c Modules/posixmodule.c Modules/pwdmodule.c Modules/signalmodule.c Modules/spwdmodule.c Modules/zlibmodule.c Objects/codeobject.c Objects/longobject.c Objects/moduleobject.c PC/os2emx/python27.def PC/winreg.c Python/errors.c Python/pythonrun.c Message-ID: <20100510211958.8F13FEE9CC@mail.python.org> Author: jeffrey.yasskin Date: Mon May 10 23:19:57 2010 New Revision: 81062 Log: Merged revisions 80885,80887-80893,80897,80900,80902,80904-80905,80910,80919,80921,80923,80925,80928,80933,80936,80938,80940,80947-80950,80955,80959,80962,80968,80971,80973,80975,80979,80981,80983,80989,80992-80993,80999,81001,81003,81005-81006,81009-81010,81014,81016-81017,81019,81021,81023-81024,81028 via svnmerge from svn+ssh://pythondev at svn.python.org/python/branches/py3k ................ r80885 | victor.stinner | 2010-05-06 15:05:07 -0700 (Thu, 06 May 2010) | 7 lines Issue #8603: Create a bytes version of os.environ for Unix Create os.environb mapping and os.getenvb() function, os.unsetenv() encodes str argument to the file system encoding with the surrogateescape error handler (instead of utf8/strict) and accepts bytes, and posix.environ keys and values are bytes. ................ r80887 | benjamin.peterson | 2010-05-06 15:09:03 -0700 (Thu, 06 May 2010) | 1 line versionadded for environb ................ r80888 | benjamin.peterson | 2010-05-06 15:13:11 -0700 (Thu, 06 May 2010) | 1 line spacing and another versionadded ................ r80889 | victor.stinner | 2010-05-06 15:19:30 -0700 (Thu, 06 May 2010) | 2 lines Fix test_posix (regression introduced by r80885) ................ r80890 | benjamin.peterson | 2010-05-06 15:23:58 -0700 (Thu, 06 May 2010) | 1 line use concise skipping ................ r80891 | benjamin.peterson | 2010-05-06 15:25:42 -0700 (Thu, 06 May 2010) | 1 line wrap long lines ................ r80892 | benjamin.peterson | 2010-05-06 15:26:31 -0700 (Thu, 06 May 2010) | 1 line self.skip -> self.skipTest ................ r80893 | benjamin.peterson | 2010-05-06 15:29:53 -0700 (Thu, 06 May 2010) | 1 line rephrase ................ r80897 | benjamin.peterson | 2010-05-06 16:03:05 -0700 (Thu, 06 May 2010) | 13 lines Merged revisions 80894,80896 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r80894 | benjamin.peterson | 2010-05-06 17:33:46 -0500 (Thu, 06 May 2010) | 1 line Availability gets its own line ........ r80896 | benjamin.peterson | 2010-05-06 17:49:28 -0500 (Thu, 06 May 2010) | 1 line ensure that availability information is on its own line at the end of the function docs ........ ................ r80900 | victor.stinner | 2010-05-06 17:41:18 -0700 (Thu, 06 May 2010) | 4 lines code_repr(): use %U to format the filename Avoid useless unicode decoding/recoding of the filename. ................ r80902 | victor.stinner | 2010-05-06 17:50:12 -0700 (Thu, 06 May 2010) | 4 lines module_repr(): use %U to format the file name Avoid useless encode/decode of the filename ................ r80904 | victor.stinner | 2010-05-06 17:54:14 -0700 (Thu, 06 May 2010) | 2 lines Fix test_os: os.environb doesn't exist on Windows ................ r80905 | victor.stinner | 2010-05-06 17:57:12 -0700 (Thu, 06 May 2010) | 4 lines regrtest.py: disable replace_stdout() on Windows until it is fixed See issue #8533 (problem with newlines on Windows). ................ r80910 | senthil.kumaran | 2010-05-06 21:19:23 -0700 (Thu, 06 May 2010) | 9 lines Merged revisions 80908 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r80908 | senthil.kumaran | 2010-05-07 09:37:29 +0530 (Fri, 07 May 2010) | 3 lines Testsuite for RFC3986 based parsing scenario. Related Issue1462525. ........ ................ r80919 | michael.foord | 2010-05-07 08:35:24 -0700 (Fri, 07 May 2010) | 9 lines Merged revisions 80918 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r80918 | michael.foord | 2010-05-07 17:34:08 +0200 (Fri, 07 May 2010) | 1 line Adding a test for unittest test discovery with dotted path name. ........ ................ r80921 | michael.foord | 2010-05-07 09:00:30 -0700 (Fri, 07 May 2010) | 9 lines Merged revisions 80920 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r80920 | michael.foord | 2010-05-07 17:52:05 +0200 (Fri, 07 May 2010) | 1 line Adding tests for unittest command line handling of buffer, catchbreak and failfast. ........ ................ r80923 | victor.stinner | 2010-05-07 09:34:53 -0700 (Fri, 07 May 2010) | 3 lines Replace PyUnicode_Decode(buf, strlen(buf), Py_FileSystemDefaultEncoding, "surrogateescape") by PyUnicode_DecodeFSDefault(val). ................ r80925 | benjamin.peterson | 2010-05-07 09:42:51 -0700 (Fri, 07 May 2010) | 1 line correct call ................ r80928 | antoine.pitrou | 2010-05-07 10:04:02 -0700 (Fri, 07 May 2010) | 11 lines Merged revisions 80926 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r80926 | antoine.pitrou | 2010-05-07 18:50:34 +0200 (ven., 07 mai 2010) | 5 lines Issue #8571: Fix an internal error when compressing or decompressing a chunk larger than 1GB with the zlib module's compressor and decompressor objects. ........ ................ r80933 | michael.foord | 2010-05-07 11:18:14 -0700 (Fri, 07 May 2010) | 9 lines Merged revisions 80932 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r80932 | michael.foord | 2010-05-07 20:16:19 +0200 (Fri, 07 May 2010) | 1 line Issue 8547 - detecting and reporting that modules have been imported from the wrong location under test discovery. ........ ................ r80936 | benjamin.peterson | 2010-05-07 12:10:11 -0700 (Fri, 07 May 2010) | 76 lines Merged revisions 80934 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ................ r80934 | benjamin.peterson | 2010-05-07 13:58:23 -0500 (Fri, 07 May 2010) | 69 lines Merged revisions 79911,79916-79917,80018,80418,80572-80573,80635-80639,80668,80922 via svnmerge from svn+ssh://pythondev at svn.python.org/sandbox/trunk/2to3/lib2to3 ........ r79911 | benjamin.peterson | 2010-04-09 15:38:53 -0500 (Fri, 09 Apr 2010) | 1 line use absolute import ........ r79916 | benjamin.peterson | 2010-04-09 16:05:21 -0500 (Fri, 09 Apr 2010) | 1 line generalize detection of __future__ imports and attach them to the tree ........ r79917 | benjamin.peterson | 2010-04-09 16:11:44 -0500 (Fri, 09 Apr 2010) | 1 line don't try to 'fix' relative imports when absolute_import is enabled #8858 ........ r80018 | benjamin.peterson | 2010-04-12 16:12:12 -0500 (Mon, 12 Apr 2010) | 4 lines prevent diffs from being mangled is multiprocess mode #6409 Patch by George Boutsioukis. ........ r80418 | benjamin.peterson | 2010-04-23 16:00:03 -0500 (Fri, 23 Apr 2010) | 1 line remove unhelpful description ........ r80572 | benjamin.peterson | 2010-04-27 20:33:54 -0500 (Tue, 27 Apr 2010) | 1 line use unicode literals ........ r80573 | jeffrey.yasskin | 2010-04-27 23:08:27 -0500 (Tue, 27 Apr 2010) | 6 lines Don't transform imports that are already relative. 2to3 turned from . import refactor into from .. import refactor which broke the transformation of 2to3 itself. ........ r80635 | benjamin.peterson | 2010-04-29 16:02:23 -0500 (Thu, 29 Apr 2010) | 1 line remove imports ........ r80636 | benjamin.peterson | 2010-04-29 16:02:41 -0500 (Thu, 29 Apr 2010) | 1 line unicode literal ........ r80637 | benjamin.peterson | 2010-04-29 16:03:42 -0500 (Thu, 29 Apr 2010) | 1 line must pass a string to Number ........ r80638 | benjamin.peterson | 2010-04-29 16:05:34 -0500 (Thu, 29 Apr 2010) | 1 line unicode literals ........ r80639 | benjamin.peterson | 2010-04-29 16:06:09 -0500 (Thu, 29 Apr 2010) | 1 line pass string to Number ........ r80668 | jeffrey.yasskin | 2010-04-30 18:02:47 -0500 (Fri, 30 Apr 2010) | 4 lines Make 2to3 run under Python 2.5 so that the benchmark suite at http://hg.python.org/benchmarks/ can use it and still run on implementations that haven't gotten to 2.6 yet. Fixes issue 8566. ........ r80922 | benjamin.peterson | 2010-05-07 11:06:25 -0500 (Fri, 07 May 2010) | 1 line prevent xrange transformation from wrapping range calls it produces in list ........ ................ ................ r80938 | benjamin.peterson | 2010-05-07 13:21:26 -0700 (Fri, 07 May 2010) | 1 line alias PyUnicode_CompareWithASCII ................ r80940 | benjamin.peterson | 2010-05-07 13:47:43 -0700 (Fri, 07 May 2010) | 9 lines Merged revisions 80939 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r80939 | benjamin.peterson | 2010-05-07 15:45:07 -0500 (Fri, 07 May 2010) | 1 line revert r80932; it breaks windows ........ ................ r80947 | michael.foord | 2010-05-07 16:42:40 -0700 (Fri, 07 May 2010) | 9 lines Merged revisions 80946 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r80946 | michael.foord | 2010-05-08 01:39:38 +0200 (Sat, 08 May 2010) | 1 line Issue 8547 - detecting and reporting that modules have been imported from the wrong location under test discovery. ........ ................ r80948 | victor.stinner | 2010-05-07 17:07:07 -0700 (Fri, 07 May 2010) | 2 lines err_input(): don't encode/decode the unicode message ................ r80949 | victor.stinner | 2010-05-07 17:35:33 -0700 (Fri, 07 May 2010) | 3 lines PyErr_SetFromErrnoWithFilename() decodes the filename using PyUnicode_DecodeFSDefault() instead of PyUnicode_FromString() ................ r80950 | victor.stinner | 2010-05-07 17:36:42 -0700 (Fri, 07 May 2010) | 5 lines posix_error_with_allocated_filename() decodes the filename with PyUnicode_DecodeFSDefaultAndSize() and call PyErr_SetFromErrnoWithFilenameObject() instead of PyErr_SetFromErrnoWithFilename() ................ r80955 | senthil.kumaran | 2010-05-07 20:29:09 -0700 (Fri, 07 May 2010) | 9 lines Merged revisions 80953 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r80953 | senthil.kumaran | 2010-05-08 08:41:50 +0530 (Sat, 08 May 2010) | 3 lines Fix Issue8656 - urllib2 mangles file://-scheme URLs ........ ................ r80959 | senthil.kumaran | 2010-05-07 22:12:05 -0700 (Fri, 07 May 2010) | 9 lines Merged revisions 80957 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r80957 | senthil.kumaran | 2010-05-08 10:30:11 +0530 (Sat, 08 May 2010) | 2 lines Fixing the errors trigerred in test_urllib2net. Related to issue8656. ........ ................ r80962 | mark.dickinson | 2010-05-08 01:03:09 -0700 (Sat, 08 May 2010) | 9 lines Merged revisions 80961 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r80961 | mark.dickinson | 2010-05-08 09:01:19 +0100 (Sat, 08 May 2010) | 2 lines Issue #8659: Remove redundant ABS calls. Thanks Daniel Stutzbach. ........ ................ r80968 | ronald.oussoren | 2010-05-08 03:49:43 -0700 (Sat, 08 May 2010) | 11 lines Merged revisions 80967 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r80967 | ronald.oussoren | 2010-05-08 12:29:06 +0200 (Sat, 08 May 2010) | 4 lines Issue #8084: ensure that the --user directory conforms to platforms standars on OSX when using a python framework. ........ ................ r80971 | victor.stinner | 2010-05-08 04:10:09 -0700 (Sat, 08 May 2010) | 3 lines Issue #8514: Add os.fsencode() function (Unix only): encode a string to bytes for use in the file system, environment variables or the command line. ................ r80973 | matthias.klose | 2010-05-08 04:12:56 -0700 (Sat, 08 May 2010) | 27 lines Blocked revisions 80964-80966,80969-80970 via svnmerge ........ r80964 | matthias.klose | 2010-05-08 12:00:28 +0200 (Sa, 08 Mai 2010) | 2 lines - Issue #8510: Update to autoconf2.65. ........ r80965 | matthias.klose | 2010-05-08 12:14:46 +0200 (Sa, 08 Mai 2010) | 2 lines - configure.in: Replace AC_HELP_STRING with AS_HELP_STRING ........ r80966 | matthias.klose | 2010-05-08 12:17:27 +0200 (Sa, 08 Mai 2010) | 2 lines configure.in: s/AC_AIX/AC_USE_SYSTEM_EXTENSIONS/ ........ r80969 | matthias.klose | 2010-05-08 13:01:39 +0200 (Sa, 08 Mai 2010) | 3 lines configure.in: convert all obsolete AC_TRY_* macros to AC_*_IFELSE, only whitespace changes in generated configure (diff -uEwB). ........ r80970 | matthias.klose | 2010-05-08 13:04:18 +0200 (Sa, 08 Mai 2010) | 4 lines configure.in: Avoid autoconf warning: Assume C89 semantics that RETSIGTYPE is always void (issue #8510). pyconfig.h: Regenerate ........ ................ r80975 | michael.foord | 2010-05-08 06:23:31 -0700 (Sat, 08 May 2010) | 9 lines Merged revisions 80974 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r80974 | michael.foord | 2010-05-08 15:20:07 +0200 (Sat, 08 May 2010) | 1 line Issue 7780. Adding a test for unittest test discovery from a dotted path. ........ ................ r80979 | mark.dickinson | 2010-05-08 07:35:02 -0700 (Sat, 08 May 2010) | 6 lines Issue #8644: Improve accuracy of timedelta.total_seconds, by doing intermediate computations with integer arithmetic instead of floating point. td.total_seconds() now agrees with td / timedelta(seconds = 1). Thanks Alexander Belopolsky for the patch. ................ r80981 | michael.foord | 2010-05-08 08:13:42 -0700 (Sat, 08 May 2010) | 9 lines Merged revisions 80980 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r80980 | michael.foord | 2010-05-08 17:09:37 +0200 (Sat, 08 May 2010) | 1 line Documenting test discovery from package name and potential problems with test discovery importing tests from the wrong location. Issue 7780 and issue 8547. ........ ................ r80983 | benjamin.peterson | 2010-05-08 08:26:30 -0700 (Sat, 08 May 2010) | 1 line replace long with int ................ r80989 | benjamin.peterson | 2010-05-08 08:51:23 -0700 (Sat, 08 May 2010) | 13 lines Merged revisions 80986-80987 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r80986 | benjamin.peterson | 2010-05-08 10:41:44 -0500 (Sat, 08 May 2010) | 1 line r80967 introduced a new scheme ........ r80987 | benjamin.peterson | 2010-05-08 10:42:29 -0500 (Sat, 08 May 2010) | 1 line add underscore ........ ................ r80992 | michael.foord | 2010-05-08 09:46:14 -0700 (Sat, 08 May 2010) | 9 lines Merged revisions 80990 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r80990 | michael.foord | 2010-05-08 18:40:52 +0200 (Sat, 08 May 2010) | 1 line Updating documentation and adding docstrings to unittest.TestCase.assertRegexpMatches and assertNotRegexpMatches. Issue 8038. ........ ................ r80993 | benjamin.peterson | 2010-05-08 09:51:16 -0700 (Sat, 08 May 2010) | 9 lines Merged revisions 80991 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r80991 | benjamin.peterson | 2010-05-08 11:44:52 -0500 (Sat, 08 May 2010) | 1 line run and fix enumerate start test cases #8636 ........ ................ r80999 | michael.foord | 2010-05-08 10:10:05 -0700 (Sat, 08 May 2010) | 9 lines Merged revisions 80997 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r80997 | michael.foord | 2010-05-08 19:06:25 +0200 (Sat, 08 May 2010) | 1 line unittest: issue 8301. Adding functions to test suites no longer crashes. ........ ................ r81001 | gregory.p.smith | 2010-05-08 11:05:46 -0700 (Sat, 08 May 2010) | 2 lines Adds a unittest for the internal os._execvpe function. ................ r81003 | benjamin.peterson | 2010-05-08 11:57:34 -0700 (Sat, 08 May 2010) | 16 lines Blocked revisions 80996,80998,81002 via svnmerge ........ r80996 | benjamin.peterson | 2010-05-08 12:05:19 -0500 (Sat, 08 May 2010) | 1 line update pydoc-topics ........ r80998 | benjamin.peterson | 2010-05-08 12:08:17 -0500 (Sat, 08 May 2010) | 1 line bump version to 2.7 beta 2 ........ r81002 | benjamin.peterson | 2010-05-08 13:53:42 -0500 (Sat, 08 May 2010) | 1 line towards 2.7 release candidate 1 ........ ................ r81005 | benjamin.peterson | 2010-05-08 12:52:21 -0700 (Sat, 08 May 2010) | 4 lines Create __pycache__ dir when the pyc path is explicitly given Patch from Arfrever Frehtes Taifersar Arahesis. ................ r81006 | benjamin.peterson | 2010-05-08 12:52:49 -0700 (Sat, 08 May 2010) | 1 line add news for r81005 ................ r81009 | benjamin.peterson | 2010-05-08 14:03:44 -0700 (Sat, 08 May 2010) | 8 lines Blocked revisions 81008 via svnmerge ........ r81008 | benjamin.peterson | 2010-05-08 15:59:42 -0500 (Sat, 08 May 2010) | 1 line remove svn:mergeinfo property ........ ................ r81010 | benjamin.peterson | 2010-05-08 14:05:35 -0700 (Sat, 08 May 2010) | 1 line remove svn:mergeinfo ................ r81014 | victor.stinner | 2010-05-08 20:15:33 -0700 (Sat, 08 May 2010) | 2 lines Write tests for the new function os.fsencode() ................ r81016 | jean-paul.calderone | 2010-05-08 20:18:57 -0700 (Sat, 08 May 2010) | 9 lines Merged revisions 81007 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r81007 | jean-paul.calderone | 2010-05-08 16:06:02 -0400 (Sat, 08 May 2010) | 1 line Skip signal handler re-installation if it is not necessary. Issue 8354. ........ ................ r81017 | benjamin.peterson | 2010-05-08 20:22:58 -0700 (Sat, 08 May 2010) | 1 line make condition more specific ................ r81019 | gregory.p.smith | 2010-05-08 20:36:42 -0700 (Sat, 08 May 2010) | 3 lines Replace /s with os.sep in the new internal_execvpe test. Hopefully fixes this test on windows. ................ r81021 | mark.dickinson | 2010-05-09 02:30:53 -0700 (Sun, 09 May 2010) | 9 lines Blocked revisions 81020 via svnmerge ........ r81020 | mark.dickinson | 2010-05-09 10:30:06 +0100 (Sun, 09 May 2010) | 3 lines Issue #8644: Improve accuracy of timedelta.total_seconds method. (Backport of r80979 to py3k.) Thanks Alexander Belopolsky. ........ ................ r81023 | michael.foord | 2010-05-09 02:59:35 -0700 (Sun, 09 May 2010) | 9 lines Merged revisions 81022 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r81022 | michael.foord | 2010-05-09 11:58:25 +0200 (Sun, 09 May 2010) | 1 line Adding a test for unittest.BaseTestSuite. ........ ................ r81024 | mark.dickinson | 2010-05-09 05:16:29 -0700 (Sun, 09 May 2010) | 1 line Fix test_urllib2 failure on OS X. ................ r81028 | eric.smith | 2010-05-09 07:09:25 -0700 (Sun, 09 May 2010) | 8 lines Blocked revisions 81026 via svnmerge ........ r81026 | eric.smith | 2010-05-09 10:04:59 -0400 (Sun, 09 May 2010) | 1 line Issue 8671: Whitespace fix. ........ ................ Modified: python/branches/py3k-jit/ (props changed) python/branches/py3k-jit/Doc/library/_dummy_thread.rst (props changed) python/branches/py3k-jit/Doc/library/_thread.rst (props changed) python/branches/py3k-jit/Doc/library/datetime.rst python/branches/py3k-jit/Doc/library/html.parser.rst (props changed) python/branches/py3k-jit/Doc/library/http.client.rst (props changed) python/branches/py3k-jit/Doc/library/http.cookiejar.rst (props changed) python/branches/py3k-jit/Doc/library/http.cookies.rst (props changed) python/branches/py3k-jit/Doc/library/http.server.rst (props changed) python/branches/py3k-jit/Doc/library/os.path.rst python/branches/py3k-jit/Doc/library/os.rst python/branches/py3k-jit/Doc/library/posix.rst python/branches/py3k-jit/Doc/library/tkinter.scrolledtext.rst (props changed) python/branches/py3k-jit/Doc/library/tkinter.tix.rst (props changed) python/branches/py3k-jit/Doc/library/tkinter.ttk.rst (props changed) python/branches/py3k-jit/Doc/library/turtle.rst (props changed) python/branches/py3k-jit/Doc/library/unittest.rst python/branches/py3k-jit/Doc/library/weakref.rst python/branches/py3k-jit/Doc/library/winreg.rst (props changed) python/branches/py3k-jit/Doc/library/xmlrpc.client.rst (props changed) python/branches/py3k-jit/Doc/library/xmlrpc.server.rst (props changed) python/branches/py3k-jit/Include/unicodeobject.h python/branches/py3k-jit/Lib/_dummy_thread.py (props changed) python/branches/py3k-jit/Lib/compileall.py python/branches/py3k-jit/Lib/dbm/dumb.py (props changed) python/branches/py3k-jit/Lib/email/test/test_email_codecs.py (props changed) python/branches/py3k-jit/Lib/http/client.py (props changed) python/branches/py3k-jit/Lib/http/cookiejar.py (props changed) python/branches/py3k-jit/Lib/http/cookies.py (props changed) python/branches/py3k-jit/Lib/http/server.py (props changed) python/branches/py3k-jit/Lib/lib2to3/fixes/fix_import.py python/branches/py3k-jit/Lib/lib2to3/fixes/fix_operator.py python/branches/py3k-jit/Lib/lib2to3/fixes/fix_reduce.py python/branches/py3k-jit/Lib/lib2to3/fixes/fix_tuple_params.py python/branches/py3k-jit/Lib/lib2to3/fixes/fix_xrange.py python/branches/py3k-jit/Lib/lib2to3/main.py python/branches/py3k-jit/Lib/lib2to3/pgen2/tokenize.py python/branches/py3k-jit/Lib/lib2to3/pytree.py python/branches/py3k-jit/Lib/lib2to3/refactor.py python/branches/py3k-jit/Lib/lib2to3/tests/test_fixers.py python/branches/py3k-jit/Lib/lib2to3/tests/test_parser.py python/branches/py3k-jit/Lib/lib2to3/tests/test_pytree.py python/branches/py3k-jit/Lib/lib2to3/tests/test_refactor.py python/branches/py3k-jit/Lib/os.py python/branches/py3k-jit/Lib/py_compile.py python/branches/py3k-jit/Lib/site.py python/branches/py3k-jit/Lib/subprocess.py python/branches/py3k-jit/Lib/sysconfig.py python/branches/py3k-jit/Lib/test/regrtest.py python/branches/py3k-jit/Lib/test/test_datetime.py python/branches/py3k-jit/Lib/test/test_dbm.py (props changed) python/branches/py3k-jit/Lib/test/test_dbm_dumb.py (props changed) python/branches/py3k-jit/Lib/test/test_dbm_gnu.py (props changed) python/branches/py3k-jit/Lib/test/test_dbm_ndbm.py (props changed) python/branches/py3k-jit/Lib/test/test_enumerate.py python/branches/py3k-jit/Lib/test/test_http_cookiejar.py (props changed) python/branches/py3k-jit/Lib/test/test_http_cookies.py (props changed) python/branches/py3k-jit/Lib/test/test_os.py python/branches/py3k-jit/Lib/test/test_posix.py python/branches/py3k-jit/Lib/test/test_signal.py python/branches/py3k-jit/Lib/test/test_subprocess.py python/branches/py3k-jit/Lib/test/test_sysconfig.py python/branches/py3k-jit/Lib/test/test_ttk_guionly.py (props changed) python/branches/py3k-jit/Lib/test/test_ttk_textonly.py (props changed) python/branches/py3k-jit/Lib/test/test_urllib2.py python/branches/py3k-jit/Lib/test/test_urlparse.py python/branches/py3k-jit/Lib/test/test_zlib.py python/branches/py3k-jit/Lib/tkinter/__init__.py (props changed) python/branches/py3k-jit/Lib/tkinter/_fix.py (props changed) python/branches/py3k-jit/Lib/tkinter/colorchooser.py (props changed) python/branches/py3k-jit/Lib/tkinter/commondialog.py (props changed) python/branches/py3k-jit/Lib/tkinter/constants.py (props changed) python/branches/py3k-jit/Lib/tkinter/dialog.py (props changed) python/branches/py3k-jit/Lib/tkinter/dnd.py (props changed) python/branches/py3k-jit/Lib/tkinter/filedialog.py (props changed) python/branches/py3k-jit/Lib/tkinter/font.py (props changed) python/branches/py3k-jit/Lib/tkinter/messagebox.py (props changed) python/branches/py3k-jit/Lib/tkinter/scrolledtext.py (props changed) python/branches/py3k-jit/Lib/tkinter/simpledialog.py (props changed) python/branches/py3k-jit/Lib/tkinter/test/support.py (props changed) python/branches/py3k-jit/Lib/tkinter/tix.py (props changed) python/branches/py3k-jit/Lib/turtle.py (props changed) python/branches/py3k-jit/Lib/unittest/case.py python/branches/py3k-jit/Lib/unittest/loader.py python/branches/py3k-jit/Lib/unittest/main.py python/branches/py3k-jit/Lib/unittest/suite.py python/branches/py3k-jit/Lib/unittest/test/test_discovery.py python/branches/py3k-jit/Lib/unittest/test/test_program.py python/branches/py3k-jit/Lib/unittest/test/test_runner.py python/branches/py3k-jit/Lib/unittest/test/test_suite.py python/branches/py3k-jit/Lib/urllib/request.py python/branches/py3k-jit/Lib/xmlrpc/client.py (props changed) python/branches/py3k-jit/Lib/xmlrpc/server.py (props changed) python/branches/py3k-jit/Misc/NEWS python/branches/py3k-jit/Modules/_dbmmodule.c (props changed) python/branches/py3k-jit/Modules/_gdbmmodule.c (props changed) python/branches/py3k-jit/Modules/_io/_iomodule.c (props changed) python/branches/py3k-jit/Modules/_io/_iomodule.h (props changed) python/branches/py3k-jit/Modules/_io/bufferedio.c (props changed) python/branches/py3k-jit/Modules/_io/bytesio.c (props changed) python/branches/py3k-jit/Modules/_io/fileio.c (props changed) python/branches/py3k-jit/Modules/_io/iobase.c (props changed) python/branches/py3k-jit/Modules/_io/stringio.c (props changed) python/branches/py3k-jit/Modules/_io/textio.c (props changed) python/branches/py3k-jit/Modules/_threadmodule.c (props changed) python/branches/py3k-jit/Modules/datetimemodule.c python/branches/py3k-jit/Modules/grpmodule.c python/branches/py3k-jit/Modules/posixmodule.c python/branches/py3k-jit/Modules/pwdmodule.c python/branches/py3k-jit/Modules/signalmodule.c python/branches/py3k-jit/Modules/spwdmodule.c python/branches/py3k-jit/Modules/zlibmodule.c python/branches/py3k-jit/Objects/codeobject.c python/branches/py3k-jit/Objects/longobject.c python/branches/py3k-jit/Objects/moduleobject.c python/branches/py3k-jit/PC/os2emx/python27.def (props changed) python/branches/py3k-jit/PC/winreg.c (props changed) python/branches/py3k-jit/Python/errors.c python/branches/py3k-jit/Python/pythonrun.c Modified: python/branches/py3k-jit/Doc/library/datetime.rst ============================================================================== --- python/branches/py3k-jit/Doc/library/datetime.rst (original) +++ python/branches/py3k-jit/Doc/library/datetime.rst Mon May 10 23:19:57 2010 @@ -287,7 +287,10 @@ .. method:: timedelta.total_seconds() Return the total number of seconds contained in the duration. Equivalent to - ``td.microseconds / 1000000 + td.seconds + td.days * 24 * 3600``. + ``td / timedelta(seconds=1)``. + + Note that for very large time intervals (greater than 270 years on + most platforms) this method will lose microsecond accuracy. .. versionadded:: 3.2 Modified: python/branches/py3k-jit/Doc/library/os.path.rst ============================================================================== --- python/branches/py3k-jit/Doc/library/os.path.rst (original) +++ python/branches/py3k-jit/Doc/library/os.path.rst Mon May 10 23:19:57 2010 @@ -223,19 +223,24 @@ Return a relative filepath to *path* either from the current directory or from an optional *start* point. - *start* defaults to :attr:`os.curdir`. Availability: Windows, Unix. + *start* defaults to :attr:`os.curdir`. + + Availability: Windows, Unix. .. function:: samefile(path1, path2) Return ``True`` if both pathname arguments refer to the same file or directory (as indicated by device number and i-node number). Raise an exception if a - :func:`os.stat` call on either pathname fails. Availability: Unix. + :func:`os.stat` call on either pathname fails. + + Availability: Unix. .. function:: sameopenfile(fp1, fp2) Return ``True`` if the file descriptors *fp1* and *fp2* refer to the same file. + Availability: Unix. @@ -244,7 +249,9 @@ Return ``True`` if the stat tuples *stat1* and *stat2* refer to the same file. These structures may have been returned by :func:`fstat`, :func:`lstat`, or :func:`stat`. This function implements the underlying comparison used by - :func:`samefile` and :func:`sameopenfile`. Availability: Unix. + :func:`samefile` and :func:`sameopenfile`. + + Availability: Unix. .. function:: split(path) @@ -293,7 +300,9 @@ Split the pathname *path* into a pair ``(unc, rest)`` so that *unc* is the UNC mount point (such as ``r'\\host\mount'``), if present, and *rest* the rest of the path (such as ``r'\path\file.ext'``). For paths containing drive letters, - *unc* will always be the empty string. Availability: Windows. + *unc* will always be the empty string. + + Availability: Windows. .. data:: supports_unicode_filenames Modified: python/branches/py3k-jit/Doc/library/os.rst ============================================================================== --- python/branches/py3k-jit/Doc/library/os.rst (original) +++ python/branches/py3k-jit/Doc/library/os.rst Mon May 10 23:19:57 2010 @@ -41,6 +41,9 @@ * If not separately noted, all functions that claim "Availability: Unix" are supported on Mac OS X, which builds on a Unix core. +.. Availability notes get their own line and occur at the end of the function +.. documentation. + .. note:: All functions in this module raise :exc:`OSError` in the case of invalid or @@ -107,6 +110,10 @@ to modify the environment as well as query the environment. :func:`putenv` will be called automatically when the mapping is modified. + On Unix, keys and values use :func:`sys.getfilesystemencoding` and + ``'surrogateescape'`` error handler. Use :data:`environb` if you would like + to use a different encoding. + .. note:: Calling :func:`putenv` directly does not change ``os.environ``, so it's better @@ -128,6 +135,18 @@ one of the :meth:`pop` or :meth:`clear` methods is called. +.. data:: environb + + Bytes version of :data:`environ`: a mapping object representing the + environment as byte strings. :data:`environ` and :data:`environb` are + synchronized (modify :data:`environb` updates :data:`environ`, and vice + versa). + + Availability: Unix. + + .. versionadded:: 3.2 + + .. function:: chdir(path) fchdir(fd) getcwd() @@ -136,6 +155,17 @@ These functions are described in :ref:`os-file-dir`. +.. function:: fsencode(value) + + Encode *value* to bytes for use in the file system, environment variables or + the command line. Uses :func:`sys.getfilesystemencoding` and + ``'surrogateescape'`` error handler for strings and returns bytes unchanged. + + Availability: Unix. + + .. versionadded:: 3.2 + + .. function:: get_exec_path(env=None) Returns the list of directories that will be searched for a named @@ -150,33 +180,40 @@ .. function:: ctermid() Return the filename corresponding to the controlling terminal of the process. + Availability: Unix. .. function:: getegid() Return the effective group id of the current process. This corresponds to the - "set id" bit on the file being executed in the current process. Availability: - Unix. + "set id" bit on the file being executed in the current process. + + Availability: Unix. .. function:: geteuid() .. index:: single: user; effective id - Return the current process's effective user id. Availability: Unix. + Return the current process's effective user id. + + Availability: Unix. .. function:: getgid() .. index:: single: process; group - Return the real group id of the current process. Availability: Unix. + Return the real group id of the current process. + + Availability: Unix. .. function:: getgroups() Return list of supplemental group ids associated with the current process. + Availability: Unix. @@ -184,7 +221,9 @@ Call the system initgroups() to initialize the group access list with all of the groups of which the specified username is a member, plus the specified - group id. Availability: Unix. + group id. + + Availability: Unix. .. versionadded:: 3.2 @@ -195,40 +234,51 @@ process. For most purposes, it is more useful to use the environment variable :envvar:`LOGNAME` to find out who the user is, or ``pwd.getpwuid(os.getuid())[0]`` to get the login name of the currently - effective user id. Availability: Unix. + effective user id. + + Availability: Unix. .. function:: getpgid(pid) Return the process group id of the process with process id *pid*. If *pid* is 0, - the process group id of the current process is returned. Availability: Unix. + the process group id of the current process is returned. + Availability: Unix. .. function:: getpgrp() .. index:: single: process; group - Return the id of the current process group. Availability: Unix. + Return the id of the current process group. + + Availability: Unix. .. function:: getpid() .. index:: single: process; id - Return the current process id. Availability: Unix, Windows. + Return the current process id. + + Availability: Unix, Windows. .. function:: getppid() .. index:: single: process; id of parent - Return the parent's process id. Availability: Unix. + Return the parent's process id. + + Availability: Unix. .. function:: getresuid() Return a tuple (ruid, euid, suid) denoting the current process's - real, effective, and saved user ids. Availability: Unix. + real, effective, and saved user ids. + + Availability: Unix. .. versionadded:: 3.2 @@ -236,7 +286,9 @@ .. function:: getresgid() Return a tuple (rgid, egid, sgid) denoting the current process's - real, effective, and saved user ids. Availability: Unix. + real, effective, and saved user ids. + + Availability: Unix. .. versionadded:: 3.2 @@ -245,13 +297,31 @@ .. index:: single: user; id - Return the current process's user id. Availability: Unix. + Return the current process's user id. + + Availability: Unix. .. function:: getenv(key, default=None) Return the value of the environment variable *key* if it exists, or - *default* if it doesn't. Availability: most flavors of Unix, Windows. + *default* if it doesn't. *key*, *default* and the result are str. + + On Unix, keys and values are decoded with :func:`sys.getfilesystemencoding` + and ``'surrogateescape'`` error handler. Use :func:`os.getenvb` if you + would like to use a different encoding. + + Availability: most flavors of Unix, Windows. + + +.. function:: getenvb(key, default=None) + + Return the value of the environment variable *key* if it exists, or + *default* if it doesn't. *key*, *default* and the result are bytes. + + Availability: most flavors of Unix. + + .. versionadded:: 3.2 .. function:: putenv(key, value) @@ -260,8 +330,9 @@ Set the environment variable named *key* to the string *value*. Such changes to the environment affect subprocesses started with :func:`os.system`, - :func:`popen` or :func:`fork` and :func:`execv`. Availability: most flavors of - Unix, Windows. + :func:`popen` or :func:`fork` and :func:`execv`. + + Availability: most flavors of Unix, Windows. .. note:: @@ -276,17 +347,23 @@ .. function:: setegid(egid) - Set the current process's effective group id. Availability: Unix. + Set the current process's effective group id. + + Availability: Unix. .. function:: seteuid(euid) - Set the current process's effective user id. Availability: Unix. + Set the current process's effective user id. + + Availability: Unix. .. function:: setgid(gid) - Set the current process' group id. Availability: Unix. + Set the current process' group id. + + Availability: Unix. .. function:: setgroups(groups) @@ -294,6 +371,7 @@ Set the list of supplemental group ids associated with the current process to *groups*. *groups* must be a sequence, and each element must be an integer identifying a group. This operation is typically available only to the superuser. + Availability: Unix. @@ -301,6 +379,7 @@ Call the system call :cfunc:`setpgrp` or :cfunc:`setpgrp(0, 0)` depending on which version is implemented (if any). See the Unix manual for the semantics. + Availability: Unix. @@ -308,17 +387,22 @@ Call the system call :cfunc:`setpgid` to set the process group id of the process with id *pid* to the process group with id *pgrp*. See the Unix manual - for the semantics. Availability: Unix. + for the semantics. + + Availability: Unix. .. function:: setregid(rgid, egid) - Set the current process's real and effective group ids. Availability: Unix. + Set the current process's real and effective group ids. + + Availability: Unix. .. function:: setresgid(rgid, egid, sgid) Set the current process's real, effective, and saved group ids. + Availability: Unix. .. versionadded:: 3.2 @@ -327,6 +411,7 @@ .. function:: setresuid(ruid, euid, suid) Set the current process's real, effective, and saved user ids. + Availibility: Unix. .. versionadded:: 3.2 @@ -334,18 +419,22 @@ .. function:: setreuid(ruid, euid) - Set the current process's real and effective user ids. Availability: Unix. + Set the current process's real and effective user ids. + + Availability: Unix. .. function:: getsid(pid) Call the system call :cfunc:`getsid`. See the Unix manual for the semantics. + Availability: Unix. .. function:: setsid() Call the system call :cfunc:`setsid`. See the Unix manual for the semantics. + Availability: Unix. @@ -353,7 +442,9 @@ .. index:: single: user; id, setting - Set the current process's user id. Availability: Unix. + Set the current process's user id. + + Availability: Unix. .. placed in this section since it relates to errno.... a little weak @@ -361,13 +452,16 @@ Return the error message corresponding to the error code in *code*. On platforms where :cfunc:`strerror` returns ``NULL`` when given an unknown - error number, :exc:`ValueError` is raised. Availability: Unix, Windows. + error number, :exc:`ValueError` is raised. + + Availability: Unix, Windows. .. function:: umask(mask) - Set the current numeric umask and return the previous umask. Availability: - Unix, Windows. + Set the current numeric umask and return the previous umask. + + Availability: Unix, Windows. .. function:: uname() @@ -381,8 +475,9 @@ machine)``. Some systems truncate the nodename to 8 characters or to the leading component; a better way to get the hostname is :func:`socket.gethostname` or even - ``socket.gethostbyaddr(socket.gethostname())``. Availability: recent flavors of - Unix. + ``socket.gethostbyaddr(socket.gethostname())``. + + Availability: recent flavors of Unix. .. function:: unsetenv(key) @@ -391,13 +486,15 @@ Unset (delete) the environment variable named *key*. Such changes to the environment affect subprocesses started with :func:`os.system`, :func:`popen` or - :func:`fork` and :func:`execv`. Availability: most flavors of Unix, Windows. + :func:`fork` and :func:`execv`. When :func:`unsetenv` is supported, deletion of items in ``os.environ`` is automatically translated into a corresponding call to :func:`unsetenv`; however, calls to :func:`unsetenv` don't update ``os.environ``, so it is actually preferable to delete items of ``os.environ``. + Availability: most flavors of Unix, Windows. + .. _os-newstreams: @@ -413,7 +510,7 @@ Return an open file object connected to the file descriptor *fd*. The *mode* and *bufsize* arguments have the same meaning as the corresponding arguments to - the built-in :func:`open` function. Availability: Unix, Windows. + the built-in :func:`open` function. When specified, the *mode* argument must start with one of the letters ``'r'``, ``'w'``, or ``'a'``, otherwise a :exc:`ValueError` is raised. @@ -422,6 +519,8 @@ set on the file descriptor (which the :cfunc:`fdopen` implementation already does on most platforms). + Availability: Unix, Windows. + .. _os-fd-ops: @@ -444,7 +543,9 @@ .. function:: close(fd) - Close file descriptor *fd*. Availability: Unix, Windows. + Close file descriptor *fd*. + + Availability: Unix, Windows. .. note:: @@ -457,7 +558,7 @@ .. function:: closerange(fd_low, fd_high) Close all file descriptors from *fd_low* (inclusive) to *fd_high* (exclusive), - ignoring errors. Availability: Unix, Windows. Equivalent to:: + ignoring errors. Equivalent to:: for fd in range(fd_low, fd_high): try: @@ -465,6 +566,8 @@ except OSError: pass + Availability: Unix, Windows. + .. function:: device_encoding(fd) @@ -474,33 +577,40 @@ .. function:: dup(fd) - Return a duplicate of file descriptor *fd*. Availability: Unix, - Windows. + Return a duplicate of file descriptor *fd*. + + Availability: Unix, Windows. .. function:: dup2(fd, fd2) Duplicate file descriptor *fd* to *fd2*, closing the latter first if necessary. + Availability: Unix, Windows. .. function:: fchmod(fd, mode) Change the mode of the file given by *fd* to the numeric *mode*. See the docs - for :func:`chmod` for possible values of *mode*. Availability: Unix. + for :func:`chmod` for possible values of *mode*. + + Availability: Unix. .. function:: fchown(fd, uid, gid) Change the owner and group id of the file given by *fd* to the numeric *uid* and *gid*. To leave one of the ids unchanged, set it to -1. + Availability: Unix. .. function:: fdatasync(fd) Force write of file with filedescriptor *fd* to disk. Does not force update of - metadata. Availability: Unix. + metadata. + + Availability: Unix. .. note:: This function is not available on MacOS. @@ -515,24 +625,28 @@ additional names as well. The names known to the host operating system are given in the ``pathconf_names`` dictionary. For configuration variables not included in that mapping, passing an integer for *name* is also accepted. - Availability: Unix. If *name* is a string and is not known, :exc:`ValueError` is raised. If a specific value for *name* is not supported by the host system, even if it is included in ``pathconf_names``, an :exc:`OSError` is raised with :const:`errno.EINVAL` for the error number. + Availability: Unix. + .. function:: fstat(fd) - Return status for file descriptor *fd*, like :func:`stat`. Availability: - Unix, Windows. + Return status for file descriptor *fd*, like :func:`stat`. + + Availability: Unix, Windows. .. function:: fstatvfs(fd) Return information about the filesystem containing the file associated with file - descriptor *fd*, like :func:`statvfs`. Availability: Unix. + descriptor *fd*, like :func:`statvfs`. + + Availability: Unix. .. function:: fsync(fd) @@ -542,19 +656,25 @@ If you're starting with a Python file object *f*, first do ``f.flush()``, and then do ``os.fsync(f.fileno())``, to ensure that all internal buffers associated - with *f* are written to disk. Availability: Unix, Windows. + with *f* are written to disk. + + Availability: Unix, and Windows. .. function:: ftruncate(fd, length) Truncate the file corresponding to file descriptor *fd*, so that it is at most - *length* bytes in size. Availability: Unix. + *length* bytes in size. + + Availability: Unix. .. function:: isatty(fd) Return ``True`` if the file descriptor *fd* is open and connected to a - tty(-like) device, else ``False``. Availability: Unix. + tty(-like) device, else ``False``. + + Availability: Unix. .. function:: lseek(fd, pos, how) @@ -563,7 +683,9 @@ by *how*: :const:`SEEK_SET` or ``0`` to set the position relative to the beginning of the file; :const:`SEEK_CUR` or ``1`` to set it relative to the current position; :const:`os.SEEK_END` or ``2`` to set it relative to the end of - the file. Availability: Unix, Windows. + the file. + + Availability: Unix, Windows. .. function:: open(file, flags[, mode]) @@ -571,17 +693,19 @@ Open the file *file* and set various flags according to *flags* and possibly its mode according to *mode*. The default *mode* is ``0o777`` (octal), and the current umask value is first masked out. Return the file descriptor for - the newly opened file. Availability: Unix, Windows. + the newly opened file. For a description of the flag and mode values, see the C run-time documentation; flag constants (like :const:`O_RDONLY` and :const:`O_WRONLY`) are defined in this module too (see below). + Availability: Unix, Windows. + .. note:: This function is intended for low-level I/O. For normal usage, use the built-in function :func:`open`, which returns a "file object" with - :meth:`~file.read` and :meth:`~file.write` methods (and many more). To + :meth:`~file.read` and :meth:`~file.wprite` methods (and many more). To wrap a file descriptor in a "file object", use :func:`fdopen`. @@ -591,21 +715,26 @@ Open a new pseudo-terminal pair. Return a pair of file descriptors ``(master, slave)`` for the pty and the tty, respectively. For a (slightly) more portable - approach, use the :mod:`pty` module. Availability: some flavors of - Unix. + approach, use the :mod:`pty` module. + + Availability: some flavors of Unix. .. function:: pipe() Create a pipe. Return a pair of file descriptors ``(r, w)`` usable for reading - and writing, respectively. Availability: Unix, Windows. + and writing, respectively. + + Availability: Unix, Windows. .. function:: read(fd, n) Read at most *n* bytes from file descriptor *fd*. Return a bytestring containing the bytes read. If the end of the file referred to by *fd* has been reached, an - empty bytes object is returned. Availability: Unix, Windows. + empty bytes object is returned. + + Availability: Unix, Windows. .. note:: @@ -619,26 +748,34 @@ .. function:: tcgetpgrp(fd) Return the process group associated with the terminal given by *fd* (an open - file descriptor as returned by :func:`os.open`). Availability: Unix. + file descriptor as returned by :func:`os.open`). + + Availability: Unix. .. function:: tcsetpgrp(fd, pg) Set the process group associated with the terminal given by *fd* (an open file - descriptor as returned by :func:`os.open`) to *pg*. Availability: Unix. + descriptor as returned by :func:`os.open`) to *pg*. + + Availability: Unix. .. function:: ttyname(fd) Return a string which specifies the terminal device associated with file descriptor *fd*. If *fd* is not associated with a terminal device, an - exception is raised. Availability: Unix. + exception is raised. + + Availability: Unix. .. function:: write(fd, str) Write the bytestring in *str* to file descriptor *fd*. Return the number of - bytes actually written. Availability: Unix, Windows. + bytes actually written. + + Availability: Unix, Windows. .. note:: @@ -721,7 +858,9 @@ can be the inclusive OR of one or more of :const:`R_OK`, :const:`W_OK`, and :const:`X_OK` to test permissions. Return :const:`True` if access is allowed, :const:`False` if not. See the Unix man page :manpage:`access(2)` for more - information. Availability: Unix, Windows. + information. + + Availability: Unix, Windows. .. note:: @@ -765,25 +904,31 @@ .. index:: single: directory; changing - Change the current working directory to *path*. Availability: Unix, - Windows. + Change the current working directory to *path*. + + Availability: Unix, Windows. .. function:: fchdir(fd) Change the current working directory to the directory represented by the file descriptor *fd*. The descriptor must refer to an opened directory, not an open - file. Availability: Unix. + file. + + Availability: Unix. .. function:: getcwd() Return a string representing the current working directory. + Availability: Unix, Windows. + .. function:: getcwdb() Return a bytestring representing the current working directory. + Availability: Unix, Windows. @@ -851,32 +996,41 @@ .. function:: chown(path, uid, gid) Change the owner and group id of *path* to the numeric *uid* and *gid*. To leave - one of the ids unchanged, set it to -1. Availability: Unix. + one of the ids unchanged, set it to -1. + + Availability: Unix. .. function:: lchflags(path, flags) Set the flags of *path* to the numeric *flags*, like :func:`chflags`, but do not - follow symbolic links. Availability: Unix. + follow symbolic links. + + Availability: Unix. .. function:: lchmod(path, mode) Change the mode of *path* to the numeric *mode*. If path is a symlink, this affects the symlink rather than the target. See the docs for :func:`chmod` - for possible values of *mode*. Availability: Unix. + for possible values of *mode*. + + Availability: Unix. .. function:: lchown(path, uid, gid) Change the owner and group id of *path* to the numeric *uid* and *gid*. This - function will not follow symbolic links. Availability: Unix. + function will not follow symbolic links. + + Availability: Unix. .. function:: link(source, link_name) - Create a hard link pointing to *source* named *link_name*. Availability: - Unix. + Create a hard link pointing to *source* named *link_name*. + + Availability: Unix. .. function:: listdir(path) @@ -884,11 +1038,12 @@ Return a list containing the names of the entries in the directory given by *path*. The list is in arbitrary order. It does not include the special entries ``'.'`` and ``'..'`` even if they are present in the directory. - Availability: Unix, Windows. This function can be called with a bytes or string argument, and returns filenames of the same datatype. + Availability: Unix, Windows. + .. function:: lstat(path) @@ -901,7 +1056,7 @@ Create a FIFO (a named pipe) named *path* with numeric mode *mode*. The default *mode* is ``0o666`` (octal). The current umask value is first masked - out from the mode. Availability: Unix. + out from the mode. FIFOs are pipes that can be accessed like regular files. FIFOs exist until they are deleted (for example with :func:`os.unlink`). Generally, FIFOs are used as @@ -909,6 +1064,8 @@ FIFO for reading, and the client opens it for writing. Note that :func:`mkfifo` doesn't open the FIFO --- it just creates the rendezvous point. + Availability: Unix. + .. function:: mknod(filename[, mode=0o600[, device]]) @@ -942,11 +1099,13 @@ Create a directory named *path* with numeric mode *mode*. The default *mode* is ``0o777`` (octal). On some systems, *mode* is ignored. Where it is used, - the current umask value is first masked out. Availability: Unix, Windows. + the current umask value is first masked out. It is also possible to create temporary directories; see the :mod:`tempfile` module's :func:`tempfile.mkdtemp` function. + Availability: Unix, Windows. + .. function:: makedirs(path[, mode]) @@ -977,13 +1136,14 @@ additional names as well. The names known to the host operating system are given in the ``pathconf_names`` dictionary. For configuration variables not included in that mapping, passing an integer for *name* is also accepted. - Availability: Unix. If *name* is a string and is not known, :exc:`ValueError` is raised. If a specific value for *name* is not supported by the host system, even if it is included in ``pathconf_names``, an :exc:`OSError` is raised with :const:`errno.EINVAL` for the error number. + Availability: Unix. + .. data:: pathconf_names @@ -1014,8 +1174,9 @@ the :func:`unlink` function documented below. On Windows, attempting to remove a file that is in use causes an exception to be raised; on Unix, the directory entry is removed but the storage allocated to the file is not made - available until the original file is no longer in use. Availability: Unix, - Windows. + available until the original file is no longer in use. + + Availability: Unix, Windows. .. function:: removedirs(path) @@ -1041,7 +1202,9 @@ the renaming will be an atomic operation (this is a POSIX requirement). On Windows, if *dst* already exists, :exc:`OSError` will be raised even if it is a file; there may be no way to implement an atomic rename when *dst* names an - existing file. Availability: Unix, Windows. + existing file. + + Availability: Unix, Windows. .. function:: renames(old, new) @@ -1061,8 +1224,9 @@ Remove (delete) the directory *path*. Only works when the directory is empty, otherwise, :exc:`OSError` is raised. In order to remove whole - directory trees, :func:`shutil.rmtree` can be used. Availability: Unix, - Windows. + directory trees, :func:`shutil.rmtree` can be used. + + Availability: Unix, Windows. .. function:: stat(path) @@ -1153,20 +1317,25 @@ correspond to the members of the :ctype:`statvfs` structure, namely: :attr:`f_bsize`, :attr:`f_frsize`, :attr:`f_blocks`, :attr:`f_bfree`, :attr:`f_bavail`, :attr:`f_files`, :attr:`f_ffree`, :attr:`f_favail`, - :attr:`f_flag`, :attr:`f_namemax`. Availability: Unix. + :attr:`f_flag`, :attr:`f_namemax`. + + Availability: Unix. .. function:: symlink(source, link_name) - Create a symbolic link pointing to *source* named *link_name*. Availability: - Unix. + Create a symbolic link pointing to *source* named *link_name*. + + Availability: Unix. .. function:: unlink(path) Remove (delete) the file *path*. This is the same function as :func:`remove`; the :func:`unlink` name is its traditional Unix - name. Availability: Unix, Windows. + name. + + Availability: Unix, Windows. .. function:: utime(path, times) @@ -1290,6 +1459,7 @@ behavior is to produce a core dump; on Windows, the process immediately returns an exit code of ``3``. Be aware that programs which use :func:`signal.signal` to register a handler for :const:`SIGABRT` will behave differently. + Availability: Unix, Windows. @@ -1345,7 +1515,9 @@ .. function:: _exit(n) Exit to the system with status *n*, without calling cleanup handlers, flushing - stdio buffers, etc. Availability: Unix, Windows. + stdio buffers, etc. + + Availability: Unix, Windows. .. note:: @@ -1365,69 +1537,88 @@ .. data:: EX_OK - Exit code that means no error occurred. Availability: Unix. + Exit code that means no error occurred. + + Availability: Unix. .. data:: EX_USAGE Exit code that means the command was used incorrectly, such as when the wrong - number of arguments are given. Availability: Unix. + number of arguments are given. + + Availability: Unix. .. data:: EX_DATAERR - Exit code that means the input data was incorrect. Availability: Unix. + Exit code that means the input data was incorrect. + + Availability: Unix. .. data:: EX_NOINPUT Exit code that means an input file did not exist or was not readable. + Availability: Unix. .. data:: EX_NOUSER - Exit code that means a specified user did not exist. Availability: Unix. + Exit code that means a specified user did not exist. + + Availability: Unix. .. data:: EX_NOHOST - Exit code that means a specified host did not exist. Availability: Unix. + Exit code that means a specified host did not exist. + + Availability: Unix. .. data:: EX_UNAVAILABLE - Exit code that means that a required service is unavailable. Availability: - Unix. + Exit code that means that a required service is unavailable. + + Availability: Unix. .. data:: EX_SOFTWARE - Exit code that means an internal software error was detected. Availability: - Unix. + Exit code that means an internal software error was detected. + + Availability: Unix. .. data:: EX_OSERR Exit code that means an operating system error was detected, such as the - inability to fork or create a pipe. Availability: Unix. + inability to fork or create a pipe. + + Availability: Unix. .. data:: EX_OSFILE Exit code that means some system file did not exist, could not be opened, or had - some other kind of error. Availability: Unix. + some other kind of error. + + Availability: Unix. .. data:: EX_CANTCREAT Exit code that means a user specified output file could not be created. + Availability: Unix. .. data:: EX_IOERR Exit code that means that an error occurred while doing I/O on some file. + Availability: Unix. @@ -1435,31 +1626,39 @@ Exit code that means a temporary failure occurred. This indicates something that may not really be an error, such as a network connection that couldn't be - made during a retryable operation. Availability: Unix. + made during a retryable operation. + + Availability: Unix. .. data:: EX_PROTOCOL Exit code that means that a protocol exchange was illegal, invalid, or not - understood. Availability: Unix. + understood. + + Availability: Unix. .. data:: EX_NOPERM Exit code that means that there were insufficient permissions to perform the - operation (but not intended for file system problems). Availability: Unix. + operation (but not intended for file system problems). + + Availability: Unix. .. data:: EX_CONFIG Exit code that means that some kind of configuration error occurred. + Availability: Unix. .. data:: EX_NOTFOUND - Exit code that means something like "an entry was not found". Availability: - Unix. + Exit code that means something like "an entry was not found". + + Availability: Unix. .. function:: fork() @@ -1480,6 +1679,7 @@ new child's process id in the parent, and *fd* is the file descriptor of the master end of the pseudo-terminal. For a more portable approach, use the :mod:`pty` module. If an error occurs :exc:`OSError` is raised. + Availability: some flavors of Unix. @@ -1509,19 +1709,24 @@ single: process; killing single: process; signalling - Send the signal *sig* to the process group *pgid*. Availability: Unix. + Send the signal *sig* to the process group *pgid*. + + Availability: Unix. .. function:: nice(increment) Add *increment* to the process's "niceness". Return the new niceness. + Availability: Unix. .. function:: plock(op) Lock program segments into memory. The value of *op* (defined in - ````) determines which segments are locked. Availability: Unix. + ````) determines which segments are locked. + + Availability: Unix. .. function:: popen(...) @@ -1600,7 +1805,9 @@ Possible values for the *mode* parameter to the :func:`spawn\*` family of functions. If either of these values is given, the :func:`spawn\*` functions will return as soon as the new process has been created, with the process id as - the return value. Availability: Unix, Windows. + the return value. + + Availability: Unix, Windows. .. data:: P_WAIT @@ -1609,7 +1816,9 @@ functions. If this is given as *mode*, the :func:`spawn\*` functions will not return until the new process has run to completion and will return the exit code of the process the run is successful, or ``-signal`` if a signal kills the - process. Availability: Unix, Windows. + process. + + Availability: Unix, Windows. .. data:: P_DETACH @@ -1620,6 +1829,7 @@ is similar to :const:`P_NOWAIT`, but the new process is detached from the console of the calling process. If :const:`P_OVERLAY` is used, the current process will be replaced; the :func:`spawn\*` function will not return. + Availability: Windows. @@ -1643,7 +1853,9 @@ directory. If you want to use an absolute path, make sure the first character is not a slash (``'/'``); the underlying Win32 :cfunc:`ShellExecute` function doesn't work if it is. Use the :func:`os.path.normpath` function to ensure that - the path is properly encoded for Win32. Availability: Windows. + the path is properly encoded for Win32. + + Availability: Windows. .. function:: system(command) @@ -1665,22 +1877,24 @@ the command run; on systems using a non-native shell, consult your shell documentation. - Availability: Unix, Windows. - The :mod:`subprocess` module provides more powerful facilities for spawning new processes and retrieving their results; using that module is preferable to using this function. Use the :mod:`subprocess` module. Check especially the :ref:`subprocess-replacements` section. + Availability: Unix, Windows. + .. function:: times() - Return a 5-tuple of floating point numbers indicating accumulated (processor or - other) times, in seconds. The items are: user time, system time, children's - user time, children's system time, and elapsed real time since a fixed point in - the past, in that order. See the Unix manual page :manpage:`times(2)` or the - corresponding Windows Platform API documentation. Availability: Unix, - Windows. On Windows, only the first two items are filled, the others are zero. + Return a 5-tuple of floating point numbers indicating accumulated (processor + or other) times, in seconds. The items are: user time, system time, + children's user time, children's system time, and elapsed real time since a + fixed point in the past, in that order. See the Unix manual page + :manpage:`times(2)` or the corresponding Windows Platform API documentation. + On Windows, only the first two items are filled, the others are zero. + + Availability: Unix, Windows .. function:: wait() @@ -1689,7 +1903,9 @@ and exit status indication: a 16-bit number, whose low byte is the signal number that killed the process, and whose high byte is the exit status (if the signal number is zero); the high bit of the low byte is set if a core file was - produced. Availability: Unix. + produced. + + Availability: Unix. .. function:: waitpid(pid, options) @@ -1727,6 +1943,7 @@ resource usage information is returned. Refer to :mod:`resource`.\ :func:`getrusage` for details on resource usage information. The option argument is the same as that provided to :func:`waitpid` and :func:`wait4`. + Availability: Unix. @@ -1736,28 +1953,33 @@ process id, exit status indication, and resource usage information is returned. Refer to :mod:`resource`.\ :func:`getrusage` for details on resource usage information. The arguments to :func:`wait4` are the same as those provided to - :func:`waitpid`. Availability: Unix. + :func:`waitpid`. + + Availability: Unix. .. data:: WNOHANG The option for :func:`waitpid` to return immediately if no child process status is available immediately. The function returns ``(0, 0)`` in this case. + Availability: Unix. .. data:: WCONTINUED This option causes child processes to be reported if they have been continued - from a job control stop since their status was last reported. Availability: Some - Unix systems. + from a job control stop since their status was last reported. + + Availability: Some Unix systems. .. data:: WUNTRACED This option causes child processes to be reported if they have been stopped but - their current state has not been reported since they were stopped. Availability: - Unix. + their current state has not been reported since they were stopped. + + Availability: Unix. The following functions take a process status code as returned by @@ -1767,48 +1989,63 @@ .. function:: WCOREDUMP(status) Return ``True`` if a core dump was generated for the process, otherwise - return ``False``. Availability: Unix. + return ``False``. + + Availability: Unix. .. function:: WIFCONTINUED(status) Return ``True`` if the process has been continued from a job control stop, - otherwise return ``False``. Availability: Unix. + otherwise return ``False``. + + Availability: Unix. .. function:: WIFSTOPPED(status) Return ``True`` if the process has been stopped, otherwise return - ``False``. Availability: Unix. + ``False``. + + Availability: Unix. .. function:: WIFSIGNALED(status) Return ``True`` if the process exited due to a signal, otherwise return - ``False``. Availability: Unix. + ``False``. + + Availability: Unix. .. function:: WIFEXITED(status) Return ``True`` if the process exited using the :manpage:`exit(2)` system call, - otherwise return ``False``. Availability: Unix. + otherwise return ``False``. + + Availability: Unix. .. function:: WEXITSTATUS(status) If ``WIFEXITED(status)`` is true, return the integer parameter to the :manpage:`exit(2)` system call. Otherwise, the return value is meaningless. + Availability: Unix. .. function:: WSTOPSIG(status) - Return the signal which caused the process to stop. Availability: Unix. + Return the signal which caused the process to stop. + + Availability: Unix. .. function:: WTERMSIG(status) - Return the signal which caused the process to exit. Availability: Unix. + Return the signal which caused the process to exit. + + Availability: Unix. .. _os-path: @@ -1825,8 +2062,7 @@ Unix 95, Unix 98, and others). Some platforms define additional names as well. The names known to the host operating system are given as the keys of the ``confstr_names`` dictionary. For configuration variables not included in that - mapping, passing an integer for *name* is also accepted. Availability: - Unix. + mapping, passing an integer for *name* is also accepted. If the configuration value specified by *name* isn't defined, ``None`` is returned. @@ -1836,19 +2072,25 @@ included in ``confstr_names``, an :exc:`OSError` is raised with :const:`errno.EINVAL` for the error number. + Availability: Unix + .. data:: confstr_names Dictionary mapping names accepted by :func:`confstr` to the integer values defined for those names by the host operating system. This can be used to - determine the set of names known to the system. Availability: Unix. + determine the set of names known to the system. + + Availability: Unix. .. function:: getloadavg() Return the number of processes in the system run queue averaged over the last 1, 5, and 15 minutes or raises :exc:`OSError` if the load average was - unobtainable. Availability: Unix. + unobtainable. + + Availability: Unix. .. function:: sysconf(name) @@ -1857,6 +2099,7 @@ specified by *name* isn't defined, ``-1`` is returned. The comments regarding the *name* parameter for :func:`confstr` apply here as well; the dictionary that provides information on the known names is given by ``sysconf_names``. + Availability: Unix. @@ -1864,7 +2107,9 @@ Dictionary mapping names accepted by :func:`sysconf` to the integer values defined for those names by the host operating system. This can be used to - determine the set of names known to the system. Availability: Unix. + determine the set of names known to the system. + + Availability: Unix. The following data values are used to support path manipulation operations. These are defined for all platforms. Modified: python/branches/py3k-jit/Doc/library/posix.rst ============================================================================== --- python/branches/py3k-jit/Doc/library/posix.rst (original) +++ python/branches/py3k-jit/Doc/library/posix.rst Mon May 10 23:19:57 2010 @@ -69,17 +69,22 @@ .. data:: environ A dictionary representing the string environment at the time the interpreter - was started. For example, ``environ['HOME']`` is the pathname of your home - directory, equivalent to ``getenv("HOME")`` in C. + was started. Keys and values are bytes on Unix and str on Windows. For + example, ``environ[b'HOME']`` (``environ['HOME']`` on Windows) is the + pathname of your home directory, equivalent to ``getenv("HOME")`` in C. Modifying this dictionary does not affect the string environment passed on by :func:`execv`, :func:`popen` or :func:`system`; if you need to change the environment, pass ``environ`` to :func:`execve` or add variable assignments and export statements to the command string for :func:`system` or :func:`popen`. + .. versionchanged:: 3.2 + On Unix, keys and values are bytes. + .. note:: - The :mod:`os` module provides an alternate implementation of ``environ`` which - updates the environment on modification. Note also that updating ``os.environ`` - will render this dictionary obsolete. Use of the :mod:`os` module version of - this is recommended over direct access to the :mod:`posix` module. + The :mod:`os` module provides an alternate implementation of ``environ`` + which updates the environment on modification. Note also that updating + :data:`os.environ` will render this dictionary obsolete. Use of the + :mod:`os` module version of this is recommended over direct access to the + :mod:`posix` module. Modified: python/branches/py3k-jit/Doc/library/unittest.rst ============================================================================== --- python/branches/py3k-jit/Doc/library/unittest.rst (original) +++ python/branches/py3k-jit/Doc/library/unittest.rst Mon May 10 23:19:57 2010 @@ -276,6 +276,27 @@ python -m unittest discover -s project_directory -p '*_test.py' python -m unittest discover project_directory '*_test.py' +As well as being a path it is possible to pass a package name, for example +``myproject.subpackage.test``, as the start directory. The package name you +supply will then be imported and its location on the filesystem will be used +as the start directory. + +.. caution:: + + Test discovery loads tests by importing them. Once test discovery has + found all the test files from the start directory you specify it turns the + paths into package names to import. For example `foo/bar/baz.py` will be + imported as ``foo.bar.baz``. + + If you have a package installed globally and attempt test discovery on + a different copy of the package then the import *could* happen from the + wrong place. If this happens test discovery will warn you and exit. + + If you supply the start directory as a package name rather than a + path to a directory then discover assumes that whichever location it + imports from is the location you intended, so you will not get the + warning. + Test modules and packages can customize test loading and discovery by through the `load_tests protocol`_. @@ -882,9 +903,9 @@ .. method:: assertNotRegexpMatches(text, regexp, msg=None) Verifies that a *regexp* search does not match *text*. Fails with an error - message including the pattern and the *text*. *regexp* may be - a regular expression object or a string containing a regular expression - suitable for use by :func:`re.search`. + message including the pattern and the part of *text* that matches. *regexp* + may be a regular expression object or a string containing a regular + expression suitable for use by :func:`re.search`. .. versionadded:: 3.2 Modified: python/branches/py3k-jit/Doc/library/weakref.rst ============================================================================== --- python/branches/py3k-jit/Doc/library/weakref.rst (original) +++ python/branches/py3k-jit/Doc/library/weakref.rst Mon May 10 23:19:57 2010 @@ -72,9 +72,9 @@ obj = Dict(red=1, green=2, blue=3) # this object is weak referenceable -Other built-in types such as :class:`tuple` and :class:`long` do not support -weak references even when subclassed (This is an implementation detail and may -be different across various Python implementations.). +Other built-in types such as :class:`tuple` and :class:`int` do not support weak +references even when subclassed (This is an implementation detail and may be +different across various Python implementations.). Extension types can easily be made to support weak references; see :ref:`weakref-support`. Modified: python/branches/py3k-jit/Include/unicodeobject.h ============================================================================== --- python/branches/py3k-jit/Include/unicodeobject.h (original) +++ python/branches/py3k-jit/Include/unicodeobject.h Mon May 10 23:19:57 2010 @@ -158,6 +158,7 @@ # define PyUnicode_AsWideChar PyUnicodeUCS2_AsWideChar # define PyUnicode_ClearFreeList PyUnicodeUCS2_ClearFreelist # define PyUnicode_Compare PyUnicodeUCS2_Compare +# define PyUnicode_CompareWithASCII PyUnicodeUCS2_CompareASCII # define PyUnicode_Concat PyUnicodeUCS2_Concat # define PyUnicode_Append PyUnicodeUCS2_Append # define PyUnicode_AppendAndDel PyUnicodeUCS2_AppendAndDel @@ -257,6 +258,7 @@ # define PyUnicode_AsWideChar PyUnicodeUCS4_AsWideChar # define PyUnicode_ClearFreeList PyUnicodeUCS4_ClearFreelist # define PyUnicode_Compare PyUnicodeUCS4_Compare +# define PyUnicode_CompareWithASCII PyUnicodeUCS4_CompareWithASCII # define PyUnicode_Concat PyUnicodeUCS4_Concat # define PyUnicode_Append PyUnicodeUCS4_Append # define PyUnicode_AppendAndDel PyUnicodeUCS4_AppendAndDel Modified: python/branches/py3k-jit/Lib/compileall.py ============================================================================== --- python/branches/py3k-jit/Lib/compileall.py (original) +++ python/branches/py3k-jit/Lib/compileall.py Mon May 10 23:19:57 2010 @@ -93,12 +93,6 @@ cache_dir = os.path.dirname(cfile) head, tail = name[:-3], name[-3:] if tail == '.py': - if not legacy: - try: - os.mkdir(cache_dir) - except OSError as error: - if error.errno != errno.EEXIST: - raise if not force: try: mtime = int(os.stat(fullname).st_mtime) Modified: python/branches/py3k-jit/Lib/lib2to3/fixes/fix_import.py ============================================================================== --- python/branches/py3k-jit/Lib/lib2to3/fixes/fix_import.py (original) +++ python/branches/py3k-jit/Lib/lib2to3/fixes/fix_import.py Mon May 10 23:19:57 2010 @@ -43,7 +43,13 @@ import_name< 'import' imp=any > """ + def start_tree(self, tree, name): + super(FixImport, self).start_tree(tree, name) + self.skip = "absolute_import" in tree.future_features + def transform(self, node, results): + if self.skip: + return imp = results['imp'] if node.type == syms.import_from: @@ -71,19 +77,22 @@ self.warning(node, "absolute and local imports together") return - new = FromImport('.', [imp]) + new = FromImport(".", [imp]) new.prefix = node.prefix return new def probably_a_local_import(self, imp_name): - imp_name = imp_name.split('.', 1)[0] + if imp_name.startswith("."): + # Relative imports are certainly not local imports. + return False + imp_name = imp_name.split(".", 1)[0] base_path = dirname(self.filename) base_path = join(base_path, imp_name) # If there is no __init__.py next to the file its not in a package # so can't be a relative import. - if not exists(join(dirname(base_path), '__init__.py')): + if not exists(join(dirname(base_path), "__init__.py")): return False - for ext in ['.py', sep, '.pyc', '.so', '.sl', '.pyd']: + for ext in [".py", sep, ".pyc", ".so", ".sl", ".pyd"]: if exists(base_path + ext): return True return False Modified: python/branches/py3k-jit/Lib/lib2to3/fixes/fix_operator.py ============================================================================== --- python/branches/py3k-jit/Lib/lib2to3/fixes/fix_operator.py (original) +++ python/branches/py3k-jit/Lib/lib2to3/fixes/fix_operator.py Mon May 10 23:19:57 2010 @@ -14,10 +14,10 @@ func = "'(' func=any ')'" PATTERN = """ power< module='operator' - trailer< '.' {methods} > trailer< {func} > > + trailer< '.' %(methods)s > trailer< %(func)s > > | - power< {methods} trailer< {func} > > - """.format(methods=methods, func=func) + power< %(methods)s trailer< %(func)s > > + """ % dict(methods=methods, func=func) def transform(self, node, results): method = results["method"][0] Modified: python/branches/py3k-jit/Lib/lib2to3/fixes/fix_reduce.py ============================================================================== --- python/branches/py3k-jit/Lib/lib2to3/fixes/fix_reduce.py (original) +++ python/branches/py3k-jit/Lib/lib2to3/fixes/fix_reduce.py Mon May 10 23:19:57 2010 @@ -7,9 +7,8 @@ used in that module. """ -from .. import pytree -from .. import fixer_base -from ..fixer_util import Name, Attr, touch_import +from lib2to3 import fixer_base +from lib2to3.fixer_util import touch_import Modified: python/branches/py3k-jit/Lib/lib2to3/fixes/fix_tuple_params.py ============================================================================== --- python/branches/py3k-jit/Lib/lib2to3/fixes/fix_tuple_params.py (original) +++ python/branches/py3k-jit/Lib/lib2to3/fixes/fix_tuple_params.py Mon May 10 23:19:57 2010 @@ -154,7 +154,7 @@ if d is None: d = {} for i, obj in enumerate(param_list): - trailer = [Subscript(Number(i))] + trailer = [Subscript(Number(str(i)))] if isinstance(obj, list): map_to_index(obj, trailer, d=d) else: Modified: python/branches/py3k-jit/Lib/lib2to3/fixes/fix_xrange.py ============================================================================== --- python/branches/py3k-jit/Lib/lib2to3/fixes/fix_xrange.py (original) +++ python/branches/py3k-jit/Lib/lib2to3/fixes/fix_xrange.py Mon May 10 23:19:57 2010 @@ -17,6 +17,13 @@ rest=any* > """ + def start_tree(self, tree, filename): + super(FixXrange, self).start_tree(tree, filename) + self.transformed_xranges = set() + + def finish_tree(self, tree, filename): + self.transformed_xranges = None + def transform(self, node, results): name = results["name"] if name.value == "xrange": @@ -29,9 +36,12 @@ def transform_xrange(self, node, results): name = results["name"] name.replace(Name("range", prefix=name.prefix)) + # This prevents the new range call from being wrapped in a list later. + self.transformed_xranges.add(id(node)) def transform_range(self, node, results): - if not self.in_special_context(node): + if (id(node) not in self.transformed_xranges and + not self.in_special_context(node)): range_call = Call(Name("range"), [results["args"].clone()]) # Encase the range call in list(). list_call = Call(Name("list"), [range_call], Modified: python/branches/py3k-jit/Lib/lib2to3/main.py ============================================================================== --- python/branches/py3k-jit/Lib/lib2to3/main.py (original) +++ python/branches/py3k-jit/Lib/lib2to3/main.py Mon May 10 23:19:57 2010 @@ -2,6 +2,8 @@ Main program for 2to3. """ +from __future__ import with_statement + import sys import os import difflib @@ -62,8 +64,14 @@ if self.show_diffs: diff_lines = diff_texts(old, new, filename) try: - for line in diff_lines: - print(line) + if self.output_lock is not None: + with self.output_lock: + for line in diff_lines: + print(line) + sys.stdout.flush() + else: + for line in diff_lines: + print(line) except UnicodeEncodeError: warn("couldn't encode %s's diff for your terminal" % (filename,)) @@ -94,7 +102,7 @@ parser.add_option("-x", "--nofix", action="append", default=[], help="Prevent a fixer from being run.") parser.add_option("-l", "--list-fixes", action="store_true", - help="List available transformations (fixes/fix_*.py)") + help="List available transformations") parser.add_option("-p", "--print-function", action="store_true", help="Modify the grammar so that print() is a function") parser.add_option("-v", "--verbose", action="store_true", Modified: python/branches/py3k-jit/Lib/lib2to3/pgen2/tokenize.py ============================================================================== --- python/branches/py3k-jit/Lib/lib2to3/pgen2/tokenize.py (original) +++ python/branches/py3k-jit/Lib/lib2to3/pgen2/tokenize.py Mon May 10 23:19:57 2010 @@ -38,6 +38,13 @@ "generate_tokens", "untokenize"] del token +try: + bytes +except NameError: + # Support bytes type in Python <= 2.5, so 2to3 turns itself into + # valid Python 3 code. + bytes = str + def group(*choices): return '(' + '|'.join(choices) + ')' def any(*choices): return group(*choices) + '*' def maybe(*choices): return group(*choices) + '?' @@ -267,7 +274,7 @@ try: return readline() except StopIteration: - return b'' + return bytes() def find_cookie(line): try: Modified: python/branches/py3k-jit/Lib/lib2to3/pytree.py ============================================================================== --- python/branches/py3k-jit/Lib/lib2to3/pytree.py (original) +++ python/branches/py3k-jit/Lib/lib2to3/pytree.py Mon May 10 23:19:57 2010 @@ -289,8 +289,7 @@ for node in child.post_order(): yield node - @property - def prefix(self): + def _prefix_getter(self): """ The whitespace and comments preceding this node in the input. """ @@ -298,11 +297,12 @@ return "" return self.children[0].prefix - @prefix.setter - def prefix(self, prefix): + def _prefix_setter(self, prefix): if self.children: self.children[0].prefix = prefix + prefix = property(_prefix_getter, _prefix_setter) + def set_child(self, i, child): """ Equivalent to 'node.children[i] = child'. This method also sets the @@ -390,18 +390,17 @@ """Return a pre-order iterator for the tree.""" yield self - @property - def prefix(self): + def _prefix_getter(self): """ The whitespace and comments preceding this token in the input. """ return self._prefix - @prefix.setter - def prefix(self, prefix): + def _prefix_setter(self, prefix): self.changed() self._prefix = prefix + prefix = property(_prefix_getter, _prefix_setter) def convert(gr, raw_node): """ Modified: python/branches/py3k-jit/Lib/lib2to3/refactor.py ============================================================================== --- python/branches/py3k-jit/Lib/lib2to3/refactor.py (original) +++ python/branches/py3k-jit/Lib/lib2to3/refactor.py Mon May 10 23:19:57 2010 @@ -8,6 +8,8 @@ provides infrastructure to write your own refactoring tool. """ +from __future__ import with_statement + __author__ = "Guido van Rossum " @@ -122,13 +124,14 @@ _to_system_newlines = _identity -def _detect_future_print(source): +def _detect_future_features(source): have_docstring = False gen = tokenize.generate_tokens(io.StringIO(source).readline) def advance(): tok = next(gen) return tok[0], tok[1] ignore = frozenset((token.NEWLINE, tokenize.NL, token.COMMENT)) + features = set() try: while True: tp, value = advance() @@ -140,26 +143,25 @@ have_docstring = True elif tp == token.NAME and value == "from": tp, value = advance() - if tp != token.NAME and value != "__future__": + if tp != token.NAME or value != "__future__": break tp, value = advance() - if tp != token.NAME and value != "import": + if tp != token.NAME or value != "import": break tp, value = advance() if tp == token.OP and value == "(": tp, value = advance() while tp == token.NAME: - if value == "print_function": - return True + features.add(value) tp, value = advance() - if tp != token.OP and value != ",": + if tp != token.OP or value != ",": break tp, value = advance() else: break except StopIteration: pass - return False + return frozenset(features) class FixerError(Exception): @@ -341,7 +343,8 @@ An AST corresponding to the refactored input stream; None if there were errors during the parse. """ - if _detect_future_print(data): + features = _detect_future_features(data) + if "print_function" in features: self.driver.grammar = pygram.python_grammar_no_print_statement try: tree = self.driver.parse_string(data) @@ -351,6 +354,7 @@ return finally: self.driver.grammar = self.grammar + tree.future_features = features self.log_debug("Refactoring %s", name) self.refactor_tree(tree, name) return tree @@ -605,6 +609,7 @@ def __init__(self, *args, **kwargs): super(MultiprocessRefactoringTool, self).__init__(*args, **kwargs) self.queue = None + self.output_lock = None def refactor(self, items, write=False, doctests_only=False, num_processes=1): @@ -618,6 +623,7 @@ if self.queue is not None: raise RuntimeError("already doing multiple processes") self.queue = multiprocessing.JoinableQueue() + self.output_lock = multiprocessing.Lock() processes = [multiprocessing.Process(target=self._child) for i in range(num_processes)] try: Modified: python/branches/py3k-jit/Lib/lib2to3/tests/test_fixers.py ============================================================================== --- python/branches/py3k-jit/Lib/lib2to3/tests/test_fixers.py (original) +++ python/branches/py3k-jit/Lib/lib2to3/tests/test_fixers.py Mon May 10 23:19:57 2010 @@ -1497,6 +1497,17 @@ for call in fixer_util.consuming_calls: self.unchanged("a = %s(range(10))" % call) +class Test_xrange_with_reduce(FixerTestCase): + + def setUp(self): + super(Test_xrange_with_reduce, self).setUp(["xrange", "reduce"]) + + def test_double_transform(self): + b = """reduce(x, xrange(5))""" + a = """from functools import reduce +reduce(x, range(5))""" + self.check(b, a) + class Test_raw_input(FixerTestCase): fixer = "raw_input" @@ -3679,7 +3690,7 @@ self.files_checked.append(name) return self.always_exists or (name in self.present_files) - from ..fixes import fix_import + from lib2to3.fixes import fix_import fix_import.exists = fake_exists def tearDown(self): @@ -3722,6 +3733,12 @@ self.present_files = set(["bar.py"]) self.unchanged(s) + def test_with_absolute_import_enabled(self): + s = "from __future__ import absolute_import\nimport bar" + self.always_exists = False + self.present_files = set(["__init__.py", "bar.py"]) + self.unchanged(s) + def test_in_package(self): b = "import bar" a = "from . import bar" @@ -3736,6 +3753,10 @@ self.present_files = set(["__init__.py", "bar" + os.path.sep]) self.check(b, a) + def test_already_relative_import(self): + s = "from . import bar" + self.unchanged(s) + def test_comments_and_indent(self): b = "import bar # Foo" a = "from . import bar # Foo" Modified: python/branches/py3k-jit/Lib/lib2to3/tests/test_parser.py ============================================================================== --- python/branches/py3k-jit/Lib/lib2to3/tests/test_parser.py (original) +++ python/branches/py3k-jit/Lib/lib2to3/tests/test_parser.py Mon May 10 23:19:57 2010 @@ -6,6 +6,8 @@ test_grammar.py files from both Python 2 and Python 3. """ +from __future__ import with_statement + # Testing imports from . import support from .support import driver, test_dir @@ -149,10 +151,11 @@ for filepath in support.all_project_files(): with open(filepath, "rb") as fp: encoding = tokenize.detect_encoding(fp.readline)[0] - fp.seek(0) + self.assertTrue(encoding is not None, + "can't detect encoding for %s" % filepath) + with open(filepath, "r") as fp: source = fp.read() - if encoding: - source = source.decode(encoding) + source = source.decode(encoding) tree = driver.parse_string(source) new = str(tree) if encoding: @@ -199,10 +202,10 @@ self.validate(s) -def diff(fn, result): - f = open("@", "wb") +def diff(fn, result, encoding): + f = open("@", "w") try: - f.write(result) + f.write(result.encode(encoding)) finally: f.close() try: Modified: python/branches/py3k-jit/Lib/lib2to3/tests/test_pytree.py ============================================================================== --- python/branches/py3k-jit/Lib/lib2to3/tests/test_pytree.py (original) +++ python/branches/py3k-jit/Lib/lib2to3/tests/test_pytree.py Mon May 10 23:19:57 2010 @@ -9,6 +9,9 @@ especially when debugging a test. """ +from __future__ import with_statement + +import sys import warnings # Testing imports @@ -28,20 +31,22 @@ """Unit tests for nodes (Base, Leaf, Node).""" - def test_deprecated_prefix_methods(self): - l = pytree.Leaf(100, "foo") - with warnings.catch_warnings(record=True) as w: - warnings.simplefilter("always", DeprecationWarning) - self.assertEqual(l.get_prefix(), "") - l.set_prefix("hi") - self.assertEqual(l.prefix, "hi") - self.assertEqual(len(w), 2) - for warning in w: - self.assertTrue(warning.category is DeprecationWarning) - self.assertEqual(str(w[0].message), "get_prefix() is deprecated; " \ - "use the prefix property") - self.assertEqual(str(w[1].message), "set_prefix() is deprecated; " \ - "use the prefix property") + if sys.version_info >= (2,6): + # warnings.catch_warnings is new in 2.6. + def test_deprecated_prefix_methods(self): + l = pytree.Leaf(100, "foo") + with warnings.catch_warnings(record=True) as w: + warnings.simplefilter("always", DeprecationWarning) + self.assertEqual(l.get_prefix(), "") + l.set_prefix("hi") + self.assertEqual(l.prefix, "hi") + self.assertEqual(len(w), 2) + for warning in w: + self.assertTrue(warning.category is DeprecationWarning) + self.assertEqual(str(w[0].message), "get_prefix() is deprecated; " \ + "use the prefix property") + self.assertEqual(str(w[1].message), "set_prefix() is deprecated; " \ + "use the prefix property") def test_instantiate_base(self): if __debug__: Modified: python/branches/py3k-jit/Lib/lib2to3/tests/test_refactor.py ============================================================================== --- python/branches/py3k-jit/Lib/lib2to3/tests/test_refactor.py (original) +++ python/branches/py3k-jit/Lib/lib2to3/tests/test_refactor.py Mon May 10 23:19:57 2010 @@ -2,6 +2,8 @@ Unit tests for refactor.py. """ +from __future__ import with_statement + import sys import os import codecs @@ -61,42 +63,50 @@ self.assertEqual(full_names, ["myfixes.fix_" + name for name in contents]) - def test_detect_future_print(self): - run = refactor._detect_future_print - self.assertFalse(run("")) - self.assertTrue(run("from __future__ import print_function")) - self.assertFalse(run("from __future__ import generators")) - self.assertFalse(run("from __future__ import generators, feature")) - input = "from __future__ import generators, print_function" - self.assertTrue(run(input)) - input ="from __future__ import print_function, generators" - self.assertTrue(run(input)) - input = "from __future__ import (print_function,)" - self.assertTrue(run(input)) - input = "from __future__ import (generators, print_function)" - self.assertTrue(run(input)) - input = "from __future__ import (generators, nested_scopes)" - self.assertFalse(run(input)) - input = """from __future__ import generators + def test_detect_future_features(self): + run = refactor._detect_future_features + fs = frozenset + empty = fs() + self.assertEqual(run(""), empty) + self.assertEqual(run("from __future__ import print_function"), + fs(("print_function",))) + self.assertEqual(run("from __future__ import generators"), + fs(("generators",))) + self.assertEqual(run("from __future__ import generators, feature"), + fs(("generators", "feature"))) + inp = "from __future__ import generators, print_function" + self.assertEqual(run(inp), fs(("generators", "print_function"))) + inp ="from __future__ import print_function, generators" + self.assertEqual(run(inp), fs(("print_function", "generators"))) + inp = "from __future__ import (print_function,)" + self.assertEqual(run(inp), fs(("print_function",))) + inp = "from __future__ import (generators, print_function)" + self.assertEqual(run(inp), fs(("generators", "print_function"))) + inp = "from __future__ import (generators, nested_scopes)" + self.assertEqual(run(inp), fs(("generators", "nested_scopes"))) + inp = """from __future__ import generators from __future__ import print_function""" - self.assertTrue(run(input)) - self.assertFalse(run("from")) - self.assertFalse(run("from 4")) - self.assertFalse(run("from x")) - self.assertFalse(run("from x 5")) - self.assertFalse(run("from x im")) - self.assertFalse(run("from x import")) - self.assertFalse(run("from x import 4")) - input = "'docstring'\nfrom __future__ import print_function" - self.assertTrue(run(input)) - input = "'docstring'\n'somng'\nfrom __future__ import print_function" - self.assertFalse(run(input)) - input = "# comment\nfrom __future__ import print_function" - self.assertTrue(run(input)) - input = "# comment\n'doc'\nfrom __future__ import print_function" - self.assertTrue(run(input)) - input = "class x: pass\nfrom __future__ import print_function" - self.assertFalse(run(input)) + self.assertEqual(run(inp), fs(("generators", "print_function"))) + invalid = ("from", + "from 4", + "from x", + "from x 5", + "from x im", + "from x import", + "from x import 4", + ) + for inp in invalid: + self.assertEqual(run(inp), empty) + inp = "'docstring'\nfrom __future__ import print_function" + self.assertEqual(run(inp), fs(("print_function",))) + inp = "'docstring'\n'somng'\nfrom __future__ import print_function" + self.assertEqual(run(inp), empty) + inp = "# comment\nfrom __future__ import print_function" + self.assertEqual(run(inp), fs(("print_function",))) + inp = "# comment\n'doc'\nfrom __future__ import print_function" + self.assertEqual(run(inp), fs(("print_function",))) + inp = "class x: pass\nfrom __future__ import print_function" + self.assertEqual(run(inp), empty) def test_get_headnode_dict(self): class NoneFix(fixer_base.BaseFix): Modified: python/branches/py3k-jit/Lib/os.py ============================================================================== --- python/branches/py3k-jit/Lib/os.py (original) +++ python/branches/py3k-jit/Lib/os.py Mon May 10 23:19:57 2010 @@ -387,29 +387,33 @@ from _abcoll import MutableMapping # Can't use collections (bootstrap) class _Environ(MutableMapping): - def __init__(self, environ, keymap, putenv, unsetenv): - self.keymap = keymap + def __init__(self, data, encodekey, decodekey, encodevalue, decodevalue, putenv, unsetenv): + self.encodekey = encodekey + self.decodekey = decodekey + self.encodevalue = encodevalue + self.decodevalue = decodevalue self.putenv = putenv self.unsetenv = unsetenv - self.data = data = {} - for key, value in environ.items(): - data[keymap(key)] = str(value) + self.data = data def __getitem__(self, key): - return self.data[self.keymap(key)] + value = self.data[self.encodekey(key)] + return self.decodevalue(value) def __setitem__(self, key, value): - value = str(value) + key = self.encodekey(key) + value = self.encodevalue(value) self.putenv(key, value) - self.data[self.keymap(key)] = value + self.data[key] = value def __delitem__(self, key): + key = self.encodekey(key) self.unsetenv(key) - del self.data[self.keymap(key)] + del self.data[key] def __iter__(self): for key in self.data: - yield key + yield self.decodekey(key) def __len__(self): return len(self.data) @@ -439,22 +443,78 @@ else: __all__.append("unsetenv") -if name in ('os2', 'nt'): # Where Env Var Names Must Be UPPERCASE - _keymap = lambda key: str(key.upper()) -else: # Where Env Var Names Can Be Mixed Case - _keymap = lambda key: str(key) - -environ = _Environ(environ, _keymap, _putenv, _unsetenv) +def _createenviron(): + if name in ('os2', 'nt'): + # Where Env Var Names Must Be UPPERCASE + def check_str(value): + if not isinstance(value, str): + raise TypeError("str expected, not %s" % type(value).__name__) + return value + encode = check_str + decode = str + def encodekey(key): + return encode(key).upper() + data = {} + for key, value in environ.items(): + data[encodekey(key)] = value + else: + # Where Env Var Names Can Be Mixed Case + def encode(value): + if not isinstance(value, str): + raise TypeError("str expected, not %s" % type(value).__name__) + return value.encode(sys.getfilesystemencoding(), 'surrogateescape') + def decode(value): + return value.decode(sys.getfilesystemencoding(), 'surrogateescape') + encodekey = encode + data = environ + return _Environ(data, + encodekey, decode, + encode, decode, + _putenv, _unsetenv) + +# unicode environ +environ = _createenviron() +del _createenviron def getenv(key, default=None): """Get an environment variable, return None if it doesn't exist. - The optional second argument can specify an alternate default.""" - if isinstance(key, bytes): - key = key.decode(sys.getfilesystemencoding(), "surrogateescape") + The optional second argument can specify an alternate default. + key, default and the result are str.""" return environ.get(key, default) __all__.append("getenv") +if name not in ('os2', 'nt'): + def _check_bytes(value): + if not isinstance(value, bytes): + raise TypeError("bytes expected, not %s" % type(value).__name__) + return value + + # bytes environ + environb = _Environ(environ.data, + _check_bytes, bytes, + _check_bytes, bytes, + _putenv, _unsetenv) + del _check_bytes + + def getenvb(key, default=None): + """Get an environment variable, return None if it doesn't exist. + The optional second argument can specify an alternate default. + key, default and the result are bytes.""" + return environb.get(key, default) + __all__.append("getenvb") + +if name != 'nt': + def fsencode(value): + """Encode value for use in the file system, environment variables + or the command line.""" + if isinstance(value, bytes): + return value + elif isinstance(value, str): + return value.encode(sys.getfilesystemencoding(), 'surrogateescape') + else: + raise TypeError("expect bytes or str, not %s" % type(value).__name__) + def _exists(name): return name in globals() Modified: python/branches/py3k-jit/Lib/py_compile.py ============================================================================== --- python/branches/py3k-jit/Lib/py_compile.py (original) +++ python/branches/py3k-jit/Lib/py_compile.py Mon May 10 23:19:57 2010 @@ -123,11 +123,11 @@ return if cfile is None: cfile = imp.cache_from_source(file) - try: - os.mkdir(os.path.dirname(cfile)) - except OSError as error: - if error.errno != errno.EEXIST: - raise + try: + os.makedirs(os.path.dirname(cfile)) + except OSError as error: + if error.errno != errno.EEXIST: + raise with open(cfile, 'wb') as fc: fc.write(b'\0\0\0\0') wr_long(fc, timestamp) Modified: python/branches/py3k-jit/Lib/site.py ============================================================================== --- python/branches/py3k-jit/Lib/site.py (original) +++ python/branches/py3k-jit/Lib/site.py Mon May 10 23:19:57 2010 @@ -240,6 +240,13 @@ from sysconfig import get_path import os + + if sys.platform == 'darwin': + from sysconfig import get_config_var + if get_config_var('PYTHONFRAMEWORK'): + USER_SITE = get_path('purelib', 'osx_framework_user') + return USER_SITE + USER_SITE = get_path('purelib', '%s_user' % os.name) return USER_SITE @@ -286,13 +293,11 @@ if sys.platform == "darwin": # for framework builds *only* we add the standard Apple # locations. - if 'Python.framework' in prefix: - sitepackages.append( - os.path.expanduser( - os.path.join("~", "Library", "Python", - sys.version[:3], "site-packages"))) + from sysconfig import get_config_var + framework = get_config_var("PYTHONFRAMEWORK") + if framework and "/%s.framework/"%(framework,) in prefix: sitepackages.append( - os.path.join("/Library", "Python", + os.path.join("/Library", framework, sys.version[:3], "site-packages")) return sitepackages Modified: python/branches/py3k-jit/Lib/subprocess.py ============================================================================== --- python/branches/py3k-jit/Lib/subprocess.py (original) +++ python/branches/py3k-jit/Lib/subprocess.py Mon May 10 23:19:57 2010 @@ -1079,32 +1079,24 @@ self._set_cloexec_flag(errpipe_write) if _posixsubprocess: - fs_encoding = sys.getfilesystemencoding() - def fs_encode(s): - """Encode s for use in the env, fs or cmdline.""" - if isinstance(s, bytes): - return s - else: - return s.encode(fs_encoding, 'surrogateescape') - # We must avoid complex work that could involve # malloc or free in the child process to avoid # potential deadlocks, thus we do all this here. # and pass it to fork_exec() if env: - env_list = [fs_encode(k) + b'=' + fs_encode(v) + env_list = [os.fsencode(k) + b'=' + os.fsencode(v) for k, v in env.items()] else: env_list = None # Use execv instead of execve. if os.path.dirname(executable): - executable_list = (fs_encode(executable),) + executable_list = (os.fsencode(executable),) else: # This matches the behavior of os._execvpe(). path_list = os.get_exec_path(env) executable_list = (os.path.join(dir, executable) for dir in path_list) - executable_list = tuple(fs_encode(exe) + executable_list = tuple(os.fsencode(exe) for exe in executable_list) self.pid = _posixsubprocess.fork_exec( args, executable_list, Modified: python/branches/py3k-jit/Lib/sysconfig.py ============================================================================== --- python/branches/py3k-jit/Lib/sysconfig.py (original) +++ python/branches/py3k-jit/Lib/sysconfig.py Mon May 10 23:19:57 2010 @@ -73,6 +73,15 @@ 'scripts': '{userbase}/bin', 'data' : '{userbase}', }, + 'osx_framework_user': { + 'stdlib': '{userbase}/lib/python', + 'platstdlib': '{userbase}/lib/python', + 'purelib': '{userbase}/lib/python/site-packages', + 'platlib': '{userbase}/lib/python/site-packages', + 'include': '{userbase}/include', + 'scripts': '{userbase}/bin', + 'data' : '{userbase}', + }, } _SCHEME_KEYS = ('stdlib', 'platstdlib', 'purelib', 'platlib', 'include', @@ -157,6 +166,12 @@ base = os.environ.get("APPDATA") or "~" return env_base if env_base else joinuser(base, "Python") + if sys.platform == "darwin": + framework = get_config_var("PYTHONFRAMEWORK") + if framework: + return joinuser("~", "Library", framework, "%d.%d"%( + sys.version_info[:2])) + return env_base if env_base else joinuser("~", ".local") @@ -400,13 +415,17 @@ _CONFIG_VARS['py_version_nodot'] = _PY_VERSION[0] + _PY_VERSION[2] _CONFIG_VARS['base'] = _PREFIX _CONFIG_VARS['platbase'] = _EXEC_PREFIX - _CONFIG_VARS['userbase'] = _getuserbase() _CONFIG_VARS['projectbase'] = _PROJECT_BASE if os.name in ('nt', 'os2'): _init_non_posix(_CONFIG_VARS) if os.name == 'posix': _init_posix(_CONFIG_VARS) + # Setting 'userbase' is done below the call to the + # init function to enable using 'get_config_var' in + # the init-function. + _CONFIG_VARS['userbase'] = _getuserbase() + if 'srcdir' not in _CONFIG_VARS: _CONFIG_VARS['srcdir'] = _PROJECT_BASE Modified: python/branches/py3k-jit/Lib/test/regrtest.py ============================================================================== --- python/branches/py3k-jit/Lib/test/regrtest.py (original) +++ python/branches/py3k-jit/Lib/test/regrtest.py Mon May 10 23:19:57 2010 @@ -733,6 +733,9 @@ def replace_stdout(): """Set stdout encoder error handler to backslashreplace (as stderr error handler) to avoid UnicodeEncodeError when printing a traceback""" + if os.name == "nt": + # Replace sys.stdout breaks the stdout newlines on Windows: issue #8533 + return stdout = sys.stdout sys.stdout = open(stdout.fileno(), 'w', encoding=stdout.encoding, Modified: python/branches/py3k-jit/Lib/test/test_datetime.py ============================================================================== --- python/branches/py3k-jit/Lib/test/test_datetime.py (original) +++ python/branches/py3k-jit/Lib/test/test_datetime.py Mon May 10 23:19:57 2010 @@ -264,6 +264,11 @@ for total_seconds in [123456.789012, -123456.789012, 0.123456, 0, 1e6]: td = timedelta(seconds=total_seconds) self.assertEqual(td.total_seconds(), total_seconds) + # Issue8644: Test that td.total_seconds() has the same + # accuracy as td / timedelta(seconds=1). + for ms in [-1, -2, -123]: + td = timedelta(microseconds=ms) + self.assertEqual(td.total_seconds(), td / timedelta(seconds=1)) def test_carries(self): t1 = timedelta(days=100, Modified: python/branches/py3k-jit/Lib/test/test_enumerate.py ============================================================================== --- python/branches/py3k-jit/Lib/test/test_enumerate.py (original) +++ python/branches/py3k-jit/Lib/test/test_enumerate.py Mon May 10 23:19:57 2010 @@ -199,26 +199,31 @@ self.assertEqual(rc, sys.getrefcount(r)) -class TestStart(EnumerateTestCase): +class EnumerateStartTestCase(EnumerateTestCase): - enum = lambda i: enumerate(i, start=11) - seq, res = 'abc', [(1, 'a'), (2, 'b'), (3, 'c')] + def test_basicfunction(self): + e = self.enum(self.seq) + self.assertEqual(iter(e), e) + self.assertEqual(list(self.enum(self.seq)), self.res) -class TestLongStart(EnumerateTestCase): +class TestStart(EnumerateStartTestCase): - enum = lambda i: enumerate(i, start=sys.maxsize+1) + enum = lambda self, i: enumerate(i, start=11) + seq, res = 'abc', [(11, 'a'), (12, 'b'), (13, 'c')] + + +class TestLongStart(EnumerateStartTestCase): + + enum = lambda self, i: enumerate(i, start=sys.maxsize+1) seq, res = 'abc', [(sys.maxsize+1,'a'), (sys.maxsize+2,'b'), (sys.maxsize+3,'c')] def test_main(verbose=None): - testclasses = (EnumerateTestCase, SubclassTestCase, TestEmpty, TestBig, - TestReversed) - support.run_unittest(*testclasses) + support.run_unittest(__name__) # verify reference counting - import sys if verbose and hasattr(sys, "gettotalrefcount"): counts = [None] * 5 for i in range(len(counts)): Modified: python/branches/py3k-jit/Lib/test/test_os.py ============================================================================== --- python/branches/py3k-jit/Lib/test/test_os.py (original) +++ python/branches/py3k-jit/Lib/test/test_os.py Mon May 10 23:19:57 2010 @@ -369,12 +369,17 @@ def setUp(self): self.__save = dict(os.environ) + if os.name not in ('os2', 'nt'): + self.__saveb = dict(os.environb) for key, value in self._reference().items(): os.environ[key] = value def tearDown(self): os.environ.clear() os.environ.update(self.__save) + if os.name not in ('os2', 'nt'): + os.environb.clear() + os.environb.update(self.__saveb) def _reference(self): return {"KEY1":"VALUE1", "KEY2":"VALUE2", "KEY3":"VALUE3"} @@ -439,6 +444,27 @@ # Supplied PATH environment variable self.assertSequenceEqual(test_path, os.get_exec_path(test_env)) + @unittest.skipIf(sys.platform == "win32", "POSIX specific test") + def test_environb(self): + # os.environ -> os.environb + value = 'euro\u20ac' + try: + value_bytes = value.encode(sys.getfilesystemencoding(), + 'surrogateescape') + except UnicodeEncodeError: + msg = "U+20AC character is not encodable to %s" % ( + sys.getfilesystemencoding(),) + self.skipTest(msg) + os.environ['unicode'] = value + self.assertEquals(os.environ['unicode'], value) + self.assertEquals(os.environb[b'unicode'], value_bytes) + + # os.environb -> os.environ + value = b'\xff' + os.environb[b'bytes'] = value + self.assertEquals(os.environb[b'bytes'], value) + value_str = value.decode(sys.getfilesystemencoding(), 'surrogateescape') + self.assertEquals(os.environ['bytes'], value_str) class WalkTests(unittest.TestCase): """Tests for os.walk().""" @@ -607,6 +633,58 @@ def test_execvpe_with_bad_arglist(self): self.assertRaises(ValueError, os.execvpe, 'notepad', [], None) + class _stub_out_for_execvpe_test(object): + """ + Stubs out execv, execve and get_exec_path functions when + used as context manager. Records exec calls. The mock execv + and execve functions always raise an exception as they would + normally never return. + """ + def __init__(self): + # A list of tuples containing (function name, first arg, args) + # of calls to execv or execve that have been made. + self.calls = [] + def _mock_execv(self, name, *args): + self.calls.append(('execv', name, args)) + raise RuntimeError("execv called") + + def _mock_execve(self, name, *args): + self.calls.append(('execve', name, args)) + raise OSError(errno.ENOTDIR, "execve called") + + def _mock_get_exec_path(self, env=None): + return [os.sep+'p', os.sep+'pp'] + + def __enter__(self): + self.orig_execv = os.execv + self.orig_execve = os.execve + self.orig_get_exec_path = os.get_exec_path + os.execv = self._mock_execv + os.execve = self._mock_execve + os.get_exec_path = self._mock_get_exec_path + + def __exit__(self, type, value, tb): + os.execv = self.orig_execv + os.execve = self.orig_execve + os.get_exec_path = self.orig_get_exec_path + + @unittest.skipUnless(hasattr(os, '_execvpe'), + "No internal os._execvpe function to test.") + def test_internal_execvpe(self): + exec_stubbed = self._stub_out_for_execvpe_test() + with exec_stubbed: + self.assertRaises(RuntimeError, os._execvpe, os.sep+'f', ['-a']) + self.assertEqual([('execv', os.sep+'f', (['-a'],))], + exec_stubbed.calls) + exec_stubbed.calls = [] + self.assertRaises(OSError, os._execvpe, 'f', ['-a'], + env={'spam': 'beans'}) + self.assertEqual([('execve', os.sep+'p'+os.sep+'f', + (['-a'], {'spam': 'beans'})), + ('execve', os.sep+'pp'+os.sep+'f', + (['-a'], {'spam': 'beans'}))], + exec_stubbed.calls) + class Win32ErrorTests(unittest.TestCase): def test_rename(self): self.assertRaises(WindowsError, os.rename, support.TESTFN, support.TESTFN+".bak") @@ -862,6 +940,14 @@ self._kill_with_event(signal.CTRL_BREAK_EVENT, "CTRL_BREAK_EVENT") +class MiscTests(unittest.TestCase): + + @unittest.skipIf(os.name == "nt", "POSIX specific test") + def test_fsencode(self): + self.assertEquals(os.fsencode(b'ab\xff'), b'ab\xff') + self.assertEquals(os.fsencode('ab\uDCFF'), b'ab\xff') + + def test_main(): support.run_unittest( FileTests, @@ -876,7 +962,8 @@ TestInvalidFD, PosixUidGidTests, Pep383Tests, - Win32KillTests + Win32KillTests, + MiscTests, ) if __name__ == "__main__": Modified: python/branches/py3k-jit/Lib/test/test_posix.py ============================================================================== --- python/branches/py3k-jit/Lib/test/test_posix.py (original) +++ python/branches/py3k-jit/Lib/test/test_posix.py Mon May 10 23:19:57 2010 @@ -299,9 +299,13 @@ posix.lchflags(support.TESTFN, st.st_flags) def test_environ(self): + if os.name == "nt": + item_type = str + else: + item_type = bytes for k, v in posix.environ.items(): - self.assertEqual(type(k), str) - self.assertEqual(type(v), str) + self.assertEqual(type(k), item_type) + self.assertEqual(type(v), item_type) def test_getcwd_long_pathnames(self): if hasattr(posix, 'getcwd'): Modified: python/branches/py3k-jit/Lib/test/test_signal.py ============================================================================== --- python/branches/py3k-jit/Lib/test/test_signal.py (original) +++ python/branches/py3k-jit/Lib/test/test_signal.py Mon May 10 23:19:57 2010 @@ -255,48 +255,105 @@ class SiginterruptTest(unittest.TestCase): signum = signal.SIGUSR1 - def readpipe_interrupted(self, cb): + + def setUp(self): + """Install a no-op signal handler that can be set to allow + interrupts or not, and arrange for the original signal handler to be + re-installed when the test is finished. + """ + oldhandler = signal.signal(self.signum, lambda x,y: None) + self.addCleanup(signal.signal, self.signum, oldhandler) + + def readpipe_interrupted(self): + """Perform a read during which a signal will arrive. Return True if the + read is interrupted by the signal and raises an exception. Return False + if it returns normally. + """ + # Create a pipe that can be used for the read. Also clean it up + # when the test is over, since nothing else will (but see below for + # the write end). r, w = os.pipe() + self.addCleanup(os.close, r) + + # Create another process which can send a signal to this one to try + # to interrupt the read. ppid = os.getpid() pid = os.fork() - oldhandler = signal.signal(self.signum, lambda x,y: None) - cb() - if pid==0: - # child code: sleep, kill, sleep. and then exit, - # which closes the pipe from which the parent process reads + if pid == 0: + # Child code: sleep to give the parent enough time to enter the + # read() call (there's a race here, but it's really tricky to + # eliminate it); then signal the parent process. Also, sleep + # again to make it likely that the signal is delivered to the + # parent process before the child exits. If the child exits + # first, the write end of the pipe will be closed and the test + # is invalid. try: time.sleep(0.2) os.kill(ppid, self.signum) time.sleep(0.2) finally: + # No matter what, just exit as fast as possible now. exit_subprocess() - - try: + else: + # Parent code. + # Make sure the child is eventually reaped, else it'll be a + # zombie for the rest of the test suite run. + self.addCleanup(os.waitpid, pid, 0) + + # Close the write end of the pipe. The child has a copy, so + # it's not really closed until the child exits. We need it to + # close when the child exits so that in the non-interrupt case + # the read eventually completes, otherwise we could just close + # it *after* the test. os.close(w) + # Try the read and report whether it is interrupted or not to + # the caller. try: - d=os.read(r, 1) + d = os.read(r, 1) return False except OSError as err: if err.errno != errno.EINTR: raise return True - finally: - signal.signal(self.signum, oldhandler) - os.waitpid(pid, 0) def test_without_siginterrupt(self): - i=self.readpipe_interrupted(lambda: None) - self.assertEquals(i, True) + """If a signal handler is installed and siginterrupt is not called + at all, when that signal arrives, it interrupts a syscall that's in + progress. + """ + i = self.readpipe_interrupted() + self.assertTrue(i) + # Arrival of the signal shouldn't have changed anything. + i = self.readpipe_interrupted() + self.assertTrue(i) def test_siginterrupt_on(self): - i=self.readpipe_interrupted(lambda: signal.siginterrupt(self.signum, 1)) - self.assertEquals(i, True) + """If a signal handler is installed and siginterrupt is called with + a true value for the second argument, when that signal arrives, it + interrupts a syscall that's in progress. + """ + signal.siginterrupt(self.signum, 1) + i = self.readpipe_interrupted() + self.assertTrue(i) + # Arrival of the signal shouldn't have changed anything. + i = self.readpipe_interrupted() + self.assertTrue(i) def test_siginterrupt_off(self): - i=self.readpipe_interrupted(lambda: signal.siginterrupt(self.signum, 0)) - self.assertEquals(i, False) + """If a signal handler is installed and siginterrupt is called with + a false value for the second argument, when that signal arrives, it + does not interrupt a syscall that's in progress. + """ + signal.siginterrupt(self.signum, 0) + i = self.readpipe_interrupted() + self.assertFalse(i) + # Arrival of the signal shouldn't have changed anything. + i = self.readpipe_interrupted() + self.assertFalse(i) + + class ItimerTest(unittest.TestCase): def setUp(self): Modified: python/branches/py3k-jit/Lib/test/test_subprocess.py ============================================================================== --- python/branches/py3k-jit/Lib/test/test_subprocess.py (original) +++ python/branches/py3k-jit/Lib/test/test_subprocess.py Mon May 10 23:19:57 2010 @@ -803,8 +803,6 @@ def test_undecodable_env(self): for key, value in (('test', 'abc\uDCFF'), ('test\uDCFF', '42')): - value_repr = repr(value).encode("ascii") - # test str with surrogates script = "import os; print(repr(os.getenv(%s)))" % repr(key) env = os.environ.copy() @@ -813,19 +811,19 @@ [sys.executable, "-c", script], env=env) stdout = stdout.rstrip(b'\n\r') - self.assertEquals(stdout, value_repr) + self.assertEquals(stdout.decode('ascii'), repr(value)) # test bytes key = key.encode("ascii", "surrogateescape") value = value.encode("ascii", "surrogateescape") - script = "import os; print(repr(os.getenv(%s)))" % repr(key) + script = "import os; print(repr(os.getenvb(%s)))" % repr(key) env = os.environ.copy() env[key] = value stdout = subprocess.check_output( [sys.executable, "-c", script], env=env) stdout = stdout.rstrip(b'\n\r') - self.assertEquals(stdout, value_repr) + self.assertEquals(stdout.decode('ascii'), repr(value)) @unittest.skipUnless(mswindows, "Windows specific tests") Modified: python/branches/py3k-jit/Lib/test/test_sysconfig.py ============================================================================== --- python/branches/py3k-jit/Lib/test/test_sysconfig.py (original) +++ python/branches/py3k-jit/Lib/test/test_sysconfig.py Mon May 10 23:19:57 2010 @@ -234,8 +234,8 @@ self.assertTrue(os.path.isfile(config_h), config_h) def test_get_scheme_names(self): - wanted = ('nt', 'nt_user', 'os2', 'os2_home', 'posix_home', - 'posix_prefix', 'posix_user') + wanted = ('nt', 'nt_user', 'os2', 'os2_home', 'osx_framework_user', + 'posix_home', 'posix_prefix', 'posix_user') self.assertEquals(get_scheme_names(), wanted) def test_symlink(self): Modified: python/branches/py3k-jit/Lib/test/test_urllib2.py ============================================================================== --- python/branches/py3k-jit/Lib/test/test_urllib2.py (original) +++ python/branches/py3k-jit/Lib/test/test_urllib2.py Mon May 10 23:19:57 2010 @@ -684,7 +684,7 @@ try: data = r.read() headers = r.info() - newurl = r.geturl() + respurl = r.geturl() finally: r.close() stats = os.stat(TESTFN) @@ -695,6 +695,7 @@ self.assertEqual(headers["Content-type"], "text/plain") self.assertEqual(headers["Content-length"], "13") self.assertEqual(headers["Last-modified"], modified) + self.assertEqual(respurl, url) for url in [ "file://localhost:80%s" % urlpath, Modified: python/branches/py3k-jit/Lib/test/test_urlparse.py ============================================================================== --- python/branches/py3k-jit/Lib/test/test_urlparse.py (original) +++ python/branches/py3k-jit/Lib/test/test_urlparse.py Mon May 10 23:19:57 2010 @@ -6,7 +6,7 @@ RFC1808_BASE = "http://a/b/c/d;p?q#f" RFC2396_BASE = "http://a/b/c/d;p?q" -RFC3986_BASE = "http://a/b/c/d;p?q" +RFC3986_BASE = 'http://a/b/c/d;p?q' # A list of test cases. Each test case is a a two-tuple that contains # a string with the query and a dictionary with the expected result. @@ -235,14 +235,60 @@ self.checkJoin(RFC2396_BASE, 'g#s/./x', 'http://a/b/c/g#s/./x') self.checkJoin(RFC2396_BASE, 'g#s/../x', 'http://a/b/c/g#s/../x') - #The following scenarios have been updated in RFC3986 - #self.checkJoin(RFC2396_BASE, '?y', 'http://a/b/c/?y') - #self.checkJoin(RFC2396_BASE, ';x', 'http://a/b/c/;x') - - def test_RFC3986(self): + # Test cases from RFC3986 self.checkJoin(RFC3986_BASE, '?y','http://a/b/c/d;p?y') self.checkJoin(RFC2396_BASE, ';x', 'http://a/b/c/;x') + self.checkJoin(RFC3986_BASE, 'g:h','g:h') + self.checkJoin(RFC3986_BASE, 'g','http://a/b/c/g') + self.checkJoin(RFC3986_BASE, './g','http://a/b/c/g') + self.checkJoin(RFC3986_BASE, 'g/','http://a/b/c/g/') + self.checkJoin(RFC3986_BASE, '/g','http://a/g') + self.checkJoin(RFC3986_BASE, '//g','http://g') + self.checkJoin(RFC3986_BASE, '?y','http://a/b/c/d;p?y') + self.checkJoin(RFC3986_BASE, 'g?y','http://a/b/c/g?y') + self.checkJoin(RFC3986_BASE, '#s','http://a/b/c/d;p?q#s') + self.checkJoin(RFC3986_BASE, 'g#s','http://a/b/c/g#s') + self.checkJoin(RFC3986_BASE, 'g?y#s','http://a/b/c/g?y#s') + self.checkJoin(RFC3986_BASE, ';x','http://a/b/c/;x') + self.checkJoin(RFC3986_BASE, 'g;x','http://a/b/c/g;x') + self.checkJoin(RFC3986_BASE, 'g;x?y#s','http://a/b/c/g;x?y#s') + self.checkJoin(RFC3986_BASE, '','http://a/b/c/d;p?q') + self.checkJoin(RFC3986_BASE, '.','http://a/b/c/') + self.checkJoin(RFC3986_BASE, './','http://a/b/c/') + self.checkJoin(RFC3986_BASE, '..','http://a/b/') + self.checkJoin(RFC3986_BASE, '../','http://a/b/') + self.checkJoin(RFC3986_BASE, '../g','http://a/b/g') + self.checkJoin(RFC3986_BASE, '../..','http://a/') + self.checkJoin(RFC3986_BASE, '../../','http://a/') + self.checkJoin(RFC3986_BASE, '../../g','http://a/g') + + #Abnormal Examples + + # The 'abnormal scenarios' are incompatible with RFC2986 parsing + # Tests are here for reference. + + #self.checkJoin(RFC3986_BASE, '../../../g','http://a/g') + #self.checkJoin(RFC3986_BASE, '../../../../g','http://a/g') + #self.checkJoin(RFC3986_BASE, '/./g','http://a/g') + #self.checkJoin(RFC3986_BASE, '/../g','http://a/g') + + self.checkJoin(RFC3986_BASE, 'g.','http://a/b/c/g.') + self.checkJoin(RFC3986_BASE, '.g','http://a/b/c/.g') + self.checkJoin(RFC3986_BASE, 'g..','http://a/b/c/g..') + self.checkJoin(RFC3986_BASE, '..g','http://a/b/c/..g') + self.checkJoin(RFC3986_BASE, './../g','http://a/b/g') + self.checkJoin(RFC3986_BASE, './g/.','http://a/b/c/g/') + self.checkJoin(RFC3986_BASE, 'g/./h','http://a/b/c/g/h') + self.checkJoin(RFC3986_BASE, 'g/../h','http://a/b/c/h') + self.checkJoin(RFC3986_BASE, 'g;x=1/./y','http://a/b/c/g;x=1/y') + self.checkJoin(RFC3986_BASE, 'g;x=1/../y','http://a/b/c/y') + self.checkJoin(RFC3986_BASE, 'g?y/./x','http://a/b/c/g?y/./x') + self.checkJoin(RFC3986_BASE, 'g?y/../x','http://a/b/c/g?y/../x') + self.checkJoin(RFC3986_BASE, 'g#s/./x','http://a/b/c/g#s/./x') + self.checkJoin(RFC3986_BASE, 'g#s/../x','http://a/b/c/g#s/../x') + #self.checkJoin(RFC3986_BASE, 'http:g','http:g') # strict parser + self.checkJoin(RFC3986_BASE, 'http:g','http://a/b/c/g') #relaxed parser def test_RFC2732(self): for url, hostname, port in [ Modified: python/branches/py3k-jit/Lib/test/test_zlib.py ============================================================================== --- python/branches/py3k-jit/Lib/test/test_zlib.py (original) +++ python/branches/py3k-jit/Lib/test/test_zlib.py Mon May 10 23:19:57 2010 @@ -2,6 +2,7 @@ from test import support import binascii import random +from test.support import precisionbigmemtest, _1G zlib = support.import_module('zlib') @@ -93,8 +94,39 @@ self.assertRaises(ValueError, zlib.decompressobj().flush, -1) +class BaseCompressTestCase(object): + def check_big_compress_buffer(self, size, compress_func): + _1M = 1024 * 1024 + fmt = "%%0%dx" % (2 * _1M) + # Generate 10MB worth of random, and expand it by repeating it. + # The assumption is that zlib's memory is not big enough to exploit + # such spread out redundancy. + data = b''.join([random.getrandbits(8 * _1M).to_bytes(_1M, 'little') + for i in range(10)]) + data = data * (size // len(data) + 1) + try: + compress_func(data) + finally: + # Release memory + data = None + + def check_big_decompress_buffer(self, size, decompress_func): + data = b'x' * size + try: + compressed = zlib.compress(data, 1) + finally: + # Release memory + data = None + data = decompress_func(compressed) + # Sanity check + try: + self.assertEqual(len(data), size) + self.assertEqual(len(data.strip(b'x')), 0) + finally: + data = None -class CompressTestCase(unittest.TestCase): + +class CompressTestCase(BaseCompressTestCase, unittest.TestCase): # Test compression in one go (whole message compression) def test_speech(self): x = zlib.compress(HAMLET_SCENE) @@ -108,9 +140,19 @@ for ob in x, bytearray(x): self.assertEqual(zlib.decompress(ob), data) + # Memory use of the following functions takes into account overallocation + + @precisionbigmemtest(size=_1G + 1024 * 1024, memuse=3) + def test_big_compress_buffer(self, size): + compress = lambda s: zlib.compress(s, 1) + self.check_big_compress_buffer(size, compress) + + @precisionbigmemtest(size=_1G + 1024 * 1024, memuse=2) + def test_big_decompress_buffer(self, size): + self.check_big_decompress_buffer(size, zlib.decompress) -class CompressObjectTestCase(unittest.TestCase): +class CompressObjectTestCase(BaseCompressTestCase, unittest.TestCase): # Test compression object def test_pair(self): # straightforward compress/decompress objects @@ -399,6 +441,21 @@ d.flush() self.assertRaises(ValueError, d.copy) + # Memory use of the following functions takes into account overallocation + + @precisionbigmemtest(size=_1G + 1024 * 1024, memuse=3) + def test_big_compress_buffer(self, size): + c = zlib.compressobj(1) + compress = lambda s: c.compress(s) + c.flush() + self.check_big_compress_buffer(size, compress) + + @precisionbigmemtest(size=_1G + 1024 * 1024, memuse=2) + def test_big_decompress_buffer(self, size): + d = zlib.decompressobj() + decompress = lambda s: d.decompress(s) + d.flush() + self.check_big_decompress_buffer(size, decompress) + + def genblock(seed, length, step=1024, generator=random): """length-byte stream of random data from a seed (in step-byte blocks).""" if seed is not None: Modified: python/branches/py3k-jit/Lib/unittest/case.py ============================================================================== --- python/branches/py3k-jit/Lib/unittest/case.py (original) +++ python/branches/py3k-jit/Lib/unittest/case.py Mon May 10 23:19:57 2010 @@ -993,6 +993,7 @@ callable_obj(*args, **kwargs) def assertRegexpMatches(self, text, expected_regexp, msg=None): + """Fail the test unless the text matches the regular expression.""" if isinstance(expected_regexp, (str, bytes)): expected_regexp = re.compile(expected_regexp) if not expected_regexp.search(text): @@ -1001,6 +1002,7 @@ raise self.failureException(msg) def assertNotRegexpMatches(self, text, unexpected_regexp, msg=None): + """Fail the test if the text matches the regular expression.""" if isinstance(unexpected_regexp, (str, bytes)): unexpected_regexp = re.compile(unexpected_regexp) match = unexpected_regexp.search(text) Modified: python/branches/py3k-jit/Lib/unittest/loader.py ============================================================================== --- python/branches/py3k-jit/Lib/unittest/loader.py (original) +++ python/branches/py3k-jit/Lib/unittest/loader.py Mon May 10 23:19:57 2010 @@ -178,7 +178,10 @@ if not top_level_dir in sys.path: # all test modules must be importable from the top level directory - sys.path.append(top_level_dir) + # should we *unconditionally* put the start directory in first + # in sys.path to minimise likelihood of conflicts between installed + # modules and development versions? + sys.path.insert(0, top_level_dir) self._top_level_dir = top_level_dir is_not_importable = False @@ -251,6 +254,16 @@ except: yield _make_failed_import_test(name, self.suiteClass) else: + mod_file = os.path.abspath(getattr(module, '__file__', full_path)) + 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] + expected_dir = os.path.dirname(full_path) + msg = ("%r module incorrectly imported from %r. Expected %r. " + "Is this module globally installed?") + raise ImportError(msg % (mod_name, module_dir, expected_dir)) yield self.loadTestsFromModule(module) elif os.path.isdir(full_path): if not os.path.isfile(os.path.join(full_path, '__init__.py')): Modified: python/branches/py3k-jit/Lib/unittest/main.py ============================================================================== --- python/branches/py3k-jit/Lib/unittest/main.py (original) +++ python/branches/py3k-jit/Lib/unittest/main.py Mon May 10 23:19:57 2010 @@ -70,10 +70,10 @@ # defaults for testing failfast = catchbreak = buffer = None - def __init__(self, module='__main__', defaultTest=None, - argv=None, testRunner=None, - testLoader=loader.defaultTestLoader, exit=True, - verbosity=1, failfast=None, catchbreak=None, buffer=None): + def __init__(self, module='__main__', defaultTest=None, argv=None, + testRunner=None, testLoader=loader.defaultTestLoader, + exit=True, verbosity=1, failfast=None, catchbreak=None, + buffer=None): if isinstance(module, str): self.module = __import__(module) for part in module.split('.')[1:]: Modified: python/branches/py3k-jit/Lib/unittest/suite.py ============================================================================== --- python/branches/py3k-jit/Lib/unittest/suite.py (original) +++ python/branches/py3k-jit/Lib/unittest/suite.py Mon May 10 23:19:57 2010 @@ -116,7 +116,12 @@ if getattr(currentClass, "__unittest_skip__", False): return - currentClass._classSetupFailed = False + try: + currentClass._classSetupFailed = False + except TypeError: + # test may actually be a function + # so its class will be a builtin-type + pass setUpClass = getattr(currentClass, 'setUpClass', None) if setUpClass is not None: Modified: python/branches/py3k-jit/Lib/unittest/test/test_discovery.py ============================================================================== --- python/branches/py3k-jit/Lib/unittest/test/test_discovery.py (original) +++ python/branches/py3k-jit/Lib/unittest/test/test_discovery.py Mon May 10 23:19:57 2010 @@ -1,4 +1,5 @@ import os +import re import sys import unittest @@ -53,8 +54,9 @@ loader._get_module_from_name = lambda path: path + ' module' loader.loadTestsFromModule = lambda module: module + ' tests' - loader._top_level_dir = '/foo' - suite = list(loader._find_tests('/foo', 'test*.py')) + top_level = os.path.abspath('/foo') + loader._top_level_dir = top_level + suite = list(loader._find_tests(top_level, 'test*.py')) expected = [name + ' module tests' for name in ('test1', 'test2')] @@ -294,6 +296,63 @@ self.assertTrue(program.failfast) self.assertTrue(program.catchbreak) + def test_detect_module_clash(self): + class Module(object): + __file__ = 'bar/foo.py' + sys.modules['foo'] = Module + full_path = os.path.abspath('foo') + original_listdir = os.listdir + original_isfile = os.path.isfile + original_isdir = os.path.isdir + + def cleanup(): + os.listdir = original_listdir + os.path.isfile = original_isfile + os.path.isdir = original_isdir + del sys.modules['foo'] + if full_path in sys.path: + sys.path.remove(full_path) + self.addCleanup(cleanup) + + def listdir(_): + return ['foo.py'] + def isfile(_): + return True + def isdir(_): + return True + os.listdir = listdir + os.path.isfile = isfile + os.path.isdir = isdir + + loader = unittest.TestLoader() + + mod_dir = os.path.abspath('bar') + expected_dir = os.path.abspath('foo') + msg = re.escape(r"'foo' module incorrectly imported from %r. Expected %r. " + "Is this module globally installed?" % (mod_dir, expected_dir)) + self.assertRaisesRegexp( + ImportError, '^%s$' % msg, loader.discover, + start_dir='foo', pattern='foo.py' + ) + self.assertEqual(sys.path[0], full_path) + + + def test_discovery_from_dotted_path(self): + loader = unittest.TestLoader() + + tests = [self] + expectedPath = os.path.abspath(os.path.dirname(unittest.test.__file__)) + + self.wasRun = False + def _find_tests(start_dir, pattern): + self.wasRun = True + self.assertEqual(start_dir, expectedPath) + return tests + loader._find_tests = _find_tests + suite = loader.discover('unittest.test') + self.assertTrue(self.wasRun) + self.assertEqual(suite._tests, tests) + if __name__ == '__main__': unittest.main() Modified: python/branches/py3k-jit/Lib/unittest/test/test_program.py ============================================================================== --- python/branches/py3k-jit/Lib/unittest/test/test_program.py (original) +++ python/branches/py3k-jit/Lib/unittest/test/test_program.py Mon May 10 23:19:57 2010 @@ -1,10 +1,28 @@ import io +import os +import sys import unittest class Test_TestProgram(unittest.TestCase): + def test_discovery_from_dotted_path(self): + loader = unittest.TestLoader() + + tests = [self] + expectedPath = os.path.abspath(os.path.dirname(unittest.test.__file__)) + + self.wasRun = False + def _find_tests(start_dir, pattern): + self.wasRun = True + self.assertEqual(start_dir, expectedPath) + return tests + loader._find_tests = _find_tests + suite = loader.discover('unittest.test') + self.assertTrue(self.wasRun) + self.assertEqual(suite._tests, tests) + # Horrible white box test def testNoExit(self): result = object() @@ -72,3 +90,166 @@ argv=["foobar"], testRunner=unittest.TextTestRunner(stream=io.StringIO()), testLoader=self.FooBarLoader()) + + +class InitialisableProgram(unittest.TestProgram): + exit = False + result = None + verbosity = 1 + defaultTest = None + testRunner = None + testLoader = unittest.defaultTestLoader + progName = 'test' + test = 'test' + def __init__(self, *args): + pass + +RESULT = object() + +class FakeRunner(object): + initArgs = None + test = None + raiseError = False + + def __init__(self, **kwargs): + FakeRunner.initArgs = kwargs + if FakeRunner.raiseError: + FakeRunner.raiseError = False + raise TypeError + + def run(self, test): + FakeRunner.test = test + return RESULT + +class TestCommandLineArgs(unittest.TestCase): + + def setUp(self): + self.program = InitialisableProgram() + self.program.createTests = lambda: None + FakeRunner.initArgs = None + FakeRunner.test = None + FakeRunner.raiseError = False + + def testHelpAndUnknown(self): + program = self.program + def usageExit(msg=None): + program.msg = msg + program.exit = True + program.usageExit = usageExit + + for opt in '-h', '-H', '--help': + program.exit = False + program.parseArgs([None, opt]) + self.assertTrue(program.exit) + self.assertIsNone(program.msg) + + program.parseArgs([None, '-$']) + self.assertTrue(program.exit) + self.assertIsNotNone(program.msg) + + def testVerbosity(self): + program = self.program + + for opt in '-q', '--quiet': + program.verbosity = 1 + program.parseArgs([None, opt]) + self.assertEqual(program.verbosity, 0) + + for opt in '-v', '--verbose': + program.verbosity = 1 + program.parseArgs([None, opt]) + self.assertEqual(program.verbosity, 2) + + def testBufferCatchFailfast(self): + program = self.program + for arg, attr in (('buffer', 'buffer'), ('failfast', 'failfast'), + ('catch', 'catchbreak')): + if attr == 'catch' and not hasInstallHandler: + continue + + short_opt = '-%s' % arg[0] + long_opt = '--%s' % arg + for opt in short_opt, long_opt: + setattr(program, attr, None) + + program.parseArgs([None, opt]) + self.assertTrue(getattr(program, attr)) + + for opt in short_opt, long_opt: + not_none = object() + setattr(program, attr, not_none) + + program.parseArgs([None, opt]) + self.assertEqual(getattr(program, attr), not_none) + + def testRunTestsRunnerClass(self): + program = self.program + + program.testRunner = FakeRunner + program.verbosity = 'verbosity' + program.failfast = 'failfast' + program.buffer = 'buffer' + + program.runTests() + + self.assertEqual(FakeRunner.initArgs, {'verbosity': 'verbosity', + 'failfast': 'failfast', + 'buffer': 'buffer'}) + self.assertEqual(FakeRunner.test, 'test') + self.assertIs(program.result, RESULT) + + def testRunTestsRunnerInstance(self): + program = self.program + + program.testRunner = FakeRunner() + FakeRunner.initArgs = None + + program.runTests() + + # A new FakeRunner should not have been instantiated + self.assertIsNone(FakeRunner.initArgs) + + self.assertEqual(FakeRunner.test, 'test') + self.assertIs(program.result, RESULT) + + def testRunTestsOldRunnerClass(self): + program = self.program + + FakeRunner.raiseError = True + program.testRunner = FakeRunner + program.verbosity = 'verbosity' + program.failfast = 'failfast' + program.buffer = 'buffer' + program.test = 'test' + + program.runTests() + + # If initialising raises a type error it should be retried + # without the new keyword arguments + self.assertEqual(FakeRunner.initArgs, {}) + self.assertEqual(FakeRunner.test, 'test') + self.assertIs(program.result, RESULT) + + def testCatchBreakInstallsHandler(self): + module = sys.modules['unittest.main'] + original = module.installHandler + def restore(): + module.installHandler = original + self.addCleanup(restore) + + self.installed = False + def fakeInstallHandler(): + self.installed = True + module.installHandler = fakeInstallHandler + + program = self.program + program.catchbreak = True + + program.testRunner = FakeRunner + + program.runTests() + self.assertTrue(self.installed) + + +if __name__ == '__main__': + unittest.main() Modified: python/branches/py3k-jit/Lib/unittest/test/test_runner.py ============================================================================== --- python/branches/py3k-jit/Lib/unittest/test/test_runner.py (original) +++ python/branches/py3k-jit/Lib/unittest/test/test_runner.py Mon May 10 23:19:57 2010 @@ -114,6 +114,52 @@ class Test_TextTestRunner(unittest.TestCase): """Tests for TextTestRunner.""" + def test_init(self): + runner = unittest.TextTestRunner() + self.assertFalse(runner.failfast) + self.assertFalse(runner.buffer) + self.assertEqual(runner.verbosity, 1) + self.assertTrue(runner.descriptions) + self.assertEqual(runner.resultclass, unittest.TextTestResult) + + + def testBufferAndFailfast(self): + class Test(unittest.TestCase): + def testFoo(self): + pass + result = unittest.TestResult() + runner = unittest.TextTestRunner(stream=io.StringIO(), failfast=True, + buffer=True) + # Use our result object + runner._makeResult = lambda: result + runner.run(Test('testFoo')) + + self.assertTrue(result.failfast) + self.assertTrue(result.buffer) + + def testRunnerRegistersResult(self): + class Test(unittest.TestCase): + def testFoo(self): + pass + originalRegisterResult = unittest.runner.registerResult + def cleanup(): + unittest.runner.registerResult = originalRegisterResult + self.addCleanup(cleanup) + + result = unittest.TestResult() + runner = unittest.TextTestRunner(stream=io.StringIO()) + # Use our result object + runner._makeResult = lambda: result + + self.wasRegistered = 0 + def fakeRegisterResult(thisResult): + self.wasRegistered += 1 + self.assertEqual(thisResult, result) + unittest.runner.registerResult = fakeRegisterResult + + runner.run(unittest.TestSuite()) + self.assertEqual(self.wasRegistered, 1) + def test_works_with_result_without_startTestRun_stopTestRun(self): class OldTextResult(ResultWithNoStartTestRunStopTestRun): separator2 = '' Modified: python/branches/py3k-jit/Lib/unittest/test/test_suite.py ============================================================================== --- python/branches/py3k-jit/Lib/unittest/test/test_suite.py (original) +++ python/branches/py3k-jit/Lib/unittest/test/test_suite.py Mon May 10 23:19:57 2010 @@ -1,5 +1,6 @@ import unittest +import sys from .support import LoggingResult, TestEquality @@ -289,3 +290,60 @@ def test_addTests__string(self): suite = unittest.TestSuite() self.assertRaises(TypeError, suite.addTests, "foo") + + def test_function_in_suite(self): + def f(_): + pass + suite = unittest.TestSuite() + suite.addTest(f) + + # when the bug is fixed this line will not crash + suite.run(unittest.TestResult()) + + + + def test_basetestsuite(self): + class Test(unittest.TestCase): + wasSetUp = False + wasTornDown = False + @classmethod + def setUpClass(cls): + cls.wasSetUp = True + @classmethod + def tearDownClass(cls): + cls.wasTornDown = True + def testPass(self): + pass + def testFail(self): + fail + class Module(object): + wasSetUp = False + wasTornDown = False + @staticmethod + def setUpModule(): + Module.wasSetUp = True + @staticmethod + def tearDownModule(): + Module.wasTornDown = True + + Test.__module__ = 'Module' + sys.modules['Module'] = Module + self.addCleanup(sys.modules.pop, 'Module') + + suite = unittest.BaseTestSuite() + suite.addTests([Test('testPass'), Test('testFail')]) + self.assertEqual(suite.countTestCases(), 2) + + result = unittest.TestResult() + suite.run(result) + self.assertFalse(Module.wasSetUp) + self.assertFalse(Module.wasTornDown) + self.assertFalse(Test.wasSetUp) + self.assertFalse(Test.wasTornDown) + self.assertEqual(len(result.errors), 1) + self.assertEqual(len(result.failures), 0) + self.assertEqual(result.testsRun, 2) + + +if __name__ == '__main__': + unittest.main() Modified: python/branches/py3k-jit/Lib/urllib/request.py ============================================================================== --- python/branches/py3k-jit/Lib/urllib/request.py (original) +++ python/branches/py3k-jit/Lib/urllib/request.py Mon May 10 23:19:57 2010 @@ -1202,13 +1202,13 @@ import email.utils import mimetypes host = req.host - file = req.selector - localfile = url2pathname(file) + filename = req.selector + localfile = url2pathname(filename) try: stats = os.stat(localfile) size = stats.st_size modified = email.utils.formatdate(stats.st_mtime, usegmt=True) - mtype = mimetypes.guess_type(file)[0] + mtype = mimetypes.guess_type(filename)[0] headers = email.message_from_string( 'Content-type: %s\nContent-length: %d\nLast-modified: %s\n' % (mtype or 'text/plain', size, modified)) @@ -1216,7 +1216,11 @@ host, port = splitport(host) if not host or \ (not port and _safe_gethostbyname(host) in self.get_names()): - return addinfourl(open(localfile, 'rb'), headers, 'file:'+file) + if host: + origurl = 'file://' + host + filename + else: + origurl = 'file://' + filename + return addinfourl(open(localfile, 'rb'), headers, origurl) except OSError as msg: # users shouldn't expect OSErrors coming from urlopen() raise URLError(msg) @@ -2155,7 +2159,7 @@ def ip2num(ipAddr): parts = ipAddr.split('.') - parts = map(int, parts) + parts = list(map(int, parts)) if len(parts) != 4: parts = (parts + [0, 0, 0, 0])[:4] return (parts[0] << 24) | (parts[1] << 16) | (parts[2] << 8) | parts[3] Modified: python/branches/py3k-jit/Misc/NEWS ============================================================================== --- python/branches/py3k-jit/Misc/NEWS (original) +++ python/branches/py3k-jit/Misc/NEWS Mon May 10 23:19:57 2010 @@ -290,6 +290,9 @@ - Issue #7072: isspace(0xa0) is true on Mac OS X +- Issue #8084: PEP 370 now conforms to system conventions for framework + builds on MacOS X. That is, "python setup.py install --user" will install + into "~/Library/Python/2.7" instead of "~/.local". C-API ----- @@ -348,6 +351,21 @@ Library ------- +- Issue #8664: In py_compile, create __pycache__ when the compiled path is + given. + +- Issue #8514: Add os.fsencode() function (Unix only): encode a string to bytes + for use in the file system, environment variables or the command line. + +- Issue #8571: Fix an internal error when compressing or decompressing a + chunk larger than 1GB with the zlib module's compressor and decompressor + objects. + +- Issue #8603: Support bytes environmental variables on Unix: Add os.environb + mapping and os.getenvb() function. os.unsetenv() encodes str argument to the + file system encoding with the surrogateescape error handler (instead of + utf8/strict) and accepts bytes. posix.environ keys and values are now bytes. + - Issue #8573: asyncore _strerror() function might throw ValueError. - Issue #8483: asyncore.dispatcher's __getattr__ method produced confusing @@ -379,6 +397,9 @@ - Issue #4687: Fix accuracy of garbage collection runtimes displayed with gc.DEBUG_STATS. +- Issue #8354: The siginterrupt setting is now preserved for all signals, + not just SIGCHLD. + - Issue #7192: webbrowser.get("firefox") now wors on Mac OS X, as does webbrowser.get("safari"). @@ -1090,6 +1111,11 @@ Extension Modules ----------------- +- Issue #8644: The accuracy of td.total_seconds() has been improved (by + calculating with integer arithmetic instead of float arithmetic internally): + the result is now always correctly rounded, and is equivalent to td / + timedelta(seconds=1). + - Issue #2706: Allow division of a timedelta by another timedelta: timedelta / timedelta, timedelta % timedelta, timedelta // timedelta and divmod(timedelta, timedelta) are all supported. Modified: python/branches/py3k-jit/Modules/datetimemodule.c ============================================================================== --- python/branches/py3k-jit/Modules/datetimemodule.c (original) +++ python/branches/py3k-jit/Modules/datetimemodule.c Mon May 10 23:19:57 2010 @@ -2211,9 +2211,25 @@ static PyObject * delta_total_seconds(PyObject *self) { - return PyFloat_FromDouble(GET_TD_MICROSECONDS(self) / 1000000.0 + - GET_TD_SECONDS(self) + - GET_TD_DAYS(self) * 24.0 * 3600.0); + PyObject *total_seconds; + PyObject *total_microseconds; + PyObject *one_million; + + total_microseconds = delta_to_microseconds((PyDateTime_Delta *)self); + if (total_microseconds == NULL) + return NULL; + + one_million = PyLong_FromLong(1000000L); + if (one_million == NULL) { + Py_DECREF(total_microseconds); + return NULL; + } + + total_seconds = PyNumber_TrueDivide(total_microseconds, one_million); + + Py_DECREF(total_microseconds); + Py_DECREF(one_million); + return total_seconds; } static PyObject * Modified: python/branches/py3k-jit/Modules/grpmodule.c ============================================================================== --- python/branches/py3k-jit/Modules/grpmodule.c (original) +++ python/branches/py3k-jit/Modules/grpmodule.c Mon May 10 23:19:57 2010 @@ -46,11 +46,8 @@ Py_DECREF(v); return NULL; } -#define FSDECODE(val) PyUnicode_Decode(val, strlen(val),\ - Py_FileSystemDefaultEncoding,\ - "surrogateescape") for (member = p->gr_mem; *member != NULL; member++) { - PyObject *x = FSDECODE(*member); + PyObject *x = PyUnicode_DecodeFSDefault(*member); if (x == NULL || PyList_Append(w, x) != 0) { Py_XDECREF(x); Py_DECREF(w); @@ -61,13 +58,13 @@ } #define SET(i,val) PyStructSequence_SET_ITEM(v, i, val) - SET(setIndex++, FSDECODE(p->gr_name)); + SET(setIndex++, PyUnicode_DecodeFSDefault(p->gr_name)); #ifdef __VMS SET(setIndex++, Py_None); Py_INCREF(Py_None); #else if (p->gr_passwd) - SET(setIndex++, FSDECODE(p->gr_passwd)); + SET(setIndex++, PyUnicode_DecodeFSDefault(p->gr_passwd)); else { SET(setIndex++, Py_None); Py_INCREF(Py_None); Modified: python/branches/py3k-jit/Modules/posixmodule.c ============================================================================== --- python/branches/py3k-jit/Modules/posixmodule.c (original) +++ python/branches/py3k-jit/Modules/posixmodule.c Mon May 10 23:19:57 2010 @@ -498,14 +498,12 @@ char *p = strchr(*e, '='); if (p == NULL) continue; - k = PyUnicode_Decode(*e, (int)(p-*e), - Py_FileSystemDefaultEncoding, "surrogateescape"); + k = PyBytes_FromStringAndSize(*e, (int)(p-*e)); if (k == NULL) { PyErr_Clear(); continue; } - v = PyUnicode_Decode(p+1, strlen(p+1), - Py_FileSystemDefaultEncoding, "surrogateescape"); + v = PyBytes_FromStringAndSize(p+1, strlen(p+1)); if (v == NULL) { PyErr_Clear(); Py_DECREF(k); @@ -561,9 +559,13 @@ static PyObject * posix_error_with_allocated_filename(PyObject* name) { - PyObject *rc = PyErr_SetFromErrnoWithFilename(PyExc_OSError, - PyBytes_AsString(name)); + PyObject *name_str, *rc; + name_str = PyUnicode_DecodeFSDefaultAndSize(PyBytes_AsString(name), + PyBytes_GET_SIZE(name)); Py_DECREF(name); + rc = PyErr_SetFromErrnoWithFilenameObject(PyExc_OSError, + name_str); + Py_XDECREF(name_str); return rc; } @@ -2033,7 +2035,7 @@ return posix_error(); if (use_bytes) return PyBytes_FromStringAndSize(buf, strlen(buf)); - return PyUnicode_Decode(buf, strlen(buf), Py_FileSystemDefaultEncoding,"surrogateescape"); + return PyUnicode_DecodeFSDefault(buf); } PyDoc_STRVAR(posix_getcwd__doc__, @@ -5301,7 +5303,7 @@ char *s1, *s2; char *newenv; #endif - PyObject *newstr; + PyObject *newstr = NULL; size_t len; #ifdef MS_WINDOWS @@ -5324,15 +5326,19 @@ APIRET rc; rc = DosSetExtLIBPATH(s2, BEGIN_LIBPATH); - if (rc != NO_ERROR) - return os2_error(rc); + if (rc != NO_ERROR) { + os2_error(rc); + goto error; + } } else if (stricmp(s1, "ENDLIBPATH") == 0) { APIRET rc; rc = DosSetExtLIBPATH(s2, END_LIBPATH); - if (rc != NO_ERROR) - return os2_error(rc); + if (rc != NO_ERROR) { + os2_error(rc); + goto error; + } } else { #endif /* XXX This can leak memory -- not easy to fix :-( */ @@ -5342,36 +5348,40 @@ len = wcslen(s1) + wcslen(s2) + 2; newstr = PyUnicode_FromUnicode(NULL, (int)len - 1); #else - len = strlen(s1) + strlen(s2) + 2; + len = PyBytes_GET_SIZE(os1) + PyBytes_GET_SIZE(os2) + 2; newstr = PyBytes_FromStringAndSize(NULL, (int)len - 1); #endif - if (newstr == NULL) - return PyErr_NoMemory(); + if (newstr == NULL) { + PyErr_NoMemory(); + goto error; + } #ifdef MS_WINDOWS newenv = PyUnicode_AsUnicode(newstr); _snwprintf(newenv, len, L"%s=%s", s1, s2); if (_wputenv(newenv)) { - Py_DECREF(newstr); posix_error(); - return NULL; + goto error; } #else newenv = PyBytes_AS_STRING(newstr); PyOS_snprintf(newenv, len, "%s=%s", s1, s2); if (putenv(newenv)) { - Py_DECREF(newstr); - Py_DECREF(os1); - Py_DECREF(os2); posix_error(); - return NULL; + goto error; } #endif + /* Install the first arg and newstr in posix_putenv_garbage; * this will cause previous value to be collected. This has to * happen after the real putenv() call because the old value * was still accessible until then. */ if (PyDict_SetItem(posix_putenv_garbage, - PyTuple_GET_ITEM(args, 0), newstr)) { +#ifdef MS_WINDOWS + PyTuple_GET_ITEM(args, 0), +#else + os1, +#endif + newstr)) { /* really not much we can do; just leak */ PyErr_Clear(); } @@ -5382,12 +5392,20 @@ #if defined(PYOS_OS2) } #endif + #ifndef MS_WINDOWS Py_DECREF(os1); Py_DECREF(os2); #endif - Py_INCREF(Py_None); - return Py_None; + Py_RETURN_NONE; + +error: +#ifndef MS_WINDOWS + Py_DECREF(os1); + Py_DECREF(os2); +#endif + Py_XDECREF(newstr); + return NULL; } #endif /* putenv */ @@ -5399,10 +5417,20 @@ static PyObject * posix_unsetenv(PyObject *self, PyObject *args) { +#ifdef MS_WINDOWS char *s1; if (!PyArg_ParseTuple(args, "s:unsetenv", &s1)) return NULL; +#else + PyObject *os1; + char *s1; + + if (!PyArg_ParseTuple(args, "O&:unsetenv", + PyUnicode_FSConverter, &os1)) + return NULL; + s1 = PyBytes_AsString(os1); +#endif unsetenv(s1); @@ -5412,13 +5440,20 @@ * old value was still accessible until then. */ if (PyDict_DelItem(posix_putenv_garbage, - PyTuple_GET_ITEM(args, 0))) { +#ifdef MS_WINDOWS + PyTuple_GET_ITEM(args, 0) +#else + os1 +#endif + )) { /* really not much we can do; just leak */ PyErr_Clear(); } - Py_INCREF(Py_None); - return Py_None; +#ifndef MS_WINDOWS + Py_DECREF(os1); +#endif + Py_RETURN_NONE; } #endif /* unsetenv */ Modified: python/branches/py3k-jit/Modules/pwdmodule.c ============================================================================== --- python/branches/py3k-jit/Modules/pwdmodule.c (original) +++ python/branches/py3k-jit/Modules/pwdmodule.c Mon May 10 23:19:57 2010 @@ -49,9 +49,7 @@ sets(PyObject *v, int i, const char* val) { if (val) { - PyObject *o = PyUnicode_Decode(val, strlen(val), - Py_FileSystemDefaultEncoding, - "surrogateescape"); + PyObject *o = PyUnicode_DecodeFSDefault(val); PyStructSequence_SET_ITEM(v, i, o); } else { Modified: python/branches/py3k-jit/Modules/signalmodule.c ============================================================================== --- python/branches/py3k-jit/Modules/signalmodule.c (original) +++ python/branches/py3k-jit/Modules/signalmodule.c Mon May 10 23:19:57 2010 @@ -198,7 +198,12 @@ return; } #endif +#ifndef HAVE_SIGACTION + /* If the handler was not set up with sigaction, reinstall it. See + * Python/pythonrun.c for the implementation of PyOS_setsig which + * makes this true. See also issue8354. */ PyOS_setsig(sig_num, signal_handler); +#endif } Modified: python/branches/py3k-jit/Modules/spwdmodule.c ============================================================================== --- python/branches/py3k-jit/Modules/spwdmodule.c (original) +++ python/branches/py3k-jit/Modules/spwdmodule.c Mon May 10 23:19:57 2010 @@ -60,9 +60,7 @@ sets(PyObject *v, int i, const char* val) { if (val) { - PyObject *o = PyUnicode_Decode(val, strlen(val), - Py_FileSystemDefaultEncoding, - "surrogateescape"); + PyObject *o = PyUnicode_DecodeFSDefault(val); PyStructSequence_SET_ITEM(v, i, o); } else { PyStructSequence_SET_ITEM(v, i, Py_None); Modified: python/branches/py3k-jit/Modules/zlibmodule.c ============================================================================== --- python/branches/py3k-jit/Modules/zlibmodule.c (original) +++ python/branches/py3k-jit/Modules/zlibmodule.c Mon May 10 23:19:57 2010 @@ -396,7 +396,8 @@ static PyObject * PyZlib_objcompress(compobject *self, PyObject *args) { - int err, inplen, length = DEFAULTALLOC; + int err, inplen; + Py_ssize_t length = DEFAULTALLOC; PyObject *RetVal; Py_buffer pinput; Byte *input; @@ -477,8 +478,8 @@ static PyObject * PyZlib_objdecompress(compobject *self, PyObject *args) { - int err, inplen, old_length, length = DEFAULTALLOC; - int max_length = 0; + int err, inplen, max_length = 0; + Py_ssize_t old_length, length = DEFAULTALLOC; PyObject *RetVal; Py_buffer pinput; Byte *input; Modified: python/branches/py3k-jit/Objects/codeobject.c ============================================================================== --- python/branches/py3k-jit/Objects/codeobject.c (original) +++ python/branches/py3k-jit/Objects/codeobject.c Mon May 10 23:19:57 2010 @@ -340,16 +340,20 @@ static PyObject * code_repr(PyCodeObject *co) { - int lineno = -1; - char *filename = "???"; - + int lineno; if (co->co_firstlineno != 0) lineno = co->co_firstlineno; - if (co->co_filename && PyUnicode_Check(co->co_filename)) - filename = _PyUnicode_AsString(co->co_filename); - return PyUnicode_FromFormat( - "", - co->co_name, co, filename, lineno); + else + lineno = -1; + if (co->co_filename && PyUnicode_Check(co->co_filename)) { + return PyUnicode_FromFormat( + "", + co->co_name, co, co->co_filename, lineno); + } else { + return PyUnicode_FromFormat( + "", + co->co_name, co, lineno); + } } static PyObject * Modified: python/branches/py3k-jit/Objects/longobject.c ============================================================================== --- python/branches/py3k-jit/Objects/longobject.c (original) +++ python/branches/py3k-jit/Objects/longobject.c Mon May 10 23:19:57 2010 @@ -2492,10 +2492,7 @@ Py_ssize_t sign; if (Py_SIZE(a) != Py_SIZE(b)) { - if (ABS(Py_SIZE(a)) == 0 && ABS(Py_SIZE(b)) == 0) - sign = 0; - else - sign = Py_SIZE(a) - Py_SIZE(b); + sign = Py_SIZE(a) - Py_SIZE(b); } else { Py_ssize_t i = ABS(Py_SIZE(a)); @@ -3772,7 +3769,7 @@ static int long_bool(PyLongObject *v) { - return ABS(Py_SIZE(v)) != 0; + return Py_SIZE(v) != 0; } static PyObject * Modified: python/branches/py3k-jit/Objects/moduleobject.c ============================================================================== --- python/branches/py3k-jit/Objects/moduleobject.c (original) +++ python/branches/py3k-jit/Objects/moduleobject.c Mon May 10 23:19:57 2010 @@ -191,8 +191,8 @@ return _PyUnicode_AsString(nameobj); } -const char * -PyModule_GetFilename(PyObject *m) +static PyObject* +module_getfilename(PyObject *m) { PyObject *d; PyObject *fileobj; @@ -208,6 +208,16 @@ PyErr_SetString(PyExc_SystemError, "module filename missing"); return NULL; } + return fileobj; +} + +const char * +PyModule_GetFilename(PyObject *m) +{ + PyObject *fileobj; + fileobj = module_getfilename(m); + if (fileobj == NULL) + return NULL; return _PyUnicode_AsString(fileobj); } @@ -327,19 +337,19 @@ module_repr(PyModuleObject *m) { const char *name; - const char *filename; + PyObject *filename; name = PyModule_GetName((PyObject *)m); if (name == NULL) { PyErr_Clear(); name = "?"; } - filename = PyModule_GetFilename((PyObject *)m); + filename = module_getfilename((PyObject *)m); if (filename == NULL) { PyErr_Clear(); return PyUnicode_FromFormat("", name); } - return PyUnicode_FromFormat("", name, filename); + return PyUnicode_FromFormat("", name, filename); } static int Modified: python/branches/py3k-jit/Python/errors.c ============================================================================== --- python/branches/py3k-jit/Python/errors.c (original) +++ python/branches/py3k-jit/Python/errors.c Mon May 10 23:19:57 2010 @@ -446,7 +446,7 @@ PyObject * PyErr_SetFromErrnoWithFilename(PyObject *exc, const char *filename) { - PyObject *name = filename ? PyUnicode_FromString(filename) : NULL; + PyObject *name = filename ? PyUnicode_DecodeFSDefault(filename) : NULL; PyObject *result = PyErr_SetFromErrnoWithFilenameObject(exc, name); Py_XDECREF(name); return result; Modified: python/branches/py3k-jit/Python/pythonrun.c ============================================================================== --- python/branches/py3k-jit/Python/pythonrun.c (original) +++ python/branches/py3k-jit/Python/pythonrun.c Mon May 10 23:19:57 2010 @@ -1896,7 +1896,7 @@ err_input(perrdetail *err) { PyObject *v, *w, *errtype, *errtext; - PyObject* u = NULL; + PyObject *msg_obj = NULL; char *msg = NULL; errtype = PyExc_SyntaxError; switch (err->error) { @@ -1952,14 +1952,9 @@ case E_DECODE: { PyObject *type, *value, *tb; PyErr_Fetch(&type, &value, &tb); - if (value != NULL) { - u = PyObject_Str(value); - if (u != NULL) { - msg = _PyUnicode_AsString(u); - } - } - if (msg == NULL) - msg = "unknown decode error"; + msg = "unknown decode error"; + if (value != NULL) + msg_obj = PyObject_Str(value); Py_XDECREF(type); Py_XDECREF(value); Py_XDECREF(tb); @@ -1988,14 +1983,18 @@ } v = Py_BuildValue("(ziiN)", err->filename, err->lineno, err->offset, errtext); - w = NULL; - if (v != NULL) - w = Py_BuildValue("(sO)", msg, v); - Py_XDECREF(u); + if (v != NULL) { + if (msg_obj) + w = Py_BuildValue("(OO)", msg_obj, v); + else + w = Py_BuildValue("(sO)", msg, v); + } else + w = NULL; Py_XDECREF(v); PyErr_SetObject(errtype, w); Py_XDECREF(w); cleanup: + Py_XDECREF(msg_obj); if (err->text != NULL) { PyObject_FREE(err->text); err->text = NULL; @@ -2255,6 +2254,10 @@ PyOS_setsig(int sig, PyOS_sighandler_t handler) { #ifdef HAVE_SIGACTION + /* Some code in Modules/signalmodule.c depends on sigaction() being + * used here if HAVE_SIGACTION is defined. Fix that if this code + * changes to invalidate that assumption. + */ struct sigaction context, ocontext; context.sa_handler = handler; sigemptyset(&context.sa_mask); From python-checkins at python.org Mon May 10 23:27:53 2010 From: python-checkins at python.org (mark.dickinson) Date: Mon, 10 May 2010 23:27:53 +0200 (CEST) Subject: [Python-checkins] r81063 - in python/branches/py3k: Objects/longobject.c Message-ID: <20100510212753.DFB0FEE9F4@mail.python.org> Author: mark.dickinson Date: Mon May 10 23:27:53 2010 New Revision: 81063 Log: Merged revisions 81036 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r81036 | mark.dickinson | 2010-05-09 21:30:29 +0100 (Sun, 09 May 2010) | 1 line Post-detabification cleanup: whitespace fixes and long line rewraps only. ........ Modified: python/branches/py3k/ (props changed) python/branches/py3k/Objects/longobject.c Modified: python/branches/py3k/Objects/longobject.c ============================================================================== --- python/branches/py3k/Objects/longobject.c (original) +++ python/branches/py3k/Objects/longobject.c Mon May 10 23:27:53 2010 @@ -278,12 +278,12 @@ neg = 0; if (Py_IS_INFINITY(dval)) { PyErr_SetString(PyExc_OverflowError, - "cannot convert float infinity to integer"); + "cannot convert float infinity to integer"); return NULL; } if (Py_IS_NAN(dval)) { PyErr_SetString(PyExc_ValueError, - "cannot convert float NaN to integer"); + "cannot convert float NaN to integer"); return NULL; } if (dval < 0.0) { @@ -404,7 +404,7 @@ /* res is already set to -1 */ } } - exit: + exit: if (do_decref) { Py_DECREF(vv); } @@ -474,7 +474,7 @@ } /* else overflow */ - overflow: + overflow: PyErr_SetString(PyExc_OverflowError, "Python int too large to convert to C ssize_t"); return -1; @@ -504,7 +504,7 @@ x = 0; if (i < 0) { PyErr_SetString(PyExc_OverflowError, - "can't convert negative value to unsigned int"); + "can't convert negative value to unsigned int"); return (unsigned long) -1; } switch (i) { @@ -516,7 +516,8 @@ x = (x << PyLong_SHIFT) | v->ob_digit[i]; if ((x >> PyLong_SHIFT) != prev) { PyErr_SetString(PyExc_OverflowError, - "python int too large to convert to C unsigned long"); + "python int too large to convert " + "to C unsigned long"); return (unsigned long) -1; } } @@ -671,7 +672,7 @@ } return result; -Overflow: + Overflow: PyErr_SetString(PyExc_OverflowError, "int has too many bits " "to express in a platform size_t"); return (size_t)-1; @@ -681,7 +682,7 @@ _PyLong_FromByteArray(const unsigned char* bytes, size_t n, int little_endian, int is_signed) { - const unsigned char* pstartbyte;/* LSB of bytes */ + const unsigned char* pstartbyte; /* LSB of bytes */ int incr; /* direction to move pstartbyte */ const unsigned char* pendbyte; /* MSB of bytes */ size_t numsignificantbytes; /* number of bytes that matter */ @@ -769,8 +770,7 @@ if (accumbits >= PyLong_SHIFT) { /* There's enough to fill a Python digit. */ assert(idigit < ndigits); - v->ob_digit[idigit] = (digit)(accum & - PyLong_MASK); + v->ob_digit[idigit] = (digit)(accum & PyLong_MASK); ++idigit; accum >>= PyLong_SHIFT; accumbits -= PyLong_SHIFT; @@ -795,9 +795,9 @@ int little_endian, int is_signed) { Py_ssize_t i; /* index into v->ob_digit */ - Py_ssize_t ndigits; /* |v->ob_size| */ + Py_ssize_t ndigits; /* |v->ob_size| */ twodigits accum; /* sliding register */ - unsigned int accumbits; /* # bits in accum */ + unsigned int accumbits; /* # bits in accum */ int do_twos_comp; /* store 2's-comp? is_signed and v < 0 */ digit carry; /* for computing 2's-comp */ size_t j; /* # bytes filled */ @@ -810,7 +810,7 @@ ndigits = -(Py_SIZE(v)); if (!is_signed) { PyErr_SetString(PyExc_OverflowError, - "can't convert negative int to unsigned"); + "can't convert negative int to unsigned"); return -1; } do_twos_comp = 1; @@ -856,8 +856,7 @@ /* Count # of sign bits -- they needn't be stored, * although for signed conversion we need later to * make sure at least one sign bit gets stored. */ - digit s = do_twos_comp ? thisdigit ^ PyLong_MASK : - thisdigit; + digit s = do_twos_comp ? thisdigit ^ PyLong_MASK : thisdigit; while (s != 0) { s >>= 1; accumbits++; @@ -917,7 +916,7 @@ return 0; -Overflow: + Overflow: PyErr_SetString(PyExc_OverflowError, "int too big to convert"); return -1; @@ -986,7 +985,7 @@ */ #define IS_LITTLE_ENDIAN (int)*(unsigned char*)&one -#define PY_ABS_LLONG_MIN (0-(unsigned PY_LONG_LONG)PY_LLONG_MIN) +#define PY_ABS_LLONG_MIN (0-(unsigned PY_LONG_LONG)PY_LLONG_MIN) /* Create a new long int object from a C PY_LONG_LONG int. */ @@ -1172,9 +1171,8 @@ case 0: return 0; case 1: return v->ob_digit[0]; } - res = _PyLong_AsByteArray( - (PyLongObject *)vv, (unsigned char *)&bytes, - SIZEOF_LONG_LONG, IS_LITTLE_ENDIAN, 1); + res = _PyLong_AsByteArray((PyLongObject *)vv, (unsigned char *)&bytes, + SIZEOF_LONG_LONG, IS_LITTLE_ENDIAN, 1); /* Plan 9 can't handle PY_LONG_LONG in ? : expressions */ if (res < 0) @@ -1205,9 +1203,8 @@ case 1: return v->ob_digit[0]; } - res = _PyLong_AsByteArray( - (PyLongObject *)vv, (unsigned char *)&bytes, - SIZEOF_LONG_LONG, IS_LITTLE_ENDIAN, 0); + res = _PyLong_AsByteArray((PyLongObject *)vv, (unsigned char *)&bytes, + SIZEOF_LONG_LONG, IS_LITTLE_ENDIAN, 0); /* Plan 9 can't handle PY_LONG_LONG in ? : expressions */ if (res < 0) @@ -1373,7 +1370,7 @@ /* res is already set to -1 */ } } - exit: + exit: if (do_decref) { Py_DECREF(vv); } @@ -1600,9 +1597,9 @@ } /* check for keyboard interrupt */ SIGCHECK({ - Py_DECREF(scratch); - return NULL; - }) + Py_DECREF(scratch); + return NULL; + }) } /* pout should have at least one digit, so that the case when a = 0 works correctly */ @@ -1998,8 +1995,8 @@ twodigits convmax = base; int i = 1; - log_base_BASE[base] = log((double)base) / - log((double)PyLong_BASE); + log_base_BASE[base] = (log((double)base) / + log((double)PyLong_BASE)); for (;;) { twodigits next = convmax * base; if (next > PyLong_BASE) @@ -2043,7 +2040,7 @@ c = (digit)_PyLong_DigitValue[Py_CHARMASK(*str++)]; for (i = 1; i < convwidth && str != scan; ++i, ++str) { c = (twodigits)(c * base + - (int)_PyLong_DigitValue[Py_CHARMASK(*str)]); + (int)_PyLong_DigitValue[Py_CHARMASK(*str)]); assert(c < PyLong_BASE); } @@ -2116,7 +2113,7 @@ long_normalize(z); return (PyObject *) maybe_small_long(z); - onError: + onError: Py_XDECREF(z); slen = strlen(orig_str) < 200 ? strlen(orig_str) : 200; strobj = PyUnicode_FromStringAndSize(orig_str, slen); @@ -2272,12 +2269,12 @@ single-digit quotient q, remainder in vk[0:size_w]. */ SIGCHECK({ - Py_DECREF(a); - Py_DECREF(w); - Py_DECREF(v); - *prem = NULL; - return NULL; - }) + Py_DECREF(a); + Py_DECREF(w); + Py_DECREF(v); + *prem = NULL; + return NULL; + }) /* estimate quotient digit q; may overestimate by 1 (rare) */ vtop = vk[size_w]; @@ -2303,7 +2300,7 @@ (stwodigits)q * (stwodigits)w0[i]; vk[i] = (digit)z & PyLong_MASK; zhi = (sdigit)Py_ARITHMETIC_RIGHT_SHIFT(stwodigits, - z, PyLong_SHIFT); + z, PyLong_SHIFT); } /* add w back if q was too large (this branch taken rarely) */ @@ -2370,7 +2367,7 @@ if (a_size >= (PY_SSIZE_T_MAX - 1) / PyLong_SHIFT + 1 && (a_size > (PY_SSIZE_T_MAX - 1) / PyLong_SHIFT + 1 || a_bits > (PY_SSIZE_T_MAX - 1) % PyLong_SHIFT + 1)) - goto overflow; + goto overflow; a_bits = (a_size - 1) * PyLong_SHIFT + a_bits; /* Shift the first DBL_MANT_DIG + 2 bits of a into x_digits[0:x_size] @@ -2428,7 +2425,8 @@ break; } } - assert(1 <= x_size && x_size <= (Py_ssize_t)(sizeof(x_digits)/sizeof(digit))); + assert(1 <= x_size && + x_size <= (Py_ssize_t)(sizeof(x_digits)/sizeof(digit))); /* Round, and convert to double. */ x_digits[0] += half_even_correction[x_digits[0] & 7]; @@ -2603,8 +2601,8 @@ if (size_a < size_b) { { PyLongObject *temp = a; a = b; b = temp; } { Py_ssize_t size_temp = size_a; - size_a = size_b; - size_b = size_temp; } + size_a = size_b; + size_b = size_temp; } } z = _PyLong_New(size_a+1); if (z == NULL) @@ -2639,8 +2637,8 @@ sign = -1; { PyLongObject *temp = a; a = b; b = temp; } { Py_ssize_t size_temp = size_a; - size_a = size_b; - size_b = size_temp; } + size_a = size_b; + size_b = size_temp; } } else if (size_a == size_b) { /* Find highest digit where a and b differ: */ @@ -2768,9 +2766,9 @@ digit *paend = a->ob_digit + size_a; SIGCHECK({ - Py_DECREF(z); - return NULL; - }) + Py_DECREF(z); + return NULL; + }) carry = *pz + f * f; *pz++ = (digit)(carry & PyLong_MASK); @@ -2806,9 +2804,9 @@ digit *pbend = b->ob_digit + size_b; SIGCHECK({ - Py_DECREF(z); - return NULL; - }) + Py_DECREF(z); + return NULL; + }) while (pb < pbend) { carry += *pz + *pb++ * f; @@ -2832,7 +2830,10 @@ Returns 0 on success, -1 on failure. */ static int -kmul_split(PyLongObject *n, Py_ssize_t size, PyLongObject **high, PyLongObject **low) +kmul_split(PyLongObject *n, + Py_ssize_t size, + PyLongObject **high, + PyLongObject **low) { PyLongObject *hi, *lo; Py_ssize_t size_lo, size_hi; @@ -3021,7 +3022,7 @@ return long_normalize(ret); - fail: + fail: Py_XDECREF(ret); Py_XDECREF(ah); Py_XDECREF(al); @@ -3131,7 +3132,7 @@ Py_DECREF(bslice); return long_normalize(ret); - fail: + fail: Py_DECREF(ret); Py_XDECREF(bslice); return NULL; @@ -3414,7 +3415,7 @@ here. Both a and b would have to be enormous, using close to SIZE_T_MAX bytes of memory each. */ PyErr_SetString(PyExc_OverflowError, - "intermediate overflow during division"); + "intermediate overflow during division"); goto error; } x = _PyLong_New(a_size + shift_digits + 1); @@ -3578,7 +3579,7 @@ if (Py_SIZE(b) < 0) { /* if exponent is negative */ if (c) { PyErr_SetString(PyExc_TypeError, "pow() 2nd argument " - "cannot be negative when 3rd argument specified"); + "cannot be negative when 3rd argument specified"); goto Error; } else { @@ -3708,13 +3709,13 @@ } goto Done; - Error: + Error: if (z != NULL) { Py_DECREF(z); z = NULL; } /* fall through */ - Done: + Done: if (Py_SIZE(b) > FIVEARY_CUTOFF) { for (i = 0; i < 32; ++i) Py_XDECREF(table[i]); @@ -3819,12 +3820,11 @@ for (i = 0, j = wordshift; i < newsize; i++, j++) { z->ob_digit[i] = (a->ob_digit[j] >> loshift) & lomask; if (i+1 < newsize) - z->ob_digit[i] |= - (a->ob_digit[j+1] << hishift) & himask; + z->ob_digit[i] |= (a->ob_digit[j+1] << hishift) & himask; } z = long_normalize(z); } -rshift_error: + rshift_error: return (PyObject *) maybe_small_long(z); } @@ -3874,7 +3874,7 @@ else assert(!accum); z = long_normalize(z); -lshift_error: + lshift_error: return (PyObject *) maybe_small_long(z); } @@ -3900,7 +3900,7 @@ static PyObject * long_bitwise(PyLongObject *a, int op, /* '&', '|', '^' */ - PyLongObject *b) + PyLongObject *b) { int nega, negb, negz; Py_ssize_t size_a, size_b, size_z, i; @@ -4103,15 +4103,15 @@ /* We only see this if there's a null byte in x, x is a bytes or buffer, *and* a base is given. */ PyErr_Format(PyExc_ValueError, - "invalid literal for int() with base %d: %R", - base, x); + "invalid literal for int() with base %d: %R", + base, x); return NULL; } return PyLong_FromString(string, NULL, base); } else { PyErr_SetString(PyExc_TypeError, - "int() can't convert non-string with explicit base"); + "int() can't convert non-string with explicit base"); return NULL; } } @@ -4371,7 +4371,7 @@ return (PyObject *)result; -error: + error: Py_DECREF(result); return NULL; } @@ -4633,40 +4633,40 @@ converting a non-string."); static PyNumberMethods long_as_number = { - (binaryfunc) long_add, /*nb_add*/ - (binaryfunc) long_sub, /*nb_subtract*/ - (binaryfunc) long_mul, /*nb_multiply*/ - long_mod, /*nb_remainder*/ - long_divmod, /*nb_divmod*/ - long_pow, /*nb_power*/ - (unaryfunc) long_neg, /*nb_negative*/ - (unaryfunc) long_long, /*tp_positive*/ - (unaryfunc) long_abs, /*tp_absolute*/ - (inquiry) long_bool, /*tp_bool*/ - (unaryfunc) long_invert, /*nb_invert*/ - long_lshift, /*nb_lshift*/ - (binaryfunc) long_rshift, /*nb_rshift*/ - long_and, /*nb_and*/ - long_xor, /*nb_xor*/ - long_or, /*nb_or*/ - long_long, /*nb_int*/ - 0, /*nb_reserved*/ - long_float, /*nb_float*/ - 0, /* nb_inplace_add */ - 0, /* nb_inplace_subtract */ - 0, /* nb_inplace_multiply */ - 0, /* nb_inplace_remainder */ - 0, /* nb_inplace_power */ - 0, /* nb_inplace_lshift */ - 0, /* nb_inplace_rshift */ - 0, /* nb_inplace_and */ - 0, /* nb_inplace_xor */ - 0, /* nb_inplace_or */ - long_div, /* nb_floor_divide */ - long_true_divide, /* nb_true_divide */ - 0, /* nb_inplace_floor_divide */ - 0, /* nb_inplace_true_divide */ - long_long, /* nb_index */ + (binaryfunc)long_add, /*nb_add*/ + (binaryfunc)long_sub, /*nb_subtract*/ + (binaryfunc)long_mul, /*nb_multiply*/ + long_mod, /*nb_remainder*/ + long_divmod, /*nb_divmod*/ + long_pow, /*nb_power*/ + (unaryfunc)long_neg, /*nb_negative*/ + (unaryfunc)long_long, /*tp_positive*/ + (unaryfunc)long_abs, /*tp_absolute*/ + (inquiry)long_bool, /*tp_bool*/ + (unaryfunc)long_invert, /*nb_invert*/ + long_lshift, /*nb_lshift*/ + (binaryfunc)long_rshift, /*nb_rshift*/ + long_and, /*nb_and*/ + long_xor, /*nb_xor*/ + long_or, /*nb_or*/ + long_long, /*nb_int*/ + 0, /*nb_reserved*/ + long_float, /*nb_float*/ + 0, /* nb_inplace_add */ + 0, /* nb_inplace_subtract */ + 0, /* nb_inplace_multiply */ + 0, /* nb_inplace_remainder */ + 0, /* nb_inplace_power */ + 0, /* nb_inplace_lshift */ + 0, /* nb_inplace_rshift */ + 0, /* nb_inplace_and */ + 0, /* nb_inplace_xor */ + 0, /* nb_inplace_or */ + long_div, /* nb_floor_divide */ + long_true_divide, /* nb_true_divide */ + 0, /* nb_inplace_floor_divide */ + 0, /* nb_inplace_true_divide */ + long_long, /* nb_index */ }; PyTypeObject PyLong_Type = { @@ -4722,8 +4722,7 @@ static PyStructSequence_Field int_info_fields[] = { {"bits_per_digit", "size of a digit in bits"}, - {"sizeof_digit", "size in bytes of the C type used to " - "represent a digit"}, + {"sizeof_digit", "size in bytes of the C type used to represent a digit"}, {NULL, NULL} }; From python-checkins at python.org Mon May 10 23:37:34 2010 From: python-checkins at python.org (mark.dickinson) Date: Mon, 10 May 2010 23:37:34 +0200 (CEST) Subject: [Python-checkins] r81064 - in python/branches/py3k: Objects/longobject.c Message-ID: <20100510213734.DB1CFEEA4E@mail.python.org> Author: mark.dickinson Date: Mon May 10 23:37:34 2010 New Revision: 81064 Log: Merged revisions 81037 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r81037 | mark.dickinson | 2010-05-09 21:42:09 +0100 (Sun, 09 May 2010) | 1 line Wrap multiline macros in a 'do {} while(0)', for safety. ........ Modified: python/branches/py3k/ (props changed) python/branches/py3k/Objects/longobject.c Modified: python/branches/py3k/Objects/longobject.c ============================================================================== --- python/branches/py3k/Objects/longobject.c (original) +++ python/branches/py3k/Objects/longobject.c Mon May 10 23:37:34 2010 @@ -95,8 +95,10 @@ #define MAX(x, y) ((x) < (y) ? (y) : (x)) #define MIN(x, y) ((x) > (y) ? (y) : (x)) -#define SIGCHECK(PyTryBlock) \ - if (PyErr_CheckSignals()) PyTryBlock \ +#define SIGCHECK(PyTryBlock) \ + do { \ + if (PyErr_CheckSignals()) PyTryBlock \ + } while(0) /* Normalize (remove leading zeros from) a long int object. Doesn't attempt to free the storage--in most cases, due to the nature @@ -1379,11 +1381,13 @@ #endif /* HAVE_LONG_LONG */ -#define CHECK_BINOP(v,w) \ - if (!PyLong_Check(v) || !PyLong_Check(w)) { \ - Py_INCREF(Py_NotImplemented); \ - return Py_NotImplemented; \ - } +#define CHECK_BINOP(v,w) \ + do { \ + if (!PyLong_Check(v) || !PyLong_Check(w)) { \ + Py_INCREF(Py_NotImplemented); \ + return Py_NotImplemented; \ + } \ + } while(0) /* bits_in_digit(d) returns the unique integer k such that 2**(k-1) <= d < 2**k if d is nonzero, else 0. */ @@ -1599,7 +1603,7 @@ SIGCHECK({ Py_DECREF(scratch); return NULL; - }) + }); } /* pout should have at least one digit, so that the case when a = 0 works correctly */ @@ -2274,7 +2278,7 @@ Py_DECREF(v); *prem = NULL; return NULL; - }) + }); /* estimate quotient digit q; may overestimate by 1 (rare) */ vtop = vk[size_w]; @@ -2768,7 +2772,7 @@ SIGCHECK({ Py_DECREF(z); return NULL; - }) + }); carry = *pz + f * f; *pz++ = (digit)(carry & PyLong_MASK); @@ -2806,7 +2810,7 @@ SIGCHECK({ Py_DECREF(z); return NULL; - }) + }); while (pb < pbend) { carry += *pz + *pb++ * f; @@ -3645,26 +3649,28 @@ * is NULL. */ #define REDUCE(X) \ - if (c != NULL) { \ - if (l_divmod(X, c, NULL, &temp) < 0) \ - goto Error; \ - Py_XDECREF(X); \ - X = temp; \ - temp = NULL; \ - } + do { \ + if (c != NULL) { \ + if (l_divmod(X, c, NULL, &temp) < 0) \ + goto Error; \ + Py_XDECREF(X); \ + X = temp; \ + temp = NULL; \ + } \ + } while(0) /* Multiply two values, then reduce the result: result = X*Y % c. If c is NULL, skip the mod. */ -#define MULT(X, Y, result) \ -{ \ - temp = (PyLongObject *)long_mul(X, Y); \ - if (temp == NULL) \ - goto Error; \ - Py_XDECREF(result); \ - result = temp; \ - temp = NULL; \ - REDUCE(result) \ -} +#define MULT(X, Y, result) \ + do { \ + temp = (PyLongObject *)long_mul(X, Y); \ + if (temp == NULL) \ + goto Error; \ + Py_XDECREF(result); \ + result = temp; \ + temp = NULL; \ + REDUCE(result); \ + } while(0) if (Py_SIZE(b) <= FIVEARY_CUTOFF) { /* Left-to-right binary exponentiation (HAC Algorithm 14.79) */ @@ -3673,9 +3679,9 @@ digit bi = b->ob_digit[i]; for (j = (digit)1 << (PyLong_SHIFT-1); j != 0; j >>= 1) { - MULT(z, z, z) + MULT(z, z, z); if (bi & j) - MULT(z, a, z) + MULT(z, a, z); } } } @@ -3684,7 +3690,7 @@ Py_INCREF(z); /* still holds 1L */ table[0] = z; for (i = 1; i < 32; ++i) - MULT(table[i-1], a, table[i]) + MULT(table[i-1], a, table[i]); for (i = Py_SIZE(b) - 1; i >= 0; --i) { const digit bi = b->ob_digit[i]; @@ -3692,9 +3698,9 @@ for (j = PyLong_SHIFT - 5; j >= 0; j -= 5) { const int index = (bi >> j) & 0x1f; for (k = 0; k < 5; ++k) - MULT(z, z, z) + MULT(z, z, z); if (index) - MULT(z, table[index], z) + MULT(z, table[index], z); } } } From python-checkins at python.org Mon May 10 23:46:50 2010 From: python-checkins at python.org (georg.brandl) Date: Mon, 10 May 2010 23:46:50 +0200 (CEST) Subject: [Python-checkins] r81065 - python/trunk/Doc/library/ftplib.rst Message-ID: <20100510214650.ACA12EE981@mail.python.org> Author: georg.brandl Date: Mon May 10 23:46:50 2010 New Revision: 81065 Log: Fix reference direction. Modified: python/trunk/Doc/library/ftplib.rst Modified: python/trunk/Doc/library/ftplib.rst ============================================================================== --- python/trunk/Doc/library/ftplib.rst (original) +++ python/trunk/Doc/library/ftplib.rst Mon May 10 23:46:50 2010 @@ -110,7 +110,7 @@ The set of all exceptions (as a tuple) that methods of :class:`FTP` instances may raise as a result of problems with the FTP connection (as opposed to programming errors made by the caller). This set includes the - four exceptions listed below as well as :exc:`socket.error` and + four exceptions listed above as well as :exc:`socket.error` and :exc:`IOError`. From python-checkins at python.org Mon May 10 23:50:57 2010 From: python-checkins at python.org (georg.brandl) Date: Mon, 10 May 2010 23:50:57 +0200 (CEST) Subject: [Python-checkins] r81066 - python/trunk/Doc/library/unittest.rst Message-ID: <20100510215057.CE4E2EE981@mail.python.org> Author: georg.brandl Date: Mon May 10 23:50:57 2010 New Revision: 81066 Log: Consolidate deprecation messages. Modified: python/trunk/Doc/library/unittest.rst Modified: python/trunk/Doc/library/unittest.rst ============================================================================== --- python/trunk/Doc/library/unittest.rst (original) +++ python/trunk/Doc/library/unittest.rst Mon May 10 23:50:57 2010 @@ -776,8 +776,7 @@ will be *msg* if given, otherwise it will be :const:`None`. .. deprecated:: 2.7 - :meth:`failUnless`; use one of the ``assert`` variants. - :meth:`assert_`; use :meth:`assertTrue`. + :meth:`failUnless` and :meth:`assert_`; use :meth:`assertTrue`. .. method:: assertEqual(first, second[, msg]) From python-checkins at python.org Mon May 10 23:51:33 2010 From: python-checkins at python.org (georg.brandl) Date: Mon, 10 May 2010 23:51:33 +0200 (CEST) Subject: [Python-checkins] r81067 - python/trunk/Doc/library/io.rst Message-ID: <20100510215133.2966DEE981@mail.python.org> Author: georg.brandl Date: Mon May 10 23:51:33 2010 New Revision: 81067 Log: Fix typo. Modified: python/trunk/Doc/library/io.rst Modified: python/trunk/Doc/library/io.rst ============================================================================== --- python/trunk/Doc/library/io.rst (original) +++ python/trunk/Doc/library/io.rst Mon May 10 23:51:33 2010 @@ -246,7 +246,7 @@ Flush and close this stream. This method has no effect if the file is already closed. Once the file is closed, any operation on the file - (e.g. reading or writing) will raise an :exc:`ValueError`. + (e.g. reading or writing) will raise a :exc:`ValueError`. As a convenience, it is allowed to call this method more than once; only the first call, however, will have an effect. From python-checkins at python.org Mon May 10 23:55:54 2010 From: python-checkins at python.org (jeffrey.yasskin) Date: Mon, 10 May 2010 23:55:54 +0200 (CEST) Subject: [Python-checkins] r81068 - in python/branches/py3k-jit: Demo/embed/demo.c Demo/embed/loop.c Demo/pysvr/pysvr.c Include/abstract.h Include/ceval.h Include/datetime.h Include/descrobject.h Include/dictobject.h Include/object.h Include/objimpl.h Include/pyerrors.h Include/pymacconfig.h Include/pyport.h Include/pythonrun.h Include/setobject.h Include/structseq.h Include/symtable.h Include/unicodeobject.h Mac/Tools/pythonw.c Misc/setuid-prog.c Modules/_bisectmodule.c Modules/_codecsmodule.c Modules/_collectionsmodule.c Modules/_csv.c Modules/_ctypes/_ctypes.c Modules/_ctypes/_ctypes_test.c Modules/_ctypes/callbacks.c Modules/_ctypes/callproc.c Modules/_ctypes/cfield.c Modules/_ctypes/ctypes.h Modules/_ctypes/darwin/dlfcn_simple.c Modules/_ctypes/malloc_closure.c Modules/_ctypes/stgdict.c Modules/_curses_panel.c Modules/_dbmmodule.c Modules/_functoolsmodule.c Modules/_gdbmmodule.c Modules/_gestalt.c Modules/_heapqmodule.c Modules/_json.c Modules/_localemodule.c Modules/_lsprof.c Modules/_math.c Modules/_multiprocessing/connection.h Modules/_multiprocessing/multiprocessing.c Modules/_multiprocessing/multiprocessing.h Modules/_multiprocessing/pipe_connection.c Modules/_multiprocessing/semaphore.c Modules/_multiprocessing/socket_connection.c Modules/_multiprocessing/win32_functions.c Modules/_randommodule.c Modules/_scproxy.c Modules/_sqlite/module.c Modules/_struct.c Modules/_testcapimodule.c Modules/_threadmodule.c Modules/_tkinter.c Modules/addrinfo.h Modules/arraymodule.c Modules/audioop.c Modules/binascii.c Modules/bz2module.c Modules/cjkcodecs/_codecs_cn.c Modules/cjkcodecs/_codecs_hk.c Modules/cjkcodecs/_codecs_iso2022.c Modules/cjkcodecs/_codecs_jp.c Modules/cjkcodecs/_codecs_kr.c Modules/cjkcodecs/_codecs_tw.c Modules/cjkcodecs/alg_jisx0201.h Modules/cjkcodecs/cjkcodecs.h Modules/cjkcodecs/emu_jisx0213_2000.h Modules/cjkcodecs/multibytecodec.c Modules/cjkcodecs/multibytecodec.h Modules/cmathmodule.c Modules/cryptmodule.c Modules/datetimemodule.c Modules/errnomodule.c Modules/fcntlmodule.c Modules/fpectlmodule.c Modules/fpetestmodule.c Modules/gcmodule.c Modules/getaddrinfo.c Modules/getbuildinfo.c Modules/getnameinfo.c Modules/getpath.c Modules/grpmodule.c Modules/itertoolsmodule.c Modules/main.c Modules/mathmodule.c Modules/md5module.c Modules/mmapmodule.c Modules/nismodule.c Modules/operator.c Modules/ossaudiodev.c Modules/parsermodule.c Modules/pwdmodule.c Modules/pyexpat.c Modules/python.c Modules/readline.c Modules/resource.c Modules/rotatingtree.c Modules/selectmodule.c Modules/sha1module.c Modules/sha256module.c Modules/sha512module.c Modules/signalmodule.c Modules/socketmodule.c Modules/socketmodule.h Modules/spwdmodule.c Modules/symtablemodule.c Modules/syslogmodule.c Modules/termios.c Modules/testcapi_long.h Modules/timemodule.c Modules/tkappinit.c Modules/unicodedata.c Modules/xxmodule.c Modules/xxsubtype.c Modules/zipimport.c Modules/zlibmodule.c Objects/abstract.c Objects/boolobject.c Objects/bytes_methods.c Objects/bytesobject.c Objects/cellobject.c Objects/classobject.c Objects/codeobject.c Objects/complexobject.c Objects/descrobject.c Objects/dictobject.c Objects/enumobject.c Objects/exceptions.c Objects/fileobject.c Objects/floatobject.c Objects/frameobject.c Objects/funcobject.c Objects/genobject.c Objects/iterobject.c Objects/listobject.c Objects/longobject.c Objects/methodobject.c Objects/moduleobject.c Objects/object.c Objects/obmalloc.c Objects/rangeobject.c Objects/setobject.c Objects/sliceobject.c Objects/stringlib/eq.h Objects/stringlib/string_format.h Objects/structseq.c Objects/tupleobject.c Objects/typeobject.c Objects/weakrefobject.c PC/VS7.1/make_buildinfo.c PC/VS8.0/make_buildinfo.c PC/_msi.c PC/_subprocess.c PC/bdist_wininst/archive.h PC/bdist_wininst/extract.c PC/bdist_wininst/install.c PC/config.c PC/dl_nt.c PC/errmap.h PC/example_nt/example.c PC/frozen_dllmain.c PC/generrmap.c PC/getpathp.c PC/import_nt.c PC/make_versioninfo.c PC/msvcrtmodule.c PC/os2emx/config.c PC/os2emx/dlfcn.c PC/os2emx/dllentry.c PC/os2emx/getpathp.c PC/os2emx/pythonpm.c PC/os2vacpp/getpathp.c PC/winreg.c PC/winsound.c PCbuild/make_buildinfo.c Parser/acceler.c Parser/bitset.c Parser/firstsets.c Parser/grammar.c Parser/grammar1.c Parser/intrcheck.c Parser/listnode.c Parser/metagrammar.c Parser/myreadline.c Parser/node.c Parser/parser.c Parser/parsetok.c Parser/pgen.c Parser/pgenmain.c Parser/printgrammar.c Parser/tokenizer.c Parser/tokenizer.h Python/_warnings.c Python/asdl.c Python/ast.c Python/bltinmodule.c Python/ceval.c Python/codecs.c Python/compile.c Python/dynload_aix.c Python/dynload_hpux.c Python/dynload_next.c Python/dynload_os2.c Python/dynload_shlib.c Python/dynload_win.c Python/errors.c Python/frozen.c Python/frozenmain.c Python/future.c Python/getargs.c Python/getcwd.c Python/getopt.c Python/import.c Python/importdl.c Python/importdl.h Python/makeopcodetargets.py Python/marshal.c Python/modsupport.c Python/mysnprintf.c Python/mystrtoul.c Python/opcode_targets.h Python/peephole.c Python/pyarena.c Python/pymath.c Python/pystate.c Python/pystrcmp.c Python/pystrtod.c Python/pythonrun.c Python/structmember.c Python/symtable.c Python/sysmodule.c Python/thread.c Python/thread_cthread.h Python/thread_foobar.h Python/thread_lwp.h Python/thread_nt.h Python/thread_os2.h Python/thread_pth.h Python/thread_pthread.h Python/thread_sgi.h Python/thread_solaris.h Python/thread_wince.h Python/traceback.c Tools/msi/msisupport.c Message-ID: <20100510215554.80FD8EE9B9@mail.python.org> Author: jeffrey.yasskin Date: Mon May 10 23:55:43 2010 New Revision: 81068 Log: Merged revisions 81032 via svnmerge from svn+ssh://pythondev at svn.python.org/python/branches/py3k ................ r81032 | antoine.pitrou | 2010-05-09 08:52:27 -0700 (Sun, 09 May 2010) | 9 lines Recorded merge of revisions 81029 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r81029 | antoine.pitrou | 2010-05-09 16:46:46 +0200 (dim., 09 mai 2010) | 3 lines Untabify C files. Will watch buildbots. ........ ................ Modified: python/branches/py3k-jit/ (props changed) python/branches/py3k-jit/Demo/embed/demo.c python/branches/py3k-jit/Demo/embed/loop.c python/branches/py3k-jit/Demo/pysvr/pysvr.c python/branches/py3k-jit/Include/abstract.h python/branches/py3k-jit/Include/ceval.h python/branches/py3k-jit/Include/datetime.h python/branches/py3k-jit/Include/descrobject.h python/branches/py3k-jit/Include/dictobject.h python/branches/py3k-jit/Include/object.h python/branches/py3k-jit/Include/objimpl.h python/branches/py3k-jit/Include/pyerrors.h python/branches/py3k-jit/Include/pymacconfig.h python/branches/py3k-jit/Include/pyport.h python/branches/py3k-jit/Include/pythonrun.h python/branches/py3k-jit/Include/setobject.h python/branches/py3k-jit/Include/structseq.h python/branches/py3k-jit/Include/symtable.h python/branches/py3k-jit/Include/unicodeobject.h python/branches/py3k-jit/Mac/Tools/pythonw.c python/branches/py3k-jit/Misc/setuid-prog.c python/branches/py3k-jit/Modules/_bisectmodule.c python/branches/py3k-jit/Modules/_codecsmodule.c python/branches/py3k-jit/Modules/_collectionsmodule.c python/branches/py3k-jit/Modules/_csv.c python/branches/py3k-jit/Modules/_ctypes/_ctypes.c python/branches/py3k-jit/Modules/_ctypes/_ctypes_test.c python/branches/py3k-jit/Modules/_ctypes/callbacks.c python/branches/py3k-jit/Modules/_ctypes/callproc.c python/branches/py3k-jit/Modules/_ctypes/cfield.c python/branches/py3k-jit/Modules/_ctypes/ctypes.h python/branches/py3k-jit/Modules/_ctypes/darwin/dlfcn_simple.c python/branches/py3k-jit/Modules/_ctypes/malloc_closure.c python/branches/py3k-jit/Modules/_ctypes/stgdict.c python/branches/py3k-jit/Modules/_curses_panel.c python/branches/py3k-jit/Modules/_dbmmodule.c python/branches/py3k-jit/Modules/_functoolsmodule.c python/branches/py3k-jit/Modules/_gdbmmodule.c python/branches/py3k-jit/Modules/_gestalt.c python/branches/py3k-jit/Modules/_heapqmodule.c python/branches/py3k-jit/Modules/_json.c python/branches/py3k-jit/Modules/_localemodule.c python/branches/py3k-jit/Modules/_lsprof.c python/branches/py3k-jit/Modules/_math.c python/branches/py3k-jit/Modules/_multiprocessing/connection.h python/branches/py3k-jit/Modules/_multiprocessing/multiprocessing.c python/branches/py3k-jit/Modules/_multiprocessing/multiprocessing.h python/branches/py3k-jit/Modules/_multiprocessing/pipe_connection.c python/branches/py3k-jit/Modules/_multiprocessing/semaphore.c python/branches/py3k-jit/Modules/_multiprocessing/socket_connection.c python/branches/py3k-jit/Modules/_multiprocessing/win32_functions.c python/branches/py3k-jit/Modules/_randommodule.c python/branches/py3k-jit/Modules/_scproxy.c python/branches/py3k-jit/Modules/_sqlite/module.c python/branches/py3k-jit/Modules/_struct.c python/branches/py3k-jit/Modules/_testcapimodule.c python/branches/py3k-jit/Modules/_threadmodule.c python/branches/py3k-jit/Modules/_tkinter.c python/branches/py3k-jit/Modules/addrinfo.h python/branches/py3k-jit/Modules/arraymodule.c python/branches/py3k-jit/Modules/audioop.c python/branches/py3k-jit/Modules/binascii.c python/branches/py3k-jit/Modules/bz2module.c python/branches/py3k-jit/Modules/cjkcodecs/_codecs_cn.c python/branches/py3k-jit/Modules/cjkcodecs/_codecs_hk.c python/branches/py3k-jit/Modules/cjkcodecs/_codecs_iso2022.c python/branches/py3k-jit/Modules/cjkcodecs/_codecs_jp.c python/branches/py3k-jit/Modules/cjkcodecs/_codecs_kr.c python/branches/py3k-jit/Modules/cjkcodecs/_codecs_tw.c python/branches/py3k-jit/Modules/cjkcodecs/alg_jisx0201.h python/branches/py3k-jit/Modules/cjkcodecs/cjkcodecs.h python/branches/py3k-jit/Modules/cjkcodecs/emu_jisx0213_2000.h python/branches/py3k-jit/Modules/cjkcodecs/multibytecodec.c python/branches/py3k-jit/Modules/cjkcodecs/multibytecodec.h python/branches/py3k-jit/Modules/cmathmodule.c python/branches/py3k-jit/Modules/cryptmodule.c python/branches/py3k-jit/Modules/datetimemodule.c python/branches/py3k-jit/Modules/errnomodule.c python/branches/py3k-jit/Modules/fcntlmodule.c python/branches/py3k-jit/Modules/fpectlmodule.c python/branches/py3k-jit/Modules/fpetestmodule.c python/branches/py3k-jit/Modules/gcmodule.c python/branches/py3k-jit/Modules/getaddrinfo.c python/branches/py3k-jit/Modules/getbuildinfo.c python/branches/py3k-jit/Modules/getnameinfo.c python/branches/py3k-jit/Modules/getpath.c python/branches/py3k-jit/Modules/grpmodule.c python/branches/py3k-jit/Modules/itertoolsmodule.c python/branches/py3k-jit/Modules/main.c python/branches/py3k-jit/Modules/mathmodule.c python/branches/py3k-jit/Modules/md5module.c python/branches/py3k-jit/Modules/mmapmodule.c python/branches/py3k-jit/Modules/nismodule.c python/branches/py3k-jit/Modules/operator.c python/branches/py3k-jit/Modules/ossaudiodev.c python/branches/py3k-jit/Modules/parsermodule.c python/branches/py3k-jit/Modules/pwdmodule.c python/branches/py3k-jit/Modules/pyexpat.c python/branches/py3k-jit/Modules/python.c python/branches/py3k-jit/Modules/readline.c python/branches/py3k-jit/Modules/resource.c python/branches/py3k-jit/Modules/rotatingtree.c python/branches/py3k-jit/Modules/selectmodule.c python/branches/py3k-jit/Modules/sha1module.c python/branches/py3k-jit/Modules/sha256module.c python/branches/py3k-jit/Modules/sha512module.c python/branches/py3k-jit/Modules/signalmodule.c python/branches/py3k-jit/Modules/socketmodule.c python/branches/py3k-jit/Modules/socketmodule.h python/branches/py3k-jit/Modules/spwdmodule.c python/branches/py3k-jit/Modules/symtablemodule.c python/branches/py3k-jit/Modules/syslogmodule.c python/branches/py3k-jit/Modules/termios.c python/branches/py3k-jit/Modules/testcapi_long.h python/branches/py3k-jit/Modules/timemodule.c python/branches/py3k-jit/Modules/tkappinit.c python/branches/py3k-jit/Modules/unicodedata.c python/branches/py3k-jit/Modules/xxmodule.c python/branches/py3k-jit/Modules/xxsubtype.c python/branches/py3k-jit/Modules/zipimport.c python/branches/py3k-jit/Modules/zlibmodule.c python/branches/py3k-jit/Objects/abstract.c python/branches/py3k-jit/Objects/boolobject.c python/branches/py3k-jit/Objects/bytes_methods.c python/branches/py3k-jit/Objects/bytesobject.c python/branches/py3k-jit/Objects/cellobject.c python/branches/py3k-jit/Objects/classobject.c python/branches/py3k-jit/Objects/codeobject.c python/branches/py3k-jit/Objects/complexobject.c python/branches/py3k-jit/Objects/descrobject.c python/branches/py3k-jit/Objects/dictobject.c python/branches/py3k-jit/Objects/enumobject.c python/branches/py3k-jit/Objects/exceptions.c python/branches/py3k-jit/Objects/fileobject.c python/branches/py3k-jit/Objects/floatobject.c python/branches/py3k-jit/Objects/frameobject.c python/branches/py3k-jit/Objects/funcobject.c python/branches/py3k-jit/Objects/genobject.c python/branches/py3k-jit/Objects/iterobject.c python/branches/py3k-jit/Objects/listobject.c python/branches/py3k-jit/Objects/longobject.c python/branches/py3k-jit/Objects/methodobject.c python/branches/py3k-jit/Objects/moduleobject.c python/branches/py3k-jit/Objects/object.c python/branches/py3k-jit/Objects/obmalloc.c python/branches/py3k-jit/Objects/rangeobject.c python/branches/py3k-jit/Objects/setobject.c python/branches/py3k-jit/Objects/sliceobject.c python/branches/py3k-jit/Objects/stringlib/eq.h python/branches/py3k-jit/Objects/stringlib/string_format.h python/branches/py3k-jit/Objects/structseq.c python/branches/py3k-jit/Objects/tupleobject.c python/branches/py3k-jit/Objects/typeobject.c python/branches/py3k-jit/Objects/weakrefobject.c python/branches/py3k-jit/PC/VS7.1/make_buildinfo.c python/branches/py3k-jit/PC/VS8.0/make_buildinfo.c python/branches/py3k-jit/PC/_msi.c python/branches/py3k-jit/PC/_subprocess.c python/branches/py3k-jit/PC/bdist_wininst/archive.h python/branches/py3k-jit/PC/bdist_wininst/extract.c python/branches/py3k-jit/PC/bdist_wininst/install.c python/branches/py3k-jit/PC/config.c python/branches/py3k-jit/PC/dl_nt.c python/branches/py3k-jit/PC/errmap.h python/branches/py3k-jit/PC/example_nt/example.c python/branches/py3k-jit/PC/frozen_dllmain.c python/branches/py3k-jit/PC/generrmap.c python/branches/py3k-jit/PC/getpathp.c python/branches/py3k-jit/PC/import_nt.c python/branches/py3k-jit/PC/make_versioninfo.c python/branches/py3k-jit/PC/msvcrtmodule.c python/branches/py3k-jit/PC/os2emx/config.c python/branches/py3k-jit/PC/os2emx/dlfcn.c python/branches/py3k-jit/PC/os2emx/dllentry.c python/branches/py3k-jit/PC/os2emx/getpathp.c python/branches/py3k-jit/PC/os2emx/pythonpm.c python/branches/py3k-jit/PC/os2vacpp/getpathp.c python/branches/py3k-jit/PC/winreg.c python/branches/py3k-jit/PC/winsound.c python/branches/py3k-jit/PCbuild/make_buildinfo.c python/branches/py3k-jit/Parser/acceler.c python/branches/py3k-jit/Parser/bitset.c python/branches/py3k-jit/Parser/firstsets.c python/branches/py3k-jit/Parser/grammar.c python/branches/py3k-jit/Parser/grammar1.c python/branches/py3k-jit/Parser/intrcheck.c python/branches/py3k-jit/Parser/listnode.c python/branches/py3k-jit/Parser/metagrammar.c python/branches/py3k-jit/Parser/myreadline.c python/branches/py3k-jit/Parser/node.c python/branches/py3k-jit/Parser/parser.c python/branches/py3k-jit/Parser/parsetok.c python/branches/py3k-jit/Parser/pgen.c python/branches/py3k-jit/Parser/pgenmain.c python/branches/py3k-jit/Parser/printgrammar.c python/branches/py3k-jit/Parser/tokenizer.c python/branches/py3k-jit/Parser/tokenizer.h python/branches/py3k-jit/Python/_warnings.c python/branches/py3k-jit/Python/asdl.c python/branches/py3k-jit/Python/ast.c python/branches/py3k-jit/Python/bltinmodule.c python/branches/py3k-jit/Python/ceval.c python/branches/py3k-jit/Python/codecs.c python/branches/py3k-jit/Python/compile.c python/branches/py3k-jit/Python/dynload_aix.c python/branches/py3k-jit/Python/dynload_hpux.c python/branches/py3k-jit/Python/dynload_next.c python/branches/py3k-jit/Python/dynload_os2.c python/branches/py3k-jit/Python/dynload_shlib.c python/branches/py3k-jit/Python/dynload_win.c python/branches/py3k-jit/Python/errors.c python/branches/py3k-jit/Python/frozen.c python/branches/py3k-jit/Python/frozenmain.c python/branches/py3k-jit/Python/future.c python/branches/py3k-jit/Python/getargs.c python/branches/py3k-jit/Python/getcwd.c python/branches/py3k-jit/Python/getopt.c python/branches/py3k-jit/Python/import.c python/branches/py3k-jit/Python/importdl.c python/branches/py3k-jit/Python/importdl.h python/branches/py3k-jit/Python/makeopcodetargets.py python/branches/py3k-jit/Python/marshal.c python/branches/py3k-jit/Python/modsupport.c python/branches/py3k-jit/Python/mysnprintf.c python/branches/py3k-jit/Python/mystrtoul.c python/branches/py3k-jit/Python/opcode_targets.h python/branches/py3k-jit/Python/peephole.c python/branches/py3k-jit/Python/pyarena.c python/branches/py3k-jit/Python/pymath.c python/branches/py3k-jit/Python/pystate.c python/branches/py3k-jit/Python/pystrcmp.c python/branches/py3k-jit/Python/pystrtod.c python/branches/py3k-jit/Python/pythonrun.c python/branches/py3k-jit/Python/structmember.c python/branches/py3k-jit/Python/symtable.c python/branches/py3k-jit/Python/sysmodule.c python/branches/py3k-jit/Python/thread.c python/branches/py3k-jit/Python/thread_cthread.h python/branches/py3k-jit/Python/thread_foobar.h python/branches/py3k-jit/Python/thread_lwp.h python/branches/py3k-jit/Python/thread_nt.h python/branches/py3k-jit/Python/thread_os2.h python/branches/py3k-jit/Python/thread_pth.h python/branches/py3k-jit/Python/thread_pthread.h python/branches/py3k-jit/Python/thread_sgi.h python/branches/py3k-jit/Python/thread_solaris.h python/branches/py3k-jit/Python/thread_wince.h python/branches/py3k-jit/Python/traceback.c python/branches/py3k-jit/Tools/msi/msisupport.c Modified: python/branches/py3k-jit/Demo/embed/demo.c ============================================================================== --- python/branches/py3k-jit/Demo/embed/demo.c (original) +++ python/branches/py3k-jit/Demo/embed/demo.c Mon May 10 23:55:43 2010 @@ -6,44 +6,44 @@ main(int argc, char **argv) { - /* Ignore passed-in argc/argv. If desired, conversion - should use mbstowcs to convert them. */ - wchar_t *args[] = {L"embed", L"hello", 0}; - - /* Pass argv[0] to the Python interpreter */ - Py_SetProgramName(args[0]); - - /* Add a static module */ - PyImport_AppendInittab("xyzzy", PyInit_xyzzy); - - /* Initialize the Python interpreter. Required. */ - Py_Initialize(); - - /* Define sys.argv. It is up to the application if you - want this; you can also let it undefined (since the Python - code is generally not a main program it has no business - touching sys.argv...) */ - PySys_SetArgv(2, args); - - /* Do some application specific code */ - printf("Hello, brave new world\n\n"); - - /* Execute some Python statements (in module __main__) */ - PyRun_SimpleString("import sys\n"); - PyRun_SimpleString("print(sys.builtin_module_names)\n"); - PyRun_SimpleString("print(sys.modules.keys())\n"); - PyRun_SimpleString("print(sys.executable)\n"); - PyRun_SimpleString("print(sys.argv)\n"); - - /* Note that you can call any public function of the Python - interpreter here, e.g. call_object(). */ - - /* Some more application specific code */ - printf("\nGoodbye, cruel world\n"); - - /* Exit, cleaning up the interpreter */ - Py_Exit(0); - /*NOTREACHED*/ + /* Ignore passed-in argc/argv. If desired, conversion + should use mbstowcs to convert them. */ + wchar_t *args[] = {L"embed", L"hello", 0}; + + /* Pass argv[0] to the Python interpreter */ + Py_SetProgramName(args[0]); + + /* Add a static module */ + PyImport_AppendInittab("xyzzy", PyInit_xyzzy); + + /* Initialize the Python interpreter. Required. */ + Py_Initialize(); + + /* Define sys.argv. It is up to the application if you + want this; you can also let it undefined (since the Python + code is generally not a main program it has no business + touching sys.argv...) */ + PySys_SetArgv(2, args); + + /* Do some application specific code */ + printf("Hello, brave new world\n\n"); + + /* Execute some Python statements (in module __main__) */ + PyRun_SimpleString("import sys\n"); + PyRun_SimpleString("print(sys.builtin_module_names)\n"); + PyRun_SimpleString("print(sys.modules.keys())\n"); + PyRun_SimpleString("print(sys.executable)\n"); + PyRun_SimpleString("print(sys.argv)\n"); + + /* Note that you can call any public function of the Python + interpreter here, e.g. call_object(). */ + + /* Some more application specific code */ + printf("\nGoodbye, cruel world\n"); + + /* Exit, cleaning up the interpreter */ + Py_Exit(0); + /*NOTREACHED*/ } /* A static module */ @@ -52,29 +52,29 @@ static PyObject * xyzzy_foo(PyObject *self, PyObject* args) { - return PyLong_FromLong(42L); + return PyLong_FromLong(42L); } static PyMethodDef xyzzy_methods[] = { - {"foo", xyzzy_foo, METH_NOARGS, - "Return the meaning of everything."}, - {NULL, NULL} /* sentinel */ + {"foo", xyzzy_foo, METH_NOARGS, + "Return the meaning of everything."}, + {NULL, NULL} /* sentinel */ }; static struct PyModuleDef xyzzymodule = { - {}, /* m_base */ - "xyzzy", /* m_name */ - 0, /* m_doc */ - 0, /* m_size */ - xyzzy_methods, /* m_methods */ - 0, /* m_reload */ - 0, /* m_traverse */ - 0, /* m_clear */ - 0, /* m_free */ + {}, /* m_base */ + "xyzzy", /* m_name */ + 0, /* m_doc */ + 0, /* m_size */ + xyzzy_methods, /* m_methods */ + 0, /* m_reload */ + 0, /* m_traverse */ + 0, /* m_clear */ + 0, /* m_free */ }; PyObject* PyInit_xyzzy(void) { - return PyModule_Create(&xyzzymodule); + return PyModule_Create(&xyzzymodule); } Modified: python/branches/py3k-jit/Demo/embed/loop.c ============================================================================== --- python/branches/py3k-jit/Demo/embed/loop.c (original) +++ python/branches/py3k-jit/Demo/embed/loop.c Mon May 10 23:55:43 2010 @@ -6,28 +6,28 @@ main(int argc, char **argv) { - int count = -1; - char *command; + int count = -1; + char *command; - if (argc < 2 || argc > 3) { - fprintf(stderr, "usage: loop [count]\n"); - exit(2); - } - command = argv[1]; - - if (argc == 3) { - count = atoi(argv[2]); - } - - Py_SetProgramName(argv[0]); - - /* uncomment this if you don't want to load site.py */ - /* Py_NoSiteFlag = 1; */ - - while (count == -1 || --count >= 0 ) { - Py_Initialize(); - PyRun_SimpleString(command); - Py_Finalize(); - } - return 0; + if (argc < 2 || argc > 3) { + fprintf(stderr, "usage: loop [count]\n"); + exit(2); + } + command = argv[1]; + + if (argc == 3) { + count = atoi(argv[2]); + } + + Py_SetProgramName(argv[0]); + + /* uncomment this if you don't want to load site.py */ + /* Py_NoSiteFlag = 1; */ + + while (count == -1 || --count >= 0 ) { + Py_Initialize(); + PyRun_SimpleString(command); + Py_Finalize(); + } + return 0; } Modified: python/branches/py3k-jit/Demo/pysvr/pysvr.c ============================================================================== --- python/branches/py3k-jit/Demo/pysvr/pysvr.c (original) +++ python/branches/py3k-jit/Demo/pysvr/pysvr.c Mon May 10 23:55:43 2010 @@ -34,8 +34,8 @@ #endif struct workorder { - int conn; - struct sockaddr_in addr; + int conn; + struct sockaddr_in addr; }; /* Forward */ @@ -55,40 +55,40 @@ main(int argc, char **argv) { - int port = PORT; - int c; + int port = PORT; + int c; - if (argc > 0 && argv[0] != NULL && argv[0][0] != '\0') - progname = argv[0]; + if (argc > 0 && argv[0] != NULL && argv[0][0] != '\0') + progname = argv[0]; - while ((c = getopt(argc, argv, "v")) != EOF) { - switch (c) { - case 'v': - Py_VerboseFlag++; - break; - default: - usage(); - } - } - - if (optind < argc) { - if (optind+1 < argc) { - oprogname(); - fprintf(stderr, "too many arguments\n"); - usage(); - } - port = atoi(argv[optind]); - if (port <= 0) { - fprintf(stderr, "bad port (%s)\n", argv[optind]); - usage(); - } - } + while ((c = getopt(argc, argv, "v")) != EOF) { + switch (c) { + case 'v': + Py_VerboseFlag++; + break; + default: + usage(); + } + } + + if (optind < argc) { + if (optind+1 < argc) { + oprogname(); + fprintf(stderr, "too many arguments\n"); + usage(); + } + port = atoi(argv[optind]); + if (port <= 0) { + fprintf(stderr, "bad port (%s)\n", argv[optind]); + usage(); + } + } - main_thread(port); + main_thread(port); - fprintf(stderr, "Bye.\n"); + fprintf(stderr, "Bye.\n"); - exit(0); + exit(0); } static char usage_line[] = "usage: %s [port]\n"; @@ -96,120 +96,120 @@ static void usage(void) { - fprintf(stderr, usage_line, progname); - exit(2); + fprintf(stderr, usage_line, progname); + exit(2); } static void main_thread(int port) { - int sock, conn, size, i; - struct sockaddr_in addr, clientaddr; + int sock, conn, size, i; + struct sockaddr_in addr, clientaddr; - sock = socket(PF_INET, SOCK_STREAM, 0); - if (sock < 0) { - oprogname(); - perror("can't create socket"); - exit(1); - } + sock = socket(PF_INET, SOCK_STREAM, 0); + if (sock < 0) { + oprogname(); + perror("can't create socket"); + exit(1); + } #ifdef SO_REUSEADDR - i = 1; - setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, (char *) &i, sizeof i); + i = 1; + setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, (char *) &i, sizeof i); #endif - memset((char *)&addr, '\0', sizeof addr); - addr.sin_family = AF_INET; - addr.sin_port = htons(port); - addr.sin_addr.s_addr = 0L; - if (bind(sock, (struct sockaddr *)&addr, sizeof addr) < 0) { - oprogname(); - perror("can't bind socket to address"); - exit(1); - } - - if (listen(sock, 5) < 0) { - oprogname(); - perror("can't listen on socket"); - exit(1); - } - - fprintf(stderr, "Listening on port %d...\n", port); - - for (i = 0; ; i++) { - size = sizeof clientaddr; - memset((char *) &clientaddr, '\0', size); - conn = accept(sock, (struct sockaddr *) &clientaddr, &size); - if (conn < 0) { - oprogname(); - perror("can't accept connection from socket"); - exit(1); - } - - size = sizeof addr; - memset((char *) &addr, '\0', size); - if (getsockname(conn, (struct sockaddr *)&addr, &size) < 0) { - oprogname(); - perror("can't get socket name of connection"); - exit(1); - } - if (clientaddr.sin_addr.s_addr != addr.sin_addr.s_addr) { - oprogname(); - perror("connection from non-local host refused"); - fprintf(stderr, "(addr=%lx, clientaddr=%lx)\n", - ntohl(addr.sin_addr.s_addr), - ntohl(clientaddr.sin_addr.s_addr)); - close(conn); - continue; - } - if (i == 4) { - close(conn); - break; - } - create_thread(conn, &clientaddr); - } - - close(sock); - - if (gtstate) { - PyEval_AcquireThread(gtstate); - gtstate = NULL; - Py_Finalize(); - /* And a second time, just because we can. */ - Py_Finalize(); /* This should be harmless. */ - } - exit(0); + memset((char *)&addr, '\0', sizeof addr); + addr.sin_family = AF_INET; + addr.sin_port = htons(port); + addr.sin_addr.s_addr = 0L; + if (bind(sock, (struct sockaddr *)&addr, sizeof addr) < 0) { + oprogname(); + perror("can't bind socket to address"); + exit(1); + } + + if (listen(sock, 5) < 0) { + oprogname(); + perror("can't listen on socket"); + exit(1); + } + + fprintf(stderr, "Listening on port %d...\n", port); + + for (i = 0; ; i++) { + size = sizeof clientaddr; + memset((char *) &clientaddr, '\0', size); + conn = accept(sock, (struct sockaddr *) &clientaddr, &size); + if (conn < 0) { + oprogname(); + perror("can't accept connection from socket"); + exit(1); + } + + size = sizeof addr; + memset((char *) &addr, '\0', size); + if (getsockname(conn, (struct sockaddr *)&addr, &size) < 0) { + oprogname(); + perror("can't get socket name of connection"); + exit(1); + } + if (clientaddr.sin_addr.s_addr != addr.sin_addr.s_addr) { + oprogname(); + perror("connection from non-local host refused"); + fprintf(stderr, "(addr=%lx, clientaddr=%lx)\n", + ntohl(addr.sin_addr.s_addr), + ntohl(clientaddr.sin_addr.s_addr)); + close(conn); + continue; + } + if (i == 4) { + close(conn); + break; + } + create_thread(conn, &clientaddr); + } + + close(sock); + + if (gtstate) { + PyEval_AcquireThread(gtstate); + gtstate = NULL; + Py_Finalize(); + /* And a second time, just because we can. */ + Py_Finalize(); /* This should be harmless. */ + } + exit(0); } static void create_thread(int conn, struct sockaddr_in *addr) { - struct workorder *work; - pthread_t tdata; + struct workorder *work; + pthread_t tdata; - work = malloc(sizeof(struct workorder)); - if (work == NULL) { - oprogname(); - fprintf(stderr, "out of memory for thread.\n"); - close(conn); - return; - } - work->conn = conn; - work->addr = *addr; - - init_python(); - - if (pthread_create(&tdata, NULL, (void *)service_thread, work) < 0) { - oprogname(); - perror("can't create new thread"); - close(conn); - return; - } - - if (pthread_detach(tdata) < 0) { - oprogname(); - perror("can't detach from thread"); - } + work = malloc(sizeof(struct workorder)); + if (work == NULL) { + oprogname(); + fprintf(stderr, "out of memory for thread.\n"); + close(conn); + return; + } + work->conn = conn; + work->addr = *addr; + + init_python(); + + if (pthread_create(&tdata, NULL, (void *)service_thread, work) < 0) { + oprogname(); + perror("can't create new thread"); + close(conn); + return; + } + + if (pthread_detach(tdata) < 0) { + oprogname(); + perror("can't detach from thread"); + } } static PyThreadState *the_tstate; @@ -219,152 +219,152 @@ static void init_python(void) { - if (gtstate) - return; - Py_Initialize(); /* Initialize the interpreter */ - PyEval_InitThreads(); /* Create (and acquire) the interpreter lock */ - gtstate = PyEval_SaveThread(); /* Release the thread state */ + if (gtstate) + return; + Py_Initialize(); /* Initialize the interpreter */ + PyEval_InitThreads(); /* Create (and acquire) the interpreter lock */ + gtstate = PyEval_SaveThread(); /* Release the thread state */ } static void * service_thread(struct workorder *work) { - FILE *input, *output; + FILE *input, *output; - fprintf(stderr, "Start thread for connection %d.\n", work->conn); + fprintf(stderr, "Start thread for connection %d.\n", work->conn); - ps(); + ps(); - input = fdopen(work->conn, "r"); - if (input == NULL) { - oprogname(); - perror("can't create input stream"); - goto done; - } - - output = fdopen(work->conn, "w"); - if (output == NULL) { - oprogname(); - perror("can't create output stream"); - fclose(input); - goto done; - } + input = fdopen(work->conn, "r"); + if (input == NULL) { + oprogname(); + perror("can't create input stream"); + goto done; + } + + output = fdopen(work->conn, "w"); + if (output == NULL) { + oprogname(); + perror("can't create output stream"); + fclose(input); + goto done; + } - setvbuf(input, NULL, _IONBF, 0); - setvbuf(output, NULL, _IONBF, 0); + setvbuf(input, NULL, _IONBF, 0); + setvbuf(output, NULL, _IONBF, 0); - run_interpreter(input, output); + run_interpreter(input, output); - fclose(input); - fclose(output); + fclose(input); + fclose(output); done: - fprintf(stderr, "End thread for connection %d.\n", work->conn); - close(work->conn); - free(work); + fprintf(stderr, "End thread for connection %d.\n", work->conn); + close(work->conn); + free(work); } static void oprogname(void) { - int save = errno; - fprintf(stderr, "%s: ", progname); - errno = save; + int save = errno; + fprintf(stderr, "%s: ", progname); + errno = save; } static void run_interpreter(FILE *input, FILE *output) { - PyThreadState *tstate; - PyObject *new_stdin, *new_stdout; - PyObject *mainmod, *globals; - char buffer[1000]; - char *p, *q; - int n, end; - - PyEval_AcquireLock(); - tstate = Py_NewInterpreter(); - if (tstate == NULL) { - fprintf(output, "Sorry -- can't create an interpreter\n"); - return; - } - - mainmod = PyImport_AddModule("__main__"); - globals = PyModule_GetDict(mainmod); - Py_INCREF(globals); - - new_stdin = PyFile_FromFile(input, "", "r", NULL); - new_stdout = PyFile_FromFile(output, "", "w", NULL); - - PySys_SetObject("stdin", new_stdin); - PySys_SetObject("stdout", new_stdout); - PySys_SetObject("stderr", new_stdout); - - for (n = 1; !PyErr_Occurred(); n++) { - Py_BEGIN_ALLOW_THREADS - fprintf(output, "%d> ", n); - p = fgets(buffer, sizeof buffer, input); - Py_END_ALLOW_THREADS - - if (p == NULL) - break; - if (p[0] == '\377' && p[1] == '\354') - break; - - q = strrchr(p, '\r'); - if (q && q[1] == '\n' && q[2] == '\0') { - *q++ = '\n'; - *q++ = '\0'; - } - - while (*p && isspace(*p)) - p++; - if (p[0] == '#' || p[0] == '\0') - continue; - - end = run_command(buffer, globals); - if (end < 0) - PyErr_Print(); - - if (end) - break; - } - - Py_XDECREF(globals); - Py_XDECREF(new_stdin); - Py_XDECREF(new_stdout); + PyThreadState *tstate; + PyObject *new_stdin, *new_stdout; + PyObject *mainmod, *globals; + char buffer[1000]; + char *p, *q; + int n, end; + + PyEval_AcquireLock(); + tstate = Py_NewInterpreter(); + if (tstate == NULL) { + fprintf(output, "Sorry -- can't create an interpreter\n"); + return; + } + + mainmod = PyImport_AddModule("__main__"); + globals = PyModule_GetDict(mainmod); + Py_INCREF(globals); + + new_stdin = PyFile_FromFile(input, "", "r", NULL); + new_stdout = PyFile_FromFile(output, "", "w", NULL); + + PySys_SetObject("stdin", new_stdin); + PySys_SetObject("stdout", new_stdout); + PySys_SetObject("stderr", new_stdout); + + for (n = 1; !PyErr_Occurred(); n++) { + Py_BEGIN_ALLOW_THREADS + fprintf(output, "%d> ", n); + p = fgets(buffer, sizeof buffer, input); + Py_END_ALLOW_THREADS + + if (p == NULL) + break; + if (p[0] == '\377' && p[1] == '\354') + break; + + q = strrchr(p, '\r'); + if (q && q[1] == '\n' && q[2] == '\0') { + *q++ = '\n'; + *q++ = '\0'; + } + + while (*p && isspace(*p)) + p++; + if (p[0] == '#' || p[0] == '\0') + continue; + + end = run_command(buffer, globals); + if (end < 0) + PyErr_Print(); + + if (end) + break; + } + + Py_XDECREF(globals); + Py_XDECREF(new_stdin); + Py_XDECREF(new_stdout); - Py_EndInterpreter(tstate); - PyEval_ReleaseLock(); + Py_EndInterpreter(tstate); + PyEval_ReleaseLock(); - fprintf(output, "Goodbye!\n"); + fprintf(output, "Goodbye!\n"); } static int run_command(char *buffer, PyObject *globals) { - PyObject *m, *d, *v; - fprintf(stderr, "run_command: %s", buffer); - if (strchr(buffer, '\n') == NULL) - fprintf(stderr, "\n"); - v = PyRun_String(buffer, Py_single_input, globals, globals); - if (v == NULL) { - if (PyErr_Occurred() == PyExc_SystemExit) { - PyErr_Clear(); - return 1; - } - PyErr_Print(); - return 0; - } - Py_DECREF(v); - return 0; + PyObject *m, *d, *v; + fprintf(stderr, "run_command: %s", buffer); + if (strchr(buffer, '\n') == NULL) + fprintf(stderr, "\n"); + v = PyRun_String(buffer, Py_single_input, globals, globals); + if (v == NULL) { + if (PyErr_Occurred() == PyExc_SystemExit) { + PyErr_Clear(); + return 1; + } + PyErr_Print(); + return 0; + } + Py_DECREF(v); + return 0; } static void ps(void) { - char buffer[100]; - PyOS_snprintf(buffer, sizeof(buffer), - "ps -l -p %d ob_type->tp_as_buffer != NULL) && \ - ((obj)->ob_type->tp_as_buffer->bf_getbuffer != NULL)) + (((obj)->ob_type->tp_as_buffer != NULL) && \ + ((obj)->ob_type->tp_as_buffer->bf_getbuffer != NULL)) - /* Return 1 if the getbuffer function is available, otherwise - return 0 */ + /* Return 1 if the getbuffer function is available, otherwise + return 0 */ - PyAPI_FUNC(int) PyObject_GetBuffer(PyObject *obj, Py_buffer *view, - int flags); + PyAPI_FUNC(int) PyObject_GetBuffer(PyObject *obj, Py_buffer *view, + int flags); - /* This is a C-API version of the getbuffer function call. It checks - to make sure object has the required function pointer and issues the - call. Returns -1 and raises an error on failure and returns 0 on - success - */ + /* This is a C-API version of the getbuffer function call. It checks + to make sure object has the required function pointer and issues the + call. Returns -1 and raises an error on failure and returns 0 on + success + */ PyAPI_FUNC(void *) PyBuffer_GetPointer(Py_buffer *view, Py_ssize_t *indices); - - /* Get the memory area pointed to by the indices for the buffer given. - Note that view->ndim is the assumed size of indices - */ + + /* Get the memory area pointed to by the indices for the buffer given. + Note that view->ndim is the assumed size of indices + */ PyAPI_FUNC(int) PyBuffer_SizeFromFormat(const char *); - - /* Return the implied itemsize of the data-format area from a - struct-style description */ - - + /* Return the implied itemsize of the data-format area from a + struct-style description */ + + + PyAPI_FUNC(int) PyBuffer_ToContiguous(void *buf, Py_buffer *view, - Py_ssize_t len, char fort); + Py_ssize_t len, char fort); - PyAPI_FUNC(int) PyBuffer_FromContiguous(Py_buffer *view, void *buf, - Py_ssize_t len, char fort); + PyAPI_FUNC(int) PyBuffer_FromContiguous(Py_buffer *view, void *buf, + Py_ssize_t len, char fort); - /* Copy len bytes of data from the contiguous chunk of memory - pointed to by buf into the buffer exported by obj. Return - 0 on success and return -1 and raise a PyBuffer_Error on - error (i.e. the object does not have a buffer interface or - it is not working). - - If fort is 'F', then if the object is multi-dimensional, - then the data will be copied into the array in - Fortran-style (first dimension varies the fastest). If - fort is 'C', then the data will be copied into the array - in C-style (last dimension varies the fastest). If fort - is 'A', then it does not matter and the copy will be made - in whatever way is more efficient. + /* Copy len bytes of data from the contiguous chunk of memory + pointed to by buf into the buffer exported by obj. Return + 0 on success and return -1 and raise a PyBuffer_Error on + error (i.e. the object does not have a buffer interface or + it is not working). + + If fort is 'F', then if the object is multi-dimensional, + then the data will be copied into the array in + Fortran-style (first dimension varies the fastest). If + fort is 'C', then the data will be copied into the array + in C-style (last dimension varies the fastest). If fort + is 'A', then it does not matter and the copy will be made + in whatever way is more efficient. - */ + */ PyAPI_FUNC(int) PyObject_CopyData(PyObject *dest, PyObject *src); - - /* Copy the data from the src buffer to the buffer of destination - */ + + /* Copy the data from the src buffer to the buffer of destination + */ PyAPI_FUNC(int) PyBuffer_IsContiguous(Py_buffer *view, char fort); - PyAPI_FUNC(void) PyBuffer_FillContiguousStrides(int ndims, - Py_ssize_t *shape, - Py_ssize_t *strides, - int itemsize, - char fort); - - /* Fill the strides array with byte-strides of a contiguous - (Fortran-style if fort is 'F' or C-style otherwise) - array of the given shape with the given number of bytes - per element. - */ + PyAPI_FUNC(void) PyBuffer_FillContiguousStrides(int ndims, + Py_ssize_t *shape, + Py_ssize_t *strides, + int itemsize, + char fort); + + /* Fill the strides array with byte-strides of a contiguous + (Fortran-style if fort is 'F' or C-style otherwise) + array of the given shape with the given number of bytes + per element. + */ PyAPI_FUNC(int) PyBuffer_FillInfo(Py_buffer *view, PyObject *o, void *buf, - Py_ssize_t len, int readonly, - int flags); + Py_ssize_t len, int readonly, + int flags); - /* Fills in a buffer-info structure correctly for an exporter - that can only share a contiguous chunk of memory of - "unsigned bytes" of the given length. Returns 0 on success - and -1 (with raising an error) on error. - */ + /* Fills in a buffer-info structure correctly for an exporter + that can only share a contiguous chunk of memory of + "unsigned bytes" of the given length. Returns 0 on success + and -1 (with raising an error) on error. + */ PyAPI_FUNC(void) PyBuffer_Release(Py_buffer *view); /* Releases a Py_buffer obtained from getbuffer ParseTuple's s*. - */ + */ PyAPI_FUNC(PyObject *) PyObject_Format(PyObject* obj, - PyObject *format_spec); + PyObject *format_spec); /* - Takes an arbitrary object and returns the result of - calling obj.__format__(format_spec). + Takes an arbitrary object and returns the result of + calling obj.__format__(format_spec). */ /* Iterators */ PyAPI_FUNC(PyObject *) PyObject_GetIter(PyObject *); /* Takes an object and returns an iterator for it. - This is typically a new iterator but if the argument - is an iterator, this returns itself. */ + This is typically a new iterator but if the argument + is an iterator, this returns itself. */ #define PyIter_Check(obj) \ ((obj)->ob_type->tp_iternext != NULL && \ @@ -594,314 +594,314 @@ PyAPI_FUNC(PyObject *) PyIter_Next(PyObject *); /* Takes an iterator object and calls its tp_iternext slot, - returning the next value. If the iterator is exhausted, - this returns NULL without setting an exception. - NULL with an exception means an error occurred. */ + returning the next value. If the iterator is exhausted, + this returns NULL without setting an exception. + NULL with an exception means an error occurred. */ /* Number Protocol:*/ PyAPI_FUNC(int) PyNumber_Check(PyObject *o); /* - Returns 1 if the object, o, provides numeric protocols, and - false otherwise. + Returns 1 if the object, o, provides numeric protocols, and + false otherwise. - This function always succeeds. + This function always succeeds. */ PyAPI_FUNC(PyObject *) PyNumber_Add(PyObject *o1, PyObject *o2); /* - Returns the result of adding o1 and o2, or null on failure. - This is the equivalent of the Python expression: o1+o2. + Returns the result of adding o1 and o2, or null on failure. + This is the equivalent of the Python expression: o1+o2. */ PyAPI_FUNC(PyObject *) PyNumber_Subtract(PyObject *o1, PyObject *o2); /* - Returns the result of subtracting o2 from o1, or null on - failure. This is the equivalent of the Python expression: - o1-o2. + Returns the result of subtracting o2 from o1, or null on + failure. This is the equivalent of the Python expression: + o1-o2. */ PyAPI_FUNC(PyObject *) PyNumber_Multiply(PyObject *o1, PyObject *o2); /* - Returns the result of multiplying o1 and o2, or null on - failure. This is the equivalent of the Python expression: - o1*o2. + Returns the result of multiplying o1 and o2, or null on + failure. This is the equivalent of the Python expression: + o1*o2. */ PyAPI_FUNC(PyObject *) PyNumber_FloorDivide(PyObject *o1, PyObject *o2); /* - Returns the result of dividing o1 by o2 giving an integral result, - or null on failure. - This is the equivalent of the Python expression: o1//o2. + Returns the result of dividing o1 by o2 giving an integral result, + or null on failure. + This is the equivalent of the Python expression: o1//o2. */ PyAPI_FUNC(PyObject *) PyNumber_TrueDivide(PyObject *o1, PyObject *o2); /* - Returns the result of dividing o1 by o2 giving a float result, - or null on failure. - This is the equivalent of the Python expression: o1/o2. + Returns the result of dividing o1 by o2 giving a float result, + or null on failure. + This is the equivalent of the Python expression: o1/o2. */ PyAPI_FUNC(PyObject *) PyNumber_Remainder(PyObject *o1, PyObject *o2); /* - Returns the remainder of dividing o1 by o2, or null on - failure. This is the equivalent of the Python expression: - o1%o2. + Returns the remainder of dividing o1 by o2, or null on + failure. This is the equivalent of the Python expression: + o1%o2. */ PyAPI_FUNC(PyObject *) PyNumber_Divmod(PyObject *o1, PyObject *o2); /* - See the built-in function divmod. Returns NULL on failure. - This is the equivalent of the Python expression: - divmod(o1,o2). + See the built-in function divmod. Returns NULL on failure. + This is the equivalent of the Python expression: + divmod(o1,o2). */ PyAPI_FUNC(PyObject *) PyNumber_Power(PyObject *o1, PyObject *o2, PyObject *o3); /* - See the built-in function pow. Returns NULL on failure. - This is the equivalent of the Python expression: - pow(o1,o2,o3), where o3 is optional. + See the built-in function pow. Returns NULL on failure. + This is the equivalent of the Python expression: + pow(o1,o2,o3), where o3 is optional. */ PyAPI_FUNC(PyObject *) PyNumber_Negative(PyObject *o); /* - Returns the negation of o on success, or null on failure. - This is the equivalent of the Python expression: -o. + Returns the negation of o on success, or null on failure. + This is the equivalent of the Python expression: -o. */ PyAPI_FUNC(PyObject *) PyNumber_Positive(PyObject *o); /* - Returns the (what?) of o on success, or NULL on failure. - This is the equivalent of the Python expression: +o. + Returns the (what?) of o on success, or NULL on failure. + This is the equivalent of the Python expression: +o. */ PyAPI_FUNC(PyObject *) PyNumber_Absolute(PyObject *o); /* - Returns the absolute value of o, or null on failure. This is - the equivalent of the Python expression: abs(o). + Returns the absolute value of o, or null on failure. This is + the equivalent of the Python expression: abs(o). */ PyAPI_FUNC(PyObject *) PyNumber_Invert(PyObject *o); /* - Returns the bitwise negation of o on success, or NULL on - failure. This is the equivalent of the Python expression: - ~o. + Returns the bitwise negation of o on success, or NULL on + failure. This is the equivalent of the Python expression: + ~o. */ PyAPI_FUNC(PyObject *) PyNumber_Lshift(PyObject *o1, PyObject *o2); /* - Returns the result of left shifting o1 by o2 on success, or - NULL on failure. This is the equivalent of the Python - expression: o1 << o2. + Returns the result of left shifting o1 by o2 on success, or + NULL on failure. This is the equivalent of the Python + expression: o1 << o2. */ PyAPI_FUNC(PyObject *) PyNumber_Rshift(PyObject *o1, PyObject *o2); /* - Returns the result of right shifting o1 by o2 on success, or - NULL on failure. This is the equivalent of the Python - expression: o1 >> o2. + Returns the result of right shifting o1 by o2 on success, or + NULL on failure. This is the equivalent of the Python + expression: o1 >> o2. */ PyAPI_FUNC(PyObject *) PyNumber_And(PyObject *o1, PyObject *o2); /* - Returns the result of bitwise and of o1 and o2 on success, or - NULL on failure. This is the equivalent of the Python - expression: o1&o2. + Returns the result of bitwise and of o1 and o2 on success, or + NULL on failure. This is the equivalent of the Python + expression: o1&o2. */ PyAPI_FUNC(PyObject *) PyNumber_Xor(PyObject *o1, PyObject *o2); /* - Returns the bitwise exclusive or of o1 by o2 on success, or - NULL on failure. This is the equivalent of the Python - expression: o1^o2. + Returns the bitwise exclusive or of o1 by o2 on success, or + NULL on failure. This is the equivalent of the Python + expression: o1^o2. */ PyAPI_FUNC(PyObject *) PyNumber_Or(PyObject *o1, PyObject *o2); /* - Returns the result of bitwise or on o1 and o2 on success, or - NULL on failure. This is the equivalent of the Python - expression: o1|o2. + Returns the result of bitwise or on o1 and o2 on success, or + NULL on failure. This is the equivalent of the Python + expression: o1|o2. */ #define PyIndex_Check(obj) \ ((obj)->ob_type->tp_as_number != NULL && \ (obj)->ob_type->tp_as_number->nb_index != NULL) - + PyAPI_FUNC(PyObject *) PyNumber_Index(PyObject *o); /* - Returns the object converted to a Python long or int - or NULL with an error raised on failure. + Returns the object converted to a Python long or int + or NULL with an error raised on failure. */ PyAPI_FUNC(Py_ssize_t) PyNumber_AsSsize_t(PyObject *o, PyObject *exc); /* - Returns the Integral instance converted to an int. The - instance is expected to be int or long or have an __int__ - method. Steals integral's reference. error_format will be - used to create the TypeError if integral isn't actually an - Integral instance. error_format should be a format string - that can accept a char* naming integral's type. + Returns the Integral instance converted to an int. The + instance is expected to be int or long or have an __int__ + method. Steals integral's reference. error_format will be + used to create the TypeError if integral isn't actually an + Integral instance. error_format should be a format string + that can accept a char* naming integral's type. */ PyAPI_FUNC(PyObject *) _PyNumber_ConvertIntegralToInt( - PyObject *integral, - const char* error_format); + PyObject *integral, + const char* error_format); /* - Returns the object converted to Py_ssize_t by going through - PyNumber_Index first. If an overflow error occurs while - converting the int-or-long to Py_ssize_t, then the second argument - is the error-type to return. If it is NULL, then the overflow error - is cleared and the value is clipped. + Returns the object converted to Py_ssize_t by going through + PyNumber_Index first. If an overflow error occurs while + converting the int-or-long to Py_ssize_t, then the second argument + is the error-type to return. If it is NULL, then the overflow error + is cleared and the value is clipped. */ PyAPI_FUNC(PyObject *) PyNumber_Long(PyObject *o); /* - Returns the o converted to an integer object on success, or - NULL on failure. This is the equivalent of the Python - expression: int(o). + Returns the o converted to an integer object on success, or + NULL on failure. This is the equivalent of the Python + expression: int(o). */ PyAPI_FUNC(PyObject *) PyNumber_Float(PyObject *o); /* - Returns the o converted to a float object on success, or NULL - on failure. This is the equivalent of the Python expression: - float(o). + Returns the o converted to a float object on success, or NULL + on failure. This is the equivalent of the Python expression: + float(o). */ - + /* In-place variants of (some of) the above number protocol functions */ PyAPI_FUNC(PyObject *) PyNumber_InPlaceAdd(PyObject *o1, PyObject *o2); /* - Returns the result of adding o2 to o1, possibly in-place, or null - on failure. This is the equivalent of the Python expression: - o1 += o2. + Returns the result of adding o2 to o1, possibly in-place, or null + on failure. This is the equivalent of the Python expression: + o1 += o2. */ PyAPI_FUNC(PyObject *) PyNumber_InPlaceSubtract(PyObject *o1, PyObject *o2); /* - Returns the result of subtracting o2 from o1, possibly in-place or - null on failure. This is the equivalent of the Python expression: - o1 -= o2. + Returns the result of subtracting o2 from o1, possibly in-place or + null on failure. This is the equivalent of the Python expression: + o1 -= o2. */ PyAPI_FUNC(PyObject *) PyNumber_InPlaceMultiply(PyObject *o1, PyObject *o2); /* - Returns the result of multiplying o1 by o2, possibly in-place, or - null on failure. This is the equivalent of the Python expression: - o1 *= o2. + Returns the result of multiplying o1 by o2, possibly in-place, or + null on failure. This is the equivalent of the Python expression: + o1 *= o2. */ PyAPI_FUNC(PyObject *) PyNumber_InPlaceFloorDivide(PyObject *o1, - PyObject *o2); + PyObject *o2); /* - Returns the result of dividing o1 by o2 giving an integral result, - possibly in-place, or null on failure. - This is the equivalent of the Python expression: - o1 /= o2. + Returns the result of dividing o1 by o2 giving an integral result, + possibly in-place, or null on failure. + This is the equivalent of the Python expression: + o1 /= o2. */ PyAPI_FUNC(PyObject *) PyNumber_InPlaceTrueDivide(PyObject *o1, - PyObject *o2); + PyObject *o2); /* - Returns the result of dividing o1 by o2 giving a float result, - possibly in-place, or null on failure. - This is the equivalent of the Python expression: - o1 /= o2. + Returns the result of dividing o1 by o2 giving a float result, + possibly in-place, or null on failure. + This is the equivalent of the Python expression: + o1 /= o2. */ PyAPI_FUNC(PyObject *) PyNumber_InPlaceRemainder(PyObject *o1, PyObject *o2); /* - Returns the remainder of dividing o1 by o2, possibly in-place, or - null on failure. This is the equivalent of the Python expression: - o1 %= o2. + Returns the remainder of dividing o1 by o2, possibly in-place, or + null on failure. This is the equivalent of the Python expression: + o1 %= o2. */ PyAPI_FUNC(PyObject *) PyNumber_InPlacePower(PyObject *o1, PyObject *o2, - PyObject *o3); + PyObject *o3); /* - Returns the result of raising o1 to the power of o2, possibly - in-place, or null on failure. This is the equivalent of the Python - expression: o1 **= o2, or pow(o1, o2, o3) if o3 is present. + Returns the result of raising o1 to the power of o2, possibly + in-place, or null on failure. This is the equivalent of the Python + expression: o1 **= o2, or pow(o1, o2, o3) if o3 is present. */ PyAPI_FUNC(PyObject *) PyNumber_InPlaceLshift(PyObject *o1, PyObject *o2); /* - Returns the result of left shifting o1 by o2, possibly in-place, or - null on failure. This is the equivalent of the Python expression: - o1 <<= o2. + Returns the result of left shifting o1 by o2, possibly in-place, or + null on failure. This is the equivalent of the Python expression: + o1 <<= o2. */ PyAPI_FUNC(PyObject *) PyNumber_InPlaceRshift(PyObject *o1, PyObject *o2); /* - Returns the result of right shifting o1 by o2, possibly in-place or - null on failure. This is the equivalent of the Python expression: - o1 >>= o2. + Returns the result of right shifting o1 by o2, possibly in-place or + null on failure. This is the equivalent of the Python expression: + o1 >>= o2. */ PyAPI_FUNC(PyObject *) PyNumber_InPlaceAnd(PyObject *o1, PyObject *o2); /* - Returns the result of bitwise and of o1 and o2, possibly in-place, - or null on failure. This is the equivalent of the Python - expression: o1 &= o2. + Returns the result of bitwise and of o1 and o2, possibly in-place, + or null on failure. This is the equivalent of the Python + expression: o1 &= o2. */ PyAPI_FUNC(PyObject *) PyNumber_InPlaceXor(PyObject *o1, PyObject *o2); /* - Returns the bitwise exclusive or of o1 by o2, possibly in-place, or - null on failure. This is the equivalent of the Python expression: - o1 ^= o2. + Returns the bitwise exclusive or of o1 by o2, possibly in-place, or + null on failure. This is the equivalent of the Python expression: + o1 ^= o2. */ PyAPI_FUNC(PyObject *) PyNumber_InPlaceOr(PyObject *o1, PyObject *o2); /* - Returns the result of bitwise or of o1 and o2, possibly in-place, - or null on failure. This is the equivalent of the Python - expression: o1 |= o2. + Returns the result of bitwise or of o1 and o2, possibly in-place, + or null on failure. This is the equivalent of the Python + expression: o1 |= o2. */ PyAPI_FUNC(PyObject *) PyNumber_ToBase(PyObject *n, int base); /* - Returns the integer n converted to a string with a base, with a base - marker of 0b, 0o or 0x prefixed if applicable. - If n is not an int object, it is converted with PyNumber_Index first. + Returns the integer n converted to a string with a base, with a base + marker of 0b, 0o or 0x prefixed if applicable. + If n is not an int object, it is converted with PyNumber_Index first. */ @@ -910,16 +910,16 @@ PyAPI_FUNC(int) PySequence_Check(PyObject *o); /* - Return 1 if the object provides sequence protocol, and zero - otherwise. + Return 1 if the object provides sequence protocol, and zero + otherwise. - This function always succeeds. + This function always succeeds. */ PyAPI_FUNC(Py_ssize_t) PySequence_Size(PyObject *o); /* - Return the size of sequence object o, or -1 on failure. + Return the size of sequence object o, or -1 on failure. */ /* For DLL compatibility */ @@ -931,147 +931,147 @@ PyAPI_FUNC(PyObject *) PySequence_Concat(PyObject *o1, PyObject *o2); /* - Return the concatenation of o1 and o2 on success, and NULL on - failure. This is the equivalent of the Python - expression: o1+o2. + Return the concatenation of o1 and o2 on success, and NULL on + failure. This is the equivalent of the Python + expression: o1+o2. */ PyAPI_FUNC(PyObject *) PySequence_Repeat(PyObject *o, Py_ssize_t count); /* - Return the result of repeating sequence object o count times, - or NULL on failure. This is the equivalent of the Python - expression: o1*count. + Return the result of repeating sequence object o count times, + or NULL on failure. This is the equivalent of the Python + expression: o1*count. */ PyAPI_FUNC(PyObject *) PySequence_GetItem(PyObject *o, Py_ssize_t i); /* - Return the ith element of o, or NULL on failure. This is the - equivalent of the Python expression: o[i]. + Return the ith element of o, or NULL on failure. This is the + equivalent of the Python expression: o[i]. */ PyAPI_FUNC(PyObject *) PySequence_GetSlice(PyObject *o, Py_ssize_t i1, Py_ssize_t i2); /* - Return the slice of sequence object o between i1 and i2, or - NULL on failure. This is the equivalent of the Python - expression: o[i1:i2]. + Return the slice of sequence object o between i1 and i2, or + NULL on failure. This is the equivalent of the Python + expression: o[i1:i2]. */ PyAPI_FUNC(int) PySequence_SetItem(PyObject *o, Py_ssize_t i, PyObject *v); /* - Assign object v to the ith element of o. Returns - -1 on failure. This is the equivalent of the Python - statement: o[i]=v. + Assign object v to the ith element of o. Returns + -1 on failure. This is the equivalent of the Python + statement: o[i]=v. */ PyAPI_FUNC(int) PySequence_DelItem(PyObject *o, Py_ssize_t i); /* - Delete the ith element of object v. Returns - -1 on failure. This is the equivalent of the Python - statement: del o[i]. + Delete the ith element of object v. Returns + -1 on failure. This is the equivalent of the Python + statement: del o[i]. */ PyAPI_FUNC(int) PySequence_SetSlice(PyObject *o, Py_ssize_t i1, Py_ssize_t i2, PyObject *v); /* - Assign the sequence object, v, to the slice in sequence - object, o, from i1 to i2. Returns -1 on failure. This is the - equivalent of the Python statement: o[i1:i2]=v. + Assign the sequence object, v, to the slice in sequence + object, o, from i1 to i2. Returns -1 on failure. This is the + equivalent of the Python statement: o[i1:i2]=v. */ PyAPI_FUNC(int) PySequence_DelSlice(PyObject *o, Py_ssize_t i1, Py_ssize_t i2); /* - Delete the slice in sequence object, o, from i1 to i2. - Returns -1 on failure. This is the equivalent of the Python - statement: del o[i1:i2]. + Delete the slice in sequence object, o, from i1 to i2. + Returns -1 on failure. This is the equivalent of the Python + statement: del o[i1:i2]. */ PyAPI_FUNC(PyObject *) PySequence_Tuple(PyObject *o); /* - Returns the sequence, o, as a tuple on success, and NULL on failure. - This is equivalent to the Python expression: tuple(o) + Returns the sequence, o, as a tuple on success, and NULL on failure. + This is equivalent to the Python expression: tuple(o) */ PyAPI_FUNC(PyObject *) PySequence_List(PyObject *o); /* - Returns the sequence, o, as a list on success, and NULL on failure. - This is equivalent to the Python expression: list(o) + Returns the sequence, o, as a list on success, and NULL on failure. + This is equivalent to the Python expression: list(o) */ PyAPI_FUNC(PyObject *) PySequence_Fast(PyObject *o, const char* m); /* - Returns the sequence, o, as a tuple, unless it's already a - tuple or list. Use PySequence_Fast_GET_ITEM to access the - members of this list, and PySequence_Fast_GET_SIZE to get its length. + Returns the sequence, o, as a tuple, unless it's already a + tuple or list. Use PySequence_Fast_GET_ITEM to access the + members of this list, and PySequence_Fast_GET_SIZE to get its length. - Returns NULL on failure. If the object does not support iteration, - raises a TypeError exception with m as the message text. + Returns NULL on failure. If the object does not support iteration, + raises a TypeError exception with m as the message text. */ #define PySequence_Fast_GET_SIZE(o) \ - (PyList_Check(o) ? PyList_GET_SIZE(o) : PyTuple_GET_SIZE(o)) + (PyList_Check(o) ? PyList_GET_SIZE(o) : PyTuple_GET_SIZE(o)) /* - Return the size of o, assuming that o was returned by - PySequence_Fast and is not NULL. + Return the size of o, assuming that o was returned by + PySequence_Fast and is not NULL. */ #define PySequence_Fast_GET_ITEM(o, i)\ (PyList_Check(o) ? PyList_GET_ITEM(o, i) : PyTuple_GET_ITEM(o, i)) /* - Return the ith element of o, assuming that o was returned by - PySequence_Fast, and that i is within bounds. + Return the ith element of o, assuming that o was returned by + PySequence_Fast, and that i is within bounds. */ #define PySequence_ITEM(o, i)\ - ( Py_TYPE(o)->tp_as_sequence->sq_item(o, i) ) + ( Py_TYPE(o)->tp_as_sequence->sq_item(o, i) ) /* Assume tp_as_sequence and sq_item exist and that i does not - need to be corrected for a negative index - */ + need to be corrected for a negative index + */ #define PySequence_Fast_ITEMS(sf) \ - (PyList_Check(sf) ? ((PyListObject *)(sf))->ob_item \ - : ((PyTupleObject *)(sf))->ob_item) - /* Return a pointer to the underlying item array for - an object retured by PySequence_Fast */ + (PyList_Check(sf) ? ((PyListObject *)(sf))->ob_item \ + : ((PyTupleObject *)(sf))->ob_item) + /* Return a pointer to the underlying item array for + an object retured by PySequence_Fast */ PyAPI_FUNC(Py_ssize_t) PySequence_Count(PyObject *o, PyObject *value); /* - Return the number of occurrences on value on o, that is, - return the number of keys for which o[key]==value. On - failure, return -1. This is equivalent to the Python - expression: o.count(value). + Return the number of occurrences on value on o, that is, + return the number of keys for which o[key]==value. On + failure, return -1. This is equivalent to the Python + expression: o.count(value). */ PyAPI_FUNC(int) PySequence_Contains(PyObject *seq, PyObject *ob); /* - Return -1 if error; 1 if ob in seq; 0 if ob not in seq. - Use __contains__ if possible, else _PySequence_IterSearch(). + Return -1 if error; 1 if ob in seq; 0 if ob not in seq. + Use __contains__ if possible, else _PySequence_IterSearch(). */ #define PY_ITERSEARCH_COUNT 1 #define PY_ITERSEARCH_INDEX 2 #define PY_ITERSEARCH_CONTAINS 3 PyAPI_FUNC(Py_ssize_t) _PySequence_IterSearch(PyObject *seq, - PyObject *obj, int operation); - /* - Iterate over seq. Result depends on the operation: - PY_ITERSEARCH_COUNT: return # of times obj appears in seq; -1 if - error. - PY_ITERSEARCH_INDEX: return 0-based index of first occurrence of - obj in seq; set ValueError and return -1 if none found; - also return -1 on error. - PY_ITERSEARCH_CONTAINS: return 1 if obj in seq, else 0; -1 on - error. - */ + PyObject *obj, int operation); + /* + Iterate over seq. Result depends on the operation: + PY_ITERSEARCH_COUNT: return # of times obj appears in seq; -1 if + error. + PY_ITERSEARCH_INDEX: return 0-based index of first occurrence of + obj in seq; set ValueError and return -1 if none found; + also return -1 on error. + PY_ITERSEARCH_CONTAINS: return 1 if obj in seq, else 0; -1 on + error. + */ /* For DLL-level backwards compatibility */ #undef PySequence_In @@ -1081,17 +1081,17 @@ #define PySequence_In PySequence_Contains /* - Determine if o contains value. If an item in o is equal to - X, return 1, otherwise return 0. On error, return -1. This - is equivalent to the Python expression: value in o. + Determine if o contains value. If an item in o is equal to + X, return 1, otherwise return 0. On error, return -1. This + is equivalent to the Python expression: value in o. */ PyAPI_FUNC(Py_ssize_t) PySequence_Index(PyObject *o, PyObject *value); /* - Return the first index for which o[i]=value. On error, - return -1. This is equivalent to the Python - expression: o.index(value). + Return the first index for which o[i]=value. On error, + return -1. This is equivalent to the Python + expression: o.index(value). */ /* In-place versions of some of the above Sequence functions. */ @@ -1099,18 +1099,18 @@ PyAPI_FUNC(PyObject *) PySequence_InPlaceConcat(PyObject *o1, PyObject *o2); /* - Append o2 to o1, in-place when possible. Return the resulting - object, which could be o1, or NULL on failure. This is the - equivalent of the Python expression: o1 += o2. + Append o2 to o1, in-place when possible. Return the resulting + object, which could be o1, or NULL on failure. This is the + equivalent of the Python expression: o1 += o2. */ PyAPI_FUNC(PyObject *) PySequence_InPlaceRepeat(PyObject *o, Py_ssize_t count); /* - Repeat o1 by count, in-place when possible. Return the resulting - object, which could be o1, or NULL on failure. This is the - equivalent of the Python expression: o1 *= count. + Repeat o1 by count, in-place when possible. Return the resulting + object, which could be o1, or NULL on failure. This is the + equivalent of the Python expression: o1 *= count. */ @@ -1119,18 +1119,18 @@ PyAPI_FUNC(int) PyMapping_Check(PyObject *o); /* - Return 1 if the object provides mapping protocol, and zero - otherwise. + Return 1 if the object provides mapping protocol, and zero + otherwise. - This function always succeeds. + This function always succeeds. */ PyAPI_FUNC(Py_ssize_t) PyMapping_Size(PyObject *o); /* - Returns the number of keys in object o on success, and -1 on - failure. For objects that do not provide sequence protocol, - this is equivalent to the Python expression: len(o). + Returns the number of keys in object o on success, and -1 on + failure. For objects that do not provide sequence protocol, + this is equivalent to the Python expression: len(o). */ /* For DLL compatibility */ @@ -1143,9 +1143,9 @@ int PyMapping_DelItemString(PyObject *o, char *key); - Remove the mapping for object, key, from the object *o. - Returns -1 on failure. This is equivalent to - the Python statement: del o[key]. + Remove the mapping for object, key, from the object *o. + Returns -1 on failure. This is equivalent to + the Python statement: del o[key]. */ #define PyMapping_DelItemString(O,K) PyObject_DelItemString((O),(K)) @@ -1153,71 +1153,71 @@ int PyMapping_DelItem(PyObject *o, PyObject *key); - Remove the mapping for object, key, from the object *o. - Returns -1 on failure. This is equivalent to - the Python statement: del o[key]. + Remove the mapping for object, key, from the object *o. + Returns -1 on failure. This is equivalent to + the Python statement: del o[key]. */ #define PyMapping_DelItem(O,K) PyObject_DelItem((O),(K)) PyAPI_FUNC(int) PyMapping_HasKeyString(PyObject *o, char *key); /* - On success, return 1 if the mapping object has the key, key, - and 0 otherwise. This is equivalent to the Python expression: - key in o. + On success, return 1 if the mapping object has the key, key, + and 0 otherwise. This is equivalent to the Python expression: + key in o. - This function always succeeds. + This function always succeeds. */ PyAPI_FUNC(int) PyMapping_HasKey(PyObject *o, PyObject *key); /* - Return 1 if the mapping object has the key, key, - and 0 otherwise. This is equivalent to the Python expression: - key in o. + Return 1 if the mapping object has the key, key, + and 0 otherwise. This is equivalent to the Python expression: + key in o. - This function always succeeds. + This function always succeeds. */ PyAPI_FUNC(PyObject *) PyMapping_Keys(PyObject *o); /* - On success, return a list or tuple of the keys in object o. - On failure, return NULL. + On success, return a list or tuple of the keys in object o. + On failure, return NULL. */ PyAPI_FUNC(PyObject *) PyMapping_Values(PyObject *o); /* - On success, return a list or tuple of the values in object o. - On failure, return NULL. + On success, return a list or tuple of the values in object o. + On failure, return NULL. */ PyAPI_FUNC(PyObject *) PyMapping_Items(PyObject *o); /* - On success, return a list or tuple of the items in object o, - where each item is a tuple containing a key-value pair. - On failure, return NULL. + On success, return a list or tuple of the items in object o, + where each item is a tuple containing a key-value pair. + On failure, return NULL. */ PyAPI_FUNC(PyObject *) PyMapping_GetItemString(PyObject *o, char *key); /* - Return element of o corresponding to the object, key, or NULL - on failure. This is the equivalent of the Python expression: - o[key]. + Return element of o corresponding to the object, key, or NULL + on failure. This is the equivalent of the Python expression: + o[key]. */ PyAPI_FUNC(int) PyMapping_SetItemString(PyObject *o, char *key, PyObject *value); /* - Map the object, key, to the value, v. Returns - -1 on failure. This is the equivalent of the Python - statement: o[key]=v. + Map the object, key, to the value, v. Returns + -1 on failure. This is the equivalent of the Python + statement: o[key]=v. */ Modified: python/branches/py3k-jit/Include/ceval.h ============================================================================== --- python/branches/py3k-jit/Include/ceval.h (original) +++ python/branches/py3k-jit/Include/ceval.h Mon May 10 23:55:43 2010 @@ -8,11 +8,11 @@ /* Interface to random parts in ceval.c */ PyAPI_FUNC(PyObject *) PyEval_CallObjectWithKeywords( - PyObject *, PyObject *, PyObject *); + PyObject *, PyObject *, PyObject *); /* Inline this */ #define PyEval_CallObject(func,arg) \ - PyEval_CallObjectWithKeywords(func, arg, (PyObject *)NULL) + PyEval_CallObjectWithKeywords(func, arg, (PyObject *)NULL) PyAPI_FUNC(PyObject *) PyEval_CallFunction(PyObject *obj, const char *format, ...); @@ -45,7 +45,7 @@ exceeds the current recursion limit. It raises a RuntimeError, and sets the "overflowed" flag in the thread state structure. This flag temporarily *disables* the normal protection; this allows cleanup code - to potentially outgrow the recursion limit while processing the + to potentially outgrow the recursion limit while processing the RuntimeError. * "last chance" anti-recursion protection is triggered when the recursion level exceeds "current recursion limit + 50". By construction, this @@ -67,12 +67,12 @@ PyAPI_FUNC(int) Py_GetRecursionLimit(void); #define Py_EnterRecursiveCall(where) \ - (_Py_MakeRecCheck(PyThreadState_GET()->recursion_depth) && \ - _Py_CheckRecursiveCall(where)) -#define Py_LeaveRecursiveCall() \ + (_Py_MakeRecCheck(PyThreadState_GET()->recursion_depth) && \ + _Py_CheckRecursiveCall(where)) +#define Py_LeaveRecursiveCall() \ do{ if(_Py_MakeEndRecCheck(PyThreadState_GET()->recursion_depth)) \ - PyThreadState_GET()->overflowed = 0; \ - } while(0) + PyThreadState_GET()->overflowed = 0; \ + } while(0) PyAPI_FUNC(int) _Py_CheckRecursiveCall(char *where); PyAPI_DATA(int) _Py_CheckRecursionLimit; @@ -83,15 +83,15 @@ of _Py_CheckRecursionLimit for _Py_MakeEndRecCheck() to function properly. */ # define _Py_MakeRecCheck(x) \ - (++(x) > (_Py_CheckRecursionLimit += PyThreadState_GET()->overflowed - 1)) + (++(x) > (_Py_CheckRecursionLimit += PyThreadState_GET()->overflowed - 1)) #else # define _Py_MakeRecCheck(x) (++(x) > _Py_CheckRecursionLimit) #endif #define _Py_MakeEndRecCheck(x) \ - (--(x) < ((_Py_CheckRecursionLimit > 100) \ - ? (_Py_CheckRecursionLimit - 50) \ - : (3 * (_Py_CheckRecursionLimit >> 2)))) + (--(x) < ((_Py_CheckRecursionLimit > 100) \ + ? (_Py_CheckRecursionLimit - 50) \ + : (3 * (_Py_CheckRecursionLimit >> 2)))) #define Py_ALLOW_RECURSION \ do { unsigned char _old = PyThreadState_GET()->recursion_critical;\ @@ -114,31 +114,31 @@ that lasts a long time and doesn't touch Python data) can allow other threads to run as follows: - ...preparations here... - Py_BEGIN_ALLOW_THREADS - ...blocking system call here... - Py_END_ALLOW_THREADS - ...interpret result here... + ...preparations here... + Py_BEGIN_ALLOW_THREADS + ...blocking system call here... + Py_END_ALLOW_THREADS + ...interpret result here... The Py_BEGIN_ALLOW_THREADS/Py_END_ALLOW_THREADS pair expands to a {}-surrounded block. To leave the block in the middle (e.g., with return), you must insert a line containing Py_BLOCK_THREADS before the return, e.g. - if (...premature_exit...) { - Py_BLOCK_THREADS - PyErr_SetFromErrno(PyExc_IOError); - return NULL; - } + if (...premature_exit...) { + Py_BLOCK_THREADS + PyErr_SetFromErrno(PyExc_IOError); + return NULL; + } An alternative is: - Py_BLOCK_THREADS - if (...premature_exit...) { - PyErr_SetFromErrno(PyExc_IOError); - return NULL; - } - Py_UNBLOCK_THREADS + Py_BLOCK_THREADS + if (...premature_exit...) { + PyErr_SetFromErrno(PyExc_IOError); + return NULL; + } + Py_UNBLOCK_THREADS For convenience, that the value of 'errno' is restored across Py_END_ALLOW_THREADS and Py_BLOCK_THREADS. @@ -170,12 +170,12 @@ PyAPI_FUNC(unsigned long) _PyEval_GetSwitchInterval(void); #define Py_BEGIN_ALLOW_THREADS { \ - PyThreadState *_save; \ - _save = PyEval_SaveThread(); -#define Py_BLOCK_THREADS PyEval_RestoreThread(_save); -#define Py_UNBLOCK_THREADS _save = PyEval_SaveThread(); -#define Py_END_ALLOW_THREADS PyEval_RestoreThread(_save); \ - } + PyThreadState *_save; \ + _save = PyEval_SaveThread(); +#define Py_BLOCK_THREADS PyEval_RestoreThread(_save); +#define Py_UNBLOCK_THREADS _save = PyEval_SaveThread(); +#define Py_END_ALLOW_THREADS PyEval_RestoreThread(_save); \ + } #else /* !WITH_THREAD */ Modified: python/branches/py3k-jit/Include/datetime.h ============================================================================== --- python/branches/py3k-jit/Include/datetime.h (original) +++ python/branches/py3k-jit/Include/datetime.h Mon May 10 23:55:43 2010 @@ -11,13 +11,13 @@ * big-endian, unless otherwise noted: * * byte offset - * 0 year 2 bytes, 1-9999 - * 2 month 1 byte, 1-12 - * 3 day 1 byte, 1-31 - * 4 hour 1 byte, 0-23 - * 5 minute 1 byte, 0-59 - * 6 second 1 byte, 0-59 - * 7 usecond 3 bytes, 0-999999 + * 0 year 2 bytes, 1-9999 + * 2 month 1 byte, 1-12 + * 3 day 1 byte, 1-31 + * 4 hour 1 byte, 0-23 + * 5 minute 1 byte, 0-59 + * 6 second 1 byte, 0-59 + * 7 usecond 3 bytes, 0-999999 * 10 */ @@ -33,26 +33,26 @@ typedef struct { - PyObject_HEAD - long hashcode; /* -1 when unknown */ - int days; /* -MAX_DELTA_DAYS <= days <= MAX_DELTA_DAYS */ - int seconds; /* 0 <= seconds < 24*3600 is invariant */ - int microseconds; /* 0 <= microseconds < 1000000 is invariant */ + PyObject_HEAD + long hashcode; /* -1 when unknown */ + int days; /* -MAX_DELTA_DAYS <= days <= MAX_DELTA_DAYS */ + int seconds; /* 0 <= seconds < 24*3600 is invariant */ + int microseconds; /* 0 <= microseconds < 1000000 is invariant */ } PyDateTime_Delta; typedef struct { - PyObject_HEAD /* a pure abstract base clase */ + PyObject_HEAD /* a pure abstract base clase */ } PyDateTime_TZInfo; /* The datetime and time types have hashcodes, and an optional tzinfo member, * present if and only if hastzinfo is true. */ -#define _PyTZINFO_HEAD \ - PyObject_HEAD \ - long hashcode; \ - char hastzinfo; /* boolean flag */ +#define _PyTZINFO_HEAD \ + PyObject_HEAD \ + long hashcode; \ + char hastzinfo; /* boolean flag */ /* No _PyDateTime_BaseTZInfo is allocated; it's just to have something * convenient to cast to, when getting at the hastzinfo member of objects @@ -60,7 +60,7 @@ */ typedef struct { - _PyTZINFO_HEAD + _PyTZINFO_HEAD } _PyDateTime_BaseTZInfo; /* All time objects are of PyDateTime_TimeType, but that can be allocated @@ -69,20 +69,20 @@ * internal struct used to allocate the right amount of space for the * "without" case. */ -#define _PyDateTime_TIMEHEAD \ - _PyTZINFO_HEAD \ - unsigned char data[_PyDateTime_TIME_DATASIZE]; +#define _PyDateTime_TIMEHEAD \ + _PyTZINFO_HEAD \ + unsigned char data[_PyDateTime_TIME_DATASIZE]; typedef struct { - _PyDateTime_TIMEHEAD -} _PyDateTime_BaseTime; /* hastzinfo false */ + _PyDateTime_TIMEHEAD +} _PyDateTime_BaseTime; /* hastzinfo false */ typedef struct { - _PyDateTime_TIMEHEAD - PyObject *tzinfo; -} PyDateTime_Time; /* hastzinfo true */ + _PyDateTime_TIMEHEAD + PyObject *tzinfo; +} PyDateTime_Time; /* hastzinfo true */ /* All datetime objects are of PyDateTime_DateTimeType, but that can be @@ -92,48 +92,48 @@ */ typedef struct { - _PyTZINFO_HEAD - unsigned char data[_PyDateTime_DATE_DATASIZE]; + _PyTZINFO_HEAD + unsigned char data[_PyDateTime_DATE_DATASIZE]; } PyDateTime_Date; -#define _PyDateTime_DATETIMEHEAD \ - _PyTZINFO_HEAD \ - unsigned char data[_PyDateTime_DATETIME_DATASIZE]; +#define _PyDateTime_DATETIMEHEAD \ + _PyTZINFO_HEAD \ + unsigned char data[_PyDateTime_DATETIME_DATASIZE]; typedef struct { - _PyDateTime_DATETIMEHEAD -} _PyDateTime_BaseDateTime; /* hastzinfo false */ + _PyDateTime_DATETIMEHEAD +} _PyDateTime_BaseDateTime; /* hastzinfo false */ typedef struct { - _PyDateTime_DATETIMEHEAD - PyObject *tzinfo; -} PyDateTime_DateTime; /* hastzinfo true */ + _PyDateTime_DATETIMEHEAD + PyObject *tzinfo; +} PyDateTime_DateTime; /* hastzinfo true */ /* Apply for date and datetime instances. */ #define PyDateTime_GET_YEAR(o) ((((PyDateTime_Date*)o)->data[0] << 8) | \ - ((PyDateTime_Date*)o)->data[1]) + ((PyDateTime_Date*)o)->data[1]) #define PyDateTime_GET_MONTH(o) (((PyDateTime_Date*)o)->data[2]) #define PyDateTime_GET_DAY(o) (((PyDateTime_Date*)o)->data[3]) #define PyDateTime_DATE_GET_HOUR(o) (((PyDateTime_DateTime*)o)->data[4]) #define PyDateTime_DATE_GET_MINUTE(o) (((PyDateTime_DateTime*)o)->data[5]) #define PyDateTime_DATE_GET_SECOND(o) (((PyDateTime_DateTime*)o)->data[6]) -#define PyDateTime_DATE_GET_MICROSECOND(o) \ - ((((PyDateTime_DateTime*)o)->data[7] << 16) | \ - (((PyDateTime_DateTime*)o)->data[8] << 8) | \ - ((PyDateTime_DateTime*)o)->data[9]) +#define PyDateTime_DATE_GET_MICROSECOND(o) \ + ((((PyDateTime_DateTime*)o)->data[7] << 16) | \ + (((PyDateTime_DateTime*)o)->data[8] << 8) | \ + ((PyDateTime_DateTime*)o)->data[9]) /* Apply for time instances. */ #define PyDateTime_TIME_GET_HOUR(o) (((PyDateTime_Time*)o)->data[0]) #define PyDateTime_TIME_GET_MINUTE(o) (((PyDateTime_Time*)o)->data[1]) #define PyDateTime_TIME_GET_SECOND(o) (((PyDateTime_Time*)o)->data[2]) -#define PyDateTime_TIME_GET_MICROSECOND(o) \ - ((((PyDateTime_Time*)o)->data[3] << 16) | \ - (((PyDateTime_Time*)o)->data[4] << 8) | \ - ((PyDateTime_Time*)o)->data[5]) +#define PyDateTime_TIME_GET_MICROSECOND(o) \ + ((((PyDateTime_Time*)o)->data[3] << 16) | \ + (((PyDateTime_Time*)o)->data[4] << 8) | \ + ((PyDateTime_Time*)o)->data[5]) /* Define structure for C API. */ @@ -148,7 +148,7 @@ /* constructors */ PyObject *(*Date_FromDate)(int, int, int, PyTypeObject*); PyObject *(*DateTime_FromDateAndTime)(int, int, int, int, int, int, int, - PyObject*, PyTypeObject*); + PyObject*, PyTypeObject*); PyObject *(*Time_FromTime)(int, int, int, int, PyObject*, PyTypeObject*); PyObject *(*Delta_FromDelta)(int, int, int, int, PyTypeObject*); @@ -185,7 +185,7 @@ static PyDateTime_CAPI *PyDateTimeAPI = NULL; #define PyDateTime_IMPORT \ - PyDateTimeAPI = (PyDateTime_CAPI *)PyCapsule_Import(PyDateTime_CAPSULE_NAME, 0) + PyDateTimeAPI = (PyDateTime_CAPI *)PyCapsule_Import(PyDateTime_CAPSULE_NAME, 0) /* Macros for type checking when not building the Python core. */ #define PyDate_Check(op) PyObject_TypeCheck(op, PyDateTimeAPI->DateType) @@ -205,30 +205,30 @@ /* Macros for accessing constructors in a simplified fashion. */ #define PyDate_FromDate(year, month, day) \ - PyDateTimeAPI->Date_FromDate(year, month, day, PyDateTimeAPI->DateType) + PyDateTimeAPI->Date_FromDate(year, month, day, PyDateTimeAPI->DateType) #define PyDateTime_FromDateAndTime(year, month, day, hour, min, sec, usec) \ - PyDateTimeAPI->DateTime_FromDateAndTime(year, month, day, hour, \ - min, sec, usec, Py_None, PyDateTimeAPI->DateTimeType) + PyDateTimeAPI->DateTime_FromDateAndTime(year, month, day, hour, \ + min, sec, usec, Py_None, PyDateTimeAPI->DateTimeType) #define PyTime_FromTime(hour, minute, second, usecond) \ - PyDateTimeAPI->Time_FromTime(hour, minute, second, usecond, \ - Py_None, PyDateTimeAPI->TimeType) + PyDateTimeAPI->Time_FromTime(hour, minute, second, usecond, \ + Py_None, PyDateTimeAPI->TimeType) #define PyDelta_FromDSU(days, seconds, useconds) \ - PyDateTimeAPI->Delta_FromDelta(days, seconds, useconds, 1, \ - PyDateTimeAPI->DeltaType) + PyDateTimeAPI->Delta_FromDelta(days, seconds, useconds, 1, \ + PyDateTimeAPI->DeltaType) /* Macros supporting the DB API. */ #define PyDateTime_FromTimestamp(args) \ - PyDateTimeAPI->DateTime_FromTimestamp( \ - (PyObject*) (PyDateTimeAPI->DateTimeType), args, NULL) + PyDateTimeAPI->DateTime_FromTimestamp( \ + (PyObject*) (PyDateTimeAPI->DateTimeType), args, NULL) #define PyDate_FromTimestamp(args) \ - PyDateTimeAPI->Date_FromTimestamp( \ - (PyObject*) (PyDateTimeAPI->DateType), args) + PyDateTimeAPI->Date_FromTimestamp( \ + (PyObject*) (PyDateTimeAPI->DateType), args) -#endif /* Py_BUILD_CORE */ +#endif /* Py_BUILD_CORE */ #ifdef __cplusplus } Modified: python/branches/py3k-jit/Include/descrobject.h ============================================================================== --- python/branches/py3k-jit/Include/descrobject.h (original) +++ python/branches/py3k-jit/Include/descrobject.h Mon May 10 23:55:43 2010 @@ -9,27 +9,27 @@ typedef int (*setter)(PyObject *, PyObject *, void *); typedef struct PyGetSetDef { - char *name; - getter get; - setter set; - char *doc; - void *closure; + char *name; + getter get; + setter set; + char *doc; + void *closure; } PyGetSetDef; typedef PyObject *(*wrapperfunc)(PyObject *self, PyObject *args, - void *wrapped); + void *wrapped); typedef PyObject *(*wrapperfunc_kwds)(PyObject *self, PyObject *args, - void *wrapped, PyObject *kwds); + void *wrapped, PyObject *kwds); struct wrapperbase { - char *name; - int offset; - void *function; - wrapperfunc wrapper; - char *doc; - int flags; - PyObject *name_strobj; + char *name; + int offset; + void *function; + wrapperfunc wrapper; + char *doc; + int flags; + PyObject *name_strobj; }; /* Flags for above struct */ @@ -38,9 +38,9 @@ /* Various kinds of descriptor objects */ typedef struct { - PyObject_HEAD - PyTypeObject *d_type; - PyObject *d_name; + PyObject_HEAD + PyTypeObject *d_type; + PyObject *d_name; } PyDescrObject; #define PyDescr_COMMON PyDescrObject d_common @@ -49,24 +49,24 @@ #define PyDescr_NAME(x) (((PyDescrObject *)(x))->d_name) typedef struct { - PyDescr_COMMON; - PyMethodDef *d_method; + PyDescr_COMMON; + PyMethodDef *d_method; } PyMethodDescrObject; typedef struct { - PyDescr_COMMON; - struct PyMemberDef *d_member; + PyDescr_COMMON; + struct PyMemberDef *d_member; } PyMemberDescrObject; typedef struct { - PyDescr_COMMON; - PyGetSetDef *d_getset; + PyDescr_COMMON; + PyGetSetDef *d_getset; } PyGetSetDescrObject; typedef struct { - PyDescr_COMMON; - struct wrapperbase *d_base; - void *d_wrapped; /* This can be any function pointer */ + PyDescr_COMMON; + struct wrapperbase *d_base; + void *d_wrapped; /* This can be any function pointer */ } PyWrapperDescrObject; PyAPI_DATA(PyTypeObject) PyClassMethodDescr_Type; @@ -79,11 +79,11 @@ PyAPI_FUNC(PyObject *) PyDescr_NewMethod(PyTypeObject *, PyMethodDef *); PyAPI_FUNC(PyObject *) PyDescr_NewClassMethod(PyTypeObject *, PyMethodDef *); PyAPI_FUNC(PyObject *) PyDescr_NewMember(PyTypeObject *, - struct PyMemberDef *); + struct PyMemberDef *); PyAPI_FUNC(PyObject *) PyDescr_NewGetSet(PyTypeObject *, - struct PyGetSetDef *); + struct PyGetSetDef *); PyAPI_FUNC(PyObject *) PyDescr_NewWrapper(PyTypeObject *, - struct wrapperbase *, void *); + struct wrapperbase *, void *); #define PyDescr_IsData(d) (Py_TYPE(d)->tp_descr_set != NULL) PyAPI_FUNC(PyObject *) PyDictProxy_New(PyObject *); Modified: python/branches/py3k-jit/Include/dictobject.h ============================================================================== --- python/branches/py3k-jit/Include/dictobject.h (original) +++ python/branches/py3k-jit/Include/dictobject.h Mon May 10 23:55:43 2010 @@ -48,13 +48,13 @@ #define PyDict_MINSIZE 8 typedef struct { - /* Cached hash code of me_key. Note that hash codes are C longs. - * We have to use Py_ssize_t instead because dict_popitem() abuses - * me_hash to hold a search finger. - */ - Py_ssize_t me_hash; - PyObject *me_key; - PyObject *me_value; + /* Cached hash code of me_key. Note that hash codes are C longs. + * We have to use Py_ssize_t instead because dict_popitem() abuses + * me_hash to hold a search finger. + */ + Py_ssize_t me_hash; + PyObject *me_key; + PyObject *me_value; } PyDictEntry; /* @@ -68,24 +68,24 @@ */ typedef struct _dictobject PyDictObject; struct _dictobject { - PyObject_HEAD - Py_ssize_t ma_fill; /* # Active + # Dummy */ - Py_ssize_t ma_used; /* # Active */ - - /* The table contains ma_mask + 1 slots, and that's a power of 2. - * We store the mask instead of the size because the mask is more - * frequently needed. - */ - Py_ssize_t ma_mask; - - /* ma_table points to ma_smalltable for small tables, else to - * additional malloc'ed memory. ma_table is never NULL! This rule - * saves repeated runtime null-tests in the workhorse getitem and - * setitem calls. - */ - PyDictEntry *ma_table; - PyDictEntry *(*ma_lookup)(PyDictObject *mp, PyObject *key, long hash); - PyDictEntry ma_smalltable[PyDict_MINSIZE]; + PyObject_HEAD + Py_ssize_t ma_fill; /* # Active + # Dummy */ + Py_ssize_t ma_used; /* # Active */ + + /* The table contains ma_mask + 1 slots, and that's a power of 2. + * We store the mask instead of the size because the mask is more + * frequently needed. + */ + Py_ssize_t ma_mask; + + /* ma_table points to ma_smalltable for small tables, else to + * additional malloc'ed memory. ma_table is never NULL! This rule + * saves repeated runtime null-tests in the workhorse getitem and + * setitem calls. + */ + PyDictEntry *ma_table; + PyDictEntry *(*ma_lookup)(PyDictObject *mp, PyObject *key, long hash); + PyDictEntry ma_smalltable[PyDict_MINSIZE]; }; PyAPI_DATA(PyTypeObject) PyDict_Type; @@ -104,7 +104,7 @@ #define PyDictValues_Check(op) (Py_TYPE(op) == &PyDictValues_Type) /* This excludes Values, since they are not sets. */ # define PyDictViewSet_Check(op) \ - (PyDictKeys_Check(op) || PyDictItems_Check(op)) + (PyDictKeys_Check(op) || PyDictItems_Check(op)) PyAPI_FUNC(PyObject *) PyDict_New(void); @@ -114,9 +114,9 @@ PyAPI_FUNC(int) PyDict_DelItem(PyObject *mp, PyObject *key); PyAPI_FUNC(void) PyDict_Clear(PyObject *mp); PyAPI_FUNC(int) PyDict_Next( - PyObject *mp, Py_ssize_t *pos, PyObject **key, PyObject **value); + PyObject *mp, Py_ssize_t *pos, PyObject **key, PyObject **value); PyAPI_FUNC(int) _PyDict_Next( - PyObject *mp, Py_ssize_t *pos, PyObject **key, PyObject **value, long *hash); + PyObject *mp, Py_ssize_t *pos, PyObject **key, PyObject **value, long *hash); PyAPI_FUNC(PyObject *) PyDict_Keys(PyObject *mp); PyAPI_FUNC(PyObject *) PyDict_Values(PyObject *mp); PyAPI_FUNC(PyObject *) PyDict_Items(PyObject *mp); @@ -137,8 +137,8 @@ dict.update(other) is equivalent to PyDict_Merge(dict, other, 1). */ PyAPI_FUNC(int) PyDict_Merge(PyObject *mp, - PyObject *other, - int override); + PyObject *other, + int override); /* PyDict_MergeFromSeq2 updates/merges from an iterable object producing iterable objects of length 2. If override is true, the last occurrence @@ -146,8 +146,8 @@ is equivalent to dict={}; PyDict_MergeFromSeq(dict, seq2, 1). */ PyAPI_FUNC(int) PyDict_MergeFromSeq2(PyObject *d, - PyObject *seq2, - int override); + PyObject *seq2, + int override); PyAPI_FUNC(PyObject *) PyDict_GetItemString(PyObject *dp, const char *key); PyAPI_FUNC(int) PyDict_SetItemString(PyObject *dp, const char *key, PyObject *item); Modified: python/branches/py3k-jit/Include/object.h ============================================================================== --- python/branches/py3k-jit/Include/object.h (original) +++ python/branches/py3k-jit/Include/object.h Mon May 10 23:55:43 2010 @@ -63,9 +63,9 @@ #ifdef Py_TRACE_REFS /* Define pointers to support a doubly-linked list of all live heap objects. */ -#define _PyObject_HEAD_EXTRA \ - struct _object *_ob_next; \ - struct _object *_ob_prev; +#define _PyObject_HEAD_EXTRA \ + struct _object *_ob_next; \ + struct _object *_ob_prev; #define _PyObject_EXTRA_INIT 0, 0, @@ -75,14 +75,14 @@ #endif /* PyObject_HEAD defines the initial segment of every PyObject. */ -#define PyObject_HEAD PyObject ob_base; +#define PyObject_HEAD PyObject ob_base; -#define PyObject_HEAD_INIT(type) \ - { _PyObject_EXTRA_INIT \ - 1, type }, +#define PyObject_HEAD_INIT(type) \ + { _PyObject_EXTRA_INIT \ + 1, type }, -#define PyVarObject_HEAD_INIT(type, size) \ - { PyObject_HEAD_INIT(type) size }, +#define PyVarObject_HEAD_INIT(type, size) \ + { PyObject_HEAD_INIT(type) size }, /* PyObject_VAR_HEAD defines the initial segment of all variable-size * container objects. These end with a declaration of an array with 1 @@ -99,19 +99,19 @@ * in addition, be cast to PyVarObject*. */ typedef struct _object { - _PyObject_HEAD_EXTRA - Py_ssize_t ob_refcnt; - struct _typeobject *ob_type; + _PyObject_HEAD_EXTRA + Py_ssize_t ob_refcnt; + struct _typeobject *ob_type; } PyObject; typedef struct { - PyObject ob_base; - Py_ssize_t ob_size; /* Number of items in variable part */ + PyObject ob_base; + Py_ssize_t ob_size; /* Number of items in variable part */ } PyVarObject; -#define Py_REFCNT(ob) (((PyObject*)(ob))->ob_refcnt) -#define Py_TYPE(ob) (((PyObject*)(ob))->ob_type) -#define Py_SIZE(ob) (((PyVarObject*)(ob))->ob_size) +#define Py_REFCNT(ob) (((PyObject*)(ob))->ob_refcnt) +#define Py_TYPE(ob) (((PyObject*)(ob))->ob_type) +#define Py_SIZE(ob) (((PyVarObject*)(ob))->ob_size) /* Type objects contain a string containing the type name (to help somewhat @@ -142,26 +142,26 @@ /* buffer interface */ typedef struct bufferinfo { - void *buf; - PyObject *obj; /* owned reference */ - Py_ssize_t len; - Py_ssize_t itemsize; /* This is Py_ssize_t so it can be - pointed to by strides in simple case.*/ - int readonly; - int ndim; - char *format; - Py_ssize_t *shape; - Py_ssize_t *strides; - Py_ssize_t *suboffsets; - Py_ssize_t smalltable[2]; /* static store for shape and strides of - mono-dimensional buffers. */ - void *internal; + void *buf; + PyObject *obj; /* owned reference */ + Py_ssize_t len; + Py_ssize_t itemsize; /* This is Py_ssize_t so it can be + pointed to by strides in simple case.*/ + int readonly; + int ndim; + char *format; + Py_ssize_t *shape; + Py_ssize_t *strides; + Py_ssize_t *suboffsets; + Py_ssize_t smalltable[2]; /* static store for shape and strides of + mono-dimensional buffers. */ + void *internal; } Py_buffer; typedef int (*getbufferproc)(PyObject *, Py_buffer *, int); typedef void (*releasebufferproc)(PyObject *, Py_buffer *); - /* Flags for getting buffers */ + /* Flags for getting buffers */ #define PyBUF_SIMPLE 0 #define PyBUF_WRITABLE 0x0001 /* we used to include an E, backwards compatible alias */ @@ -198,67 +198,67 @@ typedef int (*traverseproc)(PyObject *, visitproc, void *); typedef struct { - /* Number implementations must check *both* - arguments for proper type and implement the necessary conversions - in the slot functions themselves. */ - - binaryfunc nb_add; - binaryfunc nb_subtract; - binaryfunc nb_multiply; - binaryfunc nb_remainder; - binaryfunc nb_divmod; - ternaryfunc nb_power; - unaryfunc nb_negative; - unaryfunc nb_positive; - unaryfunc nb_absolute; - inquiry nb_bool; - unaryfunc nb_invert; - binaryfunc nb_lshift; - binaryfunc nb_rshift; - binaryfunc nb_and; - binaryfunc nb_xor; - binaryfunc nb_or; - unaryfunc nb_int; - void *nb_reserved; /* the slot formerly known as nb_long */ - unaryfunc nb_float; - - binaryfunc nb_inplace_add; - binaryfunc nb_inplace_subtract; - binaryfunc nb_inplace_multiply; - binaryfunc nb_inplace_remainder; - ternaryfunc nb_inplace_power; - binaryfunc nb_inplace_lshift; - binaryfunc nb_inplace_rshift; - binaryfunc nb_inplace_and; - binaryfunc nb_inplace_xor; - binaryfunc nb_inplace_or; - - binaryfunc nb_floor_divide; - binaryfunc nb_true_divide; - binaryfunc nb_inplace_floor_divide; - binaryfunc nb_inplace_true_divide; + /* Number implementations must check *both* + arguments for proper type and implement the necessary conversions + in the slot functions themselves. */ + + binaryfunc nb_add; + binaryfunc nb_subtract; + binaryfunc nb_multiply; + binaryfunc nb_remainder; + binaryfunc nb_divmod; + ternaryfunc nb_power; + unaryfunc nb_negative; + unaryfunc nb_positive; + unaryfunc nb_absolute; + inquiry nb_bool; + unaryfunc nb_invert; + binaryfunc nb_lshift; + binaryfunc nb_rshift; + binaryfunc nb_and; + binaryfunc nb_xor; + binaryfunc nb_or; + unaryfunc nb_int; + void *nb_reserved; /* the slot formerly known as nb_long */ + unaryfunc nb_float; + + binaryfunc nb_inplace_add; + binaryfunc nb_inplace_subtract; + binaryfunc nb_inplace_multiply; + binaryfunc nb_inplace_remainder; + ternaryfunc nb_inplace_power; + binaryfunc nb_inplace_lshift; + binaryfunc nb_inplace_rshift; + binaryfunc nb_inplace_and; + binaryfunc nb_inplace_xor; + binaryfunc nb_inplace_or; + + binaryfunc nb_floor_divide; + binaryfunc nb_true_divide; + binaryfunc nb_inplace_floor_divide; + binaryfunc nb_inplace_true_divide; - unaryfunc nb_index; + unaryfunc nb_index; } PyNumberMethods; typedef struct { - lenfunc sq_length; - binaryfunc sq_concat; - ssizeargfunc sq_repeat; - ssizeargfunc sq_item; - void *was_sq_slice; - ssizeobjargproc sq_ass_item; - void *was_sq_ass_slice; - objobjproc sq_contains; + lenfunc sq_length; + binaryfunc sq_concat; + ssizeargfunc sq_repeat; + ssizeargfunc sq_item; + void *was_sq_slice; + ssizeobjargproc sq_ass_item; + void *was_sq_ass_slice; + objobjproc sq_contains; - binaryfunc sq_inplace_concat; - ssizeargfunc sq_inplace_repeat; + binaryfunc sq_inplace_concat; + ssizeargfunc sq_inplace_repeat; } PySequenceMethods; typedef struct { - lenfunc mp_length; - binaryfunc mp_subscript; - objobjargproc mp_ass_subscript; + lenfunc mp_length; + binaryfunc mp_subscript; + objobjargproc mp_ass_subscript; } PyMappingMethods; @@ -286,109 +286,109 @@ typedef PyObject *(*allocfunc)(struct _typeobject *, Py_ssize_t); typedef struct _typeobject { - PyObject_VAR_HEAD - const char *tp_name; /* For printing, in format "." */ - Py_ssize_t tp_basicsize, tp_itemsize; /* For allocation */ - - /* Methods to implement standard operations */ - - destructor tp_dealloc; - printfunc tp_print; - getattrfunc tp_getattr; - setattrfunc tp_setattr; - void *tp_reserved; /* formerly known as tp_compare */ - reprfunc tp_repr; - - /* Method suites for standard classes */ - - PyNumberMethods *tp_as_number; - PySequenceMethods *tp_as_sequence; - PyMappingMethods *tp_as_mapping; - - /* More standard operations (here for binary compatibility) */ - - hashfunc tp_hash; - ternaryfunc tp_call; - reprfunc tp_str; - getattrofunc tp_getattro; - setattrofunc tp_setattro; - - /* Functions to access object as input/output buffer */ - PyBufferProcs *tp_as_buffer; - - /* Flags to define presence of optional/expanded features */ - long tp_flags; - - const char *tp_doc; /* Documentation string */ - - /* Assigned meaning in release 2.0 */ - /* call function for all accessible objects */ - traverseproc tp_traverse; - - /* delete references to contained objects */ - inquiry tp_clear; - - /* Assigned meaning in release 2.1 */ - /* rich comparisons */ - richcmpfunc tp_richcompare; - - /* weak reference enabler */ - Py_ssize_t tp_weaklistoffset; - - /* Iterators */ - getiterfunc tp_iter; - iternextfunc tp_iternext; - - /* Attribute descriptor and subclassing stuff */ - struct PyMethodDef *tp_methods; - struct PyMemberDef *tp_members; - struct PyGetSetDef *tp_getset; - struct _typeobject *tp_base; - PyObject *tp_dict; - descrgetfunc tp_descr_get; - descrsetfunc tp_descr_set; - Py_ssize_t tp_dictoffset; - initproc tp_init; - allocfunc tp_alloc; - newfunc tp_new; - freefunc tp_free; /* Low-level free-memory routine */ - inquiry tp_is_gc; /* For PyObject_IS_GC */ - PyObject *tp_bases; - PyObject *tp_mro; /* method resolution order */ - PyObject *tp_cache; - PyObject *tp_subclasses; - PyObject *tp_weaklist; - destructor tp_del; + PyObject_VAR_HEAD + const char *tp_name; /* For printing, in format "." */ + Py_ssize_t tp_basicsize, tp_itemsize; /* For allocation */ + + /* Methods to implement standard operations */ + + destructor tp_dealloc; + printfunc tp_print; + getattrfunc tp_getattr; + setattrfunc tp_setattr; + void *tp_reserved; /* formerly known as tp_compare */ + reprfunc tp_repr; + + /* Method suites for standard classes */ + + PyNumberMethods *tp_as_number; + PySequenceMethods *tp_as_sequence; + PyMappingMethods *tp_as_mapping; + + /* More standard operations (here for binary compatibility) */ + + hashfunc tp_hash; + ternaryfunc tp_call; + reprfunc tp_str; + getattrofunc tp_getattro; + setattrofunc tp_setattro; + + /* Functions to access object as input/output buffer */ + PyBufferProcs *tp_as_buffer; + + /* Flags to define presence of optional/expanded features */ + long tp_flags; + + const char *tp_doc; /* Documentation string */ + + /* Assigned meaning in release 2.0 */ + /* call function for all accessible objects */ + traverseproc tp_traverse; + + /* delete references to contained objects */ + inquiry tp_clear; + + /* Assigned meaning in release 2.1 */ + /* rich comparisons */ + richcmpfunc tp_richcompare; + + /* weak reference enabler */ + Py_ssize_t tp_weaklistoffset; + + /* Iterators */ + getiterfunc tp_iter; + iternextfunc tp_iternext; + + /* Attribute descriptor and subclassing stuff */ + struct PyMethodDef *tp_methods; + struct PyMemberDef *tp_members; + struct PyGetSetDef *tp_getset; + struct _typeobject *tp_base; + PyObject *tp_dict; + descrgetfunc tp_descr_get; + descrsetfunc tp_descr_set; + Py_ssize_t tp_dictoffset; + initproc tp_init; + allocfunc tp_alloc; + newfunc tp_new; + freefunc tp_free; /* Low-level free-memory routine */ + inquiry tp_is_gc; /* For PyObject_IS_GC */ + PyObject *tp_bases; + PyObject *tp_mro; /* method resolution order */ + PyObject *tp_cache; + PyObject *tp_subclasses; + PyObject *tp_weaklist; + destructor tp_del; - /* Type attribute cache version tag. Added in version 2.6 */ - unsigned int tp_version_tag; + /* Type attribute cache version tag. Added in version 2.6 */ + unsigned int tp_version_tag; #ifdef COUNT_ALLOCS - /* these must be last and never explicitly initialized */ - Py_ssize_t tp_allocs; - Py_ssize_t tp_frees; - Py_ssize_t tp_maxalloc; - struct _typeobject *tp_prev; - struct _typeobject *tp_next; + /* these must be last and never explicitly initialized */ + Py_ssize_t tp_allocs; + Py_ssize_t tp_frees; + Py_ssize_t tp_maxalloc; + struct _typeobject *tp_prev; + struct _typeobject *tp_next; #endif } PyTypeObject; /* The *real* layout of a type object when allocated on the heap */ typedef struct _heaptypeobject { - /* Note: there's a dependency on the order of these members - in slotptr() in typeobject.c . */ - PyTypeObject ht_type; - PyNumberMethods as_number; - PyMappingMethods as_mapping; - PySequenceMethods as_sequence; /* as_sequence comes after as_mapping, - so that the mapping wins when both - the mapping and the sequence define - a given operator (e.g. __getitem__). - see add_operators() in typeobject.c . */ - PyBufferProcs as_buffer; - PyObject *ht_name, *ht_slots; - /* here are optional user slots, followed by the members. */ + /* Note: there's a dependency on the order of these members + in slotptr() in typeobject.c . */ + PyTypeObject ht_type; + PyNumberMethods as_number; + PyMappingMethods as_mapping; + PySequenceMethods as_sequence; /* as_sequence comes after as_mapping, + so that the mapping wins when both + the mapping and the sequence define + a given operator (e.g. __getitem__). + see add_operators() in typeobject.c . */ + PyBufferProcs as_buffer; + PyObject *ht_name, *ht_slots; + /* here are optional user slots, followed by the members. */ } PyHeapTypeObject; /* access macro to the members which are floating "behind" the object */ @@ -399,20 +399,20 @@ /* Generic type check */ PyAPI_FUNC(int) PyType_IsSubtype(PyTypeObject *, PyTypeObject *); #define PyObject_TypeCheck(ob, tp) \ - (Py_TYPE(ob) == (tp) || PyType_IsSubtype(Py_TYPE(ob), (tp))) + (Py_TYPE(ob) == (tp) || PyType_IsSubtype(Py_TYPE(ob), (tp))) PyAPI_DATA(PyTypeObject) PyType_Type; /* built-in 'type' */ PyAPI_DATA(PyTypeObject) PyBaseObject_Type; /* built-in 'object' */ PyAPI_DATA(PyTypeObject) PySuper_Type; /* built-in 'super' */ #define PyType_Check(op) \ - PyType_FastSubclass(Py_TYPE(op), Py_TPFLAGS_TYPE_SUBCLASS) + PyType_FastSubclass(Py_TYPE(op), Py_TPFLAGS_TYPE_SUBCLASS) #define PyType_CheckExact(op) (Py_TYPE(op) == &PyType_Type) PyAPI_FUNC(int) PyType_Ready(PyTypeObject *); PyAPI_FUNC(PyObject *) PyType_GenericAlloc(PyTypeObject *, Py_ssize_t); PyAPI_FUNC(PyObject *) PyType_GenericNew(PyTypeObject *, - PyObject *, PyObject *); + PyObject *, PyObject *); PyAPI_FUNC(PyObject *) _PyType_Lookup(PyTypeObject *, PyObject *); PyAPI_FUNC(PyObject *) _PyObject_LookupSpecial(PyObject *, char *, PyObject **); PyAPI_FUNC(unsigned int) PyType_ClearCache(void); @@ -439,7 +439,7 @@ PyAPI_FUNC(PyObject *) _PyObject_NextNotImplemented(PyObject *); PyAPI_FUNC(PyObject *) PyObject_GenericGetAttr(PyObject *, PyObject *); PyAPI_FUNC(int) PyObject_GenericSetAttr(PyObject *, - PyObject *, PyObject *); + PyObject *, PyObject *); PyAPI_FUNC(long) PyObject_Hash(PyObject *); PyAPI_FUNC(long) PyObject_HashNotImplemented(PyObject *); PyAPI_FUNC(int) PyObject_IsTrue(PyObject *); @@ -469,7 +469,7 @@ #define PyObject_REPR(obj) _PyUnicode_AsString(PyObject_Repr(obj)) /* Flag bits for printing: */ -#define Py_PRINT_RAW 1 /* No string quotes etc. */ +#define Py_PRINT_RAW 1 /* No string quotes etc. */ /* `Type flags (tp_flags) @@ -524,20 +524,20 @@ #define Py_TPFLAGS_IS_ABSTRACT (1L<<20) /* These flags are used to determine if a type is a subclass. */ -#define Py_TPFLAGS_INT_SUBCLASS (1L<<23) -#define Py_TPFLAGS_LONG_SUBCLASS (1L<<24) -#define Py_TPFLAGS_LIST_SUBCLASS (1L<<25) -#define Py_TPFLAGS_TUPLE_SUBCLASS (1L<<26) -#define Py_TPFLAGS_BYTES_SUBCLASS (1L<<27) -#define Py_TPFLAGS_UNICODE_SUBCLASS (1L<<28) -#define Py_TPFLAGS_DICT_SUBCLASS (1L<<29) -#define Py_TPFLAGS_BASE_EXC_SUBCLASS (1L<<30) -#define Py_TPFLAGS_TYPE_SUBCLASS (1L<<31) +#define Py_TPFLAGS_INT_SUBCLASS (1L<<23) +#define Py_TPFLAGS_LONG_SUBCLASS (1L<<24) +#define Py_TPFLAGS_LIST_SUBCLASS (1L<<25) +#define Py_TPFLAGS_TUPLE_SUBCLASS (1L<<26) +#define Py_TPFLAGS_BYTES_SUBCLASS (1L<<27) +#define Py_TPFLAGS_UNICODE_SUBCLASS (1L<<28) +#define Py_TPFLAGS_DICT_SUBCLASS (1L<<29) +#define Py_TPFLAGS_BASE_EXC_SUBCLASS (1L<<30) +#define Py_TPFLAGS_TYPE_SUBCLASS (1L<<31) #define Py_TPFLAGS_DEFAULT ( \ - Py_TPFLAGS_HAVE_STACKLESS_EXTENSION | \ - Py_TPFLAGS_HAVE_VERSION_TAG | \ - 0) + Py_TPFLAGS_HAVE_STACKLESS_EXTENSION | \ + Py_TPFLAGS_HAVE_VERSION_TAG | \ + 0) #define PyType_HasFeature(t,f) (((t)->tp_flags & (f)) != 0) #define PyType_FastSubclass(t,f) PyType_HasFeature(t,f) @@ -589,32 +589,32 @@ #ifdef Py_REF_DEBUG PyAPI_DATA(Py_ssize_t) _Py_RefTotal; PyAPI_FUNC(void) _Py_NegativeRefcount(const char *fname, - int lineno, PyObject *op); + int lineno, PyObject *op); PyAPI_FUNC(PyObject *) _PyDict_Dummy(void); PyAPI_FUNC(PyObject *) _PySet_Dummy(void); PyAPI_FUNC(Py_ssize_t) _Py_GetRefTotal(void); -#define _Py_INC_REFTOTAL _Py_RefTotal++ -#define _Py_DEC_REFTOTAL _Py_RefTotal-- -#define _Py_REF_DEBUG_COMMA , -#define _Py_CHECK_REFCNT(OP) \ -{ if (((PyObject*)OP)->ob_refcnt < 0) \ - _Py_NegativeRefcount(__FILE__, __LINE__, \ - (PyObject *)(OP)); \ +#define _Py_INC_REFTOTAL _Py_RefTotal++ +#define _Py_DEC_REFTOTAL _Py_RefTotal-- +#define _Py_REF_DEBUG_COMMA , +#define _Py_CHECK_REFCNT(OP) \ +{ if (((PyObject*)OP)->ob_refcnt < 0) \ + _Py_NegativeRefcount(__FILE__, __LINE__, \ + (PyObject *)(OP)); \ } #else #define _Py_INC_REFTOTAL #define _Py_DEC_REFTOTAL #define _Py_REF_DEBUG_COMMA -#define _Py_CHECK_REFCNT(OP) /* a semicolon */; +#define _Py_CHECK_REFCNT(OP) /* a semicolon */; #endif /* Py_REF_DEBUG */ #ifdef COUNT_ALLOCS PyAPI_FUNC(void) inc_count(PyTypeObject *); PyAPI_FUNC(void) dec_count(PyTypeObject *); -#define _Py_INC_TPALLOCS(OP) inc_count(Py_TYPE(OP)) -#define _Py_INC_TPFREES(OP) dec_count(Py_TYPE(OP)) -#define _Py_DEC_TPFREES(OP) Py_TYPE(OP)->tp_frees-- -#define _Py_COUNT_ALLOCS_COMMA , +#define _Py_INC_TPALLOCS(OP) inc_count(Py_TYPE(OP)) +#define _Py_INC_TPFREES(OP) dec_count(Py_TYPE(OP)) +#define _Py_DEC_TPFREES(OP) Py_TYPE(OP)->tp_frees-- +#define _Py_COUNT_ALLOCS_COMMA , #else #define _Py_INC_TPALLOCS(OP) #define _Py_INC_TPFREES(OP) @@ -635,30 +635,30 @@ /* Without Py_TRACE_REFS, there's little enough to do that we expand code * inline. */ -#define _Py_NewReference(op) ( \ - _Py_INC_TPALLOCS(op) _Py_COUNT_ALLOCS_COMMA \ - _Py_INC_REFTOTAL _Py_REF_DEBUG_COMMA \ - Py_REFCNT(op) = 1) +#define _Py_NewReference(op) ( \ + _Py_INC_TPALLOCS(op) _Py_COUNT_ALLOCS_COMMA \ + _Py_INC_REFTOTAL _Py_REF_DEBUG_COMMA \ + Py_REFCNT(op) = 1) #define _Py_ForgetReference(op) _Py_INC_TPFREES(op) -#define _Py_Dealloc(op) ( \ - _Py_INC_TPFREES(op) _Py_COUNT_ALLOCS_COMMA \ - (*Py_TYPE(op)->tp_dealloc)((PyObject *)(op))) +#define _Py_Dealloc(op) ( \ + _Py_INC_TPFREES(op) _Py_COUNT_ALLOCS_COMMA \ + (*Py_TYPE(op)->tp_dealloc)((PyObject *)(op))) #endif /* !Py_TRACE_REFS */ -#define Py_INCREF(op) ( \ - _Py_INC_REFTOTAL _Py_REF_DEBUG_COMMA \ - ((PyObject*)(op))->ob_refcnt++) - -#define Py_DECREF(op) \ - do { \ - if (_Py_DEC_REFTOTAL _Py_REF_DEBUG_COMMA \ - --((PyObject*)(op))->ob_refcnt != 0) \ - _Py_CHECK_REFCNT(op) \ - else \ - _Py_Dealloc((PyObject *)(op)); \ - } while (0) +#define Py_INCREF(op) ( \ + _Py_INC_REFTOTAL _Py_REF_DEBUG_COMMA \ + ((PyObject*)(op))->ob_refcnt++) + +#define Py_DECREF(op) \ + do { \ + if (_Py_DEC_REFTOTAL _Py_REF_DEBUG_COMMA \ + --((PyObject*)(op))->ob_refcnt != 0) \ + _Py_CHECK_REFCNT(op) \ + else \ + _Py_Dealloc((PyObject *)(op)); \ + } while (0) /* Safely decref `op` and set `op` to NULL, especially useful in tp_clear * and tp_dealloc implementatons. @@ -694,14 +694,14 @@ * Python integers aren't currently weakly referencable. Best practice is * to use Py_CLEAR() even if you can't think of a reason for why you need to. */ -#define Py_CLEAR(op) \ - do { \ - if (op) { \ - PyObject *_py_tmp = (PyObject *)(op); \ - (op) = NULL; \ - Py_DECREF(_py_tmp); \ - } \ - } while (0) +#define Py_CLEAR(op) \ + do { \ + if (op) { \ + PyObject *_py_tmp = (PyObject *)(op); \ + (op) = NULL; \ + Py_DECREF(_py_tmp); \ + } \ + } while (0) /* Macros to use in case the object pointer may be NULL: */ #define Py_XINCREF(op) do { if ((op) == NULL) ; else Py_INCREF(op); } while (0) @@ -813,13 +813,13 @@ static void mytype_dealloc(mytype *p) { - ... declarations go here ... + ... declarations go here ... - PyObject_GC_UnTrack(p); // must untrack first - Py_TRASHCAN_SAFE_BEGIN(p) - ... The body of the deallocator goes here, including all calls ... - ... to Py_DECREF on contained objects. ... - Py_TRASHCAN_SAFE_END(p) + PyObject_GC_UnTrack(p); // must untrack first + Py_TRASHCAN_SAFE_BEGIN(p) + ... The body of the deallocator goes here, including all calls ... + ... to Py_DECREF on contained objects. ... + Py_TRASHCAN_SAFE_END(p) } CAUTION: Never return from the middle of the body! If the body needs to @@ -849,16 +849,16 @@ #define PyTrash_UNWIND_LEVEL 50 #define Py_TRASHCAN_SAFE_BEGIN(op) \ - if (_PyTrash_delete_nesting < PyTrash_UNWIND_LEVEL) { \ - ++_PyTrash_delete_nesting; - /* The body of the deallocator is here. */ + if (_PyTrash_delete_nesting < PyTrash_UNWIND_LEVEL) { \ + ++_PyTrash_delete_nesting; + /* The body of the deallocator is here. */ #define Py_TRASHCAN_SAFE_END(op) \ - --_PyTrash_delete_nesting; \ - if (_PyTrash_delete_later && _PyTrash_delete_nesting <= 0) \ - _PyTrash_destroy_chain(); \ - } \ - else \ - _PyTrash_deposit_object((PyObject*)op); + --_PyTrash_delete_nesting; \ + if (_PyTrash_delete_later && _PyTrash_delete_nesting <= 0) \ + _PyTrash_destroy_chain(); \ + } \ + else \ + _PyTrash_deposit_object((PyObject*)op); #ifdef __cplusplus } Modified: python/branches/py3k-jit/Include/objimpl.h ============================================================================== --- python/branches/py3k-jit/Include/objimpl.h (original) +++ python/branches/py3k-jit/Include/objimpl.h Mon May 10 23:55:43 2010 @@ -101,7 +101,7 @@ /* Macros */ #ifdef WITH_PYMALLOC -#ifdef PYMALLOC_DEBUG /* WITH_PYMALLOC && PYMALLOC_DEBUG */ +#ifdef PYMALLOC_DEBUG /* WITH_PYMALLOC && PYMALLOC_DEBUG */ PyAPI_FUNC(void *) _PyObject_DebugMalloc(size_t nbytes); PyAPI_FUNC(void *) _PyObject_DebugRealloc(void *p, size_t nbytes); PyAPI_FUNC(void) _PyObject_DebugFree(void *p); @@ -115,28 +115,28 @@ PyAPI_FUNC(void *) _PyMem_DebugMalloc(size_t nbytes); PyAPI_FUNC(void *) _PyMem_DebugRealloc(void *p, size_t nbytes); PyAPI_FUNC(void) _PyMem_DebugFree(void *p); -#define PyObject_MALLOC _PyObject_DebugMalloc -#define PyObject_Malloc _PyObject_DebugMalloc -#define PyObject_REALLOC _PyObject_DebugRealloc -#define PyObject_Realloc _PyObject_DebugRealloc -#define PyObject_FREE _PyObject_DebugFree -#define PyObject_Free _PyObject_DebugFree - -#else /* WITH_PYMALLOC && ! PYMALLOC_DEBUG */ -#define PyObject_MALLOC PyObject_Malloc -#define PyObject_REALLOC PyObject_Realloc -#define PyObject_FREE PyObject_Free +#define PyObject_MALLOC _PyObject_DebugMalloc +#define PyObject_Malloc _PyObject_DebugMalloc +#define PyObject_REALLOC _PyObject_DebugRealloc +#define PyObject_Realloc _PyObject_DebugRealloc +#define PyObject_FREE _PyObject_DebugFree +#define PyObject_Free _PyObject_DebugFree + +#else /* WITH_PYMALLOC && ! PYMALLOC_DEBUG */ +#define PyObject_MALLOC PyObject_Malloc +#define PyObject_REALLOC PyObject_Realloc +#define PyObject_FREE PyObject_Free #endif -#else /* ! WITH_PYMALLOC */ -#define PyObject_MALLOC PyMem_MALLOC -#define PyObject_REALLOC PyMem_REALLOC -#define PyObject_FREE PyMem_FREE +#else /* ! WITH_PYMALLOC */ +#define PyObject_MALLOC PyMem_MALLOC +#define PyObject_REALLOC PyMem_REALLOC +#define PyObject_FREE PyMem_FREE -#endif /* WITH_PYMALLOC */ +#endif /* WITH_PYMALLOC */ -#define PyObject_Del PyObject_Free -#define PyObject_DEL PyObject_FREE +#define PyObject_Del PyObject_Free +#define PyObject_DEL PyObject_FREE /* * Generic object allocator interface @@ -151,16 +151,16 @@ PyAPI_FUNC(PyVarObject *) _PyObject_NewVar(PyTypeObject *, Py_ssize_t); #define PyObject_New(type, typeobj) \ - ( (type *) _PyObject_New(typeobj) ) + ( (type *) _PyObject_New(typeobj) ) #define PyObject_NewVar(type, typeobj, n) \ - ( (type *) _PyObject_NewVar((typeobj), (n)) ) + ( (type *) _PyObject_NewVar((typeobj), (n)) ) /* Macros trading binary compatibility for speed. See also pymem.h. Note that these macros expect non-NULL object pointers.*/ #define PyObject_INIT(op, typeobj) \ - ( Py_TYPE(op) = (typeobj), _Py_NewReference((PyObject *)(op)), (op) ) + ( Py_TYPE(op) = (typeobj), _Py_NewReference((PyObject *)(op)), (op) ) #define PyObject_INIT_VAR(op, typeobj, size) \ - ( Py_SIZE(op) = (size), PyObject_INIT((op), (typeobj)) ) + ( Py_SIZE(op) = (size), PyObject_INIT((op), (typeobj)) ) #define _PyObject_SIZE(typeobj) ( (typeobj)->tp_basicsize ) @@ -178,17 +178,17 @@ # error "_PyObject_VAR_SIZE requires SIZEOF_VOID_P be a power of 2" #endif -#define _PyObject_VAR_SIZE(typeobj, nitems) \ - (size_t) \ - ( ( (typeobj)->tp_basicsize + \ - (nitems)*(typeobj)->tp_itemsize + \ - (SIZEOF_VOID_P - 1) \ - ) & ~(SIZEOF_VOID_P - 1) \ - ) +#define _PyObject_VAR_SIZE(typeobj, nitems) \ + (size_t) \ + ( ( (typeobj)->tp_basicsize + \ + (nitems)*(typeobj)->tp_itemsize + \ + (SIZEOF_VOID_P - 1) \ + ) & ~(SIZEOF_VOID_P - 1) \ + ) #define PyObject_NEW(type, typeobj) \ ( (type *) PyObject_Init( \ - (PyObject *) PyObject_MALLOC( _PyObject_SIZE(typeobj) ), (typeobj)) ) + (PyObject *) PyObject_MALLOC( _PyObject_SIZE(typeobj) ), (typeobj)) ) #define PyObject_NEW_VAR(type, typeobj, n) \ ( (type *) PyObject_InitVar( \ @@ -200,7 +200,7 @@ distinction between two steps (at least): 1) the actual allocation of the object storage; 2) the initialization of the Python specific fields - in this storage with PyObject_{Init, InitVar}. + in this storage with PyObject_{Init, InitVar}. PyObject * YourObject_New(...) @@ -209,7 +209,7 @@ op = (PyObject *) Your_Allocator(_PyObject_SIZE(YourTypeStruct)); if (op == NULL) - return PyErr_NoMemory(); + return PyErr_NoMemory(); PyObject_Init(op, &YourTypeStruct); @@ -236,44 +236,44 @@ /* Test if an object has a GC head */ #define PyObject_IS_GC(o) (PyType_IS_GC(Py_TYPE(o)) && \ - (Py_TYPE(o)->tp_is_gc == NULL || Py_TYPE(o)->tp_is_gc(o))) + (Py_TYPE(o)->tp_is_gc == NULL || Py_TYPE(o)->tp_is_gc(o))) PyAPI_FUNC(PyVarObject *) _PyObject_GC_Resize(PyVarObject *, Py_ssize_t); #define PyObject_GC_Resize(type, op, n) \ - ( (type *) _PyObject_GC_Resize((PyVarObject *)(op), (n)) ) + ( (type *) _PyObject_GC_Resize((PyVarObject *)(op), (n)) ) /* for source compatibility with 2.2 */ #define _PyObject_GC_Del PyObject_GC_Del /* GC information is stored BEFORE the object structure. */ typedef union _gc_head { - struct { - union _gc_head *gc_next; - union _gc_head *gc_prev; - Py_ssize_t gc_refs; - } gc; - long double dummy; /* force worst-case alignment */ + struct { + union _gc_head *gc_next; + union _gc_head *gc_prev; + Py_ssize_t gc_refs; + } gc; + long double dummy; /* force worst-case alignment */ } PyGC_Head; extern PyGC_Head *_PyGC_generation0; #define _Py_AS_GC(o) ((PyGC_Head *)(o)-1) -#define _PyGC_REFS_UNTRACKED (-2) -#define _PyGC_REFS_REACHABLE (-3) -#define _PyGC_REFS_TENTATIVELY_UNREACHABLE (-4) +#define _PyGC_REFS_UNTRACKED (-2) +#define _PyGC_REFS_REACHABLE (-3) +#define _PyGC_REFS_TENTATIVELY_UNREACHABLE (-4) /* Tell the GC to track this object. NB: While the object is tracked the * collector it must be safe to call the ob_traverse method. */ #define _PyObject_GC_TRACK(o) do { \ - PyGC_Head *g = _Py_AS_GC(o); \ - if (g->gc.gc_refs != _PyGC_REFS_UNTRACKED) \ - Py_FatalError("GC object already tracked"); \ - g->gc.gc_refs = _PyGC_REFS_REACHABLE; \ - g->gc.gc_next = _PyGC_generation0; \ - g->gc.gc_prev = _PyGC_generation0->gc.gc_prev; \ - g->gc.gc_prev->gc.gc_next = g; \ - _PyGC_generation0->gc.gc_prev = g; \ + PyGC_Head *g = _Py_AS_GC(o); \ + if (g->gc.gc_refs != _PyGC_REFS_UNTRACKED) \ + Py_FatalError("GC object already tracked"); \ + g->gc.gc_refs = _PyGC_REFS_REACHABLE; \ + g->gc.gc_next = _PyGC_generation0; \ + g->gc.gc_prev = _PyGC_generation0->gc.gc_prev; \ + g->gc.gc_prev->gc.gc_next = g; \ + _PyGC_generation0->gc.gc_prev = g; \ } while (0); /* Tell the GC to stop tracking this object. @@ -281,23 +281,23 @@ * way to provoke memory errors if calling code is confused. */ #define _PyObject_GC_UNTRACK(o) do { \ - PyGC_Head *g = _Py_AS_GC(o); \ - assert(g->gc.gc_refs != _PyGC_REFS_UNTRACKED); \ - g->gc.gc_refs = _PyGC_REFS_UNTRACKED; \ - g->gc.gc_prev->gc.gc_next = g->gc.gc_next; \ - g->gc.gc_next->gc.gc_prev = g->gc.gc_prev; \ - g->gc.gc_next = NULL; \ + PyGC_Head *g = _Py_AS_GC(o); \ + assert(g->gc.gc_refs != _PyGC_REFS_UNTRACKED); \ + g->gc.gc_refs = _PyGC_REFS_UNTRACKED; \ + g->gc.gc_prev->gc.gc_next = g->gc.gc_next; \ + g->gc.gc_next->gc.gc_prev = g->gc.gc_prev; \ + g->gc.gc_next = NULL; \ } while (0); /* True if the object is currently tracked by the GC. */ #define _PyObject_GC_IS_TRACKED(o) \ - ((_Py_AS_GC(o))->gc.gc_refs != _PyGC_REFS_UNTRACKED) - + ((_Py_AS_GC(o))->gc.gc_refs != _PyGC_REFS_UNTRACKED) + /* True if the object may be tracked by the GC in the future, or already is. This can be useful to implement some optimizations. */ #define _PyObject_GC_MAY_BE_TRACKED(obj) \ - (PyObject_IS_GC(obj) && \ - (!PyTuple_CheckExact(obj) || _PyObject_GC_IS_TRACKED(obj))) + (PyObject_IS_GC(obj) && \ + (!PyTuple_CheckExact(obj) || _PyObject_GC_IS_TRACKED(obj))) PyAPI_FUNC(PyObject *) _PyObject_GC_Malloc(size_t); @@ -308,9 +308,9 @@ PyAPI_FUNC(void) PyObject_GC_Del(void *); #define PyObject_GC_New(type, typeobj) \ - ( (type *) _PyObject_GC_New(typeobj) ) + ( (type *) _PyObject_GC_New(typeobj) ) #define PyObject_GC_NewVar(type, typeobj, n) \ - ( (type *) _PyObject_GC_NewVar((typeobj), (n)) ) + ( (type *) _PyObject_GC_NewVar((typeobj), (n)) ) /* Utility macro to help write tp_traverse functions. @@ -318,14 +318,14 @@ * "visit" and "arg". This is intended to keep tp_traverse functions * looking as much alike as possible. */ -#define Py_VISIT(op) \ - do { \ - if (op) { \ - int vret = visit((PyObject *)(op), arg); \ - if (vret) \ - return vret; \ - } \ - } while (0) +#define Py_VISIT(op) \ + do { \ + if (op) { \ + int vret = visit((PyObject *)(op), arg); \ + if (vret) \ + return vret; \ + } \ + } while (0) /* This is here for the sake of backwards compatibility. Extensions that * use the old GC API will still compile but the objects will not be @@ -341,7 +341,7 @@ #define PyType_SUPPORTS_WEAKREFS(t) ((t)->tp_weaklistoffset > 0) #define PyObject_GET_WEAKREFS_LISTPTR(o) \ - ((PyObject **) (((char *) (o)) + Py_TYPE(o)->tp_weaklistoffset)) + ((PyObject **) (((char *) (o)) + Py_TYPE(o)->tp_weaklistoffset)) #ifdef __cplusplus } Modified: python/branches/py3k-jit/Include/pyerrors.h ============================================================================== --- python/branches/py3k-jit/Include/pyerrors.h (original) +++ python/branches/py3k-jit/Include/pyerrors.h Mon May 10 23:55:43 2010 @@ -8,8 +8,8 @@ /* PyException_HEAD defines the initial segment of every exception class. */ #define PyException_HEAD PyObject_HEAD PyObject *dict;\ - PyObject *args; PyObject *traceback;\ - PyObject *context; PyObject *cause; + PyObject *args; PyObject *traceback;\ + PyObject *context; PyObject *cause; typedef struct { PyException_HEAD @@ -92,15 +92,15 @@ /* */ -#define PyExceptionClass_Check(x) \ - (PyType_Check((x)) && \ - PyType_FastSubclass((PyTypeObject*)(x), Py_TPFLAGS_BASE_EXC_SUBCLASS)) +#define PyExceptionClass_Check(x) \ + (PyType_Check((x)) && \ + PyType_FastSubclass((PyTypeObject*)(x), Py_TPFLAGS_BASE_EXC_SUBCLASS)) -#define PyExceptionInstance_Check(x) \ - PyType_FastSubclass((x)->ob_type, Py_TPFLAGS_BASE_EXC_SUBCLASS) +#define PyExceptionInstance_Check(x) \ + PyType_FastSubclass((x)->ob_type, Py_TPFLAGS_BASE_EXC_SUBCLASS) #define PyExceptionClass_Name(x) \ - ((char *)(((PyTypeObject*)(x))->tp_name)) + ((char *)(((PyTypeObject*)(x))->tp_name)) #define PyExceptionInstance_Class(x) ((PyObject*)((x)->ob_type)) @@ -175,30 +175,30 @@ PyAPI_FUNC(PyObject *) PyErr_NoMemory(void); PyAPI_FUNC(PyObject *) PyErr_SetFromErrno(PyObject *); PyAPI_FUNC(PyObject *) PyErr_SetFromErrnoWithFilenameObject( - PyObject *, PyObject *); + PyObject *, PyObject *); PyAPI_FUNC(PyObject *) PyErr_SetFromErrnoWithFilename( - PyObject *, const char *); + PyObject *, const char *); #ifdef MS_WINDOWS PyAPI_FUNC(PyObject *) PyErr_SetFromErrnoWithUnicodeFilename( - PyObject *, const Py_UNICODE *); + PyObject *, const Py_UNICODE *); #endif /* MS_WINDOWS */ PyAPI_FUNC(PyObject *) PyErr_Format(PyObject *, const char *, ...); #ifdef MS_WINDOWS PyAPI_FUNC(PyObject *) PyErr_SetFromWindowsErrWithFilenameObject( - int, const char *); + int, const char *); PyAPI_FUNC(PyObject *) PyErr_SetFromWindowsErrWithFilename( - int, const char *); + int, const char *); PyAPI_FUNC(PyObject *) PyErr_SetFromWindowsErrWithUnicodeFilename( - int, const Py_UNICODE *); + int, const Py_UNICODE *); PyAPI_FUNC(PyObject *) PyErr_SetFromWindowsErr(int); PyAPI_FUNC(PyObject *) PyErr_SetExcFromWindowsErrWithFilenameObject( - PyObject *,int, PyObject *); + PyObject *,int, PyObject *); PyAPI_FUNC(PyObject *) PyErr_SetExcFromWindowsErrWithFilename( - PyObject *,int, const char *); + PyObject *,int, const char *); PyAPI_FUNC(PyObject *) PyErr_SetExcFromWindowsErrWithUnicodeFilename( - PyObject *,int, const Py_UNICODE *); + PyObject *,int, const Py_UNICODE *); PyAPI_FUNC(PyObject *) PyErr_SetExcFromWindowsErr(PyObject *, int); #endif /* MS_WINDOWS */ @@ -211,9 +211,9 @@ /* Function to create a new exception */ PyAPI_FUNC(PyObject *) PyErr_NewException( - const char *name, PyObject *base, PyObject *dict); + const char *name, PyObject *base, PyObject *dict); PyAPI_FUNC(PyObject *) PyErr_NewExceptionWithDoc( - const char *name, const char *doc, PyObject *base, PyObject *dict); + const char *name, const char *doc, PyObject *base, PyObject *dict); PyAPI_FUNC(void) PyErr_WriteUnraisable(PyObject *); /* In sigcheck.c or signalmodule.c */ @@ -232,15 +232,15 @@ /* create a UnicodeDecodeError object */ PyAPI_FUNC(PyObject *) PyUnicodeDecodeError_Create( - const char *, const char *, Py_ssize_t, Py_ssize_t, Py_ssize_t, const char *); + const char *, const char *, Py_ssize_t, Py_ssize_t, Py_ssize_t, const char *); /* create a UnicodeEncodeError object */ PyAPI_FUNC(PyObject *) PyUnicodeEncodeError_Create( - const char *, const Py_UNICODE *, Py_ssize_t, Py_ssize_t, Py_ssize_t, const char *); + const char *, const Py_UNICODE *, Py_ssize_t, Py_ssize_t, Py_ssize_t, const char *); /* create a UnicodeTranslateError object */ PyAPI_FUNC(PyObject *) PyUnicodeTranslateError_Create( - const Py_UNICODE *, Py_ssize_t, Py_ssize_t, Py_ssize_t, const char *); + const Py_UNICODE *, Py_ssize_t, Py_ssize_t, Py_ssize_t, const char *); /* get the encoding attribute */ PyAPI_FUNC(PyObject *) PyUnicodeEncodeError_GetEncoding(PyObject *); @@ -283,11 +283,11 @@ /* assign a new value to the reason attribute return 0 on success, -1 on failure */ PyAPI_FUNC(int) PyUnicodeEncodeError_SetReason( - PyObject *, const char *); + PyObject *, const char *); PyAPI_FUNC(int) PyUnicodeDecodeError_SetReason( - PyObject *, const char *); + PyObject *, const char *); PyAPI_FUNC(int) PyUnicodeTranslateError_SetReason( - PyObject *, const char *); + PyObject *, const char *); /* These APIs aren't really part of the error implementation, but @@ -306,9 +306,9 @@ #include PyAPI_FUNC(int) PyOS_snprintf(char *str, size_t size, const char *format, ...) - Py_GCC_ATTRIBUTE((format(printf, 3, 4))); + Py_GCC_ATTRIBUTE((format(printf, 3, 4))); PyAPI_FUNC(int) PyOS_vsnprintf(char *str, size_t size, const char *format, va_list va) - Py_GCC_ATTRIBUTE((format(printf, 3, 0))); + Py_GCC_ATTRIBUTE((format(printf, 3, 0))); #ifdef __cplusplus } Modified: python/branches/py3k-jit/Include/pymacconfig.h ============================================================================== --- python/branches/py3k-jit/Include/pymacconfig.h (original) +++ python/branches/py3k-jit/Include/pymacconfig.h Mon May 10 23:55:43 2010 @@ -4,7 +4,7 @@ * This file moves some of the autoconf magic to compile-time * when building on MacOSX. This is needed for building 4-way * universal binaries and for 64-bit universal binaries because - * the values redefined below aren't configure-time constant but + * the values redefined below aren't configure-time constant but * only compile-time constant in these scenarios. */ @@ -36,40 +36,40 @@ # undef SIZEOF_LONG # ifdef __LP64__ -# define SIZEOF__BOOL 1 -# define SIZEOF__BOOL 1 -# define SIZEOF_LONG 8 -# define SIZEOF_PTHREAD_T 8 -# define SIZEOF_SIZE_T 8 -# define SIZEOF_TIME_T 8 -# define SIZEOF_VOID_P 8 -# define SIZEOF_UINTPTR_T 8 -# define SIZEOF_PTHREAD_T 8 +# define SIZEOF__BOOL 1 +# define SIZEOF__BOOL 1 +# define SIZEOF_LONG 8 +# define SIZEOF_PTHREAD_T 8 +# define SIZEOF_SIZE_T 8 +# define SIZEOF_TIME_T 8 +# define SIZEOF_VOID_P 8 +# define SIZEOF_UINTPTR_T 8 +# define SIZEOF_PTHREAD_T 8 # else # ifdef __ppc__ -# define SIZEOF__BOOL 4 +# define SIZEOF__BOOL 4 # else -# define SIZEOF__BOOL 1 +# define SIZEOF__BOOL 1 # endif -# define SIZEOF_LONG 4 -# define SIZEOF_PTHREAD_T 4 -# define SIZEOF_SIZE_T 4 -# define SIZEOF_TIME_T 4 -# define SIZEOF_VOID_P 4 -# define SIZEOF_UINTPTR_T 4 -# define SIZEOF_PTHREAD_T 4 +# define SIZEOF_LONG 4 +# define SIZEOF_PTHREAD_T 4 +# define SIZEOF_SIZE_T 4 +# define SIZEOF_TIME_T 4 +# define SIZEOF_VOID_P 4 +# define SIZEOF_UINTPTR_T 4 +# define SIZEOF_PTHREAD_T 4 # endif # if defined(__LP64__) - /* MacOSX 10.4 (the first release to suppport 64-bit code - * at all) only supports 64-bit in the UNIX layer. - * Therefore surpress the toolbox-glue in 64-bit mode. - */ - - /* In 64-bit mode setpgrp always has no argments, in 32-bit - * mode that depends on the compilation environment - */ -# undef SETPGRP_HAVE_ARG + /* MacOSX 10.4 (the first release to suppport 64-bit code + * at all) only supports 64-bit in the UNIX layer. + * Therefore surpress the toolbox-glue in 64-bit mode. + */ + + /* In 64-bit mode setpgrp always has no argments, in 32-bit + * mode that depends on the compilation environment + */ +# undef SETPGRP_HAVE_ARG # endif @@ -84,17 +84,17 @@ # define HAVE_GCC_ASM_FOR_X87 #endif - /* - * The definition in pyconfig.h is only valid on the OS release - * where configure ran on and not necessarily for all systems where - * the executable can be used on. - * - * Specifically: OSX 10.4 has limited supported for '%zd', while - * 10.5 has full support for '%zd'. A binary built on 10.5 won't - * work properly on 10.4 unless we surpress the definition - * of PY_FORMAT_SIZE_T - */ -#undef PY_FORMAT_SIZE_T + /* + * The definition in pyconfig.h is only valid on the OS release + * where configure ran on and not necessarily for all systems where + * the executable can be used on. + * + * Specifically: OSX 10.4 has limited supported for '%zd', while + * 10.5 has full support for '%zd'. A binary built on 10.5 won't + * work properly on 10.4 unless we surpress the definition + * of PY_FORMAT_SIZE_T + */ +#undef PY_FORMAT_SIZE_T #endif /* defined(_APPLE__) */ Modified: python/branches/py3k-jit/Include/pyport.h ============================================================================== --- python/branches/py3k-jit/Include/pyport.h (original) +++ python/branches/py3k-jit/Include/pyport.h Mon May 10 23:55:43 2010 @@ -132,20 +132,20 @@ * integral type. */ #ifdef HAVE_UINTPTR_T -typedef uintptr_t Py_uintptr_t; -typedef intptr_t Py_intptr_t; +typedef uintptr_t Py_uintptr_t; +typedef intptr_t Py_intptr_t; #elif SIZEOF_VOID_P <= SIZEOF_INT -typedef unsigned int Py_uintptr_t; -typedef int Py_intptr_t; +typedef unsigned int Py_uintptr_t; +typedef int Py_intptr_t; #elif SIZEOF_VOID_P <= SIZEOF_LONG -typedef unsigned long Py_uintptr_t; -typedef long Py_intptr_t; +typedef unsigned long Py_uintptr_t; +typedef long Py_intptr_t; #elif defined(HAVE_LONG_LONG) && (SIZEOF_VOID_P <= SIZEOF_LONG_LONG) -typedef unsigned PY_LONG_LONG Py_uintptr_t; -typedef PY_LONG_LONG Py_intptr_t; +typedef unsigned PY_LONG_LONG Py_uintptr_t; +typedef PY_LONG_LONG Py_intptr_t; #else # error "Python needs a typedef for Py_uintptr_t in pyport.h." @@ -156,9 +156,9 @@ * unsigned integral type). See PEP 353 for details. */ #ifdef HAVE_SSIZE_T -typedef ssize_t Py_ssize_t; +typedef ssize_t Py_ssize_t; #elif SIZEOF_VOID_P == SIZEOF_SIZE_T -typedef Py_intptr_t Py_ssize_t; +typedef Py_intptr_t Py_ssize_t; #else # error "Python needs a typedef for Py_ssize_t in pyport.h." #endif @@ -166,7 +166,7 @@ /* Largest possible value of size_t. SIZE_MAX is part of C99, so it might be defined on some platforms. If it is not defined, (size_t)-1 is a portable - definition for C89, due to the way signed->unsigned + definition for C89, due to the way signed->unsigned conversion is defined. */ #ifdef SIZE_MAX #define PY_SIZE_MAX SIZE_MAX @@ -259,7 +259,7 @@ /* enable more aggressive optimization for visual studio */ #pragma optimize("agtw", on) #endif -/* ignore warnings if the compiler decides not to inline a function */ +/* ignore warnings if the compiler decides not to inline a function */ #pragma warning(disable: 4710) /* fastest possible local call under MSVC */ #define Py_LOCAL(type) static type __fastcall @@ -279,16 +279,16 @@ */ #if defined(_MSC_VER) -#define Py_MEMCPY(target, source, length) do { \ - size_t i_, n_ = (length); \ - char *t_ = (void*) (target); \ - const char *s_ = (void*) (source); \ - if (n_ >= 16) \ - memcpy(t_, s_, n_); \ - else \ - for (i_ = 0; i_ < n_; i_++) \ - t_[i_] = s_[i_]; \ - } while (0) +#define Py_MEMCPY(target, source, length) do { \ + size_t i_, n_ = (length); \ + char *t_ = (void*) (target); \ + const char *s_ = (void*) (source); \ + if (n_ >= 16) \ + memcpy(t_, s_, n_); \ + else \ + for (i_ = 0; i_ < n_; i_++) \ + t_[i_] = s_[i_]; \ + } while (0) #else #define Py_MEMCPY memcpy #endif @@ -403,7 +403,7 @@ */ #ifdef SIGNED_RIGHT_SHIFT_ZERO_FILLS #define Py_ARITHMETIC_RIGHT_SHIFT(TYPE, I, J) \ - ((I) < 0 ? -1-((-1-(I)) >> (J)) : (I) >> (J)) + ((I) < 0 ? -1-((-1-(I)) >> (J)) : (I) >> (J)) #else #define Py_ARITHMETIC_RIGHT_SHIFT(TYPE, I, J) ((I) >> (J)) #endif @@ -423,7 +423,7 @@ */ #ifdef Py_DEBUG #define Py_SAFE_DOWNCAST(VALUE, WIDE, NARROW) \ - (assert((WIDE)(NARROW)(VALUE) == (VALUE)), (NARROW)(VALUE)) + (assert((WIDE)(NARROW)(VALUE) == (VALUE)), (NARROW)(VALUE)) #else #define Py_SAFE_DOWNCAST(VALUE, WIDE, NARROW) (NARROW)(VALUE) #endif @@ -443,13 +443,13 @@ #define _Py_SET_EDOM_FOR_NAN(X) ; #endif #define Py_SET_ERRNO_ON_MATH_ERROR(X) \ - do { \ - if (errno == 0) { \ - if ((X) == Py_HUGE_VAL || (X) == -Py_HUGE_VAL) \ - errno = ERANGE; \ - else _Py_SET_EDOM_FOR_NAN(X) \ - } \ - } while(0) + do { \ + if (errno == 0) { \ + if ((X) == Py_HUGE_VAL || (X) == -Py_HUGE_VAL) \ + errno = ERANGE; \ + else _Py_SET_EDOM_FOR_NAN(X) \ + } \ + } while(0) /* Py_SET_ERANGE_ON_OVERFLOW(x) * An alias of Py_SET_ERRNO_ON_MATH_ERROR for backward-compatibility. @@ -470,26 +470,26 @@ * This isn't reliable. See Py_OVERFLOWED comments. * X and Y may be evaluated more than once. */ -#define Py_ADJUST_ERANGE1(X) \ - do { \ - if (errno == 0) { \ - if ((X) == Py_HUGE_VAL || (X) == -Py_HUGE_VAL) \ - errno = ERANGE; \ - } \ - else if (errno == ERANGE && (X) == 0.0) \ - errno = 0; \ - } while(0) - -#define Py_ADJUST_ERANGE2(X, Y) \ - do { \ - if ((X) == Py_HUGE_VAL || (X) == -Py_HUGE_VAL || \ - (Y) == Py_HUGE_VAL || (Y) == -Py_HUGE_VAL) { \ - if (errno == 0) \ - errno = ERANGE; \ - } \ - else if (errno == ERANGE) \ - errno = 0; \ - } while(0) +#define Py_ADJUST_ERANGE1(X) \ + do { \ + if (errno == 0) { \ + if ((X) == Py_HUGE_VAL || (X) == -Py_HUGE_VAL) \ + errno = ERANGE; \ + } \ + else if (errno == ERANGE && (X) == 0.0) \ + errno = 0; \ + } while(0) + +#define Py_ADJUST_ERANGE2(X, Y) \ + do { \ + if ((X) == Py_HUGE_VAL || (X) == -Py_HUGE_VAL || \ + (Y) == Py_HUGE_VAL || (Y) == -Py_HUGE_VAL) { \ + if (errno == 0) \ + errno = ERANGE; \ + } \ + else if (errno == ERANGE) \ + errno = 0; \ + } while(0) /* The functions _Py_dg_strtod and _Py_dg_dtoa in Python/dtoa.c (which are * required to support the short float repr introduced in Python 3.1) require @@ -518,18 +518,18 @@ #ifdef HAVE_GCC_ASM_FOR_X87 #define HAVE_PY_SET_53BIT_PRECISION 1 /* _Py_get/set_387controlword functions are defined in Python/pymath.c */ -#define _Py_SET_53BIT_PRECISION_HEADER \ - unsigned short old_387controlword, new_387controlword -#define _Py_SET_53BIT_PRECISION_START \ - do { \ - old_387controlword = _Py_get_387controlword(); \ - new_387controlword = (old_387controlword & ~0x0f00) | 0x0200; \ - if (new_387controlword != old_387controlword) \ - _Py_set_387controlword(new_387controlword); \ - } while (0) -#define _Py_SET_53BIT_PRECISION_END \ - if (new_387controlword != old_387controlword) \ - _Py_set_387controlword(old_387controlword) +#define _Py_SET_53BIT_PRECISION_HEADER \ + unsigned short old_387controlword, new_387controlword +#define _Py_SET_53BIT_PRECISION_START \ + do { \ + old_387controlword = _Py_get_387controlword(); \ + new_387controlword = (old_387controlword & ~0x0f00) | 0x0200; \ + if (new_387controlword != old_387controlword) \ + _Py_set_387controlword(new_387controlword); \ + } while (0) +#define _Py_SET_53BIT_PRECISION_END \ + if (new_387controlword != old_387controlword) \ + _Py_set_387controlword(old_387controlword) #endif /* default definitions are empty */ @@ -573,7 +573,7 @@ * extern int x() Py_DEPRECATED(2.5); */ #if defined(__GNUC__) && ((__GNUC__ >= 4) || \ - (__GNUC__ == 3) && (__GNUC_MINOR__ >= 1)) + (__GNUC__ == 3) && (__GNUC_MINOR__ >= 1)) #define Py_DEPRECATED(VERSION_UNUSED) __attribute__((__deprecated__)) #else #define Py_DEPRECATED(VERSION_UNUSED) @@ -593,7 +593,7 @@ #endif #ifdef HAVE__GETPTY -#include /* we need to import mode_t */ +#include /* we need to import mode_t */ extern char * _getpty(int *, int, mode_t, int); #endif @@ -674,54 +674,54 @@ linkage handling and it uses __declspec(). */ #if defined(__CYGWIN__) -# define HAVE_DECLSPEC_DLL +# define HAVE_DECLSPEC_DLL #endif /* only get special linkage if built as shared or platform is Cygwin */ #if defined(Py_ENABLE_SHARED) || defined(__CYGWIN__) -# if defined(HAVE_DECLSPEC_DLL) -# ifdef Py_BUILD_CORE -# define PyAPI_FUNC(RTYPE) __declspec(dllexport) RTYPE -# define PyAPI_DATA(RTYPE) extern __declspec(dllexport) RTYPE - /* module init functions inside the core need no external linkage */ - /* except for Cygwin to handle embedding */ -# if defined(__CYGWIN__) -# define PyMODINIT_FUNC __declspec(dllexport) PyObject* -# else /* __CYGWIN__ */ -# define PyMODINIT_FUNC PyObject* -# endif /* __CYGWIN__ */ -# else /* Py_BUILD_CORE */ - /* Building an extension module, or an embedded situation */ - /* public Python functions and data are imported */ - /* Under Cygwin, auto-import functions to prevent compilation */ - /* failures similar to http://python.org/doc/FAQ.html#3.24 */ -# if !defined(__CYGWIN__) -# define PyAPI_FUNC(RTYPE) __declspec(dllimport) RTYPE -# endif /* !__CYGWIN__ */ -# define PyAPI_DATA(RTYPE) extern __declspec(dllimport) RTYPE - /* module init functions outside the core must be exported */ -# if defined(__cplusplus) -# define PyMODINIT_FUNC extern "C" __declspec(dllexport) PyObject* -# else /* __cplusplus */ -# define PyMODINIT_FUNC __declspec(dllexport) PyObject* -# endif /* __cplusplus */ -# endif /* Py_BUILD_CORE */ -# endif /* HAVE_DECLSPEC */ +# if defined(HAVE_DECLSPEC_DLL) +# ifdef Py_BUILD_CORE +# define PyAPI_FUNC(RTYPE) __declspec(dllexport) RTYPE +# define PyAPI_DATA(RTYPE) extern __declspec(dllexport) RTYPE + /* module init functions inside the core need no external linkage */ + /* except for Cygwin to handle embedding */ +# if defined(__CYGWIN__) +# define PyMODINIT_FUNC __declspec(dllexport) PyObject* +# else /* __CYGWIN__ */ +# define PyMODINIT_FUNC PyObject* +# endif /* __CYGWIN__ */ +# else /* Py_BUILD_CORE */ + /* Building an extension module, or an embedded situation */ + /* public Python functions and data are imported */ + /* Under Cygwin, auto-import functions to prevent compilation */ + /* failures similar to http://python.org/doc/FAQ.html#3.24 */ +# if !defined(__CYGWIN__) +# define PyAPI_FUNC(RTYPE) __declspec(dllimport) RTYPE +# endif /* !__CYGWIN__ */ +# define PyAPI_DATA(RTYPE) extern __declspec(dllimport) RTYPE + /* module init functions outside the core must be exported */ +# if defined(__cplusplus) +# define PyMODINIT_FUNC extern "C" __declspec(dllexport) PyObject* +# else /* __cplusplus */ +# define PyMODINIT_FUNC __declspec(dllexport) PyObject* +# endif /* __cplusplus */ +# endif /* Py_BUILD_CORE */ +# endif /* HAVE_DECLSPEC */ #endif /* Py_ENABLE_SHARED */ /* If no external linkage macros defined by now, create defaults */ #ifndef PyAPI_FUNC -# define PyAPI_FUNC(RTYPE) RTYPE +# define PyAPI_FUNC(RTYPE) RTYPE #endif #ifndef PyAPI_DATA -# define PyAPI_DATA(RTYPE) extern RTYPE +# define PyAPI_DATA(RTYPE) extern RTYPE #endif #ifndef PyMODINIT_FUNC -# if defined(__cplusplus) -# define PyMODINIT_FUNC extern "C" PyObject* -# else /* __cplusplus */ -# define PyMODINIT_FUNC PyObject* -# endif /* __cplusplus */ +# if defined(__cplusplus) +# define PyMODINIT_FUNC extern "C" PyObject* +# else /* __cplusplus */ +# define PyMODINIT_FUNC PyObject* +# endif /* __cplusplus */ #endif /* limits.h constants that may be missing */ Modified: python/branches/py3k-jit/Include/pythonrun.h ============================================================================== --- python/branches/py3k-jit/Include/pythonrun.h (original) +++ python/branches/py3k-jit/Include/pythonrun.h Mon May 10 23:55:43 2010 @@ -17,7 +17,7 @@ #define PyCF_IGNORE_COOKIE 0x0800 typedef struct { - int cf_flags; /* bitmask of CO_xxx flags relevant to future */ + int cf_flags; /* bitmask of CO_xxx flags relevant to future */ } PyCompilerFlags; PyAPI_FUNC(void) Py_SetProgramName(wchar_t *); @@ -40,33 +40,33 @@ PyAPI_FUNC(int) PyRun_InteractiveOneFlags(FILE *, const char *, PyCompilerFlags *); PyAPI_FUNC(int) PyRun_InteractiveLoopFlags(FILE *, const char *, PyCompilerFlags *); -PyAPI_FUNC(struct _mod *) PyParser_ASTFromString(const char *, const char *, - int, PyCompilerFlags *flags, +PyAPI_FUNC(struct _mod *) PyParser_ASTFromString(const char *, const char *, + int, PyCompilerFlags *flags, PyArena *); -PyAPI_FUNC(struct _mod *) PyParser_ASTFromFile(FILE *, const char *, - const char*, int, - char *, char *, +PyAPI_FUNC(struct _mod *) PyParser_ASTFromFile(FILE *, const char *, + const char*, int, + char *, char *, PyCompilerFlags *, int *, PyArena *); #define PyParser_SimpleParseString(S, B) \ - PyParser_SimpleParseStringFlags(S, B, 0) + PyParser_SimpleParseStringFlags(S, B, 0) #define PyParser_SimpleParseFile(FP, S, B) \ - PyParser_SimpleParseFileFlags(FP, S, B, 0) -PyAPI_FUNC(struct _node *) PyParser_SimpleParseStringFlags(const char *, int, - int); + PyParser_SimpleParseFileFlags(FP, S, B, 0) +PyAPI_FUNC(struct _node *) PyParser_SimpleParseStringFlags(const char *, int, + int); PyAPI_FUNC(struct _node *) PyParser_SimpleParseFileFlags(FILE *, const char *, - int, int); + int, int); -PyAPI_FUNC(PyObject *) PyRun_StringFlags(const char *, int, PyObject *, - PyObject *, PyCompilerFlags *); +PyAPI_FUNC(PyObject *) PyRun_StringFlags(const char *, int, PyObject *, + PyObject *, PyCompilerFlags *); -PyAPI_FUNC(PyObject *) PyRun_FileExFlags(FILE *, const char *, int, - PyObject *, PyObject *, int, - PyCompilerFlags *); +PyAPI_FUNC(PyObject *) PyRun_FileExFlags(FILE *, const char *, int, + PyObject *, PyObject *, int, + PyCompilerFlags *); #define Py_CompileString(str, p, s) Py_CompileStringFlags(str, p, s, NULL) PyAPI_FUNC(PyObject *) Py_CompileStringFlags(const char *, const char *, int, - PyCompilerFlags *); + PyCompilerFlags *); PyAPI_FUNC(struct symtable *) Py_SymtableString(const char *, const char *, int); PyAPI_FUNC(void) PyErr_Print(void); @@ -93,20 +93,20 @@ #define PyRun_String(str, s, g, l) PyRun_StringFlags(str, s, g, l, NULL) #define PyRun_AnyFile(fp, name) PyRun_AnyFileExFlags(fp, name, 0, NULL) #define PyRun_AnyFileEx(fp, name, closeit) \ - PyRun_AnyFileExFlags(fp, name, closeit, NULL) + PyRun_AnyFileExFlags(fp, name, closeit, NULL) #define PyRun_AnyFileFlags(fp, name, flags) \ - PyRun_AnyFileExFlags(fp, name, 0, flags) + PyRun_AnyFileExFlags(fp, name, 0, flags) #define PyRun_SimpleString(s) PyRun_SimpleStringFlags(s, NULL) #define PyRun_SimpleFile(f, p) PyRun_SimpleFileExFlags(f, p, 0, NULL) #define PyRun_SimpleFileEx(f, p, c) PyRun_SimpleFileExFlags(f, p, c, NULL) #define PyRun_InteractiveOne(f, p) PyRun_InteractiveOneFlags(f, p, NULL) #define PyRun_InteractiveLoop(f, p) PyRun_InteractiveLoopFlags(f, p, NULL) #define PyRun_File(fp, p, s, g, l) \ - PyRun_FileExFlags(fp, p, s, g, l, 0, NULL) + PyRun_FileExFlags(fp, p, s, g, l, 0, NULL) #define PyRun_FileEx(fp, p, s, g, l, c) \ - PyRun_FileExFlags(fp, p, s, g, l, c, NULL) + PyRun_FileExFlags(fp, p, s, g, l, c, NULL) #define PyRun_FileFlags(fp, p, s, g, l, flags) \ - PyRun_FileExFlags(fp, p, s, g, l, 0, flags) + PyRun_FileExFlags(fp, p, s, g, l, 0, flags) /* In getpath.c */ PyAPI_FUNC(wchar_t *) Py_GetProgramFullPath(void); Modified: python/branches/py3k-jit/Include/setobject.h ============================================================================== --- python/branches/py3k-jit/Include/setobject.h (original) +++ python/branches/py3k-jit/Include/setobject.h Mon May 10 23:55:43 2010 @@ -22,8 +22,8 @@ #define PySet_MINSIZE 8 typedef struct { - long hash; /* cached hash code for the entry key */ - PyObject *key; + long hash; /* cached hash code for the entry key */ + PyObject *key; } setentry; @@ -33,27 +33,27 @@ typedef struct _setobject PySetObject; struct _setobject { - PyObject_HEAD + PyObject_HEAD - Py_ssize_t fill; /* # Active + # Dummy */ - Py_ssize_t used; /* # Active */ + Py_ssize_t fill; /* # Active + # Dummy */ + Py_ssize_t used; /* # Active */ - /* The table contains mask + 1 slots, and that's a power of 2. - * We store the mask instead of the size because the mask is more - * frequently needed. - */ - Py_ssize_t mask; - - /* table points to smalltable for small tables, else to - * additional malloc'ed memory. table is never NULL! This rule - * saves repeated runtime null-tests. - */ - setentry *table; - setentry *(*lookup)(PySetObject *so, PyObject *key, long hash); - setentry smalltable[PySet_MINSIZE]; + /* The table contains mask + 1 slots, and that's a power of 2. + * We store the mask instead of the size because the mask is more + * frequently needed. + */ + Py_ssize_t mask; + + /* table points to smalltable for small tables, else to + * additional malloc'ed memory. table is never NULL! This rule + * saves repeated runtime null-tests. + */ + setentry *table; + setentry *(*lookup)(PySetObject *so, PyObject *key, long hash); + setentry smalltable[PySet_MINSIZE]; - long hash; /* only used by frozenset objects */ - PyObject *weakreflist; /* List of weak references */ + long hash; /* only used by frozenset objects */ + PyObject *weakreflist; /* List of weak references */ }; PyAPI_DATA(PyTypeObject) PySet_Type; @@ -69,17 +69,17 @@ #define PyFrozenSet_CheckExact(ob) (Py_TYPE(ob) == &PyFrozenSet_Type) #define PyAnySet_CheckExact(ob) \ - (Py_TYPE(ob) == &PySet_Type || Py_TYPE(ob) == &PyFrozenSet_Type) + (Py_TYPE(ob) == &PySet_Type || Py_TYPE(ob) == &PyFrozenSet_Type) #define PyAnySet_Check(ob) \ - (Py_TYPE(ob) == &PySet_Type || Py_TYPE(ob) == &PyFrozenSet_Type || \ - PyType_IsSubtype(Py_TYPE(ob), &PySet_Type) || \ - PyType_IsSubtype(Py_TYPE(ob), &PyFrozenSet_Type)) + (Py_TYPE(ob) == &PySet_Type || Py_TYPE(ob) == &PyFrozenSet_Type || \ + PyType_IsSubtype(Py_TYPE(ob), &PySet_Type) || \ + PyType_IsSubtype(Py_TYPE(ob), &PyFrozenSet_Type)) #define PySet_Check(ob) \ - (Py_TYPE(ob) == &PySet_Type || \ - PyType_IsSubtype(Py_TYPE(ob), &PySet_Type)) + (Py_TYPE(ob) == &PySet_Type || \ + PyType_IsSubtype(Py_TYPE(ob), &PySet_Type)) #define PyFrozenSet_Check(ob) \ - (Py_TYPE(ob) == &PyFrozenSet_Type || \ - PyType_IsSubtype(Py_TYPE(ob), &PyFrozenSet_Type)) + (Py_TYPE(ob) == &PyFrozenSet_Type || \ + PyType_IsSubtype(Py_TYPE(ob), &PyFrozenSet_Type)) PyAPI_FUNC(PyObject *) PySet_New(PyObject *); PyAPI_FUNC(PyObject *) PyFrozenSet_New(PyObject *); Modified: python/branches/py3k-jit/Include/structseq.h ============================================================================== --- python/branches/py3k-jit/Include/structseq.h (original) +++ python/branches/py3k-jit/Include/structseq.h Mon May 10 23:55:43 2010 @@ -8,35 +8,35 @@ #endif typedef struct PyStructSequence_Field { - char *name; - char *doc; + char *name; + char *doc; } PyStructSequence_Field; typedef struct PyStructSequence_Desc { - char *name; - char *doc; - struct PyStructSequence_Field *fields; - int n_in_sequence; + char *name; + char *doc; + struct PyStructSequence_Field *fields; + int n_in_sequence; } PyStructSequence_Desc; extern char* PyStructSequence_UnnamedField; PyAPI_FUNC(void) PyStructSequence_InitType(PyTypeObject *type, - PyStructSequence_Desc *desc); + PyStructSequence_Desc *desc); PyAPI_FUNC(PyObject *) PyStructSequence_New(PyTypeObject* type); typedef struct { - PyObject_VAR_HEAD - PyObject *ob_item[1]; + PyObject_VAR_HEAD + PyObject *ob_item[1]; } PyStructSequence; /* Macro, *only* to be used to fill in brand new objects */ #define PyStructSequence_SET_ITEM(op, i, v) \ - (((PyStructSequence *)(op))->ob_item[i] = v) + (((PyStructSequence *)(op))->ob_item[i] = v) #define PyStructSequence_GET_ITEM(op, i) \ - (((PyStructSequence *)(op))->ob_item[i]) + (((PyStructSequence *)(op))->ob_item[i]) #ifdef __cplusplus Modified: python/branches/py3k-jit/Include/symtable.h ============================================================================== --- python/branches/py3k-jit/Include/symtable.h (original) +++ python/branches/py3k-jit/Include/symtable.h Mon May 10 23:55:43 2010 @@ -15,40 +15,40 @@ struct _symtable_entry; struct symtable { - const char *st_filename; /* name of file being compiled */ - struct _symtable_entry *st_cur; /* current symbol table entry */ - struct _symtable_entry *st_top; /* symbol table entry for module */ - PyObject *st_blocks; /* dict: map AST node addresses - * to symbol table entries */ - PyObject *st_stack; /* list: stack of namespace info */ - PyObject *st_global; /* borrowed ref to st_top->st_symbols */ - int st_nblocks; /* number of blocks used */ - PyObject *st_private; /* name of current class or NULL */ - PyFutureFeatures *st_future; /* module's future features */ + const char *st_filename; /* name of file being compiled */ + struct _symtable_entry *st_cur; /* current symbol table entry */ + struct _symtable_entry *st_top; /* symbol table entry for module */ + PyObject *st_blocks; /* dict: map AST node addresses + * to symbol table entries */ + PyObject *st_stack; /* list: stack of namespace info */ + PyObject *st_global; /* borrowed ref to st_top->st_symbols */ + int st_nblocks; /* number of blocks used */ + PyObject *st_private; /* name of current class or NULL */ + PyFutureFeatures *st_future; /* module's future features */ }; typedef struct _symtable_entry { - PyObject_HEAD - PyObject *ste_id; /* int: key in ste_table->st_blocks */ - PyObject *ste_symbols; /* dict: variable names to flags */ - PyObject *ste_name; /* string: name of current block */ - PyObject *ste_varnames; /* list of variable names */ - PyObject *ste_children; /* list of child blocks */ - _Py_block_ty ste_type; /* module, class, or function */ - int ste_unoptimized; /* false if namespace is optimized */ - int ste_nested; /* true if block is nested */ - unsigned ste_free : 1; /* true if block has free variables */ - unsigned ste_child_free : 1; /* true if a child block has free vars, - including free refs to globals */ - unsigned ste_generator : 1; /* true if namespace is a generator */ - unsigned ste_varargs : 1; /* true if block has varargs */ - unsigned ste_varkeywords : 1; /* true if block has varkeywords */ - unsigned ste_returns_value : 1; /* true if namespace uses return with - an argument */ - int ste_lineno; /* first line of block */ - int ste_opt_lineno; /* lineno of last exec or import * */ - int ste_tmpname; /* counter for listcomp temp vars */ - struct symtable *ste_table; + PyObject_HEAD + PyObject *ste_id; /* int: key in ste_table->st_blocks */ + PyObject *ste_symbols; /* dict: variable names to flags */ + PyObject *ste_name; /* string: name of current block */ + PyObject *ste_varnames; /* list of variable names */ + PyObject *ste_children; /* list of child blocks */ + _Py_block_ty ste_type; /* module, class, or function */ + int ste_unoptimized; /* false if namespace is optimized */ + int ste_nested; /* true if block is nested */ + unsigned ste_free : 1; /* true if block has free variables */ + unsigned ste_child_free : 1; /* true if a child block has free vars, + including free refs to globals */ + unsigned ste_generator : 1; /* true if namespace is a generator */ + unsigned ste_varargs : 1; /* true if block has varargs */ + unsigned ste_varkeywords : 1; /* true if block has varkeywords */ + unsigned ste_returns_value : 1; /* true if namespace uses return with + an argument */ + int ste_lineno; /* first line of block */ + int ste_opt_lineno; /* lineno of last exec or import * */ + int ste_tmpname; /* counter for listcomp temp vars */ + struct symtable *ste_table; } PySTEntryObject; PyAPI_DATA(PyTypeObject) PySTEntry_Type; @@ -57,8 +57,8 @@ PyAPI_FUNC(int) PyST_GetScope(PySTEntryObject *, PyObject *); -PyAPI_FUNC(struct symtable *) PySymtable_Build(mod_ty, const char *, - PyFutureFeatures *); +PyAPI_FUNC(struct symtable *) PySymtable_Build(mod_ty, const char *, + PyFutureFeatures *); PyAPI_FUNC(PySTEntryObject *) PySymtable_Lookup(struct symtable *, void *); PyAPI_FUNC(void) PySymtable_Free(struct symtable *); @@ -77,7 +77,7 @@ #define DEF_BOUND (DEF_LOCAL | DEF_PARAM | DEF_IMPORT) /* GLOBAL_EXPLICIT and GLOBAL_IMPLICIT are used internally by the symbol - table. GLOBAL is returned from PyST_GetScope() for either of them. + table. GLOBAL is returned from PyST_GetScope() for either of them. It is stored in ste_symbols at bits 12-15. */ #define SCOPE_OFFSET 11 Modified: python/branches/py3k-jit/Include/unicodeobject.h ============================================================================== --- python/branches/py3k-jit/Include/unicodeobject.h (original) +++ python/branches/py3k-jit/Include/unicodeobject.h Mon May 10 23:55:43 2010 @@ -28,14 +28,14 @@ * * -------------------------------------------------------------------- * This Unicode String Type is - * + * * Copyright (c) 1999 by Secret Labs AB * Copyright (c) 1999 by Fredrik Lundh - * + * * By obtaining, using, and/or copying this software and/or its * associated documentation, you agree that you have read, understood, * and will comply with the following terms and conditions: - * + * * Permission to use, copy, modify, and distribute this software and its * associated documentation for any purpose and without fee is hereby * granted, provided that the above copyright notice appears in all @@ -44,7 +44,7 @@ * AB or the author not be used in advertising or publicity pertaining to * distribution of the software without specific, written prior * permission. - * + * * SECRET LABS AB AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO * THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND * FITNESS. IN NO EVENT SHALL SECRET LABS AB OR THE AUTHOR BE LIABLE FOR @@ -61,7 +61,7 @@ /* --- Internal Unicode Format -------------------------------------------- */ /* Python 3.x requires unicode */ -#define Py_USING_UNICODE +#define Py_USING_UNICODE /* FIXME: MvL's new implementation assumes that Py_UNICODE_SIZE is properly set, but the default rules below doesn't set it. I'll @@ -120,10 +120,10 @@ * Use this typedef when you need to represent a UTF-16 surrogate pair * as single unsigned integer. */ -#if SIZEOF_INT >= 4 -typedef unsigned int Py_UCS4; +#if SIZEOF_INT >= 4 +typedef unsigned int Py_UCS4; #elif SIZEOF_LONG >= 4 -typedef unsigned long Py_UCS4; +typedef unsigned long Py_UCS4; #endif /* Py_UNICODE is the native Unicode storage format (code unit) used by @@ -384,7 +384,7 @@ */ #define Py_UNICODE_ISSPACE(ch) \ - ((ch) < 128U ? _Py_ascii_whitespace[(ch)] : _PyUnicode_IsWhitespace(ch)) + ((ch) < 128U ? _Py_ascii_whitespace[(ch)] : _PyUnicode_IsWhitespace(ch)) #define Py_UNICODE_ISLOWER(ch) _PyUnicode_IsLowercase(ch) #define Py_UNICODE_ISUPPER(ch) _PyUnicode_IsUppercase(ch) @@ -410,16 +410,16 @@ #define Py_UNICODE_ISALNUM(ch) \ (Py_UNICODE_ISALPHA(ch) || \ - Py_UNICODE_ISDECIMAL(ch) || \ - Py_UNICODE_ISDIGIT(ch) || \ - Py_UNICODE_ISNUMERIC(ch)) + Py_UNICODE_ISDECIMAL(ch) || \ + Py_UNICODE_ISDIGIT(ch) || \ + Py_UNICODE_ISNUMERIC(ch)) -#define Py_UNICODE_COPY(target, source, length) \ - Py_MEMCPY((target), (source), (length)*sizeof(Py_UNICODE)) +#define Py_UNICODE_COPY(target, source, length) \ + Py_MEMCPY((target), (source), (length)*sizeof(Py_UNICODE)) #define Py_UNICODE_FILL(target, value, length) \ do {Py_ssize_t i_; Py_UNICODE *t_ = (target); Py_UNICODE v_ = (value);\ - for (i_ = 0; i_ < (length); i_++) t_[i_] = v_;\ + for (i_ = 0; i_ < (length); i_++) t_[i_] = v_;\ } while (0) /* Check if substring matches at given offset. the offset must be @@ -438,15 +438,15 @@ typedef struct { PyObject_HEAD - Py_ssize_t length; /* Length of raw Unicode data in buffer */ - Py_UNICODE *str; /* Raw Unicode buffer */ - long hash; /* Hash value; -1 if not set */ - int state; /* != 0 if interned. In this case the two - * references from the dictionary to this object - * are *not* counted in ob_refcnt. */ - PyObject *defenc; /* (Default) Encoded version as Python - string, or NULL; this is used for - implementing the buffer protocol */ + Py_ssize_t length; /* Length of raw Unicode data in buffer */ + Py_UNICODE *str; /* Raw Unicode buffer */ + long hash; /* Hash value; -1 if not set */ + int state; /* != 0 if interned. In this case the two + * references from the dictionary to this object + * are *not* counted in ob_refcnt. */ + PyObject *defenc; /* (Default) Encoded version as Python + string, or NULL; this is used for + implementing the buffer protocol */ } PyUnicodeObject; PyAPI_DATA(PyTypeObject) PyUnicode_Type; @@ -462,13 +462,13 @@ /* Fast access macros */ #define PyUnicode_GET_SIZE(op) \ - (assert(PyUnicode_Check(op)),(((PyUnicodeObject *)(op))->length)) + (assert(PyUnicode_Check(op)),(((PyUnicodeObject *)(op))->length)) #define PyUnicode_GET_DATA_SIZE(op) \ - (assert(PyUnicode_Check(op)),(((PyUnicodeObject *)(op))->length * sizeof(Py_UNICODE))) + (assert(PyUnicode_Check(op)),(((PyUnicodeObject *)(op))->length * sizeof(Py_UNICODE))) #define PyUnicode_AS_UNICODE(op) \ - (assert(PyUnicode_Check(op)),(((PyUnicodeObject *)(op))->str)) + (assert(PyUnicode_Check(op)),(((PyUnicodeObject *)(op))->str)) #define PyUnicode_AS_DATA(op) \ - (assert(PyUnicode_Check(op)),((const char *)((PyUnicodeObject *)(op))->str)) + (assert(PyUnicode_Check(op)),((const char *)((PyUnicodeObject *)(op))->str)) /* --- Constants ---------------------------------------------------------- */ @@ -484,7 +484,7 @@ /* --- Plain Py_UNICODE --------------------------------------------------- */ /* Create a Unicode Object from the Py_UNICODE buffer u of the given - size. + size. u may be NULL which causes the contents to be undefined. It is the user's responsibility to fill in the needed data afterwards. Note @@ -514,13 +514,13 @@ Py_UNICODE buffer. */ PyAPI_FUNC(Py_UNICODE *) PyUnicode_AsUnicode( - PyObject *unicode /* Unicode object */ + PyObject *unicode /* Unicode object */ ); /* Get the length of the Unicode object. */ PyAPI_FUNC(Py_ssize_t) PyUnicode_GetSize( - PyObject *unicode /* Unicode object */ + PyObject *unicode /* Unicode object */ ); /* Get the maximum ordinal for a Unicode character. */ @@ -541,8 +541,8 @@ */ PyAPI_FUNC(int) PyUnicode_Resize( - PyObject **unicode, /* Pointer to the Unicode object */ - Py_ssize_t length /* New length */ + PyObject **unicode, /* Pointer to the Unicode object */ + Py_ssize_t length /* New length */ ); /* Coerce obj to an Unicode object and return a reference with @@ -563,14 +563,14 @@ */ PyAPI_FUNC(PyObject*) PyUnicode_FromEncodedObject( - register PyObject *obj, /* Object */ + register PyObject *obj, /* Object */ const char *encoding, /* encoding */ const char *errors /* error handling */ ); /* Coerce obj to an Unicode object and return a reference with *incremented* refcount. - + Unicode objects are passed back as-is (subclasses are converted to true Unicode objects), all other objects are delegated to PyUnicode_FromEncodedObject(obj, NULL, "strict") which results in @@ -582,7 +582,7 @@ */ PyAPI_FUNC(PyObject*) PyUnicode_FromObject( - register PyObject *obj /* Object */ + register PyObject *obj /* Object */ ); PyAPI_FUNC(PyObject *) PyUnicode_FromFormatV(const char*, va_list); @@ -638,8 +638,8 @@ /* --- Unicode ordinals --------------------------------------------------- */ -/* Create a Unicode Object from the given Unicode code point ordinal. - +/* Create a Unicode Object from the given Unicode code point ordinal. + The ordinal must be in range(0x10000) on narrow Python builds (UCS2), and range(0x110000) on wide builds (UCS4). A ValueError is raised in case it is not. @@ -659,11 +659,11 @@ PyAPI_FUNC(int) PyUnicode_ClearFreeList(void); -/* === Builtin Codecs ===================================================== +/* === Builtin Codecs ===================================================== Many of these APIs take two arguments encoding and errors. These parameters encoding and errors have the same semantics as the ones - of the builtin unicode() API. + of the builtin unicode() API. Setting encoding to NULL causes the default encoding to be used. @@ -680,7 +680,7 @@ /* --- Manage the default encoding ---------------------------------------- */ /* Return a Python string holding the default encoded value of the - Unicode object. + Unicode object. The resulting string is cached in the Unicode object for subsequent usage by this function. The cached version is needed to implement @@ -712,7 +712,7 @@ */ PyAPI_FUNC(char *) _PyUnicode_AsStringAndSize( - PyObject *unicode, + PyObject *unicode, Py_ssize_t *size); /* Returns a pointer to the default encoding (normally, UTf-8) of the @@ -737,7 +737,7 @@ process global. This may change in future versions of the interpreter to become a parameter which is managed on a per-thread basis. - + */ PyAPI_FUNC(const char*) PyUnicode_GetDefaultEncoding(void); @@ -745,11 +745,11 @@ /* Sets the currently active default encoding. Returns 0 on success, -1 in case of an error. - + */ PyAPI_FUNC(int) PyUnicode_SetDefaultEncoding( - const char *encoding /* Encoding name in standard form */ + const char *encoding /* Encoding name in standard form */ ); /* --- Generic Codecs ----------------------------------------------------- */ @@ -768,21 +768,21 @@ object. */ PyAPI_FUNC(PyObject*) PyUnicode_AsDecodedObject( - PyObject *unicode, /* Unicode object */ - const char *encoding, /* encoding */ - const char *errors /* error handling */ + PyObject *unicode, /* Unicode object */ + const char *encoding, /* encoding */ + const char *errors /* error handling */ ); /* Decode a Unicode object unicode and return the result as Unicode object. */ PyAPI_FUNC(PyObject*) PyUnicode_AsDecodedUnicode( - PyObject *unicode, /* Unicode object */ - const char *encoding, /* encoding */ - const char *errors /* error handling */ + PyObject *unicode, /* Unicode object */ + const char *encoding, /* encoding */ + const char *errors /* error handling */ ); -/* Encodes a Py_UNICODE buffer of the given size and returns a +/* Encodes a Py_UNICODE buffer of the given size and returns a Python string object. */ PyAPI_FUNC(PyObject*) PyUnicode_Encode( @@ -796,27 +796,27 @@ object. */ PyAPI_FUNC(PyObject*) PyUnicode_AsEncodedObject( - PyObject *unicode, /* Unicode object */ - const char *encoding, /* encoding */ - const char *errors /* error handling */ + PyObject *unicode, /* Unicode object */ + const char *encoding, /* encoding */ + const char *errors /* error handling */ ); /* Encodes a Unicode object and returns the result as Python string object. */ PyAPI_FUNC(PyObject*) PyUnicode_AsEncodedString( - PyObject *unicode, /* Unicode object */ - const char *encoding, /* encoding */ - const char *errors /* error handling */ + PyObject *unicode, /* Unicode object */ + const char *encoding, /* encoding */ + const char *errors /* error handling */ ); /* Encodes a Unicode object and returns the result as Unicode object. */ PyAPI_FUNC(PyObject*) PyUnicode_AsEncodedUnicode( - PyObject *unicode, /* Unicode object */ - const char *encoding, /* encoding */ - const char *errors /* error handling */ + PyObject *unicode, /* Unicode object */ + const char *encoding, /* encoding */ + const char *errors /* error handling */ ); /* Build an encoding map. */ @@ -828,49 +828,49 @@ /* --- UTF-7 Codecs ------------------------------------------------------- */ PyAPI_FUNC(PyObject*) PyUnicode_DecodeUTF7( - const char *string, /* UTF-7 encoded string */ - Py_ssize_t length, /* size of string */ - const char *errors /* error handling */ + const char *string, /* UTF-7 encoded string */ + Py_ssize_t length, /* size of string */ + const char *errors /* error handling */ ); PyAPI_FUNC(PyObject*) PyUnicode_DecodeUTF7Stateful( - const char *string, /* UTF-7 encoded string */ - Py_ssize_t length, /* size of string */ - const char *errors, /* error handling */ - Py_ssize_t *consumed /* bytes consumed */ + const char *string, /* UTF-7 encoded string */ + Py_ssize_t length, /* size of string */ + const char *errors, /* error handling */ + Py_ssize_t *consumed /* bytes consumed */ ); PyAPI_FUNC(PyObject*) PyUnicode_EncodeUTF7( - const Py_UNICODE *data, /* Unicode char buffer */ - Py_ssize_t length, /* number of Py_UNICODE chars to encode */ - int base64SetO, /* Encode RFC2152 Set O characters in base64 */ - int base64WhiteSpace, /* Encode whitespace (sp, ht, nl, cr) in base64 */ - const char *errors /* error handling */ + const Py_UNICODE *data, /* Unicode char buffer */ + Py_ssize_t length, /* number of Py_UNICODE chars to encode */ + int base64SetO, /* Encode RFC2152 Set O characters in base64 */ + int base64WhiteSpace, /* Encode whitespace (sp, ht, nl, cr) in base64 */ + const char *errors /* error handling */ ); /* --- UTF-8 Codecs ------------------------------------------------------- */ PyAPI_FUNC(PyObject*) PyUnicode_DecodeUTF8( - const char *string, /* UTF-8 encoded string */ - Py_ssize_t length, /* size of string */ - const char *errors /* error handling */ + const char *string, /* UTF-8 encoded string */ + Py_ssize_t length, /* size of string */ + const char *errors /* error handling */ ); PyAPI_FUNC(PyObject*) PyUnicode_DecodeUTF8Stateful( - const char *string, /* UTF-8 encoded string */ - Py_ssize_t length, /* size of string */ - const char *errors, /* error handling */ - Py_ssize_t *consumed /* bytes consumed */ + const char *string, /* UTF-8 encoded string */ + Py_ssize_t length, /* size of string */ + const char *errors, /* error handling */ + Py_ssize_t *consumed /* bytes consumed */ ); PyAPI_FUNC(PyObject*) PyUnicode_AsUTF8String( - PyObject *unicode /* Unicode object */ + PyObject *unicode /* Unicode object */ ); PyAPI_FUNC(PyObject*) PyUnicode_EncodeUTF8( - const Py_UNICODE *data, /* Unicode char buffer */ - Py_ssize_t length, /* number of Py_UNICODE chars to encode */ - const char *errors /* error handling */ + const Py_UNICODE *data, /* Unicode char buffer */ + Py_ssize_t length, /* number of Py_UNICODE chars to encode */ + const char *errors /* error handling */ ); /* --- UTF-32 Codecs ------------------------------------------------------ */ @@ -879,14 +879,14 @@ the corresponding Unicode object. errors (if non-NULL) defines the error handling. It defaults - to "strict". + to "strict". If byteorder is non-NULL, the decoder starts decoding using the given byte order: - *byteorder == -1: little endian - *byteorder == 0: native order - *byteorder == 1: big endian + *byteorder == -1: little endian + *byteorder == 0: native order + *byteorder == 1: big endian In native mode, the first four bytes of the stream are checked for a BOM mark. If found, the BOM mark is analysed, the byte order @@ -899,29 +899,29 @@ */ PyAPI_FUNC(PyObject*) PyUnicode_DecodeUTF32( - const char *string, /* UTF-32 encoded string */ - Py_ssize_t length, /* size of string */ - const char *errors, /* error handling */ - int *byteorder /* pointer to byteorder to use - 0=native;-1=LE,1=BE; updated on - exit */ + const char *string, /* UTF-32 encoded string */ + Py_ssize_t length, /* size of string */ + const char *errors, /* error handling */ + int *byteorder /* pointer to byteorder to use + 0=native;-1=LE,1=BE; updated on + exit */ ); PyAPI_FUNC(PyObject*) PyUnicode_DecodeUTF32Stateful( - const char *string, /* UTF-32 encoded string */ - Py_ssize_t length, /* size of string */ - const char *errors, /* error handling */ - int *byteorder, /* pointer to byteorder to use - 0=native;-1=LE,1=BE; updated on - exit */ - Py_ssize_t *consumed /* bytes consumed */ + const char *string, /* UTF-32 encoded string */ + Py_ssize_t length, /* size of string */ + const char *errors, /* error handling */ + int *byteorder, /* pointer to byteorder to use + 0=native;-1=LE,1=BE; updated on + exit */ + Py_ssize_t *consumed /* bytes consumed */ ); /* Returns a Python string using the UTF-32 encoding in native byte order. The string always starts with a BOM mark. */ PyAPI_FUNC(PyObject*) PyUnicode_AsUTF32String( - PyObject *unicode /* Unicode object */ + PyObject *unicode /* Unicode object */ ); /* Returns a Python string object holding the UTF-32 encoded value of @@ -941,10 +941,10 @@ */ PyAPI_FUNC(PyObject*) PyUnicode_EncodeUTF32( - const Py_UNICODE *data, /* Unicode char buffer */ - Py_ssize_t length, /* number of Py_UNICODE chars to encode */ - const char *errors, /* error handling */ - int byteorder /* byteorder to use 0=BOM+native;-1=LE,1=BE */ + const Py_UNICODE *data, /* Unicode char buffer */ + Py_ssize_t length, /* number of Py_UNICODE chars to encode */ + const char *errors, /* error handling */ + int byteorder /* byteorder to use 0=BOM+native;-1=LE,1=BE */ ); /* --- UTF-16 Codecs ------------------------------------------------------ */ @@ -953,14 +953,14 @@ the corresponding Unicode object. errors (if non-NULL) defines the error handling. It defaults - to "strict". + to "strict". If byteorder is non-NULL, the decoder starts decoding using the given byte order: - *byteorder == -1: little endian - *byteorder == 0: native order - *byteorder == 1: big endian + *byteorder == -1: little endian + *byteorder == 0: native order + *byteorder == 1: big endian In native mode, the first two bytes of the stream are checked for a BOM mark. If found, the BOM mark is analysed, the byte order @@ -973,29 +973,29 @@ */ PyAPI_FUNC(PyObject*) PyUnicode_DecodeUTF16( - const char *string, /* UTF-16 encoded string */ - Py_ssize_t length, /* size of string */ - const char *errors, /* error handling */ - int *byteorder /* pointer to byteorder to use - 0=native;-1=LE,1=BE; updated on - exit */ + const char *string, /* UTF-16 encoded string */ + Py_ssize_t length, /* size of string */ + const char *errors, /* error handling */ + int *byteorder /* pointer to byteorder to use + 0=native;-1=LE,1=BE; updated on + exit */ ); PyAPI_FUNC(PyObject*) PyUnicode_DecodeUTF16Stateful( - const char *string, /* UTF-16 encoded string */ - Py_ssize_t length, /* size of string */ - const char *errors, /* error handling */ - int *byteorder, /* pointer to byteorder to use - 0=native;-1=LE,1=BE; updated on - exit */ - Py_ssize_t *consumed /* bytes consumed */ + const char *string, /* UTF-16 encoded string */ + Py_ssize_t length, /* size of string */ + const char *errors, /* error handling */ + int *byteorder, /* pointer to byteorder to use + 0=native;-1=LE,1=BE; updated on + exit */ + Py_ssize_t *consumed /* bytes consumed */ ); /* Returns a Python string using the UTF-16 encoding in native byte order. The string always starts with a BOM mark. */ PyAPI_FUNC(PyObject*) PyUnicode_AsUTF16String( - PyObject *unicode /* Unicode object */ + PyObject *unicode /* Unicode object */ ); /* Returns a Python string object holding the UTF-16 encoded value of @@ -1019,44 +1019,44 @@ */ PyAPI_FUNC(PyObject*) PyUnicode_EncodeUTF16( - const Py_UNICODE *data, /* Unicode char buffer */ - Py_ssize_t length, /* number of Py_UNICODE chars to encode */ - const char *errors, /* error handling */ - int byteorder /* byteorder to use 0=BOM+native;-1=LE,1=BE */ + const Py_UNICODE *data, /* Unicode char buffer */ + Py_ssize_t length, /* number of Py_UNICODE chars to encode */ + const char *errors, /* error handling */ + int byteorder /* byteorder to use 0=BOM+native;-1=LE,1=BE */ ); /* --- Unicode-Escape Codecs ---------------------------------------------- */ PyAPI_FUNC(PyObject*) PyUnicode_DecodeUnicodeEscape( - const char *string, /* Unicode-Escape encoded string */ - Py_ssize_t length, /* size of string */ - const char *errors /* error handling */ + const char *string, /* Unicode-Escape encoded string */ + Py_ssize_t length, /* size of string */ + const char *errors /* error handling */ ); PyAPI_FUNC(PyObject*) PyUnicode_AsUnicodeEscapeString( - PyObject *unicode /* Unicode object */ + PyObject *unicode /* Unicode object */ ); PyAPI_FUNC(PyObject*) PyUnicode_EncodeUnicodeEscape( - const Py_UNICODE *data, /* Unicode char buffer */ - Py_ssize_t length /* Number of Py_UNICODE chars to encode */ + const Py_UNICODE *data, /* Unicode char buffer */ + Py_ssize_t length /* Number of Py_UNICODE chars to encode */ ); /* --- Raw-Unicode-Escape Codecs ------------------------------------------ */ PyAPI_FUNC(PyObject*) PyUnicode_DecodeRawUnicodeEscape( - const char *string, /* Raw-Unicode-Escape encoded string */ - Py_ssize_t length, /* size of string */ - const char *errors /* error handling */ + const char *string, /* Raw-Unicode-Escape encoded string */ + Py_ssize_t length, /* size of string */ + const char *errors /* error handling */ ); PyAPI_FUNC(PyObject*) PyUnicode_AsRawUnicodeEscapeString( - PyObject *unicode /* Unicode object */ + PyObject *unicode /* Unicode object */ ); PyAPI_FUNC(PyObject*) PyUnicode_EncodeRawUnicodeEscape( - const Py_UNICODE *data, /* Unicode char buffer */ - Py_ssize_t length /* Number of Py_UNICODE chars to encode */ + const Py_UNICODE *data, /* Unicode char buffer */ + Py_ssize_t length /* Number of Py_UNICODE chars to encode */ ); /* --- Unicode Internal Codec --------------------------------------------- @@ -1069,53 +1069,53 @@ const char *errors ); -/* --- Latin-1 Codecs ----------------------------------------------------- +/* --- Latin-1 Codecs ----------------------------------------------------- Note: Latin-1 corresponds to the first 256 Unicode ordinals. */ PyAPI_FUNC(PyObject*) PyUnicode_DecodeLatin1( - const char *string, /* Latin-1 encoded string */ - Py_ssize_t length, /* size of string */ - const char *errors /* error handling */ + const char *string, /* Latin-1 encoded string */ + Py_ssize_t length, /* size of string */ + const char *errors /* error handling */ ); PyAPI_FUNC(PyObject*) PyUnicode_AsLatin1String( - PyObject *unicode /* Unicode object */ + PyObject *unicode /* Unicode object */ ); PyAPI_FUNC(PyObject*) PyUnicode_EncodeLatin1( - const Py_UNICODE *data, /* Unicode char buffer */ - Py_ssize_t length, /* Number of Py_UNICODE chars to encode */ - const char *errors /* error handling */ + const Py_UNICODE *data, /* Unicode char buffer */ + Py_ssize_t length, /* Number of Py_UNICODE chars to encode */ + const char *errors /* error handling */ ); -/* --- ASCII Codecs ------------------------------------------------------- +/* --- ASCII Codecs ------------------------------------------------------- Only 7-bit ASCII data is excepted. All other codes generate errors. */ PyAPI_FUNC(PyObject*) PyUnicode_DecodeASCII( - const char *string, /* ASCII encoded string */ - Py_ssize_t length, /* size of string */ - const char *errors /* error handling */ + const char *string, /* ASCII encoded string */ + Py_ssize_t length, /* size of string */ + const char *errors /* error handling */ ); PyAPI_FUNC(PyObject*) PyUnicode_AsASCIIString( - PyObject *unicode /* Unicode object */ + PyObject *unicode /* Unicode object */ ); PyAPI_FUNC(PyObject*) PyUnicode_EncodeASCII( - const Py_UNICODE *data, /* Unicode char buffer */ - Py_ssize_t length, /* Number of Py_UNICODE chars to encode */ - const char *errors /* error handling */ + const Py_UNICODE *data, /* Unicode char buffer */ + Py_ssize_t length, /* Number of Py_UNICODE chars to encode */ + const char *errors /* error handling */ ); -/* --- Character Map Codecs ----------------------------------------------- +/* --- Character Map Codecs ----------------------------------------------- - This codec uses mappings to encode and decode characters. + This codec uses mappings to encode and decode characters. Decoding mappings must map single string characters to single Unicode characters, integers (which are then interpreted as Unicode @@ -1136,25 +1136,25 @@ */ PyAPI_FUNC(PyObject*) PyUnicode_DecodeCharmap( - const char *string, /* Encoded string */ - Py_ssize_t length, /* size of string */ - PyObject *mapping, /* character mapping - (char ordinal -> unicode ordinal) */ - const char *errors /* error handling */ + const char *string, /* Encoded string */ + Py_ssize_t length, /* size of string */ + PyObject *mapping, /* character mapping + (char ordinal -> unicode ordinal) */ + const char *errors /* error handling */ ); PyAPI_FUNC(PyObject*) PyUnicode_AsCharmapString( - PyObject *unicode, /* Unicode object */ - PyObject *mapping /* character mapping - (unicode ordinal -> char ordinal) */ + PyObject *unicode, /* Unicode object */ + PyObject *mapping /* character mapping + (unicode ordinal -> char ordinal) */ ); PyAPI_FUNC(PyObject*) PyUnicode_EncodeCharmap( - const Py_UNICODE *data, /* Unicode char buffer */ - Py_ssize_t length, /* Number of Py_UNICODE chars to encode */ - PyObject *mapping, /* character mapping - (unicode ordinal -> char ordinal) */ - const char *errors /* error handling */ + const Py_UNICODE *data, /* Unicode char buffer */ + Py_ssize_t length, /* Number of Py_UNICODE chars to encode */ + PyObject *mapping, /* character mapping + (unicode ordinal -> char ordinal) */ + const char *errors /* error handling */ ); /* Translate a Py_UNICODE buffer of the given length by applying a @@ -1162,7 +1162,7 @@ object. The mapping table must map Unicode ordinal integers to Unicode - ordinal integers or None (causing deletion of the character). + ordinal integers or None (causing deletion of the character). Mapping tables may be dictionaries or sequences. Unmapped character ordinals (ones which cause a LookupError) are left untouched and @@ -1171,10 +1171,10 @@ */ PyAPI_FUNC(PyObject *) PyUnicode_TranslateCharmap( - const Py_UNICODE *data, /* Unicode char buffer */ - Py_ssize_t length, /* Number of Py_UNICODE chars to encode */ - PyObject *table, /* Translate table */ - const char *errors /* error handling */ + const Py_UNICODE *data, /* Unicode char buffer */ + Py_ssize_t length, /* Number of Py_UNICODE chars to encode */ + PyObject *table, /* Translate table */ + const char *errors /* error handling */ ); #ifdef MS_WIN32 @@ -1223,7 +1223,7 @@ NULL or "strict": raise a ValueError "ignore": ignore the wrong characters (these are not copied to the - output buffer) + output buffer) "replace": replaces illegal characters with '?' Returns 0 on success, -1 on failure. @@ -1231,10 +1231,10 @@ */ PyAPI_FUNC(int) PyUnicode_EncodeDecimal( - Py_UNICODE *s, /* Unicode buffer */ - Py_ssize_t length, /* Number of Py_UNICODE chars to encode */ - char *output, /* Output buffer; must have size >= length */ - const char *errors /* error handling */ + Py_UNICODE *s, /* Unicode buffer */ + Py_ssize_t length, /* Number of Py_UNICODE chars to encode */ + char *output, /* Output buffer; must have size >= length */ + const char *errors /* error handling */ ); /* --- File system encoding ---------------------------------------------- */ @@ -1273,24 +1273,24 @@ /* Concat two strings giving a new Unicode string. */ PyAPI_FUNC(PyObject*) PyUnicode_Concat( - PyObject *left, /* Left string */ - PyObject *right /* Right string */ + PyObject *left, /* Left string */ + PyObject *right /* Right string */ ); /* Concat two strings and put the result in *pleft (sets *pleft to NULL on error) */ PyAPI_FUNC(void) PyUnicode_Append( - PyObject **pleft, /* Pointer to left string */ - PyObject *right /* Right string */ + PyObject **pleft, /* Pointer to left string */ + PyObject *right /* Right string */ ); /* Concat two strings, put the result in *pleft and drop the right object (sets *pleft to NULL on error) */ PyAPI_FUNC(void) PyUnicode_AppendAndDel( - PyObject **pleft, /* Pointer to left string */ - PyObject *right /* Right string */ + PyObject **pleft, /* Pointer to left string */ + PyObject *right /* Right string */ ); /* Split a string giving a list of Unicode strings. @@ -1305,35 +1305,35 @@ */ PyAPI_FUNC(PyObject*) PyUnicode_Split( - PyObject *s, /* String to split */ - PyObject *sep, /* String separator */ - Py_ssize_t maxsplit /* Maxsplit count */ - ); + PyObject *s, /* String to split */ + PyObject *sep, /* String separator */ + Py_ssize_t maxsplit /* Maxsplit count */ + ); /* Dito, but split at line breaks. CRLF is considered to be one line break. Line breaks are not included in the resulting list. */ - + PyAPI_FUNC(PyObject*) PyUnicode_Splitlines( - PyObject *s, /* String to split */ - int keepends /* If true, line end markers are included */ - ); + PyObject *s, /* String to split */ + int keepends /* If true, line end markers are included */ + ); /* Partition a string using a given separator. */ PyAPI_FUNC(PyObject*) PyUnicode_Partition( - PyObject *s, /* String to partition */ - PyObject *sep /* String separator */ - ); + PyObject *s, /* String to partition */ + PyObject *sep /* String separator */ + ); /* Partition a string using a given separator, searching from the end of the string. */ PyAPI_FUNC(PyObject*) PyUnicode_RPartition( - PyObject *s, /* String to partition */ - PyObject *sep /* String separator */ - ); + PyObject *s, /* String to partition */ + PyObject *sep /* String separator */ + ); /* Split a string giving a list of Unicode strings. @@ -1349,16 +1349,16 @@ */ PyAPI_FUNC(PyObject*) PyUnicode_RSplit( - PyObject *s, /* String to split */ - PyObject *sep, /* String separator */ - Py_ssize_t maxsplit /* Maxsplit count */ - ); + PyObject *s, /* String to split */ + PyObject *sep, /* String separator */ + Py_ssize_t maxsplit /* Maxsplit count */ + ); /* Translate a string by applying a character mapping table to it and return the resulting Unicode object. The mapping table must map Unicode ordinal integers to Unicode - ordinal integers or None (causing deletion of the character). + ordinal integers or None (causing deletion of the character). Mapping tables may be dictionaries or sequences. Unmapped character ordinals (ones which cause a LookupError) are left untouched and @@ -1367,28 +1367,28 @@ */ PyAPI_FUNC(PyObject *) PyUnicode_Translate( - PyObject *str, /* String */ - PyObject *table, /* Translate table */ - const char *errors /* error handling */ + PyObject *str, /* String */ + PyObject *table, /* Translate table */ + const char *errors /* error handling */ ); /* Join a sequence of strings using the given separator and return the resulting Unicode string. */ - + PyAPI_FUNC(PyObject*) PyUnicode_Join( - PyObject *separator, /* Separator string */ - PyObject *seq /* Sequence object */ + PyObject *separator, /* Separator string */ + PyObject *seq /* Sequence object */ ); /* Return 1 if substr matches str[start:end] at the given tail end, 0 otherwise. */ PyAPI_FUNC(Py_ssize_t) PyUnicode_Tailmatch( - PyObject *str, /* String */ - PyObject *substr, /* Prefix or Suffix string */ - Py_ssize_t start, /* Start index */ - Py_ssize_t end, /* Stop index */ - int direction /* Tail end: -1 prefix, +1 suffix */ + PyObject *str, /* String */ + PyObject *substr, /* Prefix or Suffix string */ + Py_ssize_t start, /* Start index */ + Py_ssize_t end, /* Stop index */ + int direction /* Tail end: -1 prefix, +1 suffix */ ); /* Return the first position of substr in str[start:end] using the @@ -1396,39 +1396,39 @@ an error occurred and an exception is set. */ PyAPI_FUNC(Py_ssize_t) PyUnicode_Find( - PyObject *str, /* String */ - PyObject *substr, /* Substring to find */ - Py_ssize_t start, /* Start index */ - Py_ssize_t end, /* Stop index */ - int direction /* Find direction: +1 forward, -1 backward */ + PyObject *str, /* String */ + PyObject *substr, /* Substring to find */ + Py_ssize_t start, /* Start index */ + Py_ssize_t end, /* Stop index */ + int direction /* Find direction: +1 forward, -1 backward */ ); /* Count the number of occurrences of substr in str[start:end]. */ PyAPI_FUNC(Py_ssize_t) PyUnicode_Count( - PyObject *str, /* String */ - PyObject *substr, /* Substring to count */ - Py_ssize_t start, /* Start index */ - Py_ssize_t end /* Stop index */ + PyObject *str, /* String */ + PyObject *substr, /* Substring to count */ + Py_ssize_t start, /* Start index */ + Py_ssize_t end /* Stop index */ ); /* Replace at most maxcount occurrences of substr in str with replstr and return the resulting Unicode object. */ PyAPI_FUNC(PyObject *) PyUnicode_Replace( - PyObject *str, /* String */ - PyObject *substr, /* Substring to find */ - PyObject *replstr, /* Substring to replace */ - Py_ssize_t maxcount /* Max. number of replacements to apply; - -1 = all */ + PyObject *str, /* String */ + PyObject *substr, /* Substring to find */ + PyObject *replstr, /* Substring to replace */ + Py_ssize_t maxcount /* Max. number of replacements to apply; + -1 = all */ ); /* Compare two strings and return -1, 0, 1 for less than, equal, greater than resp. */ PyAPI_FUNC(int) PyUnicode_Compare( - PyObject *left, /* Left string */ - PyObject *right /* Right string */ + PyObject *left, /* Left string */ + PyObject *right /* Right string */ ); PyAPI_FUNC(int) PyUnicode_CompareWithASCIIString( @@ -1453,17 +1453,17 @@ */ PyAPI_FUNC(PyObject *) PyUnicode_RichCompare( - PyObject *left, /* Left string */ - PyObject *right, /* Right string */ - int op /* Operation: Py_EQ, Py_NE, Py_GT, etc. */ + PyObject *left, /* Left string */ + PyObject *right, /* Right string */ + int op /* Operation: Py_EQ, Py_NE, Py_GT, etc. */ ); /* Apply a argument tuple or dictionary to a format string and return the resulting Unicode string. */ PyAPI_FUNC(PyObject *) PyUnicode_Format( - PyObject *format, /* Format string */ - PyObject *args /* Argument tuple or dictionary */ + PyObject *format, /* Format string */ + PyObject *args /* Argument tuple or dictionary */ ); /* Checks whether element is contained in container and return 1/0 @@ -1473,8 +1473,8 @@ returned in case of an error. */ PyAPI_FUNC(int) PyUnicode_Contains( - PyObject *container, /* Container string */ - PyObject *element /* Element string */ + PyObject *container, /* Container string */ + PyObject *element /* Element string */ ); /* Checks whether argument is a valid identifier. */ @@ -1515,82 +1515,82 @@ PyAPI_DATA(const unsigned char) _Py_ascii_whitespace[]; /* These should not be used directly. Use the Py_UNICODE_IS* and - Py_UNICODE_TO* macros instead. + Py_UNICODE_TO* macros instead. These APIs are implemented in Objects/unicodectype.c. */ PyAPI_FUNC(int) _PyUnicode_IsLowercase( - Py_UNICODE ch /* Unicode character */ + Py_UNICODE ch /* Unicode character */ ); PyAPI_FUNC(int) _PyUnicode_IsUppercase( - Py_UNICODE ch /* Unicode character */ + Py_UNICODE ch /* Unicode character */ ); PyAPI_FUNC(int) _PyUnicode_IsTitlecase( - Py_UNICODE ch /* Unicode character */ + Py_UNICODE ch /* Unicode character */ ); PyAPI_FUNC(int) _PyUnicode_IsXidStart( - Py_UNICODE ch /* Unicode character */ + Py_UNICODE ch /* Unicode character */ ); PyAPI_FUNC(int) _PyUnicode_IsXidContinue( - Py_UNICODE ch /* Unicode character */ + Py_UNICODE ch /* Unicode character */ ); PyAPI_FUNC(int) _PyUnicode_IsWhitespace( - const Py_UNICODE ch /* Unicode character */ + const Py_UNICODE ch /* Unicode character */ ); PyAPI_FUNC(int) _PyUnicode_IsLinebreak( - const Py_UNICODE ch /* Unicode character */ + const Py_UNICODE ch /* Unicode character */ ); PyAPI_FUNC(Py_UNICODE) _PyUnicode_ToLowercase( - Py_UNICODE ch /* Unicode character */ + Py_UNICODE ch /* Unicode character */ ); PyAPI_FUNC(Py_UNICODE) _PyUnicode_ToUppercase( - Py_UNICODE ch /* Unicode character */ + Py_UNICODE ch /* Unicode character */ ); PyAPI_FUNC(Py_UNICODE) _PyUnicode_ToTitlecase( - Py_UNICODE ch /* Unicode character */ + Py_UNICODE ch /* Unicode character */ ); PyAPI_FUNC(int) _PyUnicode_ToDecimalDigit( - Py_UNICODE ch /* Unicode character */ + Py_UNICODE ch /* Unicode character */ ); PyAPI_FUNC(int) _PyUnicode_ToDigit( - Py_UNICODE ch /* Unicode character */ + Py_UNICODE ch /* Unicode character */ ); PyAPI_FUNC(double) _PyUnicode_ToNumeric( - Py_UNICODE ch /* Unicode character */ + Py_UNICODE ch /* Unicode character */ ); PyAPI_FUNC(int) _PyUnicode_IsDecimalDigit( - Py_UNICODE ch /* Unicode character */ + Py_UNICODE ch /* Unicode character */ ); PyAPI_FUNC(int) _PyUnicode_IsDigit( - Py_UNICODE ch /* Unicode character */ + Py_UNICODE ch /* Unicode character */ ); PyAPI_FUNC(int) _PyUnicode_IsNumeric( - Py_UNICODE ch /* Unicode character */ + Py_UNICODE ch /* Unicode character */ ); PyAPI_FUNC(int) _PyUnicode_IsPrintable( - Py_UNICODE ch /* Unicode character */ + Py_UNICODE ch /* Unicode character */ ); PyAPI_FUNC(int) _PyUnicode_IsAlpha( - Py_UNICODE ch /* Unicode character */ + Py_UNICODE ch /* Unicode character */ ); PyAPI_FUNC(size_t) Py_UNICODE_strlen(const Py_UNICODE *u); Modified: python/branches/py3k-jit/Mac/Tools/pythonw.c ============================================================================== --- python/branches/py3k-jit/Mac/Tools/pythonw.c (original) +++ python/branches/py3k-jit/Mac/Tools/pythonw.c Mon May 10 23:55:43 2010 @@ -39,8 +39,8 @@ * In a regular framework the structure is: * * Python.framework/Versions/2.7 - * /Python - * /Resources/Python.app/Contents/MacOS/Python + * /Python + * /Resources/Python.app/Contents/MacOS/Python * * In a virtualenv style structure the expected * structure is: @@ -50,121 +50,121 @@ * /.Python <- the dylib * /.Resources/Python.app/Contents/MacOS/Python * - * NOTE: virtualenv's are not an officially supported + * NOTE: virtualenv's are not an officially supported * feature, support for that structure is provided as * a convenience. */ static char* get_python_path(void) { - size_t len; - Dl_info info; - char* end; - char* g_path; - - if (dladdr(Py_Initialize, &info) == 0) { - return NULL; - } - - len = strlen(info.dli_fname); - - g_path = malloc(len+60); - if (g_path == NULL) { - return NULL; - } - - strcpy(g_path, info.dli_fname); - end = g_path + len - 1; - while (end != g_path && *end != '/') { - end --; - } - end++; - if (*end == '.') { - end++; - } - strcpy(end, "Resources/Python.app/Contents/MacOS/" PYTHONFRAMEWORK); + size_t len; + Dl_info info; + char* end; + char* g_path; + + if (dladdr(Py_Initialize, &info) == 0) { + return NULL; + } + + len = strlen(info.dli_fname); + + g_path = malloc(len+60); + if (g_path == NULL) { + return NULL; + } + + strcpy(g_path, info.dli_fname); + end = g_path + len - 1; + while (end != g_path && *end != '/') { + end --; + } + end++; + if (*end == '.') { + end++; + } + strcpy(end, "Resources/Python.app/Contents/MacOS/" PYTHONFRAMEWORK); - return g_path; + return g_path; } #ifdef HAVE_SPAWN_H static void setup_spawnattr(posix_spawnattr_t* spawnattr) { - size_t ocount; - size_t count; - cpu_type_t cpu_types[1]; - short flags = 0; + size_t ocount; + size_t count; + cpu_type_t cpu_types[1]; + short flags = 0; #ifdef __LP64__ - int ch; + int ch; #endif - if ((errno = posix_spawnattr_init(spawnattr)) != 0) { - err(2, "posix_spawnattr_int"); - /* NOTREACHTED */ - } - - count = 1; - - /* Run the real python executable using the same architure as this - * executable, this allows users to controle the architecture using - * "arch -ppc python" - */ + if ((errno = posix_spawnattr_init(spawnattr)) != 0) { + err(2, "posix_spawnattr_int"); + /* NOTREACHTED */ + } + + count = 1; + + /* Run the real python executable using the same architure as this + * executable, this allows users to controle the architecture using + * "arch -ppc python" + */ #if defined(__ppc64__) - cpu_types[0] = CPU_TYPE_POWERPC64; + cpu_types[0] = CPU_TYPE_POWERPC64; #elif defined(__x86_64__) - cpu_types[0] = CPU_TYPE_X86_64; + cpu_types[0] = CPU_TYPE_X86_64; #elif defined(__ppc__) - cpu_types[0] = CPU_TYPE_POWERPC; + cpu_types[0] = CPU_TYPE_POWERPC; #elif defined(__i386__) - cpu_types[0] = CPU_TYPE_X86; + cpu_types[0] = CPU_TYPE_X86; #else -# error "Unknown CPU" +# error "Unknown CPU" #endif - if (posix_spawnattr_setbinpref_np(spawnattr, count, - cpu_types, &ocount) == -1) { - err(1, "posix_spawnattr_setbinpref"); - /* NOTREACHTED */ - } - if (count != ocount) { - fprintf(stderr, "posix_spawnattr_setbinpref failed to copy\n"); - exit(1); - /* NOTREACHTED */ - } - - - /* - * Set flag that causes posix_spawn to behave like execv - */ - flags |= POSIX_SPAWN_SETEXEC; - if ((errno = posix_spawnattr_setflags(spawnattr, flags)) != 0) { - err(1, "posix_spawnattr_setflags"); - /* NOTREACHTED */ - } + if (posix_spawnattr_setbinpref_np(spawnattr, count, + cpu_types, &ocount) == -1) { + err(1, "posix_spawnattr_setbinpref"); + /* NOTREACHTED */ + } + if (count != ocount) { + fprintf(stderr, "posix_spawnattr_setbinpref failed to copy\n"); + exit(1); + /* NOTREACHTED */ + } + + + /* + * Set flag that causes posix_spawn to behave like execv + */ + flags |= POSIX_SPAWN_SETEXEC; + if ((errno = posix_spawnattr_setflags(spawnattr, flags)) != 0) { + err(1, "posix_spawnattr_setflags"); + /* NOTREACHTED */ + } } #endif -int +int main(int argc, char **argv) { - char* exec_path = get_python_path(); + char* exec_path = get_python_path(); #ifdef HAVE_SPAWN_H - /* We're weak-linking to posix-spawnv to ensure that - * an executable build on 10.5 can work on 10.4. - */ - if (posix_spawn != NULL) { - posix_spawnattr_t spawnattr = NULL; - - setup_spawnattr(&spawnattr); - posix_spawn(NULL, exec_path, NULL, - &spawnattr, argv, environ); - err(1, "posix_spawn: %s", exec_path); - } + /* We're weak-linking to posix-spawnv to ensure that + * an executable build on 10.5 can work on 10.4. + */ + if (posix_spawn != NULL) { + posix_spawnattr_t spawnattr = NULL; + + setup_spawnattr(&spawnattr); + posix_spawn(NULL, exec_path, NULL, + &spawnattr, argv, environ); + err(1, "posix_spawn: %s", exec_path); + } #endif - execve(exec_path, argv, environ); - err(1, "execve: %s", argv[0]); - /* NOTREACHED */ + execve(exec_path, argv, environ); + err(1, "execve: %s", argv[0]); + /* NOTREACHED */ } Modified: python/branches/py3k-jit/Misc/setuid-prog.c ============================================================================== --- python/branches/py3k-jit/Misc/setuid-prog.c (original) +++ python/branches/py3k-jit/Misc/setuid-prog.c Mon May 10 23:55:43 2010 @@ -21,28 +21,28 @@ Assuming the script is a Bourne shell script, the first line of the script should be - #!/bin/sh - + #!/bin/sh - The - is important, don't omit it. If you're using esh, the first line should be - #!/usr/local/bin/esh -f + #!/usr/local/bin/esh -f and for ksh, the first line should be - #!/usr/local/bin/ksh -p + #!/usr/local/bin/ksh -p The script should then set the variable IFS to the string consisting of , , and . After this (*not* before!), the PATH variable should be set to a reasonable value and exported. Do not expect the PATH to have a reasonable value, so do not trust the old value of PATH. You should then set the umask of the program by calling - umask 077 # or 022 if you want the files to be readable + umask 077 # or 022 if you want the files to be readable If you plan to change directories, you should either unset CDPATH or set it to a good value. Setting CDPATH to just ``.'' (dot) is a good idea. If, for some reason, you want to use csh, the first line should be - #!/bin/csh -fb + #!/bin/csh -fb You should then set the path variable to something reasonable, without trusting the inherited path. Here too, you should set the umask using the command - umask 077 # or 022 if you want the files to be readable + umask 077 # or 022 if you want the files to be readable */ #include @@ -54,14 +54,14 @@ /* CONFIGURATION SECTION */ -#ifndef FULL_PATH /* so that this can be specified from the Makefile */ +#ifndef FULL_PATH /* so that this can be specified from the Makefile */ /* Uncomment the following line: -#define FULL_PATH "/full/path/of/script" +#define FULL_PATH "/full/path/of/script" * Then comment out the #error line. */ #error "You must define FULL_PATH somewhere" #endif #ifndef UMASK -#define UMASK 077 +#define UMASK 077 #endif /* END OF CONFIGURATION SECTION */ @@ -101,76 +101,76 @@ void clean_environ(void) { - char **p; - extern char **environ; + char **p; + extern char **environ; - for (p = environ; *p; p++) { - if (strncmp(*p, "LD_", 3) == 0) - **p = 'X'; - else if (strncmp(*p, "_RLD", 4) == 0) - **p = 'X'; - else if (strncmp(*p, "PYTHON", 6) == 0) - **p = 'X'; - else if (strncmp(*p, "IFS=", 4) == 0) - *p = def_IFS; - else if (strncmp(*p, "CDPATH=", 7) == 0) - *p = def_CDPATH; - else if (strncmp(*p, "ENV=", 4) == 0) - *p = def_ENV; - } - putenv(def_PATH); + for (p = environ; *p; p++) { + if (strncmp(*p, "LD_", 3) == 0) + **p = 'X'; + else if (strncmp(*p, "_RLD", 4) == 0) + **p = 'X'; + else if (strncmp(*p, "PYTHON", 6) == 0) + **p = 'X'; + else if (strncmp(*p, "IFS=", 4) == 0) + *p = def_IFS; + else if (strncmp(*p, "CDPATH=", 7) == 0) + *p = def_CDPATH; + else if (strncmp(*p, "ENV=", 4) == 0) + *p = def_ENV; + } + putenv(def_PATH); } int main(int argc, char **argv) { - struct stat statb; - gid_t egid = getegid(); - uid_t euid = geteuid(); - - /* - Sanity check #1. - This check should be made compile-time, but that's not possible. - If you're sure that you specified a full path name for FULL_PATH, - you can omit this check. - */ - if (FULL_PATH[0] != '/') { - fprintf(stderr, "%s: %s is not a full path name\n", argv[0], - FULL_PATH); - fprintf(stderr, "You can only use this wrapper if you\n"); - fprintf(stderr, "compile it with an absolute path.\n"); - exit(1); - } - - /* - Sanity check #2. - Check that the owner of the script is equal to either the - effective uid or the super user. - */ - if (stat(FULL_PATH, &statb) < 0) { - perror("stat"); - exit(1); - } - if (statb.st_uid != 0 && statb.st_uid != euid) { - fprintf(stderr, "%s: %s has the wrong owner\n", argv[0], - FULL_PATH); - fprintf(stderr, "The script should be owned by root,\n"); - fprintf(stderr, "and shouldn't be writable by anyone.\n"); - exit(1); - } - - if (setregid(egid, egid) < 0) - perror("setregid"); - if (setreuid(euid, euid) < 0) - perror("setreuid"); - - clean_environ(); - - umask(UMASK); - - while (**argv == '-') /* don't let argv[0] start with '-' */ - (*argv)++; - execv(FULL_PATH, argv); - fprintf(stderr, "%s: could not execute the script\n", argv[0]); - exit(1); + struct stat statb; + gid_t egid = getegid(); + uid_t euid = geteuid(); + + /* + Sanity check #1. + This check should be made compile-time, but that's not possible. + If you're sure that you specified a full path name for FULL_PATH, + you can omit this check. + */ + if (FULL_PATH[0] != '/') { + fprintf(stderr, "%s: %s is not a full path name\n", argv[0], + FULL_PATH); + fprintf(stderr, "You can only use this wrapper if you\n"); + fprintf(stderr, "compile it with an absolute path.\n"); + exit(1); + } + + /* + Sanity check #2. + Check that the owner of the script is equal to either the + effective uid or the super user. + */ + if (stat(FULL_PATH, &statb) < 0) { + perror("stat"); + exit(1); + } + if (statb.st_uid != 0 && statb.st_uid != euid) { + fprintf(stderr, "%s: %s has the wrong owner\n", argv[0], + FULL_PATH); + fprintf(stderr, "The script should be owned by root,\n"); + fprintf(stderr, "and shouldn't be writable by anyone.\n"); + exit(1); + } + + if (setregid(egid, egid) < 0) + perror("setregid"); + if (setreuid(euid, euid) < 0) + perror("setreuid"); + + clean_environ(); + + umask(UMASK); + + while (**argv == '-') /* don't let argv[0] start with '-' */ + (*argv)++; + execv(FULL_PATH, argv); + fprintf(stderr, "%s: could not execute the script\n", argv[0]); + exit(1); } Modified: python/branches/py3k-jit/Modules/_bisectmodule.c ============================================================================== --- python/branches/py3k-jit/Modules/_bisectmodule.c (original) +++ python/branches/py3k-jit/Modules/_bisectmodule.c Mon May 10 23:55:43 2010 @@ -8,51 +8,51 @@ static Py_ssize_t internal_bisect_right(PyObject *list, PyObject *item, Py_ssize_t lo, Py_ssize_t hi) { - PyObject *litem; - Py_ssize_t mid, res; + PyObject *litem; + Py_ssize_t mid, res; - if (lo < 0) { - PyErr_SetString(PyExc_ValueError, "lo must be non-negative"); - return -1; - } - if (hi == -1) { - hi = PySequence_Size(list); - if (hi < 0) - return -1; - } - while (lo < hi) { - mid = (lo + hi) / 2; - litem = PySequence_GetItem(list, mid); - if (litem == NULL) - return -1; - res = PyObject_RichCompareBool(item, litem, Py_LT); - Py_DECREF(litem); - if (res < 0) - return -1; - if (res) - hi = mid; - else - lo = mid + 1; - } - return lo; + if (lo < 0) { + PyErr_SetString(PyExc_ValueError, "lo must be non-negative"); + return -1; + } + if (hi == -1) { + hi = PySequence_Size(list); + if (hi < 0) + return -1; + } + while (lo < hi) { + mid = (lo + hi) / 2; + litem = PySequence_GetItem(list, mid); + if (litem == NULL) + return -1; + res = PyObject_RichCompareBool(item, litem, Py_LT); + Py_DECREF(litem); + if (res < 0) + return -1; + if (res) + hi = mid; + else + lo = mid + 1; + } + return lo; } static PyObject * bisect_right(PyObject *self, PyObject *args, PyObject *kw) { - PyObject *list, *item; - Py_ssize_t lo = 0; - Py_ssize_t hi = -1; - Py_ssize_t index; - static char *keywords[] = {"a", "x", "lo", "hi", NULL}; - - if (!PyArg_ParseTupleAndKeywords(args, kw, "OO|nn:bisect_right", - keywords, &list, &item, &lo, &hi)) - return NULL; - index = internal_bisect_right(list, item, lo, hi); - if (index < 0) - return NULL; - return PyLong_FromSsize_t(index); + PyObject *list, *item; + Py_ssize_t lo = 0; + Py_ssize_t hi = -1; + Py_ssize_t index; + static char *keywords[] = {"a", "x", "lo", "hi", NULL}; + + if (!PyArg_ParseTupleAndKeywords(args, kw, "OO|nn:bisect_right", + keywords, &list, &item, &lo, &hi)) + return NULL; + index = internal_bisect_right(list, item, lo, hi); + if (index < 0) + return NULL; + return PyLong_FromSsize_t(index); } PyDoc_STRVAR(bisect_right_doc, @@ -70,30 +70,30 @@ static PyObject * insort_right(PyObject *self, PyObject *args, PyObject *kw) { - PyObject *list, *item, *result; - Py_ssize_t lo = 0; - Py_ssize_t hi = -1; - Py_ssize_t index; - static char *keywords[] = {"a", "x", "lo", "hi", NULL}; - - if (!PyArg_ParseTupleAndKeywords(args, kw, "OO|nn:insort_right", - keywords, &list, &item, &lo, &hi)) - return NULL; - index = internal_bisect_right(list, item, lo, hi); - if (index < 0) - return NULL; - if (PyList_CheckExact(list)) { - if (PyList_Insert(list, index, item) < 0) - return NULL; - } else { - result = PyObject_CallMethod(list, "insert", "nO", - index, item); - if (result == NULL) - return NULL; - Py_DECREF(result); - } + PyObject *list, *item, *result; + Py_ssize_t lo = 0; + Py_ssize_t hi = -1; + Py_ssize_t index; + static char *keywords[] = {"a", "x", "lo", "hi", NULL}; + + if (!PyArg_ParseTupleAndKeywords(args, kw, "OO|nn:insort_right", + keywords, &list, &item, &lo, &hi)) + return NULL; + index = internal_bisect_right(list, item, lo, hi); + if (index < 0) + return NULL; + if (PyList_CheckExact(list)) { + if (PyList_Insert(list, index, item) < 0) + return NULL; + } else { + result = PyObject_CallMethod(list, "insert", "nO", + index, item); + if (result == NULL) + return NULL; + Py_DECREF(result); + } - Py_RETURN_NONE; + Py_RETURN_NONE; } PyDoc_STRVAR(insort_right_doc, @@ -109,51 +109,51 @@ static Py_ssize_t internal_bisect_left(PyObject *list, PyObject *item, Py_ssize_t lo, Py_ssize_t hi) { - PyObject *litem; - Py_ssize_t mid, res; + PyObject *litem; + Py_ssize_t mid, res; - if (lo < 0) { - PyErr_SetString(PyExc_ValueError, "lo must be non-negative"); - return -1; - } - if (hi == -1) { - hi = PySequence_Size(list); - if (hi < 0) - return -1; - } - while (lo < hi) { - mid = (lo + hi) / 2; - litem = PySequence_GetItem(list, mid); - if (litem == NULL) - return -1; - res = PyObject_RichCompareBool(litem, item, Py_LT); - Py_DECREF(litem); - if (res < 0) - return -1; - if (res) - lo = mid + 1; - else - hi = mid; - } - return lo; + if (lo < 0) { + PyErr_SetString(PyExc_ValueError, "lo must be non-negative"); + return -1; + } + if (hi == -1) { + hi = PySequence_Size(list); + if (hi < 0) + return -1; + } + while (lo < hi) { + mid = (lo + hi) / 2; + litem = PySequence_GetItem(list, mid); + if (litem == NULL) + return -1; + res = PyObject_RichCompareBool(litem, item, Py_LT); + Py_DECREF(litem); + if (res < 0) + return -1; + if (res) + lo = mid + 1; + else + hi = mid; + } + return lo; } static PyObject * bisect_left(PyObject *self, PyObject *args, PyObject *kw) { - PyObject *list, *item; - Py_ssize_t lo = 0; - Py_ssize_t hi = -1; - Py_ssize_t index; - static char *keywords[] = {"a", "x", "lo", "hi", NULL}; - - if (!PyArg_ParseTupleAndKeywords(args, kw, "OO|nn:bisect_left", - keywords, &list, &item, &lo, &hi)) - return NULL; - index = internal_bisect_left(list, item, lo, hi); - if (index < 0) - return NULL; - return PyLong_FromSsize_t(index); + PyObject *list, *item; + Py_ssize_t lo = 0; + Py_ssize_t hi = -1; + Py_ssize_t index; + static char *keywords[] = {"a", "x", "lo", "hi", NULL}; + + if (!PyArg_ParseTupleAndKeywords(args, kw, "OO|nn:bisect_left", + keywords, &list, &item, &lo, &hi)) + return NULL; + index = internal_bisect_left(list, item, lo, hi); + if (index < 0) + return NULL; + return PyLong_FromSsize_t(index); } PyDoc_STRVAR(bisect_left_doc, @@ -171,30 +171,30 @@ static PyObject * insort_left(PyObject *self, PyObject *args, PyObject *kw) { - PyObject *list, *item, *result; - Py_ssize_t lo = 0; - Py_ssize_t hi = -1; - Py_ssize_t index; - static char *keywords[] = {"a", "x", "lo", "hi", NULL}; - - if (!PyArg_ParseTupleAndKeywords(args, kw, "OO|nn:insort_left", - keywords, &list, &item, &lo, &hi)) - return NULL; - index = internal_bisect_left(list, item, lo, hi); - if (index < 0) - return NULL; - if (PyList_CheckExact(list)) { - if (PyList_Insert(list, index, item) < 0) - return NULL; - } else { - result = PyObject_CallMethod(list, "insert", "iO", - index, item); - if (result == NULL) - return NULL; - Py_DECREF(result); - } + PyObject *list, *item, *result; + Py_ssize_t lo = 0; + Py_ssize_t hi = -1; + Py_ssize_t index; + static char *keywords[] = {"a", "x", "lo", "hi", NULL}; + + if (!PyArg_ParseTupleAndKeywords(args, kw, "OO|nn:insort_left", + keywords, &list, &item, &lo, &hi)) + return NULL; + index = internal_bisect_left(list, item, lo, hi); + if (index < 0) + return NULL; + if (PyList_CheckExact(list)) { + if (PyList_Insert(list, index, item) < 0) + return NULL; + } else { + result = PyObject_CallMethod(list, "insert", "iO", + index, item); + if (result == NULL) + return NULL; + Py_DECREF(result); + } - Py_RETURN_NONE; + Py_RETURN_NONE; } PyDoc_STRVAR(insort_left_doc, @@ -211,19 +211,19 @@ PyDoc_STRVAR(insort_doc, "Alias for insort_right().\n"); static PyMethodDef bisect_methods[] = { - {"bisect_right", (PyCFunction)bisect_right, - METH_VARARGS|METH_KEYWORDS, bisect_right_doc}, - {"bisect", (PyCFunction)bisect_right, - METH_VARARGS|METH_KEYWORDS, bisect_doc}, - {"insort_right", (PyCFunction)insort_right, - METH_VARARGS|METH_KEYWORDS, insort_right_doc}, - {"insort", (PyCFunction)insort_right, - METH_VARARGS|METH_KEYWORDS, insort_doc}, - {"bisect_left", (PyCFunction)bisect_left, - METH_VARARGS|METH_KEYWORDS, bisect_left_doc}, - {"insort_left", (PyCFunction)insort_left, - METH_VARARGS|METH_KEYWORDS, insort_left_doc}, - {NULL, NULL} /* sentinel */ + {"bisect_right", (PyCFunction)bisect_right, + METH_VARARGS|METH_KEYWORDS, bisect_right_doc}, + {"bisect", (PyCFunction)bisect_right, + METH_VARARGS|METH_KEYWORDS, bisect_doc}, + {"insort_right", (PyCFunction)insort_right, + METH_VARARGS|METH_KEYWORDS, insort_right_doc}, + {"insort", (PyCFunction)insort_right, + METH_VARARGS|METH_KEYWORDS, insort_doc}, + {"bisect_left", (PyCFunction)bisect_left, + METH_VARARGS|METH_KEYWORDS, bisect_left_doc}, + {"insort_left", (PyCFunction)insort_left, + METH_VARARGS|METH_KEYWORDS, insort_left_doc}, + {NULL, NULL} /* sentinel */ }; PyDoc_STRVAR(module_doc, @@ -236,19 +236,19 @@ static struct PyModuleDef _bisectmodule = { - PyModuleDef_HEAD_INIT, - "_bisect", - module_doc, - -1, - bisect_methods, - NULL, - NULL, - NULL, - NULL + PyModuleDef_HEAD_INIT, + "_bisect", + module_doc, + -1, + bisect_methods, + NULL, + NULL, + NULL, + NULL }; PyMODINIT_FUNC PyInit__bisect(void) { - return PyModule_Create(&_bisectmodule); + return PyModule_Create(&_bisectmodule); } Modified: python/branches/py3k-jit/Modules/_codecsmodule.c ============================================================================== --- python/branches/py3k-jit/Modules/_codecsmodule.c (original) +++ python/branches/py3k-jit/Modules/_codecsmodule.c Mon May 10 23:55:43 2010 @@ -15,7 +15,7 @@ The builtin Unicode codecs use the following interface: _encode(Unicode_object[,errors='strict']) -> - (string object, bytes consumed) + (string object, bytes consumed) _decode(char_buffer_obj[,errors='strict']) -> (Unicode object, bytes consumed) @@ -95,7 +95,7 @@ return NULL; if (encoding == NULL) - encoding = PyUnicode_GetDefaultEncoding(); + encoding = PyUnicode_GetDefaultEncoding(); /* Encode via the codec registry */ return PyCodec_Encode(v, encoding, errors); @@ -122,7 +122,7 @@ return NULL; if (encoding == NULL) - encoding = PyUnicode_GetDefaultEncoding(); + encoding = PyUnicode_GetDefaultEncoding(); /* Decode via the codec registry */ return PyCodec_Decode(v, encoding, errors); @@ -132,7 +132,7 @@ static PyObject *codec_tuple(PyObject *unicode, - Py_ssize_t len) + Py_ssize_t len) { PyObject *v; if (unicode == NULL) @@ -145,86 +145,86 @@ /* --- String codecs ------------------------------------------------------ */ static PyObject * escape_decode(PyObject *self, - PyObject *args) + PyObject *args) { const char *errors = NULL; const char *data; Py_ssize_t size; if (!PyArg_ParseTuple(args, "s#|z:escape_decode", - &data, &size, &errors)) - return NULL; + &data, &size, &errors)) + return NULL; return codec_tuple(PyBytes_DecodeEscape(data, size, errors, 0, NULL), - size); + size); } static PyObject * escape_encode(PyObject *self, - PyObject *args) + PyObject *args) { - static const char *hexdigits = "0123456789abcdef"; - PyObject *str; - Py_ssize_t size; - Py_ssize_t newsize; - const char *errors = NULL; - PyObject *v; - - if (!PyArg_ParseTuple(args, "O!|z:escape_encode", - &PyBytes_Type, &str, &errors)) - return NULL; - - size = PyBytes_GET_SIZE(str); - newsize = 4*size; - if (newsize > PY_SSIZE_T_MAX || newsize / 4 != size) { - PyErr_SetString(PyExc_OverflowError, - "string is too large to encode"); - return NULL; - } - v = PyBytes_FromStringAndSize(NULL, newsize); - - if (v == NULL) { - return NULL; - } - else { - register Py_ssize_t i; - register char c; - register char *p = PyBytes_AS_STRING(v); - - for (i = 0; i < size; i++) { - /* There's at least enough room for a hex escape */ - assert(newsize - (p - PyBytes_AS_STRING(v)) >= 4); - c = PyBytes_AS_STRING(str)[i]; - if (c == '\'' || 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++ = hexdigits[(c & 0xf0) >> 4]; - *p++ = hexdigits[c & 0xf]; - } - else - *p++ = c; - } - *p = '\0'; - if (_PyBytes_Resize(&v, (p - PyBytes_AS_STRING(v)))) { - return NULL; - } - } - - return codec_tuple(v, size); + static const char *hexdigits = "0123456789abcdef"; + PyObject *str; + Py_ssize_t size; + Py_ssize_t newsize; + const char *errors = NULL; + PyObject *v; + + if (!PyArg_ParseTuple(args, "O!|z:escape_encode", + &PyBytes_Type, &str, &errors)) + return NULL; + + size = PyBytes_GET_SIZE(str); + newsize = 4*size; + if (newsize > PY_SSIZE_T_MAX || newsize / 4 != size) { + PyErr_SetString(PyExc_OverflowError, + "string is too large to encode"); + return NULL; + } + v = PyBytes_FromStringAndSize(NULL, newsize); + + if (v == NULL) { + return NULL; + } + else { + register Py_ssize_t i; + register char c; + register char *p = PyBytes_AS_STRING(v); + + for (i = 0; i < size; i++) { + /* There's at least enough room for a hex escape */ + assert(newsize - (p - PyBytes_AS_STRING(v)) >= 4); + c = PyBytes_AS_STRING(str)[i]; + if (c == '\'' || 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++ = hexdigits[(c & 0xf0) >> 4]; + *p++ = hexdigits[c & 0xf]; + } + else + *p++ = c; + } + *p = '\0'; + if (_PyBytes_Resize(&v, (p - PyBytes_AS_STRING(v)))) { + return NULL; + } + } + + return codec_tuple(v, size); } /* --- Decoder ------------------------------------------------------------ */ static PyObject * unicode_internal_decode(PyObject *self, - PyObject *args) + PyObject *args) { PyObject *obj; const char *errors = NULL; @@ -232,19 +232,19 @@ Py_ssize_t size; if (!PyArg_ParseTuple(args, "O|z:unicode_internal_decode", - &obj, &errors)) - return NULL; + &obj, &errors)) + return NULL; if (PyUnicode_Check(obj)) { - Py_INCREF(obj); - return codec_tuple(obj, PyUnicode_GET_SIZE(obj)); + Py_INCREF(obj); + return codec_tuple(obj, PyUnicode_GET_SIZE(obj)); } else { - if (PyObject_AsReadBuffer(obj, (const void **)&data, &size)) - return NULL; + if (PyObject_AsReadBuffer(obj, (const void **)&data, &size)) + return NULL; - return codec_tuple(_PyUnicode_DecodeUnicodeInternal(data, size, errors), - size); + return codec_tuple(_PyUnicode_DecodeUnicodeInternal(data, size, errors), + size); } } @@ -252,20 +252,20 @@ utf_7_decode(PyObject *self, PyObject *args) { - Py_buffer pbuf; + Py_buffer pbuf; const char *errors = NULL; int final = 0; Py_ssize_t consumed; PyObject *decoded = NULL; if (!PyArg_ParseTuple(args, "y*|zi:utf_7_decode", - &pbuf, &errors, &final)) - return NULL; + &pbuf, &errors, &final)) + return NULL; consumed = pbuf.len; decoded = PyUnicode_DecodeUTF7Stateful(pbuf.buf, pbuf.len, errors, - final ? NULL : &consumed); - PyBuffer_Release(&pbuf); + final ? NULL : &consumed); + PyBuffer_Release(&pbuf); if (decoded == NULL) return NULL; return codec_tuple(decoded, consumed); @@ -273,32 +273,32 @@ static PyObject * utf_8_decode(PyObject *self, - PyObject *args) + PyObject *args) { - Py_buffer pbuf; + Py_buffer pbuf; const char *errors = NULL; int final = 0; Py_ssize_t consumed; PyObject *decoded = NULL; if (!PyArg_ParseTuple(args, "y*|zi:utf_8_decode", - &pbuf, &errors, &final)) - return NULL; + &pbuf, &errors, &final)) + return NULL; consumed = pbuf.len; decoded = PyUnicode_DecodeUTF8Stateful(pbuf.buf, pbuf.len, errors, - final ? NULL : &consumed); - PyBuffer_Release(&pbuf); + final ? NULL : &consumed); + PyBuffer_Release(&pbuf); if (decoded == NULL) - return NULL; + return NULL; return codec_tuple(decoded, consumed); } static PyObject * utf_16_decode(PyObject *self, - PyObject *args) + PyObject *args) { - Py_buffer pbuf; + Py_buffer pbuf; const char *errors = NULL; int byteorder = 0; int final = 0; @@ -306,22 +306,22 @@ PyObject *decoded; if (!PyArg_ParseTuple(args, "y*|zi:utf_16_decode", - &pbuf, &errors, &final)) - return NULL; + &pbuf, &errors, &final)) + return NULL; consumed = pbuf.len; /* This is overwritten unless final is true. */ decoded = PyUnicode_DecodeUTF16Stateful(pbuf.buf, pbuf.len, errors, - &byteorder, final ? NULL : &consumed); - PyBuffer_Release(&pbuf); + &byteorder, final ? NULL : &consumed); + PyBuffer_Release(&pbuf); if (decoded == NULL) - return NULL; + return NULL; return codec_tuple(decoded, consumed); } static PyObject * utf_16_le_decode(PyObject *self, - PyObject *args) + PyObject *args) { - Py_buffer pbuf; + Py_buffer pbuf; const char *errors = NULL; int byteorder = -1; int final = 0; @@ -329,23 +329,23 @@ PyObject *decoded = NULL; if (!PyArg_ParseTuple(args, "y*|zi:utf_16_le_decode", - &pbuf, &errors, &final)) - return NULL; + &pbuf, &errors, &final)) + return NULL; consumed = pbuf.len; /* This is overwritten unless final is true. */ decoded = PyUnicode_DecodeUTF16Stateful(pbuf.buf, pbuf.len, errors, - &byteorder, final ? NULL : &consumed); - PyBuffer_Release(&pbuf); + &byteorder, final ? NULL : &consumed); + PyBuffer_Release(&pbuf); if (decoded == NULL) - return NULL; + return NULL; return codec_tuple(decoded, consumed); } static PyObject * utf_16_be_decode(PyObject *self, - PyObject *args) + PyObject *args) { - Py_buffer pbuf; + Py_buffer pbuf; const char *errors = NULL; int byteorder = 1; int final = 0; @@ -353,15 +353,15 @@ PyObject *decoded = NULL; if (!PyArg_ParseTuple(args, "y*|zi:utf_16_be_decode", - &pbuf, &errors, &final)) - return NULL; + &pbuf, &errors, &final)) + return NULL; consumed = pbuf.len; /* This is overwritten unless final is true. */ decoded = PyUnicode_DecodeUTF16Stateful(pbuf.buf, pbuf.len, errors, - &byteorder, final ? NULL : &consumed); - PyBuffer_Release(&pbuf); + &byteorder, final ? NULL : &consumed); + PyBuffer_Release(&pbuf); if (decoded == NULL) - return NULL; + return NULL; return codec_tuple(decoded, consumed); } @@ -375,9 +375,9 @@ static PyObject * utf_16_ex_decode(PyObject *self, - PyObject *args) + PyObject *args) { - Py_buffer pbuf; + Py_buffer pbuf; const char *errors = NULL; int byteorder = 0; PyObject *unicode, *tuple; @@ -385,14 +385,14 @@ Py_ssize_t consumed; if (!PyArg_ParseTuple(args, "y*|zii:utf_16_ex_decode", - &pbuf, &errors, &byteorder, &final)) - return NULL; + &pbuf, &errors, &byteorder, &final)) + return NULL; consumed = pbuf.len; /* This is overwritten unless final is true. */ unicode = PyUnicode_DecodeUTF16Stateful(pbuf.buf, pbuf.len, errors, - &byteorder, final ? NULL : &consumed); - PyBuffer_Release(&pbuf); + &byteorder, final ? NULL : &consumed); + PyBuffer_Release(&pbuf); if (unicode == NULL) - return NULL; + return NULL; tuple = Py_BuildValue("Oni", unicode, consumed, byteorder); Py_DECREF(unicode); return tuple; @@ -400,9 +400,9 @@ static PyObject * utf_32_decode(PyObject *self, - PyObject *args) + PyObject *args) { - Py_buffer pbuf; + Py_buffer pbuf; const char *errors = NULL; int byteorder = 0; int final = 0; @@ -410,22 +410,22 @@ PyObject *decoded; if (!PyArg_ParseTuple(args, "y*|zi:utf_32_decode", - &pbuf, &errors, &final)) - return NULL; + &pbuf, &errors, &final)) + return NULL; consumed = pbuf.len; /* This is overwritten unless final is true. */ decoded = PyUnicode_DecodeUTF32Stateful(pbuf.buf, pbuf.len, errors, - &byteorder, final ? NULL : &consumed); - PyBuffer_Release(&pbuf); + &byteorder, final ? NULL : &consumed); + PyBuffer_Release(&pbuf); if (decoded == NULL) - return NULL; + return NULL; return codec_tuple(decoded, consumed); } static PyObject * utf_32_le_decode(PyObject *self, - PyObject *args) + PyObject *args) { - Py_buffer pbuf; + Py_buffer pbuf; const char *errors = NULL; int byteorder = -1; int final = 0; @@ -433,22 +433,22 @@ PyObject *decoded; if (!PyArg_ParseTuple(args, "y*|zi:utf_32_le_decode", - &pbuf, &errors, &final)) - return NULL; + &pbuf, &errors, &final)) + return NULL; consumed = pbuf.len; /* This is overwritten unless final is true. */ decoded = PyUnicode_DecodeUTF32Stateful(pbuf.buf, pbuf.len, errors, - &byteorder, final ? NULL : &consumed); - PyBuffer_Release(&pbuf); + &byteorder, final ? NULL : &consumed); + PyBuffer_Release(&pbuf); if (decoded == NULL) - return NULL; + return NULL; return codec_tuple(decoded, consumed); } static PyObject * utf_32_be_decode(PyObject *self, - PyObject *args) + PyObject *args) { - Py_buffer pbuf; + Py_buffer pbuf; const char *errors = NULL; int byteorder = 1; int final = 0; @@ -456,14 +456,14 @@ PyObject *decoded; if (!PyArg_ParseTuple(args, "y*|zi:utf_32_be_decode", - &pbuf, &errors, &final)) - return NULL; + &pbuf, &errors, &final)) + return NULL; consumed = pbuf.len; /* This is overwritten unless final is true. */ decoded = PyUnicode_DecodeUTF32Stateful(pbuf.buf, pbuf.len, errors, - &byteorder, final ? NULL : &consumed); - PyBuffer_Release(&pbuf); + &byteorder, final ? NULL : &consumed); + PyBuffer_Release(&pbuf); if (decoded == NULL) - return NULL; + return NULL; return codec_tuple(decoded, consumed); } @@ -477,9 +477,9 @@ static PyObject * utf_32_ex_decode(PyObject *self, - PyObject *args) + PyObject *args) { - Py_buffer pbuf; + Py_buffer pbuf; const char *errors = NULL; int byteorder = 0; PyObject *unicode, *tuple; @@ -487,14 +487,14 @@ Py_ssize_t consumed; if (!PyArg_ParseTuple(args, "y*|zii:utf_32_ex_decode", - &pbuf, &errors, &byteorder, &final)) - return NULL; + &pbuf, &errors, &byteorder, &final)) + return NULL; consumed = pbuf.len; /* This is overwritten unless final is true. */ unicode = PyUnicode_DecodeUTF32Stateful(pbuf.buf, pbuf.len, errors, - &byteorder, final ? NULL : &consumed); - PyBuffer_Release(&pbuf); + &byteorder, final ? NULL : &consumed); + PyBuffer_Release(&pbuf); if (unicode == NULL) - return NULL; + return NULL; tuple = Py_BuildValue("Oni", unicode, consumed, byteorder); Py_DECREF(unicode); return tuple; @@ -502,114 +502,114 @@ static PyObject * unicode_escape_decode(PyObject *self, - PyObject *args) + PyObject *args) { - Py_buffer pbuf; + Py_buffer pbuf; const char *errors = NULL; - PyObject *unicode; + PyObject *unicode; if (!PyArg_ParseTuple(args, "s*|z:unicode_escape_decode", - &pbuf, &errors)) - return NULL; + &pbuf, &errors)) + return NULL; - unicode = PyUnicode_DecodeUnicodeEscape(pbuf.buf, pbuf.len, errors); - PyBuffer_Release(&pbuf); - return codec_tuple(unicode, pbuf.len); + unicode = PyUnicode_DecodeUnicodeEscape(pbuf.buf, pbuf.len, errors); + PyBuffer_Release(&pbuf); + return codec_tuple(unicode, pbuf.len); } static PyObject * raw_unicode_escape_decode(PyObject *self, - PyObject *args) + PyObject *args) { - Py_buffer pbuf; + Py_buffer pbuf; const char *errors = NULL; - PyObject *unicode; + PyObject *unicode; if (!PyArg_ParseTuple(args, "s*|z:raw_unicode_escape_decode", - &pbuf, &errors)) - return NULL; + &pbuf, &errors)) + return NULL; - unicode = PyUnicode_DecodeRawUnicodeEscape(pbuf.buf, pbuf.len, errors); - PyBuffer_Release(&pbuf); - return codec_tuple(unicode, pbuf.len); + unicode = PyUnicode_DecodeRawUnicodeEscape(pbuf.buf, pbuf.len, errors); + PyBuffer_Release(&pbuf); + return codec_tuple(unicode, pbuf.len); } static PyObject * latin_1_decode(PyObject *self, - PyObject *args) + PyObject *args) { - Py_buffer pbuf; - PyObject *unicode; + Py_buffer pbuf; + PyObject *unicode; const char *errors = NULL; if (!PyArg_ParseTuple(args, "y*|z:latin_1_decode", - &pbuf, &errors)) - return NULL; + &pbuf, &errors)) + return NULL; - unicode = PyUnicode_DecodeLatin1(pbuf.buf, pbuf.len, errors); - PyBuffer_Release(&pbuf); - return codec_tuple(unicode, pbuf.len); + unicode = PyUnicode_DecodeLatin1(pbuf.buf, pbuf.len, errors); + PyBuffer_Release(&pbuf); + return codec_tuple(unicode, pbuf.len); } static PyObject * ascii_decode(PyObject *self, - PyObject *args) + PyObject *args) { - Py_buffer pbuf; - PyObject *unicode; + Py_buffer pbuf; + PyObject *unicode; const char *errors = NULL; if (!PyArg_ParseTuple(args, "y*|z:ascii_decode", - &pbuf, &errors)) - return NULL; + &pbuf, &errors)) + return NULL; - unicode = PyUnicode_DecodeASCII(pbuf.buf, pbuf.len, errors); - PyBuffer_Release(&pbuf); - return codec_tuple(unicode, pbuf.len); + unicode = PyUnicode_DecodeASCII(pbuf.buf, pbuf.len, errors); + PyBuffer_Release(&pbuf); + return codec_tuple(unicode, pbuf.len); } static PyObject * charmap_decode(PyObject *self, - PyObject *args) + PyObject *args) { - Py_buffer pbuf; - PyObject *unicode; + Py_buffer pbuf; + PyObject *unicode; const char *errors = NULL; PyObject *mapping = NULL; if (!PyArg_ParseTuple(args, "y*|zO:charmap_decode", - &pbuf, &errors, &mapping)) - return NULL; + &pbuf, &errors, &mapping)) + return NULL; if (mapping == Py_None) - mapping = NULL; + mapping = NULL; - unicode = PyUnicode_DecodeCharmap(pbuf.buf, pbuf.len, mapping, errors); - PyBuffer_Release(&pbuf); - return codec_tuple(unicode, pbuf.len); + unicode = PyUnicode_DecodeCharmap(pbuf.buf, pbuf.len, mapping, errors); + PyBuffer_Release(&pbuf); + return codec_tuple(unicode, pbuf.len); } #if defined(MS_WINDOWS) && defined(HAVE_USABLE_WCHAR_T) static PyObject * mbcs_decode(PyObject *self, - PyObject *args) + PyObject *args) { - Py_buffer pbuf; + Py_buffer pbuf; const char *errors = NULL; int final = 0; Py_ssize_t consumed; PyObject *decoded = NULL; if (!PyArg_ParseTuple(args, "y*|zi:mbcs_decode", - &pbuf, &errors, &final)) - return NULL; + &pbuf, &errors, &final)) + return NULL; consumed = pbuf.len; decoded = PyUnicode_DecodeMBCSStateful(pbuf.buf, pbuf.len, errors, - final ? NULL : &consumed); - PyBuffer_Release(&pbuf); + final ? NULL : &consumed); + PyBuffer_Release(&pbuf); if (decoded == NULL) - return NULL; + return NULL; return codec_tuple(decoded, consumed); } @@ -619,7 +619,7 @@ static PyObject * readbuffer_encode(PyObject *self, - PyObject *args) + PyObject *args) { Py_buffer pdata; const char *data; @@ -628,8 +628,8 @@ PyObject *result; if (!PyArg_ParseTuple(args, "s*|z:readbuffer_encode", - &pdata, &errors)) - return NULL; + &pdata, &errors)) + return NULL; data = pdata.buf; size = pdata.len; @@ -640,22 +640,22 @@ static PyObject * charbuffer_encode(PyObject *self, - PyObject *args) + PyObject *args) { const char *data; Py_ssize_t size; const char *errors = NULL; if (!PyArg_ParseTuple(args, "t#|z:charbuffer_encode", - &data, &size, &errors)) - return NULL; + &data, &size, &errors)) + return NULL; return codec_tuple(PyBytes_FromStringAndSize(data, size), size); } static PyObject * unicode_internal_encode(PyObject *self, - PyObject *args) + PyObject *args) { PyObject *obj; const char *errors = NULL; @@ -663,64 +663,64 @@ Py_ssize_t size; if (!PyArg_ParseTuple(args, "O|z:unicode_internal_encode", - &obj, &errors)) - return NULL; + &obj, &errors)) + return NULL; if (PyUnicode_Check(obj)) { - data = PyUnicode_AS_DATA(obj); - size = PyUnicode_GET_DATA_SIZE(obj); - return codec_tuple(PyBytes_FromStringAndSize(data, size), - PyUnicode_GET_SIZE(obj)); + data = PyUnicode_AS_DATA(obj); + size = PyUnicode_GET_DATA_SIZE(obj); + return codec_tuple(PyBytes_FromStringAndSize(data, size), + PyUnicode_GET_SIZE(obj)); } else { - if (PyObject_AsReadBuffer(obj, (const void **)&data, &size)) - return NULL; - return codec_tuple(PyBytes_FromStringAndSize(data, size), size); + if (PyObject_AsReadBuffer(obj, (const void **)&data, &size)) + return NULL; + return codec_tuple(PyBytes_FromStringAndSize(data, size), size); } } static PyObject * utf_7_encode(PyObject *self, - PyObject *args) + PyObject *args) { PyObject *str, *v; const char *errors = NULL; if (!PyArg_ParseTuple(args, "O|z:utf_7_encode", - &str, &errors)) - return NULL; + &str, &errors)) + return NULL; str = PyUnicode_FromObject(str); if (str == NULL) - return NULL; + return NULL; v = codec_tuple(PyUnicode_EncodeUTF7(PyUnicode_AS_UNICODE(str), - PyUnicode_GET_SIZE(str), - 0, - 0, - errors), - PyUnicode_GET_SIZE(str)); + PyUnicode_GET_SIZE(str), + 0, + 0, + errors), + PyUnicode_GET_SIZE(str)); Py_DECREF(str); return v; } static PyObject * utf_8_encode(PyObject *self, - PyObject *args) + PyObject *args) { PyObject *str, *v; const char *errors = NULL; if (!PyArg_ParseTuple(args, "O|z:utf_8_encode", - &str, &errors)) - return NULL; + &str, &errors)) + return NULL; str = PyUnicode_FromObject(str); if (str == NULL) - return NULL; + return NULL; v = codec_tuple(PyUnicode_EncodeUTF8(PyUnicode_AS_UNICODE(str), - PyUnicode_GET_SIZE(str), - errors), - PyUnicode_GET_SIZE(str)); + PyUnicode_GET_SIZE(str), + errors), + PyUnicode_GET_SIZE(str)); Py_DECREF(str); return v; } @@ -734,70 +734,70 @@ static PyObject * utf_16_encode(PyObject *self, - PyObject *args) + PyObject *args) { PyObject *str, *v; const char *errors = NULL; int byteorder = 0; if (!PyArg_ParseTuple(args, "O|zi:utf_16_encode", - &str, &errors, &byteorder)) - return NULL; + &str, &errors, &byteorder)) + return NULL; str = PyUnicode_FromObject(str); if (str == NULL) - return NULL; + return NULL; v = codec_tuple(PyUnicode_EncodeUTF16(PyUnicode_AS_UNICODE(str), - PyUnicode_GET_SIZE(str), - errors, - byteorder), - PyUnicode_GET_SIZE(str)); + PyUnicode_GET_SIZE(str), + errors, + byteorder), + PyUnicode_GET_SIZE(str)); Py_DECREF(str); return v; } static PyObject * utf_16_le_encode(PyObject *self, - PyObject *args) + PyObject *args) { PyObject *str, *v; const char *errors = NULL; if (!PyArg_ParseTuple(args, "O|z:utf_16_le_encode", - &str, &errors)) - return NULL; + &str, &errors)) + return NULL; str = PyUnicode_FromObject(str); if (str == NULL) - return NULL; + return NULL; v = codec_tuple(PyUnicode_EncodeUTF16(PyUnicode_AS_UNICODE(str), - PyUnicode_GET_SIZE(str), - errors, - -1), - PyUnicode_GET_SIZE(str)); + PyUnicode_GET_SIZE(str), + errors, + -1), + PyUnicode_GET_SIZE(str)); Py_DECREF(str); return v; } static PyObject * utf_16_be_encode(PyObject *self, - PyObject *args) + PyObject *args) { PyObject *str, *v; const char *errors = NULL; if (!PyArg_ParseTuple(args, "O|z:utf_16_be_encode", - &str, &errors)) - return NULL; + &str, &errors)) + return NULL; str = PyUnicode_FromObject(str); if (str == NULL) - return NULL; + return NULL; v = codec_tuple(PyUnicode_EncodeUTF16(PyUnicode_AS_UNICODE(str), - PyUnicode_GET_SIZE(str), - errors, - +1), - PyUnicode_GET_SIZE(str)); + PyUnicode_GET_SIZE(str), + errors, + +1), + PyUnicode_GET_SIZE(str)); Py_DECREF(str); return v; } @@ -811,186 +811,186 @@ static PyObject * utf_32_encode(PyObject *self, - PyObject *args) + PyObject *args) { PyObject *str, *v; const char *errors = NULL; int byteorder = 0; if (!PyArg_ParseTuple(args, "O|zi:utf_32_encode", - &str, &errors, &byteorder)) - return NULL; + &str, &errors, &byteorder)) + return NULL; str = PyUnicode_FromObject(str); if (str == NULL) - return NULL; + return NULL; v = codec_tuple(PyUnicode_EncodeUTF32(PyUnicode_AS_UNICODE(str), - PyUnicode_GET_SIZE(str), - errors, - byteorder), - PyUnicode_GET_SIZE(str)); + PyUnicode_GET_SIZE(str), + errors, + byteorder), + PyUnicode_GET_SIZE(str)); Py_DECREF(str); return v; } static PyObject * utf_32_le_encode(PyObject *self, - PyObject *args) + PyObject *args) { PyObject *str, *v; const char *errors = NULL; if (!PyArg_ParseTuple(args, "O|z:utf_32_le_encode", - &str, &errors)) - return NULL; + &str, &errors)) + return NULL; str = PyUnicode_FromObject(str); if (str == NULL) - return NULL; + return NULL; v = codec_tuple(PyUnicode_EncodeUTF32(PyUnicode_AS_UNICODE(str), - PyUnicode_GET_SIZE(str), - errors, - -1), - PyUnicode_GET_SIZE(str)); + PyUnicode_GET_SIZE(str), + errors, + -1), + PyUnicode_GET_SIZE(str)); Py_DECREF(str); return v; } static PyObject * utf_32_be_encode(PyObject *self, - PyObject *args) + PyObject *args) { PyObject *str, *v; const char *errors = NULL; if (!PyArg_ParseTuple(args, "O|z:utf_32_be_encode", - &str, &errors)) - return NULL; + &str, &errors)) + return NULL; str = PyUnicode_FromObject(str); if (str == NULL) - return NULL; + return NULL; v = codec_tuple(PyUnicode_EncodeUTF32(PyUnicode_AS_UNICODE(str), - PyUnicode_GET_SIZE(str), - errors, - +1), - PyUnicode_GET_SIZE(str)); + PyUnicode_GET_SIZE(str), + errors, + +1), + PyUnicode_GET_SIZE(str)); Py_DECREF(str); return v; } static PyObject * unicode_escape_encode(PyObject *self, - PyObject *args) + PyObject *args) { PyObject *str, *v; const char *errors = NULL; if (!PyArg_ParseTuple(args, "O|z:unicode_escape_encode", - &str, &errors)) - return NULL; + &str, &errors)) + return NULL; str = PyUnicode_FromObject(str); if (str == NULL) - return NULL; + return NULL; v = codec_tuple(PyUnicode_EncodeUnicodeEscape(PyUnicode_AS_UNICODE(str), - PyUnicode_GET_SIZE(str)), - PyUnicode_GET_SIZE(str)); + PyUnicode_GET_SIZE(str)), + PyUnicode_GET_SIZE(str)); Py_DECREF(str); return v; } static PyObject * raw_unicode_escape_encode(PyObject *self, - PyObject *args) + PyObject *args) { PyObject *str, *v; const char *errors = NULL; if (!PyArg_ParseTuple(args, "O|z:raw_unicode_escape_encode", - &str, &errors)) - return NULL; + &str, &errors)) + return NULL; str = PyUnicode_FromObject(str); if (str == NULL) - return NULL; + return NULL; v = codec_tuple(PyUnicode_EncodeRawUnicodeEscape( - PyUnicode_AS_UNICODE(str), - PyUnicode_GET_SIZE(str)), - PyUnicode_GET_SIZE(str)); + PyUnicode_AS_UNICODE(str), + PyUnicode_GET_SIZE(str)), + PyUnicode_GET_SIZE(str)); Py_DECREF(str); return v; } static PyObject * latin_1_encode(PyObject *self, - PyObject *args) + PyObject *args) { PyObject *str, *v; const char *errors = NULL; if (!PyArg_ParseTuple(args, "O|z:latin_1_encode", - &str, &errors)) - return NULL; + &str, &errors)) + return NULL; str = PyUnicode_FromObject(str); if (str == NULL) - return NULL; + return NULL; v = codec_tuple(PyUnicode_EncodeLatin1( - PyUnicode_AS_UNICODE(str), - PyUnicode_GET_SIZE(str), - errors), - PyUnicode_GET_SIZE(str)); + PyUnicode_AS_UNICODE(str), + PyUnicode_GET_SIZE(str), + errors), + PyUnicode_GET_SIZE(str)); Py_DECREF(str); return v; } static PyObject * ascii_encode(PyObject *self, - PyObject *args) + PyObject *args) { PyObject *str, *v; const char *errors = NULL; if (!PyArg_ParseTuple(args, "O|z:ascii_encode", - &str, &errors)) - return NULL; + &str, &errors)) + return NULL; str = PyUnicode_FromObject(str); if (str == NULL) - return NULL; + return NULL; v = codec_tuple(PyUnicode_EncodeASCII( - PyUnicode_AS_UNICODE(str), - PyUnicode_GET_SIZE(str), - errors), - PyUnicode_GET_SIZE(str)); + PyUnicode_AS_UNICODE(str), + PyUnicode_GET_SIZE(str), + errors), + PyUnicode_GET_SIZE(str)); Py_DECREF(str); return v; } static PyObject * charmap_encode(PyObject *self, - PyObject *args) + PyObject *args) { PyObject *str, *v; const char *errors = NULL; PyObject *mapping = NULL; if (!PyArg_ParseTuple(args, "O|zO:charmap_encode", - &str, &errors, &mapping)) - return NULL; + &str, &errors, &mapping)) + return NULL; if (mapping == Py_None) - mapping = NULL; + mapping = NULL; str = PyUnicode_FromObject(str); if (str == NULL) - return NULL; + return NULL; v = codec_tuple(PyUnicode_EncodeCharmap( - PyUnicode_AS_UNICODE(str), - PyUnicode_GET_SIZE(str), - mapping, - errors), - PyUnicode_GET_SIZE(str)); + PyUnicode_AS_UNICODE(str), + PyUnicode_GET_SIZE(str), + mapping, + errors), + PyUnicode_GET_SIZE(str)); Py_DECREF(str); return v; } @@ -1008,23 +1008,23 @@ static PyObject * mbcs_encode(PyObject *self, - PyObject *args) + PyObject *args) { PyObject *str, *v; const char *errors = NULL; if (!PyArg_ParseTuple(args, "O|z:mbcs_encode", - &str, &errors)) - return NULL; + &str, &errors)) + return NULL; str = PyUnicode_FromObject(str); if (str == NULL) - return NULL; + return NULL; v = codec_tuple(PyUnicode_EncodeMBCS( - PyUnicode_AS_UNICODE(str), - PyUnicode_GET_SIZE(str), - errors), - PyUnicode_GET_SIZE(str)); + PyUnicode_AS_UNICODE(str), + PyUnicode_GET_SIZE(str), + errors), + PyUnicode_GET_SIZE(str)); Py_DECREF(str); return v; } @@ -1048,8 +1048,8 @@ PyObject *handler; if (!PyArg_ParseTuple(args, "sO:register_error", - &name, &handler)) - return NULL; + &name, &handler)) + return NULL; if (PyCodec_RegisterError(name, handler)) return NULL; Py_RETURN_NONE; @@ -1066,82 +1066,82 @@ const char *name; if (!PyArg_ParseTuple(args, "s:lookup_error", - &name)) - return NULL; + &name)) + return NULL; return PyCodec_LookupError(name); } /* --- Module API --------------------------------------------------------- */ static PyMethodDef _codecs_functions[] = { - {"register", codec_register, METH_O, + {"register", codec_register, METH_O, register__doc__}, - {"lookup", codec_lookup, METH_VARARGS, + {"lookup", codec_lookup, METH_VARARGS, lookup__doc__}, - {"encode", codec_encode, METH_VARARGS, - encode__doc__}, - {"decode", codec_decode, METH_VARARGS, - decode__doc__}, - {"escape_encode", escape_encode, METH_VARARGS}, - {"escape_decode", escape_decode, METH_VARARGS}, - {"utf_8_encode", utf_8_encode, METH_VARARGS}, - {"utf_8_decode", utf_8_decode, METH_VARARGS}, - {"utf_7_encode", utf_7_encode, METH_VARARGS}, - {"utf_7_decode", utf_7_decode, METH_VARARGS}, - {"utf_16_encode", utf_16_encode, METH_VARARGS}, - {"utf_16_le_encode", utf_16_le_encode, METH_VARARGS}, - {"utf_16_be_encode", utf_16_be_encode, METH_VARARGS}, - {"utf_16_decode", utf_16_decode, METH_VARARGS}, - {"utf_16_le_decode", utf_16_le_decode, METH_VARARGS}, - {"utf_16_be_decode", utf_16_be_decode, METH_VARARGS}, - {"utf_16_ex_decode", utf_16_ex_decode, METH_VARARGS}, - {"utf_32_encode", utf_32_encode, METH_VARARGS}, - {"utf_32_le_encode", utf_32_le_encode, METH_VARARGS}, - {"utf_32_be_encode", utf_32_be_encode, METH_VARARGS}, - {"utf_32_decode", utf_32_decode, METH_VARARGS}, - {"utf_32_le_decode", utf_32_le_decode, METH_VARARGS}, - {"utf_32_be_decode", utf_32_be_decode, METH_VARARGS}, - {"utf_32_ex_decode", utf_32_ex_decode, METH_VARARGS}, - {"unicode_escape_encode", unicode_escape_encode, METH_VARARGS}, - {"unicode_escape_decode", unicode_escape_decode, METH_VARARGS}, - {"unicode_internal_encode", unicode_internal_encode, METH_VARARGS}, - {"unicode_internal_decode", unicode_internal_decode, METH_VARARGS}, - {"raw_unicode_escape_encode", raw_unicode_escape_encode, METH_VARARGS}, - {"raw_unicode_escape_decode", raw_unicode_escape_decode, METH_VARARGS}, - {"latin_1_encode", latin_1_encode, METH_VARARGS}, - {"latin_1_decode", latin_1_decode, METH_VARARGS}, - {"ascii_encode", ascii_encode, METH_VARARGS}, - {"ascii_decode", ascii_decode, METH_VARARGS}, - {"charmap_encode", charmap_encode, METH_VARARGS}, - {"charmap_decode", charmap_decode, METH_VARARGS}, - {"charmap_build", charmap_build, METH_VARARGS}, - {"readbuffer_encode", readbuffer_encode, METH_VARARGS}, - {"charbuffer_encode", charbuffer_encode, METH_VARARGS}, + {"encode", codec_encode, METH_VARARGS, + encode__doc__}, + {"decode", codec_decode, METH_VARARGS, + decode__doc__}, + {"escape_encode", escape_encode, METH_VARARGS}, + {"escape_decode", escape_decode, METH_VARARGS}, + {"utf_8_encode", utf_8_encode, METH_VARARGS}, + {"utf_8_decode", utf_8_decode, METH_VARARGS}, + {"utf_7_encode", utf_7_encode, METH_VARARGS}, + {"utf_7_decode", utf_7_decode, METH_VARARGS}, + {"utf_16_encode", utf_16_encode, METH_VARARGS}, + {"utf_16_le_encode", utf_16_le_encode, METH_VARARGS}, + {"utf_16_be_encode", utf_16_be_encode, METH_VARARGS}, + {"utf_16_decode", utf_16_decode, METH_VARARGS}, + {"utf_16_le_decode", utf_16_le_decode, METH_VARARGS}, + {"utf_16_be_decode", utf_16_be_decode, METH_VARARGS}, + {"utf_16_ex_decode", utf_16_ex_decode, METH_VARARGS}, + {"utf_32_encode", utf_32_encode, METH_VARARGS}, + {"utf_32_le_encode", utf_32_le_encode, METH_VARARGS}, + {"utf_32_be_encode", utf_32_be_encode, METH_VARARGS}, + {"utf_32_decode", utf_32_decode, METH_VARARGS}, + {"utf_32_le_decode", utf_32_le_decode, METH_VARARGS}, + {"utf_32_be_decode", utf_32_be_decode, METH_VARARGS}, + {"utf_32_ex_decode", utf_32_ex_decode, METH_VARARGS}, + {"unicode_escape_encode", unicode_escape_encode, METH_VARARGS}, + {"unicode_escape_decode", unicode_escape_decode, METH_VARARGS}, + {"unicode_internal_encode", unicode_internal_encode, METH_VARARGS}, + {"unicode_internal_decode", unicode_internal_decode, METH_VARARGS}, + {"raw_unicode_escape_encode", raw_unicode_escape_encode, METH_VARARGS}, + {"raw_unicode_escape_decode", raw_unicode_escape_decode, METH_VARARGS}, + {"latin_1_encode", latin_1_encode, METH_VARARGS}, + {"latin_1_decode", latin_1_decode, METH_VARARGS}, + {"ascii_encode", ascii_encode, METH_VARARGS}, + {"ascii_decode", ascii_decode, METH_VARARGS}, + {"charmap_encode", charmap_encode, METH_VARARGS}, + {"charmap_decode", charmap_decode, METH_VARARGS}, + {"charmap_build", charmap_build, METH_VARARGS}, + {"readbuffer_encode", readbuffer_encode, METH_VARARGS}, + {"charbuffer_encode", charbuffer_encode, METH_VARARGS}, #if defined(MS_WINDOWS) && defined(HAVE_USABLE_WCHAR_T) - {"mbcs_encode", mbcs_encode, METH_VARARGS}, - {"mbcs_decode", mbcs_decode, METH_VARARGS}, + {"mbcs_encode", mbcs_encode, METH_VARARGS}, + {"mbcs_decode", mbcs_decode, METH_VARARGS}, #endif - {"register_error", register_error, METH_VARARGS, + {"register_error", register_error, METH_VARARGS, register_error__doc__}, - {"lookup_error", lookup_error, METH_VARARGS, + {"lookup_error", lookup_error, METH_VARARGS, lookup_error__doc__}, - {NULL, NULL} /* sentinel */ + {NULL, NULL} /* sentinel */ }; static struct PyModuleDef codecsmodule = { - PyModuleDef_HEAD_INIT, - "_codecs", - NULL, - -1, - _codecs_functions, - NULL, - NULL, - NULL, - NULL + PyModuleDef_HEAD_INIT, + "_codecs", + NULL, + -1, + _codecs_functions, + NULL, + NULL, + NULL, + NULL }; PyMODINIT_FUNC PyInit__codecs(void) { - return PyModule_Create(&codecsmodule); + return PyModule_Create(&codecsmodule); } Modified: python/branches/py3k-jit/Modules/_collectionsmodule.c ============================================================================== --- python/branches/py3k-jit/Modules/_collectionsmodule.c (original) +++ python/branches/py3k-jit/Modules/_collectionsmodule.c Mon May 10 23:55:43 2010 @@ -46,9 +46,9 @@ */ typedef struct BLOCK { - struct BLOCK *leftlink; - struct BLOCK *rightlink; - PyObject *data[BLOCKLEN]; + struct BLOCK *leftlink; + struct BLOCK *rightlink; + PyObject *data[BLOCKLEN]; } block; #define MAXFREEBLOCKS 10 @@ -57,71 +57,71 @@ static block * newblock(block *leftlink, block *rightlink, Py_ssize_t len) { - block *b; - /* To prevent len from overflowing PY_SSIZE_T_MAX on 64-bit machines, we - * refuse to allocate new blocks if the current len is dangerously - * close. There is some extra margin to prevent spurious arithmetic - * overflows at various places. The following check ensures that - * the blocks allocated to the deque, in the worst case, can only - * have PY_SSIZE_T_MAX-2 entries in total. - */ - if (len >= PY_SSIZE_T_MAX - 2*BLOCKLEN) { - PyErr_SetString(PyExc_OverflowError, - "cannot add more blocks to the deque"); - return NULL; - } - if (numfreeblocks) { - numfreeblocks -= 1; - b = freeblocks[numfreeblocks]; - } else { - b = PyMem_Malloc(sizeof(block)); - if (b == NULL) { - PyErr_NoMemory(); - return NULL; - } - } - b->leftlink = leftlink; - b->rightlink = rightlink; - return b; + block *b; + /* To prevent len from overflowing PY_SSIZE_T_MAX on 64-bit machines, we + * refuse to allocate new blocks if the current len is dangerously + * close. There is some extra margin to prevent spurious arithmetic + * overflows at various places. The following check ensures that + * the blocks allocated to the deque, in the worst case, can only + * have PY_SSIZE_T_MAX-2 entries in total. + */ + if (len >= PY_SSIZE_T_MAX - 2*BLOCKLEN) { + PyErr_SetString(PyExc_OverflowError, + "cannot add more blocks to the deque"); + return NULL; + } + if (numfreeblocks) { + numfreeblocks -= 1; + b = freeblocks[numfreeblocks]; + } else { + b = PyMem_Malloc(sizeof(block)); + if (b == NULL) { + PyErr_NoMemory(); + return NULL; + } + } + b->leftlink = leftlink; + b->rightlink = rightlink; + return b; } static void freeblock(block *b) { - if (numfreeblocks < MAXFREEBLOCKS) { - freeblocks[numfreeblocks] = b; - numfreeblocks++; - } else { - PyMem_Free(b); - } + if (numfreeblocks < MAXFREEBLOCKS) { + freeblocks[numfreeblocks] = b; + numfreeblocks++; + } else { + PyMem_Free(b); + } } typedef struct { - PyObject_HEAD - block *leftblock; - block *rightblock; - Py_ssize_t leftindex; /* in range(BLOCKLEN) */ - Py_ssize_t rightindex; /* in range(BLOCKLEN) */ - Py_ssize_t len; - Py_ssize_t maxlen; - long state; /* incremented whenever the indices move */ - PyObject *weakreflist; /* List of weak references */ + PyObject_HEAD + block *leftblock; + block *rightblock; + Py_ssize_t leftindex; /* in range(BLOCKLEN) */ + Py_ssize_t rightindex; /* in range(BLOCKLEN) */ + Py_ssize_t len; + Py_ssize_t maxlen; + long state; /* incremented whenever the indices move */ + PyObject *weakreflist; /* List of weak references */ } dequeobject; /* The deque's size limit is d.maxlen. The limit can be zero or positive. * If there is no limit, then d.maxlen == -1. - * + * * After an item is added to a deque, we check to see if the size has grown past * the limit. If it has, we get the size back down to the limit by popping an * item off of the opposite end. The methods that can trigger this are append(), * appendleft(), extend(), and extendleft(). */ -#define TRIM(d, popfunction) \ - if (d->maxlen != -1 && d->len > d->maxlen) { \ - PyObject *rv = popfunction(d, NULL); \ - assert(rv != NULL && d->len <= d->maxlen); \ - Py_DECREF(rv); \ +#define TRIM(d, popfunction) \ + if (d->maxlen != -1 && d->len > d->maxlen) { \ + PyObject *rv = popfunction(d, NULL); \ + assert(rv != NULL && d->len <= d->maxlen); \ + Py_DECREF(rv); \ } static PyTypeObject deque_type; @@ -129,65 +129,65 @@ static PyObject * deque_new(PyTypeObject *type, PyObject *args, PyObject *kwds) { - dequeobject *deque; - block *b; + dequeobject *deque; + block *b; + + /* create dequeobject structure */ + deque = (dequeobject *)type->tp_alloc(type, 0); + if (deque == NULL) + return NULL; + + b = newblock(NULL, NULL, 0); + if (b == NULL) { + Py_DECREF(deque); + return NULL; + } - /* create dequeobject structure */ - deque = (dequeobject *)type->tp_alloc(type, 0); - if (deque == NULL) - return NULL; - - b = newblock(NULL, NULL, 0); - if (b == NULL) { - Py_DECREF(deque); - return NULL; - } - - assert(BLOCKLEN >= 2); - deque->leftblock = b; - deque->rightblock = b; - deque->leftindex = CENTER + 1; - deque->rightindex = CENTER; - deque->len = 0; - deque->state = 0; - deque->weakreflist = NULL; - deque->maxlen = -1; + assert(BLOCKLEN >= 2); + deque->leftblock = b; + deque->rightblock = b; + deque->leftindex = CENTER + 1; + deque->rightindex = CENTER; + deque->len = 0; + deque->state = 0; + deque->weakreflist = NULL; + deque->maxlen = -1; - return (PyObject *)deque; + return (PyObject *)deque; } static PyObject * deque_pop(dequeobject *deque, PyObject *unused) { - PyObject *item; - block *prevblock; + PyObject *item; + block *prevblock; - if (deque->len == 0) { - PyErr_SetString(PyExc_IndexError, "pop from an empty deque"); - return NULL; - } - item = deque->rightblock->data[deque->rightindex]; - deque->rightindex--; - deque->len--; - deque->state++; - - if (deque->rightindex == -1) { - if (deque->len == 0) { - assert(deque->leftblock == deque->rightblock); - assert(deque->leftindex == deque->rightindex+1); - /* re-center instead of freeing a block */ - deque->leftindex = CENTER + 1; - deque->rightindex = CENTER; - } else { - prevblock = deque->rightblock->leftlink; - assert(deque->leftblock != deque->rightblock); - freeblock(deque->rightblock); - prevblock->rightlink = NULL; - deque->rightblock = prevblock; - deque->rightindex = BLOCKLEN - 1; - } - } - return item; + if (deque->len == 0) { + PyErr_SetString(PyExc_IndexError, "pop from an empty deque"); + return NULL; + } + item = deque->rightblock->data[deque->rightindex]; + deque->rightindex--; + deque->len--; + deque->state++; + + if (deque->rightindex == -1) { + if (deque->len == 0) { + assert(deque->leftblock == deque->rightblock); + assert(deque->leftindex == deque->rightindex+1); + /* re-center instead of freeing a block */ + deque->leftindex = CENTER + 1; + deque->rightindex = CENTER; + } else { + prevblock = deque->rightblock->leftlink; + assert(deque->leftblock != deque->rightblock); + freeblock(deque->rightblock); + prevblock->rightlink = NULL; + deque->rightblock = prevblock; + deque->rightindex = BLOCKLEN - 1; + } + } + return item; } PyDoc_STRVAR(pop_doc, "Remove and return the rightmost element."); @@ -195,37 +195,37 @@ static PyObject * deque_popleft(dequeobject *deque, PyObject *unused) { - PyObject *item; - block *prevblock; + PyObject *item; + block *prevblock; - if (deque->len == 0) { - PyErr_SetString(PyExc_IndexError, "pop from an empty deque"); - return NULL; - } - assert(deque->leftblock != NULL); - item = deque->leftblock->data[deque->leftindex]; - deque->leftindex++; - deque->len--; - deque->state++; - - if (deque->leftindex == BLOCKLEN) { - if (deque->len == 0) { - assert(deque->leftblock == deque->rightblock); - assert(deque->leftindex == deque->rightindex+1); - /* re-center instead of freeing a block */ - deque->leftindex = CENTER + 1; - deque->rightindex = CENTER; - } else { - assert(deque->leftblock != deque->rightblock); - prevblock = deque->leftblock->rightlink; - freeblock(deque->leftblock); - assert(prevblock != NULL); - prevblock->leftlink = NULL; - deque->leftblock = prevblock; - deque->leftindex = 0; - } - } - return item; + if (deque->len == 0) { + PyErr_SetString(PyExc_IndexError, "pop from an empty deque"); + return NULL; + } + assert(deque->leftblock != NULL); + item = deque->leftblock->data[deque->leftindex]; + deque->leftindex++; + deque->len--; + deque->state++; + + if (deque->leftindex == BLOCKLEN) { + if (deque->len == 0) { + assert(deque->leftblock == deque->rightblock); + assert(deque->leftindex == deque->rightindex+1); + /* re-center instead of freeing a block */ + deque->leftindex = CENTER + 1; + deque->rightindex = CENTER; + } else { + assert(deque->leftblock != deque->rightblock); + prevblock = deque->leftblock->rightlink; + freeblock(deque->leftblock); + assert(prevblock != NULL); + prevblock->leftlink = NULL; + deque->leftblock = prevblock; + deque->leftindex = 0; + } + } + return item; } PyDoc_STRVAR(popleft_doc, "Remove and return the leftmost element."); @@ -233,22 +233,22 @@ static PyObject * deque_append(dequeobject *deque, PyObject *item) { - deque->state++; - if (deque->rightindex == BLOCKLEN-1) { - block *b = newblock(deque->rightblock, NULL, deque->len); - if (b == NULL) - return NULL; - assert(deque->rightblock->rightlink == NULL); - deque->rightblock->rightlink = b; - deque->rightblock = b; - deque->rightindex = -1; - } - Py_INCREF(item); - deque->len++; - deque->rightindex++; - deque->rightblock->data[deque->rightindex] = item; - TRIM(deque, deque_popleft); - Py_RETURN_NONE; + deque->state++; + if (deque->rightindex == BLOCKLEN-1) { + block *b = newblock(deque->rightblock, NULL, deque->len); + if (b == NULL) + return NULL; + assert(deque->rightblock->rightlink == NULL); + deque->rightblock->rightlink = b; + deque->rightblock = b; + deque->rightindex = -1; + } + Py_INCREF(item); + deque->len++; + deque->rightindex++; + deque->rightblock->data[deque->rightindex] = item; + TRIM(deque, deque_popleft); + Py_RETURN_NONE; } PyDoc_STRVAR(append_doc, "Add an element to the right side of the deque."); @@ -256,90 +256,90 @@ static PyObject * deque_appendleft(dequeobject *deque, PyObject *item) { - deque->state++; - if (deque->leftindex == 0) { - block *b = newblock(NULL, deque->leftblock, deque->len); - if (b == NULL) - return NULL; - assert(deque->leftblock->leftlink == NULL); - deque->leftblock->leftlink = b; - deque->leftblock = b; - deque->leftindex = BLOCKLEN; - } - Py_INCREF(item); - deque->len++; - deque->leftindex--; - deque->leftblock->data[deque->leftindex] = item; - TRIM(deque, deque_pop); - Py_RETURN_NONE; + deque->state++; + if (deque->leftindex == 0) { + block *b = newblock(NULL, deque->leftblock, deque->len); + if (b == NULL) + return NULL; + assert(deque->leftblock->leftlink == NULL); + deque->leftblock->leftlink = b; + deque->leftblock = b; + deque->leftindex = BLOCKLEN; + } + Py_INCREF(item); + deque->len++; + deque->leftindex--; + deque->leftblock->data[deque->leftindex] = item; + TRIM(deque, deque_pop); + Py_RETURN_NONE; } PyDoc_STRVAR(appendleft_doc, "Add an element to the left side of the deque."); -/* Run an iterator to exhaustion. Shortcut for +/* Run an iterator to exhaustion. Shortcut for the extend/extendleft methods when maxlen == 0. */ static PyObject* consume_iterator(PyObject *it) { - PyObject *item; + PyObject *item; - while ((item = PyIter_Next(it)) != NULL) { - Py_DECREF(item); - } - Py_DECREF(it); - if (PyErr_Occurred()) - return NULL; - Py_RETURN_NONE; + while ((item = PyIter_Next(it)) != NULL) { + Py_DECREF(item); + } + Py_DECREF(it); + if (PyErr_Occurred()) + return NULL; + Py_RETURN_NONE; } static PyObject * deque_extend(dequeobject *deque, PyObject *iterable) { - PyObject *it, *item; + PyObject *it, *item; - /* Handle case where id(deque) == id(iterable) */ - if ((PyObject *)deque == iterable) { - PyObject *result; - PyObject *s = PySequence_List(iterable); - if (s == NULL) - return NULL; - result = deque_extend(deque, s); - Py_DECREF(s); - return result; - } - - it = PyObject_GetIter(iterable); - if (it == NULL) - return NULL; - - if (deque->maxlen == 0) - return consume_iterator(it); - - while ((item = PyIter_Next(it)) != NULL) { - deque->state++; - if (deque->rightindex == BLOCKLEN-1) { - block *b = newblock(deque->rightblock, NULL, - deque->len); - if (b == NULL) { - Py_DECREF(item); - Py_DECREF(it); - return NULL; - } - assert(deque->rightblock->rightlink == NULL); - deque->rightblock->rightlink = b; - deque->rightblock = b; - deque->rightindex = -1; - } - deque->len++; - deque->rightindex++; - deque->rightblock->data[deque->rightindex] = item; - TRIM(deque, deque_popleft); - } - Py_DECREF(it); - if (PyErr_Occurred()) - return NULL; - Py_RETURN_NONE; + /* Handle case where id(deque) == id(iterable) */ + if ((PyObject *)deque == iterable) { + PyObject *result; + PyObject *s = PySequence_List(iterable); + if (s == NULL) + return NULL; + result = deque_extend(deque, s); + Py_DECREF(s); + return result; + } + + it = PyObject_GetIter(iterable); + if (it == NULL) + return NULL; + + if (deque->maxlen == 0) + return consume_iterator(it); + + while ((item = PyIter_Next(it)) != NULL) { + deque->state++; + if (deque->rightindex == BLOCKLEN-1) { + block *b = newblock(deque->rightblock, NULL, + deque->len); + if (b == NULL) { + Py_DECREF(item); + Py_DECREF(it); + return NULL; + } + assert(deque->rightblock->rightlink == NULL); + deque->rightblock->rightlink = b; + deque->rightblock = b; + deque->rightindex = -1; + } + deque->len++; + deque->rightindex++; + deque->rightblock->data[deque->rightindex] = item; + TRIM(deque, deque_popleft); + } + Py_DECREF(it); + if (PyErr_Occurred()) + return NULL; + Py_RETURN_NONE; } PyDoc_STRVAR(extend_doc, @@ -348,50 +348,50 @@ static PyObject * deque_extendleft(dequeobject *deque, PyObject *iterable) { - PyObject *it, *item; + PyObject *it, *item; - /* Handle case where id(deque) == id(iterable) */ - if ((PyObject *)deque == iterable) { - PyObject *result; - PyObject *s = PySequence_List(iterable); - if (s == NULL) - return NULL; - result = deque_extendleft(deque, s); - Py_DECREF(s); - return result; - } - - it = PyObject_GetIter(iterable); - if (it == NULL) - return NULL; - - if (deque->maxlen == 0) - return consume_iterator(it); - - while ((item = PyIter_Next(it)) != NULL) { - deque->state++; - if (deque->leftindex == 0) { - block *b = newblock(NULL, deque->leftblock, - deque->len); - if (b == NULL) { - Py_DECREF(item); - Py_DECREF(it); - return NULL; - } - assert(deque->leftblock->leftlink == NULL); - deque->leftblock->leftlink = b; - deque->leftblock = b; - deque->leftindex = BLOCKLEN; - } - deque->len++; - deque->leftindex--; - deque->leftblock->data[deque->leftindex] = item; - TRIM(deque, deque_pop); - } - Py_DECREF(it); - if (PyErr_Occurred()) - return NULL; - Py_RETURN_NONE; + /* Handle case where id(deque) == id(iterable) */ + if ((PyObject *)deque == iterable) { + PyObject *result; + PyObject *s = PySequence_List(iterable); + if (s == NULL) + return NULL; + result = deque_extendleft(deque, s); + Py_DECREF(s); + return result; + } + + it = PyObject_GetIter(iterable); + if (it == NULL) + return NULL; + + if (deque->maxlen == 0) + return consume_iterator(it); + + while ((item = PyIter_Next(it)) != NULL) { + deque->state++; + if (deque->leftindex == 0) { + block *b = newblock(NULL, deque->leftblock, + deque->len); + if (b == NULL) { + Py_DECREF(item); + Py_DECREF(it); + return NULL; + } + assert(deque->leftblock->leftlink == NULL); + deque->leftblock->leftlink = b; + deque->leftblock = b; + deque->leftindex = BLOCKLEN; + } + deque->len++; + deque->leftindex--; + deque->leftblock->data[deque->leftindex] = item; + TRIM(deque, deque_pop); + } + Py_DECREF(it); + if (PyErr_Occurred()) + return NULL; + Py_RETURN_NONE; } PyDoc_STRVAR(extendleft_doc, @@ -400,63 +400,63 @@ static PyObject * deque_inplace_concat(dequeobject *deque, PyObject *other) { - PyObject *result; + PyObject *result; - result = deque_extend(deque, other); - if (result == NULL) - return result; - Py_DECREF(result); - Py_INCREF(deque); - return (PyObject *)deque; + result = deque_extend(deque, other); + if (result == NULL) + return result; + Py_DECREF(result); + Py_INCREF(deque); + return (PyObject *)deque; } static int _deque_rotate(dequeobject *deque, Py_ssize_t n) { - Py_ssize_t i, len=deque->len, halflen=(len+1)>>1; - PyObject *item, *rv; + Py_ssize_t i, len=deque->len, halflen=(len+1)>>1; + PyObject *item, *rv; + + if (len == 0) + return 0; + if (n > halflen || n < -halflen) { + n %= len; + if (n > halflen) + n -= len; + else if (n < -halflen) + n += len; + } - if (len == 0) - return 0; - if (n > halflen || n < -halflen) { - n %= len; - if (n > halflen) - n -= len; - else if (n < -halflen) - n += len; - } - - for (i=0 ; in ; i--) { - item = deque_popleft(deque, NULL); - assert (item != NULL); - rv = deque_append(deque, item); - Py_DECREF(item); - if (rv == NULL) - return -1; - Py_DECREF(rv); - } - return 0; + for (i=0 ; in ; i--) { + item = deque_popleft(deque, NULL); + assert (item != NULL); + rv = deque_append(deque, item); + Py_DECREF(item); + if (rv == NULL) + return -1; + Py_DECREF(rv); + } + return 0; } static PyObject * deque_rotate(dequeobject *deque, PyObject *args) { - Py_ssize_t n=1; + Py_ssize_t n=1; - if (!PyArg_ParseTuple(args, "|n:rotate", &n)) - return NULL; - if (_deque_rotate(deque, n) == 0) - Py_RETURN_NONE; - return NULL; + if (!PyArg_ParseTuple(args, "|n:rotate", &n)) + return NULL; + if (_deque_rotate(deque, n) == 0) + Py_RETURN_NONE; + return NULL; } PyDoc_STRVAR(rotate_doc, @@ -465,40 +465,40 @@ static PyObject * deque_reverse(dequeobject *deque, PyObject *unused) { - block *leftblock = deque->leftblock; - block *rightblock = deque->rightblock; - Py_ssize_t leftindex = deque->leftindex; - Py_ssize_t rightindex = deque->rightindex; - Py_ssize_t n = (deque->len)/2; - Py_ssize_t i; - PyObject *tmp; - - for (i=0 ; idata[leftindex]; - leftblock->data[leftindex] = rightblock->data[rightindex]; - rightblock->data[rightindex] = tmp; - - /* Advance left block/index pair */ - leftindex++; - if (leftindex == BLOCKLEN) { - assert (leftblock->rightlink != NULL); - leftblock = leftblock->rightlink; - leftindex = 0; - } - - /* Step backwards with the right block/index pair */ - rightindex--; - if (rightindex == -1) { - assert (rightblock->leftlink != NULL); - rightblock = rightblock->leftlink; - rightindex = BLOCKLEN - 1; - } - } - Py_RETURN_NONE; + block *leftblock = deque->leftblock; + block *rightblock = deque->rightblock; + Py_ssize_t leftindex = deque->leftindex; + Py_ssize_t rightindex = deque->rightindex; + Py_ssize_t n = (deque->len)/2; + Py_ssize_t i; + PyObject *tmp; + + for (i=0 ; idata[leftindex]; + leftblock->data[leftindex] = rightblock->data[rightindex]; + rightblock->data[rightindex] = tmp; + + /* Advance left block/index pair */ + leftindex++; + if (leftindex == BLOCKLEN) { + assert (leftblock->rightlink != NULL); + leftblock = leftblock->rightlink; + leftindex = 0; + } + + /* Step backwards with the right block/index pair */ + rightindex--; + if (rightindex == -1) { + assert (rightblock->leftlink != NULL); + rightblock = rightblock->leftlink; + rightindex = BLOCKLEN - 1; + } + } + Py_RETURN_NONE; } PyDoc_STRVAR(reverse_doc, @@ -507,38 +507,38 @@ static PyObject * deque_count(dequeobject *deque, PyObject *v) { - block *leftblock = deque->leftblock; - Py_ssize_t leftindex = deque->leftindex; - Py_ssize_t n = (deque->len); - Py_ssize_t i; - Py_ssize_t count = 0; - PyObject *item; - long start_state = deque->state; - int cmp; - - for (i=0 ; idata[leftindex]; - cmp = PyObject_RichCompareBool(item, v, Py_EQ); - if (cmp > 0) - count++; - else if (cmp < 0) - return NULL; - - if (start_state != deque->state) { - PyErr_SetString(PyExc_RuntimeError, - "deque mutated during iteration"); - return NULL; - } - - /* Advance left block/index pair */ - leftindex++; - if (leftindex == BLOCKLEN) { - assert (leftblock->rightlink != NULL); - leftblock = leftblock->rightlink; - leftindex = 0; - } - } - return PyLong_FromSsize_t(count); + block *leftblock = deque->leftblock; + Py_ssize_t leftindex = deque->leftindex; + Py_ssize_t n = (deque->len); + Py_ssize_t i; + Py_ssize_t count = 0; + PyObject *item; + long start_state = deque->state; + int cmp; + + for (i=0 ; idata[leftindex]; + cmp = PyObject_RichCompareBool(item, v, Py_EQ); + if (cmp > 0) + count++; + else if (cmp < 0) + return NULL; + + if (start_state != deque->state) { + PyErr_SetString(PyExc_RuntimeError, + "deque mutated during iteration"); + return NULL; + } + + /* Advance left block/index pair */ + leftindex++; + if (leftindex == BLOCKLEN) { + assert (leftblock->rightlink != NULL); + leftblock = leftblock->rightlink; + leftindex = 0; + } + } + return PyLong_FromSsize_t(count); } PyDoc_STRVAR(count_doc, @@ -547,39 +547,39 @@ static Py_ssize_t deque_len(dequeobject *deque) { - return deque->len; + return deque->len; } static PyObject * deque_remove(dequeobject *deque, PyObject *value) { - Py_ssize_t i, n=deque->len; + Py_ssize_t i, n=deque->len; - for (i=0 ; ileftblock->data[deque->leftindex]; - int cmp = PyObject_RichCompareBool(item, value, Py_EQ); - - if (deque->len != n) { - PyErr_SetString(PyExc_IndexError, - "deque mutated during remove()."); - return NULL; - } - if (cmp > 0) { - PyObject *tgt = deque_popleft(deque, NULL); - assert (tgt != NULL); - Py_DECREF(tgt); - if (_deque_rotate(deque, i) == -1) - return NULL; - Py_RETURN_NONE; - } - else if (cmp < 0) { - _deque_rotate(deque, i); - return NULL; - } - _deque_rotate(deque, -1); - } - PyErr_SetString(PyExc_ValueError, "deque.remove(x): x not in deque"); - return NULL; + for (i=0 ; ileftblock->data[deque->leftindex]; + int cmp = PyObject_RichCompareBool(item, value, Py_EQ); + + if (deque->len != n) { + PyErr_SetString(PyExc_IndexError, + "deque mutated during remove()."); + return NULL; + } + if (cmp > 0) { + PyObject *tgt = deque_popleft(deque, NULL); + assert (tgt != NULL); + Py_DECREF(tgt); + if (_deque_rotate(deque, i) == -1) + return NULL; + Py_RETURN_NONE; + } + else if (cmp < 0) { + _deque_rotate(deque, i); + return NULL; + } + _deque_rotate(deque, -1); + } + PyErr_SetString(PyExc_ValueError, "deque.remove(x): x not in deque"); + return NULL; } PyDoc_STRVAR(remove_doc, @@ -588,56 +588,56 @@ static int deque_clear(dequeobject *deque) { - PyObject *item; + PyObject *item; - while (deque->len) { - item = deque_pop(deque, NULL); - assert (item != NULL); - Py_DECREF(item); - } - assert(deque->leftblock == deque->rightblock && - deque->leftindex - 1 == deque->rightindex && - deque->len == 0); - return 0; + while (deque->len) { + item = deque_pop(deque, NULL); + assert (item != NULL); + Py_DECREF(item); + } + assert(deque->leftblock == deque->rightblock && + deque->leftindex - 1 == deque->rightindex && + deque->len == 0); + return 0; } static PyObject * deque_item(dequeobject *deque, Py_ssize_t i) { - block *b; - PyObject *item; - Py_ssize_t n, index=i; - - if (i < 0 || i >= deque->len) { - PyErr_SetString(PyExc_IndexError, - "deque index out of range"); - return NULL; - } - - if (i == 0) { - i = deque->leftindex; - b = deque->leftblock; - } else if (i == deque->len - 1) { - i = deque->rightindex; - b = deque->rightblock; - } else { - i += deque->leftindex; - n = i / BLOCKLEN; - i %= BLOCKLEN; - if (index < (deque->len >> 1)) { - b = deque->leftblock; - while (n--) - b = b->rightlink; - } else { - n = (deque->leftindex + deque->len - 1) / BLOCKLEN - n; - b = deque->rightblock; - while (n--) - b = b->leftlink; - } - } - item = b->data[i]; - Py_INCREF(item); - return item; + block *b; + PyObject *item; + Py_ssize_t n, index=i; + + if (i < 0 || i >= deque->len) { + PyErr_SetString(PyExc_IndexError, + "deque index out of range"); + return NULL; + } + + if (i == 0) { + i = deque->leftindex; + b = deque->leftblock; + } else if (i == deque->len - 1) { + i = deque->rightindex; + b = deque->rightblock; + } else { + i += deque->leftindex; + n = i / BLOCKLEN; + i %= BLOCKLEN; + if (index < (deque->len >> 1)) { + b = deque->leftblock; + while (n--) + b = b->rightlink; + } else { + n = (deque->leftindex + deque->len - 1) / BLOCKLEN - n; + b = deque->rightblock; + while (n--) + b = b->leftlink; + } + } + item = b->data[i]; + Py_INCREF(item); + return item; } /* delitem() implemented in terms of rotate for simplicity and reasonable @@ -650,62 +650,62 @@ static int deque_del_item(dequeobject *deque, Py_ssize_t i) { - PyObject *item; + PyObject *item; - assert (i >= 0 && i < deque->len); - if (_deque_rotate(deque, -i) == -1) - return -1; + assert (i >= 0 && i < deque->len); + if (_deque_rotate(deque, -i) == -1) + return -1; - item = deque_popleft(deque, NULL); - assert (item != NULL); - Py_DECREF(item); + item = deque_popleft(deque, NULL); + assert (item != NULL); + Py_DECREF(item); - return _deque_rotate(deque, i); + return _deque_rotate(deque, i); } static int deque_ass_item(dequeobject *deque, Py_ssize_t i, PyObject *v) { - PyObject *old_value; - block *b; - Py_ssize_t n, len=deque->len, halflen=(len+1)>>1, index=i; - - if (i < 0 || i >= len) { - PyErr_SetString(PyExc_IndexError, - "deque index out of range"); - return -1; - } - if (v == NULL) - return deque_del_item(deque, i); - - i += deque->leftindex; - n = i / BLOCKLEN; - i %= BLOCKLEN; - if (index <= halflen) { - b = deque->leftblock; - while (n--) - b = b->rightlink; - } else { - n = (deque->leftindex + len - 1) / BLOCKLEN - n; - b = deque->rightblock; - while (n--) - b = b->leftlink; - } - Py_INCREF(v); - old_value = b->data[i]; - b->data[i] = v; - Py_DECREF(old_value); - return 0; + PyObject *old_value; + block *b; + Py_ssize_t n, len=deque->len, halflen=(len+1)>>1, index=i; + + if (i < 0 || i >= len) { + PyErr_SetString(PyExc_IndexError, + "deque index out of range"); + return -1; + } + if (v == NULL) + return deque_del_item(deque, i); + + i += deque->leftindex; + n = i / BLOCKLEN; + i %= BLOCKLEN; + if (index <= halflen) { + b = deque->leftblock; + while (n--) + b = b->rightlink; + } else { + n = (deque->leftindex + len - 1) / BLOCKLEN - n; + b = deque->rightblock; + while (n--) + b = b->leftlink; + } + Py_INCREF(v); + old_value = b->data[i]; + b->data[i] = v; + Py_DECREF(old_value); + return 0; } static PyObject * deque_clearmethod(dequeobject *deque) { - int rv; + int rv; - rv = deque_clear(deque); - assert (rv != -1); - Py_RETURN_NONE; + rv = deque_clear(deque); + assert (rv != -1); + Py_RETURN_NONE; } PyDoc_STRVAR(clear_doc, "Remove all elements from the deque."); @@ -713,49 +713,49 @@ static void deque_dealloc(dequeobject *deque) { - PyObject_GC_UnTrack(deque); - if (deque->weakreflist != NULL) - PyObject_ClearWeakRefs((PyObject *) deque); - if (deque->leftblock != NULL) { - deque_clear(deque); - assert(deque->leftblock != NULL); - freeblock(deque->leftblock); - } - deque->leftblock = NULL; - deque->rightblock = NULL; - Py_TYPE(deque)->tp_free(deque); + PyObject_GC_UnTrack(deque); + if (deque->weakreflist != NULL) + PyObject_ClearWeakRefs((PyObject *) deque); + if (deque->leftblock != NULL) { + deque_clear(deque); + assert(deque->leftblock != NULL); + freeblock(deque->leftblock); + } + deque->leftblock = NULL; + deque->rightblock = NULL; + Py_TYPE(deque)->tp_free(deque); } static int deque_traverse(dequeobject *deque, visitproc visit, void *arg) { - block *b; - PyObject *item; - Py_ssize_t index; - Py_ssize_t indexlo = deque->leftindex; - - for (b = deque->leftblock; b != NULL; b = b->rightlink) { - const Py_ssize_t indexhi = b == deque->rightblock ? - deque->rightindex : - BLOCKLEN - 1; - - for (index = indexlo; index <= indexhi; ++index) { - item = b->data[index]; - Py_VISIT(item); - } - indexlo = 0; - } - return 0; + block *b; + PyObject *item; + Py_ssize_t index; + Py_ssize_t indexlo = deque->leftindex; + + for (b = deque->leftblock; b != NULL; b = b->rightlink) { + const Py_ssize_t indexhi = b == deque->rightblock ? + deque->rightindex : + BLOCKLEN - 1; + + for (index = indexlo; index <= indexhi; ++index) { + item = b->data[index]; + Py_VISIT(item); + } + indexlo = 0; + } + return 0; } static PyObject * deque_copy(PyObject *deque) { - if (((dequeobject *)deque)->maxlen == -1) - return PyObject_CallFunction((PyObject *)(Py_TYPE(deque)), "O", deque, NULL); - else - return PyObject_CallFunction((PyObject *)(Py_TYPE(deque)), "Oi", - deque, ((dequeobject *)deque)->maxlen, NULL); + if (((dequeobject *)deque)->maxlen == -1) + return PyObject_CallFunction((PyObject *)(Py_TYPE(deque)), "O", deque, NULL); + else + return PyObject_CallFunction((PyObject *)(Py_TYPE(deque)), "Oi", + deque, ((dequeobject *)deque)->maxlen, NULL); } PyDoc_STRVAR(copy_doc, "Return a shallow copy of a deque."); @@ -763,30 +763,30 @@ static PyObject * deque_reduce(dequeobject *deque) { - PyObject *dict, *result, *aslist; + PyObject *dict, *result, *aslist; - dict = PyObject_GetAttrString((PyObject *)deque, "__dict__"); - if (dict == NULL) - PyErr_Clear(); - aslist = PySequence_List((PyObject *)deque); - if (aslist == NULL) { - Py_XDECREF(dict); - return NULL; - } - if (dict == NULL) { - if (deque->maxlen == -1) - result = Py_BuildValue("O(O)", Py_TYPE(deque), aslist); - else - result = Py_BuildValue("O(On)", Py_TYPE(deque), aslist, deque->maxlen); - } else { - if (deque->maxlen == -1) - result = Py_BuildValue("O(OO)O", Py_TYPE(deque), aslist, Py_None, dict); - else - result = Py_BuildValue("O(On)O", Py_TYPE(deque), aslist, deque->maxlen, dict); - } - Py_XDECREF(dict); - Py_DECREF(aslist); - return result; + dict = PyObject_GetAttrString((PyObject *)deque, "__dict__"); + if (dict == NULL) + PyErr_Clear(); + aslist = PySequence_List((PyObject *)deque); + if (aslist == NULL) { + Py_XDECREF(dict); + return NULL; + } + if (dict == NULL) { + if (deque->maxlen == -1) + result = Py_BuildValue("O(O)", Py_TYPE(deque), aslist); + else + result = Py_BuildValue("O(On)", Py_TYPE(deque), aslist, deque->maxlen); + } else { + if (deque->maxlen == -1) + result = Py_BuildValue("O(OO)O", Py_TYPE(deque), aslist, Py_None, dict); + else + result = Py_BuildValue("O(On)O", Py_TYPE(deque), aslist, deque->maxlen, dict); + } + Py_XDECREF(dict); + Py_DECREF(aslist); + return result; } PyDoc_STRVAR(reduce_doc, "Return state information for pickling."); @@ -794,166 +794,166 @@ static PyObject * deque_repr(PyObject *deque) { - PyObject *aslist, *result; - int i; + PyObject *aslist, *result; + int i; + + i = Py_ReprEnter(deque); + if (i != 0) { + if (i < 0) + return NULL; + return PyUnicode_FromString("[...]"); + } - i = Py_ReprEnter(deque); - if (i != 0) { - if (i < 0) - return NULL; - return PyUnicode_FromString("[...]"); - } - - aslist = PySequence_List(deque); - if (aslist == NULL) { - Py_ReprLeave(deque); - return NULL; - } - if (((dequeobject *)deque)->maxlen != -1) - - result = PyUnicode_FromFormat("deque(%R, maxlen=%zd)", - aslist, ((dequeobject *)deque)->maxlen); - else - result = PyUnicode_FromFormat("deque(%R)", aslist); - Py_DECREF(aslist); - Py_ReprLeave(deque); - return result; + aslist = PySequence_List(deque); + if (aslist == NULL) { + Py_ReprLeave(deque); + return NULL; + } + if (((dequeobject *)deque)->maxlen != -1) + + result = PyUnicode_FromFormat("deque(%R, maxlen=%zd)", + aslist, ((dequeobject *)deque)->maxlen); + else + result = PyUnicode_FromFormat("deque(%R)", aslist); + Py_DECREF(aslist); + Py_ReprLeave(deque); + return result; } static PyObject * deque_richcompare(PyObject *v, PyObject *w, int op) { - PyObject *it1=NULL, *it2=NULL, *x, *y; - Py_ssize_t vs, ws; - int b, cmp=-1; - - if (!PyObject_TypeCheck(v, &deque_type) || - !PyObject_TypeCheck(w, &deque_type)) { - Py_INCREF(Py_NotImplemented); - return Py_NotImplemented; - } - - /* Shortcuts */ - vs = ((dequeobject *)v)->len; - ws = ((dequeobject *)w)->len; - if (op == Py_EQ) { - if (v == w) - Py_RETURN_TRUE; - if (vs != ws) - Py_RETURN_FALSE; - } - if (op == Py_NE) { - if (v == w) - Py_RETURN_FALSE; - if (vs != ws) - Py_RETURN_TRUE; - } - - /* Search for the first index where items are different */ - it1 = PyObject_GetIter(v); - if (it1 == NULL) - goto done; - it2 = PyObject_GetIter(w); - if (it2 == NULL) - goto done; - for (;;) { - x = PyIter_Next(it1); - if (x == NULL && PyErr_Occurred()) - goto done; - y = PyIter_Next(it2); - if (x == NULL || y == NULL) - break; - b = PyObject_RichCompareBool(x, y, Py_EQ); - if (b == 0) { - cmp = PyObject_RichCompareBool(x, y, op); - Py_DECREF(x); - Py_DECREF(y); - goto done; - } - Py_DECREF(x); - Py_DECREF(y); - if (b == -1) - goto done; - } - /* We reached the end of one deque or both */ - Py_XDECREF(x); - Py_XDECREF(y); - if (PyErr_Occurred()) - goto done; - switch (op) { - case Py_LT: cmp = y != NULL; break; /* if w was longer */ - case Py_LE: cmp = x == NULL; break; /* if v was not longer */ - case Py_EQ: cmp = x == y; break; /* if we reached the end of both */ - case Py_NE: cmp = x != y; break; /* if one deque continues */ - case Py_GT: cmp = x != NULL; break; /* if v was longer */ - case Py_GE: cmp = y == NULL; break; /* if w was not longer */ - } + PyObject *it1=NULL, *it2=NULL, *x, *y; + Py_ssize_t vs, ws; + int b, cmp=-1; + + if (!PyObject_TypeCheck(v, &deque_type) || + !PyObject_TypeCheck(w, &deque_type)) { + Py_INCREF(Py_NotImplemented); + return Py_NotImplemented; + } + + /* Shortcuts */ + vs = ((dequeobject *)v)->len; + ws = ((dequeobject *)w)->len; + if (op == Py_EQ) { + if (v == w) + Py_RETURN_TRUE; + if (vs != ws) + Py_RETURN_FALSE; + } + if (op == Py_NE) { + if (v == w) + Py_RETURN_FALSE; + if (vs != ws) + Py_RETURN_TRUE; + } + + /* Search for the first index where items are different */ + it1 = PyObject_GetIter(v); + if (it1 == NULL) + goto done; + it2 = PyObject_GetIter(w); + if (it2 == NULL) + goto done; + for (;;) { + x = PyIter_Next(it1); + if (x == NULL && PyErr_Occurred()) + goto done; + y = PyIter_Next(it2); + if (x == NULL || y == NULL) + break; + b = PyObject_RichCompareBool(x, y, Py_EQ); + if (b == 0) { + cmp = PyObject_RichCompareBool(x, y, op); + Py_DECREF(x); + Py_DECREF(y); + goto done; + } + Py_DECREF(x); + Py_DECREF(y); + if (b == -1) + goto done; + } + /* We reached the end of one deque or both */ + Py_XDECREF(x); + Py_XDECREF(y); + if (PyErr_Occurred()) + goto done; + switch (op) { + case Py_LT: cmp = y != NULL; break; /* if w was longer */ + case Py_LE: cmp = x == NULL; break; /* if v was not longer */ + case Py_EQ: cmp = x == y; break; /* if we reached the end of both */ + case Py_NE: cmp = x != y; break; /* if one deque continues */ + case Py_GT: cmp = x != NULL; break; /* if v was longer */ + case Py_GE: cmp = y == NULL; break; /* if w was not longer */ + } done: - Py_XDECREF(it1); - Py_XDECREF(it2); - if (cmp == 1) - Py_RETURN_TRUE; - if (cmp == 0) - Py_RETURN_FALSE; - return NULL; + Py_XDECREF(it1); + Py_XDECREF(it2); + if (cmp == 1) + Py_RETURN_TRUE; + if (cmp == 0) + Py_RETURN_FALSE; + return NULL; } static int deque_init(dequeobject *deque, PyObject *args, PyObject *kwdargs) { - PyObject *iterable = NULL; - PyObject *maxlenobj = NULL; - Py_ssize_t maxlen = -1; - char *kwlist[] = {"iterable", "maxlen", 0}; - - if (!PyArg_ParseTupleAndKeywords(args, kwdargs, "|OO:deque", kwlist, &iterable, &maxlenobj)) - return -1; - if (maxlenobj != NULL && maxlenobj != Py_None) { - maxlen = PyLong_AsSsize_t(maxlenobj); - if (maxlen == -1 && PyErr_Occurred()) - return -1; - if (maxlen < 0) { - PyErr_SetString(PyExc_ValueError, "maxlen must be non-negative"); - return -1; - } - } - deque->maxlen = maxlen; - deque_clear(deque); - if (iterable != NULL) { - PyObject *rv = deque_extend(deque, iterable); - if (rv == NULL) - return -1; - Py_DECREF(rv); - } - return 0; + PyObject *iterable = NULL; + PyObject *maxlenobj = NULL; + Py_ssize_t maxlen = -1; + char *kwlist[] = {"iterable", "maxlen", 0}; + + if (!PyArg_ParseTupleAndKeywords(args, kwdargs, "|OO:deque", kwlist, &iterable, &maxlenobj)) + return -1; + if (maxlenobj != NULL && maxlenobj != Py_None) { + maxlen = PyLong_AsSsize_t(maxlenobj); + if (maxlen == -1 && PyErr_Occurred()) + return -1; + if (maxlen < 0) { + PyErr_SetString(PyExc_ValueError, "maxlen must be non-negative"); + return -1; + } + } + deque->maxlen = maxlen; + deque_clear(deque); + if (iterable != NULL) { + PyObject *rv = deque_extend(deque, iterable); + if (rv == NULL) + return -1; + Py_DECREF(rv); + } + return 0; } static PyObject * deque_get_maxlen(dequeobject *deque) { - if (deque->maxlen == -1) - Py_RETURN_NONE; - return PyLong_FromSsize_t(deque->maxlen); + if (deque->maxlen == -1) + Py_RETURN_NONE; + return PyLong_FromSsize_t(deque->maxlen); } static PyGetSetDef deque_getset[] = { - {"maxlen", (getter)deque_get_maxlen, (setter)NULL, - "maximum size of a deque or None if unbounded"}, - {0} + {"maxlen", (getter)deque_get_maxlen, (setter)NULL, + "maximum size of a deque or None if unbounded"}, + {0} }; static PySequenceMethods deque_as_sequence = { - (lenfunc)deque_len, /* sq_length */ - 0, /* sq_concat */ - 0, /* sq_repeat */ - (ssizeargfunc)deque_item, /* sq_item */ - 0, /* sq_slice */ - (ssizeobjargproc)deque_ass_item, /* sq_ass_item */ - 0, /* sq_ass_slice */ - 0, /* sq_contains */ - (binaryfunc)deque_inplace_concat, /* sq_inplace_concat */ - 0, /* sq_inplace_repeat */ + (lenfunc)deque_len, /* sq_length */ + 0, /* sq_concat */ + 0, /* sq_repeat */ + (ssizeargfunc)deque_item, /* sq_item */ + 0, /* sq_slice */ + (ssizeobjargproc)deque_ass_item, /* sq_ass_item */ + 0, /* sq_ass_slice */ + 0, /* sq_contains */ + (binaryfunc)deque_inplace_concat, /* sq_inplace_concat */ + 0, /* sq_inplace_repeat */ }; @@ -962,38 +962,38 @@ static PyObject *deque_iter(dequeobject *deque); static PyObject *deque_reviter(dequeobject *deque); PyDoc_STRVAR(reversed_doc, - "D.__reversed__() -- return a reverse iterator over the deque"); + "D.__reversed__() -- return a reverse iterator over the deque"); static PyMethodDef deque_methods[] = { - {"append", (PyCFunction)deque_append, - METH_O, append_doc}, - {"appendleft", (PyCFunction)deque_appendleft, - METH_O, appendleft_doc}, - {"clear", (PyCFunction)deque_clearmethod, - METH_NOARGS, clear_doc}, - {"__copy__", (PyCFunction)deque_copy, - METH_NOARGS, copy_doc}, - {"count", (PyCFunction)deque_count, - METH_O, count_doc}, - {"extend", (PyCFunction)deque_extend, - METH_O, extend_doc}, - {"extendleft", (PyCFunction)deque_extendleft, - METH_O, extendleft_doc}, - {"pop", (PyCFunction)deque_pop, - METH_NOARGS, pop_doc}, - {"popleft", (PyCFunction)deque_popleft, - METH_NOARGS, popleft_doc}, - {"__reduce__", (PyCFunction)deque_reduce, - METH_NOARGS, reduce_doc}, - {"remove", (PyCFunction)deque_remove, - METH_O, remove_doc}, - {"__reversed__", (PyCFunction)deque_reviter, - METH_NOARGS, reversed_doc}, - {"reverse", (PyCFunction)deque_reverse, - METH_NOARGS, reverse_doc}, - {"rotate", (PyCFunction)deque_rotate, - METH_VARARGS, rotate_doc}, - {NULL, NULL} /* sentinel */ + {"append", (PyCFunction)deque_append, + METH_O, append_doc}, + {"appendleft", (PyCFunction)deque_appendleft, + METH_O, appendleft_doc}, + {"clear", (PyCFunction)deque_clearmethod, + METH_NOARGS, clear_doc}, + {"__copy__", (PyCFunction)deque_copy, + METH_NOARGS, copy_doc}, + {"count", (PyCFunction)deque_count, + METH_O, count_doc}, + {"extend", (PyCFunction)deque_extend, + METH_O, extend_doc}, + {"extendleft", (PyCFunction)deque_extendleft, + METH_O, extendleft_doc}, + {"pop", (PyCFunction)deque_pop, + METH_NOARGS, pop_doc}, + {"popleft", (PyCFunction)deque_popleft, + METH_NOARGS, popleft_doc}, + {"__reduce__", (PyCFunction)deque_reduce, + METH_NOARGS, reduce_doc}, + {"remove", (PyCFunction)deque_remove, + METH_O, remove_doc}, + {"__reversed__", (PyCFunction)deque_reviter, + METH_NOARGS, reversed_doc}, + {"reverse", (PyCFunction)deque_reverse, + METH_NOARGS, reverse_doc}, + {"rotate", (PyCFunction)deque_rotate, + METH_VARARGS, rotate_doc}, + {NULL, NULL} /* sentinel */ }; PyDoc_STRVAR(deque_doc, @@ -1002,58 +1002,58 @@ Build an ordered collection accessible from endpoints only."); static PyTypeObject deque_type = { - PyVarObject_HEAD_INIT(NULL, 0) - "collections.deque", /* tp_name */ - sizeof(dequeobject), /* tp_basicsize */ - 0, /* tp_itemsize */ - /* methods */ - (destructor)deque_dealloc, /* tp_dealloc */ - 0, /* tp_print */ - 0, /* tp_getattr */ - 0, /* tp_setattr */ - 0, /* tp_reserved */ - deque_repr, /* tp_repr */ - 0, /* tp_as_number */ - &deque_as_sequence, /* tp_as_sequence */ - 0, /* tp_as_mapping */ - (hashfunc)PyObject_HashNotImplemented, /* tp_hash */ - 0, /* tp_call */ - 0, /* tp_str */ - PyObject_GenericGetAttr, /* tp_getattro */ - 0, /* tp_setattro */ - 0, /* tp_as_buffer */ - Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC, - /* tp_flags */ - deque_doc, /* tp_doc */ - (traverseproc)deque_traverse, /* tp_traverse */ - (inquiry)deque_clear, /* tp_clear */ - (richcmpfunc)deque_richcompare, /* tp_richcompare */ - offsetof(dequeobject, weakreflist), /* tp_weaklistoffset*/ - (getiterfunc)deque_iter, /* tp_iter */ - 0, /* tp_iternext */ - deque_methods, /* tp_methods */ - 0, /* tp_members */ - deque_getset, /* tp_getset */ - 0, /* tp_base */ - 0, /* tp_dict */ - 0, /* tp_descr_get */ - 0, /* tp_descr_set */ - 0, /* tp_dictoffset */ - (initproc)deque_init, /* tp_init */ - PyType_GenericAlloc, /* tp_alloc */ - deque_new, /* tp_new */ - PyObject_GC_Del, /* tp_free */ + PyVarObject_HEAD_INIT(NULL, 0) + "collections.deque", /* tp_name */ + sizeof(dequeobject), /* tp_basicsize */ + 0, /* tp_itemsize */ + /* methods */ + (destructor)deque_dealloc, /* tp_dealloc */ + 0, /* tp_print */ + 0, /* tp_getattr */ + 0, /* tp_setattr */ + 0, /* tp_reserved */ + deque_repr, /* tp_repr */ + 0, /* tp_as_number */ + &deque_as_sequence, /* tp_as_sequence */ + 0, /* tp_as_mapping */ + (hashfunc)PyObject_HashNotImplemented, /* tp_hash */ + 0, /* tp_call */ + 0, /* tp_str */ + PyObject_GenericGetAttr, /* tp_getattro */ + 0, /* tp_setattro */ + 0, /* tp_as_buffer */ + Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC, + /* tp_flags */ + deque_doc, /* tp_doc */ + (traverseproc)deque_traverse, /* tp_traverse */ + (inquiry)deque_clear, /* tp_clear */ + (richcmpfunc)deque_richcompare, /* tp_richcompare */ + offsetof(dequeobject, weakreflist), /* tp_weaklistoffset*/ + (getiterfunc)deque_iter, /* tp_iter */ + 0, /* tp_iternext */ + deque_methods, /* tp_methods */ + 0, /* tp_members */ + deque_getset, /* tp_getset */ + 0, /* tp_base */ + 0, /* tp_dict */ + 0, /* tp_descr_get */ + 0, /* tp_descr_set */ + 0, /* tp_dictoffset */ + (initproc)deque_init, /* tp_init */ + PyType_GenericAlloc, /* tp_alloc */ + deque_new, /* tp_new */ + PyObject_GC_Del, /* tp_free */ }; /*********************** Deque Iterator **************************/ typedef struct { - PyObject_HEAD - Py_ssize_t index; - block *b; - dequeobject *deque; - long state; /* state when the iterator is created */ - Py_ssize_t counter; /* number of items remaining for iteration */ + PyObject_HEAD + Py_ssize_t index; + block *b; + dequeobject *deque; + long state; /* state when the iterator is created */ + Py_ssize_t counter; /* number of items remaining for iteration */ } dequeiterobject; static PyTypeObject dequeiter_type; @@ -1061,107 +1061,107 @@ static PyObject * deque_iter(dequeobject *deque) { - dequeiterobject *it; + dequeiterobject *it; - it = PyObject_GC_New(dequeiterobject, &dequeiter_type); - if (it == NULL) - return NULL; - it->b = deque->leftblock; - it->index = deque->leftindex; - Py_INCREF(deque); - it->deque = deque; - it->state = deque->state; - it->counter = deque->len; - PyObject_GC_Track(it); - return (PyObject *)it; + it = PyObject_GC_New(dequeiterobject, &dequeiter_type); + if (it == NULL) + return NULL; + it->b = deque->leftblock; + it->index = deque->leftindex; + Py_INCREF(deque); + it->deque = deque; + it->state = deque->state; + it->counter = deque->len; + PyObject_GC_Track(it); + return (PyObject *)it; } static int dequeiter_traverse(dequeiterobject *dio, visitproc visit, void *arg) { - Py_VISIT(dio->deque); - return 0; + Py_VISIT(dio->deque); + return 0; } static void dequeiter_dealloc(dequeiterobject *dio) { - Py_XDECREF(dio->deque); - PyObject_GC_Del(dio); + Py_XDECREF(dio->deque); + PyObject_GC_Del(dio); } static PyObject * dequeiter_next(dequeiterobject *it) { - PyObject *item; + PyObject *item; - if (it->deque->state != it->state) { - it->counter = 0; - PyErr_SetString(PyExc_RuntimeError, - "deque mutated during iteration"); - return NULL; - } - if (it->counter == 0) - return NULL; - assert (!(it->b == it->deque->rightblock && - it->index > it->deque->rightindex)); - - item = it->b->data[it->index]; - it->index++; - it->counter--; - if (it->index == BLOCKLEN && it->counter > 0) { - assert (it->b->rightlink != NULL); - it->b = it->b->rightlink; - it->index = 0; - } - Py_INCREF(item); - return item; + if (it->deque->state != it->state) { + it->counter = 0; + PyErr_SetString(PyExc_RuntimeError, + "deque mutated during iteration"); + return NULL; + } + if (it->counter == 0) + return NULL; + assert (!(it->b == it->deque->rightblock && + it->index > it->deque->rightindex)); + + item = it->b->data[it->index]; + it->index++; + it->counter--; + if (it->index == BLOCKLEN && it->counter > 0) { + assert (it->b->rightlink != NULL); + it->b = it->b->rightlink; + it->index = 0; + } + Py_INCREF(item); + return item; } static PyObject * dequeiter_len(dequeiterobject *it) { - return PyLong_FromLong(it->counter); + return PyLong_FromLong(it->counter); } PyDoc_STRVAR(length_hint_doc, "Private method returning an estimate of len(list(it))."); static PyMethodDef dequeiter_methods[] = { - {"__length_hint__", (PyCFunction)dequeiter_len, METH_NOARGS, length_hint_doc}, - {NULL, NULL} /* sentinel */ + {"__length_hint__", (PyCFunction)dequeiter_len, METH_NOARGS, length_hint_doc}, + {NULL, NULL} /* sentinel */ }; static PyTypeObject dequeiter_type = { - PyVarObject_HEAD_INIT(NULL, 0) - "deque_iterator", /* tp_name */ - sizeof(dequeiterobject), /* tp_basicsize */ - 0, /* tp_itemsize */ - /* methods */ - (destructor)dequeiter_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)dequeiter_traverse, /* tp_traverse */ - 0, /* tp_clear */ - 0, /* tp_richcompare */ - 0, /* tp_weaklistoffset */ - PyObject_SelfIter, /* tp_iter */ - (iternextfunc)dequeiter_next, /* tp_iternext */ - dequeiter_methods, /* tp_methods */ - 0, + PyVarObject_HEAD_INIT(NULL, 0) + "deque_iterator", /* tp_name */ + sizeof(dequeiterobject), /* tp_basicsize */ + 0, /* tp_itemsize */ + /* methods */ + (destructor)dequeiter_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)dequeiter_traverse, /* tp_traverse */ + 0, /* tp_clear */ + 0, /* tp_richcompare */ + 0, /* tp_weaklistoffset */ + PyObject_SelfIter, /* tp_iter */ + (iternextfunc)dequeiter_next, /* tp_iternext */ + dequeiter_methods, /* tp_methods */ + 0, }; /*********************** Deque Reverse Iterator **************************/ @@ -1171,87 +1171,87 @@ static PyObject * deque_reviter(dequeobject *deque) { - dequeiterobject *it; + dequeiterobject *it; - it = PyObject_GC_New(dequeiterobject, &dequereviter_type); - if (it == NULL) - return NULL; - it->b = deque->rightblock; - it->index = deque->rightindex; - Py_INCREF(deque); - it->deque = deque; - it->state = deque->state; - it->counter = deque->len; - PyObject_GC_Track(it); - return (PyObject *)it; + it = PyObject_GC_New(dequeiterobject, &dequereviter_type); + if (it == NULL) + return NULL; + it->b = deque->rightblock; + it->index = deque->rightindex; + Py_INCREF(deque); + it->deque = deque; + it->state = deque->state; + it->counter = deque->len; + PyObject_GC_Track(it); + return (PyObject *)it; } static PyObject * dequereviter_next(dequeiterobject *it) { - PyObject *item; - if (it->counter == 0) - return NULL; - - if (it->deque->state != it->state) { - it->counter = 0; - PyErr_SetString(PyExc_RuntimeError, - "deque mutated during iteration"); - return NULL; - } - assert (!(it->b == it->deque->leftblock && - it->index < it->deque->leftindex)); - - item = it->b->data[it->index]; - it->index--; - it->counter--; - if (it->index == -1 && it->counter > 0) { - assert (it->b->leftlink != NULL); - it->b = it->b->leftlink; - it->index = BLOCKLEN - 1; - } - Py_INCREF(item); - return item; + PyObject *item; + if (it->counter == 0) + return NULL; + + if (it->deque->state != it->state) { + it->counter = 0; + PyErr_SetString(PyExc_RuntimeError, + "deque mutated during iteration"); + return NULL; + } + assert (!(it->b == it->deque->leftblock && + it->index < it->deque->leftindex)); + + item = it->b->data[it->index]; + it->index--; + it->counter--; + if (it->index == -1 && it->counter > 0) { + assert (it->b->leftlink != NULL); + it->b = it->b->leftlink; + it->index = BLOCKLEN - 1; + } + Py_INCREF(item); + return item; } static PyTypeObject dequereviter_type = { - PyVarObject_HEAD_INIT(NULL, 0) - "deque_reverse_iterator", /* tp_name */ - sizeof(dequeiterobject), /* tp_basicsize */ - 0, /* tp_itemsize */ - /* methods */ - (destructor)dequeiter_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)dequeiter_traverse, /* tp_traverse */ - 0, /* tp_clear */ - 0, /* tp_richcompare */ - 0, /* tp_weaklistoffset */ - PyObject_SelfIter, /* tp_iter */ - (iternextfunc)dequereviter_next, /* tp_iternext */ - dequeiter_methods, /* tp_methods */ - 0, + PyVarObject_HEAD_INIT(NULL, 0) + "deque_reverse_iterator", /* tp_name */ + sizeof(dequeiterobject), /* tp_basicsize */ + 0, /* tp_itemsize */ + /* methods */ + (destructor)dequeiter_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)dequeiter_traverse, /* tp_traverse */ + 0, /* tp_clear */ + 0, /* tp_richcompare */ + 0, /* tp_weaklistoffset */ + PyObject_SelfIter, /* tp_iter */ + (iternextfunc)dequereviter_next, /* tp_iternext */ + dequeiter_methods, /* tp_methods */ + 0, }; /* defaultdict type *********************************************************/ typedef struct { - PyDictObject dict; - PyObject *default_factory; + PyDictObject dict; + PyObject *default_factory; } defdictobject; static PyTypeObject defdict_type; /* Forward */ @@ -1266,25 +1266,25 @@ static PyObject * defdict_missing(defdictobject *dd, PyObject *key) { - PyObject *factory = dd->default_factory; - PyObject *value; - if (factory == NULL || factory == Py_None) { - /* XXX Call dict.__missing__(key) */ - PyObject *tup; - tup = PyTuple_Pack(1, key); - if (!tup) return NULL; - PyErr_SetObject(PyExc_KeyError, tup); - Py_DECREF(tup); - return NULL; - } - value = PyEval_CallObject(factory, NULL); - if (value == NULL) - return value; - if (PyObject_SetItem((PyObject *)dd, key, value) < 0) { - Py_DECREF(value); - return NULL; - } - return value; + PyObject *factory = dd->default_factory; + PyObject *value; + if (factory == NULL || factory == Py_None) { + /* XXX Call dict.__missing__(key) */ + PyObject *tup; + tup = PyTuple_Pack(1, key); + if (!tup) return NULL; + PyErr_SetObject(PyExc_KeyError, tup); + Py_DECREF(tup); + return NULL; + } + value = PyEval_CallObject(factory, NULL); + if (value == NULL) + return value; + if (PyObject_SetItem((PyObject *)dd, key, value) < 0) { + Py_DECREF(value); + return NULL; + } + return value; } PyDoc_STRVAR(defdict_copy_doc, "D.copy() -> a shallow copy of D."); @@ -1292,175 +1292,175 @@ static PyObject * defdict_copy(defdictobject *dd) { - /* This calls the object's class. That only works for subclasses - whose class constructor has the same signature. Subclasses that - define a different constructor signature must override copy(). - */ - - if (dd->default_factory == NULL) - return PyObject_CallFunctionObjArgs((PyObject*)Py_TYPE(dd), Py_None, dd, NULL); - return PyObject_CallFunctionObjArgs((PyObject*)Py_TYPE(dd), - dd->default_factory, dd, NULL); + /* This calls the object's class. That only works for subclasses + whose class constructor has the same signature. Subclasses that + define a different constructor signature must override copy(). + */ + + if (dd->default_factory == NULL) + return PyObject_CallFunctionObjArgs((PyObject*)Py_TYPE(dd), Py_None, dd, NULL); + return PyObject_CallFunctionObjArgs((PyObject*)Py_TYPE(dd), + dd->default_factory, dd, NULL); } static PyObject * defdict_reduce(defdictobject *dd) { - /* __reduce__ must return a 5-tuple as follows: + /* __reduce__ must return a 5-tuple as follows: - - factory function - - tuple of args for the factory function - - additional state (here None) - - sequence iterator (here None) - - dictionary iterator (yielding successive (key, value) pairs - - This API is used by pickle.py and copy.py. - - For this to be useful with pickle.py, the default_factory - must be picklable; e.g., None, a built-in, or a global - function in a module or package. - - Both shallow and deep copying are supported, but for deep - copying, the default_factory must be deep-copyable; e.g. None, - or a built-in (functions are not copyable at this time). - - This only works for subclasses as long as their constructor - signature is compatible; the first argument must be the - optional default_factory, defaulting to None. - */ - PyObject *args; - PyObject *items; - PyObject *iter; - PyObject *result; - if (dd->default_factory == NULL || dd->default_factory == Py_None) - args = PyTuple_New(0); - else - args = PyTuple_Pack(1, dd->default_factory); - if (args == NULL) - return NULL; - items = PyObject_CallMethod((PyObject *)dd, "items", "()"); - if (items == NULL) { - Py_DECREF(args); - return NULL; - } - iter = PyObject_GetIter(items); - if (iter == NULL) { - Py_DECREF(items); - Py_DECREF(args); - return NULL; - } - result = PyTuple_Pack(5, Py_TYPE(dd), args, - Py_None, Py_None, iter); - Py_DECREF(iter); - Py_DECREF(items); - Py_DECREF(args); - return result; + - factory function + - tuple of args for the factory function + - additional state (here None) + - sequence iterator (here None) + - dictionary iterator (yielding successive (key, value) pairs + + This API is used by pickle.py and copy.py. + + For this to be useful with pickle.py, the default_factory + must be picklable; e.g., None, a built-in, or a global + function in a module or package. + + Both shallow and deep copying are supported, but for deep + copying, the default_factory must be deep-copyable; e.g. None, + or a built-in (functions are not copyable at this time). + + This only works for subclasses as long as their constructor + signature is compatible; the first argument must be the + optional default_factory, defaulting to None. + */ + PyObject *args; + PyObject *items; + PyObject *iter; + PyObject *result; + if (dd->default_factory == NULL || dd->default_factory == Py_None) + args = PyTuple_New(0); + else + args = PyTuple_Pack(1, dd->default_factory); + if (args == NULL) + return NULL; + items = PyObject_CallMethod((PyObject *)dd, "items", "()"); + if (items == NULL) { + Py_DECREF(args); + return NULL; + } + iter = PyObject_GetIter(items); + if (iter == NULL) { + Py_DECREF(items); + Py_DECREF(args); + return NULL; + } + result = PyTuple_Pack(5, Py_TYPE(dd), args, + Py_None, Py_None, iter); + Py_DECREF(iter); + Py_DECREF(items); + Py_DECREF(args); + return result; } static PyMethodDef defdict_methods[] = { - {"__missing__", (PyCFunction)defdict_missing, METH_O, - defdict_missing_doc}, - {"copy", (PyCFunction)defdict_copy, METH_NOARGS, - defdict_copy_doc}, - {"__copy__", (PyCFunction)defdict_copy, METH_NOARGS, - defdict_copy_doc}, - {"__reduce__", (PyCFunction)defdict_reduce, METH_NOARGS, - reduce_doc}, - {NULL} + {"__missing__", (PyCFunction)defdict_missing, METH_O, + defdict_missing_doc}, + {"copy", (PyCFunction)defdict_copy, METH_NOARGS, + defdict_copy_doc}, + {"__copy__", (PyCFunction)defdict_copy, METH_NOARGS, + defdict_copy_doc}, + {"__reduce__", (PyCFunction)defdict_reduce, METH_NOARGS, + reduce_doc}, + {NULL} }; static PyMemberDef defdict_members[] = { - {"default_factory", T_OBJECT, - offsetof(defdictobject, default_factory), 0, - PyDoc_STR("Factory for default value called by __missing__().")}, - {NULL} + {"default_factory", T_OBJECT, + offsetof(defdictobject, default_factory), 0, + PyDoc_STR("Factory for default value called by __missing__().")}, + {NULL} }; static void defdict_dealloc(defdictobject *dd) { - Py_CLEAR(dd->default_factory); - PyDict_Type.tp_dealloc((PyObject *)dd); + Py_CLEAR(dd->default_factory); + PyDict_Type.tp_dealloc((PyObject *)dd); } static PyObject * defdict_repr(defdictobject *dd) { - PyObject *baserepr; - PyObject *defrepr; - PyObject *result; - baserepr = PyDict_Type.tp_repr((PyObject *)dd); - if (baserepr == NULL) - return NULL; - if (dd->default_factory == NULL) - defrepr = PyUnicode_FromString("None"); - else - { - int status = Py_ReprEnter(dd->default_factory); - if (status != 0) { - if (status < 0) - return NULL; - defrepr = PyUnicode_FromString("..."); - } - else - defrepr = PyObject_Repr(dd->default_factory); - Py_ReprLeave(dd->default_factory); - } - if (defrepr == NULL) { - Py_DECREF(baserepr); - return NULL; - } - result = PyUnicode_FromFormat("defaultdict(%U, %U)", - defrepr, baserepr); - Py_DECREF(defrepr); - Py_DECREF(baserepr); - return result; + PyObject *baserepr; + PyObject *defrepr; + PyObject *result; + baserepr = PyDict_Type.tp_repr((PyObject *)dd); + if (baserepr == NULL) + return NULL; + if (dd->default_factory == NULL) + defrepr = PyUnicode_FromString("None"); + else + { + int status = Py_ReprEnter(dd->default_factory); + if (status != 0) { + if (status < 0) + return NULL; + defrepr = PyUnicode_FromString("..."); + } + else + defrepr = PyObject_Repr(dd->default_factory); + Py_ReprLeave(dd->default_factory); + } + if (defrepr == NULL) { + Py_DECREF(baserepr); + return NULL; + } + result = PyUnicode_FromFormat("defaultdict(%U, %U)", + defrepr, baserepr); + Py_DECREF(defrepr); + Py_DECREF(baserepr); + return result; } static int defdict_traverse(PyObject *self, visitproc visit, void *arg) { - Py_VISIT(((defdictobject *)self)->default_factory); - return PyDict_Type.tp_traverse(self, visit, arg); + Py_VISIT(((defdictobject *)self)->default_factory); + return PyDict_Type.tp_traverse(self, visit, arg); } static int defdict_tp_clear(defdictobject *dd) { - Py_CLEAR(dd->default_factory); - return PyDict_Type.tp_clear((PyObject *)dd); + Py_CLEAR(dd->default_factory); + return PyDict_Type.tp_clear((PyObject *)dd); } static int defdict_init(PyObject *self, PyObject *args, PyObject *kwds) { - defdictobject *dd = (defdictobject *)self; - PyObject *olddefault = dd->default_factory; - PyObject *newdefault = NULL; - PyObject *newargs; - int result; - if (args == NULL || !PyTuple_Check(args)) - newargs = PyTuple_New(0); - else { - Py_ssize_t n = PyTuple_GET_SIZE(args); - if (n > 0) { - newdefault = PyTuple_GET_ITEM(args, 0); - if (!PyCallable_Check(newdefault) && newdefault != Py_None) { - PyErr_SetString(PyExc_TypeError, - "first argument must be callable"); - return -1; - } - } - newargs = PySequence_GetSlice(args, 1, n); - } - if (newargs == NULL) - return -1; - Py_XINCREF(newdefault); - dd->default_factory = newdefault; - result = PyDict_Type.tp_init(self, newargs, kwds); - Py_DECREF(newargs); - Py_XDECREF(olddefault); - return result; + defdictobject *dd = (defdictobject *)self; + PyObject *olddefault = dd->default_factory; + PyObject *newdefault = NULL; + PyObject *newargs; + int result; + if (args == NULL || !PyTuple_Check(args)) + newargs = PyTuple_New(0); + else { + Py_ssize_t n = PyTuple_GET_SIZE(args); + if (n > 0) { + newdefault = PyTuple_GET_ITEM(args, 0); + if (!PyCallable_Check(newdefault) && newdefault != Py_None) { + PyErr_SetString(PyExc_TypeError, + "first argument must be callable"); + return -1; + } + } + newargs = PySequence_GetSlice(args, 1, n); + } + if (newargs == NULL) + return -1; + Py_XINCREF(newdefault); + dd->default_factory = newdefault; + result = PyDict_Type.tp_init(self, newargs, kwds); + Py_DECREF(newargs); + Py_XDECREF(olddefault); + return result; } PyDoc_STRVAR(defdict_doc, @@ -1475,47 +1475,47 @@ #define DEFERRED_ADDRESS(ADDR) 0 static PyTypeObject defdict_type = { - PyVarObject_HEAD_INIT(DEFERRED_ADDRESS(&PyType_Type), 0) - "collections.defaultdict", /* tp_name */ - sizeof(defdictobject), /* tp_basicsize */ - 0, /* tp_itemsize */ - /* methods */ - (destructor)defdict_dealloc, /* tp_dealloc */ - 0, /* tp_print */ - 0, /* tp_getattr */ - 0, /* tp_setattr */ - 0, /* tp_reserved */ - (reprfunc)defdict_repr, /* 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_BASETYPE | Py_TPFLAGS_HAVE_GC, - /* tp_flags */ - defdict_doc, /* tp_doc */ - defdict_traverse, /* tp_traverse */ - (inquiry)defdict_tp_clear, /* tp_clear */ - 0, /* tp_richcompare */ - 0, /* tp_weaklistoffset*/ - 0, /* tp_iter */ - 0, /* tp_iternext */ - defdict_methods, /* tp_methods */ - defdict_members, /* tp_members */ - 0, /* tp_getset */ - DEFERRED_ADDRESS(&PyDict_Type), /* tp_base */ - 0, /* tp_dict */ - 0, /* tp_descr_get */ - 0, /* tp_descr_set */ - 0, /* tp_dictoffset */ - defdict_init, /* tp_init */ - PyType_GenericAlloc, /* tp_alloc */ - 0, /* tp_new */ - PyObject_GC_Del, /* tp_free */ + PyVarObject_HEAD_INIT(DEFERRED_ADDRESS(&PyType_Type), 0) + "collections.defaultdict", /* tp_name */ + sizeof(defdictobject), /* tp_basicsize */ + 0, /* tp_itemsize */ + /* methods */ + (destructor)defdict_dealloc, /* tp_dealloc */ + 0, /* tp_print */ + 0, /* tp_getattr */ + 0, /* tp_setattr */ + 0, /* tp_reserved */ + (reprfunc)defdict_repr, /* 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_BASETYPE | Py_TPFLAGS_HAVE_GC, + /* tp_flags */ + defdict_doc, /* tp_doc */ + defdict_traverse, /* tp_traverse */ + (inquiry)defdict_tp_clear, /* tp_clear */ + 0, /* tp_richcompare */ + 0, /* tp_weaklistoffset*/ + 0, /* tp_iter */ + 0, /* tp_iternext */ + defdict_methods, /* tp_methods */ + defdict_members, /* tp_members */ + 0, /* tp_getset */ + DEFERRED_ADDRESS(&PyDict_Type), /* tp_base */ + 0, /* tp_dict */ + 0, /* tp_descr_get */ + 0, /* tp_descr_set */ + 0, /* tp_dictoffset */ + defdict_init, /* tp_init */ + PyType_GenericAlloc, /* tp_alloc */ + 0, /* tp_new */ + PyObject_GC_Del, /* tp_free */ }; /* module level code ********************************************************/ @@ -1528,42 +1528,42 @@ static struct PyModuleDef _collectionsmodule = { - PyModuleDef_HEAD_INIT, - "_collections", - module_doc, - -1, - NULL, - NULL, - NULL, - NULL, - NULL + PyModuleDef_HEAD_INIT, + "_collections", + module_doc, + -1, + NULL, + NULL, + NULL, + NULL, + NULL }; PyMODINIT_FUNC PyInit__collections(void) { - PyObject *m; + PyObject *m; - m = PyModule_Create(&_collectionsmodule); - if (m == NULL) - return NULL; - - if (PyType_Ready(&deque_type) < 0) - return NULL; - Py_INCREF(&deque_type); - PyModule_AddObject(m, "deque", (PyObject *)&deque_type); - - defdict_type.tp_base = &PyDict_Type; - if (PyType_Ready(&defdict_type) < 0) - return NULL; - Py_INCREF(&defdict_type); - PyModule_AddObject(m, "defaultdict", (PyObject *)&defdict_type); + m = PyModule_Create(&_collectionsmodule); + if (m == NULL) + return NULL; + + if (PyType_Ready(&deque_type) < 0) + return NULL; + Py_INCREF(&deque_type); + PyModule_AddObject(m, "deque", (PyObject *)&deque_type); + + defdict_type.tp_base = &PyDict_Type; + if (PyType_Ready(&defdict_type) < 0) + return NULL; + Py_INCREF(&defdict_type); + PyModule_AddObject(m, "defaultdict", (PyObject *)&defdict_type); - if (PyType_Ready(&dequeiter_type) < 0) - return NULL; + if (PyType_Ready(&dequeiter_type) < 0) + return NULL; - if (PyType_Ready(&dequereviter_type) < 0) - return NULL; + if (PyType_Ready(&dequereviter_type) < 0) + return NULL; - return m; + return m; } Modified: python/branches/py3k-jit/Modules/_csv.c ============================================================================== --- python/branches/py3k-jit/Modules/_csv.c (original) +++ python/branches/py3k-jit/Modules/_csv.c Mon May 10 23:55:43 2010 @@ -18,65 +18,65 @@ #include "structmember.h" #define IS_BASESTRING(o) \ - PyUnicode_Check(o) + PyUnicode_Check(o) -static PyObject *error_obj; /* CSV exception */ +static PyObject *error_obj; /* CSV exception */ static PyObject *dialects; /* Dialect registry */ -static long field_limit = 128 * 1024; /* max parsed field size */ +static long field_limit = 128 * 1024; /* max parsed field size */ typedef enum { - START_RECORD, START_FIELD, ESCAPED_CHAR, IN_FIELD, - IN_QUOTED_FIELD, ESCAPE_IN_QUOTED_FIELD, QUOTE_IN_QUOTED_FIELD, - EAT_CRNL + START_RECORD, START_FIELD, ESCAPED_CHAR, IN_FIELD, + IN_QUOTED_FIELD, ESCAPE_IN_QUOTED_FIELD, QUOTE_IN_QUOTED_FIELD, + EAT_CRNL } ParserState; typedef enum { - QUOTE_MINIMAL, QUOTE_ALL, QUOTE_NONNUMERIC, QUOTE_NONE + QUOTE_MINIMAL, QUOTE_ALL, QUOTE_NONNUMERIC, QUOTE_NONE } QuoteStyle; typedef struct { - QuoteStyle style; - char *name; + QuoteStyle style; + char *name; } StyleDesc; static StyleDesc quote_styles[] = { - { QUOTE_MINIMAL, "QUOTE_MINIMAL" }, - { QUOTE_ALL, "QUOTE_ALL" }, - { QUOTE_NONNUMERIC, "QUOTE_NONNUMERIC" }, - { QUOTE_NONE, "QUOTE_NONE" }, - { 0 } + { QUOTE_MINIMAL, "QUOTE_MINIMAL" }, + { QUOTE_ALL, "QUOTE_ALL" }, + { QUOTE_NONNUMERIC, "QUOTE_NONNUMERIC" }, + { QUOTE_NONE, "QUOTE_NONE" }, + { 0 } }; typedef struct { - PyObject_HEAD + PyObject_HEAD - int doublequote; /* is " represented by ""? */ - Py_UNICODE delimiter; /* field separator */ - Py_UNICODE quotechar; /* quote character */ - Py_UNICODE escapechar; /* escape character */ - int skipinitialspace; /* ignore spaces following delimiter? */ - PyObject *lineterminator; /* string to write between records */ - int quoting; /* style of quoting to write */ + int doublequote; /* is " represented by ""? */ + Py_UNICODE delimiter; /* field separator */ + Py_UNICODE quotechar; /* quote character */ + Py_UNICODE escapechar; /* escape character */ + int skipinitialspace; /* ignore spaces following delimiter? */ + PyObject *lineterminator; /* string to write between records */ + int quoting; /* style of quoting to write */ - int strict; /* raise exception on bad CSV */ + int strict; /* raise exception on bad CSV */ } DialectObj; static PyTypeObject Dialect_Type; typedef struct { - PyObject_HEAD + PyObject_HEAD - PyObject *input_iter; /* iterate over this for input lines */ + PyObject *input_iter; /* iterate over this for input lines */ - DialectObj *dialect; /* parsing dialect */ + DialectObj *dialect; /* parsing dialect */ - PyObject *fields; /* field list for current record */ - ParserState state; /* current CSV parse state */ - Py_UNICODE *field; /* build current field in here */ - int field_size; /* size of allocated buffer */ - Py_ssize_t field_len; /* length of current field */ - int numeric_field; /* treat field as numeric */ - unsigned long line_num; /* Source-file line number */ + PyObject *fields; /* field list for current record */ + ParserState state; /* current CSV parse state */ + Py_UNICODE *field; /* build current field in here */ + int field_size; /* size of allocated buffer */ + Py_ssize_t field_len; /* length of current field */ + int numeric_field; /* treat field as numeric */ + unsigned long line_num; /* Source-file line number */ } ReaderObj; static PyTypeObject Reader_Type; @@ -84,16 +84,16 @@ #define ReaderObject_Check(v) (Py_TYPE(v) == &Reader_Type) typedef struct { - PyObject_HEAD + PyObject_HEAD - PyObject *writeline; /* write output lines to this file */ + PyObject *writeline; /* write output lines to this file */ - DialectObj *dialect; /* parsing dialect */ + DialectObj *dialect; /* parsing dialect */ - Py_UNICODE *rec; /* buffer for parser.join */ - int rec_size; /* size of allocated record */ - Py_ssize_t rec_len; /* length of record */ - int num_fields; /* number of fields in record */ + Py_UNICODE *rec; /* buffer for parser.join */ + int rec_size; /* size of allocated record */ + Py_ssize_t rec_len; /* length of record */ + int num_fields; /* number of fields in record */ } WriterObj; static PyTypeObject Writer_Type; @@ -105,375 +105,375 @@ static PyObject * get_dialect_from_registry(PyObject * name_obj) { - PyObject *dialect_obj; + PyObject *dialect_obj; - dialect_obj = PyDict_GetItem(dialects, name_obj); - if (dialect_obj == NULL) { - if (!PyErr_Occurred()) - PyErr_Format(error_obj, "unknown dialect"); - } - else - Py_INCREF(dialect_obj); - return dialect_obj; + dialect_obj = PyDict_GetItem(dialects, name_obj); + if (dialect_obj == NULL) { + if (!PyErr_Occurred()) + PyErr_Format(error_obj, "unknown dialect"); + } + else + Py_INCREF(dialect_obj); + return dialect_obj; } static PyObject * get_string(PyObject *str) { - Py_XINCREF(str); - return str; + Py_XINCREF(str); + return str; } static PyObject * get_nullchar_as_None(Py_UNICODE c) { - if (c == '\0') { - Py_INCREF(Py_None); - return Py_None; - } - else - return PyUnicode_FromUnicode((Py_UNICODE *)&c, 1); + if (c == '\0') { + Py_INCREF(Py_None); + return Py_None; + } + else + return PyUnicode_FromUnicode((Py_UNICODE *)&c, 1); } static PyObject * Dialect_get_lineterminator(DialectObj *self) { - return get_string(self->lineterminator); + return get_string(self->lineterminator); } static PyObject * Dialect_get_delimiter(DialectObj *self) { - return get_nullchar_as_None(self->delimiter); + return get_nullchar_as_None(self->delimiter); } static PyObject * Dialect_get_escapechar(DialectObj *self) { - return get_nullchar_as_None(self->escapechar); + return get_nullchar_as_None(self->escapechar); } static PyObject * Dialect_get_quotechar(DialectObj *self) { - return get_nullchar_as_None(self->quotechar); + return get_nullchar_as_None(self->quotechar); } static PyObject * Dialect_get_quoting(DialectObj *self) { - return PyLong_FromLong(self->quoting); + return PyLong_FromLong(self->quoting); } static int _set_bool(const char *name, int *target, PyObject *src, int dflt) { - if (src == NULL) - *target = dflt; - else - *target = PyObject_IsTrue(src); - return 0; + if (src == NULL) + *target = dflt; + else + *target = PyObject_IsTrue(src); + return 0; } static int _set_int(const char *name, int *target, PyObject *src, int dflt) { - if (src == NULL) - *target = dflt; - else { - long value; - if (!PyLong_CheckExact(src)) { - PyErr_Format(PyExc_TypeError, - "\"%s\" must be an integer", name); - return -1; - } - value = PyLong_AsLong(src); - if (value == -1 && PyErr_Occurred()) - return -1; + if (src == NULL) + *target = dflt; + else { + long value; + if (!PyLong_CheckExact(src)) { + PyErr_Format(PyExc_TypeError, + "\"%s\" must be an integer", name); + return -1; + } + value = PyLong_AsLong(src); + if (value == -1 && PyErr_Occurred()) + return -1; #if SIZEOF_LONG > SIZEOF_INT - if (value > INT_MAX || value < INT_MIN) { - PyErr_Format(PyExc_ValueError, - "integer out of range for \"%s\"", name); - return -1; - } + if (value > INT_MAX || value < INT_MIN) { + PyErr_Format(PyExc_ValueError, + "integer out of range for \"%s\"", name); + return -1; + } #endif - *target = (int)value; - } - return 0; + *target = (int)value; + } + return 0; } static int _set_char(const char *name, Py_UNICODE *target, PyObject *src, Py_UNICODE dflt) { - if (src == NULL) - *target = dflt; - else { - *target = '\0'; - if (src != Py_None) { - Py_UNICODE *buf; - Py_ssize_t len; - buf = PyUnicode_AsUnicode(src); - len = PyUnicode_GetSize(src); - if (buf == NULL || len > 1) { - PyErr_Format(PyExc_TypeError, - "\"%s\" must be an 1-character string", - name); - return -1; - } - if (len > 0) - *target = buf[0]; - } - } - return 0; + if (src == NULL) + *target = dflt; + else { + *target = '\0'; + if (src != Py_None) { + Py_UNICODE *buf; + Py_ssize_t len; + buf = PyUnicode_AsUnicode(src); + len = PyUnicode_GetSize(src); + if (buf == NULL || len > 1) { + PyErr_Format(PyExc_TypeError, + "\"%s\" must be an 1-character string", + name); + return -1; + } + if (len > 0) + *target = buf[0]; + } + } + return 0; } static int _set_str(const char *name, PyObject **target, PyObject *src, const char *dflt) { - if (src == NULL) - *target = PyUnicode_DecodeASCII(dflt, strlen(dflt), NULL); - else { - if (src == Py_None) - *target = NULL; - else if (!IS_BASESTRING(src)) { - PyErr_Format(PyExc_TypeError, - "\"%s\" must be a string", name); - return -1; - } - else { - Py_XDECREF(*target); - Py_INCREF(src); - *target = src; - } - } - return 0; + if (src == NULL) + *target = PyUnicode_DecodeASCII(dflt, strlen(dflt), NULL); + else { + if (src == Py_None) + *target = NULL; + else if (!IS_BASESTRING(src)) { + PyErr_Format(PyExc_TypeError, + "\"%s\" must be a string", name); + return -1; + } + else { + Py_XDECREF(*target); + Py_INCREF(src); + *target = src; + } + } + return 0; } static int dialect_check_quoting(int quoting) { - StyleDesc *qs = quote_styles; + StyleDesc *qs = quote_styles; - for (qs = quote_styles; qs->name; qs++) { - if (qs->style == quoting) - return 0; - } - PyErr_Format(PyExc_TypeError, "bad \"quoting\" value"); - return -1; + for (qs = quote_styles; qs->name; qs++) { + if (qs->style == quoting) + return 0; + } + PyErr_Format(PyExc_TypeError, "bad \"quoting\" value"); + return -1; } #define D_OFF(x) offsetof(DialectObj, x) static struct PyMemberDef Dialect_memberlist[] = { - { "skipinitialspace", T_INT, D_OFF(skipinitialspace), READONLY }, - { "doublequote", T_INT, D_OFF(doublequote), READONLY }, - { "strict", T_INT, D_OFF(strict), READONLY }, - { NULL } + { "skipinitialspace", T_INT, D_OFF(skipinitialspace), READONLY }, + { "doublequote", T_INT, D_OFF(doublequote), READONLY }, + { "strict", T_INT, D_OFF(strict), READONLY }, + { NULL } }; static PyGetSetDef Dialect_getsetlist[] = { - { "delimiter", (getter)Dialect_get_delimiter}, - { "escapechar", (getter)Dialect_get_escapechar}, - { "lineterminator", (getter)Dialect_get_lineterminator}, - { "quotechar", (getter)Dialect_get_quotechar}, - { "quoting", (getter)Dialect_get_quoting}, - {NULL}, + { "delimiter", (getter)Dialect_get_delimiter}, + { "escapechar", (getter)Dialect_get_escapechar}, + { "lineterminator", (getter)Dialect_get_lineterminator}, + { "quotechar", (getter)Dialect_get_quotechar}, + { "quoting", (getter)Dialect_get_quoting}, + {NULL}, }; static void Dialect_dealloc(DialectObj *self) { - Py_XDECREF(self->lineterminator); - Py_TYPE(self)->tp_free((PyObject *)self); + Py_XDECREF(self->lineterminator); + Py_TYPE(self)->tp_free((PyObject *)self); } static char *dialect_kws[] = { - "dialect", - "delimiter", - "doublequote", - "escapechar", - "lineterminator", - "quotechar", - "quoting", - "skipinitialspace", - "strict", - NULL + "dialect", + "delimiter", + "doublequote", + "escapechar", + "lineterminator", + "quotechar", + "quoting", + "skipinitialspace", + "strict", + NULL }; static PyObject * dialect_new(PyTypeObject *type, PyObject *args, PyObject *kwargs) { - DialectObj *self; - PyObject *ret = NULL; - PyObject *dialect = NULL; - PyObject *delimiter = NULL; - PyObject *doublequote = NULL; - PyObject *escapechar = NULL; - PyObject *lineterminator = NULL; - PyObject *quotechar = NULL; - PyObject *quoting = NULL; - PyObject *skipinitialspace = NULL; - PyObject *strict = NULL; - - if (!PyArg_ParseTupleAndKeywords(args, kwargs, - "|OOOOOOOOO", dialect_kws, - &dialect, - &delimiter, - &doublequote, - &escapechar, - &lineterminator, - "echar, - "ing, - &skipinitialspace, - &strict)) - return NULL; - - if (dialect != NULL) { - if (IS_BASESTRING(dialect)) { - dialect = get_dialect_from_registry(dialect); - if (dialect == NULL) - return NULL; - } - else - Py_INCREF(dialect); - /* Can we reuse this instance? */ - if (PyObject_TypeCheck(dialect, &Dialect_Type) && - delimiter == 0 && - doublequote == 0 && - escapechar == 0 && - lineterminator == 0 && - quotechar == 0 && - quoting == 0 && - skipinitialspace == 0 && - strict == 0) - return dialect; - } - - self = (DialectObj *)type->tp_alloc(type, 0); - if (self == NULL) { - Py_XDECREF(dialect); - return NULL; - } - self->lineterminator = NULL; - - Py_XINCREF(delimiter); - Py_XINCREF(doublequote); - Py_XINCREF(escapechar); - Py_XINCREF(lineterminator); - Py_XINCREF(quotechar); - Py_XINCREF(quoting); - Py_XINCREF(skipinitialspace); - Py_XINCREF(strict); - if (dialect != NULL) { + DialectObj *self; + PyObject *ret = NULL; + PyObject *dialect = NULL; + PyObject *delimiter = NULL; + PyObject *doublequote = NULL; + PyObject *escapechar = NULL; + PyObject *lineterminator = NULL; + PyObject *quotechar = NULL; + PyObject *quoting = NULL; + PyObject *skipinitialspace = NULL; + PyObject *strict = NULL; + + if (!PyArg_ParseTupleAndKeywords(args, kwargs, + "|OOOOOOOOO", dialect_kws, + &dialect, + &delimiter, + &doublequote, + &escapechar, + &lineterminator, + "echar, + "ing, + &skipinitialspace, + &strict)) + return NULL; + + if (dialect != NULL) { + if (IS_BASESTRING(dialect)) { + dialect = get_dialect_from_registry(dialect); + if (dialect == NULL) + return NULL; + } + else + Py_INCREF(dialect); + /* Can we reuse this instance? */ + if (PyObject_TypeCheck(dialect, &Dialect_Type) && + delimiter == 0 && + doublequote == 0 && + escapechar == 0 && + lineterminator == 0 && + quotechar == 0 && + quoting == 0 && + skipinitialspace == 0 && + strict == 0) + return dialect; + } + + self = (DialectObj *)type->tp_alloc(type, 0); + if (self == NULL) { + Py_XDECREF(dialect); + return NULL; + } + self->lineterminator = NULL; + + Py_XINCREF(delimiter); + Py_XINCREF(doublequote); + Py_XINCREF(escapechar); + Py_XINCREF(lineterminator); + Py_XINCREF(quotechar); + Py_XINCREF(quoting); + Py_XINCREF(skipinitialspace); + Py_XINCREF(strict); + if (dialect != NULL) { #define DIALECT_GETATTR(v, n) \ - if (v == NULL) \ - v = PyObject_GetAttrString(dialect, n) - DIALECT_GETATTR(delimiter, "delimiter"); - DIALECT_GETATTR(doublequote, "doublequote"); - DIALECT_GETATTR(escapechar, "escapechar"); - DIALECT_GETATTR(lineterminator, "lineterminator"); - DIALECT_GETATTR(quotechar, "quotechar"); - DIALECT_GETATTR(quoting, "quoting"); - DIALECT_GETATTR(skipinitialspace, "skipinitialspace"); - DIALECT_GETATTR(strict, "strict"); - PyErr_Clear(); - } + if (v == NULL) \ + v = PyObject_GetAttrString(dialect, n) + DIALECT_GETATTR(delimiter, "delimiter"); + DIALECT_GETATTR(doublequote, "doublequote"); + DIALECT_GETATTR(escapechar, "escapechar"); + DIALECT_GETATTR(lineterminator, "lineterminator"); + DIALECT_GETATTR(quotechar, "quotechar"); + DIALECT_GETATTR(quoting, "quoting"); + DIALECT_GETATTR(skipinitialspace, "skipinitialspace"); + DIALECT_GETATTR(strict, "strict"); + PyErr_Clear(); + } - /* check types and convert to C values */ + /* check types and convert to C values */ #define DIASET(meth, name, target, src, dflt) \ - if (meth(name, target, src, dflt)) \ - goto err - DIASET(_set_char, "delimiter", &self->delimiter, delimiter, ','); - DIASET(_set_bool, "doublequote", &self->doublequote, doublequote, 1); - DIASET(_set_char, "escapechar", &self->escapechar, escapechar, 0); - DIASET(_set_str, "lineterminator", &self->lineterminator, lineterminator, "\r\n"); - DIASET(_set_char, "quotechar", &self->quotechar, quotechar, '"'); - DIASET(_set_int, "quoting", &self->quoting, quoting, QUOTE_MINIMAL); - DIASET(_set_bool, "skipinitialspace", &self->skipinitialspace, skipinitialspace, 0); - DIASET(_set_bool, "strict", &self->strict, strict, 0); - - /* validate options */ - if (dialect_check_quoting(self->quoting)) - goto err; - if (self->delimiter == 0) { - PyErr_SetString(PyExc_TypeError, "delimiter must be set"); - goto err; - } - if (quotechar == Py_None && quoting == NULL) - self->quoting = QUOTE_NONE; - if (self->quoting != QUOTE_NONE && self->quotechar == 0) { - PyErr_SetString(PyExc_TypeError, - "quotechar must be set if quoting enabled"); - goto err; - } - if (self->lineterminator == 0) { - PyErr_SetString(PyExc_TypeError, "lineterminator must be set"); - goto err; - } + if (meth(name, target, src, dflt)) \ + goto err + DIASET(_set_char, "delimiter", &self->delimiter, delimiter, ','); + DIASET(_set_bool, "doublequote", &self->doublequote, doublequote, 1); + DIASET(_set_char, "escapechar", &self->escapechar, escapechar, 0); + DIASET(_set_str, "lineterminator", &self->lineterminator, lineterminator, "\r\n"); + DIASET(_set_char, "quotechar", &self->quotechar, quotechar, '"'); + DIASET(_set_int, "quoting", &self->quoting, quoting, QUOTE_MINIMAL); + DIASET(_set_bool, "skipinitialspace", &self->skipinitialspace, skipinitialspace, 0); + DIASET(_set_bool, "strict", &self->strict, strict, 0); + + /* validate options */ + if (dialect_check_quoting(self->quoting)) + goto err; + if (self->delimiter == 0) { + PyErr_SetString(PyExc_TypeError, "delimiter must be set"); + goto err; + } + if (quotechar == Py_None && quoting == NULL) + self->quoting = QUOTE_NONE; + if (self->quoting != QUOTE_NONE && self->quotechar == 0) { + PyErr_SetString(PyExc_TypeError, + "quotechar must be set if quoting enabled"); + goto err; + } + if (self->lineterminator == 0) { + PyErr_SetString(PyExc_TypeError, "lineterminator must be set"); + goto err; + } - ret = (PyObject *)self; - Py_INCREF(self); + ret = (PyObject *)self; + Py_INCREF(self); err: - Py_XDECREF(self); - Py_XDECREF(dialect); - Py_XDECREF(delimiter); - Py_XDECREF(doublequote); - Py_XDECREF(escapechar); - Py_XDECREF(lineterminator); - Py_XDECREF(quotechar); - Py_XDECREF(quoting); - Py_XDECREF(skipinitialspace); - Py_XDECREF(strict); - return ret; + Py_XDECREF(self); + Py_XDECREF(dialect); + Py_XDECREF(delimiter); + Py_XDECREF(doublequote); + Py_XDECREF(escapechar); + Py_XDECREF(lineterminator); + Py_XDECREF(quotechar); + Py_XDECREF(quoting); + Py_XDECREF(skipinitialspace); + Py_XDECREF(strict); + return ret; } -PyDoc_STRVAR(Dialect_Type_doc, +PyDoc_STRVAR(Dialect_Type_doc, "CSV dialect\n" "\n" "The Dialect type records CSV parsing and generation options.\n"); static PyTypeObject Dialect_Type = { - PyVarObject_HEAD_INIT(NULL, 0) - "_csv.Dialect", /* tp_name */ - sizeof(DialectObj), /* tp_basicsize */ - 0, /* tp_itemsize */ - /* methods */ - (destructor)Dialect_dealloc, /* tp_dealloc */ - (printfunc)0, /* tp_print */ - (getattrfunc)0, /* tp_getattr */ - (setattrfunc)0, /* tp_setattr */ - 0, /* tp_reserved */ - (reprfunc)0, /* tp_repr */ - 0, /* tp_as_number */ - 0, /* tp_as_sequence */ - 0, /* tp_as_mapping */ - (hashfunc)0, /* tp_hash */ - (ternaryfunc)0, /* tp_call */ - (reprfunc)0, /* tp_str */ - 0, /* tp_getattro */ - 0, /* tp_setattro */ - 0, /* tp_as_buffer */ - Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */ - Dialect_Type_doc, /* tp_doc */ - 0, /* tp_traverse */ - 0, /* tp_clear */ - 0, /* tp_richcompare */ - 0, /* tp_weaklistoffset */ - 0, /* tp_iter */ - 0, /* tp_iternext */ - 0, /* tp_methods */ - Dialect_memberlist, /* tp_members */ - Dialect_getsetlist, /* tp_getset */ - 0, /* tp_base */ - 0, /* tp_dict */ - 0, /* tp_descr_get */ - 0, /* tp_descr_set */ - 0, /* tp_dictoffset */ - 0, /* tp_init */ - 0, /* tp_alloc */ - dialect_new, /* tp_new */ - 0, /* tp_free */ + PyVarObject_HEAD_INIT(NULL, 0) + "_csv.Dialect", /* tp_name */ + sizeof(DialectObj), /* tp_basicsize */ + 0, /* tp_itemsize */ + /* methods */ + (destructor)Dialect_dealloc, /* tp_dealloc */ + (printfunc)0, /* tp_print */ + (getattrfunc)0, /* tp_getattr */ + (setattrfunc)0, /* tp_setattr */ + 0, /* tp_reserved */ + (reprfunc)0, /* tp_repr */ + 0, /* tp_as_number */ + 0, /* tp_as_sequence */ + 0, /* tp_as_mapping */ + (hashfunc)0, /* tp_hash */ + (ternaryfunc)0, /* tp_call */ + (reprfunc)0, /* tp_str */ + 0, /* tp_getattro */ + 0, /* tp_setattro */ + 0, /* tp_as_buffer */ + Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */ + Dialect_Type_doc, /* tp_doc */ + 0, /* tp_traverse */ + 0, /* tp_clear */ + 0, /* tp_richcompare */ + 0, /* tp_weaklistoffset */ + 0, /* tp_iter */ + 0, /* tp_iternext */ + 0, /* tp_methods */ + Dialect_memberlist, /* tp_members */ + Dialect_getsetlist, /* tp_getset */ + 0, /* tp_base */ + 0, /* tp_dict */ + 0, /* tp_descr_get */ + 0, /* tp_descr_set */ + 0, /* tp_dictoffset */ + 0, /* tp_init */ + 0, /* tp_alloc */ + dialect_new, /* tp_new */ + 0, /* tp_free */ }; /* @@ -483,15 +483,15 @@ static PyObject * _call_dialect(PyObject *dialect_inst, PyObject *kwargs) { - PyObject *ctor_args; - PyObject *dialect; + PyObject *ctor_args; + PyObject *dialect; - ctor_args = Py_BuildValue(dialect_inst ? "(O)" : "()", dialect_inst); - if (ctor_args == NULL) - return NULL; - dialect = PyObject_Call((PyObject *)&Dialect_Type, ctor_args, kwargs); - Py_DECREF(ctor_args); - return dialect; + ctor_args = Py_BuildValue(dialect_inst ? "(O)" : "()", dialect_inst); + if (ctor_args == NULL) + return NULL; + dialect = PyObject_Call((PyObject *)&Dialect_Type, ctor_args, kwargs); + Py_DECREF(ctor_args); + return dialect; } /* @@ -500,339 +500,339 @@ static int parse_save_field(ReaderObj *self) { - PyObject *field; + PyObject *field; - field = PyUnicode_FromUnicode(self->field, self->field_len); - if (field == NULL) - return -1; - self->field_len = 0; - if (self->numeric_field) { - PyObject *tmp; - - self->numeric_field = 0; - tmp = PyNumber_Float(field); - if (tmp == NULL) { - Py_DECREF(field); - return -1; - } - Py_DECREF(field); - field = tmp; - } - PyList_Append(self->fields, field); - Py_DECREF(field); - return 0; + field = PyUnicode_FromUnicode(self->field, self->field_len); + if (field == NULL) + return -1; + self->field_len = 0; + if (self->numeric_field) { + PyObject *tmp; + + self->numeric_field = 0; + tmp = PyNumber_Float(field); + if (tmp == NULL) { + Py_DECREF(field); + return -1; + } + Py_DECREF(field); + field = tmp; + } + PyList_Append(self->fields, field); + Py_DECREF(field); + return 0; } 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_New(Py_UNICODE, self->field_size); - } - else { - if (self->field_size > INT_MAX / 2) { - PyErr_NoMemory(); - return 0; - } - self->field_size *= 2; - self->field = PyMem_Resize(self->field, Py_UNICODE, - self->field_size); - } - if (self->field == NULL) { - PyErr_NoMemory(); - return 0; - } - return 1; + if (self->field_size == 0) { + self->field_size = 4096; + if (self->field != NULL) + PyMem_Free(self->field); + self->field = PyMem_New(Py_UNICODE, self->field_size); + } + else { + if (self->field_size > INT_MAX / 2) { + PyErr_NoMemory(); + return 0; + } + self->field_size *= 2; + self->field = PyMem_Resize(self->field, Py_UNICODE, + self->field_size); + } + if (self->field == NULL) { + PyErr_NoMemory(); + return 0; + } + return 1; } static int parse_add_char(ReaderObj *self, Py_UNICODE c) { - if (self->field_len >= field_limit) { - PyErr_Format(error_obj, "field larger than field limit (%ld)", - field_limit); - return -1; - } - if (self->field_len == self->field_size && !parse_grow_buff(self)) - return -1; - self->field[self->field_len++] = c; - return 0; + if (self->field_len >= field_limit) { + PyErr_Format(error_obj, "field larger than field limit (%ld)", + field_limit); + return -1; + } + if (self->field_len == self->field_size && !parse_grow_buff(self)) + return -1; + self->field[self->field_len++] = c; + return 0; } static int parse_process_char(ReaderObj *self, Py_UNICODE c) { - DialectObj *dialect = self->dialect; + DialectObj *dialect = self->dialect; - switch (self->state) { - case START_RECORD: - /* start of record */ - if (c == '\0') - /* empty line - return [] */ - break; - else if (c == '\n' || c == '\r') { - self->state = EAT_CRNL; - break; - } - /* normal character - handle as START_FIELD */ - self->state = START_FIELD; - /* fallthru */ - case START_FIELD: - /* expecting field */ - if (c == '\n' || c == '\r' || c == '\0') { - /* save empty field - return [fields] */ - if (parse_save_field(self) < 0) - return -1; - self->state = (c == '\0' ? START_RECORD : EAT_CRNL); - } - else if (c == dialect->quotechar && - dialect->quoting != QUOTE_NONE) { - /* start quoted field */ - self->state = IN_QUOTED_FIELD; - } - else if (c == dialect->escapechar) { - /* possible escaped character */ - self->state = ESCAPED_CHAR; - } - else if (c == ' ' && dialect->skipinitialspace) - /* ignore space at start of field */ - ; - else if (c == dialect->delimiter) { - /* save empty field */ - if (parse_save_field(self) < 0) - return -1; - } - else { - /* begin new unquoted field */ - if (dialect->quoting == QUOTE_NONNUMERIC) - self->numeric_field = 1; - if (parse_add_char(self, c) < 0) - return -1; - self->state = IN_FIELD; - } - break; - - case ESCAPED_CHAR: - if (c == '\0') - c = '\n'; - if (parse_add_char(self, c) < 0) - return -1; - self->state = IN_FIELD; - break; - - case IN_FIELD: - /* in unquoted field */ - if (c == '\n' || c == '\r' || c == '\0') { - /* end of line - return [fields] */ - if (parse_save_field(self) < 0) - return -1; - self->state = (c == '\0' ? START_RECORD : EAT_CRNL); - } - else if (c == dialect->escapechar) { - /* possible escaped character */ - self->state = ESCAPED_CHAR; - } - else if (c == dialect->delimiter) { - /* save field - wait for new field */ - if (parse_save_field(self) < 0) - return -1; - self->state = START_FIELD; - } - else { - /* normal character - save in field */ - if (parse_add_char(self, c) < 0) - return -1; - } - break; - - case IN_QUOTED_FIELD: - /* in quoted field */ - if (c == '\0') - ; - else if (c == dialect->escapechar) { - /* Possible escape character */ - self->state = ESCAPE_IN_QUOTED_FIELD; - } - else if (c == dialect->quotechar && - dialect->quoting != QUOTE_NONE) { - if (dialect->doublequote) { - /* doublequote; " represented by "" */ - self->state = QUOTE_IN_QUOTED_FIELD; - } - else { - /* end of quote part of field */ - self->state = IN_FIELD; - } - } - else { - /* normal character - save in field */ - if (parse_add_char(self, c) < 0) - return -1; - } - break; - - case ESCAPE_IN_QUOTED_FIELD: - if (c == '\0') - c = '\n'; - if (parse_add_char(self, c) < 0) - return -1; - self->state = IN_QUOTED_FIELD; - break; - - case QUOTE_IN_QUOTED_FIELD: - /* doublequote - seen a quote in an quoted field */ - if (dialect->quoting != QUOTE_NONE && - c == dialect->quotechar) { - /* save "" as " */ - if (parse_add_char(self, c) < 0) - return -1; - self->state = IN_QUOTED_FIELD; - } - else if (c == dialect->delimiter) { - /* save field - wait for new field */ - if (parse_save_field(self) < 0) - return -1; - self->state = START_FIELD; - } - else if (c == '\n' || c == '\r' || c == '\0') { - /* end of line - return [fields] */ - if (parse_save_field(self) < 0) - return -1; - self->state = (c == '\0' ? START_RECORD : EAT_CRNL); - } - else if (!dialect->strict) { - if (parse_add_char(self, c) < 0) - return -1; - self->state = IN_FIELD; - } - else { - /* illegal */ - PyErr_Format(error_obj, "'%c' expected after '%c'", - dialect->delimiter, - dialect->quotechar); - return -1; - } - break; - - case EAT_CRNL: - if (c == '\n' || c == '\r') - ; - else if (c == '\0') - self->state = START_RECORD; - else { - PyErr_Format(error_obj, "new-line character seen in unquoted field - do you need to open the file in universal-newline mode?"); - return -1; - } - break; + switch (self->state) { + case START_RECORD: + /* start of record */ + if (c == '\0') + /* empty line - return [] */ + break; + else if (c == '\n' || c == '\r') { + self->state = EAT_CRNL; + break; + } + /* normal character - handle as START_FIELD */ + self->state = START_FIELD; + /* fallthru */ + case START_FIELD: + /* expecting field */ + if (c == '\n' || c == '\r' || c == '\0') { + /* save empty field - return [fields] */ + if (parse_save_field(self) < 0) + return -1; + self->state = (c == '\0' ? START_RECORD : EAT_CRNL); + } + else if (c == dialect->quotechar && + dialect->quoting != QUOTE_NONE) { + /* start quoted field */ + self->state = IN_QUOTED_FIELD; + } + else if (c == dialect->escapechar) { + /* possible escaped character */ + self->state = ESCAPED_CHAR; + } + else if (c == ' ' && dialect->skipinitialspace) + /* ignore space at start of field */ + ; + else if (c == dialect->delimiter) { + /* save empty field */ + if (parse_save_field(self) < 0) + return -1; + } + else { + /* begin new unquoted field */ + if (dialect->quoting == QUOTE_NONNUMERIC) + self->numeric_field = 1; + if (parse_add_char(self, c) < 0) + return -1; + self->state = IN_FIELD; + } + break; - } - return 0; + case ESCAPED_CHAR: + if (c == '\0') + c = '\n'; + if (parse_add_char(self, c) < 0) + return -1; + self->state = IN_FIELD; + break; + + case IN_FIELD: + /* in unquoted field */ + if (c == '\n' || c == '\r' || c == '\0') { + /* end of line - return [fields] */ + if (parse_save_field(self) < 0) + return -1; + self->state = (c == '\0' ? START_RECORD : EAT_CRNL); + } + else if (c == dialect->escapechar) { + /* possible escaped character */ + self->state = ESCAPED_CHAR; + } + else if (c == dialect->delimiter) { + /* save field - wait for new field */ + if (parse_save_field(self) < 0) + return -1; + self->state = START_FIELD; + } + else { + /* normal character - save in field */ + if (parse_add_char(self, c) < 0) + return -1; + } + break; + + case IN_QUOTED_FIELD: + /* in quoted field */ + if (c == '\0') + ; + else if (c == dialect->escapechar) { + /* Possible escape character */ + self->state = ESCAPE_IN_QUOTED_FIELD; + } + else if (c == dialect->quotechar && + dialect->quoting != QUOTE_NONE) { + if (dialect->doublequote) { + /* doublequote; " represented by "" */ + self->state = QUOTE_IN_QUOTED_FIELD; + } + else { + /* end of quote part of field */ + self->state = IN_FIELD; + } + } + else { + /* normal character - save in field */ + if (parse_add_char(self, c) < 0) + return -1; + } + break; + + case ESCAPE_IN_QUOTED_FIELD: + if (c == '\0') + c = '\n'; + if (parse_add_char(self, c) < 0) + return -1; + self->state = IN_QUOTED_FIELD; + break; + + case QUOTE_IN_QUOTED_FIELD: + /* doublequote - seen a quote in an quoted field */ + if (dialect->quoting != QUOTE_NONE && + c == dialect->quotechar) { + /* save "" as " */ + if (parse_add_char(self, c) < 0) + return -1; + self->state = IN_QUOTED_FIELD; + } + else if (c == dialect->delimiter) { + /* save field - wait for new field */ + if (parse_save_field(self) < 0) + return -1; + self->state = START_FIELD; + } + else if (c == '\n' || c == '\r' || c == '\0') { + /* end of line - return [fields] */ + if (parse_save_field(self) < 0) + return -1; + self->state = (c == '\0' ? START_RECORD : EAT_CRNL); + } + else if (!dialect->strict) { + if (parse_add_char(self, c) < 0) + return -1; + self->state = IN_FIELD; + } + else { + /* illegal */ + PyErr_Format(error_obj, "'%c' expected after '%c'", + dialect->delimiter, + dialect->quotechar); + return -1; + } + break; + + case EAT_CRNL: + if (c == '\n' || c == '\r') + ; + else if (c == '\0') + self->state = START_RECORD; + else { + PyErr_Format(error_obj, "new-line character seen in unquoted field - do you need to open the file in universal-newline mode?"); + return -1; + } + break; + + } + return 0; } static int parse_reset(ReaderObj *self) { - Py_XDECREF(self->fields); - self->fields = PyList_New(0); - if (self->fields == NULL) - return -1; - self->field_len = 0; - self->state = START_RECORD; - self->numeric_field = 0; - return 0; + Py_XDECREF(self->fields); + self->fields = PyList_New(0); + if (self->fields == NULL) + return -1; + self->field_len = 0; + self->state = START_RECORD; + self->numeric_field = 0; + return 0; } static PyObject * Reader_iternext(ReaderObj *self) { - PyObject *lineobj; - PyObject *fields = NULL; - Py_UNICODE *line, c; - Py_ssize_t linelen; - - if (parse_reset(self) < 0) - return NULL; - do { - lineobj = PyIter_Next(self->input_iter); - if (lineobj == NULL) { - /* End of input OR exception */ - if (!PyErr_Occurred() && self->field_len != 0) - PyErr_Format(error_obj, - "newline inside string"); - return NULL; - } - if (!PyUnicode_Check(lineobj)) { - PyErr_Format(error_obj, - "iterator should return strings, " - "not %.200s " - "(did you open the file in text mode?)", - lineobj->ob_type->tp_name - ); - Py_DECREF(lineobj); - return NULL; - } - ++self->line_num; - line = PyUnicode_AsUnicode(lineobj); - linelen = PyUnicode_GetSize(lineobj); - if (line == NULL || linelen < 0) { - Py_DECREF(lineobj); - return NULL; - } - while (linelen--) { - c = *line++; - if (c == '\0') { - Py_DECREF(lineobj); - PyErr_Format(error_obj, - "line contains NULL byte"); - goto err; - } - if (parse_process_char(self, c) < 0) { - Py_DECREF(lineobj); - goto err; - } - } + PyObject *lineobj; + PyObject *fields = NULL; + Py_UNICODE *line, c; + Py_ssize_t linelen; + + if (parse_reset(self) < 0) + return NULL; + do { + lineobj = PyIter_Next(self->input_iter); + if (lineobj == NULL) { + /* End of input OR exception */ + if (!PyErr_Occurred() && self->field_len != 0) + PyErr_Format(error_obj, + "newline inside string"); + return NULL; + } + if (!PyUnicode_Check(lineobj)) { + PyErr_Format(error_obj, + "iterator should return strings, " + "not %.200s " + "(did you open the file in text mode?)", + lineobj->ob_type->tp_name + ); + Py_DECREF(lineobj); + return NULL; + } + ++self->line_num; + line = PyUnicode_AsUnicode(lineobj); + linelen = PyUnicode_GetSize(lineobj); + if (line == NULL || linelen < 0) { + Py_DECREF(lineobj); + return NULL; + } + while (linelen--) { + c = *line++; + if (c == '\0') { + Py_DECREF(lineobj); + PyErr_Format(error_obj, + "line contains NULL byte"); + goto err; + } + if (parse_process_char(self, c) < 0) { Py_DECREF(lineobj); - if (parse_process_char(self, 0) < 0) - goto err; - } while (self->state != START_RECORD); + goto err; + } + } + Py_DECREF(lineobj); + if (parse_process_char(self, 0) < 0) + goto err; + } while (self->state != START_RECORD); - fields = self->fields; - self->fields = NULL; + fields = self->fields; + self->fields = NULL; err: - return fields; + return fields; } static void Reader_dealloc(ReaderObj *self) { - PyObject_GC_UnTrack(self); - Py_XDECREF(self->dialect); - Py_XDECREF(self->input_iter); - Py_XDECREF(self->fields); - if (self->field != NULL) - PyMem_Free(self->field); - PyObject_GC_Del(self); + PyObject_GC_UnTrack(self); + Py_XDECREF(self->dialect); + Py_XDECREF(self->input_iter); + Py_XDECREF(self->fields); + if (self->field != NULL) + PyMem_Free(self->field); + PyObject_GC_Del(self); } static int Reader_traverse(ReaderObj *self, visitproc visit, void *arg) { - Py_VISIT(self->dialect); - Py_VISIT(self->input_iter); - Py_VISIT(self->fields); - return 0; + Py_VISIT(self->dialect); + Py_VISIT(self->input_iter); + Py_VISIT(self->fields); + return 0; } static int Reader_clear(ReaderObj *self) { - Py_CLEAR(self->dialect); - Py_CLEAR(self->input_iter); - Py_CLEAR(self->fields); - return 0; + Py_CLEAR(self->dialect); + Py_CLEAR(self->input_iter); + Py_CLEAR(self->fields); + return 0; } PyDoc_STRVAR(Reader_Type_doc, @@ -843,93 +843,93 @@ ); static struct PyMethodDef Reader_methods[] = { - { NULL, NULL } + { NULL, NULL } }; #define R_OFF(x) offsetof(ReaderObj, x) static struct PyMemberDef Reader_memberlist[] = { - { "dialect", T_OBJECT, R_OFF(dialect), READONLY }, - { "line_num", T_ULONG, R_OFF(line_num), READONLY }, - { NULL } + { "dialect", T_OBJECT, R_OFF(dialect), READONLY }, + { "line_num", T_ULONG, R_OFF(line_num), READONLY }, + { NULL } }; static PyTypeObject Reader_Type = { - PyVarObject_HEAD_INIT(NULL, 0) - "_csv.reader", /*tp_name*/ - sizeof(ReaderObj), /*tp_basicsize*/ - 0, /*tp_itemsize*/ - /* methods */ - (destructor)Reader_dealloc, /*tp_dealloc*/ - (printfunc)0, /*tp_print*/ - (getattrfunc)0, /*tp_getattr*/ - (setattrfunc)0, /*tp_setattr*/ - 0, /*tp_reserved*/ - (reprfunc)0, /*tp_repr*/ - 0, /*tp_as_number*/ - 0, /*tp_as_sequence*/ - 0, /*tp_as_mapping*/ - (hashfunc)0, /*tp_hash*/ - (ternaryfunc)0, /*tp_call*/ - (reprfunc)0, /*tp_str*/ - 0, /*tp_getattro*/ - 0, /*tp_setattro*/ - 0, /*tp_as_buffer*/ - Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | - Py_TPFLAGS_HAVE_GC, /*tp_flags*/ - Reader_Type_doc, /*tp_doc*/ - (traverseproc)Reader_traverse, /*tp_traverse*/ - (inquiry)Reader_clear, /*tp_clear*/ - 0, /*tp_richcompare*/ - 0, /*tp_weaklistoffset*/ - PyObject_SelfIter, /*tp_iter*/ - (getiterfunc)Reader_iternext, /*tp_iternext*/ - Reader_methods, /*tp_methods*/ - Reader_memberlist, /*tp_members*/ - 0, /*tp_getset*/ + PyVarObject_HEAD_INIT(NULL, 0) + "_csv.reader", /*tp_name*/ + sizeof(ReaderObj), /*tp_basicsize*/ + 0, /*tp_itemsize*/ + /* methods */ + (destructor)Reader_dealloc, /*tp_dealloc*/ + (printfunc)0, /*tp_print*/ + (getattrfunc)0, /*tp_getattr*/ + (setattrfunc)0, /*tp_setattr*/ + 0, /*tp_reserved*/ + (reprfunc)0, /*tp_repr*/ + 0, /*tp_as_number*/ + 0, /*tp_as_sequence*/ + 0, /*tp_as_mapping*/ + (hashfunc)0, /*tp_hash*/ + (ternaryfunc)0, /*tp_call*/ + (reprfunc)0, /*tp_str*/ + 0, /*tp_getattro*/ + 0, /*tp_setattro*/ + 0, /*tp_as_buffer*/ + Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | + Py_TPFLAGS_HAVE_GC, /*tp_flags*/ + Reader_Type_doc, /*tp_doc*/ + (traverseproc)Reader_traverse, /*tp_traverse*/ + (inquiry)Reader_clear, /*tp_clear*/ + 0, /*tp_richcompare*/ + 0, /*tp_weaklistoffset*/ + PyObject_SelfIter, /*tp_iter*/ + (getiterfunc)Reader_iternext, /*tp_iternext*/ + Reader_methods, /*tp_methods*/ + Reader_memberlist, /*tp_members*/ + 0, /*tp_getset*/ }; static PyObject * csv_reader(PyObject *module, PyObject *args, PyObject *keyword_args) { - PyObject * iterator, * dialect = NULL; - ReaderObj * self = PyObject_GC_New(ReaderObj, &Reader_Type); - - if (!self) - return NULL; + PyObject * iterator, * dialect = NULL; + ReaderObj * self = PyObject_GC_New(ReaderObj, &Reader_Type); - self->dialect = NULL; - self->fields = NULL; - self->input_iter = NULL; - self->field = NULL; - self->field_size = 0; - self->line_num = 0; + if (!self) + return NULL; - if (parse_reset(self) < 0) { - Py_DECREF(self); - return NULL; - } - - if (!PyArg_UnpackTuple(args, "", 1, 2, &iterator, &dialect)) { - Py_DECREF(self); - return NULL; - } - self->input_iter = PyObject_GetIter(iterator); - if (self->input_iter == NULL) { - PyErr_SetString(PyExc_TypeError, - "argument 1 must be an iterator"); - Py_DECREF(self); - return NULL; - } - self->dialect = (DialectObj *)_call_dialect(dialect, keyword_args); - if (self->dialect == NULL) { - Py_DECREF(self); - return NULL; - } + self->dialect = NULL; + self->fields = NULL; + self->input_iter = NULL; + self->field = NULL; + self->field_size = 0; + self->line_num = 0; + + if (parse_reset(self) < 0) { + Py_DECREF(self); + return NULL; + } + + if (!PyArg_UnpackTuple(args, "", 1, 2, &iterator, &dialect)) { + Py_DECREF(self); + return NULL; + } + self->input_iter = PyObject_GetIter(iterator); + if (self->input_iter == NULL) { + PyErr_SetString(PyExc_TypeError, + "argument 1 must be an iterator"); + Py_DECREF(self); + return NULL; + } + self->dialect = (DialectObj *)_call_dialect(dialect, keyword_args); + if (self->dialect == NULL) { + Py_DECREF(self); + return NULL; + } - PyObject_GC_Track(self); - return (PyObject *)self; + PyObject_GC_Track(self); + return (PyObject *)self; } /* @@ -939,8 +939,8 @@ static void join_reset(WriterObj *self) { - self->rec_len = 0; - self->num_fields = 0; + self->rec_len = 0; + self->num_fields = 0; } #define MEM_INCR 32768 @@ -952,90 +952,90 @@ join_append_data(WriterObj *self, Py_UNICODE *field, int quote_empty, int *quoted, int copy_phase) { - DialectObj *dialect = self->dialect; - int i; - int rec_len; - Py_UNICODE *lineterm; + DialectObj *dialect = self->dialect; + int i; + int rec_len; + Py_UNICODE *lineterm; #define ADDCH(c) \ - do {\ - if (copy_phase) \ - self->rec[rec_len] = c;\ - rec_len++;\ - } while(0) - - lineterm = PyUnicode_AsUnicode(dialect->lineterminator); - if (lineterm == NULL) - return -1; - - rec_len = self->rec_len; - - /* If this is not the first field we need a field separator */ - if (self->num_fields > 0) - ADDCH(dialect->delimiter); - - /* Handle preceding quote */ - if (copy_phase && *quoted) - ADDCH(dialect->quotechar); - - /* Copy/count field data */ - /* If field is null just pass over */ - for (i = 0; field; i++) { - Py_UNICODE c = field[i]; - int want_escape = 0; - - if (c == '\0') - break; - - if (c == dialect->delimiter || - c == dialect->escapechar || - c == dialect->quotechar || - Py_UNICODE_strchr(lineterm, c)) { - if (dialect->quoting == QUOTE_NONE) - want_escape = 1; - else { - if (c == dialect->quotechar) { - if (dialect->doublequote) - ADDCH(dialect->quotechar); - else - want_escape = 1; - } - if (!want_escape) - *quoted = 1; - } - if (want_escape) { - if (!dialect->escapechar) { - PyErr_Format(error_obj, - "need to escape, but no escapechar set"); - return -1; - } - ADDCH(dialect->escapechar); - } - } - /* Copy field character into record buffer. - */ - ADDCH(c); - } - - /* If field is empty check if it needs to be quoted. - */ - if (i == 0 && quote_empty) { - if (dialect->quoting == QUOTE_NONE) { - PyErr_Format(error_obj, - "single empty field record must be quoted"); - return -1; - } - else - *quoted = 1; - } - - if (*quoted) { - if (copy_phase) - ADDCH(dialect->quotechar); - else - rec_len += 2; - } - return rec_len; + do {\ + if (copy_phase) \ + self->rec[rec_len] = c;\ + rec_len++;\ + } while(0) + + lineterm = PyUnicode_AsUnicode(dialect->lineterminator); + if (lineterm == NULL) + return -1; + + rec_len = self->rec_len; + + /* If this is not the first field we need a field separator */ + if (self->num_fields > 0) + ADDCH(dialect->delimiter); + + /* Handle preceding quote */ + if (copy_phase && *quoted) + ADDCH(dialect->quotechar); + + /* Copy/count field data */ + /* If field is null just pass over */ + for (i = 0; field; i++) { + Py_UNICODE c = field[i]; + int want_escape = 0; + + if (c == '\0') + break; + + if (c == dialect->delimiter || + c == dialect->escapechar || + c == dialect->quotechar || + Py_UNICODE_strchr(lineterm, c)) { + if (dialect->quoting == QUOTE_NONE) + want_escape = 1; + else { + if (c == dialect->quotechar) { + if (dialect->doublequote) + ADDCH(dialect->quotechar); + else + want_escape = 1; + } + if (!want_escape) + *quoted = 1; + } + if (want_escape) { + if (!dialect->escapechar) { + PyErr_Format(error_obj, + "need to escape, but no escapechar set"); + return -1; + } + ADDCH(dialect->escapechar); + } + } + /* Copy field character into record buffer. + */ + ADDCH(c); + } + + /* If field is empty check if it needs to be quoted. + */ + if (i == 0 && quote_empty) { + if (dialect->quoting == QUOTE_NONE) { + PyErr_Format(error_obj, + "single empty field record must be quoted"); + return -1; + } + else + *quoted = 1; + } + + if (*quoted) { + if (copy_phase) + ADDCH(dialect->quotechar); + else + rec_len += 2; + } + return rec_len; #undef ADDCH } @@ -1043,76 +1043,76 @@ join_check_rec_size(WriterObj *self, int rec_len) { - if (rec_len < 0 || rec_len > INT_MAX - MEM_INCR) { - PyErr_NoMemory(); - return 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_New(Py_UNICODE, self->rec_size); - } - else { - Py_UNICODE* old_rec = self->rec; - - self->rec_size = (rec_len / MEM_INCR + 1) * MEM_INCR; - self->rec = PyMem_Resize(self->rec, Py_UNICODE, - self->rec_size); - if (self->rec == NULL) - PyMem_Free(old_rec); - } - if (self->rec == NULL) { - PyErr_NoMemory(); - return 0; - } - } - return 1; + if (rec_len < 0 || rec_len > INT_MAX - MEM_INCR) { + PyErr_NoMemory(); + return 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_New(Py_UNICODE, self->rec_size); + } + else { + Py_UNICODE* old_rec = self->rec; + + self->rec_size = (rec_len / MEM_INCR + 1) * MEM_INCR; + self->rec = PyMem_Resize(self->rec, Py_UNICODE, + self->rec_size); + if (self->rec == NULL) + PyMem_Free(old_rec); + } + if (self->rec == NULL) { + PyErr_NoMemory(); + return 0; + } + } + return 1; } static int join_append(WriterObj *self, Py_UNICODE *field, int *quoted, int quote_empty) { - int rec_len; + int rec_len; - rec_len = join_append_data(self, field, quote_empty, quoted, 0); - if (rec_len < 0) - return 0; + rec_len = join_append_data(self, field, quote_empty, quoted, 0); + if (rec_len < 0) + return 0; - /* grow record buffer if necessary */ - if (!join_check_rec_size(self, rec_len)) - return 0; + /* grow record buffer if necessary */ + if (!join_check_rec_size(self, rec_len)) + return 0; - self->rec_len = join_append_data(self, field, quote_empty, quoted, 1); - self->num_fields++; + self->rec_len = join_append_data(self, field, quote_empty, quoted, 1); + self->num_fields++; - return 1; + return 1; } static int join_append_lineterminator(WriterObj *self) { - int terminator_len; - Py_UNICODE *terminator; + int terminator_len; + Py_UNICODE *terminator; + + terminator_len = PyUnicode_GetSize(self->dialect->lineterminator); + if (terminator_len == -1) + return 0; - terminator_len = PyUnicode_GetSize(self->dialect->lineterminator); - if (terminator_len == -1) - return 0; - - /* grow record buffer if necessary */ - if (!join_check_rec_size(self, self->rec_len + terminator_len)) - return 0; - - terminator = PyUnicode_AsUnicode(self->dialect->lineterminator); - if (terminator == NULL) - return 0; - memmove(self->rec + self->rec_len, terminator, - sizeof(Py_UNICODE)*terminator_len); - self->rec_len += terminator_len; + /* grow record buffer if necessary */ + if (!join_check_rec_size(self, self->rec_len + terminator_len)) + return 0; + + terminator = PyUnicode_AsUnicode(self->dialect->lineterminator); + if (terminator == NULL) + return 0; + memmove(self->rec + self->rec_len, terminator, + sizeof(Py_UNICODE)*terminator_len); + self->rec_len += terminator_len; - return 1; + return 1; } PyDoc_STRVAR(csv_writerow_doc, @@ -1124,75 +1124,75 @@ static PyObject * csv_writerow(WriterObj *self, PyObject *seq) { - DialectObj *dialect = self->dialect; - int len, i; + DialectObj *dialect = self->dialect; + int len, i; + + if (!PySequence_Check(seq)) + return PyErr_Format(error_obj, "sequence expected"); - if (!PySequence_Check(seq)) - return PyErr_Format(error_obj, "sequence expected"); + len = PySequence_Length(seq); + if (len < 0) + return NULL; + + /* Join all fields in internal buffer. + */ + join_reset(self); + for (i = 0; i < len; i++) { + PyObject *field; + int append_ok; + int quoted; + + field = PySequence_GetItem(seq, i); + if (field == NULL) + return NULL; + + switch (dialect->quoting) { + case QUOTE_NONNUMERIC: + quoted = !PyNumber_Check(field); + break; + case QUOTE_ALL: + quoted = 1; + break; + default: + quoted = 0; + break; + } + + if (PyUnicode_Check(field)) { + append_ok = join_append(self, + PyUnicode_AS_UNICODE(field), + "ed, len == 1); + Py_DECREF(field); + } + else if (field == Py_None) { + append_ok = join_append(self, NULL, + "ed, len == 1); + Py_DECREF(field); + } + else { + PyObject *str; - len = PySequence_Length(seq); - if (len < 0) - return NULL; - - /* Join all fields in internal buffer. - */ - join_reset(self); - for (i = 0; i < len; i++) { - PyObject *field; - int append_ok; - int quoted; - - field = PySequence_GetItem(seq, i); - if (field == NULL) - return NULL; - - switch (dialect->quoting) { - case QUOTE_NONNUMERIC: - quoted = !PyNumber_Check(field); - break; - case QUOTE_ALL: - quoted = 1; - break; - default: - quoted = 0; - break; - } - - if (PyUnicode_Check(field)) { - append_ok = join_append(self, - PyUnicode_AS_UNICODE(field), - "ed, len == 1); - Py_DECREF(field); - } - else if (field == Py_None) { - append_ok = join_append(self, NULL, + str = PyObject_Str(field); + Py_DECREF(field); + if (str == NULL) + return NULL; + append_ok = join_append(self, + PyUnicode_AS_UNICODE(str), "ed, len == 1); - Py_DECREF(field); - } - else { - PyObject *str; - - str = PyObject_Str(field); - Py_DECREF(field); - if (str == NULL) - return NULL; - append_ok = join_append(self, - PyUnicode_AS_UNICODE(str), - "ed, len == 1); - Py_DECREF(str); - } - if (!append_ok) - return NULL; - } - - /* Add line terminator. - */ - if (!join_append_lineterminator(self)) - return 0; - - return PyObject_CallFunction(self->writeline, - "(u#)", self->rec, - self->rec_len); + Py_DECREF(str); + } + if (!append_ok) + return NULL; + } + + /* Add line terminator. + */ + if (!join_append_lineterminator(self)) + return 0; + + return PyObject_CallFunction(self->writeline, + "(u#)", self->rec, + self->rec_len); } PyDoc_STRVAR(csv_writerows_doc, @@ -1204,72 +1204,72 @@ static PyObject * csv_writerows(WriterObj *self, PyObject *seqseq) { - PyObject *row_iter, *row_obj, *result; + PyObject *row_iter, *row_obj, *result; - row_iter = PyObject_GetIter(seqseq); - if (row_iter == NULL) { - PyErr_SetString(PyExc_TypeError, - "writerows() argument must be iterable"); - return NULL; - } - while ((row_obj = PyIter_Next(row_iter))) { - result = csv_writerow(self, row_obj); - Py_DECREF(row_obj); - if (!result) { - Py_DECREF(row_iter); - return NULL; - } - else - Py_DECREF(result); + row_iter = PyObject_GetIter(seqseq); + if (row_iter == NULL) { + PyErr_SetString(PyExc_TypeError, + "writerows() argument must be iterable"); + return NULL; + } + while ((row_obj = PyIter_Next(row_iter))) { + result = csv_writerow(self, row_obj); + Py_DECREF(row_obj); + if (!result) { + Py_DECREF(row_iter); + return NULL; } - Py_DECREF(row_iter); - if (PyErr_Occurred()) - return NULL; - Py_INCREF(Py_None); - return Py_None; + else + Py_DECREF(result); + } + Py_DECREF(row_iter); + if (PyErr_Occurred()) + return NULL; + Py_INCREF(Py_None); + return Py_None; } static struct PyMethodDef Writer_methods[] = { - { "writerow", (PyCFunction)csv_writerow, METH_O, csv_writerow_doc}, - { "writerows", (PyCFunction)csv_writerows, METH_O, csv_writerows_doc}, - { NULL, NULL } + { "writerow", (PyCFunction)csv_writerow, METH_O, csv_writerow_doc}, + { "writerows", (PyCFunction)csv_writerows, METH_O, csv_writerows_doc}, + { NULL, NULL } }; #define W_OFF(x) offsetof(WriterObj, x) static struct PyMemberDef Writer_memberlist[] = { - { "dialect", T_OBJECT, W_OFF(dialect), READONLY }, - { NULL } + { "dialect", T_OBJECT, W_OFF(dialect), READONLY }, + { NULL } }; static void Writer_dealloc(WriterObj *self) { - PyObject_GC_UnTrack(self); - Py_XDECREF(self->dialect); - Py_XDECREF(self->writeline); - if (self->rec != NULL) - PyMem_Free(self->rec); - PyObject_GC_Del(self); + PyObject_GC_UnTrack(self); + Py_XDECREF(self->dialect); + Py_XDECREF(self->writeline); + if (self->rec != NULL) + PyMem_Free(self->rec); + PyObject_GC_Del(self); } static int Writer_traverse(WriterObj *self, visitproc visit, void *arg) { - Py_VISIT(self->dialect); - Py_VISIT(self->writeline); - return 0; + Py_VISIT(self->dialect); + Py_VISIT(self->writeline); + return 0; } static int Writer_clear(WriterObj *self) { - Py_CLEAR(self->dialect); - Py_CLEAR(self->writeline); - return 0; + Py_CLEAR(self->dialect); + Py_CLEAR(self->writeline); + return 0; } -PyDoc_STRVAR(Writer_Type_doc, +PyDoc_STRVAR(Writer_Type_doc, "CSV writer\n" "\n" "Writer objects are responsible for generating tabular data\n" @@ -1277,75 +1277,75 @@ ); static PyTypeObject Writer_Type = { - PyVarObject_HEAD_INIT(NULL, 0) - "_csv.writer", /*tp_name*/ - sizeof(WriterObj), /*tp_basicsize*/ - 0, /*tp_itemsize*/ - /* methods */ - (destructor)Writer_dealloc, /*tp_dealloc*/ - (printfunc)0, /*tp_print*/ - (getattrfunc)0, /*tp_getattr*/ - (setattrfunc)0, /*tp_setattr*/ - 0, /*tp_reserved*/ - (reprfunc)0, /*tp_repr*/ - 0, /*tp_as_number*/ - 0, /*tp_as_sequence*/ - 0, /*tp_as_mapping*/ - (hashfunc)0, /*tp_hash*/ - (ternaryfunc)0, /*tp_call*/ - (reprfunc)0, /*tp_str*/ - 0, /*tp_getattro*/ - 0, /*tp_setattro*/ - 0, /*tp_as_buffer*/ - Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | - Py_TPFLAGS_HAVE_GC, /*tp_flags*/ - Writer_Type_doc, - (traverseproc)Writer_traverse, /*tp_traverse*/ - (inquiry)Writer_clear, /*tp_clear*/ - 0, /*tp_richcompare*/ - 0, /*tp_weaklistoffset*/ - (getiterfunc)0, /*tp_iter*/ - (getiterfunc)0, /*tp_iternext*/ - Writer_methods, /*tp_methods*/ - Writer_memberlist, /*tp_members*/ - 0, /*tp_getset*/ + PyVarObject_HEAD_INIT(NULL, 0) + "_csv.writer", /*tp_name*/ + sizeof(WriterObj), /*tp_basicsize*/ + 0, /*tp_itemsize*/ + /* methods */ + (destructor)Writer_dealloc, /*tp_dealloc*/ + (printfunc)0, /*tp_print*/ + (getattrfunc)0, /*tp_getattr*/ + (setattrfunc)0, /*tp_setattr*/ + 0, /*tp_reserved*/ + (reprfunc)0, /*tp_repr*/ + 0, /*tp_as_number*/ + 0, /*tp_as_sequence*/ + 0, /*tp_as_mapping*/ + (hashfunc)0, /*tp_hash*/ + (ternaryfunc)0, /*tp_call*/ + (reprfunc)0, /*tp_str*/ + 0, /*tp_getattro*/ + 0, /*tp_setattro*/ + 0, /*tp_as_buffer*/ + Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | + Py_TPFLAGS_HAVE_GC, /*tp_flags*/ + Writer_Type_doc, + (traverseproc)Writer_traverse, /*tp_traverse*/ + (inquiry)Writer_clear, /*tp_clear*/ + 0, /*tp_richcompare*/ + 0, /*tp_weaklistoffset*/ + (getiterfunc)0, /*tp_iter*/ + (getiterfunc)0, /*tp_iternext*/ + Writer_methods, /*tp_methods*/ + Writer_memberlist, /*tp_members*/ + 0, /*tp_getset*/ }; static PyObject * csv_writer(PyObject *module, PyObject *args, PyObject *keyword_args) { - PyObject * output_file, * dialect = NULL; - WriterObj * self = PyObject_GC_New(WriterObj, &Writer_Type); + PyObject * output_file, * dialect = NULL; + WriterObj * self = PyObject_GC_New(WriterObj, &Writer_Type); - if (!self) - return NULL; - - self->dialect = NULL; - self->writeline = NULL; + if (!self) + return NULL; - self->rec = NULL; - self->rec_size = 0; - self->rec_len = 0; - self->num_fields = 0; + self->dialect = NULL; + self->writeline = NULL; - if (!PyArg_UnpackTuple(args, "", 1, 2, &output_file, &dialect)) { - Py_DECREF(self); - return NULL; - } - self->writeline = PyObject_GetAttrString(output_file, "write"); - if (self->writeline == NULL || !PyCallable_Check(self->writeline)) { - PyErr_SetString(PyExc_TypeError, - "argument 1 must have a \"write\" method"); - Py_DECREF(self); - return NULL; - } - self->dialect = (DialectObj *)_call_dialect(dialect, keyword_args); - if (self->dialect == NULL) { - Py_DECREF(self); - return NULL; - } - PyObject_GC_Track(self); - return (PyObject *)self; + self->rec = NULL; + self->rec_size = 0; + self->rec_len = 0; + self->num_fields = 0; + + if (!PyArg_UnpackTuple(args, "", 1, 2, &output_file, &dialect)) { + Py_DECREF(self); + return NULL; + } + self->writeline = PyObject_GetAttrString(output_file, "write"); + if (self->writeline == NULL || !PyCallable_Check(self->writeline)) { + PyErr_SetString(PyExc_TypeError, + "argument 1 must have a \"write\" method"); + Py_DECREF(self); + return NULL; + } + self->dialect = (DialectObj *)_call_dialect(dialect, keyword_args); + if (self->dialect == NULL) { + Py_DECREF(self); + return NULL; + } + PyObject_GC_Track(self); + return (PyObject *)self; } /* @@ -1354,70 +1354,70 @@ static PyObject * csv_list_dialects(PyObject *module, PyObject *args) { - return PyDict_Keys(dialects); + return PyDict_Keys(dialects); } static PyObject * csv_register_dialect(PyObject *module, PyObject *args, PyObject *kwargs) { - PyObject *name_obj, *dialect_obj = NULL; - PyObject *dialect; + PyObject *name_obj, *dialect_obj = NULL; + PyObject *dialect; - if (!PyArg_UnpackTuple(args, "", 1, 2, &name_obj, &dialect_obj)) - return NULL; - if (!IS_BASESTRING(name_obj)) { - PyErr_SetString(PyExc_TypeError, - "dialect name must be a string or unicode"); - return NULL; - } - dialect = _call_dialect(dialect_obj, kwargs); - if (dialect == NULL) - return NULL; - if (PyDict_SetItem(dialects, name_obj, dialect) < 0) { - Py_DECREF(dialect); - return NULL; - } - Py_DECREF(dialect); - Py_INCREF(Py_None); - return Py_None; + if (!PyArg_UnpackTuple(args, "", 1, 2, &name_obj, &dialect_obj)) + return NULL; + if (!IS_BASESTRING(name_obj)) { + PyErr_SetString(PyExc_TypeError, + "dialect name must be a string or unicode"); + return NULL; + } + dialect = _call_dialect(dialect_obj, kwargs); + if (dialect == NULL) + return NULL; + if (PyDict_SetItem(dialects, name_obj, dialect) < 0) { + Py_DECREF(dialect); + return NULL; + } + Py_DECREF(dialect); + Py_INCREF(Py_None); + return Py_None; } static PyObject * csv_unregister_dialect(PyObject *module, PyObject *name_obj) { - if (PyDict_DelItem(dialects, name_obj) < 0) - return PyErr_Format(error_obj, "unknown dialect"); - Py_INCREF(Py_None); - return Py_None; + if (PyDict_DelItem(dialects, name_obj) < 0) + return PyErr_Format(error_obj, "unknown dialect"); + Py_INCREF(Py_None); + return Py_None; } static PyObject * csv_get_dialect(PyObject *module, PyObject *name_obj) { - return get_dialect_from_registry(name_obj); + return get_dialect_from_registry(name_obj); } static PyObject * csv_field_size_limit(PyObject *module, PyObject *args) { - PyObject *new_limit = NULL; - long old_limit = field_limit; + PyObject *new_limit = NULL; + long old_limit = field_limit; - if (!PyArg_UnpackTuple(args, "field_size_limit", 0, 1, &new_limit)) - return NULL; - if (new_limit != NULL) { - if (!PyLong_CheckExact(new_limit)) { - PyErr_Format(PyExc_TypeError, - "limit must be an integer"); - return NULL; - } - field_limit = PyLong_AsLong(new_limit); - if (field_limit == -1 && PyErr_Occurred()) { - field_limit = old_limit; - return NULL; - } - } - return PyLong_FromLong(old_limit); + if (!PyArg_UnpackTuple(args, "field_size_limit", 0, 1, &new_limit)) + return NULL; + if (new_limit != NULL) { + if (!PyLong_CheckExact(new_limit)) { + PyErr_Format(PyExc_TypeError, + "limit must be an integer"); + return NULL; + } + field_limit = PyLong_AsLong(new_limit); + if (field_limit == -1 && PyErr_Occurred()) { + field_limit = old_limit; + return NULL; + } + } + return PyLong_FromLong(old_limit); } /* @@ -1535,84 +1535,84 @@ "the old limit is returned"); static struct PyMethodDef csv_methods[] = { - { "reader", (PyCFunction)csv_reader, - METH_VARARGS | METH_KEYWORDS, csv_reader_doc}, - { "writer", (PyCFunction)csv_writer, - METH_VARARGS | METH_KEYWORDS, csv_writer_doc}, - { "list_dialects", (PyCFunction)csv_list_dialects, - METH_NOARGS, csv_list_dialects_doc}, - { "register_dialect", (PyCFunction)csv_register_dialect, - METH_VARARGS | METH_KEYWORDS, csv_register_dialect_doc}, - { "unregister_dialect", (PyCFunction)csv_unregister_dialect, - METH_O, csv_unregister_dialect_doc}, - { "get_dialect", (PyCFunction)csv_get_dialect, - METH_O, csv_get_dialect_doc}, - { "field_size_limit", (PyCFunction)csv_field_size_limit, - METH_VARARGS, csv_field_size_limit_doc}, - { NULL, NULL } + { "reader", (PyCFunction)csv_reader, + METH_VARARGS | METH_KEYWORDS, csv_reader_doc}, + { "writer", (PyCFunction)csv_writer, + METH_VARARGS | METH_KEYWORDS, csv_writer_doc}, + { "list_dialects", (PyCFunction)csv_list_dialects, + METH_NOARGS, csv_list_dialects_doc}, + { "register_dialect", (PyCFunction)csv_register_dialect, + METH_VARARGS | METH_KEYWORDS, csv_register_dialect_doc}, + { "unregister_dialect", (PyCFunction)csv_unregister_dialect, + METH_O, csv_unregister_dialect_doc}, + { "get_dialect", (PyCFunction)csv_get_dialect, + METH_O, csv_get_dialect_doc}, + { "field_size_limit", (PyCFunction)csv_field_size_limit, + METH_VARARGS, csv_field_size_limit_doc}, + { NULL, NULL } }; static struct PyModuleDef _csvmodule = { - PyModuleDef_HEAD_INIT, - "_csv", - csv_module_doc, - -1, - csv_methods, - NULL, - NULL, - NULL, - NULL + PyModuleDef_HEAD_INIT, + "_csv", + csv_module_doc, + -1, + csv_methods, + NULL, + NULL, + NULL, + NULL }; PyMODINIT_FUNC PyInit__csv(void) { - PyObject *module; - StyleDesc *style; - - if (PyType_Ready(&Dialect_Type) < 0) - return NULL; + PyObject *module; + StyleDesc *style; - if (PyType_Ready(&Reader_Type) < 0) - return NULL; + if (PyType_Ready(&Dialect_Type) < 0) + return NULL; - if (PyType_Ready(&Writer_Type) < 0) - return NULL; - - /* Create the module and add the functions */ - module = PyModule_Create(&_csvmodule); - if (module == NULL) - return NULL; - - /* Add version to the module. */ - if (PyModule_AddStringConstant(module, "__version__", - MODULE_VERSION) == -1) - return NULL; - - /* Add _dialects dictionary */ - dialects = PyDict_New(); - if (dialects == NULL) - return NULL; - if (PyModule_AddObject(module, "_dialects", dialects)) - return NULL; - - /* Add quote styles into dictionary */ - for (style = quote_styles; style->name; style++) { - if (PyModule_AddIntConstant(module, style->name, - style->style) == -1) - return NULL; - } - - /* Add the Dialect type */ - Py_INCREF(&Dialect_Type); - if (PyModule_AddObject(module, "Dialect", (PyObject *)&Dialect_Type)) - return NULL; + if (PyType_Ready(&Reader_Type) < 0) + return NULL; - /* Add the CSV exception object to the module. */ - error_obj = PyErr_NewException("_csv.Error", NULL, NULL); - if (error_obj == NULL) - return NULL; - PyModule_AddObject(module, "Error", error_obj); - return module; + if (PyType_Ready(&Writer_Type) < 0) + return NULL; + + /* Create the module and add the functions */ + module = PyModule_Create(&_csvmodule); + if (module == NULL) + return NULL; + + /* Add version to the module. */ + if (PyModule_AddStringConstant(module, "__version__", + MODULE_VERSION) == -1) + return NULL; + + /* Add _dialects dictionary */ + dialects = PyDict_New(); + if (dialects == NULL) + return NULL; + if (PyModule_AddObject(module, "_dialects", dialects)) + return NULL; + + /* Add quote styles into dictionary */ + for (style = quote_styles; style->name; style++) { + if (PyModule_AddIntConstant(module, style->name, + style->style) == -1) + return NULL; + } + + /* Add the Dialect type */ + Py_INCREF(&Dialect_Type); + if (PyModule_AddObject(module, "Dialect", (PyObject *)&Dialect_Type)) + return NULL; + + /* Add the CSV exception object to the module. */ + error_obj = PyErr_NewException("_csv.Error", NULL, NULL); + if (error_obj == NULL) + return NULL; + PyModule_AddObject(module, "Error", error_obj); + return module; } Modified: python/branches/py3k-jit/Modules/_ctypes/_ctypes.c ============================================================================== --- python/branches/py3k-jit/Modules/_ctypes/_ctypes.c (original) +++ python/branches/py3k-jit/Modules/_ctypes/_ctypes.c Mon May 10 23:55:43 2010 @@ -20,20 +20,20 @@ /* -Name methods, members, getsets +Name methods, members, getsets ============================================================================== -PyCStructType_Type __new__(), from_address(), __mul__(), from_param() -UnionType_Type __new__(), from_address(), __mul__(), from_param() -PyCPointerType_Type __new__(), from_address(), __mul__(), from_param(), set_type() -PyCArrayType_Type __new__(), from_address(), __mul__(), from_param() -PyCSimpleType_Type __new__(), from_address(), __mul__(), from_param() +PyCStructType_Type __new__(), from_address(), __mul__(), from_param() +UnionType_Type __new__(), from_address(), __mul__(), from_param() +PyCPointerType_Type __new__(), from_address(), __mul__(), from_param(), set_type() +PyCArrayType_Type __new__(), from_address(), __mul__(), from_param() +PyCSimpleType_Type __new__(), from_address(), __mul__(), from_param() PyCData_Type - Struct_Type __new__(), __init__() - PyCPointer_Type __new__(), __init__(), _as_parameter_, contents - PyCArray_Type __new__(), __init__(), _as_parameter_, __get/setitem__(), __len__() - Simple_Type __new__(), __init__(), _as_parameter_ + Struct_Type __new__(), __init__() + PyCPointer_Type __new__(), __init__(), _as_parameter_, contents + PyCArray_Type __new__(), __init__(), _as_parameter_, __get/setitem__(), __len__() + Simple_Type __new__(), __init__(), _as_parameter_ PyCField_Type PyCStgDict_Type @@ -45,28 +45,28 @@ It has some similarity to the byref() construct compared to pointer() from_address(addr) - - construct an instance from a given memory block (sharing this memory block) + - construct an instance from a given memory block (sharing this memory block) from_param(obj) - - typecheck and convert a Python object into a C function call parameter - the result may be an instance of the type, or an integer or tuple - (typecode, value[, obj]) + - typecheck and convert a Python object into a C function call parameter + the result may be an instance of the type, or an integer or tuple + (typecode, value[, obj]) instance methods/properties --------------------------- _as_parameter_ - - convert self into a C function call parameter - This is either an integer, or a 3-tuple (typecode, value, obj) + - convert self into a C function call parameter + This is either an integer, or a 3-tuple (typecode, value, obj) functions --------- sizeof(cdata) - - return the number of bytes the buffer contains + - return the number of bytes the buffer contains sizeof(ctype) - - return the number of bytes the buffer of an instance would contain + - return the number of bytes the buffer of an instance would contain byref(cdata) @@ -77,7 +77,7 @@ POINTER(ctype) bytes(cdata) - - return the buffer contents as a sequence of bytes (which is currently a string) + - return the buffer contents as a sequence of bytes (which is currently a string) */ @@ -98,7 +98,7 @@ * PyCField_Type * */ - + #define PY_SSIZE_T_CLEAN #include "Python.h" @@ -135,128 +135,128 @@ char *_ctypes_conversion_encoding = NULL; char *_ctypes_conversion_errors = NULL; - + /****************************************************************/ typedef struct { - PyObject_HEAD - PyObject *key; - PyObject *dict; + PyObject_HEAD + PyObject *key; + PyObject *dict; } DictRemoverObject; static void _DictRemover_dealloc(PyObject *_self) { - DictRemoverObject *self = (DictRemoverObject *)_self; - Py_XDECREF(self->key); - Py_XDECREF(self->dict); - Py_TYPE(self)->tp_free(_self); + DictRemoverObject *self = (DictRemoverObject *)_self; + Py_XDECREF(self->key); + Py_XDECREF(self->dict); + Py_TYPE(self)->tp_free(_self); } static PyObject * _DictRemover_call(PyObject *_self, PyObject *args, PyObject *kw) { - DictRemoverObject *self = (DictRemoverObject *)_self; - if (self->key && self->dict) { - if (-1 == PyDict_DelItem(self->dict, self->key)) - /* XXX Error context */ - PyErr_WriteUnraisable(Py_None); - Py_DECREF(self->key); - self->key = NULL; - Py_DECREF(self->dict); - self->dict = NULL; - } - Py_INCREF(Py_None); - return Py_None; + DictRemoverObject *self = (DictRemoverObject *)_self; + if (self->key && self->dict) { + if (-1 == PyDict_DelItem(self->dict, self->key)) + /* XXX Error context */ + PyErr_WriteUnraisable(Py_None); + Py_DECREF(self->key); + self->key = NULL; + Py_DECREF(self->dict); + self->dict = NULL; + } + Py_INCREF(Py_None); + return Py_None; } static PyTypeObject DictRemover_Type = { - PyVarObject_HEAD_INIT(NULL, 0) - "_ctypes.DictRemover", /* tp_name */ - sizeof(DictRemoverObject), /* tp_basicsize */ - 0, /* tp_itemsize */ - _DictRemover_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 */ - _DictRemover_call, /* tp_call */ - 0, /* tp_str */ - 0, /* tp_getattro */ - 0, /* tp_setattro */ - 0, /* tp_as_buffer */ + PyVarObject_HEAD_INIT(NULL, 0) + "_ctypes.DictRemover", /* tp_name */ + sizeof(DictRemoverObject), /* tp_basicsize */ + 0, /* tp_itemsize */ + _DictRemover_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 */ + _DictRemover_call, /* tp_call */ + 0, /* tp_str */ + 0, /* tp_getattro */ + 0, /* tp_setattro */ + 0, /* tp_as_buffer */ /* XXX should participate in GC? */ - Py_TPFLAGS_DEFAULT, /* tp_flags */ - "deletes a key from a dictionary", /* tp_doc */ - 0, /* tp_traverse */ - 0, /* tp_clear */ - 0, /* tp_richcompare */ - 0, /* tp_weaklistoffset */ - 0, /* tp_iter */ - 0, /* tp_iternext */ - 0, /* tp_methods */ - 0, /* tp_members */ - 0, /* tp_getset */ - 0, /* tp_base */ - 0, /* tp_dict */ - 0, /* tp_descr_get */ - 0, /* tp_descr_set */ - 0, /* tp_dictoffset */ - 0, /* tp_init */ - 0, /* tp_alloc */ - 0, /* tp_new */ - 0, /* tp_free */ + Py_TPFLAGS_DEFAULT, /* tp_flags */ + "deletes a key from a dictionary", /* tp_doc */ + 0, /* tp_traverse */ + 0, /* tp_clear */ + 0, /* tp_richcompare */ + 0, /* tp_weaklistoffset */ + 0, /* tp_iter */ + 0, /* tp_iternext */ + 0, /* tp_methods */ + 0, /* tp_members */ + 0, /* tp_getset */ + 0, /* tp_base */ + 0, /* tp_dict */ + 0, /* tp_descr_get */ + 0, /* tp_descr_set */ + 0, /* tp_dictoffset */ + 0, /* tp_init */ + 0, /* tp_alloc */ + 0, /* tp_new */ + 0, /* tp_free */ }; int PyDict_SetItemProxy(PyObject *dict, PyObject *key, PyObject *item) { - PyObject *obj; - DictRemoverObject *remover; - PyObject *proxy; - int result; - - obj = PyObject_CallObject((PyObject *)&DictRemover_Type, NULL); - if (obj == NULL) - return -1; - - remover = (DictRemoverObject *)obj; - assert(remover->key == NULL); - assert(remover->dict == NULL); - Py_INCREF(key); - remover->key = key; - Py_INCREF(dict); - remover->dict = dict; - - proxy = PyWeakref_NewProxy(item, obj); - Py_DECREF(obj); - if (proxy == NULL) - return -1; - - result = PyDict_SetItem(dict, key, proxy); - Py_DECREF(proxy); - return result; + PyObject *obj; + DictRemoverObject *remover; + PyObject *proxy; + int result; + + obj = PyObject_CallObject((PyObject *)&DictRemover_Type, NULL); + if (obj == NULL) + return -1; + + remover = (DictRemoverObject *)obj; + assert(remover->key == NULL); + assert(remover->dict == NULL); + Py_INCREF(key); + remover->key = key; + Py_INCREF(dict); + remover->dict = dict; + + proxy = PyWeakref_NewProxy(item, obj); + Py_DECREF(obj); + if (proxy == NULL) + return -1; + + result = PyDict_SetItem(dict, key, proxy); + Py_DECREF(proxy); + return result; } PyObject * PyDict_GetItemProxy(PyObject *dict, PyObject *key) { - PyObject *result; - PyObject *item = PyDict_GetItem(dict, key); + PyObject *result; + PyObject *item = PyDict_GetItem(dict, key); - if (item == NULL) - return NULL; - if (!PyWeakref_CheckProxy(item)) - return item; - result = PyWeakref_GET_OBJECT(item); - if (result == Py_None) - return NULL; - return result; + if (item == NULL) + return NULL; + if (!PyWeakref_CheckProxy(item)) + return item; + result = PyWeakref_GET_OBJECT(item); + if (result == Py_None) + return NULL; + return result; } /******************************************************************/ @@ -269,25 +269,25 @@ char * _ctypes_alloc_format_string(const char *prefix, const char *suffix) { - size_t len; - char *result; + size_t len; + char *result; - if (suffix == NULL) { - assert(PyErr_Occurred()); - return NULL; - } - len = strlen(suffix); - if (prefix) - len += strlen(prefix); - result = PyMem_Malloc(len + 1); - if (result == NULL) - return NULL; - if (prefix) - strcpy(result, prefix); - else - result[0] = '\0'; - strcat(result, suffix); - return result; + if (suffix == NULL) { + assert(PyErr_Occurred()); + return NULL; + } + len = strlen(suffix); + if (prefix) + len += strlen(prefix); + result = PyMem_Malloc(len + 1); + if (result == NULL) + return NULL; + if (prefix) + strcpy(result, prefix); + else + result[0] = '\0'; + strcat(result, suffix); + return result; } /* @@ -300,100 +300,100 @@ static PyCArgObject * StructUnionType_paramfunc(CDataObject *self) { - PyCArgObject *parg; - StgDictObject *stgdict; - - parg = PyCArgObject_new(); - if (parg == NULL) - return NULL; - - parg->tag = 'V'; - stgdict = PyObject_stgdict((PyObject *)self); - assert(stgdict); /* Cannot be NULL for structure/union instances */ - parg->pffi_type = &stgdict->ffi_type_pointer; - /* For structure parameters (by value), parg->value doesn't contain the structure - data itself, instead parg->value.p *points* to the structure's data - See also _ctypes.c, function _call_function_pointer(). - */ - parg->value.p = self->b_ptr; - parg->size = self->b_size; - Py_INCREF(self); - parg->obj = (PyObject *)self; - return parg; + PyCArgObject *parg; + StgDictObject *stgdict; + + parg = PyCArgObject_new(); + if (parg == NULL) + return NULL; + + parg->tag = 'V'; + stgdict = PyObject_stgdict((PyObject *)self); + assert(stgdict); /* Cannot be NULL for structure/union instances */ + parg->pffi_type = &stgdict->ffi_type_pointer; + /* For structure parameters (by value), parg->value doesn't contain the structure + data itself, instead parg->value.p *points* to the structure's data + See also _ctypes.c, function _call_function_pointer(). + */ + parg->value.p = self->b_ptr; + parg->size = self->b_size; + Py_INCREF(self); + parg->obj = (PyObject *)self; + return parg; } static PyObject * StructUnionType_new(PyTypeObject *type, PyObject *args, PyObject *kwds, int isStruct) { - PyTypeObject *result; - PyObject *fields; - StgDictObject *dict; - - /* create the new instance (which is a class, - since we are a metatype!) */ - result = (PyTypeObject *)PyType_Type.tp_new(type, args, kwds); - if (!result) - return NULL; - - /* keep this for bw compatibility */ - if (PyDict_GetItemString(result->tp_dict, "_abstract_")) - return (PyObject *)result; - - dict = (StgDictObject *)PyObject_CallObject((PyObject *)&PyCStgDict_Type, NULL); - if (!dict) { - Py_DECREF(result); - return NULL; - } - /* replace the class dict by our updated stgdict, which holds info - about storage requirements of the instances */ - if (-1 == PyDict_Update((PyObject *)dict, result->tp_dict)) { - Py_DECREF(result); - Py_DECREF((PyObject *)dict); - return NULL; - } - Py_DECREF(result->tp_dict); - result->tp_dict = (PyObject *)dict; - dict->format = _ctypes_alloc_format_string(NULL, "B"); - if (dict->format == NULL) { - Py_DECREF(result); - return NULL; - } - - dict->paramfunc = StructUnionType_paramfunc; - - fields = PyDict_GetItemString((PyObject *)dict, "_fields_"); - if (!fields) { - StgDictObject *basedict = PyType_stgdict((PyObject *)result->tp_base); - - if (basedict == NULL) - return (PyObject *)result; - /* copy base dict */ - if (-1 == PyCStgDict_clone(dict, basedict)) { - Py_DECREF(result); - return NULL; - } - dict->flags &= ~DICTFLAG_FINAL; /* clear the 'final' flag in the subclass dict */ - basedict->flags |= DICTFLAG_FINAL; /* set the 'final' flag in the baseclass dict */ - return (PyObject *)result; - } - - if (-1 == PyObject_SetAttrString((PyObject *)result, "_fields_", fields)) { - Py_DECREF(result); - return NULL; - } - return (PyObject *)result; + PyTypeObject *result; + PyObject *fields; + StgDictObject *dict; + + /* create the new instance (which is a class, + since we are a metatype!) */ + result = (PyTypeObject *)PyType_Type.tp_new(type, args, kwds); + if (!result) + return NULL; + + /* keep this for bw compatibility */ + if (PyDict_GetItemString(result->tp_dict, "_abstract_")) + return (PyObject *)result; + + dict = (StgDictObject *)PyObject_CallObject((PyObject *)&PyCStgDict_Type, NULL); + if (!dict) { + Py_DECREF(result); + return NULL; + } + /* replace the class dict by our updated stgdict, which holds info + about storage requirements of the instances */ + if (-1 == PyDict_Update((PyObject *)dict, result->tp_dict)) { + Py_DECREF(result); + Py_DECREF((PyObject *)dict); + return NULL; + } + Py_DECREF(result->tp_dict); + result->tp_dict = (PyObject *)dict; + dict->format = _ctypes_alloc_format_string(NULL, "B"); + if (dict->format == NULL) { + Py_DECREF(result); + return NULL; + } + + dict->paramfunc = StructUnionType_paramfunc; + + fields = PyDict_GetItemString((PyObject *)dict, "_fields_"); + if (!fields) { + StgDictObject *basedict = PyType_stgdict((PyObject *)result->tp_base); + + if (basedict == NULL) + return (PyObject *)result; + /* copy base dict */ + if (-1 == PyCStgDict_clone(dict, basedict)) { + Py_DECREF(result); + return NULL; + } + dict->flags &= ~DICTFLAG_FINAL; /* clear the 'final' flag in the subclass dict */ + basedict->flags |= DICTFLAG_FINAL; /* set the 'final' flag in the baseclass dict */ + return (PyObject *)result; + } + + if (-1 == PyObject_SetAttrString((PyObject *)result, "_fields_", fields)) { + Py_DECREF(result); + return NULL; + } + return (PyObject *)result; } static PyObject * PyCStructType_new(PyTypeObject *type, PyObject *args, PyObject *kwds) { - return StructUnionType_new(type, args, kwds, 1); + return StructUnionType_new(type, args, kwds, 1); } static PyObject * UnionType_new(PyTypeObject *type, PyObject *args, PyObject *kwds) { - return StructUnionType_new(type, args, kwds, 0); + return StructUnionType_new(type, args, kwds, 0); } static char from_address_doc[] = @@ -402,16 +402,16 @@ static PyObject * CDataType_from_address(PyObject *type, PyObject *value) { - void *buf; - if (!PyLong_Check(value)) { - PyErr_SetString(PyExc_TypeError, - "integer expected"); - return NULL; - } - buf = (void *)PyLong_AsVoidPtr(value); - if (PyErr_Occurred()) - return NULL; - return PyCData_AtAddress(type, buf); + void *buf; + if (!PyLong_Check(value)) { + PyErr_SetString(PyExc_TypeError, + "integer expected"); + return NULL; + } + buf = (void *)PyLong_AsVoidPtr(value); + if (PyErr_Occurred()) + return NULL; + return PyCData_AtAddress(type, buf); } static char from_buffer_doc[] = @@ -423,51 +423,51 @@ static PyObject * CDataType_from_buffer(PyObject *type, PyObject *args) { - void *buffer; - Py_ssize_t buffer_len; - Py_ssize_t offset = 0; - PyObject *obj, *result; - StgDictObject *dict = PyType_stgdict(type); - assert (dict); + void *buffer; + Py_ssize_t buffer_len; + Py_ssize_t offset = 0; + PyObject *obj, *result; + StgDictObject *dict = PyType_stgdict(type); + assert (dict); - if (!PyArg_ParseTuple(args, + if (!PyArg_ParseTuple(args, #if (PY_VERSION_HEX < 0x02050000) - "O|i:from_buffer", + "O|i:from_buffer", #else - "O|n:from_buffer", + "O|n:from_buffer", #endif - &obj, &offset)) - return NULL; + &obj, &offset)) + return NULL; - if (-1 == PyObject_AsWriteBuffer(obj, &buffer, &buffer_len)) - return NULL; + if (-1 == PyObject_AsWriteBuffer(obj, &buffer, &buffer_len)) + return NULL; - if (offset < 0) { - PyErr_SetString(PyExc_ValueError, - "offset cannot be negative"); - return NULL; - } - if (dict->size > buffer_len - offset) { - PyErr_Format(PyExc_ValueError, + if (offset < 0) { + PyErr_SetString(PyExc_ValueError, + "offset cannot be negative"); + return NULL; + } + if (dict->size > buffer_len - offset) { + PyErr_Format(PyExc_ValueError, #if (PY_VERSION_HEX < 0x02050000) - "Buffer size too small (%d instead of at least %d bytes)", + "Buffer size too small (%d instead of at least %d bytes)", #else - "Buffer size too small (%zd instead of at least %zd bytes)", + "Buffer size too small (%zd instead of at least %zd bytes)", #endif - buffer_len, dict->size + offset); - return NULL; - } - - result = PyCData_AtAddress(type, (char *)buffer + offset); - if (result == NULL) - return NULL; - - Py_INCREF(obj); - if (-1 == KeepRef((CDataObject *)result, -1, obj)) { - Py_DECREF(result); - return NULL; - } - return result; + buffer_len, dict->size + offset); + return NULL; + } + + result = PyCData_AtAddress(type, (char *)buffer + offset); + if (result == NULL) + return NULL; + + Py_INCREF(obj); + if (-1 == KeepRef((CDataObject *)result, -1, obj)) { + Py_DECREF(result); + return NULL; + } + return result; } static char from_buffer_copy_doc[] = @@ -479,48 +479,48 @@ static PyObject * CDataType_from_buffer_copy(PyObject *type, PyObject *args) { - const void *buffer; - Py_ssize_t buffer_len; - Py_ssize_t offset = 0; - PyObject *obj, *result; - StgDictObject *dict = PyType_stgdict(type); - assert (dict); + const void *buffer; + Py_ssize_t buffer_len; + Py_ssize_t offset = 0; + PyObject *obj, *result; + StgDictObject *dict = PyType_stgdict(type); + assert (dict); - if (!PyArg_ParseTuple(args, + if (!PyArg_ParseTuple(args, #if (PY_VERSION_HEX < 0x02050000) - "O|i:from_buffer", + "O|i:from_buffer", #else - "O|n:from_buffer", + "O|n:from_buffer", #endif - &obj, &offset)) - return NULL; + &obj, &offset)) + return NULL; - if (-1 == PyObject_AsReadBuffer(obj, (const void**)&buffer, &buffer_len)) - return NULL; + if (-1 == PyObject_AsReadBuffer(obj, (const void**)&buffer, &buffer_len)) + return NULL; - if (offset < 0) { - PyErr_SetString(PyExc_ValueError, - "offset cannot be negative"); - return NULL; - } + if (offset < 0) { + PyErr_SetString(PyExc_ValueError, + "offset cannot be negative"); + return NULL; + } - if (dict->size > buffer_len - offset) { - PyErr_Format(PyExc_ValueError, + if (dict->size > buffer_len - offset) { + PyErr_Format(PyExc_ValueError, #if (PY_VERSION_HEX < 0x02050000) - "Buffer size too small (%d instead of at least %d bytes)", + "Buffer size too small (%d instead of at least %d bytes)", #else - "Buffer size too small (%zd instead of at least %zd bytes)", + "Buffer size too small (%zd instead of at least %zd bytes)", #endif - buffer_len, dict->size + offset); - return NULL; - } - - result = GenericPyCData_new((PyTypeObject *)type, NULL, NULL); - if (result == NULL) - return NULL; - memcpy(((CDataObject *)result)->b_ptr, - (char *)buffer+offset, dict->size); - return result; + buffer_len, dict->size + offset); + return NULL; + } + + result = GenericPyCData_new((PyTypeObject *)type, NULL, NULL); + if (result == NULL) + return NULL; + memcpy(((CDataObject *)result)->b_ptr, + (char *)buffer+offset, dict->size); + return result; } static char in_dll_doc[] = @@ -529,55 +529,55 @@ static PyObject * CDataType_in_dll(PyObject *type, PyObject *args) { - PyObject *dll; - char *name; - PyObject *obj; - void *handle; - void *address; - - if (!PyArg_ParseTuple(args, "Os:in_dll", &dll, &name)) - return NULL; - - obj = PyObject_GetAttrString(dll, "_handle"); - if (!obj) - return NULL; - if (!PyLong_Check(obj)) { - PyErr_SetString(PyExc_TypeError, - "the _handle attribute of the second argument must be an integer"); - Py_DECREF(obj); - return NULL; - } - handle = (void *)PyLong_AsVoidPtr(obj); - Py_DECREF(obj); - if (PyErr_Occurred()) { - PyErr_SetString(PyExc_ValueError, - "could not convert the _handle attribute to a pointer"); - return NULL; - } + PyObject *dll; + char *name; + PyObject *obj; + void *handle; + void *address; + + if (!PyArg_ParseTuple(args, "Os:in_dll", &dll, &name)) + return NULL; + + obj = PyObject_GetAttrString(dll, "_handle"); + if (!obj) + return NULL; + if (!PyLong_Check(obj)) { + PyErr_SetString(PyExc_TypeError, + "the _handle attribute of the second argument must be an integer"); + Py_DECREF(obj); + return NULL; + } + handle = (void *)PyLong_AsVoidPtr(obj); + Py_DECREF(obj); + if (PyErr_Occurred()) { + PyErr_SetString(PyExc_ValueError, + "could not convert the _handle attribute to a pointer"); + return NULL; + } #ifdef MS_WIN32 - address = (void *)GetProcAddress(handle, name); - if (!address) { - PyErr_Format(PyExc_ValueError, - "symbol '%s' not found", - name); - return NULL; - } + address = (void *)GetProcAddress(handle, name); + if (!address) { + PyErr_Format(PyExc_ValueError, + "symbol '%s' not found", + name); + return NULL; + } #else - address = (void *)ctypes_dlsym(handle, name); - if (!address) { + address = (void *)ctypes_dlsym(handle, name); + if (!address) { #ifdef __CYGWIN__ /* dlerror() isn't very helpful on cygwin */ - PyErr_Format(PyExc_ValueError, - "symbol '%s' not found (%s) ", - name); + PyErr_Format(PyExc_ValueError, + "symbol '%s' not found (%s) ", + name); #else - PyErr_SetString(PyExc_ValueError, ctypes_dlerror()); + PyErr_SetString(PyExc_ValueError, ctypes_dlerror()); #endif - return NULL; - } + return NULL; + } #endif - return PyCData_AtAddress(type, address); + return PyCData_AtAddress(type, address); } static char from_param_doc[] = @@ -586,210 +586,210 @@ static PyObject * CDataType_from_param(PyObject *type, PyObject *value) { - PyObject *as_parameter; - if (1 == PyObject_IsInstance(value, type)) { - Py_INCREF(value); - return value; - } - if (PyCArg_CheckExact(value)) { - PyCArgObject *p = (PyCArgObject *)value; - PyObject *ob = p->obj; - const char *ob_name; - StgDictObject *dict; - dict = PyType_stgdict(type); - - /* If we got a PyCArgObject, we must check if the object packed in it - is an instance of the type's dict->proto */ - if(dict && ob - && PyObject_IsInstance(ob, dict->proto)) { - Py_INCREF(value); - return value; - } - ob_name = (ob) ? Py_TYPE(ob)->tp_name : "???"; - PyErr_Format(PyExc_TypeError, - "expected %s instance instead of pointer to %s", - ((PyTypeObject *)type)->tp_name, ob_name); - return NULL; - } - - as_parameter = PyObject_GetAttrString(value, "_as_parameter_"); - if (as_parameter) { - value = CDataType_from_param(type, as_parameter); - Py_DECREF(as_parameter); - return value; - } - PyErr_Format(PyExc_TypeError, - "expected %s instance instead of %s", - ((PyTypeObject *)type)->tp_name, - Py_TYPE(value)->tp_name); - return NULL; + PyObject *as_parameter; + if (1 == PyObject_IsInstance(value, type)) { + Py_INCREF(value); + return value; + } + if (PyCArg_CheckExact(value)) { + PyCArgObject *p = (PyCArgObject *)value; + PyObject *ob = p->obj; + const char *ob_name; + StgDictObject *dict; + dict = PyType_stgdict(type); + + /* If we got a PyCArgObject, we must check if the object packed in it + is an instance of the type's dict->proto */ + if(dict && ob + && PyObject_IsInstance(ob, dict->proto)) { + Py_INCREF(value); + return value; + } + ob_name = (ob) ? Py_TYPE(ob)->tp_name : "???"; + PyErr_Format(PyExc_TypeError, + "expected %s instance instead of pointer to %s", + ((PyTypeObject *)type)->tp_name, ob_name); + return NULL; + } + + as_parameter = PyObject_GetAttrString(value, "_as_parameter_"); + if (as_parameter) { + value = CDataType_from_param(type, as_parameter); + Py_DECREF(as_parameter); + return value; + } + PyErr_Format(PyExc_TypeError, + "expected %s instance instead of %s", + ((PyTypeObject *)type)->tp_name, + Py_TYPE(value)->tp_name); + return NULL; } static PyMethodDef CDataType_methods[] = { - { "from_param", CDataType_from_param, METH_O, from_param_doc }, - { "from_address", CDataType_from_address, METH_O, from_address_doc }, - { "from_buffer", CDataType_from_buffer, METH_VARARGS, from_buffer_doc, }, - { "from_buffer_copy", CDataType_from_buffer_copy, METH_VARARGS, from_buffer_copy_doc, }, - { "in_dll", CDataType_in_dll, METH_VARARGS, in_dll_doc }, - { NULL, NULL }, + { "from_param", CDataType_from_param, METH_O, from_param_doc }, + { "from_address", CDataType_from_address, METH_O, from_address_doc }, + { "from_buffer", CDataType_from_buffer, METH_VARARGS, from_buffer_doc, }, + { "from_buffer_copy", CDataType_from_buffer_copy, METH_VARARGS, from_buffer_copy_doc, }, + { "in_dll", CDataType_in_dll, METH_VARARGS, in_dll_doc }, + { NULL, NULL }, }; static PyObject * CDataType_repeat(PyObject *self, Py_ssize_t length) { - if (length < 0) - return PyErr_Format(PyExc_ValueError, - "Array length must be >= 0, not %zd", - length); - return PyCArrayType_from_ctype(self, length); + if (length < 0) + return PyErr_Format(PyExc_ValueError, + "Array length must be >= 0, not %zd", + length); + return PyCArrayType_from_ctype(self, length); } static PySequenceMethods CDataType_as_sequence = { - 0, /* inquiry sq_length; */ - 0, /* binaryfunc sq_concat; */ - CDataType_repeat, /* intargfunc sq_repeat; */ - 0, /* intargfunc sq_item; */ - 0, /* intintargfunc sq_slice; */ - 0, /* intobjargproc sq_ass_item; */ - 0, /* intintobjargproc sq_ass_slice; */ - 0, /* objobjproc sq_contains; */ - - 0, /* binaryfunc sq_inplace_concat; */ - 0, /* intargfunc sq_inplace_repeat; */ + 0, /* inquiry sq_length; */ + 0, /* binaryfunc sq_concat; */ + CDataType_repeat, /* intargfunc sq_repeat; */ + 0, /* intargfunc sq_item; */ + 0, /* intintargfunc sq_slice; */ + 0, /* intobjargproc sq_ass_item; */ + 0, /* intintobjargproc sq_ass_slice; */ + 0, /* objobjproc sq_contains; */ + + 0, /* binaryfunc sq_inplace_concat; */ + 0, /* intargfunc sq_inplace_repeat; */ }; static int CDataType_clear(PyTypeObject *self) { - StgDictObject *dict = PyType_stgdict((PyObject *)self); - if (dict) - Py_CLEAR(dict->proto); - return PyType_Type.tp_clear((PyObject *)self); + StgDictObject *dict = PyType_stgdict((PyObject *)self); + if (dict) + Py_CLEAR(dict->proto); + return PyType_Type.tp_clear((PyObject *)self); } static int CDataType_traverse(PyTypeObject *self, visitproc visit, void *arg) { - StgDictObject *dict = PyType_stgdict((PyObject *)self); - if (dict) - Py_VISIT(dict->proto); - return PyType_Type.tp_traverse((PyObject *)self, visit, arg); + StgDictObject *dict = PyType_stgdict((PyObject *)self); + if (dict) + Py_VISIT(dict->proto); + return PyType_Type.tp_traverse((PyObject *)self, visit, arg); } static int PyCStructType_setattro(PyObject *self, PyObject *key, PyObject *value) { - /* XXX Should we disallow deleting _fields_? */ - if (-1 == PyType_Type.tp_setattro(self, key, value)) - return -1; - - if (value && PyUnicode_Check(key) && - /* XXX struni _PyUnicode_AsString can fail (also in other places)! */ - 0 == strcmp(_PyUnicode_AsString(key), "_fields_")) - return PyCStructUnionType_update_stgdict(self, value, 1); - return 0; + /* XXX Should we disallow deleting _fields_? */ + if (-1 == PyType_Type.tp_setattro(self, key, value)) + return -1; + + if (value && PyUnicode_Check(key) && + /* XXX struni _PyUnicode_AsString can fail (also in other places)! */ + 0 == strcmp(_PyUnicode_AsString(key), "_fields_")) + return PyCStructUnionType_update_stgdict(self, value, 1); + return 0; } static int UnionType_setattro(PyObject *self, PyObject *key, PyObject *value) { - /* XXX Should we disallow deleting _fields_? */ - if (-1 == PyObject_GenericSetAttr(self, key, value)) - return -1; - - if (PyUnicode_Check(key) && - 0 == strcmp(_PyUnicode_AsString(key), "_fields_")) - return PyCStructUnionType_update_stgdict(self, value, 0); - return 0; + /* XXX Should we disallow deleting _fields_? */ + if (-1 == PyObject_GenericSetAttr(self, key, value)) + return -1; + + if (PyUnicode_Check(key) && + 0 == strcmp(_PyUnicode_AsString(key), "_fields_")) + return PyCStructUnionType_update_stgdict(self, value, 0); + return 0; } PyTypeObject PyCStructType_Type = { - PyVarObject_HEAD_INIT(NULL, 0) - "_ctypes.PyCStructType", /* tp_name */ - 0, /* tp_basicsize */ - 0, /* tp_itemsize */ - 0, /* tp_dealloc */ - 0, /* tp_print */ - 0, /* tp_getattr */ - 0, /* tp_setattr */ - 0, /* tp_reserved */ - 0, /* tp_repr */ - 0, /* tp_as_number */ - &CDataType_as_sequence, /* tp_as_sequence */ - 0, /* tp_as_mapping */ - 0, /* tp_hash */ - 0, /* tp_call */ - 0, /* tp_str */ - 0, /* tp_getattro */ - PyCStructType_setattro, /* tp_setattro */ - 0, /* tp_as_buffer */ - Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC, /* tp_flags */ - "metatype for the CData Objects", /* tp_doc */ - (traverseproc)CDataType_traverse, /* tp_traverse */ - (inquiry)CDataType_clear, /* tp_clear */ - 0, /* tp_richcompare */ - 0, /* tp_weaklistoffset */ - 0, /* tp_iter */ - 0, /* tp_iternext */ - CDataType_methods, /* tp_methods */ - 0, /* tp_members */ - 0, /* tp_getset */ - 0, /* tp_base */ - 0, /* tp_dict */ - 0, /* tp_descr_get */ - 0, /* tp_descr_set */ - 0, /* tp_dictoffset */ - 0, /* tp_init */ - 0, /* tp_alloc */ - PyCStructType_new, /* tp_new */ - 0, /* tp_free */ + PyVarObject_HEAD_INIT(NULL, 0) + "_ctypes.PyCStructType", /* tp_name */ + 0, /* tp_basicsize */ + 0, /* tp_itemsize */ + 0, /* tp_dealloc */ + 0, /* tp_print */ + 0, /* tp_getattr */ + 0, /* tp_setattr */ + 0, /* tp_reserved */ + 0, /* tp_repr */ + 0, /* tp_as_number */ + &CDataType_as_sequence, /* tp_as_sequence */ + 0, /* tp_as_mapping */ + 0, /* tp_hash */ + 0, /* tp_call */ + 0, /* tp_str */ + 0, /* tp_getattro */ + PyCStructType_setattro, /* tp_setattro */ + 0, /* tp_as_buffer */ + Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC, /* tp_flags */ + "metatype for the CData Objects", /* tp_doc */ + (traverseproc)CDataType_traverse, /* tp_traverse */ + (inquiry)CDataType_clear, /* tp_clear */ + 0, /* tp_richcompare */ + 0, /* tp_weaklistoffset */ + 0, /* tp_iter */ + 0, /* tp_iternext */ + CDataType_methods, /* tp_methods */ + 0, /* tp_members */ + 0, /* tp_getset */ + 0, /* tp_base */ + 0, /* tp_dict */ + 0, /* tp_descr_get */ + 0, /* tp_descr_set */ + 0, /* tp_dictoffset */ + 0, /* tp_init */ + 0, /* tp_alloc */ + PyCStructType_new, /* tp_new */ + 0, /* tp_free */ }; static PyTypeObject UnionType_Type = { - PyVarObject_HEAD_INIT(NULL, 0) - "_ctypes.UnionType", /* tp_name */ - 0, /* tp_basicsize */ - 0, /* tp_itemsize */ - 0, /* tp_dealloc */ - 0, /* tp_print */ - 0, /* tp_getattr */ - 0, /* tp_setattr */ - 0, /* tp_reserved */ - 0, /* tp_repr */ - 0, /* tp_as_number */ - &CDataType_as_sequence, /* tp_as_sequence */ - 0, /* tp_as_mapping */ - 0, /* tp_hash */ - 0, /* tp_call */ - 0, /* tp_str */ - 0, /* tp_getattro */ - UnionType_setattro, /* tp_setattro */ - 0, /* tp_as_buffer */ - Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC, /* tp_flags */ - "metatype for the CData Objects", /* tp_doc */ - (traverseproc)CDataType_traverse, /* tp_traverse */ - (inquiry)CDataType_clear, /* tp_clear */ - 0, /* tp_richcompare */ - 0, /* tp_weaklistoffset */ - 0, /* tp_iter */ - 0, /* tp_iternext */ - CDataType_methods, /* tp_methods */ - 0, /* tp_members */ - 0, /* tp_getset */ - 0, /* tp_base */ - 0, /* tp_dict */ - 0, /* tp_descr_get */ - 0, /* tp_descr_set */ - 0, /* tp_dictoffset */ - 0, /* tp_init */ - 0, /* tp_alloc */ - UnionType_new, /* tp_new */ - 0, /* tp_free */ + PyVarObject_HEAD_INIT(NULL, 0) + "_ctypes.UnionType", /* tp_name */ + 0, /* tp_basicsize */ + 0, /* tp_itemsize */ + 0, /* tp_dealloc */ + 0, /* tp_print */ + 0, /* tp_getattr */ + 0, /* tp_setattr */ + 0, /* tp_reserved */ + 0, /* tp_repr */ + 0, /* tp_as_number */ + &CDataType_as_sequence, /* tp_as_sequence */ + 0, /* tp_as_mapping */ + 0, /* tp_hash */ + 0, /* tp_call */ + 0, /* tp_str */ + 0, /* tp_getattro */ + UnionType_setattro, /* tp_setattro */ + 0, /* tp_as_buffer */ + Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC, /* tp_flags */ + "metatype for the CData Objects", /* tp_doc */ + (traverseproc)CDataType_traverse, /* tp_traverse */ + (inquiry)CDataType_clear, /* tp_clear */ + 0, /* tp_richcompare */ + 0, /* tp_weaklistoffset */ + 0, /* tp_iter */ + 0, /* tp_iternext */ + CDataType_methods, /* tp_methods */ + 0, /* tp_members */ + 0, /* tp_getset */ + 0, /* tp_base */ + 0, /* tp_dict */ + 0, /* tp_descr_get */ + 0, /* tp_descr_set */ + 0, /* tp_dictoffset */ + 0, /* tp_init */ + 0, /* tp_alloc */ + UnionType_new, /* tp_new */ + 0, /* tp_free */ }; - + /******************************************************************/ /* @@ -809,124 +809,124 @@ static int PyCPointerType_SetProto(StgDictObject *stgdict, PyObject *proto) { - if (!proto || !PyType_Check(proto)) { - PyErr_SetString(PyExc_TypeError, - "_type_ must be a type"); - return -1; - } - if (!PyType_stgdict(proto)) { - PyErr_SetString(PyExc_TypeError, - "_type_ must have storage info"); - return -1; - } - Py_INCREF(proto); - Py_XDECREF(stgdict->proto); - stgdict->proto = proto; - return 0; + if (!proto || !PyType_Check(proto)) { + PyErr_SetString(PyExc_TypeError, + "_type_ must be a type"); + return -1; + } + if (!PyType_stgdict(proto)) { + PyErr_SetString(PyExc_TypeError, + "_type_ must have storage info"); + return -1; + } + Py_INCREF(proto); + Py_XDECREF(stgdict->proto); + stgdict->proto = proto; + return 0; } static PyCArgObject * PyCPointerType_paramfunc(CDataObject *self) { - PyCArgObject *parg; + PyCArgObject *parg; - parg = PyCArgObject_new(); - if (parg == NULL) - return NULL; - - parg->tag = 'P'; - parg->pffi_type = &ffi_type_pointer; - Py_INCREF(self); - parg->obj = (PyObject *)self; - parg->value.p = *(void **)self->b_ptr; - return parg; + parg = PyCArgObject_new(); + if (parg == NULL) + return NULL; + + parg->tag = 'P'; + parg->pffi_type = &ffi_type_pointer; + Py_INCREF(self); + parg->obj = (PyObject *)self; + parg->value.p = *(void **)self->b_ptr; + return parg; } static PyObject * PyCPointerType_new(PyTypeObject *type, PyObject *args, PyObject *kwds) { - PyTypeObject *result; - StgDictObject *stgdict; - PyObject *proto; - PyObject *typedict; - - typedict = PyTuple_GetItem(args, 2); - if (!typedict) - return NULL; + PyTypeObject *result; + StgDictObject *stgdict; + PyObject *proto; + PyObject *typedict; + + typedict = PyTuple_GetItem(args, 2); + if (!typedict) + return NULL; /* stgdict items size, align, length contain info about pointers itself, stgdict->proto has info about the pointed to type! */ - stgdict = (StgDictObject *)PyObject_CallObject( - (PyObject *)&PyCStgDict_Type, NULL); - if (!stgdict) - return NULL; - stgdict->size = sizeof(void *); - stgdict->align = _ctypes_get_fielddesc("P")->pffi_type->alignment; - stgdict->length = 1; - stgdict->ffi_type_pointer = ffi_type_pointer; - stgdict->paramfunc = PyCPointerType_paramfunc; - stgdict->flags |= TYPEFLAG_ISPOINTER; - - proto = PyDict_GetItemString(typedict, "_type_"); /* Borrowed ref */ - if (proto && -1 == PyCPointerType_SetProto(stgdict, proto)) { - Py_DECREF((PyObject *)stgdict); - return NULL; - } - - if (proto) { - StgDictObject *itemdict = PyType_stgdict(proto); - assert(itemdict); - /* If itemdict->format is NULL, then this is a pointer to an - incomplete type. We create a generic format string - 'pointer to bytes' in this case. XXX Better would be to - fix the format string later... - */ - stgdict->format = _ctypes_alloc_format_string("&", - itemdict->format ? itemdict->format : "B"); - if (stgdict->format == NULL) { - Py_DECREF((PyObject *)stgdict); - return NULL; - } - } - - /* create the new instance (which is a class, - since we are a metatype!) */ - result = (PyTypeObject *)PyType_Type.tp_new(type, args, kwds); - if (result == NULL) { - Py_DECREF((PyObject *)stgdict); - return NULL; - } - - /* replace the class dict by our updated spam dict */ - if (-1 == PyDict_Update((PyObject *)stgdict, result->tp_dict)) { - Py_DECREF(result); - Py_DECREF((PyObject *)stgdict); - return NULL; - } - Py_DECREF(result->tp_dict); - result->tp_dict = (PyObject *)stgdict; + stgdict = (StgDictObject *)PyObject_CallObject( + (PyObject *)&PyCStgDict_Type, NULL); + if (!stgdict) + return NULL; + stgdict->size = sizeof(void *); + stgdict->align = _ctypes_get_fielddesc("P")->pffi_type->alignment; + stgdict->length = 1; + stgdict->ffi_type_pointer = ffi_type_pointer; + stgdict->paramfunc = PyCPointerType_paramfunc; + stgdict->flags |= TYPEFLAG_ISPOINTER; + + proto = PyDict_GetItemString(typedict, "_type_"); /* Borrowed ref */ + if (proto && -1 == PyCPointerType_SetProto(stgdict, proto)) { + Py_DECREF((PyObject *)stgdict); + return NULL; + } + + if (proto) { + StgDictObject *itemdict = PyType_stgdict(proto); + assert(itemdict); + /* If itemdict->format is NULL, then this is a pointer to an + incomplete type. We create a generic format string + 'pointer to bytes' in this case. XXX Better would be to + fix the format string later... + */ + stgdict->format = _ctypes_alloc_format_string("&", + itemdict->format ? itemdict->format : "B"); + if (stgdict->format == NULL) { + Py_DECREF((PyObject *)stgdict); + return NULL; + } + } + + /* create the new instance (which is a class, + since we are a metatype!) */ + result = (PyTypeObject *)PyType_Type.tp_new(type, args, kwds); + if (result == NULL) { + Py_DECREF((PyObject *)stgdict); + return NULL; + } + + /* replace the class dict by our updated spam dict */ + if (-1 == PyDict_Update((PyObject *)stgdict, result->tp_dict)) { + Py_DECREF(result); + Py_DECREF((PyObject *)stgdict); + return NULL; + } + Py_DECREF(result->tp_dict); + result->tp_dict = (PyObject *)stgdict; - return (PyObject *)result; + return (PyObject *)result; } static PyObject * PyCPointerType_set_type(PyTypeObject *self, PyObject *type) { - StgDictObject *dict; + StgDictObject *dict; - dict = PyType_stgdict((PyObject *)self); - assert(dict); + dict = PyType_stgdict((PyObject *)self); + assert(dict); - if (-1 == PyCPointerType_SetProto(dict, type)) - return NULL; + if (-1 == PyCPointerType_SetProto(dict, type)) + return NULL; - if (-1 == PyDict_SetItemString((PyObject *)dict, "_type_", type)) - return NULL; + if (-1 == PyDict_SetItemString((PyObject *)dict, "_type_", type)) + return NULL; - Py_INCREF(Py_None); - return Py_None; + Py_INCREF(Py_None); + return Py_None; } static PyObject *_byref(PyObject *); @@ -934,98 +934,98 @@ static PyObject * PyCPointerType_from_param(PyObject *type, PyObject *value) { - StgDictObject *typedict; + StgDictObject *typedict; - if (value == Py_None) { - /* ConvParam will convert to a NULL pointer later */ - Py_INCREF(value); - return value; - } - - typedict = PyType_stgdict(type); - assert(typedict); /* Cannot be NULL for pointer types */ - - /* If we expect POINTER(), but receive a instance, accept - it by calling byref(). - */ - switch (PyObject_IsInstance(value, typedict->proto)) { - case 1: - Py_INCREF(value); /* _byref steals a refcount */ - return _byref(value); - case -1: - PyErr_Clear(); - break; - default: - break; - } - - if (PointerObject_Check(value) || ArrayObject_Check(value)) { - /* Array instances are also pointers when - the item types are the same. - */ - StgDictObject *v = PyObject_stgdict(value); - assert(v); /* Cannot be NULL for pointer or array objects */ - if (PyObject_IsSubclass(v->proto, typedict->proto)) { - Py_INCREF(value); - return value; - } - } - return CDataType_from_param(type, value); + if (value == Py_None) { + /* ConvParam will convert to a NULL pointer later */ + Py_INCREF(value); + return value; + } + + typedict = PyType_stgdict(type); + assert(typedict); /* Cannot be NULL for pointer types */ + + /* If we expect POINTER(), but receive a instance, accept + it by calling byref(). + */ + switch (PyObject_IsInstance(value, typedict->proto)) { + case 1: + Py_INCREF(value); /* _byref steals a refcount */ + return _byref(value); + case -1: + PyErr_Clear(); + break; + default: + break; + } + + if (PointerObject_Check(value) || ArrayObject_Check(value)) { + /* Array instances are also pointers when + the item types are the same. + */ + StgDictObject *v = PyObject_stgdict(value); + assert(v); /* Cannot be NULL for pointer or array objects */ + if (PyObject_IsSubclass(v->proto, typedict->proto)) { + Py_INCREF(value); + return value; + } + } + return CDataType_from_param(type, value); } static PyMethodDef PyCPointerType_methods[] = { - { "from_address", CDataType_from_address, METH_O, from_address_doc }, - { "from_buffer", CDataType_from_buffer, METH_VARARGS, from_buffer_doc, }, - { "from_buffer_copy", CDataType_from_buffer_copy, METH_VARARGS, from_buffer_copy_doc, }, - { "in_dll", CDataType_in_dll, METH_VARARGS, in_dll_doc}, - { "from_param", (PyCFunction)PyCPointerType_from_param, METH_O, from_param_doc}, - { "set_type", (PyCFunction)PyCPointerType_set_type, METH_O }, - { NULL, NULL }, + { "from_address", CDataType_from_address, METH_O, from_address_doc }, + { "from_buffer", CDataType_from_buffer, METH_VARARGS, from_buffer_doc, }, + { "from_buffer_copy", CDataType_from_buffer_copy, METH_VARARGS, from_buffer_copy_doc, }, + { "in_dll", CDataType_in_dll, METH_VARARGS, in_dll_doc}, + { "from_param", (PyCFunction)PyCPointerType_from_param, METH_O, from_param_doc}, + { "set_type", (PyCFunction)PyCPointerType_set_type, METH_O }, + { NULL, NULL }, }; PyTypeObject PyCPointerType_Type = { - PyVarObject_HEAD_INIT(NULL, 0) - "_ctypes.PyCPointerType", /* tp_name */ - 0, /* tp_basicsize */ - 0, /* tp_itemsize */ - 0, /* tp_dealloc */ - 0, /* tp_print */ - 0, /* tp_getattr */ - 0, /* tp_setattr */ - 0, /* tp_reserved */ - 0, /* tp_repr */ - 0, /* tp_as_number */ - &CDataType_as_sequence, /* tp_as_sequence */ - 0, /* tp_as_mapping */ - 0, /* tp_hash */ - 0, /* tp_call */ - 0, /* tp_str */ - 0, /* tp_getattro */ - 0, /* tp_setattro */ - 0, /* tp_as_buffer */ - Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC, /* tp_flags */ - "metatype for the Pointer Objects", /* tp_doc */ - (traverseproc)CDataType_traverse, /* tp_traverse */ - (inquiry)CDataType_clear, /* tp_clear */ - 0, /* tp_richcompare */ - 0, /* tp_weaklistoffset */ - 0, /* tp_iter */ - 0, /* tp_iternext */ - PyCPointerType_methods, /* tp_methods */ - 0, /* tp_members */ - 0, /* tp_getset */ - 0, /* tp_base */ - 0, /* tp_dict */ - 0, /* tp_descr_get */ - 0, /* tp_descr_set */ - 0, /* tp_dictoffset */ - 0, /* tp_init */ - 0, /* tp_alloc */ - PyCPointerType_new, /* tp_new */ - 0, /* tp_free */ + PyVarObject_HEAD_INIT(NULL, 0) + "_ctypes.PyCPointerType", /* tp_name */ + 0, /* tp_basicsize */ + 0, /* tp_itemsize */ + 0, /* tp_dealloc */ + 0, /* tp_print */ + 0, /* tp_getattr */ + 0, /* tp_setattr */ + 0, /* tp_reserved */ + 0, /* tp_repr */ + 0, /* tp_as_number */ + &CDataType_as_sequence, /* tp_as_sequence */ + 0, /* tp_as_mapping */ + 0, /* tp_hash */ + 0, /* tp_call */ + 0, /* tp_str */ + 0, /* tp_getattro */ + 0, /* tp_setattro */ + 0, /* tp_as_buffer */ + Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC, /* tp_flags */ + "metatype for the Pointer Objects", /* tp_doc */ + (traverseproc)CDataType_traverse, /* tp_traverse */ + (inquiry)CDataType_clear, /* tp_clear */ + 0, /* tp_richcompare */ + 0, /* tp_weaklistoffset */ + 0, /* tp_iter */ + 0, /* tp_iternext */ + PyCPointerType_methods, /* tp_methods */ + 0, /* tp_members */ + 0, /* tp_getset */ + 0, /* tp_base */ + 0, /* tp_dict */ + 0, /* tp_descr_get */ + 0, /* tp_descr_set */ + 0, /* tp_dictoffset */ + 0, /* tp_init */ + 0, /* tp_alloc */ + PyCPointerType_new, /* tp_new */ + 0, /* tp_free */ }; - + /******************************************************************/ /* PyCArrayType_Type @@ -1038,152 +1038,152 @@ static int CharArray_set_raw(CDataObject *self, PyObject *value) { - char *ptr; - Py_ssize_t size; - Py_buffer view; - - if (PyObject_GetBuffer(value, &view, PyBUF_SIMPLE) < 0) - return -1; - size = view.len; - ptr = view.buf; - if (size > self->b_size) { - PyErr_SetString(PyExc_ValueError, - "string too long"); - goto fail; - } + char *ptr; + Py_ssize_t size; + Py_buffer view; + + if (PyObject_GetBuffer(value, &view, PyBUF_SIMPLE) < 0) + return -1; + size = view.len; + ptr = view.buf; + if (size > self->b_size) { + PyErr_SetString(PyExc_ValueError, + "string too long"); + goto fail; + } - memcpy(self->b_ptr, ptr, size); + memcpy(self->b_ptr, ptr, size); - PyBuffer_Release(&view); - return 0; + PyBuffer_Release(&view); + return 0; fail: - PyBuffer_Release(&view); - return -1; + PyBuffer_Release(&view); + return -1; } static PyObject * CharArray_get_raw(CDataObject *self) { - return PyBytes_FromStringAndSize(self->b_ptr, self->b_size); + return PyBytes_FromStringAndSize(self->b_ptr, self->b_size); } static PyObject * CharArray_get_value(CDataObject *self) { - int i; - char *ptr = self->b_ptr; - for (i = 0; i < self->b_size; ++i) - if (*ptr++ == '\0') - break; - return PyBytes_FromStringAndSize(self->b_ptr, i); + int i; + char *ptr = self->b_ptr; + for (i = 0; i < self->b_size; ++i) + if (*ptr++ == '\0') + break; + return PyBytes_FromStringAndSize(self->b_ptr, i); } static int CharArray_set_value(CDataObject *self, PyObject *value) { - char *ptr; - Py_ssize_t size; + char *ptr; + Py_ssize_t size; + + if (value == NULL) { + PyErr_SetString(PyExc_TypeError, + "can't delete attribute"); + return -1; + } - if (value == NULL) { - PyErr_SetString(PyExc_TypeError, - "can't delete attribute"); - return -1; - } - - if (PyUnicode_Check(value)) { - value = PyUnicode_AsEncodedString(value, - _ctypes_conversion_encoding, - _ctypes_conversion_errors); - if (!value) - return -1; - } else if (!PyBytes_Check(value)) { - PyErr_Format(PyExc_TypeError, - "str/bytes expected instead of %s instance", - Py_TYPE(value)->tp_name); - return -1; - } else - Py_INCREF(value); - size = PyBytes_GET_SIZE(value); - if (size > self->b_size) { - PyErr_SetString(PyExc_ValueError, - "string too long"); - Py_DECREF(value); - return -1; - } - - ptr = PyBytes_AS_STRING(value); - memcpy(self->b_ptr, ptr, size); - if (size < self->b_size) - self->b_ptr[size] = '\0'; - Py_DECREF(value); + if (PyUnicode_Check(value)) { + value = PyUnicode_AsEncodedString(value, + _ctypes_conversion_encoding, + _ctypes_conversion_errors); + if (!value) + return -1; + } else if (!PyBytes_Check(value)) { + PyErr_Format(PyExc_TypeError, + "str/bytes expected instead of %s instance", + Py_TYPE(value)->tp_name); + return -1; + } else + Py_INCREF(value); + size = PyBytes_GET_SIZE(value); + if (size > self->b_size) { + PyErr_SetString(PyExc_ValueError, + "string too long"); + Py_DECREF(value); + return -1; + } - return 0; + ptr = PyBytes_AS_STRING(value); + memcpy(self->b_ptr, ptr, size); + if (size < self->b_size) + self->b_ptr[size] = '\0'; + Py_DECREF(value); + + return 0; } static PyGetSetDef CharArray_getsets[] = { - { "raw", (getter)CharArray_get_raw, (setter)CharArray_set_raw, - "value", NULL }, - { "value", (getter)CharArray_get_value, (setter)CharArray_set_value, - "string value"}, - { NULL, NULL } + { "raw", (getter)CharArray_get_raw, (setter)CharArray_set_raw, + "value", NULL }, + { "value", (getter)CharArray_get_value, (setter)CharArray_set_value, + "string value"}, + { NULL, NULL } }; #ifdef CTYPES_UNICODE static PyObject * WCharArray_get_value(CDataObject *self) { - unsigned int i; - wchar_t *ptr = (wchar_t *)self->b_ptr; - for (i = 0; i < self->b_size/sizeof(wchar_t); ++i) - if (*ptr++ == (wchar_t)0) - break; - return PyUnicode_FromWideChar((wchar_t *)self->b_ptr, i); + unsigned int i; + wchar_t *ptr = (wchar_t *)self->b_ptr; + for (i = 0; i < self->b_size/sizeof(wchar_t); ++i) + if (*ptr++ == (wchar_t)0) + break; + return PyUnicode_FromWideChar((wchar_t *)self->b_ptr, i); } static int WCharArray_set_value(CDataObject *self, PyObject *value) { - Py_ssize_t result = 0; + Py_ssize_t result = 0; - if (value == NULL) { - PyErr_SetString(PyExc_TypeError, - "can't delete attribute"); - return -1; - } - if (PyBytes_Check(value)) { - value = PyUnicode_FromEncodedObject(value, - _ctypes_conversion_encoding, - _ctypes_conversion_errors); - if (!value) - return -1; - } else if (!PyUnicode_Check(value)) { - PyErr_Format(PyExc_TypeError, - "unicode string expected instead of %s instance", - Py_TYPE(value)->tp_name); - return -1; - } else - Py_INCREF(value); - if ((unsigned)PyUnicode_GET_SIZE(value) > self->b_size/sizeof(wchar_t)) { - PyErr_SetString(PyExc_ValueError, - "string too long"); - result = -1; - goto done; - } - result = PyUnicode_AsWideChar((PyUnicodeObject *)value, - (wchar_t *)self->b_ptr, - self->b_size/sizeof(wchar_t)); - if (result >= 0 && (size_t)result < self->b_size/sizeof(wchar_t)) - ((wchar_t *)self->b_ptr)[result] = (wchar_t)0; + if (value == NULL) { + PyErr_SetString(PyExc_TypeError, + "can't delete attribute"); + return -1; + } + if (PyBytes_Check(value)) { + value = PyUnicode_FromEncodedObject(value, + _ctypes_conversion_encoding, + _ctypes_conversion_errors); + if (!value) + return -1; + } else if (!PyUnicode_Check(value)) { + PyErr_Format(PyExc_TypeError, + "unicode string expected instead of %s instance", + Py_TYPE(value)->tp_name); + return -1; + } else + Py_INCREF(value); + if ((unsigned)PyUnicode_GET_SIZE(value) > self->b_size/sizeof(wchar_t)) { + PyErr_SetString(PyExc_ValueError, + "string too long"); + result = -1; + goto done; + } + result = PyUnicode_AsWideChar((PyUnicodeObject *)value, + (wchar_t *)self->b_ptr, + self->b_size/sizeof(wchar_t)); + if (result >= 0 && (size_t)result < self->b_size/sizeof(wchar_t)) + ((wchar_t *)self->b_ptr)[result] = (wchar_t)0; done: - Py_DECREF(value); + Py_DECREF(value); - return result >= 0 ? 0 : -1; + return result >= 0 ? 0 : -1; } static PyGetSetDef WCharArray_getsets[] = { - { "value", (getter)WCharArray_get_value, (setter)WCharArray_set_value, - "string value"}, - { NULL, NULL } + { "value", (getter)WCharArray_get_value, (setter)WCharArray_set_value, + "string value"}, + { NULL, NULL } }; #endif @@ -1198,236 +1198,236 @@ static int add_methods(PyTypeObject *type, PyMethodDef *meth) { - PyObject *dict = type->tp_dict; - for (; meth->ml_name != NULL; meth++) { - PyObject *descr; - descr = PyDescr_NewMethod(type, meth); - if (descr == NULL) - return -1; - if (PyDict_SetItemString(dict,meth->ml_name, descr) < 0) - return -1; - Py_DECREF(descr); - } - return 0; + PyObject *dict = type->tp_dict; + for (; meth->ml_name != NULL; meth++) { + PyObject *descr; + descr = PyDescr_NewMethod(type, meth); + if (descr == NULL) + return -1; + if (PyDict_SetItemString(dict,meth->ml_name, descr) < 0) + return -1; + Py_DECREF(descr); + } + return 0; } static int add_members(PyTypeObject *type, PyMemberDef *memb) { - PyObject *dict = type->tp_dict; - for (; memb->name != NULL; memb++) { - PyObject *descr; - descr = PyDescr_NewMember(type, memb); - if (descr == NULL) - return -1; - if (PyDict_SetItemString(dict, memb->name, descr) < 0) - return -1; - Py_DECREF(descr); - } - return 0; + PyObject *dict = type->tp_dict; + for (; memb->name != NULL; memb++) { + PyObject *descr; + descr = PyDescr_NewMember(type, memb); + if (descr == NULL) + return -1; + if (PyDict_SetItemString(dict, memb->name, descr) < 0) + return -1; + Py_DECREF(descr); + } + return 0; } */ static int add_getset(PyTypeObject *type, PyGetSetDef *gsp) { - PyObject *dict = type->tp_dict; - for (; gsp->name != NULL; gsp++) { - PyObject *descr; - descr = PyDescr_NewGetSet(type, gsp); - if (descr == NULL) - return -1; - if (PyDict_SetItemString(dict, gsp->name, descr) < 0) - return -1; - Py_DECREF(descr); - } - return 0; + PyObject *dict = type->tp_dict; + for (; gsp->name != NULL; gsp++) { + PyObject *descr; + descr = PyDescr_NewGetSet(type, gsp); + if (descr == NULL) + return -1; + if (PyDict_SetItemString(dict, gsp->name, descr) < 0) + return -1; + Py_DECREF(descr); + } + return 0; } static PyCArgObject * PyCArrayType_paramfunc(CDataObject *self) { - PyCArgObject *p = PyCArgObject_new(); - if (p == NULL) - return NULL; - p->tag = 'P'; - p->pffi_type = &ffi_type_pointer; - p->value.p = (char *)self->b_ptr; - Py_INCREF(self); - p->obj = (PyObject *)self; - return p; + PyCArgObject *p = PyCArgObject_new(); + if (p == NULL) + return NULL; + p->tag = 'P'; + p->pffi_type = &ffi_type_pointer; + p->value.p = (char *)self->b_ptr; + Py_INCREF(self); + p->obj = (PyObject *)self; + return p; } static PyObject * PyCArrayType_new(PyTypeObject *type, PyObject *args, PyObject *kwds) { - PyTypeObject *result; - StgDictObject *stgdict; - StgDictObject *itemdict; - PyObject *proto; - PyObject *typedict; - long length; - int overflow; - Py_ssize_t itemsize, itemalign; - char buf[32]; - - typedict = PyTuple_GetItem(args, 2); - if (!typedict) - return NULL; - - proto = PyDict_GetItemString(typedict, "_length_"); /* Borrowed ref */ - if (!proto || !PyLong_Check(proto)) { - PyErr_SetString(PyExc_AttributeError, - "class must define a '_length_' attribute, " - "which must be a positive integer"); - return NULL; - } - length = PyLong_AsLongAndOverflow(proto, &overflow); - if (overflow) { - PyErr_SetString(PyExc_OverflowError, - "The '_length_' attribute is too large"); - return NULL; - } - - proto = PyDict_GetItemString(typedict, "_type_"); /* Borrowed ref */ - if (!proto) { - PyErr_SetString(PyExc_AttributeError, - "class must define a '_type_' attribute"); - return NULL; - } - - stgdict = (StgDictObject *)PyObject_CallObject( - (PyObject *)&PyCStgDict_Type, NULL); - if (!stgdict) - return NULL; - - itemdict = PyType_stgdict(proto); - if (!itemdict) { - PyErr_SetString(PyExc_TypeError, - "_type_ must have storage info"); - Py_DECREF((PyObject *)stgdict); - return NULL; - } - - assert(itemdict->format); - if (itemdict->format[0] == '(') { - sprintf(buf, "(%ld,", length); - stgdict->format = _ctypes_alloc_format_string(buf, itemdict->format+1); - } else { - sprintf(buf, "(%ld)", length); - stgdict->format = _ctypes_alloc_format_string(buf, itemdict->format); - } - if (stgdict->format == NULL) { - Py_DECREF((PyObject *)stgdict); - return NULL; - } - stgdict->ndim = itemdict->ndim + 1; - stgdict->shape = PyMem_Malloc(sizeof(Py_ssize_t *) * stgdict->ndim); - if (stgdict->shape == NULL) { - Py_DECREF((PyObject *)stgdict); - return NULL; - } - stgdict->shape[0] = length; - memmove(&stgdict->shape[1], itemdict->shape, - sizeof(Py_ssize_t) * (stgdict->ndim - 1)); - - itemsize = itemdict->size; - if (length * itemsize < 0) { - PyErr_SetString(PyExc_OverflowError, - "array too large"); - return NULL; - } - - itemalign = itemdict->align; - - if (itemdict->flags & (TYPEFLAG_ISPOINTER | TYPEFLAG_HASPOINTER)) - stgdict->flags |= TYPEFLAG_HASPOINTER; - - stgdict->size = itemsize * length; - stgdict->align = itemalign; - stgdict->length = length; - Py_INCREF(proto); - stgdict->proto = proto; - - stgdict->paramfunc = &PyCArrayType_paramfunc; - - /* Arrays are passed as pointers to function calls. */ - stgdict->ffi_type_pointer = ffi_type_pointer; - - /* create the new instance (which is a class, - since we are a metatype!) */ - result = (PyTypeObject *)PyType_Type.tp_new(type, args, kwds); - if (result == NULL) - return NULL; - - /* replace the class dict by our updated spam dict */ - if (-1 == PyDict_Update((PyObject *)stgdict, result->tp_dict)) { - Py_DECREF(result); - Py_DECREF((PyObject *)stgdict); - return NULL; - } - Py_DECREF(result->tp_dict); - result->tp_dict = (PyObject *)stgdict; - - /* Special case for character arrays. - A permanent annoyance: char arrays are also strings! - */ - if (itemdict->getfunc == _ctypes_get_fielddesc("c")->getfunc) { - if (-1 == add_getset(result, CharArray_getsets)) - return NULL; + PyTypeObject *result; + StgDictObject *stgdict; + StgDictObject *itemdict; + PyObject *proto; + PyObject *typedict; + long length; + int overflow; + Py_ssize_t itemsize, itemalign; + char buf[32]; + + typedict = PyTuple_GetItem(args, 2); + if (!typedict) + return NULL; + + proto = PyDict_GetItemString(typedict, "_length_"); /* Borrowed ref */ + if (!proto || !PyLong_Check(proto)) { + PyErr_SetString(PyExc_AttributeError, + "class must define a '_length_' attribute, " + "which must be a positive integer"); + return NULL; + } + length = PyLong_AsLongAndOverflow(proto, &overflow); + if (overflow) { + PyErr_SetString(PyExc_OverflowError, + "The '_length_' attribute is too large"); + return NULL; + } + + proto = PyDict_GetItemString(typedict, "_type_"); /* Borrowed ref */ + if (!proto) { + PyErr_SetString(PyExc_AttributeError, + "class must define a '_type_' attribute"); + return NULL; + } + + stgdict = (StgDictObject *)PyObject_CallObject( + (PyObject *)&PyCStgDict_Type, NULL); + if (!stgdict) + return NULL; + + itemdict = PyType_stgdict(proto); + if (!itemdict) { + PyErr_SetString(PyExc_TypeError, + "_type_ must have storage info"); + Py_DECREF((PyObject *)stgdict); + return NULL; + } + + assert(itemdict->format); + if (itemdict->format[0] == '(') { + sprintf(buf, "(%ld,", length); + stgdict->format = _ctypes_alloc_format_string(buf, itemdict->format+1); + } else { + sprintf(buf, "(%ld)", length); + stgdict->format = _ctypes_alloc_format_string(buf, itemdict->format); + } + if (stgdict->format == NULL) { + Py_DECREF((PyObject *)stgdict); + return NULL; + } + stgdict->ndim = itemdict->ndim + 1; + stgdict->shape = PyMem_Malloc(sizeof(Py_ssize_t *) * stgdict->ndim); + if (stgdict->shape == NULL) { + Py_DECREF((PyObject *)stgdict); + return NULL; + } + stgdict->shape[0] = length; + memmove(&stgdict->shape[1], itemdict->shape, + sizeof(Py_ssize_t) * (stgdict->ndim - 1)); + + itemsize = itemdict->size; + if (length * itemsize < 0) { + PyErr_SetString(PyExc_OverflowError, + "array too large"); + return NULL; + } + + itemalign = itemdict->align; + + if (itemdict->flags & (TYPEFLAG_ISPOINTER | TYPEFLAG_HASPOINTER)) + stgdict->flags |= TYPEFLAG_HASPOINTER; + + stgdict->size = itemsize * length; + stgdict->align = itemalign; + stgdict->length = length; + Py_INCREF(proto); + stgdict->proto = proto; + + stgdict->paramfunc = &PyCArrayType_paramfunc; + + /* Arrays are passed as pointers to function calls. */ + stgdict->ffi_type_pointer = ffi_type_pointer; + + /* create the new instance (which is a class, + since we are a metatype!) */ + result = (PyTypeObject *)PyType_Type.tp_new(type, args, kwds); + if (result == NULL) + return NULL; + + /* replace the class dict by our updated spam dict */ + if (-1 == PyDict_Update((PyObject *)stgdict, result->tp_dict)) { + Py_DECREF(result); + Py_DECREF((PyObject *)stgdict); + return NULL; + } + Py_DECREF(result->tp_dict); + result->tp_dict = (PyObject *)stgdict; + + /* Special case for character arrays. + A permanent annoyance: char arrays are also strings! + */ + if (itemdict->getfunc == _ctypes_get_fielddesc("c")->getfunc) { + if (-1 == add_getset(result, CharArray_getsets)) + return NULL; #ifdef CTYPES_UNICODE - } else if (itemdict->getfunc == _ctypes_get_fielddesc("u")->getfunc) { - if (-1 == add_getset(result, WCharArray_getsets)) - return NULL; + } else if (itemdict->getfunc == _ctypes_get_fielddesc("u")->getfunc) { + if (-1 == add_getset(result, WCharArray_getsets)) + return NULL; #endif - } + } - return (PyObject *)result; + return (PyObject *)result; } PyTypeObject PyCArrayType_Type = { - PyVarObject_HEAD_INIT(NULL, 0) - "_ctypes.PyCArrayType", /* tp_name */ - 0, /* tp_basicsize */ - 0, /* tp_itemsize */ - 0, /* tp_dealloc */ - 0, /* tp_print */ - 0, /* tp_getattr */ - 0, /* tp_setattr */ - 0, /* tp_reserved */ - 0, /* tp_repr */ - 0, /* tp_as_number */ - &CDataType_as_sequence, /* tp_as_sequence */ - 0, /* tp_as_mapping */ - 0, /* tp_hash */ - 0, /* tp_call */ - 0, /* tp_str */ - 0, /* tp_getattro */ - 0, /* tp_setattro */ - 0, /* tp_as_buffer */ - Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */ - "metatype for the Array Objects", /* tp_doc */ - 0, /* tp_traverse */ - 0, /* tp_clear */ - 0, /* tp_richcompare */ - 0, /* tp_weaklistoffset */ - 0, /* tp_iter */ - 0, /* tp_iternext */ - CDataType_methods, /* tp_methods */ - 0, /* tp_members */ - 0, /* tp_getset */ - 0, /* tp_base */ - 0, /* tp_dict */ - 0, /* tp_descr_get */ - 0, /* tp_descr_set */ - 0, /* tp_dictoffset */ - 0, /* tp_init */ - 0, /* tp_alloc */ - PyCArrayType_new, /* tp_new */ - 0, /* tp_free */ + PyVarObject_HEAD_INIT(NULL, 0) + "_ctypes.PyCArrayType", /* tp_name */ + 0, /* tp_basicsize */ + 0, /* tp_itemsize */ + 0, /* tp_dealloc */ + 0, /* tp_print */ + 0, /* tp_getattr */ + 0, /* tp_setattr */ + 0, /* tp_reserved */ + 0, /* tp_repr */ + 0, /* tp_as_number */ + &CDataType_as_sequence, /* tp_as_sequence */ + 0, /* tp_as_mapping */ + 0, /* tp_hash */ + 0, /* tp_call */ + 0, /* tp_str */ + 0, /* tp_getattro */ + 0, /* tp_setattro */ + 0, /* tp_as_buffer */ + Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */ + "metatype for the Array Objects", /* tp_doc */ + 0, /* tp_traverse */ + 0, /* tp_clear */ + 0, /* tp_richcompare */ + 0, /* tp_weaklistoffset */ + 0, /* tp_iter */ + 0, /* tp_iternext */ + CDataType_methods, /* tp_methods */ + 0, /* tp_members */ + 0, /* tp_getset */ + 0, /* tp_base */ + 0, /* tp_dict */ + 0, /* tp_descr_get */ + 0, /* tp_descr_set */ + 0, /* tp_dictoffset */ + 0, /* tp_init */ + 0, /* tp_alloc */ + PyCArrayType_new, /* tp_new */ + 0, /* tp_free */ }; - + /******************************************************************/ /* PyCSimpleType_Type @@ -1444,273 +1444,273 @@ static PyObject * c_wchar_p_from_param(PyObject *type, PyObject *value) { - PyObject *as_parameter; - if (value == Py_None) { - Py_INCREF(Py_None); - return Py_None; - } - if (PyUnicode_Check(value) || PyBytes_Check(value)) { - PyCArgObject *parg; - struct fielddesc *fd = _ctypes_get_fielddesc("Z"); - - parg = PyCArgObject_new(); - if (parg == NULL) - return NULL; - parg->pffi_type = &ffi_type_pointer; - parg->tag = 'Z'; - parg->obj = fd->setfunc(&parg->value, value, 0); - if (parg->obj == NULL) { - Py_DECREF(parg); - return NULL; - } - return (PyObject *)parg; - } - if (PyObject_IsInstance(value, type)) { - Py_INCREF(value); - return value; - } - if (ArrayObject_Check(value) || PointerObject_Check(value)) { - /* c_wchar array instance or pointer(c_wchar(...)) */ - StgDictObject *dt = PyObject_stgdict(value); - StgDictObject *dict; - assert(dt); /* Cannot be NULL for pointer or array objects */ - dict = dt && dt->proto ? PyType_stgdict(dt->proto) : NULL; - if (dict && (dict->setfunc == _ctypes_get_fielddesc("u")->setfunc)) { - Py_INCREF(value); - return value; - } - } - if (PyCArg_CheckExact(value)) { - /* byref(c_char(...)) */ - PyCArgObject *a = (PyCArgObject *)value; - StgDictObject *dict = PyObject_stgdict(a->obj); - if (dict && (dict->setfunc == _ctypes_get_fielddesc("u")->setfunc)) { - Py_INCREF(value); - return value; - } - } - - as_parameter = PyObject_GetAttrString(value, "_as_parameter_"); - if (as_parameter) { - value = c_wchar_p_from_param(type, as_parameter); - Py_DECREF(as_parameter); - return value; - } - /* XXX better message */ - PyErr_SetString(PyExc_TypeError, - "wrong type"); - return NULL; + PyObject *as_parameter; + if (value == Py_None) { + Py_INCREF(Py_None); + return Py_None; + } + if (PyUnicode_Check(value) || PyBytes_Check(value)) { + PyCArgObject *parg; + struct fielddesc *fd = _ctypes_get_fielddesc("Z"); + + parg = PyCArgObject_new(); + if (parg == NULL) + return NULL; + parg->pffi_type = &ffi_type_pointer; + parg->tag = 'Z'; + parg->obj = fd->setfunc(&parg->value, value, 0); + if (parg->obj == NULL) { + Py_DECREF(parg); + return NULL; + } + return (PyObject *)parg; + } + if (PyObject_IsInstance(value, type)) { + Py_INCREF(value); + return value; + } + if (ArrayObject_Check(value) || PointerObject_Check(value)) { + /* c_wchar array instance or pointer(c_wchar(...)) */ + StgDictObject *dt = PyObject_stgdict(value); + StgDictObject *dict; + assert(dt); /* Cannot be NULL for pointer or array objects */ + dict = dt && dt->proto ? PyType_stgdict(dt->proto) : NULL; + if (dict && (dict->setfunc == _ctypes_get_fielddesc("u")->setfunc)) { + Py_INCREF(value); + return value; + } + } + if (PyCArg_CheckExact(value)) { + /* byref(c_char(...)) */ + PyCArgObject *a = (PyCArgObject *)value; + StgDictObject *dict = PyObject_stgdict(a->obj); + if (dict && (dict->setfunc == _ctypes_get_fielddesc("u")->setfunc)) { + Py_INCREF(value); + return value; + } + } + + as_parameter = PyObject_GetAttrString(value, "_as_parameter_"); + if (as_parameter) { + value = c_wchar_p_from_param(type, as_parameter); + Py_DECREF(as_parameter); + return value; + } + /* XXX better message */ + PyErr_SetString(PyExc_TypeError, + "wrong type"); + return NULL; } static PyObject * c_char_p_from_param(PyObject *type, PyObject *value) { - PyObject *as_parameter; - if (value == Py_None) { - Py_INCREF(Py_None); - return Py_None; - } - if (PyBytes_Check(value) || PyUnicode_Check(value)) { - PyCArgObject *parg; - struct fielddesc *fd = _ctypes_get_fielddesc("z"); - - parg = PyCArgObject_new(); - if (parg == NULL) - return NULL; - parg->pffi_type = &ffi_type_pointer; - parg->tag = 'z'; - parg->obj = fd->setfunc(&parg->value, value, 0); - if (parg->obj == NULL) { - Py_DECREF(parg); - return NULL; - } - return (PyObject *)parg; - } - if (PyObject_IsInstance(value, type)) { - Py_INCREF(value); - return value; - } - if (ArrayObject_Check(value) || PointerObject_Check(value)) { - /* c_char array instance or pointer(c_char(...)) */ - StgDictObject *dt = PyObject_stgdict(value); - StgDictObject *dict; - assert(dt); /* Cannot be NULL for pointer or array objects */ - dict = dt && dt->proto ? PyType_stgdict(dt->proto) : NULL; - if (dict && (dict->setfunc == _ctypes_get_fielddesc("c")->setfunc)) { - Py_INCREF(value); - return value; - } - } - if (PyCArg_CheckExact(value)) { - /* byref(c_char(...)) */ - PyCArgObject *a = (PyCArgObject *)value; - StgDictObject *dict = PyObject_stgdict(a->obj); - if (dict && (dict->setfunc == _ctypes_get_fielddesc("c")->setfunc)) { - Py_INCREF(value); - return value; - } - } - - as_parameter = PyObject_GetAttrString(value, "_as_parameter_"); - if (as_parameter) { - value = c_char_p_from_param(type, as_parameter); - Py_DECREF(as_parameter); - return value; - } - /* XXX better message */ - PyErr_SetString(PyExc_TypeError, - "wrong type"); - return NULL; + PyObject *as_parameter; + if (value == Py_None) { + Py_INCREF(Py_None); + return Py_None; + } + if (PyBytes_Check(value) || PyUnicode_Check(value)) { + PyCArgObject *parg; + struct fielddesc *fd = _ctypes_get_fielddesc("z"); + + parg = PyCArgObject_new(); + if (parg == NULL) + return NULL; + parg->pffi_type = &ffi_type_pointer; + parg->tag = 'z'; + parg->obj = fd->setfunc(&parg->value, value, 0); + if (parg->obj == NULL) { + Py_DECREF(parg); + return NULL; + } + return (PyObject *)parg; + } + if (PyObject_IsInstance(value, type)) { + Py_INCREF(value); + return value; + } + if (ArrayObject_Check(value) || PointerObject_Check(value)) { + /* c_char array instance or pointer(c_char(...)) */ + StgDictObject *dt = PyObject_stgdict(value); + StgDictObject *dict; + assert(dt); /* Cannot be NULL for pointer or array objects */ + dict = dt && dt->proto ? PyType_stgdict(dt->proto) : NULL; + if (dict && (dict->setfunc == _ctypes_get_fielddesc("c")->setfunc)) { + Py_INCREF(value); + return value; + } + } + if (PyCArg_CheckExact(value)) { + /* byref(c_char(...)) */ + PyCArgObject *a = (PyCArgObject *)value; + StgDictObject *dict = PyObject_stgdict(a->obj); + if (dict && (dict->setfunc == _ctypes_get_fielddesc("c")->setfunc)) { + Py_INCREF(value); + return value; + } + } + + as_parameter = PyObject_GetAttrString(value, "_as_parameter_"); + if (as_parameter) { + value = c_char_p_from_param(type, as_parameter); + Py_DECREF(as_parameter); + return value; + } + /* XXX better message */ + PyErr_SetString(PyExc_TypeError, + "wrong type"); + return NULL; } static PyObject * c_void_p_from_param(PyObject *type, PyObject *value) { - StgDictObject *stgd; - PyObject *as_parameter; + StgDictObject *stgd; + PyObject *as_parameter; /* None */ - if (value == Py_None) { - Py_INCREF(Py_None); - return Py_None; - } - /* Should probably allow buffer interface as well */ + if (value == Py_None) { + Py_INCREF(Py_None); + return Py_None; + } + /* Should probably allow buffer interface as well */ /* int, long */ - if (PyLong_Check(value)) { - PyCArgObject *parg; - struct fielddesc *fd = _ctypes_get_fielddesc("P"); - - parg = PyCArgObject_new(); - if (parg == NULL) - return NULL; - parg->pffi_type = &ffi_type_pointer; - parg->tag = 'P'; - parg->obj = fd->setfunc(&parg->value, value, 0); - if (parg->obj == NULL) { - Py_DECREF(parg); - return NULL; - } - return (PyObject *)parg; - } - /* XXX struni: remove later */ + if (PyLong_Check(value)) { + PyCArgObject *parg; + struct fielddesc *fd = _ctypes_get_fielddesc("P"); + + parg = PyCArgObject_new(); + if (parg == NULL) + return NULL; + parg->pffi_type = &ffi_type_pointer; + parg->tag = 'P'; + parg->obj = fd->setfunc(&parg->value, value, 0); + if (parg->obj == NULL) { + Py_DECREF(parg); + return NULL; + } + return (PyObject *)parg; + } + /* XXX struni: remove later */ /* string */ - if (PyBytes_Check(value)) { - PyCArgObject *parg; - struct fielddesc *fd = _ctypes_get_fielddesc("z"); - - parg = PyCArgObject_new(); - if (parg == NULL) - return NULL; - parg->pffi_type = &ffi_type_pointer; - parg->tag = 'z'; - parg->obj = fd->setfunc(&parg->value, value, 0); - if (parg->obj == NULL) { - Py_DECREF(parg); - return NULL; - } - return (PyObject *)parg; - } + if (PyBytes_Check(value)) { + PyCArgObject *parg; + struct fielddesc *fd = _ctypes_get_fielddesc("z"); + + parg = PyCArgObject_new(); + if (parg == NULL) + return NULL; + parg->pffi_type = &ffi_type_pointer; + parg->tag = 'z'; + parg->obj = fd->setfunc(&parg->value, value, 0); + if (parg->obj == NULL) { + Py_DECREF(parg); + return NULL; + } + return (PyObject *)parg; + } /* bytes */ - if (PyByteArray_Check(value)) { - PyCArgObject *parg; - struct fielddesc *fd = _ctypes_get_fielddesc("z"); - - parg = PyCArgObject_new(); - if (parg == NULL) - return NULL; - parg->pffi_type = &ffi_type_pointer; - parg->tag = 'z'; - parg->obj = fd->setfunc(&parg->value, value, 0); - if (parg->obj == NULL) { - Py_DECREF(parg); - return NULL; - } - return (PyObject *)parg; - } + if (PyByteArray_Check(value)) { + PyCArgObject *parg; + struct fielddesc *fd = _ctypes_get_fielddesc("z"); + + parg = PyCArgObject_new(); + if (parg == NULL) + return NULL; + parg->pffi_type = &ffi_type_pointer; + parg->tag = 'z'; + parg->obj = fd->setfunc(&parg->value, value, 0); + if (parg->obj == NULL) { + Py_DECREF(parg); + return NULL; + } + return (PyObject *)parg; + } /* unicode */ - if (PyUnicode_Check(value)) { - PyCArgObject *parg; - struct fielddesc *fd = _ctypes_get_fielddesc("Z"); - - parg = PyCArgObject_new(); - if (parg == NULL) - return NULL; - parg->pffi_type = &ffi_type_pointer; - parg->tag = 'Z'; - parg->obj = fd->setfunc(&parg->value, value, 0); - if (parg->obj == NULL) { - Py_DECREF(parg); - return NULL; - } - return (PyObject *)parg; - } + if (PyUnicode_Check(value)) { + PyCArgObject *parg; + struct fielddesc *fd = _ctypes_get_fielddesc("Z"); + + parg = PyCArgObject_new(); + if (parg == NULL) + return NULL; + parg->pffi_type = &ffi_type_pointer; + parg->tag = 'Z'; + parg->obj = fd->setfunc(&parg->value, value, 0); + if (parg->obj == NULL) { + Py_DECREF(parg); + return NULL; + } + return (PyObject *)parg; + } /* c_void_p instance (or subclass) */ - if (PyObject_IsInstance(value, type)) { - /* c_void_p instances */ - Py_INCREF(value); - return value; - } + if (PyObject_IsInstance(value, type)) { + /* c_void_p instances */ + Py_INCREF(value); + return value; + } /* ctypes array or pointer instance */ - if (ArrayObject_Check(value) || PointerObject_Check(value)) { - /* Any array or pointer is accepted */ - Py_INCREF(value); - return value; - } + if (ArrayObject_Check(value) || PointerObject_Check(value)) { + /* Any array or pointer is accepted */ + Py_INCREF(value); + return value; + } /* byref(...) */ - if (PyCArg_CheckExact(value)) { - /* byref(c_xxx()) */ - PyCArgObject *a = (PyCArgObject *)value; - if (a->tag == 'P') { - Py_INCREF(value); - return value; - } - } + if (PyCArg_CheckExact(value)) { + /* byref(c_xxx()) */ + PyCArgObject *a = (PyCArgObject *)value; + if (a->tag == 'P') { + Py_INCREF(value); + return value; + } + } /* function pointer */ - if (PyCFuncPtrObject_Check(value)) { - PyCArgObject *parg; - PyCFuncPtrObject *func; - func = (PyCFuncPtrObject *)value; - parg = PyCArgObject_new(); - if (parg == NULL) - return NULL; - parg->pffi_type = &ffi_type_pointer; - parg->tag = 'P'; - Py_INCREF(value); - parg->value.p = *(void **)func->b_ptr; - parg->obj = value; - return (PyObject *)parg; - } + if (PyCFuncPtrObject_Check(value)) { + PyCArgObject *parg; + PyCFuncPtrObject *func; + func = (PyCFuncPtrObject *)value; + parg = PyCArgObject_new(); + if (parg == NULL) + return NULL; + parg->pffi_type = &ffi_type_pointer; + parg->tag = 'P'; + Py_INCREF(value); + parg->value.p = *(void **)func->b_ptr; + parg->obj = value; + return (PyObject *)parg; + } /* c_char_p, c_wchar_p */ - stgd = PyObject_stgdict(value); - if (stgd && CDataObject_Check(value) && stgd->proto && PyUnicode_Check(stgd->proto)) { - PyCArgObject *parg; - - switch (_PyUnicode_AsString(stgd->proto)[0]) { - case 'z': /* c_char_p */ - case 'Z': /* c_wchar_p */ - parg = PyCArgObject_new(); - if (parg == NULL) - return NULL; - parg->pffi_type = &ffi_type_pointer; - parg->tag = 'Z'; - Py_INCREF(value); - parg->obj = value; - /* Remember: b_ptr points to where the pointer is stored! */ - parg->value.p = *(void **)(((CDataObject *)value)->b_ptr); - return (PyObject *)parg; - } - } - - as_parameter = PyObject_GetAttrString(value, "_as_parameter_"); - if (as_parameter) { - value = c_void_p_from_param(type, as_parameter); - Py_DECREF(as_parameter); - return value; - } - /* XXX better message */ - PyErr_SetString(PyExc_TypeError, - "wrong type"); - return NULL; + stgd = PyObject_stgdict(value); + if (stgd && CDataObject_Check(value) && stgd->proto && PyUnicode_Check(stgd->proto)) { + PyCArgObject *parg; + + switch (_PyUnicode_AsString(stgd->proto)[0]) { + case 'z': /* c_char_p */ + case 'Z': /* c_wchar_p */ + parg = PyCArgObject_new(); + if (parg == NULL) + return NULL; + parg->pffi_type = &ffi_type_pointer; + parg->tag = 'Z'; + Py_INCREF(value); + parg->obj = value; + /* Remember: b_ptr points to where the pointer is stored! */ + parg->value.p = *(void **)(((CDataObject *)value)->b_ptr); + return (PyObject *)parg; + } + } + + as_parameter = PyObject_GetAttrString(value, "_as_parameter_"); + if (as_parameter) { + value = c_void_p_from_param(type, as_parameter); + Py_DECREF(as_parameter); + return value; + } + /* XXX better message */ + PyErr_SetString(PyExc_TypeError, + "wrong type"); + return NULL; } static PyMethodDef c_void_p_method = { "from_param", c_void_p_from_param, METH_O }; @@ -1718,278 +1718,278 @@ static PyMethodDef c_wchar_p_method = { "from_param", c_wchar_p_from_param, METH_O }; static PyObject *CreateSwappedType(PyTypeObject *type, PyObject *args, PyObject *kwds, - PyObject *proto, struct fielddesc *fmt) + PyObject *proto, struct fielddesc *fmt) { - PyTypeObject *result; - StgDictObject *stgdict; - PyObject *name = PyTuple_GET_ITEM(args, 0); - PyObject *newname; - PyObject *swapped_args; - static PyObject *suffix; - Py_ssize_t i; - - swapped_args = PyTuple_New(PyTuple_GET_SIZE(args)); - if (!swapped_args) - return NULL; + PyTypeObject *result; + StgDictObject *stgdict; + PyObject *name = PyTuple_GET_ITEM(args, 0); + PyObject *newname; + PyObject *swapped_args; + static PyObject *suffix; + Py_ssize_t i; + + swapped_args = PyTuple_New(PyTuple_GET_SIZE(args)); + if (!swapped_args) + return NULL; - if (suffix == NULL) + if (suffix == NULL) #ifdef WORDS_BIGENDIAN - suffix = PyUnicode_InternFromString("_le"); + suffix = PyUnicode_InternFromString("_le"); #else - suffix = PyUnicode_InternFromString("_be"); + suffix = PyUnicode_InternFromString("_be"); #endif - newname = PyUnicode_Concat(name, suffix); - if (newname == NULL) { - return NULL; - } - - PyTuple_SET_ITEM(swapped_args, 0, newname); - for (i=1; iffi_type_pointer = *fmt->pffi_type; - stgdict->align = fmt->pffi_type->alignment; - stgdict->length = 0; - stgdict->size = fmt->pffi_type->size; - stgdict->setfunc = fmt->setfunc_swapped; - stgdict->getfunc = fmt->getfunc_swapped; - - Py_INCREF(proto); - stgdict->proto = proto; - - /* replace the class dict by our updated spam dict */ - if (-1 == PyDict_Update((PyObject *)stgdict, result->tp_dict)) { - Py_DECREF(result); - Py_DECREF((PyObject *)stgdict); - return NULL; - } - Py_DECREF(result->tp_dict); - result->tp_dict = (PyObject *)stgdict; + newname = PyUnicode_Concat(name, suffix); + if (newname == NULL) { + return NULL; + } + + PyTuple_SET_ITEM(swapped_args, 0, newname); + for (i=1; iffi_type_pointer = *fmt->pffi_type; + stgdict->align = fmt->pffi_type->alignment; + stgdict->length = 0; + stgdict->size = fmt->pffi_type->size; + stgdict->setfunc = fmt->setfunc_swapped; + stgdict->getfunc = fmt->getfunc_swapped; + + Py_INCREF(proto); + stgdict->proto = proto; + + /* replace the class dict by our updated spam dict */ + if (-1 == PyDict_Update((PyObject *)stgdict, result->tp_dict)) { + Py_DECREF(result); + Py_DECREF((PyObject *)stgdict); + return NULL; + } + Py_DECREF(result->tp_dict); + result->tp_dict = (PyObject *)stgdict; - return (PyObject *)result; + return (PyObject *)result; } static PyCArgObject * PyCSimpleType_paramfunc(CDataObject *self) { - StgDictObject *dict; - char *fmt; - PyCArgObject *parg; - struct fielddesc *fd; - - dict = PyObject_stgdict((PyObject *)self); - assert(dict); /* Cannot be NULL for CDataObject instances */ - fmt = _PyUnicode_AsString(dict->proto); - assert(fmt); - - fd = _ctypes_get_fielddesc(fmt); - assert(fd); - - parg = PyCArgObject_new(); - if (parg == NULL) - return NULL; - - parg->tag = fmt[0]; - parg->pffi_type = fd->pffi_type; - Py_INCREF(self); - parg->obj = (PyObject *)self; - memcpy(&parg->value, self->b_ptr, self->b_size); - return parg; + StgDictObject *dict; + char *fmt; + PyCArgObject *parg; + struct fielddesc *fd; + + dict = PyObject_stgdict((PyObject *)self); + assert(dict); /* Cannot be NULL for CDataObject instances */ + fmt = _PyUnicode_AsString(dict->proto); + assert(fmt); + + fd = _ctypes_get_fielddesc(fmt); + assert(fd); + + parg = PyCArgObject_new(); + if (parg == NULL) + return NULL; + + parg->tag = fmt[0]; + parg->pffi_type = fd->pffi_type; + Py_INCREF(self); + parg->obj = (PyObject *)self; + memcpy(&parg->value, self->b_ptr, self->b_size); + return parg; } static PyObject * PyCSimpleType_new(PyTypeObject *type, PyObject *args, PyObject *kwds) { - PyTypeObject *result; - StgDictObject *stgdict; - PyObject *proto; - const char *proto_str; - Py_ssize_t proto_len; - PyMethodDef *ml; - struct fielddesc *fmt; - - /* create the new instance (which is a class, - since we are a metatype!) */ - result = (PyTypeObject *)PyType_Type.tp_new(type, args, kwds); - if (result == NULL) - return NULL; - - proto = PyObject_GetAttrString((PyObject *)result, "_type_"); /* new ref */ - if (!proto) { - PyErr_SetString(PyExc_AttributeError, - "class must define a '_type_' attribute"); + PyTypeObject *result; + StgDictObject *stgdict; + PyObject *proto; + const char *proto_str; + Py_ssize_t proto_len; + PyMethodDef *ml; + struct fielddesc *fmt; + + /* create the new instance (which is a class, + since we are a metatype!) */ + result = (PyTypeObject *)PyType_Type.tp_new(type, args, kwds); + if (result == NULL) + return NULL; + + proto = PyObject_GetAttrString((PyObject *)result, "_type_"); /* new ref */ + if (!proto) { + PyErr_SetString(PyExc_AttributeError, + "class must define a '_type_' attribute"); error: - Py_XDECREF(proto); - Py_XDECREF(result); - return NULL; - } - if (PyUnicode_Check(proto)) { - PyObject *v = _PyUnicode_AsDefaultEncodedString(proto, NULL); - if (!v) - goto error; - proto_str = PyBytes_AS_STRING(v); - proto_len = PyBytes_GET_SIZE(v); - } else { - PyErr_SetString(PyExc_TypeError, - "class must define a '_type_' string attribute"); - goto error; - } - if (proto_len != 1) { - PyErr_SetString(PyExc_ValueError, - "class must define a '_type_' attribute " - "which must be a string of length 1"); - goto error; - } - if (!strchr(SIMPLE_TYPE_CHARS, *proto_str)) { - PyErr_Format(PyExc_AttributeError, - "class must define a '_type_' attribute which must be\n" - "a single character string containing one of '%s'.", - SIMPLE_TYPE_CHARS); - goto error; - } - fmt = _ctypes_get_fielddesc(proto_str); - if (fmt == NULL) { - PyErr_Format(PyExc_ValueError, - "_type_ '%s' not supported", proto_str); - goto error; - } - - stgdict = (StgDictObject *)PyObject_CallObject( - (PyObject *)&PyCStgDict_Type, NULL); - if (!stgdict) - goto error; - - stgdict->ffi_type_pointer = *fmt->pffi_type; - stgdict->align = fmt->pffi_type->alignment; - stgdict->length = 0; - stgdict->size = fmt->pffi_type->size; - stgdict->setfunc = fmt->setfunc; - stgdict->getfunc = fmt->getfunc; + Py_XDECREF(proto); + Py_XDECREF(result); + return NULL; + } + if (PyUnicode_Check(proto)) { + PyObject *v = _PyUnicode_AsDefaultEncodedString(proto, NULL); + if (!v) + goto error; + proto_str = PyBytes_AS_STRING(v); + proto_len = PyBytes_GET_SIZE(v); + } else { + PyErr_SetString(PyExc_TypeError, + "class must define a '_type_' string attribute"); + goto error; + } + if (proto_len != 1) { + PyErr_SetString(PyExc_ValueError, + "class must define a '_type_' attribute " + "which must be a string of length 1"); + goto error; + } + if (!strchr(SIMPLE_TYPE_CHARS, *proto_str)) { + PyErr_Format(PyExc_AttributeError, + "class must define a '_type_' attribute which must be\n" + "a single character string containing one of '%s'.", + SIMPLE_TYPE_CHARS); + goto error; + } + fmt = _ctypes_get_fielddesc(proto_str); + if (fmt == NULL) { + PyErr_Format(PyExc_ValueError, + "_type_ '%s' not supported", proto_str); + goto error; + } + + stgdict = (StgDictObject *)PyObject_CallObject( + (PyObject *)&PyCStgDict_Type, NULL); + if (!stgdict) + goto error; + + stgdict->ffi_type_pointer = *fmt->pffi_type; + stgdict->align = fmt->pffi_type->alignment; + stgdict->length = 0; + stgdict->size = fmt->pffi_type->size; + stgdict->setfunc = fmt->setfunc; + stgdict->getfunc = fmt->getfunc; #ifdef WORDS_BIGENDIAN - stgdict->format = _ctypes_alloc_format_string(">", proto_str); + stgdict->format = _ctypes_alloc_format_string(">", proto_str); #else - stgdict->format = _ctypes_alloc_format_string("<", proto_str); + stgdict->format = _ctypes_alloc_format_string("<", proto_str); #endif - if (stgdict->format == NULL) { - Py_DECREF(result); - Py_DECREF(proto); - Py_DECREF((PyObject *)stgdict); - return NULL; - } + if (stgdict->format == NULL) { + Py_DECREF(result); + Py_DECREF(proto); + Py_DECREF((PyObject *)stgdict); + return NULL; + } - stgdict->paramfunc = PyCSimpleType_paramfunc; + stgdict->paramfunc = PyCSimpleType_paramfunc; /* - if (result->tp_base != &Simple_Type) { - stgdict->setfunc = NULL; - stgdict->getfunc = NULL; - } + if (result->tp_base != &Simple_Type) { + stgdict->setfunc = NULL; + stgdict->getfunc = NULL; + } */ - /* This consumes the refcount on proto which we have */ - stgdict->proto = proto; + /* This consumes the refcount on proto which we have */ + stgdict->proto = proto; - /* replace the class dict by our updated spam dict */ - if (-1 == PyDict_Update((PyObject *)stgdict, result->tp_dict)) { - Py_DECREF(result); - Py_DECREF((PyObject *)stgdict); - return NULL; - } - Py_DECREF(result->tp_dict); - result->tp_dict = (PyObject *)stgdict; - - /* Install from_param class methods in ctypes base classes. - Overrides the PyCSimpleType_from_param generic method. - */ - if (result->tp_base == &Simple_Type) { - switch (*proto_str) { - case 'z': /* c_char_p */ - ml = &c_char_p_method; - stgdict->flags |= TYPEFLAG_ISPOINTER; - break; - case 'Z': /* c_wchar_p */ - ml = &c_wchar_p_method; - stgdict->flags |= TYPEFLAG_ISPOINTER; - break; - case 'P': /* c_void_p */ - ml = &c_void_p_method; - stgdict->flags |= TYPEFLAG_ISPOINTER; - break; - case 's': - case 'X': - case 'O': - ml = NULL; - stgdict->flags |= TYPEFLAG_ISPOINTER; - break; - default: - ml = NULL; - break; - } - - if (ml) { - PyObject *meth; - int x; - meth = PyDescr_NewClassMethod(result, ml); - if (!meth) - return NULL; - x = PyDict_SetItemString(result->tp_dict, - ml->ml_name, - meth); - Py_DECREF(meth); - if (x == -1) { - Py_DECREF(result); - return NULL; - } - } - } - - if (type == &PyCSimpleType_Type && fmt->setfunc_swapped && fmt->getfunc_swapped) { - PyObject *swapped = CreateSwappedType(type, args, kwds, - proto, fmt); - StgDictObject *sw_dict; - if (swapped == NULL) { - Py_DECREF(result); - return NULL; - } - sw_dict = PyType_stgdict(swapped); + /* replace the class dict by our updated spam dict */ + if (-1 == PyDict_Update((PyObject *)stgdict, result->tp_dict)) { + Py_DECREF(result); + Py_DECREF((PyObject *)stgdict); + return NULL; + } + Py_DECREF(result->tp_dict); + result->tp_dict = (PyObject *)stgdict; + + /* Install from_param class methods in ctypes base classes. + Overrides the PyCSimpleType_from_param generic method. + */ + if (result->tp_base == &Simple_Type) { + switch (*proto_str) { + case 'z': /* c_char_p */ + ml = &c_char_p_method; + stgdict->flags |= TYPEFLAG_ISPOINTER; + break; + case 'Z': /* c_wchar_p */ + ml = &c_wchar_p_method; + stgdict->flags |= TYPEFLAG_ISPOINTER; + break; + case 'P': /* c_void_p */ + ml = &c_void_p_method; + stgdict->flags |= TYPEFLAG_ISPOINTER; + break; + case 's': + case 'X': + case 'O': + ml = NULL; + stgdict->flags |= TYPEFLAG_ISPOINTER; + break; + default: + ml = NULL; + break; + } + + if (ml) { + PyObject *meth; + int x; + meth = PyDescr_NewClassMethod(result, ml); + if (!meth) + return NULL; + x = PyDict_SetItemString(result->tp_dict, + ml->ml_name, + meth); + Py_DECREF(meth); + if (x == -1) { + Py_DECREF(result); + return NULL; + } + } + } + + if (type == &PyCSimpleType_Type && fmt->setfunc_swapped && fmt->getfunc_swapped) { + PyObject *swapped = CreateSwappedType(type, args, kwds, + proto, fmt); + StgDictObject *sw_dict; + if (swapped == NULL) { + Py_DECREF(result); + return NULL; + } + sw_dict = PyType_stgdict(swapped); #ifdef WORDS_BIGENDIAN - PyObject_SetAttrString((PyObject *)result, "__ctype_le__", swapped); - PyObject_SetAttrString((PyObject *)result, "__ctype_be__", (PyObject *)result); - PyObject_SetAttrString(swapped, "__ctype_be__", (PyObject *)result); - PyObject_SetAttrString(swapped, "__ctype_le__", swapped); - /* We are creating the type for the OTHER endian */ - sw_dict->format = _ctypes_alloc_format_string("<", stgdict->format+1); + PyObject_SetAttrString((PyObject *)result, "__ctype_le__", swapped); + PyObject_SetAttrString((PyObject *)result, "__ctype_be__", (PyObject *)result); + PyObject_SetAttrString(swapped, "__ctype_be__", (PyObject *)result); + PyObject_SetAttrString(swapped, "__ctype_le__", swapped); + /* We are creating the type for the OTHER endian */ + sw_dict->format = _ctypes_alloc_format_string("<", stgdict->format+1); #else - PyObject_SetAttrString((PyObject *)result, "__ctype_be__", swapped); - PyObject_SetAttrString((PyObject *)result, "__ctype_le__", (PyObject *)result); - PyObject_SetAttrString(swapped, "__ctype_le__", (PyObject *)result); - PyObject_SetAttrString(swapped, "__ctype_be__", swapped); - /* We are creating the type for the OTHER endian */ - sw_dict->format = _ctypes_alloc_format_string(">", stgdict->format+1); + PyObject_SetAttrString((PyObject *)result, "__ctype_be__", swapped); + PyObject_SetAttrString((PyObject *)result, "__ctype_le__", (PyObject *)result); + PyObject_SetAttrString(swapped, "__ctype_le__", (PyObject *)result); + PyObject_SetAttrString(swapped, "__ctype_be__", swapped); + /* We are creating the type for the OTHER endian */ + sw_dict->format = _ctypes_alloc_format_string(">", stgdict->format+1); #endif - Py_DECREF(swapped); - if (PyErr_Occurred()) { - Py_DECREF(result); - return NULL; - } - }; + Py_DECREF(swapped); + if (PyErr_Occurred()) { + Py_DECREF(result); + return NULL; + } + }; - return (PyObject *)result; + return (PyObject *)result; } /* @@ -1999,101 +1999,101 @@ static PyObject * PyCSimpleType_from_param(PyObject *type, PyObject *value) { - StgDictObject *dict; - char *fmt; - PyCArgObject *parg; - struct fielddesc *fd; - PyObject *as_parameter; - - /* If the value is already an instance of the requested type, - we can use it as is */ - if (1 == PyObject_IsInstance(value, type)) { - Py_INCREF(value); - return value; - } - - dict = PyType_stgdict(type); - assert(dict); - - /* I think we can rely on this being a one-character string */ - fmt = _PyUnicode_AsString(dict->proto); - assert(fmt); - - fd = _ctypes_get_fielddesc(fmt); - assert(fd); - - parg = PyCArgObject_new(); - if (parg == NULL) - return NULL; - - parg->tag = fmt[0]; - parg->pffi_type = fd->pffi_type; - parg->obj = fd->setfunc(&parg->value, value, 0); - if (parg->obj) - return (PyObject *)parg; - PyErr_Clear(); - Py_DECREF(parg); - - as_parameter = PyObject_GetAttrString(value, "_as_parameter_"); - if (as_parameter) { - value = PyCSimpleType_from_param(type, as_parameter); - Py_DECREF(as_parameter); - return value; - } - PyErr_SetString(PyExc_TypeError, - "wrong type"); - return NULL; + StgDictObject *dict; + char *fmt; + PyCArgObject *parg; + struct fielddesc *fd; + PyObject *as_parameter; + + /* If the value is already an instance of the requested type, + we can use it as is */ + if (1 == PyObject_IsInstance(value, type)) { + Py_INCREF(value); + return value; + } + + dict = PyType_stgdict(type); + assert(dict); + + /* I think we can rely on this being a one-character string */ + fmt = _PyUnicode_AsString(dict->proto); + assert(fmt); + + fd = _ctypes_get_fielddesc(fmt); + assert(fd); + + parg = PyCArgObject_new(); + if (parg == NULL) + return NULL; + + parg->tag = fmt[0]; + parg->pffi_type = fd->pffi_type; + parg->obj = fd->setfunc(&parg->value, value, 0); + if (parg->obj) + return (PyObject *)parg; + PyErr_Clear(); + Py_DECREF(parg); + + as_parameter = PyObject_GetAttrString(value, "_as_parameter_"); + if (as_parameter) { + value = PyCSimpleType_from_param(type, as_parameter); + Py_DECREF(as_parameter); + return value; + } + PyErr_SetString(PyExc_TypeError, + "wrong type"); + return NULL; } static PyMethodDef PyCSimpleType_methods[] = { - { "from_param", PyCSimpleType_from_param, METH_O, from_param_doc }, - { "from_address", CDataType_from_address, METH_O, from_address_doc }, - { "from_buffer", CDataType_from_buffer, METH_VARARGS, from_buffer_doc, }, - { "from_buffer_copy", CDataType_from_buffer_copy, METH_VARARGS, from_buffer_copy_doc, }, - { "in_dll", CDataType_in_dll, METH_VARARGS, in_dll_doc}, - { NULL, NULL }, + { "from_param", PyCSimpleType_from_param, METH_O, from_param_doc }, + { "from_address", CDataType_from_address, METH_O, from_address_doc }, + { "from_buffer", CDataType_from_buffer, METH_VARARGS, from_buffer_doc, }, + { "from_buffer_copy", CDataType_from_buffer_copy, METH_VARARGS, from_buffer_copy_doc, }, + { "in_dll", CDataType_in_dll, METH_VARARGS, in_dll_doc}, + { NULL, NULL }, }; PyTypeObject PyCSimpleType_Type = { - PyVarObject_HEAD_INIT(NULL, 0) - "_ctypes.PyCSimpleType", /* tp_name */ - 0, /* tp_basicsize */ - 0, /* tp_itemsize */ - 0, /* tp_dealloc */ - 0, /* tp_print */ - 0, /* tp_getattr */ - 0, /* tp_setattr */ - 0, /* tp_reserved */ - 0, /* tp_repr */ - 0, /* tp_as_number */ - &CDataType_as_sequence, /* tp_as_sequence */ - 0, /* tp_as_mapping */ - 0, /* tp_hash */ - 0, /* tp_call */ - 0, /* tp_str */ - 0, /* tp_getattro */ - 0, /* tp_setattro */ - 0, /* tp_as_buffer */ - Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */ - "metatype for the PyCSimpleType Objects", /* tp_doc */ - 0, /* tp_traverse */ - 0, /* tp_clear */ - 0, /* tp_richcompare */ - 0, /* tp_weaklistoffset */ - 0, /* tp_iter */ - 0, /* tp_iternext */ - PyCSimpleType_methods, /* tp_methods */ - 0, /* tp_members */ - 0, /* tp_getset */ - 0, /* tp_base */ - 0, /* tp_dict */ - 0, /* tp_descr_get */ - 0, /* tp_descr_set */ - 0, /* tp_dictoffset */ - 0, /* tp_init */ - 0, /* tp_alloc */ - PyCSimpleType_new, /* tp_new */ - 0, /* tp_free */ + PyVarObject_HEAD_INIT(NULL, 0) + "_ctypes.PyCSimpleType", /* tp_name */ + 0, /* tp_basicsize */ + 0, /* tp_itemsize */ + 0, /* tp_dealloc */ + 0, /* tp_print */ + 0, /* tp_getattr */ + 0, /* tp_setattr */ + 0, /* tp_reserved */ + 0, /* tp_repr */ + 0, /* tp_as_number */ + &CDataType_as_sequence, /* tp_as_sequence */ + 0, /* tp_as_mapping */ + 0, /* tp_hash */ + 0, /* tp_call */ + 0, /* tp_str */ + 0, /* tp_getattro */ + 0, /* tp_setattro */ + 0, /* tp_as_buffer */ + Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */ + "metatype for the PyCSimpleType Objects", /* tp_doc */ + 0, /* tp_traverse */ + 0, /* tp_clear */ + 0, /* tp_richcompare */ + 0, /* tp_weaklistoffset */ + 0, /* tp_iter */ + 0, /* tp_iternext */ + PyCSimpleType_methods, /* tp_methods */ + 0, /* tp_members */ + 0, /* tp_getset */ + 0, /* tp_base */ + 0, /* tp_dict */ + 0, /* tp_descr_get */ + 0, /* tp_descr_set */ + 0, /* tp_dictoffset */ + 0, /* tp_init */ + 0, /* tp_alloc */ + PyCSimpleType_new, /* tp_new */ + 0, /* tp_free */ }; /******************************************************************/ @@ -2104,217 +2104,217 @@ static PyObject * converters_from_argtypes(PyObject *ob) { - PyObject *converters; - Py_ssize_t i; - Py_ssize_t nArgs; - - ob = PySequence_Tuple(ob); /* new reference */ - if (!ob) { - PyErr_SetString(PyExc_TypeError, - "_argtypes_ must be a sequence of types"); - return NULL; - } - - nArgs = PyTuple_GET_SIZE(ob); - converters = PyTuple_New(nArgs); - if (!converters) - return NULL; - - /* I have to check if this is correct. Using c_char, which has a size - of 1, will be assumed to be pushed as only one byte! - Aren't these promoted to integers by the C compiler and pushed as 4 bytes? - */ - - for (i = 0; i < nArgs; ++i) { - PyObject *tp = PyTuple_GET_ITEM(ob, i); - PyObject *cnv = PyObject_GetAttrString(tp, "from_param"); - if (!cnv) - goto argtypes_error_1; - PyTuple_SET_ITEM(converters, i, cnv); - } - Py_DECREF(ob); - return converters; + PyObject *converters; + Py_ssize_t i; + Py_ssize_t nArgs; + + ob = PySequence_Tuple(ob); /* new reference */ + if (!ob) { + PyErr_SetString(PyExc_TypeError, + "_argtypes_ must be a sequence of types"); + return NULL; + } + + nArgs = PyTuple_GET_SIZE(ob); + converters = PyTuple_New(nArgs); + if (!converters) + return NULL; + + /* I have to check if this is correct. Using c_char, which has a size + of 1, will be assumed to be pushed as only one byte! + Aren't these promoted to integers by the C compiler and pushed as 4 bytes? + */ + + for (i = 0; i < nArgs; ++i) { + PyObject *tp = PyTuple_GET_ITEM(ob, i); + PyObject *cnv = PyObject_GetAttrString(tp, "from_param"); + if (!cnv) + goto argtypes_error_1; + PyTuple_SET_ITEM(converters, i, cnv); + } + Py_DECREF(ob); + return converters; argtypes_error_1: - Py_XDECREF(converters); - Py_DECREF(ob); - PyErr_Format(PyExc_TypeError, - "item %zd in _argtypes_ has no from_param method", - i+1); - return NULL; + Py_XDECREF(converters); + Py_DECREF(ob); + PyErr_Format(PyExc_TypeError, + "item %zd in _argtypes_ has no from_param method", + i+1); + return NULL; } static int make_funcptrtype_dict(StgDictObject *stgdict) { - PyObject *ob; - PyObject *converters = NULL; + PyObject *ob; + PyObject *converters = NULL; - stgdict->align = _ctypes_get_fielddesc("P")->pffi_type->alignment; - stgdict->length = 1; - stgdict->size = sizeof(void *); - stgdict->setfunc = NULL; - stgdict->getfunc = NULL; - stgdict->ffi_type_pointer = ffi_type_pointer; - - ob = PyDict_GetItemString((PyObject *)stgdict, "_flags_"); - if (!ob || !PyLong_Check(ob)) { - PyErr_SetString(PyExc_TypeError, - "class must define _flags_ which must be an integer"); - return -1; - } - stgdict->flags = PyLong_AS_LONG(ob) | TYPEFLAG_ISPOINTER; - - /* _argtypes_ is optional... */ - ob = PyDict_GetItemString((PyObject *)stgdict, "_argtypes_"); - if (ob) { - converters = converters_from_argtypes(ob); - if (!converters) - goto error; - Py_INCREF(ob); - stgdict->argtypes = ob; - stgdict->converters = converters; - } - - ob = PyDict_GetItemString((PyObject *)stgdict, "_restype_"); - if (ob) { - if (ob != Py_None && !PyType_stgdict(ob) && !PyCallable_Check(ob)) { - PyErr_SetString(PyExc_TypeError, - "_restype_ must be a type, a callable, or None"); - return -1; - } - Py_INCREF(ob); - stgdict->restype = ob; - stgdict->checker = PyObject_GetAttrString(ob, "_check_retval_"); - if (stgdict->checker == NULL) - PyErr_Clear(); - } + stgdict->align = _ctypes_get_fielddesc("P")->pffi_type->alignment; + stgdict->length = 1; + stgdict->size = sizeof(void *); + stgdict->setfunc = NULL; + stgdict->getfunc = NULL; + stgdict->ffi_type_pointer = ffi_type_pointer; + + ob = PyDict_GetItemString((PyObject *)stgdict, "_flags_"); + if (!ob || !PyLong_Check(ob)) { + PyErr_SetString(PyExc_TypeError, + "class must define _flags_ which must be an integer"); + return -1; + } + stgdict->flags = PyLong_AS_LONG(ob) | TYPEFLAG_ISPOINTER; + + /* _argtypes_ is optional... */ + ob = PyDict_GetItemString((PyObject *)stgdict, "_argtypes_"); + if (ob) { + converters = converters_from_argtypes(ob); + if (!converters) + goto error; + Py_INCREF(ob); + stgdict->argtypes = ob; + stgdict->converters = converters; + } + + ob = PyDict_GetItemString((PyObject *)stgdict, "_restype_"); + if (ob) { + if (ob != Py_None && !PyType_stgdict(ob) && !PyCallable_Check(ob)) { + PyErr_SetString(PyExc_TypeError, + "_restype_ must be a type, a callable, or None"); + return -1; + } + Py_INCREF(ob); + stgdict->restype = ob; + stgdict->checker = PyObject_GetAttrString(ob, "_check_retval_"); + if (stgdict->checker == NULL) + PyErr_Clear(); + } /* XXX later, maybe. - ob = PyDict_GetItemString((PyObject *)stgdict, "_errcheck_"); - if (ob) { - if (!PyCallable_Check(ob)) { - PyErr_SetString(PyExc_TypeError, - "_errcheck_ must be callable"); - return -1; - } - Py_INCREF(ob); - stgdict->errcheck = ob; - } + ob = PyDict_GetItemString((PyObject *)stgdict, "_errcheck_"); + if (ob) { + if (!PyCallable_Check(ob)) { + PyErr_SetString(PyExc_TypeError, + "_errcheck_ must be callable"); + return -1; + } + Py_INCREF(ob); + stgdict->errcheck = ob; + } */ - return 0; + return 0; error: - Py_XDECREF(converters); - return -1; + Py_XDECREF(converters); + return -1; } static PyCArgObject * PyCFuncPtrType_paramfunc(CDataObject *self) { - PyCArgObject *parg; - - parg = PyCArgObject_new(); - if (parg == NULL) - return NULL; - - parg->tag = 'P'; - parg->pffi_type = &ffi_type_pointer; - Py_INCREF(self); - parg->obj = (PyObject *)self; - parg->value.p = *(void **)self->b_ptr; - return parg; + PyCArgObject *parg; + + parg = PyCArgObject_new(); + if (parg == NULL) + return NULL; + + parg->tag = 'P'; + parg->pffi_type = &ffi_type_pointer; + Py_INCREF(self); + parg->obj = (PyObject *)self; + parg->value.p = *(void **)self->b_ptr; + return parg; } static PyObject * PyCFuncPtrType_new(PyTypeObject *type, PyObject *args, PyObject *kwds) { - PyTypeObject *result; - StgDictObject *stgdict; + PyTypeObject *result; + StgDictObject *stgdict; - stgdict = (StgDictObject *)PyObject_CallObject( - (PyObject *)&PyCStgDict_Type, NULL); - if (!stgdict) - return NULL; - - stgdict->paramfunc = PyCFuncPtrType_paramfunc; - /* We do NOT expose the function signature in the format string. It - is impossible, generally, because the only requirement for the - argtypes items is that they have a .from_param method - we do not - know the types of the arguments (although, in practice, most - argtypes would be a ctypes type). - */ - stgdict->format = _ctypes_alloc_format_string(NULL, "X{}"); - stgdict->flags |= TYPEFLAG_ISPOINTER; - - /* create the new instance (which is a class, - since we are a metatype!) */ - result = (PyTypeObject *)PyType_Type.tp_new(type, args, kwds); - if (result == NULL) { - Py_DECREF((PyObject *)stgdict); - return NULL; - } - - /* replace the class dict by our updated storage dict */ - if (-1 == PyDict_Update((PyObject *)stgdict, result->tp_dict)) { - Py_DECREF(result); - Py_DECREF((PyObject *)stgdict); - return NULL; - } - Py_DECREF(result->tp_dict); - result->tp_dict = (PyObject *)stgdict; - - if (-1 == make_funcptrtype_dict(stgdict)) { - Py_DECREF(result); - return NULL; - } + stgdict = (StgDictObject *)PyObject_CallObject( + (PyObject *)&PyCStgDict_Type, NULL); + if (!stgdict) + return NULL; + + stgdict->paramfunc = PyCFuncPtrType_paramfunc; + /* We do NOT expose the function signature in the format string. It + is impossible, generally, because the only requirement for the + argtypes items is that they have a .from_param method - we do not + know the types of the arguments (although, in practice, most + argtypes would be a ctypes type). + */ + stgdict->format = _ctypes_alloc_format_string(NULL, "X{}"); + stgdict->flags |= TYPEFLAG_ISPOINTER; + + /* create the new instance (which is a class, + since we are a metatype!) */ + result = (PyTypeObject *)PyType_Type.tp_new(type, args, kwds); + if (result == NULL) { + Py_DECREF((PyObject *)stgdict); + return NULL; + } + + /* replace the class dict by our updated storage dict */ + if (-1 == PyDict_Update((PyObject *)stgdict, result->tp_dict)) { + Py_DECREF(result); + Py_DECREF((PyObject *)stgdict); + return NULL; + } + Py_DECREF(result->tp_dict); + result->tp_dict = (PyObject *)stgdict; + + if (-1 == make_funcptrtype_dict(stgdict)) { + Py_DECREF(result); + return NULL; + } - return (PyObject *)result; + return (PyObject *)result; } PyTypeObject PyCFuncPtrType_Type = { - PyVarObject_HEAD_INIT(NULL, 0) - "_ctypes.PyCFuncPtrType", /* tp_name */ - 0, /* tp_basicsize */ - 0, /* tp_itemsize */ - 0, /* tp_dealloc */ - 0, /* tp_print */ - 0, /* tp_getattr */ - 0, /* tp_setattr */ - 0, /* tp_reserved */ - 0, /* tp_repr */ - 0, /* tp_as_number */ - &CDataType_as_sequence, /* tp_as_sequence */ - 0, /* tp_as_mapping */ - 0, /* tp_hash */ - 0, /* tp_call */ - 0, /* tp_str */ - 0, /* tp_getattro */ - 0, /* tp_setattro */ - 0, /* tp_as_buffer */ - Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC, /* tp_flags */ - "metatype for C function pointers", /* tp_doc */ - (traverseproc)CDataType_traverse, /* tp_traverse */ - (inquiry)CDataType_clear, /* tp_clear */ - 0, /* tp_richcompare */ - 0, /* tp_weaklistoffset */ - 0, /* tp_iter */ - 0, /* tp_iternext */ - CDataType_methods, /* tp_methods */ - 0, /* tp_members */ - 0, /* tp_getset */ - 0, /* tp_base */ - 0, /* tp_dict */ - 0, /* tp_descr_get */ - 0, /* tp_descr_set */ - 0, /* tp_dictoffset */ - 0, /* tp_init */ - 0, /* tp_alloc */ - PyCFuncPtrType_new, /* tp_new */ - 0, /* tp_free */ + PyVarObject_HEAD_INIT(NULL, 0) + "_ctypes.PyCFuncPtrType", /* tp_name */ + 0, /* tp_basicsize */ + 0, /* tp_itemsize */ + 0, /* tp_dealloc */ + 0, /* tp_print */ + 0, /* tp_getattr */ + 0, /* tp_setattr */ + 0, /* tp_reserved */ + 0, /* tp_repr */ + 0, /* tp_as_number */ + &CDataType_as_sequence, /* tp_as_sequence */ + 0, /* tp_as_mapping */ + 0, /* tp_hash */ + 0, /* tp_call */ + 0, /* tp_str */ + 0, /* tp_getattro */ + 0, /* tp_setattro */ + 0, /* tp_as_buffer */ + Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC, /* tp_flags */ + "metatype for C function pointers", /* tp_doc */ + (traverseproc)CDataType_traverse, /* tp_traverse */ + (inquiry)CDataType_clear, /* tp_clear */ + 0, /* tp_richcompare */ + 0, /* tp_weaklistoffset */ + 0, /* tp_iter */ + 0, /* tp_iternext */ + CDataType_methods, /* tp_methods */ + 0, /* tp_members */ + 0, /* tp_getset */ + 0, /* tp_base */ + 0, /* tp_dict */ + 0, /* tp_descr_get */ + 0, /* tp_descr_set */ + 0, /* tp_dictoffset */ + 0, /* tp_init */ + 0, /* tp_alloc */ + PyCFuncPtrType_new, /* tp_new */ + 0, /* tp_free */ }; - + /***************************************************************** * Code to keep needed objects alive */ @@ -2322,46 +2322,46 @@ static CDataObject * PyCData_GetContainer(CDataObject *self) { - while (self->b_base) - self = self->b_base; - if (self->b_objects == NULL) { - if (self->b_length) { - self->b_objects = PyDict_New(); - } else { - Py_INCREF(Py_None); - self->b_objects = Py_None; - } - } - return self; + while (self->b_base) + self = self->b_base; + if (self->b_objects == NULL) { + if (self->b_length) { + self->b_objects = PyDict_New(); + } else { + Py_INCREF(Py_None); + self->b_objects = Py_None; + } + } + return self; } static PyObject * GetKeepedObjects(CDataObject *target) { - return PyCData_GetContainer(target)->b_objects; + return PyCData_GetContainer(target)->b_objects; } static PyObject * unique_key(CDataObject *target, Py_ssize_t index) { - char string[256]; - char *cp = string; - size_t bytes_left; - - assert(sizeof(string) - 1 > sizeof(Py_ssize_t) * 2); - cp += sprintf(cp, "%x", Py_SAFE_DOWNCAST(index, Py_ssize_t, int)); - while (target->b_base) { - bytes_left = sizeof(string) - (cp - string) - 1; - /* Hex format needs 2 characters per byte */ - if (bytes_left < sizeof(Py_ssize_t) * 2) { - PyErr_SetString(PyExc_ValueError, - "ctypes object structure too deep"); - return NULL; - } - cp += sprintf(cp, ":%x", Py_SAFE_DOWNCAST(target->b_index, Py_ssize_t, int)); - target = target->b_base; - } - return PyUnicode_FromStringAndSize(string, cp-string); + char string[256]; + char *cp = string; + size_t bytes_left; + + assert(sizeof(string) - 1 > sizeof(Py_ssize_t) * 2); + cp += sprintf(cp, "%x", Py_SAFE_DOWNCAST(index, Py_ssize_t, int)); + while (target->b_base) { + bytes_left = sizeof(string) - (cp - string) - 1; + /* Hex format needs 2 characters per byte */ + if (bytes_left < sizeof(Py_ssize_t) * 2) { + PyErr_SetString(PyExc_ValueError, + "ctypes object structure too deep"); + return NULL; + } + cp += sprintf(cp, ":%x", Py_SAFE_DOWNCAST(target->b_index, Py_ssize_t, int)); + target = target->b_base; + } + return PyUnicode_FromStringAndSize(string, cp-string); } /* @@ -2385,30 +2385,30 @@ static int KeepRef(CDataObject *target, Py_ssize_t index, PyObject *keep) { - int result; - CDataObject *ob; - PyObject *key; + int result; + CDataObject *ob; + PyObject *key; /* Optimization: no need to store None */ - if (keep == Py_None) { - Py_DECREF(Py_None); - return 0; - } - ob = PyCData_GetContainer(target); - if (ob->b_objects == NULL || !PyDict_CheckExact(ob->b_objects)) { - Py_XDECREF(ob->b_objects); - ob->b_objects = keep; /* refcount consumed */ - return 0; - } - key = unique_key(target, index); - if (key == NULL) { - Py_DECREF(keep); - return -1; - } - result = PyDict_SetItem(ob->b_objects, key, keep); - Py_DECREF(key); - Py_DECREF(keep); - return result; + if (keep == Py_None) { + Py_DECREF(Py_None); + return 0; + } + ob = PyCData_GetContainer(target); + if (ob->b_objects == NULL || !PyDict_CheckExact(ob->b_objects)) { + Py_XDECREF(ob->b_objects); + ob->b_objects = keep; /* refcount consumed */ + return 0; + } + key = unique_key(target, index); + if (key == NULL) { + Py_DECREF(keep); + return -1; + } + result = PyDict_SetItem(ob->b_objects, key, keep); + Py_DECREF(key); + Py_DECREF(keep); + return result; } /******************************************************************/ @@ -2418,75 +2418,75 @@ static int PyCData_traverse(CDataObject *self, visitproc visit, void *arg) { - Py_VISIT(self->b_objects); - Py_VISIT((PyObject *)self->b_base); - return 0; + Py_VISIT(self->b_objects); + Py_VISIT((PyObject *)self->b_base); + return 0; } static int PyCData_clear(CDataObject *self) { - StgDictObject *dict = PyObject_stgdict((PyObject *)self); - assert(dict); /* Cannot be NULL for CDataObject instances */ - Py_CLEAR(self->b_objects); - if ((self->b_needsfree) - && ((size_t)dict->size > sizeof(self->b_value))) - PyMem_Free(self->b_ptr); - self->b_ptr = NULL; - Py_CLEAR(self->b_base); - return 0; + StgDictObject *dict = PyObject_stgdict((PyObject *)self); + assert(dict); /* Cannot be NULL for CDataObject instances */ + Py_CLEAR(self->b_objects); + if ((self->b_needsfree) + && ((size_t)dict->size > sizeof(self->b_value))) + PyMem_Free(self->b_ptr); + self->b_ptr = NULL; + Py_CLEAR(self->b_base); + return 0; } static void PyCData_dealloc(PyObject *self) { - PyCData_clear((CDataObject *)self); - Py_TYPE(self)->tp_free(self); + PyCData_clear((CDataObject *)self); + Py_TYPE(self)->tp_free(self); } static PyMemberDef PyCData_members[] = { - { "_b_base_", T_OBJECT, - offsetof(CDataObject, b_base), READONLY, - "the base object" }, - { "_b_needsfree_", T_INT, - offsetof(CDataObject, b_needsfree), READONLY, - "whether the object owns the memory or not" }, - { "_objects", T_OBJECT, - offsetof(CDataObject, b_objects), READONLY, - "internal objects tree (NEVER CHANGE THIS OBJECT!)"}, - { NULL }, + { "_b_base_", T_OBJECT, + offsetof(CDataObject, b_base), READONLY, + "the base object" }, + { "_b_needsfree_", T_INT, + offsetof(CDataObject, b_needsfree), READONLY, + "whether the object owns the memory or not" }, + { "_objects", T_OBJECT, + offsetof(CDataObject, b_objects), READONLY, + "internal objects tree (NEVER CHANGE THIS OBJECT!)"}, + { NULL }, }; static int PyCData_NewGetBuffer(PyObject *_self, Py_buffer *view, int flags) { - CDataObject *self = (CDataObject *)_self; - StgDictObject *dict = PyObject_stgdict(_self); - Py_ssize_t i; - - if (view == NULL) return 0; - - view->buf = self->b_ptr; - view->obj = _self; - Py_INCREF(_self); - view->len = self->b_size; - view->readonly = 0; - /* use default format character if not set */ - view->format = dict->format ? dict->format : "B"; - view->ndim = dict->ndim; - view->shape = dict->shape; - view->itemsize = self->b_size; - for (i = 0; i < view->ndim; ++i) { - view->itemsize /= dict->shape[i]; - } - view->strides = NULL; - view->suboffsets = NULL; - view->internal = NULL; - return 0; + CDataObject *self = (CDataObject *)_self; + StgDictObject *dict = PyObject_stgdict(_self); + Py_ssize_t i; + + if (view == NULL) return 0; + + view->buf = self->b_ptr; + view->obj = _self; + Py_INCREF(_self); + view->len = self->b_size; + view->readonly = 0; + /* use default format character if not set */ + view->format = dict->format ? dict->format : "B"; + view->ndim = dict->ndim; + view->shape = dict->shape; + view->itemsize = self->b_size; + for (i = 0; i < view->ndim; ++i) { + view->itemsize /= dict->shape[i]; + } + view->strides = NULL; + view->suboffsets = NULL; + view->internal = NULL; + return 0; } static PyBufferProcs PyCData_as_buffer = { - PyCData_NewGetBuffer, - NULL, + PyCData_NewGetBuffer, + NULL, }; /* @@ -2495,47 +2495,47 @@ static long PyCData_nohash(PyObject *self) { - PyErr_SetString(PyExc_TypeError, "unhashable type"); - return -1; + PyErr_SetString(PyExc_TypeError, "unhashable type"); + return -1; } static PyObject * PyCData_reduce(PyObject *_self, PyObject *args) { - CDataObject *self = (CDataObject *)_self; + CDataObject *self = (CDataObject *)_self; - if (PyObject_stgdict(_self)->flags & (TYPEFLAG_ISPOINTER|TYPEFLAG_HASPOINTER)) { - PyErr_SetString(PyExc_ValueError, - "ctypes objects containing pointers cannot be pickled"); - return NULL; - } - return Py_BuildValue("O(O(NN))", - _unpickle, - Py_TYPE(_self), - PyObject_GetAttrString(_self, "__dict__"), - PyBytes_FromStringAndSize(self->b_ptr, self->b_size)); + if (PyObject_stgdict(_self)->flags & (TYPEFLAG_ISPOINTER|TYPEFLAG_HASPOINTER)) { + PyErr_SetString(PyExc_ValueError, + "ctypes objects containing pointers cannot be pickled"); + return NULL; + } + return Py_BuildValue("O(O(NN))", + _unpickle, + Py_TYPE(_self), + PyObject_GetAttrString(_self, "__dict__"), + PyBytes_FromStringAndSize(self->b_ptr, self->b_size)); } static PyObject * PyCData_setstate(PyObject *_self, PyObject *args) { - void *data; - Py_ssize_t len; - int res; - PyObject *dict, *mydict; - CDataObject *self = (CDataObject *)_self; - if (!PyArg_ParseTuple(args, "Os#", &dict, &data, &len)) - return NULL; - if (len > self->b_size) - len = self->b_size; - memmove(self->b_ptr, data, len); - mydict = PyObject_GetAttrString(_self, "__dict__"); - res = PyDict_Update(mydict, dict); - Py_DECREF(mydict); - if (res == -1) - return NULL; - Py_INCREF(Py_None); - return Py_None; + void *data; + Py_ssize_t len; + int res; + PyObject *dict, *mydict; + CDataObject *self = (CDataObject *)_self; + if (!PyArg_ParseTuple(args, "Os#", &dict, &data, &len)) + return NULL; + if (len > self->b_size) + len = self->b_size; + memmove(self->b_ptr, data, len); + mydict = PyObject_GetAttrString(_self, "__dict__"); + res = PyDict_Update(mydict, dict); + Py_DECREF(mydict); + if (res == -1) + return NULL; + Py_INCREF(Py_None); + return Py_None; } /* @@ -2544,124 +2544,124 @@ static PyObject * PyCData_from_outparam(PyObject *self, PyObject *args) { - Py_INCREF(self); - return self; + Py_INCREF(self); + return self; } static PyMethodDef PyCData_methods[] = { - { "__ctypes_from_outparam__", PyCData_from_outparam, METH_NOARGS, }, - { "__reduce__", PyCData_reduce, METH_NOARGS, }, - { "__setstate__", PyCData_setstate, METH_VARARGS, }, - { NULL, NULL }, + { "__ctypes_from_outparam__", PyCData_from_outparam, METH_NOARGS, }, + { "__reduce__", PyCData_reduce, METH_NOARGS, }, + { "__setstate__", PyCData_setstate, METH_VARARGS, }, + { NULL, NULL }, }; PyTypeObject PyCData_Type = { - PyVarObject_HEAD_INIT(NULL, 0) - "_ctypes._CData", - sizeof(CDataObject), /* tp_basicsize */ - 0, /* tp_itemsize */ - PyCData_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 */ - PyCData_nohash, /* tp_hash */ - 0, /* tp_call */ - 0, /* tp_str */ - 0, /* tp_getattro */ - 0, /* tp_setattro */ - &PyCData_as_buffer, /* tp_as_buffer */ - Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */ - "XXX to be provided", /* tp_doc */ - (traverseproc)PyCData_traverse, /* tp_traverse */ - (inquiry)PyCData_clear, /* tp_clear */ - 0, /* tp_richcompare */ - 0, /* tp_weaklistoffset */ - 0, /* tp_iter */ - 0, /* tp_iternext */ - PyCData_methods, /* tp_methods */ - PyCData_members, /* tp_members */ - 0, /* tp_getset */ - 0, /* tp_base */ - 0, /* tp_dict */ - 0, /* tp_descr_get */ - 0, /* tp_descr_set */ - 0, /* tp_dictoffset */ - 0, /* tp_init */ - 0, /* tp_alloc */ - 0, /* tp_new */ - 0, /* tp_free */ + PyVarObject_HEAD_INIT(NULL, 0) + "_ctypes._CData", + sizeof(CDataObject), /* tp_basicsize */ + 0, /* tp_itemsize */ + PyCData_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 */ + PyCData_nohash, /* tp_hash */ + 0, /* tp_call */ + 0, /* tp_str */ + 0, /* tp_getattro */ + 0, /* tp_setattro */ + &PyCData_as_buffer, /* tp_as_buffer */ + Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */ + "XXX to be provided", /* tp_doc */ + (traverseproc)PyCData_traverse, /* tp_traverse */ + (inquiry)PyCData_clear, /* tp_clear */ + 0, /* tp_richcompare */ + 0, /* tp_weaklistoffset */ + 0, /* tp_iter */ + 0, /* tp_iternext */ + PyCData_methods, /* tp_methods */ + PyCData_members, /* tp_members */ + 0, /* tp_getset */ + 0, /* tp_base */ + 0, /* tp_dict */ + 0, /* tp_descr_get */ + 0, /* tp_descr_set */ + 0, /* tp_dictoffset */ + 0, /* tp_init */ + 0, /* tp_alloc */ + 0, /* tp_new */ + 0, /* tp_free */ }; static int PyCData_MallocBuffer(CDataObject *obj, StgDictObject *dict) { - if ((size_t)dict->size <= sizeof(obj->b_value)) { - /* No need to call malloc, can use the default buffer */ - obj->b_ptr = (char *)&obj->b_value; - /* The b_needsfree flag does not mean that we actually did - call PyMem_Malloc to allocate the memory block; instead it - means we are the *owner* of the memory and are responsible - for freeing resources associated with the memory. This is - also the reason that b_needsfree is exposed to Python. - */ - obj->b_needsfree = 1; - } else { - /* In python 2.4, and ctypes 0.9.6, the malloc call took about - 33% of the creation time for c_int(). - */ - obj->b_ptr = (char *)PyMem_Malloc(dict->size); - if (obj->b_ptr == NULL) { - PyErr_NoMemory(); - return -1; - } - obj->b_needsfree = 1; - memset(obj->b_ptr, 0, dict->size); - } - obj->b_size = dict->size; - return 0; + if ((size_t)dict->size <= sizeof(obj->b_value)) { + /* No need to call malloc, can use the default buffer */ + obj->b_ptr = (char *)&obj->b_value; + /* The b_needsfree flag does not mean that we actually did + call PyMem_Malloc to allocate the memory block; instead it + means we are the *owner* of the memory and are responsible + for freeing resources associated with the memory. This is + also the reason that b_needsfree is exposed to Python. + */ + obj->b_needsfree = 1; + } else { + /* In python 2.4, and ctypes 0.9.6, the malloc call took about + 33% of the creation time for c_int(). + */ + obj->b_ptr = (char *)PyMem_Malloc(dict->size); + if (obj->b_ptr == NULL) { + PyErr_NoMemory(); + return -1; + } + obj->b_needsfree = 1; + memset(obj->b_ptr, 0, dict->size); + } + obj->b_size = dict->size; + return 0; } PyObject * PyCData_FromBaseObj(PyObject *type, PyObject *base, Py_ssize_t index, char *adr) { - CDataObject *cmem; - StgDictObject *dict; + CDataObject *cmem; + StgDictObject *dict; - assert(PyType_Check(type)); - dict = PyType_stgdict(type); - if (!dict) { - PyErr_SetString(PyExc_TypeError, - "abstract class"); - return NULL; - } - dict->flags |= DICTFLAG_FINAL; - cmem = (CDataObject *)((PyTypeObject *)type)->tp_alloc((PyTypeObject *)type, 0); - if (cmem == NULL) - return NULL; - assert(CDataObject_Check(cmem)); - - cmem->b_length = dict->length; - cmem->b_size = dict->size; - if (base) { /* use base's buffer */ - assert(CDataObject_Check(base)); - cmem->b_ptr = adr; - cmem->b_needsfree = 0; - Py_INCREF(base); - cmem->b_base = (CDataObject *)base; - cmem->b_index = index; - } else { /* copy contents of adr */ - if (-1 == PyCData_MallocBuffer(cmem, dict)) { - return NULL; - Py_DECREF(cmem); - } - memcpy(cmem->b_ptr, adr, dict->size); - cmem->b_index = index; - } - return (PyObject *)cmem; + assert(PyType_Check(type)); + dict = PyType_stgdict(type); + if (!dict) { + PyErr_SetString(PyExc_TypeError, + "abstract class"); + return NULL; + } + dict->flags |= DICTFLAG_FINAL; + cmem = (CDataObject *)((PyTypeObject *)type)->tp_alloc((PyTypeObject *)type, 0); + if (cmem == NULL) + return NULL; + assert(CDataObject_Check(cmem)); + + cmem->b_length = dict->length; + cmem->b_size = dict->size; + if (base) { /* use base's buffer */ + assert(CDataObject_Check(base)); + cmem->b_ptr = adr; + cmem->b_needsfree = 0; + Py_INCREF(base); + cmem->b_base = (CDataObject *)base; + cmem->b_index = index; + } else { /* copy contents of adr */ + if (-1 == PyCData_MallocBuffer(cmem, dict)) { + return NULL; + Py_DECREF(cmem); + } + memcpy(cmem->b_ptr, adr, dict->size); + cmem->b_index = index; + } + return (PyObject *)cmem; } /* @@ -2670,26 +2670,26 @@ PyObject * PyCData_AtAddress(PyObject *type, void *buf) { - CDataObject *pd; - StgDictObject *dict; + CDataObject *pd; + StgDictObject *dict; - assert(PyType_Check(type)); - dict = PyType_stgdict(type); - if (!dict) { - PyErr_SetString(PyExc_TypeError, - "abstract class"); - return NULL; - } - dict->flags |= DICTFLAG_FINAL; - - pd = (CDataObject *)((PyTypeObject *)type)->tp_alloc((PyTypeObject *)type, 0); - if (!pd) - return NULL; - assert(CDataObject_Check(pd)); - pd->b_ptr = (char *)buf; - pd->b_length = dict->length; - pd->b_size = dict->size; - return (PyObject *)pd; + assert(PyType_Check(type)); + dict = PyType_stgdict(type); + if (!dict) { + PyErr_SetString(PyExc_TypeError, + "abstract class"); + return NULL; + } + dict->flags |= DICTFLAG_FINAL; + + pd = (CDataObject *)((PyTypeObject *)type)->tp_alloc((PyTypeObject *)type, 0); + if (!pd) + return NULL; + assert(CDataObject_Check(pd)); + pd->b_ptr = (char *)buf; + pd->b_length = dict->length; + pd->b_size = dict->size; + return (PyObject *)pd; } /* @@ -2699,25 +2699,25 @@ */ int _ctypes_simple_instance(PyObject *obj) { - PyTypeObject *type = (PyTypeObject *)obj; + PyTypeObject *type = (PyTypeObject *)obj; - if (PyCSimpleTypeObject_Check(type)) - return type->tp_base != &Simple_Type; - return 0; + if (PyCSimpleTypeObject_Check(type)) + return type->tp_base != &Simple_Type; + return 0; } PyObject * PyCData_get(PyObject *type, GETFUNC getfunc, PyObject *src, - Py_ssize_t index, Py_ssize_t size, char *adr) + Py_ssize_t index, Py_ssize_t size, char *adr) { - StgDictObject *dict; - if (getfunc) - return getfunc(adr, size); - assert(type); - dict = PyType_stgdict(type); - if (dict && dict->getfunc && !_ctypes_simple_instance(type)) - return dict->getfunc(adr, size); - return PyCData_FromBaseObj(type, src, index, adr); + StgDictObject *dict; + if (getfunc) + return getfunc(adr, size); + assert(type); + dict = PyType_stgdict(type); + if (dict && dict->getfunc && !_ctypes_simple_instance(type)) + return dict->getfunc(adr, size); + return PyCData_FromBaseObj(type, src, index, adr); } /* @@ -2725,96 +2725,96 @@ */ static PyObject * _PyCData_set(CDataObject *dst, PyObject *type, SETFUNC setfunc, PyObject *value, - Py_ssize_t size, char *ptr) + Py_ssize_t size, char *ptr) { - CDataObject *src; + CDataObject *src; - if (setfunc) - return setfunc(ptr, value, size); - - if (!CDataObject_Check(value)) { - StgDictObject *dict = PyType_stgdict(type); - if (dict && dict->setfunc) - return dict->setfunc(ptr, value, size); - /* - If value is a tuple, we try to call the type with the tuple - and use the result! - */ - assert(PyType_Check(type)); - if (PyTuple_Check(value)) { - PyObject *ob; - PyObject *result; - ob = PyObject_CallObject(type, value); - if (ob == NULL) { - _ctypes_extend_error(PyExc_RuntimeError, "(%s) ", - ((PyTypeObject *)type)->tp_name); - return NULL; - } - result = _PyCData_set(dst, type, setfunc, ob, - size, ptr); - Py_DECREF(ob); - return result; - } else if (value == Py_None && PyCPointerTypeObject_Check(type)) { - *(void **)ptr = NULL; - Py_INCREF(Py_None); - return Py_None; - } else { - PyErr_Format(PyExc_TypeError, - "expected %s instance, got %s", - ((PyTypeObject *)type)->tp_name, - Py_TYPE(value)->tp_name); - return NULL; - } - } - src = (CDataObject *)value; - - if (PyObject_IsInstance(value, type)) { - memcpy(ptr, - src->b_ptr, - size); - - if (PyCPointerTypeObject_Check(type)) - /* XXX */; - - value = GetKeepedObjects(src); - Py_INCREF(value); - return value; - } - - if (PyCPointerTypeObject_Check(type) - && ArrayObject_Check(value)) { - StgDictObject *p1, *p2; - PyObject *keep; - p1 = PyObject_stgdict(value); - assert(p1); /* Cannot be NULL for array instances */ - p2 = PyType_stgdict(type); - assert(p2); /* Cannot be NULL for pointer types */ - - if (p1->proto != p2->proto) { - PyErr_Format(PyExc_TypeError, - "incompatible types, %s instance instead of %s instance", - Py_TYPE(value)->tp_name, - ((PyTypeObject *)type)->tp_name); - return NULL; - } - *(void **)ptr = src->b_ptr; - - keep = GetKeepedObjects(src); - /* - We are assigning an array object to a field which represents - a pointer. This has the same effect as converting an array - into a pointer. So, again, we have to keep the whole object - pointed to (which is the array in this case) alive, and not - only it's object list. So we create a tuple, containing - b_objects list PLUS the array itself, and return that! - */ - return PyTuple_Pack(2, keep, value); - } - PyErr_Format(PyExc_TypeError, - "incompatible types, %s instance instead of %s instance", - Py_TYPE(value)->tp_name, - ((PyTypeObject *)type)->tp_name); - return NULL; + if (setfunc) + return setfunc(ptr, value, size); + + if (!CDataObject_Check(value)) { + StgDictObject *dict = PyType_stgdict(type); + if (dict && dict->setfunc) + return dict->setfunc(ptr, value, size); + /* + If value is a tuple, we try to call the type with the tuple + and use the result! + */ + assert(PyType_Check(type)); + if (PyTuple_Check(value)) { + PyObject *ob; + PyObject *result; + ob = PyObject_CallObject(type, value); + if (ob == NULL) { + _ctypes_extend_error(PyExc_RuntimeError, "(%s) ", + ((PyTypeObject *)type)->tp_name); + return NULL; + } + result = _PyCData_set(dst, type, setfunc, ob, + size, ptr); + Py_DECREF(ob); + return result; + } else if (value == Py_None && PyCPointerTypeObject_Check(type)) { + *(void **)ptr = NULL; + Py_INCREF(Py_None); + return Py_None; + } else { + PyErr_Format(PyExc_TypeError, + "expected %s instance, got %s", + ((PyTypeObject *)type)->tp_name, + Py_TYPE(value)->tp_name); + return NULL; + } + } + src = (CDataObject *)value; + + if (PyObject_IsInstance(value, type)) { + memcpy(ptr, + src->b_ptr, + size); + + if (PyCPointerTypeObject_Check(type)) + /* XXX */; + + value = GetKeepedObjects(src); + Py_INCREF(value); + return value; + } + + if (PyCPointerTypeObject_Check(type) + && ArrayObject_Check(value)) { + StgDictObject *p1, *p2; + PyObject *keep; + p1 = PyObject_stgdict(value); + assert(p1); /* Cannot be NULL for array instances */ + p2 = PyType_stgdict(type); + assert(p2); /* Cannot be NULL for pointer types */ + + if (p1->proto != p2->proto) { + PyErr_Format(PyExc_TypeError, + "incompatible types, %s instance instead of %s instance", + Py_TYPE(value)->tp_name, + ((PyTypeObject *)type)->tp_name); + return NULL; + } + *(void **)ptr = src->b_ptr; + + keep = GetKeepedObjects(src); + /* + We are assigning an array object to a field which represents + a pointer. This has the same effect as converting an array + into a pointer. So, again, we have to keep the whole object + pointed to (which is the array in this case) alive, and not + only it's object list. So we create a tuple, containing + b_objects list PLUS the array itself, and return that! + */ + return PyTuple_Pack(2, keep, value); + } + PyErr_Format(PyExc_TypeError, + "incompatible types, %s instance instead of %s instance", + Py_TYPE(value)->tp_name, + ((PyTypeObject *)type)->tp_name); + return NULL; } /* @@ -2823,58 +2823,58 @@ */ int PyCData_set(PyObject *dst, PyObject *type, SETFUNC setfunc, PyObject *value, - Py_ssize_t index, Py_ssize_t size, char *ptr) + Py_ssize_t index, Py_ssize_t size, char *ptr) { - CDataObject *mem = (CDataObject *)dst; - PyObject *result; + CDataObject *mem = (CDataObject *)dst; + PyObject *result; - if (!CDataObject_Check(dst)) { - PyErr_SetString(PyExc_TypeError, - "not a ctype instance"); - return -1; - } + if (!CDataObject_Check(dst)) { + PyErr_SetString(PyExc_TypeError, + "not a ctype instance"); + return -1; + } - result = _PyCData_set(mem, type, setfunc, value, - size, ptr); - if (result == NULL) - return -1; + result = _PyCData_set(mem, type, setfunc, value, + size, ptr); + if (result == NULL) + return -1; - /* KeepRef steals a refcount from it's last argument */ - /* If KeepRef fails, we are stumped. The dst memory block has already - been changed */ - return KeepRef(mem, index, result); + /* KeepRef steals a refcount from it's last argument */ + /* If KeepRef fails, we are stumped. The dst memory block has already + been changed */ + return KeepRef(mem, index, result); } - + /******************************************************************/ static PyObject * GenericPyCData_new(PyTypeObject *type, PyObject *args, PyObject *kwds) { - CDataObject *obj; - StgDictObject *dict; + CDataObject *obj; + StgDictObject *dict; - dict = PyType_stgdict((PyObject *)type); - if (!dict) { - PyErr_SetString(PyExc_TypeError, - "abstract class"); - return NULL; - } - dict->flags |= DICTFLAG_FINAL; - - obj = (CDataObject *)type->tp_alloc(type, 0); - if (!obj) - return NULL; - - obj->b_base = NULL; - obj->b_index = 0; - obj->b_objects = NULL; - obj->b_length = dict->length; - - if (-1 == PyCData_MallocBuffer(obj, dict)) { - Py_DECREF(obj); - return NULL; - } - return (PyObject *)obj; + dict = PyType_stgdict((PyObject *)type); + if (!dict) { + PyErr_SetString(PyExc_TypeError, + "abstract class"); + return NULL; + } + dict->flags |= DICTFLAG_FINAL; + + obj = (CDataObject *)type->tp_alloc(type, 0); + if (!obj) + return NULL; + + obj->b_base = NULL; + obj->b_index = 0; + obj->b_objects = NULL; + obj->b_length = dict->length; + + if (-1 == PyCData_MallocBuffer(obj, dict)) { + Py_DECREF(obj); + return NULL; + } + return (PyObject *)obj; } /*****************************************************************/ /* @@ -2884,165 +2884,165 @@ static int PyCFuncPtr_set_errcheck(PyCFuncPtrObject *self, PyObject *ob) { - if (ob && !PyCallable_Check(ob)) { - PyErr_SetString(PyExc_TypeError, - "the errcheck attribute must be callable"); - return -1; - } - Py_XDECREF(self->errcheck); - Py_XINCREF(ob); - self->errcheck = ob; - return 0; + if (ob && !PyCallable_Check(ob)) { + PyErr_SetString(PyExc_TypeError, + "the errcheck attribute must be callable"); + return -1; + } + Py_XDECREF(self->errcheck); + Py_XINCREF(ob); + self->errcheck = ob; + return 0; } static PyObject * PyCFuncPtr_get_errcheck(PyCFuncPtrObject *self) { - if (self->errcheck) { - Py_INCREF(self->errcheck); - return self->errcheck; - } - Py_INCREF(Py_None); - return Py_None; + if (self->errcheck) { + Py_INCREF(self->errcheck); + return self->errcheck; + } + Py_INCREF(Py_None); + return Py_None; } static int PyCFuncPtr_set_restype(PyCFuncPtrObject *self, PyObject *ob) { - if (ob == NULL) { - Py_XDECREF(self->restype); - self->restype = NULL; - Py_XDECREF(self->checker); - self->checker = NULL; - return 0; - } - if (ob != Py_None && !PyType_stgdict(ob) && !PyCallable_Check(ob)) { - PyErr_SetString(PyExc_TypeError, - "restype must be a type, a callable, or None"); - return -1; - } - Py_XDECREF(self->checker); - Py_XDECREF(self->restype); - Py_INCREF(ob); - self->restype = ob; - self->checker = PyObject_GetAttrString(ob, "_check_retval_"); - if (self->checker == NULL) - PyErr_Clear(); - return 0; + if (ob == NULL) { + Py_XDECREF(self->restype); + self->restype = NULL; + Py_XDECREF(self->checker); + self->checker = NULL; + return 0; + } + if (ob != Py_None && !PyType_stgdict(ob) && !PyCallable_Check(ob)) { + PyErr_SetString(PyExc_TypeError, + "restype must be a type, a callable, or None"); + return -1; + } + Py_XDECREF(self->checker); + Py_XDECREF(self->restype); + Py_INCREF(ob); + self->restype = ob; + self->checker = PyObject_GetAttrString(ob, "_check_retval_"); + if (self->checker == NULL) + PyErr_Clear(); + return 0; } static PyObject * PyCFuncPtr_get_restype(PyCFuncPtrObject *self) { - StgDictObject *dict; - if (self->restype) { - Py_INCREF(self->restype); - return self->restype; - } - dict = PyObject_stgdict((PyObject *)self); - assert(dict); /* Cannot be NULL for PyCFuncPtrObject instances */ - if (dict->restype) { - Py_INCREF(dict->restype); - return dict->restype; - } else { - Py_INCREF(Py_None); - return Py_None; - } + StgDictObject *dict; + if (self->restype) { + Py_INCREF(self->restype); + return self->restype; + } + dict = PyObject_stgdict((PyObject *)self); + assert(dict); /* Cannot be NULL for PyCFuncPtrObject instances */ + if (dict->restype) { + Py_INCREF(dict->restype); + return dict->restype; + } else { + Py_INCREF(Py_None); + return Py_None; + } } static int PyCFuncPtr_set_argtypes(PyCFuncPtrObject *self, PyObject *ob) { - PyObject *converters; + PyObject *converters; - if (ob == NULL || ob == Py_None) { - Py_XDECREF(self->converters); - self->converters = NULL; - Py_XDECREF(self->argtypes); - self->argtypes = NULL; - } else { - converters = converters_from_argtypes(ob); - if (!converters) - return -1; - Py_XDECREF(self->converters); - self->converters = converters; - Py_XDECREF(self->argtypes); - Py_INCREF(ob); - self->argtypes = ob; - } - return 0; + if (ob == NULL || ob == Py_None) { + Py_XDECREF(self->converters); + self->converters = NULL; + Py_XDECREF(self->argtypes); + self->argtypes = NULL; + } else { + converters = converters_from_argtypes(ob); + if (!converters) + return -1; + Py_XDECREF(self->converters); + self->converters = converters; + Py_XDECREF(self->argtypes); + Py_INCREF(ob); + self->argtypes = ob; + } + return 0; } static PyObject * PyCFuncPtr_get_argtypes(PyCFuncPtrObject *self) { - StgDictObject *dict; - if (self->argtypes) { - Py_INCREF(self->argtypes); - return self->argtypes; - } - dict = PyObject_stgdict((PyObject *)self); - assert(dict); /* Cannot be NULL for PyCFuncPtrObject instances */ - if (dict->argtypes) { - Py_INCREF(dict->argtypes); - return dict->argtypes; - } else { - Py_INCREF(Py_None); - return Py_None; - } + StgDictObject *dict; + if (self->argtypes) { + Py_INCREF(self->argtypes); + return self->argtypes; + } + dict = PyObject_stgdict((PyObject *)self); + assert(dict); /* Cannot be NULL for PyCFuncPtrObject instances */ + if (dict->argtypes) { + Py_INCREF(dict->argtypes); + return dict->argtypes; + } else { + Py_INCREF(Py_None); + return Py_None; + } } static PyGetSetDef PyCFuncPtr_getsets[] = { - { "errcheck", (getter)PyCFuncPtr_get_errcheck, (setter)PyCFuncPtr_set_errcheck, - "a function to check for errors", NULL }, - { "restype", (getter)PyCFuncPtr_get_restype, (setter)PyCFuncPtr_set_restype, - "specify the result type", NULL }, - { "argtypes", (getter)PyCFuncPtr_get_argtypes, - (setter)PyCFuncPtr_set_argtypes, - "specify the argument types", NULL }, - { NULL, NULL } + { "errcheck", (getter)PyCFuncPtr_get_errcheck, (setter)PyCFuncPtr_set_errcheck, + "a function to check for errors", NULL }, + { "restype", (getter)PyCFuncPtr_get_restype, (setter)PyCFuncPtr_set_restype, + "specify the result type", NULL }, + { "argtypes", (getter)PyCFuncPtr_get_argtypes, + (setter)PyCFuncPtr_set_argtypes, + "specify the argument types", NULL }, + { NULL, NULL } }; #ifdef MS_WIN32 static PPROC FindAddress(void *handle, char *name, PyObject *type) { #ifdef MS_WIN64 - /* win64 has no stdcall calling conv, so it should - also not have the name mangling of it. - */ - return (PPROC)GetProcAddress(handle, name); + /* win64 has no stdcall calling conv, so it should + also not have the name mangling of it. + */ + return (PPROC)GetProcAddress(handle, name); #else - PPROC address; - char *mangled_name; - int i; - StgDictObject *dict; - - address = (PPROC)GetProcAddress(handle, name); - if (address) - return address; - if (((size_t)name & ~0xFFFF) == 0) { - return NULL; - } - - dict = PyType_stgdict((PyObject *)type); - /* It should not happen that dict is NULL, but better be safe */ - if (dict==NULL || dict->flags & FUNCFLAG_CDECL) - return address; - - /* for stdcall, try mangled names: - funcname -> _funcname@ - where n is 0, 4, 8, 12, ..., 128 - */ - mangled_name = alloca(strlen(name) + 1 + 1 + 1 + 3); /* \0 _ @ %d */ - if (!mangled_name) - return NULL; - for (i = 0; i < 32; ++i) { - sprintf(mangled_name, "_%s@%d", name, i*4); - address = (PPROC)GetProcAddress(handle, mangled_name); - if (address) - return address; - } - return NULL; + PPROC address; + char *mangled_name; + int i; + StgDictObject *dict; + + address = (PPROC)GetProcAddress(handle, name); + if (address) + return address; + if (((size_t)name & ~0xFFFF) == 0) { + return NULL; + } + + dict = PyType_stgdict((PyObject *)type); + /* It should not happen that dict is NULL, but better be safe */ + if (dict==NULL || dict->flags & FUNCFLAG_CDECL) + return address; + + /* for stdcall, try mangled names: + funcname -> _funcname@ + where n is 0, 4, 8, 12, ..., 128 + */ + mangled_name = alloca(strlen(name) + 1 + 1 + 1 + 3); /* \0 _ @ %d */ + if (!mangled_name) + return NULL; + for (i = 0; i < 32; ++i) { + sprintf(mangled_name, "_%s@%d", name, i*4); + address = (PPROC)GetProcAddress(handle, mangled_name); + if (address) + return address; + } + return NULL; #endif } #endif @@ -3051,227 +3051,227 @@ static int _check_outarg_type(PyObject *arg, Py_ssize_t index) { - StgDictObject *dict; + StgDictObject *dict; - if (PyCPointerTypeObject_Check(arg)) - return 1; + if (PyCPointerTypeObject_Check(arg)) + return 1; - if (PyCArrayTypeObject_Check(arg)) - return 1; + if (PyCArrayTypeObject_Check(arg)) + return 1; - dict = PyType_stgdict(arg); - if (dict - /* simple pointer types, c_void_p, c_wchar_p, BSTR, ... */ - && PyUnicode_Check(dict->proto) + dict = PyType_stgdict(arg); + if (dict + /* simple pointer types, c_void_p, c_wchar_p, BSTR, ... */ + && PyUnicode_Check(dict->proto) /* We only allow c_void_p, c_char_p and c_wchar_p as a simple output parameter type */ - && (strchr("PzZ", _PyUnicode_AsString(dict->proto)[0]))) { - return 1; - } - - PyErr_Format(PyExc_TypeError, - "'out' parameter %d must be a pointer type, not %s", - Py_SAFE_DOWNCAST(index, Py_ssize_t, int), - PyType_Check(arg) ? - ((PyTypeObject *)arg)->tp_name : - Py_TYPE(arg)->tp_name); - return 0; + && (strchr("PzZ", _PyUnicode_AsString(dict->proto)[0]))) { + return 1; + } + + PyErr_Format(PyExc_TypeError, + "'out' parameter %d must be a pointer type, not %s", + Py_SAFE_DOWNCAST(index, Py_ssize_t, int), + PyType_Check(arg) ? + ((PyTypeObject *)arg)->tp_name : + Py_TYPE(arg)->tp_name); + return 0; } /* Returns 1 on success, 0 on error */ static int _validate_paramflags(PyTypeObject *type, PyObject *paramflags) { - Py_ssize_t i, len; - StgDictObject *dict; - PyObject *argtypes; - - dict = PyType_stgdict((PyObject *)type); - assert(dict); /* Cannot be NULL. 'type' is a PyCFuncPtr type. */ - argtypes = dict->argtypes; - - if (paramflags == NULL || dict->argtypes == NULL) - return 1; - - if (!PyTuple_Check(paramflags)) { - PyErr_SetString(PyExc_TypeError, - "paramflags must be a tuple or None"); - return 0; - } - - len = PyTuple_GET_SIZE(paramflags); - if (len != PyTuple_GET_SIZE(dict->argtypes)) { - PyErr_SetString(PyExc_ValueError, - "paramflags must have the same length as argtypes"); - return 0; - } - - for (i = 0; i < len; ++i) { - PyObject *item = PyTuple_GET_ITEM(paramflags, i); - int flag; - char *name; - PyObject *defval; - PyObject *typ; - if (!PyArg_ParseTuple(item, "i|ZO", &flag, &name, &defval)) { - PyErr_SetString(PyExc_TypeError, - "paramflags must be a sequence of (int [,string [,value]]) tuples"); - return 0; - } - typ = PyTuple_GET_ITEM(argtypes, i); - switch (flag & (PARAMFLAG_FIN | PARAMFLAG_FOUT | PARAMFLAG_FLCID)) { - case 0: - case PARAMFLAG_FIN: - case PARAMFLAG_FIN | PARAMFLAG_FLCID: - case PARAMFLAG_FIN | PARAMFLAG_FOUT: - break; - case PARAMFLAG_FOUT: - if (!_check_outarg_type(typ, i+1)) - return 0; - break; - default: - PyErr_Format(PyExc_TypeError, - "paramflag value %d not supported", - flag); - return 0; - } - } - return 1; + Py_ssize_t i, len; + StgDictObject *dict; + PyObject *argtypes; + + dict = PyType_stgdict((PyObject *)type); + assert(dict); /* Cannot be NULL. 'type' is a PyCFuncPtr type. */ + argtypes = dict->argtypes; + + if (paramflags == NULL || dict->argtypes == NULL) + return 1; + + if (!PyTuple_Check(paramflags)) { + PyErr_SetString(PyExc_TypeError, + "paramflags must be a tuple or None"); + return 0; + } + + len = PyTuple_GET_SIZE(paramflags); + if (len != PyTuple_GET_SIZE(dict->argtypes)) { + PyErr_SetString(PyExc_ValueError, + "paramflags must have the same length as argtypes"); + return 0; + } + + for (i = 0; i < len; ++i) { + PyObject *item = PyTuple_GET_ITEM(paramflags, i); + int flag; + char *name; + PyObject *defval; + PyObject *typ; + if (!PyArg_ParseTuple(item, "i|ZO", &flag, &name, &defval)) { + PyErr_SetString(PyExc_TypeError, + "paramflags must be a sequence of (int [,string [,value]]) tuples"); + return 0; + } + typ = PyTuple_GET_ITEM(argtypes, i); + switch (flag & (PARAMFLAG_FIN | PARAMFLAG_FOUT | PARAMFLAG_FLCID)) { + case 0: + case PARAMFLAG_FIN: + case PARAMFLAG_FIN | PARAMFLAG_FLCID: + case PARAMFLAG_FIN | PARAMFLAG_FOUT: + break; + case PARAMFLAG_FOUT: + if (!_check_outarg_type(typ, i+1)) + return 0; + break; + default: + PyErr_Format(PyExc_TypeError, + "paramflag value %d not supported", + flag); + return 0; + } + } + return 1; } static int _get_name(PyObject *obj, char **pname) { #ifdef MS_WIN32 - if (PyLong_Check(obj)) { - /* We have to use MAKEINTRESOURCEA for Windows CE. - Works on Windows as well, of course. - */ - *pname = MAKEINTRESOURCEA(PyLong_AsUnsignedLongMask(obj) & 0xFFFF); - return 1; - } + if (PyLong_Check(obj)) { + /* We have to use MAKEINTRESOURCEA for Windows CE. + Works on Windows as well, of course. + */ + *pname = MAKEINTRESOURCEA(PyLong_AsUnsignedLongMask(obj) & 0xFFFF); + return 1; + } #endif - if (PyBytes_Check(obj)) { - *pname = PyBytes_AS_STRING(obj); - return *pname ? 1 : 0; - } - if (PyUnicode_Check(obj)) { - *pname = _PyUnicode_AsString(obj); - return *pname ? 1 : 0; - } - PyErr_SetString(PyExc_TypeError, - "function name must be string or integer"); - return 0; + if (PyBytes_Check(obj)) { + *pname = PyBytes_AS_STRING(obj); + return *pname ? 1 : 0; + } + if (PyUnicode_Check(obj)) { + *pname = _PyUnicode_AsString(obj); + return *pname ? 1 : 0; + } + PyErr_SetString(PyExc_TypeError, + "function name must be string or integer"); + return 0; } static PyObject * PyCFuncPtr_FromDll(PyTypeObject *type, PyObject *args, PyObject *kwds) { - char *name; - int (* address)(void); - PyObject *dll; - PyObject *obj; - PyCFuncPtrObject *self; - void *handle; - PyObject *paramflags = NULL; - - if (!PyArg_ParseTuple(args, "(O&O)|O", _get_name, &name, &dll, ¶mflags)) - return NULL; - if (paramflags == Py_None) - paramflags = NULL; - - obj = PyObject_GetAttrString(dll, "_handle"); - if (!obj) - return NULL; - if (!PyLong_Check(obj)) { - PyErr_SetString(PyExc_TypeError, - "the _handle attribute of the second argument must be an integer"); - Py_DECREF(obj); - return NULL; - } - handle = (void *)PyLong_AsVoidPtr(obj); - Py_DECREF(obj); - if (PyErr_Occurred()) { - PyErr_SetString(PyExc_ValueError, - "could not convert the _handle attribute to a pointer"); - return NULL; - } + char *name; + int (* address)(void); + PyObject *dll; + PyObject *obj; + PyCFuncPtrObject *self; + void *handle; + PyObject *paramflags = NULL; + + if (!PyArg_ParseTuple(args, "(O&O)|O", _get_name, &name, &dll, ¶mflags)) + return NULL; + if (paramflags == Py_None) + paramflags = NULL; + + obj = PyObject_GetAttrString(dll, "_handle"); + if (!obj) + return NULL; + if (!PyLong_Check(obj)) { + PyErr_SetString(PyExc_TypeError, + "the _handle attribute of the second argument must be an integer"); + Py_DECREF(obj); + return NULL; + } + handle = (void *)PyLong_AsVoidPtr(obj); + Py_DECREF(obj); + if (PyErr_Occurred()) { + PyErr_SetString(PyExc_ValueError, + "could not convert the _handle attribute to a pointer"); + return NULL; + } #ifdef MS_WIN32 - address = FindAddress(handle, name, (PyObject *)type); - if (!address) { - if (!IS_INTRESOURCE(name)) - PyErr_Format(PyExc_AttributeError, - "function '%s' not found", - name); - else - PyErr_Format(PyExc_AttributeError, - "function ordinal %d not found", - (WORD)(size_t)name); - return NULL; - } + address = FindAddress(handle, name, (PyObject *)type); + if (!address) { + if (!IS_INTRESOURCE(name)) + PyErr_Format(PyExc_AttributeError, + "function '%s' not found", + name); + else + PyErr_Format(PyExc_AttributeError, + "function ordinal %d not found", + (WORD)(size_t)name); + return NULL; + } #else - address = (PPROC)ctypes_dlsym(handle, name); - if (!address) { + address = (PPROC)ctypes_dlsym(handle, name); + if (!address) { #ifdef __CYGWIN__ /* dlerror() isn't very helpful on cygwin */ - PyErr_Format(PyExc_AttributeError, - "function '%s' not found (%s) ", - name); + PyErr_Format(PyExc_AttributeError, + "function '%s' not found (%s) ", + name); #else - PyErr_SetString(PyExc_AttributeError, ctypes_dlerror()); + PyErr_SetString(PyExc_AttributeError, ctypes_dlerror()); #endif - return NULL; - } + return NULL; + } #endif - if (!_validate_paramflags(type, paramflags)) - return NULL; + if (!_validate_paramflags(type, paramflags)) + return NULL; - self = (PyCFuncPtrObject *)GenericPyCData_new(type, args, kwds); - if (!self) - return NULL; - - Py_XINCREF(paramflags); - self->paramflags = paramflags; - - *(void **)self->b_ptr = address; - - Py_INCREF((PyObject *)dll); /* for KeepRef */ - if (-1 == KeepRef((CDataObject *)self, 0, dll)) { - Py_DECREF((PyObject *)self); - return NULL; - } - - Py_INCREF(self); - self->callable = (PyObject *)self; - return (PyObject *)self; + self = (PyCFuncPtrObject *)GenericPyCData_new(type, args, kwds); + if (!self) + return NULL; + + Py_XINCREF(paramflags); + self->paramflags = paramflags; + + *(void **)self->b_ptr = address; + + Py_INCREF((PyObject *)dll); /* for KeepRef */ + if (-1 == KeepRef((CDataObject *)self, 0, dll)) { + Py_DECREF((PyObject *)self); + return NULL; + } + + Py_INCREF(self); + self->callable = (PyObject *)self; + return (PyObject *)self; } #ifdef MS_WIN32 static PyObject * PyCFuncPtr_FromVtblIndex(PyTypeObject *type, PyObject *args, PyObject *kwds) { - PyCFuncPtrObject *self; - int index; - char *name = NULL; - PyObject *paramflags = NULL; - GUID *iid = NULL; - Py_ssize_t iid_len = 0; - - if (!PyArg_ParseTuple(args, "is|Oz#", &index, &name, ¶mflags, &iid, &iid_len)) - return NULL; - if (paramflags == Py_None) - paramflags = NULL; - - if (!_validate_paramflags(type, paramflags)) - return NULL; - - self = (PyCFuncPtrObject *)GenericPyCData_new(type, args, kwds); - self->index = index + 0x1000; - Py_XINCREF(paramflags); - self->paramflags = paramflags; - if (iid_len == sizeof(GUID)) - self->iid = iid; - return (PyObject *)self; + PyCFuncPtrObject *self; + int index; + char *name = NULL; + PyObject *paramflags = NULL; + GUID *iid = NULL; + Py_ssize_t iid_len = 0; + + if (!PyArg_ParseTuple(args, "is|Oz#", &index, &name, ¶mflags, &iid, &iid_len)) + return NULL; + if (paramflags == Py_None) + paramflags = NULL; + + if (!_validate_paramflags(type, paramflags)) + return NULL; + + self = (PyCFuncPtrObject *)GenericPyCData_new(type, args, kwds); + self->index = index + 0x1000; + Py_XINCREF(paramflags); + self->paramflags = paramflags; + if (iid_len == sizeof(GUID)) + self->iid = iid; + return (PyObject *)self; } #endif @@ -3291,90 +3291,90 @@ static PyObject * PyCFuncPtr_new(PyTypeObject *type, PyObject *args, PyObject *kwds) { - PyCFuncPtrObject *self; - PyObject *callable; - StgDictObject *dict; - CThunkObject *thunk; + PyCFuncPtrObject *self; + PyObject *callable; + StgDictObject *dict; + CThunkObject *thunk; - if (PyTuple_GET_SIZE(args) == 0) - return GenericPyCData_new(type, args, kwds); + if (PyTuple_GET_SIZE(args) == 0) + return GenericPyCData_new(type, args, kwds); - if (1 <= PyTuple_GET_SIZE(args) && PyTuple_Check(PyTuple_GET_ITEM(args, 0))) - return PyCFuncPtr_FromDll(type, args, kwds); + if (1 <= PyTuple_GET_SIZE(args) && PyTuple_Check(PyTuple_GET_ITEM(args, 0))) + return PyCFuncPtr_FromDll(type, args, kwds); #ifdef MS_WIN32 - if (2 <= PyTuple_GET_SIZE(args) && PyLong_Check(PyTuple_GET_ITEM(args, 0))) - return PyCFuncPtr_FromVtblIndex(type, args, kwds); + if (2 <= PyTuple_GET_SIZE(args) && PyLong_Check(PyTuple_GET_ITEM(args, 0))) + return PyCFuncPtr_FromVtblIndex(type, args, kwds); #endif - if (1 == PyTuple_GET_SIZE(args) - && (PyLong_Check(PyTuple_GET_ITEM(args, 0)))) { - CDataObject *ob; - void *ptr = PyLong_AsVoidPtr(PyTuple_GET_ITEM(args, 0)); - if (ptr == NULL && PyErr_Occurred()) - return NULL; - ob = (CDataObject *)GenericPyCData_new(type, args, kwds); - if (ob == NULL) - return NULL; - *(void **)ob->b_ptr = ptr; - return (PyObject *)ob; - } - - if (!PyArg_ParseTuple(args, "O", &callable)) - return NULL; - if (!PyCallable_Check(callable)) { - PyErr_SetString(PyExc_TypeError, - "argument must be callable or integer function address"); - return NULL; - } - - /* XXX XXX This would allow to pass additional options. For COM - method *implementations*, we would probably want different - behaviour than in 'normal' callback functions: return a HRESULT if - an exception occurrs in the callback, and print the traceback not - only on the console, but also to OutputDebugString() or something - like that. - */ + if (1 == PyTuple_GET_SIZE(args) + && (PyLong_Check(PyTuple_GET_ITEM(args, 0)))) { + CDataObject *ob; + void *ptr = PyLong_AsVoidPtr(PyTuple_GET_ITEM(args, 0)); + if (ptr == NULL && PyErr_Occurred()) + return NULL; + ob = (CDataObject *)GenericPyCData_new(type, args, kwds); + if (ob == NULL) + return NULL; + *(void **)ob->b_ptr = ptr; + return (PyObject *)ob; + } + + if (!PyArg_ParseTuple(args, "O", &callable)) + return NULL; + if (!PyCallable_Check(callable)) { + PyErr_SetString(PyExc_TypeError, + "argument must be callable or integer function address"); + return NULL; + } + + /* XXX XXX This would allow to pass additional options. For COM + method *implementations*, we would probably want different + behaviour than in 'normal' callback functions: return a HRESULT if + an exception occurrs in the callback, and print the traceback not + only on the console, but also to OutputDebugString() or something + like that. + */ /* - if (kwds && PyDict_GetItemString(kwds, "options")) { - ... - } + if (kwds && PyDict_GetItemString(kwds, "options")) { + ... + } */ - dict = PyType_stgdict((PyObject *)type); - /* XXXX Fails if we do: 'PyCFuncPtr(lambda x: x)' */ - if (!dict || !dict->argtypes) { - PyErr_SetString(PyExc_TypeError, - "cannot construct instance of this class:" - " no argtypes"); - return NULL; - } - - thunk = _ctypes_alloc_callback(callable, - dict->argtypes, - dict->restype, - dict->flags); - if (!thunk) - return NULL; - - self = (PyCFuncPtrObject *)GenericPyCData_new(type, args, kwds); - if (self == NULL) { - Py_DECREF(thunk); - return NULL; - } - - Py_INCREF(callable); - self->callable = callable; - - self->thunk = thunk; - *(void **)self->b_ptr = (void *)thunk->pcl; - - Py_INCREF((PyObject *)thunk); /* for KeepRef */ - if (-1 == KeepRef((CDataObject *)self, 0, (PyObject *)thunk)) { - Py_DECREF((PyObject *)self); - return NULL; - } - return (PyObject *)self; + dict = PyType_stgdict((PyObject *)type); + /* XXXX Fails if we do: 'PyCFuncPtr(lambda x: x)' */ + if (!dict || !dict->argtypes) { + PyErr_SetString(PyExc_TypeError, + "cannot construct instance of this class:" + " no argtypes"); + return NULL; + } + + thunk = _ctypes_alloc_callback(callable, + dict->argtypes, + dict->restype, + dict->flags); + if (!thunk) + return NULL; + + self = (PyCFuncPtrObject *)GenericPyCData_new(type, args, kwds); + if (self == NULL) { + Py_DECREF(thunk); + return NULL; + } + + Py_INCREF(callable); + self->callable = callable; + + self->thunk = thunk; + *(void **)self->b_ptr = (void *)thunk->pcl; + + Py_INCREF((PyObject *)thunk); /* for KeepRef */ + if (-1 == KeepRef((CDataObject *)self, 0, (PyObject *)thunk)) { + Py_DECREF((PyObject *)self); + return NULL; + } + return (PyObject *)self; } @@ -3384,54 +3384,54 @@ static PyObject * _byref(PyObject *obj) { - PyCArgObject *parg; - if (!CDataObject_Check(obj)) { - PyErr_SetString(PyExc_TypeError, - "expected CData instance"); - return NULL; - } - - parg = PyCArgObject_new(); - if (parg == NULL) { - Py_DECREF(obj); - return NULL; - } - - parg->tag = 'P'; - parg->pffi_type = &ffi_type_pointer; - parg->obj = obj; - parg->value.p = ((CDataObject *)obj)->b_ptr; - return (PyObject *)parg; + PyCArgObject *parg; + if (!CDataObject_Check(obj)) { + PyErr_SetString(PyExc_TypeError, + "expected CData instance"); + return NULL; + } + + parg = PyCArgObject_new(); + if (parg == NULL) { + Py_DECREF(obj); + return NULL; + } + + parg->tag = 'P'; + parg->pffi_type = &ffi_type_pointer; + parg->obj = obj; + parg->value.p = ((CDataObject *)obj)->b_ptr; + return (PyObject *)parg; } static PyObject * _get_arg(int *pindex, PyObject *name, PyObject *defval, PyObject *inargs, PyObject *kwds) { - PyObject *v; + PyObject *v; - if (*pindex < PyTuple_GET_SIZE(inargs)) { - v = PyTuple_GET_ITEM(inargs, *pindex); - ++*pindex; - Py_INCREF(v); - return v; - } - if (kwds && (v = PyDict_GetItem(kwds, name))) { - ++*pindex; - Py_INCREF(v); - return v; - } - if (defval) { - Py_INCREF(defval); - return defval; - } - /* we can't currently emit a better error message */ - if (name) - PyErr_Format(PyExc_TypeError, - "required argument '%S' missing", name); - else - PyErr_Format(PyExc_TypeError, - "not enough arguments"); - return NULL; + if (*pindex < PyTuple_GET_SIZE(inargs)) { + v = PyTuple_GET_ITEM(inargs, *pindex); + ++*pindex; + Py_INCREF(v); + return v; + } + if (kwds && (v = PyDict_GetItem(kwds, name))) { + ++*pindex; + Py_INCREF(v); + return v; + } + if (defval) { + Py_INCREF(defval); + return defval; + } + /* we can't currently emit a better error message */ + if (name) + PyErr_Format(PyExc_TypeError, + "required argument '%S' missing", name); + else + PyErr_Format(PyExc_TypeError, + "not enough arguments"); + return NULL; } /* @@ -3454,166 +3454,166 @@ */ static PyObject * _build_callargs(PyCFuncPtrObject *self, PyObject *argtypes, - PyObject *inargs, PyObject *kwds, - int *poutmask, int *pinoutmask, unsigned int *pnumretvals) + PyObject *inargs, PyObject *kwds, + int *poutmask, int *pinoutmask, unsigned int *pnumretvals) { - PyObject *paramflags = self->paramflags; - PyObject *callargs; - StgDictObject *dict; - Py_ssize_t i, len; - int inargs_index = 0; - /* It's a little bit difficult to determine how many arguments the - function call requires/accepts. For simplicity, we count the consumed - args and compare this to the number of supplied args. */ - Py_ssize_t actual_args; - - *poutmask = 0; - *pinoutmask = 0; - *pnumretvals = 0; + PyObject *paramflags = self->paramflags; + PyObject *callargs; + StgDictObject *dict; + Py_ssize_t i, len; + int inargs_index = 0; + /* It's a little bit difficult to determine how many arguments the + function call requires/accepts. For simplicity, we count the consumed + args and compare this to the number of supplied args. */ + Py_ssize_t actual_args; + + *poutmask = 0; + *pinoutmask = 0; + *pnumretvals = 0; - /* Trivial cases, where we either return inargs itself, or a slice of it. */ - if (argtypes == NULL || paramflags == NULL || PyTuple_GET_SIZE(argtypes) == 0) { + /* Trivial cases, where we either return inargs itself, or a slice of it. */ + if (argtypes == NULL || paramflags == NULL || PyTuple_GET_SIZE(argtypes) == 0) { #ifdef MS_WIN32 - if (self->index) - return PyTuple_GetSlice(inargs, 1, PyTuple_GET_SIZE(inargs)); + if (self->index) + return PyTuple_GetSlice(inargs, 1, PyTuple_GET_SIZE(inargs)); #endif - Py_INCREF(inargs); - return inargs; - } - - len = PyTuple_GET_SIZE(argtypes); - callargs = PyTuple_New(len); /* the argument tuple we build */ - if (callargs == NULL) - return NULL; + Py_INCREF(inargs); + return inargs; + } + + len = PyTuple_GET_SIZE(argtypes); + callargs = PyTuple_New(len); /* the argument tuple we build */ + if (callargs == NULL) + return NULL; #ifdef MS_WIN32 - /* For a COM method, skip the first arg */ - if (self->index) { - inargs_index = 1; - } + /* For a COM method, skip the first arg */ + if (self->index) { + inargs_index = 1; + } #endif - for (i = 0; i < len; ++i) { - PyObject *item = PyTuple_GET_ITEM(paramflags, i); - PyObject *ob; - int flag; - PyObject *name = NULL; - PyObject *defval = NULL; - - /* This way seems to be ~2 us faster than the PyArg_ParseTuple - calls below. */ - /* We HAVE already checked that the tuple can be parsed with "i|ZO", so... */ - Py_ssize_t tsize = PyTuple_GET_SIZE(item); - flag = PyLong_AS_LONG(PyTuple_GET_ITEM(item, 0)); - name = tsize > 1 ? PyTuple_GET_ITEM(item, 1) : NULL; - defval = tsize > 2 ? PyTuple_GET_ITEM(item, 2) : NULL; - - switch (flag & (PARAMFLAG_FIN | PARAMFLAG_FOUT | PARAMFLAG_FLCID)) { - case PARAMFLAG_FIN | PARAMFLAG_FLCID: - /* ['in', 'lcid'] parameter. Always taken from defval, - if given, else the integer 0. */ - if (defval == NULL) { - defval = PyLong_FromLong(0); - if (defval == NULL) - goto error; - } else - Py_INCREF(defval); - PyTuple_SET_ITEM(callargs, i, defval); - break; - case (PARAMFLAG_FIN | PARAMFLAG_FOUT): - *pinoutmask |= (1 << i); /* mark as inout arg */ - (*pnumretvals)++; - /* fall through to PARAMFLAG_FIN... */ - case 0: - case PARAMFLAG_FIN: - /* 'in' parameter. Copy it from inargs. */ - ob =_get_arg(&inargs_index, name, defval, inargs, kwds); - if (ob == NULL) - goto error; - PyTuple_SET_ITEM(callargs, i, ob); - break; - case PARAMFLAG_FOUT: - /* XXX Refactor this code into a separate function. */ - /* 'out' parameter. - argtypes[i] must be a POINTER to a c type. - - Cannot by supplied in inargs, but a defval will be used - if available. XXX Should we support getting it from kwds? - */ - if (defval) { - /* XXX Using mutable objects as defval will - make the function non-threadsafe, unless we - copy the object in each invocation */ - Py_INCREF(defval); - PyTuple_SET_ITEM(callargs, i, defval); - *poutmask |= (1 << i); /* mark as out arg */ - (*pnumretvals)++; - break; - } - ob = PyTuple_GET_ITEM(argtypes, i); - dict = PyType_stgdict(ob); - if (dict == NULL) { - /* Cannot happen: _validate_paramflags() - would not accept such an object */ - PyErr_Format(PyExc_RuntimeError, - "NULL stgdict unexpected"); - goto error; - } - if (PyUnicode_Check(dict->proto)) { - PyErr_Format( - PyExc_TypeError, - "%s 'out' parameter must be passed as default value", - ((PyTypeObject *)ob)->tp_name); - goto error; - } - if (PyCArrayTypeObject_Check(ob)) - ob = PyObject_CallObject(ob, NULL); - else - /* Create an instance of the pointed-to type */ - ob = PyObject_CallObject(dict->proto, NULL); - /* - XXX Is the following correct any longer? - We must not pass a byref() to the array then but - the array instance itself. Then, we cannot retrive - the result from the PyCArgObject. - */ - if (ob == NULL) - goto error; - /* The .from_param call that will ocurr later will pass this - as a byref parameter. */ - PyTuple_SET_ITEM(callargs, i, ob); - *poutmask |= (1 << i); /* mark as out arg */ - (*pnumretvals)++; - break; - default: - PyErr_Format(PyExc_ValueError, - "paramflag %d not yet implemented", flag); - goto error; - break; - } - } - - /* We have counted the arguments we have consumed in 'inargs_index'. This - must be the same as len(inargs) + len(kwds), otherwise we have - either too much or not enough arguments. */ - - actual_args = PyTuple_GET_SIZE(inargs) + (kwds ? PyDict_Size(kwds) : 0); - if (actual_args != inargs_index) { - /* When we have default values or named parameters, this error - message is misleading. See unittests/test_paramflags.py - */ - PyErr_Format(PyExc_TypeError, - "call takes exactly %d arguments (%zd given)", - inargs_index, actual_args); - goto error; - } - - /* outmask is a bitmask containing indexes into callargs. Items at - these indexes contain values to return. - */ - return callargs; + for (i = 0; i < len; ++i) { + PyObject *item = PyTuple_GET_ITEM(paramflags, i); + PyObject *ob; + int flag; + PyObject *name = NULL; + PyObject *defval = NULL; + + /* This way seems to be ~2 us faster than the PyArg_ParseTuple + calls below. */ + /* We HAVE already checked that the tuple can be parsed with "i|ZO", so... */ + Py_ssize_t tsize = PyTuple_GET_SIZE(item); + flag = PyLong_AS_LONG(PyTuple_GET_ITEM(item, 0)); + name = tsize > 1 ? PyTuple_GET_ITEM(item, 1) : NULL; + defval = tsize > 2 ? PyTuple_GET_ITEM(item, 2) : NULL; + + switch (flag & (PARAMFLAG_FIN | PARAMFLAG_FOUT | PARAMFLAG_FLCID)) { + case PARAMFLAG_FIN | PARAMFLAG_FLCID: + /* ['in', 'lcid'] parameter. Always taken from defval, + if given, else the integer 0. */ + if (defval == NULL) { + defval = PyLong_FromLong(0); + if (defval == NULL) + goto error; + } else + Py_INCREF(defval); + PyTuple_SET_ITEM(callargs, i, defval); + break; + case (PARAMFLAG_FIN | PARAMFLAG_FOUT): + *pinoutmask |= (1 << i); /* mark as inout arg */ + (*pnumretvals)++; + /* fall through to PARAMFLAG_FIN... */ + case 0: + case PARAMFLAG_FIN: + /* 'in' parameter. Copy it from inargs. */ + ob =_get_arg(&inargs_index, name, defval, inargs, kwds); + if (ob == NULL) + goto error; + PyTuple_SET_ITEM(callargs, i, ob); + break; + case PARAMFLAG_FOUT: + /* XXX Refactor this code into a separate function. */ + /* 'out' parameter. + argtypes[i] must be a POINTER to a c type. + + Cannot by supplied in inargs, but a defval will be used + if available. XXX Should we support getting it from kwds? + */ + if (defval) { + /* XXX Using mutable objects as defval will + make the function non-threadsafe, unless we + copy the object in each invocation */ + Py_INCREF(defval); + PyTuple_SET_ITEM(callargs, i, defval); + *poutmask |= (1 << i); /* mark as out arg */ + (*pnumretvals)++; + break; + } + ob = PyTuple_GET_ITEM(argtypes, i); + dict = PyType_stgdict(ob); + if (dict == NULL) { + /* Cannot happen: _validate_paramflags() + would not accept such an object */ + PyErr_Format(PyExc_RuntimeError, + "NULL stgdict unexpected"); + goto error; + } + if (PyUnicode_Check(dict->proto)) { + PyErr_Format( + PyExc_TypeError, + "%s 'out' parameter must be passed as default value", + ((PyTypeObject *)ob)->tp_name); + goto error; + } + if (PyCArrayTypeObject_Check(ob)) + ob = PyObject_CallObject(ob, NULL); + else + /* Create an instance of the pointed-to type */ + ob = PyObject_CallObject(dict->proto, NULL); + /* + XXX Is the following correct any longer? + We must not pass a byref() to the array then but + the array instance itself. Then, we cannot retrive + the result from the PyCArgObject. + */ + if (ob == NULL) + goto error; + /* The .from_param call that will ocurr later will pass this + as a byref parameter. */ + PyTuple_SET_ITEM(callargs, i, ob); + *poutmask |= (1 << i); /* mark as out arg */ + (*pnumretvals)++; + break; + default: + PyErr_Format(PyExc_ValueError, + "paramflag %d not yet implemented", flag); + goto error; + break; + } + } + + /* We have counted the arguments we have consumed in 'inargs_index'. This + must be the same as len(inargs) + len(kwds), otherwise we have + either too much or not enough arguments. */ + + actual_args = PyTuple_GET_SIZE(inargs) + (kwds ? PyDict_Size(kwds) : 0); + if (actual_args != inargs_index) { + /* When we have default values or named parameters, this error + message is misleading. See unittests/test_paramflags.py + */ + PyErr_Format(PyExc_TypeError, + "call takes exactly %d arguments (%zd given)", + inargs_index, actual_args); + goto error; + } + + /* outmask is a bitmask containing indexes into callargs. Items at + these indexes contain values to return. + */ + return callargs; error: - Py_DECREF(callargs); - return NULL; + Py_DECREF(callargs); + return NULL; } /* See also: @@ -3626,307 +3626,307 @@ */ static PyObject * _build_result(PyObject *result, PyObject *callargs, - int outmask, int inoutmask, unsigned int numretvals) + int outmask, int inoutmask, unsigned int numretvals) { - unsigned int i, index; - int bit; - PyObject *tup = NULL; - - if (callargs == NULL) - return result; - if (result == NULL || numretvals == 0) { - Py_DECREF(callargs); - return result; - } - Py_DECREF(result); - - /* tup will not be allocated if numretvals == 1 */ - /* allocate tuple to hold the result */ - if (numretvals > 1) { - tup = PyTuple_New(numretvals); - if (tup == NULL) { - Py_DECREF(callargs); - return NULL; - } - } - - index = 0; - for (bit = 1, i = 0; i < 32; ++i, bit <<= 1) { - PyObject *v; - if (bit & inoutmask) { - v = PyTuple_GET_ITEM(callargs, i); - Py_INCREF(v); - if (numretvals == 1) { - Py_DECREF(callargs); - return v; - } - PyTuple_SET_ITEM(tup, index, v); - index++; - } else if (bit & outmask) { - v = PyTuple_GET_ITEM(callargs, i); - v = PyObject_CallMethod(v, "__ctypes_from_outparam__", NULL); - if (v == NULL || numretvals == 1) { - Py_DECREF(callargs); - return v; - } - PyTuple_SET_ITEM(tup, index, v); - index++; - } - if (index == numretvals) - break; - } + unsigned int i, index; + int bit; + PyObject *tup = NULL; + + if (callargs == NULL) + return result; + if (result == NULL || numretvals == 0) { + Py_DECREF(callargs); + return result; + } + Py_DECREF(result); + + /* tup will not be allocated if numretvals == 1 */ + /* allocate tuple to hold the result */ + if (numretvals > 1) { + tup = PyTuple_New(numretvals); + if (tup == NULL) { + Py_DECREF(callargs); + return NULL; + } + } + + index = 0; + for (bit = 1, i = 0; i < 32; ++i, bit <<= 1) { + PyObject *v; + if (bit & inoutmask) { + v = PyTuple_GET_ITEM(callargs, i); + Py_INCREF(v); + if (numretvals == 1) { + Py_DECREF(callargs); + return v; + } + PyTuple_SET_ITEM(tup, index, v); + index++; + } else if (bit & outmask) { + v = PyTuple_GET_ITEM(callargs, i); + v = PyObject_CallMethod(v, "__ctypes_from_outparam__", NULL); + if (v == NULL || numretvals == 1) { + Py_DECREF(callargs); + return v; + } + PyTuple_SET_ITEM(tup, index, v); + index++; + } + if (index == numretvals) + break; + } - Py_DECREF(callargs); - return tup; + Py_DECREF(callargs); + return tup; } static PyObject * PyCFuncPtr_call(PyCFuncPtrObject *self, PyObject *inargs, PyObject *kwds) { - PyObject *restype; - PyObject *converters; - PyObject *checker; - PyObject *argtypes; - StgDictObject *dict = PyObject_stgdict((PyObject *)self); - PyObject *result; - PyObject *callargs; - PyObject *errcheck; + PyObject *restype; + PyObject *converters; + PyObject *checker; + PyObject *argtypes; + StgDictObject *dict = PyObject_stgdict((PyObject *)self); + PyObject *result; + PyObject *callargs; + PyObject *errcheck; #ifdef MS_WIN32 - IUnknown *piunk = NULL; + IUnknown *piunk = NULL; #endif - void *pProc = NULL; + void *pProc = NULL; - int inoutmask; - int outmask; - unsigned int numretvals; - - assert(dict); /* Cannot be NULL for PyCFuncPtrObject instances */ - restype = self->restype ? self->restype : dict->restype; - converters = self->converters ? self->converters : dict->converters; - checker = self->checker ? self->checker : dict->checker; - argtypes = self->argtypes ? self->argtypes : dict->argtypes; + int inoutmask; + int outmask; + unsigned int numretvals; + + assert(dict); /* Cannot be NULL for PyCFuncPtrObject instances */ + restype = self->restype ? self->restype : dict->restype; + converters = self->converters ? self->converters : dict->converters; + checker = self->checker ? self->checker : dict->checker; + argtypes = self->argtypes ? self->argtypes : dict->argtypes; /* later, we probably want to have an errcheck field in stgdict */ - errcheck = self->errcheck /* ? self->errcheck : dict->errcheck */; + errcheck = self->errcheck /* ? self->errcheck : dict->errcheck */; - pProc = *(void **)self->b_ptr; + pProc = *(void **)self->b_ptr; #ifdef MS_WIN32 - if (self->index) { - /* It's a COM method */ - CDataObject *this; - this = (CDataObject *)PyTuple_GetItem(inargs, 0); /* borrowed ref! */ - if (!this) { - PyErr_SetString(PyExc_ValueError, - "native com method call without 'this' parameter"); - return NULL; - } - if (!CDataObject_Check(this)) { - PyErr_SetString(PyExc_TypeError, - "Expected a COM this pointer as first argument"); - return NULL; - } - /* there should be more checks? No, in Python */ - /* First arg is an pointer to an interface instance */ - if (!this->b_ptr || *(void **)this->b_ptr == NULL) { - PyErr_SetString(PyExc_ValueError, - "NULL COM pointer access"); - return NULL; - } - piunk = *(IUnknown **)this->b_ptr; - if (NULL == piunk->lpVtbl) { - PyErr_SetString(PyExc_ValueError, - "COM method call without VTable"); - return NULL; - } - pProc = ((void **)piunk->lpVtbl)[self->index - 0x1000]; - } + if (self->index) { + /* It's a COM method */ + CDataObject *this; + this = (CDataObject *)PyTuple_GetItem(inargs, 0); /* borrowed ref! */ + if (!this) { + PyErr_SetString(PyExc_ValueError, + "native com method call without 'this' parameter"); + return NULL; + } + if (!CDataObject_Check(this)) { + PyErr_SetString(PyExc_TypeError, + "Expected a COM this pointer as first argument"); + return NULL; + } + /* there should be more checks? No, in Python */ + /* First arg is an pointer to an interface instance */ + if (!this->b_ptr || *(void **)this->b_ptr == NULL) { + PyErr_SetString(PyExc_ValueError, + "NULL COM pointer access"); + return NULL; + } + piunk = *(IUnknown **)this->b_ptr; + if (NULL == piunk->lpVtbl) { + PyErr_SetString(PyExc_ValueError, + "COM method call without VTable"); + return NULL; + } + pProc = ((void **)piunk->lpVtbl)[self->index - 0x1000]; + } #endif - callargs = _build_callargs(self, argtypes, - inargs, kwds, - &outmask, &inoutmask, &numretvals); - if (callargs == NULL) - return NULL; - - if (converters) { - int required = Py_SAFE_DOWNCAST(PyTuple_GET_SIZE(converters), - Py_ssize_t, int); - int actual = Py_SAFE_DOWNCAST(PyTuple_GET_SIZE(callargs), - Py_ssize_t, int); - - if ((dict->flags & FUNCFLAG_CDECL) == FUNCFLAG_CDECL) { - /* For cdecl functions, we allow more actual arguments - than the length of the argtypes tuple. - */ - if (required > actual) { - Py_DECREF(callargs); - PyErr_Format(PyExc_TypeError, - "this function takes at least %d argument%s (%d given)", - required, - required == 1 ? "" : "s", - actual); - return NULL; - } - } else if (required != actual) { - Py_DECREF(callargs); - PyErr_Format(PyExc_TypeError, - "this function takes %d argument%s (%d given)", - required, - required == 1 ? "" : "s", - actual); - return NULL; - } - } + callargs = _build_callargs(self, argtypes, + inargs, kwds, + &outmask, &inoutmask, &numretvals); + if (callargs == NULL) + return NULL; + + if (converters) { + int required = Py_SAFE_DOWNCAST(PyTuple_GET_SIZE(converters), + Py_ssize_t, int); + int actual = Py_SAFE_DOWNCAST(PyTuple_GET_SIZE(callargs), + Py_ssize_t, int); + + if ((dict->flags & FUNCFLAG_CDECL) == FUNCFLAG_CDECL) { + /* For cdecl functions, we allow more actual arguments + than the length of the argtypes tuple. + */ + if (required > actual) { + Py_DECREF(callargs); + PyErr_Format(PyExc_TypeError, + "this function takes at least %d argument%s (%d given)", + required, + required == 1 ? "" : "s", + actual); + return NULL; + } + } else if (required != actual) { + Py_DECREF(callargs); + PyErr_Format(PyExc_TypeError, + "this function takes %d argument%s (%d given)", + required, + required == 1 ? "" : "s", + actual); + return NULL; + } + } - result = _ctypes_callproc(pProc, - callargs, + result = _ctypes_callproc(pProc, + callargs, #ifdef MS_WIN32 - piunk, - self->iid, + piunk, + self->iid, #endif - dict->flags, - converters, - restype, - checker); + dict->flags, + converters, + restype, + checker); /* The 'errcheck' protocol */ - if (result != NULL && errcheck) { - PyObject *v = PyObject_CallFunctionObjArgs(errcheck, - result, - self, - callargs, - NULL); - /* If the errcheck funtion failed, return NULL. - If the errcheck function returned callargs unchanged, - continue normal processing. - If the errcheck function returned something else, - use that as result. - */ - if (v == NULL || v != callargs) { - Py_DECREF(result); - Py_DECREF(callargs); - return v; - } - Py_DECREF(v); - } + if (result != NULL && errcheck) { + PyObject *v = PyObject_CallFunctionObjArgs(errcheck, + result, + self, + callargs, + NULL); + /* If the errcheck funtion failed, return NULL. + If the errcheck function returned callargs unchanged, + continue normal processing. + If the errcheck function returned something else, + use that as result. + */ + if (v == NULL || v != callargs) { + Py_DECREF(result); + Py_DECREF(callargs); + return v; + } + Py_DECREF(v); + } - return _build_result(result, callargs, - outmask, inoutmask, numretvals); + return _build_result(result, callargs, + outmask, inoutmask, numretvals); } static int PyCFuncPtr_traverse(PyCFuncPtrObject *self, visitproc visit, void *arg) { - Py_VISIT(self->callable); - Py_VISIT(self->restype); - Py_VISIT(self->checker); - Py_VISIT(self->errcheck); - Py_VISIT(self->argtypes); - Py_VISIT(self->converters); - Py_VISIT(self->paramflags); - Py_VISIT(self->thunk); - return PyCData_traverse((CDataObject *)self, visit, arg); + Py_VISIT(self->callable); + Py_VISIT(self->restype); + Py_VISIT(self->checker); + Py_VISIT(self->errcheck); + Py_VISIT(self->argtypes); + Py_VISIT(self->converters); + Py_VISIT(self->paramflags); + Py_VISIT(self->thunk); + return PyCData_traverse((CDataObject *)self, visit, arg); } static int PyCFuncPtr_clear(PyCFuncPtrObject *self) { - Py_CLEAR(self->callable); - Py_CLEAR(self->restype); - Py_CLEAR(self->checker); - Py_CLEAR(self->errcheck); - Py_CLEAR(self->argtypes); - Py_CLEAR(self->converters); - Py_CLEAR(self->paramflags); - Py_CLEAR(self->thunk); - return PyCData_clear((CDataObject *)self); + Py_CLEAR(self->callable); + Py_CLEAR(self->restype); + Py_CLEAR(self->checker); + Py_CLEAR(self->errcheck); + Py_CLEAR(self->argtypes); + Py_CLEAR(self->converters); + Py_CLEAR(self->paramflags); + Py_CLEAR(self->thunk); + return PyCData_clear((CDataObject *)self); } static void PyCFuncPtr_dealloc(PyCFuncPtrObject *self) { - PyCFuncPtr_clear(self); - Py_TYPE(self)->tp_free((PyObject *)self); + PyCFuncPtr_clear(self); + Py_TYPE(self)->tp_free((PyObject *)self); } static PyObject * PyCFuncPtr_repr(PyCFuncPtrObject *self) { #ifdef MS_WIN32 - if (self->index) - return PyUnicode_FromFormat("", - self->index - 0x1000, - Py_TYPE(self)->tp_name, - self); + if (self->index) + return PyUnicode_FromFormat("", + self->index - 0x1000, + Py_TYPE(self)->tp_name, + self); #endif - return PyUnicode_FromFormat("<%s object at %p>", - Py_TYPE(self)->tp_name, - self); + return PyUnicode_FromFormat("<%s object at %p>", + Py_TYPE(self)->tp_name, + self); } static int PyCFuncPtr_bool(PyCFuncPtrObject *self) { - return ((*(void **)self->b_ptr != NULL) + return ((*(void **)self->b_ptr != NULL) #ifdef MS_WIN32 - || (self->index != 0) + || (self->index != 0) #endif - ); + ); } static PyNumberMethods PyCFuncPtr_as_number = { - 0, /* nb_add */ - 0, /* nb_subtract */ - 0, /* nb_multiply */ - 0, /* nb_remainder */ - 0, /* nb_divmod */ - 0, /* nb_power */ - 0, /* nb_negative */ - 0, /* nb_positive */ - 0, /* nb_absolute */ - (inquiry)PyCFuncPtr_bool, /* nb_bool */ + 0, /* nb_add */ + 0, /* nb_subtract */ + 0, /* nb_multiply */ + 0, /* nb_remainder */ + 0, /* nb_divmod */ + 0, /* nb_power */ + 0, /* nb_negative */ + 0, /* nb_positive */ + 0, /* nb_absolute */ + (inquiry)PyCFuncPtr_bool, /* nb_bool */ }; PyTypeObject PyCFuncPtr_Type = { - PyVarObject_HEAD_INIT(NULL, 0) - "_ctypes.PyCFuncPtr", - sizeof(PyCFuncPtrObject), /* tp_basicsize */ - 0, /* tp_itemsize */ - (destructor)PyCFuncPtr_dealloc, /* tp_dealloc */ - 0, /* tp_print */ - 0, /* tp_getattr */ - 0, /* tp_setattr */ - 0, /* tp_reserved */ - (reprfunc)PyCFuncPtr_repr, /* tp_repr */ - &PyCFuncPtr_as_number, /* tp_as_number */ - 0, /* tp_as_sequence */ - 0, /* tp_as_mapping */ - 0, /* tp_hash */ - (ternaryfunc)PyCFuncPtr_call, /* tp_call */ - 0, /* tp_str */ - 0, /* tp_getattro */ - 0, /* tp_setattro */ - &PyCData_as_buffer, /* tp_as_buffer */ - Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */ - "Function Pointer", /* tp_doc */ - (traverseproc)PyCFuncPtr_traverse, /* tp_traverse */ - (inquiry)PyCFuncPtr_clear, /* tp_clear */ - 0, /* tp_richcompare */ - 0, /* tp_weaklistoffset */ - 0, /* tp_iter */ - 0, /* tp_iternext */ - 0, /* tp_methods */ - 0, /* tp_members */ - PyCFuncPtr_getsets, /* tp_getset */ - 0, /* tp_base */ - 0, /* tp_dict */ - 0, /* tp_descr_get */ - 0, /* tp_descr_set */ - 0, /* tp_dictoffset */ - 0, /* tp_init */ - 0, /* tp_alloc */ - PyCFuncPtr_new, /* tp_new */ - 0, /* tp_free */ + PyVarObject_HEAD_INIT(NULL, 0) + "_ctypes.PyCFuncPtr", + sizeof(PyCFuncPtrObject), /* tp_basicsize */ + 0, /* tp_itemsize */ + (destructor)PyCFuncPtr_dealloc, /* tp_dealloc */ + 0, /* tp_print */ + 0, /* tp_getattr */ + 0, /* tp_setattr */ + 0, /* tp_reserved */ + (reprfunc)PyCFuncPtr_repr, /* tp_repr */ + &PyCFuncPtr_as_number, /* tp_as_number */ + 0, /* tp_as_sequence */ + 0, /* tp_as_mapping */ + 0, /* tp_hash */ + (ternaryfunc)PyCFuncPtr_call, /* tp_call */ + 0, /* tp_str */ + 0, /* tp_getattro */ + 0, /* tp_setattro */ + &PyCData_as_buffer, /* tp_as_buffer */ + Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */ + "Function Pointer", /* tp_doc */ + (traverseproc)PyCFuncPtr_traverse, /* tp_traverse */ + (inquiry)PyCFuncPtr_clear, /* tp_clear */ + 0, /* tp_richcompare */ + 0, /* tp_weaklistoffset */ + 0, /* tp_iter */ + 0, /* tp_iternext */ + 0, /* tp_methods */ + 0, /* tp_members */ + PyCFuncPtr_getsets, /* tp_getset */ + 0, /* tp_base */ + 0, /* tp_dict */ + 0, /* tp_descr_get */ + 0, /* tp_descr_set */ + 0, /* tp_dictoffset */ + 0, /* tp_init */ + 0, /* tp_alloc */ + PyCFuncPtr_new, /* tp_new */ + 0, /* tp_free */ }; - + /*****************************************************************/ /* Struct_Type @@ -3941,61 +3941,61 @@ */ static int _init_pos_args(PyObject *self, PyTypeObject *type, - PyObject *args, PyObject *kwds, - int index) + PyObject *args, PyObject *kwds, + int index) { - StgDictObject *dict; - PyObject *fields; - int i; - - if (PyType_stgdict((PyObject *)type->tp_base)) { - index = _init_pos_args(self, type->tp_base, - args, kwds, - index); - if (index == -1) - return -1; - } - - dict = PyType_stgdict((PyObject *)type); - fields = PyDict_GetItemString((PyObject *)dict, "_fields_"); - if (fields == NULL) - return index; - - for (i = 0; - i < dict->length && (i+index) < PyTuple_GET_SIZE(args); - ++i) { - PyObject *pair = PySequence_GetItem(fields, i); - PyObject *name, *val; - int res; - if (!pair) - return -1; - name = PySequence_GetItem(pair, 0); - if (!name) { - Py_DECREF(pair); - return -1; - } - val = PyTuple_GET_ITEM(args, i + index); - if (kwds && PyDict_GetItem(kwds, name)) { - char *field = PyBytes_AsString(name); - if (field == NULL) { - PyErr_Clear(); - field = "???"; - } - PyErr_Format(PyExc_TypeError, - "duplicate values for field '%s'", - field); - Py_DECREF(pair); - Py_DECREF(name); - return -1; - } - - res = PyObject_SetAttr(self, name, val); - Py_DECREF(pair); - Py_DECREF(name); - if (res == -1) - return -1; - } - return index + dict->length; + StgDictObject *dict; + PyObject *fields; + int i; + + if (PyType_stgdict((PyObject *)type->tp_base)) { + index = _init_pos_args(self, type->tp_base, + args, kwds, + index); + if (index == -1) + return -1; + } + + dict = PyType_stgdict((PyObject *)type); + fields = PyDict_GetItemString((PyObject *)dict, "_fields_"); + if (fields == NULL) + return index; + + for (i = 0; + i < dict->length && (i+index) < PyTuple_GET_SIZE(args); + ++i) { + PyObject *pair = PySequence_GetItem(fields, i); + PyObject *name, *val; + int res; + if (!pair) + return -1; + name = PySequence_GetItem(pair, 0); + if (!name) { + Py_DECREF(pair); + return -1; + } + val = PyTuple_GET_ITEM(args, i + index); + if (kwds && PyDict_GetItem(kwds, name)) { + char *field = PyBytes_AsString(name); + if (field == NULL) { + PyErr_Clear(); + field = "???"; + } + PyErr_Format(PyExc_TypeError, + "duplicate values for field '%s'", + field); + Py_DECREF(pair); + Py_DECREF(name); + return -1; + } + + res = PyObject_SetAttr(self, name, val); + Py_DECREF(pair); + Py_DECREF(name); + if (res == -1) + return -1; + } + return index + dict->length; } static int @@ -4004,119 +4004,119 @@ /* Optimization possible: Store the attribute names _fields_[x][0] * in C accessible fields somewhere ? */ - if (!PyTuple_Check(args)) { - PyErr_SetString(PyExc_TypeError, - "args not a tuple?"); - return -1; - } - if (PyTuple_GET_SIZE(args)) { - int res = _init_pos_args(self, Py_TYPE(self), - args, kwds, 0); - if (res == -1) - return -1; - if (res < PyTuple_GET_SIZE(args)) { - PyErr_SetString(PyExc_TypeError, - "too many initializers"); - return -1; - } - } - - if (kwds) { - PyObject *key, *value; - Py_ssize_t pos = 0; - while(PyDict_Next(kwds, &pos, &key, &value)) { - if (-1 == PyObject_SetAttr(self, key, value)) - return -1; - } - } - return 0; + if (!PyTuple_Check(args)) { + PyErr_SetString(PyExc_TypeError, + "args not a tuple?"); + return -1; + } + if (PyTuple_GET_SIZE(args)) { + int res = _init_pos_args(self, Py_TYPE(self), + args, kwds, 0); + if (res == -1) + return -1; + if (res < PyTuple_GET_SIZE(args)) { + PyErr_SetString(PyExc_TypeError, + "too many initializers"); + return -1; + } + } + + if (kwds) { + PyObject *key, *value; + Py_ssize_t pos = 0; + while(PyDict_Next(kwds, &pos, &key, &value)) { + if (-1 == PyObject_SetAttr(self, key, value)) + return -1; + } + } + return 0; } static PyTypeObject Struct_Type = { - PyVarObject_HEAD_INIT(NULL, 0) - "_ctypes.Structure", - sizeof(CDataObject), /* tp_basicsize */ - 0, /* tp_itemsize */ - 0, /* tp_dealloc */ - 0, /* tp_print */ - 0, /* tp_getattr */ - 0, /* tp_setattr */ - 0, /* tp_reserved */ - 0, /* tp_repr */ - 0, /* tp_as_number */ - 0, /* tp_as_sequence */ - 0, /* tp_as_mapping */ - 0, /* tp_hash */ - 0, /* tp_call */ - 0, /* tp_str */ - 0, /* tp_getattro */ - 0, /* tp_setattro */ - &PyCData_as_buffer, /* tp_as_buffer */ - Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */ - "Structure base class", /* tp_doc */ - (traverseproc)PyCData_traverse, /* tp_traverse */ - (inquiry)PyCData_clear, /* tp_clear */ - 0, /* tp_richcompare */ - 0, /* tp_weaklistoffset */ - 0, /* tp_iter */ - 0, /* tp_iternext */ - 0, /* tp_methods */ - 0, /* tp_members */ - 0, /* tp_getset */ - 0, /* tp_base */ - 0, /* tp_dict */ - 0, /* tp_descr_get */ - 0, /* tp_descr_set */ - 0, /* tp_dictoffset */ - Struct_init, /* tp_init */ - 0, /* tp_alloc */ - GenericPyCData_new, /* tp_new */ - 0, /* tp_free */ + PyVarObject_HEAD_INIT(NULL, 0) + "_ctypes.Structure", + sizeof(CDataObject), /* tp_basicsize */ + 0, /* tp_itemsize */ + 0, /* tp_dealloc */ + 0, /* tp_print */ + 0, /* tp_getattr */ + 0, /* tp_setattr */ + 0, /* tp_reserved */ + 0, /* tp_repr */ + 0, /* tp_as_number */ + 0, /* tp_as_sequence */ + 0, /* tp_as_mapping */ + 0, /* tp_hash */ + 0, /* tp_call */ + 0, /* tp_str */ + 0, /* tp_getattro */ + 0, /* tp_setattro */ + &PyCData_as_buffer, /* tp_as_buffer */ + Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */ + "Structure base class", /* tp_doc */ + (traverseproc)PyCData_traverse, /* tp_traverse */ + (inquiry)PyCData_clear, /* tp_clear */ + 0, /* tp_richcompare */ + 0, /* tp_weaklistoffset */ + 0, /* tp_iter */ + 0, /* tp_iternext */ + 0, /* tp_methods */ + 0, /* tp_members */ + 0, /* tp_getset */ + 0, /* tp_base */ + 0, /* tp_dict */ + 0, /* tp_descr_get */ + 0, /* tp_descr_set */ + 0, /* tp_dictoffset */ + Struct_init, /* tp_init */ + 0, /* tp_alloc */ + GenericPyCData_new, /* tp_new */ + 0, /* tp_free */ }; static PyTypeObject Union_Type = { - PyVarObject_HEAD_INIT(NULL, 0) - "_ctypes.Union", - sizeof(CDataObject), /* tp_basicsize */ - 0, /* tp_itemsize */ - 0, /* tp_dealloc */ - 0, /* tp_print */ - 0, /* tp_getattr */ - 0, /* tp_setattr */ - 0, /* tp_reserved */ - 0, /* tp_repr */ - 0, /* tp_as_number */ - 0, /* tp_as_sequence */ - 0, /* tp_as_mapping */ - 0, /* tp_hash */ - 0, /* tp_call */ - 0, /* tp_str */ - 0, /* tp_getattro */ - 0, /* tp_setattro */ - &PyCData_as_buffer, /* tp_as_buffer */ - Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */ - "Union base class", /* tp_doc */ - (traverseproc)PyCData_traverse, /* tp_traverse */ - (inquiry)PyCData_clear, /* tp_clear */ - 0, /* tp_richcompare */ - 0, /* tp_weaklistoffset */ - 0, /* tp_iter */ - 0, /* tp_iternext */ - 0, /* tp_methods */ - 0, /* tp_members */ - 0, /* tp_getset */ - 0, /* tp_base */ - 0, /* tp_dict */ - 0, /* tp_descr_get */ - 0, /* tp_descr_set */ - 0, /* tp_dictoffset */ - Struct_init, /* tp_init */ - 0, /* tp_alloc */ - GenericPyCData_new, /* tp_new */ - 0, /* tp_free */ + PyVarObject_HEAD_INIT(NULL, 0) + "_ctypes.Union", + sizeof(CDataObject), /* tp_basicsize */ + 0, /* tp_itemsize */ + 0, /* tp_dealloc */ + 0, /* tp_print */ + 0, /* tp_getattr */ + 0, /* tp_setattr */ + 0, /* tp_reserved */ + 0, /* tp_repr */ + 0, /* tp_as_number */ + 0, /* tp_as_sequence */ + 0, /* tp_as_mapping */ + 0, /* tp_hash */ + 0, /* tp_call */ + 0, /* tp_str */ + 0, /* tp_getattro */ + 0, /* tp_setattro */ + &PyCData_as_buffer, /* tp_as_buffer */ + Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */ + "Union base class", /* tp_doc */ + (traverseproc)PyCData_traverse, /* tp_traverse */ + (inquiry)PyCData_clear, /* tp_clear */ + 0, /* tp_richcompare */ + 0, /* tp_weaklistoffset */ + 0, /* tp_iter */ + 0, /* tp_iternext */ + 0, /* tp_methods */ + 0, /* tp_members */ + 0, /* tp_getset */ + 0, /* tp_base */ + 0, /* tp_dict */ + 0, /* tp_descr_get */ + 0, /* tp_descr_set */ + 0, /* tp_dictoffset */ + Struct_init, /* tp_init */ + 0, /* tp_alloc */ + GenericPyCData_new, /* tp_new */ + 0, /* tp_free */ }; - + /******************************************************************/ /* PyCArray_Type @@ -4124,371 +4124,371 @@ static int Array_init(CDataObject *self, PyObject *args, PyObject *kw) { - Py_ssize_t i; - Py_ssize_t n; + Py_ssize_t i; + Py_ssize_t n; - if (!PyTuple_Check(args)) { - PyErr_SetString(PyExc_TypeError, - "args not a tuple?"); - return -1; - } - n = PyTuple_GET_SIZE(args); - for (i = 0; i < n; ++i) { - PyObject *v; - v = PyTuple_GET_ITEM(args, i); - if (-1 == PySequence_SetItem((PyObject *)self, i, v)) - return -1; - } - return 0; + if (!PyTuple_Check(args)) { + PyErr_SetString(PyExc_TypeError, + "args not a tuple?"); + return -1; + } + n = PyTuple_GET_SIZE(args); + for (i = 0; i < n; ++i) { + PyObject *v; + v = PyTuple_GET_ITEM(args, i); + if (-1 == PySequence_SetItem((PyObject *)self, i, v)) + return -1; + } + return 0; } static PyObject * Array_item(PyObject *_self, Py_ssize_t index) { - CDataObject *self = (CDataObject *)_self; - Py_ssize_t offset, size; - StgDictObject *stgdict; - - - if (index < 0 || index >= self->b_length) { - PyErr_SetString(PyExc_IndexError, - "invalid index"); - return NULL; - } - - stgdict = PyObject_stgdict((PyObject *)self); - assert(stgdict); /* Cannot be NULL for array instances */ - /* Would it be clearer if we got the item size from - stgdict->proto's stgdict? - */ - size = stgdict->size / stgdict->length; - offset = index * size; + CDataObject *self = (CDataObject *)_self; + Py_ssize_t offset, size; + StgDictObject *stgdict; + + + if (index < 0 || index >= self->b_length) { + PyErr_SetString(PyExc_IndexError, + "invalid index"); + return NULL; + } + + stgdict = PyObject_stgdict((PyObject *)self); + assert(stgdict); /* Cannot be NULL for array instances */ + /* Would it be clearer if we got the item size from + stgdict->proto's stgdict? + */ + size = stgdict->size / stgdict->length; + offset = index * size; - return PyCData_get(stgdict->proto, stgdict->getfunc, (PyObject *)self, - index, size, self->b_ptr + offset); + return PyCData_get(stgdict->proto, stgdict->getfunc, (PyObject *)self, + index, size, self->b_ptr + offset); } static PyObject * Array_subscript(PyObject *_self, PyObject *item) { - CDataObject *self = (CDataObject *)_self; + CDataObject *self = (CDataObject *)_self; - 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 += self->b_length; - return Array_item(_self, i); - } - else if PySlice_Check(item) { - StgDictObject *stgdict, *itemdict; - PyObject *proto; - PyObject *np; - Py_ssize_t start, stop, step, slicelen, cur, i; - - if (PySlice_GetIndicesEx((PySliceObject *)item, - self->b_length, &start, &stop, - &step, &slicelen) < 0) { - return NULL; - } - - stgdict = PyObject_stgdict((PyObject *)self); - assert(stgdict); /* Cannot be NULL for array object instances */ - proto = stgdict->proto; - itemdict = PyType_stgdict(proto); - assert(itemdict); /* proto is the item type of the array, a - ctypes type, so this cannot be NULL */ - - if (itemdict->getfunc == _ctypes_get_fielddesc("c")->getfunc) { - char *ptr = (char *)self->b_ptr; - char *dest; - - if (slicelen <= 0) - return PyBytes_FromStringAndSize("", 0); - if (step == 1) { - return PyBytes_FromStringAndSize(ptr + start, - slicelen); - } - dest = (char *)PyMem_Malloc(slicelen); - - if (dest == NULL) - return PyErr_NoMemory(); - - for (cur = start, i = 0; i < slicelen; - cur += step, i++) { - dest[i] = ptr[cur]; - } - - np = PyBytes_FromStringAndSize(dest, slicelen); - PyMem_Free(dest); - return np; - } + 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 += self->b_length; + return Array_item(_self, i); + } + else if PySlice_Check(item) { + StgDictObject *stgdict, *itemdict; + PyObject *proto; + PyObject *np; + Py_ssize_t start, stop, step, slicelen, cur, i; + + if (PySlice_GetIndicesEx((PySliceObject *)item, + self->b_length, &start, &stop, + &step, &slicelen) < 0) { + return NULL; + } + + stgdict = PyObject_stgdict((PyObject *)self); + assert(stgdict); /* Cannot be NULL for array object instances */ + proto = stgdict->proto; + itemdict = PyType_stgdict(proto); + assert(itemdict); /* proto is the item type of the array, a + ctypes type, so this cannot be NULL */ + + if (itemdict->getfunc == _ctypes_get_fielddesc("c")->getfunc) { + char *ptr = (char *)self->b_ptr; + char *dest; + + if (slicelen <= 0) + return PyBytes_FromStringAndSize("", 0); + if (step == 1) { + return PyBytes_FromStringAndSize(ptr + start, + slicelen); + } + dest = (char *)PyMem_Malloc(slicelen); + + if (dest == NULL) + return PyErr_NoMemory(); + + for (cur = start, i = 0; i < slicelen; + cur += step, i++) { + dest[i] = ptr[cur]; + } + + np = PyBytes_FromStringAndSize(dest, slicelen); + PyMem_Free(dest); + return np; + } #ifdef CTYPES_UNICODE - if (itemdict->getfunc == _ctypes_get_fielddesc("u")->getfunc) { - wchar_t *ptr = (wchar_t *)self->b_ptr; - wchar_t *dest; - - if (slicelen <= 0) - return PyUnicode_FromUnicode(NULL, 0); - if (step == 1) { - return PyUnicode_FromWideChar(ptr + start, - slicelen); - } - - dest = (wchar_t *)PyMem_Malloc( - slicelen * sizeof(wchar_t)); - - for (cur = start, i = 0; i < slicelen; - cur += step, i++) { - dest[i] = ptr[cur]; - } - - np = PyUnicode_FromWideChar(dest, slicelen); - PyMem_Free(dest); - return np; - } + if (itemdict->getfunc == _ctypes_get_fielddesc("u")->getfunc) { + wchar_t *ptr = (wchar_t *)self->b_ptr; + wchar_t *dest; + + if (slicelen <= 0) + return PyUnicode_FromUnicode(NULL, 0); + if (step == 1) { + return PyUnicode_FromWideChar(ptr + start, + slicelen); + } + + dest = (wchar_t *)PyMem_Malloc( + slicelen * sizeof(wchar_t)); + + for (cur = start, i = 0; i < slicelen; + cur += step, i++) { + dest[i] = ptr[cur]; + } + + np = PyUnicode_FromWideChar(dest, slicelen); + PyMem_Free(dest); + return np; + } #endif - np = PyList_New(slicelen); - if (np == NULL) - return NULL; - - for (cur = start, i = 0; i < slicelen; - cur += step, i++) { - PyObject *v = Array_item(_self, cur); - PyList_SET_ITEM(np, i, v); - } - return np; - } - else { - PyErr_SetString(PyExc_TypeError, - "indices must be integers"); - return NULL; - } + np = PyList_New(slicelen); + if (np == NULL) + return NULL; + + for (cur = start, i = 0; i < slicelen; + cur += step, i++) { + PyObject *v = Array_item(_self, cur); + PyList_SET_ITEM(np, i, v); + } + return np; + } + else { + PyErr_SetString(PyExc_TypeError, + "indices must be integers"); + return NULL; + } } static int Array_ass_item(PyObject *_self, Py_ssize_t index, PyObject *value) { - CDataObject *self = (CDataObject *)_self; - Py_ssize_t size, offset; - StgDictObject *stgdict; - char *ptr; - - if (value == NULL) { - PyErr_SetString(PyExc_TypeError, - "Array does not support item deletion"); - return -1; - } - - stgdict = PyObject_stgdict((PyObject *)self); - assert(stgdict); /* Cannot be NULL for array object instances */ - if (index < 0 || index >= stgdict->length) { - PyErr_SetString(PyExc_IndexError, - "invalid index"); - return -1; - } - size = stgdict->size / stgdict->length; - offset = index * size; - ptr = self->b_ptr + offset; + CDataObject *self = (CDataObject *)_self; + Py_ssize_t size, offset; + StgDictObject *stgdict; + char *ptr; + + if (value == NULL) { + PyErr_SetString(PyExc_TypeError, + "Array does not support item deletion"); + return -1; + } + + stgdict = PyObject_stgdict((PyObject *)self); + assert(stgdict); /* Cannot be NULL for array object instances */ + if (index < 0 || index >= stgdict->length) { + PyErr_SetString(PyExc_IndexError, + "invalid index"); + return -1; + } + size = stgdict->size / stgdict->length; + offset = index * size; + ptr = self->b_ptr + offset; - return PyCData_set((PyObject *)self, stgdict->proto, stgdict->setfunc, value, - index, size, ptr); + return PyCData_set((PyObject *)self, stgdict->proto, stgdict->setfunc, value, + index, size, ptr); } static int Array_ass_subscript(PyObject *_self, PyObject *item, PyObject *value) { - CDataObject *self = (CDataObject *)_self; - - if (value == NULL) { - PyErr_SetString(PyExc_TypeError, - "Array does not support item deletion"); - return -1; - } - - if (PyIndex_Check(item)) { - Py_ssize_t i = PyNumber_AsSsize_t(item, PyExc_IndexError); - - if (i == -1 && PyErr_Occurred()) - return -1; - if (i < 0) - i += self->b_length; - return Array_ass_item(_self, i, value); - } - else if (PySlice_Check(item)) { - Py_ssize_t start, stop, step, slicelen, otherlen, i, cur; - - if (PySlice_GetIndicesEx((PySliceObject *)item, - self->b_length, &start, &stop, - &step, &slicelen) < 0) { - return -1; - } - if ((step < 0 && start < stop) || - (step > 0 && start > stop)) - stop = start; - - otherlen = PySequence_Length(value); - if (otherlen != slicelen) { - PyErr_SetString(PyExc_ValueError, - "Can only assign sequence of same size"); - return -1; - } - for (cur = start, i = 0; i < otherlen; cur += step, i++) { - PyObject *item = PySequence_GetItem(value, i); - int result; - if (item == NULL) - return -1; - result = Array_ass_item(_self, cur, item); - Py_DECREF(item); - if (result == -1) - return -1; - } - return 0; - } - else { - PyErr_SetString(PyExc_TypeError, - "indices must be integer"); - return -1; - } + CDataObject *self = (CDataObject *)_self; + + if (value == NULL) { + PyErr_SetString(PyExc_TypeError, + "Array does not support item deletion"); + return -1; + } + + if (PyIndex_Check(item)) { + Py_ssize_t i = PyNumber_AsSsize_t(item, PyExc_IndexError); + + if (i == -1 && PyErr_Occurred()) + return -1; + if (i < 0) + i += self->b_length; + return Array_ass_item(_self, i, value); + } + else if (PySlice_Check(item)) { + Py_ssize_t start, stop, step, slicelen, otherlen, i, cur; + + if (PySlice_GetIndicesEx((PySliceObject *)item, + self->b_length, &start, &stop, + &step, &slicelen) < 0) { + return -1; + } + if ((step < 0 && start < stop) || + (step > 0 && start > stop)) + stop = start; + + otherlen = PySequence_Length(value); + if (otherlen != slicelen) { + PyErr_SetString(PyExc_ValueError, + "Can only assign sequence of same size"); + return -1; + } + for (cur = start, i = 0; i < otherlen; cur += step, i++) { + PyObject *item = PySequence_GetItem(value, i); + int result; + if (item == NULL) + return -1; + result = Array_ass_item(_self, cur, item); + Py_DECREF(item); + if (result == -1) + return -1; + } + return 0; + } + else { + PyErr_SetString(PyExc_TypeError, + "indices must be integer"); + return -1; + } } static Py_ssize_t Array_length(PyObject *_self) { - CDataObject *self = (CDataObject *)_self; - return self->b_length; + CDataObject *self = (CDataObject *)_self; + return self->b_length; } static PySequenceMethods Array_as_sequence = { - Array_length, /* sq_length; */ - 0, /* sq_concat; */ - 0, /* sq_repeat; */ - Array_item, /* sq_item; */ - 0, /* sq_slice; */ - Array_ass_item, /* sq_ass_item; */ - 0, /* sq_ass_slice; */ - 0, /* sq_contains; */ - - 0, /* sq_inplace_concat; */ - 0, /* sq_inplace_repeat; */ + Array_length, /* sq_length; */ + 0, /* sq_concat; */ + 0, /* sq_repeat; */ + Array_item, /* sq_item; */ + 0, /* sq_slice; */ + Array_ass_item, /* sq_ass_item; */ + 0, /* sq_ass_slice; */ + 0, /* sq_contains; */ + + 0, /* sq_inplace_concat; */ + 0, /* sq_inplace_repeat; */ }; static PyMappingMethods Array_as_mapping = { - Array_length, - Array_subscript, - Array_ass_subscript, + Array_length, + Array_subscript, + Array_ass_subscript, }; PyTypeObject PyCArray_Type = { - PyVarObject_HEAD_INIT(NULL, 0) - "_ctypes.Array", - sizeof(CDataObject), /* tp_basicsize */ - 0, /* tp_itemsize */ - 0, /* tp_dealloc */ - 0, /* tp_print */ - 0, /* tp_getattr */ - 0, /* tp_setattr */ - 0, /* tp_reserved */ - 0, /* tp_repr */ - 0, /* tp_as_number */ - &Array_as_sequence, /* tp_as_sequence */ - &Array_as_mapping, /* tp_as_mapping */ - 0, /* tp_hash */ - 0, /* tp_call */ - 0, /* tp_str */ - 0, /* tp_getattro */ - 0, /* tp_setattro */ - &PyCData_as_buffer, /* tp_as_buffer */ - Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */ - "XXX to be provided", /* tp_doc */ - (traverseproc)PyCData_traverse, /* tp_traverse */ - (inquiry)PyCData_clear, /* tp_clear */ - 0, /* tp_richcompare */ - 0, /* tp_weaklistoffset */ - 0, /* tp_iter */ - 0, /* tp_iternext */ - 0, /* tp_methods */ - 0, /* tp_members */ - 0, /* tp_getset */ - 0, /* tp_base */ - 0, /* tp_dict */ - 0, /* tp_descr_get */ - 0, /* tp_descr_set */ - 0, /* tp_dictoffset */ - (initproc)Array_init, /* tp_init */ - 0, /* tp_alloc */ - GenericPyCData_new, /* tp_new */ - 0, /* tp_free */ + PyVarObject_HEAD_INIT(NULL, 0) + "_ctypes.Array", + sizeof(CDataObject), /* tp_basicsize */ + 0, /* tp_itemsize */ + 0, /* tp_dealloc */ + 0, /* tp_print */ + 0, /* tp_getattr */ + 0, /* tp_setattr */ + 0, /* tp_reserved */ + 0, /* tp_repr */ + 0, /* tp_as_number */ + &Array_as_sequence, /* tp_as_sequence */ + &Array_as_mapping, /* tp_as_mapping */ + 0, /* tp_hash */ + 0, /* tp_call */ + 0, /* tp_str */ + 0, /* tp_getattro */ + 0, /* tp_setattro */ + &PyCData_as_buffer, /* tp_as_buffer */ + Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */ + "XXX to be provided", /* tp_doc */ + (traverseproc)PyCData_traverse, /* tp_traverse */ + (inquiry)PyCData_clear, /* tp_clear */ + 0, /* tp_richcompare */ + 0, /* tp_weaklistoffset */ + 0, /* tp_iter */ + 0, /* tp_iternext */ + 0, /* tp_methods */ + 0, /* tp_members */ + 0, /* tp_getset */ + 0, /* tp_base */ + 0, /* tp_dict */ + 0, /* tp_descr_get */ + 0, /* tp_descr_set */ + 0, /* tp_dictoffset */ + (initproc)Array_init, /* tp_init */ + 0, /* tp_alloc */ + GenericPyCData_new, /* tp_new */ + 0, /* tp_free */ }; PyObject * PyCArrayType_from_ctype(PyObject *itemtype, Py_ssize_t length) { - static PyObject *cache; - PyObject *key; - PyObject *result; - char name[256]; - PyObject *len; - - if (cache == NULL) { - cache = PyDict_New(); - if (cache == NULL) - return NULL; - } - len = PyLong_FromSsize_t(length); - if (len == NULL) - return NULL; - key = PyTuple_Pack(2, itemtype, len); - Py_DECREF(len); - if (!key) - return NULL; - result = PyDict_GetItemProxy(cache, key); - if (result) { - Py_INCREF(result); - Py_DECREF(key); - return result; - } - - if (!PyType_Check(itemtype)) { - PyErr_SetString(PyExc_TypeError, - "Expected a type object"); - return NULL; - } + static PyObject *cache; + PyObject *key; + PyObject *result; + char name[256]; + PyObject *len; + + if (cache == NULL) { + cache = PyDict_New(); + if (cache == NULL) + return NULL; + } + len = PyLong_FromSsize_t(length); + if (len == NULL) + return NULL; + key = PyTuple_Pack(2, itemtype, len); + Py_DECREF(len); + if (!key) + return NULL; + result = PyDict_GetItemProxy(cache, key); + if (result) { + Py_INCREF(result); + Py_DECREF(key); + return result; + } + + if (!PyType_Check(itemtype)) { + PyErr_SetString(PyExc_TypeError, + "Expected a type object"); + return NULL; + } #ifdef MS_WIN64 - sprintf(name, "%.200s_Array_%Id", - ((PyTypeObject *)itemtype)->tp_name, length); + sprintf(name, "%.200s_Array_%Id", + ((PyTypeObject *)itemtype)->tp_name, length); #else - sprintf(name, "%.200s_Array_%ld", - ((PyTypeObject *)itemtype)->tp_name, (long)length); + sprintf(name, "%.200s_Array_%ld", + ((PyTypeObject *)itemtype)->tp_name, (long)length); #endif - result = PyObject_CallFunction((PyObject *)&PyCArrayType_Type, - "U(O){s:n,s:O}", - name, - &PyCArray_Type, - "_length_", - length, - "_type_", - itemtype - ); - if (result == NULL) { - Py_DECREF(key); - return NULL; - } - if (-1 == PyDict_SetItemProxy(cache, key, result)) { - Py_DECREF(key); - Py_DECREF(result); - return NULL; - } - Py_DECREF(key); - return result; + result = PyObject_CallFunction((PyObject *)&PyCArrayType_Type, + "U(O){s:n,s:O}", + name, + &PyCArray_Type, + "_length_", + length, + "_type_", + itemtype + ); + if (result == NULL) { + Py_DECREF(key); + return NULL; + } + if (-1 == PyDict_SetItemProxy(cache, key, result)) { + Py_DECREF(key); + Py_DECREF(result); + return NULL; + } + Py_DECREF(key); + return result; } - + /******************************************************************/ /* Simple_Type @@ -4497,166 +4497,166 @@ static int Simple_set_value(CDataObject *self, PyObject *value) { - PyObject *result; - StgDictObject *dict = PyObject_stgdict((PyObject *)self); + PyObject *result; + StgDictObject *dict = PyObject_stgdict((PyObject *)self); - if (value == NULL) { - PyErr_SetString(PyExc_TypeError, - "can't delete attribute"); - return -1; - } - assert(dict); /* Cannot be NULL for CDataObject instances */ - assert(dict->setfunc); - result = dict->setfunc(self->b_ptr, value, dict->size); - if (!result) - return -1; + if (value == NULL) { + PyErr_SetString(PyExc_TypeError, + "can't delete attribute"); + return -1; + } + assert(dict); /* Cannot be NULL for CDataObject instances */ + assert(dict->setfunc); + result = dict->setfunc(self->b_ptr, value, dict->size); + if (!result) + return -1; - /* consumes the refcount the setfunc returns */ - return KeepRef(self, 0, result); + /* consumes the refcount the setfunc returns */ + return KeepRef(self, 0, result); } static int Simple_init(CDataObject *self, PyObject *args, PyObject *kw) { - PyObject *value = NULL; - if (!PyArg_UnpackTuple(args, "__init__", 0, 1, &value)) - return -1; - if (value) - return Simple_set_value(self, value); - return 0; + PyObject *value = NULL; + if (!PyArg_UnpackTuple(args, "__init__", 0, 1, &value)) + return -1; + if (value) + return Simple_set_value(self, value); + return 0; } static PyObject * Simple_get_value(CDataObject *self) { - StgDictObject *dict; - dict = PyObject_stgdict((PyObject *)self); - assert(dict); /* Cannot be NULL for CDataObject instances */ - assert(dict->getfunc); - return dict->getfunc(self->b_ptr, self->b_size); + StgDictObject *dict; + dict = PyObject_stgdict((PyObject *)self); + assert(dict); /* Cannot be NULL for CDataObject instances */ + assert(dict->getfunc); + return dict->getfunc(self->b_ptr, self->b_size); } static PyGetSetDef Simple_getsets[] = { - { "value", (getter)Simple_get_value, (setter)Simple_set_value, - "current value", NULL }, - { NULL, NULL } + { "value", (getter)Simple_get_value, (setter)Simple_set_value, + "current value", NULL }, + { NULL, NULL } }; static PyObject * Simple_from_outparm(PyObject *self, PyObject *args) { - if (_ctypes_simple_instance((PyObject *)Py_TYPE(self))) { - Py_INCREF(self); - return self; - } - /* call stgdict->getfunc */ - return Simple_get_value((CDataObject *)self); + if (_ctypes_simple_instance((PyObject *)Py_TYPE(self))) { + Py_INCREF(self); + return self; + } + /* call stgdict->getfunc */ + return Simple_get_value((CDataObject *)self); } static PyMethodDef Simple_methods[] = { - { "__ctypes_from_outparam__", Simple_from_outparm, METH_NOARGS, }, - { NULL, NULL }, + { "__ctypes_from_outparam__", Simple_from_outparm, METH_NOARGS, }, + { NULL, NULL }, }; static int Simple_bool(CDataObject *self) { - return memcmp(self->b_ptr, "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0", self->b_size); + return memcmp(self->b_ptr, "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0", self->b_size); } static PyNumberMethods Simple_as_number = { - 0, /* nb_add */ - 0, /* nb_subtract */ - 0, /* nb_multiply */ - 0, /* nb_remainder */ - 0, /* nb_divmod */ - 0, /* nb_power */ - 0, /* nb_negative */ - 0, /* nb_positive */ - 0, /* nb_absolute */ - (inquiry)Simple_bool, /* nb_bool */ + 0, /* nb_add */ + 0, /* nb_subtract */ + 0, /* nb_multiply */ + 0, /* nb_remainder */ + 0, /* nb_divmod */ + 0, /* nb_power */ + 0, /* nb_negative */ + 0, /* nb_positive */ + 0, /* nb_absolute */ + (inquiry)Simple_bool, /* nb_bool */ }; /* "%s(%s)" % (self.__class__.__name__, self.value) */ static PyObject * Simple_repr(CDataObject *self) { - PyObject *val, *name, *args, *result; - static PyObject *format; + PyObject *val, *name, *args, *result; + static PyObject *format; - if (Py_TYPE(self)->tp_base != &Simple_Type) { - return PyUnicode_FromFormat("<%s object at %p>", - Py_TYPE(self)->tp_name, self); - } - - if (format == NULL) { - format = PyUnicode_InternFromString("%s(%r)"); - if (format == NULL) - return NULL; - } - - val = Simple_get_value(self); - if (val == NULL) - return NULL; - - name = PyUnicode_FromString(Py_TYPE(self)->tp_name); - if (name == NULL) { - Py_DECREF(val); - return NULL; - } - - args = PyTuple_Pack(2, name, val); - Py_DECREF(name); - Py_DECREF(val); - if (args == NULL) - return NULL; - - result = PyUnicode_Format(format, args); - Py_DECREF(args); - return result; + if (Py_TYPE(self)->tp_base != &Simple_Type) { + return PyUnicode_FromFormat("<%s object at %p>", + Py_TYPE(self)->tp_name, self); + } + + if (format == NULL) { + format = PyUnicode_InternFromString("%s(%r)"); + if (format == NULL) + return NULL; + } + + val = Simple_get_value(self); + if (val == NULL) + return NULL; + + name = PyUnicode_FromString(Py_TYPE(self)->tp_name); + if (name == NULL) { + Py_DECREF(val); + return NULL; + } + + args = PyTuple_Pack(2, name, val); + Py_DECREF(name); + Py_DECREF(val); + if (args == NULL) + return NULL; + + result = PyUnicode_Format(format, args); + Py_DECREF(args); + return result; } static PyTypeObject Simple_Type = { - PyVarObject_HEAD_INIT(NULL, 0) - "_ctypes._SimpleCData", - sizeof(CDataObject), /* tp_basicsize */ - 0, /* tp_itemsize */ - 0, /* tp_dealloc */ - 0, /* tp_print */ - 0, /* tp_getattr */ - 0, /* tp_setattr */ - 0, /* tp_reserved */ - (reprfunc)&Simple_repr, /* tp_repr */ - &Simple_as_number, /* tp_as_number */ - 0, /* tp_as_sequence */ - 0, /* tp_as_mapping */ - 0, /* tp_hash */ - 0, /* tp_call */ - 0, /* tp_str */ - 0, /* tp_getattro */ - 0, /* tp_setattro */ - &PyCData_as_buffer, /* tp_as_buffer */ - Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */ - "XXX to be provided", /* tp_doc */ - (traverseproc)PyCData_traverse, /* tp_traverse */ - (inquiry)PyCData_clear, /* tp_clear */ - 0, /* tp_richcompare */ - 0, /* tp_weaklistoffset */ - 0, /* tp_iter */ - 0, /* tp_iternext */ - Simple_methods, /* tp_methods */ - 0, /* tp_members */ - Simple_getsets, /* tp_getset */ - 0, /* tp_base */ - 0, /* tp_dict */ - 0, /* tp_descr_get */ - 0, /* tp_descr_set */ - 0, /* tp_dictoffset */ - (initproc)Simple_init, /* tp_init */ - 0, /* tp_alloc */ - GenericPyCData_new, /* tp_new */ - 0, /* tp_free */ + PyVarObject_HEAD_INIT(NULL, 0) + "_ctypes._SimpleCData", + sizeof(CDataObject), /* tp_basicsize */ + 0, /* tp_itemsize */ + 0, /* tp_dealloc */ + 0, /* tp_print */ + 0, /* tp_getattr */ + 0, /* tp_setattr */ + 0, /* tp_reserved */ + (reprfunc)&Simple_repr, /* tp_repr */ + &Simple_as_number, /* tp_as_number */ + 0, /* tp_as_sequence */ + 0, /* tp_as_mapping */ + 0, /* tp_hash */ + 0, /* tp_call */ + 0, /* tp_str */ + 0, /* tp_getattro */ + 0, /* tp_setattro */ + &PyCData_as_buffer, /* tp_as_buffer */ + Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */ + "XXX to be provided", /* tp_doc */ + (traverseproc)PyCData_traverse, /* tp_traverse */ + (inquiry)PyCData_clear, /* tp_clear */ + 0, /* tp_richcompare */ + 0, /* tp_weaklistoffset */ + 0, /* tp_iter */ + 0, /* tp_iternext */ + Simple_methods, /* tp_methods */ + 0, /* tp_members */ + Simple_getsets, /* tp_getset */ + 0, /* tp_base */ + 0, /* tp_dict */ + 0, /* tp_descr_get */ + 0, /* tp_descr_set */ + 0, /* tp_dictoffset */ + (initproc)Simple_init, /* tp_init */ + 0, /* tp_alloc */ + GenericPyCData_new, /* tp_new */ + 0, /* tp_free */ }; - + /******************************************************************/ /* PyCPointer_Type @@ -4664,377 +4664,377 @@ static PyObject * Pointer_item(PyObject *_self, Py_ssize_t index) { - CDataObject *self = (CDataObject *)_self; - Py_ssize_t size; - Py_ssize_t offset; - StgDictObject *stgdict, *itemdict; - PyObject *proto; - - if (*(void **)self->b_ptr == NULL) { - PyErr_SetString(PyExc_ValueError, - "NULL pointer access"); - return NULL; - } - - stgdict = PyObject_stgdict((PyObject *)self); - assert(stgdict); /* Cannot be NULL for pointer object instances */ - - proto = stgdict->proto; - assert(proto); - itemdict = PyType_stgdict(proto); - assert(itemdict); /* proto is the item type of the pointer, a ctypes - type, so this cannot be NULL */ + CDataObject *self = (CDataObject *)_self; + Py_ssize_t size; + Py_ssize_t offset; + StgDictObject *stgdict, *itemdict; + PyObject *proto; + + if (*(void **)self->b_ptr == NULL) { + PyErr_SetString(PyExc_ValueError, + "NULL pointer access"); + return NULL; + } + + stgdict = PyObject_stgdict((PyObject *)self); + assert(stgdict); /* Cannot be NULL for pointer object instances */ + + proto = stgdict->proto; + assert(proto); + itemdict = PyType_stgdict(proto); + assert(itemdict); /* proto is the item type of the pointer, a ctypes + type, so this cannot be NULL */ - size = itemdict->size; - offset = index * itemdict->size; + size = itemdict->size; + offset = index * itemdict->size; - return PyCData_get(proto, stgdict->getfunc, (PyObject *)self, - index, size, (*(char **)self->b_ptr) + offset); + return PyCData_get(proto, stgdict->getfunc, (PyObject *)self, + index, size, (*(char **)self->b_ptr) + offset); } static int Pointer_ass_item(PyObject *_self, Py_ssize_t index, PyObject *value) { - CDataObject *self = (CDataObject *)_self; - Py_ssize_t size; - Py_ssize_t offset; - StgDictObject *stgdict, *itemdict; - PyObject *proto; - - if (value == NULL) { - PyErr_SetString(PyExc_TypeError, - "Pointer does not support item deletion"); - return -1; - } - - if (*(void **)self->b_ptr == NULL) { - PyErr_SetString(PyExc_ValueError, - "NULL pointer access"); - return -1; - } - - stgdict = PyObject_stgdict((PyObject *)self); - assert(stgdict); /* Cannot be NULL fr pointer instances */ - - proto = stgdict->proto; - assert(proto); - - itemdict = PyType_stgdict(proto); - assert(itemdict); /* Cannot be NULL because the itemtype of a pointer - is always a ctypes type */ + CDataObject *self = (CDataObject *)_self; + Py_ssize_t size; + Py_ssize_t offset; + StgDictObject *stgdict, *itemdict; + PyObject *proto; + + if (value == NULL) { + PyErr_SetString(PyExc_TypeError, + "Pointer does not support item deletion"); + return -1; + } + + if (*(void **)self->b_ptr == NULL) { + PyErr_SetString(PyExc_ValueError, + "NULL pointer access"); + return -1; + } + + stgdict = PyObject_stgdict((PyObject *)self); + assert(stgdict); /* Cannot be NULL fr pointer instances */ + + proto = stgdict->proto; + assert(proto); - size = itemdict->size; - offset = index * itemdict->size; + itemdict = PyType_stgdict(proto); + assert(itemdict); /* Cannot be NULL because the itemtype of a pointer + is always a ctypes type */ - return PyCData_set((PyObject *)self, proto, stgdict->setfunc, value, - index, size, (*(char **)self->b_ptr) + offset); + size = itemdict->size; + offset = index * itemdict->size; + + return PyCData_set((PyObject *)self, proto, stgdict->setfunc, value, + index, size, (*(char **)self->b_ptr) + offset); } static PyObject * Pointer_get_contents(CDataObject *self, void *closure) { - StgDictObject *stgdict; + StgDictObject *stgdict; - if (*(void **)self->b_ptr == NULL) { - PyErr_SetString(PyExc_ValueError, - "NULL pointer access"); - return NULL; - } - - stgdict = PyObject_stgdict((PyObject *)self); - assert(stgdict); /* Cannot be NULL fr pointer instances */ - return PyCData_FromBaseObj(stgdict->proto, - (PyObject *)self, 0, - *(void **)self->b_ptr); + if (*(void **)self->b_ptr == NULL) { + PyErr_SetString(PyExc_ValueError, + "NULL pointer access"); + return NULL; + } + + stgdict = PyObject_stgdict((PyObject *)self); + assert(stgdict); /* Cannot be NULL fr pointer instances */ + return PyCData_FromBaseObj(stgdict->proto, + (PyObject *)self, 0, + *(void **)self->b_ptr); } static int Pointer_set_contents(CDataObject *self, PyObject *value, void *closure) { - StgDictObject *stgdict; - CDataObject *dst; - PyObject *keep; - - if (value == NULL) { - PyErr_SetString(PyExc_TypeError, - "Pointer does not support item deletion"); - return -1; - } - stgdict = PyObject_stgdict((PyObject *)self); - assert(stgdict); /* Cannot be NULL fr pointer instances */ - assert(stgdict->proto); - if (!CDataObject_Check(value) - || 0 == PyObject_IsInstance(value, stgdict->proto)) { - /* XXX PyObject_IsInstance could return -1! */ - PyErr_Format(PyExc_TypeError, - "expected %s instead of %s", - ((PyTypeObject *)(stgdict->proto))->tp_name, - Py_TYPE(value)->tp_name); - return -1; - } - - dst = (CDataObject *)value; - *(void **)self->b_ptr = dst->b_ptr; - - /* - A Pointer instance must keep a the value it points to alive. So, a - pointer instance has b_length set to 2 instead of 1, and we set - 'value' itself as the second item of the b_objects list, additionally. - */ - Py_INCREF(value); - if (-1 == KeepRef(self, 1, value)) - return -1; - - keep = GetKeepedObjects(dst); - Py_INCREF(keep); - return KeepRef(self, 0, keep); + StgDictObject *stgdict; + CDataObject *dst; + PyObject *keep; + + if (value == NULL) { + PyErr_SetString(PyExc_TypeError, + "Pointer does not support item deletion"); + return -1; + } + stgdict = PyObject_stgdict((PyObject *)self); + assert(stgdict); /* Cannot be NULL fr pointer instances */ + assert(stgdict->proto); + if (!CDataObject_Check(value) + || 0 == PyObject_IsInstance(value, stgdict->proto)) { + /* XXX PyObject_IsInstance could return -1! */ + PyErr_Format(PyExc_TypeError, + "expected %s instead of %s", + ((PyTypeObject *)(stgdict->proto))->tp_name, + Py_TYPE(value)->tp_name); + return -1; + } + + dst = (CDataObject *)value; + *(void **)self->b_ptr = dst->b_ptr; + + /* + A Pointer instance must keep a the value it points to alive. So, a + pointer instance has b_length set to 2 instead of 1, and we set + 'value' itself as the second item of the b_objects list, additionally. + */ + Py_INCREF(value); + if (-1 == KeepRef(self, 1, value)) + return -1; + + keep = GetKeepedObjects(dst); + Py_INCREF(keep); + return KeepRef(self, 0, keep); } static PyGetSetDef Pointer_getsets[] = { - { "contents", (getter)Pointer_get_contents, - (setter)Pointer_set_contents, - "the object this pointer points to (read-write)", NULL }, - { NULL, NULL } + { "contents", (getter)Pointer_get_contents, + (setter)Pointer_set_contents, + "the object this pointer points to (read-write)", NULL }, + { NULL, NULL } }; static int Pointer_init(CDataObject *self, PyObject *args, PyObject *kw) { - PyObject *value = NULL; + PyObject *value = NULL; - if (!PyArg_UnpackTuple(args, "POINTER", 0, 1, &value)) - return -1; - if (value == NULL) - return 0; - return Pointer_set_contents(self, value, NULL); + if (!PyArg_UnpackTuple(args, "POINTER", 0, 1, &value)) + return -1; + if (value == NULL) + return 0; + return Pointer_set_contents(self, value, NULL); } static PyObject * Pointer_new(PyTypeObject *type, PyObject *args, PyObject *kw) { - StgDictObject *dict = PyType_stgdict((PyObject *)type); - if (!dict || !dict->proto) { - PyErr_SetString(PyExc_TypeError, - "Cannot create instance: has no _type_"); - return NULL; - } - return GenericPyCData_new(type, args, kw); + StgDictObject *dict = PyType_stgdict((PyObject *)type); + if (!dict || !dict->proto) { + PyErr_SetString(PyExc_TypeError, + "Cannot create instance: has no _type_"); + return NULL; + } + return GenericPyCData_new(type, args, kw); } static PyObject * Pointer_subscript(PyObject *_self, PyObject *item) { - CDataObject *self = (CDataObject *)_self; - if (PyIndex_Check(item)) { - Py_ssize_t i = PyNumber_AsSsize_t(item, PyExc_IndexError); - if (i == -1 && PyErr_Occurred()) - return NULL; - return Pointer_item(_self, i); - } - else if (PySlice_Check(item)) { - PySliceObject *slice = (PySliceObject *)item; - Py_ssize_t start, stop, step; - PyObject *np; - StgDictObject *stgdict, *itemdict; - PyObject *proto; - Py_ssize_t i, len, cur; - - /* Since pointers have no length, and we want to apply - different semantics to negative indices than normal - slicing, we have to dissect the slice object ourselves.*/ - if (slice->step == Py_None) { - step = 1; - } - else { - step = PyNumber_AsSsize_t(slice->step, - PyExc_ValueError); - if (step == -1 && PyErr_Occurred()) - return NULL; - if (step == 0) { - PyErr_SetString(PyExc_ValueError, - "slice step cannot be zero"); - return NULL; - } - } - if (slice->start == Py_None) { - if (step < 0) { - PyErr_SetString(PyExc_ValueError, - "slice start is required " - "for step < 0"); - return NULL; - } - start = 0; - } - else { - start = PyNumber_AsSsize_t(slice->start, - PyExc_ValueError); - if (start == -1 && PyErr_Occurred()) - return NULL; - } - if (slice->stop == Py_None) { - PyErr_SetString(PyExc_ValueError, - "slice stop is required"); - return NULL; - } - stop = PyNumber_AsSsize_t(slice->stop, - PyExc_ValueError); - if (stop == -1 && PyErr_Occurred()) - return NULL; - if ((step > 0 && start > stop) || - (step < 0 && start < stop)) - len = 0; - else if (step > 0) - len = (stop - start - 1) / step + 1; - else - len = (stop - start + 1) / step + 1; - - stgdict = PyObject_stgdict((PyObject *)self); - assert(stgdict); /* Cannot be NULL for pointer instances */ - proto = stgdict->proto; - assert(proto); - itemdict = PyType_stgdict(proto); - assert(itemdict); - if (itemdict->getfunc == _ctypes_get_fielddesc("c")->getfunc) { - char *ptr = *(char **)self->b_ptr; - char *dest; - - if (len <= 0) - return PyBytes_FromStringAndSize("", 0); - if (step == 1) { - return PyBytes_FromStringAndSize(ptr + start, - len); - } - dest = (char *)PyMem_Malloc(len); - if (dest == NULL) - return PyErr_NoMemory(); - for (cur = start, i = 0; i < len; cur += step, i++) { - dest[i] = ptr[cur]; - } - np = PyBytes_FromStringAndSize(dest, len); - PyMem_Free(dest); - return np; - } + CDataObject *self = (CDataObject *)_self; + if (PyIndex_Check(item)) { + Py_ssize_t i = PyNumber_AsSsize_t(item, PyExc_IndexError); + if (i == -1 && PyErr_Occurred()) + return NULL; + return Pointer_item(_self, i); + } + else if (PySlice_Check(item)) { + PySliceObject *slice = (PySliceObject *)item; + Py_ssize_t start, stop, step; + PyObject *np; + StgDictObject *stgdict, *itemdict; + PyObject *proto; + Py_ssize_t i, len, cur; + + /* Since pointers have no length, and we want to apply + different semantics to negative indices than normal + slicing, we have to dissect the slice object ourselves.*/ + if (slice->step == Py_None) { + step = 1; + } + else { + step = PyNumber_AsSsize_t(slice->step, + PyExc_ValueError); + if (step == -1 && PyErr_Occurred()) + return NULL; + if (step == 0) { + PyErr_SetString(PyExc_ValueError, + "slice step cannot be zero"); + return NULL; + } + } + if (slice->start == Py_None) { + if (step < 0) { + PyErr_SetString(PyExc_ValueError, + "slice start is required " + "for step < 0"); + return NULL; + } + start = 0; + } + else { + start = PyNumber_AsSsize_t(slice->start, + PyExc_ValueError); + if (start == -1 && PyErr_Occurred()) + return NULL; + } + if (slice->stop == Py_None) { + PyErr_SetString(PyExc_ValueError, + "slice stop is required"); + return NULL; + } + stop = PyNumber_AsSsize_t(slice->stop, + PyExc_ValueError); + if (stop == -1 && PyErr_Occurred()) + return NULL; + if ((step > 0 && start > stop) || + (step < 0 && start < stop)) + len = 0; + else if (step > 0) + len = (stop - start - 1) / step + 1; + else + len = (stop - start + 1) / step + 1; + + stgdict = PyObject_stgdict((PyObject *)self); + assert(stgdict); /* Cannot be NULL for pointer instances */ + proto = stgdict->proto; + assert(proto); + itemdict = PyType_stgdict(proto); + assert(itemdict); + if (itemdict->getfunc == _ctypes_get_fielddesc("c")->getfunc) { + char *ptr = *(char **)self->b_ptr; + char *dest; + + if (len <= 0) + return PyBytes_FromStringAndSize("", 0); + if (step == 1) { + return PyBytes_FromStringAndSize(ptr + start, + len); + } + dest = (char *)PyMem_Malloc(len); + if (dest == NULL) + return PyErr_NoMemory(); + for (cur = start, i = 0; i < len; cur += step, i++) { + dest[i] = ptr[cur]; + } + np = PyBytes_FromStringAndSize(dest, len); + PyMem_Free(dest); + return np; + } #ifdef CTYPES_UNICODE - if (itemdict->getfunc == _ctypes_get_fielddesc("u")->getfunc) { - wchar_t *ptr = *(wchar_t **)self->b_ptr; - wchar_t *dest; - - if (len <= 0) - return PyUnicode_FromUnicode(NULL, 0); - if (step == 1) { - return PyUnicode_FromWideChar(ptr + start, - len); - } - dest = (wchar_t *)PyMem_Malloc(len * sizeof(wchar_t)); - if (dest == NULL) - return PyErr_NoMemory(); - for (cur = start, i = 0; i < len; cur += step, i++) { - dest[i] = ptr[cur]; - } - np = PyUnicode_FromWideChar(dest, len); - PyMem_Free(dest); - return np; - } + if (itemdict->getfunc == _ctypes_get_fielddesc("u")->getfunc) { + wchar_t *ptr = *(wchar_t **)self->b_ptr; + wchar_t *dest; + + if (len <= 0) + return PyUnicode_FromUnicode(NULL, 0); + if (step == 1) { + return PyUnicode_FromWideChar(ptr + start, + len); + } + dest = (wchar_t *)PyMem_Malloc(len * sizeof(wchar_t)); + if (dest == NULL) + return PyErr_NoMemory(); + for (cur = start, i = 0; i < len; cur += step, i++) { + dest[i] = ptr[cur]; + } + np = PyUnicode_FromWideChar(dest, len); + PyMem_Free(dest); + return np; + } #endif - np = PyList_New(len); - if (np == NULL) - return NULL; - - for (cur = start, i = 0; i < len; cur += step, i++) { - PyObject *v = Pointer_item(_self, cur); - PyList_SET_ITEM(np, i, v); - } - return np; - } - else { - PyErr_SetString(PyExc_TypeError, - "Pointer indices must be integer"); - return NULL; - } + np = PyList_New(len); + if (np == NULL) + return NULL; + + for (cur = start, i = 0; i < len; cur += step, i++) { + PyObject *v = Pointer_item(_self, cur); + PyList_SET_ITEM(np, i, v); + } + return np; + } + else { + PyErr_SetString(PyExc_TypeError, + "Pointer indices must be integer"); + return NULL; + } } static PySequenceMethods Pointer_as_sequence = { - 0, /* inquiry sq_length; */ - 0, /* binaryfunc sq_concat; */ - 0, /* intargfunc sq_repeat; */ - Pointer_item, /* intargfunc sq_item; */ - 0, /* intintargfunc sq_slice; */ - Pointer_ass_item, /* intobjargproc sq_ass_item; */ - 0, /* intintobjargproc sq_ass_slice; */ - 0, /* objobjproc sq_contains; */ - /* Added in release 2.0 */ - 0, /* binaryfunc sq_inplace_concat; */ - 0, /* intargfunc sq_inplace_repeat; */ + 0, /* inquiry sq_length; */ + 0, /* binaryfunc sq_concat; */ + 0, /* intargfunc sq_repeat; */ + Pointer_item, /* intargfunc sq_item; */ + 0, /* intintargfunc sq_slice; */ + Pointer_ass_item, /* intobjargproc sq_ass_item; */ + 0, /* intintobjargproc sq_ass_slice; */ + 0, /* objobjproc sq_contains; */ + /* Added in release 2.0 */ + 0, /* binaryfunc sq_inplace_concat; */ + 0, /* intargfunc sq_inplace_repeat; */ }; static PyMappingMethods Pointer_as_mapping = { - 0, - Pointer_subscript, + 0, + Pointer_subscript, }; static int Pointer_bool(CDataObject *self) { - return (*(void **)self->b_ptr != NULL); + return (*(void **)self->b_ptr != NULL); } static PyNumberMethods Pointer_as_number = { - 0, /* nb_add */ - 0, /* nb_subtract */ - 0, /* nb_multiply */ - 0, /* nb_remainder */ - 0, /* nb_divmod */ - 0, /* nb_power */ - 0, /* nb_negative */ - 0, /* nb_positive */ - 0, /* nb_absolute */ - (inquiry)Pointer_bool, /* nb_bool */ + 0, /* nb_add */ + 0, /* nb_subtract */ + 0, /* nb_multiply */ + 0, /* nb_remainder */ + 0, /* nb_divmod */ + 0, /* nb_power */ + 0, /* nb_negative */ + 0, /* nb_positive */ + 0, /* nb_absolute */ + (inquiry)Pointer_bool, /* nb_bool */ }; PyTypeObject PyCPointer_Type = { - PyVarObject_HEAD_INIT(NULL, 0) - "_ctypes._Pointer", - sizeof(CDataObject), /* tp_basicsize */ - 0, /* tp_itemsize */ - 0, /* tp_dealloc */ - 0, /* tp_print */ - 0, /* tp_getattr */ - 0, /* tp_setattr */ - 0, /* tp_reserved */ - 0, /* tp_repr */ - &Pointer_as_number, /* tp_as_number */ - &Pointer_as_sequence, /* tp_as_sequence */ - &Pointer_as_mapping, /* tp_as_mapping */ - 0, /* tp_hash */ - 0, /* tp_call */ - 0, /* tp_str */ - 0, /* tp_getattro */ - 0, /* tp_setattro */ - &PyCData_as_buffer, /* tp_as_buffer */ - Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */ - "XXX to be provided", /* tp_doc */ - (traverseproc)PyCData_traverse, /* tp_traverse */ - (inquiry)PyCData_clear, /* tp_clear */ - 0, /* tp_richcompare */ - 0, /* tp_weaklistoffset */ - 0, /* tp_iter */ - 0, /* tp_iternext */ - 0, /* tp_methods */ - 0, /* tp_members */ - Pointer_getsets, /* tp_getset */ - 0, /* tp_base */ - 0, /* tp_dict */ - 0, /* tp_descr_get */ - 0, /* tp_descr_set */ - 0, /* tp_dictoffset */ - (initproc)Pointer_init, /* tp_init */ - 0, /* tp_alloc */ - Pointer_new, /* tp_new */ - 0, /* tp_free */ + PyVarObject_HEAD_INIT(NULL, 0) + "_ctypes._Pointer", + sizeof(CDataObject), /* tp_basicsize */ + 0, /* tp_itemsize */ + 0, /* tp_dealloc */ + 0, /* tp_print */ + 0, /* tp_getattr */ + 0, /* tp_setattr */ + 0, /* tp_reserved */ + 0, /* tp_repr */ + &Pointer_as_number, /* tp_as_number */ + &Pointer_as_sequence, /* tp_as_sequence */ + &Pointer_as_mapping, /* tp_as_mapping */ + 0, /* tp_hash */ + 0, /* tp_call */ + 0, /* tp_str */ + 0, /* tp_getattro */ + 0, /* tp_setattro */ + &PyCData_as_buffer, /* tp_as_buffer */ + Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */ + "XXX to be provided", /* tp_doc */ + (traverseproc)PyCData_traverse, /* tp_traverse */ + (inquiry)PyCData_clear, /* tp_clear */ + 0, /* tp_richcompare */ + 0, /* tp_weaklistoffset */ + 0, /* tp_iter */ + 0, /* tp_iternext */ + 0, /* tp_methods */ + 0, /* tp_members */ + Pointer_getsets, /* tp_getset */ + 0, /* tp_base */ + 0, /* tp_dict */ + 0, /* tp_descr_get */ + 0, /* tp_descr_set */ + 0, /* tp_dictoffset */ + (initproc)Pointer_init, /* tp_init */ + 0, /* tp_alloc */ + Pointer_new, /* tp_new */ + 0, /* tp_free */ }; - + /******************************************************************/ /* * Module initialization. @@ -5056,27 +5056,27 @@ int status; if (!_PyArg_NoKeywords(Py_TYPE(self)->tp_name, kwds)) - return -1; + return -1; if (!PyArg_ParseTuple(args, "OOO:COMError", &hresult, &text, &details)) - return -1; + return -1; a = PySequence_GetSlice(args, 1, PySequence_Size(args)); if (!a) - return -1; + return -1; status = PyObject_SetAttrString(self, "args", a); Py_DECREF(a); if (status < 0) - return -1; + return -1; if (PyObject_SetAttrString(self, "hresult", hresult) < 0) - return -1; + return -1; if (PyObject_SetAttrString(self, "text", text) < 0) - return -1; + return -1; if (PyObject_SetAttrString(self, "details", details) < 0) - return -1; + return -1; bself = (PyBaseExceptionObject *)self; Py_DECREF(bself->args); @@ -5131,11 +5131,11 @@ static int create_comerror(void) { - PyComError_Type.tp_base = (PyTypeObject*)PyExc_Exception; - if (PyType_Ready(&PyComError_Type) < 0) - return -1; - ComError = (PyObject*)&PyComError_Type; - return 0; + PyComError_Type.tp_base = (PyTypeObject*)PyExc_Exception; + if (PyType_Ready(&PyComError_Type) < 0) + return -1; + ComError = (PyObject*)&PyComError_Type; + return 0; } #endif @@ -5143,259 +5143,259 @@ static PyObject * string_at(const char *ptr, int size) { - if (size == -1) - return PyBytes_FromStringAndSize(ptr, strlen(ptr)); - return PyBytes_FromStringAndSize(ptr, size); + if (size == -1) + return PyBytes_FromStringAndSize(ptr, strlen(ptr)); + return PyBytes_FromStringAndSize(ptr, size); } static int cast_check_pointertype(PyObject *arg) { - StgDictObject *dict; + StgDictObject *dict; - if (PyCPointerTypeObject_Check(arg)) - return 1; - if (PyCFuncPtrTypeObject_Check(arg)) - return 1; - dict = PyType_stgdict(arg); - if (dict) { - if (PyUnicode_Check(dict->proto) - && (strchr("sPzUZXO", _PyUnicode_AsString(dict->proto)[0]))) { - /* simple pointer types, c_void_p, c_wchar_p, BSTR, ... */ - return 1; - } - } - PyErr_Format(PyExc_TypeError, - "cast() argument 2 must be a pointer type, not %s", - PyType_Check(arg) - ? ((PyTypeObject *)arg)->tp_name - : Py_TYPE(arg)->tp_name); - return 0; + if (PyCPointerTypeObject_Check(arg)) + return 1; + if (PyCFuncPtrTypeObject_Check(arg)) + return 1; + dict = PyType_stgdict(arg); + if (dict) { + if (PyUnicode_Check(dict->proto) + && (strchr("sPzUZXO", _PyUnicode_AsString(dict->proto)[0]))) { + /* simple pointer types, c_void_p, c_wchar_p, BSTR, ... */ + return 1; + } + } + PyErr_Format(PyExc_TypeError, + "cast() argument 2 must be a pointer type, not %s", + PyType_Check(arg) + ? ((PyTypeObject *)arg)->tp_name + : Py_TYPE(arg)->tp_name); + return 0; } static PyObject * cast(void *ptr, PyObject *src, PyObject *ctype) { - CDataObject *result; - if (0 == cast_check_pointertype(ctype)) - return NULL; - result = (CDataObject *)PyObject_CallFunctionObjArgs(ctype, NULL); - if (result == NULL) - return NULL; - - /* - The casted objects '_objects' member: - - It must certainly contain the source objects one. - It must contain the source object itself. - */ - if (CDataObject_Check(src)) { - CDataObject *obj = (CDataObject *)src; - /* PyCData_GetContainer will initialize src.b_objects, we need - this so it can be shared */ - PyCData_GetContainer(obj); - /* But we need a dictionary! */ - if (obj->b_objects == Py_None) { - Py_DECREF(Py_None); - obj->b_objects = PyDict_New(); - if (obj->b_objects == NULL) - goto failed; - } - Py_XINCREF(obj->b_objects); - result->b_objects = obj->b_objects; - if (result->b_objects && PyDict_CheckExact(result->b_objects)) { - PyObject *index; - int rc; - index = PyLong_FromVoidPtr((void *)src); - if (index == NULL) - goto failed; - rc = PyDict_SetItem(result->b_objects, index, src); - Py_DECREF(index); - if (rc == -1) - goto failed; - } - } - /* Should we assert that result is a pointer type? */ - memcpy(result->b_ptr, &ptr, sizeof(void *)); - return (PyObject *)result; + CDataObject *result; + if (0 == cast_check_pointertype(ctype)) + return NULL; + result = (CDataObject *)PyObject_CallFunctionObjArgs(ctype, NULL); + if (result == NULL) + return NULL; + + /* + The casted objects '_objects' member: + + It must certainly contain the source objects one. + It must contain the source object itself. + */ + if (CDataObject_Check(src)) { + CDataObject *obj = (CDataObject *)src; + /* PyCData_GetContainer will initialize src.b_objects, we need + this so it can be shared */ + PyCData_GetContainer(obj); + /* But we need a dictionary! */ + if (obj->b_objects == Py_None) { + Py_DECREF(Py_None); + obj->b_objects = PyDict_New(); + if (obj->b_objects == NULL) + goto failed; + } + Py_XINCREF(obj->b_objects); + result->b_objects = obj->b_objects; + if (result->b_objects && PyDict_CheckExact(result->b_objects)) { + PyObject *index; + int rc; + index = PyLong_FromVoidPtr((void *)src); + if (index == NULL) + goto failed; + rc = PyDict_SetItem(result->b_objects, index, src); + Py_DECREF(index); + if (rc == -1) + goto failed; + } + } + /* Should we assert that result is a pointer type? */ + memcpy(result->b_ptr, &ptr, sizeof(void *)); + return (PyObject *)result; failed: - Py_DECREF(result); - return NULL; + Py_DECREF(result); + return NULL; } #ifdef CTYPES_UNICODE static PyObject * wstring_at(const wchar_t *ptr, int size) { - Py_ssize_t ssize = size; - if (ssize == -1) - ssize = wcslen(ptr); - return PyUnicode_FromWideChar(ptr, ssize); + Py_ssize_t ssize = size; + if (ssize == -1) + ssize = wcslen(ptr); + return PyUnicode_FromWideChar(ptr, ssize); } #endif static struct PyModuleDef _ctypesmodule = { - PyModuleDef_HEAD_INIT, - "_ctypes", - module_docs, - -1, - _ctypes_module_methods, - NULL, - NULL, - NULL, - NULL + PyModuleDef_HEAD_INIT, + "_ctypes", + module_docs, + -1, + _ctypes_module_methods, + NULL, + NULL, + NULL, + NULL }; PyMODINIT_FUNC PyInit__ctypes(void) { - PyObject *m; + PyObject *m; /* Note: ob_type is the metatype (the 'type'), defaults to PyType_Type, tp_base is the base type, defaults to 'object' aka PyBaseObject_Type. */ #ifdef WITH_THREAD - PyEval_InitThreads(); + PyEval_InitThreads(); #endif - m = PyModule_Create(&_ctypesmodule); - if (!m) - return NULL; - - _ctypes_ptrtype_cache = PyDict_New(); - if (_ctypes_ptrtype_cache == NULL) - return NULL; - - PyModule_AddObject(m, "_pointer_type_cache", (PyObject *)_ctypes_ptrtype_cache); - - _unpickle = PyObject_GetAttrString(m, "_unpickle"); - if (_unpickle == NULL) - return NULL; - - if (PyType_Ready(&PyCArg_Type) < 0) - return NULL; - - if (PyType_Ready(&PyCThunk_Type) < 0) - return NULL; - - /* StgDict is derived from PyDict_Type */ - PyCStgDict_Type.tp_base = &PyDict_Type; - if (PyType_Ready(&PyCStgDict_Type) < 0) - return NULL; - - /************************************************* - * - * Metaclasses - */ - - PyCStructType_Type.tp_base = &PyType_Type; - if (PyType_Ready(&PyCStructType_Type) < 0) - return NULL; - - UnionType_Type.tp_base = &PyType_Type; - if (PyType_Ready(&UnionType_Type) < 0) - return NULL; - - PyCPointerType_Type.tp_base = &PyType_Type; - if (PyType_Ready(&PyCPointerType_Type) < 0) - return NULL; - - PyCArrayType_Type.tp_base = &PyType_Type; - if (PyType_Ready(&PyCArrayType_Type) < 0) - return NULL; - - PyCSimpleType_Type.tp_base = &PyType_Type; - if (PyType_Ready(&PyCSimpleType_Type) < 0) - return NULL; - - PyCFuncPtrType_Type.tp_base = &PyType_Type; - if (PyType_Ready(&PyCFuncPtrType_Type) < 0) - return NULL; - - /************************************************* - * - * Classes using a custom metaclass - */ - - if (PyType_Ready(&PyCData_Type) < 0) - return NULL; - - Py_TYPE(&Struct_Type) = &PyCStructType_Type; - Struct_Type.tp_base = &PyCData_Type; - if (PyType_Ready(&Struct_Type) < 0) - return NULL; - PyModule_AddObject(m, "Structure", (PyObject *)&Struct_Type); - - Py_TYPE(&Union_Type) = &UnionType_Type; - Union_Type.tp_base = &PyCData_Type; - if (PyType_Ready(&Union_Type) < 0) - return NULL; - PyModule_AddObject(m, "Union", (PyObject *)&Union_Type); - - Py_TYPE(&PyCPointer_Type) = &PyCPointerType_Type; - PyCPointer_Type.tp_base = &PyCData_Type; - if (PyType_Ready(&PyCPointer_Type) < 0) - return NULL; - PyModule_AddObject(m, "_Pointer", (PyObject *)&PyCPointer_Type); - - Py_TYPE(&PyCArray_Type) = &PyCArrayType_Type; - PyCArray_Type.tp_base = &PyCData_Type; - if (PyType_Ready(&PyCArray_Type) < 0) - return NULL; - PyModule_AddObject(m, "Array", (PyObject *)&PyCArray_Type); - - Py_TYPE(&Simple_Type) = &PyCSimpleType_Type; - Simple_Type.tp_base = &PyCData_Type; - if (PyType_Ready(&Simple_Type) < 0) - return NULL; - PyModule_AddObject(m, "_SimpleCData", (PyObject *)&Simple_Type); - - Py_TYPE(&PyCFuncPtr_Type) = &PyCFuncPtrType_Type; - PyCFuncPtr_Type.tp_base = &PyCData_Type; - if (PyType_Ready(&PyCFuncPtr_Type) < 0) - return NULL; - PyModule_AddObject(m, "CFuncPtr", (PyObject *)&PyCFuncPtr_Type); - - /************************************************* - * - * Simple classes - */ - - /* PyCField_Type is derived from PyBaseObject_Type */ - if (PyType_Ready(&PyCField_Type) < 0) - return NULL; - - /************************************************* - * - * Other stuff - */ - - DictRemover_Type.tp_new = PyType_GenericNew; - if (PyType_Ready(&DictRemover_Type) < 0) - return NULL; + m = PyModule_Create(&_ctypesmodule); + if (!m) + return NULL; + + _ctypes_ptrtype_cache = PyDict_New(); + if (_ctypes_ptrtype_cache == NULL) + return NULL; + + PyModule_AddObject(m, "_pointer_type_cache", (PyObject *)_ctypes_ptrtype_cache); + + _unpickle = PyObject_GetAttrString(m, "_unpickle"); + if (_unpickle == NULL) + return NULL; + + if (PyType_Ready(&PyCArg_Type) < 0) + return NULL; + + if (PyType_Ready(&PyCThunk_Type) < 0) + return NULL; + + /* StgDict is derived from PyDict_Type */ + PyCStgDict_Type.tp_base = &PyDict_Type; + if (PyType_Ready(&PyCStgDict_Type) < 0) + return NULL; + + /************************************************* + * + * Metaclasses + */ + + PyCStructType_Type.tp_base = &PyType_Type; + if (PyType_Ready(&PyCStructType_Type) < 0) + return NULL; + + UnionType_Type.tp_base = &PyType_Type; + if (PyType_Ready(&UnionType_Type) < 0) + return NULL; + + PyCPointerType_Type.tp_base = &PyType_Type; + if (PyType_Ready(&PyCPointerType_Type) < 0) + return NULL; + + PyCArrayType_Type.tp_base = &PyType_Type; + if (PyType_Ready(&PyCArrayType_Type) < 0) + return NULL; + + PyCSimpleType_Type.tp_base = &PyType_Type; + if (PyType_Ready(&PyCSimpleType_Type) < 0) + return NULL; + + PyCFuncPtrType_Type.tp_base = &PyType_Type; + if (PyType_Ready(&PyCFuncPtrType_Type) < 0) + return NULL; + + /************************************************* + * + * Classes using a custom metaclass + */ + + if (PyType_Ready(&PyCData_Type) < 0) + return NULL; + + Py_TYPE(&Struct_Type) = &PyCStructType_Type; + Struct_Type.tp_base = &PyCData_Type; + if (PyType_Ready(&Struct_Type) < 0) + return NULL; + PyModule_AddObject(m, "Structure", (PyObject *)&Struct_Type); + + Py_TYPE(&Union_Type) = &UnionType_Type; + Union_Type.tp_base = &PyCData_Type; + if (PyType_Ready(&Union_Type) < 0) + return NULL; + PyModule_AddObject(m, "Union", (PyObject *)&Union_Type); + + Py_TYPE(&PyCPointer_Type) = &PyCPointerType_Type; + PyCPointer_Type.tp_base = &PyCData_Type; + if (PyType_Ready(&PyCPointer_Type) < 0) + return NULL; + PyModule_AddObject(m, "_Pointer", (PyObject *)&PyCPointer_Type); + + Py_TYPE(&PyCArray_Type) = &PyCArrayType_Type; + PyCArray_Type.tp_base = &PyCData_Type; + if (PyType_Ready(&PyCArray_Type) < 0) + return NULL; + PyModule_AddObject(m, "Array", (PyObject *)&PyCArray_Type); + + Py_TYPE(&Simple_Type) = &PyCSimpleType_Type; + Simple_Type.tp_base = &PyCData_Type; + if (PyType_Ready(&Simple_Type) < 0) + return NULL; + PyModule_AddObject(m, "_SimpleCData", (PyObject *)&Simple_Type); + + Py_TYPE(&PyCFuncPtr_Type) = &PyCFuncPtrType_Type; + PyCFuncPtr_Type.tp_base = &PyCData_Type; + if (PyType_Ready(&PyCFuncPtr_Type) < 0) + return NULL; + PyModule_AddObject(m, "CFuncPtr", (PyObject *)&PyCFuncPtr_Type); + + /************************************************* + * + * Simple classes + */ + + /* PyCField_Type is derived from PyBaseObject_Type */ + if (PyType_Ready(&PyCField_Type) < 0) + return NULL; + + /************************************************* + * + * Other stuff + */ + + DictRemover_Type.tp_new = PyType_GenericNew; + if (PyType_Ready(&DictRemover_Type) < 0) + return NULL; #ifdef MS_WIN32 - if (create_comerror() < 0) - return NULL; - PyModule_AddObject(m, "COMError", ComError); + if (create_comerror() < 0) + return NULL; + PyModule_AddObject(m, "COMError", ComError); - PyModule_AddObject(m, "FUNCFLAG_HRESULT", PyLong_FromLong(FUNCFLAG_HRESULT)); - PyModule_AddObject(m, "FUNCFLAG_STDCALL", PyLong_FromLong(FUNCFLAG_STDCALL)); + PyModule_AddObject(m, "FUNCFLAG_HRESULT", PyLong_FromLong(FUNCFLAG_HRESULT)); + PyModule_AddObject(m, "FUNCFLAG_STDCALL", PyLong_FromLong(FUNCFLAG_STDCALL)); #endif - PyModule_AddObject(m, "FUNCFLAG_CDECL", PyLong_FromLong(FUNCFLAG_CDECL)); - PyModule_AddObject(m, "FUNCFLAG_USE_ERRNO", PyLong_FromLong(FUNCFLAG_USE_ERRNO)); - PyModule_AddObject(m, "FUNCFLAG_USE_LASTERROR", PyLong_FromLong(FUNCFLAG_USE_LASTERROR)); - PyModule_AddObject(m, "FUNCFLAG_PYTHONAPI", PyLong_FromLong(FUNCFLAG_PYTHONAPI)); - PyModule_AddStringConstant(m, "__version__", "1.1.0"); - - PyModule_AddObject(m, "_memmove_addr", PyLong_FromVoidPtr(memmove)); - PyModule_AddObject(m, "_memset_addr", PyLong_FromVoidPtr(memset)); - PyModule_AddObject(m, "_string_at_addr", PyLong_FromVoidPtr(string_at)); - PyModule_AddObject(m, "_cast_addr", PyLong_FromVoidPtr(cast)); + PyModule_AddObject(m, "FUNCFLAG_CDECL", PyLong_FromLong(FUNCFLAG_CDECL)); + PyModule_AddObject(m, "FUNCFLAG_USE_ERRNO", PyLong_FromLong(FUNCFLAG_USE_ERRNO)); + PyModule_AddObject(m, "FUNCFLAG_USE_LASTERROR", PyLong_FromLong(FUNCFLAG_USE_LASTERROR)); + PyModule_AddObject(m, "FUNCFLAG_PYTHONAPI", PyLong_FromLong(FUNCFLAG_PYTHONAPI)); + PyModule_AddStringConstant(m, "__version__", "1.1.0"); + + PyModule_AddObject(m, "_memmove_addr", PyLong_FromVoidPtr(memmove)); + PyModule_AddObject(m, "_memset_addr", PyLong_FromVoidPtr(memset)); + PyModule_AddObject(m, "_string_at_addr", PyLong_FromVoidPtr(string_at)); + PyModule_AddObject(m, "_cast_addr", PyLong_FromVoidPtr(cast)); #ifdef CTYPES_UNICODE - PyModule_AddObject(m, "_wstring_at_addr", PyLong_FromVoidPtr(wstring_at)); + PyModule_AddObject(m, "_wstring_at_addr", PyLong_FromVoidPtr(wstring_at)); #endif /* If RTLD_LOCAL is not defined (Windows!), set it to zero. */ @@ -5410,15 +5410,15 @@ #define RTLD_GLOBAL RTLD_LOCAL #endif - PyModule_AddObject(m, "RTLD_LOCAL", PyLong_FromLong(RTLD_LOCAL)); - PyModule_AddObject(m, "RTLD_GLOBAL", PyLong_FromLong(RTLD_GLOBAL)); - - PyExc_ArgError = PyErr_NewException("ctypes.ArgumentError", NULL, NULL); - if (PyExc_ArgError) { - Py_INCREF(PyExc_ArgError); - PyModule_AddObject(m, "ArgumentError", PyExc_ArgError); - } - return m; + PyModule_AddObject(m, "RTLD_LOCAL", PyLong_FromLong(RTLD_LOCAL)); + PyModule_AddObject(m, "RTLD_GLOBAL", PyLong_FromLong(RTLD_GLOBAL)); + + PyExc_ArgError = PyErr_NewException("ctypes.ArgumentError", NULL, NULL); + if (PyExc_ArgError) { + Py_INCREF(PyExc_ArgError); + PyModule_AddObject(m, "ArgumentError", PyExc_ArgError); + } + return m; } /* Modified: python/branches/py3k-jit/Modules/_ctypes/_ctypes_test.c ============================================================================== --- python/branches/py3k-jit/Modules/_ctypes/_ctypes_test.c (original) +++ python/branches/py3k-jit/Modules/_ctypes/_ctypes_test.c Mon May 10 23:55:43 2010 @@ -14,152 +14,152 @@ EXPORT(void)testfunc_array(int values[4]) { - printf("testfunc_array %d %d %d %d\n", - values[0], - values[1], - values[2], - values[3]); + printf("testfunc_array %d %d %d %d\n", + values[0], + values[1], + values[2], + values[3]); } EXPORT(long double)testfunc_Ddd(double a, double b) { - long double result = (long double)(a * b); - printf("testfunc_Ddd(%p, %p)\n", &a, &b); - printf("testfunc_Ddd(%g, %g)\n", a, b); - return result; + long double result = (long double)(a * b); + printf("testfunc_Ddd(%p, %p)\n", &a, &b); + printf("testfunc_Ddd(%g, %g)\n", a, b); + return result; } EXPORT(long double)testfunc_DDD(long double a, long double b) { - long double result = a * b; - printf("testfunc_DDD(%p, %p)\n", &a, &b); - printf("testfunc_DDD(%Lg, %Lg)\n", a, b); - return result; + long double result = a * b; + printf("testfunc_DDD(%p, %p)\n", &a, &b); + printf("testfunc_DDD(%Lg, %Lg)\n", a, b); + return result; } EXPORT(int)testfunc_iii(int a, int b) { - int result = a * b; - printf("testfunc_iii(%p, %p)\n", &a, &b); - return result; + int result = a * b; + printf("testfunc_iii(%p, %p)\n", &a, &b); + return result; } EXPORT(int)myprintf(char *fmt, ...) { - int result; - va_list argptr; - va_start(argptr, fmt); - result = vprintf(fmt, argptr); - va_end(argptr); - return result; + int result; + va_list argptr; + va_start(argptr, fmt); + result = vprintf(fmt, argptr); + va_end(argptr); + return result; } EXPORT(char *)my_strtok(char *token, const char *delim) { - return strtok(token, delim); + return strtok(token, delim); } EXPORT(char *)my_strchr(const char *s, int c) { - return strchr(s, c); + return strchr(s, c); } EXPORT(double) my_sqrt(double a) { - return sqrt(a); + return sqrt(a); } EXPORT(void) my_qsort(void *base, size_t num, size_t width, int(*compare)(const void*, const void*)) { - qsort(base, num, width, compare); + qsort(base, num, width, compare); } EXPORT(int *) _testfunc_ai8(int a[8]) { - return a; + return a; } EXPORT(void) _testfunc_v(int a, int b, int *presult) { - *presult = a + b; + *presult = a + b; } EXPORT(int) _testfunc_i_bhilfd(signed char b, short h, int i, long l, float f, double d) { -/* printf("_testfunc_i_bhilfd got %d %d %d %ld %f %f\n", - b, h, i, l, f, d); +/* printf("_testfunc_i_bhilfd got %d %d %d %ld %f %f\n", + b, h, i, l, f, d); */ - return (int)(b + h + i + l + f + d); + return (int)(b + h + i + l + f + d); } EXPORT(float) _testfunc_f_bhilfd(signed char b, short h, int i, long l, float f, double d) { -/* printf("_testfunc_f_bhilfd got %d %d %d %ld %f %f\n", - b, h, i, l, f, d); +/* printf("_testfunc_f_bhilfd got %d %d %d %ld %f %f\n", + b, h, i, l, f, d); */ - return (float)(b + h + i + l + f + d); + return (float)(b + h + i + l + f + d); } EXPORT(double) _testfunc_d_bhilfd(signed char b, short h, int i, long l, float f, double d) { -/* printf("_testfunc_d_bhilfd got %d %d %d %ld %f %f\n", - b, h, i, l, f, d); +/* printf("_testfunc_d_bhilfd got %d %d %d %ld %f %f\n", + b, h, i, l, f, d); */ - return (double)(b + h + i + l + f + d); + return (double)(b + h + i + l + f + d); } EXPORT(long double) _testfunc_D_bhilfD(signed char b, short h, int i, long l, float f, long double d) { -/* printf("_testfunc_d_bhilfd got %d %d %d %ld %f %f\n", - b, h, i, l, f, d); +/* printf("_testfunc_d_bhilfd got %d %d %d %ld %f %f\n", + b, h, i, l, f, d); */ - return (long double)(b + h + i + l + f + d); + return (long double)(b + h + i + l + f + d); } EXPORT(char *) _testfunc_p_p(void *s) { - return (char *)s; + return (char *)s; } EXPORT(void *) _testfunc_c_p_p(int *argcp, char **argv) { - return argv[(*argcp)-1]; + return argv[(*argcp)-1]; } EXPORT(void *) get_strchr(void) { - return (void *)strchr; + return (void *)strchr; } EXPORT(char *) my_strdup(char *src) { - char *dst = (char *)malloc(strlen(src)+1); - if (!dst) - return NULL; - strcpy(dst, src); - return dst; + char *dst = (char *)malloc(strlen(src)+1); + if (!dst) + return NULL; + strcpy(dst, src); + return dst; } EXPORT(void)my_free(void *ptr) { - free(ptr); + free(ptr); } #ifdef HAVE_WCHAR_H EXPORT(wchar_t *) my_wcsdup(wchar_t *src) { - size_t len = wcslen(src); - wchar_t *ptr = (wchar_t *)malloc((len + 1) * sizeof(wchar_t)); - if (ptr == NULL) - return NULL; - memcpy(ptr, src, (len+1) * sizeof(wchar_t)); - return ptr; + size_t len = wcslen(src); + wchar_t *ptr = (wchar_t *)malloc((len + 1) * sizeof(wchar_t)); + if (ptr == NULL) + return NULL; + memcpy(ptr, src, (len+1) * sizeof(wchar_t)); + return ptr; } EXPORT(size_t) my_wcslen(wchar_t *src) { - return wcslen(src); + return wcslen(src); } #endif @@ -170,158 +170,158 @@ #endif typedef struct { - int (*c)(int, int); - int (__stdcall *s)(int, int); + int (*c)(int, int); + int (__stdcall *s)(int, int); } FUNCS; EXPORT(int) _testfunc_callfuncp(FUNCS *fp) { - fp->c(1, 2); - fp->s(3, 4); - return 0; + fp->c(1, 2); + fp->s(3, 4); + return 0; } EXPORT(int) _testfunc_deref_pointer(int *pi) { - return *pi; + return *pi; } #ifdef MS_WIN32 EXPORT(int) _testfunc_piunk(IUnknown FAR *piunk) { - piunk->lpVtbl->AddRef(piunk); - return piunk->lpVtbl->Release(piunk); + piunk->lpVtbl->AddRef(piunk); + return piunk->lpVtbl->Release(piunk); } #endif EXPORT(int) _testfunc_callback_with_pointer(int (*func)(int *)) { - int table[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; + int table[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; - return (*func)(table); + return (*func)(table); } #ifdef HAVE_LONG_LONG EXPORT(PY_LONG_LONG) _testfunc_q_bhilfdq(signed char b, short h, int i, long l, float f, - double d, PY_LONG_LONG q) + double d, PY_LONG_LONG q) { - return (PY_LONG_LONG)(b + h + i + l + f + d + q); + return (PY_LONG_LONG)(b + h + i + l + f + d + q); } EXPORT(PY_LONG_LONG) _testfunc_q_bhilfd(signed char b, short h, int i, long l, float f, double d) { - return (PY_LONG_LONG)(b + h + i + l + f + d); + return (PY_LONG_LONG)(b + h + i + l + f + d); } EXPORT(int) _testfunc_callback_i_if(int value, int (*func)(int)) { - int sum = 0; - while (value != 0) { - sum += func(value); - value /= 2; - } - return sum; + int sum = 0; + while (value != 0) { + sum += func(value); + value /= 2; + } + return sum; } EXPORT(PY_LONG_LONG) _testfunc_callback_q_qf(PY_LONG_LONG value, - PY_LONG_LONG (*func)(PY_LONG_LONG)) + PY_LONG_LONG (*func)(PY_LONG_LONG)) { - PY_LONG_LONG sum = 0; + PY_LONG_LONG sum = 0; - while (value != 0) { - sum += func(value); - value /= 2; - } - return sum; + while (value != 0) { + sum += func(value); + value /= 2; + } + return sum; } #endif typedef struct { - char *name; - char *value; + char *name; + char *value; } SPAM; typedef struct { - char *name; - int num_spams; - SPAM *spams; + char *name; + int num_spams; + SPAM *spams; } EGG; SPAM my_spams[2] = { - { "name1", "value1" }, - { "name2", "value2" }, + { "name1", "value1" }, + { "name2", "value2" }, }; EGG my_eggs[1] = { - { "first egg", 1, my_spams } + { "first egg", 1, my_spams } }; EXPORT(int) getSPAMANDEGGS(EGG **eggs) { - *eggs = my_eggs; - return 1; + *eggs = my_eggs; + return 1; } typedef struct tagpoint { - int x; - int y; + int x; + int y; } point; EXPORT(int) _testfunc_byval(point in, point *pout) { - if (pout) { - pout->x = in.x; - pout->y = in.y; - } - return in.x + in.y; + if (pout) { + pout->x = in.x; + pout->y = in.y; + } + return in.x + in.y; } EXPORT (int) an_integer = 42; EXPORT(int) get_an_integer(void) { - return an_integer; + return an_integer; } EXPORT(double) integrate(double a, double b, double (*f)(double), long nstep) { - double x, sum=0.0, dx=(b-a)/(double)nstep; - for(x=a+0.5*dx; (b-x)*(x-a)>0.0; x+=dx) - sum += f(x); - return sum/(double)nstep; + double x, sum=0.0, dx=(b-a)/(double)nstep; + for(x=a+0.5*dx; (b-x)*(x-a)>0.0; x+=dx) + sum += f(x); + return sum/(double)nstep; } typedef struct { - void (*initialize)(void *(*)(int), void(*)(void *)); + void (*initialize)(void *(*)(int), void(*)(void *)); } xxx_library; static void _xxx_init(void *(*Xalloc)(int), void (*Xfree)(void *)) { - void *ptr; - - printf("_xxx_init got %p %p\n", Xalloc, Xfree); - printf("calling\n"); - ptr = Xalloc(32); - Xfree(ptr); - printf("calls done, ptr was %p\n", ptr); + void *ptr; + + printf("_xxx_init got %p %p\n", Xalloc, Xfree); + printf("calling\n"); + ptr = Xalloc(32); + Xfree(ptr); + printf("calls done, ptr was %p\n", ptr); } xxx_library _xxx_lib = { - _xxx_init + _xxx_init }; EXPORT(xxx_library) *library_get(void) { - return &_xxx_lib; + return &_xxx_lib; } #ifdef MS_WIN32 /* See Don Box (german), pp 79ff. */ EXPORT(void) GetString(BSTR *pbstr) { - *pbstr = SysAllocString(L"Goodbye!"); + *pbstr = SysAllocString(L"Goodbye!"); } #endif @@ -330,12 +330,12 @@ */ PyObject *py_func_si(PyObject *self, PyObject *args) { - char *name; - int i; - if (!PyArg_ParseTuple(args, "si", &name, &i)) - return NULL; - Py_INCREF(Py_None); - return Py_None; + char *name; + int i; + if (!PyArg_ParseTuple(args, "si", &name, &i)) + return NULL; + Py_INCREF(Py_None); + return Py_None; } EXPORT(void) _py_func_si(char *s, int i) @@ -344,8 +344,8 @@ PyObject *py_func(PyObject *self, PyObject *args) { - Py_INCREF(Py_None); - return Py_None; + Py_INCREF(Py_None); + return Py_None; } EXPORT(void) _py_func(void) @@ -356,64 +356,64 @@ EXPORT(unsigned PY_LONG_LONG) last_tf_arg_u; struct BITS { - int A: 1, B:2, C:3, D:4, E: 5, F: 6, G: 7, H: 8, I: 9; - short M: 1, N: 2, O: 3, P: 4, Q: 5, R: 6, S: 7; + int A: 1, B:2, C:3, D:4, E: 5, F: 6, G: 7, H: 8, I: 9; + short M: 1, N: 2, O: 3, P: 4, Q: 5, R: 6, S: 7; }; EXPORT(void) set_bitfields(struct BITS *bits, char name, int value) { - switch (name) { - case 'A': bits->A = value; break; - case 'B': bits->B = value; break; - case 'C': bits->C = value; break; - case 'D': bits->D = value; break; - case 'E': bits->E = value; break; - case 'F': bits->F = value; break; - case 'G': bits->G = value; break; - case 'H': bits->H = value; break; - case 'I': bits->I = value; break; - - case 'M': bits->M = value; break; - case 'N': bits->N = value; break; - case 'O': bits->O = value; break; - case 'P': bits->P = value; break; - case 'Q': bits->Q = value; break; - case 'R': bits->R = value; break; - case 'S': bits->S = value; break; - } + switch (name) { + case 'A': bits->A = value; break; + case 'B': bits->B = value; break; + case 'C': bits->C = value; break; + case 'D': bits->D = value; break; + case 'E': bits->E = value; break; + case 'F': bits->F = value; break; + case 'G': bits->G = value; break; + case 'H': bits->H = value; break; + case 'I': bits->I = value; break; + + case 'M': bits->M = value; break; + case 'N': bits->N = value; break; + case 'O': bits->O = value; break; + case 'P': bits->P = value; break; + case 'Q': bits->Q = value; break; + case 'R': bits->R = value; break; + case 'S': bits->S = value; break; + } } EXPORT(int) unpack_bitfields(struct BITS *bits, char name) { - switch (name) { - case 'A': return bits->A; - case 'B': return bits->B; - case 'C': return bits->C; - case 'D': return bits->D; - case 'E': return bits->E; - case 'F': return bits->F; - case 'G': return bits->G; - case 'H': return bits->H; - case 'I': return bits->I; - - case 'M': return bits->M; - case 'N': return bits->N; - case 'O': return bits->O; - case 'P': return bits->P; - case 'Q': return bits->Q; - case 'R': return bits->R; - case 'S': return bits->S; - } - return 0; + switch (name) { + case 'A': return bits->A; + case 'B': return bits->B; + case 'C': return bits->C; + case 'D': return bits->D; + case 'E': return bits->E; + case 'F': return bits->F; + case 'G': return bits->G; + case 'H': return bits->H; + case 'I': return bits->I; + + case 'M': return bits->M; + case 'N': return bits->N; + case 'O': return bits->O; + case 'P': return bits->P; + case 'Q': return bits->Q; + case 'R': return bits->R; + case 'S': return bits->S; + } + return 0; } static PyMethodDef module_methods[] = { -/* {"get_last_tf_arg_s", get_last_tf_arg_s, METH_NOARGS}, - {"get_last_tf_arg_u", get_last_tf_arg_u, METH_NOARGS}, +/* {"get_last_tf_arg_s", get_last_tf_arg_s, METH_NOARGS}, + {"get_last_tf_arg_u", get_last_tf_arg_u, METH_NOARGS}, */ - {"func_si", py_func_si, METH_VARARGS}, - {"func", py_func, METH_NOARGS}, - { NULL, NULL, 0, NULL}, + {"func_si", py_func_si, METH_VARARGS}, + {"func", py_func, METH_NOARGS}, + { NULL, NULL, 0, NULL}, }; #define S last_tf_arg_s = (PY_LONG_LONG)c @@ -483,80 +483,80 @@ #endif /********/ - + #ifndef MS_WIN32 typedef struct { - long x; - long y; + long x; + long y; } POINT; typedef struct { - long left; - long top; - long right; - long bottom; + long left; + long top; + long right; + long bottom; } RECT; #endif EXPORT(int) PointInRect(RECT *prc, POINT pt) { - if (pt.x < prc->left) - return 0; - if (pt.x > prc->right) - return 0; - if (pt.y < prc->top) - return 0; - if (pt.y > prc->bottom) - return 0; - return 1; + if (pt.x < prc->left) + return 0; + if (pt.x > prc->right) + return 0; + if (pt.y < prc->top) + return 0; + if (pt.y > prc->bottom) + return 0; + return 1; } typedef struct { - short x; - short y; + short x; + short y; } S2H; EXPORT(S2H) ret_2h_func(S2H inp) { - inp.x *= 2; - inp.y *= 3; - return inp; + inp.x *= 2; + inp.y *= 3; + return inp; } typedef struct { - int a, b, c, d, e, f, g, h; + int a, b, c, d, e, f, g, h; } S8I; EXPORT(S8I) ret_8i_func(S8I inp) { - inp.a *= 2; - inp.b *= 3; - inp.c *= 4; - inp.d *= 5; - inp.e *= 6; - inp.f *= 7; - inp.g *= 8; - inp.h *= 9; - return inp; + inp.a *= 2; + inp.b *= 3; + inp.c *= 4; + inp.d *= 5; + inp.e *= 6; + inp.f *= 7; + inp.g *= 8; + inp.h *= 9; + return inp; } EXPORT(int) GetRectangle(int flag, RECT *prect) { - if (flag == 0) - return 0; - prect->left = (int)flag; - prect->top = (int)flag + 1; - prect->right = (int)flag + 2; - prect->bottom = (int)flag + 3; - return 1; + if (flag == 0) + return 0; + prect->left = (int)flag; + prect->top = (int)flag + 1; + prect->right = (int)flag + 2; + prect->bottom = (int)flag + 3; + return 1; } EXPORT(void) TwoOutArgs(int a, int *pi, int b, int *pj) { - *pi += a; - *pj += b; + *pi += a; + *pj += b; } #ifdef MS_WIN32 @@ -571,32 +571,32 @@ EXPORT (HRESULT) KeepObject(IUnknown *punk) { - static IUnknown *pobj; - if (punk) - punk->lpVtbl->AddRef(punk); - if (pobj) - pobj->lpVtbl->Release(pobj); - pobj = punk; - return S_OK; + static IUnknown *pobj; + if (punk) + punk->lpVtbl->AddRef(punk); + if (pobj) + pobj->lpVtbl->Release(pobj); + pobj = punk; + return S_OK; } #endif static struct PyModuleDef _ctypes_testmodule = { - PyModuleDef_HEAD_INIT, - "_ctypes_test", - NULL, - -1, - module_methods, - NULL, - NULL, - NULL, - NULL + PyModuleDef_HEAD_INIT, + "_ctypes_test", + NULL, + -1, + module_methods, + NULL, + NULL, + NULL, + NULL }; PyMODINIT_FUNC PyInit__ctypes_test(void) { - return PyModule_Create(&_ctypes_testmodule); + return PyModule_Create(&_ctypes_testmodule); } Modified: python/branches/py3k-jit/Modules/_ctypes/callbacks.c ============================================================================== --- python/branches/py3k-jit/Modules/_ctypes/callbacks.c (original) +++ python/branches/py3k-jit/Modules/_ctypes/callbacks.c Mon May 10 23:55:43 2010 @@ -12,65 +12,65 @@ static void CThunkObject_dealloc(PyObject *_self) { - CThunkObject *self = (CThunkObject *)_self; - Py_XDECREF(self->converters); - Py_XDECREF(self->callable); - Py_XDECREF(self->restype); - if (self->pcl) - _ctypes_free_closure(self->pcl); - PyObject_GC_Del(self); + CThunkObject *self = (CThunkObject *)_self; + Py_XDECREF(self->converters); + Py_XDECREF(self->callable); + Py_XDECREF(self->restype); + if (self->pcl) + _ctypes_free_closure(self->pcl); + PyObject_GC_Del(self); } static int CThunkObject_traverse(PyObject *_self, visitproc visit, void *arg) { - CThunkObject *self = (CThunkObject *)_self; - Py_VISIT(self->converters); - Py_VISIT(self->callable); - Py_VISIT(self->restype); - return 0; + CThunkObject *self = (CThunkObject *)_self; + Py_VISIT(self->converters); + Py_VISIT(self->callable); + Py_VISIT(self->restype); + return 0; } static int CThunkObject_clear(PyObject *_self) { - CThunkObject *self = (CThunkObject *)_self; - Py_CLEAR(self->converters); - Py_CLEAR(self->callable); - Py_CLEAR(self->restype); - return 0; + CThunkObject *self = (CThunkObject *)_self; + Py_CLEAR(self->converters); + Py_CLEAR(self->callable); + Py_CLEAR(self->restype); + return 0; } PyTypeObject PyCThunk_Type = { - PyVarObject_HEAD_INIT(NULL, 0) - "_ctypes.CThunkObject", - sizeof(CThunkObject), /* tp_basicsize */ - sizeof(ffi_type), /* tp_itemsize */ - CThunkObject_dealloc, /* tp_dealloc */ - 0, /* tp_print */ - 0, /* tp_getattr */ - 0, /* tp_setattr */ - 0, /* tp_reserved */ - 0, /* tp_repr */ - 0, /* tp_as_number */ - 0, /* tp_as_sequence */ - 0, /* tp_as_mapping */ - 0, /* tp_hash */ - 0, /* tp_call */ - 0, /* tp_str */ - 0, /* tp_getattro */ - 0, /* tp_setattro */ - 0, /* tp_as_buffer */ - Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC, /* tp_flags */ - "CThunkObject", /* tp_doc */ - CThunkObject_traverse, /* tp_traverse */ - CThunkObject_clear, /* tp_clear */ - 0, /* tp_richcompare */ - 0, /* tp_weaklistoffset */ - 0, /* tp_iter */ - 0, /* tp_iternext */ - 0, /* tp_methods */ - 0, /* tp_members */ + PyVarObject_HEAD_INIT(NULL, 0) + "_ctypes.CThunkObject", + sizeof(CThunkObject), /* tp_basicsize */ + sizeof(ffi_type), /* tp_itemsize */ + CThunkObject_dealloc, /* tp_dealloc */ + 0, /* tp_print */ + 0, /* tp_getattr */ + 0, /* tp_setattr */ + 0, /* tp_reserved */ + 0, /* tp_repr */ + 0, /* tp_as_number */ + 0, /* tp_as_sequence */ + 0, /* tp_as_mapping */ + 0, /* tp_hash */ + 0, /* tp_call */ + 0, /* tp_str */ + 0, /* tp_getattro */ + 0, /* tp_setattro */ + 0, /* tp_as_buffer */ + Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC, /* tp_flags */ + "CThunkObject", /* tp_doc */ + CThunkObject_traverse, /* tp_traverse */ + CThunkObject_clear, /* tp_clear */ + 0, /* tp_richcompare */ + 0, /* tp_weaklistoffset */ + 0, /* tp_iter */ + 0, /* tp_iternext */ + 0, /* tp_methods */ + 0, /* tp_members */ }; /**************************************************************/ @@ -78,43 +78,43 @@ static void PrintError(char *msg, ...) { - char buf[512]; - PyObject *f = PySys_GetObject("stderr"); - va_list marker; - - va_start(marker, msg); - vsnprintf(buf, sizeof(buf), msg, marker); - va_end(marker); - if (f != NULL && f != Py_None) - PyFile_WriteString(buf, f); - PyErr_Print(); + char buf[512]; + PyObject *f = PySys_GetObject("stderr"); + va_list marker; + + va_start(marker, msg); + vsnprintf(buf, sizeof(buf), msg, marker); + va_end(marker); + if (f != NULL && f != Py_None) + PyFile_WriteString(buf, f); + PyErr_Print(); } /* after code that pyrex generates */ void _ctypes_add_traceback(char *funcname, char *filename, int lineno) { - PyObject *py_globals = 0; - PyCodeObject *py_code = 0; - PyFrameObject *py_frame = 0; - - py_globals = PyDict_New(); - if (!py_globals) goto bad; - py_code = PyCode_NewEmpty(filename, funcname, lineno); - if (!py_code) goto bad; - py_frame = PyFrame_New( - PyThreadState_Get(), /*PyThreadState *tstate,*/ - py_code, /*PyCodeObject *code,*/ - py_globals, /*PyObject *globals,*/ - 0 /*PyObject *locals*/ - ); - if (!py_frame) goto bad; - py_frame->f_lineno = lineno; - PyTraceBack_Here(py_frame); + PyObject *py_globals = 0; + PyCodeObject *py_code = 0; + PyFrameObject *py_frame = 0; + + py_globals = PyDict_New(); + if (!py_globals) goto bad; + py_code = PyCode_NewEmpty(filename, funcname, lineno); + if (!py_code) goto bad; + py_frame = PyFrame_New( + PyThreadState_Get(), /*PyThreadState *tstate,*/ + py_code, /*PyCodeObject *code,*/ + py_globals, /*PyObject *globals,*/ + 0 /*PyObject *locals*/ + ); + if (!py_frame) goto bad; + py_frame->f_lineno = lineno; + PyTraceBack_Here(py_frame); bad: - Py_XDECREF(py_globals); - Py_XDECREF(py_code); - Py_XDECREF(py_frame); + Py_XDECREF(py_globals); + Py_XDECREF(py_code); + Py_XDECREF(py_frame); } #ifdef MS_WIN32 @@ -131,15 +131,15 @@ static void TryAddRef(StgDictObject *dict, CDataObject *obj) { - IUnknown *punk; + IUnknown *punk; - if (NULL == PyDict_GetItemString((PyObject *)dict, "_needs_com_addref_")) - return; + if (NULL == PyDict_GetItemString((PyObject *)dict, "_needs_com_addref_")) + return; - punk = *(IUnknown **)obj->b_ptr; - if (punk) - punk->lpVtbl->AddRef(punk); - return; + punk = *(IUnknown **)obj->b_ptr; + if (punk) + punk->lpVtbl->AddRef(punk); + return; } #endif @@ -149,421 +149,421 @@ * */ static void _CallPythonObject(void *mem, - ffi_type *restype, - SETFUNC setfunc, - PyObject *callable, - PyObject *converters, - int flags, - void **pArgs) -{ - Py_ssize_t i; - PyObject *result; - PyObject *arglist = NULL; - Py_ssize_t nArgs; - PyObject *error_object = NULL; - int *space; + ffi_type *restype, + SETFUNC setfunc, + PyObject *callable, + PyObject *converters, + int flags, + void **pArgs) +{ + Py_ssize_t i; + PyObject *result; + PyObject *arglist = NULL; + Py_ssize_t nArgs; + PyObject *error_object = NULL; + int *space; #ifdef WITH_THREAD - PyGILState_STATE state = PyGILState_Ensure(); + PyGILState_STATE state = PyGILState_Ensure(); #endif - nArgs = PySequence_Length(converters); - /* Hm. What to return in case of error? - For COM, 0xFFFFFFFF seems better than 0. - */ - if (nArgs < 0) { - PrintError("BUG: PySequence_Length"); - goto Done; - } - - arglist = PyTuple_New(nArgs); - if (!arglist) { - PrintError("PyTuple_New()"); - goto Done; - } - for (i = 0; i < nArgs; ++i) { - /* Note: new reference! */ - PyObject *cnv = PySequence_GetItem(converters, i); - StgDictObject *dict; - if (cnv) - dict = PyType_stgdict(cnv); - else { - PrintError("Getting argument converter %d\n", i); - goto Done; - } - - if (dict && dict->getfunc && !_ctypes_simple_instance(cnv)) { - PyObject *v = dict->getfunc(*pArgs, dict->size); - if (!v) { - PrintError("create argument %d:\n", i); - Py_DECREF(cnv); - goto Done; - } - PyTuple_SET_ITEM(arglist, i, v); - /* XXX XXX XX - We have the problem that c_byte or c_short have dict->size of - 1 resp. 4, but these parameters are pushed as sizeof(int) bytes. - BTW, the same problem occurrs when they are pushed as parameters - */ - } else if (dict) { - /* Hm, shouldn't we use PyCData_AtAddress() or something like that instead? */ - CDataObject *obj = (CDataObject *)PyObject_CallFunctionObjArgs(cnv, NULL); - if (!obj) { - PrintError("create argument %d:\n", i); - Py_DECREF(cnv); - goto Done; - } - if (!CDataObject_Check(obj)) { - Py_DECREF(obj); - Py_DECREF(cnv); - PrintError("unexpected result of create argument %d:\n", i); - goto Done; - } - memcpy(obj->b_ptr, *pArgs, dict->size); - PyTuple_SET_ITEM(arglist, i, (PyObject *)obj); + nArgs = PySequence_Length(converters); + /* Hm. What to return in case of error? + For COM, 0xFFFFFFFF seems better than 0. + */ + if (nArgs < 0) { + PrintError("BUG: PySequence_Length"); + goto Done; + } + + arglist = PyTuple_New(nArgs); + if (!arglist) { + PrintError("PyTuple_New()"); + goto Done; + } + for (i = 0; i < nArgs; ++i) { + /* Note: new reference! */ + PyObject *cnv = PySequence_GetItem(converters, i); + StgDictObject *dict; + if (cnv) + dict = PyType_stgdict(cnv); + else { + PrintError("Getting argument converter %d\n", i); + goto Done; + } + + if (dict && dict->getfunc && !_ctypes_simple_instance(cnv)) { + PyObject *v = dict->getfunc(*pArgs, dict->size); + if (!v) { + PrintError("create argument %d:\n", i); + Py_DECREF(cnv); + goto Done; + } + PyTuple_SET_ITEM(arglist, i, v); + /* XXX XXX XX + We have the problem that c_byte or c_short have dict->size of + 1 resp. 4, but these parameters are pushed as sizeof(int) bytes. + BTW, the same problem occurrs when they are pushed as parameters + */ + } else if (dict) { + /* Hm, shouldn't we use PyCData_AtAddress() or something like that instead? */ + CDataObject *obj = (CDataObject *)PyObject_CallFunctionObjArgs(cnv, NULL); + if (!obj) { + PrintError("create argument %d:\n", i); + Py_DECREF(cnv); + goto Done; + } + if (!CDataObject_Check(obj)) { + Py_DECREF(obj); + Py_DECREF(cnv); + PrintError("unexpected result of create argument %d:\n", i); + goto Done; + } + memcpy(obj->b_ptr, *pArgs, dict->size); + PyTuple_SET_ITEM(arglist, i, (PyObject *)obj); #ifdef MS_WIN32 - TryAddRef(dict, obj); + TryAddRef(dict, obj); #endif - } else { - PyErr_SetString(PyExc_TypeError, - "cannot build parameter"); - PrintError("Parsing argument %d\n", i); - Py_DECREF(cnv); - goto Done; - } - Py_DECREF(cnv); - /* XXX error handling! */ - pArgs++; - } + } else { + PyErr_SetString(PyExc_TypeError, + "cannot build parameter"); + PrintError("Parsing argument %d\n", i); + Py_DECREF(cnv); + goto Done; + } + Py_DECREF(cnv); + /* XXX error handling! */ + pArgs++; + } #define CHECK(what, x) \ if (x == NULL) _ctypes_add_traceback(what, "_ctypes/callbacks.c", __LINE__ - 1), PyErr_Print() - if (flags & (FUNCFLAG_USE_ERRNO | FUNCFLAG_USE_LASTERROR)) { - error_object = _ctypes_get_errobj(&space); - if (error_object == NULL) - goto Done; - if (flags & FUNCFLAG_USE_ERRNO) { - int temp = space[0]; - space[0] = errno; - errno = temp; - } + if (flags & (FUNCFLAG_USE_ERRNO | FUNCFLAG_USE_LASTERROR)) { + error_object = _ctypes_get_errobj(&space); + if (error_object == NULL) + goto Done; + if (flags & FUNCFLAG_USE_ERRNO) { + int temp = space[0]; + space[0] = errno; + errno = temp; + } #ifdef MS_WIN32 - if (flags & FUNCFLAG_USE_LASTERROR) { - int temp = space[1]; - space[1] = GetLastError(); - SetLastError(temp); - } + if (flags & FUNCFLAG_USE_LASTERROR) { + int temp = space[1]; + space[1] = GetLastError(); + SetLastError(temp); + } #endif - } + } - result = PyObject_CallObject(callable, arglist); - CHECK("'calling callback function'", result); + result = PyObject_CallObject(callable, arglist); + CHECK("'calling callback function'", result); #ifdef MS_WIN32 - if (flags & FUNCFLAG_USE_LASTERROR) { - int temp = space[1]; - space[1] = GetLastError(); - SetLastError(temp); - } -#endif - if (flags & FUNCFLAG_USE_ERRNO) { - int temp = space[0]; - space[0] = errno; - errno = temp; - } - Py_XDECREF(error_object); - - if ((restype != &ffi_type_void) && result) { - PyObject *keep; - assert(setfunc); + if (flags & FUNCFLAG_USE_LASTERROR) { + int temp = space[1]; + space[1] = GetLastError(); + SetLastError(temp); + } +#endif + if (flags & FUNCFLAG_USE_ERRNO) { + int temp = space[0]; + space[0] = errno; + errno = temp; + } + Py_XDECREF(error_object); + + if ((restype != &ffi_type_void) && result) { + PyObject *keep; + assert(setfunc); #ifdef WORDS_BIGENDIAN - /* See the corresponding code in callproc.c, around line 961 */ - if (restype->type != FFI_TYPE_FLOAT && restype->size < sizeof(ffi_arg)) - mem = (char *)mem + sizeof(ffi_arg) - restype->size; -#endif - keep = setfunc(mem, result, 0); - CHECK("'converting callback result'", keep); - /* keep is an object we have to keep alive so that the result - stays valid. If there is no such object, the setfunc will - have returned Py_None. - - If there is such an object, we have no choice than to keep - it alive forever - but a refcount and/or memory leak will - be the result. EXCEPT when restype is py_object - Python - itself knows how to manage the refcount of these objects. - */ - if (keep == NULL) /* Could not convert callback result. */ - PyErr_WriteUnraisable(callable); - else if (keep == Py_None) /* Nothing to keep */ - Py_DECREF(keep); - else if (setfunc != _ctypes_get_fielddesc("O")->setfunc) { - if (-1 == PyErr_WarnEx(PyExc_RuntimeWarning, - "memory leak in callback function.", - 1)) - PyErr_WriteUnraisable(callable); - } - } - Py_XDECREF(result); + /* See the corresponding code in callproc.c, around line 961 */ + if (restype->type != FFI_TYPE_FLOAT && restype->size < sizeof(ffi_arg)) + mem = (char *)mem + sizeof(ffi_arg) - restype->size; +#endif + keep = setfunc(mem, result, 0); + CHECK("'converting callback result'", keep); + /* keep is an object we have to keep alive so that the result + stays valid. If there is no such object, the setfunc will + have returned Py_None. + + If there is such an object, we have no choice than to keep + it alive forever - but a refcount and/or memory leak will + be the result. EXCEPT when restype is py_object - Python + itself knows how to manage the refcount of these objects. + */ + if (keep == NULL) /* Could not convert callback result. */ + PyErr_WriteUnraisable(callable); + else if (keep == Py_None) /* Nothing to keep */ + Py_DECREF(keep); + else if (setfunc != _ctypes_get_fielddesc("O")->setfunc) { + if (-1 == PyErr_WarnEx(PyExc_RuntimeWarning, + "memory leak in callback function.", + 1)) + PyErr_WriteUnraisable(callable); + } + } + Py_XDECREF(result); Done: - Py_XDECREF(arglist); + Py_XDECREF(arglist); #ifdef WITH_THREAD - PyGILState_Release(state); + PyGILState_Release(state); #endif } static void closure_fcn(ffi_cif *cif, - void *resp, - void **args, - void *userdata) -{ - CThunkObject *p = (CThunkObject *)userdata; - - _CallPythonObject(resp, - p->ffi_restype, - p->setfunc, - p->callable, - p->converters, - p->flags, - args); + void *resp, + void **args, + void *userdata) +{ + CThunkObject *p = (CThunkObject *)userdata; + + _CallPythonObject(resp, + p->ffi_restype, + p->setfunc, + p->callable, + p->converters, + p->flags, + args); } static CThunkObject* CThunkObject_new(Py_ssize_t nArgs) { - CThunkObject *p; - int i; + CThunkObject *p; + int i; - p = PyObject_GC_NewVar(CThunkObject, &PyCThunk_Type, nArgs); - if (p == NULL) { - PyErr_NoMemory(); - return NULL; - } - - p->pcl = NULL; - memset(&p->cif, 0, sizeof(p->cif)); - p->converters = NULL; - p->callable = NULL; - p->setfunc = NULL; - p->ffi_restype = NULL; - - for (i = 0; i < nArgs + 1; ++i) - p->atypes[i] = NULL; - PyObject_GC_Track((PyObject *)p); - return p; + p = PyObject_GC_NewVar(CThunkObject, &PyCThunk_Type, nArgs); + if (p == NULL) { + PyErr_NoMemory(); + return NULL; + } + + p->pcl = NULL; + memset(&p->cif, 0, sizeof(p->cif)); + p->converters = NULL; + p->callable = NULL; + p->setfunc = NULL; + p->ffi_restype = NULL; + + for (i = 0; i < nArgs + 1; ++i) + p->atypes[i] = NULL; + PyObject_GC_Track((PyObject *)p); + return p; } CThunkObject *_ctypes_alloc_callback(PyObject *callable, - PyObject *converters, - PyObject *restype, - int flags) -{ - int result; - CThunkObject *p; - Py_ssize_t nArgs, i; - ffi_abi cc; - - nArgs = PySequence_Size(converters); - p = CThunkObject_new(nArgs); - if (p == NULL) - return NULL; - - assert(CThunk_CheckExact((PyObject *)p)); - - p->pcl = _ctypes_alloc_closure(); - if (p->pcl == NULL) { - PyErr_NoMemory(); - goto error; - } - - p->flags = flags; - for (i = 0; i < nArgs; ++i) { - PyObject *cnv = PySequence_GetItem(converters, i); - if (cnv == NULL) - goto error; - p->atypes[i] = _ctypes_get_ffi_type(cnv); - Py_DECREF(cnv); - } - p->atypes[i] = NULL; - - Py_INCREF(restype); - p->restype = restype; - if (restype == Py_None) { - p->setfunc = NULL; - p->ffi_restype = &ffi_type_void; - } else { - StgDictObject *dict = PyType_stgdict(restype); - if (dict == NULL || dict->setfunc == NULL) { - PyErr_SetString(PyExc_TypeError, - "invalid result type for callback function"); - goto error; - } - p->setfunc = dict->setfunc; - p->ffi_restype = &dict->ffi_type_pointer; - } + PyObject *converters, + PyObject *restype, + int flags) +{ + int result; + CThunkObject *p; + Py_ssize_t nArgs, i; + ffi_abi cc; + + nArgs = PySequence_Size(converters); + p = CThunkObject_new(nArgs); + if (p == NULL) + return NULL; + + assert(CThunk_CheckExact((PyObject *)p)); + + p->pcl = _ctypes_alloc_closure(); + if (p->pcl == NULL) { + PyErr_NoMemory(); + goto error; + } + + p->flags = flags; + for (i = 0; i < nArgs; ++i) { + PyObject *cnv = PySequence_GetItem(converters, i); + if (cnv == NULL) + goto error; + p->atypes[i] = _ctypes_get_ffi_type(cnv); + Py_DECREF(cnv); + } + p->atypes[i] = NULL; + + Py_INCREF(restype); + p->restype = restype; + if (restype == Py_None) { + p->setfunc = NULL; + p->ffi_restype = &ffi_type_void; + } else { + StgDictObject *dict = PyType_stgdict(restype); + if (dict == NULL || dict->setfunc == NULL) { + PyErr_SetString(PyExc_TypeError, + "invalid result type for callback function"); + goto error; + } + p->setfunc = dict->setfunc; + p->ffi_restype = &dict->ffi_type_pointer; + } - cc = FFI_DEFAULT_ABI; + cc = FFI_DEFAULT_ABI; #if defined(MS_WIN32) && !defined(_WIN32_WCE) && !defined(MS_WIN64) - if ((flags & FUNCFLAG_CDECL) == 0) - cc = FFI_STDCALL; + if ((flags & FUNCFLAG_CDECL) == 0) + cc = FFI_STDCALL; #endif - result = ffi_prep_cif(&p->cif, cc, - Py_SAFE_DOWNCAST(nArgs, Py_ssize_t, int), - _ctypes_get_ffi_type(restype), - &p->atypes[0]); - if (result != FFI_OK) { - PyErr_Format(PyExc_RuntimeError, - "ffi_prep_cif failed with %d", result); - goto error; - } - result = ffi_prep_closure(p->pcl, &p->cif, closure_fcn, p); - if (result != FFI_OK) { - PyErr_Format(PyExc_RuntimeError, - "ffi_prep_closure failed with %d", result); - goto error; - } - - Py_INCREF(converters); - p->converters = converters; - Py_INCREF(callable); - p->callable = callable; - return p; + result = ffi_prep_cif(&p->cif, cc, + Py_SAFE_DOWNCAST(nArgs, Py_ssize_t, int), + _ctypes_get_ffi_type(restype), + &p->atypes[0]); + if (result != FFI_OK) { + PyErr_Format(PyExc_RuntimeError, + "ffi_prep_cif failed with %d", result); + goto error; + } + result = ffi_prep_closure(p->pcl, &p->cif, closure_fcn, p); + if (result != FFI_OK) { + PyErr_Format(PyExc_RuntimeError, + "ffi_prep_closure failed with %d", result); + goto error; + } + + Py_INCREF(converters); + p->converters = converters; + Py_INCREF(callable); + p->callable = callable; + return p; error: - Py_XDECREF(p); - return NULL; + Py_XDECREF(p); + return NULL; } #ifdef MS_WIN32 static void LoadPython(void) { - if (!Py_IsInitialized()) { + if (!Py_IsInitialized()) { #ifdef WITH_THREAD - PyEval_InitThreads(); + PyEval_InitThreads(); #endif - Py_Initialize(); - } + Py_Initialize(); + } } /******************************************************************/ long Call_GetClassObject(REFCLSID rclsid, REFIID riid, LPVOID *ppv) { - PyObject *mod, *func, *result; - long retval; - static PyObject *context; - - if (context == NULL) - context = PyUnicode_InternFromString("_ctypes.DllGetClassObject"); - - mod = PyImport_ImportModuleNoBlock("ctypes"); - if (!mod) { - PyErr_WriteUnraisable(context ? context : Py_None); - /* There has been a warning before about this already */ - return E_FAIL; - } - - func = PyObject_GetAttrString(mod, "DllGetClassObject"); - Py_DECREF(mod); - if (!func) { - PyErr_WriteUnraisable(context ? context : Py_None); - return E_FAIL; - } - - { - PyObject *py_rclsid = PyLong_FromVoidPtr((void *)rclsid); - PyObject *py_riid = PyLong_FromVoidPtr((void *)riid); - PyObject *py_ppv = PyLong_FromVoidPtr(ppv); - if (!py_rclsid || !py_riid || !py_ppv) { - Py_XDECREF(py_rclsid); - Py_XDECREF(py_riid); - Py_XDECREF(py_ppv); - Py_DECREF(func); - PyErr_WriteUnraisable(context ? context : Py_None); - return E_FAIL; - } - result = PyObject_CallFunctionObjArgs(func, - py_rclsid, - py_riid, - py_ppv, - NULL); - Py_DECREF(py_rclsid); - Py_DECREF(py_riid); - Py_DECREF(py_ppv); - } - Py_DECREF(func); - if (!result) { - PyErr_WriteUnraisable(context ? context : Py_None); - return E_FAIL; - } - - retval = PyLong_AsLong(result); - if (PyErr_Occurred()) { - PyErr_WriteUnraisable(context ? context : Py_None); - retval = E_FAIL; - } - Py_DECREF(result); - return retval; + PyObject *mod, *func, *result; + long retval; + static PyObject *context; + + if (context == NULL) + context = PyUnicode_InternFromString("_ctypes.DllGetClassObject"); + + mod = PyImport_ImportModuleNoBlock("ctypes"); + if (!mod) { + PyErr_WriteUnraisable(context ? context : Py_None); + /* There has been a warning before about this already */ + return E_FAIL; + } + + func = PyObject_GetAttrString(mod, "DllGetClassObject"); + Py_DECREF(mod); + if (!func) { + PyErr_WriteUnraisable(context ? context : Py_None); + return E_FAIL; + } + + { + PyObject *py_rclsid = PyLong_FromVoidPtr((void *)rclsid); + PyObject *py_riid = PyLong_FromVoidPtr((void *)riid); + PyObject *py_ppv = PyLong_FromVoidPtr(ppv); + if (!py_rclsid || !py_riid || !py_ppv) { + Py_XDECREF(py_rclsid); + Py_XDECREF(py_riid); + Py_XDECREF(py_ppv); + Py_DECREF(func); + PyErr_WriteUnraisable(context ? context : Py_None); + return E_FAIL; + } + result = PyObject_CallFunctionObjArgs(func, + py_rclsid, + py_riid, + py_ppv, + NULL); + Py_DECREF(py_rclsid); + Py_DECREF(py_riid); + Py_DECREF(py_ppv); + } + Py_DECREF(func); + if (!result) { + PyErr_WriteUnraisable(context ? context : Py_None); + return E_FAIL; + } + + retval = PyLong_AsLong(result); + if (PyErr_Occurred()) { + PyErr_WriteUnraisable(context ? context : Py_None); + retval = E_FAIL; + } + Py_DECREF(result); + return retval; } STDAPI DllGetClassObject(REFCLSID rclsid, - REFIID riid, - LPVOID *ppv) + REFIID riid, + LPVOID *ppv) { - long result; + long result; #ifdef WITH_THREAD - PyGILState_STATE state; + PyGILState_STATE state; #endif - LoadPython(); + LoadPython(); #ifdef WITH_THREAD - state = PyGILState_Ensure(); + state = PyGILState_Ensure(); #endif - result = Call_GetClassObject(rclsid, riid, ppv); + result = Call_GetClassObject(rclsid, riid, ppv); #ifdef WITH_THREAD - PyGILState_Release(state); + PyGILState_Release(state); #endif - return result; + return result; } long Call_CanUnloadNow(void) { - PyObject *mod, *func, *result; - long retval; - static PyObject *context; - - if (context == NULL) - context = PyUnicode_InternFromString("_ctypes.DllCanUnloadNow"); - - mod = PyImport_ImportModuleNoBlock("ctypes"); - if (!mod) { -/* OutputDebugString("Could not import ctypes"); */ - /* We assume that this error can only occur when shutting - down, so we silently ignore it */ - PyErr_Clear(); - return E_FAIL; - } - /* Other errors cannot be raised, but are printed to stderr */ - func = PyObject_GetAttrString(mod, "DllCanUnloadNow"); - Py_DECREF(mod); - if (!func) { - PyErr_WriteUnraisable(context ? context : Py_None); - return E_FAIL; - } - - result = PyObject_CallFunction(func, NULL); - Py_DECREF(func); - if (!result) { - PyErr_WriteUnraisable(context ? context : Py_None); - return E_FAIL; - } - - retval = PyLong_AsLong(result); - if (PyErr_Occurred()) { - PyErr_WriteUnraisable(context ? context : Py_None); - retval = E_FAIL; - } - Py_DECREF(result); - return retval; + PyObject *mod, *func, *result; + long retval; + static PyObject *context; + + if (context == NULL) + context = PyUnicode_InternFromString("_ctypes.DllCanUnloadNow"); + + mod = PyImport_ImportModuleNoBlock("ctypes"); + if (!mod) { +/* OutputDebugString("Could not import ctypes"); */ + /* We assume that this error can only occur when shutting + down, so we silently ignore it */ + PyErr_Clear(); + return E_FAIL; + } + /* Other errors cannot be raised, but are printed to stderr */ + func = PyObject_GetAttrString(mod, "DllCanUnloadNow"); + Py_DECREF(mod); + if (!func) { + PyErr_WriteUnraisable(context ? context : Py_None); + return E_FAIL; + } + + result = PyObject_CallFunction(func, NULL); + Py_DECREF(func); + if (!result) { + PyErr_WriteUnraisable(context ? context : Py_None); + return E_FAIL; + } + + retval = PyLong_AsLong(result); + if (PyErr_Occurred()) { + PyErr_WriteUnraisable(context ? context : Py_None); + retval = E_FAIL; + } + Py_DECREF(result); + return retval; } /* @@ -572,26 +572,26 @@ STDAPI DllCanUnloadNow(void) { - long result; + long result; #ifdef WITH_THREAD - PyGILState_STATE state = PyGILState_Ensure(); + PyGILState_STATE state = PyGILState_Ensure(); #endif - result = Call_CanUnloadNow(); + result = Call_CanUnloadNow(); #ifdef WITH_THREAD - PyGILState_Release(state); + PyGILState_Release(state); #endif - return result; + return result; } #ifndef Py_NO_ENABLE_SHARED BOOL WINAPI DllMain(HINSTANCE hinstDLL, DWORD fdwReason, LPVOID lpvRes) { - switch(fdwReason) { - case DLL_PROCESS_ATTACH: - DisableThreadLibraryCalls(hinstDLL); - break; - } - return TRUE; + switch(fdwReason) { + case DLL_PROCESS_ATTACH: + DisableThreadLibraryCalls(hinstDLL); + break; + } + return TRUE; } #endif Modified: python/branches/py3k-jit/Modules/_ctypes/callproc.c ============================================================================== --- python/branches/py3k-jit/Modules/_ctypes/callproc.c (original) +++ python/branches/py3k-jit/Modules/_ctypes/callproc.c Mon May 10 23:55:43 2010 @@ -4,9 +4,9 @@ */ /* * Related Work: - * - calldll http://www.nightmare.com/software.html - * - libffi http://sourceware.cygnus.com/libffi/ - * - ffcall http://clisp.cons.org/~haible/packages-ffcall.html + * - calldll http://www.nightmare.com/software.html + * - libffi http://sourceware.cygnus.com/libffi/ + * - ffcall http://clisp.cons.org/~haible/packages-ffcall.html * and, of course, Don Beaudry's MESS package, but this is more ctypes * related. */ @@ -82,17 +82,17 @@ static void pymem_destructor(PyObject *ptr) { - void *p = PyCapsule_GetPointer(ptr, CTYPES_CAPSULE_NAME_PYMEM); - if (p) { - PyMem_Free(p); - } + void *p = PyCapsule_GetPointer(ptr, CTYPES_CAPSULE_NAME_PYMEM); + if (p) { + PyMem_Free(p); + } } /* ctypes maintains thread-local storage that has space for two error numbers: private copies of the system 'errno' value and, on Windows, the system error code accessed by the GetLastError() and SetLastError() api functions. - + Foreign functions created with CDLL(..., use_errno=True), when called, swap the system 'errno' value with the private copy just before the actual function call, and swapped again immediately afterwards. The 'use_errno' @@ -125,88 +125,88 @@ PyObject * _ctypes_get_errobj(int **pspace) { - PyObject *dict = PyThreadState_GetDict(); - PyObject *errobj; - static PyObject *error_object_name; - if (dict == 0) { - PyErr_SetString(PyExc_RuntimeError, - "cannot get thread state"); - return NULL; - } - if (error_object_name == NULL) { - error_object_name = PyUnicode_InternFromString("ctypes.error_object"); - if (error_object_name == NULL) - return NULL; - } - errobj = PyDict_GetItem(dict, error_object_name); - if (errobj) { - if (!PyCapsule_IsValid(errobj, CTYPES_CAPSULE_NAME_PYMEM)) { - PyErr_SetString(PyExc_RuntimeError, - "ctypes.error_object is an invalid capsule"); - return NULL; - } - Py_INCREF(errobj); - } - else { - void *space = PyMem_Malloc(sizeof(int) * 2); - if (space == NULL) - return NULL; - memset(space, 0, sizeof(int) * 2); - errobj = PyCapsule_New(space, CTYPES_CAPSULE_NAME_PYMEM, pymem_destructor); - if (errobj == NULL) - return NULL; - if (-1 == PyDict_SetItem(dict, error_object_name, - errobj)) { - Py_DECREF(errobj); - return NULL; - } - } - *pspace = (int *)PyCapsule_GetPointer(errobj, CTYPES_CAPSULE_NAME_PYMEM); - return errobj; + PyObject *dict = PyThreadState_GetDict(); + PyObject *errobj; + static PyObject *error_object_name; + if (dict == 0) { + PyErr_SetString(PyExc_RuntimeError, + "cannot get thread state"); + return NULL; + } + if (error_object_name == NULL) { + error_object_name = PyUnicode_InternFromString("ctypes.error_object"); + if (error_object_name == NULL) + return NULL; + } + errobj = PyDict_GetItem(dict, error_object_name); + if (errobj) { + if (!PyCapsule_IsValid(errobj, CTYPES_CAPSULE_NAME_PYMEM)) { + PyErr_SetString(PyExc_RuntimeError, + "ctypes.error_object is an invalid capsule"); + return NULL; + } + Py_INCREF(errobj); + } + else { + void *space = PyMem_Malloc(sizeof(int) * 2); + if (space == NULL) + return NULL; + memset(space, 0, sizeof(int) * 2); + errobj = PyCapsule_New(space, CTYPES_CAPSULE_NAME_PYMEM, pymem_destructor); + if (errobj == NULL) + return NULL; + if (-1 == PyDict_SetItem(dict, error_object_name, + errobj)) { + Py_DECREF(errobj); + return NULL; + } + } + *pspace = (int *)PyCapsule_GetPointer(errobj, CTYPES_CAPSULE_NAME_PYMEM); + return errobj; } static PyObject * get_error_internal(PyObject *self, PyObject *args, int index) { - int *space; - PyObject *errobj = _ctypes_get_errobj(&space); - PyObject *result; - - if (errobj == NULL) - return NULL; - result = PyLong_FromLong(space[index]); - Py_DECREF(errobj); - return result; + int *space; + PyObject *errobj = _ctypes_get_errobj(&space); + PyObject *result; + + if (errobj == NULL) + return NULL; + result = PyLong_FromLong(space[index]); + Py_DECREF(errobj); + return result; } static PyObject * set_error_internal(PyObject *self, PyObject *args, int index) { - int new_errno, old_errno; - PyObject *errobj; - int *space; - - if (!PyArg_ParseTuple(args, "i", &new_errno)) - return NULL; - errobj = _ctypes_get_errobj(&space); - if (errobj == NULL) - return NULL; - old_errno = space[index]; - space[index] = new_errno; - Py_DECREF(errobj); - return PyLong_FromLong(old_errno); + int new_errno, old_errno; + PyObject *errobj; + int *space; + + if (!PyArg_ParseTuple(args, "i", &new_errno)) + return NULL; + errobj = _ctypes_get_errobj(&space); + if (errobj == NULL) + return NULL; + old_errno = space[index]; + space[index] = new_errno; + Py_DECREF(errobj); + return PyLong_FromLong(old_errno); } static PyObject * get_errno(PyObject *self, PyObject *args) { - return get_error_internal(self, args, 0); + return get_error_internal(self, args, 0); } static PyObject * set_errno(PyObject *self, PyObject *args) { - return set_error_internal(self, args, 0); + return set_error_internal(self, args, 0); } #ifdef MS_WIN32 @@ -214,202 +214,202 @@ static PyObject * get_last_error(PyObject *self, PyObject *args) { - return get_error_internal(self, args, 1); + return get_error_internal(self, args, 1); } static PyObject * set_last_error(PyObject *self, PyObject *args) { - return set_error_internal(self, args, 1); + return set_error_internal(self, args, 1); } PyObject *ComError; static WCHAR *FormatError(DWORD code) { - WCHAR *lpMsgBuf; - DWORD n; - n = FormatMessageW(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM, - NULL, - code, - MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), /* Default language */ - (LPWSTR) &lpMsgBuf, - 0, - NULL); - if (n) { - while (iswspace(lpMsgBuf[n-1])) - --n; - lpMsgBuf[n] = L'\0'; /* rstrip() */ - } - return lpMsgBuf; + WCHAR *lpMsgBuf; + DWORD n; + n = FormatMessageW(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM, + NULL, + code, + MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), /* Default language */ + (LPWSTR) &lpMsgBuf, + 0, + NULL); + if (n) { + while (iswspace(lpMsgBuf[n-1])) + --n; + lpMsgBuf[n] = L'\0'; /* rstrip() */ + } + return lpMsgBuf; } #ifndef DONT_USE_SEH static void SetException(DWORD code, EXCEPTION_RECORD *pr) { - /* The 'code' is a normal win32 error code so it could be handled by - PyErr_SetFromWindowsErr(). However, for some errors, we have additional - information not included in the error code. We handle those here and - delegate all others to the generic function. */ - switch (code) { - case EXCEPTION_ACCESS_VIOLATION: - /* The thread attempted to read from or write - to a virtual address for which it does not - have the appropriate access. */ - if (pr->ExceptionInformation[0] == 0) - PyErr_Format(PyExc_WindowsError, - "exception: access violation reading %p", - pr->ExceptionInformation[1]); - else - PyErr_Format(PyExc_WindowsError, - "exception: access violation writing %p", - pr->ExceptionInformation[1]); - break; - - case EXCEPTION_BREAKPOINT: - /* A breakpoint was encountered. */ - PyErr_SetString(PyExc_WindowsError, - "exception: breakpoint encountered"); - break; - - case EXCEPTION_DATATYPE_MISALIGNMENT: - /* The thread attempted to read or write data that is - misaligned on hardware that does not provide - alignment. For example, 16-bit values must be - aligned on 2-byte boundaries, 32-bit values on - 4-byte boundaries, and so on. */ - PyErr_SetString(PyExc_WindowsError, - "exception: datatype misalignment"); - break; - - case EXCEPTION_SINGLE_STEP: - /* A trace trap or other single-instruction mechanism - signaled that one instruction has been executed. */ - PyErr_SetString(PyExc_WindowsError, - "exception: single step"); - break; - - case EXCEPTION_ARRAY_BOUNDS_EXCEEDED: - /* The thread attempted to access an array element - that is out of bounds, and the underlying hardware - supports bounds checking. */ - PyErr_SetString(PyExc_WindowsError, - "exception: array bounds exceeded"); - break; - - case EXCEPTION_FLT_DENORMAL_OPERAND: - /* One of the operands in a floating-point operation - is denormal. A denormal value is one that is too - small to represent as a standard floating-point - value. */ - PyErr_SetString(PyExc_WindowsError, - "exception: floating-point operand denormal"); - break; - - case EXCEPTION_FLT_DIVIDE_BY_ZERO: - /* The thread attempted to divide a floating-point - value by a floating-point divisor of zero. */ - PyErr_SetString(PyExc_WindowsError, - "exception: float divide by zero"); - break; - - case EXCEPTION_FLT_INEXACT_RESULT: - /* The result of a floating-point operation cannot be - represented exactly as a decimal fraction. */ - PyErr_SetString(PyExc_WindowsError, - "exception: float inexact"); - break; - - case EXCEPTION_FLT_INVALID_OPERATION: - /* This exception represents any floating-point - exception not included in this list. */ - PyErr_SetString(PyExc_WindowsError, - "exception: float invalid operation"); - break; - - case EXCEPTION_FLT_OVERFLOW: - /* The exponent of a floating-point operation is - greater than the magnitude allowed by the - corresponding type. */ - PyErr_SetString(PyExc_WindowsError, - "exception: float overflow"); - break; - - case EXCEPTION_FLT_STACK_CHECK: - /* The stack overflowed or underflowed as the result - of a floating-point operation. */ - PyErr_SetString(PyExc_WindowsError, - "exception: stack over/underflow"); - break; - - case EXCEPTION_STACK_OVERFLOW: - /* The stack overflowed or underflowed as the result - of a floating-point operation. */ - PyErr_SetString(PyExc_WindowsError, - "exception: stack overflow"); - break; - - case EXCEPTION_FLT_UNDERFLOW: - /* The exponent of a floating-point operation is less - than the magnitude allowed by the corresponding - type. */ - PyErr_SetString(PyExc_WindowsError, - "exception: float underflow"); - break; - - case EXCEPTION_INT_DIVIDE_BY_ZERO: - /* The thread attempted to divide an integer value by - an integer divisor of zero. */ - PyErr_SetString(PyExc_WindowsError, - "exception: integer divide by zero"); - break; - - case EXCEPTION_INT_OVERFLOW: - /* The result of an integer operation caused a carry - out of the most significant bit of the result. */ - PyErr_SetString(PyExc_WindowsError, - "exception: integer overflow"); - break; - - case EXCEPTION_PRIV_INSTRUCTION: - /* The thread attempted to execute an instruction - whose operation is not allowed in the current - machine mode. */ - PyErr_SetString(PyExc_WindowsError, - "exception: priviledged instruction"); - break; - - case EXCEPTION_NONCONTINUABLE_EXCEPTION: - /* The thread attempted to continue execution after a - noncontinuable exception occurred. */ - PyErr_SetString(PyExc_WindowsError, - "exception: nocontinuable"); - break; - - default: - PyErr_SetFromWindowsErr(code); - break; - } + /* The 'code' is a normal win32 error code so it could be handled by + PyErr_SetFromWindowsErr(). However, for some errors, we have additional + information not included in the error code. We handle those here and + delegate all others to the generic function. */ + switch (code) { + case EXCEPTION_ACCESS_VIOLATION: + /* The thread attempted to read from or write + to a virtual address for which it does not + have the appropriate access. */ + if (pr->ExceptionInformation[0] == 0) + PyErr_Format(PyExc_WindowsError, + "exception: access violation reading %p", + pr->ExceptionInformation[1]); + else + PyErr_Format(PyExc_WindowsError, + "exception: access violation writing %p", + pr->ExceptionInformation[1]); + break; + + case EXCEPTION_BREAKPOINT: + /* A breakpoint was encountered. */ + PyErr_SetString(PyExc_WindowsError, + "exception: breakpoint encountered"); + break; + + case EXCEPTION_DATATYPE_MISALIGNMENT: + /* The thread attempted to read or write data that is + misaligned on hardware that does not provide + alignment. For example, 16-bit values must be + aligned on 2-byte boundaries, 32-bit values on + 4-byte boundaries, and so on. */ + PyErr_SetString(PyExc_WindowsError, + "exception: datatype misalignment"); + break; + + case EXCEPTION_SINGLE_STEP: + /* A trace trap or other single-instruction mechanism + signaled that one instruction has been executed. */ + PyErr_SetString(PyExc_WindowsError, + "exception: single step"); + break; + + case EXCEPTION_ARRAY_BOUNDS_EXCEEDED: + /* The thread attempted to access an array element + that is out of bounds, and the underlying hardware + supports bounds checking. */ + PyErr_SetString(PyExc_WindowsError, + "exception: array bounds exceeded"); + break; + + case EXCEPTION_FLT_DENORMAL_OPERAND: + /* One of the operands in a floating-point operation + is denormal. A denormal value is one that is too + small to represent as a standard floating-point + value. */ + PyErr_SetString(PyExc_WindowsError, + "exception: floating-point operand denormal"); + break; + + case EXCEPTION_FLT_DIVIDE_BY_ZERO: + /* The thread attempted to divide a floating-point + value by a floating-point divisor of zero. */ + PyErr_SetString(PyExc_WindowsError, + "exception: float divide by zero"); + break; + + case EXCEPTION_FLT_INEXACT_RESULT: + /* The result of a floating-point operation cannot be + represented exactly as a decimal fraction. */ + PyErr_SetString(PyExc_WindowsError, + "exception: float inexact"); + break; + + case EXCEPTION_FLT_INVALID_OPERATION: + /* This exception represents any floating-point + exception not included in this list. */ + PyErr_SetString(PyExc_WindowsError, + "exception: float invalid operation"); + break; + + case EXCEPTION_FLT_OVERFLOW: + /* The exponent of a floating-point operation is + greater than the magnitude allowed by the + corresponding type. */ + PyErr_SetString(PyExc_WindowsError, + "exception: float overflow"); + break; + + case EXCEPTION_FLT_STACK_CHECK: + /* The stack overflowed or underflowed as the result + of a floating-point operation. */ + PyErr_SetString(PyExc_WindowsError, + "exception: stack over/underflow"); + break; + + case EXCEPTION_STACK_OVERFLOW: + /* The stack overflowed or underflowed as the result + of a floating-point operation. */ + PyErr_SetString(PyExc_WindowsError, + "exception: stack overflow"); + break; + + case EXCEPTION_FLT_UNDERFLOW: + /* The exponent of a floating-point operation is less + than the magnitude allowed by the corresponding + type. */ + PyErr_SetString(PyExc_WindowsError, + "exception: float underflow"); + break; + + case EXCEPTION_INT_DIVIDE_BY_ZERO: + /* The thread attempted to divide an integer value by + an integer divisor of zero. */ + PyErr_SetString(PyExc_WindowsError, + "exception: integer divide by zero"); + break; + + case EXCEPTION_INT_OVERFLOW: + /* The result of an integer operation caused a carry + out of the most significant bit of the result. */ + PyErr_SetString(PyExc_WindowsError, + "exception: integer overflow"); + break; + + case EXCEPTION_PRIV_INSTRUCTION: + /* The thread attempted to execute an instruction + whose operation is not allowed in the current + machine mode. */ + PyErr_SetString(PyExc_WindowsError, + "exception: priviledged instruction"); + break; + + case EXCEPTION_NONCONTINUABLE_EXCEPTION: + /* The thread attempted to continue execution after a + noncontinuable exception occurred. */ + PyErr_SetString(PyExc_WindowsError, + "exception: nocontinuable"); + break; + + default: + PyErr_SetFromWindowsErr(code); + break; + } } static DWORD HandleException(EXCEPTION_POINTERS *ptrs, - DWORD *pdw, EXCEPTION_RECORD *record) + DWORD *pdw, EXCEPTION_RECORD *record) { - *pdw = ptrs->ExceptionRecord->ExceptionCode; - *record = *ptrs->ExceptionRecord; - return EXCEPTION_EXECUTE_HANDLER; + *pdw = ptrs->ExceptionRecord->ExceptionCode; + *record = *ptrs->ExceptionRecord; + return EXCEPTION_EXECUTE_HANDLER; } #endif static PyObject * check_hresult(PyObject *self, PyObject *args) { - HRESULT hr; - if (!PyArg_ParseTuple(args, "i", &hr)) - return NULL; - if (FAILED(hr)) - return PyErr_SetFromWindowsErr(hr); - return PyLong_FromLong(hr); + HRESULT hr; + if (!PyArg_ParseTuple(args, "i", &hr)) + return NULL; + if (FAILED(hr)) + return PyErr_SetFromWindowsErr(hr); + return PyLong_FromLong(hr); } #endif @@ -419,132 +419,132 @@ PyCArgObject * PyCArgObject_new(void) { - PyCArgObject *p; - p = PyObject_New(PyCArgObject, &PyCArg_Type); - if (p == NULL) - return NULL; - p->pffi_type = NULL; - p->tag = '\0'; - p->obj = NULL; - memset(&p->value, 0, sizeof(p->value)); - return p; + PyCArgObject *p; + p = PyObject_New(PyCArgObject, &PyCArg_Type); + if (p == NULL) + return NULL; + p->pffi_type = NULL; + p->tag = '\0'; + p->obj = NULL; + memset(&p->value, 0, sizeof(p->value)); + return p; } static void PyCArg_dealloc(PyCArgObject *self) { - Py_XDECREF(self->obj); - PyObject_Del(self); + Py_XDECREF(self->obj); + PyObject_Del(self); } static PyObject * PyCArg_repr(PyCArgObject *self) { - char buffer[256]; - switch(self->tag) { - case 'b': - case 'B': - sprintf(buffer, "", - self->tag, self->value.b); - break; - case 'h': - case 'H': - sprintf(buffer, "", - self->tag, self->value.h); - break; - case 'i': - case 'I': - sprintf(buffer, "", - self->tag, self->value.i); - break; - case 'l': - case 'L': - sprintf(buffer, "", - self->tag, self->value.l); - break; - + char buffer[256]; + switch(self->tag) { + case 'b': + case 'B': + sprintf(buffer, "", + self->tag, self->value.b); + break; + case 'h': + case 'H': + sprintf(buffer, "", + self->tag, self->value.h); + break; + case 'i': + case 'I': + sprintf(buffer, "", + self->tag, self->value.i); + break; + case 'l': + case 'L': + sprintf(buffer, "", + self->tag, self->value.l); + break; + #ifdef HAVE_LONG_LONG - case 'q': - case 'Q': - sprintf(buffer, + case 'q': + case 'Q': + sprintf(buffer, #ifdef MS_WIN32 - "", + "", #else - "", + "", #endif - self->tag, self->value.q); - break; + self->tag, self->value.q); + break; #endif - case 'd': - sprintf(buffer, "", - self->tag, self->value.d); - break; - case 'f': - sprintf(buffer, "", - self->tag, self->value.f); - break; - - case 'c': - sprintf(buffer, "", - self->tag, self->value.c); - break; + case 'd': + sprintf(buffer, "", + self->tag, self->value.d); + break; + case 'f': + sprintf(buffer, "", + self->tag, self->value.f); + break; + + case 'c': + sprintf(buffer, "", + self->tag, self->value.c); + break; /* Hm, are these 'z' and 'Z' codes useful at all? Shouldn't they be replaced by the functionality of c_string and c_wstring ? */ - case 'z': - case 'Z': - case 'P': - sprintf(buffer, "", - self->tag, self->value.p); - break; - - default: - sprintf(buffer, "", - self->tag, self); - break; - } - return PyUnicode_FromString(buffer); + case 'z': + case 'Z': + case 'P': + sprintf(buffer, "", + self->tag, self->value.p); + break; + + default: + sprintf(buffer, "", + self->tag, self); + break; + } + return PyUnicode_FromString(buffer); } static PyMemberDef PyCArgType_members[] = { - { "_obj", T_OBJECT, - offsetof(PyCArgObject, obj), READONLY, - "the wrapped object" }, - { NULL }, + { "_obj", T_OBJECT, + offsetof(PyCArgObject, obj), READONLY, + "the wrapped object" }, + { NULL }, }; PyTypeObject PyCArg_Type = { - PyVarObject_HEAD_INIT(NULL, 0) - "CArgObject", - sizeof(PyCArgObject), - 0, - (destructor)PyCArg_dealloc, /* tp_dealloc */ - 0, /* tp_print */ - 0, /* tp_getattr */ - 0, /* tp_setattr */ - 0, /* tp_reserved */ - (reprfunc)PyCArg_repr, /* tp_repr */ - 0, /* tp_as_number */ - 0, /* tp_as_sequence */ - 0, /* tp_as_mapping */ - 0, /* tp_hash */ - 0, /* tp_call */ - 0, /* tp_str */ - 0, /* tp_getattro */ - 0, /* tp_setattro */ - 0, /* tp_as_buffer */ - Py_TPFLAGS_DEFAULT, /* tp_flags */ - 0, /* tp_doc */ - 0, /* tp_traverse */ - 0, /* tp_clear */ - 0, /* tp_richcompare */ - 0, /* tp_weaklistoffset */ - 0, /* tp_iter */ - 0, /* tp_iternext */ - 0, /* tp_methods */ - PyCArgType_members, /* tp_members */ + PyVarObject_HEAD_INIT(NULL, 0) + "CArgObject", + sizeof(PyCArgObject), + 0, + (destructor)PyCArg_dealloc, /* tp_dealloc */ + 0, /* tp_print */ + 0, /* tp_getattr */ + 0, /* tp_setattr */ + 0, /* tp_reserved */ + (reprfunc)PyCArg_repr, /* tp_repr */ + 0, /* tp_as_number */ + 0, /* tp_as_sequence */ + 0, /* tp_as_mapping */ + 0, /* tp_hash */ + 0, /* tp_call */ + 0, /* tp_str */ + 0, /* tp_getattro */ + 0, /* tp_setattro */ + 0, /* tp_as_buffer */ + Py_TPFLAGS_DEFAULT, /* tp_flags */ + 0, /* tp_doc */ + 0, /* tp_traverse */ + 0, /* tp_clear */ + 0, /* tp_richcompare */ + 0, /* tp_weaklistoffset */ + 0, /* tp_iter */ + 0, /* tp_iternext */ + 0, /* tp_methods */ + PyCArgType_members, /* tp_members */ }; /****************************************************************/ @@ -577,24 +577,24 @@ */ union result { - char c; - char b; - short h; - int i; - long l; + char c; + char b; + short h; + int i; + long l; #ifdef HAVE_LONG_LONG - PY_LONG_LONG q; + PY_LONG_LONG q; #endif - long double D; - double d; - float f; - void *p; + long double D; + double d; + float f; + void *p; }; struct argument { - ffi_type *ffi_type; - PyObject *keep; - union result value; + ffi_type *ffi_type; + PyObject *keep; + union result value; }; /* @@ -602,134 +602,134 @@ */ static int ConvParam(PyObject *obj, Py_ssize_t index, struct argument *pa) { - StgDictObject *dict; - pa->keep = NULL; /* so we cannot forget it later */ + StgDictObject *dict; + pa->keep = NULL; /* so we cannot forget it later */ - dict = PyObject_stgdict(obj); - if (dict) { - PyCArgObject *carg; - assert(dict->paramfunc); - /* If it has an stgdict, it is a CDataObject */ - carg = dict->paramfunc((CDataObject *)obj); - pa->ffi_type = carg->pffi_type; - memcpy(&pa->value, &carg->value, sizeof(pa->value)); - pa->keep = (PyObject *)carg; - return 0; - } - - if (PyCArg_CheckExact(obj)) { - PyCArgObject *carg = (PyCArgObject *)obj; - pa->ffi_type = carg->pffi_type; - Py_INCREF(obj); - pa->keep = obj; - memcpy(&pa->value, &carg->value, sizeof(pa->value)); - return 0; - } - - /* check for None, integer, string or unicode and use directly if successful */ - if (obj == Py_None) { - pa->ffi_type = &ffi_type_pointer; - pa->value.p = NULL; - return 0; - } - - if (PyLong_Check(obj)) { - pa->ffi_type = &ffi_type_sint; - pa->value.i = (long)PyLong_AsUnsignedLong(obj); - if (pa->value.i == -1 && PyErr_Occurred()) { - PyErr_Clear(); - pa->value.i = PyLong_AsLong(obj); - if (pa->value.i == -1 && PyErr_Occurred()) { - PyErr_SetString(PyExc_OverflowError, - "long int too long to convert"); - return -1; - } - } - return 0; - } - - if (PyBytes_Check(obj)) { - pa->ffi_type = &ffi_type_pointer; - pa->value.p = PyBytes_AsString(obj); - Py_INCREF(obj); - pa->keep = obj; - return 0; - } + dict = PyObject_stgdict(obj); + if (dict) { + PyCArgObject *carg; + assert(dict->paramfunc); + /* If it has an stgdict, it is a CDataObject */ + carg = dict->paramfunc((CDataObject *)obj); + pa->ffi_type = carg->pffi_type; + memcpy(&pa->value, &carg->value, sizeof(pa->value)); + pa->keep = (PyObject *)carg; + return 0; + } + + if (PyCArg_CheckExact(obj)) { + PyCArgObject *carg = (PyCArgObject *)obj; + pa->ffi_type = carg->pffi_type; + Py_INCREF(obj); + pa->keep = obj; + memcpy(&pa->value, &carg->value, sizeof(pa->value)); + return 0; + } + + /* check for None, integer, string or unicode and use directly if successful */ + if (obj == Py_None) { + pa->ffi_type = &ffi_type_pointer; + pa->value.p = NULL; + return 0; + } + + if (PyLong_Check(obj)) { + pa->ffi_type = &ffi_type_sint; + pa->value.i = (long)PyLong_AsUnsignedLong(obj); + if (pa->value.i == -1 && PyErr_Occurred()) { + PyErr_Clear(); + pa->value.i = PyLong_AsLong(obj); + if (pa->value.i == -1 && PyErr_Occurred()) { + PyErr_SetString(PyExc_OverflowError, + "long int too long to convert"); + return -1; + } + } + return 0; + } + + if (PyBytes_Check(obj)) { + pa->ffi_type = &ffi_type_pointer; + pa->value.p = PyBytes_AsString(obj); + Py_INCREF(obj); + pa->keep = obj; + return 0; + } #ifdef CTYPES_UNICODE - if (PyUnicode_Check(obj)) { + if (PyUnicode_Check(obj)) { #ifdef HAVE_USABLE_WCHAR_T - pa->ffi_type = &ffi_type_pointer; - pa->value.p = PyUnicode_AS_UNICODE(obj); - Py_INCREF(obj); - pa->keep = obj; - return 0; + pa->ffi_type = &ffi_type_pointer; + pa->value.p = PyUnicode_AS_UNICODE(obj); + Py_INCREF(obj); + pa->keep = obj; + return 0; #else - int size = PyUnicode_GET_SIZE(obj); - pa->ffi_type = &ffi_type_pointer; - size += 1; /* terminating NUL */ - size *= sizeof(wchar_t); - pa->value.p = PyMem_Malloc(size); - if (!pa->value.p) { - PyErr_NoMemory(); - return -1; - } - memset(pa->value.p, 0, size); - pa->keep = PyCapsule_New(pa->value.p, CTYPES_CAPSULE_NAME_PYMEM, pymem_destructor); - if (!pa->keep) { - PyMem_Free(pa->value.p); - return -1; - } - if (-1 == PyUnicode_AsWideChar((PyUnicodeObject *)obj, - pa->value.p, PyUnicode_GET_SIZE(obj))) - return -1; - return 0; -#endif - } -#endif - - { - PyObject *arg; - arg = PyObject_GetAttrString(obj, "_as_parameter_"); - /* Which types should we exactly allow here? - integers are required for using Python classes - as parameters (they have to expose the '_as_parameter_' - attribute) - */ - if (arg) { - int result; - result = ConvParam(arg, index, pa); - Py_DECREF(arg); - return result; - } - PyErr_Format(PyExc_TypeError, - "Don't know how to convert parameter %d", - Py_SAFE_DOWNCAST(index, Py_ssize_t, int)); - return -1; - } + int size = PyUnicode_GET_SIZE(obj); + pa->ffi_type = &ffi_type_pointer; + size += 1; /* terminating NUL */ + size *= sizeof(wchar_t); + pa->value.p = PyMem_Malloc(size); + if (!pa->value.p) { + PyErr_NoMemory(); + return -1; + } + memset(pa->value.p, 0, size); + pa->keep = PyCapsule_New(pa->value.p, CTYPES_CAPSULE_NAME_PYMEM, pymem_destructor); + if (!pa->keep) { + PyMem_Free(pa->value.p); + return -1; + } + if (-1 == PyUnicode_AsWideChar((PyUnicodeObject *)obj, + pa->value.p, PyUnicode_GET_SIZE(obj))) + return -1; + return 0; +#endif + } +#endif + + { + PyObject *arg; + arg = PyObject_GetAttrString(obj, "_as_parameter_"); + /* Which types should we exactly allow here? + integers are required for using Python classes + as parameters (they have to expose the '_as_parameter_' + attribute) + */ + if (arg) { + int result; + result = ConvParam(arg, index, pa); + Py_DECREF(arg); + return result; + } + PyErr_Format(PyExc_TypeError, + "Don't know how to convert parameter %d", + Py_SAFE_DOWNCAST(index, Py_ssize_t, int)); + return -1; + } } ffi_type *_ctypes_get_ffi_type(PyObject *obj) { - StgDictObject *dict; - if (obj == NULL) - return &ffi_type_sint; - dict = PyType_stgdict(obj); - if (dict == NULL) - return &ffi_type_sint; + StgDictObject *dict; + if (obj == NULL) + return &ffi_type_sint; + dict = PyType_stgdict(obj); + if (dict == NULL) + return &ffi_type_sint; #if defined(MS_WIN32) && !defined(_WIN32_WCE) - /* This little trick works correctly with MSVC. - It returns small structures in registers - */ - if (dict->ffi_type_pointer.type == FFI_TYPE_STRUCT) { - if (dict->ffi_type_pointer.size <= 4) - return &ffi_type_sint32; - else if (dict->ffi_type_pointer.size <= 8) - return &ffi_type_sint64; - } + /* This little trick works correctly with MSVC. + It returns small structures in registers + */ + if (dict->ffi_type_pointer.type == FFI_TYPE_STRUCT) { + if (dict->ffi_type_pointer.size <= 4) + return &ffi_type_sint32; + else if (dict->ffi_type_pointer.size <= 8) + return &ffi_type_sint64; + } #endif - return &dict->ffi_type_pointer; + return &dict->ffi_type_pointer; } @@ -737,7 +737,7 @@ * libffi uses: * * ffi_status ffi_prep_cif(ffi_cif *cif, ffi_abi abi, - * unsigned int nargs, + * unsigned int nargs, * ffi_type *rtype, * ffi_type **atypes); * @@ -746,108 +746,108 @@ * void ffi_call(ffi_cif *cif, void *fn, void *rvalue, void **avalues); */ static int _call_function_pointer(int flags, - PPROC pProc, - void **avalues, - ffi_type **atypes, - ffi_type *restype, - void *resmem, - int argcount) + PPROC pProc, + void **avalues, + ffi_type **atypes, + ffi_type *restype, + void *resmem, + int argcount) { #ifdef WITH_THREAD - PyThreadState *_save = NULL; /* For Py_BLOCK_THREADS and Py_UNBLOCK_THREADS */ + PyThreadState *_save = NULL; /* For Py_BLOCK_THREADS and Py_UNBLOCK_THREADS */ #endif - PyObject *error_object = NULL; - int *space; - ffi_cif cif; - int cc; + PyObject *error_object = NULL; + int *space; + ffi_cif cif; + int cc; #ifdef MS_WIN32 #ifndef DONT_USE_SEH - DWORD dwExceptionCode = 0; - EXCEPTION_RECORD record; + DWORD dwExceptionCode = 0; + EXCEPTION_RECORD record; #endif #endif - /* XXX check before here */ - if (restype == NULL) { - PyErr_SetString(PyExc_RuntimeError, - "No ffi_type for result"); - return -1; - } - - cc = FFI_DEFAULT_ABI; + /* XXX check before here */ + if (restype == NULL) { + PyErr_SetString(PyExc_RuntimeError, + "No ffi_type for result"); + return -1; + } + + cc = FFI_DEFAULT_ABI; #if defined(MS_WIN32) && !defined(MS_WIN64) && !defined(_WIN32_WCE) - if ((flags & FUNCFLAG_CDECL) == 0) - cc = FFI_STDCALL; + if ((flags & FUNCFLAG_CDECL) == 0) + cc = FFI_STDCALL; #endif - if (FFI_OK != ffi_prep_cif(&cif, - cc, - argcount, - restype, - atypes)) { - PyErr_SetString(PyExc_RuntimeError, - "ffi_prep_cif failed"); - return -1; - } - - if (flags & (FUNCFLAG_USE_ERRNO | FUNCFLAG_USE_LASTERROR)) { - error_object = _ctypes_get_errobj(&space); - if (error_object == NULL) - return -1; - } + if (FFI_OK != ffi_prep_cif(&cif, + cc, + argcount, + restype, + atypes)) { + PyErr_SetString(PyExc_RuntimeError, + "ffi_prep_cif failed"); + return -1; + } + + if (flags & (FUNCFLAG_USE_ERRNO | FUNCFLAG_USE_LASTERROR)) { + error_object = _ctypes_get_errobj(&space); + if (error_object == NULL) + return -1; + } #ifdef WITH_THREAD - if ((flags & FUNCFLAG_PYTHONAPI) == 0) - Py_UNBLOCK_THREADS + if ((flags & FUNCFLAG_PYTHONAPI) == 0) + Py_UNBLOCK_THREADS #endif - if (flags & FUNCFLAG_USE_ERRNO) { - int temp = space[0]; - space[0] = errno; - errno = temp; - } + if (flags & FUNCFLAG_USE_ERRNO) { + int temp = space[0]; + space[0] = errno; + errno = temp; + } #ifdef MS_WIN32 - if (flags & FUNCFLAG_USE_LASTERROR) { - int temp = space[1]; - space[1] = GetLastError(); - SetLastError(temp); - } + if (flags & FUNCFLAG_USE_LASTERROR) { + int temp = space[1]; + space[1] = GetLastError(); + SetLastError(temp); + } #ifndef DONT_USE_SEH - __try { + __try { #endif #endif - ffi_call(&cif, (void *)pProc, resmem, avalues); + ffi_call(&cif, (void *)pProc, resmem, avalues); #ifdef MS_WIN32 #ifndef DONT_USE_SEH - } - __except (HandleException(GetExceptionInformation(), - &dwExceptionCode, &record)) { - ; - } -#endif - if (flags & FUNCFLAG_USE_LASTERROR) { - int temp = space[1]; - space[1] = GetLastError(); - SetLastError(temp); - } -#endif - if (flags & FUNCFLAG_USE_ERRNO) { - int temp = space[0]; - space[0] = errno; - errno = temp; - } - Py_XDECREF(error_object); + } + __except (HandleException(GetExceptionInformation(), + &dwExceptionCode, &record)) { + ; + } +#endif + if (flags & FUNCFLAG_USE_LASTERROR) { + int temp = space[1]; + space[1] = GetLastError(); + SetLastError(temp); + } +#endif + if (flags & FUNCFLAG_USE_ERRNO) { + int temp = space[0]; + space[0] = errno; + errno = temp; + } + Py_XDECREF(error_object); #ifdef WITH_THREAD - if ((flags & FUNCFLAG_PYTHONAPI) == 0) - Py_BLOCK_THREADS + if ((flags & FUNCFLAG_PYTHONAPI) == 0) + Py_BLOCK_THREADS #endif #ifdef MS_WIN32 #ifndef DONT_USE_SEH - if (dwExceptionCode) { - SetException(dwExceptionCode, &record); - return -1; - } + if (dwExceptionCode) { + SetException(dwExceptionCode, &record); + return -1; + } #endif #endif - if ((flags & FUNCFLAG_PYTHONAPI) && PyErr_Occurred()) - return -1; - return 0; + if ((flags & FUNCFLAG_PYTHONAPI) && PyErr_Occurred()) + return -1; + return 0; } /* @@ -862,41 +862,41 @@ */ static PyObject *GetResult(PyObject *restype, void *result, PyObject *checker) { - StgDictObject *dict; - PyObject *retval, *v; + StgDictObject *dict; + PyObject *retval, *v; - if (restype == NULL) - return PyLong_FromLong(*(int *)result); + if (restype == NULL) + return PyLong_FromLong(*(int *)result); - if (restype == Py_None) { - Py_INCREF(Py_None); - return Py_None; - } - - dict = PyType_stgdict(restype); - if (dict == NULL) - return PyObject_CallFunction(restype, "i", *(int *)result); - - if (dict->getfunc && !_ctypes_simple_instance(restype)) { - retval = dict->getfunc(result, dict->size); - /* If restype is py_object (detected by comparing getfunc with - O_get), we have to call Py_DECREF because O_get has already - called Py_INCREF. - */ - if (dict->getfunc == _ctypes_get_fielddesc("O")->getfunc) { - Py_DECREF(retval); - } - } else - retval = PyCData_FromBaseObj(restype, NULL, 0, result); - - if (!checker || !retval) - return retval; - - v = PyObject_CallFunctionObjArgs(checker, retval, NULL); - if (v == NULL) - _ctypes_add_traceback("GetResult", "_ctypes/callproc.c", __LINE__-2); - Py_DECREF(retval); - return v; + if (restype == Py_None) { + Py_INCREF(Py_None); + return Py_None; + } + + dict = PyType_stgdict(restype); + if (dict == NULL) + return PyObject_CallFunction(restype, "i", *(int *)result); + + if (dict->getfunc && !_ctypes_simple_instance(restype)) { + retval = dict->getfunc(result, dict->size); + /* If restype is py_object (detected by comparing getfunc with + O_get), we have to call Py_DECREF because O_get has already + called Py_INCREF. + */ + if (dict->getfunc == _ctypes_get_fielddesc("O")->getfunc) { + Py_DECREF(retval); + } + } else + retval = PyCData_FromBaseObj(restype, NULL, 0, result); + + if (!checker || !retval) + return retval; + + v = PyObject_CallFunctionObjArgs(checker, retval, NULL); + if (v == NULL) + _ctypes_add_traceback("GetResult", "_ctypes/callproc.c", __LINE__-2); + Py_DECREF(retval); + return v; } /* @@ -905,40 +905,40 @@ */ void _ctypes_extend_error(PyObject *exc_class, char *fmt, ...) { - va_list vargs; - PyObject *tp, *v, *tb, *s, *cls_str, *msg_str; + va_list vargs; + PyObject *tp, *v, *tb, *s, *cls_str, *msg_str; - va_start(vargs, fmt); - s = PyUnicode_FromFormatV(fmt, vargs); - va_end(vargs); - if (!s) - return; - - PyErr_Fetch(&tp, &v, &tb); - PyErr_NormalizeException(&tp, &v, &tb); - cls_str = PyObject_Str(tp); - if (cls_str) { - PyUnicode_AppendAndDel(&s, cls_str); - PyUnicode_AppendAndDel(&s, PyUnicode_FromString(": ")); - if (s == NULL) - goto error; - } else - PyErr_Clear(); - msg_str = PyObject_Str(v); - if (msg_str) - PyUnicode_AppendAndDel(&s, msg_str); - else { - PyErr_Clear(); - PyUnicode_AppendAndDel(&s, PyUnicode_FromString("???")); - if (s == NULL) - goto error; - } - PyErr_SetObject(exc_class, s); + va_start(vargs, fmt); + s = PyUnicode_FromFormatV(fmt, vargs); + va_end(vargs); + if (!s) + return; + + PyErr_Fetch(&tp, &v, &tb); + PyErr_NormalizeException(&tp, &v, &tb); + cls_str = PyObject_Str(tp); + if (cls_str) { + PyUnicode_AppendAndDel(&s, cls_str); + PyUnicode_AppendAndDel(&s, PyUnicode_FromString(": ")); + if (s == NULL) + goto error; + } else + PyErr_Clear(); + msg_str = PyObject_Str(v); + if (msg_str) + PyUnicode_AppendAndDel(&s, msg_str); + else { + PyErr_Clear(); + PyUnicode_AppendAndDel(&s, PyUnicode_FromString("???")); + if (s == NULL) + goto error; + } + PyErr_SetObject(exc_class, s); error: - Py_XDECREF(tp); - Py_XDECREF(v); - Py_XDECREF(tb); - Py_XDECREF(s); + Py_XDECREF(tp); + Py_XDECREF(v); + Py_XDECREF(tb); + Py_XDECREF(s); } @@ -947,73 +947,73 @@ static PyObject * GetComError(HRESULT errcode, GUID *riid, IUnknown *pIunk) { - HRESULT hr; - ISupportErrorInfo *psei = NULL; - IErrorInfo *pei = NULL; - BSTR descr=NULL, helpfile=NULL, source=NULL; - GUID guid; - DWORD helpcontext=0; - LPOLESTR progid; - PyObject *obj; - LPOLESTR text; - - /* We absolutely have to release the GIL during COM method calls, - otherwise we may get a deadlock! - */ + HRESULT hr; + ISupportErrorInfo *psei = NULL; + IErrorInfo *pei = NULL; + BSTR descr=NULL, helpfile=NULL, source=NULL; + GUID guid; + DWORD helpcontext=0; + LPOLESTR progid; + PyObject *obj; + LPOLESTR text; + + /* We absolutely have to release the GIL during COM method calls, + otherwise we may get a deadlock! + */ #ifdef WITH_THREAD - Py_BEGIN_ALLOW_THREADS + Py_BEGIN_ALLOW_THREADS #endif - hr = pIunk->lpVtbl->QueryInterface(pIunk, &IID_ISupportErrorInfo, (void **)&psei); - if (FAILED(hr)) - goto failed; + hr = pIunk->lpVtbl->QueryInterface(pIunk, &IID_ISupportErrorInfo, (void **)&psei); + if (FAILED(hr)) + goto failed; - hr = psei->lpVtbl->InterfaceSupportsErrorInfo(psei, riid); - psei->lpVtbl->Release(psei); - if (FAILED(hr)) - goto failed; + hr = psei->lpVtbl->InterfaceSupportsErrorInfo(psei, riid); + psei->lpVtbl->Release(psei); + if (FAILED(hr)) + goto failed; - hr = GetErrorInfo(0, &pei); - if (hr != S_OK) - goto failed; + hr = GetErrorInfo(0, &pei); + if (hr != S_OK) + goto failed; - pei->lpVtbl->GetDescription(pei, &descr); - pei->lpVtbl->GetGUID(pei, &guid); - pei->lpVtbl->GetHelpContext(pei, &helpcontext); - pei->lpVtbl->GetHelpFile(pei, &helpfile); - pei->lpVtbl->GetSource(pei, &source); + pei->lpVtbl->GetDescription(pei, &descr); + pei->lpVtbl->GetGUID(pei, &guid); + pei->lpVtbl->GetHelpContext(pei, &helpcontext); + pei->lpVtbl->GetHelpFile(pei, &helpfile); + pei->lpVtbl->GetSource(pei, &source); - pei->lpVtbl->Release(pei); + pei->lpVtbl->Release(pei); failed: #ifdef WITH_THREAD - Py_END_ALLOW_THREADS + Py_END_ALLOW_THREADS #endif - progid = NULL; - ProgIDFromCLSID(&guid, &progid); + progid = NULL; + ProgIDFromCLSID(&guid, &progid); - text = FormatError(errcode); - obj = Py_BuildValue( - "iu(uuuiu)", - errcode, - text, - descr, source, helpfile, helpcontext, - progid); - if (obj) { - PyErr_SetObject(ComError, obj); - Py_DECREF(obj); - } - LocalFree(text); - - if (descr) - SysFreeString(descr); - if (helpfile) - SysFreeString(helpfile); - if (source) - SysFreeString(source); + text = FormatError(errcode); + obj = Py_BuildValue( + "iu(uuuiu)", + errcode, + text, + descr, source, helpfile, helpcontext, + progid); + if (obj) { + PyErr_SetObject(ComError, obj); + Py_DECREF(obj); + } + LocalFree(text); + + if (descr) + SysFreeString(descr); + if (helpfile) + SysFreeString(helpfile); + if (source) + SysFreeString(source); - return NULL; + return NULL; } #endif @@ -1025,154 +1025,154 @@ * - XXX various requirements for restype, not yet collected */ PyObject *_ctypes_callproc(PPROC pProc, - PyObject *argtuple, + PyObject *argtuple, #ifdef MS_WIN32 - IUnknown *pIunk, - GUID *iid, + IUnknown *pIunk, + GUID *iid, #endif - int flags, - PyObject *argtypes, /* misleading name: This is a tuple of - methods, not types: the .from_param - class methods of the types */ - PyObject *restype, - PyObject *checker) -{ - Py_ssize_t i, n, argcount, argtype_count; - void *resbuf; - struct argument *args, *pa; - ffi_type **atypes; - ffi_type *rtype; - void **avalues; - PyObject *retval = NULL; + int flags, + PyObject *argtypes, /* misleading name: This is a tuple of + methods, not types: the .from_param + class methods of the types */ + PyObject *restype, + PyObject *checker) +{ + Py_ssize_t i, n, argcount, argtype_count; + void *resbuf; + struct argument *args, *pa; + ffi_type **atypes; + ffi_type *rtype; + void **avalues; + PyObject *retval = NULL; - n = argcount = PyTuple_GET_SIZE(argtuple); + n = argcount = PyTuple_GET_SIZE(argtuple); #ifdef MS_WIN32 - /* an optional COM object this pointer */ - if (pIunk) - ++argcount; + /* an optional COM object this pointer */ + if (pIunk) + ++argcount; #endif - args = (struct argument *)alloca(sizeof(struct argument) * argcount); - if (!args) { - PyErr_NoMemory(); - return NULL; - } - memset(args, 0, sizeof(struct argument) * argcount); - argtype_count = argtypes ? PyTuple_GET_SIZE(argtypes) : 0; + args = (struct argument *)alloca(sizeof(struct argument) * argcount); + if (!args) { + PyErr_NoMemory(); + return NULL; + } + memset(args, 0, sizeof(struct argument) * argcount); + argtype_count = argtypes ? PyTuple_GET_SIZE(argtypes) : 0; #ifdef MS_WIN32 - if (pIunk) { - args[0].ffi_type = &ffi_type_pointer; - args[0].value.p = pIunk; - pa = &args[1]; - } else -#endif - pa = &args[0]; - - /* Convert the arguments */ - for (i = 0; i < n; ++i, ++pa) { - PyObject *converter; - PyObject *arg; - int err; - - arg = PyTuple_GET_ITEM(argtuple, i); /* borrowed ref */ - /* For cdecl functions, we allow more actual arguments - than the length of the argtypes tuple. - This is checked in _ctypes::PyCFuncPtr_Call - */ - if (argtypes && argtype_count > i) { - PyObject *v; - converter = PyTuple_GET_ITEM(argtypes, i); - v = PyObject_CallFunctionObjArgs(converter, - arg, - NULL); - if (v == NULL) { - _ctypes_extend_error(PyExc_ArgError, "argument %d: ", i+1); - goto cleanup; - } - - err = ConvParam(v, i+1, pa); - Py_DECREF(v); - if (-1 == err) { - _ctypes_extend_error(PyExc_ArgError, "argument %d: ", i+1); - goto cleanup; - } - } else { - err = ConvParam(arg, i+1, pa); - if (-1 == err) { - _ctypes_extend_error(PyExc_ArgError, "argument %d: ", i+1); - goto cleanup; /* leaking ? */ - } - } - } - - rtype = _ctypes_get_ffi_type(restype); - resbuf = alloca(max(rtype->size, sizeof(ffi_arg))); - - avalues = (void **)alloca(sizeof(void *) * argcount); - atypes = (ffi_type **)alloca(sizeof(ffi_type *) * argcount); - if (!resbuf || !avalues || !atypes) { - PyErr_NoMemory(); - goto cleanup; - } - for (i = 0; i < argcount; ++i) { - atypes[i] = args[i].ffi_type; - if (atypes[i]->type == FFI_TYPE_STRUCT) - avalues[i] = (void *)args[i].value.p; - else - avalues[i] = (void *)&args[i].value; - } - - if (-1 == _call_function_pointer(flags, pProc, avalues, atypes, - rtype, resbuf, - Py_SAFE_DOWNCAST(argcount, - Py_ssize_t, - int))) - goto cleanup; + if (pIunk) { + args[0].ffi_type = &ffi_type_pointer; + args[0].value.p = pIunk; + pa = &args[1]; + } else +#endif + pa = &args[0]; + + /* Convert the arguments */ + for (i = 0; i < n; ++i, ++pa) { + PyObject *converter; + PyObject *arg; + int err; + + arg = PyTuple_GET_ITEM(argtuple, i); /* borrowed ref */ + /* For cdecl functions, we allow more actual arguments + than the length of the argtypes tuple. + This is checked in _ctypes::PyCFuncPtr_Call + */ + if (argtypes && argtype_count > i) { + PyObject *v; + converter = PyTuple_GET_ITEM(argtypes, i); + v = PyObject_CallFunctionObjArgs(converter, + arg, + NULL); + if (v == NULL) { + _ctypes_extend_error(PyExc_ArgError, "argument %d: ", i+1); + goto cleanup; + } + + err = ConvParam(v, i+1, pa); + Py_DECREF(v); + if (-1 == err) { + _ctypes_extend_error(PyExc_ArgError, "argument %d: ", i+1); + goto cleanup; + } + } else { + err = ConvParam(arg, i+1, pa); + if (-1 == err) { + _ctypes_extend_error(PyExc_ArgError, "argument %d: ", i+1); + goto cleanup; /* leaking ? */ + } + } + } + + rtype = _ctypes_get_ffi_type(restype); + resbuf = alloca(max(rtype->size, sizeof(ffi_arg))); + + avalues = (void **)alloca(sizeof(void *) * argcount); + atypes = (ffi_type **)alloca(sizeof(ffi_type *) * argcount); + if (!resbuf || !avalues || !atypes) { + PyErr_NoMemory(); + goto cleanup; + } + for (i = 0; i < argcount; ++i) { + atypes[i] = args[i].ffi_type; + if (atypes[i]->type == FFI_TYPE_STRUCT) + avalues[i] = (void *)args[i].value.p; + else + avalues[i] = (void *)&args[i].value; + } + + if (-1 == _call_function_pointer(flags, pProc, avalues, atypes, + rtype, resbuf, + Py_SAFE_DOWNCAST(argcount, + Py_ssize_t, + int))) + goto cleanup; #ifdef WORDS_BIGENDIAN - /* libffi returns the result in a buffer with sizeof(ffi_arg). This - causes problems on big endian machines, since the result buffer - address cannot simply be used as result pointer, instead we must - adjust the pointer value: - */ - /* - XXX I should find out and clarify why this is needed at all, - especially why adjusting for ffi_type_float must be avoided on - 64-bit platforms. - */ - if (rtype->type != FFI_TYPE_FLOAT - && rtype->type != FFI_TYPE_STRUCT - && rtype->size < sizeof(ffi_arg)) - resbuf = (char *)resbuf + sizeof(ffi_arg) - rtype->size; + /* libffi returns the result in a buffer with sizeof(ffi_arg). This + causes problems on big endian machines, since the result buffer + address cannot simply be used as result pointer, instead we must + adjust the pointer value: + */ + /* + XXX I should find out and clarify why this is needed at all, + especially why adjusting for ffi_type_float must be avoided on + 64-bit platforms. + */ + if (rtype->type != FFI_TYPE_FLOAT + && rtype->type != FFI_TYPE_STRUCT + && rtype->size < sizeof(ffi_arg)) + resbuf = (char *)resbuf + sizeof(ffi_arg) - rtype->size; #endif #ifdef MS_WIN32 - if (iid && pIunk) { - if (*(int *)resbuf & 0x80000000) - retval = GetComError(*(HRESULT *)resbuf, iid, pIunk); - else - retval = PyLong_FromLong(*(int *)resbuf); - } else if (flags & FUNCFLAG_HRESULT) { - if (*(int *)resbuf & 0x80000000) - retval = PyErr_SetFromWindowsErr(*(int *)resbuf); - else - retval = PyLong_FromLong(*(int *)resbuf); - } else + if (iid && pIunk) { + if (*(int *)resbuf & 0x80000000) + retval = GetComError(*(HRESULT *)resbuf, iid, pIunk); + else + retval = PyLong_FromLong(*(int *)resbuf); + } else if (flags & FUNCFLAG_HRESULT) { + if (*(int *)resbuf & 0x80000000) + retval = PyErr_SetFromWindowsErr(*(int *)resbuf); + else + retval = PyLong_FromLong(*(int *)resbuf); + } else #endif - retval = GetResult(restype, resbuf, checker); + retval = GetResult(restype, resbuf, checker); cleanup: - for (i = 0; i < argcount; ++i) - Py_XDECREF(args[i].keep); - return retval; + for (i = 0; i < argcount; ++i) + Py_XDECREF(args[i].keep); + return retval; } static int _parse_voidp(PyObject *obj, void **address) { - *address = PyLong_AsVoidPtr(obj); - if (*address == NULL) - return 0; - return 1; + *address = PyLong_AsVoidPtr(obj); + if (*address == NULL) + return 0; + return 1; } #ifdef MS_WIN32 @@ -1184,21 +1184,21 @@ given, the return value of a call to GetLastError() is used.\n"; static PyObject *format_error(PyObject *self, PyObject *args) { - PyObject *result; - wchar_t *lpMsgBuf; - DWORD code = 0; - if (!PyArg_ParseTuple(args, "|i:FormatError", &code)) - return NULL; - if (code == 0) - code = GetLastError(); - lpMsgBuf = FormatError(code); - if (lpMsgBuf) { - result = PyUnicode_FromWideChar(lpMsgBuf, wcslen(lpMsgBuf)); - LocalFree(lpMsgBuf); - } else { - result = PyUnicode_FromString(""); - } - return result; + PyObject *result; + wchar_t *lpMsgBuf; + DWORD code = 0; + if (!PyArg_ParseTuple(args, "|i:FormatError", &code)) + return NULL; + if (code == 0) + code = GetLastError(); + lpMsgBuf = FormatError(code); + if (lpMsgBuf) { + result = PyUnicode_FromWideChar(lpMsgBuf, wcslen(lpMsgBuf)); + LocalFree(lpMsgBuf); + } else { + result = PyUnicode_FromString(""); + } + return result; } static char load_library_doc[] = @@ -1209,24 +1209,24 @@ module.\n"; static PyObject *load_library(PyObject *self, PyObject *args) { - WCHAR *name; - PyObject *nameobj; - PyObject *ignored; - HMODULE hMod; - if (!PyArg_ParseTuple(args, "O|O:LoadLibrary", &nameobj, &ignored)) - return NULL; - - name = PyUnicode_AsUnicode(nameobj); - if (!name) - return NULL; - - hMod = LoadLibraryW(name); - if (!hMod) - return PyErr_SetFromWindowsErr(GetLastError()); + WCHAR *name; + PyObject *nameobj; + PyObject *ignored; + HMODULE hMod; + if (!PyArg_ParseTuple(args, "O|O:LoadLibrary", &nameobj, &ignored)) + return NULL; + + name = PyUnicode_AsUnicode(nameobj); + if (!name) + return NULL; + + hMod = LoadLibraryW(name); + if (!hMod) + return PyErr_SetFromWindowsErr(GetLastError()); #ifdef _WIN64 - return PyLong_FromVoidPtr(hMod); + return PyLong_FromVoidPtr(hMod); #else - return Py_BuildValue("i", hMod); + return Py_BuildValue("i", hMod); #endif } @@ -1236,13 +1236,13 @@ Free the handle of an executable previously loaded by LoadLibrary.\n"; static PyObject *free_library(PyObject *self, PyObject *args) { - void *hMod; - if (!PyArg_ParseTuple(args, "O&:FreeLibrary", &_parse_voidp, &hMod)) - return NULL; - if (!FreeLibrary((HMODULE)hMod)) - return PyErr_SetFromWindowsErr(GetLastError()); - Py_INCREF(Py_None); - return Py_None; + void *hMod; + if (!PyArg_ParseTuple(args, "O&:FreeLibrary", &_parse_voidp, &hMod)) + return NULL; + if (!FreeLibrary((HMODULE)hMod)) + return PyErr_SetFromWindowsErr(GetLastError()); + Py_INCREF(Py_None); + return Py_None; } /* obsolete, should be removed */ @@ -1250,55 +1250,55 @@ static PyObject * call_commethod(PyObject *self, PyObject *args) { - IUnknown *pIunk; - int index; - PyObject *arguments; - PPROC *lpVtbl; - PyObject *result; - CDataObject *pcom; - PyObject *argtypes = NULL; - - if (!PyArg_ParseTuple(args, - "OiO!|O!", - &pcom, &index, - &PyTuple_Type, &arguments, - &PyTuple_Type, &argtypes)) - return NULL; - - if (argtypes && (PyTuple_GET_SIZE(arguments) != PyTuple_GET_SIZE(argtypes))) { - PyErr_Format(PyExc_TypeError, - "Method takes %d arguments (%d given)", - PyTuple_GET_SIZE(argtypes), PyTuple_GET_SIZE(arguments)); - return NULL; - } - - if (!CDataObject_Check(pcom) || (pcom->b_size != sizeof(void *))) { - PyErr_Format(PyExc_TypeError, - "COM Pointer expected instead of %s instance", - Py_TYPE(pcom)->tp_name); - return NULL; - } - - if ((*(void **)(pcom->b_ptr)) == NULL) { - PyErr_SetString(PyExc_ValueError, - "The COM 'this' pointer is NULL"); - return NULL; - } + IUnknown *pIunk; + int index; + PyObject *arguments; + PPROC *lpVtbl; + PyObject *result; + CDataObject *pcom; + PyObject *argtypes = NULL; + + if (!PyArg_ParseTuple(args, + "OiO!|O!", + &pcom, &index, + &PyTuple_Type, &arguments, + &PyTuple_Type, &argtypes)) + return NULL; + + if (argtypes && (PyTuple_GET_SIZE(arguments) != PyTuple_GET_SIZE(argtypes))) { + PyErr_Format(PyExc_TypeError, + "Method takes %d arguments (%d given)", + PyTuple_GET_SIZE(argtypes), PyTuple_GET_SIZE(arguments)); + return NULL; + } + + if (!CDataObject_Check(pcom) || (pcom->b_size != sizeof(void *))) { + PyErr_Format(PyExc_TypeError, + "COM Pointer expected instead of %s instance", + Py_TYPE(pcom)->tp_name); + return NULL; + } + + if ((*(void **)(pcom->b_ptr)) == NULL) { + PyErr_SetString(PyExc_ValueError, + "The COM 'this' pointer is NULL"); + return NULL; + } - pIunk = (IUnknown *)(*(void **)(pcom->b_ptr)); - lpVtbl = (PPROC *)(pIunk->lpVtbl); + pIunk = (IUnknown *)(*(void **)(pcom->b_ptr)); + lpVtbl = (PPROC *)(pIunk->lpVtbl); - result = _ctypes_callproc(lpVtbl[index], - arguments, + result = _ctypes_callproc(lpVtbl[index], + arguments, #ifdef MS_WIN32 - pIunk, - NULL, + pIunk, + NULL, #endif - FUNCFLAG_HRESULT, /* flags */ - argtypes, /* self->argtypes */ - NULL, /* self->restype */ - NULL); /* checker */ - return result; + FUNCFLAG_HRESULT, /* flags */ + argtypes, /* self->argtypes */ + NULL, /* self->restype */ + NULL); /* checker */ + return result; } static char copy_com_pointer_doc[] = @@ -1307,102 +1307,102 @@ static PyObject * copy_com_pointer(PyObject *self, PyObject *args) { - PyObject *p1, *p2, *r = NULL; - struct argument a, b; - IUnknown *src, **pdst; - if (!PyArg_ParseTuple(args, "OO:CopyComPointer", &p1, &p2)) - return NULL; - a.keep = b.keep = NULL; - - if (-1 == ConvParam(p1, 0, &a) || -1 == ConvParam(p2, 1, &b)) - goto done; - src = (IUnknown *)a.value.p; - pdst = (IUnknown **)b.value.p; - - if (pdst == NULL) - r = PyLong_FromLong(E_POINTER); - else { - if (src) - src->lpVtbl->AddRef(src); - *pdst = src; - r = PyLong_FromLong(S_OK); - } + PyObject *p1, *p2, *r = NULL; + struct argument a, b; + IUnknown *src, **pdst; + if (!PyArg_ParseTuple(args, "OO:CopyComPointer", &p1, &p2)) + return NULL; + a.keep = b.keep = NULL; + + if (-1 == ConvParam(p1, 0, &a) || -1 == ConvParam(p2, 1, &b)) + goto done; + src = (IUnknown *)a.value.p; + pdst = (IUnknown **)b.value.p; + + if (pdst == NULL) + r = PyLong_FromLong(E_POINTER); + else { + if (src) + src->lpVtbl->AddRef(src); + *pdst = src; + r = PyLong_FromLong(S_OK); + } done: - Py_XDECREF(a.keep); - Py_XDECREF(b.keep); - return r; + Py_XDECREF(a.keep); + Py_XDECREF(b.keep); + return r; } #else static PyObject *py_dl_open(PyObject *self, PyObject *args) { - PyObject *name, *name2; - char *name_str; - void * handle; -#ifdef RTLD_LOCAL - int mode = RTLD_NOW | RTLD_LOCAL; + PyObject *name, *name2; + char *name_str; + void * handle; +#ifdef RTLD_LOCAL + int mode = RTLD_NOW | RTLD_LOCAL; #else - /* cygwin doesn't define RTLD_LOCAL */ - int mode = RTLD_NOW; + /* cygwin doesn't define RTLD_LOCAL */ + int mode = RTLD_NOW; #endif - if (!PyArg_ParseTuple(args, "O|i:dlopen", &name, &mode)) - return NULL; - mode |= RTLD_NOW; - if (name != Py_None) { - if (PyUnicode_FSConverter(name, &name2) == 0) - return NULL; - if (PyBytes_Check(name2)) - name_str = PyBytes_AS_STRING(name2); - else - name_str = PyByteArray_AS_STRING(name2); - } else { - name_str = NULL; - name2 = NULL; - } - handle = ctypes_dlopen(name_str, mode); - Py_XDECREF(name2); - if (!handle) { - char *errmsg = ctypes_dlerror(); - if (!errmsg) - errmsg = "dlopen() error"; - PyErr_SetString(PyExc_OSError, - errmsg); - return NULL; - } - return PyLong_FromVoidPtr(handle); + if (!PyArg_ParseTuple(args, "O|i:dlopen", &name, &mode)) + return NULL; + mode |= RTLD_NOW; + if (name != Py_None) { + if (PyUnicode_FSConverter(name, &name2) == 0) + return NULL; + if (PyBytes_Check(name2)) + name_str = PyBytes_AS_STRING(name2); + else + name_str = PyByteArray_AS_STRING(name2); + } else { + name_str = NULL; + name2 = NULL; + } + handle = ctypes_dlopen(name_str, mode); + Py_XDECREF(name2); + if (!handle) { + char *errmsg = ctypes_dlerror(); + if (!errmsg) + errmsg = "dlopen() error"; + PyErr_SetString(PyExc_OSError, + errmsg); + return NULL; + } + return PyLong_FromVoidPtr(handle); } static PyObject *py_dl_close(PyObject *self, PyObject *args) { - void *handle; + void *handle; - if (!PyArg_ParseTuple(args, "O&:dlclose", &_parse_voidp, &handle)) - return NULL; - if (dlclose(handle)) { - PyErr_SetString(PyExc_OSError, - ctypes_dlerror()); - return NULL; - } - Py_INCREF(Py_None); - return Py_None; + if (!PyArg_ParseTuple(args, "O&:dlclose", &_parse_voidp, &handle)) + return NULL; + if (dlclose(handle)) { + PyErr_SetString(PyExc_OSError, + ctypes_dlerror()); + return NULL; + } + Py_INCREF(Py_None); + return Py_None; } static PyObject *py_dl_sym(PyObject *self, PyObject *args) { - char *name; - void *handle; - void *ptr; - - if (!PyArg_ParseTuple(args, "O&s:dlsym", - &_parse_voidp, &handle, &name)) - return NULL; - ptr = ctypes_dlsym((void*)handle, name); - if (!ptr) { - PyErr_SetString(PyExc_OSError, - ctypes_dlerror()); - return NULL; - } - return PyLong_FromVoidPtr(ptr); + char *name; + void *handle; + void *ptr; + + if (!PyArg_ParseTuple(args, "O&s:dlsym", + &_parse_voidp, &handle, &name)) + return NULL; + ptr = ctypes_dlsym((void*)handle, name); + if (!ptr) { + PyErr_SetString(PyExc_OSError, + ctypes_dlerror()); + return NULL; + } + return PyLong_FromVoidPtr(ptr); } #endif @@ -1414,27 +1414,27 @@ static PyObject * call_function(PyObject *self, PyObject *args) { - void *func; - PyObject *arguments; - PyObject *result; - - if (!PyArg_ParseTuple(args, - "O&O!", - &_parse_voidp, &func, - &PyTuple_Type, &arguments)) - return NULL; + void *func; + PyObject *arguments; + PyObject *result; + + if (!PyArg_ParseTuple(args, + "O&O!", + &_parse_voidp, &func, + &PyTuple_Type, &arguments)) + return NULL; - result = _ctypes_callproc((PPROC)func, - arguments, + result = _ctypes_callproc((PPROC)func, + arguments, #ifdef MS_WIN32 - NULL, - NULL, + NULL, + NULL, #endif - 0, /* flags */ - NULL, /* self->argtypes */ - NULL, /* self->restype */ - NULL); /* checker */ - return result; + 0, /* flags */ + NULL, /* self->argtypes */ + NULL, /* self->restype */ + NULL); /* checker */ + return result; } /* @@ -1445,27 +1445,27 @@ static PyObject * call_cdeclfunction(PyObject *self, PyObject *args) { - void *func; - PyObject *arguments; - PyObject *result; - - if (!PyArg_ParseTuple(args, - "O&O!", - &_parse_voidp, &func, - &PyTuple_Type, &arguments)) - return NULL; + void *func; + PyObject *arguments; + PyObject *result; + + if (!PyArg_ParseTuple(args, + "O&O!", + &_parse_voidp, &func, + &PyTuple_Type, &arguments)) + return NULL; - result = _ctypes_callproc((PPROC)func, - arguments, + result = _ctypes_callproc((PPROC)func, + arguments, #ifdef MS_WIN32 - NULL, - NULL, + NULL, + NULL, #endif - FUNCFLAG_CDECL, /* flags */ - NULL, /* self->argtypes */ - NULL, /* self->restype */ - NULL); /* checker */ - return result; + FUNCFLAG_CDECL, /* flags */ + NULL, /* self->argtypes */ + NULL, /* self->restype */ + NULL); /* checker */ + return result; } /***************************************************************** @@ -1479,17 +1479,17 @@ static PyObject * sizeof_func(PyObject *self, PyObject *obj) { - StgDictObject *dict; + StgDictObject *dict; - dict = PyType_stgdict(obj); - if (dict) - return PyLong_FromSsize_t(dict->size); - - if (CDataObject_Check(obj)) - return PyLong_FromSsize_t(((CDataObject *)obj)->b_size); - PyErr_SetString(PyExc_TypeError, - "this type has no size"); - return NULL; + dict = PyType_stgdict(obj); + if (dict) + return PyLong_FromSsize_t(dict->size); + + if (CDataObject_Check(obj)) + return PyLong_FromSsize_t(((CDataObject *)obj)->b_size); + PyErr_SetString(PyExc_TypeError, + "this type has no size"); + return NULL; } static char alignment_doc[] = @@ -1500,19 +1500,19 @@ static PyObject * align_func(PyObject *self, PyObject *obj) { - StgDictObject *dict; + StgDictObject *dict; - dict = PyType_stgdict(obj); - if (dict) - return PyLong_FromSsize_t(dict->align); - - dict = PyObject_stgdict(obj); - if (dict) - return PyLong_FromSsize_t(dict->align); - - PyErr_SetString(PyExc_TypeError, - "no alignment info"); - return NULL; + dict = PyType_stgdict(obj); + if (dict) + return PyLong_FromSsize_t(dict->align); + + dict = PyObject_stgdict(obj); + if (dict) + return PyLong_FromSsize_t(dict->align); + + PyErr_SetString(PyExc_TypeError, + "no alignment info"); + return NULL; } static char byref_doc[] = @@ -1527,36 +1527,36 @@ static PyObject * byref(PyObject *self, PyObject *args) { - PyCArgObject *parg; - PyObject *obj; - PyObject *pyoffset = NULL; - Py_ssize_t offset = 0; - - if (!PyArg_UnpackTuple(args, "byref", 1, 2, - &obj, &pyoffset)) - return NULL; - if (pyoffset) { - offset = PyNumber_AsSsize_t(pyoffset, NULL); - if (offset == -1 && PyErr_Occurred()) - return NULL; - } - if (!CDataObject_Check(obj)) { - PyErr_Format(PyExc_TypeError, - "byref() argument must be a ctypes instance, not '%s'", - Py_TYPE(obj)->tp_name); - return NULL; - } - - parg = PyCArgObject_new(); - if (parg == NULL) - return NULL; - - parg->tag = 'P'; - parg->pffi_type = &ffi_type_pointer; - Py_INCREF(obj); - parg->obj = obj; - parg->value.p = (char *)((CDataObject *)obj)->b_ptr + offset; - return (PyObject *)parg; + PyCArgObject *parg; + PyObject *obj; + PyObject *pyoffset = NULL; + Py_ssize_t offset = 0; + + if (!PyArg_UnpackTuple(args, "byref", 1, 2, + &obj, &pyoffset)) + return NULL; + if (pyoffset) { + offset = PyNumber_AsSsize_t(pyoffset, NULL); + if (offset == -1 && PyErr_Occurred()) + return NULL; + } + if (!CDataObject_Check(obj)) { + PyErr_Format(PyExc_TypeError, + "byref() argument must be a ctypes instance, not '%s'", + Py_TYPE(obj)->tp_name); + return NULL; + } + + parg = PyCArgObject_new(); + if (parg == NULL) + return NULL; + + parg->tag = 'P'; + parg->pffi_type = &ffi_type_pointer; + Py_INCREF(obj); + parg->obj = obj; + parg->value.p = (char *)((CDataObject *)obj)->b_ptr + offset; + return (PyObject *)parg; } static char addressof_doc[] = @@ -1566,44 +1566,44 @@ static PyObject * addressof(PyObject *self, PyObject *obj) { - if (CDataObject_Check(obj)) - return PyLong_FromVoidPtr(((CDataObject *)obj)->b_ptr); - PyErr_SetString(PyExc_TypeError, - "invalid type"); - return NULL; + if (CDataObject_Check(obj)) + return PyLong_FromVoidPtr(((CDataObject *)obj)->b_ptr); + PyErr_SetString(PyExc_TypeError, + "invalid type"); + return NULL; } static int converter(PyObject *obj, void **address) { - *address = PyLong_AsVoidPtr(obj); - return *address != NULL; + *address = PyLong_AsVoidPtr(obj); + return *address != NULL; } static PyObject * My_PyObj_FromPtr(PyObject *self, PyObject *args) { - PyObject *ob; - if (!PyArg_ParseTuple(args, "O&:PyObj_FromPtr", converter, &ob)) - return NULL; - Py_INCREF(ob); - return ob; + PyObject *ob; + if (!PyArg_ParseTuple(args, "O&:PyObj_FromPtr", converter, &ob)) + return NULL; + Py_INCREF(ob); + return ob; } static PyObject * My_Py_INCREF(PyObject *self, PyObject *arg) { - Py_INCREF(arg); /* that's what this function is for */ - Py_INCREF(arg); /* that for returning it */ - return arg; + Py_INCREF(arg); /* that's what this function is for */ + Py_INCREF(arg); /* that for returning it */ + return arg; } static PyObject * My_Py_DECREF(PyObject *self, PyObject *arg) { - Py_DECREF(arg); /* that's what this function is for */ - Py_INCREF(arg); /* that's for returning it */ - return arg; + Py_DECREF(arg); /* that's what this function is for */ + Py_INCREF(arg); /* that's for returning it */ + return arg; } #ifdef CTYPES_UNICODE @@ -1617,234 +1617,234 @@ static PyObject * set_conversion_mode(PyObject *self, PyObject *args) { - char *coding, *mode; - PyObject *result; + char *coding, *mode; + PyObject *result; - if (!PyArg_ParseTuple(args, "zs:set_conversion_mode", &coding, &mode)) - return NULL; - result = Py_BuildValue("(zz)", _ctypes_conversion_encoding, _ctypes_conversion_errors); - if (coding) { - PyMem_Free(_ctypes_conversion_encoding); - _ctypes_conversion_encoding = PyMem_Malloc(strlen(coding) + 1); - strcpy(_ctypes_conversion_encoding, coding); - } else { - _ctypes_conversion_encoding = NULL; - } - PyMem_Free(_ctypes_conversion_errors); - _ctypes_conversion_errors = PyMem_Malloc(strlen(mode) + 1); - strcpy(_ctypes_conversion_errors, mode); - return result; + if (!PyArg_ParseTuple(args, "zs:set_conversion_mode", &coding, &mode)) + return NULL; + result = Py_BuildValue("(zz)", _ctypes_conversion_encoding, _ctypes_conversion_errors); + if (coding) { + PyMem_Free(_ctypes_conversion_encoding); + _ctypes_conversion_encoding = PyMem_Malloc(strlen(coding) + 1); + strcpy(_ctypes_conversion_encoding, coding); + } else { + _ctypes_conversion_encoding = NULL; + } + PyMem_Free(_ctypes_conversion_errors); + _ctypes_conversion_errors = PyMem_Malloc(strlen(mode) + 1); + strcpy(_ctypes_conversion_errors, mode); + return result; } #endif static PyObject * resize(PyObject *self, PyObject *args) { - CDataObject *obj; - StgDictObject *dict; - Py_ssize_t size; - - if (!PyArg_ParseTuple(args, - "On:resize", - &obj, &size)) - return NULL; - - dict = PyObject_stgdict((PyObject *)obj); - if (dict == NULL) { - PyErr_SetString(PyExc_TypeError, - "excepted ctypes instance"); - return NULL; - } - if (size < dict->size) { - PyErr_Format(PyExc_ValueError, - "minimum size is %zd", - dict->size); - return NULL; - } - if (obj->b_needsfree == 0) { - PyErr_Format(PyExc_ValueError, - "Memory cannot be resized because this object doesn't own it"); - return NULL; - } - if (size <= sizeof(obj->b_value)) { - /* internal default buffer is large enough */ - obj->b_size = size; - goto done; - } - if (obj->b_size <= sizeof(obj->b_value)) { - /* We are currently using the objects default buffer, but it - isn't large enough any more. */ - void *ptr = PyMem_Malloc(size); - if (ptr == NULL) - return PyErr_NoMemory(); - memset(ptr, 0, size); - memmove(ptr, obj->b_ptr, obj->b_size); - obj->b_ptr = ptr; - obj->b_size = size; - } else { - void * ptr = PyMem_Realloc(obj->b_ptr, size); - if (ptr == NULL) - return PyErr_NoMemory(); - obj->b_ptr = ptr; - obj->b_size = size; - } + CDataObject *obj; + StgDictObject *dict; + Py_ssize_t size; + + if (!PyArg_ParseTuple(args, + "On:resize", + &obj, &size)) + return NULL; + + dict = PyObject_stgdict((PyObject *)obj); + if (dict == NULL) { + PyErr_SetString(PyExc_TypeError, + "excepted ctypes instance"); + return NULL; + } + if (size < dict->size) { + PyErr_Format(PyExc_ValueError, + "minimum size is %zd", + dict->size); + return NULL; + } + if (obj->b_needsfree == 0) { + PyErr_Format(PyExc_ValueError, + "Memory cannot be resized because this object doesn't own it"); + return NULL; + } + if (size <= sizeof(obj->b_value)) { + /* internal default buffer is large enough */ + obj->b_size = size; + goto done; + } + if (obj->b_size <= sizeof(obj->b_value)) { + /* We are currently using the objects default buffer, but it + isn't large enough any more. */ + void *ptr = PyMem_Malloc(size); + if (ptr == NULL) + return PyErr_NoMemory(); + memset(ptr, 0, size); + memmove(ptr, obj->b_ptr, obj->b_size); + obj->b_ptr = ptr; + obj->b_size = size; + } else { + void * ptr = PyMem_Realloc(obj->b_ptr, size); + if (ptr == NULL) + return PyErr_NoMemory(); + obj->b_ptr = ptr; + obj->b_size = size; + } done: - Py_INCREF(Py_None); - return Py_None; + Py_INCREF(Py_None); + return Py_None; } static PyObject * unpickle(PyObject *self, PyObject *args) { - PyObject *typ; - PyObject *state; - PyObject *result; - PyObject *tmp; - - if (!PyArg_ParseTuple(args, "OO", &typ, &state)) - return NULL; - result = PyObject_CallMethod(typ, "__new__", "O", typ); - if (result == NULL) - return NULL; - tmp = PyObject_CallMethod(result, "__setstate__", "O", state); - if (tmp == NULL) { - Py_DECREF(result); - return NULL; - } - Py_DECREF(tmp); - return result; + PyObject *typ; + PyObject *state; + PyObject *result; + PyObject *tmp; + + if (!PyArg_ParseTuple(args, "OO", &typ, &state)) + return NULL; + result = PyObject_CallMethod(typ, "__new__", "O", typ); + if (result == NULL) + return NULL; + tmp = PyObject_CallMethod(result, "__setstate__", "O", state); + if (tmp == NULL) { + Py_DECREF(result); + return NULL; + } + Py_DECREF(tmp); + return result; } static PyObject * POINTER(PyObject *self, PyObject *cls) { - PyObject *result; - PyTypeObject *typ; - PyObject *key; - char *buf; - - result = PyDict_GetItem(_ctypes_ptrtype_cache, cls); - if (result) { - Py_INCREF(result); - return result; - } - if (PyUnicode_CheckExact(cls)) { - char *name = _PyUnicode_AsString(cls); - buf = alloca(strlen(name) + 3 + 1); - sprintf(buf, "LP_%s", name); - result = PyObject_CallFunction((PyObject *)Py_TYPE(&PyCPointer_Type), - "s(O){}", - buf, - &PyCPointer_Type); - if (result == NULL) - return result; - key = PyLong_FromVoidPtr(result); - } else if (PyType_Check(cls)) { - typ = (PyTypeObject *)cls; - buf = alloca(strlen(typ->tp_name) + 3 + 1); - sprintf(buf, "LP_%s", typ->tp_name); - result = PyObject_CallFunction((PyObject *)Py_TYPE(&PyCPointer_Type), - "s(O){sO}", - buf, - &PyCPointer_Type, - "_type_", cls); - if (result == NULL) - return result; - Py_INCREF(cls); - key = cls; - } else { - PyErr_SetString(PyExc_TypeError, "must be a ctypes type"); - return NULL; - } - if (-1 == PyDict_SetItem(_ctypes_ptrtype_cache, key, result)) { - Py_DECREF(result); - Py_DECREF(key); - return NULL; - } - Py_DECREF(key); - return result; + PyObject *result; + PyTypeObject *typ; + PyObject *key; + char *buf; + + result = PyDict_GetItem(_ctypes_ptrtype_cache, cls); + if (result) { + Py_INCREF(result); + return result; + } + if (PyUnicode_CheckExact(cls)) { + char *name = _PyUnicode_AsString(cls); + buf = alloca(strlen(name) + 3 + 1); + sprintf(buf, "LP_%s", name); + result = PyObject_CallFunction((PyObject *)Py_TYPE(&PyCPointer_Type), + "s(O){}", + buf, + &PyCPointer_Type); + if (result == NULL) + return result; + key = PyLong_FromVoidPtr(result); + } else if (PyType_Check(cls)) { + typ = (PyTypeObject *)cls; + buf = alloca(strlen(typ->tp_name) + 3 + 1); + sprintf(buf, "LP_%s", typ->tp_name); + result = PyObject_CallFunction((PyObject *)Py_TYPE(&PyCPointer_Type), + "s(O){sO}", + buf, + &PyCPointer_Type, + "_type_", cls); + if (result == NULL) + return result; + Py_INCREF(cls); + key = cls; + } else { + PyErr_SetString(PyExc_TypeError, "must be a ctypes type"); + return NULL; + } + if (-1 == PyDict_SetItem(_ctypes_ptrtype_cache, key, result)) { + Py_DECREF(result); + Py_DECREF(key); + return NULL; + } + Py_DECREF(key); + return result; } static PyObject * pointer(PyObject *self, PyObject *arg) { - PyObject *result; - PyObject *typ; + PyObject *result; + PyObject *typ; - typ = PyDict_GetItem(_ctypes_ptrtype_cache, (PyObject *)Py_TYPE(arg)); - if (typ) - return PyObject_CallFunctionObjArgs(typ, arg, NULL); - typ = POINTER(NULL, (PyObject *)Py_TYPE(arg)); - if (typ == NULL) - return NULL; - result = PyObject_CallFunctionObjArgs(typ, arg, NULL); - Py_DECREF(typ); - return result; + typ = PyDict_GetItem(_ctypes_ptrtype_cache, (PyObject *)Py_TYPE(arg)); + if (typ) + return PyObject_CallFunctionObjArgs(typ, arg, NULL); + typ = POINTER(NULL, (PyObject *)Py_TYPE(arg)); + if (typ == NULL) + return NULL; + result = PyObject_CallFunctionObjArgs(typ, arg, NULL); + Py_DECREF(typ); + return result; } static PyObject * buffer_info(PyObject *self, PyObject *arg) { - StgDictObject *dict = PyType_stgdict(arg); - PyObject *shape; - Py_ssize_t i; - - if (dict == NULL) - dict = PyObject_stgdict(arg); - if (dict == NULL) { - PyErr_SetString(PyExc_TypeError, - "not a ctypes type or object"); - return NULL; - } - shape = PyTuple_New(dict->ndim); - if (shape == NULL) - return NULL; - for (i = 0; i < (int)dict->ndim; ++i) - PyTuple_SET_ITEM(shape, i, PyLong_FromSsize_t(dict->shape[i])); - - if (PyErr_Occurred()) { - Py_DECREF(shape); - return NULL; - } - return Py_BuildValue("siN", dict->format, dict->ndim, shape); + StgDictObject *dict = PyType_stgdict(arg); + PyObject *shape; + Py_ssize_t i; + + if (dict == NULL) + dict = PyObject_stgdict(arg); + if (dict == NULL) { + PyErr_SetString(PyExc_TypeError, + "not a ctypes type or object"); + return NULL; + } + shape = PyTuple_New(dict->ndim); + if (shape == NULL) + return NULL; + for (i = 0; i < (int)dict->ndim; ++i) + PyTuple_SET_ITEM(shape, i, PyLong_FromSsize_t(dict->shape[i])); + + if (PyErr_Occurred()) { + Py_DECREF(shape); + return NULL; + } + return Py_BuildValue("siN", dict->format, dict->ndim, shape); } PyMethodDef _ctypes_module_methods[] = { - {"get_errno", get_errno, METH_NOARGS}, - {"set_errno", set_errno, METH_VARARGS}, - {"POINTER", POINTER, METH_O }, - {"pointer", pointer, METH_O }, - {"_unpickle", unpickle, METH_VARARGS }, - {"buffer_info", buffer_info, METH_O, "Return buffer interface information"}, - {"resize", resize, METH_VARARGS, "Resize the memory buffer of a ctypes instance"}, + {"get_errno", get_errno, METH_NOARGS}, + {"set_errno", set_errno, METH_VARARGS}, + {"POINTER", POINTER, METH_O }, + {"pointer", pointer, METH_O }, + {"_unpickle", unpickle, METH_VARARGS }, + {"buffer_info", buffer_info, METH_O, "Return buffer interface information"}, + {"resize", resize, METH_VARARGS, "Resize the memory buffer of a ctypes instance"}, #ifdef CTYPES_UNICODE - {"set_conversion_mode", set_conversion_mode, METH_VARARGS, set_conversion_mode_doc}, + {"set_conversion_mode", set_conversion_mode, METH_VARARGS, set_conversion_mode_doc}, #endif #ifdef MS_WIN32 - {"get_last_error", get_last_error, METH_NOARGS}, - {"set_last_error", set_last_error, METH_VARARGS}, - {"CopyComPointer", copy_com_pointer, METH_VARARGS, copy_com_pointer_doc}, - {"FormatError", format_error, METH_VARARGS, format_error_doc}, - {"LoadLibrary", load_library, METH_VARARGS, load_library_doc}, - {"FreeLibrary", free_library, METH_VARARGS, free_library_doc}, - {"call_commethod", call_commethod, METH_VARARGS }, - {"_check_HRESULT", check_hresult, METH_VARARGS}, + {"get_last_error", get_last_error, METH_NOARGS}, + {"set_last_error", set_last_error, METH_VARARGS}, + {"CopyComPointer", copy_com_pointer, METH_VARARGS, copy_com_pointer_doc}, + {"FormatError", format_error, METH_VARARGS, format_error_doc}, + {"LoadLibrary", load_library, METH_VARARGS, load_library_doc}, + {"FreeLibrary", free_library, METH_VARARGS, free_library_doc}, + {"call_commethod", call_commethod, METH_VARARGS }, + {"_check_HRESULT", check_hresult, METH_VARARGS}, #else - {"dlopen", py_dl_open, METH_VARARGS, - "dlopen(name, flag={RTLD_GLOBAL|RTLD_LOCAL}) open a shared library"}, - {"dlclose", py_dl_close, METH_VARARGS, "dlclose a library"}, - {"dlsym", py_dl_sym, METH_VARARGS, "find symbol in shared library"}, -#endif - {"alignment", align_func, METH_O, alignment_doc}, - {"sizeof", sizeof_func, METH_O, sizeof_doc}, - {"byref", byref, METH_VARARGS, byref_doc}, - {"addressof", addressof, METH_O, addressof_doc}, - {"call_function", call_function, METH_VARARGS }, - {"call_cdeclfunction", call_cdeclfunction, METH_VARARGS }, - {"PyObj_FromPtr", My_PyObj_FromPtr, METH_VARARGS }, - {"Py_INCREF", My_Py_INCREF, METH_O }, - {"Py_DECREF", My_Py_DECREF, METH_O }, - {NULL, NULL} /* Sentinel */ + {"dlopen", py_dl_open, METH_VARARGS, + "dlopen(name, flag={RTLD_GLOBAL|RTLD_LOCAL}) open a shared library"}, + {"dlclose", py_dl_close, METH_VARARGS, "dlclose a library"}, + {"dlsym", py_dl_sym, METH_VARARGS, "find symbol in shared library"}, +#endif + {"alignment", align_func, METH_O, alignment_doc}, + {"sizeof", sizeof_func, METH_O, sizeof_doc}, + {"byref", byref, METH_VARARGS, byref_doc}, + {"addressof", addressof, METH_O, addressof_doc}, + {"call_function", call_function, METH_VARARGS }, + {"call_cdeclfunction", call_cdeclfunction, METH_VARARGS }, + {"PyObj_FromPtr", My_PyObj_FromPtr, METH_VARARGS }, + {"Py_INCREF", My_Py_INCREF, METH_O }, + {"Py_DECREF", My_Py_DECREF, METH_O }, + {NULL, NULL} /* Sentinel */ }; /* Modified: python/branches/py3k-jit/Modules/_ctypes/cfield.c ============================================================================== --- python/branches/py3k-jit/Modules/_ctypes/cfield.c (original) +++ python/branches/py3k-jit/Modules/_ctypes/cfield.c Mon May 10 23:55:43 2010 @@ -11,10 +11,10 @@ static void pymem_destructor(PyObject *ptr) { - void *p = PyCapsule_GetPointer(ptr, CTYPES_CFIELD_CAPSULE_NAME_PYMEM); - if (p) { - PyMem_Free(p); - } + void *p = PyCapsule_GetPointer(ptr, CTYPES_CFIELD_CAPSULE_NAME_PYMEM); + if (p) { + PyMem_Free(p); + } } @@ -25,9 +25,9 @@ static PyObject * PyCField_new(PyTypeObject *type, PyObject *args, PyObject *kwds) { - CFieldObject *obj; - obj = (CFieldObject *)type->tp_alloc(type, 0); - return (PyObject *)obj; + CFieldObject *obj; + obj = (CFieldObject *)type->tp_alloc(type, 0); + return (PyObject *)obj; } /* @@ -44,297 +44,297 @@ */ PyObject * PyCField_FromDesc(PyObject *desc, Py_ssize_t index, - Py_ssize_t *pfield_size, int bitsize, int *pbitofs, - Py_ssize_t *psize, Py_ssize_t *poffset, Py_ssize_t *palign, - int pack, int big_endian) -{ - CFieldObject *self; - PyObject *proto; - Py_ssize_t size, align, length; - SETFUNC setfunc = NULL; - GETFUNC getfunc = NULL; - StgDictObject *dict; - int fieldtype; + Py_ssize_t *pfield_size, int bitsize, int *pbitofs, + Py_ssize_t *psize, Py_ssize_t *poffset, Py_ssize_t *palign, + int pack, int big_endian) +{ + CFieldObject *self; + PyObject *proto; + Py_ssize_t size, align, length; + SETFUNC setfunc = NULL; + GETFUNC getfunc = NULL; + StgDictObject *dict; + int fieldtype; #define NO_BITFIELD 0 #define NEW_BITFIELD 1 #define CONT_BITFIELD 2 #define EXPAND_BITFIELD 3 - self = (CFieldObject *)PyObject_CallObject((PyObject *)&PyCField_Type, - NULL); - if (self == NULL) - return NULL; - dict = PyType_stgdict(desc); - if (!dict) { - PyErr_SetString(PyExc_TypeError, - "has no _stginfo_"); - Py_DECREF(self); - return NULL; - } - if (bitsize /* this is a bitfield request */ - && *pfield_size /* we have a bitfield open */ + self = (CFieldObject *)PyObject_CallObject((PyObject *)&PyCField_Type, + NULL); + if (self == NULL) + return NULL; + dict = PyType_stgdict(desc); + if (!dict) { + PyErr_SetString(PyExc_TypeError, + "has no _stginfo_"); + Py_DECREF(self); + return NULL; + } + if (bitsize /* this is a bitfield request */ + && *pfield_size /* we have a bitfield open */ #ifdef MS_WIN32 - /* MSVC, GCC with -mms-bitfields */ - && dict->size * 8 == *pfield_size + /* MSVC, GCC with -mms-bitfields */ + && dict->size * 8 == *pfield_size #else - /* GCC */ - && dict->size * 8 <= *pfield_size + /* GCC */ + && dict->size * 8 <= *pfield_size #endif - && (*pbitofs + bitsize) <= *pfield_size) { - /* continue bit field */ - fieldtype = CONT_BITFIELD; + && (*pbitofs + bitsize) <= *pfield_size) { + /* continue bit field */ + fieldtype = CONT_BITFIELD; #ifndef MS_WIN32 - } else if (bitsize /* this is a bitfield request */ - && *pfield_size /* we have a bitfield open */ - && dict->size * 8 >= *pfield_size - && (*pbitofs + bitsize) <= dict->size * 8) { - /* expand bit field */ - fieldtype = EXPAND_BITFIELD; -#endif - } else if (bitsize) { - /* start new bitfield */ - fieldtype = NEW_BITFIELD; - *pbitofs = 0; - *pfield_size = dict->size * 8; - } else { - /* not a bit field */ - fieldtype = NO_BITFIELD; - *pbitofs = 0; - *pfield_size = 0; - } - - size = dict->size; - length = dict->length; - proto = desc; - - /* Field descriptors for 'c_char * n' are be scpecial cased to - return a Python string instead of an Array object instance... - */ - if (PyCArrayTypeObject_Check(proto)) { - StgDictObject *adict = PyType_stgdict(proto); - StgDictObject *idict; - if (adict && adict->proto) { - idict = PyType_stgdict(adict->proto); - if (!idict) { - PyErr_SetString(PyExc_TypeError, - "has no _stginfo_"); - Py_DECREF(self); - return NULL; - } - if (idict->getfunc == _ctypes_get_fielddesc("c")->getfunc) { - struct fielddesc *fd = _ctypes_get_fielddesc("s"); - getfunc = fd->getfunc; - setfunc = fd->setfunc; - } + } else if (bitsize /* this is a bitfield request */ + && *pfield_size /* we have a bitfield open */ + && dict->size * 8 >= *pfield_size + && (*pbitofs + bitsize) <= dict->size * 8) { + /* expand bit field */ + fieldtype = EXPAND_BITFIELD; +#endif + } else if (bitsize) { + /* start new bitfield */ + fieldtype = NEW_BITFIELD; + *pbitofs = 0; + *pfield_size = dict->size * 8; + } else { + /* not a bit field */ + fieldtype = NO_BITFIELD; + *pbitofs = 0; + *pfield_size = 0; + } + + size = dict->size; + length = dict->length; + proto = desc; + + /* Field descriptors for 'c_char * n' are be scpecial cased to + return a Python string instead of an Array object instance... + */ + if (PyCArrayTypeObject_Check(proto)) { + StgDictObject *adict = PyType_stgdict(proto); + StgDictObject *idict; + if (adict && adict->proto) { + idict = PyType_stgdict(adict->proto); + if (!idict) { + PyErr_SetString(PyExc_TypeError, + "has no _stginfo_"); + Py_DECREF(self); + return NULL; + } + if (idict->getfunc == _ctypes_get_fielddesc("c")->getfunc) { + struct fielddesc *fd = _ctypes_get_fielddesc("s"); + getfunc = fd->getfunc; + setfunc = fd->setfunc; + } #ifdef CTYPES_UNICODE - if (idict->getfunc == _ctypes_get_fielddesc("u")->getfunc) { - struct fielddesc *fd = _ctypes_get_fielddesc("U"); - getfunc = fd->getfunc; - setfunc = fd->setfunc; - } -#endif - } - } - - self->setfunc = setfunc; - self->getfunc = getfunc; - self->index = index; - - Py_INCREF(proto); - self->proto = proto; - - switch (fieldtype) { - case NEW_BITFIELD: - if (big_endian) - self->size = (bitsize << 16) + *pfield_size - *pbitofs - bitsize; - else - self->size = (bitsize << 16) + *pbitofs; - *pbitofs = bitsize; - /* fall through */ - case NO_BITFIELD: - if (pack) - align = min(pack, dict->align); - else - align = dict->align; - if (align && *poffset % align) { - Py_ssize_t delta = align - (*poffset % align); - *psize += delta; - *poffset += delta; - } - - if (bitsize == 0) - self->size = size; - *psize += size; - - self->offset = *poffset; - *poffset += size; - - *palign = align; - break; - - case EXPAND_BITFIELD: - *poffset += dict->size - *pfield_size/8; - *psize += dict->size - *pfield_size/8; - - *pfield_size = dict->size * 8; - - if (big_endian) - self->size = (bitsize << 16) + *pfield_size - *pbitofs - bitsize; - else - self->size = (bitsize << 16) + *pbitofs; - - self->offset = *poffset - size; /* poffset is already updated for the NEXT field */ - *pbitofs += bitsize; - break; - - case CONT_BITFIELD: - if (big_endian) - self->size = (bitsize << 16) + *pfield_size - *pbitofs - bitsize; - else - self->size = (bitsize << 16) + *pbitofs; - - self->offset = *poffset - size; /* poffset is already updated for the NEXT field */ - *pbitofs += bitsize; - break; - } + if (idict->getfunc == _ctypes_get_fielddesc("u")->getfunc) { + struct fielddesc *fd = _ctypes_get_fielddesc("U"); + getfunc = fd->getfunc; + setfunc = fd->setfunc; + } +#endif + } + } + + self->setfunc = setfunc; + self->getfunc = getfunc; + self->index = index; + + Py_INCREF(proto); + self->proto = proto; + + switch (fieldtype) { + case NEW_BITFIELD: + if (big_endian) + self->size = (bitsize << 16) + *pfield_size - *pbitofs - bitsize; + else + self->size = (bitsize << 16) + *pbitofs; + *pbitofs = bitsize; + /* fall through */ + case NO_BITFIELD: + if (pack) + align = min(pack, dict->align); + else + align = dict->align; + if (align && *poffset % align) { + Py_ssize_t delta = align - (*poffset % align); + *psize += delta; + *poffset += delta; + } + + if (bitsize == 0) + self->size = size; + *psize += size; + + self->offset = *poffset; + *poffset += size; + + *palign = align; + break; + + case EXPAND_BITFIELD: + *poffset += dict->size - *pfield_size/8; + *psize += dict->size - *pfield_size/8; + + *pfield_size = dict->size * 8; + + if (big_endian) + self->size = (bitsize << 16) + *pfield_size - *pbitofs - bitsize; + else + self->size = (bitsize << 16) + *pbitofs; + + self->offset = *poffset - size; /* poffset is already updated for the NEXT field */ + *pbitofs += bitsize; + break; + + case CONT_BITFIELD: + if (big_endian) + self->size = (bitsize << 16) + *pfield_size - *pbitofs - bitsize; + else + self->size = (bitsize << 16) + *pbitofs; + + self->offset = *poffset - size; /* poffset is already updated for the NEXT field */ + *pbitofs += bitsize; + break; + } - return (PyObject *)self; + return (PyObject *)self; } static int PyCField_set(CFieldObject *self, PyObject *inst, PyObject *value) { - CDataObject *dst; - char *ptr; - assert(CDataObject_Check(inst)); - dst = (CDataObject *)inst; - ptr = dst->b_ptr + self->offset; - if (value == NULL) { - PyErr_SetString(PyExc_TypeError, - "can't delete attribute"); - return -1; - } - return PyCData_set(inst, self->proto, self->setfunc, value, - self->index, self->size, ptr); + CDataObject *dst; + char *ptr; + assert(CDataObject_Check(inst)); + dst = (CDataObject *)inst; + ptr = dst->b_ptr + self->offset; + if (value == NULL) { + PyErr_SetString(PyExc_TypeError, + "can't delete attribute"); + return -1; + } + return PyCData_set(inst, self->proto, self->setfunc, value, + self->index, self->size, ptr); } static PyObject * PyCField_get(CFieldObject *self, PyObject *inst, PyTypeObject *type) { - CDataObject *src; - if (inst == NULL) { - Py_INCREF(self); - return (PyObject *)self; - } - assert(CDataObject_Check(inst)); - src = (CDataObject *)inst; - return PyCData_get(self->proto, self->getfunc, inst, - self->index, self->size, src->b_ptr + self->offset); + CDataObject *src; + if (inst == NULL) { + Py_INCREF(self); + return (PyObject *)self; + } + assert(CDataObject_Check(inst)); + src = (CDataObject *)inst; + return PyCData_get(self->proto, self->getfunc, inst, + self->index, self->size, src->b_ptr + self->offset); } static PyObject * PyCField_get_offset(PyObject *self, void *data) { - return PyLong_FromSsize_t(((CFieldObject *)self)->offset); + return PyLong_FromSsize_t(((CFieldObject *)self)->offset); } static PyObject * PyCField_get_size(PyObject *self, void *data) { - return PyLong_FromSsize_t(((CFieldObject *)self)->size); + return PyLong_FromSsize_t(((CFieldObject *)self)->size); } static PyGetSetDef PyCField_getset[] = { - { "offset", PyCField_get_offset, NULL, "offset in bytes of this field" }, - { "size", PyCField_get_size, NULL, "size in bytes of this field" }, - { NULL, NULL, NULL, NULL }, + { "offset", PyCField_get_offset, NULL, "offset in bytes of this field" }, + { "size", PyCField_get_size, NULL, "size in bytes of this field" }, + { NULL, NULL, NULL, NULL }, }; static int PyCField_traverse(CFieldObject *self, visitproc visit, void *arg) { - Py_VISIT(self->proto); - return 0; + Py_VISIT(self->proto); + return 0; } static int PyCField_clear(CFieldObject *self) { - Py_CLEAR(self->proto); - return 0; + Py_CLEAR(self->proto); + return 0; } static void PyCField_dealloc(PyObject *self) { - PyCField_clear((CFieldObject *)self); - self->ob_type->tp_free((PyObject *)self); + PyCField_clear((CFieldObject *)self); + self->ob_type->tp_free((PyObject *)self); } static PyObject * PyCField_repr(CFieldObject *self) { - PyObject *result; - Py_ssize_t bits = self->size >> 16; - Py_ssize_t size = self->size & 0xFFFF; - const char *name; - - name = ((PyTypeObject *)self->proto)->tp_name; - - if (bits) - result = PyUnicode_FromFormat( - "", - name, self->offset, size, bits); - else - result = PyUnicode_FromFormat( - "", - name, self->offset, size); - return result; + PyObject *result; + Py_ssize_t bits = self->size >> 16; + Py_ssize_t size = self->size & 0xFFFF; + const char *name; + + name = ((PyTypeObject *)self->proto)->tp_name; + + if (bits) + result = PyUnicode_FromFormat( + "", + name, self->offset, size, bits); + else + result = PyUnicode_FromFormat( + "", + name, self->offset, size); + return result; } PyTypeObject PyCField_Type = { - PyVarObject_HEAD_INIT(NULL, 0) - "_ctypes.CField", /* tp_name */ - sizeof(CFieldObject), /* tp_basicsize */ - 0, /* tp_itemsize */ - PyCField_dealloc, /* tp_dealloc */ - 0, /* tp_print */ - 0, /* tp_getattr */ - 0, /* tp_setattr */ - 0, /* tp_reserved */ - (reprfunc)PyCField_repr, /* tp_repr */ - 0, /* tp_as_number */ - 0, /* tp_as_sequence */ - 0, /* tp_as_mapping */ - 0, /* tp_hash */ - 0, /* tp_call */ - 0, /* tp_str */ - 0, /* tp_getattro */ - 0, /* tp_setattro */ - 0, /* tp_as_buffer */ - Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC, /* tp_flags */ - "Structure/Union member", /* tp_doc */ - (traverseproc)PyCField_traverse, /* tp_traverse */ - (inquiry)PyCField_clear, /* tp_clear */ - 0, /* tp_richcompare */ - 0, /* tp_weaklistoffset */ - 0, /* tp_iter */ - 0, /* tp_iternext */ - 0, /* tp_methods */ - 0, /* tp_members */ - PyCField_getset, /* tp_getset */ - 0, /* tp_base */ - 0, /* tp_dict */ - (descrgetfunc)PyCField_get, /* tp_descr_get */ - (descrsetfunc)PyCField_set, /* tp_descr_set */ - 0, /* tp_dictoffset */ - 0, /* tp_init */ - 0, /* tp_alloc */ - PyCField_new, /* tp_new */ - 0, /* tp_free */ + PyVarObject_HEAD_INIT(NULL, 0) + "_ctypes.CField", /* tp_name */ + sizeof(CFieldObject), /* tp_basicsize */ + 0, /* tp_itemsize */ + PyCField_dealloc, /* tp_dealloc */ + 0, /* tp_print */ + 0, /* tp_getattr */ + 0, /* tp_setattr */ + 0, /* tp_reserved */ + (reprfunc)PyCField_repr, /* tp_repr */ + 0, /* tp_as_number */ + 0, /* tp_as_sequence */ + 0, /* tp_as_mapping */ + 0, /* tp_hash */ + 0, /* tp_call */ + 0, /* tp_str */ + 0, /* tp_getattro */ + 0, /* tp_setattro */ + 0, /* tp_as_buffer */ + Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC, /* tp_flags */ + "Structure/Union member", /* tp_doc */ + (traverseproc)PyCField_traverse, /* tp_traverse */ + (inquiry)PyCField_clear, /* tp_clear */ + 0, /* tp_richcompare */ + 0, /* tp_weaklistoffset */ + 0, /* tp_iter */ + 0, /* tp_iternext */ + 0, /* tp_methods */ + 0, /* tp_members */ + PyCField_getset, /* tp_getset */ + 0, /* tp_base */ + 0, /* tp_dict */ + (descrgetfunc)PyCField_get, /* tp_descr_get */ + (descrsetfunc)PyCField_set, /* tp_descr_set */ + 0, /* tp_dictoffset */ + 0, /* tp_init */ + 0, /* tp_alloc */ + PyCField_new, /* tp_new */ + 0, /* tp_free */ }; - + /******************************************************************/ /* Accessor functions @@ -347,18 +347,18 @@ static int get_long(PyObject *v, long *p) { - long x; + long x; - if (PyFloat_Check(v)) { - PyErr_SetString(PyExc_TypeError, - "int expected instead of float"); - return -1; - } - x = PyLong_AsUnsignedLongMask(v); - if (x == -1 && PyErr_Occurred()) - return -1; - *p = x; - return 0; + if (PyFloat_Check(v)) { + PyErr_SetString(PyExc_TypeError, + "int expected instead of float"); + return -1; + } + x = PyLong_AsUnsignedLongMask(v); + if (x == -1 && PyErr_Occurred()) + return -1; + *p = x; + return 0; } /* Same, but handling unsigned long */ @@ -366,18 +366,18 @@ static int get_ulong(PyObject *v, unsigned long *p) { - unsigned long x; + unsigned long x; - if (PyFloat_Check(v)) { - PyErr_SetString(PyExc_TypeError, - "int expected instead of float"); - return -1; - } - x = PyLong_AsUnsignedLongMask(v); - if (x == (unsigned long)-1 && PyErr_Occurred()) - return -1; - *p = x; - return 0; + if (PyFloat_Check(v)) { + PyErr_SetString(PyExc_TypeError, + "int expected instead of float"); + return -1; + } + x = PyLong_AsUnsignedLongMask(v); + if (x == (unsigned long)-1 && PyErr_Occurred()) + return -1; + *p = x; + return 0; } #ifdef HAVE_LONG_LONG @@ -387,17 +387,17 @@ static int get_longlong(PyObject *v, PY_LONG_LONG *p) { - PY_LONG_LONG x; - if (PyFloat_Check(v)) { - PyErr_SetString(PyExc_TypeError, - "int expected instead of float"); - return -1; - } - x = PyLong_AsUnsignedLongLongMask(v); - if (x == -1 && PyErr_Occurred()) - return -1; - *p = x; - return 0; + PY_LONG_LONG x; + if (PyFloat_Check(v)) { + PyErr_SetString(PyExc_TypeError, + "int expected instead of float"); + return -1; + } + x = PyLong_AsUnsignedLongLongMask(v); + if (x == -1 && PyErr_Occurred()) + return -1; + *p = x; + return 0; } /* Same, but handling native unsigned long long. */ @@ -405,17 +405,17 @@ static int get_ulonglong(PyObject *v, unsigned PY_LONG_LONG *p) { - unsigned PY_LONG_LONG x; - if (PyFloat_Check(v)) { - PyErr_SetString(PyExc_TypeError, - "int expected instead of float"); - return -1; - } - x = PyLong_AsUnsignedLongLongMask(v); - if (x == (unsigned PY_LONG_LONG)-1 && PyErr_Occurred()) - return -1; - *p = x; - return 0; + unsigned PY_LONG_LONG x; + if (PyFloat_Check(v)) { + PyErr_SetString(PyExc_TypeError, + "int expected instead of float"); + return -1; + } + x = PyLong_AsUnsignedLongLongMask(v); + if (x == (unsigned PY_LONG_LONG)-1 && PyErr_Occurred()) + return -1; + *p = x; + return 0; } #endif @@ -438,49 +438,49 @@ /* This macro CHANGES the first parameter IN PLACE. For proper sign handling, we must first shift left, then right. */ -#define GET_BITFIELD(v, size) \ - if (NUM_BITS(size)) { \ - v <<= (sizeof(v)*8 - LOW_BIT(size) - NUM_BITS(size)); \ - v >>= (sizeof(v)*8 - NUM_BITS(size)); \ - } +#define GET_BITFIELD(v, size) \ + if (NUM_BITS(size)) { \ + v <<= (sizeof(v)*8 - LOW_BIT(size) - NUM_BITS(size)); \ + v >>= (sizeof(v)*8 - NUM_BITS(size)); \ + } /* This macro RETURNS the first parameter with the bit field CHANGED. */ -#define SET(x, v, size) \ - (NUM_BITS(size) ? \ - ( ( x & ~(BIT_MASK(size) << LOW_BIT(size)) ) | ( (v & BIT_MASK(size)) << LOW_BIT(size) ) ) \ - : v) +#define SET(x, v, size) \ + (NUM_BITS(size) ? \ + ( ( x & ~(BIT_MASK(size) << LOW_BIT(size)) ) | ( (v & BIT_MASK(size)) << LOW_BIT(size) ) ) \ + : v) /* byte swapping macros */ -#define SWAP_2(v) \ - ( ( (v >> 8) & 0x00FF) | \ - ( (v << 8) & 0xFF00) ) - -#define SWAP_4(v) \ - ( ( (v & 0x000000FF) << 24 ) | \ - ( (v & 0x0000FF00) << 8 ) | \ - ( (v & 0x00FF0000) >> 8 ) | \ - ( ((v >> 24) & 0xFF)) ) +#define SWAP_2(v) \ + ( ( (v >> 8) & 0x00FF) | \ + ( (v << 8) & 0xFF00) ) + +#define SWAP_4(v) \ + ( ( (v & 0x000000FF) << 24 ) | \ + ( (v & 0x0000FF00) << 8 ) | \ + ( (v & 0x00FF0000) >> 8 ) | \ + ( ((v >> 24) & 0xFF)) ) #ifdef _MSC_VER -#define SWAP_8(v) \ - ( ( (v & 0x00000000000000FFL) << 56 ) | \ - ( (v & 0x000000000000FF00L) << 40 ) | \ - ( (v & 0x0000000000FF0000L) << 24 ) | \ - ( (v & 0x00000000FF000000L) << 8 ) | \ - ( (v & 0x000000FF00000000L) >> 8 ) | \ - ( (v & 0x0000FF0000000000L) >> 24 ) | \ - ( (v & 0x00FF000000000000L) >> 40 ) | \ - ( ((v >> 56) & 0xFF)) ) +#define SWAP_8(v) \ + ( ( (v & 0x00000000000000FFL) << 56 ) | \ + ( (v & 0x000000000000FF00L) << 40 ) | \ + ( (v & 0x0000000000FF0000L) << 24 ) | \ + ( (v & 0x00000000FF000000L) << 8 ) | \ + ( (v & 0x000000FF00000000L) >> 8 ) | \ + ( (v & 0x0000FF0000000000L) >> 24 ) | \ + ( (v & 0x00FF000000000000L) >> 40 ) | \ + ( ((v >> 56) & 0xFF)) ) #else -#define SWAP_8(v) \ - ( ( (v & 0x00000000000000FFLL) << 56 ) | \ - ( (v & 0x000000000000FF00LL) << 40 ) | \ - ( (v & 0x0000000000FF0000LL) << 24 ) | \ - ( (v & 0x00000000FF000000LL) << 8 ) | \ - ( (v & 0x000000FF00000000LL) >> 8 ) | \ - ( (v & 0x0000FF0000000000LL) >> 24 ) | \ - ( (v & 0x00FF000000000000LL) >> 40 ) | \ - ( ((v >> 56) & 0xFF)) ) +#define SWAP_8(v) \ + ( ( (v & 0x00000000000000FFLL) << 56 ) | \ + ( (v & 0x000000000000FF00LL) << 40 ) | \ + ( (v & 0x0000000000FF0000LL) << 24 ) | \ + ( (v & 0x00000000FF000000LL) << 8 ) | \ + ( (v & 0x000000FF00000000LL) >> 8 ) | \ + ( (v & 0x0000FF0000000000LL) >> 24 ) | \ + ( (v & 0x00FF000000000000LL) >> 40 ) | \ + ( ((v >> 56) & 0xFF)) ) #endif #define SWAP_INT SWAP_4 @@ -517,184 +517,184 @@ static PyObject * b_set(void *ptr, PyObject *value, Py_ssize_t size) { - long val; - if (get_long(value, &val) < 0) - return NULL; - *(signed char *)ptr = (signed char)SET(*(signed char *)ptr, (signed char)val, size); - _RET(value); + long val; + if (get_long(value, &val) < 0) + return NULL; + *(signed char *)ptr = (signed char)SET(*(signed char *)ptr, (signed char)val, size); + _RET(value); } static PyObject * b_get(void *ptr, Py_ssize_t size) { - signed char val = *(signed char *)ptr; - GET_BITFIELD(val, size); - return PyLong_FromLong(val); + signed char val = *(signed char *)ptr; + GET_BITFIELD(val, size); + return PyLong_FromLong(val); } static PyObject * B_set(void *ptr, PyObject *value, Py_ssize_t size) { - unsigned long val; - if (get_ulong(value, &val) < 0) - return NULL; - *(unsigned char *)ptr = (unsigned char)SET(*(unsigned char*)ptr, - (unsigned short)val, size); - _RET(value); + unsigned long val; + if (get_ulong(value, &val) < 0) + return NULL; + *(unsigned char *)ptr = (unsigned char)SET(*(unsigned char*)ptr, + (unsigned short)val, size); + _RET(value); } static PyObject * B_get(void *ptr, Py_ssize_t size) { - unsigned char val = *(unsigned char *)ptr; - GET_BITFIELD(val, size); - return PyLong_FromLong(val); + unsigned char val = *(unsigned char *)ptr; + GET_BITFIELD(val, size); + return PyLong_FromLong(val); } static PyObject * h_set(void *ptr, PyObject *value, Py_ssize_t size) { - long val; - short x; - if (get_long(value, &val) < 0) - return NULL; - memcpy(&x, ptr, sizeof(x)); - x = SET(x, (short)val, size); - memcpy(ptr, &x, sizeof(x)); - _RET(value); + long val; + short x; + if (get_long(value, &val) < 0) + return NULL; + memcpy(&x, ptr, sizeof(x)); + x = SET(x, (short)val, size); + memcpy(ptr, &x, sizeof(x)); + _RET(value); } static PyObject * h_set_sw(void *ptr, PyObject *value, Py_ssize_t size) { - long val; - short field; - if (get_long(value, &val) < 0) - return NULL; - memcpy(&field, ptr, sizeof(field)); - field = SWAP_2(field); - field = SET(field, (short)val, size); - field = SWAP_2(field); - memcpy(ptr, &field, sizeof(field)); - _RET(value); + long val; + short field; + if (get_long(value, &val) < 0) + return NULL; + memcpy(&field, ptr, sizeof(field)); + field = SWAP_2(field); + field = SET(field, (short)val, size); + field = SWAP_2(field); + memcpy(ptr, &field, sizeof(field)); + _RET(value); } static PyObject * h_get(void *ptr, Py_ssize_t size) { - short val; - memcpy(&val, ptr, sizeof(val)); - GET_BITFIELD(val, size); - return PyLong_FromLong((long)val); + short val; + memcpy(&val, ptr, sizeof(val)); + GET_BITFIELD(val, size); + return PyLong_FromLong((long)val); } static PyObject * h_get_sw(void *ptr, Py_ssize_t size) { - short val; - memcpy(&val, ptr, sizeof(val)); - val = SWAP_2(val); - GET_BITFIELD(val, size); - return PyLong_FromLong(val); + short val; + memcpy(&val, ptr, sizeof(val)); + val = SWAP_2(val); + GET_BITFIELD(val, size); + return PyLong_FromLong(val); } static PyObject * H_set(void *ptr, PyObject *value, Py_ssize_t size) { - unsigned long val; - unsigned short x; - if (get_ulong(value, &val) < 0) - return NULL; - memcpy(&x, ptr, sizeof(x)); - x = SET(x, (unsigned short)val, size); - memcpy(ptr, &x, sizeof(x)); - _RET(value); + unsigned long val; + unsigned short x; + if (get_ulong(value, &val) < 0) + return NULL; + memcpy(&x, ptr, sizeof(x)); + x = SET(x, (unsigned short)val, size); + memcpy(ptr, &x, sizeof(x)); + _RET(value); } static PyObject * H_set_sw(void *ptr, PyObject *value, Py_ssize_t size) { - unsigned long val; - unsigned short field; - if (get_ulong(value, &val) < 0) - return NULL; - memcpy(&field, ptr, sizeof(field)); - field = SWAP_2(field); - field = SET(field, (unsigned short)val, size); - field = SWAP_2(field); - memcpy(ptr, &field, sizeof(field)); - _RET(value); + unsigned long val; + unsigned short field; + if (get_ulong(value, &val) < 0) + return NULL; + memcpy(&field, ptr, sizeof(field)); + field = SWAP_2(field); + field = SET(field, (unsigned short)val, size); + field = SWAP_2(field); + memcpy(ptr, &field, sizeof(field)); + _RET(value); } static PyObject * H_get(void *ptr, Py_ssize_t size) { - unsigned short val; - memcpy(&val, ptr, sizeof(val)); - GET_BITFIELD(val, size); - return PyLong_FromLong(val); + unsigned short val; + memcpy(&val, ptr, sizeof(val)); + GET_BITFIELD(val, size); + return PyLong_FromLong(val); } static PyObject * H_get_sw(void *ptr, Py_ssize_t size) { - unsigned short val; - memcpy(&val, ptr, sizeof(val)); - val = SWAP_2(val); - GET_BITFIELD(val, size); - return PyLong_FromLong(val); + unsigned short val; + memcpy(&val, ptr, sizeof(val)); + val = SWAP_2(val); + GET_BITFIELD(val, size); + return PyLong_FromLong(val); } static PyObject * i_set(void *ptr, PyObject *value, Py_ssize_t size) { - long val; - int x; - if (get_long(value, &val) < 0) - return NULL; - memcpy(&x, ptr, sizeof(x)); - x = SET(x, (int)val, size); - memcpy(ptr, &x, sizeof(x)); - _RET(value); + long val; + int x; + if (get_long(value, &val) < 0) + return NULL; + memcpy(&x, ptr, sizeof(x)); + x = SET(x, (int)val, size); + memcpy(ptr, &x, sizeof(x)); + _RET(value); } static PyObject * i_set_sw(void *ptr, PyObject *value, Py_ssize_t size) { - long val; - int field; - if (get_long(value, &val) < 0) - return NULL; - memcpy(&field, ptr, sizeof(field)); - field = SWAP_INT(field); - field = SET(field, (int)val, size); - field = SWAP_INT(field); - memcpy(ptr, &field, sizeof(field)); - _RET(value); + long val; + int field; + if (get_long(value, &val) < 0) + return NULL; + memcpy(&field, ptr, sizeof(field)); + field = SWAP_INT(field); + field = SET(field, (int)val, size); + field = SWAP_INT(field); + memcpy(ptr, &field, sizeof(field)); + _RET(value); } static PyObject * i_get(void *ptr, Py_ssize_t size) { - int val; - memcpy(&val, ptr, sizeof(val)); - GET_BITFIELD(val, size); - return PyLong_FromLong(val); + int val; + memcpy(&val, ptr, sizeof(val)); + GET_BITFIELD(val, size); + return PyLong_FromLong(val); } static PyObject * i_get_sw(void *ptr, Py_ssize_t size) { - int val; - memcpy(&val, ptr, sizeof(val)); - val = SWAP_INT(val); - GET_BITFIELD(val, size); - return PyLong_FromLong(val); + int val; + memcpy(&val, ptr, sizeof(val)); + val = SWAP_INT(val); + GET_BITFIELD(val, size); + return PyLong_FromLong(val); } #ifdef MS_WIN32 @@ -702,22 +702,22 @@ static PyObject * vBOOL_set(void *ptr, PyObject *value, Py_ssize_t size) { - switch (PyObject_IsTrue(value)) { - case -1: - return NULL; - case 0: - *(short int *)ptr = VARIANT_FALSE; - _RET(value); - default: - *(short int *)ptr = VARIANT_TRUE; - _RET(value); - } + switch (PyObject_IsTrue(value)) { + case -1: + return NULL; + case 0: + *(short int *)ptr = VARIANT_FALSE; + _RET(value); + default: + *(short int *)ptr = VARIANT_TRUE; + _RET(value); + } } static PyObject * vBOOL_get(void *ptr, Py_ssize_t size) { - return PyBool_FromLong((long)*(short int *)ptr); + return PyBool_FromLong((long)*(short int *)ptr); } #endif @@ -732,260 +732,260 @@ static PyObject * bool_set(void *ptr, PyObject *value, Py_ssize_t size) { - switch (PyObject_IsTrue(value)) { - case -1: - return NULL; - case 0: - *(BOOL_TYPE *)ptr = 0; - _RET(value); - default: - *(BOOL_TYPE *)ptr = 1; - _RET(value); - } + switch (PyObject_IsTrue(value)) { + case -1: + return NULL; + case 0: + *(BOOL_TYPE *)ptr = 0; + _RET(value); + default: + *(BOOL_TYPE *)ptr = 1; + _RET(value); + } } static PyObject * bool_get(void *ptr, Py_ssize_t size) { - return PyBool_FromLong((long)*(BOOL_TYPE *)ptr); + return PyBool_FromLong((long)*(BOOL_TYPE *)ptr); } static PyObject * I_set(void *ptr, PyObject *value, Py_ssize_t size) { - unsigned long val; - unsigned int x; - if (get_ulong(value, &val) < 0) - return NULL; - memcpy(&x, ptr, sizeof(x)); - x = SET(x, (unsigned int)val, size); - memcpy(ptr, &x, sizeof(x)); - _RET(value); + unsigned long val; + unsigned int x; + if (get_ulong(value, &val) < 0) + return NULL; + memcpy(&x, ptr, sizeof(x)); + x = SET(x, (unsigned int)val, size); + memcpy(ptr, &x, sizeof(x)); + _RET(value); } static PyObject * I_set_sw(void *ptr, PyObject *value, Py_ssize_t size) { - unsigned long val; - unsigned int field; - if (get_ulong(value, &val) < 0) - return NULL; - memcpy(&field, ptr, sizeof(field)); - field = (unsigned int)SET(field, (unsigned int)val, size); - field = SWAP_INT(field); - memcpy(ptr, &field, sizeof(field)); - _RET(value); + unsigned long val; + unsigned int field; + if (get_ulong(value, &val) < 0) + return NULL; + memcpy(&field, ptr, sizeof(field)); + field = (unsigned int)SET(field, (unsigned int)val, size); + field = SWAP_INT(field); + memcpy(ptr, &field, sizeof(field)); + _RET(value); } static PyObject * I_get(void *ptr, Py_ssize_t size) { - unsigned int val; - memcpy(&val, ptr, sizeof(val)); - GET_BITFIELD(val, size); - return PyLong_FromUnsignedLong(val); + unsigned int val; + memcpy(&val, ptr, sizeof(val)); + GET_BITFIELD(val, size); + return PyLong_FromUnsignedLong(val); } static PyObject * I_get_sw(void *ptr, Py_ssize_t size) { - unsigned int val; - memcpy(&val, ptr, sizeof(val)); - val = SWAP_INT(val); - GET_BITFIELD(val, size); - return PyLong_FromUnsignedLong(val); + unsigned int val; + memcpy(&val, ptr, sizeof(val)); + val = SWAP_INT(val); + GET_BITFIELD(val, size); + return PyLong_FromUnsignedLong(val); } static PyObject * l_set(void *ptr, PyObject *value, Py_ssize_t size) { - long val; - long x; - if (get_long(value, &val) < 0) - return NULL; - memcpy(&x, ptr, sizeof(x)); - x = SET(x, val, size); - memcpy(ptr, &x, sizeof(x)); - _RET(value); + long val; + long x; + if (get_long(value, &val) < 0) + return NULL; + memcpy(&x, ptr, sizeof(x)); + x = SET(x, val, size); + memcpy(ptr, &x, sizeof(x)); + _RET(value); } static PyObject * l_set_sw(void *ptr, PyObject *value, Py_ssize_t size) { - long val; - long field; - if (get_long(value, &val) < 0) - return NULL; - memcpy(&field, ptr, sizeof(field)); - field = SWAP_LONG(field); - field = (long)SET(field, val, size); - field = SWAP_LONG(field); - memcpy(ptr, &field, sizeof(field)); - _RET(value); + long val; + long field; + if (get_long(value, &val) < 0) + return NULL; + memcpy(&field, ptr, sizeof(field)); + field = SWAP_LONG(field); + field = (long)SET(field, val, size); + field = SWAP_LONG(field); + memcpy(ptr, &field, sizeof(field)); + _RET(value); } static PyObject * l_get(void *ptr, Py_ssize_t size) { - long val; - memcpy(&val, ptr, sizeof(val)); - GET_BITFIELD(val, size); - return PyLong_FromLong(val); + long val; + memcpy(&val, ptr, sizeof(val)); + GET_BITFIELD(val, size); + return PyLong_FromLong(val); } static PyObject * l_get_sw(void *ptr, Py_ssize_t size) { - long val; - memcpy(&val, ptr, sizeof(val)); - val = SWAP_LONG(val); - GET_BITFIELD(val, size); - return PyLong_FromLong(val); + long val; + memcpy(&val, ptr, sizeof(val)); + val = SWAP_LONG(val); + GET_BITFIELD(val, size); + return PyLong_FromLong(val); } static PyObject * L_set(void *ptr, PyObject *value, Py_ssize_t size) { - unsigned long val; - unsigned long x; - if (get_ulong(value, &val) < 0) - return NULL; - memcpy(&x, ptr, sizeof(x)); - x = SET(x, val, size); - memcpy(ptr, &x, sizeof(x)); - _RET(value); + unsigned long val; + unsigned long x; + if (get_ulong(value, &val) < 0) + return NULL; + memcpy(&x, ptr, sizeof(x)); + x = SET(x, val, size); + memcpy(ptr, &x, sizeof(x)); + _RET(value); } static PyObject * L_set_sw(void *ptr, PyObject *value, Py_ssize_t size) { - unsigned long val; - unsigned long field; - if (get_ulong(value, &val) < 0) - return NULL; - memcpy(&field, ptr, sizeof(field)); - field = SWAP_LONG(field); - field = (unsigned long)SET(field, val, size); - field = SWAP_LONG(field); - memcpy(ptr, &field, sizeof(field)); - _RET(value); + unsigned long val; + unsigned long field; + if (get_ulong(value, &val) < 0) + return NULL; + memcpy(&field, ptr, sizeof(field)); + field = SWAP_LONG(field); + field = (unsigned long)SET(field, val, size); + field = SWAP_LONG(field); + memcpy(ptr, &field, sizeof(field)); + _RET(value); } static PyObject * L_get(void *ptr, Py_ssize_t size) { - unsigned long val; - memcpy(&val, ptr, sizeof(val)); - GET_BITFIELD(val, size); - return PyLong_FromUnsignedLong(val); + unsigned long val; + memcpy(&val, ptr, sizeof(val)); + GET_BITFIELD(val, size); + return PyLong_FromUnsignedLong(val); } static PyObject * L_get_sw(void *ptr, Py_ssize_t size) { - unsigned long val; - memcpy(&val, ptr, sizeof(val)); - val = SWAP_LONG(val); - GET_BITFIELD(val, size); - return PyLong_FromUnsignedLong(val); + unsigned long val; + memcpy(&val, ptr, sizeof(val)); + val = SWAP_LONG(val); + GET_BITFIELD(val, size); + return PyLong_FromUnsignedLong(val); } #ifdef HAVE_LONG_LONG static PyObject * q_set(void *ptr, PyObject *value, Py_ssize_t size) { - PY_LONG_LONG val; - PY_LONG_LONG x; - if (get_longlong(value, &val) < 0) - return NULL; - memcpy(&x, ptr, sizeof(x)); - x = SET(x, val, size); - memcpy(ptr, &x, sizeof(x)); - _RET(value); + PY_LONG_LONG val; + PY_LONG_LONG x; + if (get_longlong(value, &val) < 0) + return NULL; + memcpy(&x, ptr, sizeof(x)); + x = SET(x, val, size); + memcpy(ptr, &x, sizeof(x)); + _RET(value); } static PyObject * q_set_sw(void *ptr, PyObject *value, Py_ssize_t size) { - PY_LONG_LONG val; - PY_LONG_LONG field; - if (get_longlong(value, &val) < 0) - return NULL; - memcpy(&field, ptr, sizeof(field)); - field = SWAP_8(field); - field = (PY_LONG_LONG)SET(field, val, size); - field = SWAP_8(field); - memcpy(ptr, &field, sizeof(field)); - _RET(value); + PY_LONG_LONG val; + PY_LONG_LONG field; + if (get_longlong(value, &val) < 0) + return NULL; + memcpy(&field, ptr, sizeof(field)); + field = SWAP_8(field); + field = (PY_LONG_LONG)SET(field, val, size); + field = SWAP_8(field); + memcpy(ptr, &field, sizeof(field)); + _RET(value); } static PyObject * q_get(void *ptr, Py_ssize_t size) { - PY_LONG_LONG val; - memcpy(&val, ptr, sizeof(val)); - GET_BITFIELD(val, size); - return PyLong_FromLongLong(val); + PY_LONG_LONG val; + memcpy(&val, ptr, sizeof(val)); + GET_BITFIELD(val, size); + return PyLong_FromLongLong(val); } static PyObject * q_get_sw(void *ptr, Py_ssize_t size) { - PY_LONG_LONG val; - memcpy(&val, ptr, sizeof(val)); - val = SWAP_8(val); - GET_BITFIELD(val, size); - return PyLong_FromLongLong(val); + PY_LONG_LONG val; + memcpy(&val, ptr, sizeof(val)); + val = SWAP_8(val); + GET_BITFIELD(val, size); + return PyLong_FromLongLong(val); } static PyObject * Q_set(void *ptr, PyObject *value, Py_ssize_t size) { - unsigned PY_LONG_LONG val; - unsigned PY_LONG_LONG x; - if (get_ulonglong(value, &val) < 0) - return NULL; - memcpy(&x, ptr, sizeof(x)); - x = SET(x, val, size); - memcpy(ptr, &x, sizeof(x)); - _RET(value); + unsigned PY_LONG_LONG val; + unsigned PY_LONG_LONG x; + if (get_ulonglong(value, &val) < 0) + return NULL; + memcpy(&x, ptr, sizeof(x)); + x = SET(x, val, size); + memcpy(ptr, &x, sizeof(x)); + _RET(value); } static PyObject * Q_set_sw(void *ptr, PyObject *value, Py_ssize_t size) { - unsigned PY_LONG_LONG val; - unsigned PY_LONG_LONG field; - if (get_ulonglong(value, &val) < 0) - return NULL; - memcpy(&field, ptr, sizeof(field)); - field = SWAP_8(field); - field = (unsigned PY_LONG_LONG)SET(field, val, size); - field = SWAP_8(field); - memcpy(ptr, &field, sizeof(field)); - _RET(value); + unsigned PY_LONG_LONG val; + unsigned PY_LONG_LONG field; + if (get_ulonglong(value, &val) < 0) + return NULL; + memcpy(&field, ptr, sizeof(field)); + field = SWAP_8(field); + field = (unsigned PY_LONG_LONG)SET(field, val, size); + field = SWAP_8(field); + memcpy(ptr, &field, sizeof(field)); + _RET(value); } static PyObject * Q_get(void *ptr, Py_ssize_t size) { - unsigned PY_LONG_LONG val; - memcpy(&val, ptr, sizeof(val)); - GET_BITFIELD(val, size); - return PyLong_FromUnsignedLongLong(val); + unsigned PY_LONG_LONG val; + memcpy(&val, ptr, sizeof(val)); + GET_BITFIELD(val, size); + return PyLong_FromUnsignedLongLong(val); } static PyObject * Q_get_sw(void *ptr, Py_ssize_t size) { - unsigned PY_LONG_LONG val; - memcpy(&val, ptr, sizeof(val)); - val = SWAP_8(val); - GET_BITFIELD(val, size); - return PyLong_FromUnsignedLongLong(val); + unsigned PY_LONG_LONG val; + memcpy(&val, ptr, sizeof(val)); + val = SWAP_8(val); + GET_BITFIELD(val, size); + return PyLong_FromUnsignedLongLong(val); } #endif @@ -997,136 +997,136 @@ static PyObject * g_set(void *ptr, PyObject *value, Py_ssize_t size) { - long double x; + long double x; - x = PyFloat_AsDouble(value); - if (x == -1 && PyErr_Occurred()) { - PyErr_Format(PyExc_TypeError, - " float expected instead of %s instance", - value->ob_type->tp_name); - return NULL; - } - memcpy(ptr, &x, sizeof(long double)); - _RET(value); + x = PyFloat_AsDouble(value); + if (x == -1 && PyErr_Occurred()) { + PyErr_Format(PyExc_TypeError, + " float expected instead of %s instance", + value->ob_type->tp_name); + return NULL; + } + memcpy(ptr, &x, sizeof(long double)); + _RET(value); } static PyObject * g_get(void *ptr, Py_ssize_t size) { - long double val; - memcpy(&val, ptr, sizeof(long double)); - return PyFloat_FromDouble(val); + long double val; + memcpy(&val, ptr, sizeof(long double)); + return PyFloat_FromDouble(val); } static PyObject * d_set(void *ptr, PyObject *value, Py_ssize_t size) { - double x; + double x; - x = PyFloat_AsDouble(value); - if (x == -1 && PyErr_Occurred()) { - PyErr_Format(PyExc_TypeError, - " float expected instead of %s instance", - value->ob_type->tp_name); - return NULL; - } - memcpy(ptr, &x, sizeof(double)); - _RET(value); + x = PyFloat_AsDouble(value); + if (x == -1 && PyErr_Occurred()) { + PyErr_Format(PyExc_TypeError, + " float expected instead of %s instance", + value->ob_type->tp_name); + return NULL; + } + memcpy(ptr, &x, sizeof(double)); + _RET(value); } static PyObject * d_get(void *ptr, Py_ssize_t size) { - double val; - memcpy(&val, ptr, sizeof(val)); - return PyFloat_FromDouble(val); + double val; + memcpy(&val, ptr, sizeof(val)); + return PyFloat_FromDouble(val); } static PyObject * d_set_sw(void *ptr, PyObject *value, Py_ssize_t size) { - double x; + double x; - x = PyFloat_AsDouble(value); - if (x == -1 && PyErr_Occurred()) { - PyErr_Format(PyExc_TypeError, - " float expected instead of %s instance", - value->ob_type->tp_name); - return NULL; - } + x = PyFloat_AsDouble(value); + if (x == -1 && PyErr_Occurred()) { + PyErr_Format(PyExc_TypeError, + " float expected instead of %s instance", + value->ob_type->tp_name); + return NULL; + } #ifdef WORDS_BIGENDIAN - if (_PyFloat_Pack8(x, (unsigned char *)ptr, 1)) - return NULL; + if (_PyFloat_Pack8(x, (unsigned char *)ptr, 1)) + return NULL; #else - if (_PyFloat_Pack8(x, (unsigned char *)ptr, 0)) - return NULL; + if (_PyFloat_Pack8(x, (unsigned char *)ptr, 0)) + return NULL; #endif - _RET(value); + _RET(value); } static PyObject * d_get_sw(void *ptr, Py_ssize_t size) { #ifdef WORDS_BIGENDIAN - return PyFloat_FromDouble(_PyFloat_Unpack8(ptr, 1)); + return PyFloat_FromDouble(_PyFloat_Unpack8(ptr, 1)); #else - return PyFloat_FromDouble(_PyFloat_Unpack8(ptr, 0)); + return PyFloat_FromDouble(_PyFloat_Unpack8(ptr, 0)); #endif } static PyObject * f_set(void *ptr, PyObject *value, Py_ssize_t size) { - float x; + float x; - x = (float)PyFloat_AsDouble(value); - if (x == -1 && PyErr_Occurred()) { - PyErr_Format(PyExc_TypeError, - " float expected instead of %s instance", - value->ob_type->tp_name); - return NULL; - } - memcpy(ptr, &x, sizeof(x)); - _RET(value); + x = (float)PyFloat_AsDouble(value); + if (x == -1 && PyErr_Occurred()) { + PyErr_Format(PyExc_TypeError, + " float expected instead of %s instance", + value->ob_type->tp_name); + return NULL; + } + memcpy(ptr, &x, sizeof(x)); + _RET(value); } static PyObject * f_get(void *ptr, Py_ssize_t size) { - float val; - memcpy(&val, ptr, sizeof(val)); - return PyFloat_FromDouble(val); + float val; + memcpy(&val, ptr, sizeof(val)); + return PyFloat_FromDouble(val); } static PyObject * f_set_sw(void *ptr, PyObject *value, Py_ssize_t size) { - float x; + float x; - x = (float)PyFloat_AsDouble(value); - if (x == -1 && PyErr_Occurred()) { - PyErr_Format(PyExc_TypeError, - " float expected instead of %s instance", - value->ob_type->tp_name); - return NULL; - } + x = (float)PyFloat_AsDouble(value); + if (x == -1 && PyErr_Occurred()) { + PyErr_Format(PyExc_TypeError, + " float expected instead of %s instance", + value->ob_type->tp_name); + return NULL; + } #ifdef WORDS_BIGENDIAN - if (_PyFloat_Pack4(x, (unsigned char *)ptr, 1)) - return NULL; + if (_PyFloat_Pack4(x, (unsigned char *)ptr, 1)) + return NULL; #else - if (_PyFloat_Pack4(x, (unsigned char *)ptr, 0)) - return NULL; + if (_PyFloat_Pack4(x, (unsigned char *)ptr, 0)) + return NULL; #endif - _RET(value); + _RET(value); } static PyObject * f_get_sw(void *ptr, Py_ssize_t size) { #ifdef WORDS_BIGENDIAN - return PyFloat_FromDouble(_PyFloat_Unpack4(ptr, 1)); + return PyFloat_FromDouble(_PyFloat_Unpack4(ptr, 1)); #else - return PyFloat_FromDouble(_PyFloat_Unpack4(ptr, 0)); + return PyFloat_FromDouble(_PyFloat_Unpack4(ptr, 0)); #endif } @@ -1143,72 +1143,72 @@ static PyObject * O_get(void *ptr, Py_ssize_t size) { - PyObject *ob = *(PyObject **)ptr; - if (ob == NULL) { - if (!PyErr_Occurred()) - /* Set an error if not yet set */ - PyErr_SetString(PyExc_ValueError, - "PyObject is NULL"); - return NULL; - } - Py_INCREF(ob); - return ob; + PyObject *ob = *(PyObject **)ptr; + if (ob == NULL) { + if (!PyErr_Occurred()) + /* Set an error if not yet set */ + PyErr_SetString(PyExc_ValueError, + "PyObject is NULL"); + return NULL; + } + Py_INCREF(ob); + return ob; } static PyObject * O_set(void *ptr, PyObject *value, Py_ssize_t size) { - /* Hm, does the memory block need it's own refcount or not? */ - *(PyObject **)ptr = value; - Py_INCREF(value); - return value; + /* Hm, does the memory block need it's own refcount or not? */ + *(PyObject **)ptr = value; + Py_INCREF(value); + return value; } static PyObject * c_set(void *ptr, PyObject *value, Py_ssize_t size) { - if (PyUnicode_Check(value)) { - value = PyUnicode_AsEncodedString(value, - _ctypes_conversion_encoding, - _ctypes_conversion_errors); - if (value == NULL) - return NULL; - if (PyBytes_GET_SIZE(value) != 1) { - Py_DECREF(value); - goto error; - } - *(char *)ptr = PyBytes_AS_STRING(value)[0]; - Py_DECREF(value); - _RET(value); - } - if (PyBytes_Check(value) && PyBytes_GET_SIZE(value) == 1) { - *(char *)ptr = PyBytes_AS_STRING(value)[0]; - _RET(value); - } - if (PyByteArray_Check(value) && PyByteArray_GET_SIZE(value) == 1) { - *(char *)ptr = PyByteArray_AS_STRING(value)[0]; - _RET(value); - } - if (PyLong_Check(value)) - { - long longval = PyLong_AS_LONG(value); - if (longval < 0 || longval >= 256) - goto error; - *(char *)ptr = (char)longval; - _RET(value); - } + if (PyUnicode_Check(value)) { + value = PyUnicode_AsEncodedString(value, + _ctypes_conversion_encoding, + _ctypes_conversion_errors); + if (value == NULL) + return NULL; + if (PyBytes_GET_SIZE(value) != 1) { + Py_DECREF(value); + goto error; + } + *(char *)ptr = PyBytes_AS_STRING(value)[0]; + Py_DECREF(value); + _RET(value); + } + if (PyBytes_Check(value) && PyBytes_GET_SIZE(value) == 1) { + *(char *)ptr = PyBytes_AS_STRING(value)[0]; + _RET(value); + } + if (PyByteArray_Check(value) && PyByteArray_GET_SIZE(value) == 1) { + *(char *)ptr = PyByteArray_AS_STRING(value)[0]; + _RET(value); + } + if (PyLong_Check(value)) + { + long longval = PyLong_AS_LONG(value); + if (longval < 0 || longval >= 256) + goto error; + *(char *)ptr = (char)longval; + _RET(value); + } error: - PyErr_Format(PyExc_TypeError, - "one character string expected"); - return NULL; + PyErr_Format(PyExc_TypeError, + "one character string expected"); + return NULL; } static PyObject * c_get(void *ptr, Py_ssize_t size) { - return PyBytes_FromStringAndSize((char *)ptr, 1); + return PyBytes_FromStringAndSize((char *)ptr, 1); } #ifdef CTYPES_UNICODE @@ -1216,107 +1216,107 @@ static PyObject * u_set(void *ptr, PyObject *value, Py_ssize_t size) { - Py_ssize_t len; - if (PyBytes_Check(value)) { - value = PyUnicode_FromEncodedObject(value, - _ctypes_conversion_encoding, - _ctypes_conversion_errors); - if (!value) - return NULL; - } else if (!PyUnicode_Check(value)) { - PyErr_Format(PyExc_TypeError, - "unicode string expected instead of %s instance", - value->ob_type->tp_name); - return NULL; - } else - Py_INCREF(value); - - len = PyUnicode_GET_SIZE(value); - if (len != 1) { - Py_DECREF(value); - PyErr_SetString(PyExc_TypeError, - "one character unicode string expected"); - return NULL; - } + Py_ssize_t len; + if (PyBytes_Check(value)) { + value = PyUnicode_FromEncodedObject(value, + _ctypes_conversion_encoding, + _ctypes_conversion_errors); + if (!value) + return NULL; + } else if (!PyUnicode_Check(value)) { + PyErr_Format(PyExc_TypeError, + "unicode string expected instead of %s instance", + value->ob_type->tp_name); + return NULL; + } else + Py_INCREF(value); + + len = PyUnicode_GET_SIZE(value); + if (len != 1) { + Py_DECREF(value); + PyErr_SetString(PyExc_TypeError, + "one character unicode string expected"); + return NULL; + } - *(wchar_t *)ptr = PyUnicode_AS_UNICODE(value)[0]; - Py_DECREF(value); + *(wchar_t *)ptr = PyUnicode_AS_UNICODE(value)[0]; + Py_DECREF(value); - _RET(value); + _RET(value); } static PyObject * u_get(void *ptr, Py_ssize_t size) { - return PyUnicode_FromWideChar((wchar_t *)ptr, 1); + return PyUnicode_FromWideChar((wchar_t *)ptr, 1); } /* U - a unicode string */ static PyObject * U_get(void *ptr, Py_ssize_t size) { - PyObject *result; - Py_ssize_t len; - Py_UNICODE *p; - - size /= sizeof(wchar_t); /* we count character units here, not bytes */ - - result = PyUnicode_FromWideChar((wchar_t *)ptr, size); - if (!result) - return NULL; - /* We need 'result' to be able to count the characters with wcslen, - since ptr may not be NUL terminated. If the length is smaller (if - it was actually NUL terminated, we construct a new one and throw - away the result. - */ - /* chop off at the first NUL character, if any. */ - p = PyUnicode_AS_UNICODE(result); - for (len = 0; len < size; ++len) - if (!p[len]) - break; - - if (len < size) { - PyObject *ob = PyUnicode_FromWideChar((wchar_t *)ptr, len); - Py_DECREF(result); - return ob; - } - return result; + PyObject *result; + Py_ssize_t len; + Py_UNICODE *p; + + size /= sizeof(wchar_t); /* we count character units here, not bytes */ + + result = PyUnicode_FromWideChar((wchar_t *)ptr, size); + if (!result) + return NULL; + /* We need 'result' to be able to count the characters with wcslen, + since ptr may not be NUL terminated. If the length is smaller (if + it was actually NUL terminated, we construct a new one and throw + away the result. + */ + /* chop off at the first NUL character, if any. */ + p = PyUnicode_AS_UNICODE(result); + for (len = 0; len < size; ++len) + if (!p[len]) + break; + + if (len < size) { + PyObject *ob = PyUnicode_FromWideChar((wchar_t *)ptr, len); + Py_DECREF(result); + return ob; + } + return result; } static PyObject * U_set(void *ptr, PyObject *value, Py_ssize_t length) { - Py_ssize_t size; + Py_ssize_t size; - /* It's easier to calculate in characters than in bytes */ - length /= sizeof(wchar_t); + /* It's easier to calculate in characters than in bytes */ + length /= sizeof(wchar_t); - if (PyBytes_Check(value)) { - value = PyUnicode_FromEncodedObject(value, - _ctypes_conversion_encoding, - _ctypes_conversion_errors); - if (!value) - return NULL; - } else if (!PyUnicode_Check(value)) { - PyErr_Format(PyExc_TypeError, - "unicode string expected instead of %s instance", - value->ob_type->tp_name); - return NULL; - } else - Py_INCREF(value); - size = PyUnicode_GET_SIZE(value); - if (size > length) { - PyErr_Format(PyExc_ValueError, - "string too long (%zd, maximum length %zd)", - size, length); - Py_DECREF(value); - return NULL; - } else if (size < length-1) - /* copy terminating NUL character if there is space */ - size += 1; - PyUnicode_AsWideChar((PyUnicodeObject *)value, (wchar_t *)ptr, size); - return value; + if (PyBytes_Check(value)) { + value = PyUnicode_FromEncodedObject(value, + _ctypes_conversion_encoding, + _ctypes_conversion_errors); + if (!value) + return NULL; + } else if (!PyUnicode_Check(value)) { + PyErr_Format(PyExc_TypeError, + "unicode string expected instead of %s instance", + value->ob_type->tp_name); + return NULL; + } else + Py_INCREF(value); + size = PyUnicode_GET_SIZE(value); + if (size > length) { + PyErr_Format(PyExc_ValueError, + "string too long (%zd, maximum length %zd)", + size, length); + Py_DECREF(value); + return NULL; + } else if (size < length-1) + /* copy terminating NUL character if there is space */ + size += 1; + PyUnicode_AsWideChar((PyUnicodeObject *)value, (wchar_t *)ptr, size); + return value; } #endif @@ -1324,210 +1324,210 @@ static PyObject * s_get(void *ptr, Py_ssize_t size) { - Py_ssize_t i; - char *p; + Py_ssize_t i; + char *p; - p = (char *)ptr; - for (i = 0; i < size; ++i) { - if (*p++ == '\0') - break; - } + p = (char *)ptr; + for (i = 0; i < size; ++i) { + if (*p++ == '\0') + break; + } - return PyUnicode_FromStringAndSize((char *)ptr, (Py_ssize_t)i); + return PyUnicode_FromStringAndSize((char *)ptr, (Py_ssize_t)i); } static PyObject * s_set(void *ptr, PyObject *value, Py_ssize_t length) { - char *data; - Py_ssize_t size; + char *data; + Py_ssize_t size; - if (PyUnicode_Check(value)) { - value = PyUnicode_AsEncodedString(value, - _ctypes_conversion_encoding, - _ctypes_conversion_errors); - if (value == NULL) - return NULL; - assert(PyBytes_Check(value)); - } else if(PyBytes_Check(value)) { - Py_INCREF(value); - } else { - PyErr_Format(PyExc_TypeError, - "expected string, %s found", - value->ob_type->tp_name); - return NULL; - } - - data = PyBytes_AS_STRING(value); - if (!data) - return NULL; - size = strlen(data); /* XXX Why not Py_SIZE(value)? */ - if (size < length) { - /* This will copy the leading NUL character - * if there is space for it. - */ - ++size; - } else if (size > length) { - PyErr_Format(PyExc_ValueError, - "string too long (%zd, maximum length %zd)", - size, length); - Py_DECREF(value); - return NULL; - } - /* Also copy the terminating NUL character if there is space */ - memcpy((char *)ptr, data, size); + if (PyUnicode_Check(value)) { + value = PyUnicode_AsEncodedString(value, + _ctypes_conversion_encoding, + _ctypes_conversion_errors); + if (value == NULL) + return NULL; + assert(PyBytes_Check(value)); + } else if(PyBytes_Check(value)) { + Py_INCREF(value); + } else { + PyErr_Format(PyExc_TypeError, + "expected string, %s found", + value->ob_type->tp_name); + return NULL; + } + + data = PyBytes_AS_STRING(value); + if (!data) + return NULL; + size = strlen(data); /* XXX Why not Py_SIZE(value)? */ + if (size < length) { + /* This will copy the leading NUL character + * if there is space for it. + */ + ++size; + } else if (size > length) { + PyErr_Format(PyExc_ValueError, + "string too long (%zd, maximum length %zd)", + size, length); + Py_DECREF(value); + return NULL; + } + /* Also copy the terminating NUL character if there is space */ + memcpy((char *)ptr, data, size); - Py_DECREF(value); - _RET(value); + Py_DECREF(value); + _RET(value); } static PyObject * z_set(void *ptr, PyObject *value, Py_ssize_t size) { - if (value == Py_None) { - *(char **)ptr = NULL; - Py_INCREF(value); - return value; - } - if (PyBytes_Check(value)) { - *(char **)ptr = PyBytes_AsString(value); - Py_INCREF(value); - return value; - } else if (PyUnicode_Check(value)) { - PyObject *str = PyUnicode_AsEncodedString(value, - _ctypes_conversion_encoding, - _ctypes_conversion_errors); - if (str == NULL) - return NULL; - *(char **)ptr = PyBytes_AS_STRING(str); - return str; - } else if (PyLong_Check(value)) { + if (value == Py_None) { + *(char **)ptr = NULL; + Py_INCREF(value); + return value; + } + if (PyBytes_Check(value)) { + *(char **)ptr = PyBytes_AsString(value); + Py_INCREF(value); + return value; + } else if (PyUnicode_Check(value)) { + PyObject *str = PyUnicode_AsEncodedString(value, + _ctypes_conversion_encoding, + _ctypes_conversion_errors); + if (str == NULL) + return NULL; + *(char **)ptr = PyBytes_AS_STRING(str); + return str; + } else if (PyLong_Check(value)) { #if SIZEOF_VOID_P == SIZEOF_LONG_LONG - *(char **)ptr = (char *)PyLong_AsUnsignedLongLongMask(value); + *(char **)ptr = (char *)PyLong_AsUnsignedLongLongMask(value); #else - *(char **)ptr = (char *)PyLong_AsUnsignedLongMask(value); + *(char **)ptr = (char *)PyLong_AsUnsignedLongMask(value); #endif - _RET(value); - } - PyErr_Format(PyExc_TypeError, - "string or integer address expected instead of %s instance", - value->ob_type->tp_name); - return NULL; + _RET(value); + } + PyErr_Format(PyExc_TypeError, + "string or integer address expected instead of %s instance", + value->ob_type->tp_name); + return NULL; } static PyObject * z_get(void *ptr, Py_ssize_t size) { - /* XXX What about invalid pointers ??? */ - if (*(void **)ptr) { + /* XXX What about invalid pointers ??? */ + if (*(void **)ptr) { #if defined(MS_WIN32) && !defined(_WIN32_WCE) - if (IsBadStringPtrA(*(char **)ptr, -1)) { - PyErr_Format(PyExc_ValueError, - "invalid string pointer %p", - *(char **)ptr); - return NULL; - } -#endif - return PyBytes_FromStringAndSize(*(char **)ptr, - strlen(*(char **)ptr)); - } else { - Py_INCREF(Py_None); - return Py_None; - } + if (IsBadStringPtrA(*(char **)ptr, -1)) { + PyErr_Format(PyExc_ValueError, + "invalid string pointer %p", + *(char **)ptr); + return NULL; + } +#endif + return PyBytes_FromStringAndSize(*(char **)ptr, + strlen(*(char **)ptr)); + } else { + Py_INCREF(Py_None); + return Py_None; + } } #ifdef CTYPES_UNICODE static PyObject * Z_set(void *ptr, PyObject *value, Py_ssize_t size) { - if (value == Py_None) { - *(wchar_t **)ptr = NULL; - Py_INCREF(value); - return value; - } - if (PyLong_Check(value) || PyLong_Check(value)) { + if (value == Py_None) { + *(wchar_t **)ptr = NULL; + Py_INCREF(value); + return value; + } + if (PyLong_Check(value) || PyLong_Check(value)) { #if SIZEOF_VOID_P == SIZEOF_LONG_LONG - *(wchar_t **)ptr = (wchar_t *)PyLong_AsUnsignedLongLongMask(value); + *(wchar_t **)ptr = (wchar_t *)PyLong_AsUnsignedLongLongMask(value); #else - *(wchar_t **)ptr = (wchar_t *)PyLong_AsUnsignedLongMask(value); + *(wchar_t **)ptr = (wchar_t *)PyLong_AsUnsignedLongMask(value); #endif - Py_INCREF(Py_None); - return Py_None; - } - if (PyBytes_Check(value)) { - value = PyUnicode_FromEncodedObject(value, - _ctypes_conversion_encoding, - _ctypes_conversion_errors); - if (!value) - return NULL; - } else if (!PyUnicode_Check(value)) { - PyErr_Format(PyExc_TypeError, - "unicode string or integer address expected instead of %s instance", - value->ob_type->tp_name); - return NULL; - } else - Py_INCREF(value); + Py_INCREF(Py_None); + return Py_None; + } + if (PyBytes_Check(value)) { + value = PyUnicode_FromEncodedObject(value, + _ctypes_conversion_encoding, + _ctypes_conversion_errors); + if (!value) + return NULL; + } else if (!PyUnicode_Check(value)) { + PyErr_Format(PyExc_TypeError, + "unicode string or integer address expected instead of %s instance", + value->ob_type->tp_name); + return NULL; + } else + Py_INCREF(value); #ifdef HAVE_USABLE_WCHAR_T - /* HAVE_USABLE_WCHAR_T means that Py_UNICODE and wchar_t is the same - type. So we can copy directly. Hm, are unicode objects always NUL - terminated in Python, internally? - */ - *(wchar_t **)ptr = PyUnicode_AS_UNICODE(value); - return value; + /* HAVE_USABLE_WCHAR_T means that Py_UNICODE and wchar_t is the same + type. So we can copy directly. Hm, are unicode objects always NUL + terminated in Python, internally? + */ + *(wchar_t **)ptr = PyUnicode_AS_UNICODE(value); + return value; #else - { - /* We must create a wchar_t* buffer from the unicode object, - and keep it alive */ - PyObject *keep; - wchar_t *buffer; - - int size = PyUnicode_GET_SIZE(value); - size += 1; /* terminating NUL */ - size *= sizeof(wchar_t); - buffer = (wchar_t *)PyMem_Malloc(size); - if (!buffer) { - Py_DECREF(value); - return PyErr_NoMemory(); - } - memset(buffer, 0, size); - keep = PyCapsule_New(buffer, CTYPES_CFIELD_CAPSULE_NAME_PYMEM, pymem_destructor); - if (!keep) { - Py_DECREF(value); - PyMem_Free(buffer); - return NULL; - } - *(wchar_t **)ptr = (wchar_t *)buffer; - if (-1 == PyUnicode_AsWideChar((PyUnicodeObject *)value, - buffer, PyUnicode_GET_SIZE(value))) { - Py_DECREF(value); - Py_DECREF(keep); - return NULL; - } - Py_DECREF(value); - return keep; - } + { + /* We must create a wchar_t* buffer from the unicode object, + and keep it alive */ + PyObject *keep; + wchar_t *buffer; + + int size = PyUnicode_GET_SIZE(value); + size += 1; /* terminating NUL */ + size *= sizeof(wchar_t); + buffer = (wchar_t *)PyMem_Malloc(size); + if (!buffer) { + Py_DECREF(value); + return PyErr_NoMemory(); + } + memset(buffer, 0, size); + keep = PyCapsule_New(buffer, CTYPES_CFIELD_CAPSULE_NAME_PYMEM, pymem_destructor); + if (!keep) { + Py_DECREF(value); + PyMem_Free(buffer); + return NULL; + } + *(wchar_t **)ptr = (wchar_t *)buffer; + if (-1 == PyUnicode_AsWideChar((PyUnicodeObject *)value, + buffer, PyUnicode_GET_SIZE(value))) { + Py_DECREF(value); + Py_DECREF(keep); + return NULL; + } + Py_DECREF(value); + return keep; + } #endif } static PyObject * Z_get(void *ptr, Py_ssize_t size) { - wchar_t *p; - p = *(wchar_t **)ptr; - if (p) { + wchar_t *p; + p = *(wchar_t **)ptr; + if (p) { #if defined(MS_WIN32) && !defined(_WIN32_WCE) - if (IsBadStringPtrW(*(wchar_t **)ptr, -1)) { - PyErr_Format(PyExc_ValueError, - "invalid string pointer %p", - *(wchar_t **)ptr); - return NULL; - } -#endif - return PyUnicode_FromWideChar(p, wcslen(p)); - } else { - Py_INCREF(Py_None); - return Py_None; - } + if (IsBadStringPtrW(*(wchar_t **)ptr, -1)) { + PyErr_Format(PyExc_ValueError, + "invalid string pointer %p", + *(wchar_t **)ptr); + return NULL; + } +#endif + return PyUnicode_FromWideChar(p, wcslen(p)); + } else { + Py_INCREF(Py_None); + return Py_None; + } } #endif @@ -1535,166 +1535,166 @@ static PyObject * BSTR_set(void *ptr, PyObject *value, Py_ssize_t size) { - BSTR bstr; + BSTR bstr; + + /* convert value into a PyUnicodeObject or NULL */ + if (Py_None == value) { + value = NULL; + } else if (PyBytes_Check(value)) { + value = PyUnicode_FromEncodedObject(value, + _ctypes_conversion_encoding, + _ctypes_conversion_errors); + if (!value) + return NULL; + } else if (PyUnicode_Check(value)) { + Py_INCREF(value); /* for the descref below */ + } else { + PyErr_Format(PyExc_TypeError, + "unicode string expected instead of %s instance", + value->ob_type->tp_name); + return NULL; + } + + /* create a BSTR from value */ + if (value) { + Py_ssize_t size = PyUnicode_GET_SIZE(value); + if ((unsigned) size != size) { + PyErr_SetString(PyExc_ValueError, "String too long for BSTR"); + return NULL; + } + bstr = SysAllocStringLen(PyUnicode_AS_UNICODE(value), + (unsigned)size); + Py_DECREF(value); + } else + bstr = NULL; + + /* free the previous contents, if any */ + if (*(BSTR *)ptr) + SysFreeString(*(BSTR *)ptr); - /* convert value into a PyUnicodeObject or NULL */ - if (Py_None == value) { - value = NULL; - } else if (PyBytes_Check(value)) { - value = PyUnicode_FromEncodedObject(value, - _ctypes_conversion_encoding, - _ctypes_conversion_errors); - if (!value) - return NULL; - } else if (PyUnicode_Check(value)) { - Py_INCREF(value); /* for the descref below */ - } else { - PyErr_Format(PyExc_TypeError, - "unicode string expected instead of %s instance", - value->ob_type->tp_name); - return NULL; - } - - /* create a BSTR from value */ - if (value) { - Py_ssize_t size = PyUnicode_GET_SIZE(value); - if ((unsigned) size != size) { - PyErr_SetString(PyExc_ValueError, "String too long for BSTR"); - return NULL; - } - bstr = SysAllocStringLen(PyUnicode_AS_UNICODE(value), - (unsigned)size); - Py_DECREF(value); - } else - bstr = NULL; - - /* free the previous contents, if any */ - if (*(BSTR *)ptr) - SysFreeString(*(BSTR *)ptr); - - /* and store it */ - *(BSTR *)ptr = bstr; + /* and store it */ + *(BSTR *)ptr = bstr; - /* We don't need to keep any other object */ - _RET(value); + /* We don't need to keep any other object */ + _RET(value); } static PyObject * BSTR_get(void *ptr, Py_ssize_t size) { - BSTR p; - p = *(BSTR *)ptr; - if (p) - return PyUnicode_FromWideChar(p, SysStringLen(p)); - else { - /* Hm, it seems NULL pointer and zero length string are the - same in BSTR, see Don Box, p 81 - */ - Py_INCREF(Py_None); - return Py_None; - } + BSTR p; + p = *(BSTR *)ptr; + if (p) + return PyUnicode_FromWideChar(p, SysStringLen(p)); + else { + /* Hm, it seems NULL pointer and zero length string are the + same in BSTR, see Don Box, p 81 + */ + Py_INCREF(Py_None); + return Py_None; + } } #endif static PyObject * P_set(void *ptr, PyObject *value, Py_ssize_t size) { - void *v; - if (value == Py_None) { - *(void **)ptr = NULL; - _RET(value); - } - - if (!PyLong_Check(value) && !PyLong_Check(value)) { - PyErr_SetString(PyExc_TypeError, - "cannot be converted to pointer"); - return NULL; - } + void *v; + if (value == Py_None) { + *(void **)ptr = NULL; + _RET(value); + } + + if (!PyLong_Check(value) && !PyLong_Check(value)) { + PyErr_SetString(PyExc_TypeError, + "cannot be converted to pointer"); + return NULL; + } #if SIZEOF_VOID_P <= SIZEOF_LONG - v = (void *)PyLong_AsUnsignedLongMask(value); + v = (void *)PyLong_AsUnsignedLongMask(value); #else #ifndef HAVE_LONG_LONG # error "PyLong_AsVoidPtr: sizeof(void*) > sizeof(long), but no long long" #elif SIZEOF_LONG_LONG < SIZEOF_VOID_P # error "PyLong_AsVoidPtr: sizeof(PY_LONG_LONG) < sizeof(void*)" #endif - v = (void *)PyLong_AsUnsignedLongLongMask(value); + v = (void *)PyLong_AsUnsignedLongLongMask(value); #endif - if (PyErr_Occurred()) - return NULL; + if (PyErr_Occurred()) + return NULL; - *(void **)ptr = v; - _RET(value); + *(void **)ptr = v; + _RET(value); } static PyObject * P_get(void *ptr, Py_ssize_t size) { - if (*(void **)ptr == NULL) { - Py_INCREF(Py_None); - return Py_None; - } - return PyLong_FromVoidPtr(*(void **)ptr); + if (*(void **)ptr == NULL) { + Py_INCREF(Py_None); + return Py_None; + } + return PyLong_FromVoidPtr(*(void **)ptr); } static struct fielddesc formattable[] = { - { 's', s_set, s_get, &ffi_type_pointer}, - { 'b', b_set, b_get, &ffi_type_schar}, - { 'B', B_set, B_get, &ffi_type_uchar}, - { 'c', c_set, c_get, &ffi_type_schar}, - { 'd', d_set, d_get, &ffi_type_double, d_set_sw, d_get_sw}, - { 'g', g_set, g_get, &ffi_type_longdouble}, - { 'f', f_set, f_get, &ffi_type_float, f_set_sw, f_get_sw}, - { 'h', h_set, h_get, &ffi_type_sshort, h_set_sw, h_get_sw}, - { 'H', H_set, H_get, &ffi_type_ushort, H_set_sw, H_get_sw}, - { 'i', i_set, i_get, &ffi_type_sint, i_set_sw, i_get_sw}, - { 'I', I_set, I_get, &ffi_type_uint, I_set_sw, I_get_sw}, + { 's', s_set, s_get, &ffi_type_pointer}, + { 'b', b_set, b_get, &ffi_type_schar}, + { 'B', B_set, B_get, &ffi_type_uchar}, + { 'c', c_set, c_get, &ffi_type_schar}, + { 'd', d_set, d_get, &ffi_type_double, d_set_sw, d_get_sw}, + { 'g', g_set, g_get, &ffi_type_longdouble}, + { 'f', f_set, f_get, &ffi_type_float, f_set_sw, f_get_sw}, + { 'h', h_set, h_get, &ffi_type_sshort, h_set_sw, h_get_sw}, + { 'H', H_set, H_get, &ffi_type_ushort, H_set_sw, H_get_sw}, + { 'i', i_set, i_get, &ffi_type_sint, i_set_sw, i_get_sw}, + { 'I', I_set, I_get, &ffi_type_uint, I_set_sw, I_get_sw}, /* XXX Hm, sizeof(int) == sizeof(long) doesn't hold on every platform */ /* As soon as we can get rid of the type codes, this is no longer a problem */ #if SIZEOF_LONG == 4 - { 'l', l_set, l_get, &ffi_type_sint32, l_set_sw, l_get_sw}, - { 'L', L_set, L_get, &ffi_type_uint32, L_set_sw, L_get_sw}, + { 'l', l_set, l_get, &ffi_type_sint32, l_set_sw, l_get_sw}, + { 'L', L_set, L_get, &ffi_type_uint32, L_set_sw, L_get_sw}, #elif SIZEOF_LONG == 8 - { 'l', l_set, l_get, &ffi_type_sint64, l_set_sw, l_get_sw}, - { 'L', L_set, L_get, &ffi_type_uint64, L_set_sw, L_get_sw}, + { 'l', l_set, l_get, &ffi_type_sint64, l_set_sw, l_get_sw}, + { 'L', L_set, L_get, &ffi_type_uint64, L_set_sw, L_get_sw}, #else # error #endif #ifdef HAVE_LONG_LONG #if SIZEOF_LONG_LONG == 8 - { 'q', q_set, q_get, &ffi_type_sint64, q_set_sw, q_get_sw}, - { 'Q', Q_set, Q_get, &ffi_type_uint64, Q_set_sw, Q_get_sw}, + { 'q', q_set, q_get, &ffi_type_sint64, q_set_sw, q_get_sw}, + { 'Q', Q_set, Q_get, &ffi_type_uint64, Q_set_sw, Q_get_sw}, #else # error #endif #endif - { 'P', P_set, P_get, &ffi_type_pointer}, - { 'z', z_set, z_get, &ffi_type_pointer}, + { 'P', P_set, P_get, &ffi_type_pointer}, + { 'z', z_set, z_get, &ffi_type_pointer}, #ifdef CTYPES_UNICODE - { 'u', u_set, u_get, NULL}, /* ffi_type set later */ - { 'U', U_set, U_get, &ffi_type_pointer}, - { 'Z', Z_set, Z_get, &ffi_type_pointer}, + { 'u', u_set, u_get, NULL}, /* ffi_type set later */ + { 'U', U_set, U_get, &ffi_type_pointer}, + { 'Z', Z_set, Z_get, &ffi_type_pointer}, #endif #ifdef MS_WIN32 - { 'X', BSTR_set, BSTR_get, &ffi_type_pointer}, - { 'v', vBOOL_set, vBOOL_get, &ffi_type_sshort}, + { 'X', BSTR_set, BSTR_get, &ffi_type_pointer}, + { 'v', vBOOL_set, vBOOL_get, &ffi_type_sshort}, #endif #if SIZEOF__BOOL == 1 - { '?', bool_set, bool_get, &ffi_type_uchar}, /* Also fallback for no native _Bool support */ + { '?', bool_set, bool_get, &ffi_type_uchar}, /* Also fallback for no native _Bool support */ #elif SIZEOF__BOOL == SIZEOF_SHORT - { '?', bool_set, bool_get, &ffi_type_ushort}, + { '?', bool_set, bool_get, &ffi_type_ushort}, #elif SIZEOF__BOOL == SIZEOF_INT - { '?', bool_set, bool_get, &ffi_type_uint, I_set_sw, I_get_sw}, + { '?', bool_set, bool_get, &ffi_type_uint, I_set_sw, I_get_sw}, #elif SIZEOF__BOOL == SIZEOF_LONG - { '?', bool_set, bool_get, &ffi_type_ulong, L_set_sw, L_get_sw}, + { '?', bool_set, bool_get, &ffi_type_ulong, L_set_sw, L_get_sw}, #elif SIZEOF__BOOL == SIZEOF_LONG_LONG - { '?', bool_set, bool_get, &ffi_type_ulong, Q_set_sw, Q_get_sw}, + { '?', bool_set, bool_get, &ffi_type_ulong, Q_set_sw, Q_get_sw}, #endif /* SIZEOF__BOOL */ - { 'O', O_set, O_get, &ffi_type_pointer}, - { 0, NULL, NULL, NULL}, + { 'O', O_set, O_get, &ffi_type_pointer}, + { 0, NULL, NULL, NULL}, }; /* @@ -1705,26 +1705,26 @@ struct fielddesc * _ctypes_get_fielddesc(const char *fmt) { - static int initialized = 0; - struct fielddesc *table = formattable; + static int initialized = 0; + struct fielddesc *table = formattable; - if (!initialized) { - initialized = 1; + if (!initialized) { + initialized = 1; #ifdef CTYPES_UNICODE - if (sizeof(wchar_t) == sizeof(short)) - _ctypes_get_fielddesc("u")->pffi_type = &ffi_type_sshort; - else if (sizeof(wchar_t) == sizeof(int)) - _ctypes_get_fielddesc("u")->pffi_type = &ffi_type_sint; - else if (sizeof(wchar_t) == sizeof(long)) - _ctypes_get_fielddesc("u")->pffi_type = &ffi_type_slong; -#endif - } - - for (; table->code; ++table) { - if (table->code == fmt[0]) - return table; - } - return NULL; + if (sizeof(wchar_t) == sizeof(short)) + _ctypes_get_fielddesc("u")->pffi_type = &ffi_type_sshort; + else if (sizeof(wchar_t) == sizeof(int)) + _ctypes_get_fielddesc("u")->pffi_type = &ffi_type_sint; + else if (sizeof(wchar_t) == sizeof(long)) + _ctypes_get_fielddesc("u")->pffi_type = &ffi_type_slong; +#endif + } + + for (; table->code; ++table) { + if (table->code == fmt[0]) + return table; + } + return NULL; } typedef struct { char c; char x; } s_char; @@ -1768,10 +1768,10 @@ /* from ffi.h: typedef struct _ffi_type { - size_t size; - unsigned short alignment; - unsigned short type; - struct _ffi_type **elements; + size_t size; + unsigned short alignment; + unsigned short type; + struct _ffi_type **elements; } ffi_type; */ @@ -1798,7 +1798,7 @@ #endif /* This is already defined on OSX */ ffi_type ffi_type_longdouble = { sizeof(long double), LONGDOUBLE_ALIGN, - FFI_TYPE_LONGDOUBLE }; + FFI_TYPE_LONGDOUBLE }; ffi_type ffi_type_pointer = { sizeof(void *), VOID_P_ALIGN, FFI_TYPE_POINTER }; Modified: python/branches/py3k-jit/Modules/_ctypes/ctypes.h ============================================================================== --- python/branches/py3k-jit/Modules/_ctypes/ctypes.h (original) +++ python/branches/py3k-jit/Modules/_ctypes/ctypes.h Mon May 10 23:55:43 2010 @@ -21,16 +21,16 @@ difficult in the presence of PyCFuncPtrObject. Maybe later. */ union value { - char c[16]; - short s; - int i; - long l; - float f; - double d; + char c[16]; + short s; + int i; + long l; + float f; + double d; #ifdef HAVE_LONG_LONG - PY_LONG_LONG ll; + PY_LONG_LONG ll; #endif - long double D; + long double D; }; /* @@ -40,67 +40,67 @@ */ struct tagCDataObject { - PyObject_HEAD - char *b_ptr; /* pointer to memory block */ - int b_needsfree; /* need _we_ free the memory? */ - CDataObject *b_base; /* pointer to base object or NULL */ - Py_ssize_t b_size; /* size of memory block in bytes */ - Py_ssize_t b_length; /* number of references we need */ - Py_ssize_t b_index; /* index of this object into base's - b_object list */ - PyObject *b_objects; /* dictionary of references we need to keep, or Py_None */ - union value b_value; + PyObject_HEAD + char *b_ptr; /* pointer to memory block */ + int b_needsfree; /* need _we_ free the memory? */ + CDataObject *b_base; /* pointer to base object or NULL */ + Py_ssize_t b_size; /* size of memory block in bytes */ + Py_ssize_t b_length; /* number of references we need */ + Py_ssize_t b_index; /* index of this object into base's + b_object list */ + PyObject *b_objects; /* dictionary of references we need to keep, or Py_None */ + union value b_value; }; typedef struct { - PyObject_VAR_HEAD - ffi_closure *pcl; /* the C callable */ - ffi_cif cif; - int flags; - PyObject *converters; - PyObject *callable; - PyObject *restype; - SETFUNC setfunc; - ffi_type *ffi_restype; - ffi_type *atypes[1]; + PyObject_VAR_HEAD + ffi_closure *pcl; /* the C callable */ + ffi_cif cif; + int flags; + PyObject *converters; + PyObject *callable; + PyObject *restype; + SETFUNC setfunc; + ffi_type *ffi_restype; + ffi_type *atypes[1]; } CThunkObject; extern PyTypeObject PyCThunk_Type; -#define CThunk_CheckExact(v) ((v)->ob_type == &PyCThunk_Type) +#define CThunk_CheckExact(v) ((v)->ob_type == &PyCThunk_Type) typedef struct { - /* First part identical to tagCDataObject */ - PyObject_HEAD - char *b_ptr; /* pointer to memory block */ - int b_needsfree; /* need _we_ free the memory? */ - CDataObject *b_base; /* pointer to base object or NULL */ - Py_ssize_t b_size; /* size of memory block in bytes */ - Py_ssize_t b_length; /* number of references we need */ - Py_ssize_t b_index; /* index of this object into base's - b_object list */ - PyObject *b_objects; /* list of references we need to keep */ - union value b_value; - /* end of tagCDataObject, additional fields follow */ - - CThunkObject *thunk; - PyObject *callable; - - /* These two fields will override the ones in the type's stgdict if - they are set */ - PyObject *converters; - PyObject *argtypes; - PyObject *restype; - PyObject *checker; - PyObject *errcheck; + /* First part identical to tagCDataObject */ + PyObject_HEAD + char *b_ptr; /* pointer to memory block */ + int b_needsfree; /* need _we_ free the memory? */ + CDataObject *b_base; /* pointer to base object or NULL */ + Py_ssize_t b_size; /* size of memory block in bytes */ + Py_ssize_t b_length; /* number of references we need */ + Py_ssize_t b_index; /* index of this object into base's + b_object list */ + PyObject *b_objects; /* list of references we need to keep */ + union value b_value; + /* end of tagCDataObject, additional fields follow */ + + CThunkObject *thunk; + PyObject *callable; + + /* These two fields will override the ones in the type's stgdict if + they are set */ + PyObject *converters; + PyObject *argtypes; + PyObject *restype; + PyObject *checker; + PyObject *errcheck; #ifdef MS_WIN32 - int index; - GUID *iid; + int index; + GUID *iid; #endif - PyObject *paramflags; + PyObject *paramflags; } PyCFuncPtrObject; extern PyTypeObject PyCStgDict_Type; -#define PyCStgDict_CheckExact(v) ((v)->ob_type == &PyCStgDict_Type) -#define PyCStgDict_Check(v) PyObject_TypeCheck(v, &PyCStgDict_Type) +#define PyCStgDict_CheckExact(v) ((v)->ob_type == &PyCStgDict_Type) +#define PyCStgDict_Check(v) PyObject_TypeCheck(v, &PyCStgDict_Type) extern int PyCStructUnionType_update_stgdict(PyObject *fields, PyObject *type, int isStruct); extern int PyType_stginfo(PyTypeObject *self, Py_ssize_t *psize, Py_ssize_t *palign, Py_ssize_t *plength); @@ -109,12 +109,12 @@ extern PyTypeObject PyCData_Type; -#define CDataObject_CheckExact(v) ((v)->ob_type == &PyCData_Type) -#define CDataObject_Check(v) PyObject_TypeCheck(v, &PyCData_Type) +#define CDataObject_CheckExact(v) ((v)->ob_type == &PyCData_Type) +#define CDataObject_Check(v) PyObject_TypeCheck(v, &PyCData_Type) extern PyTypeObject PyCSimpleType_Type; -#define PyCSimpleTypeObject_CheckExact(v) ((v)->ob_type == &PyCSimpleType_Type) -#define PyCSimpleTypeObject_Check(v) PyObject_TypeCheck(v, &PyCSimpleType_Type) +#define PyCSimpleTypeObject_CheckExact(v) ((v)->ob_type == &PyCSimpleType_Type) +#define PyCSimpleTypeObject_Check(v) PyObject_TypeCheck(v, &PyCSimpleType_Type) extern PyTypeObject PyCField_Type; extern struct fielddesc *_ctypes_get_fielddesc(const char *fmt); @@ -122,9 +122,9 @@ extern PyObject * PyCField_FromDesc(PyObject *desc, Py_ssize_t index, - Py_ssize_t *pfield_size, int bitsize, int *pbitofs, - Py_ssize_t *psize, Py_ssize_t *poffset, Py_ssize_t *palign, - int pack, int is_big_endian); + Py_ssize_t *pfield_size, int bitsize, int *pbitofs, + Py_ssize_t *psize, Py_ssize_t *poffset, Py_ssize_t *palign, + int pack, int is_big_endian); extern PyObject *PyCData_AtAddress(PyObject *type, void *buf); extern PyObject *PyCData_FromBytes(PyObject *type, char *data, Py_ssize_t length); @@ -137,13 +137,13 @@ extern PyTypeObject PyCFuncPtrType_Type; extern PyTypeObject PyCStructType_Type; -#define PyCArrayTypeObject_Check(v) PyObject_TypeCheck(v, &PyCArrayType_Type) -#define ArrayObject_Check(v) PyObject_TypeCheck(v, &PyCArray_Type) -#define PointerObject_Check(v) PyObject_TypeCheck(v, &PyCPointer_Type) -#define PyCPointerTypeObject_Check(v) PyObject_TypeCheck(v, &PyCPointerType_Type) -#define PyCFuncPtrObject_Check(v) PyObject_TypeCheck(v, &PyCFuncPtr_Type) -#define PyCFuncPtrTypeObject_Check(v) PyObject_TypeCheck(v, &PyCFuncPtrType_Type) -#define PyCStructTypeObject_Check(v) PyObject_TypeCheck(v, &PyCStructType_Type) +#define PyCArrayTypeObject_Check(v) PyObject_TypeCheck(v, &PyCArrayType_Type) +#define ArrayObject_Check(v) PyObject_TypeCheck(v, &PyCArray_Type) +#define PointerObject_Check(v) PyObject_TypeCheck(v, &PyCPointer_Type) +#define PyCPointerTypeObject_Check(v) PyObject_TypeCheck(v, &PyCPointerType_Type) +#define PyCFuncPtrObject_Check(v) PyObject_TypeCheck(v, &PyCFuncPtr_Type) +#define PyCFuncPtrTypeObject_Check(v) PyObject_TypeCheck(v, &PyCFuncPtrType_Type) +#define PyCStructTypeObject_Check(v) PyObject_TypeCheck(v, &PyCStructType_Type) extern PyObject * PyCArrayType_from_ctype(PyObject *itemtype, Py_ssize_t length); @@ -151,35 +151,35 @@ extern PyMethodDef _ctypes_module_methods[]; extern CThunkObject *_ctypes_alloc_callback(PyObject *callable, - PyObject *converters, - PyObject *restype, - int flags); + PyObject *converters, + PyObject *restype, + int flags); /* a table entry describing a predefined ctypes type */ struct fielddesc { - char code; - SETFUNC setfunc; - GETFUNC getfunc; - ffi_type *pffi_type; /* always statically allocated */ - SETFUNC setfunc_swapped; - GETFUNC getfunc_swapped; + char code; + SETFUNC setfunc; + GETFUNC getfunc; + ffi_type *pffi_type; /* always statically allocated */ + SETFUNC setfunc_swapped; + GETFUNC getfunc_swapped; }; typedef struct { - PyObject_HEAD - Py_ssize_t offset; - Py_ssize_t size; - Py_ssize_t index; /* Index into CDataObject's - object array */ - PyObject *proto; /* a type or NULL */ - GETFUNC getfunc; /* getter function if proto is NULL */ - SETFUNC setfunc; /* setter function if proto is NULL */ - int anonymous; + PyObject_HEAD + Py_ssize_t offset; + Py_ssize_t size; + Py_ssize_t index; /* Index into CDataObject's + object array */ + PyObject *proto; /* a type or NULL */ + GETFUNC getfunc; /* getter function if proto is NULL */ + SETFUNC setfunc; /* setter function if proto is NULL */ + int anonymous; } CFieldObject; /* A subclass of PyDictObject, used as the instance dictionary of ctypes metatypes */ typedef struct { - PyDictObject dict; /* first part identical to PyDictObject */ + PyDictObject dict; /* first part identical to PyDictObject */ /* The size and align fields are unneeded, they are in ffi_type as well. As an experiment shows, it's trivial to get rid of them, the only thing to remember is that in PyCArrayType_new the ffi_type fields must be filled in - @@ -188,28 +188,28 @@ too much risk to change that now, and there are other fields which doen't belong into this structure anyway. Maybe in ctypes 2.0... (ctypes 2000?) */ - Py_ssize_t size; /* number of bytes */ - Py_ssize_t align; /* alignment requirements */ - Py_ssize_t length; /* number of fields */ - ffi_type ffi_type_pointer; - PyObject *proto; /* Only for Pointer/ArrayObject */ - SETFUNC setfunc; /* Only for simple objects */ - GETFUNC getfunc; /* Only for simple objects */ - PARAMFUNC paramfunc; - - /* Following fields only used by PyCFuncPtrType_Type instances */ - PyObject *argtypes; /* tuple of CDataObjects */ - PyObject *converters; /* tuple([t.from_param for t in argtypes]) */ - PyObject *restype; /* CDataObject or NULL */ - PyObject *checker; - int flags; /* calling convention and such */ - - /* pep3118 fields, pointers neeed PyMem_Free */ - char *format; - int ndim; - Py_ssize_t *shape; -/* Py_ssize_t *strides; */ /* unused in ctypes */ -/* Py_ssize_t *suboffsets; */ /* unused in ctypes */ + Py_ssize_t size; /* number of bytes */ + Py_ssize_t align; /* alignment requirements */ + Py_ssize_t length; /* number of fields */ + ffi_type ffi_type_pointer; + PyObject *proto; /* Only for Pointer/ArrayObject */ + SETFUNC setfunc; /* Only for simple objects */ + GETFUNC getfunc; /* Only for simple objects */ + PARAMFUNC paramfunc; + + /* Following fields only used by PyCFuncPtrType_Type instances */ + PyObject *argtypes; /* tuple of CDataObjects */ + PyObject *converters; /* tuple([t.from_param for t in argtypes]) */ + PyObject *restype; /* CDataObject or NULL */ + PyObject *checker; + int flags; /* calling convention and such */ + + /* pep3118 fields, pointers neeed PyMem_Free */ + char *format; + int ndim; + Py_ssize_t *shape; +/* Py_ssize_t *strides; */ /* unused in ctypes */ +/* Py_ssize_t *suboffsets; */ /* unused in ctypes */ } StgDictObject; @@ -264,16 +264,16 @@ typedef int(* PPROC)(void); PyObject *_ctypes_callproc(PPROC pProc, - PyObject *arguments, + PyObject *arguments, #ifdef MS_WIN32 - IUnknown *pIUnk, - GUID *iid, + IUnknown *pIUnk, + GUID *iid, #endif - int flags, - PyObject *argtypes, - PyObject *restype, - PyObject *checker); - + int flags, + PyObject *argtypes, + PyObject *restype, + PyObject *checker); + #define FUNCFLAG_STDCALL 0x0 #define FUNCFLAG_CDECL 0x1 @@ -288,45 +288,45 @@ #define DICTFLAG_FINAL 0x1000 struct tagPyCArgObject { - PyObject_HEAD - ffi_type *pffi_type; - char tag; - union { - char c; - char b; - short h; - int i; - long l; + PyObject_HEAD + ffi_type *pffi_type; + char tag; + union { + char c; + char b; + short h; + int i; + long l; #ifdef HAVE_LONG_LONG - PY_LONG_LONG q; + PY_LONG_LONG q; #endif - long double D; - double d; - float f; - void *p; - } value; - PyObject *obj; - Py_ssize_t size; /* for the 'V' tag */ + long double D; + double d; + float f; + void *p; + } value; + PyObject *obj; + Py_ssize_t size; /* for the 'V' tag */ }; extern PyTypeObject PyCArg_Type; -#define PyCArg_CheckExact(v) ((v)->ob_type == &PyCArg_Type) +#define PyCArg_CheckExact(v) ((v)->ob_type == &PyCArg_Type) extern PyCArgObject *PyCArgObject_new(void); extern PyObject * PyCData_get(PyObject *type, GETFUNC getfunc, PyObject *src, - Py_ssize_t index, Py_ssize_t size, char *ptr); + Py_ssize_t index, Py_ssize_t size, char *ptr); extern int PyCData_set(PyObject *dst, PyObject *type, SETFUNC setfunc, PyObject *value, - Py_ssize_t index, Py_ssize_t size, char *ptr); + Py_ssize_t index, Py_ssize_t size, char *ptr); extern void _ctypes_extend_error(PyObject *exc_class, char *fmt, ...); struct basespec { - CDataObject *base; - Py_ssize_t index; - char *adr; + CDataObject *base; + Py_ssize_t index; + char *adr; }; extern char basespec_string[]; Modified: python/branches/py3k-jit/Modules/_ctypes/darwin/dlfcn_simple.c ============================================================================== --- python/branches/py3k-jit/Modules/_ctypes/darwin/dlfcn_simple.c (original) +++ python/branches/py3k-jit/Modules/_ctypes/darwin/dlfcn_simple.c Mon May 10 23:55:43 2010 @@ -81,167 +81,167 @@ /* Set and get the error string for use by dlerror */ static const char *error(int setget, const char *str, ...) { - static char errstr[ERR_STR_LEN]; - static int err_filled = 0; - const char *retval; - va_list arg; - if (setget == 0) - { - va_start(arg, str); - strncpy(errstr, "dlcompat: ", ERR_STR_LEN); - vsnprintf(errstr + 10, ERR_STR_LEN - 10, str, arg); - va_end(arg); - err_filled = 1; - retval = NULL; - } - else - { - if (!err_filled) - retval = NULL; - else - retval = errstr; - err_filled = 0; - } - return retval; + static char errstr[ERR_STR_LEN]; + static int err_filled = 0; + const char *retval; + va_list arg; + if (setget == 0) + { + va_start(arg, str); + strncpy(errstr, "dlcompat: ", ERR_STR_LEN); + vsnprintf(errstr + 10, ERR_STR_LEN - 10, str, arg); + va_end(arg); + err_filled = 1; + retval = NULL; + } + else + { + if (!err_filled) + retval = NULL; + else + retval = errstr; + err_filled = 0; + } + return retval; } /* darwin_dlopen */ static void *darwin_dlopen(const char *path, int mode) { - void *module = 0; - NSObjectFileImage ofi = 0; - NSObjectFileImageReturnCode ofirc; - - /* If we got no path, the app wants the global namespace, use -1 as the marker - in this case */ - if (!path) - return (void *)-1; - - /* Create the object file image, works for things linked with the -bundle arg to ld */ - ofirc = NSCreateObjectFileImageFromFile(path, &ofi); - switch (ofirc) - { - case NSObjectFileImageSuccess: - /* It was okay, so use NSLinkModule to link in the image */ - module = NSLinkModule(ofi, path, - NSLINKMODULE_OPTION_RETURN_ON_ERROR - | (mode & RTLD_GLOBAL) ? 0 : NSLINKMODULE_OPTION_PRIVATE - | (mode & RTLD_LAZY) ? 0 : NSLINKMODULE_OPTION_BINDNOW); - NSDestroyObjectFileImage(ofi); - break; - case NSObjectFileImageInappropriateFile: - /* It may have been a dynamic library rather than a bundle, try to load it */ - module = (void *)NSAddImage(path, NSADDIMAGE_OPTION_RETURN_ON_ERROR); - break; - default: - /* God knows what we got */ - error(0, "Can not open \"%s\"", path); - return 0; - } - if (!module) - error(0, "Can not open \"%s\"", path); - return module; + void *module = 0; + NSObjectFileImage ofi = 0; + NSObjectFileImageReturnCode ofirc; + + /* If we got no path, the app wants the global namespace, use -1 as the marker + in this case */ + if (!path) + return (void *)-1; + + /* Create the object file image, works for things linked with the -bundle arg to ld */ + ofirc = NSCreateObjectFileImageFromFile(path, &ofi); + switch (ofirc) + { + case NSObjectFileImageSuccess: + /* It was okay, so use NSLinkModule to link in the image */ + module = NSLinkModule(ofi, path, + NSLINKMODULE_OPTION_RETURN_ON_ERROR + | (mode & RTLD_GLOBAL) ? 0 : NSLINKMODULE_OPTION_PRIVATE + | (mode & RTLD_LAZY) ? 0 : NSLINKMODULE_OPTION_BINDNOW); + NSDestroyObjectFileImage(ofi); + break; + case NSObjectFileImageInappropriateFile: + /* It may have been a dynamic library rather than a bundle, try to load it */ + module = (void *)NSAddImage(path, NSADDIMAGE_OPTION_RETURN_ON_ERROR); + break; + default: + /* God knows what we got */ + error(0, "Can not open \"%s\"", path); + return 0; + } + if (!module) + error(0, "Can not open \"%s\"", path); + return module; } /* dlsymIntern is used by dlsym to find the symbol */ static void *dlsymIntern(void *handle, const char *symbol) { - NSSymbol nssym = 0; - /* If the handle is -1, if is the app global context */ - if (handle == (void *)-1) - { - /* Global context, use NSLookupAndBindSymbol */ - if (NSIsSymbolNameDefined(symbol)) - { - nssym = NSLookupAndBindSymbol(symbol); - } - - } - /* Now see if the handle is a struch mach_header* or not, use NSLookupSymbol in image - for libraries, and NSLookupSymbolInModule for bundles */ - else - { - /* Check for both possible magic numbers depending on x86/ppc byte order */ - if ((((struct mach_header *)handle)->magic == MH_MAGIC) || - (((struct mach_header *)handle)->magic == MH_CIGAM)) - { - if (NSIsSymbolNameDefinedInImage((struct mach_header *)handle, symbol)) - { - nssym = NSLookupSymbolInImage((struct mach_header *)handle, - symbol, - NSLOOKUPSYMBOLINIMAGE_OPTION_BIND - | NSLOOKUPSYMBOLINIMAGE_OPTION_RETURN_ON_ERROR); - } - - } - else - { - nssym = NSLookupSymbolInModule(handle, symbol); - } - } - if (!nssym) - { - error(0, "Symbol \"%s\" Not found", symbol); - return NULL; - } - return NSAddressOfSymbol(nssym); + NSSymbol nssym = 0; + /* If the handle is -1, if is the app global context */ + if (handle == (void *)-1) + { + /* Global context, use NSLookupAndBindSymbol */ + if (NSIsSymbolNameDefined(symbol)) + { + nssym = NSLookupAndBindSymbol(symbol); + } + + } + /* Now see if the handle is a struch mach_header* or not, use NSLookupSymbol in image + for libraries, and NSLookupSymbolInModule for bundles */ + else + { + /* Check for both possible magic numbers depending on x86/ppc byte order */ + if ((((struct mach_header *)handle)->magic == MH_MAGIC) || + (((struct mach_header *)handle)->magic == MH_CIGAM)) + { + if (NSIsSymbolNameDefinedInImage((struct mach_header *)handle, symbol)) + { + nssym = NSLookupSymbolInImage((struct mach_header *)handle, + symbol, + NSLOOKUPSYMBOLINIMAGE_OPTION_BIND + | NSLOOKUPSYMBOLINIMAGE_OPTION_RETURN_ON_ERROR); + } + + } + else + { + nssym = NSLookupSymbolInModule(handle, symbol); + } + } + if (!nssym) + { + error(0, "Symbol \"%s\" Not found", symbol); + return NULL; + } + return NSAddressOfSymbol(nssym); } static const char *darwin_dlerror(void) { - return error(1, (char *)NULL); + return error(1, (char *)NULL); } static int darwin_dlclose(void *handle) { - if ((((struct mach_header *)handle)->magic == MH_MAGIC) || - (((struct mach_header *)handle)->magic == MH_CIGAM)) - { - error(0, "Can't remove dynamic libraries on darwin"); - return 0; - } - if (!NSUnLinkModule(handle, 0)) - { - error(0, "unable to unlink module %s", NSNameOfModule(handle)); - return 1; - } - return 0; + if ((((struct mach_header *)handle)->magic == MH_MAGIC) || + (((struct mach_header *)handle)->magic == MH_CIGAM)) + { + error(0, "Can't remove dynamic libraries on darwin"); + return 0; + } + if (!NSUnLinkModule(handle, 0)) + { + error(0, "unable to unlink module %s", NSNameOfModule(handle)); + return 1; + } + return 0; } /* dlsym, prepend the underscore and call dlsymIntern */ static void *darwin_dlsym(void *handle, const char *symbol) { - static char undersym[257]; /* Saves calls to malloc(3) */ - int sym_len = strlen(symbol); - void *value = NULL; - char *malloc_sym = NULL; - - if (sym_len < 256) - { - snprintf(undersym, 256, "_%s", symbol); - value = dlsymIntern(handle, undersym); - } - else - { - malloc_sym = malloc(sym_len + 2); - if (malloc_sym) - { - sprintf(malloc_sym, "_%s", symbol); - value = dlsymIntern(handle, malloc_sym); - free(malloc_sym); - } - else - { - error(0, "Unable to allocate memory"); - } - } - return value; + static char undersym[257]; /* Saves calls to malloc(3) */ + int sym_len = strlen(symbol); + void *value = NULL; + char *malloc_sym = NULL; + + if (sym_len < 256) + { + snprintf(undersym, 256, "_%s", symbol); + value = dlsymIntern(handle, undersym); + } + else + { + malloc_sym = malloc(sym_len + 2); + if (malloc_sym) + { + sprintf(malloc_sym, "_%s", symbol); + value = dlsymIntern(handle, malloc_sym); + free(malloc_sym); + } + else + { + error(0, "Unable to allocate memory"); + } + } + return value; } static int darwin_dladdr(const void *handle, Dl_info *info) { - return 0; + return 0; } #endif /* MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_3 */ @@ -252,21 +252,21 @@ static #endif void ctypes_dlfcn_init(void) { - if (dlopen != NULL) { - ctypes_dlsym = dlsym; - ctypes_dlopen = dlopen; - ctypes_dlerror = dlerror; - ctypes_dlclose = dlclose; - ctypes_dladdr = dladdr; - } else { + if (dlopen != NULL) { + ctypes_dlsym = dlsym; + ctypes_dlopen = dlopen; + ctypes_dlerror = dlerror; + ctypes_dlclose = dlclose; + ctypes_dladdr = dladdr; + } else { #if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_3 - ctypes_dlsym = darwin_dlsym; - ctypes_dlopen = darwin_dlopen; - ctypes_dlerror = darwin_dlerror; - ctypes_dlclose = darwin_dlclose; - ctypes_dladdr = darwin_dladdr; + ctypes_dlsym = darwin_dlsym; + ctypes_dlopen = darwin_dlopen; + ctypes_dlerror = darwin_dlerror; + ctypes_dlclose = darwin_dlclose; + ctypes_dladdr = darwin_dladdr; #endif /* MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_3 */ - } + } } #endif /* CTYPES_DARWIN_DLFCN */ Modified: python/branches/py3k-jit/Modules/_ctypes/malloc_closure.c ============================================================================== --- python/branches/py3k-jit/Modules/_ctypes/malloc_closure.c (original) +++ python/branches/py3k-jit/Modules/_ctypes/malloc_closure.c Mon May 10 23:55:43 2010 @@ -23,8 +23,8 @@ /******************************************************************/ typedef union _tagITEM { - ffi_closure closure; - union _tagITEM *next; + ffi_closure closure; + union _tagITEM *next; } ITEM; static ITEM *free_list; @@ -32,58 +32,58 @@ static void more_core(void) { - ITEM *item; - int count, i; + ITEM *item; + int count, i; /* determine the pagesize */ #ifdef MS_WIN32 - if (!_pagesize) { - SYSTEM_INFO systeminfo; - GetSystemInfo(&systeminfo); - _pagesize = systeminfo.dwPageSize; - } + if (!_pagesize) { + SYSTEM_INFO systeminfo; + GetSystemInfo(&systeminfo); + _pagesize = systeminfo.dwPageSize; + } #else - if (!_pagesize) { + if (!_pagesize) { #ifdef _SC_PAGESIZE - _pagesize = sysconf(_SC_PAGESIZE); + _pagesize = sysconf(_SC_PAGESIZE); #else - _pagesize = getpagesize(); + _pagesize = getpagesize(); #endif - } + } #endif - /* calculate the number of nodes to allocate */ - count = BLOCKSIZE / sizeof(ITEM); + /* calculate the number of nodes to allocate */ + count = BLOCKSIZE / sizeof(ITEM); - /* allocate a memory block */ + /* allocate a memory block */ #ifdef MS_WIN32 - item = (ITEM *)VirtualAlloc(NULL, - count * sizeof(ITEM), - MEM_COMMIT, - PAGE_EXECUTE_READWRITE); - if (item == NULL) - return; + item = (ITEM *)VirtualAlloc(NULL, + count * sizeof(ITEM), + MEM_COMMIT, + PAGE_EXECUTE_READWRITE); + if (item == NULL) + return; #else - item = (ITEM *)mmap(NULL, - count * sizeof(ITEM), - PROT_READ | PROT_WRITE | PROT_EXEC, - MAP_PRIVATE | MAP_ANONYMOUS, - -1, - 0); - if (item == (void *)MAP_FAILED) - return; + item = (ITEM *)mmap(NULL, + count * sizeof(ITEM), + PROT_READ | PROT_WRITE | PROT_EXEC, + MAP_PRIVATE | MAP_ANONYMOUS, + -1, + 0); + if (item == (void *)MAP_FAILED) + return; #endif #ifdef MALLOC_CLOSURE_DEBUG - printf("block at %p allocated (%d bytes), %d ITEMs\n", - item, count * sizeof(ITEM), count); + printf("block at %p allocated (%d bytes), %d ITEMs\n", + item, count * sizeof(ITEM), count); #endif - /* put them into the free list */ - for (i = 0; i < count; ++i) { - item->next = free_list; - free_list = item; - ++item; - } + /* put them into the free list */ + for (i = 0; i < count; ++i) { + item->next = free_list; + free_list = item; + ++item; + } } /******************************************************************/ @@ -91,20 +91,20 @@ /* put the item back into the free list */ void _ctypes_free_closure(void *p) { - ITEM *item = (ITEM *)p; - item->next = free_list; - free_list = item; + ITEM *item = (ITEM *)p; + item->next = free_list; + free_list = item; } /* return one item from the free list, allocating more if needed */ void *_ctypes_alloc_closure(void) { - ITEM *item; - if (!free_list) - more_core(); - if (!free_list) - return NULL; - item = free_list; - free_list = item->next; - return item; + ITEM *item; + if (!free_list) + more_core(); + if (!free_list) + return NULL; + item = free_list; + free_list = item->next; + return item; } Modified: python/branches/py3k-jit/Modules/_ctypes/stgdict.c ============================================================================== --- python/branches/py3k-jit/Modules/_ctypes/stgdict.c (original) +++ python/branches/py3k-jit/Modules/_ctypes/stgdict.c Mon May 10 23:55:43 2010 @@ -19,143 +19,143 @@ static int PyCStgDict_init(StgDictObject *self, PyObject *args, PyObject *kwds) { - if (PyDict_Type.tp_init((PyObject *)self, args, kwds) < 0) - return -1; - self->format = NULL; - self->ndim = 0; - self->shape = NULL; - return 0; + if (PyDict_Type.tp_init((PyObject *)self, args, kwds) < 0) + return -1; + self->format = NULL; + self->ndim = 0; + self->shape = NULL; + return 0; } static int PyCStgDict_clear(StgDictObject *self) { - Py_CLEAR(self->proto); - Py_CLEAR(self->argtypes); - Py_CLEAR(self->converters); - Py_CLEAR(self->restype); - Py_CLEAR(self->checker); - return 0; + Py_CLEAR(self->proto); + Py_CLEAR(self->argtypes); + Py_CLEAR(self->converters); + Py_CLEAR(self->restype); + Py_CLEAR(self->checker); + return 0; } static void PyCStgDict_dealloc(StgDictObject *self) { - PyCStgDict_clear(self); - PyMem_Free(self->format); - PyMem_Free(self->shape); - PyMem_Free(self->ffi_type_pointer.elements); - PyDict_Type.tp_dealloc((PyObject *)self); + PyCStgDict_clear(self); + PyMem_Free(self->format); + PyMem_Free(self->shape); + PyMem_Free(self->ffi_type_pointer.elements); + PyDict_Type.tp_dealloc((PyObject *)self); } int PyCStgDict_clone(StgDictObject *dst, StgDictObject *src) { - char *d, *s; - Py_ssize_t size; + char *d, *s; + Py_ssize_t size; - PyCStgDict_clear(dst); - PyMem_Free(dst->ffi_type_pointer.elements); - PyMem_Free(dst->format); - dst->format = NULL; - PyMem_Free(dst->shape); - dst->shape = NULL; - dst->ffi_type_pointer.elements = NULL; - - d = (char *)dst; - s = (char *)src; - memcpy(d + sizeof(PyDictObject), - s + sizeof(PyDictObject), - sizeof(StgDictObject) - sizeof(PyDictObject)); - - Py_XINCREF(dst->proto); - Py_XINCREF(dst->argtypes); - Py_XINCREF(dst->converters); - Py_XINCREF(dst->restype); - Py_XINCREF(dst->checker); - - if (src->format) { - dst->format = PyMem_Malloc(strlen(src->format) + 1); - if (dst->format == NULL) - return -1; - strcpy(dst->format, src->format); - } - if (src->shape) { - dst->shape = PyMem_Malloc(sizeof(Py_ssize_t) * src->ndim); - if (dst->shape == NULL) - return -1; - memcpy(dst->shape, src->shape, - sizeof(Py_ssize_t) * src->ndim); - } - - if (src->ffi_type_pointer.elements == NULL) - return 0; - size = sizeof(ffi_type *) * (src->length + 1); - dst->ffi_type_pointer.elements = PyMem_Malloc(size); - if (dst->ffi_type_pointer.elements == NULL) { - PyErr_NoMemory(); - return -1; - } - memcpy(dst->ffi_type_pointer.elements, - src->ffi_type_pointer.elements, - size); - return 0; + PyCStgDict_clear(dst); + PyMem_Free(dst->ffi_type_pointer.elements); + PyMem_Free(dst->format); + dst->format = NULL; + PyMem_Free(dst->shape); + dst->shape = NULL; + dst->ffi_type_pointer.elements = NULL; + + d = (char *)dst; + s = (char *)src; + memcpy(d + sizeof(PyDictObject), + s + sizeof(PyDictObject), + sizeof(StgDictObject) - sizeof(PyDictObject)); + + Py_XINCREF(dst->proto); + Py_XINCREF(dst->argtypes); + Py_XINCREF(dst->converters); + Py_XINCREF(dst->restype); + Py_XINCREF(dst->checker); + + if (src->format) { + dst->format = PyMem_Malloc(strlen(src->format) + 1); + if (dst->format == NULL) + return -1; + strcpy(dst->format, src->format); + } + if (src->shape) { + dst->shape = PyMem_Malloc(sizeof(Py_ssize_t) * src->ndim); + if (dst->shape == NULL) + return -1; + memcpy(dst->shape, src->shape, + sizeof(Py_ssize_t) * src->ndim); + } + + if (src->ffi_type_pointer.elements == NULL) + return 0; + size = sizeof(ffi_type *) * (src->length + 1); + dst->ffi_type_pointer.elements = PyMem_Malloc(size); + if (dst->ffi_type_pointer.elements == NULL) { + PyErr_NoMemory(); + return -1; + } + memcpy(dst->ffi_type_pointer.elements, + src->ffi_type_pointer.elements, + size); + return 0; } PyTypeObject PyCStgDict_Type = { - PyVarObject_HEAD_INIT(NULL, 0) - "StgDict", - sizeof(StgDictObject), - 0, - (destructor)PyCStgDict_dealloc, /* tp_dealloc */ - 0, /* tp_print */ - 0, /* tp_getattr */ - 0, /* tp_setattr */ - 0, /* tp_reserved */ - 0, /* tp_repr */ - 0, /* tp_as_number */ - 0, /* tp_as_sequence */ - 0, /* tp_as_mapping */ - 0, /* tp_hash */ - 0, /* tp_call */ - 0, /* tp_str */ - 0, /* tp_getattro */ - 0, /* tp_setattro */ - 0, /* tp_as_buffer */ - Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */ - 0, /* tp_doc */ - 0, /* tp_traverse */ - 0, /* tp_clear */ - 0, /* tp_richcompare */ - 0, /* tp_weaklistoffset */ - 0, /* tp_iter */ - 0, /* tp_iternext */ - 0, /* tp_methods */ - 0, /* tp_members */ - 0, /* tp_getset */ - 0, /* tp_base */ - 0, /* tp_dict */ - 0, /* tp_descr_get */ - 0, /* tp_descr_set */ - 0, /* tp_dictoffset */ - (initproc)PyCStgDict_init, /* tp_init */ - 0, /* tp_alloc */ - 0, /* tp_new */ - 0, /* tp_free */ + PyVarObject_HEAD_INIT(NULL, 0) + "StgDict", + sizeof(StgDictObject), + 0, + (destructor)PyCStgDict_dealloc, /* tp_dealloc */ + 0, /* tp_print */ + 0, /* tp_getattr */ + 0, /* tp_setattr */ + 0, /* tp_reserved */ + 0, /* tp_repr */ + 0, /* tp_as_number */ + 0, /* tp_as_sequence */ + 0, /* tp_as_mapping */ + 0, /* tp_hash */ + 0, /* tp_call */ + 0, /* tp_str */ + 0, /* tp_getattro */ + 0, /* tp_setattro */ + 0, /* tp_as_buffer */ + Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */ + 0, /* tp_doc */ + 0, /* tp_traverse */ + 0, /* tp_clear */ + 0, /* tp_richcompare */ + 0, /* tp_weaklistoffset */ + 0, /* tp_iter */ + 0, /* tp_iternext */ + 0, /* tp_methods */ + 0, /* tp_members */ + 0, /* tp_getset */ + 0, /* tp_base */ + 0, /* tp_dict */ + 0, /* tp_descr_get */ + 0, /* tp_descr_set */ + 0, /* tp_dictoffset */ + (initproc)PyCStgDict_init, /* tp_init */ + 0, /* tp_alloc */ + 0, /* tp_new */ + 0, /* tp_free */ }; /* May return NULL, but does not set an exception! */ StgDictObject * PyType_stgdict(PyObject *obj) { - PyTypeObject *type; + PyTypeObject *type; - if (!PyType_Check(obj)) - return NULL; - type = (PyTypeObject *)obj; - if (!type->tp_dict || !PyCStgDict_CheckExact(type->tp_dict)) - return NULL; - return (StgDictObject *)type->tp_dict; + if (!PyType_Check(obj)) + return NULL; + type = (PyTypeObject *)obj; + if (!type->tp_dict || !PyCStgDict_CheckExact(type->tp_dict)) + return NULL; + return (StgDictObject *)type->tp_dict; } /* May return NULL, but does not set an exception! */ @@ -166,10 +166,10 @@ StgDictObject * PyObject_stgdict(PyObject *self) { - PyTypeObject *type = self->ob_type; - if (!type->tp_dict || !PyCStgDict_CheckExact(type->tp_dict)) - return NULL; - return (StgDictObject *)type->tp_dict; + PyTypeObject *type = self->ob_type; + if (!type->tp_dict || !PyCStgDict_CheckExact(type->tp_dict)) + return NULL; + return (StgDictObject *)type->tp_dict; } /* descr is the descriptor for a field marked as anonymous. Get all the @@ -178,78 +178,78 @@ */ static int MakeFields(PyObject *type, CFieldObject *descr, - Py_ssize_t index, Py_ssize_t offset) + Py_ssize_t index, Py_ssize_t offset) { - Py_ssize_t i; - PyObject *fields; - PyObject *fieldlist; - - fields = PyObject_GetAttrString(descr->proto, "_fields_"); - if (fields == NULL) - return -1; - fieldlist = PySequence_Fast(fields, "_fields_ must be a sequence"); - Py_DECREF(fields); - if (fieldlist == NULL) - return -1; - - for (i = 0; i < PySequence_Fast_GET_SIZE(fieldlist); ++i) { - PyObject *pair = PySequence_Fast_GET_ITEM(fieldlist, i); /* borrowed */ - PyObject *fname, *ftype, *bits; - CFieldObject *fdescr; - CFieldObject *new_descr; - /* Convert to PyArg_UnpackTuple... */ - if (!PyArg_ParseTuple(pair, "OO|O", &fname, &ftype, &bits)) { - Py_DECREF(fieldlist); - return -1; - } - fdescr = (CFieldObject *)PyObject_GetAttr(descr->proto, fname); - if (fdescr == NULL) { - Py_DECREF(fieldlist); - return -1; - } - if (Py_TYPE(fdescr) != &PyCField_Type) { - PyErr_SetString(PyExc_TypeError, "unexpected type"); - Py_DECREF(fdescr); - Py_DECREF(fieldlist); - return -1; - } - if (fdescr->anonymous) { - int rc = MakeFields(type, fdescr, - index + fdescr->index, - offset + fdescr->offset); - Py_DECREF(fdescr); - if (rc == -1) { - Py_DECREF(fieldlist); - return -1; - } - continue; - } - new_descr = (CFieldObject *)PyObject_CallObject((PyObject *)&PyCField_Type, NULL); - if (new_descr == NULL) { - Py_DECREF(fdescr); - Py_DECREF(fieldlist); - return -1; - } - assert(Py_TYPE(new_descr) == &PyCField_Type); - new_descr->size = fdescr->size; - new_descr->offset = fdescr->offset + offset; - new_descr->index = fdescr->index + index; - new_descr->proto = fdescr->proto; - Py_XINCREF(new_descr->proto); - new_descr->getfunc = fdescr->getfunc; - new_descr->setfunc = fdescr->setfunc; - - Py_DECREF(fdescr); - - if (-1 == PyObject_SetAttr(type, fname, (PyObject *)new_descr)) { - Py_DECREF(fieldlist); - Py_DECREF(new_descr); - return -1; - } - Py_DECREF(new_descr); - } - Py_DECREF(fieldlist); - return 0; + Py_ssize_t i; + PyObject *fields; + PyObject *fieldlist; + + fields = PyObject_GetAttrString(descr->proto, "_fields_"); + if (fields == NULL) + return -1; + fieldlist = PySequence_Fast(fields, "_fields_ must be a sequence"); + Py_DECREF(fields); + if (fieldlist == NULL) + return -1; + + for (i = 0; i < PySequence_Fast_GET_SIZE(fieldlist); ++i) { + PyObject *pair = PySequence_Fast_GET_ITEM(fieldlist, i); /* borrowed */ + PyObject *fname, *ftype, *bits; + CFieldObject *fdescr; + CFieldObject *new_descr; + /* Convert to PyArg_UnpackTuple... */ + if (!PyArg_ParseTuple(pair, "OO|O", &fname, &ftype, &bits)) { + Py_DECREF(fieldlist); + return -1; + } + fdescr = (CFieldObject *)PyObject_GetAttr(descr->proto, fname); + if (fdescr == NULL) { + Py_DECREF(fieldlist); + return -1; + } + if (Py_TYPE(fdescr) != &PyCField_Type) { + PyErr_SetString(PyExc_TypeError, "unexpected type"); + Py_DECREF(fdescr); + Py_DECREF(fieldlist); + return -1; + } + if (fdescr->anonymous) { + int rc = MakeFields(type, fdescr, + index + fdescr->index, + offset + fdescr->offset); + Py_DECREF(fdescr); + if (rc == -1) { + Py_DECREF(fieldlist); + return -1; + } + continue; + } + new_descr = (CFieldObject *)PyObject_CallObject((PyObject *)&PyCField_Type, NULL); + if (new_descr == NULL) { + Py_DECREF(fdescr); + Py_DECREF(fieldlist); + return -1; + } + assert(Py_TYPE(new_descr) == &PyCField_Type); + new_descr->size = fdescr->size; + new_descr->offset = fdescr->offset + offset; + new_descr->index = fdescr->index + index; + new_descr->proto = fdescr->proto; + Py_XINCREF(new_descr->proto); + new_descr->getfunc = fdescr->getfunc; + new_descr->setfunc = fdescr->setfunc; + + Py_DECREF(fdescr); + + if (-1 == PyObject_SetAttr(type, fname, (PyObject *)new_descr)) { + Py_DECREF(fieldlist); + Py_DECREF(new_descr); + return -1; + } + Py_DECREF(new_descr); + } + Py_DECREF(fieldlist); + return 0; } /* Iterate over the names in the type's _anonymous_ attribute, if present, @@ -257,43 +257,43 @@ static int MakeAnonFields(PyObject *type) { - PyObject *anon; - PyObject *anon_names; - Py_ssize_t i; - - anon = PyObject_GetAttrString(type, "_anonymous_"); - if (anon == NULL) { - PyErr_Clear(); - return 0; - } - anon_names = PySequence_Fast(anon, "_anonymous_ must be a sequence"); - Py_DECREF(anon); - if (anon_names == NULL) - return -1; - - for (i = 0; i < PySequence_Fast_GET_SIZE(anon_names); ++i) { - PyObject *fname = PySequence_Fast_GET_ITEM(anon_names, i); /* borrowed */ - CFieldObject *descr = (CFieldObject *)PyObject_GetAttr(type, fname); - if (descr == NULL) { - Py_DECREF(anon_names); - return -1; - } - assert(Py_TYPE(descr) == &PyCField_Type); - descr->anonymous = 1; - - /* descr is in the field descriptor. */ - if (-1 == MakeFields(type, (CFieldObject *)descr, - ((CFieldObject *)descr)->index, - ((CFieldObject *)descr)->offset)) { - Py_DECREF(descr); - Py_DECREF(anon_names); - return -1; - } - Py_DECREF(descr); - } + PyObject *anon; + PyObject *anon_names; + Py_ssize_t i; + + anon = PyObject_GetAttrString(type, "_anonymous_"); + if (anon == NULL) { + PyErr_Clear(); + return 0; + } + anon_names = PySequence_Fast(anon, "_anonymous_ must be a sequence"); + Py_DECREF(anon); + if (anon_names == NULL) + return -1; + + for (i = 0; i < PySequence_Fast_GET_SIZE(anon_names); ++i) { + PyObject *fname = PySequence_Fast_GET_ITEM(anon_names, i); /* borrowed */ + CFieldObject *descr = (CFieldObject *)PyObject_GetAttr(type, fname); + if (descr == NULL) { + Py_DECREF(anon_names); + return -1; + } + assert(Py_TYPE(descr) == &PyCField_Type); + descr->anonymous = 1; + + /* descr is in the field descriptor. */ + if (-1 == MakeFields(type, (CFieldObject *)descr, + ((CFieldObject *)descr)->index, + ((CFieldObject *)descr)->offset)) { + Py_DECREF(descr); + Py_DECREF(anon_names); + return -1; + } + Py_DECREF(descr); + } - Py_DECREF(anon_names); - return 0; + Py_DECREF(anon_names); + return 0; } /* @@ -303,261 +303,261 @@ int PyCStructUnionType_update_stgdict(PyObject *type, PyObject *fields, int isStruct) { - StgDictObject *stgdict, *basedict; - Py_ssize_t len, offset, size, align, i; - Py_ssize_t union_size, total_align; - Py_ssize_t field_size = 0; - int bitofs; - PyObject *isPacked; - int pack = 0; - Py_ssize_t ffi_ofs; - int big_endian; - - /* HACK Alert: I cannot be bothered to fix ctypes.com, so there has to - be a way to use the old, broken sematics: _fields_ are not extended - but replaced in subclasses. - - XXX Remove this in ctypes 1.0! - */ - int use_broken_old_ctypes_semantics; + StgDictObject *stgdict, *basedict; + Py_ssize_t len, offset, size, align, i; + Py_ssize_t union_size, total_align; + Py_ssize_t field_size = 0; + int bitofs; + PyObject *isPacked; + int pack = 0; + Py_ssize_t ffi_ofs; + int big_endian; + + /* HACK Alert: I cannot be bothered to fix ctypes.com, so there has to + be a way to use the old, broken sematics: _fields_ are not extended + but replaced in subclasses. + + XXX Remove this in ctypes 1.0! + */ + int use_broken_old_ctypes_semantics; - if (fields == NULL) - return 0; + if (fields == NULL) + return 0; #ifdef WORDS_BIGENDIAN - big_endian = PyObject_HasAttrString(type, "_swappedbytes_") ? 0 : 1; + big_endian = PyObject_HasAttrString(type, "_swappedbytes_") ? 0 : 1; #else - big_endian = PyObject_HasAttrString(type, "_swappedbytes_") ? 1 : 0; + big_endian = PyObject_HasAttrString(type, "_swappedbytes_") ? 1 : 0; #endif - use_broken_old_ctypes_semantics = \ - PyObject_HasAttrString(type, "_use_broken_old_ctypes_structure_semantics_"); + use_broken_old_ctypes_semantics = \ + PyObject_HasAttrString(type, "_use_broken_old_ctypes_structure_semantics_"); - isPacked = PyObject_GetAttrString(type, "_pack_"); - if (isPacked) { - pack = PyLong_AsLong(isPacked); - if (pack < 0 || PyErr_Occurred()) { - Py_XDECREF(isPacked); - PyErr_SetString(PyExc_ValueError, - "_pack_ must be a non-negative integer"); - return -1; - } - Py_DECREF(isPacked); - } else - PyErr_Clear(); - - len = PySequence_Length(fields); - if (len == -1) { - PyErr_SetString(PyExc_TypeError, - "'_fields_' must be a sequence of pairs"); - return -1; - } - - stgdict = PyType_stgdict(type); - if (!stgdict) - return -1; - /* If this structure/union is already marked final we cannot assign - _fields_ anymore. */ - - if (stgdict->flags & DICTFLAG_FINAL) {/* is final ? */ - PyErr_SetString(PyExc_AttributeError, - "_fields_ is final"); - return -1; - } - - if (stgdict->format) { - PyMem_Free(stgdict->format); - stgdict->format = NULL; - } - - if (stgdict->ffi_type_pointer.elements) - PyMem_Free(stgdict->ffi_type_pointer.elements); - - basedict = PyType_stgdict((PyObject *)((PyTypeObject *)type)->tp_base); - if (basedict && !use_broken_old_ctypes_semantics) { - size = offset = basedict->size; - align = basedict->align; - union_size = 0; - total_align = align ? align : 1; - stgdict->ffi_type_pointer.type = FFI_TYPE_STRUCT; - stgdict->ffi_type_pointer.elements = PyMem_Malloc(sizeof(ffi_type *) * (basedict->length + len + 1)); - if (stgdict->ffi_type_pointer.elements == NULL) { - PyErr_NoMemory(); - return -1; - } - memset(stgdict->ffi_type_pointer.elements, 0, - sizeof(ffi_type *) * (basedict->length + len + 1)); - memcpy(stgdict->ffi_type_pointer.elements, - basedict->ffi_type_pointer.elements, - sizeof(ffi_type *) * (basedict->length)); - ffi_ofs = basedict->length; - } else { - offset = 0; - size = 0; - align = 0; - union_size = 0; - total_align = 1; - stgdict->ffi_type_pointer.type = FFI_TYPE_STRUCT; - stgdict->ffi_type_pointer.elements = PyMem_Malloc(sizeof(ffi_type *) * (len + 1)); - if (stgdict->ffi_type_pointer.elements == NULL) { - PyErr_NoMemory(); - return -1; - } - memset(stgdict->ffi_type_pointer.elements, 0, - sizeof(ffi_type *) * (len + 1)); - ffi_ofs = 0; - } - - assert(stgdict->format == NULL); - if (isStruct && !isPacked) { - stgdict->format = _ctypes_alloc_format_string(NULL, "T{"); - } else { - /* PEP3118 doesn't support union, or packed structures (well, - only standard packing, but we dont support the pep for - that). Use 'B' for bytes. */ - stgdict->format = _ctypes_alloc_format_string(NULL, "B"); - } + isPacked = PyObject_GetAttrString(type, "_pack_"); + if (isPacked) { + pack = PyLong_AsLong(isPacked); + if (pack < 0 || PyErr_Occurred()) { + Py_XDECREF(isPacked); + PyErr_SetString(PyExc_ValueError, + "_pack_ must be a non-negative integer"); + return -1; + } + Py_DECREF(isPacked); + } else + PyErr_Clear(); + + len = PySequence_Length(fields); + if (len == -1) { + PyErr_SetString(PyExc_TypeError, + "'_fields_' must be a sequence of pairs"); + return -1; + } + + stgdict = PyType_stgdict(type); + if (!stgdict) + return -1; + /* If this structure/union is already marked final we cannot assign + _fields_ anymore. */ + + if (stgdict->flags & DICTFLAG_FINAL) {/* is final ? */ + PyErr_SetString(PyExc_AttributeError, + "_fields_ is final"); + return -1; + } + + if (stgdict->format) { + PyMem_Free(stgdict->format); + stgdict->format = NULL; + } + + if (stgdict->ffi_type_pointer.elements) + PyMem_Free(stgdict->ffi_type_pointer.elements); + + basedict = PyType_stgdict((PyObject *)((PyTypeObject *)type)->tp_base); + if (basedict && !use_broken_old_ctypes_semantics) { + size = offset = basedict->size; + align = basedict->align; + union_size = 0; + total_align = align ? align : 1; + stgdict->ffi_type_pointer.type = FFI_TYPE_STRUCT; + stgdict->ffi_type_pointer.elements = PyMem_Malloc(sizeof(ffi_type *) * (basedict->length + len + 1)); + if (stgdict->ffi_type_pointer.elements == NULL) { + PyErr_NoMemory(); + return -1; + } + memset(stgdict->ffi_type_pointer.elements, 0, + sizeof(ffi_type *) * (basedict->length + len + 1)); + memcpy(stgdict->ffi_type_pointer.elements, + basedict->ffi_type_pointer.elements, + sizeof(ffi_type *) * (basedict->length)); + ffi_ofs = basedict->length; + } else { + offset = 0; + size = 0; + align = 0; + union_size = 0; + total_align = 1; + stgdict->ffi_type_pointer.type = FFI_TYPE_STRUCT; + stgdict->ffi_type_pointer.elements = PyMem_Malloc(sizeof(ffi_type *) * (len + 1)); + if (stgdict->ffi_type_pointer.elements == NULL) { + PyErr_NoMemory(); + return -1; + } + memset(stgdict->ffi_type_pointer.elements, 0, + sizeof(ffi_type *) * (len + 1)); + ffi_ofs = 0; + } + + assert(stgdict->format == NULL); + if (isStruct && !isPacked) { + stgdict->format = _ctypes_alloc_format_string(NULL, "T{"); + } else { + /* PEP3118 doesn't support union, or packed structures (well, + only standard packing, but we dont support the pep for + that). Use 'B' for bytes. */ + stgdict->format = _ctypes_alloc_format_string(NULL, "B"); + } #define realdict ((PyObject *)&stgdict->dict) - for (i = 0; i < len; ++i) { - PyObject *name = NULL, *desc = NULL; - PyObject *pair = PySequence_GetItem(fields, i); - PyObject *prop; - StgDictObject *dict; - int bitsize = 0; - - if (!pair || !PyArg_ParseTuple(pair, "OO|i", &name, &desc, &bitsize)) { - PyErr_SetString(PyExc_AttributeError, - "'_fields_' must be a sequence of pairs"); - Py_XDECREF(pair); - return -1; - } - dict = PyType_stgdict(desc); - if (dict == NULL) { - Py_DECREF(pair); - PyErr_Format(PyExc_TypeError, - "second item in _fields_ tuple (index %zd) must be a C type", - i); - return -1; - } - stgdict->ffi_type_pointer.elements[ffi_ofs + i] = &dict->ffi_type_pointer; - if (dict->flags & (TYPEFLAG_ISPOINTER | TYPEFLAG_HASPOINTER)) - stgdict->flags |= TYPEFLAG_HASPOINTER; - dict->flags |= DICTFLAG_FINAL; /* mark field type final */ - if (PyTuple_Size(pair) == 3) { /* bits specified */ - switch(dict->ffi_type_pointer.type) { - case FFI_TYPE_UINT8: - case FFI_TYPE_UINT16: - case FFI_TYPE_UINT32: - case FFI_TYPE_SINT64: - case FFI_TYPE_UINT64: - break; - - case FFI_TYPE_SINT8: - case FFI_TYPE_SINT16: - case FFI_TYPE_SINT32: - if (dict->getfunc != _ctypes_get_fielddesc("c")->getfunc + for (i = 0; i < len; ++i) { + PyObject *name = NULL, *desc = NULL; + PyObject *pair = PySequence_GetItem(fields, i); + PyObject *prop; + StgDictObject *dict; + int bitsize = 0; + + if (!pair || !PyArg_ParseTuple(pair, "OO|i", &name, &desc, &bitsize)) { + PyErr_SetString(PyExc_AttributeError, + "'_fields_' must be a sequence of pairs"); + Py_XDECREF(pair); + return -1; + } + dict = PyType_stgdict(desc); + if (dict == NULL) { + Py_DECREF(pair); + PyErr_Format(PyExc_TypeError, + "second item in _fields_ tuple (index %zd) must be a C type", + i); + return -1; + } + stgdict->ffi_type_pointer.elements[ffi_ofs + i] = &dict->ffi_type_pointer; + if (dict->flags & (TYPEFLAG_ISPOINTER | TYPEFLAG_HASPOINTER)) + stgdict->flags |= TYPEFLAG_HASPOINTER; + dict->flags |= DICTFLAG_FINAL; /* mark field type final */ + if (PyTuple_Size(pair) == 3) { /* bits specified */ + switch(dict->ffi_type_pointer.type) { + case FFI_TYPE_UINT8: + case FFI_TYPE_UINT16: + case FFI_TYPE_UINT32: + case FFI_TYPE_SINT64: + case FFI_TYPE_UINT64: + break; + + case FFI_TYPE_SINT8: + case FFI_TYPE_SINT16: + case FFI_TYPE_SINT32: + if (dict->getfunc != _ctypes_get_fielddesc("c")->getfunc #ifdef CTYPES_UNICODE - && dict->getfunc != _ctypes_get_fielddesc("u")->getfunc + && dict->getfunc != _ctypes_get_fielddesc("u")->getfunc #endif - ) - break; - /* else fall through */ - default: - PyErr_Format(PyExc_TypeError, - "bit fields not allowed for type %s", - ((PyTypeObject *)desc)->tp_name); - Py_DECREF(pair); - return -1; - } - if (bitsize <= 0 || bitsize > dict->size * 8) { - PyErr_SetString(PyExc_ValueError, - "number of bits invalid for bit field"); - Py_DECREF(pair); - return -1; - } - } else - bitsize = 0; - if (isStruct && !isPacked) { - char *fieldfmt = dict->format ? dict->format : "B"; - char *fieldname = _PyUnicode_AsString(name); - char *ptr; - Py_ssize_t len = strlen(fieldname) + strlen(fieldfmt); - char *buf = alloca(len + 2 + 1); - - sprintf(buf, "%s:%s:", fieldfmt, fieldname); - - ptr = stgdict->format; - stgdict->format = _ctypes_alloc_format_string(stgdict->format, buf); - PyMem_Free(ptr); - - if (stgdict->format == NULL) { - Py_DECREF(pair); - return -1; - } - } - if (isStruct) { - prop = PyCField_FromDesc(desc, i, - &field_size, bitsize, &bitofs, - &size, &offset, &align, - pack, big_endian); - } else /* union */ { - size = 0; - offset = 0; - align = 0; - prop = PyCField_FromDesc(desc, i, - &field_size, bitsize, &bitofs, - &size, &offset, &align, - pack, big_endian); - union_size = max(size, union_size); - } - total_align = max(align, total_align); - - if (!prop) { - Py_DECREF(pair); - return -1; - } - if (-1 == PyObject_SetAttr(type, name, prop)) { - Py_DECREF(prop); - Py_DECREF(pair); - return -1; - } - Py_DECREF(pair); - Py_DECREF(prop); - } + ) + break; + /* else fall through */ + default: + PyErr_Format(PyExc_TypeError, + "bit fields not allowed for type %s", + ((PyTypeObject *)desc)->tp_name); + Py_DECREF(pair); + return -1; + } + if (bitsize <= 0 || bitsize > dict->size * 8) { + PyErr_SetString(PyExc_ValueError, + "number of bits invalid for bit field"); + Py_DECREF(pair); + return -1; + } + } else + bitsize = 0; + if (isStruct && !isPacked) { + char *fieldfmt = dict->format ? dict->format : "B"; + char *fieldname = _PyUnicode_AsString(name); + char *ptr; + Py_ssize_t len = strlen(fieldname) + strlen(fieldfmt); + char *buf = alloca(len + 2 + 1); + + sprintf(buf, "%s:%s:", fieldfmt, fieldname); + + ptr = stgdict->format; + stgdict->format = _ctypes_alloc_format_string(stgdict->format, buf); + PyMem_Free(ptr); + + if (stgdict->format == NULL) { + Py_DECREF(pair); + return -1; + } + } + if (isStruct) { + prop = PyCField_FromDesc(desc, i, + &field_size, bitsize, &bitofs, + &size, &offset, &align, + pack, big_endian); + } else /* union */ { + size = 0; + offset = 0; + align = 0; + prop = PyCField_FromDesc(desc, i, + &field_size, bitsize, &bitofs, + &size, &offset, &align, + pack, big_endian); + union_size = max(size, union_size); + } + total_align = max(align, total_align); + + if (!prop) { + Py_DECREF(pair); + return -1; + } + if (-1 == PyObject_SetAttr(type, name, prop)) { + Py_DECREF(prop); + Py_DECREF(pair); + return -1; + } + Py_DECREF(pair); + Py_DECREF(prop); + } #undef realdict - if (isStruct && !isPacked) { - char *ptr = stgdict->format; - stgdict->format = _ctypes_alloc_format_string(stgdict->format, "}"); - PyMem_Free(ptr); - if (stgdict->format == NULL) - return -1; - } - - if (!isStruct) - size = union_size; - - /* Adjust the size according to the alignment requirements */ - size = ((size + total_align - 1) / total_align) * total_align; - - stgdict->ffi_type_pointer.alignment = Py_SAFE_DOWNCAST(total_align, - Py_ssize_t, - unsigned short); - stgdict->ffi_type_pointer.size = size; - - stgdict->size = size; - stgdict->align = total_align; - stgdict->length = len; /* ADD ffi_ofs? */ - - /* We did check that this flag was NOT set above, it must not - have been set until now. */ - if (stgdict->flags & DICTFLAG_FINAL) { - PyErr_SetString(PyExc_AttributeError, - "Structure or union cannot contain itself"); - return -1; - } - stgdict->flags |= DICTFLAG_FINAL; + if (isStruct && !isPacked) { + char *ptr = stgdict->format; + stgdict->format = _ctypes_alloc_format_string(stgdict->format, "}"); + PyMem_Free(ptr); + if (stgdict->format == NULL) + return -1; + } + + if (!isStruct) + size = union_size; + + /* Adjust the size according to the alignment requirements */ + size = ((size + total_align - 1) / total_align) * total_align; + + stgdict->ffi_type_pointer.alignment = Py_SAFE_DOWNCAST(total_align, + Py_ssize_t, + unsigned short); + stgdict->ffi_type_pointer.size = size; + + stgdict->size = size; + stgdict->align = total_align; + stgdict->length = len; /* ADD ffi_ofs? */ + + /* We did check that this flag was NOT set above, it must not + have been set until now. */ + if (stgdict->flags & DICTFLAG_FINAL) { + PyErr_SetString(PyExc_AttributeError, + "Structure or union cannot contain itself"); + return -1; + } + stgdict->flags |= DICTFLAG_FINAL; - return MakeAnonFields(type); + return MakeAnonFields(type); } Modified: python/branches/py3k-jit/Modules/_curses_panel.c ============================================================================== --- python/branches/py3k-jit/Modules/_curses_panel.c (original) +++ python/branches/py3k-jit/Modules/_curses_panel.c Mon May 10 23:55:43 2010 @@ -22,7 +22,7 @@ /* Utility Functions */ /* - * Check the return code from a curses function and return None + * Check the return code from a curses function and return None * or raise an exception as appropriate. */ @@ -30,15 +30,15 @@ PyCursesCheckERR(int code, char *fname) { if (code != ERR) { - Py_INCREF(Py_None); - return Py_None; + Py_INCREF(Py_None); + return Py_None; } else { - if (fname == NULL) { - PyErr_SetString(PyCursesError, catchall_ERR); - } else { - PyErr_Format(PyCursesError, "%s() returned ERR", fname); - } - return NULL; + if (fname == NULL) { + PyErr_SetString(PyCursesError, catchall_ERR); + } else { + PyErr_Format(PyCursesError, "%s() returned ERR", fname); + } + return NULL; } } @@ -51,12 +51,12 @@ typedef struct { PyObject_HEAD PANEL *pan; - PyCursesWindowObject *wo; /* for reference counts */ + PyCursesWindowObject *wo; /* for reference counts */ } PyCursesPanelObject; PyTypeObject PyCursesPanel_Type; -#define PyCursesPanel_Check(v) (Py_TYPE(v) == &PyCursesPanel_Type) +#define PyCursesPanel_Check(v) (Py_TYPE(v) == &PyCursesPanel_Type) /* Some helper functions. The problem is that there's always a window associated with a panel. To ensure that Python's GC doesn't pull @@ -88,10 +88,10 @@ insert_lop(PyCursesPanelObject *po) { list_of_panels *new; - + if ((new = (list_of_panels *)malloc(sizeof(list_of_panels))) == NULL) { - PyErr_NoMemory(); - return -1; + PyErr_NoMemory(); + return -1; } new->po = po; new->next = lop; @@ -107,17 +107,17 @@ temp = lop; if (temp->po == po) { - lop = temp->next; - free(temp); - return; + lop = temp->next; + free(temp); + return; } while (temp->next == NULL || temp->next->po != po) { - if (temp->next == NULL) { - PyErr_SetString(PyExc_RuntimeError, - "remove_lop: can't find Panel Object"); - return; - } - temp = temp->next; + if (temp->next == NULL) { + PyErr_SetString(PyExc_RuntimeError, + "remove_lop: can't find Panel Object"); + return; + } + temp = temp->next; } n = temp->next->next; free(temp->next); @@ -131,7 +131,7 @@ { list_of_panels *temp; for (temp = lop; temp->po->pan != pan; temp = temp->next) - if (temp->next == NULL) return NULL; /* not found!? */ + if (temp->next == NULL) return NULL; /* not found!? */ return temp->po; } @@ -179,9 +179,9 @@ if (po == NULL) return NULL; po->pan = pan; if (insert_lop(po) < 0) { - po->wo = NULL; - Py_DECREF(po); - return NULL; + po->wo = NULL; + Py_DECREF(po); + return NULL; } po->wo = wo; Py_INCREF(wo); @@ -193,8 +193,8 @@ { (void)del_panel(po->pan); if (po->wo != NULL) { - Py_DECREF(po->wo); - remove_lop(po); + Py_DECREF(po->wo); + remove_lop(po); } PyObject_DEL(po); } @@ -206,19 +206,19 @@ { PANEL *pan; PyCursesPanelObject *po; - + pan = panel_above(self->pan); - if (pan == NULL) { /* valid output, it means the calling panel - is on top of the stack */ - Py_INCREF(Py_None); - return Py_None; + if (pan == NULL) { /* valid output, it means the calling panel + is on top of the stack */ + Py_INCREF(Py_None); + return Py_None; } po = find_po(pan); if (po == NULL) { - PyErr_SetString(PyExc_RuntimeError, - "panel_above: can't find Panel Object"); - return NULL; + PyErr_SetString(PyExc_RuntimeError, + "panel_above: can't find Panel Object"); + return NULL; } Py_INCREF(po); return (PyObject *)po; @@ -231,19 +231,19 @@ { PANEL *pan; PyCursesPanelObject *po; - + pan = panel_below(self->pan); - - if (pan == NULL) { /* valid output, it means the calling panel - is on the bottom of the stack */ - Py_INCREF(Py_None); - return Py_None; + + if (pan == NULL) { /* valid output, it means the calling panel + is on the bottom of the stack */ + Py_INCREF(Py_None); + return Py_None; } po = find_po(pan); if (po == NULL) { - PyErr_SetString(PyExc_RuntimeError, - "panel_below: can't find Panel Object"); - return NULL; + PyErr_SetString(PyExc_RuntimeError, + "panel_below: can't find Panel Object"); + return NULL; } Py_INCREF(po); return (PyObject *)po; @@ -262,26 +262,26 @@ PyCursesPanelObject *po; PyCursesWindowObject *temp; int rtn; - + if (PyTuple_Size(args) != 1) { - PyErr_SetString(PyExc_TypeError, "replace requires one argument"); - return NULL; + PyErr_SetString(PyExc_TypeError, "replace requires one argument"); + return NULL; } if (!PyArg_ParseTuple(args, "O!;window object", - &PyCursesWindow_Type, &temp)) - return NULL; + &PyCursesWindow_Type, &temp)) + return NULL; po = find_po(self->pan); if (po == NULL) { - PyErr_SetString(PyExc_RuntimeError, - "replace_panel: can't find Panel Object"); - return NULL; + PyErr_SetString(PyExc_RuntimeError, + "replace_panel: can't find Panel Object"); + return NULL; } rtn = replace_panel(self->pan, temp->win); if (rtn == ERR) { - PyErr_SetString(PyCursesError, "replace_panel() returned ERR"); - return NULL; + PyErr_SetString(PyCursesError, "replace_panel() returned ERR"); + return NULL; } Py_DECREF(po->wo); po->wo = temp; @@ -302,11 +302,11 @@ PyCursesPanel_userptr(PyCursesPanelObject *self) { PyObject *obj; - PyCursesInitialised; + PyCursesInitialised; obj = (PyObject *) panel_userptr(self->pan); if (obj == NULL) { - PyErr_SetString(PyCursesError, "no userptr set"); - return NULL; + PyErr_SetString(PyCursesError, "no userptr set"); + return NULL; } Py_INCREF(obj); @@ -329,40 +329,40 @@ {"top", (PyCFunction)PyCursesPanel_top_panel, METH_NOARGS}, {"userptr", (PyCFunction)PyCursesPanel_userptr, METH_NOARGS}, {"window", (PyCFunction)PyCursesPanel_window, METH_NOARGS}, - {NULL, NULL} /* sentinel */ + {NULL, NULL} /* sentinel */ }; /* -------------------------------------------------------*/ PyTypeObject PyCursesPanel_Type = { PyVarObject_HEAD_INIT(NULL, 0) - "_curses_panel.curses panel", /*tp_name*/ - sizeof(PyCursesPanelObject), /*tp_basicsize*/ - 0, /*tp_itemsize*/ + "_curses_panel.curses panel", /*tp_name*/ + sizeof(PyCursesPanelObject), /*tp_basicsize*/ + 0, /*tp_itemsize*/ /* methods */ (destructor)PyCursesPanel_Dealloc, /*tp_dealloc*/ - 0, /*tp_print*/ - 0, /*tp_getattr*/ - 0, /*tp_setattr*/ - 0, /*tp_reserved*/ - 0, /*tp_repr*/ - 0, /*tp_as_number*/ - 0, /*tp_as_sequence*/ - 0, /*tp_as_mapping*/ - 0, /*tp_hash*/ - 0, /*tp_call*/ - 0, /*tp_str*/ - 0, /*tp_getattro*/ - 0, /*tp_setattro*/ - 0, /*tp_as_buffer*/ + 0, /*tp_print*/ + 0, /*tp_getattr*/ + 0, /*tp_setattr*/ + 0, /*tp_reserved*/ + 0, /*tp_repr*/ + 0, /*tp_as_number*/ + 0, /*tp_as_sequence*/ + 0, /*tp_as_mapping*/ + 0, /*tp_hash*/ + 0, /*tp_call*/ + 0, /*tp_str*/ + 0, /*tp_getattro*/ + 0, /*tp_setattro*/ + 0, /*tp_as_buffer*/ Py_TPFLAGS_DEFAULT, /*tp_flags*/ - 0, /*tp_doc*/ - 0, /*tp_traverse*/ - 0, /*tp_clear*/ - 0, /*tp_richcompare*/ - 0, /*tp_weaklistoffset*/ - 0, /*tp_iter*/ - 0, /*tp_iternext*/ + 0, /*tp_doc*/ + 0, /*tp_traverse*/ + 0, /*tp_clear*/ + 0, /*tp_richcompare*/ + 0, /*tp_weaklistoffset*/ + 0, /*tp_iter*/ + 0, /*tp_iternext*/ PyCursesPanel_Methods, /*tp_methods*/ }; @@ -380,16 +380,16 @@ pan = panel_above(NULL); - if (pan == NULL) { /* valid output, it means - there's no panel at all */ - Py_INCREF(Py_None); - return Py_None; + if (pan == NULL) { /* valid output, it means + there's no panel at all */ + Py_INCREF(Py_None); + return Py_None; } po = find_po(pan); if (po == NULL) { - PyErr_SetString(PyExc_RuntimeError, - "panel_above: can't find Panel Object"); - return NULL; + PyErr_SetString(PyExc_RuntimeError, + "panel_above: can't find Panel Object"); + return NULL; } Py_INCREF(po); return (PyObject *)po; @@ -405,8 +405,8 @@ return NULL; pan = new_panel(win->win); if (pan == NULL) { - PyErr_SetString(PyCursesError, catchall_NULL); - return NULL; + PyErr_SetString(PyCursesError, catchall_NULL); + return NULL; } return (PyObject *)PyCursesPanel_New(pan, win); } @@ -421,28 +421,28 @@ { PANEL *pan; PyCursesPanelObject *po; - + PyCursesInitialised; pan = panel_below(NULL); - if (pan == NULL) { /* valid output, it means - there's no panel at all */ - Py_INCREF(Py_None); - return Py_None; + if (pan == NULL) { /* valid output, it means + there's no panel at all */ + Py_INCREF(Py_None); + return Py_None; } po = find_po(pan); if (po == NULL) { - PyErr_SetString(PyExc_RuntimeError, - "panel_below: can't find Panel Object"); - return NULL; + PyErr_SetString(PyExc_RuntimeError, + "panel_below: can't find Panel Object"); + return NULL; } Py_INCREF(po); return (PyObject *)po; } static PyObject *PyCurses_update_panels(PyObject *self) -{ +{ PyCursesInitialised; update_panels(); Py_INCREF(Py_None); @@ -457,22 +457,22 @@ {"new_panel", (PyCFunction)PyCurses_new_panel, METH_VARARGS}, {"top_panel", (PyCFunction)PyCurses_top_panel, METH_NOARGS}, {"update_panels", (PyCFunction)PyCurses_update_panels, METH_NOARGS}, - {NULL, NULL} /* sentinel */ + {NULL, NULL} /* sentinel */ }; /* Initialization function for the module */ static struct PyModuleDef _curses_panelmodule = { - PyModuleDef_HEAD_INIT, - "_curses_panel", - NULL, - -1, - PyCurses_methods, - NULL, - NULL, - NULL, - NULL + PyModuleDef_HEAD_INIT, + "_curses_panel", + NULL, + -1, + PyCurses_methods, + NULL, + NULL, + NULL, + NULL }; PyMODINIT_FUNC @@ -489,7 +489,7 @@ /* Create the module and add the functions */ m = PyModule_Create(&_curses_panelmodule); if (m == NULL) - return NULL; + return NULL; d = PyModule_GetDict(m); /* For exception _curses_panel.error */ Modified: python/branches/py3k-jit/Modules/_dbmmodule.c ============================================================================== --- python/branches/py3k-jit/Modules/_dbmmodule.c (original) +++ python/branches/py3k-jit/Modules/_dbmmodule.c Mon May 10 23:55:43 2010 @@ -33,9 +33,9 @@ #endif typedef struct { - PyObject_HEAD - int di_size; /* -1 means recompute */ - DBM *di_dbm; + PyObject_HEAD + int di_size; /* -1 means recompute */ + DBM *di_dbm; } dbmobject; static PyTypeObject Dbmtype; @@ -50,18 +50,18 @@ static PyObject * newdbmobject(char *file, int flags, int mode) { - dbmobject *dp; + dbmobject *dp; - dp = PyObject_New(dbmobject, &Dbmtype); - if (dp == NULL) - return NULL; - dp->di_size = -1; - if ( (dp->di_dbm = dbm_open(file, flags, mode)) == 0 ) { - PyErr_SetFromErrno(DbmError); - Py_DECREF(dp); - return NULL; - } - return (PyObject *)dp; + dp = PyObject_New(dbmobject, &Dbmtype); + if (dp == NULL) + return NULL; + dp->di_size = -1; + if ( (dp->di_dbm = dbm_open(file, flags, mode)) == 0 ) { + PyErr_SetFromErrno(DbmError); + Py_DECREF(dp); + return NULL; + } + return (PyObject *)dp; } /* Methods */ @@ -69,294 +69,294 @@ static void dbm_dealloc(register dbmobject *dp) { - if ( dp->di_dbm ) - dbm_close(dp->di_dbm); - PyObject_Del(dp); + if ( dp->di_dbm ) + dbm_close(dp->di_dbm); + PyObject_Del(dp); } static Py_ssize_t dbm_length(dbmobject *dp) { - if (dp->di_dbm == NULL) { - PyErr_SetString(DbmError, "DBM object has already been closed"); - return -1; - } - if ( dp->di_size < 0 ) { - datum key; - int size; - - size = 0; - for ( key=dbm_firstkey(dp->di_dbm); key.dptr; - key = dbm_nextkey(dp->di_dbm)) - size++; - dp->di_size = size; - } - return dp->di_size; + if (dp->di_dbm == NULL) { + PyErr_SetString(DbmError, "DBM object has already been closed"); + return -1; + } + if ( dp->di_size < 0 ) { + datum key; + int size; + + size = 0; + for ( key=dbm_firstkey(dp->di_dbm); key.dptr; + key = dbm_nextkey(dp->di_dbm)) + size++; + dp->di_size = size; + } + return dp->di_size; } static PyObject * dbm_subscript(dbmobject *dp, register PyObject *key) { - datum drec, krec; - Py_ssize_t tmp_size; - - if (!PyArg_Parse(key, "s#", &krec.dptr, &tmp_size) ) - return NULL; - - krec.dsize = tmp_size; - check_dbmobject_open(dp); - drec = dbm_fetch(dp->di_dbm, krec); - if ( drec.dptr == 0 ) { - PyErr_SetObject(PyExc_KeyError, key); - return NULL; - } - if ( dbm_error(dp->di_dbm) ) { - dbm_clearerr(dp->di_dbm); - PyErr_SetString(DbmError, ""); - return NULL; - } - return PyBytes_FromStringAndSize(drec.dptr, drec.dsize); + datum drec, krec; + Py_ssize_t tmp_size; + + if (!PyArg_Parse(key, "s#", &krec.dptr, &tmp_size) ) + return NULL; + + krec.dsize = tmp_size; + check_dbmobject_open(dp); + drec = dbm_fetch(dp->di_dbm, krec); + if ( drec.dptr == 0 ) { + PyErr_SetObject(PyExc_KeyError, key); + return NULL; + } + if ( dbm_error(dp->di_dbm) ) { + dbm_clearerr(dp->di_dbm); + PyErr_SetString(DbmError, ""); + return NULL; + } + return PyBytes_FromStringAndSize(drec.dptr, drec.dsize); } static int dbm_ass_sub(dbmobject *dp, PyObject *v, PyObject *w) { - datum krec, drec; - Py_ssize_t tmp_size; - - if ( !PyArg_Parse(v, "s#", &krec.dptr, &tmp_size) ) { - PyErr_SetString(PyExc_TypeError, - "dbm mappings have bytes or string keys only"); - return -1; - } - krec.dsize = tmp_size; - if (dp->di_dbm == NULL) { - PyErr_SetString(DbmError, "DBM object has already been closed"); - return -1; + datum krec, drec; + Py_ssize_t tmp_size; + + if ( !PyArg_Parse(v, "s#", &krec.dptr, &tmp_size) ) { + PyErr_SetString(PyExc_TypeError, + "dbm mappings have bytes or string keys only"); + return -1; + } + krec.dsize = tmp_size; + if (dp->di_dbm == NULL) { + PyErr_SetString(DbmError, "DBM object has already been closed"); + return -1; + } + dp->di_size = -1; + if (w == NULL) { + if ( dbm_delete(dp->di_dbm, krec) < 0 ) { + dbm_clearerr(dp->di_dbm); + PyErr_SetObject(PyExc_KeyError, v); + return -1; + } + } else { + if ( !PyArg_Parse(w, "s#", &drec.dptr, &tmp_size) ) { + PyErr_SetString(PyExc_TypeError, + "dbm mappings have byte or string elements only"); + return -1; } - dp->di_size = -1; - if (w == NULL) { - if ( dbm_delete(dp->di_dbm, krec) < 0 ) { - dbm_clearerr(dp->di_dbm); - PyErr_SetObject(PyExc_KeyError, v); - return -1; - } - } else { - if ( !PyArg_Parse(w, "s#", &drec.dptr, &tmp_size) ) { - PyErr_SetString(PyExc_TypeError, - "dbm mappings have byte or string elements only"); - return -1; - } - drec.dsize = tmp_size; - if ( dbm_store(dp->di_dbm, krec, drec, DBM_REPLACE) < 0 ) { - dbm_clearerr(dp->di_dbm); - PyErr_SetString(DbmError, - "cannot add item to database"); - return -1; - } - } - if ( dbm_error(dp->di_dbm) ) { - dbm_clearerr(dp->di_dbm); - PyErr_SetString(DbmError, ""); - return -1; - } - return 0; + drec.dsize = tmp_size; + if ( dbm_store(dp->di_dbm, krec, drec, DBM_REPLACE) < 0 ) { + dbm_clearerr(dp->di_dbm); + PyErr_SetString(DbmError, + "cannot add item to database"); + return -1; + } + } + if ( dbm_error(dp->di_dbm) ) { + dbm_clearerr(dp->di_dbm); + PyErr_SetString(DbmError, ""); + return -1; + } + return 0; } static PyMappingMethods dbm_as_mapping = { - (lenfunc)dbm_length, /*mp_length*/ - (binaryfunc)dbm_subscript, /*mp_subscript*/ - (objobjargproc)dbm_ass_sub, /*mp_ass_subscript*/ + (lenfunc)dbm_length, /*mp_length*/ + (binaryfunc)dbm_subscript, /*mp_subscript*/ + (objobjargproc)dbm_ass_sub, /*mp_ass_subscript*/ }; static PyObject * dbm__close(register dbmobject *dp, PyObject *unused) { - if (dp->di_dbm) - dbm_close(dp->di_dbm); - dp->di_dbm = NULL; - Py_INCREF(Py_None); - return Py_None; + if (dp->di_dbm) + dbm_close(dp->di_dbm); + dp->di_dbm = NULL; + Py_INCREF(Py_None); + return Py_None; } static PyObject * dbm_keys(register dbmobject *dp, PyObject *unused) { - register PyObject *v, *item; - datum key; - int err; - - check_dbmobject_open(dp); - v = PyList_New(0); - if (v == NULL) - return NULL; - for (key = dbm_firstkey(dp->di_dbm); key.dptr; - key = dbm_nextkey(dp->di_dbm)) { - item = PyBytes_FromStringAndSize(key.dptr, key.dsize); - if (item == NULL) { - Py_DECREF(v); - return NULL; - } - err = PyList_Append(v, item); - Py_DECREF(item); - if (err != 0) { - Py_DECREF(v); - return NULL; - } - } - return v; + register PyObject *v, *item; + datum key; + int err; + + check_dbmobject_open(dp); + v = PyList_New(0); + if (v == NULL) + return NULL; + for (key = dbm_firstkey(dp->di_dbm); key.dptr; + key = dbm_nextkey(dp->di_dbm)) { + item = PyBytes_FromStringAndSize(key.dptr, key.dsize); + if (item == NULL) { + Py_DECREF(v); + return NULL; + } + err = PyList_Append(v, item); + Py_DECREF(item); + if (err != 0) { + Py_DECREF(v); + return NULL; + } + } + return v; } static int dbm_contains(PyObject *self, PyObject *arg) { - dbmobject *dp = (dbmobject *)self; - datum key, val; + dbmobject *dp = (dbmobject *)self; + datum key, val; - if ((dp)->di_dbm == NULL) { - PyErr_SetString(DbmError, - "DBM object has already been closed"); - return -1; - } - if (PyUnicode_Check(arg)) { - arg = _PyUnicode_AsDefaultEncodedString(arg, NULL); - if (arg == NULL) - return -1; - } - if (!PyBytes_Check(arg)) { - PyErr_Format(PyExc_TypeError, - "dbm key must be string, not %.100s", - arg->ob_type->tp_name); - return -1; - } - key.dptr = PyBytes_AS_STRING(arg); - key.dsize = PyBytes_GET_SIZE(arg); - val = dbm_fetch(dp->di_dbm, key); - return val.dptr != NULL; + if ((dp)->di_dbm == NULL) { + PyErr_SetString(DbmError, + "DBM object has already been closed"); + return -1; + } + if (PyUnicode_Check(arg)) { + arg = _PyUnicode_AsDefaultEncodedString(arg, NULL); + if (arg == NULL) + return -1; + } + if (!PyBytes_Check(arg)) { + PyErr_Format(PyExc_TypeError, + "dbm key must be string, not %.100s", + arg->ob_type->tp_name); + return -1; + } + key.dptr = PyBytes_AS_STRING(arg); + key.dsize = PyBytes_GET_SIZE(arg); + val = dbm_fetch(dp->di_dbm, key); + return val.dptr != NULL; } static PySequenceMethods dbm_as_sequence = { - 0, /* sq_length */ - 0, /* sq_concat */ - 0, /* sq_repeat */ - 0, /* sq_item */ - 0, /* sq_slice */ - 0, /* sq_ass_item */ - 0, /* sq_ass_slice */ - dbm_contains, /* sq_contains */ - 0, /* sq_inplace_concat */ - 0, /* sq_inplace_repeat */ + 0, /* sq_length */ + 0, /* sq_concat */ + 0, /* sq_repeat */ + 0, /* sq_item */ + 0, /* sq_slice */ + 0, /* sq_ass_item */ + 0, /* sq_ass_slice */ + dbm_contains, /* sq_contains */ + 0, /* sq_inplace_concat */ + 0, /* sq_inplace_repeat */ }; static PyObject * dbm_get(register dbmobject *dp, PyObject *args) { - datum key, val; - PyObject *defvalue = Py_None; - char *tmp_ptr; - Py_ssize_t tmp_size; - - if (!PyArg_ParseTuple(args, "s#|O:get", - &tmp_ptr, &tmp_size, &defvalue)) - return NULL; - key.dptr = tmp_ptr; - key.dsize = tmp_size; - check_dbmobject_open(dp); - val = dbm_fetch(dp->di_dbm, key); - if (val.dptr != NULL) - return PyBytes_FromStringAndSize(val.dptr, val.dsize); - else { - Py_INCREF(defvalue); - return defvalue; - } + datum key, val; + PyObject *defvalue = Py_None; + char *tmp_ptr; + Py_ssize_t tmp_size; + + if (!PyArg_ParseTuple(args, "s#|O:get", + &tmp_ptr, &tmp_size, &defvalue)) + return NULL; + key.dptr = tmp_ptr; + key.dsize = tmp_size; + check_dbmobject_open(dp); + val = dbm_fetch(dp->di_dbm, key); + if (val.dptr != NULL) + return PyBytes_FromStringAndSize(val.dptr, val.dsize); + else { + Py_INCREF(defvalue); + return defvalue; + } } static PyObject * dbm_setdefault(register dbmobject *dp, PyObject *args) { - datum key, val; - PyObject *defvalue = NULL; - char *tmp_ptr; - Py_ssize_t tmp_size; - - if (!PyArg_ParseTuple(args, "s#|O:setdefault", - &tmp_ptr, &tmp_size, &defvalue)) - return NULL; - key.dptr = tmp_ptr; - key.dsize = tmp_size; - check_dbmobject_open(dp); - val = dbm_fetch(dp->di_dbm, key); - if (val.dptr != NULL) - return PyBytes_FromStringAndSize(val.dptr, val.dsize); - if (defvalue == NULL) { - defvalue = PyBytes_FromStringAndSize(NULL, 0); - if (defvalue == NULL) - return NULL; - val.dptr = NULL; - val.dsize = 0; - } - else { - if ( !PyArg_Parse(defvalue, "s#", &val.dptr, &tmp_size) ) { - PyErr_SetString(PyExc_TypeError, - "dbm mappings have byte string elements only"); - return NULL; - } - val.dsize = tmp_size; - Py_INCREF(defvalue); - } - if (dbm_store(dp->di_dbm, key, val, DBM_INSERT) < 0) { - dbm_clearerr(dp->di_dbm); - PyErr_SetString(DbmError, "cannot add item to database"); - Py_DECREF(defvalue); - return NULL; - } - return defvalue; + datum key, val; + PyObject *defvalue = NULL; + char *tmp_ptr; + Py_ssize_t tmp_size; + + if (!PyArg_ParseTuple(args, "s#|O:setdefault", + &tmp_ptr, &tmp_size, &defvalue)) + return NULL; + key.dptr = tmp_ptr; + key.dsize = tmp_size; + check_dbmobject_open(dp); + val = dbm_fetch(dp->di_dbm, key); + if (val.dptr != NULL) + return PyBytes_FromStringAndSize(val.dptr, val.dsize); + if (defvalue == NULL) { + defvalue = PyBytes_FromStringAndSize(NULL, 0); + if (defvalue == NULL) + return NULL; + val.dptr = NULL; + val.dsize = 0; + } + else { + if ( !PyArg_Parse(defvalue, "s#", &val.dptr, &tmp_size) ) { + PyErr_SetString(PyExc_TypeError, + "dbm mappings have byte string elements only"); + return NULL; + } + val.dsize = tmp_size; + Py_INCREF(defvalue); + } + if (dbm_store(dp->di_dbm, key, val, DBM_INSERT) < 0) { + dbm_clearerr(dp->di_dbm); + PyErr_SetString(DbmError, "cannot add item to database"); + Py_DECREF(defvalue); + return NULL; + } + return defvalue; } static PyMethodDef dbm_methods[] = { - {"close", (PyCFunction)dbm__close, METH_NOARGS, - "close()\nClose the database."}, - {"keys", (PyCFunction)dbm_keys, METH_NOARGS, - "keys() -> list\nReturn a list of all keys in the database."}, - {"get", (PyCFunction)dbm_get, METH_VARARGS, - "get(key[, default]) -> value\n" - "Return the value for key if present, otherwise default."}, - {"setdefault", (PyCFunction)dbm_setdefault, METH_VARARGS, - "setdefault(key[, default]) -> value\n" - "Return the value for key if present, otherwise default. If key\n" - "is not in the database, it is inserted with default as the value."}, - {NULL, NULL} /* sentinel */ + {"close", (PyCFunction)dbm__close, METH_NOARGS, + "close()\nClose the database."}, + {"keys", (PyCFunction)dbm_keys, METH_NOARGS, + "keys() -> list\nReturn a list of all keys in the database."}, + {"get", (PyCFunction)dbm_get, METH_VARARGS, + "get(key[, default]) -> value\n" + "Return the value for key if present, otherwise default."}, + {"setdefault", (PyCFunction)dbm_setdefault, METH_VARARGS, + "setdefault(key[, default]) -> value\n" + "Return the value for key if present, otherwise default. If key\n" + "is not in the database, it is inserted with default as the value."}, + {NULL, NULL} /* sentinel */ }; static PyTypeObject Dbmtype = { - PyVarObject_HEAD_INIT(NULL, 0) - "_dbm.dbm", - sizeof(dbmobject), - 0, - (destructor)dbm_dealloc, /*tp_dealloc*/ - 0, /*tp_print*/ - 0, /*tp_getattr*/ - 0, /*tp_setattr*/ - 0, /*tp_reserved*/ - 0, /*tp_repr*/ - 0, /*tp_as_number*/ - &dbm_as_sequence, /*tp_as_sequence*/ - &dbm_as_mapping, /*tp_as_mapping*/ - 0, /*tp_hash*/ - 0, /*tp_call*/ - 0, /*tp_str*/ - 0, /*tp_getattro*/ - 0, /*tp_setattro*/ - 0, /*tp_as_buffer*/ - Py_TPFLAGS_DEFAULT, /*tp_flags*/ - 0, /*tp_doc*/ - 0, /*tp_traverse*/ - 0, /*tp_clear*/ - 0, /*tp_richcompare*/ - 0, /*tp_weaklistoffset*/ - 0, /*tp_iter*/ - 0, /*tp_iternext*/ - dbm_methods, /*tp_methods*/ + PyVarObject_HEAD_INIT(NULL, 0) + "_dbm.dbm", + sizeof(dbmobject), + 0, + (destructor)dbm_dealloc, /*tp_dealloc*/ + 0, /*tp_print*/ + 0, /*tp_getattr*/ + 0, /*tp_setattr*/ + 0, /*tp_reserved*/ + 0, /*tp_repr*/ + 0, /*tp_as_number*/ + &dbm_as_sequence, /*tp_as_sequence*/ + &dbm_as_mapping, /*tp_as_mapping*/ + 0, /*tp_hash*/ + 0, /*tp_call*/ + 0, /*tp_str*/ + 0, /*tp_getattro*/ + 0, /*tp_setattro*/ + 0, /*tp_as_buffer*/ + Py_TPFLAGS_DEFAULT, /*tp_flags*/ + 0, /*tp_doc*/ + 0, /*tp_traverse*/ + 0, /*tp_clear*/ + 0, /*tp_richcompare*/ + 0, /*tp_weaklistoffset*/ + 0, /*tp_iter*/ + 0, /*tp_iternext*/ + dbm_methods, /*tp_methods*/ }; /* ----------------------------------------------------------------- */ @@ -364,74 +364,74 @@ static PyObject * dbmopen(PyObject *self, PyObject *args) { - char *name; - char *flags = "r"; - int iflags; - int mode = 0666; - - if ( !PyArg_ParseTuple(args, "s|si:open", &name, &flags, &mode) ) - return NULL; - if ( strcmp(flags, "r") == 0 ) - iflags = O_RDONLY; - else if ( strcmp(flags, "w") == 0 ) - iflags = O_RDWR; - else if ( strcmp(flags, "rw") == 0 ) /* B/W compat */ - iflags = O_RDWR|O_CREAT; - else if ( strcmp(flags, "c") == 0 ) - iflags = O_RDWR|O_CREAT; - else if ( strcmp(flags, "n") == 0 ) - iflags = O_RDWR|O_CREAT|O_TRUNC; - else { - PyErr_SetString(DbmError, - "arg 2 to open should be 'r', 'w', 'c', or 'n'"); - return NULL; - } - return newdbmobject(name, iflags, mode); + char *name; + char *flags = "r"; + int iflags; + int mode = 0666; + + if ( !PyArg_ParseTuple(args, "s|si:open", &name, &flags, &mode) ) + return NULL; + if ( strcmp(flags, "r") == 0 ) + iflags = O_RDONLY; + else if ( strcmp(flags, "w") == 0 ) + iflags = O_RDWR; + else if ( strcmp(flags, "rw") == 0 ) /* B/W compat */ + iflags = O_RDWR|O_CREAT; + else if ( strcmp(flags, "c") == 0 ) + iflags = O_RDWR|O_CREAT; + else if ( strcmp(flags, "n") == 0 ) + iflags = O_RDWR|O_CREAT|O_TRUNC; + else { + PyErr_SetString(DbmError, + "arg 2 to open should be 'r', 'w', 'c', or 'n'"); + return NULL; + } + return newdbmobject(name, iflags, mode); } static PyMethodDef dbmmodule_methods[] = { - { "open", (PyCFunction)dbmopen, METH_VARARGS, - "open(path[, flag[, mode]]) -> mapping\n" - "Return a database object."}, - { 0, 0 }, + { "open", (PyCFunction)dbmopen, METH_VARARGS, + "open(path[, flag[, mode]]) -> mapping\n" + "Return a database object."}, + { 0, 0 }, }; static struct PyModuleDef _dbmmodule = { - PyModuleDef_HEAD_INIT, - "_dbm", - NULL, - -1, - dbmmodule_methods, - NULL, - NULL, - NULL, - NULL + PyModuleDef_HEAD_INIT, + "_dbm", + NULL, + -1, + dbmmodule_methods, + NULL, + NULL, + NULL, + NULL }; PyMODINIT_FUNC PyInit__dbm(void) { - PyObject *m, *d, *s; + PyObject *m, *d, *s; - if (PyType_Ready(&Dbmtype) < 0) - return NULL; - m = PyModule_Create(&_dbmmodule); - if (m == NULL) - return NULL; - d = PyModule_GetDict(m); - if (DbmError == NULL) - DbmError = PyErr_NewException("_dbm.error", - PyExc_IOError, NULL); - s = PyUnicode_FromString(which_dbm); - if (s != NULL) { - PyDict_SetItemString(d, "library", s); - Py_DECREF(s); - } - if (DbmError != NULL) - PyDict_SetItemString(d, "error", DbmError); - if (PyErr_Occurred()) { - Py_DECREF(m); - m = NULL; - } - return m; + if (PyType_Ready(&Dbmtype) < 0) + return NULL; + m = PyModule_Create(&_dbmmodule); + if (m == NULL) + return NULL; + d = PyModule_GetDict(m); + if (DbmError == NULL) + DbmError = PyErr_NewException("_dbm.error", + PyExc_IOError, NULL); + s = PyUnicode_FromString(which_dbm); + if (s != NULL) { + PyDict_SetItemString(d, "library", s); + Py_DECREF(s); + } + if (DbmError != NULL) + PyDict_SetItemString(d, "error", DbmError); + if (PyErr_Occurred()) { + Py_DECREF(m); + m = NULL; + } + return m; } Modified: python/branches/py3k-jit/Modules/_functoolsmodule.c ============================================================================== --- python/branches/py3k-jit/Modules/_functoolsmodule.c (original) +++ python/branches/py3k-jit/Modules/_functoolsmodule.c Mon May 10 23:55:43 2010 @@ -2,7 +2,7 @@ #include "Python.h" #include "structmember.h" -/* _functools module written and maintained +/* _functools module written and maintained by Hye-Shik Chang with adaptations by Raymond Hettinger Copyright (c) 2004, 2005, 2006 Python Software Foundation. @@ -12,12 +12,12 @@ /* partial object **********************************************************/ typedef struct { - PyObject_HEAD - PyObject *fn; - PyObject *args; - PyObject *kw; - PyObject *dict; - PyObject *weakreflist; /* List of weak references */ + PyObject_HEAD + PyObject *fn; + PyObject *args; + PyObject *kw; + PyObject *dict; + PyObject *weakreflist; /* List of weak references */ } partialobject; static PyTypeObject partial_type; @@ -25,175 +25,175 @@ static PyObject * partial_new(PyTypeObject *type, PyObject *args, PyObject *kw) { - PyObject *func; - partialobject *pto; + PyObject *func; + partialobject *pto; - if (PyTuple_GET_SIZE(args) < 1) { - PyErr_SetString(PyExc_TypeError, - "type 'partial' takes at least one argument"); - return NULL; - } - - func = PyTuple_GET_ITEM(args, 0); - if (!PyCallable_Check(func)) { - PyErr_SetString(PyExc_TypeError, - "the first argument must be callable"); - return NULL; - } - - /* create partialobject structure */ - pto = (partialobject *)type->tp_alloc(type, 0); - if (pto == NULL) - return NULL; - - pto->fn = func; - Py_INCREF(func); - pto->args = PyTuple_GetSlice(args, 1, PY_SSIZE_T_MAX); - if (pto->args == NULL) { - pto->kw = NULL; - Py_DECREF(pto); - return NULL; - } - if (kw != NULL) { - pto->kw = PyDict_Copy(kw); - if (pto->kw == NULL) { - Py_DECREF(pto); - return NULL; - } - } else { - pto->kw = Py_None; - Py_INCREF(Py_None); - } + if (PyTuple_GET_SIZE(args) < 1) { + PyErr_SetString(PyExc_TypeError, + "type 'partial' takes at least one argument"); + return NULL; + } + + func = PyTuple_GET_ITEM(args, 0); + if (!PyCallable_Check(func)) { + PyErr_SetString(PyExc_TypeError, + "the first argument must be callable"); + return NULL; + } + + /* create partialobject structure */ + pto = (partialobject *)type->tp_alloc(type, 0); + if (pto == NULL) + return NULL; + + pto->fn = func; + Py_INCREF(func); + pto->args = PyTuple_GetSlice(args, 1, PY_SSIZE_T_MAX); + if (pto->args == NULL) { + pto->kw = NULL; + Py_DECREF(pto); + return NULL; + } + if (kw != NULL) { + pto->kw = PyDict_Copy(kw); + if (pto->kw == NULL) { + Py_DECREF(pto); + return NULL; + } + } else { + pto->kw = Py_None; + Py_INCREF(Py_None); + } - pto->weakreflist = NULL; - pto->dict = NULL; + pto->weakreflist = NULL; + pto->dict = NULL; - return (PyObject *)pto; + return (PyObject *)pto; } static void partial_dealloc(partialobject *pto) { - PyObject_GC_UnTrack(pto); - if (pto->weakreflist != NULL) - PyObject_ClearWeakRefs((PyObject *) pto); - Py_XDECREF(pto->fn); - Py_XDECREF(pto->args); - Py_XDECREF(pto->kw); - Py_XDECREF(pto->dict); - Py_TYPE(pto)->tp_free(pto); + PyObject_GC_UnTrack(pto); + if (pto->weakreflist != NULL) + PyObject_ClearWeakRefs((PyObject *) pto); + Py_XDECREF(pto->fn); + Py_XDECREF(pto->args); + Py_XDECREF(pto->kw); + Py_XDECREF(pto->dict); + Py_TYPE(pto)->tp_free(pto); } static PyObject * partial_call(partialobject *pto, PyObject *args, PyObject *kw) { - PyObject *ret; - PyObject *argappl = NULL, *kwappl = NULL; + PyObject *ret; + PyObject *argappl = NULL, *kwappl = NULL; - assert (PyCallable_Check(pto->fn)); - assert (PyTuple_Check(pto->args)); - assert (pto->kw == Py_None || PyDict_Check(pto->kw)); - - if (PyTuple_GET_SIZE(pto->args) == 0) { - argappl = args; - Py_INCREF(args); - } else if (PyTuple_GET_SIZE(args) == 0) { - argappl = pto->args; - Py_INCREF(pto->args); - } else { - argappl = PySequence_Concat(pto->args, args); - if (argappl == NULL) - return NULL; - } - - if (pto->kw == Py_None) { - kwappl = kw; - Py_XINCREF(kw); - } else { - kwappl = PyDict_Copy(pto->kw); - if (kwappl == NULL) { - Py_DECREF(argappl); - return NULL; - } - if (kw != NULL) { - if (PyDict_Merge(kwappl, kw, 1) != 0) { - Py_DECREF(argappl); - Py_DECREF(kwappl); - return NULL; - } - } - } - - ret = PyObject_Call(pto->fn, argappl, kwappl); - Py_DECREF(argappl); - Py_XDECREF(kwappl); - return ret; + assert (PyCallable_Check(pto->fn)); + assert (PyTuple_Check(pto->args)); + assert (pto->kw == Py_None || PyDict_Check(pto->kw)); + + if (PyTuple_GET_SIZE(pto->args) == 0) { + argappl = args; + Py_INCREF(args); + } else if (PyTuple_GET_SIZE(args) == 0) { + argappl = pto->args; + Py_INCREF(pto->args); + } else { + argappl = PySequence_Concat(pto->args, args); + if (argappl == NULL) + return NULL; + } + + if (pto->kw == Py_None) { + kwappl = kw; + Py_XINCREF(kw); + } else { + kwappl = PyDict_Copy(pto->kw); + if (kwappl == NULL) { + Py_DECREF(argappl); + return NULL; + } + if (kw != NULL) { + if (PyDict_Merge(kwappl, kw, 1) != 0) { + Py_DECREF(argappl); + Py_DECREF(kwappl); + return NULL; + } + } + } + + ret = PyObject_Call(pto->fn, argappl, kwappl); + Py_DECREF(argappl); + Py_XDECREF(kwappl); + return ret; } static int partial_traverse(partialobject *pto, visitproc visit, void *arg) { - Py_VISIT(pto->fn); - Py_VISIT(pto->args); - Py_VISIT(pto->kw); - Py_VISIT(pto->dict); - return 0; + Py_VISIT(pto->fn); + Py_VISIT(pto->args); + Py_VISIT(pto->kw); + Py_VISIT(pto->dict); + return 0; } PyDoc_STRVAR(partial_doc, "partial(func, *args, **keywords) - new function with partial application\n\ - of the given arguments and keywords.\n"); + of the given arguments and keywords.\n"); #define OFF(x) offsetof(partialobject, x) static PyMemberDef partial_memberlist[] = { - {"func", T_OBJECT, OFF(fn), READONLY, - "function object to use in future partial calls"}, - {"args", T_OBJECT, OFF(args), READONLY, - "tuple of arguments to future partial calls"}, - {"keywords", T_OBJECT, OFF(kw), READONLY, - "dictionary of keyword arguments to future partial calls"}, - {NULL} /* Sentinel */ + {"func", T_OBJECT, OFF(fn), READONLY, + "function object to use in future partial calls"}, + {"args", T_OBJECT, OFF(args), READONLY, + "tuple of arguments to future partial calls"}, + {"keywords", T_OBJECT, OFF(kw), READONLY, + "dictionary of keyword arguments to future partial calls"}, + {NULL} /* Sentinel */ }; static PyObject * partial_get_dict(partialobject *pto) { - if (pto->dict == NULL) { - pto->dict = PyDict_New(); - if (pto->dict == NULL) - return NULL; - } - Py_INCREF(pto->dict); - return pto->dict; + if (pto->dict == NULL) { + pto->dict = PyDict_New(); + if (pto->dict == NULL) + return NULL; + } + Py_INCREF(pto->dict); + return pto->dict; } static int partial_set_dict(partialobject *pto, PyObject *value) { - PyObject *tmp; + PyObject *tmp; - /* It is illegal to del p.__dict__ */ - if (value == NULL) { - PyErr_SetString(PyExc_TypeError, - "a partial object's dictionary may not be deleted"); - return -1; - } - /* Can only set __dict__ to a dictionary */ - if (!PyDict_Check(value)) { - PyErr_SetString(PyExc_TypeError, - "setting partial object's dictionary to a non-dict"); - return -1; - } - tmp = pto->dict; - Py_INCREF(value); - pto->dict = value; - Py_XDECREF(tmp); - return 0; + /* It is illegal to del p.__dict__ */ + if (value == NULL) { + PyErr_SetString(PyExc_TypeError, + "a partial object's dictionary may not be deleted"); + return -1; + } + /* Can only set __dict__ to a dictionary */ + if (!PyDict_Check(value)) { + PyErr_SetString(PyExc_TypeError, + "setting partial object's dictionary to a non-dict"); + return -1; + } + tmp = pto->dict; + Py_INCREF(value); + pto->dict = value; + Py_XDECREF(tmp); + return 0; } static PyGetSetDef partial_getsetlist[] = { - {"__dict__", (getter)partial_get_dict, (setter)partial_set_dict}, - {NULL} /* Sentinel */ + {"__dict__", (getter)partial_get_dict, (setter)partial_set_dict}, + {NULL} /* Sentinel */ }; /* Pickle strategy: @@ -206,85 +206,85 @@ static PyObject * partial_reduce(partialobject *pto, PyObject *unused) { - return Py_BuildValue("O(O)(OOOO)", Py_TYPE(pto), pto->fn, pto->fn, - pto->args, pto->kw, - pto->dict ? pto->dict : Py_None); + return Py_BuildValue("O(O)(OOOO)", Py_TYPE(pto), pto->fn, pto->fn, + pto->args, pto->kw, + pto->dict ? pto->dict : Py_None); } static PyObject * partial_setstate(partialobject *pto, PyObject *args) { - PyObject *fn, *fnargs, *kw, *dict; - if (!PyArg_ParseTuple(args, "(OOOO):__setstate__", - &fn, &fnargs, &kw, &dict)) - return NULL; - Py_XDECREF(pto->fn); - Py_XDECREF(pto->args); - Py_XDECREF(pto->kw); - Py_XDECREF(pto->dict); - pto->fn = fn; - pto->args = fnargs; - pto->kw = kw; - if (dict != Py_None) { - pto->dict = dict; - Py_INCREF(dict); - } else { - pto->dict = NULL; - } - Py_INCREF(fn); - Py_INCREF(fnargs); - Py_INCREF(kw); - Py_RETURN_NONE; + PyObject *fn, *fnargs, *kw, *dict; + if (!PyArg_ParseTuple(args, "(OOOO):__setstate__", + &fn, &fnargs, &kw, &dict)) + return NULL; + Py_XDECREF(pto->fn); + Py_XDECREF(pto->args); + Py_XDECREF(pto->kw); + Py_XDECREF(pto->dict); + pto->fn = fn; + pto->args = fnargs; + pto->kw = kw; + if (dict != Py_None) { + pto->dict = dict; + Py_INCREF(dict); + } else { + pto->dict = NULL; + } + Py_INCREF(fn); + Py_INCREF(fnargs); + Py_INCREF(kw); + Py_RETURN_NONE; } static PyMethodDef partial_methods[] = { - {"__reduce__", (PyCFunction)partial_reduce, METH_NOARGS}, - {"__setstate__", (PyCFunction)partial_setstate, METH_VARARGS}, - {NULL, NULL} /* sentinel */ + {"__reduce__", (PyCFunction)partial_reduce, METH_NOARGS}, + {"__setstate__", (PyCFunction)partial_setstate, METH_VARARGS}, + {NULL, NULL} /* sentinel */ }; static PyTypeObject partial_type = { - PyVarObject_HEAD_INIT(NULL, 0) - "functools.partial", /* tp_name */ - sizeof(partialobject), /* tp_basicsize */ - 0, /* tp_itemsize */ - /* methods */ - (destructor)partial_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 */ - (ternaryfunc)partial_call, /* tp_call */ - 0, /* tp_str */ - PyObject_GenericGetAttr, /* tp_getattro */ - PyObject_GenericSetAttr, /* tp_setattro */ - 0, /* tp_as_buffer */ - Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC | - Py_TPFLAGS_BASETYPE, /* tp_flags */ - partial_doc, /* tp_doc */ - (traverseproc)partial_traverse, /* tp_traverse */ - 0, /* tp_clear */ - 0, /* tp_richcompare */ - offsetof(partialobject, weakreflist), /* tp_weaklistoffset */ - 0, /* tp_iter */ - 0, /* tp_iternext */ - partial_methods, /* tp_methods */ - partial_memberlist, /* tp_members */ - partial_getsetlist, /* tp_getset */ - 0, /* tp_base */ - 0, /* tp_dict */ - 0, /* tp_descr_get */ - 0, /* tp_descr_set */ - offsetof(partialobject, dict), /* tp_dictoffset */ - 0, /* tp_init */ - 0, /* tp_alloc */ - partial_new, /* tp_new */ - PyObject_GC_Del, /* tp_free */ + PyVarObject_HEAD_INIT(NULL, 0) + "functools.partial", /* tp_name */ + sizeof(partialobject), /* tp_basicsize */ + 0, /* tp_itemsize */ + /* methods */ + (destructor)partial_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 */ + (ternaryfunc)partial_call, /* tp_call */ + 0, /* tp_str */ + PyObject_GenericGetAttr, /* tp_getattro */ + PyObject_GenericSetAttr, /* tp_setattro */ + 0, /* tp_as_buffer */ + Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC | + Py_TPFLAGS_BASETYPE, /* tp_flags */ + partial_doc, /* tp_doc */ + (traverseproc)partial_traverse, /* tp_traverse */ + 0, /* tp_clear */ + 0, /* tp_richcompare */ + offsetof(partialobject, weakreflist), /* tp_weaklistoffset */ + 0, /* tp_iter */ + 0, /* tp_iternext */ + partial_methods, /* tp_methods */ + partial_memberlist, /* tp_members */ + partial_getsetlist, /* tp_getset */ + 0, /* tp_base */ + 0, /* tp_dict */ + 0, /* tp_descr_get */ + 0, /* tp_descr_set */ + offsetof(partialobject, dict), /* tp_dictoffset */ + 0, /* tp_init */ + 0, /* tp_alloc */ + partial_new, /* tp_new */ + PyObject_GC_Del, /* tp_free */ }; @@ -293,64 +293,64 @@ static PyObject * functools_reduce(PyObject *self, PyObject *args) { - PyObject *seq, *func, *result = NULL, *it; + PyObject *seq, *func, *result = NULL, *it; - if (!PyArg_UnpackTuple(args, "reduce", 2, 3, &func, &seq, &result)) - return NULL; - if (result != NULL) - Py_INCREF(result); - - it = PyObject_GetIter(seq); - if (it == NULL) { - PyErr_SetString(PyExc_TypeError, - "reduce() arg 2 must support iteration"); - Py_XDECREF(result); - return NULL; - } - - if ((args = PyTuple_New(2)) == NULL) - goto Fail; - - for (;;) { - PyObject *op2; - - if (args->ob_refcnt > 1) { - Py_DECREF(args); - if ((args = PyTuple_New(2)) == NULL) - goto Fail; - } - - op2 = PyIter_Next(it); - if (op2 == NULL) { - if (PyErr_Occurred()) - goto Fail; - break; - } - - if (result == NULL) - result = op2; - else { - PyTuple_SetItem(args, 0, result); - PyTuple_SetItem(args, 1, op2); - if ((result = PyEval_CallObject(func, args)) == NULL) - goto Fail; - } - } - - Py_DECREF(args); - - if (result == NULL) - PyErr_SetString(PyExc_TypeError, - "reduce() of empty sequence with no initial value"); + if (!PyArg_UnpackTuple(args, "reduce", 2, 3, &func, &seq, &result)) + return NULL; + if (result != NULL) + Py_INCREF(result); + + it = PyObject_GetIter(seq); + if (it == NULL) { + PyErr_SetString(PyExc_TypeError, + "reduce() arg 2 must support iteration"); + Py_XDECREF(result); + return NULL; + } + + if ((args = PyTuple_New(2)) == NULL) + goto Fail; + + for (;;) { + PyObject *op2; + + if (args->ob_refcnt > 1) { + Py_DECREF(args); + if ((args = PyTuple_New(2)) == NULL) + goto Fail; + } + + op2 = PyIter_Next(it); + if (op2 == NULL) { + if (PyErr_Occurred()) + goto Fail; + break; + } + + if (result == NULL) + result = op2; + else { + PyTuple_SetItem(args, 0, result); + PyTuple_SetItem(args, 1, op2); + if ((result = PyEval_CallObject(func, args)) == NULL) + goto Fail; + } + } + + Py_DECREF(args); + + if (result == NULL) + PyErr_SetString(PyExc_TypeError, + "reduce() of empty sequence with no initial value"); - Py_DECREF(it); - return result; + Py_DECREF(it); + return result; Fail: - Py_XDECREF(args); - Py_XDECREF(result); - Py_DECREF(it); - return NULL; + Py_XDECREF(args); + Py_XDECREF(result); + Py_DECREF(it); + return NULL; } PyDoc_STRVAR(functools_reduce_doc, @@ -369,47 +369,47 @@ "Tools that operate on functions."); static PyMethodDef module_methods[] = { - {"reduce", functools_reduce, METH_VARARGS, functools_reduce_doc}, - {NULL, NULL} /* sentinel */ + {"reduce", functools_reduce, METH_VARARGS, functools_reduce_doc}, + {NULL, NULL} /* sentinel */ }; static struct PyModuleDef _functoolsmodule = { - PyModuleDef_HEAD_INIT, - "_functools", - module_doc, - -1, - module_methods, - NULL, - NULL, - NULL, - NULL + PyModuleDef_HEAD_INIT, + "_functools", + module_doc, + -1, + module_methods, + NULL, + NULL, + NULL, + NULL }; PyMODINIT_FUNC PyInit__functools(void) { - int i; - PyObject *m; - char *name; - PyTypeObject *typelist[] = { - &partial_type, - NULL - }; - - m = PyModule_Create(&_functoolsmodule); - if (m == NULL) - return NULL; - - for (i=0 ; typelist[i] != NULL ; i++) { - if (PyType_Ready(typelist[i]) < 0) { - Py_DECREF(m); - return NULL; - } - name = strchr(typelist[i]->tp_name, '.'); - assert (name != NULL); - Py_INCREF(typelist[i]); - PyModule_AddObject(m, name+1, (PyObject *)typelist[i]); - } - return m; + int i; + PyObject *m; + char *name; + PyTypeObject *typelist[] = { + &partial_type, + NULL + }; + + m = PyModule_Create(&_functoolsmodule); + if (m == NULL) + return NULL; + + for (i=0 ; typelist[i] != NULL ; i++) { + if (PyType_Ready(typelist[i]) < 0) { + Py_DECREF(m); + return NULL; + } + name = strchr(typelist[i]->tp_name, '.'); + assert (name != NULL); + Py_INCREF(typelist[i]); + PyModule_AddObject(m, name+1, (PyObject *)typelist[i]); + } + return m; } Modified: python/branches/py3k-jit/Modules/_gdbmmodule.c ============================================================================== --- python/branches/py3k-jit/Modules/_gdbmmodule.c (original) +++ python/branches/py3k-jit/Modules/_gdbmmodule.c Mon May 10 23:55:43 2010 @@ -30,7 +30,7 @@ typedef struct { PyObject_HEAD - int di_size; /* -1 means recompute */ + int di_size; /* -1 means recompute */ GDBM_FILE di_dbm; } dbmobject; @@ -177,7 +177,7 @@ } static PyMappingMethods dbm_as_mapping = { - (lenfunc)dbm_length, /*mp_length*/ + (lenfunc)dbm_length, /*mp_length*/ (binaryfunc)dbm_subscript, /*mp_subscript*/ (objobjargproc)dbm_ass_sub, /*mp_ass_subscript*/ }; @@ -247,15 +247,15 @@ datum key; if ((dp)->di_dbm == NULL) { - PyErr_SetString(DbmError, - "GDBM object has already been closed"); - return -1; + PyErr_SetString(DbmError, + "GDBM object has already been closed"); + return -1; } if (!PyBytes_Check(arg)) { - PyErr_Format(PyExc_TypeError, - "gdbm key must be bytes, not %.100s", - arg->ob_type->tp_name); - return -1; + PyErr_Format(PyExc_TypeError, + "gdbm key must be bytes, not %.100s", + arg->ob_type->tp_name); + return -1; } key.dptr = PyBytes_AS_STRING(arg); key.dsize = PyBytes_GET_SIZE(arg); @@ -263,16 +263,16 @@ } static PySequenceMethods dbm_as_sequence = { - 0, /* sq_length */ - 0, /* sq_concat */ - 0, /* sq_repeat */ - 0, /* sq_item */ - 0, /* sq_slice */ - 0, /* sq_ass_item */ - 0, /* sq_ass_slice */ - dbm_contains, /* sq_contains */ - 0, /* sq_inplace_concat */ - 0, /* sq_inplace_repeat */ + 0, /* sq_length */ + 0, /* sq_concat */ + 0, /* sq_repeat */ + 0, /* sq_item */ + 0, /* sq_slice */ + 0, /* sq_ass_item */ + 0, /* sq_ass_slice */ + dbm_contains, /* sq_contains */ + 0, /* sq_inplace_concat */ + 0, /* sq_inplace_repeat */ }; PyDoc_STRVAR(dbm_firstkey__doc__, @@ -372,13 +372,13 @@ } static PyMethodDef dbm_methods[] = { - {"close", (PyCFunction)dbm_close, METH_NOARGS, dbm_close__doc__}, - {"keys", (PyCFunction)dbm_keys, METH_NOARGS, dbm_keys__doc__}, + {"close", (PyCFunction)dbm_close, METH_NOARGS, dbm_close__doc__}, + {"keys", (PyCFunction)dbm_keys, METH_NOARGS, dbm_keys__doc__}, {"firstkey", (PyCFunction)dbm_firstkey,METH_NOARGS, dbm_firstkey__doc__}, - {"nextkey", (PyCFunction)dbm_nextkey, METH_VARARGS, dbm_nextkey__doc__}, + {"nextkey", (PyCFunction)dbm_nextkey, METH_VARARGS, dbm_nextkey__doc__}, {"reorganize",(PyCFunction)dbm_reorganize,METH_NOARGS, dbm_reorganize__doc__}, {"sync", (PyCFunction)dbm_sync, METH_NOARGS, dbm_sync__doc__}, - {NULL, NULL} /* sentinel */ + {NULL, NULL} /* sentinel */ }; static PyTypeObject Dbmtype = { @@ -486,7 +486,7 @@ #endif default: PyOS_snprintf(buf, sizeof(buf), "Flag '%c' is not supported.", - *flags); + *flags); PyErr_SetString(DbmError, buf); return NULL; } @@ -514,15 +514,15 @@ static struct PyModuleDef _gdbmmodule = { - PyModuleDef_HEAD_INIT, - "_gdbm", - gdbmmodule__doc__, - -1, - dbmmodule_methods, - NULL, - NULL, - NULL, - NULL + PyModuleDef_HEAD_INIT, + "_gdbm", + gdbmmodule__doc__, + -1, + dbmmodule_methods, + NULL, + NULL, + NULL, + NULL }; PyMODINIT_FUNC @@ -530,10 +530,10 @@ PyObject *m, *d, *s; if (PyType_Ready(&Dbmtype) < 0) - return NULL; + return NULL; m = PyModule_Create(&_gdbmmodule); if (m == NULL) - return NULL; + return NULL; d = PyModule_GetDict(m); DbmError = PyErr_NewException("_gdbm.error", PyExc_IOError, NULL); if (DbmError != NULL) { Modified: python/branches/py3k-jit/Modules/_gestalt.c ============================================================================== --- python/branches/py3k-jit/Modules/_gestalt.c (original) +++ python/branches/py3k-jit/Modules/_gestalt.c Mon May 10 23:55:43 2010 @@ -4,10 +4,10 @@ All Rights Reserved -Permission to use, copy, modify, and distribute this software and its -documentation for any purpose and without fee is hereby granted, +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 +both that copyright notice and this permission notice appear in supporting documentation, and that the names of Stichting Mathematisch Centrum or CWI not be used in advertising or publicity pertaining to distribution of the software without specific, written prior permission. @@ -34,9 +34,9 @@ { uint32_t tmp; if (!PyUnicode_Check(v) || PyUnicode_GetSize(v) != 4) { - PyErr_SetString(PyExc_TypeError, - "OSType arg must be string of 4 chars"); - return 0; + PyErr_SetString(PyExc_TypeError, + "OSType arg must be string of 4 chars"); + return 0; } memcpy((char *)&tmp, _PyUnicode_AsString(v), 4); *pr = (OSType)ntohl(tmp); @@ -50,12 +50,12 @@ OSType selector; SInt32 response; if (!PyArg_ParseTuple(args, "O&", convert_to_OSType, &selector)) - return NULL; + return NULL; iErr = Gestalt(selector, &response); if (iErr != 0) { - PyErr_SetString(PyExc_OSError, - "non-zero exit code!"); - return NULL; + PyErr_SetString(PyExc_OSError, + "non-zero exit code!"); + return NULL; } return PyLong_FromLong(response); } @@ -66,19 +66,19 @@ }; static struct PyModuleDef gestaltmodule = { - PyModuleDef_HEAD_INIT, - "_gestalt", - NULL, - -1, - gestalt_methods, - NULL, - NULL, - NULL, - NULL + PyModuleDef_HEAD_INIT, + "_gestalt", + NULL, + -1, + gestalt_methods, + NULL, + NULL, + NULL, + NULL }; PyMODINIT_FUNC PyInit__gestalt(void) { - return PyModule_Create(&gestaltmodule); + return PyModule_Create(&gestaltmodule); } Modified: python/branches/py3k-jit/Modules/_heapqmodule.c ============================================================================== --- python/branches/py3k-jit/Modules/_heapqmodule.c (original) +++ python/branches/py3k-jit/Modules/_heapqmodule.c Mon May 10 23:55:43 2010 @@ -1,4 +1,4 @@ -/* Drop in replacement for heapq.py +/* Drop in replacement for heapq.py C implementation derived directly from heapq.py in Py2.3 which was written by Kevin O'Connor, augmented by Tim Peters, @@ -11,115 +11,115 @@ static int cmp_lt(PyObject *x, PyObject *y) { - return PyObject_RichCompareBool(x, y, Py_LT); + return PyObject_RichCompareBool(x, y, Py_LT); } static int _siftdown(PyListObject *heap, Py_ssize_t startpos, Py_ssize_t pos) { - PyObject *newitem, *parent; - int cmp; - Py_ssize_t parentpos; - - assert(PyList_Check(heap)); - if (pos >= PyList_GET_SIZE(heap)) { - PyErr_SetString(PyExc_IndexError, "index out of range"); - return -1; - } - - newitem = PyList_GET_ITEM(heap, pos); - Py_INCREF(newitem); - /* Follow the path to the root, moving parents down until finding - a place newitem fits. */ - while (pos > startpos){ - parentpos = (pos - 1) >> 1; - parent = PyList_GET_ITEM(heap, parentpos); - cmp = cmp_lt(newitem, parent); - if (cmp == -1) { - Py_DECREF(newitem); - return -1; - } - if (cmp == 0) - break; - Py_INCREF(parent); - Py_DECREF(PyList_GET_ITEM(heap, pos)); - PyList_SET_ITEM(heap, pos, parent); - pos = parentpos; - } - Py_DECREF(PyList_GET_ITEM(heap, pos)); - PyList_SET_ITEM(heap, pos, newitem); - return 0; + PyObject *newitem, *parent; + int cmp; + Py_ssize_t parentpos; + + assert(PyList_Check(heap)); + if (pos >= PyList_GET_SIZE(heap)) { + PyErr_SetString(PyExc_IndexError, "index out of range"); + return -1; + } + + newitem = PyList_GET_ITEM(heap, pos); + Py_INCREF(newitem); + /* Follow the path to the root, moving parents down until finding + a place newitem fits. */ + while (pos > startpos){ + parentpos = (pos - 1) >> 1; + parent = PyList_GET_ITEM(heap, parentpos); + cmp = cmp_lt(newitem, parent); + if (cmp == -1) { + Py_DECREF(newitem); + return -1; + } + if (cmp == 0) + break; + Py_INCREF(parent); + Py_DECREF(PyList_GET_ITEM(heap, pos)); + PyList_SET_ITEM(heap, pos, parent); + pos = parentpos; + } + Py_DECREF(PyList_GET_ITEM(heap, pos)); + PyList_SET_ITEM(heap, pos, newitem); + return 0; } static int _siftup(PyListObject *heap, Py_ssize_t pos) { - Py_ssize_t startpos, endpos, childpos, rightpos; - int cmp; - PyObject *newitem, *tmp; - - assert(PyList_Check(heap)); - endpos = PyList_GET_SIZE(heap); - startpos = pos; - if (pos >= endpos) { - PyErr_SetString(PyExc_IndexError, "index out of range"); - return -1; - } - newitem = PyList_GET_ITEM(heap, pos); - Py_INCREF(newitem); - - /* Bubble up the smaller child until hitting a leaf. */ - childpos = 2*pos + 1; /* leftmost child position */ - while (childpos < endpos) { - /* Set childpos to index of smaller child. */ - rightpos = childpos + 1; - if (rightpos < endpos) { - cmp = cmp_lt( - PyList_GET_ITEM(heap, childpos), - PyList_GET_ITEM(heap, rightpos)); - if (cmp == -1) { - Py_DECREF(newitem); - return -1; - } - if (cmp == 0) - childpos = rightpos; - } - /* Move the smaller child up. */ - tmp = PyList_GET_ITEM(heap, childpos); - Py_INCREF(tmp); - Py_DECREF(PyList_GET_ITEM(heap, pos)); - PyList_SET_ITEM(heap, pos, tmp); - pos = childpos; - childpos = 2*pos + 1; - } - - /* The leaf at pos is empty now. Put newitem there, and and bubble - it up to its final resting place (by sifting its parents down). */ - Py_DECREF(PyList_GET_ITEM(heap, pos)); - PyList_SET_ITEM(heap, pos, newitem); - return _siftdown(heap, startpos, pos); + Py_ssize_t startpos, endpos, childpos, rightpos; + int cmp; + PyObject *newitem, *tmp; + + assert(PyList_Check(heap)); + endpos = PyList_GET_SIZE(heap); + startpos = pos; + if (pos >= endpos) { + PyErr_SetString(PyExc_IndexError, "index out of range"); + return -1; + } + newitem = PyList_GET_ITEM(heap, pos); + Py_INCREF(newitem); + + /* Bubble up the smaller child until hitting a leaf. */ + childpos = 2*pos + 1; /* leftmost child position */ + while (childpos < endpos) { + /* Set childpos to index of smaller child. */ + rightpos = childpos + 1; + if (rightpos < endpos) { + cmp = cmp_lt( + PyList_GET_ITEM(heap, childpos), + PyList_GET_ITEM(heap, rightpos)); + if (cmp == -1) { + Py_DECREF(newitem); + return -1; + } + if (cmp == 0) + childpos = rightpos; + } + /* Move the smaller child up. */ + tmp = PyList_GET_ITEM(heap, childpos); + Py_INCREF(tmp); + Py_DECREF(PyList_GET_ITEM(heap, pos)); + PyList_SET_ITEM(heap, pos, tmp); + pos = childpos; + childpos = 2*pos + 1; + } + + /* The leaf at pos is empty now. Put newitem there, and and bubble + it up to its final resting place (by sifting its parents down). */ + Py_DECREF(PyList_GET_ITEM(heap, pos)); + PyList_SET_ITEM(heap, pos, newitem); + return _siftdown(heap, startpos, pos); } static PyObject * heappush(PyObject *self, PyObject *args) { - PyObject *heap, *item; + PyObject *heap, *item; - if (!PyArg_UnpackTuple(args, "heappush", 2, 2, &heap, &item)) - return NULL; + if (!PyArg_UnpackTuple(args, "heappush", 2, 2, &heap, &item)) + return NULL; - if (!PyList_Check(heap)) { - PyErr_SetString(PyExc_TypeError, "heap argument must be a list"); - return NULL; - } - - if (PyList_Append(heap, item) == -1) - return NULL; - - if (_siftdown((PyListObject *)heap, 0, PyList_GET_SIZE(heap)-1) == -1) - return NULL; - Py_INCREF(Py_None); - return Py_None; + if (!PyList_Check(heap)) { + PyErr_SetString(PyExc_TypeError, "heap argument must be a list"); + return NULL; + } + + if (PyList_Append(heap, item) == -1) + return NULL; + + if (_siftdown((PyListObject *)heap, 0, PyList_GET_SIZE(heap)-1) == -1) + return NULL; + Py_INCREF(Py_None); + return Py_None; } PyDoc_STRVAR(heappush_doc, @@ -128,35 +128,35 @@ static PyObject * heappop(PyObject *self, PyObject *heap) { - PyObject *lastelt, *returnitem; - Py_ssize_t n; + PyObject *lastelt, *returnitem; + Py_ssize_t n; - if (!PyList_Check(heap)) { - PyErr_SetString(PyExc_TypeError, "heap argument must be a list"); - return NULL; - } - - /* # raises appropriate IndexError if heap is empty */ - n = PyList_GET_SIZE(heap); - if (n == 0) { - PyErr_SetString(PyExc_IndexError, "index out of range"); - return NULL; - } - - lastelt = PyList_GET_ITEM(heap, n-1) ; - Py_INCREF(lastelt); - PyList_SetSlice(heap, n-1, n, NULL); - n--; - - if (!n) - return lastelt; - returnitem = PyList_GET_ITEM(heap, 0); - PyList_SET_ITEM(heap, 0, lastelt); - if (_siftup((PyListObject *)heap, 0) == -1) { - Py_DECREF(returnitem); - return NULL; - } - return returnitem; + if (!PyList_Check(heap)) { + PyErr_SetString(PyExc_TypeError, "heap argument must be a list"); + return NULL; + } + + /* # raises appropriate IndexError if heap is empty */ + n = PyList_GET_SIZE(heap); + if (n == 0) { + PyErr_SetString(PyExc_IndexError, "index out of range"); + return NULL; + } + + lastelt = PyList_GET_ITEM(heap, n-1) ; + Py_INCREF(lastelt); + PyList_SetSlice(heap, n-1, n, NULL); + n--; + + if (!n) + return lastelt; + returnitem = PyList_GET_ITEM(heap, 0); + PyList_SET_ITEM(heap, 0, lastelt); + if (_siftup((PyListObject *)heap, 0) == -1) { + Py_DECREF(returnitem); + return NULL; + } + return returnitem; } PyDoc_STRVAR(heappop_doc, @@ -165,29 +165,29 @@ static PyObject * heapreplace(PyObject *self, PyObject *args) { - PyObject *heap, *item, *returnitem; + PyObject *heap, *item, *returnitem; - if (!PyArg_UnpackTuple(args, "heapreplace", 2, 2, &heap, &item)) - return NULL; + if (!PyArg_UnpackTuple(args, "heapreplace", 2, 2, &heap, &item)) + return NULL; - if (!PyList_Check(heap)) { - PyErr_SetString(PyExc_TypeError, "heap argument must be a list"); - return NULL; - } - - if (PyList_GET_SIZE(heap) < 1) { - PyErr_SetString(PyExc_IndexError, "index out of range"); - return NULL; - } - - returnitem = PyList_GET_ITEM(heap, 0); - Py_INCREF(item); - PyList_SET_ITEM(heap, 0, item); - if (_siftup((PyListObject *)heap, 0) == -1) { - Py_DECREF(returnitem); - return NULL; - } - return returnitem; + if (!PyList_Check(heap)) { + PyErr_SetString(PyExc_TypeError, "heap argument must be a list"); + return NULL; + } + + if (PyList_GET_SIZE(heap) < 1) { + PyErr_SetString(PyExc_IndexError, "index out of range"); + return NULL; + } + + returnitem = PyList_GET_ITEM(heap, 0); + Py_INCREF(item); + PyList_SET_ITEM(heap, 0, item); + if (_siftup((PyListObject *)heap, 0) == -1) { + Py_DECREF(returnitem); + return NULL; + } + return returnitem; } PyDoc_STRVAR(heapreplace_doc, @@ -197,44 +197,44 @@ more appropriate when using a fixed-size heap. Note that the value\n\ returned may be larger than item! That constrains reasonable uses of\n\ this routine unless written as part of a conditional replacement:\n\n\ - if item > heap[0]:\n\ - item = heapreplace(heap, item)\n"); + if item > heap[0]:\n\ + item = heapreplace(heap, item)\n"); static PyObject * heappushpop(PyObject *self, PyObject *args) { - PyObject *heap, *item, *returnitem; - int cmp; + PyObject *heap, *item, *returnitem; + int cmp; - if (!PyArg_UnpackTuple(args, "heappushpop", 2, 2, &heap, &item)) - return NULL; + if (!PyArg_UnpackTuple(args, "heappushpop", 2, 2, &heap, &item)) + return NULL; - if (!PyList_Check(heap)) { - PyErr_SetString(PyExc_TypeError, "heap argument must be a list"); - return NULL; - } - - if (PyList_GET_SIZE(heap) < 1) { - Py_INCREF(item); - return item; - } - - cmp = cmp_lt(PyList_GET_ITEM(heap, 0), item); - if (cmp == -1) - return NULL; - if (cmp == 0) { - Py_INCREF(item); - return item; - } - - returnitem = PyList_GET_ITEM(heap, 0); - Py_INCREF(item); - PyList_SET_ITEM(heap, 0, item); - if (_siftup((PyListObject *)heap, 0) == -1) { - Py_DECREF(returnitem); - return NULL; - } - return returnitem; + if (!PyList_Check(heap)) { + PyErr_SetString(PyExc_TypeError, "heap argument must be a list"); + return NULL; + } + + if (PyList_GET_SIZE(heap) < 1) { + Py_INCREF(item); + return item; + } + + cmp = cmp_lt(PyList_GET_ITEM(heap, 0), item); + if (cmp == -1) + return NULL; + if (cmp == 0) { + Py_INCREF(item); + return item; + } + + returnitem = PyList_GET_ITEM(heap, 0); + Py_INCREF(item); + PyList_SET_ITEM(heap, 0, item); + if (_siftup((PyListObject *)heap, 0) == -1) { + Py_DECREF(returnitem); + return NULL; + } + return returnitem; } PyDoc_STRVAR(heappushpop_doc, @@ -245,26 +245,26 @@ static PyObject * heapify(PyObject *self, PyObject *heap) { - Py_ssize_t i, n; + Py_ssize_t i, n; - if (!PyList_Check(heap)) { - PyErr_SetString(PyExc_TypeError, "heap argument must be a list"); - return NULL; - } - - n = PyList_GET_SIZE(heap); - /* Transform bottom-up. The largest index there's any point to - looking at is the largest with a child index in-range, so must - have 2*i + 1 < n, or i < (n-1)/2. If n is even = 2*j, this is - (2*j-1)/2 = j-1/2 so j-1 is the largest, which is n//2 - 1. If - n is odd = 2*j+1, this is (2*j+1-1)/2 = j so j-1 is the largest, - and that's again n//2-1. - */ - for (i=n/2-1 ; i>=0 ; i--) - if(_siftup((PyListObject *)heap, i) == -1) - return NULL; - Py_INCREF(Py_None); - return Py_None; + if (!PyList_Check(heap)) { + PyErr_SetString(PyExc_TypeError, "heap argument must be a list"); + return NULL; + } + + n = PyList_GET_SIZE(heap); + /* Transform bottom-up. The largest index there's any point to + looking at is the largest with a child index in-range, so must + have 2*i + 1 < n, or i < (n-1)/2. If n is even = 2*j, this is + (2*j-1)/2 = j-1/2 so j-1 is the largest, which is n//2 - 1. If + n is odd = 2*j+1, this is (2*j+1-1)/2 = j so j-1 is the largest, + and that's again n//2-1. + */ + for (i=n/2-1 ; i>=0 ; i--) + if(_siftup((PyListObject *)heap, i) == -1) + return NULL; + Py_INCREF(Py_None); + return Py_None; } PyDoc_STRVAR(heapify_doc, @@ -273,79 +273,79 @@ static PyObject * nlargest(PyObject *self, PyObject *args) { - PyObject *heap=NULL, *elem, *iterable, *sol, *it, *oldelem; - Py_ssize_t i, n; - int cmp; - - if (!PyArg_ParseTuple(args, "nO:nlargest", &n, &iterable)) - return NULL; - - it = PyObject_GetIter(iterable); - if (it == NULL) - return NULL; - - heap = PyList_New(0); - if (heap == NULL) - goto fail; - - for (i=0 ; i=0 ; i--) - if(_siftup((PyListObject *)heap, i) == -1) - goto fail; - - sol = PyList_GET_ITEM(heap, 0); - while (1) { - elem = PyIter_Next(it); - if (elem == NULL) { - if (PyErr_Occurred()) - goto fail; - else - goto sortit; - } - cmp = cmp_lt(sol, elem); - if (cmp == -1) { - Py_DECREF(elem); - goto fail; - } - if (cmp == 0) { - Py_DECREF(elem); - continue; - } - oldelem = PyList_GET_ITEM(heap, 0); - PyList_SET_ITEM(heap, 0, elem); - Py_DECREF(oldelem); - if (_siftup((PyListObject *)heap, 0) == -1) - goto fail; - sol = PyList_GET_ITEM(heap, 0); - } + PyObject *heap=NULL, *elem, *iterable, *sol, *it, *oldelem; + Py_ssize_t i, n; + int cmp; + + if (!PyArg_ParseTuple(args, "nO:nlargest", &n, &iterable)) + return NULL; + + it = PyObject_GetIter(iterable); + if (it == NULL) + return NULL; + + heap = PyList_New(0); + if (heap == NULL) + goto fail; + + for (i=0 ; i=0 ; i--) + if(_siftup((PyListObject *)heap, i) == -1) + goto fail; + + sol = PyList_GET_ITEM(heap, 0); + while (1) { + elem = PyIter_Next(it); + if (elem == NULL) { + if (PyErr_Occurred()) + goto fail; + else + goto sortit; + } + cmp = cmp_lt(sol, elem); + if (cmp == -1) { + Py_DECREF(elem); + goto fail; + } + if (cmp == 0) { + Py_DECREF(elem); + continue; + } + oldelem = PyList_GET_ITEM(heap, 0); + PyList_SET_ITEM(heap, 0, elem); + Py_DECREF(oldelem); + if (_siftup((PyListObject *)heap, 0) == -1) + goto fail; + sol = PyList_GET_ITEM(heap, 0); + } sortit: - if (PyList_Sort(heap) == -1) - goto fail; - if (PyList_Reverse(heap) == -1) - goto fail; - Py_DECREF(it); - return heap; + if (PyList_Sort(heap) == -1) + goto fail; + if (PyList_Reverse(heap) == -1) + goto fail; + Py_DECREF(it); + return heap; fail: - Py_DECREF(it); - Py_XDECREF(heap); - return NULL; + Py_DECREF(it); + Py_XDECREF(heap); + return NULL; } PyDoc_STRVAR(nlargest_doc, @@ -356,166 +356,166 @@ static int _siftdownmax(PyListObject *heap, Py_ssize_t startpos, Py_ssize_t pos) { - PyObject *newitem, *parent; - int cmp; - Py_ssize_t parentpos; - - assert(PyList_Check(heap)); - if (pos >= PyList_GET_SIZE(heap)) { - PyErr_SetString(PyExc_IndexError, "index out of range"); - return -1; - } - - newitem = PyList_GET_ITEM(heap, pos); - Py_INCREF(newitem); - /* Follow the path to the root, moving parents down until finding - a place newitem fits. */ - while (pos > startpos){ - parentpos = (pos - 1) >> 1; - parent = PyList_GET_ITEM(heap, parentpos); - cmp = cmp_lt(parent, newitem); - if (cmp == -1) { - Py_DECREF(newitem); - return -1; - } - if (cmp == 0) - break; - Py_INCREF(parent); - Py_DECREF(PyList_GET_ITEM(heap, pos)); - PyList_SET_ITEM(heap, pos, parent); - pos = parentpos; - } - Py_DECREF(PyList_GET_ITEM(heap, pos)); - PyList_SET_ITEM(heap, pos, newitem); - return 0; + PyObject *newitem, *parent; + int cmp; + Py_ssize_t parentpos; + + assert(PyList_Check(heap)); + if (pos >= PyList_GET_SIZE(heap)) { + PyErr_SetString(PyExc_IndexError, "index out of range"); + return -1; + } + + newitem = PyList_GET_ITEM(heap, pos); + Py_INCREF(newitem); + /* Follow the path to the root, moving parents down until finding + a place newitem fits. */ + while (pos > startpos){ + parentpos = (pos - 1) >> 1; + parent = PyList_GET_ITEM(heap, parentpos); + cmp = cmp_lt(parent, newitem); + if (cmp == -1) { + Py_DECREF(newitem); + return -1; + } + if (cmp == 0) + break; + Py_INCREF(parent); + Py_DECREF(PyList_GET_ITEM(heap, pos)); + PyList_SET_ITEM(heap, pos, parent); + pos = parentpos; + } + Py_DECREF(PyList_GET_ITEM(heap, pos)); + PyList_SET_ITEM(heap, pos, newitem); + return 0; } static int _siftupmax(PyListObject *heap, Py_ssize_t pos) { - Py_ssize_t startpos, endpos, childpos, rightpos; - int cmp; - PyObject *newitem, *tmp; - - assert(PyList_Check(heap)); - endpos = PyList_GET_SIZE(heap); - startpos = pos; - if (pos >= endpos) { - PyErr_SetString(PyExc_IndexError, "index out of range"); - return -1; - } - newitem = PyList_GET_ITEM(heap, pos); - Py_INCREF(newitem); - - /* Bubble up the smaller child until hitting a leaf. */ - childpos = 2*pos + 1; /* leftmost child position */ - while (childpos < endpos) { - /* Set childpos to index of smaller child. */ - rightpos = childpos + 1; - if (rightpos < endpos) { - cmp = cmp_lt( - PyList_GET_ITEM(heap, rightpos), - PyList_GET_ITEM(heap, childpos)); - if (cmp == -1) { - Py_DECREF(newitem); - return -1; - } - if (cmp == 0) - childpos = rightpos; - } - /* Move the smaller child up. */ - tmp = PyList_GET_ITEM(heap, childpos); - Py_INCREF(tmp); - Py_DECREF(PyList_GET_ITEM(heap, pos)); - PyList_SET_ITEM(heap, pos, tmp); - pos = childpos; - childpos = 2*pos + 1; - } - - /* The leaf at pos is empty now. Put newitem there, and and bubble - it up to its final resting place (by sifting its parents down). */ - Py_DECREF(PyList_GET_ITEM(heap, pos)); - PyList_SET_ITEM(heap, pos, newitem); - return _siftdownmax(heap, startpos, pos); + Py_ssize_t startpos, endpos, childpos, rightpos; + int cmp; + PyObject *newitem, *tmp; + + assert(PyList_Check(heap)); + endpos = PyList_GET_SIZE(heap); + startpos = pos; + if (pos >= endpos) { + PyErr_SetString(PyExc_IndexError, "index out of range"); + return -1; + } + newitem = PyList_GET_ITEM(heap, pos); + Py_INCREF(newitem); + + /* Bubble up the smaller child until hitting a leaf. */ + childpos = 2*pos + 1; /* leftmost child position */ + while (childpos < endpos) { + /* Set childpos to index of smaller child. */ + rightpos = childpos + 1; + if (rightpos < endpos) { + cmp = cmp_lt( + PyList_GET_ITEM(heap, rightpos), + PyList_GET_ITEM(heap, childpos)); + if (cmp == -1) { + Py_DECREF(newitem); + return -1; + } + if (cmp == 0) + childpos = rightpos; + } + /* Move the smaller child up. */ + tmp = PyList_GET_ITEM(heap, childpos); + Py_INCREF(tmp); + Py_DECREF(PyList_GET_ITEM(heap, pos)); + PyList_SET_ITEM(heap, pos, tmp); + pos = childpos; + childpos = 2*pos + 1; + } + + /* The leaf at pos is empty now. Put newitem there, and and bubble + it up to its final resting place (by sifting its parents down). */ + Py_DECREF(PyList_GET_ITEM(heap, pos)); + PyList_SET_ITEM(heap, pos, newitem); + return _siftdownmax(heap, startpos, pos); } static PyObject * nsmallest(PyObject *self, PyObject *args) { - PyObject *heap=NULL, *elem, *iterable, *los, *it, *oldelem; - Py_ssize_t i, n; - int cmp; - - if (!PyArg_ParseTuple(args, "nO:nsmallest", &n, &iterable)) - return NULL; - - it = PyObject_GetIter(iterable); - if (it == NULL) - return NULL; - - heap = PyList_New(0); - if (heap == NULL) - goto fail; - - for (i=0 ; i=0 ; i--) - if(_siftupmax((PyListObject *)heap, i) == -1) - goto fail; - - los = PyList_GET_ITEM(heap, 0); - while (1) { - elem = PyIter_Next(it); - if (elem == NULL) { - if (PyErr_Occurred()) - goto fail; - else - goto sortit; - } - cmp = cmp_lt(elem, los); - if (cmp == -1) { - Py_DECREF(elem); - goto fail; - } - if (cmp == 0) { - Py_DECREF(elem); - continue; - } - - oldelem = PyList_GET_ITEM(heap, 0); - PyList_SET_ITEM(heap, 0, elem); - Py_DECREF(oldelem); - if (_siftupmax((PyListObject *)heap, 0) == -1) - goto fail; - los = PyList_GET_ITEM(heap, 0); - } + PyObject *heap=NULL, *elem, *iterable, *los, *it, *oldelem; + Py_ssize_t i, n; + int cmp; + + if (!PyArg_ParseTuple(args, "nO:nsmallest", &n, &iterable)) + return NULL; + + it = PyObject_GetIter(iterable); + if (it == NULL) + return NULL; + + heap = PyList_New(0); + if (heap == NULL) + goto fail; + + for (i=0 ; i=0 ; i--) + if(_siftupmax((PyListObject *)heap, i) == -1) + goto fail; + + los = PyList_GET_ITEM(heap, 0); + while (1) { + elem = PyIter_Next(it); + if (elem == NULL) { + if (PyErr_Occurred()) + goto fail; + else + goto sortit; + } + cmp = cmp_lt(elem, los); + if (cmp == -1) { + Py_DECREF(elem); + goto fail; + } + if (cmp == 0) { + Py_DECREF(elem); + continue; + } + + oldelem = PyList_GET_ITEM(heap, 0); + PyList_SET_ITEM(heap, 0, elem); + Py_DECREF(oldelem); + if (_siftupmax((PyListObject *)heap, 0) == -1) + goto fail; + los = PyList_GET_ITEM(heap, 0); + } sortit: - if (PyList_Sort(heap) == -1) - goto fail; - Py_DECREF(it); - return heap; + if (PyList_Sort(heap) == -1) + goto fail; + Py_DECREF(it); + return heap; fail: - Py_DECREF(it); - Py_XDECREF(heap); - return NULL; + Py_DECREF(it); + Py_XDECREF(heap); + return NULL; } PyDoc_STRVAR(nsmallest_doc, @@ -524,21 +524,21 @@ Equivalent to: sorted(iterable)[:n]\n"); static PyMethodDef heapq_methods[] = { - {"heappush", (PyCFunction)heappush, - METH_VARARGS, heappush_doc}, - {"heappushpop", (PyCFunction)heappushpop, - METH_VARARGS, heappushpop_doc}, - {"heappop", (PyCFunction)heappop, - METH_O, heappop_doc}, - {"heapreplace", (PyCFunction)heapreplace, - METH_VARARGS, heapreplace_doc}, - {"heapify", (PyCFunction)heapify, - METH_O, heapify_doc}, - {"nlargest", (PyCFunction)nlargest, - METH_VARARGS, nlargest_doc}, - {"nsmallest", (PyCFunction)nsmallest, - METH_VARARGS, nsmallest_doc}, - {NULL, NULL} /* sentinel */ + {"heappush", (PyCFunction)heappush, + METH_VARARGS, heappush_doc}, + {"heappushpop", (PyCFunction)heappushpop, + METH_VARARGS, heappushpop_doc}, + {"heappop", (PyCFunction)heappop, + METH_O, heappop_doc}, + {"heapreplace", (PyCFunction)heapreplace, + METH_VARARGS, heapreplace_doc}, + {"heapify", (PyCFunction)heapify, + METH_O, heapify_doc}, + {"nlargest", (PyCFunction)nlargest, + METH_VARARGS, nlargest_doc}, + {"nsmallest", (PyCFunction)nsmallest, + METH_VARARGS, nsmallest_doc}, + {NULL, NULL} /* sentinel */ }; PyDoc_STRVAR(module_doc, @@ -668,27 +668,27 @@ static struct PyModuleDef _heapqmodule = { - PyModuleDef_HEAD_INIT, - "_heapq", - module_doc, - -1, - heapq_methods, - NULL, - NULL, - NULL, - NULL + PyModuleDef_HEAD_INIT, + "_heapq", + module_doc, + -1, + heapq_methods, + NULL, + NULL, + NULL, + NULL }; PyMODINIT_FUNC PyInit__heapq(void) { - PyObject *m, *about; + PyObject *m, *about; - m = PyModule_Create(&_heapqmodule); - if (m == NULL) - return NULL; - about = PyUnicode_DecodeUTF8(__about__, strlen(__about__), NULL); - PyModule_AddObject(m, "__about__", about); - return m; + m = PyModule_Create(&_heapqmodule); + if (m == NULL) + return NULL; + about = PyUnicode_DecodeUTF8(__about__, strlen(__about__), NULL); + PyModule_AddObject(m, "__about__", about); + return m; } Modified: python/branches/py3k-jit/Modules/_json.c ============================================================================== --- python/branches/py3k-jit/Modules/_json.c (original) +++ python/branches/py3k-jit/Modules/_json.c Mon May 10 23:55:43 2010 @@ -511,7 +511,7 @@ rval = scanstring_unicode(pystr, end, strict, &next_end); } else { - PyErr_Format(PyExc_TypeError, + PyErr_Format(PyExc_TypeError, "first argument must be a string or bytes, not %.80s", Py_TYPE(pystr)->tp_name); return NULL; @@ -1394,7 +1394,7 @@ if (PyObject_IsTrue(s->sort_keys)) { if (code == NULL) { - code = Py_CompileString("sorted(d.items(), key=lambda kv: kv[0])", + code = Py_CompileString("sorted(d.items(), key=lambda kv: kv[0])", "_json.c", Py_eval_input); if (code == NULL) goto bail; @@ -1409,14 +1409,14 @@ } items = PyEval_EvalCode((PyCodeObject *)code, PyEval_GetGlobals(), mapping); Py_DECREF(mapping); - } else { + } else { items = PyMapping_Items(dct); - } - if (items == NULL) + } + if (items == NULL) goto bail; it = PyObject_GetIter(items); - Py_DECREF(items); - if (it == NULL) + Py_DECREF(items); + if (it == NULL) goto bail; skipkeys = PyObject_IsTrue(s->skipkeys); idx = 0; @@ -1437,8 +1437,8 @@ goto bail; } else if (key == Py_True || key == Py_False || key == Py_None) { - /* This must come before the PyLong_Check because - True and False are also 1 and 0.*/ + /* This must come before the PyLong_Check because + True and False are also 1 and 0.*/ kstr = _encoded_const(key); if (kstr == NULL) goto bail; @@ -1704,15 +1704,15 @@ "json speedups\n"); static struct PyModuleDef jsonmodule = { - PyModuleDef_HEAD_INIT, - "_json", - module_doc, - -1, - speedups_methods, - NULL, - NULL, - NULL, - NULL + PyModuleDef_HEAD_INIT, + "_json", + module_doc, + -1, + speedups_methods, + NULL, + NULL, + NULL, + NULL }; PyObject* Modified: python/branches/py3k-jit/Modules/_localemodule.c ============================================================================== --- python/branches/py3k-jit/Modules/_localemodule.c (original) +++ python/branches/py3k-jit/Modules/_localemodule.c Mon May 10 23:55:43 2010 @@ -77,7 +77,7 @@ if (dest != smallbuf) PyMem_Free(dest); return res2; -} +} /* support functions for formatting floating point numbers */ @@ -243,7 +243,7 @@ PyObject *os1, *os2, *result = NULL; wchar_t *ws1 = NULL, *ws2 = NULL; Py_ssize_t len1, len2; - + if (!PyArg_ParseTuple(args, "UU:strcoll", &os1, &os2)) return NULL; /* Convert the unicode strings to wchar[]. */ @@ -373,9 +373,9 @@ #ifdef HAVE_LANGINFO_H #define LANGINFO(X) {#X, X} static struct langinfo_constant{ - char* name; - int value; -} langinfo_constants[] = + char* name; + int value; +} langinfo_constants[] = { /* These constants should exist on any langinfo implementation */ LANGINFO(DAY_1), @@ -514,10 +514,10 @@ static PyObject* PyIntl_gettext(PyObject* self, PyObject *args) { - char *in; - if (!PyArg_ParseTuple(args, "s", &in)) - return 0; - return str2uni(gettext(in)); + char *in; + if (!PyArg_ParseTuple(args, "s", &in)) + return 0; + return str2uni(gettext(in)); } PyDoc_STRVAR(dgettext__doc__, @@ -527,10 +527,10 @@ static PyObject* PyIntl_dgettext(PyObject* self, PyObject *args) { - char *domain, *in; - if (!PyArg_ParseTuple(args, "zs", &domain, &in)) - return 0; - return str2uni(dgettext(domain, in)); + char *domain, *in; + if (!PyArg_ParseTuple(args, "zs", &domain, &in)) + return 0; + return str2uni(dgettext(domain, in)); } PyDoc_STRVAR(dcgettext__doc__, @@ -540,11 +540,11 @@ static PyObject* PyIntl_dcgettext(PyObject *self, PyObject *args) { - char *domain, *msgid; - int category; - if (!PyArg_ParseTuple(args, "zsi", &domain, &msgid, &category)) - return 0; - return str2uni(dcgettext(domain,msgid,category)); + char *domain, *msgid; + int category; + if (!PyArg_ParseTuple(args, "zsi", &domain, &msgid, &category)) + return 0; + return str2uni(dcgettext(domain,msgid,category)); } PyDoc_STRVAR(textdomain__doc__, @@ -554,15 +554,15 @@ static PyObject* PyIntl_textdomain(PyObject* self, PyObject* args) { - char *domain; - if (!PyArg_ParseTuple(args, "z", &domain)) - return 0; - domain = textdomain(domain); - if (!domain) { - PyErr_SetFromErrno(PyExc_OSError); - return NULL; - } - return str2uni(domain); + char *domain; + if (!PyArg_ParseTuple(args, "z", &domain)) + return 0; + domain = textdomain(domain); + if (!domain) { + PyErr_SetFromErrno(PyExc_OSError); + return NULL; + } + return str2uni(domain); } PyDoc_STRVAR(bindtextdomain__doc__, @@ -572,19 +572,19 @@ static PyObject* PyIntl_bindtextdomain(PyObject* self,PyObject*args) { - char *domain, *dirname; - if (!PyArg_ParseTuple(args, "sz", &domain, &dirname)) - return 0; - if (!strlen(domain)) { - PyErr_SetString(Error, "domain must be a non-empty string"); - return 0; - } - dirname = bindtextdomain(domain, dirname); - if (!dirname) { - PyErr_SetFromErrno(PyExc_OSError); - return NULL; - } - return str2uni(dirname); + char *domain, *dirname; + if (!PyArg_ParseTuple(args, "sz", &domain, &dirname)) + return 0; + if (!strlen(domain)) { + PyErr_SetString(Error, "domain must be a non-empty string"); + return 0; + } + dirname = bindtextdomain(domain, dirname); + if (!dirname) { + PyErr_SetFromErrno(PyExc_OSError); + return NULL; + } + return str2uni(dirname); } #ifdef HAVE_BIND_TEXTDOMAIN_CODESET @@ -595,32 +595,32 @@ static PyObject* PyIntl_bind_textdomain_codeset(PyObject* self,PyObject*args) { - char *domain,*codeset; - if (!PyArg_ParseTuple(args, "sz", &domain, &codeset)) - return NULL; - codeset = bind_textdomain_codeset(domain, codeset); - if (codeset) - return str2uni(codeset); - Py_RETURN_NONE; + char *domain,*codeset; + if (!PyArg_ParseTuple(args, "sz", &domain, &codeset)) + return NULL; + codeset = bind_textdomain_codeset(domain, codeset); + if (codeset) + return str2uni(codeset); + Py_RETURN_NONE; } #endif #endif static struct PyMethodDef PyLocale_Methods[] = { - {"setlocale", (PyCFunction) PyLocale_setlocale, + {"setlocale", (PyCFunction) PyLocale_setlocale, METH_VARARGS, setlocale__doc__}, - {"localeconv", (PyCFunction) PyLocale_localeconv, + {"localeconv", (PyCFunction) PyLocale_localeconv, METH_NOARGS, localeconv__doc__}, #ifdef HAVE_WCSCOLL - {"strcoll", (PyCFunction) PyLocale_strcoll, + {"strcoll", (PyCFunction) PyLocale_strcoll, METH_VARARGS, strcoll__doc__}, #endif #ifdef HAVE_WCSXFRM - {"strxfrm", (PyCFunction) PyLocale_strxfrm, + {"strxfrm", (PyCFunction) PyLocale_strxfrm, METH_VARARGS, strxfrm__doc__}, #endif -#if defined(MS_WINDOWS) +#if defined(MS_WINDOWS) {"_getdefaultlocale", (PyCFunction) PyLocale_getdefaultlocale, METH_NOARGS}, #endif #ifdef HAVE_LANGINFO_H @@ -642,21 +642,21 @@ {"bind_textdomain_codeset",(PyCFunction)PyIntl_bind_textdomain_codeset, METH_VARARGS, bind_textdomain_codeset__doc__}, #endif -#endif +#endif {NULL, NULL} }; static struct PyModuleDef _localemodule = { - PyModuleDef_HEAD_INIT, - "_locale", - locale__doc__, - -1, - PyLocale_Methods, - NULL, - NULL, - NULL, - NULL + PyModuleDef_HEAD_INIT, + "_locale", + locale__doc__, + -1, + PyLocale_Methods, + NULL, + NULL, + NULL, + NULL }; PyMODINIT_FUNC @@ -669,7 +669,7 @@ m = PyModule_Create(&_localemodule); if (m == NULL) - return NULL; + return NULL; d = PyModule_GetDict(m); @@ -712,14 +712,14 @@ #ifdef HAVE_LANGINFO_H for (i = 0; langinfo_constants[i].name; i++) { - PyModule_AddIntConstant(m, langinfo_constants[i].name, - langinfo_constants[i].value); + PyModule_AddIntConstant(m, langinfo_constants[i].name, + langinfo_constants[i].value); } #endif return m; } -/* +/* Local variables: c-basic-offset: 4 indent-tabs-mode: nil Modified: python/branches/py3k-jit/Modules/_lsprof.c ============================================================================== --- python/branches/py3k-jit/Modules/_lsprof.c (original) +++ python/branches/py3k-jit/Modules/_lsprof.c Mon May 10 23:55:43 2010 @@ -17,19 +17,19 @@ static PY_LONG_LONG hpTimer(void) { - LARGE_INTEGER li; - QueryPerformanceCounter(&li); - return li.QuadPart; + LARGE_INTEGER li; + QueryPerformanceCounter(&li); + return li.QuadPart; } static double hpTimerUnit(void) { - LARGE_INTEGER li; - if (QueryPerformanceFrequency(&li)) - return 1.0 / li.QuadPart; - else - return 0.000001; /* unlikely */ + LARGE_INTEGER li; + if (QueryPerformanceFrequency(&li)) + return 1.0 / li.QuadPart; + else + return 0.000001; /* unlikely */ } #else /* !MS_WINDOWS */ @@ -48,22 +48,22 @@ static PY_LONG_LONG hpTimer(void) { - struct timeval tv; - PY_LONG_LONG ret; + struct timeval tv; + PY_LONG_LONG ret; #ifdef GETTIMEOFDAY_NO_TZ - gettimeofday(&tv); + gettimeofday(&tv); #else - gettimeofday(&tv, (struct timezone *)NULL); + gettimeofday(&tv, (struct timezone *)NULL); #endif - ret = tv.tv_sec; - ret = ret * 1000000 + tv.tv_usec; - return ret; + ret = tv.tv_sec; + ret = ret * 1000000 + tv.tv_usec; + return ret; } static double hpTimerUnit(void) { - return 0.000001; + return 0.000001; } #endif /* MS_WINDOWS */ @@ -75,41 +75,41 @@ /* represents a function called from another function */ typedef struct _ProfilerSubEntry { - rotating_node_t header; - PY_LONG_LONG tt; - PY_LONG_LONG it; - long callcount; - long recursivecallcount; - long recursionLevel; + rotating_node_t header; + PY_LONG_LONG tt; + PY_LONG_LONG it; + long callcount; + long recursivecallcount; + long recursionLevel; } ProfilerSubEntry; /* represents a function or user defined block */ typedef struct _ProfilerEntry { - rotating_node_t header; - PyObject *userObj; /* PyCodeObject, or a descriptive str for builtins */ - PY_LONG_LONG tt; /* total time in this entry */ - PY_LONG_LONG it; /* inline time in this entry (not in subcalls) */ - long callcount; /* how many times this was called */ - long recursivecallcount; /* how many times called recursively */ - long recursionLevel; - rotating_node_t *calls; + rotating_node_t header; + PyObject *userObj; /* PyCodeObject, or a descriptive str for builtins */ + PY_LONG_LONG tt; /* total time in this entry */ + PY_LONG_LONG it; /* inline time in this entry (not in subcalls) */ + long callcount; /* how many times this was called */ + long recursivecallcount; /* how many times called recursively */ + long recursionLevel; + rotating_node_t *calls; } ProfilerEntry; typedef struct _ProfilerContext { - PY_LONG_LONG t0; - PY_LONG_LONG subt; - struct _ProfilerContext *previous; - ProfilerEntry *ctxEntry; + PY_LONG_LONG t0; + PY_LONG_LONG subt; + struct _ProfilerContext *previous; + ProfilerEntry *ctxEntry; } ProfilerContext; typedef struct { - PyObject_HEAD - rotating_node_t *profilerEntries; - ProfilerContext *currentProfilerContext; - ProfilerContext *freelistProfilerContext; - int flags; - PyObject *externalTimer; - double externalTimerUnit; + PyObject_HEAD + rotating_node_t *profilerEntries; + ProfilerContext *currentProfilerContext; + ProfilerContext *freelistProfilerContext; + int flags; + PyObject *externalTimer; + double externalTimerUnit; } ProfilerObject; #define POF_ENABLED 0x001 @@ -129,407 +129,407 @@ static PY_LONG_LONG CallExternalTimer(ProfilerObject *pObj) { - PY_LONG_LONG result; - PyObject *o = PyObject_Call(pObj->externalTimer, empty_tuple, NULL); - if (o == NULL) { - PyErr_WriteUnraisable(pObj->externalTimer); - return 0; - } - if (pObj->externalTimerUnit > 0.0) { - /* interpret the result as an integer that will be scaled - in profiler_getstats() */ - result = PyLong_AsLongLong(o); - } - else { - /* interpret the result as a double measured in seconds. - As the profiler works with PY_LONG_LONG internally - we convert it to a large integer */ - double val = PyFloat_AsDouble(o); - /* error handling delayed to the code below */ - result = (PY_LONG_LONG) (val * DOUBLE_TIMER_PRECISION); - } - Py_DECREF(o); - if (PyErr_Occurred()) { - PyErr_WriteUnraisable(pObj->externalTimer); - return 0; - } - return result; -} - -#define CALL_TIMER(pObj) ((pObj)->externalTimer ? \ - CallExternalTimer(pObj) : \ - hpTimer()) + PY_LONG_LONG result; + PyObject *o = PyObject_Call(pObj->externalTimer, empty_tuple, NULL); + if (o == NULL) { + PyErr_WriteUnraisable(pObj->externalTimer); + return 0; + } + if (pObj->externalTimerUnit > 0.0) { + /* interpret the result as an integer that will be scaled + in profiler_getstats() */ + result = PyLong_AsLongLong(o); + } + else { + /* interpret the result as a double measured in seconds. + As the profiler works with PY_LONG_LONG internally + we convert it to a large integer */ + double val = PyFloat_AsDouble(o); + /* error handling delayed to the code below */ + result = (PY_LONG_LONG) (val * DOUBLE_TIMER_PRECISION); + } + Py_DECREF(o); + if (PyErr_Occurred()) { + PyErr_WriteUnraisable(pObj->externalTimer); + return 0; + } + return result; +} + +#define CALL_TIMER(pObj) ((pObj)->externalTimer ? \ + CallExternalTimer(pObj) : \ + hpTimer()) /*** ProfilerObject ***/ static PyObject * normalizeUserObj(PyObject *obj) { - PyCFunctionObject *fn; - if (!PyCFunction_Check(obj)) { - Py_INCREF(obj); - return obj; - } - /* Replace built-in function objects with a descriptive string - because of built-in methods -- keeping a reference to - __self__ is probably not a good idea. */ - fn = (PyCFunctionObject *)obj; - - if (fn->m_self == NULL) { - /* built-in function: look up the module name */ - PyObject *mod = fn->m_module; - const char *modname; - if (mod && PyUnicode_Check(mod)) { - modname = _PyUnicode_AsString(mod); - } - else if (mod && PyModule_Check(mod)) { - modname = PyModule_GetName(mod); - if (modname == NULL) { - PyErr_Clear(); - modname = "builtins"; - } - } - else { - modname = "builtins"; - } - if (strcmp(modname, "builtins") != 0) - return PyUnicode_FromFormat("<%s.%s>", - modname, - fn->m_ml->ml_name); - else - return PyUnicode_FromFormat("<%s>", - fn->m_ml->ml_name); - } - else { - /* built-in method: try to return - repr(getattr(type(__self__), __name__)) - */ - PyObject *self = fn->m_self; - PyObject *name = PyUnicode_FromString(fn->m_ml->ml_name); - if (name != NULL) { - PyObject *mo = _PyType_Lookup(Py_TYPE(self), name); - Py_XINCREF(mo); - Py_DECREF(name); - if (mo != NULL) { - PyObject *res = PyObject_Repr(mo); - Py_DECREF(mo); - if (res != NULL) - return res; - } - } - PyErr_Clear(); - return PyUnicode_FromFormat("", - fn->m_ml->ml_name); - } + PyCFunctionObject *fn; + if (!PyCFunction_Check(obj)) { + Py_INCREF(obj); + return obj; + } + /* Replace built-in function objects with a descriptive string + because of built-in methods -- keeping a reference to + __self__ is probably not a good idea. */ + fn = (PyCFunctionObject *)obj; + + if (fn->m_self == NULL) { + /* built-in function: look up the module name */ + PyObject *mod = fn->m_module; + const char *modname; + if (mod && PyUnicode_Check(mod)) { + modname = _PyUnicode_AsString(mod); + } + else if (mod && PyModule_Check(mod)) { + modname = PyModule_GetName(mod); + if (modname == NULL) { + PyErr_Clear(); + modname = "builtins"; + } + } + else { + modname = "builtins"; + } + if (strcmp(modname, "builtins") != 0) + return PyUnicode_FromFormat("<%s.%s>", + modname, + fn->m_ml->ml_name); + else + return PyUnicode_FromFormat("<%s>", + fn->m_ml->ml_name); + } + else { + /* built-in method: try to return + repr(getattr(type(__self__), __name__)) + */ + PyObject *self = fn->m_self; + PyObject *name = PyUnicode_FromString(fn->m_ml->ml_name); + if (name != NULL) { + PyObject *mo = _PyType_Lookup(Py_TYPE(self), name); + Py_XINCREF(mo); + Py_DECREF(name); + if (mo != NULL) { + PyObject *res = PyObject_Repr(mo); + Py_DECREF(mo); + if (res != NULL) + return res; + } + } + PyErr_Clear(); + return PyUnicode_FromFormat("", + fn->m_ml->ml_name); + } } static ProfilerEntry* newProfilerEntry(ProfilerObject *pObj, void *key, PyObject *userObj) { - ProfilerEntry *self; - self = (ProfilerEntry*) malloc(sizeof(ProfilerEntry)); - if (self == NULL) { - pObj->flags |= POF_NOMEMORY; - return NULL; - } - userObj = normalizeUserObj(userObj); - if (userObj == NULL) { - PyErr_Clear(); - free(self); - pObj->flags |= POF_NOMEMORY; - return NULL; - } - self->header.key = key; - self->userObj = userObj; - self->tt = 0; - self->it = 0; - self->callcount = 0; - self->recursivecallcount = 0; - self->recursionLevel = 0; - self->calls = EMPTY_ROTATING_TREE; - RotatingTree_Add(&pObj->profilerEntries, &self->header); - return self; + ProfilerEntry *self; + self = (ProfilerEntry*) malloc(sizeof(ProfilerEntry)); + if (self == NULL) { + pObj->flags |= POF_NOMEMORY; + return NULL; + } + userObj = normalizeUserObj(userObj); + if (userObj == NULL) { + PyErr_Clear(); + free(self); + pObj->flags |= POF_NOMEMORY; + return NULL; + } + self->header.key = key; + self->userObj = userObj; + self->tt = 0; + self->it = 0; + self->callcount = 0; + self->recursivecallcount = 0; + self->recursionLevel = 0; + self->calls = EMPTY_ROTATING_TREE; + RotatingTree_Add(&pObj->profilerEntries, &self->header); + return self; } static ProfilerEntry* getEntry(ProfilerObject *pObj, void *key) { - return (ProfilerEntry*) RotatingTree_Get(&pObj->profilerEntries, key); + return (ProfilerEntry*) RotatingTree_Get(&pObj->profilerEntries, key); } -static ProfilerSubEntry * +static ProfilerSubEntry * getSubEntry(ProfilerObject *pObj, ProfilerEntry *caller, ProfilerEntry* entry) { - return (ProfilerSubEntry*) RotatingTree_Get(&caller->calls, - (void *)entry); + return (ProfilerSubEntry*) RotatingTree_Get(&caller->calls, + (void *)entry); } static ProfilerSubEntry * newSubEntry(ProfilerObject *pObj, ProfilerEntry *caller, ProfilerEntry* entry) { - ProfilerSubEntry *self; - self = (ProfilerSubEntry*) malloc(sizeof(ProfilerSubEntry)); - if (self == NULL) { - pObj->flags |= POF_NOMEMORY; - return NULL; - } - self->header.key = (void *)entry; - self->tt = 0; - self->it = 0; - self->callcount = 0; - self->recursivecallcount = 0; - self->recursionLevel = 0; - RotatingTree_Add(&caller->calls, &self->header); - return self; + ProfilerSubEntry *self; + self = (ProfilerSubEntry*) malloc(sizeof(ProfilerSubEntry)); + if (self == NULL) { + pObj->flags |= POF_NOMEMORY; + return NULL; + } + self->header.key = (void *)entry; + self->tt = 0; + self->it = 0; + self->callcount = 0; + self->recursivecallcount = 0; + self->recursionLevel = 0; + RotatingTree_Add(&caller->calls, &self->header); + return self; } static int freeSubEntry(rotating_node_t *header, void *arg) { - ProfilerSubEntry *subentry = (ProfilerSubEntry*) header; - free(subentry); - return 0; + ProfilerSubEntry *subentry = (ProfilerSubEntry*) header; + free(subentry); + return 0; } static int freeEntry(rotating_node_t *header, void *arg) { - ProfilerEntry *entry = (ProfilerEntry*) header; - RotatingTree_Enum(entry->calls, freeSubEntry, NULL); - Py_DECREF(entry->userObj); - free(entry); - return 0; + ProfilerEntry *entry = (ProfilerEntry*) header; + RotatingTree_Enum(entry->calls, freeSubEntry, NULL); + Py_DECREF(entry->userObj); + free(entry); + return 0; } static void clearEntries(ProfilerObject *pObj) { - RotatingTree_Enum(pObj->profilerEntries, freeEntry, NULL); - pObj->profilerEntries = EMPTY_ROTATING_TREE; - /* release the memory hold by the ProfilerContexts */ - if (pObj->currentProfilerContext) { - free(pObj->currentProfilerContext); - pObj->currentProfilerContext = NULL; - } - while (pObj->freelistProfilerContext) { - ProfilerContext *c = pObj->freelistProfilerContext; - pObj->freelistProfilerContext = c->previous; - free(c); - } - pObj->freelistProfilerContext = NULL; + RotatingTree_Enum(pObj->profilerEntries, freeEntry, NULL); + pObj->profilerEntries = EMPTY_ROTATING_TREE; + /* release the memory hold by the ProfilerContexts */ + if (pObj->currentProfilerContext) { + free(pObj->currentProfilerContext); + pObj->currentProfilerContext = NULL; + } + while (pObj->freelistProfilerContext) { + ProfilerContext *c = pObj->freelistProfilerContext; + pObj->freelistProfilerContext = c->previous; + free(c); + } + pObj->freelistProfilerContext = NULL; } static void initContext(ProfilerObject *pObj, ProfilerContext *self, ProfilerEntry *entry) { - self->ctxEntry = entry; - self->subt = 0; - self->previous = pObj->currentProfilerContext; - pObj->currentProfilerContext = self; - ++entry->recursionLevel; - if ((pObj->flags & POF_SUBCALLS) && self->previous) { - /* find or create an entry for me in my caller's entry */ - ProfilerEntry *caller = self->previous->ctxEntry; - ProfilerSubEntry *subentry = getSubEntry(pObj, caller, entry); - if (subentry == NULL) - subentry = newSubEntry(pObj, caller, entry); - if (subentry) - ++subentry->recursionLevel; - } - self->t0 = CALL_TIMER(pObj); + self->ctxEntry = entry; + self->subt = 0; + self->previous = pObj->currentProfilerContext; + pObj->currentProfilerContext = self; + ++entry->recursionLevel; + if ((pObj->flags & POF_SUBCALLS) && self->previous) { + /* find or create an entry for me in my caller's entry */ + ProfilerEntry *caller = self->previous->ctxEntry; + ProfilerSubEntry *subentry = getSubEntry(pObj, caller, entry); + if (subentry == NULL) + subentry = newSubEntry(pObj, caller, entry); + if (subentry) + ++subentry->recursionLevel; + } + self->t0 = CALL_TIMER(pObj); } static void Stop(ProfilerObject *pObj, ProfilerContext *self, ProfilerEntry *entry) { - PY_LONG_LONG tt = CALL_TIMER(pObj) - self->t0; - PY_LONG_LONG it = tt - self->subt; - if (self->previous) - self->previous->subt += tt; - pObj->currentProfilerContext = self->previous; - if (--entry->recursionLevel == 0) - entry->tt += tt; - else - ++entry->recursivecallcount; - entry->it += it; - entry->callcount++; - if ((pObj->flags & POF_SUBCALLS) && self->previous) { - /* find or create an entry for me in my caller's entry */ - ProfilerEntry *caller = self->previous->ctxEntry; - ProfilerSubEntry *subentry = getSubEntry(pObj, caller, entry); - if (subentry) { - if (--subentry->recursionLevel == 0) - subentry->tt += tt; - else - ++subentry->recursivecallcount; - subentry->it += it; - ++subentry->callcount; - } - } + PY_LONG_LONG tt = CALL_TIMER(pObj) - self->t0; + PY_LONG_LONG it = tt - self->subt; + if (self->previous) + self->previous->subt += tt; + pObj->currentProfilerContext = self->previous; + if (--entry->recursionLevel == 0) + entry->tt += tt; + else + ++entry->recursivecallcount; + entry->it += it; + entry->callcount++; + if ((pObj->flags & POF_SUBCALLS) && self->previous) { + /* find or create an entry for me in my caller's entry */ + ProfilerEntry *caller = self->previous->ctxEntry; + ProfilerSubEntry *subentry = getSubEntry(pObj, caller, entry); + if (subentry) { + if (--subentry->recursionLevel == 0) + subentry->tt += tt; + else + ++subentry->recursivecallcount; + subentry->it += it; + ++subentry->callcount; + } + } } static void ptrace_enter_call(PyObject *self, void *key, PyObject *userObj) { - /* entering a call to the function identified by 'key' - (which can be a PyCodeObject or a PyMethodDef pointer) */ - ProfilerObject *pObj = (ProfilerObject*)self; - ProfilerEntry *profEntry; - ProfilerContext *pContext; - - /* In the case of entering a generator expression frame via a - * throw (gen_send_ex(.., 1)), we may already have an - * Exception set here. We must not mess around with this - * exception, and some of the code under here assumes that - * PyErr_* is its own to mess around with, so we have to - * save and restore any current exception. */ - PyObject *last_type, *last_value, *last_tb; - PyErr_Fetch(&last_type, &last_value, &last_tb); - - profEntry = getEntry(pObj, key); - if (profEntry == NULL) { - profEntry = newProfilerEntry(pObj, key, userObj); - if (profEntry == NULL) - goto restorePyerr; - } - /* grab a ProfilerContext out of the free list */ - pContext = pObj->freelistProfilerContext; - if (pContext) { - pObj->freelistProfilerContext = pContext->previous; - } - else { - /* free list exhausted, allocate a new one */ - pContext = (ProfilerContext*) - malloc(sizeof(ProfilerContext)); - if (pContext == NULL) { - pObj->flags |= POF_NOMEMORY; - goto restorePyerr; - } - } - initContext(pObj, pContext, profEntry); + /* entering a call to the function identified by 'key' + (which can be a PyCodeObject or a PyMethodDef pointer) */ + ProfilerObject *pObj = (ProfilerObject*)self; + ProfilerEntry *profEntry; + ProfilerContext *pContext; + + /* In the case of entering a generator expression frame via a + * throw (gen_send_ex(.., 1)), we may already have an + * Exception set here. We must not mess around with this + * exception, and some of the code under here assumes that + * PyErr_* is its own to mess around with, so we have to + * save and restore any current exception. */ + PyObject *last_type, *last_value, *last_tb; + PyErr_Fetch(&last_type, &last_value, &last_tb); + + profEntry = getEntry(pObj, key); + if (profEntry == NULL) { + profEntry = newProfilerEntry(pObj, key, userObj); + if (profEntry == NULL) + goto restorePyerr; + } + /* grab a ProfilerContext out of the free list */ + pContext = pObj->freelistProfilerContext; + if (pContext) { + pObj->freelistProfilerContext = pContext->previous; + } + else { + /* free list exhausted, allocate a new one */ + pContext = (ProfilerContext*) + malloc(sizeof(ProfilerContext)); + if (pContext == NULL) { + pObj->flags |= POF_NOMEMORY; + goto restorePyerr; + } + } + initContext(pObj, pContext, profEntry); restorePyerr: - PyErr_Restore(last_type, last_value, last_tb); + PyErr_Restore(last_type, last_value, last_tb); } static void ptrace_leave_call(PyObject *self, void *key) { - /* leaving a call to the function identified by 'key' */ - ProfilerObject *pObj = (ProfilerObject*)self; - ProfilerEntry *profEntry; - ProfilerContext *pContext; - - pContext = pObj->currentProfilerContext; - if (pContext == NULL) - return; - profEntry = getEntry(pObj, key); - if (profEntry) { - Stop(pObj, pContext, profEntry); - } - else { - pObj->currentProfilerContext = pContext->previous; - } - /* put pContext into the free list */ - pContext->previous = pObj->freelistProfilerContext; - pObj->freelistProfilerContext = pContext; + /* leaving a call to the function identified by 'key' */ + ProfilerObject *pObj = (ProfilerObject*)self; + ProfilerEntry *profEntry; + ProfilerContext *pContext; + + pContext = pObj->currentProfilerContext; + if (pContext == NULL) + return; + profEntry = getEntry(pObj, key); + if (profEntry) { + Stop(pObj, pContext, profEntry); + } + else { + pObj->currentProfilerContext = pContext->previous; + } + /* put pContext into the free list */ + pContext->previous = pObj->freelistProfilerContext; + pObj->freelistProfilerContext = pContext; } static int profiler_callback(PyObject *self, PyFrameObject *frame, int what, - PyObject *arg) + PyObject *arg) { - switch (what) { + switch (what) { - /* the 'frame' of a called function is about to start its execution */ - case PyTrace_CALL: - ptrace_enter_call(self, (void *)frame->f_code, - (PyObject *)frame->f_code); - break; - - /* the 'frame' of a called function is about to finish - (either normally or with an exception) */ - case PyTrace_RETURN: - ptrace_leave_call(self, (void *)frame->f_code); - break; - - /* case PyTrace_EXCEPTION: - If the exception results in the function exiting, a - PyTrace_RETURN event will be generated, so we don't need to - handle it. */ - -#ifdef PyTrace_C_CALL /* not defined in Python <= 2.3 */ - /* the Python function 'frame' is issuing a call to the built-in - function 'arg' */ - case PyTrace_C_CALL: - if ((((ProfilerObject *)self)->flags & POF_BUILTINS) - && PyCFunction_Check(arg)) { - ptrace_enter_call(self, - ((PyCFunctionObject *)arg)->m_ml, - arg); - } - break; - - /* the call to the built-in function 'arg' is returning into its - caller 'frame' */ - case PyTrace_C_RETURN: /* ...normally */ - case PyTrace_C_EXCEPTION: /* ...with an exception set */ - if ((((ProfilerObject *)self)->flags & POF_BUILTINS) - && PyCFunction_Check(arg)) { - ptrace_leave_call(self, - ((PyCFunctionObject *)arg)->m_ml); - } - break; + /* the 'frame' of a called function is about to start its execution */ + case PyTrace_CALL: + ptrace_enter_call(self, (void *)frame->f_code, + (PyObject *)frame->f_code); + break; + + /* the 'frame' of a called function is about to finish + (either normally or with an exception) */ + case PyTrace_RETURN: + ptrace_leave_call(self, (void *)frame->f_code); + break; + + /* case PyTrace_EXCEPTION: + If the exception results in the function exiting, a + PyTrace_RETURN event will be generated, so we don't need to + handle it. */ + +#ifdef PyTrace_C_CALL /* not defined in Python <= 2.3 */ + /* the Python function 'frame' is issuing a call to the built-in + function 'arg' */ + case PyTrace_C_CALL: + if ((((ProfilerObject *)self)->flags & POF_BUILTINS) + && PyCFunction_Check(arg)) { + ptrace_enter_call(self, + ((PyCFunctionObject *)arg)->m_ml, + arg); + } + break; + + /* the call to the built-in function 'arg' is returning into its + caller 'frame' */ + case PyTrace_C_RETURN: /* ...normally */ + case PyTrace_C_EXCEPTION: /* ...with an exception set */ + if ((((ProfilerObject *)self)->flags & POF_BUILTINS) + && PyCFunction_Check(arg)) { + ptrace_leave_call(self, + ((PyCFunctionObject *)arg)->m_ml); + } + break; #endif - default: - break; - } - return 0; + default: + break; + } + return 0; } static int pending_exception(ProfilerObject *pObj) { - if (pObj->flags & POF_NOMEMORY) { - pObj->flags -= POF_NOMEMORY; - PyErr_SetString(PyExc_MemoryError, - "memory was exhausted while profiling"); - return -1; - } - return 0; + if (pObj->flags & POF_NOMEMORY) { + pObj->flags -= POF_NOMEMORY; + PyErr_SetString(PyExc_MemoryError, + "memory was exhausted while profiling"); + return -1; + } + return 0; } /************************************************************/ static PyStructSequence_Field profiler_entry_fields[] = { - {"code", "code object or built-in function name"}, - {"callcount", "how many times this was called"}, - {"reccallcount", "how many times called recursively"}, - {"totaltime", "total time in this entry"}, - {"inlinetime", "inline time in this entry (not in subcalls)"}, - {"calls", "details of the calls"}, - {0} + {"code", "code object or built-in function name"}, + {"callcount", "how many times this was called"}, + {"reccallcount", "how many times called recursively"}, + {"totaltime", "total time in this entry"}, + {"inlinetime", "inline time in this entry (not in subcalls)"}, + {"calls", "details of the calls"}, + {0} }; static PyStructSequence_Field profiler_subentry_fields[] = { - {"code", "called code object or built-in function name"}, - {"callcount", "how many times this is called"}, - {"reccallcount", "how many times this is called recursively"}, - {"totaltime", "total time spent in this call"}, - {"inlinetime", "inline time (not in further subcalls)"}, - {0} + {"code", "called code object or built-in function name"}, + {"callcount", "how many times this is called"}, + {"reccallcount", "how many times this is called recursively"}, + {"totaltime", "total time spent in this call"}, + {"inlinetime", "inline time (not in further subcalls)"}, + {0} }; static PyStructSequence_Desc profiler_entry_desc = { - "_lsprof.profiler_entry", /* name */ - NULL, /* doc */ - profiler_entry_fields, - 6 + "_lsprof.profiler_entry", /* name */ + NULL, /* doc */ + profiler_entry_fields, + 6 }; static PyStructSequence_Desc profiler_subentry_desc = { - "_lsprof.profiler_subentry", /* name */ - NULL, /* doc */ - profiler_subentry_fields, - 5 + "_lsprof.profiler_subentry", /* name */ + NULL, /* doc */ + profiler_subentry_fields, + 5 }; static int initialized; @@ -538,70 +538,70 @@ typedef struct { - PyObject *list; - PyObject *sublist; - double factor; + PyObject *list; + PyObject *sublist; + double factor; } statscollector_t; static int statsForSubEntry(rotating_node_t *node, void *arg) { - ProfilerSubEntry *sentry = (ProfilerSubEntry*) node; - statscollector_t *collect = (statscollector_t*) arg; - ProfilerEntry *entry = (ProfilerEntry*) sentry->header.key; - int err; - PyObject *sinfo; - sinfo = PyObject_CallFunction((PyObject*) &StatsSubEntryType, - "((Olldd))", - entry->userObj, - sentry->callcount, - sentry->recursivecallcount, - collect->factor * sentry->tt, - collect->factor * sentry->it); - if (sinfo == NULL) - return -1; - err = PyList_Append(collect->sublist, sinfo); - Py_DECREF(sinfo); - return err; + ProfilerSubEntry *sentry = (ProfilerSubEntry*) node; + statscollector_t *collect = (statscollector_t*) arg; + ProfilerEntry *entry = (ProfilerEntry*) sentry->header.key; + int err; + PyObject *sinfo; + sinfo = PyObject_CallFunction((PyObject*) &StatsSubEntryType, + "((Olldd))", + entry->userObj, + sentry->callcount, + sentry->recursivecallcount, + collect->factor * sentry->tt, + collect->factor * sentry->it); + if (sinfo == NULL) + return -1; + err = PyList_Append(collect->sublist, sinfo); + Py_DECREF(sinfo); + return err; } static int statsForEntry(rotating_node_t *node, void *arg) { - ProfilerEntry *entry = (ProfilerEntry*) node; - statscollector_t *collect = (statscollector_t*) arg; - PyObject *info; - int err; - if (entry->callcount == 0) - return 0; /* skip */ - - if (entry->calls != EMPTY_ROTATING_TREE) { - collect->sublist = PyList_New(0); - if (collect->sublist == NULL) - return -1; - if (RotatingTree_Enum(entry->calls, - statsForSubEntry, collect) != 0) { - Py_DECREF(collect->sublist); - return -1; - } - } - else { - Py_INCREF(Py_None); - collect->sublist = Py_None; - } - - info = PyObject_CallFunction((PyObject*) &StatsEntryType, - "((OllddO))", - entry->userObj, - entry->callcount, - entry->recursivecallcount, - collect->factor * entry->tt, - collect->factor * entry->it, - collect->sublist); - Py_DECREF(collect->sublist); - if (info == NULL) - return -1; - err = PyList_Append(collect->list, info); - Py_DECREF(info); - return err; + ProfilerEntry *entry = (ProfilerEntry*) node; + statscollector_t *collect = (statscollector_t*) arg; + PyObject *info; + int err; + if (entry->callcount == 0) + return 0; /* skip */ + + if (entry->calls != EMPTY_ROTATING_TREE) { + collect->sublist = PyList_New(0); + if (collect->sublist == NULL) + return -1; + if (RotatingTree_Enum(entry->calls, + statsForSubEntry, collect) != 0) { + Py_DECREF(collect->sublist); + return -1; + } + } + else { + Py_INCREF(Py_None); + collect->sublist = Py_None; + } + + info = PyObject_CallFunction((PyObject*) &StatsEntryType, + "((OllddO))", + entry->userObj, + entry->callcount, + entry->recursivecallcount, + collect->factor * entry->tt, + collect->factor * entry->it, + collect->sublist); + Py_DECREF(collect->sublist); + if (info == NULL) + return -1; + err = PyList_Append(collect->list, info); + Py_DECREF(info); + return err; } PyDoc_STRVAR(getstats_doc, "\ @@ -631,51 +631,51 @@ static PyObject* profiler_getstats(ProfilerObject *pObj, PyObject* noarg) { - statscollector_t collect; - if (pending_exception(pObj)) - return NULL; - if (!pObj->externalTimer) - collect.factor = hpTimerUnit(); - else if (pObj->externalTimerUnit > 0.0) - collect.factor = pObj->externalTimerUnit; - else - collect.factor = 1.0 / DOUBLE_TIMER_PRECISION; - collect.list = PyList_New(0); - if (collect.list == NULL) - return NULL; - if (RotatingTree_Enum(pObj->profilerEntries, statsForEntry, &collect) - != 0) { - Py_DECREF(collect.list); - return NULL; - } - return collect.list; + statscollector_t collect; + if (pending_exception(pObj)) + return NULL; + if (!pObj->externalTimer) + collect.factor = hpTimerUnit(); + else if (pObj->externalTimerUnit > 0.0) + collect.factor = pObj->externalTimerUnit; + else + collect.factor = 1.0 / DOUBLE_TIMER_PRECISION; + collect.list = PyList_New(0); + if (collect.list == NULL) + return NULL; + if (RotatingTree_Enum(pObj->profilerEntries, statsForEntry, &collect) + != 0) { + Py_DECREF(collect.list); + return NULL; + } + return collect.list; } static int setSubcalls(ProfilerObject *pObj, int nvalue) { - if (nvalue == 0) - pObj->flags &= ~POF_SUBCALLS; - else if (nvalue > 0) - pObj->flags |= POF_SUBCALLS; - return 0; + if (nvalue == 0) + pObj->flags &= ~POF_SUBCALLS; + else if (nvalue > 0) + pObj->flags |= POF_SUBCALLS; + return 0; } static int setBuiltins(ProfilerObject *pObj, int nvalue) { - if (nvalue == 0) - pObj->flags &= ~POF_BUILTINS; - else if (nvalue > 0) { + if (nvalue == 0) + pObj->flags &= ~POF_BUILTINS; + else if (nvalue > 0) { #ifndef PyTrace_C_CALL - PyErr_SetString(PyExc_ValueError, - "builtins=True requires Python >= 2.4"); - return -1; + PyErr_SetString(PyExc_ValueError, + "builtins=True requires Python >= 2.4"); + return -1; #else - pObj->flags |= POF_BUILTINS; + pObj->flags |= POF_BUILTINS; #endif - } - return 0; + } + return 0; } PyDoc_STRVAR(enable_doc, "\ @@ -691,33 +691,33 @@ static PyObject* profiler_enable(ProfilerObject *self, PyObject *args, PyObject *kwds) { - int subcalls = -1; - int builtins = -1; - static char *kwlist[] = {"subcalls", "builtins", 0}; - if (!PyArg_ParseTupleAndKeywords(args, kwds, "|ii:enable", - kwlist, &subcalls, &builtins)) - return NULL; - if (setSubcalls(self, subcalls) < 0 || setBuiltins(self, builtins) < 0) - return NULL; - PyEval_SetProfile(profiler_callback, (PyObject*)self); - self->flags |= POF_ENABLED; - Py_INCREF(Py_None); - return Py_None; + int subcalls = -1; + int builtins = -1; + static char *kwlist[] = {"subcalls", "builtins", 0}; + if (!PyArg_ParseTupleAndKeywords(args, kwds, "|ii:enable", + kwlist, &subcalls, &builtins)) + return NULL; + if (setSubcalls(self, subcalls) < 0 || setBuiltins(self, builtins) < 0) + return NULL; + PyEval_SetProfile(profiler_callback, (PyObject*)self); + self->flags |= POF_ENABLED; + Py_INCREF(Py_None); + return Py_None; } static void flush_unmatched(ProfilerObject *pObj) { - while (pObj->currentProfilerContext) { - ProfilerContext *pContext = pObj->currentProfilerContext; - ProfilerEntry *profEntry= pContext->ctxEntry; - if (profEntry) - Stop(pObj, pContext, profEntry); - else - pObj->currentProfilerContext = pContext->previous; - if (pContext) - free(pContext); - } + while (pObj->currentProfilerContext) { + ProfilerContext *pContext = pObj->currentProfilerContext; + ProfilerEntry *profEntry= pContext->ctxEntry; + if (profEntry) + Stop(pObj, pContext, profEntry); + else + pObj->currentProfilerContext = pContext->previous; + if (pContext) + free(pContext); + } } @@ -730,13 +730,13 @@ static PyObject* profiler_disable(ProfilerObject *self, PyObject* noarg) { - self->flags &= ~POF_ENABLED; - PyEval_SetProfile(NULL, NULL); - flush_unmatched(self); - if (pending_exception(self)) - return NULL; - Py_INCREF(Py_None); - return Py_None; + self->flags &= ~POF_ENABLED; + PyEval_SetProfile(NULL, NULL); + flush_unmatched(self); + if (pending_exception(self)) + return NULL; + Py_INCREF(Py_None); + return Py_None; } PyDoc_STRVAR(clear_doc, "\ @@ -748,62 +748,62 @@ static PyObject* profiler_clear(ProfilerObject *pObj, PyObject* noarg) { - clearEntries(pObj); - Py_INCREF(Py_None); - return Py_None; + clearEntries(pObj); + Py_INCREF(Py_None); + return Py_None; } static void profiler_dealloc(ProfilerObject *op) { - if (op->flags & POF_ENABLED) - PyEval_SetProfile(NULL, NULL); - flush_unmatched(op); - clearEntries(op); - Py_XDECREF(op->externalTimer); - Py_TYPE(op)->tp_free(op); + if (op->flags & POF_ENABLED) + PyEval_SetProfile(NULL, NULL); + flush_unmatched(op); + clearEntries(op); + Py_XDECREF(op->externalTimer); + Py_TYPE(op)->tp_free(op); } static int profiler_init(ProfilerObject *pObj, PyObject *args, PyObject *kw) { - PyObject *o; - PyObject *timer = NULL; - double timeunit = 0.0; - int subcalls = 1; + PyObject *o; + PyObject *timer = NULL; + double timeunit = 0.0; + int subcalls = 1; #ifdef PyTrace_C_CALL - int builtins = 1; + int builtins = 1; #else - int builtins = 0; + int builtins = 0; #endif - static char *kwlist[] = {"timer", "timeunit", - "subcalls", "builtins", 0}; + static char *kwlist[] = {"timer", "timeunit", + "subcalls", "builtins", 0}; - if (!PyArg_ParseTupleAndKeywords(args, kw, "|Odii:Profiler", kwlist, - &timer, &timeunit, - &subcalls, &builtins)) - return -1; - - if (setSubcalls(pObj, subcalls) < 0 || setBuiltins(pObj, builtins) < 0) - return -1; - o = pObj->externalTimer; - pObj->externalTimer = timer; - Py_XINCREF(timer); - Py_XDECREF(o); - pObj->externalTimerUnit = timeunit; - return 0; + if (!PyArg_ParseTupleAndKeywords(args, kw, "|Odii:Profiler", kwlist, + &timer, &timeunit, + &subcalls, &builtins)) + return -1; + + if (setSubcalls(pObj, subcalls) < 0 || setBuiltins(pObj, builtins) < 0) + return -1; + o = pObj->externalTimer; + pObj->externalTimer = timer; + Py_XINCREF(timer); + Py_XDECREF(o); + pObj->externalTimerUnit = timeunit; + return 0; } static PyMethodDef profiler_methods[] = { - {"getstats", (PyCFunction)profiler_getstats, - METH_NOARGS, getstats_doc}, - {"enable", (PyCFunction)profiler_enable, - METH_VARARGS | METH_KEYWORDS, enable_doc}, - {"disable", (PyCFunction)profiler_disable, - METH_NOARGS, disable_doc}, - {"clear", (PyCFunction)profiler_clear, - METH_NOARGS, clear_doc}, - {NULL, NULL} + {"getstats", (PyCFunction)profiler_getstats, + METH_NOARGS, getstats_doc}, + {"enable", (PyCFunction)profiler_enable, + METH_VARARGS | METH_KEYWORDS, enable_doc}, + {"disable", (PyCFunction)profiler_disable, + METH_NOARGS, disable_doc}, + {"clear", (PyCFunction)profiler_clear, + METH_NOARGS, clear_doc}, + {NULL, NULL} }; PyDoc_STRVAR(profiler_doc, "\ @@ -817,89 +817,89 @@ "); static PyTypeObject PyProfiler_Type = { - PyVarObject_HEAD_INIT(NULL, 0) - "_lsprof.Profiler", /* tp_name */ - sizeof(ProfilerObject), /* tp_basicsize */ - 0, /* tp_itemsize */ - (destructor)profiler_dealloc, /* tp_dealloc */ - 0, /* tp_print */ - 0, /* tp_getattr */ - 0, /* tp_setattr */ - 0, /* tp_reserved */ - 0, /* tp_repr */ - 0, /* tp_as_number */ - 0, /* tp_as_sequence */ - 0, /* tp_as_mapping */ - 0, /* tp_hash */ - 0, /* tp_call */ - 0, /* tp_str */ - 0, /* tp_getattro */ - 0, /* tp_setattro */ - 0, /* tp_as_buffer */ - Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */ - profiler_doc, /* tp_doc */ - 0, /* tp_traverse */ - 0, /* tp_clear */ - 0, /* tp_richcompare */ - 0, /* tp_weaklistoffset */ - 0, /* tp_iter */ - 0, /* tp_iternext */ - profiler_methods, /* tp_methods */ - 0, /* tp_members */ - 0, /* tp_getset */ - 0, /* tp_base */ - 0, /* tp_dict */ - 0, /* tp_descr_get */ - 0, /* tp_descr_set */ - 0, /* tp_dictoffset */ - (initproc)profiler_init, /* tp_init */ - PyType_GenericAlloc, /* tp_alloc */ - PyType_GenericNew, /* tp_new */ - PyObject_Del, /* tp_free */ + PyVarObject_HEAD_INIT(NULL, 0) + "_lsprof.Profiler", /* tp_name */ + sizeof(ProfilerObject), /* tp_basicsize */ + 0, /* tp_itemsize */ + (destructor)profiler_dealloc, /* tp_dealloc */ + 0, /* tp_print */ + 0, /* tp_getattr */ + 0, /* tp_setattr */ + 0, /* tp_reserved */ + 0, /* tp_repr */ + 0, /* tp_as_number */ + 0, /* tp_as_sequence */ + 0, /* tp_as_mapping */ + 0, /* tp_hash */ + 0, /* tp_call */ + 0, /* tp_str */ + 0, /* tp_getattro */ + 0, /* tp_setattro */ + 0, /* tp_as_buffer */ + Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */ + profiler_doc, /* tp_doc */ + 0, /* tp_traverse */ + 0, /* tp_clear */ + 0, /* tp_richcompare */ + 0, /* tp_weaklistoffset */ + 0, /* tp_iter */ + 0, /* tp_iternext */ + profiler_methods, /* tp_methods */ + 0, /* tp_members */ + 0, /* tp_getset */ + 0, /* tp_base */ + 0, /* tp_dict */ + 0, /* tp_descr_get */ + 0, /* tp_descr_set */ + 0, /* tp_dictoffset */ + (initproc)profiler_init, /* tp_init */ + PyType_GenericAlloc, /* tp_alloc */ + PyType_GenericNew, /* tp_new */ + PyObject_Del, /* tp_free */ }; static PyMethodDef moduleMethods[] = { - {NULL, NULL} + {NULL, NULL} }; static struct PyModuleDef _lsprofmodule = { - PyModuleDef_HEAD_INIT, - "_lsprof", - "Fast profiler", - -1, - moduleMethods, - NULL, - NULL, - NULL, - NULL + PyModuleDef_HEAD_INIT, + "_lsprof", + "Fast profiler", + -1, + moduleMethods, + NULL, + NULL, + NULL, + NULL }; PyMODINIT_FUNC PyInit__lsprof(void) { - PyObject *module, *d; - module = PyModule_Create(&_lsprofmodule); - if (module == NULL) - return NULL; - d = PyModule_GetDict(module); - if (PyType_Ready(&PyProfiler_Type) < 0) - return NULL; - PyDict_SetItemString(d, "Profiler", (PyObject *)&PyProfiler_Type); - - if (!initialized) { - PyStructSequence_InitType(&StatsEntryType, - &profiler_entry_desc); - PyStructSequence_InitType(&StatsSubEntryType, - &profiler_subentry_desc); - } - Py_INCREF((PyObject*) &StatsEntryType); - Py_INCREF((PyObject*) &StatsSubEntryType); - PyModule_AddObject(module, "profiler_entry", - (PyObject*) &StatsEntryType); - PyModule_AddObject(module, "profiler_subentry", - (PyObject*) &StatsSubEntryType); - empty_tuple = PyTuple_New(0); - initialized = 1; - return module; + PyObject *module, *d; + module = PyModule_Create(&_lsprofmodule); + if (module == NULL) + return NULL; + d = PyModule_GetDict(module); + if (PyType_Ready(&PyProfiler_Type) < 0) + return NULL; + PyDict_SetItemString(d, "Profiler", (PyObject *)&PyProfiler_Type); + + if (!initialized) { + PyStructSequence_InitType(&StatsEntryType, + &profiler_entry_desc); + PyStructSequence_InitType(&StatsSubEntryType, + &profiler_subentry_desc); + } + Py_INCREF((PyObject*) &StatsEntryType); + Py_INCREF((PyObject*) &StatsSubEntryType); + PyModule_AddObject(module, "profiler_entry", + (PyObject*) &StatsEntryType); + PyModule_AddObject(module, "profiler_subentry", + (PyObject*) &StatsSubEntryType); + empty_tuple = PyTuple_New(0); + initialized = 1; + return module; } Modified: python/branches/py3k-jit/Modules/_math.c ============================================================================== --- python/branches/py3k-jit/Modules/_math.c (original) +++ python/branches/py3k-jit/Modules/_math.c Mon May 10 23:55:43 2010 @@ -14,7 +14,7 @@ * * Developed at SunPro, a Sun Microsystems, Inc. business. * Permission to use, copy, modify, and distribute this - * software is freely granted, provided that this notice + * software is freely granted, provided that this notice * is preserved. * ==================================================== */ @@ -27,11 +27,11 @@ /* acosh(x) * Method : * Based on - * acosh(x) = log [ x + sqrt(x*x-1) ] + * acosh(x) = log [ x + sqrt(x*x-1) ] * we have - * acosh(x) := log(x)+ln2, if x is large; else - * acosh(x) := log(2x-1/(sqrt(x*x-1)+x)) if x>2; else - * acosh(x) := log1p(t+sqrt(2.0*t+t*t)); where t=x-1. + * acosh(x) := log(x)+ln2, if x is large; else + * acosh(x) := log(2x-1/(sqrt(x*x-1)+x)) if x>2; else + * acosh(x) := log1p(t+sqrt(2.0*t+t*t)); where t=x-1. * * Special cases: * acosh(x) is NaN with signal if x<1. @@ -41,82 +41,82 @@ double _Py_acosh(double x) { - if (Py_IS_NAN(x)) { - return x+x; - } - if (x < 1.) { /* x < 1; return a signaling NaN */ - errno = EDOM; + if (Py_IS_NAN(x)) { + return x+x; + } + if (x < 1.) { /* x < 1; return a signaling NaN */ + errno = EDOM; #ifdef Py_NAN - return Py_NAN; + return Py_NAN; #else - return (x-x)/(x-x); + return (x-x)/(x-x); #endif - } - else if (x >= two_pow_p28) { /* x > 2**28 */ - if (Py_IS_INFINITY(x)) { - return x+x; - } else { - return log(x)+ln2; /* acosh(huge)=log(2x) */ - } - } - else if (x == 1.) { - return 0.0; /* acosh(1) = 0 */ - } - else if (x > 2.) { /* 2 < x < 2**28 */ - double t = x*x; - return log(2.0*x - 1.0 / (x + sqrt(t - 1.0))); - } - else { /* 1 < x <= 2 */ - double t = x - 1.0; - return m_log1p(t + sqrt(2.0*t + t*t)); - } + } + else if (x >= two_pow_p28) { /* x > 2**28 */ + if (Py_IS_INFINITY(x)) { + return x+x; + } else { + return log(x)+ln2; /* acosh(huge)=log(2x) */ + } + } + else if (x == 1.) { + return 0.0; /* acosh(1) = 0 */ + } + else if (x > 2.) { /* 2 < x < 2**28 */ + double t = x*x; + return log(2.0*x - 1.0 / (x + sqrt(t - 1.0))); + } + else { /* 1 < x <= 2 */ + double t = x - 1.0; + return m_log1p(t + sqrt(2.0*t + t*t)); + } } /* asinh(x) * Method : - * Based on - * asinh(x) = sign(x) * log [ |x| + sqrt(x*x+1) ] - * we have - * asinh(x) := x if 1+x*x=1, - * := sign(x)*(log(x)+ln2)) for large |x|, else - * := sign(x)*log(2|x|+1/(|x|+sqrt(x*x+1))) if|x|>2, else - * := sign(x)*log1p(|x| + x^2/(1 + sqrt(1+x^2))) + * Based on + * asinh(x) = sign(x) * log [ |x| + sqrt(x*x+1) ] + * we have + * asinh(x) := x if 1+x*x=1, + * := sign(x)*(log(x)+ln2)) for large |x|, else + * := sign(x)*log(2|x|+1/(|x|+sqrt(x*x+1))) if|x|>2, else + * := sign(x)*log1p(|x| + x^2/(1 + sqrt(1+x^2))) */ double _Py_asinh(double x) -{ - double w; - double absx = fabs(x); - - if (Py_IS_NAN(x) || Py_IS_INFINITY(x)) { - return x+x; - } - if (absx < two_pow_m28) { /* |x| < 2**-28 */ - return x; /* return x inexact except 0 */ - } - if (absx > two_pow_p28) { /* |x| > 2**28 */ - w = log(absx)+ln2; - } - else if (absx > 2.0) { /* 2 < |x| < 2**28 */ - w = log(2.0*absx + 1.0 / (sqrt(x*x + 1.0) + absx)); - } - else { /* 2**-28 <= |x| < 2= */ - double t = x*x; - w = m_log1p(absx + t / (1.0 + sqrt(1.0 + t))); - } - return copysign(w, x); - +{ + double w; + double absx = fabs(x); + + if (Py_IS_NAN(x) || Py_IS_INFINITY(x)) { + return x+x; + } + if (absx < two_pow_m28) { /* |x| < 2**-28 */ + return x; /* return x inexact except 0 */ + } + if (absx > two_pow_p28) { /* |x| > 2**28 */ + w = log(absx)+ln2; + } + else if (absx > 2.0) { /* 2 < |x| < 2**28 */ + w = log(2.0*absx + 1.0 / (sqrt(x*x + 1.0) + absx)); + } + else { /* 2**-28 <= |x| < 2= */ + double t = x*x; + w = m_log1p(absx + t / (1.0 + sqrt(1.0 + t))); + } + return copysign(w, x); + } /* atanh(x) * Method : * 1.Reduced x to positive by atanh(-x) = -atanh(x) * 2.For x>=0.5 - * 1 2x x + * 1 2x x * atanh(x) = --- * log(1 + -------) = 0.5 * log1p(2 * --------) - * 2 1 - x 1 - x + * 2 1 - x 1 - x * * For x<0.5 * atanh(x) = 0.5*log1p(2x+2x*x/(1-x)) @@ -130,32 +130,32 @@ double _Py_atanh(double x) { - double absx; - double t; + double absx; + double t; - if (Py_IS_NAN(x)) { - return x+x; - } - absx = fabs(x); - if (absx >= 1.) { /* |x| >= 1 */ - errno = EDOM; + if (Py_IS_NAN(x)) { + return x+x; + } + absx = fabs(x); + if (absx >= 1.) { /* |x| >= 1 */ + errno = EDOM; #ifdef Py_NAN - return Py_NAN; + return Py_NAN; #else - return x/zero; + return x/zero; #endif - } - if (absx < two_pow_m28) { /* |x| < 2**-28 */ - return x; - } - if (absx < 0.5) { /* |x| < 0.5 */ - t = absx+absx; - t = 0.5 * m_log1p(t + t*absx / (1.0 - absx)); - } - else { /* 0.5 <= |x| <= 1.0 */ - t = 0.5 * m_log1p((absx + absx) / (1.0 - absx)); - } - return copysign(t, x); + } + if (absx < two_pow_m28) { /* |x| < 2**-28 */ + return x; + } + if (absx < 0.5) { /* |x| < 0.5 */ + t = absx+absx; + t = 0.5 * m_log1p(t + t*absx / (1.0 - absx)); + } + else { /* 0.5 <= |x| <= 1.0 */ + t = 0.5 * m_log1p((absx + absx) / (1.0 - absx)); + } + return copysign(t, x); } /* Mathematically, expm1(x) = exp(x) - 1. The expm1 function is designed @@ -173,15 +173,15 @@ */ if (fabs(x) < 0.7) { - double u; - u = exp(x); - if (u == 1.0) - return x; - else - return (u - 1.0) * x / log(u); + double u; + u = exp(x); + if (u == 1.0) + return x; + else + return (u - 1.0) * x / log(u); } else - return exp(x) - 1.0; + return exp(x) - 1.0; } /* log1p(x) = log(1+x). The log1p function is designed to avoid the @@ -194,7 +194,7 @@ /* For x small, we use the following approach. Let y be the nearest float to 1+x, then - 1+x = y * (1 - (y-1-x)/y) + 1+x = y * (1 - (y-1-x)/y) so log(1+x) = log(y) + log(1-(y-1-x)/y). Since (y-1-x)/y is tiny, the second term is well approximated by (y-1-x)/y. If abs(x) >= @@ -213,17 +213,17 @@ double y; if (fabs(x) < DBL_EPSILON/2.) { - return x; + return x; } else if (-0.5 <= x && x <= 1.) { - /* WARNING: it's possible than an overeager compiler - will incorrectly optimize the following two lines - to the equivalent of "return log(1.+x)". If this - happens, then results from log1p will be inaccurate - for small x. */ - y = 1.+x; - return log(y)-((y-1.)-x)/y; + /* WARNING: it's possible than an overeager compiler + will incorrectly optimize the following two lines + to the equivalent of "return log(1.+x)". If this + happens, then results from log1p will be inaccurate + for small x. */ + y = 1.+x; + return log(y)-((y-1.)-x)/y; } else { - /* NaNs and infinities should end up here */ - return log(1.+x); + /* NaNs and infinities should end up here */ + return log(1.+x); } } Modified: python/branches/py3k-jit/Modules/_multiprocessing/connection.h ============================================================================== --- python/branches/py3k-jit/Modules/_multiprocessing/connection.h (original) +++ python/branches/py3k-jit/Modules/_multiprocessing/connection.h Mon May 10 23:55:43 2010 @@ -1,5 +1,5 @@ /* - * Definition of a `Connection` type. + * Definition of a `Connection` type. * Used by `socket_connection.c` and `pipe_connection.c`. * * connection.h @@ -19,14 +19,14 @@ #define CHECK_READABLE(self) \ if (!(self->flags & READABLE)) { \ - PyErr_SetString(PyExc_IOError, "connection is write-only"); \ - return NULL; \ + PyErr_SetString(PyExc_IOError, "connection is write-only"); \ + return NULL; \ } #define CHECK_WRITABLE(self) \ if (!(self->flags & WRITABLE)) { \ - PyErr_SetString(PyExc_IOError, "connection is read-only"); \ - return NULL; \ + PyErr_SetString(PyExc_IOError, "connection is read-only"); \ + return NULL; \ } /* @@ -36,57 +36,57 @@ static PyObject * connection_new(PyTypeObject *type, PyObject *args, PyObject *kwds) { - ConnectionObject *self; - HANDLE handle; - BOOL readable = TRUE, writable = TRUE; - - static char *kwlist[] = {"handle", "readable", "writable", NULL}; - - if (!PyArg_ParseTupleAndKeywords(args, kwds, F_HANDLE "|ii", kwlist, - &handle, &readable, &writable)) - return NULL; - - if (handle == INVALID_HANDLE_VALUE || (Py_ssize_t)handle < 0) { - PyErr_Format(PyExc_IOError, "invalid handle %zd", - (Py_ssize_t)handle); - return NULL; - } - - if (!readable && !writable) { - PyErr_SetString(PyExc_ValueError, - "either readable or writable must be true"); - return NULL; - } - - self = PyObject_New(ConnectionObject, type); - if (self == NULL) - return NULL; - - self->weakreflist = NULL; - self->handle = handle; - self->flags = 0; - - if (readable) - self->flags |= READABLE; - if (writable) - self->flags |= WRITABLE; - assert(self->flags >= 1 && self->flags <= 3); + ConnectionObject *self; + HANDLE handle; + BOOL readable = TRUE, writable = TRUE; + + static char *kwlist[] = {"handle", "readable", "writable", NULL}; + + if (!PyArg_ParseTupleAndKeywords(args, kwds, F_HANDLE "|ii", kwlist, + &handle, &readable, &writable)) + return NULL; + + if (handle == INVALID_HANDLE_VALUE || (Py_ssize_t)handle < 0) { + PyErr_Format(PyExc_IOError, "invalid handle %zd", + (Py_ssize_t)handle); + return NULL; + } + + if (!readable && !writable) { + PyErr_SetString(PyExc_ValueError, + "either readable or writable must be true"); + return NULL; + } - return (PyObject*)self; + self = PyObject_New(ConnectionObject, type); + if (self == NULL) + return NULL; + + self->weakreflist = NULL; + self->handle = handle; + self->flags = 0; + + if (readable) + self->flags |= READABLE; + if (writable) + self->flags |= WRITABLE; + assert(self->flags >= 1 && self->flags <= 3); + + return (PyObject*)self; } static void connection_dealloc(ConnectionObject* self) { - if (self->weakreflist != NULL) - PyObject_ClearWeakRefs((PyObject*)self); + if (self->weakreflist != NULL) + PyObject_ClearWeakRefs((PyObject*)self); - if (self->handle != INVALID_HANDLE_VALUE) { - Py_BEGIN_ALLOW_THREADS - CLOSE(self->handle); - Py_END_ALLOW_THREADS - } - PyObject_Del(self); + if (self->handle != INVALID_HANDLE_VALUE) { + Py_BEGIN_ALLOW_THREADS + CLOSE(self->handle); + Py_END_ALLOW_THREADS + } + PyObject_Del(self); } /* @@ -96,168 +96,168 @@ static PyObject * connection_sendbytes(ConnectionObject *self, PyObject *args) { - Py_buffer pbuffer; - char *buffer; - Py_ssize_t length, offset=0, size=PY_SSIZE_T_MIN; - int res; - - if (!PyArg_ParseTuple(args, F_RBUFFER "*|" F_PY_SSIZE_T F_PY_SSIZE_T, - &pbuffer, &offset, &size)) - return NULL; - buffer = pbuffer.buf; - length = pbuffer.len; - - CHECK_WRITABLE(self); /* XXX release buffer in case of failure */ - - if (offset < 0) { - PyBuffer_Release(&pbuffer); - PyErr_SetString(PyExc_ValueError, "offset is negative"); - return NULL; - } - if (length < offset) { - PyBuffer_Release(&pbuffer); - PyErr_SetString(PyExc_ValueError, "buffer length < offset"); - return NULL; - } - - if (size == PY_SSIZE_T_MIN) { - size = length - offset; - } else { - if (size < 0) { - PyBuffer_Release(&pbuffer); - PyErr_SetString(PyExc_ValueError, "size is negative"); - return NULL; - } - if (offset + size > length) { - PyBuffer_Release(&pbuffer); - PyErr_SetString(PyExc_ValueError, - "buffer length < offset + size"); - return NULL; - } - } - - res = conn_send_string(self, buffer + offset, size); - - PyBuffer_Release(&pbuffer); - if (res < 0) { - if (PyErr_Occurred()) - return NULL; - else - return mp_SetError(PyExc_IOError, res); - } - - Py_RETURN_NONE; -} - -static PyObject * -connection_recvbytes(ConnectionObject *self, PyObject *args) -{ - char *freeme = NULL; - Py_ssize_t res, maxlength = PY_SSIZE_T_MAX; - PyObject *result = NULL; - - if (!PyArg_ParseTuple(args, "|" F_PY_SSIZE_T, &maxlength)) - return NULL; - - CHECK_READABLE(self); - - if (maxlength < 0) { - PyErr_SetString(PyExc_ValueError, "maxlength < 0"); - return NULL; - } - - res = conn_recv_string(self, self->buffer, CONNECTION_BUFFER_SIZE, - &freeme, maxlength); - - if (res < 0) { - if (res == MP_BAD_MESSAGE_LENGTH) { - if ((self->flags & WRITABLE) == 0) { - Py_BEGIN_ALLOW_THREADS - CLOSE(self->handle); - Py_END_ALLOW_THREADS - self->handle = INVALID_HANDLE_VALUE; - } else { - self->flags = WRITABLE; - } - } - mp_SetError(PyExc_IOError, res); - } else { - if (freeme == NULL) { - result = PyBytes_FromStringAndSize(self->buffer, res); - } else { - result = PyBytes_FromStringAndSize(freeme, res); - PyMem_Free(freeme); - } - } - - return result; -} - -static PyObject * -connection_recvbytes_into(ConnectionObject *self, PyObject *args) -{ - char *freeme = NULL, *buffer = NULL; - Py_ssize_t res, length, offset = 0; - PyObject *result = NULL; - Py_buffer pbuf; - - CHECK_READABLE(self); - - if (!PyArg_ParseTuple(args, "w*|" F_PY_SSIZE_T, - &pbuf, &offset)) - return NULL; - - buffer = pbuf.buf; - length = pbuf.len; - - if (offset < 0) { - PyErr_SetString(PyExc_ValueError, "negative offset"); - goto _error; - } - - if (offset > length) { - PyErr_SetString(PyExc_ValueError, "offset too large"); - goto _error; - } - - res = conn_recv_string(self, buffer+offset, length-offset, - &freeme, PY_SSIZE_T_MAX); - - if (res < 0) { - if (res == MP_BAD_MESSAGE_LENGTH) { - if ((self->flags & WRITABLE) == 0) { - Py_BEGIN_ALLOW_THREADS - CLOSE(self->handle); - Py_END_ALLOW_THREADS - self->handle = INVALID_HANDLE_VALUE; - } else { - self->flags = WRITABLE; - } - } - mp_SetError(PyExc_IOError, res); - } else { - if (freeme == NULL) { - result = PyInt_FromSsize_t(res); - } else { - result = PyObject_CallFunction(BufferTooShort, - F_RBUFFER "#", - freeme, res); - PyMem_Free(freeme); - if (result) { - PyErr_SetObject(BufferTooShort, result); - Py_DECREF(result); - } - goto _error; - } - } + Py_buffer pbuffer; + char *buffer; + Py_ssize_t length, offset=0, size=PY_SSIZE_T_MIN; + int res; + + if (!PyArg_ParseTuple(args, F_RBUFFER "*|" F_PY_SSIZE_T F_PY_SSIZE_T, + &pbuffer, &offset, &size)) + return NULL; + buffer = pbuffer.buf; + length = pbuffer.len; + + CHECK_WRITABLE(self); /* XXX release buffer in case of failure */ + + if (offset < 0) { + PyBuffer_Release(&pbuffer); + PyErr_SetString(PyExc_ValueError, "offset is negative"); + return NULL; + } + if (length < offset) { + PyBuffer_Release(&pbuffer); + PyErr_SetString(PyExc_ValueError, "buffer length < offset"); + return NULL; + } + + if (size == PY_SSIZE_T_MIN) { + size = length - offset; + } else { + if (size < 0) { + PyBuffer_Release(&pbuffer); + PyErr_SetString(PyExc_ValueError, "size is negative"); + return NULL; + } + if (offset + size > length) { + PyBuffer_Release(&pbuffer); + PyErr_SetString(PyExc_ValueError, + "buffer length < offset + size"); + return NULL; + } + } + + res = conn_send_string(self, buffer + offset, size); + + PyBuffer_Release(&pbuffer); + if (res < 0) { + if (PyErr_Occurred()) + return NULL; + else + return mp_SetError(PyExc_IOError, res); + } + + Py_RETURN_NONE; +} + +static PyObject * +connection_recvbytes(ConnectionObject *self, PyObject *args) +{ + char *freeme = NULL; + Py_ssize_t res, maxlength = PY_SSIZE_T_MAX; + PyObject *result = NULL; + + if (!PyArg_ParseTuple(args, "|" F_PY_SSIZE_T, &maxlength)) + return NULL; + + CHECK_READABLE(self); + + if (maxlength < 0) { + PyErr_SetString(PyExc_ValueError, "maxlength < 0"); + return NULL; + } + + res = conn_recv_string(self, self->buffer, CONNECTION_BUFFER_SIZE, + &freeme, maxlength); + + if (res < 0) { + if (res == MP_BAD_MESSAGE_LENGTH) { + if ((self->flags & WRITABLE) == 0) { + Py_BEGIN_ALLOW_THREADS + CLOSE(self->handle); + Py_END_ALLOW_THREADS + self->handle = INVALID_HANDLE_VALUE; + } else { + self->flags = WRITABLE; + } + } + mp_SetError(PyExc_IOError, res); + } else { + if (freeme == NULL) { + result = PyBytes_FromStringAndSize(self->buffer, res); + } else { + result = PyBytes_FromStringAndSize(freeme, res); + PyMem_Free(freeme); + } + } + + return result; +} + +static PyObject * +connection_recvbytes_into(ConnectionObject *self, PyObject *args) +{ + char *freeme = NULL, *buffer = NULL; + Py_ssize_t res, length, offset = 0; + PyObject *result = NULL; + Py_buffer pbuf; + + CHECK_READABLE(self); + + if (!PyArg_ParseTuple(args, "w*|" F_PY_SSIZE_T, + &pbuf, &offset)) + return NULL; + + buffer = pbuf.buf; + length = pbuf.len; + + if (offset < 0) { + PyErr_SetString(PyExc_ValueError, "negative offset"); + goto _error; + } + + if (offset > length) { + PyErr_SetString(PyExc_ValueError, "offset too large"); + goto _error; + } + + res = conn_recv_string(self, buffer+offset, length-offset, + &freeme, PY_SSIZE_T_MAX); + + if (res < 0) { + if (res == MP_BAD_MESSAGE_LENGTH) { + if ((self->flags & WRITABLE) == 0) { + Py_BEGIN_ALLOW_THREADS + CLOSE(self->handle); + Py_END_ALLOW_THREADS + self->handle = INVALID_HANDLE_VALUE; + } else { + self->flags = WRITABLE; + } + } + mp_SetError(PyExc_IOError, res); + } else { + if (freeme == NULL) { + result = PyInt_FromSsize_t(res); + } else { + result = PyObject_CallFunction(BufferTooShort, + F_RBUFFER "#", + freeme, res); + PyMem_Free(freeme); + if (result) { + PyErr_SetObject(BufferTooShort, result); + Py_DECREF(result); + } + goto _error; + } + } _cleanup: - PyBuffer_Release(&pbuf); - return result; + PyBuffer_Release(&pbuf); + return result; _error: - result = NULL; - goto _cleanup; + result = NULL; + goto _cleanup; } /* @@ -267,74 +267,74 @@ static PyObject * connection_send_obj(ConnectionObject *self, PyObject *obj) { - char *buffer; - int res; - Py_ssize_t length; - PyObject *pickled_string = NULL; - - CHECK_WRITABLE(self); - - pickled_string = PyObject_CallFunctionObjArgs(pickle_dumps, obj, - pickle_protocol, NULL); - if (!pickled_string) - goto failure; - - if (PyBytes_AsStringAndSize(pickled_string, &buffer, &length) < 0) - goto failure; - - res = conn_send_string(self, buffer, (int)length); - - if (res < 0) { - mp_SetError(PyExc_IOError, res); - goto failure; - } + char *buffer; + int res; + Py_ssize_t length; + PyObject *pickled_string = NULL; + + CHECK_WRITABLE(self); + + pickled_string = PyObject_CallFunctionObjArgs(pickle_dumps, obj, + pickle_protocol, NULL); + if (!pickled_string) + goto failure; + + if (PyBytes_AsStringAndSize(pickled_string, &buffer, &length) < 0) + goto failure; + + res = conn_send_string(self, buffer, (int)length); + + if (res < 0) { + mp_SetError(PyExc_IOError, res); + goto failure; + } - Py_XDECREF(pickled_string); - Py_RETURN_NONE; + Py_XDECREF(pickled_string); + Py_RETURN_NONE; failure: - Py_XDECREF(pickled_string); - return NULL; + Py_XDECREF(pickled_string); + return NULL; } static PyObject * connection_recv_obj(ConnectionObject *self) { - char *freeme = NULL; - Py_ssize_t res; - PyObject *temp = NULL, *result = NULL; - - CHECK_READABLE(self); - - res = conn_recv_string(self, self->buffer, CONNECTION_BUFFER_SIZE, - &freeme, PY_SSIZE_T_MAX); - - if (res < 0) { - if (res == MP_BAD_MESSAGE_LENGTH) { - if ((self->flags & WRITABLE) == 0) { - Py_BEGIN_ALLOW_THREADS - CLOSE(self->handle); - Py_END_ALLOW_THREADS - self->handle = INVALID_HANDLE_VALUE; - } else { - self->flags = WRITABLE; - } - } - mp_SetError(PyExc_IOError, res); - } else { - if (freeme == NULL) { - temp = PyBytes_FromStringAndSize(self->buffer, res); - } else { - temp = PyBytes_FromStringAndSize(freeme, res); - PyMem_Free(freeme); - } - } - - if (temp) - result = PyObject_CallFunctionObjArgs(pickle_loads, - temp, NULL); - Py_XDECREF(temp); - return result; + char *freeme = NULL; + Py_ssize_t res; + PyObject *temp = NULL, *result = NULL; + + CHECK_READABLE(self); + + res = conn_recv_string(self, self->buffer, CONNECTION_BUFFER_SIZE, + &freeme, PY_SSIZE_T_MAX); + + if (res < 0) { + if (res == MP_BAD_MESSAGE_LENGTH) { + if ((self->flags & WRITABLE) == 0) { + Py_BEGIN_ALLOW_THREADS + CLOSE(self->handle); + Py_END_ALLOW_THREADS + self->handle = INVALID_HANDLE_VALUE; + } else { + self->flags = WRITABLE; + } + } + mp_SetError(PyExc_IOError, res); + } else { + if (freeme == NULL) { + temp = PyBytes_FromStringAndSize(self->buffer, res); + } else { + temp = PyBytes_FromStringAndSize(freeme, res); + PyMem_Free(freeme); + } + } + + if (temp) + result = PyObject_CallFunctionObjArgs(pickle_loads, + temp, NULL); + Py_XDECREF(temp); + return result; } /* @@ -344,73 +344,73 @@ static PyObject * connection_poll(ConnectionObject *self, PyObject *args) { - PyObject *timeout_obj = NULL; - double timeout = 0.0; - int res; - - CHECK_READABLE(self); - - if (!PyArg_ParseTuple(args, "|O", &timeout_obj)) - return NULL; - - if (timeout_obj == NULL) { - timeout = 0.0; - } else if (timeout_obj == Py_None) { - timeout = -1.0; /* block forever */ - } else { - timeout = PyFloat_AsDouble(timeout_obj); - if (PyErr_Occurred()) - return NULL; - if (timeout < 0.0) - timeout = 0.0; - } - - Py_BEGIN_ALLOW_THREADS - res = conn_poll(self, timeout, _save); - Py_END_ALLOW_THREADS - - switch (res) { - case TRUE: - Py_RETURN_TRUE; - case FALSE: - Py_RETURN_FALSE; - default: - return mp_SetError(PyExc_IOError, res); - } + PyObject *timeout_obj = NULL; + double timeout = 0.0; + int res; + + CHECK_READABLE(self); + + if (!PyArg_ParseTuple(args, "|O", &timeout_obj)) + return NULL; + + if (timeout_obj == NULL) { + timeout = 0.0; + } else if (timeout_obj == Py_None) { + timeout = -1.0; /* block forever */ + } else { + timeout = PyFloat_AsDouble(timeout_obj); + if (PyErr_Occurred()) + return NULL; + if (timeout < 0.0) + timeout = 0.0; + } + + Py_BEGIN_ALLOW_THREADS + res = conn_poll(self, timeout, _save); + Py_END_ALLOW_THREADS + + switch (res) { + case TRUE: + Py_RETURN_TRUE; + case FALSE: + Py_RETURN_FALSE; + default: + return mp_SetError(PyExc_IOError, res); + } } static PyObject * connection_fileno(ConnectionObject* self) { - if (self->handle == INVALID_HANDLE_VALUE) { - PyErr_SetString(PyExc_IOError, "handle is invalid"); - return NULL; - } - return PyInt_FromLong((long)self->handle); + if (self->handle == INVALID_HANDLE_VALUE) { + PyErr_SetString(PyExc_IOError, "handle is invalid"); + return NULL; + } + return PyInt_FromLong((long)self->handle); } static PyObject * connection_close(ConnectionObject *self) { - if (self->handle != INVALID_HANDLE_VALUE) { - Py_BEGIN_ALLOW_THREADS - CLOSE(self->handle); - Py_END_ALLOW_THREADS - self->handle = INVALID_HANDLE_VALUE; - } + if (self->handle != INVALID_HANDLE_VALUE) { + Py_BEGIN_ALLOW_THREADS + CLOSE(self->handle); + Py_END_ALLOW_THREADS + self->handle = INVALID_HANDLE_VALUE; + } - Py_RETURN_NONE; + Py_RETURN_NONE; } static PyObject * connection_repr(ConnectionObject *self) { - static char *conn_type[] = {"read-only", "write-only", "read-write"}; + static char *conn_type[] = {"read-only", "write-only", "read-write"}; - assert(self->flags >= 1 && self->flags <= 3); - return FROM_FORMAT("<%s %s, handle %zd>", - conn_type[self->flags - 1], - CONNECTION_NAME, (Py_ssize_t)self->handle); + assert(self->flags >= 1 && self->flags <= 3); + return FROM_FORMAT("<%s %s, handle %zd>", + conn_type[self->flags - 1], + CONNECTION_NAME, (Py_ssize_t)self->handle); } /* @@ -420,19 +420,19 @@ static PyObject * connection_closed(ConnectionObject *self, void *closure) { - return PyBool_FromLong((long)(self->handle == INVALID_HANDLE_VALUE)); + return PyBool_FromLong((long)(self->handle == INVALID_HANDLE_VALUE)); } static PyObject * connection_readable(ConnectionObject *self, void *closure) { - return PyBool_FromLong((long)(self->flags & READABLE)); + return PyBool_FromLong((long)(self->flags & READABLE)); } static PyObject * connection_writable(ConnectionObject *self, void *closure) { - return PyBool_FromLong((long)(self->flags & WRITABLE)); + return PyBool_FromLong((long)(self->flags & WRITABLE)); } /* @@ -440,37 +440,37 @@ */ static PyMethodDef connection_methods[] = { - {"send_bytes", (PyCFunction)connection_sendbytes, METH_VARARGS, - "send the byte data from a readable buffer-like object"}, - {"recv_bytes", (PyCFunction)connection_recvbytes, METH_VARARGS, - "receive byte data as a string"}, - {"recv_bytes_into",(PyCFunction)connection_recvbytes_into,METH_VARARGS, - "receive byte data into a writeable buffer-like object\n" - "returns the number of bytes read"}, - - {"send", (PyCFunction)connection_send_obj, METH_O, - "send a (picklable) object"}, - {"recv", (PyCFunction)connection_recv_obj, METH_NOARGS, - "receive a (picklable) object"}, - - {"poll", (PyCFunction)connection_poll, METH_VARARGS, - "whether there is any input available to be read"}, - {"fileno", (PyCFunction)connection_fileno, METH_NOARGS, - "file descriptor or handle of the connection"}, - {"close", (PyCFunction)connection_close, METH_NOARGS, - "close the connection"}, + {"send_bytes", (PyCFunction)connection_sendbytes, METH_VARARGS, + "send the byte data from a readable buffer-like object"}, + {"recv_bytes", (PyCFunction)connection_recvbytes, METH_VARARGS, + "receive byte data as a string"}, + {"recv_bytes_into",(PyCFunction)connection_recvbytes_into,METH_VARARGS, + "receive byte data into a writeable buffer-like object\n" + "returns the number of bytes read"}, + + {"send", (PyCFunction)connection_send_obj, METH_O, + "send a (picklable) object"}, + {"recv", (PyCFunction)connection_recv_obj, METH_NOARGS, + "receive a (picklable) object"}, + + {"poll", (PyCFunction)connection_poll, METH_VARARGS, + "whether there is any input available to be read"}, + {"fileno", (PyCFunction)connection_fileno, METH_NOARGS, + "file descriptor or handle of the connection"}, + {"close", (PyCFunction)connection_close, METH_NOARGS, + "close the connection"}, - {NULL} /* Sentinel */ + {NULL} /* Sentinel */ }; static PyGetSetDef connection_getset[] = { - {"closed", (getter)connection_closed, NULL, - "True if the connection is closed", NULL}, - {"readable", (getter)connection_readable, NULL, - "True if the connection is readable", NULL}, - {"writable", (getter)connection_writable, NULL, - "True if the connection is writable", NULL}, - {NULL} + {"closed", (getter)connection_closed, NULL, + "True if the connection is closed", NULL}, + {"readable", (getter)connection_readable, NULL, + "True if the connection is readable", NULL}, + {"writable", (getter)connection_writable, NULL, + "True if the connection is writable", NULL}, + {NULL} }; /* @@ -478,50 +478,50 @@ */ PyDoc_STRVAR(connection_doc, - "Connection type whose constructor signature is\n\n" - " Connection(handle, readable=True, writable=True).\n\n" - "The constructor does *not* duplicate the handle."); + "Connection type whose constructor signature is\n\n" + " Connection(handle, readable=True, writable=True).\n\n" + "The constructor does *not* duplicate the handle."); PyTypeObject CONNECTION_TYPE = { - PyVarObject_HEAD_INIT(NULL, 0) - /* tp_name */ "_multiprocessing." CONNECTION_NAME, - /* tp_basicsize */ sizeof(ConnectionObject), - /* tp_itemsize */ 0, - /* tp_dealloc */ (destructor)connection_dealloc, - /* tp_print */ 0, - /* tp_getattr */ 0, - /* tp_setattr */ 0, - /* tp_reserved */ 0, - /* tp_repr */ (reprfunc)connection_repr, - /* tp_as_number */ 0, - /* tp_as_sequence */ 0, - /* tp_as_mapping */ 0, - /* tp_hash */ 0, - /* tp_call */ 0, - /* tp_str */ 0, - /* tp_getattro */ 0, - /* tp_setattro */ 0, - /* tp_as_buffer */ 0, - /* tp_flags */ Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | - Py_TPFLAGS_HAVE_WEAKREFS, - /* tp_doc */ connection_doc, - /* tp_traverse */ 0, - /* tp_clear */ 0, - /* tp_richcompare */ 0, - /* tp_weaklistoffset */ offsetof(ConnectionObject, weakreflist), - /* tp_iter */ 0, - /* tp_iternext */ 0, - /* tp_methods */ connection_methods, - /* tp_members */ 0, - /* tp_getset */ connection_getset, - /* tp_base */ 0, - /* tp_dict */ 0, - /* tp_descr_get */ 0, - /* tp_descr_set */ 0, - /* tp_dictoffset */ 0, - /* tp_init */ 0, - /* tp_alloc */ 0, - /* tp_new */ connection_new, + PyVarObject_HEAD_INIT(NULL, 0) + /* tp_name */ "_multiprocessing." CONNECTION_NAME, + /* tp_basicsize */ sizeof(ConnectionObject), + /* tp_itemsize */ 0, + /* tp_dealloc */ (destructor)connection_dealloc, + /* tp_print */ 0, + /* tp_getattr */ 0, + /* tp_setattr */ 0, + /* tp_reserved */ 0, + /* tp_repr */ (reprfunc)connection_repr, + /* tp_as_number */ 0, + /* tp_as_sequence */ 0, + /* tp_as_mapping */ 0, + /* tp_hash */ 0, + /* tp_call */ 0, + /* tp_str */ 0, + /* tp_getattro */ 0, + /* tp_setattro */ 0, + /* tp_as_buffer */ 0, + /* tp_flags */ Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | + Py_TPFLAGS_HAVE_WEAKREFS, + /* tp_doc */ connection_doc, + /* tp_traverse */ 0, + /* tp_clear */ 0, + /* tp_richcompare */ 0, + /* tp_weaklistoffset */ offsetof(ConnectionObject, weakreflist), + /* tp_iter */ 0, + /* tp_iternext */ 0, + /* tp_methods */ connection_methods, + /* tp_members */ 0, + /* tp_getset */ connection_getset, + /* tp_base */ 0, + /* tp_dict */ 0, + /* tp_descr_get */ 0, + /* tp_descr_set */ 0, + /* tp_dictoffset */ 0, + /* tp_init */ 0, + /* tp_alloc */ 0, + /* tp_new */ connection_new, }; #endif /* CONNECTION_H */ Modified: python/branches/py3k-jit/Modules/_multiprocessing/multiprocessing.c ============================================================================== --- python/branches/py3k-jit/Modules/_multiprocessing/multiprocessing.c (original) +++ python/branches/py3k-jit/Modules/_multiprocessing/multiprocessing.c Mon May 10 23:55:43 2010 @@ -9,9 +9,9 @@ #include "multiprocessing.h" #ifdef SCM_RIGHTS - #define HAVE_FD_TRANSFER 1 + #define HAVE_FD_TRANSFER 1 #else - #define HAVE_FD_TRANSFER 0 + #define HAVE_FD_TRANSFER 0 #endif PyObject *create_win32_namespace(void); @@ -26,46 +26,46 @@ PyObject * mp_SetError(PyObject *Type, int num) { - switch (num) { + switch (num) { #ifdef MS_WINDOWS - case MP_STANDARD_ERROR: - if (Type == NULL) - Type = PyExc_WindowsError; - PyErr_SetExcFromWindowsErr(Type, 0); - break; - case MP_SOCKET_ERROR: - if (Type == NULL) - Type = PyExc_WindowsError; - PyErr_SetExcFromWindowsErr(Type, WSAGetLastError()); - break; + case MP_STANDARD_ERROR: + if (Type == NULL) + Type = PyExc_WindowsError; + PyErr_SetExcFromWindowsErr(Type, 0); + break; + case MP_SOCKET_ERROR: + if (Type == NULL) + Type = PyExc_WindowsError; + PyErr_SetExcFromWindowsErr(Type, WSAGetLastError()); + break; #else /* !MS_WINDOWS */ - case MP_STANDARD_ERROR: - case MP_SOCKET_ERROR: - if (Type == NULL) - Type = PyExc_OSError; - PyErr_SetFromErrno(Type); - break; + case MP_STANDARD_ERROR: + case MP_SOCKET_ERROR: + if (Type == NULL) + Type = PyExc_OSError; + PyErr_SetFromErrno(Type); + break; #endif /* !MS_WINDOWS */ - case MP_MEMORY_ERROR: - PyErr_NoMemory(); - break; - case MP_END_OF_FILE: - PyErr_SetNone(PyExc_EOFError); - break; - case MP_EARLY_END_OF_FILE: - PyErr_SetString(PyExc_IOError, - "got end of file during message"); - break; - case MP_BAD_MESSAGE_LENGTH: - PyErr_SetString(PyExc_IOError, "bad message length"); - break; - case MP_EXCEPTION_HAS_BEEN_SET: - break; - default: - PyErr_Format(PyExc_RuntimeError, - "unkown error number %d", num); - } - return NULL; + case MP_MEMORY_ERROR: + PyErr_NoMemory(); + break; + case MP_END_OF_FILE: + PyErr_SetNone(PyExc_EOFError); + break; + case MP_EARLY_END_OF_FILE: + PyErr_SetString(PyExc_IOError, + "got end of file during message"); + break; + case MP_BAD_MESSAGE_LENGTH: + PyErr_SetString(PyExc_IOError, "bad message length"); + break; + case MP_EXCEPTION_HAS_BEEN_SET: + break; + default: + PyErr_Format(PyExc_RuntimeError, + "unkown error number %d", num); + } + return NULL; } @@ -82,8 +82,8 @@ static BOOL WINAPI ProcessingCtrlHandler(DWORD dwCtrlType) { - SetEvent(sigint_event); - return FALSE; + SetEvent(sigint_event); + return FALSE; } /* @@ -101,72 +101,72 @@ static PyObject * multiprocessing_sendfd(PyObject *self, PyObject *args) { - int conn, fd, res; - char dummy_char; - char buf[CMSG_SPACE(sizeof(int))]; - struct msghdr msg = {0}; - struct iovec dummy_iov; - struct cmsghdr *cmsg; - - if (!PyArg_ParseTuple(args, "ii", &conn, &fd)) - return NULL; - - dummy_iov.iov_base = &dummy_char; - dummy_iov.iov_len = 1; - msg.msg_control = buf; - msg.msg_controllen = sizeof(buf); - msg.msg_iov = &dummy_iov; - msg.msg_iovlen = 1; - cmsg = CMSG_FIRSTHDR(&msg); - cmsg->cmsg_level = SOL_SOCKET; - cmsg->cmsg_type = SCM_RIGHTS; - cmsg->cmsg_len = CMSG_LEN(sizeof(int)); - msg.msg_controllen = cmsg->cmsg_len; - *(int*)CMSG_DATA(cmsg) = fd; - - Py_BEGIN_ALLOW_THREADS - res = sendmsg(conn, &msg, 0); - Py_END_ALLOW_THREADS - - if (res < 0) - return PyErr_SetFromErrno(PyExc_OSError); - Py_RETURN_NONE; + int conn, fd, res; + char dummy_char; + char buf[CMSG_SPACE(sizeof(int))]; + struct msghdr msg = {0}; + struct iovec dummy_iov; + struct cmsghdr *cmsg; + + if (!PyArg_ParseTuple(args, "ii", &conn, &fd)) + return NULL; + + dummy_iov.iov_base = &dummy_char; + dummy_iov.iov_len = 1; + msg.msg_control = buf; + msg.msg_controllen = sizeof(buf); + msg.msg_iov = &dummy_iov; + msg.msg_iovlen = 1; + cmsg = CMSG_FIRSTHDR(&msg); + cmsg->cmsg_level = SOL_SOCKET; + cmsg->cmsg_type = SCM_RIGHTS; + cmsg->cmsg_len = CMSG_LEN(sizeof(int)); + msg.msg_controllen = cmsg->cmsg_len; + *(int*)CMSG_DATA(cmsg) = fd; + + Py_BEGIN_ALLOW_THREADS + res = sendmsg(conn, &msg, 0); + Py_END_ALLOW_THREADS + + if (res < 0) + return PyErr_SetFromErrno(PyExc_OSError); + Py_RETURN_NONE; } static PyObject * multiprocessing_recvfd(PyObject *self, PyObject *args) { - int conn, fd, res; - char dummy_char; - char buf[CMSG_SPACE(sizeof(int))]; - struct msghdr msg = {0}; - struct iovec dummy_iov; - struct cmsghdr *cmsg; - - if (!PyArg_ParseTuple(args, "i", &conn)) - return NULL; - - dummy_iov.iov_base = &dummy_char; - dummy_iov.iov_len = 1; - msg.msg_control = buf; - msg.msg_controllen = sizeof(buf); - msg.msg_iov = &dummy_iov; - msg.msg_iovlen = 1; - cmsg = CMSG_FIRSTHDR(&msg); - cmsg->cmsg_level = SOL_SOCKET; - cmsg->cmsg_type = SCM_RIGHTS; - cmsg->cmsg_len = CMSG_LEN(sizeof(int)); - msg.msg_controllen = cmsg->cmsg_len; - - Py_BEGIN_ALLOW_THREADS - res = recvmsg(conn, &msg, 0); - Py_END_ALLOW_THREADS + int conn, fd, res; + char dummy_char; + char buf[CMSG_SPACE(sizeof(int))]; + struct msghdr msg = {0}; + struct iovec dummy_iov; + struct cmsghdr *cmsg; + + if (!PyArg_ParseTuple(args, "i", &conn)) + return NULL; + + dummy_iov.iov_base = &dummy_char; + dummy_iov.iov_len = 1; + msg.msg_control = buf; + msg.msg_controllen = sizeof(buf); + msg.msg_iov = &dummy_iov; + msg.msg_iovlen = 1; + cmsg = CMSG_FIRSTHDR(&msg); + cmsg->cmsg_level = SOL_SOCKET; + cmsg->cmsg_type = SCM_RIGHTS; + cmsg->cmsg_len = CMSG_LEN(sizeof(int)); + msg.msg_controllen = cmsg->cmsg_len; + + Py_BEGIN_ALLOW_THREADS + res = recvmsg(conn, &msg, 0); + Py_END_ALLOW_THREADS - if (res < 0) - return PyErr_SetFromErrno(PyExc_OSError); + if (res < 0) + return PyErr_SetFromErrno(PyExc_OSError); - fd = *(int*)CMSG_DATA(cmsg); - return Py_BuildValue("i", fd); + fd = *(int*)CMSG_DATA(cmsg); + return Py_BuildValue("i", fd); } #endif /* HAVE_FD_TRANSFER */ @@ -181,14 +181,14 @@ static PyObject* multiprocessing_address_of_buffer(PyObject *self, PyObject *obj) { - void *buffer; - Py_ssize_t buffer_len; + void *buffer; + Py_ssize_t buffer_len; - if (PyObject_AsWriteBuffer(obj, &buffer, &buffer_len) < 0) - return NULL; + if (PyObject_AsWriteBuffer(obj, &buffer, &buffer_len) < 0) + return NULL; - return Py_BuildValue("N" F_PY_SSIZE_T, - PyLong_FromVoidPtr(buffer), buffer_len); + return Py_BuildValue("N" F_PY_SSIZE_T, + PyLong_FromVoidPtr(buffer), buffer_len); } @@ -197,20 +197,20 @@ */ static PyMethodDef module_methods[] = { - {"address_of_buffer", multiprocessing_address_of_buffer, METH_O, - "address_of_buffer(obj) -> int\n" - "Return address of obj assuming obj supports buffer inteface"}, + {"address_of_buffer", multiprocessing_address_of_buffer, METH_O, + "address_of_buffer(obj) -> int\n" + "Return address of obj assuming obj supports buffer inteface"}, #if HAVE_FD_TRANSFER - {"sendfd", multiprocessing_sendfd, METH_VARARGS, - "sendfd(sockfd, fd) -> None\n" - "Send file descriptor given by fd over the unix domain socket\n" - "whose file decriptor is sockfd"}, - {"recvfd", multiprocessing_recvfd, METH_VARARGS, - "recvfd(sockfd) -> fd\n" - "Receive a file descriptor over a unix domain socket\n" - "whose file decriptor is sockfd"}, + {"sendfd", multiprocessing_sendfd, METH_VARARGS, + "sendfd(sockfd, fd) -> None\n" + "Send file descriptor given by fd over the unix domain socket\n" + "whose file decriptor is sockfd"}, + {"recvfd", multiprocessing_recvfd, METH_VARARGS, + "recvfd(sockfd) -> fd\n" + "Receive a file descriptor over a unix domain socket\n" + "whose file decriptor is sockfd"}, #endif - {NULL} + {NULL} }; @@ -219,117 +219,117 @@ */ static struct PyModuleDef multiprocessing_module = { - PyModuleDef_HEAD_INIT, - "_multiprocessing", - NULL, - -1, - module_methods, - NULL, - NULL, - NULL, - NULL + PyModuleDef_HEAD_INIT, + "_multiprocessing", + NULL, + -1, + module_methods, + NULL, + NULL, + NULL, + NULL }; -PyMODINIT_FUNC +PyMODINIT_FUNC PyInit__multiprocessing(void) { - PyObject *module, *temp, *value; + PyObject *module, *temp, *value; - /* Initialize module */ - module = PyModule_Create(&multiprocessing_module); - if (!module) - return NULL; - - /* Get copy of objects from pickle */ - temp = PyImport_ImportModule(PICKLE_MODULE); - if (!temp) - return NULL; - pickle_dumps = PyObject_GetAttrString(temp, "dumps"); - pickle_loads = PyObject_GetAttrString(temp, "loads"); - pickle_protocol = PyObject_GetAttrString(temp, "HIGHEST_PROTOCOL"); - Py_XDECREF(temp); - - /* Get copy of BufferTooShort */ - temp = PyImport_ImportModule("multiprocessing"); - if (!temp) - return NULL; - BufferTooShort = PyObject_GetAttrString(temp, "BufferTooShort"); - Py_XDECREF(temp); - - /* Add connection type to module */ - if (PyType_Ready(&ConnectionType) < 0) - return NULL; - Py_INCREF(&ConnectionType); - PyModule_AddObject(module, "Connection", (PyObject*)&ConnectionType); + /* Initialize module */ + module = PyModule_Create(&multiprocessing_module); + if (!module) + return NULL; + + /* Get copy of objects from pickle */ + temp = PyImport_ImportModule(PICKLE_MODULE); + if (!temp) + return NULL; + pickle_dumps = PyObject_GetAttrString(temp, "dumps"); + pickle_loads = PyObject_GetAttrString(temp, "loads"); + pickle_protocol = PyObject_GetAttrString(temp, "HIGHEST_PROTOCOL"); + Py_XDECREF(temp); + + /* Get copy of BufferTooShort */ + temp = PyImport_ImportModule("multiprocessing"); + if (!temp) + return NULL; + BufferTooShort = PyObject_GetAttrString(temp, "BufferTooShort"); + Py_XDECREF(temp); + + /* Add connection type to module */ + if (PyType_Ready(&ConnectionType) < 0) + return NULL; + Py_INCREF(&ConnectionType); + PyModule_AddObject(module, "Connection", (PyObject*)&ConnectionType); -#if defined(MS_WINDOWS) || \ +#if defined(MS_WINDOWS) || \ (defined(HAVE_SEM_OPEN) && !defined(POSIX_SEMAPHORES_NOT_ENABLED)) - /* Add SemLock type to module */ - if (PyType_Ready(&SemLockType) < 0) - return NULL; - Py_INCREF(&SemLockType); - PyDict_SetItemString(SemLockType.tp_dict, "SEM_VALUE_MAX", - Py_BuildValue("i", SEM_VALUE_MAX)); - PyModule_AddObject(module, "SemLock", (PyObject*)&SemLockType); + /* Add SemLock type to module */ + if (PyType_Ready(&SemLockType) < 0) + return NULL; + Py_INCREF(&SemLockType); + PyDict_SetItemString(SemLockType.tp_dict, "SEM_VALUE_MAX", + Py_BuildValue("i", SEM_VALUE_MAX)); + PyModule_AddObject(module, "SemLock", (PyObject*)&SemLockType); #endif #ifdef MS_WINDOWS - /* Add PipeConnection to module */ - if (PyType_Ready(&PipeConnectionType) < 0) - return NULL; - Py_INCREF(&PipeConnectionType); - PyModule_AddObject(module, "PipeConnection", - (PyObject*)&PipeConnectionType); - - /* Initialize win32 class and add to multiprocessing */ - temp = create_win32_namespace(); - if (!temp) - return NULL; - PyModule_AddObject(module, "win32", temp); - - /* Initialize the event handle used to signal Ctrl-C */ - sigint_event = CreateEvent(NULL, TRUE, FALSE, NULL); - if (!sigint_event) { - PyErr_SetFromWindowsErr(0); - return NULL; - } - if (!SetConsoleCtrlHandler(ProcessingCtrlHandler, TRUE)) { - PyErr_SetFromWindowsErr(0); - return NULL; - } + /* Add PipeConnection to module */ + if (PyType_Ready(&PipeConnectionType) < 0) + return NULL; + Py_INCREF(&PipeConnectionType); + PyModule_AddObject(module, "PipeConnection", + (PyObject*)&PipeConnectionType); + + /* Initialize win32 class and add to multiprocessing */ + temp = create_win32_namespace(); + if (!temp) + return NULL; + PyModule_AddObject(module, "win32", temp); + + /* Initialize the event handle used to signal Ctrl-C */ + sigint_event = CreateEvent(NULL, TRUE, FALSE, NULL); + if (!sigint_event) { + PyErr_SetFromWindowsErr(0); + return NULL; + } + if (!SetConsoleCtrlHandler(ProcessingCtrlHandler, TRUE)) { + PyErr_SetFromWindowsErr(0); + return NULL; + } #endif - /* Add configuration macros */ - temp = PyDict_New(); - if (!temp) - return NULL; - -#define ADD_FLAG(name) \ - value = Py_BuildValue("i", name); \ - if (value == NULL) { Py_DECREF(temp); return NULL; } \ - if (PyDict_SetItemString(temp, #name, value) < 0) { \ - Py_DECREF(temp); Py_DECREF(value); return NULL; } \ - Py_DECREF(value) - + /* Add configuration macros */ + temp = PyDict_New(); + if (!temp) + return NULL; + +#define ADD_FLAG(name) \ + value = Py_BuildValue("i", name); \ + if (value == NULL) { Py_DECREF(temp); return NULL; } \ + if (PyDict_SetItemString(temp, #name, value) < 0) { \ + Py_DECREF(temp); Py_DECREF(value); return NULL; } \ + Py_DECREF(value) + #if defined(HAVE_SEM_OPEN) && !defined(POSIX_SEMAPHORES_NOT_ENABLED) - ADD_FLAG(HAVE_SEM_OPEN); + ADD_FLAG(HAVE_SEM_OPEN); #endif #ifdef HAVE_SEM_TIMEDWAIT - ADD_FLAG(HAVE_SEM_TIMEDWAIT); + ADD_FLAG(HAVE_SEM_TIMEDWAIT); #endif #ifdef HAVE_FD_TRANSFER - ADD_FLAG(HAVE_FD_TRANSFER); + ADD_FLAG(HAVE_FD_TRANSFER); #endif #ifdef HAVE_BROKEN_SEM_GETVALUE - ADD_FLAG(HAVE_BROKEN_SEM_GETVALUE); + ADD_FLAG(HAVE_BROKEN_SEM_GETVALUE); #endif #ifdef HAVE_BROKEN_SEM_UNLINK - ADD_FLAG(HAVE_BROKEN_SEM_UNLINK); + ADD_FLAG(HAVE_BROKEN_SEM_UNLINK); #endif - if (PyModule_AddObject(module, "flags", temp) < 0) - return NULL; + if (PyModule_AddObject(module, "flags", temp) < 0) + return NULL; - return module; + return module; } Modified: python/branches/py3k-jit/Modules/_multiprocessing/multiprocessing.h ============================================================================== --- python/branches/py3k-jit/Modules/_multiprocessing/multiprocessing.h (original) +++ python/branches/py3k-jit/Modules/_multiprocessing/multiprocessing.h Mon May 10 23:55:43 2010 @@ -15,7 +15,7 @@ # define WIN32_LEAN_AND_MEAN # include # include -# include /* getpid() */ +# include /* getpid() */ # ifdef Py_DEBUG # include # endif @@ -45,15 +45,15 @@ * Issue 3110 - Solaris does not define SEM_VALUE_MAX */ #ifndef SEM_VALUE_MAX - #if defined(HAVE_SYSCONF) && defined(_SC_SEM_VALUE_MAX) - # define SEM_VALUE_MAX sysconf(_SC_SEM_VALUE_MAX) - #elif defined(_SEM_VALUE_MAX) - # define SEM_VALUE_MAX _SEM_VALUE_MAX - #elif defined(_POSIX_SEM_VALUE_MAX) - # define SEM_VALUE_MAX _POSIX_SEM_VALUE_MAX - #else - # define SEM_VALUE_MAX INT_MAX - #endif + #if defined(HAVE_SYSCONF) && defined(_SC_SEM_VALUE_MAX) + # define SEM_VALUE_MAX sysconf(_SC_SEM_VALUE_MAX) + #elif defined(_SEM_VALUE_MAX) + # define SEM_VALUE_MAX _SEM_VALUE_MAX + #elif defined(_POSIX_SEM_VALUE_MAX) + # define SEM_VALUE_MAX _POSIX_SEM_VALUE_MAX + #else + # define SEM_VALUE_MAX INT_MAX + #endif #endif @@ -162,11 +162,11 @@ #define CONNECTION_BUFFER_SIZE 1024 typedef struct { - PyObject_HEAD - HANDLE handle; - int flags; - PyObject *weakreflist; - char buffer[CONNECTION_BUFFER_SIZE]; + PyObject_HEAD + HANDLE handle; + int flags; + PyObject *weakreflist; + char buffer[CONNECTION_BUFFER_SIZE]; } ConnectionObject; /* Modified: python/branches/py3k-jit/Modules/_multiprocessing/pipe_connection.c ============================================================================== --- python/branches/py3k-jit/Modules/_multiprocessing/pipe_connection.c (original) +++ python/branches/py3k-jit/Modules/_multiprocessing/pipe_connection.c Mon May 10 23:55:43 2010 @@ -17,19 +17,19 @@ static Py_ssize_t conn_send_string(ConnectionObject *conn, char *string, size_t length) { - DWORD amount_written; - BOOL ret; + DWORD amount_written; + BOOL ret; - Py_BEGIN_ALLOW_THREADS - ret = WriteFile(conn->handle, string, length, &amount_written, NULL); - Py_END_ALLOW_THREADS - - if (ret == 0 && GetLastError() == ERROR_NO_SYSTEM_RESOURCES) { - PyErr_Format(PyExc_ValueError, "Cannnot send %" PY_FORMAT_SIZE_T "d bytes over connection", length); - return MP_STANDARD_ERROR; - } + Py_BEGIN_ALLOW_THREADS + ret = WriteFile(conn->handle, string, length, &amount_written, NULL); + Py_END_ALLOW_THREADS + + if (ret == 0 && GetLastError() == ERROR_NO_SYSTEM_RESOURCES) { + PyErr_Format(PyExc_ValueError, "Cannnot send %" PY_FORMAT_SIZE_T "d bytes over connection", length); + return MP_STANDARD_ERROR; + } - return ret ? MP_SUCCESS : MP_STANDARD_ERROR; + return ret ? MP_SUCCESS : MP_STANDARD_ERROR; } /* @@ -39,50 +39,50 @@ */ static Py_ssize_t -conn_recv_string(ConnectionObject *conn, char *buffer, - size_t buflength, char **newbuffer, size_t maxlength) +conn_recv_string(ConnectionObject *conn, char *buffer, + size_t buflength, char **newbuffer, size_t maxlength) { - DWORD left, length, full_length, err; - BOOL ret; - *newbuffer = NULL; - - Py_BEGIN_ALLOW_THREADS - ret = ReadFile(conn->handle, buffer, MIN(buflength, maxlength), - &length, NULL); - Py_END_ALLOW_THREADS - if (ret) - return length; - - err = GetLastError(); - if (err != ERROR_MORE_DATA) { - if (err == ERROR_BROKEN_PIPE) - return MP_END_OF_FILE; - return MP_STANDARD_ERROR; - } - - if (!PeekNamedPipe(conn->handle, NULL, 0, NULL, NULL, &left)) - return MP_STANDARD_ERROR; - - full_length = length + left; - if (full_length > maxlength) - return MP_BAD_MESSAGE_LENGTH; - - *newbuffer = PyMem_Malloc(full_length); - if (*newbuffer == NULL) - return MP_MEMORY_ERROR; - - memcpy(*newbuffer, buffer, length); - - Py_BEGIN_ALLOW_THREADS - ret = ReadFile(conn->handle, *newbuffer+length, left, &length, NULL); - Py_END_ALLOW_THREADS - if (ret) { - assert(length == left); - return full_length; - } else { - PyMem_Free(*newbuffer); - return MP_STANDARD_ERROR; - } + DWORD left, length, full_length, err; + BOOL ret; + *newbuffer = NULL; + + Py_BEGIN_ALLOW_THREADS + ret = ReadFile(conn->handle, buffer, MIN(buflength, maxlength), + &length, NULL); + Py_END_ALLOW_THREADS + if (ret) + return length; + + err = GetLastError(); + if (err != ERROR_MORE_DATA) { + if (err == ERROR_BROKEN_PIPE) + return MP_END_OF_FILE; + return MP_STANDARD_ERROR; + } + + if (!PeekNamedPipe(conn->handle, NULL, 0, NULL, NULL, &left)) + return MP_STANDARD_ERROR; + + full_length = length + left; + if (full_length > maxlength) + return MP_BAD_MESSAGE_LENGTH; + + *newbuffer = PyMem_Malloc(full_length); + if (*newbuffer == NULL) + return MP_MEMORY_ERROR; + + memcpy(*newbuffer, buffer, length); + + Py_BEGIN_ALLOW_THREADS + ret = ReadFile(conn->handle, *newbuffer+length, left, &length, NULL); + Py_END_ALLOW_THREADS + if (ret) { + assert(length == left); + return full_length; + } else { + PyMem_Free(*newbuffer); + return MP_STANDARD_ERROR; + } } /* @@ -92,51 +92,51 @@ static int conn_poll(ConnectionObject *conn, double timeout, PyThreadState *_save) { - DWORD bytes, deadline, delay; - int difference, res; - BOOL block = FALSE; - - if (!PeekNamedPipe(conn->handle, NULL, 0, NULL, &bytes, NULL)) - return MP_STANDARD_ERROR; - - if (timeout == 0.0) - return bytes > 0; - - if (timeout < 0.0) - block = TRUE; - else - /* XXX does not check for overflow */ - deadline = GetTickCount() + (DWORD)(1000 * timeout + 0.5); - - Sleep(0); - - for (delay = 1 ; ; delay += 1) { - if (!PeekNamedPipe(conn->handle, NULL, 0, NULL, &bytes, NULL)) - return MP_STANDARD_ERROR; - else if (bytes > 0) - return TRUE; - - if (!block) { - difference = deadline - GetTickCount(); - if (difference < 0) - return FALSE; - if ((int)delay > difference) - delay = difference; - } - - if (delay > 20) - delay = 20; - - Sleep(delay); - - /* check for signals */ - Py_BLOCK_THREADS - res = PyErr_CheckSignals(); - Py_UNBLOCK_THREADS - - if (res) - return MP_EXCEPTION_HAS_BEEN_SET; - } + DWORD bytes, deadline, delay; + int difference, res; + BOOL block = FALSE; + + if (!PeekNamedPipe(conn->handle, NULL, 0, NULL, &bytes, NULL)) + return MP_STANDARD_ERROR; + + if (timeout == 0.0) + return bytes > 0; + + if (timeout < 0.0) + block = TRUE; + else + /* XXX does not check for overflow */ + deadline = GetTickCount() + (DWORD)(1000 * timeout + 0.5); + + Sleep(0); + + for (delay = 1 ; ; delay += 1) { + if (!PeekNamedPipe(conn->handle, NULL, 0, NULL, &bytes, NULL)) + return MP_STANDARD_ERROR; + else if (bytes > 0) + return TRUE; + + if (!block) { + difference = deadline - GetTickCount(); + if (difference < 0) + return FALSE; + if ((int)delay > difference) + delay = difference; + } + + if (delay > 20) + delay = 20; + + Sleep(delay); + + /* check for signals */ + Py_BLOCK_THREADS + res = PyErr_CheckSignals(); + Py_UNBLOCK_THREADS + + if (res) + return MP_EXCEPTION_HAS_BEEN_SET; + } } /* Modified: python/branches/py3k-jit/Modules/_multiprocessing/semaphore.c ============================================================================== --- python/branches/py3k-jit/Modules/_multiprocessing/semaphore.c (original) +++ python/branches/py3k-jit/Modules/_multiprocessing/semaphore.c Mon May 10 23:55:43 2010 @@ -11,12 +11,12 @@ enum { RECURSIVE_MUTEX, SEMAPHORE }; typedef struct { - PyObject_HEAD - SEM_HANDLE handle; - long last_tid; - int count; - int maxvalue; - int kind; + PyObject_HEAD + SEM_HANDLE handle; + long last_tid; + int count; + int maxvalue; + int kind; } SemLockObject; #define ISMINE(o) (o->count > 0 && PyThread_get_thread_ident() == o->last_tid) @@ -40,148 +40,148 @@ static int _GetSemaphoreValue(HANDLE handle, long *value) { - long previous; + long previous; - switch (WaitForSingleObject(handle, 0)) { - case WAIT_OBJECT_0: - if (!ReleaseSemaphore(handle, 1, &previous)) - return MP_STANDARD_ERROR; - *value = previous + 1; - return 0; - case WAIT_TIMEOUT: - *value = 0; - return 0; - default: - return MP_STANDARD_ERROR; - } + switch (WaitForSingleObject(handle, 0)) { + case WAIT_OBJECT_0: + if (!ReleaseSemaphore(handle, 1, &previous)) + return MP_STANDARD_ERROR; + *value = previous + 1; + return 0; + case WAIT_TIMEOUT: + *value = 0; + return 0; + default: + return MP_STANDARD_ERROR; + } } static PyObject * semlock_acquire(SemLockObject *self, PyObject *args, PyObject *kwds) { - int blocking = 1; - double timeout; - PyObject *timeout_obj = Py_None; - DWORD res, full_msecs, msecs, start, ticks; - - static char *kwlist[] = {"block", "timeout", NULL}; - - if (!PyArg_ParseTupleAndKeywords(args, kwds, "|iO", kwlist, - &blocking, &timeout_obj)) - return NULL; - - /* calculate timeout */ - if (!blocking) { - full_msecs = 0; - } else if (timeout_obj == Py_None) { - full_msecs = INFINITE; - } else { - timeout = PyFloat_AsDouble(timeout_obj); - if (PyErr_Occurred()) - return NULL; - timeout *= 1000.0; /* convert to millisecs */ - if (timeout < 0.0) { - timeout = 0.0; - } else if (timeout >= 0.5 * INFINITE) { /* 25 days */ - PyErr_SetString(PyExc_OverflowError, - "timeout is too large"); - return NULL; - } - full_msecs = (DWORD)(timeout + 0.5); - } - - /* check whether we already own the lock */ - if (self->kind == RECURSIVE_MUTEX && ISMINE(self)) { - ++self->count; - Py_RETURN_TRUE; - } - - /* check whether we can acquire without blocking */ - if (WaitForSingleObject(self->handle, 0) == WAIT_OBJECT_0) { - self->last_tid = GetCurrentThreadId(); - ++self->count; - Py_RETURN_TRUE; - } - - msecs = full_msecs; - start = GetTickCount(); - - for ( ; ; ) { - HANDLE handles[2] = {self->handle, sigint_event}; - - /* do the wait */ - Py_BEGIN_ALLOW_THREADS - ResetEvent(sigint_event); - res = WaitForMultipleObjects(2, handles, FALSE, msecs); - Py_END_ALLOW_THREADS - - /* handle result */ - if (res != WAIT_OBJECT_0 + 1) - break; - - /* got SIGINT so give signal handler a chance to run */ - Sleep(1); - - /* if this is main thread let KeyboardInterrupt be raised */ - if (PyErr_CheckSignals()) - return NULL; - - /* recalculate timeout */ - if (msecs != INFINITE) { - ticks = GetTickCount(); - if ((DWORD)(ticks - start) >= full_msecs) - Py_RETURN_FALSE; - msecs = full_msecs - (ticks - start); - } - } - - /* handle result */ - switch (res) { - case WAIT_TIMEOUT: - Py_RETURN_FALSE; - case WAIT_OBJECT_0: - self->last_tid = GetCurrentThreadId(); - ++self->count; - Py_RETURN_TRUE; - case WAIT_FAILED: - return PyErr_SetFromWindowsErr(0); - default: - PyErr_Format(PyExc_RuntimeError, "WaitForSingleObject() or " - "WaitForMultipleObjects() gave unrecognized " - "value %d", res); - return NULL; - } + int blocking = 1; + double timeout; + PyObject *timeout_obj = Py_None; + DWORD res, full_msecs, msecs, start, ticks; + + static char *kwlist[] = {"block", "timeout", NULL}; + + if (!PyArg_ParseTupleAndKeywords(args, kwds, "|iO", kwlist, + &blocking, &timeout_obj)) + return NULL; + + /* calculate timeout */ + if (!blocking) { + full_msecs = 0; + } else if (timeout_obj == Py_None) { + full_msecs = INFINITE; + } else { + timeout = PyFloat_AsDouble(timeout_obj); + if (PyErr_Occurred()) + return NULL; + timeout *= 1000.0; /* convert to millisecs */ + if (timeout < 0.0) { + timeout = 0.0; + } else if (timeout >= 0.5 * INFINITE) { /* 25 days */ + PyErr_SetString(PyExc_OverflowError, + "timeout is too large"); + return NULL; + } + full_msecs = (DWORD)(timeout + 0.5); + } + + /* check whether we already own the lock */ + if (self->kind == RECURSIVE_MUTEX && ISMINE(self)) { + ++self->count; + Py_RETURN_TRUE; + } + + /* check whether we can acquire without blocking */ + if (WaitForSingleObject(self->handle, 0) == WAIT_OBJECT_0) { + self->last_tid = GetCurrentThreadId(); + ++self->count; + Py_RETURN_TRUE; + } + + msecs = full_msecs; + start = GetTickCount(); + + for ( ; ; ) { + HANDLE handles[2] = {self->handle, sigint_event}; + + /* do the wait */ + Py_BEGIN_ALLOW_THREADS + ResetEvent(sigint_event); + res = WaitForMultipleObjects(2, handles, FALSE, msecs); + Py_END_ALLOW_THREADS + + /* handle result */ + if (res != WAIT_OBJECT_0 + 1) + break; + + /* got SIGINT so give signal handler a chance to run */ + Sleep(1); + + /* if this is main thread let KeyboardInterrupt be raised */ + if (PyErr_CheckSignals()) + return NULL; + + /* recalculate timeout */ + if (msecs != INFINITE) { + ticks = GetTickCount(); + if ((DWORD)(ticks - start) >= full_msecs) + Py_RETURN_FALSE; + msecs = full_msecs - (ticks - start); + } + } + + /* handle result */ + switch (res) { + case WAIT_TIMEOUT: + Py_RETURN_FALSE; + case WAIT_OBJECT_0: + self->last_tid = GetCurrentThreadId(); + ++self->count; + Py_RETURN_TRUE; + case WAIT_FAILED: + return PyErr_SetFromWindowsErr(0); + default: + PyErr_Format(PyExc_RuntimeError, "WaitForSingleObject() or " + "WaitForMultipleObjects() gave unrecognized " + "value %d", res); + return NULL; + } } static PyObject * semlock_release(SemLockObject *self, PyObject *args) { - if (self->kind == RECURSIVE_MUTEX) { - if (!ISMINE(self)) { - PyErr_SetString(PyExc_AssertionError, "attempt to " - "release recursive lock not owned " - "by thread"); - return NULL; - } - if (self->count > 1) { - --self->count; - Py_RETURN_NONE; - } - assert(self->count == 1); - } - - if (!ReleaseSemaphore(self->handle, 1, NULL)) { - if (GetLastError() == ERROR_TOO_MANY_POSTS) { - PyErr_SetString(PyExc_ValueError, "semaphore or lock " - "released too many times"); - return NULL; - } else { - return PyErr_SetFromWindowsErr(0); - } - } + if (self->kind == RECURSIVE_MUTEX) { + if (!ISMINE(self)) { + PyErr_SetString(PyExc_AssertionError, "attempt to " + "release recursive lock not owned " + "by thread"); + return NULL; + } + if (self->count > 1) { + --self->count; + Py_RETURN_NONE; + } + assert(self->count == 1); + } + + if (!ReleaseSemaphore(self->handle, 1, NULL)) { + if (GetLastError() == ERROR_TOO_MANY_POSTS) { + PyErr_SetString(PyExc_ValueError, "semaphore or lock " + "released too many times"); + return NULL; + } else { + return PyErr_SetFromWindowsErr(0); + } + } - --self->count; - Py_RETURN_NONE; + --self->count; + Py_RETURN_NONE; } #else /* !MS_WINDOWS */ @@ -207,59 +207,59 @@ int sem_timedwait_save(sem_t *sem, struct timespec *deadline, PyThreadState *_save) { - int res; - unsigned long delay, difference; - struct timeval now, tvdeadline, tvdelay; - - errno = 0; - tvdeadline.tv_sec = deadline->tv_sec; - tvdeadline.tv_usec = deadline->tv_nsec / 1000; - - for (delay = 0 ; ; delay += 1000) { - /* poll */ - if (sem_trywait(sem) == 0) - return 0; - else if (errno != EAGAIN) - return MP_STANDARD_ERROR; - - /* get current time */ - if (gettimeofday(&now, NULL) < 0) - return MP_STANDARD_ERROR; - - /* check for timeout */ - if (tvdeadline.tv_sec < now.tv_sec || - (tvdeadline.tv_sec == now.tv_sec && - tvdeadline.tv_usec <= now.tv_usec)) { - errno = ETIMEDOUT; - return MP_STANDARD_ERROR; - } - - /* calculate how much time is left */ - difference = (tvdeadline.tv_sec - now.tv_sec) * 1000000 + - (tvdeadline.tv_usec - now.tv_usec); - - /* check delay not too long -- maximum is 20 msecs */ - if (delay > 20000) - delay = 20000; - if (delay > difference) - delay = difference; - - /* sleep */ - tvdelay.tv_sec = delay / 1000000; - tvdelay.tv_usec = delay % 1000000; - if (select(0, NULL, NULL, NULL, &tvdelay) < 0) - return MP_STANDARD_ERROR; - - /* check for signals */ - Py_BLOCK_THREADS - res = PyErr_CheckSignals(); - Py_UNBLOCK_THREADS - - if (res) { - errno = EINTR; - return MP_EXCEPTION_HAS_BEEN_SET; - } - } + int res; + unsigned long delay, difference; + struct timeval now, tvdeadline, tvdelay; + + errno = 0; + tvdeadline.tv_sec = deadline->tv_sec; + tvdeadline.tv_usec = deadline->tv_nsec / 1000; + + for (delay = 0 ; ; delay += 1000) { + /* poll */ + if (sem_trywait(sem) == 0) + return 0; + else if (errno != EAGAIN) + return MP_STANDARD_ERROR; + + /* get current time */ + if (gettimeofday(&now, NULL) < 0) + return MP_STANDARD_ERROR; + + /* check for timeout */ + if (tvdeadline.tv_sec < now.tv_sec || + (tvdeadline.tv_sec == now.tv_sec && + tvdeadline.tv_usec <= now.tv_usec)) { + errno = ETIMEDOUT; + return MP_STANDARD_ERROR; + } + + /* calculate how much time is left */ + difference = (tvdeadline.tv_sec - now.tv_sec) * 1000000 + + (tvdeadline.tv_usec - now.tv_usec); + + /* check delay not too long -- maximum is 20 msecs */ + if (delay > 20000) + delay = 20000; + if (delay > difference) + delay = difference; + + /* sleep */ + tvdelay.tv_sec = delay / 1000000; + tvdelay.tv_usec = delay % 1000000; + if (select(0, NULL, NULL, NULL, &tvdelay) < 0) + return MP_STANDARD_ERROR; + + /* check for signals */ + Py_BLOCK_THREADS + res = PyErr_CheckSignals(); + Py_UNBLOCK_THREADS + + if (res) { + errno = EINTR; + return MP_EXCEPTION_HAS_BEEN_SET; + } + } } #endif /* !HAVE_SEM_TIMEDWAIT */ @@ -267,129 +267,129 @@ static PyObject * semlock_acquire(SemLockObject *self, PyObject *args, PyObject *kwds) { - int blocking = 1, res; - double timeout; - PyObject *timeout_obj = Py_None; - struct timespec deadline = {0}; - struct timeval now; - long sec, nsec; - - static char *kwlist[] = {"block", "timeout", NULL}; - - if (!PyArg_ParseTupleAndKeywords(args, kwds, "|iO", kwlist, - &blocking, &timeout_obj)) - return NULL; - - if (self->kind == RECURSIVE_MUTEX && ISMINE(self)) { - ++self->count; - Py_RETURN_TRUE; - } - - if (timeout_obj != Py_None) { - timeout = PyFloat_AsDouble(timeout_obj); - if (PyErr_Occurred()) - return NULL; - if (timeout < 0.0) - timeout = 0.0; - - if (gettimeofday(&now, NULL) < 0) { - PyErr_SetFromErrno(PyExc_OSError); - return NULL; - } - sec = (long) timeout; - nsec = (long) (1e9 * (timeout - sec) + 0.5); - deadline.tv_sec = now.tv_sec + sec; - deadline.tv_nsec = now.tv_usec * 1000 + nsec; - deadline.tv_sec += (deadline.tv_nsec / 1000000000); - deadline.tv_nsec %= 1000000000; - } - - do { - Py_BEGIN_ALLOW_THREADS - if (blocking && timeout_obj == Py_None) - res = sem_wait(self->handle); - else if (!blocking) - res = sem_trywait(self->handle); - else - res = sem_timedwait(self->handle, &deadline); - Py_END_ALLOW_THREADS - if (res == MP_EXCEPTION_HAS_BEEN_SET) - break; - } while (res < 0 && errno == EINTR && !PyErr_CheckSignals()); - - if (res < 0) { - if (errno == EAGAIN || errno == ETIMEDOUT) - Py_RETURN_FALSE; - else if (errno == EINTR) - return NULL; - else - return PyErr_SetFromErrno(PyExc_OSError); - } + int blocking = 1, res; + double timeout; + PyObject *timeout_obj = Py_None; + struct timespec deadline = {0}; + struct timeval now; + long sec, nsec; + + static char *kwlist[] = {"block", "timeout", NULL}; + + if (!PyArg_ParseTupleAndKeywords(args, kwds, "|iO", kwlist, + &blocking, &timeout_obj)) + return NULL; + + if (self->kind == RECURSIVE_MUTEX && ISMINE(self)) { + ++self->count; + Py_RETURN_TRUE; + } + + if (timeout_obj != Py_None) { + timeout = PyFloat_AsDouble(timeout_obj); + if (PyErr_Occurred()) + return NULL; + if (timeout < 0.0) + timeout = 0.0; + + if (gettimeofday(&now, NULL) < 0) { + PyErr_SetFromErrno(PyExc_OSError); + return NULL; + } + sec = (long) timeout; + nsec = (long) (1e9 * (timeout - sec) + 0.5); + deadline.tv_sec = now.tv_sec + sec; + deadline.tv_nsec = now.tv_usec * 1000 + nsec; + deadline.tv_sec += (deadline.tv_nsec / 1000000000); + deadline.tv_nsec %= 1000000000; + } + + do { + Py_BEGIN_ALLOW_THREADS + if (blocking && timeout_obj == Py_None) + res = sem_wait(self->handle); + else if (!blocking) + res = sem_trywait(self->handle); + else + res = sem_timedwait(self->handle, &deadline); + Py_END_ALLOW_THREADS + if (res == MP_EXCEPTION_HAS_BEEN_SET) + break; + } while (res < 0 && errno == EINTR && !PyErr_CheckSignals()); + + if (res < 0) { + if (errno == EAGAIN || errno == ETIMEDOUT) + Py_RETURN_FALSE; + else if (errno == EINTR) + return NULL; + else + return PyErr_SetFromErrno(PyExc_OSError); + } - ++self->count; - self->last_tid = PyThread_get_thread_ident(); + ++self->count; + self->last_tid = PyThread_get_thread_ident(); - Py_RETURN_TRUE; + Py_RETURN_TRUE; } static PyObject * semlock_release(SemLockObject *self, PyObject *args) { - if (self->kind == RECURSIVE_MUTEX) { - if (!ISMINE(self)) { - PyErr_SetString(PyExc_AssertionError, "attempt to " - "release recursive lock not owned " - "by thread"); - return NULL; - } - if (self->count > 1) { - --self->count; - Py_RETURN_NONE; - } - assert(self->count == 1); - } else { + if (self->kind == RECURSIVE_MUTEX) { + if (!ISMINE(self)) { + PyErr_SetString(PyExc_AssertionError, "attempt to " + "release recursive lock not owned " + "by thread"); + return NULL; + } + if (self->count > 1) { + --self->count; + Py_RETURN_NONE; + } + assert(self->count == 1); + } else { #ifdef HAVE_BROKEN_SEM_GETVALUE - /* We will only check properly the maxvalue == 1 case */ - if (self->maxvalue == 1) { - /* make sure that already locked */ - if (sem_trywait(self->handle) < 0) { - if (errno != EAGAIN) { - PyErr_SetFromErrno(PyExc_OSError); - return NULL; - } - /* it is already locked as expected */ - } else { - /* it was not locked so undo wait and raise */ - if (sem_post(self->handle) < 0) { - PyErr_SetFromErrno(PyExc_OSError); - return NULL; - } - PyErr_SetString(PyExc_ValueError, "semaphore " - "or lock released too many " - "times"); - return NULL; - } - } + /* We will only check properly the maxvalue == 1 case */ + if (self->maxvalue == 1) { + /* make sure that already locked */ + if (sem_trywait(self->handle) < 0) { + if (errno != EAGAIN) { + PyErr_SetFromErrno(PyExc_OSError); + return NULL; + } + /* it is already locked as expected */ + } else { + /* it was not locked so undo wait and raise */ + if (sem_post(self->handle) < 0) { + PyErr_SetFromErrno(PyExc_OSError); + return NULL; + } + PyErr_SetString(PyExc_ValueError, "semaphore " + "or lock released too many " + "times"); + return NULL; + } + } #else - int sval; + int sval; - /* This check is not an absolute guarantee that the semaphore - does not rise above maxvalue. */ - if (sem_getvalue(self->handle, &sval) < 0) { - return PyErr_SetFromErrno(PyExc_OSError); - } else if (sval >= self->maxvalue) { - PyErr_SetString(PyExc_ValueError, "semaphore or lock " - "released too many times"); - return NULL; - } + /* This check is not an absolute guarantee that the semaphore + does not rise above maxvalue. */ + if (sem_getvalue(self->handle, &sval) < 0) { + return PyErr_SetFromErrno(PyExc_OSError); + } else if (sval >= self->maxvalue) { + PyErr_SetString(PyExc_ValueError, "semaphore or lock " + "released too many times"); + return NULL; + } #endif - } + } - if (sem_post(self->handle) < 0) - return PyErr_SetFromErrno(PyExc_OSError); + if (sem_post(self->handle) < 0) + return PyErr_SetFromErrno(PyExc_OSError); - --self->count; - Py_RETURN_NONE; + --self->count; + Py_RETURN_NONE; } #endif /* !MS_WINDOWS */ @@ -401,111 +401,111 @@ static PyObject * newsemlockobject(PyTypeObject *type, SEM_HANDLE handle, int kind, int maxvalue) { - SemLockObject *self; + SemLockObject *self; - self = PyObject_New(SemLockObject, type); - if (!self) - return NULL; - self->handle = handle; - self->kind = kind; - self->count = 0; - self->last_tid = 0; - self->maxvalue = maxvalue; - return (PyObject*)self; + self = PyObject_New(SemLockObject, type); + if (!self) + return NULL; + self->handle = handle; + self->kind = kind; + self->count = 0; + self->last_tid = 0; + self->maxvalue = maxvalue; + return (PyObject*)self; } static PyObject * semlock_new(PyTypeObject *type, PyObject *args, PyObject *kwds) { - char buffer[256]; - SEM_HANDLE handle = SEM_FAILED; - int kind, maxvalue, value; - PyObject *result; - static char *kwlist[] = {"kind", "value", "maxvalue", NULL}; - static int counter = 0; - - if (!PyArg_ParseTupleAndKeywords(args, kwds, "iii", kwlist, - &kind, &value, &maxvalue)) - return NULL; - - if (kind != RECURSIVE_MUTEX && kind != SEMAPHORE) { - PyErr_SetString(PyExc_ValueError, "unrecognized kind"); - return NULL; - } - - PyOS_snprintf(buffer, sizeof(buffer), "/mp%d-%d", getpid(), counter++); - - SEM_CLEAR_ERROR(); - handle = SEM_CREATE(buffer, value, maxvalue); - /* On Windows we should fail if GetLastError()==ERROR_ALREADY_EXISTS */ - if (handle == SEM_FAILED || SEM_GET_LAST_ERROR() != 0) - goto failure; - - if (SEM_UNLINK(buffer) < 0) - goto failure; - - result = newsemlockobject(type, handle, kind, maxvalue); - if (!result) - goto failure; + char buffer[256]; + SEM_HANDLE handle = SEM_FAILED; + int kind, maxvalue, value; + PyObject *result; + static char *kwlist[] = {"kind", "value", "maxvalue", NULL}; + static int counter = 0; + + if (!PyArg_ParseTupleAndKeywords(args, kwds, "iii", kwlist, + &kind, &value, &maxvalue)) + return NULL; + + if (kind != RECURSIVE_MUTEX && kind != SEMAPHORE) { + PyErr_SetString(PyExc_ValueError, "unrecognized kind"); + return NULL; + } + + PyOS_snprintf(buffer, sizeof(buffer), "/mp%d-%d", getpid(), counter++); + + SEM_CLEAR_ERROR(); + handle = SEM_CREATE(buffer, value, maxvalue); + /* On Windows we should fail if GetLastError()==ERROR_ALREADY_EXISTS */ + if (handle == SEM_FAILED || SEM_GET_LAST_ERROR() != 0) + goto failure; + + if (SEM_UNLINK(buffer) < 0) + goto failure; + + result = newsemlockobject(type, handle, kind, maxvalue); + if (!result) + goto failure; - return result; + return result; failure: - if (handle != SEM_FAILED) - SEM_CLOSE(handle); - mp_SetError(NULL, MP_STANDARD_ERROR); - return NULL; + if (handle != SEM_FAILED) + SEM_CLOSE(handle); + mp_SetError(NULL, MP_STANDARD_ERROR); + return NULL; } static PyObject * semlock_rebuild(PyTypeObject *type, PyObject *args) { - SEM_HANDLE handle; - int kind, maxvalue; + SEM_HANDLE handle; + int kind, maxvalue; - if (!PyArg_ParseTuple(args, F_SEM_HANDLE "ii", - &handle, &kind, &maxvalue)) - return NULL; + if (!PyArg_ParseTuple(args, F_SEM_HANDLE "ii", + &handle, &kind, &maxvalue)) + return NULL; - return newsemlockobject(type, handle, kind, maxvalue); + return newsemlockobject(type, handle, kind, maxvalue); } static void semlock_dealloc(SemLockObject* self) { - if (self->handle != SEM_FAILED) - SEM_CLOSE(self->handle); - PyObject_Del(self); + if (self->handle != SEM_FAILED) + SEM_CLOSE(self->handle); + PyObject_Del(self); } static PyObject * semlock_count(SemLockObject *self) { - return PyInt_FromLong((long)self->count); + return PyInt_FromLong((long)self->count); } static PyObject * semlock_ismine(SemLockObject *self) { - /* only makes sense for a lock */ - return PyBool_FromLong(ISMINE(self)); + /* only makes sense for a lock */ + return PyBool_FromLong(ISMINE(self)); } static PyObject * semlock_getvalue(SemLockObject *self) { #ifdef HAVE_BROKEN_SEM_GETVALUE - PyErr_SetNone(PyExc_NotImplementedError); - return NULL; + PyErr_SetNone(PyExc_NotImplementedError); + return NULL; #else - int sval; - if (SEM_GETVALUE(self->handle, &sval) < 0) - return mp_SetError(NULL, MP_STANDARD_ERROR); - /* some posix implementations use negative numbers to indicate - the number of waiting threads */ - if (sval < 0) - sval = 0; - return PyInt_FromLong((long)sval); + int sval; + if (SEM_GETVALUE(self->handle, &sval) < 0) + return mp_SetError(NULL, MP_STANDARD_ERROR); + /* some posix implementations use negative numbers to indicate + the number of waiting threads */ + if (sval < 0) + sval = 0; + return PyInt_FromLong((long)sval); #endif } @@ -513,28 +513,28 @@ semlock_iszero(SemLockObject *self) { #ifdef HAVE_BROKEN_SEM_GETVALUE - if (sem_trywait(self->handle) < 0) { - if (errno == EAGAIN) - Py_RETURN_TRUE; - return mp_SetError(NULL, MP_STANDARD_ERROR); - } else { - if (sem_post(self->handle) < 0) - return mp_SetError(NULL, MP_STANDARD_ERROR); - Py_RETURN_FALSE; - } + if (sem_trywait(self->handle) < 0) { + if (errno == EAGAIN) + Py_RETURN_TRUE; + return mp_SetError(NULL, MP_STANDARD_ERROR); + } else { + if (sem_post(self->handle) < 0) + return mp_SetError(NULL, MP_STANDARD_ERROR); + Py_RETURN_FALSE; + } #else - int sval; - if (SEM_GETVALUE(self->handle, &sval) < 0) - return mp_SetError(NULL, MP_STANDARD_ERROR); - return PyBool_FromLong((long)sval == 0); + int sval; + if (SEM_GETVALUE(self->handle, &sval) < 0) + return mp_SetError(NULL, MP_STANDARD_ERROR); + return PyBool_FromLong((long)sval == 0); #endif } static PyObject * semlock_afterfork(SemLockObject *self) { - self->count = 0; - Py_RETURN_NONE; + self->count = 0; + Py_RETURN_NONE; } /* @@ -542,27 +542,27 @@ */ static PyMethodDef semlock_methods[] = { - {"acquire", (PyCFunction)semlock_acquire, METH_VARARGS | METH_KEYWORDS, - "acquire the semaphore/lock"}, - {"release", (PyCFunction)semlock_release, METH_NOARGS, - "release the semaphore/lock"}, + {"acquire", (PyCFunction)semlock_acquire, METH_VARARGS | METH_KEYWORDS, + "acquire the semaphore/lock"}, + {"release", (PyCFunction)semlock_release, METH_NOARGS, + "release the semaphore/lock"}, {"__enter__", (PyCFunction)semlock_acquire, METH_VARARGS | METH_KEYWORDS, - "enter the semaphore/lock"}, - {"__exit__", (PyCFunction)semlock_release, METH_VARARGS, - "exit the semaphore/lock"}, - {"_count", (PyCFunction)semlock_count, METH_NOARGS, - "num of `acquire()`s minus num of `release()`s for this process"}, - {"_is_mine", (PyCFunction)semlock_ismine, METH_NOARGS, - "whether the lock is owned by this thread"}, - {"_get_value", (PyCFunction)semlock_getvalue, METH_NOARGS, - "get the value of the semaphore"}, - {"_is_zero", (PyCFunction)semlock_iszero, METH_NOARGS, - "returns whether semaphore has value zero"}, - {"_rebuild", (PyCFunction)semlock_rebuild, METH_VARARGS | METH_CLASS, - ""}, - {"_after_fork", (PyCFunction)semlock_afterfork, METH_NOARGS, - "rezero the net acquisition count after fork()"}, - {NULL} + "enter the semaphore/lock"}, + {"__exit__", (PyCFunction)semlock_release, METH_VARARGS, + "exit the semaphore/lock"}, + {"_count", (PyCFunction)semlock_count, METH_NOARGS, + "num of `acquire()`s minus num of `release()`s for this process"}, + {"_is_mine", (PyCFunction)semlock_ismine, METH_NOARGS, + "whether the lock is owned by this thread"}, + {"_get_value", (PyCFunction)semlock_getvalue, METH_NOARGS, + "get the value of the semaphore"}, + {"_is_zero", (PyCFunction)semlock_iszero, METH_NOARGS, + "returns whether semaphore has value zero"}, + {"_rebuild", (PyCFunction)semlock_rebuild, METH_VARARGS | METH_CLASS, + ""}, + {"_after_fork", (PyCFunction)semlock_afterfork, METH_NOARGS, + "rezero the net acquisition count after fork()"}, + {NULL} }; /* @@ -570,13 +570,13 @@ */ static PyMemberDef semlock_members[] = { - {"handle", T_SEM_HANDLE, offsetof(SemLockObject, handle), READONLY, - ""}, - {"kind", T_INT, offsetof(SemLockObject, kind), READONLY, - ""}, - {"maxvalue", T_INT, offsetof(SemLockObject, maxvalue), READONLY, - ""}, - {NULL} + {"handle", T_SEM_HANDLE, offsetof(SemLockObject, handle), READONLY, + ""}, + {"kind", T_INT, offsetof(SemLockObject, kind), READONLY, + ""}, + {"maxvalue", T_INT, offsetof(SemLockObject, maxvalue), READONLY, + ""}, + {NULL} }; /* @@ -584,42 +584,42 @@ */ PyTypeObject SemLockType = { - PyVarObject_HEAD_INIT(NULL, 0) - /* tp_name */ "_multiprocessing.SemLock", - /* tp_basicsize */ sizeof(SemLockObject), - /* tp_itemsize */ 0, - /* tp_dealloc */ (destructor)semlock_dealloc, - /* tp_print */ 0, - /* tp_getattr */ 0, - /* tp_setattr */ 0, - /* tp_reserved */ 0, - /* tp_repr */ 0, - /* tp_as_number */ 0, - /* tp_as_sequence */ 0, - /* tp_as_mapping */ 0, - /* tp_hash */ 0, - /* tp_call */ 0, - /* tp_str */ 0, - /* tp_getattro */ 0, - /* tp_setattro */ 0, - /* tp_as_buffer */ 0, - /* tp_flags */ Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, - /* tp_doc */ "Semaphore/Mutex type", - /* tp_traverse */ 0, - /* tp_clear */ 0, - /* tp_richcompare */ 0, - /* tp_weaklistoffset */ 0, - /* tp_iter */ 0, - /* tp_iternext */ 0, - /* tp_methods */ semlock_methods, - /* tp_members */ semlock_members, - /* tp_getset */ 0, - /* tp_base */ 0, - /* tp_dict */ 0, - /* tp_descr_get */ 0, - /* tp_descr_set */ 0, - /* tp_dictoffset */ 0, - /* tp_init */ 0, - /* tp_alloc */ 0, - /* tp_new */ semlock_new, + PyVarObject_HEAD_INIT(NULL, 0) + /* tp_name */ "_multiprocessing.SemLock", + /* tp_basicsize */ sizeof(SemLockObject), + /* tp_itemsize */ 0, + /* tp_dealloc */ (destructor)semlock_dealloc, + /* tp_print */ 0, + /* tp_getattr */ 0, + /* tp_setattr */ 0, + /* tp_reserved */ 0, + /* tp_repr */ 0, + /* tp_as_number */ 0, + /* tp_as_sequence */ 0, + /* tp_as_mapping */ 0, + /* tp_hash */ 0, + /* tp_call */ 0, + /* tp_str */ 0, + /* tp_getattro */ 0, + /* tp_setattro */ 0, + /* tp_as_buffer */ 0, + /* tp_flags */ Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, + /* tp_doc */ "Semaphore/Mutex type", + /* tp_traverse */ 0, + /* tp_clear */ 0, + /* tp_richcompare */ 0, + /* tp_weaklistoffset */ 0, + /* tp_iter */ 0, + /* tp_iternext */ 0, + /* tp_methods */ semlock_methods, + /* tp_members */ semlock_members, + /* tp_getset */ 0, + /* tp_base */ 0, + /* tp_dict */ 0, + /* tp_descr_get */ 0, + /* tp_descr_set */ 0, + /* tp_dictoffset */ 0, + /* tp_init */ 0, + /* tp_alloc */ 0, + /* tp_new */ semlock_new, }; Modified: python/branches/py3k-jit/Modules/_multiprocessing/socket_connection.c ============================================================================== --- python/branches/py3k-jit/Modules/_multiprocessing/socket_connection.c (original) +++ python/branches/py3k-jit/Modules/_multiprocessing/socket_connection.c Mon May 10 23:55:43 2010 @@ -25,45 +25,45 @@ static Py_ssize_t _conn_sendall(HANDLE h, char *string, size_t length) { - char *p = string; - Py_ssize_t res; + char *p = string; + Py_ssize_t res; - while (length > 0) { - res = WRITE(h, p, length); - if (res < 0) - return MP_SOCKET_ERROR; - length -= res; - p += res; - } + while (length > 0) { + res = WRITE(h, p, length); + if (res < 0) + return MP_SOCKET_ERROR; + length -= res; + p += res; + } - return MP_SUCCESS; + return MP_SUCCESS; } /* - * Receive string of exact length from file descriptor + * Receive string of exact length from file descriptor */ static Py_ssize_t _conn_recvall(HANDLE h, char *buffer, size_t length) { - size_t remaining = length; - Py_ssize_t temp; - char *p = buffer; - - while (remaining > 0) { - temp = READ(h, p, remaining); - if (temp <= 0) { - if (temp == 0) - return remaining == length ? - MP_END_OF_FILE : MP_EARLY_END_OF_FILE; - else - return temp; - } - remaining -= temp; - p += temp; - } + size_t remaining = length; + Py_ssize_t temp; + char *p = buffer; + + while (remaining > 0) { + temp = READ(h, p, remaining); + if (temp <= 0) { + if (temp == 0) + return remaining == length ? + MP_END_OF_FILE : MP_EARLY_END_OF_FILE; + else + return temp; + } + remaining -= temp; + p += temp; + } - return MP_SUCCESS; + return MP_SUCCESS; } /* @@ -73,38 +73,38 @@ static Py_ssize_t conn_send_string(ConnectionObject *conn, char *string, size_t length) { - Py_ssize_t res; - /* The "header" of the message is a 32 bit unsigned number (in - network order) which specifies the length of the "body". If - the message is shorter than about 16kb then it is quicker to - combine the "header" and the "body" of the message and send - them at once. */ - if (length < (16*1024)) { - char *message; - - message = PyMem_Malloc(length+4); - if (message == NULL) - return MP_MEMORY_ERROR; - - *(UINT32*)message = htonl((UINT32)length); - memcpy(message+4, string, length); - Py_BEGIN_ALLOW_THREADS - res = _conn_sendall(conn->handle, message, length+4); - Py_END_ALLOW_THREADS - PyMem_Free(message); - } else { - UINT32 lenbuff; - - if (length > MAX_MESSAGE_LENGTH) - return MP_BAD_MESSAGE_LENGTH; - - lenbuff = htonl((UINT32)length); - Py_BEGIN_ALLOW_THREADS - res = _conn_sendall(conn->handle, (char*)&lenbuff, 4) || - _conn_sendall(conn->handle, string, length); - Py_END_ALLOW_THREADS - } - return res; + Py_ssize_t res; + /* The "header" of the message is a 32 bit unsigned number (in + network order) which specifies the length of the "body". If + the message is shorter than about 16kb then it is quicker to + combine the "header" and the "body" of the message and send + them at once. */ + if (length < (16*1024)) { + char *message; + + message = PyMem_Malloc(length+4); + if (message == NULL) + return MP_MEMORY_ERROR; + + *(UINT32*)message = htonl((UINT32)length); + memcpy(message+4, string, length); + Py_BEGIN_ALLOW_THREADS + res = _conn_sendall(conn->handle, message, length+4); + Py_END_ALLOW_THREADS + PyMem_Free(message); + } else { + UINT32 lenbuff; + + if (length > MAX_MESSAGE_LENGTH) + return MP_BAD_MESSAGE_LENGTH; + + lenbuff = htonl((UINT32)length); + Py_BEGIN_ALLOW_THREADS + res = _conn_sendall(conn->handle, (char*)&lenbuff, 4) || + _conn_sendall(conn->handle, string, length); + Py_END_ALLOW_THREADS + } + return res; } /* @@ -114,38 +114,38 @@ */ static Py_ssize_t -conn_recv_string(ConnectionObject *conn, char *buffer, - size_t buflength, char **newbuffer, size_t maxlength) +conn_recv_string(ConnectionObject *conn, char *buffer, + size_t buflength, char **newbuffer, size_t maxlength) { - int res; - UINT32 ulength; + int res; + UINT32 ulength; - *newbuffer = NULL; + *newbuffer = NULL; - Py_BEGIN_ALLOW_THREADS - res = _conn_recvall(conn->handle, (char*)&ulength, 4); - Py_END_ALLOW_THREADS - if (res < 0) - return res; - - ulength = ntohl(ulength); - if (ulength > maxlength) - return MP_BAD_MESSAGE_LENGTH; - - if (ulength <= buflength) { - Py_BEGIN_ALLOW_THREADS - res = _conn_recvall(conn->handle, buffer, (size_t)ulength); - Py_END_ALLOW_THREADS - return res < 0 ? res : ulength; - } else { - *newbuffer = PyMem_Malloc((size_t)ulength); - if (*newbuffer == NULL) - return MP_MEMORY_ERROR; - Py_BEGIN_ALLOW_THREADS - res = _conn_recvall(conn->handle, *newbuffer, (size_t)ulength); - Py_END_ALLOW_THREADS - return res < 0 ? (Py_ssize_t)res : (Py_ssize_t)ulength; - } + Py_BEGIN_ALLOW_THREADS + res = _conn_recvall(conn->handle, (char*)&ulength, 4); + Py_END_ALLOW_THREADS + if (res < 0) + return res; + + ulength = ntohl(ulength); + if (ulength > maxlength) + return MP_BAD_MESSAGE_LENGTH; + + if (ulength <= buflength) { + Py_BEGIN_ALLOW_THREADS + res = _conn_recvall(conn->handle, buffer, (size_t)ulength); + Py_END_ALLOW_THREADS + return res < 0 ? res : ulength; + } else { + *newbuffer = PyMem_Malloc((size_t)ulength); + if (*newbuffer == NULL) + return MP_MEMORY_ERROR; + Py_BEGIN_ALLOW_THREADS + res = _conn_recvall(conn->handle, *newbuffer, (size_t)ulength); + Py_END_ALLOW_THREADS + return res < 0 ? (Py_ssize_t)res : (Py_ssize_t)ulength; + } } /* @@ -155,41 +155,41 @@ static int conn_poll(ConnectionObject *conn, double timeout, PyThreadState *_save) { - int res; - fd_set rfds; + int res; + fd_set rfds; - /* - * Verify the handle, issue 3321. Not required for windows. - */ - #ifndef MS_WINDOWS - if (((int)conn->handle) < 0 || ((int)conn->handle) >= FD_SETSIZE) { - Py_BLOCK_THREADS - PyErr_SetString(PyExc_IOError, "handle out of range in select()"); - Py_UNBLOCK_THREADS - return MP_EXCEPTION_HAS_BEEN_SET; - } - #endif - - FD_ZERO(&rfds); - FD_SET((SOCKET)conn->handle, &rfds); - - if (timeout < 0.0) { - res = select((int)conn->handle+1, &rfds, NULL, NULL, NULL); - } else { - struct timeval tv; - tv.tv_sec = (long)timeout; - tv.tv_usec = (long)((timeout - tv.tv_sec) * 1e6 + 0.5); - res = select((int)conn->handle+1, &rfds, NULL, NULL, &tv); - } - - if (res < 0) { - return MP_SOCKET_ERROR; - } else if (FD_ISSET(conn->handle, &rfds)) { - return TRUE; - } else { - assert(res == 0); - return FALSE; - } + /* + * Verify the handle, issue 3321. Not required for windows. + */ + #ifndef MS_WINDOWS + if (((int)conn->handle) < 0 || ((int)conn->handle) >= FD_SETSIZE) { + Py_BLOCK_THREADS + PyErr_SetString(PyExc_IOError, "handle out of range in select()"); + Py_UNBLOCK_THREADS + return MP_EXCEPTION_HAS_BEEN_SET; + } + #endif + + FD_ZERO(&rfds); + FD_SET((SOCKET)conn->handle, &rfds); + + if (timeout < 0.0) { + res = select((int)conn->handle+1, &rfds, NULL, NULL, NULL); + } else { + struct timeval tv; + tv.tv_sec = (long)timeout; + tv.tv_usec = (long)((timeout - tv.tv_sec) * 1e6 + 0.5); + res = select((int)conn->handle+1, &rfds, NULL, NULL, &tv); + } + + if (res < 0) { + return MP_SOCKET_ERROR; + } else if (FD_ISSET(conn->handle, &rfds)) { + return TRUE; + } else { + assert(res == 0); + return FALSE; + } } /* Modified: python/branches/py3k-jit/Modules/_multiprocessing/win32_functions.c ============================================================================== --- python/branches/py3k-jit/Modules/_multiprocessing/win32_functions.c (original) +++ python/branches/py3k-jit/Modules/_multiprocessing/win32_functions.c Mon May 10 23:55:43 2010 @@ -19,248 +19,248 @@ static PyObject * win32_CloseHandle(PyObject *self, PyObject *args) { - HANDLE hObject; - BOOL success; + HANDLE hObject; + BOOL success; - if (!PyArg_ParseTuple(args, F_HANDLE, &hObject)) - return NULL; + if (!PyArg_ParseTuple(args, F_HANDLE, &hObject)) + return NULL; - Py_BEGIN_ALLOW_THREADS - success = CloseHandle(hObject); - Py_END_ALLOW_THREADS + Py_BEGIN_ALLOW_THREADS + success = CloseHandle(hObject); + Py_END_ALLOW_THREADS - if (!success) - return PyErr_SetFromWindowsErr(0); + if (!success) + return PyErr_SetFromWindowsErr(0); - Py_RETURN_NONE; + Py_RETURN_NONE; } static PyObject * win32_ConnectNamedPipe(PyObject *self, PyObject *args) { - HANDLE hNamedPipe; - LPOVERLAPPED lpOverlapped; - BOOL success; - - if (!PyArg_ParseTuple(args, F_HANDLE F_POINTER, - &hNamedPipe, &lpOverlapped)) - return NULL; - - Py_BEGIN_ALLOW_THREADS - success = ConnectNamedPipe(hNamedPipe, lpOverlapped); - Py_END_ALLOW_THREADS + HANDLE hNamedPipe; + LPOVERLAPPED lpOverlapped; + BOOL success; + + if (!PyArg_ParseTuple(args, F_HANDLE F_POINTER, + &hNamedPipe, &lpOverlapped)) + return NULL; + + Py_BEGIN_ALLOW_THREADS + success = ConnectNamedPipe(hNamedPipe, lpOverlapped); + Py_END_ALLOW_THREADS - if (!success) - return PyErr_SetFromWindowsErr(0); + if (!success) + return PyErr_SetFromWindowsErr(0); - Py_RETURN_NONE; + Py_RETURN_NONE; } static PyObject * win32_CreateFile(PyObject *self, PyObject *args) { - LPCTSTR lpFileName; - DWORD dwDesiredAccess; - DWORD dwShareMode; - LPSECURITY_ATTRIBUTES lpSecurityAttributes; - DWORD dwCreationDisposition; - DWORD dwFlagsAndAttributes; - HANDLE hTemplateFile; - HANDLE handle; - - if (!PyArg_ParseTuple(args, "s" F_DWORD F_DWORD F_POINTER - F_DWORD F_DWORD F_HANDLE, - &lpFileName, &dwDesiredAccess, &dwShareMode, - &lpSecurityAttributes, &dwCreationDisposition, - &dwFlagsAndAttributes, &hTemplateFile)) - return NULL; - - Py_BEGIN_ALLOW_THREADS - handle = CreateFile(lpFileName, dwDesiredAccess, - dwShareMode, lpSecurityAttributes, - dwCreationDisposition, - dwFlagsAndAttributes, hTemplateFile); - Py_END_ALLOW_THREADS + LPCTSTR lpFileName; + DWORD dwDesiredAccess; + DWORD dwShareMode; + LPSECURITY_ATTRIBUTES lpSecurityAttributes; + DWORD dwCreationDisposition; + DWORD dwFlagsAndAttributes; + HANDLE hTemplateFile; + HANDLE handle; + + if (!PyArg_ParseTuple(args, "s" F_DWORD F_DWORD F_POINTER + F_DWORD F_DWORD F_HANDLE, + &lpFileName, &dwDesiredAccess, &dwShareMode, + &lpSecurityAttributes, &dwCreationDisposition, + &dwFlagsAndAttributes, &hTemplateFile)) + return NULL; + + Py_BEGIN_ALLOW_THREADS + handle = CreateFile(lpFileName, dwDesiredAccess, + dwShareMode, lpSecurityAttributes, + dwCreationDisposition, + dwFlagsAndAttributes, hTemplateFile); + Py_END_ALLOW_THREADS - if (handle == INVALID_HANDLE_VALUE) - return PyErr_SetFromWindowsErr(0); + if (handle == INVALID_HANDLE_VALUE) + return PyErr_SetFromWindowsErr(0); - return Py_BuildValue(F_HANDLE, handle); + return Py_BuildValue(F_HANDLE, handle); } static PyObject * win32_CreateNamedPipe(PyObject *self, PyObject *args) { - LPCTSTR lpName; - DWORD dwOpenMode; - DWORD dwPipeMode; - DWORD nMaxInstances; - DWORD nOutBufferSize; - DWORD nInBufferSize; - DWORD nDefaultTimeOut; - LPSECURITY_ATTRIBUTES lpSecurityAttributes; - HANDLE handle; - - if (!PyArg_ParseTuple(args, "s" F_DWORD F_DWORD F_DWORD - F_DWORD F_DWORD F_DWORD F_POINTER, - &lpName, &dwOpenMode, &dwPipeMode, - &nMaxInstances, &nOutBufferSize, - &nInBufferSize, &nDefaultTimeOut, - &lpSecurityAttributes)) - return NULL; - - Py_BEGIN_ALLOW_THREADS - handle = CreateNamedPipe(lpName, dwOpenMode, dwPipeMode, - nMaxInstances, nOutBufferSize, - nInBufferSize, nDefaultTimeOut, - lpSecurityAttributes); - Py_END_ALLOW_THREADS + LPCTSTR lpName; + DWORD dwOpenMode; + DWORD dwPipeMode; + DWORD nMaxInstances; + DWORD nOutBufferSize; + DWORD nInBufferSize; + DWORD nDefaultTimeOut; + LPSECURITY_ATTRIBUTES lpSecurityAttributes; + HANDLE handle; + + if (!PyArg_ParseTuple(args, "s" F_DWORD F_DWORD F_DWORD + F_DWORD F_DWORD F_DWORD F_POINTER, + &lpName, &dwOpenMode, &dwPipeMode, + &nMaxInstances, &nOutBufferSize, + &nInBufferSize, &nDefaultTimeOut, + &lpSecurityAttributes)) + return NULL; + + Py_BEGIN_ALLOW_THREADS + handle = CreateNamedPipe(lpName, dwOpenMode, dwPipeMode, + nMaxInstances, nOutBufferSize, + nInBufferSize, nDefaultTimeOut, + lpSecurityAttributes); + Py_END_ALLOW_THREADS - if (handle == INVALID_HANDLE_VALUE) - return PyErr_SetFromWindowsErr(0); + if (handle == INVALID_HANDLE_VALUE) + return PyErr_SetFromWindowsErr(0); - return Py_BuildValue(F_HANDLE, handle); + return Py_BuildValue(F_HANDLE, handle); } static PyObject * win32_ExitProcess(PyObject *self, PyObject *args) { - UINT uExitCode; + UINT uExitCode; - if (!PyArg_ParseTuple(args, "I", &uExitCode)) - return NULL; + if (!PyArg_ParseTuple(args, "I", &uExitCode)) + return NULL; - #if defined(Py_DEBUG) - SetErrorMode(SEM_FAILCRITICALERRORS|SEM_NOALIGNMENTFAULTEXCEPT|SEM_NOGPFAULTERRORBOX|SEM_NOOPENFILEERRORBOX); - _CrtSetReportMode(_CRT_ASSERT, _CRTDBG_MODE_DEBUG); - #endif + #if defined(Py_DEBUG) + SetErrorMode(SEM_FAILCRITICALERRORS|SEM_NOALIGNMENTFAULTEXCEPT|SEM_NOGPFAULTERRORBOX|SEM_NOOPENFILEERRORBOX); + _CrtSetReportMode(_CRT_ASSERT, _CRTDBG_MODE_DEBUG); + #endif - ExitProcess(uExitCode); + ExitProcess(uExitCode); - return NULL; + return NULL; } static PyObject * win32_GetLastError(PyObject *self, PyObject *args) { - return Py_BuildValue(F_DWORD, GetLastError()); + return Py_BuildValue(F_DWORD, GetLastError()); } static PyObject * win32_OpenProcess(PyObject *self, PyObject *args) { - DWORD dwDesiredAccess; - BOOL bInheritHandle; - DWORD dwProcessId; - HANDLE handle; - - if (!PyArg_ParseTuple(args, F_DWORD "i" F_DWORD, - &dwDesiredAccess, &bInheritHandle, &dwProcessId)) - return NULL; - - handle = OpenProcess(dwDesiredAccess, bInheritHandle, dwProcessId); - if (handle == NULL) - return PyErr_SetFromWindowsErr(0); + DWORD dwDesiredAccess; + BOOL bInheritHandle; + DWORD dwProcessId; + HANDLE handle; + + if (!PyArg_ParseTuple(args, F_DWORD "i" F_DWORD, + &dwDesiredAccess, &bInheritHandle, &dwProcessId)) + return NULL; + + handle = OpenProcess(dwDesiredAccess, bInheritHandle, dwProcessId); + if (handle == NULL) + return PyErr_SetFromWindowsErr(0); - return Py_BuildValue(F_HANDLE, handle); + return Py_BuildValue(F_HANDLE, handle); } static PyObject * win32_SetNamedPipeHandleState(PyObject *self, PyObject *args) { - HANDLE hNamedPipe; - PyObject *oArgs[3]; - DWORD dwArgs[3], *pArgs[3] = {NULL, NULL, NULL}; - int i; - - if (!PyArg_ParseTuple(args, F_HANDLE "OOO", - &hNamedPipe, &oArgs[0], &oArgs[1], &oArgs[2])) - return NULL; - - PyErr_Clear(); - - for (i = 0 ; i < 3 ; i++) { - if (oArgs[i] != Py_None) { - dwArgs[i] = PyLong_AsUnsignedLongMask(oArgs[i]); - if (PyErr_Occurred()) - return NULL; - pArgs[i] = &dwArgs[i]; - } - } + HANDLE hNamedPipe; + PyObject *oArgs[3]; + DWORD dwArgs[3], *pArgs[3] = {NULL, NULL, NULL}; + int i; + + if (!PyArg_ParseTuple(args, F_HANDLE "OOO", + &hNamedPipe, &oArgs[0], &oArgs[1], &oArgs[2])) + return NULL; + + PyErr_Clear(); + + for (i = 0 ; i < 3 ; i++) { + if (oArgs[i] != Py_None) { + dwArgs[i] = PyLong_AsUnsignedLongMask(oArgs[i]); + if (PyErr_Occurred()) + return NULL; + pArgs[i] = &dwArgs[i]; + } + } - if (!SetNamedPipeHandleState(hNamedPipe, pArgs[0], pArgs[1], pArgs[2])) - return PyErr_SetFromWindowsErr(0); + if (!SetNamedPipeHandleState(hNamedPipe, pArgs[0], pArgs[1], pArgs[2])) + return PyErr_SetFromWindowsErr(0); - Py_RETURN_NONE; + Py_RETURN_NONE; } static PyObject * win32_WaitNamedPipe(PyObject *self, PyObject *args) { - LPCTSTR lpNamedPipeName; - DWORD nTimeOut; - BOOL success; + LPCTSTR lpNamedPipeName; + DWORD nTimeOut; + BOOL success; - if (!PyArg_ParseTuple(args, "s" F_DWORD, &lpNamedPipeName, &nTimeOut)) - return NULL; + if (!PyArg_ParseTuple(args, "s" F_DWORD, &lpNamedPipeName, &nTimeOut)) + return NULL; - Py_BEGIN_ALLOW_THREADS - success = WaitNamedPipe(lpNamedPipeName, nTimeOut); - Py_END_ALLOW_THREADS + Py_BEGIN_ALLOW_THREADS + success = WaitNamedPipe(lpNamedPipeName, nTimeOut); + Py_END_ALLOW_THREADS - if (!success) - return PyErr_SetFromWindowsErr(0); + if (!success) + return PyErr_SetFromWindowsErr(0); - Py_RETURN_NONE; + Py_RETURN_NONE; } static PyMethodDef win32_methods[] = { - WIN32_FUNCTION(CloseHandle), - WIN32_FUNCTION(GetLastError), - WIN32_FUNCTION(OpenProcess), - WIN32_FUNCTION(ExitProcess), - WIN32_FUNCTION(ConnectNamedPipe), - WIN32_FUNCTION(CreateFile), - WIN32_FUNCTION(CreateNamedPipe), - WIN32_FUNCTION(SetNamedPipeHandleState), - WIN32_FUNCTION(WaitNamedPipe), - {NULL} + WIN32_FUNCTION(CloseHandle), + WIN32_FUNCTION(GetLastError), + WIN32_FUNCTION(OpenProcess), + WIN32_FUNCTION(ExitProcess), + WIN32_FUNCTION(ConnectNamedPipe), + WIN32_FUNCTION(CreateFile), + WIN32_FUNCTION(CreateNamedPipe), + WIN32_FUNCTION(SetNamedPipeHandleState), + WIN32_FUNCTION(WaitNamedPipe), + {NULL} }; PyTypeObject Win32Type = { - PyVarObject_HEAD_INIT(NULL, 0) + PyVarObject_HEAD_INIT(NULL, 0) }; PyObject * create_win32_namespace(void) { - Win32Type.tp_name = "_multiprocessing.win32"; - Win32Type.tp_methods = win32_methods; - if (PyType_Ready(&Win32Type) < 0) - return NULL; - Py_INCREF(&Win32Type); - - WIN32_CONSTANT(F_DWORD, ERROR_ALREADY_EXISTS); - WIN32_CONSTANT(F_DWORD, ERROR_PIPE_BUSY); - WIN32_CONSTANT(F_DWORD, ERROR_PIPE_CONNECTED); - WIN32_CONSTANT(F_DWORD, ERROR_SEM_TIMEOUT); - WIN32_CONSTANT(F_DWORD, GENERIC_READ); - WIN32_CONSTANT(F_DWORD, GENERIC_WRITE); - WIN32_CONSTANT(F_DWORD, INFINITE); - WIN32_CONSTANT(F_DWORD, NMPWAIT_WAIT_FOREVER); - WIN32_CONSTANT(F_DWORD, OPEN_EXISTING); - WIN32_CONSTANT(F_DWORD, PIPE_ACCESS_DUPLEX); - WIN32_CONSTANT(F_DWORD, PIPE_ACCESS_INBOUND); - WIN32_CONSTANT(F_DWORD, PIPE_READMODE_MESSAGE); - WIN32_CONSTANT(F_DWORD, PIPE_TYPE_MESSAGE); - WIN32_CONSTANT(F_DWORD, PIPE_UNLIMITED_INSTANCES); - WIN32_CONSTANT(F_DWORD, PIPE_WAIT); - WIN32_CONSTANT(F_DWORD, PROCESS_ALL_ACCESS); + Win32Type.tp_name = "_multiprocessing.win32"; + Win32Type.tp_methods = win32_methods; + if (PyType_Ready(&Win32Type) < 0) + return NULL; + Py_INCREF(&Win32Type); + + WIN32_CONSTANT(F_DWORD, ERROR_ALREADY_EXISTS); + WIN32_CONSTANT(F_DWORD, ERROR_PIPE_BUSY); + WIN32_CONSTANT(F_DWORD, ERROR_PIPE_CONNECTED); + WIN32_CONSTANT(F_DWORD, ERROR_SEM_TIMEOUT); + WIN32_CONSTANT(F_DWORD, GENERIC_READ); + WIN32_CONSTANT(F_DWORD, GENERIC_WRITE); + WIN32_CONSTANT(F_DWORD, INFINITE); + WIN32_CONSTANT(F_DWORD, NMPWAIT_WAIT_FOREVER); + WIN32_CONSTANT(F_DWORD, OPEN_EXISTING); + WIN32_CONSTANT(F_DWORD, PIPE_ACCESS_DUPLEX); + WIN32_CONSTANT(F_DWORD, PIPE_ACCESS_INBOUND); + WIN32_CONSTANT(F_DWORD, PIPE_READMODE_MESSAGE); + WIN32_CONSTANT(F_DWORD, PIPE_TYPE_MESSAGE); + WIN32_CONSTANT(F_DWORD, PIPE_UNLIMITED_INSTANCES); + WIN32_CONSTANT(F_DWORD, PIPE_WAIT); + WIN32_CONSTANT(F_DWORD, PROCESS_ALL_ACCESS); - WIN32_CONSTANT("i", NULL); + WIN32_CONSTANT("i", NULL); - return (PyObject*)&Win32Type; + return (PyObject*)&Win32Type; } Modified: python/branches/py3k-jit/Modules/_randommodule.c ============================================================================== --- python/branches/py3k-jit/Modules/_randommodule.c (original) +++ python/branches/py3k-jit/Modules/_randommodule.c Mon May 10 23:55:43 2010 @@ -2,23 +2,23 @@ /* ------------------------------------------------------------------ The code in this module was based on a download from: - http://www.math.keio.ac.jp/~matumoto/MT2002/emt19937ar.html + http://www.math.keio.ac.jp/~matumoto/MT2002/emt19937ar.html It was modified in 2002 by Raymond Hettinger as follows: - * the principal computational lines untouched except for tabbing. + * the principal computational lines untouched except for tabbing. - * renamed genrand_res53() to random_random() and wrapped - in python calling/return code. + * renamed genrand_res53() to random_random() and wrapped + in python calling/return code. - * genrand_int32() and the helper functions, init_genrand() - and init_by_array(), were declared static, wrapped in - Python calling/return code. also, their global data - references were replaced with structure references. - - * unused functions from the original were deleted. - new, original C python code was added to implement the - Random() interface. + * genrand_int32() and the helper functions, init_genrand() + and init_by_array(), were declared static, wrapped in + Python calling/return code. also, their global data + references were replaced with structure references. + + * unused functions from the original were deleted. + new, original C python code was added to implement the + Random() interface. The following are the verbatim comments from the original code: @@ -36,15 +36,15 @@ are met: 1. Redistributions of source code must retain the above copyright - notice, this list of conditions and the following disclaimer. + 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. + 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. + 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 @@ -67,24 +67,24 @@ /* ---------------------------------------------------------------*/ #include "Python.h" -#include /* for seeding to current time */ +#include /* for seeding to current time */ /* Period parameters -- These are all magic. Don't change. */ #define N 624 #define M 397 -#define MATRIX_A 0x9908b0dfUL /* constant vector a */ +#define MATRIX_A 0x9908b0dfUL /* constant vector a */ #define UPPER_MASK 0x80000000UL /* most significant w-r bits */ #define LOWER_MASK 0x7fffffffUL /* least significant r bits */ typedef struct { - PyObject_HEAD - unsigned long state[N]; - int index; + PyObject_HEAD + unsigned long state[N]; + int index; } RandomObject; static PyTypeObject Random_Type; -#define RandomObject_Check(v) (Py_TYPE(v) == &Random_Type) +#define RandomObject_Check(v) (Py_TYPE(v) == &Random_Type) /* Random methods */ @@ -94,28 +94,28 @@ static unsigned long genrand_int32(RandomObject *self) { - unsigned long y; - static unsigned long mag01[2]={0x0UL, MATRIX_A}; - /* mag01[x] = x * MATRIX_A for x=0,1 */ - unsigned long *mt; - - mt = self->state; - if (self->index >= N) { /* generate N words at one time */ - int kk; - - for (kk=0;kk> 1) ^ mag01[y & 0x1UL]; - } - for (;kk> 1) ^ mag01[y & 0x1UL]; - } - y = (mt[N-1]&UPPER_MASK)|(mt[0]&LOWER_MASK); - mt[N-1] = mt[M-1] ^ (y >> 1) ^ mag01[y & 0x1UL]; + unsigned long y; + static unsigned long mag01[2]={0x0UL, MATRIX_A}; + /* mag01[x] = x * MATRIX_A for x=0,1 */ + unsigned long *mt; + + mt = self->state; + if (self->index >= N) { /* generate N words at one time */ + int kk; + + for (kk=0;kk> 1) ^ mag01[y & 0x1UL]; + } + for (;kk> 1) ^ mag01[y & 0x1UL]; + } + y = (mt[N-1]&UPPER_MASK)|(mt[0]&LOWER_MASK); + mt[N-1] = mt[M-1] ^ (y >> 1) ^ mag01[y & 0x1UL]; - self->index = 0; - } + self->index = 0; + } y = mt[self->index++]; y ^= (y >> 11); @@ -137,31 +137,31 @@ static PyObject * random_random(RandomObject *self) { - unsigned long a=genrand_int32(self)>>5, b=genrand_int32(self)>>6; - return PyFloat_FromDouble((a*67108864.0+b)*(1.0/9007199254740992.0)); + unsigned long a=genrand_int32(self)>>5, b=genrand_int32(self)>>6; + return PyFloat_FromDouble((a*67108864.0+b)*(1.0/9007199254740992.0)); } /* initializes mt[N] with a seed */ static void init_genrand(RandomObject *self, unsigned long s) { - int mti; - unsigned long *mt; + int mti; + unsigned long *mt; - mt = self->state; - mt[0]= s & 0xffffffffUL; - for (mti=1; mti> 30)) + mti); - /* See Knuth TAOCP Vol2. 3rd Ed. P.106 for multiplier. */ - /* In the previous versions, MSBs of the seed affect */ - /* only MSBs of the array mt[]. */ - /* 2002/01/09 modified by Makoto Matsumoto */ - mt[mti] &= 0xffffffffUL; - /* for >32 bit machines */ - } - self->index = mti; - return; + mt = self->state; + mt[0]= s & 0xffffffffUL; + for (mti=1; mti> 30)) + mti); + /* See Knuth TAOCP Vol2. 3rd Ed. P.106 for multiplier. */ + /* In the previous versions, MSBs of the seed affect */ + /* only MSBs of the array mt[]. */ + /* 2002/01/09 modified by Makoto Matsumoto */ + mt[mti] &= 0xffffffffUL; + /* for >32 bit machines */ + } + self->index = mti; + return; } /* initialize by an array with array-length */ @@ -170,28 +170,28 @@ static PyObject * init_by_array(RandomObject *self, unsigned long init_key[], unsigned long key_length) { - unsigned int i, j, k; /* was signed in the original code. RDH 12/16/2002 */ - unsigned long *mt; + unsigned int i, j, k; /* was signed in the original code. RDH 12/16/2002 */ + unsigned long *mt; - mt = self->state; - init_genrand(self, 19650218UL); - i=1; j=0; - k = (N>key_length ? N : key_length); - for (; k; k--) { - mt[i] = (mt[i] ^ ((mt[i-1] ^ (mt[i-1] >> 30)) * 1664525UL)) - + init_key[j] + j; /* non linear */ - mt[i] &= 0xffffffffUL; /* for WORDSIZE > 32 machines */ - i++; j++; - if (i>=N) { mt[0] = mt[N-1]; i=1; } - if (j>=key_length) j=0; - } - for (k=N-1; k; k--) { - mt[i] = (mt[i] ^ ((mt[i-1] ^ (mt[i-1] >> 30)) * 1566083941UL)) - - i; /* non linear */ - mt[i] &= 0xffffffffUL; /* for WORDSIZE > 32 machines */ - i++; - if (i>=N) { mt[0] = mt[N-1]; i=1; } - } + mt = self->state; + init_genrand(self, 19650218UL); + i=1; j=0; + k = (N>key_length ? N : key_length); + for (; k; k--) { + mt[i] = (mt[i] ^ ((mt[i-1] ^ (mt[i-1] >> 30)) * 1664525UL)) + + init_key[j] + j; /* non linear */ + mt[i] &= 0xffffffffUL; /* for WORDSIZE > 32 machines */ + i++; j++; + if (i>=N) { mt[0] = mt[N-1]; i=1; } + if (j>=key_length) j=0; + } + for (k=N-1; k; k--) { + mt[i] = (mt[i] ^ ((mt[i-1] ^ (mt[i-1] >> 30)) * 1566083941UL)) + - i; /* non linear */ + mt[i] &= 0xffffffffUL; /* for WORDSIZE > 32 machines */ + i++; + if (i>=N) { mt[0] = mt[N-1]; i=1; } + } mt[0] = 0x80000000UL; /* MSB is 1; assuring non-zero initial array */ Py_INCREF(Py_None); @@ -206,291 +206,291 @@ static PyObject * random_seed(RandomObject *self, PyObject *args) { - PyObject *result = NULL; /* guilty until proved innocent */ - PyObject *masklower = NULL; - PyObject *thirtytwo = NULL; - PyObject *n = NULL; - unsigned long *key = NULL; - unsigned long keymax; /* # of allocated slots in key */ - unsigned long keyused; /* # of used slots in key */ - int err; - - PyObject *arg = NULL; - - if (!PyArg_UnpackTuple(args, "seed", 0, 1, &arg)) - return NULL; - - if (arg == NULL || arg == Py_None) { - time_t now; - - time(&now); - init_genrand(self, (unsigned long)now); - Py_INCREF(Py_None); - return Py_None; - } - /* If the arg is an int or long, use its absolute value; else use - * the absolute value of its hash code. - */ - if (PyLong_Check(arg)) - n = PyNumber_Absolute(arg); - else { - long hash = PyObject_Hash(arg); - if (hash == -1) - goto Done; - n = PyLong_FromUnsignedLong((unsigned long)hash); - } - if (n == NULL) - goto Done; - - /* Now split n into 32-bit chunks, from the right. Each piece is - * stored into key, which has a capacity of keymax chunks, of which - * keyused are filled. Alas, the repeated shifting makes this a - * quadratic-time algorithm; we'd really like to use - * _PyLong_AsByteArray here, but then we'd have to break into the - * long representation to figure out how big an array was needed - * in advance. - */ - keymax = 8; /* arbitrary; grows later if needed */ - keyused = 0; - key = (unsigned long *)PyMem_Malloc(keymax * sizeof(*key)); - if (key == NULL) - goto Done; - - masklower = PyLong_FromUnsignedLong(0xffffffffU); - if (masklower == NULL) - goto Done; - thirtytwo = PyLong_FromLong(32L); - if (thirtytwo == NULL) - goto Done; - while ((err=PyObject_IsTrue(n))) { - PyObject *newn; - PyObject *pychunk; - unsigned long chunk; - - if (err == -1) - goto Done; - pychunk = PyNumber_And(n, masklower); - if (pychunk == NULL) - goto Done; - chunk = PyLong_AsUnsignedLong(pychunk); - Py_DECREF(pychunk); - if (chunk == (unsigned long)-1 && PyErr_Occurred()) - goto Done; - newn = PyNumber_Rshift(n, thirtytwo); - if (newn == NULL) - goto Done; - Py_DECREF(n); - n = newn; - if (keyused >= keymax) { - unsigned long bigger = keymax << 1; - if ((bigger >> 1) != keymax) { - PyErr_NoMemory(); - goto Done; - } - key = (unsigned long *)PyMem_Realloc(key, - bigger * sizeof(*key)); - if (key == NULL) - goto Done; - keymax = bigger; - } - assert(keyused < keymax); - key[keyused++] = chunk; - } - - if (keyused == 0) - key[keyused++] = 0UL; - result = init_by_array(self, key, keyused); + PyObject *result = NULL; /* guilty until proved innocent */ + PyObject *masklower = NULL; + PyObject *thirtytwo = NULL; + PyObject *n = NULL; + unsigned long *key = NULL; + unsigned long keymax; /* # of allocated slots in key */ + unsigned long keyused; /* # of used slots in key */ + int err; + + PyObject *arg = NULL; + + if (!PyArg_UnpackTuple(args, "seed", 0, 1, &arg)) + return NULL; + + if (arg == NULL || arg == Py_None) { + time_t now; + + time(&now); + init_genrand(self, (unsigned long)now); + Py_INCREF(Py_None); + return Py_None; + } + /* If the arg is an int or long, use its absolute value; else use + * the absolute value of its hash code. + */ + if (PyLong_Check(arg)) + n = PyNumber_Absolute(arg); + else { + long hash = PyObject_Hash(arg); + if (hash == -1) + goto Done; + n = PyLong_FromUnsignedLong((unsigned long)hash); + } + if (n == NULL) + goto Done; + + /* Now split n into 32-bit chunks, from the right. Each piece is + * stored into key, which has a capacity of keymax chunks, of which + * keyused are filled. Alas, the repeated shifting makes this a + * quadratic-time algorithm; we'd really like to use + * _PyLong_AsByteArray here, but then we'd have to break into the + * long representation to figure out how big an array was needed + * in advance. + */ + keymax = 8; /* arbitrary; grows later if needed */ + keyused = 0; + key = (unsigned long *)PyMem_Malloc(keymax * sizeof(*key)); + if (key == NULL) + goto Done; + + masklower = PyLong_FromUnsignedLong(0xffffffffU); + if (masklower == NULL) + goto Done; + thirtytwo = PyLong_FromLong(32L); + if (thirtytwo == NULL) + goto Done; + while ((err=PyObject_IsTrue(n))) { + PyObject *newn; + PyObject *pychunk; + unsigned long chunk; + + if (err == -1) + goto Done; + pychunk = PyNumber_And(n, masklower); + if (pychunk == NULL) + goto Done; + chunk = PyLong_AsUnsignedLong(pychunk); + Py_DECREF(pychunk); + if (chunk == (unsigned long)-1 && PyErr_Occurred()) + goto Done; + newn = PyNumber_Rshift(n, thirtytwo); + if (newn == NULL) + goto Done; + Py_DECREF(n); + n = newn; + if (keyused >= keymax) { + unsigned long bigger = keymax << 1; + if ((bigger >> 1) != keymax) { + PyErr_NoMemory(); + goto Done; + } + key = (unsigned long *)PyMem_Realloc(key, + bigger * sizeof(*key)); + if (key == NULL) + goto Done; + keymax = bigger; + } + assert(keyused < keymax); + key[keyused++] = chunk; + } + + if (keyused == 0) + key[keyused++] = 0UL; + result = init_by_array(self, key, keyused); Done: - Py_XDECREF(masklower); - Py_XDECREF(thirtytwo); - Py_XDECREF(n); - PyMem_Free(key); - return result; + Py_XDECREF(masklower); + Py_XDECREF(thirtytwo); + Py_XDECREF(n); + PyMem_Free(key); + return result; } static PyObject * random_getstate(RandomObject *self) { - PyObject *state; - PyObject *element; - int i; - - state = PyTuple_New(N+1); - if (state == NULL) - return NULL; - for (i=0; istate[i]); - if (element == NULL) - goto Fail; - PyTuple_SET_ITEM(state, i, element); - } - element = PyLong_FromLong((long)(self->index)); - if (element == NULL) - goto Fail; - PyTuple_SET_ITEM(state, i, element); - return state; + PyObject *state; + PyObject *element; + int i; + + state = PyTuple_New(N+1); + if (state == NULL) + return NULL; + for (i=0; istate[i]); + if (element == NULL) + goto Fail; + PyTuple_SET_ITEM(state, i, element); + } + element = PyLong_FromLong((long)(self->index)); + if (element == NULL) + goto Fail; + PyTuple_SET_ITEM(state, i, element); + return state; Fail: - Py_DECREF(state); - return NULL; + Py_DECREF(state); + return NULL; } static PyObject * random_setstate(RandomObject *self, PyObject *state) { - int i; - unsigned long element; - long index; - - if (!PyTuple_Check(state)) { - PyErr_SetString(PyExc_TypeError, - "state vector must be a tuple"); - return NULL; - } - if (PyTuple_Size(state) != N+1) { - PyErr_SetString(PyExc_ValueError, - "state vector is the wrong size"); - return NULL; - } - - for (i=0; istate[i] = element & 0xffffffffUL; /* Make sure we get sane state */ - } - - index = PyLong_AsLong(PyTuple_GET_ITEM(state, i)); - if (index == -1 && PyErr_Occurred()) - return NULL; - self->index = (int)index; + int i; + unsigned long element; + long index; + + if (!PyTuple_Check(state)) { + PyErr_SetString(PyExc_TypeError, + "state vector must be a tuple"); + return NULL; + } + if (PyTuple_Size(state) != N+1) { + PyErr_SetString(PyExc_ValueError, + "state vector is the wrong size"); + return NULL; + } + + for (i=0; istate[i] = element & 0xffffffffUL; /* Make sure we get sane state */ + } + + index = PyLong_AsLong(PyTuple_GET_ITEM(state, i)); + if (index == -1 && PyErr_Occurred()) + return NULL; + self->index = (int)index; - Py_INCREF(Py_None); - return Py_None; + Py_INCREF(Py_None); + return Py_None; } static PyObject * random_getrandbits(RandomObject *self, PyObject *args) { - int k, i, bytes; - unsigned long r; - unsigned char *bytearray; - PyObject *result; - - if (!PyArg_ParseTuple(args, "i:getrandbits", &k)) - return NULL; - - if (k <= 0) { - PyErr_SetString(PyExc_ValueError, - "number of bits must be greater than zero"); - return NULL; - } - - bytes = ((k - 1) / 32 + 1) * 4; - bytearray = (unsigned char *)PyMem_Malloc(bytes); - if (bytearray == NULL) { - PyErr_NoMemory(); - return NULL; - } - - /* Fill-out whole words, byte-by-byte to avoid endianness issues */ - for (i=0 ; i>= (32 - k); - bytearray[i+0] = (unsigned char)r; - bytearray[i+1] = (unsigned char)(r >> 8); - bytearray[i+2] = (unsigned char)(r >> 16); - bytearray[i+3] = (unsigned char)(r >> 24); - } - - /* little endian order to match bytearray assignment order */ - result = _PyLong_FromByteArray(bytearray, bytes, 1, 0); - PyMem_Free(bytearray); - return result; + int k, i, bytes; + unsigned long r; + unsigned char *bytearray; + PyObject *result; + + if (!PyArg_ParseTuple(args, "i:getrandbits", &k)) + return NULL; + + if (k <= 0) { + PyErr_SetString(PyExc_ValueError, + "number of bits must be greater than zero"); + return NULL; + } + + bytes = ((k - 1) / 32 + 1) * 4; + bytearray = (unsigned char *)PyMem_Malloc(bytes); + if (bytearray == NULL) { + PyErr_NoMemory(); + return NULL; + } + + /* Fill-out whole words, byte-by-byte to avoid endianness issues */ + for (i=0 ; i>= (32 - k); + bytearray[i+0] = (unsigned char)r; + bytearray[i+1] = (unsigned char)(r >> 8); + bytearray[i+2] = (unsigned char)(r >> 16); + bytearray[i+3] = (unsigned char)(r >> 24); + } + + /* little endian order to match bytearray assignment order */ + result = _PyLong_FromByteArray(bytearray, bytes, 1, 0); + PyMem_Free(bytearray); + return result; } static PyObject * random_new(PyTypeObject *type, PyObject *args, PyObject *kwds) { - RandomObject *self; - PyObject *tmp; + RandomObject *self; + PyObject *tmp; - if (type == &Random_Type && !_PyArg_NoKeywords("Random()", kwds)) - return NULL; + if (type == &Random_Type && !_PyArg_NoKeywords("Random()", kwds)) + return NULL; - self = (RandomObject *)type->tp_alloc(type, 0); - if (self == NULL) - return NULL; - tmp = random_seed(self, args); - if (tmp == NULL) { - Py_DECREF(self); - return NULL; - } - Py_DECREF(tmp); - return (PyObject *)self; + self = (RandomObject *)type->tp_alloc(type, 0); + if (self == NULL) + return NULL; + tmp = random_seed(self, args); + if (tmp == NULL) { + Py_DECREF(self); + return NULL; + } + Py_DECREF(tmp); + return (PyObject *)self; } static PyMethodDef random_methods[] = { - {"random", (PyCFunction)random_random, METH_NOARGS, - PyDoc_STR("random() -> x in the interval [0, 1).")}, - {"seed", (PyCFunction)random_seed, METH_VARARGS, - PyDoc_STR("seed([n]) -> None. Defaults to current time.")}, - {"getstate", (PyCFunction)random_getstate, METH_NOARGS, - PyDoc_STR("getstate() -> tuple containing the current state.")}, - {"setstate", (PyCFunction)random_setstate, METH_O, - PyDoc_STR("setstate(state) -> None. Restores generator state.")}, - {"getrandbits", (PyCFunction)random_getrandbits, METH_VARARGS, - PyDoc_STR("getrandbits(k) -> x. Generates a long int with " - "k random bits.")}, - {NULL, NULL} /* sentinel */ + {"random", (PyCFunction)random_random, METH_NOARGS, + PyDoc_STR("random() -> x in the interval [0, 1).")}, + {"seed", (PyCFunction)random_seed, METH_VARARGS, + PyDoc_STR("seed([n]) -> None. Defaults to current time.")}, + {"getstate", (PyCFunction)random_getstate, METH_NOARGS, + PyDoc_STR("getstate() -> tuple containing the current state.")}, + {"setstate", (PyCFunction)random_setstate, METH_O, + PyDoc_STR("setstate(state) -> None. Restores generator state.")}, + {"getrandbits", (PyCFunction)random_getrandbits, METH_VARARGS, + PyDoc_STR("getrandbits(k) -> x. Generates a long int with " + "k random bits.")}, + {NULL, NULL} /* sentinel */ }; PyDoc_STRVAR(random_doc, "Random() -> create a random number generator with its own internal state."); static PyTypeObject Random_Type = { - PyVarObject_HEAD_INIT(NULL, 0) - "_random.Random", /*tp_name*/ - sizeof(RandomObject), /*tp_basicsize*/ - 0, /*tp_itemsize*/ - /* methods */ - 0, /*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_BASETYPE, /*tp_flags*/ - random_doc, /*tp_doc*/ - 0, /*tp_traverse*/ - 0, /*tp_clear*/ - 0, /*tp_richcompare*/ - 0, /*tp_weaklistoffset*/ - 0, /*tp_iter*/ - 0, /*tp_iternext*/ - random_methods, /*tp_methods*/ - 0, /*tp_members*/ - 0, /*tp_getset*/ - 0, /*tp_base*/ - 0, /*tp_dict*/ - 0, /*tp_descr_get*/ - 0, /*tp_descr_set*/ - 0, /*tp_dictoffset*/ - 0, /*tp_init*/ - 0, /*tp_alloc*/ - random_new, /*tp_new*/ - PyObject_Free, /*tp_free*/ - 0, /*tp_is_gc*/ + PyVarObject_HEAD_INIT(NULL, 0) + "_random.Random", /*tp_name*/ + sizeof(RandomObject), /*tp_basicsize*/ + 0, /*tp_itemsize*/ + /* methods */ + 0, /*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_BASETYPE, /*tp_flags*/ + random_doc, /*tp_doc*/ + 0, /*tp_traverse*/ + 0, /*tp_clear*/ + 0, /*tp_richcompare*/ + 0, /*tp_weaklistoffset*/ + 0, /*tp_iter*/ + 0, /*tp_iternext*/ + random_methods, /*tp_methods*/ + 0, /*tp_members*/ + 0, /*tp_getset*/ + 0, /*tp_base*/ + 0, /*tp_dict*/ + 0, /*tp_descr_get*/ + 0, /*tp_descr_set*/ + 0, /*tp_dictoffset*/ + 0, /*tp_init*/ + 0, /*tp_alloc*/ + random_new, /*tp_new*/ + PyObject_Free, /*tp_free*/ + 0, /*tp_is_gc*/ }; PyDoc_STRVAR(module_doc, @@ -498,28 +498,28 @@ static struct PyModuleDef _randommodule = { - PyModuleDef_HEAD_INIT, - "_random", - module_doc, - -1, - NULL, - NULL, - NULL, - NULL, - NULL + PyModuleDef_HEAD_INIT, + "_random", + module_doc, + -1, + NULL, + NULL, + NULL, + NULL, + NULL }; PyMODINIT_FUNC PyInit__random(void) { - PyObject *m; + PyObject *m; - if (PyType_Ready(&Random_Type) < 0) - return NULL; - m = PyModule_Create(&_randommodule); - if (m == NULL) - return NULL; - Py_INCREF(&Random_Type); - PyModule_AddObject(m, "Random", (PyObject *)&Random_Type); - return m; + if (PyType_Ready(&Random_Type) < 0) + return NULL; + m = PyModule_Create(&_randommodule); + if (m == NULL) + return NULL; + Py_INCREF(&Random_Type); + PyModule_AddObject(m, "Random", (PyObject *)&Random_Type); + return m; } Modified: python/branches/py3k-jit/Modules/_scproxy.c ============================================================================== --- python/branches/py3k-jit/Modules/_scproxy.c (original) +++ python/branches/py3k-jit/Modules/_scproxy.c Mon May 10 23:55:43 2010 @@ -5,167 +5,167 @@ #include #include -static int32_t +static int32_t cfnum_to_int32(CFNumberRef num) { - int32_t result; + int32_t result; - CFNumberGetValue(num, kCFNumberSInt32Type, &result); - return result; + CFNumberGetValue(num, kCFNumberSInt32Type, &result); + return result; } static PyObject* cfstring_to_pystring(CFStringRef ref) { - const char* s; + const char* s; - s = CFStringGetCStringPtr(ref, kCFStringEncodingUTF8); - if (s) { - return PyUnicode_DecodeUTF8( - s, strlen(s), NULL); - - } else { - CFIndex len = CFStringGetLength(ref); - Boolean ok; - PyObject* result; - char* buf; - - buf = PyMem_Malloc(len*4); - if (buf == NULL) { - PyErr_NoMemory(); - return NULL; - } - - ok = CFStringGetCString(ref, - buf, len * 4, - kCFStringEncodingUTF8); - if (!ok) { - PyMem_Free(buf); - return NULL; - } else { - result = PyUnicode_DecodeUTF8( - buf, strlen(buf), NULL); - PyMem_Free(buf); - } - return result; - } + s = CFStringGetCStringPtr(ref, kCFStringEncodingUTF8); + if (s) { + return PyUnicode_DecodeUTF8( + s, strlen(s), NULL); + + } else { + CFIndex len = CFStringGetLength(ref); + Boolean ok; + PyObject* result; + char* buf; + + buf = PyMem_Malloc(len*4); + if (buf == NULL) { + PyErr_NoMemory(); + return NULL; + } + + ok = CFStringGetCString(ref, + buf, len * 4, + kCFStringEncodingUTF8); + if (!ok) { + PyMem_Free(buf); + return NULL; + } else { + result = PyUnicode_DecodeUTF8( + buf, strlen(buf), NULL); + PyMem_Free(buf); + } + return result; + } } static PyObject* get_proxy_settings(PyObject* mod __attribute__((__unused__))) { - CFDictionaryRef proxyDict = NULL; - CFNumberRef aNum = NULL; - CFArrayRef anArray = NULL; - PyObject* result = NULL; - PyObject* v; - int r; - - proxyDict = SCDynamicStoreCopyProxies(NULL); - if (!proxyDict) { - Py_INCREF(Py_None); - return Py_None; - } - - result = PyDict_New(); - if (result == NULL) goto error; - - if (&kSCPropNetProxiesExcludeSimpleHostnames != NULL) { - aNum = CFDictionaryGetValue(proxyDict, - kSCPropNetProxiesExcludeSimpleHostnames); - if (aNum == NULL) { - v = PyBool_FromLong(1); - } else { - v = PyBool_FromLong(cfnum_to_int32(aNum)); - } - } else { - v = PyBool_FromLong(1); - } - - if (v == NULL) goto error; - - r = PyDict_SetItemString(result, "exclude_simple", v); - Py_DECREF(v); v = NULL; - if (r == -1) goto error; - - anArray = CFDictionaryGetValue(proxyDict, - kSCPropNetProxiesExceptionsList); - if (anArray != NULL) { - CFIndex len = CFArrayGetCount(anArray); - CFIndex i; - v = PyTuple_New(len); - if (v == NULL) goto error; - - r = PyDict_SetItemString(result, "exceptions", v); - Py_DECREF(v); - if (r == -1) goto error; - - for (i = 0; i < len; i++) { - CFStringRef aString = NULL; - - aString = CFArrayGetValueAtIndex(anArray, i); - if (aString == NULL) { - PyTuple_SetItem(v, i, Py_None); - Py_INCREF(Py_None); - } else { - PyObject* t = cfstring_to_pystring(aString); - if (!t) { - PyTuple_SetItem(v, i, Py_None); - Py_INCREF(Py_None); - } else { - PyTuple_SetItem(v, i, t); - } - } - } - } + CFDictionaryRef proxyDict = NULL; + CFNumberRef aNum = NULL; + CFArrayRef anArray = NULL; + PyObject* result = NULL; + PyObject* v; + int r; + + proxyDict = SCDynamicStoreCopyProxies(NULL); + if (!proxyDict) { + Py_INCREF(Py_None); + return Py_None; + } + + result = PyDict_New(); + if (result == NULL) goto error; + + if (&kSCPropNetProxiesExcludeSimpleHostnames != NULL) { + aNum = CFDictionaryGetValue(proxyDict, + kSCPropNetProxiesExcludeSimpleHostnames); + if (aNum == NULL) { + v = PyBool_FromLong(1); + } else { + v = PyBool_FromLong(cfnum_to_int32(aNum)); + } + } else { + v = PyBool_FromLong(1); + } + + if (v == NULL) goto error; + + r = PyDict_SetItemString(result, "exclude_simple", v); + Py_DECREF(v); v = NULL; + if (r == -1) goto error; + + anArray = CFDictionaryGetValue(proxyDict, + kSCPropNetProxiesExceptionsList); + if (anArray != NULL) { + CFIndex len = CFArrayGetCount(anArray); + CFIndex i; + v = PyTuple_New(len); + if (v == NULL) goto error; + + r = PyDict_SetItemString(result, "exceptions", v); + Py_DECREF(v); + if (r == -1) goto error; + + for (i = 0; i < len; i++) { + CFStringRef aString = NULL; + + aString = CFArrayGetValueAtIndex(anArray, i); + if (aString == NULL) { + PyTuple_SetItem(v, i, Py_None); + Py_INCREF(Py_None); + } else { + PyObject* t = cfstring_to_pystring(aString); + if (!t) { + PyTuple_SetItem(v, i, Py_None); + Py_INCREF(Py_None); + } else { + PyTuple_SetItem(v, i, t); + } + } + } + } - CFRelease(proxyDict); - return result; + CFRelease(proxyDict); + return result; error: - if (proxyDict) CFRelease(proxyDict); - Py_XDECREF(result); - return NULL; + if (proxyDict) CFRelease(proxyDict); + Py_XDECREF(result); + return NULL; } static int set_proxy(PyObject* proxies, char* proto, CFDictionaryRef proxyDict, - CFStringRef enabledKey, - CFStringRef hostKey, CFStringRef portKey) + CFStringRef enabledKey, + CFStringRef hostKey, CFStringRef portKey) { - CFNumberRef aNum; + CFNumberRef aNum; - aNum = CFDictionaryGetValue(proxyDict, enabledKey); - if (aNum && cfnum_to_int32(aNum)) { - CFStringRef hostString; - - hostString = CFDictionaryGetValue(proxyDict, hostKey); - aNum = CFDictionaryGetValue(proxyDict, portKey); - - if (hostString) { - int r; - PyObject* h = cfstring_to_pystring(hostString); - PyObject* v; - if (h) { - if (aNum) { - int32_t port = cfnum_to_int32(aNum); - v = PyUnicode_FromFormat("http://%U:%ld", - h, (long)port); - } else { - v = PyUnicode_FromFormat("http://%U", h); - } - Py_DECREF(h); - if (!v) return -1; - r = PyDict_SetItemString(proxies, proto, - v); - Py_DECREF(v); - return r; - } - } + aNum = CFDictionaryGetValue(proxyDict, enabledKey); + if (aNum && cfnum_to_int32(aNum)) { + CFStringRef hostString; + + hostString = CFDictionaryGetValue(proxyDict, hostKey); + aNum = CFDictionaryGetValue(proxyDict, portKey); + + if (hostString) { + int r; + PyObject* h = cfstring_to_pystring(hostString); + PyObject* v; + if (h) { + if (aNum) { + int32_t port = cfnum_to_int32(aNum); + v = PyUnicode_FromFormat("http://%U:%ld", + h, (long)port); + } else { + v = PyUnicode_FromFormat("http://%U", h); + } + Py_DECREF(h); + if (!v) return -1; + r = PyDict_SetItemString(proxies, proto, + v); + Py_DECREF(v); + return r; + } + } - } - return 0; + } + return 0; } @@ -173,75 +173,75 @@ static PyObject* get_proxies(PyObject* mod __attribute__((__unused__))) { - PyObject* result = NULL; - int r; - CFDictionaryRef proxyDict = NULL; - - proxyDict = SCDynamicStoreCopyProxies(NULL); - if (proxyDict == NULL) { - return PyDict_New(); - } - - result = PyDict_New(); - if (result == NULL) goto error; - - r = set_proxy(result, "http", proxyDict, - kSCPropNetProxiesHTTPEnable, - kSCPropNetProxiesHTTPProxy, - kSCPropNetProxiesHTTPPort); - if (r == -1) goto error; - r = set_proxy(result, "https", proxyDict, - kSCPropNetProxiesHTTPSEnable, - kSCPropNetProxiesHTTPSProxy, - kSCPropNetProxiesHTTPSPort); - if (r == -1) goto error; - r = set_proxy(result, "ftp", proxyDict, - kSCPropNetProxiesFTPEnable, - kSCPropNetProxiesFTPProxy, - kSCPropNetProxiesFTPPort); - if (r == -1) goto error; - r = set_proxy(result, "gopher", proxyDict, - kSCPropNetProxiesGopherEnable, - kSCPropNetProxiesGopherProxy, - kSCPropNetProxiesGopherPort); - if (r == -1) goto error; + PyObject* result = NULL; + int r; + CFDictionaryRef proxyDict = NULL; + + proxyDict = SCDynamicStoreCopyProxies(NULL); + if (proxyDict == NULL) { + return PyDict_New(); + } + + result = PyDict_New(); + if (result == NULL) goto error; + + r = set_proxy(result, "http", proxyDict, + kSCPropNetProxiesHTTPEnable, + kSCPropNetProxiesHTTPProxy, + kSCPropNetProxiesHTTPPort); + if (r == -1) goto error; + r = set_proxy(result, "https", proxyDict, + kSCPropNetProxiesHTTPSEnable, + kSCPropNetProxiesHTTPSProxy, + kSCPropNetProxiesHTTPSPort); + if (r == -1) goto error; + r = set_proxy(result, "ftp", proxyDict, + kSCPropNetProxiesFTPEnable, + kSCPropNetProxiesFTPProxy, + kSCPropNetProxiesFTPPort); + if (r == -1) goto error; + r = set_proxy(result, "gopher", proxyDict, + kSCPropNetProxiesGopherEnable, + kSCPropNetProxiesGopherProxy, + kSCPropNetProxiesGopherPort); + if (r == -1) goto error; - CFRelease(proxyDict); - return result; + CFRelease(proxyDict); + return result; error: - if (proxyDict) CFRelease(proxyDict); - Py_XDECREF(result); - return NULL; + if (proxyDict) CFRelease(proxyDict); + Py_XDECREF(result); + return NULL; } static PyMethodDef mod_methods[] = { - { - "_get_proxy_settings", - (PyCFunction)get_proxy_settings, - METH_NOARGS, - NULL, - }, - { - "_get_proxies", - (PyCFunction)get_proxies, - METH_NOARGS, - NULL, - }, - { 0, 0, 0, 0 } + { + "_get_proxy_settings", + (PyCFunction)get_proxy_settings, + METH_NOARGS, + NULL, + }, + { + "_get_proxies", + (PyCFunction)get_proxies, + METH_NOARGS, + NULL, + }, + { 0, 0, 0, 0 } }; static struct PyModuleDef mod_module = { - PyModuleDef_HEAD_INIT, - "_scproxy", - NULL, - -1, - mod_methods, - NULL, - NULL, - NULL, - NULL + PyModuleDef_HEAD_INIT, + "_scproxy", + NULL, + -1, + mod_methods, + NULL, + NULL, + NULL, + NULL }; @@ -249,10 +249,10 @@ extern "C" { #endif -PyObject* +PyObject* PyInit__scproxy(void) { - return PyModule_Create(&mod_module); + return PyModule_Create(&mod_module); } #ifdef __cplusplus Modified: python/branches/py3k-jit/Modules/_sqlite/module.c ============================================================================== --- python/branches/py3k-jit/Modules/_sqlite/module.c (original) +++ python/branches/py3k-jit/Modules/_sqlite/module.c Mon May 10 23:55:43 2010 @@ -64,7 +64,7 @@ if (!PyArg_ParseTupleAndKeywords(args, kwargs, "s|diOiOi", kwlist, &database, &timeout, &detect_types, &isolation_level, &check_same_thread, &factory, &cached_statements)) { - return NULL; + return NULL; } if (factory == NULL) { @@ -93,7 +93,7 @@ if (!PyArg_ParseTupleAndKeywords(args, kwargs, "s", kwlist, &statement)) { - return NULL; + return NULL; } if (sqlite3_complete(statement)) { @@ -122,7 +122,7 @@ if (!PyArg_ParseTupleAndKeywords(args, kwargs, "i", kwlist, &do_enable)) { - return NULL; + return NULL; } rc = sqlite3_enable_shared_cache(do_enable); @@ -302,15 +302,15 @@ static struct PyModuleDef _sqlite3module = { - PyModuleDef_HEAD_INIT, - "_sqlite3", - NULL, - -1, - module_methods, - NULL, - NULL, - NULL, - NULL + PyModuleDef_HEAD_INIT, + "_sqlite3", + NULL, + -1, + module_methods, + NULL, + NULL, + NULL, + NULL }; PyMODINIT_FUNC PyInit__sqlite3(void) @@ -329,7 +329,7 @@ (pysqlite_statement_setup_types() < 0) || (pysqlite_prepare_protocol_setup_types() < 0) ) { - Py_DECREF(module); + Py_DECREF(module); return NULL; } @@ -448,7 +448,7 @@ /* Original comment from _bsddb.c in the Python core. This is also still * needed nowadays for Python 2.3/2.4. - * + * * PyEval_InitThreads is called here due to a quirk in python 1.5 * - 2.2.1 (at least) according to Russell Williamson : * The global interpreter lock is not initialized until the first @@ -467,8 +467,8 @@ if (PyErr_Occurred()) { PyErr_SetString(PyExc_ImportError, MODULE_NAME ": init failed"); - Py_DECREF(module); - module = NULL; + Py_DECREF(module); + module = NULL; } return module; } Modified: python/branches/py3k-jit/Modules/_struct.c ============================================================================== --- python/branches/py3k-jit/Modules/_struct.c (original) +++ python/branches/py3k-jit/Modules/_struct.c Mon May 10 23:55:43 2010 @@ -14,30 +14,30 @@ /* The translation function for each format character is table driven */ typedef struct _formatdef { - char format; - Py_ssize_t size; - Py_ssize_t alignment; - PyObject* (*unpack)(const char *, - const struct _formatdef *); - int (*pack)(char *, PyObject *, - const struct _formatdef *); + char format; + Py_ssize_t size; + Py_ssize_t alignment; + PyObject* (*unpack)(const char *, + const struct _formatdef *); + int (*pack)(char *, PyObject *, + const struct _formatdef *); } formatdef; typedef struct _formatcode { - const struct _formatdef *fmtdef; - Py_ssize_t offset; - Py_ssize_t size; + const struct _formatdef *fmtdef; + Py_ssize_t offset; + Py_ssize_t size; } formatcode; /* Struct object interface */ typedef struct { - PyObject_HEAD - Py_ssize_t s_size; - Py_ssize_t s_len; - formatcode *s_codes; - PyObject *s_format; - PyObject *weakreflist; /* List of weak references */ + PyObject_HEAD + Py_ssize_t s_size; + Py_ssize_t s_len; + formatcode *s_codes; + PyObject *s_format; + PyObject *weakreflist; /* List of weak references */ } PyStructObject; @@ -95,25 +95,25 @@ static PyObject * get_pylong(PyObject *v) { - assert(v != NULL); - if (!PyLong_Check(v)) { - /* Not an integer; try to use __index__ to convert. */ - if (PyIndex_Check(v)) { - v = PyNumber_Index(v); - if (v == NULL) - return NULL; - } - else { - PyErr_SetString(StructError, - "required argument is not an integer"); - return NULL; - } - } - else - Py_INCREF(v); + assert(v != NULL); + if (!PyLong_Check(v)) { + /* Not an integer; try to use __index__ to convert. */ + if (PyIndex_Check(v)) { + v = PyNumber_Index(v); + if (v == NULL) + return NULL; + } + else { + PyErr_SetString(StructError, + "required argument is not an integer"); + return NULL; + } + } + else + Py_INCREF(v); - assert(PyLong_Check(v)); - return v; + assert(PyLong_Check(v)); + return v; } /* Helper routine to get a C long and raise the appropriate error if it isn't @@ -122,22 +122,22 @@ static int get_long(PyObject *v, long *p) { - long x; + long x; - v = get_pylong(v); - if (v == NULL) - return -1; - assert(PyLong_Check(v)); - x = PyLong_AsLong(v); - Py_DECREF(v); - if (x == (long)-1 && PyErr_Occurred()) { - if (PyErr_ExceptionMatches(PyExc_OverflowError)) - PyErr_SetString(StructError, - "argument out of range"); - return -1; - } - *p = x; - return 0; + v = get_pylong(v); + if (v == NULL) + return -1; + assert(PyLong_Check(v)); + x = PyLong_AsLong(v); + Py_DECREF(v); + if (x == (long)-1 && PyErr_Occurred()) { + if (PyErr_ExceptionMatches(PyExc_OverflowError)) + PyErr_SetString(StructError, + "argument out of range"); + return -1; + } + *p = x; + return 0; } @@ -146,22 +146,22 @@ static int get_ulong(PyObject *v, unsigned long *p) { - unsigned long x; + unsigned long x; - v = get_pylong(v); - if (v == NULL) - return -1; - assert(PyLong_Check(v)); - x = PyLong_AsUnsignedLong(v); - Py_DECREF(v); - if (x == (unsigned long)-1 && PyErr_Occurred()) { - if (PyErr_ExceptionMatches(PyExc_OverflowError)) - PyErr_SetString(StructError, - "argument out of range"); - return -1; - } - *p = x; - return 0; + v = get_pylong(v); + if (v == NULL) + return -1; + assert(PyLong_Check(v)); + x = PyLong_AsUnsignedLong(v); + Py_DECREF(v); + if (x == (unsigned long)-1 && PyErr_Occurred()) { + if (PyErr_ExceptionMatches(PyExc_OverflowError)) + PyErr_SetString(StructError, + "argument out of range"); + return -1; + } + *p = x; + return 0; } #ifdef HAVE_LONG_LONG @@ -171,22 +171,22 @@ static int get_longlong(PyObject *v, PY_LONG_LONG *p) { - PY_LONG_LONG x; + PY_LONG_LONG x; - v = get_pylong(v); - if (v == NULL) - return -1; - assert(PyLong_Check(v)); - x = PyLong_AsLongLong(v); - Py_DECREF(v); - if (x == (PY_LONG_LONG)-1 && PyErr_Occurred()) { - if (PyErr_ExceptionMatches(PyExc_OverflowError)) - PyErr_SetString(StructError, - "argument out of range"); - return -1; - } - *p = x; - return 0; + v = get_pylong(v); + if (v == NULL) + return -1; + assert(PyLong_Check(v)); + x = PyLong_AsLongLong(v); + Py_DECREF(v); + if (x == (PY_LONG_LONG)-1 && PyErr_Occurred()) { + if (PyErr_ExceptionMatches(PyExc_OverflowError)) + PyErr_SetString(StructError, + "argument out of range"); + return -1; + } + *p = x; + return 0; } /* Same, but handling native unsigned long long. */ @@ -194,22 +194,22 @@ static int get_ulonglong(PyObject *v, unsigned PY_LONG_LONG *p) { - unsigned PY_LONG_LONG x; + unsigned PY_LONG_LONG x; - v = get_pylong(v); - if (v == NULL) - return -1; - assert(PyLong_Check(v)); - x = PyLong_AsUnsignedLongLong(v); - Py_DECREF(v); - if (x == (unsigned PY_LONG_LONG)-1 && PyErr_Occurred()) { - if (PyErr_ExceptionMatches(PyExc_OverflowError)) - PyErr_SetString(StructError, - "argument out of range"); - return -1; - } - *p = x; - return 0; + v = get_pylong(v); + if (v == NULL) + return -1; + assert(PyLong_Check(v)); + x = PyLong_AsUnsignedLongLong(v); + Py_DECREF(v); + if (x == (unsigned PY_LONG_LONG)-1 && PyErr_Occurred()) { + if (PyErr_ExceptionMatches(PyExc_OverflowError)) + PyErr_SetString(StructError, + "argument out of range"); + return -1; + } + *p = x; + return 0; } #endif @@ -222,57 +222,57 @@ static PyObject * unpack_float(const char *p, /* start of 4-byte string */ - int le) /* true for little-endian, false for big-endian */ + int le) /* true for little-endian, false for big-endian */ { - double x; + double x; - x = _PyFloat_Unpack4((unsigned char *)p, le); - if (x == -1.0 && PyErr_Occurred()) - return NULL; - return PyFloat_FromDouble(x); + x = _PyFloat_Unpack4((unsigned char *)p, le); + if (x == -1.0 && PyErr_Occurred()) + return NULL; + return PyFloat_FromDouble(x); } static PyObject * unpack_double(const char *p, /* start of 8-byte string */ - int le) /* true for little-endian, false for big-endian */ + int le) /* true for little-endian, false for big-endian */ { - double x; + double x; - x = _PyFloat_Unpack8((unsigned char *)p, le); - if (x == -1.0 && PyErr_Occurred()) - return NULL; - return PyFloat_FromDouble(x); + x = _PyFloat_Unpack8((unsigned char *)p, le); + if (x == -1.0 && PyErr_Occurred()) + return NULL; + return PyFloat_FromDouble(x); } /* Helper to format the range error exceptions */ static int _range_error(const formatdef *f, int is_unsigned) { - /* ulargest is the largest unsigned value with f->size bytes. - * Note that the simpler: - * ((size_t)1 << (f->size * 8)) - 1 - * doesn't work when f->size == sizeof(size_t) because C doesn't - * define what happens when a left shift count is >= the number of - * bits in the integer being shifted; e.g., on some boxes it doesn't - * shift at all when they're equal. - */ - const size_t ulargest = (size_t)-1 >> ((SIZEOF_SIZE_T - f->size)*8); - assert(f->size >= 1 && f->size <= SIZEOF_SIZE_T); - if (is_unsigned) - PyErr_Format(StructError, - "'%c' format requires 0 <= number <= %zu", - f->format, - ulargest); - else { - const Py_ssize_t largest = (Py_ssize_t)(ulargest >> 1); - PyErr_Format(StructError, - "'%c' format requires %zd <= number <= %zd", - f->format, - ~ largest, - largest); - } + /* ulargest is the largest unsigned value with f->size bytes. + * Note that the simpler: + * ((size_t)1 << (f->size * 8)) - 1 + * doesn't work when f->size == sizeof(size_t) because C doesn't + * define what happens when a left shift count is >= the number of + * bits in the integer being shifted; e.g., on some boxes it doesn't + * shift at all when they're equal. + */ + const size_t ulargest = (size_t)-1 >> ((SIZEOF_SIZE_T - f->size)*8); + assert(f->size >= 1 && f->size <= SIZEOF_SIZE_T); + if (is_unsigned) + PyErr_Format(StructError, + "'%c' format requires 0 <= number <= %zu", + f->format, + ulargest); + else { + const Py_ssize_t largest = (Py_ssize_t)(ulargest >> 1); + PyErr_Format(StructError, + "'%c' format requires %zd <= number <= %zd", + f->format, + ~ largest, + largest); + } - return -1; + return -1; } @@ -299,75 +299,75 @@ static PyObject * nu_char(const char *p, const formatdef *f) { - return PyBytes_FromStringAndSize(p, 1); + return PyBytes_FromStringAndSize(p, 1); } static PyObject * nu_byte(const char *p, const formatdef *f) { - return PyLong_FromLong((long) *(signed char *)p); + return PyLong_FromLong((long) *(signed char *)p); } static PyObject * nu_ubyte(const char *p, const formatdef *f) { - return PyLong_FromLong((long) *(unsigned char *)p); + return PyLong_FromLong((long) *(unsigned char *)p); } static PyObject * nu_short(const char *p, const formatdef *f) { - short x; - memcpy((char *)&x, p, sizeof x); - return PyLong_FromLong((long)x); + short x; + memcpy((char *)&x, p, sizeof x); + return PyLong_FromLong((long)x); } static PyObject * nu_ushort(const char *p, const formatdef *f) { - unsigned short x; - memcpy((char *)&x, p, sizeof x); - return PyLong_FromLong((long)x); + unsigned short x; + memcpy((char *)&x, p, sizeof x); + return PyLong_FromLong((long)x); } static PyObject * nu_int(const char *p, const formatdef *f) { - int x; - memcpy((char *)&x, p, sizeof x); - return PyLong_FromLong((long)x); + int x; + memcpy((char *)&x, p, sizeof x); + return PyLong_FromLong((long)x); } static PyObject * nu_uint(const char *p, const formatdef *f) { - unsigned int x; - memcpy((char *)&x, p, sizeof x); + unsigned int x; + memcpy((char *)&x, p, sizeof x); #if (SIZEOF_LONG > SIZEOF_INT) - return PyLong_FromLong((long)x); + return PyLong_FromLong((long)x); #else - if (x <= ((unsigned int)LONG_MAX)) - return PyLong_FromLong((long)x); - return PyLong_FromUnsignedLong((unsigned long)x); + if (x <= ((unsigned int)LONG_MAX)) + return PyLong_FromLong((long)x); + return PyLong_FromUnsignedLong((unsigned long)x); #endif } static PyObject * nu_long(const char *p, const formatdef *f) { - long x; - memcpy((char *)&x, p, sizeof x); - return PyLong_FromLong(x); + long x; + memcpy((char *)&x, p, sizeof x); + return PyLong_FromLong(x); } static PyObject * nu_ulong(const char *p, const formatdef *f) { - unsigned long x; - memcpy((char *)&x, p, sizeof x); - if (x <= LONG_MAX) - return PyLong_FromLong((long)x); - return PyLong_FromUnsignedLong(x); + unsigned long x; + memcpy((char *)&x, p, sizeof x); + if (x <= LONG_MAX) + return PyLong_FromLong((long)x); + return PyLong_FromUnsignedLong(x); } /* Native mode doesn't support q or Q unless the platform C supports @@ -378,21 +378,21 @@ static PyObject * nu_longlong(const char *p, const formatdef *f) { - PY_LONG_LONG x; - memcpy((char *)&x, p, sizeof x); - if (x >= LONG_MIN && x <= LONG_MAX) - return PyLong_FromLong(Py_SAFE_DOWNCAST(x, PY_LONG_LONG, long)); - return PyLong_FromLongLong(x); + PY_LONG_LONG x; + memcpy((char *)&x, p, sizeof x); + if (x >= LONG_MIN && x <= LONG_MAX) + return PyLong_FromLong(Py_SAFE_DOWNCAST(x, PY_LONG_LONG, long)); + return PyLong_FromLongLong(x); } static PyObject * nu_ulonglong(const char *p, const formatdef *f) { - unsigned PY_LONG_LONG x; - memcpy((char *)&x, p, sizeof x); - if (x <= LONG_MAX) - return PyLong_FromLong(Py_SAFE_DOWNCAST(x, unsigned PY_LONG_LONG, long)); - return PyLong_FromUnsignedLongLong(x); + unsigned PY_LONG_LONG x; + memcpy((char *)&x, p, sizeof x); + if (x <= LONG_MAX) + return PyLong_FromLong(Py_SAFE_DOWNCAST(x, unsigned PY_LONG_LONG, long)); + return PyLong_FromUnsignedLongLong(x); } #endif @@ -400,168 +400,168 @@ static PyObject * nu_bool(const char *p, const formatdef *f) { - BOOL_TYPE x; - memcpy((char *)&x, p, sizeof x); - return PyBool_FromLong(x != 0); + BOOL_TYPE x; + memcpy((char *)&x, p, sizeof x); + return PyBool_FromLong(x != 0); } static PyObject * nu_float(const char *p, const formatdef *f) { - float x; - memcpy((char *)&x, p, sizeof x); - return PyFloat_FromDouble((double)x); + float x; + memcpy((char *)&x, p, sizeof x); + return PyFloat_FromDouble((double)x); } static PyObject * nu_double(const char *p, const formatdef *f) { - double x; - memcpy((char *)&x, p, sizeof x); - return PyFloat_FromDouble(x); + double x; + memcpy((char *)&x, p, sizeof x); + return PyFloat_FromDouble(x); } static PyObject * nu_void_p(const char *p, const formatdef *f) { - void *x; - memcpy((char *)&x, p, sizeof x); - return PyLong_FromVoidPtr(x); + void *x; + memcpy((char *)&x, p, sizeof x); + return PyLong_FromVoidPtr(x); } static int np_byte(char *p, PyObject *v, const formatdef *f) { - long x; - if (get_long(v, &x) < 0) - return -1; - if (x < -128 || x > 127){ - PyErr_SetString(StructError, - "byte format requires -128 <= number <= 127"); - return -1; - } - *p = (char)x; - return 0; + long x; + if (get_long(v, &x) < 0) + return -1; + if (x < -128 || x > 127){ + PyErr_SetString(StructError, + "byte format requires -128 <= number <= 127"); + return -1; + } + *p = (char)x; + return 0; } static int np_ubyte(char *p, PyObject *v, const formatdef *f) { - long x; - if (get_long(v, &x) < 0) - return -1; - if (x < 0 || x > 255){ - PyErr_SetString(StructError, - "ubyte format requires 0 <= number <= 255"); - return -1; - } - *p = (char)x; - return 0; + long x; + if (get_long(v, &x) < 0) + return -1; + if (x < 0 || x > 255){ + PyErr_SetString(StructError, + "ubyte format requires 0 <= number <= 255"); + return -1; + } + *p = (char)x; + return 0; } static int np_char(char *p, PyObject *v, const formatdef *f) { - if (PyUnicode_Check(v)) { - v = _PyUnicode_AsDefaultEncodedString(v, NULL); - if (v == NULL) - return -1; - } - if (!PyBytes_Check(v) || PyBytes_Size(v) != 1) { - PyErr_SetString(StructError, - "char format requires bytes or string of length 1"); - return -1; - } - *p = *PyBytes_AsString(v); - return 0; + if (PyUnicode_Check(v)) { + v = _PyUnicode_AsDefaultEncodedString(v, NULL); + if (v == NULL) + return -1; + } + if (!PyBytes_Check(v) || PyBytes_Size(v) != 1) { + PyErr_SetString(StructError, + "char format requires bytes or string of length 1"); + return -1; + } + *p = *PyBytes_AsString(v); + return 0; } static int np_short(char *p, PyObject *v, const formatdef *f) { - long x; - short y; - if (get_long(v, &x) < 0) - return -1; - if (x < SHRT_MIN || x > SHRT_MAX){ - PyErr_SetString(StructError, - "short format requires " STRINGIFY(SHRT_MIN) - " <= number <= " STRINGIFY(SHRT_MAX)); - return -1; - } - y = (short)x; - memcpy(p, (char *)&y, sizeof y); - return 0; + long x; + short y; + if (get_long(v, &x) < 0) + return -1; + if (x < SHRT_MIN || x > SHRT_MAX){ + PyErr_SetString(StructError, + "short format requires " STRINGIFY(SHRT_MIN) + " <= number <= " STRINGIFY(SHRT_MAX)); + return -1; + } + y = (short)x; + memcpy(p, (char *)&y, sizeof y); + return 0; } static int np_ushort(char *p, PyObject *v, const formatdef *f) { - long x; - unsigned short y; - if (get_long(v, &x) < 0) - return -1; - if (x < 0 || x > USHRT_MAX){ - PyErr_SetString(StructError, - "ushort format requires 0 <= number <= " STRINGIFY(USHRT_MAX)); - return -1; - } - y = (unsigned short)x; - memcpy(p, (char *)&y, sizeof y); - return 0; + long x; + unsigned short y; + if (get_long(v, &x) < 0) + return -1; + if (x < 0 || x > USHRT_MAX){ + PyErr_SetString(StructError, + "ushort format requires 0 <= number <= " STRINGIFY(USHRT_MAX)); + return -1; + } + y = (unsigned short)x; + memcpy(p, (char *)&y, sizeof y); + return 0; } static int np_int(char *p, PyObject *v, const formatdef *f) { - long x; - int y; - if (get_long(v, &x) < 0) - return -1; + long x; + int y; + if (get_long(v, &x) < 0) + return -1; #if (SIZEOF_LONG > SIZEOF_INT) - if ((x < ((long)INT_MIN)) || (x > ((long)INT_MAX))) - RANGE_ERROR(x, f, 0, -1); + if ((x < ((long)INT_MIN)) || (x > ((long)INT_MAX))) + RANGE_ERROR(x, f, 0, -1); #endif - y = (int)x; - memcpy(p, (char *)&y, sizeof y); - return 0; + y = (int)x; + memcpy(p, (char *)&y, sizeof y); + return 0; } static int np_uint(char *p, PyObject *v, const formatdef *f) { - unsigned long x; - unsigned int y; - if (get_ulong(v, &x) < 0) - return -1; - y = (unsigned int)x; + unsigned long x; + unsigned int y; + if (get_ulong(v, &x) < 0) + return -1; + y = (unsigned int)x; #if (SIZEOF_LONG > SIZEOF_INT) - if (x > ((unsigned long)UINT_MAX)) - RANGE_ERROR(y, f, 1, -1); + if (x > ((unsigned long)UINT_MAX)) + RANGE_ERROR(y, f, 1, -1); #endif - memcpy(p, (char *)&y, sizeof y); - return 0; + memcpy(p, (char *)&y, sizeof y); + return 0; } static int np_long(char *p, PyObject *v, const formatdef *f) { - long x; - if (get_long(v, &x) < 0) - return -1; - memcpy(p, (char *)&x, sizeof x); - return 0; + long x; + if (get_long(v, &x) < 0) + return -1; + memcpy(p, (char *)&x, sizeof x); + return 0; } static int np_ulong(char *p, PyObject *v, const formatdef *f) { - unsigned long x; - if (get_ulong(v, &x) < 0) - return -1; - memcpy(p, (char *)&x, sizeof x); - return 0; + unsigned long x; + if (get_ulong(v, &x) < 0) + return -1; + memcpy(p, (char *)&x, sizeof x); + return 0; } #ifdef HAVE_LONG_LONG @@ -569,21 +569,21 @@ static int np_longlong(char *p, PyObject *v, const formatdef *f) { - PY_LONG_LONG x; - if (get_longlong(v, &x) < 0) - return -1; - memcpy(p, (char *)&x, sizeof x); - return 0; + PY_LONG_LONG x; + if (get_longlong(v, &x) < 0) + return -1; + memcpy(p, (char *)&x, sizeof x); + return 0; } static int np_ulonglong(char *p, PyObject *v, const formatdef *f) { - unsigned PY_LONG_LONG x; - if (get_ulonglong(v, &x) < 0) - return -1; - memcpy(p, (char *)&x, sizeof x); - return 0; + unsigned PY_LONG_LONG x; + if (get_ulonglong(v, &x) < 0) + return -1; + memcpy(p, (char *)&x, sizeof x); + return 0; } #endif @@ -591,77 +591,77 @@ static int np_bool(char *p, PyObject *v, const formatdef *f) { - BOOL_TYPE y; - y = PyObject_IsTrue(v); - memcpy(p, (char *)&y, sizeof y); - return 0; + BOOL_TYPE y; + y = PyObject_IsTrue(v); + memcpy(p, (char *)&y, sizeof y); + return 0; } static int np_float(char *p, PyObject *v, const formatdef *f) { - float x = (float)PyFloat_AsDouble(v); - if (x == -1 && PyErr_Occurred()) { - PyErr_SetString(StructError, - "required argument is not a float"); - return -1; - } - memcpy(p, (char *)&x, sizeof x); - return 0; + float x = (float)PyFloat_AsDouble(v); + if (x == -1 && PyErr_Occurred()) { + PyErr_SetString(StructError, + "required argument is not a float"); + return -1; + } + memcpy(p, (char *)&x, sizeof x); + return 0; } static int np_double(char *p, PyObject *v, const formatdef *f) { - double x = PyFloat_AsDouble(v); - if (x == -1 && PyErr_Occurred()) { - PyErr_SetString(StructError, - "required argument is not a float"); - return -1; - } - memcpy(p, (char *)&x, sizeof(double)); - return 0; + double x = PyFloat_AsDouble(v); + if (x == -1 && PyErr_Occurred()) { + PyErr_SetString(StructError, + "required argument is not a float"); + return -1; + } + memcpy(p, (char *)&x, sizeof(double)); + return 0; } static int np_void_p(char *p, PyObject *v, const formatdef *f) { - void *x; + void *x; - v = get_pylong(v); - if (v == NULL) - return -1; - assert(PyLong_Check(v)); - x = PyLong_AsVoidPtr(v); - Py_DECREF(v); - if (x == NULL && PyErr_Occurred()) - return -1; - memcpy(p, (char *)&x, sizeof x); - return 0; + v = get_pylong(v); + if (v == NULL) + return -1; + assert(PyLong_Check(v)); + x = PyLong_AsVoidPtr(v); + Py_DECREF(v); + if (x == NULL && PyErr_Occurred()) + return -1; + memcpy(p, (char *)&x, sizeof x); + return 0; } static formatdef native_table[] = { - {'x', sizeof(char), 0, NULL}, - {'b', sizeof(char), 0, nu_byte, np_byte}, - {'B', sizeof(char), 0, nu_ubyte, np_ubyte}, - {'c', sizeof(char), 0, nu_char, np_char}, - {'s', sizeof(char), 0, NULL}, - {'p', sizeof(char), 0, NULL}, - {'h', sizeof(short), SHORT_ALIGN, nu_short, np_short}, - {'H', sizeof(short), SHORT_ALIGN, nu_ushort, np_ushort}, - {'i', sizeof(int), INT_ALIGN, nu_int, np_int}, - {'I', sizeof(int), INT_ALIGN, nu_uint, np_uint}, - {'l', sizeof(long), LONG_ALIGN, nu_long, np_long}, - {'L', sizeof(long), LONG_ALIGN, nu_ulong, np_ulong}, + {'x', sizeof(char), 0, NULL}, + {'b', sizeof(char), 0, nu_byte, np_byte}, + {'B', sizeof(char), 0, nu_ubyte, np_ubyte}, + {'c', sizeof(char), 0, nu_char, np_char}, + {'s', sizeof(char), 0, NULL}, + {'p', sizeof(char), 0, NULL}, + {'h', sizeof(short), SHORT_ALIGN, nu_short, np_short}, + {'H', sizeof(short), SHORT_ALIGN, nu_ushort, np_ushort}, + {'i', sizeof(int), INT_ALIGN, nu_int, np_int}, + {'I', sizeof(int), INT_ALIGN, nu_uint, np_uint}, + {'l', sizeof(long), LONG_ALIGN, nu_long, np_long}, + {'L', sizeof(long), LONG_ALIGN, nu_ulong, np_ulong}, #ifdef HAVE_LONG_LONG - {'q', sizeof(PY_LONG_LONG), LONG_LONG_ALIGN, nu_longlong, np_longlong}, - {'Q', sizeof(PY_LONG_LONG), LONG_LONG_ALIGN, nu_ulonglong,np_ulonglong}, + {'q', sizeof(PY_LONG_LONG), LONG_LONG_ALIGN, nu_longlong, np_longlong}, + {'Q', sizeof(PY_LONG_LONG), LONG_LONG_ALIGN, nu_ulonglong,np_ulonglong}, #endif - {'?', sizeof(BOOL_TYPE), BOOL_ALIGN, nu_bool, np_bool}, - {'f', sizeof(float), FLOAT_ALIGN, nu_float, np_float}, - {'d', sizeof(double), DOUBLE_ALIGN, nu_double, np_double}, - {'P', sizeof(void *), VOID_P_ALIGN, nu_void_p, np_void_p}, - {0} + {'?', sizeof(BOOL_TYPE), BOOL_ALIGN, nu_bool, np_bool}, + {'f', sizeof(float), FLOAT_ALIGN, nu_float, np_float}, + {'d', sizeof(double), DOUBLE_ALIGN, nu_double, np_double}, + {'P', sizeof(void *), VOID_P_ALIGN, nu_void_p, np_void_p}, + {0} }; /* Big-endian routines. *****************************************************/ @@ -669,53 +669,53 @@ static PyObject * bu_int(const char *p, const formatdef *f) { - long x = 0; - Py_ssize_t i = f->size; - const unsigned char *bytes = (const unsigned char *)p; - do { - x = (x<<8) | *bytes++; - } while (--i > 0); - /* Extend the sign bit. */ - if (SIZEOF_LONG > f->size) - x |= -(x & (1L << ((8 * f->size) - 1))); - return PyLong_FromLong(x); + long x = 0; + Py_ssize_t i = f->size; + const unsigned char *bytes = (const unsigned char *)p; + do { + x = (x<<8) | *bytes++; + } while (--i > 0); + /* Extend the sign bit. */ + if (SIZEOF_LONG > f->size) + x |= -(x & (1L << ((8 * f->size) - 1))); + return PyLong_FromLong(x); } static PyObject * bu_uint(const char *p, const formatdef *f) { - unsigned long x = 0; - Py_ssize_t i = f->size; - const unsigned char *bytes = (const unsigned char *)p; - do { - x = (x<<8) | *bytes++; - } while (--i > 0); - if (x <= LONG_MAX) - return PyLong_FromLong((long)x); - return PyLong_FromUnsignedLong(x); + unsigned long x = 0; + Py_ssize_t i = f->size; + const unsigned char *bytes = (const unsigned char *)p; + do { + x = (x<<8) | *bytes++; + } while (--i > 0); + if (x <= LONG_MAX) + return PyLong_FromLong((long)x); + return PyLong_FromUnsignedLong(x); } static PyObject * bu_longlong(const char *p, const formatdef *f) { #ifdef HAVE_LONG_LONG - PY_LONG_LONG x = 0; - Py_ssize_t i = f->size; - const unsigned char *bytes = (const unsigned char *)p; - do { - x = (x<<8) | *bytes++; - } while (--i > 0); - /* Extend the sign bit. */ - if (SIZEOF_LONG_LONG > f->size) - x |= -(x & ((PY_LONG_LONG)1 << ((8 * f->size) - 1))); - if (x >= LONG_MIN && x <= LONG_MAX) - return PyLong_FromLong(Py_SAFE_DOWNCAST(x, PY_LONG_LONG, long)); - return PyLong_FromLongLong(x); + PY_LONG_LONG x = 0; + Py_ssize_t i = f->size; + const unsigned char *bytes = (const unsigned char *)p; + do { + x = (x<<8) | *bytes++; + } while (--i > 0); + /* Extend the sign bit. */ + if (SIZEOF_LONG_LONG > f->size) + x |= -(x & ((PY_LONG_LONG)1 << ((8 * f->size) - 1))); + if (x >= LONG_MIN && x <= LONG_MAX) + return PyLong_FromLong(Py_SAFE_DOWNCAST(x, PY_LONG_LONG, long)); + return PyLong_FromLongLong(x); #else - return _PyLong_FromByteArray((const unsigned char *)p, - 8, - 0, /* little-endian */ - 1 /* signed */); + return _PyLong_FromByteArray((const unsigned char *)p, + 8, + 0, /* little-endian */ + 1 /* signed */); #endif } @@ -723,171 +723,171 @@ bu_ulonglong(const char *p, const formatdef *f) { #ifdef HAVE_LONG_LONG - unsigned PY_LONG_LONG x = 0; - Py_ssize_t i = f->size; - const unsigned char *bytes = (const unsigned char *)p; - do { - x = (x<<8) | *bytes++; - } while (--i > 0); - if (x <= LONG_MAX) - return PyLong_FromLong(Py_SAFE_DOWNCAST(x, unsigned PY_LONG_LONG, long)); - return PyLong_FromUnsignedLongLong(x); + unsigned PY_LONG_LONG x = 0; + Py_ssize_t i = f->size; + const unsigned char *bytes = (const unsigned char *)p; + do { + x = (x<<8) | *bytes++; + } while (--i > 0); + if (x <= LONG_MAX) + return PyLong_FromLong(Py_SAFE_DOWNCAST(x, unsigned PY_LONG_LONG, long)); + return PyLong_FromUnsignedLongLong(x); #else - return _PyLong_FromByteArray((const unsigned char *)p, - 8, - 0, /* little-endian */ - 0 /* signed */); + return _PyLong_FromByteArray((const unsigned char *)p, + 8, + 0, /* little-endian */ + 0 /* signed */); #endif } static PyObject * bu_float(const char *p, const formatdef *f) { - return unpack_float(p, 0); + return unpack_float(p, 0); } static PyObject * bu_double(const char *p, const formatdef *f) { - return unpack_double(p, 0); + return unpack_double(p, 0); } static PyObject * bu_bool(const char *p, const formatdef *f) { - char x; - memcpy((char *)&x, p, sizeof x); - return PyBool_FromLong(x != 0); + char x; + memcpy((char *)&x, p, sizeof x); + return PyBool_FromLong(x != 0); } static int bp_int(char *p, PyObject *v, const formatdef *f) { - long x; - Py_ssize_t i; - if (get_long(v, &x) < 0) - return -1; - i = f->size; - if (i != SIZEOF_LONG) { - if ((i == 2) && (x < -32768 || x > 32767)) - RANGE_ERROR(x, f, 0, 0xffffL); + long x; + Py_ssize_t i; + if (get_long(v, &x) < 0) + return -1; + i = f->size; + if (i != SIZEOF_LONG) { + if ((i == 2) && (x < -32768 || x > 32767)) + RANGE_ERROR(x, f, 0, 0xffffL); #if (SIZEOF_LONG != 4) - else if ((i == 4) && (x < -2147483648L || x > 2147483647L)) - RANGE_ERROR(x, f, 0, 0xffffffffL); + else if ((i == 4) && (x < -2147483648L || x > 2147483647L)) + RANGE_ERROR(x, f, 0, 0xffffffffL); #endif - } - do { - p[--i] = (char)x; - x >>= 8; - } while (i > 0); - return 0; + } + do { + p[--i] = (char)x; + x >>= 8; + } while (i > 0); + return 0; } static int bp_uint(char *p, PyObject *v, const formatdef *f) { - unsigned long x; - Py_ssize_t i; - if (get_ulong(v, &x) < 0) - return -1; - i = f->size; - if (i != SIZEOF_LONG) { - unsigned long maxint = 1; - maxint <<= (unsigned long)(i * 8); - if (x >= maxint) - RANGE_ERROR(x, f, 1, maxint - 1); - } - do { - p[--i] = (char)x; - x >>= 8; - } while (i > 0); - return 0; + unsigned long x; + Py_ssize_t i; + if (get_ulong(v, &x) < 0) + return -1; + i = f->size; + if (i != SIZEOF_LONG) { + unsigned long maxint = 1; + maxint <<= (unsigned long)(i * 8); + if (x >= maxint) + RANGE_ERROR(x, f, 1, maxint - 1); + } + do { + p[--i] = (char)x; + x >>= 8; + } while (i > 0); + return 0; } static int bp_longlong(char *p, PyObject *v, const formatdef *f) { - int res; - v = get_pylong(v); - if (v == NULL) - return -1; - res = _PyLong_AsByteArray((PyLongObject *)v, - (unsigned char *)p, - 8, - 0, /* little_endian */ - 1 /* signed */); - Py_DECREF(v); - return res; + int res; + v = get_pylong(v); + if (v == NULL) + return -1; + res = _PyLong_AsByteArray((PyLongObject *)v, + (unsigned char *)p, + 8, + 0, /* little_endian */ + 1 /* signed */); + Py_DECREF(v); + return res; } static int bp_ulonglong(char *p, PyObject *v, const formatdef *f) { - int res; - v = get_pylong(v); - if (v == NULL) - return -1; - res = _PyLong_AsByteArray((PyLongObject *)v, - (unsigned char *)p, - 8, - 0, /* little_endian */ - 0 /* signed */); - Py_DECREF(v); - return res; + int res; + v = get_pylong(v); + if (v == NULL) + return -1; + res = _PyLong_AsByteArray((PyLongObject *)v, + (unsigned char *)p, + 8, + 0, /* little_endian */ + 0 /* signed */); + Py_DECREF(v); + return res; } static int bp_float(char *p, PyObject *v, const formatdef *f) { - double x = PyFloat_AsDouble(v); - if (x == -1 && PyErr_Occurred()) { - PyErr_SetString(StructError, - "required argument is not a float"); - return -1; - } - return _PyFloat_Pack4(x, (unsigned char *)p, 0); + double x = PyFloat_AsDouble(v); + if (x == -1 && PyErr_Occurred()) { + PyErr_SetString(StructError, + "required argument is not a float"); + return -1; + } + return _PyFloat_Pack4(x, (unsigned char *)p, 0); } static int bp_double(char *p, PyObject *v, const formatdef *f) { - double x = PyFloat_AsDouble(v); - if (x == -1 && PyErr_Occurred()) { - PyErr_SetString(StructError, - "required argument is not a float"); - return -1; - } - return _PyFloat_Pack8(x, (unsigned char *)p, 0); + double x = PyFloat_AsDouble(v); + if (x == -1 && PyErr_Occurred()) { + PyErr_SetString(StructError, + "required argument is not a float"); + return -1; + } + return _PyFloat_Pack8(x, (unsigned char *)p, 0); } static int bp_bool(char *p, PyObject *v, const formatdef *f) { - char y; - y = PyObject_IsTrue(v); - memcpy(p, (char *)&y, sizeof y); - return 0; + char y; + y = PyObject_IsTrue(v); + memcpy(p, (char *)&y, sizeof y); + return 0; } static formatdef bigendian_table[] = { - {'x', 1, 0, NULL}, - {'b', 1, 0, nu_byte, np_byte}, - {'B', 1, 0, nu_ubyte, np_ubyte}, - {'c', 1, 0, nu_char, np_char}, - {'s', 1, 0, NULL}, - {'p', 1, 0, NULL}, - {'h', 2, 0, bu_int, bp_int}, - {'H', 2, 0, bu_uint, bp_uint}, - {'i', 4, 0, bu_int, bp_int}, - {'I', 4, 0, bu_uint, bp_uint}, - {'l', 4, 0, bu_int, bp_int}, - {'L', 4, 0, bu_uint, bp_uint}, - {'q', 8, 0, bu_longlong, bp_longlong}, - {'Q', 8, 0, bu_ulonglong, bp_ulonglong}, - {'?', 1, 0, bu_bool, bp_bool}, - {'f', 4, 0, bu_float, bp_float}, - {'d', 8, 0, bu_double, bp_double}, - {0} + {'x', 1, 0, NULL}, + {'b', 1, 0, nu_byte, np_byte}, + {'B', 1, 0, nu_ubyte, np_ubyte}, + {'c', 1, 0, nu_char, np_char}, + {'s', 1, 0, NULL}, + {'p', 1, 0, NULL}, + {'h', 2, 0, bu_int, bp_int}, + {'H', 2, 0, bu_uint, bp_uint}, + {'i', 4, 0, bu_int, bp_int}, + {'I', 4, 0, bu_uint, bp_uint}, + {'l', 4, 0, bu_int, bp_int}, + {'L', 4, 0, bu_uint, bp_uint}, + {'q', 8, 0, bu_longlong, bp_longlong}, + {'Q', 8, 0, bu_ulonglong, bp_ulonglong}, + {'?', 1, 0, bu_bool, bp_bool}, + {'f', 4, 0, bu_float, bp_float}, + {'d', 8, 0, bu_double, bp_double}, + {0} }; /* Little-endian routines. *****************************************************/ @@ -895,53 +895,53 @@ static PyObject * lu_int(const char *p, const formatdef *f) { - long x = 0; - Py_ssize_t i = f->size; - const unsigned char *bytes = (const unsigned char *)p; - do { - x = (x<<8) | bytes[--i]; - } while (i > 0); - /* Extend the sign bit. */ - if (SIZEOF_LONG > f->size) - x |= -(x & (1L << ((8 * f->size) - 1))); - return PyLong_FromLong(x); + long x = 0; + Py_ssize_t i = f->size; + const unsigned char *bytes = (const unsigned char *)p; + do { + x = (x<<8) | bytes[--i]; + } while (i > 0); + /* Extend the sign bit. */ + if (SIZEOF_LONG > f->size) + x |= -(x & (1L << ((8 * f->size) - 1))); + return PyLong_FromLong(x); } static PyObject * lu_uint(const char *p, const formatdef *f) { - unsigned long x = 0; - Py_ssize_t i = f->size; - const unsigned char *bytes = (const unsigned char *)p; - do { - x = (x<<8) | bytes[--i]; - } while (i > 0); - if (x <= LONG_MAX) - return PyLong_FromLong((long)x); - return PyLong_FromUnsignedLong((long)x); + unsigned long x = 0; + Py_ssize_t i = f->size; + const unsigned char *bytes = (const unsigned char *)p; + do { + x = (x<<8) | bytes[--i]; + } while (i > 0); + if (x <= LONG_MAX) + return PyLong_FromLong((long)x); + return PyLong_FromUnsignedLong((long)x); } static PyObject * lu_longlong(const char *p, const formatdef *f) { #ifdef HAVE_LONG_LONG - PY_LONG_LONG x = 0; - Py_ssize_t i = f->size; - const unsigned char *bytes = (const unsigned char *)p; - do { - x = (x<<8) | bytes[--i]; - } while (i > 0); - /* Extend the sign bit. */ - if (SIZEOF_LONG_LONG > f->size) - x |= -(x & ((PY_LONG_LONG)1 << ((8 * f->size) - 1))); - if (x >= LONG_MIN && x <= LONG_MAX) - return PyLong_FromLong(Py_SAFE_DOWNCAST(x, PY_LONG_LONG, long)); - return PyLong_FromLongLong(x); + PY_LONG_LONG x = 0; + Py_ssize_t i = f->size; + const unsigned char *bytes = (const unsigned char *)p; + do { + x = (x<<8) | bytes[--i]; + } while (i > 0); + /* Extend the sign bit. */ + if (SIZEOF_LONG_LONG > f->size) + x |= -(x & ((PY_LONG_LONG)1 << ((8 * f->size) - 1))); + if (x >= LONG_MIN && x <= LONG_MAX) + return PyLong_FromLong(Py_SAFE_DOWNCAST(x, PY_LONG_LONG, long)); + return PyLong_FromLongLong(x); #else - return _PyLong_FromByteArray((const unsigned char *)p, - 8, - 1, /* little-endian */ - 1 /* signed */); + return _PyLong_FromByteArray((const unsigned char *)p, + 8, + 1, /* little-endian */ + 1 /* signed */); #endif } @@ -949,182 +949,182 @@ lu_ulonglong(const char *p, const formatdef *f) { #ifdef HAVE_LONG_LONG - unsigned PY_LONG_LONG x = 0; - Py_ssize_t i = f->size; - const unsigned char *bytes = (const unsigned char *)p; - do { - x = (x<<8) | bytes[--i]; - } while (i > 0); - if (x <= LONG_MAX) - return PyLong_FromLong(Py_SAFE_DOWNCAST(x, unsigned PY_LONG_LONG, long)); - return PyLong_FromUnsignedLongLong(x); + unsigned PY_LONG_LONG x = 0; + Py_ssize_t i = f->size; + const unsigned char *bytes = (const unsigned char *)p; + do { + x = (x<<8) | bytes[--i]; + } while (i > 0); + if (x <= LONG_MAX) + return PyLong_FromLong(Py_SAFE_DOWNCAST(x, unsigned PY_LONG_LONG, long)); + return PyLong_FromUnsignedLongLong(x); #else - return _PyLong_FromByteArray((const unsigned char *)p, - 8, - 1, /* little-endian */ - 0 /* signed */); + return _PyLong_FromByteArray((const unsigned char *)p, + 8, + 1, /* little-endian */ + 0 /* signed */); #endif } static PyObject * lu_float(const char *p, const formatdef *f) { - return unpack_float(p, 1); + return unpack_float(p, 1); } static PyObject * lu_double(const char *p, const formatdef *f) { - return unpack_double(p, 1); + return unpack_double(p, 1); } static int lp_int(char *p, PyObject *v, const formatdef *f) { - long x; - Py_ssize_t i; - if (get_long(v, &x) < 0) - return -1; - i = f->size; - if (i != SIZEOF_LONG) { - if ((i == 2) && (x < -32768 || x > 32767)) - RANGE_ERROR(x, f, 0, 0xffffL); + long x; + Py_ssize_t i; + if (get_long(v, &x) < 0) + return -1; + i = f->size; + if (i != SIZEOF_LONG) { + if ((i == 2) && (x < -32768 || x > 32767)) + RANGE_ERROR(x, f, 0, 0xffffL); #if (SIZEOF_LONG != 4) - else if ((i == 4) && (x < -2147483648L || x > 2147483647L)) - RANGE_ERROR(x, f, 0, 0xffffffffL); + else if ((i == 4) && (x < -2147483648L || x > 2147483647L)) + RANGE_ERROR(x, f, 0, 0xffffffffL); #endif - } - do { - *p++ = (char)x; - x >>= 8; - } while (--i > 0); - return 0; + } + do { + *p++ = (char)x; + x >>= 8; + } while (--i > 0); + return 0; } static int lp_uint(char *p, PyObject *v, const formatdef *f) { - unsigned long x; - Py_ssize_t i; - if (get_ulong(v, &x) < 0) - return -1; - i = f->size; - if (i != SIZEOF_LONG) { - unsigned long maxint = 1; - maxint <<= (unsigned long)(i * 8); - if (x >= maxint) - RANGE_ERROR(x, f, 1, maxint - 1); - } - do { - *p++ = (char)x; - x >>= 8; - } while (--i > 0); - return 0; + unsigned long x; + Py_ssize_t i; + if (get_ulong(v, &x) < 0) + return -1; + i = f->size; + if (i != SIZEOF_LONG) { + unsigned long maxint = 1; + maxint <<= (unsigned long)(i * 8); + if (x >= maxint) + RANGE_ERROR(x, f, 1, maxint - 1); + } + do { + *p++ = (char)x; + x >>= 8; + } while (--i > 0); + return 0; } static int lp_longlong(char *p, PyObject *v, const formatdef *f) { - int res; - v = get_pylong(v); - if (v == NULL) - return -1; - res = _PyLong_AsByteArray((PyLongObject*)v, - (unsigned char *)p, - 8, - 1, /* little_endian */ - 1 /* signed */); - Py_DECREF(v); - return res; + int res; + v = get_pylong(v); + if (v == NULL) + return -1; + res = _PyLong_AsByteArray((PyLongObject*)v, + (unsigned char *)p, + 8, + 1, /* little_endian */ + 1 /* signed */); + Py_DECREF(v); + return res; } static int lp_ulonglong(char *p, PyObject *v, const formatdef *f) { - int res; - v = get_pylong(v); - if (v == NULL) - return -1; - res = _PyLong_AsByteArray((PyLongObject*)v, - (unsigned char *)p, - 8, - 1, /* little_endian */ - 0 /* signed */); - Py_DECREF(v); - return res; + int res; + v = get_pylong(v); + if (v == NULL) + return -1; + res = _PyLong_AsByteArray((PyLongObject*)v, + (unsigned char *)p, + 8, + 1, /* little_endian */ + 0 /* signed */); + Py_DECREF(v); + return res; } static int lp_float(char *p, PyObject *v, const formatdef *f) { - double x = PyFloat_AsDouble(v); - if (x == -1 && PyErr_Occurred()) { - PyErr_SetString(StructError, - "required argument is not a float"); - return -1; - } - return _PyFloat_Pack4(x, (unsigned char *)p, 1); + double x = PyFloat_AsDouble(v); + if (x == -1 && PyErr_Occurred()) { + PyErr_SetString(StructError, + "required argument is not a float"); + return -1; + } + return _PyFloat_Pack4(x, (unsigned char *)p, 1); } static int lp_double(char *p, PyObject *v, const formatdef *f) { - double x = PyFloat_AsDouble(v); - if (x == -1 && PyErr_Occurred()) { - PyErr_SetString(StructError, - "required argument is not a float"); - return -1; - } - return _PyFloat_Pack8(x, (unsigned char *)p, 1); + double x = PyFloat_AsDouble(v); + if (x == -1 && PyErr_Occurred()) { + PyErr_SetString(StructError, + "required argument is not a float"); + return -1; + } + return _PyFloat_Pack8(x, (unsigned char *)p, 1); } static formatdef lilendian_table[] = { - {'x', 1, 0, NULL}, - {'b', 1, 0, nu_byte, np_byte}, - {'B', 1, 0, nu_ubyte, np_ubyte}, - {'c', 1, 0, nu_char, np_char}, - {'s', 1, 0, NULL}, - {'p', 1, 0, NULL}, - {'h', 2, 0, lu_int, lp_int}, - {'H', 2, 0, lu_uint, lp_uint}, - {'i', 4, 0, lu_int, lp_int}, - {'I', 4, 0, lu_uint, lp_uint}, - {'l', 4, 0, lu_int, lp_int}, - {'L', 4, 0, lu_uint, lp_uint}, - {'q', 8, 0, lu_longlong, lp_longlong}, - {'Q', 8, 0, lu_ulonglong, lp_ulonglong}, - {'?', 1, 0, bu_bool, bp_bool}, /* Std rep not endian dep, - but potentially different from native rep -- reuse bx_bool funcs. */ - {'f', 4, 0, lu_float, lp_float}, - {'d', 8, 0, lu_double, lp_double}, - {0} + {'x', 1, 0, NULL}, + {'b', 1, 0, nu_byte, np_byte}, + {'B', 1, 0, nu_ubyte, np_ubyte}, + {'c', 1, 0, nu_char, np_char}, + {'s', 1, 0, NULL}, + {'p', 1, 0, NULL}, + {'h', 2, 0, lu_int, lp_int}, + {'H', 2, 0, lu_uint, lp_uint}, + {'i', 4, 0, lu_int, lp_int}, + {'I', 4, 0, lu_uint, lp_uint}, + {'l', 4, 0, lu_int, lp_int}, + {'L', 4, 0, lu_uint, lp_uint}, + {'q', 8, 0, lu_longlong, lp_longlong}, + {'Q', 8, 0, lu_ulonglong, lp_ulonglong}, + {'?', 1, 0, bu_bool, bp_bool}, /* Std rep not endian dep, + but potentially different from native rep -- reuse bx_bool funcs. */ + {'f', 4, 0, lu_float, lp_float}, + {'d', 8, 0, lu_double, lp_double}, + {0} }; static const formatdef * whichtable(char **pfmt) { - const char *fmt = (*pfmt)++; /* May be backed out of later */ - switch (*fmt) { - case '<': - return lilendian_table; - case '>': - case '!': /* Network byte order is big-endian */ - return bigendian_table; - case '=': { /* Host byte order -- different from native in aligment! */ - int n = 1; - char *p = (char *) &n; - if (*p == 1) - return lilendian_table; - else - return bigendian_table; - } - default: - --*pfmt; /* Back out of pointer increment */ - /* Fall through */ - case '@': - return native_table; - } + const char *fmt = (*pfmt)++; /* May be backed out of later */ + switch (*fmt) { + case '<': + return lilendian_table; + case '>': + case '!': /* Network byte order is big-endian */ + return bigendian_table; + case '=': { /* Host byte order -- different from native in aligment! */ + int n = 1; + char *p = (char *) &n; + if (*p == 1) + return lilendian_table; + else + return bigendian_table; + } + default: + --*pfmt; /* Back out of pointer increment */ + /* Fall through */ + case '@': + return native_table; + } } @@ -1133,13 +1133,13 @@ static const formatdef * getentry(int c, const formatdef *f) { - for (; f->format != '\0'; f++) { - if (f->format == c) { - return f; - } - } - PyErr_SetString(StructError, "bad char in struct format"); - return NULL; + for (; f->format != '\0'; f++) { + if (f->format == c) { + return f; + } + } + PyErr_SetString(StructError, "bad char in struct format"); + return NULL; } @@ -1148,14 +1148,14 @@ static int align(Py_ssize_t size, char c, const formatdef *e) { - if (e->format == c) { - if (e->alignment) { - size = ((size + e->alignment - 1) - / e->alignment) - * e->alignment; - } - } - return size; + if (e->format == c) { + if (e->alignment) { + size = ((size + e->alignment - 1) + / e->alignment) + * e->alignment; + } + } + return size; } @@ -1164,224 +1164,224 @@ static int prepare_s(PyStructObject *self) { - const formatdef *f; - const formatdef *e; - formatcode *codes; - - const char *s; - const char *fmt; - char c; - Py_ssize_t size, len, num, itemsize, x; - - fmt = PyBytes_AS_STRING(self->s_format); - - f = whichtable((char **)&fmt); - - s = fmt; - size = 0; - len = 0; - while ((c = *s++) != '\0') { - if (isspace(Py_CHARMASK(c))) - continue; - if ('0' <= c && c <= '9') { - num = c - '0'; - while ('0' <= (c = *s++) && c <= '9') { - x = num*10 + (c - '0'); - if (x/10 != num) { - PyErr_SetString( - StructError, - "overflow in item count"); - return -1; - } - num = x; - } - if (c == '\0') - break; - } - else - num = 1; - - e = getentry(c, f); - if (e == NULL) - return -1; - - switch (c) { - case 's': /* fall through */ - case 'p': len++; break; - case 'x': break; - default: len += num; break; - } - - itemsize = e->size; - size = align(size, c, e); - x = num * itemsize; - size += x; - if (x/itemsize != num || size < 0) { - PyErr_SetString(StructError, - "total struct size too long"); - return -1; - } - } - - /* check for overflow */ - if ((len + 1) > (PY_SSIZE_T_MAX / sizeof(formatcode))) { - PyErr_NoMemory(); - return -1; - } - - self->s_size = size; - self->s_len = len; - codes = PyMem_MALLOC((len + 1) * sizeof(formatcode)); - if (codes == NULL) { - PyErr_NoMemory(); - return -1; - } - self->s_codes = codes; - - s = fmt; - size = 0; - while ((c = *s++) != '\0') { - if (isspace(Py_CHARMASK(c))) - continue; - if ('0' <= c && c <= '9') { - num = c - '0'; - while ('0' <= (c = *s++) && c <= '9') - num = num*10 + (c - '0'); - if (c == '\0') - break; - } - else - num = 1; - - e = getentry(c, f); - - size = align(size, c, e); - if (c == 's' || c == 'p') { - codes->offset = size; - codes->size = num; - codes->fmtdef = e; - codes++; - size += num; - } else if (c == 'x') { - size += num; - } else { - while (--num >= 0) { - codes->offset = size; - codes->size = e->size; - codes->fmtdef = e; - codes++; - size += e->size; - } - } - } - codes->fmtdef = NULL; - codes->offset = size; - codes->size = 0; + const formatdef *f; + const formatdef *e; + formatcode *codes; + + const char *s; + const char *fmt; + char c; + Py_ssize_t size, len, num, itemsize, x; + + fmt = PyBytes_AS_STRING(self->s_format); + + f = whichtable((char **)&fmt); + + s = fmt; + size = 0; + len = 0; + while ((c = *s++) != '\0') { + if (isspace(Py_CHARMASK(c))) + continue; + if ('0' <= c && c <= '9') { + num = c - '0'; + while ('0' <= (c = *s++) && c <= '9') { + x = num*10 + (c - '0'); + if (x/10 != num) { + PyErr_SetString( + StructError, + "overflow in item count"); + return -1; + } + num = x; + } + if (c == '\0') + break; + } + else + num = 1; + + e = getentry(c, f); + if (e == NULL) + return -1; + + switch (c) { + case 's': /* fall through */ + case 'p': len++; break; + case 'x': break; + default: len += num; break; + } + + itemsize = e->size; + size = align(size, c, e); + x = num * itemsize; + size += x; + if (x/itemsize != num || size < 0) { + PyErr_SetString(StructError, + "total struct size too long"); + return -1; + } + } + + /* check for overflow */ + if ((len + 1) > (PY_SSIZE_T_MAX / sizeof(formatcode))) { + PyErr_NoMemory(); + return -1; + } + + self->s_size = size; + self->s_len = len; + codes = PyMem_MALLOC((len + 1) * sizeof(formatcode)); + if (codes == NULL) { + PyErr_NoMemory(); + return -1; + } + self->s_codes = codes; + + s = fmt; + size = 0; + while ((c = *s++) != '\0') { + if (isspace(Py_CHARMASK(c))) + continue; + if ('0' <= c && c <= '9') { + num = c - '0'; + while ('0' <= (c = *s++) && c <= '9') + num = num*10 + (c - '0'); + if (c == '\0') + break; + } + else + num = 1; + + e = getentry(c, f); + + size = align(size, c, e); + if (c == 's' || c == 'p') { + codes->offset = size; + codes->size = num; + codes->fmtdef = e; + codes++; + size += num; + } else if (c == 'x') { + size += num; + } else { + while (--num >= 0) { + codes->offset = size; + codes->size = e->size; + codes->fmtdef = e; + codes++; + size += e->size; + } + } + } + codes->fmtdef = NULL; + codes->offset = size; + codes->size = 0; - return 0; + return 0; } static PyObject * s_new(PyTypeObject *type, PyObject *args, PyObject *kwds) { - PyObject *self; + PyObject *self; - assert(type != NULL && type->tp_alloc != NULL); + assert(type != NULL && type->tp_alloc != NULL); - self = type->tp_alloc(type, 0); - if (self != NULL) { - PyStructObject *s = (PyStructObject*)self; - Py_INCREF(Py_None); - s->s_format = Py_None; - s->s_codes = NULL; - s->s_size = -1; - s->s_len = -1; - } - return self; + self = type->tp_alloc(type, 0); + if (self != NULL) { + PyStructObject *s = (PyStructObject*)self; + Py_INCREF(Py_None); + s->s_format = Py_None; + s->s_codes = NULL; + s->s_size = -1; + s->s_len = -1; + } + return self; } static int s_init(PyObject *self, PyObject *args, PyObject *kwds) { - PyStructObject *soself = (PyStructObject *)self; - PyObject *o_format = NULL; - int ret = 0; - static char *kwlist[] = {"format", 0}; - - assert(PyStruct_Check(self)); - - if (!PyArg_ParseTupleAndKeywords(args, kwds, "O:Struct", kwlist, - &o_format)) - return -1; - - if (PyUnicode_Check(o_format)) { - o_format = PyUnicode_AsASCIIString(o_format); - if (o_format == NULL) - return -1; - } - /* XXX support buffer interface, too */ - else { - Py_INCREF(o_format); - } - - if (!PyBytes_Check(o_format)) { - Py_DECREF(o_format); - PyErr_Format(PyExc_TypeError, - "Struct() argument 1 must be bytes, not %.200s", - Py_TYPE(o_format)->tp_name); - return -1; - } + PyStructObject *soself = (PyStructObject *)self; + PyObject *o_format = NULL; + int ret = 0; + static char *kwlist[] = {"format", 0}; + + assert(PyStruct_Check(self)); + + if (!PyArg_ParseTupleAndKeywords(args, kwds, "O:Struct", kwlist, + &o_format)) + return -1; + + if (PyUnicode_Check(o_format)) { + o_format = PyUnicode_AsASCIIString(o_format); + if (o_format == NULL) + return -1; + } + /* XXX support buffer interface, too */ + else { + Py_INCREF(o_format); + } + + if (!PyBytes_Check(o_format)) { + Py_DECREF(o_format); + PyErr_Format(PyExc_TypeError, + "Struct() argument 1 must be bytes, not %.200s", + Py_TYPE(o_format)->tp_name); + return -1; + } - Py_CLEAR(soself->s_format); - soself->s_format = o_format; + Py_CLEAR(soself->s_format); + soself->s_format = o_format; - ret = prepare_s(soself); - return ret; + ret = prepare_s(soself); + return ret; } static void s_dealloc(PyStructObject *s) { - if (s->weakreflist != NULL) - PyObject_ClearWeakRefs((PyObject *)s); - if (s->s_codes != NULL) { - PyMem_FREE(s->s_codes); - } - Py_XDECREF(s->s_format); - Py_TYPE(s)->tp_free((PyObject *)s); + if (s->weakreflist != NULL) + PyObject_ClearWeakRefs((PyObject *)s); + if (s->s_codes != NULL) { + PyMem_FREE(s->s_codes); + } + Py_XDECREF(s->s_format); + Py_TYPE(s)->tp_free((PyObject *)s); } static PyObject * s_unpack_internal(PyStructObject *soself, char *startfrom) { - formatcode *code; - Py_ssize_t i = 0; - PyObject *result = PyTuple_New(soself->s_len); - if (result == NULL) - return NULL; - - for (code = soself->s_codes; code->fmtdef != NULL; code++) { - PyObject *v; - const formatdef *e = code->fmtdef; - const char *res = startfrom + code->offset; - if (e->format == 's') { - v = PyBytes_FromStringAndSize(res, code->size); - } else if (e->format == 'p') { - Py_ssize_t n = *(unsigned char*)res; - if (n >= code->size) - n = code->size - 1; - v = PyBytes_FromStringAndSize(res + 1, n); - } else { - v = e->unpack(res, e); - } - if (v == NULL) - goto fail; - PyTuple_SET_ITEM(result, i++, v); - } + formatcode *code; + Py_ssize_t i = 0; + PyObject *result = PyTuple_New(soself->s_len); + if (result == NULL) + return NULL; + + for (code = soself->s_codes; code->fmtdef != NULL; code++) { + PyObject *v; + const formatdef *e = code->fmtdef; + const char *res = startfrom + code->offset; + if (e->format == 's') { + v = PyBytes_FromStringAndSize(res, code->size); + } else if (e->format == 'p') { + Py_ssize_t n = *(unsigned char*)res; + if (n >= code->size) + n = code->size - 1; + v = PyBytes_FromStringAndSize(res + 1, n); + } else { + v = e->unpack(res, e); + } + if (v == NULL) + goto fail; + PyTuple_SET_ITEM(result, i++, v); + } - return result; + return result; fail: - Py_DECREF(result); - return NULL; + Py_DECREF(result); + return NULL; } @@ -1395,24 +1395,24 @@ static PyObject * s_unpack(PyObject *self, PyObject *input) { - Py_buffer vbuf; - PyObject *result; - PyStructObject *soself = (PyStructObject *)self; - - assert(PyStruct_Check(self)); - assert(soself->s_codes != NULL); - if (PyObject_GetBuffer(input, &vbuf, PyBUF_SIMPLE) < 0) - return NULL; - if (vbuf.len != soself->s_size) { - PyErr_Format(StructError, - "unpack requires a bytes argument of length %zd", - soself->s_size); - PyBuffer_Release(&vbuf); - return NULL; - } - result = s_unpack_internal(soself, vbuf.buf); - PyBuffer_Release(&vbuf); - return result; + Py_buffer vbuf; + PyObject *result; + PyStructObject *soself = (PyStructObject *)self; + + assert(PyStruct_Check(self)); + assert(soself->s_codes != NULL); + if (PyObject_GetBuffer(input, &vbuf, PyBUF_SIMPLE) < 0) + return NULL; + if (vbuf.len != soself->s_size) { + PyErr_Format(StructError, + "unpack requires a bytes argument of length %zd", + soself->s_size); + PyBuffer_Release(&vbuf); + return NULL; + } + result = s_unpack_internal(soself, vbuf.buf); + PyBuffer_Release(&vbuf); + return result; } PyDoc_STRVAR(s_unpack_from__doc__, @@ -1426,35 +1426,35 @@ static PyObject * s_unpack_from(PyObject *self, PyObject *args, PyObject *kwds) { - static char *kwlist[] = {"buffer", "offset", 0}; + static char *kwlist[] = {"buffer", "offset", 0}; - PyObject *input; - Py_ssize_t offset = 0; - Py_buffer vbuf; - PyObject *result; - PyStructObject *soself = (PyStructObject *)self; - - assert(PyStruct_Check(self)); - assert(soself->s_codes != NULL); - - if (!PyArg_ParseTupleAndKeywords(args, kwds, - "O|n:unpack_from", kwlist, - &input, &offset)) - return NULL; - if (PyObject_GetBuffer(input, &vbuf, PyBUF_SIMPLE) < 0) - return NULL; - if (offset < 0) - offset += vbuf.len; - if (offset < 0 || vbuf.len - offset < soself->s_size) { - PyErr_Format(StructError, - "unpack_from requires a buffer of at least %zd bytes", - soself->s_size); - PyBuffer_Release(&vbuf); - return NULL; - } - result = s_unpack_internal(soself, (char*)vbuf.buf + offset); - PyBuffer_Release(&vbuf); - return result; + PyObject *input; + Py_ssize_t offset = 0; + Py_buffer vbuf; + PyObject *result; + PyStructObject *soself = (PyStructObject *)self; + + assert(PyStruct_Check(self)); + assert(soself->s_codes != NULL); + + if (!PyArg_ParseTupleAndKeywords(args, kwds, + "O|n:unpack_from", kwlist, + &input, &offset)) + return NULL; + if (PyObject_GetBuffer(input, &vbuf, PyBUF_SIMPLE) < 0) + return NULL; + if (offset < 0) + offset += vbuf.len; + if (offset < 0 || vbuf.len - offset < soself->s_size) { + PyErr_Format(StructError, + "unpack_from requires a buffer of at least %zd bytes", + soself->s_size); + PyBuffer_Release(&vbuf); + return NULL; + } + result = s_unpack_internal(soself, (char*)vbuf.buf + offset); + PyBuffer_Release(&vbuf); + return result; } @@ -1471,85 +1471,85 @@ static int s_pack_internal(PyStructObject *soself, PyObject *args, int offset, char* buf) { - formatcode *code; - /* XXX(nnorwitz): why does i need to be a local? can we use - the offset parameter or do we need the wider width? */ - Py_ssize_t i; - - memset(buf, '\0', soself->s_size); - i = offset; - for (code = soself->s_codes; code->fmtdef != NULL; code++) { - Py_ssize_t n; - PyObject *v = PyTuple_GET_ITEM(args, i++); - const formatdef *e = code->fmtdef; - char *res = buf + code->offset; - if (e->format == 's') { - int isstring; - void *p; - if (PyUnicode_Check(v)) { - v = _PyUnicode_AsDefaultEncodedString(v, NULL); - if (v == NULL) - return -1; - } - isstring = PyBytes_Check(v); - if (!isstring && !PyByteArray_Check(v)) { - PyErr_SetString(StructError, - "argument for 's' must be a bytes or string"); - return -1; - } - if (isstring) { - n = PyBytes_GET_SIZE(v); - p = PyBytes_AS_STRING(v); - } - else { - n = PyByteArray_GET_SIZE(v); - p = PyByteArray_AS_STRING(v); - } - if (n > code->size) - n = code->size; - if (n > 0) - memcpy(res, p, n); - } else if (e->format == 'p') { - int isstring; - void *p; - if (PyUnicode_Check(v)) { - v = _PyUnicode_AsDefaultEncodedString(v, NULL); - if (v == NULL) - return -1; - } - isstring = PyBytes_Check(v); - if (!isstring && !PyByteArray_Check(v)) { - PyErr_SetString(StructError, - "argument for 'p' must be a bytes or string"); - return -1; - } - if (isstring) { - n = PyBytes_GET_SIZE(v); - p = PyBytes_AS_STRING(v); - } - else { - n = PyByteArray_GET_SIZE(v); - p = PyByteArray_AS_STRING(v); - } - if (n > (code->size - 1)) - n = code->size - 1; - if (n > 0) - memcpy(res + 1, p, n); - if (n > 255) - n = 255; - *res = Py_SAFE_DOWNCAST(n, Py_ssize_t, unsigned char); - } else { - if (e->pack(res, v, e) < 0) { - if (PyLong_Check(v) && PyErr_ExceptionMatches(PyExc_OverflowError)) - PyErr_SetString(StructError, - "long too large to convert to int"); - return -1; - } - } - } + formatcode *code; + /* XXX(nnorwitz): why does i need to be a local? can we use + the offset parameter or do we need the wider width? */ + Py_ssize_t i; + + memset(buf, '\0', soself->s_size); + i = offset; + for (code = soself->s_codes; code->fmtdef != NULL; code++) { + Py_ssize_t n; + PyObject *v = PyTuple_GET_ITEM(args, i++); + const formatdef *e = code->fmtdef; + char *res = buf + code->offset; + if (e->format == 's') { + int isstring; + void *p; + if (PyUnicode_Check(v)) { + v = _PyUnicode_AsDefaultEncodedString(v, NULL); + if (v == NULL) + return -1; + } + isstring = PyBytes_Check(v); + if (!isstring && !PyByteArray_Check(v)) { + PyErr_SetString(StructError, + "argument for 's' must be a bytes or string"); + return -1; + } + if (isstring) { + n = PyBytes_GET_SIZE(v); + p = PyBytes_AS_STRING(v); + } + else { + n = PyByteArray_GET_SIZE(v); + p = PyByteArray_AS_STRING(v); + } + if (n > code->size) + n = code->size; + if (n > 0) + memcpy(res, p, n); + } else if (e->format == 'p') { + int isstring; + void *p; + if (PyUnicode_Check(v)) { + v = _PyUnicode_AsDefaultEncodedString(v, NULL); + if (v == NULL) + return -1; + } + isstring = PyBytes_Check(v); + if (!isstring && !PyByteArray_Check(v)) { + PyErr_SetString(StructError, + "argument for 'p' must be a bytes or string"); + return -1; + } + if (isstring) { + n = PyBytes_GET_SIZE(v); + p = PyBytes_AS_STRING(v); + } + else { + n = PyByteArray_GET_SIZE(v); + p = PyByteArray_AS_STRING(v); + } + if (n > (code->size - 1)) + n = code->size - 1; + if (n > 0) + memcpy(res + 1, p, n); + if (n > 255) + n = 255; + *res = Py_SAFE_DOWNCAST(n, Py_ssize_t, unsigned char); + } else { + if (e->pack(res, v, e) < 0) { + if (PyLong_Check(v) && PyErr_ExceptionMatches(PyExc_OverflowError)) + PyErr_SetString(StructError, + "long too large to convert to int"); + return -1; + } + } + } - /* Success */ - return 0; + /* Success */ + return 0; } @@ -1562,32 +1562,32 @@ static PyObject * s_pack(PyObject *self, PyObject *args) { - PyStructObject *soself; - PyObject *result; + PyStructObject *soself; + PyObject *result; - /* Validate arguments. */ - soself = (PyStructObject *)self; - assert(PyStruct_Check(self)); - assert(soself->s_codes != NULL); - if (PyTuple_GET_SIZE(args) != soself->s_len) - { - PyErr_Format(StructError, - "pack requires exactly %zd arguments", soself->s_len); - return NULL; - } - - /* Allocate a new string */ - result = PyBytes_FromStringAndSize((char *)NULL, soself->s_size); - if (result == NULL) - return NULL; - - /* Call the guts */ - if ( s_pack_internal(soself, args, 0, PyBytes_AS_STRING(result)) != 0 ) { - Py_DECREF(result); - return NULL; - } + /* Validate arguments. */ + soself = (PyStructObject *)self; + assert(PyStruct_Check(self)); + assert(soself->s_codes != NULL); + if (PyTuple_GET_SIZE(args) != soself->s_len) + { + PyErr_Format(StructError, + "pack requires exactly %zd arguments", soself->s_len); + return NULL; + } + + /* Allocate a new string */ + result = PyBytes_FromStringAndSize((char *)NULL, soself->s_size); + if (result == NULL) + return NULL; + + /* Call the guts */ + if ( s_pack_internal(soself, args, 0, PyBytes_AS_STRING(result)) != 0 ) { + Py_DECREF(result); + return NULL; + } - return result; + return result; } PyDoc_STRVAR(s_pack_into__doc__, @@ -1601,59 +1601,59 @@ static PyObject * s_pack_into(PyObject *self, PyObject *args) { - PyStructObject *soself; - char *buffer; - Py_ssize_t buffer_len, offset; - - /* Validate arguments. +1 is for the first arg as buffer. */ - soself = (PyStructObject *)self; - assert(PyStruct_Check(self)); - assert(soself->s_codes != NULL); - if (PyTuple_GET_SIZE(args) != (soself->s_len + 2)) - { - PyErr_Format(StructError, - "pack_into requires exactly %zd arguments", - (soself->s_len + 2)); - return NULL; - } - - /* Extract a writable memory buffer from the first argument */ - if ( PyObject_AsWriteBuffer(PyTuple_GET_ITEM(args, 0), - (void**)&buffer, &buffer_len) == -1 ) { - return NULL; - } - assert( buffer_len >= 0 ); - - /* Extract the offset from the first argument */ - offset = PyNumber_AsSsize_t(PyTuple_GET_ITEM(args, 1), PyExc_IndexError); - if (offset == -1 && PyErr_Occurred()) - return NULL; - - /* Support negative offsets. */ - if (offset < 0) - offset += buffer_len; - - /* Check boundaries */ - if (offset < 0 || (buffer_len - offset) < soself->s_size) { - PyErr_Format(StructError, - "pack_into requires a buffer of at least %zd bytes", - soself->s_size); - return NULL; - } - - /* Call the guts */ - if ( s_pack_internal(soself, args, 2, buffer + offset) != 0 ) { - return NULL; - } + PyStructObject *soself; + char *buffer; + Py_ssize_t buffer_len, offset; + + /* Validate arguments. +1 is for the first arg as buffer. */ + soself = (PyStructObject *)self; + assert(PyStruct_Check(self)); + assert(soself->s_codes != NULL); + if (PyTuple_GET_SIZE(args) != (soself->s_len + 2)) + { + PyErr_Format(StructError, + "pack_into requires exactly %zd arguments", + (soself->s_len + 2)); + return NULL; + } + + /* Extract a writable memory buffer from the first argument */ + if ( PyObject_AsWriteBuffer(PyTuple_GET_ITEM(args, 0), + (void**)&buffer, &buffer_len) == -1 ) { + return NULL; + } + assert( buffer_len >= 0 ); + + /* Extract the offset from the first argument */ + offset = PyNumber_AsSsize_t(PyTuple_GET_ITEM(args, 1), PyExc_IndexError); + if (offset == -1 && PyErr_Occurred()) + return NULL; + + /* Support negative offsets. */ + if (offset < 0) + offset += buffer_len; + + /* Check boundaries */ + if (offset < 0 || (buffer_len - offset) < soself->s_size) { + PyErr_Format(StructError, + "pack_into requires a buffer of at least %zd bytes", + soself->s_size); + return NULL; + } + + /* Call the guts */ + if ( s_pack_internal(soself, args, 2, buffer + offset) != 0 ) { + return NULL; + } - Py_RETURN_NONE; + Py_RETURN_NONE; } static PyObject * s_get_format(PyStructObject *self, void *unused) { - Py_INCREF(self->s_format); - return self->s_format; + Py_INCREF(self->s_format); + return self->s_format; } static PyObject * @@ -1665,12 +1665,12 @@ /* List of functions */ static struct PyMethodDef s_methods[] = { - {"pack", s_pack, METH_VARARGS, s_pack__doc__}, - {"pack_into", s_pack_into, METH_VARARGS, s_pack_into__doc__}, - {"unpack", s_unpack, METH_O, s_unpack__doc__}, - {"unpack_from", (PyCFunction)s_unpack_from, METH_VARARGS|METH_KEYWORDS, - s_unpack_from__doc__}, - {NULL, NULL} /* sentinel */ + {"pack", s_pack, METH_VARARGS, s_pack__doc__}, + {"pack_into", s_pack_into, METH_VARARGS, s_pack_into__doc__}, + {"unpack", s_unpack, METH_O, s_unpack__doc__}, + {"unpack_from", (PyCFunction)s_unpack_from, METH_VARARGS|METH_KEYWORDS, + s_unpack_from__doc__}, + {NULL, NULL} /* sentinel */ }; PyDoc_STRVAR(s__doc__, "Compiled struct object"); @@ -1678,52 +1678,52 @@ #define OFF(x) offsetof(PyStructObject, x) static PyGetSetDef s_getsetlist[] = { - {"format", (getter)s_get_format, (setter)NULL, "struct format string", NULL}, - {"size", (getter)s_get_size, (setter)NULL, "struct size in bytes", NULL}, - {NULL} /* sentinel */ + {"format", (getter)s_get_format, (setter)NULL, "struct format string", NULL}, + {"size", (getter)s_get_size, (setter)NULL, "struct size in bytes", NULL}, + {NULL} /* sentinel */ }; static PyTypeObject PyStructType = { - PyVarObject_HEAD_INIT(NULL, 0) - "Struct", - sizeof(PyStructObject), - 0, - (destructor)s_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 */ - PyObject_GenericSetAttr, /* tp_setattro */ - 0, /* tp_as_buffer */ - Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */ - s__doc__, /* tp_doc */ - 0, /* tp_traverse */ - 0, /* tp_clear */ - 0, /* tp_richcompare */ - offsetof(PyStructObject, weakreflist), /* tp_weaklistoffset */ - 0, /* tp_iter */ - 0, /* tp_iternext */ - s_methods, /* tp_methods */ - NULL, /* tp_members */ - s_getsetlist, /* tp_getset */ - 0, /* tp_base */ - 0, /* tp_dict */ - 0, /* tp_descr_get */ - 0, /* tp_descr_set */ - 0, /* tp_dictoffset */ - s_init, /* tp_init */ - PyType_GenericAlloc,/* tp_alloc */ - s_new, /* tp_new */ - PyObject_Del, /* tp_free */ + PyVarObject_HEAD_INIT(NULL, 0) + "Struct", + sizeof(PyStructObject), + 0, + (destructor)s_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 */ + PyObject_GenericSetAttr, /* tp_setattro */ + 0, /* tp_as_buffer */ + Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */ + s__doc__, /* tp_doc */ + 0, /* tp_traverse */ + 0, /* tp_clear */ + 0, /* tp_richcompare */ + offsetof(PyStructObject, weakreflist), /* tp_weaklistoffset */ + 0, /* tp_iter */ + 0, /* tp_iternext */ + s_methods, /* tp_methods */ + NULL, /* tp_members */ + s_getsetlist, /* tp_getset */ + 0, /* tp_base */ + 0, /* tp_dict */ + 0, /* tp_descr_get */ + 0, /* tp_descr_set */ + 0, /* tp_dictoffset */ + s_init, /* tp_init */ + PyType_GenericAlloc,/* tp_alloc */ + s_new, /* tp_new */ + PyObject_Del, /* tp_free */ }; @@ -1735,29 +1735,29 @@ static PyObject * cache_struct(PyObject *fmt) { - PyObject * s_object; + PyObject * s_object; - if (cache == NULL) { - cache = PyDict_New(); - if (cache == NULL) - return NULL; - } - - s_object = PyDict_GetItem(cache, fmt); - if (s_object != NULL) { - Py_INCREF(s_object); - return s_object; - } - - s_object = PyObject_CallFunctionObjArgs((PyObject *)(&PyStructType), fmt, NULL); - if (s_object != NULL) { - if (PyDict_Size(cache) >= MAXCACHE) - PyDict_Clear(cache); - /* Attempt to cache the result */ - if (PyDict_SetItem(cache, fmt, s_object) == -1) - PyErr_Clear(); - } - return s_object; + if (cache == NULL) { + cache = PyDict_New(); + if (cache == NULL) + return NULL; + } + + s_object = PyDict_GetItem(cache, fmt); + if (s_object != NULL) { + Py_INCREF(s_object); + return s_object; + } + + s_object = PyObject_CallFunctionObjArgs((PyObject *)(&PyStructType), fmt, NULL); + if (s_object != NULL) { + if (PyDict_Size(cache) >= MAXCACHE) + PyDict_Clear(cache); + /* Attempt to cache the result */ + if (PyDict_SetItem(cache, fmt, s_object) == -1) + PyErr_Clear(); + } + return s_object; } PyDoc_STRVAR(clearcache_doc, @@ -1766,8 +1766,8 @@ static PyObject * clearcache(PyObject *self) { - Py_CLEAR(cache); - Py_RETURN_NONE; + Py_CLEAR(cache); + Py_RETURN_NONE; } PyDoc_STRVAR(calcsize_doc, @@ -1776,13 +1776,13 @@ static PyObject * calcsize(PyObject *self, PyObject *fmt) { - Py_ssize_t n; - PyObject *s_object = cache_struct(fmt); - if (s_object == NULL) - return NULL; - n = ((PyStructObject *)s_object)->s_size; - Py_DECREF(s_object); - return PyLong_FromSsize_t(n); + Py_ssize_t n; + PyObject *s_object = cache_struct(fmt); + if (s_object == NULL) + return NULL; + n = ((PyStructObject *)s_object)->s_size; + Py_DECREF(s_object); + return PyLong_FromSsize_t(n); } PyDoc_STRVAR(pack_doc, @@ -1791,27 +1791,27 @@ static PyObject * pack(PyObject *self, PyObject *args) { - PyObject *s_object, *fmt, *newargs, *result; - Py_ssize_t n = PyTuple_GET_SIZE(args); + PyObject *s_object, *fmt, *newargs, *result; + Py_ssize_t n = PyTuple_GET_SIZE(args); - if (n == 0) { - PyErr_SetString(PyExc_TypeError, "missing format argument"); - return NULL; - } - fmt = PyTuple_GET_ITEM(args, 0); - newargs = PyTuple_GetSlice(args, 1, n); - if (newargs == NULL) - return NULL; - - s_object = cache_struct(fmt); - if (s_object == NULL) { - Py_DECREF(newargs); - return NULL; - } - result = s_pack(s_object, newargs); - Py_DECREF(newargs); - Py_DECREF(s_object); - return result; + if (n == 0) { + PyErr_SetString(PyExc_TypeError, "missing format argument"); + return NULL; + } + fmt = PyTuple_GET_ITEM(args, 0); + newargs = PyTuple_GetSlice(args, 1, n); + if (newargs == NULL) + return NULL; + + s_object = cache_struct(fmt); + if (s_object == NULL) { + Py_DECREF(newargs); + return NULL; + } + result = s_pack(s_object, newargs); + Py_DECREF(newargs); + Py_DECREF(s_object); + return result; } PyDoc_STRVAR(pack_into_doc, @@ -1821,27 +1821,27 @@ static PyObject * pack_into(PyObject *self, PyObject *args) { - PyObject *s_object, *fmt, *newargs, *result; - Py_ssize_t n = PyTuple_GET_SIZE(args); + PyObject *s_object, *fmt, *newargs, *result; + Py_ssize_t n = PyTuple_GET_SIZE(args); - if (n == 0) { - PyErr_SetString(PyExc_TypeError, "missing format argument"); - return NULL; - } - fmt = PyTuple_GET_ITEM(args, 0); - newargs = PyTuple_GetSlice(args, 1, n); - if (newargs == NULL) - return NULL; - - s_object = cache_struct(fmt); - if (s_object == NULL) { - Py_DECREF(newargs); - return NULL; - } - result = s_pack_into(s_object, newargs); - Py_DECREF(newargs); - Py_DECREF(s_object); - return result; + if (n == 0) { + PyErr_SetString(PyExc_TypeError, "missing format argument"); + return NULL; + } + fmt = PyTuple_GET_ITEM(args, 0); + newargs = PyTuple_GetSlice(args, 1, n); + if (newargs == NULL) + return NULL; + + s_object = cache_struct(fmt); + if (s_object == NULL) { + Py_DECREF(newargs); + return NULL; + } + result = s_pack_into(s_object, newargs); + Py_DECREF(newargs); + Py_DECREF(s_object); + return result; } PyDoc_STRVAR(unpack_doc, @@ -1851,17 +1851,17 @@ static PyObject * unpack(PyObject *self, PyObject *args) { - PyObject *s_object, *fmt, *inputstr, *result; + PyObject *s_object, *fmt, *inputstr, *result; - if (!PyArg_UnpackTuple(args, "unpack", 2, 2, &fmt, &inputstr)) - return NULL; + if (!PyArg_UnpackTuple(args, "unpack", 2, 2, &fmt, &inputstr)) + return NULL; - s_object = cache_struct(fmt); - if (s_object == NULL) - return NULL; - result = s_unpack(s_object, inputstr); - Py_DECREF(s_object); - return result; + s_object = cache_struct(fmt); + if (s_object == NULL) + return NULL; + result = s_unpack(s_object, inputstr); + Py_DECREF(s_object); + return result; } PyDoc_STRVAR(unpack_from_doc, @@ -1871,38 +1871,38 @@ static PyObject * unpack_from(PyObject *self, PyObject *args, PyObject *kwds) { - PyObject *s_object, *fmt, *newargs, *result; - Py_ssize_t n = PyTuple_GET_SIZE(args); + PyObject *s_object, *fmt, *newargs, *result; + Py_ssize_t n = PyTuple_GET_SIZE(args); - if (n == 0) { - PyErr_SetString(PyExc_TypeError, "missing format argument"); - return NULL; - } - fmt = PyTuple_GET_ITEM(args, 0); - newargs = PyTuple_GetSlice(args, 1, n); - if (newargs == NULL) - return NULL; - - s_object = cache_struct(fmt); - if (s_object == NULL) { - Py_DECREF(newargs); - return NULL; - } - result = s_unpack_from(s_object, newargs, kwds); - Py_DECREF(newargs); - Py_DECREF(s_object); - return result; + if (n == 0) { + PyErr_SetString(PyExc_TypeError, "missing format argument"); + return NULL; + } + fmt = PyTuple_GET_ITEM(args, 0); + newargs = PyTuple_GetSlice(args, 1, n); + if (newargs == NULL) + return NULL; + + s_object = cache_struct(fmt); + if (s_object == NULL) { + Py_DECREF(newargs); + return NULL; + } + result = s_unpack_from(s_object, newargs, kwds); + Py_DECREF(newargs); + Py_DECREF(s_object); + return result; } static struct PyMethodDef module_functions[] = { - {"_clearcache", (PyCFunction)clearcache, METH_NOARGS, clearcache_doc}, - {"calcsize", calcsize, METH_O, calcsize_doc}, - {"pack", pack, METH_VARARGS, pack_doc}, - {"pack_into", pack_into, METH_VARARGS, pack_into_doc}, - {"unpack", unpack, METH_VARARGS, unpack_doc}, - {"unpack_from", (PyCFunction)unpack_from, - METH_VARARGS|METH_KEYWORDS, unpack_from_doc}, - {NULL, NULL} /* sentinel */ + {"_clearcache", (PyCFunction)clearcache, METH_NOARGS, clearcache_doc}, + {"calcsize", calcsize, METH_O, calcsize_doc}, + {"pack", pack, METH_VARARGS, pack_doc}, + {"pack_into", pack_into, METH_VARARGS, pack_into_doc}, + {"unpack", unpack, METH_VARARGS, unpack_doc}, + {"unpack_from", (PyCFunction)unpack_from, + METH_VARARGS|METH_KEYWORDS, unpack_from_doc}, + {NULL, NULL} /* sentinel */ }; @@ -1939,87 +1939,87 @@ static struct PyModuleDef _structmodule = { - PyModuleDef_HEAD_INIT, - "_struct", - module_doc, - -1, - module_functions, - NULL, - NULL, - NULL, - NULL + PyModuleDef_HEAD_INIT, + "_struct", + module_doc, + -1, + module_functions, + NULL, + NULL, + NULL, + NULL }; PyMODINIT_FUNC PyInit__struct(void) { - PyObject *ver, *m; + PyObject *ver, *m; - ver = PyBytes_FromString("0.3"); - if (ver == NULL) - return NULL; - - m = PyModule_Create(&_structmodule); - if (m == NULL) - return NULL; - - Py_TYPE(&PyStructType) = &PyType_Type; - if (PyType_Ready(&PyStructType) < 0) - return NULL; - - /* Check endian and swap in faster functions */ - { - int one = 1; - formatdef *native = native_table; - formatdef *other, *ptr; - if ((int)*(unsigned char*)&one) - other = lilendian_table; - else - other = bigendian_table; - /* Scan through the native table, find a matching - entry in the endian table and swap in the - native implementations whenever possible - (64-bit platforms may not have "standard" sizes) */ - while (native->format != '\0' && other->format != '\0') { - ptr = other; - while (ptr->format != '\0') { - if (ptr->format == native->format) { - /* Match faster when formats are - listed in the same order */ - if (ptr == other) - other++; - /* Only use the trick if the - size matches */ - if (ptr->size != native->size) - break; - /* Skip float and double, could be - "unknown" float format */ - if (ptr->format == 'd' || ptr->format == 'f') - break; - ptr->pack = native->pack; - ptr->unpack = native->unpack; - break; - } - ptr++; - } - native++; - } - } - - /* Add some symbolic constants to the module */ - if (StructError == NULL) { - StructError = PyErr_NewException("struct.error", NULL, NULL); - if (StructError == NULL) - return NULL; - } - - Py_INCREF(StructError); - PyModule_AddObject(m, "error", StructError); + ver = PyBytes_FromString("0.3"); + if (ver == NULL) + return NULL; + + m = PyModule_Create(&_structmodule); + if (m == NULL) + return NULL; + + Py_TYPE(&PyStructType) = &PyType_Type; + if (PyType_Ready(&PyStructType) < 0) + return NULL; + + /* Check endian and swap in faster functions */ + { + int one = 1; + formatdef *native = native_table; + formatdef *other, *ptr; + if ((int)*(unsigned char*)&one) + other = lilendian_table; + else + other = bigendian_table; + /* Scan through the native table, find a matching + entry in the endian table and swap in the + native implementations whenever possible + (64-bit platforms may not have "standard" sizes) */ + while (native->format != '\0' && other->format != '\0') { + ptr = other; + while (ptr->format != '\0') { + if (ptr->format == native->format) { + /* Match faster when formats are + listed in the same order */ + if (ptr == other) + other++; + /* Only use the trick if the + size matches */ + if (ptr->size != native->size) + break; + /* Skip float and double, could be + "unknown" float format */ + if (ptr->format == 'd' || ptr->format == 'f') + break; + ptr->pack = native->pack; + ptr->unpack = native->unpack; + break; + } + ptr++; + } + native++; + } + } + + /* Add some symbolic constants to the module */ + if (StructError == NULL) { + StructError = PyErr_NewException("struct.error", NULL, NULL); + if (StructError == NULL) + return NULL; + } + + Py_INCREF(StructError); + PyModule_AddObject(m, "error", StructError); - Py_INCREF((PyObject*)&PyStructType); - PyModule_AddObject(m, "Struct", (PyObject*)&PyStructType); + Py_INCREF((PyObject*)&PyStructType); + PyModule_AddObject(m, "Struct", (PyObject*)&PyStructType); - PyModule_AddObject(m, "__version__", ver); + PyModule_AddObject(m, "__version__", ver); - return m; + return m; } Modified: python/branches/py3k-jit/Modules/_testcapimodule.c ============================================================================== --- python/branches/py3k-jit/Modules/_testcapimodule.c (original) +++ python/branches/py3k-jit/Modules/_testcapimodule.c Mon May 10 23:55:43 2010 @@ -14,22 +14,22 @@ #ifdef WITH_THREAD #include "pythread.h" #endif /* WITH_THREAD */ -static PyObject *TestError; /* set to exception object in init */ +static PyObject *TestError; /* set to exception object in init */ /* Raise TestError with test_name + ": " + msg, and return NULL. */ static PyObject * raiseTestError(const char* test_name, const char* msg) { - char buf[2048]; + char buf[2048]; - if (strlen(test_name) + strlen(msg) > sizeof(buf) - 50) - PyErr_SetString(TestError, "internal error msg too large"); - else { - PyOS_snprintf(buf, sizeof(buf), "%s: %s", test_name, msg); - PyErr_SetString(TestError, buf); - } - return NULL; + if (strlen(test_name) + strlen(msg) > sizeof(buf) - 50) + PyErr_SetString(TestError, "internal error msg too large"); + else { + PyOS_snprintf(buf, sizeof(buf), "%s: %s", test_name, msg); + PyErr_SetString(TestError, buf); + } + return NULL; } /* Test #defines from pyconfig.h (particularly the SIZEOF_* defines). @@ -40,36 +40,36 @@ */ static PyObject* sizeof_error(const char* fatname, const char* typname, - int expected, int got) + int expected, int got) { - char buf[1024]; - PyOS_snprintf(buf, sizeof(buf), - "%.200s #define == %d but sizeof(%.200s) == %d", - fatname, expected, typname, got); - PyErr_SetString(TestError, buf); - return (PyObject*)NULL; + char buf[1024]; + PyOS_snprintf(buf, sizeof(buf), + "%.200s #define == %d but sizeof(%.200s) == %d", + fatname, expected, typname, got); + PyErr_SetString(TestError, buf); + return (PyObject*)NULL; } static PyObject* test_config(PyObject *self) { #define CHECK_SIZEOF(FATNAME, TYPE) \ - if (FATNAME != sizeof(TYPE)) \ - return sizeof_error(#FATNAME, #TYPE, FATNAME, sizeof(TYPE)) + if (FATNAME != sizeof(TYPE)) \ + return sizeof_error(#FATNAME, #TYPE, FATNAME, sizeof(TYPE)) - CHECK_SIZEOF(SIZEOF_SHORT, short); - CHECK_SIZEOF(SIZEOF_INT, int); - CHECK_SIZEOF(SIZEOF_LONG, long); - CHECK_SIZEOF(SIZEOF_VOID_P, void*); - CHECK_SIZEOF(SIZEOF_TIME_T, time_t); + CHECK_SIZEOF(SIZEOF_SHORT, short); + CHECK_SIZEOF(SIZEOF_INT, int); + CHECK_SIZEOF(SIZEOF_LONG, long); + CHECK_SIZEOF(SIZEOF_VOID_P, void*); + CHECK_SIZEOF(SIZEOF_TIME_T, time_t); #ifdef HAVE_LONG_LONG - CHECK_SIZEOF(SIZEOF_LONG_LONG, PY_LONG_LONG); + CHECK_SIZEOF(SIZEOF_LONG_LONG, PY_LONG_LONG); #endif #undef CHECK_SIZEOF - Py_INCREF(Py_None); - return Py_None; + Py_INCREF(Py_None); + return Py_None; } @@ -77,107 +77,107 @@ * PyType_Ready if it hasn't already been called */ static PyTypeObject _HashInheritanceTester_Type = { - PyVarObject_HEAD_INIT(NULL, 0) - "hashinheritancetester", /* Name of this type */ - sizeof(PyObject), /* Basic object size */ - 0, /* Item size for varobject */ - (destructor)PyObject_Del, /* 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, /* tp_flags */ - 0, /* tp_doc */ - 0, /* tp_traverse */ - 0, /* tp_clear */ - 0, /* tp_richcompare */ - 0, /* tp_weaklistoffset */ - 0, /* tp_iter */ - 0, /* tp_iternext */ - 0, /* tp_methods */ - 0, /* tp_members */ - 0, /* tp_getset */ - 0, /* tp_base */ - 0, /* tp_dict */ - 0, /* tp_descr_get */ - 0, /* tp_descr_set */ - 0, /* tp_dictoffset */ - 0, /* tp_init */ - 0, /* tp_alloc */ - PyType_GenericNew, /* tp_new */ + PyVarObject_HEAD_INIT(NULL, 0) + "hashinheritancetester", /* Name of this type */ + sizeof(PyObject), /* Basic object size */ + 0, /* Item size for varobject */ + (destructor)PyObject_Del, /* 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, /* tp_flags */ + 0, /* tp_doc */ + 0, /* tp_traverse */ + 0, /* tp_clear */ + 0, /* tp_richcompare */ + 0, /* tp_weaklistoffset */ + 0, /* tp_iter */ + 0, /* tp_iternext */ + 0, /* tp_methods */ + 0, /* tp_members */ + 0, /* tp_getset */ + 0, /* tp_base */ + 0, /* tp_dict */ + 0, /* tp_descr_get */ + 0, /* tp_descr_set */ + 0, /* tp_dictoffset */ + 0, /* tp_init */ + 0, /* tp_alloc */ + PyType_GenericNew, /* tp_new */ }; static PyObject* test_lazy_hash_inheritance(PyObject* self) { - PyTypeObject *type; - PyObject *obj; - long hash; - - type = &_HashInheritanceTester_Type; - - if (type->tp_dict != NULL) - /* The type has already been initialized. This probably means - -R is being used. */ - Py_RETURN_NONE; - - - obj = PyObject_New(PyObject, type); - if (obj == NULL) { - PyErr_Clear(); - PyErr_SetString( - TestError, - "test_lazy_hash_inheritance: failed to create object"); - return NULL; - } - - if (type->tp_dict != NULL) { - PyErr_SetString( - TestError, - "test_lazy_hash_inheritance: type initialised too soon"); - Py_DECREF(obj); - return NULL; - } - - hash = PyObject_Hash(obj); - if ((hash == -1) && PyErr_Occurred()) { - PyErr_Clear(); - PyErr_SetString( - TestError, - "test_lazy_hash_inheritance: could not hash object"); - Py_DECREF(obj); - return NULL; - } - - if (type->tp_dict == NULL) { - PyErr_SetString( - TestError, - "test_lazy_hash_inheritance: type not initialised by hash()"); - Py_DECREF(obj); - return NULL; - } - - if (type->tp_hash != PyType_Type.tp_hash) { - PyErr_SetString( - TestError, - "test_lazy_hash_inheritance: unexpected hash function"); - Py_DECREF(obj); - return NULL; - } + PyTypeObject *type; + PyObject *obj; + long hash; + + type = &_HashInheritanceTester_Type; + + if (type->tp_dict != NULL) + /* The type has already been initialized. This probably means + -R is being used. */ + Py_RETURN_NONE; + + + obj = PyObject_New(PyObject, type); + if (obj == NULL) { + PyErr_Clear(); + PyErr_SetString( + TestError, + "test_lazy_hash_inheritance: failed to create object"); + return NULL; + } + + if (type->tp_dict != NULL) { + PyErr_SetString( + TestError, + "test_lazy_hash_inheritance: type initialised too soon"); + Py_DECREF(obj); + return NULL; + } + + hash = PyObject_Hash(obj); + if ((hash == -1) && PyErr_Occurred()) { + PyErr_Clear(); + PyErr_SetString( + TestError, + "test_lazy_hash_inheritance: could not hash object"); + Py_DECREF(obj); + return NULL; + } + + if (type->tp_dict == NULL) { + PyErr_SetString( + TestError, + "test_lazy_hash_inheritance: type not initialised by hash()"); + Py_DECREF(obj); + return NULL; + } + + if (type->tp_hash != PyType_Type.tp_hash) { + PyErr_SetString( + TestError, + "test_lazy_hash_inheritance: unexpected hash function"); + Py_DECREF(obj); + return NULL; + } - Py_DECREF(obj); + Py_DECREF(obj); - Py_RETURN_NONE; + Py_RETURN_NONE; } @@ -188,85 +188,85 @@ static int broken_buffer_getbuffer(PyObject *self, Py_buffer *view, int flags) { - PyErr_SetString( - TestError, - "test_broken_memoryview: expected error in bf_getbuffer"); - return -1; + PyErr_SetString( + TestError, + "test_broken_memoryview: expected error in bf_getbuffer"); + return -1; } static PyBufferProcs memoryviewtester_as_buffer = { - (getbufferproc)broken_buffer_getbuffer, /* bf_getbuffer */ - 0, /* bf_releasebuffer */ + (getbufferproc)broken_buffer_getbuffer, /* bf_getbuffer */ + 0, /* bf_releasebuffer */ }; static PyTypeObject _MemoryViewTester_Type = { - PyVarObject_HEAD_INIT(NULL, 0) - "memoryviewtester", /* Name of this type */ - sizeof(PyObject), /* Basic object size */ - 0, /* Item size for varobject */ - (destructor)PyObject_Del, /* tp_dealloc */ - 0, /* tp_print */ - 0, /* tp_getattr */ - 0, /* tp_setattr */ - 0, /* tp_compare */ - 0, /* tp_repr */ - 0, /* tp_as_number */ - 0, /* tp_as_sequence */ - 0, /* tp_as_mapping */ - 0, /* tp_hash */ - 0, /* tp_call */ - 0, /* tp_str */ - PyObject_GenericGetAttr, /* tp_getattro */ - 0, /* tp_setattro */ - &memoryviewtester_as_buffer, /* tp_as_buffer */ - Py_TPFLAGS_DEFAULT, /* tp_flags */ - 0, /* tp_doc */ - 0, /* tp_traverse */ - 0, /* tp_clear */ - 0, /* tp_richcompare */ - 0, /* tp_weaklistoffset */ - 0, /* tp_iter */ - 0, /* tp_iternext */ - 0, /* tp_methods */ - 0, /* tp_members */ - 0, /* tp_getset */ - 0, /* tp_base */ - 0, /* tp_dict */ - 0, /* tp_descr_get */ - 0, /* tp_descr_set */ - 0, /* tp_dictoffset */ - 0, /* tp_init */ - 0, /* tp_alloc */ - PyType_GenericNew, /* tp_new */ + PyVarObject_HEAD_INIT(NULL, 0) + "memoryviewtester", /* Name of this type */ + sizeof(PyObject), /* Basic object size */ + 0, /* Item size for varobject */ + (destructor)PyObject_Del, /* tp_dealloc */ + 0, /* tp_print */ + 0, /* tp_getattr */ + 0, /* tp_setattr */ + 0, /* tp_compare */ + 0, /* tp_repr */ + 0, /* tp_as_number */ + 0, /* tp_as_sequence */ + 0, /* tp_as_mapping */ + 0, /* tp_hash */ + 0, /* tp_call */ + 0, /* tp_str */ + PyObject_GenericGetAttr, /* tp_getattro */ + 0, /* tp_setattro */ + &memoryviewtester_as_buffer, /* tp_as_buffer */ + Py_TPFLAGS_DEFAULT, /* tp_flags */ + 0, /* tp_doc */ + 0, /* tp_traverse */ + 0, /* tp_clear */ + 0, /* tp_richcompare */ + 0, /* tp_weaklistoffset */ + 0, /* tp_iter */ + 0, /* tp_iternext */ + 0, /* tp_methods */ + 0, /* tp_members */ + 0, /* tp_getset */ + 0, /* tp_base */ + 0, /* tp_dict */ + 0, /* tp_descr_get */ + 0, /* tp_descr_set */ + 0, /* tp_dictoffset */ + 0, /* tp_init */ + 0, /* tp_alloc */ + PyType_GenericNew, /* tp_new */ }; static PyObject* test_broken_memoryview(PyObject* self) { - PyObject *obj = PyObject_New(PyObject, &_MemoryViewTester_Type); - PyObject *res; + PyObject *obj = PyObject_New(PyObject, &_MemoryViewTester_Type); + PyObject *res; - if (obj == NULL) { - PyErr_Clear(); - PyErr_SetString( - TestError, - "test_broken_memoryview: failed to create object"); - return NULL; - } - - res = PyMemoryView_FromObject(obj); - if (res || !PyErr_Occurred()){ - PyErr_SetString( - TestError, - "test_broken_memoryview: memoryview() didn't raise an Exception"); - Py_XDECREF(res); - Py_DECREF(obj); - return NULL; - } - - PyErr_Clear(); - Py_DECREF(obj); - Py_RETURN_NONE; + if (obj == NULL) { + PyErr_Clear(); + PyErr_SetString( + TestError, + "test_broken_memoryview: failed to create object"); + return NULL; + } + + res = PyMemoryView_FromObject(obj); + if (res || !PyErr_Occurred()){ + PyErr_SetString( + TestError, + "test_broken_memoryview: memoryview() didn't raise an Exception"); + Py_XDECREF(res); + Py_DECREF(obj); + return NULL; + } + + PyErr_Clear(); + Py_DECREF(obj); + Py_RETURN_NONE; } @@ -290,22 +290,22 @@ static PyObject * raise_test_long_error(const char* msg) { - return raiseTestError("test_long_api", msg); + return raiseTestError("test_long_api", msg); } -#define TESTNAME test_long_api_inner -#define TYPENAME long -#define F_S_TO_PY PyLong_FromLong -#define F_PY_TO_S PyLong_AsLong -#define F_U_TO_PY PyLong_FromUnsignedLong -#define F_PY_TO_U PyLong_AsUnsignedLong +#define TESTNAME test_long_api_inner +#define TYPENAME long +#define F_S_TO_PY PyLong_FromLong +#define F_PY_TO_S PyLong_AsLong +#define F_U_TO_PY PyLong_FromUnsignedLong +#define F_PY_TO_U PyLong_AsUnsignedLong #include "testcapi_long.h" static PyObject * test_long_api(PyObject* self) { - return TESTNAME(raise_test_long_error); + return TESTNAME(raise_test_long_error); } #undef TESTNAME @@ -320,22 +320,22 @@ static PyObject * raise_test_longlong_error(const char* msg) { - return raiseTestError("test_longlong_api", msg); + return raiseTestError("test_longlong_api", msg); } -#define TESTNAME test_longlong_api_inner -#define TYPENAME PY_LONG_LONG -#define F_S_TO_PY PyLong_FromLongLong -#define F_PY_TO_S PyLong_AsLongLong -#define F_U_TO_PY PyLong_FromUnsignedLongLong -#define F_PY_TO_U PyLong_AsUnsignedLongLong +#define TESTNAME test_longlong_api_inner +#define TYPENAME PY_LONG_LONG +#define F_S_TO_PY PyLong_FromLongLong +#define F_PY_TO_S PyLong_AsLongLong +#define F_U_TO_PY PyLong_FromUnsignedLongLong +#define F_PY_TO_U PyLong_AsUnsignedLongLong #include "testcapi_long.h" static PyObject * test_longlong_api(PyObject* self, PyObject *args) { - return TESTNAME(raise_test_longlong_error); + return TESTNAME(raise_test_longlong_error); } #undef TESTNAME @@ -353,161 +353,161 @@ static PyObject * test_long_and_overflow(PyObject *self) { - PyObject *num, *one, *temp; - long value; - int overflow; - - /* Test that overflow is set properly for a large value. */ - /* num is a number larger than LONG_MAX even on 64-bit platforms */ - num = PyLong_FromString("FFFFFFFFFFFFFFFFFFFFFFFF", NULL, 16); - if (num == NULL) - return NULL; - overflow = 1234; - value = PyLong_AsLongAndOverflow(num, &overflow); - Py_DECREF(num); - if (value == -1 && PyErr_Occurred()) - return NULL; - if (value != -1) - return raiseTestError("test_long_and_overflow", - "return value was not set to -1"); - if (overflow != 1) - return raiseTestError("test_long_and_overflow", - "overflow was not set to 1"); - - /* Same again, with num = LONG_MAX + 1 */ - num = PyLong_FromLong(LONG_MAX); - if (num == NULL) - return NULL; - one = PyLong_FromLong(1L); - if (one == NULL) { - Py_DECREF(num); - return NULL; - } - temp = PyNumber_Add(num, one); - Py_DECREF(one); - Py_DECREF(num); - num = temp; - if (num == NULL) - return NULL; - overflow = 0; - value = PyLong_AsLongAndOverflow(num, &overflow); - Py_DECREF(num); - if (value == -1 && PyErr_Occurred()) - return NULL; - if (value != -1) - return raiseTestError("test_long_and_overflow", - "return value was not set to -1"); - if (overflow != 1) - return raiseTestError("test_long_and_overflow", - "overflow was not set to 1"); - - /* Test that overflow is set properly for a large negative value. */ - /* num is a number smaller than LONG_MIN even on 64-bit platforms */ - num = PyLong_FromString("-FFFFFFFFFFFFFFFFFFFFFFFF", NULL, 16); - if (num == NULL) - return NULL; - overflow = 1234; - value = PyLong_AsLongAndOverflow(num, &overflow); - Py_DECREF(num); - if (value == -1 && PyErr_Occurred()) - return NULL; - if (value != -1) - return raiseTestError("test_long_and_overflow", - "return value was not set to -1"); - if (overflow != -1) - return raiseTestError("test_long_and_overflow", - "overflow was not set to -1"); - - /* Same again, with num = LONG_MIN - 1 */ - num = PyLong_FromLong(LONG_MIN); - if (num == NULL) - return NULL; - one = PyLong_FromLong(1L); - if (one == NULL) { - Py_DECREF(num); - return NULL; - } - temp = PyNumber_Subtract(num, one); - Py_DECREF(one); - Py_DECREF(num); - num = temp; - if (num == NULL) - return NULL; - overflow = 0; - value = PyLong_AsLongAndOverflow(num, &overflow); - Py_DECREF(num); - if (value == -1 && PyErr_Occurred()) - return NULL; - if (value != -1) - return raiseTestError("test_long_and_overflow", - "return value was not set to -1"); - if (overflow != -1) - return raiseTestError("test_long_and_overflow", - "overflow was not set to -1"); - - /* Test that overflow is cleared properly for small values. */ - num = PyLong_FromString("FF", NULL, 16); - if (num == NULL) - return NULL; - overflow = 1234; - value = PyLong_AsLongAndOverflow(num, &overflow); - Py_DECREF(num); - if (value == -1 && PyErr_Occurred()) - return NULL; - if (value != 0xFF) - return raiseTestError("test_long_and_overflow", - "expected return value 0xFF"); - if (overflow != 0) - return raiseTestError("test_long_and_overflow", - "overflow was not cleared"); - - num = PyLong_FromString("-FF", NULL, 16); - if (num == NULL) - return NULL; - overflow = 0; - value = PyLong_AsLongAndOverflow(num, &overflow); - Py_DECREF(num); - if (value == -1 && PyErr_Occurred()) - return NULL; - if (value != -0xFF) - return raiseTestError("test_long_and_overflow", - "expected return value 0xFF"); - if (overflow != 0) - return raiseTestError("test_long_and_overflow", - "overflow was set incorrectly"); - - num = PyLong_FromLong(LONG_MAX); - if (num == NULL) - return NULL; - overflow = 1234; - value = PyLong_AsLongAndOverflow(num, &overflow); - Py_DECREF(num); - if (value == -1 && PyErr_Occurred()) - return NULL; - if (value != LONG_MAX) - return raiseTestError("test_long_and_overflow", - "expected return value LONG_MAX"); - if (overflow != 0) - return raiseTestError("test_long_and_overflow", - "overflow was not cleared"); - - num = PyLong_FromLong(LONG_MIN); - if (num == NULL) - return NULL; - overflow = 0; - value = PyLong_AsLongAndOverflow(num, &overflow); - Py_DECREF(num); - if (value == -1 && PyErr_Occurred()) - return NULL; - if (value != LONG_MIN) - return raiseTestError("test_long_and_overflow", - "expected return value LONG_MIN"); - if (overflow != 0) - return raiseTestError("test_long_and_overflow", - "overflow was not cleared"); + PyObject *num, *one, *temp; + long value; + int overflow; + + /* Test that overflow is set properly for a large value. */ + /* num is a number larger than LONG_MAX even on 64-bit platforms */ + num = PyLong_FromString("FFFFFFFFFFFFFFFFFFFFFFFF", NULL, 16); + if (num == NULL) + return NULL; + overflow = 1234; + value = PyLong_AsLongAndOverflow(num, &overflow); + Py_DECREF(num); + if (value == -1 && PyErr_Occurred()) + return NULL; + if (value != -1) + return raiseTestError("test_long_and_overflow", + "return value was not set to -1"); + if (overflow != 1) + return raiseTestError("test_long_and_overflow", + "overflow was not set to 1"); + + /* Same again, with num = LONG_MAX + 1 */ + num = PyLong_FromLong(LONG_MAX); + if (num == NULL) + return NULL; + one = PyLong_FromLong(1L); + if (one == NULL) { + Py_DECREF(num); + return NULL; + } + temp = PyNumber_Add(num, one); + Py_DECREF(one); + Py_DECREF(num); + num = temp; + if (num == NULL) + return NULL; + overflow = 0; + value = PyLong_AsLongAndOverflow(num, &overflow); + Py_DECREF(num); + if (value == -1 && PyErr_Occurred()) + return NULL; + if (value != -1) + return raiseTestError("test_long_and_overflow", + "return value was not set to -1"); + if (overflow != 1) + return raiseTestError("test_long_and_overflow", + "overflow was not set to 1"); + + /* Test that overflow is set properly for a large negative value. */ + /* num is a number smaller than LONG_MIN even on 64-bit platforms */ + num = PyLong_FromString("-FFFFFFFFFFFFFFFFFFFFFFFF", NULL, 16); + if (num == NULL) + return NULL; + overflow = 1234; + value = PyLong_AsLongAndOverflow(num, &overflow); + Py_DECREF(num); + if (value == -1 && PyErr_Occurred()) + return NULL; + if (value != -1) + return raiseTestError("test_long_and_overflow", + "return value was not set to -1"); + if (overflow != -1) + return raiseTestError("test_long_and_overflow", + "overflow was not set to -1"); + + /* Same again, with num = LONG_MIN - 1 */ + num = PyLong_FromLong(LONG_MIN); + if (num == NULL) + return NULL; + one = PyLong_FromLong(1L); + if (one == NULL) { + Py_DECREF(num); + return NULL; + } + temp = PyNumber_Subtract(num, one); + Py_DECREF(one); + Py_DECREF(num); + num = temp; + if (num == NULL) + return NULL; + overflow = 0; + value = PyLong_AsLongAndOverflow(num, &overflow); + Py_DECREF(num); + if (value == -1 && PyErr_Occurred()) + return NULL; + if (value != -1) + return raiseTestError("test_long_and_overflow", + "return value was not set to -1"); + if (overflow != -1) + return raiseTestError("test_long_and_overflow", + "overflow was not set to -1"); + + /* Test that overflow is cleared properly for small values. */ + num = PyLong_FromString("FF", NULL, 16); + if (num == NULL) + return NULL; + overflow = 1234; + value = PyLong_AsLongAndOverflow(num, &overflow); + Py_DECREF(num); + if (value == -1 && PyErr_Occurred()) + return NULL; + if (value != 0xFF) + return raiseTestError("test_long_and_overflow", + "expected return value 0xFF"); + if (overflow != 0) + return raiseTestError("test_long_and_overflow", + "overflow was not cleared"); + + num = PyLong_FromString("-FF", NULL, 16); + if (num == NULL) + return NULL; + overflow = 0; + value = PyLong_AsLongAndOverflow(num, &overflow); + Py_DECREF(num); + if (value == -1 && PyErr_Occurred()) + return NULL; + if (value != -0xFF) + return raiseTestError("test_long_and_overflow", + "expected return value 0xFF"); + if (overflow != 0) + return raiseTestError("test_long_and_overflow", + "overflow was set incorrectly"); + + num = PyLong_FromLong(LONG_MAX); + if (num == NULL) + return NULL; + overflow = 1234; + value = PyLong_AsLongAndOverflow(num, &overflow); + Py_DECREF(num); + if (value == -1 && PyErr_Occurred()) + return NULL; + if (value != LONG_MAX) + return raiseTestError("test_long_and_overflow", + "expected return value LONG_MAX"); + if (overflow != 0) + return raiseTestError("test_long_and_overflow", + "overflow was not cleared"); + + num = PyLong_FromLong(LONG_MIN); + if (num == NULL) + return NULL; + overflow = 0; + value = PyLong_AsLongAndOverflow(num, &overflow); + Py_DECREF(num); + if (value == -1 && PyErr_Occurred()) + return NULL; + if (value != LONG_MIN) + return raiseTestError("test_long_and_overflow", + "expected return value LONG_MIN"); + if (overflow != 0) + return raiseTestError("test_long_and_overflow", + "overflow was not cleared"); - Py_INCREF(Py_None); - return Py_None; + Py_INCREF(Py_None); + return Py_None; } /* Test the PyLong_AsLongLongAndOverflow API. General conversion to @@ -518,189 +518,189 @@ static PyObject * test_long_long_and_overflow(PyObject *self) { - PyObject *num, *one, *temp; - PY_LONG_LONG value; - int overflow; - - /* Test that overflow is set properly for a large value. */ - /* num is a number larger than PY_LLONG_MAX on a typical machine. */ - num = PyLong_FromString("FFFFFFFFFFFFFFFFFFFFFFFF", NULL, 16); - if (num == NULL) - return NULL; - overflow = 1234; - value = PyLong_AsLongLongAndOverflow(num, &overflow); - Py_DECREF(num); - if (value == -1 && PyErr_Occurred()) - return NULL; - if (value != -1) - return raiseTestError("test_long_long_and_overflow", - "return value was not set to -1"); - if (overflow != 1) - return raiseTestError("test_long_long_and_overflow", - "overflow was not set to 1"); - - /* Same again, with num = PY_LLONG_MAX + 1 */ - num = PyLong_FromLongLong(PY_LLONG_MAX); - if (num == NULL) - return NULL; - one = PyLong_FromLong(1L); - if (one == NULL) { - Py_DECREF(num); - return NULL; - } - temp = PyNumber_Add(num, one); - Py_DECREF(one); - Py_DECREF(num); - num = temp; - if (num == NULL) - return NULL; - overflow = 0; - value = PyLong_AsLongLongAndOverflow(num, &overflow); - Py_DECREF(num); - if (value == -1 && PyErr_Occurred()) - return NULL; - if (value != -1) - return raiseTestError("test_long_long_and_overflow", - "return value was not set to -1"); - if (overflow != 1) - return raiseTestError("test_long_long_and_overflow", - "overflow was not set to 1"); - - /* Test that overflow is set properly for a large negative value. */ - /* num is a number smaller than PY_LLONG_MIN on a typical platform */ - num = PyLong_FromString("-FFFFFFFFFFFFFFFFFFFFFFFF", NULL, 16); - if (num == NULL) - return NULL; - overflow = 1234; - value = PyLong_AsLongLongAndOverflow(num, &overflow); - Py_DECREF(num); - if (value == -1 && PyErr_Occurred()) - return NULL; - if (value != -1) - return raiseTestError("test_long_long_and_overflow", - "return value was not set to -1"); - if (overflow != -1) - return raiseTestError("test_long_long_and_overflow", - "overflow was not set to -1"); - - /* Same again, with num = PY_LLONG_MIN - 1 */ - num = PyLong_FromLongLong(PY_LLONG_MIN); - if (num == NULL) - return NULL; - one = PyLong_FromLong(1L); - if (one == NULL) { - Py_DECREF(num); - return NULL; - } - temp = PyNumber_Subtract(num, one); - Py_DECREF(one); - Py_DECREF(num); - num = temp; - if (num == NULL) - return NULL; - overflow = 0; - value = PyLong_AsLongLongAndOverflow(num, &overflow); - Py_DECREF(num); - if (value == -1 && PyErr_Occurred()) - return NULL; - if (value != -1) - return raiseTestError("test_long_long_and_overflow", - "return value was not set to -1"); - if (overflow != -1) - return raiseTestError("test_long_long_and_overflow", - "overflow was not set to -1"); - - /* Test that overflow is cleared properly for small values. */ - num = PyLong_FromString("FF", NULL, 16); - if (num == NULL) - return NULL; - overflow = 1234; - value = PyLong_AsLongLongAndOverflow(num, &overflow); - Py_DECREF(num); - if (value == -1 && PyErr_Occurred()) - return NULL; - if (value != 0xFF) - return raiseTestError("test_long_long_and_overflow", - "expected return value 0xFF"); - if (overflow != 0) - return raiseTestError("test_long_long_and_overflow", - "overflow was not cleared"); - - num = PyLong_FromString("-FF", NULL, 16); - if (num == NULL) - return NULL; - overflow = 0; - value = PyLong_AsLongLongAndOverflow(num, &overflow); - Py_DECREF(num); - if (value == -1 && PyErr_Occurred()) - return NULL; - if (value != -0xFF) - return raiseTestError("test_long_long_and_overflow", - "expected return value 0xFF"); - if (overflow != 0) - return raiseTestError("test_long_long_and_overflow", - "overflow was set incorrectly"); - - num = PyLong_FromLongLong(PY_LLONG_MAX); - if (num == NULL) - return NULL; - overflow = 1234; - value = PyLong_AsLongLongAndOverflow(num, &overflow); - Py_DECREF(num); - if (value == -1 && PyErr_Occurred()) - return NULL; - if (value != PY_LLONG_MAX) - return raiseTestError("test_long_long_and_overflow", - "expected return value PY_LLONG_MAX"); - if (overflow != 0) - return raiseTestError("test_long_long_and_overflow", - "overflow was not cleared"); - - num = PyLong_FromLongLong(PY_LLONG_MIN); - if (num == NULL) - return NULL; - overflow = 0; - value = PyLong_AsLongLongAndOverflow(num, &overflow); - Py_DECREF(num); - if (value == -1 && PyErr_Occurred()) - return NULL; - if (value != PY_LLONG_MIN) - return raiseTestError("test_long_long_and_overflow", - "expected return value PY_LLONG_MIN"); - if (overflow != 0) - return raiseTestError("test_long_long_and_overflow", - "overflow was not cleared"); + PyObject *num, *one, *temp; + PY_LONG_LONG value; + int overflow; + + /* Test that overflow is set properly for a large value. */ + /* num is a number larger than PY_LLONG_MAX on a typical machine. */ + num = PyLong_FromString("FFFFFFFFFFFFFFFFFFFFFFFF", NULL, 16); + if (num == NULL) + return NULL; + overflow = 1234; + value = PyLong_AsLongLongAndOverflow(num, &overflow); + Py_DECREF(num); + if (value == -1 && PyErr_Occurred()) + return NULL; + if (value != -1) + return raiseTestError("test_long_long_and_overflow", + "return value was not set to -1"); + if (overflow != 1) + return raiseTestError("test_long_long_and_overflow", + "overflow was not set to 1"); + + /* Same again, with num = PY_LLONG_MAX + 1 */ + num = PyLong_FromLongLong(PY_LLONG_MAX); + if (num == NULL) + return NULL; + one = PyLong_FromLong(1L); + if (one == NULL) { + Py_DECREF(num); + return NULL; + } + temp = PyNumber_Add(num, one); + Py_DECREF(one); + Py_DECREF(num); + num = temp; + if (num == NULL) + return NULL; + overflow = 0; + value = PyLong_AsLongLongAndOverflow(num, &overflow); + Py_DECREF(num); + if (value == -1 && PyErr_Occurred()) + return NULL; + if (value != -1) + return raiseTestError("test_long_long_and_overflow", + "return value was not set to -1"); + if (overflow != 1) + return raiseTestError("test_long_long_and_overflow", + "overflow was not set to 1"); + + /* Test that overflow is set properly for a large negative value. */ + /* num is a number smaller than PY_LLONG_MIN on a typical platform */ + num = PyLong_FromString("-FFFFFFFFFFFFFFFFFFFFFFFF", NULL, 16); + if (num == NULL) + return NULL; + overflow = 1234; + value = PyLong_AsLongLongAndOverflow(num, &overflow); + Py_DECREF(num); + if (value == -1 && PyErr_Occurred()) + return NULL; + if (value != -1) + return raiseTestError("test_long_long_and_overflow", + "return value was not set to -1"); + if (overflow != -1) + return raiseTestError("test_long_long_and_overflow", + "overflow was not set to -1"); + + /* Same again, with num = PY_LLONG_MIN - 1 */ + num = PyLong_FromLongLong(PY_LLONG_MIN); + if (num == NULL) + return NULL; + one = PyLong_FromLong(1L); + if (one == NULL) { + Py_DECREF(num); + return NULL; + } + temp = PyNumber_Subtract(num, one); + Py_DECREF(one); + Py_DECREF(num); + num = temp; + if (num == NULL) + return NULL; + overflow = 0; + value = PyLong_AsLongLongAndOverflow(num, &overflow); + Py_DECREF(num); + if (value == -1 && PyErr_Occurred()) + return NULL; + if (value != -1) + return raiseTestError("test_long_long_and_overflow", + "return value was not set to -1"); + if (overflow != -1) + return raiseTestError("test_long_long_and_overflow", + "overflow was not set to -1"); + + /* Test that overflow is cleared properly for small values. */ + num = PyLong_FromString("FF", NULL, 16); + if (num == NULL) + return NULL; + overflow = 1234; + value = PyLong_AsLongLongAndOverflow(num, &overflow); + Py_DECREF(num); + if (value == -1 && PyErr_Occurred()) + return NULL; + if (value != 0xFF) + return raiseTestError("test_long_long_and_overflow", + "expected return value 0xFF"); + if (overflow != 0) + return raiseTestError("test_long_long_and_overflow", + "overflow was not cleared"); + + num = PyLong_FromString("-FF", NULL, 16); + if (num == NULL) + return NULL; + overflow = 0; + value = PyLong_AsLongLongAndOverflow(num, &overflow); + Py_DECREF(num); + if (value == -1 && PyErr_Occurred()) + return NULL; + if (value != -0xFF) + return raiseTestError("test_long_long_and_overflow", + "expected return value 0xFF"); + if (overflow != 0) + return raiseTestError("test_long_long_and_overflow", + "overflow was set incorrectly"); + + num = PyLong_FromLongLong(PY_LLONG_MAX); + if (num == NULL) + return NULL; + overflow = 1234; + value = PyLong_AsLongLongAndOverflow(num, &overflow); + Py_DECREF(num); + if (value == -1 && PyErr_Occurred()) + return NULL; + if (value != PY_LLONG_MAX) + return raiseTestError("test_long_long_and_overflow", + "expected return value PY_LLONG_MAX"); + if (overflow != 0) + return raiseTestError("test_long_long_and_overflow", + "overflow was not cleared"); + + num = PyLong_FromLongLong(PY_LLONG_MIN); + if (num == NULL) + return NULL; + overflow = 0; + value = PyLong_AsLongLongAndOverflow(num, &overflow); + Py_DECREF(num); + if (value == -1 && PyErr_Occurred()) + return NULL; + if (value != PY_LLONG_MIN) + return raiseTestError("test_long_long_and_overflow", + "expected return value PY_LLONG_MIN"); + if (overflow != 0) + return raiseTestError("test_long_long_and_overflow", + "overflow was not cleared"); - Py_INCREF(Py_None); - return Py_None; + Py_INCREF(Py_None); + return Py_None; } -#endif /* ifdef HAVE_LONG_LONG */ +#endif /* ifdef HAVE_LONG_LONG */ /* Test tuple argument processing */ static PyObject * getargs_tuple(PyObject *self, PyObject *args) { - int a, b, c; - if (!PyArg_ParseTuple(args, "i(ii)", &a, &b, &c)) - return NULL; - return Py_BuildValue("iii", a, b, c); + int a, b, c; + if (!PyArg_ParseTuple(args, "i(ii)", &a, &b, &c)) + return NULL; + return Py_BuildValue("iii", a, b, c); } /* test PyArg_ParseTupleAndKeywords */ static PyObject *getargs_keywords(PyObject *self, PyObject *args, PyObject *kwargs) { - static char *keywords[] = {"arg1","arg2","arg3","arg4","arg5", NULL}; - static char *fmt="(ii)i|(i(ii))(iii)i"; - int int_args[10]={-1, -1, -1, -1, -1, -1, -1, -1, -1, -1}; - - if (!PyArg_ParseTupleAndKeywords(args, kwargs, fmt, keywords, - &int_args[0], &int_args[1], &int_args[2], &int_args[3], &int_args[4], - &int_args[5], &int_args[6], &int_args[7], &int_args[8], &int_args[9])) - return NULL; - return Py_BuildValue("iiiiiiiiii", - int_args[0], int_args[1], int_args[2], int_args[3], int_args[4], - int_args[5], int_args[6], int_args[7], int_args[8], int_args[9]); + static char *keywords[] = {"arg1","arg2","arg3","arg4","arg5", NULL}; + static char *fmt="(ii)i|(i(ii))(iii)i"; + int int_args[10]={-1, -1, -1, -1, -1, -1, -1, -1, -1, -1}; + + if (!PyArg_ParseTupleAndKeywords(args, kwargs, fmt, keywords, + &int_args[0], &int_args[1], &int_args[2], &int_args[3], &int_args[4], + &int_args[5], &int_args[6], &int_args[7], &int_args[8], &int_args[9])) + return NULL; + return Py_BuildValue("iiiiiiiiii", + int_args[0], int_args[1], int_args[2], int_args[3], int_args[4], + int_args[5], int_args[6], int_args[7], int_args[8], int_args[9]); } /* Functions to call PyArg_ParseTuple with integer format codes, @@ -709,101 +709,101 @@ static PyObject * getargs_b(PyObject *self, PyObject *args) { - unsigned char value; - if (!PyArg_ParseTuple(args, "b", &value)) - return NULL; - return PyLong_FromUnsignedLong((unsigned long)value); + unsigned char value; + if (!PyArg_ParseTuple(args, "b", &value)) + return NULL; + return PyLong_FromUnsignedLong((unsigned long)value); } static PyObject * getargs_B(PyObject *self, PyObject *args) { - unsigned char value; - if (!PyArg_ParseTuple(args, "B", &value)) - return NULL; - return PyLong_FromUnsignedLong((unsigned long)value); + unsigned char value; + if (!PyArg_ParseTuple(args, "B", &value)) + return NULL; + return PyLong_FromUnsignedLong((unsigned long)value); } static PyObject * getargs_h(PyObject *self, PyObject *args) { - short value; - if (!PyArg_ParseTuple(args, "h", &value)) - return NULL; - return PyLong_FromLong((long)value); + short value; + if (!PyArg_ParseTuple(args, "h", &value)) + return NULL; + return PyLong_FromLong((long)value); } static PyObject * getargs_H(PyObject *self, PyObject *args) { - unsigned short value; - if (!PyArg_ParseTuple(args, "H", &value)) - return NULL; - return PyLong_FromUnsignedLong((unsigned long)value); + unsigned short value; + if (!PyArg_ParseTuple(args, "H", &value)) + return NULL; + return PyLong_FromUnsignedLong((unsigned long)value); } static PyObject * getargs_I(PyObject *self, PyObject *args) { - unsigned int value; - if (!PyArg_ParseTuple(args, "I", &value)) - return NULL; - return PyLong_FromUnsignedLong((unsigned long)value); + unsigned int value; + if (!PyArg_ParseTuple(args, "I", &value)) + return NULL; + return PyLong_FromUnsignedLong((unsigned long)value); } static PyObject * getargs_k(PyObject *self, PyObject *args) { - unsigned long value; - if (!PyArg_ParseTuple(args, "k", &value)) - return NULL; - return PyLong_FromUnsignedLong(value); + unsigned long value; + if (!PyArg_ParseTuple(args, "k", &value)) + return NULL; + return PyLong_FromUnsignedLong(value); } static PyObject * getargs_i(PyObject *self, PyObject *args) { - int value; - if (!PyArg_ParseTuple(args, "i", &value)) - return NULL; - return PyLong_FromLong((long)value); + int value; + if (!PyArg_ParseTuple(args, "i", &value)) + return NULL; + return PyLong_FromLong((long)value); } static PyObject * getargs_l(PyObject *self, PyObject *args) { - long value; - if (!PyArg_ParseTuple(args, "l", &value)) - return NULL; - return PyLong_FromLong(value); + long value; + if (!PyArg_ParseTuple(args, "l", &value)) + return NULL; + return PyLong_FromLong(value); } static PyObject * getargs_n(PyObject *self, PyObject *args) { - Py_ssize_t value; - if (!PyArg_ParseTuple(args, "n", &value)) - return NULL; - return PyLong_FromSsize_t(value); + Py_ssize_t value; + if (!PyArg_ParseTuple(args, "n", &value)) + return NULL; + return PyLong_FromSsize_t(value); } #ifdef HAVE_LONG_LONG static PyObject * getargs_L(PyObject *self, PyObject *args) { - PY_LONG_LONG value; - if (!PyArg_ParseTuple(args, "L", &value)) - return NULL; - return PyLong_FromLongLong(value); + PY_LONG_LONG value; + if (!PyArg_ParseTuple(args, "L", &value)) + return NULL; + return PyLong_FromLongLong(value); } static PyObject * getargs_K(PyObject *self, PyObject *args) { - unsigned PY_LONG_LONG value; - if (!PyArg_ParseTuple(args, "K", &value)) - return NULL; - return PyLong_FromUnsignedLongLong(value); + unsigned PY_LONG_LONG value; + if (!PyArg_ParseTuple(args, "K", &value)) + return NULL; + return PyLong_FromUnsignedLongLong(value); } #endif @@ -811,117 +811,117 @@ static PyObject * test_Z_code(PyObject *self) { - PyObject *tuple, *obj; - Py_UNICODE *value1, *value2; - Py_ssize_t len1, len2; - - tuple = PyTuple_New(2); - if (tuple == NULL) - return NULL; - - obj = PyUnicode_FromString("test"); - PyTuple_SET_ITEM(tuple, 0, obj); - Py_INCREF(Py_None); - PyTuple_SET_ITEM(tuple, 1, Py_None); - - /* swap values on purpose */ - value1 = NULL; - value2 = PyUnicode_AS_UNICODE(obj); - - /* Test Z for both values */ - if (PyArg_ParseTuple(tuple, "ZZ:test_Z_code", &value1, &value2) < 0) - return NULL; - if (value1 != PyUnicode_AS_UNICODE(obj)) - return raiseTestError("test_Z_code", - "Z code returned wrong value for 'test'"); - if (value2 != NULL) - return raiseTestError("test_Z_code", - "Z code returned wrong value for None"); - - value1 = NULL; - value2 = PyUnicode_AS_UNICODE(obj); - len1 = -1; - len2 = -1; - - /* Test Z# for both values */ - if (PyArg_ParseTuple(tuple, "Z#Z#:test_Z_code", &value1, &len1, - &value2, &len2) < 0) - return NULL; - if (value1 != PyUnicode_AS_UNICODE(obj) || - len1 != PyUnicode_GET_SIZE(obj)) - return raiseTestError("test_Z_code", - "Z# code returned wrong values for 'test'"); - if (value2 != NULL || - len2 != 0) - return raiseTestError("test_Z_code", - "Z# code returned wrong values for None'"); + PyObject *tuple, *obj; + Py_UNICODE *value1, *value2; + Py_ssize_t len1, len2; + + tuple = PyTuple_New(2); + if (tuple == NULL) + return NULL; + + obj = PyUnicode_FromString("test"); + PyTuple_SET_ITEM(tuple, 0, obj); + Py_INCREF(Py_None); + PyTuple_SET_ITEM(tuple, 1, Py_None); + + /* swap values on purpose */ + value1 = NULL; + value2 = PyUnicode_AS_UNICODE(obj); + + /* Test Z for both values */ + if (PyArg_ParseTuple(tuple, "ZZ:test_Z_code", &value1, &value2) < 0) + return NULL; + if (value1 != PyUnicode_AS_UNICODE(obj)) + return raiseTestError("test_Z_code", + "Z code returned wrong value for 'test'"); + if (value2 != NULL) + return raiseTestError("test_Z_code", + "Z code returned wrong value for None"); + + value1 = NULL; + value2 = PyUnicode_AS_UNICODE(obj); + len1 = -1; + len2 = -1; + + /* Test Z# for both values */ + if (PyArg_ParseTuple(tuple, "Z#Z#:test_Z_code", &value1, &len1, + &value2, &len2) < 0) + return NULL; + if (value1 != PyUnicode_AS_UNICODE(obj) || + len1 != PyUnicode_GET_SIZE(obj)) + return raiseTestError("test_Z_code", + "Z# code returned wrong values for 'test'"); + if (value2 != NULL || + len2 != 0) + return raiseTestError("test_Z_code", + "Z# code returned wrong values for None'"); - Py_DECREF(tuple); - Py_RETURN_NONE; + Py_DECREF(tuple); + Py_RETURN_NONE; } static PyObject * test_widechar(PyObject *self) { #if defined(SIZEOF_WCHAR_T) && (SIZEOF_WCHAR_T == 4) - const wchar_t wtext[2] = {(wchar_t)0x10ABCDu}; - size_t wtextlen = 1; + const wchar_t wtext[2] = {(wchar_t)0x10ABCDu}; + size_t wtextlen = 1; #else - const wchar_t wtext[3] = {(wchar_t)0xDBEAu, (wchar_t)0xDFCDu}; - size_t wtextlen = 2; + const wchar_t wtext[3] = {(wchar_t)0xDBEAu, (wchar_t)0xDFCDu}; + size_t wtextlen = 2; #endif - PyObject *wide, *utf8; + PyObject *wide, *utf8; - wide = PyUnicode_FromWideChar(wtext, wtextlen); - if (wide == NULL) - return NULL; - - utf8 = PyUnicode_FromString("\xf4\x8a\xaf\x8d"); - if (utf8 == NULL) { - Py_DECREF(wide); - return NULL; - } - - if (PyUnicode_GET_SIZE(wide) != PyUnicode_GET_SIZE(utf8)) { - Py_DECREF(wide); - Py_DECREF(utf8); - return raiseTestError("test_widechar", - "wide string and utf8 string " - "have different length"); - } - if (PyUnicode_Compare(wide, utf8)) { - Py_DECREF(wide); - Py_DECREF(utf8); - if (PyErr_Occurred()) - return NULL; - return raiseTestError("test_widechar", - "wide string and utf8 string " - "are different"); - } - - Py_DECREF(wide); - Py_DECREF(utf8); - Py_RETURN_NONE; + wide = PyUnicode_FromWideChar(wtext, wtextlen); + if (wide == NULL) + return NULL; + + utf8 = PyUnicode_FromString("\xf4\x8a\xaf\x8d"); + if (utf8 == NULL) { + Py_DECREF(wide); + return NULL; + } + + if (PyUnicode_GET_SIZE(wide) != PyUnicode_GET_SIZE(utf8)) { + Py_DECREF(wide); + Py_DECREF(utf8); + return raiseTestError("test_widechar", + "wide string and utf8 string " + "have different length"); + } + if (PyUnicode_Compare(wide, utf8)) { + Py_DECREF(wide); + Py_DECREF(utf8); + if (PyErr_Occurred()) + return NULL; + return raiseTestError("test_widechar", + "wide string and utf8 string " + "are different"); + } + + Py_DECREF(wide); + Py_DECREF(utf8); + Py_RETURN_NONE; } static PyObject * codec_incrementalencoder(PyObject *self, PyObject *args) { - const char *encoding, *errors = NULL; - if (!PyArg_ParseTuple(args, "s|s:test_incrementalencoder", - &encoding, &errors)) - return NULL; - return PyCodec_IncrementalEncoder(encoding, errors); + const char *encoding, *errors = NULL; + if (!PyArg_ParseTuple(args, "s|s:test_incrementalencoder", + &encoding, &errors)) + return NULL; + return PyCodec_IncrementalEncoder(encoding, errors); } static PyObject * codec_incrementaldecoder(PyObject *self, PyObject *args) { - const char *encoding, *errors = NULL; - if (!PyArg_ParseTuple(args, "s|s:test_incrementaldecoder", - &encoding, &errors)) - return NULL; - return PyCodec_IncrementalDecoder(encoding, errors); + const char *encoding, *errors = NULL; + if (!PyArg_ParseTuple(args, "s|s:test_incrementaldecoder", + &encoding, &errors)) + return NULL; + return PyCodec_IncrementalDecoder(encoding, errors); } @@ -929,69 +929,69 @@ static PyObject * test_long_numbits(PyObject *self) { - struct triple { - long input; - size_t nbits; - int sign; - } testcases[] = {{0, 0, 0}, - {1L, 1, 1}, - {-1L, 1, -1}, - {2L, 2, 1}, - {-2L, 2, -1}, - {3L, 2, 1}, - {-3L, 2, -1}, - {4L, 3, 1}, - {-4L, 3, -1}, - {0x7fffL, 15, 1}, /* one Python long digit */ - {-0x7fffL, 15, -1}, - {0xffffL, 16, 1}, - {-0xffffL, 16, -1}, - {0xfffffffL, 28, 1}, - {-0xfffffffL, 28, -1}}; - int i; - - for (i = 0; i < sizeof(testcases) / sizeof(struct triple); ++i) { - PyObject *plong = PyLong_FromLong(testcases[i].input); - size_t nbits = _PyLong_NumBits(plong); - int sign = _PyLong_Sign(plong); - - Py_DECREF(plong); - if (nbits != testcases[i].nbits) - return raiseTestError("test_long_numbits", - "wrong result for _PyLong_NumBits"); - if (sign != testcases[i].sign) - return raiseTestError("test_long_numbits", - "wrong result for _PyLong_Sign"); - } - Py_INCREF(Py_None); - return Py_None; + struct triple { + long input; + size_t nbits; + int sign; + } testcases[] = {{0, 0, 0}, + {1L, 1, 1}, + {-1L, 1, -1}, + {2L, 2, 1}, + {-2L, 2, -1}, + {3L, 2, 1}, + {-3L, 2, -1}, + {4L, 3, 1}, + {-4L, 3, -1}, + {0x7fffL, 15, 1}, /* one Python long digit */ + {-0x7fffL, 15, -1}, + {0xffffL, 16, 1}, + {-0xffffL, 16, -1}, + {0xfffffffL, 28, 1}, + {-0xfffffffL, 28, -1}}; + int i; + + for (i = 0; i < sizeof(testcases) / sizeof(struct triple); ++i) { + PyObject *plong = PyLong_FromLong(testcases[i].input); + size_t nbits = _PyLong_NumBits(plong); + int sign = _PyLong_Sign(plong); + + Py_DECREF(plong); + if (nbits != testcases[i].nbits) + return raiseTestError("test_long_numbits", + "wrong result for _PyLong_NumBits"); + if (sign != testcases[i].sign) + return raiseTestError("test_long_numbits", + "wrong result for _PyLong_Sign"); + } + Py_INCREF(Py_None); + return Py_None; } static PyObject * raise_exception(PyObject *self, PyObject *args) { - PyObject *exc; - PyObject *exc_args, *v; - int num_args, i; - - if (!PyArg_ParseTuple(args, "Oi:raise_exception", - &exc, &num_args)) - return NULL; - - exc_args = PyTuple_New(num_args); - if (exc_args == NULL) - return NULL; - for (i = 0; i < num_args; ++i) { - v = PyLong_FromLong(i); - if (v == NULL) { - Py_DECREF(exc_args); - return NULL; - } - PyTuple_SET_ITEM(exc_args, i, v); - } - PyErr_SetObject(exc, exc_args); - Py_DECREF(exc_args); - return NULL; + PyObject *exc; + PyObject *exc_args, *v; + int num_args, i; + + if (!PyArg_ParseTuple(args, "Oi:raise_exception", + &exc, &num_args)) + return NULL; + + exc_args = PyTuple_New(num_args); + if (exc_args == NULL) + return NULL; + for (i = 0; i < num_args; ++i) { + v = PyLong_FromLong(i); + if (v == NULL) { + Py_DECREF(exc_args); + return NULL; + } + PyTuple_SET_ITEM(exc_args, i, v); + } + PyErr_SetObject(exc, exc_args); + Py_DECREF(exc_args); + return NULL; } @@ -1009,14 +1009,14 @@ static int _make_call(void *callable) { - PyObject *rc; - int success; - PyGILState_STATE s = PyGILState_Ensure(); - rc = PyObject_CallFunction((PyObject *)callable, ""); - success = (rc != NULL); - Py_XDECREF(rc); - PyGILState_Release(s); - return success; + PyObject *rc; + int success; + PyGILState_STATE s = PyGILState_Ensure(); + rc = PyObject_CallFunction((PyObject *)callable, ""); + success = (rc != NULL); + Py_XDECREF(rc); + PyGILState_Release(s); + return success; } /* Same thing, but releases `thread_done` when it returns. This variant @@ -1025,70 +1025,70 @@ static void _make_call_from_thread(void *callable) { - _make_call(callable); - PyThread_release_lock(thread_done); + _make_call(callable); + PyThread_release_lock(thread_done); } static PyObject * test_thread_state(PyObject *self, PyObject *args) { - PyObject *fn; - int success = 1; + PyObject *fn; + int success = 1; - if (!PyArg_ParseTuple(args, "O:test_thread_state", &fn)) - return NULL; + if (!PyArg_ParseTuple(args, "O:test_thread_state", &fn)) + return NULL; - if (!PyCallable_Check(fn)) { - PyErr_Format(PyExc_TypeError, "'%s' object is not callable", - fn->ob_type->tp_name); - return NULL; - } - - /* Ensure Python is set up for threading */ - PyEval_InitThreads(); - thread_done = PyThread_allocate_lock(); - if (thread_done == NULL) - return PyErr_NoMemory(); - PyThread_acquire_lock(thread_done, 1); - - /* Start a new thread with our callback. */ - PyThread_start_new_thread(_make_call_from_thread, fn); - /* Make the callback with the thread lock held by this thread */ - success &= _make_call(fn); - /* Do it all again, but this time with the thread-lock released */ - Py_BEGIN_ALLOW_THREADS - success &= _make_call(fn); - PyThread_acquire_lock(thread_done, 1); /* wait for thread to finish */ - Py_END_ALLOW_THREADS - - /* And once more with and without a thread - XXX - should use a lock and work out exactly what we are trying - to test - */ - Py_BEGIN_ALLOW_THREADS - PyThread_start_new_thread(_make_call_from_thread, fn); - success &= _make_call(fn); - PyThread_acquire_lock(thread_done, 1); /* wait for thread to finish */ - Py_END_ALLOW_THREADS - - /* Release lock we acquired above. This is required on HP-UX. */ - PyThread_release_lock(thread_done); - - PyThread_free_lock(thread_done); - if (!success) - return NULL; - Py_RETURN_NONE; + if (!PyCallable_Check(fn)) { + PyErr_Format(PyExc_TypeError, "'%s' object is not callable", + fn->ob_type->tp_name); + return NULL; + } + + /* Ensure Python is set up for threading */ + PyEval_InitThreads(); + thread_done = PyThread_allocate_lock(); + if (thread_done == NULL) + return PyErr_NoMemory(); + PyThread_acquire_lock(thread_done, 1); + + /* Start a new thread with our callback. */ + PyThread_start_new_thread(_make_call_from_thread, fn); + /* Make the callback with the thread lock held by this thread */ + success &= _make_call(fn); + /* Do it all again, but this time with the thread-lock released */ + Py_BEGIN_ALLOW_THREADS + success &= _make_call(fn); + PyThread_acquire_lock(thread_done, 1); /* wait for thread to finish */ + Py_END_ALLOW_THREADS + + /* And once more with and without a thread + XXX - should use a lock and work out exactly what we are trying + to test + */ + Py_BEGIN_ALLOW_THREADS + PyThread_start_new_thread(_make_call_from_thread, fn); + success &= _make_call(fn); + PyThread_acquire_lock(thread_done, 1); /* wait for thread to finish */ + Py_END_ALLOW_THREADS + + /* Release lock we acquired above. This is required on HP-UX. */ + PyThread_release_lock(thread_done); + + PyThread_free_lock(thread_done); + if (!success) + return NULL; + Py_RETURN_NONE; } /* test Py_AddPendingCalls using threads */ static int _pending_callback(void *arg) { - /* we assume the argument is callable object to which we own a reference */ - PyObject *callable = (PyObject *)arg; - PyObject *r = PyObject_CallObject(callable, NULL); - Py_DECREF(callable); - Py_XDECREF(r); - return r != NULL ? 0 : -1; + /* we assume the argument is callable object to which we own a reference */ + PyObject *callable = (PyObject *)arg; + PyObject *r = PyObject_CallObject(callable, NULL); + Py_DECREF(callable); + Py_XDECREF(r); + return r != NULL ? 0 : -1; } /* The following requests n callbacks to _pending_callback. It can be @@ -1096,25 +1096,25 @@ */ PyObject *pending_threadfunc(PyObject *self, PyObject *arg) { - PyObject *callable; - int r; - if (PyArg_ParseTuple(arg, "O", &callable) == 0) - return NULL; - - /* create the reference for the callbackwhile we hold the lock */ - Py_INCREF(callable); - - Py_BEGIN_ALLOW_THREADS - r = Py_AddPendingCall(&_pending_callback, callable); - Py_END_ALLOW_THREADS - - if (r<0) { - Py_DECREF(callable); /* unsuccessful add, destroy the extra reference */ - Py_INCREF(Py_False); - return Py_False; - } - Py_INCREF(Py_True); - return Py_True; + PyObject *callable; + int r; + if (PyArg_ParseTuple(arg, "O", &callable) == 0) + return NULL; + + /* create the reference for the callbackwhile we hold the lock */ + Py_INCREF(callable); + + Py_BEGIN_ALLOW_THREADS + r = Py_AddPendingCall(&_pending_callback, callable); + Py_END_ALLOW_THREADS + + if (r<0) { + Py_DECREF(callable); /* unsuccessful add, destroy the extra reference */ + Py_INCREF(Py_False); + return Py_False; + } + Py_INCREF(Py_True); + return Py_True; } #endif @@ -1122,40 +1122,40 @@ static PyObject * test_string_from_format(PyObject *self, PyObject *args) { - PyObject *result; - char *msg; + PyObject *result; + char *msg; -#define CHECK_1_FORMAT(FORMAT, TYPE) \ - result = PyUnicode_FromFormat(FORMAT, (TYPE)1); \ - if (result == NULL) \ - return NULL; \ - if (strcmp(_PyUnicode_AsString(result), "1")) { \ - msg = FORMAT " failed at 1"; \ - goto Fail; \ - } \ - Py_DECREF(result) - - CHECK_1_FORMAT("%d", int); - CHECK_1_FORMAT("%ld", long); - /* The z width modifier was added in Python 2.5. */ - CHECK_1_FORMAT("%zd", Py_ssize_t); - - /* The u type code was added in Python 2.5. */ - CHECK_1_FORMAT("%u", unsigned int); - CHECK_1_FORMAT("%lu", unsigned long); - CHECK_1_FORMAT("%zu", size_t); +#define CHECK_1_FORMAT(FORMAT, TYPE) \ + result = PyUnicode_FromFormat(FORMAT, (TYPE)1); \ + if (result == NULL) \ + return NULL; \ + if (strcmp(_PyUnicode_AsString(result), "1")) { \ + msg = FORMAT " failed at 1"; \ + goto Fail; \ + } \ + Py_DECREF(result) + + CHECK_1_FORMAT("%d", int); + CHECK_1_FORMAT("%ld", long); + /* The z width modifier was added in Python 2.5. */ + CHECK_1_FORMAT("%zd", Py_ssize_t); + + /* The u type code was added in Python 2.5. */ + CHECK_1_FORMAT("%u", unsigned int); + CHECK_1_FORMAT("%lu", unsigned long); + CHECK_1_FORMAT("%zu", size_t); - /* "%lld" and "%llu" support added in Python 2.7. */ + /* "%lld" and "%llu" support added in Python 2.7. */ #ifdef HAVE_LONG_LONG - CHECK_1_FORMAT("%llu", unsigned PY_LONG_LONG); - CHECK_1_FORMAT("%lld", PY_LONG_LONG); + CHECK_1_FORMAT("%llu", unsigned PY_LONG_LONG); + CHECK_1_FORMAT("%lld", PY_LONG_LONG); #endif - Py_RETURN_NONE; + Py_RETURN_NONE; Fail: - Py_XDECREF(result); - return raiseTestError("test_string_from_format", msg); + Py_XDECREF(result); + return raiseTestError("test_string_from_format", msg); #undef CHECK_1_FORMAT } @@ -1165,52 +1165,52 @@ static PyObject * test_with_docstring(PyObject *self) { - Py_RETURN_NONE; + Py_RETURN_NONE; } /* Test PyOS_string_to_double. */ static PyObject * test_string_to_double(PyObject *self) { - double result; - char *msg; + double result; + char *msg; -#define CHECK_STRING(STR, expected) \ - result = PyOS_string_to_double(STR, NULL, NULL); \ - if (result == -1.0 && PyErr_Occurred()) \ - return NULL; \ - if (result != expected) { \ - msg = "conversion of " STR " to float failed"; \ - goto fail; \ - } - -#define CHECK_INVALID(STR) \ - result = PyOS_string_to_double(STR, NULL, NULL); \ - if (result == -1.0 && PyErr_Occurred()) { \ - if (PyErr_ExceptionMatches(PyExc_ValueError)) \ - PyErr_Clear(); \ - else \ - return NULL; \ - } \ - else { \ - msg = "conversion of " STR " didn't raise ValueError"; \ - goto fail; \ - } - - CHECK_STRING("0.1", 0.1); - CHECK_STRING("1.234", 1.234); - CHECK_STRING("-1.35", -1.35); - CHECK_STRING(".1e01", 1.0); - CHECK_STRING("2.e-2", 0.02); - - CHECK_INVALID(" 0.1"); - CHECK_INVALID("\t\n-3"); - CHECK_INVALID(".123 "); - CHECK_INVALID("3\n"); - CHECK_INVALID("123abc"); +#define CHECK_STRING(STR, expected) \ + result = PyOS_string_to_double(STR, NULL, NULL); \ + if (result == -1.0 && PyErr_Occurred()) \ + return NULL; \ + if (result != expected) { \ + msg = "conversion of " STR " to float failed"; \ + goto fail; \ + } + +#define CHECK_INVALID(STR) \ + result = PyOS_string_to_double(STR, NULL, NULL); \ + if (result == -1.0 && PyErr_Occurred()) { \ + if (PyErr_ExceptionMatches(PyExc_ValueError)) \ + PyErr_Clear(); \ + else \ + return NULL; \ + } \ + else { \ + msg = "conversion of " STR " didn't raise ValueError"; \ + goto fail; \ + } + + CHECK_STRING("0.1", 0.1); + CHECK_STRING("1.234", 1.234); + CHECK_STRING("-1.35", -1.35); + CHECK_STRING(".1e01", 1.0); + CHECK_STRING("2.e-2", 0.02); + + CHECK_INVALID(" 0.1"); + CHECK_INVALID("\t\n-3"); + CHECK_INVALID(".123 "); + CHECK_INVALID("3\n"); + CHECK_INVALID("123abc"); - Py_RETURN_NONE; + Py_RETURN_NONE; fail: - return raiseTestError("test_string_to_double", msg); + return raiseTestError("test_string_to_double", msg); #undef CHECK_STRING #undef CHECK_INVALID } @@ -1227,143 +1227,143 @@ static void capsule_destructor(PyObject *o) { - capsule_destructor_call_count++; - if (PyCapsule_GetContext(o) != capsule_context) { - capsule_error = "context did not match in destructor!"; - } else if (PyCapsule_GetDestructor(o) != capsule_destructor) { - capsule_error = "destructor did not match in destructor! (woah!)"; - } else if (PyCapsule_GetName(o) != capsule_name) { - capsule_error = "name did not match in destructor!"; - } else if (PyCapsule_GetPointer(o, capsule_name) != capsule_pointer) { - capsule_error = "pointer did not match in destructor!"; - } + capsule_destructor_call_count++; + if (PyCapsule_GetContext(o) != capsule_context) { + capsule_error = "context did not match in destructor!"; + } else if (PyCapsule_GetDestructor(o) != capsule_destructor) { + capsule_error = "destructor did not match in destructor! (woah!)"; + } else if (PyCapsule_GetName(o) != capsule_name) { + capsule_error = "name did not match in destructor!"; + } else if (PyCapsule_GetPointer(o, capsule_name) != capsule_pointer) { + capsule_error = "pointer did not match in destructor!"; + } } typedef struct { - char *name; - char *module; - char *attribute; + char *name; + char *module; + char *attribute; } known_capsule; static PyObject * test_capsule(PyObject *self, PyObject *args) { - PyObject *object; - const char *error = NULL; - void *pointer; - void *pointer2; - known_capsule known_capsules[] = { - #define KNOWN_CAPSULE(module, name) { module "." name, module, name } - KNOWN_CAPSULE("_socket", "CAPI"), - KNOWN_CAPSULE("_curses", "_C_API"), - KNOWN_CAPSULE("datetime", "datetime_CAPI"), - { NULL, NULL }, - }; - known_capsule *known = &known_capsules[0]; + PyObject *object; + const char *error = NULL; + void *pointer; + void *pointer2; + known_capsule known_capsules[] = { + #define KNOWN_CAPSULE(module, name) { module "." name, module, name } + KNOWN_CAPSULE("_socket", "CAPI"), + KNOWN_CAPSULE("_curses", "_C_API"), + KNOWN_CAPSULE("datetime", "datetime_CAPI"), + { NULL, NULL }, + }; + known_capsule *known = &known_capsules[0]; #define FAIL(x) { error = (x); goto exit; } #define CHECK_DESTRUCTOR \ - if (capsule_error) { \ - FAIL(capsule_error); \ - } \ - else if (!capsule_destructor_call_count) { \ - FAIL("destructor not called!"); \ - } \ - capsule_destructor_call_count = 0; \ - - object = PyCapsule_New(capsule_pointer, capsule_name, capsule_destructor); - PyCapsule_SetContext(object, capsule_context); - capsule_destructor(object); - CHECK_DESTRUCTOR; - Py_DECREF(object); - CHECK_DESTRUCTOR; - - object = PyCapsule_New(known, "ignored", NULL); - PyCapsule_SetPointer(object, capsule_pointer); - PyCapsule_SetName(object, capsule_name); - PyCapsule_SetDestructor(object, capsule_destructor); - PyCapsule_SetContext(object, capsule_context); - capsule_destructor(object); - CHECK_DESTRUCTOR; - /* intentionally access using the wrong name */ - pointer2 = PyCapsule_GetPointer(object, "the wrong name"); - if (!PyErr_Occurred()) { - FAIL("PyCapsule_GetPointer should have failed but did not!"); - } - PyErr_Clear(); - if (pointer2) { - if (pointer2 == capsule_pointer) { - FAIL("PyCapsule_GetPointer should not have" - " returned the internal pointer!"); - } else { - FAIL("PyCapsule_GetPointer should have " - "returned NULL pointer but did not!"); - } - } - PyCapsule_SetDestructor(object, NULL); - Py_DECREF(object); - if (capsule_destructor_call_count) { - FAIL("destructor called when it should not have been!"); - } - - for (known = &known_capsules[0]; known->module != NULL; known++) { - /* yeah, ordinarily I wouldn't do this either, - but it's fine for this test harness. - */ - static char buffer[256]; + if (capsule_error) { \ + FAIL(capsule_error); \ + } \ + else if (!capsule_destructor_call_count) { \ + FAIL("destructor not called!"); \ + } \ + capsule_destructor_call_count = 0; \ + + object = PyCapsule_New(capsule_pointer, capsule_name, capsule_destructor); + PyCapsule_SetContext(object, capsule_context); + capsule_destructor(object); + CHECK_DESTRUCTOR; + Py_DECREF(object); + CHECK_DESTRUCTOR; + + object = PyCapsule_New(known, "ignored", NULL); + PyCapsule_SetPointer(object, capsule_pointer); + PyCapsule_SetName(object, capsule_name); + PyCapsule_SetDestructor(object, capsule_destructor); + PyCapsule_SetContext(object, capsule_context); + capsule_destructor(object); + CHECK_DESTRUCTOR; + /* intentionally access using the wrong name */ + pointer2 = PyCapsule_GetPointer(object, "the wrong name"); + if (!PyErr_Occurred()) { + FAIL("PyCapsule_GetPointer should have failed but did not!"); + } + PyErr_Clear(); + if (pointer2) { + if (pointer2 == capsule_pointer) { + FAIL("PyCapsule_GetPointer should not have" + " returned the internal pointer!"); + } else { + FAIL("PyCapsule_GetPointer should have " + "returned NULL pointer but did not!"); + } + } + PyCapsule_SetDestructor(object, NULL); + Py_DECREF(object); + if (capsule_destructor_call_count) { + FAIL("destructor called when it should not have been!"); + } + + for (known = &known_capsules[0]; known->module != NULL; known++) { + /* yeah, ordinarily I wouldn't do this either, + but it's fine for this test harness. + */ + static char buffer[256]; #undef FAIL #define FAIL(x) \ - { \ - sprintf(buffer, "%s module: \"%s\" attribute: \"%s\"", \ - x, known->module, known->attribute); \ - error = buffer; \ - goto exit; \ - } \ - - PyObject *module = PyImport_ImportModule(known->module); - if (module) { - pointer = PyCapsule_Import(known->name, 0); - if (!pointer) { - Py_DECREF(module); - FAIL("PyCapsule_GetPointer returned NULL unexpectedly!"); - } - object = PyObject_GetAttrString(module, known->attribute); - if (!object) { - Py_DECREF(module); - return NULL; - } - pointer2 = PyCapsule_GetPointer(object, - "weebles wobble but they don't fall down"); - if (!PyErr_Occurred()) { - Py_DECREF(object); - Py_DECREF(module); - FAIL("PyCapsule_GetPointer should have failed but did not!"); - } - PyErr_Clear(); - if (pointer2) { - Py_DECREF(module); - Py_DECREF(object); - if (pointer2 == pointer) { - FAIL("PyCapsule_GetPointer should not have" - " returned its internal pointer!"); - } else { - FAIL("PyCapsule_GetPointer should have" - " returned NULL pointer but did not!"); - } - } - Py_DECREF(object); - Py_DECREF(module); - } - else - PyErr_Clear(); - } + { \ + sprintf(buffer, "%s module: \"%s\" attribute: \"%s\"", \ + x, known->module, known->attribute); \ + error = buffer; \ + goto exit; \ + } \ + + PyObject *module = PyImport_ImportModule(known->module); + if (module) { + pointer = PyCapsule_Import(known->name, 0); + if (!pointer) { + Py_DECREF(module); + FAIL("PyCapsule_GetPointer returned NULL unexpectedly!"); + } + object = PyObject_GetAttrString(module, known->attribute); + if (!object) { + Py_DECREF(module); + return NULL; + } + pointer2 = PyCapsule_GetPointer(object, + "weebles wobble but they don't fall down"); + if (!PyErr_Occurred()) { + Py_DECREF(object); + Py_DECREF(module); + FAIL("PyCapsule_GetPointer should have failed but did not!"); + } + PyErr_Clear(); + if (pointer2) { + Py_DECREF(module); + Py_DECREF(object); + if (pointer2 == pointer) { + FAIL("PyCapsule_GetPointer should not have" + " returned its internal pointer!"); + } else { + FAIL("PyCapsule_GetPointer should have" + " returned NULL pointer but did not!"); + } + } + Py_DECREF(object); + Py_DECREF(module); + } + else + PyErr_Clear(); + } exit: - if (error) { - return raiseTestError("test_capsule", error); - } - Py_RETURN_NONE; + if (error) { + return raiseTestError("test_capsule", error); + } + Py_RETURN_NONE; #undef FAIL } @@ -1371,112 +1371,112 @@ /* Profiling of integer performance */ static void print_delta(int test, struct timeval *s, struct timeval *e) { - e->tv_sec -= s->tv_sec; - e->tv_usec -= s->tv_usec; - if (e->tv_usec < 0) { - e->tv_sec -=1; - e->tv_usec += 1000000; - } - printf("Test %d: %d.%06ds\n", test, (int)e->tv_sec, (int)e->tv_usec); + e->tv_sec -= s->tv_sec; + e->tv_usec -= s->tv_usec; + if (e->tv_usec < 0) { + e->tv_sec -=1; + e->tv_usec += 1000000; + } + printf("Test %d: %d.%06ds\n", test, (int)e->tv_sec, (int)e->tv_usec); } static PyObject * profile_int(PyObject *self, PyObject* args) { - int i, k; - struct timeval start, stop; - PyObject *single, **multiple, *op1, *result; - - /* Test 1: Allocate and immediately deallocate - many small integers */ - gettimeofday(&start, NULL); - for(k=0; k < 20000; k++) - for(i=0; i < 1000; i++) { - single = PyLong_FromLong(i); - Py_DECREF(single); - } - gettimeofday(&stop, NULL); - print_delta(1, &start, &stop); - - /* Test 2: Allocate and immediately deallocate - many large integers */ - gettimeofday(&start, NULL); - for(k=0; k < 20000; k++) - for(i=0; i < 1000; i++) { - single = PyLong_FromLong(i+1000000); - Py_DECREF(single); - } - gettimeofday(&stop, NULL); - print_delta(2, &start, &stop); - - /* Test 3: Allocate a few integers, then release - them all simultaneously. */ - multiple = malloc(sizeof(PyObject*) * 1000); - gettimeofday(&start, NULL); - for(k=0; k < 20000; k++) { - for(i=0; i < 1000; i++) { - multiple[i] = PyLong_FromLong(i+1000000); - } - for(i=0; i < 1000; i++) { - Py_DECREF(multiple[i]); - } - } - gettimeofday(&stop, NULL); - print_delta(3, &start, &stop); - - /* Test 4: Allocate many integers, then release - them all simultaneously. */ - multiple = malloc(sizeof(PyObject*) * 1000000); - gettimeofday(&start, NULL); - for(k=0; k < 20; k++) { - for(i=0; i < 1000000; i++) { - multiple[i] = PyLong_FromLong(i+1000000); - } - for(i=0; i < 1000000; i++) { - Py_DECREF(multiple[i]); - } - } - gettimeofday(&stop, NULL); - print_delta(4, &start, &stop); - - /* Test 5: Allocate many integers < 32000 */ - multiple = malloc(sizeof(PyObject*) * 1000000); - gettimeofday(&start, NULL); - for(k=0; k < 10; k++) { - for(i=0; i < 1000000; i++) { - multiple[i] = PyLong_FromLong(i+1000); - } - for(i=0; i < 1000000; i++) { - Py_DECREF(multiple[i]); - } - } - gettimeofday(&stop, NULL); - print_delta(5, &start, &stop); - - /* Test 6: Perform small int addition */ - op1 = PyLong_FromLong(1); - gettimeofday(&start, NULL); - for(i=0; i < 10000000; i++) { - result = PyNumber_Add(op1, op1); - Py_DECREF(result); - } - gettimeofday(&stop, NULL); - Py_DECREF(op1); - print_delta(6, &start, &stop); - - /* Test 7: Perform medium int addition */ - op1 = PyLong_FromLong(1000); - gettimeofday(&start, NULL); - for(i=0; i < 10000000; i++) { - result = PyNumber_Add(op1, op1); - Py_DECREF(result); - } - gettimeofday(&stop, NULL); - Py_DECREF(op1); - print_delta(7, &start, &stop); + int i, k; + struct timeval start, stop; + PyObject *single, **multiple, *op1, *result; + + /* Test 1: Allocate and immediately deallocate + many small integers */ + gettimeofday(&start, NULL); + for(k=0; k < 20000; k++) + for(i=0; i < 1000; i++) { + single = PyLong_FromLong(i); + Py_DECREF(single); + } + gettimeofday(&stop, NULL); + print_delta(1, &start, &stop); + + /* Test 2: Allocate and immediately deallocate + many large integers */ + gettimeofday(&start, NULL); + for(k=0; k < 20000; k++) + for(i=0; i < 1000; i++) { + single = PyLong_FromLong(i+1000000); + Py_DECREF(single); + } + gettimeofday(&stop, NULL); + print_delta(2, &start, &stop); + + /* Test 3: Allocate a few integers, then release + them all simultaneously. */ + multiple = malloc(sizeof(PyObject*) * 1000); + gettimeofday(&start, NULL); + for(k=0; k < 20000; k++) { + for(i=0; i < 1000; i++) { + multiple[i] = PyLong_FromLong(i+1000000); + } + for(i=0; i < 1000; i++) { + Py_DECREF(multiple[i]); + } + } + gettimeofday(&stop, NULL); + print_delta(3, &start, &stop); + + /* Test 4: Allocate many integers, then release + them all simultaneously. */ + multiple = malloc(sizeof(PyObject*) * 1000000); + gettimeofday(&start, NULL); + for(k=0; k < 20; k++) { + for(i=0; i < 1000000; i++) { + multiple[i] = PyLong_FromLong(i+1000000); + } + for(i=0; i < 1000000; i++) { + Py_DECREF(multiple[i]); + } + } + gettimeofday(&stop, NULL); + print_delta(4, &start, &stop); + + /* Test 5: Allocate many integers < 32000 */ + multiple = malloc(sizeof(PyObject*) * 1000000); + gettimeofday(&start, NULL); + for(k=0; k < 10; k++) { + for(i=0; i < 1000000; i++) { + multiple[i] = PyLong_FromLong(i+1000); + } + for(i=0; i < 1000000; i++) { + Py_DECREF(multiple[i]); + } + } + gettimeofday(&stop, NULL); + print_delta(5, &start, &stop); + + /* Test 6: Perform small int addition */ + op1 = PyLong_FromLong(1); + gettimeofday(&start, NULL); + for(i=0; i < 10000000; i++) { + result = PyNumber_Add(op1, op1); + Py_DECREF(result); + } + gettimeofday(&stop, NULL); + Py_DECREF(op1); + print_delta(6, &start, &stop); + + /* Test 7: Perform medium int addition */ + op1 = PyLong_FromLong(1000); + gettimeofday(&start, NULL); + for(i=0; i < 10000000; i++) { + result = PyNumber_Add(op1, op1); + Py_DECREF(result); + } + gettimeofday(&stop, NULL); + Py_DECREF(op1); + print_delta(7, &start, &stop); - Py_INCREF(Py_None); - return Py_None; + Py_INCREF(Py_None); + return Py_None; } #endif @@ -1484,40 +1484,40 @@ static PyObject * traceback_print(PyObject *self, PyObject *args) { - PyObject *file; - PyObject *traceback; - int result; - - if (!PyArg_ParseTuple(args, "OO:traceback_print", - &traceback, &file)) - return NULL; - - result = PyTraceBack_Print(traceback, file); - if (result < 0) - return NULL; - Py_RETURN_NONE; + PyObject *file; + PyObject *traceback; + int result; + + if (!PyArg_ParseTuple(args, "OO:traceback_print", + &traceback, &file)) + return NULL; + + result = PyTraceBack_Print(traceback, file); + if (result < 0) + return NULL; + Py_RETURN_NONE; } /* To test the format of exceptions as printed out. */ static PyObject * exception_print(PyObject *self, PyObject *args) { - PyObject *value; - PyObject *tb; + PyObject *value; + PyObject *tb; - if (!PyArg_ParseTuple(args, "O:exception_print", - &value)) - return NULL; - if (!PyExceptionInstance_Check(value)) { - PyErr_Format(PyExc_TypeError, "an exception instance is required"); - return NULL; - } - - tb = PyException_GetTraceback(value); - PyErr_Display((PyObject *) Py_TYPE(value), value, tb); - Py_XDECREF(tb); + if (!PyArg_ParseTuple(args, "O:exception_print", + &value)) + return NULL; + if (!PyExceptionInstance_Check(value)) { + PyErr_Format(PyExc_TypeError, "an exception instance is required"); + return NULL; + } + + tb = PyException_GetTraceback(value); + PyErr_Display((PyObject *) Py_TYPE(value), value, tb); + Py_XDECREF(tb); - Py_RETURN_NONE; + Py_RETURN_NONE; } @@ -1527,8 +1527,8 @@ static PyObject * raise_memoryerror(PyObject *self) { - PyErr_NoMemory(); - return NULL; + PyErr_NoMemory(); + return NULL; } /* Issue 6012 */ @@ -1536,45 +1536,45 @@ static int failing_converter(PyObject *obj, void *arg) { - /* Clone str1, then let the conversion fail. */ - assert(str1); - str2 = str1; - Py_INCREF(str2); - return 0; + /* Clone str1, then let the conversion fail. */ + assert(str1); + str2 = str1; + Py_INCREF(str2); + return 0; } static PyObject* argparsing(PyObject *o, PyObject *args) { - PyObject *res; - str1 = str2 = NULL; - if (!PyArg_ParseTuple(args, "O&O&", - PyUnicode_FSConverter, &str1, - failing_converter, &str2)) { - if (!str2) - /* argument converter not called? */ - return NULL; - /* Should be 1 */ - res = PyLong_FromLong(Py_REFCNT(str2)); - Py_DECREF(str2); - PyErr_Clear(); - return res; - } - Py_RETURN_NONE; + PyObject *res; + str1 = str2 = NULL; + if (!PyArg_ParseTuple(args, "O&O&", + PyUnicode_FSConverter, &str1, + failing_converter, &str2)) { + if (!str2) + /* argument converter not called? */ + return NULL; + /* Should be 1 */ + res = PyLong_FromLong(Py_REFCNT(str2)); + Py_DECREF(str2); + PyErr_Clear(); + return res; + } + Py_RETURN_NONE; } /* To test that the result of PyCode_NewEmpty has the right members. */ static PyObject * code_newempty(PyObject *self, PyObject *args) { - const char *filename; - const char *funcname; - int firstlineno; - - if (!PyArg_ParseTuple(args, "ssi:code_newempty", - &filename, &funcname, &firstlineno)) - return NULL; + const char *filename; + const char *funcname; + int firstlineno; + + if (!PyArg_ParseTuple(args, "ssi:code_newempty", + &filename, &funcname, &firstlineno)) + return NULL; - return (PyObject *)PyCode_NewEmpty(filename, funcname, firstlineno); + return (PyObject *)PyCode_NewEmpty(filename, funcname, firstlineno); } /* Test PyErr_NewExceptionWithDoc (also exercise PyErr_NewException). @@ -1582,291 +1582,291 @@ static PyObject * make_exception_with_doc(PyObject *self, PyObject *args, PyObject *kwargs) { - const char *name; - const char *doc = NULL; - PyObject *base = NULL; - PyObject *dict = NULL; - - static char *kwlist[] = {"name", "doc", "base", "dict", NULL}; - - if (!PyArg_ParseTupleAndKeywords(args, kwargs, - "s|sOO:make_exception_with_doc", kwlist, - &name, &doc, &base, &dict)) - return NULL; + const char *name; + const char *doc = NULL; + PyObject *base = NULL; + PyObject *dict = NULL; + + static char *kwlist[] = {"name", "doc", "base", "dict", NULL}; + + if (!PyArg_ParseTupleAndKeywords(args, kwargs, + "s|sOO:make_exception_with_doc", kwlist, + &name, &doc, &base, &dict)) + return NULL; - return PyErr_NewExceptionWithDoc(name, doc, base, dict); + return PyErr_NewExceptionWithDoc(name, doc, base, dict); } static PyMethodDef TestMethods[] = { - {"raise_exception", raise_exception, METH_VARARGS}, - {"raise_memoryerror", (PyCFunction)raise_memoryerror, METH_NOARGS}, - {"test_config", (PyCFunction)test_config, METH_NOARGS}, - {"test_lazy_hash_inheritance", (PyCFunction)test_lazy_hash_inheritance,METH_NOARGS}, - {"test_broken_memoryview", (PyCFunction)test_broken_memoryview,METH_NOARGS}, - {"test_long_api", (PyCFunction)test_long_api, METH_NOARGS}, - {"test_long_and_overflow", (PyCFunction)test_long_and_overflow, - METH_NOARGS}, - {"test_long_numbits", (PyCFunction)test_long_numbits, METH_NOARGS}, - {"test_string_from_format", (PyCFunction)test_string_from_format, METH_NOARGS}, - {"test_with_docstring", (PyCFunction)test_with_docstring, METH_NOARGS, - PyDoc_STR("This is a pretty normal docstring.")}, - {"test_string_to_double", (PyCFunction)test_string_to_double, METH_NOARGS}, - {"test_capsule", (PyCFunction)test_capsule, METH_NOARGS}, - {"getargs_tuple", getargs_tuple, METH_VARARGS}, - {"getargs_keywords", (PyCFunction)getargs_keywords, - METH_VARARGS|METH_KEYWORDS}, - {"getargs_b", getargs_b, METH_VARARGS}, - {"getargs_B", getargs_B, METH_VARARGS}, - {"getargs_h", getargs_h, METH_VARARGS}, - {"getargs_H", getargs_H, METH_VARARGS}, - {"getargs_I", getargs_I, METH_VARARGS}, - {"getargs_k", getargs_k, METH_VARARGS}, - {"getargs_i", getargs_i, METH_VARARGS}, - {"getargs_l", getargs_l, METH_VARARGS}, - {"getargs_n", getargs_n, METH_VARARGS}, + {"raise_exception", raise_exception, METH_VARARGS}, + {"raise_memoryerror", (PyCFunction)raise_memoryerror, METH_NOARGS}, + {"test_config", (PyCFunction)test_config, METH_NOARGS}, + {"test_lazy_hash_inheritance", (PyCFunction)test_lazy_hash_inheritance,METH_NOARGS}, + {"test_broken_memoryview", (PyCFunction)test_broken_memoryview,METH_NOARGS}, + {"test_long_api", (PyCFunction)test_long_api, METH_NOARGS}, + {"test_long_and_overflow", (PyCFunction)test_long_and_overflow, + METH_NOARGS}, + {"test_long_numbits", (PyCFunction)test_long_numbits, METH_NOARGS}, + {"test_string_from_format", (PyCFunction)test_string_from_format, METH_NOARGS}, + {"test_with_docstring", (PyCFunction)test_with_docstring, METH_NOARGS, + PyDoc_STR("This is a pretty normal docstring.")}, + {"test_string_to_double", (PyCFunction)test_string_to_double, METH_NOARGS}, + {"test_capsule", (PyCFunction)test_capsule, METH_NOARGS}, + {"getargs_tuple", getargs_tuple, METH_VARARGS}, + {"getargs_keywords", (PyCFunction)getargs_keywords, + METH_VARARGS|METH_KEYWORDS}, + {"getargs_b", getargs_b, METH_VARARGS}, + {"getargs_B", getargs_B, METH_VARARGS}, + {"getargs_h", getargs_h, METH_VARARGS}, + {"getargs_H", getargs_H, METH_VARARGS}, + {"getargs_I", getargs_I, METH_VARARGS}, + {"getargs_k", getargs_k, METH_VARARGS}, + {"getargs_i", getargs_i, METH_VARARGS}, + {"getargs_l", getargs_l, METH_VARARGS}, + {"getargs_n", getargs_n, METH_VARARGS}, #ifdef HAVE_LONG_LONG - {"getargs_L", getargs_L, METH_VARARGS}, - {"getargs_K", getargs_K, METH_VARARGS}, - {"test_longlong_api", test_longlong_api, METH_NOARGS}, - {"test_long_long_and_overflow", - (PyCFunction)test_long_long_and_overflow, METH_NOARGS}, - {"codec_incrementalencoder", - (PyCFunction)codec_incrementalencoder, METH_VARARGS}, - {"codec_incrementaldecoder", - (PyCFunction)codec_incrementaldecoder, METH_VARARGS}, + {"getargs_L", getargs_L, METH_VARARGS}, + {"getargs_K", getargs_K, METH_VARARGS}, + {"test_longlong_api", test_longlong_api, METH_NOARGS}, + {"test_long_long_and_overflow", + (PyCFunction)test_long_long_and_overflow, METH_NOARGS}, + {"codec_incrementalencoder", + (PyCFunction)codec_incrementalencoder, METH_VARARGS}, + {"codec_incrementaldecoder", + (PyCFunction)codec_incrementaldecoder, METH_VARARGS}, #endif - {"test_Z_code", (PyCFunction)test_Z_code, METH_NOARGS}, - {"test_widechar", (PyCFunction)test_widechar, METH_NOARGS}, + {"test_Z_code", (PyCFunction)test_Z_code, METH_NOARGS}, + {"test_widechar", (PyCFunction)test_widechar, METH_NOARGS}, #ifdef WITH_THREAD - {"_test_thread_state", test_thread_state, METH_VARARGS}, - {"_pending_threadfunc", pending_threadfunc, METH_VARARGS}, + {"_test_thread_state", test_thread_state, METH_VARARGS}, + {"_pending_threadfunc", pending_threadfunc, METH_VARARGS}, #endif #ifdef HAVE_GETTIMEOFDAY - {"profile_int", profile_int, METH_NOARGS}, + {"profile_int", profile_int, METH_NOARGS}, #endif - {"traceback_print", traceback_print, METH_VARARGS}, - {"exception_print", exception_print, METH_VARARGS}, - {"argparsing", argparsing, METH_VARARGS}, - {"code_newempty", code_newempty, METH_VARARGS}, - {"make_exception_with_doc", (PyCFunction)make_exception_with_doc, - METH_VARARGS | METH_KEYWORDS}, - {NULL, NULL} /* sentinel */ + {"traceback_print", traceback_print, METH_VARARGS}, + {"exception_print", exception_print, METH_VARARGS}, + {"argparsing", argparsing, METH_VARARGS}, + {"code_newempty", code_newempty, METH_VARARGS}, + {"make_exception_with_doc", (PyCFunction)make_exception_with_doc, + METH_VARARGS | METH_KEYWORDS}, + {NULL, NULL} /* sentinel */ }; #define AddSym(d, n, f, v) {PyObject *o = f(v); PyDict_SetItemString(d, n, o); Py_DECREF(o);} typedef struct { - char bool_member; - char byte_member; - unsigned char ubyte_member; - short short_member; - unsigned short ushort_member; - int int_member; - unsigned int uint_member; - long long_member; - unsigned long ulong_member; - Py_ssize_t pyssizet_member; - float float_member; - double double_member; - char inplace_member[6]; + char bool_member; + char byte_member; + unsigned char ubyte_member; + short short_member; + unsigned short ushort_member; + int int_member; + unsigned int uint_member; + long long_member; + unsigned long ulong_member; + Py_ssize_t pyssizet_member; + float float_member; + double double_member; + char inplace_member[6]; #ifdef HAVE_LONG_LONG - PY_LONG_LONG longlong_member; - unsigned PY_LONG_LONG ulonglong_member; + PY_LONG_LONG longlong_member; + unsigned PY_LONG_LONG ulonglong_member; #endif } all_structmembers; typedef struct { PyObject_HEAD - all_structmembers structmembers; + all_structmembers structmembers; } test_structmembers; static struct PyMemberDef test_members[] = { - {"T_BOOL", T_BOOL, offsetof(test_structmembers, structmembers.bool_member), 0, NULL}, - {"T_BYTE", T_BYTE, offsetof(test_structmembers, structmembers.byte_member), 0, NULL}, - {"T_UBYTE", T_UBYTE, offsetof(test_structmembers, structmembers.ubyte_member), 0, NULL}, - {"T_SHORT", T_SHORT, offsetof(test_structmembers, structmembers.short_member), 0, NULL}, - {"T_USHORT", T_USHORT, offsetof(test_structmembers, structmembers.ushort_member), 0, NULL}, - {"T_INT", T_INT, offsetof(test_structmembers, structmembers.int_member), 0, NULL}, - {"T_UINT", T_UINT, offsetof(test_structmembers, structmembers.uint_member), 0, NULL}, - {"T_LONG", T_LONG, offsetof(test_structmembers, structmembers.long_member), 0, NULL}, - {"T_ULONG", T_ULONG, offsetof(test_structmembers, structmembers.ulong_member), 0, NULL}, - {"T_PYSSIZET", T_PYSSIZET, offsetof(test_structmembers, structmembers.pyssizet_member), 0, NULL}, - {"T_FLOAT", T_FLOAT, offsetof(test_structmembers, structmembers.float_member), 0, NULL}, - {"T_DOUBLE", T_DOUBLE, offsetof(test_structmembers, structmembers.double_member), 0, NULL}, - {"T_STRING_INPLACE", T_STRING_INPLACE, offsetof(test_structmembers, structmembers.inplace_member), 0, NULL}, + {"T_BOOL", T_BOOL, offsetof(test_structmembers, structmembers.bool_member), 0, NULL}, + {"T_BYTE", T_BYTE, offsetof(test_structmembers, structmembers.byte_member), 0, NULL}, + {"T_UBYTE", T_UBYTE, offsetof(test_structmembers, structmembers.ubyte_member), 0, NULL}, + {"T_SHORT", T_SHORT, offsetof(test_structmembers, structmembers.short_member), 0, NULL}, + {"T_USHORT", T_USHORT, offsetof(test_structmembers, structmembers.ushort_member), 0, NULL}, + {"T_INT", T_INT, offsetof(test_structmembers, structmembers.int_member), 0, NULL}, + {"T_UINT", T_UINT, offsetof(test_structmembers, structmembers.uint_member), 0, NULL}, + {"T_LONG", T_LONG, offsetof(test_structmembers, structmembers.long_member), 0, NULL}, + {"T_ULONG", T_ULONG, offsetof(test_structmembers, structmembers.ulong_member), 0, NULL}, + {"T_PYSSIZET", T_PYSSIZET, offsetof(test_structmembers, structmembers.pyssizet_member), 0, NULL}, + {"T_FLOAT", T_FLOAT, offsetof(test_structmembers, structmembers.float_member), 0, NULL}, + {"T_DOUBLE", T_DOUBLE, offsetof(test_structmembers, structmembers.double_member), 0, NULL}, + {"T_STRING_INPLACE", T_STRING_INPLACE, offsetof(test_structmembers, structmembers.inplace_member), 0, NULL}, #ifdef HAVE_LONG_LONG - {"T_LONGLONG", T_LONGLONG, offsetof(test_structmembers, structmembers.longlong_member), 0, NULL}, - {"T_ULONGLONG", T_ULONGLONG, offsetof(test_structmembers, structmembers.ulonglong_member), 0, NULL}, + {"T_LONGLONG", T_LONGLONG, offsetof(test_structmembers, structmembers.longlong_member), 0, NULL}, + {"T_ULONGLONG", T_ULONGLONG, offsetof(test_structmembers, structmembers.ulonglong_member), 0, NULL}, #endif - {NULL} + {NULL} }; static PyObject * test_structmembers_new(PyTypeObject *type, PyObject *args, PyObject *kwargs) { - static char *keywords[] = { - "T_BOOL", "T_BYTE", "T_UBYTE", "T_SHORT", "T_USHORT", - "T_INT", "T_UINT", "T_LONG", "T_ULONG", "T_PYSSIZET", - "T_FLOAT", "T_DOUBLE", "T_STRING_INPLACE", + static char *keywords[] = { + "T_BOOL", "T_BYTE", "T_UBYTE", "T_SHORT", "T_USHORT", + "T_INT", "T_UINT", "T_LONG", "T_ULONG", "T_PYSSIZET", + "T_FLOAT", "T_DOUBLE", "T_STRING_INPLACE", #ifdef HAVE_LONG_LONG - "T_LONGLONG", "T_ULONGLONG", + "T_LONGLONG", "T_ULONGLONG", #endif - NULL}; - static char *fmt = "|bbBhHiIlknfds#" + NULL}; + static char *fmt = "|bbBhHiIlknfds#" #ifdef HAVE_LONG_LONG - "LK" + "LK" #endif - ; - test_structmembers *ob; - const char *s = NULL; - Py_ssize_t string_len = 0; - ob = PyObject_New(test_structmembers, type); - if (ob == NULL) - return NULL; - memset(&ob->structmembers, 0, sizeof(all_structmembers)); - if (!PyArg_ParseTupleAndKeywords(args, kwargs, fmt, keywords, - &ob->structmembers.bool_member, - &ob->structmembers.byte_member, - &ob->structmembers.ubyte_member, - &ob->structmembers.short_member, - &ob->structmembers.ushort_member, - &ob->structmembers.int_member, - &ob->structmembers.uint_member, - &ob->structmembers.long_member, - &ob->structmembers.ulong_member, - &ob->structmembers.pyssizet_member, - &ob->structmembers.float_member, - &ob->structmembers.double_member, - &s, &string_len + ; + test_structmembers *ob; + const char *s = NULL; + Py_ssize_t string_len = 0; + ob = PyObject_New(test_structmembers, type); + if (ob == NULL) + return NULL; + memset(&ob->structmembers, 0, sizeof(all_structmembers)); + if (!PyArg_ParseTupleAndKeywords(args, kwargs, fmt, keywords, + &ob->structmembers.bool_member, + &ob->structmembers.byte_member, + &ob->structmembers.ubyte_member, + &ob->structmembers.short_member, + &ob->structmembers.ushort_member, + &ob->structmembers.int_member, + &ob->structmembers.uint_member, + &ob->structmembers.long_member, + &ob->structmembers.ulong_member, + &ob->structmembers.pyssizet_member, + &ob->structmembers.float_member, + &ob->structmembers.double_member, + &s, &string_len #ifdef HAVE_LONG_LONG - , &ob->structmembers.longlong_member, - &ob->structmembers.ulonglong_member + , &ob->structmembers.longlong_member, + &ob->structmembers.ulonglong_member #endif - )) { - Py_DECREF(ob); - return NULL; - } - if (s != NULL) { - if (string_len > 5) { - Py_DECREF(ob); - PyErr_SetString(PyExc_ValueError, "string too long"); - return NULL; - } - strcpy(ob->structmembers.inplace_member, s); - } - else { - strcpy(ob->structmembers.inplace_member, ""); - } - return (PyObject *)ob; + )) { + Py_DECREF(ob); + return NULL; + } + if (s != NULL) { + if (string_len > 5) { + Py_DECREF(ob); + PyErr_SetString(PyExc_ValueError, "string too long"); + return NULL; + } + strcpy(ob->structmembers.inplace_member, s); + } + else { + strcpy(ob->structmembers.inplace_member, ""); + } + return (PyObject *)ob; } static void test_structmembers_free(PyObject *ob) { - PyObject_FREE(ob); + PyObject_FREE(ob); } static PyTypeObject test_structmembersType = { PyVarObject_HEAD_INIT(NULL, 0) - "test_structmembersType", - sizeof(test_structmembers), /* tp_basicsize */ - 0, /* tp_itemsize */ - test_structmembers_free, /* destructor 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 */ - PyObject_GenericSetAttr, /* tp_setattro */ - 0, /* tp_as_buffer */ - 0, /* tp_flags */ - "Type containing all structmember types", - 0, /* traverseproc tp_traverse */ - 0, /* tp_clear */ - 0, /* tp_richcompare */ - 0, /* tp_weaklistoffset */ - 0, /* tp_iter */ - 0, /* tp_iternext */ - 0, /* tp_methods */ - test_members, /* tp_members */ - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - test_structmembers_new, /* tp_new */ + "test_structmembersType", + sizeof(test_structmembers), /* tp_basicsize */ + 0, /* tp_itemsize */ + test_structmembers_free, /* destructor 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 */ + PyObject_GenericSetAttr, /* tp_setattro */ + 0, /* tp_as_buffer */ + 0, /* tp_flags */ + "Type containing all structmember types", + 0, /* traverseproc tp_traverse */ + 0, /* tp_clear */ + 0, /* tp_richcompare */ + 0, /* tp_weaklistoffset */ + 0, /* tp_iter */ + 0, /* tp_iternext */ + 0, /* tp_methods */ + test_members, /* tp_members */ + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + test_structmembers_new, /* tp_new */ }; static struct PyModuleDef _testcapimodule = { - PyModuleDef_HEAD_INIT, - "_testcapi", - NULL, - -1, - TestMethods, - NULL, - NULL, - NULL, - NULL + PyModuleDef_HEAD_INIT, + "_testcapi", + NULL, + -1, + TestMethods, + NULL, + NULL, + NULL, + NULL }; PyMODINIT_FUNC PyInit__testcapi(void) { - PyObject *m; + PyObject *m; - m = PyModule_Create(&_testcapimodule); - if (m == NULL) - return NULL; - - Py_TYPE(&_HashInheritanceTester_Type)=&PyType_Type; - Py_TYPE(&_MemoryViewTester_Type)=&PyType_Type; - - Py_TYPE(&test_structmembersType)=&PyType_Type; - Py_INCREF(&test_structmembersType); - /* don't use a name starting with "test", since we don't want - test_capi to automatically call this */ - PyModule_AddObject(m, "_test_structmembersType", (PyObject *)&test_structmembersType); - - PyModule_AddObject(m, "CHAR_MAX", PyLong_FromLong(CHAR_MAX)); - PyModule_AddObject(m, "CHAR_MIN", PyLong_FromLong(CHAR_MIN)); - PyModule_AddObject(m, "UCHAR_MAX", PyLong_FromLong(UCHAR_MAX)); - PyModule_AddObject(m, "SHRT_MAX", PyLong_FromLong(SHRT_MAX)); - PyModule_AddObject(m, "SHRT_MIN", PyLong_FromLong(SHRT_MIN)); - PyModule_AddObject(m, "USHRT_MAX", PyLong_FromLong(USHRT_MAX)); - PyModule_AddObject(m, "INT_MAX", PyLong_FromLong(INT_MAX)); - PyModule_AddObject(m, "INT_MIN", PyLong_FromLong(INT_MIN)); - PyModule_AddObject(m, "UINT_MAX", PyLong_FromUnsignedLong(UINT_MAX)); - PyModule_AddObject(m, "LONG_MAX", PyLong_FromLong(LONG_MAX)); - PyModule_AddObject(m, "LONG_MIN", PyLong_FromLong(LONG_MIN)); - PyModule_AddObject(m, "ULONG_MAX", PyLong_FromUnsignedLong(ULONG_MAX)); - PyModule_AddObject(m, "FLT_MAX", PyFloat_FromDouble(FLT_MAX)); - PyModule_AddObject(m, "FLT_MIN", PyFloat_FromDouble(FLT_MIN)); - PyModule_AddObject(m, "DBL_MAX", PyFloat_FromDouble(DBL_MAX)); - PyModule_AddObject(m, "DBL_MIN", PyFloat_FromDouble(DBL_MIN)); - PyModule_AddObject(m, "LLONG_MAX", PyLong_FromLongLong(PY_LLONG_MAX)); - PyModule_AddObject(m, "LLONG_MIN", PyLong_FromLongLong(PY_LLONG_MIN)); - PyModule_AddObject(m, "ULLONG_MAX", PyLong_FromUnsignedLongLong(PY_ULLONG_MAX)); - PyModule_AddObject(m, "PY_SSIZE_T_MAX", PyLong_FromSsize_t(PY_SSIZE_T_MAX)); - PyModule_AddObject(m, "PY_SSIZE_T_MIN", PyLong_FromSsize_t(PY_SSIZE_T_MIN)); - PyModule_AddObject(m, "SIZEOF_PYGC_HEAD", PyLong_FromSsize_t(sizeof(PyGC_Head))); - Py_INCREF(&PyInstanceMethod_Type); - PyModule_AddObject(m, "instancemethod", (PyObject *)&PyInstanceMethod_Type); - - TestError = PyErr_NewException("_testcapi.error", NULL, NULL); - Py_INCREF(TestError); - PyModule_AddObject(m, "error", TestError); - return m; + m = PyModule_Create(&_testcapimodule); + if (m == NULL) + return NULL; + + Py_TYPE(&_HashInheritanceTester_Type)=&PyType_Type; + Py_TYPE(&_MemoryViewTester_Type)=&PyType_Type; + + Py_TYPE(&test_structmembersType)=&PyType_Type; + Py_INCREF(&test_structmembersType); + /* don't use a name starting with "test", since we don't want + test_capi to automatically call this */ + PyModule_AddObject(m, "_test_structmembersType", (PyObject *)&test_structmembersType); + + PyModule_AddObject(m, "CHAR_MAX", PyLong_FromLong(CHAR_MAX)); + PyModule_AddObject(m, "CHAR_MIN", PyLong_FromLong(CHAR_MIN)); + PyModule_AddObject(m, "UCHAR_MAX", PyLong_FromLong(UCHAR_MAX)); + PyModule_AddObject(m, "SHRT_MAX", PyLong_FromLong(SHRT_MAX)); + PyModule_AddObject(m, "SHRT_MIN", PyLong_FromLong(SHRT_MIN)); + PyModule_AddObject(m, "USHRT_MAX", PyLong_FromLong(USHRT_MAX)); + PyModule_AddObject(m, "INT_MAX", PyLong_FromLong(INT_MAX)); + PyModule_AddObject(m, "INT_MIN", PyLong_FromLong(INT_MIN)); + PyModule_AddObject(m, "UINT_MAX", PyLong_FromUnsignedLong(UINT_MAX)); + PyModule_AddObject(m, "LONG_MAX", PyLong_FromLong(LONG_MAX)); + PyModule_AddObject(m, "LONG_MIN", PyLong_FromLong(LONG_MIN)); + PyModule_AddObject(m, "ULONG_MAX", PyLong_FromUnsignedLong(ULONG_MAX)); + PyModule_AddObject(m, "FLT_MAX", PyFloat_FromDouble(FLT_MAX)); + PyModule_AddObject(m, "FLT_MIN", PyFloat_FromDouble(FLT_MIN)); + PyModule_AddObject(m, "DBL_MAX", PyFloat_FromDouble(DBL_MAX)); + PyModule_AddObject(m, "DBL_MIN", PyFloat_FromDouble(DBL_MIN)); + PyModule_AddObject(m, "LLONG_MAX", PyLong_FromLongLong(PY_LLONG_MAX)); + PyModule_AddObject(m, "LLONG_MIN", PyLong_FromLongLong(PY_LLONG_MIN)); + PyModule_AddObject(m, "ULLONG_MAX", PyLong_FromUnsignedLongLong(PY_ULLONG_MAX)); + PyModule_AddObject(m, "PY_SSIZE_T_MAX", PyLong_FromSsize_t(PY_SSIZE_T_MAX)); + PyModule_AddObject(m, "PY_SSIZE_T_MIN", PyLong_FromSsize_t(PY_SSIZE_T_MIN)); + PyModule_AddObject(m, "SIZEOF_PYGC_HEAD", PyLong_FromSsize_t(sizeof(PyGC_Head))); + Py_INCREF(&PyInstanceMethod_Type); + PyModule_AddObject(m, "instancemethod", (PyObject *)&PyInstanceMethod_Type); + + TestError = PyErr_NewException("_testcapi.error", NULL, NULL); + Py_INCREF(TestError); + PyModule_AddObject(m, "error", TestError); + return m; } Modified: python/branches/py3k-jit/Modules/_threadmodule.c ============================================================================== --- python/branches/py3k-jit/Modules/_threadmodule.c (original) +++ python/branches/py3k-jit/Modules/_threadmodule.c Mon May 10 23:55:43 2010 @@ -19,68 +19,68 @@ /* Lock objects */ typedef struct { - PyObject_HEAD - PyThread_type_lock lock_lock; - PyObject *in_weakreflist; + PyObject_HEAD + PyThread_type_lock lock_lock; + PyObject *in_weakreflist; } lockobject; static void lock_dealloc(lockobject *self) { - if (self->in_weakreflist != NULL) - PyObject_ClearWeakRefs((PyObject *) self); - if (self->lock_lock != NULL) { - /* Unlock the lock so it's safe to free it */ - PyThread_acquire_lock(self->lock_lock, 0); - PyThread_release_lock(self->lock_lock); - - PyThread_free_lock(self->lock_lock); - } - PyObject_Del(self); + if (self->in_weakreflist != NULL) + PyObject_ClearWeakRefs((PyObject *) self); + if (self->lock_lock != NULL) { + /* Unlock the lock so it's safe to free it */ + PyThread_acquire_lock(self->lock_lock, 0); + PyThread_release_lock(self->lock_lock); + + PyThread_free_lock(self->lock_lock); + } + PyObject_Del(self); } static PyObject * lock_PyThread_acquire_lock(lockobject *self, PyObject *args, PyObject *kwds) { - char *kwlist[] = {"blocking", "timeout", NULL}; - int blocking = 1; - double timeout = -1; - PY_TIMEOUT_T microseconds; - int r; - - if (!PyArg_ParseTupleAndKeywords(args, kwds, "|id:acquire", kwlist, - &blocking, &timeout)) - return NULL; - - if (!blocking && timeout != -1) { - PyErr_SetString(PyExc_ValueError, "can't specify a timeout " - "for a non-blocking call"); - return NULL; - } - if (timeout < 0 && timeout != -1) { - PyErr_SetString(PyExc_ValueError, "timeout value must be " - "strictly positive"); - return NULL; - } - if (!blocking) - microseconds = 0; - else if (timeout == -1) - microseconds = -1; - else { - timeout *= 1e6; - if (timeout >= (double) PY_TIMEOUT_MAX) { - PyErr_SetString(PyExc_OverflowError, - "timeout value is too large"); - return NULL; - } - microseconds = (PY_TIMEOUT_T) timeout; - } - - Py_BEGIN_ALLOW_THREADS - r = PyThread_acquire_lock_timed(self->lock_lock, microseconds); - Py_END_ALLOW_THREADS + char *kwlist[] = {"blocking", "timeout", NULL}; + int blocking = 1; + double timeout = -1; + PY_TIMEOUT_T microseconds; + int r; + + if (!PyArg_ParseTupleAndKeywords(args, kwds, "|id:acquire", kwlist, + &blocking, &timeout)) + return NULL; + + if (!blocking && timeout != -1) { + PyErr_SetString(PyExc_ValueError, "can't specify a timeout " + "for a non-blocking call"); + return NULL; + } + if (timeout < 0 && timeout != -1) { + PyErr_SetString(PyExc_ValueError, "timeout value must be " + "strictly positive"); + return NULL; + } + if (!blocking) + microseconds = 0; + else if (timeout == -1) + microseconds = -1; + else { + timeout *= 1e6; + if (timeout >= (double) PY_TIMEOUT_MAX) { + PyErr_SetString(PyExc_OverflowError, + "timeout value is too large"); + return NULL; + } + microseconds = (PY_TIMEOUT_T) timeout; + } + + Py_BEGIN_ALLOW_THREADS + r = PyThread_acquire_lock_timed(self->lock_lock, microseconds); + Py_END_ALLOW_THREADS - return PyBool_FromLong(r); + return PyBool_FromLong(r); } PyDoc_STRVAR(acquire_doc, @@ -97,16 +97,16 @@ static PyObject * lock_PyThread_release_lock(lockobject *self) { - /* Sanity check: the lock must be locked */ - if (PyThread_acquire_lock(self->lock_lock, 0)) { - PyThread_release_lock(self->lock_lock); - PyErr_SetString(ThreadError, "release unlocked lock"); - return NULL; - } - - PyThread_release_lock(self->lock_lock); - Py_INCREF(Py_None); - return Py_None; + /* Sanity check: the lock must be locked */ + if (PyThread_acquire_lock(self->lock_lock, 0)) { + PyThread_release_lock(self->lock_lock); + PyErr_SetString(ThreadError, "release unlocked lock"); + return NULL; + } + + PyThread_release_lock(self->lock_lock); + Py_INCREF(Py_None); + return Py_None; } PyDoc_STRVAR(release_doc, @@ -120,11 +120,11 @@ static PyObject * lock_locked_lock(lockobject *self) { - if (PyThread_acquire_lock(self->lock_lock, 0)) { - PyThread_release_lock(self->lock_lock); - return PyBool_FromLong(0L); - } - return PyBool_FromLong(1L); + if (PyThread_acquire_lock(self->lock_lock, 0)) { + PyThread_release_lock(self->lock_lock); + return PyBool_FromLong(0L); + } + return PyBool_FromLong(1L); } PyDoc_STRVAR(locked_doc, @@ -134,147 +134,147 @@ Return whether the lock is in the locked state."); static PyMethodDef lock_methods[] = { - {"acquire_lock", (PyCFunction)lock_PyThread_acquire_lock, - METH_VARARGS | METH_KEYWORDS, acquire_doc}, - {"acquire", (PyCFunction)lock_PyThread_acquire_lock, - METH_VARARGS | METH_KEYWORDS, acquire_doc}, - {"release_lock", (PyCFunction)lock_PyThread_release_lock, - METH_NOARGS, release_doc}, - {"release", (PyCFunction)lock_PyThread_release_lock, - METH_NOARGS, release_doc}, - {"locked_lock", (PyCFunction)lock_locked_lock, - METH_NOARGS, locked_doc}, - {"locked", (PyCFunction)lock_locked_lock, - METH_NOARGS, locked_doc}, - {"__enter__", (PyCFunction)lock_PyThread_acquire_lock, - METH_VARARGS | METH_KEYWORDS, acquire_doc}, - {"__exit__", (PyCFunction)lock_PyThread_release_lock, - METH_VARARGS, release_doc}, - {NULL, NULL} /* sentinel */ + {"acquire_lock", (PyCFunction)lock_PyThread_acquire_lock, + METH_VARARGS | METH_KEYWORDS, acquire_doc}, + {"acquire", (PyCFunction)lock_PyThread_acquire_lock, + METH_VARARGS | METH_KEYWORDS, acquire_doc}, + {"release_lock", (PyCFunction)lock_PyThread_release_lock, + METH_NOARGS, release_doc}, + {"release", (PyCFunction)lock_PyThread_release_lock, + METH_NOARGS, release_doc}, + {"locked_lock", (PyCFunction)lock_locked_lock, + METH_NOARGS, locked_doc}, + {"locked", (PyCFunction)lock_locked_lock, + METH_NOARGS, locked_doc}, + {"__enter__", (PyCFunction)lock_PyThread_acquire_lock, + METH_VARARGS | METH_KEYWORDS, acquire_doc}, + {"__exit__", (PyCFunction)lock_PyThread_release_lock, + METH_VARARGS, release_doc}, + {NULL, NULL} /* sentinel */ }; static PyTypeObject Locktype = { - PyVarObject_HEAD_INIT(&PyType_Type, 0) - "_thread.lock", /*tp_name*/ - sizeof(lockobject), /*tp_size*/ - 0, /*tp_itemsize*/ - /* methods */ - (destructor)lock_dealloc, /*tp_dealloc*/ - 0, /*tp_print*/ - 0, /*tp_getattr*/ - 0, /*tp_setattr*/ - 0, /*tp_reserved*/ - 0, /*tp_repr*/ - 0, /*tp_as_number*/ - 0, /*tp_as_sequence*/ - 0, /*tp_as_mapping*/ - 0, /*tp_hash*/ - 0, /*tp_call*/ - 0, /*tp_str*/ - 0, /*tp_getattro*/ - 0, /*tp_setattro*/ - 0, /*tp_as_buffer*/ - Py_TPFLAGS_DEFAULT, /*tp_flags*/ - 0, /*tp_doc*/ - 0, /*tp_traverse*/ - 0, /*tp_clear*/ - 0, /*tp_richcompare*/ - offsetof(lockobject, in_weakreflist), /*tp_weaklistoffset*/ - 0, /*tp_iter*/ - 0, /*tp_iternext*/ - lock_methods, /*tp_methods*/ + PyVarObject_HEAD_INIT(&PyType_Type, 0) + "_thread.lock", /*tp_name*/ + sizeof(lockobject), /*tp_size*/ + 0, /*tp_itemsize*/ + /* methods */ + (destructor)lock_dealloc, /*tp_dealloc*/ + 0, /*tp_print*/ + 0, /*tp_getattr*/ + 0, /*tp_setattr*/ + 0, /*tp_reserved*/ + 0, /*tp_repr*/ + 0, /*tp_as_number*/ + 0, /*tp_as_sequence*/ + 0, /*tp_as_mapping*/ + 0, /*tp_hash*/ + 0, /*tp_call*/ + 0, /*tp_str*/ + 0, /*tp_getattro*/ + 0, /*tp_setattro*/ + 0, /*tp_as_buffer*/ + Py_TPFLAGS_DEFAULT, /*tp_flags*/ + 0, /*tp_doc*/ + 0, /*tp_traverse*/ + 0, /*tp_clear*/ + 0, /*tp_richcompare*/ + offsetof(lockobject, in_weakreflist), /*tp_weaklistoffset*/ + 0, /*tp_iter*/ + 0, /*tp_iternext*/ + lock_methods, /*tp_methods*/ }; /* Recursive lock objects */ typedef struct { - PyObject_HEAD - PyThread_type_lock rlock_lock; - long rlock_owner; - unsigned long rlock_count; - PyObject *in_weakreflist; + PyObject_HEAD + PyThread_type_lock rlock_lock; + long rlock_owner; + unsigned long rlock_count; + PyObject *in_weakreflist; } rlockobject; static void rlock_dealloc(rlockobject *self) { - assert(self->rlock_lock); - if (self->in_weakreflist != NULL) - PyObject_ClearWeakRefs((PyObject *) self); - /* Unlock the lock so it's safe to free it */ - if (self->rlock_count > 0) - PyThread_release_lock(self->rlock_lock); - - PyThread_free_lock(self->rlock_lock); - Py_TYPE(self)->tp_free(self); + assert(self->rlock_lock); + if (self->in_weakreflist != NULL) + PyObject_ClearWeakRefs((PyObject *) self); + /* Unlock the lock so it's safe to free it */ + if (self->rlock_count > 0) + PyThread_release_lock(self->rlock_lock); + + PyThread_free_lock(self->rlock_lock); + Py_TYPE(self)->tp_free(self); } static PyObject * rlock_acquire(rlockobject *self, PyObject *args, PyObject *kwds) { - char *kwlist[] = {"blocking", "timeout", NULL}; - int blocking = 1; - double timeout = -1; - PY_TIMEOUT_T microseconds; - long tid; - int r = 1; - - if (!PyArg_ParseTupleAndKeywords(args, kwds, "|id:acquire", kwlist, - &blocking, &timeout)) - return NULL; - - if (!blocking && timeout != -1) { - PyErr_SetString(PyExc_ValueError, "can't specify a timeout " - "for a non-blocking call"); - return NULL; - } - if (timeout < 0 && timeout != -1) { - PyErr_SetString(PyExc_ValueError, "timeout value must be " - "strictly positive"); - return NULL; - } - if (!blocking) - microseconds = 0; - else if (timeout == -1) - microseconds = -1; - else { - timeout *= 1e6; - if (timeout >= (double) PY_TIMEOUT_MAX) { - PyErr_SetString(PyExc_OverflowError, - "timeout value is too large"); - return NULL; - } - microseconds = (PY_TIMEOUT_T) timeout; - } - - tid = PyThread_get_thread_ident(); - if (self->rlock_count > 0 && tid == self->rlock_owner) { - unsigned long count = self->rlock_count + 1; - if (count <= self->rlock_count) { - PyErr_SetString(PyExc_OverflowError, - "Internal lock count overflowed"); - return NULL; - } - self->rlock_count = count; - Py_RETURN_TRUE; - } - - if (self->rlock_count > 0 || - !PyThread_acquire_lock(self->rlock_lock, 0)) { - if (microseconds == 0) { - Py_RETURN_FALSE; - } - Py_BEGIN_ALLOW_THREADS - r = PyThread_acquire_lock_timed(self->rlock_lock, microseconds); - Py_END_ALLOW_THREADS - } - if (r) { - assert(self->rlock_count == 0); - self->rlock_owner = tid; - self->rlock_count = 1; - } + char *kwlist[] = {"blocking", "timeout", NULL}; + int blocking = 1; + double timeout = -1; + PY_TIMEOUT_T microseconds; + long tid; + int r = 1; + + if (!PyArg_ParseTupleAndKeywords(args, kwds, "|id:acquire", kwlist, + &blocking, &timeout)) + return NULL; + + if (!blocking && timeout != -1) { + PyErr_SetString(PyExc_ValueError, "can't specify a timeout " + "for a non-blocking call"); + return NULL; + } + if (timeout < 0 && timeout != -1) { + PyErr_SetString(PyExc_ValueError, "timeout value must be " + "strictly positive"); + return NULL; + } + if (!blocking) + microseconds = 0; + else if (timeout == -1) + microseconds = -1; + else { + timeout *= 1e6; + if (timeout >= (double) PY_TIMEOUT_MAX) { + PyErr_SetString(PyExc_OverflowError, + "timeout value is too large"); + return NULL; + } + microseconds = (PY_TIMEOUT_T) timeout; + } + + tid = PyThread_get_thread_ident(); + if (self->rlock_count > 0 && tid == self->rlock_owner) { + unsigned long count = self->rlock_count + 1; + if (count <= self->rlock_count) { + PyErr_SetString(PyExc_OverflowError, + "Internal lock count overflowed"); + return NULL; + } + self->rlock_count = count; + Py_RETURN_TRUE; + } + + if (self->rlock_count > 0 || + !PyThread_acquire_lock(self->rlock_lock, 0)) { + if (microseconds == 0) { + Py_RETURN_FALSE; + } + Py_BEGIN_ALLOW_THREADS + r = PyThread_acquire_lock_timed(self->rlock_lock, microseconds); + Py_END_ALLOW_THREADS + } + if (r) { + assert(self->rlock_count == 0); + self->rlock_owner = tid; + self->rlock_count = 1; + } - return PyBool_FromLong(r); + return PyBool_FromLong(r); } PyDoc_STRVAR(rlock_acquire_doc, @@ -296,18 +296,18 @@ static PyObject * rlock_release(rlockobject *self) { - long tid = PyThread_get_thread_ident(); + long tid = PyThread_get_thread_ident(); - if (self->rlock_count == 0 || self->rlock_owner != tid) { - PyErr_SetString(PyExc_RuntimeError, - "cannot release un-acquired lock"); - return NULL; - } - if (--self->rlock_count == 0) { - self->rlock_owner = 0; - PyThread_release_lock(self->rlock_lock); - } - Py_RETURN_NONE; + if (self->rlock_count == 0 || self->rlock_owner != tid) { + PyErr_SetString(PyExc_RuntimeError, + "cannot release un-acquired lock"); + return NULL; + } + if (--self->rlock_count == 0) { + self->rlock_owner = 0; + PyThread_release_lock(self->rlock_lock); + } + Py_RETURN_NONE; } PyDoc_STRVAR(rlock_release_doc, @@ -325,26 +325,26 @@ static PyObject * rlock_acquire_restore(rlockobject *self, PyObject *arg) { - long owner; - unsigned long count; - int r = 1; - - if (!PyArg_ParseTuple(arg, "kl:_acquire_restore", &count, &owner)) - return NULL; - - if (!PyThread_acquire_lock(self->rlock_lock, 0)) { - Py_BEGIN_ALLOW_THREADS - r = PyThread_acquire_lock(self->rlock_lock, 1); - Py_END_ALLOW_THREADS - } - if (!r) { - PyErr_SetString(ThreadError, "couldn't acquire lock"); - return NULL; - } - assert(self->rlock_count == 0); - self->rlock_owner = owner; - self->rlock_count = count; - Py_RETURN_NONE; + long owner; + unsigned long count; + int r = 1; + + if (!PyArg_ParseTuple(arg, "kl:_acquire_restore", &count, &owner)) + return NULL; + + if (!PyThread_acquire_lock(self->rlock_lock, 0)) { + Py_BEGIN_ALLOW_THREADS + r = PyThread_acquire_lock(self->rlock_lock, 1); + Py_END_ALLOW_THREADS + } + if (!r) { + PyErr_SetString(ThreadError, "couldn't acquire lock"); + return NULL; + } + assert(self->rlock_count == 0); + self->rlock_owner = owner; + self->rlock_count = count; + Py_RETURN_NONE; } PyDoc_STRVAR(rlock_acquire_restore_doc, @@ -355,15 +355,15 @@ static PyObject * rlock_release_save(rlockobject *self) { - long owner; - unsigned long count; + long owner; + unsigned long count; - owner = self->rlock_owner; - count = self->rlock_count; - self->rlock_count = 0; - self->rlock_owner = 0; - PyThread_release_lock(self->rlock_lock); - return Py_BuildValue("kl", count, owner); + owner = self->rlock_owner; + count = self->rlock_count; + self->rlock_count = 0; + self->rlock_owner = 0; + PyThread_release_lock(self->rlock_lock); + return Py_BuildValue("kl", count, owner); } PyDoc_STRVAR(rlock_release_save_doc, @@ -375,12 +375,12 @@ static PyObject * rlock_is_owned(rlockobject *self) { - long tid = PyThread_get_thread_ident(); - - if (self->rlock_count > 0 && self->rlock_owner == tid) { - Py_RETURN_TRUE; - } - Py_RETURN_FALSE; + long tid = PyThread_get_thread_ident(); + + if (self->rlock_count > 0 && self->rlock_owner == tid) { + Py_RETURN_TRUE; + } + Py_RETURN_FALSE; } PyDoc_STRVAR(rlock_is_owned_doc, @@ -391,108 +391,108 @@ static PyObject * rlock_new(PyTypeObject *type, PyObject *args, PyObject *kwds) { - rlockobject *self; + rlockobject *self; - self = (rlockobject *) type->tp_alloc(type, 0); - if (self != NULL) { - self->rlock_lock = PyThread_allocate_lock(); - if (self->rlock_lock == NULL) { - type->tp_free(self); - PyErr_SetString(ThreadError, "can't allocate lock"); - return NULL; - } - self->in_weakreflist = NULL; - self->rlock_owner = 0; - self->rlock_count = 0; - } + self = (rlockobject *) type->tp_alloc(type, 0); + if (self != NULL) { + self->rlock_lock = PyThread_allocate_lock(); + if (self->rlock_lock == NULL) { + type->tp_free(self); + PyErr_SetString(ThreadError, "can't allocate lock"); + return NULL; + } + self->in_weakreflist = NULL; + self->rlock_owner = 0; + self->rlock_count = 0; + } - return (PyObject *) self; + return (PyObject *) self; } static PyObject * rlock_repr(rlockobject *self) { - return PyUnicode_FromFormat("<%s owner=%ld count=%lu>", - Py_TYPE(self)->tp_name, self->rlock_owner, self->rlock_count); + return PyUnicode_FromFormat("<%s owner=%ld count=%lu>", + Py_TYPE(self)->tp_name, self->rlock_owner, self->rlock_count); } static PyMethodDef rlock_methods[] = { - {"acquire", (PyCFunction)rlock_acquire, - METH_VARARGS | METH_KEYWORDS, rlock_acquire_doc}, - {"release", (PyCFunction)rlock_release, - METH_NOARGS, rlock_release_doc}, - {"_is_owned", (PyCFunction)rlock_is_owned, - METH_NOARGS, rlock_is_owned_doc}, - {"_acquire_restore", (PyCFunction)rlock_acquire_restore, - METH_O, rlock_acquire_restore_doc}, - {"_release_save", (PyCFunction)rlock_release_save, - METH_NOARGS, rlock_release_save_doc}, - {"__enter__", (PyCFunction)rlock_acquire, - METH_VARARGS | METH_KEYWORDS, rlock_acquire_doc}, - {"__exit__", (PyCFunction)rlock_release, - METH_VARARGS, rlock_release_doc}, - {NULL, NULL} /* sentinel */ + {"acquire", (PyCFunction)rlock_acquire, + METH_VARARGS | METH_KEYWORDS, rlock_acquire_doc}, + {"release", (PyCFunction)rlock_release, + METH_NOARGS, rlock_release_doc}, + {"_is_owned", (PyCFunction)rlock_is_owned, + METH_NOARGS, rlock_is_owned_doc}, + {"_acquire_restore", (PyCFunction)rlock_acquire_restore, + METH_O, rlock_acquire_restore_doc}, + {"_release_save", (PyCFunction)rlock_release_save, + METH_NOARGS, rlock_release_save_doc}, + {"__enter__", (PyCFunction)rlock_acquire, + METH_VARARGS | METH_KEYWORDS, rlock_acquire_doc}, + {"__exit__", (PyCFunction)rlock_release, + METH_VARARGS, rlock_release_doc}, + {NULL, NULL} /* sentinel */ }; static PyTypeObject RLocktype = { - PyVarObject_HEAD_INIT(&PyType_Type, 0) - "_thread.RLock", /*tp_name*/ - sizeof(rlockobject), /*tp_size*/ - 0, /*tp_itemsize*/ - /* methods */ - (destructor)rlock_dealloc, /*tp_dealloc*/ - 0, /*tp_print*/ - 0, /*tp_getattr*/ - 0, /*tp_setattr*/ - 0, /*tp_reserved*/ - (reprfunc)rlock_repr, /*tp_repr*/ - 0, /*tp_as_number*/ - 0, /*tp_as_sequence*/ - 0, /*tp_as_mapping*/ - 0, /*tp_hash*/ - 0, /*tp_call*/ - 0, /*tp_str*/ - 0, /*tp_getattro*/ - 0, /*tp_setattro*/ - 0, /*tp_as_buffer*/ - Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */ - 0, /*tp_doc*/ - 0, /*tp_traverse*/ - 0, /*tp_clear*/ - 0, /*tp_richcompare*/ - offsetof(rlockobject, in_weakreflist), /*tp_weaklistoffset*/ - 0, /*tp_iter*/ - 0, /*tp_iternext*/ - rlock_methods, /*tp_methods*/ - 0, /* tp_members */ - 0, /* tp_getset */ - 0, /* tp_base */ - 0, /* tp_dict */ - 0, /* tp_descr_get */ - 0, /* tp_descr_set */ - 0, /* tp_dictoffset */ - 0, /* tp_init */ - PyType_GenericAlloc, /* tp_alloc */ - rlock_new /* tp_new */ + PyVarObject_HEAD_INIT(&PyType_Type, 0) + "_thread.RLock", /*tp_name*/ + sizeof(rlockobject), /*tp_size*/ + 0, /*tp_itemsize*/ + /* methods */ + (destructor)rlock_dealloc, /*tp_dealloc*/ + 0, /*tp_print*/ + 0, /*tp_getattr*/ + 0, /*tp_setattr*/ + 0, /*tp_reserved*/ + (reprfunc)rlock_repr, /*tp_repr*/ + 0, /*tp_as_number*/ + 0, /*tp_as_sequence*/ + 0, /*tp_as_mapping*/ + 0, /*tp_hash*/ + 0, /*tp_call*/ + 0, /*tp_str*/ + 0, /*tp_getattro*/ + 0, /*tp_setattro*/ + 0, /*tp_as_buffer*/ + Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */ + 0, /*tp_doc*/ + 0, /*tp_traverse*/ + 0, /*tp_clear*/ + 0, /*tp_richcompare*/ + offsetof(rlockobject, in_weakreflist), /*tp_weaklistoffset*/ + 0, /*tp_iter*/ + 0, /*tp_iternext*/ + rlock_methods, /*tp_methods*/ + 0, /* tp_members */ + 0, /* tp_getset */ + 0, /* tp_base */ + 0, /* tp_dict */ + 0, /* tp_descr_get */ + 0, /* tp_descr_set */ + 0, /* tp_dictoffset */ + 0, /* tp_init */ + PyType_GenericAlloc, /* tp_alloc */ + rlock_new /* tp_new */ }; static lockobject * newlockobject(void) { - lockobject *self; - self = PyObject_New(lockobject, &Locktype); - if (self == NULL) - return NULL; - self->lock_lock = PyThread_allocate_lock(); - self->in_weakreflist = NULL; - if (self->lock_lock == NULL) { - Py_DECREF(self); - PyErr_SetString(ThreadError, "can't allocate lock"); - return NULL; - } - return self; + lockobject *self; + self = PyObject_New(lockobject, &Locktype); + if (self == NULL) + return NULL; + self->lock_lock = PyThread_allocate_lock(); + self->in_weakreflist = NULL; + if (self->lock_lock == NULL) { + Py_DECREF(self); + PyErr_SetString(ThreadError, "can't allocate lock"); + return NULL; + } + return self; } /* Thread-local objects */ @@ -500,353 +500,353 @@ #include "structmember.h" typedef struct { - PyObject_HEAD - PyObject *key; - PyObject *args; - PyObject *kw; - PyObject *dict; + PyObject_HEAD + PyObject *key; + PyObject *args; + PyObject *kw; + PyObject *dict; } localobject; static PyObject * local_new(PyTypeObject *type, PyObject *args, PyObject *kw) { - localobject *self; - PyObject *tdict; + localobject *self; + PyObject *tdict; - if (type->tp_init == PyBaseObject_Type.tp_init - && ((args && PyObject_IsTrue(args)) - || (kw && PyObject_IsTrue(kw)))) { - PyErr_SetString(PyExc_TypeError, - "Initialization arguments are not supported"); - return NULL; - } - - self = (localobject *)type->tp_alloc(type, 0); - if (self == NULL) - return NULL; - - Py_XINCREF(args); - self->args = args; - Py_XINCREF(kw); - self->kw = kw; - self->dict = NULL; /* making sure */ - self->key = PyUnicode_FromFormat("thread.local.%p", self); - if (self->key == NULL) - goto err; - - self->dict = PyDict_New(); - if (self->dict == NULL) - goto err; - - tdict = PyThreadState_GetDict(); - if (tdict == NULL) { - PyErr_SetString(PyExc_SystemError, - "Couldn't get thread-state dictionary"); - goto err; - } + if (type->tp_init == PyBaseObject_Type.tp_init + && ((args && PyObject_IsTrue(args)) + || (kw && PyObject_IsTrue(kw)))) { + PyErr_SetString(PyExc_TypeError, + "Initialization arguments are not supported"); + return NULL; + } + + self = (localobject *)type->tp_alloc(type, 0); + if (self == NULL) + return NULL; + + Py_XINCREF(args); + self->args = args; + Py_XINCREF(kw); + self->kw = kw; + self->dict = NULL; /* making sure */ + self->key = PyUnicode_FromFormat("thread.local.%p", self); + if (self->key == NULL) + goto err; + + self->dict = PyDict_New(); + if (self->dict == NULL) + goto err; + + tdict = PyThreadState_GetDict(); + if (tdict == NULL) { + PyErr_SetString(PyExc_SystemError, + "Couldn't get thread-state dictionary"); + goto err; + } - if (PyDict_SetItem(tdict, self->key, self->dict) < 0) - goto err; + if (PyDict_SetItem(tdict, self->key, self->dict) < 0) + goto err; - return (PyObject *)self; + return (PyObject *)self; err: - Py_DECREF(self); - return NULL; + Py_DECREF(self); + return NULL; } static int local_traverse(localobject *self, visitproc visit, void *arg) { - Py_VISIT(self->args); - Py_VISIT(self->kw); - Py_VISIT(self->dict); - return 0; + Py_VISIT(self->args); + Py_VISIT(self->kw); + Py_VISIT(self->dict); + return 0; } static int local_clear(localobject *self) { - Py_CLEAR(self->args); - Py_CLEAR(self->kw); - Py_CLEAR(self->dict); - return 0; + Py_CLEAR(self->args); + Py_CLEAR(self->kw); + Py_CLEAR(self->dict); + return 0; } static void local_dealloc(localobject *self) { - PyThreadState *tstate; - if (self->key - && (tstate = PyThreadState_Get()) - && tstate->interp) { - for(tstate = PyInterpreterState_ThreadHead(tstate->interp); - tstate; - tstate = PyThreadState_Next(tstate)) - if (tstate->dict && - PyDict_GetItem(tstate->dict, self->key)) - PyDict_DelItem(tstate->dict, self->key); - } - - Py_XDECREF(self->key); - local_clear(self); - Py_TYPE(self)->tp_free((PyObject*)self); + PyThreadState *tstate; + if (self->key + && (tstate = PyThreadState_Get()) + && tstate->interp) { + for(tstate = PyInterpreterState_ThreadHead(tstate->interp); + tstate; + tstate = PyThreadState_Next(tstate)) + if (tstate->dict && + PyDict_GetItem(tstate->dict, self->key)) + PyDict_DelItem(tstate->dict, self->key); + } + + Py_XDECREF(self->key); + local_clear(self); + Py_TYPE(self)->tp_free((PyObject*)self); } static PyObject * _ldict(localobject *self) { - PyObject *tdict, *ldict; + PyObject *tdict, *ldict; - tdict = PyThreadState_GetDict(); - if (tdict == NULL) { - PyErr_SetString(PyExc_SystemError, - "Couldn't get thread-state dictionary"); - return NULL; - } - - ldict = PyDict_GetItem(tdict, self->key); - if (ldict == NULL) { - ldict = PyDict_New(); /* we own ldict */ - - if (ldict == NULL) - return NULL; - else { - int i = PyDict_SetItem(tdict, self->key, ldict); - Py_DECREF(ldict); /* now ldict is borrowed */ - if (i < 0) - return NULL; - } - - Py_CLEAR(self->dict); - Py_INCREF(ldict); - self->dict = ldict; /* still borrowed */ - - if (Py_TYPE(self)->tp_init != PyBaseObject_Type.tp_init && - Py_TYPE(self)->tp_init((PyObject*)self, - self->args, self->kw) < 0) { - /* we need to get rid of ldict from thread so - we create a new one the next time we do an attr - acces */ - PyDict_DelItem(tdict, self->key); - return NULL; - } - - } - - /* The call to tp_init above may have caused another thread to run. - Install our ldict again. */ - if (self->dict != ldict) { - Py_CLEAR(self->dict); - Py_INCREF(ldict); - self->dict = ldict; - } + tdict = PyThreadState_GetDict(); + if (tdict == NULL) { + PyErr_SetString(PyExc_SystemError, + "Couldn't get thread-state dictionary"); + return NULL; + } + + ldict = PyDict_GetItem(tdict, self->key); + if (ldict == NULL) { + ldict = PyDict_New(); /* we own ldict */ + + if (ldict == NULL) + return NULL; + else { + int i = PyDict_SetItem(tdict, self->key, ldict); + Py_DECREF(ldict); /* now ldict is borrowed */ + if (i < 0) + return NULL; + } + + Py_CLEAR(self->dict); + Py_INCREF(ldict); + self->dict = ldict; /* still borrowed */ + + if (Py_TYPE(self)->tp_init != PyBaseObject_Type.tp_init && + Py_TYPE(self)->tp_init((PyObject*)self, + self->args, self->kw) < 0) { + /* we need to get rid of ldict from thread so + we create a new one the next time we do an attr + acces */ + PyDict_DelItem(tdict, self->key); + return NULL; + } + + } + + /* The call to tp_init above may have caused another thread to run. + Install our ldict again. */ + if (self->dict != ldict) { + Py_CLEAR(self->dict); + Py_INCREF(ldict); + self->dict = ldict; + } - return ldict; + return ldict; } static int local_setattro(localobject *self, PyObject *name, PyObject *v) { - PyObject *ldict; - - ldict = _ldict(self); - if (ldict == NULL) - return -1; + PyObject *ldict; - return PyObject_GenericSetAttr((PyObject *)self, name, v); + ldict = _ldict(self); + if (ldict == NULL) + return -1; + + return PyObject_GenericSetAttr((PyObject *)self, name, v); } static PyObject * local_getdict(localobject *self, void *closure) { - if (self->dict == NULL) { - PyErr_SetString(PyExc_AttributeError, "__dict__"); - return NULL; - } + if (self->dict == NULL) { + PyErr_SetString(PyExc_AttributeError, "__dict__"); + return NULL; + } - Py_INCREF(self->dict); - return self->dict; + Py_INCREF(self->dict); + return self->dict; } static PyGetSetDef local_getset[] = { - {"__dict__", (getter)local_getdict, (setter)NULL, - "Local-data dictionary", NULL}, - {NULL} /* Sentinel */ + {"__dict__", (getter)local_getdict, (setter)NULL, + "Local-data dictionary", NULL}, + {NULL} /* Sentinel */ }; static PyObject *local_getattro(localobject *, PyObject *); static PyTypeObject localtype = { - PyVarObject_HEAD_INIT(NULL, 0) - /* tp_name */ "_thread._local", - /* tp_basicsize */ sizeof(localobject), - /* tp_itemsize */ 0, - /* tp_dealloc */ (destructor)local_dealloc, - /* tp_print */ 0, - /* tp_getattr */ 0, - /* tp_setattr */ 0, - /* tp_reserved */ 0, - /* tp_repr */ 0, - /* tp_as_number */ 0, - /* tp_as_sequence */ 0, - /* tp_as_mapping */ 0, - /* tp_hash */ 0, - /* tp_call */ 0, - /* tp_str */ 0, - /* tp_getattro */ (getattrofunc)local_getattro, - /* tp_setattro */ (setattrofunc)local_setattro, - /* tp_as_buffer */ 0, - /* tp_flags */ Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, - /* tp_doc */ "Thread-local data", - /* tp_traverse */ (traverseproc)local_traverse, - /* tp_clear */ (inquiry)local_clear, - /* tp_richcompare */ 0, - /* tp_weaklistoffset */ 0, - /* tp_iter */ 0, - /* tp_iternext */ 0, - /* tp_methods */ 0, - /* tp_members */ 0, - /* tp_getset */ local_getset, - /* tp_base */ 0, - /* tp_dict */ 0, /* internal use */ - /* tp_descr_get */ 0, - /* tp_descr_set */ 0, - /* tp_dictoffset */ offsetof(localobject, dict), - /* tp_init */ 0, - /* tp_alloc */ 0, - /* tp_new */ local_new, - /* tp_free */ 0, /* Low-level free-mem routine */ - /* tp_is_gc */ 0, /* For PyObject_IS_GC */ + PyVarObject_HEAD_INIT(NULL, 0) + /* tp_name */ "_thread._local", + /* tp_basicsize */ sizeof(localobject), + /* tp_itemsize */ 0, + /* tp_dealloc */ (destructor)local_dealloc, + /* tp_print */ 0, + /* tp_getattr */ 0, + /* tp_setattr */ 0, + /* tp_reserved */ 0, + /* tp_repr */ 0, + /* tp_as_number */ 0, + /* tp_as_sequence */ 0, + /* tp_as_mapping */ 0, + /* tp_hash */ 0, + /* tp_call */ 0, + /* tp_str */ 0, + /* tp_getattro */ (getattrofunc)local_getattro, + /* tp_setattro */ (setattrofunc)local_setattro, + /* tp_as_buffer */ 0, + /* tp_flags */ Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, + /* tp_doc */ "Thread-local data", + /* tp_traverse */ (traverseproc)local_traverse, + /* tp_clear */ (inquiry)local_clear, + /* tp_richcompare */ 0, + /* tp_weaklistoffset */ 0, + /* tp_iter */ 0, + /* tp_iternext */ 0, + /* tp_methods */ 0, + /* tp_members */ 0, + /* tp_getset */ local_getset, + /* tp_base */ 0, + /* tp_dict */ 0, /* internal use */ + /* tp_descr_get */ 0, + /* tp_descr_set */ 0, + /* tp_dictoffset */ offsetof(localobject, dict), + /* tp_init */ 0, + /* tp_alloc */ 0, + /* tp_new */ local_new, + /* tp_free */ 0, /* Low-level free-mem routine */ + /* tp_is_gc */ 0, /* For PyObject_IS_GC */ }; static PyObject * local_getattro(localobject *self, PyObject *name) { - PyObject *ldict, *value; + PyObject *ldict, *value; - ldict = _ldict(self); - if (ldict == NULL) - return NULL; - - if (Py_TYPE(self) != &localtype) - /* use generic lookup for subtypes */ - return PyObject_GenericGetAttr((PyObject *)self, name); - - /* Optimization: just look in dict ourselves */ - value = PyDict_GetItem(ldict, name); - if (value == NULL) - /* Fall back on generic to get __class__ and __dict__ */ - return PyObject_GenericGetAttr((PyObject *)self, name); + ldict = _ldict(self); + if (ldict == NULL) + return NULL; + + if (Py_TYPE(self) != &localtype) + /* use generic lookup for subtypes */ + return PyObject_GenericGetAttr((PyObject *)self, name); + + /* Optimization: just look in dict ourselves */ + value = PyDict_GetItem(ldict, name); + if (value == NULL) + /* Fall back on generic to get __class__ and __dict__ */ + return PyObject_GenericGetAttr((PyObject *)self, name); - Py_INCREF(value); - return value; + Py_INCREF(value); + return value; } /* Module functions */ struct bootstate { - PyInterpreterState *interp; - PyObject *func; - PyObject *args; - PyObject *keyw; - PyThreadState *tstate; + PyInterpreterState *interp; + PyObject *func; + PyObject *args; + PyObject *keyw; + PyThreadState *tstate; }; static void t_bootstrap(void *boot_raw) { - struct bootstate *boot = (struct bootstate *) boot_raw; - PyThreadState *tstate; - PyObject *res; - - tstate = boot->tstate; - tstate->thread_id = PyThread_get_thread_ident(); - _PyThreadState_Init(tstate); - PyEval_AcquireThread(tstate); - nb_threads++; - res = PyEval_CallObjectWithKeywords( - boot->func, boot->args, boot->keyw); - if (res == NULL) { - if (PyErr_ExceptionMatches(PyExc_SystemExit)) - PyErr_Clear(); - else { - PyObject *file; - PySys_WriteStderr( - "Unhandled exception in thread started by "); - file = PySys_GetObject("stderr"); - if (file != NULL && file != Py_None) - PyFile_WriteObject(boot->func, file, 0); - else - PyObject_Print(boot->func, stderr, 0); - PySys_WriteStderr("\n"); - PyErr_PrintEx(0); - } - } - else - Py_DECREF(res); - Py_DECREF(boot->func); - Py_DECREF(boot->args); - Py_XDECREF(boot->keyw); - PyMem_DEL(boot_raw); - nb_threads--; - PyThreadState_Clear(tstate); - PyThreadState_DeleteCurrent(); - PyThread_exit_thread(); + struct bootstate *boot = (struct bootstate *) boot_raw; + PyThreadState *tstate; + PyObject *res; + + tstate = boot->tstate; + tstate->thread_id = PyThread_get_thread_ident(); + _PyThreadState_Init(tstate); + PyEval_AcquireThread(tstate); + nb_threads++; + res = PyEval_CallObjectWithKeywords( + boot->func, boot->args, boot->keyw); + if (res == NULL) { + if (PyErr_ExceptionMatches(PyExc_SystemExit)) + PyErr_Clear(); + else { + PyObject *file; + PySys_WriteStderr( + "Unhandled exception in thread started by "); + file = PySys_GetObject("stderr"); + if (file != NULL && file != Py_None) + PyFile_WriteObject(boot->func, file, 0); + else + PyObject_Print(boot->func, stderr, 0); + PySys_WriteStderr("\n"); + PyErr_PrintEx(0); + } + } + else + Py_DECREF(res); + Py_DECREF(boot->func); + Py_DECREF(boot->args); + Py_XDECREF(boot->keyw); + PyMem_DEL(boot_raw); + nb_threads--; + PyThreadState_Clear(tstate); + PyThreadState_DeleteCurrent(); + PyThread_exit_thread(); } static PyObject * thread_PyThread_start_new_thread(PyObject *self, PyObject *fargs) { - PyObject *func, *args, *keyw = NULL; - struct bootstate *boot; - long ident; - - if (!PyArg_UnpackTuple(fargs, "start_new_thread", 2, 3, - &func, &args, &keyw)) - return NULL; - if (!PyCallable_Check(func)) { - PyErr_SetString(PyExc_TypeError, - "first arg must be callable"); - return NULL; - } - if (!PyTuple_Check(args)) { - PyErr_SetString(PyExc_TypeError, - "2nd arg must be a tuple"); - return NULL; - } - if (keyw != NULL && !PyDict_Check(keyw)) { - PyErr_SetString(PyExc_TypeError, - "optional 3rd arg must be a dictionary"); - return NULL; - } - boot = PyMem_NEW(struct bootstate, 1); - if (boot == NULL) - return PyErr_NoMemory(); - boot->interp = PyThreadState_GET()->interp; - boot->func = func; - boot->args = args; - boot->keyw = keyw; - boot->tstate = _PyThreadState_Prealloc(boot->interp); - if (boot->tstate == NULL) { - PyMem_DEL(boot); - return PyErr_NoMemory(); - } - Py_INCREF(func); - Py_INCREF(args); - Py_XINCREF(keyw); - PyEval_InitThreads(); /* Start the interpreter's thread-awareness */ - ident = PyThread_start_new_thread(t_bootstrap, (void*) boot); - if (ident == -1) { - PyErr_SetString(ThreadError, "can't start new thread"); - Py_DECREF(func); - Py_DECREF(args); - Py_XDECREF(keyw); - PyThreadState_Clear(boot->tstate); - PyMem_DEL(boot); - return NULL; - } - return PyLong_FromLong(ident); + PyObject *func, *args, *keyw = NULL; + struct bootstate *boot; + long ident; + + if (!PyArg_UnpackTuple(fargs, "start_new_thread", 2, 3, + &func, &args, &keyw)) + return NULL; + if (!PyCallable_Check(func)) { + PyErr_SetString(PyExc_TypeError, + "first arg must be callable"); + return NULL; + } + if (!PyTuple_Check(args)) { + PyErr_SetString(PyExc_TypeError, + "2nd arg must be a tuple"); + return NULL; + } + if (keyw != NULL && !PyDict_Check(keyw)) { + PyErr_SetString(PyExc_TypeError, + "optional 3rd arg must be a dictionary"); + return NULL; + } + boot = PyMem_NEW(struct bootstate, 1); + if (boot == NULL) + return PyErr_NoMemory(); + boot->interp = PyThreadState_GET()->interp; + boot->func = func; + boot->args = args; + boot->keyw = keyw; + boot->tstate = _PyThreadState_Prealloc(boot->interp); + if (boot->tstate == NULL) { + PyMem_DEL(boot); + return PyErr_NoMemory(); + } + Py_INCREF(func); + Py_INCREF(args); + Py_XINCREF(keyw); + PyEval_InitThreads(); /* Start the interpreter's thread-awareness */ + ident = PyThread_start_new_thread(t_bootstrap, (void*) boot); + if (ident == -1) { + PyErr_SetString(ThreadError, "can't start new thread"); + Py_DECREF(func); + Py_DECREF(args); + Py_XDECREF(keyw); + PyThreadState_Clear(boot->tstate); + PyMem_DEL(boot); + return NULL; + } + return PyLong_FromLong(ident); } PyDoc_STRVAR(start_new_doc, @@ -863,8 +863,8 @@ static PyObject * thread_PyThread_exit_thread(PyObject *self) { - PyErr_SetNone(PyExc_SystemExit); - return NULL; + PyErr_SetNone(PyExc_SystemExit); + return NULL; } PyDoc_STRVAR(exit_doc, @@ -877,9 +877,9 @@ static PyObject * thread_PyThread_interrupt_main(PyObject * self) { - PyErr_SetInterrupt(); - Py_INCREF(Py_None); - return Py_None; + PyErr_SetInterrupt(); + Py_INCREF(Py_None); + return Py_None; } PyDoc_STRVAR(interrupt_doc, @@ -894,7 +894,7 @@ static PyObject * thread_PyThread_allocate_lock(PyObject *self) { - return (PyObject *) newlockobject(); + return (PyObject *) newlockobject(); } PyDoc_STRVAR(allocate_doc, @@ -906,13 +906,13 @@ static PyObject * thread_get_ident(PyObject *self) { - long ident; - ident = PyThread_get_thread_ident(); - if (ident == -1) { - PyErr_SetString(ThreadError, "no current thread ident"); - return NULL; - } - return PyLong_FromLong(ident); + long ident; + ident = PyThread_get_thread_ident(); + if (ident == -1) { + PyErr_SetString(ThreadError, "no current thread ident"); + return NULL; + } + return PyLong_FromLong(ident); } PyDoc_STRVAR(get_ident_doc, @@ -929,7 +929,7 @@ static PyObject * thread__count(PyObject *self) { - return PyLong_FromLong(nb_threads); + return PyLong_FromLong(nb_threads); } PyDoc_STRVAR(_count_doc, @@ -947,35 +947,35 @@ static PyObject * thread_stack_size(PyObject *self, PyObject *args) { - size_t old_size; - Py_ssize_t new_size = 0; - int rc; - - if (!PyArg_ParseTuple(args, "|n:stack_size", &new_size)) - return NULL; - - if (new_size < 0) { - PyErr_SetString(PyExc_ValueError, - "size must be 0 or a positive value"); - return NULL; - } - - old_size = PyThread_get_stacksize(); - - rc = PyThread_set_stacksize((size_t) new_size); - if (rc == -1) { - PyErr_Format(PyExc_ValueError, - "size not valid: %zd bytes", - new_size); - return NULL; - } - if (rc == -2) { - PyErr_SetString(ThreadError, - "setting stack size not supported"); - return NULL; - } + size_t old_size; + Py_ssize_t new_size = 0; + int rc; + + if (!PyArg_ParseTuple(args, "|n:stack_size", &new_size)) + return NULL; + + if (new_size < 0) { + PyErr_SetString(PyExc_ValueError, + "size must be 0 or a positive value"); + return NULL; + } + + old_size = PyThread_get_stacksize(); + + rc = PyThread_set_stacksize((size_t) new_size); + if (rc == -1) { + PyErr_Format(PyExc_ValueError, + "size not valid: %zd bytes", + new_size); + return NULL; + } + if (rc == -2) { + PyErr_SetString(ThreadError, + "setting stack size not supported"); + return NULL; + } - return PyLong_FromSsize_t((Py_ssize_t) old_size); + return PyLong_FromSsize_t((Py_ssize_t) old_size); } PyDoc_STRVAR(stack_size_doc, @@ -999,30 +999,30 @@ the suggested approach in the absence of more specific information)."); static PyMethodDef thread_methods[] = { - {"start_new_thread", (PyCFunction)thread_PyThread_start_new_thread, - METH_VARARGS, - start_new_doc}, - {"start_new", (PyCFunction)thread_PyThread_start_new_thread, - METH_VARARGS, - start_new_doc}, - {"allocate_lock", (PyCFunction)thread_PyThread_allocate_lock, - METH_NOARGS, allocate_doc}, - {"allocate", (PyCFunction)thread_PyThread_allocate_lock, - METH_NOARGS, allocate_doc}, - {"exit_thread", (PyCFunction)thread_PyThread_exit_thread, - METH_NOARGS, exit_doc}, - {"exit", (PyCFunction)thread_PyThread_exit_thread, - METH_NOARGS, exit_doc}, - {"interrupt_main", (PyCFunction)thread_PyThread_interrupt_main, - METH_NOARGS, interrupt_doc}, - {"get_ident", (PyCFunction)thread_get_ident, - METH_NOARGS, get_ident_doc}, - {"_count", (PyCFunction)thread__count, - METH_NOARGS, _count_doc}, - {"stack_size", (PyCFunction)thread_stack_size, - METH_VARARGS, - stack_size_doc}, - {NULL, NULL} /* sentinel */ + {"start_new_thread", (PyCFunction)thread_PyThread_start_new_thread, + METH_VARARGS, + start_new_doc}, + {"start_new", (PyCFunction)thread_PyThread_start_new_thread, + METH_VARARGS, + start_new_doc}, + {"allocate_lock", (PyCFunction)thread_PyThread_allocate_lock, + METH_NOARGS, allocate_doc}, + {"allocate", (PyCFunction)thread_PyThread_allocate_lock, + METH_NOARGS, allocate_doc}, + {"exit_thread", (PyCFunction)thread_PyThread_exit_thread, + METH_NOARGS, exit_doc}, + {"exit", (PyCFunction)thread_PyThread_exit_thread, + METH_NOARGS, exit_doc}, + {"interrupt_main", (PyCFunction)thread_PyThread_interrupt_main, + METH_NOARGS, interrupt_doc}, + {"get_ident", (PyCFunction)thread_get_ident, + METH_NOARGS, get_ident_doc}, + {"_count", (PyCFunction)thread__count, + METH_NOARGS, _count_doc}, + {"stack_size", (PyCFunction)thread_stack_size, + METH_VARARGS, + stack_size_doc}, + {NULL, NULL} /* sentinel */ }; @@ -1045,61 +1045,61 @@ will block until another thread unlocks it. Deadlocks may ensue."); static struct PyModuleDef threadmodule = { - PyModuleDef_HEAD_INIT, - "_thread", - thread_doc, - -1, - thread_methods, - NULL, - NULL, - NULL, - NULL + PyModuleDef_HEAD_INIT, + "_thread", + thread_doc, + -1, + thread_methods, + NULL, + NULL, + NULL, + NULL }; PyMODINIT_FUNC PyInit__thread(void) { - PyObject *m, *d, *timeout_max; - - /* Initialize types: */ - if (PyType_Ready(&localtype) < 0) - return NULL; - if (PyType_Ready(&Locktype) < 0) - return NULL; - if (PyType_Ready(&RLocktype) < 0) - return NULL; - - /* Create the module and add the functions */ - m = PyModule_Create(&threadmodule); - if (m == NULL) - return NULL; - - timeout_max = PyFloat_FromDouble(PY_TIMEOUT_MAX / 1000000); - if (!timeout_max) - return NULL; - if (PyModule_AddObject(m, "TIMEOUT_MAX", timeout_max) < 0) - return NULL; - - /* Add a symbolic constant */ - d = PyModule_GetDict(m); - ThreadError = PyErr_NewException("_thread.error", NULL, NULL); - PyDict_SetItemString(d, "error", ThreadError); - Locktype.tp_doc = lock_doc; - Py_INCREF(&Locktype); - PyDict_SetItemString(d, "LockType", (PyObject *)&Locktype); - - Py_INCREF(&RLocktype); - if (PyModule_AddObject(m, "RLock", (PyObject *)&RLocktype) < 0) - return NULL; - - Py_INCREF(&localtype); - if (PyModule_AddObject(m, "_local", (PyObject *)&localtype) < 0) - return NULL; - - nb_threads = 0; - - /* Initialize the C thread library */ - PyThread_init_thread(); - return m; + PyObject *m, *d, *timeout_max; + + /* Initialize types: */ + if (PyType_Ready(&localtype) < 0) + return NULL; + if (PyType_Ready(&Locktype) < 0) + return NULL; + if (PyType_Ready(&RLocktype) < 0) + return NULL; + + /* Create the module and add the functions */ + m = PyModule_Create(&threadmodule); + if (m == NULL) + return NULL; + + timeout_max = PyFloat_FromDouble(PY_TIMEOUT_MAX / 1000000); + if (!timeout_max) + return NULL; + if (PyModule_AddObject(m, "TIMEOUT_MAX", timeout_max) < 0) + return NULL; + + /* Add a symbolic constant */ + d = PyModule_GetDict(m); + ThreadError = PyErr_NewException("_thread.error", NULL, NULL); + PyDict_SetItemString(d, "error", ThreadError); + Locktype.tp_doc = lock_doc; + Py_INCREF(&Locktype); + PyDict_SetItemString(d, "LockType", (PyObject *)&Locktype); + + Py_INCREF(&RLocktype); + if (PyModule_AddObject(m, "RLock", (PyObject *)&RLocktype) < 0) + return NULL; + + Py_INCREF(&localtype); + if (PyModule_AddObject(m, "_local", (PyObject *)&localtype) < 0) + return NULL; + + nb_threads = 0; + + /* Initialize the C thread library */ + PyThread_init_thread(); + return m; } Modified: python/branches/py3k-jit/Modules/_tkinter.c ============================================================================== --- python/branches/py3k-jit/Modules/_tkinter.c (original) +++ python/branches/py3k-jit/Modules/_tkinter.c Mon May 10 23:55:43 2010 @@ -9,9 +9,9 @@ /* TCL/TK VERSION INFO: - Only Tcl/Tk 8.3.1 and later are supported. Older versions are not - supported. Use Python 2.6 or older if you cannot upgrade your - Tcl/Tk libraries. + Only Tcl/Tk 8.3.1 and later are supported. Older versions are not + supported. Use Python 2.6 or older if you cannot upgrade your + Tcl/Tk libraries. */ /* XXX Further speed-up ideas, involving Tcl 8.0 features: @@ -197,32 +197,32 @@ #endif #define ENTER_TCL \ - { PyThreadState *tstate = PyThreadState_Get(); Py_BEGIN_ALLOW_THREADS \ - if(tcl_lock)PyThread_acquire_lock(tcl_lock, 1); tcl_tstate = tstate; + { PyThreadState *tstate = PyThreadState_Get(); Py_BEGIN_ALLOW_THREADS \ + if(tcl_lock)PyThread_acquire_lock(tcl_lock, 1); tcl_tstate = tstate; #define LEAVE_TCL \ tcl_tstate = NULL; if(tcl_lock)PyThread_release_lock(tcl_lock); Py_END_ALLOW_THREADS} #define ENTER_OVERLAP \ - Py_END_ALLOW_THREADS + Py_END_ALLOW_THREADS #define LEAVE_OVERLAP_TCL \ - tcl_tstate = NULL; if(tcl_lock)PyThread_release_lock(tcl_lock); } + tcl_tstate = NULL; if(tcl_lock)PyThread_release_lock(tcl_lock); } #define ENTER_PYTHON \ - { PyThreadState *tstate = tcl_tstate; tcl_tstate = NULL; \ - if(tcl_lock)PyThread_release_lock(tcl_lock); PyEval_RestoreThread((tstate)); } + { PyThreadState *tstate = tcl_tstate; tcl_tstate = NULL; \ + if(tcl_lock)PyThread_release_lock(tcl_lock); PyEval_RestoreThread((tstate)); } #define LEAVE_PYTHON \ - { PyThreadState *tstate = PyEval_SaveThread(); \ - if(tcl_lock)PyThread_acquire_lock(tcl_lock, 1); tcl_tstate = tstate; } + { PyThreadState *tstate = PyEval_SaveThread(); \ + if(tcl_lock)PyThread_acquire_lock(tcl_lock, 1); tcl_tstate = tstate; } #define CHECK_TCL_APPARTMENT \ - if (((TkappObject *)self)->threaded && \ - ((TkappObject *)self)->thread_id != Tcl_GetCurrentThread()) { \ - PyErr_SetString(PyExc_RuntimeError, "Calling Tcl from different appartment"); \ - return 0; \ - } + if (((TkappObject *)self)->threaded && \ + ((TkappObject *)self)->thread_id != Tcl_GetCurrentThread()) { \ + PyErr_SetString(PyExc_RuntimeError, "Calling Tcl from different appartment"); \ + return 0; \ + } #else @@ -245,21 +245,21 @@ static PyTypeObject Tkapp_Type; typedef struct { - PyObject_HEAD - Tcl_Interp *interp; - int wantobjects; - int threaded; /* True if tcl_platform[threaded] */ - Tcl_ThreadId thread_id; - int dispatching; - /* We cannot include tclInt.h, as this is internal. - So we cache interesting types here. */ - Tcl_ObjType *BooleanType; - Tcl_ObjType *ByteArrayType; - Tcl_ObjType *DoubleType; - Tcl_ObjType *IntType; - Tcl_ObjType *ListType; - Tcl_ObjType *ProcBodyType; - Tcl_ObjType *StringType; + PyObject_HEAD + Tcl_Interp *interp; + int wantobjects; + int threaded; /* True if tcl_platform[threaded] */ + Tcl_ThreadId thread_id; + int dispatching; + /* We cannot include tclInt.h, as this is internal. + So we cache interesting types here. */ + Tcl_ObjType *BooleanType; + Tcl_ObjType *ByteArrayType; + Tcl_ObjType *DoubleType; + Tcl_ObjType *IntType; + Tcl_ObjType *ListType; + Tcl_ObjType *ProcBodyType; + Tcl_ObjType *StringType; } TkappObject; #define Tkapp_Check(v) (Py_TYPE(v) == &Tkapp_Type) @@ -270,7 +270,7 @@ (void *) v, Py_REFCNT(v))) - + /**** Error Handling ****/ static PyObject *Tkinter_TclError; @@ -284,16 +284,16 @@ static int tk_load_failed = 0; #endif - + static PyObject * Tkinter_Error(PyObject *v) { - PyErr_SetString(Tkinter_TclError, Tkapp_Result(v)); - return NULL; + PyErr_SetString(Tkinter_TclError, Tkapp_Result(v)); + return NULL; } - + /**** Utils ****/ static int Tkinter_busywaitinterval = 20; @@ -306,11 +306,11 @@ static void Sleep(int milli) { - /* XXX Too bad if you don't have select(). */ - struct timeval t; - t.tv_sec = milli/1000; - t.tv_usec = (milli%1000) * 1000; - select(0, (fd_set *)0, (fd_set *)0, (fd_set *)0, &t); + /* XXX Too bad if you don't have select(). */ + struct timeval t; + t.tv_sec = milli/1000; + t.tv_usec = (milli%1000) * 1000; + select(0, (fd_set *)0, (fd_set *)0, (fd_set *)0, &t); } #endif /* MS_WINDOWS */ @@ -319,172 +319,172 @@ static int WaitForMainloop(TkappObject* self) { - int i; - for (i = 0; i < 10; i++) { - if (self->dispatching) - return 1; - Py_BEGIN_ALLOW_THREADS - Sleep(100); - Py_END_ALLOW_THREADS - } - if (self->dispatching) - return 1; - PyErr_SetString(PyExc_RuntimeError, "main thread is not in main loop"); - return 0; + int i; + for (i = 0; i < 10; i++) { + if (self->dispatching) + return 1; + Py_BEGIN_ALLOW_THREADS + Sleep(100); + Py_END_ALLOW_THREADS + } + if (self->dispatching) + return 1; + PyErr_SetString(PyExc_RuntimeError, "main thread is not in main loop"); + return 0; } #endif /* WITH_THREAD */ - + static char * AsString(PyObject *value, PyObject *tmp) { - if (PyBytes_Check(value)) - return PyBytes_AsString(value); - else if (PyUnicode_Check(value)) { - PyObject *v = PyUnicode_AsUTF8String(value); - if (v == NULL) - return NULL; - if (PyList_Append(tmp, v) != 0) { - Py_DECREF(v); - return NULL; - } - Py_DECREF(v); - return PyBytes_AsString(v); - } - else { - PyObject *v = PyObject_Str(value); - if (v == NULL) - return NULL; - if (PyList_Append(tmp, v) != 0) { - Py_DECREF(v); - return NULL; - } - Py_DECREF(v); - return PyBytes_AsString(v); - } + if (PyBytes_Check(value)) + return PyBytes_AsString(value); + else if (PyUnicode_Check(value)) { + PyObject *v = PyUnicode_AsUTF8String(value); + if (v == NULL) + return NULL; + if (PyList_Append(tmp, v) != 0) { + Py_DECREF(v); + return NULL; + } + Py_DECREF(v); + return PyBytes_AsString(v); + } + else { + PyObject *v = PyObject_Str(value); + if (v == NULL) + return NULL; + if (PyList_Append(tmp, v) != 0) { + Py_DECREF(v); + return NULL; + } + Py_DECREF(v); + return PyBytes_AsString(v); + } } - + #define ARGSZ 64 static char * Merge(PyObject *args) { - PyObject *tmp = NULL; - char *argvStore[ARGSZ]; - char **argv = NULL; - int fvStore[ARGSZ]; - int *fv = NULL; - int argc = 0, fvc = 0, i; - char *res = NULL; - - if (!(tmp = PyList_New(0))) - return NULL; - - argv = argvStore; - fv = fvStore; - - if (args == NULL) - argc = 0; - - else if (!PyTuple_Check(args)) { - argc = 1; - fv[0] = 0; - if (!(argv[0] = AsString(args, tmp))) - goto finally; - } - else { - argc = PyTuple_Size(args); - - if (argc > ARGSZ) { - argv = (char **)ckalloc(argc * sizeof(char *)); - fv = (int *)ckalloc(argc * sizeof(int)); - if (argv == NULL || fv == NULL) { - PyErr_NoMemory(); - goto finally; - } - } - - for (i = 0; i < argc; i++) { - PyObject *v = PyTuple_GetItem(args, i); - if (PyTuple_Check(v)) { - fv[i] = 1; - if (!(argv[i] = Merge(v))) - goto finally; - fvc++; - } - else if (v == Py_None) { - argc = i; - break; - } - else { - fv[i] = 0; - if (!(argv[i] = AsString(v, tmp))) - goto finally; - fvc++; - } - } - } - res = Tcl_Merge(argc, argv); - if (res == NULL) - PyErr_SetString(Tkinter_TclError, "merge failed"); + PyObject *tmp = NULL; + char *argvStore[ARGSZ]; + char **argv = NULL; + int fvStore[ARGSZ]; + int *fv = NULL; + int argc = 0, fvc = 0, i; + char *res = NULL; + + if (!(tmp = PyList_New(0))) + return NULL; + + argv = argvStore; + fv = fvStore; + + if (args == NULL) + argc = 0; + + else if (!PyTuple_Check(args)) { + argc = 1; + fv[0] = 0; + if (!(argv[0] = AsString(args, tmp))) + goto finally; + } + else { + argc = PyTuple_Size(args); + + if (argc > ARGSZ) { + argv = (char **)ckalloc(argc * sizeof(char *)); + fv = (int *)ckalloc(argc * sizeof(int)); + if (argv == NULL || fv == NULL) { + PyErr_NoMemory(); + goto finally; + } + } + + for (i = 0; i < argc; i++) { + PyObject *v = PyTuple_GetItem(args, i); + if (PyTuple_Check(v)) { + fv[i] = 1; + if (!(argv[i] = Merge(v))) + goto finally; + fvc++; + } + else if (v == Py_None) { + argc = i; + break; + } + else { + fv[i] = 0; + if (!(argv[i] = AsString(v, tmp))) + goto finally; + fvc++; + } + } + } + res = Tcl_Merge(argc, argv); + if (res == NULL) + PyErr_SetString(Tkinter_TclError, "merge failed"); finally: - for (i = 0; i < fvc; i++) - if (fv[i]) { - ckfree(argv[i]); - } - if (argv != argvStore) - ckfree(FREECAST argv); - if (fv != fvStore) - ckfree(FREECAST fv); + for (i = 0; i < fvc; i++) + if (fv[i]) { + ckfree(argv[i]); + } + if (argv != argvStore) + ckfree(FREECAST argv); + if (fv != fvStore) + ckfree(FREECAST fv); - Py_DECREF(tmp); - return res; + Py_DECREF(tmp); + return res; } - + static PyObject * Split(char *list) { - int argc; - char **argv; - PyObject *v; - - if (list == NULL) { - Py_INCREF(Py_None); - return Py_None; - } - - if (Tcl_SplitList((Tcl_Interp *)NULL, list, &argc, &argv) != TCL_OK) { - /* Not a list. - * Could be a quoted string containing funnies, e.g. {"}. - * Return the string itself. - */ - return PyUnicode_FromString(list); - } - - if (argc == 0) - v = PyUnicode_FromString(""); - else if (argc == 1) - v = PyUnicode_FromString(argv[0]); - else if ((v = PyTuple_New(argc)) != NULL) { - int i; - PyObject *w; - - for (i = 0; i < argc; i++) { - if ((w = Split(argv[i])) == NULL) { - Py_DECREF(v); - v = NULL; - break; - } - PyTuple_SetItem(v, i, w); - } - } - Tcl_Free(FREECAST argv); - return v; + int argc; + char **argv; + PyObject *v; + + if (list == NULL) { + Py_INCREF(Py_None); + return Py_None; + } + + if (Tcl_SplitList((Tcl_Interp *)NULL, list, &argc, &argv) != TCL_OK) { + /* Not a list. + * Could be a quoted string containing funnies, e.g. {"}. + * Return the string itself. + */ + return PyUnicode_FromString(list); + } + + if (argc == 0) + v = PyUnicode_FromString(""); + else if (argc == 1) + v = PyUnicode_FromString(argv[0]); + else if ((v = PyTuple_New(argc)) != NULL) { + int i; + PyObject *w; + + for (i = 0; i < argc; i++) { + if ((w = Split(argv[i])) == NULL) { + Py_DECREF(v); + v = NULL; + break; + } + PyTuple_SetItem(v, i, w); + } + } + Tcl_Free(FREECAST argv); + return v; } /* In some cases, Tcl will still return strings that are supposed to be @@ -494,103 +494,103 @@ static PyObject * SplitObj(PyObject *arg) { - if (PyTuple_Check(arg)) { - int i, size; - PyObject *elem, *newelem, *result; - - size = PyTuple_Size(arg); - result = NULL; - /* Recursively invoke SplitObj for all tuple items. - If this does not return a new object, no action is - needed. */ - for(i = 0; i < size; i++) { - elem = PyTuple_GetItem(arg, i); - newelem = SplitObj(elem); - if (!newelem) { - Py_XDECREF(result); - return NULL; - } - if (!result) { - int k; - if (newelem == elem) { - Py_DECREF(newelem); - continue; - } - result = PyTuple_New(size); - if (!result) - return NULL; - for(k = 0; k < i; k++) { - elem = PyTuple_GetItem(arg, k); - Py_INCREF(elem); - PyTuple_SetItem(result, k, elem); - } - } - PyTuple_SetItem(result, i, newelem); - } - if (result) - return result; - /* Fall through, returning arg. */ - } - else if (PyBytes_Check(arg)) { - int argc; - char **argv; - char *list = PyBytes_AsString(arg); - - if (Tcl_SplitList((Tcl_Interp *)NULL, list, &argc, &argv) != TCL_OK) { - Py_INCREF(arg); - return arg; - } - Tcl_Free(FREECAST argv); - if (argc > 1) - return Split(PyBytes_AsString(arg)); - /* Fall through, returning arg. */ - } - Py_INCREF(arg); - return arg; + if (PyTuple_Check(arg)) { + int i, size; + PyObject *elem, *newelem, *result; + + size = PyTuple_Size(arg); + result = NULL; + /* Recursively invoke SplitObj for all tuple items. + If this does not return a new object, no action is + needed. */ + for(i = 0; i < size; i++) { + elem = PyTuple_GetItem(arg, i); + newelem = SplitObj(elem); + if (!newelem) { + Py_XDECREF(result); + return NULL; + } + if (!result) { + int k; + if (newelem == elem) { + Py_DECREF(newelem); + continue; + } + result = PyTuple_New(size); + if (!result) + return NULL; + for(k = 0; k < i; k++) { + elem = PyTuple_GetItem(arg, k); + Py_INCREF(elem); + PyTuple_SetItem(result, k, elem); + } + } + PyTuple_SetItem(result, i, newelem); + } + if (result) + return result; + /* Fall through, returning arg. */ + } + else if (PyBytes_Check(arg)) { + int argc; + char **argv; + char *list = PyBytes_AsString(arg); + + if (Tcl_SplitList((Tcl_Interp *)NULL, list, &argc, &argv) != TCL_OK) { + Py_INCREF(arg); + return arg; + } + Tcl_Free(FREECAST argv); + if (argc > 1) + return Split(PyBytes_AsString(arg)); + /* Fall through, returning arg. */ + } + Py_INCREF(arg); + return arg; } - + /**** Tkapp Object ****/ #ifndef WITH_APPINIT int Tcl_AppInit(Tcl_Interp *interp) { - const char * _tkinter_skip_tk_init; + const char * _tkinter_skip_tk_init; - if (Tcl_Init(interp) == TCL_ERROR) { - PySys_WriteStderr("Tcl_Init error: %s\n", Tcl_GetStringResult(interp)); - return TCL_ERROR; - } - - _tkinter_skip_tk_init = Tcl_GetVar(interp, - "_tkinter_skip_tk_init", TCL_GLOBAL_ONLY); - if (_tkinter_skip_tk_init != NULL && - strcmp(_tkinter_skip_tk_init, "1") == 0) { - return TCL_OK; - } + if (Tcl_Init(interp) == TCL_ERROR) { + PySys_WriteStderr("Tcl_Init error: %s\n", Tcl_GetStringResult(interp)); + return TCL_ERROR; + } + + _tkinter_skip_tk_init = Tcl_GetVar(interp, + "_tkinter_skip_tk_init", TCL_GLOBAL_ONLY); + if (_tkinter_skip_tk_init != NULL && + strcmp(_tkinter_skip_tk_init, "1") == 0) { + return TCL_OK; + } #ifdef TKINTER_PROTECT_LOADTK - if (tk_load_failed) { - PySys_WriteStderr("Tk_Init error: %s\n", TKINTER_LOADTK_ERRMSG); - return TCL_ERROR; - } + if (tk_load_failed) { + PySys_WriteStderr("Tk_Init error: %s\n", TKINTER_LOADTK_ERRMSG); + return TCL_ERROR; + } #endif - if (Tk_Init(interp) == TCL_ERROR) { + if (Tk_Init(interp) == TCL_ERROR) { #ifdef TKINTER_PROTECT_LOADTK - tk_load_failed = 1; + tk_load_failed = 1; #endif - PySys_WriteStderr("Tk_Init error: %s\n", Tcl_GetStringResult(interp)); - return TCL_ERROR; - } + PySys_WriteStderr("Tk_Init error: %s\n", Tcl_GetStringResult(interp)); + return TCL_ERROR; + } - return TCL_OK; + return TCL_OK; } #endif /* !WITH_APPINIT */ - + /* Initialize the Tk application; see the `main' function in * `tkMain.c'. @@ -601,189 +601,189 @@ static TkappObject * Tkapp_New(char *screenName, char *className, - int interactive, int wantobjects, int wantTk, int sync, char *use) + int interactive, int wantobjects, int wantTk, int sync, char *use) { - TkappObject *v; - char *argv0; + TkappObject *v; + char *argv0; - v = PyObject_New(TkappObject, &Tkapp_Type); - if (v == NULL) - return NULL; - - v->interp = Tcl_CreateInterp(); - v->wantobjects = wantobjects; - v->threaded = Tcl_GetVar2Ex(v->interp, "tcl_platform", "threaded", - TCL_GLOBAL_ONLY) != NULL; - v->thread_id = Tcl_GetCurrentThread(); - v->dispatching = 0; + v = PyObject_New(TkappObject, &Tkapp_Type); + if (v == NULL) + return NULL; + + v->interp = Tcl_CreateInterp(); + v->wantobjects = wantobjects; + v->threaded = Tcl_GetVar2Ex(v->interp, "tcl_platform", "threaded", + TCL_GLOBAL_ONLY) != NULL; + v->thread_id = Tcl_GetCurrentThread(); + v->dispatching = 0; #ifndef TCL_THREADS - if (v->threaded) { - PyErr_SetString(PyExc_RuntimeError, "Tcl is threaded but _tkinter is not"); - Py_DECREF(v); - return 0; - } -#endif -#ifdef WITH_THREAD - if (v->threaded && tcl_lock) { - /* If Tcl is threaded, we don't need the lock. */ - PyThread_free_lock(tcl_lock); - tcl_lock = NULL; - } -#endif - - v->BooleanType = Tcl_GetObjType("boolean"); - v->ByteArrayType = Tcl_GetObjType("bytearray"); - v->DoubleType = Tcl_GetObjType("double"); - v->IntType = Tcl_GetObjType("int"); - v->ListType = Tcl_GetObjType("list"); - v->ProcBodyType = Tcl_GetObjType("procbody"); - v->StringType = Tcl_GetObjType("string"); - - /* Delete the 'exit' command, which can screw things up */ - Tcl_DeleteCommand(v->interp, "exit"); - - if (screenName != NULL) - Tcl_SetVar2(v->interp, "env", "DISPLAY", - screenName, TCL_GLOBAL_ONLY); - - if (interactive) - Tcl_SetVar(v->interp, "tcl_interactive", "1", TCL_GLOBAL_ONLY); - else - Tcl_SetVar(v->interp, "tcl_interactive", "0", TCL_GLOBAL_ONLY); - - /* This is used to get the application class for Tk 4.1 and up */ - argv0 = (char*)ckalloc(strlen(className) + 1); - if (!argv0) { - PyErr_NoMemory(); - Py_DECREF(v); - return NULL; - } - - strcpy(argv0, className); - if (isupper(Py_CHARMASK(argv0[0]))) - argv0[0] = tolower(Py_CHARMASK(argv0[0])); - Tcl_SetVar(v->interp, "argv0", argv0, TCL_GLOBAL_ONLY); - ckfree(argv0); - - if (! wantTk) { - Tcl_SetVar(v->interp, - "_tkinter_skip_tk_init", "1", TCL_GLOBAL_ONLY); - } + if (v->threaded) { + PyErr_SetString(PyExc_RuntimeError, "Tcl is threaded but _tkinter is not"); + Py_DECREF(v); + return 0; + } +#endif +#ifdef WITH_THREAD + if (v->threaded && tcl_lock) { + /* If Tcl is threaded, we don't need the lock. */ + PyThread_free_lock(tcl_lock); + tcl_lock = NULL; + } +#endif + + v->BooleanType = Tcl_GetObjType("boolean"); + v->ByteArrayType = Tcl_GetObjType("bytearray"); + v->DoubleType = Tcl_GetObjType("double"); + v->IntType = Tcl_GetObjType("int"); + v->ListType = Tcl_GetObjType("list"); + v->ProcBodyType = Tcl_GetObjType("procbody"); + v->StringType = Tcl_GetObjType("string"); + + /* Delete the 'exit' command, which can screw things up */ + Tcl_DeleteCommand(v->interp, "exit"); + + if (screenName != NULL) + Tcl_SetVar2(v->interp, "env", "DISPLAY", + screenName, TCL_GLOBAL_ONLY); + + if (interactive) + Tcl_SetVar(v->interp, "tcl_interactive", "1", TCL_GLOBAL_ONLY); + else + Tcl_SetVar(v->interp, "tcl_interactive", "0", TCL_GLOBAL_ONLY); + + /* This is used to get the application class for Tk 4.1 and up */ + argv0 = (char*)ckalloc(strlen(className) + 1); + if (!argv0) { + PyErr_NoMemory(); + Py_DECREF(v); + return NULL; + } + + strcpy(argv0, className); + if (isupper(Py_CHARMASK(argv0[0]))) + argv0[0] = tolower(Py_CHARMASK(argv0[0])); + Tcl_SetVar(v->interp, "argv0", argv0, TCL_GLOBAL_ONLY); + ckfree(argv0); + + if (! wantTk) { + Tcl_SetVar(v->interp, + "_tkinter_skip_tk_init", "1", TCL_GLOBAL_ONLY); + } #ifdef TKINTER_PROTECT_LOADTK - else if (tk_load_failed) { - Tcl_SetVar(v->interp, - "_tkinter_tk_failed", "1", TCL_GLOBAL_ONLY); - } -#endif - - /* some initial arguments need to be in argv */ - if (sync || use) { - char *args; - int len = 0; - - if (sync) - len += sizeof "-sync"; - if (use) - len += strlen(use) + sizeof "-use "; - - args = (char*)ckalloc(len); - if (!args) { - PyErr_NoMemory(); - Py_DECREF(v); - return NULL; - } - - args[0] = '\0'; - if (sync) - strcat(args, "-sync"); - if (use) { - if (sync) - strcat(args, " "); - strcat(args, "-use "); - strcat(args, use); - } - - Tcl_SetVar(v->interp, "argv", args, TCL_GLOBAL_ONLY); - ckfree(args); - } + else if (tk_load_failed) { + Tcl_SetVar(v->interp, + "_tkinter_tk_failed", "1", TCL_GLOBAL_ONLY); + } +#endif + + /* some initial arguments need to be in argv */ + if (sync || use) { + char *args; + int len = 0; + + if (sync) + len += sizeof "-sync"; + if (use) + len += strlen(use) + sizeof "-use "; + + args = (char*)ckalloc(len); + if (!args) { + PyErr_NoMemory(); + Py_DECREF(v); + return NULL; + } + + args[0] = '\0'; + if (sync) + strcat(args, "-sync"); + if (use) { + if (sync) + strcat(args, " "); + strcat(args, "-use "); + strcat(args, use); + } + + Tcl_SetVar(v->interp, "argv", args, TCL_GLOBAL_ONLY); + ckfree(args); + } - if (Tcl_AppInit(v->interp) != TCL_OK) { - PyObject *result = Tkinter_Error((PyObject *)v); + if (Tcl_AppInit(v->interp) != TCL_OK) { + PyObject *result = Tkinter_Error((PyObject *)v); #ifdef TKINTER_PROTECT_LOADTK - if (wantTk) { - const char *_tkinter_tk_failed; - _tkinter_tk_failed = Tcl_GetVar(v->interp, - "_tkinter_tk_failed", TCL_GLOBAL_ONLY); - - if ( _tkinter_tk_failed != NULL && - strcmp(_tkinter_tk_failed, "1") == 0) { - tk_load_failed = 1; - } - } -#endif - Py_DECREF((PyObject *)v); - return (TkappObject *)result; - } + if (wantTk) { + const char *_tkinter_tk_failed; + _tkinter_tk_failed = Tcl_GetVar(v->interp, + "_tkinter_tk_failed", TCL_GLOBAL_ONLY); + + if ( _tkinter_tk_failed != NULL && + strcmp(_tkinter_tk_failed, "1") == 0) { + tk_load_failed = 1; + } + } +#endif + Py_DECREF((PyObject *)v); + return (TkappObject *)result; + } - EnableEventHook(); + EnableEventHook(); - return v; + return v; } #ifdef WITH_THREAD static void Tkapp_ThreadSend(TkappObject *self, Tcl_Event *ev, - Tcl_Condition *cond, Tcl_Mutex *mutex) + Tcl_Condition *cond, Tcl_Mutex *mutex) { - Py_BEGIN_ALLOW_THREADS; - Tcl_MutexLock(mutex); - Tcl_ThreadQueueEvent(self->thread_id, ev, TCL_QUEUE_TAIL); - Tcl_ThreadAlert(self->thread_id); - Tcl_ConditionWait(cond, mutex, NULL); - Tcl_MutexUnlock(mutex); - Py_END_ALLOW_THREADS + Py_BEGIN_ALLOW_THREADS; + Tcl_MutexLock(mutex); + Tcl_ThreadQueueEvent(self->thread_id, ev, TCL_QUEUE_TAIL); + Tcl_ThreadAlert(self->thread_id); + Tcl_ConditionWait(cond, mutex, NULL); + Tcl_MutexUnlock(mutex); + Py_END_ALLOW_THREADS } #endif - + /** Tcl Eval **/ typedef struct { - PyObject_HEAD - Tcl_Obj *value; - PyObject *string; /* This cannot cause cycles. */ + PyObject_HEAD + Tcl_Obj *value; + PyObject *string; /* This cannot cause cycles. */ } PyTclObject; static PyTypeObject PyTclObject_Type; -#define PyTclObject_Check(v) ((v)->ob_type == &PyTclObject_Type) +#define PyTclObject_Check(v) ((v)->ob_type == &PyTclObject_Type) static PyObject * newPyTclObject(Tcl_Obj *arg) { - PyTclObject *self; - self = PyObject_New(PyTclObject, &PyTclObject_Type); - if (self == NULL) - return NULL; - Tcl_IncrRefCount(arg); - self->value = arg; - self->string = NULL; - return (PyObject*)self; + PyTclObject *self; + self = PyObject_New(PyTclObject, &PyTclObject_Type); + if (self == NULL) + return NULL; + Tcl_IncrRefCount(arg); + self->value = arg; + self->string = NULL; + return (PyObject*)self; } static void PyTclObject_dealloc(PyTclObject *self) { - Tcl_DecrRefCount(self->value); - Py_XDECREF(self->string); - PyObject_Del(self); + Tcl_DecrRefCount(self->value); + Py_XDECREF(self->string); + PyObject_Del(self); } static char* PyTclObject_TclString(PyObject *self) { - return Tcl_GetString(((PyTclObject*)self)->value); + return Tcl_GetString(((PyTclObject*)self)->value); } /* Like _str, but create Unicode if necessary. */ @@ -793,37 +793,37 @@ static PyObject * PyTclObject_string(PyTclObject *self, void *ignored) { - char *s; - int len; - if (!self->string) { - s = Tcl_GetStringFromObj(self->value, &len); - self->string = PyUnicode_FromStringAndSize(s, len); - if (!self->string) - return NULL; - } - Py_INCREF(self->string); - return self->string; + char *s; + int len; + if (!self->string) { + s = Tcl_GetStringFromObj(self->value, &len); + self->string = PyUnicode_FromStringAndSize(s, len); + if (!self->string) + return NULL; + } + Py_INCREF(self->string); + return self->string; } static PyObject * PyTclObject_str(PyTclObject *self, void *ignored) { - char *s; - int len; - if (self->string && PyUnicode_Check(self->string)) { - Py_INCREF(self->string); - return self->string; - } - /* XXX Could chache result if it is non-ASCII. */ - s = Tcl_GetStringFromObj(self->value, &len); - return PyUnicode_DecodeUTF8(s, len, "strict"); + char *s; + int len; + if (self->string && PyUnicode_Check(self->string)) { + Py_INCREF(self->string); + return self->string; + } + /* XXX Could chache result if it is non-ASCII. */ + s = Tcl_GetStringFromObj(self->value, &len); + return PyUnicode_DecodeUTF8(s, len, "strict"); } static PyObject * PyTclObject_repr(PyTclObject *self) { - return PyUnicode_FromFormat("<%s object at %p>", - self->value->typePtr->name, self->value); + return PyUnicode_FromFormat("<%s object at %p>", + self->value->typePtr->name, self->value); } #define TEST_COND(cond) ((cond) ? Py_True : Py_False) @@ -831,54 +831,54 @@ static PyObject * PyTclObject_richcompare(PyObject *self, PyObject *other, int op) { - int result; - PyObject *v; + int result; + PyObject *v; - /* neither argument should be NULL, unless something's gone wrong */ - if (self == NULL || other == NULL) { - PyErr_BadInternalCall(); - return NULL; - } - - /* both arguments should be instances of PyTclObject */ - if (!PyTclObject_Check(self) || !PyTclObject_Check(other)) { - v = Py_NotImplemented; - goto finished; - } - - if (self == other) - /* fast path when self and other are identical */ - result = 0; - else - result = strcmp(Tcl_GetString(((PyTclObject *)self)->value), - Tcl_GetString(((PyTclObject *)other)->value)); - /* Convert return value to a Boolean */ - switch (op) { - case Py_EQ: - v = TEST_COND(result == 0); - break; - case Py_NE: - v = TEST_COND(result != 0); - break; - case Py_LE: - v = TEST_COND(result <= 0); - break; - case Py_GE: - v = TEST_COND(result >= 0); - break; - case Py_LT: - v = TEST_COND(result < 0); - break; - case Py_GT: - v = TEST_COND(result > 0); - break; - default: - PyErr_BadArgument(); - return NULL; - } + /* neither argument should be NULL, unless something's gone wrong */ + if (self == NULL || other == NULL) { + PyErr_BadInternalCall(); + return NULL; + } + + /* both arguments should be instances of PyTclObject */ + if (!PyTclObject_Check(self) || !PyTclObject_Check(other)) { + v = Py_NotImplemented; + goto finished; + } + + if (self == other) + /* fast path when self and other are identical */ + result = 0; + else + result = strcmp(Tcl_GetString(((PyTclObject *)self)->value), + Tcl_GetString(((PyTclObject *)other)->value)); + /* Convert return value to a Boolean */ + switch (op) { + case Py_EQ: + v = TEST_COND(result == 0); + break; + case Py_NE: + v = TEST_COND(result != 0); + break; + case Py_LE: + v = TEST_COND(result <= 0); + break; + case Py_GE: + v = TEST_COND(result >= 0); + break; + case Py_LT: + v = TEST_COND(result < 0); + break; + case Py_GT: + v = TEST_COND(result > 0); + break; + default: + PyErr_BadArgument(); + return NULL; + } finished: - Py_INCREF(v); - return v; + Py_INCREF(v); + return v; } PyDoc_STRVAR(get_typename__doc__, "name of the Tcl type"); @@ -886,230 +886,230 @@ static PyObject* get_typename(PyTclObject* obj, void* ignored) { - return PyUnicode_FromString(obj->value->typePtr->name); + return PyUnicode_FromString(obj->value->typePtr->name); } static PyGetSetDef PyTclObject_getsetlist[] = { - {"typename", (getter)get_typename, NULL, get_typename__doc__}, - {"string", (getter)PyTclObject_string, NULL, - PyTclObject_string__doc__}, - {0}, + {"typename", (getter)get_typename, NULL, get_typename__doc__}, + {"string", (getter)PyTclObject_string, NULL, + PyTclObject_string__doc__}, + {0}, }; static PyTypeObject PyTclObject_Type = { - PyVarObject_HEAD_INIT(NULL, 0) - "_tkinter.Tcl_Obj", /*tp_name*/ - sizeof(PyTclObject), /*tp_basicsize*/ - 0, /*tp_itemsize*/ - /* methods */ - (destructor)PyTclObject_dealloc,/*tp_dealloc*/ - 0, /*tp_print*/ - 0, /*tp_getattr*/ - 0, /*tp_setattr*/ - 0, /*tp_reserved*/ - (reprfunc)PyTclObject_repr, /*tp_repr*/ - 0, /*tp_as_number*/ - 0, /*tp_as_sequence*/ - 0, /*tp_as_mapping*/ - 0, /*tp_hash*/ - 0, /*tp_call*/ - (reprfunc)PyTclObject_str, /*tp_str*/ - PyObject_GenericGetAttr, /*tp_getattro*/ - 0, /*tp_setattro*/ - 0, /*tp_as_buffer*/ - Py_TPFLAGS_DEFAULT, /*tp_flags*/ - 0, /*tp_doc*/ - 0, /*tp_traverse*/ - 0, /*tp_clear*/ - PyTclObject_richcompare, /*tp_richcompare*/ - 0, /*tp_weaklistoffset*/ - 0, /*tp_iter*/ - 0, /*tp_iternext*/ - 0, /*tp_methods*/ - 0, /*tp_members*/ - PyTclObject_getsetlist, /*tp_getset*/ - 0, /*tp_base*/ - 0, /*tp_dict*/ - 0, /*tp_descr_get*/ - 0, /*tp_descr_set*/ - 0, /*tp_dictoffset*/ - 0, /*tp_init*/ - 0, /*tp_alloc*/ - 0, /*tp_new*/ - 0, /*tp_free*/ - 0, /*tp_is_gc*/ + PyVarObject_HEAD_INIT(NULL, 0) + "_tkinter.Tcl_Obj", /*tp_name*/ + sizeof(PyTclObject), /*tp_basicsize*/ + 0, /*tp_itemsize*/ + /* methods */ + (destructor)PyTclObject_dealloc,/*tp_dealloc*/ + 0, /*tp_print*/ + 0, /*tp_getattr*/ + 0, /*tp_setattr*/ + 0, /*tp_reserved*/ + (reprfunc)PyTclObject_repr, /*tp_repr*/ + 0, /*tp_as_number*/ + 0, /*tp_as_sequence*/ + 0, /*tp_as_mapping*/ + 0, /*tp_hash*/ + 0, /*tp_call*/ + (reprfunc)PyTclObject_str, /*tp_str*/ + PyObject_GenericGetAttr, /*tp_getattro*/ + 0, /*tp_setattro*/ + 0, /*tp_as_buffer*/ + Py_TPFLAGS_DEFAULT, /*tp_flags*/ + 0, /*tp_doc*/ + 0, /*tp_traverse*/ + 0, /*tp_clear*/ + PyTclObject_richcompare, /*tp_richcompare*/ + 0, /*tp_weaklistoffset*/ + 0, /*tp_iter*/ + 0, /*tp_iternext*/ + 0, /*tp_methods*/ + 0, /*tp_members*/ + PyTclObject_getsetlist, /*tp_getset*/ + 0, /*tp_base*/ + 0, /*tp_dict*/ + 0, /*tp_descr_get*/ + 0, /*tp_descr_set*/ + 0, /*tp_dictoffset*/ + 0, /*tp_init*/ + 0, /*tp_alloc*/ + 0, /*tp_new*/ + 0, /*tp_free*/ + 0, /*tp_is_gc*/ }; static Tcl_Obj* AsObj(PyObject *value) { - Tcl_Obj *result; - long longVal; - int overflow; - - if (PyBytes_Check(value)) - return Tcl_NewStringObj(PyBytes_AS_STRING(value), - PyBytes_GET_SIZE(value)); - else if (PyBool_Check(value)) - return Tcl_NewBooleanObj(PyObject_IsTrue(value)); - else if (PyLong_CheckExact(value) && - ((longVal = PyLong_AsLongAndOverflow(value, &overflow)), - !overflow)) { - /* If there is an overflow in the long conversion, - fall through to default object handling. */ - return Tcl_NewLongObj(longVal); - } - else if (PyFloat_Check(value)) - return Tcl_NewDoubleObj(PyFloat_AS_DOUBLE(value)); - else if (PyTuple_Check(value)) { - Tcl_Obj **argv = (Tcl_Obj**) - ckalloc(PyTuple_Size(value)*sizeof(Tcl_Obj*)); - int i; - if(!argv) - return 0; - for(i=0;i= size) - outbuf = (Tcl_UniChar*)ckalloc(allocsize); - /* Else overflow occurred, and we take the next exit */ - if (!outbuf) { - PyErr_NoMemory(); - return NULL; - } - for (i = 0; i < size; i++) { - if (inbuf[i] >= 0x10000) { - /* Tcl doesn't do UTF-16, yet. */ - PyErr_SetString(PyExc_ValueError, - "unsupported character"); - ckfree(FREECAST outbuf); - return NULL; - } - outbuf[i] = inbuf[i]; - } - result = Tcl_NewUnicodeObj(outbuf, size); - ckfree(FREECAST outbuf); - return result; + Tcl_UniChar *outbuf = NULL; + Py_ssize_t i; + size_t allocsize = ((size_t)size) * sizeof(Tcl_UniChar); + if (allocsize >= size) + outbuf = (Tcl_UniChar*)ckalloc(allocsize); + /* Else overflow occurred, and we take the next exit */ + if (!outbuf) { + PyErr_NoMemory(); + return NULL; + } + for (i = 0; i < size; i++) { + if (inbuf[i] >= 0x10000) { + /* Tcl doesn't do UTF-16, yet. */ + PyErr_SetString(PyExc_ValueError, + "unsupported character"); + ckfree(FREECAST outbuf); + return NULL; + } + outbuf[i] = inbuf[i]; + } + result = Tcl_NewUnicodeObj(outbuf, size); + ckfree(FREECAST outbuf); + return result; #else - return Tcl_NewUnicodeObj(inbuf, size); + return Tcl_NewUnicodeObj(inbuf, size); #endif - } - else if(PyTclObject_Check(value)) { - Tcl_Obj *v = ((PyTclObject*)value)->value; - Tcl_IncrRefCount(v); - return v; - } - else { - PyObject *v = PyObject_Str(value); - if (!v) - return 0; - result = AsObj(v); - Py_DECREF(v); - return result; - } + } + else if(PyTclObject_Check(value)) { + Tcl_Obj *v = ((PyTclObject*)value)->value; + Tcl_IncrRefCount(v); + return v; + } + else { + PyObject *v = PyObject_Str(value); + if (!v) + return 0; + result = AsObj(v); + Py_DECREF(v); + return result; + } } static PyObject* FromObj(PyObject* tkapp, Tcl_Obj *value) { - PyObject *result = NULL; - TkappObject *app = (TkappObject*)tkapp; + PyObject *result = NULL; + TkappObject *app = (TkappObject*)tkapp; - if (value->typePtr == NULL) { - return PyUnicode_FromStringAndSize(value->bytes, - value->length); - } - - if (value->typePtr == app->BooleanType) { - result = value->internalRep.longValue ? Py_True : Py_False; - Py_INCREF(result); - return result; - } - - if (value->typePtr == app->ByteArrayType) { - int size; - char *data = (char*)Tcl_GetByteArrayFromObj(value, &size); - return PyBytes_FromStringAndSize(data, size); - } - - if (value->typePtr == app->DoubleType) { - return PyFloat_FromDouble(value->internalRep.doubleValue); - } - - if (value->typePtr == app->IntType) { - return PyLong_FromLong(value->internalRep.longValue); - } - - if (value->typePtr == app->ListType) { - int size; - int i, status; - PyObject *elem; - Tcl_Obj *tcl_elem; - - status = Tcl_ListObjLength(Tkapp_Interp(tkapp), value, &size); - if (status == TCL_ERROR) - return Tkinter_Error(tkapp); - result = PyTuple_New(size); - if (!result) - return NULL; - for (i = 0; i < size; i++) { - status = Tcl_ListObjIndex(Tkapp_Interp(tkapp), - value, i, &tcl_elem); - if (status == TCL_ERROR) { - Py_DECREF(result); - return Tkinter_Error(tkapp); - } - elem = FromObj(tkapp, tcl_elem); - if (!elem) { - Py_DECREF(result); - return NULL; - } - PyTuple_SetItem(result, i, elem); - } - return result; - } - - if (value->typePtr == app->ProcBodyType) { - /* fall through: return tcl object. */ - } + if (value->typePtr == NULL) { + return PyUnicode_FromStringAndSize(value->bytes, + value->length); + } + + if (value->typePtr == app->BooleanType) { + result = value->internalRep.longValue ? Py_True : Py_False; + Py_INCREF(result); + return result; + } + + if (value->typePtr == app->ByteArrayType) { + int size; + char *data = (char*)Tcl_GetByteArrayFromObj(value, &size); + return PyBytes_FromStringAndSize(data, size); + } + + if (value->typePtr == app->DoubleType) { + return PyFloat_FromDouble(value->internalRep.doubleValue); + } + + if (value->typePtr == app->IntType) { + return PyLong_FromLong(value->internalRep.longValue); + } + + if (value->typePtr == app->ListType) { + int size; + int i, status; + PyObject *elem; + Tcl_Obj *tcl_elem; + + status = Tcl_ListObjLength(Tkapp_Interp(tkapp), value, &size); + if (status == TCL_ERROR) + return Tkinter_Error(tkapp); + result = PyTuple_New(size); + if (!result) + return NULL; + for (i = 0; i < size; i++) { + status = Tcl_ListObjIndex(Tkapp_Interp(tkapp), + value, i, &tcl_elem); + if (status == TCL_ERROR) { + Py_DECREF(result); + return Tkinter_Error(tkapp); + } + elem = FromObj(tkapp, tcl_elem); + if (!elem) { + Py_DECREF(result); + return NULL; + } + PyTuple_SetItem(result, i, elem); + } + return result; + } + + if (value->typePtr == app->ProcBodyType) { + /* fall through: return tcl object. */ + } - if (value->typePtr == app->StringType) { + if (value->typePtr == app->StringType) { #if defined(Py_UNICODE_WIDE) && TCL_UTF_MAX==3 - PyObject *result; - int size; - Tcl_UniChar *input; - Py_UNICODE *output; - - size = Tcl_GetCharLength(value); - result = PyUnicode_FromUnicode(NULL, size); - if (!result) - return NULL; - input = Tcl_GetUnicode(value); - output = PyUnicode_AS_UNICODE(result); - while (size--) - *output++ = *input++; - return result; + PyObject *result; + int size; + Tcl_UniChar *input; + Py_UNICODE *output; + + size = Tcl_GetCharLength(value); + result = PyUnicode_FromUnicode(NULL, size); + if (!result) + return NULL; + input = Tcl_GetUnicode(value); + output = PyUnicode_AS_UNICODE(result); + while (size--) + *output++ = *input++; + return result; #else - return PyUnicode_FromUnicode(Tcl_GetUnicode(value), - Tcl_GetCharLength(value)); + return PyUnicode_FromUnicode(Tcl_GetUnicode(value), + Tcl_GetCharLength(value)); #endif - } + } - return newPyTclObject(value); + return newPyTclObject(value); } #ifdef WITH_THREAD @@ -1117,24 +1117,24 @@ TCL_DECLARE_MUTEX(call_mutex) typedef struct Tkapp_CallEvent { - Tcl_Event ev; /* Must be first */ - TkappObject *self; - PyObject *args; - int flags; - PyObject **res; - PyObject **exc_type, **exc_value, **exc_tb; - Tcl_Condition *done; + Tcl_Event ev; /* Must be first */ + TkappObject *self; + PyObject *args; + int flags; + PyObject **res; + PyObject **exc_type, **exc_value, **exc_tb; + Tcl_Condition *done; } Tkapp_CallEvent; #endif void Tkapp_CallDeallocArgs(Tcl_Obj** objv, Tcl_Obj** objStore, int objc) { - int i; - for (i = 0; i < objc; i++) - Tcl_DecrRefCount(objv[i]); - if (objv != objStore) - ckfree(FREECAST objv); + int i; + for (i = 0; i < objc; i++) + Tcl_DecrRefCount(objv[i]); + if (objv != objStore) + ckfree(FREECAST objv); } /* Convert Python objects to Tcl objects. This must happen in the @@ -1143,51 +1143,51 @@ static Tcl_Obj** Tkapp_CallArgs(PyObject *args, Tcl_Obj** objStore, int *pobjc) { - Tcl_Obj **objv = objStore; - int objc = 0, i; - if (args == NULL) - /* do nothing */; - - else if (!PyTuple_Check(args)) { - objv[0] = AsObj(args); - if (objv[0] == 0) - goto finally; - objc = 1; - Tcl_IncrRefCount(objv[0]); - } - else { - objc = PyTuple_Size(args); - - if (objc > ARGSZ) { - objv = (Tcl_Obj **)ckalloc(objc * sizeof(char *)); - if (objv == NULL) { - PyErr_NoMemory(); - objc = 0; - goto finally; - } - } - - for (i = 0; i < objc; i++) { - PyObject *v = PyTuple_GetItem(args, i); - if (v == Py_None) { - objc = i; - break; - } - objv[i] = AsObj(v); - if (!objv[i]) { - /* Reset objc, so it attempts to clear - objects only up to i. */ - objc = i; - goto finally; - } - Tcl_IncrRefCount(objv[i]); - } - } - *pobjc = objc; - return objv; + Tcl_Obj **objv = objStore; + int objc = 0, i; + if (args == NULL) + /* do nothing */; + + else if (!PyTuple_Check(args)) { + objv[0] = AsObj(args); + if (objv[0] == 0) + goto finally; + objc = 1; + Tcl_IncrRefCount(objv[0]); + } + else { + objc = PyTuple_Size(args); + + if (objc > ARGSZ) { + objv = (Tcl_Obj **)ckalloc(objc * sizeof(char *)); + if (objv == NULL) { + PyErr_NoMemory(); + objc = 0; + goto finally; + } + } + + for (i = 0; i < objc; i++) { + PyObject *v = PyTuple_GetItem(args, i); + if (v == Py_None) { + objc = i; + break; + } + objv[i] = AsObj(v); + if (!objv[i]) { + /* Reset objc, so it attempts to clear + objects only up to i. */ + objc = i; + goto finally; + } + Tcl_IncrRefCount(objv[i]); + } + } + *pobjc = objc; + return objv; finally: - Tkapp_CallDeallocArgs(objv, objStore, objc); - return NULL; + Tkapp_CallDeallocArgs(objv, objStore, objc); + return NULL; } /* Convert the results of a command call into a Python objects. */ @@ -1195,22 +1195,22 @@ static PyObject* Tkapp_CallResult(TkappObject *self) { - PyObject *res = NULL; - if(self->wantobjects) { - Tcl_Obj *value = Tcl_GetObjResult(self->interp); - /* Not sure whether the IncrRef is necessary, but something - may overwrite the interpreter result while we are - converting it. */ - Tcl_IncrRefCount(value); - res = FromObj((PyObject*)self, value); - Tcl_DecrRefCount(value); - } else { - const char *s = Tcl_GetStringResult(self->interp); - const char *p = s; - - res = PyUnicode_FromStringAndSize(s, (int)(p-s)); - } - return res; + PyObject *res = NULL; + if(self->wantobjects) { + Tcl_Obj *value = Tcl_GetObjResult(self->interp); + /* Not sure whether the IncrRef is necessary, but something + may overwrite the interpreter result while we are + converting it. */ + Tcl_IncrRefCount(value); + res = FromObj((PyObject*)self, value); + Tcl_DecrRefCount(value); + } else { + const char *s = Tcl_GetStringResult(self->interp); + const char *p = s; + + res = PyUnicode_FromStringAndSize(s, (int)(p-s)); + } + return res; } #ifdef WITH_THREAD @@ -1222,41 +1222,41 @@ static int Tkapp_CallProc(Tkapp_CallEvent *e, int flags) { - Tcl_Obj *objStore[ARGSZ]; - Tcl_Obj **objv; - int objc; - int i; - ENTER_PYTHON - objv = Tkapp_CallArgs(e->args, objStore, &objc); - if (!objv) { - PyErr_Fetch(e->exc_type, e->exc_value, e->exc_tb); - *(e->res) = NULL; - } - LEAVE_PYTHON - if (!objv) - goto done; - i = Tcl_EvalObjv(e->self->interp, objc, objv, e->flags); - ENTER_PYTHON - if (i == TCL_ERROR) { - *(e->res) = NULL; - *(e->exc_type) = NULL; - *(e->exc_tb) = NULL; - *(e->exc_value) = PyObject_CallFunction( - Tkinter_TclError, "s", - Tcl_GetStringResult(e->self->interp)); - } - else { - *(e->res) = Tkapp_CallResult(e->self); - } - LEAVE_PYTHON + Tcl_Obj *objStore[ARGSZ]; + Tcl_Obj **objv; + int objc; + int i; + ENTER_PYTHON + objv = Tkapp_CallArgs(e->args, objStore, &objc); + if (!objv) { + PyErr_Fetch(e->exc_type, e->exc_value, e->exc_tb); + *(e->res) = NULL; + } + LEAVE_PYTHON + if (!objv) + goto done; + i = Tcl_EvalObjv(e->self->interp, objc, objv, e->flags); + ENTER_PYTHON + if (i == TCL_ERROR) { + *(e->res) = NULL; + *(e->exc_type) = NULL; + *(e->exc_tb) = NULL; + *(e->exc_value) = PyObject_CallFunction( + Tkinter_TclError, "s", + Tcl_GetStringResult(e->self->interp)); + } + else { + *(e->res) = Tkapp_CallResult(e->self); + } + LEAVE_PYTHON - Tkapp_CallDeallocArgs(objv, objStore, objc); + Tkapp_CallDeallocArgs(objv, objStore, objc); done: - /* Wake up calling thread. */ - Tcl_MutexLock(&call_mutex); - Tcl_ConditionNotify(e->done); - Tcl_MutexUnlock(&call_mutex); - return 1; + /* Wake up calling thread. */ + Tcl_MutexLock(&call_mutex); + Tcl_ConditionNotify(e->done); + Tcl_MutexUnlock(&call_mutex); + return 1; } #endif @@ -1276,218 +1276,218 @@ static PyObject * Tkapp_Call(PyObject *selfptr, PyObject *args) { - Tcl_Obj *objStore[ARGSZ]; - Tcl_Obj **objv = NULL; - int objc, i; - PyObject *res = NULL; - TkappObject *self = (TkappObject*)selfptr; - int flags = TCL_EVAL_DIRECT | TCL_EVAL_GLOBAL; - - /* If args is a single tuple, replace with contents of tuple */ - if (1 == PyTuple_Size(args)){ - PyObject* item = PyTuple_GetItem(args, 0); - if (PyTuple_Check(item)) - args = item; - } -#ifdef WITH_THREAD - if (self->threaded && self->thread_id != Tcl_GetCurrentThread()) { - /* We cannot call the command directly. Instead, we must - marshal the parameters to the interpreter thread. */ - Tkapp_CallEvent *ev; - Tcl_Condition cond = NULL; - PyObject *exc_type, *exc_value, *exc_tb; - if (!WaitForMainloop(self)) - return NULL; - ev = (Tkapp_CallEvent*)ckalloc(sizeof(Tkapp_CallEvent)); - ev->ev.proc = (Tcl_EventProc*)Tkapp_CallProc; - ev->self = self; - ev->args = args; - ev->res = &res; - ev->exc_type = &exc_type; - ev->exc_value = &exc_value; - ev->exc_tb = &exc_tb; - ev->done = &cond; - - Tkapp_ThreadSend(self, (Tcl_Event*)ev, &cond, &call_mutex); - - if (res == NULL) { - if (exc_type) - PyErr_Restore(exc_type, exc_value, exc_tb); - else - PyErr_SetObject(Tkinter_TclError, exc_value); - } - Tcl_ConditionFinalize(&cond); - } - else -#endif - { - - objv = Tkapp_CallArgs(args, objStore, &objc); - if (!objv) - return NULL; - - ENTER_TCL - - i = Tcl_EvalObjv(self->interp, objc, objv, flags); - - ENTER_OVERLAP - - if (i == TCL_ERROR) - Tkinter_Error(selfptr); - else - res = Tkapp_CallResult(self); - - LEAVE_OVERLAP_TCL - - Tkapp_CallDeallocArgs(objv, objStore, objc); - } - return res; + Tcl_Obj *objStore[ARGSZ]; + Tcl_Obj **objv = NULL; + int objc, i; + PyObject *res = NULL; + TkappObject *self = (TkappObject*)selfptr; + int flags = TCL_EVAL_DIRECT | TCL_EVAL_GLOBAL; + + /* If args is a single tuple, replace with contents of tuple */ + if (1 == PyTuple_Size(args)){ + PyObject* item = PyTuple_GetItem(args, 0); + if (PyTuple_Check(item)) + args = item; + } +#ifdef WITH_THREAD + if (self->threaded && self->thread_id != Tcl_GetCurrentThread()) { + /* We cannot call the command directly. Instead, we must + marshal the parameters to the interpreter thread. */ + Tkapp_CallEvent *ev; + Tcl_Condition cond = NULL; + PyObject *exc_type, *exc_value, *exc_tb; + if (!WaitForMainloop(self)) + return NULL; + ev = (Tkapp_CallEvent*)ckalloc(sizeof(Tkapp_CallEvent)); + ev->ev.proc = (Tcl_EventProc*)Tkapp_CallProc; + ev->self = self; + ev->args = args; + ev->res = &res; + ev->exc_type = &exc_type; + ev->exc_value = &exc_value; + ev->exc_tb = &exc_tb; + ev->done = &cond; + + Tkapp_ThreadSend(self, (Tcl_Event*)ev, &cond, &call_mutex); + + if (res == NULL) { + if (exc_type) + PyErr_Restore(exc_type, exc_value, exc_tb); + else + PyErr_SetObject(Tkinter_TclError, exc_value); + } + Tcl_ConditionFinalize(&cond); + } + else +#endif + { + + objv = Tkapp_CallArgs(args, objStore, &objc); + if (!objv) + return NULL; + + ENTER_TCL + + i = Tcl_EvalObjv(self->interp, objc, objv, flags); + + ENTER_OVERLAP + + if (i == TCL_ERROR) + Tkinter_Error(selfptr); + else + res = Tkapp_CallResult(self); + + LEAVE_OVERLAP_TCL + + Tkapp_CallDeallocArgs(objv, objStore, objc); + } + return res; } static PyObject * Tkapp_GlobalCall(PyObject *self, PyObject *args) { - /* Could do the same here as for Tkapp_Call(), but this is not used - much, so I can't be bothered. Unfortunately Tcl doesn't export a - way for the user to do what all its Global* variants do (save and - reset the scope pointer, call the local version, restore the saved - scope pointer). */ - - char *cmd; - PyObject *res = NULL; - - CHECK_TCL_APPARTMENT; - - cmd = Merge(args); - if (cmd) { - int err; - ENTER_TCL - err = Tcl_GlobalEval(Tkapp_Interp(self), cmd); - ENTER_OVERLAP - if (err == TCL_ERROR) - res = Tkinter_Error(self); - else - res = PyUnicode_FromString(Tkapp_Result(self)); - LEAVE_OVERLAP_TCL - ckfree(cmd); - } + /* Could do the same here as for Tkapp_Call(), but this is not used + much, so I can't be bothered. Unfortunately Tcl doesn't export a + way for the user to do what all its Global* variants do (save and + reset the scope pointer, call the local version, restore the saved + scope pointer). */ + + char *cmd; + PyObject *res = NULL; + + CHECK_TCL_APPARTMENT; + + cmd = Merge(args); + if (cmd) { + int err; + ENTER_TCL + err = Tcl_GlobalEval(Tkapp_Interp(self), cmd); + ENTER_OVERLAP + if (err == TCL_ERROR) + res = Tkinter_Error(self); + else + res = PyUnicode_FromString(Tkapp_Result(self)); + LEAVE_OVERLAP_TCL + ckfree(cmd); + } - return res; + return res; } static PyObject * Tkapp_Eval(PyObject *self, PyObject *args) { - char *script; - PyObject *res = NULL; - int err; - - if (!PyArg_ParseTuple(args, "s:eval", &script)) - return NULL; - - CHECK_TCL_APPARTMENT; - - ENTER_TCL - err = Tcl_Eval(Tkapp_Interp(self), script); - ENTER_OVERLAP - if (err == TCL_ERROR) - res = Tkinter_Error(self); - else - res = PyUnicode_FromString(Tkapp_Result(self)); - LEAVE_OVERLAP_TCL - return res; + char *script; + PyObject *res = NULL; + int err; + + if (!PyArg_ParseTuple(args, "s:eval", &script)) + return NULL; + + CHECK_TCL_APPARTMENT; + + ENTER_TCL + err = Tcl_Eval(Tkapp_Interp(self), script); + ENTER_OVERLAP + if (err == TCL_ERROR) + res = Tkinter_Error(self); + else + res = PyUnicode_FromString(Tkapp_Result(self)); + LEAVE_OVERLAP_TCL + return res; } static PyObject * Tkapp_GlobalEval(PyObject *self, PyObject *args) { - char *script; - PyObject *res = NULL; - int err; - - if (!PyArg_ParseTuple(args, "s:globaleval", &script)) - return NULL; - - CHECK_TCL_APPARTMENT; - - ENTER_TCL - err = Tcl_GlobalEval(Tkapp_Interp(self), script); - ENTER_OVERLAP - if (err == TCL_ERROR) - res = Tkinter_Error(self); - else - res = PyUnicode_FromString(Tkapp_Result(self)); - LEAVE_OVERLAP_TCL - return res; + char *script; + PyObject *res = NULL; + int err; + + if (!PyArg_ParseTuple(args, "s:globaleval", &script)) + return NULL; + + CHECK_TCL_APPARTMENT; + + ENTER_TCL + err = Tcl_GlobalEval(Tkapp_Interp(self), script); + ENTER_OVERLAP + if (err == TCL_ERROR) + res = Tkinter_Error(self); + else + res = PyUnicode_FromString(Tkapp_Result(self)); + LEAVE_OVERLAP_TCL + return res; } static PyObject * Tkapp_EvalFile(PyObject *self, PyObject *args) { - char *fileName; - PyObject *res = NULL; - int err; - - if (!PyArg_ParseTuple(args, "s:evalfile", &fileName)) - return NULL; - - CHECK_TCL_APPARTMENT; - - ENTER_TCL - err = Tcl_EvalFile(Tkapp_Interp(self), fileName); - ENTER_OVERLAP - if (err == TCL_ERROR) - res = Tkinter_Error(self); - - else - res = PyUnicode_FromString(Tkapp_Result(self)); - LEAVE_OVERLAP_TCL - return res; + char *fileName; + PyObject *res = NULL; + int err; + + if (!PyArg_ParseTuple(args, "s:evalfile", &fileName)) + return NULL; + + CHECK_TCL_APPARTMENT; + + ENTER_TCL + err = Tcl_EvalFile(Tkapp_Interp(self), fileName); + ENTER_OVERLAP + if (err == TCL_ERROR) + res = Tkinter_Error(self); + + else + res = PyUnicode_FromString(Tkapp_Result(self)); + LEAVE_OVERLAP_TCL + return res; } static PyObject * Tkapp_Record(PyObject *self, PyObject *args) { - char *script; - PyObject *res = NULL; - int err; - - if (!PyArg_ParseTuple(args, "s", &script)) - return NULL; - - CHECK_TCL_APPARTMENT; - - ENTER_TCL - err = Tcl_RecordAndEval(Tkapp_Interp(self), script, TCL_NO_EVAL); - ENTER_OVERLAP - if (err == TCL_ERROR) - res = Tkinter_Error(self); - else - res = PyUnicode_FromString(Tkapp_Result(self)); - LEAVE_OVERLAP_TCL - return res; + char *script; + PyObject *res = NULL; + int err; + + if (!PyArg_ParseTuple(args, "s", &script)) + return NULL; + + CHECK_TCL_APPARTMENT; + + ENTER_TCL + err = Tcl_RecordAndEval(Tkapp_Interp(self), script, TCL_NO_EVAL); + ENTER_OVERLAP + if (err == TCL_ERROR) + res = Tkinter_Error(self); + else + res = PyUnicode_FromString(Tkapp_Result(self)); + LEAVE_OVERLAP_TCL + return res; } static PyObject * Tkapp_AddErrorInfo(PyObject *self, PyObject *args) { - char *msg; - - if (!PyArg_ParseTuple(args, "s:adderrorinfo", &msg)) - return NULL; - CHECK_TCL_APPARTMENT; + char *msg; - ENTER_TCL - Tcl_AddErrorInfo(Tkapp_Interp(self), msg); - LEAVE_TCL + if (!PyArg_ParseTuple(args, "s:adderrorinfo", &msg)) + return NULL; + CHECK_TCL_APPARTMENT; + + ENTER_TCL + Tcl_AddErrorInfo(Tkapp_Interp(self), msg); + LEAVE_TCL - Py_INCREF(Py_None); - return Py_None; + Py_INCREF(Py_None); + return Py_None; } - + /** Tcl Variable **/ typedef PyObject* (*EventFunc)(PyObject*, PyObject *args, int flags); @@ -1496,36 +1496,36 @@ TCL_DECLARE_MUTEX(var_mutex) typedef struct VarEvent { - Tcl_Event ev; /* must be first */ - PyObject *self; - PyObject *args; - int flags; - EventFunc func; - PyObject **res; - PyObject **exc_type; - PyObject **exc_val; - Tcl_Condition *cond; + Tcl_Event ev; /* must be first */ + PyObject *self; + PyObject *args; + int flags; + EventFunc func; + PyObject **res; + PyObject **exc_type; + PyObject **exc_val; + Tcl_Condition *cond; } VarEvent; #endif static int varname_converter(PyObject *in, void *_out) { - char **out = (char**)_out; - if (PyBytes_Check(in)) { - *out = PyBytes_AsString(in); - return 1; - } - if (PyUnicode_Check(in)) { - *out = _PyUnicode_AsString(in); - return 1; - } - if (PyTclObject_Check(in)) { - *out = PyTclObject_TclString(in); - return 1; - } - /* XXX: Should give diagnostics. */ - return 0; + char **out = (char**)_out; + if (PyBytes_Check(in)) { + *out = PyBytes_AsString(in); + return 1; + } + if (PyUnicode_Check(in)) { + *out = _PyUnicode_AsString(in); + return 1; + } + if (PyTclObject_Check(in)) { + *out = PyTclObject_TclString(in); + return 1; + } + /* XXX: Should give diagnostics. */ + return 0; } #ifdef WITH_THREAD @@ -1533,28 +1533,28 @@ static void var_perform(VarEvent *ev) { - *(ev->res) = ev->func(ev->self, ev->args, ev->flags); - if (!*(ev->res)) { - PyObject *exc, *val, *tb; - PyErr_Fetch(&exc, &val, &tb); - PyErr_NormalizeException(&exc, &val, &tb); - *(ev->exc_type) = exc; - *(ev->exc_val) = val; - Py_DECREF(tb); - } + *(ev->res) = ev->func(ev->self, ev->args, ev->flags); + if (!*(ev->res)) { + PyObject *exc, *val, *tb; + PyErr_Fetch(&exc, &val, &tb); + PyErr_NormalizeException(&exc, &val, &tb); + *(ev->exc_type) = exc; + *(ev->exc_val) = val; + Py_DECREF(tb); + } } static int var_proc(VarEvent* ev, int flags) { - ENTER_PYTHON - var_perform(ev); - Tcl_MutexLock(&var_mutex); - Tcl_ConditionNotify(ev->cond); - Tcl_MutexUnlock(&var_mutex); - LEAVE_PYTHON - return 1; + ENTER_PYTHON + var_perform(ev); + Tcl_MutexLock(&var_mutex); + Tcl_ConditionNotify(ev->cond); + Tcl_MutexUnlock(&var_mutex); + LEAVE_PYTHON + return 1; } #endif @@ -1563,439 +1563,439 @@ var_invoke(EventFunc func, PyObject *selfptr, PyObject *args, int flags) { #ifdef WITH_THREAD - TkappObject *self = (TkappObject*)selfptr; - if (self->threaded && self->thread_id != Tcl_GetCurrentThread()) { - TkappObject *self = (TkappObject*)selfptr; - VarEvent *ev; - PyObject *res, *exc_type, *exc_val; - Tcl_Condition cond = NULL; - - /* The current thread is not the interpreter thread. Marshal - the call to the interpreter thread, then wait for - completion. */ - if (!WaitForMainloop(self)) - return NULL; - - ev = (VarEvent*)ckalloc(sizeof(VarEvent)); - - ev->self = selfptr; - ev->args = args; - ev->flags = flags; - ev->func = func; - ev->res = &res; - ev->exc_type = &exc_type; - ev->exc_val = &exc_val; - ev->cond = &cond; - ev->ev.proc = (Tcl_EventProc*)var_proc; - Tkapp_ThreadSend(self, (Tcl_Event*)ev, &cond, &var_mutex); - Tcl_ConditionFinalize(&cond); - if (!res) { - PyErr_SetObject(exc_type, exc_val); - Py_DECREF(exc_type); - Py_DECREF(exc_val); - return NULL; - } - return res; - } + TkappObject *self = (TkappObject*)selfptr; + if (self->threaded && self->thread_id != Tcl_GetCurrentThread()) { + TkappObject *self = (TkappObject*)selfptr; + VarEvent *ev; + PyObject *res, *exc_type, *exc_val; + Tcl_Condition cond = NULL; + + /* The current thread is not the interpreter thread. Marshal + the call to the interpreter thread, then wait for + completion. */ + if (!WaitForMainloop(self)) + return NULL; + + ev = (VarEvent*)ckalloc(sizeof(VarEvent)); + + ev->self = selfptr; + ev->args = args; + ev->flags = flags; + ev->func = func; + ev->res = &res; + ev->exc_type = &exc_type; + ev->exc_val = &exc_val; + ev->cond = &cond; + ev->ev.proc = (Tcl_EventProc*)var_proc; + Tkapp_ThreadSend(self, (Tcl_Event*)ev, &cond, &var_mutex); + Tcl_ConditionFinalize(&cond); + if (!res) { + PyErr_SetObject(exc_type, exc_val); + Py_DECREF(exc_type); + Py_DECREF(exc_val); + return NULL; + } + return res; + } #endif - /* Tcl is not threaded, or this is the interpreter thread. */ - return func(selfptr, args, flags); + /* Tcl is not threaded, or this is the interpreter thread. */ + return func(selfptr, args, flags); } static PyObject * SetVar(PyObject *self, PyObject *args, int flags) { - char *name1, *name2; - PyObject *newValue; - PyObject *res = NULL; - Tcl_Obj *newval, *ok; - - if (PyArg_ParseTuple(args, "O&O:setvar", - varname_converter, &name1, &newValue)) { - /* XXX Acquire tcl lock??? */ - newval = AsObj(newValue); - if (newval == NULL) - return NULL; - ENTER_TCL - ok = Tcl_SetVar2Ex(Tkapp_Interp(self), name1, NULL, - newval, flags); - ENTER_OVERLAP - if (!ok) - Tkinter_Error(self); - else { - res = Py_None; - Py_INCREF(res); - } - LEAVE_OVERLAP_TCL - } - else { - PyErr_Clear(); - if (PyArg_ParseTuple(args, "ssO:setvar", - &name1, &name2, &newValue)) { - /* XXX must hold tcl lock already??? */ - newval = AsObj(newValue); - ENTER_TCL - ok = Tcl_SetVar2Ex(Tkapp_Interp(self), name1, name2, newval, flags); - ENTER_OVERLAP - if (!ok) - Tkinter_Error(self); - else { - res = Py_None; - Py_INCREF(res); - } - LEAVE_OVERLAP_TCL - } - else { - return NULL; - } - } - return res; + char *name1, *name2; + PyObject *newValue; + PyObject *res = NULL; + Tcl_Obj *newval, *ok; + + if (PyArg_ParseTuple(args, "O&O:setvar", + varname_converter, &name1, &newValue)) { + /* XXX Acquire tcl lock??? */ + newval = AsObj(newValue); + if (newval == NULL) + return NULL; + ENTER_TCL + ok = Tcl_SetVar2Ex(Tkapp_Interp(self), name1, NULL, + newval, flags); + ENTER_OVERLAP + if (!ok) + Tkinter_Error(self); + else { + res = Py_None; + Py_INCREF(res); + } + LEAVE_OVERLAP_TCL + } + else { + PyErr_Clear(); + if (PyArg_ParseTuple(args, "ssO:setvar", + &name1, &name2, &newValue)) { + /* XXX must hold tcl lock already??? */ + newval = AsObj(newValue); + ENTER_TCL + ok = Tcl_SetVar2Ex(Tkapp_Interp(self), name1, name2, newval, flags); + ENTER_OVERLAP + if (!ok) + Tkinter_Error(self); + else { + res = Py_None; + Py_INCREF(res); + } + LEAVE_OVERLAP_TCL + } + else { + return NULL; + } + } + return res; } static PyObject * Tkapp_SetVar(PyObject *self, PyObject *args) { - return var_invoke(SetVar, self, args, TCL_LEAVE_ERR_MSG); + return var_invoke(SetVar, self, args, TCL_LEAVE_ERR_MSG); } static PyObject * Tkapp_GlobalSetVar(PyObject *self, PyObject *args) { - return var_invoke(SetVar, self, args, TCL_LEAVE_ERR_MSG | TCL_GLOBAL_ONLY); + return var_invoke(SetVar, self, args, TCL_LEAVE_ERR_MSG | TCL_GLOBAL_ONLY); } - + static PyObject * GetVar(PyObject *self, PyObject *args, int flags) { - char *name1, *name2=NULL; - PyObject *res = NULL; - Tcl_Obj *tres; - - if (!PyArg_ParseTuple(args, "O&|s:getvar", - varname_converter, &name1, &name2)) - return NULL; - - ENTER_TCL - tres = Tcl_GetVar2Ex(Tkapp_Interp(self), name1, name2, flags); - ENTER_OVERLAP - if (tres == NULL) { - PyErr_SetString(Tkinter_TclError, Tcl_GetStringResult(Tkapp_Interp(self))); - } else { - if (((TkappObject*)self)->wantobjects) { - res = FromObj(self, tres); - } - else { - res = PyUnicode_FromString(Tcl_GetString(tres)); - } - } - LEAVE_OVERLAP_TCL - return res; + char *name1, *name2=NULL; + PyObject *res = NULL; + Tcl_Obj *tres; + + if (!PyArg_ParseTuple(args, "O&|s:getvar", + varname_converter, &name1, &name2)) + return NULL; + + ENTER_TCL + tres = Tcl_GetVar2Ex(Tkapp_Interp(self), name1, name2, flags); + ENTER_OVERLAP + if (tres == NULL) { + PyErr_SetString(Tkinter_TclError, Tcl_GetStringResult(Tkapp_Interp(self))); + } else { + if (((TkappObject*)self)->wantobjects) { + res = FromObj(self, tres); + } + else { + res = PyUnicode_FromString(Tcl_GetString(tres)); + } + } + LEAVE_OVERLAP_TCL + return res; } static PyObject * Tkapp_GetVar(PyObject *self, PyObject *args) { - return var_invoke(GetVar, self, args, TCL_LEAVE_ERR_MSG); + return var_invoke(GetVar, self, args, TCL_LEAVE_ERR_MSG); } static PyObject * Tkapp_GlobalGetVar(PyObject *self, PyObject *args) { - return var_invoke(GetVar, self, args, TCL_LEAVE_ERR_MSG | TCL_GLOBAL_ONLY); + return var_invoke(GetVar, self, args, TCL_LEAVE_ERR_MSG | TCL_GLOBAL_ONLY); } - + static PyObject * UnsetVar(PyObject *self, PyObject *args, int flags) { - char *name1, *name2=NULL; - int code; - PyObject *res = NULL; - - if (!PyArg_ParseTuple(args, "s|s:unsetvar", &name1, &name2)) - return NULL; - - ENTER_TCL - code = Tcl_UnsetVar2(Tkapp_Interp(self), name1, name2, flags); - ENTER_OVERLAP - if (code == TCL_ERROR) - res = Tkinter_Error(self); - else { - Py_INCREF(Py_None); - res = Py_None; - } - LEAVE_OVERLAP_TCL - return res; + char *name1, *name2=NULL; + int code; + PyObject *res = NULL; + + if (!PyArg_ParseTuple(args, "s|s:unsetvar", &name1, &name2)) + return NULL; + + ENTER_TCL + code = Tcl_UnsetVar2(Tkapp_Interp(self), name1, name2, flags); + ENTER_OVERLAP + if (code == TCL_ERROR) + res = Tkinter_Error(self); + else { + Py_INCREF(Py_None); + res = Py_None; + } + LEAVE_OVERLAP_TCL + return res; } static PyObject * Tkapp_UnsetVar(PyObject *self, PyObject *args) { - return var_invoke(UnsetVar, self, args, TCL_LEAVE_ERR_MSG); + return var_invoke(UnsetVar, self, args, TCL_LEAVE_ERR_MSG); } static PyObject * Tkapp_GlobalUnsetVar(PyObject *self, PyObject *args) { - return var_invoke(UnsetVar, self, args, TCL_LEAVE_ERR_MSG | TCL_GLOBAL_ONLY); + return var_invoke(UnsetVar, self, args, TCL_LEAVE_ERR_MSG | TCL_GLOBAL_ONLY); } - + /** Tcl to Python **/ static PyObject * Tkapp_GetInt(PyObject *self, PyObject *args) { - char *s; - int v; + char *s; + int v; - if (PyTuple_Size(args) == 1) { - PyObject* o = PyTuple_GetItem(args, 0); - if (PyLong_Check(o)) { - Py_INCREF(o); - return o; - } - } - if (!PyArg_ParseTuple(args, "s:getint", &s)) - return NULL; - if (Tcl_GetInt(Tkapp_Interp(self), s, &v) == TCL_ERROR) - return Tkinter_Error(self); - return Py_BuildValue("i", v); + if (PyTuple_Size(args) == 1) { + PyObject* o = PyTuple_GetItem(args, 0); + if (PyLong_Check(o)) { + Py_INCREF(o); + return o; + } + } + if (!PyArg_ParseTuple(args, "s:getint", &s)) + return NULL; + if (Tcl_GetInt(Tkapp_Interp(self), s, &v) == TCL_ERROR) + return Tkinter_Error(self); + return Py_BuildValue("i", v); } static PyObject * Tkapp_GetDouble(PyObject *self, PyObject *args) { - char *s; - double v; + char *s; + double v; - if (PyTuple_Size(args) == 1) { - PyObject *o = PyTuple_GetItem(args, 0); - if (PyFloat_Check(o)) { - Py_INCREF(o); - return o; - } - } - if (!PyArg_ParseTuple(args, "s:getdouble", &s)) - return NULL; - if (Tcl_GetDouble(Tkapp_Interp(self), s, &v) == TCL_ERROR) - return Tkinter_Error(self); - return Py_BuildValue("d", v); + if (PyTuple_Size(args) == 1) { + PyObject *o = PyTuple_GetItem(args, 0); + if (PyFloat_Check(o)) { + Py_INCREF(o); + return o; + } + } + if (!PyArg_ParseTuple(args, "s:getdouble", &s)) + return NULL; + if (Tcl_GetDouble(Tkapp_Interp(self), s, &v) == TCL_ERROR) + return Tkinter_Error(self); + return Py_BuildValue("d", v); } static PyObject * Tkapp_GetBoolean(PyObject *self, PyObject *args) { - char *s; - int v; + char *s; + int v; - if (PyTuple_Size(args) == 1) { - PyObject *o = PyTuple_GetItem(args, 0); - if (PyLong_Check(o)) { - Py_INCREF(o); - return o; - } - } - if (!PyArg_ParseTuple(args, "s:getboolean", &s)) - return NULL; - if (Tcl_GetBoolean(Tkapp_Interp(self), s, &v) == TCL_ERROR) - return Tkinter_Error(self); - return PyBool_FromLong(v); + if (PyTuple_Size(args) == 1) { + PyObject *o = PyTuple_GetItem(args, 0); + if (PyLong_Check(o)) { + Py_INCREF(o); + return o; + } + } + if (!PyArg_ParseTuple(args, "s:getboolean", &s)) + return NULL; + if (Tcl_GetBoolean(Tkapp_Interp(self), s, &v) == TCL_ERROR) + return Tkinter_Error(self); + return PyBool_FromLong(v); } static PyObject * Tkapp_ExprString(PyObject *self, PyObject *args) { - char *s; - PyObject *res = NULL; - int retval; - - if (!PyArg_ParseTuple(args, "s:exprstring", &s)) - return NULL; - - CHECK_TCL_APPARTMENT; - - ENTER_TCL - retval = Tcl_ExprString(Tkapp_Interp(self), s); - ENTER_OVERLAP - if (retval == TCL_ERROR) - res = Tkinter_Error(self); - else - res = Py_BuildValue("s", Tkapp_Result(self)); - LEAVE_OVERLAP_TCL - return res; + char *s; + PyObject *res = NULL; + int retval; + + if (!PyArg_ParseTuple(args, "s:exprstring", &s)) + return NULL; + + CHECK_TCL_APPARTMENT; + + ENTER_TCL + retval = Tcl_ExprString(Tkapp_Interp(self), s); + ENTER_OVERLAP + if (retval == TCL_ERROR) + res = Tkinter_Error(self); + else + res = Py_BuildValue("s", Tkapp_Result(self)); + LEAVE_OVERLAP_TCL + return res; } static PyObject * Tkapp_ExprLong(PyObject *self, PyObject *args) { - char *s; - PyObject *res = NULL; - int retval; - long v; - - if (!PyArg_ParseTuple(args, "s:exprlong", &s)) - return NULL; - - CHECK_TCL_APPARTMENT; - - ENTER_TCL - retval = Tcl_ExprLong(Tkapp_Interp(self), s, &v); - ENTER_OVERLAP - if (retval == TCL_ERROR) - res = Tkinter_Error(self); - else - res = Py_BuildValue("l", v); - LEAVE_OVERLAP_TCL - return res; + char *s; + PyObject *res = NULL; + int retval; + long v; + + if (!PyArg_ParseTuple(args, "s:exprlong", &s)) + return NULL; + + CHECK_TCL_APPARTMENT; + + ENTER_TCL + retval = Tcl_ExprLong(Tkapp_Interp(self), s, &v); + ENTER_OVERLAP + if (retval == TCL_ERROR) + res = Tkinter_Error(self); + else + res = Py_BuildValue("l", v); + LEAVE_OVERLAP_TCL + return res; } static PyObject * Tkapp_ExprDouble(PyObject *self, PyObject *args) { - char *s; - PyObject *res = NULL; - double v; - int retval; - - if (!PyArg_ParseTuple(args, "s:exprdouble", &s)) - return NULL; - CHECK_TCL_APPARTMENT; - PyFPE_START_PROTECT("Tkapp_ExprDouble", return 0) - ENTER_TCL - retval = Tcl_ExprDouble(Tkapp_Interp(self), s, &v); - ENTER_OVERLAP - PyFPE_END_PROTECT(retval) - if (retval == TCL_ERROR) - res = Tkinter_Error(self); - else - res = Py_BuildValue("d", v); - LEAVE_OVERLAP_TCL - return res; + char *s; + PyObject *res = NULL; + double v; + int retval; + + if (!PyArg_ParseTuple(args, "s:exprdouble", &s)) + return NULL; + CHECK_TCL_APPARTMENT; + PyFPE_START_PROTECT("Tkapp_ExprDouble", return 0) + ENTER_TCL + retval = Tcl_ExprDouble(Tkapp_Interp(self), s, &v); + ENTER_OVERLAP + PyFPE_END_PROTECT(retval) + if (retval == TCL_ERROR) + res = Tkinter_Error(self); + else + res = Py_BuildValue("d", v); + LEAVE_OVERLAP_TCL + return res; } static PyObject * Tkapp_ExprBoolean(PyObject *self, PyObject *args) { - char *s; - PyObject *res = NULL; - int retval; - int v; - - if (!PyArg_ParseTuple(args, "s:exprboolean", &s)) - return NULL; - CHECK_TCL_APPARTMENT; - ENTER_TCL - retval = Tcl_ExprBoolean(Tkapp_Interp(self), s, &v); - ENTER_OVERLAP - if (retval == TCL_ERROR) - res = Tkinter_Error(self); - else - res = Py_BuildValue("i", v); - LEAVE_OVERLAP_TCL - return res; + char *s; + PyObject *res = NULL; + int retval; + int v; + + if (!PyArg_ParseTuple(args, "s:exprboolean", &s)) + return NULL; + CHECK_TCL_APPARTMENT; + ENTER_TCL + retval = Tcl_ExprBoolean(Tkapp_Interp(self), s, &v); + ENTER_OVERLAP + if (retval == TCL_ERROR) + res = Tkinter_Error(self); + else + res = Py_BuildValue("i", v); + LEAVE_OVERLAP_TCL + return res; } - + static PyObject * Tkapp_SplitList(PyObject *self, PyObject *args) { - char *list; - int argc; - char **argv; - PyObject *v; - int i; - - if (PyTuple_Size(args) == 1) { - v = PyTuple_GetItem(args, 0); - if (PyTuple_Check(v)) { - Py_INCREF(v); - return v; - } - } - if (!PyArg_ParseTuple(args, "et:splitlist", "utf-8", &list)) - return NULL; - - if (Tcl_SplitList(Tkapp_Interp(self), list, - &argc, &argv) == TCL_ERROR) { - PyMem_Free(list); - return Tkinter_Error(self); - } - - if (!(v = PyTuple_New(argc))) - goto finally; - - for (i = 0; i < argc; i++) { - PyObject *s = PyUnicode_FromString(argv[i]); - if (!s || PyTuple_SetItem(v, i, s)) { - Py_DECREF(v); - v = NULL; - goto finally; - } - } + char *list; + int argc; + char **argv; + PyObject *v; + int i; + + if (PyTuple_Size(args) == 1) { + v = PyTuple_GetItem(args, 0); + if (PyTuple_Check(v)) { + Py_INCREF(v); + return v; + } + } + if (!PyArg_ParseTuple(args, "et:splitlist", "utf-8", &list)) + return NULL; + + if (Tcl_SplitList(Tkapp_Interp(self), list, + &argc, &argv) == TCL_ERROR) { + PyMem_Free(list); + return Tkinter_Error(self); + } + + if (!(v = PyTuple_New(argc))) + goto finally; + + for (i = 0; i < argc; i++) { + PyObject *s = PyUnicode_FromString(argv[i]); + if (!s || PyTuple_SetItem(v, i, s)) { + Py_DECREF(v); + v = NULL; + goto finally; + } + } finally: - ckfree(FREECAST argv); - PyMem_Free(list); - return v; + ckfree(FREECAST argv); + PyMem_Free(list); + return v; } static PyObject * Tkapp_Split(PyObject *self, PyObject *args) { - PyObject *v; - char *list; + PyObject *v; + char *list; - if (PyTuple_Size(args) == 1) { - PyObject* o = PyTuple_GetItem(args, 0); - if (PyTuple_Check(o)) { - o = SplitObj(o); - return o; - } - } - if (!PyArg_ParseTuple(args, "et:split", "utf-8", &list)) - return NULL; - v = Split(list); - PyMem_Free(list); - return v; + if (PyTuple_Size(args) == 1) { + PyObject* o = PyTuple_GetItem(args, 0); + if (PyTuple_Check(o)) { + o = SplitObj(o); + return o; + } + } + if (!PyArg_ParseTuple(args, "et:split", "utf-8", &list)) + return NULL; + v = Split(list); + PyMem_Free(list); + return v; } static PyObject * Tkapp_Merge(PyObject *self, PyObject *args) { - char *s = Merge(args); - PyObject *res = NULL; + char *s = Merge(args); + PyObject *res = NULL; - if (s) { - res = PyUnicode_FromString(s); - ckfree(s); - } + if (s) { + res = PyUnicode_FromString(s); + ckfree(s); + } - return res; + return res; } - + /** Tcl Command **/ /* Client data struct */ typedef struct { - PyObject *self; - PyObject *func; + PyObject *self; + PyObject *func; } PythonCmd_ClientData; static int PythonCmd_Error(Tcl_Interp *interp) { - errorInCmd = 1; - PyErr_Fetch(&excInCmd, &valInCmd, &trbInCmd); - LEAVE_PYTHON - return TCL_ERROR; + errorInCmd = 1; + PyErr_Fetch(&excInCmd, &valInCmd, &trbInCmd); + LEAVE_PYTHON + return TCL_ERROR; } /* This is the Tcl command that acts as a wrapper for Python @@ -2004,211 +2004,211 @@ static int PythonCmd(ClientData clientData, Tcl_Interp *interp, int argc, char *argv[]) { - PythonCmd_ClientData *data = (PythonCmd_ClientData *)clientData; - PyObject *self, *func, *arg, *res; - int i, rv; - Tcl_Obj *obj_res; - - ENTER_PYTHON - - /* TBD: no error checking here since we know, via the - * Tkapp_CreateCommand() that the client data is a two-tuple - */ - self = data->self; - func = data->func; - - /* Create argument list (argv1, ..., argvN) */ - if (!(arg = PyTuple_New(argc - 1))) - return PythonCmd_Error(interp); - - for (i = 0; i < (argc - 1); i++) { - PyObject *s = PyUnicode_FromString(argv[i + 1]); - if (!s || PyTuple_SetItem(arg, i, s)) { - Py_DECREF(arg); - return PythonCmd_Error(interp); - } - } - res = PyEval_CallObject(func, arg); - Py_DECREF(arg); - - if (res == NULL) - return PythonCmd_Error(interp); - - obj_res = AsObj(res); - if (obj_res == NULL) { - Py_DECREF(res); - return PythonCmd_Error(interp); - } - else { - Tcl_SetObjResult(interp, obj_res); - rv = TCL_OK; - } + PythonCmd_ClientData *data = (PythonCmd_ClientData *)clientData; + PyObject *self, *func, *arg, *res; + int i, rv; + Tcl_Obj *obj_res; + + ENTER_PYTHON + + /* TBD: no error checking here since we know, via the + * Tkapp_CreateCommand() that the client data is a two-tuple + */ + self = data->self; + func = data->func; + + /* Create argument list (argv1, ..., argvN) */ + if (!(arg = PyTuple_New(argc - 1))) + return PythonCmd_Error(interp); + + for (i = 0; i < (argc - 1); i++) { + PyObject *s = PyUnicode_FromString(argv[i + 1]); + if (!s || PyTuple_SetItem(arg, i, s)) { + Py_DECREF(arg); + return PythonCmd_Error(interp); + } + } + res = PyEval_CallObject(func, arg); + Py_DECREF(arg); + + if (res == NULL) + return PythonCmd_Error(interp); + + obj_res = AsObj(res); + if (obj_res == NULL) { + Py_DECREF(res); + return PythonCmd_Error(interp); + } + else { + Tcl_SetObjResult(interp, obj_res); + rv = TCL_OK; + } - Py_DECREF(res); + Py_DECREF(res); - LEAVE_PYTHON + LEAVE_PYTHON - return rv; + return rv; } static void PythonCmdDelete(ClientData clientData) { - PythonCmd_ClientData *data = (PythonCmd_ClientData *)clientData; + PythonCmd_ClientData *data = (PythonCmd_ClientData *)clientData; - ENTER_PYTHON - Py_XDECREF(data->self); - Py_XDECREF(data->func); - PyMem_DEL(data); - LEAVE_PYTHON + ENTER_PYTHON + Py_XDECREF(data->self); + Py_XDECREF(data->func); + PyMem_DEL(data); + LEAVE_PYTHON } - + #ifdef WITH_THREAD TCL_DECLARE_MUTEX(command_mutex) typedef struct CommandEvent{ - Tcl_Event ev; - Tcl_Interp* interp; - char *name; - int create; - int *status; - ClientData *data; - Tcl_Condition *done; + Tcl_Event ev; + Tcl_Interp* interp; + char *name; + int create; + int *status; + ClientData *data; + Tcl_Condition *done; } CommandEvent; static int Tkapp_CommandProc(CommandEvent *ev, int flags) { - if (ev->create) - *ev->status = Tcl_CreateCommand( - ev->interp, ev->name, PythonCmd, - ev->data, PythonCmdDelete) == NULL; - else - *ev->status = Tcl_DeleteCommand(ev->interp, ev->name); - Tcl_MutexLock(&command_mutex); - Tcl_ConditionNotify(ev->done); - Tcl_MutexUnlock(&command_mutex); - return 1; + if (ev->create) + *ev->status = Tcl_CreateCommand( + ev->interp, ev->name, PythonCmd, + ev->data, PythonCmdDelete) == NULL; + else + *ev->status = Tcl_DeleteCommand(ev->interp, ev->name); + Tcl_MutexLock(&command_mutex); + Tcl_ConditionNotify(ev->done); + Tcl_MutexUnlock(&command_mutex); + return 1; } #endif static PyObject * Tkapp_CreateCommand(PyObject *selfptr, PyObject *args) { - TkappObject *self = (TkappObject*)selfptr; - PythonCmd_ClientData *data; - char *cmdName; - PyObject *func; - int err; - - if (!PyArg_ParseTuple(args, "sO:createcommand", &cmdName, &func)) - return NULL; - if (!PyCallable_Check(func)) { - PyErr_SetString(PyExc_TypeError, "command not callable"); - return NULL; - } - -#ifdef WITH_THREAD - if (self->threaded && self->thread_id != Tcl_GetCurrentThread() && - !WaitForMainloop(self)) - return NULL; -#endif - - data = PyMem_NEW(PythonCmd_ClientData, 1); - if (!data) - return PyErr_NoMemory(); - Py_INCREF(self); - Py_INCREF(func); - data->self = selfptr; - data->func = func; -#ifdef WITH_THREAD - if (self->threaded && self->thread_id != Tcl_GetCurrentThread()) { - Tcl_Condition cond = NULL; - CommandEvent *ev = (CommandEvent*)ckalloc(sizeof(CommandEvent)); - ev->ev.proc = (Tcl_EventProc*)Tkapp_CommandProc; - ev->interp = self->interp; - ev->create = 1; - ev->name = cmdName; - ev->data = (ClientData)data; - ev->status = &err; - ev->done = &cond; - Tkapp_ThreadSend(self, (Tcl_Event*)ev, &cond, &command_mutex); - Tcl_ConditionFinalize(&cond); - } - else -#endif - { - ENTER_TCL - err = Tcl_CreateCommand( - Tkapp_Interp(self), cmdName, PythonCmd, - (ClientData)data, PythonCmdDelete) == NULL; - LEAVE_TCL - } - if (err) { - PyErr_SetString(Tkinter_TclError, "can't create Tcl command"); - PyMem_DEL(data); - return NULL; - } + TkappObject *self = (TkappObject*)selfptr; + PythonCmd_ClientData *data; + char *cmdName; + PyObject *func; + int err; + + if (!PyArg_ParseTuple(args, "sO:createcommand", &cmdName, &func)) + return NULL; + if (!PyCallable_Check(func)) { + PyErr_SetString(PyExc_TypeError, "command not callable"); + return NULL; + } + +#ifdef WITH_THREAD + if (self->threaded && self->thread_id != Tcl_GetCurrentThread() && + !WaitForMainloop(self)) + return NULL; +#endif + + data = PyMem_NEW(PythonCmd_ClientData, 1); + if (!data) + return PyErr_NoMemory(); + Py_INCREF(self); + Py_INCREF(func); + data->self = selfptr; + data->func = func; +#ifdef WITH_THREAD + if (self->threaded && self->thread_id != Tcl_GetCurrentThread()) { + Tcl_Condition cond = NULL; + CommandEvent *ev = (CommandEvent*)ckalloc(sizeof(CommandEvent)); + ev->ev.proc = (Tcl_EventProc*)Tkapp_CommandProc; + ev->interp = self->interp; + ev->create = 1; + ev->name = cmdName; + ev->data = (ClientData)data; + ev->status = &err; + ev->done = &cond; + Tkapp_ThreadSend(self, (Tcl_Event*)ev, &cond, &command_mutex); + Tcl_ConditionFinalize(&cond); + } + else +#endif + { + ENTER_TCL + err = Tcl_CreateCommand( + Tkapp_Interp(self), cmdName, PythonCmd, + (ClientData)data, PythonCmdDelete) == NULL; + LEAVE_TCL + } + if (err) { + PyErr_SetString(Tkinter_TclError, "can't create Tcl command"); + PyMem_DEL(data); + return NULL; + } - Py_INCREF(Py_None); - return Py_None; + Py_INCREF(Py_None); + return Py_None; } - + static PyObject * Tkapp_DeleteCommand(PyObject *selfptr, PyObject *args) { - TkappObject *self = (TkappObject*)selfptr; - char *cmdName; - int err; - - if (!PyArg_ParseTuple(args, "s:deletecommand", &cmdName)) - return NULL; - -#ifdef WITH_THREAD - if (self->threaded && self->thread_id != Tcl_GetCurrentThread()) { - Tcl_Condition cond = NULL; - CommandEvent *ev; - ev = (CommandEvent*)ckalloc(sizeof(CommandEvent)); - ev->ev.proc = (Tcl_EventProc*)Tkapp_CommandProc; - ev->interp = self->interp; - ev->create = 0; - ev->name = cmdName; - ev->status = &err; - ev->done = &cond; - Tkapp_ThreadSend(self, (Tcl_Event*)ev, &cond, - &command_mutex); - Tcl_ConditionFinalize(&cond); - } - else -#endif - { - ENTER_TCL - err = Tcl_DeleteCommand(self->interp, cmdName); - LEAVE_TCL - } - if (err == -1) { - PyErr_SetString(Tkinter_TclError, "can't delete Tcl command"); - return NULL; - } - Py_INCREF(Py_None); - return Py_None; + TkappObject *self = (TkappObject*)selfptr; + char *cmdName; + int err; + + if (!PyArg_ParseTuple(args, "s:deletecommand", &cmdName)) + return NULL; + +#ifdef WITH_THREAD + if (self->threaded && self->thread_id != Tcl_GetCurrentThread()) { + Tcl_Condition cond = NULL; + CommandEvent *ev; + ev = (CommandEvent*)ckalloc(sizeof(CommandEvent)); + ev->ev.proc = (Tcl_EventProc*)Tkapp_CommandProc; + ev->interp = self->interp; + ev->create = 0; + ev->name = cmdName; + ev->status = &err; + ev->done = &cond; + Tkapp_ThreadSend(self, (Tcl_Event*)ev, &cond, + &command_mutex); + Tcl_ConditionFinalize(&cond); + } + else +#endif + { + ENTER_TCL + err = Tcl_DeleteCommand(self->interp, cmdName); + LEAVE_TCL + } + if (err == -1) { + PyErr_SetString(Tkinter_TclError, "can't delete Tcl command"); + return NULL; + } + Py_INCREF(Py_None); + return Py_None; } - + #ifdef HAVE_CREATEFILEHANDLER /** File Handler **/ typedef struct _fhcdata { - PyObject *func; - PyObject *file; - int id; - struct _fhcdata *next; + PyObject *func; + PyObject *file; + int id; + struct _fhcdata *next; } FileHandler_ClientData; static FileHandler_ClientData *HeadFHCD; @@ -2216,712 +2216,712 @@ static FileHandler_ClientData * NewFHCD(PyObject *func, PyObject *file, int id) { - FileHandler_ClientData *p; - p = PyMem_NEW(FileHandler_ClientData, 1); - if (p != NULL) { - Py_XINCREF(func); - Py_XINCREF(file); - p->func = func; - p->file = file; - p->id = id; - p->next = HeadFHCD; - HeadFHCD = p; - } - return p; + FileHandler_ClientData *p; + p = PyMem_NEW(FileHandler_ClientData, 1); + if (p != NULL) { + Py_XINCREF(func); + Py_XINCREF(file); + p->func = func; + p->file = file; + p->id = id; + p->next = HeadFHCD; + HeadFHCD = p; + } + return p; } static void DeleteFHCD(int id) { - FileHandler_ClientData *p, **pp; + FileHandler_ClientData *p, **pp; - pp = &HeadFHCD; - while ((p = *pp) != NULL) { - if (p->id == id) { - *pp = p->next; - Py_XDECREF(p->func); - Py_XDECREF(p->file); - PyMem_DEL(p); - } - else - pp = &p->next; - } + pp = &HeadFHCD; + while ((p = *pp) != NULL) { + if (p->id == id) { + *pp = p->next; + Py_XDECREF(p->func); + Py_XDECREF(p->file); + PyMem_DEL(p); + } + else + pp = &p->next; + } } static void FileHandler(ClientData clientData, int mask) { - FileHandler_ClientData *data = (FileHandler_ClientData *)clientData; - PyObject *func, *file, *arg, *res; + FileHandler_ClientData *data = (FileHandler_ClientData *)clientData; + PyObject *func, *file, *arg, *res; - ENTER_PYTHON - func = data->func; - file = data->file; - - arg = Py_BuildValue("(Oi)", file, (long) mask); - res = PyEval_CallObject(func, arg); - Py_DECREF(arg); - - if (res == NULL) { - errorInCmd = 1; - PyErr_Fetch(&excInCmd, &valInCmd, &trbInCmd); - } - Py_XDECREF(res); - LEAVE_PYTHON + ENTER_PYTHON + func = data->func; + file = data->file; + + arg = Py_BuildValue("(Oi)", file, (long) mask); + res = PyEval_CallObject(func, arg); + Py_DECREF(arg); + + if (res == NULL) { + errorInCmd = 1; + PyErr_Fetch(&excInCmd, &valInCmd, &trbInCmd); + } + Py_XDECREF(res); + LEAVE_PYTHON } static PyObject * Tkapp_CreateFileHandler(PyObject *self, PyObject *args) /* args is (file, mask, func) */ { - FileHandler_ClientData *data; - PyObject *file, *func; - int mask, tfile; - - if (!PyArg_ParseTuple(args, "OiO:createfilehandler", - &file, &mask, &func)) - return NULL; - - CHECK_TCL_APPARTMENT; - - tfile = PyObject_AsFileDescriptor(file); - if (tfile < 0) - return NULL; - if (!PyCallable_Check(func)) { - PyErr_SetString(PyExc_TypeError, "bad argument list"); - return NULL; - } - - data = NewFHCD(func, file, tfile); - if (data == NULL) - return NULL; - - /* Ought to check for null Tcl_File object... */ - ENTER_TCL - Tcl_CreateFileHandler(tfile, mask, FileHandler, (ClientData) data); - LEAVE_TCL - Py_INCREF(Py_None); - return Py_None; + FileHandler_ClientData *data; + PyObject *file, *func; + int mask, tfile; + + if (!PyArg_ParseTuple(args, "OiO:createfilehandler", + &file, &mask, &func)) + return NULL; + + CHECK_TCL_APPARTMENT; + + tfile = PyObject_AsFileDescriptor(file); + if (tfile < 0) + return NULL; + if (!PyCallable_Check(func)) { + PyErr_SetString(PyExc_TypeError, "bad argument list"); + return NULL; + } + + data = NewFHCD(func, file, tfile); + if (data == NULL) + return NULL; + + /* Ought to check for null Tcl_File object... */ + ENTER_TCL + Tcl_CreateFileHandler(tfile, mask, FileHandler, (ClientData) data); + LEAVE_TCL + Py_INCREF(Py_None); + return Py_None; } static PyObject * Tkapp_DeleteFileHandler(PyObject *self, PyObject *args) { - PyObject *file; - int tfile; + PyObject *file; + int tfile; - if (!PyArg_ParseTuple(args, "O:deletefilehandler", &file)) - return NULL; + if (!PyArg_ParseTuple(args, "O:deletefilehandler", &file)) + return NULL; - CHECK_TCL_APPARTMENT; + CHECK_TCL_APPARTMENT; - tfile = PyObject_AsFileDescriptor(file); - if (tfile < 0) - return NULL; - - DeleteFHCD(tfile); - - /* Ought to check for null Tcl_File object... */ - ENTER_TCL - Tcl_DeleteFileHandler(tfile); - LEAVE_TCL - Py_INCREF(Py_None); - return Py_None; + tfile = PyObject_AsFileDescriptor(file); + if (tfile < 0) + return NULL; + + DeleteFHCD(tfile); + + /* Ought to check for null Tcl_File object... */ + ENTER_TCL + Tcl_DeleteFileHandler(tfile); + LEAVE_TCL + Py_INCREF(Py_None); + return Py_None; } #endif /* HAVE_CREATEFILEHANDLER */ - + /**** Tktt Object (timer token) ****/ static PyTypeObject Tktt_Type; typedef struct { - PyObject_HEAD - Tcl_TimerToken token; - PyObject *func; + PyObject_HEAD + Tcl_TimerToken token; + PyObject *func; } TkttObject; static PyObject * Tktt_DeleteTimerHandler(PyObject *self, PyObject *args) { - TkttObject *v = (TkttObject *)self; - PyObject *func = v->func; + TkttObject *v = (TkttObject *)self; + PyObject *func = v->func; - if (!PyArg_ParseTuple(args, ":deletetimerhandler")) - return NULL; - if (v->token != NULL) { - Tcl_DeleteTimerHandler(v->token); - v->token = NULL; - } - if (func != NULL) { - v->func = NULL; - Py_DECREF(func); - Py_DECREF(v); /* See Tktt_New() */ - } - Py_INCREF(Py_None); - return Py_None; + if (!PyArg_ParseTuple(args, ":deletetimerhandler")) + return NULL; + if (v->token != NULL) { + Tcl_DeleteTimerHandler(v->token); + v->token = NULL; + } + if (func != NULL) { + v->func = NULL; + Py_DECREF(func); + Py_DECREF(v); /* See Tktt_New() */ + } + Py_INCREF(Py_None); + return Py_None; } static PyMethodDef Tktt_methods[] = { - {"deletetimerhandler", Tktt_DeleteTimerHandler, METH_VARARGS}, - {NULL, NULL} + {"deletetimerhandler", Tktt_DeleteTimerHandler, METH_VARARGS}, + {NULL, NULL} }; static TkttObject * Tktt_New(PyObject *func) { - TkttObject *v; + TkttObject *v; - v = PyObject_New(TkttObject, &Tktt_Type); - if (v == NULL) - return NULL; - - Py_INCREF(func); - v->token = NULL; - v->func = func; - - /* Extra reference, deleted when called or when handler is deleted */ - Py_INCREF(v); - return v; + v = PyObject_New(TkttObject, &Tktt_Type); + if (v == NULL) + return NULL; + + Py_INCREF(func); + v->token = NULL; + v->func = func; + + /* Extra reference, deleted when called or when handler is deleted */ + Py_INCREF(v); + return v; } static void Tktt_Dealloc(PyObject *self) { - TkttObject *v = (TkttObject *)self; - PyObject *func = v->func; + TkttObject *v = (TkttObject *)self; + PyObject *func = v->func; - Py_XDECREF(func); + Py_XDECREF(func); - PyObject_Del(self); + PyObject_Del(self); } static PyObject * Tktt_Repr(PyObject *self) { - TkttObject *v = (TkttObject *)self; - char buf[100]; + TkttObject *v = (TkttObject *)self; + char buf[100]; - PyOS_snprintf(buf, sizeof(buf), "", v, - v->func == NULL ? ", handler deleted" : ""); - return PyUnicode_FromString(buf); + PyOS_snprintf(buf, sizeof(buf), "", v, + v->func == NULL ? ", handler deleted" : ""); + return PyUnicode_FromString(buf); } static PyTypeObject Tktt_Type = { - PyVarObject_HEAD_INIT(NULL, 0) - "tktimertoken", /*tp_name */ - sizeof(TkttObject), /*tp_basicsize */ - 0, /*tp_itemsize */ - Tktt_Dealloc, /*tp_dealloc */ - 0, /*tp_print */ - 0, /*tp_getattr */ - 0, /*tp_setattr */ - 0, /*tp_reserved */ - Tktt_Repr, /*tp_repr */ - 0, /*tp_as_number */ - 0, /*tp_as_sequence */ - 0, /*tp_as_mapping */ - 0, /*tp_hash */ - 0, /*tp_call*/ - 0, /*tp_str*/ - 0, /*tp_getattro*/ - 0, /*tp_setattro*/ - 0, /*tp_as_buffer*/ - Py_TPFLAGS_DEFAULT, /*tp_flags*/ - 0, /*tp_doc*/ - 0, /*tp_traverse*/ - 0, /*tp_clear*/ - 0, /*tp_richcompare*/ - 0, /*tp_weaklistoffset*/ - 0, /*tp_iter*/ - 0, /*tp_iternext*/ - Tktt_methods, /*tp_methods*/ + PyVarObject_HEAD_INIT(NULL, 0) + "tktimertoken", /*tp_name */ + sizeof(TkttObject), /*tp_basicsize */ + 0, /*tp_itemsize */ + Tktt_Dealloc, /*tp_dealloc */ + 0, /*tp_print */ + 0, /*tp_getattr */ + 0, /*tp_setattr */ + 0, /*tp_reserved */ + Tktt_Repr, /*tp_repr */ + 0, /*tp_as_number */ + 0, /*tp_as_sequence */ + 0, /*tp_as_mapping */ + 0, /*tp_hash */ + 0, /*tp_call*/ + 0, /*tp_str*/ + 0, /*tp_getattro*/ + 0, /*tp_setattro*/ + 0, /*tp_as_buffer*/ + Py_TPFLAGS_DEFAULT, /*tp_flags*/ + 0, /*tp_doc*/ + 0, /*tp_traverse*/ + 0, /*tp_clear*/ + 0, /*tp_richcompare*/ + 0, /*tp_weaklistoffset*/ + 0, /*tp_iter*/ + 0, /*tp_iternext*/ + Tktt_methods, /*tp_methods*/ }; - + /** Timer Handler **/ static void TimerHandler(ClientData clientData) { - TkttObject *v = (TkttObject *)clientData; - PyObject *func = v->func; - PyObject *res; + TkttObject *v = (TkttObject *)clientData; + PyObject *func = v->func; + PyObject *res; - if (func == NULL) - return; + if (func == NULL) + return; - v->func = NULL; + v->func = NULL; - ENTER_PYTHON + ENTER_PYTHON - res = PyEval_CallObject(func, NULL); - Py_DECREF(func); - Py_DECREF(v); /* See Tktt_New() */ + res = PyEval_CallObject(func, NULL); + Py_DECREF(func); + Py_DECREF(v); /* See Tktt_New() */ - if (res == NULL) { - errorInCmd = 1; - PyErr_Fetch(&excInCmd, &valInCmd, &trbInCmd); - } - else - Py_DECREF(res); + if (res == NULL) { + errorInCmd = 1; + PyErr_Fetch(&excInCmd, &valInCmd, &trbInCmd); + } + else + Py_DECREF(res); - LEAVE_PYTHON + LEAVE_PYTHON } static PyObject * Tkapp_CreateTimerHandler(PyObject *self, PyObject *args) { - int milliseconds; - PyObject *func; - TkttObject *v; - - if (!PyArg_ParseTuple(args, "iO:createtimerhandler", - &milliseconds, &func)) - return NULL; - if (!PyCallable_Check(func)) { - PyErr_SetString(PyExc_TypeError, "bad argument list"); - return NULL; - } - - CHECK_TCL_APPARTMENT; - - v = Tktt_New(func); - if (v) { - v->token = Tcl_CreateTimerHandler(milliseconds, TimerHandler, - (ClientData)v); - } + int milliseconds; + PyObject *func; + TkttObject *v; + + if (!PyArg_ParseTuple(args, "iO:createtimerhandler", + &milliseconds, &func)) + return NULL; + if (!PyCallable_Check(func)) { + PyErr_SetString(PyExc_TypeError, "bad argument list"); + return NULL; + } + + CHECK_TCL_APPARTMENT; + + v = Tktt_New(func); + if (v) { + v->token = Tcl_CreateTimerHandler(milliseconds, TimerHandler, + (ClientData)v); + } - return (PyObject *) v; + return (PyObject *) v; } - + /** Event Loop **/ static PyObject * Tkapp_MainLoop(PyObject *selfptr, PyObject *args) { - int threshold = 0; - TkappObject *self = (TkappObject*)selfptr; + int threshold = 0; + TkappObject *self = (TkappObject*)selfptr; #ifdef WITH_THREAD - PyThreadState *tstate = PyThreadState_Get(); + PyThreadState *tstate = PyThreadState_Get(); #endif - if (!PyArg_ParseTuple(args, "|i:mainloop", &threshold)) - return NULL; + if (!PyArg_ParseTuple(args, "|i:mainloop", &threshold)) + return NULL; - CHECK_TCL_APPARTMENT; - self->dispatching = 1; - - quitMainLoop = 0; - while (Tk_GetNumMainWindows() > threshold && - !quitMainLoop && - !errorInCmd) - { - int result; - -#ifdef WITH_THREAD - if (self->threaded) { - /* Allow other Python threads to run. */ - ENTER_TCL - result = Tcl_DoOneEvent(0); - LEAVE_TCL - } - else { - Py_BEGIN_ALLOW_THREADS - if(tcl_lock)PyThread_acquire_lock(tcl_lock, 1); - tcl_tstate = tstate; - result = Tcl_DoOneEvent(TCL_DONT_WAIT); - tcl_tstate = NULL; - if(tcl_lock)PyThread_release_lock(tcl_lock); - if (result == 0) - Sleep(Tkinter_busywaitinterval); - Py_END_ALLOW_THREADS - } + CHECK_TCL_APPARTMENT; + self->dispatching = 1; + + quitMainLoop = 0; + while (Tk_GetNumMainWindows() > threshold && + !quitMainLoop && + !errorInCmd) + { + int result; + +#ifdef WITH_THREAD + if (self->threaded) { + /* Allow other Python threads to run. */ + ENTER_TCL + result = Tcl_DoOneEvent(0); + LEAVE_TCL + } + else { + Py_BEGIN_ALLOW_THREADS + if(tcl_lock)PyThread_acquire_lock(tcl_lock, 1); + tcl_tstate = tstate; + result = Tcl_DoOneEvent(TCL_DONT_WAIT); + tcl_tstate = NULL; + if(tcl_lock)PyThread_release_lock(tcl_lock); + if (result == 0) + Sleep(Tkinter_busywaitinterval); + Py_END_ALLOW_THREADS + } #else - result = Tcl_DoOneEvent(0); + result = Tcl_DoOneEvent(0); #endif - if (PyErr_CheckSignals() != 0) { - self->dispatching = 0; - return NULL; - } - if (result < 0) - break; - } - self->dispatching = 0; - quitMainLoop = 0; - - if (errorInCmd) { - errorInCmd = 0; - PyErr_Restore(excInCmd, valInCmd, trbInCmd); - excInCmd = valInCmd = trbInCmd = NULL; - return NULL; - } - Py_INCREF(Py_None); - return Py_None; + if (PyErr_CheckSignals() != 0) { + self->dispatching = 0; + return NULL; + } + if (result < 0) + break; + } + self->dispatching = 0; + quitMainLoop = 0; + + if (errorInCmd) { + errorInCmd = 0; + PyErr_Restore(excInCmd, valInCmd, trbInCmd); + excInCmd = valInCmd = trbInCmd = NULL; + return NULL; + } + Py_INCREF(Py_None); + return Py_None; } static PyObject * Tkapp_DoOneEvent(PyObject *self, PyObject *args) { - int flags = 0; - int rv; + int flags = 0; + int rv; - if (!PyArg_ParseTuple(args, "|i:dooneevent", &flags)) - return NULL; + if (!PyArg_ParseTuple(args, "|i:dooneevent", &flags)) + return NULL; - ENTER_TCL - rv = Tcl_DoOneEvent(flags); - LEAVE_TCL - return Py_BuildValue("i", rv); + ENTER_TCL + rv = Tcl_DoOneEvent(flags); + LEAVE_TCL + return Py_BuildValue("i", rv); } static PyObject * Tkapp_Quit(PyObject *self, PyObject *args) { - if (!PyArg_ParseTuple(args, ":quit")) - return NULL; + if (!PyArg_ParseTuple(args, ":quit")) + return NULL; - quitMainLoop = 1; - Py_INCREF(Py_None); - return Py_None; + quitMainLoop = 1; + Py_INCREF(Py_None); + return Py_None; } static PyObject * Tkapp_InterpAddr(PyObject *self, PyObject *args) { - if (!PyArg_ParseTuple(args, ":interpaddr")) - return NULL; + if (!PyArg_ParseTuple(args, ":interpaddr")) + return NULL; - return PyLong_FromLong((long)Tkapp_Interp(self)); + return PyLong_FromLong((long)Tkapp_Interp(self)); } -static PyObject * +static PyObject * Tkapp_TkInit(PyObject *self, PyObject *args) { - Tcl_Interp *interp = Tkapp_Interp(self); - const char * _tk_exists = NULL; - int err; + Tcl_Interp *interp = Tkapp_Interp(self); + const char * _tk_exists = NULL; + int err; #ifdef TKINTER_PROTECT_LOADTK - /* Up to Tk 8.4.13, Tk_Init deadlocks on the second call when the - * first call failed. - * To avoid the deadlock, we just refuse the second call through - * a static variable. - */ - if (tk_load_failed) { - PyErr_SetString(Tkinter_TclError, TKINTER_LOADTK_ERRMSG); - return NULL; - } -#endif - - /* We want to guard against calling Tk_Init() multiple times */ - CHECK_TCL_APPARTMENT; - ENTER_TCL - err = Tcl_Eval(Tkapp_Interp(self), "info exists tk_version"); - ENTER_OVERLAP - if (err == TCL_ERROR) { - /* This sets an exception, but we cannot return right - away because we need to exit the overlap first. */ - Tkinter_Error(self); - } else { - _tk_exists = Tkapp_Result(self); - } - LEAVE_OVERLAP_TCL - if (err == TCL_ERROR) { - return NULL; - } - if (_tk_exists == NULL || strcmp(_tk_exists, "1") != 0) { - if (Tk_Init(interp) == TCL_ERROR) { - PyErr_SetString(Tkinter_TclError, Tcl_GetStringResult(Tkapp_Interp(self))); + /* Up to Tk 8.4.13, Tk_Init deadlocks on the second call when the + * first call failed. + * To avoid the deadlock, we just refuse the second call through + * a static variable. + */ + if (tk_load_failed) { + PyErr_SetString(Tkinter_TclError, TKINTER_LOADTK_ERRMSG); + return NULL; + } +#endif + + /* We want to guard against calling Tk_Init() multiple times */ + CHECK_TCL_APPARTMENT; + ENTER_TCL + err = Tcl_Eval(Tkapp_Interp(self), "info exists tk_version"); + ENTER_OVERLAP + if (err == TCL_ERROR) { + /* This sets an exception, but we cannot return right + away because we need to exit the overlap first. */ + Tkinter_Error(self); + } else { + _tk_exists = Tkapp_Result(self); + } + LEAVE_OVERLAP_TCL + if (err == TCL_ERROR) { + return NULL; + } + if (_tk_exists == NULL || strcmp(_tk_exists, "1") != 0) { + if (Tk_Init(interp) == TCL_ERROR) { + PyErr_SetString(Tkinter_TclError, Tcl_GetStringResult(Tkapp_Interp(self))); #ifdef TKINTER_PROTECT_LOADTK - tk_load_failed = 1; + tk_load_failed = 1; #endif - return NULL; - } - } - Py_INCREF(Py_None); - return Py_None; + return NULL; + } + } + Py_INCREF(Py_None); + return Py_None; } static PyObject * Tkapp_WantObjects(PyObject *self, PyObject *args) { - int wantobjects = -1; - if (!PyArg_ParseTuple(args, "|i:wantobjects", &wantobjects)) - return NULL; - if (wantobjects == -1) - return PyBool_FromLong(((TkappObject*)self)->wantobjects); - ((TkappObject*)self)->wantobjects = wantobjects; + int wantobjects = -1; + if (!PyArg_ParseTuple(args, "|i:wantobjects", &wantobjects)) + return NULL; + if (wantobjects == -1) + return PyBool_FromLong(((TkappObject*)self)->wantobjects); + ((TkappObject*)self)->wantobjects = wantobjects; - Py_INCREF(Py_None); - return Py_None; + Py_INCREF(Py_None); + return Py_None; } static PyObject * Tkapp_WillDispatch(PyObject *self, PyObject *args) { - ((TkappObject*)self)->dispatching = 1; + ((TkappObject*)self)->dispatching = 1; - Py_INCREF(Py_None); - return Py_None; + Py_INCREF(Py_None); + return Py_None; } - + /**** Tkapp Method List ****/ static PyMethodDef Tkapp_methods[] = { - {"willdispatch", Tkapp_WillDispatch, METH_NOARGS}, - {"wantobjects", Tkapp_WantObjects, METH_VARARGS}, - {"call", Tkapp_Call, METH_VARARGS}, - {"globalcall", Tkapp_GlobalCall, METH_VARARGS}, - {"eval", Tkapp_Eval, METH_VARARGS}, - {"globaleval", Tkapp_GlobalEval, METH_VARARGS}, - {"evalfile", Tkapp_EvalFile, METH_VARARGS}, - {"record", Tkapp_Record, METH_VARARGS}, - {"adderrorinfo", Tkapp_AddErrorInfo, METH_VARARGS}, - {"setvar", Tkapp_SetVar, METH_VARARGS}, - {"globalsetvar", Tkapp_GlobalSetVar, METH_VARARGS}, - {"getvar", Tkapp_GetVar, METH_VARARGS}, - {"globalgetvar", Tkapp_GlobalGetVar, METH_VARARGS}, - {"unsetvar", Tkapp_UnsetVar, METH_VARARGS}, - {"globalunsetvar", Tkapp_GlobalUnsetVar, METH_VARARGS}, - {"getint", Tkapp_GetInt, METH_VARARGS}, - {"getdouble", Tkapp_GetDouble, METH_VARARGS}, - {"getboolean", Tkapp_GetBoolean, METH_VARARGS}, - {"exprstring", Tkapp_ExprString, METH_VARARGS}, - {"exprlong", Tkapp_ExprLong, METH_VARARGS}, - {"exprdouble", Tkapp_ExprDouble, METH_VARARGS}, - {"exprboolean", Tkapp_ExprBoolean, METH_VARARGS}, - {"splitlist", Tkapp_SplitList, METH_VARARGS}, - {"split", Tkapp_Split, METH_VARARGS}, - {"merge", Tkapp_Merge, METH_VARARGS}, - {"createcommand", Tkapp_CreateCommand, METH_VARARGS}, - {"deletecommand", Tkapp_DeleteCommand, METH_VARARGS}, + {"willdispatch", Tkapp_WillDispatch, METH_NOARGS}, + {"wantobjects", Tkapp_WantObjects, METH_VARARGS}, + {"call", Tkapp_Call, METH_VARARGS}, + {"globalcall", Tkapp_GlobalCall, METH_VARARGS}, + {"eval", Tkapp_Eval, METH_VARARGS}, + {"globaleval", Tkapp_GlobalEval, METH_VARARGS}, + {"evalfile", Tkapp_EvalFile, METH_VARARGS}, + {"record", Tkapp_Record, METH_VARARGS}, + {"adderrorinfo", Tkapp_AddErrorInfo, METH_VARARGS}, + {"setvar", Tkapp_SetVar, METH_VARARGS}, + {"globalsetvar", Tkapp_GlobalSetVar, METH_VARARGS}, + {"getvar", Tkapp_GetVar, METH_VARARGS}, + {"globalgetvar", Tkapp_GlobalGetVar, METH_VARARGS}, + {"unsetvar", Tkapp_UnsetVar, METH_VARARGS}, + {"globalunsetvar", Tkapp_GlobalUnsetVar, METH_VARARGS}, + {"getint", Tkapp_GetInt, METH_VARARGS}, + {"getdouble", Tkapp_GetDouble, METH_VARARGS}, + {"getboolean", Tkapp_GetBoolean, METH_VARARGS}, + {"exprstring", Tkapp_ExprString, METH_VARARGS}, + {"exprlong", Tkapp_ExprLong, METH_VARARGS}, + {"exprdouble", Tkapp_ExprDouble, METH_VARARGS}, + {"exprboolean", Tkapp_ExprBoolean, METH_VARARGS}, + {"splitlist", Tkapp_SplitList, METH_VARARGS}, + {"split", Tkapp_Split, METH_VARARGS}, + {"merge", Tkapp_Merge, METH_VARARGS}, + {"createcommand", Tkapp_CreateCommand, METH_VARARGS}, + {"deletecommand", Tkapp_DeleteCommand, METH_VARARGS}, #ifdef HAVE_CREATEFILEHANDLER - {"createfilehandler", Tkapp_CreateFileHandler, METH_VARARGS}, - {"deletefilehandler", Tkapp_DeleteFileHandler, METH_VARARGS}, + {"createfilehandler", Tkapp_CreateFileHandler, METH_VARARGS}, + {"deletefilehandler", Tkapp_DeleteFileHandler, METH_VARARGS}, #endif - {"createtimerhandler", Tkapp_CreateTimerHandler, METH_VARARGS}, - {"mainloop", Tkapp_MainLoop, METH_VARARGS}, - {"dooneevent", Tkapp_DoOneEvent, METH_VARARGS}, - {"quit", Tkapp_Quit, METH_VARARGS}, - {"interpaddr", Tkapp_InterpAddr, METH_VARARGS}, - {"loadtk", Tkapp_TkInit, METH_NOARGS}, - {NULL, NULL} + {"createtimerhandler", Tkapp_CreateTimerHandler, METH_VARARGS}, + {"mainloop", Tkapp_MainLoop, METH_VARARGS}, + {"dooneevent", Tkapp_DoOneEvent, METH_VARARGS}, + {"quit", Tkapp_Quit, METH_VARARGS}, + {"interpaddr", Tkapp_InterpAddr, METH_VARARGS}, + {"loadtk", Tkapp_TkInit, METH_NOARGS}, + {NULL, NULL} }; - + /**** Tkapp Type Methods ****/ static void Tkapp_Dealloc(PyObject *self) { - /*CHECK_TCL_APPARTMENT;*/ - ENTER_TCL - Tcl_DeleteInterp(Tkapp_Interp(self)); - LEAVE_TCL - PyObject_Del(self); - DisableEventHook(); + /*CHECK_TCL_APPARTMENT;*/ + ENTER_TCL + Tcl_DeleteInterp(Tkapp_Interp(self)); + LEAVE_TCL + PyObject_Del(self); + DisableEventHook(); } static PyTypeObject Tkapp_Type = { - PyVarObject_HEAD_INIT(NULL, 0) - "tkapp", /*tp_name */ - sizeof(TkappObject), /*tp_basicsize */ - 0, /*tp_itemsize */ - Tkapp_Dealloc, /*tp_dealloc */ - 0, /*tp_print */ - 0, /*tp_getattr */ - 0, /*tp_setattr */ - 0, /*tp_reserved */ - 0, /*tp_repr */ - 0, /*tp_as_number */ - 0, /*tp_as_sequence */ - 0, /*tp_as_mapping */ - 0, /*tp_hash */ - 0, /*tp_call*/ - 0, /*tp_str*/ - 0, /*tp_getattro*/ - 0, /*tp_setattro*/ - 0, /*tp_as_buffer*/ - Py_TPFLAGS_DEFAULT, /*tp_flags*/ - 0, /*tp_doc*/ - 0, /*tp_traverse*/ - 0, /*tp_clear*/ - 0, /*tp_richcompare*/ - 0, /*tp_weaklistoffset*/ - 0, /*tp_iter*/ - 0, /*tp_iternext*/ - Tkapp_methods, /*tp_methods*/ + PyVarObject_HEAD_INIT(NULL, 0) + "tkapp", /*tp_name */ + sizeof(TkappObject), /*tp_basicsize */ + 0, /*tp_itemsize */ + Tkapp_Dealloc, /*tp_dealloc */ + 0, /*tp_print */ + 0, /*tp_getattr */ + 0, /*tp_setattr */ + 0, /*tp_reserved */ + 0, /*tp_repr */ + 0, /*tp_as_number */ + 0, /*tp_as_sequence */ + 0, /*tp_as_mapping */ + 0, /*tp_hash */ + 0, /*tp_call*/ + 0, /*tp_str*/ + 0, /*tp_getattro*/ + 0, /*tp_setattro*/ + 0, /*tp_as_buffer*/ + Py_TPFLAGS_DEFAULT, /*tp_flags*/ + 0, /*tp_doc*/ + 0, /*tp_traverse*/ + 0, /*tp_clear*/ + 0, /*tp_richcompare*/ + 0, /*tp_weaklistoffset*/ + 0, /*tp_iter*/ + 0, /*tp_iternext*/ + Tkapp_methods, /*tp_methods*/ }; - + /**** Tkinter Module ****/ typedef struct { - PyObject* tuple; - int size; /* current size */ - int maxsize; /* allocated size */ + PyObject* tuple; + int size; /* current size */ + int maxsize; /* allocated size */ } FlattenContext; static int _bump(FlattenContext* context, int size) { - /* expand tuple to hold (at least) size new items. - return true if successful, false if an exception was raised */ + /* expand tuple to hold (at least) size new items. + return true if successful, false if an exception was raised */ - int maxsize = context->maxsize * 2; + int maxsize = context->maxsize * 2; - if (maxsize < context->size + size) - maxsize = context->size + size; + if (maxsize < context->size + size) + maxsize = context->size + size; - context->maxsize = maxsize; + context->maxsize = maxsize; - return _PyTuple_Resize(&context->tuple, maxsize) >= 0; + return _PyTuple_Resize(&context->tuple, maxsize) >= 0; } static int _flatten1(FlattenContext* context, PyObject* item, int depth) { - /* add tuple or list to argument tuple (recursively) */ + /* add tuple or list to argument tuple (recursively) */ - int i, size; + int i, size; - if (depth > 1000) { - PyErr_SetString(PyExc_ValueError, - "nesting too deep in _flatten"); - return 0; - } else if (PyList_Check(item)) { - size = PyList_GET_SIZE(item); - /* preallocate (assume no nesting) */ - if (context->size + size > context->maxsize && - !_bump(context, size)) - return 0; - /* copy items to output tuple */ - for (i = 0; i < size; i++) { - PyObject *o = PyList_GET_ITEM(item, i); - if (PyList_Check(o) || PyTuple_Check(o)) { - if (!_flatten1(context, o, depth + 1)) - return 0; - } else if (o != Py_None) { - if (context->size + 1 > context->maxsize && - !_bump(context, 1)) - return 0; - Py_INCREF(o); - PyTuple_SET_ITEM(context->tuple, - context->size++, o); - } - } - } else if (PyTuple_Check(item)) { - /* same, for tuples */ - size = PyTuple_GET_SIZE(item); - if (context->size + size > context->maxsize && - !_bump(context, size)) - return 0; - for (i = 0; i < size; i++) { - PyObject *o = PyTuple_GET_ITEM(item, i); - if (PyList_Check(o) || PyTuple_Check(o)) { - if (!_flatten1(context, o, depth + 1)) - return 0; - } else if (o != Py_None) { - if (context->size + 1 > context->maxsize && - !_bump(context, 1)) - return 0; - Py_INCREF(o); - PyTuple_SET_ITEM(context->tuple, - context->size++, o); - } - } - } else { - PyErr_SetString(PyExc_TypeError, "argument must be sequence"); - return 0; - } - return 1; + if (depth > 1000) { + PyErr_SetString(PyExc_ValueError, + "nesting too deep in _flatten"); + return 0; + } else if (PyList_Check(item)) { + size = PyList_GET_SIZE(item); + /* preallocate (assume no nesting) */ + if (context->size + size > context->maxsize && + !_bump(context, size)) + return 0; + /* copy items to output tuple */ + for (i = 0; i < size; i++) { + PyObject *o = PyList_GET_ITEM(item, i); + if (PyList_Check(o) || PyTuple_Check(o)) { + if (!_flatten1(context, o, depth + 1)) + return 0; + } else if (o != Py_None) { + if (context->size + 1 > context->maxsize && + !_bump(context, 1)) + return 0; + Py_INCREF(o); + PyTuple_SET_ITEM(context->tuple, + context->size++, o); + } + } + } else if (PyTuple_Check(item)) { + /* same, for tuples */ + size = PyTuple_GET_SIZE(item); + if (context->size + size > context->maxsize && + !_bump(context, size)) + return 0; + for (i = 0; i < size; i++) { + PyObject *o = PyTuple_GET_ITEM(item, i); + if (PyList_Check(o) || PyTuple_Check(o)) { + if (!_flatten1(context, o, depth + 1)) + return 0; + } else if (o != Py_None) { + if (context->size + 1 > context->maxsize && + !_bump(context, 1)) + return 0; + Py_INCREF(o); + PyTuple_SET_ITEM(context->tuple, + context->size++, o); + } + } + } else { + PyErr_SetString(PyExc_TypeError, "argument must be sequence"); + return 0; + } + return 1; } static PyObject * Tkinter_Flatten(PyObject* self, PyObject* args) { - FlattenContext context; - PyObject* item; + FlattenContext context; + PyObject* item; - if (!PyArg_ParseTuple(args, "O:_flatten", &item)) - return NULL; + if (!PyArg_ParseTuple(args, "O:_flatten", &item)) + return NULL; - context.maxsize = PySequence_Size(item); - if (context.maxsize < 0) - return NULL; - if (context.maxsize == 0) - return PyTuple_New(0); + context.maxsize = PySequence_Size(item); + if (context.maxsize < 0) + return NULL; + if (context.maxsize == 0) + return PyTuple_New(0); - context.tuple = PyTuple_New(context.maxsize); - if (!context.tuple) - return NULL; + context.tuple = PyTuple_New(context.maxsize); + if (!context.tuple) + return NULL; - context.size = 0; + context.size = 0; - if (!_flatten1(&context, item,0)) - return NULL; + if (!_flatten1(&context, item,0)) + return NULL; - if (_PyTuple_Resize(&context.tuple, context.size)) - return NULL; + if (_PyTuple_Resize(&context.tuple, context.size)) + return NULL; - return context.tuple; + return context.tuple; } static PyObject * Tkinter_Create(PyObject *self, PyObject *args) { - char *screenName = NULL; - char *baseName = NULL; /* XXX this is not used anymore; - try getting rid of it. */ - char *className = NULL; - int interactive = 0; - int wantobjects = 0; - int wantTk = 1; /* If false, then Tk_Init() doesn't get called */ - int sync = 0; /* pass -sync to wish */ - char *use = NULL; /* pass -use to wish */ - - className = "Tk"; - - if (!PyArg_ParseTuple(args, "|zssiiiiz:create", - &screenName, &baseName, &className, - &interactive, &wantobjects, &wantTk, - &sync, &use)) - return NULL; - - return (PyObject *) Tkapp_New(screenName, className, - interactive, wantobjects, wantTk, - sync, use); + char *screenName = NULL; + char *baseName = NULL; /* XXX this is not used anymore; + try getting rid of it. */ + char *className = NULL; + int interactive = 0; + int wantobjects = 0; + int wantTk = 1; /* If false, then Tk_Init() doesn't get called */ + int sync = 0; /* pass -sync to wish */ + char *use = NULL; /* pass -use to wish */ + + className = "Tk"; + + if (!PyArg_ParseTuple(args, "|zssiiiiz:create", + &screenName, &baseName, &className, + &interactive, &wantobjects, &wantTk, + &sync, &use)) + return NULL; + + return (PyObject *) Tkapp_New(screenName, className, + interactive, wantobjects, wantTk, + sync, use); } static PyObject * Tkinter_setbusywaitinterval(PyObject *self, PyObject *args) { - int new_val; - if (!PyArg_ParseTuple(args, "i:setbusywaitinterval", &new_val)) - return NULL; - if (new_val < 0) { - PyErr_SetString(PyExc_ValueError, - "busywaitinterval must be >= 0"); - return NULL; - } - Tkinter_busywaitinterval = new_val; - Py_INCREF(Py_None); - return Py_None; + int new_val; + if (!PyArg_ParseTuple(args, "i:setbusywaitinterval", &new_val)) + return NULL; + if (new_val < 0) { + PyErr_SetString(PyExc_ValueError, + "busywaitinterval must be >= 0"); + return NULL; + } + Tkinter_busywaitinterval = new_val; + Py_INCREF(Py_None); + return Py_None; } static char setbusywaitinterval_doc[] = @@ -2935,7 +2935,7 @@ static PyObject * Tkinter_getbusywaitinterval(PyObject *self, PyObject *args) { - return PyLong_FromLong(Tkinter_busywaitinterval); + return PyLong_FromLong(Tkinter_busywaitinterval); } static char getbusywaitinterval_doc[] = @@ -2946,13 +2946,13 @@ static PyMethodDef moduleMethods[] = { - {"_flatten", Tkinter_Flatten, METH_VARARGS}, - {"create", Tkinter_Create, METH_VARARGS}, - {"setbusywaitinterval",Tkinter_setbusywaitinterval, METH_VARARGS, - setbusywaitinterval_doc}, - {"getbusywaitinterval",(PyCFunction)Tkinter_getbusywaitinterval, - METH_NOARGS, getbusywaitinterval_doc}, - {NULL, NULL} + {"_flatten", Tkinter_Flatten, METH_VARARGS}, + {"create", Tkinter_Create, METH_VARARGS}, + {"setbusywaitinterval",Tkinter_setbusywaitinterval, METH_VARARGS, + setbusywaitinterval_doc}, + {"getbusywaitinterval",(PyCFunction)Tkinter_getbusywaitinterval, + METH_NOARGS, getbusywaitinterval_doc}, + {NULL, NULL} }; #ifdef WAIT_FOR_STDIN @@ -2963,7 +2963,7 @@ static void MyFileProc(void *clientData, int mask) { - stdin_ready = 1; + stdin_ready = 1; } #endif @@ -2975,57 +2975,57 @@ EventHook(void) { #ifndef MS_WINDOWS - int tfile; + int tfile; #endif #ifdef WITH_THREAD - PyEval_RestoreThread(event_tstate); + PyEval_RestoreThread(event_tstate); #endif - stdin_ready = 0; - errorInCmd = 0; + stdin_ready = 0; + errorInCmd = 0; #ifndef MS_WINDOWS - tfile = fileno(stdin); - Tcl_CreateFileHandler(tfile, TCL_READABLE, MyFileProc, NULL); + tfile = fileno(stdin); + Tcl_CreateFileHandler(tfile, TCL_READABLE, MyFileProc, NULL); #endif - while (!errorInCmd && !stdin_ready) { - int result; + while (!errorInCmd && !stdin_ready) { + int result; #ifdef MS_WINDOWS - if (_kbhit()) { - stdin_ready = 1; - break; - } + if (_kbhit()) { + stdin_ready = 1; + break; + } #endif #if defined(WITH_THREAD) || defined(MS_WINDOWS) - Py_BEGIN_ALLOW_THREADS - if(tcl_lock)PyThread_acquire_lock(tcl_lock, 1); - tcl_tstate = event_tstate; - - result = Tcl_DoOneEvent(TCL_DONT_WAIT); - - tcl_tstate = NULL; - if(tcl_lock)PyThread_release_lock(tcl_lock); - if (result == 0) - Sleep(Tkinter_busywaitinterval); - Py_END_ALLOW_THREADS + Py_BEGIN_ALLOW_THREADS + if(tcl_lock)PyThread_acquire_lock(tcl_lock, 1); + tcl_tstate = event_tstate; + + result = Tcl_DoOneEvent(TCL_DONT_WAIT); + + tcl_tstate = NULL; + if(tcl_lock)PyThread_release_lock(tcl_lock); + if (result == 0) + Sleep(Tkinter_busywaitinterval); + Py_END_ALLOW_THREADS #else - result = Tcl_DoOneEvent(0); + result = Tcl_DoOneEvent(0); #endif - if (result < 0) - break; - } + if (result < 0) + break; + } #ifndef MS_WINDOWS - Tcl_DeleteFileHandler(tfile); + Tcl_DeleteFileHandler(tfile); #endif - if (errorInCmd) { - errorInCmd = 0; - PyErr_Restore(excInCmd, valInCmd, trbInCmd); - excInCmd = valInCmd = trbInCmd = NULL; - PyErr_Print(); - } + if (errorInCmd) { + errorInCmd = 0; + PyErr_Restore(excInCmd, valInCmd, trbInCmd); + excInCmd = valInCmd = trbInCmd = NULL; + PyErr_Print(); + } #ifdef WITH_THREAD - PyEval_SaveThread(); + PyEval_SaveThread(); #endif - return 0; + return 0; } #endif @@ -3034,12 +3034,12 @@ EnableEventHook(void) { #ifdef WAIT_FOR_STDIN - if (PyOS_InputHook == NULL) { + if (PyOS_InputHook == NULL) { #ifdef WITH_THREAD - event_tstate = PyThreadState_Get(); + event_tstate = PyThreadState_Get(); #endif - PyOS_InputHook = EventHook; - } + PyOS_InputHook = EventHook; + } #endif } @@ -3047,9 +3047,9 @@ DisableEventHook(void) { #ifdef WAIT_FOR_STDIN - if (Tk_GetNumMainWindows() == 0 && PyOS_InputHook == EventHook) { - PyOS_InputHook = NULL; - } + if (Tk_GetNumMainWindows() == 0 && PyOS_InputHook == EventHook) { + PyOS_InputHook = NULL; + } #endif } @@ -3058,114 +3058,114 @@ static void ins_long(PyObject *d, char *name, long val) { - PyObject *v = PyLong_FromLong(val); - if (v) { - PyDict_SetItemString(d, name, v); - Py_DECREF(v); - } + PyObject *v = PyLong_FromLong(val); + if (v) { + PyDict_SetItemString(d, name, v); + Py_DECREF(v); + } } static void ins_string(PyObject *d, char *name, char *val) { - PyObject *v = PyUnicode_FromString(val); - if (v) { - PyDict_SetItemString(d, name, v); - Py_DECREF(v); - } + PyObject *v = PyUnicode_FromString(val); + if (v) { + PyDict_SetItemString(d, name, v); + Py_DECREF(v); + } } static struct PyModuleDef _tkintermodule = { - PyModuleDef_HEAD_INIT, - "_tkinter", - NULL, - -1, - moduleMethods, - NULL, - NULL, - NULL, - NULL + PyModuleDef_HEAD_INIT, + "_tkinter", + NULL, + -1, + moduleMethods, + NULL, + NULL, + NULL, + NULL }; PyMODINIT_FUNC PyInit__tkinter(void) { - PyObject *m, *d, *uexe, *cexe; + PyObject *m, *d, *uexe, *cexe; - if (PyType_Ready(&Tkapp_Type) < 0) - return NULL; + if (PyType_Ready(&Tkapp_Type) < 0) + return NULL; #ifdef WITH_THREAD - tcl_lock = PyThread_allocate_lock(); + tcl_lock = PyThread_allocate_lock(); #endif - m = PyModule_Create(&_tkintermodule); - if (m == NULL) - return NULL; + m = PyModule_Create(&_tkintermodule); + if (m == NULL) + return NULL; - d = PyModule_GetDict(m); - Tkinter_TclError = PyErr_NewException("_tkinter.TclError", NULL, NULL); - PyDict_SetItemString(d, "TclError", Tkinter_TclError); + d = PyModule_GetDict(m); + Tkinter_TclError = PyErr_NewException("_tkinter.TclError", NULL, NULL); + PyDict_SetItemString(d, "TclError", Tkinter_TclError); - ins_long(d, "READABLE", TCL_READABLE); - ins_long(d, "WRITABLE", TCL_WRITABLE); - ins_long(d, "EXCEPTION", TCL_EXCEPTION); - ins_long(d, "WINDOW_EVENTS", TCL_WINDOW_EVENTS); - ins_long(d, "FILE_EVENTS", TCL_FILE_EVENTS); - ins_long(d, "TIMER_EVENTS", TCL_TIMER_EVENTS); - ins_long(d, "IDLE_EVENTS", TCL_IDLE_EVENTS); - ins_long(d, "ALL_EVENTS", TCL_ALL_EVENTS); - ins_long(d, "DONT_WAIT", TCL_DONT_WAIT); - ins_string(d, "TK_VERSION", TK_VERSION); - ins_string(d, "TCL_VERSION", TCL_VERSION); + ins_long(d, "READABLE", TCL_READABLE); + ins_long(d, "WRITABLE", TCL_WRITABLE); + ins_long(d, "EXCEPTION", TCL_EXCEPTION); + ins_long(d, "WINDOW_EVENTS", TCL_WINDOW_EVENTS); + ins_long(d, "FILE_EVENTS", TCL_FILE_EVENTS); + ins_long(d, "TIMER_EVENTS", TCL_TIMER_EVENTS); + ins_long(d, "IDLE_EVENTS", TCL_IDLE_EVENTS); + ins_long(d, "ALL_EVENTS", TCL_ALL_EVENTS); + ins_long(d, "DONT_WAIT", TCL_DONT_WAIT); + ins_string(d, "TK_VERSION", TK_VERSION); + ins_string(d, "TCL_VERSION", TCL_VERSION); - PyDict_SetItemString(d, "TkappType", (PyObject *)&Tkapp_Type); + PyDict_SetItemString(d, "TkappType", (PyObject *)&Tkapp_Type); - if (PyType_Ready(&Tktt_Type) < 0) - return NULL; - PyDict_SetItemString(d, "TkttType", (PyObject *)&Tktt_Type); + if (PyType_Ready(&Tktt_Type) < 0) + return NULL; + PyDict_SetItemString(d, "TkttType", (PyObject *)&Tktt_Type); - Py_TYPE(&PyTclObject_Type) = &PyType_Type; - PyDict_SetItemString(d, "Tcl_Obj", (PyObject *)&PyTclObject_Type); + Py_TYPE(&PyTclObject_Type) = &PyType_Type; + PyDict_SetItemString(d, "Tcl_Obj", (PyObject *)&PyTclObject_Type); #ifdef TK_AQUA - /* Tk_MacOSXSetupTkNotifier must be called before Tcl's subsystems - * start waking up. Note that Tcl_FindExecutable will do this, this - * code must be above it! The original warning from - * tkMacOSXAppInit.c is copied below. - * - * NB - You have to swap in the Tk Notifier BEFORE you start up the - * Tcl interpreter for now. It probably should work to do this - * in the other order, but for now it doesn't seem to. - * - */ - Tk_MacOSXSetupTkNotifier(); + /* Tk_MacOSXSetupTkNotifier must be called before Tcl's subsystems + * start waking up. Note that Tcl_FindExecutable will do this, this + * code must be above it! The original warning from + * tkMacOSXAppInit.c is copied below. + * + * NB - You have to swap in the Tk Notifier BEFORE you start up the + * Tcl interpreter for now. It probably should work to do this + * in the other order, but for now it doesn't seem to. + * + */ + Tk_MacOSXSetupTkNotifier(); #endif - /* This helps the dynamic loader; in Unicode aware Tcl versions - it also helps Tcl find its encodings. */ - uexe = PyUnicode_FromWideChar(Py_GetProgramName(), -1); - if (uexe) { - cexe = PyUnicode_AsEncodedString(uexe, - Py_FileSystemDefaultEncoding, - NULL); - if (cexe) - Tcl_FindExecutable(PyBytes_AsString(cexe)); - Py_XDECREF(cexe); - Py_DECREF(uexe); - } - - if (PyErr_Occurred()) { - Py_DECREF(m); - return NULL; - } + /* This helps the dynamic loader; in Unicode aware Tcl versions + it also helps Tcl find its encodings. */ + uexe = PyUnicode_FromWideChar(Py_GetProgramName(), -1); + if (uexe) { + cexe = PyUnicode_AsEncodedString(uexe, + Py_FileSystemDefaultEncoding, + NULL); + if (cexe) + Tcl_FindExecutable(PyBytes_AsString(cexe)); + Py_XDECREF(cexe); + Py_DECREF(uexe); + } + + if (PyErr_Occurred()) { + Py_DECREF(m); + return NULL; + } #if 0 - /* This was not a good idea; through bindings, - Tcl_Finalize() may invoke Python code but at that point the - interpreter and thread state have already been destroyed! */ - Py_AtExit(Tcl_Finalize); + /* This was not a good idea; through bindings, + Tcl_Finalize() may invoke Python code but at that point the + interpreter and thread state have already been destroyed! */ + Py_AtExit(Tcl_Finalize); #endif - return m; + return m; } Modified: python/branches/py3k-jit/Modules/addrinfo.h ============================================================================== --- python/branches/py3k-jit/Modules/addrinfo.h (original) +++ python/branches/py3k-jit/Modules/addrinfo.h Mon May 10 23:55:43 2010 @@ -1,7 +1,7 @@ /* * Copyright (C) 1995, 1996, 1997, 1998, and 1999 WIDE Project. * All rights reserved. - * + * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: @@ -13,7 +13,7 @@ * 3. Neither the name of the project nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. - * + * * THIS SOFTWARE IS PROVIDED BY THE PROJECT AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE @@ -55,20 +55,20 @@ #define getaddrinfo fake_getaddrinfo #endif /* EAI_ADDRFAMILY */ -#define EAI_ADDRFAMILY 1 /* address family for hostname not supported */ -#define EAI_AGAIN 2 /* temporary failure in name resolution */ -#define EAI_BADFLAGS 3 /* invalid value for ai_flags */ -#define EAI_FAIL 4 /* non-recoverable failure in name resolution */ -#define EAI_FAMILY 5 /* ai_family not supported */ -#define EAI_MEMORY 6 /* memory allocation failure */ -#define EAI_NODATA 7 /* no address associated with hostname */ -#define EAI_NONAME 8 /* hostname nor servname provided, or not known */ -#define EAI_SERVICE 9 /* servname not supported for ai_socktype */ -#define EAI_SOCKTYPE 10 /* ai_socktype not supported */ -#define EAI_SYSTEM 11 /* system error returned in errno */ -#define EAI_BADHINTS 12 -#define EAI_PROTOCOL 13 -#define EAI_MAX 14 +#define EAI_ADDRFAMILY 1 /* address family for hostname not supported */ +#define EAI_AGAIN 2 /* temporary failure in name resolution */ +#define EAI_BADFLAGS 3 /* invalid value for ai_flags */ +#define EAI_FAIL 4 /* non-recoverable failure in name resolution */ +#define EAI_FAMILY 5 /* ai_family not supported */ +#define EAI_MEMORY 6 /* memory allocation failure */ +#define EAI_NODATA 7 /* no address associated with hostname */ +#define EAI_NONAME 8 /* hostname nor servname provided, or not known */ +#define EAI_SERVICE 9 /* servname not supported for ai_socktype */ +#define EAI_SOCKTYPE 10 /* ai_socktype not supported */ +#define EAI_SYSTEM 11 /* system error returned in errno */ +#define EAI_BADHINTS 12 +#define EAI_PROTOCOL 13 +#define EAI_MAX 14 /* * Flag values for getaddrinfo() @@ -85,18 +85,18 @@ #undef AI_DEFAULT #endif /* AI_PASSIVE */ -#define AI_PASSIVE 0x00000001 /* get address to use bind() */ -#define AI_CANONNAME 0x00000002 /* fill ai_canonname */ -#define AI_NUMERICHOST 0x00000004 /* prevent name resolution */ +#define AI_PASSIVE 0x00000001 /* get address to use bind() */ +#define AI_CANONNAME 0x00000002 /* fill ai_canonname */ +#define AI_NUMERICHOST 0x00000004 /* prevent name resolution */ /* valid flags for addrinfo */ -#define AI_MASK (AI_PASSIVE | AI_CANONNAME | AI_NUMERICHOST) +#define AI_MASK (AI_PASSIVE | AI_CANONNAME | AI_NUMERICHOST) -#define AI_ALL 0x00000100 /* IPv6 and IPv4-mapped (with AI_V4MAPPED) */ -#define AI_V4MAPPED_CFG 0x00000200 /* accept IPv4-mapped if kernel supports */ -#define AI_ADDRCONFIG 0x00000400 /* only if any address is assigned */ -#define AI_V4MAPPED 0x00000800 /* accept IPv4-mapped IPv6 address */ +#define AI_ALL 0x00000100 /* IPv6 and IPv4-mapped (with AI_V4MAPPED) */ +#define AI_V4MAPPED_CFG 0x00000200 /* accept IPv4-mapped if kernel supports */ +#define AI_ADDRCONFIG 0x00000400 /* only if any address is assigned */ +#define AI_V4MAPPED 0x00000800 /* accept IPv4-mapped IPv6 address */ /* special recommended flags for getipnodebyname */ -#define AI_DEFAULT (AI_V4MAPPED_CFG | AI_ADDRCONFIG) +#define AI_DEFAULT (AI_V4MAPPED_CFG | AI_ADDRCONFIG) #endif /* !HAVE_GETADDRINFO */ @@ -106,33 +106,33 @@ * Constants for getnameinfo() */ #ifndef NI_MAXHOST -#define NI_MAXHOST 1025 -#define NI_MAXSERV 32 +#define NI_MAXHOST 1025 +#define NI_MAXSERV 32 #endif /* !NI_MAXHOST */ /* * Flag values for getnameinfo() */ #ifndef NI_NOFQDN -#define NI_NOFQDN 0x00000001 -#define NI_NUMERICHOST 0x00000002 -#define NI_NAMEREQD 0x00000004 -#define NI_NUMERICSERV 0x00000008 -#define NI_DGRAM 0x00000010 +#define NI_NOFQDN 0x00000001 +#define NI_NUMERICHOST 0x00000002 +#define NI_NAMEREQD 0x00000004 +#define NI_NUMERICSERV 0x00000008 +#define NI_DGRAM 0x00000010 #endif /* !NI_NOFQDN */ #endif /* !HAVE_GETNAMEINFO */ #ifndef HAVE_ADDRINFO struct addrinfo { - int ai_flags; /* AI_PASSIVE, AI_CANONNAME */ - int ai_family; /* PF_xxx */ - int ai_socktype; /* SOCK_xxx */ - int ai_protocol; /* 0 or IPPROTO_xxx for IPv4 and IPv6 */ - size_t ai_addrlen; /* length of ai_addr */ - char *ai_canonname; /* canonical name for hostname */ - struct sockaddr *ai_addr; /* binary address */ - struct addrinfo *ai_next; /* next structure in linked list */ + int ai_flags; /* AI_PASSIVE, AI_CANONNAME */ + int ai_family; /* PF_xxx */ + int ai_socktype; /* SOCK_xxx */ + int ai_protocol; /* 0 or IPPROTO_xxx for IPv4 and IPv6 */ + size_t ai_addrlen; /* length of ai_addr */ + char *ai_canonname; /* canonical name for hostname */ + struct sockaddr *ai_addr; /* binary address */ + struct addrinfo *ai_next; /* next structure in linked list */ }; #endif /* !HAVE_ADDRINFO */ @@ -140,30 +140,30 @@ /* * RFC 2553: protocol-independent placeholder for socket addresses */ -#define _SS_MAXSIZE 128 +#define _SS_MAXSIZE 128 #ifdef HAVE_LONG_LONG -#define _SS_ALIGNSIZE (sizeof(PY_LONG_LONG)) +#define _SS_ALIGNSIZE (sizeof(PY_LONG_LONG)) #else -#define _SS_ALIGNSIZE (sizeof(double)) +#define _SS_ALIGNSIZE (sizeof(double)) #endif /* HAVE_LONG_LONG */ -#define _SS_PAD1SIZE (_SS_ALIGNSIZE - sizeof(u_char) * 2) -#define _SS_PAD2SIZE (_SS_MAXSIZE - sizeof(u_char) * 2 - \ - _SS_PAD1SIZE - _SS_ALIGNSIZE) +#define _SS_PAD1SIZE (_SS_ALIGNSIZE - sizeof(u_char) * 2) +#define _SS_PAD2SIZE (_SS_MAXSIZE - sizeof(u_char) * 2 - \ + _SS_PAD1SIZE - _SS_ALIGNSIZE) struct sockaddr_storage { #ifdef HAVE_SOCKADDR_SA_LEN - unsigned char ss_len; /* address length */ - unsigned char ss_family; /* address family */ + unsigned char ss_len; /* address length */ + unsigned char ss_family; /* address family */ #else - unsigned short ss_family; /* address family */ + unsigned short ss_family; /* address family */ #endif /* HAVE_SOCKADDR_SA_LEN */ - char __ss_pad1[_SS_PAD1SIZE]; + char __ss_pad1[_SS_PAD1SIZE]; #ifdef HAVE_LONG_LONG - PY_LONG_LONG __ss_align; /* force desired structure storage alignment */ + PY_LONG_LONG __ss_align; /* force desired structure storage alignment */ #else - double __ss_align; /* force desired structure storage alignment */ + double __ss_align; /* force desired structure storage alignment */ #endif /* HAVE_LONG_LONG */ - char __ss_pad2[_SS_PAD2SIZE]; + char __ss_pad2[_SS_PAD2SIZE]; }; #endif /* !HAVE_SOCKADDR_STORAGE */ Modified: python/branches/py3k-jit/Modules/arraymodule.c ============================================================================== --- python/branches/py3k-jit/Modules/arraymodule.c (original) +++ python/branches/py3k-jit/Modules/arraymodule.c Mon May 10 23:55:43 2010 @@ -11,7 +11,7 @@ #include #else /* !STDC_HEADERS */ #ifdef HAVE_SYS_TYPES_H -#include /* For size_t */ +#include /* For size_t */ #endif /* HAVE_SYS_TYPES_H */ #endif /* !STDC_HEADERS */ @@ -22,22 +22,22 @@ * functions aren't visible yet. */ struct arraydescr { - int typecode; - int itemsize; - PyObject * (*getitem)(struct arrayobject *, Py_ssize_t); - int (*setitem)(struct arrayobject *, Py_ssize_t, PyObject *); - char *formats; - int is_integer_type; - int is_signed; + int typecode; + int itemsize; + PyObject * (*getitem)(struct arrayobject *, Py_ssize_t); + int (*setitem)(struct arrayobject *, Py_ssize_t, PyObject *); + char *formats; + int is_integer_type; + int is_signed; }; typedef struct arrayobject { - PyObject_VAR_HEAD - char *ob_item; - Py_ssize_t allocated; - struct arraydescr *ob_descr; - PyObject *weakreflist; /* List of weak references */ - int ob_exports; /* Number of exported buffers */ + PyObject_VAR_HEAD + char *ob_item; + Py_ssize_t allocated; + struct arraydescr *ob_descr; + PyObject *weakreflist; /* List of weak references */ + int ob_exports; /* Number of exported buffers */ } arrayobject; static PyTypeObject Arraytype; @@ -48,63 +48,63 @@ static int array_resize(arrayobject *self, Py_ssize_t newsize) { - char *items; - size_t _new_size; + char *items; + size_t _new_size; - if (self->ob_exports > 0 && newsize != Py_SIZE(self)) { - PyErr_SetString(PyExc_BufferError, - "cannot resize an array that is exporting buffers"); - return -1; - } - - /* Bypass realloc() when a previous overallocation is large enough - to accommodate the newsize. If the newsize is 16 smaller than the - current size, then proceed with the realloc() to shrink the array. - */ - - if (self->allocated >= newsize && - Py_SIZE(self) < newsize + 16 && - self->ob_item != NULL) { - Py_SIZE(self) = newsize; - return 0; - } - - if (newsize == 0) { - PyMem_FREE(self->ob_item); - self->ob_item = NULL; - Py_SIZE(self) = 0; - self->allocated = 0; - return 0; - } - - /* This over-allocates proportional to the array size, making room - * for additional growth. The over-allocation is mild, but is - * enough to give linear-time amortized behavior over a long - * sequence of appends() in the presence of a poorly-performing - * system realloc(). - * The growth pattern is: 0, 4, 8, 16, 25, 34, 46, 56, 67, 79, ... - * Note, the pattern starts out the same as for lists but then - * grows at a smaller rate so that larger arrays only overallocate - * by about 1/16th -- this is done because arrays are presumed to be more - * memory critical. - */ - - _new_size = (newsize >> 4) + (Py_SIZE(self) < 8 ? 3 : 7) + newsize; - items = self->ob_item; - /* XXX The following multiplication and division does not optimize away - like it does for lists since the size is not known at compile time */ - if (_new_size <= ((~(size_t)0) / self->ob_descr->itemsize)) - PyMem_RESIZE(items, char, (_new_size * self->ob_descr->itemsize)); - else - items = NULL; - if (items == NULL) { - PyErr_NoMemory(); - return -1; - } - self->ob_item = items; - Py_SIZE(self) = newsize; - self->allocated = _new_size; - return 0; + if (self->ob_exports > 0 && newsize != Py_SIZE(self)) { + PyErr_SetString(PyExc_BufferError, + "cannot resize an array that is exporting buffers"); + return -1; + } + + /* Bypass realloc() when a previous overallocation is large enough + to accommodate the newsize. If the newsize is 16 smaller than the + current size, then proceed with the realloc() to shrink the array. + */ + + if (self->allocated >= newsize && + Py_SIZE(self) < newsize + 16 && + self->ob_item != NULL) { + Py_SIZE(self) = newsize; + return 0; + } + + if (newsize == 0) { + PyMem_FREE(self->ob_item); + self->ob_item = NULL; + Py_SIZE(self) = 0; + self->allocated = 0; + return 0; + } + + /* This over-allocates proportional to the array size, making room + * for additional growth. The over-allocation is mild, but is + * enough to give linear-time amortized behavior over a long + * sequence of appends() in the presence of a poorly-performing + * system realloc(). + * The growth pattern is: 0, 4, 8, 16, 25, 34, 46, 56, 67, 79, ... + * Note, the pattern starts out the same as for lists but then + * grows at a smaller rate so that larger arrays only overallocate + * by about 1/16th -- this is done because arrays are presumed to be more + * memory critical. + */ + + _new_size = (newsize >> 4) + (Py_SIZE(self) < 8 ? 3 : 7) + newsize; + items = self->ob_item; + /* XXX The following multiplication and division does not optimize away + like it does for lists since the size is not known at compile time */ + if (_new_size <= ((~(size_t)0) / self->ob_descr->itemsize)) + PyMem_RESIZE(items, char, (_new_size * self->ob_descr->itemsize)); + else + items = NULL; + if (items == NULL) { + PyErr_NoMemory(); + return -1; + } + self->ob_item = items; + Py_SIZE(self) = newsize; + self->allocated = _new_size; + return 0; } /**************************************************************************** @@ -122,272 +122,272 @@ static PyObject * b_getitem(arrayobject *ap, Py_ssize_t i) { - long x = ((char *)ap->ob_item)[i]; - if (x >= 128) - x -= 256; - return PyLong_FromLong(x); + long x = ((char *)ap->ob_item)[i]; + if (x >= 128) + x -= 256; + return PyLong_FromLong(x); } static int b_setitem(arrayobject *ap, Py_ssize_t i, PyObject *v) { - short x; - /* PyArg_Parse's 'b' formatter is for an unsigned char, therefore - must use the next size up that is signed ('h') and manually do - the overflow checking */ - if (!PyArg_Parse(v, "h;array item must be integer", &x)) - return -1; - else if (x < -128) { - PyErr_SetString(PyExc_OverflowError, - "signed char is less than minimum"); - return -1; - } - else if (x > 127) { - PyErr_SetString(PyExc_OverflowError, - "signed char is greater than maximum"); - return -1; - } - if (i >= 0) - ((char *)ap->ob_item)[i] = (char)x; - return 0; + short x; + /* PyArg_Parse's 'b' formatter is for an unsigned char, therefore + must use the next size up that is signed ('h') and manually do + the overflow checking */ + if (!PyArg_Parse(v, "h;array item must be integer", &x)) + return -1; + else if (x < -128) { + PyErr_SetString(PyExc_OverflowError, + "signed char is less than minimum"); + return -1; + } + else if (x > 127) { + PyErr_SetString(PyExc_OverflowError, + "signed char is greater than maximum"); + return -1; + } + if (i >= 0) + ((char *)ap->ob_item)[i] = (char)x; + return 0; } static PyObject * BB_getitem(arrayobject *ap, Py_ssize_t i) { - long x = ((unsigned char *)ap->ob_item)[i]; - return PyLong_FromLong(x); + long x = ((unsigned char *)ap->ob_item)[i]; + return PyLong_FromLong(x); } static int BB_setitem(arrayobject *ap, Py_ssize_t i, PyObject *v) { - unsigned char x; - /* 'B' == unsigned char, maps to PyArg_Parse's 'b' formatter */ - if (!PyArg_Parse(v, "b;array item must be integer", &x)) - return -1; - if (i >= 0) - ((char *)ap->ob_item)[i] = x; - return 0; + unsigned char x; + /* 'B' == unsigned char, maps to PyArg_Parse's 'b' formatter */ + if (!PyArg_Parse(v, "b;array item must be integer", &x)) + return -1; + if (i >= 0) + ((char *)ap->ob_item)[i] = x; + return 0; } static PyObject * u_getitem(arrayobject *ap, Py_ssize_t i) { - return PyUnicode_FromUnicode(&((Py_UNICODE *) ap->ob_item)[i], 1); + return PyUnicode_FromUnicode(&((Py_UNICODE *) ap->ob_item)[i], 1); } static int u_setitem(arrayobject *ap, Py_ssize_t i, PyObject *v) { - Py_UNICODE *p; - Py_ssize_t len; + Py_UNICODE *p; + Py_ssize_t len; - if (!PyArg_Parse(v, "u#;array item must be unicode character", &p, &len)) - return -1; - if (len != 1) { - PyErr_SetString(PyExc_TypeError, - "array item must be unicode character"); - return -1; - } - if (i >= 0) - ((Py_UNICODE *)ap->ob_item)[i] = p[0]; - return 0; + if (!PyArg_Parse(v, "u#;array item must be unicode character", &p, &len)) + return -1; + if (len != 1) { + PyErr_SetString(PyExc_TypeError, + "array item must be unicode character"); + return -1; + } + if (i >= 0) + ((Py_UNICODE *)ap->ob_item)[i] = p[0]; + return 0; } static PyObject * h_getitem(arrayobject *ap, Py_ssize_t i) { - return PyLong_FromLong((long) ((short *)ap->ob_item)[i]); + return PyLong_FromLong((long) ((short *)ap->ob_item)[i]); } static int h_setitem(arrayobject *ap, Py_ssize_t i, PyObject *v) { - short x; - /* 'h' == signed short, maps to PyArg_Parse's 'h' formatter */ - if (!PyArg_Parse(v, "h;array item must be integer", &x)) - return -1; - if (i >= 0) - ((short *)ap->ob_item)[i] = x; - return 0; + short x; + /* 'h' == signed short, maps to PyArg_Parse's 'h' formatter */ + if (!PyArg_Parse(v, "h;array item must be integer", &x)) + return -1; + if (i >= 0) + ((short *)ap->ob_item)[i] = x; + return 0; } static PyObject * HH_getitem(arrayobject *ap, Py_ssize_t i) { - return PyLong_FromLong((long) ((unsigned short *)ap->ob_item)[i]); + return PyLong_FromLong((long) ((unsigned short *)ap->ob_item)[i]); } static int HH_setitem(arrayobject *ap, Py_ssize_t i, PyObject *v) { - int x; - /* PyArg_Parse's 'h' formatter is for a signed short, therefore - must use the next size up and manually do the overflow checking */ - if (!PyArg_Parse(v, "i;array item must be integer", &x)) - return -1; - else if (x < 0) { - PyErr_SetString(PyExc_OverflowError, - "unsigned short is less than minimum"); - return -1; - } - else if (x > USHRT_MAX) { - PyErr_SetString(PyExc_OverflowError, - "unsigned short is greater than maximum"); - return -1; - } - if (i >= 0) - ((short *)ap->ob_item)[i] = (short)x; - return 0; + int x; + /* PyArg_Parse's 'h' formatter is for a signed short, therefore + must use the next size up and manually do the overflow checking */ + if (!PyArg_Parse(v, "i;array item must be integer", &x)) + return -1; + else if (x < 0) { + PyErr_SetString(PyExc_OverflowError, + "unsigned short is less than minimum"); + return -1; + } + else if (x > USHRT_MAX) { + PyErr_SetString(PyExc_OverflowError, + "unsigned short is greater than maximum"); + return -1; + } + if (i >= 0) + ((short *)ap->ob_item)[i] = (short)x; + return 0; } static PyObject * i_getitem(arrayobject *ap, Py_ssize_t i) { - return PyLong_FromLong((long) ((int *)ap->ob_item)[i]); + return PyLong_FromLong((long) ((int *)ap->ob_item)[i]); } static int i_setitem(arrayobject *ap, Py_ssize_t i, PyObject *v) { - int x; - /* 'i' == signed int, maps to PyArg_Parse's 'i' formatter */ - if (!PyArg_Parse(v, "i;array item must be integer", &x)) - return -1; - if (i >= 0) - ((int *)ap->ob_item)[i] = x; - return 0; + int x; + /* 'i' == signed int, maps to PyArg_Parse's 'i' formatter */ + if (!PyArg_Parse(v, "i;array item must be integer", &x)) + return -1; + if (i >= 0) + ((int *)ap->ob_item)[i] = x; + return 0; } static PyObject * II_getitem(arrayobject *ap, Py_ssize_t i) { - return PyLong_FromUnsignedLong( - (unsigned long) ((unsigned int *)ap->ob_item)[i]); + return PyLong_FromUnsignedLong( + (unsigned long) ((unsigned int *)ap->ob_item)[i]); } static int II_setitem(arrayobject *ap, Py_ssize_t i, PyObject *v) { - unsigned long x; - if (PyLong_Check(v)) { - x = PyLong_AsUnsignedLong(v); - if (x == (unsigned long) -1 && PyErr_Occurred()) - return -1; - } - else { - long y; - if (!PyArg_Parse(v, "l;array item must be integer", &y)) - return -1; - if (y < 0) { - PyErr_SetString(PyExc_OverflowError, - "unsigned int is less than minimum"); - return -1; - } - x = (unsigned long)y; - - } - if (x > UINT_MAX) { - PyErr_SetString(PyExc_OverflowError, - "unsigned int is greater than maximum"); - return -1; - } - - if (i >= 0) - ((unsigned int *)ap->ob_item)[i] = (unsigned int)x; - return 0; + unsigned long x; + if (PyLong_Check(v)) { + x = PyLong_AsUnsignedLong(v); + if (x == (unsigned long) -1 && PyErr_Occurred()) + return -1; + } + else { + long y; + if (!PyArg_Parse(v, "l;array item must be integer", &y)) + return -1; + if (y < 0) { + PyErr_SetString(PyExc_OverflowError, + "unsigned int is less than minimum"); + return -1; + } + x = (unsigned long)y; + + } + if (x > UINT_MAX) { + PyErr_SetString(PyExc_OverflowError, + "unsigned int is greater than maximum"); + return -1; + } + + if (i >= 0) + ((unsigned int *)ap->ob_item)[i] = (unsigned int)x; + return 0; } static PyObject * l_getitem(arrayobject *ap, Py_ssize_t i) { - return PyLong_FromLong(((long *)ap->ob_item)[i]); + return PyLong_FromLong(((long *)ap->ob_item)[i]); } static int l_setitem(arrayobject *ap, Py_ssize_t i, PyObject *v) { - long x; - if (!PyArg_Parse(v, "l;array item must be integer", &x)) - return -1; - if (i >= 0) - ((long *)ap->ob_item)[i] = x; - return 0; + long x; + if (!PyArg_Parse(v, "l;array item must be integer", &x)) + return -1; + if (i >= 0) + ((long *)ap->ob_item)[i] = x; + return 0; } static PyObject * LL_getitem(arrayobject *ap, Py_ssize_t i) { - return PyLong_FromUnsignedLong(((unsigned long *)ap->ob_item)[i]); + return PyLong_FromUnsignedLong(((unsigned long *)ap->ob_item)[i]); } static int LL_setitem(arrayobject *ap, Py_ssize_t i, PyObject *v) { - unsigned long x; - if (PyLong_Check(v)) { - x = PyLong_AsUnsignedLong(v); - if (x == (unsigned long) -1 && PyErr_Occurred()) - return -1; - } - else { - long y; - if (!PyArg_Parse(v, "l;array item must be integer", &y)) - return -1; - if (y < 0) { - PyErr_SetString(PyExc_OverflowError, - "unsigned long is less than minimum"); - return -1; - } - x = (unsigned long)y; - - } - if (x > ULONG_MAX) { - PyErr_SetString(PyExc_OverflowError, - "unsigned long is greater than maximum"); - return -1; - } - - if (i >= 0) - ((unsigned long *)ap->ob_item)[i] = x; - return 0; + unsigned long x; + if (PyLong_Check(v)) { + x = PyLong_AsUnsignedLong(v); + if (x == (unsigned long) -1 && PyErr_Occurred()) + return -1; + } + else { + long y; + if (!PyArg_Parse(v, "l;array item must be integer", &y)) + return -1; + if (y < 0) { + PyErr_SetString(PyExc_OverflowError, + "unsigned long is less than minimum"); + return -1; + } + x = (unsigned long)y; + + } + if (x > ULONG_MAX) { + PyErr_SetString(PyExc_OverflowError, + "unsigned long is greater than maximum"); + return -1; + } + + if (i >= 0) + ((unsigned long *)ap->ob_item)[i] = x; + return 0; } static PyObject * f_getitem(arrayobject *ap, Py_ssize_t i) { - return PyFloat_FromDouble((double) ((float *)ap->ob_item)[i]); + return PyFloat_FromDouble((double) ((float *)ap->ob_item)[i]); } static int f_setitem(arrayobject *ap, Py_ssize_t i, PyObject *v) { - float x; - if (!PyArg_Parse(v, "f;array item must be float", &x)) - return -1; - if (i >= 0) - ((float *)ap->ob_item)[i] = x; - return 0; + float x; + if (!PyArg_Parse(v, "f;array item must be float", &x)) + return -1; + if (i >= 0) + ((float *)ap->ob_item)[i] = x; + return 0; } static PyObject * d_getitem(arrayobject *ap, Py_ssize_t i) { - return PyFloat_FromDouble(((double *)ap->ob_item)[i]); + return PyFloat_FromDouble(((double *)ap->ob_item)[i]); } static int d_setitem(arrayobject *ap, Py_ssize_t i, PyObject *v) { - double x; - if (!PyArg_Parse(v, "d;array item must be float", &x)) - return -1; - if (i >= 0) - ((double *)ap->ob_item)[i] = x; - return 0; + double x; + if (!PyArg_Parse(v, "d;array item must be float", &x)) + return -1; + if (i >= 0) + ((double *)ap->ob_item)[i] = x; + return 0; } @@ -397,18 +397,18 @@ * typecode. */ static struct arraydescr descriptors[] = { - {'b', 1, b_getitem, b_setitem, "b", 1, 1}, - {'B', 1, BB_getitem, BB_setitem, "B", 1, 0}, - {'u', sizeof(Py_UNICODE), u_getitem, u_setitem, "u", 0, 0}, - {'h', sizeof(short), h_getitem, h_setitem, "h", 1, 1}, - {'H', sizeof(short), HH_getitem, HH_setitem, "H", 1, 0}, - {'i', sizeof(int), i_getitem, i_setitem, "i", 1, 1}, - {'I', sizeof(int), II_getitem, II_setitem, "I", 1, 0}, - {'l', sizeof(long), l_getitem, l_setitem, "l", 1, 1}, - {'L', sizeof(long), LL_getitem, LL_setitem, "L", 1, 0}, - {'f', sizeof(float), f_getitem, f_setitem, "f", 0, 0}, - {'d', sizeof(double), d_getitem, d_setitem, "d", 0, 0}, - {'\0', 0, 0, 0, 0, 0, 0} /* Sentinel */ + {'b', 1, b_getitem, b_setitem, "b", 1, 1}, + {'B', 1, BB_getitem, BB_setitem, "B", 1, 0}, + {'u', sizeof(Py_UNICODE), u_getitem, u_setitem, "u", 0, 0}, + {'h', sizeof(short), h_getitem, h_setitem, "h", 1, 1}, + {'H', sizeof(short), HH_getitem, HH_setitem, "H", 1, 0}, + {'i', sizeof(int), i_getitem, i_setitem, "i", 1, 1}, + {'I', sizeof(int), II_getitem, II_setitem, "I", 1, 0}, + {'l', sizeof(long), l_getitem, l_setitem, "l", 1, 1}, + {'L', sizeof(long), LL_getitem, LL_setitem, "L", 1, 0}, + {'f', sizeof(float), f_getitem, f_setitem, "f", 0, 0}, + {'d', sizeof(double), d_getitem, d_setitem, "d", 0, 0}, + {'\0', 0, 0, 0, 0, 0, 0} /* Sentinel */ }; /**************************************************************************** @@ -418,79 +418,79 @@ static PyObject * newarrayobject(PyTypeObject *type, Py_ssize_t size, struct arraydescr *descr) { - arrayobject *op; - size_t nbytes; + arrayobject *op; + size_t nbytes; - if (size < 0) { - PyErr_BadInternalCall(); - return NULL; - } - - nbytes = size * descr->itemsize; - /* Check for overflow */ - if (nbytes / descr->itemsize != (size_t)size) { - return PyErr_NoMemory(); - } - op = (arrayobject *) type->tp_alloc(type, 0); - if (op == NULL) { - return NULL; - } - op->ob_descr = descr; - op->allocated = size; - op->weakreflist = NULL; - Py_SIZE(op) = size; - if (size <= 0) { - op->ob_item = NULL; - } - else { - op->ob_item = PyMem_NEW(char, nbytes); - if (op->ob_item == NULL) { - Py_DECREF(op); - return PyErr_NoMemory(); - } - } - op->ob_exports = 0; - return (PyObject *) op; + if (size < 0) { + PyErr_BadInternalCall(); + return NULL; + } + + nbytes = size * descr->itemsize; + /* Check for overflow */ + if (nbytes / descr->itemsize != (size_t)size) { + return PyErr_NoMemory(); + } + op = (arrayobject *) type->tp_alloc(type, 0); + if (op == NULL) { + return NULL; + } + op->ob_descr = descr; + op->allocated = size; + op->weakreflist = NULL; + Py_SIZE(op) = size; + if (size <= 0) { + op->ob_item = NULL; + } + else { + op->ob_item = PyMem_NEW(char, nbytes); + if (op->ob_item == NULL) { + Py_DECREF(op); + return PyErr_NoMemory(); + } + } + op->ob_exports = 0; + return (PyObject *) op; } static PyObject * getarrayitem(PyObject *op, Py_ssize_t i) { - register arrayobject *ap; - assert(array_Check(op)); - ap = (arrayobject *)op; - assert(i>=0 && iob_descr->getitem)(ap, i); + register arrayobject *ap; + assert(array_Check(op)); + ap = (arrayobject *)op; + assert(i>=0 && iob_descr->getitem)(ap, i); } static int ins1(arrayobject *self, Py_ssize_t where, PyObject *v) { - char *items; - Py_ssize_t n = Py_SIZE(self); - if (v == NULL) { - PyErr_BadInternalCall(); - return -1; - } - if ((*self->ob_descr->setitem)(self, -1, v) < 0) - return -1; - - if (array_resize(self, n+1) == -1) - return -1; - items = self->ob_item; - if (where < 0) { - where += n; - if (where < 0) - where = 0; - } - if (where > n) - where = n; - /* appends don't need to call memmove() */ - if (where != n) - memmove(items + (where+1)*self->ob_descr->itemsize, - items + where*self->ob_descr->itemsize, - (n-where)*self->ob_descr->itemsize); - return (*self->ob_descr->setitem)(self, where, v); + char *items; + Py_ssize_t n = Py_SIZE(self); + if (v == NULL) { + PyErr_BadInternalCall(); + return -1; + } + if ((*self->ob_descr->setitem)(self, -1, v) < 0) + return -1; + + if (array_resize(self, n+1) == -1) + return -1; + items = self->ob_item; + if (where < 0) { + where += n; + if (where < 0) + where = 0; + } + if (where > n) + where = n; + /* appends don't need to call memmove() */ + if (where != n) + memmove(items + (where+1)*self->ob_descr->itemsize, + items + where*self->ob_descr->itemsize, + (n-where)*self->ob_descr->itemsize); + return (*self->ob_descr->setitem)(self, where, v); } /* Methods */ @@ -498,141 +498,141 @@ static void array_dealloc(arrayobject *op) { - if (op->weakreflist != NULL) - PyObject_ClearWeakRefs((PyObject *) op); - if (op->ob_item != NULL) - PyMem_DEL(op->ob_item); - Py_TYPE(op)->tp_free((PyObject *)op); + if (op->weakreflist != NULL) + PyObject_ClearWeakRefs((PyObject *) op); + if (op->ob_item != NULL) + PyMem_DEL(op->ob_item); + Py_TYPE(op)->tp_free((PyObject *)op); } static PyObject * array_richcompare(PyObject *v, PyObject *w, int op) { - arrayobject *va, *wa; - PyObject *vi = NULL; - PyObject *wi = NULL; - Py_ssize_t i, k; - PyObject *res; - - if (!array_Check(v) || !array_Check(w)) { - Py_INCREF(Py_NotImplemented); - return Py_NotImplemented; - } - - va = (arrayobject *)v; - wa = (arrayobject *)w; - - if (Py_SIZE(va) != Py_SIZE(wa) && (op == Py_EQ || op == Py_NE)) { - /* Shortcut: if the lengths differ, the arrays differ */ - if (op == Py_EQ) - res = Py_False; - else - res = Py_True; - Py_INCREF(res); - return res; - } - - /* Search for the first index where items are different */ - k = 1; - for (i = 0; i < Py_SIZE(va) && i < Py_SIZE(wa); i++) { - vi = getarrayitem(v, i); - wi = getarrayitem(w, i); - if (vi == NULL || wi == NULL) { - Py_XDECREF(vi); - Py_XDECREF(wi); - return NULL; - } - k = PyObject_RichCompareBool(vi, wi, Py_EQ); - if (k == 0) - break; /* Keeping vi and wi alive! */ - Py_DECREF(vi); - Py_DECREF(wi); - if (k < 0) - return NULL; - } - - if (k) { - /* No more items to compare -- compare sizes */ - Py_ssize_t vs = Py_SIZE(va); - Py_ssize_t ws = Py_SIZE(wa); - int cmp; - switch (op) { - case Py_LT: cmp = vs < ws; break; - case Py_LE: cmp = vs <= ws; break; - case Py_EQ: cmp = vs == ws; break; - case Py_NE: cmp = vs != ws; break; - case Py_GT: cmp = vs > ws; break; - case Py_GE: cmp = vs >= ws; break; - default: return NULL; /* cannot happen */ - } - if (cmp) - res = Py_True; - else - res = Py_False; - Py_INCREF(res); - return res; - } - - /* We have an item that differs. First, shortcuts for EQ/NE */ - if (op == Py_EQ) { - Py_INCREF(Py_False); - res = Py_False; - } - else if (op == Py_NE) { - Py_INCREF(Py_True); - res = Py_True; - } - else { - /* Compare the final item again using the proper operator */ - res = PyObject_RichCompare(vi, wi, op); - } - Py_DECREF(vi); - Py_DECREF(wi); - return res; + arrayobject *va, *wa; + PyObject *vi = NULL; + PyObject *wi = NULL; + Py_ssize_t i, k; + PyObject *res; + + if (!array_Check(v) || !array_Check(w)) { + Py_INCREF(Py_NotImplemented); + return Py_NotImplemented; + } + + va = (arrayobject *)v; + wa = (arrayobject *)w; + + if (Py_SIZE(va) != Py_SIZE(wa) && (op == Py_EQ || op == Py_NE)) { + /* Shortcut: if the lengths differ, the arrays differ */ + if (op == Py_EQ) + res = Py_False; + else + res = Py_True; + Py_INCREF(res); + return res; + } + + /* Search for the first index where items are different */ + k = 1; + for (i = 0; i < Py_SIZE(va) && i < Py_SIZE(wa); i++) { + vi = getarrayitem(v, i); + wi = getarrayitem(w, i); + if (vi == NULL || wi == NULL) { + Py_XDECREF(vi); + Py_XDECREF(wi); + return NULL; + } + k = PyObject_RichCompareBool(vi, wi, Py_EQ); + if (k == 0) + break; /* Keeping vi and wi alive! */ + Py_DECREF(vi); + Py_DECREF(wi); + if (k < 0) + return NULL; + } + + if (k) { + /* No more items to compare -- compare sizes */ + Py_ssize_t vs = Py_SIZE(va); + Py_ssize_t ws = Py_SIZE(wa); + int cmp; + switch (op) { + case Py_LT: cmp = vs < ws; break; + case Py_LE: cmp = vs <= ws; break; + case Py_EQ: cmp = vs == ws; break; + case Py_NE: cmp = vs != ws; break; + case Py_GT: cmp = vs > ws; break; + case Py_GE: cmp = vs >= ws; break; + default: return NULL; /* cannot happen */ + } + if (cmp) + res = Py_True; + else + res = Py_False; + Py_INCREF(res); + return res; + } + + /* We have an item that differs. First, shortcuts for EQ/NE */ + if (op == Py_EQ) { + Py_INCREF(Py_False); + res = Py_False; + } + else if (op == Py_NE) { + Py_INCREF(Py_True); + res = Py_True; + } + else { + /* Compare the final item again using the proper operator */ + res = PyObject_RichCompare(vi, wi, op); + } + Py_DECREF(vi); + Py_DECREF(wi); + return res; } static Py_ssize_t array_length(arrayobject *a) { - return Py_SIZE(a); + return Py_SIZE(a); } static PyObject * array_item(arrayobject *a, Py_ssize_t i) { - if (i < 0 || i >= Py_SIZE(a)) { - PyErr_SetString(PyExc_IndexError, "array index out of range"); - return NULL; - } - return getarrayitem((PyObject *)a, i); + if (i < 0 || i >= Py_SIZE(a)) { + PyErr_SetString(PyExc_IndexError, "array index out of range"); + return NULL; + } + return getarrayitem((PyObject *)a, i); } static PyObject * array_slice(arrayobject *a, Py_ssize_t ilow, Py_ssize_t ihigh) { - arrayobject *np; - if (ilow < 0) - ilow = 0; - else if (ilow > Py_SIZE(a)) - ilow = Py_SIZE(a); - if (ihigh < 0) - ihigh = 0; - if (ihigh < ilow) - ihigh = ilow; - else if (ihigh > Py_SIZE(a)) - ihigh = Py_SIZE(a); - np = (arrayobject *) newarrayobject(&Arraytype, ihigh - ilow, a->ob_descr); - if (np == NULL) - return NULL; - memcpy(np->ob_item, a->ob_item + ilow * a->ob_descr->itemsize, - (ihigh-ilow) * a->ob_descr->itemsize); - return (PyObject *)np; + arrayobject *np; + if (ilow < 0) + ilow = 0; + else if (ilow > Py_SIZE(a)) + ilow = Py_SIZE(a); + if (ihigh < 0) + ihigh = 0; + if (ihigh < ilow) + ihigh = ilow; + else if (ihigh > Py_SIZE(a)) + ihigh = Py_SIZE(a); + np = (arrayobject *) newarrayobject(&Arraytype, ihigh - ilow, a->ob_descr); + if (np == NULL) + return NULL; + memcpy(np->ob_item, a->ob_item + ilow * a->ob_descr->itemsize, + (ihigh-ilow) * a->ob_descr->itemsize); + return (PyObject *)np; } static PyObject * array_copy(arrayobject *a, PyObject *unused) { - return array_slice(a, 0, Py_SIZE(a)); + return array_slice(a, 0, Py_SIZE(a)); } PyDoc_STRVAR(copy_doc, @@ -643,278 +643,278 @@ static PyObject * array_concat(arrayobject *a, PyObject *bb) { - Py_ssize_t size; - arrayobject *np; - if (!array_Check(bb)) { - PyErr_Format(PyExc_TypeError, - "can only append array (not \"%.200s\") to array", - Py_TYPE(bb)->tp_name); - return NULL; - } + Py_ssize_t size; + arrayobject *np; + if (!array_Check(bb)) { + PyErr_Format(PyExc_TypeError, + "can only append array (not \"%.200s\") to array", + Py_TYPE(bb)->tp_name); + return NULL; + } #define b ((arrayobject *)bb) - if (a->ob_descr != b->ob_descr) { - PyErr_BadArgument(); - return NULL; - } - if (Py_SIZE(a) > PY_SSIZE_T_MAX - Py_SIZE(b)) { - return PyErr_NoMemory(); - } - size = Py_SIZE(a) + Py_SIZE(b); - np = (arrayobject *) newarrayobject(&Arraytype, size, a->ob_descr); - if (np == NULL) { - return NULL; - } - memcpy(np->ob_item, a->ob_item, Py_SIZE(a)*a->ob_descr->itemsize); - memcpy(np->ob_item + Py_SIZE(a)*a->ob_descr->itemsize, - b->ob_item, Py_SIZE(b)*b->ob_descr->itemsize); - return (PyObject *)np; + if (a->ob_descr != b->ob_descr) { + PyErr_BadArgument(); + return NULL; + } + if (Py_SIZE(a) > PY_SSIZE_T_MAX - Py_SIZE(b)) { + return PyErr_NoMemory(); + } + size = Py_SIZE(a) + Py_SIZE(b); + np = (arrayobject *) newarrayobject(&Arraytype, size, a->ob_descr); + if (np == NULL) { + return NULL; + } + memcpy(np->ob_item, a->ob_item, Py_SIZE(a)*a->ob_descr->itemsize); + memcpy(np->ob_item + Py_SIZE(a)*a->ob_descr->itemsize, + b->ob_item, Py_SIZE(b)*b->ob_descr->itemsize); + return (PyObject *)np; #undef b } static PyObject * array_repeat(arrayobject *a, Py_ssize_t n) { - Py_ssize_t i; - Py_ssize_t size; - arrayobject *np; - char *p; - Py_ssize_t nbytes; - if (n < 0) - n = 0; - if ((Py_SIZE(a) != 0) && (n > PY_SSIZE_T_MAX / Py_SIZE(a))) { - return PyErr_NoMemory(); - } - size = Py_SIZE(a) * n; - np = (arrayobject *) newarrayobject(&Arraytype, size, a->ob_descr); - if (np == NULL) - return NULL; - p = np->ob_item; - nbytes = Py_SIZE(a) * a->ob_descr->itemsize; - for (i = 0; i < n; i++) { - memcpy(p, a->ob_item, nbytes); - p += nbytes; - } - return (PyObject *) np; + Py_ssize_t i; + Py_ssize_t size; + arrayobject *np; + char *p; + Py_ssize_t nbytes; + if (n < 0) + n = 0; + if ((Py_SIZE(a) != 0) && (n > PY_SSIZE_T_MAX / Py_SIZE(a))) { + return PyErr_NoMemory(); + } + size = Py_SIZE(a) * n; + np = (arrayobject *) newarrayobject(&Arraytype, size, a->ob_descr); + if (np == NULL) + return NULL; + p = np->ob_item; + nbytes = Py_SIZE(a) * a->ob_descr->itemsize; + for (i = 0; i < n; i++) { + memcpy(p, a->ob_item, nbytes); + p += nbytes; + } + return (PyObject *) np; } static int array_ass_slice(arrayobject *a, Py_ssize_t ilow, Py_ssize_t ihigh, PyObject *v) { - char *item; - Py_ssize_t n; /* Size of replacement array */ - Py_ssize_t d; /* Change in size */ + char *item; + Py_ssize_t n; /* Size of replacement array */ + Py_ssize_t d; /* Change in size */ #define b ((arrayobject *)v) - if (v == NULL) - n = 0; - else if (array_Check(v)) { - n = Py_SIZE(b); - if (a == b) { - /* Special case "a[i:j] = a" -- copy b first */ - int ret; - v = array_slice(b, 0, n); - if (!v) - return -1; - ret = array_ass_slice(a, ilow, ihigh, v); - Py_DECREF(v); - return ret; - } - if (b->ob_descr != a->ob_descr) { - PyErr_BadArgument(); - return -1; - } - } - else { - PyErr_Format(PyExc_TypeError, - "can only assign array (not \"%.200s\") to array slice", - Py_TYPE(v)->tp_name); - return -1; - } - if (ilow < 0) - ilow = 0; - else if (ilow > Py_SIZE(a)) - ilow = Py_SIZE(a); - if (ihigh < 0) - ihigh = 0; - if (ihigh < ilow) - ihigh = ilow; - else if (ihigh > Py_SIZE(a)) - ihigh = Py_SIZE(a); - item = a->ob_item; - d = n - (ihigh-ilow); - /* Issue #4509: If the array has exported buffers and the slice - assignment would change the size of the array, fail early to make - sure we don't modify it. */ - if (d != 0 && a->ob_exports > 0) { - PyErr_SetString(PyExc_BufferError, - "cannot resize an array that is exporting buffers"); - return -1; - } - if (d < 0) { /* Delete -d items */ - memmove(item + (ihigh+d)*a->ob_descr->itemsize, - item + ihigh*a->ob_descr->itemsize, - (Py_SIZE(a)-ihigh)*a->ob_descr->itemsize); - if (array_resize(a, Py_SIZE(a) + d) == -1) - return -1; - } - else if (d > 0) { /* Insert d items */ - if (array_resize(a, Py_SIZE(a) + d)) - return -1; - memmove(item + (ihigh+d)*a->ob_descr->itemsize, - item + ihigh*a->ob_descr->itemsize, - (Py_SIZE(a)-ihigh)*a->ob_descr->itemsize); - } - if (n > 0) - memcpy(item + ilow*a->ob_descr->itemsize, b->ob_item, - n*b->ob_descr->itemsize); - return 0; + if (v == NULL) + n = 0; + else if (array_Check(v)) { + n = Py_SIZE(b); + if (a == b) { + /* Special case "a[i:j] = a" -- copy b first */ + int ret; + v = array_slice(b, 0, n); + if (!v) + return -1; + ret = array_ass_slice(a, ilow, ihigh, v); + Py_DECREF(v); + return ret; + } + if (b->ob_descr != a->ob_descr) { + PyErr_BadArgument(); + return -1; + } + } + else { + PyErr_Format(PyExc_TypeError, + "can only assign array (not \"%.200s\") to array slice", + Py_TYPE(v)->tp_name); + return -1; + } + if (ilow < 0) + ilow = 0; + else if (ilow > Py_SIZE(a)) + ilow = Py_SIZE(a); + if (ihigh < 0) + ihigh = 0; + if (ihigh < ilow) + ihigh = ilow; + else if (ihigh > Py_SIZE(a)) + ihigh = Py_SIZE(a); + item = a->ob_item; + d = n - (ihigh-ilow); + /* Issue #4509: If the array has exported buffers and the slice + assignment would change the size of the array, fail early to make + sure we don't modify it. */ + if (d != 0 && a->ob_exports > 0) { + PyErr_SetString(PyExc_BufferError, + "cannot resize an array that is exporting buffers"); + return -1; + } + if (d < 0) { /* Delete -d items */ + memmove(item + (ihigh+d)*a->ob_descr->itemsize, + item + ihigh*a->ob_descr->itemsize, + (Py_SIZE(a)-ihigh)*a->ob_descr->itemsize); + if (array_resize(a, Py_SIZE(a) + d) == -1) + return -1; + } + else if (d > 0) { /* Insert d items */ + if (array_resize(a, Py_SIZE(a) + d)) + return -1; + memmove(item + (ihigh+d)*a->ob_descr->itemsize, + item + ihigh*a->ob_descr->itemsize, + (Py_SIZE(a)-ihigh)*a->ob_descr->itemsize); + } + if (n > 0) + memcpy(item + ilow*a->ob_descr->itemsize, b->ob_item, + n*b->ob_descr->itemsize); + return 0; #undef b } static int array_ass_item(arrayobject *a, Py_ssize_t i, PyObject *v) { - if (i < 0 || i >= Py_SIZE(a)) { - PyErr_SetString(PyExc_IndexError, - "array assignment index out of range"); - return -1; - } - if (v == NULL) - return array_ass_slice(a, i, i+1, v); - return (*a->ob_descr->setitem)(a, i, v); + if (i < 0 || i >= Py_SIZE(a)) { + PyErr_SetString(PyExc_IndexError, + "array assignment index out of range"); + return -1; + } + if (v == NULL) + return array_ass_slice(a, i, i+1, v); + return (*a->ob_descr->setitem)(a, i, v); } static int setarrayitem(PyObject *a, Py_ssize_t i, PyObject *v) { - assert(array_Check(a)); - return array_ass_item((arrayobject *)a, i, v); + assert(array_Check(a)); + return array_ass_item((arrayobject *)a, i, v); } static int array_iter_extend(arrayobject *self, PyObject *bb) { - PyObject *it, *v; + PyObject *it, *v; - it = PyObject_GetIter(bb); - if (it == NULL) - return -1; - - while ((v = PyIter_Next(it)) != NULL) { - if (ins1(self, (int) Py_SIZE(self), v) != 0) { - Py_DECREF(v); - Py_DECREF(it); - return -1; - } - Py_DECREF(v); - } - Py_DECREF(it); - if (PyErr_Occurred()) - return -1; - return 0; + it = PyObject_GetIter(bb); + if (it == NULL) + return -1; + + while ((v = PyIter_Next(it)) != NULL) { + if (ins1(self, (int) Py_SIZE(self), v) != 0) { + Py_DECREF(v); + Py_DECREF(it); + return -1; + } + Py_DECREF(v); + } + Py_DECREF(it); + if (PyErr_Occurred()) + return -1; + return 0; } static int array_do_extend(arrayobject *self, PyObject *bb) { - Py_ssize_t size, oldsize, bbsize; - - if (!array_Check(bb)) - return array_iter_extend(self, bb); + Py_ssize_t size, oldsize, bbsize; + + if (!array_Check(bb)) + return array_iter_extend(self, bb); #define b ((arrayobject *)bb) - if (self->ob_descr != b->ob_descr) { - PyErr_SetString(PyExc_TypeError, - "can only extend with array of same kind"); - return -1; - } - if ((Py_SIZE(self) > PY_SSIZE_T_MAX - Py_SIZE(b)) || - ((Py_SIZE(self) + Py_SIZE(b)) > PY_SSIZE_T_MAX / self->ob_descr->itemsize)) { - PyErr_NoMemory(); - return -1; - } - oldsize = Py_SIZE(self); - /* Get the size of bb before resizing the array since bb could be self. */ - bbsize = Py_SIZE(bb); - size = oldsize + Py_SIZE(b); - if (array_resize(self, size) == -1) - return -1; - memcpy(self->ob_item + oldsize * self->ob_descr->itemsize, - b->ob_item, bbsize * b->ob_descr->itemsize); + if (self->ob_descr != b->ob_descr) { + PyErr_SetString(PyExc_TypeError, + "can only extend with array of same kind"); + return -1; + } + if ((Py_SIZE(self) > PY_SSIZE_T_MAX - Py_SIZE(b)) || + ((Py_SIZE(self) + Py_SIZE(b)) > PY_SSIZE_T_MAX / self->ob_descr->itemsize)) { + PyErr_NoMemory(); + return -1; + } + oldsize = Py_SIZE(self); + /* Get the size of bb before resizing the array since bb could be self. */ + bbsize = Py_SIZE(bb); + size = oldsize + Py_SIZE(b); + if (array_resize(self, size) == -1) + return -1; + memcpy(self->ob_item + oldsize * self->ob_descr->itemsize, + b->ob_item, bbsize * b->ob_descr->itemsize); - return 0; + return 0; #undef b } static PyObject * array_inplace_concat(arrayobject *self, PyObject *bb) { - if (!array_Check(bb)) { - PyErr_Format(PyExc_TypeError, - "can only extend array with array (not \"%.200s\")", - Py_TYPE(bb)->tp_name); - return NULL; - } - if (array_do_extend(self, bb) == -1) - return NULL; - Py_INCREF(self); - return (PyObject *)self; + if (!array_Check(bb)) { + PyErr_Format(PyExc_TypeError, + "can only extend array with array (not \"%.200s\")", + Py_TYPE(bb)->tp_name); + return NULL; + } + if (array_do_extend(self, bb) == -1) + return NULL; + Py_INCREF(self); + return (PyObject *)self; } static PyObject * array_inplace_repeat(arrayobject *self, Py_ssize_t n) { - char *items, *p; - Py_ssize_t size, i; + char *items, *p; + Py_ssize_t size, i; - if (Py_SIZE(self) > 0) { - if (n < 0) - n = 0; - items = self->ob_item; - if ((self->ob_descr->itemsize != 0) && - (Py_SIZE(self) > PY_SSIZE_T_MAX / self->ob_descr->itemsize)) { - return PyErr_NoMemory(); - } - size = Py_SIZE(self) * self->ob_descr->itemsize; - if (n > 0 && size > PY_SSIZE_T_MAX / n) { - return PyErr_NoMemory(); - } - if (array_resize(self, n * Py_SIZE(self)) == -1) - return NULL; - items = p = self->ob_item; - for (i = 1; i < n; i++) { - p += size; - memcpy(p, items, size); - } - } - Py_INCREF(self); - return (PyObject *)self; + if (Py_SIZE(self) > 0) { + if (n < 0) + n = 0; + items = self->ob_item; + if ((self->ob_descr->itemsize != 0) && + (Py_SIZE(self) > PY_SSIZE_T_MAX / self->ob_descr->itemsize)) { + return PyErr_NoMemory(); + } + size = Py_SIZE(self) * self->ob_descr->itemsize; + if (n > 0 && size > PY_SSIZE_T_MAX / n) { + return PyErr_NoMemory(); + } + if (array_resize(self, n * Py_SIZE(self)) == -1) + return NULL; + items = p = self->ob_item; + for (i = 1; i < n; i++) { + p += size; + memcpy(p, items, size); + } + } + Py_INCREF(self); + return (PyObject *)self; } static PyObject * ins(arrayobject *self, Py_ssize_t where, PyObject *v) { - if (ins1(self, where, v) != 0) - return NULL; - Py_INCREF(Py_None); - return Py_None; + if (ins1(self, where, v) != 0) + return NULL; + Py_INCREF(Py_None); + return Py_None; } static PyObject * array_count(arrayobject *self, PyObject *v) { - Py_ssize_t count = 0; - Py_ssize_t i; + Py_ssize_t count = 0; + Py_ssize_t i; - for (i = 0; i < Py_SIZE(self); i++) { - PyObject *selfi = getarrayitem((PyObject *)self, i); - int cmp = PyObject_RichCompareBool(selfi, v, Py_EQ); - Py_DECREF(selfi); - if (cmp > 0) - count++; - else if (cmp < 0) - return NULL; - } - return PyLong_FromSsize_t(count); + for (i = 0; i < Py_SIZE(self); i++) { + PyObject *selfi = getarrayitem((PyObject *)self, i); + int cmp = PyObject_RichCompareBool(selfi, v, Py_EQ); + Py_DECREF(selfi); + if (cmp > 0) + count++; + else if (cmp < 0) + return NULL; + } + return PyLong_FromSsize_t(count); } PyDoc_STRVAR(count_doc, @@ -925,20 +925,20 @@ static PyObject * array_index(arrayobject *self, PyObject *v) { - Py_ssize_t i; + Py_ssize_t i; - for (i = 0; i < Py_SIZE(self); i++) { - PyObject *selfi = getarrayitem((PyObject *)self, i); - int cmp = PyObject_RichCompareBool(selfi, v, Py_EQ); - Py_DECREF(selfi); - if (cmp > 0) { - return PyLong_FromLong((long)i); - } - else if (cmp < 0) - return NULL; - } - PyErr_SetString(PyExc_ValueError, "array.index(x): x not in list"); - return NULL; + for (i = 0; i < Py_SIZE(self); i++) { + PyObject *selfi = getarrayitem((PyObject *)self, i); + int cmp = PyObject_RichCompareBool(selfi, v, Py_EQ); + Py_DECREF(selfi); + if (cmp > 0) { + return PyLong_FromLong((long)i); + } + else if (cmp < 0) + return NULL; + } + PyErr_SetString(PyExc_ValueError, "array.index(x): x not in list"); + return NULL; } PyDoc_STRVAR(index_doc, @@ -949,38 +949,38 @@ static int array_contains(arrayobject *self, PyObject *v) { - Py_ssize_t i; - int cmp; + Py_ssize_t i; + int cmp; - for (i = 0, cmp = 0 ; cmp == 0 && i < Py_SIZE(self); i++) { - PyObject *selfi = getarrayitem((PyObject *)self, i); - cmp = PyObject_RichCompareBool(selfi, v, Py_EQ); - Py_DECREF(selfi); - } - return cmp; + for (i = 0, cmp = 0 ; cmp == 0 && i < Py_SIZE(self); i++) { + PyObject *selfi = getarrayitem((PyObject *)self, i); + cmp = PyObject_RichCompareBool(selfi, v, Py_EQ); + Py_DECREF(selfi); + } + return cmp; } static PyObject * array_remove(arrayobject *self, PyObject *v) { - int i; + int i; - for (i = 0; i < Py_SIZE(self); i++) { - PyObject *selfi = getarrayitem((PyObject *)self,i); - int cmp = PyObject_RichCompareBool(selfi, v, Py_EQ); - Py_DECREF(selfi); - if (cmp > 0) { - if (array_ass_slice(self, i, i+1, - (PyObject *)NULL) != 0) - return NULL; - Py_INCREF(Py_None); - return Py_None; - } - else if (cmp < 0) - return NULL; - } - PyErr_SetString(PyExc_ValueError, "array.remove(x): x not in list"); - return NULL; + for (i = 0; i < Py_SIZE(self); i++) { + PyObject *selfi = getarrayitem((PyObject *)self,i); + int cmp = PyObject_RichCompareBool(selfi, v, Py_EQ); + Py_DECREF(selfi); + if (cmp > 0) { + if (array_ass_slice(self, i, i+1, + (PyObject *)NULL) != 0) + return NULL; + Py_INCREF(Py_None); + return Py_None; + } + else if (cmp < 0) + return NULL; + } + PyErr_SetString(PyExc_ValueError, "array.remove(x): x not in list"); + return NULL; } PyDoc_STRVAR(remove_doc, @@ -991,27 +991,27 @@ static PyObject * array_pop(arrayobject *self, PyObject *args) { - Py_ssize_t i = -1; - PyObject *v; - if (!PyArg_ParseTuple(args, "|n:pop", &i)) - return NULL; - if (Py_SIZE(self) == 0) { - /* Special-case most common failure cause */ - PyErr_SetString(PyExc_IndexError, "pop from empty array"); - return NULL; - } - if (i < 0) - i += Py_SIZE(self); - if (i < 0 || i >= Py_SIZE(self)) { - PyErr_SetString(PyExc_IndexError, "pop index out of range"); - return NULL; - } - v = getarrayitem((PyObject *)self,i); - if (array_ass_slice(self, i, i+1, (PyObject *)NULL) != 0) { - Py_DECREF(v); - return NULL; - } - return v; + Py_ssize_t i = -1; + PyObject *v; + if (!PyArg_ParseTuple(args, "|n:pop", &i)) + return NULL; + if (Py_SIZE(self) == 0) { + /* Special-case most common failure cause */ + PyErr_SetString(PyExc_IndexError, "pop from empty array"); + return NULL; + } + if (i < 0) + i += Py_SIZE(self); + if (i < 0 || i >= Py_SIZE(self)) { + PyErr_SetString(PyExc_IndexError, "pop index out of range"); + return NULL; + } + v = getarrayitem((PyObject *)self,i); + if (array_ass_slice(self, i, i+1, (PyObject *)NULL) != 0) { + Py_DECREF(v); + return NULL; + } + return v; } PyDoc_STRVAR(pop_doc, @@ -1022,10 +1022,10 @@ static PyObject * array_extend(arrayobject *self, PyObject *bb) { - if (array_do_extend(self, bb) == -1) - return NULL; - Py_INCREF(Py_None); - return Py_None; + if (array_do_extend(self, bb) == -1) + return NULL; + Py_INCREF(Py_None); + return Py_None; } PyDoc_STRVAR(extend_doc, @@ -1036,11 +1036,11 @@ static PyObject * array_insert(arrayobject *self, PyObject *args) { - Py_ssize_t i; - PyObject *v; - if (!PyArg_ParseTuple(args, "nO:insert", &i, &v)) - return NULL; - return ins(self, i, v); + Py_ssize_t i; + PyObject *v; + if (!PyArg_ParseTuple(args, "nO:insert", &i, &v)) + return NULL; + return ins(self, i, v); } PyDoc_STRVAR(insert_doc, @@ -1052,15 +1052,15 @@ static PyObject * array_buffer_info(arrayobject *self, PyObject *unused) { - PyObject* retval = NULL; - retval = PyTuple_New(2); - if (!retval) - return NULL; + PyObject* retval = NULL; + retval = PyTuple_New(2); + if (!retval) + return NULL; - PyTuple_SET_ITEM(retval, 0, PyLong_FromVoidPtr(self->ob_item)); - PyTuple_SET_ITEM(retval, 1, PyLong_FromLong((long)(Py_SIZE(self)))); + PyTuple_SET_ITEM(retval, 0, PyLong_FromVoidPtr(self->ob_item)); + PyTuple_SET_ITEM(retval, 1, PyLong_FromLong((long)(Py_SIZE(self)))); - return retval; + return retval; } PyDoc_STRVAR(buffer_info_doc, @@ -1075,7 +1075,7 @@ static PyObject * array_append(arrayobject *self, PyObject *v) { - return ins(self, (int) Py_SIZE(self), v); + return ins(self, (int) Py_SIZE(self), v); } PyDoc_STRVAR(append_doc, @@ -1087,52 +1087,52 @@ static PyObject * array_byteswap(arrayobject *self, PyObject *unused) { - char *p; - Py_ssize_t i; + char *p; + Py_ssize_t i; - switch (self->ob_descr->itemsize) { - case 1: - break; - case 2: - for (p = self->ob_item, i = Py_SIZE(self); --i >= 0; p += 2) { - char p0 = p[0]; - p[0] = p[1]; - p[1] = p0; - } - break; - case 4: - for (p = self->ob_item, i = Py_SIZE(self); --i >= 0; p += 4) { - char p0 = p[0]; - char p1 = p[1]; - p[0] = p[3]; - p[1] = p[2]; - p[2] = p1; - p[3] = p0; - } - break; - case 8: - for (p = self->ob_item, i = Py_SIZE(self); --i >= 0; p += 8) { - char p0 = p[0]; - char p1 = p[1]; - char p2 = p[2]; - char p3 = p[3]; - p[0] = p[7]; - p[1] = p[6]; - p[2] = p[5]; - p[3] = p[4]; - p[4] = p3; - p[5] = p2; - p[6] = p1; - p[7] = p0; - } - break; - default: - PyErr_SetString(PyExc_RuntimeError, - "don't know how to byteswap this array type"); - return NULL; - } - Py_INCREF(Py_None); - return Py_None; + switch (self->ob_descr->itemsize) { + case 1: + break; + case 2: + for (p = self->ob_item, i = Py_SIZE(self); --i >= 0; p += 2) { + char p0 = p[0]; + p[0] = p[1]; + p[1] = p0; + } + break; + case 4: + for (p = self->ob_item, i = Py_SIZE(self); --i >= 0; p += 4) { + char p0 = p[0]; + char p1 = p[1]; + p[0] = p[3]; + p[1] = p[2]; + p[2] = p1; + p[3] = p0; + } + break; + case 8: + for (p = self->ob_item, i = Py_SIZE(self); --i >= 0; p += 8) { + char p0 = p[0]; + char p1 = p[1]; + char p2 = p[2]; + char p3 = p[3]; + p[0] = p[7]; + p[1] = p[6]; + p[2] = p[5]; + p[3] = p[4]; + p[4] = p3; + p[5] = p2; + p[6] = p1; + p[7] = p0; + } + break; + default: + PyErr_SetString(PyExc_RuntimeError, + "don't know how to byteswap this array type"); + return NULL; + } + Py_INCREF(Py_None); + return Py_None; } PyDoc_STRVAR(byteswap_doc, @@ -1144,28 +1144,28 @@ static PyObject * array_reverse(arrayobject *self, PyObject *unused) { - register Py_ssize_t itemsize = self->ob_descr->itemsize; - register char *p, *q; - /* little buffer to hold items while swapping */ - char tmp[256]; /* 8 is probably enough -- but why skimp */ - assert((size_t)itemsize <= sizeof(tmp)); - - if (Py_SIZE(self) > 1) { - for (p = self->ob_item, - q = self->ob_item + (Py_SIZE(self) - 1)*itemsize; - p < q; - p += itemsize, q -= itemsize) { - /* memory areas guaranteed disjoint, so memcpy - * is safe (& memmove may be slower). - */ - memcpy(tmp, p, itemsize); - memcpy(p, q, itemsize); - memcpy(q, tmp, itemsize); - } - } + register Py_ssize_t itemsize = self->ob_descr->itemsize; + register char *p, *q; + /* little buffer to hold items while swapping */ + char tmp[256]; /* 8 is probably enough -- but why skimp */ + assert((size_t)itemsize <= sizeof(tmp)); + + if (Py_SIZE(self) > 1) { + for (p = self->ob_item, + q = self->ob_item + (Py_SIZE(self) - 1)*itemsize; + p < q; + p += itemsize, q -= itemsize) { + /* memory areas guaranteed disjoint, so memcpy + * is safe (& memmove may be slower). + */ + memcpy(tmp, p, itemsize); + memcpy(p, q, itemsize); + memcpy(q, tmp, itemsize); + } + } - Py_INCREF(Py_None); - return Py_None; + Py_INCREF(Py_None); + return Py_None; } PyDoc_STRVAR(reverse_doc, @@ -1180,51 +1180,51 @@ static PyObject * array_fromfile(arrayobject *self, PyObject *args) { - PyObject *f, *b, *res; - Py_ssize_t itemsize = self->ob_descr->itemsize; - Py_ssize_t n, nbytes; - int not_enough_bytes; - - if (!PyArg_ParseTuple(args, "On:fromfile", &f, &n)) - return NULL; - - nbytes = n * itemsize; - if (nbytes < 0 || nbytes/itemsize != n) { - PyErr_NoMemory(); - return NULL; - } - - b = PyObject_CallMethod(f, "read", "n", nbytes); - if (b == NULL) - return NULL; - - if (!PyBytes_Check(b)) { - PyErr_SetString(PyExc_TypeError, - "read() didn't return bytes"); - Py_DECREF(b); - return NULL; - } - - not_enough_bytes = (PyBytes_GET_SIZE(b) != nbytes); - - args = Py_BuildValue("(O)", b); - Py_DECREF(b); - if (args == NULL) - return NULL; - - res = array_fromstring(self, args); - Py_DECREF(args); - if (res == NULL) - return NULL; - - if (not_enough_bytes) { - PyErr_SetString(PyExc_EOFError, - "read() didn't return enough bytes"); - Py_DECREF(res); - return NULL; - } + PyObject *f, *b, *res; + Py_ssize_t itemsize = self->ob_descr->itemsize; + Py_ssize_t n, nbytes; + int not_enough_bytes; + + if (!PyArg_ParseTuple(args, "On:fromfile", &f, &n)) + return NULL; + + nbytes = n * itemsize; + if (nbytes < 0 || nbytes/itemsize != n) { + PyErr_NoMemory(); + return NULL; + } + + b = PyObject_CallMethod(f, "read", "n", nbytes); + if (b == NULL) + return NULL; + + if (!PyBytes_Check(b)) { + PyErr_SetString(PyExc_TypeError, + "read() didn't return bytes"); + Py_DECREF(b); + return NULL; + } + + not_enough_bytes = (PyBytes_GET_SIZE(b) != nbytes); + + args = Py_BuildValue("(O)", b); + Py_DECREF(b); + if (args == NULL) + return NULL; + + res = array_fromstring(self, args); + Py_DECREF(args); + if (res == NULL) + return NULL; + + if (not_enough_bytes) { + PyErr_SetString(PyExc_EOFError, + "read() didn't return enough bytes"); + Py_DECREF(res); + return NULL; + } - return res; + return res; } PyDoc_STRVAR(fromfile_doc, @@ -1237,35 +1237,35 @@ static PyObject * array_tofile(arrayobject *self, PyObject *f) { - Py_ssize_t nbytes = Py_SIZE(self) * self->ob_descr->itemsize; - /* Write 64K blocks at a time */ - /* XXX Make the block size settable */ - int BLOCKSIZE = 64*1024; - Py_ssize_t nblocks = (nbytes + BLOCKSIZE - 1) / BLOCKSIZE; - Py_ssize_t i; - - if (Py_SIZE(self) == 0) - goto done; - - for (i = 0; i < nblocks; i++) { - char* ptr = self->ob_item + i*BLOCKSIZE; - Py_ssize_t size = BLOCKSIZE; - PyObject *bytes, *res; - if (i*BLOCKSIZE + size > nbytes) - size = nbytes - i*BLOCKSIZE; - bytes = PyBytes_FromStringAndSize(ptr, size); - if (bytes == NULL) - return NULL; - res = PyObject_CallMethod(f, "write", "O", bytes); - Py_DECREF(bytes); - if (res == NULL) - return NULL; - Py_DECREF(res); /* drop write result */ - } + Py_ssize_t nbytes = Py_SIZE(self) * self->ob_descr->itemsize; + /* Write 64K blocks at a time */ + /* XXX Make the block size settable */ + int BLOCKSIZE = 64*1024; + Py_ssize_t nblocks = (nbytes + BLOCKSIZE - 1) / BLOCKSIZE; + Py_ssize_t i; + + if (Py_SIZE(self) == 0) + goto done; + + for (i = 0; i < nblocks; i++) { + char* ptr = self->ob_item + i*BLOCKSIZE; + Py_ssize_t size = BLOCKSIZE; + PyObject *bytes, *res; + if (i*BLOCKSIZE + size > nbytes) + size = nbytes - i*BLOCKSIZE; + bytes = PyBytes_FromStringAndSize(ptr, size); + if (bytes == NULL) + return NULL; + res = PyObject_CallMethod(f, "write", "O", bytes); + Py_DECREF(bytes); + if (res == NULL) + return NULL; + Py_DECREF(res); /* drop write result */ + } done: - Py_INCREF(Py_None); - return Py_None; + Py_INCREF(Py_None); + return Py_None; } PyDoc_STRVAR(tofile_doc, @@ -1277,29 +1277,29 @@ static PyObject * array_fromlist(arrayobject *self, PyObject *list) { - Py_ssize_t n; + Py_ssize_t n; - if (!PyList_Check(list)) { - PyErr_SetString(PyExc_TypeError, "arg must be list"); - return NULL; - } - n = PyList_Size(list); - if (n > 0) { - Py_ssize_t i, old_size; - old_size = Py_SIZE(self); - if (array_resize(self, old_size + n) == -1) - return NULL; - for (i = 0; i < n; i++) { - PyObject *v = PyList_GetItem(list, i); - if ((*self->ob_descr->setitem)(self, - Py_SIZE(self) - n + i, v) != 0) { - array_resize(self, old_size); - return NULL; - } - } - } - Py_INCREF(Py_None); - return Py_None; + if (!PyList_Check(list)) { + PyErr_SetString(PyExc_TypeError, "arg must be list"); + return NULL; + } + n = PyList_Size(list); + if (n > 0) { + Py_ssize_t i, old_size; + old_size = Py_SIZE(self); + if (array_resize(self, old_size + n) == -1) + return NULL; + for (i = 0; i < n; i++) { + PyObject *v = PyList_GetItem(list, i); + if ((*self->ob_descr->setitem)(self, + Py_SIZE(self) - n + i, v) != 0) { + array_resize(self, old_size); + return NULL; + } + } + } + Py_INCREF(Py_None); + return Py_None; } PyDoc_STRVAR(fromlist_doc, @@ -1310,20 +1310,20 @@ static PyObject * array_tolist(arrayobject *self, PyObject *unused) { - PyObject *list = PyList_New(Py_SIZE(self)); - Py_ssize_t i; + PyObject *list = PyList_New(Py_SIZE(self)); + Py_ssize_t i; - if (list == NULL) - return NULL; - for (i = 0; i < Py_SIZE(self); i++) { - PyObject *v = getarrayitem((PyObject *)self, i); - if (v == NULL) { - Py_DECREF(list); - return NULL; - } - PyList_SetItem(list, i, v); - } - return list; + if (list == NULL) + return NULL; + for (i = 0; i < Py_SIZE(self); i++) { + PyObject *v = getarrayitem((PyObject *)self, i); + if (v == NULL) { + Py_DECREF(list); + return NULL; + } + PyList_SetItem(list, i, v); + } + return list; } PyDoc_STRVAR(tolist_doc, @@ -1335,30 +1335,30 @@ static PyObject * array_fromstring(arrayobject *self, PyObject *args) { - char *str; - Py_ssize_t n; - int itemsize = self->ob_descr->itemsize; - if (!PyArg_ParseTuple(args, "s#:fromstring", &str, &n)) - return NULL; - if (n % itemsize != 0) { - PyErr_SetString(PyExc_ValueError, - "string length not a multiple of item size"); - return NULL; - } - n = n / itemsize; - if (n > 0) { - Py_ssize_t old_size = Py_SIZE(self); - if ((n > PY_SSIZE_T_MAX - old_size) || - ((old_size + n) > PY_SSIZE_T_MAX / itemsize)) { - return PyErr_NoMemory(); - } - if (array_resize(self, old_size + n) == -1) - return NULL; - memcpy(self->ob_item + old_size * itemsize, - str, n * itemsize); - } - Py_INCREF(Py_None); - return Py_None; + char *str; + Py_ssize_t n; + int itemsize = self->ob_descr->itemsize; + if (!PyArg_ParseTuple(args, "s#:fromstring", &str, &n)) + return NULL; + if (n % itemsize != 0) { + PyErr_SetString(PyExc_ValueError, + "string length not a multiple of item size"); + return NULL; + } + n = n / itemsize; + if (n > 0) { + Py_ssize_t old_size = Py_SIZE(self); + if ((n > PY_SSIZE_T_MAX - old_size) || + ((old_size + n) > PY_SSIZE_T_MAX / itemsize)) { + return PyErr_NoMemory(); + } + if (array_resize(self, old_size + n) == -1) + return NULL; + memcpy(self->ob_item + old_size * itemsize, + str, n * itemsize); + } + Py_INCREF(Py_None); + return Py_None; } PyDoc_STRVAR(fromstring_doc, @@ -1371,12 +1371,12 @@ static PyObject * array_tostring(arrayobject *self, PyObject *unused) { - if (Py_SIZE(self) <= PY_SSIZE_T_MAX / self->ob_descr->itemsize) { - return PyBytes_FromStringAndSize(self->ob_item, - Py_SIZE(self) * self->ob_descr->itemsize); - } else { - return PyErr_NoMemory(); - } + if (Py_SIZE(self) <= PY_SSIZE_T_MAX / self->ob_descr->itemsize) { + return PyBytes_FromStringAndSize(self->ob_item, + Py_SIZE(self) * self->ob_descr->itemsize); + } else { + return PyErr_NoMemory(); + } } PyDoc_STRVAR(tostring_doc, @@ -1390,29 +1390,29 @@ static PyObject * array_fromunicode(arrayobject *self, PyObject *args) { - Py_UNICODE *ustr; - Py_ssize_t n; - char typecode; - - if (!PyArg_ParseTuple(args, "u#:fromunicode", &ustr, &n)) - return NULL; - typecode = self->ob_descr->typecode; - if ((typecode != 'u')) { - PyErr_SetString(PyExc_ValueError, - "fromunicode() may only be called on " - "unicode type arrays"); - return NULL; - } - if (n > 0) { - Py_ssize_t old_size = Py_SIZE(self); - if (array_resize(self, old_size + n) == -1) - return NULL; - memcpy(self->ob_item + old_size * sizeof(Py_UNICODE), - ustr, n * sizeof(Py_UNICODE)); - } + Py_UNICODE *ustr; + Py_ssize_t n; + char typecode; + + if (!PyArg_ParseTuple(args, "u#:fromunicode", &ustr, &n)) + return NULL; + typecode = self->ob_descr->typecode; + if ((typecode != 'u')) { + PyErr_SetString(PyExc_ValueError, + "fromunicode() may only be called on " + "unicode type arrays"); + return NULL; + } + if (n > 0) { + Py_ssize_t old_size = Py_SIZE(self); + if (array_resize(self, old_size + n) == -1) + return NULL; + memcpy(self->ob_item + old_size * sizeof(Py_UNICODE), + ustr, n * sizeof(Py_UNICODE)); + } - Py_INCREF(Py_None); - return Py_None; + Py_INCREF(Py_None); + return Py_None; } PyDoc_STRVAR(fromunicode_doc, @@ -1427,14 +1427,14 @@ static PyObject * array_tounicode(arrayobject *self, PyObject *unused) { - char typecode; - typecode = self->ob_descr->typecode; - if ((typecode != 'u')) { - PyErr_SetString(PyExc_ValueError, - "tounicode() may only be called on unicode type arrays"); - return NULL; - } - return PyUnicode_FromUnicode((Py_UNICODE *) self->ob_item, Py_SIZE(self)); + char typecode; + typecode = self->ob_descr->typecode; + if ((typecode != 'u')) { + PyErr_SetString(PyExc_ValueError, + "tounicode() may only be called on unicode type arrays"); + return NULL; + } + return PyUnicode_FromUnicode((Py_UNICODE *) self->ob_item, Py_SIZE(self)); } PyDoc_STRVAR(tounicode_doc, @@ -1450,71 +1450,71 @@ /*********************** Pickling support ************************/ enum machine_format_code { - UNKNOWN_FORMAT = -1, - /* UNKNOWN_FORMAT is used to indicate that the machine format for an - * array type code cannot be interpreted. When this occurs, a list of - * Python objects is used to represent the content of the array - * instead of using the memory content of the array directly. In that - * case, the array_reconstructor mechanism is bypassed completely, and - * the standard array constructor is used instead. - * - * This is will most likely occur when the machine doesn't use IEEE - * floating-point numbers. - */ - - UNSIGNED_INT8 = 0, - SIGNED_INT8 = 1, - UNSIGNED_INT16_LE = 2, - UNSIGNED_INT16_BE = 3, - SIGNED_INT16_LE = 4, - SIGNED_INT16_BE = 5, - UNSIGNED_INT32_LE = 6, - UNSIGNED_INT32_BE = 7, - SIGNED_INT32_LE = 8, - SIGNED_INT32_BE = 9, - UNSIGNED_INT64_LE = 10, - UNSIGNED_INT64_BE = 11, - SIGNED_INT64_LE = 12, - SIGNED_INT64_BE = 13, - IEEE_754_FLOAT_LE = 14, - IEEE_754_FLOAT_BE = 15, - IEEE_754_DOUBLE_LE = 16, - IEEE_754_DOUBLE_BE = 17, - UTF16_LE = 18, - UTF16_BE = 19, - UTF32_LE = 20, - UTF32_BE = 21 + UNKNOWN_FORMAT = -1, + /* UNKNOWN_FORMAT is used to indicate that the machine format for an + * array type code cannot be interpreted. When this occurs, a list of + * Python objects is used to represent the content of the array + * instead of using the memory content of the array directly. In that + * case, the array_reconstructor mechanism is bypassed completely, and + * the standard array constructor is used instead. + * + * This is will most likely occur when the machine doesn't use IEEE + * floating-point numbers. + */ + + UNSIGNED_INT8 = 0, + SIGNED_INT8 = 1, + UNSIGNED_INT16_LE = 2, + UNSIGNED_INT16_BE = 3, + SIGNED_INT16_LE = 4, + SIGNED_INT16_BE = 5, + UNSIGNED_INT32_LE = 6, + UNSIGNED_INT32_BE = 7, + SIGNED_INT32_LE = 8, + SIGNED_INT32_BE = 9, + UNSIGNED_INT64_LE = 10, + UNSIGNED_INT64_BE = 11, + SIGNED_INT64_LE = 12, + SIGNED_INT64_BE = 13, + IEEE_754_FLOAT_LE = 14, + IEEE_754_FLOAT_BE = 15, + IEEE_754_DOUBLE_LE = 16, + IEEE_754_DOUBLE_BE = 17, + UTF16_LE = 18, + UTF16_BE = 19, + UTF32_LE = 20, + UTF32_BE = 21 }; #define MACHINE_FORMAT_CODE_MIN 0 #define MACHINE_FORMAT_CODE_MAX 21 static const struct mformatdescr { - size_t size; - int is_signed; - int is_big_endian; + size_t size; + int is_signed; + int is_big_endian; } mformat_descriptors[] = { - {1, 0, 0}, /* 0: UNSIGNED_INT8 */ - {1, 1, 0}, /* 1: SIGNED_INT8 */ - {2, 0, 0}, /* 2: UNSIGNED_INT16_LE */ - {2, 0, 1}, /* 3: UNSIGNED_INT16_BE */ - {2, 1, 0}, /* 4: SIGNED_INT16_LE */ - {2, 1, 1}, /* 5: SIGNED_INT16_BE */ - {4, 0, 0}, /* 6: UNSIGNED_INT32_LE */ - {4, 0, 1}, /* 7: UNSIGNED_INT32_BE */ - {4, 1, 0}, /* 8: SIGNED_INT32_LE */ - {4, 1, 1}, /* 9: SIGNED_INT32_BE */ - {8, 0, 0}, /* 10: UNSIGNED_INT64_LE */ - {8, 0, 1}, /* 11: UNSIGNED_INT64_BE */ - {8, 1, 0}, /* 12: SIGNED_INT64_LE */ - {8, 1, 1}, /* 13: SIGNED_INT64_BE */ - {4, 0, 0}, /* 14: IEEE_754_FLOAT_LE */ - {4, 0, 1}, /* 15: IEEE_754_FLOAT_BE */ - {8, 0, 0}, /* 16: IEEE_754_DOUBLE_LE */ - {8, 0, 1}, /* 17: IEEE_754_DOUBLE_BE */ - {4, 0, 0}, /* 18: UTF16_LE */ - {4, 0, 1}, /* 19: UTF16_BE */ - {8, 0, 0}, /* 20: UTF32_LE */ - {8, 0, 1} /* 21: UTF32_BE */ + {1, 0, 0}, /* 0: UNSIGNED_INT8 */ + {1, 1, 0}, /* 1: SIGNED_INT8 */ + {2, 0, 0}, /* 2: UNSIGNED_INT16_LE */ + {2, 0, 1}, /* 3: UNSIGNED_INT16_BE */ + {2, 1, 0}, /* 4: SIGNED_INT16_LE */ + {2, 1, 1}, /* 5: SIGNED_INT16_BE */ + {4, 0, 0}, /* 6: UNSIGNED_INT32_LE */ + {4, 0, 1}, /* 7: UNSIGNED_INT32_BE */ + {4, 1, 0}, /* 8: SIGNED_INT32_LE */ + {4, 1, 1}, /* 9: SIGNED_INT32_BE */ + {8, 0, 0}, /* 10: UNSIGNED_INT64_LE */ + {8, 0, 1}, /* 11: UNSIGNED_INT64_BE */ + {8, 1, 0}, /* 12: SIGNED_INT64_LE */ + {8, 1, 1}, /* 13: SIGNED_INT64_BE */ + {4, 0, 0}, /* 14: IEEE_754_FLOAT_LE */ + {4, 0, 1}, /* 15: IEEE_754_FLOAT_BE */ + {8, 0, 0}, /* 16: IEEE_754_DOUBLE_LE */ + {8, 0, 1}, /* 17: IEEE_754_DOUBLE_BE */ + {4, 0, 0}, /* 18: UTF16_LE */ + {4, 0, 1}, /* 19: UTF16_BE */ + {8, 0, 0}, /* 20: UTF32_LE */ + {8, 0, 1} /* 21: UTF32_BE */ }; @@ -1527,86 +1527,86 @@ typecode_to_mformat_code(int typecode) { #ifdef WORDS_BIGENDIAN - const int is_big_endian = 1; + const int is_big_endian = 1; #else - const int is_big_endian = 0; + const int is_big_endian = 0; #endif - size_t intsize; - int is_signed; + size_t intsize; + int is_signed; + + switch (typecode) { + case 'b': + return SIGNED_INT8; + case 'B': + return UNSIGNED_INT8; + + case 'u': + if (sizeof(Py_UNICODE) == 2) { + return UTF16_LE + is_big_endian; + } + if (sizeof(Py_UNICODE) == 4) { + return UTF32_LE + is_big_endian; + } + return UNKNOWN_FORMAT; + + case 'f': + if (sizeof(float) == 4) { + const float y = 16711938.0; + if (memcmp(&y, "\x4b\x7f\x01\x02", 4) == 0) + return IEEE_754_FLOAT_BE; + if (memcmp(&y, "\x02\x01\x7f\x4b", 4) == 0) + return IEEE_754_FLOAT_LE; + } + return UNKNOWN_FORMAT; - switch (typecode) { - case 'b': - return SIGNED_INT8; - case 'B': - return UNSIGNED_INT8; - - case 'u': - if (sizeof(Py_UNICODE) == 2) { - return UTF16_LE + is_big_endian; - } - if (sizeof(Py_UNICODE) == 4) { - return UTF32_LE + is_big_endian; - } - return UNKNOWN_FORMAT; - - case 'f': - if (sizeof(float) == 4) { - const float y = 16711938.0; - if (memcmp(&y, "\x4b\x7f\x01\x02", 4) == 0) - return IEEE_754_FLOAT_BE; - if (memcmp(&y, "\x02\x01\x7f\x4b", 4) == 0) - return IEEE_754_FLOAT_LE; - } - return UNKNOWN_FORMAT; - - case 'd': - if (sizeof(double) == 8) { - const double x = 9006104071832581.0; - if (memcmp(&x, "\x43\x3f\xff\x01\x02\x03\x04\x05", 8) == 0) - return IEEE_754_DOUBLE_BE; - if (memcmp(&x, "\x05\x04\x03\x02\x01\xff\x3f\x43", 8) == 0) - return IEEE_754_DOUBLE_LE; - } - return UNKNOWN_FORMAT; - - /* Integers */ - case 'h': - intsize = sizeof(short); - is_signed = 1; - break; - case 'H': - intsize = sizeof(short); - is_signed = 0; - break; - case 'i': - intsize = sizeof(int); - is_signed = 1; - break; - case 'I': - intsize = sizeof(int); - is_signed = 0; - break; - case 'l': - intsize = sizeof(long); - is_signed = 1; - break; - case 'L': - intsize = sizeof(long); - is_signed = 0; - break; - default: - return UNKNOWN_FORMAT; - } - switch (intsize) { - case 2: - return UNSIGNED_INT16_LE + is_big_endian + (2 * is_signed); - case 4: - return UNSIGNED_INT32_LE + is_big_endian + (2 * is_signed); - case 8: - return UNSIGNED_INT64_LE + is_big_endian + (2 * is_signed); - default: - return UNKNOWN_FORMAT; - } + case 'd': + if (sizeof(double) == 8) { + const double x = 9006104071832581.0; + if (memcmp(&x, "\x43\x3f\xff\x01\x02\x03\x04\x05", 8) == 0) + return IEEE_754_DOUBLE_BE; + if (memcmp(&x, "\x05\x04\x03\x02\x01\xff\x3f\x43", 8) == 0) + return IEEE_754_DOUBLE_LE; + } + return UNKNOWN_FORMAT; + + /* Integers */ + case 'h': + intsize = sizeof(short); + is_signed = 1; + break; + case 'H': + intsize = sizeof(short); + is_signed = 0; + break; + case 'i': + intsize = sizeof(int); + is_signed = 1; + break; + case 'I': + intsize = sizeof(int); + is_signed = 0; + break; + case 'l': + intsize = sizeof(long); + is_signed = 1; + break; + case 'L': + intsize = sizeof(long); + is_signed = 0; + break; + default: + return UNKNOWN_FORMAT; + } + switch (intsize) { + case 2: + return UNSIGNED_INT16_LE + is_big_endian + (2 * is_signed); + case 4: + return UNSIGNED_INT32_LE + is_big_endian + (2 * is_signed); + case 8: + return UNSIGNED_INT64_LE + is_big_endian + (2 * is_signed); + default: + return UNKNOWN_FORMAT; + } } /* Forward declaration. */ @@ -1619,38 +1619,38 @@ * Unicode character value, like 'i' or 'f' for example, representing an array * type code. The items argument is a bytes or a list object from which * contains the initial value of the array. - * + * * On success, this functions returns the array object created. Otherwise, * NULL is returned to indicate a failure. */ static PyObject * make_array(PyTypeObject *arraytype, int typecode, PyObject *items) { - PyObject *new_args; - PyObject *array_obj; - PyObject *typecode_obj; - Py_UNICODE typecode_str[1] = {typecode}; - - assert(arraytype != NULL); - assert(items != NULL); - - typecode_obj = PyUnicode_FromUnicode(typecode_str, 1); - if (typecode_obj == NULL) - return NULL; - - new_args = PyTuple_New(2); - if (new_args == NULL) - return NULL; - Py_INCREF(items); - PyTuple_SET_ITEM(new_args, 0, typecode_obj); - PyTuple_SET_ITEM(new_args, 1, items); - - array_obj = array_new(arraytype, new_args, NULL); - Py_DECREF(new_args); - if (array_obj == NULL) - return NULL; + PyObject *new_args; + PyObject *array_obj; + PyObject *typecode_obj; + Py_UNICODE typecode_str[1] = {typecode}; + + assert(arraytype != NULL); + assert(items != NULL); + + typecode_obj = PyUnicode_FromUnicode(typecode_str, 1); + if (typecode_obj == NULL) + return NULL; + + new_args = PyTuple_New(2); + if (new_args == NULL) + return NULL; + Py_INCREF(items); + PyTuple_SET_ITEM(new_args, 0, typecode_obj); + PyTuple_SET_ITEM(new_args, 1, items); + + array_obj = array_new(arraytype, new_args, NULL); + Py_DECREF(new_args); + if (array_obj == NULL) + return NULL; - return array_obj; + return array_obj; } /* @@ -1660,283 +1660,283 @@ static PyObject * array_reconstructor(PyObject *self, PyObject *args) { - PyTypeObject *arraytype; - PyObject *items; - PyObject *converted_items; - PyObject *result; - int typecode; - enum machine_format_code mformat_code; - struct arraydescr *descr; - - if (!PyArg_ParseTuple(args, "OCiO:array._array_reconstructor", - &arraytype, &typecode, &mformat_code, &items)) - return NULL; - - if (!PyType_Check(arraytype)) { - PyErr_Format(PyExc_TypeError, - "first argument must a type object, not %.200s", - Py_TYPE(arraytype)->tp_name); - return NULL; - } - if (!PyType_IsSubtype(arraytype, &Arraytype)) { - PyErr_Format(PyExc_TypeError, - "%.200s is not a subtype of %.200s", - arraytype->tp_name, Arraytype.tp_name); - return NULL; - } - for (descr = descriptors; descr->typecode != '\0'; descr++) { - if (descr->typecode == typecode) - break; - } - if (descr->typecode == '\0') { - PyErr_SetString(PyExc_ValueError, - "second argument must be a valid type code"); - return NULL; - } - if (mformat_code < MACHINE_FORMAT_CODE_MIN || - mformat_code > MACHINE_FORMAT_CODE_MAX) { - PyErr_SetString(PyExc_ValueError, - "third argument must be a valid machine format code."); - return NULL; - } - if (!PyBytes_Check(items)) { - PyErr_Format(PyExc_TypeError, - "fourth argument should be bytes, not %.200s", - Py_TYPE(items)->tp_name); - return NULL; - } - - /* Fast path: No decoding has to be done. */ - if (mformat_code == typecode_to_mformat_code(typecode) || - mformat_code == UNKNOWN_FORMAT) { - return make_array(arraytype, typecode, items); - } - - /* Slow path: Decode the byte string according to the given machine - * format code. This occurs when the computer unpickling the array - * object is architecturally different from the one that pickled the - * array. - */ - if (Py_SIZE(items) % mformat_descriptors[mformat_code].size != 0) { - PyErr_SetString(PyExc_ValueError, - "string length not a multiple of item size"); - return NULL; - } - switch (mformat_code) { - case IEEE_754_FLOAT_LE: - case IEEE_754_FLOAT_BE: { - int i; - int le = (mformat_code == IEEE_754_FLOAT_LE) ? 1 : 0; - Py_ssize_t itemcount = Py_SIZE(items) / 4; - const unsigned char *memstr = - (unsigned char *)PyBytes_AS_STRING(items); - - converted_items = PyList_New(itemcount); - if (converted_items == NULL) - return NULL; - for (i = 0; i < itemcount; i++) { - PyObject *pyfloat = PyFloat_FromDouble( - _PyFloat_Unpack4(&memstr[i * 4], le)); - if (pyfloat == NULL) { - Py_DECREF(converted_items); - return NULL; - } - PyList_SET_ITEM(converted_items, i, pyfloat); - } - break; - } - case IEEE_754_DOUBLE_LE: - case IEEE_754_DOUBLE_BE: { - int i; - int le = (mformat_code == IEEE_754_DOUBLE_LE) ? 1 : 0; - Py_ssize_t itemcount = Py_SIZE(items) / 8; - const unsigned char *memstr = - (unsigned char *)PyBytes_AS_STRING(items); - - converted_items = PyList_New(itemcount); - if (converted_items == NULL) - return NULL; - for (i = 0; i < itemcount; i++) { - PyObject *pyfloat = PyFloat_FromDouble( - _PyFloat_Unpack8(&memstr[i * 8], le)); - if (pyfloat == NULL) { - Py_DECREF(converted_items); - return NULL; - } - PyList_SET_ITEM(converted_items, i, pyfloat); - } - break; - } - case UTF16_LE: - case UTF16_BE: { - int byteorder = (mformat_code == UTF16_LE) ? -1 : 1; - converted_items = PyUnicode_DecodeUTF16( - PyBytes_AS_STRING(items), Py_SIZE(items), - "strict", &byteorder); - if (converted_items == NULL) - return NULL; - break; - } - case UTF32_LE: - case UTF32_BE: { - int byteorder = (mformat_code == UTF32_LE) ? -1 : 1; - converted_items = PyUnicode_DecodeUTF32( - PyBytes_AS_STRING(items), Py_SIZE(items), - "strict", &byteorder); - if (converted_items == NULL) - return NULL; - break; - } - - case UNSIGNED_INT8: - case SIGNED_INT8: - case UNSIGNED_INT16_LE: - case UNSIGNED_INT16_BE: - case SIGNED_INT16_LE: - case SIGNED_INT16_BE: - case UNSIGNED_INT32_LE: - case UNSIGNED_INT32_BE: - case SIGNED_INT32_LE: - case SIGNED_INT32_BE: - case UNSIGNED_INT64_LE: - case UNSIGNED_INT64_BE: - case SIGNED_INT64_LE: - case SIGNED_INT64_BE: { - int i; - const struct mformatdescr mf_descr = - mformat_descriptors[mformat_code]; - Py_ssize_t itemcount = Py_SIZE(items) / mf_descr.size; - const unsigned char *memstr = - (unsigned char *)PyBytes_AS_STRING(items); - struct arraydescr *descr; - - /* If possible, try to pack array's items using a data type - * that fits better. This may result in an array with narrower - * or wider elements. - * - * For example, if a 32-bit machine pickles a L-code array of - * unsigned longs, then the array will be unpickled by 64-bit - * machine as an I-code array of unsigned ints. - * - * XXX: Is it possible to write a unit test for this? - */ - for (descr = descriptors; descr->typecode != '\0'; descr++) { - if (descr->is_integer_type && - descr->itemsize == mf_descr.size && - descr->is_signed == mf_descr.is_signed) - typecode = descr->typecode; - } - - converted_items = PyList_New(itemcount); - if (converted_items == NULL) - return NULL; - for (i = 0; i < itemcount; i++) { - PyObject *pylong; - - pylong = _PyLong_FromByteArray( - &memstr[i * mf_descr.size], - mf_descr.size, - !mf_descr.is_big_endian, - mf_descr.is_signed); - if (pylong == NULL) { - Py_DECREF(converted_items); - return NULL; - } - PyList_SET_ITEM(converted_items, i, pylong); - } - break; - } - case UNKNOWN_FORMAT: - /* Impossible, but needed to shut up GCC about the unhandled - * enumeration value. - */ - default: - PyErr_BadArgument(); - return NULL; - } - - result = make_array(arraytype, typecode, converted_items); - Py_DECREF(converted_items); - return result; + PyTypeObject *arraytype; + PyObject *items; + PyObject *converted_items; + PyObject *result; + int typecode; + enum machine_format_code mformat_code; + struct arraydescr *descr; + + if (!PyArg_ParseTuple(args, "OCiO:array._array_reconstructor", + &arraytype, &typecode, &mformat_code, &items)) + return NULL; + + if (!PyType_Check(arraytype)) { + PyErr_Format(PyExc_TypeError, + "first argument must a type object, not %.200s", + Py_TYPE(arraytype)->tp_name); + return NULL; + } + if (!PyType_IsSubtype(arraytype, &Arraytype)) { + PyErr_Format(PyExc_TypeError, + "%.200s is not a subtype of %.200s", + arraytype->tp_name, Arraytype.tp_name); + return NULL; + } + for (descr = descriptors; descr->typecode != '\0'; descr++) { + if (descr->typecode == typecode) + break; + } + if (descr->typecode == '\0') { + PyErr_SetString(PyExc_ValueError, + "second argument must be a valid type code"); + return NULL; + } + if (mformat_code < MACHINE_FORMAT_CODE_MIN || + mformat_code > MACHINE_FORMAT_CODE_MAX) { + PyErr_SetString(PyExc_ValueError, + "third argument must be a valid machine format code."); + return NULL; + } + if (!PyBytes_Check(items)) { + PyErr_Format(PyExc_TypeError, + "fourth argument should be bytes, not %.200s", + Py_TYPE(items)->tp_name); + return NULL; + } + + /* Fast path: No decoding has to be done. */ + if (mformat_code == typecode_to_mformat_code(typecode) || + mformat_code == UNKNOWN_FORMAT) { + return make_array(arraytype, typecode, items); + } + + /* Slow path: Decode the byte string according to the given machine + * format code. This occurs when the computer unpickling the array + * object is architecturally different from the one that pickled the + * array. + */ + if (Py_SIZE(items) % mformat_descriptors[mformat_code].size != 0) { + PyErr_SetString(PyExc_ValueError, + "string length not a multiple of item size"); + return NULL; + } + switch (mformat_code) { + case IEEE_754_FLOAT_LE: + case IEEE_754_FLOAT_BE: { + int i; + int le = (mformat_code == IEEE_754_FLOAT_LE) ? 1 : 0; + Py_ssize_t itemcount = Py_SIZE(items) / 4; + const unsigned char *memstr = + (unsigned char *)PyBytes_AS_STRING(items); + + converted_items = PyList_New(itemcount); + if (converted_items == NULL) + return NULL; + for (i = 0; i < itemcount; i++) { + PyObject *pyfloat = PyFloat_FromDouble( + _PyFloat_Unpack4(&memstr[i * 4], le)); + if (pyfloat == NULL) { + Py_DECREF(converted_items); + return NULL; + } + PyList_SET_ITEM(converted_items, i, pyfloat); + } + break; + } + case IEEE_754_DOUBLE_LE: + case IEEE_754_DOUBLE_BE: { + int i; + int le = (mformat_code == IEEE_754_DOUBLE_LE) ? 1 : 0; + Py_ssize_t itemcount = Py_SIZE(items) / 8; + const unsigned char *memstr = + (unsigned char *)PyBytes_AS_STRING(items); + + converted_items = PyList_New(itemcount); + if (converted_items == NULL) + return NULL; + for (i = 0; i < itemcount; i++) { + PyObject *pyfloat = PyFloat_FromDouble( + _PyFloat_Unpack8(&memstr[i * 8], le)); + if (pyfloat == NULL) { + Py_DECREF(converted_items); + return NULL; + } + PyList_SET_ITEM(converted_items, i, pyfloat); + } + break; + } + case UTF16_LE: + case UTF16_BE: { + int byteorder = (mformat_code == UTF16_LE) ? -1 : 1; + converted_items = PyUnicode_DecodeUTF16( + PyBytes_AS_STRING(items), Py_SIZE(items), + "strict", &byteorder); + if (converted_items == NULL) + return NULL; + break; + } + case UTF32_LE: + case UTF32_BE: { + int byteorder = (mformat_code == UTF32_LE) ? -1 : 1; + converted_items = PyUnicode_DecodeUTF32( + PyBytes_AS_STRING(items), Py_SIZE(items), + "strict", &byteorder); + if (converted_items == NULL) + return NULL; + break; + } + + case UNSIGNED_INT8: + case SIGNED_INT8: + case UNSIGNED_INT16_LE: + case UNSIGNED_INT16_BE: + case SIGNED_INT16_LE: + case SIGNED_INT16_BE: + case UNSIGNED_INT32_LE: + case UNSIGNED_INT32_BE: + case SIGNED_INT32_LE: + case SIGNED_INT32_BE: + case UNSIGNED_INT64_LE: + case UNSIGNED_INT64_BE: + case SIGNED_INT64_LE: + case SIGNED_INT64_BE: { + int i; + const struct mformatdescr mf_descr = + mformat_descriptors[mformat_code]; + Py_ssize_t itemcount = Py_SIZE(items) / mf_descr.size; + const unsigned char *memstr = + (unsigned char *)PyBytes_AS_STRING(items); + struct arraydescr *descr; + + /* If possible, try to pack array's items using a data type + * that fits better. This may result in an array with narrower + * or wider elements. + * + * For example, if a 32-bit machine pickles a L-code array of + * unsigned longs, then the array will be unpickled by 64-bit + * machine as an I-code array of unsigned ints. + * + * XXX: Is it possible to write a unit test for this? + */ + for (descr = descriptors; descr->typecode != '\0'; descr++) { + if (descr->is_integer_type && + descr->itemsize == mf_descr.size && + descr->is_signed == mf_descr.is_signed) + typecode = descr->typecode; + } + + converted_items = PyList_New(itemcount); + if (converted_items == NULL) + return NULL; + for (i = 0; i < itemcount; i++) { + PyObject *pylong; + + pylong = _PyLong_FromByteArray( + &memstr[i * mf_descr.size], + mf_descr.size, + !mf_descr.is_big_endian, + mf_descr.is_signed); + if (pylong == NULL) { + Py_DECREF(converted_items); + return NULL; + } + PyList_SET_ITEM(converted_items, i, pylong); + } + break; + } + case UNKNOWN_FORMAT: + /* Impossible, but needed to shut up GCC about the unhandled + * enumeration value. + */ + default: + PyErr_BadArgument(); + return NULL; + } + + result = make_array(arraytype, typecode, converted_items); + Py_DECREF(converted_items); + return result; } static PyObject * array_reduce_ex(arrayobject *array, PyObject *value) { - PyObject *dict; - PyObject *result; - PyObject *array_str; - int typecode = array->ob_descr->typecode; - int mformat_code; - static PyObject *array_reconstructor = NULL; - long protocol; - - if (array_reconstructor == NULL) { - PyObject *array_module = PyImport_ImportModule("array"); - if (array_module == NULL) - return NULL; - array_reconstructor = PyObject_GetAttrString( - array_module, - "_array_reconstructor"); - Py_DECREF(array_module); - if (array_reconstructor == NULL) - return NULL; - } - - if (!PyLong_Check(value)) { - PyErr_SetString(PyExc_TypeError, - "__reduce_ex__ argument should an integer"); - return NULL; - } - protocol = PyLong_AsLong(value); - if (protocol == -1 && PyErr_Occurred()) - return NULL; - - dict = PyObject_GetAttrString((PyObject *)array, "__dict__"); - if (dict == NULL) { - if (!PyErr_ExceptionMatches(PyExc_AttributeError)) - return NULL; - PyErr_Clear(); - dict = Py_None; - Py_INCREF(dict); - } - - mformat_code = typecode_to_mformat_code(typecode); - if (mformat_code == UNKNOWN_FORMAT || protocol < 3) { - /* Convert the array to a list if we got something weird - * (e.g., non-IEEE floats), or we are pickling the array using - * a Python 2.x compatible protocol. - * - * It is necessary to use a list representation for Python 2.x - * compatible pickle protocol, since Python 2's str objects - * are unpickled as unicode by Python 3. Thus it is impossible - * to make arrays unpicklable by Python 3 by using their memory - * representation, unless we resort to ugly hacks such as - * coercing unicode objects to bytes in array_reconstructor. - */ - PyObject *list; - list = array_tolist(array, NULL); - if (list == NULL) { - Py_DECREF(dict); - return NULL; - } - result = Py_BuildValue( - "O(CO)O", Py_TYPE(array), typecode, list, dict); - Py_DECREF(list); - Py_DECREF(dict); - return result; - } - - array_str = array_tostring(array, NULL); - if (array_str == NULL) { - Py_DECREF(dict); - return NULL; - } - result = Py_BuildValue( - "O(OCiN)O", array_reconstructor, Py_TYPE(array), typecode, - mformat_code, array_str, dict); - Py_DECREF(dict); - return result; + PyObject *dict; + PyObject *result; + PyObject *array_str; + int typecode = array->ob_descr->typecode; + int mformat_code; + static PyObject *array_reconstructor = NULL; + long protocol; + + if (array_reconstructor == NULL) { + PyObject *array_module = PyImport_ImportModule("array"); + if (array_module == NULL) + return NULL; + array_reconstructor = PyObject_GetAttrString( + array_module, + "_array_reconstructor"); + Py_DECREF(array_module); + if (array_reconstructor == NULL) + return NULL; + } + + if (!PyLong_Check(value)) { + PyErr_SetString(PyExc_TypeError, + "__reduce_ex__ argument should an integer"); + return NULL; + } + protocol = PyLong_AsLong(value); + if (protocol == -1 && PyErr_Occurred()) + return NULL; + + dict = PyObject_GetAttrString((PyObject *)array, "__dict__"); + if (dict == NULL) { + if (!PyErr_ExceptionMatches(PyExc_AttributeError)) + return NULL; + PyErr_Clear(); + dict = Py_None; + Py_INCREF(dict); + } + + mformat_code = typecode_to_mformat_code(typecode); + if (mformat_code == UNKNOWN_FORMAT || protocol < 3) { + /* Convert the array to a list if we got something weird + * (e.g., non-IEEE floats), or we are pickling the array using + * a Python 2.x compatible protocol. + * + * It is necessary to use a list representation for Python 2.x + * compatible pickle protocol, since Python 2's str objects + * are unpickled as unicode by Python 3. Thus it is impossible + * to make arrays unpicklable by Python 3 by using their memory + * representation, unless we resort to ugly hacks such as + * coercing unicode objects to bytes in array_reconstructor. + */ + PyObject *list; + list = array_tolist(array, NULL); + if (list == NULL) { + Py_DECREF(dict); + return NULL; + } + result = Py_BuildValue( + "O(CO)O", Py_TYPE(array), typecode, list, dict); + Py_DECREF(list); + Py_DECREF(dict); + return result; + } + + array_str = array_tostring(array, NULL); + if (array_str == NULL) { + Py_DECREF(dict); + return NULL; + } + result = Py_BuildValue( + "O(OCiN)O", array_reconstructor, Py_TYPE(array), typecode, + mformat_code, array_str, dict); + Py_DECREF(dict); + return result; } PyDoc_STRVAR(reduce_doc, "Return state information for pickling."); @@ -1944,313 +1944,313 @@ static PyObject * array_get_typecode(arrayobject *a, void *closure) { - char tc = a->ob_descr->typecode; - return PyUnicode_FromStringAndSize(&tc, 1); + char tc = a->ob_descr->typecode; + return PyUnicode_FromStringAndSize(&tc, 1); } static PyObject * array_get_itemsize(arrayobject *a, void *closure) { - return PyLong_FromLong((long)a->ob_descr->itemsize); + return PyLong_FromLong((long)a->ob_descr->itemsize); } static PyGetSetDef array_getsets [] = { - {"typecode", (getter) array_get_typecode, NULL, - "the typecode character used to create the array"}, - {"itemsize", (getter) array_get_itemsize, NULL, - "the size, in bytes, of one array item"}, - {NULL} + {"typecode", (getter) array_get_typecode, NULL, + "the typecode character used to create the array"}, + {"itemsize", (getter) array_get_itemsize, NULL, + "the size, in bytes, of one array item"}, + {NULL} }; static PyMethodDef array_methods[] = { - {"append", (PyCFunction)array_append, METH_O, - append_doc}, - {"buffer_info", (PyCFunction)array_buffer_info, METH_NOARGS, - buffer_info_doc}, - {"byteswap", (PyCFunction)array_byteswap, METH_NOARGS, - byteswap_doc}, - {"__copy__", (PyCFunction)array_copy, METH_NOARGS, - copy_doc}, - {"count", (PyCFunction)array_count, METH_O, - count_doc}, - {"__deepcopy__",(PyCFunction)array_copy, METH_O, - copy_doc}, - {"extend", (PyCFunction)array_extend, METH_O, - extend_doc}, - {"fromfile", (PyCFunction)array_fromfile, METH_VARARGS, - fromfile_doc}, - {"fromlist", (PyCFunction)array_fromlist, METH_O, - fromlist_doc}, - {"fromstring", (PyCFunction)array_fromstring, METH_VARARGS, - fromstring_doc}, - {"fromunicode", (PyCFunction)array_fromunicode, METH_VARARGS, - fromunicode_doc}, - {"index", (PyCFunction)array_index, METH_O, - index_doc}, - {"insert", (PyCFunction)array_insert, METH_VARARGS, - insert_doc}, - {"pop", (PyCFunction)array_pop, METH_VARARGS, - pop_doc}, - {"__reduce_ex__", (PyCFunction)array_reduce_ex, METH_O, - reduce_doc}, - {"remove", (PyCFunction)array_remove, METH_O, - remove_doc}, - {"reverse", (PyCFunction)array_reverse, METH_NOARGS, - reverse_doc}, -/* {"sort", (PyCFunction)array_sort, METH_VARARGS, - sort_doc},*/ - {"tofile", (PyCFunction)array_tofile, METH_O, - tofile_doc}, - {"tolist", (PyCFunction)array_tolist, METH_NOARGS, - tolist_doc}, - {"tostring", (PyCFunction)array_tostring, METH_NOARGS, - tostring_doc}, - {"tounicode", (PyCFunction)array_tounicode, METH_NOARGS, - tounicode_doc}, - {NULL, NULL} /* sentinel */ + {"append", (PyCFunction)array_append, METH_O, + append_doc}, + {"buffer_info", (PyCFunction)array_buffer_info, METH_NOARGS, + buffer_info_doc}, + {"byteswap", (PyCFunction)array_byteswap, METH_NOARGS, + byteswap_doc}, + {"__copy__", (PyCFunction)array_copy, METH_NOARGS, + copy_doc}, + {"count", (PyCFunction)array_count, METH_O, + count_doc}, + {"__deepcopy__",(PyCFunction)array_copy, METH_O, + copy_doc}, + {"extend", (PyCFunction)array_extend, METH_O, + extend_doc}, + {"fromfile", (PyCFunction)array_fromfile, METH_VARARGS, + fromfile_doc}, + {"fromlist", (PyCFunction)array_fromlist, METH_O, + fromlist_doc}, + {"fromstring", (PyCFunction)array_fromstring, METH_VARARGS, + fromstring_doc}, + {"fromunicode", (PyCFunction)array_fromunicode, METH_VARARGS, + fromunicode_doc}, + {"index", (PyCFunction)array_index, METH_O, + index_doc}, + {"insert", (PyCFunction)array_insert, METH_VARARGS, + insert_doc}, + {"pop", (PyCFunction)array_pop, METH_VARARGS, + pop_doc}, + {"__reduce_ex__", (PyCFunction)array_reduce_ex, METH_O, + reduce_doc}, + {"remove", (PyCFunction)array_remove, METH_O, + remove_doc}, + {"reverse", (PyCFunction)array_reverse, METH_NOARGS, + reverse_doc}, +/* {"sort", (PyCFunction)array_sort, METH_VARARGS, + sort_doc},*/ + {"tofile", (PyCFunction)array_tofile, METH_O, + tofile_doc}, + {"tolist", (PyCFunction)array_tolist, METH_NOARGS, + tolist_doc}, + {"tostring", (PyCFunction)array_tostring, METH_NOARGS, + tostring_doc}, + {"tounicode", (PyCFunction)array_tounicode, METH_NOARGS, + tounicode_doc}, + {NULL, NULL} /* sentinel */ }; static PyObject * array_repr(arrayobject *a) { - char typecode; - PyObject *s, *v = NULL; - Py_ssize_t len; - - len = Py_SIZE(a); - typecode = a->ob_descr->typecode; - if (len == 0) { - return PyUnicode_FromFormat("array('%c')", typecode); - } - if ((typecode == 'u')) - v = array_tounicode(a, NULL); - else - v = array_tolist(a, NULL); - - s = PyUnicode_FromFormat("array('%c', %R)", typecode, v); - Py_DECREF(v); - return s; + char typecode; + PyObject *s, *v = NULL; + Py_ssize_t len; + + len = Py_SIZE(a); + typecode = a->ob_descr->typecode; + if (len == 0) { + return PyUnicode_FromFormat("array('%c')", typecode); + } + if ((typecode == 'u')) + v = array_tounicode(a, NULL); + else + v = array_tolist(a, NULL); + + s = PyUnicode_FromFormat("array('%c', %R)", typecode, v); + Py_DECREF(v); + return s; } static PyObject* array_subscr(arrayobject* 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 += Py_SIZE(self); - return array_item(self, i); - } - else if (PySlice_Check(item)) { - Py_ssize_t start, stop, step, slicelength, cur, i; - PyObject* result; - arrayobject* ar; - int itemsize = self->ob_descr->itemsize; - - if (PySlice_GetIndicesEx((PySliceObject*)item, Py_SIZE(self), - &start, &stop, &step, &slicelength) < 0) { - return NULL; - } - - if (slicelength <= 0) { - return newarrayobject(&Arraytype, 0, self->ob_descr); - } - else if (step == 1) { - PyObject *result = newarrayobject(&Arraytype, - slicelength, self->ob_descr); - if (result == NULL) - return NULL; - memcpy(((arrayobject *)result)->ob_item, - self->ob_item + start * itemsize, - slicelength * itemsize); - return result; - } - else { - result = newarrayobject(&Arraytype, slicelength, self->ob_descr); - if (!result) return NULL; - - ar = (arrayobject*)result; - - for (cur = start, i = 0; i < slicelength; - cur += step, i++) { - memcpy(ar->ob_item + i*itemsize, - self->ob_item + cur*itemsize, - itemsize); - } - - return result; - } - } - else { - PyErr_SetString(PyExc_TypeError, - "array indices must be integers"); - return NULL; - } + 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 += Py_SIZE(self); + return array_item(self, i); + } + else if (PySlice_Check(item)) { + Py_ssize_t start, stop, step, slicelength, cur, i; + PyObject* result; + arrayobject* ar; + int itemsize = self->ob_descr->itemsize; + + if (PySlice_GetIndicesEx((PySliceObject*)item, Py_SIZE(self), + &start, &stop, &step, &slicelength) < 0) { + return NULL; + } + + if (slicelength <= 0) { + return newarrayobject(&Arraytype, 0, self->ob_descr); + } + else if (step == 1) { + PyObject *result = newarrayobject(&Arraytype, + slicelength, self->ob_descr); + if (result == NULL) + return NULL; + memcpy(((arrayobject *)result)->ob_item, + self->ob_item + start * itemsize, + slicelength * itemsize); + return result; + } + else { + result = newarrayobject(&Arraytype, slicelength, self->ob_descr); + if (!result) return NULL; + + ar = (arrayobject*)result; + + for (cur = start, i = 0; i < slicelength; + cur += step, i++) { + memcpy(ar->ob_item + i*itemsize, + self->ob_item + cur*itemsize, + itemsize); + } + + return result; + } + } + else { + PyErr_SetString(PyExc_TypeError, + "array indices must be integers"); + return NULL; + } } static int array_ass_subscr(arrayobject* self, PyObject* item, PyObject* value) { - Py_ssize_t start, stop, step, slicelength, needed; - arrayobject* other; - int itemsize; - - if (PyIndex_Check(item)) { - Py_ssize_t i = PyNumber_AsSsize_t(item, PyExc_IndexError); - - if (i == -1 && PyErr_Occurred()) - return -1; - if (i < 0) - i += Py_SIZE(self); - if (i < 0 || i >= Py_SIZE(self)) { - PyErr_SetString(PyExc_IndexError, - "array assignment index out of range"); - return -1; - } - if (value == NULL) { - /* Fall through to slice assignment */ - start = i; - stop = i + 1; - step = 1; - slicelength = 1; - } - else - return (*self->ob_descr->setitem)(self, i, value); - } - else if (PySlice_Check(item)) { - if (PySlice_GetIndicesEx((PySliceObject *)item, - Py_SIZE(self), &start, &stop, - &step, &slicelength) < 0) { - return -1; - } - } - else { - PyErr_SetString(PyExc_TypeError, - "array indices must be integer"); - return -1; - } - if (value == NULL) { - other = NULL; - needed = 0; - } - else if (array_Check(value)) { - other = (arrayobject *)value; - needed = Py_SIZE(other); - if (self == other) { - /* Special case "self[i:j] = self" -- copy self first */ - int ret; - value = array_slice(other, 0, needed); - if (value == NULL) - return -1; - ret = array_ass_subscr(self, item, value); - Py_DECREF(value); - return ret; - } - if (other->ob_descr != self->ob_descr) { - PyErr_BadArgument(); - return -1; - } - } - else { - PyErr_Format(PyExc_TypeError, - "can only assign array (not \"%.200s\") to array slice", - Py_TYPE(value)->tp_name); - return -1; - } - itemsize = self->ob_descr->itemsize; - /* for 'a[2:1] = ...', the insertion point is 'start', not 'stop' */ - if ((step > 0 && stop < start) || - (step < 0 && stop > start)) - stop = start; - - /* Issue #4509: If the array has exported buffers and the slice - assignment would change the size of the array, fail early to make - sure we don't modify it. */ - if ((needed == 0 || slicelength != needed) && self->ob_exports > 0) { - PyErr_SetString(PyExc_BufferError, - "cannot resize an array that is exporting buffers"); - return -1; - } - - if (step == 1) { - if (slicelength > needed) { - memmove(self->ob_item + (start + needed) * itemsize, - self->ob_item + stop * itemsize, - (Py_SIZE(self) - stop) * itemsize); - if (array_resize(self, Py_SIZE(self) + - needed - slicelength) < 0) - return -1; - } - else if (slicelength < needed) { - if (array_resize(self, Py_SIZE(self) + - needed - slicelength) < 0) - return -1; - memmove(self->ob_item + (start + needed) * itemsize, - self->ob_item + stop * itemsize, - (Py_SIZE(self) - start - needed) * itemsize); - } - if (needed > 0) - memcpy(self->ob_item + start * itemsize, - other->ob_item, needed * itemsize); - return 0; - } - else if (needed == 0) { - /* Delete slice */ - size_t cur; - Py_ssize_t i; - - if (step < 0) { - stop = start + 1; - start = stop + step * (slicelength - 1) - 1; - step = -step; - } - for (cur = start, i = 0; i < slicelength; - cur += step, i++) { - Py_ssize_t lim = step - 1; - - if (cur + step >= (size_t)Py_SIZE(self)) - lim = Py_SIZE(self) - cur - 1; - memmove(self->ob_item + (cur - i) * itemsize, - self->ob_item + (cur + 1) * itemsize, - lim * itemsize); - } - cur = start + slicelength * step; - if (cur < (size_t)Py_SIZE(self)) { - memmove(self->ob_item + (cur-slicelength) * itemsize, - self->ob_item + cur * itemsize, - (Py_SIZE(self) - cur) * itemsize); - } - if (array_resize(self, Py_SIZE(self) - slicelength) < 0) - return -1; - return 0; - } - else { - Py_ssize_t cur, i; - - if (needed != slicelength) { - PyErr_Format(PyExc_ValueError, - "attempt to assign array of size %zd " - "to extended slice of size %zd", - needed, slicelength); - return -1; - } - for (cur = start, i = 0; i < slicelength; - cur += step, i++) { - memcpy(self->ob_item + cur * itemsize, - other->ob_item + i * itemsize, - itemsize); - } - return 0; - } + Py_ssize_t start, stop, step, slicelength, needed; + arrayobject* other; + int itemsize; + + if (PyIndex_Check(item)) { + Py_ssize_t i = PyNumber_AsSsize_t(item, PyExc_IndexError); + + if (i == -1 && PyErr_Occurred()) + return -1; + if (i < 0) + i += Py_SIZE(self); + if (i < 0 || i >= Py_SIZE(self)) { + PyErr_SetString(PyExc_IndexError, + "array assignment index out of range"); + return -1; + } + if (value == NULL) { + /* Fall through to slice assignment */ + start = i; + stop = i + 1; + step = 1; + slicelength = 1; + } + else + return (*self->ob_descr->setitem)(self, i, value); + } + else if (PySlice_Check(item)) { + if (PySlice_GetIndicesEx((PySliceObject *)item, + Py_SIZE(self), &start, &stop, + &step, &slicelength) < 0) { + return -1; + } + } + else { + PyErr_SetString(PyExc_TypeError, + "array indices must be integer"); + return -1; + } + if (value == NULL) { + other = NULL; + needed = 0; + } + else if (array_Check(value)) { + other = (arrayobject *)value; + needed = Py_SIZE(other); + if (self == other) { + /* Special case "self[i:j] = self" -- copy self first */ + int ret; + value = array_slice(other, 0, needed); + if (value == NULL) + return -1; + ret = array_ass_subscr(self, item, value); + Py_DECREF(value); + return ret; + } + if (other->ob_descr != self->ob_descr) { + PyErr_BadArgument(); + return -1; + } + } + else { + PyErr_Format(PyExc_TypeError, + "can only assign array (not \"%.200s\") to array slice", + Py_TYPE(value)->tp_name); + return -1; + } + itemsize = self->ob_descr->itemsize; + /* for 'a[2:1] = ...', the insertion point is 'start', not 'stop' */ + if ((step > 0 && stop < start) || + (step < 0 && stop > start)) + stop = start; + + /* Issue #4509: If the array has exported buffers and the slice + assignment would change the size of the array, fail early to make + sure we don't modify it. */ + if ((needed == 0 || slicelength != needed) && self->ob_exports > 0) { + PyErr_SetString(PyExc_BufferError, + "cannot resize an array that is exporting buffers"); + return -1; + } + + if (step == 1) { + if (slicelength > needed) { + memmove(self->ob_item + (start + needed) * itemsize, + self->ob_item + stop * itemsize, + (Py_SIZE(self) - stop) * itemsize); + if (array_resize(self, Py_SIZE(self) + + needed - slicelength) < 0) + return -1; + } + else if (slicelength < needed) { + if (array_resize(self, Py_SIZE(self) + + needed - slicelength) < 0) + return -1; + memmove(self->ob_item + (start + needed) * itemsize, + self->ob_item + stop * itemsize, + (Py_SIZE(self) - start - needed) * itemsize); + } + if (needed > 0) + memcpy(self->ob_item + start * itemsize, + other->ob_item, needed * itemsize); + return 0; + } + else if (needed == 0) { + /* Delete slice */ + size_t cur; + Py_ssize_t i; + + if (step < 0) { + stop = start + 1; + start = stop + step * (slicelength - 1) - 1; + step = -step; + } + for (cur = start, i = 0; i < slicelength; + cur += step, i++) { + Py_ssize_t lim = step - 1; + + if (cur + step >= (size_t)Py_SIZE(self)) + lim = Py_SIZE(self) - cur - 1; + memmove(self->ob_item + (cur - i) * itemsize, + self->ob_item + (cur + 1) * itemsize, + lim * itemsize); + } + cur = start + slicelength * step; + if (cur < (size_t)Py_SIZE(self)) { + memmove(self->ob_item + (cur-slicelength) * itemsize, + self->ob_item + cur * itemsize, + (Py_SIZE(self) - cur) * itemsize); + } + if (array_resize(self, Py_SIZE(self) - slicelength) < 0) + return -1; + return 0; + } + else { + Py_ssize_t cur, i; + + if (needed != slicelength) { + PyErr_Format(PyExc_ValueError, + "attempt to assign array of size %zd " + "to extended slice of size %zd", + needed, slicelength); + return -1; + } + for (cur = start, i = 0; i < slicelength; + cur += step, i++) { + memcpy(self->ob_item + cur * itemsize, + other->ob_item + i * itemsize, + itemsize); + } + return 0; + } } static PyMappingMethods array_as_mapping = { - (lenfunc)array_length, - (binaryfunc)array_subscr, - (objobjargproc)array_ass_subscr + (lenfunc)array_length, + (binaryfunc)array_subscr, + (objobjargproc)array_ass_subscr }; static const void *emptybuf = ""; @@ -2259,173 +2259,173 @@ static int array_buffer_getbuf(arrayobject *self, Py_buffer *view, int flags) { - if (view==NULL) goto finish; + if (view==NULL) goto finish; - view->buf = (void *)self->ob_item; - view->obj = (PyObject*)self; - Py_INCREF(self); - if (view->buf == NULL) - view->buf = (void *)emptybuf; - view->len = (Py_SIZE(self)) * self->ob_descr->itemsize; - view->readonly = 0; - view->ndim = 1; - view->itemsize = self->ob_descr->itemsize; - view->suboffsets = NULL; - view->shape = NULL; - if ((flags & PyBUF_ND)==PyBUF_ND) { - view->shape = &((Py_SIZE(self))); - } - view->strides = NULL; - if ((flags & PyBUF_STRIDES)==PyBUF_STRIDES) - view->strides = &(view->itemsize); - view->format = NULL; - view->internal = NULL; - if ((flags & PyBUF_FORMAT) == PyBUF_FORMAT) { - view->format = self->ob_descr->formats; + view->buf = (void *)self->ob_item; + view->obj = (PyObject*)self; + Py_INCREF(self); + if (view->buf == NULL) + view->buf = (void *)emptybuf; + view->len = (Py_SIZE(self)) * self->ob_descr->itemsize; + view->readonly = 0; + view->ndim = 1; + view->itemsize = self->ob_descr->itemsize; + view->suboffsets = NULL; + view->shape = NULL; + if ((flags & PyBUF_ND)==PyBUF_ND) { + view->shape = &((Py_SIZE(self))); + } + view->strides = NULL; + if ((flags & PyBUF_STRIDES)==PyBUF_STRIDES) + view->strides = &(view->itemsize); + view->format = NULL; + view->internal = NULL; + if ((flags & PyBUF_FORMAT) == PyBUF_FORMAT) { + view->format = self->ob_descr->formats; #ifdef Py_UNICODE_WIDE - if (self->ob_descr->typecode == 'u') { - view->format = "w"; - } -#endif + if (self->ob_descr->typecode == 'u') { + view->format = "w"; } +#endif + } finish: - self->ob_exports++; - return 0; + self->ob_exports++; + return 0; } static void array_buffer_relbuf(arrayobject *self, Py_buffer *view) { - self->ob_exports--; + self->ob_exports--; } static PySequenceMethods array_as_sequence = { - (lenfunc)array_length, /*sq_length*/ - (binaryfunc)array_concat, /*sq_concat*/ - (ssizeargfunc)array_repeat, /*sq_repeat*/ - (ssizeargfunc)array_item, /*sq_item*/ - 0, /*sq_slice*/ - (ssizeobjargproc)array_ass_item, /*sq_ass_item*/ - 0, /*sq_ass_slice*/ - (objobjproc)array_contains, /*sq_contains*/ - (binaryfunc)array_inplace_concat, /*sq_inplace_concat*/ - (ssizeargfunc)array_inplace_repeat /*sq_inplace_repeat*/ + (lenfunc)array_length, /*sq_length*/ + (binaryfunc)array_concat, /*sq_concat*/ + (ssizeargfunc)array_repeat, /*sq_repeat*/ + (ssizeargfunc)array_item, /*sq_item*/ + 0, /*sq_slice*/ + (ssizeobjargproc)array_ass_item, /*sq_ass_item*/ + 0, /*sq_ass_slice*/ + (objobjproc)array_contains, /*sq_contains*/ + (binaryfunc)array_inplace_concat, /*sq_inplace_concat*/ + (ssizeargfunc)array_inplace_repeat /*sq_inplace_repeat*/ }; static PyBufferProcs array_as_buffer = { - (getbufferproc)array_buffer_getbuf, - (releasebufferproc)array_buffer_relbuf + (getbufferproc)array_buffer_getbuf, + (releasebufferproc)array_buffer_relbuf }; static PyObject * array_new(PyTypeObject *type, PyObject *args, PyObject *kwds) { - int c; - PyObject *initial = NULL, *it = NULL; - struct arraydescr *descr; - - if (type == &Arraytype && !_PyArg_NoKeywords("array.array()", kwds)) - return NULL; - - if (!PyArg_ParseTuple(args, "C|O:array", &c, &initial)) - return NULL; - - if (!(initial == NULL || PyList_Check(initial) - || PyByteArray_Check(initial) - || PyBytes_Check(initial) - || PyTuple_Check(initial) - || ((c=='u') && PyUnicode_Check(initial)))) { - it = PyObject_GetIter(initial); - if (it == NULL) - return NULL; - /* We set initial to NULL so that the subsequent code - will create an empty array of the appropriate type - and afterwards we can use array_iter_extend to populate - the array. - */ - initial = NULL; - } - for (descr = descriptors; descr->typecode != '\0'; descr++) { - if (descr->typecode == c) { - PyObject *a; - Py_ssize_t len; - - if (initial == NULL || !(PyList_Check(initial) - || PyTuple_Check(initial))) - len = 0; - else - len = PySequence_Size(initial); - - a = newarrayobject(type, len, descr); - if (a == NULL) - return NULL; - - if (len > 0) { - Py_ssize_t i; - for (i = 0; i < len; i++) { - PyObject *v = - PySequence_GetItem(initial, i); - if (v == NULL) { - Py_DECREF(a); - return NULL; - } - if (setarrayitem(a, i, v) != 0) { - Py_DECREF(v); - Py_DECREF(a); - return NULL; - } - Py_DECREF(v); - } - } - else if (initial != NULL && (PyByteArray_Check(initial) || - PyBytes_Check(initial))) { - PyObject *t_initial, *v; - t_initial = PyTuple_Pack(1, initial); - if (t_initial == NULL) { - Py_DECREF(a); - return NULL; - } - v = array_fromstring((arrayobject *)a, - t_initial); - Py_DECREF(t_initial); - if (v == NULL) { - Py_DECREF(a); - return NULL; - } - Py_DECREF(v); - } - else if (initial != NULL && PyUnicode_Check(initial)) { - Py_ssize_t n = PyUnicode_GET_DATA_SIZE(initial); - if (n > 0) { - arrayobject *self = (arrayobject *)a; - char *item = self->ob_item; - item = (char *)PyMem_Realloc(item, n); - if (item == NULL) { - PyErr_NoMemory(); - Py_DECREF(a); - return NULL; - } - self->ob_item = item; - Py_SIZE(self) = n / sizeof(Py_UNICODE); - memcpy(item, PyUnicode_AS_DATA(initial), n); - self->allocated = Py_SIZE(self); - } - } - if (it != NULL) { - if (array_iter_extend((arrayobject *)a, it) == -1) { - Py_DECREF(it); - Py_DECREF(a); - return NULL; - } - Py_DECREF(it); - } - return a; - } - } - PyErr_SetString(PyExc_ValueError, - "bad typecode (must be b, B, u, h, H, i, I, l, L, f or d)"); - return NULL; + int c; + PyObject *initial = NULL, *it = NULL; + struct arraydescr *descr; + + if (type == &Arraytype && !_PyArg_NoKeywords("array.array()", kwds)) + return NULL; + + if (!PyArg_ParseTuple(args, "C|O:array", &c, &initial)) + return NULL; + + if (!(initial == NULL || PyList_Check(initial) + || PyByteArray_Check(initial) + || PyBytes_Check(initial) + || PyTuple_Check(initial) + || ((c=='u') && PyUnicode_Check(initial)))) { + it = PyObject_GetIter(initial); + if (it == NULL) + return NULL; + /* We set initial to NULL so that the subsequent code + will create an empty array of the appropriate type + and afterwards we can use array_iter_extend to populate + the array. + */ + initial = NULL; + } + for (descr = descriptors; descr->typecode != '\0'; descr++) { + if (descr->typecode == c) { + PyObject *a; + Py_ssize_t len; + + if (initial == NULL || !(PyList_Check(initial) + || PyTuple_Check(initial))) + len = 0; + else + len = PySequence_Size(initial); + + a = newarrayobject(type, len, descr); + if (a == NULL) + return NULL; + + if (len > 0) { + Py_ssize_t i; + for (i = 0; i < len; i++) { + PyObject *v = + PySequence_GetItem(initial, i); + if (v == NULL) { + Py_DECREF(a); + return NULL; + } + if (setarrayitem(a, i, v) != 0) { + Py_DECREF(v); + Py_DECREF(a); + return NULL; + } + Py_DECREF(v); + } + } + else if (initial != NULL && (PyByteArray_Check(initial) || + PyBytes_Check(initial))) { + PyObject *t_initial, *v; + t_initial = PyTuple_Pack(1, initial); + if (t_initial == NULL) { + Py_DECREF(a); + return NULL; + } + v = array_fromstring((arrayobject *)a, + t_initial); + Py_DECREF(t_initial); + if (v == NULL) { + Py_DECREF(a); + return NULL; + } + Py_DECREF(v); + } + else if (initial != NULL && PyUnicode_Check(initial)) { + Py_ssize_t n = PyUnicode_GET_DATA_SIZE(initial); + if (n > 0) { + arrayobject *self = (arrayobject *)a; + char *item = self->ob_item; + item = (char *)PyMem_Realloc(item, n); + if (item == NULL) { + PyErr_NoMemory(); + Py_DECREF(a); + return NULL; + } + self->ob_item = item; + Py_SIZE(self) = n / sizeof(Py_UNICODE); + memcpy(item, PyUnicode_AS_DATA(initial), n); + self->allocated = Py_SIZE(self); + } + } + if (it != NULL) { + if (array_iter_extend((arrayobject *)a, it) == -1) { + Py_DECREF(it); + Py_DECREF(a); + return NULL; + } + Py_DECREF(it); + } + return a; + } + } + PyErr_SetString(PyExc_ValueError, + "bad typecode (must be b, B, u, h, H, i, I, l, L, f or d)"); + return NULL; } @@ -2496,55 +2496,55 @@ static PyObject *array_iter(arrayobject *ao); static PyTypeObject Arraytype = { - PyVarObject_HEAD_INIT(NULL, 0) - "array.array", - sizeof(arrayobject), - 0, - (destructor)array_dealloc, /* tp_dealloc */ - 0, /* tp_print */ - 0, /* tp_getattr */ - 0, /* tp_setattr */ - 0, /* tp_reserved */ - (reprfunc)array_repr, /* tp_repr */ - 0, /* tp_as_number*/ - &array_as_sequence, /* tp_as_sequence*/ - &array_as_mapping, /* tp_as_mapping*/ - 0, /* tp_hash */ - 0, /* tp_call */ - 0, /* tp_str */ - PyObject_GenericGetAttr, /* tp_getattro */ - 0, /* tp_setattro */ - &array_as_buffer, /* tp_as_buffer*/ - Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */ - arraytype_doc, /* tp_doc */ - 0, /* tp_traverse */ - 0, /* tp_clear */ - array_richcompare, /* tp_richcompare */ - offsetof(arrayobject, weakreflist), /* tp_weaklistoffset */ - (getiterfunc)array_iter, /* tp_iter */ - 0, /* tp_iternext */ - array_methods, /* tp_methods */ - 0, /* tp_members */ - array_getsets, /* tp_getset */ - 0, /* tp_base */ - 0, /* tp_dict */ - 0, /* tp_descr_get */ - 0, /* tp_descr_set */ - 0, /* tp_dictoffset */ - 0, /* tp_init */ - PyType_GenericAlloc, /* tp_alloc */ - array_new, /* tp_new */ - PyObject_Del, /* tp_free */ + PyVarObject_HEAD_INIT(NULL, 0) + "array.array", + sizeof(arrayobject), + 0, + (destructor)array_dealloc, /* tp_dealloc */ + 0, /* tp_print */ + 0, /* tp_getattr */ + 0, /* tp_setattr */ + 0, /* tp_reserved */ + (reprfunc)array_repr, /* tp_repr */ + 0, /* tp_as_number*/ + &array_as_sequence, /* tp_as_sequence*/ + &array_as_mapping, /* tp_as_mapping*/ + 0, /* tp_hash */ + 0, /* tp_call */ + 0, /* tp_str */ + PyObject_GenericGetAttr, /* tp_getattro */ + 0, /* tp_setattro */ + &array_as_buffer, /* tp_as_buffer*/ + Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */ + arraytype_doc, /* tp_doc */ + 0, /* tp_traverse */ + 0, /* tp_clear */ + array_richcompare, /* tp_richcompare */ + offsetof(arrayobject, weakreflist), /* tp_weaklistoffset */ + (getiterfunc)array_iter, /* tp_iter */ + 0, /* tp_iternext */ + array_methods, /* tp_methods */ + 0, /* tp_members */ + array_getsets, /* tp_getset */ + 0, /* tp_base */ + 0, /* tp_dict */ + 0, /* tp_descr_get */ + 0, /* tp_descr_set */ + 0, /* tp_dictoffset */ + 0, /* tp_init */ + PyType_GenericAlloc, /* tp_alloc */ + array_new, /* tp_new */ + PyObject_Del, /* tp_free */ }; /*********************** Array Iterator **************************/ typedef struct { - PyObject_HEAD - Py_ssize_t index; - arrayobject *ao; - PyObject * (*getitem)(struct arrayobject *, Py_ssize_t); + PyObject_HEAD + Py_ssize_t index; + arrayobject *ao; + PyObject * (*getitem)(struct arrayobject *, Py_ssize_t); } arrayiterobject; static PyTypeObject PyArrayIter_Type; @@ -2554,79 +2554,79 @@ static PyObject * array_iter(arrayobject *ao) { - arrayiterobject *it; + arrayiterobject *it; - if (!array_Check(ao)) { - PyErr_BadInternalCall(); - return NULL; - } - - it = PyObject_GC_New(arrayiterobject, &PyArrayIter_Type); - if (it == NULL) - return NULL; - - Py_INCREF(ao); - it->ao = ao; - it->index = 0; - it->getitem = ao->ob_descr->getitem; - PyObject_GC_Track(it); - return (PyObject *)it; + if (!array_Check(ao)) { + PyErr_BadInternalCall(); + return NULL; + } + + it = PyObject_GC_New(arrayiterobject, &PyArrayIter_Type); + if (it == NULL) + return NULL; + + Py_INCREF(ao); + it->ao = ao; + it->index = 0; + it->getitem = ao->ob_descr->getitem; + PyObject_GC_Track(it); + return (PyObject *)it; } static PyObject * arrayiter_next(arrayiterobject *it) { - assert(PyArrayIter_Check(it)); - if (it->index < Py_SIZE(it->ao)) - return (*it->getitem)(it->ao, it->index++); - return NULL; + assert(PyArrayIter_Check(it)); + if (it->index < Py_SIZE(it->ao)) + return (*it->getitem)(it->ao, it->index++); + return NULL; } static void arrayiter_dealloc(arrayiterobject *it) { - PyObject_GC_UnTrack(it); - Py_XDECREF(it->ao); - PyObject_GC_Del(it); + PyObject_GC_UnTrack(it); + Py_XDECREF(it->ao); + PyObject_GC_Del(it); } static int arrayiter_traverse(arrayiterobject *it, visitproc visit, void *arg) { - Py_VISIT(it->ao); - return 0; + Py_VISIT(it->ao); + return 0; } static PyTypeObject PyArrayIter_Type = { - PyVarObject_HEAD_INIT(NULL, 0) - "arrayiterator", /* tp_name */ - sizeof(arrayiterobject), /* tp_basicsize */ - 0, /* tp_itemsize */ - /* methods */ - (destructor)arrayiter_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)arrayiter_traverse, /* tp_traverse */ - 0, /* tp_clear */ - 0, /* tp_richcompare */ - 0, /* tp_weaklistoffset */ - PyObject_SelfIter, /* tp_iter */ - (iternextfunc)arrayiter_next, /* tp_iternext */ - 0, /* tp_methods */ + PyVarObject_HEAD_INIT(NULL, 0) + "arrayiterator", /* tp_name */ + sizeof(arrayiterobject), /* tp_basicsize */ + 0, /* tp_itemsize */ + /* methods */ + (destructor)arrayiter_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)arrayiter_traverse, /* tp_traverse */ + 0, /* tp_clear */ + 0, /* tp_richcompare */ + 0, /* tp_weaklistoffset */ + PyObject_SelfIter, /* tp_iter */ + (iternextfunc)arrayiter_next, /* tp_iternext */ + 0, /* tp_methods */ }; @@ -2640,54 +2640,54 @@ }; static struct PyModuleDef arraymodule = { - PyModuleDef_HEAD_INIT, - "array", - module_doc, - -1, - a_methods, - NULL, - NULL, - NULL, - NULL + PyModuleDef_HEAD_INIT, + "array", + module_doc, + -1, + a_methods, + NULL, + NULL, + NULL, + NULL }; PyMODINIT_FUNC PyInit_array(void) { - PyObject *m; - PyObject *typecodes; - Py_ssize_t size = 0; - register Py_UNICODE *p; - struct arraydescr *descr; - - if (PyType_Ready(&Arraytype) < 0) - return NULL; - Py_TYPE(&PyArrayIter_Type) = &PyType_Type; - m = PyModule_Create(&arraymodule); - if (m == NULL) - return NULL; - - Py_INCREF((PyObject *)&Arraytype); - PyModule_AddObject(m, "ArrayType", (PyObject *)&Arraytype); - Py_INCREF((PyObject *)&Arraytype); - PyModule_AddObject(m, "array", (PyObject *)&Arraytype); - - for (descr=descriptors; descr->typecode != '\0'; descr++) { - size++; - } - - typecodes = PyUnicode_FromStringAndSize(NULL, size); - p = PyUnicode_AS_UNICODE(typecodes); - for (descr = descriptors; descr->typecode != '\0'; descr++) { - *p++ = (char)descr->typecode; - } - - PyModule_AddObject(m, "typecodes", (PyObject *)typecodes); - - if (PyErr_Occurred()) { - Py_DECREF(m); - m = NULL; - } - return m; + PyObject *m; + PyObject *typecodes; + Py_ssize_t size = 0; + register Py_UNICODE *p; + struct arraydescr *descr; + + if (PyType_Ready(&Arraytype) < 0) + return NULL; + Py_TYPE(&PyArrayIter_Type) = &PyType_Type; + m = PyModule_Create(&arraymodule); + if (m == NULL) + return NULL; + + Py_INCREF((PyObject *)&Arraytype); + PyModule_AddObject(m, "ArrayType", (PyObject *)&Arraytype); + Py_INCREF((PyObject *)&Arraytype); + PyModule_AddObject(m, "array", (PyObject *)&Arraytype); + + for (descr=descriptors; descr->typecode != '\0'; descr++) { + size++; + } + + typecodes = PyUnicode_FromStringAndSize(NULL, size); + p = PyUnicode_AS_UNICODE(typecodes); + for (descr = descriptors; descr->typecode != '\0'; descr++) { + *p++ = (char)descr->typecode; + } + + PyModule_AddObject(m, "typecodes", (PyObject *)typecodes); + + if (PyErr_Occurred()) { + Py_DECREF(m); + m = NULL; + } + return m; } Modified: python/branches/py3k-jit/Modules/audioop.c ============================================================================== --- python/branches/py3k-jit/Modules/audioop.c (original) +++ python/branches/py3k-jit/Modules/audioop.c Mon May 10 23:55:43 2010 @@ -53,13 +53,13 @@ static PyInt16 search(PyInt16 val, PyInt16 *table, int size) { - int i; + int i; - for (i = 0; i < size; i++) { - if (val <= *table++) - return (i); - } - return (size); + for (i = 0; i < size; i++) { + if (val <= *table++) + return (i); + } + return (size); } #define st_ulaw2linear16(uc) (_st_ulaw2linear16[uc]) #define st_alaw2linear16(uc) (_st_alaw2linear16[uc]) @@ -83,7 +83,7 @@ -228, -212, -196, -180, -164, -148, -132, -120, -112, -104, -96, -88, -80, -72, -64, -56, -48, -40, -32, -24, -16, - -8, 0, 32124, 31100, 30076, 29052, 28028, + -8, 0, 32124, 31100, 30076, 29052, 28028, 27004, 25980, 24956, 23932, 22908, 21884, 20860, 19836, 18812, 17788, 16764, 15996, 15484, 14972, 14460, 13948, 13436, 12924, 12412, 11900, 11388, @@ -100,8 +100,8 @@ 372, 356, 340, 324, 308, 292, 276, 260, 244, 228, 212, 196, 180, 164, 148, 132, 120, 112, 104, 96, 88, - 80, 72, 64, 56, 48, 40, 32, - 24, 16, 8, 0 + 80, 72, 64, 56, 48, 40, 32, + 24, 16, 8, 0 }; /* @@ -137,39 +137,39 @@ * John Wiley & Sons, pps 98-111 and 472-476. */ static unsigned char -st_14linear2ulaw(PyInt16 pcm_val) /* 2's complement (14-bit range) */ +st_14linear2ulaw(PyInt16 pcm_val) /* 2's complement (14-bit range) */ { - PyInt16 mask; - PyInt16 seg; - unsigned char uval; - - /* The original sox code does this in the calling function, not here */ - pcm_val = pcm_val >> 2; - - /* u-law inverts all bits */ - /* Get the sign and the magnitude of the value. */ - if (pcm_val < 0) { - pcm_val = -pcm_val; - mask = 0x7F; - } else { - mask = 0xFF; - } - if ( pcm_val > CLIP ) pcm_val = CLIP; /* clip the magnitude */ - pcm_val += (BIAS >> 2); - - /* Convert the scaled magnitude to segment number. */ - seg = search(pcm_val, seg_uend, 8); - - /* - * Combine the sign, segment, quantization bits; - * and complement the code word. - */ - if (seg >= 8) /* out of range, return maximum value. */ - return (unsigned char) (0x7F ^ mask); - else { - uval = (unsigned char) (seg << 4) | ((pcm_val >> (seg + 1)) & 0xF); - return (uval ^ mask); - } + PyInt16 mask; + PyInt16 seg; + unsigned char uval; + + /* The original sox code does this in the calling function, not here */ + pcm_val = pcm_val >> 2; + + /* u-law inverts all bits */ + /* Get the sign and the magnitude of the value. */ + if (pcm_val < 0) { + pcm_val = -pcm_val; + mask = 0x7F; + } else { + mask = 0xFF; + } + if ( pcm_val > CLIP ) pcm_val = CLIP; /* clip the magnitude */ + pcm_val += (BIAS >> 2); + + /* Convert the scaled magnitude to segment number. */ + seg = search(pcm_val, seg_uend, 8); + + /* + * Combine the sign, segment, quantization bits; + * and complement the code word. + */ + if (seg >= 8) /* out of range, return maximum value. */ + return (unsigned char) (0x7F ^ mask); + else { + uval = (unsigned char) (seg << 4) | ((pcm_val >> (seg + 1)) & 0xF); + return (uval ^ mask); + } } @@ -234,59 +234,59 @@ * John Wiley & Sons, pps 98-111 and 472-476. */ static unsigned char -st_linear2alaw(PyInt16 pcm_val) /* 2's complement (13-bit range) */ +st_linear2alaw(PyInt16 pcm_val) /* 2's complement (13-bit range) */ { - PyInt16 mask; - short seg; - unsigned char aval; - - /* The original sox code does this in the calling function, not here */ - pcm_val = pcm_val >> 3; - - /* A-law using even bit inversion */ - if (pcm_val >= 0) { - mask = 0xD5; /* sign (7th) bit = 1 */ - } else { - mask = 0x55; /* sign bit = 0 */ - pcm_val = -pcm_val - 1; - } - - /* Convert the scaled magnitude to segment number. */ - seg = search(pcm_val, seg_aend, 8); - - /* Combine the sign, segment, and quantization bits. */ - - if (seg >= 8) /* out of range, return maximum value. */ - return (unsigned char) (0x7F ^ mask); - else { - aval = (unsigned char) seg << SEG_SHIFT; - if (seg < 2) - aval |= (pcm_val >> 1) & QUANT_MASK; - else - aval |= (pcm_val >> seg) & QUANT_MASK; - return (aval ^ mask); - } + PyInt16 mask; + short seg; + unsigned char aval; + + /* The original sox code does this in the calling function, not here */ + pcm_val = pcm_val >> 3; + + /* A-law using even bit inversion */ + if (pcm_val >= 0) { + mask = 0xD5; /* sign (7th) bit = 1 */ + } else { + mask = 0x55; /* sign bit = 0 */ + pcm_val = -pcm_val - 1; + } + + /* Convert the scaled magnitude to segment number. */ + seg = search(pcm_val, seg_aend, 8); + + /* Combine the sign, segment, and quantization bits. */ + + if (seg >= 8) /* out of range, return maximum value. */ + return (unsigned char) (0x7F ^ mask); + else { + aval = (unsigned char) seg << SEG_SHIFT; + if (seg < 2) + aval |= (pcm_val >> 1) & QUANT_MASK; + else + aval |= (pcm_val >> seg) & QUANT_MASK; + return (aval ^ mask); + } } /* End of code taken from sox */ /* Intel ADPCM step variation table */ static int indexTable[16] = { - -1, -1, -1, -1, 2, 4, 6, 8, - -1, -1, -1, -1, 2, 4, 6, 8, + -1, -1, -1, -1, 2, 4, 6, 8, + -1, -1, -1, -1, 2, 4, 6, 8, }; static int stepsizeTable[89] = { - 7, 8, 9, 10, 11, 12, 13, 14, 16, 17, - 19, 21, 23, 25, 28, 31, 34, 37, 41, 45, - 50, 55, 60, 66, 73, 80, 88, 97, 107, 118, - 130, 143, 157, 173, 190, 209, 230, 253, 279, 307, - 337, 371, 408, 449, 494, 544, 598, 658, 724, 796, - 876, 963, 1060, 1166, 1282, 1411, 1552, 1707, 1878, 2066, - 2272, 2499, 2749, 3024, 3327, 3660, 4026, 4428, 4871, 5358, - 5894, 6484, 7132, 7845, 8630, 9493, 10442, 11487, 12635, 13899, - 15289, 16818, 18500, 20350, 22385, 24623, 27086, 29794, 32767 + 7, 8, 9, 10, 11, 12, 13, 14, 16, 17, + 19, 21, 23, 25, 28, 31, 34, 37, 41, 45, + 50, 55, 60, 66, 73, 80, 88, 97, 107, 118, + 130, 143, 157, 173, 190, 209, 230, 253, 279, 307, + 337, 371, 408, 449, 494, 544, 598, 658, 724, 796, + 876, 963, 1060, 1166, 1282, 1411, 1552, 1707, 1878, 2066, + 2272, 2499, 2749, 3024, 3327, 3660, 4026, 4428, 4871, 5358, + 5894, 6484, 7132, 7845, 8630, 9493, 10442, 11487, 12635, 13899, + 15289, 16818, 18500, 20350, 22385, 24623, 27086, 29794, 32767 }; - + #define CHARP(cp, i) ((signed char *)(cp+i)) #define SHORTP(cp, i) ((short *)(cp+i)) #define LONGP(cp, i) ((Py_Int32 *)(cp+i)) @@ -298,137 +298,137 @@ static PyObject * audioop_getsample(PyObject *self, PyObject *args) { - signed char *cp; - int len, size, val = 0; - int i; - - if ( !PyArg_ParseTuple(args, "s#ii:getsample", &cp, &len, &size, &i) ) - return 0; - if ( size != 1 && size != 2 && size != 4 ) { - PyErr_SetString(AudioopError, "Size should be 1, 2 or 4"); - return 0; - } - if ( i < 0 || i >= len/size ) { - PyErr_SetString(AudioopError, "Index out of range"); - return 0; - } - if ( size == 1 ) val = (int)*CHARP(cp, i); - else if ( size == 2 ) val = (int)*SHORTP(cp, i*2); - else if ( size == 4 ) val = (int)*LONGP(cp, i*4); - return PyLong_FromLong(val); + signed char *cp; + int len, size, val = 0; + int i; + + if ( !PyArg_ParseTuple(args, "s#ii:getsample", &cp, &len, &size, &i) ) + return 0; + if ( size != 1 && size != 2 && size != 4 ) { + PyErr_SetString(AudioopError, "Size should be 1, 2 or 4"); + return 0; + } + if ( i < 0 || i >= len/size ) { + PyErr_SetString(AudioopError, "Index out of range"); + return 0; + } + if ( size == 1 ) val = (int)*CHARP(cp, i); + else if ( size == 2 ) val = (int)*SHORTP(cp, i*2); + else if ( size == 4 ) val = (int)*LONGP(cp, i*4); + return PyLong_FromLong(val); } static PyObject * audioop_max(PyObject *self, PyObject *args) { - signed char *cp; - int len, size, val = 0; - int i; - int max = 0; - - if ( !PyArg_ParseTuple(args, "s#i:max", &cp, &len, &size) ) - return 0; - if ( size != 1 && size != 2 && size != 4 ) { - PyErr_SetString(AudioopError, "Size should be 1, 2 or 4"); - return 0; - } - for ( i=0; i max ) max = val; - } - return PyLong_FromLong(max); + signed char *cp; + int len, size, val = 0; + int i; + int max = 0; + + if ( !PyArg_ParseTuple(args, "s#i:max", &cp, &len, &size) ) + return 0; + if ( size != 1 && size != 2 && size != 4 ) { + PyErr_SetString(AudioopError, "Size should be 1, 2 or 4"); + return 0; + } + for ( i=0; i max ) max = val; + } + return PyLong_FromLong(max); } static PyObject * audioop_minmax(PyObject *self, PyObject *args) { - signed char *cp; - int len, size, val = 0; - int i; - int min = 0x7fffffff, max = -0x7fffffff; - - if (!PyArg_ParseTuple(args, "s#i:minmax", &cp, &len, &size)) - return NULL; - if (size != 1 && size != 2 && size != 4) { - PyErr_SetString(AudioopError, "Size should be 1, 2 or 4"); - return NULL; - } - for (i = 0; i < len; i += size) { - 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); - if (val > max) max = val; - if (val < min) min = val; - } - return Py_BuildValue("(ii)", min, max); + signed char *cp; + int len, size, val = 0; + int i; + int min = 0x7fffffff, max = -0x7fffffff; + + if (!PyArg_ParseTuple(args, "s#i:minmax", &cp, &len, &size)) + return NULL; + if (size != 1 && size != 2 && size != 4) { + PyErr_SetString(AudioopError, "Size should be 1, 2 or 4"); + return NULL; + } + for (i = 0; i < len; i += size) { + 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); + if (val > max) max = val; + if (val < min) min = val; + } + return Py_BuildValue("(ii)", min, max); } static PyObject * audioop_avg(PyObject *self, PyObject *args) { - signed char *cp; - int len, size, val = 0; - int i; - double avg = 0.0; - - if ( !PyArg_ParseTuple(args, "s#i:avg", &cp, &len, &size) ) - return 0; - if ( size != 1 && size != 2 && size != 4 ) { - PyErr_SetString(AudioopError, "Size should be 1, 2 or 4"); - return 0; - } - for ( i=0; i>= 1; - len2 >>= 1; - - if ( len1 < len2 ) { - PyErr_SetString(AudioopError, "First sample should be longer"); - return 0; - } - sum_ri_2 = _sum2(cp2, cp2, len2); - sum_aij_2 = _sum2(cp1, cp1, len2); - sum_aij_ri = _sum2(cp1, cp2, len2); - - result = (sum_ri_2*sum_aij_2 - sum_aij_ri*sum_aij_ri) / sum_aij_2; - - best_result = result; - best_j = 0; - j = 0; - - for ( j=1; j<=len1-len2; j++) { - aj_m1 = (double)cp1[j-1]; - aj_lm1 = (double)cp1[j+len2-1]; - - sum_aij_2 = sum_aij_2 + aj_lm1*aj_lm1 - aj_m1*aj_m1; - sum_aij_ri = _sum2(cp1+j, cp2, len2); - - result = (sum_ri_2*sum_aij_2 - sum_aij_ri*sum_aij_ri) - / sum_aij_2; - - if ( result < best_result ) { - best_result = result; - best_j = j; - } - + short *cp1, *cp2; + int len1, len2; + int j, best_j; + double aj_m1, aj_lm1; + double sum_ri_2, sum_aij_2, sum_aij_ri, result, best_result, factor; + + /* Passing a short** for an 's' argument is correct only + if the string contents is aligned for interpretation + as short[]. Due to the definition of PyBytesObject, + this is currently (Python 2.6) the case. */ + if ( !PyArg_ParseTuple(args, "s#s#:findfit", + (char**)&cp1, &len1, (char**)&cp2, &len2) ) + return 0; + if ( len1 & 1 || len2 & 1 ) { + PyErr_SetString(AudioopError, "Strings should be even-sized"); + return 0; + } + len1 >>= 1; + len2 >>= 1; + + if ( len1 < len2 ) { + PyErr_SetString(AudioopError, "First sample should be longer"); + return 0; + } + sum_ri_2 = _sum2(cp2, cp2, len2); + sum_aij_2 = _sum2(cp1, cp1, len2); + sum_aij_ri = _sum2(cp1, cp2, len2); + + result = (sum_ri_2*sum_aij_2 - sum_aij_ri*sum_aij_ri) / sum_aij_2; + + best_result = result; + best_j = 0; + j = 0; + + for ( j=1; j<=len1-len2; j++) { + aj_m1 = (double)cp1[j-1]; + aj_lm1 = (double)cp1[j+len2-1]; + + sum_aij_2 = sum_aij_2 + aj_lm1*aj_lm1 - aj_m1*aj_m1; + sum_aij_ri = _sum2(cp1+j, cp2, len2); + + result = (sum_ri_2*sum_aij_2 - sum_aij_ri*sum_aij_ri) + / sum_aij_2; + + if ( result < best_result ) { + best_result = result; + best_j = j; } - factor = _sum2(cp1+best_j, cp2, len2) / sum_ri_2; - - return Py_BuildValue("(if)", best_j, factor); + } + + factor = _sum2(cp1+best_j, cp2, len2) / sum_ri_2; + + return Py_BuildValue("(if)", best_j, factor); } /* @@ -529,28 +529,28 @@ static PyObject * audioop_findfactor(PyObject *self, PyObject *args) { - short *cp1, *cp2; - int len1, len2; - double sum_ri_2, sum_aij_ri, result; - - if ( !PyArg_ParseTuple(args, "s#s#:findfactor", - (char**)&cp1, &len1, (char**)&cp2, &len2) ) - return 0; - if ( len1 & 1 || len2 & 1 ) { - PyErr_SetString(AudioopError, "Strings should be even-sized"); - return 0; - } - if ( len1 != len2 ) { - PyErr_SetString(AudioopError, "Samples should be same size"); - return 0; - } - len2 >>= 1; - sum_ri_2 = _sum2(cp2, cp2, len2); - sum_aij_ri = _sum2(cp1, cp2, len2); + short *cp1, *cp2; + int len1, len2; + double sum_ri_2, sum_aij_ri, result; + + if ( !PyArg_ParseTuple(args, "s#s#:findfactor", + (char**)&cp1, &len1, (char**)&cp2, &len2) ) + return 0; + if ( len1 & 1 || len2 & 1 ) { + PyErr_SetString(AudioopError, "Strings should be even-sized"); + return 0; + } + if ( len1 != len2 ) { + PyErr_SetString(AudioopError, "Samples should be same size"); + return 0; + } + len2 >>= 1; + sum_ri_2 = _sum2(cp2, cp2, len2); + sum_aij_ri = _sum2(cp1, cp2, len2); - result = sum_aij_ri / sum_ri_2; + result = sum_aij_ri / sum_ri_2; - return PyFloat_FromDouble(result); + return PyFloat_FromDouble(result); } /* @@ -560,1114 +560,1114 @@ static PyObject * audioop_findmax(PyObject *self, PyObject *args) { - short *cp1; - int len1, len2; - int j, best_j; - double aj_m1, aj_lm1; - double result, best_result; - - if ( !PyArg_ParseTuple(args, "s#i:findmax", - (char**)&cp1, &len1, &len2) ) - return 0; - if ( len1 & 1 ) { - PyErr_SetString(AudioopError, "Strings should be even-sized"); - return 0; + short *cp1; + int len1, len2; + int j, best_j; + double aj_m1, aj_lm1; + double result, best_result; + + if ( !PyArg_ParseTuple(args, "s#i:findmax", + (char**)&cp1, &len1, &len2) ) + return 0; + if ( len1 & 1 ) { + PyErr_SetString(AudioopError, "Strings should be even-sized"); + return 0; + } + len1 >>= 1; + + if ( len2 < 0 || len1 < len2 ) { + PyErr_SetString(AudioopError, "Input sample should be longer"); + return 0; + } + + result = _sum2(cp1, cp1, len2); + + best_result = result; + best_j = 0; + j = 0; + + for ( j=1; j<=len1-len2; j++) { + aj_m1 = (double)cp1[j-1]; + aj_lm1 = (double)cp1[j+len2-1]; + + result = result + aj_lm1*aj_lm1 - aj_m1*aj_m1; + + if ( result > best_result ) { + best_result = result; + best_j = j; } - len1 >>= 1; - - if ( len2 < 0 || len1 < len2 ) { - PyErr_SetString(AudioopError, "Input sample should be longer"); - return 0; - } - - result = _sum2(cp1, cp1, len2); - best_result = result; - best_j = 0; - j = 0; - - for ( j=1; j<=len1-len2; j++) { - aj_m1 = (double)cp1[j-1]; - aj_lm1 = (double)cp1[j+len2-1]; - - result = result + aj_lm1*aj_lm1 - aj_m1*aj_m1; - - if ( result > best_result ) { - best_result = result; - best_j = j; - } - - } + } - return PyLong_FromLong(best_j); + return PyLong_FromLong(best_j); } static PyObject * audioop_avgpp(PyObject *self, PyObject *args) { - signed char *cp; - int len, size, val = 0, prevval = 0, prevextremevalid = 0, - prevextreme = 0; - int i; - double avg = 0.0; - int diff, prevdiff, extremediff, nextreme = 0; - - if ( !PyArg_ParseTuple(args, "s#i:avgpp", &cp, &len, &size) ) - return 0; - if ( size != 1 && size != 2 && size != 4 ) { - PyErr_SetString(AudioopError, "Size should be 1, 2 or 4"); - return 0; - } - /* Compute first delta value ahead. Also automatically makes us - ** skip the first extreme value - */ - if ( size == 1 ) prevval = (int)*CHARP(cp, 0); - else if ( size == 2 ) prevval = (int)*SHORTP(cp, 0); - else if ( size == 4 ) prevval = (int)*LONGP(cp, 0); - if ( size == 1 ) val = (int)*CHARP(cp, size); - else if ( size == 2 ) val = (int)*SHORTP(cp, size); - else if ( size == 4 ) val = (int)*LONGP(cp, size); - prevdiff = val - prevval; - - for ( i=size; i max ) - max = extremediff; - } - prevextremevalid = 1; - prevextreme = prevval; - } - prevval = val; - if ( diff != 0 ) - prevdiff = diff; - } - return PyLong_FromLong(max); + signed char *cp; + int len, size, val = 0, prevval = 0, prevextremevalid = 0, + prevextreme = 0; + int i; + int max = 0; + int diff, prevdiff, extremediff; + + if ( !PyArg_ParseTuple(args, "s#i:maxpp", &cp, &len, &size) ) + return 0; + if ( size != 1 && size != 2 && size != 4 ) { + PyErr_SetString(AudioopError, "Size should be 1, 2 or 4"); + return 0; + } + /* Compute first delta value ahead. Also automatically makes us + ** skip the first extreme value + */ + if ( size == 1 ) prevval = (int)*CHARP(cp, 0); + else if ( size == 2 ) prevval = (int)*SHORTP(cp, 0); + else if ( size == 4 ) prevval = (int)*LONGP(cp, 0); + if ( size == 1 ) val = (int)*CHARP(cp, size); + else if ( size == 2 ) val = (int)*SHORTP(cp, size); + else if ( size == 4 ) val = (int)*LONGP(cp, size); + prevdiff = val - prevval; + + for ( i=size; i max ) + max = extremediff; + } + prevextremevalid = 1; + prevextreme = prevval; + } + prevval = val; + if ( diff != 0 ) + prevdiff = diff; + } + return PyLong_FromLong(max); } static PyObject * audioop_cross(PyObject *self, PyObject *args) { - signed char *cp; - int len, size, val = 0; - int i; - int prevval, ncross; - - if ( !PyArg_ParseTuple(args, "s#i:cross", &cp, &len, &size) ) - return 0; - if ( size != 1 && size != 2 && size != 4 ) { - PyErr_SetString(AudioopError, "Size should be 1, 2 or 4"); - return 0; - } - ncross = -1; - prevval = 17; /* Anything <> 0,1 */ - for ( i=0; i> 7; - else if ( size == 2 ) val = ((int)*SHORTP(cp, i)) >> 15; - else if ( size == 4 ) val = ((int)*LONGP(cp, i)) >> 31; - val = val & 1; - if ( val != prevval ) ncross++; - prevval = val; - } - return PyLong_FromLong(ncross); + signed char *cp; + int len, size, val = 0; + int i; + int prevval, ncross; + + if ( !PyArg_ParseTuple(args, "s#i:cross", &cp, &len, &size) ) + return 0; + if ( size != 1 && size != 2 && size != 4 ) { + PyErr_SetString(AudioopError, "Size should be 1, 2 or 4"); + return 0; + } + ncross = -1; + prevval = 17; /* Anything <> 0,1 */ + for ( i=0; i> 7; + else if ( size == 2 ) val = ((int)*SHORTP(cp, i)) >> 15; + else if ( size == 4 ) val = ((int)*LONGP(cp, i)) >> 31; + val = val & 1; + if ( val != prevval ) ncross++; + prevval = val; + } + return PyLong_FromLong(ncross); } static PyObject * audioop_mul(PyObject *self, PyObject *args) { - signed char *cp, *ncp; - int len, size, val = 0; - double factor, fval, maxval; - PyObject *rv; - int i; - - if ( !PyArg_ParseTuple(args, "s#id:mul", &cp, &len, &size, &factor ) ) - return 0; - - if ( size == 1 ) maxval = (double) 0x7f; - else if ( size == 2 ) maxval = (double) 0x7fff; - else if ( size == 4 ) maxval = (double) 0x7fffffff; - else { - PyErr_SetString(AudioopError, "Size should be 1, 2 or 4"); - return 0; - } - - rv = PyBytes_FromStringAndSize(NULL, len); - if ( rv == 0 ) - return 0; - ncp = (signed char *)PyBytes_AsString(rv); - - - for ( i=0; i < len; i += size ) { - 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; - if ( fval > maxval ) fval = maxval; - else if ( fval < -maxval ) fval = -maxval; - val = (int)fval; - 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; - } - return rv; + signed char *cp, *ncp; + int len, size, val = 0; + double factor, fval, maxval; + PyObject *rv; + int i; + + if ( !PyArg_ParseTuple(args, "s#id:mul", &cp, &len, &size, &factor ) ) + return 0; + + if ( size == 1 ) maxval = (double) 0x7f; + else if ( size == 2 ) maxval = (double) 0x7fff; + else if ( size == 4 ) maxval = (double) 0x7fffffff; + else { + PyErr_SetString(AudioopError, "Size should be 1, 2 or 4"); + return 0; + } + + rv = PyBytes_FromStringAndSize(NULL, len); + if ( rv == 0 ) + return 0; + ncp = (signed char *)PyBytes_AsString(rv); + + + for ( i=0; i < len; i += size ) { + 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; + if ( fval > maxval ) fval = maxval; + else if ( fval < -maxval ) fval = -maxval; + val = (int)fval; + 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; + } + return rv; } static PyObject * audioop_tomono(PyObject *self, PyObject *args) { - Py_buffer pcp; - signed char *cp, *ncp; - int len, size, val1 = 0, val2 = 0; - double fac1, fac2, fval, maxval; - PyObject *rv; - int i; - - if ( !PyArg_ParseTuple(args, "s*idd:tomono", - &pcp, &size, &fac1, &fac2 ) ) - return 0; - cp = pcp.buf; - len = pcp.len; - - if ( size == 1 ) maxval = (double) 0x7f; - else if ( size == 2 ) maxval = (double) 0x7fff; - else if ( size == 4 ) maxval = (double) 0x7fffffff; - else { - PyBuffer_Release(&pcp); - PyErr_SetString(AudioopError, "Size should be 1, 2 or 4"); - return 0; - } - - rv = PyBytes_FromStringAndSize(NULL, len/2); - if ( rv == 0 ) - return 0; - ncp = (signed char *)PyBytes_AsString(rv); - - - for ( i=0; i < len; i += size*2 ) { - if ( size == 1 ) val1 = (int)*CHARP(cp, i); - else if ( size == 2 ) val1 = (int)*SHORTP(cp, i); - else if ( size == 4 ) val1 = (int)*LONGP(cp, i); - 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; - if ( fval > maxval ) fval = maxval; - else if ( fval < -maxval ) fval = -maxval; - val1 = (int)fval; - 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; - } - PyBuffer_Release(&pcp); - return rv; + Py_buffer pcp; + signed char *cp, *ncp; + int len, size, val1 = 0, val2 = 0; + double fac1, fac2, fval, maxval; + PyObject *rv; + int i; + + if ( !PyArg_ParseTuple(args, "s*idd:tomono", + &pcp, &size, &fac1, &fac2 ) ) + return 0; + cp = pcp.buf; + len = pcp.len; + + if ( size == 1 ) maxval = (double) 0x7f; + else if ( size == 2 ) maxval = (double) 0x7fff; + else if ( size == 4 ) maxval = (double) 0x7fffffff; + else { + PyBuffer_Release(&pcp); + PyErr_SetString(AudioopError, "Size should be 1, 2 or 4"); + return 0; + } + + rv = PyBytes_FromStringAndSize(NULL, len/2); + if ( rv == 0 ) + return 0; + ncp = (signed char *)PyBytes_AsString(rv); + + + for ( i=0; i < len; i += size*2 ) { + if ( size == 1 ) val1 = (int)*CHARP(cp, i); + else if ( size == 2 ) val1 = (int)*SHORTP(cp, i); + else if ( size == 4 ) val1 = (int)*LONGP(cp, i); + 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; + if ( fval > maxval ) fval = maxval; + else if ( fval < -maxval ) fval = -maxval; + val1 = (int)fval; + 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; + } + PyBuffer_Release(&pcp); + return rv; } static PyObject * audioop_tostereo(PyObject *self, PyObject *args) { - signed char *cp, *ncp; - int len, new_len, size, val1, val2, val = 0; - double fac1, fac2, fval, maxval; - PyObject *rv; - int i; - - if ( !PyArg_ParseTuple(args, "s#idd:tostereo", - &cp, &len, &size, &fac1, &fac2 ) ) - return 0; - - if ( size == 1 ) maxval = (double) 0x7f; - else if ( size == 2 ) maxval = (double) 0x7fff; - else if ( size == 4 ) maxval = (double) 0x7fffffff; - else { - PyErr_SetString(AudioopError, "Size should be 1, 2 or 4"); - return 0; - } - - new_len = len*2; - if (new_len < 0) { - PyErr_SetString(PyExc_MemoryError, - "not enough memory for output buffer"); - return 0; - } + signed char *cp, *ncp; + int len, new_len, size, val1, val2, val = 0; + double fac1, fac2, fval, maxval; + PyObject *rv; + int i; + + if ( !PyArg_ParseTuple(args, "s#idd:tostereo", + &cp, &len, &size, &fac1, &fac2 ) ) + return 0; + + if ( size == 1 ) maxval = (double) 0x7f; + else if ( size == 2 ) maxval = (double) 0x7fff; + else if ( size == 4 ) maxval = (double) 0x7fffffff; + else { + PyErr_SetString(AudioopError, "Size should be 1, 2 or 4"); + return 0; + } + + new_len = len*2; + if (new_len < 0) { + PyErr_SetString(PyExc_MemoryError, + "not enough memory for output buffer"); + return 0; + } + + rv = PyBytes_FromStringAndSize(NULL, new_len); + if ( rv == 0 ) + return 0; + ncp = (signed char *)PyBytes_AsString(rv); - rv = PyBytes_FromStringAndSize(NULL, new_len); - if ( rv == 0 ) - return 0; - ncp = (signed char *)PyBytes_AsString(rv); - - - for ( i=0; i < len; i += size ) { - 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*fac1; - if ( fval > maxval ) fval = maxval; - else if ( fval < -maxval ) fval = -maxval; - val1 = (int)fval; - - fval = (double)val*fac2; - if ( fval > maxval ) fval = maxval; - else if ( fval < -maxval ) fval = -maxval; - val2 = (int)fval; - - 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; - - if ( size == 1 ) *CHARP(ncp, i*2+1) = (signed char)val2; - else if ( size == 2 ) *SHORTP(ncp, i*2+2) = (short)val2; - else if ( size == 4 ) *LONGP(ncp, i*2+4) = (Py_Int32)val2; - } - return rv; + + for ( i=0; i < len; i += size ) { + 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*fac1; + if ( fval > maxval ) fval = maxval; + else if ( fval < -maxval ) fval = -maxval; + val1 = (int)fval; + + fval = (double)val*fac2; + if ( fval > maxval ) fval = maxval; + else if ( fval < -maxval ) fval = -maxval; + val2 = (int)fval; + + 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; + + if ( size == 1 ) *CHARP(ncp, i*2+1) = (signed char)val2; + else if ( size == 2 ) *SHORTP(ncp, i*2+2) = (short)val2; + else if ( size == 4 ) *LONGP(ncp, i*2+4) = (Py_Int32)val2; + } + return rv; } static PyObject * audioop_add(PyObject *self, PyObject *args) { - signed char *cp1, *cp2, *ncp; - int len1, len2, size, val1 = 0, val2 = 0, maxval, newval; - PyObject *rv; - int i; - - if ( !PyArg_ParseTuple(args, "s#s#i:add", - &cp1, &len1, &cp2, &len2, &size ) ) - return 0; - - if ( len1 != len2 ) { - PyErr_SetString(AudioopError, "Lengths should be the same"); - return 0; - } - - if ( size == 1 ) maxval = 0x7f; - else if ( size == 2 ) maxval = 0x7fff; - else if ( size == 4 ) maxval = 0x7fffffff; - else { - PyErr_SetString(AudioopError, "Size should be 1, 2 or 4"); - return 0; - } - - rv = PyBytes_FromStringAndSize(NULL, len1); - if ( rv == 0 ) - return 0; - ncp = (signed char *)PyBytes_AsString(rv); - - for ( i=0; i < len1; i += size ) { - if ( size == 1 ) val1 = (int)*CHARP(cp1, i); - else if ( size == 2 ) val1 = (int)*SHORTP(cp1, i); - else if ( size == 4 ) val1 = (int)*LONGP(cp1, i); - - if ( size == 1 ) val2 = (int)*CHARP(cp2, i); - else if ( size == 2 ) val2 = (int)*SHORTP(cp2, i); - else if ( size == 4 ) val2 = (int)*LONGP(cp2, i); - - newval = val1 + val2; - /* truncate in case of overflow */ - if (newval > maxval) newval = maxval; - else if (newval < -maxval) newval = -maxval; - else if (size == 4 && (newval^val1) < 0 && (newval^val2) < 0) - newval = val1 > 0 ? maxval : - maxval; - - if ( size == 1 ) *CHARP(ncp, i) = (signed char)newval; - else if ( size == 2 ) *SHORTP(ncp, i) = (short)newval; - else if ( size == 4 ) *LONGP(ncp, i) = (Py_Int32)newval; - } - return rv; + signed char *cp1, *cp2, *ncp; + int len1, len2, size, val1 = 0, val2 = 0, maxval, newval; + PyObject *rv; + int i; + + if ( !PyArg_ParseTuple(args, "s#s#i:add", + &cp1, &len1, &cp2, &len2, &size ) ) + return 0; + + if ( len1 != len2 ) { + PyErr_SetString(AudioopError, "Lengths should be the same"); + return 0; + } + + if ( size == 1 ) maxval = 0x7f; + else if ( size == 2 ) maxval = 0x7fff; + else if ( size == 4 ) maxval = 0x7fffffff; + else { + PyErr_SetString(AudioopError, "Size should be 1, 2 or 4"); + return 0; + } + + rv = PyBytes_FromStringAndSize(NULL, len1); + if ( rv == 0 ) + return 0; + ncp = (signed char *)PyBytes_AsString(rv); + + for ( i=0; i < len1; i += size ) { + if ( size == 1 ) val1 = (int)*CHARP(cp1, i); + else if ( size == 2 ) val1 = (int)*SHORTP(cp1, i); + else if ( size == 4 ) val1 = (int)*LONGP(cp1, i); + + if ( size == 1 ) val2 = (int)*CHARP(cp2, i); + else if ( size == 2 ) val2 = (int)*SHORTP(cp2, i); + else if ( size == 4 ) val2 = (int)*LONGP(cp2, i); + + newval = val1 + val2; + /* truncate in case of overflow */ + if (newval > maxval) newval = maxval; + else if (newval < -maxval) newval = -maxval; + else if (size == 4 && (newval^val1) < 0 && (newval^val2) < 0) + newval = val1 > 0 ? maxval : - maxval; + + if ( size == 1 ) *CHARP(ncp, i) = (signed char)newval; + else if ( size == 2 ) *SHORTP(ncp, i) = (short)newval; + else if ( size == 4 ) *LONGP(ncp, i) = (Py_Int32)newval; + } + return rv; } static PyObject * audioop_bias(PyObject *self, PyObject *args) { - signed char *cp, *ncp; - int len, size, val = 0; - PyObject *rv; - int i; - int bias; - - if ( !PyArg_ParseTuple(args, "s#ii:bias", - &cp, &len, &size , &bias) ) - return 0; - - if ( size != 1 && size != 2 && size != 4) { - PyErr_SetString(AudioopError, "Size should be 1, 2 or 4"); - return 0; - } - - rv = PyBytes_FromStringAndSize(NULL, len); - if ( rv == 0 ) - return 0; - ncp = (signed char *)PyBytes_AsString(rv); - - - for ( i=0; i < len; i += size ) { - 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); - - if ( size == 1 ) *CHARP(ncp, i) = (signed char)(val+bias); - else if ( size == 2 ) *SHORTP(ncp, i) = (short)(val+bias); - else if ( size == 4 ) *LONGP(ncp, i) = (Py_Int32)(val+bias); - } - return rv; + signed char *cp, *ncp; + int len, size, val = 0; + PyObject *rv; + int i; + int bias; + + if ( !PyArg_ParseTuple(args, "s#ii:bias", + &cp, &len, &size , &bias) ) + return 0; + + if ( size != 1 && size != 2 && size != 4) { + PyErr_SetString(AudioopError, "Size should be 1, 2 or 4"); + return 0; + } + + rv = PyBytes_FromStringAndSize(NULL, len); + if ( rv == 0 ) + return 0; + ncp = (signed char *)PyBytes_AsString(rv); + + + for ( i=0; i < len; i += size ) { + 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); + + if ( size == 1 ) *CHARP(ncp, i) = (signed char)(val+bias); + else if ( size == 2 ) *SHORTP(ncp, i) = (short)(val+bias); + else if ( size == 4 ) *LONGP(ncp, i) = (Py_Int32)(val+bias); + } + return rv; } static PyObject * audioop_reverse(PyObject *self, PyObject *args) { - signed char *cp; - unsigned char *ncp; - int len, size, val = 0; - PyObject *rv; - int i, j; - - if ( !PyArg_ParseTuple(args, "s#i:reverse", - &cp, &len, &size) ) - return 0; - - if ( size != 1 && size != 2 && size != 4 ) { - PyErr_SetString(AudioopError, "Size should be 1, 2 or 4"); - return 0; - } - - rv = PyBytes_FromStringAndSize(NULL, len); - if ( rv == 0 ) - return 0; - ncp = (unsigned char *)PyBytes_AsString(rv); - - for ( i=0; i < len; i += size ) { - if ( size == 1 ) val = ((int)*CHARP(cp, i)) << 8; - else if ( size == 2 ) val = (int)*SHORTP(cp, i); - else if ( size == 4 ) val = ((int)*LONGP(cp, i)) >> 16; - - j = len - i - size; - - if ( size == 1 ) *CHARP(ncp, j) = (signed char)(val >> 8); - else if ( size == 2 ) *SHORTP(ncp, j) = (short)(val); - else if ( size == 4 ) *LONGP(ncp, j) = (Py_Int32)(val<<16); - } - return rv; + signed char *cp; + unsigned char *ncp; + int len, size, val = 0; + PyObject *rv; + int i, j; + + if ( !PyArg_ParseTuple(args, "s#i:reverse", + &cp, &len, &size) ) + return 0; + + if ( size != 1 && size != 2 && size != 4 ) { + PyErr_SetString(AudioopError, "Size should be 1, 2 or 4"); + return 0; + } + + rv = PyBytes_FromStringAndSize(NULL, len); + if ( rv == 0 ) + return 0; + ncp = (unsigned char *)PyBytes_AsString(rv); + + for ( i=0; i < len; i += size ) { + if ( size == 1 ) val = ((int)*CHARP(cp, i)) << 8; + else if ( size == 2 ) val = (int)*SHORTP(cp, i); + else if ( size == 4 ) val = ((int)*LONGP(cp, i)) >> 16; + + j = len - i - size; + + if ( size == 1 ) *CHARP(ncp, j) = (signed char)(val >> 8); + else if ( size == 2 ) *SHORTP(ncp, j) = (short)(val); + else if ( size == 4 ) *LONGP(ncp, j) = (Py_Int32)(val<<16); + } + return rv; } static PyObject * audioop_lin2lin(PyObject *self, PyObject *args) { - signed char *cp; - unsigned char *ncp; - int len, new_len, size, size2, val = 0; - PyObject *rv; - int i, j; - - if ( !PyArg_ParseTuple(args, "s#ii:lin2lin", - &cp, &len, &size, &size2) ) - return 0; - - if ( (size != 1 && size != 2 && size != 4) || - (size2 != 1 && size2 != 2 && size2 != 4)) { - PyErr_SetString(AudioopError, "Size should be 1, 2 or 4"); - return 0; - } - - new_len = (len/size)*size2; - if (new_len < 0) { - PyErr_SetString(PyExc_MemoryError, - "not enough memory for output buffer"); - return 0; - } - rv = PyBytes_FromStringAndSize(NULL, new_len); - if ( rv == 0 ) - return 0; - ncp = (unsigned char *)PyBytes_AsString(rv); - - for ( i=0, j=0; i < len; i += size, j += size2 ) { - if ( size == 1 ) val = ((int)*CHARP(cp, i)) << 8; - else if ( size == 2 ) val = (int)*SHORTP(cp, i); - else if ( size == 4 ) val = ((int)*LONGP(cp, i)) >> 16; - - if ( size2 == 1 ) *CHARP(ncp, j) = (signed char)(val >> 8); - else if ( size2 == 2 ) *SHORTP(ncp, j) = (short)(val); - else if ( size2 == 4 ) *LONGP(ncp, j) = (Py_Int32)(val<<16); - } - return rv; + signed char *cp; + unsigned char *ncp; + int len, new_len, size, size2, val = 0; + PyObject *rv; + int i, j; + + if ( !PyArg_ParseTuple(args, "s#ii:lin2lin", + &cp, &len, &size, &size2) ) + return 0; + + if ( (size != 1 && size != 2 && size != 4) || + (size2 != 1 && size2 != 2 && size2 != 4)) { + PyErr_SetString(AudioopError, "Size should be 1, 2 or 4"); + return 0; + } + + new_len = (len/size)*size2; + if (new_len < 0) { + PyErr_SetString(PyExc_MemoryError, + "not enough memory for output buffer"); + return 0; + } + rv = PyBytes_FromStringAndSize(NULL, new_len); + if ( rv == 0 ) + return 0; + ncp = (unsigned char *)PyBytes_AsString(rv); + + for ( i=0, j=0; i < len; i += size, j += size2 ) { + if ( size == 1 ) val = ((int)*CHARP(cp, i)) << 8; + else if ( size == 2 ) val = (int)*SHORTP(cp, i); + else if ( size == 4 ) val = ((int)*LONGP(cp, i)) >> 16; + + if ( size2 == 1 ) *CHARP(ncp, j) = (signed char)(val >> 8); + else if ( size2 == 2 ) *SHORTP(ncp, j) = (short)(val); + else if ( size2 == 4 ) *LONGP(ncp, j) = (Py_Int32)(val<<16); + } + return rv; } static int gcd(int a, int b) { - while (b > 0) { - int tmp = a % b; - a = b; - b = tmp; - } - return a; + while (b > 0) { + int tmp = a % b; + a = b; + b = tmp; + } + return a; } static PyObject * audioop_ratecv(PyObject *self, PyObject *args) { - char *cp, *ncp; - int len, size, nchannels, inrate, outrate, weightA, weightB; - int chan, d, *prev_i, *cur_i, cur_o; - PyObject *state, *samps, *str, *rv = NULL; - int bytes_per_frame; - size_t alloc_size; - - weightA = 1; - weightB = 0; - if (!PyArg_ParseTuple(args, "s#iiiiO|ii:ratecv", &cp, &len, &size, - &nchannels, &inrate, &outrate, &state, - &weightA, &weightB)) - return NULL; - if (size != 1 && size != 2 && size != 4) { - PyErr_SetString(AudioopError, "Size should be 1, 2 or 4"); - return NULL; - } - if (nchannels < 1) { - PyErr_SetString(AudioopError, "# of channels should be >= 1"); - return NULL; - } - bytes_per_frame = size * nchannels; - if (bytes_per_frame / nchannels != size) { - /* This overflow test is rigorously correct because - both multiplicands are >= 1. Use the argument names - from the docs for the error msg. */ - PyErr_SetString(PyExc_OverflowError, - "width * nchannels too big for a C int"); - return NULL; - } - if (weightA < 1 || weightB < 0) { - PyErr_SetString(AudioopError, - "weightA should be >= 1, weightB should be >= 0"); - return NULL; - } - if (len % bytes_per_frame != 0) { - PyErr_SetString(AudioopError, "not a whole number of frames"); - return NULL; - } - if (inrate <= 0 || outrate <= 0) { - PyErr_SetString(AudioopError, "sampling rate not > 0"); - return NULL; - } - /* divide inrate and outrate by their greatest common divisor */ - d = gcd(inrate, outrate); - inrate /= d; - outrate /= d; - - alloc_size = sizeof(int) * (unsigned)nchannels; - if (alloc_size < (unsigned)nchannels) { - PyErr_SetString(PyExc_MemoryError, - "not enough memory for output buffer"); - return 0; - } - prev_i = (int *) malloc(alloc_size); - cur_i = (int *) malloc(alloc_size); - if (prev_i == NULL || cur_i == NULL) { - (void) PyErr_NoMemory(); + char *cp, *ncp; + int len, size, nchannels, inrate, outrate, weightA, weightB; + int chan, d, *prev_i, *cur_i, cur_o; + PyObject *state, *samps, *str, *rv = NULL; + int bytes_per_frame; + size_t alloc_size; + + weightA = 1; + weightB = 0; + if (!PyArg_ParseTuple(args, "s#iiiiO|ii:ratecv", &cp, &len, &size, + &nchannels, &inrate, &outrate, &state, + &weightA, &weightB)) + return NULL; + if (size != 1 && size != 2 && size != 4) { + PyErr_SetString(AudioopError, "Size should be 1, 2 or 4"); + return NULL; + } + if (nchannels < 1) { + PyErr_SetString(AudioopError, "# of channels should be >= 1"); + return NULL; + } + bytes_per_frame = size * nchannels; + if (bytes_per_frame / nchannels != size) { + /* This overflow test is rigorously correct because + both multiplicands are >= 1. Use the argument names + from the docs for the error msg. */ + PyErr_SetString(PyExc_OverflowError, + "width * nchannels too big for a C int"); + return NULL; + } + if (weightA < 1 || weightB < 0) { + PyErr_SetString(AudioopError, + "weightA should be >= 1, weightB should be >= 0"); + return NULL; + } + if (len % bytes_per_frame != 0) { + PyErr_SetString(AudioopError, "not a whole number of frames"); + return NULL; + } + if (inrate <= 0 || outrate <= 0) { + PyErr_SetString(AudioopError, "sampling rate not > 0"); + return NULL; + } + /* divide inrate and outrate by their greatest common divisor */ + d = gcd(inrate, outrate); + inrate /= d; + outrate /= d; + + alloc_size = sizeof(int) * (unsigned)nchannels; + if (alloc_size < (unsigned)nchannels) { + PyErr_SetString(PyExc_MemoryError, + "not enough memory for output buffer"); + return 0; + } + prev_i = (int *) malloc(alloc_size); + cur_i = (int *) malloc(alloc_size); + if (prev_i == NULL || cur_i == NULL) { + (void) PyErr_NoMemory(); + goto exit; + } + + len /= bytes_per_frame; /* # of frames */ + + if (state == Py_None) { + d = -outrate; + for (chan = 0; chan < nchannels; chan++) + prev_i[chan] = cur_i[chan] = 0; + } + else { + if (!PyArg_ParseTuple(state, + "iO!;audioop.ratecv: illegal state argument", + &d, &PyTuple_Type, &samps)) + goto exit; + if (PyTuple_Size(samps) != nchannels) { + PyErr_SetString(AudioopError, + "illegal state argument"); + goto exit; + } + for (chan = 0; chan < nchannels; chan++) { + if (!PyArg_ParseTuple(PyTuple_GetItem(samps, chan), + "ii:ratecv", &prev_i[chan], + &cur_i[chan])) goto exit; } + } - len /= bytes_per_frame; /* # of frames */ + /* str <- Space for the output buffer. */ + { + /* There are len input frames, so we need (mathematically) + ceiling(len*outrate/inrate) output frames, and each frame + requires bytes_per_frame bytes. Computing this + without spurious overflow is the challenge; we can + settle for a reasonable upper bound, though. */ + int ceiling; /* the number of output frames */ + int nbytes; /* the number of output bytes needed */ + int q = len / inrate; + /* Now len = q * inrate + r exactly (with r = len % inrate), + and this is less than q * inrate + inrate = (q+1)*inrate. + So a reasonable upper bound on len*outrate/inrate is + ((q+1)*inrate)*outrate/inrate = + (q+1)*outrate. + */ + ceiling = (q+1) * outrate; + nbytes = ceiling * bytes_per_frame; + /* See whether anything overflowed; if not, get the space. */ + if (q+1 < 0 || + ceiling / outrate != q+1 || + nbytes / bytes_per_frame != ceiling) + str = NULL; + else + str = PyBytes_FromStringAndSize(NULL, nbytes); - if (state == Py_None) { - d = -outrate; + if (str == NULL) { + PyErr_SetString(PyExc_MemoryError, + "not enough memory for output buffer"); + goto exit; + } + } + ncp = PyBytes_AsString(str); + + for (;;) { + while (d < 0) { + if (len == 0) { + samps = PyTuple_New(nchannels); + if (samps == NULL) + goto exit; for (chan = 0; chan < nchannels; chan++) - prev_i[chan] = cur_i[chan] = 0; - } - else { - if (!PyArg_ParseTuple(state, - "iO!;audioop.ratecv: illegal state argument", - &d, &PyTuple_Type, &samps)) - goto exit; - if (PyTuple_Size(samps) != nchannels) { - PyErr_SetString(AudioopError, - "illegal state argument"); - goto exit; - } - for (chan = 0; chan < nchannels; chan++) { - if (!PyArg_ParseTuple(PyTuple_GetItem(samps, chan), - "ii:ratecv", &prev_i[chan], - &cur_i[chan])) - goto exit; - } - } - - /* str <- Space for the output buffer. */ - { - /* There are len input frames, so we need (mathematically) - ceiling(len*outrate/inrate) output frames, and each frame - requires bytes_per_frame bytes. Computing this - without spurious overflow is the challenge; we can - settle for a reasonable upper bound, though. */ - int ceiling; /* the number of output frames */ - int nbytes; /* the number of output bytes needed */ - int q = len / inrate; - /* Now len = q * inrate + r exactly (with r = len % inrate), - and this is less than q * inrate + inrate = (q+1)*inrate. - So a reasonable upper bound on len*outrate/inrate is - ((q+1)*inrate)*outrate/inrate = - (q+1)*outrate. - */ - ceiling = (q+1) * outrate; - nbytes = ceiling * bytes_per_frame; - /* See whether anything overflowed; if not, get the space. */ - if (q+1 < 0 || - ceiling / outrate != q+1 || - nbytes / bytes_per_frame != ceiling) - str = NULL; - else - str = PyBytes_FromStringAndSize(NULL, nbytes); - - if (str == NULL) { - PyErr_SetString(PyExc_MemoryError, - "not enough memory for output buffer"); - goto exit; - } - } - ncp = PyBytes_AsString(str); - - for (;;) { - while (d < 0) { - if (len == 0) { - samps = PyTuple_New(nchannels); - if (samps == NULL) - goto exit; - for (chan = 0; chan < nchannels; chan++) - PyTuple_SetItem(samps, chan, - Py_BuildValue("(ii)", - prev_i[chan], - cur_i[chan])); - if (PyErr_Occurred()) - goto exit; - /* We have checked before that the length - * of the string fits into int. */ - len = (int)(ncp - PyBytes_AsString(str)); - rv = PyBytes_FromStringAndSize - (PyBytes_AsString(str), len); - Py_DECREF(str); - str = rv; - if (str == NULL) - goto exit; - rv = Py_BuildValue("(O(iO))", str, d, samps); - Py_DECREF(samps); - Py_DECREF(str); - goto exit; /* return rv */ - } - for (chan = 0; chan < nchannels; chan++) { - prev_i[chan] = cur_i[chan]; - if (size == 1) - cur_i[chan] = ((int)*CHARP(cp, 0)) << 8; - else if (size == 2) - cur_i[chan] = (int)*SHORTP(cp, 0); - else if (size == 4) - cur_i[chan] = ((int)*LONGP(cp, 0)) >> 16; - cp += size; - /* implements a simple digital filter */ - cur_i[chan] = - (weightA * cur_i[chan] + - weightB * prev_i[chan]) / - (weightA + weightB); - } - len--; - d += outrate; - } - while (d >= 0) { - for (chan = 0; chan < nchannels; chan++) { - cur_o = (prev_i[chan] * d + - cur_i[chan] * (outrate - d)) / - outrate; - if (size == 1) - *CHARP(ncp, 0) = (signed char)(cur_o >> 8); - else if (size == 2) - *SHORTP(ncp, 0) = (short)(cur_o); - else if (size == 4) - *LONGP(ncp, 0) = (Py_Int32)(cur_o<<16); - ncp += size; - } - d -= inrate; - } + PyTuple_SetItem(samps, chan, + Py_BuildValue("(ii)", + prev_i[chan], + cur_i[chan])); + if (PyErr_Occurred()) + goto exit; + /* We have checked before that the length + * of the string fits into int. */ + len = (int)(ncp - PyBytes_AsString(str)); + rv = PyBytes_FromStringAndSize + (PyBytes_AsString(str), len); + Py_DECREF(str); + str = rv; + if (str == NULL) + goto exit; + rv = Py_BuildValue("(O(iO))", str, d, samps); + Py_DECREF(samps); + Py_DECREF(str); + goto exit; /* return rv */ + } + for (chan = 0; chan < nchannels; chan++) { + prev_i[chan] = cur_i[chan]; + if (size == 1) + cur_i[chan] = ((int)*CHARP(cp, 0)) << 8; + else if (size == 2) + cur_i[chan] = (int)*SHORTP(cp, 0); + else if (size == 4) + cur_i[chan] = ((int)*LONGP(cp, 0)) >> 16; + cp += size; + /* implements a simple digital filter */ + cur_i[chan] = + (weightA * cur_i[chan] + + weightB * prev_i[chan]) / + (weightA + weightB); + } + len--; + d += outrate; + } + while (d >= 0) { + for (chan = 0; chan < nchannels; chan++) { + cur_o = (prev_i[chan] * d + + cur_i[chan] * (outrate - d)) / + outrate; + if (size == 1) + *CHARP(ncp, 0) = (signed char)(cur_o >> 8); + else if (size == 2) + *SHORTP(ncp, 0) = (short)(cur_o); + else if (size == 4) + *LONGP(ncp, 0) = (Py_Int32)(cur_o<<16); + ncp += size; + } + d -= inrate; } + } exit: - if (prev_i != NULL) - free(prev_i); - if (cur_i != NULL) - free(cur_i); - return rv; + if (prev_i != NULL) + free(prev_i); + if (cur_i != NULL) + free(cur_i); + return rv; } static PyObject * audioop_lin2ulaw(PyObject *self, PyObject *args) { - signed char *cp; - unsigned char *ncp; - int len, size, val = 0; - PyObject *rv; - int i; - - if ( !PyArg_ParseTuple(args, "s#i:lin2ulaw", - &cp, &len, &size) ) - return 0 ; - - if ( size != 1 && size != 2 && size != 4) { - PyErr_SetString(AudioopError, "Size should be 1, 2 or 4"); - return 0; - } - - rv = PyBytes_FromStringAndSize(NULL, len/size); - if ( rv == 0 ) - return 0; - ncp = (unsigned char *)PyBytes_AsString(rv); - - for ( i=0; i < len; i += size ) { - if ( size == 1 ) val = ((int)*CHARP(cp, i)) << 8; - else if ( size == 2 ) val = (int)*SHORTP(cp, i); - else if ( size == 4 ) val = ((int)*LONGP(cp, i)) >> 16; - - *ncp++ = st_14linear2ulaw(val); - } - return rv; + signed char *cp; + unsigned char *ncp; + int len, size, val = 0; + PyObject *rv; + int i; + + if ( !PyArg_ParseTuple(args, "s#i:lin2ulaw", + &cp, &len, &size) ) + return 0 ; + + if ( size != 1 && size != 2 && size != 4) { + PyErr_SetString(AudioopError, "Size should be 1, 2 or 4"); + return 0; + } + + rv = PyBytes_FromStringAndSize(NULL, len/size); + if ( rv == 0 ) + return 0; + ncp = (unsigned char *)PyBytes_AsString(rv); + + for ( i=0; i < len; i += size ) { + if ( size == 1 ) val = ((int)*CHARP(cp, i)) << 8; + else if ( size == 2 ) val = (int)*SHORTP(cp, i); + else if ( size == 4 ) val = ((int)*LONGP(cp, i)) >> 16; + + *ncp++ = st_14linear2ulaw(val); + } + return rv; } static PyObject * audioop_ulaw2lin(PyObject *self, PyObject *args) { - unsigned char *cp; - unsigned char cval; - signed char *ncp; - int len, new_len, size, val; - PyObject *rv; - int i; - - if ( !PyArg_ParseTuple(args, "s#i:ulaw2lin", - &cp, &len, &size) ) - return 0; - - if ( size != 1 && size != 2 && size != 4) { - PyErr_SetString(AudioopError, "Size should be 1, 2 or 4"); - return 0; - } - - new_len = len*size; - if (new_len < 0) { - PyErr_SetString(PyExc_MemoryError, - "not enough memory for output buffer"); - return 0; - } - rv = PyBytes_FromStringAndSize(NULL, new_len); - if ( rv == 0 ) - return 0; - ncp = (signed char *)PyBytes_AsString(rv); - - for ( i=0; i < new_len; i += size ) { - cval = *cp++; - val = st_ulaw2linear16(cval); - - if ( size == 1 ) *CHARP(ncp, i) = (signed char)(val >> 8); - else if ( size == 2 ) *SHORTP(ncp, i) = (short)(val); - else if ( size == 4 ) *LONGP(ncp, i) = (Py_Int32)(val<<16); - } - return rv; + unsigned char *cp; + unsigned char cval; + signed char *ncp; + int len, new_len, size, val; + PyObject *rv; + int i; + + if ( !PyArg_ParseTuple(args, "s#i:ulaw2lin", + &cp, &len, &size) ) + return 0; + + if ( size != 1 && size != 2 && size != 4) { + PyErr_SetString(AudioopError, "Size should be 1, 2 or 4"); + return 0; + } + + new_len = len*size; + if (new_len < 0) { + PyErr_SetString(PyExc_MemoryError, + "not enough memory for output buffer"); + return 0; + } + rv = PyBytes_FromStringAndSize(NULL, new_len); + if ( rv == 0 ) + return 0; + ncp = (signed char *)PyBytes_AsString(rv); + + for ( i=0; i < new_len; i += size ) { + cval = *cp++; + val = st_ulaw2linear16(cval); + + if ( size == 1 ) *CHARP(ncp, i) = (signed char)(val >> 8); + else if ( size == 2 ) *SHORTP(ncp, i) = (short)(val); + else if ( size == 4 ) *LONGP(ncp, i) = (Py_Int32)(val<<16); + } + return rv; } static PyObject * audioop_lin2alaw(PyObject *self, PyObject *args) { - signed char *cp; - unsigned char *ncp; - int len, size, val = 0; - PyObject *rv; - int i; - - if ( !PyArg_ParseTuple(args, "s#i:lin2alaw", - &cp, &len, &size) ) - return 0; - - if ( size != 1 && size != 2 && size != 4) { - PyErr_SetString(AudioopError, "Size should be 1, 2 or 4"); - return 0; - } - - rv = PyBytes_FromStringAndSize(NULL, len/size); - if ( rv == 0 ) - return 0; - ncp = (unsigned char *)PyBytes_AsString(rv); - - for ( i=0; i < len; i += size ) { - if ( size == 1 ) val = ((int)*CHARP(cp, i)) << 8; - else if ( size == 2 ) val = (int)*SHORTP(cp, i); - else if ( size == 4 ) val = ((int)*LONGP(cp, i)) >> 16; - - *ncp++ = st_linear2alaw(val); - } - return rv; + signed char *cp; + unsigned char *ncp; + int len, size, val = 0; + PyObject *rv; + int i; + + if ( !PyArg_ParseTuple(args, "s#i:lin2alaw", + &cp, &len, &size) ) + return 0; + + if ( size != 1 && size != 2 && size != 4) { + PyErr_SetString(AudioopError, "Size should be 1, 2 or 4"); + return 0; + } + + rv = PyBytes_FromStringAndSize(NULL, len/size); + if ( rv == 0 ) + return 0; + ncp = (unsigned char *)PyBytes_AsString(rv); + + for ( i=0; i < len; i += size ) { + if ( size == 1 ) val = ((int)*CHARP(cp, i)) << 8; + else if ( size == 2 ) val = (int)*SHORTP(cp, i); + else if ( size == 4 ) val = ((int)*LONGP(cp, i)) >> 16; + + *ncp++ = st_linear2alaw(val); + } + return rv; } static PyObject * audioop_alaw2lin(PyObject *self, PyObject *args) { - unsigned char *cp; - unsigned char cval; - signed char *ncp; - int len, new_len, size, val; - PyObject *rv; - int i; - - if ( !PyArg_ParseTuple(args, "s#i:alaw2lin", - &cp, &len, &size) ) - return 0; - - if ( size != 1 && size != 2 && size != 4) { - PyErr_SetString(AudioopError, "Size should be 1, 2 or 4"); - return 0; - } - - new_len = len*size; - if (new_len < 0) { - PyErr_SetString(PyExc_MemoryError, - "not enough memory for output buffer"); - return 0; - } - rv = PyBytes_FromStringAndSize(NULL, new_len); - if ( rv == 0 ) - return 0; - ncp = (signed char *)PyBytes_AsString(rv); - - for ( i=0; i < new_len; i += size ) { - cval = *cp++; - val = st_alaw2linear16(cval); - - if ( size == 1 ) *CHARP(ncp, i) = (signed char)(val >> 8); - else if ( size == 2 ) *SHORTP(ncp, i) = (short)(val); - else if ( size == 4 ) *LONGP(ncp, i) = (Py_Int32)(val<<16); - } - return rv; + unsigned char *cp; + unsigned char cval; + signed char *ncp; + int len, new_len, size, val; + PyObject *rv; + int i; + + if ( !PyArg_ParseTuple(args, "s#i:alaw2lin", + &cp, &len, &size) ) + return 0; + + if ( size != 1 && size != 2 && size != 4) { + PyErr_SetString(AudioopError, "Size should be 1, 2 or 4"); + return 0; + } + + new_len = len*size; + if (new_len < 0) { + PyErr_SetString(PyExc_MemoryError, + "not enough memory for output buffer"); + return 0; + } + rv = PyBytes_FromStringAndSize(NULL, new_len); + if ( rv == 0 ) + return 0; + ncp = (signed char *)PyBytes_AsString(rv); + + for ( i=0; i < new_len; i += size ) { + cval = *cp++; + val = st_alaw2linear16(cval); + + if ( size == 1 ) *CHARP(ncp, i) = (signed char)(val >> 8); + else if ( size == 2 ) *SHORTP(ncp, i) = (short)(val); + else if ( size == 4 ) *LONGP(ncp, i) = (Py_Int32)(val<<16); + } + return rv; } static PyObject * audioop_lin2adpcm(PyObject *self, PyObject *args) { - signed char *cp; - signed char *ncp; - int len, size, val = 0, step, valpred, delta, - index, sign, vpdiff, diff; - PyObject *rv, *state, *str; - int i, outputbuffer = 0, bufferstep; - - if ( !PyArg_ParseTuple(args, "s#iO:lin2adpcm", - &cp, &len, &size, &state) ) - return 0; - - - if ( size != 1 && size != 2 && size != 4) { - PyErr_SetString(AudioopError, "Size should be 1, 2 or 4"); - return 0; - } - - str = PyBytes_FromStringAndSize(NULL, len/(size*2)); - if ( str == 0 ) - return 0; - ncp = (signed char *)PyBytes_AsString(str); - - /* Decode state, should have (value, step) */ - if ( state == Py_None ) { - /* First time, it seems. Set defaults */ - valpred = 0; - step = 7; - index = 0; - } else if ( !PyArg_ParseTuple(state, "ii", &valpred, &index) ) - return 0; + signed char *cp; + signed char *ncp; + int len, size, val = 0, step, valpred, delta, + index, sign, vpdiff, diff; + PyObject *rv, *state, *str; + int i, outputbuffer = 0, bufferstep; + + if ( !PyArg_ParseTuple(args, "s#iO:lin2adpcm", + &cp, &len, &size, &state) ) + return 0; + + + if ( size != 1 && size != 2 && size != 4) { + PyErr_SetString(AudioopError, "Size should be 1, 2 or 4"); + return 0; + } + + str = PyBytes_FromStringAndSize(NULL, len/(size*2)); + if ( str == 0 ) + return 0; + ncp = (signed char *)PyBytes_AsString(str); + + /* Decode state, should have (value, step) */ + if ( state == Py_None ) { + /* First time, it seems. Set defaults */ + valpred = 0; + step = 7; + index = 0; + } else if ( !PyArg_ParseTuple(state, "ii", &valpred, &index) ) + return 0; + + step = stepsizeTable[index]; + bufferstep = 1; + + for ( i=0; i < len; i += size ) { + if ( size == 1 ) val = ((int)*CHARP(cp, i)) << 8; + else if ( size == 2 ) val = (int)*SHORTP(cp, i); + else if ( size == 4 ) val = ((int)*LONGP(cp, i)) >> 16; + + /* Step 1 - compute difference with previous value */ + diff = val - valpred; + sign = (diff < 0) ? 8 : 0; + if ( sign ) diff = (-diff); + + /* Step 2 - Divide and clamp */ + /* Note: + ** This code *approximately* computes: + ** delta = diff*4/step; + ** vpdiff = (delta+0.5)*step/4; + ** but in shift step bits are dropped. The net result of this + ** is that even if you have fast mul/div hardware you cannot + ** put it to good use since the fixup would be too expensive. + */ + delta = 0; + vpdiff = (step >> 3); + if ( diff >= step ) { + delta = 4; + diff -= step; + vpdiff += step; + } + step >>= 1; + if ( diff >= step ) { + delta |= 2; + diff -= step; + vpdiff += step; + } + step >>= 1; + if ( diff >= step ) { + delta |= 1; + vpdiff += step; + } + + /* Step 3 - Update previous value */ + if ( sign ) + valpred -= vpdiff; + else + valpred += vpdiff; + + /* Step 4 - Clamp previous value to 16 bits */ + if ( valpred > 32767 ) + valpred = 32767; + else if ( valpred < -32768 ) + valpred = -32768; + + /* Step 5 - Assemble value, update index and step values */ + delta |= sign; + + index += indexTable[delta]; + if ( index < 0 ) index = 0; + if ( index > 88 ) index = 88; step = stepsizeTable[index]; - bufferstep = 1; - for ( i=0; i < len; i += size ) { - if ( size == 1 ) val = ((int)*CHARP(cp, i)) << 8; - else if ( size == 2 ) val = (int)*SHORTP(cp, i); - else if ( size == 4 ) val = ((int)*LONGP(cp, i)) >> 16; - - /* Step 1 - compute difference with previous value */ - diff = val - valpred; - sign = (diff < 0) ? 8 : 0; - if ( sign ) diff = (-diff); - - /* Step 2 - Divide and clamp */ - /* Note: - ** This code *approximately* computes: - ** delta = diff*4/step; - ** vpdiff = (delta+0.5)*step/4; - ** but in shift step bits are dropped. The net result of this - ** is that even if you have fast mul/div hardware you cannot - ** put it to good use since the fixup would be too expensive. - */ - delta = 0; - vpdiff = (step >> 3); - - if ( diff >= step ) { - delta = 4; - diff -= step; - vpdiff += step; - } - step >>= 1; - if ( diff >= step ) { - delta |= 2; - diff -= step; - vpdiff += step; - } - step >>= 1; - if ( diff >= step ) { - delta |= 1; - vpdiff += step; - } - - /* Step 3 - Update previous value */ - if ( sign ) - valpred -= vpdiff; - else - valpred += vpdiff; - - /* Step 4 - Clamp previous value to 16 bits */ - if ( valpred > 32767 ) - valpred = 32767; - else if ( valpred < -32768 ) - valpred = -32768; - - /* Step 5 - Assemble value, update index and step values */ - delta |= sign; - - index += indexTable[delta]; - if ( index < 0 ) index = 0; - if ( index > 88 ) index = 88; - step = stepsizeTable[index]; - - /* Step 6 - Output value */ - if ( bufferstep ) { - outputbuffer = (delta << 4) & 0xf0; - } else { - *ncp++ = (delta & 0x0f) | outputbuffer; - } - bufferstep = !bufferstep; + /* Step 6 - Output value */ + if ( bufferstep ) { + outputbuffer = (delta << 4) & 0xf0; + } else { + *ncp++ = (delta & 0x0f) | outputbuffer; } - rv = Py_BuildValue("(O(ii))", str, valpred, index); - Py_DECREF(str); - return rv; + bufferstep = !bufferstep; + } + rv = Py_BuildValue("(O(ii))", str, valpred, index); + Py_DECREF(str); + return rv; } static PyObject * audioop_adpcm2lin(PyObject *self, PyObject *args) { - signed char *cp; - signed char *ncp; - int len, new_len, size, valpred, step, delta, index, sign, vpdiff; - PyObject *rv, *str, *state; - int i, inputbuffer = 0, bufferstep; - - if ( !PyArg_ParseTuple(args, "s#iO:adpcm2lin", - &cp, &len, &size, &state) ) - return 0; - - if ( size != 1 && size != 2 && size != 4) { - PyErr_SetString(AudioopError, "Size should be 1, 2 or 4"); - return 0; - } - - /* Decode state, should have (value, step) */ - if ( state == Py_None ) { - /* First time, it seems. Set defaults */ - valpred = 0; - step = 7; - index = 0; - } else if ( !PyArg_ParseTuple(state, "ii", &valpred, &index) ) - return 0; - - new_len = len*size*2; - if (new_len < 0) { - PyErr_SetString(PyExc_MemoryError, - "not enough memory for output buffer"); - return 0; + signed char *cp; + signed char *ncp; + int len, new_len, size, valpred, step, delta, index, sign, vpdiff; + PyObject *rv, *str, *state; + int i, inputbuffer = 0, bufferstep; + + if ( !PyArg_ParseTuple(args, "s#iO:adpcm2lin", + &cp, &len, &size, &state) ) + return 0; + + if ( size != 1 && size != 2 && size != 4) { + PyErr_SetString(AudioopError, "Size should be 1, 2 or 4"); + return 0; + } + + /* Decode state, should have (value, step) */ + if ( state == Py_None ) { + /* First time, it seems. Set defaults */ + valpred = 0; + step = 7; + index = 0; + } else if ( !PyArg_ParseTuple(state, "ii", &valpred, &index) ) + return 0; + + new_len = len*size*2; + if (new_len < 0) { + PyErr_SetString(PyExc_MemoryError, + "not enough memory for output buffer"); + return 0; + } + str = PyBytes_FromStringAndSize(NULL, new_len); + if ( str == 0 ) + return 0; + ncp = (signed char *)PyBytes_AsString(str); + + step = stepsizeTable[index]; + bufferstep = 0; + + for ( i=0; i < new_len; i += size ) { + /* Step 1 - get the delta value and compute next index */ + if ( bufferstep ) { + delta = inputbuffer & 0xf; + } else { + inputbuffer = *cp++; + delta = (inputbuffer >> 4) & 0xf; } - str = PyBytes_FromStringAndSize(NULL, new_len); - if ( str == 0 ) - return 0; - ncp = (signed char *)PyBytes_AsString(str); + bufferstep = !bufferstep; + + /* Step 2 - Find new index value (for later) */ + index += indexTable[delta]; + if ( index < 0 ) index = 0; + if ( index > 88 ) index = 88; + + /* Step 3 - Separate sign and magnitude */ + sign = delta & 8; + delta = delta & 7; + + /* Step 4 - Compute difference and new predicted value */ + /* + ** Computes 'vpdiff = (delta+0.5)*step/4', but see comment + ** in adpcm_coder. + */ + vpdiff = step >> 3; + if ( delta & 4 ) vpdiff += step; + if ( delta & 2 ) vpdiff += step>>1; + if ( delta & 1 ) vpdiff += step>>2; + + if ( sign ) + valpred -= vpdiff; + else + valpred += vpdiff; + + /* Step 5 - clamp output value */ + if ( valpred > 32767 ) + valpred = 32767; + else if ( valpred < -32768 ) + valpred = -32768; + + /* Step 6 - Update step value */ step = stepsizeTable[index]; - bufferstep = 0; - - for ( i=0; i < new_len; i += size ) { - /* Step 1 - get the delta value and compute next index */ - if ( bufferstep ) { - delta = inputbuffer & 0xf; - } else { - inputbuffer = *cp++; - delta = (inputbuffer >> 4) & 0xf; - } - - bufferstep = !bufferstep; - - /* Step 2 - Find new index value (for later) */ - index += indexTable[delta]; - if ( index < 0 ) index = 0; - if ( index > 88 ) index = 88; - - /* Step 3 - Separate sign and magnitude */ - sign = delta & 8; - delta = delta & 7; - - /* Step 4 - Compute difference and new predicted value */ - /* - ** Computes 'vpdiff = (delta+0.5)*step/4', but see comment - ** in adpcm_coder. - */ - vpdiff = step >> 3; - if ( delta & 4 ) vpdiff += step; - if ( delta & 2 ) vpdiff += step>>1; - if ( delta & 1 ) vpdiff += step>>2; - - if ( sign ) - valpred -= vpdiff; - else - valpred += vpdiff; - - /* Step 5 - clamp output value */ - if ( valpred > 32767 ) - valpred = 32767; - else if ( valpred < -32768 ) - valpred = -32768; - - /* Step 6 - Update step value */ - step = stepsizeTable[index]; - - /* Step 6 - Output value */ - if ( size == 1 ) *CHARP(ncp, i) = (signed char)(valpred >> 8); - else if ( size == 2 ) *SHORTP(ncp, i) = (short)(valpred); - else if ( size == 4 ) *LONGP(ncp, i) = (Py_Int32)(valpred<<16); - } - rv = Py_BuildValue("(O(ii))", str, valpred, index); - Py_DECREF(str); - return rv; + /* Step 6 - Output value */ + if ( size == 1 ) *CHARP(ncp, i) = (signed char)(valpred >> 8); + else if ( size == 2 ) *SHORTP(ncp, i) = (short)(valpred); + else if ( size == 4 ) *LONGP(ncp, i) = (Py_Int32)(valpred<<16); + } + + rv = Py_BuildValue("(O(ii))", str, valpred, index); + Py_DECREF(str); + return rv; } static PyMethodDef audioop_methods[] = { - { "max", audioop_max, METH_VARARGS }, - { "minmax", audioop_minmax, METH_VARARGS }, - { "avg", audioop_avg, METH_VARARGS }, - { "maxpp", audioop_maxpp, METH_VARARGS }, - { "avgpp", audioop_avgpp, METH_VARARGS }, - { "rms", audioop_rms, METH_VARARGS }, - { "findfit", audioop_findfit, METH_VARARGS }, - { "findmax", audioop_findmax, METH_VARARGS }, - { "findfactor", audioop_findfactor, METH_VARARGS }, - { "cross", audioop_cross, METH_VARARGS }, - { "mul", audioop_mul, METH_VARARGS }, - { "add", audioop_add, METH_VARARGS }, - { "bias", audioop_bias, METH_VARARGS }, - { "ulaw2lin", audioop_ulaw2lin, METH_VARARGS }, - { "lin2ulaw", audioop_lin2ulaw, METH_VARARGS }, - { "alaw2lin", audioop_alaw2lin, METH_VARARGS }, - { "lin2alaw", audioop_lin2alaw, METH_VARARGS }, - { "lin2lin", audioop_lin2lin, METH_VARARGS }, - { "adpcm2lin", audioop_adpcm2lin, METH_VARARGS }, - { "lin2adpcm", audioop_lin2adpcm, METH_VARARGS }, - { "tomono", audioop_tomono, METH_VARARGS }, - { "tostereo", audioop_tostereo, METH_VARARGS }, - { "getsample", audioop_getsample, METH_VARARGS }, - { "reverse", audioop_reverse, METH_VARARGS }, - { "ratecv", audioop_ratecv, METH_VARARGS }, - { 0, 0 } + { "max", audioop_max, METH_VARARGS }, + { "minmax", audioop_minmax, METH_VARARGS }, + { "avg", audioop_avg, METH_VARARGS }, + { "maxpp", audioop_maxpp, METH_VARARGS }, + { "avgpp", audioop_avgpp, METH_VARARGS }, + { "rms", audioop_rms, METH_VARARGS }, + { "findfit", audioop_findfit, METH_VARARGS }, + { "findmax", audioop_findmax, METH_VARARGS }, + { "findfactor", audioop_findfactor, METH_VARARGS }, + { "cross", audioop_cross, METH_VARARGS }, + { "mul", audioop_mul, METH_VARARGS }, + { "add", audioop_add, METH_VARARGS }, + { "bias", audioop_bias, METH_VARARGS }, + { "ulaw2lin", audioop_ulaw2lin, METH_VARARGS }, + { "lin2ulaw", audioop_lin2ulaw, METH_VARARGS }, + { "alaw2lin", audioop_alaw2lin, METH_VARARGS }, + { "lin2alaw", audioop_lin2alaw, METH_VARARGS }, + { "lin2lin", audioop_lin2lin, METH_VARARGS }, + { "adpcm2lin", audioop_adpcm2lin, METH_VARARGS }, + { "lin2adpcm", audioop_lin2adpcm, METH_VARARGS }, + { "tomono", audioop_tomono, METH_VARARGS }, + { "tostereo", audioop_tostereo, METH_VARARGS }, + { "getsample", audioop_getsample, METH_VARARGS }, + { "reverse", audioop_reverse, METH_VARARGS }, + { "ratecv", audioop_ratecv, METH_VARARGS }, + { 0, 0 } }; static struct PyModuleDef audioopmodule = { - PyModuleDef_HEAD_INIT, - "audioop", - NULL, - -1, - audioop_methods, - NULL, - NULL, - NULL, - NULL + PyModuleDef_HEAD_INIT, + "audioop", + NULL, + -1, + audioop_methods, + NULL, + NULL, + NULL, + NULL }; PyMODINIT_FUNC PyInit_audioop(void) { - PyObject *m, *d; - m = PyModule_Create(&audioopmodule); - if (m == NULL) - return NULL; - d = PyModule_GetDict(m); - if (d == NULL) - return NULL; - AudioopError = PyErr_NewException("audioop.error", NULL, NULL); - if (AudioopError != NULL) - PyDict_SetItemString(d,"error",AudioopError); - return m; + PyObject *m, *d; + m = PyModule_Create(&audioopmodule); + if (m == NULL) + return NULL; + d = PyModule_GetDict(m); + if (d == NULL) + return NULL; + AudioopError = PyErr_NewException("audioop.error", NULL, NULL); + if (AudioopError != NULL) + PyDict_SetItemString(d,"error",AudioopError); + return m; } Modified: python/branches/py3k-jit/Modules/binascii.c ============================================================================== --- python/branches/py3k-jit/Modules/binascii.c (original) +++ python/branches/py3k-jit/Modules/binascii.c Mon May 10 23:55:43 2010 @@ -3,40 +3,40 @@ ** ** This module currently supports the following encodings: ** uuencode: -** each line encodes 45 bytes (except possibly the last) -** First char encodes (binary) length, rest data -** each char encodes 6 bits, as follows: -** binary: 01234567 abcdefgh ijklmnop -** ascii: 012345 67abcd efghij klmnop -** ASCII encoding method is "excess-space": 000000 is encoded as ' ', etc. -** short binary data is zero-extended (so the bits are always in the -** right place), this does *not* reflect in the length. +** each line encodes 45 bytes (except possibly the last) +** First char encodes (binary) length, rest data +** each char encodes 6 bits, as follows: +** binary: 01234567 abcdefgh ijklmnop +** ascii: 012345 67abcd efghij klmnop +** ASCII encoding method is "excess-space": 000000 is encoded as ' ', etc. +** short binary data is zero-extended (so the bits are always in the +** right place), this does *not* reflect in the length. ** base64: ** Line breaks are insignificant, but lines are at most 76 chars ** each char encodes 6 bits, in similar order as uucode/hqx. Encoding ** is done via a table. ** Short binary data is filled (in ASCII) with '='. ** hqx: -** File starts with introductory text, real data starts and ends -** with colons. -** Data consists of three similar parts: info, datafork, resourcefork. -** Each part is protected (at the end) with a 16-bit crc -** The binary data is run-length encoded, and then ascii-fied: -** binary: 01234567 abcdefgh ijklmnop -** ascii: 012345 67abcd efghij klmnop -** ASCII encoding is table-driven, see the code. -** Short binary data results in the runt ascii-byte being output with -** the bits in the right place. +** File starts with introductory text, real data starts and ends +** with colons. +** Data consists of three similar parts: info, datafork, resourcefork. +** Each part is protected (at the end) with a 16-bit crc +** The binary data is run-length encoded, and then ascii-fied: +** binary: 01234567 abcdefgh ijklmnop +** ascii: 012345 67abcd efghij klmnop +** ASCII encoding is table-driven, see the code. +** Short binary data results in the runt ascii-byte being output with +** the bits in the right place. ** ** While I was reading dozens of programs that encode or decode the formats ** here (documentation? hihi:-) I have formulated Jansen's Observation: ** -** Programs that encode binary data in ASCII are written in -** such a style that they are as unreadable as possible. Devices used -** include unnecessary global variables, burying important tables -** in unrelated sourcefiles, putting functions in include files, -** using seemingly-descriptive variable names for different purposes, -** calls to empty subroutines and a host of others. +** Programs that encode binary data in ASCII are written in +** such a style that they are as unreadable as possible. Devices used +** include unnecessary global variables, burying important tables +** in unrelated sourcefiles, putting functions in include files, +** using seemingly-descriptive variable names for different purposes, +** calls to empty subroutines and a host of others. ** ** I have attempted to break with this tradition, but I guess that that ** does make the performance sub-optimal. Oh well, too bad... @@ -75,67 +75,67 @@ static unsigned char table_a2b_hqx[256] = { /* ^@ ^A ^B ^C ^D ^E ^F ^G */ -/* 0*/ FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, +/* 0*/ FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, /* \b \t \n ^K ^L \r ^N ^O */ -/* 1*/ FAIL, FAIL, SKIP, FAIL, FAIL, SKIP, FAIL, FAIL, +/* 1*/ FAIL, FAIL, SKIP, FAIL, FAIL, SKIP, FAIL, FAIL, /* ^P ^Q ^R ^S ^T ^U ^V ^W */ -/* 2*/ FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, +/* 2*/ FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, /* ^X ^Y ^Z ^[ ^\ ^] ^^ ^_ */ -/* 3*/ FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, +/* 3*/ FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, /* ! " # $ % & ' */ -/* 4*/ FAIL, 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, +/* 4*/ FAIL, 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, /* ( ) * + , - . / */ -/* 5*/ 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, FAIL, FAIL, +/* 5*/ 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, FAIL, FAIL, /* 0 1 2 3 4 5 6 7 */ -/* 6*/ 0x0D, 0x0E, 0x0F, 0x10, 0x11, 0x12, 0x13, FAIL, +/* 6*/ 0x0D, 0x0E, 0x0F, 0x10, 0x11, 0x12, 0x13, FAIL, /* 8 9 : ; < = > ? */ -/* 7*/ 0x14, 0x15, DONE, FAIL, FAIL, FAIL, FAIL, FAIL, +/* 7*/ 0x14, 0x15, DONE, FAIL, FAIL, FAIL, FAIL, FAIL, /* @ A B C D E F G */ -/* 8*/ 0x16, 0x17, 0x18, 0x19, 0x1A, 0x1B, 0x1C, 0x1D, +/* 8*/ 0x16, 0x17, 0x18, 0x19, 0x1A, 0x1B, 0x1C, 0x1D, /* H I J K L M N O */ -/* 9*/ 0x1E, 0x1F, 0x20, 0x21, 0x22, 0x23, 0x24, FAIL, +/* 9*/ 0x1E, 0x1F, 0x20, 0x21, 0x22, 0x23, 0x24, FAIL, /* P Q R S T U V W */ -/*10*/ 0x25, 0x26, 0x27, 0x28, 0x29, 0x2A, 0x2B, FAIL, +/*10*/ 0x25, 0x26, 0x27, 0x28, 0x29, 0x2A, 0x2B, FAIL, /* X Y Z [ \ ] ^ _ */ -/*11*/ 0x2C, 0x2D, 0x2E, 0x2F, FAIL, FAIL, FAIL, FAIL, +/*11*/ 0x2C, 0x2D, 0x2E, 0x2F, FAIL, FAIL, FAIL, FAIL, /* ` a b c d e f g */ -/*12*/ 0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, FAIL, +/*12*/ 0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, FAIL, /* h i j k l m n o */ -/*13*/ 0x37, 0x38, 0x39, 0x3A, 0x3B, 0x3C, FAIL, FAIL, +/*13*/ 0x37, 0x38, 0x39, 0x3A, 0x3B, 0x3C, FAIL, FAIL, /* p q r s t u v w */ -/*14*/ 0x3D, 0x3E, 0x3F, FAIL, FAIL, FAIL, FAIL, FAIL, +/*14*/ 0x3D, 0x3E, 0x3F, FAIL, FAIL, FAIL, FAIL, FAIL, /* x y z { | } ~ ^? */ -/*15*/ FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, -/*16*/ FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, - FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, - FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, - FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, - FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, - FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, - FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, - FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, - FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, - FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, - FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, - FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, - FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, - FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, - FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, - FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, +/*15*/ FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, +/*16*/ FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, + FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, + FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, + FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, + FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, + FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, + FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, + FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, + FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, + FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, + FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, + FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, + FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, + FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, + FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, + FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, }; static unsigned char table_b2a_hqx[] = "!\"#$%&'()*+,-012345689 at ABCDEFGHIJKLMNPQRSTUVXYZ[`abcdefhijklmpqr"; static char table_a2b_base64[] = { - -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1, - -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1, - -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,62, -1,-1,-1,63, - 52,53,54,55, 56,57,58,59, 60,61,-1,-1, -1, 0,-1,-1, /* Note PAD->0 */ - -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9,10, 11,12,13,14, - 15,16,17,18, 19,20,21,22, 23,24,25,-1, -1,-1,-1,-1, - -1,26,27,28, 29,30,31,32, 33,34,35,36, 37,38,39,40, - 41,42,43,44, 45,46,47,48, 49,50,51,-1, -1,-1,-1,-1 + -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1, + -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1, + -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,62, -1,-1,-1,63, + 52,53,54,55, 56,57,58,59, 60,61,-1,-1, -1, 0,-1,-1, /* Note PAD->0 */ + -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9,10, 11,12,13,14, + 15,16,17,18, 19,20,21,22, 23,24,25,-1, -1,-1,-1,-1, + -1,26,27,28, 29,30,31,32, 33,34,35,36, 37,38,39,40, + 41,42,43,44, 45,46,47,48, 49,50,51,-1, -1,-1,-1,-1 }; #define BASE64_PAD '=' @@ -149,38 +149,38 @@ static unsigned short crctab_hqx[256] = { - 0x0000, 0x1021, 0x2042, 0x3063, 0x4084, 0x50a5, 0x60c6, 0x70e7, - 0x8108, 0x9129, 0xa14a, 0xb16b, 0xc18c, 0xd1ad, 0xe1ce, 0xf1ef, - 0x1231, 0x0210, 0x3273, 0x2252, 0x52b5, 0x4294, 0x72f7, 0x62d6, - 0x9339, 0x8318, 0xb37b, 0xa35a, 0xd3bd, 0xc39c, 0xf3ff, 0xe3de, - 0x2462, 0x3443, 0x0420, 0x1401, 0x64e6, 0x74c7, 0x44a4, 0x5485, - 0xa56a, 0xb54b, 0x8528, 0x9509, 0xe5ee, 0xf5cf, 0xc5ac, 0xd58d, - 0x3653, 0x2672, 0x1611, 0x0630, 0x76d7, 0x66f6, 0x5695, 0x46b4, - 0xb75b, 0xa77a, 0x9719, 0x8738, 0xf7df, 0xe7fe, 0xd79d, 0xc7bc, - 0x48c4, 0x58e5, 0x6886, 0x78a7, 0x0840, 0x1861, 0x2802, 0x3823, - 0xc9cc, 0xd9ed, 0xe98e, 0xf9af, 0x8948, 0x9969, 0xa90a, 0xb92b, - 0x5af5, 0x4ad4, 0x7ab7, 0x6a96, 0x1a71, 0x0a50, 0x3a33, 0x2a12, - 0xdbfd, 0xcbdc, 0xfbbf, 0xeb9e, 0x9b79, 0x8b58, 0xbb3b, 0xab1a, - 0x6ca6, 0x7c87, 0x4ce4, 0x5cc5, 0x2c22, 0x3c03, 0x0c60, 0x1c41, - 0xedae, 0xfd8f, 0xcdec, 0xddcd, 0xad2a, 0xbd0b, 0x8d68, 0x9d49, - 0x7e97, 0x6eb6, 0x5ed5, 0x4ef4, 0x3e13, 0x2e32, 0x1e51, 0x0e70, - 0xff9f, 0xefbe, 0xdfdd, 0xcffc, 0xbf1b, 0xaf3a, 0x9f59, 0x8f78, - 0x9188, 0x81a9, 0xb1ca, 0xa1eb, 0xd10c, 0xc12d, 0xf14e, 0xe16f, - 0x1080, 0x00a1, 0x30c2, 0x20e3, 0x5004, 0x4025, 0x7046, 0x6067, - 0x83b9, 0x9398, 0xa3fb, 0xb3da, 0xc33d, 0xd31c, 0xe37f, 0xf35e, - 0x02b1, 0x1290, 0x22f3, 0x32d2, 0x4235, 0x5214, 0x6277, 0x7256, - 0xb5ea, 0xa5cb, 0x95a8, 0x8589, 0xf56e, 0xe54f, 0xd52c, 0xc50d, - 0x34e2, 0x24c3, 0x14a0, 0x0481, 0x7466, 0x6447, 0x5424, 0x4405, - 0xa7db, 0xb7fa, 0x8799, 0x97b8, 0xe75f, 0xf77e, 0xc71d, 0xd73c, - 0x26d3, 0x36f2, 0x0691, 0x16b0, 0x6657, 0x7676, 0x4615, 0x5634, - 0xd94c, 0xc96d, 0xf90e, 0xe92f, 0x99c8, 0x89e9, 0xb98a, 0xa9ab, - 0x5844, 0x4865, 0x7806, 0x6827, 0x18c0, 0x08e1, 0x3882, 0x28a3, - 0xcb7d, 0xdb5c, 0xeb3f, 0xfb1e, 0x8bf9, 0x9bd8, 0xabbb, 0xbb9a, - 0x4a75, 0x5a54, 0x6a37, 0x7a16, 0x0af1, 0x1ad0, 0x2ab3, 0x3a92, - 0xfd2e, 0xed0f, 0xdd6c, 0xcd4d, 0xbdaa, 0xad8b, 0x9de8, 0x8dc9, - 0x7c26, 0x6c07, 0x5c64, 0x4c45, 0x3ca2, 0x2c83, 0x1ce0, 0x0cc1, - 0xef1f, 0xff3e, 0xcf5d, 0xdf7c, 0xaf9b, 0xbfba, 0x8fd9, 0x9ff8, - 0x6e17, 0x7e36, 0x4e55, 0x5e74, 0x2e93, 0x3eb2, 0x0ed1, 0x1ef0, + 0x0000, 0x1021, 0x2042, 0x3063, 0x4084, 0x50a5, 0x60c6, 0x70e7, + 0x8108, 0x9129, 0xa14a, 0xb16b, 0xc18c, 0xd1ad, 0xe1ce, 0xf1ef, + 0x1231, 0x0210, 0x3273, 0x2252, 0x52b5, 0x4294, 0x72f7, 0x62d6, + 0x9339, 0x8318, 0xb37b, 0xa35a, 0xd3bd, 0xc39c, 0xf3ff, 0xe3de, + 0x2462, 0x3443, 0x0420, 0x1401, 0x64e6, 0x74c7, 0x44a4, 0x5485, + 0xa56a, 0xb54b, 0x8528, 0x9509, 0xe5ee, 0xf5cf, 0xc5ac, 0xd58d, + 0x3653, 0x2672, 0x1611, 0x0630, 0x76d7, 0x66f6, 0x5695, 0x46b4, + 0xb75b, 0xa77a, 0x9719, 0x8738, 0xf7df, 0xe7fe, 0xd79d, 0xc7bc, + 0x48c4, 0x58e5, 0x6886, 0x78a7, 0x0840, 0x1861, 0x2802, 0x3823, + 0xc9cc, 0xd9ed, 0xe98e, 0xf9af, 0x8948, 0x9969, 0xa90a, 0xb92b, + 0x5af5, 0x4ad4, 0x7ab7, 0x6a96, 0x1a71, 0x0a50, 0x3a33, 0x2a12, + 0xdbfd, 0xcbdc, 0xfbbf, 0xeb9e, 0x9b79, 0x8b58, 0xbb3b, 0xab1a, + 0x6ca6, 0x7c87, 0x4ce4, 0x5cc5, 0x2c22, 0x3c03, 0x0c60, 0x1c41, + 0xedae, 0xfd8f, 0xcdec, 0xddcd, 0xad2a, 0xbd0b, 0x8d68, 0x9d49, + 0x7e97, 0x6eb6, 0x5ed5, 0x4ef4, 0x3e13, 0x2e32, 0x1e51, 0x0e70, + 0xff9f, 0xefbe, 0xdfdd, 0xcffc, 0xbf1b, 0xaf3a, 0x9f59, 0x8f78, + 0x9188, 0x81a9, 0xb1ca, 0xa1eb, 0xd10c, 0xc12d, 0xf14e, 0xe16f, + 0x1080, 0x00a1, 0x30c2, 0x20e3, 0x5004, 0x4025, 0x7046, 0x6067, + 0x83b9, 0x9398, 0xa3fb, 0xb3da, 0xc33d, 0xd31c, 0xe37f, 0xf35e, + 0x02b1, 0x1290, 0x22f3, 0x32d2, 0x4235, 0x5214, 0x6277, 0x7256, + 0xb5ea, 0xa5cb, 0x95a8, 0x8589, 0xf56e, 0xe54f, 0xd52c, 0xc50d, + 0x34e2, 0x24c3, 0x14a0, 0x0481, 0x7466, 0x6447, 0x5424, 0x4405, + 0xa7db, 0xb7fa, 0x8799, 0x97b8, 0xe75f, 0xf77e, 0xc71d, 0xd73c, + 0x26d3, 0x36f2, 0x0691, 0x16b0, 0x6657, 0x7676, 0x4615, 0x5634, + 0xd94c, 0xc96d, 0xf90e, 0xe92f, 0x99c8, 0x89e9, 0xb98a, 0xa9ab, + 0x5844, 0x4865, 0x7806, 0x6827, 0x18c0, 0x08e1, 0x3882, 0x28a3, + 0xcb7d, 0xdb5c, 0xeb3f, 0xfb1e, 0x8bf9, 0x9bd8, 0xabbb, 0xbb9a, + 0x4a75, 0x5a54, 0x6a37, 0x7a16, 0x0af1, 0x1ad0, 0x2ab3, 0x3a92, + 0xfd2e, 0xed0f, 0xdd6c, 0xcd4d, 0xbdaa, 0xad8b, 0x9de8, 0x8dc9, + 0x7c26, 0x6c07, 0x5c64, 0x4c45, 0x3ca2, 0x2c83, 0x1ce0, 0x0cc1, + 0xef1f, 0xff3e, 0xcf5d, 0xdf7c, 0xaf9b, 0xbfba, 0x8fd9, 0x9ff8, + 0x6e17, 0x7e36, 0x4e55, 0x5e74, 0x2e93, 0x3eb2, 0x0ed1, 0x1ef0, }; PyDoc_STRVAR(doc_a2b_uu, "(ascii) -> bin. Decode a line of uuencoded data"); @@ -188,85 +188,85 @@ static PyObject * binascii_a2b_uu(PyObject *self, PyObject *args) { - Py_buffer pascii; - unsigned char *ascii_data, *bin_data; - int leftbits = 0; - unsigned char this_ch; - unsigned int leftchar = 0; - PyObject *rv; - Py_ssize_t ascii_len, bin_len; - - if ( !PyArg_ParseTuple(args, "y*:a2b_uu", &pascii) ) - return NULL; - ascii_data = pascii.buf; - ascii_len = pascii.len; - - assert(ascii_len >= 0); - - /* First byte: binary data length (in bytes) */ - bin_len = (*ascii_data++ - ' ') & 077; - ascii_len--; - - /* Allocate the buffer */ - if ( (rv=PyBytes_FromStringAndSize(NULL, bin_len)) == NULL ) { - PyBuffer_Release(&pascii); - return NULL; - } - bin_data = (unsigned char *)PyBytes_AS_STRING(rv); - - for( ; bin_len > 0 ; ascii_len--, ascii_data++ ) { - /* XXX is it really best to add NULs if there's no more data */ - this_ch = (ascii_len > 0) ? *ascii_data : 0; - if ( this_ch == '\n' || this_ch == '\r' || ascii_len <= 0) { - /* - ** Whitespace. Assume some spaces got eaten at - ** end-of-line. (We check this later) - */ - this_ch = 0; - } else { - /* Check the character for legality - ** The 64 in stead of the expected 63 is because - ** there are a few uuencodes out there that use - ** '`' as zero instead of space. - */ - if ( this_ch < ' ' || this_ch > (' ' + 64)) { - PyErr_SetString(Error, "Illegal char"); - PyBuffer_Release(&pascii); - Py_DECREF(rv); - return NULL; - } - this_ch = (this_ch - ' ') & 077; - } - /* - ** Shift it in on the low end, and see if there's - ** a byte ready for output. - */ - leftchar = (leftchar << 6) | (this_ch); - leftbits += 6; - if ( leftbits >= 8 ) { - leftbits -= 8; - *bin_data++ = (leftchar >> leftbits) & 0xff; - leftchar &= ((1 << leftbits) - 1); - bin_len--; - } - } - /* - ** Finally, check that if there's anything left on the line - ** that it's whitespace only. - */ - while( ascii_len-- > 0 ) { - this_ch = *ascii_data++; - /* Extra '`' may be written as padding in some cases */ - if ( this_ch != ' ' && this_ch != ' '+64 && - this_ch != '\n' && this_ch != '\r' ) { - PyErr_SetString(Error, "Trailing garbage"); - PyBuffer_Release(&pascii); - Py_DECREF(rv); - return NULL; - } - } - PyBuffer_Release(&pascii); - return rv; + Py_buffer pascii; + unsigned char *ascii_data, *bin_data; + int leftbits = 0; + unsigned char this_ch; + unsigned int leftchar = 0; + PyObject *rv; + Py_ssize_t ascii_len, bin_len; + + if ( !PyArg_ParseTuple(args, "y*:a2b_uu", &pascii) ) + return NULL; + ascii_data = pascii.buf; + ascii_len = pascii.len; + + assert(ascii_len >= 0); + + /* First byte: binary data length (in bytes) */ + bin_len = (*ascii_data++ - ' ') & 077; + ascii_len--; + + /* Allocate the buffer */ + if ( (rv=PyBytes_FromStringAndSize(NULL, bin_len)) == NULL ) { + PyBuffer_Release(&pascii); + return NULL; + } + bin_data = (unsigned char *)PyBytes_AS_STRING(rv); + + for( ; bin_len > 0 ; ascii_len--, ascii_data++ ) { + /* XXX is it really best to add NULs if there's no more data */ + this_ch = (ascii_len > 0) ? *ascii_data : 0; + if ( this_ch == '\n' || this_ch == '\r' || ascii_len <= 0) { + /* + ** Whitespace. Assume some spaces got eaten at + ** end-of-line. (We check this later) + */ + this_ch = 0; + } else { + /* Check the character for legality + ** The 64 in stead of the expected 63 is because + ** there are a few uuencodes out there that use + ** '`' as zero instead of space. + */ + if ( this_ch < ' ' || this_ch > (' ' + 64)) { + PyErr_SetString(Error, "Illegal char"); + PyBuffer_Release(&pascii); + Py_DECREF(rv); + return NULL; + } + this_ch = (this_ch - ' ') & 077; + } + /* + ** Shift it in on the low end, and see if there's + ** a byte ready for output. + */ + leftchar = (leftchar << 6) | (this_ch); + leftbits += 6; + if ( leftbits >= 8 ) { + leftbits -= 8; + *bin_data++ = (leftchar >> leftbits) & 0xff; + leftchar &= ((1 << leftbits) - 1); + bin_len--; + } + } + /* + ** Finally, check that if there's anything left on the line + ** that it's whitespace only. + */ + while( ascii_len-- > 0 ) { + this_ch = *ascii_data++; + /* Extra '`' may be written as padding in some cases */ + if ( this_ch != ' ' && this_ch != ' '+64 && + this_ch != '\n' && this_ch != '\r' ) { + PyErr_SetString(Error, "Trailing garbage"); + PyBuffer_Release(&pascii); + Py_DECREF(rv); + return NULL; + } + } + PyBuffer_Release(&pascii); + return rv; } PyDoc_STRVAR(doc_b2a_uu, "(bin) -> ascii. Uuencode line of data"); @@ -274,86 +274,86 @@ static PyObject * binascii_b2a_uu(PyObject *self, PyObject *args) { - Py_buffer pbin; - unsigned char *ascii_data, *bin_data; - int leftbits = 0; - unsigned char this_ch; - unsigned int leftchar = 0; - PyObject *rv; - Py_ssize_t bin_len; - - if ( !PyArg_ParseTuple(args, "y*:b2a_uu", &pbin) ) - return NULL; - bin_data = pbin.buf; - bin_len = pbin.len; - if ( bin_len > 45 ) { - /* The 45 is a limit that appears in all uuencode's */ - PyErr_SetString(Error, "At most 45 bytes at once"); - PyBuffer_Release(&pbin); - return NULL; - } - - /* We're lazy and allocate to much (fixed up later) */ - if ( (rv=PyBytes_FromStringAndSize(NULL, 2 + (bin_len+2)/3*4)) == NULL ) { - PyBuffer_Release(&pbin); - return NULL; - } - ascii_data = (unsigned char *)PyBytes_AS_STRING(rv); - - /* Store the length */ - *ascii_data++ = ' ' + (bin_len & 077); - - for( ; bin_len > 0 || leftbits != 0 ; bin_len--, bin_data++ ) { - /* Shift the data (or padding) into our buffer */ - if ( bin_len > 0 ) /* Data */ - leftchar = (leftchar << 8) | *bin_data; - else /* Padding */ - leftchar <<= 8; - leftbits += 8; - - /* See if there are 6-bit groups ready */ - while ( leftbits >= 6 ) { - this_ch = (leftchar >> (leftbits-6)) & 0x3f; - leftbits -= 6; - *ascii_data++ = this_ch + ' '; - } - } - *ascii_data++ = '\n'; /* Append a courtesy newline */ - - if (_PyBytes_Resize(&rv, - (ascii_data - - (unsigned char *)PyBytes_AS_STRING(rv))) < 0) { - Py_DECREF(rv); - rv = NULL; - } - PyBuffer_Release(&pbin); - return rv; + Py_buffer pbin; + unsigned char *ascii_data, *bin_data; + int leftbits = 0; + unsigned char this_ch; + unsigned int leftchar = 0; + PyObject *rv; + Py_ssize_t bin_len; + + if ( !PyArg_ParseTuple(args, "y*:b2a_uu", &pbin) ) + return NULL; + bin_data = pbin.buf; + bin_len = pbin.len; + if ( bin_len > 45 ) { + /* The 45 is a limit that appears in all uuencode's */ + PyErr_SetString(Error, "At most 45 bytes at once"); + PyBuffer_Release(&pbin); + return NULL; + } + + /* We're lazy and allocate to much (fixed up later) */ + if ( (rv=PyBytes_FromStringAndSize(NULL, 2 + (bin_len+2)/3*4)) == NULL ) { + PyBuffer_Release(&pbin); + return NULL; + } + ascii_data = (unsigned char *)PyBytes_AS_STRING(rv); + + /* Store the length */ + *ascii_data++ = ' ' + (bin_len & 077); + + for( ; bin_len > 0 || leftbits != 0 ; bin_len--, bin_data++ ) { + /* Shift the data (or padding) into our buffer */ + if ( bin_len > 0 ) /* Data */ + leftchar = (leftchar << 8) | *bin_data; + else /* Padding */ + leftchar <<= 8; + leftbits += 8; + + /* See if there are 6-bit groups ready */ + while ( leftbits >= 6 ) { + this_ch = (leftchar >> (leftbits-6)) & 0x3f; + leftbits -= 6; + *ascii_data++ = this_ch + ' '; + } + } + *ascii_data++ = '\n'; /* Append a courtesy newline */ + + if (_PyBytes_Resize(&rv, + (ascii_data - + (unsigned char *)PyBytes_AS_STRING(rv))) < 0) { + Py_DECREF(rv); + rv = NULL; + } + PyBuffer_Release(&pbin); + return rv; } static int binascii_find_valid(unsigned char *s, Py_ssize_t slen, int num) { - /* Finds & returns the (num+1)th - ** valid character for base64, or -1 if none. - */ - - int ret = -1; - unsigned char c, b64val; - - while ((slen > 0) && (ret == -1)) { - c = *s; - b64val = table_a2b_base64[c & 0x7f]; - if ( ((c <= 0x7f) && (b64val != (unsigned char)-1)) ) { - if (num == 0) - ret = *s; - num--; - } - - s++; - slen--; - } - return ret; + /* Finds & returns the (num+1)th + ** valid character for base64, or -1 if none. + */ + + int ret = -1; + unsigned char c, b64val; + + while ((slen > 0) && (ret == -1)) { + c = *s; + b64val = table_a2b_base64[c & 0x7f]; + if ( ((c <= 0x7f) && (b64val != (unsigned char)-1)) ) { + if (num == 0) + ret = *s; + num--; + } + + s++; + slen--; + } + return ret; } PyDoc_STRVAR(doc_a2b_base64, "(ascii) -> bin. Decode a line of base64 data"); @@ -361,108 +361,108 @@ static PyObject * binascii_a2b_base64(PyObject *self, PyObject *args) { - Py_buffer pascii; - unsigned char *ascii_data, *bin_data; - int leftbits = 0; - unsigned char this_ch; - unsigned int leftchar = 0; - PyObject *rv; - Py_ssize_t ascii_len, bin_len; - int quad_pos = 0; - - if ( !PyArg_ParseTuple(args, "y*:a2b_base64", &pascii) ) - return NULL; - ascii_data = pascii.buf; - ascii_len = pascii.len; - - assert(ascii_len >= 0); - - if (ascii_len > PY_SSIZE_T_MAX - 3) { - PyBuffer_Release(&pascii); - return PyErr_NoMemory(); - } - - bin_len = ((ascii_len+3)/4)*3; /* Upper bound, corrected later */ - - /* Allocate the buffer */ - if ( (rv=PyBytes_FromStringAndSize(NULL, bin_len)) == NULL ) { - PyBuffer_Release(&pascii); - return NULL; - } - bin_data = (unsigned char *)PyBytes_AS_STRING(rv); - bin_len = 0; - - for( ; ascii_len > 0; ascii_len--, ascii_data++) { - this_ch = *ascii_data; - - if (this_ch > 0x7f || - this_ch == '\r' || this_ch == '\n' || this_ch == ' ') - continue; - - /* Check for pad sequences and ignore - ** the invalid ones. - */ - if (this_ch == BASE64_PAD) { - if ( (quad_pos < 2) || - ((quad_pos == 2) && - (binascii_find_valid(ascii_data, ascii_len, 1) - != BASE64_PAD)) ) - { - continue; - } - else { - /* A pad sequence means no more input. - ** We've already interpreted the data - ** from the quad at this point. - */ - leftbits = 0; - break; - } - } - - this_ch = table_a2b_base64[*ascii_data]; - if ( this_ch == (unsigned char) -1 ) - continue; - - /* - ** Shift it in on the low end, and see if there's - ** a byte ready for output. - */ - quad_pos = (quad_pos + 1) & 0x03; - leftchar = (leftchar << 6) | (this_ch); - leftbits += 6; - - if ( leftbits >= 8 ) { - leftbits -= 8; - *bin_data++ = (leftchar >> leftbits) & 0xff; - bin_len++; - leftchar &= ((1 << leftbits) - 1); - } - } - - if (leftbits != 0) { - PyBuffer_Release(&pascii); - PyErr_SetString(Error, "Incorrect padding"); - Py_DECREF(rv); - return NULL; - } - - /* And set string size correctly. If the result string is empty - ** (because the input was all invalid) return the shared empty - ** string instead; _PyBytes_Resize() won't do this for us. - */ - if (bin_len > 0) { - if (_PyBytes_Resize(&rv, bin_len) < 0) { - Py_DECREF(rv); - rv = NULL; - } - } - else { - Py_DECREF(rv); - rv = PyBytes_FromStringAndSize("", 0); - } - PyBuffer_Release(&pascii); - return rv; + Py_buffer pascii; + unsigned char *ascii_data, *bin_data; + int leftbits = 0; + unsigned char this_ch; + unsigned int leftchar = 0; + PyObject *rv; + Py_ssize_t ascii_len, bin_len; + int quad_pos = 0; + + if ( !PyArg_ParseTuple(args, "y*:a2b_base64", &pascii) ) + return NULL; + ascii_data = pascii.buf; + ascii_len = pascii.len; + + assert(ascii_len >= 0); + + if (ascii_len > PY_SSIZE_T_MAX - 3) { + PyBuffer_Release(&pascii); + return PyErr_NoMemory(); + } + + bin_len = ((ascii_len+3)/4)*3; /* Upper bound, corrected later */ + + /* Allocate the buffer */ + if ( (rv=PyBytes_FromStringAndSize(NULL, bin_len)) == NULL ) { + PyBuffer_Release(&pascii); + return NULL; + } + bin_data = (unsigned char *)PyBytes_AS_STRING(rv); + bin_len = 0; + + for( ; ascii_len > 0; ascii_len--, ascii_data++) { + this_ch = *ascii_data; + + if (this_ch > 0x7f || + this_ch == '\r' || this_ch == '\n' || this_ch == ' ') + continue; + + /* Check for pad sequences and ignore + ** the invalid ones. + */ + if (this_ch == BASE64_PAD) { + if ( (quad_pos < 2) || + ((quad_pos == 2) && + (binascii_find_valid(ascii_data, ascii_len, 1) + != BASE64_PAD)) ) + { + continue; + } + else { + /* A pad sequence means no more input. + ** We've already interpreted the data + ** from the quad at this point. + */ + leftbits = 0; + break; + } + } + + this_ch = table_a2b_base64[*ascii_data]; + if ( this_ch == (unsigned char) -1 ) + continue; + + /* + ** Shift it in on the low end, and see if there's + ** a byte ready for output. + */ + quad_pos = (quad_pos + 1) & 0x03; + leftchar = (leftchar << 6) | (this_ch); + leftbits += 6; + + if ( leftbits >= 8 ) { + leftbits -= 8; + *bin_data++ = (leftchar >> leftbits) & 0xff; + bin_len++; + leftchar &= ((1 << leftbits) - 1); + } + } + + if (leftbits != 0) { + PyBuffer_Release(&pascii); + PyErr_SetString(Error, "Incorrect padding"); + Py_DECREF(rv); + return NULL; + } + + /* And set string size correctly. If the result string is empty + ** (because the input was all invalid) return the shared empty + ** string instead; _PyBytes_Resize() won't do this for us. + */ + if (bin_len > 0) { + if (_PyBytes_Resize(&rv, bin_len) < 0) { + Py_DECREF(rv); + rv = NULL; + } + } + else { + Py_DECREF(rv); + rv = PyBytes_FromStringAndSize("", 0); + } + PyBuffer_Release(&pascii); + return rv; } PyDoc_STRVAR(doc_b2a_base64, "(bin) -> ascii. Base64-code line of data"); @@ -470,66 +470,66 @@ static PyObject * binascii_b2a_base64(PyObject *self, PyObject *args) { - Py_buffer pbuf; - unsigned char *ascii_data, *bin_data; - int leftbits = 0; - unsigned char this_ch; - unsigned int leftchar = 0; - PyObject *rv; - Py_ssize_t bin_len; - - if ( !PyArg_ParseTuple(args, "y*:b2a_base64", &pbuf) ) - return NULL; - bin_data = pbuf.buf; - bin_len = pbuf.len; - - assert(bin_len >= 0); - - if ( bin_len > BASE64_MAXBIN ) { - PyErr_SetString(Error, "Too much data for base64 line"); - PyBuffer_Release(&pbuf); - return NULL; - } - - /* We're lazy and allocate too much (fixed up later). - "+3" leaves room for up to two pad characters and a trailing - newline. Note that 'b' gets encoded as 'Yg==\n' (1 in, 5 out). */ - if ( (rv=PyBytes_FromStringAndSize(NULL, bin_len*2 + 3)) == NULL ) { - PyBuffer_Release(&pbuf); - return NULL; - } - ascii_data = (unsigned char *)PyBytes_AS_STRING(rv); - - for( ; bin_len > 0 ; bin_len--, bin_data++ ) { - /* Shift the data into our buffer */ - leftchar = (leftchar << 8) | *bin_data; - leftbits += 8; - - /* See if there are 6-bit groups ready */ - while ( leftbits >= 6 ) { - this_ch = (leftchar >> (leftbits-6)) & 0x3f; - leftbits -= 6; - *ascii_data++ = table_b2a_base64[this_ch]; - } - } - if ( leftbits == 2 ) { - *ascii_data++ = table_b2a_base64[(leftchar&3) << 4]; - *ascii_data++ = BASE64_PAD; - *ascii_data++ = BASE64_PAD; - } else if ( leftbits == 4 ) { - *ascii_data++ = table_b2a_base64[(leftchar&0xf) << 2]; - *ascii_data++ = BASE64_PAD; - } - *ascii_data++ = '\n'; /* Append a courtesy newline */ - - if (_PyBytes_Resize(&rv, - (ascii_data - - (unsigned char *)PyBytes_AS_STRING(rv))) < 0) { - Py_DECREF(rv); - rv = NULL; - } - PyBuffer_Release(&pbuf); - return rv; + Py_buffer pbuf; + unsigned char *ascii_data, *bin_data; + int leftbits = 0; + unsigned char this_ch; + unsigned int leftchar = 0; + PyObject *rv; + Py_ssize_t bin_len; + + if ( !PyArg_ParseTuple(args, "y*:b2a_base64", &pbuf) ) + return NULL; + bin_data = pbuf.buf; + bin_len = pbuf.len; + + assert(bin_len >= 0); + + if ( bin_len > BASE64_MAXBIN ) { + PyErr_SetString(Error, "Too much data for base64 line"); + PyBuffer_Release(&pbuf); + return NULL; + } + + /* We're lazy and allocate too much (fixed up later). + "+3" leaves room for up to two pad characters and a trailing + newline. Note that 'b' gets encoded as 'Yg==\n' (1 in, 5 out). */ + if ( (rv=PyBytes_FromStringAndSize(NULL, bin_len*2 + 3)) == NULL ) { + PyBuffer_Release(&pbuf); + return NULL; + } + ascii_data = (unsigned char *)PyBytes_AS_STRING(rv); + + for( ; bin_len > 0 ; bin_len--, bin_data++ ) { + /* Shift the data into our buffer */ + leftchar = (leftchar << 8) | *bin_data; + leftbits += 8; + + /* See if there are 6-bit groups ready */ + while ( leftbits >= 6 ) { + this_ch = (leftchar >> (leftbits-6)) & 0x3f; + leftbits -= 6; + *ascii_data++ = table_b2a_base64[this_ch]; + } + } + if ( leftbits == 2 ) { + *ascii_data++ = table_b2a_base64[(leftchar&3) << 4]; + *ascii_data++ = BASE64_PAD; + *ascii_data++ = BASE64_PAD; + } else if ( leftbits == 4 ) { + *ascii_data++ = table_b2a_base64[(leftchar&0xf) << 2]; + *ascii_data++ = BASE64_PAD; + } + *ascii_data++ = '\n'; /* Append a courtesy newline */ + + if (_PyBytes_Resize(&rv, + (ascii_data - + (unsigned char *)PyBytes_AS_STRING(rv))) < 0) { + Py_DECREF(rv); + rv = NULL; + } + PyBuffer_Release(&pbuf); + return rv; } PyDoc_STRVAR(doc_a2b_hqx, "ascii -> bin, done. Decode .hqx coding"); @@ -537,85 +537,85 @@ static PyObject * binascii_a2b_hqx(PyObject *self, PyObject *args) { - Py_buffer pascii; - unsigned char *ascii_data, *bin_data; - int leftbits = 0; - unsigned char this_ch; - unsigned int leftchar = 0; - PyObject *rv; - Py_ssize_t len; - int done = 0; - - if ( !PyArg_ParseTuple(args, "s*:a2b_hqx", &pascii) ) - return NULL; - ascii_data = pascii.buf; - len = pascii.len; - - assert(len >= 0); - - if (len > PY_SSIZE_T_MAX - 2) { - PyBuffer_Release(&pascii); - return PyErr_NoMemory(); - } - - /* Allocate a string that is too big (fixed later) - Add two to the initial length to prevent interning which - would preclude subsequent resizing. */ - if ( (rv=PyBytes_FromStringAndSize(NULL, len+2)) == NULL ) { - PyBuffer_Release(&pascii); - return NULL; - } - bin_data = (unsigned char *)PyBytes_AS_STRING(rv); - - for( ; len > 0 ; len--, ascii_data++ ) { - /* Get the byte and look it up */ - this_ch = table_a2b_hqx[*ascii_data]; - if ( this_ch == SKIP ) - continue; - if ( this_ch == FAIL ) { - PyErr_SetString(Error, "Illegal char"); - PyBuffer_Release(&pascii); - Py_DECREF(rv); - return NULL; - } - if ( this_ch == DONE ) { - /* The terminating colon */ - done = 1; - break; - } - - /* Shift it into the buffer and see if any bytes are ready */ - leftchar = (leftchar << 6) | (this_ch); - leftbits += 6; - if ( leftbits >= 8 ) { - leftbits -= 8; - *bin_data++ = (leftchar >> leftbits) & 0xff; - leftchar &= ((1 << leftbits) - 1); - } - } - - if ( leftbits && !done ) { - PyErr_SetString(Incomplete, - "String has incomplete number of bytes"); - PyBuffer_Release(&pascii); - Py_DECREF(rv); - return NULL; - } - if (_PyBytes_Resize(&rv, - (bin_data - - (unsigned char *)PyBytes_AS_STRING(rv))) < 0) { - Py_DECREF(rv); - rv = NULL; - } - if (rv) { - PyObject *rrv = Py_BuildValue("Oi", rv, done); - PyBuffer_Release(&pascii); - Py_DECREF(rv); - return rrv; - } + Py_buffer pascii; + unsigned char *ascii_data, *bin_data; + int leftbits = 0; + unsigned char this_ch; + unsigned int leftchar = 0; + PyObject *rv; + Py_ssize_t len; + int done = 0; + + if ( !PyArg_ParseTuple(args, "s*:a2b_hqx", &pascii) ) + return NULL; + ascii_data = pascii.buf; + len = pascii.len; + + assert(len >= 0); + + if (len > PY_SSIZE_T_MAX - 2) { + PyBuffer_Release(&pascii); + return PyErr_NoMemory(); + } + + /* Allocate a string that is too big (fixed later) + Add two to the initial length to prevent interning which + would preclude subsequent resizing. */ + if ( (rv=PyBytes_FromStringAndSize(NULL, len+2)) == NULL ) { + PyBuffer_Release(&pascii); + return NULL; + } + bin_data = (unsigned char *)PyBytes_AS_STRING(rv); + + for( ; len > 0 ; len--, ascii_data++ ) { + /* Get the byte and look it up */ + this_ch = table_a2b_hqx[*ascii_data]; + if ( this_ch == SKIP ) + continue; + if ( this_ch == FAIL ) { + PyErr_SetString(Error, "Illegal char"); + PyBuffer_Release(&pascii); + Py_DECREF(rv); + return NULL; + } + if ( this_ch == DONE ) { + /* The terminating colon */ + done = 1; + break; + } + + /* Shift it into the buffer and see if any bytes are ready */ + leftchar = (leftchar << 6) | (this_ch); + leftbits += 6; + if ( leftbits >= 8 ) { + leftbits -= 8; + *bin_data++ = (leftchar >> leftbits) & 0xff; + leftchar &= ((1 << leftbits) - 1); + } + } + + if ( leftbits && !done ) { + PyErr_SetString(Incomplete, + "String has incomplete number of bytes"); + PyBuffer_Release(&pascii); + Py_DECREF(rv); + return NULL; + } + if (_PyBytes_Resize(&rv, + (bin_data - + (unsigned char *)PyBytes_AS_STRING(rv))) < 0) { + Py_DECREF(rv); + rv = NULL; + } + if (rv) { + PyObject *rrv = Py_BuildValue("Oi", rv, done); + PyBuffer_Release(&pascii); + Py_DECREF(rv); + return rrv; + } - PyBuffer_Release(&pascii); - return NULL; + PyBuffer_Release(&pascii); + return NULL; } PyDoc_STRVAR(doc_rlecode_hqx, "Binhex RLE-code binary data"); @@ -623,63 +623,63 @@ static PyObject * binascii_rlecode_hqx(PyObject *self, PyObject *args) { - Py_buffer pbuf; - unsigned char *in_data, *out_data; - PyObject *rv; - unsigned char ch; - Py_ssize_t in, inend, len; - - if ( !PyArg_ParseTuple(args, "y*:rlecode_hqx", &pbuf) ) - return NULL; - in_data = pbuf.buf; - len = pbuf.len; - - assert(len >= 0); - - if (len > PY_SSIZE_T_MAX / 2 - 2) { - PyBuffer_Release(&pbuf); - return PyErr_NoMemory(); - } - - /* Worst case: output is twice as big as input (fixed later) */ - if ( (rv=PyBytes_FromStringAndSize(NULL, len*2+2)) == NULL ) { - PyBuffer_Release(&pbuf); - return NULL; - } - out_data = (unsigned char *)PyBytes_AS_STRING(rv); - - for( in=0; in 3 ) { - /* More than 3 in a row. Output RLE. */ - *out_data++ = ch; - *out_data++ = RUNCHAR; - *out_data++ = inend-in; - in = inend-1; - } else { - /* Less than 3. Output the byte itself */ - *out_data++ = ch; - } - } - } - if (_PyBytes_Resize(&rv, - (out_data - - (unsigned char *)PyBytes_AS_STRING(rv))) < 0) { - Py_DECREF(rv); - rv = NULL; - } - PyBuffer_Release(&pbuf); - return rv; + Py_buffer pbuf; + unsigned char *in_data, *out_data; + PyObject *rv; + unsigned char ch; + Py_ssize_t in, inend, len; + + if ( !PyArg_ParseTuple(args, "y*:rlecode_hqx", &pbuf) ) + return NULL; + in_data = pbuf.buf; + len = pbuf.len; + + assert(len >= 0); + + if (len > PY_SSIZE_T_MAX / 2 - 2) { + PyBuffer_Release(&pbuf); + return PyErr_NoMemory(); + } + + /* Worst case: output is twice as big as input (fixed later) */ + if ( (rv=PyBytes_FromStringAndSize(NULL, len*2+2)) == NULL ) { + PyBuffer_Release(&pbuf); + return NULL; + } + out_data = (unsigned char *)PyBytes_AS_STRING(rv); + + for( in=0; in 3 ) { + /* More than 3 in a row. Output RLE. */ + *out_data++ = ch; + *out_data++ = RUNCHAR; + *out_data++ = inend-in; + in = inend-1; + } else { + /* Less than 3. Output the byte itself */ + *out_data++ = ch; + } + } + } + if (_PyBytes_Resize(&rv, + (out_data - + (unsigned char *)PyBytes_AS_STRING(rv))) < 0) { + Py_DECREF(rv); + rv = NULL; + } + PyBuffer_Release(&pbuf); + return rv; } PyDoc_STRVAR(doc_b2a_hqx, "Encode .hqx data"); @@ -687,56 +687,56 @@ static PyObject * binascii_b2a_hqx(PyObject *self, PyObject *args) { - Py_buffer pbin; - unsigned char *ascii_data, *bin_data; - int leftbits = 0; - unsigned char this_ch; - unsigned int leftchar = 0; - PyObject *rv; - Py_ssize_t len; - - if ( !PyArg_ParseTuple(args, "y*:b2a_hqx", &pbin) ) - return NULL; - bin_data = pbin.buf; - len = pbin.len; - - assert(len >= 0); - - if (len > PY_SSIZE_T_MAX / 2 - 2) { - PyBuffer_Release(&pbin); - return PyErr_NoMemory(); - } - - /* Allocate a buffer that is at least large enough */ - if ( (rv=PyBytes_FromStringAndSize(NULL, len*2+2)) == NULL ) { - PyBuffer_Release(&pbin); - return NULL; - } - ascii_data = (unsigned char *)PyBytes_AS_STRING(rv); - - for( ; len > 0 ; len--, bin_data++ ) { - /* Shift into our buffer, and output any 6bits ready */ - leftchar = (leftchar << 8) | *bin_data; - leftbits += 8; - while ( leftbits >= 6 ) { - this_ch = (leftchar >> (leftbits-6)) & 0x3f; - leftbits -= 6; - *ascii_data++ = table_b2a_hqx[this_ch]; - } - } - /* Output a possible runt byte */ - if ( leftbits ) { - leftchar <<= (6-leftbits); - *ascii_data++ = table_b2a_hqx[leftchar & 0x3f]; - } - if (_PyBytes_Resize(&rv, - (ascii_data - - (unsigned char *)PyBytes_AS_STRING(rv))) < 0) { - Py_DECREF(rv); - rv = NULL; - } - PyBuffer_Release(&pbin); - return rv; + Py_buffer pbin; + unsigned char *ascii_data, *bin_data; + int leftbits = 0; + unsigned char this_ch; + unsigned int leftchar = 0; + PyObject *rv; + Py_ssize_t len; + + if ( !PyArg_ParseTuple(args, "y*:b2a_hqx", &pbin) ) + return NULL; + bin_data = pbin.buf; + len = pbin.len; + + assert(len >= 0); + + if (len > PY_SSIZE_T_MAX / 2 - 2) { + PyBuffer_Release(&pbin); + return PyErr_NoMemory(); + } + + /* Allocate a buffer that is at least large enough */ + if ( (rv=PyBytes_FromStringAndSize(NULL, len*2+2)) == NULL ) { + PyBuffer_Release(&pbin); + return NULL; + } + ascii_data = (unsigned char *)PyBytes_AS_STRING(rv); + + for( ; len > 0 ; len--, bin_data++ ) { + /* Shift into our buffer, and output any 6bits ready */ + leftchar = (leftchar << 8) | *bin_data; + leftbits += 8; + while ( leftbits >= 6 ) { + this_ch = (leftchar >> (leftbits-6)) & 0x3f; + leftbits -= 6; + *ascii_data++ = table_b2a_hqx[this_ch]; + } + } + /* Output a possible runt byte */ + if ( leftbits ) { + leftchar <<= (6-leftbits); + *ascii_data++ = table_b2a_hqx[leftchar & 0x3f]; + } + if (_PyBytes_Resize(&rv, + (ascii_data - + (unsigned char *)PyBytes_AS_STRING(rv))) < 0) { + Py_DECREF(rv); + rv = NULL; + } + PyBuffer_Release(&pbin); + return rv; } PyDoc_STRVAR(doc_rledecode_hqx, "Decode hexbin RLE-coded string"); @@ -744,116 +744,116 @@ static PyObject * binascii_rledecode_hqx(PyObject *self, PyObject *args) { - Py_buffer pin; - unsigned char *in_data, *out_data; - unsigned char in_byte, in_repeat; - PyObject *rv; - Py_ssize_t in_len, out_len, out_len_left; - - if ( !PyArg_ParseTuple(args, "s*:rledecode_hqx", &pin) ) - return NULL; - in_data = pin.buf; - in_len = pin.len; - - assert(in_len >= 0); - - /* Empty string is a special case */ - if ( in_len == 0 ) { - PyBuffer_Release(&pin); - return PyBytes_FromStringAndSize("", 0); - } - else if (in_len > PY_SSIZE_T_MAX / 2) { - PyBuffer_Release(&pin); - return PyErr_NoMemory(); - } - - /* Allocate a buffer of reasonable size. Resized when needed */ - out_len = in_len*2; - if ( (rv=PyBytes_FromStringAndSize(NULL, out_len)) == NULL ) { - PyBuffer_Release(&pin); - return NULL; - } - out_len_left = out_len; - out_data = (unsigned char *)PyBytes_AS_STRING(rv); - - /* - ** We need two macros here to get/put bytes and handle - ** end-of-buffer for input and output strings. - */ + Py_buffer pin; + unsigned char *in_data, *out_data; + unsigned char in_byte, in_repeat; + PyObject *rv; + Py_ssize_t in_len, out_len, out_len_left; + + if ( !PyArg_ParseTuple(args, "s*:rledecode_hqx", &pin) ) + return NULL; + in_data = pin.buf; + in_len = pin.len; + + assert(in_len >= 0); + + /* Empty string is a special case */ + if ( in_len == 0 ) { + PyBuffer_Release(&pin); + return PyBytes_FromStringAndSize("", 0); + } + else if (in_len > PY_SSIZE_T_MAX / 2) { + PyBuffer_Release(&pin); + return PyErr_NoMemory(); + } + + /* Allocate a buffer of reasonable size. Resized when needed */ + out_len = in_len*2; + if ( (rv=PyBytes_FromStringAndSize(NULL, out_len)) == NULL ) { + PyBuffer_Release(&pin); + return NULL; + } + out_len_left = out_len; + out_data = (unsigned char *)PyBytes_AS_STRING(rv); + + /* + ** We need two macros here to get/put bytes and handle + ** end-of-buffer for input and output strings. + */ #define INBYTE(b) \ - do { \ - if ( --in_len < 0 ) { \ - PyErr_SetString(Incomplete, ""); \ - Py_DECREF(rv); \ - PyBuffer_Release(&pin); \ - return NULL; \ - } \ - b = *in_data++; \ - } while(0) + do { \ + if ( --in_len < 0 ) { \ + PyErr_SetString(Incomplete, ""); \ + Py_DECREF(rv); \ + PyBuffer_Release(&pin); \ + return NULL; \ + } \ + b = *in_data++; \ + } while(0) #define OUTBYTE(b) \ - do { \ - if ( --out_len_left < 0 ) { \ - if ( out_len > PY_SSIZE_T_MAX / 2) return PyErr_NoMemory(); \ - if (_PyBytes_Resize(&rv, 2*out_len) < 0) \ - { Py_DECREF(rv); PyBuffer_Release(&pin); return NULL; } \ - out_data = (unsigned char *)PyBytes_AS_STRING(rv) \ - + out_len; \ - out_len_left = out_len-1; \ - out_len = out_len * 2; \ - } \ - *out_data++ = b; \ - } while(0) - - /* - ** Handle first byte separately (since we have to get angry - ** in case of an orphaned RLE code). - */ - INBYTE(in_byte); - - if (in_byte == RUNCHAR) { - INBYTE(in_repeat); - if (in_repeat != 0) { - /* Note Error, not Incomplete (which is at the end - ** of the string only). This is a programmer error. - */ - PyErr_SetString(Error, "Orphaned RLE code at start"); - PyBuffer_Release(&pin); - Py_DECREF(rv); - return NULL; - } - OUTBYTE(RUNCHAR); - } else { - OUTBYTE(in_byte); - } - - while( in_len > 0 ) { - INBYTE(in_byte); - - if (in_byte == RUNCHAR) { - INBYTE(in_repeat); - if ( in_repeat == 0 ) { - /* Just an escaped RUNCHAR value */ - OUTBYTE(RUNCHAR); - } else { - /* Pick up value and output a sequence of it */ - in_byte = out_data[-1]; - while ( --in_repeat > 0 ) - OUTBYTE(in_byte); - } - } else { - /* Normal byte */ - OUTBYTE(in_byte); - } - } - if (_PyBytes_Resize(&rv, - (out_data - - (unsigned char *)PyBytes_AS_STRING(rv))) < 0) { - Py_DECREF(rv); - rv = NULL; - } - PyBuffer_Release(&pin); - return rv; + do { \ + if ( --out_len_left < 0 ) { \ + if ( out_len > PY_SSIZE_T_MAX / 2) return PyErr_NoMemory(); \ + if (_PyBytes_Resize(&rv, 2*out_len) < 0) \ + { Py_DECREF(rv); PyBuffer_Release(&pin); return NULL; } \ + out_data = (unsigned char *)PyBytes_AS_STRING(rv) \ + + out_len; \ + out_len_left = out_len-1; \ + out_len = out_len * 2; \ + } \ + *out_data++ = b; \ + } while(0) + + /* + ** Handle first byte separately (since we have to get angry + ** in case of an orphaned RLE code). + */ + INBYTE(in_byte); + + if (in_byte == RUNCHAR) { + INBYTE(in_repeat); + if (in_repeat != 0) { + /* Note Error, not Incomplete (which is at the end + ** of the string only). This is a programmer error. + */ + PyErr_SetString(Error, "Orphaned RLE code at start"); + PyBuffer_Release(&pin); + Py_DECREF(rv); + return NULL; + } + OUTBYTE(RUNCHAR); + } else { + OUTBYTE(in_byte); + } + + while( in_len > 0 ) { + INBYTE(in_byte); + + if (in_byte == RUNCHAR) { + INBYTE(in_repeat); + if ( in_repeat == 0 ) { + /* Just an escaped RUNCHAR value */ + OUTBYTE(RUNCHAR); + } else { + /* Pick up value and output a sequence of it */ + in_byte = out_data[-1]; + while ( --in_repeat > 0 ) + OUTBYTE(in_byte); + } + } else { + /* Normal byte */ + OUTBYTE(in_byte); + } + } + if (_PyBytes_Resize(&rv, + (out_data - + (unsigned char *)PyBytes_AS_STRING(rv))) < 0) { + Py_DECREF(rv); + rv = NULL; + } + PyBuffer_Release(&pin); + return rv; } PyDoc_STRVAR(doc_crc_hqx, @@ -862,22 +862,22 @@ static PyObject * binascii_crc_hqx(PyObject *self, PyObject *args) { - Py_buffer pin; - unsigned char *bin_data; - unsigned int crc; - Py_ssize_t len; - - if ( !PyArg_ParseTuple(args, "y*i:crc_hqx", &pin, &crc) ) - return NULL; - bin_data = pin.buf; - len = pin.len; - - while(len-- > 0) { - crc=((crc<<8)&0xff00)^crctab_hqx[((crc>>8)&0xff)^*bin_data++]; - } + Py_buffer pin; + unsigned char *bin_data; + unsigned int crc; + Py_ssize_t len; - PyBuffer_Release(&pin); - return Py_BuildValue("i", crc); + if ( !PyArg_ParseTuple(args, "y*i:crc_hqx", &pin, &crc) ) + return NULL; + bin_data = pin.buf; + len = pin.len; + + while(len-- > 0) { + crc=((crc<<8)&0xff00)^crctab_hqx[((crc>>8)&0xff)^*bin_data++]; + } + + PyBuffer_Release(&pin); + return Py_BuildValue("i", crc); } PyDoc_STRVAR(doc_crc32, @@ -895,7 +895,7 @@ int signed_val; if (!PyArg_ParseTuple(args, "y*|I:crc32", &pbuf, &crc32val)) - return NULL; + return NULL; buf = (Byte*)pbuf.buf; len = pbuf.len; signed_val = crc32(crc32val, buf, len); @@ -1024,26 +1024,26 @@ static PyObject * binascii_crc32(PyObject *self, PyObject *args) { /* By Jim Ahlstrom; All rights transferred to CNRI */ - Py_buffer pbin; - unsigned char *bin_data; - unsigned int crc = 0; /* initial value of CRC */ - Py_ssize_t len; - unsigned int result; - - if ( !PyArg_ParseTuple(args, "y*|I:crc32", &pbin, &crc) ) - return NULL; - bin_data = pbin.buf; - len = pbin.len; - - crc = ~ crc; - while (len-- > 0) { - crc = crc_32_tab[(crc ^ *bin_data++) & 0xff] ^ (crc >> 8); - /* Note: (crc >> 8) MUST zero fill on left */ - } - - result = (crc ^ 0xFFFFFFFF); - PyBuffer_Release(&pbin); - return PyLong_FromUnsignedLong(result & 0xffffffff); + Py_buffer pbin; + unsigned char *bin_data; + unsigned int crc = 0; /* initial value of CRC */ + Py_ssize_t len; + unsigned int result; + + if ( !PyArg_ParseTuple(args, "y*|I:crc32", &pbin, &crc) ) + return NULL; + bin_data = pbin.buf; + len = pbin.len; + + crc = ~ crc; + while (len-- > 0) { + crc = crc_32_tab[(crc ^ *bin_data++) & 0xff] ^ (crc >> 8); + /* Note: (crc >> 8) MUST zero fill on left */ + } + + result = (crc ^ 0xFFFFFFFF); + PyBuffer_Release(&pbin); + return PyLong_FromUnsignedLong(result & 0xffffffff); } #endif /* USE_ZLIB_CRC32 */ @@ -1051,43 +1051,43 @@ static PyObject * binascii_hexlify(PyObject *self, PyObject *args) { - Py_buffer parg; - char* argbuf; - Py_ssize_t arglen; - PyObject *retval; - char* retbuf; - Py_ssize_t i, j; - - if (!PyArg_ParseTuple(args, "y*:b2a_hex", &parg)) - return NULL; - argbuf = parg.buf; - arglen = parg.len; - - assert(arglen >= 0); - if (arglen > PY_SSIZE_T_MAX / 2) { - PyBuffer_Release(&parg); - return PyErr_NoMemory(); - } - - retval = PyBytes_FromStringAndSize(NULL, arglen*2); - if (!retval) { - PyBuffer_Release(&parg); - return NULL; - } - retbuf = PyBytes_AS_STRING(retval); - - /* make hex version of string, taken from shamodule.c */ - for (i=j=0; i < arglen; i++) { - char c; - c = (argbuf[i] >> 4) & 0xf; - c = (c>9) ? c+'a'-10 : c + '0'; - retbuf[j++] = c; - c = argbuf[i] & 0xf; - c = (c>9) ? c+'a'-10 : c + '0'; - retbuf[j++] = c; - } - PyBuffer_Release(&parg); - return retval; + Py_buffer parg; + char* argbuf; + Py_ssize_t arglen; + PyObject *retval; + char* retbuf; + Py_ssize_t i, j; + + if (!PyArg_ParseTuple(args, "y*:b2a_hex", &parg)) + return NULL; + argbuf = parg.buf; + arglen = parg.len; + + assert(arglen >= 0); + if (arglen > PY_SSIZE_T_MAX / 2) { + PyBuffer_Release(&parg); + return PyErr_NoMemory(); + } + + retval = PyBytes_FromStringAndSize(NULL, arglen*2); + if (!retval) { + PyBuffer_Release(&parg); + return NULL; + } + retbuf = PyBytes_AS_STRING(retval); + + /* make hex version of string, taken from shamodule.c */ + for (i=j=0; i < arglen; i++) { + char c; + c = (argbuf[i] >> 4) & 0xf; + c = (c>9) ? c+'a'-10 : c + '0'; + retbuf[j++] = c; + c = argbuf[i] & 0xf; + c = (c>9) ? c+'a'-10 : c + '0'; + retbuf[j++] = c; + } + PyBuffer_Release(&parg); + return retval; } PyDoc_STRVAR(doc_hexlify, @@ -1099,69 +1099,69 @@ static int to_int(int c) { - if (isdigit(c)) - return c - '0'; - else { - if (isupper(c)) - c = tolower(c); - if (c >= 'a' && c <= 'f') - return c - 'a' + 10; - } - return -1; + if (isdigit(c)) + return c - '0'; + else { + if (isupper(c)) + c = tolower(c); + if (c >= 'a' && c <= 'f') + return c - 'a' + 10; + } + return -1; } static PyObject * binascii_unhexlify(PyObject *self, PyObject *args) { - Py_buffer parg; - char* argbuf; - Py_ssize_t arglen; - PyObject *retval; - char* retbuf; - Py_ssize_t i, j; - - if (!PyArg_ParseTuple(args, "s*:a2b_hex", &parg)) - return NULL; - argbuf = parg.buf; - arglen = parg.len; - - assert(arglen >= 0); - - /* XXX What should we do about strings with an odd length? Should - * we add an implicit leading zero, or a trailing zero? For now, - * raise an exception. - */ - if (arglen % 2) { - PyBuffer_Release(&parg); - PyErr_SetString(Error, "Odd-length string"); - return NULL; - } - - retval = PyBytes_FromStringAndSize(NULL, (arglen/2)); - if (!retval) { - PyBuffer_Release(&parg); - return NULL; - } - retbuf = PyBytes_AS_STRING(retval); - - for (i=j=0; i < arglen; i += 2) { - int top = to_int(Py_CHARMASK(argbuf[i])); - int bot = to_int(Py_CHARMASK(argbuf[i+1])); - if (top == -1 || bot == -1) { - PyErr_SetString(Error, - "Non-hexadecimal digit found"); - goto finally; - } - retbuf[j++] = (top << 4) + bot; - } - PyBuffer_Release(&parg); - return retval; + Py_buffer parg; + char* argbuf; + Py_ssize_t arglen; + PyObject *retval; + char* retbuf; + Py_ssize_t i, j; + + if (!PyArg_ParseTuple(args, "s*:a2b_hex", &parg)) + return NULL; + argbuf = parg.buf; + arglen = parg.len; + + assert(arglen >= 0); + + /* XXX What should we do about strings with an odd length? Should + * we add an implicit leading zero, or a trailing zero? For now, + * raise an exception. + */ + if (arglen % 2) { + PyBuffer_Release(&parg); + PyErr_SetString(Error, "Odd-length string"); + return NULL; + } + + retval = PyBytes_FromStringAndSize(NULL, (arglen/2)); + if (!retval) { + PyBuffer_Release(&parg); + return NULL; + } + retbuf = PyBytes_AS_STRING(retval); + + for (i=j=0; i < arglen; i += 2) { + int top = to_int(Py_CHARMASK(argbuf[i])); + int bot = to_int(Py_CHARMASK(argbuf[i+1])); + if (top == -1 || bot == -1) { + PyErr_SetString(Error, + "Non-hexadecimal digit found"); + goto finally; + } + retbuf[j++] = (top << 4) + bot; + } + PyBuffer_Release(&parg); + return retval; finally: - PyBuffer_Release(&parg); - Py_DECREF(retval); - return NULL; + PyBuffer_Release(&parg); + Py_DECREF(retval); + return NULL; } PyDoc_STRVAR(doc_unhexlify, @@ -1190,96 +1190,96 @@ static PyObject* binascii_a2b_qp(PyObject *self, PyObject *args, PyObject *kwargs) { - Py_ssize_t in, out; - char ch; - Py_buffer pdata; - unsigned char *data, *odata; - Py_ssize_t datalen = 0; - PyObject *rv; - static char *kwlist[] = {"data", "header", NULL}; - int header = 0; - - if (!PyArg_ParseTupleAndKeywords(args, kwargs, "s*|i", kwlist, &pdata, - &header)) - return NULL; - data = pdata.buf; - datalen = pdata.len; - - /* We allocate the output same size as input, this is overkill. - * The previous implementation used calloc() so we'll zero out the - * memory here too, since PyMem_Malloc() does not guarantee that. - */ - odata = (unsigned char *) PyMem_Malloc(datalen); - if (odata == NULL) { - PyBuffer_Release(&pdata); - PyErr_NoMemory(); - return NULL; - } - memset(odata, 0, datalen); - - in = out = 0; - while (in < datalen) { - if (data[in] == '=') { - in++; - if (in >= datalen) break; - /* Soft line breaks */ - if ((data[in] == '\n') || (data[in] == '\r')) { - if (data[in] != '\n') { - while (in < datalen && data[in] != '\n') in++; - } - if (in < datalen) in++; - } - else if (data[in] == '=') { - /* broken case from broken python qp */ - odata[out++] = '='; - in++; - } - else if (((data[in] >= 'A' && data[in] <= 'F') || - (data[in] >= 'a' && data[in] <= 'f') || - (data[in] >= '0' && data[in] <= '9')) && - ((data[in+1] >= 'A' && data[in+1] <= 'F') || - (data[in+1] >= 'a' && data[in+1] <= 'f') || - (data[in+1] >= '0' && data[in+1] <= '9'))) { - /* hexval */ - ch = hexval(data[in]) << 4; - in++; - ch |= hexval(data[in]); - in++; - odata[out++] = ch; - } - else { - odata[out++] = '='; - } - } - else if (header && data[in] == '_') { - odata[out++] = ' '; - in++; - } - else { - odata[out] = data[in]; - in++; - out++; - } - } - if ((rv = PyBytes_FromStringAndSize((char *)odata, out)) == NULL) { - PyBuffer_Release(&pdata); - PyMem_Free(odata); - return NULL; - } - PyBuffer_Release(&pdata); - PyMem_Free(odata); - return rv; + Py_ssize_t in, out; + char ch; + Py_buffer pdata; + unsigned char *data, *odata; + Py_ssize_t datalen = 0; + PyObject *rv; + static char *kwlist[] = {"data", "header", NULL}; + int header = 0; + + if (!PyArg_ParseTupleAndKeywords(args, kwargs, "s*|i", kwlist, &pdata, + &header)) + return NULL; + data = pdata.buf; + datalen = pdata.len; + + /* We allocate the output same size as input, this is overkill. + * The previous implementation used calloc() so we'll zero out the + * memory here too, since PyMem_Malloc() does not guarantee that. + */ + odata = (unsigned char *) PyMem_Malloc(datalen); + if (odata == NULL) { + PyBuffer_Release(&pdata); + PyErr_NoMemory(); + return NULL; + } + memset(odata, 0, datalen); + + in = out = 0; + while (in < datalen) { + if (data[in] == '=') { + in++; + if (in >= datalen) break; + /* Soft line breaks */ + if ((data[in] == '\n') || (data[in] == '\r')) { + if (data[in] != '\n') { + while (in < datalen && data[in] != '\n') in++; + } + if (in < datalen) in++; + } + else if (data[in] == '=') { + /* broken case from broken python qp */ + odata[out++] = '='; + in++; + } + else if (((data[in] >= 'A' && data[in] <= 'F') || + (data[in] >= 'a' && data[in] <= 'f') || + (data[in] >= '0' && data[in] <= '9')) && + ((data[in+1] >= 'A' && data[in+1] <= 'F') || + (data[in+1] >= 'a' && data[in+1] <= 'f') || + (data[in+1] >= '0' && data[in+1] <= '9'))) { + /* hexval */ + ch = hexval(data[in]) << 4; + in++; + ch |= hexval(data[in]); + in++; + odata[out++] = ch; + } + else { + odata[out++] = '='; + } + } + else if (header && data[in] == '_') { + odata[out++] = ' '; + in++; + } + else { + odata[out] = data[in]; + in++; + out++; + } + } + if ((rv = PyBytes_FromStringAndSize((char *)odata, out)) == NULL) { + PyBuffer_Release(&pdata); + PyMem_Free(odata); + return NULL; + } + PyBuffer_Release(&pdata); + PyMem_Free(odata); + return rv; } static int to_hex (unsigned char ch, unsigned char *s) { - unsigned int uvalue = ch; + unsigned int uvalue = ch; - s[1] = "0123456789ABCDEF"[uvalue % 16]; - uvalue = (uvalue / 16); - s[0] = "0123456789ABCDEF"[uvalue % 16]; - return 0; + s[1] = "0123456789ABCDEF"[uvalue % 16]; + uvalue = (uvalue / 16); + s[0] = "0123456789ABCDEF"[uvalue % 16]; + return 0; } PyDoc_STRVAR(doc_b2a_qp, @@ -1296,210 +1296,210 @@ static PyObject* binascii_b2a_qp (PyObject *self, PyObject *args, PyObject *kwargs) { - Py_ssize_t in, out; - Py_buffer pdata; - unsigned char *data, *odata; - Py_ssize_t datalen = 0, odatalen = 0; - PyObject *rv; - unsigned int linelen = 0; - static char *kwlist[] = {"data", "quotetabs", "istext", - "header", NULL}; - int istext = 1; - int quotetabs = 0; - int header = 0; - unsigned char ch; - int crlf = 0; - unsigned char *p; - - if (!PyArg_ParseTupleAndKeywords(args, kwargs, "y*|iii", kwlist, &pdata, - "etabs, &istext, &header)) - return NULL; - data = pdata.buf; - datalen = pdata.len; - - /* See if this string is using CRLF line ends */ - /* XXX: this function has the side effect of converting all of - * the end of lines to be the same depending on this detection - * here */ - p = (unsigned char *) memchr(data, '\n', datalen); - if ((p != NULL) && (p > data) && (*(p-1) == '\r')) - crlf = 1; - - /* First, scan to see how many characters need to be encoded */ - in = 0; - while (in < datalen) { - if ((data[in] > 126) || - (data[in] == '=') || - (header && data[in] == '_') || - ((data[in] == '.') && (linelen == 0) && - (data[in+1] == '\n' || data[in+1] == '\r' || data[in+1] == 0)) || - (!istext && ((data[in] == '\r') || (data[in] == '\n'))) || - ((data[in] == '\t' || data[in] == ' ') && (in + 1 == datalen)) || - ((data[in] < 33) && - (data[in] != '\r') && (data[in] != '\n') && - (quotetabs || - (!quotetabs && ((data[in] != '\t') && (data[in] != ' ')))))) - { - if ((linelen + 3) >= MAXLINESIZE) { - linelen = 0; - if (crlf) - odatalen += 3; - else - odatalen += 2; - } - linelen += 3; - odatalen += 3; - in++; - } - else { - if (istext && - ((data[in] == '\n') || - ((in+1 < datalen) && (data[in] == '\r') && - (data[in+1] == '\n')))) - { - linelen = 0; - /* Protect against whitespace on end of line */ - if (in && ((data[in-1] == ' ') || (data[in-1] == '\t'))) - odatalen += 2; - if (crlf) - odatalen += 2; - else - odatalen += 1; - if (data[in] == '\r') - in += 2; - else - in++; - } - else { - if ((in + 1 != datalen) && - (data[in+1] != '\n') && - (linelen + 1) >= MAXLINESIZE) { - linelen = 0; - if (crlf) - odatalen += 3; - else - odatalen += 2; - } - linelen++; - odatalen++; - in++; - } - } - } - - /* We allocate the output same size as input, this is overkill. - * The previous implementation used calloc() so we'll zero out the - * memory here too, since PyMem_Malloc() does not guarantee that. - */ - odata = (unsigned char *) PyMem_Malloc(odatalen); - if (odata == NULL) { - PyBuffer_Release(&pdata); - PyErr_NoMemory(); - return NULL; - } - memset(odata, 0, odatalen); - - in = out = linelen = 0; - while (in < datalen) { - if ((data[in] > 126) || - (data[in] == '=') || - (header && data[in] == '_') || - ((data[in] == '.') && (linelen == 0) && - (data[in+1] == '\n' || data[in+1] == '\r' || data[in+1] == 0)) || - (!istext && ((data[in] == '\r') || (data[in] == '\n'))) || - ((data[in] == '\t' || data[in] == ' ') && (in + 1 == datalen)) || - ((data[in] < 33) && - (data[in] != '\r') && (data[in] != '\n') && - (quotetabs || - (!quotetabs && ((data[in] != '\t') && (data[in] != ' ')))))) - { - if ((linelen + 3 )>= MAXLINESIZE) { - odata[out++] = '='; - if (crlf) odata[out++] = '\r'; - odata[out++] = '\n'; - linelen = 0; - } - odata[out++] = '='; - to_hex(data[in], &odata[out]); - out += 2; - in++; - linelen += 3; - } - else { - if (istext && - ((data[in] == '\n') || - ((in+1 < datalen) && (data[in] == '\r') && - (data[in+1] == '\n')))) - { - linelen = 0; - /* Protect against whitespace on end of line */ - if (out && ((odata[out-1] == ' ') || (odata[out-1] == '\t'))) { - ch = odata[out-1]; - odata[out-1] = '='; - to_hex(ch, &odata[out]); - out += 2; - } - - if (crlf) odata[out++] = '\r'; - odata[out++] = '\n'; - if (data[in] == '\r') - in += 2; - else - in++; - } - else { - if ((in + 1 != datalen) && - (data[in+1] != '\n') && - (linelen + 1) >= MAXLINESIZE) { - odata[out++] = '='; - if (crlf) odata[out++] = '\r'; - odata[out++] = '\n'; - linelen = 0; - } - linelen++; - if (header && data[in] == ' ') { - odata[out++] = '_'; - in++; - } - else { - odata[out++] = data[in++]; - } - } - } - } - if ((rv = PyBytes_FromStringAndSize((char *)odata, out)) == NULL) { - PyBuffer_Release(&pdata); - PyMem_Free(odata); - return NULL; - } - PyBuffer_Release(&pdata); - PyMem_Free(odata); - return rv; + Py_ssize_t in, out; + Py_buffer pdata; + unsigned char *data, *odata; + Py_ssize_t datalen = 0, odatalen = 0; + PyObject *rv; + unsigned int linelen = 0; + static char *kwlist[] = {"data", "quotetabs", "istext", + "header", NULL}; + int istext = 1; + int quotetabs = 0; + int header = 0; + unsigned char ch; + int crlf = 0; + unsigned char *p; + + if (!PyArg_ParseTupleAndKeywords(args, kwargs, "y*|iii", kwlist, &pdata, + "etabs, &istext, &header)) + return NULL; + data = pdata.buf; + datalen = pdata.len; + + /* See if this string is using CRLF line ends */ + /* XXX: this function has the side effect of converting all of + * the end of lines to be the same depending on this detection + * here */ + p = (unsigned char *) memchr(data, '\n', datalen); + if ((p != NULL) && (p > data) && (*(p-1) == '\r')) + crlf = 1; + + /* First, scan to see how many characters need to be encoded */ + in = 0; + while (in < datalen) { + if ((data[in] > 126) || + (data[in] == '=') || + (header && data[in] == '_') || + ((data[in] == '.') && (linelen == 0) && + (data[in+1] == '\n' || data[in+1] == '\r' || data[in+1] == 0)) || + (!istext && ((data[in] == '\r') || (data[in] == '\n'))) || + ((data[in] == '\t' || data[in] == ' ') && (in + 1 == datalen)) || + ((data[in] < 33) && + (data[in] != '\r') && (data[in] != '\n') && + (quotetabs || + (!quotetabs && ((data[in] != '\t') && (data[in] != ' ')))))) + { + if ((linelen + 3) >= MAXLINESIZE) { + linelen = 0; + if (crlf) + odatalen += 3; + else + odatalen += 2; + } + linelen += 3; + odatalen += 3; + in++; + } + else { + if (istext && + ((data[in] == '\n') || + ((in+1 < datalen) && (data[in] == '\r') && + (data[in+1] == '\n')))) + { + linelen = 0; + /* Protect against whitespace on end of line */ + if (in && ((data[in-1] == ' ') || (data[in-1] == '\t'))) + odatalen += 2; + if (crlf) + odatalen += 2; + else + odatalen += 1; + if (data[in] == '\r') + in += 2; + else + in++; + } + else { + if ((in + 1 != datalen) && + (data[in+1] != '\n') && + (linelen + 1) >= MAXLINESIZE) { + linelen = 0; + if (crlf) + odatalen += 3; + else + odatalen += 2; + } + linelen++; + odatalen++; + in++; + } + } + } + + /* We allocate the output same size as input, this is overkill. + * The previous implementation used calloc() so we'll zero out the + * memory here too, since PyMem_Malloc() does not guarantee that. + */ + odata = (unsigned char *) PyMem_Malloc(odatalen); + if (odata == NULL) { + PyBuffer_Release(&pdata); + PyErr_NoMemory(); + return NULL; + } + memset(odata, 0, odatalen); + + in = out = linelen = 0; + while (in < datalen) { + if ((data[in] > 126) || + (data[in] == '=') || + (header && data[in] == '_') || + ((data[in] == '.') && (linelen == 0) && + (data[in+1] == '\n' || data[in+1] == '\r' || data[in+1] == 0)) || + (!istext && ((data[in] == '\r') || (data[in] == '\n'))) || + ((data[in] == '\t' || data[in] == ' ') && (in + 1 == datalen)) || + ((data[in] < 33) && + (data[in] != '\r') && (data[in] != '\n') && + (quotetabs || + (!quotetabs && ((data[in] != '\t') && (data[in] != ' ')))))) + { + if ((linelen + 3 )>= MAXLINESIZE) { + odata[out++] = '='; + if (crlf) odata[out++] = '\r'; + odata[out++] = '\n'; + linelen = 0; + } + odata[out++] = '='; + to_hex(data[in], &odata[out]); + out += 2; + in++; + linelen += 3; + } + else { + if (istext && + ((data[in] == '\n') || + ((in+1 < datalen) && (data[in] == '\r') && + (data[in+1] == '\n')))) + { + linelen = 0; + /* Protect against whitespace on end of line */ + if (out && ((odata[out-1] == ' ') || (odata[out-1] == '\t'))) { + ch = odata[out-1]; + odata[out-1] = '='; + to_hex(ch, &odata[out]); + out += 2; + } + + if (crlf) odata[out++] = '\r'; + odata[out++] = '\n'; + if (data[in] == '\r') + in += 2; + else + in++; + } + else { + if ((in + 1 != datalen) && + (data[in+1] != '\n') && + (linelen + 1) >= MAXLINESIZE) { + odata[out++] = '='; + if (crlf) odata[out++] = '\r'; + odata[out++] = '\n'; + linelen = 0; + } + linelen++; + if (header && data[in] == ' ') { + odata[out++] = '_'; + in++; + } + else { + odata[out++] = data[in++]; + } + } + } + } + if ((rv = PyBytes_FromStringAndSize((char *)odata, out)) == NULL) { + PyBuffer_Release(&pdata); + PyMem_Free(odata); + return NULL; + } + PyBuffer_Release(&pdata); + PyMem_Free(odata); + return rv; } /* List of functions defined in the module */ static struct PyMethodDef binascii_module_methods[] = { - {"a2b_uu", binascii_a2b_uu, METH_VARARGS, doc_a2b_uu}, - {"b2a_uu", binascii_b2a_uu, METH_VARARGS, doc_b2a_uu}, - {"a2b_base64", binascii_a2b_base64, METH_VARARGS, doc_a2b_base64}, - {"b2a_base64", binascii_b2a_base64, METH_VARARGS, doc_b2a_base64}, - {"a2b_hqx", binascii_a2b_hqx, METH_VARARGS, doc_a2b_hqx}, - {"b2a_hqx", binascii_b2a_hqx, METH_VARARGS, doc_b2a_hqx}, - {"b2a_hex", binascii_hexlify, METH_VARARGS, doc_hexlify}, - {"a2b_hex", binascii_unhexlify, METH_VARARGS, doc_unhexlify}, - {"hexlify", binascii_hexlify, METH_VARARGS, doc_hexlify}, - {"unhexlify", binascii_unhexlify, METH_VARARGS, doc_unhexlify}, - {"rlecode_hqx", binascii_rlecode_hqx, METH_VARARGS, doc_rlecode_hqx}, - {"rledecode_hqx", binascii_rledecode_hqx, METH_VARARGS, - doc_rledecode_hqx}, - {"crc_hqx", binascii_crc_hqx, METH_VARARGS, doc_crc_hqx}, - {"crc32", binascii_crc32, METH_VARARGS, doc_crc32}, - {"a2b_qp", (PyCFunction)binascii_a2b_qp, METH_VARARGS | METH_KEYWORDS, - doc_a2b_qp}, - {"b2a_qp", (PyCFunction)binascii_b2a_qp, METH_VARARGS | METH_KEYWORDS, - doc_b2a_qp}, - {NULL, NULL} /* sentinel */ + {"a2b_uu", binascii_a2b_uu, METH_VARARGS, doc_a2b_uu}, + {"b2a_uu", binascii_b2a_uu, METH_VARARGS, doc_b2a_uu}, + {"a2b_base64", binascii_a2b_base64, METH_VARARGS, doc_a2b_base64}, + {"b2a_base64", binascii_b2a_base64, METH_VARARGS, doc_b2a_base64}, + {"a2b_hqx", binascii_a2b_hqx, METH_VARARGS, doc_a2b_hqx}, + {"b2a_hqx", binascii_b2a_hqx, METH_VARARGS, doc_b2a_hqx}, + {"b2a_hex", binascii_hexlify, METH_VARARGS, doc_hexlify}, + {"a2b_hex", binascii_unhexlify, METH_VARARGS, doc_unhexlify}, + {"hexlify", binascii_hexlify, METH_VARARGS, doc_hexlify}, + {"unhexlify", binascii_unhexlify, METH_VARARGS, doc_unhexlify}, + {"rlecode_hqx", binascii_rlecode_hqx, METH_VARARGS, doc_rlecode_hqx}, + {"rledecode_hqx", binascii_rledecode_hqx, METH_VARARGS, + doc_rledecode_hqx}, + {"crc_hqx", binascii_crc_hqx, METH_VARARGS, doc_crc_hqx}, + {"crc32", binascii_crc32, METH_VARARGS, doc_crc32}, + {"a2b_qp", (PyCFunction)binascii_a2b_qp, METH_VARARGS | METH_KEYWORDS, + doc_a2b_qp}, + {"b2a_qp", (PyCFunction)binascii_b2a_qp, METH_VARARGS | METH_KEYWORDS, + doc_b2a_qp}, + {NULL, NULL} /* sentinel */ }; @@ -1508,36 +1508,36 @@ static struct PyModuleDef binasciimodule = { - PyModuleDef_HEAD_INIT, - "binascii", - doc_binascii, - -1, - binascii_module_methods, - NULL, - NULL, - NULL, - NULL + PyModuleDef_HEAD_INIT, + "binascii", + doc_binascii, + -1, + binascii_module_methods, + NULL, + NULL, + NULL, + NULL }; PyMODINIT_FUNC PyInit_binascii(void) { - PyObject *m, *d; + PyObject *m, *d; + + /* Create the module and add the functions */ + m = PyModule_Create(&binasciimodule); + if (m == NULL) + return NULL; + + d = PyModule_GetDict(m); - /* Create the module and add the functions */ - m = PyModule_Create(&binasciimodule); - if (m == NULL) - return NULL; - - d = PyModule_GetDict(m); - - Error = PyErr_NewException("binascii.Error", PyExc_ValueError, NULL); - PyDict_SetItemString(d, "Error", Error); - Incomplete = PyErr_NewException("binascii.Incomplete", NULL, NULL); - PyDict_SetItemString(d, "Incomplete", Incomplete); - if (PyErr_Occurred()) { - Py_DECREF(m); - m = NULL; - } - return m; + Error = PyErr_NewException("binascii.Error", PyExc_ValueError, NULL); + PyDict_SetItemString(d, "Error", Error); + Incomplete = PyErr_NewException("binascii.Incomplete", NULL, NULL); + PyDict_SetItemString(d, "Incomplete", Incomplete); + if (PyErr_Occurred()) { + Py_DECREF(m); + m = NULL; + } + return m; } Modified: python/branches/py3k-jit/Modules/bz2module.c ============================================================================== --- python/branches/py3k-jit/Modules/bz2module.c (original) +++ python/branches/py3k-jit/Modules/bz2module.c Mon May 10 23:55:43 2010 @@ -41,20 +41,20 @@ #define MODE_READ_EOF 2 #define MODE_WRITE 3 -#define BZ2FileObject_Check(v) (Py_TYPE(v) == &BZ2File_Type) +#define BZ2FileObject_Check(v) (Py_TYPE(v) == &BZ2File_Type) #ifdef BZ_CONFIG_ERROR #if SIZEOF_LONG >= 8 #define BZS_TOTAL_OUT(bzs) \ - (((long)bzs->total_out_hi32 << 32) + bzs->total_out_lo32) + (((long)bzs->total_out_hi32 << 32) + bzs->total_out_lo32) #elif SIZEOF_LONG_LONG >= 8 #define BZS_TOTAL_OUT(bzs) \ - (((PY_LONG_LONG)bzs->total_out_hi32 << 32) + bzs->total_out_lo32) + (((PY_LONG_LONG)bzs->total_out_hi32 << 32) + bzs->total_out_lo32) #else #define BZS_TOTAL_OUT(bzs) \ - bzs->total_out_lo32 + bzs->total_out_lo32 #endif #else /* ! BZ_CONFIG_ERROR */ @@ -79,11 +79,11 @@ #ifdef WITH_THREAD #define ACQUIRE_LOCK(obj) do { \ - if (!PyThread_acquire_lock(obj->lock, 0)) { \ - Py_BEGIN_ALLOW_THREADS \ - PyThread_acquire_lock(obj->lock, 1); \ - Py_END_ALLOW_THREADS \ - } } while(0) + if (!PyThread_acquire_lock(obj->lock, 0)) { \ + Py_BEGIN_ALLOW_THREADS \ + PyThread_acquire_lock(obj->lock, 1); \ + Py_END_ALLOW_THREADS \ + } } while(0) #define RELEASE_LOCK(obj) PyThread_release_lock(obj->lock) #else #define ACQUIRE_LOCK(obj) @@ -91,47 +91,47 @@ #endif /* Bits in f_newlinetypes */ -#define NEWLINE_UNKNOWN 0 /* No newline seen, yet */ -#define NEWLINE_CR 1 /* \r newline seen */ -#define NEWLINE_LF 2 /* \n newline seen */ -#define NEWLINE_CRLF 4 /* \r\n newline seen */ +#define NEWLINE_UNKNOWN 0 /* No newline seen, yet */ +#define NEWLINE_CR 1 /* \r newline seen */ +#define NEWLINE_LF 2 /* \n newline seen */ +#define NEWLINE_CRLF 4 /* \r\n newline seen */ /* ===================================================================== */ /* Structure definitions. */ typedef struct { - PyObject_HEAD - FILE *rawfp; + PyObject_HEAD + FILE *rawfp; - char* f_buf; /* Allocated readahead buffer */ - char* f_bufend; /* Points after last occupied position */ - char* f_bufptr; /* Current buffer position */ - - BZFILE *fp; - int mode; - Py_off_t pos; - Py_off_t size; + char* f_buf; /* Allocated readahead buffer */ + char* f_bufend; /* Points after last occupied position */ + char* f_bufptr; /* Current buffer position */ + + BZFILE *fp; + int mode; + Py_off_t pos; + Py_off_t size; #ifdef WITH_THREAD - PyThread_type_lock lock; + PyThread_type_lock lock; #endif } BZ2FileObject; typedef struct { - PyObject_HEAD - bz_stream bzs; - int running; + PyObject_HEAD + bz_stream bzs; + int running; #ifdef WITH_THREAD - PyThread_type_lock lock; + PyThread_type_lock lock; #endif } BZ2CompObject; typedef struct { - PyObject_HEAD - bz_stream bzs; - int running; - PyObject *unused_data; + PyObject_HEAD + bz_stream bzs; + int running; + PyObject *unused_data; #ifdef WITH_THREAD - PyThread_type_lock lock; + PyThread_type_lock lock; #endif } BZ2DecompObject; @@ -141,59 +141,59 @@ static int Util_CatchBZ2Error(int bzerror) { - int ret = 0; - switch(bzerror) { - case BZ_OK: - case BZ_STREAM_END: - break; + int ret = 0; + switch(bzerror) { + case BZ_OK: + case BZ_STREAM_END: + break; #ifdef BZ_CONFIG_ERROR - case BZ_CONFIG_ERROR: - PyErr_SetString(PyExc_SystemError, - "the bz2 library was not compiled " - "correctly"); - ret = 1; - break; + case BZ_CONFIG_ERROR: + PyErr_SetString(PyExc_SystemError, + "the bz2 library was not compiled " + "correctly"); + ret = 1; + break; #endif - case BZ_PARAM_ERROR: - PyErr_SetString(PyExc_ValueError, - "the bz2 library has received wrong " - "parameters"); - ret = 1; - break; - - case BZ_MEM_ERROR: - PyErr_NoMemory(); - ret = 1; - break; - - case BZ_DATA_ERROR: - case BZ_DATA_ERROR_MAGIC: - PyErr_SetString(PyExc_IOError, "invalid data stream"); - ret = 1; - break; - - case BZ_IO_ERROR: - PyErr_SetString(PyExc_IOError, "unknown IO error"); - ret = 1; - break; - - case BZ_UNEXPECTED_EOF: - PyErr_SetString(PyExc_EOFError, - "compressed file ended before the " - "logical end-of-stream was detected"); - ret = 1; - break; - - case BZ_SEQUENCE_ERROR: - PyErr_SetString(PyExc_RuntimeError, - "wrong sequence of bz2 library " - "commands used"); - ret = 1; - break; - } - return ret; + case BZ_PARAM_ERROR: + PyErr_SetString(PyExc_ValueError, + "the bz2 library has received wrong " + "parameters"); + ret = 1; + break; + + case BZ_MEM_ERROR: + PyErr_NoMemory(); + ret = 1; + break; + + case BZ_DATA_ERROR: + case BZ_DATA_ERROR_MAGIC: + PyErr_SetString(PyExc_IOError, "invalid data stream"); + ret = 1; + break; + + case BZ_IO_ERROR: + PyErr_SetString(PyExc_IOError, "unknown IO error"); + ret = 1; + break; + + case BZ_UNEXPECTED_EOF: + PyErr_SetString(PyExc_EOFError, + "compressed file ended before the " + "logical end-of-stream was detected"); + ret = 1; + break; + + case BZ_SEQUENCE_ERROR: + PyErr_SetString(PyExc_RuntimeError, + "wrong sequence of bz2 library " + "commands used"); + ret = 1; + break; + } + return ret; } #if BUFSIZ < 8192 @@ -212,134 +212,134 @@ static size_t Util_NewBufferSize(size_t currentsize) { - if (currentsize > SMALLCHUNK) { - /* Keep doubling until we reach BIGCHUNK; - then keep adding BIGCHUNK. */ - if (currentsize <= BIGCHUNK) - return currentsize + currentsize; - else - return currentsize + BIGCHUNK; - } - return currentsize + SMALLCHUNK; + if (currentsize > SMALLCHUNK) { + /* Keep doubling until we reach BIGCHUNK; + then keep adding BIGCHUNK. */ + if (currentsize <= BIGCHUNK) + return currentsize + currentsize; + else + return currentsize + BIGCHUNK; + } + return currentsize + SMALLCHUNK; } /* This is a hacked version of Python's fileobject.c:get_line(). */ static PyObject * Util_GetLine(BZ2FileObject *f, int n) { - char c; - char *buf, *end; - size_t total_v_size; /* total # of slots in buffer */ - size_t used_v_size; /* # used slots in buffer */ - size_t increment; /* amount to increment the buffer */ - PyObject *v; - int bzerror; - int bytes_read; - - total_v_size = n > 0 ? n : 100; - v = PyBytes_FromStringAndSize((char *)NULL, total_v_size); - if (v == NULL) - return NULL; - - buf = BUF(v); - end = buf + total_v_size; - - for (;;) { - Py_BEGIN_ALLOW_THREADS - do { - bytes_read = BZ2_bzRead(&bzerror, f->fp, &c, 1); - f->pos++; - if (bytes_read == 0) - break; - *buf++ = c; - } while (bzerror == BZ_OK && c != '\n' && buf != end); - Py_END_ALLOW_THREADS - if (bzerror == BZ_STREAM_END) { - f->size = f->pos; - f->mode = MODE_READ_EOF; - break; - } else if (bzerror != BZ_OK) { - Util_CatchBZ2Error(bzerror); - Py_DECREF(v); - return NULL; - } - if (c == '\n') - break; - /* Must be because buf == end */ - if (n > 0) - break; - used_v_size = total_v_size; - increment = total_v_size >> 2; /* mild exponential growth */ - total_v_size += increment; - if (total_v_size > INT_MAX) { - PyErr_SetString(PyExc_OverflowError, - "line is longer than a Python string can hold"); - Py_DECREF(v); - return NULL; - } - if (_PyBytes_Resize(&v, total_v_size) < 0) { - return NULL; - } - buf = BUF(v) + used_v_size; - end = BUF(v) + total_v_size; - } - - used_v_size = buf - BUF(v); - if (used_v_size != total_v_size) { - if (_PyBytes_Resize(&v, used_v_size) < 0) { - v = NULL; - } - } - return v; + char c; + char *buf, *end; + size_t total_v_size; /* total # of slots in buffer */ + size_t used_v_size; /* # used slots in buffer */ + size_t increment; /* amount to increment the buffer */ + PyObject *v; + int bzerror; + int bytes_read; + + total_v_size = n > 0 ? n : 100; + v = PyBytes_FromStringAndSize((char *)NULL, total_v_size); + if (v == NULL) + return NULL; + + buf = BUF(v); + end = buf + total_v_size; + + for (;;) { + Py_BEGIN_ALLOW_THREADS + do { + bytes_read = BZ2_bzRead(&bzerror, f->fp, &c, 1); + f->pos++; + if (bytes_read == 0) + break; + *buf++ = c; + } while (bzerror == BZ_OK && c != '\n' && buf != end); + Py_END_ALLOW_THREADS + if (bzerror == BZ_STREAM_END) { + f->size = f->pos; + f->mode = MODE_READ_EOF; + break; + } else if (bzerror != BZ_OK) { + Util_CatchBZ2Error(bzerror); + Py_DECREF(v); + return NULL; + } + if (c == '\n') + break; + /* Must be because buf == end */ + if (n > 0) + break; + used_v_size = total_v_size; + increment = total_v_size >> 2; /* mild exponential growth */ + total_v_size += increment; + if (total_v_size > INT_MAX) { + PyErr_SetString(PyExc_OverflowError, + "line is longer than a Python string can hold"); + Py_DECREF(v); + return NULL; + } + if (_PyBytes_Resize(&v, total_v_size) < 0) { + return NULL; + } + buf = BUF(v) + used_v_size; + end = BUF(v) + total_v_size; + } + + used_v_size = buf - BUF(v); + if (used_v_size != total_v_size) { + if (_PyBytes_Resize(&v, used_v_size) < 0) { + v = NULL; + } + } + return v; } /* This is a hacked version of Python's fileobject.c:drop_readahead(). */ static void Util_DropReadAhead(BZ2FileObject *f) { - if (f->f_buf != NULL) { - PyMem_Free(f->f_buf); - f->f_buf = NULL; - } + if (f->f_buf != NULL) { + PyMem_Free(f->f_buf); + f->f_buf = NULL; + } } /* This is a hacked version of Python's fileobject.c:readahead(). */ static int Util_ReadAhead(BZ2FileObject *f, int bufsize) { - int chunksize; - int bzerror; + int chunksize; + int bzerror; - if (f->f_buf != NULL) { - if((f->f_bufend - f->f_bufptr) >= 1) - return 0; - else - Util_DropReadAhead(f); - } - if (f->mode == MODE_READ_EOF) { - f->f_bufptr = f->f_buf; - f->f_bufend = f->f_buf; - return 0; - } - if ((f->f_buf = PyMem_Malloc(bufsize)) == NULL) { - PyErr_NoMemory(); - return -1; - } - Py_BEGIN_ALLOW_THREADS - chunksize = BZ2_bzRead(&bzerror, f->fp, f->f_buf, bufsize); - Py_END_ALLOW_THREADS - f->pos += chunksize; - if (bzerror == BZ_STREAM_END) { - f->size = f->pos; - f->mode = MODE_READ_EOF; - } else if (bzerror != BZ_OK) { - Util_CatchBZ2Error(bzerror); - Util_DropReadAhead(f); - return -1; - } - f->f_bufptr = f->f_buf; - f->f_bufend = f->f_buf + chunksize; - return 0; + if (f->f_buf != NULL) { + if((f->f_bufend - f->f_bufptr) >= 1) + return 0; + else + Util_DropReadAhead(f); + } + if (f->mode == MODE_READ_EOF) { + f->f_bufptr = f->f_buf; + f->f_bufend = f->f_buf; + return 0; + } + if ((f->f_buf = PyMem_Malloc(bufsize)) == NULL) { + PyErr_NoMemory(); + return -1; + } + Py_BEGIN_ALLOW_THREADS + chunksize = BZ2_bzRead(&bzerror, f->fp, f->f_buf, bufsize); + Py_END_ALLOW_THREADS + f->pos += chunksize; + if (bzerror == BZ_STREAM_END) { + f->size = f->pos; + f->mode = MODE_READ_EOF; + } else if (bzerror != BZ_OK) { + Util_CatchBZ2Error(bzerror); + Util_DropReadAhead(f); + return -1; + } + f->f_bufptr = f->f_buf; + f->f_bufend = f->f_buf + chunksize; + return 0; } /* This is a hacked version of Python's @@ -347,45 +347,45 @@ static PyBytesObject * Util_ReadAheadGetLineSkip(BZ2FileObject *f, int skip, int bufsize) { - PyBytesObject* s; - char *bufptr; - char *buf; - int len; - - if (f->f_buf == NULL) - if (Util_ReadAhead(f, bufsize) < 0) - return NULL; - - len = f->f_bufend - f->f_bufptr; - if (len == 0) - return (PyBytesObject *) - PyBytes_FromStringAndSize(NULL, skip); - bufptr = memchr(f->f_bufptr, '\n', len); - if (bufptr != NULL) { - bufptr++; /* Count the '\n' */ - len = bufptr - f->f_bufptr; - s = (PyBytesObject *) - PyBytes_FromStringAndSize(NULL, skip+len); - if (s == NULL) - return NULL; - memcpy(PyBytes_AS_STRING(s)+skip, f->f_bufptr, len); - f->f_bufptr = bufptr; - if (bufptr == f->f_bufend) - Util_DropReadAhead(f); - } else { - bufptr = f->f_bufptr; - buf = f->f_buf; - f->f_buf = NULL; /* Force new readahead buffer */ - s = Util_ReadAheadGetLineSkip(f, skip+len, - bufsize + (bufsize>>2)); - if (s == NULL) { - PyMem_Free(buf); - return NULL; - } - memcpy(PyBytes_AS_STRING(s)+skip, bufptr, len); - PyMem_Free(buf); - } - return s; + PyBytesObject* s; + char *bufptr; + char *buf; + int len; + + if (f->f_buf == NULL) + if (Util_ReadAhead(f, bufsize) < 0) + return NULL; + + len = f->f_bufend - f->f_bufptr; + if (len == 0) + return (PyBytesObject *) + PyBytes_FromStringAndSize(NULL, skip); + bufptr = memchr(f->f_bufptr, '\n', len); + if (bufptr != NULL) { + bufptr++; /* Count the '\n' */ + len = bufptr - f->f_bufptr; + s = (PyBytesObject *) + PyBytes_FromStringAndSize(NULL, skip+len); + if (s == NULL) + return NULL; + memcpy(PyBytes_AS_STRING(s)+skip, f->f_bufptr, len); + f->f_bufptr = bufptr; + if (bufptr == f->f_bufend) + Util_DropReadAhead(f); + } else { + bufptr = f->f_bufptr; + buf = f->f_buf; + f->f_buf = NULL; /* Force new readahead buffer */ + s = Util_ReadAheadGetLineSkip(f, skip+len, + bufsize + (bufsize>>2)); + if (s == NULL) { + PyMem_Free(buf); + return NULL; + } + memcpy(PyBytes_AS_STRING(s)+skip, bufptr, len); + PyMem_Free(buf); + } + return s; } /* ===================================================================== */ @@ -402,83 +402,83 @@ static PyObject * BZ2File_read(BZ2FileObject *self, PyObject *args) { - long bytesrequested = -1; - size_t bytesread, buffersize, chunksize; - int bzerror; - PyObject *ret = NULL; - - if (!PyArg_ParseTuple(args, "|l:read", &bytesrequested)) - return NULL; - - ACQUIRE_LOCK(self); - switch (self->mode) { - case MODE_READ: - break; - case MODE_READ_EOF: - ret = PyBytes_FromStringAndSize("", 0); - goto cleanup; - case MODE_CLOSED: - PyErr_SetString(PyExc_ValueError, - "I/O operation on closed file"); - goto cleanup; - default: - PyErr_SetString(PyExc_IOError, - "file is not ready for reading"); - goto cleanup; - } - - if (bytesrequested < 0) - buffersize = Util_NewBufferSize((size_t)0); - else - buffersize = bytesrequested; - if (buffersize > INT_MAX) { - PyErr_SetString(PyExc_OverflowError, - "requested number of bytes is " - "more than a Python string can hold"); - goto cleanup; - } - ret = PyBytes_FromStringAndSize((char *)NULL, buffersize); - if (ret == NULL || buffersize == 0) - goto cleanup; - bytesread = 0; - - for (;;) { - Py_BEGIN_ALLOW_THREADS - chunksize = BZ2_bzRead(&bzerror, self->fp, - BUF(ret)+bytesread, - buffersize-bytesread); - self->pos += chunksize; - Py_END_ALLOW_THREADS - bytesread += chunksize; - if (bzerror == BZ_STREAM_END) { - self->size = self->pos; - self->mode = MODE_READ_EOF; - break; - } else if (bzerror != BZ_OK) { - Util_CatchBZ2Error(bzerror); - Py_DECREF(ret); - ret = NULL; - goto cleanup; - } - if (bytesrequested < 0) { - buffersize = Util_NewBufferSize(buffersize); - if (_PyBytes_Resize(&ret, buffersize) < 0) { - ret = NULL; - goto cleanup; - } - } else { - break; - } - } - if (bytesread != buffersize) { - if (_PyBytes_Resize(&ret, bytesread) < 0) { - ret = NULL; - } - } + long bytesrequested = -1; + size_t bytesread, buffersize, chunksize; + int bzerror; + PyObject *ret = NULL; + + if (!PyArg_ParseTuple(args, "|l:read", &bytesrequested)) + return NULL; + + ACQUIRE_LOCK(self); + switch (self->mode) { + case MODE_READ: + break; + case MODE_READ_EOF: + ret = PyBytes_FromStringAndSize("", 0); + goto cleanup; + case MODE_CLOSED: + PyErr_SetString(PyExc_ValueError, + "I/O operation on closed file"); + goto cleanup; + default: + PyErr_SetString(PyExc_IOError, + "file is not ready for reading"); + goto cleanup; + } + + if (bytesrequested < 0) + buffersize = Util_NewBufferSize((size_t)0); + else + buffersize = bytesrequested; + if (buffersize > INT_MAX) { + PyErr_SetString(PyExc_OverflowError, + "requested number of bytes is " + "more than a Python string can hold"); + goto cleanup; + } + ret = PyBytes_FromStringAndSize((char *)NULL, buffersize); + if (ret == NULL || buffersize == 0) + goto cleanup; + bytesread = 0; + + for (;;) { + Py_BEGIN_ALLOW_THREADS + chunksize = BZ2_bzRead(&bzerror, self->fp, + BUF(ret)+bytesread, + buffersize-bytesread); + self->pos += chunksize; + Py_END_ALLOW_THREADS + bytesread += chunksize; + if (bzerror == BZ_STREAM_END) { + self->size = self->pos; + self->mode = MODE_READ_EOF; + break; + } else if (bzerror != BZ_OK) { + Util_CatchBZ2Error(bzerror); + Py_DECREF(ret); + ret = NULL; + goto cleanup; + } + if (bytesrequested < 0) { + buffersize = Util_NewBufferSize(buffersize); + if (_PyBytes_Resize(&ret, buffersize) < 0) { + ret = NULL; + goto cleanup; + } + } else { + break; + } + } + if (bytesread != buffersize) { + if (_PyBytes_Resize(&ret, bytesread) < 0) { + ret = NULL; + } + } cleanup: - RELEASE_LOCK(self); - return ret; + RELEASE_LOCK(self); + return ret; } PyDoc_STRVAR(BZ2File_readline__doc__, @@ -493,37 +493,37 @@ static PyObject * BZ2File_readline(BZ2FileObject *self, PyObject *args) { - PyObject *ret = NULL; - int sizehint = -1; + PyObject *ret = NULL; + int sizehint = -1; - if (!PyArg_ParseTuple(args, "|i:readline", &sizehint)) - return NULL; + if (!PyArg_ParseTuple(args, "|i:readline", &sizehint)) + return NULL; - ACQUIRE_LOCK(self); - switch (self->mode) { - case MODE_READ: - break; - case MODE_READ_EOF: - ret = PyBytes_FromStringAndSize("", 0); - goto cleanup; - case MODE_CLOSED: - PyErr_SetString(PyExc_ValueError, - "I/O operation on closed file"); - goto cleanup; - default: - PyErr_SetString(PyExc_IOError, - "file is not ready for reading"); - goto cleanup; - } - - if (sizehint == 0) - ret = PyBytes_FromStringAndSize("", 0); - else - ret = Util_GetLine(self, (sizehint < 0) ? 0 : sizehint); + ACQUIRE_LOCK(self); + switch (self->mode) { + case MODE_READ: + break; + case MODE_READ_EOF: + ret = PyBytes_FromStringAndSize("", 0); + goto cleanup; + case MODE_CLOSED: + PyErr_SetString(PyExc_ValueError, + "I/O operation on closed file"); + goto cleanup; + default: + PyErr_SetString(PyExc_IOError, + "file is not ready for reading"); + goto cleanup; + } + + if (sizehint == 0) + ret = PyBytes_FromStringAndSize("", 0); + else + ret = Util_GetLine(self, (sizehint < 0) ? 0 : sizehint); cleanup: - RELEASE_LOCK(self); - return ret; + RELEASE_LOCK(self); + return ret; } PyDoc_STRVAR(BZ2File_readlines__doc__, @@ -538,150 +538,150 @@ static PyObject * BZ2File_readlines(BZ2FileObject *self, PyObject *args) { - long sizehint = 0; - PyObject *list = NULL; - PyObject *line; - char small_buffer[SMALLCHUNK]; - char *buffer = small_buffer; - size_t buffersize = SMALLCHUNK; - PyObject *big_buffer = NULL; - size_t nfilled = 0; - size_t nread; - size_t totalread = 0; - char *p, *q, *end; - int err; - int shortread = 0; - int bzerror; - - if (!PyArg_ParseTuple(args, "|l:readlines", &sizehint)) - return NULL; - - ACQUIRE_LOCK(self); - switch (self->mode) { - case MODE_READ: - break; - case MODE_READ_EOF: - list = PyList_New(0); - goto cleanup; - case MODE_CLOSED: - PyErr_SetString(PyExc_ValueError, - "I/O operation on closed file"); - goto cleanup; - default: - PyErr_SetString(PyExc_IOError, - "file is not ready for reading"); - goto cleanup; - } - - if ((list = PyList_New(0)) == NULL) - goto cleanup; - - for (;;) { - Py_BEGIN_ALLOW_THREADS - nread = BZ2_bzRead(&bzerror, self->fp, - buffer+nfilled, buffersize-nfilled); - self->pos += nread; - Py_END_ALLOW_THREADS - if (bzerror == BZ_STREAM_END) { - self->size = self->pos; - self->mode = MODE_READ_EOF; - if (nread == 0) { - sizehint = 0; - break; - } - shortread = 1; - } else if (bzerror != BZ_OK) { - Util_CatchBZ2Error(bzerror); - error: - Py_DECREF(list); - list = NULL; - goto cleanup; - } - totalread += nread; - p = memchr(buffer+nfilled, '\n', nread); - if (!shortread && p == NULL) { - /* Need a larger buffer to fit this line */ - nfilled += nread; - buffersize *= 2; - if (buffersize > INT_MAX) { - PyErr_SetString(PyExc_OverflowError, - "line is longer than a Python string can hold"); - goto error; - } - if (big_buffer == NULL) { - /* Create the big buffer */ - big_buffer = PyBytes_FromStringAndSize( - NULL, buffersize); - if (big_buffer == NULL) - goto error; - buffer = PyBytes_AS_STRING(big_buffer); - memcpy(buffer, small_buffer, nfilled); - } - else { - /* Grow the big buffer */ - if (_PyBytes_Resize(&big_buffer, buffersize) < 0){ - big_buffer = NULL; - goto error; - } - buffer = PyBytes_AS_STRING(big_buffer); - } - continue; - } - end = buffer+nfilled+nread; - q = buffer; - while (p != NULL) { - /* Process complete lines */ - p++; - line = PyBytes_FromStringAndSize(q, p-q); - if (line == NULL) - goto error; - err = PyList_Append(list, line); - Py_DECREF(line); - if (err != 0) - goto error; - q = p; - p = memchr(q, '\n', end-q); - } - /* Move the remaining incomplete line to the start */ - nfilled = end-q; - memmove(buffer, q, nfilled); - if (sizehint > 0) - if (totalread >= (size_t)sizehint) - break; - if (shortread) { - sizehint = 0; - break; - } - } - if (nfilled != 0) { - /* Partial last line */ - line = PyBytes_FromStringAndSize(buffer, nfilled); - if (line == NULL) - goto error; - if (sizehint > 0) { - /* Need to complete the last line */ - PyObject *rest = Util_GetLine(self, 0); - if (rest == NULL) { - Py_DECREF(line); - goto error; - } - PyBytes_Concat(&line, rest); - Py_DECREF(rest); - if (line == NULL) - goto error; - } - err = PyList_Append(list, line); - Py_DECREF(line); - if (err != 0) - goto error; - } + long sizehint = 0; + PyObject *list = NULL; + PyObject *line; + char small_buffer[SMALLCHUNK]; + char *buffer = small_buffer; + size_t buffersize = SMALLCHUNK; + PyObject *big_buffer = NULL; + size_t nfilled = 0; + size_t nread; + size_t totalread = 0; + char *p, *q, *end; + int err; + int shortread = 0; + int bzerror; + + if (!PyArg_ParseTuple(args, "|l:readlines", &sizehint)) + return NULL; + + ACQUIRE_LOCK(self); + switch (self->mode) { + case MODE_READ: + break; + case MODE_READ_EOF: + list = PyList_New(0); + goto cleanup; + case MODE_CLOSED: + PyErr_SetString(PyExc_ValueError, + "I/O operation on closed file"); + goto cleanup; + default: + PyErr_SetString(PyExc_IOError, + "file is not ready for reading"); + goto cleanup; + } + + if ((list = PyList_New(0)) == NULL) + goto cleanup; + + for (;;) { + Py_BEGIN_ALLOW_THREADS + nread = BZ2_bzRead(&bzerror, self->fp, + buffer+nfilled, buffersize-nfilled); + self->pos += nread; + Py_END_ALLOW_THREADS + if (bzerror == BZ_STREAM_END) { + self->size = self->pos; + self->mode = MODE_READ_EOF; + if (nread == 0) { + sizehint = 0; + break; + } + shortread = 1; + } else if (bzerror != BZ_OK) { + Util_CatchBZ2Error(bzerror); + error: + Py_DECREF(list); + list = NULL; + goto cleanup; + } + totalread += nread; + p = memchr(buffer+nfilled, '\n', nread); + if (!shortread && p == NULL) { + /* Need a larger buffer to fit this line */ + nfilled += nread; + buffersize *= 2; + if (buffersize > INT_MAX) { + PyErr_SetString(PyExc_OverflowError, + "line is longer than a Python string can hold"); + goto error; + } + if (big_buffer == NULL) { + /* Create the big buffer */ + big_buffer = PyBytes_FromStringAndSize( + NULL, buffersize); + if (big_buffer == NULL) + goto error; + buffer = PyBytes_AS_STRING(big_buffer); + memcpy(buffer, small_buffer, nfilled); + } + else { + /* Grow the big buffer */ + if (_PyBytes_Resize(&big_buffer, buffersize) < 0){ + big_buffer = NULL; + goto error; + } + buffer = PyBytes_AS_STRING(big_buffer); + } + continue; + } + end = buffer+nfilled+nread; + q = buffer; + while (p != NULL) { + /* Process complete lines */ + p++; + line = PyBytes_FromStringAndSize(q, p-q); + if (line == NULL) + goto error; + err = PyList_Append(list, line); + Py_DECREF(line); + if (err != 0) + goto error; + q = p; + p = memchr(q, '\n', end-q); + } + /* Move the remaining incomplete line to the start */ + nfilled = end-q; + memmove(buffer, q, nfilled); + if (sizehint > 0) + if (totalread >= (size_t)sizehint) + break; + if (shortread) { + sizehint = 0; + break; + } + } + if (nfilled != 0) { + /* Partial last line */ + line = PyBytes_FromStringAndSize(buffer, nfilled); + if (line == NULL) + goto error; + if (sizehint > 0) { + /* Need to complete the last line */ + PyObject *rest = Util_GetLine(self, 0); + if (rest == NULL) { + Py_DECREF(line); + goto error; + } + PyBytes_Concat(&line, rest); + Py_DECREF(rest); + if (line == NULL) + goto error; + } + err = PyList_Append(list, line); + Py_DECREF(line); + if (err != 0) + goto error; + } cleanup: - RELEASE_LOCK(self); - if (big_buffer) { - Py_DECREF(big_buffer); - } - return list; + RELEASE_LOCK(self); + if (big_buffer) { + Py_DECREF(big_buffer); + } + return list; } PyDoc_STRVAR(BZ2File_write__doc__, @@ -695,50 +695,50 @@ static PyObject * BZ2File_write(BZ2FileObject *self, PyObject *args) { - PyObject *ret = NULL; - Py_buffer pbuf; - char *buf; - int len; - int bzerror; - - if (!PyArg_ParseTuple(args, "y*:write", &pbuf)) - return NULL; - buf = pbuf.buf; - len = pbuf.len; - - ACQUIRE_LOCK(self); - switch (self->mode) { - case MODE_WRITE: - break; - - case MODE_CLOSED: - PyErr_SetString(PyExc_ValueError, - "I/O operation on closed file"); - goto cleanup; - - default: - PyErr_SetString(PyExc_IOError, - "file is not ready for writing"); - goto cleanup; - } - - Py_BEGIN_ALLOW_THREADS - BZ2_bzWrite (&bzerror, self->fp, buf, len); - self->pos += len; - Py_END_ALLOW_THREADS - - if (bzerror != BZ_OK) { - Util_CatchBZ2Error(bzerror); - goto cleanup; - } + PyObject *ret = NULL; + Py_buffer pbuf; + char *buf; + int len; + int bzerror; + + if (!PyArg_ParseTuple(args, "y*:write", &pbuf)) + return NULL; + buf = pbuf.buf; + len = pbuf.len; + + ACQUIRE_LOCK(self); + switch (self->mode) { + case MODE_WRITE: + break; + + case MODE_CLOSED: + PyErr_SetString(PyExc_ValueError, + "I/O operation on closed file"); + goto cleanup; + + default: + PyErr_SetString(PyExc_IOError, + "file is not ready for writing"); + goto cleanup; + } + + Py_BEGIN_ALLOW_THREADS + BZ2_bzWrite (&bzerror, self->fp, buf, len); + self->pos += len; + Py_END_ALLOW_THREADS + + if (bzerror != BZ_OK) { + Util_CatchBZ2Error(bzerror); + goto cleanup; + } - Py_INCREF(Py_None); - ret = Py_None; + Py_INCREF(Py_None); + ret = Py_None; cleanup: - PyBuffer_Release(&pbuf); - RELEASE_LOCK(self); - return ret; + PyBuffer_Release(&pbuf); + RELEASE_LOCK(self); + return ret; } PyDoc_STRVAR(BZ2File_writelines__doc__, @@ -754,122 +754,122 @@ BZ2File_writelines(BZ2FileObject *self, PyObject *seq) { #define CHUNKSIZE 1000 - PyObject *list = NULL; - PyObject *iter = NULL; - PyObject *ret = NULL; - PyObject *line; - int i, j, index, len, islist; - int bzerror; - - ACQUIRE_LOCK(self); - switch (self->mode) { - case MODE_WRITE: - break; - - case MODE_CLOSED: - PyErr_SetString(PyExc_ValueError, - "I/O operation on closed file"); - goto error; - - default: - PyErr_SetString(PyExc_IOError, - "file is not ready for writing"); - goto error; - } - - islist = PyList_Check(seq); - if (!islist) { - iter = PyObject_GetIter(seq); - if (iter == NULL) { - PyErr_SetString(PyExc_TypeError, - "writelines() requires an iterable argument"); - goto error; - } - list = PyList_New(CHUNKSIZE); - if (list == NULL) - goto error; - } - - /* Strategy: slurp CHUNKSIZE lines into a private list, - checking that they are all strings, then write that list - without holding the interpreter lock, then come back for more. */ - for (index = 0; ; index += CHUNKSIZE) { - if (islist) { - Py_XDECREF(list); - list = PyList_GetSlice(seq, index, index+CHUNKSIZE); - if (list == NULL) - goto error; - j = PyList_GET_SIZE(list); - } - else { - for (j = 0; j < CHUNKSIZE; j++) { - line = PyIter_Next(iter); - if (line == NULL) { - if (PyErr_Occurred()) - goto error; - break; - } - PyList_SetItem(list, j, line); - } - } - if (j == 0) - break; - - /* Check that all entries are indeed byte strings. If not, - apply the same rules as for file.write() and - convert the rets to strings. This is slow, but - seems to be the only way since all conversion APIs - could potentially execute Python code. */ - for (i = 0; i < j; i++) { - PyObject *v = PyList_GET_ITEM(list, i); - if (!PyBytes_Check(v)) { - const char *buffer; - Py_ssize_t len; - if (PyObject_AsCharBuffer(v, &buffer, &len)) { - PyErr_SetString(PyExc_TypeError, - "writelines() " - "argument must be " - "a sequence of " - "bytes objects"); - goto error; - } - line = PyBytes_FromStringAndSize(buffer, - len); - if (line == NULL) - goto error; - Py_DECREF(v); - PyList_SET_ITEM(list, i, line); - } - } - - /* Since we are releasing the global lock, the - following code may *not* execute Python code. */ - Py_BEGIN_ALLOW_THREADS - for (i = 0; i < j; i++) { - line = PyList_GET_ITEM(list, i); - len = PyBytes_GET_SIZE(line); - BZ2_bzWrite (&bzerror, self->fp, - PyBytes_AS_STRING(line), len); - if (bzerror != BZ_OK) { - Py_BLOCK_THREADS - Util_CatchBZ2Error(bzerror); - goto error; - } - } - Py_END_ALLOW_THREADS - - if (j < CHUNKSIZE) - break; - } + PyObject *list = NULL; + PyObject *iter = NULL; + PyObject *ret = NULL; + PyObject *line; + int i, j, index, len, islist; + int bzerror; + + ACQUIRE_LOCK(self); + switch (self->mode) { + case MODE_WRITE: + break; + + case MODE_CLOSED: + PyErr_SetString(PyExc_ValueError, + "I/O operation on closed file"); + goto error; + + default: + PyErr_SetString(PyExc_IOError, + "file is not ready for writing"); + goto error; + } + + islist = PyList_Check(seq); + if (!islist) { + iter = PyObject_GetIter(seq); + if (iter == NULL) { + PyErr_SetString(PyExc_TypeError, + "writelines() requires an iterable argument"); + goto error; + } + list = PyList_New(CHUNKSIZE); + if (list == NULL) + goto error; + } + + /* Strategy: slurp CHUNKSIZE lines into a private list, + checking that they are all strings, then write that list + without holding the interpreter lock, then come back for more. */ + for (index = 0; ; index += CHUNKSIZE) { + if (islist) { + Py_XDECREF(list); + list = PyList_GetSlice(seq, index, index+CHUNKSIZE); + if (list == NULL) + goto error; + j = PyList_GET_SIZE(list); + } + else { + for (j = 0; j < CHUNKSIZE; j++) { + line = PyIter_Next(iter); + if (line == NULL) { + if (PyErr_Occurred()) + goto error; + break; + } + PyList_SetItem(list, j, line); + } + } + if (j == 0) + break; + + /* Check that all entries are indeed byte strings. If not, + apply the same rules as for file.write() and + convert the rets to strings. This is slow, but + seems to be the only way since all conversion APIs + could potentially execute Python code. */ + for (i = 0; i < j; i++) { + PyObject *v = PyList_GET_ITEM(list, i); + if (!PyBytes_Check(v)) { + const char *buffer; + Py_ssize_t len; + if (PyObject_AsCharBuffer(v, &buffer, &len)) { + PyErr_SetString(PyExc_TypeError, + "writelines() " + "argument must be " + "a sequence of " + "bytes objects"); + goto error; + } + line = PyBytes_FromStringAndSize(buffer, + len); + if (line == NULL) + goto error; + Py_DECREF(v); + PyList_SET_ITEM(list, i, line); + } + } + + /* Since we are releasing the global lock, the + following code may *not* execute Python code. */ + Py_BEGIN_ALLOW_THREADS + for (i = 0; i < j; i++) { + line = PyList_GET_ITEM(list, i); + len = PyBytes_GET_SIZE(line); + BZ2_bzWrite (&bzerror, self->fp, + PyBytes_AS_STRING(line), len); + if (bzerror != BZ_OK) { + Py_BLOCK_THREADS + Util_CatchBZ2Error(bzerror); + goto error; + } + } + Py_END_ALLOW_THREADS + + if (j < CHUNKSIZE) + break; + } - Py_INCREF(Py_None); - ret = Py_None; + Py_INCREF(Py_None); + ret = Py_None; error: - RELEASE_LOCK(self); - Py_XDECREF(list); - Py_XDECREF(iter); - return ret; + RELEASE_LOCK(self); + Py_XDECREF(list); + Py_XDECREF(iter); + return ret; #undef CHUNKSIZE } @@ -889,135 +889,135 @@ static PyObject * BZ2File_seek(BZ2FileObject *self, PyObject *args) { - int where = 0; - PyObject *offobj; - Py_off_t offset; - char small_buffer[SMALLCHUNK]; - char *buffer = small_buffer; - size_t buffersize = SMALLCHUNK; - Py_off_t bytesread = 0; - size_t readsize; - int chunksize; - int bzerror; - PyObject *ret = NULL; + int where = 0; + PyObject *offobj; + Py_off_t offset; + char small_buffer[SMALLCHUNK]; + char *buffer = small_buffer; + size_t buffersize = SMALLCHUNK; + Py_off_t bytesread = 0; + size_t readsize; + int chunksize; + int bzerror; + PyObject *ret = NULL; - if (!PyArg_ParseTuple(args, "O|i:seek", &offobj, &where)) - return NULL; + if (!PyArg_ParseTuple(args, "O|i:seek", &offobj, &where)) + return NULL; #if !defined(HAVE_LARGEFILE_SUPPORT) - offset = PyLong_AsLong(offobj); + offset = PyLong_AsLong(offobj); #else - offset = PyLong_Check(offobj) ? - PyLong_AsLongLong(offobj) : PyLong_AsLong(offobj); + offset = PyLong_Check(offobj) ? + PyLong_AsLongLong(offobj) : PyLong_AsLong(offobj); #endif - if (PyErr_Occurred()) - return NULL; + if (PyErr_Occurred()) + return NULL; - ACQUIRE_LOCK(self); - Util_DropReadAhead(self); - switch (self->mode) { - case MODE_READ: - case MODE_READ_EOF: - break; - - case MODE_CLOSED: - PyErr_SetString(PyExc_ValueError, - "I/O operation on closed file"); - goto cleanup; - - default: - PyErr_SetString(PyExc_IOError, - "seek works only while reading"); - goto cleanup; - } - - if (where == 2) { - if (self->size == -1) { - assert(self->mode != MODE_READ_EOF); - for (;;) { - Py_BEGIN_ALLOW_THREADS - chunksize = BZ2_bzRead(&bzerror, self->fp, - buffer, buffersize); - self->pos += chunksize; - Py_END_ALLOW_THREADS - - bytesread += chunksize; - if (bzerror == BZ_STREAM_END) { - break; - } else if (bzerror != BZ_OK) { - Util_CatchBZ2Error(bzerror); - goto cleanup; - } - } - self->mode = MODE_READ_EOF; - self->size = self->pos; - bytesread = 0; - } - offset = self->size + offset; - } else if (where == 1) { - offset = self->pos + offset; - } - - /* Before getting here, offset must be the absolute position the file - * pointer should be set to. */ - - if (offset >= self->pos) { - /* we can move forward */ - offset -= self->pos; - } else { - /* we cannot move back, so rewind the stream */ - BZ2_bzReadClose(&bzerror, self->fp); - if (bzerror != BZ_OK) { - Util_CatchBZ2Error(bzerror); - goto cleanup; - } - rewind(self->rawfp); - self->pos = 0; - self->fp = BZ2_bzReadOpen(&bzerror, self->rawfp, - 0, 0, NULL, 0); - if (bzerror != BZ_OK) { - Util_CatchBZ2Error(bzerror); - goto cleanup; - } - self->mode = MODE_READ; - } - - if (offset <= 0 || self->mode == MODE_READ_EOF) - goto exit; - - /* Before getting here, offset must be set to the number of bytes - * to walk forward. */ - for (;;) { - if (offset-bytesread > buffersize) - readsize = buffersize; - else - /* offset might be wider that readsize, but the result - * of the subtraction is bound by buffersize (see the - * condition above). buffersize is 8192. */ - readsize = (size_t)(offset-bytesread); - Py_BEGIN_ALLOW_THREADS - chunksize = BZ2_bzRead(&bzerror, self->fp, buffer, readsize); - self->pos += chunksize; - Py_END_ALLOW_THREADS - bytesread += chunksize; - if (bzerror == BZ_STREAM_END) { - self->size = self->pos; - self->mode = MODE_READ_EOF; - break; - } else if (bzerror != BZ_OK) { - Util_CatchBZ2Error(bzerror); - goto cleanup; - } - if (bytesread == offset) - break; - } + ACQUIRE_LOCK(self); + Util_DropReadAhead(self); + switch (self->mode) { + case MODE_READ: + case MODE_READ_EOF: + break; + + case MODE_CLOSED: + PyErr_SetString(PyExc_ValueError, + "I/O operation on closed file"); + goto cleanup; + + default: + PyErr_SetString(PyExc_IOError, + "seek works only while reading"); + goto cleanup; + } + + if (where == 2) { + if (self->size == -1) { + assert(self->mode != MODE_READ_EOF); + for (;;) { + Py_BEGIN_ALLOW_THREADS + chunksize = BZ2_bzRead(&bzerror, self->fp, + buffer, buffersize); + self->pos += chunksize; + Py_END_ALLOW_THREADS + + bytesread += chunksize; + if (bzerror == BZ_STREAM_END) { + break; + } else if (bzerror != BZ_OK) { + Util_CatchBZ2Error(bzerror); + goto cleanup; + } + } + self->mode = MODE_READ_EOF; + self->size = self->pos; + bytesread = 0; + } + offset = self->size + offset; + } else if (where == 1) { + offset = self->pos + offset; + } + + /* Before getting here, offset must be the absolute position the file + * pointer should be set to. */ + + if (offset >= self->pos) { + /* we can move forward */ + offset -= self->pos; + } else { + /* we cannot move back, so rewind the stream */ + BZ2_bzReadClose(&bzerror, self->fp); + if (bzerror != BZ_OK) { + Util_CatchBZ2Error(bzerror); + goto cleanup; + } + rewind(self->rawfp); + self->pos = 0; + self->fp = BZ2_bzReadOpen(&bzerror, self->rawfp, + 0, 0, NULL, 0); + if (bzerror != BZ_OK) { + Util_CatchBZ2Error(bzerror); + goto cleanup; + } + self->mode = MODE_READ; + } + + if (offset <= 0 || self->mode == MODE_READ_EOF) + goto exit; + + /* Before getting here, offset must be set to the number of bytes + * to walk forward. */ + for (;;) { + if (offset-bytesread > buffersize) + readsize = buffersize; + else + /* offset might be wider that readsize, but the result + * of the subtraction is bound by buffersize (see the + * condition above). buffersize is 8192. */ + readsize = (size_t)(offset-bytesread); + Py_BEGIN_ALLOW_THREADS + chunksize = BZ2_bzRead(&bzerror, self->fp, buffer, readsize); + self->pos += chunksize; + Py_END_ALLOW_THREADS + bytesread += chunksize; + if (bzerror == BZ_STREAM_END) { + self->size = self->pos; + self->mode = MODE_READ_EOF; + break; + } else if (bzerror != BZ_OK) { + Util_CatchBZ2Error(bzerror); + goto cleanup; + } + if (bytesread == offset) + break; + } exit: - Py_INCREF(Py_None); - ret = Py_None; + Py_INCREF(Py_None); + ret = Py_None; cleanup: - RELEASE_LOCK(self); - return ret; + RELEASE_LOCK(self); + return ret; } PyDoc_STRVAR(BZ2File_tell__doc__, @@ -1029,22 +1029,22 @@ static PyObject * BZ2File_tell(BZ2FileObject *self, PyObject *args) { - PyObject *ret = NULL; + PyObject *ret = NULL; - if (self->mode == MODE_CLOSED) { - PyErr_SetString(PyExc_ValueError, - "I/O operation on closed file"); - goto cleanup; - } + if (self->mode == MODE_CLOSED) { + PyErr_SetString(PyExc_ValueError, + "I/O operation on closed file"); + goto cleanup; + } #if !defined(HAVE_LARGEFILE_SUPPORT) - ret = PyLong_FromLong(self->pos); + ret = PyLong_FromLong(self->pos); #else - ret = PyLong_FromLongLong(self->pos); + ret = PyLong_FromLongLong(self->pos); #endif cleanup: - return ret; + return ret; } PyDoc_STRVAR(BZ2File_close__doc__, @@ -1058,37 +1058,37 @@ static PyObject * BZ2File_close(BZ2FileObject *self) { - PyObject *ret = NULL; - int bzerror = BZ_OK; + PyObject *ret = NULL; + int bzerror = BZ_OK; - if (self->mode == MODE_CLOSED) { - Py_RETURN_NONE; - } - - ACQUIRE_LOCK(self); - switch (self->mode) { - case MODE_READ: - case MODE_READ_EOF: - BZ2_bzReadClose(&bzerror, self->fp); - break; - case MODE_WRITE: - BZ2_bzWriteClose(&bzerror, self->fp, - 0, NULL, NULL); - break; - } - self->mode = MODE_CLOSED; - fclose(self->rawfp); - self->rawfp = NULL; - if (bzerror == BZ_OK) { - Py_INCREF(Py_None); - ret = Py_None; - } - else { - Util_CatchBZ2Error(bzerror); - } + if (self->mode == MODE_CLOSED) { + Py_RETURN_NONE; + } + + ACQUIRE_LOCK(self); + switch (self->mode) { + case MODE_READ: + case MODE_READ_EOF: + BZ2_bzReadClose(&bzerror, self->fp); + break; + case MODE_WRITE: + BZ2_bzWriteClose(&bzerror, self->fp, + 0, NULL, NULL); + break; + } + self->mode = MODE_CLOSED; + fclose(self->rawfp); + self->rawfp = NULL; + if (bzerror == BZ_OK) { + Py_INCREF(Py_None); + ret = Py_None; + } + else { + Util_CatchBZ2Error(bzerror); + } - RELEASE_LOCK(self); - return ret; + RELEASE_LOCK(self); + return ret; } PyDoc_STRVAR(BZ2File_enter_doc, @@ -1097,13 +1097,13 @@ static PyObject * BZ2File_enter(BZ2FileObject *self) { - if (self->mode == MODE_CLOSED) { - PyErr_SetString(PyExc_ValueError, - "I/O operation on closed file"); - return NULL; - } - Py_INCREF(self); - return (PyObject *) self; + if (self->mode == MODE_CLOSED) { + PyErr_SetString(PyExc_ValueError, + "I/O operation on closed file"); + return NULL; + } + Py_INCREF(self); + return (PyObject *) self; } PyDoc_STRVAR(BZ2File_exit_doc, @@ -1112,29 +1112,29 @@ static PyObject * BZ2File_exit(BZ2FileObject *self, PyObject *args) { - PyObject *ret = PyObject_CallMethod((PyObject *) self, "close", NULL); - if (!ret) - /* If error occurred, pass through */ - return NULL; - Py_DECREF(ret); - Py_RETURN_NONE; + PyObject *ret = PyObject_CallMethod((PyObject *) self, "close", NULL); + if (!ret) + /* If error occurred, pass through */ + return NULL; + Py_DECREF(ret); + Py_RETURN_NONE; } static PyObject *BZ2File_getiter(BZ2FileObject *self); static PyMethodDef BZ2File_methods[] = { - {"read", (PyCFunction)BZ2File_read, METH_VARARGS, BZ2File_read__doc__}, - {"readline", (PyCFunction)BZ2File_readline, METH_VARARGS, BZ2File_readline__doc__}, - {"readlines", (PyCFunction)BZ2File_readlines, METH_VARARGS, BZ2File_readlines__doc__}, - {"write", (PyCFunction)BZ2File_write, METH_VARARGS, BZ2File_write__doc__}, - {"writelines", (PyCFunction)BZ2File_writelines, METH_O, BZ2File_writelines__doc__}, - {"seek", (PyCFunction)BZ2File_seek, METH_VARARGS, BZ2File_seek__doc__}, - {"tell", (PyCFunction)BZ2File_tell, METH_NOARGS, BZ2File_tell__doc__}, - {"close", (PyCFunction)BZ2File_close, METH_NOARGS, BZ2File_close__doc__}, - {"__enter__", (PyCFunction)BZ2File_enter, METH_NOARGS, BZ2File_enter_doc}, - {"__exit__", (PyCFunction)BZ2File_exit, METH_VARARGS, BZ2File_exit_doc}, - {NULL, NULL} /* sentinel */ + {"read", (PyCFunction)BZ2File_read, METH_VARARGS, BZ2File_read__doc__}, + {"readline", (PyCFunction)BZ2File_readline, METH_VARARGS, BZ2File_readline__doc__}, + {"readlines", (PyCFunction)BZ2File_readlines, METH_VARARGS, BZ2File_readlines__doc__}, + {"write", (PyCFunction)BZ2File_write, METH_VARARGS, BZ2File_write__doc__}, + {"writelines", (PyCFunction)BZ2File_writelines, METH_O, BZ2File_writelines__doc__}, + {"seek", (PyCFunction)BZ2File_seek, METH_VARARGS, BZ2File_seek__doc__}, + {"tell", (PyCFunction)BZ2File_tell, METH_NOARGS, BZ2File_tell__doc__}, + {"close", (PyCFunction)BZ2File_close, METH_NOARGS, BZ2File_close__doc__}, + {"__enter__", (PyCFunction)BZ2File_enter, METH_NOARGS, BZ2File_enter_doc}, + {"__exit__", (PyCFunction)BZ2File_exit, METH_VARARGS, BZ2File_exit_doc}, + {NULL, NULL} /* sentinel */ }; @@ -1144,13 +1144,13 @@ static PyObject * BZ2File_get_closed(BZ2FileObject *self, void *closure) { - return PyLong_FromLong(self->mode == MODE_CLOSED); + return PyLong_FromLong(self->mode == MODE_CLOSED); } static PyGetSetDef BZ2File_getset[] = { - {"closed", (getter)BZ2File_get_closed, NULL, - "True if the file is closed"}, - {NULL} /* Sentinel */ + {"closed", (getter)BZ2File_get_closed, NULL, + "True if the file is closed"}, + {NULL} /* Sentinel */ }; @@ -1160,148 +1160,148 @@ static int BZ2File_init(BZ2FileObject *self, PyObject *args, PyObject *kwargs) { - static char *kwlist[] = {"filename", "mode", "buffering", - "compresslevel", 0}; - PyObject *name_obj = NULL; - char *name; - char *mode = "r"; - int buffering = -1; - int compresslevel = 9; - int bzerror; - int mode_char = 0; - - self->size = -1; - - if (!PyArg_ParseTupleAndKeywords(args, kwargs, "O&|sii:BZ2File", - kwlist, PyUnicode_FSConverter, &name_obj, - &mode, &buffering, - &compresslevel)) - return -1; - - name = PyBytes_AsString(name_obj); - if (compresslevel < 1 || compresslevel > 9) { - PyErr_SetString(PyExc_ValueError, - "compresslevel must be between 1 and 9"); - Py_DECREF(name_obj); - return -1; - } - - for (;;) { - int error = 0; - switch (*mode) { - case 'r': - case 'w': - if (mode_char) - error = 1; - mode_char = *mode; - break; - - case 'b': - break; - - default: - error = 1; - break; - } - if (error) { - PyErr_Format(PyExc_ValueError, - "invalid mode char %c", *mode); - Py_DECREF(name_obj); - return -1; - } - mode++; - if (*mode == '\0') - break; - } - - if (mode_char == 0) { - mode_char = 'r'; - } - - mode = (mode_char == 'r') ? "rb" : "wb"; - - self->rawfp = fopen(name, mode); - Py_DECREF(name_obj); - if (self->rawfp == NULL) { - PyErr_SetFromErrno(PyExc_IOError); - return -1; - } - /* XXX Ignore buffering */ + static char *kwlist[] = {"filename", "mode", "buffering", + "compresslevel", 0}; + PyObject *name_obj = NULL; + char *name; + char *mode = "r"; + int buffering = -1; + int compresslevel = 9; + int bzerror; + int mode_char = 0; + + self->size = -1; + + if (!PyArg_ParseTupleAndKeywords(args, kwargs, "O&|sii:BZ2File", + kwlist, PyUnicode_FSConverter, &name_obj, + &mode, &buffering, + &compresslevel)) + return -1; + + name = PyBytes_AsString(name_obj); + if (compresslevel < 1 || compresslevel > 9) { + PyErr_SetString(PyExc_ValueError, + "compresslevel must be between 1 and 9"); + Py_DECREF(name_obj); + return -1; + } + + for (;;) { + int error = 0; + switch (*mode) { + case 'r': + case 'w': + if (mode_char) + error = 1; + mode_char = *mode; + break; + + case 'b': + break; + + default: + error = 1; + break; + } + if (error) { + PyErr_Format(PyExc_ValueError, + "invalid mode char %c", *mode); + Py_DECREF(name_obj); + return -1; + } + mode++; + if (*mode == '\0') + break; + } + + if (mode_char == 0) { + mode_char = 'r'; + } + + mode = (mode_char == 'r') ? "rb" : "wb"; + + self->rawfp = fopen(name, mode); + Py_DECREF(name_obj); + if (self->rawfp == NULL) { + PyErr_SetFromErrno(PyExc_IOError); + return -1; + } + /* XXX Ignore buffering */ - /* From now on, we have stuff to dealloc, so jump to error label - * instead of returning */ + /* From now on, we have stuff to dealloc, so jump to error label + * instead of returning */ #ifdef WITH_THREAD - self->lock = PyThread_allocate_lock(); - if (!self->lock) { - PyErr_SetString(PyExc_MemoryError, "unable to allocate lock"); - goto error; - } + self->lock = PyThread_allocate_lock(); + if (!self->lock) { + PyErr_SetString(PyExc_MemoryError, "unable to allocate lock"); + goto error; + } #endif - if (mode_char == 'r') - self->fp = BZ2_bzReadOpen(&bzerror, self->rawfp, - 0, 0, NULL, 0); - else - self->fp = BZ2_bzWriteOpen(&bzerror, self->rawfp, - compresslevel, 0, 0); - - if (bzerror != BZ_OK) { - Util_CatchBZ2Error(bzerror); - goto error; - } + if (mode_char == 'r') + self->fp = BZ2_bzReadOpen(&bzerror, self->rawfp, + 0, 0, NULL, 0); + else + self->fp = BZ2_bzWriteOpen(&bzerror, self->rawfp, + compresslevel, 0, 0); + + if (bzerror != BZ_OK) { + Util_CatchBZ2Error(bzerror); + goto error; + } - self->mode = (mode_char == 'r') ? MODE_READ : MODE_WRITE; + self->mode = (mode_char == 'r') ? MODE_READ : MODE_WRITE; - return 0; + return 0; error: - fclose(self->rawfp); - self->rawfp = NULL; + fclose(self->rawfp); + self->rawfp = NULL; #ifdef WITH_THREAD - if (self->lock) { - PyThread_free_lock(self->lock); - self->lock = NULL; - } + if (self->lock) { + PyThread_free_lock(self->lock); + self->lock = NULL; + } #endif - return -1; + return -1; } static void BZ2File_dealloc(BZ2FileObject *self) { - int bzerror; + int bzerror; #ifdef WITH_THREAD - if (self->lock) - PyThread_free_lock(self->lock); + if (self->lock) + PyThread_free_lock(self->lock); #endif - switch (self->mode) { - case MODE_READ: - case MODE_READ_EOF: - BZ2_bzReadClose(&bzerror, self->fp); - break; - case MODE_WRITE: - BZ2_bzWriteClose(&bzerror, self->fp, - 0, NULL, NULL); - break; - } - Util_DropReadAhead(self); - if (self->rawfp != NULL) - fclose(self->rawfp); - Py_TYPE(self)->tp_free((PyObject *)self); + switch (self->mode) { + case MODE_READ: + case MODE_READ_EOF: + BZ2_bzReadClose(&bzerror, self->fp); + break; + case MODE_WRITE: + BZ2_bzWriteClose(&bzerror, self->fp, + 0, NULL, NULL); + break; + } + Util_DropReadAhead(self); + if (self->rawfp != NULL) + fclose(self->rawfp); + Py_TYPE(self)->tp_free((PyObject *)self); } /* This is a hacked version of Python's fileobject.c:file_getiter(). */ static PyObject * BZ2File_getiter(BZ2FileObject *self) { - if (self->mode == MODE_CLOSED) { - PyErr_SetString(PyExc_ValueError, - "I/O operation on closed file"); - return NULL; - } - Py_INCREF((PyObject*)self); - return (PyObject *)self; + if (self->mode == MODE_CLOSED) { + PyErr_SetString(PyExc_ValueError, + "I/O operation on closed file"); + return NULL; + } + Py_INCREF((PyObject*)self); + return (PyObject *)self; } /* This is a hacked version of Python's fileobject.c:file_iternext(). */ @@ -1309,21 +1309,21 @@ static PyObject * BZ2File_iternext(BZ2FileObject *self) { - PyBytesObject* ret; - ACQUIRE_LOCK(self); - if (self->mode == MODE_CLOSED) { - RELEASE_LOCK(self); - PyErr_SetString(PyExc_ValueError, - "I/O operation on closed file"); - return NULL; - } - ret = Util_ReadAheadGetLineSkip(self, 0, READAHEAD_BUFSIZE); - RELEASE_LOCK(self); - if (ret == NULL || PyBytes_GET_SIZE(ret) == 0) { - Py_XDECREF(ret); - return NULL; - } - return (PyObject *)ret; + PyBytesObject* ret; + ACQUIRE_LOCK(self); + if (self->mode == MODE_CLOSED) { + RELEASE_LOCK(self); + PyErr_SetString(PyExc_ValueError, + "I/O operation on closed file"); + return NULL; + } + ret = Util_ReadAheadGetLineSkip(self, 0, READAHEAD_BUFSIZE); + RELEASE_LOCK(self); + if (ret == NULL || PyBytes_GET_SIZE(ret) == 0) { + Py_XDECREF(ret); + return NULL; + } + return (PyObject *)ret; } /* ===================================================================== */ @@ -1342,46 +1342,46 @@ "); static PyTypeObject BZ2File_Type = { - PyVarObject_HEAD_INIT(NULL, 0) - "bz2.BZ2File", /*tp_name*/ - sizeof(BZ2FileObject), /*tp_basicsize*/ - 0, /*tp_itemsize*/ - (destructor)BZ2File_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*/ - PyObject_GenericSetAttr,/*tp_setattro*/ - 0, /*tp_as_buffer*/ - Py_TPFLAGS_DEFAULT|Py_TPFLAGS_BASETYPE, /*tp_flags*/ - BZ2File__doc__, /*tp_doc*/ - 0, /*tp_traverse*/ - 0, /*tp_clear*/ - 0, /*tp_richcompare*/ - 0, /*tp_weaklistoffset*/ - (getiterfunc)BZ2File_getiter, /*tp_iter*/ - (iternextfunc)BZ2File_iternext, /*tp_iternext*/ - BZ2File_methods, /*tp_methods*/ - 0, /*tp_members*/ - BZ2File_getset, /*tp_getset*/ - 0, /*tp_base*/ - 0, /*tp_dict*/ - 0, /*tp_descr_get*/ - 0, /*tp_descr_set*/ - 0, /*tp_dictoffset*/ - (initproc)BZ2File_init, /*tp_init*/ - PyType_GenericAlloc, /*tp_alloc*/ - PyType_GenericNew, /*tp_new*/ - PyObject_Free, /*tp_free*/ - 0, /*tp_is_gc*/ + PyVarObject_HEAD_INIT(NULL, 0) + "bz2.BZ2File", /*tp_name*/ + sizeof(BZ2FileObject), /*tp_basicsize*/ + 0, /*tp_itemsize*/ + (destructor)BZ2File_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*/ + PyObject_GenericSetAttr,/*tp_setattro*/ + 0, /*tp_as_buffer*/ + Py_TPFLAGS_DEFAULT|Py_TPFLAGS_BASETYPE, /*tp_flags*/ + BZ2File__doc__, /*tp_doc*/ + 0, /*tp_traverse*/ + 0, /*tp_clear*/ + 0, /*tp_richcompare*/ + 0, /*tp_weaklistoffset*/ + (getiterfunc)BZ2File_getiter, /*tp_iter*/ + (iternextfunc)BZ2File_iternext, /*tp_iternext*/ + BZ2File_methods, /*tp_methods*/ + 0, /*tp_members*/ + BZ2File_getset, /*tp_getset*/ + 0, /*tp_base*/ + 0, /*tp_dict*/ + 0, /*tp_descr_get*/ + 0, /*tp_descr_set*/ + 0, /*tp_dictoffset*/ + (initproc)BZ2File_init, /*tp_init*/ + PyType_GenericAlloc, /*tp_alloc*/ + PyType_GenericNew, /*tp_new*/ + PyObject_Free, /*tp_free*/ + 0, /*tp_is_gc*/ }; @@ -1400,78 +1400,78 @@ static PyObject * BZ2Comp_compress(BZ2CompObject *self, PyObject *args) { - Py_buffer pdata; - char *data; - int datasize; - int bufsize = SMALLCHUNK; - PY_LONG_LONG totalout; - PyObject *ret = NULL; - bz_stream *bzs = &self->bzs; - int bzerror; - - if (!PyArg_ParseTuple(args, "y*:compress", &pdata)) - return NULL; - data = pdata.buf; - datasize = pdata.len; - - if (datasize == 0) { - PyBuffer_Release(&pdata); - return PyBytes_FromStringAndSize("", 0); - } - - ACQUIRE_LOCK(self); - if (!self->running) { - PyErr_SetString(PyExc_ValueError, - "this object was already flushed"); - goto error; - } - - ret = PyBytes_FromStringAndSize(NULL, bufsize); - if (!ret) - goto error; - - bzs->next_in = data; - bzs->avail_in = datasize; - bzs->next_out = BUF(ret); - bzs->avail_out = bufsize; - - totalout = BZS_TOTAL_OUT(bzs); - - for (;;) { - Py_BEGIN_ALLOW_THREADS - bzerror = BZ2_bzCompress(bzs, BZ_RUN); - Py_END_ALLOW_THREADS - if (bzerror != BZ_RUN_OK) { - Util_CatchBZ2Error(bzerror); - goto error; - } - if (bzs->avail_in == 0) - break; /* no more input data */ - if (bzs->avail_out == 0) { - bufsize = Util_NewBufferSize(bufsize); - if (_PyBytes_Resize(&ret, bufsize) < 0) { - BZ2_bzCompressEnd(bzs); - goto error; - } - bzs->next_out = BUF(ret) + (BZS_TOTAL_OUT(bzs) - - totalout); - bzs->avail_out = bufsize - (bzs->next_out - BUF(ret)); - } - } - - if (_PyBytes_Resize(&ret, - (Py_ssize_t)(BZS_TOTAL_OUT(bzs) - totalout)) < 0) - goto error; - - RELEASE_LOCK(self); - PyBuffer_Release(&pdata); - return ret; + Py_buffer pdata; + char *data; + int datasize; + int bufsize = SMALLCHUNK; + PY_LONG_LONG totalout; + PyObject *ret = NULL; + bz_stream *bzs = &self->bzs; + int bzerror; + + if (!PyArg_ParseTuple(args, "y*:compress", &pdata)) + return NULL; + data = pdata.buf; + datasize = pdata.len; + + if (datasize == 0) { + PyBuffer_Release(&pdata); + return PyBytes_FromStringAndSize("", 0); + } + + ACQUIRE_LOCK(self); + if (!self->running) { + PyErr_SetString(PyExc_ValueError, + "this object was already flushed"); + goto error; + } + + ret = PyBytes_FromStringAndSize(NULL, bufsize); + if (!ret) + goto error; + + bzs->next_in = data; + bzs->avail_in = datasize; + bzs->next_out = BUF(ret); + bzs->avail_out = bufsize; + + totalout = BZS_TOTAL_OUT(bzs); + + for (;;) { + Py_BEGIN_ALLOW_THREADS + bzerror = BZ2_bzCompress(bzs, BZ_RUN); + Py_END_ALLOW_THREADS + if (bzerror != BZ_RUN_OK) { + Util_CatchBZ2Error(bzerror); + goto error; + } + if (bzs->avail_in == 0) + break; /* no more input data */ + if (bzs->avail_out == 0) { + bufsize = Util_NewBufferSize(bufsize); + if (_PyBytes_Resize(&ret, bufsize) < 0) { + BZ2_bzCompressEnd(bzs); + goto error; + } + bzs->next_out = BUF(ret) + (BZS_TOTAL_OUT(bzs) + - totalout); + bzs->avail_out = bufsize - (bzs->next_out - BUF(ret)); + } + } + + if (_PyBytes_Resize(&ret, + (Py_ssize_t)(BZS_TOTAL_OUT(bzs) - totalout)) < 0) + goto error; + + RELEASE_LOCK(self); + PyBuffer_Release(&pdata); + return ret; error: - RELEASE_LOCK(self); - PyBuffer_Release(&pdata); - Py_XDECREF(ret); - return NULL; + RELEASE_LOCK(self); + PyBuffer_Release(&pdata); + Py_XDECREF(ret); + return NULL; } PyDoc_STRVAR(BZ2Comp_flush__doc__, @@ -1484,71 +1484,71 @@ static PyObject * BZ2Comp_flush(BZ2CompObject *self) { - int bufsize = SMALLCHUNK; - PyObject *ret = NULL; - bz_stream *bzs = &self->bzs; - PY_LONG_LONG totalout; - int bzerror; - - ACQUIRE_LOCK(self); - if (!self->running) { - PyErr_SetString(PyExc_ValueError, "object was already " - "flushed"); - goto error; - } - self->running = 0; - - ret = PyBytes_FromStringAndSize(NULL, bufsize); - if (!ret) - goto error; - - bzs->next_out = BUF(ret); - bzs->avail_out = bufsize; - - totalout = BZS_TOTAL_OUT(bzs); - - for (;;) { - Py_BEGIN_ALLOW_THREADS - bzerror = BZ2_bzCompress(bzs, BZ_FINISH); - Py_END_ALLOW_THREADS - if (bzerror == BZ_STREAM_END) { - break; - } else if (bzerror != BZ_FINISH_OK) { - Util_CatchBZ2Error(bzerror); - goto error; - } - if (bzs->avail_out == 0) { - bufsize = Util_NewBufferSize(bufsize); - if (_PyBytes_Resize(&ret, bufsize) < 0) - goto error; - bzs->next_out = BUF(ret); - bzs->next_out = BUF(ret) + (BZS_TOTAL_OUT(bzs) - - totalout); - bzs->avail_out = bufsize - (bzs->next_out - BUF(ret)); - } - } - - if (bzs->avail_out != 0) { - if (_PyBytes_Resize(&ret, - (Py_ssize_t)(BZS_TOTAL_OUT(bzs) - totalout)) < 0) - goto error; - } + int bufsize = SMALLCHUNK; + PyObject *ret = NULL; + bz_stream *bzs = &self->bzs; + PY_LONG_LONG totalout; + int bzerror; + + ACQUIRE_LOCK(self); + if (!self->running) { + PyErr_SetString(PyExc_ValueError, "object was already " + "flushed"); + goto error; + } + self->running = 0; + + ret = PyBytes_FromStringAndSize(NULL, bufsize); + if (!ret) + goto error; + + bzs->next_out = BUF(ret); + bzs->avail_out = bufsize; + + totalout = BZS_TOTAL_OUT(bzs); + + for (;;) { + Py_BEGIN_ALLOW_THREADS + bzerror = BZ2_bzCompress(bzs, BZ_FINISH); + Py_END_ALLOW_THREADS + if (bzerror == BZ_STREAM_END) { + break; + } else if (bzerror != BZ_FINISH_OK) { + Util_CatchBZ2Error(bzerror); + goto error; + } + if (bzs->avail_out == 0) { + bufsize = Util_NewBufferSize(bufsize); + if (_PyBytes_Resize(&ret, bufsize) < 0) + goto error; + bzs->next_out = BUF(ret); + bzs->next_out = BUF(ret) + (BZS_TOTAL_OUT(bzs) + - totalout); + bzs->avail_out = bufsize - (bzs->next_out - BUF(ret)); + } + } + + if (bzs->avail_out != 0) { + if (_PyBytes_Resize(&ret, + (Py_ssize_t)(BZS_TOTAL_OUT(bzs) - totalout)) < 0) + goto error; + } - RELEASE_LOCK(self); - return ret; + RELEASE_LOCK(self); + return ret; error: - RELEASE_LOCK(self); - Py_XDECREF(ret); - return NULL; + RELEASE_LOCK(self); + Py_XDECREF(ret); + return NULL; } static PyMethodDef BZ2Comp_methods[] = { - {"compress", (PyCFunction)BZ2Comp_compress, METH_VARARGS, - BZ2Comp_compress__doc__}, - {"flush", (PyCFunction)BZ2Comp_flush, METH_NOARGS, - BZ2Comp_flush__doc__}, - {NULL, NULL} /* sentinel */ + {"compress", (PyCFunction)BZ2Comp_compress, METH_VARARGS, + BZ2Comp_compress__doc__}, + {"flush", (PyCFunction)BZ2Comp_flush, METH_NOARGS, + BZ2Comp_flush__doc__}, + {NULL, NULL} /* sentinel */ }; @@ -1558,57 +1558,57 @@ static int BZ2Comp_init(BZ2CompObject *self, PyObject *args, PyObject *kwargs) { - int compresslevel = 9; - int bzerror; - static char *kwlist[] = {"compresslevel", 0}; - - if (!PyArg_ParseTupleAndKeywords(args, kwargs, "|i:BZ2Compressor", - kwlist, &compresslevel)) - return -1; - - if (compresslevel < 1 || compresslevel > 9) { - PyErr_SetString(PyExc_ValueError, - "compresslevel must be between 1 and 9"); - goto error; - } + int compresslevel = 9; + int bzerror; + static char *kwlist[] = {"compresslevel", 0}; + + if (!PyArg_ParseTupleAndKeywords(args, kwargs, "|i:BZ2Compressor", + kwlist, &compresslevel)) + return -1; + + if (compresslevel < 1 || compresslevel > 9) { + PyErr_SetString(PyExc_ValueError, + "compresslevel must be between 1 and 9"); + goto error; + } #ifdef WITH_THREAD - self->lock = PyThread_allocate_lock(); - if (!self->lock) { - PyErr_SetString(PyExc_MemoryError, "unable to allocate lock"); - goto error; - } + self->lock = PyThread_allocate_lock(); + if (!self->lock) { + PyErr_SetString(PyExc_MemoryError, "unable to allocate lock"); + goto error; + } #endif - memset(&self->bzs, 0, sizeof(bz_stream)); - bzerror = BZ2_bzCompressInit(&self->bzs, compresslevel, 0, 0); - if (bzerror != BZ_OK) { - Util_CatchBZ2Error(bzerror); - goto error; - } + memset(&self->bzs, 0, sizeof(bz_stream)); + bzerror = BZ2_bzCompressInit(&self->bzs, compresslevel, 0, 0); + if (bzerror != BZ_OK) { + Util_CatchBZ2Error(bzerror); + goto error; + } - self->running = 1; + self->running = 1; - return 0; + return 0; error: #ifdef WITH_THREAD - if (self->lock) { - PyThread_free_lock(self->lock); - self->lock = NULL; - } + if (self->lock) { + PyThread_free_lock(self->lock); + self->lock = NULL; + } #endif - return -1; + return -1; } static void BZ2Comp_dealloc(BZ2CompObject *self) { #ifdef WITH_THREAD - if (self->lock) - PyThread_free_lock(self->lock); + if (self->lock) + PyThread_free_lock(self->lock); #endif - BZ2_bzCompressEnd(&self->bzs); - Py_TYPE(self)->tp_free((PyObject *)self); + BZ2_bzCompressEnd(&self->bzs); + Py_TYPE(self)->tp_free((PyObject *)self); } @@ -1625,46 +1625,46 @@ "); static PyTypeObject BZ2Comp_Type = { - PyVarObject_HEAD_INIT(NULL, 0) - "bz2.BZ2Compressor", /*tp_name*/ - sizeof(BZ2CompObject), /*tp_basicsize*/ - 0, /*tp_itemsize*/ - (destructor)BZ2Comp_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*/ - PyObject_GenericSetAttr,/*tp_setattro*/ - 0, /*tp_as_buffer*/ - Py_TPFLAGS_DEFAULT|Py_TPFLAGS_BASETYPE, /*tp_flags*/ - BZ2Comp__doc__, /*tp_doc*/ - 0, /*tp_traverse*/ - 0, /*tp_clear*/ - 0, /*tp_richcompare*/ - 0, /*tp_weaklistoffset*/ - 0, /*tp_iter*/ - 0, /*tp_iternext*/ - BZ2Comp_methods, /*tp_methods*/ - 0, /*tp_members*/ - 0, /*tp_getset*/ - 0, /*tp_base*/ - 0, /*tp_dict*/ - 0, /*tp_descr_get*/ - 0, /*tp_descr_set*/ - 0, /*tp_dictoffset*/ - (initproc)BZ2Comp_init, /*tp_init*/ - PyType_GenericAlloc, /*tp_alloc*/ - PyType_GenericNew, /*tp_new*/ - PyObject_Free, /*tp_free*/ - 0, /*tp_is_gc*/ + PyVarObject_HEAD_INIT(NULL, 0) + "bz2.BZ2Compressor", /*tp_name*/ + sizeof(BZ2CompObject), /*tp_basicsize*/ + 0, /*tp_itemsize*/ + (destructor)BZ2Comp_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*/ + PyObject_GenericSetAttr,/*tp_setattro*/ + 0, /*tp_as_buffer*/ + Py_TPFLAGS_DEFAULT|Py_TPFLAGS_BASETYPE, /*tp_flags*/ + BZ2Comp__doc__, /*tp_doc*/ + 0, /*tp_traverse*/ + 0, /*tp_clear*/ + 0, /*tp_richcompare*/ + 0, /*tp_weaklistoffset*/ + 0, /*tp_iter*/ + 0, /*tp_iternext*/ + BZ2Comp_methods, /*tp_methods*/ + 0, /*tp_members*/ + 0, /*tp_getset*/ + 0, /*tp_base*/ + 0, /*tp_dict*/ + 0, /*tp_descr_get*/ + 0, /*tp_descr_set*/ + 0, /*tp_dictoffset*/ + (initproc)BZ2Comp_init, /*tp_init*/ + PyType_GenericAlloc, /*tp_alloc*/ + PyType_GenericNew, /*tp_new*/ + PyObject_Free, /*tp_free*/ + 0, /*tp_is_gc*/ }; @@ -1675,8 +1675,8 @@ #define OFF(x) offsetof(BZ2DecompObject, x) static PyMemberDef BZ2Decomp_members[] = { - {"unused_data", T_OBJECT, OFF(unused_data), READONLY}, - {NULL} /* Sentinel */ + {"unused_data", T_OBJECT, OFF(unused_data), READONLY}, + {NULL} /* Sentinel */ }; @@ -1696,91 +1696,91 @@ static PyObject * BZ2Decomp_decompress(BZ2DecompObject *self, PyObject *args) { - Py_buffer pdata; - char *data; - int datasize; - int bufsize = SMALLCHUNK; - PY_LONG_LONG totalout; - PyObject *ret = NULL; - bz_stream *bzs = &self->bzs; - int bzerror; - - if (!PyArg_ParseTuple(args, "y*:decompress", &pdata)) - return NULL; - data = pdata.buf; - datasize = pdata.len; - - ACQUIRE_LOCK(self); - if (!self->running) { - PyErr_SetString(PyExc_EOFError, "end of stream was " - "already found"); - goto error; - } - - ret = PyBytes_FromStringAndSize(NULL, bufsize); - if (!ret) - goto error; - - bzs->next_in = data; - bzs->avail_in = datasize; - bzs->next_out = BUF(ret); - bzs->avail_out = bufsize; - - totalout = BZS_TOTAL_OUT(bzs); - - for (;;) { - Py_BEGIN_ALLOW_THREADS - bzerror = BZ2_bzDecompress(bzs); - Py_END_ALLOW_THREADS - if (bzerror == BZ_STREAM_END) { - if (bzs->avail_in != 0) { - Py_DECREF(self->unused_data); - self->unused_data = - PyBytes_FromStringAndSize(bzs->next_in, - bzs->avail_in); - } - self->running = 0; - break; - } - if (bzerror != BZ_OK) { - Util_CatchBZ2Error(bzerror); - goto error; - } - if (bzs->avail_in == 0) - break; /* no more input data */ - if (bzs->avail_out == 0) { - bufsize = Util_NewBufferSize(bufsize); - if (_PyBytes_Resize(&ret, bufsize) < 0) { - BZ2_bzDecompressEnd(bzs); - goto error; - } - bzs->next_out = BUF(ret); - bzs->next_out = BUF(ret) + (BZS_TOTAL_OUT(bzs) - - totalout); - bzs->avail_out = bufsize - (bzs->next_out - BUF(ret)); - } - } - - if (bzs->avail_out != 0) { - if (_PyBytes_Resize(&ret, - (Py_ssize_t)(BZS_TOTAL_OUT(bzs) - totalout)) < 0) - goto error; - } - - RELEASE_LOCK(self); - PyBuffer_Release(&pdata); - return ret; + Py_buffer pdata; + char *data; + int datasize; + int bufsize = SMALLCHUNK; + PY_LONG_LONG totalout; + PyObject *ret = NULL; + bz_stream *bzs = &self->bzs; + int bzerror; + + if (!PyArg_ParseTuple(args, "y*:decompress", &pdata)) + return NULL; + data = pdata.buf; + datasize = pdata.len; + + ACQUIRE_LOCK(self); + if (!self->running) { + PyErr_SetString(PyExc_EOFError, "end of stream was " + "already found"); + goto error; + } + + ret = PyBytes_FromStringAndSize(NULL, bufsize); + if (!ret) + goto error; + + bzs->next_in = data; + bzs->avail_in = datasize; + bzs->next_out = BUF(ret); + bzs->avail_out = bufsize; + + totalout = BZS_TOTAL_OUT(bzs); + + for (;;) { + Py_BEGIN_ALLOW_THREADS + bzerror = BZ2_bzDecompress(bzs); + Py_END_ALLOW_THREADS + if (bzerror == BZ_STREAM_END) { + if (bzs->avail_in != 0) { + Py_DECREF(self->unused_data); + self->unused_data = + PyBytes_FromStringAndSize(bzs->next_in, + bzs->avail_in); + } + self->running = 0; + break; + } + if (bzerror != BZ_OK) { + Util_CatchBZ2Error(bzerror); + goto error; + } + if (bzs->avail_in == 0) + break; /* no more input data */ + if (bzs->avail_out == 0) { + bufsize = Util_NewBufferSize(bufsize); + if (_PyBytes_Resize(&ret, bufsize) < 0) { + BZ2_bzDecompressEnd(bzs); + goto error; + } + bzs->next_out = BUF(ret); + bzs->next_out = BUF(ret) + (BZS_TOTAL_OUT(bzs) + - totalout); + bzs->avail_out = bufsize - (bzs->next_out - BUF(ret)); + } + } + + if (bzs->avail_out != 0) { + if (_PyBytes_Resize(&ret, + (Py_ssize_t)(BZS_TOTAL_OUT(bzs) - totalout)) < 0) + goto error; + } + + RELEASE_LOCK(self); + PyBuffer_Release(&pdata); + return ret; error: - RELEASE_LOCK(self); - PyBuffer_Release(&pdata); - Py_XDECREF(ret); - return NULL; + RELEASE_LOCK(self); + PyBuffer_Release(&pdata); + Py_XDECREF(ret); + return NULL; } static PyMethodDef BZ2Decomp_methods[] = { - {"decompress", (PyCFunction)BZ2Decomp_decompress, METH_VARARGS, BZ2Decomp_decompress__doc__}, - {NULL, NULL} /* sentinel */ + {"decompress", (PyCFunction)BZ2Decomp_decompress, METH_VARARGS, BZ2Decomp_decompress__doc__}, + {NULL, NULL} /* sentinel */ }; @@ -1790,55 +1790,55 @@ static int BZ2Decomp_init(BZ2DecompObject *self, PyObject *args, PyObject *kwargs) { - int bzerror; + int bzerror; - if (!PyArg_ParseTuple(args, ":BZ2Decompressor")) - return -1; + if (!PyArg_ParseTuple(args, ":BZ2Decompressor")) + return -1; #ifdef WITH_THREAD - self->lock = PyThread_allocate_lock(); - if (!self->lock) { - PyErr_SetString(PyExc_MemoryError, "unable to allocate lock"); - goto error; - } + self->lock = PyThread_allocate_lock(); + if (!self->lock) { + PyErr_SetString(PyExc_MemoryError, "unable to allocate lock"); + goto error; + } #endif - self->unused_data = PyBytes_FromStringAndSize("", 0); - if (!self->unused_data) - goto error; - - memset(&self->bzs, 0, sizeof(bz_stream)); - bzerror = BZ2_bzDecompressInit(&self->bzs, 0, 0); - if (bzerror != BZ_OK) { - Util_CatchBZ2Error(bzerror); - goto error; - } + self->unused_data = PyBytes_FromStringAndSize("", 0); + if (!self->unused_data) + goto error; + + memset(&self->bzs, 0, sizeof(bz_stream)); + bzerror = BZ2_bzDecompressInit(&self->bzs, 0, 0); + if (bzerror != BZ_OK) { + Util_CatchBZ2Error(bzerror); + goto error; + } - self->running = 1; + self->running = 1; - return 0; + return 0; error: #ifdef WITH_THREAD - if (self->lock) { - PyThread_free_lock(self->lock); - self->lock = NULL; - } + if (self->lock) { + PyThread_free_lock(self->lock); + self->lock = NULL; + } #endif - Py_CLEAR(self->unused_data); - return -1; + Py_CLEAR(self->unused_data); + return -1; } static void BZ2Decomp_dealloc(BZ2DecompObject *self) { #ifdef WITH_THREAD - if (self->lock) - PyThread_free_lock(self->lock); + if (self->lock) + PyThread_free_lock(self->lock); #endif - Py_XDECREF(self->unused_data); - BZ2_bzDecompressEnd(&self->bzs); - Py_TYPE(self)->tp_free((PyObject *)self); + Py_XDECREF(self->unused_data); + BZ2_bzDecompressEnd(&self->bzs); + Py_TYPE(self)->tp_free((PyObject *)self); } @@ -1854,46 +1854,46 @@ "); static PyTypeObject BZ2Decomp_Type = { - PyVarObject_HEAD_INIT(NULL, 0) - "bz2.BZ2Decompressor", /*tp_name*/ - sizeof(BZ2DecompObject), /*tp_basicsize*/ - 0, /*tp_itemsize*/ - (destructor)BZ2Decomp_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*/ - PyObject_GenericSetAttr,/*tp_setattro*/ - 0, /*tp_as_buffer*/ - Py_TPFLAGS_DEFAULT|Py_TPFLAGS_BASETYPE, /*tp_flags*/ - BZ2Decomp__doc__, /*tp_doc*/ - 0, /*tp_traverse*/ - 0, /*tp_clear*/ - 0, /*tp_richcompare*/ - 0, /*tp_weaklistoffset*/ - 0, /*tp_iter*/ - 0, /*tp_iternext*/ - BZ2Decomp_methods, /*tp_methods*/ - BZ2Decomp_members, /*tp_members*/ - 0, /*tp_getset*/ - 0, /*tp_base*/ - 0, /*tp_dict*/ - 0, /*tp_descr_get*/ - 0, /*tp_descr_set*/ - 0, /*tp_dictoffset*/ - (initproc)BZ2Decomp_init, /*tp_init*/ - PyType_GenericAlloc, /*tp_alloc*/ - PyType_GenericNew, /*tp_new*/ - PyObject_Free, /*tp_free*/ - 0, /*tp_is_gc*/ + PyVarObject_HEAD_INIT(NULL, 0) + "bz2.BZ2Decompressor", /*tp_name*/ + sizeof(BZ2DecompObject), /*tp_basicsize*/ + 0, /*tp_itemsize*/ + (destructor)BZ2Decomp_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*/ + PyObject_GenericSetAttr,/*tp_setattro*/ + 0, /*tp_as_buffer*/ + Py_TPFLAGS_DEFAULT|Py_TPFLAGS_BASETYPE, /*tp_flags*/ + BZ2Decomp__doc__, /*tp_doc*/ + 0, /*tp_traverse*/ + 0, /*tp_clear*/ + 0, /*tp_richcompare*/ + 0, /*tp_weaklistoffset*/ + 0, /*tp_iter*/ + 0, /*tp_iternext*/ + BZ2Decomp_methods, /*tp_methods*/ + BZ2Decomp_members, /*tp_members*/ + 0, /*tp_getset*/ + 0, /*tp_base*/ + 0, /*tp_dict*/ + 0, /*tp_descr_get*/ + 0, /*tp_descr_set*/ + 0, /*tp_dictoffset*/ + (initproc)BZ2Decomp_init, /*tp_init*/ + PyType_GenericAlloc, /*tp_alloc*/ + PyType_GenericNew, /*tp_new*/ + PyObject_Free, /*tp_free*/ + 0, /*tp_is_gc*/ }; @@ -1911,90 +1911,90 @@ static PyObject * bz2_compress(PyObject *self, PyObject *args, PyObject *kwargs) { - int compresslevel=9; - Py_buffer pdata; - char *data; - int datasize; - int bufsize; - PyObject *ret = NULL; - bz_stream _bzs; - bz_stream *bzs = &_bzs; - int bzerror; - static char *kwlist[] = {"data", "compresslevel", 0}; - - if (!PyArg_ParseTupleAndKeywords(args, kwargs, "y*|i", - kwlist, &pdata, - &compresslevel)) - return NULL; - data = pdata.buf; - datasize = pdata.len; - - if (compresslevel < 1 || compresslevel > 9) { - PyErr_SetString(PyExc_ValueError, - "compresslevel must be between 1 and 9"); - PyBuffer_Release(&pdata); - return NULL; - } - - /* Conforming to bz2 manual, this is large enough to fit compressed - * data in one shot. We will check it later anyway. */ - bufsize = datasize + (datasize/100+1) + 600; - - ret = PyBytes_FromStringAndSize(NULL, bufsize); - if (!ret) { - PyBuffer_Release(&pdata); - return NULL; - } - - memset(bzs, 0, sizeof(bz_stream)); - - bzs->next_in = data; - bzs->avail_in = datasize; - bzs->next_out = BUF(ret); - bzs->avail_out = bufsize; - - bzerror = BZ2_bzCompressInit(bzs, compresslevel, 0, 0); - if (bzerror != BZ_OK) { - Util_CatchBZ2Error(bzerror); - PyBuffer_Release(&pdata); - Py_DECREF(ret); - return NULL; - } - - for (;;) { - Py_BEGIN_ALLOW_THREADS - bzerror = BZ2_bzCompress(bzs, BZ_FINISH); - Py_END_ALLOW_THREADS - if (bzerror == BZ_STREAM_END) { - break; - } else if (bzerror != BZ_FINISH_OK) { - BZ2_bzCompressEnd(bzs); - Util_CatchBZ2Error(bzerror); - PyBuffer_Release(&pdata); - Py_DECREF(ret); - return NULL; - } - if (bzs->avail_out == 0) { - bufsize = Util_NewBufferSize(bufsize); - if (_PyBytes_Resize(&ret, bufsize) < 0) { - BZ2_bzCompressEnd(bzs); - PyBuffer_Release(&pdata); - return NULL; - } - bzs->next_out = BUF(ret) + BZS_TOTAL_OUT(bzs); - bzs->avail_out = bufsize - (bzs->next_out - BUF(ret)); - } - } - - if (bzs->avail_out != 0) { - if (_PyBytes_Resize(&ret, (Py_ssize_t)BZS_TOTAL_OUT(bzs)) < 0) { - ret = NULL; - } - } - BZ2_bzCompressEnd(bzs); + int compresslevel=9; + Py_buffer pdata; + char *data; + int datasize; + int bufsize; + PyObject *ret = NULL; + bz_stream _bzs; + bz_stream *bzs = &_bzs; + int bzerror; + static char *kwlist[] = {"data", "compresslevel", 0}; + + if (!PyArg_ParseTupleAndKeywords(args, kwargs, "y*|i", + kwlist, &pdata, + &compresslevel)) + return NULL; + data = pdata.buf; + datasize = pdata.len; + + if (compresslevel < 1 || compresslevel > 9) { + PyErr_SetString(PyExc_ValueError, + "compresslevel must be between 1 and 9"); + PyBuffer_Release(&pdata); + return NULL; + } + + /* Conforming to bz2 manual, this is large enough to fit compressed + * data in one shot. We will check it later anyway. */ + bufsize = datasize + (datasize/100+1) + 600; + + ret = PyBytes_FromStringAndSize(NULL, bufsize); + if (!ret) { + PyBuffer_Release(&pdata); + return NULL; + } + + memset(bzs, 0, sizeof(bz_stream)); + + bzs->next_in = data; + bzs->avail_in = datasize; + bzs->next_out = BUF(ret); + bzs->avail_out = bufsize; + + bzerror = BZ2_bzCompressInit(bzs, compresslevel, 0, 0); + if (bzerror != BZ_OK) { + Util_CatchBZ2Error(bzerror); + PyBuffer_Release(&pdata); + Py_DECREF(ret); + return NULL; + } + + for (;;) { + Py_BEGIN_ALLOW_THREADS + bzerror = BZ2_bzCompress(bzs, BZ_FINISH); + Py_END_ALLOW_THREADS + if (bzerror == BZ_STREAM_END) { + break; + } else if (bzerror != BZ_FINISH_OK) { + BZ2_bzCompressEnd(bzs); + Util_CatchBZ2Error(bzerror); + PyBuffer_Release(&pdata); + Py_DECREF(ret); + return NULL; + } + if (bzs->avail_out == 0) { + bufsize = Util_NewBufferSize(bufsize); + if (_PyBytes_Resize(&ret, bufsize) < 0) { + BZ2_bzCompressEnd(bzs); + PyBuffer_Release(&pdata); + return NULL; + } + bzs->next_out = BUF(ret) + BZS_TOTAL_OUT(bzs); + bzs->avail_out = bufsize - (bzs->next_out - BUF(ret)); + } + } + + if (bzs->avail_out != 0) { + if (_PyBytes_Resize(&ret, (Py_ssize_t)BZS_TOTAL_OUT(bzs)) < 0) { + ret = NULL; + } + } + BZ2_bzCompressEnd(bzs); - PyBuffer_Release(&pdata); - return ret; + PyBuffer_Release(&pdata); + return ret; } PyDoc_STRVAR(bz2_decompress__doc__, @@ -2007,96 +2007,96 @@ static PyObject * bz2_decompress(PyObject *self, PyObject *args) { - Py_buffer pdata; - char *data; - int datasize; - int bufsize = SMALLCHUNK; - PyObject *ret; - bz_stream _bzs; - bz_stream *bzs = &_bzs; - int bzerror; - - if (!PyArg_ParseTuple(args, "y*:decompress", &pdata)) - return NULL; - data = pdata.buf; - datasize = pdata.len; - - if (datasize == 0) { - PyBuffer_Release(&pdata); - return PyBytes_FromStringAndSize("", 0); - } - - ret = PyBytes_FromStringAndSize(NULL, bufsize); - if (!ret) { - PyBuffer_Release(&pdata); - return NULL; - } - - memset(bzs, 0, sizeof(bz_stream)); - - bzs->next_in = data; - bzs->avail_in = datasize; - bzs->next_out = BUF(ret); - bzs->avail_out = bufsize; - - bzerror = BZ2_bzDecompressInit(bzs, 0, 0); - if (bzerror != BZ_OK) { - Util_CatchBZ2Error(bzerror); - Py_DECREF(ret); - PyBuffer_Release(&pdata); - return NULL; - } - - for (;;) { - Py_BEGIN_ALLOW_THREADS - bzerror = BZ2_bzDecompress(bzs); - Py_END_ALLOW_THREADS - if (bzerror == BZ_STREAM_END) { - break; - } else if (bzerror != BZ_OK) { - BZ2_bzDecompressEnd(bzs); - Util_CatchBZ2Error(bzerror); - PyBuffer_Release(&pdata); - Py_DECREF(ret); - return NULL; - } - if (bzs->avail_in == 0) { - BZ2_bzDecompressEnd(bzs); - PyErr_SetString(PyExc_ValueError, - "couldn't find end of stream"); - PyBuffer_Release(&pdata); - Py_DECREF(ret); - return NULL; - } - if (bzs->avail_out == 0) { - bufsize = Util_NewBufferSize(bufsize); - if (_PyBytes_Resize(&ret, bufsize) < 0) { - BZ2_bzDecompressEnd(bzs); - PyBuffer_Release(&pdata); - return NULL; - } - bzs->next_out = BUF(ret) + BZS_TOTAL_OUT(bzs); - bzs->avail_out = bufsize - (bzs->next_out - BUF(ret)); - } - } - - if (bzs->avail_out != 0) { - if (_PyBytes_Resize(&ret, (Py_ssize_t)BZS_TOTAL_OUT(bzs)) < 0) { - ret = NULL; - } - } - BZ2_bzDecompressEnd(bzs); - PyBuffer_Release(&pdata); + Py_buffer pdata; + char *data; + int datasize; + int bufsize = SMALLCHUNK; + PyObject *ret; + bz_stream _bzs; + bz_stream *bzs = &_bzs; + int bzerror; + + if (!PyArg_ParseTuple(args, "y*:decompress", &pdata)) + return NULL; + data = pdata.buf; + datasize = pdata.len; + + if (datasize == 0) { + PyBuffer_Release(&pdata); + return PyBytes_FromStringAndSize("", 0); + } + + ret = PyBytes_FromStringAndSize(NULL, bufsize); + if (!ret) { + PyBuffer_Release(&pdata); + return NULL; + } + + memset(bzs, 0, sizeof(bz_stream)); + + bzs->next_in = data; + bzs->avail_in = datasize; + bzs->next_out = BUF(ret); + bzs->avail_out = bufsize; + + bzerror = BZ2_bzDecompressInit(bzs, 0, 0); + if (bzerror != BZ_OK) { + Util_CatchBZ2Error(bzerror); + Py_DECREF(ret); + PyBuffer_Release(&pdata); + return NULL; + } + + for (;;) { + Py_BEGIN_ALLOW_THREADS + bzerror = BZ2_bzDecompress(bzs); + Py_END_ALLOW_THREADS + if (bzerror == BZ_STREAM_END) { + break; + } else if (bzerror != BZ_OK) { + BZ2_bzDecompressEnd(bzs); + Util_CatchBZ2Error(bzerror); + PyBuffer_Release(&pdata); + Py_DECREF(ret); + return NULL; + } + if (bzs->avail_in == 0) { + BZ2_bzDecompressEnd(bzs); + PyErr_SetString(PyExc_ValueError, + "couldn't find end of stream"); + PyBuffer_Release(&pdata); + Py_DECREF(ret); + return NULL; + } + if (bzs->avail_out == 0) { + bufsize = Util_NewBufferSize(bufsize); + if (_PyBytes_Resize(&ret, bufsize) < 0) { + BZ2_bzDecompressEnd(bzs); + PyBuffer_Release(&pdata); + return NULL; + } + bzs->next_out = BUF(ret) + BZS_TOTAL_OUT(bzs); + bzs->avail_out = bufsize - (bzs->next_out - BUF(ret)); + } + } + + if (bzs->avail_out != 0) { + if (_PyBytes_Resize(&ret, (Py_ssize_t)BZS_TOTAL_OUT(bzs)) < 0) { + ret = NULL; + } + } + BZ2_bzDecompressEnd(bzs); + PyBuffer_Release(&pdata); - return ret; + return ret; } static PyMethodDef bz2_methods[] = { - {"compress", (PyCFunction) bz2_compress, METH_VARARGS|METH_KEYWORDS, - bz2_compress__doc__}, - {"decompress", (PyCFunction) bz2_decompress, METH_VARARGS, - bz2_decompress__doc__}, - {NULL, NULL} /* sentinel */ + {"compress", (PyCFunction) bz2_compress, METH_VARARGS|METH_KEYWORDS, + bz2_compress__doc__}, + {"decompress", (PyCFunction) bz2_decompress, METH_VARARGS, + bz2_decompress__doc__}, + {NULL, NULL} /* sentinel */ }; /* ===================================================================== */ @@ -2111,39 +2111,39 @@ static struct PyModuleDef bz2module = { - PyModuleDef_HEAD_INIT, - "bz2", - bz2__doc__, - -1, - bz2_methods, - NULL, - NULL, - NULL, - NULL + PyModuleDef_HEAD_INIT, + "bz2", + bz2__doc__, + -1, + bz2_methods, + NULL, + NULL, + NULL, + NULL }; PyMODINIT_FUNC PyInit_bz2(void) { - PyObject *m; + PyObject *m; - Py_TYPE(&BZ2File_Type) = &PyType_Type; - Py_TYPE(&BZ2Comp_Type) = &PyType_Type; - Py_TYPE(&BZ2Decomp_Type) = &PyType_Type; + Py_TYPE(&BZ2File_Type) = &PyType_Type; + Py_TYPE(&BZ2Comp_Type) = &PyType_Type; + Py_TYPE(&BZ2Decomp_Type) = &PyType_Type; - m = PyModule_Create(&bz2module); - if (m == NULL) - return NULL; + m = PyModule_Create(&bz2module); + if (m == NULL) + return NULL; - PyModule_AddObject(m, "__author__", PyUnicode_FromString(__author__)); + PyModule_AddObject(m, "__author__", PyUnicode_FromString(__author__)); - Py_INCREF(&BZ2File_Type); - PyModule_AddObject(m, "BZ2File", (PyObject *)&BZ2File_Type); + Py_INCREF(&BZ2File_Type); + PyModule_AddObject(m, "BZ2File", (PyObject *)&BZ2File_Type); - Py_INCREF(&BZ2Comp_Type); - PyModule_AddObject(m, "BZ2Compressor", (PyObject *)&BZ2Comp_Type); + Py_INCREF(&BZ2Comp_Type); + PyModule_AddObject(m, "BZ2Compressor", (PyObject *)&BZ2Comp_Type); - Py_INCREF(&BZ2Decomp_Type); - PyModule_AddObject(m, "BZ2Decompressor", (PyObject *)&BZ2Decomp_Type); - return m; + Py_INCREF(&BZ2Decomp_Type); + PyModule_AddObject(m, "BZ2Decompressor", (PyObject *)&BZ2Decomp_Type); + return m; } Modified: python/branches/py3k-jit/Modules/cjkcodecs/_codecs_cn.c ============================================================================== --- python/branches/py3k-jit/Modules/cjkcodecs/_codecs_cn.c (original) +++ python/branches/py3k-jit/Modules/cjkcodecs/_codecs_cn.c Mon May 10 23:55:43 2010 @@ -17,24 +17,24 @@ /* GBK and GB2312 map differently in few codepoints that are listed below: * - * gb2312 gbk - * A1A4 U+30FB KATAKANA MIDDLE DOT U+00B7 MIDDLE DOT - * A1AA U+2015 HORIZONTAL BAR U+2014 EM DASH - * A844 undefined U+2015 HORIZONTAL BAR + * gb2312 gbk + * A1A4 U+30FB KATAKANA MIDDLE DOT U+00B7 MIDDLE DOT + * A1AA U+2015 HORIZONTAL BAR U+2014 EM DASH + * A844 undefined U+2015 HORIZONTAL BAR */ #define GBK_DECODE(dc1, dc2, assi) \ - if ((dc1) == 0xa1 && (dc2) == 0xaa) (assi) = 0x2014; \ - else if ((dc1) == 0xa8 && (dc2) == 0x44) (assi) = 0x2015; \ - else if ((dc1) == 0xa1 && (dc2) == 0xa4) (assi) = 0x00b7; \ - else TRYMAP_DEC(gb2312, assi, dc1 ^ 0x80, dc2 ^ 0x80); \ - else TRYMAP_DEC(gbkext, assi, dc1, dc2); + if ((dc1) == 0xa1 && (dc2) == 0xaa) (assi) = 0x2014; \ + else if ((dc1) == 0xa8 && (dc2) == 0x44) (assi) = 0x2015; \ + else if ((dc1) == 0xa1 && (dc2) == 0xa4) (assi) = 0x00b7; \ + else TRYMAP_DEC(gb2312, assi, dc1 ^ 0x80, dc2 ^ 0x80); \ + else TRYMAP_DEC(gbkext, assi, dc1, dc2); #define GBK_ENCODE(code, assi) \ - if ((code) == 0x2014) (assi) = 0xa1aa; \ - else if ((code) == 0x2015) (assi) = 0xa844; \ - else if ((code) == 0x00b7) (assi) = 0xa1a4; \ - else if ((code) != 0x30fb && TRYMAP_ENC_COND(gbcommon, assi, code)); + if ((code) == 0x2014) (assi) = 0xa1aa; \ + else if ((code) == 0x2015) (assi) = 0xa844; \ + else if ((code) == 0x00b7) (assi) = 0xa1a4; \ + else if ((code) != 0x30fb && TRYMAP_ENC_COND(gbcommon, assi, code)); /* * GB2312 codec @@ -42,53 +42,53 @@ ENCODER(gb2312) { - while (inleft > 0) { - Py_UNICODE c = IN1; - DBCHAR code; - - if (c < 0x80) { - WRITE1((unsigned char)c) - NEXT(1, 1) - continue; - } - UCS4INVALID(c) - - REQUIRE_OUTBUF(2) - TRYMAP_ENC(gbcommon, code, c); - else return 1; - - if (code & 0x8000) /* MSB set: GBK */ - return 1; - - OUT1((code >> 8) | 0x80) - OUT2((code & 0xFF) | 0x80) - NEXT(1, 2) - } + while (inleft > 0) { + Py_UNICODE c = IN1; + DBCHAR code; + + if (c < 0x80) { + WRITE1((unsigned char)c) + NEXT(1, 1) + continue; + } + UCS4INVALID(c) + + REQUIRE_OUTBUF(2) + TRYMAP_ENC(gbcommon, code, c); + else return 1; + + if (code & 0x8000) /* MSB set: GBK */ + return 1; + + OUT1((code >> 8) | 0x80) + OUT2((code & 0xFF) | 0x80) + NEXT(1, 2) + } - return 0; + return 0; } DECODER(gb2312) { - while (inleft > 0) { - unsigned char c = **inbuf; + while (inleft > 0) { + unsigned char c = **inbuf; - REQUIRE_OUTBUF(1) + REQUIRE_OUTBUF(1) - if (c < 0x80) { - OUT1(c) - NEXT(1, 1) - continue; - } - - REQUIRE_INBUF(2) - TRYMAP_DEC(gb2312, **outbuf, c ^ 0x80, IN2 ^ 0x80) { - NEXT(2, 1) - } - else return 2; - } + if (c < 0x80) { + OUT1(c) + NEXT(1, 1) + continue; + } + + REQUIRE_INBUF(2) + TRYMAP_DEC(gb2312, **outbuf, c ^ 0x80, IN2 ^ 0x80) { + NEXT(2, 1) + } + else return 2; + } - return 0; + return 0; } @@ -98,55 +98,55 @@ ENCODER(gbk) { - while (inleft > 0) { - Py_UNICODE c = IN1; - DBCHAR code; - - if (c < 0x80) { - WRITE1((unsigned char)c) - NEXT(1, 1) - continue; - } - UCS4INVALID(c) - - REQUIRE_OUTBUF(2) - - GBK_ENCODE(c, code) - else return 1; - - OUT1((code >> 8) | 0x80) - if (code & 0x8000) - OUT2((code & 0xFF)) /* MSB set: GBK */ - else - OUT2((code & 0xFF) | 0x80) /* MSB unset: GB2312 */ - NEXT(1, 2) - } + while (inleft > 0) { + Py_UNICODE c = IN1; + DBCHAR code; + + if (c < 0x80) { + WRITE1((unsigned char)c) + NEXT(1, 1) + continue; + } + UCS4INVALID(c) + + REQUIRE_OUTBUF(2) + + GBK_ENCODE(c, code) + else return 1; + + OUT1((code >> 8) | 0x80) + if (code & 0x8000) + OUT2((code & 0xFF)) /* MSB set: GBK */ + else + OUT2((code & 0xFF) | 0x80) /* MSB unset: GB2312 */ + NEXT(1, 2) + } - return 0; + return 0; } DECODER(gbk) { - while (inleft > 0) { - unsigned char c = IN1; + while (inleft > 0) { + unsigned char c = IN1; - REQUIRE_OUTBUF(1) + REQUIRE_OUTBUF(1) - if (c < 0x80) { - OUT1(c) - NEXT(1, 1) - continue; - } + if (c < 0x80) { + OUT1(c) + NEXT(1, 1) + continue; + } - REQUIRE_INBUF(2) + REQUIRE_INBUF(2) - GBK_DECODE(c, IN2, **outbuf) - else return 2; + GBK_DECODE(c, IN2, **outbuf) + else return 2; - NEXT(2, 1) - } + NEXT(2, 1) + } - return 0; + return 0; } @@ -156,153 +156,153 @@ ENCODER(gb18030) { - while (inleft > 0) { - ucs4_t c = IN1; - DBCHAR code; - - if (c < 0x80) { - WRITE1(c) - NEXT(1, 1) - continue; - } + while (inleft > 0) { + ucs4_t c = IN1; + DBCHAR code; + + if (c < 0x80) { + WRITE1(c) + NEXT(1, 1) + continue; + } - DECODE_SURROGATE(c) - if (c > 0x10FFFF) + DECODE_SURROGATE(c) + if (c > 0x10FFFF) #if Py_UNICODE_SIZE == 2 - return 2; /* surrogates pair */ + return 2; /* surrogates pair */ #else - return 1; + return 1; #endif - else if (c >= 0x10000) { - ucs4_t tc = c - 0x10000; + else if (c >= 0x10000) { + ucs4_t tc = c - 0x10000; - REQUIRE_OUTBUF(4) + REQUIRE_OUTBUF(4) - OUT4((unsigned char)(tc % 10) + 0x30) - tc /= 10; - OUT3((unsigned char)(tc % 126) + 0x81) - tc /= 126; - OUT2((unsigned char)(tc % 10) + 0x30) - tc /= 10; - OUT1((unsigned char)(tc + 0x90)) + OUT4((unsigned char)(tc % 10) + 0x30) + tc /= 10; + OUT3((unsigned char)(tc % 126) + 0x81) + tc /= 126; + OUT2((unsigned char)(tc % 10) + 0x30) + tc /= 10; + OUT1((unsigned char)(tc + 0x90)) #if Py_UNICODE_SIZE == 2 - NEXT(2, 4) /* surrogates pair */ + NEXT(2, 4) /* surrogates pair */ #else - NEXT(1, 4) + NEXT(1, 4) #endif - continue; - } + continue; + } - REQUIRE_OUTBUF(2) + REQUIRE_OUTBUF(2) - GBK_ENCODE(c, code) - else TRYMAP_ENC(gb18030ext, code, c); - else { - const struct _gb18030_to_unibmp_ranges *utrrange; - - REQUIRE_OUTBUF(4) - - for (utrrange = gb18030_to_unibmp_ranges; - utrrange->first != 0; - utrrange++) - if (utrrange->first <= c && - c <= utrrange->last) { - Py_UNICODE tc; - - tc = c - utrrange->first + - utrrange->base; - - OUT4((unsigned char)(tc % 10) + 0x30) - tc /= 10; - OUT3((unsigned char)(tc % 126) + 0x81) - tc /= 126; - OUT2((unsigned char)(tc % 10) + 0x30) - tc /= 10; - OUT1((unsigned char)tc + 0x81) - - NEXT(1, 4) - break; - } - - if (utrrange->first == 0) - return 1; - continue; - } - - OUT1((code >> 8) | 0x80) - if (code & 0x8000) - OUT2((code & 0xFF)) /* MSB set: GBK or GB18030ext */ - else - OUT2((code & 0xFF) | 0x80) /* MSB unset: GB2312 */ + GBK_ENCODE(c, code) + else TRYMAP_ENC(gb18030ext, code, c); + else { + const struct _gb18030_to_unibmp_ranges *utrrange; + + REQUIRE_OUTBUF(4) + + for (utrrange = gb18030_to_unibmp_ranges; + utrrange->first != 0; + utrrange++) + if (utrrange->first <= c && + c <= utrrange->last) { + Py_UNICODE tc; + + tc = c - utrrange->first + + utrrange->base; + + OUT4((unsigned char)(tc % 10) + 0x30) + tc /= 10; + OUT3((unsigned char)(tc % 126) + 0x81) + tc /= 126; + OUT2((unsigned char)(tc % 10) + 0x30) + tc /= 10; + OUT1((unsigned char)tc + 0x81) + + NEXT(1, 4) + break; + } + + if (utrrange->first == 0) + return 1; + continue; + } + + OUT1((code >> 8) | 0x80) + if (code & 0x8000) + OUT2((code & 0xFF)) /* MSB set: GBK or GB18030ext */ + else + OUT2((code & 0xFF) | 0x80) /* MSB unset: GB2312 */ - NEXT(1, 2) - } + NEXT(1, 2) + } - return 0; + return 0; } DECODER(gb18030) { - while (inleft > 0) { - unsigned char c = IN1, c2; + while (inleft > 0) { + unsigned char c = IN1, c2; - REQUIRE_OUTBUF(1) + REQUIRE_OUTBUF(1) - if (c < 0x80) { - OUT1(c) - NEXT(1, 1) - continue; - } - - REQUIRE_INBUF(2) - - c2 = IN2; - if (c2 >= 0x30 && c2 <= 0x39) { /* 4 bytes seq */ - const struct _gb18030_to_unibmp_ranges *utr; - unsigned char c3, c4; - ucs4_t lseq; - - REQUIRE_INBUF(4) - c3 = IN3; - c4 = IN4; - if (c < 0x81 || c3 < 0x81 || c4 < 0x30 || c4 > 0x39) - return 4; - c -= 0x81; c2 -= 0x30; - c3 -= 0x81; c4 -= 0x30; - - if (c < 4) { /* U+0080 - U+FFFF */ - lseq = ((ucs4_t)c * 10 + c2) * 1260 + - (ucs4_t)c3 * 10 + c4; - if (lseq < 39420) { - for (utr = gb18030_to_unibmp_ranges; - lseq >= (utr + 1)->base; - utr++) ; - OUT1(utr->first - utr->base + lseq) - NEXT(4, 1) - continue; - } - } - else if (c >= 15) { /* U+10000 - U+10FFFF */ - lseq = 0x10000 + (((ucs4_t)c-15) * 10 + c2) - * 1260 + (ucs4_t)c3 * 10 + c4; - if (lseq <= 0x10FFFF) { - WRITEUCS4(lseq); - NEXT_IN(4) - continue; - } - } - return 4; - } - - GBK_DECODE(c, c2, **outbuf) - else TRYMAP_DEC(gb18030ext, **outbuf, c, c2); - else return 2; + if (c < 0x80) { + OUT1(c) + NEXT(1, 1) + continue; + } + + REQUIRE_INBUF(2) + + c2 = IN2; + if (c2 >= 0x30 && c2 <= 0x39) { /* 4 bytes seq */ + const struct _gb18030_to_unibmp_ranges *utr; + unsigned char c3, c4; + ucs4_t lseq; + + REQUIRE_INBUF(4) + c3 = IN3; + c4 = IN4; + if (c < 0x81 || c3 < 0x81 || c4 < 0x30 || c4 > 0x39) + return 4; + c -= 0x81; c2 -= 0x30; + c3 -= 0x81; c4 -= 0x30; + + if (c < 4) { /* U+0080 - U+FFFF */ + lseq = ((ucs4_t)c * 10 + c2) * 1260 + + (ucs4_t)c3 * 10 + c4; + if (lseq < 39420) { + for (utr = gb18030_to_unibmp_ranges; + lseq >= (utr + 1)->base; + utr++) ; + OUT1(utr->first - utr->base + lseq) + NEXT(4, 1) + continue; + } + } + else if (c >= 15) { /* U+10000 - U+10FFFF */ + lseq = 0x10000 + (((ucs4_t)c-15) * 10 + c2) + * 1260 + (ucs4_t)c3 * 10 + c4; + if (lseq <= 0x10FFFF) { + WRITEUCS4(lseq); + NEXT_IN(4) + continue; + } + } + return 4; + } + + GBK_DECODE(c, c2, **outbuf) + else TRYMAP_DEC(gb18030ext, **outbuf, c, c2); + else return 2; - NEXT(2, 1) - } + NEXT(2, 1) + } - return 0; + return 0; } @@ -312,118 +312,118 @@ ENCODER_INIT(hz) { - state->i = 0; - return 0; + state->i = 0; + return 0; } ENCODER_RESET(hz) { - if (state->i != 0) { - WRITE2('~', '}') - state->i = 0; - NEXT_OUT(2) - } - return 0; + if (state->i != 0) { + WRITE2('~', '}') + state->i = 0; + NEXT_OUT(2) + } + return 0; } ENCODER(hz) { - while (inleft > 0) { - Py_UNICODE c = IN1; - DBCHAR code; - - if (c < 0x80) { - if (state->i == 0) { - WRITE1((unsigned char)c) - NEXT(1, 1) - } - else { - WRITE3('~', '}', (unsigned char)c) - NEXT(1, 3) - state->i = 0; - } - continue; - } - - UCS4INVALID(c) - - TRYMAP_ENC(gbcommon, code, c); - else return 1; - - if (code & 0x8000) /* MSB set: GBK */ - return 1; - - if (state->i == 0) { - WRITE4('~', '{', code >> 8, code & 0xff) - NEXT(1, 4) - state->i = 1; - } - else { - WRITE2(code >> 8, code & 0xff) - NEXT(1, 2) - } - } + while (inleft > 0) { + Py_UNICODE c = IN1; + DBCHAR code; + + if (c < 0x80) { + if (state->i == 0) { + WRITE1((unsigned char)c) + NEXT(1, 1) + } + else { + WRITE3('~', '}', (unsigned char)c) + NEXT(1, 3) + state->i = 0; + } + continue; + } + + UCS4INVALID(c) + + TRYMAP_ENC(gbcommon, code, c); + else return 1; + + if (code & 0x8000) /* MSB set: GBK */ + return 1; + + if (state->i == 0) { + WRITE4('~', '{', code >> 8, code & 0xff) + NEXT(1, 4) + state->i = 1; + } + else { + WRITE2(code >> 8, code & 0xff) + NEXT(1, 2) + } + } - return 0; + return 0; } DECODER_INIT(hz) { - state->i = 0; - return 0; + state->i = 0; + return 0; } DECODER_RESET(hz) { - state->i = 0; - return 0; + state->i = 0; + return 0; } DECODER(hz) { - while (inleft > 0) { - unsigned char c = IN1; + while (inleft > 0) { + unsigned char c = IN1; - if (c == '~') { - unsigned char c2 = IN2; + if (c == '~') { + unsigned char c2 = IN2; - REQUIRE_INBUF(2) - if (c2 == '~') { - WRITE1('~') - NEXT(2, 1) - continue; - } - else if (c2 == '{' && state->i == 0) - state->i = 1; /* set GB */ - else if (c2 == '}' && state->i == 1) - state->i = 0; /* set ASCII */ - else if (c2 == '\n') - ; /* line-continuation */ - else - return 2; - NEXT(2, 0); - continue; - } - - if (c & 0x80) - return 1; - - if (state->i == 0) { /* ASCII mode */ - WRITE1(c) - NEXT(1, 1) - } - else { /* GB mode */ - REQUIRE_INBUF(2) - REQUIRE_OUTBUF(1) - TRYMAP_DEC(gb2312, **outbuf, c, IN2) { - NEXT(2, 1) - } - else - return 2; - } - } + REQUIRE_INBUF(2) + if (c2 == '~') { + WRITE1('~') + NEXT(2, 1) + continue; + } + else if (c2 == '{' && state->i == 0) + state->i = 1; /* set GB */ + else if (c2 == '}' && state->i == 1) + state->i = 0; /* set ASCII */ + else if (c2 == '\n') + ; /* line-continuation */ + else + return 2; + NEXT(2, 0); + continue; + } + + if (c & 0x80) + return 1; + + if (state->i == 0) { /* ASCII mode */ + WRITE1(c) + NEXT(1, 1) + } + else { /* GB mode */ + REQUIRE_INBUF(2) + REQUIRE_OUTBUF(1) + TRYMAP_DEC(gb2312, **outbuf, c, IN2) { + NEXT(2, 1) + } + else + return 2; + } + } - return 0; + return 0; } Modified: python/branches/py3k-jit/Modules/cjkcodecs/_codecs_hk.c ============================================================================== --- python/branches/py3k-jit/Modules/cjkcodecs/_codecs_hk.c (original) +++ python/branches/py3k-jit/Modules/cjkcodecs/_codecs_hk.c Mon May 10 23:55:43 2010 @@ -18,12 +18,12 @@ CODEC_INIT(big5hkscs) { - static int initialized = 0; + static int initialized = 0; - if (!initialized && IMPORT_MAP(tw, big5, &big5_encmap, &big5_decmap)) - return -1; - initialized = 1; - return 0; + if (!initialized && IMPORT_MAP(tw, big5, &big5_encmap, &big5_decmap)) + return -1; + initialized = 1; + return 0; } /* @@ -38,135 +38,135 @@ ENCODER(big5hkscs) { - while (inleft > 0) { - ucs4_t c = **inbuf; - DBCHAR code; - Py_ssize_t insize; - - if (c < 0x80) { - REQUIRE_OUTBUF(1) - **outbuf = (unsigned char)c; - NEXT(1, 1) - continue; - } - - DECODE_SURROGATE(c) - insize = GET_INSIZE(c); - - REQUIRE_OUTBUF(2) - - if (c < 0x10000) { - TRYMAP_ENC(big5hkscs_bmp, code, c) { - if (code == MULTIC) { - if (inleft >= 2 && - ((c & 0xffdf) == 0x00ca) && - (((*inbuf)[1] & 0xfff7) == 0x0304)) { - code = big5hkscs_pairenc_table[ - ((c >> 4) | - ((*inbuf)[1] >> 3)) & 3]; - insize = 2; - } - else if (inleft < 2 && - !(flags & MBENC_FLUSH)) - return MBERR_TOOFEW; - else { - if (c == 0xca) - code = 0x8866; - else /* c == 0xea */ - code = 0x88a7; - } - } - } - else TRYMAP_ENC(big5, code, c); - else return 1; - } - else if (c < 0x20000) - return insize; - else if (c < 0x30000) { - TRYMAP_ENC(big5hkscs_nonbmp, code, c & 0xffff); - else return insize; - } - else - return insize; - - OUT1(code >> 8) - OUT2(code & 0xFF) - NEXT(insize, 2) - } + while (inleft > 0) { + ucs4_t c = **inbuf; + DBCHAR code; + Py_ssize_t insize; + + if (c < 0x80) { + REQUIRE_OUTBUF(1) + **outbuf = (unsigned char)c; + NEXT(1, 1) + continue; + } + + DECODE_SURROGATE(c) + insize = GET_INSIZE(c); + + REQUIRE_OUTBUF(2) + + if (c < 0x10000) { + TRYMAP_ENC(big5hkscs_bmp, code, c) { + if (code == MULTIC) { + if (inleft >= 2 && + ((c & 0xffdf) == 0x00ca) && + (((*inbuf)[1] & 0xfff7) == 0x0304)) { + code = big5hkscs_pairenc_table[ + ((c >> 4) | + ((*inbuf)[1] >> 3)) & 3]; + insize = 2; + } + else if (inleft < 2 && + !(flags & MBENC_FLUSH)) + return MBERR_TOOFEW; + else { + if (c == 0xca) + code = 0x8866; + else /* c == 0xea */ + code = 0x88a7; + } + } + } + else TRYMAP_ENC(big5, code, c); + else return 1; + } + else if (c < 0x20000) + return insize; + else if (c < 0x30000) { + TRYMAP_ENC(big5hkscs_nonbmp, code, c & 0xffff); + else return insize; + } + else + return insize; + + OUT1(code >> 8) + OUT2(code & 0xFF) + NEXT(insize, 2) + } - return 0; + return 0; } #define BH2S(c1, c2) (((c1) - 0x87) * (0xfe - 0x40 + 1) + ((c2) - 0x40)) DECODER(big5hkscs) { - while (inleft > 0) { - unsigned char c = IN1; - ucs4_t decoded; - - REQUIRE_OUTBUF(1) - - if (c < 0x80) { - OUT1(c) - NEXT(1, 1) - continue; - } - - REQUIRE_INBUF(2) - - if (0xc6 <= c && c <= 0xc8 && (c >= 0xc7 || IN2 >= 0xa1)) - goto hkscsdec; - - TRYMAP_DEC(big5, **outbuf, c, IN2) { - NEXT(2, 1) - } - else -hkscsdec: TRYMAP_DEC(big5hkscs, decoded, c, IN2) { - int s = BH2S(c, IN2); - const unsigned char *hintbase; - - assert(0x87 <= c && c <= 0xfe); - assert(0x40 <= IN2 && IN2 <= 0xfe); - - if (BH2S(0x87, 0x40) <= s && s <= BH2S(0xa0, 0xfe)) { - hintbase = big5hkscs_phint_0; - s -= BH2S(0x87, 0x40); - } - else if (BH2S(0xc6,0xa1) <= s && s <= BH2S(0xc8,0xfe)){ - hintbase = big5hkscs_phint_12130; - s -= BH2S(0xc6, 0xa1); - } - else if (BH2S(0xf9,0xd6) <= s && s <= BH2S(0xfe,0xfe)){ - hintbase = big5hkscs_phint_21924; - s -= BH2S(0xf9, 0xd6); - } - else - return MBERR_INTERNAL; - - if (hintbase[s >> 3] & (1 << (s & 7))) { - WRITEUCS4(decoded | 0x20000) - NEXT_IN(2) - } - else { - OUT1(decoded) - NEXT(2, 1) - } - } - else { - switch ((c << 8) | IN2) { - case 0x8862: WRITE2(0x00ca, 0x0304); break; - case 0x8864: WRITE2(0x00ca, 0x030c); break; - case 0x88a3: WRITE2(0x00ea, 0x0304); break; - case 0x88a5: WRITE2(0x00ea, 0x030c); break; - default: return 2; - } - - NEXT(2, 2) /* all decoded codepoints are pairs, above. */ - } - } + while (inleft > 0) { + unsigned char c = IN1; + ucs4_t decoded; + + REQUIRE_OUTBUF(1) + + if (c < 0x80) { + OUT1(c) + NEXT(1, 1) + continue; + } + + REQUIRE_INBUF(2) + + if (0xc6 <= c && c <= 0xc8 && (c >= 0xc7 || IN2 >= 0xa1)) + goto hkscsdec; + + TRYMAP_DEC(big5, **outbuf, c, IN2) { + NEXT(2, 1) + } + else +hkscsdec: TRYMAP_DEC(big5hkscs, decoded, c, IN2) { + int s = BH2S(c, IN2); + const unsigned char *hintbase; + + assert(0x87 <= c && c <= 0xfe); + assert(0x40 <= IN2 && IN2 <= 0xfe); + + if (BH2S(0x87, 0x40) <= s && s <= BH2S(0xa0, 0xfe)) { + hintbase = big5hkscs_phint_0; + s -= BH2S(0x87, 0x40); + } + else if (BH2S(0xc6,0xa1) <= s && s <= BH2S(0xc8,0xfe)){ + hintbase = big5hkscs_phint_12130; + s -= BH2S(0xc6, 0xa1); + } + else if (BH2S(0xf9,0xd6) <= s && s <= BH2S(0xfe,0xfe)){ + hintbase = big5hkscs_phint_21924; + s -= BH2S(0xf9, 0xd6); + } + else + return MBERR_INTERNAL; + + if (hintbase[s >> 3] & (1 << (s & 7))) { + WRITEUCS4(decoded | 0x20000) + NEXT_IN(2) + } + else { + OUT1(decoded) + NEXT(2, 1) + } + } + else { + switch ((c << 8) | IN2) { + case 0x8862: WRITE2(0x00ca, 0x0304); break; + case 0x8864: WRITE2(0x00ca, 0x030c); break; + case 0x88a3: WRITE2(0x00ea, 0x0304); break; + case 0x88a5: WRITE2(0x00ea, 0x030c); break; + default: return 2; + } + + NEXT(2, 2) /* all decoded codepoints are pairs, above. */ + } + } - return 0; + return 0; } Modified: python/branches/py3k-jit/Modules/cjkcodecs/_codecs_iso2022.c ============================================================================== --- python/branches/py3k-jit/Modules/cjkcodecs/_codecs_iso2022.c (original) +++ python/branches/py3k-jit/Modules/cjkcodecs/_codecs_iso2022.c Mon May 10 23:55:43 2010 @@ -19,85 +19,85 @@ state->c[0-3] - 00000000 - ||^^^^^| - |+-----+---- G0-3 Character Set - +----------- Is G0-3 double byte? + 00000000 + ||^^^^^| + |+-----+---- G0-3 Character Set + +----------- Is G0-3 double byte? state->c[4] - 00000000 - || - |+---- Locked-Shift? - +----- ESC Throughout + 00000000 + || + |+---- Locked-Shift? + +----- ESC Throughout */ -#define ESC 0x1B -#define SO 0x0E -#define SI 0x0F -#define LF 0x0A - -#define MAX_ESCSEQLEN 16 - -#define CHARSET_ISO8859_1 'A' -#define CHARSET_ASCII 'B' -#define CHARSET_ISO8859_7 'F' -#define CHARSET_JISX0201_K 'I' -#define CHARSET_JISX0201_R 'J' - -#define CHARSET_GB2312 ('A'|CHARSET_DBCS) -#define CHARSET_JISX0208 ('B'|CHARSET_DBCS) -#define CHARSET_KSX1001 ('C'|CHARSET_DBCS) -#define CHARSET_JISX0212 ('D'|CHARSET_DBCS) -#define CHARSET_GB2312_8565 ('E'|CHARSET_DBCS) -#define CHARSET_CNS11643_1 ('G'|CHARSET_DBCS) -#define CHARSET_CNS11643_2 ('H'|CHARSET_DBCS) -#define CHARSET_JISX0213_2000_1 ('O'|CHARSET_DBCS) -#define CHARSET_JISX0213_2 ('P'|CHARSET_DBCS) -#define CHARSET_JISX0213_2004_1 ('Q'|CHARSET_DBCS) -#define CHARSET_JISX0208_O ('@'|CHARSET_DBCS) +#define ESC 0x1B +#define SO 0x0E +#define SI 0x0F +#define LF 0x0A + +#define MAX_ESCSEQLEN 16 + +#define CHARSET_ISO8859_1 'A' +#define CHARSET_ASCII 'B' +#define CHARSET_ISO8859_7 'F' +#define CHARSET_JISX0201_K 'I' +#define CHARSET_JISX0201_R 'J' + +#define CHARSET_GB2312 ('A'|CHARSET_DBCS) +#define CHARSET_JISX0208 ('B'|CHARSET_DBCS) +#define CHARSET_KSX1001 ('C'|CHARSET_DBCS) +#define CHARSET_JISX0212 ('D'|CHARSET_DBCS) +#define CHARSET_GB2312_8565 ('E'|CHARSET_DBCS) +#define CHARSET_CNS11643_1 ('G'|CHARSET_DBCS) +#define CHARSET_CNS11643_2 ('H'|CHARSET_DBCS) +#define CHARSET_JISX0213_2000_1 ('O'|CHARSET_DBCS) +#define CHARSET_JISX0213_2 ('P'|CHARSET_DBCS) +#define CHARSET_JISX0213_2004_1 ('Q'|CHARSET_DBCS) +#define CHARSET_JISX0208_O ('@'|CHARSET_DBCS) -#define CHARSET_DBCS 0x80 -#define ESCMARK(mark) ((mark) & 0x7f) +#define CHARSET_DBCS 0x80 +#define ESCMARK(mark) ((mark) & 0x7f) -#define IS_ESCEND(c) (((c) >= 'A' && (c) <= 'Z') || (c) == '@') +#define IS_ESCEND(c) (((c) >= 'A' && (c) <= 'Z') || (c) == '@') #define IS_ISO2022ESC(c2) \ - ((c2) == '(' || (c2) == ')' || (c2) == '$' || \ - (c2) == '.' || (c2) == '&') - /* this is not a complete list of ISO-2022 escape sequence headers. - * but, it's enough to implement CJK instances of iso-2022. */ - -#define MAP_UNMAPPABLE 0xFFFF -#define MAP_MULTIPLE_AVAIL 0xFFFE /* for JIS X 0213 */ - -#define F_SHIFTED 0x01 -#define F_ESCTHROUGHOUT 0x02 - -#define STATE_SETG(dn, v) ((state)->c[dn]) = (v); -#define STATE_GETG(dn) ((state)->c[dn]) - -#define STATE_G0 STATE_GETG(0) -#define STATE_G1 STATE_GETG(1) -#define STATE_G2 STATE_GETG(2) -#define STATE_G3 STATE_GETG(3) -#define STATE_SETG0(v) STATE_SETG(0, v) -#define STATE_SETG1(v) STATE_SETG(1, v) -#define STATE_SETG2(v) STATE_SETG(2, v) -#define STATE_SETG3(v) STATE_SETG(3, v) - -#define STATE_SETFLAG(f) ((state)->c[4]) |= (f); -#define STATE_GETFLAG(f) ((state)->c[4] & (f)) -#define STATE_CLEARFLAG(f) ((state)->c[4]) &= ~(f); -#define STATE_CLEARFLAGS() ((state)->c[4]) = 0; - -#define ISO2022_CONFIG ((const struct iso2022_config *)config) -#define CONFIG_ISSET(flag) (ISO2022_CONFIG->flags & (flag)) -#define CONFIG_DESIGNATIONS (ISO2022_CONFIG->designations) + ((c2) == '(' || (c2) == ')' || (c2) == '$' || \ + (c2) == '.' || (c2) == '&') + /* this is not a complete list of ISO-2022 escape sequence headers. + * but, it's enough to implement CJK instances of iso-2022. */ + +#define MAP_UNMAPPABLE 0xFFFF +#define MAP_MULTIPLE_AVAIL 0xFFFE /* for JIS X 0213 */ + +#define F_SHIFTED 0x01 +#define F_ESCTHROUGHOUT 0x02 + +#define STATE_SETG(dn, v) ((state)->c[dn]) = (v); +#define STATE_GETG(dn) ((state)->c[dn]) + +#define STATE_G0 STATE_GETG(0) +#define STATE_G1 STATE_GETG(1) +#define STATE_G2 STATE_GETG(2) +#define STATE_G3 STATE_GETG(3) +#define STATE_SETG0(v) STATE_SETG(0, v) +#define STATE_SETG1(v) STATE_SETG(1, v) +#define STATE_SETG2(v) STATE_SETG(2, v) +#define STATE_SETG3(v) STATE_SETG(3, v) + +#define STATE_SETFLAG(f) ((state)->c[4]) |= (f); +#define STATE_GETFLAG(f) ((state)->c[4] & (f)) +#define STATE_CLEARFLAG(f) ((state)->c[4]) &= ~(f); +#define STATE_CLEARFLAGS() ((state)->c[4]) = 0; + +#define ISO2022_CONFIG ((const struct iso2022_config *)config) +#define CONFIG_ISSET(flag) (ISO2022_CONFIG->flags & (flag)) +#define CONFIG_DESIGNATIONS (ISO2022_CONFIG->designations) /* iso2022_config.flags */ -#define NO_SHIFT 0x01 -#define USE_G2 0x02 -#define USE_JISX0208_EXT 0x04 +#define NO_SHIFT 0x01 +#define USE_G2 0x02 +#define USE_JISX0208_EXT 0x04 /*-*- internal data structures -*-*/ @@ -106,434 +106,434 @@ typedef DBCHAR (*iso2022_encode_func)(const ucs4_t *data, Py_ssize_t *length); struct iso2022_designation { - unsigned char mark; - unsigned char plane; - unsigned char width; - iso2022_init_func initializer; - iso2022_decode_func decoder; - iso2022_encode_func encoder; + unsigned char mark; + unsigned char plane; + unsigned char width; + iso2022_init_func initializer; + iso2022_decode_func decoder; + iso2022_encode_func encoder; }; struct iso2022_config { - int flags; - const struct iso2022_designation *designations; /* non-ascii desigs */ + int flags; + const struct iso2022_designation *designations; /* non-ascii desigs */ }; /*-*- iso-2022 codec implementation -*-*/ CODEC_INIT(iso2022) { - const struct iso2022_designation *desig = CONFIG_DESIGNATIONS; - for (desig = CONFIG_DESIGNATIONS; desig->mark; desig++) - if (desig->initializer != NULL && desig->initializer() != 0) - return -1; - return 0; + const struct iso2022_designation *desig = CONFIG_DESIGNATIONS; + for (desig = CONFIG_DESIGNATIONS; desig->mark; desig++) + if (desig->initializer != NULL && desig->initializer() != 0) + return -1; + return 0; } ENCODER_INIT(iso2022) { - STATE_CLEARFLAGS() - STATE_SETG0(CHARSET_ASCII) - STATE_SETG1(CHARSET_ASCII) - return 0; + STATE_CLEARFLAGS() + STATE_SETG0(CHARSET_ASCII) + STATE_SETG1(CHARSET_ASCII) + return 0; } ENCODER_RESET(iso2022) { - if (STATE_GETFLAG(F_SHIFTED)) { - WRITE1(SI) - NEXT_OUT(1) - STATE_CLEARFLAG(F_SHIFTED) - } - if (STATE_G0 != CHARSET_ASCII) { - WRITE3(ESC, '(', 'B') - NEXT_OUT(3) - STATE_SETG0(CHARSET_ASCII) - } - return 0; + if (STATE_GETFLAG(F_SHIFTED)) { + WRITE1(SI) + NEXT_OUT(1) + STATE_CLEARFLAG(F_SHIFTED) + } + if (STATE_G0 != CHARSET_ASCII) { + WRITE3(ESC, '(', 'B') + NEXT_OUT(3) + STATE_SETG0(CHARSET_ASCII) + } + return 0; } ENCODER(iso2022) { - while (inleft > 0) { - const struct iso2022_designation *dsg; - DBCHAR encoded; - ucs4_t c = **inbuf; - Py_ssize_t insize; - - if (c < 0x80) { - if (STATE_G0 != CHARSET_ASCII) { - WRITE3(ESC, '(', 'B') - STATE_SETG0(CHARSET_ASCII) - NEXT_OUT(3) - } - if (STATE_GETFLAG(F_SHIFTED)) { - WRITE1(SI) - STATE_CLEARFLAG(F_SHIFTED) - NEXT_OUT(1) - } - WRITE1((unsigned char)c) - NEXT(1, 1) - continue; - } - - DECODE_SURROGATE(c) - insize = GET_INSIZE(c); - - encoded = MAP_UNMAPPABLE; - for (dsg = CONFIG_DESIGNATIONS; dsg->mark; dsg++) { - Py_ssize_t length = 1; - encoded = dsg->encoder(&c, &length); - if (encoded == MAP_MULTIPLE_AVAIL) { - /* this implementation won't work for pair - * of non-bmp characters. */ - if (inleft < 2) { - if (!(flags & MBENC_FLUSH)) - return MBERR_TOOFEW; - length = -1; - } - else - length = 2; + while (inleft > 0) { + const struct iso2022_designation *dsg; + DBCHAR encoded; + ucs4_t c = **inbuf; + Py_ssize_t insize; + + if (c < 0x80) { + if (STATE_G0 != CHARSET_ASCII) { + WRITE3(ESC, '(', 'B') + STATE_SETG0(CHARSET_ASCII) + NEXT_OUT(3) + } + if (STATE_GETFLAG(F_SHIFTED)) { + WRITE1(SI) + STATE_CLEARFLAG(F_SHIFTED) + NEXT_OUT(1) + } + WRITE1((unsigned char)c) + NEXT(1, 1) + continue; + } + + DECODE_SURROGATE(c) + insize = GET_INSIZE(c); + + encoded = MAP_UNMAPPABLE; + for (dsg = CONFIG_DESIGNATIONS; dsg->mark; dsg++) { + Py_ssize_t length = 1; + encoded = dsg->encoder(&c, &length); + if (encoded == MAP_MULTIPLE_AVAIL) { + /* this implementation won't work for pair + * of non-bmp characters. */ + if (inleft < 2) { + if (!(flags & MBENC_FLUSH)) + return MBERR_TOOFEW; + length = -1; + } + else + length = 2; #if Py_UNICODE_SIZE == 2 - if (length == 2) { - ucs4_t u4in[2]; - u4in[0] = (ucs4_t)IN1; - u4in[1] = (ucs4_t)IN2; - encoded = dsg->encoder(u4in, &length); - } else - encoded = dsg->encoder(&c, &length); + if (length == 2) { + ucs4_t u4in[2]; + u4in[0] = (ucs4_t)IN1; + u4in[1] = (ucs4_t)IN2; + encoded = dsg->encoder(u4in, &length); + } else + encoded = dsg->encoder(&c, &length); #else - encoded = dsg->encoder(&c, &length); + encoded = dsg->encoder(&c, &length); #endif - if (encoded != MAP_UNMAPPABLE) { - insize = length; - break; - } - } - else if (encoded != MAP_UNMAPPABLE) - break; - } - - if (!dsg->mark) - return 1; - assert(dsg->width == 1 || dsg->width == 2); - - switch (dsg->plane) { - case 0: /* G0 */ - if (STATE_GETFLAG(F_SHIFTED)) { - WRITE1(SI) - STATE_CLEARFLAG(F_SHIFTED) - NEXT_OUT(1) - } - if (STATE_G0 != dsg->mark) { - if (dsg->width == 1) { - WRITE3(ESC, '(', ESCMARK(dsg->mark)) - STATE_SETG0(dsg->mark) - NEXT_OUT(3) - } - else if (dsg->mark == CHARSET_JISX0208) { - WRITE3(ESC, '$', ESCMARK(dsg->mark)) - STATE_SETG0(dsg->mark) - NEXT_OUT(3) - } - else { - WRITE4(ESC, '$', '(', - ESCMARK(dsg->mark)) - STATE_SETG0(dsg->mark) - NEXT_OUT(4) - } - } - break; - case 1: /* G1 */ - if (STATE_G1 != dsg->mark) { - if (dsg->width == 1) { - WRITE3(ESC, ')', ESCMARK(dsg->mark)) - STATE_SETG1(dsg->mark) - NEXT_OUT(3) - } - else { - WRITE4(ESC, '$', ')', - ESCMARK(dsg->mark)) - STATE_SETG1(dsg->mark) - NEXT_OUT(4) - } - } - if (!STATE_GETFLAG(F_SHIFTED)) { - WRITE1(SO) - STATE_SETFLAG(F_SHIFTED) - NEXT_OUT(1) - } - break; - default: /* G2 and G3 is not supported: no encoding in - * CJKCodecs are using them yet */ - return MBERR_INTERNAL; - } - - if (dsg->width == 1) { - WRITE1((unsigned char)encoded) - NEXT_OUT(1) - } - else { - WRITE2(encoded >> 8, encoded & 0xff) - NEXT_OUT(2) - } - NEXT_IN(insize) - } + if (encoded != MAP_UNMAPPABLE) { + insize = length; + break; + } + } + else if (encoded != MAP_UNMAPPABLE) + break; + } + + if (!dsg->mark) + return 1; + assert(dsg->width == 1 || dsg->width == 2); + + switch (dsg->plane) { + case 0: /* G0 */ + if (STATE_GETFLAG(F_SHIFTED)) { + WRITE1(SI) + STATE_CLEARFLAG(F_SHIFTED) + NEXT_OUT(1) + } + if (STATE_G0 != dsg->mark) { + if (dsg->width == 1) { + WRITE3(ESC, '(', ESCMARK(dsg->mark)) + STATE_SETG0(dsg->mark) + NEXT_OUT(3) + } + else if (dsg->mark == CHARSET_JISX0208) { + WRITE3(ESC, '$', ESCMARK(dsg->mark)) + STATE_SETG0(dsg->mark) + NEXT_OUT(3) + } + else { + WRITE4(ESC, '$', '(', + ESCMARK(dsg->mark)) + STATE_SETG0(dsg->mark) + NEXT_OUT(4) + } + } + break; + case 1: /* G1 */ + if (STATE_G1 != dsg->mark) { + if (dsg->width == 1) { + WRITE3(ESC, ')', ESCMARK(dsg->mark)) + STATE_SETG1(dsg->mark) + NEXT_OUT(3) + } + else { + WRITE4(ESC, '$', ')', + ESCMARK(dsg->mark)) + STATE_SETG1(dsg->mark) + NEXT_OUT(4) + } + } + if (!STATE_GETFLAG(F_SHIFTED)) { + WRITE1(SO) + STATE_SETFLAG(F_SHIFTED) + NEXT_OUT(1) + } + break; + default: /* G2 and G3 is not supported: no encoding in + * CJKCodecs are using them yet */ + return MBERR_INTERNAL; + } + + if (dsg->width == 1) { + WRITE1((unsigned char)encoded) + NEXT_OUT(1) + } + else { + WRITE2(encoded >> 8, encoded & 0xff) + NEXT_OUT(2) + } + NEXT_IN(insize) + } - return 0; + return 0; } DECODER_INIT(iso2022) { - STATE_CLEARFLAGS() - STATE_SETG0(CHARSET_ASCII) - STATE_SETG1(CHARSET_ASCII) - STATE_SETG2(CHARSET_ASCII) - return 0; + STATE_CLEARFLAGS() + STATE_SETG0(CHARSET_ASCII) + STATE_SETG1(CHARSET_ASCII) + STATE_SETG2(CHARSET_ASCII) + return 0; } DECODER_RESET(iso2022) { - STATE_SETG0(CHARSET_ASCII) - STATE_CLEARFLAG(F_SHIFTED) - return 0; + STATE_SETG0(CHARSET_ASCII) + STATE_CLEARFLAG(F_SHIFTED) + return 0; } static Py_ssize_t iso2022processesc(const void *config, MultibyteCodec_State *state, - const unsigned char **inbuf, Py_ssize_t *inleft) + const unsigned char **inbuf, Py_ssize_t *inleft) { - unsigned char charset, designation; - Py_ssize_t i, esclen; + unsigned char charset, designation; + Py_ssize_t i, esclen; - for (i = 1;i < MAX_ESCSEQLEN;i++) { - if (i >= *inleft) - return MBERR_TOOFEW; - if (IS_ESCEND((*inbuf)[i])) { - esclen = i + 1; - break; - } - else if (CONFIG_ISSET(USE_JISX0208_EXT) && i+1 < *inleft && - (*inbuf)[i] == '&' && (*inbuf)[i+1] == '@') - i += 2; - } - - if (i >= MAX_ESCSEQLEN) - return 1; /* unterminated escape sequence */ - - switch (esclen) { - case 3: - if (IN2 == '$') { - charset = IN3 | CHARSET_DBCS; - designation = 0; - } - else { - charset = IN3; - if (IN2 == '(') designation = 0; - else if (IN2 == ')') designation = 1; - else if (CONFIG_ISSET(USE_G2) && IN2 == '.') - designation = 2; - else return 3; - } - break; - case 4: - if (IN2 != '$') - return 4; - - charset = IN4 | CHARSET_DBCS; - if (IN3 == '(') designation = 0; - else if (IN3 == ')') designation = 1; - else return 4; - break; - case 6: /* designation with prefix */ - if (CONFIG_ISSET(USE_JISX0208_EXT) && - (*inbuf)[3] == ESC && (*inbuf)[4] == '$' && - (*inbuf)[5] == 'B') { - charset = 'B' | CHARSET_DBCS; - designation = 0; - } - else - return 6; - break; - default: - return esclen; - } - - /* raise error when the charset is not designated for this encoding */ - if (charset != CHARSET_ASCII) { - const struct iso2022_designation *dsg; - - for (dsg = CONFIG_DESIGNATIONS; dsg->mark; dsg++) - if (dsg->mark == charset) - break; - if (!dsg->mark) - return esclen; - } - - STATE_SETG(designation, charset) - *inleft -= esclen; - (*inbuf) += esclen; - return 0; -} - -#define ISO8859_7_DECODE(c, assi) \ - if ((c) < 0xa0) (assi) = (c); \ - else if ((c) < 0xc0 && (0x288f3bc9L & (1L << ((c)-0xa0)))) \ - (assi) = (c); \ - else if ((c) >= 0xb4 && (c) <= 0xfe && ((c) >= 0xd4 || \ - (0xbffffd77L & (1L << ((c)-0xb4))))) \ - (assi) = 0x02d0 + (c); \ - else if ((c) == 0xa1) (assi) = 0x2018; \ - else if ((c) == 0xa2) (assi) = 0x2019; \ - else if ((c) == 0xaf) (assi) = 0x2015; + for (i = 1;i < MAX_ESCSEQLEN;i++) { + if (i >= *inleft) + return MBERR_TOOFEW; + if (IS_ESCEND((*inbuf)[i])) { + esclen = i + 1; + break; + } + else if (CONFIG_ISSET(USE_JISX0208_EXT) && i+1 < *inleft && + (*inbuf)[i] == '&' && (*inbuf)[i+1] == '@') + i += 2; + } + + if (i >= MAX_ESCSEQLEN) + return 1; /* unterminated escape sequence */ + + switch (esclen) { + case 3: + if (IN2 == '$') { + charset = IN3 | CHARSET_DBCS; + designation = 0; + } + else { + charset = IN3; + if (IN2 == '(') designation = 0; + else if (IN2 == ')') designation = 1; + else if (CONFIG_ISSET(USE_G2) && IN2 == '.') + designation = 2; + else return 3; + } + break; + case 4: + if (IN2 != '$') + return 4; + + charset = IN4 | CHARSET_DBCS; + if (IN3 == '(') designation = 0; + else if (IN3 == ')') designation = 1; + else return 4; + break; + case 6: /* designation with prefix */ + if (CONFIG_ISSET(USE_JISX0208_EXT) && + (*inbuf)[3] == ESC && (*inbuf)[4] == '$' && + (*inbuf)[5] == 'B') { + charset = 'B' | CHARSET_DBCS; + designation = 0; + } + else + return 6; + break; + default: + return esclen; + } + + /* raise error when the charset is not designated for this encoding */ + if (charset != CHARSET_ASCII) { + const struct iso2022_designation *dsg; + + for (dsg = CONFIG_DESIGNATIONS; dsg->mark; dsg++) + if (dsg->mark == charset) + break; + if (!dsg->mark) + return esclen; + } + + STATE_SETG(designation, charset) + *inleft -= esclen; + (*inbuf) += esclen; + return 0; +} + +#define ISO8859_7_DECODE(c, assi) \ + if ((c) < 0xa0) (assi) = (c); \ + else if ((c) < 0xc0 && (0x288f3bc9L & (1L << ((c)-0xa0)))) \ + (assi) = (c); \ + else if ((c) >= 0xb4 && (c) <= 0xfe && ((c) >= 0xd4 || \ + (0xbffffd77L & (1L << ((c)-0xb4))))) \ + (assi) = 0x02d0 + (c); \ + else if ((c) == 0xa1) (assi) = 0x2018; \ + else if ((c) == 0xa2) (assi) = 0x2019; \ + else if ((c) == 0xaf) (assi) = 0x2015; static Py_ssize_t iso2022processg2(const void *config, MultibyteCodec_State *state, - const unsigned char **inbuf, Py_ssize_t *inleft, - Py_UNICODE **outbuf, Py_ssize_t *outleft) + const unsigned char **inbuf, Py_ssize_t *inleft, + Py_UNICODE **outbuf, Py_ssize_t *outleft) { - /* not written to use encoder, decoder functions because only few - * encodings use G2 designations in CJKCodecs */ - if (STATE_G2 == CHARSET_ISO8859_1) { - if (IN3 < 0x80) - OUT1(IN3 + 0x80) - else - return 3; - } - else if (STATE_G2 == CHARSET_ISO8859_7) { - ISO8859_7_DECODE(IN3 ^ 0x80, **outbuf) - else return 3; - } - else if (STATE_G2 == CHARSET_ASCII) { - if (IN3 & 0x80) return 3; - else **outbuf = IN3; - } - else - return MBERR_INTERNAL; - - (*inbuf) += 3; - *inleft -= 3; - (*outbuf) += 1; - *outleft -= 1; - return 0; + /* not written to use encoder, decoder functions because only few + * encodings use G2 designations in CJKCodecs */ + if (STATE_G2 == CHARSET_ISO8859_1) { + if (IN3 < 0x80) + OUT1(IN3 + 0x80) + else + return 3; + } + else if (STATE_G2 == CHARSET_ISO8859_7) { + ISO8859_7_DECODE(IN3 ^ 0x80, **outbuf) + else return 3; + } + else if (STATE_G2 == CHARSET_ASCII) { + if (IN3 & 0x80) return 3; + else **outbuf = IN3; + } + else + return MBERR_INTERNAL; + + (*inbuf) += 3; + *inleft -= 3; + (*outbuf) += 1; + *outleft -= 1; + return 0; } DECODER(iso2022) { - const struct iso2022_designation *dsgcache = NULL; + const struct iso2022_designation *dsgcache = NULL; - while (inleft > 0) { - unsigned char c = IN1; - Py_ssize_t err; - - if (STATE_GETFLAG(F_ESCTHROUGHOUT)) { - /* ESC throughout mode: - * for non-iso2022 escape sequences */ - WRITE1(c) /* assume as ISO-8859-1 */ - NEXT(1, 1) - if (IS_ESCEND(c)) { - STATE_CLEARFLAG(F_ESCTHROUGHOUT) - } - continue; - } - - switch (c) { - case ESC: - REQUIRE_INBUF(2) - if (IS_ISO2022ESC(IN2)) { - err = iso2022processesc(config, state, - inbuf, &inleft); - if (err != 0) - return err; - } - else if (CONFIG_ISSET(USE_G2) && IN2 == 'N') {/* SS2 */ - REQUIRE_INBUF(3) - err = iso2022processg2(config, state, - inbuf, &inleft, outbuf, &outleft); - if (err != 0) - return err; - } - else { - WRITE1(ESC) - STATE_SETFLAG(F_ESCTHROUGHOUT) - NEXT(1, 1) - } - break; - case SI: - if (CONFIG_ISSET(NO_SHIFT)) - goto bypass; - STATE_CLEARFLAG(F_SHIFTED) - NEXT_IN(1) - break; - case SO: - if (CONFIG_ISSET(NO_SHIFT)) - goto bypass; - STATE_SETFLAG(F_SHIFTED) - NEXT_IN(1) - break; - case LF: - STATE_CLEARFLAG(F_SHIFTED) - WRITE1(LF) - NEXT(1, 1) - break; - default: - if (c < 0x20) /* C0 */ - goto bypass; - else if (c >= 0x80) - return 1; - else { - const struct iso2022_designation *dsg; - unsigned char charset; - ucs4_t decoded; - - if (STATE_GETFLAG(F_SHIFTED)) - charset = STATE_G1; - else - charset = STATE_G0; - - if (charset == CHARSET_ASCII) { -bypass: WRITE1(c) - NEXT(1, 1) - break; - } - - if (dsgcache != NULL && - dsgcache->mark == charset) - dsg = dsgcache; - else { - for (dsg = CONFIG_DESIGNATIONS; - dsg->mark != charset + while (inleft > 0) { + unsigned char c = IN1; + Py_ssize_t err; + + if (STATE_GETFLAG(F_ESCTHROUGHOUT)) { + /* ESC throughout mode: + * for non-iso2022 escape sequences */ + WRITE1(c) /* assume as ISO-8859-1 */ + NEXT(1, 1) + if (IS_ESCEND(c)) { + STATE_CLEARFLAG(F_ESCTHROUGHOUT) + } + continue; + } + + switch (c) { + case ESC: + REQUIRE_INBUF(2) + if (IS_ISO2022ESC(IN2)) { + err = iso2022processesc(config, state, + inbuf, &inleft); + if (err != 0) + return err; + } + else if (CONFIG_ISSET(USE_G2) && IN2 == 'N') {/* SS2 */ + REQUIRE_INBUF(3) + err = iso2022processg2(config, state, + inbuf, &inleft, outbuf, &outleft); + if (err != 0) + return err; + } + else { + WRITE1(ESC) + STATE_SETFLAG(F_ESCTHROUGHOUT) + NEXT(1, 1) + } + break; + case SI: + if (CONFIG_ISSET(NO_SHIFT)) + goto bypass; + STATE_CLEARFLAG(F_SHIFTED) + NEXT_IN(1) + break; + case SO: + if (CONFIG_ISSET(NO_SHIFT)) + goto bypass; + STATE_SETFLAG(F_SHIFTED) + NEXT_IN(1) + break; + case LF: + STATE_CLEARFLAG(F_SHIFTED) + WRITE1(LF) + NEXT(1, 1) + break; + default: + if (c < 0x20) /* C0 */ + goto bypass; + else if (c >= 0x80) + return 1; + else { + const struct iso2022_designation *dsg; + unsigned char charset; + ucs4_t decoded; + + if (STATE_GETFLAG(F_SHIFTED)) + charset = STATE_G1; + else + charset = STATE_G0; + + if (charset == CHARSET_ASCII) { +bypass: WRITE1(c) + NEXT(1, 1) + break; + } + + if (dsgcache != NULL && + dsgcache->mark == charset) + dsg = dsgcache; + else { + for (dsg = CONFIG_DESIGNATIONS; + dsg->mark != charset #ifdef Py_DEBUG - && dsg->mark != '\0' + && dsg->mark != '\0' #endif - ;dsg++) - /* noop */; - assert(dsg->mark != '\0'); - dsgcache = dsg; - } - - REQUIRE_INBUF(dsg->width) - decoded = dsg->decoder(*inbuf); - if (decoded == MAP_UNMAPPABLE) - return dsg->width; - - if (decoded < 0x10000) { - WRITE1(decoded) - NEXT_OUT(1) - } - else if (decoded < 0x30000) { - WRITEUCS4(decoded) - } - else { /* JIS X 0213 pairs */ - WRITE2(decoded >> 16, decoded & 0xffff) - NEXT_OUT(2) - } - NEXT_IN(dsg->width) - } - break; - } - } - return 0; + ;dsg++) + /* noop */; + assert(dsg->mark != '\0'); + dsgcache = dsg; + } + + REQUIRE_INBUF(dsg->width) + decoded = dsg->decoder(*inbuf); + if (decoded == MAP_UNMAPPABLE) + return dsg->width; + + if (decoded < 0x10000) { + WRITE1(decoded) + NEXT_OUT(1) + } + else if (decoded < 0x30000) { + WRITEUCS4(decoded) + } + else { /* JIS X 0213 pairs */ + WRITE2(decoded >> 16, decoded & 0xffff) + NEXT_OUT(2) + } + NEXT_IN(dsg->width) + } + break; + } + } + return 0; } /*-*- mapping table holders -*-*/ @@ -567,542 +567,542 @@ static int ksx1001_init(void) { - static int initialized = 0; + static int initialized = 0; - if (!initialized && ( - IMPORT_MAP(kr, cp949, &cp949_encmap, NULL) || - IMPORT_MAP(kr, ksx1001, NULL, &ksx1001_decmap))) - return -1; - initialized = 1; - return 0; + if (!initialized && ( + IMPORT_MAP(kr, cp949, &cp949_encmap, NULL) || + IMPORT_MAP(kr, ksx1001, NULL, &ksx1001_decmap))) + return -1; + initialized = 1; + return 0; } static ucs4_t ksx1001_decoder(const unsigned char *data) { - ucs4_t u; - TRYMAP_DEC(ksx1001, u, data[0], data[1]) - return u; - else - return MAP_UNMAPPABLE; + ucs4_t u; + TRYMAP_DEC(ksx1001, u, data[0], data[1]) + return u; + else + return MAP_UNMAPPABLE; } static DBCHAR ksx1001_encoder(const ucs4_t *data, Py_ssize_t *length) { - DBCHAR coded; - assert(*length == 1); - if (*data < 0x10000) { - TRYMAP_ENC(cp949, coded, *data) - if (!(coded & 0x8000)) - return coded; - } - return MAP_UNMAPPABLE; + DBCHAR coded; + assert(*length == 1); + if (*data < 0x10000) { + TRYMAP_ENC(cp949, coded, *data) + if (!(coded & 0x8000)) + return coded; + } + return MAP_UNMAPPABLE; } static int jisx0208_init(void) { - static int initialized = 0; + static int initialized = 0; - if (!initialized && ( - IMPORT_MAP(jp, jisxcommon, &jisxcommon_encmap, NULL) || - IMPORT_MAP(jp, jisx0208, NULL, &jisx0208_decmap))) - return -1; - initialized = 1; - return 0; + if (!initialized && ( + IMPORT_MAP(jp, jisxcommon, &jisxcommon_encmap, NULL) || + IMPORT_MAP(jp, jisx0208, NULL, &jisx0208_decmap))) + return -1; + initialized = 1; + return 0; } static ucs4_t jisx0208_decoder(const unsigned char *data) { - ucs4_t u; - if (data[0] == 0x21 && data[1] == 0x40) /* F/W REVERSE SOLIDUS */ - return 0xff3c; - else TRYMAP_DEC(jisx0208, u, data[0], data[1]) - return u; - else - return MAP_UNMAPPABLE; + ucs4_t u; + if (data[0] == 0x21 && data[1] == 0x40) /* F/W REVERSE SOLIDUS */ + return 0xff3c; + else TRYMAP_DEC(jisx0208, u, data[0], data[1]) + return u; + else + return MAP_UNMAPPABLE; } static DBCHAR jisx0208_encoder(const ucs4_t *data, Py_ssize_t *length) { - DBCHAR coded; - assert(*length == 1); - if (*data < 0x10000) { - if (*data == 0xff3c) /* F/W REVERSE SOLIDUS */ - return 0x2140; - else TRYMAP_ENC(jisxcommon, coded, *data) { - if (!(coded & 0x8000)) - return coded; - } - } - return MAP_UNMAPPABLE; + DBCHAR coded; + assert(*length == 1); + if (*data < 0x10000) { + if (*data == 0xff3c) /* F/W REVERSE SOLIDUS */ + return 0x2140; + else TRYMAP_ENC(jisxcommon, coded, *data) { + if (!(coded & 0x8000)) + return coded; + } + } + return MAP_UNMAPPABLE; } static int jisx0212_init(void) { - static int initialized = 0; + static int initialized = 0; - if (!initialized && ( - IMPORT_MAP(jp, jisxcommon, &jisxcommon_encmap, NULL) || - IMPORT_MAP(jp, jisx0212, NULL, &jisx0212_decmap))) - return -1; - initialized = 1; - return 0; + if (!initialized && ( + IMPORT_MAP(jp, jisxcommon, &jisxcommon_encmap, NULL) || + IMPORT_MAP(jp, jisx0212, NULL, &jisx0212_decmap))) + return -1; + initialized = 1; + return 0; } static ucs4_t jisx0212_decoder(const unsigned char *data) { - ucs4_t u; - TRYMAP_DEC(jisx0212, u, data[0], data[1]) - return u; - else - return MAP_UNMAPPABLE; + ucs4_t u; + TRYMAP_DEC(jisx0212, u, data[0], data[1]) + return u; + else + return MAP_UNMAPPABLE; } static DBCHAR jisx0212_encoder(const ucs4_t *data, Py_ssize_t *length) { - DBCHAR coded; - assert(*length == 1); - if (*data < 0x10000) { - TRYMAP_ENC(jisxcommon, coded, *data) { - if (coded & 0x8000) - return coded & 0x7fff; - } - } - return MAP_UNMAPPABLE; + DBCHAR coded; + assert(*length == 1); + if (*data < 0x10000) { + TRYMAP_ENC(jisxcommon, coded, *data) { + if (coded & 0x8000) + return coded & 0x7fff; + } + } + return MAP_UNMAPPABLE; } static int jisx0213_init(void) { - static int initialized = 0; + static int initialized = 0; - if (!initialized && ( - jisx0208_init() || - IMPORT_MAP(jp, jisx0213_bmp, - &jisx0213_bmp_encmap, NULL) || - IMPORT_MAP(jp, jisx0213_1_bmp, - NULL, &jisx0213_1_bmp_decmap) || - IMPORT_MAP(jp, jisx0213_2_bmp, - NULL, &jisx0213_2_bmp_decmap) || - IMPORT_MAP(jp, jisx0213_emp, - &jisx0213_emp_encmap, NULL) || - IMPORT_MAP(jp, jisx0213_1_emp, - NULL, &jisx0213_1_emp_decmap) || - IMPORT_MAP(jp, jisx0213_2_emp, - NULL, &jisx0213_2_emp_decmap) || - IMPORT_MAP(jp, jisx0213_pair, &jisx0213_pair_encmap, - &jisx0213_pair_decmap))) - return -1; - initialized = 1; - return 0; + if (!initialized && ( + jisx0208_init() || + IMPORT_MAP(jp, jisx0213_bmp, + &jisx0213_bmp_encmap, NULL) || + IMPORT_MAP(jp, jisx0213_1_bmp, + NULL, &jisx0213_1_bmp_decmap) || + IMPORT_MAP(jp, jisx0213_2_bmp, + NULL, &jisx0213_2_bmp_decmap) || + IMPORT_MAP(jp, jisx0213_emp, + &jisx0213_emp_encmap, NULL) || + IMPORT_MAP(jp, jisx0213_1_emp, + NULL, &jisx0213_1_emp_decmap) || + IMPORT_MAP(jp, jisx0213_2_emp, + NULL, &jisx0213_2_emp_decmap) || + IMPORT_MAP(jp, jisx0213_pair, &jisx0213_pair_encmap, + &jisx0213_pair_decmap))) + return -1; + initialized = 1; + return 0; } #define config ((void *)2000) static ucs4_t jisx0213_2000_1_decoder(const unsigned char *data) { - ucs4_t u; - EMULATE_JISX0213_2000_DECODE_PLANE1(u, data[0], data[1]) - else if (data[0] == 0x21 && data[1] == 0x40) /* F/W REVERSE SOLIDUS */ - return 0xff3c; - else TRYMAP_DEC(jisx0208, u, data[0], data[1]); - else TRYMAP_DEC(jisx0213_1_bmp, u, data[0], data[1]); - else TRYMAP_DEC(jisx0213_1_emp, u, data[0], data[1]) - u |= 0x20000; - else TRYMAP_DEC(jisx0213_pair, u, data[0], data[1]); - else - return MAP_UNMAPPABLE; - return u; + ucs4_t u; + EMULATE_JISX0213_2000_DECODE_PLANE1(u, data[0], data[1]) + else if (data[0] == 0x21 && data[1] == 0x40) /* F/W REVERSE SOLIDUS */ + return 0xff3c; + else TRYMAP_DEC(jisx0208, u, data[0], data[1]); + else TRYMAP_DEC(jisx0213_1_bmp, u, data[0], data[1]); + else TRYMAP_DEC(jisx0213_1_emp, u, data[0], data[1]) + u |= 0x20000; + else TRYMAP_DEC(jisx0213_pair, u, data[0], data[1]); + else + return MAP_UNMAPPABLE; + return u; } static ucs4_t jisx0213_2000_2_decoder(const unsigned char *data) { - ucs4_t u; - EMULATE_JISX0213_2000_DECODE_PLANE2(u, data[0], data[1]) - TRYMAP_DEC(jisx0213_2_bmp, u, data[0], data[1]); - else TRYMAP_DEC(jisx0213_2_emp, u, data[0], data[1]) - u |= 0x20000; - else - return MAP_UNMAPPABLE; - return u; + ucs4_t u; + EMULATE_JISX0213_2000_DECODE_PLANE2(u, data[0], data[1]) + TRYMAP_DEC(jisx0213_2_bmp, u, data[0], data[1]); + else TRYMAP_DEC(jisx0213_2_emp, u, data[0], data[1]) + u |= 0x20000; + else + return MAP_UNMAPPABLE; + return u; } #undef config static ucs4_t jisx0213_2004_1_decoder(const unsigned char *data) { - ucs4_t u; - if (data[0] == 0x21 && data[1] == 0x40) /* F/W REVERSE SOLIDUS */ - return 0xff3c; - else TRYMAP_DEC(jisx0208, u, data[0], data[1]); - else TRYMAP_DEC(jisx0213_1_bmp, u, data[0], data[1]); - else TRYMAP_DEC(jisx0213_1_emp, u, data[0], data[1]) - u |= 0x20000; - else TRYMAP_DEC(jisx0213_pair, u, data[0], data[1]); - else - return MAP_UNMAPPABLE; - return u; + ucs4_t u; + if (data[0] == 0x21 && data[1] == 0x40) /* F/W REVERSE SOLIDUS */ + return 0xff3c; + else TRYMAP_DEC(jisx0208, u, data[0], data[1]); + else TRYMAP_DEC(jisx0213_1_bmp, u, data[0], data[1]); + else TRYMAP_DEC(jisx0213_1_emp, u, data[0], data[1]) + u |= 0x20000; + else TRYMAP_DEC(jisx0213_pair, u, data[0], data[1]); + else + return MAP_UNMAPPABLE; + return u; } static ucs4_t jisx0213_2004_2_decoder(const unsigned char *data) { - ucs4_t u; - TRYMAP_DEC(jisx0213_2_bmp, u, data[0], data[1]); - else TRYMAP_DEC(jisx0213_2_emp, u, data[0], data[1]) - u |= 0x20000; - else - return MAP_UNMAPPABLE; - return u; + ucs4_t u; + TRYMAP_DEC(jisx0213_2_bmp, u, data[0], data[1]); + else TRYMAP_DEC(jisx0213_2_emp, u, data[0], data[1]) + u |= 0x20000; + else + return MAP_UNMAPPABLE; + return u; } static DBCHAR jisx0213_encoder(const ucs4_t *data, Py_ssize_t *length, void *config) { - DBCHAR coded; + DBCHAR coded; - switch (*length) { - case 1: /* first character */ - if (*data >= 0x10000) { - if ((*data) >> 16 == 0x20000 >> 16) { - EMULATE_JISX0213_2000_ENCODE_EMP(coded, *data) - else TRYMAP_ENC(jisx0213_emp, coded, - (*data) & 0xffff) - return coded; - } - return MAP_UNMAPPABLE; - } - - EMULATE_JISX0213_2000_ENCODE_BMP(coded, *data) - else TRYMAP_ENC(jisx0213_bmp, coded, *data) { - if (coded == MULTIC) - return MAP_MULTIPLE_AVAIL; - } - else TRYMAP_ENC(jisxcommon, coded, *data) { - if (coded & 0x8000) - return MAP_UNMAPPABLE; - } - else - return MAP_UNMAPPABLE; - return coded; - case 2: /* second character of unicode pair */ - coded = find_pairencmap((ucs2_t)data[0], (ucs2_t)data[1], - jisx0213_pair_encmap, JISX0213_ENCPAIRS); - if (coded == DBCINV) { - *length = 1; - coded = find_pairencmap((ucs2_t)data[0], 0, - jisx0213_pair_encmap, JISX0213_ENCPAIRS); - if (coded == DBCINV) - return MAP_UNMAPPABLE; - } - else - return coded; - case -1: /* flush unterminated */ - *length = 1; - coded = find_pairencmap((ucs2_t)data[0], 0, - jisx0213_pair_encmap, JISX0213_ENCPAIRS); - if (coded == DBCINV) - return MAP_UNMAPPABLE; - else - return coded; - default: - return MAP_UNMAPPABLE; - } + switch (*length) { + case 1: /* first character */ + if (*data >= 0x10000) { + if ((*data) >> 16 == 0x20000 >> 16) { + EMULATE_JISX0213_2000_ENCODE_EMP(coded, *data) + else TRYMAP_ENC(jisx0213_emp, coded, + (*data) & 0xffff) + return coded; + } + return MAP_UNMAPPABLE; + } + + EMULATE_JISX0213_2000_ENCODE_BMP(coded, *data) + else TRYMAP_ENC(jisx0213_bmp, coded, *data) { + if (coded == MULTIC) + return MAP_MULTIPLE_AVAIL; + } + else TRYMAP_ENC(jisxcommon, coded, *data) { + if (coded & 0x8000) + return MAP_UNMAPPABLE; + } + else + return MAP_UNMAPPABLE; + return coded; + case 2: /* second character of unicode pair */ + coded = find_pairencmap((ucs2_t)data[0], (ucs2_t)data[1], + jisx0213_pair_encmap, JISX0213_ENCPAIRS); + if (coded == DBCINV) { + *length = 1; + coded = find_pairencmap((ucs2_t)data[0], 0, + jisx0213_pair_encmap, JISX0213_ENCPAIRS); + if (coded == DBCINV) + return MAP_UNMAPPABLE; + } + else + return coded; + case -1: /* flush unterminated */ + *length = 1; + coded = find_pairencmap((ucs2_t)data[0], 0, + jisx0213_pair_encmap, JISX0213_ENCPAIRS); + if (coded == DBCINV) + return MAP_UNMAPPABLE; + else + return coded; + default: + return MAP_UNMAPPABLE; + } } static DBCHAR jisx0213_2000_1_encoder(const ucs4_t *data, Py_ssize_t *length) { - DBCHAR coded = jisx0213_encoder(data, length, (void *)2000); - if (coded == MAP_UNMAPPABLE || coded == MAP_MULTIPLE_AVAIL) - return coded; - else if (coded & 0x8000) - return MAP_UNMAPPABLE; - else - return coded; + DBCHAR coded = jisx0213_encoder(data, length, (void *)2000); + if (coded == MAP_UNMAPPABLE || coded == MAP_MULTIPLE_AVAIL) + return coded; + else if (coded & 0x8000) + return MAP_UNMAPPABLE; + else + return coded; } static DBCHAR jisx0213_2000_1_encoder_paironly(const ucs4_t *data, Py_ssize_t *length) { - DBCHAR coded; - Py_ssize_t ilength = *length; + DBCHAR coded; + Py_ssize_t ilength = *length; - coded = jisx0213_encoder(data, length, (void *)2000); - switch (ilength) { - case 1: - if (coded == MAP_MULTIPLE_AVAIL) - return MAP_MULTIPLE_AVAIL; - else - return MAP_UNMAPPABLE; - case 2: - if (*length != 2) - return MAP_UNMAPPABLE; - else - return coded; - default: - return MAP_UNMAPPABLE; - } + coded = jisx0213_encoder(data, length, (void *)2000); + switch (ilength) { + case 1: + if (coded == MAP_MULTIPLE_AVAIL) + return MAP_MULTIPLE_AVAIL; + else + return MAP_UNMAPPABLE; + case 2: + if (*length != 2) + return MAP_UNMAPPABLE; + else + return coded; + default: + return MAP_UNMAPPABLE; + } } static DBCHAR jisx0213_2000_2_encoder(const ucs4_t *data, Py_ssize_t *length) { - DBCHAR coded = jisx0213_encoder(data, length, (void *)2000); - if (coded == MAP_UNMAPPABLE || coded == MAP_MULTIPLE_AVAIL) - return coded; - else if (coded & 0x8000) - return coded & 0x7fff; - else - return MAP_UNMAPPABLE; + DBCHAR coded = jisx0213_encoder(data, length, (void *)2000); + if (coded == MAP_UNMAPPABLE || coded == MAP_MULTIPLE_AVAIL) + return coded; + else if (coded & 0x8000) + return coded & 0x7fff; + else + return MAP_UNMAPPABLE; } static DBCHAR jisx0213_2004_1_encoder(const ucs4_t *data, Py_ssize_t *length) { - DBCHAR coded = jisx0213_encoder(data, length, NULL); - if (coded == MAP_UNMAPPABLE || coded == MAP_MULTIPLE_AVAIL) - return coded; - else if (coded & 0x8000) - return MAP_UNMAPPABLE; - else - return coded; + DBCHAR coded = jisx0213_encoder(data, length, NULL); + if (coded == MAP_UNMAPPABLE || coded == MAP_MULTIPLE_AVAIL) + return coded; + else if (coded & 0x8000) + return MAP_UNMAPPABLE; + else + return coded; } static DBCHAR jisx0213_2004_1_encoder_paironly(const ucs4_t *data, Py_ssize_t *length) { - DBCHAR coded; - Py_ssize_t ilength = *length; + DBCHAR coded; + Py_ssize_t ilength = *length; - coded = jisx0213_encoder(data, length, NULL); - switch (ilength) { - case 1: - if (coded == MAP_MULTIPLE_AVAIL) - return MAP_MULTIPLE_AVAIL; - else - return MAP_UNMAPPABLE; - case 2: - if (*length != 2) - return MAP_UNMAPPABLE; - else - return coded; - default: - return MAP_UNMAPPABLE; - } + coded = jisx0213_encoder(data, length, NULL); + switch (ilength) { + case 1: + if (coded == MAP_MULTIPLE_AVAIL) + return MAP_MULTIPLE_AVAIL; + else + return MAP_UNMAPPABLE; + case 2: + if (*length != 2) + return MAP_UNMAPPABLE; + else + return coded; + default: + return MAP_UNMAPPABLE; + } } static DBCHAR jisx0213_2004_2_encoder(const ucs4_t *data, Py_ssize_t *length) { - DBCHAR coded = jisx0213_encoder(data, length, NULL); - if (coded == MAP_UNMAPPABLE || coded == MAP_MULTIPLE_AVAIL) - return coded; - else if (coded & 0x8000) - return coded & 0x7fff; - else - return MAP_UNMAPPABLE; + DBCHAR coded = jisx0213_encoder(data, length, NULL); + if (coded == MAP_UNMAPPABLE || coded == MAP_MULTIPLE_AVAIL) + return coded; + else if (coded & 0x8000) + return coded & 0x7fff; + else + return MAP_UNMAPPABLE; } static ucs4_t jisx0201_r_decoder(const unsigned char *data) { - ucs4_t u; - JISX0201_R_DECODE(*data, u) - else return MAP_UNMAPPABLE; - return u; + ucs4_t u; + JISX0201_R_DECODE(*data, u) + else return MAP_UNMAPPABLE; + return u; } static DBCHAR jisx0201_r_encoder(const ucs4_t *data, Py_ssize_t *length) { - DBCHAR coded; - JISX0201_R_ENCODE(*data, coded) - else return MAP_UNMAPPABLE; - return coded; + DBCHAR coded; + JISX0201_R_ENCODE(*data, coded) + else return MAP_UNMAPPABLE; + return coded; } static ucs4_t jisx0201_k_decoder(const unsigned char *data) { - ucs4_t u; - JISX0201_K_DECODE(*data ^ 0x80, u) - else return MAP_UNMAPPABLE; - return u; + ucs4_t u; + JISX0201_K_DECODE(*data ^ 0x80, u) + else return MAP_UNMAPPABLE; + return u; } static DBCHAR jisx0201_k_encoder(const ucs4_t *data, Py_ssize_t *length) { - DBCHAR coded; - JISX0201_K_ENCODE(*data, coded) - else return MAP_UNMAPPABLE; - return coded - 0x80; + DBCHAR coded; + JISX0201_K_ENCODE(*data, coded) + else return MAP_UNMAPPABLE; + return coded - 0x80; } static int gb2312_init(void) { - static int initialized = 0; + static int initialized = 0; - if (!initialized && ( - IMPORT_MAP(cn, gbcommon, &gbcommon_encmap, NULL) || - IMPORT_MAP(cn, gb2312, NULL, &gb2312_decmap))) - return -1; - initialized = 1; - return 0; + if (!initialized && ( + IMPORT_MAP(cn, gbcommon, &gbcommon_encmap, NULL) || + IMPORT_MAP(cn, gb2312, NULL, &gb2312_decmap))) + return -1; + initialized = 1; + return 0; } static ucs4_t gb2312_decoder(const unsigned char *data) { - ucs4_t u; - TRYMAP_DEC(gb2312, u, data[0], data[1]) - return u; - else - return MAP_UNMAPPABLE; + ucs4_t u; + TRYMAP_DEC(gb2312, u, data[0], data[1]) + return u; + else + return MAP_UNMAPPABLE; } static DBCHAR gb2312_encoder(const ucs4_t *data, Py_ssize_t *length) { - DBCHAR coded; - assert(*length == 1); - if (*data < 0x10000) { - TRYMAP_ENC(gbcommon, coded, *data) { - if (!(coded & 0x8000)) - return coded; - } - } - return MAP_UNMAPPABLE; + DBCHAR coded; + assert(*length == 1); + if (*data < 0x10000) { + TRYMAP_ENC(gbcommon, coded, *data) { + if (!(coded & 0x8000)) + return coded; + } + } + return MAP_UNMAPPABLE; } static ucs4_t dummy_decoder(const unsigned char *data) { - return MAP_UNMAPPABLE; + return MAP_UNMAPPABLE; } static DBCHAR dummy_encoder(const ucs4_t *data, Py_ssize_t *length) { - return MAP_UNMAPPABLE; + return MAP_UNMAPPABLE; } /*-*- registry tables -*-*/ -#define REGISTRY_KSX1001_G0 { CHARSET_KSX1001, 0, 2, \ - ksx1001_init, \ - ksx1001_decoder, ksx1001_encoder } -#define REGISTRY_KSX1001_G1 { CHARSET_KSX1001, 1, 2, \ - ksx1001_init, \ - ksx1001_decoder, ksx1001_encoder } -#define REGISTRY_JISX0201_R { CHARSET_JISX0201_R, 0, 1, \ - NULL, \ - jisx0201_r_decoder, jisx0201_r_encoder } -#define REGISTRY_JISX0201_K { CHARSET_JISX0201_K, 0, 1, \ - NULL, \ - jisx0201_k_decoder, jisx0201_k_encoder } -#define REGISTRY_JISX0208 { CHARSET_JISX0208, 0, 2, \ - jisx0208_init, \ - jisx0208_decoder, jisx0208_encoder } -#define REGISTRY_JISX0208_O { CHARSET_JISX0208_O, 0, 2, \ - jisx0208_init, \ - jisx0208_decoder, jisx0208_encoder } -#define REGISTRY_JISX0212 { CHARSET_JISX0212, 0, 2, \ - jisx0212_init, \ - jisx0212_decoder, jisx0212_encoder } -#define REGISTRY_JISX0213_2000_1 { CHARSET_JISX0213_2000_1, 0, 2, \ - jisx0213_init, \ - jisx0213_2000_1_decoder, \ - jisx0213_2000_1_encoder } +#define REGISTRY_KSX1001_G0 { CHARSET_KSX1001, 0, 2, \ + ksx1001_init, \ + ksx1001_decoder, ksx1001_encoder } +#define REGISTRY_KSX1001_G1 { CHARSET_KSX1001, 1, 2, \ + ksx1001_init, \ + ksx1001_decoder, ksx1001_encoder } +#define REGISTRY_JISX0201_R { CHARSET_JISX0201_R, 0, 1, \ + NULL, \ + jisx0201_r_decoder, jisx0201_r_encoder } +#define REGISTRY_JISX0201_K { CHARSET_JISX0201_K, 0, 1, \ + NULL, \ + jisx0201_k_decoder, jisx0201_k_encoder } +#define REGISTRY_JISX0208 { CHARSET_JISX0208, 0, 2, \ + jisx0208_init, \ + jisx0208_decoder, jisx0208_encoder } +#define REGISTRY_JISX0208_O { CHARSET_JISX0208_O, 0, 2, \ + jisx0208_init, \ + jisx0208_decoder, jisx0208_encoder } +#define REGISTRY_JISX0212 { CHARSET_JISX0212, 0, 2, \ + jisx0212_init, \ + jisx0212_decoder, jisx0212_encoder } +#define REGISTRY_JISX0213_2000_1 { CHARSET_JISX0213_2000_1, 0, 2, \ + jisx0213_init, \ + jisx0213_2000_1_decoder, \ + jisx0213_2000_1_encoder } #define REGISTRY_JISX0213_2000_1_PAIRONLY { CHARSET_JISX0213_2000_1, 0, 2, \ - jisx0213_init, \ - jisx0213_2000_1_decoder, \ - jisx0213_2000_1_encoder_paironly } -#define REGISTRY_JISX0213_2000_2 { CHARSET_JISX0213_2, 0, 2, \ - jisx0213_init, \ - jisx0213_2000_2_decoder, \ - jisx0213_2000_2_encoder } -#define REGISTRY_JISX0213_2004_1 { CHARSET_JISX0213_2004_1, 0, 2, \ - jisx0213_init, \ - jisx0213_2004_1_decoder, \ - jisx0213_2004_1_encoder } + jisx0213_init, \ + jisx0213_2000_1_decoder, \ + jisx0213_2000_1_encoder_paironly } +#define REGISTRY_JISX0213_2000_2 { CHARSET_JISX0213_2, 0, 2, \ + jisx0213_init, \ + jisx0213_2000_2_decoder, \ + jisx0213_2000_2_encoder } +#define REGISTRY_JISX0213_2004_1 { CHARSET_JISX0213_2004_1, 0, 2, \ + jisx0213_init, \ + jisx0213_2004_1_decoder, \ + jisx0213_2004_1_encoder } #define REGISTRY_JISX0213_2004_1_PAIRONLY { CHARSET_JISX0213_2004_1, 0, 2, \ - jisx0213_init, \ - jisx0213_2004_1_decoder, \ - jisx0213_2004_1_encoder_paironly } -#define REGISTRY_JISX0213_2004_2 { CHARSET_JISX0213_2, 0, 2, \ - jisx0213_init, \ - jisx0213_2004_2_decoder, \ - jisx0213_2004_2_encoder } -#define REGISTRY_GB2312 { CHARSET_GB2312, 0, 2, \ - gb2312_init, \ - gb2312_decoder, gb2312_encoder } -#define REGISTRY_CNS11643_1 { CHARSET_CNS11643_1, 1, 2, \ - cns11643_init, \ - cns11643_1_decoder, cns11643_1_encoder } -#define REGISTRY_CNS11643_2 { CHARSET_CNS11643_2, 2, 2, \ - cns11643_init, \ - cns11643_2_decoder, cns11643_2_encoder } -#define REGISTRY_ISO8859_1 { CHARSET_ISO8859_1, 2, 1, \ - NULL, dummy_decoder, dummy_encoder } -#define REGISTRY_ISO8859_7 { CHARSET_ISO8859_7, 2, 1, \ - NULL, dummy_decoder, dummy_encoder } -#define REGISTRY_SENTINEL { 0, } -#define CONFIGDEF(var, attrs) \ - static const struct iso2022_config iso2022_##var##_config = { \ - attrs, iso2022_##var##_designations \ - }; + jisx0213_init, \ + jisx0213_2004_1_decoder, \ + jisx0213_2004_1_encoder_paironly } +#define REGISTRY_JISX0213_2004_2 { CHARSET_JISX0213_2, 0, 2, \ + jisx0213_init, \ + jisx0213_2004_2_decoder, \ + jisx0213_2004_2_encoder } +#define REGISTRY_GB2312 { CHARSET_GB2312, 0, 2, \ + gb2312_init, \ + gb2312_decoder, gb2312_encoder } +#define REGISTRY_CNS11643_1 { CHARSET_CNS11643_1, 1, 2, \ + cns11643_init, \ + cns11643_1_decoder, cns11643_1_encoder } +#define REGISTRY_CNS11643_2 { CHARSET_CNS11643_2, 2, 2, \ + cns11643_init, \ + cns11643_2_decoder, cns11643_2_encoder } +#define REGISTRY_ISO8859_1 { CHARSET_ISO8859_1, 2, 1, \ + NULL, dummy_decoder, dummy_encoder } +#define REGISTRY_ISO8859_7 { CHARSET_ISO8859_7, 2, 1, \ + NULL, dummy_decoder, dummy_encoder } +#define REGISTRY_SENTINEL { 0, } +#define CONFIGDEF(var, attrs) \ + static const struct iso2022_config iso2022_##var##_config = { \ + attrs, iso2022_##var##_designations \ + }; static const struct iso2022_designation iso2022_kr_designations[] = { - REGISTRY_KSX1001_G1, REGISTRY_SENTINEL + REGISTRY_KSX1001_G1, REGISTRY_SENTINEL }; CONFIGDEF(kr, 0) static const struct iso2022_designation iso2022_jp_designations[] = { - REGISTRY_JISX0208, REGISTRY_JISX0201_R, REGISTRY_JISX0208_O, - REGISTRY_SENTINEL + REGISTRY_JISX0208, REGISTRY_JISX0201_R, REGISTRY_JISX0208_O, + REGISTRY_SENTINEL }; CONFIGDEF(jp, NO_SHIFT | USE_JISX0208_EXT) static const struct iso2022_designation iso2022_jp_1_designations[] = { - REGISTRY_JISX0208, REGISTRY_JISX0212, REGISTRY_JISX0201_R, - REGISTRY_JISX0208_O, REGISTRY_SENTINEL + REGISTRY_JISX0208, REGISTRY_JISX0212, REGISTRY_JISX0201_R, + REGISTRY_JISX0208_O, REGISTRY_SENTINEL }; CONFIGDEF(jp_1, NO_SHIFT | USE_JISX0208_EXT) static const struct iso2022_designation iso2022_jp_2_designations[] = { - REGISTRY_JISX0208, REGISTRY_JISX0212, REGISTRY_KSX1001_G0, - REGISTRY_GB2312, REGISTRY_JISX0201_R, REGISTRY_JISX0208_O, - REGISTRY_ISO8859_1, REGISTRY_ISO8859_7, REGISTRY_SENTINEL + REGISTRY_JISX0208, REGISTRY_JISX0212, REGISTRY_KSX1001_G0, + REGISTRY_GB2312, REGISTRY_JISX0201_R, REGISTRY_JISX0208_O, + REGISTRY_ISO8859_1, REGISTRY_ISO8859_7, REGISTRY_SENTINEL }; CONFIGDEF(jp_2, NO_SHIFT | USE_G2 | USE_JISX0208_EXT) static const struct iso2022_designation iso2022_jp_2004_designations[] = { - REGISTRY_JISX0213_2004_1_PAIRONLY, REGISTRY_JISX0208, - REGISTRY_JISX0213_2004_1, REGISTRY_JISX0213_2004_2, REGISTRY_SENTINEL + REGISTRY_JISX0213_2004_1_PAIRONLY, REGISTRY_JISX0208, + REGISTRY_JISX0213_2004_1, REGISTRY_JISX0213_2004_2, REGISTRY_SENTINEL }; CONFIGDEF(jp_2004, NO_SHIFT | USE_JISX0208_EXT) static const struct iso2022_designation iso2022_jp_3_designations[] = { - REGISTRY_JISX0213_2000_1_PAIRONLY, REGISTRY_JISX0208, - REGISTRY_JISX0213_2000_1, REGISTRY_JISX0213_2000_2, REGISTRY_SENTINEL + REGISTRY_JISX0213_2000_1_PAIRONLY, REGISTRY_JISX0208, + REGISTRY_JISX0213_2000_1, REGISTRY_JISX0213_2000_2, REGISTRY_SENTINEL }; CONFIGDEF(jp_3, NO_SHIFT | USE_JISX0208_EXT) static const struct iso2022_designation iso2022_jp_ext_designations[] = { - REGISTRY_JISX0208, REGISTRY_JISX0212, REGISTRY_JISX0201_R, - REGISTRY_JISX0201_K, REGISTRY_JISX0208_O, REGISTRY_SENTINEL + REGISTRY_JISX0208, REGISTRY_JISX0212, REGISTRY_JISX0201_R, + REGISTRY_JISX0201_K, REGISTRY_JISX0208_O, REGISTRY_SENTINEL }; CONFIGDEF(jp_ext, NO_SHIFT | USE_JISX0208_EXT) @@ -1111,11 +1111,11 @@ /* no mapping table here */ END_MAPPINGS_LIST -#define ISO2022_CODEC(variation) { \ - "iso2022_" #variation, \ - &iso2022_##variation##_config, \ - iso2022_codec_init, \ - _STATEFUL_METHODS(iso2022) \ +#define ISO2022_CODEC(variation) { \ + "iso2022_" #variation, \ + &iso2022_##variation##_config, \ + iso2022_codec_init, \ + _STATEFUL_METHODS(iso2022) \ }, BEGIN_CODECS_LIST Modified: python/branches/py3k-jit/Modules/cjkcodecs/_codecs_jp.c ============================================================================== --- python/branches/py3k-jit/Modules/cjkcodecs/_codecs_jp.c (original) +++ python/branches/py3k-jit/Modules/cjkcodecs/_codecs_jp.c Mon May 10 23:55:43 2010 @@ -19,124 +19,124 @@ ENCODER(cp932) { - while (inleft > 0) { - Py_UNICODE c = IN1; - DBCHAR code; - unsigned char c1, c2; - - if (c <= 0x80) { - WRITE1((unsigned char)c) - NEXT(1, 1) - continue; - } - else if (c >= 0xff61 && c <= 0xff9f) { - WRITE1(c - 0xfec0) - NEXT(1, 1) - continue; - } - else if (c >= 0xf8f0 && c <= 0xf8f3) { - /* Windows compatibility */ - REQUIRE_OUTBUF(1) - if (c == 0xf8f0) - OUT1(0xa0) - else - OUT1(c - 0xfef1 + 0xfd) - NEXT(1, 1) - continue; - } - - UCS4INVALID(c) - REQUIRE_OUTBUF(2) - - TRYMAP_ENC(cp932ext, code, c) { - OUT1(code >> 8) - OUT2(code & 0xff) - } - else TRYMAP_ENC(jisxcommon, code, c) { - if (code & 0x8000) /* MSB set: JIS X 0212 */ - return 1; - - /* JIS X 0208 */ - c1 = code >> 8; - c2 = code & 0xff; - c2 = (((c1 - 0x21) & 1) ? 0x5e : 0) + (c2 - 0x21); - c1 = (c1 - 0x21) >> 1; - OUT1(c1 < 0x1f ? c1 + 0x81 : c1 + 0xc1) - OUT2(c2 < 0x3f ? c2 + 0x40 : c2 + 0x41) - } - else if (c >= 0xe000 && c < 0xe758) { - /* User-defined area */ - c1 = (Py_UNICODE)(c - 0xe000) / 188; - c2 = (Py_UNICODE)(c - 0xe000) % 188; - OUT1(c1 + 0xf0) - OUT2(c2 < 0x3f ? c2 + 0x40 : c2 + 0x41) - } - else - return 1; + while (inleft > 0) { + Py_UNICODE c = IN1; + DBCHAR code; + unsigned char c1, c2; + + if (c <= 0x80) { + WRITE1((unsigned char)c) + NEXT(1, 1) + continue; + } + else if (c >= 0xff61 && c <= 0xff9f) { + WRITE1(c - 0xfec0) + NEXT(1, 1) + continue; + } + else if (c >= 0xf8f0 && c <= 0xf8f3) { + /* Windows compatibility */ + REQUIRE_OUTBUF(1) + if (c == 0xf8f0) + OUT1(0xa0) + else + OUT1(c - 0xfef1 + 0xfd) + NEXT(1, 1) + continue; + } + + UCS4INVALID(c) + REQUIRE_OUTBUF(2) + + TRYMAP_ENC(cp932ext, code, c) { + OUT1(code >> 8) + OUT2(code & 0xff) + } + else TRYMAP_ENC(jisxcommon, code, c) { + if (code & 0x8000) /* MSB set: JIS X 0212 */ + return 1; + + /* JIS X 0208 */ + c1 = code >> 8; + c2 = code & 0xff; + c2 = (((c1 - 0x21) & 1) ? 0x5e : 0) + (c2 - 0x21); + c1 = (c1 - 0x21) >> 1; + OUT1(c1 < 0x1f ? c1 + 0x81 : c1 + 0xc1) + OUT2(c2 < 0x3f ? c2 + 0x40 : c2 + 0x41) + } + else if (c >= 0xe000 && c < 0xe758) { + /* User-defined area */ + c1 = (Py_UNICODE)(c - 0xe000) / 188; + c2 = (Py_UNICODE)(c - 0xe000) % 188; + OUT1(c1 + 0xf0) + OUT2(c2 < 0x3f ? c2 + 0x40 : c2 + 0x41) + } + else + return 1; - NEXT(1, 2) - } + NEXT(1, 2) + } - return 0; + return 0; } DECODER(cp932) { - while (inleft > 0) { - unsigned char c = IN1, c2; + while (inleft > 0) { + unsigned char c = IN1, c2; - REQUIRE_OUTBUF(1) - if (c <= 0x80) { - OUT1(c) - NEXT(1, 1) - continue; - } - else if (c >= 0xa0 && c <= 0xdf) { - if (c == 0xa0) - OUT1(0xf8f0) /* half-width katakana */ - else - OUT1(0xfec0 + c) - NEXT(1, 1) - continue; - } - else if (c >= 0xfd/* && c <= 0xff*/) { - /* Windows compatibility */ - OUT1(0xf8f1 - 0xfd + c) - NEXT(1, 1) - continue; - } - - REQUIRE_INBUF(2) - c2 = IN2; - - TRYMAP_DEC(cp932ext, **outbuf, c, c2); - else if ((c >= 0x81 && c <= 0x9f) || (c >= 0xe0 && c <= 0xea)){ - if (c2 < 0x40 || (c2 > 0x7e && c2 < 0x80) || c2 > 0xfc) - return 2; - - c = (c < 0xe0 ? c - 0x81 : c - 0xc1); - c2 = (c2 < 0x80 ? c2 - 0x40 : c2 - 0x41); - c = (2 * c + (c2 < 0x5e ? 0 : 1) + 0x21); - c2 = (c2 < 0x5e ? c2 : c2 - 0x5e) + 0x21; - - TRYMAP_DEC(jisx0208, **outbuf, c, c2); - else return 2; - } - else if (c >= 0xf0 && c <= 0xf9) { - if ((c2 >= 0x40 && c2 <= 0x7e) || - (c2 >= 0x80 && c2 <= 0xfc)) - OUT1(0xe000 + 188 * (c - 0xf0) + - (c2 < 0x80 ? c2 - 0x40 : c2 - 0x41)) - else - return 2; - } - else - return 2; + REQUIRE_OUTBUF(1) + if (c <= 0x80) { + OUT1(c) + NEXT(1, 1) + continue; + } + else if (c >= 0xa0 && c <= 0xdf) { + if (c == 0xa0) + OUT1(0xf8f0) /* half-width katakana */ + else + OUT1(0xfec0 + c) + NEXT(1, 1) + continue; + } + else if (c >= 0xfd/* && c <= 0xff*/) { + /* Windows compatibility */ + OUT1(0xf8f1 - 0xfd + c) + NEXT(1, 1) + continue; + } + + REQUIRE_INBUF(2) + c2 = IN2; + + TRYMAP_DEC(cp932ext, **outbuf, c, c2); + else if ((c >= 0x81 && c <= 0x9f) || (c >= 0xe0 && c <= 0xea)){ + if (c2 < 0x40 || (c2 > 0x7e && c2 < 0x80) || c2 > 0xfc) + return 2; + + c = (c < 0xe0 ? c - 0x81 : c - 0xc1); + c2 = (c2 < 0x80 ? c2 - 0x40 : c2 - 0x41); + c = (2 * c + (c2 < 0x5e ? 0 : 1) + 0x21); + c2 = (c2 < 0x5e ? c2 : c2 - 0x5e) + 0x21; + + TRYMAP_DEC(jisx0208, **outbuf, c, c2); + else return 2; + } + else if (c >= 0xf0 && c <= 0xf9) { + if ((c2 >= 0x40 && c2 <= 0x7e) || + (c2 >= 0x80 && c2 <= 0xfc)) + OUT1(0xe000 + 188 * (c - 0xf0) + + (c2 < 0x80 ? c2 - 0x40 : c2 - 0x41)) + else + return 2; + } + else + return 2; - NEXT(2, 1) - } + NEXT(2, 1) + } - return 0; + return 0; } @@ -146,166 +146,166 @@ ENCODER(euc_jis_2004) { - while (inleft > 0) { - ucs4_t c = IN1; - DBCHAR code; - Py_ssize_t insize; - - if (c < 0x80) { - WRITE1(c) - NEXT(1, 1) - continue; - } - - DECODE_SURROGATE(c) - insize = GET_INSIZE(c); - - if (c <= 0xFFFF) { - EMULATE_JISX0213_2000_ENCODE_BMP(code, c) - else TRYMAP_ENC(jisx0213_bmp, code, c) { - if (code == MULTIC) { - if (inleft < 2) { - if (flags & MBENC_FLUSH) { - code = find_pairencmap( - (ucs2_t)c, 0, - jisx0213_pair_encmap, - JISX0213_ENCPAIRS); - if (code == DBCINV) - return 1; - } - else - return MBERR_TOOFEW; - } - else { - code = find_pairencmap( - (ucs2_t)c, (*inbuf)[1], - jisx0213_pair_encmap, - JISX0213_ENCPAIRS); - if (code == DBCINV) { - code = find_pairencmap( - (ucs2_t)c, 0, - jisx0213_pair_encmap, - JISX0213_ENCPAIRS); - if (code == DBCINV) - return 1; - } else - insize = 2; - } - } - } - else TRYMAP_ENC(jisxcommon, code, c); - else if (c >= 0xff61 && c <= 0xff9f) { - /* JIS X 0201 half-width katakana */ - WRITE2(0x8e, c - 0xfec0) - NEXT(1, 2) - continue; - } - else if (c == 0xff3c) - /* F/W REVERSE SOLIDUS (see NOTES) */ - code = 0x2140; - else if (c == 0xff5e) - /* F/W TILDE (see NOTES) */ - code = 0x2232; - else - return 1; - } - else if (c >> 16 == EMPBASE >> 16) { - EMULATE_JISX0213_2000_ENCODE_EMP(code, c) - else TRYMAP_ENC(jisx0213_emp, code, c & 0xffff); - else return insize; - } - else - return insize; - - if (code & 0x8000) { - /* Codeset 2 */ - WRITE3(0x8f, code >> 8, (code & 0xFF) | 0x80) - NEXT(insize, 3) - } else { - /* Codeset 1 */ - WRITE2((code >> 8) | 0x80, (code & 0xFF) | 0x80) - NEXT(insize, 2) - } - } + while (inleft > 0) { + ucs4_t c = IN1; + DBCHAR code; + Py_ssize_t insize; + + if (c < 0x80) { + WRITE1(c) + NEXT(1, 1) + continue; + } + + DECODE_SURROGATE(c) + insize = GET_INSIZE(c); + + if (c <= 0xFFFF) { + EMULATE_JISX0213_2000_ENCODE_BMP(code, c) + else TRYMAP_ENC(jisx0213_bmp, code, c) { + if (code == MULTIC) { + if (inleft < 2) { + if (flags & MBENC_FLUSH) { + code = find_pairencmap( + (ucs2_t)c, 0, + jisx0213_pair_encmap, + JISX0213_ENCPAIRS); + if (code == DBCINV) + return 1; + } + else + return MBERR_TOOFEW; + } + else { + code = find_pairencmap( + (ucs2_t)c, (*inbuf)[1], + jisx0213_pair_encmap, + JISX0213_ENCPAIRS); + if (code == DBCINV) { + code = find_pairencmap( + (ucs2_t)c, 0, + jisx0213_pair_encmap, + JISX0213_ENCPAIRS); + if (code == DBCINV) + return 1; + } else + insize = 2; + } + } + } + else TRYMAP_ENC(jisxcommon, code, c); + else if (c >= 0xff61 && c <= 0xff9f) { + /* JIS X 0201 half-width katakana */ + WRITE2(0x8e, c - 0xfec0) + NEXT(1, 2) + continue; + } + else if (c == 0xff3c) + /* F/W REVERSE SOLIDUS (see NOTES) */ + code = 0x2140; + else if (c == 0xff5e) + /* F/W TILDE (see NOTES) */ + code = 0x2232; + else + return 1; + } + else if (c >> 16 == EMPBASE >> 16) { + EMULATE_JISX0213_2000_ENCODE_EMP(code, c) + else TRYMAP_ENC(jisx0213_emp, code, c & 0xffff); + else return insize; + } + else + return insize; + + if (code & 0x8000) { + /* Codeset 2 */ + WRITE3(0x8f, code >> 8, (code & 0xFF) | 0x80) + NEXT(insize, 3) + } else { + /* Codeset 1 */ + WRITE2((code >> 8) | 0x80, (code & 0xFF) | 0x80) + NEXT(insize, 2) + } + } - return 0; + return 0; } DECODER(euc_jis_2004) { - while (inleft > 0) { - unsigned char c = IN1; - ucs4_t code; - - REQUIRE_OUTBUF(1) - - if (c < 0x80) { - OUT1(c) - NEXT(1, 1) - continue; - } - - if (c == 0x8e) { - /* JIS X 0201 half-width katakana */ - unsigned char c2; - - REQUIRE_INBUF(2) - c2 = IN2; - if (c2 >= 0xa1 && c2 <= 0xdf) { - OUT1(0xfec0 + c2) - NEXT(2, 1) - } - else - return 2; - } - else if (c == 0x8f) { - unsigned char c2, c3; - - REQUIRE_INBUF(3) - c2 = IN2 ^ 0x80; - c3 = IN3 ^ 0x80; - - /* JIS X 0213 Plane 2 or JIS X 0212 (see NOTES) */ - EMULATE_JISX0213_2000_DECODE_PLANE2(**outbuf, c2, c3) - else TRYMAP_DEC(jisx0213_2_bmp, **outbuf, c2, c3) ; - else TRYMAP_DEC(jisx0213_2_emp, code, c2, c3) { - WRITEUCS4(EMPBASE | code) - NEXT_IN(3) - continue; - } - else TRYMAP_DEC(jisx0212, **outbuf, c2, c3) ; - else return 3; - NEXT(3, 1) - } - else { - unsigned char c2; - - REQUIRE_INBUF(2) - c ^= 0x80; - c2 = IN2 ^ 0x80; - - /* JIS X 0213 Plane 1 */ - EMULATE_JISX0213_2000_DECODE_PLANE1(**outbuf, c, c2) - else if (c == 0x21 && c2 == 0x40) **outbuf = 0xff3c; - else if (c == 0x22 && c2 == 0x32) **outbuf = 0xff5e; - else TRYMAP_DEC(jisx0208, **outbuf, c, c2); - else TRYMAP_DEC(jisx0213_1_bmp, **outbuf, c, c2); - else TRYMAP_DEC(jisx0213_1_emp, code, c, c2) { - WRITEUCS4(EMPBASE | code) - NEXT_IN(2) - continue; - } - else TRYMAP_DEC(jisx0213_pair, code, c, c2) { - WRITE2(code >> 16, code & 0xffff) - NEXT(2, 2) - continue; - } - else return 2; - NEXT(2, 1) - } - } + while (inleft > 0) { + unsigned char c = IN1; + ucs4_t code; + + REQUIRE_OUTBUF(1) + + if (c < 0x80) { + OUT1(c) + NEXT(1, 1) + continue; + } + + if (c == 0x8e) { + /* JIS X 0201 half-width katakana */ + unsigned char c2; + + REQUIRE_INBUF(2) + c2 = IN2; + if (c2 >= 0xa1 && c2 <= 0xdf) { + OUT1(0xfec0 + c2) + NEXT(2, 1) + } + else + return 2; + } + else if (c == 0x8f) { + unsigned char c2, c3; + + REQUIRE_INBUF(3) + c2 = IN2 ^ 0x80; + c3 = IN3 ^ 0x80; + + /* JIS X 0213 Plane 2 or JIS X 0212 (see NOTES) */ + EMULATE_JISX0213_2000_DECODE_PLANE2(**outbuf, c2, c3) + else TRYMAP_DEC(jisx0213_2_bmp, **outbuf, c2, c3) ; + else TRYMAP_DEC(jisx0213_2_emp, code, c2, c3) { + WRITEUCS4(EMPBASE | code) + NEXT_IN(3) + continue; + } + else TRYMAP_DEC(jisx0212, **outbuf, c2, c3) ; + else return 3; + NEXT(3, 1) + } + else { + unsigned char c2; + + REQUIRE_INBUF(2) + c ^= 0x80; + c2 = IN2 ^ 0x80; + + /* JIS X 0213 Plane 1 */ + EMULATE_JISX0213_2000_DECODE_PLANE1(**outbuf, c, c2) + else if (c == 0x21 && c2 == 0x40) **outbuf = 0xff3c; + else if (c == 0x22 && c2 == 0x32) **outbuf = 0xff5e; + else TRYMAP_DEC(jisx0208, **outbuf, c, c2); + else TRYMAP_DEC(jisx0213_1_bmp, **outbuf, c, c2); + else TRYMAP_DEC(jisx0213_1_emp, code, c, c2) { + WRITEUCS4(EMPBASE | code) + NEXT_IN(2) + continue; + } + else TRYMAP_DEC(jisx0213_pair, code, c, c2) { + WRITE2(code >> 16, code & 0xffff) + NEXT(2, 2) + continue; + } + else return 2; + NEXT(2, 1) + } + } - return 0; + return 0; } @@ -315,114 +315,114 @@ ENCODER(euc_jp) { - while (inleft > 0) { - Py_UNICODE c = IN1; - DBCHAR code; - - if (c < 0x80) { - WRITE1((unsigned char)c) - NEXT(1, 1) - continue; - } - - UCS4INVALID(c) - - TRYMAP_ENC(jisxcommon, code, c); - else if (c >= 0xff61 && c <= 0xff9f) { - /* JIS X 0201 half-width katakana */ - WRITE2(0x8e, c - 0xfec0) - NEXT(1, 2) - continue; - } + while (inleft > 0) { + Py_UNICODE c = IN1; + DBCHAR code; + + if (c < 0x80) { + WRITE1((unsigned char)c) + NEXT(1, 1) + continue; + } + + UCS4INVALID(c) + + TRYMAP_ENC(jisxcommon, code, c); + else if (c >= 0xff61 && c <= 0xff9f) { + /* JIS X 0201 half-width katakana */ + WRITE2(0x8e, c - 0xfec0) + NEXT(1, 2) + continue; + } #ifndef STRICT_BUILD - else if (c == 0xff3c) /* FULL-WIDTH REVERSE SOLIDUS */ - code = 0x2140; - else if (c == 0xa5) { /* YEN SIGN */ - WRITE1(0x5c); - NEXT(1, 1) - continue; - } else if (c == 0x203e) { /* OVERLINE */ - WRITE1(0x7e); - NEXT(1, 1) - continue; - } + else if (c == 0xff3c) /* FULL-WIDTH REVERSE SOLIDUS */ + code = 0x2140; + else if (c == 0xa5) { /* YEN SIGN */ + WRITE1(0x5c); + NEXT(1, 1) + continue; + } else if (c == 0x203e) { /* OVERLINE */ + WRITE1(0x7e); + NEXT(1, 1) + continue; + } #endif - else - return 1; + else + return 1; - if (code & 0x8000) { - /* JIS X 0212 */ - WRITE3(0x8f, code >> 8, (code & 0xFF) | 0x80) - NEXT(1, 3) - } else { - /* JIS X 0208 */ - WRITE2((code >> 8) | 0x80, (code & 0xFF) | 0x80) - NEXT(1, 2) - } - } + if (code & 0x8000) { + /* JIS X 0212 */ + WRITE3(0x8f, code >> 8, (code & 0xFF) | 0x80) + NEXT(1, 3) + } else { + /* JIS X 0208 */ + WRITE2((code >> 8) | 0x80, (code & 0xFF) | 0x80) + NEXT(1, 2) + } + } - return 0; + return 0; } DECODER(euc_jp) { - while (inleft > 0) { - unsigned char c = IN1; + while (inleft > 0) { + unsigned char c = IN1; - REQUIRE_OUTBUF(1) + REQUIRE_OUTBUF(1) - if (c < 0x80) { - OUT1(c) - NEXT(1, 1) - continue; - } - - if (c == 0x8e) { - /* JIS X 0201 half-width katakana */ - unsigned char c2; - - REQUIRE_INBUF(2) - c2 = IN2; - if (c2 >= 0xa1 && c2 <= 0xdf) { - OUT1(0xfec0 + c2) - NEXT(2, 1) - } - else - return 2; - } - else if (c == 0x8f) { - unsigned char c2, c3; - - REQUIRE_INBUF(3) - c2 = IN2; - c3 = IN3; - /* JIS X 0212 */ - TRYMAP_DEC(jisx0212, **outbuf, c2 ^ 0x80, c3 ^ 0x80) { - NEXT(3, 1) - } - else - return 3; - } - else { - unsigned char c2; - - REQUIRE_INBUF(2) - c2 = IN2; - /* JIS X 0208 */ + if (c < 0x80) { + OUT1(c) + NEXT(1, 1) + continue; + } + + if (c == 0x8e) { + /* JIS X 0201 half-width katakana */ + unsigned char c2; + + REQUIRE_INBUF(2) + c2 = IN2; + if (c2 >= 0xa1 && c2 <= 0xdf) { + OUT1(0xfec0 + c2) + NEXT(2, 1) + } + else + return 2; + } + else if (c == 0x8f) { + unsigned char c2, c3; + + REQUIRE_INBUF(3) + c2 = IN2; + c3 = IN3; + /* JIS X 0212 */ + TRYMAP_DEC(jisx0212, **outbuf, c2 ^ 0x80, c3 ^ 0x80) { + NEXT(3, 1) + } + else + return 3; + } + else { + unsigned char c2; + + REQUIRE_INBUF(2) + c2 = IN2; + /* JIS X 0208 */ #ifndef STRICT_BUILD - if (c == 0xa1 && c2 == 0xc0) - /* FULL-WIDTH REVERSE SOLIDUS */ - **outbuf = 0xff3c; - else + if (c == 0xa1 && c2 == 0xc0) + /* FULL-WIDTH REVERSE SOLIDUS */ + **outbuf = 0xff3c; + else #endif - TRYMAP_DEC(jisx0208, **outbuf, - c ^ 0x80, c2 ^ 0x80) ; - else return 2; - NEXT(2, 1) - } - } + TRYMAP_DEC(jisx0208, **outbuf, + c ^ 0x80, c2 ^ 0x80) ; + else return 2; + NEXT(2, 1) + } + } - return 0; + return 0; } @@ -432,105 +432,105 @@ ENCODER(shift_jis) { - while (inleft > 0) { - Py_UNICODE c = IN1; - DBCHAR code; - unsigned char c1, c2; + while (inleft > 0) { + Py_UNICODE c = IN1; + DBCHAR code; + unsigned char c1, c2; #ifdef STRICT_BUILD - JISX0201_R_ENCODE(c, code) + JISX0201_R_ENCODE(c, code) #else - if (c < 0x80) code = c; - else if (c == 0x00a5) code = 0x5c; /* YEN SIGN */ - else if (c == 0x203e) code = 0x7e; /* OVERLINE */ + if (c < 0x80) code = c; + else if (c == 0x00a5) code = 0x5c; /* YEN SIGN */ + else if (c == 0x203e) code = 0x7e; /* OVERLINE */ #endif - else JISX0201_K_ENCODE(c, code) - else UCS4INVALID(c) - else code = NOCHAR; - - if (code < 0x80 || (code >= 0xa1 && code <= 0xdf)) { - REQUIRE_OUTBUF(1) - - OUT1((unsigned char)code) - NEXT(1, 1) - continue; - } + else JISX0201_K_ENCODE(c, code) + else UCS4INVALID(c) + else code = NOCHAR; + + if (code < 0x80 || (code >= 0xa1 && code <= 0xdf)) { + REQUIRE_OUTBUF(1) + + OUT1((unsigned char)code) + NEXT(1, 1) + continue; + } - REQUIRE_OUTBUF(2) + REQUIRE_OUTBUF(2) - if (code == NOCHAR) { - TRYMAP_ENC(jisxcommon, code, c); + if (code == NOCHAR) { + TRYMAP_ENC(jisxcommon, code, c); #ifndef STRICT_BUILD - else if (c == 0xff3c) - code = 0x2140; /* FULL-WIDTH REVERSE SOLIDUS */ + else if (c == 0xff3c) + code = 0x2140; /* FULL-WIDTH REVERSE SOLIDUS */ #endif - else - return 1; + else + return 1; - if (code & 0x8000) /* MSB set: JIS X 0212 */ - return 1; - } - - c1 = code >> 8; - c2 = code & 0xff; - c2 = (((c1 - 0x21) & 1) ? 0x5e : 0) + (c2 - 0x21); - c1 = (c1 - 0x21) >> 1; - OUT1(c1 < 0x1f ? c1 + 0x81 : c1 + 0xc1) - OUT2(c2 < 0x3f ? c2 + 0x40 : c2 + 0x41) - NEXT(1, 2) - } + if (code & 0x8000) /* MSB set: JIS X 0212 */ + return 1; + } + + c1 = code >> 8; + c2 = code & 0xff; + c2 = (((c1 - 0x21) & 1) ? 0x5e : 0) + (c2 - 0x21); + c1 = (c1 - 0x21) >> 1; + OUT1(c1 < 0x1f ? c1 + 0x81 : c1 + 0xc1) + OUT2(c2 < 0x3f ? c2 + 0x40 : c2 + 0x41) + NEXT(1, 2) + } - return 0; + return 0; } DECODER(shift_jis) { - while (inleft > 0) { - unsigned char c = IN1; + while (inleft > 0) { + unsigned char c = IN1; - REQUIRE_OUTBUF(1) + REQUIRE_OUTBUF(1) #ifdef STRICT_BUILD - JISX0201_R_DECODE(c, **outbuf) + JISX0201_R_DECODE(c, **outbuf) #else - if (c < 0x80) **outbuf = c; + if (c < 0x80) **outbuf = c; #endif - else JISX0201_K_DECODE(c, **outbuf) - else if ((c >= 0x81 && c <= 0x9f) || (c >= 0xe0 && c <= 0xea)){ - unsigned char c1, c2; - - REQUIRE_INBUF(2) - c2 = IN2; - if (c2 < 0x40 || (c2 > 0x7e && c2 < 0x80) || c2 > 0xfc) - return 2; - - c1 = (c < 0xe0 ? c - 0x81 : c - 0xc1); - c2 = (c2 < 0x80 ? c2 - 0x40 : c2 - 0x41); - c1 = (2 * c1 + (c2 < 0x5e ? 0 : 1) + 0x21); - c2 = (c2 < 0x5e ? c2 : c2 - 0x5e) + 0x21; + else JISX0201_K_DECODE(c, **outbuf) + else if ((c >= 0x81 && c <= 0x9f) || (c >= 0xe0 && c <= 0xea)){ + unsigned char c1, c2; + + REQUIRE_INBUF(2) + c2 = IN2; + if (c2 < 0x40 || (c2 > 0x7e && c2 < 0x80) || c2 > 0xfc) + return 2; + + c1 = (c < 0xe0 ? c - 0x81 : c - 0xc1); + c2 = (c2 < 0x80 ? c2 - 0x40 : c2 - 0x41); + c1 = (2 * c1 + (c2 < 0x5e ? 0 : 1) + 0x21); + c2 = (c2 < 0x5e ? c2 : c2 - 0x5e) + 0x21; #ifndef STRICT_BUILD - if (c1 == 0x21 && c2 == 0x40) { - /* FULL-WIDTH REVERSE SOLIDUS */ - OUT1(0xff3c) - NEXT(2, 1) - continue; - } + if (c1 == 0x21 && c2 == 0x40) { + /* FULL-WIDTH REVERSE SOLIDUS */ + OUT1(0xff3c) + NEXT(2, 1) + continue; + } #endif - TRYMAP_DEC(jisx0208, **outbuf, c1, c2) { - NEXT(2, 1) - continue; - } - else - return 2; - } - else - return 2; + TRYMAP_DEC(jisx0208, **outbuf, c1, c2) { + NEXT(2, 1) + continue; + } + else + return 2; + } + else + return 2; - NEXT(1, 1) /* JIS X 0201 */ - } + NEXT(1, 1) /* JIS X 0201 */ + } - return 0; + return 0; } @@ -540,167 +540,167 @@ ENCODER(shift_jis_2004) { - while (inleft > 0) { - ucs4_t c = IN1; - DBCHAR code = NOCHAR; - int c1, c2; - Py_ssize_t insize; - - JISX0201_ENCODE(c, code) - else DECODE_SURROGATE(c) - - if (code < 0x80 || (code >= 0xa1 && code <= 0xdf)) { - WRITE1((unsigned char)code) - NEXT(1, 1) - continue; - } - - REQUIRE_OUTBUF(2) - insize = GET_INSIZE(c); - - if (code == NOCHAR) { - if (c <= 0xffff) { - EMULATE_JISX0213_2000_ENCODE_BMP(code, c) - else TRYMAP_ENC(jisx0213_bmp, code, c) { - if (code == MULTIC) { - if (inleft < 2) { - if (flags & MBENC_FLUSH) { - code = find_pairencmap - ((ucs2_t)c, 0, - jisx0213_pair_encmap, - JISX0213_ENCPAIRS); - if (code == DBCINV) - return 1; - } - else - return MBERR_TOOFEW; - } - else { - code = find_pairencmap( - (ucs2_t)c, IN2, - jisx0213_pair_encmap, - JISX0213_ENCPAIRS); - if (code == DBCINV) { - code = find_pairencmap( - (ucs2_t)c, 0, - jisx0213_pair_encmap, - JISX0213_ENCPAIRS); - if (code == DBCINV) - return 1; - } - else - insize = 2; - } - } - } - else TRYMAP_ENC(jisxcommon, code, c) { - /* abandon JIS X 0212 codes */ - if (code & 0x8000) - return 1; - } - else return 1; - } - else if (c >> 16 == EMPBASE >> 16) { - EMULATE_JISX0213_2000_ENCODE_EMP(code, c) - else TRYMAP_ENC(jisx0213_emp, code, c&0xffff); - else return insize; - } - else - return insize; - } - - c1 = code >> 8; - c2 = (code & 0xff) - 0x21; - - if (c1 & 0x80) { /* Plane 2 */ - if (c1 >= 0xee) c1 -= 0x87; - else if (c1 >= 0xac || c1 == 0xa8) c1 -= 0x49; - else c1 -= 0x43; - } - else /* Plane 1 */ - c1 -= 0x21; - - if (c1 & 1) c2 += 0x5e; - c1 >>= 1; - OUT1(c1 + (c1 < 0x1f ? 0x81 : 0xc1)) - OUT2(c2 + (c2 < 0x3f ? 0x40 : 0x41)) + while (inleft > 0) { + ucs4_t c = IN1; + DBCHAR code = NOCHAR; + int c1, c2; + Py_ssize_t insize; + + JISX0201_ENCODE(c, code) + else DECODE_SURROGATE(c) + + if (code < 0x80 || (code >= 0xa1 && code <= 0xdf)) { + WRITE1((unsigned char)code) + NEXT(1, 1) + continue; + } + + REQUIRE_OUTBUF(2) + insize = GET_INSIZE(c); + + if (code == NOCHAR) { + if (c <= 0xffff) { + EMULATE_JISX0213_2000_ENCODE_BMP(code, c) + else TRYMAP_ENC(jisx0213_bmp, code, c) { + if (code == MULTIC) { + if (inleft < 2) { + if (flags & MBENC_FLUSH) { + code = find_pairencmap + ((ucs2_t)c, 0, + jisx0213_pair_encmap, + JISX0213_ENCPAIRS); + if (code == DBCINV) + return 1; + } + else + return MBERR_TOOFEW; + } + else { + code = find_pairencmap( + (ucs2_t)c, IN2, + jisx0213_pair_encmap, + JISX0213_ENCPAIRS); + if (code == DBCINV) { + code = find_pairencmap( + (ucs2_t)c, 0, + jisx0213_pair_encmap, + JISX0213_ENCPAIRS); + if (code == DBCINV) + return 1; + } + else + insize = 2; + } + } + } + else TRYMAP_ENC(jisxcommon, code, c) { + /* abandon JIS X 0212 codes */ + if (code & 0x8000) + return 1; + } + else return 1; + } + else if (c >> 16 == EMPBASE >> 16) { + EMULATE_JISX0213_2000_ENCODE_EMP(code, c) + else TRYMAP_ENC(jisx0213_emp, code, c&0xffff); + else return insize; + } + else + return insize; + } + + c1 = code >> 8; + c2 = (code & 0xff) - 0x21; + + if (c1 & 0x80) { /* Plane 2 */ + if (c1 >= 0xee) c1 -= 0x87; + else if (c1 >= 0xac || c1 == 0xa8) c1 -= 0x49; + else c1 -= 0x43; + } + else /* Plane 1 */ + c1 -= 0x21; + + if (c1 & 1) c2 += 0x5e; + c1 >>= 1; + OUT1(c1 + (c1 < 0x1f ? 0x81 : 0xc1)) + OUT2(c2 + (c2 < 0x3f ? 0x40 : 0x41)) - NEXT(insize, 2) - } + NEXT(insize, 2) + } - return 0; + return 0; } DECODER(shift_jis_2004) { - while (inleft > 0) { - unsigned char c = IN1; + while (inleft > 0) { + unsigned char c = IN1; - REQUIRE_OUTBUF(1) - JISX0201_DECODE(c, **outbuf) - else if ((c >= 0x81 && c <= 0x9f) || (c >= 0xe0 && c <= 0xfc)){ - unsigned char c1, c2; - ucs4_t code; - - REQUIRE_INBUF(2) - c2 = IN2; - if (c2 < 0x40 || (c2 > 0x7e && c2 < 0x80) || c2 > 0xfc) - return 2; - - c1 = (c < 0xe0 ? c - 0x81 : c - 0xc1); - c2 = (c2 < 0x80 ? c2 - 0x40 : c2 - 0x41); - c1 = (2 * c1 + (c2 < 0x5e ? 0 : 1)); - c2 = (c2 < 0x5e ? c2 : c2 - 0x5e) + 0x21; - - if (c1 < 0x5e) { /* Plane 1 */ - c1 += 0x21; - EMULATE_JISX0213_2000_DECODE_PLANE1(**outbuf, - c1, c2) - else TRYMAP_DEC(jisx0208, **outbuf, c1, c2) { - NEXT_OUT(1) - } - else TRYMAP_DEC(jisx0213_1_bmp, **outbuf, - c1, c2) { - NEXT_OUT(1) - } - else TRYMAP_DEC(jisx0213_1_emp, code, c1, c2) { - WRITEUCS4(EMPBASE | code) - } - else TRYMAP_DEC(jisx0213_pair, code, c1, c2) { - WRITE2(code >> 16, code & 0xffff) - NEXT_OUT(2) - } - else - return 2; - NEXT_IN(2) - } - else { /* Plane 2 */ - if (c1 >= 0x67) c1 += 0x07; - else if (c1 >= 0x63 || c1 == 0x5f) c1 -= 0x37; - else c1 -= 0x3d; - - EMULATE_JISX0213_2000_DECODE_PLANE2(**outbuf, - c1, c2) - else TRYMAP_DEC(jisx0213_2_bmp, **outbuf, - c1, c2) ; - else TRYMAP_DEC(jisx0213_2_emp, code, c1, c2) { - WRITEUCS4(EMPBASE | code) - NEXT_IN(2) - continue; - } - else - return 2; - NEXT(2, 1) - } - continue; - } - else - return 2; + REQUIRE_OUTBUF(1) + JISX0201_DECODE(c, **outbuf) + else if ((c >= 0x81 && c <= 0x9f) || (c >= 0xe0 && c <= 0xfc)){ + unsigned char c1, c2; + ucs4_t code; + + REQUIRE_INBUF(2) + c2 = IN2; + if (c2 < 0x40 || (c2 > 0x7e && c2 < 0x80) || c2 > 0xfc) + return 2; + + c1 = (c < 0xe0 ? c - 0x81 : c - 0xc1); + c2 = (c2 < 0x80 ? c2 - 0x40 : c2 - 0x41); + c1 = (2 * c1 + (c2 < 0x5e ? 0 : 1)); + c2 = (c2 < 0x5e ? c2 : c2 - 0x5e) + 0x21; + + if (c1 < 0x5e) { /* Plane 1 */ + c1 += 0x21; + EMULATE_JISX0213_2000_DECODE_PLANE1(**outbuf, + c1, c2) + else TRYMAP_DEC(jisx0208, **outbuf, c1, c2) { + NEXT_OUT(1) + } + else TRYMAP_DEC(jisx0213_1_bmp, **outbuf, + c1, c2) { + NEXT_OUT(1) + } + else TRYMAP_DEC(jisx0213_1_emp, code, c1, c2) { + WRITEUCS4(EMPBASE | code) + } + else TRYMAP_DEC(jisx0213_pair, code, c1, c2) { + WRITE2(code >> 16, code & 0xffff) + NEXT_OUT(2) + } + else + return 2; + NEXT_IN(2) + } + else { /* Plane 2 */ + if (c1 >= 0x67) c1 += 0x07; + else if (c1 >= 0x63 || c1 == 0x5f) c1 -= 0x37; + else c1 -= 0x3d; + + EMULATE_JISX0213_2000_DECODE_PLANE2(**outbuf, + c1, c2) + else TRYMAP_DEC(jisx0213_2_bmp, **outbuf, + c1, c2) ; + else TRYMAP_DEC(jisx0213_2_emp, code, c1, c2) { + WRITEUCS4(EMPBASE | code) + NEXT_IN(2) + continue; + } + else + return 2; + NEXT(2, 1) + } + continue; + } + else + return 2; - NEXT(1, 1) /* JIS X 0201 */ - } + NEXT(1, 1) /* JIS X 0201 */ + } - return 0; + return 0; } Modified: python/branches/py3k-jit/Modules/cjkcodecs/_codecs_kr.c ============================================================================== --- python/branches/py3k-jit/Modules/cjkcodecs/_codecs_kr.c (original) +++ python/branches/py3k-jit/Modules/cjkcodecs/_codecs_kr.c Mon May 10 23:55:43 2010 @@ -11,151 +11,151 @@ * EUC-KR codec */ -#define EUCKR_JAMO_FIRSTBYTE 0xA4 -#define EUCKR_JAMO_FILLER 0xD4 +#define EUCKR_JAMO_FIRSTBYTE 0xA4 +#define EUCKR_JAMO_FILLER 0xD4 static const unsigned char u2cgk_choseong[19] = { - 0xa1, 0xa2, 0xa4, 0xa7, 0xa8, 0xa9, 0xb1, 0xb2, - 0xb3, 0xb5, 0xb6, 0xb7, 0xb8, 0xb9, 0xba, 0xbb, - 0xbc, 0xbd, 0xbe + 0xa1, 0xa2, 0xa4, 0xa7, 0xa8, 0xa9, 0xb1, 0xb2, + 0xb3, 0xb5, 0xb6, 0xb7, 0xb8, 0xb9, 0xba, 0xbb, + 0xbc, 0xbd, 0xbe }; static const unsigned char u2cgk_jungseong[21] = { - 0xbf, 0xc0, 0xc1, 0xc2, 0xc3, 0xc4, 0xc5, 0xc6, - 0xc7, 0xc8, 0xc9, 0xca, 0xcb, 0xcc, 0xcd, 0xce, - 0xcf, 0xd0, 0xd1, 0xd2, 0xd3 + 0xbf, 0xc0, 0xc1, 0xc2, 0xc3, 0xc4, 0xc5, 0xc6, + 0xc7, 0xc8, 0xc9, 0xca, 0xcb, 0xcc, 0xcd, 0xce, + 0xcf, 0xd0, 0xd1, 0xd2, 0xd3 }; static const unsigned char u2cgk_jongseong[28] = { - 0xd4, 0xa1, 0xa2, 0xa3, 0xa4, 0xa5, 0xa6, 0xa7, - 0xa9, 0xaa, 0xab, 0xac, 0xad, 0xae, 0xaf, 0xb0, - 0xb1, 0xb2, 0xb4, 0xb5, 0xb6, 0xb7, 0xb8, 0xba, - 0xbb, 0xbc, 0xbd, 0xbe + 0xd4, 0xa1, 0xa2, 0xa3, 0xa4, 0xa5, 0xa6, 0xa7, + 0xa9, 0xaa, 0xab, 0xac, 0xad, 0xae, 0xaf, 0xb0, + 0xb1, 0xb2, 0xb4, 0xb5, 0xb6, 0xb7, 0xb8, 0xba, + 0xbb, 0xbc, 0xbd, 0xbe }; ENCODER(euc_kr) { - while (inleft > 0) { - Py_UNICODE c = IN1; - DBCHAR code; - - if (c < 0x80) { - WRITE1((unsigned char)c) - NEXT(1, 1) - continue; - } - UCS4INVALID(c) - - REQUIRE_OUTBUF(2) - TRYMAP_ENC(cp949, code, c); - else return 1; - - if ((code & 0x8000) == 0) { - /* KS X 1001 coded character */ - OUT1((code >> 8) | 0x80) - OUT2((code & 0xFF) | 0x80) - NEXT(1, 2) - } - else { /* Mapping is found in CP949 extension, - * but we encode it in KS X 1001:1998 Annex 3, - * make-up sequence for EUC-KR. */ - - REQUIRE_OUTBUF(8) - - /* syllable composition precedence */ - OUT1(EUCKR_JAMO_FIRSTBYTE) - OUT2(EUCKR_JAMO_FILLER) - - /* All codepoints in CP949 extension are in unicode - * Hangul Syllable area. */ - assert(0xac00 <= c && c <= 0xd7a3); - c -= 0xac00; - - OUT3(EUCKR_JAMO_FIRSTBYTE) - OUT4(u2cgk_choseong[c / 588]) - NEXT_OUT(4) - - OUT1(EUCKR_JAMO_FIRSTBYTE) - OUT2(u2cgk_jungseong[(c / 28) % 21]) - OUT3(EUCKR_JAMO_FIRSTBYTE) - OUT4(u2cgk_jongseong[c % 28]) - NEXT(1, 4) - } - } + while (inleft > 0) { + Py_UNICODE c = IN1; + DBCHAR code; + + if (c < 0x80) { + WRITE1((unsigned char)c) + NEXT(1, 1) + continue; + } + UCS4INVALID(c) + + REQUIRE_OUTBUF(2) + TRYMAP_ENC(cp949, code, c); + else return 1; + + if ((code & 0x8000) == 0) { + /* KS X 1001 coded character */ + OUT1((code >> 8) | 0x80) + OUT2((code & 0xFF) | 0x80) + NEXT(1, 2) + } + else { /* Mapping is found in CP949 extension, + * but we encode it in KS X 1001:1998 Annex 3, + * make-up sequence for EUC-KR. */ + + REQUIRE_OUTBUF(8) + + /* syllable composition precedence */ + OUT1(EUCKR_JAMO_FIRSTBYTE) + OUT2(EUCKR_JAMO_FILLER) + + /* All codepoints in CP949 extension are in unicode + * Hangul Syllable area. */ + assert(0xac00 <= c && c <= 0xd7a3); + c -= 0xac00; + + OUT3(EUCKR_JAMO_FIRSTBYTE) + OUT4(u2cgk_choseong[c / 588]) + NEXT_OUT(4) + + OUT1(EUCKR_JAMO_FIRSTBYTE) + OUT2(u2cgk_jungseong[(c / 28) % 21]) + OUT3(EUCKR_JAMO_FIRSTBYTE) + OUT4(u2cgk_jongseong[c % 28]) + NEXT(1, 4) + } + } - return 0; + return 0; } -#define NONE 127 +#define NONE 127 static const unsigned char cgk2u_choseong[] = { /* [A1, BE] */ - 0, 1, NONE, 2, NONE, NONE, 3, 4, - 5, NONE, NONE, NONE, NONE, NONE, NONE, NONE, - 6, 7, 8, NONE, 9, 10, 11, 12, - 13, 14, 15, 16, 17, 18 + 0, 1, NONE, 2, NONE, NONE, 3, 4, + 5, NONE, NONE, NONE, NONE, NONE, NONE, NONE, + 6, 7, 8, NONE, 9, 10, 11, 12, + 13, 14, 15, 16, 17, 18 }; static const unsigned char cgk2u_jongseong[] = { /* [A1, BE] */ - 1, 2, 3, 4, 5, 6, 7, NONE, - 8, 9, 10, 11, 12, 13, 14, 15, - 16, 17, NONE, 18, 19, 20, 21, 22, - NONE, 23, 24, 25, 26, 27 + 1, 2, 3, 4, 5, 6, 7, NONE, + 8, 9, 10, 11, 12, 13, 14, 15, + 16, 17, NONE, 18, 19, 20, 21, 22, + NONE, 23, 24, 25, 26, 27 }; DECODER(euc_kr) { - while (inleft > 0) { - unsigned char c = IN1; + while (inleft > 0) { + unsigned char c = IN1; - REQUIRE_OUTBUF(1) + REQUIRE_OUTBUF(1) - if (c < 0x80) { - OUT1(c) - NEXT(1, 1) - continue; - } - - REQUIRE_INBUF(2) - - if (c == EUCKR_JAMO_FIRSTBYTE && - IN2 == EUCKR_JAMO_FILLER) { - /* KS X 1001:1998 Annex 3 make-up sequence */ - DBCHAR cho, jung, jong; - - REQUIRE_INBUF(8) - if ((*inbuf)[2] != EUCKR_JAMO_FIRSTBYTE || - (*inbuf)[4] != EUCKR_JAMO_FIRSTBYTE || - (*inbuf)[6] != EUCKR_JAMO_FIRSTBYTE) - return 8; - - c = (*inbuf)[3]; - if (0xa1 <= c && c <= 0xbe) - cho = cgk2u_choseong[c - 0xa1]; - else - cho = NONE; - - c = (*inbuf)[5]; - jung = (0xbf <= c && c <= 0xd3) ? c - 0xbf : NONE; - - c = (*inbuf)[7]; - if (c == EUCKR_JAMO_FILLER) - jong = 0; - else if (0xa1 <= c && c <= 0xbe) - jong = cgk2u_jongseong[c - 0xa1]; - else - jong = NONE; - - if (cho == NONE || jung == NONE || jong == NONE) - return 8; - - OUT1(0xac00 + cho*588 + jung*28 + jong); - NEXT(8, 1) - } - else TRYMAP_DEC(ksx1001, **outbuf, c ^ 0x80, IN2 ^ 0x80) { - NEXT(2, 1) - } - else - return 2; - } + if (c < 0x80) { + OUT1(c) + NEXT(1, 1) + continue; + } + + REQUIRE_INBUF(2) + + if (c == EUCKR_JAMO_FIRSTBYTE && + IN2 == EUCKR_JAMO_FILLER) { + /* KS X 1001:1998 Annex 3 make-up sequence */ + DBCHAR cho, jung, jong; + + REQUIRE_INBUF(8) + if ((*inbuf)[2] != EUCKR_JAMO_FIRSTBYTE || + (*inbuf)[4] != EUCKR_JAMO_FIRSTBYTE || + (*inbuf)[6] != EUCKR_JAMO_FIRSTBYTE) + return 8; + + c = (*inbuf)[3]; + if (0xa1 <= c && c <= 0xbe) + cho = cgk2u_choseong[c - 0xa1]; + else + cho = NONE; + + c = (*inbuf)[5]; + jung = (0xbf <= c && c <= 0xd3) ? c - 0xbf : NONE; + + c = (*inbuf)[7]; + if (c == EUCKR_JAMO_FILLER) + jong = 0; + else if (0xa1 <= c && c <= 0xbe) + jong = cgk2u_jongseong[c - 0xa1]; + else + jong = NONE; + + if (cho == NONE || jung == NONE || jong == NONE) + return 8; + + OUT1(0xac00 + cho*588 + jung*28 + jong); + NEXT(8, 1) + } + else TRYMAP_DEC(ksx1001, **outbuf, c ^ 0x80, IN2 ^ 0x80) { + NEXT(2, 1) + } + else + return 2; + } - return 0; + return 0; } #undef NONE @@ -166,54 +166,54 @@ ENCODER(cp949) { - while (inleft > 0) { - Py_UNICODE c = IN1; - DBCHAR code; - - if (c < 0x80) { - WRITE1((unsigned char)c) - NEXT(1, 1) - continue; - } - UCS4INVALID(c) - - REQUIRE_OUTBUF(2) - TRYMAP_ENC(cp949, code, c); - else return 1; - - OUT1((code >> 8) | 0x80) - if (code & 0x8000) - OUT2(code & 0xFF) /* MSB set: CP949 */ - else - OUT2((code & 0xFF) | 0x80) /* MSB unset: ks x 1001 */ - NEXT(1, 2) - } + while (inleft > 0) { + Py_UNICODE c = IN1; + DBCHAR code; + + if (c < 0x80) { + WRITE1((unsigned char)c) + NEXT(1, 1) + continue; + } + UCS4INVALID(c) + + REQUIRE_OUTBUF(2) + TRYMAP_ENC(cp949, code, c); + else return 1; + + OUT1((code >> 8) | 0x80) + if (code & 0x8000) + OUT2(code & 0xFF) /* MSB set: CP949 */ + else + OUT2((code & 0xFF) | 0x80) /* MSB unset: ks x 1001 */ + NEXT(1, 2) + } - return 0; + return 0; } DECODER(cp949) { - while (inleft > 0) { - unsigned char c = IN1; + while (inleft > 0) { + unsigned char c = IN1; - REQUIRE_OUTBUF(1) + REQUIRE_OUTBUF(1) - if (c < 0x80) { - OUT1(c) - NEXT(1, 1) - continue; - } - - REQUIRE_INBUF(2) - TRYMAP_DEC(ksx1001, **outbuf, c ^ 0x80, IN2 ^ 0x80); - else TRYMAP_DEC(cp949ext, **outbuf, c, IN2); - else return 2; + if (c < 0x80) { + OUT1(c) + NEXT(1, 1) + continue; + } + + REQUIRE_INBUF(2) + TRYMAP_DEC(ksx1001, **outbuf, c ^ 0x80, IN2 ^ 0x80); + else TRYMAP_DEC(cp949ext, **outbuf, c, IN2); + else return 2; - NEXT(2, 1) - } + NEXT(2, 1) + } - return 0; + return 0; } @@ -250,58 +250,58 @@ ENCODER(johab) { - while (inleft > 0) { - Py_UNICODE c = IN1; - DBCHAR code; - - if (c < 0x80) { - WRITE1((unsigned char)c) - NEXT(1, 1) - continue; - } - UCS4INVALID(c) - - REQUIRE_OUTBUF(2) - - if (c >= 0xac00 && c <= 0xd7a3) { - c -= 0xac00; - code = 0x8000 | - (u2johabidx_choseong[c / 588] << 10) | - (u2johabidx_jungseong[(c / 28) % 21] << 5) | - u2johabidx_jongseong[c % 28]; - } - else if (c >= 0x3131 && c <= 0x3163) - code = u2johabjamo[c - 0x3131]; - else TRYMAP_ENC(cp949, code, c) { - unsigned char c1, c2, t2; - unsigned short t1; - - assert((code & 0x8000) == 0); - c1 = code >> 8; - c2 = code & 0xff; - if (((c1 >= 0x21 && c1 <= 0x2c) || - (c1 >= 0x4a && c1 <= 0x7d)) && - (c2 >= 0x21 && c2 <= 0x7e)) { - t1 = (c1 < 0x4a ? (c1 - 0x21 + 0x1b2) : - (c1 - 0x21 + 0x197)); - t2 = ((t1 & 1) ? 0x5e : 0) + (c2 - 0x21); - OUT1(t1 >> 1) - OUT2(t2 < 0x4e ? t2 + 0x31 : t2 + 0x43) - NEXT(1, 2) - continue; - } - else - return 1; - } - else - return 1; - - OUT1(code >> 8) - OUT2(code & 0xff) - NEXT(1, 2) - } + while (inleft > 0) { + Py_UNICODE c = IN1; + DBCHAR code; + + if (c < 0x80) { + WRITE1((unsigned char)c) + NEXT(1, 1) + continue; + } + UCS4INVALID(c) + + REQUIRE_OUTBUF(2) + + if (c >= 0xac00 && c <= 0xd7a3) { + c -= 0xac00; + code = 0x8000 | + (u2johabidx_choseong[c / 588] << 10) | + (u2johabidx_jungseong[(c / 28) % 21] << 5) | + u2johabidx_jongseong[c % 28]; + } + else if (c >= 0x3131 && c <= 0x3163) + code = u2johabjamo[c - 0x3131]; + else TRYMAP_ENC(cp949, code, c) { + unsigned char c1, c2, t2; + unsigned short t1; + + assert((code & 0x8000) == 0); + c1 = code >> 8; + c2 = code & 0xff; + if (((c1 >= 0x21 && c1 <= 0x2c) || + (c1 >= 0x4a && c1 <= 0x7d)) && + (c2 >= 0x21 && c2 <= 0x7e)) { + t1 = (c1 < 0x4a ? (c1 - 0x21 + 0x1b2) : + (c1 - 0x21 + 0x197)); + t2 = ((t1 & 1) ? 0x5e : 0) + (c2 - 0x21); + OUT1(t1 >> 1) + OUT2(t2 < 0x4e ? t2 + 0x31 : t2 + 0x43) + NEXT(1, 2) + continue; + } + else + return 1; + } + else + return 1; + + OUT1(code >> 8) + OUT2(code & 0xff) + NEXT(1, 2) + } - return 0; + return 0; } #define FILL 0xfd @@ -347,91 +347,91 @@ DECODER(johab) { - while (inleft > 0) { - unsigned char c = IN1, c2; + while (inleft > 0) { + unsigned char c = IN1, c2; - REQUIRE_OUTBUF(1) + REQUIRE_OUTBUF(1) - if (c < 0x80) { - OUT1(c) - NEXT(1, 1) - continue; - } - - REQUIRE_INBUF(2) - c2 = IN2; - - if (c < 0xd8) { - /* johab hangul */ - unsigned char c_cho, c_jung, c_jong; - unsigned char i_cho, i_jung, i_jong; - - c_cho = (c >> 2) & 0x1f; - c_jung = ((c << 3) | c2 >> 5) & 0x1f; - c_jong = c2 & 0x1f; - - i_cho = johabidx_choseong[c_cho]; - i_jung = johabidx_jungseong[c_jung]; - i_jong = johabidx_jongseong[c_jong]; - - if (i_cho == NONE || i_jung == NONE || i_jong == NONE) - return 2; - - /* we don't use U+1100 hangul jamo yet. */ - if (i_cho == FILL) { - if (i_jung == FILL) { - if (i_jong == FILL) - OUT1(0x3000) - else - OUT1(0x3100 | - johabjamo_jongseong[c_jong]) - } - else { - if (i_jong == FILL) - OUT1(0x3100 | - johabjamo_jungseong[c_jung]) - else - return 2; - } - } else { - if (i_jung == FILL) { - if (i_jong == FILL) - OUT1(0x3100 | - johabjamo_choseong[c_cho]) - else - return 2; - } - else - OUT1(0xac00 + - i_cho * 588 + - i_jung * 28 + - (i_jong == FILL ? 0 : i_jong)) - } - NEXT(2, 1) - } else { - /* KS X 1001 except hangul jamos and syllables */ - if (c == 0xdf || c > 0xf9 || - c2 < 0x31 || (c2 >= 0x80 && c2 < 0x91) || - (c2 & 0x7f) == 0x7f || - (c == 0xda && (c2 >= 0xa1 && c2 <= 0xd3))) - return 2; - else { - unsigned char t1, t2; - - t1 = (c < 0xe0 ? 2 * (c - 0xd9) : - 2 * c - 0x197); - t2 = (c2 < 0x91 ? c2 - 0x31 : c2 - 0x43); - t1 = t1 + (t2 < 0x5e ? 0 : 1) + 0x21; - t2 = (t2 < 0x5e ? t2 : t2 - 0x5e) + 0x21; - - TRYMAP_DEC(ksx1001, **outbuf, t1, t2); - else return 2; - NEXT(2, 1) - } - } - } + if (c < 0x80) { + OUT1(c) + NEXT(1, 1) + continue; + } + + REQUIRE_INBUF(2) + c2 = IN2; + + if (c < 0xd8) { + /* johab hangul */ + unsigned char c_cho, c_jung, c_jong; + unsigned char i_cho, i_jung, i_jong; + + c_cho = (c >> 2) & 0x1f; + c_jung = ((c << 3) | c2 >> 5) & 0x1f; + c_jong = c2 & 0x1f; + + i_cho = johabidx_choseong[c_cho]; + i_jung = johabidx_jungseong[c_jung]; + i_jong = johabidx_jongseong[c_jong]; + + if (i_cho == NONE || i_jung == NONE || i_jong == NONE) + return 2; + + /* we don't use U+1100 hangul jamo yet. */ + if (i_cho == FILL) { + if (i_jung == FILL) { + if (i_jong == FILL) + OUT1(0x3000) + else + OUT1(0x3100 | + johabjamo_jongseong[c_jong]) + } + else { + if (i_jong == FILL) + OUT1(0x3100 | + johabjamo_jungseong[c_jung]) + else + return 2; + } + } else { + if (i_jung == FILL) { + if (i_jong == FILL) + OUT1(0x3100 | + johabjamo_choseong[c_cho]) + else + return 2; + } + else + OUT1(0xac00 + + i_cho * 588 + + i_jung * 28 + + (i_jong == FILL ? 0 : i_jong)) + } + NEXT(2, 1) + } else { + /* KS X 1001 except hangul jamos and syllables */ + if (c == 0xdf || c > 0xf9 || + c2 < 0x31 || (c2 >= 0x80 && c2 < 0x91) || + (c2 & 0x7f) == 0x7f || + (c == 0xda && (c2 >= 0xa1 && c2 <= 0xd3))) + return 2; + else { + unsigned char t1, t2; + + t1 = (c < 0xe0 ? 2 * (c - 0xd9) : + 2 * c - 0x197); + t2 = (c2 < 0x91 ? c2 - 0x31 : c2 - 0x43); + t1 = t1 + (t2 < 0x5e ? 0 : 1) + 0x21; + t2 = (t2 < 0x5e ? t2 : t2 - 0x5e) + 0x21; + + TRYMAP_DEC(ksx1001, **outbuf, t1, t2); + else return 2; + NEXT(2, 1) + } + } + } - return 0; + return 0; } #undef NONE #undef FILL Modified: python/branches/py3k-jit/Modules/cjkcodecs/_codecs_tw.c ============================================================================== --- python/branches/py3k-jit/Modules/cjkcodecs/_codecs_tw.c (original) +++ python/branches/py3k-jit/Modules/cjkcodecs/_codecs_tw.c Mon May 10 23:55:43 2010 @@ -13,52 +13,52 @@ ENCODER(big5) { - while (inleft > 0) { - Py_UNICODE c = **inbuf; - DBCHAR code; - - if (c < 0x80) { - REQUIRE_OUTBUF(1) - **outbuf = (unsigned char)c; - NEXT(1, 1) - continue; - } - UCS4INVALID(c) - - REQUIRE_OUTBUF(2) - - TRYMAP_ENC(big5, code, c); - else return 1; - - OUT1(code >> 8) - OUT2(code & 0xFF) - NEXT(1, 2) - } + while (inleft > 0) { + Py_UNICODE c = **inbuf; + DBCHAR code; + + if (c < 0x80) { + REQUIRE_OUTBUF(1) + **outbuf = (unsigned char)c; + NEXT(1, 1) + continue; + } + UCS4INVALID(c) + + REQUIRE_OUTBUF(2) + + TRYMAP_ENC(big5, code, c); + else return 1; + + OUT1(code >> 8) + OUT2(code & 0xFF) + NEXT(1, 2) + } - return 0; + return 0; } DECODER(big5) { - while (inleft > 0) { - unsigned char c = IN1; + while (inleft > 0) { + unsigned char c = IN1; - REQUIRE_OUTBUF(1) + REQUIRE_OUTBUF(1) - if (c < 0x80) { - OUT1(c) - NEXT(1, 1) - continue; - } - - REQUIRE_INBUF(2) - TRYMAP_DEC(big5, **outbuf, c, IN2) { - NEXT(2, 1) - } - else return 2; - } + if (c < 0x80) { + OUT1(c) + NEXT(1, 1) + continue; + } + + REQUIRE_INBUF(2) + TRYMAP_DEC(big5, **outbuf, c, IN2) { + NEXT(2, 1) + } + else return 2; + } - return 0; + return 0; } @@ -68,53 +68,53 @@ ENCODER(cp950) { - while (inleft > 0) { - Py_UNICODE c = IN1; - DBCHAR code; - - if (c < 0x80) { - WRITE1((unsigned char)c) - NEXT(1, 1) - continue; - } - UCS4INVALID(c) - - REQUIRE_OUTBUF(2) - TRYMAP_ENC(cp950ext, code, c); - else TRYMAP_ENC(big5, code, c); - else return 1; - - OUT1(code >> 8) - OUT2(code & 0xFF) - NEXT(1, 2) - } + while (inleft > 0) { + Py_UNICODE c = IN1; + DBCHAR code; + + if (c < 0x80) { + WRITE1((unsigned char)c) + NEXT(1, 1) + continue; + } + UCS4INVALID(c) + + REQUIRE_OUTBUF(2) + TRYMAP_ENC(cp950ext, code, c); + else TRYMAP_ENC(big5, code, c); + else return 1; + + OUT1(code >> 8) + OUT2(code & 0xFF) + NEXT(1, 2) + } - return 0; + return 0; } DECODER(cp950) { - while (inleft > 0) { - unsigned char c = IN1; + while (inleft > 0) { + unsigned char c = IN1; - REQUIRE_OUTBUF(1) + REQUIRE_OUTBUF(1) - if (c < 0x80) { - OUT1(c) - NEXT(1, 1) - continue; - } + if (c < 0x80) { + OUT1(c) + NEXT(1, 1) + continue; + } - REQUIRE_INBUF(2) + REQUIRE_INBUF(2) - TRYMAP_DEC(cp950ext, **outbuf, c, IN2); - else TRYMAP_DEC(big5, **outbuf, c, IN2); - else return 2; + TRYMAP_DEC(cp950ext, **outbuf, c, IN2); + else TRYMAP_DEC(big5, **outbuf, c, IN2); + else return 2; - NEXT(2, 1) - } + NEXT(2, 1) + } - return 0; + return 0; } Modified: python/branches/py3k-jit/Modules/cjkcodecs/alg_jisx0201.h ============================================================================== --- python/branches/py3k-jit/Modules/cjkcodecs/alg_jisx0201.h (original) +++ python/branches/py3k-jit/Modules/cjkcodecs/alg_jisx0201.h Mon May 10 23:55:43 2010 @@ -1,24 +1,24 @@ -#define JISX0201_R_ENCODE(c, assi) \ - if ((c) < 0x80 && (c) != 0x5c && (c) != 0x7e) \ - (assi) = (c); \ - else if ((c) == 0x00a5) (assi) = 0x5c; \ - else if ((c) == 0x203e) (assi) = 0x7e; -#define JISX0201_K_ENCODE(c, assi) \ - if ((c) >= 0xff61 && (c) <= 0xff9f) \ - (assi) = (c) - 0xfec0; -#define JISX0201_ENCODE(c, assi) \ - JISX0201_R_ENCODE(c, assi) \ - else JISX0201_K_ENCODE(c, assi) +#define JISX0201_R_ENCODE(c, assi) \ + if ((c) < 0x80 && (c) != 0x5c && (c) != 0x7e) \ + (assi) = (c); \ + else if ((c) == 0x00a5) (assi) = 0x5c; \ + else if ((c) == 0x203e) (assi) = 0x7e; +#define JISX0201_K_ENCODE(c, assi) \ + if ((c) >= 0xff61 && (c) <= 0xff9f) \ + (assi) = (c) - 0xfec0; +#define JISX0201_ENCODE(c, assi) \ + JISX0201_R_ENCODE(c, assi) \ + else JISX0201_K_ENCODE(c, assi) -#define JISX0201_R_DECODE(c, assi) \ - if ((c) < 0x5c) (assi) = (c); \ - else if ((c) == 0x5c) (assi) = 0x00a5; \ - else if ((c) < 0x7e) (assi) = (c); \ - else if ((c) == 0x7e) (assi) = 0x203e; \ - else if ((c) == 0x7f) (assi) = 0x7f; -#define JISX0201_K_DECODE(c, assi) \ - if ((c) >= 0xa1 && (c) <= 0xdf) \ - (assi) = 0xfec0 + (c); -#define JISX0201_DECODE(c, assi) \ - JISX0201_R_DECODE(c, assi) \ - else JISX0201_K_DECODE(c, assi) +#define JISX0201_R_DECODE(c, assi) \ + if ((c) < 0x5c) (assi) = (c); \ + else if ((c) == 0x5c) (assi) = 0x00a5; \ + else if ((c) < 0x7e) (assi) = (c); \ + else if ((c) == 0x7e) (assi) = 0x203e; \ + else if ((c) == 0x7f) (assi) = 0x7f; +#define JISX0201_K_DECODE(c, assi) \ + if ((c) >= 0xa1 && (c) <= 0xdf) \ + (assi) = 0xfec0 + (c); +#define JISX0201_DECODE(c, assi) \ + JISX0201_R_DECODE(c, assi) \ + else JISX0201_K_DECODE(c, assi) Modified: python/branches/py3k-jit/Modules/cjkcodecs/cjkcodecs.h ============================================================================== --- python/branches/py3k-jit/Modules/cjkcodecs/cjkcodecs.h (original) +++ python/branches/py3k-jit/Modules/cjkcodecs/cjkcodecs.h Mon May 10 23:55:43 2010 @@ -13,12 +13,12 @@ /* a unicode "undefined" codepoint */ -#define UNIINV 0xFFFE +#define UNIINV 0xFFFE /* internal-use DBCS codepoints which aren't used by any charsets */ -#define NOCHAR 0xFFFF -#define MULTIC 0xFFFE -#define DBCINV 0xFFFD +#define NOCHAR 0xFFFF +#define MULTIC 0xFFFE +#define DBCINV 0xFFFD /* shorter macros to save source size of mapping tables */ #define U UNIINV @@ -27,94 +27,94 @@ #define D DBCINV struct dbcs_index { - const ucs2_t *map; - unsigned char bottom, top; + const ucs2_t *map; + unsigned char bottom, top; }; typedef struct dbcs_index decode_map; struct widedbcs_index { - const ucs4_t *map; - unsigned char bottom, top; + const ucs4_t *map; + unsigned char bottom, top; }; typedef struct widedbcs_index widedecode_map; struct unim_index { - const DBCHAR *map; - unsigned char bottom, top; + const DBCHAR *map; + unsigned char bottom, top; }; typedef struct unim_index encode_map; struct unim_index_bytebased { - const unsigned char *map; - unsigned char bottom, top; + const unsigned char *map; + unsigned char bottom, top; }; struct dbcs_map { - const char *charset; - const struct unim_index *encmap; - const struct dbcs_index *decmap; + const char *charset; + const struct unim_index *encmap; + const struct dbcs_index *decmap; }; struct pair_encodemap { - ucs4_t uniseq; - DBCHAR code; + ucs4_t uniseq; + DBCHAR code; }; static const MultibyteCodec *codec_list; static const struct dbcs_map *mapping_list; -#define CODEC_INIT(encoding) \ - static int encoding##_codec_init(const void *config) +#define CODEC_INIT(encoding) \ + static int encoding##_codec_init(const void *config) -#define ENCODER_INIT(encoding) \ - static int encoding##_encode_init( \ - MultibyteCodec_State *state, const void *config) -#define ENCODER(encoding) \ - static Py_ssize_t encoding##_encode( \ - MultibyteCodec_State *state, const void *config, \ - const Py_UNICODE **inbuf, Py_ssize_t inleft, \ - unsigned char **outbuf, Py_ssize_t outleft, int flags) -#define ENCODER_RESET(encoding) \ - static Py_ssize_t encoding##_encode_reset( \ - MultibyteCodec_State *state, const void *config, \ - unsigned char **outbuf, Py_ssize_t outleft) - -#define DECODER_INIT(encoding) \ - static int encoding##_decode_init( \ - MultibyteCodec_State *state, const void *config) -#define DECODER(encoding) \ - static Py_ssize_t encoding##_decode( \ - MultibyteCodec_State *state, const void *config, \ - const unsigned char **inbuf, Py_ssize_t inleft, \ - Py_UNICODE **outbuf, Py_ssize_t outleft) -#define DECODER_RESET(encoding) \ - static Py_ssize_t encoding##_decode_reset( \ - MultibyteCodec_State *state, const void *config) +#define ENCODER_INIT(encoding) \ + static int encoding##_encode_init( \ + MultibyteCodec_State *state, const void *config) +#define ENCODER(encoding) \ + static Py_ssize_t encoding##_encode( \ + MultibyteCodec_State *state, const void *config, \ + const Py_UNICODE **inbuf, Py_ssize_t inleft, \ + unsigned char **outbuf, Py_ssize_t outleft, int flags) +#define ENCODER_RESET(encoding) \ + static Py_ssize_t encoding##_encode_reset( \ + MultibyteCodec_State *state, const void *config, \ + unsigned char **outbuf, Py_ssize_t outleft) + +#define DECODER_INIT(encoding) \ + static int encoding##_decode_init( \ + MultibyteCodec_State *state, const void *config) +#define DECODER(encoding) \ + static Py_ssize_t encoding##_decode( \ + MultibyteCodec_State *state, const void *config, \ + const unsigned char **inbuf, Py_ssize_t inleft, \ + Py_UNICODE **outbuf, Py_ssize_t outleft) +#define DECODER_RESET(encoding) \ + static Py_ssize_t encoding##_decode_reset( \ + MultibyteCodec_State *state, const void *config) #if Py_UNICODE_SIZE == 4 -#define UCS4INVALID(code) \ - if ((code) > 0xFFFF) \ - return 1; +#define UCS4INVALID(code) \ + if ((code) > 0xFFFF) \ + return 1; #else -#define UCS4INVALID(code) \ - if (0) ; +#define UCS4INVALID(code) \ + if (0) ; #endif -#define NEXT_IN(i) \ - (*inbuf) += (i); \ - (inleft) -= (i); -#define NEXT_OUT(o) \ - (*outbuf) += (o); \ - (outleft) -= (o); -#define NEXT(i, o) \ - NEXT_IN(i) NEXT_OUT(o) - -#define REQUIRE_INBUF(n) \ - if (inleft < (n)) \ - return MBERR_TOOFEW; -#define REQUIRE_OUTBUF(n) \ - if (outleft < (n)) \ - return MBERR_TOOSMALL; +#define NEXT_IN(i) \ + (*inbuf) += (i); \ + (inleft) -= (i); +#define NEXT_OUT(o) \ + (*outbuf) += (o); \ + (outleft) -= (o); +#define NEXT(i, o) \ + NEXT_IN(i) NEXT_OUT(o) + +#define REQUIRE_INBUF(n) \ + if (inleft < (n)) \ + return MBERR_TOOFEW; +#define REQUIRE_OUTBUF(n) \ + if (outleft < (n)) \ + return MBERR_TOOSMALL; #define IN1 ((*inbuf)[0]) #define IN2 ((*inbuf)[1]) @@ -126,289 +126,289 @@ #define OUT3(c) ((*outbuf)[2]) = (c); #define OUT4(c) ((*outbuf)[3]) = (c); -#define WRITE1(c1) \ - REQUIRE_OUTBUF(1) \ - (*outbuf)[0] = (c1); -#define WRITE2(c1, c2) \ - REQUIRE_OUTBUF(2) \ - (*outbuf)[0] = (c1); \ - (*outbuf)[1] = (c2); -#define WRITE3(c1, c2, c3) \ - REQUIRE_OUTBUF(3) \ - (*outbuf)[0] = (c1); \ - (*outbuf)[1] = (c2); \ - (*outbuf)[2] = (c3); -#define WRITE4(c1, c2, c3, c4) \ - REQUIRE_OUTBUF(4) \ - (*outbuf)[0] = (c1); \ - (*outbuf)[1] = (c2); \ - (*outbuf)[2] = (c3); \ - (*outbuf)[3] = (c4); +#define WRITE1(c1) \ + REQUIRE_OUTBUF(1) \ + (*outbuf)[0] = (c1); +#define WRITE2(c1, c2) \ + REQUIRE_OUTBUF(2) \ + (*outbuf)[0] = (c1); \ + (*outbuf)[1] = (c2); +#define WRITE3(c1, c2, c3) \ + REQUIRE_OUTBUF(3) \ + (*outbuf)[0] = (c1); \ + (*outbuf)[1] = (c2); \ + (*outbuf)[2] = (c3); +#define WRITE4(c1, c2, c3, c4) \ + REQUIRE_OUTBUF(4) \ + (*outbuf)[0] = (c1); \ + (*outbuf)[1] = (c2); \ + (*outbuf)[2] = (c3); \ + (*outbuf)[3] = (c4); #if Py_UNICODE_SIZE == 2 -# define WRITEUCS4(c) \ - REQUIRE_OUTBUF(2) \ - (*outbuf)[0] = 0xd800 + (((c) - 0x10000) >> 10); \ - (*outbuf)[1] = 0xdc00 + (((c) - 0x10000) & 0x3ff); \ - NEXT_OUT(2) +# define WRITEUCS4(c) \ + REQUIRE_OUTBUF(2) \ + (*outbuf)[0] = 0xd800 + (((c) - 0x10000) >> 10); \ + (*outbuf)[1] = 0xdc00 + (((c) - 0x10000) & 0x3ff); \ + NEXT_OUT(2) #else -# define WRITEUCS4(c) \ - REQUIRE_OUTBUF(1) \ - **outbuf = (Py_UNICODE)(c); \ - NEXT_OUT(1) +# define WRITEUCS4(c) \ + REQUIRE_OUTBUF(1) \ + **outbuf = (Py_UNICODE)(c); \ + NEXT_OUT(1) #endif -#define _TRYMAP_ENC(m, assi, val) \ - ((m)->map != NULL && (val) >= (m)->bottom && \ - (val)<= (m)->top && ((assi) = (m)->map[(val) - \ - (m)->bottom]) != NOCHAR) -#define TRYMAP_ENC_COND(charset, assi, uni) \ - _TRYMAP_ENC(&charset##_encmap[(uni) >> 8], assi, (uni) & 0xff) -#define TRYMAP_ENC(charset, assi, uni) \ - if TRYMAP_ENC_COND(charset, assi, uni) - -#define _TRYMAP_DEC(m, assi, val) \ - ((m)->map != NULL && (val) >= (m)->bottom && \ - (val)<= (m)->top && ((assi) = (m)->map[(val) - \ - (m)->bottom]) != UNIINV) -#define TRYMAP_DEC(charset, assi, c1, c2) \ - if _TRYMAP_DEC(&charset##_decmap[c1], assi, c2) - -#define _TRYMAP_ENC_MPLANE(m, assplane, asshi, asslo, val) \ - ((m)->map != NULL && (val) >= (m)->bottom && \ - (val)<= (m)->top && \ - ((assplane) = (m)->map[((val) - (m)->bottom)*3]) != 0 && \ - (((asshi) = (m)->map[((val) - (m)->bottom)*3 + 1]), 1) && \ - (((asslo) = (m)->map[((val) - (m)->bottom)*3 + 2]), 1)) -#define TRYMAP_ENC_MPLANE(charset, assplane, asshi, asslo, uni) \ - if _TRYMAP_ENC_MPLANE(&charset##_encmap[(uni) >> 8], \ - assplane, asshi, asslo, (uni) & 0xff) -#define TRYMAP_DEC_MPLANE(charset, assi, plane, c1, c2) \ - if _TRYMAP_DEC(&charset##_decmap[plane][c1], assi, c2) +#define _TRYMAP_ENC(m, assi, val) \ + ((m)->map != NULL && (val) >= (m)->bottom && \ + (val)<= (m)->top && ((assi) = (m)->map[(val) - \ + (m)->bottom]) != NOCHAR) +#define TRYMAP_ENC_COND(charset, assi, uni) \ + _TRYMAP_ENC(&charset##_encmap[(uni) >> 8], assi, (uni) & 0xff) +#define TRYMAP_ENC(charset, assi, uni) \ + if TRYMAP_ENC_COND(charset, assi, uni) + +#define _TRYMAP_DEC(m, assi, val) \ + ((m)->map != NULL && (val) >= (m)->bottom && \ + (val)<= (m)->top && ((assi) = (m)->map[(val) - \ + (m)->bottom]) != UNIINV) +#define TRYMAP_DEC(charset, assi, c1, c2) \ + if _TRYMAP_DEC(&charset##_decmap[c1], assi, c2) + +#define _TRYMAP_ENC_MPLANE(m, assplane, asshi, asslo, val) \ + ((m)->map != NULL && (val) >= (m)->bottom && \ + (val)<= (m)->top && \ + ((assplane) = (m)->map[((val) - (m)->bottom)*3]) != 0 && \ + (((asshi) = (m)->map[((val) - (m)->bottom)*3 + 1]), 1) && \ + (((asslo) = (m)->map[((val) - (m)->bottom)*3 + 2]), 1)) +#define TRYMAP_ENC_MPLANE(charset, assplane, asshi, asslo, uni) \ + if _TRYMAP_ENC_MPLANE(&charset##_encmap[(uni) >> 8], \ + assplane, asshi, asslo, (uni) & 0xff) +#define TRYMAP_DEC_MPLANE(charset, assi, plane, c1, c2) \ + if _TRYMAP_DEC(&charset##_decmap[plane][c1], assi, c2) #if Py_UNICODE_SIZE == 2 -#define DECODE_SURROGATE(c) \ - if (c >> 10 == 0xd800 >> 10) { /* high surrogate */ \ - REQUIRE_INBUF(2) \ - if (IN2 >> 10 == 0xdc00 >> 10) { /* low surrogate */ \ - c = 0x10000 + ((ucs4_t)(c - 0xd800) << 10) + \ - ((ucs4_t)(IN2) - 0xdc00); \ - } \ - } -#define GET_INSIZE(c) ((c) > 0xffff ? 2 : 1) +#define DECODE_SURROGATE(c) \ + if (c >> 10 == 0xd800 >> 10) { /* high surrogate */ \ + REQUIRE_INBUF(2) \ + if (IN2 >> 10 == 0xdc00 >> 10) { /* low surrogate */ \ + c = 0x10000 + ((ucs4_t)(c - 0xd800) << 10) + \ + ((ucs4_t)(IN2) - 0xdc00); \ + } \ + } +#define GET_INSIZE(c) ((c) > 0xffff ? 2 : 1) #else #define DECODE_SURROGATE(c) {;} -#define GET_INSIZE(c) 1 +#define GET_INSIZE(c) 1 #endif #define BEGIN_MAPPINGS_LIST static const struct dbcs_map _mapping_list[] = { #define MAPPING_ENCONLY(enc) {#enc, (void*)enc##_encmap, NULL}, #define MAPPING_DECONLY(enc) {#enc, NULL, (void*)enc##_decmap}, #define MAPPING_ENCDEC(enc) {#enc, (void*)enc##_encmap, (void*)enc##_decmap}, -#define END_MAPPINGS_LIST \ - {"", NULL, NULL} }; \ - static const struct dbcs_map *mapping_list = \ - (const struct dbcs_map *)_mapping_list; +#define END_MAPPINGS_LIST \ + {"", NULL, NULL} }; \ + static const struct dbcs_map *mapping_list = \ + (const struct dbcs_map *)_mapping_list; #define BEGIN_CODECS_LIST static const MultibyteCodec _codec_list[] = { -#define _STATEFUL_METHODS(enc) \ - enc##_encode, \ - enc##_encode_init, \ - enc##_encode_reset, \ - enc##_decode, \ - enc##_decode_init, \ - enc##_decode_reset, -#define _STATELESS_METHODS(enc) \ - enc##_encode, NULL, NULL, \ - enc##_decode, NULL, NULL, -#define CODEC_STATEFUL(enc) { \ - #enc, NULL, NULL, \ - _STATEFUL_METHODS(enc) \ +#define _STATEFUL_METHODS(enc) \ + enc##_encode, \ + enc##_encode_init, \ + enc##_encode_reset, \ + enc##_decode, \ + enc##_decode_init, \ + enc##_decode_reset, +#define _STATELESS_METHODS(enc) \ + enc##_encode, NULL, NULL, \ + enc##_decode, NULL, NULL, +#define CODEC_STATEFUL(enc) { \ + #enc, NULL, NULL, \ + _STATEFUL_METHODS(enc) \ }, -#define CODEC_STATELESS(enc) { \ - #enc, NULL, NULL, \ - _STATELESS_METHODS(enc) \ +#define CODEC_STATELESS(enc) { \ + #enc, NULL, NULL, \ + _STATELESS_METHODS(enc) \ }, -#define CODEC_STATELESS_WINIT(enc) { \ - #enc, NULL, \ - enc##_codec_init, \ - _STATELESS_METHODS(enc) \ +#define CODEC_STATELESS_WINIT(enc) { \ + #enc, NULL, \ + enc##_codec_init, \ + _STATELESS_METHODS(enc) \ }, -#define END_CODECS_LIST \ - {"", NULL,} }; \ - static const MultibyteCodec *codec_list = \ - (const MultibyteCodec *)_codec_list; +#define END_CODECS_LIST \ + {"", NULL,} }; \ + static const MultibyteCodec *codec_list = \ + (const MultibyteCodec *)_codec_list; static PyObject * getmultibytecodec(void) { - static PyObject *cofunc = NULL; + static PyObject *cofunc = NULL; - if (cofunc == NULL) { - PyObject *mod = PyImport_ImportModuleNoBlock("_multibytecodec"); - if (mod == NULL) - return NULL; - cofunc = PyObject_GetAttrString(mod, "__create_codec"); - Py_DECREF(mod); - } - return cofunc; + if (cofunc == NULL) { + PyObject *mod = PyImport_ImportModuleNoBlock("_multibytecodec"); + if (mod == NULL) + return NULL; + cofunc = PyObject_GetAttrString(mod, "__create_codec"); + Py_DECREF(mod); + } + return cofunc; } static PyObject * getcodec(PyObject *self, PyObject *encoding) { - PyObject *codecobj, *r, *cofunc; - const MultibyteCodec *codec; - const char *enc; - - if (!PyUnicode_Check(encoding)) { - PyErr_SetString(PyExc_TypeError, - "encoding name must be a string."); - return NULL; - } - enc = _PyUnicode_AsString(encoding); - if (enc == NULL) - return NULL; - - cofunc = getmultibytecodec(); - if (cofunc == NULL) - return NULL; - - for (codec = codec_list; codec->encoding[0]; codec++) - if (strcmp(codec->encoding, enc) == 0) - break; - - if (codec->encoding[0] == '\0') { - PyErr_SetString(PyExc_LookupError, - "no such codec is supported."); - return NULL; - } - - codecobj = PyCapsule_New((void *)codec, PyMultibyteCodec_CAPSULE_NAME, NULL); - if (codecobj == NULL) - return NULL; + PyObject *codecobj, *r, *cofunc; + const MultibyteCodec *codec; + const char *enc; + + if (!PyUnicode_Check(encoding)) { + PyErr_SetString(PyExc_TypeError, + "encoding name must be a string."); + return NULL; + } + enc = _PyUnicode_AsString(encoding); + if (enc == NULL) + return NULL; + + cofunc = getmultibytecodec(); + if (cofunc == NULL) + return NULL; + + for (codec = codec_list; codec->encoding[0]; codec++) + if (strcmp(codec->encoding, enc) == 0) + break; + + if (codec->encoding[0] == '\0') { + PyErr_SetString(PyExc_LookupError, + "no such codec is supported."); + return NULL; + } + + codecobj = PyCapsule_New((void *)codec, PyMultibyteCodec_CAPSULE_NAME, NULL); + if (codecobj == NULL) + return NULL; - r = PyObject_CallFunctionObjArgs(cofunc, codecobj, NULL); - Py_DECREF(codecobj); + r = PyObject_CallFunctionObjArgs(cofunc, codecobj, NULL); + Py_DECREF(codecobj); - return r; + return r; } static struct PyMethodDef __methods[] = { - {"getcodec", (PyCFunction)getcodec, METH_O, ""}, - {NULL, NULL}, + {"getcodec", (PyCFunction)getcodec, METH_O, ""}, + {NULL, NULL}, }; static int register_maps(PyObject *module) { - const struct dbcs_map *h; + const struct dbcs_map *h; - for (h = mapping_list; h->charset[0] != '\0'; h++) { - char mhname[256] = "__map_"; - int r; - strcpy(mhname + sizeof("__map_") - 1, h->charset); - r = PyModule_AddObject(module, mhname, - PyCapsule_New((void *)h, PyMultibyteCodec_CAPSULE_NAME, NULL)); - if (r == -1) - return -1; - } - return 0; + for (h = mapping_list; h->charset[0] != '\0'; h++) { + char mhname[256] = "__map_"; + int r; + strcpy(mhname + sizeof("__map_") - 1, h->charset); + r = PyModule_AddObject(module, mhname, + PyCapsule_New((void *)h, PyMultibyteCodec_CAPSULE_NAME, NULL)); + if (r == -1) + return -1; + } + return 0; } #ifdef USING_BINARY_PAIR_SEARCH static DBCHAR find_pairencmap(ucs2_t body, ucs2_t modifier, - const struct pair_encodemap *haystack, int haystacksize) + const struct pair_encodemap *haystack, int haystacksize) { - int pos, min, max; - ucs4_t value = body << 16 | modifier; + int pos, min, max; + ucs4_t value = body << 16 | modifier; - min = 0; - max = haystacksize; + min = 0; + max = haystacksize; - for (pos = haystacksize >> 1; min != max; pos = (min + max) >> 1) - if (value < haystack[pos].uniseq) { - if (max == pos) break; - else max = pos; - } - else if (value > haystack[pos].uniseq) { - if (min == pos) break; - else min = pos; - } - else - break; - - if (value == haystack[pos].uniseq) - return haystack[pos].code; - else - return DBCINV; + for (pos = haystacksize >> 1; min != max; pos = (min + max) >> 1) + if (value < haystack[pos].uniseq) { + if (max == pos) break; + else max = pos; + } + else if (value > haystack[pos].uniseq) { + if (min == pos) break; + else min = pos; + } + else + break; + + if (value == haystack[pos].uniseq) + return haystack[pos].code; + else + return DBCINV; } #endif #ifdef USING_IMPORTED_MAPS #define IMPORT_MAP(locale, charset, encmap, decmap) \ - importmap("_codecs_" #locale, "__map_" #charset, \ - (const void**)encmap, (const void**)decmap) + importmap("_codecs_" #locale, "__map_" #charset, \ + (const void**)encmap, (const void**)decmap) static int importmap(const char *modname, const char *symbol, - const void **encmap, const void **decmap) + const void **encmap, const void **decmap) { - PyObject *o, *mod; + PyObject *o, *mod; - mod = PyImport_ImportModule((char *)modname); - if (mod == NULL) - return -1; - - o = PyObject_GetAttrString(mod, (char*)symbol); - if (o == NULL) - goto errorexit; - else if (!PyCapsule_IsValid(o, PyMultibyteCodec_CAPSULE_NAME)) { - PyErr_SetString(PyExc_ValueError, - "map data must be a Capsule."); - goto errorexit; - } - else { - struct dbcs_map *map; - map = PyCapsule_GetPointer(o, PyMultibyteCodec_CAPSULE_NAME); - if (encmap != NULL) - *encmap = map->encmap; - if (decmap != NULL) - *decmap = map->decmap; - Py_DECREF(o); - } + mod = PyImport_ImportModule((char *)modname); + if (mod == NULL) + return -1; + + o = PyObject_GetAttrString(mod, (char*)symbol); + if (o == NULL) + goto errorexit; + else if (!PyCapsule_IsValid(o, PyMultibyteCodec_CAPSULE_NAME)) { + PyErr_SetString(PyExc_ValueError, + "map data must be a Capsule."); + goto errorexit; + } + else { + struct dbcs_map *map; + map = PyCapsule_GetPointer(o, PyMultibyteCodec_CAPSULE_NAME); + if (encmap != NULL) + *encmap = map->encmap; + if (decmap != NULL) + *decmap = map->decmap; + Py_DECREF(o); + } - Py_DECREF(mod); - return 0; + Py_DECREF(mod); + return 0; errorexit: - Py_DECREF(mod); - return -1; + Py_DECREF(mod); + return -1; } #endif -#define I_AM_A_MODULE_FOR(loc) \ - static struct PyModuleDef __module = { \ - PyModuleDef_HEAD_INIT, \ - "_codecs_"#loc, \ - NULL, \ - 0, \ - __methods, \ - NULL, \ - NULL, \ - NULL, \ - NULL \ - }; \ - PyObject* \ - PyInit__codecs_##loc(void) \ - { \ - PyObject *m = PyModule_Create(&__module); \ - if (m != NULL) \ - (void)register_maps(m); \ - return m; \ - } +#define I_AM_A_MODULE_FOR(loc) \ + static struct PyModuleDef __module = { \ + PyModuleDef_HEAD_INIT, \ + "_codecs_"#loc, \ + NULL, \ + 0, \ + __methods, \ + NULL, \ + NULL, \ + NULL, \ + NULL \ + }; \ + PyObject* \ + PyInit__codecs_##loc(void) \ + { \ + PyObject *m = PyModule_Create(&__module); \ + if (m != NULL) \ + (void)register_maps(m); \ + return m; \ + } #endif Modified: python/branches/py3k-jit/Modules/cjkcodecs/emu_jisx0213_2000.h ============================================================================== --- python/branches/py3k-jit/Modules/cjkcodecs/emu_jisx0213_2000.h (original) +++ python/branches/py3k-jit/Modules/cjkcodecs/emu_jisx0213_2000.h Mon May 10 23:55:43 2010 @@ -5,39 +5,39 @@ #define EMULATE_JISX0213_2000_ENCODE_INVALID 1 #endif -#define EMULATE_JISX0213_2000_ENCODE_BMP(assi, c) \ - if (config == (void *)2000 && ( \ - (c) == 0x9B1C || (c) == 0x4FF1 || \ - (c) == 0x525D || (c) == 0x541E || \ - (c) == 0x5653 || (c) == 0x59F8 || \ - (c) == 0x5C5B || (c) == 0x5E77 || \ - (c) == 0x7626 || (c) == 0x7E6B)) \ - return EMULATE_JISX0213_2000_ENCODE_INVALID; \ - else if (config == (void *)2000 && (c) == 0x9B1D) \ - (assi) = 0x8000 | 0x7d3b; \ +#define EMULATE_JISX0213_2000_ENCODE_BMP(assi, c) \ + if (config == (void *)2000 && ( \ + (c) == 0x9B1C || (c) == 0x4FF1 || \ + (c) == 0x525D || (c) == 0x541E || \ + (c) == 0x5653 || (c) == 0x59F8 || \ + (c) == 0x5C5B || (c) == 0x5E77 || \ + (c) == 0x7626 || (c) == 0x7E6B)) \ + return EMULATE_JISX0213_2000_ENCODE_INVALID; \ + else if (config == (void *)2000 && (c) == 0x9B1D) \ + (assi) = 0x8000 | 0x7d3b; \ -#define EMULATE_JISX0213_2000_ENCODE_EMP(assi, c) \ - if (config == (void *)2000 && (c) == 0x20B9F) \ - return EMULATE_JISX0213_2000_ENCODE_INVALID; +#define EMULATE_JISX0213_2000_ENCODE_EMP(assi, c) \ + if (config == (void *)2000 && (c) == 0x20B9F) \ + return EMULATE_JISX0213_2000_ENCODE_INVALID; #ifndef EMULATE_JISX0213_2000_DECODE_INVALID #define EMULATE_JISX0213_2000_DECODE_INVALID 2 #endif -#define EMULATE_JISX0213_2000_DECODE_PLANE1(assi, c1, c2) \ - if (config == (void *)2000 && \ - (((c1) == 0x2E && (c2) == 0x21) || \ - ((c1) == 0x2F && (c2) == 0x7E) || \ - ((c1) == 0x4F && (c2) == 0x54) || \ - ((c1) == 0x4F && (c2) == 0x7E) || \ - ((c1) == 0x74 && (c2) == 0x27) || \ - ((c1) == 0x7E && (c2) == 0x7A) || \ - ((c1) == 0x7E && (c2) == 0x7B) || \ - ((c1) == 0x7E && (c2) == 0x7C) || \ - ((c1) == 0x7E && (c2) == 0x7D) || \ - ((c1) == 0x7E && (c2) == 0x7E))) \ - return EMULATE_JISX0213_2000_DECODE_INVALID; +#define EMULATE_JISX0213_2000_DECODE_PLANE1(assi, c1, c2) \ + if (config == (void *)2000 && \ + (((c1) == 0x2E && (c2) == 0x21) || \ + ((c1) == 0x2F && (c2) == 0x7E) || \ + ((c1) == 0x4F && (c2) == 0x54) || \ + ((c1) == 0x4F && (c2) == 0x7E) || \ + ((c1) == 0x74 && (c2) == 0x27) || \ + ((c1) == 0x7E && (c2) == 0x7A) || \ + ((c1) == 0x7E && (c2) == 0x7B) || \ + ((c1) == 0x7E && (c2) == 0x7C) || \ + ((c1) == 0x7E && (c2) == 0x7D) || \ + ((c1) == 0x7E && (c2) == 0x7E))) \ + return EMULATE_JISX0213_2000_DECODE_INVALID; -#define EMULATE_JISX0213_2000_DECODE_PLANE2(assi, c1, c2) \ - if (config == (void *)2000 && (c1) == 0x7D && (c2) == 0x3B) \ - (assi) = 0x9B1D; +#define EMULATE_JISX0213_2000_DECODE_PLANE2(assi, c1, c2) \ + if (config == (void *)2000 && (c1) == 0x7D && (c2) == 0x3B) \ + (assi) = 0x9B1D; Modified: python/branches/py3k-jit/Modules/cjkcodecs/multibytecodec.c ============================================================================== --- python/branches/py3k-jit/Modules/cjkcodecs/multibytecodec.c (original) +++ python/branches/py3k-jit/Modules/cjkcodecs/multibytecodec.c Mon May 10 23:55:43 2010 @@ -45,179 +45,179 @@ static char *streamkwarglist[] = {"stream", "errors", NULL}; static PyObject *multibytecodec_encode(MultibyteCodec *, - MultibyteCodec_State *, const Py_UNICODE **, Py_ssize_t, - PyObject *, int); + MultibyteCodec_State *, const Py_UNICODE **, Py_ssize_t, + PyObject *, int); -#define MBENC_RESET MBENC_MAX<<1 /* reset after an encoding session */ +#define MBENC_RESET MBENC_MAX<<1 /* reset after an encoding session */ static PyObject * make_tuple(PyObject *object, Py_ssize_t len) { - PyObject *v, *w; + PyObject *v, *w; - if (object == NULL) - return NULL; + if (object == NULL) + return NULL; - v = PyTuple_New(2); - if (v == NULL) { - Py_DECREF(object); - return NULL; - } - PyTuple_SET_ITEM(v, 0, object); - - w = PyLong_FromSsize_t(len); - if (w == NULL) { - Py_DECREF(v); - return NULL; - } - PyTuple_SET_ITEM(v, 1, w); + v = PyTuple_New(2); + if (v == NULL) { + Py_DECREF(object); + return NULL; + } + PyTuple_SET_ITEM(v, 0, object); + + w = PyLong_FromSsize_t(len); + if (w == NULL) { + Py_DECREF(v); + return NULL; + } + PyTuple_SET_ITEM(v, 1, w); - return v; + return v; } static PyObject * internal_error_callback(const char *errors) { - if (errors == NULL || strcmp(errors, "strict") == 0) - return ERROR_STRICT; - else if (strcmp(errors, "ignore") == 0) - return ERROR_IGNORE; - else if (strcmp(errors, "replace") == 0) - return ERROR_REPLACE; - else - return PyUnicode_FromString(errors); + if (errors == NULL || strcmp(errors, "strict") == 0) + return ERROR_STRICT; + else if (strcmp(errors, "ignore") == 0) + return ERROR_IGNORE; + else if (strcmp(errors, "replace") == 0) + return ERROR_REPLACE; + else + return PyUnicode_FromString(errors); } static PyObject * call_error_callback(PyObject *errors, PyObject *exc) { - PyObject *args, *cb, *r; - const char *str; + PyObject *args, *cb, *r; + const char *str; - assert(PyUnicode_Check(errors)); - str = _PyUnicode_AsString(errors); - if (str == NULL) - return NULL; - cb = PyCodec_LookupError(str); - if (cb == NULL) - return NULL; - - args = PyTuple_New(1); - if (args == NULL) { - Py_DECREF(cb); - return NULL; - } - - PyTuple_SET_ITEM(args, 0, exc); - Py_INCREF(exc); - - r = PyObject_CallObject(cb, args); - Py_DECREF(args); - Py_DECREF(cb); - return r; + assert(PyUnicode_Check(errors)); + str = _PyUnicode_AsString(errors); + if (str == NULL) + return NULL; + cb = PyCodec_LookupError(str); + if (cb == NULL) + return NULL; + + args = PyTuple_New(1); + if (args == NULL) { + Py_DECREF(cb); + return NULL; + } + + PyTuple_SET_ITEM(args, 0, exc); + Py_INCREF(exc); + + r = PyObject_CallObject(cb, args); + Py_DECREF(args); + Py_DECREF(cb); + return r; } static PyObject * codecctx_errors_get(MultibyteStatefulCodecContext *self) { - const char *errors; + const char *errors; - if (self->errors == ERROR_STRICT) - errors = "strict"; - else if (self->errors == ERROR_IGNORE) - errors = "ignore"; - else if (self->errors == ERROR_REPLACE) - errors = "replace"; - else { - Py_INCREF(self->errors); - return self->errors; - } + if (self->errors == ERROR_STRICT) + errors = "strict"; + else if (self->errors == ERROR_IGNORE) + errors = "ignore"; + else if (self->errors == ERROR_REPLACE) + errors = "replace"; + else { + Py_INCREF(self->errors); + return self->errors; + } - return PyUnicode_FromString(errors); + return PyUnicode_FromString(errors); } static int codecctx_errors_set(MultibyteStatefulCodecContext *self, PyObject *value, - void *closure) + void *closure) { - PyObject *cb; - const char *str; + PyObject *cb; + const char *str; - if (!PyUnicode_Check(value)) { - PyErr_SetString(PyExc_TypeError, "errors must be a string"); - return -1; - } - - str = _PyUnicode_AsString(value); - if (str == NULL) - return -1; - - cb = internal_error_callback(str); - if (cb == NULL) - return -1; - - ERROR_DECREF(self->errors); - self->errors = cb; - return 0; + if (!PyUnicode_Check(value)) { + PyErr_SetString(PyExc_TypeError, "errors must be a string"); + return -1; + } + + str = _PyUnicode_AsString(value); + if (str == NULL) + return -1; + + cb = internal_error_callback(str); + if (cb == NULL) + return -1; + + ERROR_DECREF(self->errors); + self->errors = cb; + return 0; } /* This getset handlers list is used by all the stateful codec objects */ static PyGetSetDef codecctx_getsets[] = { - {"errors", (getter)codecctx_errors_get, - (setter)codecctx_errors_set, - PyDoc_STR("how to treat errors")}, - {NULL,} + {"errors", (getter)codecctx_errors_get, + (setter)codecctx_errors_set, + PyDoc_STR("how to treat errors")}, + {NULL,} }; static int expand_encodebuffer(MultibyteEncodeBuffer *buf, Py_ssize_t esize) { - Py_ssize_t orgpos, orgsize, incsize; + Py_ssize_t orgpos, orgsize, incsize; - orgpos = (Py_ssize_t)((char *)buf->outbuf - - PyBytes_AS_STRING(buf->outobj)); - orgsize = PyBytes_GET_SIZE(buf->outobj); - incsize = (esize < (orgsize >> 1) ? (orgsize >> 1) | 1 : esize); + orgpos = (Py_ssize_t)((char *)buf->outbuf - + PyBytes_AS_STRING(buf->outobj)); + orgsize = PyBytes_GET_SIZE(buf->outobj); + incsize = (esize < (orgsize >> 1) ? (orgsize >> 1) | 1 : esize); - if (orgsize > PY_SSIZE_T_MAX - incsize) - return -1; + if (orgsize > PY_SSIZE_T_MAX - incsize) + return -1; - if (_PyBytes_Resize(&buf->outobj, orgsize + incsize) == -1) - return -1; + if (_PyBytes_Resize(&buf->outobj, orgsize + incsize) == -1) + return -1; - buf->outbuf = (unsigned char *)PyBytes_AS_STRING(buf->outobj) +orgpos; - buf->outbuf_end = (unsigned char *)PyBytes_AS_STRING(buf->outobj) - + PyBytes_GET_SIZE(buf->outobj); + buf->outbuf = (unsigned char *)PyBytes_AS_STRING(buf->outobj) +orgpos; + buf->outbuf_end = (unsigned char *)PyBytes_AS_STRING(buf->outobj) + + PyBytes_GET_SIZE(buf->outobj); - return 0; + return 0; } -#define REQUIRE_ENCODEBUFFER(buf, s) { \ - if ((s) < 1 || (buf)->outbuf + (s) > (buf)->outbuf_end) \ - if (expand_encodebuffer(buf, s) == -1) \ - goto errorexit; \ +#define REQUIRE_ENCODEBUFFER(buf, s) { \ + if ((s) < 1 || (buf)->outbuf + (s) > (buf)->outbuf_end) \ + if (expand_encodebuffer(buf, s) == -1) \ + goto errorexit; \ } static int expand_decodebuffer(MultibyteDecodeBuffer *buf, Py_ssize_t esize) { - Py_ssize_t orgpos, orgsize; + Py_ssize_t orgpos, orgsize; - orgpos = (Py_ssize_t)(buf->outbuf - PyUnicode_AS_UNICODE(buf->outobj)); - orgsize = PyUnicode_GET_SIZE(buf->outobj); - if (PyUnicode_Resize(&buf->outobj, orgsize + ( - esize < (orgsize >> 1) ? (orgsize >> 1) | 1 : esize)) == -1) - return -1; - - buf->outbuf = PyUnicode_AS_UNICODE(buf->outobj) + orgpos; - buf->outbuf_end = PyUnicode_AS_UNICODE(buf->outobj) - + PyUnicode_GET_SIZE(buf->outobj); - - return 0; -} -#define REQUIRE_DECODEBUFFER(buf, s) { \ - if ((s) < 1 || (buf)->outbuf + (s) > (buf)->outbuf_end) \ - if (expand_decodebuffer(buf, s) == -1) \ - goto errorexit; \ + orgpos = (Py_ssize_t)(buf->outbuf - PyUnicode_AS_UNICODE(buf->outobj)); + orgsize = PyUnicode_GET_SIZE(buf->outobj); + if (PyUnicode_Resize(&buf->outobj, orgsize + ( + esize < (orgsize >> 1) ? (orgsize >> 1) | 1 : esize)) == -1) + return -1; + + buf->outbuf = PyUnicode_AS_UNICODE(buf->outobj) + orgpos; + buf->outbuf_end = PyUnicode_AS_UNICODE(buf->outobj) + + PyUnicode_GET_SIZE(buf->outobj); + + return 0; +} +#define REQUIRE_DECODEBUFFER(buf, s) { \ + if ((s) < 1 || (buf)->outbuf + (s) > (buf)->outbuf_end) \ + if (expand_decodebuffer(buf, s) == -1) \ + goto errorexit; \ } @@ -227,504 +227,504 @@ static int multibytecodec_encerror(MultibyteCodec *codec, - MultibyteCodec_State *state, - MultibyteEncodeBuffer *buf, - PyObject *errors, Py_ssize_t e) -{ - PyObject *retobj = NULL, *retstr = NULL, *tobj; - Py_ssize_t retstrsize, newpos; - Py_ssize_t esize, start, end; - const char *reason; - - if (e > 0) { - reason = "illegal multibyte sequence"; - esize = e; - } - else { - switch (e) { - case MBERR_TOOSMALL: - REQUIRE_ENCODEBUFFER(buf, -1); - return 0; /* retry it */ - case MBERR_TOOFEW: - reason = "incomplete multibyte sequence"; - esize = (Py_ssize_t)(buf->inbuf_end - buf->inbuf); - break; - case MBERR_INTERNAL: - PyErr_SetString(PyExc_RuntimeError, - "internal codec error"); - return -1; - default: - PyErr_SetString(PyExc_RuntimeError, - "unknown runtime error"); - return -1; - } - } - - if (errors == ERROR_REPLACE) { - const Py_UNICODE replchar = '?', *inbuf = &replchar; - Py_ssize_t r; - - for (;;) { - Py_ssize_t outleft; - - outleft = (Py_ssize_t)(buf->outbuf_end - buf->outbuf); - r = codec->encode(state, codec->config, &inbuf, 1, - &buf->outbuf, outleft, 0); - if (r == MBERR_TOOSMALL) { - REQUIRE_ENCODEBUFFER(buf, -1); - continue; - } - else - break; - } - - if (r != 0) { - REQUIRE_ENCODEBUFFER(buf, 1); - *buf->outbuf++ = '?'; - } - } - if (errors == ERROR_IGNORE || errors == ERROR_REPLACE) { - buf->inbuf += esize; - return 0; - } - - start = (Py_ssize_t)(buf->inbuf - buf->inbuf_top); - end = start + esize; - - /* use cached exception object if available */ - if (buf->excobj == NULL) { - buf->excobj = PyUnicodeEncodeError_Create(codec->encoding, - buf->inbuf_top, - buf->inbuf_end - buf->inbuf_top, - start, end, reason); - if (buf->excobj == NULL) - goto errorexit; - } - else - if (PyUnicodeEncodeError_SetStart(buf->excobj, start) != 0 || - PyUnicodeEncodeError_SetEnd(buf->excobj, end) != 0 || - PyUnicodeEncodeError_SetReason(buf->excobj, reason) != 0) - goto errorexit; - - if (errors == ERROR_STRICT) { - PyCodec_StrictErrors(buf->excobj); - goto errorexit; - } - - retobj = call_error_callback(errors, buf->excobj); - if (retobj == NULL) - goto errorexit; - - if (!PyTuple_Check(retobj) || PyTuple_GET_SIZE(retobj) != 2 || - !PyUnicode_Check((tobj = PyTuple_GET_ITEM(retobj, 0))) || - !PyLong_Check(PyTuple_GET_ITEM(retobj, 1))) { - PyErr_SetString(PyExc_TypeError, - "encoding error handler must return " - "(unicode, int) tuple"); - goto errorexit; - } - - { - const Py_UNICODE *uraw = PyUnicode_AS_UNICODE(tobj); - - retstr = multibytecodec_encode(codec, state, &uraw, - PyUnicode_GET_SIZE(tobj), ERROR_STRICT, - MBENC_FLUSH); - if (retstr == NULL) - goto errorexit; - } - - assert(PyBytes_Check(retstr)); - retstrsize = PyBytes_GET_SIZE(retstr); - REQUIRE_ENCODEBUFFER(buf, retstrsize); - - memcpy(buf->outbuf, PyBytes_AS_STRING(retstr), retstrsize); - buf->outbuf += retstrsize; - - newpos = PyLong_AsSsize_t(PyTuple_GET_ITEM(retobj, 1)); - if (newpos < 0 && !PyErr_Occurred()) - newpos += (Py_ssize_t)(buf->inbuf_end - buf->inbuf_top); - if (newpos < 0 || buf->inbuf_top + newpos > buf->inbuf_end) { - PyErr_Clear(); - PyErr_Format(PyExc_IndexError, - "position %zd from error handler out of bounds", - newpos); - goto errorexit; - } - buf->inbuf = buf->inbuf_top + newpos; - - Py_DECREF(retobj); - Py_DECREF(retstr); - return 0; + MultibyteCodec_State *state, + MultibyteEncodeBuffer *buf, + PyObject *errors, Py_ssize_t e) +{ + PyObject *retobj = NULL, *retstr = NULL, *tobj; + Py_ssize_t retstrsize, newpos; + Py_ssize_t esize, start, end; + const char *reason; + + if (e > 0) { + reason = "illegal multibyte sequence"; + esize = e; + } + else { + switch (e) { + case MBERR_TOOSMALL: + REQUIRE_ENCODEBUFFER(buf, -1); + return 0; /* retry it */ + case MBERR_TOOFEW: + reason = "incomplete multibyte sequence"; + esize = (Py_ssize_t)(buf->inbuf_end - buf->inbuf); + break; + case MBERR_INTERNAL: + PyErr_SetString(PyExc_RuntimeError, + "internal codec error"); + return -1; + default: + PyErr_SetString(PyExc_RuntimeError, + "unknown runtime error"); + return -1; + } + } + + if (errors == ERROR_REPLACE) { + const Py_UNICODE replchar = '?', *inbuf = &replchar; + Py_ssize_t r; + + for (;;) { + Py_ssize_t outleft; + + outleft = (Py_ssize_t)(buf->outbuf_end - buf->outbuf); + r = codec->encode(state, codec->config, &inbuf, 1, + &buf->outbuf, outleft, 0); + if (r == MBERR_TOOSMALL) { + REQUIRE_ENCODEBUFFER(buf, -1); + continue; + } + else + break; + } + + if (r != 0) { + REQUIRE_ENCODEBUFFER(buf, 1); + *buf->outbuf++ = '?'; + } + } + if (errors == ERROR_IGNORE || errors == ERROR_REPLACE) { + buf->inbuf += esize; + return 0; + } + + start = (Py_ssize_t)(buf->inbuf - buf->inbuf_top); + end = start + esize; + + /* use cached exception object if available */ + if (buf->excobj == NULL) { + buf->excobj = PyUnicodeEncodeError_Create(codec->encoding, + buf->inbuf_top, + buf->inbuf_end - buf->inbuf_top, + start, end, reason); + if (buf->excobj == NULL) + goto errorexit; + } + else + if (PyUnicodeEncodeError_SetStart(buf->excobj, start) != 0 || + PyUnicodeEncodeError_SetEnd(buf->excobj, end) != 0 || + PyUnicodeEncodeError_SetReason(buf->excobj, reason) != 0) + goto errorexit; + + if (errors == ERROR_STRICT) { + PyCodec_StrictErrors(buf->excobj); + goto errorexit; + } + + retobj = call_error_callback(errors, buf->excobj); + if (retobj == NULL) + goto errorexit; + + if (!PyTuple_Check(retobj) || PyTuple_GET_SIZE(retobj) != 2 || + !PyUnicode_Check((tobj = PyTuple_GET_ITEM(retobj, 0))) || + !PyLong_Check(PyTuple_GET_ITEM(retobj, 1))) { + PyErr_SetString(PyExc_TypeError, + "encoding error handler must return " + "(unicode, int) tuple"); + goto errorexit; + } + + { + const Py_UNICODE *uraw = PyUnicode_AS_UNICODE(tobj); + + retstr = multibytecodec_encode(codec, state, &uraw, + PyUnicode_GET_SIZE(tobj), ERROR_STRICT, + MBENC_FLUSH); + if (retstr == NULL) + goto errorexit; + } + + assert(PyBytes_Check(retstr)); + retstrsize = PyBytes_GET_SIZE(retstr); + REQUIRE_ENCODEBUFFER(buf, retstrsize); + + memcpy(buf->outbuf, PyBytes_AS_STRING(retstr), retstrsize); + buf->outbuf += retstrsize; + + newpos = PyLong_AsSsize_t(PyTuple_GET_ITEM(retobj, 1)); + if (newpos < 0 && !PyErr_Occurred()) + newpos += (Py_ssize_t)(buf->inbuf_end - buf->inbuf_top); + if (newpos < 0 || buf->inbuf_top + newpos > buf->inbuf_end) { + PyErr_Clear(); + PyErr_Format(PyExc_IndexError, + "position %zd from error handler out of bounds", + newpos); + goto errorexit; + } + buf->inbuf = buf->inbuf_top + newpos; + + Py_DECREF(retobj); + Py_DECREF(retstr); + return 0; errorexit: - Py_XDECREF(retobj); - Py_XDECREF(retstr); - return -1; + Py_XDECREF(retobj); + Py_XDECREF(retstr); + return -1; } static int multibytecodec_decerror(MultibyteCodec *codec, - MultibyteCodec_State *state, - MultibyteDecodeBuffer *buf, - PyObject *errors, Py_ssize_t e) -{ - PyObject *retobj = NULL, *retuni = NULL; - Py_ssize_t retunisize, newpos; - const char *reason; - Py_ssize_t esize, start, end; - - if (e > 0) { - reason = "illegal multibyte sequence"; - esize = e; - } - else { - switch (e) { - case MBERR_TOOSMALL: - REQUIRE_DECODEBUFFER(buf, -1); - return 0; /* retry it */ - case MBERR_TOOFEW: - reason = "incomplete multibyte sequence"; - esize = (Py_ssize_t)(buf->inbuf_end - buf->inbuf); - break; - case MBERR_INTERNAL: - PyErr_SetString(PyExc_RuntimeError, - "internal codec error"); - return -1; - default: - PyErr_SetString(PyExc_RuntimeError, - "unknown runtime error"); - return -1; - } - } - - if (errors == ERROR_REPLACE) { - REQUIRE_DECODEBUFFER(buf, 1); - *buf->outbuf++ = Py_UNICODE_REPLACEMENT_CHARACTER; - } - if (errors == ERROR_IGNORE || errors == ERROR_REPLACE) { - buf->inbuf += esize; - return 0; - } - - start = (Py_ssize_t)(buf->inbuf - buf->inbuf_top); - end = start + esize; - - /* use cached exception object if available */ - if (buf->excobj == NULL) { - buf->excobj = PyUnicodeDecodeError_Create(codec->encoding, - (const char *)buf->inbuf_top, - (Py_ssize_t)(buf->inbuf_end - buf->inbuf_top), - start, end, reason); - if (buf->excobj == NULL) - goto errorexit; - } - else - if (PyUnicodeDecodeError_SetStart(buf->excobj, start) || - PyUnicodeDecodeError_SetEnd(buf->excobj, end) || - PyUnicodeDecodeError_SetReason(buf->excobj, reason)) - goto errorexit; - - if (errors == ERROR_STRICT) { - PyCodec_StrictErrors(buf->excobj); - goto errorexit; - } - - retobj = call_error_callback(errors, buf->excobj); - if (retobj == NULL) - goto errorexit; - - if (!PyTuple_Check(retobj) || PyTuple_GET_SIZE(retobj) != 2 || - !PyUnicode_Check((retuni = PyTuple_GET_ITEM(retobj, 0))) || - !PyLong_Check(PyTuple_GET_ITEM(retobj, 1))) { - PyErr_SetString(PyExc_TypeError, - "decoding error handler must return " - "(unicode, int) tuple"); - goto errorexit; - } - - retunisize = PyUnicode_GET_SIZE(retuni); - if (retunisize > 0) { - REQUIRE_DECODEBUFFER(buf, retunisize); - memcpy((char *)buf->outbuf, PyUnicode_AS_DATA(retuni), - retunisize * Py_UNICODE_SIZE); - buf->outbuf += retunisize; - } - - newpos = PyLong_AsSsize_t(PyTuple_GET_ITEM(retobj, 1)); - if (newpos < 0 && !PyErr_Occurred()) - newpos += (Py_ssize_t)(buf->inbuf_end - buf->inbuf_top); - if (newpos < 0 || buf->inbuf_top + newpos > buf->inbuf_end) { - PyErr_Clear(); - PyErr_Format(PyExc_IndexError, - "position %zd from error handler out of bounds", - newpos); - goto errorexit; - } - buf->inbuf = buf->inbuf_top + newpos; - Py_DECREF(retobj); - return 0; + MultibyteCodec_State *state, + MultibyteDecodeBuffer *buf, + PyObject *errors, Py_ssize_t e) +{ + PyObject *retobj = NULL, *retuni = NULL; + Py_ssize_t retunisize, newpos; + const char *reason; + Py_ssize_t esize, start, end; + + if (e > 0) { + reason = "illegal multibyte sequence"; + esize = e; + } + else { + switch (e) { + case MBERR_TOOSMALL: + REQUIRE_DECODEBUFFER(buf, -1); + return 0; /* retry it */ + case MBERR_TOOFEW: + reason = "incomplete multibyte sequence"; + esize = (Py_ssize_t)(buf->inbuf_end - buf->inbuf); + break; + case MBERR_INTERNAL: + PyErr_SetString(PyExc_RuntimeError, + "internal codec error"); + return -1; + default: + PyErr_SetString(PyExc_RuntimeError, + "unknown runtime error"); + return -1; + } + } + + if (errors == ERROR_REPLACE) { + REQUIRE_DECODEBUFFER(buf, 1); + *buf->outbuf++ = Py_UNICODE_REPLACEMENT_CHARACTER; + } + if (errors == ERROR_IGNORE || errors == ERROR_REPLACE) { + buf->inbuf += esize; + return 0; + } + + start = (Py_ssize_t)(buf->inbuf - buf->inbuf_top); + end = start + esize; + + /* use cached exception object if available */ + if (buf->excobj == NULL) { + buf->excobj = PyUnicodeDecodeError_Create(codec->encoding, + (const char *)buf->inbuf_top, + (Py_ssize_t)(buf->inbuf_end - buf->inbuf_top), + start, end, reason); + if (buf->excobj == NULL) + goto errorexit; + } + else + if (PyUnicodeDecodeError_SetStart(buf->excobj, start) || + PyUnicodeDecodeError_SetEnd(buf->excobj, end) || + PyUnicodeDecodeError_SetReason(buf->excobj, reason)) + goto errorexit; + + if (errors == ERROR_STRICT) { + PyCodec_StrictErrors(buf->excobj); + goto errorexit; + } + + retobj = call_error_callback(errors, buf->excobj); + if (retobj == NULL) + goto errorexit; + + if (!PyTuple_Check(retobj) || PyTuple_GET_SIZE(retobj) != 2 || + !PyUnicode_Check((retuni = PyTuple_GET_ITEM(retobj, 0))) || + !PyLong_Check(PyTuple_GET_ITEM(retobj, 1))) { + PyErr_SetString(PyExc_TypeError, + "decoding error handler must return " + "(unicode, int) tuple"); + goto errorexit; + } + + retunisize = PyUnicode_GET_SIZE(retuni); + if (retunisize > 0) { + REQUIRE_DECODEBUFFER(buf, retunisize); + memcpy((char *)buf->outbuf, PyUnicode_AS_DATA(retuni), + retunisize * Py_UNICODE_SIZE); + buf->outbuf += retunisize; + } + + newpos = PyLong_AsSsize_t(PyTuple_GET_ITEM(retobj, 1)); + if (newpos < 0 && !PyErr_Occurred()) + newpos += (Py_ssize_t)(buf->inbuf_end - buf->inbuf_top); + if (newpos < 0 || buf->inbuf_top + newpos > buf->inbuf_end) { + PyErr_Clear(); + PyErr_Format(PyExc_IndexError, + "position %zd from error handler out of bounds", + newpos); + goto errorexit; + } + buf->inbuf = buf->inbuf_top + newpos; + Py_DECREF(retobj); + return 0; errorexit: - Py_XDECREF(retobj); - return -1; + Py_XDECREF(retobj); + return -1; } static PyObject * multibytecodec_encode(MultibyteCodec *codec, - MultibyteCodec_State *state, - const Py_UNICODE **data, Py_ssize_t datalen, - PyObject *errors, int flags) -{ - MultibyteEncodeBuffer buf; - Py_ssize_t finalsize, r = 0; - - if (datalen == 0) - return PyBytes_FromStringAndSize(NULL, 0); - - buf.excobj = NULL; - buf.inbuf = buf.inbuf_top = *data; - buf.inbuf_end = buf.inbuf_top + datalen; - - if (datalen > (PY_SSIZE_T_MAX - 16) / 2) { - PyErr_NoMemory(); - goto errorexit; - } - - buf.outobj = PyBytes_FromStringAndSize(NULL, datalen * 2 + 16); - if (buf.outobj == NULL) - goto errorexit; - buf.outbuf = (unsigned char *)PyBytes_AS_STRING(buf.outobj); - buf.outbuf_end = buf.outbuf + PyBytes_GET_SIZE(buf.outobj); - - while (buf.inbuf < buf.inbuf_end) { - Py_ssize_t inleft, outleft; - - /* we don't reuse inleft and outleft here. - * error callbacks can relocate the cursor anywhere on buffer*/ - inleft = (Py_ssize_t)(buf.inbuf_end - buf.inbuf); - outleft = (Py_ssize_t)(buf.outbuf_end - buf.outbuf); - r = codec->encode(state, codec->config, &buf.inbuf, inleft, - &buf.outbuf, outleft, flags); - if ((r == 0) || (r == MBERR_TOOFEW && !(flags & MBENC_FLUSH))) - break; - else if (multibytecodec_encerror(codec, state, &buf, errors,r)) - goto errorexit; - else if (r == MBERR_TOOFEW) - break; - } - - if (codec->encreset != NULL) - for (;;) { - Py_ssize_t outleft; - - outleft = (Py_ssize_t)(buf.outbuf_end - buf.outbuf); - r = codec->encreset(state, codec->config, &buf.outbuf, - outleft); - if (r == 0) - break; - else if (multibytecodec_encerror(codec, state, - &buf, errors, r)) - goto errorexit; - } - - finalsize = (Py_ssize_t)((char *)buf.outbuf - - PyBytes_AS_STRING(buf.outobj)); - - if (finalsize != PyBytes_GET_SIZE(buf.outobj)) - if (_PyBytes_Resize(&buf.outobj, finalsize) == -1) - goto errorexit; - - *data = buf.inbuf; - Py_XDECREF(buf.excobj); - return buf.outobj; + MultibyteCodec_State *state, + const Py_UNICODE **data, Py_ssize_t datalen, + PyObject *errors, int flags) +{ + MultibyteEncodeBuffer buf; + Py_ssize_t finalsize, r = 0; + + if (datalen == 0) + return PyBytes_FromStringAndSize(NULL, 0); + + buf.excobj = NULL; + buf.inbuf = buf.inbuf_top = *data; + buf.inbuf_end = buf.inbuf_top + datalen; + + if (datalen > (PY_SSIZE_T_MAX - 16) / 2) { + PyErr_NoMemory(); + goto errorexit; + } + + buf.outobj = PyBytes_FromStringAndSize(NULL, datalen * 2 + 16); + if (buf.outobj == NULL) + goto errorexit; + buf.outbuf = (unsigned char *)PyBytes_AS_STRING(buf.outobj); + buf.outbuf_end = buf.outbuf + PyBytes_GET_SIZE(buf.outobj); + + while (buf.inbuf < buf.inbuf_end) { + Py_ssize_t inleft, outleft; + + /* we don't reuse inleft and outleft here. + * error callbacks can relocate the cursor anywhere on buffer*/ + inleft = (Py_ssize_t)(buf.inbuf_end - buf.inbuf); + outleft = (Py_ssize_t)(buf.outbuf_end - buf.outbuf); + r = codec->encode(state, codec->config, &buf.inbuf, inleft, + &buf.outbuf, outleft, flags); + if ((r == 0) || (r == MBERR_TOOFEW && !(flags & MBENC_FLUSH))) + break; + else if (multibytecodec_encerror(codec, state, &buf, errors,r)) + goto errorexit; + else if (r == MBERR_TOOFEW) + break; + } + + if (codec->encreset != NULL) + for (;;) { + Py_ssize_t outleft; + + outleft = (Py_ssize_t)(buf.outbuf_end - buf.outbuf); + r = codec->encreset(state, codec->config, &buf.outbuf, + outleft); + if (r == 0) + break; + else if (multibytecodec_encerror(codec, state, + &buf, errors, r)) + goto errorexit; + } + + finalsize = (Py_ssize_t)((char *)buf.outbuf - + PyBytes_AS_STRING(buf.outobj)); + + if (finalsize != PyBytes_GET_SIZE(buf.outobj)) + if (_PyBytes_Resize(&buf.outobj, finalsize) == -1) + goto errorexit; + + *data = buf.inbuf; + Py_XDECREF(buf.excobj); + return buf.outobj; errorexit: - Py_XDECREF(buf.excobj); - Py_XDECREF(buf.outobj); - return NULL; + Py_XDECREF(buf.excobj); + Py_XDECREF(buf.outobj); + return NULL; } static PyObject * MultibyteCodec_Encode(MultibyteCodecObject *self, - PyObject *args, PyObject *kwargs) + PyObject *args, PyObject *kwargs) { - MultibyteCodec_State state; - Py_UNICODE *data; - PyObject *errorcb, *r, *arg, *ucvt; - const char *errors = NULL; - Py_ssize_t datalen; - - if (!PyArg_ParseTupleAndKeywords(args, kwargs, "O|z:encode", - codeckwarglist, &arg, &errors)) - return NULL; - - if (PyUnicode_Check(arg)) - ucvt = NULL; - else { - arg = ucvt = PyObject_Str(arg); - if (arg == NULL) - return NULL; - else if (!PyUnicode_Check(arg)) { - PyErr_SetString(PyExc_TypeError, - "couldn't convert the object to unicode."); - Py_DECREF(ucvt); - return NULL; - } - } - - data = PyUnicode_AS_UNICODE(arg); - datalen = PyUnicode_GET_SIZE(arg); - - errorcb = internal_error_callback(errors); - if (errorcb == NULL) { - Py_XDECREF(ucvt); - return NULL; - } - - if (self->codec->encinit != NULL && - self->codec->encinit(&state, self->codec->config) != 0) - goto errorexit; - r = multibytecodec_encode(self->codec, &state, - (const Py_UNICODE **)&data, datalen, errorcb, - MBENC_FLUSH | MBENC_RESET); - if (r == NULL) - goto errorexit; - - ERROR_DECREF(errorcb); - Py_XDECREF(ucvt); - return make_tuple(r, datalen); + MultibyteCodec_State state; + Py_UNICODE *data; + PyObject *errorcb, *r, *arg, *ucvt; + const char *errors = NULL; + Py_ssize_t datalen; + + if (!PyArg_ParseTupleAndKeywords(args, kwargs, "O|z:encode", + codeckwarglist, &arg, &errors)) + return NULL; + + if (PyUnicode_Check(arg)) + ucvt = NULL; + else { + arg = ucvt = PyObject_Str(arg); + if (arg == NULL) + return NULL; + else if (!PyUnicode_Check(arg)) { + PyErr_SetString(PyExc_TypeError, + "couldn't convert the object to unicode."); + Py_DECREF(ucvt); + return NULL; + } + } + + data = PyUnicode_AS_UNICODE(arg); + datalen = PyUnicode_GET_SIZE(arg); + + errorcb = internal_error_callback(errors); + if (errorcb == NULL) { + Py_XDECREF(ucvt); + return NULL; + } + + if (self->codec->encinit != NULL && + self->codec->encinit(&state, self->codec->config) != 0) + goto errorexit; + r = multibytecodec_encode(self->codec, &state, + (const Py_UNICODE **)&data, datalen, errorcb, + MBENC_FLUSH | MBENC_RESET); + if (r == NULL) + goto errorexit; + + ERROR_DECREF(errorcb); + Py_XDECREF(ucvt); + return make_tuple(r, datalen); errorexit: - ERROR_DECREF(errorcb); - Py_XDECREF(ucvt); - return NULL; + ERROR_DECREF(errorcb); + Py_XDECREF(ucvt); + return NULL; } static PyObject * MultibyteCodec_Decode(MultibyteCodecObject *self, - PyObject *args, PyObject *kwargs) + PyObject *args, PyObject *kwargs) { - MultibyteCodec_State state; - MultibyteDecodeBuffer buf; - PyObject *errorcb; - Py_buffer pdata; - const char *data, *errors = NULL; - Py_ssize_t datalen, finalsize; - - if (!PyArg_ParseTupleAndKeywords(args, kwargs, "y*|z:decode", - codeckwarglist, &pdata, &errors)) - return NULL; - data = pdata.buf; - datalen = pdata.len; - - errorcb = internal_error_callback(errors); - if (errorcb == NULL) { - PyBuffer_Release(&pdata); - return NULL; - } - - if (datalen == 0) { - PyBuffer_Release(&pdata); - ERROR_DECREF(errorcb); - return make_tuple(PyUnicode_FromUnicode(NULL, 0), 0); - } - - buf.excobj = NULL; - buf.inbuf = buf.inbuf_top = (unsigned char *)data; - buf.inbuf_end = buf.inbuf_top + datalen; - buf.outobj = PyUnicode_FromUnicode(NULL, datalen); - if (buf.outobj == NULL) - goto errorexit; - buf.outbuf = PyUnicode_AS_UNICODE(buf.outobj); - buf.outbuf_end = buf.outbuf + PyUnicode_GET_SIZE(buf.outobj); - - if (self->codec->decinit != NULL && - self->codec->decinit(&state, self->codec->config) != 0) - goto errorexit; - - while (buf.inbuf < buf.inbuf_end) { - Py_ssize_t inleft, outleft, r; - - inleft = (Py_ssize_t)(buf.inbuf_end - buf.inbuf); - outleft = (Py_ssize_t)(buf.outbuf_end - buf.outbuf); - - r = self->codec->decode(&state, self->codec->config, - &buf.inbuf, inleft, &buf.outbuf, outleft); - if (r == 0) - break; - else if (multibytecodec_decerror(self->codec, &state, - &buf, errorcb, r)) - goto errorexit; - } - - finalsize = (Py_ssize_t)(buf.outbuf - - PyUnicode_AS_UNICODE(buf.outobj)); - - if (finalsize != PyUnicode_GET_SIZE(buf.outobj)) - if (PyUnicode_Resize(&buf.outobj, finalsize) == -1) - goto errorexit; - - PyBuffer_Release(&pdata); - Py_XDECREF(buf.excobj); - ERROR_DECREF(errorcb); - return make_tuple(buf.outobj, datalen); + MultibyteCodec_State state; + MultibyteDecodeBuffer buf; + PyObject *errorcb; + Py_buffer pdata; + const char *data, *errors = NULL; + Py_ssize_t datalen, finalsize; + + if (!PyArg_ParseTupleAndKeywords(args, kwargs, "y*|z:decode", + codeckwarglist, &pdata, &errors)) + return NULL; + data = pdata.buf; + datalen = pdata.len; + + errorcb = internal_error_callback(errors); + if (errorcb == NULL) { + PyBuffer_Release(&pdata); + return NULL; + } + + if (datalen == 0) { + PyBuffer_Release(&pdata); + ERROR_DECREF(errorcb); + return make_tuple(PyUnicode_FromUnicode(NULL, 0), 0); + } + + buf.excobj = NULL; + buf.inbuf = buf.inbuf_top = (unsigned char *)data; + buf.inbuf_end = buf.inbuf_top + datalen; + buf.outobj = PyUnicode_FromUnicode(NULL, datalen); + if (buf.outobj == NULL) + goto errorexit; + buf.outbuf = PyUnicode_AS_UNICODE(buf.outobj); + buf.outbuf_end = buf.outbuf + PyUnicode_GET_SIZE(buf.outobj); + + if (self->codec->decinit != NULL && + self->codec->decinit(&state, self->codec->config) != 0) + goto errorexit; + + while (buf.inbuf < buf.inbuf_end) { + Py_ssize_t inleft, outleft, r; + + inleft = (Py_ssize_t)(buf.inbuf_end - buf.inbuf); + outleft = (Py_ssize_t)(buf.outbuf_end - buf.outbuf); + + r = self->codec->decode(&state, self->codec->config, + &buf.inbuf, inleft, &buf.outbuf, outleft); + if (r == 0) + break; + else if (multibytecodec_decerror(self->codec, &state, + &buf, errorcb, r)) + goto errorexit; + } + + finalsize = (Py_ssize_t)(buf.outbuf - + PyUnicode_AS_UNICODE(buf.outobj)); + + if (finalsize != PyUnicode_GET_SIZE(buf.outobj)) + if (PyUnicode_Resize(&buf.outobj, finalsize) == -1) + goto errorexit; + + PyBuffer_Release(&pdata); + Py_XDECREF(buf.excobj); + ERROR_DECREF(errorcb); + return make_tuple(buf.outobj, datalen); errorexit: - PyBuffer_Release(&pdata); - ERROR_DECREF(errorcb); - Py_XDECREF(buf.excobj); - Py_XDECREF(buf.outobj); + PyBuffer_Release(&pdata); + ERROR_DECREF(errorcb); + Py_XDECREF(buf.excobj); + Py_XDECREF(buf.outobj); - return NULL; + return NULL; } static struct PyMethodDef multibytecodec_methods[] = { - {"encode", (PyCFunction)MultibyteCodec_Encode, - METH_VARARGS | METH_KEYWORDS, - MultibyteCodec_Encode__doc__}, - {"decode", (PyCFunction)MultibyteCodec_Decode, - METH_VARARGS | METH_KEYWORDS, - MultibyteCodec_Decode__doc__}, - {NULL, NULL}, + {"encode", (PyCFunction)MultibyteCodec_Encode, + METH_VARARGS | METH_KEYWORDS, + MultibyteCodec_Encode__doc__}, + {"decode", (PyCFunction)MultibyteCodec_Decode, + METH_VARARGS | METH_KEYWORDS, + MultibyteCodec_Decode__doc__}, + {NULL, NULL}, }; static void multibytecodec_dealloc(MultibyteCodecObject *self) { - PyObject_Del(self); + PyObject_Del(self); } static PyTypeObject MultibyteCodec_Type = { - PyVarObject_HEAD_INIT(NULL, 0) - "MultibyteCodec", /* tp_name */ - sizeof(MultibyteCodecObject), /* tp_basicsize */ - 0, /* tp_itemsize */ - /* methods */ - (destructor)multibytecodec_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, /* tp_flags */ - 0, /* tp_doc */ - 0, /* tp_traverse */ - 0, /* tp_clear */ - 0, /* tp_richcompare */ - 0, /* tp_weaklistoffset */ - 0, /* tp_iter */ - 0, /* tp_iterext */ - multibytecodec_methods, /* tp_methods */ + PyVarObject_HEAD_INIT(NULL, 0) + "MultibyteCodec", /* tp_name */ + sizeof(MultibyteCodecObject), /* tp_basicsize */ + 0, /* tp_itemsize */ + /* methods */ + (destructor)multibytecodec_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, /* tp_flags */ + 0, /* tp_doc */ + 0, /* tp_traverse */ + 0, /* tp_clear */ + 0, /* tp_richcompare */ + 0, /* tp_weaklistoffset */ + 0, /* tp_iter */ + 0, /* tp_iterext */ + multibytecodec_methods, /* tp_methods */ }; @@ -732,150 +732,150 @@ * Utility functions for stateful codec mechanism */ -#define STATEFUL_DCTX(o) ((MultibyteStatefulDecoderContext *)(o)) -#define STATEFUL_ECTX(o) ((MultibyteStatefulEncoderContext *)(o)) +#define STATEFUL_DCTX(o) ((MultibyteStatefulDecoderContext *)(o)) +#define STATEFUL_ECTX(o) ((MultibyteStatefulEncoderContext *)(o)) static PyObject * encoder_encode_stateful(MultibyteStatefulEncoderContext *ctx, - PyObject *unistr, int final) + PyObject *unistr, int final) { - PyObject *ucvt, *r = NULL; - Py_UNICODE *inbuf, *inbuf_end, *inbuf_tmp = NULL; - Py_ssize_t datalen, origpending; - - if (PyUnicode_Check(unistr)) - ucvt = NULL; - else { - unistr = ucvt = PyObject_Str(unistr); - if (unistr == NULL) - return NULL; - else if (!PyUnicode_Check(unistr)) { - PyErr_SetString(PyExc_TypeError, - "couldn't convert the object to unicode."); - Py_DECREF(ucvt); - return NULL; - } - } - - datalen = PyUnicode_GET_SIZE(unistr); - origpending = ctx->pendingsize; - - if (origpending > 0) { - if (datalen > PY_SSIZE_T_MAX - ctx->pendingsize) { - PyErr_NoMemory(); - /* inbuf_tmp == NULL */ - goto errorexit; - } - inbuf_tmp = PyMem_New(Py_UNICODE, datalen + ctx->pendingsize); - if (inbuf_tmp == NULL) - goto errorexit; - memcpy(inbuf_tmp, ctx->pending, - Py_UNICODE_SIZE * ctx->pendingsize); - memcpy(inbuf_tmp + ctx->pendingsize, - PyUnicode_AS_UNICODE(unistr), - Py_UNICODE_SIZE * datalen); - datalen += ctx->pendingsize; - ctx->pendingsize = 0; - inbuf = inbuf_tmp; - } - else - inbuf = (Py_UNICODE *)PyUnicode_AS_UNICODE(unistr); - - inbuf_end = inbuf + datalen; - - r = multibytecodec_encode(ctx->codec, &ctx->state, - (const Py_UNICODE **)&inbuf, - datalen, ctx->errors, final ? MBENC_FLUSH : 0); - if (r == NULL) { - /* recover the original pending buffer */ - if (origpending > 0) - memcpy(ctx->pending, inbuf_tmp, - Py_UNICODE_SIZE * origpending); - ctx->pendingsize = origpending; - goto errorexit; - } - - if (inbuf < inbuf_end) { - ctx->pendingsize = (Py_ssize_t)(inbuf_end - inbuf); - if (ctx->pendingsize > MAXENCPENDING) { - /* normal codecs can't reach here */ - ctx->pendingsize = 0; - PyErr_SetString(PyExc_UnicodeError, - "pending buffer overflow"); - goto errorexit; - } - memcpy(ctx->pending, inbuf, - ctx->pendingsize * Py_UNICODE_SIZE); - } - - if (inbuf_tmp != NULL) - PyMem_Del(inbuf_tmp); - Py_XDECREF(ucvt); - return r; + PyObject *ucvt, *r = NULL; + Py_UNICODE *inbuf, *inbuf_end, *inbuf_tmp = NULL; + Py_ssize_t datalen, origpending; + + if (PyUnicode_Check(unistr)) + ucvt = NULL; + else { + unistr = ucvt = PyObject_Str(unistr); + if (unistr == NULL) + return NULL; + else if (!PyUnicode_Check(unistr)) { + PyErr_SetString(PyExc_TypeError, + "couldn't convert the object to unicode."); + Py_DECREF(ucvt); + return NULL; + } + } + + datalen = PyUnicode_GET_SIZE(unistr); + origpending = ctx->pendingsize; + + if (origpending > 0) { + if (datalen > PY_SSIZE_T_MAX - ctx->pendingsize) { + PyErr_NoMemory(); + /* inbuf_tmp == NULL */ + goto errorexit; + } + inbuf_tmp = PyMem_New(Py_UNICODE, datalen + ctx->pendingsize); + if (inbuf_tmp == NULL) + goto errorexit; + memcpy(inbuf_tmp, ctx->pending, + Py_UNICODE_SIZE * ctx->pendingsize); + memcpy(inbuf_tmp + ctx->pendingsize, + PyUnicode_AS_UNICODE(unistr), + Py_UNICODE_SIZE * datalen); + datalen += ctx->pendingsize; + ctx->pendingsize = 0; + inbuf = inbuf_tmp; + } + else + inbuf = (Py_UNICODE *)PyUnicode_AS_UNICODE(unistr); + + inbuf_end = inbuf + datalen; + + r = multibytecodec_encode(ctx->codec, &ctx->state, + (const Py_UNICODE **)&inbuf, + datalen, ctx->errors, final ? MBENC_FLUSH : 0); + if (r == NULL) { + /* recover the original pending buffer */ + if (origpending > 0) + memcpy(ctx->pending, inbuf_tmp, + Py_UNICODE_SIZE * origpending); + ctx->pendingsize = origpending; + goto errorexit; + } + + if (inbuf < inbuf_end) { + ctx->pendingsize = (Py_ssize_t)(inbuf_end - inbuf); + if (ctx->pendingsize > MAXENCPENDING) { + /* normal codecs can't reach here */ + ctx->pendingsize = 0; + PyErr_SetString(PyExc_UnicodeError, + "pending buffer overflow"); + goto errorexit; + } + memcpy(ctx->pending, inbuf, + ctx->pendingsize * Py_UNICODE_SIZE); + } + + if (inbuf_tmp != NULL) + PyMem_Del(inbuf_tmp); + Py_XDECREF(ucvt); + return r; errorexit: - if (inbuf_tmp != NULL) - PyMem_Del(inbuf_tmp); - Py_XDECREF(r); - Py_XDECREF(ucvt); - return NULL; + if (inbuf_tmp != NULL) + PyMem_Del(inbuf_tmp); + Py_XDECREF(r); + Py_XDECREF(ucvt); + return NULL; } static int decoder_append_pending(MultibyteStatefulDecoderContext *ctx, - MultibyteDecodeBuffer *buf) + MultibyteDecodeBuffer *buf) { - Py_ssize_t npendings; + Py_ssize_t npendings; - npendings = (Py_ssize_t)(buf->inbuf_end - buf->inbuf); - if (npendings + ctx->pendingsize > MAXDECPENDING || - npendings > PY_SSIZE_T_MAX - ctx->pendingsize) { - PyErr_SetString(PyExc_UnicodeError, "pending buffer overflow"); - return -1; - } - memcpy(ctx->pending + ctx->pendingsize, buf->inbuf, npendings); - ctx->pendingsize += npendings; - return 0; + npendings = (Py_ssize_t)(buf->inbuf_end - buf->inbuf); + if (npendings + ctx->pendingsize > MAXDECPENDING || + npendings > PY_SSIZE_T_MAX - ctx->pendingsize) { + PyErr_SetString(PyExc_UnicodeError, "pending buffer overflow"); + return -1; + } + memcpy(ctx->pending + ctx->pendingsize, buf->inbuf, npendings); + ctx->pendingsize += npendings; + return 0; } static int decoder_prepare_buffer(MultibyteDecodeBuffer *buf, const char *data, - Py_ssize_t size) + Py_ssize_t size) { - buf->inbuf = buf->inbuf_top = (const unsigned char *)data; - buf->inbuf_end = buf->inbuf_top + size; - if (buf->outobj == NULL) { /* only if outobj is not allocated yet */ - buf->outobj = PyUnicode_FromUnicode(NULL, size); - if (buf->outobj == NULL) - return -1; - buf->outbuf = PyUnicode_AS_UNICODE(buf->outobj); - buf->outbuf_end = buf->outbuf + - PyUnicode_GET_SIZE(buf->outobj); - } + buf->inbuf = buf->inbuf_top = (const unsigned char *)data; + buf->inbuf_end = buf->inbuf_top + size; + if (buf->outobj == NULL) { /* only if outobj is not allocated yet */ + buf->outobj = PyUnicode_FromUnicode(NULL, size); + if (buf->outobj == NULL) + return -1; + buf->outbuf = PyUnicode_AS_UNICODE(buf->outobj); + buf->outbuf_end = buf->outbuf + + PyUnicode_GET_SIZE(buf->outobj); + } - return 0; + return 0; } static int decoder_feed_buffer(MultibyteStatefulDecoderContext *ctx, - MultibyteDecodeBuffer *buf) + MultibyteDecodeBuffer *buf) { - while (buf->inbuf < buf->inbuf_end) { - Py_ssize_t inleft, outleft; - Py_ssize_t r; - - inleft = (Py_ssize_t)(buf->inbuf_end - buf->inbuf); - outleft = (Py_ssize_t)(buf->outbuf_end - buf->outbuf); - - r = ctx->codec->decode(&ctx->state, ctx->codec->config, - &buf->inbuf, inleft, &buf->outbuf, outleft); - if (r == 0 || r == MBERR_TOOFEW) - break; - else if (multibytecodec_decerror(ctx->codec, &ctx->state, - buf, ctx->errors, r)) - return -1; - } - return 0; + while (buf->inbuf < buf->inbuf_end) { + Py_ssize_t inleft, outleft; + Py_ssize_t r; + + inleft = (Py_ssize_t)(buf->inbuf_end - buf->inbuf); + outleft = (Py_ssize_t)(buf->outbuf_end - buf->outbuf); + + r = ctx->codec->decode(&ctx->state, ctx->codec->config, + &buf->inbuf, inleft, &buf->outbuf, outleft); + if (r == 0 || r == MBERR_TOOFEW) + break; + else if (multibytecodec_decerror(ctx->codec, &ctx->state, + buf, ctx->errors, r)) + return -1; + } + return 0; } @@ -885,142 +885,142 @@ static PyObject * mbiencoder_encode(MultibyteIncrementalEncoderObject *self, - PyObject *args, PyObject *kwargs) + PyObject *args, PyObject *kwargs) { - PyObject *data; - int final = 0; + PyObject *data; + int final = 0; - if (!PyArg_ParseTupleAndKeywords(args, kwargs, "O|i:encode", - incrementalkwarglist, &data, &final)) - return NULL; + if (!PyArg_ParseTupleAndKeywords(args, kwargs, "O|i:encode", + incrementalkwarglist, &data, &final)) + return NULL; - return encoder_encode_stateful(STATEFUL_ECTX(self), data, final); + return encoder_encode_stateful(STATEFUL_ECTX(self), data, final); } static PyObject * mbiencoder_reset(MultibyteIncrementalEncoderObject *self) { - if (self->codec->decreset != NULL && - self->codec->decreset(&self->state, self->codec->config) != 0) - return NULL; - self->pendingsize = 0; + if (self->codec->decreset != NULL && + self->codec->decreset(&self->state, self->codec->config) != 0) + return NULL; + self->pendingsize = 0; - Py_RETURN_NONE; + Py_RETURN_NONE; } static struct PyMethodDef mbiencoder_methods[] = { - {"encode", (PyCFunction)mbiencoder_encode, - METH_VARARGS | METH_KEYWORDS, NULL}, - {"reset", (PyCFunction)mbiencoder_reset, - METH_NOARGS, NULL}, - {NULL, NULL}, + {"encode", (PyCFunction)mbiencoder_encode, + METH_VARARGS | METH_KEYWORDS, NULL}, + {"reset", (PyCFunction)mbiencoder_reset, + METH_NOARGS, NULL}, + {NULL, NULL}, }; static PyObject * mbiencoder_new(PyTypeObject *type, PyObject *args, PyObject *kwds) { - MultibyteIncrementalEncoderObject *self; - PyObject *codec = NULL; - char *errors = NULL; - - if (!PyArg_ParseTupleAndKeywords(args, kwds, "|s:IncrementalEncoder", - incnewkwarglist, &errors)) - return NULL; - - self = (MultibyteIncrementalEncoderObject *)type->tp_alloc(type, 0); - if (self == NULL) - return NULL; - - codec = PyObject_GetAttrString((PyObject *)type, "codec"); - if (codec == NULL) - goto errorexit; - if (!MultibyteCodec_Check(codec)) { - PyErr_SetString(PyExc_TypeError, "codec is unexpected type"); - goto errorexit; - } - - self->codec = ((MultibyteCodecObject *)codec)->codec; - self->pendingsize = 0; - self->errors = internal_error_callback(errors); - if (self->errors == NULL) - goto errorexit; - if (self->codec->encinit != NULL && - self->codec->encinit(&self->state, self->codec->config) != 0) - goto errorexit; + MultibyteIncrementalEncoderObject *self; + PyObject *codec = NULL; + char *errors = NULL; + + if (!PyArg_ParseTupleAndKeywords(args, kwds, "|s:IncrementalEncoder", + incnewkwarglist, &errors)) + return NULL; + + self = (MultibyteIncrementalEncoderObject *)type->tp_alloc(type, 0); + if (self == NULL) + return NULL; + + codec = PyObject_GetAttrString((PyObject *)type, "codec"); + if (codec == NULL) + goto errorexit; + if (!MultibyteCodec_Check(codec)) { + PyErr_SetString(PyExc_TypeError, "codec is unexpected type"); + goto errorexit; + } + + self->codec = ((MultibyteCodecObject *)codec)->codec; + self->pendingsize = 0; + self->errors = internal_error_callback(errors); + if (self->errors == NULL) + goto errorexit; + if (self->codec->encinit != NULL && + self->codec->encinit(&self->state, self->codec->config) != 0) + goto errorexit; - Py_DECREF(codec); - return (PyObject *)self; + Py_DECREF(codec); + return (PyObject *)self; errorexit: - Py_XDECREF(self); - Py_XDECREF(codec); - return NULL; + Py_XDECREF(self); + Py_XDECREF(codec); + return NULL; } static int mbiencoder_init(PyObject *self, PyObject *args, PyObject *kwds) { - return 0; + return 0; } static int mbiencoder_traverse(MultibyteIncrementalEncoderObject *self, - visitproc visit, void *arg) + visitproc visit, void *arg) { - if (ERROR_ISCUSTOM(self->errors)) - Py_VISIT(self->errors); - return 0; + if (ERROR_ISCUSTOM(self->errors)) + Py_VISIT(self->errors); + return 0; } static void mbiencoder_dealloc(MultibyteIncrementalEncoderObject *self) { - PyObject_GC_UnTrack(self); - ERROR_DECREF(self->errors); - Py_TYPE(self)->tp_free(self); + PyObject_GC_UnTrack(self); + ERROR_DECREF(self->errors); + Py_TYPE(self)->tp_free(self); } static PyTypeObject MultibyteIncrementalEncoder_Type = { - PyVarObject_HEAD_INIT(NULL, 0) - "MultibyteIncrementalEncoder", /* tp_name */ - sizeof(MultibyteIncrementalEncoderObject), /* tp_basicsize */ - 0, /* tp_itemsize */ - /* methods */ - (destructor)mbiencoder_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 - | Py_TPFLAGS_BASETYPE, /* tp_flags */ - 0, /* tp_doc */ - (traverseproc)mbiencoder_traverse, /* tp_traverse */ - 0, /* tp_clear */ - 0, /* tp_richcompare */ - 0, /* tp_weaklistoffset */ - 0, /* tp_iter */ - 0, /* tp_iterext */ - mbiencoder_methods, /* tp_methods */ - 0, /* tp_members */ - codecctx_getsets, /* tp_getset */ - 0, /* tp_base */ - 0, /* tp_dict */ - 0, /* tp_descr_get */ - 0, /* tp_descr_set */ - 0, /* tp_dictoffset */ - mbiencoder_init, /* tp_init */ - 0, /* tp_alloc */ - mbiencoder_new, /* tp_new */ + PyVarObject_HEAD_INIT(NULL, 0) + "MultibyteIncrementalEncoder", /* tp_name */ + sizeof(MultibyteIncrementalEncoderObject), /* tp_basicsize */ + 0, /* tp_itemsize */ + /* methods */ + (destructor)mbiencoder_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 + | Py_TPFLAGS_BASETYPE, /* tp_flags */ + 0, /* tp_doc */ + (traverseproc)mbiencoder_traverse, /* tp_traverse */ + 0, /* tp_clear */ + 0, /* tp_richcompare */ + 0, /* tp_weaklistoffset */ + 0, /* tp_iter */ + 0, /* tp_iterext */ + mbiencoder_methods, /* tp_methods */ + 0, /* tp_members */ + codecctx_getsets, /* tp_getset */ + 0, /* tp_base */ + 0, /* tp_dict */ + 0, /* tp_descr_get */ + 0, /* tp_descr_set */ + 0, /* tp_dictoffset */ + mbiencoder_init, /* tp_init */ + 0, /* tp_alloc */ + mbiencoder_new, /* tp_new */ }; @@ -1030,206 +1030,206 @@ static PyObject * mbidecoder_decode(MultibyteIncrementalDecoderObject *self, - PyObject *args, PyObject *kwargs) + PyObject *args, PyObject *kwargs) { - MultibyteDecodeBuffer buf; - char *data, *wdata = NULL; - Py_buffer pdata; - Py_ssize_t wsize, finalsize = 0, size, origpending; - int final = 0; - - if (!PyArg_ParseTupleAndKeywords(args, kwargs, "y*|i:decode", - incrementalkwarglist, &pdata, &final)) - return NULL; - data = pdata.buf; - size = pdata.len; - - buf.outobj = buf.excobj = NULL; - origpending = self->pendingsize; - - if (self->pendingsize == 0) { - wsize = size; - wdata = data; - } - else { - if (size > PY_SSIZE_T_MAX - self->pendingsize) { - PyErr_NoMemory(); - goto errorexit; - } - wsize = size + self->pendingsize; - wdata = PyMem_Malloc(wsize); - if (wdata == NULL) - goto errorexit; - memcpy(wdata, self->pending, self->pendingsize); - memcpy(wdata + self->pendingsize, data, size); - self->pendingsize = 0; - } - - if (decoder_prepare_buffer(&buf, wdata, wsize) != 0) - goto errorexit; - - if (decoder_feed_buffer(STATEFUL_DCTX(self), &buf)) - goto errorexit; - - if (final && buf.inbuf < buf.inbuf_end) { - if (multibytecodec_decerror(self->codec, &self->state, - &buf, self->errors, MBERR_TOOFEW)) { - /* recover the original pending buffer */ - memcpy(self->pending, wdata, origpending); - self->pendingsize = origpending; - goto errorexit; - } - } - - if (buf.inbuf < buf.inbuf_end) { /* pending sequence still exists */ - if (decoder_append_pending(STATEFUL_DCTX(self), &buf) != 0) - goto errorexit; - } - - finalsize = (Py_ssize_t)(buf.outbuf - PyUnicode_AS_UNICODE(buf.outobj)); - if (finalsize != PyUnicode_GET_SIZE(buf.outobj)) - if (PyUnicode_Resize(&buf.outobj, finalsize) == -1) - goto errorexit; - - PyBuffer_Release(&pdata); - if (wdata != data) - PyMem_Del(wdata); - Py_XDECREF(buf.excobj); - return buf.outobj; + MultibyteDecodeBuffer buf; + char *data, *wdata = NULL; + Py_buffer pdata; + Py_ssize_t wsize, finalsize = 0, size, origpending; + int final = 0; + + if (!PyArg_ParseTupleAndKeywords(args, kwargs, "y*|i:decode", + incrementalkwarglist, &pdata, &final)) + return NULL; + data = pdata.buf; + size = pdata.len; + + buf.outobj = buf.excobj = NULL; + origpending = self->pendingsize; + + if (self->pendingsize == 0) { + wsize = size; + wdata = data; + } + else { + if (size > PY_SSIZE_T_MAX - self->pendingsize) { + PyErr_NoMemory(); + goto errorexit; + } + wsize = size + self->pendingsize; + wdata = PyMem_Malloc(wsize); + if (wdata == NULL) + goto errorexit; + memcpy(wdata, self->pending, self->pendingsize); + memcpy(wdata + self->pendingsize, data, size); + self->pendingsize = 0; + } + + if (decoder_prepare_buffer(&buf, wdata, wsize) != 0) + goto errorexit; + + if (decoder_feed_buffer(STATEFUL_DCTX(self), &buf)) + goto errorexit; + + if (final && buf.inbuf < buf.inbuf_end) { + if (multibytecodec_decerror(self->codec, &self->state, + &buf, self->errors, MBERR_TOOFEW)) { + /* recover the original pending buffer */ + memcpy(self->pending, wdata, origpending); + self->pendingsize = origpending; + goto errorexit; + } + } + + if (buf.inbuf < buf.inbuf_end) { /* pending sequence still exists */ + if (decoder_append_pending(STATEFUL_DCTX(self), &buf) != 0) + goto errorexit; + } + + finalsize = (Py_ssize_t)(buf.outbuf - PyUnicode_AS_UNICODE(buf.outobj)); + if (finalsize != PyUnicode_GET_SIZE(buf.outobj)) + if (PyUnicode_Resize(&buf.outobj, finalsize) == -1) + goto errorexit; + + PyBuffer_Release(&pdata); + if (wdata != data) + PyMem_Del(wdata); + Py_XDECREF(buf.excobj); + return buf.outobj; errorexit: - PyBuffer_Release(&pdata); - if (wdata != NULL && wdata != data) - PyMem_Del(wdata); - Py_XDECREF(buf.excobj); - Py_XDECREF(buf.outobj); - return NULL; + PyBuffer_Release(&pdata); + if (wdata != NULL && wdata != data) + PyMem_Del(wdata); + Py_XDECREF(buf.excobj); + Py_XDECREF(buf.outobj); + return NULL; } static PyObject * mbidecoder_reset(MultibyteIncrementalDecoderObject *self) { - if (self->codec->decreset != NULL && - self->codec->decreset(&self->state, self->codec->config) != 0) - return NULL; - self->pendingsize = 0; + if (self->codec->decreset != NULL && + self->codec->decreset(&self->state, self->codec->config) != 0) + return NULL; + self->pendingsize = 0; - Py_RETURN_NONE; + Py_RETURN_NONE; } static struct PyMethodDef mbidecoder_methods[] = { - {"decode", (PyCFunction)mbidecoder_decode, - METH_VARARGS | METH_KEYWORDS, NULL}, - {"reset", (PyCFunction)mbidecoder_reset, - METH_NOARGS, NULL}, - {NULL, NULL}, + {"decode", (PyCFunction)mbidecoder_decode, + METH_VARARGS | METH_KEYWORDS, NULL}, + {"reset", (PyCFunction)mbidecoder_reset, + METH_NOARGS, NULL}, + {NULL, NULL}, }; static PyObject * mbidecoder_new(PyTypeObject *type, PyObject *args, PyObject *kwds) { - MultibyteIncrementalDecoderObject *self; - PyObject *codec = NULL; - char *errors = NULL; - - if (!PyArg_ParseTupleAndKeywords(args, kwds, "|s:IncrementalDecoder", - incnewkwarglist, &errors)) - return NULL; - - self = (MultibyteIncrementalDecoderObject *)type->tp_alloc(type, 0); - if (self == NULL) - return NULL; - - codec = PyObject_GetAttrString((PyObject *)type, "codec"); - if (codec == NULL) - goto errorexit; - if (!MultibyteCodec_Check(codec)) { - PyErr_SetString(PyExc_TypeError, "codec is unexpected type"); - goto errorexit; - } - - self->codec = ((MultibyteCodecObject *)codec)->codec; - self->pendingsize = 0; - self->errors = internal_error_callback(errors); - if (self->errors == NULL) - goto errorexit; - if (self->codec->decinit != NULL && - self->codec->decinit(&self->state, self->codec->config) != 0) - goto errorexit; + MultibyteIncrementalDecoderObject *self; + PyObject *codec = NULL; + char *errors = NULL; + + if (!PyArg_ParseTupleAndKeywords(args, kwds, "|s:IncrementalDecoder", + incnewkwarglist, &errors)) + return NULL; + + self = (MultibyteIncrementalDecoderObject *)type->tp_alloc(type, 0); + if (self == NULL) + return NULL; + + codec = PyObject_GetAttrString((PyObject *)type, "codec"); + if (codec == NULL) + goto errorexit; + if (!MultibyteCodec_Check(codec)) { + PyErr_SetString(PyExc_TypeError, "codec is unexpected type"); + goto errorexit; + } + + self->codec = ((MultibyteCodecObject *)codec)->codec; + self->pendingsize = 0; + self->errors = internal_error_callback(errors); + if (self->errors == NULL) + goto errorexit; + if (self->codec->decinit != NULL && + self->codec->decinit(&self->state, self->codec->config) != 0) + goto errorexit; - Py_DECREF(codec); - return (PyObject *)self; + Py_DECREF(codec); + return (PyObject *)self; errorexit: - Py_XDECREF(self); - Py_XDECREF(codec); - return NULL; + Py_XDECREF(self); + Py_XDECREF(codec); + return NULL; } static int mbidecoder_init(PyObject *self, PyObject *args, PyObject *kwds) { - return 0; + return 0; } static int mbidecoder_traverse(MultibyteIncrementalDecoderObject *self, - visitproc visit, void *arg) + visitproc visit, void *arg) { - if (ERROR_ISCUSTOM(self->errors)) - Py_VISIT(self->errors); - return 0; + if (ERROR_ISCUSTOM(self->errors)) + Py_VISIT(self->errors); + return 0; } static void mbidecoder_dealloc(MultibyteIncrementalDecoderObject *self) { - PyObject_GC_UnTrack(self); - ERROR_DECREF(self->errors); - Py_TYPE(self)->tp_free(self); + PyObject_GC_UnTrack(self); + ERROR_DECREF(self->errors); + Py_TYPE(self)->tp_free(self); } static PyTypeObject MultibyteIncrementalDecoder_Type = { - PyVarObject_HEAD_INIT(NULL, 0) - "MultibyteIncrementalDecoder", /* tp_name */ - sizeof(MultibyteIncrementalDecoderObject), /* tp_basicsize */ - 0, /* tp_itemsize */ - /* methods */ - (destructor)mbidecoder_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 - | Py_TPFLAGS_BASETYPE, /* tp_flags */ - 0, /* tp_doc */ - (traverseproc)mbidecoder_traverse, /* tp_traverse */ - 0, /* tp_clear */ - 0, /* tp_richcompare */ - 0, /* tp_weaklistoffset */ - 0, /* tp_iter */ - 0, /* tp_iterext */ - mbidecoder_methods, /* tp_methods */ - 0, /* tp_members */ - codecctx_getsets, /* tp_getset */ - 0, /* tp_base */ - 0, /* tp_dict */ - 0, /* tp_descr_get */ - 0, /* tp_descr_set */ - 0, /* tp_dictoffset */ - mbidecoder_init, /* tp_init */ - 0, /* tp_alloc */ - mbidecoder_new, /* tp_new */ + PyVarObject_HEAD_INIT(NULL, 0) + "MultibyteIncrementalDecoder", /* tp_name */ + sizeof(MultibyteIncrementalDecoderObject), /* tp_basicsize */ + 0, /* tp_itemsize */ + /* methods */ + (destructor)mbidecoder_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 + | Py_TPFLAGS_BASETYPE, /* tp_flags */ + 0, /* tp_doc */ + (traverseproc)mbidecoder_traverse, /* tp_traverse */ + 0, /* tp_clear */ + 0, /* tp_richcompare */ + 0, /* tp_weaklistoffset */ + 0, /* tp_iter */ + 0, /* tp_iterext */ + mbidecoder_methods, /* tp_methods */ + 0, /* tp_members */ + codecctx_getsets, /* tp_getset */ + 0, /* tp_base */ + 0, /* tp_dict */ + 0, /* tp_descr_get */ + 0, /* tp_descr_set */ + 0, /* tp_dictoffset */ + mbidecoder_init, /* tp_init */ + 0, /* tp_alloc */ + mbidecoder_new, /* tp_new */ }; @@ -1239,327 +1239,327 @@ static PyObject * mbstreamreader_iread(MultibyteStreamReaderObject *self, - const char *method, Py_ssize_t sizehint) + const char *method, Py_ssize_t sizehint) { - MultibyteDecodeBuffer buf; - PyObject *cres; - Py_ssize_t rsize, finalsize = 0; - - if (sizehint == 0) - return PyUnicode_FromUnicode(NULL, 0); - - buf.outobj = buf.excobj = NULL; - cres = NULL; - - for (;;) { - int endoffile; - - if (sizehint < 0) - cres = PyObject_CallMethod(self->stream, - (char *)method, NULL); - else - cres = PyObject_CallMethod(self->stream, - (char *)method, "i", sizehint); - if (cres == NULL) - goto errorexit; - - if (!PyBytes_Check(cres)) { - PyErr_Format(PyExc_TypeError, - "stream function returned a " - "non-bytes object (%.100s)", - cres->ob_type->tp_name); - goto errorexit; - } - - endoffile = (PyBytes_GET_SIZE(cres) == 0); - - if (self->pendingsize > 0) { - PyObject *ctr; - char *ctrdata; - - if (PyBytes_GET_SIZE(cres) > PY_SSIZE_T_MAX - self->pendingsize) { - PyErr_NoMemory(); - goto errorexit; - } - rsize = PyBytes_GET_SIZE(cres) + self->pendingsize; - ctr = PyBytes_FromStringAndSize(NULL, rsize); - if (ctr == NULL) - goto errorexit; - ctrdata = PyBytes_AS_STRING(ctr); - memcpy(ctrdata, self->pending, self->pendingsize); - memcpy(ctrdata + self->pendingsize, - PyBytes_AS_STRING(cres), - PyBytes_GET_SIZE(cres)); - Py_DECREF(cres); - cres = ctr; - self->pendingsize = 0; - } - - rsize = PyBytes_GET_SIZE(cres); - if (decoder_prepare_buffer(&buf, PyBytes_AS_STRING(cres), - rsize) != 0) - goto errorexit; - - if (rsize > 0 && decoder_feed_buffer( - (MultibyteStatefulDecoderContext *)self, &buf)) - goto errorexit; - - if (endoffile || sizehint < 0) { - if (buf.inbuf < buf.inbuf_end && - multibytecodec_decerror(self->codec, &self->state, - &buf, self->errors, MBERR_TOOFEW)) - goto errorexit; - } - - if (buf.inbuf < buf.inbuf_end) { /* pending sequence exists */ - if (decoder_append_pending(STATEFUL_DCTX(self), - &buf) != 0) - goto errorexit; - } - - finalsize = (Py_ssize_t)(buf.outbuf - - PyUnicode_AS_UNICODE(buf.outobj)); - Py_DECREF(cres); - cres = NULL; - - if (sizehint < 0 || finalsize != 0 || rsize == 0) - break; - - sizehint = 1; /* read 1 more byte and retry */ - } - - if (finalsize != PyUnicode_GET_SIZE(buf.outobj)) - if (PyUnicode_Resize(&buf.outobj, finalsize) == -1) - goto errorexit; - - Py_XDECREF(cres); - Py_XDECREF(buf.excobj); - return buf.outobj; + MultibyteDecodeBuffer buf; + PyObject *cres; + Py_ssize_t rsize, finalsize = 0; + + if (sizehint == 0) + return PyUnicode_FromUnicode(NULL, 0); + + buf.outobj = buf.excobj = NULL; + cres = NULL; + + for (;;) { + int endoffile; + + if (sizehint < 0) + cres = PyObject_CallMethod(self->stream, + (char *)method, NULL); + else + cres = PyObject_CallMethod(self->stream, + (char *)method, "i", sizehint); + if (cres == NULL) + goto errorexit; + + if (!PyBytes_Check(cres)) { + PyErr_Format(PyExc_TypeError, + "stream function returned a " + "non-bytes object (%.100s)", + cres->ob_type->tp_name); + goto errorexit; + } + + endoffile = (PyBytes_GET_SIZE(cres) == 0); + + if (self->pendingsize > 0) { + PyObject *ctr; + char *ctrdata; + + if (PyBytes_GET_SIZE(cres) > PY_SSIZE_T_MAX - self->pendingsize) { + PyErr_NoMemory(); + goto errorexit; + } + rsize = PyBytes_GET_SIZE(cres) + self->pendingsize; + ctr = PyBytes_FromStringAndSize(NULL, rsize); + if (ctr == NULL) + goto errorexit; + ctrdata = PyBytes_AS_STRING(ctr); + memcpy(ctrdata, self->pending, self->pendingsize); + memcpy(ctrdata + self->pendingsize, + PyBytes_AS_STRING(cres), + PyBytes_GET_SIZE(cres)); + Py_DECREF(cres); + cres = ctr; + self->pendingsize = 0; + } + + rsize = PyBytes_GET_SIZE(cres); + if (decoder_prepare_buffer(&buf, PyBytes_AS_STRING(cres), + rsize) != 0) + goto errorexit; + + if (rsize > 0 && decoder_feed_buffer( + (MultibyteStatefulDecoderContext *)self, &buf)) + goto errorexit; + + if (endoffile || sizehint < 0) { + if (buf.inbuf < buf.inbuf_end && + multibytecodec_decerror(self->codec, &self->state, + &buf, self->errors, MBERR_TOOFEW)) + goto errorexit; + } + + if (buf.inbuf < buf.inbuf_end) { /* pending sequence exists */ + if (decoder_append_pending(STATEFUL_DCTX(self), + &buf) != 0) + goto errorexit; + } + + finalsize = (Py_ssize_t)(buf.outbuf - + PyUnicode_AS_UNICODE(buf.outobj)); + Py_DECREF(cres); + cres = NULL; + + if (sizehint < 0 || finalsize != 0 || rsize == 0) + break; + + sizehint = 1; /* read 1 more byte and retry */ + } + + if (finalsize != PyUnicode_GET_SIZE(buf.outobj)) + if (PyUnicode_Resize(&buf.outobj, finalsize) == -1) + goto errorexit; + + Py_XDECREF(cres); + Py_XDECREF(buf.excobj); + return buf.outobj; errorexit: - Py_XDECREF(cres); - Py_XDECREF(buf.excobj); - Py_XDECREF(buf.outobj); - return NULL; + Py_XDECREF(cres); + Py_XDECREF(buf.excobj); + Py_XDECREF(buf.outobj); + return NULL; } static PyObject * mbstreamreader_read(MultibyteStreamReaderObject *self, PyObject *args) { - PyObject *sizeobj = NULL; - Py_ssize_t size; + PyObject *sizeobj = NULL; + Py_ssize_t size; - if (!PyArg_UnpackTuple(args, "read", 0, 1, &sizeobj)) - return NULL; + if (!PyArg_UnpackTuple(args, "read", 0, 1, &sizeobj)) + return NULL; - if (sizeobj == Py_None || sizeobj == NULL) - size = -1; - else if (PyLong_Check(sizeobj)) - size = PyLong_AsSsize_t(sizeobj); - else { - PyErr_SetString(PyExc_TypeError, "arg 1 must be an integer"); - return NULL; - } + if (sizeobj == Py_None || sizeobj == NULL) + size = -1; + else if (PyLong_Check(sizeobj)) + size = PyLong_AsSsize_t(sizeobj); + else { + PyErr_SetString(PyExc_TypeError, "arg 1 must be an integer"); + return NULL; + } - if (size == -1 && PyErr_Occurred()) - return NULL; + if (size == -1 && PyErr_Occurred()) + return NULL; - return mbstreamreader_iread(self, "read", size); + return mbstreamreader_iread(self, "read", size); } static PyObject * mbstreamreader_readline(MultibyteStreamReaderObject *self, PyObject *args) { - PyObject *sizeobj = NULL; - Py_ssize_t size; + PyObject *sizeobj = NULL; + Py_ssize_t size; - if (!PyArg_UnpackTuple(args, "readline", 0, 1, &sizeobj)) - return NULL; + if (!PyArg_UnpackTuple(args, "readline", 0, 1, &sizeobj)) + return NULL; - if (sizeobj == Py_None || sizeobj == NULL) - size = -1; - else if (PyLong_Check(sizeobj)) - size = PyLong_AsSsize_t(sizeobj); - else { - PyErr_SetString(PyExc_TypeError, "arg 1 must be an integer"); - return NULL; - } + if (sizeobj == Py_None || sizeobj == NULL) + size = -1; + else if (PyLong_Check(sizeobj)) + size = PyLong_AsSsize_t(sizeobj); + else { + PyErr_SetString(PyExc_TypeError, "arg 1 must be an integer"); + return NULL; + } - if (size == -1 && PyErr_Occurred()) - return NULL; + if (size == -1 && PyErr_Occurred()) + return NULL; - return mbstreamreader_iread(self, "readline", size); + return mbstreamreader_iread(self, "readline", size); } static PyObject * mbstreamreader_readlines(MultibyteStreamReaderObject *self, PyObject *args) { - PyObject *sizehintobj = NULL, *r, *sr; - Py_ssize_t sizehint; + PyObject *sizehintobj = NULL, *r, *sr; + Py_ssize_t sizehint; - if (!PyArg_UnpackTuple(args, "readlines", 0, 1, &sizehintobj)) - return NULL; + if (!PyArg_UnpackTuple(args, "readlines", 0, 1, &sizehintobj)) + return NULL; - if (sizehintobj == Py_None || sizehintobj == NULL) - sizehint = -1; - else if (PyLong_Check(sizehintobj)) - sizehint = PyLong_AsSsize_t(sizehintobj); - else { - PyErr_SetString(PyExc_TypeError, "arg 1 must be an integer"); - return NULL; - } - - if (sizehint == -1 && PyErr_Occurred()) - return NULL; - - r = mbstreamreader_iread(self, "read", sizehint); - if (r == NULL) - return NULL; - - sr = PyUnicode_Splitlines(r, 1); - Py_DECREF(r); - return sr; + if (sizehintobj == Py_None || sizehintobj == NULL) + sizehint = -1; + else if (PyLong_Check(sizehintobj)) + sizehint = PyLong_AsSsize_t(sizehintobj); + else { + PyErr_SetString(PyExc_TypeError, "arg 1 must be an integer"); + return NULL; + } + + if (sizehint == -1 && PyErr_Occurred()) + return NULL; + + r = mbstreamreader_iread(self, "read", sizehint); + if (r == NULL) + return NULL; + + sr = PyUnicode_Splitlines(r, 1); + Py_DECREF(r); + return sr; } static PyObject * mbstreamreader_reset(MultibyteStreamReaderObject *self) { - if (self->codec->decreset != NULL && - self->codec->decreset(&self->state, self->codec->config) != 0) - return NULL; - self->pendingsize = 0; + if (self->codec->decreset != NULL && + self->codec->decreset(&self->state, self->codec->config) != 0) + return NULL; + self->pendingsize = 0; - Py_RETURN_NONE; + Py_RETURN_NONE; } static struct PyMethodDef mbstreamreader_methods[] = { - {"read", (PyCFunction)mbstreamreader_read, - METH_VARARGS, NULL}, - {"readline", (PyCFunction)mbstreamreader_readline, - METH_VARARGS, NULL}, - {"readlines", (PyCFunction)mbstreamreader_readlines, - METH_VARARGS, NULL}, - {"reset", (PyCFunction)mbstreamreader_reset, - METH_NOARGS, NULL}, - {NULL, NULL}, + {"read", (PyCFunction)mbstreamreader_read, + METH_VARARGS, NULL}, + {"readline", (PyCFunction)mbstreamreader_readline, + METH_VARARGS, NULL}, + {"readlines", (PyCFunction)mbstreamreader_readlines, + METH_VARARGS, NULL}, + {"reset", (PyCFunction)mbstreamreader_reset, + METH_NOARGS, NULL}, + {NULL, NULL}, }; static PyMemberDef mbstreamreader_members[] = { - {"stream", T_OBJECT, - offsetof(MultibyteStreamReaderObject, stream), - READONLY, NULL}, - {NULL,} + {"stream", T_OBJECT, + offsetof(MultibyteStreamReaderObject, stream), + READONLY, NULL}, + {NULL,} }; static PyObject * mbstreamreader_new(PyTypeObject *type, PyObject *args, PyObject *kwds) { - MultibyteStreamReaderObject *self; - PyObject *stream, *codec = NULL; - char *errors = NULL; - - if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|s:StreamReader", - streamkwarglist, &stream, &errors)) - return NULL; - - self = (MultibyteStreamReaderObject *)type->tp_alloc(type, 0); - if (self == NULL) - return NULL; - - codec = PyObject_GetAttrString((PyObject *)type, "codec"); - if (codec == NULL) - goto errorexit; - if (!MultibyteCodec_Check(codec)) { - PyErr_SetString(PyExc_TypeError, "codec is unexpected type"); - goto errorexit; - } - - self->codec = ((MultibyteCodecObject *)codec)->codec; - self->stream = stream; - Py_INCREF(stream); - self->pendingsize = 0; - self->errors = internal_error_callback(errors); - if (self->errors == NULL) - goto errorexit; - if (self->codec->decinit != NULL && - self->codec->decinit(&self->state, self->codec->config) != 0) - goto errorexit; + MultibyteStreamReaderObject *self; + PyObject *stream, *codec = NULL; + char *errors = NULL; + + if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|s:StreamReader", + streamkwarglist, &stream, &errors)) + return NULL; + + self = (MultibyteStreamReaderObject *)type->tp_alloc(type, 0); + if (self == NULL) + return NULL; + + codec = PyObject_GetAttrString((PyObject *)type, "codec"); + if (codec == NULL) + goto errorexit; + if (!MultibyteCodec_Check(codec)) { + PyErr_SetString(PyExc_TypeError, "codec is unexpected type"); + goto errorexit; + } + + self->codec = ((MultibyteCodecObject *)codec)->codec; + self->stream = stream; + Py_INCREF(stream); + self->pendingsize = 0; + self->errors = internal_error_callback(errors); + if (self->errors == NULL) + goto errorexit; + if (self->codec->decinit != NULL && + self->codec->decinit(&self->state, self->codec->config) != 0) + goto errorexit; - Py_DECREF(codec); - return (PyObject *)self; + Py_DECREF(codec); + return (PyObject *)self; errorexit: - Py_XDECREF(self); - Py_XDECREF(codec); - return NULL; + Py_XDECREF(self); + Py_XDECREF(codec); + return NULL; } static int mbstreamreader_init(PyObject *self, PyObject *args, PyObject *kwds) { - return 0; + return 0; } static int mbstreamreader_traverse(MultibyteStreamReaderObject *self, - visitproc visit, void *arg) + visitproc visit, void *arg) { - if (ERROR_ISCUSTOM(self->errors)) - Py_VISIT(self->errors); - Py_VISIT(self->stream); - return 0; + if (ERROR_ISCUSTOM(self->errors)) + Py_VISIT(self->errors); + Py_VISIT(self->stream); + return 0; } static void mbstreamreader_dealloc(MultibyteStreamReaderObject *self) { - PyObject_GC_UnTrack(self); - ERROR_DECREF(self->errors); - Py_XDECREF(self->stream); - Py_TYPE(self)->tp_free(self); + PyObject_GC_UnTrack(self); + ERROR_DECREF(self->errors); + Py_XDECREF(self->stream); + Py_TYPE(self)->tp_free(self); } static PyTypeObject MultibyteStreamReader_Type = { - PyVarObject_HEAD_INIT(NULL, 0) - "MultibyteStreamReader", /* tp_name */ - sizeof(MultibyteStreamReaderObject), /* tp_basicsize */ - 0, /* tp_itemsize */ - /* methods */ - (destructor)mbstreamreader_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 - | Py_TPFLAGS_BASETYPE, /* tp_flags */ - 0, /* tp_doc */ - (traverseproc)mbstreamreader_traverse, /* tp_traverse */ - 0, /* tp_clear */ - 0, /* tp_richcompare */ - 0, /* tp_weaklistoffset */ - 0, /* tp_iter */ - 0, /* tp_iterext */ - mbstreamreader_methods, /* tp_methods */ - mbstreamreader_members, /* tp_members */ - codecctx_getsets, /* tp_getset */ - 0, /* tp_base */ - 0, /* tp_dict */ - 0, /* tp_descr_get */ - 0, /* tp_descr_set */ - 0, /* tp_dictoffset */ - mbstreamreader_init, /* tp_init */ - 0, /* tp_alloc */ - mbstreamreader_new, /* tp_new */ + PyVarObject_HEAD_INIT(NULL, 0) + "MultibyteStreamReader", /* tp_name */ + sizeof(MultibyteStreamReaderObject), /* tp_basicsize */ + 0, /* tp_itemsize */ + /* methods */ + (destructor)mbstreamreader_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 + | Py_TPFLAGS_BASETYPE, /* tp_flags */ + 0, /* tp_doc */ + (traverseproc)mbstreamreader_traverse, /* tp_traverse */ + 0, /* tp_clear */ + 0, /* tp_richcompare */ + 0, /* tp_weaklistoffset */ + 0, /* tp_iter */ + 0, /* tp_iterext */ + mbstreamreader_methods, /* tp_methods */ + mbstreamreader_members, /* tp_members */ + codecctx_getsets, /* tp_getset */ + 0, /* tp_base */ + 0, /* tp_dict */ + 0, /* tp_descr_get */ + 0, /* tp_descr_set */ + 0, /* tp_dictoffset */ + mbstreamreader_init, /* tp_init */ + 0, /* tp_alloc */ + mbstreamreader_new, /* tp_new */ }; @@ -1569,217 +1569,217 @@ static int mbstreamwriter_iwrite(MultibyteStreamWriterObject *self, - PyObject *unistr) + PyObject *unistr) { - PyObject *str, *wr; + PyObject *str, *wr; - str = encoder_encode_stateful(STATEFUL_ECTX(self), unistr, 0); - if (str == NULL) - return -1; + str = encoder_encode_stateful(STATEFUL_ECTX(self), unistr, 0); + if (str == NULL) + return -1; - wr = PyObject_CallMethod(self->stream, "write", "O", str); - Py_DECREF(str); - if (wr == NULL) - return -1; + wr = PyObject_CallMethod(self->stream, "write", "O", str); + Py_DECREF(str); + if (wr == NULL) + return -1; - Py_DECREF(wr); - return 0; + Py_DECREF(wr); + return 0; } static PyObject * mbstreamwriter_write(MultibyteStreamWriterObject *self, PyObject *strobj) { - if (mbstreamwriter_iwrite(self, strobj)) - return NULL; - else - Py_RETURN_NONE; + if (mbstreamwriter_iwrite(self, strobj)) + return NULL; + else + Py_RETURN_NONE; } static PyObject * mbstreamwriter_writelines(MultibyteStreamWriterObject *self, PyObject *lines) { - PyObject *strobj; - int i, r; + PyObject *strobj; + int i, r; - if (!PySequence_Check(lines)) { - PyErr_SetString(PyExc_TypeError, - "arg must be a sequence object"); - return NULL; - } - - for (i = 0; i < PySequence_Length(lines); i++) { - /* length can be changed even within this loop */ - strobj = PySequence_GetItem(lines, i); - if (strobj == NULL) - return NULL; - - r = mbstreamwriter_iwrite(self, strobj); - Py_DECREF(strobj); - if (r == -1) - return NULL; - } + if (!PySequence_Check(lines)) { + PyErr_SetString(PyExc_TypeError, + "arg must be a sequence object"); + return NULL; + } + + for (i = 0; i < PySequence_Length(lines); i++) { + /* length can be changed even within this loop */ + strobj = PySequence_GetItem(lines, i); + if (strobj == NULL) + return NULL; + + r = mbstreamwriter_iwrite(self, strobj); + Py_DECREF(strobj); + if (r == -1) + return NULL; + } - Py_RETURN_NONE; + Py_RETURN_NONE; } static PyObject * mbstreamwriter_reset(MultibyteStreamWriterObject *self) { - const Py_UNICODE *pending; - PyObject *pwrt; + const Py_UNICODE *pending; + PyObject *pwrt; - pending = self->pending; - pwrt = multibytecodec_encode(self->codec, &self->state, - &pending, self->pendingsize, self->errors, - MBENC_FLUSH | MBENC_RESET); - /* some pending buffer can be truncated when UnicodeEncodeError is - * raised on 'strict' mode. but, 'reset' method is designed to - * reset the pending buffer or states so failed string sequence - * ought to be missed */ - self->pendingsize = 0; - if (pwrt == NULL) - return NULL; - - assert(PyBytes_Check(pwrt)); - if (PyBytes_Size(pwrt) > 0) { - PyObject *wr; - wr = PyObject_CallMethod(self->stream, "write", "O", pwrt); - if (wr == NULL) { - Py_DECREF(pwrt); - return NULL; - } - } - Py_DECREF(pwrt); + pending = self->pending; + pwrt = multibytecodec_encode(self->codec, &self->state, + &pending, self->pendingsize, self->errors, + MBENC_FLUSH | MBENC_RESET); + /* some pending buffer can be truncated when UnicodeEncodeError is + * raised on 'strict' mode. but, 'reset' method is designed to + * reset the pending buffer or states so failed string sequence + * ought to be missed */ + self->pendingsize = 0; + if (pwrt == NULL) + return NULL; + + assert(PyBytes_Check(pwrt)); + if (PyBytes_Size(pwrt) > 0) { + PyObject *wr; + wr = PyObject_CallMethod(self->stream, "write", "O", pwrt); + if (wr == NULL) { + Py_DECREF(pwrt); + return NULL; + } + } + Py_DECREF(pwrt); - Py_RETURN_NONE; + Py_RETURN_NONE; } static PyObject * mbstreamwriter_new(PyTypeObject *type, PyObject *args, PyObject *kwds) { - MultibyteStreamWriterObject *self; - PyObject *stream, *codec = NULL; - char *errors = NULL; - - if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|s:StreamWriter", - streamkwarglist, &stream, &errors)) - return NULL; - - self = (MultibyteStreamWriterObject *)type->tp_alloc(type, 0); - if (self == NULL) - return NULL; - - codec = PyObject_GetAttrString((PyObject *)type, "codec"); - if (codec == NULL) - goto errorexit; - if (!MultibyteCodec_Check(codec)) { - PyErr_SetString(PyExc_TypeError, "codec is unexpected type"); - goto errorexit; - } - - self->codec = ((MultibyteCodecObject *)codec)->codec; - self->stream = stream; - Py_INCREF(stream); - self->pendingsize = 0; - self->errors = internal_error_callback(errors); - if (self->errors == NULL) - goto errorexit; - if (self->codec->encinit != NULL && - self->codec->encinit(&self->state, self->codec->config) != 0) - goto errorexit; + MultibyteStreamWriterObject *self; + PyObject *stream, *codec = NULL; + char *errors = NULL; + + if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|s:StreamWriter", + streamkwarglist, &stream, &errors)) + return NULL; + + self = (MultibyteStreamWriterObject *)type->tp_alloc(type, 0); + if (self == NULL) + return NULL; + + codec = PyObject_GetAttrString((PyObject *)type, "codec"); + if (codec == NULL) + goto errorexit; + if (!MultibyteCodec_Check(codec)) { + PyErr_SetString(PyExc_TypeError, "codec is unexpected type"); + goto errorexit; + } + + self->codec = ((MultibyteCodecObject *)codec)->codec; + self->stream = stream; + Py_INCREF(stream); + self->pendingsize = 0; + self->errors = internal_error_callback(errors); + if (self->errors == NULL) + goto errorexit; + if (self->codec->encinit != NULL && + self->codec->encinit(&self->state, self->codec->config) != 0) + goto errorexit; - Py_DECREF(codec); - return (PyObject *)self; + Py_DECREF(codec); + return (PyObject *)self; errorexit: - Py_XDECREF(self); - Py_XDECREF(codec); - return NULL; + Py_XDECREF(self); + Py_XDECREF(codec); + return NULL; } static int mbstreamwriter_init(PyObject *self, PyObject *args, PyObject *kwds) { - return 0; + return 0; } static int mbstreamwriter_traverse(MultibyteStreamWriterObject *self, - visitproc visit, void *arg) + visitproc visit, void *arg) { - if (ERROR_ISCUSTOM(self->errors)) - Py_VISIT(self->errors); - Py_VISIT(self->stream); - return 0; + if (ERROR_ISCUSTOM(self->errors)) + Py_VISIT(self->errors); + Py_VISIT(self->stream); + return 0; } static void mbstreamwriter_dealloc(MultibyteStreamWriterObject *self) { - PyObject_GC_UnTrack(self); - ERROR_DECREF(self->errors); - Py_XDECREF(self->stream); - Py_TYPE(self)->tp_free(self); + PyObject_GC_UnTrack(self); + ERROR_DECREF(self->errors); + Py_XDECREF(self->stream); + Py_TYPE(self)->tp_free(self); } static struct PyMethodDef mbstreamwriter_methods[] = { - {"write", (PyCFunction)mbstreamwriter_write, - METH_O, NULL}, - {"writelines", (PyCFunction)mbstreamwriter_writelines, - METH_O, NULL}, - {"reset", (PyCFunction)mbstreamwriter_reset, - METH_NOARGS, NULL}, - {NULL, NULL}, + {"write", (PyCFunction)mbstreamwriter_write, + METH_O, NULL}, + {"writelines", (PyCFunction)mbstreamwriter_writelines, + METH_O, NULL}, + {"reset", (PyCFunction)mbstreamwriter_reset, + METH_NOARGS, NULL}, + {NULL, NULL}, }; static PyMemberDef mbstreamwriter_members[] = { - {"stream", T_OBJECT, - offsetof(MultibyteStreamWriterObject, stream), - READONLY, NULL}, - {NULL,} + {"stream", T_OBJECT, + offsetof(MultibyteStreamWriterObject, stream), + READONLY, NULL}, + {NULL,} }; static PyTypeObject MultibyteStreamWriter_Type = { - PyVarObject_HEAD_INIT(NULL, 0) - "MultibyteStreamWriter", /* tp_name */ - sizeof(MultibyteStreamWriterObject), /* tp_basicsize */ - 0, /* tp_itemsize */ - /* methods */ - (destructor)mbstreamwriter_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 - | Py_TPFLAGS_BASETYPE, /* tp_flags */ - 0, /* tp_doc */ - (traverseproc)mbstreamwriter_traverse, /* tp_traverse */ - 0, /* tp_clear */ - 0, /* tp_richcompare */ - 0, /* tp_weaklistoffset */ - 0, /* tp_iter */ - 0, /* tp_iterext */ - mbstreamwriter_methods, /* tp_methods */ - mbstreamwriter_members, /* tp_members */ - codecctx_getsets, /* tp_getset */ - 0, /* tp_base */ - 0, /* tp_dict */ - 0, /* tp_descr_get */ - 0, /* tp_descr_set */ - 0, /* tp_dictoffset */ - mbstreamwriter_init, /* tp_init */ - 0, /* tp_alloc */ - mbstreamwriter_new, /* tp_new */ + PyVarObject_HEAD_INIT(NULL, 0) + "MultibyteStreamWriter", /* tp_name */ + sizeof(MultibyteStreamWriterObject), /* tp_basicsize */ + 0, /* tp_itemsize */ + /* methods */ + (destructor)mbstreamwriter_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 + | Py_TPFLAGS_BASETYPE, /* tp_flags */ + 0, /* tp_doc */ + (traverseproc)mbstreamwriter_traverse, /* tp_traverse */ + 0, /* tp_clear */ + 0, /* tp_richcompare */ + 0, /* tp_weaklistoffset */ + 0, /* tp_iter */ + 0, /* tp_iterext */ + mbstreamwriter_methods, /* tp_methods */ + mbstreamwriter_members, /* tp_members */ + codecctx_getsets, /* tp_getset */ + 0, /* tp_base */ + 0, /* tp_dict */ + 0, /* tp_descr_get */ + 0, /* tp_descr_set */ + 0, /* tp_dictoffset */ + mbstreamwriter_init, /* tp_init */ + 0, /* tp_alloc */ + mbstreamwriter_new, /* tp_new */ }; @@ -1790,76 +1790,76 @@ static PyObject * __create_codec(PyObject *ignore, PyObject *arg) { - MultibyteCodecObject *self; - MultibyteCodec *codec; + MultibyteCodecObject *self; + MultibyteCodec *codec; - if (!PyCapsule_IsValid(arg, PyMultibyteCodec_CAPSULE_NAME)) { - PyErr_SetString(PyExc_ValueError, "argument type invalid"); - return NULL; - } - - codec = PyCapsule_GetPointer(arg, PyMultibyteCodec_CAPSULE_NAME); - if (codec->codecinit != NULL && codec->codecinit(codec->config) != 0) - return NULL; - - self = PyObject_New(MultibyteCodecObject, &MultibyteCodec_Type); - if (self == NULL) - return NULL; - self->codec = codec; + if (!PyCapsule_IsValid(arg, PyMultibyteCodec_CAPSULE_NAME)) { + PyErr_SetString(PyExc_ValueError, "argument type invalid"); + return NULL; + } + + codec = PyCapsule_GetPointer(arg, PyMultibyteCodec_CAPSULE_NAME); + if (codec->codecinit != NULL && codec->codecinit(codec->config) != 0) + return NULL; + + self = PyObject_New(MultibyteCodecObject, &MultibyteCodec_Type); + if (self == NULL) + return NULL; + self->codec = codec; - return (PyObject *)self; + return (PyObject *)self; } static struct PyMethodDef __methods[] = { - {"__create_codec", (PyCFunction)__create_codec, METH_O}, - {NULL, NULL}, + {"__create_codec", (PyCFunction)__create_codec, METH_O}, + {NULL, NULL}, }; static struct PyModuleDef _multibytecodecmodule = { - PyModuleDef_HEAD_INIT, - "_multibytecodec", - NULL, - -1, - __methods, - NULL, - NULL, - NULL, - NULL + PyModuleDef_HEAD_INIT, + "_multibytecodec", + NULL, + -1, + __methods, + NULL, + NULL, + NULL, + NULL }; PyMODINIT_FUNC PyInit__multibytecodec(void) { - int i; - PyObject *m; - PyTypeObject *typelist[] = { - &MultibyteIncrementalEncoder_Type, - &MultibyteIncrementalDecoder_Type, - &MultibyteStreamReader_Type, - &MultibyteStreamWriter_Type, - NULL - }; - - if (PyType_Ready(&MultibyteCodec_Type) < 0) - return NULL; - - m = PyModule_Create(&_multibytecodecmodule); - if (m == NULL) - return NULL; - - for (i = 0; typelist[i] != NULL; i++) { - if (PyType_Ready(typelist[i]) < 0) - return NULL; - Py_INCREF(typelist[i]); - PyModule_AddObject(m, typelist[i]->tp_name, - (PyObject *)typelist[i]); - } - - if (PyErr_Occurred()) { - Py_FatalError("can't initialize the _multibytecodec module"); - Py_DECREF(m); - m = NULL; - } - return m; + int i; + PyObject *m; + PyTypeObject *typelist[] = { + &MultibyteIncrementalEncoder_Type, + &MultibyteIncrementalDecoder_Type, + &MultibyteStreamReader_Type, + &MultibyteStreamWriter_Type, + NULL + }; + + if (PyType_Ready(&MultibyteCodec_Type) < 0) + return NULL; + + m = PyModule_Create(&_multibytecodecmodule); + if (m == NULL) + return NULL; + + for (i = 0; typelist[i] != NULL; i++) { + if (PyType_Ready(typelist[i]) < 0) + return NULL; + Py_INCREF(typelist[i]); + PyModule_AddObject(m, typelist[i]->tp_name, + (PyObject *)typelist[i]); + } + + if (PyErr_Occurred()) { + Py_FatalError("can't initialize the _multibytecodec module"); + Py_DECREF(m); + m = NULL; + } + return m; } Modified: python/branches/py3k-jit/Modules/cjkcodecs/multibytecodec.h ============================================================================== --- python/branches/py3k-jit/Modules/cjkcodecs/multibytecodec.h (original) +++ python/branches/py3k-jit/Modules/cjkcodecs/multibytecodec.h Mon May 10 23:55:43 2010 @@ -23,114 +23,114 @@ #endif typedef union { - void *p; - int i; - unsigned char c[8]; - ucs2_t u2[4]; - ucs4_t u4[2]; + void *p; + int i; + unsigned char c[8]; + ucs2_t u2[4]; + ucs4_t u4[2]; } MultibyteCodec_State; typedef int (*mbcodec_init)(const void *config); typedef Py_ssize_t (*mbencode_func)(MultibyteCodec_State *state, - const void *config, - const Py_UNICODE **inbuf, Py_ssize_t inleft, - unsigned char **outbuf, Py_ssize_t outleft, - int flags); + const void *config, + const Py_UNICODE **inbuf, Py_ssize_t inleft, + unsigned char **outbuf, Py_ssize_t outleft, + int flags); typedef int (*mbencodeinit_func)(MultibyteCodec_State *state, - const void *config); + const void *config); typedef Py_ssize_t (*mbencodereset_func)(MultibyteCodec_State *state, - const void *config, - unsigned char **outbuf, Py_ssize_t outleft); + const void *config, + unsigned char **outbuf, Py_ssize_t outleft); typedef Py_ssize_t (*mbdecode_func)(MultibyteCodec_State *state, - const void *config, - const unsigned char **inbuf, Py_ssize_t inleft, - Py_UNICODE **outbuf, Py_ssize_t outleft); + const void *config, + const unsigned char **inbuf, Py_ssize_t inleft, + Py_UNICODE **outbuf, Py_ssize_t outleft); typedef int (*mbdecodeinit_func)(MultibyteCodec_State *state, - const void *config); + const void *config); typedef Py_ssize_t (*mbdecodereset_func)(MultibyteCodec_State *state, - const void *config); + const void *config); typedef struct { - const char *encoding; - const void *config; - mbcodec_init codecinit; - mbencode_func encode; - mbencodeinit_func encinit; - mbencodereset_func encreset; - mbdecode_func decode; - mbdecodeinit_func decinit; - mbdecodereset_func decreset; + const char *encoding; + const void *config; + mbcodec_init codecinit; + mbencode_func encode; + mbencodeinit_func encinit; + mbencodereset_func encreset; + mbdecode_func decode; + mbdecodeinit_func decinit; + mbdecodereset_func decreset; } MultibyteCodec; typedef struct { - PyObject_HEAD - MultibyteCodec *codec; + PyObject_HEAD + MultibyteCodec *codec; } MultibyteCodecObject; #define MultibyteCodec_Check(op) ((op)->ob_type == &MultibyteCodec_Type) -#define _MultibyteStatefulCodec_HEAD \ - PyObject_HEAD \ - MultibyteCodec *codec; \ - MultibyteCodec_State state; \ - PyObject *errors; +#define _MultibyteStatefulCodec_HEAD \ + PyObject_HEAD \ + MultibyteCodec *codec; \ + MultibyteCodec_State state; \ + PyObject *errors; typedef struct { - _MultibyteStatefulCodec_HEAD + _MultibyteStatefulCodec_HEAD } MultibyteStatefulCodecContext; -#define MAXENCPENDING 2 -#define _MultibyteStatefulEncoder_HEAD \ - _MultibyteStatefulCodec_HEAD \ - Py_UNICODE pending[MAXENCPENDING]; \ - Py_ssize_t pendingsize; +#define MAXENCPENDING 2 +#define _MultibyteStatefulEncoder_HEAD \ + _MultibyteStatefulCodec_HEAD \ + Py_UNICODE pending[MAXENCPENDING]; \ + Py_ssize_t pendingsize; typedef struct { - _MultibyteStatefulEncoder_HEAD + _MultibyteStatefulEncoder_HEAD } MultibyteStatefulEncoderContext; -#define MAXDECPENDING 8 -#define _MultibyteStatefulDecoder_HEAD \ - _MultibyteStatefulCodec_HEAD \ - unsigned char pending[MAXDECPENDING]; \ - Py_ssize_t pendingsize; +#define MAXDECPENDING 8 +#define _MultibyteStatefulDecoder_HEAD \ + _MultibyteStatefulCodec_HEAD \ + unsigned char pending[MAXDECPENDING]; \ + Py_ssize_t pendingsize; typedef struct { - _MultibyteStatefulDecoder_HEAD + _MultibyteStatefulDecoder_HEAD } MultibyteStatefulDecoderContext; typedef struct { - _MultibyteStatefulEncoder_HEAD + _MultibyteStatefulEncoder_HEAD } MultibyteIncrementalEncoderObject; typedef struct { - _MultibyteStatefulDecoder_HEAD + _MultibyteStatefulDecoder_HEAD } MultibyteIncrementalDecoderObject; typedef struct { - _MultibyteStatefulDecoder_HEAD - PyObject *stream; + _MultibyteStatefulDecoder_HEAD + PyObject *stream; } MultibyteStreamReaderObject; typedef struct { - _MultibyteStatefulEncoder_HEAD - PyObject *stream; + _MultibyteStatefulEncoder_HEAD + PyObject *stream; } MultibyteStreamWriterObject; /* positive values for illegal sequences */ -#define MBERR_TOOSMALL (-1) /* insufficient output buffer space */ -#define MBERR_TOOFEW (-2) /* incomplete input buffer */ -#define MBERR_INTERNAL (-3) /* internal runtime error */ - -#define ERROR_STRICT (PyObject *)(1) -#define ERROR_IGNORE (PyObject *)(2) -#define ERROR_REPLACE (PyObject *)(3) -#define ERROR_ISCUSTOM(p) ((p) < ERROR_STRICT || ERROR_REPLACE < (p)) -#define ERROR_DECREF(p) do { \ - if (p != NULL && ERROR_ISCUSTOM(p)) { \ - Py_DECREF(p); \ - } \ +#define MBERR_TOOSMALL (-1) /* insufficient output buffer space */ +#define MBERR_TOOFEW (-2) /* incomplete input buffer */ +#define MBERR_INTERNAL (-3) /* internal runtime error */ + +#define ERROR_STRICT (PyObject *)(1) +#define ERROR_IGNORE (PyObject *)(2) +#define ERROR_REPLACE (PyObject *)(3) +#define ERROR_ISCUSTOM(p) ((p) < ERROR_STRICT || ERROR_REPLACE < (p)) +#define ERROR_DECREF(p) do { \ + if (p != NULL && ERROR_ISCUSTOM(p)) { \ + Py_DECREF(p); \ + } \ } while (0); -#define MBENC_FLUSH 0x0001 /* encode all characters encodable */ -#define MBENC_MAX MBENC_FLUSH +#define MBENC_FLUSH 0x0001 /* encode all characters encodable */ +#define MBENC_MAX MBENC_FLUSH #define PyMultibyteCodec_CAPSULE_NAME "multibytecodec.__map_*" Modified: python/branches/py3k-jit/Modules/cmathmodule.c ============================================================================== --- python/branches/py3k-jit/Modules/cmathmodule.c (original) +++ python/branches/py3k-jit/Modules/cmathmodule.c Mon May 10 23:55:43 2010 @@ -32,7 +32,7 @@ #define CM_LOG_LARGE_DOUBLE (log(CM_LARGE_DOUBLE)) #define CM_SQRT_DBL_MIN (sqrt(DBL_MIN)) -/* +/* CM_SCALE_UP is an odd integer chosen such that multiplication by 2**CM_SCALE_UP is sufficient to turn a subnormal into a normal. CM_SCALE_DOWN is (-(CM_SCALE_UP+1)/2). These scalings are used to compute @@ -63,46 +63,46 @@ */ enum special_types { - ST_NINF, /* 0, negative infinity */ - ST_NEG, /* 1, negative finite number (nonzero) */ - ST_NZERO, /* 2, -0. */ - ST_PZERO, /* 3, +0. */ - ST_POS, /* 4, positive finite number (nonzero) */ - ST_PINF, /* 5, positive infinity */ - ST_NAN /* 6, Not a Number */ + ST_NINF, /* 0, negative infinity */ + ST_NEG, /* 1, negative finite number (nonzero) */ + ST_NZERO, /* 2, -0. */ + ST_PZERO, /* 3, +0. */ + ST_POS, /* 4, positive finite number (nonzero) */ + ST_PINF, /* 5, positive infinity */ + ST_NAN /* 6, Not a Number */ }; static enum special_types special_type(double d) { - if (Py_IS_FINITE(d)) { - if (d != 0) { - if (copysign(1., d) == 1.) - return ST_POS; - else - return ST_NEG; - } - else { - if (copysign(1., d) == 1.) - return ST_PZERO; - else - return ST_NZERO; - } - } - if (Py_IS_NAN(d)) - return ST_NAN; - if (copysign(1., d) == 1.) - return ST_PINF; - else - return ST_NINF; -} - -#define SPECIAL_VALUE(z, table) \ - if (!Py_IS_FINITE((z).real) || !Py_IS_FINITE((z).imag)) { \ - errno = 0; \ - return table[special_type((z).real)] \ - [special_type((z).imag)]; \ - } + if (Py_IS_FINITE(d)) { + if (d != 0) { + if (copysign(1., d) == 1.) + return ST_POS; + else + return ST_NEG; + } + else { + if (copysign(1., d) == 1.) + return ST_PZERO; + else + return ST_NZERO; + } + } + if (Py_IS_NAN(d)) + return ST_NAN; + if (copysign(1., d) == 1.) + return ST_PINF; + else + return ST_NINF; +} + +#define SPECIAL_VALUE(z, table) \ + if (!Py_IS_FINITE((z).real) || !Py_IS_FINITE((z).imag)) { \ + errno = 0; \ + return table[special_type((z).real)] \ + [special_type((z).imag)]; \ + } #define P Py_MATH_PI #define P14 0.25*Py_MATH_PI @@ -126,34 +126,34 @@ static Py_complex c_acos(Py_complex z) { - Py_complex s1, s2, r; + Py_complex s1, s2, r; - SPECIAL_VALUE(z, acos_special_values); + SPECIAL_VALUE(z, acos_special_values); - if (fabs(z.real) > CM_LARGE_DOUBLE || fabs(z.imag) > CM_LARGE_DOUBLE) { - /* avoid unnecessary overflow for large arguments */ - r.real = atan2(fabs(z.imag), z.real); - /* split into cases to make sure that the branch cut has the - correct continuity on systems with unsigned zeros */ - if (z.real < 0.) { - r.imag = -copysign(log(hypot(z.real/2., z.imag/2.)) + - M_LN2*2., z.imag); - } else { - r.imag = copysign(log(hypot(z.real/2., z.imag/2.)) + - M_LN2*2., -z.imag); - } - } else { - s1.real = 1.-z.real; - s1.imag = -z.imag; - s1 = c_sqrt(s1); - s2.real = 1.+z.real; - s2.imag = z.imag; - s2 = c_sqrt(s2); - r.real = 2.*atan2(s1.real, s2.real); - r.imag = m_asinh(s2.real*s1.imag - s2.imag*s1.real); - } - errno = 0; - return r; + if (fabs(z.real) > CM_LARGE_DOUBLE || fabs(z.imag) > CM_LARGE_DOUBLE) { + /* avoid unnecessary overflow for large arguments */ + r.real = atan2(fabs(z.imag), z.real); + /* split into cases to make sure that the branch cut has the + correct continuity on systems with unsigned zeros */ + if (z.real < 0.) { + r.imag = -copysign(log(hypot(z.real/2., z.imag/2.)) + + M_LN2*2., z.imag); + } else { + r.imag = copysign(log(hypot(z.real/2., z.imag/2.)) + + M_LN2*2., -z.imag); + } + } else { + s1.real = 1.-z.real; + s1.imag = -z.imag; + s1 = c_sqrt(s1); + s2.real = 1.+z.real; + s2.imag = z.imag; + s2 = c_sqrt(s2); + r.real = 2.*atan2(s1.real, s2.real); + r.imag = m_asinh(s2.real*s1.imag - s2.imag*s1.real); + } + errno = 0; + return r; } PyDoc_STRVAR(c_acos_doc, @@ -167,26 +167,26 @@ static Py_complex c_acosh(Py_complex z) { - Py_complex s1, s2, r; + Py_complex s1, s2, r; - SPECIAL_VALUE(z, acosh_special_values); + SPECIAL_VALUE(z, acosh_special_values); - if (fabs(z.real) > CM_LARGE_DOUBLE || fabs(z.imag) > CM_LARGE_DOUBLE) { - /* avoid unnecessary overflow for large arguments */ - r.real = log(hypot(z.real/2., z.imag/2.)) + M_LN2*2.; - r.imag = atan2(z.imag, z.real); - } else { - s1.real = z.real - 1.; - s1.imag = z.imag; - s1 = c_sqrt(s1); - s2.real = z.real + 1.; - s2.imag = z.imag; - s2 = c_sqrt(s2); - r.real = m_asinh(s1.real*s2.real + s1.imag*s2.imag); - r.imag = 2.*atan2(s1.imag, s2.real); - } - errno = 0; - return r; + if (fabs(z.real) > CM_LARGE_DOUBLE || fabs(z.imag) > CM_LARGE_DOUBLE) { + /* avoid unnecessary overflow for large arguments */ + r.real = log(hypot(z.real/2., z.imag/2.)) + M_LN2*2.; + r.imag = atan2(z.imag, z.real); + } else { + s1.real = z.real - 1.; + s1.imag = z.imag; + s1 = c_sqrt(s1); + s2.real = z.real + 1.; + s2.imag = z.imag; + s2 = c_sqrt(s2); + r.real = m_asinh(s1.real*s2.real + s1.imag*s2.imag); + r.imag = 2.*atan2(s1.imag, s2.real); + } + errno = 0; + return r; } PyDoc_STRVAR(c_acosh_doc, @@ -198,14 +198,14 @@ static Py_complex c_asin(Py_complex z) { - /* asin(z) = -i asinh(iz) */ - Py_complex s, r; - s.real = -z.imag; - s.imag = z.real; - s = c_asinh(s); - r.real = s.imag; - r.imag = -s.real; - return r; + /* asin(z) = -i asinh(iz) */ + Py_complex s, r; + s.real = -z.imag; + s.imag = z.real; + s = c_asinh(s); + r.real = s.imag; + r.imag = -s.real; + return r; } PyDoc_STRVAR(c_asin_doc, @@ -219,31 +219,31 @@ static Py_complex c_asinh(Py_complex z) { - Py_complex s1, s2, r; + Py_complex s1, s2, r; - SPECIAL_VALUE(z, asinh_special_values); + SPECIAL_VALUE(z, asinh_special_values); - if (fabs(z.real) > CM_LARGE_DOUBLE || fabs(z.imag) > CM_LARGE_DOUBLE) { - if (z.imag >= 0.) { - r.real = copysign(log(hypot(z.real/2., z.imag/2.)) + - M_LN2*2., z.real); - } else { - r.real = -copysign(log(hypot(z.real/2., z.imag/2.)) + - M_LN2*2., -z.real); - } - r.imag = atan2(z.imag, fabs(z.real)); - } else { - s1.real = 1.+z.imag; - s1.imag = -z.real; - s1 = c_sqrt(s1); - s2.real = 1.-z.imag; - s2.imag = z.real; - s2 = c_sqrt(s2); - r.real = m_asinh(s1.real*s2.imag-s2.real*s1.imag); - r.imag = atan2(z.imag, s1.real*s2.real-s1.imag*s2.imag); - } - errno = 0; - return r; + if (fabs(z.real) > CM_LARGE_DOUBLE || fabs(z.imag) > CM_LARGE_DOUBLE) { + if (z.imag >= 0.) { + r.real = copysign(log(hypot(z.real/2., z.imag/2.)) + + M_LN2*2., z.real); + } else { + r.real = -copysign(log(hypot(z.real/2., z.imag/2.)) + + M_LN2*2., -z.real); + } + r.imag = atan2(z.imag, fabs(z.real)); + } else { + s1.real = 1.+z.imag; + s1.imag = -z.real; + s1 = c_sqrt(s1); + s2.real = 1.-z.imag; + s2.imag = z.real; + s2 = c_sqrt(s2); + r.real = m_asinh(s1.real*s2.imag-s2.real*s1.imag); + r.imag = atan2(z.imag, s1.real*s2.real-s1.imag*s2.imag); + } + errno = 0; + return r; } PyDoc_STRVAR(c_asinh_doc, @@ -255,14 +255,14 @@ static Py_complex c_atan(Py_complex z) { - /* atan(z) = -i atanh(iz) */ - Py_complex s, r; - s.real = -z.imag; - s.imag = z.real; - s = c_atanh(s); - r.real = s.imag; - r.imag = -s.real; - return r; + /* atan(z) = -i atanh(iz) */ + Py_complex s, r; + s.real = -z.imag; + s.imag = z.real; + s = c_atanh(s); + r.real = s.imag; + r.imag = -s.real; + return r; } /* Windows screws up atan2 for inf and nan, and alpha Tru64 5.1 doesn't follow @@ -270,29 +270,29 @@ static double c_atan2(Py_complex z) { - if (Py_IS_NAN(z.real) || Py_IS_NAN(z.imag)) - return Py_NAN; - if (Py_IS_INFINITY(z.imag)) { - if (Py_IS_INFINITY(z.real)) { - if (copysign(1., z.real) == 1.) - /* atan2(+-inf, +inf) == +-pi/4 */ - return copysign(0.25*Py_MATH_PI, z.imag); - else - /* atan2(+-inf, -inf) == +-pi*3/4 */ - return copysign(0.75*Py_MATH_PI, z.imag); - } - /* atan2(+-inf, x) == +-pi/2 for finite x */ - return copysign(0.5*Py_MATH_PI, z.imag); - } - if (Py_IS_INFINITY(z.real) || z.imag == 0.) { - if (copysign(1., z.real) == 1.) - /* atan2(+-y, +inf) = atan2(+-0, +x) = +-0. */ - return copysign(0., z.imag); - else - /* atan2(+-y, -inf) = atan2(+-0., -x) = +-pi. */ - return copysign(Py_MATH_PI, z.imag); - } - return atan2(z.imag, z.real); + if (Py_IS_NAN(z.real) || Py_IS_NAN(z.imag)) + return Py_NAN; + if (Py_IS_INFINITY(z.imag)) { + if (Py_IS_INFINITY(z.real)) { + if (copysign(1., z.real) == 1.) + /* atan2(+-inf, +inf) == +-pi/4 */ + return copysign(0.25*Py_MATH_PI, z.imag); + else + /* atan2(+-inf, -inf) == +-pi*3/4 */ + return copysign(0.75*Py_MATH_PI, z.imag); + } + /* atan2(+-inf, x) == +-pi/2 for finite x */ + return copysign(0.5*Py_MATH_PI, z.imag); + } + if (Py_IS_INFINITY(z.real) || z.imag == 0.) { + if (copysign(1., z.real) == 1.) + /* atan2(+-y, +inf) = atan2(+-0, +x) = +-0. */ + return copysign(0., z.imag); + else + /* atan2(+-y, -inf) = atan2(+-0., -x) = +-pi. */ + return copysign(Py_MATH_PI, z.imag); + } + return atan2(z.imag, z.real); } PyDoc_STRVAR(c_atan_doc, @@ -306,48 +306,48 @@ static Py_complex c_atanh(Py_complex z) { - Py_complex r; - double ay, h; + Py_complex r; + double ay, h; - SPECIAL_VALUE(z, atanh_special_values); + SPECIAL_VALUE(z, atanh_special_values); - /* Reduce to case where z.real >= 0., using atanh(z) = -atanh(-z). */ - if (z.real < 0.) { - return c_neg(c_atanh(c_neg(z))); - } - - ay = fabs(z.imag); - if (z.real > CM_SQRT_LARGE_DOUBLE || ay > CM_SQRT_LARGE_DOUBLE) { - /* - if abs(z) is large then we use the approximation - atanh(z) ~ 1/z +/- i*pi/2 (+/- depending on the sign - of z.imag) - */ - h = hypot(z.real/2., z.imag/2.); /* safe from overflow */ - r.real = z.real/4./h/h; - /* the two negations in the next line cancel each other out - except when working with unsigned zeros: they're there to - ensure that the branch cut has the correct continuity on - systems that don't support signed zeros */ - r.imag = -copysign(Py_MATH_PI/2., -z.imag); - errno = 0; - } else if (z.real == 1. && ay < CM_SQRT_DBL_MIN) { - /* C99 standard says: atanh(1+/-0.) should be inf +/- 0i */ - if (ay == 0.) { - r.real = INF; - r.imag = z.imag; - errno = EDOM; - } else { - r.real = -log(sqrt(ay)/sqrt(hypot(ay, 2.))); - r.imag = copysign(atan2(2., -ay)/2, z.imag); - errno = 0; - } - } else { - r.real = m_log1p(4.*z.real/((1-z.real)*(1-z.real) + ay*ay))/4.; - r.imag = -atan2(-2.*z.imag, (1-z.real)*(1+z.real) - ay*ay)/2.; - errno = 0; - } - return r; + /* Reduce to case where z.real >= 0., using atanh(z) = -atanh(-z). */ + if (z.real < 0.) { + return c_neg(c_atanh(c_neg(z))); + } + + ay = fabs(z.imag); + if (z.real > CM_SQRT_LARGE_DOUBLE || ay > CM_SQRT_LARGE_DOUBLE) { + /* + if abs(z) is large then we use the approximation + atanh(z) ~ 1/z +/- i*pi/2 (+/- depending on the sign + of z.imag) + */ + h = hypot(z.real/2., z.imag/2.); /* safe from overflow */ + r.real = z.real/4./h/h; + /* the two negations in the next line cancel each other out + except when working with unsigned zeros: they're there to + ensure that the branch cut has the correct continuity on + systems that don't support signed zeros */ + r.imag = -copysign(Py_MATH_PI/2., -z.imag); + errno = 0; + } else if (z.real == 1. && ay < CM_SQRT_DBL_MIN) { + /* C99 standard says: atanh(1+/-0.) should be inf +/- 0i */ + if (ay == 0.) { + r.real = INF; + r.imag = z.imag; + errno = EDOM; + } else { + r.real = -log(sqrt(ay)/sqrt(hypot(ay, 2.))); + r.imag = copysign(atan2(2., -ay)/2, z.imag); + errno = 0; + } + } else { + r.real = m_log1p(4.*z.real/((1-z.real)*(1-z.real) + ay*ay))/4.; + r.imag = -atan2(-2.*z.imag, (1-z.real)*(1+z.real) - ay*ay)/2.; + errno = 0; + } + return r; } PyDoc_STRVAR(c_atanh_doc, @@ -359,12 +359,12 @@ static Py_complex c_cos(Py_complex z) { - /* cos(z) = cosh(iz) */ - Py_complex r; - r.real = -z.imag; - r.imag = z.real; - r = c_cosh(r); - return r; + /* cos(z) = cosh(iz) */ + Py_complex r; + r.real = -z.imag; + r.imag = z.real; + r = c_cosh(r); + return r; } PyDoc_STRVAR(c_cos_doc, @@ -379,51 +379,51 @@ static Py_complex c_cosh(Py_complex z) { - Py_complex r; - double x_minus_one; + Py_complex r; + double x_minus_one; - /* special treatment for cosh(+/-inf + iy) if y is not a NaN */ - if (!Py_IS_FINITE(z.real) || !Py_IS_FINITE(z.imag)) { - if (Py_IS_INFINITY(z.real) && Py_IS_FINITE(z.imag) && - (z.imag != 0.)) { - if (z.real > 0) { - r.real = copysign(INF, cos(z.imag)); - r.imag = copysign(INF, sin(z.imag)); - } - else { - r.real = copysign(INF, cos(z.imag)); - r.imag = -copysign(INF, sin(z.imag)); - } - } - else { - r = cosh_special_values[special_type(z.real)] - [special_type(z.imag)]; - } - /* need to set errno = EDOM if y is +/- infinity and x is not - a NaN */ - if (Py_IS_INFINITY(z.imag) && !Py_IS_NAN(z.real)) - errno = EDOM; - else - errno = 0; - return r; - } - - if (fabs(z.real) > CM_LOG_LARGE_DOUBLE) { - /* deal correctly with cases where cosh(z.real) overflows but - cosh(z) does not. */ - x_minus_one = z.real - copysign(1., z.real); - r.real = cos(z.imag) * cosh(x_minus_one) * Py_MATH_E; - r.imag = sin(z.imag) * sinh(x_minus_one) * Py_MATH_E; - } else { - r.real = cos(z.imag) * cosh(z.real); - r.imag = sin(z.imag) * sinh(z.real); - } - /* detect overflow, and set errno accordingly */ - if (Py_IS_INFINITY(r.real) || Py_IS_INFINITY(r.imag)) - errno = ERANGE; - else - errno = 0; - return r; + /* special treatment for cosh(+/-inf + iy) if y is not a NaN */ + if (!Py_IS_FINITE(z.real) || !Py_IS_FINITE(z.imag)) { + if (Py_IS_INFINITY(z.real) && Py_IS_FINITE(z.imag) && + (z.imag != 0.)) { + if (z.real > 0) { + r.real = copysign(INF, cos(z.imag)); + r.imag = copysign(INF, sin(z.imag)); + } + else { + r.real = copysign(INF, cos(z.imag)); + r.imag = -copysign(INF, sin(z.imag)); + } + } + else { + r = cosh_special_values[special_type(z.real)] + [special_type(z.imag)]; + } + /* need to set errno = EDOM if y is +/- infinity and x is not + a NaN */ + if (Py_IS_INFINITY(z.imag) && !Py_IS_NAN(z.real)) + errno = EDOM; + else + errno = 0; + return r; + } + + if (fabs(z.real) > CM_LOG_LARGE_DOUBLE) { + /* deal correctly with cases where cosh(z.real) overflows but + cosh(z) does not. */ + x_minus_one = z.real - copysign(1., z.real); + r.real = cos(z.imag) * cosh(x_minus_one) * Py_MATH_E; + r.imag = sin(z.imag) * sinh(x_minus_one) * Py_MATH_E; + } else { + r.real = cos(z.imag) * cosh(z.real); + r.imag = sin(z.imag) * sinh(z.real); + } + /* detect overflow, and set errno accordingly */ + if (Py_IS_INFINITY(r.real) || Py_IS_INFINITY(r.imag)) + errno = ERANGE; + else + errno = 0; + return r; } PyDoc_STRVAR(c_cosh_doc, @@ -439,51 +439,51 @@ static Py_complex c_exp(Py_complex z) { - Py_complex r; - double l; + Py_complex r; + double l; - if (!Py_IS_FINITE(z.real) || !Py_IS_FINITE(z.imag)) { - if (Py_IS_INFINITY(z.real) && Py_IS_FINITE(z.imag) - && (z.imag != 0.)) { - if (z.real > 0) { - r.real = copysign(INF, cos(z.imag)); - r.imag = copysign(INF, sin(z.imag)); - } - else { - r.real = copysign(0., cos(z.imag)); - r.imag = copysign(0., sin(z.imag)); - } - } - else { - r = exp_special_values[special_type(z.real)] - [special_type(z.imag)]; - } - /* need to set errno = EDOM if y is +/- infinity and x is not - a NaN and not -infinity */ - if (Py_IS_INFINITY(z.imag) && - (Py_IS_FINITE(z.real) || - (Py_IS_INFINITY(z.real) && z.real > 0))) - errno = EDOM; - else - errno = 0; - return r; - } - - if (z.real > CM_LOG_LARGE_DOUBLE) { - l = exp(z.real-1.); - r.real = l*cos(z.imag)*Py_MATH_E; - r.imag = l*sin(z.imag)*Py_MATH_E; - } else { - l = exp(z.real); - r.real = l*cos(z.imag); - r.imag = l*sin(z.imag); - } - /* detect overflow, and set errno accordingly */ - if (Py_IS_INFINITY(r.real) || Py_IS_INFINITY(r.imag)) - errno = ERANGE; - else - errno = 0; - return r; + if (!Py_IS_FINITE(z.real) || !Py_IS_FINITE(z.imag)) { + if (Py_IS_INFINITY(z.real) && Py_IS_FINITE(z.imag) + && (z.imag != 0.)) { + if (z.real > 0) { + r.real = copysign(INF, cos(z.imag)); + r.imag = copysign(INF, sin(z.imag)); + } + else { + r.real = copysign(0., cos(z.imag)); + r.imag = copysign(0., sin(z.imag)); + } + } + else { + r = exp_special_values[special_type(z.real)] + [special_type(z.imag)]; + } + /* need to set errno = EDOM if y is +/- infinity and x is not + a NaN and not -infinity */ + if (Py_IS_INFINITY(z.imag) && + (Py_IS_FINITE(z.real) || + (Py_IS_INFINITY(z.real) && z.real > 0))) + errno = EDOM; + else + errno = 0; + return r; + } + + if (z.real > CM_LOG_LARGE_DOUBLE) { + l = exp(z.real-1.); + r.real = l*cos(z.imag)*Py_MATH_E; + r.imag = l*sin(z.imag)*Py_MATH_E; + } else { + l = exp(z.real); + r.real = l*cos(z.imag); + r.imag = l*sin(z.imag); + } + /* detect overflow, and set errno accordingly */ + if (Py_IS_INFINITY(r.real) || Py_IS_INFINITY(r.imag)) + errno = ERANGE; + else + errno = 0; + return r; } PyDoc_STRVAR(c_exp_doc, @@ -497,85 +497,85 @@ static Py_complex c_log(Py_complex z) { - /* - The usual formula for the real part is log(hypot(z.real, z.imag)). - There are four situations where this formula is potentially - problematic: - - (1) the absolute value of z is subnormal. Then hypot is subnormal, - so has fewer than the usual number of bits of accuracy, hence may - have large relative error. This then gives a large absolute error - in the log. This can be solved by rescaling z by a suitable power - of 2. - - (2) the absolute value of z is greater than DBL_MAX (e.g. when both - z.real and z.imag are within a factor of 1/sqrt(2) of DBL_MAX) - Again, rescaling solves this. - - (3) the absolute value of z is close to 1. In this case it's - difficult to achieve good accuracy, at least in part because a - change of 1ulp in the real or imaginary part of z can result in a - change of billions of ulps in the correctly rounded answer. - - (4) z = 0. The simplest thing to do here is to call the - floating-point log with an argument of 0, and let its behaviour - (returning -infinity, signaling a floating-point exception, setting - errno, or whatever) determine that of c_log. So the usual formula - is fine here. - - */ - - Py_complex r; - double ax, ay, am, an, h; - - SPECIAL_VALUE(z, log_special_values); - - ax = fabs(z.real); - ay = fabs(z.imag); - - if (ax > CM_LARGE_DOUBLE || ay > CM_LARGE_DOUBLE) { - r.real = log(hypot(ax/2., ay/2.)) + M_LN2; - } else if (ax < DBL_MIN && ay < DBL_MIN) { - if (ax > 0. || ay > 0.) { - /* catch cases where hypot(ax, ay) is subnormal */ - r.real = log(hypot(ldexp(ax, DBL_MANT_DIG), - ldexp(ay, DBL_MANT_DIG))) - DBL_MANT_DIG*M_LN2; - } - else { - /* log(+/-0. +/- 0i) */ - r.real = -INF; - r.imag = atan2(z.imag, z.real); - errno = EDOM; - return r; - } - } else { - h = hypot(ax, ay); - if (0.71 <= h && h <= 1.73) { - am = ax > ay ? ax : ay; /* max(ax, ay) */ - an = ax > ay ? ay : ax; /* min(ax, ay) */ - r.real = m_log1p((am-1)*(am+1)+an*an)/2.; - } else { - r.real = log(h); - } - } - r.imag = atan2(z.imag, z.real); - errno = 0; - return r; + /* + The usual formula for the real part is log(hypot(z.real, z.imag)). + There are four situations where this formula is potentially + problematic: + + (1) the absolute value of z is subnormal. Then hypot is subnormal, + so has fewer than the usual number of bits of accuracy, hence may + have large relative error. This then gives a large absolute error + in the log. This can be solved by rescaling z by a suitable power + of 2. + + (2) the absolute value of z is greater than DBL_MAX (e.g. when both + z.real and z.imag are within a factor of 1/sqrt(2) of DBL_MAX) + Again, rescaling solves this. + + (3) the absolute value of z is close to 1. In this case it's + difficult to achieve good accuracy, at least in part because a + change of 1ulp in the real or imaginary part of z can result in a + change of billions of ulps in the correctly rounded answer. + + (4) z = 0. The simplest thing to do here is to call the + floating-point log with an argument of 0, and let its behaviour + (returning -infinity, signaling a floating-point exception, setting + errno, or whatever) determine that of c_log. So the usual formula + is fine here. + + */ + + Py_complex r; + double ax, ay, am, an, h; + + SPECIAL_VALUE(z, log_special_values); + + ax = fabs(z.real); + ay = fabs(z.imag); + + if (ax > CM_LARGE_DOUBLE || ay > CM_LARGE_DOUBLE) { + r.real = log(hypot(ax/2., ay/2.)) + M_LN2; + } else if (ax < DBL_MIN && ay < DBL_MIN) { + if (ax > 0. || ay > 0.) { + /* catch cases where hypot(ax, ay) is subnormal */ + r.real = log(hypot(ldexp(ax, DBL_MANT_DIG), + ldexp(ay, DBL_MANT_DIG))) - DBL_MANT_DIG*M_LN2; + } + else { + /* log(+/-0. +/- 0i) */ + r.real = -INF; + r.imag = atan2(z.imag, z.real); + errno = EDOM; + return r; + } + } else { + h = hypot(ax, ay); + if (0.71 <= h && h <= 1.73) { + am = ax > ay ? ax : ay; /* max(ax, ay) */ + an = ax > ay ? ay : ax; /* min(ax, ay) */ + r.real = m_log1p((am-1)*(am+1)+an*an)/2.; + } else { + r.real = log(h); + } + } + r.imag = atan2(z.imag, z.real); + errno = 0; + return r; } static Py_complex c_log10(Py_complex z) { - Py_complex r; - int errno_save; + Py_complex r; + int errno_save; - r = c_log(z); - errno_save = errno; /* just in case the divisions affect errno */ - r.real = r.real / M_LN10; - r.imag = r.imag / M_LN10; - errno = errno_save; - return r; + r = c_log(z); + errno_save = errno; /* just in case the divisions affect errno */ + r.real = r.real / M_LN10; + r.imag = r.imag / M_LN10; + errno = errno_save; + return r; } PyDoc_STRVAR(c_log10_doc, @@ -587,14 +587,14 @@ static Py_complex c_sin(Py_complex z) { - /* sin(z) = -i sin(iz) */ - Py_complex s, r; - s.real = -z.imag; - s.imag = z.real; - s = c_sinh(s); - r.real = s.imag; - r.imag = -s.real; - return r; + /* sin(z) = -i sin(iz) */ + Py_complex s, r; + s.real = -z.imag; + s.imag = z.real; + s = c_sinh(s); + r.real = s.imag; + r.imag = -s.real; + return r; } PyDoc_STRVAR(c_sin_doc, @@ -609,50 +609,50 @@ static Py_complex c_sinh(Py_complex z) { - Py_complex r; - double x_minus_one; + Py_complex r; + double x_minus_one; - /* special treatment for sinh(+/-inf + iy) if y is finite and - nonzero */ - if (!Py_IS_FINITE(z.real) || !Py_IS_FINITE(z.imag)) { - if (Py_IS_INFINITY(z.real) && Py_IS_FINITE(z.imag) - && (z.imag != 0.)) { - if (z.real > 0) { - r.real = copysign(INF, cos(z.imag)); - r.imag = copysign(INF, sin(z.imag)); - } - else { - r.real = -copysign(INF, cos(z.imag)); - r.imag = copysign(INF, sin(z.imag)); - } - } - else { - r = sinh_special_values[special_type(z.real)] - [special_type(z.imag)]; - } - /* need to set errno = EDOM if y is +/- infinity and x is not - a NaN */ - if (Py_IS_INFINITY(z.imag) && !Py_IS_NAN(z.real)) - errno = EDOM; - else - errno = 0; - return r; - } - - if (fabs(z.real) > CM_LOG_LARGE_DOUBLE) { - x_minus_one = z.real - copysign(1., z.real); - r.real = cos(z.imag) * sinh(x_minus_one) * Py_MATH_E; - r.imag = sin(z.imag) * cosh(x_minus_one) * Py_MATH_E; - } else { - r.real = cos(z.imag) * sinh(z.real); - r.imag = sin(z.imag) * cosh(z.real); - } - /* detect overflow, and set errno accordingly */ - if (Py_IS_INFINITY(r.real) || Py_IS_INFINITY(r.imag)) - errno = ERANGE; - else - errno = 0; - return r; + /* special treatment for sinh(+/-inf + iy) if y is finite and + nonzero */ + if (!Py_IS_FINITE(z.real) || !Py_IS_FINITE(z.imag)) { + if (Py_IS_INFINITY(z.real) && Py_IS_FINITE(z.imag) + && (z.imag != 0.)) { + if (z.real > 0) { + r.real = copysign(INF, cos(z.imag)); + r.imag = copysign(INF, sin(z.imag)); + } + else { + r.real = -copysign(INF, cos(z.imag)); + r.imag = copysign(INF, sin(z.imag)); + } + } + else { + r = sinh_special_values[special_type(z.real)] + [special_type(z.imag)]; + } + /* need to set errno = EDOM if y is +/- infinity and x is not + a NaN */ + if (Py_IS_INFINITY(z.imag) && !Py_IS_NAN(z.real)) + errno = EDOM; + else + errno = 0; + return r; + } + + if (fabs(z.real) > CM_LOG_LARGE_DOUBLE) { + x_minus_one = z.real - copysign(1., z.real); + r.real = cos(z.imag) * sinh(x_minus_one) * Py_MATH_E; + r.imag = sin(z.imag) * cosh(x_minus_one) * Py_MATH_E; + } else { + r.real = cos(z.imag) * sinh(z.real); + r.imag = sin(z.imag) * cosh(z.real); + } + /* detect overflow, and set errno accordingly */ + if (Py_IS_INFINITY(r.real) || Py_IS_INFINITY(r.imag)) + errno = ERANGE; + else + errno = 0; + return r; } PyDoc_STRVAR(c_sinh_doc, @@ -666,68 +666,68 @@ static Py_complex c_sqrt(Py_complex z) { - /* - Method: use symmetries to reduce to the case when x = z.real and y - = z.imag are nonnegative. Then the real part of the result is - given by - - s = sqrt((x + hypot(x, y))/2) - - and the imaginary part is - - d = (y/2)/s - - If either x or y is very large then there's a risk of overflow in - computation of the expression x + hypot(x, y). We can avoid this - by rewriting the formula for s as: - - s = 2*sqrt(x/8 + hypot(x/8, y/8)) - - This costs us two extra multiplications/divisions, but avoids the - overhead of checking for x and y large. - - If both x and y are subnormal then hypot(x, y) may also be - subnormal, so will lack full precision. We solve this by rescaling - x and y by a sufficiently large power of 2 to ensure that x and y - are normal. - */ - - - Py_complex r; - double s,d; - double ax, ay; - - SPECIAL_VALUE(z, sqrt_special_values); - - if (z.real == 0. && z.imag == 0.) { - r.real = 0.; - r.imag = z.imag; - return r; - } - - ax = fabs(z.real); - ay = fabs(z.imag); - - if (ax < DBL_MIN && ay < DBL_MIN && (ax > 0. || ay > 0.)) { - /* here we catch cases where hypot(ax, ay) is subnormal */ - ax = ldexp(ax, CM_SCALE_UP); - s = ldexp(sqrt(ax + hypot(ax, ldexp(ay, CM_SCALE_UP))), - CM_SCALE_DOWN); - } else { - ax /= 8.; - s = 2.*sqrt(ax + hypot(ax, ay/8.)); - } - d = ay/(2.*s); - - if (z.real >= 0.) { - r.real = s; - r.imag = copysign(d, z.imag); - } else { - r.real = d; - r.imag = copysign(s, z.imag); - } - errno = 0; - return r; + /* + Method: use symmetries to reduce to the case when x = z.real and y + = z.imag are nonnegative. Then the real part of the result is + given by + + s = sqrt((x + hypot(x, y))/2) + + and the imaginary part is + + d = (y/2)/s + + If either x or y is very large then there's a risk of overflow in + computation of the expression x + hypot(x, y). We can avoid this + by rewriting the formula for s as: + + s = 2*sqrt(x/8 + hypot(x/8, y/8)) + + This costs us two extra multiplications/divisions, but avoids the + overhead of checking for x and y large. + + If both x and y are subnormal then hypot(x, y) may also be + subnormal, so will lack full precision. We solve this by rescaling + x and y by a sufficiently large power of 2 to ensure that x and y + are normal. + */ + + + Py_complex r; + double s,d; + double ax, ay; + + SPECIAL_VALUE(z, sqrt_special_values); + + if (z.real == 0. && z.imag == 0.) { + r.real = 0.; + r.imag = z.imag; + return r; + } + + ax = fabs(z.real); + ay = fabs(z.imag); + + if (ax < DBL_MIN && ay < DBL_MIN && (ax > 0. || ay > 0.)) { + /* here we catch cases where hypot(ax, ay) is subnormal */ + ax = ldexp(ax, CM_SCALE_UP); + s = ldexp(sqrt(ax + hypot(ax, ldexp(ay, CM_SCALE_UP))), + CM_SCALE_DOWN); + } else { + ax /= 8.; + s = 2.*sqrt(ax + hypot(ax, ay/8.)); + } + d = ay/(2.*s); + + if (z.real >= 0.) { + r.real = s; + r.imag = copysign(d, z.imag); + } else { + r.real = d; + r.imag = copysign(s, z.imag); + } + errno = 0; + return r; } PyDoc_STRVAR(c_sqrt_doc, @@ -739,14 +739,14 @@ static Py_complex c_tan(Py_complex z) { - /* tan(z) = -i tanh(iz) */ - Py_complex s, r; - s.real = -z.imag; - s.imag = z.real; - s = c_tanh(s); - r.real = s.imag; - r.imag = -s.real; - return r; + /* tan(z) = -i tanh(iz) */ + Py_complex s, r; + s.real = -z.imag; + s.imag = z.real; + s = c_tanh(s); + r.real = s.imag; + r.imag = -s.real; + return r; } PyDoc_STRVAR(c_tan_doc, @@ -761,65 +761,65 @@ static Py_complex c_tanh(Py_complex z) { - /* Formula: + /* Formula: - tanh(x+iy) = (tanh(x)(1+tan(y)^2) + i tan(y)(1-tanh(x))^2) / - (1+tan(y)^2 tanh(x)^2) + tanh(x+iy) = (tanh(x)(1+tan(y)^2) + i tan(y)(1-tanh(x))^2) / + (1+tan(y)^2 tanh(x)^2) - To avoid excessive roundoff error, 1-tanh(x)^2 is better computed - as 1/cosh(x)^2. When abs(x) is large, we approximate 1-tanh(x)^2 - by 4 exp(-2*x) instead, to avoid possible overflow in the - computation of cosh(x). - - */ - - Py_complex r; - double tx, ty, cx, txty, denom; - - /* special treatment for tanh(+/-inf + iy) if y is finite and - nonzero */ - if (!Py_IS_FINITE(z.real) || !Py_IS_FINITE(z.imag)) { - if (Py_IS_INFINITY(z.real) && Py_IS_FINITE(z.imag) - && (z.imag != 0.)) { - if (z.real > 0) { - r.real = 1.0; - r.imag = copysign(0., - 2.*sin(z.imag)*cos(z.imag)); - } - else { - r.real = -1.0; - r.imag = copysign(0., - 2.*sin(z.imag)*cos(z.imag)); - } - } - else { - r = tanh_special_values[special_type(z.real)] - [special_type(z.imag)]; - } - /* need to set errno = EDOM if z.imag is +/-infinity and - z.real is finite */ - if (Py_IS_INFINITY(z.imag) && Py_IS_FINITE(z.real)) - errno = EDOM; - else - errno = 0; - return r; - } - - /* danger of overflow in 2.*z.imag !*/ - if (fabs(z.real) > CM_LOG_LARGE_DOUBLE) { - r.real = copysign(1., z.real); - r.imag = 4.*sin(z.imag)*cos(z.imag)*exp(-2.*fabs(z.real)); - } else { - tx = tanh(z.real); - ty = tan(z.imag); - cx = 1./cosh(z.real); - txty = tx*ty; - denom = 1. + txty*txty; - r.real = tx*(1.+ty*ty)/denom; - r.imag = ((ty/denom)*cx)*cx; - } - errno = 0; - return r; + To avoid excessive roundoff error, 1-tanh(x)^2 is better computed + as 1/cosh(x)^2. When abs(x) is large, we approximate 1-tanh(x)^2 + by 4 exp(-2*x) instead, to avoid possible overflow in the + computation of cosh(x). + + */ + + Py_complex r; + double tx, ty, cx, txty, denom; + + /* special treatment for tanh(+/-inf + iy) if y is finite and + nonzero */ + if (!Py_IS_FINITE(z.real) || !Py_IS_FINITE(z.imag)) { + if (Py_IS_INFINITY(z.real) && Py_IS_FINITE(z.imag) + && (z.imag != 0.)) { + if (z.real > 0) { + r.real = 1.0; + r.imag = copysign(0., + 2.*sin(z.imag)*cos(z.imag)); + } + else { + r.real = -1.0; + r.imag = copysign(0., + 2.*sin(z.imag)*cos(z.imag)); + } + } + else { + r = tanh_special_values[special_type(z.real)] + [special_type(z.imag)]; + } + /* need to set errno = EDOM if z.imag is +/-infinity and + z.real is finite */ + if (Py_IS_INFINITY(z.imag) && Py_IS_FINITE(z.real)) + errno = EDOM; + else + errno = 0; + return r; + } + + /* danger of overflow in 2.*z.imag !*/ + if (fabs(z.real) > CM_LOG_LARGE_DOUBLE) { + r.real = copysign(1., z.real); + r.imag = 4.*sin(z.imag)*cos(z.imag)*exp(-2.*fabs(z.real)); + } else { + tx = tanh(z.real); + ty = tan(z.imag); + cx = 1./cosh(z.real); + txty = tx*ty; + denom = 1. + txty*txty; + r.real = tx*(1.+ty*ty)/denom; + r.imag = ((ty/denom)*cx)*cx; + } + errno = 0; + return r; } PyDoc_STRVAR(c_tanh_doc, @@ -831,23 +831,23 @@ static PyObject * cmath_log(PyObject *self, PyObject *args) { - Py_complex x; - Py_complex y; + Py_complex x; + Py_complex y; - if (!PyArg_ParseTuple(args, "D|D", &x, &y)) - return NULL; + if (!PyArg_ParseTuple(args, "D|D", &x, &y)) + return NULL; - errno = 0; - PyFPE_START_PROTECT("complex function", return 0) - x = c_log(x); - if (PyTuple_GET_SIZE(args) == 2) { - y = c_log(y); - x = c_quot(x, y); - } - PyFPE_END_PROTECT(x) - if (errno != 0) - return math_error(); - return PyComplex_FromCComplex(x); + errno = 0; + PyFPE_START_PROTECT("complex function", return 0) + x = c_log(x); + if (PyTuple_GET_SIZE(args) == 2) { + y = c_log(y); + x = c_quot(x, y); + } + PyFPE_END_PROTECT(x) + if (errno != 0) + return math_error(); + return PyComplex_FromCComplex(x); } PyDoc_STRVAR(cmath_log_doc, @@ -860,42 +860,42 @@ static PyObject * math_error(void) { - if (errno == EDOM) - PyErr_SetString(PyExc_ValueError, "math domain error"); - else if (errno == ERANGE) - PyErr_SetString(PyExc_OverflowError, "math range error"); - else /* Unexpected math error */ - PyErr_SetFromErrno(PyExc_ValueError); - return NULL; + if (errno == EDOM) + PyErr_SetString(PyExc_ValueError, "math domain error"); + else if (errno == ERANGE) + PyErr_SetString(PyExc_OverflowError, "math range error"); + else /* Unexpected math error */ + PyErr_SetFromErrno(PyExc_ValueError); + return NULL; } static PyObject * math_1(PyObject *args, Py_complex (*func)(Py_complex)) { - Py_complex x,r ; - if (!PyArg_ParseTuple(args, "D", &x)) - return NULL; - errno = 0; - PyFPE_START_PROTECT("complex function", return 0); - r = (*func)(x); - PyFPE_END_PROTECT(r); - if (errno == EDOM) { - PyErr_SetString(PyExc_ValueError, "math domain error"); - return NULL; - } - else if (errno == ERANGE) { - PyErr_SetString(PyExc_OverflowError, "math range error"); - return NULL; - } - else { - return PyComplex_FromCComplex(r); - } + Py_complex x,r ; + if (!PyArg_ParseTuple(args, "D", &x)) + return NULL; + errno = 0; + PyFPE_START_PROTECT("complex function", return 0); + r = (*func)(x); + PyFPE_END_PROTECT(r); + if (errno == EDOM) { + PyErr_SetString(PyExc_ValueError, "math domain error"); + return NULL; + } + else if (errno == ERANGE) { + PyErr_SetString(PyExc_OverflowError, "math range error"); + return NULL; + } + else { + return PyComplex_FromCComplex(r); + } } #define FUNC1(stubname, func) \ - static PyObject * stubname(PyObject *self, PyObject *args) { \ - return math_1(args, func); \ - } + static PyObject * stubname(PyObject *self, PyObject *args) { \ + return math_1(args, func); \ + } FUNC1(cmath_acos, c_acos) FUNC1(cmath_acosh, c_acosh) @@ -916,18 +916,18 @@ static PyObject * cmath_phase(PyObject *self, PyObject *args) { - Py_complex z; - double phi; - if (!PyArg_ParseTuple(args, "D:phase", &z)) - return NULL; - errno = 0; - PyFPE_START_PROTECT("arg function", return 0) - phi = c_atan2(z); - PyFPE_END_PROTECT(phi) - if (errno != 0) - return math_error(); - else - return PyFloat_FromDouble(phi); + Py_complex z; + double phi; + if (!PyArg_ParseTuple(args, "D:phase", &z)) + return NULL; + errno = 0; + PyFPE_START_PROTECT("arg function", return 0) + phi = c_atan2(z); + PyFPE_END_PROTECT(phi) + if (errno != 0) + return math_error(); + else + return PyFloat_FromDouble(phi); } PyDoc_STRVAR(cmath_phase_doc, @@ -937,18 +937,18 @@ static PyObject * cmath_polar(PyObject *self, PyObject *args) { - Py_complex z; - double r, phi; - if (!PyArg_ParseTuple(args, "D:polar", &z)) - return NULL; - PyFPE_START_PROTECT("polar function", return 0) - phi = c_atan2(z); /* should not cause any exception */ - r = c_abs(z); /* sets errno to ERANGE on overflow; otherwise 0 */ - PyFPE_END_PROTECT(r) - if (errno != 0) - return math_error(); - else - return Py_BuildValue("dd", r, phi); + Py_complex z; + double r, phi; + if (!PyArg_ParseTuple(args, "D:polar", &z)) + return NULL; + PyFPE_START_PROTECT("polar function", return 0) + phi = c_atan2(z); /* should not cause any exception */ + r = c_abs(z); /* sets errno to ERANGE on overflow; otherwise 0 */ + PyFPE_END_PROTECT(r) + if (errno != 0) + return math_error(); + else + return Py_BuildValue("dd", r, phi); } PyDoc_STRVAR(cmath_polar_doc, @@ -972,51 +972,51 @@ static PyObject * cmath_rect(PyObject *self, PyObject *args) { - Py_complex z; - double r, phi; - if (!PyArg_ParseTuple(args, "dd:rect", &r, &phi)) - return NULL; - errno = 0; - PyFPE_START_PROTECT("rect function", return 0) - - /* deal with special values */ - if (!Py_IS_FINITE(r) || !Py_IS_FINITE(phi)) { - /* if r is +/-infinity and phi is finite but nonzero then - result is (+-INF +-INF i), but we need to compute cos(phi) - and sin(phi) to figure out the signs. */ - if (Py_IS_INFINITY(r) && (Py_IS_FINITE(phi) - && (phi != 0.))) { - if (r > 0) { - z.real = copysign(INF, cos(phi)); - z.imag = copysign(INF, sin(phi)); - } - else { - z.real = -copysign(INF, cos(phi)); - z.imag = -copysign(INF, sin(phi)); - } - } - else { - z = rect_special_values[special_type(r)] - [special_type(phi)]; - } - /* need to set errno = EDOM if r is a nonzero number and phi - is infinite */ - if (r != 0. && !Py_IS_NAN(r) && Py_IS_INFINITY(phi)) - errno = EDOM; - else - errno = 0; - } - else { - z.real = r * cos(phi); - z.imag = r * sin(phi); - errno = 0; - } - - PyFPE_END_PROTECT(z) - if (errno != 0) - return math_error(); - else - return PyComplex_FromCComplex(z); + Py_complex z; + double r, phi; + if (!PyArg_ParseTuple(args, "dd:rect", &r, &phi)) + return NULL; + errno = 0; + PyFPE_START_PROTECT("rect function", return 0) + + /* deal with special values */ + if (!Py_IS_FINITE(r) || !Py_IS_FINITE(phi)) { + /* if r is +/-infinity and phi is finite but nonzero then + result is (+-INF +-INF i), but we need to compute cos(phi) + and sin(phi) to figure out the signs. */ + if (Py_IS_INFINITY(r) && (Py_IS_FINITE(phi) + && (phi != 0.))) { + if (r > 0) { + z.real = copysign(INF, cos(phi)); + z.imag = copysign(INF, sin(phi)); + } + else { + z.real = -copysign(INF, cos(phi)); + z.imag = -copysign(INF, sin(phi)); + } + } + else { + z = rect_special_values[special_type(r)] + [special_type(phi)]; + } + /* need to set errno = EDOM if r is a nonzero number and phi + is infinite */ + if (r != 0. && !Py_IS_NAN(r) && Py_IS_INFINITY(phi)) + errno = EDOM; + else + errno = 0; + } + else { + z.real = r * cos(phi); + z.imag = r * sin(phi); + errno = 0; + } + + PyFPE_END_PROTECT(z) + if (errno != 0) + return math_error(); + else + return PyComplex_FromCComplex(z); } PyDoc_STRVAR(cmath_rect_doc, @@ -1026,10 +1026,10 @@ static PyObject * cmath_isnan(PyObject *self, PyObject *args) { - Py_complex z; - if (!PyArg_ParseTuple(args, "D:isnan", &z)) - return NULL; - return PyBool_FromLong(Py_IS_NAN(z.real) || Py_IS_NAN(z.imag)); + Py_complex z; + if (!PyArg_ParseTuple(args, "D:isnan", &z)) + return NULL; + return PyBool_FromLong(Py_IS_NAN(z.real) || Py_IS_NAN(z.imag)); } PyDoc_STRVAR(cmath_isnan_doc, @@ -1039,11 +1039,11 @@ static PyObject * cmath_isinf(PyObject *self, PyObject *args) { - Py_complex z; - if (!PyArg_ParseTuple(args, "D:isnan", &z)) - return NULL; - return PyBool_FromLong(Py_IS_INFINITY(z.real) || - Py_IS_INFINITY(z.imag)); + Py_complex z; + if (!PyArg_ParseTuple(args, "D:isnan", &z)) + return NULL; + return PyBool_FromLong(Py_IS_INFINITY(z.real) || + Py_IS_INFINITY(z.imag)); } PyDoc_STRVAR(cmath_isinf_doc, @@ -1056,169 +1056,169 @@ "functions for complex numbers."); static PyMethodDef cmath_methods[] = { - {"acos", cmath_acos, METH_VARARGS, c_acos_doc}, - {"acosh", cmath_acosh, METH_VARARGS, c_acosh_doc}, - {"asin", cmath_asin, METH_VARARGS, c_asin_doc}, - {"asinh", cmath_asinh, METH_VARARGS, c_asinh_doc}, - {"atan", cmath_atan, METH_VARARGS, c_atan_doc}, - {"atanh", cmath_atanh, METH_VARARGS, c_atanh_doc}, - {"cos", cmath_cos, METH_VARARGS, c_cos_doc}, - {"cosh", cmath_cosh, METH_VARARGS, c_cosh_doc}, - {"exp", cmath_exp, METH_VARARGS, c_exp_doc}, - {"isinf", cmath_isinf, METH_VARARGS, cmath_isinf_doc}, - {"isnan", cmath_isnan, METH_VARARGS, cmath_isnan_doc}, - {"log", cmath_log, METH_VARARGS, cmath_log_doc}, - {"log10", cmath_log10, METH_VARARGS, c_log10_doc}, - {"phase", cmath_phase, METH_VARARGS, cmath_phase_doc}, - {"polar", cmath_polar, METH_VARARGS, cmath_polar_doc}, - {"rect", cmath_rect, METH_VARARGS, cmath_rect_doc}, - {"sin", cmath_sin, METH_VARARGS, c_sin_doc}, - {"sinh", cmath_sinh, METH_VARARGS, c_sinh_doc}, - {"sqrt", cmath_sqrt, METH_VARARGS, c_sqrt_doc}, - {"tan", cmath_tan, METH_VARARGS, c_tan_doc}, - {"tanh", cmath_tanh, METH_VARARGS, c_tanh_doc}, - {NULL, NULL} /* sentinel */ + {"acos", cmath_acos, METH_VARARGS, c_acos_doc}, + {"acosh", cmath_acosh, METH_VARARGS, c_acosh_doc}, + {"asin", cmath_asin, METH_VARARGS, c_asin_doc}, + {"asinh", cmath_asinh, METH_VARARGS, c_asinh_doc}, + {"atan", cmath_atan, METH_VARARGS, c_atan_doc}, + {"atanh", cmath_atanh, METH_VARARGS, c_atanh_doc}, + {"cos", cmath_cos, METH_VARARGS, c_cos_doc}, + {"cosh", cmath_cosh, METH_VARARGS, c_cosh_doc}, + {"exp", cmath_exp, METH_VARARGS, c_exp_doc}, + {"isinf", cmath_isinf, METH_VARARGS, cmath_isinf_doc}, + {"isnan", cmath_isnan, METH_VARARGS, cmath_isnan_doc}, + {"log", cmath_log, METH_VARARGS, cmath_log_doc}, + {"log10", cmath_log10, METH_VARARGS, c_log10_doc}, + {"phase", cmath_phase, METH_VARARGS, cmath_phase_doc}, + {"polar", cmath_polar, METH_VARARGS, cmath_polar_doc}, + {"rect", cmath_rect, METH_VARARGS, cmath_rect_doc}, + {"sin", cmath_sin, METH_VARARGS, c_sin_doc}, + {"sinh", cmath_sinh, METH_VARARGS, c_sinh_doc}, + {"sqrt", cmath_sqrt, METH_VARARGS, c_sqrt_doc}, + {"tan", cmath_tan, METH_VARARGS, c_tan_doc}, + {"tanh", cmath_tanh, METH_VARARGS, c_tanh_doc}, + {NULL, NULL} /* sentinel */ }; static struct PyModuleDef cmathmodule = { - PyModuleDef_HEAD_INIT, - "cmath", - module_doc, - -1, - cmath_methods, - NULL, - NULL, - NULL, - NULL + PyModuleDef_HEAD_INIT, + "cmath", + module_doc, + -1, + cmath_methods, + NULL, + NULL, + NULL, + NULL }; PyMODINIT_FUNC PyInit_cmath(void) { - PyObject *m; + PyObject *m; - m = PyModule_Create(&cmathmodule); - if (m == NULL) - return NULL; + m = PyModule_Create(&cmathmodule); + if (m == NULL) + return NULL; - PyModule_AddObject(m, "pi", - PyFloat_FromDouble(Py_MATH_PI)); - PyModule_AddObject(m, "e", PyFloat_FromDouble(Py_MATH_E)); + PyModule_AddObject(m, "pi", + PyFloat_FromDouble(Py_MATH_PI)); + PyModule_AddObject(m, "e", PyFloat_FromDouble(Py_MATH_E)); - /* initialize special value tables */ + /* initialize special value tables */ #define INIT_SPECIAL_VALUES(NAME, BODY) { Py_complex* p = (Py_complex*)NAME; BODY } #define C(REAL, IMAG) p->real = REAL; p->imag = IMAG; ++p; - INIT_SPECIAL_VALUES(acos_special_values, { - C(P34,INF) C(P,INF) C(P,INF) C(P,-INF) C(P,-INF) C(P34,-INF) C(N,INF) - C(P12,INF) C(U,U) C(U,U) C(U,U) C(U,U) C(P12,-INF) C(N,N) - C(P12,INF) C(U,U) C(P12,0.) C(P12,-0.) C(U,U) C(P12,-INF) C(P12,N) - C(P12,INF) C(U,U) C(P12,0.) C(P12,-0.) C(U,U) C(P12,-INF) C(P12,N) - C(P12,INF) C(U,U) C(U,U) C(U,U) C(U,U) C(P12,-INF) C(N,N) - C(P14,INF) C(0.,INF) C(0.,INF) C(0.,-INF) C(0.,-INF) C(P14,-INF) C(N,INF) - C(N,INF) C(N,N) C(N,N) C(N,N) C(N,N) C(N,-INF) C(N,N) - }) - - INIT_SPECIAL_VALUES(acosh_special_values, { - C(INF,-P34) C(INF,-P) C(INF,-P) C(INF,P) C(INF,P) C(INF,P34) C(INF,N) - C(INF,-P12) C(U,U) C(U,U) C(U,U) C(U,U) C(INF,P12) C(N,N) - C(INF,-P12) C(U,U) C(0.,-P12) C(0.,P12) C(U,U) C(INF,P12) C(N,N) - C(INF,-P12) C(U,U) C(0.,-P12) C(0.,P12) C(U,U) C(INF,P12) C(N,N) - C(INF,-P12) C(U,U) C(U,U) C(U,U) C(U,U) C(INF,P12) C(N,N) - C(INF,-P14) C(INF,-0.) C(INF,-0.) C(INF,0.) C(INF,0.) C(INF,P14) C(INF,N) - C(INF,N) C(N,N) C(N,N) C(N,N) C(N,N) C(INF,N) C(N,N) - }) - - INIT_SPECIAL_VALUES(asinh_special_values, { - C(-INF,-P14) C(-INF,-0.) C(-INF,-0.) C(-INF,0.) C(-INF,0.) C(-INF,P14) C(-INF,N) - C(-INF,-P12) C(U,U) C(U,U) C(U,U) C(U,U) C(-INF,P12) C(N,N) - C(-INF,-P12) C(U,U) C(-0.,-0.) C(-0.,0.) C(U,U) C(-INF,P12) C(N,N) - C(INF,-P12) C(U,U) C(0.,-0.) C(0.,0.) C(U,U) C(INF,P12) C(N,N) - C(INF,-P12) C(U,U) C(U,U) C(U,U) C(U,U) C(INF,P12) C(N,N) - C(INF,-P14) C(INF,-0.) C(INF,-0.) C(INF,0.) C(INF,0.) C(INF,P14) C(INF,N) - C(INF,N) C(N,N) C(N,-0.) C(N,0.) C(N,N) C(INF,N) C(N,N) - }) - - INIT_SPECIAL_VALUES(atanh_special_values, { - C(-0.,-P12) C(-0.,-P12) C(-0.,-P12) C(-0.,P12) C(-0.,P12) C(-0.,P12) C(-0.,N) - C(-0.,-P12) C(U,U) C(U,U) C(U,U) C(U,U) C(-0.,P12) C(N,N) - C(-0.,-P12) C(U,U) C(-0.,-0.) C(-0.,0.) C(U,U) C(-0.,P12) C(-0.,N) - C(0.,-P12) C(U,U) C(0.,-0.) C(0.,0.) C(U,U) C(0.,P12) C(0.,N) - C(0.,-P12) C(U,U) C(U,U) C(U,U) C(U,U) C(0.,P12) C(N,N) - C(0.,-P12) C(0.,-P12) C(0.,-P12) C(0.,P12) C(0.,P12) C(0.,P12) C(0.,N) - C(0.,-P12) C(N,N) C(N,N) C(N,N) C(N,N) C(0.,P12) C(N,N) - }) - - INIT_SPECIAL_VALUES(cosh_special_values, { - C(INF,N) C(U,U) C(INF,0.) C(INF,-0.) C(U,U) C(INF,N) C(INF,N) - C(N,N) C(U,U) C(U,U) C(U,U) C(U,U) C(N,N) C(N,N) - C(N,0.) C(U,U) C(1.,0.) C(1.,-0.) C(U,U) C(N,0.) C(N,0.) - C(N,0.) C(U,U) C(1.,-0.) C(1.,0.) C(U,U) C(N,0.) C(N,0.) - C(N,N) C(U,U) C(U,U) C(U,U) C(U,U) C(N,N) C(N,N) - C(INF,N) C(U,U) C(INF,-0.) C(INF,0.) C(U,U) C(INF,N) C(INF,N) - C(N,N) C(N,N) C(N,0.) C(N,0.) C(N,N) C(N,N) C(N,N) - }) - - INIT_SPECIAL_VALUES(exp_special_values, { - C(0.,0.) C(U,U) C(0.,-0.) C(0.,0.) C(U,U) C(0.,0.) C(0.,0.) - C(N,N) C(U,U) C(U,U) C(U,U) C(U,U) C(N,N) C(N,N) - C(N,N) C(U,U) C(1.,-0.) C(1.,0.) C(U,U) C(N,N) C(N,N) - C(N,N) C(U,U) C(1.,-0.) C(1.,0.) C(U,U) C(N,N) C(N,N) - C(N,N) C(U,U) C(U,U) C(U,U) C(U,U) C(N,N) C(N,N) - C(INF,N) C(U,U) C(INF,-0.) C(INF,0.) C(U,U) C(INF,N) C(INF,N) - C(N,N) C(N,N) C(N,-0.) C(N,0.) C(N,N) C(N,N) C(N,N) - }) - - INIT_SPECIAL_VALUES(log_special_values, { - C(INF,-P34) C(INF,-P) C(INF,-P) C(INF,P) C(INF,P) C(INF,P34) C(INF,N) - C(INF,-P12) C(U,U) C(U,U) C(U,U) C(U,U) C(INF,P12) C(N,N) - C(INF,-P12) C(U,U) C(-INF,-P) C(-INF,P) C(U,U) C(INF,P12) C(N,N) - C(INF,-P12) C(U,U) C(-INF,-0.) C(-INF,0.) C(U,U) C(INF,P12) C(N,N) - C(INF,-P12) C(U,U) C(U,U) C(U,U) C(U,U) C(INF,P12) C(N,N) - C(INF,-P14) C(INF,-0.) C(INF,-0.) C(INF,0.) C(INF,0.) C(INF,P14) C(INF,N) - C(INF,N) C(N,N) C(N,N) C(N,N) C(N,N) C(INF,N) C(N,N) - }) - - INIT_SPECIAL_VALUES(sinh_special_values, { - C(INF,N) C(U,U) C(-INF,-0.) C(-INF,0.) C(U,U) C(INF,N) C(INF,N) - C(N,N) C(U,U) C(U,U) C(U,U) C(U,U) C(N,N) C(N,N) - C(0.,N) C(U,U) C(-0.,-0.) C(-0.,0.) C(U,U) C(0.,N) C(0.,N) - C(0.,N) C(U,U) C(0.,-0.) C(0.,0.) C(U,U) C(0.,N) C(0.,N) - C(N,N) C(U,U) C(U,U) C(U,U) C(U,U) C(N,N) C(N,N) - C(INF,N) C(U,U) C(INF,-0.) C(INF,0.) C(U,U) C(INF,N) C(INF,N) - C(N,N) C(N,N) C(N,-0.) C(N,0.) C(N,N) C(N,N) C(N,N) - }) - - INIT_SPECIAL_VALUES(sqrt_special_values, { - C(INF,-INF) C(0.,-INF) C(0.,-INF) C(0.,INF) C(0.,INF) C(INF,INF) C(N,INF) - C(INF,-INF) C(U,U) C(U,U) C(U,U) C(U,U) C(INF,INF) C(N,N) - C(INF,-INF) C(U,U) C(0.,-0.) C(0.,0.) C(U,U) C(INF,INF) C(N,N) - C(INF,-INF) C(U,U) C(0.,-0.) C(0.,0.) C(U,U) C(INF,INF) C(N,N) - C(INF,-INF) C(U,U) C(U,U) C(U,U) C(U,U) C(INF,INF) C(N,N) - C(INF,-INF) C(INF,-0.) C(INF,-0.) C(INF,0.) C(INF,0.) C(INF,INF) C(INF,N) - C(INF,-INF) C(N,N) C(N,N) C(N,N) C(N,N) C(INF,INF) C(N,N) - }) - - INIT_SPECIAL_VALUES(tanh_special_values, { - C(-1.,0.) C(U,U) C(-1.,-0.) C(-1.,0.) C(U,U) C(-1.,0.) C(-1.,0.) - C(N,N) C(U,U) C(U,U) C(U,U) C(U,U) C(N,N) C(N,N) - C(N,N) C(U,U) C(-0.,-0.) C(-0.,0.) C(U,U) C(N,N) C(N,N) - C(N,N) C(U,U) C(0.,-0.) C(0.,0.) C(U,U) C(N,N) C(N,N) - C(N,N) C(U,U) C(U,U) C(U,U) C(U,U) C(N,N) C(N,N) - C(1.,0.) C(U,U) C(1.,-0.) C(1.,0.) C(U,U) C(1.,0.) C(1.,0.) - C(N,N) C(N,N) C(N,-0.) C(N,0.) C(N,N) C(N,N) C(N,N) - }) - - INIT_SPECIAL_VALUES(rect_special_values, { - C(INF,N) C(U,U) C(-INF,0.) C(-INF,-0.) C(U,U) C(INF,N) C(INF,N) - C(N,N) C(U,U) C(U,U) C(U,U) C(U,U) C(N,N) C(N,N) - C(0.,0.) C(U,U) C(-0.,0.) C(-0.,-0.) C(U,U) C(0.,0.) C(0.,0.) - C(0.,0.) C(U,U) C(0.,-0.) C(0.,0.) C(U,U) C(0.,0.) C(0.,0.) - C(N,N) C(U,U) C(U,U) C(U,U) C(U,U) C(N,N) C(N,N) - C(INF,N) C(U,U) C(INF,-0.) C(INF,0.) C(U,U) C(INF,N) C(INF,N) - C(N,N) C(N,N) C(N,0.) C(N,0.) C(N,N) C(N,N) C(N,N) - }) - return m; + INIT_SPECIAL_VALUES(acos_special_values, { + C(P34,INF) C(P,INF) C(P,INF) C(P,-INF) C(P,-INF) C(P34,-INF) C(N,INF) + C(P12,INF) C(U,U) C(U,U) C(U,U) C(U,U) C(P12,-INF) C(N,N) + C(P12,INF) C(U,U) C(P12,0.) C(P12,-0.) C(U,U) C(P12,-INF) C(P12,N) + C(P12,INF) C(U,U) C(P12,0.) C(P12,-0.) C(U,U) C(P12,-INF) C(P12,N) + C(P12,INF) C(U,U) C(U,U) C(U,U) C(U,U) C(P12,-INF) C(N,N) + C(P14,INF) C(0.,INF) C(0.,INF) C(0.,-INF) C(0.,-INF) C(P14,-INF) C(N,INF) + C(N,INF) C(N,N) C(N,N) C(N,N) C(N,N) C(N,-INF) C(N,N) + }) + + INIT_SPECIAL_VALUES(acosh_special_values, { + C(INF,-P34) C(INF,-P) C(INF,-P) C(INF,P) C(INF,P) C(INF,P34) C(INF,N) + C(INF,-P12) C(U,U) C(U,U) C(U,U) C(U,U) C(INF,P12) C(N,N) + C(INF,-P12) C(U,U) C(0.,-P12) C(0.,P12) C(U,U) C(INF,P12) C(N,N) + C(INF,-P12) C(U,U) C(0.,-P12) C(0.,P12) C(U,U) C(INF,P12) C(N,N) + C(INF,-P12) C(U,U) C(U,U) C(U,U) C(U,U) C(INF,P12) C(N,N) + C(INF,-P14) C(INF,-0.) C(INF,-0.) C(INF,0.) C(INF,0.) C(INF,P14) C(INF,N) + C(INF,N) C(N,N) C(N,N) C(N,N) C(N,N) C(INF,N) C(N,N) + }) + + INIT_SPECIAL_VALUES(asinh_special_values, { + C(-INF,-P14) C(-INF,-0.) C(-INF,-0.) C(-INF,0.) C(-INF,0.) C(-INF,P14) C(-INF,N) + C(-INF,-P12) C(U,U) C(U,U) C(U,U) C(U,U) C(-INF,P12) C(N,N) + C(-INF,-P12) C(U,U) C(-0.,-0.) C(-0.,0.) C(U,U) C(-INF,P12) C(N,N) + C(INF,-P12) C(U,U) C(0.,-0.) C(0.,0.) C(U,U) C(INF,P12) C(N,N) + C(INF,-P12) C(U,U) C(U,U) C(U,U) C(U,U) C(INF,P12) C(N,N) + C(INF,-P14) C(INF,-0.) C(INF,-0.) C(INF,0.) C(INF,0.) C(INF,P14) C(INF,N) + C(INF,N) C(N,N) C(N,-0.) C(N,0.) C(N,N) C(INF,N) C(N,N) + }) + + INIT_SPECIAL_VALUES(atanh_special_values, { + C(-0.,-P12) C(-0.,-P12) C(-0.,-P12) C(-0.,P12) C(-0.,P12) C(-0.,P12) C(-0.,N) + C(-0.,-P12) C(U,U) C(U,U) C(U,U) C(U,U) C(-0.,P12) C(N,N) + C(-0.,-P12) C(U,U) C(-0.,-0.) C(-0.,0.) C(U,U) C(-0.,P12) C(-0.,N) + C(0.,-P12) C(U,U) C(0.,-0.) C(0.,0.) C(U,U) C(0.,P12) C(0.,N) + C(0.,-P12) C(U,U) C(U,U) C(U,U) C(U,U) C(0.,P12) C(N,N) + C(0.,-P12) C(0.,-P12) C(0.,-P12) C(0.,P12) C(0.,P12) C(0.,P12) C(0.,N) + C(0.,-P12) C(N,N) C(N,N) C(N,N) C(N,N) C(0.,P12) C(N,N) + }) + + INIT_SPECIAL_VALUES(cosh_special_values, { + C(INF,N) C(U,U) C(INF,0.) C(INF,-0.) C(U,U) C(INF,N) C(INF,N) + C(N,N) C(U,U) C(U,U) C(U,U) C(U,U) C(N,N) C(N,N) + C(N,0.) C(U,U) C(1.,0.) C(1.,-0.) C(U,U) C(N,0.) C(N,0.) + C(N,0.) C(U,U) C(1.,-0.) C(1.,0.) C(U,U) C(N,0.) C(N,0.) + C(N,N) C(U,U) C(U,U) C(U,U) C(U,U) C(N,N) C(N,N) + C(INF,N) C(U,U) C(INF,-0.) C(INF,0.) C(U,U) C(INF,N) C(INF,N) + C(N,N) C(N,N) C(N,0.) C(N,0.) C(N,N) C(N,N) C(N,N) + }) + + INIT_SPECIAL_VALUES(exp_special_values, { + C(0.,0.) C(U,U) C(0.,-0.) C(0.,0.) C(U,U) C(0.,0.) C(0.,0.) + C(N,N) C(U,U) C(U,U) C(U,U) C(U,U) C(N,N) C(N,N) + C(N,N) C(U,U) C(1.,-0.) C(1.,0.) C(U,U) C(N,N) C(N,N) + C(N,N) C(U,U) C(1.,-0.) C(1.,0.) C(U,U) C(N,N) C(N,N) + C(N,N) C(U,U) C(U,U) C(U,U) C(U,U) C(N,N) C(N,N) + C(INF,N) C(U,U) C(INF,-0.) C(INF,0.) C(U,U) C(INF,N) C(INF,N) + C(N,N) C(N,N) C(N,-0.) C(N,0.) C(N,N) C(N,N) C(N,N) + }) + + INIT_SPECIAL_VALUES(log_special_values, { + C(INF,-P34) C(INF,-P) C(INF,-P) C(INF,P) C(INF,P) C(INF,P34) C(INF,N) + C(INF,-P12) C(U,U) C(U,U) C(U,U) C(U,U) C(INF,P12) C(N,N) + C(INF,-P12) C(U,U) C(-INF,-P) C(-INF,P) C(U,U) C(INF,P12) C(N,N) + C(INF,-P12) C(U,U) C(-INF,-0.) C(-INF,0.) C(U,U) C(INF,P12) C(N,N) + C(INF,-P12) C(U,U) C(U,U) C(U,U) C(U,U) C(INF,P12) C(N,N) + C(INF,-P14) C(INF,-0.) C(INF,-0.) C(INF,0.) C(INF,0.) C(INF,P14) C(INF,N) + C(INF,N) C(N,N) C(N,N) C(N,N) C(N,N) C(INF,N) C(N,N) + }) + + INIT_SPECIAL_VALUES(sinh_special_values, { + C(INF,N) C(U,U) C(-INF,-0.) C(-INF,0.) C(U,U) C(INF,N) C(INF,N) + C(N,N) C(U,U) C(U,U) C(U,U) C(U,U) C(N,N) C(N,N) + C(0.,N) C(U,U) C(-0.,-0.) C(-0.,0.) C(U,U) C(0.,N) C(0.,N) + C(0.,N) C(U,U) C(0.,-0.) C(0.,0.) C(U,U) C(0.,N) C(0.,N) + C(N,N) C(U,U) C(U,U) C(U,U) C(U,U) C(N,N) C(N,N) + C(INF,N) C(U,U) C(INF,-0.) C(INF,0.) C(U,U) C(INF,N) C(INF,N) + C(N,N) C(N,N) C(N,-0.) C(N,0.) C(N,N) C(N,N) C(N,N) + }) + + INIT_SPECIAL_VALUES(sqrt_special_values, { + C(INF,-INF) C(0.,-INF) C(0.,-INF) C(0.,INF) C(0.,INF) C(INF,INF) C(N,INF) + C(INF,-INF) C(U,U) C(U,U) C(U,U) C(U,U) C(INF,INF) C(N,N) + C(INF,-INF) C(U,U) C(0.,-0.) C(0.,0.) C(U,U) C(INF,INF) C(N,N) + C(INF,-INF) C(U,U) C(0.,-0.) C(0.,0.) C(U,U) C(INF,INF) C(N,N) + C(INF,-INF) C(U,U) C(U,U) C(U,U) C(U,U) C(INF,INF) C(N,N) + C(INF,-INF) C(INF,-0.) C(INF,-0.) C(INF,0.) C(INF,0.) C(INF,INF) C(INF,N) + C(INF,-INF) C(N,N) C(N,N) C(N,N) C(N,N) C(INF,INF) C(N,N) + }) + + INIT_SPECIAL_VALUES(tanh_special_values, { + C(-1.,0.) C(U,U) C(-1.,-0.) C(-1.,0.) C(U,U) C(-1.,0.) C(-1.,0.) + C(N,N) C(U,U) C(U,U) C(U,U) C(U,U) C(N,N) C(N,N) + C(N,N) C(U,U) C(-0.,-0.) C(-0.,0.) C(U,U) C(N,N) C(N,N) + C(N,N) C(U,U) C(0.,-0.) C(0.,0.) C(U,U) C(N,N) C(N,N) + C(N,N) C(U,U) C(U,U) C(U,U) C(U,U) C(N,N) C(N,N) + C(1.,0.) C(U,U) C(1.,-0.) C(1.,0.) C(U,U) C(1.,0.) C(1.,0.) + C(N,N) C(N,N) C(N,-0.) C(N,0.) C(N,N) C(N,N) C(N,N) + }) + + INIT_SPECIAL_VALUES(rect_special_values, { + C(INF,N) C(U,U) C(-INF,0.) C(-INF,-0.) C(U,U) C(INF,N) C(INF,N) + C(N,N) C(U,U) C(U,U) C(U,U) C(U,U) C(N,N) C(N,N) + C(0.,0.) C(U,U) C(-0.,0.) C(-0.,-0.) C(U,U) C(0.,0.) C(0.,0.) + C(0.,0.) C(U,U) C(0.,-0.) C(0.,0.) C(U,U) C(0.,0.) C(0.,0.) + C(N,N) C(U,U) C(U,U) C(U,U) C(U,U) C(N,N) C(N,N) + C(INF,N) C(U,U) C(INF,-0.) C(INF,0.) C(U,U) C(INF,N) C(INF,N) + C(N,N) C(N,N) C(N,0.) C(N,0.) C(N,N) C(N,N) C(N,N) + }) + return m; } Modified: python/branches/py3k-jit/Modules/cryptmodule.c ============================================================================== --- python/branches/py3k-jit/Modules/cryptmodule.c (original) +++ python/branches/py3k-jit/Modules/cryptmodule.c Mon May 10 23:55:43 2010 @@ -14,17 +14,17 @@ static PyObject *crypt_crypt(PyObject *self, PyObject *args) { - char *word, *salt; + char *word, *salt; #ifndef __VMS - extern char * crypt(const char *, const char *); + extern char * crypt(const char *, const char *); #endif - if (!PyArg_ParseTuple(args, "ss:crypt", &word, &salt)) { - return NULL; - } - /* On some platforms (AtheOS) crypt returns NULL for an invalid - salt. Return None in that case. XXX Maybe raise an exception? */ - return Py_BuildValue("s", crypt(word, salt)); + if (!PyArg_ParseTuple(args, "ss:crypt", &word, &salt)) { + return NULL; + } + /* On some platforms (AtheOS) crypt returns NULL for an invalid + salt. Return None in that case. XXX Maybe raise an exception? */ + return Py_BuildValue("s", crypt(word, salt)); } @@ -38,25 +38,25 @@ static PyMethodDef crypt_methods[] = { - {"crypt", crypt_crypt, METH_VARARGS, crypt_crypt__doc__}, - {NULL, NULL} /* sentinel */ + {"crypt", crypt_crypt, METH_VARARGS, crypt_crypt__doc__}, + {NULL, NULL} /* sentinel */ }; static struct PyModuleDef cryptmodule = { - PyModuleDef_HEAD_INIT, - "crypt", - NULL, - -1, - crypt_methods, - NULL, - NULL, - NULL, - NULL + PyModuleDef_HEAD_INIT, + "crypt", + NULL, + -1, + crypt_methods, + NULL, + NULL, + NULL, + NULL }; PyMODINIT_FUNC PyInit_crypt(void) { - return PyModule_Create(&cryptmodule); + return PyModule_Create(&cryptmodule); } Modified: python/branches/py3k-jit/Modules/datetimemodule.c ============================================================================== --- python/branches/py3k-jit/Modules/datetimemodule.c (original) +++ python/branches/py3k-jit/Modules/datetimemodule.c Mon May 10 23:55:43 2010 @@ -25,7 +25,7 @@ * final result fits in a C int (this can be an issue on 64-bit boxes). */ #if SIZEOF_INT < 4 -# error "datetime.c requires that C int have at least 32 bits" +# error "datetime.c requires that C int have at least 32 bits" #endif #define MINYEAR 1 @@ -39,59 +39,59 @@ #define MAX_DELTA_DAYS 999999999 /* Rename the long macros in datetime.h to more reasonable short names. */ -#define GET_YEAR PyDateTime_GET_YEAR -#define GET_MONTH PyDateTime_GET_MONTH -#define GET_DAY PyDateTime_GET_DAY -#define DATE_GET_HOUR PyDateTime_DATE_GET_HOUR -#define DATE_GET_MINUTE PyDateTime_DATE_GET_MINUTE -#define DATE_GET_SECOND PyDateTime_DATE_GET_SECOND -#define DATE_GET_MICROSECOND PyDateTime_DATE_GET_MICROSECOND +#define GET_YEAR PyDateTime_GET_YEAR +#define GET_MONTH PyDateTime_GET_MONTH +#define GET_DAY PyDateTime_GET_DAY +#define DATE_GET_HOUR PyDateTime_DATE_GET_HOUR +#define DATE_GET_MINUTE PyDateTime_DATE_GET_MINUTE +#define DATE_GET_SECOND PyDateTime_DATE_GET_SECOND +#define DATE_GET_MICROSECOND PyDateTime_DATE_GET_MICROSECOND /* Date accessors for date and datetime. */ -#define SET_YEAR(o, v) (((o)->data[0] = ((v) & 0xff00) >> 8), \ - ((o)->data[1] = ((v) & 0x00ff))) -#define SET_MONTH(o, v) (PyDateTime_GET_MONTH(o) = (v)) -#define SET_DAY(o, v) (PyDateTime_GET_DAY(o) = (v)) +#define SET_YEAR(o, v) (((o)->data[0] = ((v) & 0xff00) >> 8), \ + ((o)->data[1] = ((v) & 0x00ff))) +#define SET_MONTH(o, v) (PyDateTime_GET_MONTH(o) = (v)) +#define SET_DAY(o, v) (PyDateTime_GET_DAY(o) = (v)) /* Date/Time accessors for datetime. */ -#define DATE_SET_HOUR(o, v) (PyDateTime_DATE_GET_HOUR(o) = (v)) -#define DATE_SET_MINUTE(o, v) (PyDateTime_DATE_GET_MINUTE(o) = (v)) -#define DATE_SET_SECOND(o, v) (PyDateTime_DATE_GET_SECOND(o) = (v)) -#define DATE_SET_MICROSECOND(o, v) \ - (((o)->data[7] = ((v) & 0xff0000) >> 16), \ - ((o)->data[8] = ((v) & 0x00ff00) >> 8), \ - ((o)->data[9] = ((v) & 0x0000ff))) +#define DATE_SET_HOUR(o, v) (PyDateTime_DATE_GET_HOUR(o) = (v)) +#define DATE_SET_MINUTE(o, v) (PyDateTime_DATE_GET_MINUTE(o) = (v)) +#define DATE_SET_SECOND(o, v) (PyDateTime_DATE_GET_SECOND(o) = (v)) +#define DATE_SET_MICROSECOND(o, v) \ + (((o)->data[7] = ((v) & 0xff0000) >> 16), \ + ((o)->data[8] = ((v) & 0x00ff00) >> 8), \ + ((o)->data[9] = ((v) & 0x0000ff))) /* Time accessors for time. */ -#define TIME_GET_HOUR PyDateTime_TIME_GET_HOUR -#define TIME_GET_MINUTE PyDateTime_TIME_GET_MINUTE -#define TIME_GET_SECOND PyDateTime_TIME_GET_SECOND -#define TIME_GET_MICROSECOND PyDateTime_TIME_GET_MICROSECOND -#define TIME_SET_HOUR(o, v) (PyDateTime_TIME_GET_HOUR(o) = (v)) -#define TIME_SET_MINUTE(o, v) (PyDateTime_TIME_GET_MINUTE(o) = (v)) -#define TIME_SET_SECOND(o, v) (PyDateTime_TIME_GET_SECOND(o) = (v)) -#define TIME_SET_MICROSECOND(o, v) \ - (((o)->data[3] = ((v) & 0xff0000) >> 16), \ - ((o)->data[4] = ((v) & 0x00ff00) >> 8), \ - ((o)->data[5] = ((v) & 0x0000ff))) +#define TIME_GET_HOUR PyDateTime_TIME_GET_HOUR +#define TIME_GET_MINUTE PyDateTime_TIME_GET_MINUTE +#define TIME_GET_SECOND PyDateTime_TIME_GET_SECOND +#define TIME_GET_MICROSECOND PyDateTime_TIME_GET_MICROSECOND +#define TIME_SET_HOUR(o, v) (PyDateTime_TIME_GET_HOUR(o) = (v)) +#define TIME_SET_MINUTE(o, v) (PyDateTime_TIME_GET_MINUTE(o) = (v)) +#define TIME_SET_SECOND(o, v) (PyDateTime_TIME_GET_SECOND(o) = (v)) +#define TIME_SET_MICROSECOND(o, v) \ + (((o)->data[3] = ((v) & 0xff0000) >> 16), \ + ((o)->data[4] = ((v) & 0x00ff00) >> 8), \ + ((o)->data[5] = ((v) & 0x0000ff))) /* Delta accessors for timedelta. */ -#define GET_TD_DAYS(o) (((PyDateTime_Delta *)(o))->days) -#define GET_TD_SECONDS(o) (((PyDateTime_Delta *)(o))->seconds) -#define GET_TD_MICROSECONDS(o) (((PyDateTime_Delta *)(o))->microseconds) +#define GET_TD_DAYS(o) (((PyDateTime_Delta *)(o))->days) +#define GET_TD_SECONDS(o) (((PyDateTime_Delta *)(o))->seconds) +#define GET_TD_MICROSECONDS(o) (((PyDateTime_Delta *)(o))->microseconds) -#define SET_TD_DAYS(o, v) ((o)->days = (v)) -#define SET_TD_SECONDS(o, v) ((o)->seconds = (v)) +#define SET_TD_DAYS(o, v) ((o)->days = (v)) +#define SET_TD_SECONDS(o, v) ((o)->seconds = (v)) #define SET_TD_MICROSECONDS(o, v) ((o)->microseconds = (v)) /* p is a pointer to a time or a datetime object; HASTZINFO(p) returns * p->hastzinfo. */ -#define HASTZINFO(p) (((_PyDateTime_BaseTZInfo *)(p))->hastzinfo) +#define HASTZINFO(p) (((_PyDateTime_BaseTZInfo *)(p))->hastzinfo) /* M is a char or int claiming to be a valid month. The macro is equivalent * to the two-sided Python test - * 1 <= M <= 12 + * 1 <= M <= 12 */ #define MONTH_IS_SANE(M) ((unsigned int)(M) - 1 < 12) @@ -111,7 +111,7 @@ * iff (k^i)&(k^j) has sign bit set. */ #define SIGNED_ADD_OVERFLOWED(RESULT, I, J) \ - ((((RESULT) ^ (I)) & ((RESULT) ^ (J))) < 0) + ((((RESULT) ^ (I)) & ((RESULT) ^ (J))) < 0) /* Compute Python divmod(x, y), returning the quotient and storing the * remainder into *r. The quotient is the floor of x/y, and that's @@ -125,17 +125,17 @@ static int divmod(int x, int y, int *r) { - int quo; + int quo; - assert(y > 0); - quo = x / y; - *r = x - quo * y; - if (*r < 0) { - --quo; - *r += y; - } - assert(0 <= *r && *r < y); - return quo; + assert(y > 0); + quo = x / y; + *r = x - quo * y; + if (*r < 0) { + --quo; + *r += y; + } + assert(0 <= *r && *r < y); + return quo; } /* Round a double to the nearest long. |x| must be small enough to fit @@ -144,11 +144,11 @@ static long round_to_long(double x) { - if (x >= 0.0) - x = floor(x + 0.5); - else - x = ceil(x - 0.5); - return (long)x; + if (x >= 0.0) + x = floor(x + 0.5); + else + x = ceil(x - 0.5); + return (long)x; } /* --------------------------------------------------------------------------- @@ -160,52 +160,52 @@ * are correct for non-leap years only. */ static int _days_in_month[] = { - 0, /* unused; this vector uses 1-based indexing */ - 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 + 0, /* unused; this vector uses 1-based indexing */ + 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 }; static int _days_before_month[] = { - 0, /* unused; this vector uses 1-based indexing */ - 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334 + 0, /* unused; this vector uses 1-based indexing */ + 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334 }; /* year -> 1 if leap year, else 0. */ static int is_leap(int year) { - /* Cast year to unsigned. The result is the same either way, but - * C can generate faster code for unsigned mod than for signed - * mod (especially for % 4 -- a good compiler should just grab - * the last 2 bits when the LHS is unsigned). - */ - const unsigned int ayear = (unsigned int)year; - return ayear % 4 == 0 && (ayear % 100 != 0 || ayear % 400 == 0); + /* Cast year to unsigned. The result is the same either way, but + * C can generate faster code for unsigned mod than for signed + * mod (especially for % 4 -- a good compiler should just grab + * the last 2 bits when the LHS is unsigned). + */ + const unsigned int ayear = (unsigned int)year; + return ayear % 4 == 0 && (ayear % 100 != 0 || ayear % 400 == 0); } /* year, month -> number of days in that month in that year */ static int days_in_month(int year, int month) { - assert(month >= 1); - assert(month <= 12); - if (month == 2 && is_leap(year)) - return 29; - else - return _days_in_month[month]; + assert(month >= 1); + assert(month <= 12); + if (month == 2 && is_leap(year)) + return 29; + else + return _days_in_month[month]; } /* year, month -> number of days in year preceeding first day of month */ static int days_before_month(int year, int month) { - int days; + int days; - assert(month >= 1); - assert(month <= 12); - days = _days_before_month[month]; - if (month > 2 && is_leap(year)) - ++days; - return days; + assert(month >= 1); + assert(month <= 12); + days = _days_before_month[month]; + if (month > 2 && is_leap(year)) + ++days; + return days; } /* year -> number of days before January 1st of year. Remember that we @@ -214,124 +214,124 @@ static int days_before_year(int year) { - int y = year - 1; - /* This is incorrect if year <= 0; we really want the floor - * here. But so long as MINYEAR is 1, the smallest year this - * can see is 0 (this can happen in some normalization endcases), - * so we'll just special-case that. - */ - assert (year >= 0); - if (y >= 0) - return y*365 + y/4 - y/100 + y/400; - else { - assert(y == -1); - return -366; - } + int y = year - 1; + /* This is incorrect if year <= 0; we really want the floor + * here. But so long as MINYEAR is 1, the smallest year this + * can see is 0 (this can happen in some normalization endcases), + * so we'll just special-case that. + */ + assert (year >= 0); + if (y >= 0) + return y*365 + y/4 - y/100 + y/400; + else { + assert(y == -1); + return -366; + } } /* Number of days in 4, 100, and 400 year cycles. That these have * the correct values is asserted in the module init function. */ -#define DI4Y 1461 /* days_before_year(5); days in 4 years */ -#define DI100Y 36524 /* days_before_year(101); days in 100 years */ -#define DI400Y 146097 /* days_before_year(401); days in 400 years */ +#define DI4Y 1461 /* days_before_year(5); days in 4 years */ +#define DI100Y 36524 /* days_before_year(101); days in 100 years */ +#define DI400Y 146097 /* days_before_year(401); days in 400 years */ /* ordinal -> year, month, day, considering 01-Jan-0001 as day 1. */ static void ord_to_ymd(int ordinal, int *year, int *month, int *day) { - int n, n1, n4, n100, n400, leapyear, preceding; + int n, n1, n4, n100, n400, leapyear, preceding; - /* ordinal is a 1-based index, starting at 1-Jan-1. The pattern of - * leap years repeats exactly every 400 years. The basic strategy is - * to find the closest 400-year boundary at or before ordinal, then - * work with the offset from that boundary to ordinal. Life is much - * clearer if we subtract 1 from ordinal first -- then the values - * of ordinal at 400-year boundaries are exactly those divisible - * by DI400Y: - * - * D M Y n n-1 - * -- --- ---- ---------- ---------------- - * 31 Dec -400 -DI400Y -DI400Y -1 - * 1 Jan -399 -DI400Y +1 -DI400Y 400-year boundary - * ... - * 30 Dec 000 -1 -2 - * 31 Dec 000 0 -1 - * 1 Jan 001 1 0 400-year boundary - * 2 Jan 001 2 1 - * 3 Jan 001 3 2 - * ... - * 31 Dec 400 DI400Y DI400Y -1 - * 1 Jan 401 DI400Y +1 DI400Y 400-year boundary - */ - assert(ordinal >= 1); - --ordinal; - n400 = ordinal / DI400Y; - n = ordinal % DI400Y; - *year = n400 * 400 + 1; - - /* Now n is the (non-negative) offset, in days, from January 1 of - * year, to the desired date. Now compute how many 100-year cycles - * precede n. - * Note that it's possible for n100 to equal 4! In that case 4 full - * 100-year cycles precede the desired day, which implies the - * desired day is December 31 at the end of a 400-year cycle. - */ - n100 = n / DI100Y; - n = n % DI100Y; - - /* Now compute how many 4-year cycles precede it. */ - n4 = n / DI4Y; - n = n % DI4Y; - - /* And now how many single years. Again n1 can be 4, and again - * meaning that the desired day is December 31 at the end of the - * 4-year cycle. - */ - n1 = n / 365; - n = n % 365; - - *year += n100 * 100 + n4 * 4 + n1; - if (n1 == 4 || n100 == 4) { - assert(n == 0); - *year -= 1; - *month = 12; - *day = 31; - return; - } - - /* Now the year is correct, and n is the offset from January 1. We - * find the month via an estimate that's either exact or one too - * large. - */ - leapyear = n1 == 3 && (n4 != 24 || n100 == 3); - assert(leapyear == is_leap(*year)); - *month = (n + 50) >> 5; - preceding = (_days_before_month[*month] + (*month > 2 && leapyear)); - if (preceding > n) { - /* estimate is too large */ - *month -= 1; - preceding -= days_in_month(*year, *month); - } - n -= preceding; - assert(0 <= n); - assert(n < days_in_month(*year, *month)); + /* ordinal is a 1-based index, starting at 1-Jan-1. The pattern of + * leap years repeats exactly every 400 years. The basic strategy is + * to find the closest 400-year boundary at or before ordinal, then + * work with the offset from that boundary to ordinal. Life is much + * clearer if we subtract 1 from ordinal first -- then the values + * of ordinal at 400-year boundaries are exactly those divisible + * by DI400Y: + * + * D M Y n n-1 + * -- --- ---- ---------- ---------------- + * 31 Dec -400 -DI400Y -DI400Y -1 + * 1 Jan -399 -DI400Y +1 -DI400Y 400-year boundary + * ... + * 30 Dec 000 -1 -2 + * 31 Dec 000 0 -1 + * 1 Jan 001 1 0 400-year boundary + * 2 Jan 001 2 1 + * 3 Jan 001 3 2 + * ... + * 31 Dec 400 DI400Y DI400Y -1 + * 1 Jan 401 DI400Y +1 DI400Y 400-year boundary + */ + assert(ordinal >= 1); + --ordinal; + n400 = ordinal / DI400Y; + n = ordinal % DI400Y; + *year = n400 * 400 + 1; + + /* Now n is the (non-negative) offset, in days, from January 1 of + * year, to the desired date. Now compute how many 100-year cycles + * precede n. + * Note that it's possible for n100 to equal 4! In that case 4 full + * 100-year cycles precede the desired day, which implies the + * desired day is December 31 at the end of a 400-year cycle. + */ + n100 = n / DI100Y; + n = n % DI100Y; + + /* Now compute how many 4-year cycles precede it. */ + n4 = n / DI4Y; + n = n % DI4Y; + + /* And now how many single years. Again n1 can be 4, and again + * meaning that the desired day is December 31 at the end of the + * 4-year cycle. + */ + n1 = n / 365; + n = n % 365; + + *year += n100 * 100 + n4 * 4 + n1; + if (n1 == 4 || n100 == 4) { + assert(n == 0); + *year -= 1; + *month = 12; + *day = 31; + return; + } + + /* Now the year is correct, and n is the offset from January 1. We + * find the month via an estimate that's either exact or one too + * large. + */ + leapyear = n1 == 3 && (n4 != 24 || n100 == 3); + assert(leapyear == is_leap(*year)); + *month = (n + 50) >> 5; + preceding = (_days_before_month[*month] + (*month > 2 && leapyear)); + if (preceding > n) { + /* estimate is too large */ + *month -= 1; + preceding -= days_in_month(*year, *month); + } + n -= preceding; + assert(0 <= n); + assert(n < days_in_month(*year, *month)); - *day = n + 1; + *day = n + 1; } /* year, month, day -> ordinal, considering 01-Jan-0001 as day 1. */ static int ymd_to_ord(int year, int month, int day) { - return days_before_year(year) + days_before_month(year, month) + day; + return days_before_year(year) + days_before_month(year, month) + day; } /* Day of week, where Monday==0, ..., Sunday==6. 1/1/1 was a Monday. */ static int weekday(int year, int month, int day) { - return (ymd_to_ord(year, month, day) + 6) % 7; + return (ymd_to_ord(year, month, day) + 6) % 7; } /* Ordinal of the Monday starting week 1 of the ISO year. Week 1 is the @@ -340,15 +340,15 @@ static int iso_week1_monday(int year) { - int first_day = ymd_to_ord(year, 1, 1); /* ord of 1/1 */ - /* 0 if 1/1 is a Monday, 1 if a Tue, etc. */ - int first_weekday = (first_day + 6) % 7; - /* ordinal of closest Monday at or before 1/1 */ - int week1_monday = first_day - first_weekday; - - if (first_weekday > 3) /* if 1/1 was Fri, Sat, Sun */ - week1_monday += 7; - return week1_monday; + int first_day = ymd_to_ord(year, 1, 1); /* ord of 1/1 */ + /* 0 if 1/1 is a Monday, 1 if a Tue, etc. */ + int first_weekday = (first_day + 6) % 7; + /* ordinal of closest Monday at or before 1/1 */ + int week1_monday = first_day - first_weekday; + + if (first_weekday > 3) /* if 1/1 was Fri, Sat, Sun */ + week1_monday += 7; + return week1_monday; } /* --------------------------------------------------------------------------- @@ -361,12 +361,12 @@ static int check_delta_day_range(int days) { - if (-MAX_DELTA_DAYS <= days && days <= MAX_DELTA_DAYS) - return 0; - PyErr_Format(PyExc_OverflowError, - "days=%d; must have magnitude <= %d", - days, MAX_DELTA_DAYS); - return -1; + if (-MAX_DELTA_DAYS <= days && days <= MAX_DELTA_DAYS) + return 0; + PyErr_Format(PyExc_OverflowError, + "days=%d; must have magnitude <= %d", + days, MAX_DELTA_DAYS); + return -1; } /* Check that date arguments are in range. Return 0 if they are. If they @@ -376,22 +376,22 @@ check_date_args(int year, int month, int day) { - if (year < MINYEAR || year > MAXYEAR) { - PyErr_SetString(PyExc_ValueError, - "year is out of range"); - return -1; - } - if (month < 1 || month > 12) { - PyErr_SetString(PyExc_ValueError, - "month must be in 1..12"); - return -1; - } - if (day < 1 || day > days_in_month(year, month)) { - PyErr_SetString(PyExc_ValueError, - "day is out of range for month"); - return -1; - } - return 0; + if (year < MINYEAR || year > MAXYEAR) { + PyErr_SetString(PyExc_ValueError, + "year is out of range"); + return -1; + } + if (month < 1 || month > 12) { + PyErr_SetString(PyExc_ValueError, + "month must be in 1..12"); + return -1; + } + if (day < 1 || day > days_in_month(year, month)) { + PyErr_SetString(PyExc_ValueError, + "day is out of range for month"); + return -1; + } + return 0; } /* Check that time arguments are in range. Return 0 if they are. If they @@ -400,27 +400,27 @@ static int check_time_args(int h, int m, int s, int us) { - if (h < 0 || h > 23) { - PyErr_SetString(PyExc_ValueError, - "hour must be in 0..23"); - return -1; - } - if (m < 0 || m > 59) { - PyErr_SetString(PyExc_ValueError, - "minute must be in 0..59"); - return -1; - } - if (s < 0 || s > 59) { - PyErr_SetString(PyExc_ValueError, - "second must be in 0..59"); - return -1; - } - if (us < 0 || us > 999999) { - PyErr_SetString(PyExc_ValueError, - "microsecond must be in 0..999999"); - return -1; - } - return 0; + if (h < 0 || h > 23) { + PyErr_SetString(PyExc_ValueError, + "hour must be in 0..23"); + return -1; + } + if (m < 0 || m > 59) { + PyErr_SetString(PyExc_ValueError, + "minute must be in 0..59"); + return -1; + } + if (s < 0 || s > 59) { + PyErr_SetString(PyExc_ValueError, + "second must be in 0..59"); + return -1; + } + if (us < 0 || us > 999999) { + PyErr_SetString(PyExc_ValueError, + "microsecond must be in 0..999999"); + return -1; + } + return 0; } /* --------------------------------------------------------------------------- @@ -436,109 +436,109 @@ static void normalize_pair(int *hi, int *lo, int factor) { - assert(factor > 0); - assert(lo != hi); - if (*lo < 0 || *lo >= factor) { - const int num_hi = divmod(*lo, factor, lo); - const int new_hi = *hi + num_hi; - assert(! SIGNED_ADD_OVERFLOWED(new_hi, *hi, num_hi)); - *hi = new_hi; - } - assert(0 <= *lo && *lo < factor); + assert(factor > 0); + assert(lo != hi); + if (*lo < 0 || *lo >= factor) { + const int num_hi = divmod(*lo, factor, lo); + const int new_hi = *hi + num_hi; + assert(! SIGNED_ADD_OVERFLOWED(new_hi, *hi, num_hi)); + *hi = new_hi; + } + assert(0 <= *lo && *lo < factor); } /* Fiddle days (d), seconds (s), and microseconds (us) so that - * 0 <= *s < 24*3600 - * 0 <= *us < 1000000 + * 0 <= *s < 24*3600 + * 0 <= *us < 1000000 * The input values must be such that the internals don't overflow. * The way this routine is used, we don't get close. */ static void normalize_d_s_us(int *d, int *s, int *us) { - if (*us < 0 || *us >= 1000000) { - normalize_pair(s, us, 1000000); - /* |s| can't be bigger than about - * |original s| + |original us|/1000000 now. - */ - - } - if (*s < 0 || *s >= 24*3600) { - normalize_pair(d, s, 24*3600); - /* |d| can't be bigger than about - * |original d| + - * (|original s| + |original us|/1000000) / (24*3600) now. - */ - } - assert(0 <= *s && *s < 24*3600); - assert(0 <= *us && *us < 1000000); + if (*us < 0 || *us >= 1000000) { + normalize_pair(s, us, 1000000); + /* |s| can't be bigger than about + * |original s| + |original us|/1000000 now. + */ + + } + if (*s < 0 || *s >= 24*3600) { + normalize_pair(d, s, 24*3600); + /* |d| can't be bigger than about + * |original d| + + * (|original s| + |original us|/1000000) / (24*3600) now. + */ + } + assert(0 <= *s && *s < 24*3600); + assert(0 <= *us && *us < 1000000); } /* Fiddle years (y), months (m), and days (d) so that - * 1 <= *m <= 12 - * 1 <= *d <= days_in_month(*y, *m) + * 1 <= *m <= 12 + * 1 <= *d <= days_in_month(*y, *m) * The input values must be such that the internals don't overflow. * The way this routine is used, we don't get close. */ static void normalize_y_m_d(int *y, int *m, int *d) { - int dim; /* # of days in month */ + int dim; /* # of days in month */ - /* This gets muddy: the proper range for day can't be determined - * without knowing the correct month and year, but if day is, e.g., - * plus or minus a million, the current month and year values make - * no sense (and may also be out of bounds themselves). - * Saying 12 months == 1 year should be non-controversial. - */ - if (*m < 1 || *m > 12) { - --*m; - normalize_pair(y, m, 12); - ++*m; - /* |y| can't be bigger than about - * |original y| + |original m|/12 now. - */ - } - assert(1 <= *m && *m <= 12); - - /* Now only day can be out of bounds (year may also be out of bounds - * for a datetime object, but we don't care about that here). - * If day is out of bounds, what to do is arguable, but at least the - * method here is principled and explainable. - */ - dim = days_in_month(*y, *m); - if (*d < 1 || *d > dim) { - /* Move day-1 days from the first of the month. First try to - * get off cheap if we're only one day out of range - * (adjustments for timezone alone can't be worse than that). - */ - if (*d == 0) { - --*m; - if (*m > 0) - *d = days_in_month(*y, *m); - else { - --*y; - *m = 12; - *d = 31; - } - } - else if (*d == dim + 1) { - /* move forward a day */ - ++*m; - *d = 1; - if (*m > 12) { - *m = 1; - ++*y; - } - } - else { - int ordinal = ymd_to_ord(*y, *m, 1) + - *d - 1; - ord_to_ymd(ordinal, y, m, d); - } - } - assert(*m > 0); - assert(*d > 0); + /* This gets muddy: the proper range for day can't be determined + * without knowing the correct month and year, but if day is, e.g., + * plus or minus a million, the current month and year values make + * no sense (and may also be out of bounds themselves). + * Saying 12 months == 1 year should be non-controversial. + */ + if (*m < 1 || *m > 12) { + --*m; + normalize_pair(y, m, 12); + ++*m; + /* |y| can't be bigger than about + * |original y| + |original m|/12 now. + */ + } + assert(1 <= *m && *m <= 12); + + /* Now only day can be out of bounds (year may also be out of bounds + * for a datetime object, but we don't care about that here). + * If day is out of bounds, what to do is arguable, but at least the + * method here is principled and explainable. + */ + dim = days_in_month(*y, *m); + if (*d < 1 || *d > dim) { + /* Move day-1 days from the first of the month. First try to + * get off cheap if we're only one day out of range + * (adjustments for timezone alone can't be worse than that). + */ + if (*d == 0) { + --*m; + if (*m > 0) + *d = days_in_month(*y, *m); + else { + --*y; + *m = 12; + *d = 31; + } + } + else if (*d == dim + 1) { + /* move forward a day */ + ++*m; + *d = 1; + if (*m > 12) { + *m = 1; + ++*y; + } + } + else { + int ordinal = ymd_to_ord(*y, *m, 1) + + *d - 1; + ord_to_ymd(ordinal, y, m, d); + } + } + assert(*m > 0); + assert(*d > 0); } /* Fiddle out-of-bounds months and days so that the result makes some kind @@ -548,17 +548,17 @@ static int normalize_date(int *year, int *month, int *day) { - int result; + int result; - normalize_y_m_d(year, month, day); - if (MINYEAR <= *year && *year <= MAXYEAR) - result = 0; - else { - PyErr_SetString(PyExc_OverflowError, - "date value out of range"); - result = -1; - } - return result; + normalize_y_m_d(year, month, day); + if (MINYEAR <= *year && *year <= MAXYEAR) + result = 0; + else { + PyErr_SetString(PyExc_OverflowError, + "date value out of range"); + result = -1; + } + return result; } /* Force all the datetime fields into range. The parameters are both @@ -569,11 +569,11 @@ int *hour, int *minute, int *second, int *microsecond) { - normalize_pair(second, microsecond, 1000000); - normalize_pair(minute, second, 60); - normalize_pair(hour, minute, 60); - normalize_pair(day, hour, 24); - return normalize_date(year, month, day); + normalize_pair(second, microsecond, 1000000); + normalize_pair(minute, second, 60); + normalize_pair(hour, minute, 60); + normalize_pair(day, hour, 24); + return normalize_date(year, month, day); } /* --------------------------------------------------------------------------- @@ -600,31 +600,31 @@ static PyObject * time_alloc(PyTypeObject *type, Py_ssize_t aware) { - PyObject *self; + PyObject *self; - self = (PyObject *) - PyObject_MALLOC(aware ? - sizeof(PyDateTime_Time) : - sizeof(_PyDateTime_BaseTime)); - if (self == NULL) - return (PyObject *)PyErr_NoMemory(); - PyObject_INIT(self, type); - return self; + self = (PyObject *) + PyObject_MALLOC(aware ? + sizeof(PyDateTime_Time) : + sizeof(_PyDateTime_BaseTime)); + if (self == NULL) + return (PyObject *)PyErr_NoMemory(); + PyObject_INIT(self, type); + return self; } static PyObject * datetime_alloc(PyTypeObject *type, Py_ssize_t aware) { - PyObject *self; + PyObject *self; - self = (PyObject *) - PyObject_MALLOC(aware ? - sizeof(PyDateTime_DateTime) : - sizeof(_PyDateTime_BaseDateTime)); - if (self == NULL) - return (PyObject *)PyErr_NoMemory(); - PyObject_INIT(self, type); - return self; + self = (PyObject *) + PyObject_MALLOC(aware ? + sizeof(PyDateTime_DateTime) : + sizeof(_PyDateTime_BaseDateTime)); + if (self == NULL) + return (PyObject *)PyErr_NoMemory(); + PyObject_INIT(self, type); + return self; } /* --------------------------------------------------------------------------- @@ -636,10 +636,10 @@ static void set_date_fields(PyDateTime_Date *self, int y, int m, int d) { - self->hashcode = -1; - SET_YEAR(self, y); - SET_MONTH(self, m); - SET_DAY(self, d); + self->hashcode = -1; + SET_YEAR(self, y); + SET_MONTH(self, m); + SET_DAY(self, d); } /* --------------------------------------------------------------------------- @@ -650,71 +650,71 @@ static PyObject * new_date_ex(int year, int month, int day, PyTypeObject *type) { - PyDateTime_Date *self; + PyDateTime_Date *self; - self = (PyDateTime_Date *) (type->tp_alloc(type, 0)); - if (self != NULL) - set_date_fields(self, year, month, day); - return (PyObject *) self; + self = (PyDateTime_Date *) (type->tp_alloc(type, 0)); + if (self != NULL) + set_date_fields(self, year, month, day); + return (PyObject *) self; } #define new_date(year, month, day) \ - new_date_ex(year, month, day, &PyDateTime_DateType) + new_date_ex(year, month, day, &PyDateTime_DateType) /* Create a datetime instance with no range checking. */ static PyObject * new_datetime_ex(int year, int month, int day, int hour, int minute, - int second, int usecond, PyObject *tzinfo, PyTypeObject *type) + int second, int usecond, PyObject *tzinfo, PyTypeObject *type) { - PyDateTime_DateTime *self; - char aware = tzinfo != Py_None; + PyDateTime_DateTime *self; + char aware = tzinfo != Py_None; - self = (PyDateTime_DateTime *) (type->tp_alloc(type, aware)); - if (self != NULL) { - self->hastzinfo = aware; - set_date_fields((PyDateTime_Date *)self, year, month, day); - DATE_SET_HOUR(self, hour); - DATE_SET_MINUTE(self, minute); - DATE_SET_SECOND(self, second); - DATE_SET_MICROSECOND(self, usecond); - if (aware) { - Py_INCREF(tzinfo); - self->tzinfo = tzinfo; - } - } - return (PyObject *)self; -} - -#define new_datetime(y, m, d, hh, mm, ss, us, tzinfo) \ - new_datetime_ex(y, m, d, hh, mm, ss, us, tzinfo, \ - &PyDateTime_DateTimeType) + self = (PyDateTime_DateTime *) (type->tp_alloc(type, aware)); + if (self != NULL) { + self->hastzinfo = aware; + set_date_fields((PyDateTime_Date *)self, year, month, day); + DATE_SET_HOUR(self, hour); + DATE_SET_MINUTE(self, minute); + DATE_SET_SECOND(self, second); + DATE_SET_MICROSECOND(self, usecond); + if (aware) { + Py_INCREF(tzinfo); + self->tzinfo = tzinfo; + } + } + return (PyObject *)self; +} + +#define new_datetime(y, m, d, hh, mm, ss, us, tzinfo) \ + new_datetime_ex(y, m, d, hh, mm, ss, us, tzinfo, \ + &PyDateTime_DateTimeType) /* Create a time instance with no range checking. */ static PyObject * new_time_ex(int hour, int minute, int second, int usecond, - PyObject *tzinfo, PyTypeObject *type) + PyObject *tzinfo, PyTypeObject *type) { - PyDateTime_Time *self; - char aware = tzinfo != Py_None; + PyDateTime_Time *self; + char aware = tzinfo != Py_None; - self = (PyDateTime_Time *) (type->tp_alloc(type, aware)); - if (self != NULL) { - self->hastzinfo = aware; - self->hashcode = -1; - TIME_SET_HOUR(self, hour); - TIME_SET_MINUTE(self, minute); - TIME_SET_SECOND(self, second); - TIME_SET_MICROSECOND(self, usecond); - if (aware) { - Py_INCREF(tzinfo); - self->tzinfo = tzinfo; - } - } - return (PyObject *)self; + self = (PyDateTime_Time *) (type->tp_alloc(type, aware)); + if (self != NULL) { + self->hastzinfo = aware; + self->hashcode = -1; + TIME_SET_HOUR(self, hour); + TIME_SET_MINUTE(self, minute); + TIME_SET_SECOND(self, second); + TIME_SET_MICROSECOND(self, usecond); + if (aware) { + Py_INCREF(tzinfo); + self->tzinfo = tzinfo; + } + } + return (PyObject *)self; } -#define new_time(hh, mm, ss, us, tzinfo) \ - new_time_ex(hh, mm, ss, us, tzinfo, &PyDateTime_TimeType) +#define new_time(hh, mm, ss, us, tzinfo) \ + new_time_ex(hh, mm, ss, us, tzinfo, &PyDateTime_TimeType) /* Create a timedelta instance. Normalize the members iff normalize is * true. Passing false is a speed optimization, if you know for sure @@ -724,30 +724,30 @@ */ static PyObject * new_delta_ex(int days, int seconds, int microseconds, int normalize, - PyTypeObject *type) + PyTypeObject *type) { - PyDateTime_Delta *self; + PyDateTime_Delta *self; - if (normalize) - normalize_d_s_us(&days, &seconds, µseconds); - assert(0 <= seconds && seconds < 24*3600); - assert(0 <= microseconds && microseconds < 1000000); - - if (check_delta_day_range(days) < 0) - return NULL; - - self = (PyDateTime_Delta *) (type->tp_alloc(type, 0)); - if (self != NULL) { - self->hashcode = -1; - SET_TD_DAYS(self, days); - SET_TD_SECONDS(self, seconds); - SET_TD_MICROSECONDS(self, microseconds); - } - return (PyObject *) self; + if (normalize) + normalize_d_s_us(&days, &seconds, µseconds); + assert(0 <= seconds && seconds < 24*3600); + assert(0 <= microseconds && microseconds < 1000000); + + if (check_delta_day_range(days) < 0) + return NULL; + + self = (PyDateTime_Delta *) (type->tp_alloc(type, 0)); + if (self != NULL) { + self->hashcode = -1; + SET_TD_DAYS(self, days); + SET_TD_SECONDS(self, seconds); + SET_TD_MICROSECONDS(self, microseconds); + } + return (PyObject *) self; } -#define new_delta(d, s, us, normalize) \ - new_delta_ex(d, s, us, normalize, &PyDateTime_DeltaType) +#define new_delta(d, s, us, normalize) \ + new_delta_ex(d, s, us, normalize, &PyDateTime_DeltaType) /* --------------------------------------------------------------------------- * tzinfo helpers. @@ -759,13 +759,13 @@ static int check_tzinfo_subclass(PyObject *p) { - if (p == Py_None || PyTZInfo_Check(p)) - return 0; - PyErr_Format(PyExc_TypeError, - "tzinfo argument must be None or of a tzinfo subclass, " - "not type '%s'", - Py_TYPE(p)->tp_name); - return -1; + if (p == Py_None || PyTZInfo_Check(p)) + return 0; + PyErr_Format(PyExc_TypeError, + "tzinfo argument must be None or of a tzinfo subclass, " + "not type '%s'", + Py_TYPE(p)->tp_name); + return -1; } /* Return tzinfo.methname(tzinfoarg), without any checking of results. @@ -774,17 +774,17 @@ static PyObject * call_tzinfo_method(PyObject *tzinfo, char *methname, PyObject *tzinfoarg) { - PyObject *result; + PyObject *result; - assert(tzinfo && methname && tzinfoarg); - assert(check_tzinfo_subclass(tzinfo) >= 0); - if (tzinfo == Py_None) { - result = Py_None; - Py_INCREF(result); - } - else - result = PyObject_CallMethod(tzinfo, methname, "O", tzinfoarg); - return result; + assert(tzinfo && methname && tzinfoarg); + assert(check_tzinfo_subclass(tzinfo) >= 0); + if (tzinfo == Py_None) { + result = Py_None; + Py_INCREF(result); + } + else + result = PyObject_CallMethod(tzinfo, methname, "O", tzinfoarg); + return result; } /* If self has a tzinfo member, return a BORROWED reference to it. Else @@ -794,14 +794,14 @@ static PyObject * get_tzinfo_member(PyObject *self) { - PyObject *tzinfo = NULL; + PyObject *tzinfo = NULL; - if (PyDateTime_Check(self) && HASTZINFO(self)) - tzinfo = ((PyDateTime_DateTime *)self)->tzinfo; - else if (PyTime_Check(self) && HASTZINFO(self)) - tzinfo = ((PyDateTime_Time *)self)->tzinfo; + if (PyDateTime_Check(self) && HASTZINFO(self)) + tzinfo = ((PyDateTime_DateTime *)self)->tzinfo; + else if (PyTime_Check(self) && HASTZINFO(self)) + tzinfo = ((PyDateTime_Time *)self)->tzinfo; - return tzinfo; + return tzinfo; } /* Call getattr(tzinfo, name)(tzinfoarg), and extract an int from the @@ -814,59 +814,59 @@ */ static int call_utc_tzinfo_method(PyObject *tzinfo, char *name, PyObject *tzinfoarg, - int *none) + int *none) { - PyObject *u; - int result = -1; + PyObject *u; + int result = -1; - assert(tzinfo != NULL); - assert(PyTZInfo_Check(tzinfo)); - assert(tzinfoarg != NULL); - - *none = 0; - u = call_tzinfo_method(tzinfo, name, tzinfoarg); - if (u == NULL) - return -1; - - else if (u == Py_None) { - result = 0; - *none = 1; - } - else if (PyDelta_Check(u)) { - const int days = GET_TD_DAYS(u); - if (days < -1 || days > 0) - result = 24*60; /* trigger ValueError below */ - else { - /* next line can't overflow because we know days - * is -1 or 0 now - */ - int ss = days * 24 * 3600 + GET_TD_SECONDS(u); - result = divmod(ss, 60, &ss); - if (ss || GET_TD_MICROSECONDS(u)) { - PyErr_Format(PyExc_ValueError, - "tzinfo.%s() must return a " - "whole number of minutes", - name); - result = -1; - } - } - } - else { - PyErr_Format(PyExc_TypeError, - "tzinfo.%s() must return None or " - "timedelta, not '%s'", - name, Py_TYPE(u)->tp_name); - } - - Py_DECREF(u); - if (result < -1439 || result > 1439) { - PyErr_Format(PyExc_ValueError, - "tzinfo.%s() returned %d; must be in " - "-1439 .. 1439", - name, result); - result = -1; - } - return result; + assert(tzinfo != NULL); + assert(PyTZInfo_Check(tzinfo)); + assert(tzinfoarg != NULL); + + *none = 0; + u = call_tzinfo_method(tzinfo, name, tzinfoarg); + if (u == NULL) + return -1; + + else if (u == Py_None) { + result = 0; + *none = 1; + } + else if (PyDelta_Check(u)) { + const int days = GET_TD_DAYS(u); + if (days < -1 || days > 0) + result = 24*60; /* trigger ValueError below */ + else { + /* next line can't overflow because we know days + * is -1 or 0 now + */ + int ss = days * 24 * 3600 + GET_TD_SECONDS(u); + result = divmod(ss, 60, &ss); + if (ss || GET_TD_MICROSECONDS(u)) { + PyErr_Format(PyExc_ValueError, + "tzinfo.%s() must return a " + "whole number of minutes", + name); + result = -1; + } + } + } + else { + PyErr_Format(PyExc_TypeError, + "tzinfo.%s() must return None or " + "timedelta, not '%s'", + name, Py_TYPE(u)->tp_name); + } + + Py_DECREF(u); + if (result < -1439 || result > 1439) { + PyErr_Format(PyExc_ValueError, + "tzinfo.%s() returned %d; must be in " + "-1439 .. 1439", + name, result); + result = -1; + } + return result; } /* Call tzinfo.utcoffset(tzinfoarg), and extract an integer from the @@ -880,34 +880,34 @@ static int call_utcoffset(PyObject *tzinfo, PyObject *tzinfoarg, int *none) { - return call_utc_tzinfo_method(tzinfo, "utcoffset", tzinfoarg, none); + return call_utc_tzinfo_method(tzinfo, "utcoffset", tzinfoarg, none); } /* Call tzinfo.name(tzinfoarg), and return the offset as a timedelta or None. */ static PyObject * offset_as_timedelta(PyObject *tzinfo, char *name, PyObject *tzinfoarg) { - PyObject *result; + PyObject *result; - assert(tzinfo && name && tzinfoarg); - if (tzinfo == Py_None) { - result = Py_None; - Py_INCREF(result); - } - else { - int none; - int offset = call_utc_tzinfo_method(tzinfo, name, tzinfoarg, - &none); - if (offset < 0 && PyErr_Occurred()) - return NULL; - if (none) { - result = Py_None; - Py_INCREF(result); - } - else - result = new_delta(0, offset * 60, 0, 1); - } - return result; + assert(tzinfo && name && tzinfoarg); + if (tzinfo == Py_None) { + result = Py_None; + Py_INCREF(result); + } + else { + int none; + int offset = call_utc_tzinfo_method(tzinfo, name, tzinfoarg, + &none); + if (offset < 0 && PyErr_Occurred()) + return NULL; + if (none) { + result = Py_None; + Py_INCREF(result); + } + else + result = new_delta(0, offset * 60, 0, 1); + } + return result; } /* Call tzinfo.dst(tzinfoarg), and extract an integer from the @@ -921,7 +921,7 @@ static int call_dst(PyObject *tzinfo, PyObject *tzinfoarg, int *none) { - return call_utc_tzinfo_method(tzinfo, "dst", tzinfoarg, none); + return call_utc_tzinfo_method(tzinfo, "dst", tzinfoarg, none); } /* Call tzinfo.tzname(tzinfoarg), and return the result. tzinfo must be @@ -933,55 +933,55 @@ static PyObject * call_tzname(PyObject *tzinfo, PyObject *tzinfoarg) { - PyObject *result; + PyObject *result; - assert(tzinfo != NULL); - assert(check_tzinfo_subclass(tzinfo) >= 0); - assert(tzinfoarg != NULL); - - if (tzinfo == Py_None) { - result = Py_None; - Py_INCREF(result); - } - else - result = PyObject_CallMethod(tzinfo, "tzname", "O", tzinfoarg); - - if (result != NULL && result != Py_None) { - if (!PyUnicode_Check(result)) { - PyErr_Format(PyExc_TypeError, "tzinfo.tzname() must " - "return None or a string, not '%s'", - Py_TYPE(result)->tp_name); - Py_DECREF(result); - result = NULL; - } - else if (!PyUnicode_Check(result)) { - PyObject *temp = PyUnicode_FromObject(result); - Py_DECREF(result); - result = temp; - } - } - return result; + assert(tzinfo != NULL); + assert(check_tzinfo_subclass(tzinfo) >= 0); + assert(tzinfoarg != NULL); + + if (tzinfo == Py_None) { + result = Py_None; + Py_INCREF(result); + } + else + result = PyObject_CallMethod(tzinfo, "tzname", "O", tzinfoarg); + + if (result != NULL && result != Py_None) { + if (!PyUnicode_Check(result)) { + PyErr_Format(PyExc_TypeError, "tzinfo.tzname() must " + "return None or a string, not '%s'", + Py_TYPE(result)->tp_name); + Py_DECREF(result); + result = NULL; + } + else if (!PyUnicode_Check(result)) { + PyObject *temp = PyUnicode_FromObject(result); + Py_DECREF(result); + result = temp; + } + } + return result; } typedef enum { - /* an exception has been set; the caller should pass it on */ - OFFSET_ERROR, + /* an exception has been set; the caller should pass it on */ + OFFSET_ERROR, - /* type isn't date, datetime, or time subclass */ - OFFSET_UNKNOWN, + /* type isn't date, datetime, or time subclass */ + OFFSET_UNKNOWN, - /* date, - * datetime with !hastzinfo - * datetime with None tzinfo, - * datetime where utcoffset() returns None - * time with !hastzinfo - * time with None tzinfo, - * time where utcoffset() returns None - */ - OFFSET_NAIVE, + /* date, + * datetime with !hastzinfo + * datetime with None tzinfo, + * datetime where utcoffset() returns None + * time with !hastzinfo + * time with None tzinfo, + * time where utcoffset() returns None + */ + OFFSET_NAIVE, - /* time or datetime where utcoffset() doesn't return None */ - OFFSET_AWARE + /* time or datetime where utcoffset() doesn't return None */ + OFFSET_AWARE } naivety; /* Classify an object as to whether it's naive or offset-aware. See @@ -993,23 +993,23 @@ static naivety classify_utcoffset(PyObject *op, PyObject *tzinfoarg, int *offset) { - int none; - PyObject *tzinfo; + int none; + PyObject *tzinfo; - assert(tzinfoarg != NULL); - *offset = 0; - tzinfo = get_tzinfo_member(op); /* NULL means no tzinfo, not error */ - if (tzinfo == Py_None) - return OFFSET_NAIVE; - if (tzinfo == NULL) { - /* note that a datetime passes the PyDate_Check test */ - return (PyTime_Check(op) || PyDate_Check(op)) ? - OFFSET_NAIVE : OFFSET_UNKNOWN; - } - *offset = call_utcoffset(tzinfo, tzinfoarg, &none); - if (*offset == -1 && PyErr_Occurred()) - return OFFSET_ERROR; - return none ? OFFSET_NAIVE : OFFSET_AWARE; + assert(tzinfoarg != NULL); + *offset = 0; + tzinfo = get_tzinfo_member(op); /* NULL means no tzinfo, not error */ + if (tzinfo == Py_None) + return OFFSET_NAIVE; + if (tzinfo == NULL) { + /* note that a datetime passes the PyDate_Check test */ + return (PyTime_Check(op) || PyDate_Check(op)) ? + OFFSET_NAIVE : OFFSET_UNKNOWN; + } + *offset = call_utcoffset(tzinfo, tzinfoarg, &none); + if (*offset == -1 && PyErr_Occurred()) + return OFFSET_ERROR; + return none ? OFFSET_NAIVE : OFFSET_AWARE; } /* Classify two objects as to whether they're naive or offset-aware. @@ -1023,23 +1023,23 @@ */ static int classify_two_utcoffsets(PyObject *o1, int *offset1, naivety *n1, - PyObject *tzinfoarg1, - PyObject *o2, int *offset2, naivety *n2, - PyObject *tzinfoarg2) -{ - if (get_tzinfo_member(o1) == get_tzinfo_member(o2)) { - *offset1 = *offset2 = 0; - *n1 = *n2 = OFFSET_NAIVE; - } - else { - *n1 = classify_utcoffset(o1, tzinfoarg1, offset1); - if (*n1 == OFFSET_ERROR) - return -1; - *n2 = classify_utcoffset(o2, tzinfoarg2, offset2); - if (*n2 == OFFSET_ERROR) - return -1; - } - return 0; + PyObject *tzinfoarg1, + PyObject *o2, int *offset2, naivety *n2, + PyObject *tzinfoarg2) +{ + if (get_tzinfo_member(o1) == get_tzinfo_member(o2)) { + *offset1 = *offset2 = 0; + *n1 = *n2 = OFFSET_NAIVE; + } + else { + *n1 = classify_utcoffset(o1, tzinfoarg1, offset1); + if (*n1 == OFFSET_ERROR) + return -1; + *n2 = classify_utcoffset(o2, tzinfoarg2, offset2); + if (*n2 == OFFSET_ERROR) + return -1; + } + return 0; } /* repr is like "someclass(arg1, arg2)". If tzinfo isn't None, @@ -1050,22 +1050,22 @@ static PyObject * append_keyword_tzinfo(PyObject *repr, PyObject *tzinfo) { - PyObject *temp; + PyObject *temp; - assert(PyUnicode_Check(repr)); - assert(tzinfo); - if (tzinfo == Py_None) - return repr; - /* Get rid of the trailing ')'. */ - assert(PyUnicode_AS_UNICODE(repr)[PyUnicode_GET_SIZE(repr)-1] == ')'); - temp = PyUnicode_FromUnicode(PyUnicode_AS_UNICODE(repr), - PyUnicode_GET_SIZE(repr) - 1); - Py_DECREF(repr); - if (temp == NULL) - return NULL; - repr = PyUnicode_FromFormat("%U, tzinfo=%R)", temp, tzinfo); - Py_DECREF(temp); - return repr; + assert(PyUnicode_Check(repr)); + assert(tzinfo); + if (tzinfo == Py_None) + return repr; + /* Get rid of the trailing ')'. */ + assert(PyUnicode_AS_UNICODE(repr)[PyUnicode_GET_SIZE(repr)-1] == ')'); + temp = PyUnicode_FromUnicode(PyUnicode_AS_UNICODE(repr), + PyUnicode_GET_SIZE(repr) - 1); + Py_DECREF(repr); + if (temp == NULL) + return NULL; + repr = PyUnicode_FromFormat("%U, tzinfo=%R)", temp, tzinfo); + Py_DECREF(temp); + return repr; } /* --------------------------------------------------------------------------- @@ -1075,20 +1075,20 @@ static PyObject * format_ctime(PyDateTime_Date *date, int hours, int minutes, int seconds) { - static const char *DayNames[] = { - "Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun" - }; - static const char *MonthNames[] = { - "Jan", "Feb", "Mar", "Apr", "May", "Jun", - "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" - }; - - int wday = weekday(GET_YEAR(date), GET_MONTH(date), GET_DAY(date)); - - return PyUnicode_FromFormat("%s %s %2d %02d:%02d:%02d %04d", - DayNames[wday], MonthNames[GET_MONTH(date)-1], - GET_DAY(date), hours, minutes, seconds, - GET_YEAR(date)); + static const char *DayNames[] = { + "Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun" + }; + static const char *MonthNames[] = { + "Jan", "Feb", "Mar", "Apr", "May", "Jun", + "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" + }; + + int wday = weekday(GET_YEAR(date), GET_MONTH(date), GET_DAY(date)); + + return PyUnicode_FromFormat("%s %s %2d %02d:%02d:%02d %04d", + DayNames[wday], MonthNames[GET_MONTH(date)-1], + GET_DAY(date), hours, minutes, seconds, + GET_YEAR(date)); } /* Add an hours & minutes UTC offset string to buf. buf has no more than @@ -1103,87 +1103,87 @@ */ static int format_utcoffset(char *buf, size_t buflen, const char *sep, - PyObject *tzinfo, PyObject *tzinfoarg) + PyObject *tzinfo, PyObject *tzinfoarg) { - int offset; - int hours; - int minutes; - char sign; - int none; - - assert(buflen >= 1); - - offset = call_utcoffset(tzinfo, tzinfoarg, &none); - if (offset == -1 && PyErr_Occurred()) - return -1; - if (none) { - *buf = '\0'; - return 0; - } - sign = '+'; - if (offset < 0) { - sign = '-'; - offset = - offset; - } - hours = divmod(offset, 60, &minutes); - PyOS_snprintf(buf, buflen, "%c%02d%s%02d", sign, hours, sep, minutes); - return 0; + int offset; + int hours; + int minutes; + char sign; + int none; + + assert(buflen >= 1); + + offset = call_utcoffset(tzinfo, tzinfoarg, &none); + if (offset == -1 && PyErr_Occurred()) + return -1; + if (none) { + *buf = '\0'; + return 0; + } + sign = '+'; + if (offset < 0) { + sign = '-'; + offset = - offset; + } + hours = divmod(offset, 60, &minutes); + PyOS_snprintf(buf, buflen, "%c%02d%s%02d", sign, hours, sep, minutes); + return 0; } static PyObject * make_Zreplacement(PyObject *object, PyObject *tzinfoarg) { - PyObject *temp; - PyObject *tzinfo = get_tzinfo_member(object); - PyObject *Zreplacement = PyUnicode_FromStringAndSize(NULL, 0); - if (Zreplacement == NULL) - return NULL; - if (tzinfo == Py_None || tzinfo == NULL) - return Zreplacement; - - assert(tzinfoarg != NULL); - temp = call_tzname(tzinfo, tzinfoarg); - if (temp == NULL) - goto Error; - if (temp == Py_None) { - Py_DECREF(temp); - return Zreplacement; - } - - assert(PyUnicode_Check(temp)); - /* Since the tzname is getting stuffed into the - * format, we have to double any % signs so that - * strftime doesn't treat them as format codes. - */ - Py_DECREF(Zreplacement); - Zreplacement = PyObject_CallMethod(temp, "replace", "ss", "%", "%%"); - Py_DECREF(temp); - if (Zreplacement == NULL) - return NULL; - if (!PyUnicode_Check(Zreplacement)) { - PyErr_SetString(PyExc_TypeError, - "tzname.replace() did not return a string"); - goto Error; - } - return Zreplacement; + PyObject *temp; + PyObject *tzinfo = get_tzinfo_member(object); + PyObject *Zreplacement = PyUnicode_FromStringAndSize(NULL, 0); + if (Zreplacement == NULL) + return NULL; + if (tzinfo == Py_None || tzinfo == NULL) + return Zreplacement; + + assert(tzinfoarg != NULL); + temp = call_tzname(tzinfo, tzinfoarg); + if (temp == NULL) + goto Error; + if (temp == Py_None) { + Py_DECREF(temp); + return Zreplacement; + } + + assert(PyUnicode_Check(temp)); + /* Since the tzname is getting stuffed into the + * format, we have to double any % signs so that + * strftime doesn't treat them as format codes. + */ + Py_DECREF(Zreplacement); + Zreplacement = PyObject_CallMethod(temp, "replace", "ss", "%", "%%"); + Py_DECREF(temp); + if (Zreplacement == NULL) + return NULL; + if (!PyUnicode_Check(Zreplacement)) { + PyErr_SetString(PyExc_TypeError, + "tzname.replace() did not return a string"); + goto Error; + } + return Zreplacement; Error: - Py_DECREF(Zreplacement); - return NULL; + Py_DECREF(Zreplacement); + return NULL; } static PyObject * make_freplacement(PyObject *object) { - char freplacement[64]; - if (PyTime_Check(object)) - sprintf(freplacement, "%06d", TIME_GET_MICROSECOND(object)); - else if (PyDateTime_Check(object)) - sprintf(freplacement, "%06d", DATE_GET_MICROSECOND(object)); - else - sprintf(freplacement, "%06d", 0); + char freplacement[64]; + if (PyTime_Check(object)) + sprintf(freplacement, "%06d", TIME_GET_MICROSECOND(object)); + else if (PyDateTime_Check(object)) + sprintf(freplacement, "%06d", DATE_GET_MICROSECOND(object)); + else + sprintf(freplacement, "%06d", 0); - return PyBytes_FromStringAndSize(freplacement, strlen(freplacement)); + return PyBytes_FromStringAndSize(freplacement, strlen(freplacement)); } /* I sure don't want to reproduce the strftime code from the time module, @@ -1195,190 +1195,190 @@ */ static PyObject * wrap_strftime(PyObject *object, PyObject *format, PyObject *timetuple, - PyObject *tzinfoarg) + PyObject *tzinfoarg) { - PyObject *result = NULL; /* guilty until proved innocent */ + PyObject *result = NULL; /* guilty until proved innocent */ - PyObject *zreplacement = NULL; /* py string, replacement for %z */ - PyObject *Zreplacement = NULL; /* py string, replacement for %Z */ - PyObject *freplacement = NULL; /* py string, replacement for %f */ - - const char *pin; /* pointer to next char in input format */ - Py_ssize_t flen; /* length of input format */ - char ch; /* next char in input format */ - - PyObject *newfmt = NULL; /* py string, the output format */ - char *pnew; /* pointer to available byte in output format */ - size_t totalnew; /* number bytes total in output format buffer, - exclusive of trailing \0 */ - size_t usednew; /* number bytes used so far in output format buffer */ - - const char *ptoappend; /* ptr to string to append to output buffer */ - Py_ssize_t ntoappend; /* # of bytes to append to output buffer */ - - assert(object && format && timetuple); - assert(PyUnicode_Check(format)); - /* Convert the input format to a C string and size */ - pin = _PyUnicode_AsStringAndSize(format, &flen); - if (!pin) - return NULL; - - /* Give up if the year is before 1900. - * Python strftime() plays games with the year, and different - * games depending on whether envar PYTHON2K is set. This makes - * years before 1900 a nightmare, even if the platform strftime - * supports them (and not all do). - * We could get a lot farther here by avoiding Python's strftime - * wrapper and calling the C strftime() directly, but that isn't - * an option in the Python implementation of this module. - */ - { - long year; - PyObject *pyyear = PySequence_GetItem(timetuple, 0); - if (pyyear == NULL) return NULL; - assert(PyLong_Check(pyyear)); - year = PyLong_AsLong(pyyear); - Py_DECREF(pyyear); - if (year < 1900) { - PyErr_Format(PyExc_ValueError, "year=%ld is before " - "1900; the datetime strftime() " - "methods require year >= 1900", - year); - return NULL; - } - } - - /* Scan the input format, looking for %z/%Z/%f escapes, building - * a new format. Since computing the replacements for those codes - * is expensive, don't unless they're actually used. - */ - if (flen > INT_MAX - 1) { - PyErr_NoMemory(); - goto Done; - } - - totalnew = flen + 1; /* realistic if no %z/%Z */ - newfmt = PyBytes_FromStringAndSize(NULL, totalnew); - if (newfmt == NULL) goto Done; - pnew = PyBytes_AsString(newfmt); - usednew = 0; - - while ((ch = *pin++) != '\0') { - if (ch != '%') { - ptoappend = pin - 1; - ntoappend = 1; - } - else if ((ch = *pin++) == '\0') { - /* There's a lone trailing %; doesn't make sense. */ - PyErr_SetString(PyExc_ValueError, "strftime format " - "ends with raw %"); - goto Done; - } - /* A % has been seen and ch is the character after it. */ - else if (ch == 'z') { - if (zreplacement == NULL) { - /* format utcoffset */ - char buf[100]; - PyObject *tzinfo = get_tzinfo_member(object); - zreplacement = PyBytes_FromStringAndSize("", 0); - if (zreplacement == NULL) goto Done; - if (tzinfo != Py_None && tzinfo != NULL) { - assert(tzinfoarg != NULL); - if (format_utcoffset(buf, - sizeof(buf), - "", - tzinfo, - tzinfoarg) < 0) - goto Done; - Py_DECREF(zreplacement); - zreplacement = - PyBytes_FromStringAndSize(buf, - strlen(buf)); - if (zreplacement == NULL) - goto Done; - } - } - assert(zreplacement != NULL); - ptoappend = PyBytes_AS_STRING(zreplacement); - ntoappend = PyBytes_GET_SIZE(zreplacement); - } - else if (ch == 'Z') { - /* format tzname */ - if (Zreplacement == NULL) { - Zreplacement = make_Zreplacement(object, - tzinfoarg); - if (Zreplacement == NULL) - goto Done; - } - assert(Zreplacement != NULL); - assert(PyUnicode_Check(Zreplacement)); - ptoappend = _PyUnicode_AsStringAndSize(Zreplacement, - &ntoappend); - ntoappend = Py_SIZE(Zreplacement); - } - else if (ch == 'f') { - /* format microseconds */ - if (freplacement == NULL) { - freplacement = make_freplacement(object); - if (freplacement == NULL) - goto Done; - } - assert(freplacement != NULL); - assert(PyBytes_Check(freplacement)); - ptoappend = PyBytes_AS_STRING(freplacement); - ntoappend = PyBytes_GET_SIZE(freplacement); - } - else { - /* percent followed by neither z nor Z */ - ptoappend = pin - 2; - ntoappend = 2; - } - - /* Append the ntoappend chars starting at ptoappend to - * the new format. - */ - if (ntoappend == 0) - continue; - assert(ptoappend != NULL); - assert(ntoappend > 0); - while (usednew + ntoappend > totalnew) { - size_t bigger = totalnew << 1; - if ((bigger >> 1) != totalnew) { /* overflow */ - PyErr_NoMemory(); - goto Done; - } - if (_PyBytes_Resize(&newfmt, bigger) < 0) - goto Done; - totalnew = bigger; - pnew = PyBytes_AsString(newfmt) + usednew; - } - memcpy(pnew, ptoappend, ntoappend); - pnew += ntoappend; - usednew += ntoappend; - assert(usednew <= totalnew); - } /* end while() */ - - if (_PyBytes_Resize(&newfmt, usednew) < 0) - goto Done; - { - PyObject *format; - PyObject *time = PyImport_ImportModuleNoBlock("time"); - if (time == NULL) - goto Done; - format = PyUnicode_FromString(PyBytes_AS_STRING(newfmt)); - if (format != NULL) { - result = PyObject_CallMethod(time, "strftime", "OO", - format, timetuple); - Py_DECREF(format); - } - Py_DECREF(time); - } + PyObject *zreplacement = NULL; /* py string, replacement for %z */ + PyObject *Zreplacement = NULL; /* py string, replacement for %Z */ + PyObject *freplacement = NULL; /* py string, replacement for %f */ + + const char *pin; /* pointer to next char in input format */ + Py_ssize_t flen; /* length of input format */ + char ch; /* next char in input format */ + + PyObject *newfmt = NULL; /* py string, the output format */ + char *pnew; /* pointer to available byte in output format */ + size_t totalnew; /* number bytes total in output format buffer, + exclusive of trailing \0 */ + size_t usednew; /* number bytes used so far in output format buffer */ + + const char *ptoappend; /* ptr to string to append to output buffer */ + Py_ssize_t ntoappend; /* # of bytes to append to output buffer */ + + assert(object && format && timetuple); + assert(PyUnicode_Check(format)); + /* Convert the input format to a C string and size */ + pin = _PyUnicode_AsStringAndSize(format, &flen); + if (!pin) + return NULL; + + /* Give up if the year is before 1900. + * Python strftime() plays games with the year, and different + * games depending on whether envar PYTHON2K is set. This makes + * years before 1900 a nightmare, even if the platform strftime + * supports them (and not all do). + * We could get a lot farther here by avoiding Python's strftime + * wrapper and calling the C strftime() directly, but that isn't + * an option in the Python implementation of this module. + */ + { + long year; + PyObject *pyyear = PySequence_GetItem(timetuple, 0); + if (pyyear == NULL) return NULL; + assert(PyLong_Check(pyyear)); + year = PyLong_AsLong(pyyear); + Py_DECREF(pyyear); + if (year < 1900) { + PyErr_Format(PyExc_ValueError, "year=%ld is before " + "1900; the datetime strftime() " + "methods require year >= 1900", + year); + return NULL; + } + } + + /* Scan the input format, looking for %z/%Z/%f escapes, building + * a new format. Since computing the replacements for those codes + * is expensive, don't unless they're actually used. + */ + if (flen > INT_MAX - 1) { + PyErr_NoMemory(); + goto Done; + } + + totalnew = flen + 1; /* realistic if no %z/%Z */ + newfmt = PyBytes_FromStringAndSize(NULL, totalnew); + if (newfmt == NULL) goto Done; + pnew = PyBytes_AsString(newfmt); + usednew = 0; + + while ((ch = *pin++) != '\0') { + if (ch != '%') { + ptoappend = pin - 1; + ntoappend = 1; + } + else if ((ch = *pin++) == '\0') { + /* There's a lone trailing %; doesn't make sense. */ + PyErr_SetString(PyExc_ValueError, "strftime format " + "ends with raw %"); + goto Done; + } + /* A % has been seen and ch is the character after it. */ + else if (ch == 'z') { + if (zreplacement == NULL) { + /* format utcoffset */ + char buf[100]; + PyObject *tzinfo = get_tzinfo_member(object); + zreplacement = PyBytes_FromStringAndSize("", 0); + if (zreplacement == NULL) goto Done; + if (tzinfo != Py_None && tzinfo != NULL) { + assert(tzinfoarg != NULL); + if (format_utcoffset(buf, + sizeof(buf), + "", + tzinfo, + tzinfoarg) < 0) + goto Done; + Py_DECREF(zreplacement); + zreplacement = + PyBytes_FromStringAndSize(buf, + strlen(buf)); + if (zreplacement == NULL) + goto Done; + } + } + assert(zreplacement != NULL); + ptoappend = PyBytes_AS_STRING(zreplacement); + ntoappend = PyBytes_GET_SIZE(zreplacement); + } + else if (ch == 'Z') { + /* format tzname */ + if (Zreplacement == NULL) { + Zreplacement = make_Zreplacement(object, + tzinfoarg); + if (Zreplacement == NULL) + goto Done; + } + assert(Zreplacement != NULL); + assert(PyUnicode_Check(Zreplacement)); + ptoappend = _PyUnicode_AsStringAndSize(Zreplacement, + &ntoappend); + ntoappend = Py_SIZE(Zreplacement); + } + else if (ch == 'f') { + /* format microseconds */ + if (freplacement == NULL) { + freplacement = make_freplacement(object); + if (freplacement == NULL) + goto Done; + } + assert(freplacement != NULL); + assert(PyBytes_Check(freplacement)); + ptoappend = PyBytes_AS_STRING(freplacement); + ntoappend = PyBytes_GET_SIZE(freplacement); + } + else { + /* percent followed by neither z nor Z */ + ptoappend = pin - 2; + ntoappend = 2; + } + + /* Append the ntoappend chars starting at ptoappend to + * the new format. + */ + if (ntoappend == 0) + continue; + assert(ptoappend != NULL); + assert(ntoappend > 0); + while (usednew + ntoappend > totalnew) { + size_t bigger = totalnew << 1; + if ((bigger >> 1) != totalnew) { /* overflow */ + PyErr_NoMemory(); + goto Done; + } + if (_PyBytes_Resize(&newfmt, bigger) < 0) + goto Done; + totalnew = bigger; + pnew = PyBytes_AsString(newfmt) + usednew; + } + memcpy(pnew, ptoappend, ntoappend); + pnew += ntoappend; + usednew += ntoappend; + assert(usednew <= totalnew); + } /* end while() */ + + if (_PyBytes_Resize(&newfmt, usednew) < 0) + goto Done; + { + PyObject *format; + PyObject *time = PyImport_ImportModuleNoBlock("time"); + if (time == NULL) + goto Done; + format = PyUnicode_FromString(PyBytes_AS_STRING(newfmt)); + if (format != NULL) { + result = PyObject_CallMethod(time, "strftime", "OO", + format, timetuple); + Py_DECREF(format); + } + Py_DECREF(time); + } Done: - Py_XDECREF(freplacement); - Py_XDECREF(zreplacement); - Py_XDECREF(Zreplacement); - Py_XDECREF(newfmt); - return result; + Py_XDECREF(freplacement); + Py_XDECREF(zreplacement); + Py_XDECREF(Zreplacement); + Py_XDECREF(newfmt); + return result; } /* --------------------------------------------------------------------------- @@ -1390,14 +1390,14 @@ static PyObject * time_time(void) { - PyObject *result = NULL; - PyObject *time = PyImport_ImportModuleNoBlock("time"); + PyObject *result = NULL; + PyObject *time = PyImport_ImportModuleNoBlock("time"); - if (time != NULL) { - result = PyObject_CallMethod(time, "time", "()"); - Py_DECREF(time); - } - return result; + if (time != NULL) { + result = PyObject_CallMethod(time, "time", "()"); + Py_DECREF(time); + } + return result; } /* Build a time.struct_time. The weekday and day number are automatically @@ -1406,21 +1406,21 @@ static PyObject * build_struct_time(int y, int m, int d, int hh, int mm, int ss, int dstflag) { - PyObject *time; - PyObject *result = NULL; + PyObject *time; + PyObject *result = NULL; - time = PyImport_ImportModuleNoBlock("time"); - if (time != NULL) { - result = PyObject_CallMethod(time, "struct_time", - "((iiiiiiiii))", - y, m, d, - hh, mm, ss, - weekday(y, m, d), - days_before_month(y, m) + d, - dstflag); - Py_DECREF(time); - } - return result; + time = PyImport_ImportModuleNoBlock("time"); + if (time != NULL) { + result = PyObject_CallMethod(time, "struct_time", + "((iiiiiiiii))", + y, m, d, + hh, mm, ss, + weekday(y, m, d), + days_before_month(y, m) + d, + dstflag); + Py_DECREF(time); + } + return result; } /* --------------------------------------------------------------------------- @@ -1434,33 +1434,33 @@ static PyObject * diff_to_bool(int diff, int op) { - PyObject *result; - int istrue; + PyObject *result; + int istrue; - switch (op) { - case Py_EQ: istrue = diff == 0; break; - case Py_NE: istrue = diff != 0; break; - case Py_LE: istrue = diff <= 0; break; - case Py_GE: istrue = diff >= 0; break; - case Py_LT: istrue = diff < 0; break; - case Py_GT: istrue = diff > 0; break; - default: - assert(! "op unknown"); - istrue = 0; /* To shut up compiler */ - } - result = istrue ? Py_True : Py_False; - Py_INCREF(result); - return result; + switch (op) { + case Py_EQ: istrue = diff == 0; break; + case Py_NE: istrue = diff != 0; break; + case Py_LE: istrue = diff <= 0; break; + case Py_GE: istrue = diff >= 0; break; + case Py_LT: istrue = diff < 0; break; + case Py_GT: istrue = diff > 0; break; + default: + assert(! "op unknown"); + istrue = 0; /* To shut up compiler */ + } + result = istrue ? Py_True : Py_False; + Py_INCREF(result); + return result; } /* Raises a "can't compare" TypeError and returns NULL. */ static PyObject * cmperror(PyObject *a, PyObject *b) { - PyErr_Format(PyExc_TypeError, - "can't compare %s to %s", - Py_TYPE(a)->tp_name, Py_TYPE(b)->tp_name); - return NULL; + PyErr_Format(PyExc_TypeError, + "can't compare %s to %s", + Py_TYPE(a)->tp_name, Py_TYPE(b)->tp_name); + return NULL; } /* --------------------------------------------------------------------------- @@ -1468,13 +1468,13 @@ */ /* Conversion factors. */ -static PyObject *us_per_us = NULL; /* 1 */ -static PyObject *us_per_ms = NULL; /* 1000 */ -static PyObject *us_per_second = NULL; /* 1000000 */ -static PyObject *us_per_minute = NULL; /* 1e6 * 60 as Python int */ -static PyObject *us_per_hour = NULL; /* 1e6 * 3600 as Python long */ -static PyObject *us_per_day = NULL; /* 1e6 * 3600 * 24 as Python long */ -static PyObject *us_per_week = NULL; /* 1e6*3600*24*7 as Python long */ +static PyObject *us_per_us = NULL; /* 1 */ +static PyObject *us_per_ms = NULL; /* 1000 */ +static PyObject *us_per_second = NULL; /* 1000000 */ +static PyObject *us_per_minute = NULL; /* 1e6 * 60 as Python int */ +static PyObject *us_per_hour = NULL; /* 1e6 * 3600 as Python long */ +static PyObject *us_per_day = NULL; /* 1e6 * 3600 * 24 as Python long */ +static PyObject *us_per_week = NULL; /* 1e6*3600*24*7 as Python long */ static PyObject *seconds_per_day = NULL; /* 3600*24 as Python int */ /* --------------------------------------------------------------------------- @@ -1486,7 +1486,7 @@ */ /* Convert a timedelta to a number of us, - * (24*3600*self.days + self.seconds)*1000000 + self.microseconds + * (24*3600*self.days + self.seconds)*1000000 + self.microseconds * as a Python int or long. * Doing mixed-radix arithmetic by hand instead is excruciating in C, * due to ubiquitous overflow possibilities. @@ -1494,49 +1494,49 @@ static PyObject * delta_to_microseconds(PyDateTime_Delta *self) { - PyObject *x1 = NULL; - PyObject *x2 = NULL; - PyObject *x3 = NULL; - PyObject *result = NULL; - - x1 = PyLong_FromLong(GET_TD_DAYS(self)); - if (x1 == NULL) - goto Done; - x2 = PyNumber_Multiply(x1, seconds_per_day); /* days in seconds */ - if (x2 == NULL) - goto Done; - Py_DECREF(x1); - x1 = NULL; - - /* x2 has days in seconds */ - x1 = PyLong_FromLong(GET_TD_SECONDS(self)); /* seconds */ - if (x1 == NULL) - goto Done; - x3 = PyNumber_Add(x1, x2); /* days and seconds in seconds */ - if (x3 == NULL) - goto Done; - Py_DECREF(x1); - Py_DECREF(x2); - x1 = x2 = NULL; - - /* x3 has days+seconds in seconds */ - x1 = PyNumber_Multiply(x3, us_per_second); /* us */ - if (x1 == NULL) - goto Done; - Py_DECREF(x3); - x3 = NULL; - - /* x1 has days+seconds in us */ - x2 = PyLong_FromLong(GET_TD_MICROSECONDS(self)); - if (x2 == NULL) - goto Done; - result = PyNumber_Add(x1, x2); + PyObject *x1 = NULL; + PyObject *x2 = NULL; + PyObject *x3 = NULL; + PyObject *result = NULL; + + x1 = PyLong_FromLong(GET_TD_DAYS(self)); + if (x1 == NULL) + goto Done; + x2 = PyNumber_Multiply(x1, seconds_per_day); /* days in seconds */ + if (x2 == NULL) + goto Done; + Py_DECREF(x1); + x1 = NULL; + + /* x2 has days in seconds */ + x1 = PyLong_FromLong(GET_TD_SECONDS(self)); /* seconds */ + if (x1 == NULL) + goto Done; + x3 = PyNumber_Add(x1, x2); /* days and seconds in seconds */ + if (x3 == NULL) + goto Done; + Py_DECREF(x1); + Py_DECREF(x2); + x1 = x2 = NULL; + + /* x3 has days+seconds in seconds */ + x1 = PyNumber_Multiply(x3, us_per_second); /* us */ + if (x1 == NULL) + goto Done; + Py_DECREF(x3); + x3 = NULL; + + /* x1 has days+seconds in us */ + x2 = PyLong_FromLong(GET_TD_MICROSECONDS(self)); + if (x2 == NULL) + goto Done; + result = PyNumber_Add(x1, x2); Done: - Py_XDECREF(x1); - Py_XDECREF(x2); - Py_XDECREF(x3); - return result; + Py_XDECREF(x1); + Py_XDECREF(x2); + Py_XDECREF(x3); + return result; } /* Convert a number of us (as a Python int or long) to a timedelta. @@ -1544,270 +1544,270 @@ static PyObject * microseconds_to_delta_ex(PyObject *pyus, PyTypeObject *type) { - int us; - int s; - int d; - long temp; - - PyObject *tuple = NULL; - PyObject *num = NULL; - PyObject *result = NULL; - - tuple = PyNumber_Divmod(pyus, us_per_second); - if (tuple == NULL) - goto Done; - - num = PyTuple_GetItem(tuple, 1); /* us */ - if (num == NULL) - goto Done; - temp = PyLong_AsLong(num); - num = NULL; - if (temp == -1 && PyErr_Occurred()) - goto Done; - assert(0 <= temp && temp < 1000000); - us = (int)temp; - if (us < 0) { - /* The divisor was positive, so this must be an error. */ - assert(PyErr_Occurred()); - goto Done; - } - - num = PyTuple_GetItem(tuple, 0); /* leftover seconds */ - if (num == NULL) - goto Done; - Py_INCREF(num); - Py_DECREF(tuple); - - tuple = PyNumber_Divmod(num, seconds_per_day); - if (tuple == NULL) - goto Done; - Py_DECREF(num); - - num = PyTuple_GetItem(tuple, 1); /* seconds */ - if (num == NULL) - goto Done; - temp = PyLong_AsLong(num); - num = NULL; - if (temp == -1 && PyErr_Occurred()) - goto Done; - assert(0 <= temp && temp < 24*3600); - s = (int)temp; - - if (s < 0) { - /* The divisor was positive, so this must be an error. */ - assert(PyErr_Occurred()); - goto Done; - } - - num = PyTuple_GetItem(tuple, 0); /* leftover days */ - if (num == NULL) - goto Done; - Py_INCREF(num); - temp = PyLong_AsLong(num); - if (temp == -1 && PyErr_Occurred()) - goto Done; - d = (int)temp; - if ((long)d != temp) { - PyErr_SetString(PyExc_OverflowError, "normalized days too " - "large to fit in a C int"); - goto Done; - } - result = new_delta_ex(d, s, us, 0, type); + int us; + int s; + int d; + long temp; + + PyObject *tuple = NULL; + PyObject *num = NULL; + PyObject *result = NULL; + + tuple = PyNumber_Divmod(pyus, us_per_second); + if (tuple == NULL) + goto Done; + + num = PyTuple_GetItem(tuple, 1); /* us */ + if (num == NULL) + goto Done; + temp = PyLong_AsLong(num); + num = NULL; + if (temp == -1 && PyErr_Occurred()) + goto Done; + assert(0 <= temp && temp < 1000000); + us = (int)temp; + if (us < 0) { + /* The divisor was positive, so this must be an error. */ + assert(PyErr_Occurred()); + goto Done; + } + + num = PyTuple_GetItem(tuple, 0); /* leftover seconds */ + if (num == NULL) + goto Done; + Py_INCREF(num); + Py_DECREF(tuple); + + tuple = PyNumber_Divmod(num, seconds_per_day); + if (tuple == NULL) + goto Done; + Py_DECREF(num); + + num = PyTuple_GetItem(tuple, 1); /* seconds */ + if (num == NULL) + goto Done; + temp = PyLong_AsLong(num); + num = NULL; + if (temp == -1 && PyErr_Occurred()) + goto Done; + assert(0 <= temp && temp < 24*3600); + s = (int)temp; + + if (s < 0) { + /* The divisor was positive, so this must be an error. */ + assert(PyErr_Occurred()); + goto Done; + } + + num = PyTuple_GetItem(tuple, 0); /* leftover days */ + if (num == NULL) + goto Done; + Py_INCREF(num); + temp = PyLong_AsLong(num); + if (temp == -1 && PyErr_Occurred()) + goto Done; + d = (int)temp; + if ((long)d != temp) { + PyErr_SetString(PyExc_OverflowError, "normalized days too " + "large to fit in a C int"); + goto Done; + } + result = new_delta_ex(d, s, us, 0, type); Done: - Py_XDECREF(tuple); - Py_XDECREF(num); - return result; + Py_XDECREF(tuple); + Py_XDECREF(num); + return result; } -#define microseconds_to_delta(pymicros) \ - microseconds_to_delta_ex(pymicros, &PyDateTime_DeltaType) +#define microseconds_to_delta(pymicros) \ + microseconds_to_delta_ex(pymicros, &PyDateTime_DeltaType) static PyObject * multiply_int_timedelta(PyObject *intobj, PyDateTime_Delta *delta) { - PyObject *pyus_in; - PyObject *pyus_out; - PyObject *result; - - pyus_in = delta_to_microseconds(delta); - if (pyus_in == NULL) - return NULL; - - pyus_out = PyNumber_Multiply(pyus_in, intobj); - Py_DECREF(pyus_in); - if (pyus_out == NULL) - return NULL; - - result = microseconds_to_delta(pyus_out); - Py_DECREF(pyus_out); - return result; + PyObject *pyus_in; + PyObject *pyus_out; + PyObject *result; + + pyus_in = delta_to_microseconds(delta); + if (pyus_in == NULL) + return NULL; + + pyus_out = PyNumber_Multiply(pyus_in, intobj); + Py_DECREF(pyus_in); + if (pyus_out == NULL) + return NULL; + + result = microseconds_to_delta(pyus_out); + Py_DECREF(pyus_out); + return result; } static PyObject * divide_timedelta_int(PyDateTime_Delta *delta, PyObject *intobj) { - PyObject *pyus_in; - PyObject *pyus_out; - PyObject *result; - - pyus_in = delta_to_microseconds(delta); - if (pyus_in == NULL) - return NULL; - - pyus_out = PyNumber_FloorDivide(pyus_in, intobj); - Py_DECREF(pyus_in); - if (pyus_out == NULL) - return NULL; - - result = microseconds_to_delta(pyus_out); - Py_DECREF(pyus_out); - return result; + PyObject *pyus_in; + PyObject *pyus_out; + PyObject *result; + + pyus_in = delta_to_microseconds(delta); + if (pyus_in == NULL) + return NULL; + + pyus_out = PyNumber_FloorDivide(pyus_in, intobj); + Py_DECREF(pyus_in); + if (pyus_out == NULL) + return NULL; + + result = microseconds_to_delta(pyus_out); + Py_DECREF(pyus_out); + return result; } static PyObject * divide_timedelta_timedelta(PyDateTime_Delta *left, PyDateTime_Delta *right) { - PyObject *pyus_left; - PyObject *pyus_right; - PyObject *result; - - pyus_left = delta_to_microseconds(left); - if (pyus_left == NULL) - return NULL; - - pyus_right = delta_to_microseconds(right); - if (pyus_right == NULL) { - Py_DECREF(pyus_left); - return NULL; - } - - result = PyNumber_FloorDivide(pyus_left, pyus_right); - Py_DECREF(pyus_left); - Py_DECREF(pyus_right); - return result; + PyObject *pyus_left; + PyObject *pyus_right; + PyObject *result; + + pyus_left = delta_to_microseconds(left); + if (pyus_left == NULL) + return NULL; + + pyus_right = delta_to_microseconds(right); + if (pyus_right == NULL) { + Py_DECREF(pyus_left); + return NULL; + } + + result = PyNumber_FloorDivide(pyus_left, pyus_right); + Py_DECREF(pyus_left); + Py_DECREF(pyus_right); + return result; } static PyObject * truedivide_timedelta_timedelta(PyDateTime_Delta *left, PyDateTime_Delta *right) { - PyObject *pyus_left; - PyObject *pyus_right; - PyObject *result; - - pyus_left = delta_to_microseconds(left); - if (pyus_left == NULL) - return NULL; - - pyus_right = delta_to_microseconds(right); - if (pyus_right == NULL) { - Py_DECREF(pyus_left); - return NULL; - } - - result = PyNumber_TrueDivide(pyus_left, pyus_right); - Py_DECREF(pyus_left); - Py_DECREF(pyus_right); - return result; + PyObject *pyus_left; + PyObject *pyus_right; + PyObject *result; + + pyus_left = delta_to_microseconds(left); + if (pyus_left == NULL) + return NULL; + + pyus_right = delta_to_microseconds(right); + if (pyus_right == NULL) { + Py_DECREF(pyus_left); + return NULL; + } + + result = PyNumber_TrueDivide(pyus_left, pyus_right); + Py_DECREF(pyus_left); + Py_DECREF(pyus_right); + return result; } static PyObject * delta_add(PyObject *left, PyObject *right) { - PyObject *result = Py_NotImplemented; + PyObject *result = Py_NotImplemented; - if (PyDelta_Check(left) && PyDelta_Check(right)) { - /* delta + delta */ - /* The C-level additions can't overflow because of the - * invariant bounds. - */ - int days = GET_TD_DAYS(left) + GET_TD_DAYS(right); - int seconds = GET_TD_SECONDS(left) + GET_TD_SECONDS(right); - int microseconds = GET_TD_MICROSECONDS(left) + - GET_TD_MICROSECONDS(right); - result = new_delta(days, seconds, microseconds, 1); - } - - if (result == Py_NotImplemented) - Py_INCREF(result); - return result; + if (PyDelta_Check(left) && PyDelta_Check(right)) { + /* delta + delta */ + /* The C-level additions can't overflow because of the + * invariant bounds. + */ + int days = GET_TD_DAYS(left) + GET_TD_DAYS(right); + int seconds = GET_TD_SECONDS(left) + GET_TD_SECONDS(right); + int microseconds = GET_TD_MICROSECONDS(left) + + GET_TD_MICROSECONDS(right); + result = new_delta(days, seconds, microseconds, 1); + } + + if (result == Py_NotImplemented) + Py_INCREF(result); + return result; } static PyObject * delta_negative(PyDateTime_Delta *self) { - return new_delta(-GET_TD_DAYS(self), - -GET_TD_SECONDS(self), - -GET_TD_MICROSECONDS(self), - 1); + return new_delta(-GET_TD_DAYS(self), + -GET_TD_SECONDS(self), + -GET_TD_MICROSECONDS(self), + 1); } static PyObject * delta_positive(PyDateTime_Delta *self) { - /* Could optimize this (by returning self) if this isn't a - * subclass -- but who uses unary + ? Approximately nobody. - */ - return new_delta(GET_TD_DAYS(self), - GET_TD_SECONDS(self), - GET_TD_MICROSECONDS(self), - 0); + /* Could optimize this (by returning self) if this isn't a + * subclass -- but who uses unary + ? Approximately nobody. + */ + return new_delta(GET_TD_DAYS(self), + GET_TD_SECONDS(self), + GET_TD_MICROSECONDS(self), + 0); } static PyObject * delta_abs(PyDateTime_Delta *self) { - PyObject *result; + PyObject *result; - assert(GET_TD_MICROSECONDS(self) >= 0); - assert(GET_TD_SECONDS(self) >= 0); + assert(GET_TD_MICROSECONDS(self) >= 0); + assert(GET_TD_SECONDS(self) >= 0); - if (GET_TD_DAYS(self) < 0) - result = delta_negative(self); - else - result = delta_positive(self); + if (GET_TD_DAYS(self) < 0) + result = delta_negative(self); + else + result = delta_positive(self); - return result; + return result; } static PyObject * delta_subtract(PyObject *left, PyObject *right) { - PyObject *result = Py_NotImplemented; + PyObject *result = Py_NotImplemented; - if (PyDelta_Check(left) && PyDelta_Check(right)) { - /* delta - delta */ - PyObject *minus_right = PyNumber_Negative(right); - if (minus_right) { - result = delta_add(left, minus_right); - Py_DECREF(minus_right); - } - else - result = NULL; - } - - if (result == Py_NotImplemented) - Py_INCREF(result); - return result; + if (PyDelta_Check(left) && PyDelta_Check(right)) { + /* delta - delta */ + PyObject *minus_right = PyNumber_Negative(right); + if (minus_right) { + result = delta_add(left, minus_right); + Py_DECREF(minus_right); + } + else + result = NULL; + } + + if (result == Py_NotImplemented) + Py_INCREF(result); + return result; } static PyObject * delta_richcompare(PyObject *self, PyObject *other, int op) { - if (PyDelta_Check(other)) { - int diff = GET_TD_DAYS(self) - GET_TD_DAYS(other); - if (diff == 0) { - diff = GET_TD_SECONDS(self) - GET_TD_SECONDS(other); - if (diff == 0) - diff = GET_TD_MICROSECONDS(self) - - GET_TD_MICROSECONDS(other); - } - return diff_to_bool(diff, op); - } - else { - Py_INCREF(Py_NotImplemented); - return Py_NotImplemented; - } + if (PyDelta_Check(other)) { + int diff = GET_TD_DAYS(self) - GET_TD_DAYS(other); + if (diff == 0) { + diff = GET_TD_SECONDS(self) - GET_TD_SECONDS(other); + if (diff == 0) + diff = GET_TD_MICROSECONDS(self) - + GET_TD_MICROSECONDS(other); + } + return diff_to_bool(diff, op); + } + else { + Py_INCREF(Py_NotImplemented); + return Py_NotImplemented; + } } static PyObject *delta_getstate(PyDateTime_Delta *self); @@ -1815,152 +1815,152 @@ static long delta_hash(PyDateTime_Delta *self) { - if (self->hashcode == -1) { - PyObject *temp = delta_getstate(self); - if (temp != NULL) { - self->hashcode = PyObject_Hash(temp); - Py_DECREF(temp); - } - } - return self->hashcode; + if (self->hashcode == -1) { + PyObject *temp = delta_getstate(self); + if (temp != NULL) { + self->hashcode = PyObject_Hash(temp); + Py_DECREF(temp); + } + } + return self->hashcode; } static PyObject * delta_multiply(PyObject *left, PyObject *right) { - PyObject *result = Py_NotImplemented; + PyObject *result = Py_NotImplemented; - if (PyDelta_Check(left)) { - /* delta * ??? */ - if (PyLong_Check(right)) - result = multiply_int_timedelta(right, - (PyDateTime_Delta *) left); - } - else if (PyLong_Check(left)) - result = multiply_int_timedelta(left, - (PyDateTime_Delta *) right); - - if (result == Py_NotImplemented) - Py_INCREF(result); - return result; + if (PyDelta_Check(left)) { + /* delta * ??? */ + if (PyLong_Check(right)) + result = multiply_int_timedelta(right, + (PyDateTime_Delta *) left); + } + else if (PyLong_Check(left)) + result = multiply_int_timedelta(left, + (PyDateTime_Delta *) right); + + if (result == Py_NotImplemented) + Py_INCREF(result); + return result; } static PyObject * delta_divide(PyObject *left, PyObject *right) { - PyObject *result = Py_NotImplemented; + PyObject *result = Py_NotImplemented; - if (PyDelta_Check(left)) { - /* delta * ??? */ - if (PyLong_Check(right)) - result = divide_timedelta_int( - (PyDateTime_Delta *)left, - right); - else if (PyDelta_Check(right)) - result = divide_timedelta_timedelta( - (PyDateTime_Delta *)left, - (PyDateTime_Delta *)right); - } - - if (result == Py_NotImplemented) - Py_INCREF(result); - return result; + if (PyDelta_Check(left)) { + /* delta * ??? */ + if (PyLong_Check(right)) + result = divide_timedelta_int( + (PyDateTime_Delta *)left, + right); + else if (PyDelta_Check(right)) + result = divide_timedelta_timedelta( + (PyDateTime_Delta *)left, + (PyDateTime_Delta *)right); + } + + if (result == Py_NotImplemented) + Py_INCREF(result); + return result; } static PyObject * delta_truedivide(PyObject *left, PyObject *right) { - PyObject *result = Py_NotImplemented; + PyObject *result = Py_NotImplemented; - if (PyDelta_Check(left)) { - if (PyDelta_Check(right)) - result = truedivide_timedelta_timedelta( - (PyDateTime_Delta *)left, - (PyDateTime_Delta *)right); - } - - if (result == Py_NotImplemented) - Py_INCREF(result); - return result; + if (PyDelta_Check(left)) { + if (PyDelta_Check(right)) + result = truedivide_timedelta_timedelta( + (PyDateTime_Delta *)left, + (PyDateTime_Delta *)right); + } + + if (result == Py_NotImplemented) + Py_INCREF(result); + return result; } static PyObject * delta_remainder(PyObject *left, PyObject *right) { - PyObject *pyus_left; - PyObject *pyus_right; - PyObject *pyus_remainder; - PyObject *remainder; - - if (!PyDelta_Check(left) || !PyDelta_Check(right)) { - Py_INCREF(Py_NotImplemented); - return Py_NotImplemented; - } - - pyus_left = delta_to_microseconds((PyDateTime_Delta *)left); - if (pyus_left == NULL) - return NULL; - - pyus_right = delta_to_microseconds((PyDateTime_Delta *)right); - if (pyus_right == NULL) { - Py_DECREF(pyus_left); - return NULL; - } - - pyus_remainder = PyNumber_Remainder(pyus_left, pyus_right); - Py_DECREF(pyus_left); - Py_DECREF(pyus_right); - if (pyus_remainder == NULL) - return NULL; - - remainder = microseconds_to_delta(pyus_remainder); - Py_DECREF(pyus_remainder); - if (remainder == NULL) - return NULL; + PyObject *pyus_left; + PyObject *pyus_right; + PyObject *pyus_remainder; + PyObject *remainder; + + if (!PyDelta_Check(left) || !PyDelta_Check(right)) { + Py_INCREF(Py_NotImplemented); + return Py_NotImplemented; + } + + pyus_left = delta_to_microseconds((PyDateTime_Delta *)left); + if (pyus_left == NULL) + return NULL; + + pyus_right = delta_to_microseconds((PyDateTime_Delta *)right); + if (pyus_right == NULL) { + Py_DECREF(pyus_left); + return NULL; + } + + pyus_remainder = PyNumber_Remainder(pyus_left, pyus_right); + Py_DECREF(pyus_left); + Py_DECREF(pyus_right); + if (pyus_remainder == NULL) + return NULL; + + remainder = microseconds_to_delta(pyus_remainder); + Py_DECREF(pyus_remainder); + if (remainder == NULL) + return NULL; - return remainder; + return remainder; } static PyObject * delta_divmod(PyObject *left, PyObject *right) { - PyObject *pyus_left; - PyObject *pyus_right; - PyObject *divmod; - PyObject *delta; - PyObject *result; - - if (!PyDelta_Check(left) || !PyDelta_Check(right)) { - Py_INCREF(Py_NotImplemented); - return Py_NotImplemented; - } - - pyus_left = delta_to_microseconds((PyDateTime_Delta *)left); - if (pyus_left == NULL) - return NULL; - - pyus_right = delta_to_microseconds((PyDateTime_Delta *)right); - if (pyus_right == NULL) { - Py_DECREF(pyus_left); - return NULL; - } - - divmod = PyNumber_Divmod(pyus_left, pyus_right); - Py_DECREF(pyus_left); - Py_DECREF(pyus_right); - if (divmod == NULL) - return NULL; - - assert(PyTuple_Size(divmod) == 2); - delta = microseconds_to_delta(PyTuple_GET_ITEM(divmod, 1)); - if (delta == NULL) { - Py_DECREF(divmod); - return NULL; - } - result = PyTuple_Pack(2, PyTuple_GET_ITEM(divmod, 0), delta); - Py_DECREF(delta); - Py_DECREF(divmod); - return result; + PyObject *pyus_left; + PyObject *pyus_right; + PyObject *divmod; + PyObject *delta; + PyObject *result; + + if (!PyDelta_Check(left) || !PyDelta_Check(right)) { + Py_INCREF(Py_NotImplemented); + return Py_NotImplemented; + } + + pyus_left = delta_to_microseconds((PyDateTime_Delta *)left); + if (pyus_left == NULL) + return NULL; + + pyus_right = delta_to_microseconds((PyDateTime_Delta *)right); + if (pyus_right == NULL) { + Py_DECREF(pyus_left); + return NULL; + } + + divmod = PyNumber_Divmod(pyus_left, pyus_right); + Py_DECREF(pyus_left); + Py_DECREF(pyus_right); + if (divmod == NULL) + return NULL; + + assert(PyTuple_Size(divmod) == 2); + delta = microseconds_to_delta(PyTuple_GET_ITEM(divmod, 1)); + if (delta == NULL) { + Py_DECREF(divmod); + return NULL; + } + result = PyTuple_Pack(2, PyTuple_GET_ITEM(divmod, 0), delta); + Py_DECREF(delta); + Py_DECREF(divmod); + return result; } /* Fold in the value of the tag ("seconds", "weeks", etc) component of a @@ -1976,166 +1976,166 @@ accum(const char* tag, PyObject *sofar, PyObject *num, PyObject *factor, double *leftover) { - PyObject *prod; - PyObject *sum; + PyObject *prod; + PyObject *sum; - assert(num != NULL); + assert(num != NULL); - if (PyLong_Check(num)) { - prod = PyNumber_Multiply(num, factor); - if (prod == NULL) - return NULL; - sum = PyNumber_Add(sofar, prod); - Py_DECREF(prod); - return sum; - } - - if (PyFloat_Check(num)) { - double dnum; - double fracpart; - double intpart; - PyObject *x; - PyObject *y; - - /* The Plan: decompose num into an integer part and a - * fractional part, num = intpart + fracpart. - * Then num * factor == - * intpart * factor + fracpart * factor - * and the LHS can be computed exactly in long arithmetic. - * The RHS is again broken into an int part and frac part. - * and the frac part is added into *leftover. - */ - dnum = PyFloat_AsDouble(num); - if (dnum == -1.0 && PyErr_Occurred()) - return NULL; - fracpart = modf(dnum, &intpart); - x = PyLong_FromDouble(intpart); - if (x == NULL) - return NULL; - - prod = PyNumber_Multiply(x, factor); - Py_DECREF(x); - if (prod == NULL) - return NULL; - - sum = PyNumber_Add(sofar, prod); - Py_DECREF(prod); - if (sum == NULL) - return NULL; - - if (fracpart == 0.0) - return sum; - /* So far we've lost no information. Dealing with the - * fractional part requires float arithmetic, and may - * lose a little info. - */ - assert(PyLong_Check(factor)); - dnum = PyLong_AsDouble(factor); - - dnum *= fracpart; - fracpart = modf(dnum, &intpart); - x = PyLong_FromDouble(intpart); - if (x == NULL) { - Py_DECREF(sum); - return NULL; - } - - y = PyNumber_Add(sum, x); - Py_DECREF(sum); - Py_DECREF(x); - *leftover += fracpart; - return y; - } - - PyErr_Format(PyExc_TypeError, - "unsupported type for timedelta %s component: %s", - tag, Py_TYPE(num)->tp_name); - return NULL; + if (PyLong_Check(num)) { + prod = PyNumber_Multiply(num, factor); + if (prod == NULL) + return NULL; + sum = PyNumber_Add(sofar, prod); + Py_DECREF(prod); + return sum; + } + + if (PyFloat_Check(num)) { + double dnum; + double fracpart; + double intpart; + PyObject *x; + PyObject *y; + + /* The Plan: decompose num into an integer part and a + * fractional part, num = intpart + fracpart. + * Then num * factor == + * intpart * factor + fracpart * factor + * and the LHS can be computed exactly in long arithmetic. + * The RHS is again broken into an int part and frac part. + * and the frac part is added into *leftover. + */ + dnum = PyFloat_AsDouble(num); + if (dnum == -1.0 && PyErr_Occurred()) + return NULL; + fracpart = modf(dnum, &intpart); + x = PyLong_FromDouble(intpart); + if (x == NULL) + return NULL; + + prod = PyNumber_Multiply(x, factor); + Py_DECREF(x); + if (prod == NULL) + return NULL; + + sum = PyNumber_Add(sofar, prod); + Py_DECREF(prod); + if (sum == NULL) + return NULL; + + if (fracpart == 0.0) + return sum; + /* So far we've lost no information. Dealing with the + * fractional part requires float arithmetic, and may + * lose a little info. + */ + assert(PyLong_Check(factor)); + dnum = PyLong_AsDouble(factor); + + dnum *= fracpart; + fracpart = modf(dnum, &intpart); + x = PyLong_FromDouble(intpart); + if (x == NULL) { + Py_DECREF(sum); + return NULL; + } + + y = PyNumber_Add(sum, x); + Py_DECREF(sum); + Py_DECREF(x); + *leftover += fracpart; + return y; + } + + PyErr_Format(PyExc_TypeError, + "unsupported type for timedelta %s component: %s", + tag, Py_TYPE(num)->tp_name); + return NULL; } static PyObject * delta_new(PyTypeObject *type, PyObject *args, PyObject *kw) { - PyObject *self = NULL; + PyObject *self = NULL; - /* Argument objects. */ - PyObject *day = NULL; - PyObject *second = NULL; - PyObject *us = NULL; - PyObject *ms = NULL; - PyObject *minute = NULL; - PyObject *hour = NULL; - PyObject *week = NULL; - - PyObject *x = NULL; /* running sum of microseconds */ - PyObject *y = NULL; /* temp sum of microseconds */ - double leftover_us = 0.0; - - static char *keywords[] = { - "days", "seconds", "microseconds", "milliseconds", - "minutes", "hours", "weeks", NULL - }; - - if (PyArg_ParseTupleAndKeywords(args, kw, "|OOOOOOO:__new__", - keywords, - &day, &second, &us, - &ms, &minute, &hour, &week) == 0) - goto Done; - - x = PyLong_FromLong(0); - if (x == NULL) - goto Done; - -#define CLEANUP \ - Py_DECREF(x); \ - x = y; \ - if (x == NULL) \ - goto Done - - if (us) { - y = accum("microseconds", x, us, us_per_us, &leftover_us); - CLEANUP; - } - if (ms) { - y = accum("milliseconds", x, ms, us_per_ms, &leftover_us); - CLEANUP; - } - if (second) { - y = accum("seconds", x, second, us_per_second, &leftover_us); - CLEANUP; - } - if (minute) { - y = accum("minutes", x, minute, us_per_minute, &leftover_us); - CLEANUP; - } - if (hour) { - y = accum("hours", x, hour, us_per_hour, &leftover_us); - CLEANUP; - } - if (day) { - y = accum("days", x, day, us_per_day, &leftover_us); - CLEANUP; - } - if (week) { - y = accum("weeks", x, week, us_per_week, &leftover_us); - CLEANUP; - } - if (leftover_us) { - /* Round to nearest whole # of us, and add into x. */ - PyObject *temp = PyLong_FromLong(round_to_long(leftover_us)); - if (temp == NULL) { - Py_DECREF(x); - goto Done; - } - y = PyNumber_Add(x, temp); - Py_DECREF(temp); - CLEANUP; - } + /* Argument objects. */ + PyObject *day = NULL; + PyObject *second = NULL; + PyObject *us = NULL; + PyObject *ms = NULL; + PyObject *minute = NULL; + PyObject *hour = NULL; + PyObject *week = NULL; + + PyObject *x = NULL; /* running sum of microseconds */ + PyObject *y = NULL; /* temp sum of microseconds */ + double leftover_us = 0.0; + + static char *keywords[] = { + "days", "seconds", "microseconds", "milliseconds", + "minutes", "hours", "weeks", NULL + }; + + if (PyArg_ParseTupleAndKeywords(args, kw, "|OOOOOOO:__new__", + keywords, + &day, &second, &us, + &ms, &minute, &hour, &week) == 0) + goto Done; + + x = PyLong_FromLong(0); + if (x == NULL) + goto Done; + +#define CLEANUP \ + Py_DECREF(x); \ + x = y; \ + if (x == NULL) \ + goto Done + + if (us) { + y = accum("microseconds", x, us, us_per_us, &leftover_us); + CLEANUP; + } + if (ms) { + y = accum("milliseconds", x, ms, us_per_ms, &leftover_us); + CLEANUP; + } + if (second) { + y = accum("seconds", x, second, us_per_second, &leftover_us); + CLEANUP; + } + if (minute) { + y = accum("minutes", x, minute, us_per_minute, &leftover_us); + CLEANUP; + } + if (hour) { + y = accum("hours", x, hour, us_per_hour, &leftover_us); + CLEANUP; + } + if (day) { + y = accum("days", x, day, us_per_day, &leftover_us); + CLEANUP; + } + if (week) { + y = accum("weeks", x, week, us_per_week, &leftover_us); + CLEANUP; + } + if (leftover_us) { + /* Round to nearest whole # of us, and add into x. */ + PyObject *temp = PyLong_FromLong(round_to_long(leftover_us)); + if (temp == NULL) { + Py_DECREF(x); + goto Done; + } + y = PyNumber_Add(x, temp); + Py_DECREF(temp); + CLEANUP; + } - self = microseconds_to_delta_ex(x, type); - Py_DECREF(x); + self = microseconds_to_delta_ex(x, type); + Py_DECREF(x); Done: - return self; + return self; #undef CLEANUP } @@ -2143,57 +2143,57 @@ static int delta_bool(PyDateTime_Delta *self) { - return (GET_TD_DAYS(self) != 0 - || GET_TD_SECONDS(self) != 0 - || GET_TD_MICROSECONDS(self) != 0); + return (GET_TD_DAYS(self) != 0 + || GET_TD_SECONDS(self) != 0 + || GET_TD_MICROSECONDS(self) != 0); } static PyObject * delta_repr(PyDateTime_Delta *self) { - if (GET_TD_MICROSECONDS(self) != 0) - return PyUnicode_FromFormat("%s(%d, %d, %d)", - Py_TYPE(self)->tp_name, - GET_TD_DAYS(self), - GET_TD_SECONDS(self), - GET_TD_MICROSECONDS(self)); - if (GET_TD_SECONDS(self) != 0) - return PyUnicode_FromFormat("%s(%d, %d)", - Py_TYPE(self)->tp_name, - GET_TD_DAYS(self), - GET_TD_SECONDS(self)); - - return PyUnicode_FromFormat("%s(%d)", - Py_TYPE(self)->tp_name, - GET_TD_DAYS(self)); + if (GET_TD_MICROSECONDS(self) != 0) + return PyUnicode_FromFormat("%s(%d, %d, %d)", + Py_TYPE(self)->tp_name, + GET_TD_DAYS(self), + GET_TD_SECONDS(self), + GET_TD_MICROSECONDS(self)); + if (GET_TD_SECONDS(self) != 0) + return PyUnicode_FromFormat("%s(%d, %d)", + Py_TYPE(self)->tp_name, + GET_TD_DAYS(self), + GET_TD_SECONDS(self)); + + return PyUnicode_FromFormat("%s(%d)", + Py_TYPE(self)->tp_name, + GET_TD_DAYS(self)); } static PyObject * delta_str(PyDateTime_Delta *self) { - int us = GET_TD_MICROSECONDS(self); - int seconds = GET_TD_SECONDS(self); - int minutes = divmod(seconds, 60, &seconds); - int hours = divmod(minutes, 60, &minutes); - int days = GET_TD_DAYS(self); - - if (days) { - if (us) - return PyUnicode_FromFormat("%d day%s, %d:%02d:%02d.%06d", - days, (days == 1 || days == -1) ? "" : "s", - hours, minutes, seconds, us); - else - return PyUnicode_FromFormat("%d day%s, %d:%02d:%02d", - days, (days == 1 || days == -1) ? "" : "s", - hours, minutes, seconds); - } else { - if (us) - return PyUnicode_FromFormat("%d:%02d:%02d.%06d", - hours, minutes, seconds, us); - else - return PyUnicode_FromFormat("%d:%02d:%02d", - hours, minutes, seconds); - } + int us = GET_TD_MICROSECONDS(self); + int seconds = GET_TD_SECONDS(self); + int minutes = divmod(seconds, 60, &seconds); + int hours = divmod(minutes, 60, &minutes); + int days = GET_TD_DAYS(self); + + if (days) { + if (us) + return PyUnicode_FromFormat("%d day%s, %d:%02d:%02d.%06d", + days, (days == 1 || days == -1) ? "" : "s", + hours, minutes, seconds, us); + else + return PyUnicode_FromFormat("%d day%s, %d:%02d:%02d", + days, (days == 1 || days == -1) ? "" : "s", + hours, minutes, seconds); + } else { + if (us) + return PyUnicode_FromFormat("%d:%02d:%02d.%06d", + hours, minutes, seconds, us); + else + return PyUnicode_FromFormat("%d:%02d:%02d", + hours, minutes, seconds); + } } @@ -2203,145 +2203,145 @@ static PyObject * delta_getstate(PyDateTime_Delta *self) { - return Py_BuildValue("iii", GET_TD_DAYS(self), - GET_TD_SECONDS(self), - GET_TD_MICROSECONDS(self)); + return Py_BuildValue("iii", GET_TD_DAYS(self), + GET_TD_SECONDS(self), + GET_TD_MICROSECONDS(self)); } static PyObject * delta_total_seconds(PyObject *self) { - PyObject *total_seconds; - PyObject *total_microseconds; - PyObject *one_million; - - total_microseconds = delta_to_microseconds((PyDateTime_Delta *)self); - if (total_microseconds == NULL) - return NULL; - - one_million = PyLong_FromLong(1000000L); - if (one_million == NULL) { - Py_DECREF(total_microseconds); - return NULL; - } - - total_seconds = PyNumber_TrueDivide(total_microseconds, one_million); - - Py_DECREF(total_microseconds); - Py_DECREF(one_million); - return total_seconds; + PyObject *total_seconds; + PyObject *total_microseconds; + PyObject *one_million; + + total_microseconds = delta_to_microseconds((PyDateTime_Delta *)self); + if (total_microseconds == NULL) + return NULL; + + one_million = PyLong_FromLong(1000000L); + if (one_million == NULL) { + Py_DECREF(total_microseconds); + return NULL; + } + + total_seconds = PyNumber_TrueDivide(total_microseconds, one_million); + + Py_DECREF(total_microseconds); + Py_DECREF(one_million); + return total_seconds; } static PyObject * delta_reduce(PyDateTime_Delta* self) { - return Py_BuildValue("ON", Py_TYPE(self), delta_getstate(self)); + return Py_BuildValue("ON", Py_TYPE(self), delta_getstate(self)); } #define OFFSET(field) offsetof(PyDateTime_Delta, field) static PyMemberDef delta_members[] = { - {"days", T_INT, OFFSET(days), READONLY, - PyDoc_STR("Number of days.")}, + {"days", T_INT, OFFSET(days), READONLY, + PyDoc_STR("Number of days.")}, - {"seconds", T_INT, OFFSET(seconds), READONLY, - PyDoc_STR("Number of seconds (>= 0 and less than 1 day).")}, + {"seconds", T_INT, OFFSET(seconds), READONLY, + PyDoc_STR("Number of seconds (>= 0 and less than 1 day).")}, - {"microseconds", T_INT, OFFSET(microseconds), READONLY, - PyDoc_STR("Number of microseconds (>= 0 and less than 1 second).")}, - {NULL} + {"microseconds", T_INT, OFFSET(microseconds), READONLY, + PyDoc_STR("Number of microseconds (>= 0 and less than 1 second).")}, + {NULL} }; static PyMethodDef delta_methods[] = { - {"total_seconds", (PyCFunction)delta_total_seconds, METH_NOARGS, - PyDoc_STR("Total seconds in the duration.")}, + {"total_seconds", (PyCFunction)delta_total_seconds, METH_NOARGS, + PyDoc_STR("Total seconds in the duration.")}, - {"__reduce__", (PyCFunction)delta_reduce, METH_NOARGS, - PyDoc_STR("__reduce__() -> (cls, state)")}, + {"__reduce__", (PyCFunction)delta_reduce, METH_NOARGS, + PyDoc_STR("__reduce__() -> (cls, state)")}, - {NULL, NULL}, + {NULL, NULL}, }; static char delta_doc[] = PyDoc_STR("Difference between two datetime values."); static PyNumberMethods delta_as_number = { - delta_add, /* nb_add */ - delta_subtract, /* nb_subtract */ - delta_multiply, /* nb_multiply */ - delta_remainder, /* nb_remainder */ - delta_divmod, /* nb_divmod */ - 0, /* nb_power */ - (unaryfunc)delta_negative, /* nb_negative */ - (unaryfunc)delta_positive, /* nb_positive */ - (unaryfunc)delta_abs, /* nb_absolute */ - (inquiry)delta_bool, /* nb_bool */ - 0, /*nb_invert*/ - 0, /*nb_lshift*/ - 0, /*nb_rshift*/ - 0, /*nb_and*/ - 0, /*nb_xor*/ - 0, /*nb_or*/ - 0, /*nb_int*/ - 0, /*nb_reserved*/ - 0, /*nb_float*/ - 0, /*nb_inplace_add*/ - 0, /*nb_inplace_subtract*/ - 0, /*nb_inplace_multiply*/ - 0, /*nb_inplace_remainder*/ - 0, /*nb_inplace_power*/ - 0, /*nb_inplace_lshift*/ - 0, /*nb_inplace_rshift*/ - 0, /*nb_inplace_and*/ - 0, /*nb_inplace_xor*/ - 0, /*nb_inplace_or*/ - delta_divide, /* nb_floor_divide */ - delta_truedivide, /* nb_true_divide */ - 0, /* nb_inplace_floor_divide */ - 0, /* nb_inplace_true_divide */ + delta_add, /* nb_add */ + delta_subtract, /* nb_subtract */ + delta_multiply, /* nb_multiply */ + delta_remainder, /* nb_remainder */ + delta_divmod, /* nb_divmod */ + 0, /* nb_power */ + (unaryfunc)delta_negative, /* nb_negative */ + (unaryfunc)delta_positive, /* nb_positive */ + (unaryfunc)delta_abs, /* nb_absolute */ + (inquiry)delta_bool, /* nb_bool */ + 0, /*nb_invert*/ + 0, /*nb_lshift*/ + 0, /*nb_rshift*/ + 0, /*nb_and*/ + 0, /*nb_xor*/ + 0, /*nb_or*/ + 0, /*nb_int*/ + 0, /*nb_reserved*/ + 0, /*nb_float*/ + 0, /*nb_inplace_add*/ + 0, /*nb_inplace_subtract*/ + 0, /*nb_inplace_multiply*/ + 0, /*nb_inplace_remainder*/ + 0, /*nb_inplace_power*/ + 0, /*nb_inplace_lshift*/ + 0, /*nb_inplace_rshift*/ + 0, /*nb_inplace_and*/ + 0, /*nb_inplace_xor*/ + 0, /*nb_inplace_or*/ + delta_divide, /* nb_floor_divide */ + delta_truedivide, /* nb_true_divide */ + 0, /* nb_inplace_floor_divide */ + 0, /* nb_inplace_true_divide */ }; static PyTypeObject PyDateTime_DeltaType = { - PyVarObject_HEAD_INIT(NULL, 0) - "datetime.timedelta", /* tp_name */ - sizeof(PyDateTime_Delta), /* tp_basicsize */ - 0, /* tp_itemsize */ - 0, /* tp_dealloc */ - 0, /* tp_print */ - 0, /* tp_getattr */ - 0, /* tp_setattr */ - 0, /* tp_reserved */ - (reprfunc)delta_repr, /* tp_repr */ - &delta_as_number, /* tp_as_number */ - 0, /* tp_as_sequence */ - 0, /* tp_as_mapping */ - (hashfunc)delta_hash, /* tp_hash */ - 0, /* tp_call */ - (reprfunc)delta_str, /* tp_str */ - PyObject_GenericGetAttr, /* tp_getattro */ - 0, /* tp_setattro */ - 0, /* tp_as_buffer */ - Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */ - delta_doc, /* tp_doc */ - 0, /* tp_traverse */ - 0, /* tp_clear */ - delta_richcompare, /* tp_richcompare */ - 0, /* tp_weaklistoffset */ - 0, /* tp_iter */ - 0, /* tp_iternext */ - delta_methods, /* tp_methods */ - delta_members, /* tp_members */ - 0, /* tp_getset */ - 0, /* tp_base */ - 0, /* tp_dict */ - 0, /* tp_descr_get */ - 0, /* tp_descr_set */ - 0, /* tp_dictoffset */ - 0, /* tp_init */ - 0, /* tp_alloc */ - delta_new, /* tp_new */ - 0, /* tp_free */ + PyVarObject_HEAD_INIT(NULL, 0) + "datetime.timedelta", /* tp_name */ + sizeof(PyDateTime_Delta), /* tp_basicsize */ + 0, /* tp_itemsize */ + 0, /* tp_dealloc */ + 0, /* tp_print */ + 0, /* tp_getattr */ + 0, /* tp_setattr */ + 0, /* tp_reserved */ + (reprfunc)delta_repr, /* tp_repr */ + &delta_as_number, /* tp_as_number */ + 0, /* tp_as_sequence */ + 0, /* tp_as_mapping */ + (hashfunc)delta_hash, /* tp_hash */ + 0, /* tp_call */ + (reprfunc)delta_str, /* tp_str */ + PyObject_GenericGetAttr, /* tp_getattro */ + 0, /* tp_setattro */ + 0, /* tp_as_buffer */ + Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */ + delta_doc, /* tp_doc */ + 0, /* tp_traverse */ + 0, /* tp_clear */ + delta_richcompare, /* tp_richcompare */ + 0, /* tp_weaklistoffset */ + 0, /* tp_iter */ + 0, /* tp_iternext */ + delta_methods, /* tp_methods */ + delta_members, /* tp_members */ + 0, /* tp_getset */ + 0, /* tp_base */ + 0, /* tp_dict */ + 0, /* tp_descr_get */ + 0, /* tp_descr_set */ + 0, /* tp_dictoffset */ + 0, /* tp_init */ + 0, /* tp_alloc */ + delta_new, /* tp_new */ + 0, /* tp_free */ }; /* @@ -2353,26 +2353,26 @@ static PyObject * date_year(PyDateTime_Date *self, void *unused) { - return PyLong_FromLong(GET_YEAR(self)); + return PyLong_FromLong(GET_YEAR(self)); } static PyObject * date_month(PyDateTime_Date *self, void *unused) { - return PyLong_FromLong(GET_MONTH(self)); + return PyLong_FromLong(GET_MONTH(self)); } static PyObject * date_day(PyDateTime_Date *self, void *unused) { - return PyLong_FromLong(GET_DAY(self)); + return PyLong_FromLong(GET_DAY(self)); } static PyGetSetDef date_getset[] = { - {"year", (getter)date_year}, - {"month", (getter)date_month}, - {"day", (getter)date_day}, - {NULL} + {"year", (getter)date_year}, + {"month", (getter)date_month}, + {"day", (getter)date_day}, + {NULL} }; /* Constructors. */ @@ -2382,60 +2382,60 @@ static PyObject * date_new(PyTypeObject *type, PyObject *args, PyObject *kw) { - PyObject *self = NULL; - PyObject *state; - int year; - int month; - int day; - - /* Check for invocation from pickle with __getstate__ state */ - if (PyTuple_GET_SIZE(args) == 1 && - PyBytes_Check(state = PyTuple_GET_ITEM(args, 0)) && - PyBytes_GET_SIZE(state) == _PyDateTime_DATE_DATASIZE && - MONTH_IS_SANE(PyBytes_AS_STRING(state)[2])) - { - PyDateTime_Date *me; - - me = (PyDateTime_Date *) (type->tp_alloc(type, 0)); - if (me != NULL) { - char *pdata = PyBytes_AS_STRING(state); - memcpy(me->data, pdata, _PyDateTime_DATE_DATASIZE); - me->hashcode = -1; - } - return (PyObject *)me; - } - - if (PyArg_ParseTupleAndKeywords(args, kw, "iii", date_kws, - &year, &month, &day)) { - if (check_date_args(year, month, day) < 0) - return NULL; - self = new_date_ex(year, month, day, type); - } - return self; + PyObject *self = NULL; + PyObject *state; + int year; + int month; + int day; + + /* Check for invocation from pickle with __getstate__ state */ + if (PyTuple_GET_SIZE(args) == 1 && + PyBytes_Check(state = PyTuple_GET_ITEM(args, 0)) && + PyBytes_GET_SIZE(state) == _PyDateTime_DATE_DATASIZE && + MONTH_IS_SANE(PyBytes_AS_STRING(state)[2])) + { + PyDateTime_Date *me; + + me = (PyDateTime_Date *) (type->tp_alloc(type, 0)); + if (me != NULL) { + char *pdata = PyBytes_AS_STRING(state); + memcpy(me->data, pdata, _PyDateTime_DATE_DATASIZE); + me->hashcode = -1; + } + return (PyObject *)me; + } + + if (PyArg_ParseTupleAndKeywords(args, kw, "iii", date_kws, + &year, &month, &day)) { + if (check_date_args(year, month, day) < 0) + return NULL; + self = new_date_ex(year, month, day, type); + } + return self; } /* Return new date from localtime(t). */ static PyObject * date_local_from_time_t(PyObject *cls, double ts) { - struct tm *tm; - time_t t; - PyObject *result = NULL; - - t = _PyTime_DoubleToTimet(ts); - if (t == (time_t)-1 && PyErr_Occurred()) - return NULL; - tm = localtime(&t); - if (tm) - result = PyObject_CallFunction(cls, "iii", - tm->tm_year + 1900, - tm->tm_mon + 1, - tm->tm_mday); - else - PyErr_SetString(PyExc_ValueError, - "timestamp out of range for " - "platform localtime() function"); - return result; + struct tm *tm; + time_t t; + PyObject *result = NULL; + + t = _PyTime_DoubleToTimet(ts); + if (t == (time_t)-1 && PyErr_Occurred()) + return NULL; + tm = localtime(&t); + if (tm) + result = PyObject_CallFunction(cls, "iii", + tm->tm_year + 1900, + tm->tm_mon + 1, + tm->tm_mday); + else + PyErr_SetString(PyExc_ValueError, + "timestamp out of range for " + "platform localtime() function"); + return result; } /* Return new date from current time. @@ -2446,34 +2446,34 @@ static PyObject * date_today(PyObject *cls, PyObject *dummy) { - PyObject *time; - PyObject *result; + PyObject *time; + PyObject *result; - time = time_time(); - if (time == NULL) - return NULL; - - /* Note well: today() is a class method, so this may not call - * date.fromtimestamp. For example, it may call - * datetime.fromtimestamp. That's why we need all the accuracy - * time.time() delivers; if someone were gonzo about optimization, - * date.today() could get away with plain C time(). - */ - result = PyObject_CallMethod(cls, "fromtimestamp", "O", time); - Py_DECREF(time); - return result; + time = time_time(); + if (time == NULL) + return NULL; + + /* Note well: today() is a class method, so this may not call + * date.fromtimestamp. For example, it may call + * datetime.fromtimestamp. That's why we need all the accuracy + * time.time() delivers; if someone were gonzo about optimization, + * date.today() could get away with plain C time(). + */ + result = PyObject_CallMethod(cls, "fromtimestamp", "O", time); + Py_DECREF(time); + return result; } /* Return new date from given timestamp (Python timestamp -- a double). */ static PyObject * date_fromtimestamp(PyObject *cls, PyObject *args) { - double timestamp; - PyObject *result = NULL; + double timestamp; + PyObject *result = NULL; - if (PyArg_ParseTuple(args, "d:fromtimestamp", ×tamp)) - result = date_local_from_time_t(cls, timestamp); - return result; + if (PyArg_ParseTuple(args, "d:fromtimestamp", ×tamp)) + result = date_local_from_time_t(cls, timestamp); + return result; } /* Return new date from proleptic Gregorian ordinal. Raises ValueError if @@ -2482,24 +2482,24 @@ static PyObject * date_fromordinal(PyObject *cls, PyObject *args) { - PyObject *result = NULL; - int ordinal; + PyObject *result = NULL; + int ordinal; - if (PyArg_ParseTuple(args, "i:fromordinal", &ordinal)) { - int year; - int month; - int day; - - if (ordinal < 1) - PyErr_SetString(PyExc_ValueError, "ordinal must be " - ">= 1"); - else { - ord_to_ymd(ordinal, &year, &month, &day); - result = PyObject_CallFunction(cls, "iii", - year, month, day); - } - } - return result; + if (PyArg_ParseTuple(args, "i:fromordinal", &ordinal)) { + int year; + int month; + int day; + + if (ordinal < 1) + PyErr_SetString(PyExc_ValueError, "ordinal must be " + ">= 1"); + else { + ord_to_ymd(ordinal, &year, &month, &day); + result = PyObject_CallFunction(cls, "iii", + year, month, day); + } + } + return result; } /* @@ -2512,74 +2512,74 @@ static PyObject * add_date_timedelta(PyDateTime_Date *date, PyDateTime_Delta *delta, int negate) { - PyObject *result = NULL; - int year = GET_YEAR(date); - int month = GET_MONTH(date); - int deltadays = GET_TD_DAYS(delta); - /* C-level overflow is impossible because |deltadays| < 1e9. */ - int day = GET_DAY(date) + (negate ? -deltadays : deltadays); - - if (normalize_date(&year, &month, &day) >= 0) - result = new_date(year, month, day); - return result; + PyObject *result = NULL; + int year = GET_YEAR(date); + int month = GET_MONTH(date); + int deltadays = GET_TD_DAYS(delta); + /* C-level overflow is impossible because |deltadays| < 1e9. */ + int day = GET_DAY(date) + (negate ? -deltadays : deltadays); + + if (normalize_date(&year, &month, &day) >= 0) + result = new_date(year, month, day); + return result; } static PyObject * date_add(PyObject *left, PyObject *right) { - if (PyDateTime_Check(left) || PyDateTime_Check(right)) { - Py_INCREF(Py_NotImplemented); - return Py_NotImplemented; - } - if (PyDate_Check(left)) { - /* date + ??? */ - if (PyDelta_Check(right)) - /* date + delta */ - return add_date_timedelta((PyDateTime_Date *) left, - (PyDateTime_Delta *) right, - 0); - } - else { - /* ??? + date - * 'right' must be one of us, or we wouldn't have been called - */ - if (PyDelta_Check(left)) - /* delta + date */ - return add_date_timedelta((PyDateTime_Date *) right, - (PyDateTime_Delta *) left, - 0); - } - Py_INCREF(Py_NotImplemented); - return Py_NotImplemented; + if (PyDateTime_Check(left) || PyDateTime_Check(right)) { + Py_INCREF(Py_NotImplemented); + return Py_NotImplemented; + } + if (PyDate_Check(left)) { + /* date + ??? */ + if (PyDelta_Check(right)) + /* date + delta */ + return add_date_timedelta((PyDateTime_Date *) left, + (PyDateTime_Delta *) right, + 0); + } + else { + /* ??? + date + * 'right' must be one of us, or we wouldn't have been called + */ + if (PyDelta_Check(left)) + /* delta + date */ + return add_date_timedelta((PyDateTime_Date *) right, + (PyDateTime_Delta *) left, + 0); + } + Py_INCREF(Py_NotImplemented); + return Py_NotImplemented; } static PyObject * date_subtract(PyObject *left, PyObject *right) { - if (PyDateTime_Check(left) || PyDateTime_Check(right)) { - Py_INCREF(Py_NotImplemented); - return Py_NotImplemented; - } - if (PyDate_Check(left)) { - if (PyDate_Check(right)) { - /* date - date */ - int left_ord = ymd_to_ord(GET_YEAR(left), - GET_MONTH(left), - GET_DAY(left)); - int right_ord = ymd_to_ord(GET_YEAR(right), - GET_MONTH(right), - GET_DAY(right)); - return new_delta(left_ord - right_ord, 0, 0, 0); - } - if (PyDelta_Check(right)) { - /* date - delta */ - return add_date_timedelta((PyDateTime_Date *) left, - (PyDateTime_Delta *) right, - 1); - } - } - Py_INCREF(Py_NotImplemented); - return Py_NotImplemented; + if (PyDateTime_Check(left) || PyDateTime_Check(right)) { + Py_INCREF(Py_NotImplemented); + return Py_NotImplemented; + } + if (PyDate_Check(left)) { + if (PyDate_Check(right)) { + /* date - date */ + int left_ord = ymd_to_ord(GET_YEAR(left), + GET_MONTH(left), + GET_DAY(left)); + int right_ord = ymd_to_ord(GET_YEAR(right), + GET_MONTH(right), + GET_DAY(right)); + return new_delta(left_ord - right_ord, 0, 0, 0); + } + if (PyDelta_Check(right)) { + /* date - delta */ + return add_date_timedelta((PyDateTime_Date *) left, + (PyDateTime_Delta *) right, + 1); + } + } + Py_INCREF(Py_NotImplemented); + return Py_NotImplemented; } @@ -2588,69 +2588,69 @@ static PyObject * date_repr(PyDateTime_Date *self) { - return PyUnicode_FromFormat("%s(%d, %d, %d)", - Py_TYPE(self)->tp_name, - GET_YEAR(self), GET_MONTH(self), GET_DAY(self)); + return PyUnicode_FromFormat("%s(%d, %d, %d)", + Py_TYPE(self)->tp_name, + GET_YEAR(self), GET_MONTH(self), GET_DAY(self)); } static PyObject * date_isoformat(PyDateTime_Date *self) { - return PyUnicode_FromFormat("%04d-%02d-%02d", - GET_YEAR(self), GET_MONTH(self), GET_DAY(self)); + return PyUnicode_FromFormat("%04d-%02d-%02d", + GET_YEAR(self), GET_MONTH(self), GET_DAY(self)); } /* str() calls the appropriate isoformat() method. */ static PyObject * date_str(PyDateTime_Date *self) { - return PyObject_CallMethod((PyObject *)self, "isoformat", "()"); + return PyObject_CallMethod((PyObject *)self, "isoformat", "()"); } static PyObject * date_ctime(PyDateTime_Date *self) { - return format_ctime(self, 0, 0, 0); + return format_ctime(self, 0, 0, 0); } static PyObject * date_strftime(PyDateTime_Date *self, PyObject *args, PyObject *kw) { - /* This method can be inherited, and needs to call the - * timetuple() method appropriate to self's class. - */ - PyObject *result; - PyObject *tuple; - PyObject *format; - static char *keywords[] = {"format", NULL}; - - if (! PyArg_ParseTupleAndKeywords(args, kw, "U:strftime", keywords, - &format)) - return NULL; - - tuple = PyObject_CallMethod((PyObject *)self, "timetuple", "()"); - if (tuple == NULL) - return NULL; - result = wrap_strftime((PyObject *)self, format, tuple, - (PyObject *)self); - Py_DECREF(tuple); - return result; + /* This method can be inherited, and needs to call the + * timetuple() method appropriate to self's class. + */ + PyObject *result; + PyObject *tuple; + PyObject *format; + static char *keywords[] = {"format", NULL}; + + if (! PyArg_ParseTupleAndKeywords(args, kw, "U:strftime", keywords, + &format)) + return NULL; + + tuple = PyObject_CallMethod((PyObject *)self, "timetuple", "()"); + if (tuple == NULL) + return NULL; + result = wrap_strftime((PyObject *)self, format, tuple, + (PyObject *)self); + Py_DECREF(tuple); + return result; } static PyObject * date_format(PyDateTime_Date *self, PyObject *args) { - PyObject *format; + PyObject *format; - if (!PyArg_ParseTuple(args, "U:__format__", &format)) - return NULL; + if (!PyArg_ParseTuple(args, "U:__format__", &format)) + return NULL; - /* if the format is zero length, return str(self) */ - if (PyUnicode_GetSize(format) == 0) - return PyObject_Str((PyObject *)self); + /* if the format is zero length, return str(self) */ + if (PyUnicode_GetSize(format) == 0) + return PyObject_Str((PyObject *)self); - return PyObject_CallMethod((PyObject *)self, "strftime", "O", format); + return PyObject_CallMethod((PyObject *)self, "strftime", "O", format); } /* ISO methods. */ @@ -2658,31 +2658,31 @@ static PyObject * date_isoweekday(PyDateTime_Date *self) { - int dow = weekday(GET_YEAR(self), GET_MONTH(self), GET_DAY(self)); + int dow = weekday(GET_YEAR(self), GET_MONTH(self), GET_DAY(self)); - return PyLong_FromLong(dow + 1); + return PyLong_FromLong(dow + 1); } static PyObject * date_isocalendar(PyDateTime_Date *self) { - int year = GET_YEAR(self); - int week1_monday = iso_week1_monday(year); - int today = ymd_to_ord(year, GET_MONTH(self), GET_DAY(self)); - int week; - int day; - - week = divmod(today - week1_monday, 7, &day); - if (week < 0) { - --year; - week1_monday = iso_week1_monday(year); - week = divmod(today - week1_monday, 7, &day); - } - else if (week >= 52 && today >= iso_week1_monday(year + 1)) { - ++year; - week = 0; - } - return Py_BuildValue("iii", year, week + 1, day + 1); + int year = GET_YEAR(self); + int week1_monday = iso_week1_monday(year); + int today = ymd_to_ord(year, GET_MONTH(self), GET_DAY(self)); + int week; + int day; + + week = divmod(today - week1_monday, 7, &day); + if (week < 0) { + --year; + week1_monday = iso_week1_monday(year); + week = divmod(today - week1_monday, 7, &day); + } + else if (week >= 52 && today >= iso_week1_monday(year + 1)) { + ++year; + week = 0; + } + return Py_BuildValue("iii", year, week + 1, day + 1); } /* Miscellaneous methods. */ @@ -2690,65 +2690,65 @@ static PyObject * date_richcompare(PyObject *self, PyObject *other, int op) { - if (PyDate_Check(other)) { - int diff = memcmp(((PyDateTime_Date *)self)->data, - ((PyDateTime_Date *)other)->data, - _PyDateTime_DATE_DATASIZE); - return diff_to_bool(diff, op); - } - else { - Py_INCREF(Py_NotImplemented); - return Py_NotImplemented; - } + if (PyDate_Check(other)) { + int diff = memcmp(((PyDateTime_Date *)self)->data, + ((PyDateTime_Date *)other)->data, + _PyDateTime_DATE_DATASIZE); + return diff_to_bool(diff, op); + } + else { + Py_INCREF(Py_NotImplemented); + return Py_NotImplemented; + } } static PyObject * date_timetuple(PyDateTime_Date *self) { - return build_struct_time(GET_YEAR(self), - GET_MONTH(self), - GET_DAY(self), - 0, 0, 0, -1); + return build_struct_time(GET_YEAR(self), + GET_MONTH(self), + GET_DAY(self), + 0, 0, 0, -1); } static PyObject * date_replace(PyDateTime_Date *self, PyObject *args, PyObject *kw) { - PyObject *clone; - PyObject *tuple; - int year = GET_YEAR(self); - int month = GET_MONTH(self); - int day = GET_DAY(self); - - if (! PyArg_ParseTupleAndKeywords(args, kw, "|iii:replace", date_kws, - &year, &month, &day)) - return NULL; - tuple = Py_BuildValue("iii", year, month, day); - if (tuple == NULL) - return NULL; - clone = date_new(Py_TYPE(self), tuple, NULL); - Py_DECREF(tuple); - return clone; + PyObject *clone; + PyObject *tuple; + int year = GET_YEAR(self); + int month = GET_MONTH(self); + int day = GET_DAY(self); + + if (! PyArg_ParseTupleAndKeywords(args, kw, "|iii:replace", date_kws, + &year, &month, &day)) + return NULL; + tuple = Py_BuildValue("iii", year, month, day); + if (tuple == NULL) + return NULL; + clone = date_new(Py_TYPE(self), tuple, NULL); + Py_DECREF(tuple); + return clone; } /* - Borrowed from stringobject.c, originally it was string_hash() + Borrowed from stringobject.c, originally it was string_hash() */ static long generic_hash(unsigned char *data, int len) { - register unsigned char *p; - register long x; + register unsigned char *p; + register long x; - p = (unsigned char *) data; - x = *p << 7; - while (--len >= 0) - x = (1000003*x) ^ *p++; - x ^= len; - if (x == -1) - x = -2; + p = (unsigned char *) data; + x = *p << 7; + while (--len >= 0) + x = (1000003*x) ^ *p++; + x ^= len; + if (x == -1) + x = -2; - return x; + return x; } @@ -2757,26 +2757,26 @@ static long date_hash(PyDateTime_Date *self) { - if (self->hashcode == -1) - self->hashcode = generic_hash( - (unsigned char *)self->data, _PyDateTime_DATE_DATASIZE); + if (self->hashcode == -1) + self->hashcode = generic_hash( + (unsigned char *)self->data, _PyDateTime_DATE_DATASIZE); - return self->hashcode; + return self->hashcode; } static PyObject * date_toordinal(PyDateTime_Date *self) { - return PyLong_FromLong(ymd_to_ord(GET_YEAR(self), GET_MONTH(self), - GET_DAY(self))); + return PyLong_FromLong(ymd_to_ord(GET_YEAR(self), GET_MONTH(self), + GET_DAY(self))); } static PyObject * date_weekday(PyDateTime_Date *self) { - int dow = weekday(GET_YEAR(self), GET_MONTH(self), GET_DAY(self)); + int dow = weekday(GET_YEAR(self), GET_MONTH(self), GET_DAY(self)); - return PyLong_FromLong(dow); + return PyLong_FromLong(dow); } /* Pickle support, a simple use of __reduce__. */ @@ -2785,134 +2785,134 @@ static PyObject * date_getstate(PyDateTime_Date *self) { - PyObject* field; - field = PyBytes_FromStringAndSize((char*)self->data, - _PyDateTime_DATE_DATASIZE); - return Py_BuildValue("(N)", field); + PyObject* field; + field = PyBytes_FromStringAndSize((char*)self->data, + _PyDateTime_DATE_DATASIZE); + return Py_BuildValue("(N)", field); } static PyObject * date_reduce(PyDateTime_Date *self, PyObject *arg) { - return Py_BuildValue("(ON)", Py_TYPE(self), date_getstate(self)); + return Py_BuildValue("(ON)", Py_TYPE(self), date_getstate(self)); } static PyMethodDef date_methods[] = { - /* Class methods: */ + /* Class methods: */ - {"fromtimestamp", (PyCFunction)date_fromtimestamp, METH_VARARGS | - METH_CLASS, - PyDoc_STR("timestamp -> local date from a POSIX timestamp (like " - "time.time()).")}, + {"fromtimestamp", (PyCFunction)date_fromtimestamp, METH_VARARGS | + METH_CLASS, + PyDoc_STR("timestamp -> local date from a POSIX timestamp (like " + "time.time()).")}, - {"fromordinal", (PyCFunction)date_fromordinal, METH_VARARGS | - METH_CLASS, - PyDoc_STR("int -> date corresponding to a proleptic Gregorian " - "ordinal.")}, + {"fromordinal", (PyCFunction)date_fromordinal, METH_VARARGS | + METH_CLASS, + PyDoc_STR("int -> date corresponding to a proleptic Gregorian " + "ordinal.")}, - {"today", (PyCFunction)date_today, METH_NOARGS | METH_CLASS, - PyDoc_STR("Current date or datetime: same as " - "self.__class__.fromtimestamp(time.time()).")}, + {"today", (PyCFunction)date_today, METH_NOARGS | METH_CLASS, + PyDoc_STR("Current date or datetime: same as " + "self.__class__.fromtimestamp(time.time()).")}, - /* Instance methods: */ + /* Instance methods: */ - {"ctime", (PyCFunction)date_ctime, METH_NOARGS, - PyDoc_STR("Return ctime() style string.")}, + {"ctime", (PyCFunction)date_ctime, METH_NOARGS, + PyDoc_STR("Return ctime() style string.")}, - {"strftime", (PyCFunction)date_strftime, METH_VARARGS | METH_KEYWORDS, - PyDoc_STR("format -> strftime() style string.")}, + {"strftime", (PyCFunction)date_strftime, METH_VARARGS | METH_KEYWORDS, + PyDoc_STR("format -> strftime() style string.")}, - {"__format__", (PyCFunction)date_format, METH_VARARGS, - PyDoc_STR("Formats self with strftime.")}, + {"__format__", (PyCFunction)date_format, METH_VARARGS, + PyDoc_STR("Formats self with strftime.")}, - {"timetuple", (PyCFunction)date_timetuple, METH_NOARGS, - PyDoc_STR("Return time tuple, compatible with time.localtime().")}, + {"timetuple", (PyCFunction)date_timetuple, METH_NOARGS, + PyDoc_STR("Return time tuple, compatible with time.localtime().")}, - {"isocalendar", (PyCFunction)date_isocalendar, METH_NOARGS, - PyDoc_STR("Return a 3-tuple containing ISO year, week number, and " - "weekday.")}, + {"isocalendar", (PyCFunction)date_isocalendar, METH_NOARGS, + PyDoc_STR("Return a 3-tuple containing ISO year, week number, and " + "weekday.")}, - {"isoformat", (PyCFunction)date_isoformat, METH_NOARGS, - PyDoc_STR("Return string in ISO 8601 format, YYYY-MM-DD.")}, + {"isoformat", (PyCFunction)date_isoformat, METH_NOARGS, + PyDoc_STR("Return string in ISO 8601 format, YYYY-MM-DD.")}, - {"isoweekday", (PyCFunction)date_isoweekday, METH_NOARGS, - PyDoc_STR("Return the day of the week represented by the date.\n" - "Monday == 1 ... Sunday == 7")}, + {"isoweekday", (PyCFunction)date_isoweekday, METH_NOARGS, + PyDoc_STR("Return the day of the week represented by the date.\n" + "Monday == 1 ... Sunday == 7")}, - {"toordinal", (PyCFunction)date_toordinal, METH_NOARGS, - PyDoc_STR("Return proleptic Gregorian ordinal. January 1 of year " - "1 is day 1.")}, + {"toordinal", (PyCFunction)date_toordinal, METH_NOARGS, + PyDoc_STR("Return proleptic Gregorian ordinal. January 1 of year " + "1 is day 1.")}, - {"weekday", (PyCFunction)date_weekday, METH_NOARGS, - PyDoc_STR("Return the day of the week represented by the date.\n" - "Monday == 0 ... Sunday == 6")}, + {"weekday", (PyCFunction)date_weekday, METH_NOARGS, + PyDoc_STR("Return the day of the week represented by the date.\n" + "Monday == 0 ... Sunday == 6")}, - {"replace", (PyCFunction)date_replace, METH_VARARGS | METH_KEYWORDS, - PyDoc_STR("Return date with new specified fields.")}, + {"replace", (PyCFunction)date_replace, METH_VARARGS | METH_KEYWORDS, + PyDoc_STR("Return date with new specified fields.")}, - {"__reduce__", (PyCFunction)date_reduce, METH_NOARGS, - PyDoc_STR("__reduce__() -> (cls, state)")}, + {"__reduce__", (PyCFunction)date_reduce, METH_NOARGS, + PyDoc_STR("__reduce__() -> (cls, state)")}, - {NULL, NULL} + {NULL, NULL} }; static char date_doc[] = PyDoc_STR("date(year, month, day) --> date object"); static PyNumberMethods date_as_number = { - date_add, /* nb_add */ - date_subtract, /* nb_subtract */ - 0, /* nb_multiply */ - 0, /* nb_remainder */ - 0, /* nb_divmod */ - 0, /* nb_power */ - 0, /* nb_negative */ - 0, /* nb_positive */ - 0, /* nb_absolute */ - 0, /* nb_bool */ + date_add, /* nb_add */ + date_subtract, /* nb_subtract */ + 0, /* nb_multiply */ + 0, /* nb_remainder */ + 0, /* nb_divmod */ + 0, /* nb_power */ + 0, /* nb_negative */ + 0, /* nb_positive */ + 0, /* nb_absolute */ + 0, /* nb_bool */ }; static PyTypeObject PyDateTime_DateType = { - PyVarObject_HEAD_INIT(NULL, 0) - "datetime.date", /* tp_name */ - sizeof(PyDateTime_Date), /* tp_basicsize */ - 0, /* tp_itemsize */ - 0, /* tp_dealloc */ - 0, /* tp_print */ - 0, /* tp_getattr */ - 0, /* tp_setattr */ - 0, /* tp_reserved */ - (reprfunc)date_repr, /* tp_repr */ - &date_as_number, /* tp_as_number */ - 0, /* tp_as_sequence */ - 0, /* tp_as_mapping */ - (hashfunc)date_hash, /* tp_hash */ - 0, /* tp_call */ - (reprfunc)date_str, /* tp_str */ - PyObject_GenericGetAttr, /* tp_getattro */ - 0, /* tp_setattro */ - 0, /* tp_as_buffer */ - Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */ - date_doc, /* tp_doc */ - 0, /* tp_traverse */ - 0, /* tp_clear */ - date_richcompare, /* tp_richcompare */ - 0, /* tp_weaklistoffset */ - 0, /* tp_iter */ - 0, /* tp_iternext */ - date_methods, /* tp_methods */ - 0, /* tp_members */ - date_getset, /* tp_getset */ - 0, /* tp_base */ - 0, /* tp_dict */ - 0, /* tp_descr_get */ - 0, /* tp_descr_set */ - 0, /* tp_dictoffset */ - 0, /* tp_init */ - 0, /* tp_alloc */ - date_new, /* tp_new */ - 0, /* tp_free */ + PyVarObject_HEAD_INIT(NULL, 0) + "datetime.date", /* tp_name */ + sizeof(PyDateTime_Date), /* tp_basicsize */ + 0, /* tp_itemsize */ + 0, /* tp_dealloc */ + 0, /* tp_print */ + 0, /* tp_getattr */ + 0, /* tp_setattr */ + 0, /* tp_reserved */ + (reprfunc)date_repr, /* tp_repr */ + &date_as_number, /* tp_as_number */ + 0, /* tp_as_sequence */ + 0, /* tp_as_mapping */ + (hashfunc)date_hash, /* tp_hash */ + 0, /* tp_call */ + (reprfunc)date_str, /* tp_str */ + PyObject_GenericGetAttr, /* tp_getattro */ + 0, /* tp_setattro */ + 0, /* tp_as_buffer */ + Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */ + date_doc, /* tp_doc */ + 0, /* tp_traverse */ + 0, /* tp_clear */ + date_richcompare, /* tp_richcompare */ + 0, /* tp_weaklistoffset */ + 0, /* tp_iter */ + 0, /* tp_iternext */ + date_methods, /* tp_methods */ + 0, /* tp_members */ + date_getset, /* tp_getset */ + 0, /* tp_base */ + 0, /* tp_dict */ + 0, /* tp_descr_get */ + 0, /* tp_descr_set */ + 0, /* tp_dictoffset */ + 0, /* tp_init */ + 0, /* tp_alloc */ + date_new, /* tp_new */ + 0, /* tp_free */ }; /* @@ -2935,10 +2935,10 @@ static PyObject * tzinfo_nogo(const char* methodname) { - PyErr_Format(PyExc_NotImplementedError, - "a tzinfo subclass must implement %s()", - methodname); - return NULL; + PyErr_Format(PyExc_NotImplementedError, + "a tzinfo subclass must implement %s()", + methodname); + return NULL; } /* Methods. A subclass must implement these. */ @@ -2946,101 +2946,101 @@ static PyObject * tzinfo_tzname(PyDateTime_TZInfo *self, PyObject *dt) { - return tzinfo_nogo("tzname"); + return tzinfo_nogo("tzname"); } static PyObject * tzinfo_utcoffset(PyDateTime_TZInfo *self, PyObject *dt) { - return tzinfo_nogo("utcoffset"); + return tzinfo_nogo("utcoffset"); } static PyObject * tzinfo_dst(PyDateTime_TZInfo *self, PyObject *dt) { - return tzinfo_nogo("dst"); + return tzinfo_nogo("dst"); } static PyObject * tzinfo_fromutc(PyDateTime_TZInfo *self, PyDateTime_DateTime *dt) { - int y, m, d, hh, mm, ss, us; + int y, m, d, hh, mm, ss, us; - PyObject *result; - int off, dst; - int none; - int delta; - - if (! PyDateTime_Check(dt)) { - PyErr_SetString(PyExc_TypeError, - "fromutc: argument must be a datetime"); - return NULL; - } - if (! HASTZINFO(dt) || dt->tzinfo != (PyObject *)self) { - PyErr_SetString(PyExc_ValueError, "fromutc: dt.tzinfo " - "is not self"); - return NULL; - } - - off = call_utcoffset(dt->tzinfo, (PyObject *)dt, &none); - if (off == -1 && PyErr_Occurred()) - return NULL; - if (none) { - PyErr_SetString(PyExc_ValueError, "fromutc: non-None " - "utcoffset() result required"); - return NULL; - } - - dst = call_dst(dt->tzinfo, (PyObject *)dt, &none); - if (dst == -1 && PyErr_Occurred()) - return NULL; - if (none) { - PyErr_SetString(PyExc_ValueError, "fromutc: non-None " - "dst() result required"); - return NULL; - } - - y = GET_YEAR(dt); - m = GET_MONTH(dt); - d = GET_DAY(dt); - hh = DATE_GET_HOUR(dt); - mm = DATE_GET_MINUTE(dt); - ss = DATE_GET_SECOND(dt); - us = DATE_GET_MICROSECOND(dt); - - delta = off - dst; - mm += delta; - if ((mm < 0 || mm >= 60) && - normalize_datetime(&y, &m, &d, &hh, &mm, &ss, &us) < 0) - return NULL; - result = new_datetime(y, m, d, hh, mm, ss, us, dt->tzinfo); - if (result == NULL) - return result; - - dst = call_dst(dt->tzinfo, result, &none); - if (dst == -1 && PyErr_Occurred()) - goto Fail; - if (none) - goto Inconsistent; - if (dst == 0) - return result; - - mm += dst; - if ((mm < 0 || mm >= 60) && - normalize_datetime(&y, &m, &d, &hh, &mm, &ss, &us) < 0) - goto Fail; - Py_DECREF(result); - result = new_datetime(y, m, d, hh, mm, ss, us, dt->tzinfo); - return result; + PyObject *result; + int off, dst; + int none; + int delta; + + if (! PyDateTime_Check(dt)) { + PyErr_SetString(PyExc_TypeError, + "fromutc: argument must be a datetime"); + return NULL; + } + if (! HASTZINFO(dt) || dt->tzinfo != (PyObject *)self) { + PyErr_SetString(PyExc_ValueError, "fromutc: dt.tzinfo " + "is not self"); + return NULL; + } + + off = call_utcoffset(dt->tzinfo, (PyObject *)dt, &none); + if (off == -1 && PyErr_Occurred()) + return NULL; + if (none) { + PyErr_SetString(PyExc_ValueError, "fromutc: non-None " + "utcoffset() result required"); + return NULL; + } + + dst = call_dst(dt->tzinfo, (PyObject *)dt, &none); + if (dst == -1 && PyErr_Occurred()) + return NULL; + if (none) { + PyErr_SetString(PyExc_ValueError, "fromutc: non-None " + "dst() result required"); + return NULL; + } + + y = GET_YEAR(dt); + m = GET_MONTH(dt); + d = GET_DAY(dt); + hh = DATE_GET_HOUR(dt); + mm = DATE_GET_MINUTE(dt); + ss = DATE_GET_SECOND(dt); + us = DATE_GET_MICROSECOND(dt); + + delta = off - dst; + mm += delta; + if ((mm < 0 || mm >= 60) && + normalize_datetime(&y, &m, &d, &hh, &mm, &ss, &us) < 0) + return NULL; + result = new_datetime(y, m, d, hh, mm, ss, us, dt->tzinfo); + if (result == NULL) + return result; + + dst = call_dst(dt->tzinfo, result, &none); + if (dst == -1 && PyErr_Occurred()) + goto Fail; + if (none) + goto Inconsistent; + if (dst == 0) + return result; + + mm += dst; + if ((mm < 0 || mm >= 60) && + normalize_datetime(&y, &m, &d, &hh, &mm, &ss, &us) < 0) + goto Fail; + Py_DECREF(result); + result = new_datetime(y, m, d, hh, mm, ss, us, dt->tzinfo); + return result; Inconsistent: - PyErr_SetString(PyExc_ValueError, "fromutc: tz.dst() gave" - "inconsistent results; cannot convert"); + PyErr_SetString(PyExc_ValueError, "fromutc: tz.dst() gave" + "inconsistent results; cannot convert"); - /* fall thru to failure */ + /* fall thru to failure */ Fail: - Py_DECREF(result); - return NULL; + Py_DECREF(result); + return NULL; } /* @@ -3051,122 +3051,122 @@ static PyObject * tzinfo_reduce(PyObject *self) { - PyObject *args, *state, *tmp; - PyObject *getinitargs, *getstate; + PyObject *args, *state, *tmp; + PyObject *getinitargs, *getstate; - tmp = PyTuple_New(0); - if (tmp == NULL) - return NULL; - - getinitargs = PyObject_GetAttrString(self, "__getinitargs__"); - if (getinitargs != NULL) { - args = PyObject_CallObject(getinitargs, tmp); - Py_DECREF(getinitargs); - if (args == NULL) { - Py_DECREF(tmp); - return NULL; - } - } - else { - PyErr_Clear(); - args = tmp; - Py_INCREF(args); - } - - getstate = PyObject_GetAttrString(self, "__getstate__"); - if (getstate != NULL) { - state = PyObject_CallObject(getstate, tmp); - Py_DECREF(getstate); - if (state == NULL) { - Py_DECREF(args); - Py_DECREF(tmp); - return NULL; - } - } - else { - PyObject **dictptr; - PyErr_Clear(); - state = Py_None; - dictptr = _PyObject_GetDictPtr(self); - if (dictptr && *dictptr && PyDict_Size(*dictptr)) - state = *dictptr; - Py_INCREF(state); - } - - Py_DECREF(tmp); - - if (state == Py_None) { - Py_DECREF(state); - return Py_BuildValue("(ON)", Py_TYPE(self), args); - } - else - return Py_BuildValue("(ONN)", Py_TYPE(self), args, state); + tmp = PyTuple_New(0); + if (tmp == NULL) + return NULL; + + getinitargs = PyObject_GetAttrString(self, "__getinitargs__"); + if (getinitargs != NULL) { + args = PyObject_CallObject(getinitargs, tmp); + Py_DECREF(getinitargs); + if (args == NULL) { + Py_DECREF(tmp); + return NULL; + } + } + else { + PyErr_Clear(); + args = tmp; + Py_INCREF(args); + } + + getstate = PyObject_GetAttrString(self, "__getstate__"); + if (getstate != NULL) { + state = PyObject_CallObject(getstate, tmp); + Py_DECREF(getstate); + if (state == NULL) { + Py_DECREF(args); + Py_DECREF(tmp); + return NULL; + } + } + else { + PyObject **dictptr; + PyErr_Clear(); + state = Py_None; + dictptr = _PyObject_GetDictPtr(self); + if (dictptr && *dictptr && PyDict_Size(*dictptr)) + state = *dictptr; + Py_INCREF(state); + } + + Py_DECREF(tmp); + + if (state == Py_None) { + Py_DECREF(state); + return Py_BuildValue("(ON)", Py_TYPE(self), args); + } + else + return Py_BuildValue("(ONN)", Py_TYPE(self), args, state); } static PyMethodDef tzinfo_methods[] = { - {"tzname", (PyCFunction)tzinfo_tzname, METH_O, - PyDoc_STR("datetime -> string name of time zone.")}, + {"tzname", (PyCFunction)tzinfo_tzname, METH_O, + PyDoc_STR("datetime -> string name of time zone.")}, - {"utcoffset", (PyCFunction)tzinfo_utcoffset, METH_O, - PyDoc_STR("datetime -> minutes east of UTC (negative for " - "west of UTC).")}, + {"utcoffset", (PyCFunction)tzinfo_utcoffset, METH_O, + PyDoc_STR("datetime -> minutes east of UTC (negative for " + "west of UTC).")}, - {"dst", (PyCFunction)tzinfo_dst, METH_O, - PyDoc_STR("datetime -> DST offset in minutes east of UTC.")}, + {"dst", (PyCFunction)tzinfo_dst, METH_O, + PyDoc_STR("datetime -> DST offset in minutes east of UTC.")}, - {"fromutc", (PyCFunction)tzinfo_fromutc, METH_O, - PyDoc_STR("datetime in UTC -> datetime in local time.")}, + {"fromutc", (PyCFunction)tzinfo_fromutc, METH_O, + PyDoc_STR("datetime in UTC -> datetime in local time.")}, - {"__reduce__", (PyCFunction)tzinfo_reduce, METH_NOARGS, - PyDoc_STR("-> (cls, state)")}, + {"__reduce__", (PyCFunction)tzinfo_reduce, METH_NOARGS, + PyDoc_STR("-> (cls, state)")}, - {NULL, NULL} + {NULL, NULL} }; static char tzinfo_doc[] = PyDoc_STR("Abstract base class for time zone info objects."); static PyTypeObject PyDateTime_TZInfoType = { - PyVarObject_HEAD_INIT(NULL, 0) - "datetime.tzinfo", /* tp_name */ - sizeof(PyDateTime_TZInfo), /* tp_basicsize */ - 0, /* tp_itemsize */ - 0, /* 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_BASETYPE, /* tp_flags */ - tzinfo_doc, /* tp_doc */ - 0, /* tp_traverse */ - 0, /* tp_clear */ - 0, /* tp_richcompare */ - 0, /* tp_weaklistoffset */ - 0, /* tp_iter */ - 0, /* tp_iternext */ - tzinfo_methods, /* tp_methods */ - 0, /* tp_members */ - 0, /* tp_getset */ - 0, /* tp_base */ - 0, /* tp_dict */ - 0, /* tp_descr_get */ - 0, /* tp_descr_set */ - 0, /* tp_dictoffset */ - 0, /* tp_init */ - 0, /* tp_alloc */ - PyType_GenericNew, /* tp_new */ - 0, /* tp_free */ + PyVarObject_HEAD_INIT(NULL, 0) + "datetime.tzinfo", /* tp_name */ + sizeof(PyDateTime_TZInfo), /* tp_basicsize */ + 0, /* tp_itemsize */ + 0, /* 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_BASETYPE, /* tp_flags */ + tzinfo_doc, /* tp_doc */ + 0, /* tp_traverse */ + 0, /* tp_clear */ + 0, /* tp_richcompare */ + 0, /* tp_weaklistoffset */ + 0, /* tp_iter */ + 0, /* tp_iternext */ + tzinfo_methods, /* tp_methods */ + 0, /* tp_members */ + 0, /* tp_getset */ + 0, /* tp_base */ + 0, /* tp_dict */ + 0, /* tp_descr_get */ + 0, /* tp_descr_set */ + 0, /* tp_dictoffset */ + 0, /* tp_init */ + 0, /* tp_alloc */ + PyType_GenericNew, /* tp_new */ + 0, /* tp_free */ }; /* @@ -3179,43 +3179,43 @@ static PyObject * time_hour(PyDateTime_Time *self, void *unused) { - return PyLong_FromLong(TIME_GET_HOUR(self)); + return PyLong_FromLong(TIME_GET_HOUR(self)); } static PyObject * time_minute(PyDateTime_Time *self, void *unused) { - return PyLong_FromLong(TIME_GET_MINUTE(self)); + return PyLong_FromLong(TIME_GET_MINUTE(self)); } /* The name time_second conflicted with some platform header file. */ static PyObject * py_time_second(PyDateTime_Time *self, void *unused) { - return PyLong_FromLong(TIME_GET_SECOND(self)); + return PyLong_FromLong(TIME_GET_SECOND(self)); } static PyObject * time_microsecond(PyDateTime_Time *self, void *unused) { - return PyLong_FromLong(TIME_GET_MICROSECOND(self)); + return PyLong_FromLong(TIME_GET_MICROSECOND(self)); } static PyObject * time_tzinfo(PyDateTime_Time *self, void *unused) { - PyObject *result = HASTZINFO(self) ? self->tzinfo : Py_None; - Py_INCREF(result); - return result; + PyObject *result = HASTZINFO(self) ? self->tzinfo : Py_None; + Py_INCREF(result); + return result; } static PyGetSetDef time_getset[] = { - {"hour", (getter)time_hour}, - {"minute", (getter)time_minute}, - {"second", (getter)py_time_second}, - {"microsecond", (getter)time_microsecond}, - {"tzinfo", (getter)time_tzinfo}, - {NULL} + {"hour", (getter)time_hour}, + {"minute", (getter)time_minute}, + {"second", (getter)py_time_second}, + {"microsecond", (getter)time_microsecond}, + {"tzinfo", (getter)time_tzinfo}, + {NULL} }; /* @@ -3223,64 +3223,64 @@ */ static char *time_kws[] = {"hour", "minute", "second", "microsecond", - "tzinfo", NULL}; + "tzinfo", NULL}; static PyObject * time_new(PyTypeObject *type, PyObject *args, PyObject *kw) { - PyObject *self = NULL; - PyObject *state; - int hour = 0; - int minute = 0; - int second = 0; - int usecond = 0; - PyObject *tzinfo = Py_None; - - /* Check for invocation from pickle with __getstate__ state */ - if (PyTuple_GET_SIZE(args) >= 1 && - PyTuple_GET_SIZE(args) <= 2 && - PyBytes_Check(state = PyTuple_GET_ITEM(args, 0)) && - PyBytes_GET_SIZE(state) == _PyDateTime_TIME_DATASIZE && - ((unsigned char) (PyBytes_AS_STRING(state)[0])) < 24) - { - PyDateTime_Time *me; - char aware; - - if (PyTuple_GET_SIZE(args) == 2) { - tzinfo = PyTuple_GET_ITEM(args, 1); - if (check_tzinfo_subclass(tzinfo) < 0) { - PyErr_SetString(PyExc_TypeError, "bad " - "tzinfo state arg"); - return NULL; - } - } - aware = (char)(tzinfo != Py_None); - me = (PyDateTime_Time *) (type->tp_alloc(type, aware)); - if (me != NULL) { - char *pdata = PyBytes_AS_STRING(state); - - memcpy(me->data, pdata, _PyDateTime_TIME_DATASIZE); - me->hashcode = -1; - me->hastzinfo = aware; - if (aware) { - Py_INCREF(tzinfo); - me->tzinfo = tzinfo; - } - } - return (PyObject *)me; - } - - if (PyArg_ParseTupleAndKeywords(args, kw, "|iiiiO", time_kws, - &hour, &minute, &second, &usecond, - &tzinfo)) { - if (check_time_args(hour, minute, second, usecond) < 0) - return NULL; - if (check_tzinfo_subclass(tzinfo) < 0) - return NULL; - self = new_time_ex(hour, minute, second, usecond, tzinfo, - type); - } - return self; + PyObject *self = NULL; + PyObject *state; + int hour = 0; + int minute = 0; + int second = 0; + int usecond = 0; + PyObject *tzinfo = Py_None; + + /* Check for invocation from pickle with __getstate__ state */ + if (PyTuple_GET_SIZE(args) >= 1 && + PyTuple_GET_SIZE(args) <= 2 && + PyBytes_Check(state = PyTuple_GET_ITEM(args, 0)) && + PyBytes_GET_SIZE(state) == _PyDateTime_TIME_DATASIZE && + ((unsigned char) (PyBytes_AS_STRING(state)[0])) < 24) + { + PyDateTime_Time *me; + char aware; + + if (PyTuple_GET_SIZE(args) == 2) { + tzinfo = PyTuple_GET_ITEM(args, 1); + if (check_tzinfo_subclass(tzinfo) < 0) { + PyErr_SetString(PyExc_TypeError, "bad " + "tzinfo state arg"); + return NULL; + } + } + aware = (char)(tzinfo != Py_None); + me = (PyDateTime_Time *) (type->tp_alloc(type, aware)); + if (me != NULL) { + char *pdata = PyBytes_AS_STRING(state); + + memcpy(me->data, pdata, _PyDateTime_TIME_DATASIZE); + me->hashcode = -1; + me->hastzinfo = aware; + if (aware) { + Py_INCREF(tzinfo); + me->tzinfo = tzinfo; + } + } + return (PyObject *)me; + } + + if (PyArg_ParseTupleAndKeywords(args, kw, "|iiiiO", time_kws, + &hour, &minute, &second, &usecond, + &tzinfo)) { + if (check_time_args(hour, minute, second, usecond) < 0) + return NULL; + if (check_tzinfo_subclass(tzinfo) < 0) + return NULL; + self = new_time_ex(hour, minute, second, usecond, tzinfo, + type); + } + return self; } /* @@ -3290,10 +3290,10 @@ static void time_dealloc(PyDateTime_Time *self) { - if (HASTZINFO(self)) { - Py_XDECREF(self->tzinfo); - } - Py_TYPE(self)->tp_free((PyObject *)self); + if (HASTZINFO(self)) { + Py_XDECREF(self->tzinfo); + } + Py_TYPE(self)->tp_free((PyObject *)self); } /* @@ -3303,20 +3303,20 @@ /* These are all METH_NOARGS, so don't need to check the arglist. */ static PyObject * time_utcoffset(PyDateTime_Time *self, PyObject *unused) { - return offset_as_timedelta(HASTZINFO(self) ? self->tzinfo : Py_None, - "utcoffset", Py_None); + return offset_as_timedelta(HASTZINFO(self) ? self->tzinfo : Py_None, + "utcoffset", Py_None); } static PyObject * time_dst(PyDateTime_Time *self, PyObject *unused) { - return offset_as_timedelta(HASTZINFO(self) ? self->tzinfo : Py_None, - "dst", Py_None); + return offset_as_timedelta(HASTZINFO(self) ? self->tzinfo : Py_None, + "dst", Py_None); } static PyObject * time_tzname(PyDateTime_Time *self, PyObject *unused) { - return call_tzname(HASTZINFO(self) ? self->tzinfo : Py_None, - Py_None); + return call_tzname(HASTZINFO(self) ? self->tzinfo : Py_None, + Py_None); } /* @@ -3326,93 +3326,93 @@ static PyObject * time_repr(PyDateTime_Time *self) { - const char *type_name = Py_TYPE(self)->tp_name; - int h = TIME_GET_HOUR(self); - int m = TIME_GET_MINUTE(self); - int s = TIME_GET_SECOND(self); - int us = TIME_GET_MICROSECOND(self); - PyObject *result = NULL; - - if (us) - result = PyUnicode_FromFormat("%s(%d, %d, %d, %d)", - type_name, h, m, s, us); - else if (s) - result = PyUnicode_FromFormat("%s(%d, %d, %d)", - type_name, h, m, s); - else - result = PyUnicode_FromFormat("%s(%d, %d)", type_name, h, m); - if (result != NULL && HASTZINFO(self)) - result = append_keyword_tzinfo(result, self->tzinfo); - return result; + const char *type_name = Py_TYPE(self)->tp_name; + int h = TIME_GET_HOUR(self); + int m = TIME_GET_MINUTE(self); + int s = TIME_GET_SECOND(self); + int us = TIME_GET_MICROSECOND(self); + PyObject *result = NULL; + + if (us) + result = PyUnicode_FromFormat("%s(%d, %d, %d, %d)", + type_name, h, m, s, us); + else if (s) + result = PyUnicode_FromFormat("%s(%d, %d, %d)", + type_name, h, m, s); + else + result = PyUnicode_FromFormat("%s(%d, %d)", type_name, h, m); + if (result != NULL && HASTZINFO(self)) + result = append_keyword_tzinfo(result, self->tzinfo); + return result; } static PyObject * time_str(PyDateTime_Time *self) { - return PyObject_CallMethod((PyObject *)self, "isoformat", "()"); + return PyObject_CallMethod((PyObject *)self, "isoformat", "()"); } static PyObject * time_isoformat(PyDateTime_Time *self, PyObject *unused) { - char buf[100]; - PyObject *result; - int us = TIME_GET_MICROSECOND(self);; - - if (us) - result = PyUnicode_FromFormat("%02d:%02d:%02d.%06d", - TIME_GET_HOUR(self), - TIME_GET_MINUTE(self), - TIME_GET_SECOND(self), - us); - else - result = PyUnicode_FromFormat("%02d:%02d:%02d", - TIME_GET_HOUR(self), - TIME_GET_MINUTE(self), - TIME_GET_SECOND(self)); - - if (result == NULL || ! HASTZINFO(self) || self->tzinfo == Py_None) - return result; - - /* We need to append the UTC offset. */ - if (format_utcoffset(buf, sizeof(buf), ":", self->tzinfo, - Py_None) < 0) { - Py_DECREF(result); - return NULL; - } - PyUnicode_AppendAndDel(&result, PyUnicode_FromString(buf)); - return result; + char buf[100]; + PyObject *result; + int us = TIME_GET_MICROSECOND(self);; + + if (us) + result = PyUnicode_FromFormat("%02d:%02d:%02d.%06d", + TIME_GET_HOUR(self), + TIME_GET_MINUTE(self), + TIME_GET_SECOND(self), + us); + else + result = PyUnicode_FromFormat("%02d:%02d:%02d", + TIME_GET_HOUR(self), + TIME_GET_MINUTE(self), + TIME_GET_SECOND(self)); + + if (result == NULL || ! HASTZINFO(self) || self->tzinfo == Py_None) + return result; + + /* We need to append the UTC offset. */ + if (format_utcoffset(buf, sizeof(buf), ":", self->tzinfo, + Py_None) < 0) { + Py_DECREF(result); + return NULL; + } + PyUnicode_AppendAndDel(&result, PyUnicode_FromString(buf)); + return result; } static PyObject * time_strftime(PyDateTime_Time *self, PyObject *args, PyObject *kw) { - PyObject *result; - PyObject *tuple; - PyObject *format; - static char *keywords[] = {"format", NULL}; - - if (! PyArg_ParseTupleAndKeywords(args, kw, "U:strftime", keywords, - &format)) - return NULL; - - /* Python's strftime does insane things with the year part of the - * timetuple. The year is forced to (the otherwise nonsensical) - * 1900 to worm around that. - */ - tuple = Py_BuildValue("iiiiiiiii", - 1900, 1, 1, /* year, month, day */ - TIME_GET_HOUR(self), - TIME_GET_MINUTE(self), - TIME_GET_SECOND(self), - 0, 1, -1); /* weekday, daynum, dst */ - if (tuple == NULL) - return NULL; - assert(PyTuple_Size(tuple) == 9); - result = wrap_strftime((PyObject *)self, format, tuple, - Py_None); - Py_DECREF(tuple); - return result; + PyObject *result; + PyObject *tuple; + PyObject *format; + static char *keywords[] = {"format", NULL}; + + if (! PyArg_ParseTupleAndKeywords(args, kw, "U:strftime", keywords, + &format)) + return NULL; + + /* Python's strftime does insane things with the year part of the + * timetuple. The year is forced to (the otherwise nonsensical) + * 1900 to worm around that. + */ + tuple = Py_BuildValue("iiiiiiiii", + 1900, 1, 1, /* year, month, day */ + TIME_GET_HOUR(self), + TIME_GET_MINUTE(self), + TIME_GET_SECOND(self), + 0, 1, -1); /* weekday, daynum, dst */ + if (tuple == NULL) + return NULL; + assert(PyTuple_Size(tuple) == 9); + result = wrap_strftime((PyObject *)self, format, tuple, + Py_None); + Py_DECREF(tuple); + return result; } /* @@ -3422,144 +3422,144 @@ static PyObject * time_richcompare(PyObject *self, PyObject *other, int op) { - int diff; - naivety n1, n2; - int offset1, offset2; - - if (! PyTime_Check(other)) { - Py_INCREF(Py_NotImplemented); - return Py_NotImplemented; - } - if (classify_two_utcoffsets(self, &offset1, &n1, Py_None, - other, &offset2, &n2, Py_None) < 0) - return NULL; - assert(n1 != OFFSET_UNKNOWN && n2 != OFFSET_UNKNOWN); - /* If they're both naive, or both aware and have the same offsets, - * we get off cheap. Note that if they're both naive, offset1 == - * offset2 == 0 at this point. - */ - if (n1 == n2 && offset1 == offset2) { - diff = memcmp(((PyDateTime_Time *)self)->data, - ((PyDateTime_Time *)other)->data, - _PyDateTime_TIME_DATASIZE); - return diff_to_bool(diff, op); - } - - if (n1 == OFFSET_AWARE && n2 == OFFSET_AWARE) { - assert(offset1 != offset2); /* else last "if" handled it */ - /* Convert everything except microseconds to seconds. These - * can't overflow (no more than the # of seconds in 2 days). - */ - offset1 = TIME_GET_HOUR(self) * 3600 + - (TIME_GET_MINUTE(self) - offset1) * 60 + - TIME_GET_SECOND(self); - offset2 = TIME_GET_HOUR(other) * 3600 + - (TIME_GET_MINUTE(other) - offset2) * 60 + - TIME_GET_SECOND(other); - diff = offset1 - offset2; - if (diff == 0) - diff = TIME_GET_MICROSECOND(self) - - TIME_GET_MICROSECOND(other); - return diff_to_bool(diff, op); - } - - assert(n1 != n2); - PyErr_SetString(PyExc_TypeError, - "can't compare offset-naive and " - "offset-aware times"); - return NULL; + int diff; + naivety n1, n2; + int offset1, offset2; + + if (! PyTime_Check(other)) { + Py_INCREF(Py_NotImplemented); + return Py_NotImplemented; + } + if (classify_two_utcoffsets(self, &offset1, &n1, Py_None, + other, &offset2, &n2, Py_None) < 0) + return NULL; + assert(n1 != OFFSET_UNKNOWN && n2 != OFFSET_UNKNOWN); + /* If they're both naive, or both aware and have the same offsets, + * we get off cheap. Note that if they're both naive, offset1 == + * offset2 == 0 at this point. + */ + if (n1 == n2 && offset1 == offset2) { + diff = memcmp(((PyDateTime_Time *)self)->data, + ((PyDateTime_Time *)other)->data, + _PyDateTime_TIME_DATASIZE); + return diff_to_bool(diff, op); + } + + if (n1 == OFFSET_AWARE && n2 == OFFSET_AWARE) { + assert(offset1 != offset2); /* else last "if" handled it */ + /* Convert everything except microseconds to seconds. These + * can't overflow (no more than the # of seconds in 2 days). + */ + offset1 = TIME_GET_HOUR(self) * 3600 + + (TIME_GET_MINUTE(self) - offset1) * 60 + + TIME_GET_SECOND(self); + offset2 = TIME_GET_HOUR(other) * 3600 + + (TIME_GET_MINUTE(other) - offset2) * 60 + + TIME_GET_SECOND(other); + diff = offset1 - offset2; + if (diff == 0) + diff = TIME_GET_MICROSECOND(self) - + TIME_GET_MICROSECOND(other); + return diff_to_bool(diff, op); + } + + assert(n1 != n2); + PyErr_SetString(PyExc_TypeError, + "can't compare offset-naive and " + "offset-aware times"); + return NULL; } static long time_hash(PyDateTime_Time *self) { - if (self->hashcode == -1) { - naivety n; - int offset; - PyObject *temp; - - n = classify_utcoffset((PyObject *)self, Py_None, &offset); - assert(n != OFFSET_UNKNOWN); - if (n == OFFSET_ERROR) - return -1; - - /* Reduce this to a hash of another object. */ - if (offset == 0) { - self->hashcode = generic_hash( - (unsigned char *)self->data, _PyDateTime_TIME_DATASIZE); - return self->hashcode; - } - else { - int hour; - int minute; - - assert(n == OFFSET_AWARE); - assert(HASTZINFO(self)); - hour = divmod(TIME_GET_HOUR(self) * 60 + - TIME_GET_MINUTE(self) - offset, - 60, - &minute); - if (0 <= hour && hour < 24) - temp = new_time(hour, minute, - TIME_GET_SECOND(self), - TIME_GET_MICROSECOND(self), - Py_None); - else - temp = Py_BuildValue("iiii", - hour, minute, - TIME_GET_SECOND(self), - TIME_GET_MICROSECOND(self)); - } - if (temp != NULL) { - self->hashcode = PyObject_Hash(temp); - Py_DECREF(temp); - } - } - return self->hashcode; + if (self->hashcode == -1) { + naivety n; + int offset; + PyObject *temp; + + n = classify_utcoffset((PyObject *)self, Py_None, &offset); + assert(n != OFFSET_UNKNOWN); + if (n == OFFSET_ERROR) + return -1; + + /* Reduce this to a hash of another object. */ + if (offset == 0) { + self->hashcode = generic_hash( + (unsigned char *)self->data, _PyDateTime_TIME_DATASIZE); + return self->hashcode; + } + else { + int hour; + int minute; + + assert(n == OFFSET_AWARE); + assert(HASTZINFO(self)); + hour = divmod(TIME_GET_HOUR(self) * 60 + + TIME_GET_MINUTE(self) - offset, + 60, + &minute); + if (0 <= hour && hour < 24) + temp = new_time(hour, minute, + TIME_GET_SECOND(self), + TIME_GET_MICROSECOND(self), + Py_None); + else + temp = Py_BuildValue("iiii", + hour, minute, + TIME_GET_SECOND(self), + TIME_GET_MICROSECOND(self)); + } + if (temp != NULL) { + self->hashcode = PyObject_Hash(temp); + Py_DECREF(temp); + } + } + return self->hashcode; } static PyObject * time_replace(PyDateTime_Time *self, PyObject *args, PyObject *kw) { - PyObject *clone; - PyObject *tuple; - int hh = TIME_GET_HOUR(self); - int mm = TIME_GET_MINUTE(self); - int ss = TIME_GET_SECOND(self); - int us = TIME_GET_MICROSECOND(self); - PyObject *tzinfo = HASTZINFO(self) ? self->tzinfo : Py_None; - - if (! PyArg_ParseTupleAndKeywords(args, kw, "|iiiiO:replace", - time_kws, - &hh, &mm, &ss, &us, &tzinfo)) - return NULL; - tuple = Py_BuildValue("iiiiO", hh, mm, ss, us, tzinfo); - if (tuple == NULL) - return NULL; - clone = time_new(Py_TYPE(self), tuple, NULL); - Py_DECREF(tuple); - return clone; + PyObject *clone; + PyObject *tuple; + int hh = TIME_GET_HOUR(self); + int mm = TIME_GET_MINUTE(self); + int ss = TIME_GET_SECOND(self); + int us = TIME_GET_MICROSECOND(self); + PyObject *tzinfo = HASTZINFO(self) ? self->tzinfo : Py_None; + + if (! PyArg_ParseTupleAndKeywords(args, kw, "|iiiiO:replace", + time_kws, + &hh, &mm, &ss, &us, &tzinfo)) + return NULL; + tuple = Py_BuildValue("iiiiO", hh, mm, ss, us, tzinfo); + if (tuple == NULL) + return NULL; + clone = time_new(Py_TYPE(self), tuple, NULL); + Py_DECREF(tuple); + return clone; } static int time_bool(PyDateTime_Time *self) { - int offset; - int none; + int offset; + int none; - if (TIME_GET_SECOND(self) || TIME_GET_MICROSECOND(self)) { - /* Since utcoffset is in whole minutes, nothing can - * alter the conclusion that this is nonzero. - */ - return 1; - } - offset = 0; - if (HASTZINFO(self) && self->tzinfo != Py_None) { - offset = call_utcoffset(self->tzinfo, Py_None, &none); - if (offset == -1 && PyErr_Occurred()) - return -1; - } - return (TIME_GET_MINUTE(self) - offset + TIME_GET_HOUR(self)*60) != 0; + if (TIME_GET_SECOND(self) || TIME_GET_MICROSECOND(self)) { + /* Since utcoffset is in whole minutes, nothing can + * alter the conclusion that this is nonzero. + */ + return 1; + } + offset = 0; + if (HASTZINFO(self) && self->tzinfo != Py_None) { + offset = call_utcoffset(self->tzinfo, Py_None, &none); + if (offset == -1 && PyErr_Occurred()) + return -1; + } + return (TIME_GET_MINUTE(self) - offset + TIME_GET_HOUR(self)*60) != 0; } /* Pickle support, a simple use of __reduce__. */ @@ -3572,55 +3572,55 @@ static PyObject * time_getstate(PyDateTime_Time *self) { - PyObject *basestate; - PyObject *result = NULL; + PyObject *basestate; + PyObject *result = NULL; - basestate = PyBytes_FromStringAndSize((char *)self->data, - _PyDateTime_TIME_DATASIZE); - if (basestate != NULL) { - if (! HASTZINFO(self) || self->tzinfo == Py_None) - result = PyTuple_Pack(1, basestate); - else - result = PyTuple_Pack(2, basestate, self->tzinfo); - Py_DECREF(basestate); - } - return result; + basestate = PyBytes_FromStringAndSize((char *)self->data, + _PyDateTime_TIME_DATASIZE); + if (basestate != NULL) { + if (! HASTZINFO(self) || self->tzinfo == Py_None) + result = PyTuple_Pack(1, basestate); + else + result = PyTuple_Pack(2, basestate, self->tzinfo); + Py_DECREF(basestate); + } + return result; } static PyObject * time_reduce(PyDateTime_Time *self, PyObject *arg) { - return Py_BuildValue("(ON)", Py_TYPE(self), time_getstate(self)); + return Py_BuildValue("(ON)", Py_TYPE(self), time_getstate(self)); } static PyMethodDef time_methods[] = { - {"isoformat", (PyCFunction)time_isoformat, METH_NOARGS, - PyDoc_STR("Return string in ISO 8601 format, HH:MM:SS[.mmmmmm]" - "[+HH:MM].")}, + {"isoformat", (PyCFunction)time_isoformat, METH_NOARGS, + PyDoc_STR("Return string in ISO 8601 format, HH:MM:SS[.mmmmmm]" + "[+HH:MM].")}, - {"strftime", (PyCFunction)time_strftime, METH_VARARGS | METH_KEYWORDS, - PyDoc_STR("format -> strftime() style string.")}, + {"strftime", (PyCFunction)time_strftime, METH_VARARGS | METH_KEYWORDS, + PyDoc_STR("format -> strftime() style string.")}, - {"__format__", (PyCFunction)date_format, METH_VARARGS, - PyDoc_STR("Formats self with strftime.")}, + {"__format__", (PyCFunction)date_format, METH_VARARGS, + PyDoc_STR("Formats self with strftime.")}, - {"utcoffset", (PyCFunction)time_utcoffset, METH_NOARGS, - PyDoc_STR("Return self.tzinfo.utcoffset(self).")}, + {"utcoffset", (PyCFunction)time_utcoffset, METH_NOARGS, + PyDoc_STR("Return self.tzinfo.utcoffset(self).")}, - {"tzname", (PyCFunction)time_tzname, METH_NOARGS, - PyDoc_STR("Return self.tzinfo.tzname(self).")}, + {"tzname", (PyCFunction)time_tzname, METH_NOARGS, + PyDoc_STR("Return self.tzinfo.tzname(self).")}, - {"dst", (PyCFunction)time_dst, METH_NOARGS, - PyDoc_STR("Return self.tzinfo.dst(self).")}, + {"dst", (PyCFunction)time_dst, METH_NOARGS, + PyDoc_STR("Return self.tzinfo.dst(self).")}, - {"replace", (PyCFunction)time_replace, METH_VARARGS | METH_KEYWORDS, - PyDoc_STR("Return time with new specified fields.")}, + {"replace", (PyCFunction)time_replace, METH_VARARGS | METH_KEYWORDS, + PyDoc_STR("Return time with new specified fields.")}, - {"__reduce__", (PyCFunction)time_reduce, METH_NOARGS, - PyDoc_STR("__reduce__() -> (cls, state)")}, + {"__reduce__", (PyCFunction)time_reduce, METH_NOARGS, + PyDoc_STR("__reduce__() -> (cls, state)")}, - {NULL, NULL} + {NULL, NULL} }; static char time_doc[] = @@ -3630,58 +3630,58 @@ a tzinfo subclass. The remaining arguments may be ints or longs.\n"); static PyNumberMethods time_as_number = { - 0, /* nb_add */ - 0, /* nb_subtract */ - 0, /* nb_multiply */ - 0, /* nb_remainder */ - 0, /* nb_divmod */ - 0, /* nb_power */ - 0, /* nb_negative */ - 0, /* nb_positive */ - 0, /* nb_absolute */ - (inquiry)time_bool, /* nb_bool */ + 0, /* nb_add */ + 0, /* nb_subtract */ + 0, /* nb_multiply */ + 0, /* nb_remainder */ + 0, /* nb_divmod */ + 0, /* nb_power */ + 0, /* nb_negative */ + 0, /* nb_positive */ + 0, /* nb_absolute */ + (inquiry)time_bool, /* nb_bool */ }; static PyTypeObject PyDateTime_TimeType = { - PyVarObject_HEAD_INIT(NULL, 0) - "datetime.time", /* tp_name */ - sizeof(PyDateTime_Time), /* tp_basicsize */ - 0, /* tp_itemsize */ - (destructor)time_dealloc, /* tp_dealloc */ - 0, /* tp_print */ - 0, /* tp_getattr */ - 0, /* tp_setattr */ - 0, /* tp_reserved */ - (reprfunc)time_repr, /* tp_repr */ - &time_as_number, /* tp_as_number */ - 0, /* tp_as_sequence */ - 0, /* tp_as_mapping */ - (hashfunc)time_hash, /* tp_hash */ - 0, /* tp_call */ - (reprfunc)time_str, /* tp_str */ - PyObject_GenericGetAttr, /* tp_getattro */ - 0, /* tp_setattro */ - 0, /* tp_as_buffer */ - Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */ - time_doc, /* tp_doc */ - 0, /* tp_traverse */ - 0, /* tp_clear */ - time_richcompare, /* tp_richcompare */ - 0, /* tp_weaklistoffset */ - 0, /* tp_iter */ - 0, /* tp_iternext */ - time_methods, /* tp_methods */ - 0, /* tp_members */ - time_getset, /* tp_getset */ - 0, /* tp_base */ - 0, /* tp_dict */ - 0, /* tp_descr_get */ - 0, /* tp_descr_set */ - 0, /* tp_dictoffset */ - 0, /* tp_init */ - time_alloc, /* tp_alloc */ - time_new, /* tp_new */ - 0, /* tp_free */ + PyVarObject_HEAD_INIT(NULL, 0) + "datetime.time", /* tp_name */ + sizeof(PyDateTime_Time), /* tp_basicsize */ + 0, /* tp_itemsize */ + (destructor)time_dealloc, /* tp_dealloc */ + 0, /* tp_print */ + 0, /* tp_getattr */ + 0, /* tp_setattr */ + 0, /* tp_reserved */ + (reprfunc)time_repr, /* tp_repr */ + &time_as_number, /* tp_as_number */ + 0, /* tp_as_sequence */ + 0, /* tp_as_mapping */ + (hashfunc)time_hash, /* tp_hash */ + 0, /* tp_call */ + (reprfunc)time_str, /* tp_str */ + PyObject_GenericGetAttr, /* tp_getattro */ + 0, /* tp_setattro */ + 0, /* tp_as_buffer */ + Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */ + time_doc, /* tp_doc */ + 0, /* tp_traverse */ + 0, /* tp_clear */ + time_richcompare, /* tp_richcompare */ + 0, /* tp_weaklistoffset */ + 0, /* tp_iter */ + 0, /* tp_iternext */ + time_methods, /* tp_methods */ + 0, /* tp_members */ + time_getset, /* tp_getset */ + 0, /* tp_base */ + 0, /* tp_dict */ + 0, /* tp_descr_get */ + 0, /* tp_descr_set */ + 0, /* tp_dictoffset */ + 0, /* tp_init */ + time_alloc, /* tp_alloc */ + time_new, /* tp_new */ + 0, /* tp_free */ }; /* @@ -3695,42 +3695,42 @@ static PyObject * datetime_hour(PyDateTime_DateTime *self, void *unused) { - return PyLong_FromLong(DATE_GET_HOUR(self)); + return PyLong_FromLong(DATE_GET_HOUR(self)); } static PyObject * datetime_minute(PyDateTime_DateTime *self, void *unused) { - return PyLong_FromLong(DATE_GET_MINUTE(self)); + return PyLong_FromLong(DATE_GET_MINUTE(self)); } static PyObject * datetime_second(PyDateTime_DateTime *self, void *unused) { - return PyLong_FromLong(DATE_GET_SECOND(self)); + return PyLong_FromLong(DATE_GET_SECOND(self)); } static PyObject * datetime_microsecond(PyDateTime_DateTime *self, void *unused) { - return PyLong_FromLong(DATE_GET_MICROSECOND(self)); + return PyLong_FromLong(DATE_GET_MICROSECOND(self)); } static PyObject * datetime_tzinfo(PyDateTime_DateTime *self, void *unused) { - PyObject *result = HASTZINFO(self) ? self->tzinfo : Py_None; - Py_INCREF(result); - return result; + PyObject *result = HASTZINFO(self) ? self->tzinfo : Py_None; + Py_INCREF(result); + return result; } static PyGetSetDef datetime_getset[] = { - {"hour", (getter)datetime_hour}, - {"minute", (getter)datetime_minute}, - {"second", (getter)datetime_second}, - {"microsecond", (getter)datetime_microsecond}, - {"tzinfo", (getter)datetime_tzinfo}, - {NULL} + {"hour", (getter)datetime_hour}, + {"minute", (getter)datetime_minute}, + {"second", (getter)datetime_second}, + {"microsecond", (getter)datetime_microsecond}, + {"tzinfo", (getter)datetime_tzinfo}, + {NULL} }; /* @@ -3738,72 +3738,72 @@ */ static char *datetime_kws[] = { - "year", "month", "day", "hour", "minute", "second", - "microsecond", "tzinfo", NULL + "year", "month", "day", "hour", "minute", "second", + "microsecond", "tzinfo", NULL }; static PyObject * datetime_new(PyTypeObject *type, PyObject *args, PyObject *kw) { - PyObject *self = NULL; - PyObject *state; - int year; - int month; - int day; - int hour = 0; - int minute = 0; - int second = 0; - int usecond = 0; - PyObject *tzinfo = Py_None; - - /* Check for invocation from pickle with __getstate__ state */ - if (PyTuple_GET_SIZE(args) >= 1 && - PyTuple_GET_SIZE(args) <= 2 && - PyBytes_Check(state = PyTuple_GET_ITEM(args, 0)) && - PyBytes_GET_SIZE(state) == _PyDateTime_DATETIME_DATASIZE && - MONTH_IS_SANE(PyBytes_AS_STRING(state)[2])) - { - PyDateTime_DateTime *me; - char aware; - - if (PyTuple_GET_SIZE(args) == 2) { - tzinfo = PyTuple_GET_ITEM(args, 1); - if (check_tzinfo_subclass(tzinfo) < 0) { - PyErr_SetString(PyExc_TypeError, "bad " - "tzinfo state arg"); - return NULL; - } - } - aware = (char)(tzinfo != Py_None); - me = (PyDateTime_DateTime *) (type->tp_alloc(type , aware)); - if (me != NULL) { - char *pdata = PyBytes_AS_STRING(state); - - memcpy(me->data, pdata, _PyDateTime_DATETIME_DATASIZE); - me->hashcode = -1; - me->hastzinfo = aware; - if (aware) { - Py_INCREF(tzinfo); - me->tzinfo = tzinfo; - } - } - return (PyObject *)me; - } - - if (PyArg_ParseTupleAndKeywords(args, kw, "iii|iiiiO", datetime_kws, - &year, &month, &day, &hour, &minute, - &second, &usecond, &tzinfo)) { - if (check_date_args(year, month, day) < 0) - return NULL; - if (check_time_args(hour, minute, second, usecond) < 0) - return NULL; - if (check_tzinfo_subclass(tzinfo) < 0) - return NULL; - self = new_datetime_ex(year, month, day, - hour, minute, second, usecond, - tzinfo, type); - } - return self; + PyObject *self = NULL; + PyObject *state; + int year; + int month; + int day; + int hour = 0; + int minute = 0; + int second = 0; + int usecond = 0; + PyObject *tzinfo = Py_None; + + /* Check for invocation from pickle with __getstate__ state */ + if (PyTuple_GET_SIZE(args) >= 1 && + PyTuple_GET_SIZE(args) <= 2 && + PyBytes_Check(state = PyTuple_GET_ITEM(args, 0)) && + PyBytes_GET_SIZE(state) == _PyDateTime_DATETIME_DATASIZE && + MONTH_IS_SANE(PyBytes_AS_STRING(state)[2])) + { + PyDateTime_DateTime *me; + char aware; + + if (PyTuple_GET_SIZE(args) == 2) { + tzinfo = PyTuple_GET_ITEM(args, 1); + if (check_tzinfo_subclass(tzinfo) < 0) { + PyErr_SetString(PyExc_TypeError, "bad " + "tzinfo state arg"); + return NULL; + } + } + aware = (char)(tzinfo != Py_None); + me = (PyDateTime_DateTime *) (type->tp_alloc(type , aware)); + if (me != NULL) { + char *pdata = PyBytes_AS_STRING(state); + + memcpy(me->data, pdata, _PyDateTime_DATETIME_DATASIZE); + me->hashcode = -1; + me->hastzinfo = aware; + if (aware) { + Py_INCREF(tzinfo); + me->tzinfo = tzinfo; + } + } + return (PyObject *)me; + } + + if (PyArg_ParseTupleAndKeywords(args, kw, "iii|iiiiO", datetime_kws, + &year, &month, &day, &hour, &minute, + &second, &usecond, &tzinfo)) { + if (check_date_args(year, month, day) < 0) + return NULL; + if (check_time_args(hour, minute, second, usecond) < 0) + return NULL; + if (check_tzinfo_subclass(tzinfo) < 0) + return NULL; + self = new_datetime_ex(year, month, day, + hour, minute, second, usecond, + tzinfo, type); + } + return self; } /* TM_FUNC is the shared type of localtime() and gmtime(). */ @@ -3815,36 +3815,36 @@ */ static PyObject * datetime_from_timet_and_us(PyObject *cls, TM_FUNC f, time_t timet, int us, - PyObject *tzinfo) + PyObject *tzinfo) { - struct tm *tm; - PyObject *result = NULL; + struct tm *tm; + PyObject *result = NULL; - tm = f(&timet); - if (tm) { - /* The platform localtime/gmtime may insert leap seconds, - * indicated by tm->tm_sec > 59. We don't care about them, - * except to the extent that passing them on to the datetime - * constructor would raise ValueError for a reason that - * made no sense to the user. - */ - if (tm->tm_sec > 59) - tm->tm_sec = 59; - result = PyObject_CallFunction(cls, "iiiiiiiO", - tm->tm_year + 1900, - tm->tm_mon + 1, - tm->tm_mday, - tm->tm_hour, - tm->tm_min, - tm->tm_sec, - us, - tzinfo); - } - else - PyErr_SetString(PyExc_ValueError, - "timestamp out of range for " - "platform localtime()/gmtime() function"); - return result; + tm = f(&timet); + if (tm) { + /* The platform localtime/gmtime may insert leap seconds, + * indicated by tm->tm_sec > 59. We don't care about them, + * except to the extent that passing them on to the datetime + * constructor would raise ValueError for a reason that + * made no sense to the user. + */ + if (tm->tm_sec > 59) + tm->tm_sec = 59; + result = PyObject_CallFunction(cls, "iiiiiiiO", + tm->tm_year + 1900, + tm->tm_mon + 1, + tm->tm_mday, + tm->tm_hour, + tm->tm_min, + tm->tm_sec, + us, + tzinfo); + } + else + PyErr_SetString(PyExc_ValueError, + "timestamp out of range for " + "platform localtime()/gmtime() function"); + return result; } /* Internal helper. @@ -3856,31 +3856,31 @@ */ static PyObject * datetime_from_timestamp(PyObject *cls, TM_FUNC f, double timestamp, - PyObject *tzinfo) + PyObject *tzinfo) { - time_t timet; - double fraction; - int us; - - timet = _PyTime_DoubleToTimet(timestamp); - if (timet == (time_t)-1 && PyErr_Occurred()) - return NULL; - fraction = timestamp - (double)timet; - us = (int)round_to_long(fraction * 1e6); - if (us < 0) { - /* Truncation towards zero is not what we wanted - for negative numbers (Python's mod semantics) */ - timet -= 1; - us += 1000000; - } - /* If timestamp is less than one microsecond smaller than a - * full second, round up. Otherwise, ValueErrors are raised - * for some floats. */ - if (us == 1000000) { - timet += 1; - us = 0; - } - return datetime_from_timet_and_us(cls, f, timet, us, tzinfo); + time_t timet; + double fraction; + int us; + + timet = _PyTime_DoubleToTimet(timestamp); + if (timet == (time_t)-1 && PyErr_Occurred()) + return NULL; + fraction = timestamp - (double)timet; + us = (int)round_to_long(fraction * 1e6); + if (us < 0) { + /* Truncation towards zero is not what we wanted + for negative numbers (Python's mod semantics) */ + timet -= 1; + us += 1000000; + } + /* If timestamp is less than one microsecond smaller than a + * full second, round up. Otherwise, ValueErrors are raised + * for some floats. */ + if (us == 1000000) { + timet += 1; + us = 0; + } + return datetime_from_timet_and_us(cls, f, timet, us, tzinfo); } /* Internal helper. @@ -3891,36 +3891,36 @@ datetime_best_possible(PyObject *cls, TM_FUNC f, PyObject *tzinfo) { #ifdef HAVE_GETTIMEOFDAY - struct timeval t; + struct timeval t; #ifdef GETTIMEOFDAY_NO_TZ - gettimeofday(&t); + gettimeofday(&t); #else - gettimeofday(&t, (struct timezone *)NULL); + gettimeofday(&t, (struct timezone *)NULL); #endif - return datetime_from_timet_and_us(cls, f, t.tv_sec, (int)t.tv_usec, - tzinfo); + return datetime_from_timet_and_us(cls, f, t.tv_sec, (int)t.tv_usec, + tzinfo); -#else /* ! HAVE_GETTIMEOFDAY */ - /* No flavor of gettimeofday exists on this platform. Python's - * time.time() does a lot of other platform tricks to get the - * best time it can on the platform, and we're not going to do - * better than that (if we could, the better code would belong - * in time.time()!) We're limited by the precision of a double, - * though. - */ - PyObject *time; - double dtime; - - time = time_time(); - if (time == NULL) - return NULL; - dtime = PyFloat_AsDouble(time); - Py_DECREF(time); - if (dtime == -1.0 && PyErr_Occurred()) - return NULL; - return datetime_from_timestamp(cls, f, dtime, tzinfo); -#endif /* ! HAVE_GETTIMEOFDAY */ +#else /* ! HAVE_GETTIMEOFDAY */ + /* No flavor of gettimeofday exists on this platform. Python's + * time.time() does a lot of other platform tricks to get the + * best time it can on the platform, and we're not going to do + * better than that (if we could, the better code would belong + * in time.time()!) We're limited by the precision of a double, + * though. + */ + PyObject *time; + double dtime; + + time = time_time(); + if (time == NULL) + return NULL; + dtime = PyFloat_AsDouble(time); + Py_DECREF(time); + if (dtime == -1.0 && PyErr_Occurred()) + return NULL; + return datetime_from_timestamp(cls, f, dtime, tzinfo); +#endif /* ! HAVE_GETTIMEOFDAY */ } /* Return best possible local time -- this isn't constrained by the @@ -3929,26 +3929,26 @@ static PyObject * datetime_now(PyObject *cls, PyObject *args, PyObject *kw) { - PyObject *self; - PyObject *tzinfo = Py_None; - static char *keywords[] = {"tz", NULL}; - - if (! PyArg_ParseTupleAndKeywords(args, kw, "|O:now", keywords, - &tzinfo)) - return NULL; - if (check_tzinfo_subclass(tzinfo) < 0) - return NULL; - - self = datetime_best_possible(cls, - tzinfo == Py_None ? localtime : gmtime, - tzinfo); - if (self != NULL && tzinfo != Py_None) { - /* Convert UTC to tzinfo's zone. */ - PyObject *temp = self; - self = PyObject_CallMethod(tzinfo, "fromutc", "O", self); - Py_DECREF(temp); - } - return self; + PyObject *self; + PyObject *tzinfo = Py_None; + static char *keywords[] = {"tz", NULL}; + + if (! PyArg_ParseTupleAndKeywords(args, kw, "|O:now", keywords, + &tzinfo)) + return NULL; + if (check_tzinfo_subclass(tzinfo) < 0) + return NULL; + + self = datetime_best_possible(cls, + tzinfo == Py_None ? localtime : gmtime, + tzinfo); + if (self != NULL && tzinfo != Py_None) { + /* Convert UTC to tzinfo's zone. */ + PyObject *temp = self; + self = PyObject_CallMethod(tzinfo, "fromutc", "O", self); + Py_DECREF(temp); + } + return self; } /* Return best possible UTC time -- this isn't constrained by the @@ -3957,155 +3957,155 @@ static PyObject * datetime_utcnow(PyObject *cls, PyObject *dummy) { - return datetime_best_possible(cls, gmtime, Py_None); + return datetime_best_possible(cls, gmtime, Py_None); } /* Return new local datetime from timestamp (Python timestamp -- a double). */ static PyObject * datetime_fromtimestamp(PyObject *cls, PyObject *args, PyObject *kw) { - PyObject *self; - double timestamp; - PyObject *tzinfo = Py_None; - static char *keywords[] = {"timestamp", "tz", NULL}; - - if (! PyArg_ParseTupleAndKeywords(args, kw, "d|O:fromtimestamp", - keywords, ×tamp, &tzinfo)) - return NULL; - if (check_tzinfo_subclass(tzinfo) < 0) - return NULL; - - self = datetime_from_timestamp(cls, - tzinfo == Py_None ? localtime : gmtime, - timestamp, - tzinfo); - if (self != NULL && tzinfo != Py_None) { - /* Convert UTC to tzinfo's zone. */ - PyObject *temp = self; - self = PyObject_CallMethod(tzinfo, "fromutc", "O", self); - Py_DECREF(temp); - } - return self; + PyObject *self; + double timestamp; + PyObject *tzinfo = Py_None; + static char *keywords[] = {"timestamp", "tz", NULL}; + + if (! PyArg_ParseTupleAndKeywords(args, kw, "d|O:fromtimestamp", + keywords, ×tamp, &tzinfo)) + return NULL; + if (check_tzinfo_subclass(tzinfo) < 0) + return NULL; + + self = datetime_from_timestamp(cls, + tzinfo == Py_None ? localtime : gmtime, + timestamp, + tzinfo); + if (self != NULL && tzinfo != Py_None) { + /* Convert UTC to tzinfo's zone. */ + PyObject *temp = self; + self = PyObject_CallMethod(tzinfo, "fromutc", "O", self); + Py_DECREF(temp); + } + return self; } /* Return new UTC datetime from timestamp (Python timestamp -- a double). */ static PyObject * datetime_utcfromtimestamp(PyObject *cls, PyObject *args) { - double timestamp; - PyObject *result = NULL; + double timestamp; + PyObject *result = NULL; - if (PyArg_ParseTuple(args, "d:utcfromtimestamp", ×tamp)) - result = datetime_from_timestamp(cls, gmtime, timestamp, - Py_None); - return result; + if (PyArg_ParseTuple(args, "d:utcfromtimestamp", ×tamp)) + result = datetime_from_timestamp(cls, gmtime, timestamp, + Py_None); + return result; } /* Return new datetime from time.strptime(). */ static PyObject * datetime_strptime(PyObject *cls, PyObject *args) { - static PyObject *module = NULL; - PyObject *result = NULL, *obj, *st = NULL, *frac = NULL; - const Py_UNICODE *string, *format; - - if (!PyArg_ParseTuple(args, "uu:strptime", &string, &format)) - return NULL; - - if (module == NULL && - (module = PyImport_ImportModuleNoBlock("_strptime")) == NULL) - return NULL; - - /* _strptime._strptime returns a two-element tuple. The first - element is a time.struct_time object. The second is the - microseconds (which are not defined for time.struct_time). */ - obj = PyObject_CallMethod(module, "_strptime", "uu", string, format); - if (obj != NULL) { - int i, good_timetuple = 1; - long int ia[7]; - if (PySequence_Check(obj) && PySequence_Size(obj) == 2) { - st = PySequence_GetItem(obj, 0); - frac = PySequence_GetItem(obj, 1); - if (st == NULL || frac == NULL) - good_timetuple = 0; - /* copy y/m/d/h/m/s values out of the - time.struct_time */ - if (good_timetuple && - PySequence_Check(st) && - PySequence_Size(st) >= 6) { - for (i=0; i < 6; i++) { - PyObject *p = PySequence_GetItem(st, i); - if (p == NULL) { - good_timetuple = 0; - break; - } - if (PyLong_Check(p)) - ia[i] = PyLong_AsLong(p); - else - good_timetuple = 0; - Py_DECREF(p); - } -/* if (PyLong_CheckExact(p)) { - ia[i] = PyLong_AsLongAndOverflow(p, &overflow); - if (overflow) - good_timetuple = 0; - } - else - good_timetuple = 0; - Py_DECREF(p); -*/ } - else - good_timetuple = 0; - /* follow that up with a little dose of microseconds */ - if (PyLong_Check(frac)) - ia[6] = PyLong_AsLong(frac); - else - good_timetuple = 0; - } - else - good_timetuple = 0; - if (good_timetuple) - result = PyObject_CallFunction(cls, "iiiiiii", - ia[0], ia[1], ia[2], - ia[3], ia[4], ia[5], - ia[6]); - else - PyErr_SetString(PyExc_ValueError, - "unexpected value from _strptime._strptime"); - } - Py_XDECREF(obj); - Py_XDECREF(st); - Py_XDECREF(frac); - return result; + static PyObject *module = NULL; + PyObject *result = NULL, *obj, *st = NULL, *frac = NULL; + const Py_UNICODE *string, *format; + + if (!PyArg_ParseTuple(args, "uu:strptime", &string, &format)) + return NULL; + + if (module == NULL && + (module = PyImport_ImportModuleNoBlock("_strptime")) == NULL) + return NULL; + + /* _strptime._strptime returns a two-element tuple. The first + element is a time.struct_time object. The second is the + microseconds (which are not defined for time.struct_time). */ + obj = PyObject_CallMethod(module, "_strptime", "uu", string, format); + if (obj != NULL) { + int i, good_timetuple = 1; + long int ia[7]; + if (PySequence_Check(obj) && PySequence_Size(obj) == 2) { + st = PySequence_GetItem(obj, 0); + frac = PySequence_GetItem(obj, 1); + if (st == NULL || frac == NULL) + good_timetuple = 0; + /* copy y/m/d/h/m/s values out of the + time.struct_time */ + if (good_timetuple && + PySequence_Check(st) && + PySequence_Size(st) >= 6) { + for (i=0; i < 6; i++) { + PyObject *p = PySequence_GetItem(st, i); + if (p == NULL) { + good_timetuple = 0; + break; + } + if (PyLong_Check(p)) + ia[i] = PyLong_AsLong(p); + else + good_timetuple = 0; + Py_DECREF(p); + } +/* if (PyLong_CheckExact(p)) { + ia[i] = PyLong_AsLongAndOverflow(p, &overflow); + if (overflow) + good_timetuple = 0; + } + else + good_timetuple = 0; + Py_DECREF(p); +*/ } + else + good_timetuple = 0; + /* follow that up with a little dose of microseconds */ + if (PyLong_Check(frac)) + ia[6] = PyLong_AsLong(frac); + else + good_timetuple = 0; + } + else + good_timetuple = 0; + if (good_timetuple) + result = PyObject_CallFunction(cls, "iiiiiii", + ia[0], ia[1], ia[2], + ia[3], ia[4], ia[5], + ia[6]); + else + PyErr_SetString(PyExc_ValueError, + "unexpected value from _strptime._strptime"); + } + Py_XDECREF(obj); + Py_XDECREF(st); + Py_XDECREF(frac); + return result; } /* Return new datetime from date/datetime and time arguments. */ static PyObject * datetime_combine(PyObject *cls, PyObject *args, PyObject *kw) { - static char *keywords[] = {"date", "time", NULL}; - PyObject *date; - PyObject *time; - PyObject *result = NULL; - - if (PyArg_ParseTupleAndKeywords(args, kw, "O!O!:combine", keywords, - &PyDateTime_DateType, &date, - &PyDateTime_TimeType, &time)) { - PyObject *tzinfo = Py_None; - - if (HASTZINFO(time)) - tzinfo = ((PyDateTime_Time *)time)->tzinfo; - result = PyObject_CallFunction(cls, "iiiiiiiO", - GET_YEAR(date), - GET_MONTH(date), - GET_DAY(date), - TIME_GET_HOUR(time), - TIME_GET_MINUTE(time), - TIME_GET_SECOND(time), - TIME_GET_MICROSECOND(time), - tzinfo); - } - return result; + static char *keywords[] = {"date", "time", NULL}; + PyObject *date; + PyObject *time; + PyObject *result = NULL; + + if (PyArg_ParseTupleAndKeywords(args, kw, "O!O!:combine", keywords, + &PyDateTime_DateType, &date, + &PyDateTime_TimeType, &time)) { + PyObject *tzinfo = Py_None; + + if (HASTZINFO(time)) + tzinfo = ((PyDateTime_Time *)time)->tzinfo; + result = PyObject_CallFunction(cls, "iiiiiiiO", + GET_YEAR(date), + GET_MONTH(date), + GET_DAY(date), + TIME_GET_HOUR(time), + TIME_GET_MINUTE(time), + TIME_GET_SECOND(time), + TIME_GET_MICROSECOND(time), + tzinfo); + } + return result; } /* @@ -4115,10 +4115,10 @@ static void datetime_dealloc(PyDateTime_DateTime *self) { - if (HASTZINFO(self)) { - Py_XDECREF(self->tzinfo); - } - Py_TYPE(self)->tp_free((PyObject *)self); + if (HASTZINFO(self)) { + Py_XDECREF(self->tzinfo); + } + Py_TYPE(self)->tp_free((PyObject *)self); } /* @@ -4128,20 +4128,20 @@ /* These are all METH_NOARGS, so don't need to check the arglist. */ static PyObject * datetime_utcoffset(PyDateTime_DateTime *self, PyObject *unused) { - return offset_as_timedelta(HASTZINFO(self) ? self->tzinfo : Py_None, - "utcoffset", (PyObject *)self); + return offset_as_timedelta(HASTZINFO(self) ? self->tzinfo : Py_None, + "utcoffset", (PyObject *)self); } static PyObject * datetime_dst(PyDateTime_DateTime *self, PyObject *unused) { - return offset_as_timedelta(HASTZINFO(self) ? self->tzinfo : Py_None, - "dst", (PyObject *)self); + return offset_as_timedelta(HASTZINFO(self) ? self->tzinfo : Py_None, + "dst", (PyObject *)self); } static PyObject * datetime_tzname(PyDateTime_DateTime *self, PyObject *unused) { - return call_tzname(HASTZINFO(self) ? self->tzinfo : Py_None, - (PyObject *)self); + return call_tzname(HASTZINFO(self) ? self->tzinfo : Py_None, + (PyObject *)self); } /* @@ -4153,112 +4153,112 @@ */ static PyObject * add_datetime_timedelta(PyDateTime_DateTime *date, PyDateTime_Delta *delta, - int factor) + int factor) { - /* Note that the C-level additions can't overflow, because of - * invariant bounds on the member values. - */ - int year = GET_YEAR(date); - int month = GET_MONTH(date); - int day = GET_DAY(date) + GET_TD_DAYS(delta) * factor; - int hour = DATE_GET_HOUR(date); - int minute = DATE_GET_MINUTE(date); - int second = DATE_GET_SECOND(date) + GET_TD_SECONDS(delta) * factor; - int microsecond = DATE_GET_MICROSECOND(date) + - GET_TD_MICROSECONDS(delta) * factor; - - assert(factor == 1 || factor == -1); - if (normalize_datetime(&year, &month, &day, - &hour, &minute, &second, µsecond) < 0) - return NULL; - else - return new_datetime(year, month, day, - hour, minute, second, microsecond, - HASTZINFO(date) ? date->tzinfo : Py_None); + /* Note that the C-level additions can't overflow, because of + * invariant bounds on the member values. + */ + int year = GET_YEAR(date); + int month = GET_MONTH(date); + int day = GET_DAY(date) + GET_TD_DAYS(delta) * factor; + int hour = DATE_GET_HOUR(date); + int minute = DATE_GET_MINUTE(date); + int second = DATE_GET_SECOND(date) + GET_TD_SECONDS(delta) * factor; + int microsecond = DATE_GET_MICROSECOND(date) + + GET_TD_MICROSECONDS(delta) * factor; + + assert(factor == 1 || factor == -1); + if (normalize_datetime(&year, &month, &day, + &hour, &minute, &second, µsecond) < 0) + return NULL; + else + return new_datetime(year, month, day, + hour, minute, second, microsecond, + HASTZINFO(date) ? date->tzinfo : Py_None); } static PyObject * datetime_add(PyObject *left, PyObject *right) { - if (PyDateTime_Check(left)) { - /* datetime + ??? */ - if (PyDelta_Check(right)) - /* datetime + delta */ - return add_datetime_timedelta( - (PyDateTime_DateTime *)left, - (PyDateTime_Delta *)right, - 1); - } - else if (PyDelta_Check(left)) { - /* delta + datetime */ - return add_datetime_timedelta((PyDateTime_DateTime *) right, - (PyDateTime_Delta *) left, - 1); - } - Py_INCREF(Py_NotImplemented); - return Py_NotImplemented; + if (PyDateTime_Check(left)) { + /* datetime + ??? */ + if (PyDelta_Check(right)) + /* datetime + delta */ + return add_datetime_timedelta( + (PyDateTime_DateTime *)left, + (PyDateTime_Delta *)right, + 1); + } + else if (PyDelta_Check(left)) { + /* delta + datetime */ + return add_datetime_timedelta((PyDateTime_DateTime *) right, + (PyDateTime_Delta *) left, + 1); + } + Py_INCREF(Py_NotImplemented); + return Py_NotImplemented; } static PyObject * datetime_subtract(PyObject *left, PyObject *right) { - PyObject *result = Py_NotImplemented; + PyObject *result = Py_NotImplemented; - if (PyDateTime_Check(left)) { - /* datetime - ??? */ - if (PyDateTime_Check(right)) { - /* datetime - datetime */ - naivety n1, n2; - int offset1, offset2; - int delta_d, delta_s, delta_us; - - if (classify_two_utcoffsets(left, &offset1, &n1, left, - right, &offset2, &n2, - right) < 0) - return NULL; - assert(n1 != OFFSET_UNKNOWN && n2 != OFFSET_UNKNOWN); - if (n1 != n2) { - PyErr_SetString(PyExc_TypeError, - "can't subtract offset-naive and " - "offset-aware datetimes"); - return NULL; - } - delta_d = ymd_to_ord(GET_YEAR(left), - GET_MONTH(left), - GET_DAY(left)) - - ymd_to_ord(GET_YEAR(right), - GET_MONTH(right), - GET_DAY(right)); - /* These can't overflow, since the values are - * normalized. At most this gives the number of - * seconds in one day. - */ - delta_s = (DATE_GET_HOUR(left) - - DATE_GET_HOUR(right)) * 3600 + - (DATE_GET_MINUTE(left) - - DATE_GET_MINUTE(right)) * 60 + - (DATE_GET_SECOND(left) - - DATE_GET_SECOND(right)); - delta_us = DATE_GET_MICROSECOND(left) - - DATE_GET_MICROSECOND(right); - /* (left - offset1) - (right - offset2) = - * (left - right) + (offset2 - offset1) - */ - delta_s += (offset2 - offset1) * 60; - result = new_delta(delta_d, delta_s, delta_us, 1); - } - else if (PyDelta_Check(right)) { - /* datetime - delta */ - result = add_datetime_timedelta( - (PyDateTime_DateTime *)left, - (PyDateTime_Delta *)right, - -1); - } - } - - if (result == Py_NotImplemented) - Py_INCREF(result); - return result; + if (PyDateTime_Check(left)) { + /* datetime - ??? */ + if (PyDateTime_Check(right)) { + /* datetime - datetime */ + naivety n1, n2; + int offset1, offset2; + int delta_d, delta_s, delta_us; + + if (classify_two_utcoffsets(left, &offset1, &n1, left, + right, &offset2, &n2, + right) < 0) + return NULL; + assert(n1 != OFFSET_UNKNOWN && n2 != OFFSET_UNKNOWN); + if (n1 != n2) { + PyErr_SetString(PyExc_TypeError, + "can't subtract offset-naive and " + "offset-aware datetimes"); + return NULL; + } + delta_d = ymd_to_ord(GET_YEAR(left), + GET_MONTH(left), + GET_DAY(left)) - + ymd_to_ord(GET_YEAR(right), + GET_MONTH(right), + GET_DAY(right)); + /* These can't overflow, since the values are + * normalized. At most this gives the number of + * seconds in one day. + */ + delta_s = (DATE_GET_HOUR(left) - + DATE_GET_HOUR(right)) * 3600 + + (DATE_GET_MINUTE(left) - + DATE_GET_MINUTE(right)) * 60 + + (DATE_GET_SECOND(left) - + DATE_GET_SECOND(right)); + delta_us = DATE_GET_MICROSECOND(left) - + DATE_GET_MICROSECOND(right); + /* (left - offset1) - (right - offset2) = + * (left - right) + (offset2 - offset1) + */ + delta_s += (offset2 - offset1) * 60; + result = new_delta(delta_d, delta_s, delta_us, 1); + } + else if (PyDelta_Check(right)) { + /* datetime - delta */ + result = add_datetime_timedelta( + (PyDateTime_DateTime *)left, + (PyDateTime_Delta *)right, + -1); + } + } + + if (result == Py_NotImplemented) + Py_INCREF(result); + return result; } /* Various ways to turn a datetime into a string. */ @@ -4266,88 +4266,88 @@ static PyObject * datetime_repr(PyDateTime_DateTime *self) { - const char *type_name = Py_TYPE(self)->tp_name; - PyObject *baserepr; + const char *type_name = Py_TYPE(self)->tp_name; + PyObject *baserepr; - if (DATE_GET_MICROSECOND(self)) { - baserepr = PyUnicode_FromFormat( - "%s(%d, %d, %d, %d, %d, %d, %d)", - type_name, - GET_YEAR(self), GET_MONTH(self), GET_DAY(self), - DATE_GET_HOUR(self), DATE_GET_MINUTE(self), - DATE_GET_SECOND(self), - DATE_GET_MICROSECOND(self)); - } - else if (DATE_GET_SECOND(self)) { - baserepr = PyUnicode_FromFormat( - "%s(%d, %d, %d, %d, %d, %d)", - type_name, - GET_YEAR(self), GET_MONTH(self), GET_DAY(self), - DATE_GET_HOUR(self), DATE_GET_MINUTE(self), - DATE_GET_SECOND(self)); - } - else { - baserepr = PyUnicode_FromFormat( - "%s(%d, %d, %d, %d, %d)", - type_name, - GET_YEAR(self), GET_MONTH(self), GET_DAY(self), - DATE_GET_HOUR(self), DATE_GET_MINUTE(self)); - } - if (baserepr == NULL || ! HASTZINFO(self)) - return baserepr; - return append_keyword_tzinfo(baserepr, self->tzinfo); + if (DATE_GET_MICROSECOND(self)) { + baserepr = PyUnicode_FromFormat( + "%s(%d, %d, %d, %d, %d, %d, %d)", + type_name, + GET_YEAR(self), GET_MONTH(self), GET_DAY(self), + DATE_GET_HOUR(self), DATE_GET_MINUTE(self), + DATE_GET_SECOND(self), + DATE_GET_MICROSECOND(self)); + } + else if (DATE_GET_SECOND(self)) { + baserepr = PyUnicode_FromFormat( + "%s(%d, %d, %d, %d, %d, %d)", + type_name, + GET_YEAR(self), GET_MONTH(self), GET_DAY(self), + DATE_GET_HOUR(self), DATE_GET_MINUTE(self), + DATE_GET_SECOND(self)); + } + else { + baserepr = PyUnicode_FromFormat( + "%s(%d, %d, %d, %d, %d)", + type_name, + GET_YEAR(self), GET_MONTH(self), GET_DAY(self), + DATE_GET_HOUR(self), DATE_GET_MINUTE(self)); + } + if (baserepr == NULL || ! HASTZINFO(self)) + return baserepr; + return append_keyword_tzinfo(baserepr, self->tzinfo); } static PyObject * datetime_str(PyDateTime_DateTime *self) { - return PyObject_CallMethod((PyObject *)self, "isoformat", "(s)", " "); + return PyObject_CallMethod((PyObject *)self, "isoformat", "(s)", " "); } static PyObject * datetime_isoformat(PyDateTime_DateTime *self, PyObject *args, PyObject *kw) { - int sep = 'T'; - static char *keywords[] = {"sep", NULL}; - char buffer[100]; - PyObject *result; - int us = DATE_GET_MICROSECOND(self); - - if (!PyArg_ParseTupleAndKeywords(args, kw, "|C:isoformat", keywords, &sep)) - return NULL; - if (us) - result = PyUnicode_FromFormat("%04d-%02d-%02d%c%02d:%02d:%02d.%06d", - GET_YEAR(self), GET_MONTH(self), - GET_DAY(self), (int)sep, - DATE_GET_HOUR(self), DATE_GET_MINUTE(self), - DATE_GET_SECOND(self), us); - else - result = PyUnicode_FromFormat("%04d-%02d-%02d%c%02d:%02d:%02d", - GET_YEAR(self), GET_MONTH(self), - GET_DAY(self), (int)sep, - DATE_GET_HOUR(self), DATE_GET_MINUTE(self), - DATE_GET_SECOND(self)); - - if (!result || !HASTZINFO(self)) - return result; - - /* We need to append the UTC offset. */ - if (format_utcoffset(buffer, sizeof(buffer), ":", self->tzinfo, - (PyObject *)self) < 0) { - Py_DECREF(result); - return NULL; - } - PyUnicode_AppendAndDel(&result, PyUnicode_FromString(buffer)); - return result; + int sep = 'T'; + static char *keywords[] = {"sep", NULL}; + char buffer[100]; + PyObject *result; + int us = DATE_GET_MICROSECOND(self); + + if (!PyArg_ParseTupleAndKeywords(args, kw, "|C:isoformat", keywords, &sep)) + return NULL; + if (us) + result = PyUnicode_FromFormat("%04d-%02d-%02d%c%02d:%02d:%02d.%06d", + GET_YEAR(self), GET_MONTH(self), + GET_DAY(self), (int)sep, + DATE_GET_HOUR(self), DATE_GET_MINUTE(self), + DATE_GET_SECOND(self), us); + else + result = PyUnicode_FromFormat("%04d-%02d-%02d%c%02d:%02d:%02d", + GET_YEAR(self), GET_MONTH(self), + GET_DAY(self), (int)sep, + DATE_GET_HOUR(self), DATE_GET_MINUTE(self), + DATE_GET_SECOND(self)); + + if (!result || !HASTZINFO(self)) + return result; + + /* We need to append the UTC offset. */ + if (format_utcoffset(buffer, sizeof(buffer), ":", self->tzinfo, + (PyObject *)self) < 0) { + Py_DECREF(result); + return NULL; + } + PyUnicode_AppendAndDel(&result, PyUnicode_FromString(buffer)); + return result; } static PyObject * datetime_ctime(PyDateTime_DateTime *self) { - return format_ctime((PyDateTime_Date *)self, - DATE_GET_HOUR(self), - DATE_GET_MINUTE(self), - DATE_GET_SECOND(self)); + return format_ctime((PyDateTime_Date *)self, + DATE_GET_HOUR(self), + DATE_GET_MINUTE(self), + DATE_GET_SECOND(self)); } /* Miscellaneous methods. */ @@ -4355,292 +4355,292 @@ static PyObject * datetime_richcompare(PyObject *self, PyObject *other, int op) { - int diff; - naivety n1, n2; - int offset1, offset2; - - if (! PyDateTime_Check(other)) { - if (PyDate_Check(other)) { - /* Prevent invocation of date_richcompare. We want to - return NotImplemented here to give the other object - a chance. But since DateTime is a subclass of - Date, if the other object is a Date, it would - compute an ordering based on the date part alone, - and we don't want that. So force unequal or - uncomparable here in that case. */ - if (op == Py_EQ) - Py_RETURN_FALSE; - if (op == Py_NE) - Py_RETURN_TRUE; - return cmperror(self, other); - } - Py_INCREF(Py_NotImplemented); - return Py_NotImplemented; - } - - if (classify_two_utcoffsets(self, &offset1, &n1, self, - other, &offset2, &n2, other) < 0) - return NULL; - assert(n1 != OFFSET_UNKNOWN && n2 != OFFSET_UNKNOWN); - /* If they're both naive, or both aware and have the same offsets, - * we get off cheap. Note that if they're both naive, offset1 == - * offset2 == 0 at this point. - */ - if (n1 == n2 && offset1 == offset2) { - diff = memcmp(((PyDateTime_DateTime *)self)->data, - ((PyDateTime_DateTime *)other)->data, - _PyDateTime_DATETIME_DATASIZE); - return diff_to_bool(diff, op); - } - - if (n1 == OFFSET_AWARE && n2 == OFFSET_AWARE) { - PyDateTime_Delta *delta; - - assert(offset1 != offset2); /* else last "if" handled it */ - delta = (PyDateTime_Delta *)datetime_subtract((PyObject *)self, - other); - if (delta == NULL) - return NULL; - diff = GET_TD_DAYS(delta); - if (diff == 0) - diff = GET_TD_SECONDS(delta) | - GET_TD_MICROSECONDS(delta); - Py_DECREF(delta); - return diff_to_bool(diff, op); - } - - assert(n1 != n2); - PyErr_SetString(PyExc_TypeError, - "can't compare offset-naive and " - "offset-aware datetimes"); - return NULL; + int diff; + naivety n1, n2; + int offset1, offset2; + + if (! PyDateTime_Check(other)) { + if (PyDate_Check(other)) { + /* Prevent invocation of date_richcompare. We want to + return NotImplemented here to give the other object + a chance. But since DateTime is a subclass of + Date, if the other object is a Date, it would + compute an ordering based on the date part alone, + and we don't want that. So force unequal or + uncomparable here in that case. */ + if (op == Py_EQ) + Py_RETURN_FALSE; + if (op == Py_NE) + Py_RETURN_TRUE; + return cmperror(self, other); + } + Py_INCREF(Py_NotImplemented); + return Py_NotImplemented; + } + + if (classify_two_utcoffsets(self, &offset1, &n1, self, + other, &offset2, &n2, other) < 0) + return NULL; + assert(n1 != OFFSET_UNKNOWN && n2 != OFFSET_UNKNOWN); + /* If they're both naive, or both aware and have the same offsets, + * we get off cheap. Note that if they're both naive, offset1 == + * offset2 == 0 at this point. + */ + if (n1 == n2 && offset1 == offset2) { + diff = memcmp(((PyDateTime_DateTime *)self)->data, + ((PyDateTime_DateTime *)other)->data, + _PyDateTime_DATETIME_DATASIZE); + return diff_to_bool(diff, op); + } + + if (n1 == OFFSET_AWARE && n2 == OFFSET_AWARE) { + PyDateTime_Delta *delta; + + assert(offset1 != offset2); /* else last "if" handled it */ + delta = (PyDateTime_Delta *)datetime_subtract((PyObject *)self, + other); + if (delta == NULL) + return NULL; + diff = GET_TD_DAYS(delta); + if (diff == 0) + diff = GET_TD_SECONDS(delta) | + GET_TD_MICROSECONDS(delta); + Py_DECREF(delta); + return diff_to_bool(diff, op); + } + + assert(n1 != n2); + PyErr_SetString(PyExc_TypeError, + "can't compare offset-naive and " + "offset-aware datetimes"); + return NULL; } static long datetime_hash(PyDateTime_DateTime *self) { - if (self->hashcode == -1) { - naivety n; - int offset; - PyObject *temp; - - n = classify_utcoffset((PyObject *)self, (PyObject *)self, - &offset); - assert(n != OFFSET_UNKNOWN); - if (n == OFFSET_ERROR) - return -1; - - /* Reduce this to a hash of another object. */ - if (n == OFFSET_NAIVE) { - self->hashcode = generic_hash( - (unsigned char *)self->data, _PyDateTime_DATETIME_DATASIZE); - return self->hashcode; - } - else { - int days; - int seconds; - - assert(n == OFFSET_AWARE); - assert(HASTZINFO(self)); - days = ymd_to_ord(GET_YEAR(self), - GET_MONTH(self), - GET_DAY(self)); - seconds = DATE_GET_HOUR(self) * 3600 + - (DATE_GET_MINUTE(self) - offset) * 60 + - DATE_GET_SECOND(self); - temp = new_delta(days, - seconds, - DATE_GET_MICROSECOND(self), - 1); - } - if (temp != NULL) { - self->hashcode = PyObject_Hash(temp); - Py_DECREF(temp); - } - } - return self->hashcode; + if (self->hashcode == -1) { + naivety n; + int offset; + PyObject *temp; + + n = classify_utcoffset((PyObject *)self, (PyObject *)self, + &offset); + assert(n != OFFSET_UNKNOWN); + if (n == OFFSET_ERROR) + return -1; + + /* Reduce this to a hash of another object. */ + if (n == OFFSET_NAIVE) { + self->hashcode = generic_hash( + (unsigned char *)self->data, _PyDateTime_DATETIME_DATASIZE); + return self->hashcode; + } + else { + int days; + int seconds; + + assert(n == OFFSET_AWARE); + assert(HASTZINFO(self)); + days = ymd_to_ord(GET_YEAR(self), + GET_MONTH(self), + GET_DAY(self)); + seconds = DATE_GET_HOUR(self) * 3600 + + (DATE_GET_MINUTE(self) - offset) * 60 + + DATE_GET_SECOND(self); + temp = new_delta(days, + seconds, + DATE_GET_MICROSECOND(self), + 1); + } + if (temp != NULL) { + self->hashcode = PyObject_Hash(temp); + Py_DECREF(temp); + } + } + return self->hashcode; } static PyObject * datetime_replace(PyDateTime_DateTime *self, PyObject *args, PyObject *kw) { - PyObject *clone; - PyObject *tuple; - int y = GET_YEAR(self); - int m = GET_MONTH(self); - int d = GET_DAY(self); - int hh = DATE_GET_HOUR(self); - int mm = DATE_GET_MINUTE(self); - int ss = DATE_GET_SECOND(self); - int us = DATE_GET_MICROSECOND(self); - PyObject *tzinfo = HASTZINFO(self) ? self->tzinfo : Py_None; - - if (! PyArg_ParseTupleAndKeywords(args, kw, "|iiiiiiiO:replace", - datetime_kws, - &y, &m, &d, &hh, &mm, &ss, &us, - &tzinfo)) - return NULL; - tuple = Py_BuildValue("iiiiiiiO", y, m, d, hh, mm, ss, us, tzinfo); - if (tuple == NULL) - return NULL; - clone = datetime_new(Py_TYPE(self), tuple, NULL); - Py_DECREF(tuple); - return clone; + PyObject *clone; + PyObject *tuple; + int y = GET_YEAR(self); + int m = GET_MONTH(self); + int d = GET_DAY(self); + int hh = DATE_GET_HOUR(self); + int mm = DATE_GET_MINUTE(self); + int ss = DATE_GET_SECOND(self); + int us = DATE_GET_MICROSECOND(self); + PyObject *tzinfo = HASTZINFO(self) ? self->tzinfo : Py_None; + + if (! PyArg_ParseTupleAndKeywords(args, kw, "|iiiiiiiO:replace", + datetime_kws, + &y, &m, &d, &hh, &mm, &ss, &us, + &tzinfo)) + return NULL; + tuple = Py_BuildValue("iiiiiiiO", y, m, d, hh, mm, ss, us, tzinfo); + if (tuple == NULL) + return NULL; + clone = datetime_new(Py_TYPE(self), tuple, NULL); + Py_DECREF(tuple); + return clone; } static PyObject * datetime_astimezone(PyDateTime_DateTime *self, PyObject *args, PyObject *kw) { - int y, m, d, hh, mm, ss, us; - PyObject *result; - int offset, none; - - PyObject *tzinfo; - static char *keywords[] = {"tz", NULL}; - - if (! PyArg_ParseTupleAndKeywords(args, kw, "O!:astimezone", keywords, - &PyDateTime_TZInfoType, &tzinfo)) - return NULL; - - if (!HASTZINFO(self) || self->tzinfo == Py_None) - goto NeedAware; - - /* Conversion to self's own time zone is a NOP. */ - if (self->tzinfo == tzinfo) { - Py_INCREF(self); - return (PyObject *)self; - } - - /* Convert self to UTC. */ - offset = call_utcoffset(self->tzinfo, (PyObject *)self, &none); - if (offset == -1 && PyErr_Occurred()) - return NULL; - if (none) - goto NeedAware; - - y = GET_YEAR(self); - m = GET_MONTH(self); - d = GET_DAY(self); - hh = DATE_GET_HOUR(self); - mm = DATE_GET_MINUTE(self); - ss = DATE_GET_SECOND(self); - us = DATE_GET_MICROSECOND(self); - - mm -= offset; - if ((mm < 0 || mm >= 60) && - normalize_datetime(&y, &m, &d, &hh, &mm, &ss, &us) < 0) - return NULL; - - /* Attach new tzinfo and let fromutc() do the rest. */ - result = new_datetime(y, m, d, hh, mm, ss, us, tzinfo); - if (result != NULL) { - PyObject *temp = result; - - result = PyObject_CallMethod(tzinfo, "fromutc", "O", temp); - Py_DECREF(temp); - } - return result; + int y, m, d, hh, mm, ss, us; + PyObject *result; + int offset, none; + + PyObject *tzinfo; + static char *keywords[] = {"tz", NULL}; + + if (! PyArg_ParseTupleAndKeywords(args, kw, "O!:astimezone", keywords, + &PyDateTime_TZInfoType, &tzinfo)) + return NULL; + + if (!HASTZINFO(self) || self->tzinfo == Py_None) + goto NeedAware; + + /* Conversion to self's own time zone is a NOP. */ + if (self->tzinfo == tzinfo) { + Py_INCREF(self); + return (PyObject *)self; + } + + /* Convert self to UTC. */ + offset = call_utcoffset(self->tzinfo, (PyObject *)self, &none); + if (offset == -1 && PyErr_Occurred()) + return NULL; + if (none) + goto NeedAware; + + y = GET_YEAR(self); + m = GET_MONTH(self); + d = GET_DAY(self); + hh = DATE_GET_HOUR(self); + mm = DATE_GET_MINUTE(self); + ss = DATE_GET_SECOND(self); + us = DATE_GET_MICROSECOND(self); + + mm -= offset; + if ((mm < 0 || mm >= 60) && + normalize_datetime(&y, &m, &d, &hh, &mm, &ss, &us) < 0) + return NULL; + + /* Attach new tzinfo and let fromutc() do the rest. */ + result = new_datetime(y, m, d, hh, mm, ss, us, tzinfo); + if (result != NULL) { + PyObject *temp = result; + + result = PyObject_CallMethod(tzinfo, "fromutc", "O", temp); + Py_DECREF(temp); + } + return result; NeedAware: - PyErr_SetString(PyExc_ValueError, "astimezone() cannot be applied to " - "a naive datetime"); - return NULL; + PyErr_SetString(PyExc_ValueError, "astimezone() cannot be applied to " + "a naive datetime"); + return NULL; } static PyObject * datetime_timetuple(PyDateTime_DateTime *self) { - int dstflag = -1; + int dstflag = -1; - if (HASTZINFO(self) && self->tzinfo != Py_None) { - int none; + if (HASTZINFO(self) && self->tzinfo != Py_None) { + int none; - dstflag = call_dst(self->tzinfo, (PyObject *)self, &none); - if (dstflag == -1 && PyErr_Occurred()) - return NULL; - - if (none) - dstflag = -1; - else if (dstflag != 0) - dstflag = 1; - - } - return build_struct_time(GET_YEAR(self), - GET_MONTH(self), - GET_DAY(self), - DATE_GET_HOUR(self), - DATE_GET_MINUTE(self), - DATE_GET_SECOND(self), - dstflag); + dstflag = call_dst(self->tzinfo, (PyObject *)self, &none); + if (dstflag == -1 && PyErr_Occurred()) + return NULL; + + if (none) + dstflag = -1; + else if (dstflag != 0) + dstflag = 1; + + } + return build_struct_time(GET_YEAR(self), + GET_MONTH(self), + GET_DAY(self), + DATE_GET_HOUR(self), + DATE_GET_MINUTE(self), + DATE_GET_SECOND(self), + dstflag); } static PyObject * datetime_getdate(PyDateTime_DateTime *self) { - return new_date(GET_YEAR(self), - GET_MONTH(self), - GET_DAY(self)); + return new_date(GET_YEAR(self), + GET_MONTH(self), + GET_DAY(self)); } static PyObject * datetime_gettime(PyDateTime_DateTime *self) { - return new_time(DATE_GET_HOUR(self), - DATE_GET_MINUTE(self), - DATE_GET_SECOND(self), - DATE_GET_MICROSECOND(self), - Py_None); + return new_time(DATE_GET_HOUR(self), + DATE_GET_MINUTE(self), + DATE_GET_SECOND(self), + DATE_GET_MICROSECOND(self), + Py_None); } static PyObject * datetime_gettimetz(PyDateTime_DateTime *self) { - return new_time(DATE_GET_HOUR(self), - DATE_GET_MINUTE(self), - DATE_GET_SECOND(self), - DATE_GET_MICROSECOND(self), - HASTZINFO(self) ? self->tzinfo : Py_None); + return new_time(DATE_GET_HOUR(self), + DATE_GET_MINUTE(self), + DATE_GET_SECOND(self), + DATE_GET_MICROSECOND(self), + HASTZINFO(self) ? self->tzinfo : Py_None); } static PyObject * datetime_utctimetuple(PyDateTime_DateTime *self) { - int y = GET_YEAR(self); - int m = GET_MONTH(self); - int d = GET_DAY(self); - int hh = DATE_GET_HOUR(self); - int mm = DATE_GET_MINUTE(self); - int ss = DATE_GET_SECOND(self); - int us = 0; /* microseconds are ignored in a timetuple */ - int offset = 0; - - if (HASTZINFO(self) && self->tzinfo != Py_None) { - int none; - - offset = call_utcoffset(self->tzinfo, (PyObject *)self, &none); - if (offset == -1 && PyErr_Occurred()) - return NULL; - } - /* Even if offset is 0, don't call timetuple() -- tm_isdst should be - * 0 in a UTC timetuple regardless of what dst() says. - */ - if (offset) { - /* Subtract offset minutes & normalize. */ - int stat; - - mm -= offset; - stat = normalize_datetime(&y, &m, &d, &hh, &mm, &ss, &us); - if (stat < 0) { - /* At the edges, it's possible we overflowed - * beyond MINYEAR or MAXYEAR. - */ - if (PyErr_ExceptionMatches(PyExc_OverflowError)) - PyErr_Clear(); - else - return NULL; - } - } - return build_struct_time(y, m, d, hh, mm, ss, 0); + int y = GET_YEAR(self); + int m = GET_MONTH(self); + int d = GET_DAY(self); + int hh = DATE_GET_HOUR(self); + int mm = DATE_GET_MINUTE(self); + int ss = DATE_GET_SECOND(self); + int us = 0; /* microseconds are ignored in a timetuple */ + int offset = 0; + + if (HASTZINFO(self) && self->tzinfo != Py_None) { + int none; + + offset = call_utcoffset(self->tzinfo, (PyObject *)self, &none); + if (offset == -1 && PyErr_Occurred()) + return NULL; + } + /* Even if offset is 0, don't call timetuple() -- tm_isdst should be + * 0 in a UTC timetuple regardless of what dst() says. + */ + if (offset) { + /* Subtract offset minutes & normalize. */ + int stat; + + mm -= offset; + stat = normalize_datetime(&y, &m, &d, &hh, &mm, &ss, &us); + if (stat < 0) { + /* At the edges, it's possible we overflowed + * beyond MINYEAR or MAXYEAR. + */ + if (PyErr_ExceptionMatches(PyExc_OverflowError)) + PyErr_Clear(); + else + return NULL; + } + } + return build_struct_time(y, m, d, hh, mm, ss, 0); } /* Pickle support, a simple use of __reduce__. */ @@ -4653,102 +4653,102 @@ static PyObject * datetime_getstate(PyDateTime_DateTime *self) { - PyObject *basestate; - PyObject *result = NULL; + PyObject *basestate; + PyObject *result = NULL; - basestate = PyBytes_FromStringAndSize((char *)self->data, - _PyDateTime_DATETIME_DATASIZE); - if (basestate != NULL) { - if (! HASTZINFO(self) || self->tzinfo == Py_None) - result = PyTuple_Pack(1, basestate); - else - result = PyTuple_Pack(2, basestate, self->tzinfo); - Py_DECREF(basestate); - } - return result; + basestate = PyBytes_FromStringAndSize((char *)self->data, + _PyDateTime_DATETIME_DATASIZE); + if (basestate != NULL) { + if (! HASTZINFO(self) || self->tzinfo == Py_None) + result = PyTuple_Pack(1, basestate); + else + result = PyTuple_Pack(2, basestate, self->tzinfo); + Py_DECREF(basestate); + } + return result; } static PyObject * datetime_reduce(PyDateTime_DateTime *self, PyObject *arg) { - return Py_BuildValue("(ON)", Py_TYPE(self), datetime_getstate(self)); + return Py_BuildValue("(ON)", Py_TYPE(self), datetime_getstate(self)); } static PyMethodDef datetime_methods[] = { - /* Class methods: */ + /* Class methods: */ - {"now", (PyCFunction)datetime_now, - METH_VARARGS | METH_KEYWORDS | METH_CLASS, - PyDoc_STR("[tz] -> new datetime with tz's local day and time.")}, + {"now", (PyCFunction)datetime_now, + METH_VARARGS | METH_KEYWORDS | METH_CLASS, + PyDoc_STR("[tz] -> new datetime with tz's local day and time.")}, - {"utcnow", (PyCFunction)datetime_utcnow, - METH_NOARGS | METH_CLASS, - PyDoc_STR("Return a new datetime representing UTC day and time.")}, + {"utcnow", (PyCFunction)datetime_utcnow, + METH_NOARGS | METH_CLASS, + PyDoc_STR("Return a new datetime representing UTC day and time.")}, - {"fromtimestamp", (PyCFunction)datetime_fromtimestamp, - METH_VARARGS | METH_KEYWORDS | METH_CLASS, - PyDoc_STR("timestamp[, tz] -> tz's local time from POSIX timestamp.")}, + {"fromtimestamp", (PyCFunction)datetime_fromtimestamp, + METH_VARARGS | METH_KEYWORDS | METH_CLASS, + PyDoc_STR("timestamp[, tz] -> tz's local time from POSIX timestamp.")}, - {"utcfromtimestamp", (PyCFunction)datetime_utcfromtimestamp, - METH_VARARGS | METH_CLASS, - PyDoc_STR("timestamp -> UTC datetime from a POSIX timestamp " - "(like time.time()).")}, + {"utcfromtimestamp", (PyCFunction)datetime_utcfromtimestamp, + METH_VARARGS | METH_CLASS, + PyDoc_STR("timestamp -> UTC datetime from a POSIX timestamp " + "(like time.time()).")}, - {"strptime", (PyCFunction)datetime_strptime, - METH_VARARGS | METH_CLASS, - PyDoc_STR("string, format -> new datetime parsed from a string " - "(like time.strptime()).")}, + {"strptime", (PyCFunction)datetime_strptime, + METH_VARARGS | METH_CLASS, + PyDoc_STR("string, format -> new datetime parsed from a string " + "(like time.strptime()).")}, - {"combine", (PyCFunction)datetime_combine, - METH_VARARGS | METH_KEYWORDS | METH_CLASS, - PyDoc_STR("date, time -> datetime with same date and time fields")}, + {"combine", (PyCFunction)datetime_combine, + METH_VARARGS | METH_KEYWORDS | METH_CLASS, + PyDoc_STR("date, time -> datetime with same date and time fields")}, - /* Instance methods: */ + /* Instance methods: */ - {"date", (PyCFunction)datetime_getdate, METH_NOARGS, - PyDoc_STR("Return date object with same year, month and day.")}, + {"date", (PyCFunction)datetime_getdate, METH_NOARGS, + PyDoc_STR("Return date object with same year, month and day.")}, - {"time", (PyCFunction)datetime_gettime, METH_NOARGS, - PyDoc_STR("Return time object with same time but with tzinfo=None.")}, + {"time", (PyCFunction)datetime_gettime, METH_NOARGS, + PyDoc_STR("Return time object with same time but with tzinfo=None.")}, - {"timetz", (PyCFunction)datetime_gettimetz, METH_NOARGS, - PyDoc_STR("Return time object with same time and tzinfo.")}, + {"timetz", (PyCFunction)datetime_gettimetz, METH_NOARGS, + PyDoc_STR("Return time object with same time and tzinfo.")}, - {"ctime", (PyCFunction)datetime_ctime, METH_NOARGS, - PyDoc_STR("Return ctime() style string.")}, + {"ctime", (PyCFunction)datetime_ctime, METH_NOARGS, + PyDoc_STR("Return ctime() style string.")}, - {"timetuple", (PyCFunction)datetime_timetuple, METH_NOARGS, - PyDoc_STR("Return time tuple, compatible with time.localtime().")}, + {"timetuple", (PyCFunction)datetime_timetuple, METH_NOARGS, + PyDoc_STR("Return time tuple, compatible with time.localtime().")}, - {"utctimetuple", (PyCFunction)datetime_utctimetuple, METH_NOARGS, - PyDoc_STR("Return UTC time tuple, compatible with time.localtime().")}, + {"utctimetuple", (PyCFunction)datetime_utctimetuple, METH_NOARGS, + PyDoc_STR("Return UTC time tuple, compatible with time.localtime().")}, - {"isoformat", (PyCFunction)datetime_isoformat, METH_VARARGS | METH_KEYWORDS, - PyDoc_STR("[sep] -> string in ISO 8601 format, " - "YYYY-MM-DDTHH:MM:SS[.mmmmmm][+HH:MM].\n\n" - "sep is used to separate the year from the time, and " - "defaults to 'T'.")}, + {"isoformat", (PyCFunction)datetime_isoformat, METH_VARARGS | METH_KEYWORDS, + PyDoc_STR("[sep] -> string in ISO 8601 format, " + "YYYY-MM-DDTHH:MM:SS[.mmmmmm][+HH:MM].\n\n" + "sep is used to separate the year from the time, and " + "defaults to 'T'.")}, - {"utcoffset", (PyCFunction)datetime_utcoffset, METH_NOARGS, - PyDoc_STR("Return self.tzinfo.utcoffset(self).")}, + {"utcoffset", (PyCFunction)datetime_utcoffset, METH_NOARGS, + PyDoc_STR("Return self.tzinfo.utcoffset(self).")}, - {"tzname", (PyCFunction)datetime_tzname, METH_NOARGS, - PyDoc_STR("Return self.tzinfo.tzname(self).")}, + {"tzname", (PyCFunction)datetime_tzname, METH_NOARGS, + PyDoc_STR("Return self.tzinfo.tzname(self).")}, - {"dst", (PyCFunction)datetime_dst, METH_NOARGS, - PyDoc_STR("Return self.tzinfo.dst(self).")}, + {"dst", (PyCFunction)datetime_dst, METH_NOARGS, + PyDoc_STR("Return self.tzinfo.dst(self).")}, - {"replace", (PyCFunction)datetime_replace, METH_VARARGS | METH_KEYWORDS, - PyDoc_STR("Return datetime with new specified fields.")}, + {"replace", (PyCFunction)datetime_replace, METH_VARARGS | METH_KEYWORDS, + PyDoc_STR("Return datetime with new specified fields.")}, - {"astimezone", (PyCFunction)datetime_astimezone, METH_VARARGS | METH_KEYWORDS, - PyDoc_STR("tz -> convert to local time in new timezone tz\n")}, + {"astimezone", (PyCFunction)datetime_astimezone, METH_VARARGS | METH_KEYWORDS, + PyDoc_STR("tz -> convert to local time in new timezone tz\n")}, - {"__reduce__", (PyCFunction)datetime_reduce, METH_NOARGS, - PyDoc_STR("__reduce__() -> (cls, state)")}, + {"__reduce__", (PyCFunction)datetime_reduce, METH_NOARGS, + PyDoc_STR("__reduce__() -> (cls, state)")}, - {NULL, NULL} + {NULL, NULL} }; static char datetime_doc[] = @@ -4758,58 +4758,58 @@ instance of a tzinfo subclass. The remaining arguments may be ints or longs.\n"); static PyNumberMethods datetime_as_number = { - datetime_add, /* nb_add */ - datetime_subtract, /* nb_subtract */ - 0, /* nb_multiply */ - 0, /* nb_remainder */ - 0, /* nb_divmod */ - 0, /* nb_power */ - 0, /* nb_negative */ - 0, /* nb_positive */ - 0, /* nb_absolute */ - 0, /* nb_bool */ + datetime_add, /* nb_add */ + datetime_subtract, /* nb_subtract */ + 0, /* nb_multiply */ + 0, /* nb_remainder */ + 0, /* nb_divmod */ + 0, /* nb_power */ + 0, /* nb_negative */ + 0, /* nb_positive */ + 0, /* nb_absolute */ + 0, /* nb_bool */ }; static PyTypeObject PyDateTime_DateTimeType = { - PyVarObject_HEAD_INIT(NULL, 0) - "datetime.datetime", /* tp_name */ - sizeof(PyDateTime_DateTime), /* tp_basicsize */ - 0, /* tp_itemsize */ - (destructor)datetime_dealloc, /* tp_dealloc */ - 0, /* tp_print */ - 0, /* tp_getattr */ - 0, /* tp_setattr */ - 0, /* tp_reserved */ - (reprfunc)datetime_repr, /* tp_repr */ - &datetime_as_number, /* tp_as_number */ - 0, /* tp_as_sequence */ - 0, /* tp_as_mapping */ - (hashfunc)datetime_hash, /* tp_hash */ - 0, /* tp_call */ - (reprfunc)datetime_str, /* tp_str */ - PyObject_GenericGetAttr, /* tp_getattro */ - 0, /* tp_setattro */ - 0, /* tp_as_buffer */ - Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */ - datetime_doc, /* tp_doc */ - 0, /* tp_traverse */ - 0, /* tp_clear */ - datetime_richcompare, /* tp_richcompare */ - 0, /* tp_weaklistoffset */ - 0, /* tp_iter */ - 0, /* tp_iternext */ - datetime_methods, /* tp_methods */ - 0, /* tp_members */ - datetime_getset, /* tp_getset */ - &PyDateTime_DateType, /* tp_base */ - 0, /* tp_dict */ - 0, /* tp_descr_get */ - 0, /* tp_descr_set */ - 0, /* tp_dictoffset */ - 0, /* tp_init */ - datetime_alloc, /* tp_alloc */ - datetime_new, /* tp_new */ - 0, /* tp_free */ + PyVarObject_HEAD_INIT(NULL, 0) + "datetime.datetime", /* tp_name */ + sizeof(PyDateTime_DateTime), /* tp_basicsize */ + 0, /* tp_itemsize */ + (destructor)datetime_dealloc, /* tp_dealloc */ + 0, /* tp_print */ + 0, /* tp_getattr */ + 0, /* tp_setattr */ + 0, /* tp_reserved */ + (reprfunc)datetime_repr, /* tp_repr */ + &datetime_as_number, /* tp_as_number */ + 0, /* tp_as_sequence */ + 0, /* tp_as_mapping */ + (hashfunc)datetime_hash, /* tp_hash */ + 0, /* tp_call */ + (reprfunc)datetime_str, /* tp_str */ + PyObject_GenericGetAttr, /* tp_getattro */ + 0, /* tp_setattro */ + 0, /* tp_as_buffer */ + Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */ + datetime_doc, /* tp_doc */ + 0, /* tp_traverse */ + 0, /* tp_clear */ + datetime_richcompare, /* tp_richcompare */ + 0, /* tp_weaklistoffset */ + 0, /* tp_iter */ + 0, /* tp_iternext */ + datetime_methods, /* tp_methods */ + 0, /* tp_members */ + datetime_getset, /* tp_getset */ + &PyDateTime_DateType, /* tp_base */ + 0, /* tp_dict */ + 0, /* tp_descr_get */ + 0, /* tp_descr_set */ + 0, /* tp_dictoffset */ + 0, /* tp_init */ + datetime_alloc, /* tp_alloc */ + datetime_new, /* tp_new */ + 0, /* tp_free */ }; /* --------------------------------------------------------------------------- @@ -4817,204 +4817,204 @@ */ static PyMethodDef module_methods[] = { - {NULL, NULL} + {NULL, NULL} }; /* C API. Clients get at this via PyDateTime_IMPORT, defined in * datetime.h. */ static PyDateTime_CAPI CAPI = { - &PyDateTime_DateType, - &PyDateTime_DateTimeType, - &PyDateTime_TimeType, - &PyDateTime_DeltaType, - &PyDateTime_TZInfoType, - new_date_ex, - new_datetime_ex, - new_time_ex, - new_delta_ex, - datetime_fromtimestamp, - date_fromtimestamp + &PyDateTime_DateType, + &PyDateTime_DateTimeType, + &PyDateTime_TimeType, + &PyDateTime_DeltaType, + &PyDateTime_TZInfoType, + new_date_ex, + new_datetime_ex, + new_time_ex, + new_delta_ex, + datetime_fromtimestamp, + date_fromtimestamp }; static struct PyModuleDef datetimemodule = { - PyModuleDef_HEAD_INIT, - "datetime", - "Fast implementation of the datetime type.", - -1, - module_methods, - NULL, - NULL, - NULL, - NULL + PyModuleDef_HEAD_INIT, + "datetime", + "Fast implementation of the datetime type.", + -1, + module_methods, + NULL, + NULL, + NULL, + NULL }; PyMODINIT_FUNC PyInit_datetime(void) { - PyObject *m; /* a module object */ - PyObject *d; /* its dict */ - PyObject *x; - - m = PyModule_Create(&datetimemodule); - if (m == NULL) - return NULL; - - if (PyType_Ready(&PyDateTime_DateType) < 0) - return NULL; - if (PyType_Ready(&PyDateTime_DateTimeType) < 0) - return NULL; - if (PyType_Ready(&PyDateTime_DeltaType) < 0) - return NULL; - if (PyType_Ready(&PyDateTime_TimeType) < 0) - return NULL; - if (PyType_Ready(&PyDateTime_TZInfoType) < 0) - return NULL; - - /* timedelta values */ - d = PyDateTime_DeltaType.tp_dict; - - x = new_delta(0, 0, 1, 0); - if (x == NULL || PyDict_SetItemString(d, "resolution", x) < 0) - return NULL; - Py_DECREF(x); - - x = new_delta(-MAX_DELTA_DAYS, 0, 0, 0); - if (x == NULL || PyDict_SetItemString(d, "min", x) < 0) - return NULL; - Py_DECREF(x); - - x = new_delta(MAX_DELTA_DAYS, 24*3600-1, 1000000-1, 0); - if (x == NULL || PyDict_SetItemString(d, "max", x) < 0) - return NULL; - Py_DECREF(x); - - /* date values */ - d = PyDateTime_DateType.tp_dict; - - x = new_date(1, 1, 1); - if (x == NULL || PyDict_SetItemString(d, "min", x) < 0) - return NULL; - Py_DECREF(x); - - x = new_date(MAXYEAR, 12, 31); - if (x == NULL || PyDict_SetItemString(d, "max", x) < 0) - return NULL; - Py_DECREF(x); - - x = new_delta(1, 0, 0, 0); - if (x == NULL || PyDict_SetItemString(d, "resolution", x) < 0) - return NULL; - Py_DECREF(x); - - /* time values */ - d = PyDateTime_TimeType.tp_dict; - - x = new_time(0, 0, 0, 0, Py_None); - if (x == NULL || PyDict_SetItemString(d, "min", x) < 0) - return NULL; - Py_DECREF(x); - - x = new_time(23, 59, 59, 999999, Py_None); - if (x == NULL || PyDict_SetItemString(d, "max", x) < 0) - return NULL; - Py_DECREF(x); - - x = new_delta(0, 0, 1, 0); - if (x == NULL || PyDict_SetItemString(d, "resolution", x) < 0) - return NULL; - Py_DECREF(x); - - /* datetime values */ - d = PyDateTime_DateTimeType.tp_dict; - - x = new_datetime(1, 1, 1, 0, 0, 0, 0, Py_None); - if (x == NULL || PyDict_SetItemString(d, "min", x) < 0) - return NULL; - Py_DECREF(x); - - x = new_datetime(MAXYEAR, 12, 31, 23, 59, 59, 999999, Py_None); - if (x == NULL || PyDict_SetItemString(d, "max", x) < 0) - return NULL; - Py_DECREF(x); - - x = new_delta(0, 0, 1, 0); - if (x == NULL || PyDict_SetItemString(d, "resolution", x) < 0) - return NULL; - Py_DECREF(x); - - /* module initialization */ - PyModule_AddIntConstant(m, "MINYEAR", MINYEAR); - PyModule_AddIntConstant(m, "MAXYEAR", MAXYEAR); - - Py_INCREF(&PyDateTime_DateType); - PyModule_AddObject(m, "date", (PyObject *) &PyDateTime_DateType); - - Py_INCREF(&PyDateTime_DateTimeType); - PyModule_AddObject(m, "datetime", - (PyObject *)&PyDateTime_DateTimeType); - - Py_INCREF(&PyDateTime_TimeType); - PyModule_AddObject(m, "time", (PyObject *) &PyDateTime_TimeType); - - Py_INCREF(&PyDateTime_DeltaType); - PyModule_AddObject(m, "timedelta", (PyObject *) &PyDateTime_DeltaType); - - Py_INCREF(&PyDateTime_TZInfoType); - PyModule_AddObject(m, "tzinfo", (PyObject *) &PyDateTime_TZInfoType); - - x = PyCapsule_New(&CAPI, PyDateTime_CAPSULE_NAME, NULL); - if (x == NULL) - return NULL; - PyModule_AddObject(m, "datetime_CAPI", x); - - /* A 4-year cycle has an extra leap day over what we'd get from - * pasting together 4 single years. - */ - assert(DI4Y == 4 * 365 + 1); - assert(DI4Y == days_before_year(4+1)); - - /* Similarly, a 400-year cycle has an extra leap day over what we'd - * get from pasting together 4 100-year cycles. - */ - assert(DI400Y == 4 * DI100Y + 1); - assert(DI400Y == days_before_year(400+1)); - - /* OTOH, a 100-year cycle has one fewer leap day than we'd get from - * pasting together 25 4-year cycles. - */ - assert(DI100Y == 25 * DI4Y - 1); - assert(DI100Y == days_before_year(100+1)); - - us_per_us = PyLong_FromLong(1); - us_per_ms = PyLong_FromLong(1000); - us_per_second = PyLong_FromLong(1000000); - us_per_minute = PyLong_FromLong(60000000); - seconds_per_day = PyLong_FromLong(24 * 3600); - if (us_per_us == NULL || us_per_ms == NULL || us_per_second == NULL || - us_per_minute == NULL || seconds_per_day == NULL) - return NULL; - - /* The rest are too big for 32-bit ints, but even - * us_per_week fits in 40 bits, so doubles should be exact. - */ - us_per_hour = PyLong_FromDouble(3600000000.0); - us_per_day = PyLong_FromDouble(86400000000.0); - us_per_week = PyLong_FromDouble(604800000000.0); - if (us_per_hour == NULL || us_per_day == NULL || us_per_week == NULL) - return NULL; - return m; + PyObject *m; /* a module object */ + PyObject *d; /* its dict */ + PyObject *x; + + m = PyModule_Create(&datetimemodule); + if (m == NULL) + return NULL; + + if (PyType_Ready(&PyDateTime_DateType) < 0) + return NULL; + if (PyType_Ready(&PyDateTime_DateTimeType) < 0) + return NULL; + if (PyType_Ready(&PyDateTime_DeltaType) < 0) + return NULL; + if (PyType_Ready(&PyDateTime_TimeType) < 0) + return NULL; + if (PyType_Ready(&PyDateTime_TZInfoType) < 0) + return NULL; + + /* timedelta values */ + d = PyDateTime_DeltaType.tp_dict; + + x = new_delta(0, 0, 1, 0); + if (x == NULL || PyDict_SetItemString(d, "resolution", x) < 0) + return NULL; + Py_DECREF(x); + + x = new_delta(-MAX_DELTA_DAYS, 0, 0, 0); + if (x == NULL || PyDict_SetItemString(d, "min", x) < 0) + return NULL; + Py_DECREF(x); + + x = new_delta(MAX_DELTA_DAYS, 24*3600-1, 1000000-1, 0); + if (x == NULL || PyDict_SetItemString(d, "max", x) < 0) + return NULL; + Py_DECREF(x); + + /* date values */ + d = PyDateTime_DateType.tp_dict; + + x = new_date(1, 1, 1); + if (x == NULL || PyDict_SetItemString(d, "min", x) < 0) + return NULL; + Py_DECREF(x); + + x = new_date(MAXYEAR, 12, 31); + if (x == NULL || PyDict_SetItemString(d, "max", x) < 0) + return NULL; + Py_DECREF(x); + + x = new_delta(1, 0, 0, 0); + if (x == NULL || PyDict_SetItemString(d, "resolution", x) < 0) + return NULL; + Py_DECREF(x); + + /* time values */ + d = PyDateTime_TimeType.tp_dict; + + x = new_time(0, 0, 0, 0, Py_None); + if (x == NULL || PyDict_SetItemString(d, "min", x) < 0) + return NULL; + Py_DECREF(x); + + x = new_time(23, 59, 59, 999999, Py_None); + if (x == NULL || PyDict_SetItemString(d, "max", x) < 0) + return NULL; + Py_DECREF(x); + + x = new_delta(0, 0, 1, 0); + if (x == NULL || PyDict_SetItemString(d, "resolution", x) < 0) + return NULL; + Py_DECREF(x); + + /* datetime values */ + d = PyDateTime_DateTimeType.tp_dict; + + x = new_datetime(1, 1, 1, 0, 0, 0, 0, Py_None); + if (x == NULL || PyDict_SetItemString(d, "min", x) < 0) + return NULL; + Py_DECREF(x); + + x = new_datetime(MAXYEAR, 12, 31, 23, 59, 59, 999999, Py_None); + if (x == NULL || PyDict_SetItemString(d, "max", x) < 0) + return NULL; + Py_DECREF(x); + + x = new_delta(0, 0, 1, 0); + if (x == NULL || PyDict_SetItemString(d, "resolution", x) < 0) + return NULL; + Py_DECREF(x); + + /* module initialization */ + PyModule_AddIntConstant(m, "MINYEAR", MINYEAR); + PyModule_AddIntConstant(m, "MAXYEAR", MAXYEAR); + + Py_INCREF(&PyDateTime_DateType); + PyModule_AddObject(m, "date", (PyObject *) &PyDateTime_DateType); + + Py_INCREF(&PyDateTime_DateTimeType); + PyModule_AddObject(m, "datetime", + (PyObject *)&PyDateTime_DateTimeType); + + Py_INCREF(&PyDateTime_TimeType); + PyModule_AddObject(m, "time", (PyObject *) &PyDateTime_TimeType); + + Py_INCREF(&PyDateTime_DeltaType); + PyModule_AddObject(m, "timedelta", (PyObject *) &PyDateTime_DeltaType); + + Py_INCREF(&PyDateTime_TZInfoType); + PyModule_AddObject(m, "tzinfo", (PyObject *) &PyDateTime_TZInfoType); + + x = PyCapsule_New(&CAPI, PyDateTime_CAPSULE_NAME, NULL); + if (x == NULL) + return NULL; + PyModule_AddObject(m, "datetime_CAPI", x); + + /* A 4-year cycle has an extra leap day over what we'd get from + * pasting together 4 single years. + */ + assert(DI4Y == 4 * 365 + 1); + assert(DI4Y == days_before_year(4+1)); + + /* Similarly, a 400-year cycle has an extra leap day over what we'd + * get from pasting together 4 100-year cycles. + */ + assert(DI400Y == 4 * DI100Y + 1); + assert(DI400Y == days_before_year(400+1)); + + /* OTOH, a 100-year cycle has one fewer leap day than we'd get from + * pasting together 25 4-year cycles. + */ + assert(DI100Y == 25 * DI4Y - 1); + assert(DI100Y == days_before_year(100+1)); + + us_per_us = PyLong_FromLong(1); + us_per_ms = PyLong_FromLong(1000); + us_per_second = PyLong_FromLong(1000000); + us_per_minute = PyLong_FromLong(60000000); + seconds_per_day = PyLong_FromLong(24 * 3600); + if (us_per_us == NULL || us_per_ms == NULL || us_per_second == NULL || + us_per_minute == NULL || seconds_per_day == NULL) + return NULL; + + /* The rest are too big for 32-bit ints, but even + * us_per_week fits in 40 bits, so doubles should be exact. + */ + us_per_hour = PyLong_FromDouble(3600000000.0); + us_per_day = PyLong_FromDouble(86400000000.0); + us_per_week = PyLong_FromDouble(604800000000.0); + if (us_per_hour == NULL || us_per_day == NULL || us_per_week == NULL) + return NULL; + return m; } /* --------------------------------------------------------------------------- Some time zone algebra. For a datetime x, let x.n = x stripped of its timezone -- its naive time. x.o = x.utcoffset(), and assuming that doesn't raise an exception or - return None + return None x.d = x.dst(), and assuming that doesn't raise an exception or - return None + return None x.s = x's standard offset, x.o - x.d Now some derived rules, where k is a duration (timedelta). @@ -5136,13 +5136,13 @@ already): diff' = x.n - (z'.n - z'.o) = replacing z'.n via [7] - x.n - (z.n + diff - z'.o) = replacing diff via [6] - x.n - (z.n + x.n - (z.n - z.o) - z'.o) = - x.n - z.n - x.n + z.n - z.o + z'.o = cancel x.n - - z.n + z.n - z.o + z'.o = cancel z.n - - z.o + z'.o = #1 twice - -z.s - z.d + z'.s + z'.d = z and z' have same tzinfo - z'.d - z.d + x.n - (z.n + diff - z'.o) = replacing diff via [6] + x.n - (z.n + x.n - (z.n - z.o) - z'.o) = + x.n - z.n - x.n + z.n - z.o + z'.o = cancel x.n + - z.n + z.n - z.o + z'.o = cancel z.n + - z.o + z'.o = #1 twice + -z.s - z.d + z'.s + z'.d = z and z' have same tzinfo + z'.d - z.d So z' is UTC-equivalent to x iff z'.d = z.d at this point. If they are equal, we've found the UTC-equivalent so are done. In fact, we stop with [7] and Modified: python/branches/py3k-jit/Modules/errnomodule.c ============================================================================== --- python/branches/py3k-jit/Modules/errnomodule.c (original) +++ python/branches/py3k-jit/Modules/errnomodule.c Mon May 10 23:55:43 2010 @@ -11,10 +11,10 @@ /* * Pull in the system error definitions - */ + */ static PyMethodDef errno_methods[] = { - {NULL, NULL} + {NULL, NULL} }; /* Helper function doing the dictionary inserting */ @@ -22,21 +22,21 @@ static void _inscode(PyObject *d, PyObject *de, const char *name, int code) { - PyObject *u = PyUnicode_FromString(name); - PyObject *v = PyLong_FromLong((long) code); + PyObject *u = PyUnicode_FromString(name); + PyObject *v = PyLong_FromLong((long) code); - /* Don't bother checking for errors; they'll be caught at the end - * of the module initialization function by the caller of - * initerrno(). - */ - if (u && v) { - /* insert in modules dict */ - PyDict_SetItem(d, u, v); - /* insert in errorcode dict */ - PyDict_SetItem(de, v, u); - } - Py_XDECREF(u); - Py_XDECREF(v); + /* Don't bother checking for errors; they'll be caught at the end + * of the module initialization function by the caller of + * initerrno(). + */ + if (u && v) { + /* insert in modules dict */ + PyDict_SetItem(d, u, v); + /* insert in errorcode dict */ + PyDict_SetItem(de, v, u); + } + Py_XDECREF(u); + Py_XDECREF(v); } PyDoc_STRVAR(errno__doc__, @@ -54,749 +54,749 @@ e.g. os.strerror(2) could return 'No such file or directory'."); static struct PyModuleDef errnomodule = { - PyModuleDef_HEAD_INIT, - "errno", - errno__doc__, - -1, - errno_methods, - NULL, - NULL, - NULL, - NULL + PyModuleDef_HEAD_INIT, + "errno", + errno__doc__, + -1, + errno_methods, + NULL, + NULL, + NULL, + NULL }; PyMODINIT_FUNC PyInit_errno(void) { - PyObject *m, *d, *de; - m = PyModule_Create(&errnomodule); - if (m == NULL) - return NULL; - d = PyModule_GetDict(m); - de = PyDict_New(); - if (!d || !de || PyDict_SetItemString(d, "errorcode", de) < 0) - return NULL; + PyObject *m, *d, *de; + m = PyModule_Create(&errnomodule); + if (m == NULL) + return NULL; + d = PyModule_GetDict(m); + de = PyDict_New(); + if (!d || !de || PyDict_SetItemString(d, "errorcode", de) < 0) + return NULL; /* Macro so I don't have to edit each and every line below... */ #define inscode(d, ds, de, name, code, comment) _inscode(d, de, name, code) - /* - * The names and comments are borrowed from linux/include/errno.h, - * which should be pretty all-inclusive - */ + /* + * The names and comments are borrowed from linux/include/errno.h, + * which should be pretty all-inclusive + */ #ifdef ENODEV - inscode(d, ds, de, "ENODEV", ENODEV, "No such device"); + inscode(d, ds, de, "ENODEV", ENODEV, "No such device"); #endif #ifdef ENOCSI - inscode(d, ds, de, "ENOCSI", ENOCSI, "No CSI structure available"); + inscode(d, ds, de, "ENOCSI", ENOCSI, "No CSI structure available"); #endif #ifdef EHOSTUNREACH - inscode(d, ds, de, "EHOSTUNREACH", EHOSTUNREACH, "No route to host"); + inscode(d, ds, de, "EHOSTUNREACH", EHOSTUNREACH, "No route to host"); #else #ifdef WSAEHOSTUNREACH - inscode(d, ds, de, "EHOSTUNREACH", WSAEHOSTUNREACH, "No route to host"); + inscode(d, ds, de, "EHOSTUNREACH", WSAEHOSTUNREACH, "No route to host"); #endif #endif #ifdef ENOMSG - inscode(d, ds, de, "ENOMSG", ENOMSG, "No message of desired type"); + inscode(d, ds, de, "ENOMSG", ENOMSG, "No message of desired type"); #endif #ifdef EUCLEAN - inscode(d, ds, de, "EUCLEAN", EUCLEAN, "Structure needs cleaning"); + inscode(d, ds, de, "EUCLEAN", EUCLEAN, "Structure needs cleaning"); #endif #ifdef EL2NSYNC - inscode(d, ds, de, "EL2NSYNC", EL2NSYNC, "Level 2 not synchronized"); + inscode(d, ds, de, "EL2NSYNC", EL2NSYNC, "Level 2 not synchronized"); #endif #ifdef EL2HLT - inscode(d, ds, de, "EL2HLT", EL2HLT, "Level 2 halted"); + inscode(d, ds, de, "EL2HLT", EL2HLT, "Level 2 halted"); #endif #ifdef ENODATA - inscode(d, ds, de, "ENODATA", ENODATA, "No data available"); + inscode(d, ds, de, "ENODATA", ENODATA, "No data available"); #endif #ifdef ENOTBLK - inscode(d, ds, de, "ENOTBLK", ENOTBLK, "Block device required"); + inscode(d, ds, de, "ENOTBLK", ENOTBLK, "Block device required"); #endif #ifdef ENOSYS - inscode(d, ds, de, "ENOSYS", ENOSYS, "Function not implemented"); + inscode(d, ds, de, "ENOSYS", ENOSYS, "Function not implemented"); #endif #ifdef EPIPE - inscode(d, ds, de, "EPIPE", EPIPE, "Broken pipe"); + inscode(d, ds, de, "EPIPE", EPIPE, "Broken pipe"); #endif #ifdef EINVAL - inscode(d, ds, de, "EINVAL", EINVAL, "Invalid argument"); + inscode(d, ds, de, "EINVAL", EINVAL, "Invalid argument"); #else #ifdef WSAEINVAL - inscode(d, ds, de, "EINVAL", WSAEINVAL, "Invalid argument"); + inscode(d, ds, de, "EINVAL", WSAEINVAL, "Invalid argument"); #endif #endif #ifdef EOVERFLOW - inscode(d, ds, de, "EOVERFLOW", EOVERFLOW, "Value too large for defined data type"); + inscode(d, ds, de, "EOVERFLOW", EOVERFLOW, "Value too large for defined data type"); #endif #ifdef EADV - inscode(d, ds, de, "EADV", EADV, "Advertise error"); + inscode(d, ds, de, "EADV", EADV, "Advertise error"); #endif #ifdef EINTR - inscode(d, ds, de, "EINTR", EINTR, "Interrupted system call"); + inscode(d, ds, de, "EINTR", EINTR, "Interrupted system call"); #else #ifdef WSAEINTR - inscode(d, ds, de, "EINTR", WSAEINTR, "Interrupted system call"); + inscode(d, ds, de, "EINTR", WSAEINTR, "Interrupted system call"); #endif #endif #ifdef EUSERS - inscode(d, ds, de, "EUSERS", EUSERS, "Too many users"); + inscode(d, ds, de, "EUSERS", EUSERS, "Too many users"); #else #ifdef WSAEUSERS - inscode(d, ds, de, "EUSERS", WSAEUSERS, "Too many users"); + inscode(d, ds, de, "EUSERS", WSAEUSERS, "Too many users"); #endif #endif #ifdef ENOTEMPTY - inscode(d, ds, de, "ENOTEMPTY", ENOTEMPTY, "Directory not empty"); + inscode(d, ds, de, "ENOTEMPTY", ENOTEMPTY, "Directory not empty"); #else #ifdef WSAENOTEMPTY - inscode(d, ds, de, "ENOTEMPTY", WSAENOTEMPTY, "Directory not empty"); + inscode(d, ds, de, "ENOTEMPTY", WSAENOTEMPTY, "Directory not empty"); #endif #endif #ifdef ENOBUFS - inscode(d, ds, de, "ENOBUFS", ENOBUFS, "No buffer space available"); + inscode(d, ds, de, "ENOBUFS", ENOBUFS, "No buffer space available"); #else #ifdef WSAENOBUFS - inscode(d, ds, de, "ENOBUFS", WSAENOBUFS, "No buffer space available"); + inscode(d, ds, de, "ENOBUFS", WSAENOBUFS, "No buffer space available"); #endif #endif #ifdef EPROTO - inscode(d, ds, de, "EPROTO", EPROTO, "Protocol error"); + inscode(d, ds, de, "EPROTO", EPROTO, "Protocol error"); #endif #ifdef EREMOTE - inscode(d, ds, de, "EREMOTE", EREMOTE, "Object is remote"); + inscode(d, ds, de, "EREMOTE", EREMOTE, "Object is remote"); #else #ifdef WSAEREMOTE - inscode(d, ds, de, "EREMOTE", WSAEREMOTE, "Object is remote"); + inscode(d, ds, de, "EREMOTE", WSAEREMOTE, "Object is remote"); #endif #endif #ifdef ENAVAIL - inscode(d, ds, de, "ENAVAIL", ENAVAIL, "No XENIX semaphores available"); + inscode(d, ds, de, "ENAVAIL", ENAVAIL, "No XENIX semaphores available"); #endif #ifdef ECHILD - inscode(d, ds, de, "ECHILD", ECHILD, "No child processes"); + inscode(d, ds, de, "ECHILD", ECHILD, "No child processes"); #endif #ifdef ELOOP - inscode(d, ds, de, "ELOOP", ELOOP, "Too many symbolic links encountered"); + inscode(d, ds, de, "ELOOP", ELOOP, "Too many symbolic links encountered"); #else #ifdef WSAELOOP - inscode(d, ds, de, "ELOOP", WSAELOOP, "Too many symbolic links encountered"); + inscode(d, ds, de, "ELOOP", WSAELOOP, "Too many symbolic links encountered"); #endif #endif #ifdef EXDEV - inscode(d, ds, de, "EXDEV", EXDEV, "Cross-device link"); + inscode(d, ds, de, "EXDEV", EXDEV, "Cross-device link"); #endif #ifdef E2BIG - inscode(d, ds, de, "E2BIG", E2BIG, "Arg list too long"); + inscode(d, ds, de, "E2BIG", E2BIG, "Arg list too long"); #endif #ifdef ESRCH - inscode(d, ds, de, "ESRCH", ESRCH, "No such process"); + inscode(d, ds, de, "ESRCH", ESRCH, "No such process"); #endif #ifdef EMSGSIZE - inscode(d, ds, de, "EMSGSIZE", EMSGSIZE, "Message too long"); + inscode(d, ds, de, "EMSGSIZE", EMSGSIZE, "Message too long"); #else #ifdef WSAEMSGSIZE - inscode(d, ds, de, "EMSGSIZE", WSAEMSGSIZE, "Message too long"); + inscode(d, ds, de, "EMSGSIZE", WSAEMSGSIZE, "Message too long"); #endif #endif #ifdef EAFNOSUPPORT - inscode(d, ds, de, "EAFNOSUPPORT", EAFNOSUPPORT, "Address family not supported by protocol"); + inscode(d, ds, de, "EAFNOSUPPORT", EAFNOSUPPORT, "Address family not supported by protocol"); #else #ifdef WSAEAFNOSUPPORT - inscode(d, ds, de, "EAFNOSUPPORT", WSAEAFNOSUPPORT, "Address family not supported by protocol"); + inscode(d, ds, de, "EAFNOSUPPORT", WSAEAFNOSUPPORT, "Address family not supported by protocol"); #endif #endif #ifdef EBADR - inscode(d, ds, de, "EBADR", EBADR, "Invalid request descriptor"); + inscode(d, ds, de, "EBADR", EBADR, "Invalid request descriptor"); #endif #ifdef EHOSTDOWN - inscode(d, ds, de, "EHOSTDOWN", EHOSTDOWN, "Host is down"); + inscode(d, ds, de, "EHOSTDOWN", EHOSTDOWN, "Host is down"); #else #ifdef WSAEHOSTDOWN - inscode(d, ds, de, "EHOSTDOWN", WSAEHOSTDOWN, "Host is down"); + inscode(d, ds, de, "EHOSTDOWN", WSAEHOSTDOWN, "Host is down"); #endif #endif #ifdef EPFNOSUPPORT - inscode(d, ds, de, "EPFNOSUPPORT", EPFNOSUPPORT, "Protocol family not supported"); + inscode(d, ds, de, "EPFNOSUPPORT", EPFNOSUPPORT, "Protocol family not supported"); #else #ifdef WSAEPFNOSUPPORT - inscode(d, ds, de, "EPFNOSUPPORT", WSAEPFNOSUPPORT, "Protocol family not supported"); + inscode(d, ds, de, "EPFNOSUPPORT", WSAEPFNOSUPPORT, "Protocol family not supported"); #endif #endif #ifdef ENOPROTOOPT - inscode(d, ds, de, "ENOPROTOOPT", ENOPROTOOPT, "Protocol not available"); + inscode(d, ds, de, "ENOPROTOOPT", ENOPROTOOPT, "Protocol not available"); #else #ifdef WSAENOPROTOOPT - inscode(d, ds, de, "ENOPROTOOPT", WSAENOPROTOOPT, "Protocol not available"); + inscode(d, ds, de, "ENOPROTOOPT", WSAENOPROTOOPT, "Protocol not available"); #endif #endif #ifdef EBUSY - inscode(d, ds, de, "EBUSY", EBUSY, "Device or resource busy"); + inscode(d, ds, de, "EBUSY", EBUSY, "Device or resource busy"); #endif #ifdef EWOULDBLOCK - inscode(d, ds, de, "EWOULDBLOCK", EWOULDBLOCK, "Operation would block"); + inscode(d, ds, de, "EWOULDBLOCK", EWOULDBLOCK, "Operation would block"); #else #ifdef WSAEWOULDBLOCK - inscode(d, ds, de, "EWOULDBLOCK", WSAEWOULDBLOCK, "Operation would block"); + inscode(d, ds, de, "EWOULDBLOCK", WSAEWOULDBLOCK, "Operation would block"); #endif #endif #ifdef EBADFD - inscode(d, ds, de, "EBADFD", EBADFD, "File descriptor in bad state"); + inscode(d, ds, de, "EBADFD", EBADFD, "File descriptor in bad state"); #endif #ifdef EDOTDOT - inscode(d, ds, de, "EDOTDOT", EDOTDOT, "RFS specific error"); + inscode(d, ds, de, "EDOTDOT", EDOTDOT, "RFS specific error"); #endif #ifdef EISCONN - inscode(d, ds, de, "EISCONN", EISCONN, "Transport endpoint is already connected"); + inscode(d, ds, de, "EISCONN", EISCONN, "Transport endpoint is already connected"); #else #ifdef WSAEISCONN - inscode(d, ds, de, "EISCONN", WSAEISCONN, "Transport endpoint is already connected"); + inscode(d, ds, de, "EISCONN", WSAEISCONN, "Transport endpoint is already connected"); #endif #endif #ifdef ENOANO - inscode(d, ds, de, "ENOANO", ENOANO, "No anode"); + inscode(d, ds, de, "ENOANO", ENOANO, "No anode"); #endif #ifdef ESHUTDOWN - inscode(d, ds, de, "ESHUTDOWN", ESHUTDOWN, "Cannot send after transport endpoint shutdown"); + inscode(d, ds, de, "ESHUTDOWN", ESHUTDOWN, "Cannot send after transport endpoint shutdown"); #else #ifdef WSAESHUTDOWN - inscode(d, ds, de, "ESHUTDOWN", WSAESHUTDOWN, "Cannot send after transport endpoint shutdown"); + inscode(d, ds, de, "ESHUTDOWN", WSAESHUTDOWN, "Cannot send after transport endpoint shutdown"); #endif #endif #ifdef ECHRNG - inscode(d, ds, de, "ECHRNG", ECHRNG, "Channel number out of range"); + inscode(d, ds, de, "ECHRNG", ECHRNG, "Channel number out of range"); #endif #ifdef ELIBBAD - inscode(d, ds, de, "ELIBBAD", ELIBBAD, "Accessing a corrupted shared library"); + inscode(d, ds, de, "ELIBBAD", ELIBBAD, "Accessing a corrupted shared library"); #endif #ifdef ENONET - inscode(d, ds, de, "ENONET", ENONET, "Machine is not on the network"); + inscode(d, ds, de, "ENONET", ENONET, "Machine is not on the network"); #endif #ifdef EBADE - inscode(d, ds, de, "EBADE", EBADE, "Invalid exchange"); + inscode(d, ds, de, "EBADE", EBADE, "Invalid exchange"); #endif #ifdef EBADF - inscode(d, ds, de, "EBADF", EBADF, "Bad file number"); + inscode(d, ds, de, "EBADF", EBADF, "Bad file number"); #else #ifdef WSAEBADF - inscode(d, ds, de, "EBADF", WSAEBADF, "Bad file number"); + inscode(d, ds, de, "EBADF", WSAEBADF, "Bad file number"); #endif #endif #ifdef EMULTIHOP - inscode(d, ds, de, "EMULTIHOP", EMULTIHOP, "Multihop attempted"); + inscode(d, ds, de, "EMULTIHOP", EMULTIHOP, "Multihop attempted"); #endif #ifdef EIO - inscode(d, ds, de, "EIO", EIO, "I/O error"); + inscode(d, ds, de, "EIO", EIO, "I/O error"); #endif #ifdef EUNATCH - inscode(d, ds, de, "EUNATCH", EUNATCH, "Protocol driver not attached"); + inscode(d, ds, de, "EUNATCH", EUNATCH, "Protocol driver not attached"); #endif #ifdef EPROTOTYPE - inscode(d, ds, de, "EPROTOTYPE", EPROTOTYPE, "Protocol wrong type for socket"); + inscode(d, ds, de, "EPROTOTYPE", EPROTOTYPE, "Protocol wrong type for socket"); #else #ifdef WSAEPROTOTYPE - inscode(d, ds, de, "EPROTOTYPE", WSAEPROTOTYPE, "Protocol wrong type for socket"); + inscode(d, ds, de, "EPROTOTYPE", WSAEPROTOTYPE, "Protocol wrong type for socket"); #endif #endif #ifdef ENOSPC - inscode(d, ds, de, "ENOSPC", ENOSPC, "No space left on device"); + inscode(d, ds, de, "ENOSPC", ENOSPC, "No space left on device"); #endif #ifdef ENOEXEC - inscode(d, ds, de, "ENOEXEC", ENOEXEC, "Exec format error"); + inscode(d, ds, de, "ENOEXEC", ENOEXEC, "Exec format error"); #endif #ifdef EALREADY - inscode(d, ds, de, "EALREADY", EALREADY, "Operation already in progress"); + inscode(d, ds, de, "EALREADY", EALREADY, "Operation already in progress"); #else #ifdef WSAEALREADY - inscode(d, ds, de, "EALREADY", WSAEALREADY, "Operation already in progress"); + inscode(d, ds, de, "EALREADY", WSAEALREADY, "Operation already in progress"); #endif #endif #ifdef ENETDOWN - inscode(d, ds, de, "ENETDOWN", ENETDOWN, "Network is down"); + inscode(d, ds, de, "ENETDOWN", ENETDOWN, "Network is down"); #else #ifdef WSAENETDOWN - inscode(d, ds, de, "ENETDOWN", WSAENETDOWN, "Network is down"); + inscode(d, ds, de, "ENETDOWN", WSAENETDOWN, "Network is down"); #endif #endif #ifdef ENOTNAM - inscode(d, ds, de, "ENOTNAM", ENOTNAM, "Not a XENIX named type file"); + inscode(d, ds, de, "ENOTNAM", ENOTNAM, "Not a XENIX named type file"); #endif #ifdef EACCES - inscode(d, ds, de, "EACCES", EACCES, "Permission denied"); + inscode(d, ds, de, "EACCES", EACCES, "Permission denied"); #else #ifdef WSAEACCES - inscode(d, ds, de, "EACCES", WSAEACCES, "Permission denied"); + inscode(d, ds, de, "EACCES", WSAEACCES, "Permission denied"); #endif #endif #ifdef ELNRNG - inscode(d, ds, de, "ELNRNG", ELNRNG, "Link number out of range"); + inscode(d, ds, de, "ELNRNG", ELNRNG, "Link number out of range"); #endif #ifdef EILSEQ - inscode(d, ds, de, "EILSEQ", EILSEQ, "Illegal byte sequence"); + inscode(d, ds, de, "EILSEQ", EILSEQ, "Illegal byte sequence"); #endif #ifdef ENOTDIR - inscode(d, ds, de, "ENOTDIR", ENOTDIR, "Not a directory"); + inscode(d, ds, de, "ENOTDIR", ENOTDIR, "Not a directory"); #endif #ifdef ENOTUNIQ - inscode(d, ds, de, "ENOTUNIQ", ENOTUNIQ, "Name not unique on network"); + inscode(d, ds, de, "ENOTUNIQ", ENOTUNIQ, "Name not unique on network"); #endif #ifdef EPERM - inscode(d, ds, de, "EPERM", EPERM, "Operation not permitted"); + inscode(d, ds, de, "EPERM", EPERM, "Operation not permitted"); #endif #ifdef EDOM - inscode(d, ds, de, "EDOM", EDOM, "Math argument out of domain of func"); + inscode(d, ds, de, "EDOM", EDOM, "Math argument out of domain of func"); #endif #ifdef EXFULL - inscode(d, ds, de, "EXFULL", EXFULL, "Exchange full"); + inscode(d, ds, de, "EXFULL", EXFULL, "Exchange full"); #endif #ifdef ECONNREFUSED - inscode(d, ds, de, "ECONNREFUSED", ECONNREFUSED, "Connection refused"); + inscode(d, ds, de, "ECONNREFUSED", ECONNREFUSED, "Connection refused"); #else #ifdef WSAECONNREFUSED - inscode(d, ds, de, "ECONNREFUSED", WSAECONNREFUSED, "Connection refused"); + inscode(d, ds, de, "ECONNREFUSED", WSAECONNREFUSED, "Connection refused"); #endif #endif #ifdef EISDIR - inscode(d, ds, de, "EISDIR", EISDIR, "Is a directory"); + inscode(d, ds, de, "EISDIR", EISDIR, "Is a directory"); #endif #ifdef EPROTONOSUPPORT - inscode(d, ds, de, "EPROTONOSUPPORT", EPROTONOSUPPORT, "Protocol not supported"); + inscode(d, ds, de, "EPROTONOSUPPORT", EPROTONOSUPPORT, "Protocol not supported"); #else #ifdef WSAEPROTONOSUPPORT - inscode(d, ds, de, "EPROTONOSUPPORT", WSAEPROTONOSUPPORT, "Protocol not supported"); + inscode(d, ds, de, "EPROTONOSUPPORT", WSAEPROTONOSUPPORT, "Protocol not supported"); #endif #endif #ifdef EROFS - inscode(d, ds, de, "EROFS", EROFS, "Read-only file system"); + inscode(d, ds, de, "EROFS", EROFS, "Read-only file system"); #endif #ifdef EADDRNOTAVAIL - inscode(d, ds, de, "EADDRNOTAVAIL", EADDRNOTAVAIL, "Cannot assign requested address"); + inscode(d, ds, de, "EADDRNOTAVAIL", EADDRNOTAVAIL, "Cannot assign requested address"); #else #ifdef WSAEADDRNOTAVAIL - inscode(d, ds, de, "EADDRNOTAVAIL", WSAEADDRNOTAVAIL, "Cannot assign requested address"); + inscode(d, ds, de, "EADDRNOTAVAIL", WSAEADDRNOTAVAIL, "Cannot assign requested address"); #endif #endif #ifdef EIDRM - inscode(d, ds, de, "EIDRM", EIDRM, "Identifier removed"); + inscode(d, ds, de, "EIDRM", EIDRM, "Identifier removed"); #endif #ifdef ECOMM - inscode(d, ds, de, "ECOMM", ECOMM, "Communication error on send"); + inscode(d, ds, de, "ECOMM", ECOMM, "Communication error on send"); #endif #ifdef ESRMNT - inscode(d, ds, de, "ESRMNT", ESRMNT, "Srmount error"); + inscode(d, ds, de, "ESRMNT", ESRMNT, "Srmount error"); #endif #ifdef EREMOTEIO - inscode(d, ds, de, "EREMOTEIO", EREMOTEIO, "Remote I/O error"); + inscode(d, ds, de, "EREMOTEIO", EREMOTEIO, "Remote I/O error"); #endif #ifdef EL3RST - inscode(d, ds, de, "EL3RST", EL3RST, "Level 3 reset"); + inscode(d, ds, de, "EL3RST", EL3RST, "Level 3 reset"); #endif #ifdef EBADMSG - inscode(d, ds, de, "EBADMSG", EBADMSG, "Not a data message"); + inscode(d, ds, de, "EBADMSG", EBADMSG, "Not a data message"); #endif #ifdef ENFILE - inscode(d, ds, de, "ENFILE", ENFILE, "File table overflow"); + inscode(d, ds, de, "ENFILE", ENFILE, "File table overflow"); #endif #ifdef ELIBMAX - inscode(d, ds, de, "ELIBMAX", ELIBMAX, "Attempting to link in too many shared libraries"); + inscode(d, ds, de, "ELIBMAX", ELIBMAX, "Attempting to link in too many shared libraries"); #endif #ifdef ESPIPE - inscode(d, ds, de, "ESPIPE", ESPIPE, "Illegal seek"); + inscode(d, ds, de, "ESPIPE", ESPIPE, "Illegal seek"); #endif #ifdef ENOLINK - inscode(d, ds, de, "ENOLINK", ENOLINK, "Link has been severed"); + inscode(d, ds, de, "ENOLINK", ENOLINK, "Link has been severed"); #endif #ifdef ENETRESET - inscode(d, ds, de, "ENETRESET", ENETRESET, "Network dropped connection because of reset"); + inscode(d, ds, de, "ENETRESET", ENETRESET, "Network dropped connection because of reset"); #else #ifdef WSAENETRESET - inscode(d, ds, de, "ENETRESET", WSAENETRESET, "Network dropped connection because of reset"); + inscode(d, ds, de, "ENETRESET", WSAENETRESET, "Network dropped connection because of reset"); #endif #endif #ifdef ETIMEDOUT - inscode(d, ds, de, "ETIMEDOUT", ETIMEDOUT, "Connection timed out"); + inscode(d, ds, de, "ETIMEDOUT", ETIMEDOUT, "Connection timed out"); #else #ifdef WSAETIMEDOUT - inscode(d, ds, de, "ETIMEDOUT", WSAETIMEDOUT, "Connection timed out"); + inscode(d, ds, de, "ETIMEDOUT", WSAETIMEDOUT, "Connection timed out"); #endif #endif #ifdef ENOENT - inscode(d, ds, de, "ENOENT", ENOENT, "No such file or directory"); + inscode(d, ds, de, "ENOENT", ENOENT, "No such file or directory"); #endif #ifdef EEXIST - inscode(d, ds, de, "EEXIST", EEXIST, "File exists"); + inscode(d, ds, de, "EEXIST", EEXIST, "File exists"); #endif #ifdef EDQUOT - inscode(d, ds, de, "EDQUOT", EDQUOT, "Quota exceeded"); + inscode(d, ds, de, "EDQUOT", EDQUOT, "Quota exceeded"); #else #ifdef WSAEDQUOT - inscode(d, ds, de, "EDQUOT", WSAEDQUOT, "Quota exceeded"); + inscode(d, ds, de, "EDQUOT", WSAEDQUOT, "Quota exceeded"); #endif #endif #ifdef ENOSTR - inscode(d, ds, de, "ENOSTR", ENOSTR, "Device not a stream"); + inscode(d, ds, de, "ENOSTR", ENOSTR, "Device not a stream"); #endif #ifdef EBADSLT - inscode(d, ds, de, "EBADSLT", EBADSLT, "Invalid slot"); + inscode(d, ds, de, "EBADSLT", EBADSLT, "Invalid slot"); #endif #ifdef EBADRQC - inscode(d, ds, de, "EBADRQC", EBADRQC, "Invalid request code"); + inscode(d, ds, de, "EBADRQC", EBADRQC, "Invalid request code"); #endif #ifdef ELIBACC - inscode(d, ds, de, "ELIBACC", ELIBACC, "Can not access a needed shared library"); + inscode(d, ds, de, "ELIBACC", ELIBACC, "Can not access a needed shared library"); #endif #ifdef EFAULT - inscode(d, ds, de, "EFAULT", EFAULT, "Bad address"); + inscode(d, ds, de, "EFAULT", EFAULT, "Bad address"); #else #ifdef WSAEFAULT - inscode(d, ds, de, "EFAULT", WSAEFAULT, "Bad address"); + inscode(d, ds, de, "EFAULT", WSAEFAULT, "Bad address"); #endif #endif #ifdef EFBIG - inscode(d, ds, de, "EFBIG", EFBIG, "File too large"); + inscode(d, ds, de, "EFBIG", EFBIG, "File too large"); #endif #ifdef EDEADLK - inscode(d, ds, de, "EDEADLK", EDEADLK, "Resource deadlock would occur"); + inscode(d, ds, de, "EDEADLK", EDEADLK, "Resource deadlock would occur"); #endif #ifdef ENOTCONN - inscode(d, ds, de, "ENOTCONN", ENOTCONN, "Transport endpoint is not connected"); + inscode(d, ds, de, "ENOTCONN", ENOTCONN, "Transport endpoint is not connected"); #else #ifdef WSAENOTCONN - inscode(d, ds, de, "ENOTCONN", WSAENOTCONN, "Transport endpoint is not connected"); + inscode(d, ds, de, "ENOTCONN", WSAENOTCONN, "Transport endpoint is not connected"); #endif #endif #ifdef EDESTADDRREQ - inscode(d, ds, de, "EDESTADDRREQ", EDESTADDRREQ, "Destination address required"); + inscode(d, ds, de, "EDESTADDRREQ", EDESTADDRREQ, "Destination address required"); #else #ifdef WSAEDESTADDRREQ - inscode(d, ds, de, "EDESTADDRREQ", WSAEDESTADDRREQ, "Destination address required"); + inscode(d, ds, de, "EDESTADDRREQ", WSAEDESTADDRREQ, "Destination address required"); #endif #endif #ifdef ELIBSCN - inscode(d, ds, de, "ELIBSCN", ELIBSCN, ".lib section in a.out corrupted"); + inscode(d, ds, de, "ELIBSCN", ELIBSCN, ".lib section in a.out corrupted"); #endif #ifdef ENOLCK - inscode(d, ds, de, "ENOLCK", ENOLCK, "No record locks available"); + inscode(d, ds, de, "ENOLCK", ENOLCK, "No record locks available"); #endif #ifdef EISNAM - inscode(d, ds, de, "EISNAM", EISNAM, "Is a named type file"); + inscode(d, ds, de, "EISNAM", EISNAM, "Is a named type file"); #endif #ifdef ECONNABORTED - inscode(d, ds, de, "ECONNABORTED", ECONNABORTED, "Software caused connection abort"); + inscode(d, ds, de, "ECONNABORTED", ECONNABORTED, "Software caused connection abort"); #else #ifdef WSAECONNABORTED - inscode(d, ds, de, "ECONNABORTED", WSAECONNABORTED, "Software caused connection abort"); + inscode(d, ds, de, "ECONNABORTED", WSAECONNABORTED, "Software caused connection abort"); #endif #endif #ifdef ENETUNREACH - inscode(d, ds, de, "ENETUNREACH", ENETUNREACH, "Network is unreachable"); + inscode(d, ds, de, "ENETUNREACH", ENETUNREACH, "Network is unreachable"); #else #ifdef WSAENETUNREACH - inscode(d, ds, de, "ENETUNREACH", WSAENETUNREACH, "Network is unreachable"); + inscode(d, ds, de, "ENETUNREACH", WSAENETUNREACH, "Network is unreachable"); #endif #endif #ifdef ESTALE - inscode(d, ds, de, "ESTALE", ESTALE, "Stale NFS file handle"); + inscode(d, ds, de, "ESTALE", ESTALE, "Stale NFS file handle"); #else #ifdef WSAESTALE - inscode(d, ds, de, "ESTALE", WSAESTALE, "Stale NFS file handle"); + inscode(d, ds, de, "ESTALE", WSAESTALE, "Stale NFS file handle"); #endif #endif #ifdef ENOSR - inscode(d, ds, de, "ENOSR", ENOSR, "Out of streams resources"); + inscode(d, ds, de, "ENOSR", ENOSR, "Out of streams resources"); #endif #ifdef ENOMEM - inscode(d, ds, de, "ENOMEM", ENOMEM, "Out of memory"); + inscode(d, ds, de, "ENOMEM", ENOMEM, "Out of memory"); #endif #ifdef ENOTSOCK - inscode(d, ds, de, "ENOTSOCK", ENOTSOCK, "Socket operation on non-socket"); + inscode(d, ds, de, "ENOTSOCK", ENOTSOCK, "Socket operation on non-socket"); #else #ifdef WSAENOTSOCK - inscode(d, ds, de, "ENOTSOCK", WSAENOTSOCK, "Socket operation on non-socket"); + inscode(d, ds, de, "ENOTSOCK", WSAENOTSOCK, "Socket operation on non-socket"); #endif #endif #ifdef ESTRPIPE - inscode(d, ds, de, "ESTRPIPE", ESTRPIPE, "Streams pipe error"); + inscode(d, ds, de, "ESTRPIPE", ESTRPIPE, "Streams pipe error"); #endif #ifdef EMLINK - inscode(d, ds, de, "EMLINK", EMLINK, "Too many links"); + inscode(d, ds, de, "EMLINK", EMLINK, "Too many links"); #endif #ifdef ERANGE - inscode(d, ds, de, "ERANGE", ERANGE, "Math result not representable"); + inscode(d, ds, de, "ERANGE", ERANGE, "Math result not representable"); #endif #ifdef ELIBEXEC - inscode(d, ds, de, "ELIBEXEC", ELIBEXEC, "Cannot exec a shared library directly"); + inscode(d, ds, de, "ELIBEXEC", ELIBEXEC, "Cannot exec a shared library directly"); #endif #ifdef EL3HLT - inscode(d, ds, de, "EL3HLT", EL3HLT, "Level 3 halted"); + inscode(d, ds, de, "EL3HLT", EL3HLT, "Level 3 halted"); #endif #ifdef ECONNRESET - inscode(d, ds, de, "ECONNRESET", ECONNRESET, "Connection reset by peer"); + inscode(d, ds, de, "ECONNRESET", ECONNRESET, "Connection reset by peer"); #else #ifdef WSAECONNRESET - inscode(d, ds, de, "ECONNRESET", WSAECONNRESET, "Connection reset by peer"); + inscode(d, ds, de, "ECONNRESET", WSAECONNRESET, "Connection reset by peer"); #endif #endif #ifdef EADDRINUSE - inscode(d, ds, de, "EADDRINUSE", EADDRINUSE, "Address already in use"); + inscode(d, ds, de, "EADDRINUSE", EADDRINUSE, "Address already in use"); #else #ifdef WSAEADDRINUSE - inscode(d, ds, de, "EADDRINUSE", WSAEADDRINUSE, "Address already in use"); + inscode(d, ds, de, "EADDRINUSE", WSAEADDRINUSE, "Address already in use"); #endif #endif #ifdef EOPNOTSUPP - inscode(d, ds, de, "EOPNOTSUPP", EOPNOTSUPP, "Operation not supported on transport endpoint"); + inscode(d, ds, de, "EOPNOTSUPP", EOPNOTSUPP, "Operation not supported on transport endpoint"); #else #ifdef WSAEOPNOTSUPP - inscode(d, ds, de, "EOPNOTSUPP", WSAEOPNOTSUPP, "Operation not supported on transport endpoint"); + inscode(d, ds, de, "EOPNOTSUPP", WSAEOPNOTSUPP, "Operation not supported on transport endpoint"); #endif #endif #ifdef EREMCHG - inscode(d, ds, de, "EREMCHG", EREMCHG, "Remote address changed"); + inscode(d, ds, de, "EREMCHG", EREMCHG, "Remote address changed"); #endif #ifdef EAGAIN - inscode(d, ds, de, "EAGAIN", EAGAIN, "Try again"); + inscode(d, ds, de, "EAGAIN", EAGAIN, "Try again"); #endif #ifdef ENAMETOOLONG - inscode(d, ds, de, "ENAMETOOLONG", ENAMETOOLONG, "File name too long"); + inscode(d, ds, de, "ENAMETOOLONG", ENAMETOOLONG, "File name too long"); #else #ifdef WSAENAMETOOLONG - inscode(d, ds, de, "ENAMETOOLONG", WSAENAMETOOLONG, "File name too long"); + inscode(d, ds, de, "ENAMETOOLONG", WSAENAMETOOLONG, "File name too long"); #endif #endif #ifdef ENOTTY - inscode(d, ds, de, "ENOTTY", ENOTTY, "Not a typewriter"); + inscode(d, ds, de, "ENOTTY", ENOTTY, "Not a typewriter"); #endif #ifdef ERESTART - inscode(d, ds, de, "ERESTART", ERESTART, "Interrupted system call should be restarted"); + inscode(d, ds, de, "ERESTART", ERESTART, "Interrupted system call should be restarted"); #endif #ifdef ESOCKTNOSUPPORT - inscode(d, ds, de, "ESOCKTNOSUPPORT", ESOCKTNOSUPPORT, "Socket type not supported"); + inscode(d, ds, de, "ESOCKTNOSUPPORT", ESOCKTNOSUPPORT, "Socket type not supported"); #else #ifdef WSAESOCKTNOSUPPORT - inscode(d, ds, de, "ESOCKTNOSUPPORT", WSAESOCKTNOSUPPORT, "Socket type not supported"); + inscode(d, ds, de, "ESOCKTNOSUPPORT", WSAESOCKTNOSUPPORT, "Socket type not supported"); #endif #endif #ifdef ETIME - inscode(d, ds, de, "ETIME", ETIME, "Timer expired"); + inscode(d, ds, de, "ETIME", ETIME, "Timer expired"); #endif #ifdef EBFONT - inscode(d, ds, de, "EBFONT", EBFONT, "Bad font file format"); + inscode(d, ds, de, "EBFONT", EBFONT, "Bad font file format"); #endif #ifdef EDEADLOCK - inscode(d, ds, de, "EDEADLOCK", EDEADLOCK, "Error EDEADLOCK"); + inscode(d, ds, de, "EDEADLOCK", EDEADLOCK, "Error EDEADLOCK"); #endif #ifdef ETOOMANYREFS - inscode(d, ds, de, "ETOOMANYREFS", ETOOMANYREFS, "Too many references: cannot splice"); + inscode(d, ds, de, "ETOOMANYREFS", ETOOMANYREFS, "Too many references: cannot splice"); #else #ifdef WSAETOOMANYREFS - inscode(d, ds, de, "ETOOMANYREFS", WSAETOOMANYREFS, "Too many references: cannot splice"); + inscode(d, ds, de, "ETOOMANYREFS", WSAETOOMANYREFS, "Too many references: cannot splice"); #endif #endif #ifdef EMFILE - inscode(d, ds, de, "EMFILE", EMFILE, "Too many open files"); + inscode(d, ds, de, "EMFILE", EMFILE, "Too many open files"); #else #ifdef WSAEMFILE - inscode(d, ds, de, "EMFILE", WSAEMFILE, "Too many open files"); + inscode(d, ds, de, "EMFILE", WSAEMFILE, "Too many open files"); #endif #endif #ifdef ETXTBSY - inscode(d, ds, de, "ETXTBSY", ETXTBSY, "Text file busy"); + inscode(d, ds, de, "ETXTBSY", ETXTBSY, "Text file busy"); #endif #ifdef EINPROGRESS - inscode(d, ds, de, "EINPROGRESS", EINPROGRESS, "Operation now in progress"); + inscode(d, ds, de, "EINPROGRESS", EINPROGRESS, "Operation now in progress"); #else #ifdef WSAEINPROGRESS - inscode(d, ds, de, "EINPROGRESS", WSAEINPROGRESS, "Operation now in progress"); + inscode(d, ds, de, "EINPROGRESS", WSAEINPROGRESS, "Operation now in progress"); #endif #endif #ifdef ENXIO - inscode(d, ds, de, "ENXIO", ENXIO, "No such device or address"); + inscode(d, ds, de, "ENXIO", ENXIO, "No such device or address"); #endif #ifdef ENOPKG - inscode(d, ds, de, "ENOPKG", ENOPKG, "Package not installed"); + inscode(d, ds, de, "ENOPKG", ENOPKG, "Package not installed"); #endif #ifdef WSASY - inscode(d, ds, de, "WSASY", WSASY, "Error WSASY"); + inscode(d, ds, de, "WSASY", WSASY, "Error WSASY"); #endif #ifdef WSAEHOSTDOWN - inscode(d, ds, de, "WSAEHOSTDOWN", WSAEHOSTDOWN, "Host is down"); + inscode(d, ds, de, "WSAEHOSTDOWN", WSAEHOSTDOWN, "Host is down"); #endif #ifdef WSAENETDOWN - inscode(d, ds, de, "WSAENETDOWN", WSAENETDOWN, "Network is down"); + inscode(d, ds, de, "WSAENETDOWN", WSAENETDOWN, "Network is down"); #endif #ifdef WSAENOTSOCK - inscode(d, ds, de, "WSAENOTSOCK", WSAENOTSOCK, "Socket operation on non-socket"); + inscode(d, ds, de, "WSAENOTSOCK", WSAENOTSOCK, "Socket operation on non-socket"); #endif #ifdef WSAEHOSTUNREACH - inscode(d, ds, de, "WSAEHOSTUNREACH", WSAEHOSTUNREACH, "No route to host"); + inscode(d, ds, de, "WSAEHOSTUNREACH", WSAEHOSTUNREACH, "No route to host"); #endif #ifdef WSAELOOP - inscode(d, ds, de, "WSAELOOP", WSAELOOP, "Too many symbolic links encountered"); + inscode(d, ds, de, "WSAELOOP", WSAELOOP, "Too many symbolic links encountered"); #endif #ifdef WSAEMFILE - inscode(d, ds, de, "WSAEMFILE", WSAEMFILE, "Too many open files"); + inscode(d, ds, de, "WSAEMFILE", WSAEMFILE, "Too many open files"); #endif #ifdef WSAESTALE - inscode(d, ds, de, "WSAESTALE", WSAESTALE, "Stale NFS file handle"); + inscode(d, ds, de, "WSAESTALE", WSAESTALE, "Stale NFS file handle"); #endif #ifdef WSAVERNOTSUPPORTED - inscode(d, ds, de, "WSAVERNOTSUPPORTED", WSAVERNOTSUPPORTED, "Error WSAVERNOTSUPPORTED"); + inscode(d, ds, de, "WSAVERNOTSUPPORTED", WSAVERNOTSUPPORTED, "Error WSAVERNOTSUPPORTED"); #endif #ifdef WSAENETUNREACH - inscode(d, ds, de, "WSAENETUNREACH", WSAENETUNREACH, "Network is unreachable"); + inscode(d, ds, de, "WSAENETUNREACH", WSAENETUNREACH, "Network is unreachable"); #endif #ifdef WSAEPROCLIM - inscode(d, ds, de, "WSAEPROCLIM", WSAEPROCLIM, "Error WSAEPROCLIM"); + inscode(d, ds, de, "WSAEPROCLIM", WSAEPROCLIM, "Error WSAEPROCLIM"); #endif #ifdef WSAEFAULT - inscode(d, ds, de, "WSAEFAULT", WSAEFAULT, "Bad address"); + inscode(d, ds, de, "WSAEFAULT", WSAEFAULT, "Bad address"); #endif #ifdef WSANOTINITIALISED - inscode(d, ds, de, "WSANOTINITIALISED", WSANOTINITIALISED, "Error WSANOTINITIALISED"); + inscode(d, ds, de, "WSANOTINITIALISED", WSANOTINITIALISED, "Error WSANOTINITIALISED"); #endif #ifdef WSAEUSERS - inscode(d, ds, de, "WSAEUSERS", WSAEUSERS, "Too many users"); + inscode(d, ds, de, "WSAEUSERS", WSAEUSERS, "Too many users"); #endif #ifdef WSAMAKEASYNCREPL - inscode(d, ds, de, "WSAMAKEASYNCREPL", WSAMAKEASYNCREPL, "Error WSAMAKEASYNCREPL"); + inscode(d, ds, de, "WSAMAKEASYNCREPL", WSAMAKEASYNCREPL, "Error WSAMAKEASYNCREPL"); #endif #ifdef WSAENOPROTOOPT - inscode(d, ds, de, "WSAENOPROTOOPT", WSAENOPROTOOPT, "Protocol not available"); + inscode(d, ds, de, "WSAENOPROTOOPT", WSAENOPROTOOPT, "Protocol not available"); #endif #ifdef WSAECONNABORTED - inscode(d, ds, de, "WSAECONNABORTED", WSAECONNABORTED, "Software caused connection abort"); + inscode(d, ds, de, "WSAECONNABORTED", WSAECONNABORTED, "Software caused connection abort"); #endif #ifdef WSAENAMETOOLONG - inscode(d, ds, de, "WSAENAMETOOLONG", WSAENAMETOOLONG, "File name too long"); + inscode(d, ds, de, "WSAENAMETOOLONG", WSAENAMETOOLONG, "File name too long"); #endif #ifdef WSAENOTEMPTY - inscode(d, ds, de, "WSAENOTEMPTY", WSAENOTEMPTY, "Directory not empty"); + inscode(d, ds, de, "WSAENOTEMPTY", WSAENOTEMPTY, "Directory not empty"); #endif #ifdef WSAESHUTDOWN - inscode(d, ds, de, "WSAESHUTDOWN", WSAESHUTDOWN, "Cannot send after transport endpoint shutdown"); + inscode(d, ds, de, "WSAESHUTDOWN", WSAESHUTDOWN, "Cannot send after transport endpoint shutdown"); #endif #ifdef WSAEAFNOSUPPORT - inscode(d, ds, de, "WSAEAFNOSUPPORT", WSAEAFNOSUPPORT, "Address family not supported by protocol"); + inscode(d, ds, de, "WSAEAFNOSUPPORT", WSAEAFNOSUPPORT, "Address family not supported by protocol"); #endif #ifdef WSAETOOMANYREFS - inscode(d, ds, de, "WSAETOOMANYREFS", WSAETOOMANYREFS, "Too many references: cannot splice"); + inscode(d, ds, de, "WSAETOOMANYREFS", WSAETOOMANYREFS, "Too many references: cannot splice"); #endif #ifdef WSAEACCES - inscode(d, ds, de, "WSAEACCES", WSAEACCES, "Permission denied"); + inscode(d, ds, de, "WSAEACCES", WSAEACCES, "Permission denied"); #endif #ifdef WSATR - inscode(d, ds, de, "WSATR", WSATR, "Error WSATR"); + inscode(d, ds, de, "WSATR", WSATR, "Error WSATR"); #endif #ifdef WSABASEERR - inscode(d, ds, de, "WSABASEERR", WSABASEERR, "Error WSABASEERR"); + inscode(d, ds, de, "WSABASEERR", WSABASEERR, "Error WSABASEERR"); #endif #ifdef WSADESCRIPTIO - inscode(d, ds, de, "WSADESCRIPTIO", WSADESCRIPTIO, "Error WSADESCRIPTIO"); + inscode(d, ds, de, "WSADESCRIPTIO", WSADESCRIPTIO, "Error WSADESCRIPTIO"); #endif #ifdef WSAEMSGSIZE - inscode(d, ds, de, "WSAEMSGSIZE", WSAEMSGSIZE, "Message too long"); + inscode(d, ds, de, "WSAEMSGSIZE", WSAEMSGSIZE, "Message too long"); #endif #ifdef WSAEBADF - inscode(d, ds, de, "WSAEBADF", WSAEBADF, "Bad file number"); + inscode(d, ds, de, "WSAEBADF", WSAEBADF, "Bad file number"); #endif #ifdef WSAECONNRESET - inscode(d, ds, de, "WSAECONNRESET", WSAECONNRESET, "Connection reset by peer"); + inscode(d, ds, de, "WSAECONNRESET", WSAECONNRESET, "Connection reset by peer"); #endif #ifdef WSAGETSELECTERRO - inscode(d, ds, de, "WSAGETSELECTERRO", WSAGETSELECTERRO, "Error WSAGETSELECTERRO"); + inscode(d, ds, de, "WSAGETSELECTERRO", WSAGETSELECTERRO, "Error WSAGETSELECTERRO"); #endif #ifdef WSAETIMEDOUT - inscode(d, ds, de, "WSAETIMEDOUT", WSAETIMEDOUT, "Connection timed out"); + inscode(d, ds, de, "WSAETIMEDOUT", WSAETIMEDOUT, "Connection timed out"); #endif #ifdef WSAENOBUFS - inscode(d, ds, de, "WSAENOBUFS", WSAENOBUFS, "No buffer space available"); + inscode(d, ds, de, "WSAENOBUFS", WSAENOBUFS, "No buffer space available"); #endif #ifdef WSAEDISCON - inscode(d, ds, de, "WSAEDISCON", WSAEDISCON, "Error WSAEDISCON"); + inscode(d, ds, de, "WSAEDISCON", WSAEDISCON, "Error WSAEDISCON"); #endif #ifdef WSAEINTR - inscode(d, ds, de, "WSAEINTR", WSAEINTR, "Interrupted system call"); + inscode(d, ds, de, "WSAEINTR", WSAEINTR, "Interrupted system call"); #endif #ifdef WSAEPROTOTYPE - inscode(d, ds, de, "WSAEPROTOTYPE", WSAEPROTOTYPE, "Protocol wrong type for socket"); + inscode(d, ds, de, "WSAEPROTOTYPE", WSAEPROTOTYPE, "Protocol wrong type for socket"); #endif #ifdef WSAHOS - inscode(d, ds, de, "WSAHOS", WSAHOS, "Error WSAHOS"); + inscode(d, ds, de, "WSAHOS", WSAHOS, "Error WSAHOS"); #endif #ifdef WSAEADDRINUSE - inscode(d, ds, de, "WSAEADDRINUSE", WSAEADDRINUSE, "Address already in use"); + inscode(d, ds, de, "WSAEADDRINUSE", WSAEADDRINUSE, "Address already in use"); #endif #ifdef WSAEADDRNOTAVAIL - inscode(d, ds, de, "WSAEADDRNOTAVAIL", WSAEADDRNOTAVAIL, "Cannot assign requested address"); + inscode(d, ds, de, "WSAEADDRNOTAVAIL", WSAEADDRNOTAVAIL, "Cannot assign requested address"); #endif #ifdef WSAEALREADY - inscode(d, ds, de, "WSAEALREADY", WSAEALREADY, "Operation already in progress"); + inscode(d, ds, de, "WSAEALREADY", WSAEALREADY, "Operation already in progress"); #endif #ifdef WSAEPROTONOSUPPORT - inscode(d, ds, de, "WSAEPROTONOSUPPORT", WSAEPROTONOSUPPORT, "Protocol not supported"); + inscode(d, ds, de, "WSAEPROTONOSUPPORT", WSAEPROTONOSUPPORT, "Protocol not supported"); #endif #ifdef WSASYSNOTREADY - inscode(d, ds, de, "WSASYSNOTREADY", WSASYSNOTREADY, "Error WSASYSNOTREADY"); + inscode(d, ds, de, "WSASYSNOTREADY", WSASYSNOTREADY, "Error WSASYSNOTREADY"); #endif #ifdef WSAEWOULDBLOCK - inscode(d, ds, de, "WSAEWOULDBLOCK", WSAEWOULDBLOCK, "Operation would block"); + inscode(d, ds, de, "WSAEWOULDBLOCK", WSAEWOULDBLOCK, "Operation would block"); #endif #ifdef WSAEPFNOSUPPORT - inscode(d, ds, de, "WSAEPFNOSUPPORT", WSAEPFNOSUPPORT, "Protocol family not supported"); + inscode(d, ds, de, "WSAEPFNOSUPPORT", WSAEPFNOSUPPORT, "Protocol family not supported"); #endif #ifdef WSAEOPNOTSUPP - inscode(d, ds, de, "WSAEOPNOTSUPP", WSAEOPNOTSUPP, "Operation not supported on transport endpoint"); + inscode(d, ds, de, "WSAEOPNOTSUPP", WSAEOPNOTSUPP, "Operation not supported on transport endpoint"); #endif #ifdef WSAEISCONN - inscode(d, ds, de, "WSAEISCONN", WSAEISCONN, "Transport endpoint is already connected"); + inscode(d, ds, de, "WSAEISCONN", WSAEISCONN, "Transport endpoint is already connected"); #endif #ifdef WSAEDQUOT - inscode(d, ds, de, "WSAEDQUOT", WSAEDQUOT, "Quota exceeded"); + inscode(d, ds, de, "WSAEDQUOT", WSAEDQUOT, "Quota exceeded"); #endif #ifdef WSAENOTCONN - inscode(d, ds, de, "WSAENOTCONN", WSAENOTCONN, "Transport endpoint is not connected"); + inscode(d, ds, de, "WSAENOTCONN", WSAENOTCONN, "Transport endpoint is not connected"); #endif #ifdef WSAEREMOTE - inscode(d, ds, de, "WSAEREMOTE", WSAEREMOTE, "Object is remote"); + inscode(d, ds, de, "WSAEREMOTE", WSAEREMOTE, "Object is remote"); #endif #ifdef WSAEINVAL - inscode(d, ds, de, "WSAEINVAL", WSAEINVAL, "Invalid argument"); + inscode(d, ds, de, "WSAEINVAL", WSAEINVAL, "Invalid argument"); #endif #ifdef WSAEINPROGRESS - inscode(d, ds, de, "WSAEINPROGRESS", WSAEINPROGRESS, "Operation now in progress"); + inscode(d, ds, de, "WSAEINPROGRESS", WSAEINPROGRESS, "Operation now in progress"); #endif #ifdef WSAGETSELECTEVEN - inscode(d, ds, de, "WSAGETSELECTEVEN", WSAGETSELECTEVEN, "Error WSAGETSELECTEVEN"); + inscode(d, ds, de, "WSAGETSELECTEVEN", WSAGETSELECTEVEN, "Error WSAGETSELECTEVEN"); #endif #ifdef WSAESOCKTNOSUPPORT - inscode(d, ds, de, "WSAESOCKTNOSUPPORT", WSAESOCKTNOSUPPORT, "Socket type not supported"); + inscode(d, ds, de, "WSAESOCKTNOSUPPORT", WSAESOCKTNOSUPPORT, "Socket type not supported"); #endif #ifdef WSAGETASYNCERRO - inscode(d, ds, de, "WSAGETASYNCERRO", WSAGETASYNCERRO, "Error WSAGETASYNCERRO"); + inscode(d, ds, de, "WSAGETASYNCERRO", WSAGETASYNCERRO, "Error WSAGETASYNCERRO"); #endif #ifdef WSAMAKESELECTREPL - inscode(d, ds, de, "WSAMAKESELECTREPL", WSAMAKESELECTREPL, "Error WSAMAKESELECTREPL"); + inscode(d, ds, de, "WSAMAKESELECTREPL", WSAMAKESELECTREPL, "Error WSAMAKESELECTREPL"); #endif #ifdef WSAGETASYNCBUFLE - inscode(d, ds, de, "WSAGETASYNCBUFLE", WSAGETASYNCBUFLE, "Error WSAGETASYNCBUFLE"); + inscode(d, ds, de, "WSAGETASYNCBUFLE", WSAGETASYNCBUFLE, "Error WSAGETASYNCBUFLE"); #endif #ifdef WSAEDESTADDRREQ - inscode(d, ds, de, "WSAEDESTADDRREQ", WSAEDESTADDRREQ, "Destination address required"); + inscode(d, ds, de, "WSAEDESTADDRREQ", WSAEDESTADDRREQ, "Destination address required"); #endif #ifdef WSAECONNREFUSED - inscode(d, ds, de, "WSAECONNREFUSED", WSAECONNREFUSED, "Connection refused"); + inscode(d, ds, de, "WSAECONNREFUSED", WSAECONNREFUSED, "Connection refused"); #endif #ifdef WSAENETRESET - inscode(d, ds, de, "WSAENETRESET", WSAENETRESET, "Network dropped connection because of reset"); + inscode(d, ds, de, "WSAENETRESET", WSAENETRESET, "Network dropped connection because of reset"); #endif #ifdef WSAN - inscode(d, ds, de, "WSAN", WSAN, "Error WSAN"); + inscode(d, ds, de, "WSAN", WSAN, "Error WSAN"); #endif - Py_DECREF(de); - return m; + Py_DECREF(de); + return m; } Modified: python/branches/py3k-jit/Modules/fcntlmodule.c ============================================================================== --- python/branches/py3k-jit/Modules/fcntlmodule.c (original) +++ python/branches/py3k-jit/Modules/fcntlmodule.c Mon May 10 23:55:43 2010 @@ -21,7 +21,7 @@ int fd = PyObject_AsFileDescriptor(object); if (fd < 0) - return 0; + return 0; *target = fd; return 1; } @@ -32,48 +32,48 @@ static PyObject * fcntl_fcntl(PyObject *self, PyObject *args) { - int fd; - int code; - long arg; - int ret; - char *str; - Py_ssize_t len; - char buf[1024]; - - if (PyArg_ParseTuple(args, "O&is#:fcntl", - conv_descriptor, &fd, &code, &str, &len)) { - if (len > sizeof buf) { - PyErr_SetString(PyExc_ValueError, - "fcntl string arg too long"); - return NULL; - } - memcpy(buf, str, len); - Py_BEGIN_ALLOW_THREADS - ret = fcntl(fd, code, buf); - Py_END_ALLOW_THREADS - if (ret < 0) { - PyErr_SetFromErrno(PyExc_IOError); - return NULL; - } - return PyBytes_FromStringAndSize(buf, len); - } - - PyErr_Clear(); - arg = 0; - if (!PyArg_ParseTuple(args, - "O&i|l;fcntl requires a file or file descriptor," - " an integer and optionally a third integer or a string", - conv_descriptor, &fd, &code, &arg)) { - return NULL; - } - Py_BEGIN_ALLOW_THREADS - ret = fcntl(fd, code, arg); - Py_END_ALLOW_THREADS - if (ret < 0) { - PyErr_SetFromErrno(PyExc_IOError); - return NULL; - } - return PyLong_FromLong((long)ret); + int fd; + int code; + long arg; + int ret; + char *str; + Py_ssize_t len; + char buf[1024]; + + if (PyArg_ParseTuple(args, "O&is#:fcntl", + conv_descriptor, &fd, &code, &str, &len)) { + if (len > sizeof buf) { + PyErr_SetString(PyExc_ValueError, + "fcntl string arg too long"); + return NULL; + } + memcpy(buf, str, len); + Py_BEGIN_ALLOW_THREADS + ret = fcntl(fd, code, buf); + Py_END_ALLOW_THREADS + if (ret < 0) { + PyErr_SetFromErrno(PyExc_IOError); + return NULL; + } + return PyBytes_FromStringAndSize(buf, len); + } + + PyErr_Clear(); + arg = 0; + if (!PyArg_ParseTuple(args, + "O&i|l;fcntl requires a file or file descriptor," + " an integer and optionally a third integer or a string", + conv_descriptor, &fd, &code, &arg)) { + return NULL; + } + Py_BEGIN_ALLOW_THREADS + ret = fcntl(fd, code, arg); + Py_END_ALLOW_THREADS + if (ret < 0) { + PyErr_SetFromErrno(PyExc_IOError); + return NULL; + } + return PyLong_FromLong((long)ret); } PyDoc_STRVAR(fcntl_doc, @@ -96,128 +96,128 @@ fcntl_ioctl(PyObject *self, PyObject *args) { #define IOCTL_BUFSZ 1024 - int fd; - /* In PyArg_ParseTuple below, we use the unsigned non-checked 'I' - format for the 'code' parameter because Python turns 0x8000000 - into either a large positive number (PyLong or PyInt on 64-bit - platforms) or a negative number on others (32-bit PyInt) - whereas the system expects it to be a 32bit bit field value - regardless of it being passed as an int or unsigned long on - various platforms. See the termios.TIOCSWINSZ constant across - platforms for an example of thise. - - If any of the 64bit platforms ever decide to use more than 32bits - in their unsigned long ioctl codes this will break and need - special casing based on the platform being built on. - */ - unsigned int code; - int arg; - int ret; - Py_buffer pstr; - char *str; - Py_ssize_t len; - int mutate_arg = 1; - char buf[IOCTL_BUFSZ+1]; /* argument plus NUL byte */ - - if (PyArg_ParseTuple(args, "O&Iw*|i:ioctl", - conv_descriptor, &fd, &code, - &pstr, &mutate_arg)) { - char *arg; - str = pstr.buf; - len = pstr.len; - - if (mutate_arg) { - if (len <= IOCTL_BUFSZ) { - memcpy(buf, str, len); - buf[len] = '\0'; - arg = buf; - } - else { - arg = str; - } - } - else { - if (len > IOCTL_BUFSZ) { - PyBuffer_Release(&pstr); - PyErr_SetString(PyExc_ValueError, - "ioctl string arg too long"); - return NULL; - } - else { - memcpy(buf, str, len); - buf[len] = '\0'; - arg = buf; - } - } - if (buf == arg) { - Py_BEGIN_ALLOW_THREADS /* think array.resize() */ - ret = ioctl(fd, code, arg); - Py_END_ALLOW_THREADS - } - else { - ret = ioctl(fd, code, arg); - } - if (mutate_arg && (len < IOCTL_BUFSZ)) { - memcpy(str, buf, len); - } - PyBuffer_Release(&pstr); /* No further access to str below this point */ - if (ret < 0) { - PyErr_SetFromErrno(PyExc_IOError); - return NULL; - } - if (mutate_arg) { - return PyLong_FromLong(ret); - } - else { - return PyBytes_FromStringAndSize(buf, len); - } - } - - PyErr_Clear(); - if (PyArg_ParseTuple(args, "O&Is*:ioctl", - conv_descriptor, &fd, &code, &pstr)) { - str = pstr.buf; - len = pstr.len; - if (len > IOCTL_BUFSZ) { - PyBuffer_Release(&pstr); - PyErr_SetString(PyExc_ValueError, - "ioctl string arg too long"); - return NULL; - } - memcpy(buf, str, len); - buf[len] = '\0'; - Py_BEGIN_ALLOW_THREADS - ret = ioctl(fd, code, buf); - Py_END_ALLOW_THREADS - if (ret < 0) { - PyBuffer_Release(&pstr); - PyErr_SetFromErrno(PyExc_IOError); - return NULL; - } - PyBuffer_Release(&pstr); - return PyBytes_FromStringAndSize(buf, len); - } - - PyErr_Clear(); - arg = 0; - if (!PyArg_ParseTuple(args, - "O&I|i;ioctl requires a file or file descriptor," - " an integer and optionally an integer or buffer argument", - conv_descriptor, &fd, &code, &arg)) { - return NULL; - } - Py_BEGIN_ALLOW_THREADS + int fd; + /* In PyArg_ParseTuple below, we use the unsigned non-checked 'I' + format for the 'code' parameter because Python turns 0x8000000 + into either a large positive number (PyLong or PyInt on 64-bit + platforms) or a negative number on others (32-bit PyInt) + whereas the system expects it to be a 32bit bit field value + regardless of it being passed as an int or unsigned long on + various platforms. See the termios.TIOCSWINSZ constant across + platforms for an example of thise. + + If any of the 64bit platforms ever decide to use more than 32bits + in their unsigned long ioctl codes this will break and need + special casing based on the platform being built on. + */ + unsigned int code; + int arg; + int ret; + Py_buffer pstr; + char *str; + Py_ssize_t len; + int mutate_arg = 1; + char buf[IOCTL_BUFSZ+1]; /* argument plus NUL byte */ + + if (PyArg_ParseTuple(args, "O&Iw*|i:ioctl", + conv_descriptor, &fd, &code, + &pstr, &mutate_arg)) { + char *arg; + str = pstr.buf; + len = pstr.len; + + if (mutate_arg) { + if (len <= IOCTL_BUFSZ) { + memcpy(buf, str, len); + buf[len] = '\0'; + arg = buf; + } + else { + arg = str; + } + } + else { + if (len > IOCTL_BUFSZ) { + PyBuffer_Release(&pstr); + PyErr_SetString(PyExc_ValueError, + "ioctl string arg too long"); + return NULL; + } + else { + memcpy(buf, str, len); + buf[len] = '\0'; + arg = buf; + } + } + if (buf == arg) { + Py_BEGIN_ALLOW_THREADS /* think array.resize() */ + ret = ioctl(fd, code, arg); + Py_END_ALLOW_THREADS + } + else { + ret = ioctl(fd, code, arg); + } + if (mutate_arg && (len < IOCTL_BUFSZ)) { + memcpy(str, buf, len); + } + PyBuffer_Release(&pstr); /* No further access to str below this point */ + if (ret < 0) { + PyErr_SetFromErrno(PyExc_IOError); + return NULL; + } + if (mutate_arg) { + return PyLong_FromLong(ret); + } + else { + return PyBytes_FromStringAndSize(buf, len); + } + } + + PyErr_Clear(); + if (PyArg_ParseTuple(args, "O&Is*:ioctl", + conv_descriptor, &fd, &code, &pstr)) { + str = pstr.buf; + len = pstr.len; + if (len > IOCTL_BUFSZ) { + PyBuffer_Release(&pstr); + PyErr_SetString(PyExc_ValueError, + "ioctl string arg too long"); + return NULL; + } + memcpy(buf, str, len); + buf[len] = '\0'; + Py_BEGIN_ALLOW_THREADS + ret = ioctl(fd, code, buf); + Py_END_ALLOW_THREADS + if (ret < 0) { + PyBuffer_Release(&pstr); + PyErr_SetFromErrno(PyExc_IOError); + return NULL; + } + PyBuffer_Release(&pstr); + return PyBytes_FromStringAndSize(buf, len); + } + + PyErr_Clear(); + arg = 0; + if (!PyArg_ParseTuple(args, + "O&I|i;ioctl requires a file or file descriptor," + " an integer and optionally an integer or buffer argument", + conv_descriptor, &fd, &code, &arg)) { + return NULL; + } + Py_BEGIN_ALLOW_THREADS #ifdef __VMS - ret = ioctl(fd, code, (void *)arg); + ret = ioctl(fd, code, (void *)arg); #else - ret = ioctl(fd, code, arg); + ret = ioctl(fd, code, arg); #endif - Py_END_ALLOW_THREADS - if (ret < 0) { - PyErr_SetFromErrno(PyExc_IOError); - return NULL; - } - return PyLong_FromLong((long)ret); + Py_END_ALLOW_THREADS + if (ret < 0) { + PyErr_SetFromErrno(PyExc_IOError); + return NULL; + } + return PyLong_FromLong((long)ret); #undef IOCTL_BUFSZ } @@ -258,51 +258,51 @@ static PyObject * fcntl_flock(PyObject *self, PyObject *args) { - int fd; - int code; - int ret; - - if (!PyArg_ParseTuple(args, "O&i:flock", - conv_descriptor, &fd, &code)) - return NULL; + int fd; + int code; + int ret; + + if (!PyArg_ParseTuple(args, "O&i:flock", + conv_descriptor, &fd, &code)) + return NULL; #ifdef HAVE_FLOCK - Py_BEGIN_ALLOW_THREADS - ret = flock(fd, code); - Py_END_ALLOW_THREADS + Py_BEGIN_ALLOW_THREADS + ret = flock(fd, code); + Py_END_ALLOW_THREADS #else #ifndef LOCK_SH -#define LOCK_SH 1 /* shared lock */ -#define LOCK_EX 2 /* exclusive lock */ -#define LOCK_NB 4 /* don't block when locking */ -#define LOCK_UN 8 /* unlock */ -#endif - { - struct flock l; - if (code == LOCK_UN) - l.l_type = F_UNLCK; - else if (code & LOCK_SH) - l.l_type = F_RDLCK; - else if (code & LOCK_EX) - l.l_type = F_WRLCK; - else { - PyErr_SetString(PyExc_ValueError, - "unrecognized flock argument"); - return NULL; - } - l.l_whence = l.l_start = l.l_len = 0; - Py_BEGIN_ALLOW_THREADS - ret = fcntl(fd, (code & LOCK_NB) ? F_SETLK : F_SETLKW, &l); - Py_END_ALLOW_THREADS - } +#define LOCK_SH 1 /* shared lock */ +#define LOCK_EX 2 /* exclusive lock */ +#define LOCK_NB 4 /* don't block when locking */ +#define LOCK_UN 8 /* unlock */ +#endif + { + struct flock l; + if (code == LOCK_UN) + l.l_type = F_UNLCK; + else if (code & LOCK_SH) + l.l_type = F_RDLCK; + else if (code & LOCK_EX) + l.l_type = F_WRLCK; + else { + PyErr_SetString(PyExc_ValueError, + "unrecognized flock argument"); + return NULL; + } + l.l_whence = l.l_start = l.l_len = 0; + Py_BEGIN_ALLOW_THREADS + ret = fcntl(fd, (code & LOCK_NB) ? F_SETLK : F_SETLKW, &l); + Py_END_ALLOW_THREADS + } #endif /* HAVE_FLOCK */ - if (ret < 0) { - PyErr_SetFromErrno(PyExc_IOError); - return NULL; - } - Py_INCREF(Py_None); - return Py_None; + if (ret < 0) { + PyErr_SetFromErrno(PyExc_IOError); + return NULL; + } + Py_INCREF(Py_None); + return Py_None; } PyDoc_STRVAR(flock_doc, @@ -317,72 +317,72 @@ static PyObject * fcntl_lockf(PyObject *self, PyObject *args) { - int fd, code, ret, whence = 0; - PyObject *lenobj = NULL, *startobj = NULL; + int fd, code, ret, whence = 0; + PyObject *lenobj = NULL, *startobj = NULL; - if (!PyArg_ParseTuple(args, "O&i|OOi:lockf", - conv_descriptor, &fd, &code, - &lenobj, &startobj, &whence)) - return NULL; + if (!PyArg_ParseTuple(args, "O&i|OOi:lockf", + conv_descriptor, &fd, &code, + &lenobj, &startobj, &whence)) + return NULL; #if defined(PYOS_OS2) && defined(PYCC_GCC) - PyErr_SetString(PyExc_NotImplementedError, - "lockf not supported on OS/2 (EMX)"); - return NULL; + PyErr_SetString(PyExc_NotImplementedError, + "lockf not supported on OS/2 (EMX)"); + return NULL; #else #ifndef LOCK_SH -#define LOCK_SH 1 /* shared lock */ -#define LOCK_EX 2 /* exclusive lock */ -#define LOCK_NB 4 /* don't block when locking */ -#define LOCK_UN 8 /* unlock */ +#define LOCK_SH 1 /* shared lock */ +#define LOCK_EX 2 /* exclusive lock */ +#define LOCK_NB 4 /* don't block when locking */ +#define LOCK_UN 8 /* unlock */ #endif /* LOCK_SH */ - { - struct flock l; - if (code == LOCK_UN) - l.l_type = F_UNLCK; - else if (code & LOCK_SH) - l.l_type = F_RDLCK; - else if (code & LOCK_EX) - l.l_type = F_WRLCK; - else { - PyErr_SetString(PyExc_ValueError, - "unrecognized lockf argument"); - return NULL; - } - l.l_start = l.l_len = 0; - if (startobj != NULL) { + { + struct flock l; + if (code == LOCK_UN) + l.l_type = F_UNLCK; + else if (code & LOCK_SH) + l.l_type = F_RDLCK; + else if (code & LOCK_EX) + l.l_type = F_WRLCK; + else { + PyErr_SetString(PyExc_ValueError, + "unrecognized lockf argument"); + return NULL; + } + l.l_start = l.l_len = 0; + if (startobj != NULL) { #if !defined(HAVE_LARGEFILE_SUPPORT) - l.l_start = PyLong_AsLong(startobj); + l.l_start = PyLong_AsLong(startobj); #else - l.l_start = PyLong_Check(startobj) ? - PyLong_AsLongLong(startobj) : - PyLong_AsLong(startobj); -#endif - if (PyErr_Occurred()) - return NULL; - } - if (lenobj != NULL) { + l.l_start = PyLong_Check(startobj) ? + PyLong_AsLongLong(startobj) : + PyLong_AsLong(startobj); +#endif + if (PyErr_Occurred()) + return NULL; + } + if (lenobj != NULL) { #if !defined(HAVE_LARGEFILE_SUPPORT) - l.l_len = PyLong_AsLong(lenobj); + l.l_len = PyLong_AsLong(lenobj); #else - l.l_len = PyLong_Check(lenobj) ? - PyLong_AsLongLong(lenobj) : - PyLong_AsLong(lenobj); -#endif - if (PyErr_Occurred()) - return NULL; - } - l.l_whence = whence; - Py_BEGIN_ALLOW_THREADS - ret = fcntl(fd, (code & LOCK_NB) ? F_SETLK : F_SETLKW, &l); - Py_END_ALLOW_THREADS - } - if (ret < 0) { - PyErr_SetFromErrno(PyExc_IOError); - return NULL; - } - Py_INCREF(Py_None); - return Py_None; + l.l_len = PyLong_Check(lenobj) ? + PyLong_AsLongLong(lenobj) : + PyLong_AsLong(lenobj); +#endif + if (PyErr_Occurred()) + return NULL; + } + l.l_whence = whence; + Py_BEGIN_ALLOW_THREADS + ret = fcntl(fd, (code & LOCK_NB) ? F_SETLK : F_SETLKW, &l); + Py_END_ALLOW_THREADS + } + if (ret < 0) { + PyErr_SetFromErrno(PyExc_IOError); + return NULL; + } + Py_INCREF(Py_None); + return Py_None; #endif /* defined(PYOS_OS2) && defined(PYCC_GCC) */ } @@ -414,11 +414,11 @@ /* List of functions */ static PyMethodDef fcntl_methods[] = { - {"fcntl", fcntl_fcntl, METH_VARARGS, fcntl_doc}, - {"ioctl", fcntl_ioctl, METH_VARARGS, ioctl_doc}, - {"flock", fcntl_flock, METH_VARARGS, flock_doc}, - {"lockf", fcntl_lockf, METH_VARARGS, lockf_doc}, - {NULL, NULL} /* sentinel */ + {"fcntl", fcntl_fcntl, METH_VARARGS, fcntl_doc}, + {"ioctl", fcntl_ioctl, METH_VARARGS, ioctl_doc}, + {"flock", fcntl_flock, METH_VARARGS, flock_doc}, + {"lockf", fcntl_lockf, METH_VARARGS, lockf_doc}, + {NULL, NULL} /* sentinel */ }; @@ -433,12 +433,12 @@ static int ins(PyObject* d, char* symbol, long value) { - PyObject* v = PyLong_FromLong(value); - if (!v || PyDict_SetItemString(d, symbol, v) < 0) - return -1; + PyObject* v = PyLong_FromLong(value); + if (!v || PyDict_SetItemString(d, symbol, v) < 0) + return -1; - Py_DECREF(v); - return 0; + Py_DECREF(v); + return 0; } #define INS(x) if (ins(d, #x, (long)x)) return -1 @@ -446,199 +446,199 @@ static int all_ins(PyObject* d) { - if (ins(d, "LOCK_SH", (long)LOCK_SH)) return -1; - if (ins(d, "LOCK_EX", (long)LOCK_EX)) return -1; - if (ins(d, "LOCK_NB", (long)LOCK_NB)) return -1; - if (ins(d, "LOCK_UN", (long)LOCK_UN)) return -1; + if (ins(d, "LOCK_SH", (long)LOCK_SH)) return -1; + if (ins(d, "LOCK_EX", (long)LOCK_EX)) return -1; + if (ins(d, "LOCK_NB", (long)LOCK_NB)) return -1; + if (ins(d, "LOCK_UN", (long)LOCK_UN)) return -1; /* GNU extensions, as of glibc 2.2.4 */ #ifdef LOCK_MAND - if (ins(d, "LOCK_MAND", (long)LOCK_MAND)) return -1; + if (ins(d, "LOCK_MAND", (long)LOCK_MAND)) return -1; #endif #ifdef LOCK_READ - if (ins(d, "LOCK_READ", (long)LOCK_READ)) return -1; + if (ins(d, "LOCK_READ", (long)LOCK_READ)) return -1; #endif #ifdef LOCK_WRITE - if (ins(d, "LOCK_WRITE", (long)LOCK_WRITE)) return -1; + if (ins(d, "LOCK_WRITE", (long)LOCK_WRITE)) return -1; #endif #ifdef LOCK_RW - if (ins(d, "LOCK_RW", (long)LOCK_RW)) return -1; + if (ins(d, "LOCK_RW", (long)LOCK_RW)) return -1; #endif #ifdef F_DUPFD - if (ins(d, "F_DUPFD", (long)F_DUPFD)) return -1; + if (ins(d, "F_DUPFD", (long)F_DUPFD)) return -1; #endif #ifdef F_GETFD - if (ins(d, "F_GETFD", (long)F_GETFD)) return -1; + if (ins(d, "F_GETFD", (long)F_GETFD)) return -1; #endif #ifdef F_SETFD - if (ins(d, "F_SETFD", (long)F_SETFD)) return -1; + if (ins(d, "F_SETFD", (long)F_SETFD)) return -1; #endif #ifdef F_GETFL - if (ins(d, "F_GETFL", (long)F_GETFL)) return -1; + if (ins(d, "F_GETFL", (long)F_GETFL)) return -1; #endif #ifdef F_SETFL - if (ins(d, "F_SETFL", (long)F_SETFL)) return -1; + if (ins(d, "F_SETFL", (long)F_SETFL)) return -1; #endif #ifdef F_GETLK - if (ins(d, "F_GETLK", (long)F_GETLK)) return -1; + if (ins(d, "F_GETLK", (long)F_GETLK)) return -1; #endif #ifdef F_SETLK - if (ins(d, "F_SETLK", (long)F_SETLK)) return -1; + if (ins(d, "F_SETLK", (long)F_SETLK)) return -1; #endif #ifdef F_SETLKW - if (ins(d, "F_SETLKW", (long)F_SETLKW)) return -1; + if (ins(d, "F_SETLKW", (long)F_SETLKW)) return -1; #endif #ifdef F_GETOWN - if (ins(d, "F_GETOWN", (long)F_GETOWN)) return -1; + if (ins(d, "F_GETOWN", (long)F_GETOWN)) return -1; #endif #ifdef F_SETOWN - if (ins(d, "F_SETOWN", (long)F_SETOWN)) return -1; + if (ins(d, "F_SETOWN", (long)F_SETOWN)) return -1; #endif #ifdef F_GETSIG - if (ins(d, "F_GETSIG", (long)F_GETSIG)) return -1; + if (ins(d, "F_GETSIG", (long)F_GETSIG)) return -1; #endif #ifdef F_SETSIG - if (ins(d, "F_SETSIG", (long)F_SETSIG)) return -1; + if (ins(d, "F_SETSIG", (long)F_SETSIG)) return -1; #endif #ifdef F_RDLCK - if (ins(d, "F_RDLCK", (long)F_RDLCK)) return -1; + if (ins(d, "F_RDLCK", (long)F_RDLCK)) return -1; #endif #ifdef F_WRLCK - if (ins(d, "F_WRLCK", (long)F_WRLCK)) return -1; + if (ins(d, "F_WRLCK", (long)F_WRLCK)) return -1; #endif #ifdef F_UNLCK - if (ins(d, "F_UNLCK", (long)F_UNLCK)) return -1; + if (ins(d, "F_UNLCK", (long)F_UNLCK)) return -1; #endif /* LFS constants */ #ifdef F_GETLK64 - if (ins(d, "F_GETLK64", (long)F_GETLK64)) return -1; + if (ins(d, "F_GETLK64", (long)F_GETLK64)) return -1; #endif #ifdef F_SETLK64 - if (ins(d, "F_SETLK64", (long)F_SETLK64)) return -1; + if (ins(d, "F_SETLK64", (long)F_SETLK64)) return -1; #endif #ifdef F_SETLKW64 - if (ins(d, "F_SETLKW64", (long)F_SETLKW64)) return -1; + if (ins(d, "F_SETLKW64", (long)F_SETLKW64)) return -1; #endif /* GNU extensions, as of glibc 2.2.4. */ #ifdef FASYNC - if (ins(d, "FASYNC", (long)FASYNC)) return -1; + if (ins(d, "FASYNC", (long)FASYNC)) return -1; #endif #ifdef F_SETLEASE - if (ins(d, "F_SETLEASE", (long)F_SETLEASE)) return -1; + if (ins(d, "F_SETLEASE", (long)F_SETLEASE)) return -1; #endif #ifdef F_GETLEASE - if (ins(d, "F_GETLEASE", (long)F_GETLEASE)) return -1; + if (ins(d, "F_GETLEASE", (long)F_GETLEASE)) return -1; #endif #ifdef F_NOTIFY - if (ins(d, "F_NOTIFY", (long)F_NOTIFY)) return -1; + if (ins(d, "F_NOTIFY", (long)F_NOTIFY)) return -1; #endif /* Old BSD flock(). */ #ifdef F_EXLCK - if (ins(d, "F_EXLCK", (long)F_EXLCK)) return -1; + if (ins(d, "F_EXLCK", (long)F_EXLCK)) return -1; #endif #ifdef F_SHLCK - if (ins(d, "F_SHLCK", (long)F_SHLCK)) return -1; + if (ins(d, "F_SHLCK", (long)F_SHLCK)) return -1; #endif /* OS X (and maybe others) let you tell the storage device to flush to physical media */ #ifdef F_FULLFSYNC - if (ins(d, "F_FULLFSYNC", (long)F_FULLFSYNC)) return -1; + if (ins(d, "F_FULLFSYNC", (long)F_FULLFSYNC)) return -1; #endif /* For F_{GET|SET}FL */ #ifdef FD_CLOEXEC - if (ins(d, "FD_CLOEXEC", (long)FD_CLOEXEC)) return -1; + if (ins(d, "FD_CLOEXEC", (long)FD_CLOEXEC)) return -1; #endif /* For F_NOTIFY */ #ifdef DN_ACCESS - if (ins(d, "DN_ACCESS", (long)DN_ACCESS)) return -1; + if (ins(d, "DN_ACCESS", (long)DN_ACCESS)) return -1; #endif #ifdef DN_MODIFY - if (ins(d, "DN_MODIFY", (long)DN_MODIFY)) return -1; + if (ins(d, "DN_MODIFY", (long)DN_MODIFY)) return -1; #endif #ifdef DN_CREATE - if (ins(d, "DN_CREATE", (long)DN_CREATE)) return -1; + if (ins(d, "DN_CREATE", (long)DN_CREATE)) return -1; #endif #ifdef DN_DELETE - if (ins(d, "DN_DELETE", (long)DN_DELETE)) return -1; + if (ins(d, "DN_DELETE", (long)DN_DELETE)) return -1; #endif #ifdef DN_RENAME - if (ins(d, "DN_RENAME", (long)DN_RENAME)) return -1; + if (ins(d, "DN_RENAME", (long)DN_RENAME)) return -1; #endif #ifdef DN_ATTRIB - if (ins(d, "DN_ATTRIB", (long)DN_ATTRIB)) return -1; + if (ins(d, "DN_ATTRIB", (long)DN_ATTRIB)) return -1; #endif #ifdef DN_MULTISHOT - if (ins(d, "DN_MULTISHOT", (long)DN_MULTISHOT)) return -1; + if (ins(d, "DN_MULTISHOT", (long)DN_MULTISHOT)) return -1; #endif #ifdef HAVE_STROPTS_H - /* Unix 98 guarantees that these are in stropts.h. */ - INS(I_PUSH); - INS(I_POP); - INS(I_LOOK); - INS(I_FLUSH); - INS(I_FLUSHBAND); - INS(I_SETSIG); - INS(I_GETSIG); - INS(I_FIND); - INS(I_PEEK); - INS(I_SRDOPT); - INS(I_GRDOPT); - INS(I_NREAD); - INS(I_FDINSERT); - INS(I_STR); - INS(I_SWROPT); + /* Unix 98 guarantees that these are in stropts.h. */ + INS(I_PUSH); + INS(I_POP); + INS(I_LOOK); + INS(I_FLUSH); + INS(I_FLUSHBAND); + INS(I_SETSIG); + INS(I_GETSIG); + INS(I_FIND); + INS(I_PEEK); + INS(I_SRDOPT); + INS(I_GRDOPT); + INS(I_NREAD); + INS(I_FDINSERT); + INS(I_STR); + INS(I_SWROPT); #ifdef I_GWROPT - /* despite the comment above, old-ish glibcs miss a couple... */ - INS(I_GWROPT); + /* despite the comment above, old-ish glibcs miss a couple... */ + INS(I_GWROPT); #endif - INS(I_SENDFD); - INS(I_RECVFD); - INS(I_LIST); - INS(I_ATMARK); - INS(I_CKBAND); - INS(I_GETBAND); - INS(I_CANPUT); - INS(I_SETCLTIME); + INS(I_SENDFD); + INS(I_RECVFD); + INS(I_LIST); + INS(I_ATMARK); + INS(I_CKBAND); + INS(I_GETBAND); + INS(I_CANPUT); + INS(I_SETCLTIME); #ifdef I_GETCLTIME - INS(I_GETCLTIME); + INS(I_GETCLTIME); #endif - INS(I_LINK); - INS(I_UNLINK); - INS(I_PLINK); - INS(I_PUNLINK); + INS(I_LINK); + INS(I_UNLINK); + INS(I_PLINK); + INS(I_PUNLINK); #endif - - return 0; + + return 0; } static struct PyModuleDef fcntlmodule = { - PyModuleDef_HEAD_INIT, - "fcntl", - module_doc, - -1, - fcntl_methods, - NULL, - NULL, - NULL, - NULL + PyModuleDef_HEAD_INIT, + "fcntl", + module_doc, + -1, + fcntl_methods, + NULL, + NULL, + NULL, + NULL }; PyMODINIT_FUNC PyInit_fcntl(void) { - PyObject *m, *d; + PyObject *m, *d; - /* Create the module and add the functions and documentation */ - m = PyModule_Create(&fcntlmodule); - if (m == NULL) - return NULL; - - /* Add some symbolic constants to the module */ - d = PyModule_GetDict(m); - all_ins(d); - return m; + /* Create the module and add the functions and documentation */ + m = PyModule_Create(&fcntlmodule); + if (m == NULL) + return NULL; + + /* Add some symbolic constants to the module */ + d = PyModule_GetDict(m); + all_ins(d); + return m; } Modified: python/branches/py3k-jit/Modules/fpectlmodule.c ============================================================================== --- python/branches/py3k-jit/Modules/fpectlmodule.c (original) +++ python/branches/py3k-jit/Modules/fpectlmodule.c Mon May 10 23:55:43 2010 @@ -1,6 +1,6 @@ /* - --------------------------------------------------------------------- - / Copyright (c) 1996. \ + --------------------------------------------------------------------- + / Copyright (c) 1996. \ | The Regents of the University of California. | | All rights reserved. | | | @@ -32,12 +32,12 @@ | 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. / - --------------------------------------------------------------------- + \ endorsement purposes. / + --------------------------------------------------------------------- */ /* - Floating point exception control module. + Floating point exception control module. This Python module provides bare-bones control over floating point units from several hardware manufacturers. Specifically, it allows @@ -96,8 +96,8 @@ static PyObject *turnoff_sigfpe (PyObject *self,PyObject *args); static PyMethodDef fpectl_methods[] = { - {"turnon_sigfpe", (PyCFunction) turnon_sigfpe, METH_VARARGS}, - {"turnoff_sigfpe", (PyCFunction) turnoff_sigfpe, METH_VARARGS}, + {"turnon_sigfpe", (PyCFunction) turnon_sigfpe, METH_VARARGS}, + {"turnoff_sigfpe", (PyCFunction) turnoff_sigfpe, METH_VARARGS}, {0,0} }; @@ -122,19 +122,19 @@ * My usage doesn't follow the man page exactly. Maybe somebody * else can explain handle_sigfpes to me.... * cc -c -I/usr/local/python/include fpectlmodule.c - * ld -shared -o fpectlmodule.so fpectlmodule.o -lfpe + * ld -shared -o fpectlmodule.so fpectlmodule.o -lfpe */ #include typedef void user_routine (unsigned[5], int[2]); typedef void abort_routine (unsigned long); handle_sigfpes(_OFF, 0, - (user_routine *)0, - _TURN_OFF_HANDLER_ON_ERROR, - NULL); + (user_routine *)0, + _TURN_OFF_HANDLER_ON_ERROR, + NULL); handle_sigfpes(_ON, _EN_OVERFL | _EN_DIVZERO | _EN_INVALID, - (user_routine *)0, - _ABORT_ON_ERROR, - NULL); + (user_routine *)0, + _ABORT_ON_ERROR, + NULL); PyOS_setsig(SIGFPE, handler); /*-- SunOS and Solaris ----------------------------------------------------*/ @@ -195,16 +195,16 @@ /*-- DEC ALPHA VMS --------------------------------------------------------*/ #elif defined(__ALPHA) && defined(__VMS) - IEEE clrmsk; - IEEE setmsk; - clrmsk.ieee$q_flags = - IEEE$M_TRAP_ENABLE_UNF | IEEE$M_TRAP_ENABLE_INE | - IEEE$M_MAP_UMZ; - setmsk.ieee$q_flags = - IEEE$M_TRAP_ENABLE_INV | IEEE$M_TRAP_ENABLE_DZE | - IEEE$M_TRAP_ENABLE_OVF; - sys$ieee_set_fp_control(&clrmsk, &setmsk, 0); - PyOS_setsig(SIGFPE, handler); + IEEE clrmsk; + IEEE setmsk; + clrmsk.ieee$q_flags = + IEEE$M_TRAP_ENABLE_UNF | IEEE$M_TRAP_ENABLE_INE | + IEEE$M_MAP_UMZ; + setmsk.ieee$q_flags = + IEEE$M_TRAP_ENABLE_INV | IEEE$M_TRAP_ENABLE_DZE | + IEEE$M_TRAP_ENABLE_OVF; + sys$ieee_set_fp_control(&clrmsk, &setmsk, 0); + PyOS_setsig(SIGFPE, handler); /*-- HP IA64 VMS --------------------------------------------------------*/ #elif defined(__ia64) && defined(__VMS) @@ -263,13 +263,13 @@ fpresetsticky(fpgetsticky()); fpsetmask(0); #elif defined(__VMS) - IEEE clrmsk; - clrmsk.ieee$q_flags = - IEEE$M_TRAP_ENABLE_UNF | IEEE$M_TRAP_ENABLE_INE | - IEEE$M_MAP_UMZ | IEEE$M_TRAP_ENABLE_INV | - IEEE$M_TRAP_ENABLE_DZE | IEEE$M_TRAP_ENABLE_OVF | - IEEE$M_INHERIT; - sys$ieee_set_fp_control(&clrmsk, 0, 0); + IEEE clrmsk; + clrmsk.ieee$q_flags = + IEEE$M_TRAP_ENABLE_UNF | IEEE$M_TRAP_ENABLE_INE | + IEEE$M_MAP_UMZ | IEEE$M_TRAP_ENABLE_INV | + IEEE$M_TRAP_ENABLE_DZE | IEEE$M_TRAP_ENABLE_OVF | + IEEE$M_INHERIT; + sys$ieee_set_fp_control(&clrmsk, 0, 0); #else fputs("Operation not implemented\n", stderr); #endif @@ -288,15 +288,15 @@ } static struct PyModuleDef fpectlmodule = { - PyModuleDef_HEAD_INIT, - "fpectl", - NULL, - -1, - fpectl_methods, - NULL, - NULL, - NULL, - NULL + PyModuleDef_HEAD_INIT, + "fpectl", + NULL, + -1, + fpectl_methods, + NULL, + NULL, + NULL, + NULL }; PyMODINIT_FUNC PyInit_fpectl(void) @@ -304,11 +304,11 @@ PyObject *m, *d; m = PyModule_Create(&fpectlmodule); if (m == NULL) - return NULL; + return NULL; d = PyModule_GetDict(m); fpe_error = PyErr_NewException("fpectl.error", NULL, NULL); if (fpe_error != NULL) - PyDict_SetItemString(d, "error", fpe_error); + PyDict_SetItemString(d, "error", fpe_error); return m; } Modified: python/branches/py3k-jit/Modules/fpetestmodule.c ============================================================================== --- python/branches/py3k-jit/Modules/fpetestmodule.c (original) +++ python/branches/py3k-jit/Modules/fpetestmodule.c Mon May 10 23:55:43 2010 @@ -1,6 +1,6 @@ /* - --------------------------------------------------------------------- - / Copyright (c) 1996. \ + --------------------------------------------------------------------- + / Copyright (c) 1996. \ | The Regents of the University of California. | | All rights reserved. | | | @@ -32,12 +32,12 @@ | 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. / - --------------------------------------------------------------------- + \ endorsement purposes. / + --------------------------------------------------------------------- */ /* - Floating point exception test module. + Floating point exception test module. */ @@ -55,7 +55,7 @@ static void printerr(double); static PyMethodDef fpetest_methods[] = { - {"test", (PyCFunction) test, METH_VARARGS}, + {"test", (PyCFunction) test, METH_VARARGS}, {0,0} }; @@ -174,15 +174,15 @@ } static struct PyModuleDef fpetestmodule = { - PyModuleDef_HEAD_INIT, - "fpetest", - NULL, - -1, - fpetest_methods, - NULL, - NULL, - NULL, - NULL + PyModuleDef_HEAD_INIT, + "fpetest", + NULL, + -1, + fpetest_methods, + NULL, + NULL, + NULL, + NULL }; PyMODINIT_FUNC PyInit_fpetest(void) @@ -191,10 +191,10 @@ m = PyModule_Create(&fpetestmodule); if (m == NULL) - return NULL; + return NULL; d = PyModule_GetDict(m); fpe_error = PyErr_NewException("fpetest.error", NULL, NULL); if (fpe_error != NULL) - PyDict_SetItemString(d, "error", fpe_error); + PyDict_SetItemString(d, "error", fpe_error); return m; } Modified: python/branches/py3k-jit/Modules/gcmodule.c ============================================================================== --- python/branches/py3k-jit/Modules/gcmodule.c (original) +++ python/branches/py3k-jit/Modules/gcmodule.c Mon May 10 23:55:43 2010 @@ -24,7 +24,7 @@ */ #include "Python.h" -#include "frameobject.h" /* for PyFrame_ClearFreeList */ +#include "frameobject.h" /* for PyFrame_ClearFreeList */ /* Get an object's GC head */ #define AS_GC(o) ((PyGC_Head *)(o)-1) @@ -35,10 +35,10 @@ /*** Global GC state ***/ struct gc_generation { - PyGC_Head head; - int threshold; /* collection threshold */ - int count; /* count of allocations or collections of younger - generations */ + PyGC_Head head; + int threshold; /* collection threshold */ + int count; /* count of allocations or collections of younger + generations */ }; #define NUM_GENERATIONS 3 @@ -46,10 +46,10 @@ /* linked lists of container objects */ static struct gc_generation generations[NUM_GENERATIONS] = { - /* PyGC_Head, threshold, count */ - {{{GEN_HEAD(0), GEN_HEAD(0), 0}}, 700, 0}, - {{{GEN_HEAD(1), GEN_HEAD(1), 0}}, 10, 0}, - {{{GEN_HEAD(2), GEN_HEAD(2), 0}}, 10, 0}, + /* PyGC_Head, threshold, count */ + {{{GEN_HEAD(0), GEN_HEAD(0), 0}}, 700, 0}, + {{{GEN_HEAD(1), GEN_HEAD(1), 0}}, 10, 0}, + {{{GEN_HEAD(2), GEN_HEAD(2), 0}}, 10, 0}, }; PyGC_Head *_PyGC_generation0 = GEN_HEAD(0); @@ -91,7 +91,7 @@ In addition to the various configurable thresholds, we only trigger a full collection if the ratio - long_lived_pending / long_lived_total + long_lived_pending / long_lived_total is above a given value (hardwired to 25%). The reason is that, while "non-full" collections (i.e., collections of @@ -113,18 +113,18 @@ This heuristic was suggested by Martin von L?wis on python-dev in June 2008. His original analysis and proposal can be found at: - http://mail.python.org/pipermail/python-dev/2008-June/080579.html + http://mail.python.org/pipermail/python-dev/2008-June/080579.html */ /* set for debugging information */ -#define DEBUG_STATS (1<<0) /* print collection statistics */ -#define DEBUG_COLLECTABLE (1<<1) /* print collectable objects */ -#define DEBUG_UNCOLLECTABLE (1<<2) /* print uncollectable objects */ -#define DEBUG_SAVEALL (1<<5) /* save all garbage in gc.garbage */ -#define DEBUG_LEAK DEBUG_COLLECTABLE | \ - DEBUG_UNCOLLECTABLE | \ - DEBUG_SAVEALL +#define DEBUG_STATS (1<<0) /* print collection statistics */ +#define DEBUG_COLLECTABLE (1<<1) /* print collectable objects */ +#define DEBUG_UNCOLLECTABLE (1<<2) /* print uncollectable objects */ +#define DEBUG_SAVEALL (1<<5) /* save all garbage in gc.garbage */ +#define DEBUG_LEAK DEBUG_COLLECTABLE | \ + DEBUG_UNCOLLECTABLE | \ + DEBUG_SAVEALL static int debug; static PyObject *tmod = NULL; @@ -167,28 +167,28 @@ it has a __del__ method), its gc_refs is restored to GC_REACHABLE again. ---------------------------------------------------------------------------- */ -#define GC_UNTRACKED _PyGC_REFS_UNTRACKED -#define GC_REACHABLE _PyGC_REFS_REACHABLE -#define GC_TENTATIVELY_UNREACHABLE _PyGC_REFS_TENTATIVELY_UNREACHABLE +#define GC_UNTRACKED _PyGC_REFS_UNTRACKED +#define GC_REACHABLE _PyGC_REFS_REACHABLE +#define GC_TENTATIVELY_UNREACHABLE _PyGC_REFS_TENTATIVELY_UNREACHABLE #define IS_TRACKED(o) ((AS_GC(o))->gc.gc_refs != GC_UNTRACKED) #define IS_REACHABLE(o) ((AS_GC(o))->gc.gc_refs == GC_REACHABLE) #define IS_TENTATIVELY_UNREACHABLE(o) ( \ - (AS_GC(o))->gc.gc_refs == GC_TENTATIVELY_UNREACHABLE) + (AS_GC(o))->gc.gc_refs == GC_TENTATIVELY_UNREACHABLE) /*** list functions ***/ static void gc_list_init(PyGC_Head *list) { - list->gc.gc_prev = list; - list->gc.gc_next = list; + list->gc.gc_prev = list; + list->gc.gc_next = list; } static int gc_list_is_empty(PyGC_Head *list) { - return (list->gc.gc_next == list); + return (list->gc.gc_next == list); } #if 0 @@ -197,10 +197,10 @@ static void gc_list_append(PyGC_Head *node, PyGC_Head *list) { - node->gc.gc_next = list; - node->gc.gc_prev = list->gc.gc_prev; - node->gc.gc_prev->gc.gc_next = node; - list->gc.gc_prev = node; + node->gc.gc_next = list; + node->gc.gc_prev = list->gc.gc_prev; + node->gc.gc_prev->gc.gc_next = node; + list->gc.gc_prev = node; } #endif @@ -208,9 +208,9 @@ static void gc_list_remove(PyGC_Head *node) { - node->gc.gc_prev->gc.gc_next = node->gc.gc_next; - node->gc.gc_next->gc.gc_prev = node->gc.gc_prev; - node->gc.gc_next = NULL; /* object is not currently tracked */ + node->gc.gc_prev->gc.gc_next = node->gc.gc_next; + node->gc.gc_next->gc.gc_prev = node->gc.gc_prev; + node->gc.gc_next = NULL; /* object is not currently tracked */ } /* Move `node` from the gc list it's currently in (which is not explicitly @@ -220,43 +220,43 @@ static void gc_list_move(PyGC_Head *node, PyGC_Head *list) { - PyGC_Head *new_prev; - PyGC_Head *current_prev = node->gc.gc_prev; - PyGC_Head *current_next = node->gc.gc_next; - /* Unlink from current list. */ - current_prev->gc.gc_next = current_next; - current_next->gc.gc_prev = current_prev; - /* Relink at end of new list. */ - new_prev = node->gc.gc_prev = list->gc.gc_prev; - new_prev->gc.gc_next = list->gc.gc_prev = node; - node->gc.gc_next = list; + PyGC_Head *new_prev; + PyGC_Head *current_prev = node->gc.gc_prev; + PyGC_Head *current_next = node->gc.gc_next; + /* Unlink from current list. */ + current_prev->gc.gc_next = current_next; + current_next->gc.gc_prev = current_prev; + /* Relink at end of new list. */ + new_prev = node->gc.gc_prev = list->gc.gc_prev; + new_prev->gc.gc_next = list->gc.gc_prev = node; + node->gc.gc_next = list; } /* append list `from` onto list `to`; `from` becomes an empty list */ static void gc_list_merge(PyGC_Head *from, PyGC_Head *to) { - PyGC_Head *tail; - assert(from != to); - if (!gc_list_is_empty(from)) { - tail = to->gc.gc_prev; - tail->gc.gc_next = from->gc.gc_next; - tail->gc.gc_next->gc.gc_prev = tail; - to->gc.gc_prev = from->gc.gc_prev; - to->gc.gc_prev->gc.gc_next = to; - } - gc_list_init(from); + PyGC_Head *tail; + assert(from != to); + if (!gc_list_is_empty(from)) { + tail = to->gc.gc_prev; + tail->gc.gc_next = from->gc.gc_next; + tail->gc.gc_next->gc.gc_prev = tail; + to->gc.gc_prev = from->gc.gc_prev; + to->gc.gc_prev->gc.gc_next = to; + } + gc_list_init(from); } static Py_ssize_t gc_list_size(PyGC_Head *list) { - PyGC_Head *gc; - Py_ssize_t n = 0; - for (gc = list->gc.gc_next; gc != list; gc = gc->gc.gc_next) { - n++; - } - return n; + PyGC_Head *gc; + Py_ssize_t n = 0; + for (gc = list->gc.gc_next; gc != list; gc = gc->gc.gc_next) { + n++; + } + return n; } /* Append objects in a GC list to a Python list. @@ -265,16 +265,16 @@ static int append_objects(PyObject *py_list, PyGC_Head *gc_list) { - PyGC_Head *gc; - for (gc = gc_list->gc.gc_next; gc != gc_list; gc = gc->gc.gc_next) { - PyObject *op = FROM_GC(gc); - if (op != py_list) { - if (PyList_Append(py_list, op)) { - return -1; /* exception */ - } - } - } - return 0; + PyGC_Head *gc; + for (gc = gc_list->gc.gc_next; gc != gc_list; gc = gc->gc.gc_next) { + PyObject *op = FROM_GC(gc); + if (op != py_list) { + if (PyList_Append(py_list, op)) { + return -1; /* exception */ + } + } + } + return 0; } /*** end of list stuff ***/ @@ -287,48 +287,48 @@ static void update_refs(PyGC_Head *containers) { - PyGC_Head *gc = containers->gc.gc_next; - for (; gc != containers; gc = gc->gc.gc_next) { - assert(gc->gc.gc_refs == GC_REACHABLE); - gc->gc.gc_refs = Py_REFCNT(FROM_GC(gc)); - /* Python's cyclic gc should never see an incoming refcount - * of 0: if something decref'ed to 0, it should have been - * deallocated immediately at that time. - * Possible cause (if the assert triggers): a tp_dealloc - * routine left a gc-aware object tracked during its teardown - * phase, and did something-- or allowed something to happen -- - * that called back into Python. gc can trigger then, and may - * see the still-tracked dying object. Before this assert - * was added, such mistakes went on to allow gc to try to - * delete the object again. In a debug build, that caused - * a mysterious segfault, when _Py_ForgetReference tried - * to remove the object from the doubly-linked list of all - * objects a second time. In a release build, an actual - * double deallocation occurred, which leads to corruption - * of the allocator's internal bookkeeping pointers. That's - * so serious that maybe this should be a release-build - * check instead of an assert? - */ - assert(gc->gc.gc_refs != 0); - } + PyGC_Head *gc = containers->gc.gc_next; + for (; gc != containers; gc = gc->gc.gc_next) { + assert(gc->gc.gc_refs == GC_REACHABLE); + gc->gc.gc_refs = Py_REFCNT(FROM_GC(gc)); + /* Python's cyclic gc should never see an incoming refcount + * of 0: if something decref'ed to 0, it should have been + * deallocated immediately at that time. + * Possible cause (if the assert triggers): a tp_dealloc + * routine left a gc-aware object tracked during its teardown + * phase, and did something-- or allowed something to happen -- + * that called back into Python. gc can trigger then, and may + * see the still-tracked dying object. Before this assert + * was added, such mistakes went on to allow gc to try to + * delete the object again. In a debug build, that caused + * a mysterious segfault, when _Py_ForgetReference tried + * to remove the object from the doubly-linked list of all + * objects a second time. In a release build, an actual + * double deallocation occurred, which leads to corruption + * of the allocator's internal bookkeeping pointers. That's + * so serious that maybe this should be a release-build + * check instead of an assert? + */ + assert(gc->gc.gc_refs != 0); + } } /* A traversal callback for subtract_refs. */ static int visit_decref(PyObject *op, void *data) { - assert(op != NULL); - if (PyObject_IS_GC(op)) { - PyGC_Head *gc = AS_GC(op); - /* We're only interested in gc_refs for objects in the - * generation being collected, which can be recognized - * because only they have positive gc_refs. - */ - assert(gc->gc.gc_refs != 0); /* else refcount was too small */ - if (gc->gc.gc_refs > 0) - gc->gc.gc_refs--; - } - return 0; + assert(op != NULL); + if (PyObject_IS_GC(op)) { + PyGC_Head *gc = AS_GC(op); + /* We're only interested in gc_refs for objects in the + * generation being collected, which can be recognized + * because only they have positive gc_refs. + */ + assert(gc->gc.gc_refs != 0); /* else refcount was too small */ + if (gc->gc.gc_refs > 0) + gc->gc.gc_refs--; + } + return 0; } /* Subtract internal references from gc_refs. After this, gc_refs is >= 0 @@ -339,57 +339,57 @@ static void subtract_refs(PyGC_Head *containers) { - traverseproc traverse; - PyGC_Head *gc = containers->gc.gc_next; - for (; gc != containers; gc=gc->gc.gc_next) { - traverse = Py_TYPE(FROM_GC(gc))->tp_traverse; - (void) traverse(FROM_GC(gc), - (visitproc)visit_decref, - NULL); - } + traverseproc traverse; + PyGC_Head *gc = containers->gc.gc_next; + for (; gc != containers; gc=gc->gc.gc_next) { + traverse = Py_TYPE(FROM_GC(gc))->tp_traverse; + (void) traverse(FROM_GC(gc), + (visitproc)visit_decref, + NULL); + } } /* A traversal callback for move_unreachable. */ static int visit_reachable(PyObject *op, PyGC_Head *reachable) { - if (PyObject_IS_GC(op)) { - PyGC_Head *gc = AS_GC(op); - const Py_ssize_t gc_refs = gc->gc.gc_refs; - - if (gc_refs == 0) { - /* This is in move_unreachable's 'young' list, but - * the traversal hasn't yet gotten to it. All - * we need to do is tell move_unreachable that it's - * reachable. - */ - gc->gc.gc_refs = 1; - } - else if (gc_refs == GC_TENTATIVELY_UNREACHABLE) { - /* This had gc_refs = 0 when move_unreachable got - * to it, but turns out it's reachable after all. - * Move it back to move_unreachable's 'young' list, - * and move_unreachable will eventually get to it - * again. - */ - gc_list_move(gc, reachable); - gc->gc.gc_refs = 1; - } - /* Else there's nothing to do. - * If gc_refs > 0, it must be in move_unreachable's 'young' - * list, and move_unreachable will eventually get to it. - * If gc_refs == GC_REACHABLE, it's either in some other - * generation so we don't care about it, or move_unreachable - * already dealt with it. - * If gc_refs == GC_UNTRACKED, it must be ignored. - */ - else { - assert(gc_refs > 0 - || gc_refs == GC_REACHABLE - || gc_refs == GC_UNTRACKED); - } - } - return 0; + if (PyObject_IS_GC(op)) { + PyGC_Head *gc = AS_GC(op); + const Py_ssize_t gc_refs = gc->gc.gc_refs; + + if (gc_refs == 0) { + /* This is in move_unreachable's 'young' list, but + * the traversal hasn't yet gotten to it. All + * we need to do is tell move_unreachable that it's + * reachable. + */ + gc->gc.gc_refs = 1; + } + else if (gc_refs == GC_TENTATIVELY_UNREACHABLE) { + /* This had gc_refs = 0 when move_unreachable got + * to it, but turns out it's reachable after all. + * Move it back to move_unreachable's 'young' list, + * and move_unreachable will eventually get to it + * again. + */ + gc_list_move(gc, reachable); + gc->gc.gc_refs = 1; + } + /* Else there's nothing to do. + * If gc_refs > 0, it must be in move_unreachable's 'young' + * list, and move_unreachable will eventually get to it. + * If gc_refs == GC_REACHABLE, it's either in some other + * generation so we don't care about it, or move_unreachable + * already dealt with it. + * If gc_refs == GC_UNTRACKED, it must be ignored. + */ + else { + assert(gc_refs > 0 + || gc_refs == GC_REACHABLE + || gc_refs == GC_UNTRACKED); + } + } + return 0; } /* Move the unreachable objects from young to unreachable. After this, @@ -403,68 +403,68 @@ static void move_unreachable(PyGC_Head *young, PyGC_Head *unreachable) { - PyGC_Head *gc = young->gc.gc_next; + PyGC_Head *gc = young->gc.gc_next; - /* Invariants: all objects "to the left" of us in young have gc_refs - * = GC_REACHABLE, and are indeed reachable (directly or indirectly) - * from outside the young list as it was at entry. All other objects - * from the original young "to the left" of us are in unreachable now, - * and have gc_refs = GC_TENTATIVELY_UNREACHABLE. All objects to the - * left of us in 'young' now have been scanned, and no objects here - * or to the right have been scanned yet. - */ - - while (gc != young) { - PyGC_Head *next; - - if (gc->gc.gc_refs) { - /* gc is definitely reachable from outside the - * original 'young'. Mark it as such, and traverse - * its pointers to find any other objects that may - * be directly reachable from it. Note that the - * call to tp_traverse may append objects to young, - * so we have to wait until it returns to determine - * the next object to visit. - */ - PyObject *op = FROM_GC(gc); - traverseproc traverse = Py_TYPE(op)->tp_traverse; - assert(gc->gc.gc_refs > 0); - gc->gc.gc_refs = GC_REACHABLE; - (void) traverse(op, - (visitproc)visit_reachable, - (void *)young); - next = gc->gc.gc_next; - if (PyTuple_CheckExact(op)) { - _PyTuple_MaybeUntrack(op); - } - else if (PyDict_CheckExact(op)) { - _PyDict_MaybeUntrack(op); - } - } - else { - /* This *may* be unreachable. To make progress, - * assume it is. gc isn't directly reachable from - * any object we've already traversed, but may be - * reachable from an object we haven't gotten to yet. - * visit_reachable will eventually move gc back into - * young if that's so, and we'll see it again. - */ - next = gc->gc.gc_next; - gc_list_move(gc, unreachable); - gc->gc.gc_refs = GC_TENTATIVELY_UNREACHABLE; - } - gc = next; - } + /* Invariants: all objects "to the left" of us in young have gc_refs + * = GC_REACHABLE, and are indeed reachable (directly or indirectly) + * from outside the young list as it was at entry. All other objects + * from the original young "to the left" of us are in unreachable now, + * and have gc_refs = GC_TENTATIVELY_UNREACHABLE. All objects to the + * left of us in 'young' now have been scanned, and no objects here + * or to the right have been scanned yet. + */ + + while (gc != young) { + PyGC_Head *next; + + if (gc->gc.gc_refs) { + /* gc is definitely reachable from outside the + * original 'young'. Mark it as such, and traverse + * its pointers to find any other objects that may + * be directly reachable from it. Note that the + * call to tp_traverse may append objects to young, + * so we have to wait until it returns to determine + * the next object to visit. + */ + PyObject *op = FROM_GC(gc); + traverseproc traverse = Py_TYPE(op)->tp_traverse; + assert(gc->gc.gc_refs > 0); + gc->gc.gc_refs = GC_REACHABLE; + (void) traverse(op, + (visitproc)visit_reachable, + (void *)young); + next = gc->gc.gc_next; + if (PyTuple_CheckExact(op)) { + _PyTuple_MaybeUntrack(op); + } + else if (PyDict_CheckExact(op)) { + _PyDict_MaybeUntrack(op); + } + } + else { + /* This *may* be unreachable. To make progress, + * assume it is. gc isn't directly reachable from + * any object we've already traversed, but may be + * reachable from an object we haven't gotten to yet. + * visit_reachable will eventually move gc back into + * young if that's so, and we'll see it again. + */ + next = gc->gc.gc_next; + gc_list_move(gc, unreachable); + gc->gc.gc_refs = GC_TENTATIVELY_UNREACHABLE; + } + gc = next; + } } /* Return true if object has a finalization method. */ static int has_finalizer(PyObject *op) { - if (PyGen_CheckExact(op)) - return PyGen_NeedsFinalizing((PyGenObject *)op); - else - return op->ob_type->tp_del != NULL; + if (PyGen_CheckExact(op)) + return PyGen_NeedsFinalizing((PyGenObject *)op); + else + return op->ob_type->tp_del != NULL; } /* Move the objects in unreachable with __del__ methods into `finalizers`. @@ -474,37 +474,37 @@ static void move_finalizers(PyGC_Head *unreachable, PyGC_Head *finalizers) { - PyGC_Head *gc; - PyGC_Head *next; + PyGC_Head *gc; + PyGC_Head *next; - /* March over unreachable. Move objects with finalizers into - * `finalizers`. - */ - for (gc = unreachable->gc.gc_next; gc != unreachable; gc = next) { - PyObject *op = FROM_GC(gc); - - assert(IS_TENTATIVELY_UNREACHABLE(op)); - next = gc->gc.gc_next; - - if (has_finalizer(op)) { - gc_list_move(gc, finalizers); - gc->gc.gc_refs = GC_REACHABLE; - } - } + /* March over unreachable. Move objects with finalizers into + * `finalizers`. + */ + for (gc = unreachable->gc.gc_next; gc != unreachable; gc = next) { + PyObject *op = FROM_GC(gc); + + assert(IS_TENTATIVELY_UNREACHABLE(op)); + next = gc->gc.gc_next; + + if (has_finalizer(op)) { + gc_list_move(gc, finalizers); + gc->gc.gc_refs = GC_REACHABLE; + } + } } /* A traversal callback for move_finalizer_reachable. */ static int visit_move(PyObject *op, PyGC_Head *tolist) { - if (PyObject_IS_GC(op)) { - if (IS_TENTATIVELY_UNREACHABLE(op)) { - PyGC_Head *gc = AS_GC(op); - gc_list_move(gc, tolist); - gc->gc.gc_refs = GC_REACHABLE; - } - } - return 0; + if (PyObject_IS_GC(op)) { + if (IS_TENTATIVELY_UNREACHABLE(op)) { + PyGC_Head *gc = AS_GC(op); + gc_list_move(gc, tolist); + gc->gc.gc_refs = GC_REACHABLE; + } + } + return 0; } /* Move objects that are reachable from finalizers, from the unreachable set @@ -513,15 +513,15 @@ static void move_finalizer_reachable(PyGC_Head *finalizers) { - traverseproc traverse; - PyGC_Head *gc = finalizers->gc.gc_next; - for (; gc != finalizers; gc = gc->gc.gc_next) { - /* Note that the finalizers list may grow during this. */ - traverse = Py_TYPE(FROM_GC(gc))->tp_traverse; - (void) traverse(FROM_GC(gc), - (visitproc)visit_move, - (void *)finalizers); - } + traverseproc traverse; + PyGC_Head *gc = finalizers->gc.gc_next; + for (; gc != finalizers; gc = gc->gc.gc_next) { + /* Note that the finalizers list may grow during this. */ + traverse = Py_TYPE(FROM_GC(gc))->tp_traverse; + (void) traverse(FROM_GC(gc), + (visitproc)visit_move, + (void *)finalizers); + } } /* Clear all weakrefs to unreachable objects, and if such a weakref has a @@ -538,150 +538,150 @@ static int handle_weakrefs(PyGC_Head *unreachable, PyGC_Head *old) { - PyGC_Head *gc; - PyObject *op; /* generally FROM_GC(gc) */ - PyWeakReference *wr; /* generally a cast of op */ - PyGC_Head wrcb_to_call; /* weakrefs with callbacks to call */ - PyGC_Head *next; - int num_freed = 0; - - gc_list_init(&wrcb_to_call); - - /* Clear all weakrefs to the objects in unreachable. If such a weakref - * also has a callback, move it into `wrcb_to_call` if the callback - * needs to be invoked. Note that we cannot invoke any callbacks until - * all weakrefs to unreachable objects are cleared, lest the callback - * resurrect an unreachable object via a still-active weakref. We - * make another pass over wrcb_to_call, invoking callbacks, after this - * pass completes. - */ - for (gc = unreachable->gc.gc_next; gc != unreachable; gc = next) { - PyWeakReference **wrlist; - - op = FROM_GC(gc); - assert(IS_TENTATIVELY_UNREACHABLE(op)); - next = gc->gc.gc_next; - - if (! PyType_SUPPORTS_WEAKREFS(Py_TYPE(op))) - continue; - - /* It supports weakrefs. Does it have any? */ - wrlist = (PyWeakReference **) - PyObject_GET_WEAKREFS_LISTPTR(op); - - /* `op` may have some weakrefs. March over the list, clear - * all the weakrefs, and move the weakrefs with callbacks - * that must be called into wrcb_to_call. - */ - for (wr = *wrlist; wr != NULL; wr = *wrlist) { - PyGC_Head *wrasgc; /* AS_GC(wr) */ - - /* _PyWeakref_ClearRef clears the weakref but leaves - * the callback pointer intact. Obscure: it also - * changes *wrlist. - */ - assert(wr->wr_object == op); - _PyWeakref_ClearRef(wr); - assert(wr->wr_object == Py_None); - if (wr->wr_callback == NULL) - continue; /* no callback */ - - /* Headache time. `op` is going away, and is weakly referenced by - * `wr`, which has a callback. Should the callback be invoked? If wr - * is also trash, no: - * - * 1. There's no need to call it. The object and the weakref are - * both going away, so it's legitimate to pretend the weakref is - * going away first. The user has to ensure a weakref outlives its - * referent if they want a guarantee that the wr callback will get - * invoked. - * - * 2. It may be catastrophic to call it. If the callback is also in - * cyclic trash (CT), then although the CT is unreachable from - * outside the current generation, CT may be reachable from the - * callback. Then the callback could resurrect insane objects. - * - * Since the callback is never needed and may be unsafe in this case, - * wr is simply left in the unreachable set. Note that because we - * already called _PyWeakref_ClearRef(wr), its callback will never - * trigger. - * - * OTOH, if wr isn't part of CT, we should invoke the callback: the - * weakref outlived the trash. Note that since wr isn't CT in this - * case, its callback can't be CT either -- wr acted as an external - * root to this generation, and therefore its callback did too. So - * nothing in CT is reachable from the callback either, so it's hard - * to imagine how calling it later could create a problem for us. wr - * is moved to wrcb_to_call in this case. - */ - if (IS_TENTATIVELY_UNREACHABLE(wr)) - continue; - assert(IS_REACHABLE(wr)); - - /* Create a new reference so that wr can't go away - * before we can process it again. - */ - Py_INCREF(wr); - - /* Move wr to wrcb_to_call, for the next pass. */ - wrasgc = AS_GC(wr); - assert(wrasgc != next); /* wrasgc is reachable, but - next isn't, so they can't - be the same */ - gc_list_move(wrasgc, &wrcb_to_call); - } - } - - /* Invoke the callbacks we decided to honor. It's safe to invoke them - * because they can't reference unreachable objects. - */ - while (! gc_list_is_empty(&wrcb_to_call)) { - PyObject *temp; - PyObject *callback; - - gc = wrcb_to_call.gc.gc_next; - op = FROM_GC(gc); - assert(IS_REACHABLE(op)); - assert(PyWeakref_Check(op)); - wr = (PyWeakReference *)op; - callback = wr->wr_callback; - assert(callback != NULL); - - /* copy-paste of weakrefobject.c's handle_callback() */ - temp = PyObject_CallFunctionObjArgs(callback, wr, NULL); - if (temp == NULL) - PyErr_WriteUnraisable(callback); - else - Py_DECREF(temp); - - /* Give up the reference we created in the first pass. When - * op's refcount hits 0 (which it may or may not do right now), - * op's tp_dealloc will decref op->wr_callback too. Note - * that the refcount probably will hit 0 now, and because this - * weakref was reachable to begin with, gc didn't already - * add it to its count of freed objects. Example: a reachable - * weak value dict maps some key to this reachable weakref. - * The callback removes this key->weakref mapping from the - * dict, leaving no other references to the weakref (excepting - * ours). - */ - Py_DECREF(op); - if (wrcb_to_call.gc.gc_next == gc) { - /* object is still alive -- move it */ - gc_list_move(gc, old); - } - else - ++num_freed; - } + PyGC_Head *gc; + PyObject *op; /* generally FROM_GC(gc) */ + PyWeakReference *wr; /* generally a cast of op */ + PyGC_Head wrcb_to_call; /* weakrefs with callbacks to call */ + PyGC_Head *next; + int num_freed = 0; + + gc_list_init(&wrcb_to_call); + + /* Clear all weakrefs to the objects in unreachable. If such a weakref + * also has a callback, move it into `wrcb_to_call` if the callback + * needs to be invoked. Note that we cannot invoke any callbacks until + * all weakrefs to unreachable objects are cleared, lest the callback + * resurrect an unreachable object via a still-active weakref. We + * make another pass over wrcb_to_call, invoking callbacks, after this + * pass completes. + */ + for (gc = unreachable->gc.gc_next; gc != unreachable; gc = next) { + PyWeakReference **wrlist; + + op = FROM_GC(gc); + assert(IS_TENTATIVELY_UNREACHABLE(op)); + next = gc->gc.gc_next; + + if (! PyType_SUPPORTS_WEAKREFS(Py_TYPE(op))) + continue; + + /* It supports weakrefs. Does it have any? */ + wrlist = (PyWeakReference **) + PyObject_GET_WEAKREFS_LISTPTR(op); + + /* `op` may have some weakrefs. March over the list, clear + * all the weakrefs, and move the weakrefs with callbacks + * that must be called into wrcb_to_call. + */ + for (wr = *wrlist; wr != NULL; wr = *wrlist) { + PyGC_Head *wrasgc; /* AS_GC(wr) */ + + /* _PyWeakref_ClearRef clears the weakref but leaves + * the callback pointer intact. Obscure: it also + * changes *wrlist. + */ + assert(wr->wr_object == op); + _PyWeakref_ClearRef(wr); + assert(wr->wr_object == Py_None); + if (wr->wr_callback == NULL) + continue; /* no callback */ + + /* Headache time. `op` is going away, and is weakly referenced by + * `wr`, which has a callback. Should the callback be invoked? If wr + * is also trash, no: + * + * 1. There's no need to call it. The object and the weakref are + * both going away, so it's legitimate to pretend the weakref is + * going away first. The user has to ensure a weakref outlives its + * referent if they want a guarantee that the wr callback will get + * invoked. + * + * 2. It may be catastrophic to call it. If the callback is also in + * cyclic trash (CT), then although the CT is unreachable from + * outside the current generation, CT may be reachable from the + * callback. Then the callback could resurrect insane objects. + * + * Since the callback is never needed and may be unsafe in this case, + * wr is simply left in the unreachable set. Note that because we + * already called _PyWeakref_ClearRef(wr), its callback will never + * trigger. + * + * OTOH, if wr isn't part of CT, we should invoke the callback: the + * weakref outlived the trash. Note that since wr isn't CT in this + * case, its callback can't be CT either -- wr acted as an external + * root to this generation, and therefore its callback did too. So + * nothing in CT is reachable from the callback either, so it's hard + * to imagine how calling it later could create a problem for us. wr + * is moved to wrcb_to_call in this case. + */ + if (IS_TENTATIVELY_UNREACHABLE(wr)) + continue; + assert(IS_REACHABLE(wr)); + + /* Create a new reference so that wr can't go away + * before we can process it again. + */ + Py_INCREF(wr); + + /* Move wr to wrcb_to_call, for the next pass. */ + wrasgc = AS_GC(wr); + assert(wrasgc != next); /* wrasgc is reachable, but + next isn't, so they can't + be the same */ + gc_list_move(wrasgc, &wrcb_to_call); + } + } + + /* Invoke the callbacks we decided to honor. It's safe to invoke them + * because they can't reference unreachable objects. + */ + while (! gc_list_is_empty(&wrcb_to_call)) { + PyObject *temp; + PyObject *callback; + + gc = wrcb_to_call.gc.gc_next; + op = FROM_GC(gc); + assert(IS_REACHABLE(op)); + assert(PyWeakref_Check(op)); + wr = (PyWeakReference *)op; + callback = wr->wr_callback; + assert(callback != NULL); + + /* copy-paste of weakrefobject.c's handle_callback() */ + temp = PyObject_CallFunctionObjArgs(callback, wr, NULL); + if (temp == NULL) + PyErr_WriteUnraisable(callback); + else + Py_DECREF(temp); + + /* Give up the reference we created in the first pass. When + * op's refcount hits 0 (which it may or may not do right now), + * op's tp_dealloc will decref op->wr_callback too. Note + * that the refcount probably will hit 0 now, and because this + * weakref was reachable to begin with, gc didn't already + * add it to its count of freed objects. Example: a reachable + * weak value dict maps some key to this reachable weakref. + * The callback removes this key->weakref mapping from the + * dict, leaving no other references to the weakref (excepting + * ours). + */ + Py_DECREF(op); + if (wrcb_to_call.gc.gc_next == gc) { + /* object is still alive -- move it */ + gc_list_move(gc, old); + } + else + ++num_freed; + } - return num_freed; + return num_freed; } static void debug_cycle(char *msg, PyObject *op) { - PySys_WriteStderr("gc: %.100s <%.100s %p>\n", - msg, Py_TYPE(op)->tp_name, op); + PySys_WriteStderr("gc: %.100s <%.100s %p>\n", + msg, Py_TYPE(op)->tp_name, op); } /* Handle uncollectable garbage (cycles with finalizers, and stuff reachable @@ -696,56 +696,56 @@ static int handle_finalizers(PyGC_Head *finalizers, PyGC_Head *old) { - PyGC_Head *gc = finalizers->gc.gc_next; + PyGC_Head *gc = finalizers->gc.gc_next; - if (garbage == NULL) { - garbage = PyList_New(0); - if (garbage == NULL) - Py_FatalError("gc couldn't create gc.garbage list"); - } - for (; gc != finalizers; gc = gc->gc.gc_next) { - PyObject *op = FROM_GC(gc); - - if ((debug & DEBUG_SAVEALL) || has_finalizer(op)) { - if (PyList_Append(garbage, op) < 0) - return -1; - } - } + if (garbage == NULL) { + garbage = PyList_New(0); + if (garbage == NULL) + Py_FatalError("gc couldn't create gc.garbage list"); + } + for (; gc != finalizers; gc = gc->gc.gc_next) { + PyObject *op = FROM_GC(gc); + + if ((debug & DEBUG_SAVEALL) || has_finalizer(op)) { + if (PyList_Append(garbage, op) < 0) + return -1; + } + } - gc_list_merge(finalizers, old); - return 0; + gc_list_merge(finalizers, old); + return 0; } -/* Break reference cycles by clearing the containers involved. This is +/* Break reference cycles by clearing the containers involved. This is * tricky business as the lists can be changing and we don't know which * objects may be freed. It is possible I screwed something up here. */ static void delete_garbage(PyGC_Head *collectable, PyGC_Head *old) { - inquiry clear; + inquiry clear; - while (!gc_list_is_empty(collectable)) { - PyGC_Head *gc = collectable->gc.gc_next; - PyObject *op = FROM_GC(gc); - - assert(IS_TENTATIVELY_UNREACHABLE(op)); - if (debug & DEBUG_SAVEALL) { - PyList_Append(garbage, op); - } - else { - if ((clear = Py_TYPE(op)->tp_clear) != NULL) { - Py_INCREF(op); - clear(op); - Py_DECREF(op); - } - } - if (collectable->gc.gc_next == gc) { - /* object is still alive, move it, it may die later */ - gc_list_move(gc, old); - gc->gc.gc_refs = GC_REACHABLE; - } - } + while (!gc_list_is_empty(collectable)) { + PyGC_Head *gc = collectable->gc.gc_next; + PyObject *op = FROM_GC(gc); + + assert(IS_TENTATIVELY_UNREACHABLE(op)); + if (debug & DEBUG_SAVEALL) { + PyList_Append(garbage, op); + } + else { + if ((clear = Py_TYPE(op)->tp_clear) != NULL) { + Py_INCREF(op); + clear(op); + Py_DECREF(op); + } + } + if (collectable->gc.gc_next == gc) { + /* object is still alive, move it, it may die later */ + gc_list_move(gc, old); + gc->gc.gc_refs = GC_REACHABLE; + } + } } /* Clear all free lists @@ -756,30 +756,30 @@ static void clear_freelists(void) { - (void)PyMethod_ClearFreeList(); - (void)PyFrame_ClearFreeList(); - (void)PyCFunction_ClearFreeList(); - (void)PyTuple_ClearFreeList(); - (void)PyUnicode_ClearFreeList(); - (void)PyFloat_ClearFreeList(); + (void)PyMethod_ClearFreeList(); + (void)PyFrame_ClearFreeList(); + (void)PyCFunction_ClearFreeList(); + (void)PyTuple_ClearFreeList(); + (void)PyUnicode_ClearFreeList(); + (void)PyFloat_ClearFreeList(); } static double get_time(void) { - double result = 0; - if (tmod != NULL) { - PyObject *f = PyObject_CallMethod(tmod, "time", NULL); - if (f == NULL) { - PyErr_Clear(); - } - else { - if (PyFloat_Check(f)) - result = PyFloat_AsDouble(f); - Py_DECREF(f); - } - } - return result; + double result = 0; + if (tmod != NULL) { + PyObject *f = PyObject_CallMethod(tmod, "time", NULL); + if (f == NULL) { + PyErr_Clear(); + } + else { + if (PyFloat_Check(f)) + result = PyFloat_AsDouble(f); + Py_DECREF(f); + } + } + return result; } /* This is the main function. Read this to understand how the @@ -787,184 +787,184 @@ static Py_ssize_t collect(int generation) { - int i; - Py_ssize_t m = 0; /* # objects collected */ - Py_ssize_t n = 0; /* # unreachable objects that couldn't be collected */ - PyGC_Head *young; /* the generation we are examining */ - PyGC_Head *old; /* next older generation */ - PyGC_Head unreachable; /* non-problematic unreachable trash */ - PyGC_Head finalizers; /* objects with, & reachable from, __del__ */ - PyGC_Head *gc; - double t1 = 0.0; - - if (delstr == NULL) { - delstr = PyUnicode_InternFromString("__del__"); - if (delstr == NULL) - Py_FatalError("gc couldn't allocate \"__del__\""); - } - - if (debug & DEBUG_STATS) { - PySys_WriteStderr("gc: collecting generation %d...\n", - generation); - PySys_WriteStderr("gc: objects in each generation:"); - for (i = 0; i < NUM_GENERATIONS; i++) - PySys_WriteStderr(" %" PY_FORMAT_SIZE_T "d", - gc_list_size(GEN_HEAD(i))); - t1 = get_time(); - PySys_WriteStderr("\n"); - } - - /* update collection and allocation counters */ - if (generation+1 < NUM_GENERATIONS) - generations[generation+1].count += 1; - for (i = 0; i <= generation; i++) - generations[i].count = 0; - - /* merge younger generations with one we are currently collecting */ - for (i = 0; i < generation; i++) { - gc_list_merge(GEN_HEAD(i), GEN_HEAD(generation)); - } - - /* handy references */ - young = GEN_HEAD(generation); - if (generation < NUM_GENERATIONS-1) - old = GEN_HEAD(generation+1); - else - old = young; - - /* Using ob_refcnt and gc_refs, calculate which objects in the - * container set are reachable from outside the set (i.e., have a - * refcount greater than 0 when all the references within the - * set are taken into account). - */ - update_refs(young); - subtract_refs(young); - - /* Leave everything reachable from outside young in young, and move - * everything else (in young) to unreachable. - * NOTE: This used to move the reachable objects into a reachable - * set instead. But most things usually turn out to be reachable, - * so it's more efficient to move the unreachable things. - */ - gc_list_init(&unreachable); - move_unreachable(young, &unreachable); - - /* Move reachable objects to next generation. */ - if (young != old) { - if (generation == NUM_GENERATIONS - 2) { - long_lived_pending += gc_list_size(young); - } - gc_list_merge(young, old); - } - else { - long_lived_pending = 0; - long_lived_total = gc_list_size(young); - } - - /* All objects in unreachable are trash, but objects reachable from - * finalizers can't safely be deleted. Python programmers should take - * care not to create such things. For Python, finalizers means - * instance objects with __del__ methods. Weakrefs with callbacks - * can also call arbitrary Python code but they will be dealt with by - * handle_weakrefs(). - */ - gc_list_init(&finalizers); - move_finalizers(&unreachable, &finalizers); - /* finalizers contains the unreachable objects with a finalizer; - * unreachable objects reachable *from* those are also uncollectable, - * and we move those into the finalizers list too. - */ - move_finalizer_reachable(&finalizers); - - /* Collect statistics on collectable objects found and print - * debugging information. - */ - for (gc = unreachable.gc.gc_next; gc != &unreachable; - gc = gc->gc.gc_next) { - m++; - if (debug & DEBUG_COLLECTABLE) { - debug_cycle("collectable", FROM_GC(gc)); - } - } - - /* Clear weakrefs and invoke callbacks as necessary. */ - m += handle_weakrefs(&unreachable, old); - - /* Call tp_clear on objects in the unreachable set. This will cause - * the reference cycles to be broken. It may also cause some objects - * in finalizers to be freed. - */ - delete_garbage(&unreachable, old); - - /* Collect statistics on uncollectable objects found and print - * debugging information. */ - for (gc = finalizers.gc.gc_next; - gc != &finalizers; - gc = gc->gc.gc_next) { - n++; - if (debug & DEBUG_UNCOLLECTABLE) - debug_cycle("uncollectable", FROM_GC(gc)); - } - if (debug & DEBUG_STATS) { - double t2 = get_time(); - if (m == 0 && n == 0) - PySys_WriteStderr("gc: done"); - else - PySys_WriteStderr( - "gc: done, " - "%" PY_FORMAT_SIZE_T "d unreachable, " - "%" PY_FORMAT_SIZE_T "d uncollectable", - n+m, n); - if (t1 && t2) { - PySys_WriteStderr(", %.4fs elapsed", t2-t1); - } - PySys_WriteStderr(".\n"); - } - - /* Append instances in the uncollectable set to a Python - * 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); - - /* Clear free list only during the collection of the highest - * generation */ - if (generation == NUM_GENERATIONS-1) { - clear_freelists(); - } - - if (PyErr_Occurred()) { - if (gc_str == NULL) - gc_str = PyUnicode_FromString("garbage collection"); - PyErr_WriteUnraisable(gc_str); - Py_FatalError("unexpected exception during garbage collection"); - } - return n+m; + int i; + Py_ssize_t m = 0; /* # objects collected */ + Py_ssize_t n = 0; /* # unreachable objects that couldn't be collected */ + PyGC_Head *young; /* the generation we are examining */ + PyGC_Head *old; /* next older generation */ + PyGC_Head unreachable; /* non-problematic unreachable trash */ + PyGC_Head finalizers; /* objects with, & reachable from, __del__ */ + PyGC_Head *gc; + double t1 = 0.0; + + if (delstr == NULL) { + delstr = PyUnicode_InternFromString("__del__"); + if (delstr == NULL) + Py_FatalError("gc couldn't allocate \"__del__\""); + } + + if (debug & DEBUG_STATS) { + PySys_WriteStderr("gc: collecting generation %d...\n", + generation); + PySys_WriteStderr("gc: objects in each generation:"); + for (i = 0; i < NUM_GENERATIONS; i++) + PySys_WriteStderr(" %" PY_FORMAT_SIZE_T "d", + gc_list_size(GEN_HEAD(i))); + t1 = get_time(); + PySys_WriteStderr("\n"); + } + + /* update collection and allocation counters */ + if (generation+1 < NUM_GENERATIONS) + generations[generation+1].count += 1; + for (i = 0; i <= generation; i++) + generations[i].count = 0; + + /* merge younger generations with one we are currently collecting */ + for (i = 0; i < generation; i++) { + gc_list_merge(GEN_HEAD(i), GEN_HEAD(generation)); + } + + /* handy references */ + young = GEN_HEAD(generation); + if (generation < NUM_GENERATIONS-1) + old = GEN_HEAD(generation+1); + else + old = young; + + /* Using ob_refcnt and gc_refs, calculate which objects in the + * container set are reachable from outside the set (i.e., have a + * refcount greater than 0 when all the references within the + * set are taken into account). + */ + update_refs(young); + subtract_refs(young); + + /* Leave everything reachable from outside young in young, and move + * everything else (in young) to unreachable. + * NOTE: This used to move the reachable objects into a reachable + * set instead. But most things usually turn out to be reachable, + * so it's more efficient to move the unreachable things. + */ + gc_list_init(&unreachable); + move_unreachable(young, &unreachable); + + /* Move reachable objects to next generation. */ + if (young != old) { + if (generation == NUM_GENERATIONS - 2) { + long_lived_pending += gc_list_size(young); + } + gc_list_merge(young, old); + } + else { + long_lived_pending = 0; + long_lived_total = gc_list_size(young); + } + + /* All objects in unreachable are trash, but objects reachable from + * finalizers can't safely be deleted. Python programmers should take + * care not to create such things. For Python, finalizers means + * instance objects with __del__ methods. Weakrefs with callbacks + * can also call arbitrary Python code but they will be dealt with by + * handle_weakrefs(). + */ + gc_list_init(&finalizers); + move_finalizers(&unreachable, &finalizers); + /* finalizers contains the unreachable objects with a finalizer; + * unreachable objects reachable *from* those are also uncollectable, + * and we move those into the finalizers list too. + */ + move_finalizer_reachable(&finalizers); + + /* Collect statistics on collectable objects found and print + * debugging information. + */ + for (gc = unreachable.gc.gc_next; gc != &unreachable; + gc = gc->gc.gc_next) { + m++; + if (debug & DEBUG_COLLECTABLE) { + debug_cycle("collectable", FROM_GC(gc)); + } + } + + /* Clear weakrefs and invoke callbacks as necessary. */ + m += handle_weakrefs(&unreachable, old); + + /* Call tp_clear on objects in the unreachable set. This will cause + * the reference cycles to be broken. It may also cause some objects + * in finalizers to be freed. + */ + delete_garbage(&unreachable, old); + + /* Collect statistics on uncollectable objects found and print + * debugging information. */ + for (gc = finalizers.gc.gc_next; + gc != &finalizers; + gc = gc->gc.gc_next) { + n++; + if (debug & DEBUG_UNCOLLECTABLE) + debug_cycle("uncollectable", FROM_GC(gc)); + } + if (debug & DEBUG_STATS) { + double t2 = get_time(); + if (m == 0 && n == 0) + PySys_WriteStderr("gc: done"); + else + PySys_WriteStderr( + "gc: done, " + "%" PY_FORMAT_SIZE_T "d unreachable, " + "%" PY_FORMAT_SIZE_T "d uncollectable", + n+m, n); + if (t1 && t2) { + PySys_WriteStderr(", %.4fs elapsed", t2-t1); + } + PySys_WriteStderr(".\n"); + } + + /* Append instances in the uncollectable set to a Python + * 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); + + /* Clear free list only during the collection of the highest + * generation */ + if (generation == NUM_GENERATIONS-1) { + clear_freelists(); + } + + if (PyErr_Occurred()) { + if (gc_str == NULL) + gc_str = PyUnicode_FromString("garbage collection"); + PyErr_WriteUnraisable(gc_str); + Py_FatalError("unexpected exception during garbage collection"); + } + return n+m; } static Py_ssize_t collect_generations(void) { - int i; - Py_ssize_t n = 0; + int i; + Py_ssize_t n = 0; - /* Find the oldest generation (highest numbered) where the count - * exceeds the threshold. Objects in the that generation and - * generations younger than it will be collected. */ - for (i = NUM_GENERATIONS-1; i >= 0; i--) { - if (generations[i].count > generations[i].threshold) { - /* Avoid quadratic performance degradation in number - of tracked objects. See comments at the beginning - of this file, and issue #4074. - */ - if (i == NUM_GENERATIONS - 1 - && long_lived_pending < long_lived_total / 4) - continue; - n = collect(i); - break; - } - } - return n; + /* Find the oldest generation (highest numbered) where the count + * exceeds the threshold. Objects in the that generation and + * generations younger than it will be collected. */ + for (i = NUM_GENERATIONS-1; i >= 0; i--) { + if (generations[i].count > generations[i].threshold) { + /* Avoid quadratic performance degradation in number + of tracked objects. See comments at the beginning + of this file, and issue #4074. + */ + if (i == NUM_GENERATIONS - 1 + && long_lived_pending < long_lived_total / 4) + continue; + n = collect(i); + break; + } + } + return n; } PyDoc_STRVAR(gc_enable__doc__, @@ -975,9 +975,9 @@ static PyObject * gc_enable(PyObject *self, PyObject *noargs) { - enabled = 1; - Py_INCREF(Py_None); - return Py_None; + enabled = 1; + Py_INCREF(Py_None); + return Py_None; } PyDoc_STRVAR(gc_disable__doc__, @@ -988,9 +988,9 @@ static PyObject * gc_disable(PyObject *self, PyObject *noargs) { - enabled = 0; - Py_INCREF(Py_None); - return Py_None; + enabled = 0; + Py_INCREF(Py_None); + return Py_None; } PyDoc_STRVAR(gc_isenabled__doc__, @@ -1001,7 +1001,7 @@ static PyObject * gc_isenabled(PyObject *self, PyObject *noargs) { - return PyBool_FromLong((long)enabled); + return PyBool_FromLong((long)enabled); } PyDoc_STRVAR(gc_collect__doc__, @@ -1015,27 +1015,27 @@ static PyObject * gc_collect(PyObject *self, PyObject *args, PyObject *kws) { - static char *keywords[] = {"generation", NULL}; - int genarg = NUM_GENERATIONS - 1; - Py_ssize_t n; - - if (!PyArg_ParseTupleAndKeywords(args, kws, "|i", keywords, &genarg)) - return NULL; - - else if (genarg < 0 || genarg >= NUM_GENERATIONS) { - PyErr_SetString(PyExc_ValueError, "invalid generation"); - return NULL; - } - - if (collecting) - n = 0; /* already collecting, don't do anything */ - else { - collecting = 1; - n = collect(genarg); - collecting = 0; - } + static char *keywords[] = {"generation", NULL}; + int genarg = NUM_GENERATIONS - 1; + Py_ssize_t n; + + if (!PyArg_ParseTupleAndKeywords(args, kws, "|i", keywords, &genarg)) + return NULL; + + else if (genarg < 0 || genarg >= NUM_GENERATIONS) { + PyErr_SetString(PyExc_ValueError, "invalid generation"); + return NULL; + } + + if (collecting) + n = 0; /* already collecting, don't do anything */ + else { + collecting = 1; + n = collect(genarg); + collecting = 0; + } - return PyLong_FromSsize_t(n); + return PyLong_FromSsize_t(n); } PyDoc_STRVAR(gc_set_debug__doc__, @@ -1055,11 +1055,11 @@ static PyObject * gc_set_debug(PyObject *self, PyObject *args) { - if (!PyArg_ParseTuple(args, "i:set_debug", &debug)) - return NULL; + if (!PyArg_ParseTuple(args, "i:set_debug", &debug)) + return NULL; - Py_INCREF(Py_None); - return Py_None; + Py_INCREF(Py_None); + return Py_None; } PyDoc_STRVAR(gc_get_debug__doc__, @@ -1070,7 +1070,7 @@ static PyObject * gc_get_debug(PyObject *self, PyObject *noargs) { - return Py_BuildValue("i", debug); + return Py_BuildValue("i", debug); } PyDoc_STRVAR(gc_set_thresh__doc__, @@ -1082,19 +1082,19 @@ static PyObject * gc_set_thresh(PyObject *self, PyObject *args) { - int i; - if (!PyArg_ParseTuple(args, "i|ii:set_threshold", - &generations[0].threshold, - &generations[1].threshold, - &generations[2].threshold)) - return NULL; - for (i = 2; i < NUM_GENERATIONS; i++) { - /* generations higher than 2 get the same threshold */ - generations[i].threshold = generations[2].threshold; - } + int i; + if (!PyArg_ParseTuple(args, "i|ii:set_threshold", + &generations[0].threshold, + &generations[1].threshold, + &generations[2].threshold)) + return NULL; + for (i = 2; i < NUM_GENERATIONS; i++) { + /* generations higher than 2 get the same threshold */ + generations[i].threshold = generations[2].threshold; + } - Py_INCREF(Py_None); - return Py_None; + Py_INCREF(Py_None); + return Py_None; } PyDoc_STRVAR(gc_get_thresh__doc__, @@ -1105,10 +1105,10 @@ static PyObject * gc_get_thresh(PyObject *self, PyObject *noargs) { - return Py_BuildValue("(iii)", - generations[0].threshold, - generations[1].threshold, - generations[2].threshold); + return Py_BuildValue("(iii)", + generations[0].threshold, + generations[1].threshold, + generations[2].threshold); } PyDoc_STRVAR(gc_get_count__doc__, @@ -1119,39 +1119,39 @@ static PyObject * gc_get_count(PyObject *self, PyObject *noargs) { - return Py_BuildValue("(iii)", - generations[0].count, - generations[1].count, - generations[2].count); + return Py_BuildValue("(iii)", + generations[0].count, + generations[1].count, + generations[2].count); } static int referrersvisit(PyObject* obj, PyObject *objs) { - Py_ssize_t i; - for (i = 0; i < PyTuple_GET_SIZE(objs); i++) - if (PyTuple_GET_ITEM(objs, i) == obj) - return 1; - return 0; + Py_ssize_t i; + for (i = 0; i < PyTuple_GET_SIZE(objs); i++) + if (PyTuple_GET_ITEM(objs, i) == obj) + return 1; + return 0; } static int gc_referrers_for(PyObject *objs, PyGC_Head *list, PyObject *resultlist) { - PyGC_Head *gc; - PyObject *obj; - traverseproc traverse; - for (gc = list->gc.gc_next; gc != list; gc = gc->gc.gc_next) { - obj = FROM_GC(gc); - traverse = Py_TYPE(obj)->tp_traverse; - if (obj == objs || obj == resultlist) - continue; - if (traverse(obj, (visitproc)referrersvisit, objs)) { - if (PyList_Append(resultlist, obj) < 0) - return 0; /* error */ - } - } - return 1; /* no error */ + PyGC_Head *gc; + PyObject *obj; + traverseproc traverse; + for (gc = list->gc.gc_next; gc != list; gc = gc->gc.gc_next) { + obj = FROM_GC(gc); + traverse = Py_TYPE(obj)->tp_traverse; + if (obj == objs || obj == resultlist) + continue; + if (traverse(obj, (visitproc)referrersvisit, objs)) { + if (PyList_Append(resultlist, obj) < 0) + return 0; /* error */ + } + } + return 1; /* no error */ } PyDoc_STRVAR(gc_get_referrers__doc__, @@ -1161,24 +1161,24 @@ static PyObject * gc_get_referrers(PyObject *self, PyObject *args) { - int i; - PyObject *result = PyList_New(0); - if (!result) return NULL; - - for (i = 0; i < NUM_GENERATIONS; i++) { - if (!(gc_referrers_for(args, GEN_HEAD(i), result))) { - Py_DECREF(result); - return NULL; - } - } - return result; + int i; + PyObject *result = PyList_New(0); + if (!result) return NULL; + + for (i = 0; i < NUM_GENERATIONS; i++) { + if (!(gc_referrers_for(args, GEN_HEAD(i), result))) { + Py_DECREF(result); + return NULL; + } + } + return result; } /* Append obj to list; return true if error (out of memory), false if OK. */ static int referentsvisit(PyObject *obj, PyObject *list) { - return PyList_Append(list, obj) < 0; + return PyList_Append(list, obj) < 0; } PyDoc_STRVAR(gc_get_referents__doc__, @@ -1188,27 +1188,27 @@ static PyObject * gc_get_referents(PyObject *self, PyObject *args) { - Py_ssize_t i; - PyObject *result = PyList_New(0); + Py_ssize_t i; + PyObject *result = PyList_New(0); - if (result == NULL) - return NULL; + if (result == NULL) + return NULL; - for (i = 0; i < PyTuple_GET_SIZE(args); i++) { - traverseproc traverse; - PyObject *obj = PyTuple_GET_ITEM(args, i); - - if (! PyObject_IS_GC(obj)) - continue; - traverse = Py_TYPE(obj)->tp_traverse; - if (! traverse) - continue; - if (traverse(obj, (visitproc)referentsvisit, result)) { - Py_DECREF(result); - return NULL; - } - } - return result; + for (i = 0; i < PyTuple_GET_SIZE(args); i++) { + traverseproc traverse; + PyObject *obj = PyTuple_GET_ITEM(args, i); + + if (! PyObject_IS_GC(obj)) + continue; + traverse = Py_TYPE(obj)->tp_traverse; + if (! traverse) + continue; + if (traverse(obj, (visitproc)referentsvisit, result)) { + Py_DECREF(result); + return NULL; + } + } + return result; } PyDoc_STRVAR(gc_get_objects__doc__, @@ -1220,19 +1220,19 @@ static PyObject * gc_get_objects(PyObject *self, PyObject *noargs) { - int i; - PyObject* result; + int i; + PyObject* result; - result = PyList_New(0); - if (result == NULL) - return NULL; - for (i = 0; i < NUM_GENERATIONS; i++) { - if (append_objects(result, GEN_HEAD(i))) { - Py_DECREF(result); - return NULL; - } - } - return result; + result = PyList_New(0); + if (result == NULL) + return NULL; + for (i = 0; i < NUM_GENERATIONS; i++) { + if (append_objects(result, GEN_HEAD(i))) { + Py_DECREF(result); + return NULL; + } + } + return result; } PyDoc_STRVAR(gc_is_tracked__doc__, @@ -1245,14 +1245,14 @@ static PyObject * gc_is_tracked(PyObject *self, PyObject *obj) { - PyObject *result; - - if (PyObject_IS_GC(obj) && IS_TRACKED(obj)) - result = Py_True; - else - result = Py_False; - Py_INCREF(result); - return result; + PyObject *result; + + if (PyObject_IS_GC(obj) && IS_TRACKED(obj)) + result = Py_True; + else + result = Py_False; + Py_INCREF(result); + return result; } @@ -1274,101 +1274,101 @@ "get_referents() -- Return the list of objects that an object refers to.\n"); static PyMethodDef GcMethods[] = { - {"enable", gc_enable, METH_NOARGS, gc_enable__doc__}, - {"disable", gc_disable, METH_NOARGS, gc_disable__doc__}, - {"isenabled", gc_isenabled, METH_NOARGS, gc_isenabled__doc__}, - {"set_debug", gc_set_debug, METH_VARARGS, gc_set_debug__doc__}, - {"get_debug", gc_get_debug, METH_NOARGS, gc_get_debug__doc__}, - {"get_count", gc_get_count, METH_NOARGS, gc_get_count__doc__}, - {"set_threshold", gc_set_thresh, METH_VARARGS, gc_set_thresh__doc__}, - {"get_threshold", gc_get_thresh, METH_NOARGS, gc_get_thresh__doc__}, - {"collect", (PyCFunction)gc_collect, - METH_VARARGS | METH_KEYWORDS, gc_collect__doc__}, - {"get_objects", gc_get_objects,METH_NOARGS, gc_get_objects__doc__}, - {"is_tracked", gc_is_tracked, METH_O, gc_is_tracked__doc__}, - {"get_referrers", gc_get_referrers, METH_VARARGS, - gc_get_referrers__doc__}, - {"get_referents", gc_get_referents, METH_VARARGS, - gc_get_referents__doc__}, - {NULL, NULL} /* Sentinel */ + {"enable", gc_enable, METH_NOARGS, gc_enable__doc__}, + {"disable", gc_disable, METH_NOARGS, gc_disable__doc__}, + {"isenabled", gc_isenabled, METH_NOARGS, gc_isenabled__doc__}, + {"set_debug", gc_set_debug, METH_VARARGS, gc_set_debug__doc__}, + {"get_debug", gc_get_debug, METH_NOARGS, gc_get_debug__doc__}, + {"get_count", gc_get_count, METH_NOARGS, gc_get_count__doc__}, + {"set_threshold", gc_set_thresh, METH_VARARGS, gc_set_thresh__doc__}, + {"get_threshold", gc_get_thresh, METH_NOARGS, gc_get_thresh__doc__}, + {"collect", (PyCFunction)gc_collect, + METH_VARARGS | METH_KEYWORDS, gc_collect__doc__}, + {"get_objects", gc_get_objects,METH_NOARGS, gc_get_objects__doc__}, + {"is_tracked", gc_is_tracked, METH_O, gc_is_tracked__doc__}, + {"get_referrers", gc_get_referrers, METH_VARARGS, + gc_get_referrers__doc__}, + {"get_referents", gc_get_referents, METH_VARARGS, + gc_get_referents__doc__}, + {NULL, NULL} /* Sentinel */ }; static struct PyModuleDef gcmodule = { - PyModuleDef_HEAD_INIT, - "gc", - gc__doc__, - -1, - GcMethods, - NULL, - NULL, - NULL, - NULL + PyModuleDef_HEAD_INIT, + "gc", + gc__doc__, + -1, + GcMethods, + NULL, + NULL, + NULL, + NULL }; PyMODINIT_FUNC PyInit_gc(void) { - PyObject *m; + PyObject *m; - m = PyModule_Create(&gcmodule); + m = PyModule_Create(&gcmodule); - if (m == NULL) - return NULL; + if (m == NULL) + return NULL; - if (garbage == NULL) { - garbage = PyList_New(0); - if (garbage == NULL) - return NULL; - } - Py_INCREF(garbage); - if (PyModule_AddObject(m, "garbage", garbage) < 0) - return NULL; - - /* Importing can't be done in collect() because collect() - * can be called via PyGC_Collect() in Py_Finalize(). - * This wouldn't be a problem, except that is - * reset to 0 before calling collect which trips up - * the import and triggers an assertion. - */ - if (tmod == NULL) { - tmod = PyImport_ImportModuleNoBlock("time"); - if (tmod == NULL) - PyErr_Clear(); - } + if (garbage == NULL) { + garbage = PyList_New(0); + if (garbage == NULL) + return NULL; + } + Py_INCREF(garbage); + if (PyModule_AddObject(m, "garbage", garbage) < 0) + return NULL; + + /* Importing can't be done in collect() because collect() + * can be called via PyGC_Collect() in Py_Finalize(). + * This wouldn't be a problem, except that is + * reset to 0 before calling collect which trips up + * the import and triggers an assertion. + */ + if (tmod == NULL) { + tmod = PyImport_ImportModuleNoBlock("time"); + if (tmod == NULL) + PyErr_Clear(); + } #define ADD_INT(NAME) if (PyModule_AddIntConstant(m, #NAME, NAME) < 0) return NULL - ADD_INT(DEBUG_STATS); - ADD_INT(DEBUG_COLLECTABLE); - ADD_INT(DEBUG_UNCOLLECTABLE); - ADD_INT(DEBUG_SAVEALL); - ADD_INT(DEBUG_LEAK); + ADD_INT(DEBUG_STATS); + ADD_INT(DEBUG_COLLECTABLE); + ADD_INT(DEBUG_UNCOLLECTABLE); + ADD_INT(DEBUG_SAVEALL); + ADD_INT(DEBUG_LEAK); #undef ADD_INT - return m; + return m; } /* API to invoke gc.collect() from C */ Py_ssize_t PyGC_Collect(void) { - Py_ssize_t n; + Py_ssize_t n; - if (collecting) - n = 0; /* already collecting, don't do anything */ - else { - collecting = 1; - n = collect(NUM_GENERATIONS - 1); - collecting = 0; - } + if (collecting) + n = 0; /* already collecting, don't do anything */ + else { + collecting = 1; + n = collect(NUM_GENERATIONS - 1); + collecting = 0; + } - return n; + return n; } /* for debugging */ void _PyGC_Dump(PyGC_Head *g) { - _PyObject_Dump(FROM_GC(g)); + _PyObject_Dump(FROM_GC(g)); } /* extension modules might be compiled with GC support so these @@ -1382,7 +1382,7 @@ void PyObject_GC_Track(void *op) { - _PyObject_GC_TRACK(op); + _PyObject_GC_TRACK(op); } /* for binary compatibility with 2.2 */ @@ -1395,11 +1395,11 @@ void PyObject_GC_UnTrack(void *op) { - /* Obscure: the Py_TRASHCAN mechanism requires that we be able to - * call PyObject_GC_UnTrack twice on an object. - */ - if (IS_TRACKED(op)) - _PyObject_GC_UNTRACK(op); + /* Obscure: the Py_TRASHCAN mechanism requires that we be able to + * call PyObject_GC_UnTrack twice on an object. + */ + if (IS_TRACKED(op)) + _PyObject_GC_UNTRACK(op); } /* for binary compatibility with 2.2 */ @@ -1412,73 +1412,73 @@ PyObject * _PyObject_GC_Malloc(size_t basicsize) { - PyObject *op; - PyGC_Head *g; - if (basicsize > PY_SSIZE_T_MAX - sizeof(PyGC_Head)) - return PyErr_NoMemory(); - g = (PyGC_Head *)PyObject_MALLOC( - sizeof(PyGC_Head) + basicsize); - if (g == NULL) - return PyErr_NoMemory(); - g->gc.gc_refs = GC_UNTRACKED; - generations[0].count++; /* number of allocated GC objects */ - if (generations[0].count > generations[0].threshold && - enabled && - generations[0].threshold && - !collecting && - !PyErr_Occurred()) { - collecting = 1; - collect_generations(); - collecting = 0; - } - op = FROM_GC(g); - return op; + PyObject *op; + PyGC_Head *g; + if (basicsize > PY_SSIZE_T_MAX - sizeof(PyGC_Head)) + return PyErr_NoMemory(); + g = (PyGC_Head *)PyObject_MALLOC( + sizeof(PyGC_Head) + basicsize); + if (g == NULL) + return PyErr_NoMemory(); + g->gc.gc_refs = GC_UNTRACKED; + generations[0].count++; /* number of allocated GC objects */ + if (generations[0].count > generations[0].threshold && + enabled && + generations[0].threshold && + !collecting && + !PyErr_Occurred()) { + collecting = 1; + collect_generations(); + collecting = 0; + } + op = FROM_GC(g); + return op; } PyObject * _PyObject_GC_New(PyTypeObject *tp) { - PyObject *op = _PyObject_GC_Malloc(_PyObject_SIZE(tp)); - if (op != NULL) - op = PyObject_INIT(op, tp); - return op; + PyObject *op = _PyObject_GC_Malloc(_PyObject_SIZE(tp)); + if (op != NULL) + op = PyObject_INIT(op, tp); + return op; } PyVarObject * _PyObject_GC_NewVar(PyTypeObject *tp, Py_ssize_t nitems) { - const size_t size = _PyObject_VAR_SIZE(tp, nitems); - PyVarObject *op = (PyVarObject *) _PyObject_GC_Malloc(size); - if (op != NULL) - op = PyObject_INIT_VAR(op, tp, nitems); - return op; + const size_t size = _PyObject_VAR_SIZE(tp, nitems); + PyVarObject *op = (PyVarObject *) _PyObject_GC_Malloc(size); + if (op != NULL) + op = PyObject_INIT_VAR(op, tp, nitems); + return op; } PyVarObject * _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); - if (basicsize > PY_SSIZE_T_MAX - sizeof(PyGC_Head)) - return (PyVarObject *)PyErr_NoMemory(); - g = (PyGC_Head *)PyObject_REALLOC(g, sizeof(PyGC_Head) + basicsize); - if (g == NULL) - return (PyVarObject *)PyErr_NoMemory(); - op = (PyVarObject *) FROM_GC(g); - Py_SIZE(op) = nitems; - return op; + const size_t basicsize = _PyObject_VAR_SIZE(Py_TYPE(op), nitems); + PyGC_Head *g = AS_GC(op); + if (basicsize > PY_SSIZE_T_MAX - sizeof(PyGC_Head)) + return (PyVarObject *)PyErr_NoMemory(); + g = (PyGC_Head *)PyObject_REALLOC(g, sizeof(PyGC_Head) + basicsize); + if (g == NULL) + return (PyVarObject *)PyErr_NoMemory(); + op = (PyVarObject *) FROM_GC(g); + Py_SIZE(op) = nitems; + return op; } void PyObject_GC_Del(void *op) { - PyGC_Head *g = AS_GC(op); - if (IS_TRACKED(op)) - gc_list_remove(g); - if (generations[0].count > 0) { - generations[0].count--; - } - PyObject_FREE(g); + PyGC_Head *g = AS_GC(op); + if (IS_TRACKED(op)) + gc_list_remove(g); + if (generations[0].count > 0) { + generations[0].count--; + } + PyObject_FREE(g); } /* for binary compatibility with 2.2 */ Modified: python/branches/py3k-jit/Modules/getaddrinfo.c ============================================================================== --- python/branches/py3k-jit/Modules/getaddrinfo.c (original) +++ python/branches/py3k-jit/Modules/getaddrinfo.c Mon May 10 23:55:43 2010 @@ -1,7 +1,7 @@ /* * 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: @@ -13,7 +13,7 @@ * 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 @@ -73,52 +73,52 @@ static const char in_addrany[] = { 0, 0, 0, 0 }; static const char in6_addrany[] = { - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }; -static const char in_loopback[] = { 127, 0, 0, 1 }; +static const char in_loopback[] = { 127, 0, 0, 1 }; static const char in6_loopback[] = { - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1 + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1 }; struct sockinet { - u_char si_len; - u_char si_family; - u_short si_port; + u_char si_len; + u_char si_family; + u_short si_port; }; static struct gai_afd { - int a_af; - int a_addrlen; - int a_socklen; - int a_off; - const char *a_addrany; - const char *a_loopback; + int a_af; + int a_addrlen; + int a_socklen; + int a_off; + const char *a_addrany; + const char *a_loopback; } gai_afdl [] = { #ifdef ENABLE_IPV6 #define N_INET6 0 - {PF_INET6, sizeof(struct in6_addr), - sizeof(struct sockaddr_in6), - offsetof(struct sockaddr_in6, sin6_addr), - in6_addrany, in6_loopback}, + {PF_INET6, sizeof(struct in6_addr), + sizeof(struct sockaddr_in6), + offsetof(struct sockaddr_in6, sin6_addr), + in6_addrany, in6_loopback}, #define N_INET 1 #else #define N_INET 0 #endif - {PF_INET, sizeof(struct in_addr), - sizeof(struct sockaddr_in), - offsetof(struct sockaddr_in, sin_addr), - in_addrany, in_loopback}, - {0, 0, 0, 0, NULL, NULL}, + {PF_INET, sizeof(struct in_addr), + sizeof(struct sockaddr_in), + offsetof(struct sockaddr_in, sin_addr), + in_addrany, in_loopback}, + {0, 0, 0, 0, NULL, NULL}, }; #ifdef ENABLE_IPV6 -#define PTON_MAX 16 +#define PTON_MAX 16 #else -#define PTON_MAX 4 +#define PTON_MAX 4 #endif #ifndef IN_MULTICAST -#define IN_MULTICAST(i) (((i) & 0xf0000000U) == 0xe0000000U) +#define IN_MULTICAST(i) (((i) & 0xf0000000U) == 0xe0000000U) #endif #ifndef IN_EXPERIMENTAL @@ -126,73 +126,73 @@ #endif #ifndef IN_LOOPBACKNET -#define IN_LOOPBACKNET 127 +#define IN_LOOPBACKNET 127 #endif static int get_name(const char *, struct gai_afd *, - struct addrinfo **, char *, struct addrinfo *, - int); + struct addrinfo **, char *, struct addrinfo *, + int); static int get_addr(const char *, int, struct addrinfo **, - struct addrinfo *, int); + struct addrinfo *, int); static int str_isnumber(const char *); - + static char *ai_errlist[] = { - "success.", - "address family for hostname not supported.", /* EAI_ADDRFAMILY */ - "temporary failure in name resolution.", /* EAI_AGAIN */ - "invalid value for ai_flags.", /* EAI_BADFLAGS */ - "non-recoverable failure in name resolution.", /* EAI_FAIL */ - "ai_family not supported.", /* EAI_FAMILY */ - "memory allocation failure.", /* EAI_MEMORY */ - "no address associated with hostname.", /* EAI_NODATA */ - "hostname nor servname provided, or not known.",/* EAI_NONAME */ - "servname not supported for ai_socktype.", /* EAI_SERVICE */ - "ai_socktype not supported.", /* EAI_SOCKTYPE */ - "system error returned in errno.", /* EAI_SYSTEM */ - "invalid value for hints.", /* EAI_BADHINTS */ - "resolved protocol is unknown.", /* EAI_PROTOCOL */ - "unknown error.", /* EAI_MAX */ + "success.", + "address family for hostname not supported.", /* EAI_ADDRFAMILY */ + "temporary failure in name resolution.", /* EAI_AGAIN */ + "invalid value for ai_flags.", /* EAI_BADFLAGS */ + "non-recoverable failure in name resolution.", /* EAI_FAIL */ + "ai_family not supported.", /* EAI_FAMILY */ + "memory allocation failure.", /* EAI_MEMORY */ + "no address associated with hostname.", /* EAI_NODATA */ + "hostname nor servname provided, or not known.",/* EAI_NONAME */ + "servname not supported for ai_socktype.", /* EAI_SERVICE */ + "ai_socktype not supported.", /* EAI_SOCKTYPE */ + "system error returned in errno.", /* EAI_SYSTEM */ + "invalid value for hints.", /* EAI_BADHINTS */ + "resolved protocol is unknown.", /* EAI_PROTOCOL */ + "unknown error.", /* EAI_MAX */ }; #define GET_CANONNAME(ai, str) \ if (pai->ai_flags & AI_CANONNAME) {\ - if (((ai)->ai_canonname = (char *)malloc(strlen(str) + 1)) != NULL) {\ - strcpy((ai)->ai_canonname, (str));\ - } else {\ - error = EAI_MEMORY;\ - goto free;\ - }\ + if (((ai)->ai_canonname = (char *)malloc(strlen(str) + 1)) != NULL) {\ + strcpy((ai)->ai_canonname, (str));\ + } else {\ + error = EAI_MEMORY;\ + goto free;\ + }\ } #ifdef HAVE_SOCKADDR_SA_LEN #define GET_AI(ai, gai_afd, addr, port) {\ - char *p;\ - if (((ai) = (struct addrinfo *)malloc(sizeof(struct addrinfo) +\ - ((gai_afd)->a_socklen)))\ - == NULL) goto free;\ - memcpy(ai, pai, sizeof(struct addrinfo));\ - (ai)->ai_addr = (struct sockaddr *)((ai) + 1);\ - memset((ai)->ai_addr, 0, (gai_afd)->a_socklen);\ - (ai)->ai_addr->sa_len = (ai)->ai_addrlen = (gai_afd)->a_socklen;\ - (ai)->ai_addr->sa_family = (ai)->ai_family = (gai_afd)->a_af;\ - ((struct sockinet *)(ai)->ai_addr)->si_port = port;\ - p = (char *)((ai)->ai_addr);\ - memcpy(p + (gai_afd)->a_off, (addr), (gai_afd)->a_addrlen);\ + char *p;\ + if (((ai) = (struct addrinfo *)malloc(sizeof(struct addrinfo) +\ + ((gai_afd)->a_socklen)))\ + == NULL) goto free;\ + memcpy(ai, pai, sizeof(struct addrinfo));\ + (ai)->ai_addr = (struct sockaddr *)((ai) + 1);\ + memset((ai)->ai_addr, 0, (gai_afd)->a_socklen);\ + (ai)->ai_addr->sa_len = (ai)->ai_addrlen = (gai_afd)->a_socklen;\ + (ai)->ai_addr->sa_family = (ai)->ai_family = (gai_afd)->a_af;\ + ((struct sockinet *)(ai)->ai_addr)->si_port = port;\ + p = (char *)((ai)->ai_addr);\ + memcpy(p + (gai_afd)->a_off, (addr), (gai_afd)->a_addrlen);\ } #else #define GET_AI(ai, gai_afd, addr, port) {\ - char *p;\ - if (((ai) = (struct addrinfo *)malloc(sizeof(struct addrinfo) +\ - ((gai_afd)->a_socklen)))\ - == NULL) goto free;\ - memcpy(ai, pai, sizeof(struct addrinfo));\ - (ai)->ai_addr = (struct sockaddr *)((ai) + 1);\ - memset((ai)->ai_addr, 0, (gai_afd)->a_socklen);\ - (ai)->ai_addrlen = (gai_afd)->a_socklen;\ - (ai)->ai_addr->sa_family = (ai)->ai_family = (gai_afd)->a_af;\ - ((struct sockinet *)(ai)->ai_addr)->si_port = port;\ - p = (char *)((ai)->ai_addr);\ - memcpy(p + (gai_afd)->a_off, (addr), (gai_afd)->a_addrlen);\ + char *p;\ + if (((ai) = (struct addrinfo *)malloc(sizeof(struct addrinfo) +\ + ((gai_afd)->a_socklen)))\ + == NULL) goto free;\ + memcpy(ai, pai, sizeof(struct addrinfo));\ + (ai)->ai_addr = (struct sockaddr *)((ai) + 1);\ + memset((ai)->ai_addr, 0, (gai_afd)->a_socklen);\ + (ai)->ai_addrlen = (gai_afd)->a_socklen;\ + (ai)->ai_addr->sa_family = (ai)->ai_family = (gai_afd)->a_af;\ + ((struct sockinet *)(ai)->ai_addr)->si_port = port;\ + p = (char *)((ai)->ai_addr);\ + memcpy(p + (gai_afd)->a_off, (addr), (gai_afd)->a_addrlen);\ } #endif @@ -201,438 +201,438 @@ char * gai_strerror(int ecode) { - if (ecode < 0 || ecode > EAI_MAX) - ecode = EAI_MAX; - return ai_errlist[ecode]; + if (ecode < 0 || ecode > EAI_MAX) + ecode = EAI_MAX; + return ai_errlist[ecode]; } void freeaddrinfo(struct addrinfo *ai) { - struct addrinfo *next; + struct addrinfo *next; - do { - next = ai->ai_next; - if (ai->ai_canonname) - free(ai->ai_canonname); - /* no need to free(ai->ai_addr) */ - free(ai); - } while ((ai = next) != NULL); + do { + next = ai->ai_next; + if (ai->ai_canonname) + free(ai->ai_canonname); + /* no need to free(ai->ai_addr) */ + free(ai); + } while ((ai = next) != NULL); } static int str_isnumber(const char *p) { - unsigned char *q = (unsigned char *)p; - while (*q) { - if (! isdigit(*q)) - return NO; - q++; - } - return YES; + unsigned char *q = (unsigned char *)p; + while (*q) { + if (! isdigit(*q)) + return NO; + q++; + } + return YES; } int getaddrinfo(const char*hostname, const char*servname, const struct addrinfo *hints, struct addrinfo **res) { - struct addrinfo sentinel; - struct addrinfo *top = NULL; - struct addrinfo *cur; - int i, error = 0; - char pton[PTON_MAX]; - struct addrinfo ai; - struct addrinfo *pai; - u_short port; + struct addrinfo sentinel; + struct addrinfo *top = NULL; + struct addrinfo *cur; + int i, error = 0; + char pton[PTON_MAX]; + struct addrinfo ai; + struct addrinfo *pai; + u_short port; #ifdef FAITH - static int firsttime = 1; + static int firsttime = 1; - if (firsttime) { - /* translator hack */ - { - char *q = getenv("GAI"); - if (q && inet_pton(AF_INET6, q, &faith_prefix) == 1) - translate = YES; - } - firsttime = 0; - } -#endif - - /* initialize file static vars */ - sentinel.ai_next = NULL; - cur = &sentinel; - pai = &ai; - pai->ai_flags = 0; - pai->ai_family = PF_UNSPEC; - pai->ai_socktype = GAI_ANY; - pai->ai_protocol = GAI_ANY; - pai->ai_addrlen = 0; - pai->ai_canonname = NULL; - pai->ai_addr = NULL; - pai->ai_next = NULL; - port = GAI_ANY; - - if (hostname == NULL && servname == NULL) - return EAI_NONAME; - if (hints) { - /* error check for hints */ - if (hints->ai_addrlen || hints->ai_canonname || - hints->ai_addr || hints->ai_next) - ERR(EAI_BADHINTS); /* xxx */ - if (hints->ai_flags & ~AI_MASK) - ERR(EAI_BADFLAGS); - switch (hints->ai_family) { - case PF_UNSPEC: - case PF_INET: -#ifdef ENABLE_IPV6 - case PF_INET6: -#endif - break; - default: - ERR(EAI_FAMILY); - } - memcpy(pai, hints, sizeof(*pai)); - switch (pai->ai_socktype) { - case GAI_ANY: - switch (pai->ai_protocol) { - case GAI_ANY: - break; - case IPPROTO_UDP: - pai->ai_socktype = SOCK_DGRAM; - break; - case IPPROTO_TCP: - pai->ai_socktype = SOCK_STREAM; - break; - default: - pai->ai_socktype = SOCK_RAW; - break; - } - break; - case SOCK_RAW: - break; - case SOCK_DGRAM: - if (pai->ai_protocol != IPPROTO_UDP && - pai->ai_protocol != GAI_ANY) - ERR(EAI_BADHINTS); /*xxx*/ - pai->ai_protocol = IPPROTO_UDP; - break; - case SOCK_STREAM: - if (pai->ai_protocol != IPPROTO_TCP && - pai->ai_protocol != GAI_ANY) - ERR(EAI_BADHINTS); /*xxx*/ - pai->ai_protocol = IPPROTO_TCP; - break; - default: - ERR(EAI_SOCKTYPE); - /* unreachable */ - } - } - - /* - * service port - */ - if (servname) { - if (str_isnumber(servname)) { - if (pai->ai_socktype == GAI_ANY) { - /* caller accept *GAI_ANY* socktype */ - pai->ai_socktype = SOCK_DGRAM; - pai->ai_protocol = IPPROTO_UDP; - } - port = htons((u_short)atoi(servname)); - } else { - struct servent *sp; - char *proto; - - proto = NULL; - switch (pai->ai_socktype) { - case GAI_ANY: - proto = NULL; - break; - case SOCK_DGRAM: - proto = "udp"; - break; - case SOCK_STREAM: - proto = "tcp"; - break; - default: - fprintf(stderr, "panic!\n"); - break; - } - if ((sp = getservbyname(servname, proto)) == NULL) - ERR(EAI_SERVICE); - port = sp->s_port; - if (pai->ai_socktype == GAI_ANY) { - if (strcmp(sp->s_proto, "udp") == 0) { - pai->ai_socktype = SOCK_DGRAM; - pai->ai_protocol = IPPROTO_UDP; - } else if (strcmp(sp->s_proto, "tcp") == 0) { - pai->ai_socktype = SOCK_STREAM; - pai->ai_protocol = IPPROTO_TCP; - } else - ERR(EAI_PROTOCOL); /*xxx*/ - } - } - } - - /* - * hostname == NULL. - * passive socket -> anyaddr (0.0.0.0 or ::) - * non-passive socket -> localhost (127.0.0.1 or ::1) - */ - if (hostname == NULL) { - struct gai_afd *gai_afd; - - for (gai_afd = &gai_afdl[0]; gai_afd->a_af; gai_afd++) { - if (!(pai->ai_family == PF_UNSPEC - || pai->ai_family == gai_afd->a_af)) { - continue; - } - - if (pai->ai_flags & AI_PASSIVE) { - GET_AI(cur->ai_next, gai_afd, gai_afd->a_addrany, port); - /* xxx meaningless? - * GET_CANONNAME(cur->ai_next, "anyaddr"); - */ - } else { - GET_AI(cur->ai_next, gai_afd, gai_afd->a_loopback, - port); - /* xxx meaningless? - * GET_CANONNAME(cur->ai_next, "localhost"); - */ - } - cur = cur->ai_next; - } - top = sentinel.ai_next; - if (top) - goto good; - else - ERR(EAI_FAMILY); - } - - /* hostname as numeric name */ - for (i = 0; gai_afdl[i].a_af; i++) { - if (inet_pton(gai_afdl[i].a_af, hostname, pton)) { - u_long v4a; -#ifdef ENABLE_IPV6 - u_char pfx; -#endif - - switch (gai_afdl[i].a_af) { - case AF_INET: - v4a = ((struct in_addr *)pton)->s_addr; - v4a = ntohl(v4a); - if (IN_MULTICAST(v4a) || IN_EXPERIMENTAL(v4a)) - pai->ai_flags &= ~AI_CANONNAME; - v4a >>= IN_CLASSA_NSHIFT; - if (v4a == 0 || v4a == IN_LOOPBACKNET) - pai->ai_flags &= ~AI_CANONNAME; - break; -#ifdef ENABLE_IPV6 - case AF_INET6: - pfx = ((struct in6_addr *)pton)->s6_addr8[0]; - if (pfx == 0 || pfx == 0xfe || pfx == 0xff) - pai->ai_flags &= ~AI_CANONNAME; - break; -#endif - } - - if (pai->ai_family == gai_afdl[i].a_af || - pai->ai_family == PF_UNSPEC) { - if (! (pai->ai_flags & AI_CANONNAME)) { - GET_AI(top, &gai_afdl[i], pton, port); - goto good; - } - /* - * if AI_CANONNAME and if reverse lookup - * fail, return ai anyway to pacify - * calling application. - * - * XXX getaddrinfo() is a name->address - * translation function, and it looks strange - * that we do addr->name translation here. - */ - get_name(pton, &gai_afdl[i], &top, pton, pai, port); - goto good; - } else - ERR(EAI_FAMILY); /*xxx*/ - } - } - - if (pai->ai_flags & AI_NUMERICHOST) - ERR(EAI_NONAME); - - /* hostname as alphabetical name */ - error = get_addr(hostname, pai->ai_family, &top, pai, port); - if (error == 0) { - if (top) { + if (firsttime) { + /* translator hack */ + { + char *q = getenv("GAI"); + if (q && inet_pton(AF_INET6, q, &faith_prefix) == 1) + translate = YES; + } + firsttime = 0; + } +#endif + + /* initialize file static vars */ + sentinel.ai_next = NULL; + cur = &sentinel; + pai = &ai; + pai->ai_flags = 0; + pai->ai_family = PF_UNSPEC; + pai->ai_socktype = GAI_ANY; + pai->ai_protocol = GAI_ANY; + pai->ai_addrlen = 0; + pai->ai_canonname = NULL; + pai->ai_addr = NULL; + pai->ai_next = NULL; + port = GAI_ANY; + + if (hostname == NULL && servname == NULL) + return EAI_NONAME; + if (hints) { + /* error check for hints */ + if (hints->ai_addrlen || hints->ai_canonname || + hints->ai_addr || hints->ai_next) + ERR(EAI_BADHINTS); /* xxx */ + if (hints->ai_flags & ~AI_MASK) + ERR(EAI_BADFLAGS); + switch (hints->ai_family) { + case PF_UNSPEC: + case PF_INET: +#ifdef ENABLE_IPV6 + case PF_INET6: +#endif + break; + default: + ERR(EAI_FAMILY); + } + memcpy(pai, hints, sizeof(*pai)); + switch (pai->ai_socktype) { + case GAI_ANY: + switch (pai->ai_protocol) { + case GAI_ANY: + break; + case IPPROTO_UDP: + pai->ai_socktype = SOCK_DGRAM; + break; + case IPPROTO_TCP: + pai->ai_socktype = SOCK_STREAM; + break; + default: + pai->ai_socktype = SOCK_RAW; + break; + } + break; + case SOCK_RAW: + break; + case SOCK_DGRAM: + if (pai->ai_protocol != IPPROTO_UDP && + pai->ai_protocol != GAI_ANY) + ERR(EAI_BADHINTS); /*xxx*/ + pai->ai_protocol = IPPROTO_UDP; + break; + case SOCK_STREAM: + if (pai->ai_protocol != IPPROTO_TCP && + pai->ai_protocol != GAI_ANY) + ERR(EAI_BADHINTS); /*xxx*/ + pai->ai_protocol = IPPROTO_TCP; + break; + default: + ERR(EAI_SOCKTYPE); + /* unreachable */ + } + } + + /* + * service port + */ + if (servname) { + if (str_isnumber(servname)) { + if (pai->ai_socktype == GAI_ANY) { + /* caller accept *GAI_ANY* socktype */ + pai->ai_socktype = SOCK_DGRAM; + pai->ai_protocol = IPPROTO_UDP; + } + port = htons((u_short)atoi(servname)); + } else { + struct servent *sp; + char *proto; + + proto = NULL; + switch (pai->ai_socktype) { + case GAI_ANY: + proto = NULL; + break; + case SOCK_DGRAM: + proto = "udp"; + break; + case SOCK_STREAM: + proto = "tcp"; + break; + default: + fprintf(stderr, "panic!\n"); + break; + } + if ((sp = getservbyname(servname, proto)) == NULL) + ERR(EAI_SERVICE); + port = sp->s_port; + if (pai->ai_socktype == GAI_ANY) { + if (strcmp(sp->s_proto, "udp") == 0) { + pai->ai_socktype = SOCK_DGRAM; + pai->ai_protocol = IPPROTO_UDP; + } else if (strcmp(sp->s_proto, "tcp") == 0) { + pai->ai_socktype = SOCK_STREAM; + pai->ai_protocol = IPPROTO_TCP; + } else + ERR(EAI_PROTOCOL); /*xxx*/ + } + } + } + + /* + * hostname == NULL. + * passive socket -> anyaddr (0.0.0.0 or ::) + * non-passive socket -> localhost (127.0.0.1 or ::1) + */ + if (hostname == NULL) { + struct gai_afd *gai_afd; + + for (gai_afd = &gai_afdl[0]; gai_afd->a_af; gai_afd++) { + if (!(pai->ai_family == PF_UNSPEC + || pai->ai_family == gai_afd->a_af)) { + continue; + } + + if (pai->ai_flags & AI_PASSIVE) { + GET_AI(cur->ai_next, gai_afd, gai_afd->a_addrany, port); + /* xxx meaningless? + * GET_CANONNAME(cur->ai_next, "anyaddr"); + */ + } else { + GET_AI(cur->ai_next, gai_afd, gai_afd->a_loopback, + port); + /* xxx meaningless? + * GET_CANONNAME(cur->ai_next, "localhost"); + */ + } + cur = cur->ai_next; + } + top = sentinel.ai_next; + if (top) + goto good; + else + ERR(EAI_FAMILY); + } + + /* hostname as numeric name */ + for (i = 0; gai_afdl[i].a_af; i++) { + if (inet_pton(gai_afdl[i].a_af, hostname, pton)) { + u_long v4a; +#ifdef ENABLE_IPV6 + u_char pfx; +#endif + + switch (gai_afdl[i].a_af) { + case AF_INET: + v4a = ((struct in_addr *)pton)->s_addr; + v4a = ntohl(v4a); + if (IN_MULTICAST(v4a) || IN_EXPERIMENTAL(v4a)) + pai->ai_flags &= ~AI_CANONNAME; + v4a >>= IN_CLASSA_NSHIFT; + if (v4a == 0 || v4a == IN_LOOPBACKNET) + pai->ai_flags &= ~AI_CANONNAME; + break; +#ifdef ENABLE_IPV6 + case AF_INET6: + pfx = ((struct in6_addr *)pton)->s6_addr8[0]; + if (pfx == 0 || pfx == 0xfe || pfx == 0xff) + pai->ai_flags &= ~AI_CANONNAME; + break; +#endif + } + + if (pai->ai_family == gai_afdl[i].a_af || + pai->ai_family == PF_UNSPEC) { + if (! (pai->ai_flags & AI_CANONNAME)) { + GET_AI(top, &gai_afdl[i], pton, port); + goto good; + } + /* + * if AI_CANONNAME and if reverse lookup + * fail, return ai anyway to pacify + * calling application. + * + * XXX getaddrinfo() is a name->address + * translation function, and it looks strange + * that we do addr->name translation here. + */ + get_name(pton, &gai_afdl[i], &top, pton, pai, port); + goto good; + } else + ERR(EAI_FAMILY); /*xxx*/ + } + } + + if (pai->ai_flags & AI_NUMERICHOST) + ERR(EAI_NONAME); + + /* hostname as alphabetical name */ + error = get_addr(hostname, pai->ai_family, &top, pai, port); + if (error == 0) { + if (top) { good: - *res = top; - return SUCCESS; - } else - error = EAI_FAIL; - } + *res = top; + return SUCCESS; + } else + error = EAI_FAIL; + } free: - if (top) - freeaddrinfo(top); + if (top) + freeaddrinfo(top); bad: - *res = NULL; - return error; + *res = NULL; + return error; } static int get_name(addr, gai_afd, res, numaddr, pai, port0) - const char *addr; - struct gai_afd *gai_afd; - struct addrinfo **res; - char *numaddr; - struct addrinfo *pai; - int port0; + const char *addr; + struct gai_afd *gai_afd; + struct addrinfo **res; + char *numaddr; + struct addrinfo *pai; + int port0; { - u_short port = port0 & 0xffff; - struct hostent *hp; - struct addrinfo *cur; - int error = 0; + u_short port = port0 & 0xffff; + struct hostent *hp; + struct addrinfo *cur; + int error = 0; #ifdef ENABLE_IPV6 - int h_error; + int h_error; #endif - + #ifdef ENABLE_IPV6 - hp = getipnodebyaddr(addr, gai_afd->a_addrlen, gai_afd->a_af, &h_error); + hp = getipnodebyaddr(addr, gai_afd->a_addrlen, gai_afd->a_af, &h_error); #else - hp = gethostbyaddr(addr, gai_afd->a_addrlen, AF_INET); + hp = gethostbyaddr(addr, gai_afd->a_addrlen, AF_INET); #endif - if (hp && hp->h_name && hp->h_name[0] && hp->h_addr_list[0]) { - GET_AI(cur, gai_afd, hp->h_addr_list[0], port); - GET_CANONNAME(cur, hp->h_name); - } else - GET_AI(cur, gai_afd, numaddr, port); - + if (hp && hp->h_name && hp->h_name[0] && hp->h_addr_list[0]) { + GET_AI(cur, gai_afd, hp->h_addr_list[0], port); + GET_CANONNAME(cur, hp->h_name); + } else + GET_AI(cur, gai_afd, numaddr, port); + #ifdef ENABLE_IPV6 - if (hp) - freehostent(hp); + if (hp) + freehostent(hp); #endif - *res = cur; - return SUCCESS; + *res = cur; + return SUCCESS; free: - if (cur) - freeaddrinfo(cur); + if (cur) + freeaddrinfo(cur); #ifdef ENABLE_IPV6 - if (hp) - freehostent(hp); + if (hp) + freehostent(hp); #endif /* bad: */ - *res = NULL; - return error; + *res = NULL; + return error; } static int get_addr(hostname, af, res, pai, port0) - const char *hostname; - int af; - struct addrinfo **res; - struct addrinfo *pai; - int port0; + const char *hostname; + int af; + struct addrinfo **res; + struct addrinfo *pai; + int port0; { - u_short port = port0 & 0xffff; - struct addrinfo sentinel; - struct hostent *hp; - struct addrinfo *top, *cur; - struct gai_afd *gai_afd; - int i, error = 0, h_error; - char *ap; - - top = NULL; - sentinel.ai_next = NULL; - cur = &sentinel; -#ifdef ENABLE_IPV6 - if (af == AF_UNSPEC) { - hp = getipnodebyname(hostname, AF_INET6, - AI_ADDRCONFIG|AI_ALL|AI_V4MAPPED, &h_error); - } else - hp = getipnodebyname(hostname, af, AI_ADDRCONFIG, &h_error); + u_short port = port0 & 0xffff; + struct addrinfo sentinel; + struct hostent *hp; + struct addrinfo *top, *cur; + struct gai_afd *gai_afd; + int i, error = 0, h_error; + char *ap; + + top = NULL; + sentinel.ai_next = NULL; + cur = &sentinel; +#ifdef ENABLE_IPV6 + if (af == AF_UNSPEC) { + hp = getipnodebyname(hostname, AF_INET6, + AI_ADDRCONFIG|AI_ALL|AI_V4MAPPED, &h_error); + } else + hp = getipnodebyname(hostname, af, AI_ADDRCONFIG, &h_error); #else - hp = gethostbyname(hostname); - h_error = h_errno; + hp = gethostbyname(hostname); + h_error = h_errno; #endif - if (hp == NULL) { - switch (h_error) { - case HOST_NOT_FOUND: - case NO_DATA: - error = EAI_NODATA; - break; - case TRY_AGAIN: - error = EAI_AGAIN; - break; - case NO_RECOVERY: - default: - error = EAI_FAIL; - break; - } - goto free; - } - - if ((hp->h_name == NULL) || (hp->h_name[0] == 0) || - (hp->h_addr_list[0] == NULL)) { - error = EAI_FAIL; - goto free; - } - - for (i = 0; (ap = hp->h_addr_list[i]) != NULL; i++) { - switch (af) { -#ifdef ENABLE_IPV6 - case AF_INET6: - gai_afd = &gai_afdl[N_INET6]; - break; + if (hp == NULL) { + switch (h_error) { + case HOST_NOT_FOUND: + case NO_DATA: + error = EAI_NODATA; + break; + case TRY_AGAIN: + error = EAI_AGAIN; + break; + case NO_RECOVERY: + default: + error = EAI_FAIL; + break; + } + goto free; + } + + if ((hp->h_name == NULL) || (hp->h_name[0] == 0) || + (hp->h_addr_list[0] == NULL)) { + error = EAI_FAIL; + goto free; + } + + for (i = 0; (ap = hp->h_addr_list[i]) != NULL; i++) { + switch (af) { +#ifdef ENABLE_IPV6 + case AF_INET6: + gai_afd = &gai_afdl[N_INET6]; + break; #endif #ifndef ENABLE_IPV6 - default: /* AF_UNSPEC */ + default: /* AF_UNSPEC */ #endif - case AF_INET: - gai_afd = &gai_afdl[N_INET]; - break; -#ifdef ENABLE_IPV6 - default: /* AF_UNSPEC */ - if (IN6_IS_ADDR_V4MAPPED((struct in6_addr *)ap)) { - ap += sizeof(struct in6_addr) - - sizeof(struct in_addr); - gai_afd = &gai_afdl[N_INET]; - } else - gai_afd = &gai_afdl[N_INET6]; - break; + case AF_INET: + gai_afd = &gai_afdl[N_INET]; + break; +#ifdef ENABLE_IPV6 + default: /* AF_UNSPEC */ + if (IN6_IS_ADDR_V4MAPPED((struct in6_addr *)ap)) { + ap += sizeof(struct in6_addr) - + sizeof(struct in_addr); + gai_afd = &gai_afdl[N_INET]; + } else + gai_afd = &gai_afdl[N_INET6]; + break; #endif - } + } #ifdef FAITH - if (translate && gai_afd->a_af == AF_INET) { - struct in6_addr *in6; + if (translate && gai_afd->a_af == AF_INET) { + struct in6_addr *in6; - GET_AI(cur->ai_next, &gai_afdl[N_INET6], ap, port); - in6 = &((struct sockaddr_in6 *)cur->ai_next->ai_addr)->sin6_addr; - memcpy(&in6->s6_addr32[0], &faith_prefix, - sizeof(struct in6_addr) - sizeof(struct in_addr)); - memcpy(&in6->s6_addr32[3], ap, sizeof(struct in_addr)); - } else + GET_AI(cur->ai_next, &gai_afdl[N_INET6], ap, port); + in6 = &((struct sockaddr_in6 *)cur->ai_next->ai_addr)->sin6_addr; + memcpy(&in6->s6_addr32[0], &faith_prefix, + sizeof(struct in6_addr) - sizeof(struct in_addr)); + memcpy(&in6->s6_addr32[3], ap, sizeof(struct in_addr)); + } else #endif /* FAITH */ - GET_AI(cur->ai_next, gai_afd, ap, port); - if (cur == &sentinel) { - top = cur->ai_next; - GET_CANONNAME(top, hp->h_name); - } - cur = cur->ai_next; - } + GET_AI(cur->ai_next, gai_afd, ap, port); + if (cur == &sentinel) { + top = cur->ai_next; + GET_CANONNAME(top, hp->h_name); + } + cur = cur->ai_next; + } #ifdef ENABLE_IPV6 - freehostent(hp); + freehostent(hp); #endif - *res = top; - return SUCCESS; + *res = top; + return SUCCESS; free: - if (top) - freeaddrinfo(top); + if (top) + freeaddrinfo(top); #ifdef ENABLE_IPV6 - if (hp) - freehostent(hp); + if (hp) + freehostent(hp); #endif /* bad: */ - *res = NULL; - return error; + *res = NULL; + return error; } Modified: python/branches/py3k-jit/Modules/getbuildinfo.c ============================================================================== --- python/branches/py3k-jit/Modules/getbuildinfo.c (original) +++ python/branches/py3k-jit/Modules/getbuildinfo.c Mon May 10 23:55:43 2010 @@ -31,22 +31,22 @@ const char * Py_GetBuildInfo(void) { - static char buildinfo[50]; - const char *revision = Py_SubversionRevision(); - const char *sep = *revision ? ":" : ""; - const char *branch = Py_SubversionShortBranch(); - PyOS_snprintf(buildinfo, sizeof(buildinfo), - "%s%s%s, %.20s, %.9s", branch, sep, revision, - DATE, TIME); - return buildinfo; + static char buildinfo[50]; + const char *revision = Py_SubversionRevision(); + const char *sep = *revision ? ":" : ""; + const char *branch = Py_SubversionShortBranch(); + PyOS_snprintf(buildinfo, sizeof(buildinfo), + "%s%s%s, %.20s, %.9s", branch, sep, revision, + DATE, TIME); + return buildinfo; } const char * _Py_svnversion(void) { - /* the following string can be modified by subwcrev.exe */ - static const char svnversion[] = SVNVERSION; - if (svnversion[0] != '$') - return svnversion; /* it was interpolated, or passed on command line */ - return "Unversioned directory"; + /* the following string can be modified by subwcrev.exe */ + static const char svnversion[] = SVNVERSION; + if (svnversion[0] != '$') + return svnversion; /* it was interpolated, or passed on command line */ + return "Unversioned directory"; } Modified: python/branches/py3k-jit/Modules/getnameinfo.c ============================================================================== --- python/branches/py3k-jit/Modules/getnameinfo.c (original) +++ python/branches/py3k-jit/Modules/getnameinfo.c Mon May 10 23:55:43 2010 @@ -1,7 +1,7 @@ /* * 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: @@ -13,7 +13,7 @@ * 3. Neither the name of the project nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. - * + * * THIS SOFTWARE IS PROVIDED BY THE PROJECT AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE @@ -53,162 +53,162 @@ #define NO 0 static struct gni_afd { - int a_af; - int a_addrlen; - int a_socklen; - int a_off; + int a_af; + int a_addrlen; + int a_socklen; + int a_off; } gni_afdl [] = { #ifdef ENABLE_IPV6 - {PF_INET6, sizeof(struct in6_addr), sizeof(struct sockaddr_in6), - offsetof(struct sockaddr_in6, sin6_addr)}, + {PF_INET6, sizeof(struct in6_addr), sizeof(struct sockaddr_in6), + offsetof(struct sockaddr_in6, sin6_addr)}, #endif - {PF_INET, sizeof(struct in_addr), sizeof(struct sockaddr_in), - offsetof(struct sockaddr_in, sin_addr)}, - {0, 0, 0}, + {PF_INET, sizeof(struct in_addr), sizeof(struct sockaddr_in), + offsetof(struct sockaddr_in, sin_addr)}, + {0, 0, 0}, }; struct gni_sockinet { - u_char si_len; - u_char si_family; - u_short si_port; + u_char si_len; + u_char si_family; + u_short si_port; }; -#define ENI_NOSOCKET 0 -#define ENI_NOSERVNAME 1 -#define ENI_NOHOSTNAME 2 -#define ENI_MEMORY 3 -#define ENI_SYSTEM 4 -#define ENI_FAMILY 5 -#define ENI_SALEN 6 +#define ENI_NOSOCKET 0 +#define ENI_NOSERVNAME 1 +#define ENI_NOHOSTNAME 2 +#define ENI_MEMORY 3 +#define ENI_SYSTEM 4 +#define ENI_FAMILY 5 +#define ENI_SALEN 6 /* forward declaration to make gcc happy */ int getnameinfo(const struct sockaddr *, size_t, char *, size_t, - char *, size_t, int); + char *, size_t, int); int getnameinfo(sa, salen, host, hostlen, serv, servlen, flags) - const struct sockaddr *sa; - size_t salen; - char *host; - size_t hostlen; - char *serv; - size_t servlen; - int flags; + const struct sockaddr *sa; + size_t salen; + char *host; + size_t hostlen; + char *serv; + size_t servlen; + int flags; { - struct gni_afd *gni_afd; - struct servent *sp; - struct hostent *hp; - u_short port; - int family, len, i; - char *addr, *p; - u_long v4a; -#ifdef ENABLE_IPV6 - u_char pfx; -#endif - int h_error; - char numserv[512]; - char numaddr[512]; + struct gni_afd *gni_afd; + struct servent *sp; + struct hostent *hp; + u_short port; + int family, len, i; + char *addr, *p; + u_long v4a; +#ifdef ENABLE_IPV6 + u_char pfx; +#endif + int h_error; + char numserv[512]; + char numaddr[512]; - if (sa == NULL) - return ENI_NOSOCKET; + if (sa == NULL) + return ENI_NOSOCKET; #ifdef HAVE_SOCKADDR_SA_LEN - len = sa->sa_len; - if (len != salen) return ENI_SALEN; + len = sa->sa_len; + if (len != salen) return ENI_SALEN; #else - len = salen; + len = salen; #endif - - family = sa->sa_family; - for (i = 0; gni_afdl[i].a_af; i++) - if (gni_afdl[i].a_af == family) { - gni_afd = &gni_afdl[i]; - goto found; - } - return ENI_FAMILY; - + + family = sa->sa_family; + for (i = 0; gni_afdl[i].a_af; i++) + if (gni_afdl[i].a_af == family) { + gni_afd = &gni_afdl[i]; + goto found; + } + return ENI_FAMILY; + found: - if (len != gni_afd->a_socklen) return ENI_SALEN; - - port = ((struct gni_sockinet *)sa)->si_port; /* network byte order */ - addr = (char *)sa + gni_afd->a_off; - - if (serv == NULL || servlen == 0) { - /* what we should do? */ - } else if (flags & NI_NUMERICSERV) { - sprintf(numserv, "%d", ntohs(port)); - if (strlen(numserv) > servlen) - return ENI_MEMORY; - strcpy(serv, numserv); - } else { - sp = getservbyport(port, (flags & NI_DGRAM) ? "udp" : "tcp"); - if (sp) { - if (strlen(sp->s_name) > servlen) - return ENI_MEMORY; - strcpy(serv, sp->s_name); - } else - return ENI_NOSERVNAME; - } - - switch (sa->sa_family) { - case AF_INET: - v4a = ((struct sockaddr_in *)sa)->sin_addr.s_addr; - if (IN_MULTICAST(v4a) || IN_EXPERIMENTAL(v4a)) - flags |= NI_NUMERICHOST; - v4a >>= IN_CLASSA_NSHIFT; - if (v4a == 0 || v4a == IN_LOOPBACKNET) - flags |= NI_NUMERICHOST; - break; -#ifdef ENABLE_IPV6 - case AF_INET6: - pfx = ((struct sockaddr_in6 *)sa)->sin6_addr.s6_addr8[0]; - if (pfx == 0 || pfx == 0xfe || pfx == 0xff) - flags |= NI_NUMERICHOST; - break; -#endif - } - if (host == NULL || hostlen == 0) { - /* what should we do? */ - } else if (flags & NI_NUMERICHOST) { - if (inet_ntop(gni_afd->a_af, addr, numaddr, sizeof(numaddr)) - == NULL) - return ENI_SYSTEM; - if (strlen(numaddr) > hostlen) - return ENI_MEMORY; - strcpy(host, numaddr); - } else { + if (len != gni_afd->a_socklen) return ENI_SALEN; + + port = ((struct gni_sockinet *)sa)->si_port; /* network byte order */ + addr = (char *)sa + gni_afd->a_off; + + if (serv == NULL || servlen == 0) { + /* what we should do? */ + } else if (flags & NI_NUMERICSERV) { + sprintf(numserv, "%d", ntohs(port)); + if (strlen(numserv) > servlen) + return ENI_MEMORY; + strcpy(serv, numserv); + } else { + sp = getservbyport(port, (flags & NI_DGRAM) ? "udp" : "tcp"); + if (sp) { + if (strlen(sp->s_name) > servlen) + return ENI_MEMORY; + strcpy(serv, sp->s_name); + } else + return ENI_NOSERVNAME; + } + + switch (sa->sa_family) { + case AF_INET: + v4a = ((struct sockaddr_in *)sa)->sin_addr.s_addr; + if (IN_MULTICAST(v4a) || IN_EXPERIMENTAL(v4a)) + flags |= NI_NUMERICHOST; + v4a >>= IN_CLASSA_NSHIFT; + if (v4a == 0 || v4a == IN_LOOPBACKNET) + flags |= NI_NUMERICHOST; + break; +#ifdef ENABLE_IPV6 + case AF_INET6: + pfx = ((struct sockaddr_in6 *)sa)->sin6_addr.s6_addr8[0]; + if (pfx == 0 || pfx == 0xfe || pfx == 0xff) + flags |= NI_NUMERICHOST; + break; +#endif + } + if (host == NULL || hostlen == 0) { + /* what should we do? */ + } else if (flags & NI_NUMERICHOST) { + if (inet_ntop(gni_afd->a_af, addr, numaddr, sizeof(numaddr)) + == NULL) + return ENI_SYSTEM; + if (strlen(numaddr) > hostlen) + return ENI_MEMORY; + strcpy(host, numaddr); + } else { #ifdef ENABLE_IPV6 - hp = getipnodebyaddr(addr, gni_afd->a_addrlen, gni_afd->a_af, &h_error); + hp = getipnodebyaddr(addr, gni_afd->a_addrlen, gni_afd->a_af, &h_error); #else - hp = gethostbyaddr(addr, gni_afd->a_addrlen, gni_afd->a_af); - h_error = h_errno; + hp = gethostbyaddr(addr, gni_afd->a_addrlen, gni_afd->a_af); + h_error = h_errno; #endif - if (hp) { - if (flags & NI_NOFQDN) { - p = strchr(hp->h_name, '.'); - if (p) *p = '\0'; - } - if (strlen(hp->h_name) > hostlen) { -#ifdef ENABLE_IPV6 - freehostent(hp); -#endif - return ENI_MEMORY; - } - strcpy(host, hp->h_name); -#ifdef ENABLE_IPV6 - freehostent(hp); -#endif - } else { - if (flags & NI_NAMEREQD) - return ENI_NOHOSTNAME; - if (inet_ntop(gni_afd->a_af, addr, numaddr, sizeof(numaddr)) - == NULL) - return ENI_NOHOSTNAME; - if (strlen(numaddr) > hostlen) - return ENI_MEMORY; - strcpy(host, numaddr); - } - } - return SUCCESS; + if (hp) { + if (flags & NI_NOFQDN) { + p = strchr(hp->h_name, '.'); + if (p) *p = '\0'; + } + if (strlen(hp->h_name) > hostlen) { +#ifdef ENABLE_IPV6 + freehostent(hp); +#endif + return ENI_MEMORY; + } + strcpy(host, hp->h_name); +#ifdef ENABLE_IPV6 + freehostent(hp); +#endif + } else { + if (flags & NI_NAMEREQD) + return ENI_NOHOSTNAME; + if (inet_ntop(gni_afd->a_af, addr, numaddr, sizeof(numaddr)) + == NULL) + return ENI_NOHOSTNAME; + if (strlen(numaddr) > hostlen) + return ENI_MEMORY; + strcpy(host, numaddr); + } + } + return SUCCESS; } Modified: python/branches/py3k-jit/Modules/getpath.c ============================================================================== --- python/branches/py3k-jit/Modules/getpath.c (original) +++ python/branches/py3k-jit/Modules/getpath.c Mon May 10 23:55:43 2010 @@ -142,8 +142,8 @@ char fname[PATH_MAX]; size_t res = wcstombs(fname, path, sizeof(fname)); if (res == (size_t)-1) { - errno = EINVAL; - return -1; + errno = EINVAL; + return -1; } return stat(fname, buf); } @@ -155,17 +155,17 @@ { char fname[PATH_MAX]; if (getcwd(fname, PATH_MAX) == NULL) - return NULL; + return NULL; if (mbstowcs(buf, fname, size) >= size) { - errno = ERANGE; - return NULL; + errno = ERANGE; + return NULL; } return buf; } #endif #ifdef HAVE_READLINK -int +int _Py_wreadlink(const wchar_t *path, wchar_t *buf, size_t bufsiz) { char cbuf[PATH_MAX]; @@ -173,24 +173,24 @@ int res; size_t r1 = wcstombs(cpath, path, PATH_MAX); if (r1 == (size_t)-1 || r1 >= PATH_MAX) { - errno = EINVAL; - return -1; + errno = EINVAL; + return -1; } res = (int)readlink(cpath, cbuf, PATH_MAX); if (res == -1) - return -1; + return -1; if (res == PATH_MAX) { - errno = EINVAL; - return -1; + errno = EINVAL; + return -1; } cbuf[res] = '\0'; /* buf will be null terminated */ r1 = mbstowcs(buf, cbuf, bufsiz); if (r1 == -1) { - errno = EINVAL; - return -1; + errno = EINVAL; + return -1; } return (int)r1; - + } #endif @@ -279,7 +279,7 @@ buffer[n++] = SEP; } if (n > MAXPATHLEN) - Py_FatalError("buffer overflow in getpath.c's joinpath()"); + Py_FatalError("buffer overflow in getpath.c's joinpath()"); k = wcslen(stuff); if (n + k > MAXPATHLEN) k = MAXPATHLEN - n; @@ -457,25 +457,25 @@ #else unsigned long nsexeclength = MAXPATHLEN; #endif - char execpath[MAXPATHLEN+1]; + char execpath[MAXPATHLEN+1]; #endif if (_path) { - size_t r = mbstowcs(wpath, _path, MAXPATHLEN+1); - path = wpath; - if (r == (size_t)-1 || r > MAXPATHLEN) { - /* Could not convert PATH, or it's too long. */ - path = NULL; - } + size_t r = mbstowcs(wpath, _path, MAXPATHLEN+1); + path = wpath; + if (r == (size_t)-1 || r > MAXPATHLEN) { + /* Could not convert PATH, or it's too long. */ + path = NULL; + } } - /* If there is no slash in the argv0 path, then we have to - * assume python is on the user's $PATH, since there's no - * other way to find a directory to start the search from. If - * $PATH isn't exported, you lose. - */ - if (wcschr(prog, SEP)) - wcsncpy(progpath, prog, MAXPATHLEN); + /* If there is no slash in the argv0 path, then we have to + * assume python is on the user's $PATH, since there's no + * other way to find a directory to start the search from. If + * $PATH isn't exported, you lose. + */ + if (wcschr(prog, SEP)) + wcsncpy(progpath, prog, MAXPATHLEN); #ifdef __APPLE__ /* On Mac OS X, if a script uses an interpreter of the form * "#!/opt/python2.3/bin/python", the kernel only passes "python" @@ -487,52 +487,52 @@ * will fail if a relative path was used. but in that case, * absolutize() should help us out below */ - else if(0 == _NSGetExecutablePath(execpath, &nsexeclength) && execpath[0] == SEP) { - size_t r = mbstowcs(progpath, execpath, MAXPATHLEN+1); - if (r == (size_t)-1 || r > MAXPATHLEN) { - /* Could not convert execpath, or it's too long. */ - progpath[0] = '\0'; - } - } + else if(0 == _NSGetExecutablePath(execpath, &nsexeclength) && execpath[0] == SEP) { + size_t r = mbstowcs(progpath, execpath, MAXPATHLEN+1); + if (r == (size_t)-1 || r > MAXPATHLEN) { + /* Could not convert execpath, or it's too long. */ + progpath[0] = '\0'; + } + } #endif /* __APPLE__ */ - else if (path) { - while (1) { - wchar_t *delim = wcschr(path, DELIM); - - if (delim) { - size_t len = delim - path; - if (len > MAXPATHLEN) - len = MAXPATHLEN; - wcsncpy(progpath, path, len); - *(progpath + len) = '\0'; - } - else - wcsncpy(progpath, path, MAXPATHLEN); - - joinpath(progpath, prog); - if (isxfile(progpath)) - break; - - if (!delim) { - progpath[0] = L'\0'; - break; - } - path = delim + 1; - } - } - else - progpath[0] = '\0'; - if (progpath[0] != SEP && progpath[0] != '\0') - absolutize(progpath); - wcsncpy(argv0_path, progpath, MAXPATHLEN); - argv0_path[MAXPATHLEN] = '\0'; + else if (path) { + while (1) { + wchar_t *delim = wcschr(path, DELIM); + + if (delim) { + size_t len = delim - path; + if (len > MAXPATHLEN) + len = MAXPATHLEN; + wcsncpy(progpath, path, len); + *(progpath + len) = '\0'; + } + else + wcsncpy(progpath, path, MAXPATHLEN); + + joinpath(progpath, prog); + if (isxfile(progpath)) + break; + + if (!delim) { + progpath[0] = L'\0'; + break; + } + path = delim + 1; + } + } + else + progpath[0] = '\0'; + if (progpath[0] != SEP && progpath[0] != '\0') + absolutize(progpath); + wcsncpy(argv0_path, progpath, MAXPATHLEN); + argv0_path[MAXPATHLEN] = '\0'; #ifdef WITH_NEXT_FRAMEWORK - /* On Mac OS X we have a special case if we're running from a framework. - ** This is because the python home should be set relative to the library, - ** which is in the framework, not relative to the executable, which may - ** be outside of the framework. Except when we're in the build directory... - */ + /* On Mac OS X we have a special case if we're running from a framework. + ** This is because the python home should be set relative to the library, + ** which is in the framework, not relative to the executable, which may + ** be outside of the framework. Except when we're in the build directory... + */ pythonModule = NSModuleForSymbol(NSLookupAndBindSymbol("_Py_Initialize")); /* Use dylib functions to find out where the framework was loaded from */ buf = (wchar_t *)NSLibraryNameForModule(pythonModule); @@ -604,7 +604,7 @@ else wcsncpy(zip_path, L"" PREFIX, MAXPATHLEN); joinpath(zip_path, L"lib/python00.zip"); - bufsz = wcslen(zip_path); /* Replace "00" with version */ + bufsz = wcslen(zip_path); /* Replace "00" with version */ zip_path[bufsz - 6] = VERSION[0]; zip_path[bufsz - 5] = VERSION[2]; @@ -626,12 +626,12 @@ bufsz = 0; if (_rtpypath) { - size_t s = mbstowcs(rtpypath, _rtpypath, sizeof(rtpypath)/sizeof(wchar_t)); - if (s == (size_t)-1 || s >=sizeof(rtpypath)) - /* XXX deal with errors more gracefully */ - _rtpypath = NULL; - if (_rtpypath) - bufsz += wcslen(rtpypath) + 1; + size_t s = mbstowcs(rtpypath, _rtpypath, sizeof(rtpypath)/sizeof(wchar_t)); + if (s == (size_t)-1 || s >=sizeof(rtpypath)) + /* XXX deal with errors more gracefully */ + _rtpypath = NULL; + if (_rtpypath) + bufsz += wcslen(rtpypath) + 1; } prefixsz = wcslen(prefix) + 1; @@ -718,10 +718,10 @@ if (pfound > 0) { reduce(prefix); reduce(prefix); - /* The prefix is the root directory, but reduce() chopped - * off the "/". */ - if (!prefix[0]) - wcscpy(prefix, separator); + /* The prefix is the root directory, but reduce() chopped + * off the "/". */ + if (!prefix[0]) + wcscpy(prefix, separator); } else wcsncpy(prefix, L"" PREFIX, MAXPATHLEN); @@ -730,8 +730,8 @@ reduce(exec_prefix); reduce(exec_prefix); reduce(exec_prefix); - if (!exec_prefix[0]) - wcscpy(exec_prefix, separator); + if (!exec_prefix[0]) + wcscpy(exec_prefix, separator); } else wcsncpy(exec_prefix, L"" EXEC_PREFIX, MAXPATHLEN); Modified: python/branches/py3k-jit/Modules/grpmodule.c ============================================================================== --- python/branches/py3k-jit/Modules/grpmodule.c (original) +++ python/branches/py3k-jit/Modules/grpmodule.c Mon May 10 23:55:43 2010 @@ -10,8 +10,8 @@ static PyStructSequence_Field struct_group_type_fields[] = { {"gr_name", "group name"}, {"gr_passwd", "password"}, - {"gr_gid", "group id"}, - {"gr_mem", "group memebers"}, + {"gr_gid", "group id"}, + {"gr_mem", "group memebers"}, {0} }; @@ -64,10 +64,10 @@ Py_INCREF(Py_None); #else if (p->gr_passwd) - SET(setIndex++, PyUnicode_DecodeFSDefault(p->gr_passwd)); + SET(setIndex++, PyUnicode_DecodeFSDefault(p->gr_passwd)); else { - SET(setIndex++, Py_None); - Py_INCREF(Py_None); + SET(setIndex++, Py_None); + Py_INCREF(Py_None); } #endif SET(setIndex++, PyLong_FromLong((long) p->gr_gid)); @@ -91,12 +91,12 @@ py_int_id = PyNumber_Long(pyo_id); if (!py_int_id) - return NULL; + return NULL; gid = PyLong_AS_LONG(py_int_id); Py_DECREF(py_int_id); if ((p = getgrgid(gid)) == NULL) { - PyErr_Format(PyExc_KeyError, "getgrgid(): gid not found: %d", gid); + PyErr_Format(PyExc_KeyError, "getgrgid(): gid not found: %d", gid); return NULL; } return mkgrent(p); @@ -116,9 +116,9 @@ return NULL; if (PyBytes_AsStringAndSize(bytes, &name, NULL) == -1) goto out; - + if ((p = getgrnam(name)) == NULL) { - PyErr_Format(PyExc_KeyError, "getgrnam(): name not found: %s", name); + PyErr_Format(PyExc_KeyError, "getgrnam(): name not found: %s", name); goto out; } retval = mkgrent(p); @@ -151,18 +151,18 @@ } static PyMethodDef grp_methods[] = { - {"getgrgid", grp_getgrgid, METH_O, + {"getgrgid", grp_getgrgid, METH_O, "getgrgid(id) -> tuple\n\ Return the group database entry for the given numeric group ID. If\n\ id is not valid, raise KeyError."}, - {"getgrnam", grp_getgrnam, METH_VARARGS, + {"getgrnam", grp_getgrnam, METH_VARARGS, "getgrnam(name) -> tuple\n\ Return the group database entry for the given group name. If\n\ name is not valid, raise KeyError."}, - {"getgrall", grp_getgrall, METH_NOARGS, + {"getgrall", grp_getgrall, METH_NOARGS, "getgrall() -> list of tuples\n\ Return a list of all available group entries, in arbitrary order."}, - {NULL, NULL} /* sentinel */ + {NULL, NULL} /* sentinel */ }; PyDoc_STRVAR(grp__doc__, @@ -184,15 +184,15 @@ static struct PyModuleDef grpmodule = { - PyModuleDef_HEAD_INIT, - "grp", - grp__doc__, - -1, - grp_methods, - NULL, - NULL, - NULL, - NULL + PyModuleDef_HEAD_INIT, + "grp", + grp__doc__, + -1, + grp_methods, + NULL, + NULL, + NULL, + NULL }; PyMODINIT_FUNC @@ -204,7 +204,7 @@ return NULL; d = PyModule_GetDict(m); if (!initialized) - PyStructSequence_InitType(&StructGrpType, &struct_group_type_desc); + PyStructSequence_InitType(&StructGrpType, &struct_group_type_desc); PyDict_SetItemString(d, "struct_group", (PyObject *) &StructGrpType); initialized = 1; return m; Modified: python/branches/py3k-jit/Modules/itertoolsmodule.c ============================================================================== --- python/branches/py3k-jit/Modules/itertoolsmodule.c (original) +++ python/branches/py3k-jit/Modules/itertoolsmodule.c Mon May 10 23:55:43 2010 @@ -2,7 +2,7 @@ #include "Python.h" #include "structmember.h" -/* Itertools module written and maintained +/* Itertools module written and maintained by Raymond D. Hettinger Copyright (c) 2003 Python Software Foundation. All rights reserved. @@ -12,12 +12,12 @@ /* groupby object ***********************************************************/ typedef struct { - PyObject_HEAD - PyObject *it; - PyObject *keyfunc; - PyObject *tgtkey; - PyObject *currkey; - PyObject *currvalue; + PyObject_HEAD + PyObject *it; + PyObject *keyfunc; + PyObject *tgtkey; + PyObject *currkey; + PyObject *currvalue; } groupbyobject; static PyTypeObject groupby_type; @@ -26,112 +26,112 @@ static PyObject * groupby_new(PyTypeObject *type, PyObject *args, PyObject *kwds) { - static char *kwargs[] = {"iterable", "key", NULL}; - groupbyobject *gbo; - PyObject *it, *keyfunc = Py_None; - - if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|O:groupby", kwargs, - &it, &keyfunc)) - return NULL; - - gbo = (groupbyobject *)type->tp_alloc(type, 0); - if (gbo == NULL) - return NULL; - gbo->tgtkey = NULL; - gbo->currkey = NULL; - gbo->currvalue = NULL; - gbo->keyfunc = keyfunc; - Py_INCREF(keyfunc); - gbo->it = PyObject_GetIter(it); - if (gbo->it == NULL) { - Py_DECREF(gbo); - return NULL; - } - return (PyObject *)gbo; + static char *kwargs[] = {"iterable", "key", NULL}; + groupbyobject *gbo; + PyObject *it, *keyfunc = Py_None; + + if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|O:groupby", kwargs, + &it, &keyfunc)) + return NULL; + + gbo = (groupbyobject *)type->tp_alloc(type, 0); + if (gbo == NULL) + return NULL; + gbo->tgtkey = NULL; + gbo->currkey = NULL; + gbo->currvalue = NULL; + gbo->keyfunc = keyfunc; + Py_INCREF(keyfunc); + gbo->it = PyObject_GetIter(it); + if (gbo->it == NULL) { + Py_DECREF(gbo); + return NULL; + } + return (PyObject *)gbo; } static void groupby_dealloc(groupbyobject *gbo) { - PyObject_GC_UnTrack(gbo); - Py_XDECREF(gbo->it); - Py_XDECREF(gbo->keyfunc); - Py_XDECREF(gbo->tgtkey); - Py_XDECREF(gbo->currkey); - Py_XDECREF(gbo->currvalue); - Py_TYPE(gbo)->tp_free(gbo); + PyObject_GC_UnTrack(gbo); + Py_XDECREF(gbo->it); + Py_XDECREF(gbo->keyfunc); + Py_XDECREF(gbo->tgtkey); + Py_XDECREF(gbo->currkey); + Py_XDECREF(gbo->currvalue); + Py_TYPE(gbo)->tp_free(gbo); } static int groupby_traverse(groupbyobject *gbo, visitproc visit, void *arg) { - Py_VISIT(gbo->it); - Py_VISIT(gbo->keyfunc); - Py_VISIT(gbo->tgtkey); - Py_VISIT(gbo->currkey); - Py_VISIT(gbo->currvalue); - return 0; + Py_VISIT(gbo->it); + Py_VISIT(gbo->keyfunc); + Py_VISIT(gbo->tgtkey); + Py_VISIT(gbo->currkey); + Py_VISIT(gbo->currvalue); + return 0; } static PyObject * groupby_next(groupbyobject *gbo) { - PyObject *newvalue, *newkey, *r, *grouper, *tmp; + PyObject *newvalue, *newkey, *r, *grouper, *tmp; - /* skip to next iteration group */ - for (;;) { - if (gbo->currkey == NULL) - /* pass */; - else if (gbo->tgtkey == NULL) - break; - else { - int rcmp; - - rcmp = PyObject_RichCompareBool(gbo->tgtkey, - gbo->currkey, Py_EQ); - if (rcmp == -1) - return NULL; - else if (rcmp == 0) - break; - } - - newvalue = PyIter_Next(gbo->it); - if (newvalue == NULL) - return NULL; - - if (gbo->keyfunc == Py_None) { - newkey = newvalue; - Py_INCREF(newvalue); - } else { - newkey = PyObject_CallFunctionObjArgs(gbo->keyfunc, - newvalue, NULL); - if (newkey == NULL) { - Py_DECREF(newvalue); - return NULL; - } - } - - tmp = gbo->currkey; - gbo->currkey = newkey; - Py_XDECREF(tmp); - - tmp = gbo->currvalue; - gbo->currvalue = newvalue; - Py_XDECREF(tmp); - } - - Py_INCREF(gbo->currkey); - tmp = gbo->tgtkey; - gbo->tgtkey = gbo->currkey; - Py_XDECREF(tmp); - - grouper = _grouper_create(gbo, gbo->tgtkey); - if (grouper == NULL) - return NULL; - - r = PyTuple_Pack(2, gbo->currkey, grouper); - Py_DECREF(grouper); - return r; + /* skip to next iteration group */ + for (;;) { + if (gbo->currkey == NULL) + /* pass */; + else if (gbo->tgtkey == NULL) + break; + else { + int rcmp; + + rcmp = PyObject_RichCompareBool(gbo->tgtkey, + gbo->currkey, Py_EQ); + if (rcmp == -1) + return NULL; + else if (rcmp == 0) + break; + } + + newvalue = PyIter_Next(gbo->it); + if (newvalue == NULL) + return NULL; + + if (gbo->keyfunc == Py_None) { + newkey = newvalue; + Py_INCREF(newvalue); + } else { + newkey = PyObject_CallFunctionObjArgs(gbo->keyfunc, + newvalue, NULL); + if (newkey == NULL) { + Py_DECREF(newvalue); + return NULL; + } + } + + tmp = gbo->currkey; + gbo->currkey = newkey; + Py_XDECREF(tmp); + + tmp = gbo->currvalue; + gbo->currvalue = newvalue; + Py_XDECREF(tmp); + } + + Py_INCREF(gbo->currkey); + tmp = gbo->tgtkey; + gbo->tgtkey = gbo->currkey; + Py_XDECREF(tmp); + + grouper = _grouper_create(gbo, gbo->tgtkey); + if (grouper == NULL) + return NULL; + + r = PyTuple_Pack(2, gbo->currkey, grouper); + Py_DECREF(grouper); + return r; } PyDoc_STRVAR(groupby_doc, @@ -139,56 +139,56 @@ (key, sub-iterator) grouped by each value of key(value).\n"); static PyTypeObject groupby_type = { - PyVarObject_HEAD_INIT(NULL, 0) - "itertools.groupby", /* tp_name */ - sizeof(groupbyobject), /* tp_basicsize */ - 0, /* tp_itemsize */ - /* methods */ - (destructor)groupby_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 | - Py_TPFLAGS_BASETYPE, /* tp_flags */ - groupby_doc, /* tp_doc */ - (traverseproc)groupby_traverse, /* tp_traverse */ - 0, /* tp_clear */ - 0, /* tp_richcompare */ - 0, /* tp_weaklistoffset */ - PyObject_SelfIter, /* tp_iter */ - (iternextfunc)groupby_next, /* tp_iternext */ - 0, /* tp_methods */ - 0, /* tp_members */ - 0, /* tp_getset */ - 0, /* tp_base */ - 0, /* tp_dict */ - 0, /* tp_descr_get */ - 0, /* tp_descr_set */ - 0, /* tp_dictoffset */ - 0, /* tp_init */ - 0, /* tp_alloc */ - groupby_new, /* tp_new */ - PyObject_GC_Del, /* tp_free */ + PyVarObject_HEAD_INIT(NULL, 0) + "itertools.groupby", /* tp_name */ + sizeof(groupbyobject), /* tp_basicsize */ + 0, /* tp_itemsize */ + /* methods */ + (destructor)groupby_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 | + Py_TPFLAGS_BASETYPE, /* tp_flags */ + groupby_doc, /* tp_doc */ + (traverseproc)groupby_traverse, /* tp_traverse */ + 0, /* tp_clear */ + 0, /* tp_richcompare */ + 0, /* tp_weaklistoffset */ + PyObject_SelfIter, /* tp_iter */ + (iternextfunc)groupby_next, /* tp_iternext */ + 0, /* tp_methods */ + 0, /* tp_members */ + 0, /* tp_getset */ + 0, /* tp_base */ + 0, /* tp_dict */ + 0, /* tp_descr_get */ + 0, /* tp_descr_set */ + 0, /* tp_dictoffset */ + 0, /* tp_init */ + 0, /* tp_alloc */ + groupby_new, /* tp_new */ + PyObject_GC_Del, /* tp_free */ }; /* _grouper object (internal) ************************************************/ typedef struct { - PyObject_HEAD - PyObject *parent; - PyObject *tgtkey; + PyObject_HEAD + PyObject *parent; + PyObject *tgtkey; } _grouperobject; static PyTypeObject _grouper_type; @@ -196,129 +196,129 @@ static PyObject * _grouper_create(groupbyobject *parent, PyObject *tgtkey) { - _grouperobject *igo; + _grouperobject *igo; - igo = PyObject_GC_New(_grouperobject, &_grouper_type); - if (igo == NULL) - return NULL; - igo->parent = (PyObject *)parent; - Py_INCREF(parent); - igo->tgtkey = tgtkey; - Py_INCREF(tgtkey); + igo = PyObject_GC_New(_grouperobject, &_grouper_type); + if (igo == NULL) + return NULL; + igo->parent = (PyObject *)parent; + Py_INCREF(parent); + igo->tgtkey = tgtkey; + Py_INCREF(tgtkey); - PyObject_GC_Track(igo); - return (PyObject *)igo; + PyObject_GC_Track(igo); + return (PyObject *)igo; } static void _grouper_dealloc(_grouperobject *igo) { - PyObject_GC_UnTrack(igo); - Py_DECREF(igo->parent); - Py_DECREF(igo->tgtkey); - PyObject_GC_Del(igo); + PyObject_GC_UnTrack(igo); + Py_DECREF(igo->parent); + Py_DECREF(igo->tgtkey); + PyObject_GC_Del(igo); } static int _grouper_traverse(_grouperobject *igo, visitproc visit, void *arg) { - Py_VISIT(igo->parent); - Py_VISIT(igo->tgtkey); - return 0; + Py_VISIT(igo->parent); + Py_VISIT(igo->tgtkey); + return 0; } static PyObject * _grouper_next(_grouperobject *igo) { - groupbyobject *gbo = (groupbyobject *)igo->parent; - PyObject *newvalue, *newkey, *r; - int rcmp; - - if (gbo->currvalue == NULL) { - newvalue = PyIter_Next(gbo->it); - if (newvalue == NULL) - return NULL; - - if (gbo->keyfunc == Py_None) { - newkey = newvalue; - Py_INCREF(newvalue); - } else { - newkey = PyObject_CallFunctionObjArgs(gbo->keyfunc, - newvalue, NULL); - if (newkey == NULL) { - Py_DECREF(newvalue); - return NULL; - } - } - - assert(gbo->currkey == NULL); - gbo->currkey = newkey; - gbo->currvalue = newvalue; - } - - assert(gbo->currkey != NULL); - rcmp = PyObject_RichCompareBool(igo->tgtkey, gbo->currkey, Py_EQ); - if (rcmp <= 0) - /* got any error or current group is end */ - return NULL; - - r = gbo->currvalue; - gbo->currvalue = NULL; - Py_CLEAR(gbo->currkey); + groupbyobject *gbo = (groupbyobject *)igo->parent; + PyObject *newvalue, *newkey, *r; + int rcmp; + + if (gbo->currvalue == NULL) { + newvalue = PyIter_Next(gbo->it); + if (newvalue == NULL) + return NULL; + + if (gbo->keyfunc == Py_None) { + newkey = newvalue; + Py_INCREF(newvalue); + } else { + newkey = PyObject_CallFunctionObjArgs(gbo->keyfunc, + newvalue, NULL); + if (newkey == NULL) { + Py_DECREF(newvalue); + return NULL; + } + } + + assert(gbo->currkey == NULL); + gbo->currkey = newkey; + gbo->currvalue = newvalue; + } + + assert(gbo->currkey != NULL); + rcmp = PyObject_RichCompareBool(igo->tgtkey, gbo->currkey, Py_EQ); + if (rcmp <= 0) + /* got any error or current group is end */ + return NULL; + + r = gbo->currvalue; + gbo->currvalue = NULL; + Py_CLEAR(gbo->currkey); - return r; + return r; } static PyTypeObject _grouper_type = { - PyVarObject_HEAD_INIT(NULL, 0) - "itertools._grouper", /* tp_name */ - sizeof(_grouperobject), /* tp_basicsize */ - 0, /* tp_itemsize */ - /* methods */ - (destructor)_grouper_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)_grouper_traverse,/* tp_traverse */ - 0, /* tp_clear */ - 0, /* tp_richcompare */ - 0, /* tp_weaklistoffset */ - PyObject_SelfIter, /* tp_iter */ - (iternextfunc)_grouper_next, /* tp_iternext */ - 0, /* tp_methods */ - 0, /* tp_members */ - 0, /* tp_getset */ - 0, /* tp_base */ - 0, /* tp_dict */ - 0, /* tp_descr_get */ - 0, /* tp_descr_set */ - 0, /* tp_dictoffset */ - 0, /* tp_init */ - 0, /* tp_alloc */ - 0, /* tp_new */ - PyObject_GC_Del, /* tp_free */ + PyVarObject_HEAD_INIT(NULL, 0) + "itertools._grouper", /* tp_name */ + sizeof(_grouperobject), /* tp_basicsize */ + 0, /* tp_itemsize */ + /* methods */ + (destructor)_grouper_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)_grouper_traverse,/* tp_traverse */ + 0, /* tp_clear */ + 0, /* tp_richcompare */ + 0, /* tp_weaklistoffset */ + PyObject_SelfIter, /* tp_iter */ + (iternextfunc)_grouper_next, /* tp_iternext */ + 0, /* tp_methods */ + 0, /* tp_members */ + 0, /* tp_getset */ + 0, /* tp_base */ + 0, /* tp_dict */ + 0, /* tp_descr_get */ + 0, /* tp_descr_set */ + 0, /* tp_dictoffset */ + 0, /* tp_init */ + 0, /* tp_alloc */ + 0, /* tp_new */ + PyObject_GC_Del, /* tp_free */ }; - + /* tee object and with supporting function and objects ***************/ /* The teedataobject pre-allocates space for LINKCELLS number of objects. To help the object fit neatly inside cache lines (space for 16 to 32 - pointers), the value should be a multiple of 16 minus space for + pointers), the value should be a multiple of 16 minus space for the other structure members including PyHEAD overhead. The larger the value, the less memory overhead per object and the less time spent allocating/deallocating new links. The smaller the number, the less @@ -327,18 +327,18 @@ #define LINKCELLS 57 typedef struct { - PyObject_HEAD - PyObject *it; - int numread; - PyObject *nextlink; - PyObject *(values[LINKCELLS]); + PyObject_HEAD + PyObject *it; + int numread; + PyObject *nextlink; + PyObject *(values[LINKCELLS]); } teedataobject; typedef struct { - PyObject_HEAD - teedataobject *dataobj; - int index; - PyObject *weakreflist; + PyObject_HEAD + teedataobject *dataobj; + int index; + PyObject *weakreflist; } teeobject; static PyTypeObject teedataobject_type; @@ -346,123 +346,123 @@ static PyObject * teedataobject_new(PyObject *it) { - teedataobject *tdo; + teedataobject *tdo; - tdo = PyObject_GC_New(teedataobject, &teedataobject_type); - if (tdo == NULL) - return NULL; - - tdo->numread = 0; - tdo->nextlink = NULL; - Py_INCREF(it); - tdo->it = it; - PyObject_GC_Track(tdo); - return (PyObject *)tdo; + tdo = PyObject_GC_New(teedataobject, &teedataobject_type); + if (tdo == NULL) + return NULL; + + tdo->numread = 0; + tdo->nextlink = NULL; + Py_INCREF(it); + tdo->it = it; + PyObject_GC_Track(tdo); + return (PyObject *)tdo; } static PyObject * teedataobject_jumplink(teedataobject *tdo) { - if (tdo->nextlink == NULL) - tdo->nextlink = teedataobject_new(tdo->it); - Py_XINCREF(tdo->nextlink); - return tdo->nextlink; + if (tdo->nextlink == NULL) + tdo->nextlink = teedataobject_new(tdo->it); + Py_XINCREF(tdo->nextlink); + return tdo->nextlink; } static PyObject * teedataobject_getitem(teedataobject *tdo, int i) { - PyObject *value; + PyObject *value; - assert(i < LINKCELLS); - if (i < tdo->numread) - value = tdo->values[i]; - else { - /* this is the lead iterator, so fetch more data */ - assert(i == tdo->numread); - value = PyIter_Next(tdo->it); - if (value == NULL) - return NULL; - tdo->numread++; - tdo->values[i] = value; - } - Py_INCREF(value); - return value; + assert(i < LINKCELLS); + if (i < tdo->numread) + value = tdo->values[i]; + else { + /* this is the lead iterator, so fetch more data */ + assert(i == tdo->numread); + value = PyIter_Next(tdo->it); + if (value == NULL) + return NULL; + tdo->numread++; + tdo->values[i] = value; + } + Py_INCREF(value); + return value; } static int teedataobject_traverse(teedataobject *tdo, visitproc visit, void * arg) { - int i; - Py_VISIT(tdo->it); - for (i = 0; i < tdo->numread; i++) - Py_VISIT(tdo->values[i]); - Py_VISIT(tdo->nextlink); - return 0; + int i; + Py_VISIT(tdo->it); + for (i = 0; i < tdo->numread; i++) + Py_VISIT(tdo->values[i]); + Py_VISIT(tdo->nextlink); + return 0; } static int teedataobject_clear(teedataobject *tdo) { - int i; - Py_CLEAR(tdo->it); - for (i=0 ; inumread ; i++) - Py_CLEAR(tdo->values[i]); - Py_CLEAR(tdo->nextlink); - return 0; + int i; + Py_CLEAR(tdo->it); + for (i=0 ; inumread ; i++) + Py_CLEAR(tdo->values[i]); + Py_CLEAR(tdo->nextlink); + return 0; } static void teedataobject_dealloc(teedataobject *tdo) { - PyObject_GC_UnTrack(tdo); - teedataobject_clear(tdo); - PyObject_GC_Del(tdo); + PyObject_GC_UnTrack(tdo); + teedataobject_clear(tdo); + PyObject_GC_Del(tdo); } PyDoc_STRVAR(teedataobject_doc, "Data container common to multiple tee objects."); static PyTypeObject teedataobject_type = { - PyVarObject_HEAD_INIT(0, 0) /* Must fill in type value later */ - "itertools.tee_dataobject", /* tp_name */ - sizeof(teedataobject), /* tp_basicsize */ - 0, /* tp_itemsize */ - /* methods */ - (destructor)teedataobject_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 */ - teedataobject_doc, /* tp_doc */ - (traverseproc)teedataobject_traverse, /* tp_traverse */ - (inquiry)teedataobject_clear, /* tp_clear */ - 0, /* tp_richcompare */ - 0, /* tp_weaklistoffset */ - 0, /* tp_iter */ - 0, /* tp_iternext */ - 0, /* tp_methods */ - 0, /* tp_members */ - 0, /* tp_getset */ - 0, /* tp_base */ - 0, /* tp_dict */ - 0, /* tp_descr_get */ - 0, /* tp_descr_set */ - 0, /* tp_dictoffset */ - 0, /* tp_init */ - 0, /* tp_alloc */ - 0, /* tp_new */ - PyObject_GC_Del, /* tp_free */ + PyVarObject_HEAD_INIT(0, 0) /* Must fill in type value later */ + "itertools.tee_dataobject", /* tp_name */ + sizeof(teedataobject), /* tp_basicsize */ + 0, /* tp_itemsize */ + /* methods */ + (destructor)teedataobject_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 */ + teedataobject_doc, /* tp_doc */ + (traverseproc)teedataobject_traverse, /* tp_traverse */ + (inquiry)teedataobject_clear, /* tp_clear */ + 0, /* tp_richcompare */ + 0, /* tp_weaklistoffset */ + 0, /* tp_iter */ + 0, /* tp_iternext */ + 0, /* tp_methods */ + 0, /* tp_members */ + 0, /* tp_getset */ + 0, /* tp_base */ + 0, /* tp_dict */ + 0, /* tp_descr_get */ + 0, /* tp_descr_set */ + 0, /* tp_dictoffset */ + 0, /* tp_init */ + 0, /* tp_alloc */ + 0, /* tp_new */ + PyObject_GC_Del, /* tp_free */ }; @@ -471,42 +471,42 @@ static PyObject * tee_next(teeobject *to) { - PyObject *value, *link; + PyObject *value, *link; - if (to->index >= LINKCELLS) { - link = teedataobject_jumplink(to->dataobj); - Py_DECREF(to->dataobj); - to->dataobj = (teedataobject *)link; - to->index = 0; - } - value = teedataobject_getitem(to->dataobj, to->index); - if (value == NULL) - return NULL; - to->index++; - return value; + if (to->index >= LINKCELLS) { + link = teedataobject_jumplink(to->dataobj); + Py_DECREF(to->dataobj); + to->dataobj = (teedataobject *)link; + to->index = 0; + } + value = teedataobject_getitem(to->dataobj, to->index); + if (value == NULL) + return NULL; + to->index++; + return value; } static int tee_traverse(teeobject *to, visitproc visit, void *arg) { - Py_VISIT((PyObject *)to->dataobj); - return 0; + Py_VISIT((PyObject *)to->dataobj); + return 0; } static PyObject * tee_copy(teeobject *to) { - teeobject *newto; + teeobject *newto; - newto = PyObject_GC_New(teeobject, &tee_type); - if (newto == NULL) - return NULL; - Py_INCREF(to->dataobj); - newto->dataobj = to->dataobj; - newto->index = to->index; - newto->weakreflist = NULL; - PyObject_GC_Track(newto); - return (PyObject *)newto; + newto = PyObject_GC_New(teeobject, &tee_type); + if (newto == NULL) + return NULL; + Py_INCREF(to->dataobj); + newto->dataobj = to->dataobj; + newto->index = to->index; + newto->weakreflist = NULL; + PyObject_GC_Track(newto); + return (PyObject *)newto; } PyDoc_STRVAR(teecopy_doc, "Returns an independent iterator."); @@ -514,154 +514,154 @@ static PyObject * tee_fromiterable(PyObject *iterable) { - teeobject *to; - PyObject *it = NULL; + teeobject *to; + PyObject *it = NULL; - it = PyObject_GetIter(iterable); - if (it == NULL) - return NULL; - if (PyObject_TypeCheck(it, &tee_type)) { - to = (teeobject *)tee_copy((teeobject *)it); - goto done; - } - - to = PyObject_GC_New(teeobject, &tee_type); - if (to == NULL) - goto done; - to->dataobj = (teedataobject *)teedataobject_new(it); - if (!to->dataobj) { - PyObject_GC_Del(to); - to = NULL; - goto done; - } - - to->index = 0; - to->weakreflist = NULL; - PyObject_GC_Track(to); + it = PyObject_GetIter(iterable); + if (it == NULL) + return NULL; + if (PyObject_TypeCheck(it, &tee_type)) { + to = (teeobject *)tee_copy((teeobject *)it); + goto done; + } + + to = PyObject_GC_New(teeobject, &tee_type); + if (to == NULL) + goto done; + to->dataobj = (teedataobject *)teedataobject_new(it); + if (!to->dataobj) { + PyObject_GC_Del(to); + to = NULL; + goto done; + } + + to->index = 0; + to->weakreflist = NULL; + PyObject_GC_Track(to); done: - Py_XDECREF(it); - return (PyObject *)to; + Py_XDECREF(it); + return (PyObject *)to; } static PyObject * tee_new(PyTypeObject *type, PyObject *args, PyObject *kw) { - PyObject *iterable; + PyObject *iterable; - if (!PyArg_UnpackTuple(args, "tee", 1, 1, &iterable)) - return NULL; - return tee_fromiterable(iterable); + if (!PyArg_UnpackTuple(args, "tee", 1, 1, &iterable)) + return NULL; + return tee_fromiterable(iterable); } static int tee_clear(teeobject *to) { - if (to->weakreflist != NULL) - PyObject_ClearWeakRefs((PyObject *) to); - Py_CLEAR(to->dataobj); - return 0; + if (to->weakreflist != NULL) + PyObject_ClearWeakRefs((PyObject *) to); + Py_CLEAR(to->dataobj); + return 0; } static void tee_dealloc(teeobject *to) { - PyObject_GC_UnTrack(to); - tee_clear(to); - PyObject_GC_Del(to); + PyObject_GC_UnTrack(to); + tee_clear(to); + PyObject_GC_Del(to); } PyDoc_STRVAR(teeobject_doc, "Iterator wrapped to make it copyable"); static PyMethodDef tee_methods[] = { - {"__copy__", (PyCFunction)tee_copy, METH_NOARGS, teecopy_doc}, - {NULL, NULL} /* sentinel */ + {"__copy__", (PyCFunction)tee_copy, METH_NOARGS, teecopy_doc}, + {NULL, NULL} /* sentinel */ }; static PyTypeObject tee_type = { - PyVarObject_HEAD_INIT(NULL, 0) - "itertools.tee", /* tp_name */ - sizeof(teeobject), /* tp_basicsize */ - 0, /* tp_itemsize */ - /* methods */ - (destructor)tee_dealloc, /* tp_dealloc */ - 0, /* tp_print */ - 0, /* tp_getattr */ - 0, /* tp_setattr */ - 0, /* tp_reserved */ - 0, /* tp_repr */ - 0, /* tp_as_number */ - 0, /* tp_as_sequence */ - 0, /* tp_as_mapping */ - 0, /* tp_hash */ - 0, /* tp_call */ - 0, /* tp_str */ - 0, /* tp_getattro */ - 0, /* tp_setattro */ - 0, /* tp_as_buffer */ - Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC, /* tp_flags */ - teeobject_doc, /* tp_doc */ - (traverseproc)tee_traverse, /* tp_traverse */ - (inquiry)tee_clear, /* tp_clear */ - 0, /* tp_richcompare */ - offsetof(teeobject, weakreflist), /* tp_weaklistoffset */ - PyObject_SelfIter, /* tp_iter */ - (iternextfunc)tee_next, /* tp_iternext */ - tee_methods, /* tp_methods */ - 0, /* tp_members */ - 0, /* tp_getset */ - 0, /* tp_base */ - 0, /* tp_dict */ - 0, /* tp_descr_get */ - 0, /* tp_descr_set */ - 0, /* tp_dictoffset */ - 0, /* tp_init */ - 0, /* tp_alloc */ - tee_new, /* tp_new */ - PyObject_GC_Del, /* tp_free */ + PyVarObject_HEAD_INIT(NULL, 0) + "itertools.tee", /* tp_name */ + sizeof(teeobject), /* tp_basicsize */ + 0, /* tp_itemsize */ + /* methods */ + (destructor)tee_dealloc, /* tp_dealloc */ + 0, /* tp_print */ + 0, /* tp_getattr */ + 0, /* tp_setattr */ + 0, /* tp_reserved */ + 0, /* tp_repr */ + 0, /* tp_as_number */ + 0, /* tp_as_sequence */ + 0, /* tp_as_mapping */ + 0, /* tp_hash */ + 0, /* tp_call */ + 0, /* tp_str */ + 0, /* tp_getattro */ + 0, /* tp_setattro */ + 0, /* tp_as_buffer */ + Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC, /* tp_flags */ + teeobject_doc, /* tp_doc */ + (traverseproc)tee_traverse, /* tp_traverse */ + (inquiry)tee_clear, /* tp_clear */ + 0, /* tp_richcompare */ + offsetof(teeobject, weakreflist), /* tp_weaklistoffset */ + PyObject_SelfIter, /* tp_iter */ + (iternextfunc)tee_next, /* tp_iternext */ + tee_methods, /* tp_methods */ + 0, /* tp_members */ + 0, /* tp_getset */ + 0, /* tp_base */ + 0, /* tp_dict */ + 0, /* tp_descr_get */ + 0, /* tp_descr_set */ + 0, /* tp_dictoffset */ + 0, /* tp_init */ + 0, /* tp_alloc */ + tee_new, /* tp_new */ + PyObject_GC_Del, /* tp_free */ }; static PyObject * tee(PyObject *self, PyObject *args) { - Py_ssize_t i, n=2; - PyObject *it, *iterable, *copyable, *result; + Py_ssize_t i, n=2; + PyObject *it, *iterable, *copyable, *result; - if (!PyArg_ParseTuple(args, "O|n", &iterable, &n)) - return NULL; - if (n < 0) { - PyErr_SetString(PyExc_ValueError, "n must be >= 0"); - return NULL; - } - result = PyTuple_New(n); - if (result == NULL) - return NULL; - if (n == 0) - return result; - it = PyObject_GetIter(iterable); - if (it == NULL) { - Py_DECREF(result); - return NULL; - } - if (!PyObject_HasAttrString(it, "__copy__")) { - copyable = tee_fromiterable(it); - Py_DECREF(it); - if (copyable == NULL) { - Py_DECREF(result); - return NULL; - } - } else - copyable = it; - PyTuple_SET_ITEM(result, 0, copyable); - for (i=1 ; i= 0"); + return NULL; + } + result = PyTuple_New(n); + if (result == NULL) + return NULL; + if (n == 0) + return result; + it = PyObject_GetIter(iterable); + if (it == NULL) { + Py_DECREF(result); + return NULL; + } + if (!PyObject_HasAttrString(it, "__copy__")) { + copyable = tee_fromiterable(it); + Py_DECREF(it); + if (copyable == NULL) { + Py_DECREF(result); + return NULL; + } + } else + copyable = it; + PyTuple_SET_ITEM(result, 0, copyable); + for (i=1 ; itp_alloc(type, 0); - if (lz == NULL) { - Py_DECREF(it); - Py_DECREF(saved); - return NULL; - } - lz->it = it; - lz->saved = saved; - lz->firstpass = 0; + PyObject *it; + PyObject *iterable; + PyObject *saved; + cycleobject *lz; + + if (type == &cycle_type && !_PyArg_NoKeywords("cycle()", kwds)) + return NULL; + + if (!PyArg_UnpackTuple(args, "cycle", 1, 1, &iterable)) + return NULL; + + /* Get iterator. */ + it = PyObject_GetIter(iterable); + if (it == NULL) + return NULL; + + saved = PyList_New(0); + if (saved == NULL) { + Py_DECREF(it); + return NULL; + } + + /* create cycleobject structure */ + lz = (cycleobject *)type->tp_alloc(type, 0); + if (lz == NULL) { + Py_DECREF(it); + Py_DECREF(saved); + return NULL; + } + lz->it = it; + lz->saved = saved; + lz->firstpass = 0; - return (PyObject *)lz; + return (PyObject *)lz; } static void cycle_dealloc(cycleobject *lz) { - PyObject_GC_UnTrack(lz); - Py_XDECREF(lz->saved); - Py_XDECREF(lz->it); - Py_TYPE(lz)->tp_free(lz); + PyObject_GC_UnTrack(lz); + Py_XDECREF(lz->saved); + Py_XDECREF(lz->it); + Py_TYPE(lz)->tp_free(lz); } static int cycle_traverse(cycleobject *lz, visitproc visit, void *arg) { - Py_VISIT(lz->it); - Py_VISIT(lz->saved); - return 0; + Py_VISIT(lz->it); + Py_VISIT(lz->saved); + return 0; } static PyObject * cycle_next(cycleobject *lz) { - PyObject *item; - PyObject *it; - PyObject *tmp; - - while (1) { - item = PyIter_Next(lz->it); - if (item != NULL) { - if (!lz->firstpass && PyList_Append(lz->saved, item)) { - Py_DECREF(item); - return NULL; - } - return item; - } - if (PyErr_Occurred()) { - if (PyErr_ExceptionMatches(PyExc_StopIteration)) - PyErr_Clear(); - else - return NULL; - } - if (PyList_Size(lz->saved) == 0) - return NULL; - it = PyObject_GetIter(lz->saved); - if (it == NULL) - return NULL; - tmp = lz->it; - lz->it = it; - lz->firstpass = 1; - Py_DECREF(tmp); - } + PyObject *item; + PyObject *it; + PyObject *tmp; + + while (1) { + item = PyIter_Next(lz->it); + if (item != NULL) { + if (!lz->firstpass && PyList_Append(lz->saved, item)) { + Py_DECREF(item); + return NULL; + } + return item; + } + if (PyErr_Occurred()) { + if (PyErr_ExceptionMatches(PyExc_StopIteration)) + PyErr_Clear(); + else + return NULL; + } + if (PyList_Size(lz->saved) == 0) + return NULL; + it = PyObject_GetIter(lz->saved); + if (it == NULL) + return NULL; + tmp = lz->it; + lz->it = it; + lz->firstpass = 1; + Py_DECREF(tmp); + } } PyDoc_STRVAR(cycle_doc, @@ -776,57 +776,57 @@ Then repeat the sequence indefinitely."); static PyTypeObject cycle_type = { - PyVarObject_HEAD_INIT(NULL, 0) - "itertools.cycle", /* tp_name */ - sizeof(cycleobject), /* tp_basicsize */ - 0, /* tp_itemsize */ - /* methods */ - (destructor)cycle_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 | - Py_TPFLAGS_BASETYPE, /* tp_flags */ - cycle_doc, /* tp_doc */ - (traverseproc)cycle_traverse, /* tp_traverse */ - 0, /* tp_clear */ - 0, /* tp_richcompare */ - 0, /* tp_weaklistoffset */ - PyObject_SelfIter, /* tp_iter */ - (iternextfunc)cycle_next, /* tp_iternext */ - 0, /* tp_methods */ - 0, /* tp_members */ - 0, /* tp_getset */ - 0, /* tp_base */ - 0, /* tp_dict */ - 0, /* tp_descr_get */ - 0, /* tp_descr_set */ - 0, /* tp_dictoffset */ - 0, /* tp_init */ - 0, /* tp_alloc */ - cycle_new, /* tp_new */ - PyObject_GC_Del, /* tp_free */ + PyVarObject_HEAD_INIT(NULL, 0) + "itertools.cycle", /* tp_name */ + sizeof(cycleobject), /* tp_basicsize */ + 0, /* tp_itemsize */ + /* methods */ + (destructor)cycle_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 | + Py_TPFLAGS_BASETYPE, /* tp_flags */ + cycle_doc, /* tp_doc */ + (traverseproc)cycle_traverse, /* tp_traverse */ + 0, /* tp_clear */ + 0, /* tp_richcompare */ + 0, /* tp_weaklistoffset */ + PyObject_SelfIter, /* tp_iter */ + (iternextfunc)cycle_next, /* tp_iternext */ + 0, /* tp_methods */ + 0, /* tp_members */ + 0, /* tp_getset */ + 0, /* tp_base */ + 0, /* tp_dict */ + 0, /* tp_descr_get */ + 0, /* tp_descr_set */ + 0, /* tp_dictoffset */ + 0, /* tp_init */ + 0, /* tp_alloc */ + cycle_new, /* tp_new */ + PyObject_GC_Del, /* tp_free */ }; /* dropwhile object **********************************************************/ typedef struct { - PyObject_HEAD - PyObject *func; - PyObject *it; - long start; + PyObject_HEAD + PyObject *func; + PyObject *it; + long start; } dropwhileobject; static PyTypeObject dropwhile_type; @@ -834,81 +834,81 @@ static PyObject * dropwhile_new(PyTypeObject *type, PyObject *args, PyObject *kwds) { - PyObject *func, *seq; - PyObject *it; - dropwhileobject *lz; - - if (type == &dropwhile_type && !_PyArg_NoKeywords("dropwhile()", kwds)) - return NULL; - - if (!PyArg_UnpackTuple(args, "dropwhile", 2, 2, &func, &seq)) - return NULL; - - /* Get iterator. */ - it = PyObject_GetIter(seq); - if (it == NULL) - return NULL; - - /* create dropwhileobject structure */ - lz = (dropwhileobject *)type->tp_alloc(type, 0); - if (lz == NULL) { - Py_DECREF(it); - return NULL; - } - Py_INCREF(func); - lz->func = func; - lz->it = it; - lz->start = 0; + PyObject *func, *seq; + PyObject *it; + dropwhileobject *lz; + + if (type == &dropwhile_type && !_PyArg_NoKeywords("dropwhile()", kwds)) + return NULL; + + if (!PyArg_UnpackTuple(args, "dropwhile", 2, 2, &func, &seq)) + return NULL; + + /* Get iterator. */ + it = PyObject_GetIter(seq); + if (it == NULL) + return NULL; + + /* create dropwhileobject structure */ + lz = (dropwhileobject *)type->tp_alloc(type, 0); + if (lz == NULL) { + Py_DECREF(it); + return NULL; + } + Py_INCREF(func); + lz->func = func; + lz->it = it; + lz->start = 0; - return (PyObject *)lz; + return (PyObject *)lz; } static void dropwhile_dealloc(dropwhileobject *lz) { - PyObject_GC_UnTrack(lz); - Py_XDECREF(lz->func); - Py_XDECREF(lz->it); - Py_TYPE(lz)->tp_free(lz); + PyObject_GC_UnTrack(lz); + Py_XDECREF(lz->func); + Py_XDECREF(lz->it); + Py_TYPE(lz)->tp_free(lz); } static int dropwhile_traverse(dropwhileobject *lz, visitproc visit, void *arg) { - Py_VISIT(lz->it); - Py_VISIT(lz->func); - return 0; + Py_VISIT(lz->it); + Py_VISIT(lz->func); + return 0; } static PyObject * dropwhile_next(dropwhileobject *lz) { - PyObject *item, *good; - PyObject *it = lz->it; - long ok; - PyObject *(*iternext)(PyObject *); - - iternext = *Py_TYPE(it)->tp_iternext; - for (;;) { - item = iternext(it); - if (item == NULL) - return NULL; - if (lz->start == 1) - return item; - - good = PyObject_CallFunctionObjArgs(lz->func, item, NULL); - if (good == NULL) { - Py_DECREF(item); - return NULL; - } - ok = PyObject_IsTrue(good); - Py_DECREF(good); - if (!ok) { - lz->start = 1; - return item; - } - Py_DECREF(item); - } + PyObject *item, *good; + PyObject *it = lz->it; + long ok; + PyObject *(*iternext)(PyObject *); + + iternext = *Py_TYPE(it)->tp_iternext; + for (;;) { + item = iternext(it); + if (item == NULL) + return NULL; + if (lz->start == 1) + return item; + + good = PyObject_CallFunctionObjArgs(lz->func, item, NULL); + if (good == NULL) { + Py_DECREF(item); + return NULL; + } + ok = PyObject_IsTrue(good); + Py_DECREF(good); + if (!ok) { + lz->start = 1; + return item; + } + Py_DECREF(item); + } } PyDoc_STRVAR(dropwhile_doc, @@ -918,57 +918,57 @@ Afterwards, return every element until the iterable is exhausted."); static PyTypeObject dropwhile_type = { - PyVarObject_HEAD_INIT(NULL, 0) - "itertools.dropwhile", /* tp_name */ - sizeof(dropwhileobject), /* tp_basicsize */ - 0, /* tp_itemsize */ - /* methods */ - (destructor)dropwhile_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 | - Py_TPFLAGS_BASETYPE, /* tp_flags */ - dropwhile_doc, /* tp_doc */ - (traverseproc)dropwhile_traverse, /* tp_traverse */ - 0, /* tp_clear */ - 0, /* tp_richcompare */ - 0, /* tp_weaklistoffset */ - PyObject_SelfIter, /* tp_iter */ - (iternextfunc)dropwhile_next, /* tp_iternext */ - 0, /* tp_methods */ - 0, /* tp_members */ - 0, /* tp_getset */ - 0, /* tp_base */ - 0, /* tp_dict */ - 0, /* tp_descr_get */ - 0, /* tp_descr_set */ - 0, /* tp_dictoffset */ - 0, /* tp_init */ - 0, /* tp_alloc */ - dropwhile_new, /* tp_new */ - PyObject_GC_Del, /* tp_free */ + PyVarObject_HEAD_INIT(NULL, 0) + "itertools.dropwhile", /* tp_name */ + sizeof(dropwhileobject), /* tp_basicsize */ + 0, /* tp_itemsize */ + /* methods */ + (destructor)dropwhile_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 | + Py_TPFLAGS_BASETYPE, /* tp_flags */ + dropwhile_doc, /* tp_doc */ + (traverseproc)dropwhile_traverse, /* tp_traverse */ + 0, /* tp_clear */ + 0, /* tp_richcompare */ + 0, /* tp_weaklistoffset */ + PyObject_SelfIter, /* tp_iter */ + (iternextfunc)dropwhile_next, /* tp_iternext */ + 0, /* tp_methods */ + 0, /* tp_members */ + 0, /* tp_getset */ + 0, /* tp_base */ + 0, /* tp_dict */ + 0, /* tp_descr_get */ + 0, /* tp_descr_set */ + 0, /* tp_dictoffset */ + 0, /* tp_init */ + 0, /* tp_alloc */ + dropwhile_new, /* tp_new */ + PyObject_GC_Del, /* tp_free */ }; /* takewhile object **********************************************************/ typedef struct { - PyObject_HEAD - PyObject *func; - PyObject *it; - long stop; + PyObject_HEAD + PyObject *func; + PyObject *it; + long stop; } takewhileobject; static PyTypeObject takewhile_type; @@ -976,78 +976,78 @@ static PyObject * takewhile_new(PyTypeObject *type, PyObject *args, PyObject *kwds) { - PyObject *func, *seq; - PyObject *it; - takewhileobject *lz; - - if (type == &takewhile_type && !_PyArg_NoKeywords("takewhile()", kwds)) - return NULL; - - if (!PyArg_UnpackTuple(args, "takewhile", 2, 2, &func, &seq)) - return NULL; - - /* Get iterator. */ - it = PyObject_GetIter(seq); - if (it == NULL) - return NULL; - - /* create takewhileobject structure */ - lz = (takewhileobject *)type->tp_alloc(type, 0); - if (lz == NULL) { - Py_DECREF(it); - return NULL; - } - Py_INCREF(func); - lz->func = func; - lz->it = it; - lz->stop = 0; + PyObject *func, *seq; + PyObject *it; + takewhileobject *lz; + + if (type == &takewhile_type && !_PyArg_NoKeywords("takewhile()", kwds)) + return NULL; + + if (!PyArg_UnpackTuple(args, "takewhile", 2, 2, &func, &seq)) + return NULL; + + /* Get iterator. */ + it = PyObject_GetIter(seq); + if (it == NULL) + return NULL; + + /* create takewhileobject structure */ + lz = (takewhileobject *)type->tp_alloc(type, 0); + if (lz == NULL) { + Py_DECREF(it); + return NULL; + } + Py_INCREF(func); + lz->func = func; + lz->it = it; + lz->stop = 0; - return (PyObject *)lz; + return (PyObject *)lz; } static void takewhile_dealloc(takewhileobject *lz) { - PyObject_GC_UnTrack(lz); - Py_XDECREF(lz->func); - Py_XDECREF(lz->it); - Py_TYPE(lz)->tp_free(lz); + PyObject_GC_UnTrack(lz); + Py_XDECREF(lz->func); + Py_XDECREF(lz->it); + Py_TYPE(lz)->tp_free(lz); } static int takewhile_traverse(takewhileobject *lz, visitproc visit, void *arg) { - Py_VISIT(lz->it); - Py_VISIT(lz->func); - return 0; + Py_VISIT(lz->it); + Py_VISIT(lz->func); + return 0; } static PyObject * takewhile_next(takewhileobject *lz) { - PyObject *item, *good; - PyObject *it = lz->it; - long ok; - - if (lz->stop == 1) - return NULL; - - item = (*Py_TYPE(it)->tp_iternext)(it); - if (item == NULL) - return NULL; - - good = PyObject_CallFunctionObjArgs(lz->func, item, NULL); - if (good == NULL) { - Py_DECREF(item); - return NULL; - } - ok = PyObject_IsTrue(good); - Py_DECREF(good); - if (ok) - return item; - Py_DECREF(item); - lz->stop = 1; - return NULL; + PyObject *item, *good; + PyObject *it = lz->it; + long ok; + + if (lz->stop == 1) + return NULL; + + item = (*Py_TYPE(it)->tp_iternext)(it); + if (item == NULL) + return NULL; + + good = PyObject_CallFunctionObjArgs(lz->func, item, NULL); + if (good == NULL) { + Py_DECREF(item); + return NULL; + } + ok = PyObject_IsTrue(good); + Py_DECREF(good); + if (ok) + return item; + Py_DECREF(item); + lz->stop = 1; + return NULL; } PyDoc_STRVAR(takewhile_doc, @@ -1057,59 +1057,59 @@ predicate evaluates to true for each entry."); static PyTypeObject takewhile_type = { - PyVarObject_HEAD_INIT(NULL, 0) - "itertools.takewhile", /* tp_name */ - sizeof(takewhileobject), /* tp_basicsize */ - 0, /* tp_itemsize */ - /* methods */ - (destructor)takewhile_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 | - Py_TPFLAGS_BASETYPE, /* tp_flags */ - takewhile_doc, /* tp_doc */ - (traverseproc)takewhile_traverse, /* tp_traverse */ - 0, /* tp_clear */ - 0, /* tp_richcompare */ - 0, /* tp_weaklistoffset */ - PyObject_SelfIter, /* tp_iter */ - (iternextfunc)takewhile_next, /* tp_iternext */ - 0, /* tp_methods */ - 0, /* tp_members */ - 0, /* tp_getset */ - 0, /* tp_base */ - 0, /* tp_dict */ - 0, /* tp_descr_get */ - 0, /* tp_descr_set */ - 0, /* tp_dictoffset */ - 0, /* tp_init */ - 0, /* tp_alloc */ - takewhile_new, /* tp_new */ - PyObject_GC_Del, /* tp_free */ + PyVarObject_HEAD_INIT(NULL, 0) + "itertools.takewhile", /* tp_name */ + sizeof(takewhileobject), /* tp_basicsize */ + 0, /* tp_itemsize */ + /* methods */ + (destructor)takewhile_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 | + Py_TPFLAGS_BASETYPE, /* tp_flags */ + takewhile_doc, /* tp_doc */ + (traverseproc)takewhile_traverse, /* tp_traverse */ + 0, /* tp_clear */ + 0, /* tp_richcompare */ + 0, /* tp_weaklistoffset */ + PyObject_SelfIter, /* tp_iter */ + (iternextfunc)takewhile_next, /* tp_iternext */ + 0, /* tp_methods */ + 0, /* tp_members */ + 0, /* tp_getset */ + 0, /* tp_base */ + 0, /* tp_dict */ + 0, /* tp_descr_get */ + 0, /* tp_descr_set */ + 0, /* tp_dictoffset */ + 0, /* tp_init */ + 0, /* tp_alloc */ + takewhile_new, /* tp_new */ + PyObject_GC_Del, /* tp_free */ }; /* islice object ************************************************************/ typedef struct { - PyObject_HEAD - PyObject *it; - Py_ssize_t next; - Py_ssize_t stop; - Py_ssize_t step; - Py_ssize_t cnt; + PyObject_HEAD + PyObject *it; + Py_ssize_t next; + Py_ssize_t stop; + Py_ssize_t step; + Py_ssize_t cnt; } isliceobject; static PyTypeObject islice_type; @@ -1117,126 +1117,126 @@ static PyObject * islice_new(PyTypeObject *type, PyObject *args, PyObject *kwds) { - PyObject *seq; - Py_ssize_t start=0, stop=-1, step=1; - PyObject *it, *a1=NULL, *a2=NULL, *a3=NULL; - Py_ssize_t numargs; - isliceobject *lz; - - if (type == &islice_type && !_PyArg_NoKeywords("islice()", kwds)) - return NULL; - - if (!PyArg_UnpackTuple(args, "islice", 2, 4, &seq, &a1, &a2, &a3)) - return NULL; - - numargs = PyTuple_Size(args); - if (numargs == 2) { - if (a1 != Py_None) { - stop = PyLong_AsSsize_t(a1); - if (stop == -1) { - if (PyErr_Occurred()) - PyErr_Clear(); - PyErr_SetString(PyExc_ValueError, - "Stop argument for islice() must be None or an integer: 0 <= x <= sys.maxsize."); - return NULL; - } - } - } else { - if (a1 != Py_None) - start = PyLong_AsSsize_t(a1); - if (start == -1 && PyErr_Occurred()) - PyErr_Clear(); - if (a2 != Py_None) { - stop = PyLong_AsSsize_t(a2); - if (stop == -1) { - if (PyErr_Occurred()) - PyErr_Clear(); - PyErr_SetString(PyExc_ValueError, - "Stop argument for islice() must be None or an integer: 0 <= x <= sys.maxsize."); - return NULL; - } - } - } - if (start<0 || stop<-1) { - PyErr_SetString(PyExc_ValueError, - "Indices for islice() must be None or an integer: 0 <= x <= sys.maxsize."); - return NULL; - } - - if (a3 != NULL) { - if (a3 != Py_None) - step = PyLong_AsSsize_t(a3); - if (step == -1 && PyErr_Occurred()) - PyErr_Clear(); - } - if (step<1) { - PyErr_SetString(PyExc_ValueError, - "Step for islice() must be a positive integer or None."); - return NULL; - } - - /* Get iterator. */ - it = PyObject_GetIter(seq); - if (it == NULL) - return NULL; - - /* create isliceobject structure */ - lz = (isliceobject *)type->tp_alloc(type, 0); - if (lz == NULL) { - Py_DECREF(it); - return NULL; - } - lz->it = it; - lz->next = start; - lz->stop = stop; - lz->step = step; - lz->cnt = 0L; + PyObject *seq; + Py_ssize_t start=0, stop=-1, step=1; + PyObject *it, *a1=NULL, *a2=NULL, *a3=NULL; + Py_ssize_t numargs; + isliceobject *lz; + + if (type == &islice_type && !_PyArg_NoKeywords("islice()", kwds)) + return NULL; + + if (!PyArg_UnpackTuple(args, "islice", 2, 4, &seq, &a1, &a2, &a3)) + return NULL; + + numargs = PyTuple_Size(args); + if (numargs == 2) { + if (a1 != Py_None) { + stop = PyLong_AsSsize_t(a1); + if (stop == -1) { + if (PyErr_Occurred()) + PyErr_Clear(); + PyErr_SetString(PyExc_ValueError, + "Stop argument for islice() must be None or an integer: 0 <= x <= sys.maxsize."); + return NULL; + } + } + } else { + if (a1 != Py_None) + start = PyLong_AsSsize_t(a1); + if (start == -1 && PyErr_Occurred()) + PyErr_Clear(); + if (a2 != Py_None) { + stop = PyLong_AsSsize_t(a2); + if (stop == -1) { + if (PyErr_Occurred()) + PyErr_Clear(); + PyErr_SetString(PyExc_ValueError, + "Stop argument for islice() must be None or an integer: 0 <= x <= sys.maxsize."); + return NULL; + } + } + } + if (start<0 || stop<-1) { + PyErr_SetString(PyExc_ValueError, + "Indices for islice() must be None or an integer: 0 <= x <= sys.maxsize."); + return NULL; + } + + if (a3 != NULL) { + if (a3 != Py_None) + step = PyLong_AsSsize_t(a3); + if (step == -1 && PyErr_Occurred()) + PyErr_Clear(); + } + if (step<1) { + PyErr_SetString(PyExc_ValueError, + "Step for islice() must be a positive integer or None."); + return NULL; + } + + /* Get iterator. */ + it = PyObject_GetIter(seq); + if (it == NULL) + return NULL; + + /* create isliceobject structure */ + lz = (isliceobject *)type->tp_alloc(type, 0); + if (lz == NULL) { + Py_DECREF(it); + return NULL; + } + lz->it = it; + lz->next = start; + lz->stop = stop; + lz->step = step; + lz->cnt = 0L; - return (PyObject *)lz; + return (PyObject *)lz; } static void islice_dealloc(isliceobject *lz) { - PyObject_GC_UnTrack(lz); - Py_XDECREF(lz->it); - Py_TYPE(lz)->tp_free(lz); + PyObject_GC_UnTrack(lz); + Py_XDECREF(lz->it); + Py_TYPE(lz)->tp_free(lz); } static int islice_traverse(isliceobject *lz, visitproc visit, void *arg) { - Py_VISIT(lz->it); - return 0; + Py_VISIT(lz->it); + return 0; } static PyObject * islice_next(isliceobject *lz) { - PyObject *item; - PyObject *it = lz->it; - Py_ssize_t oldnext; - PyObject *(*iternext)(PyObject *); - - iternext = *Py_TYPE(it)->tp_iternext; - while (lz->cnt < lz->next) { - item = iternext(it); - if (item == NULL) - return NULL; - Py_DECREF(item); - lz->cnt++; - } - if (lz->stop != -1 && lz->cnt >= lz->stop) - return NULL; - item = iternext(it); - if (item == NULL) - return NULL; - lz->cnt++; - oldnext = lz->next; - lz->next += lz->step; - if (lz->next < oldnext) /* Check for overflow */ - lz->next = lz->stop; - return item; + PyObject *item; + PyObject *it = lz->it; + Py_ssize_t oldnext; + PyObject *(*iternext)(PyObject *); + + iternext = *Py_TYPE(it)->tp_iternext; + while (lz->cnt < lz->next) { + item = iternext(it); + if (item == NULL) + return NULL; + Py_DECREF(item); + lz->cnt++; + } + if (lz->stop != -1 && lz->cnt >= lz->stop) + return NULL; + item = iternext(it); + if (item == NULL) + return NULL; + lz->cnt++; + oldnext = lz->next; + lz->next += lz->step; + if (lz->next < oldnext) /* Check for overflow */ + lz->next = lz->stop; + return item; } PyDoc_STRVAR(islice_doc, @@ -1250,56 +1250,56 @@ but returns an iterator."); static PyTypeObject islice_type = { - PyVarObject_HEAD_INIT(NULL, 0) - "itertools.islice", /* tp_name */ - sizeof(isliceobject), /* tp_basicsize */ - 0, /* tp_itemsize */ - /* methods */ - (destructor)islice_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 | - Py_TPFLAGS_BASETYPE, /* tp_flags */ - islice_doc, /* tp_doc */ - (traverseproc)islice_traverse, /* tp_traverse */ - 0, /* tp_clear */ - 0, /* tp_richcompare */ - 0, /* tp_weaklistoffset */ - PyObject_SelfIter, /* tp_iter */ - (iternextfunc)islice_next, /* tp_iternext */ - 0, /* tp_methods */ - 0, /* tp_members */ - 0, /* tp_getset */ - 0, /* tp_base */ - 0, /* tp_dict */ - 0, /* tp_descr_get */ - 0, /* tp_descr_set */ - 0, /* tp_dictoffset */ - 0, /* tp_init */ - 0, /* tp_alloc */ - islice_new, /* tp_new */ - PyObject_GC_Del, /* tp_free */ + PyVarObject_HEAD_INIT(NULL, 0) + "itertools.islice", /* tp_name */ + sizeof(isliceobject), /* tp_basicsize */ + 0, /* tp_itemsize */ + /* methods */ + (destructor)islice_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 | + Py_TPFLAGS_BASETYPE, /* tp_flags */ + islice_doc, /* tp_doc */ + (traverseproc)islice_traverse, /* tp_traverse */ + 0, /* tp_clear */ + 0, /* tp_richcompare */ + 0, /* tp_weaklistoffset */ + PyObject_SelfIter, /* tp_iter */ + (iternextfunc)islice_next, /* tp_iternext */ + 0, /* tp_methods */ + 0, /* tp_members */ + 0, /* tp_getset */ + 0, /* tp_base */ + 0, /* tp_dict */ + 0, /* tp_descr_get */ + 0, /* tp_descr_set */ + 0, /* tp_dictoffset */ + 0, /* tp_init */ + 0, /* tp_alloc */ + islice_new, /* tp_new */ + PyObject_GC_Del, /* tp_free */ }; /* starmap object ************************************************************/ typedef struct { - PyObject_HEAD - PyObject *func; - PyObject *it; + PyObject_HEAD + PyObject *func; + PyObject *it; } starmapobject; static PyTypeObject starmap_type; @@ -1307,71 +1307,71 @@ static PyObject * starmap_new(PyTypeObject *type, PyObject *args, PyObject *kwds) { - PyObject *func, *seq; - PyObject *it; - starmapobject *lz; - - if (type == &starmap_type && !_PyArg_NoKeywords("starmap()", kwds)) - return NULL; - - if (!PyArg_UnpackTuple(args, "starmap", 2, 2, &func, &seq)) - return NULL; - - /* Get iterator. */ - it = PyObject_GetIter(seq); - if (it == NULL) - return NULL; - - /* create starmapobject structure */ - lz = (starmapobject *)type->tp_alloc(type, 0); - if (lz == NULL) { - Py_DECREF(it); - return NULL; - } - Py_INCREF(func); - lz->func = func; - lz->it = it; + PyObject *func, *seq; + PyObject *it; + starmapobject *lz; + + if (type == &starmap_type && !_PyArg_NoKeywords("starmap()", kwds)) + return NULL; + + if (!PyArg_UnpackTuple(args, "starmap", 2, 2, &func, &seq)) + return NULL; + + /* Get iterator. */ + it = PyObject_GetIter(seq); + if (it == NULL) + return NULL; + + /* create starmapobject structure */ + lz = (starmapobject *)type->tp_alloc(type, 0); + if (lz == NULL) { + Py_DECREF(it); + return NULL; + } + Py_INCREF(func); + lz->func = func; + lz->it = it; - return (PyObject *)lz; + return (PyObject *)lz; } static void starmap_dealloc(starmapobject *lz) { - PyObject_GC_UnTrack(lz); - Py_XDECREF(lz->func); - Py_XDECREF(lz->it); - Py_TYPE(lz)->tp_free(lz); + PyObject_GC_UnTrack(lz); + Py_XDECREF(lz->func); + Py_XDECREF(lz->it); + Py_TYPE(lz)->tp_free(lz); } static int starmap_traverse(starmapobject *lz, visitproc visit, void *arg) { - Py_VISIT(lz->it); - Py_VISIT(lz->func); - return 0; + Py_VISIT(lz->it); + Py_VISIT(lz->func); + return 0; } static PyObject * starmap_next(starmapobject *lz) { - PyObject *args; - PyObject *result; - PyObject *it = lz->it; - - args = (*Py_TYPE(it)->tp_iternext)(it); - if (args == NULL) - return NULL; - if (!PyTuple_CheckExact(args)) { - PyObject *newargs = PySequence_Tuple(args); - Py_DECREF(args); - if (newargs == NULL) - return NULL; - args = newargs; - } - result = PyObject_Call(lz->func, args, NULL); - Py_DECREF(args); - return result; + PyObject *args; + PyObject *result; + PyObject *it = lz->it; + + args = (*Py_TYPE(it)->tp_iternext)(it); + if (args == NULL) + return NULL; + if (!PyTuple_CheckExact(args)) { + PyObject *newargs = PySequence_Tuple(args); + Py_DECREF(args); + if (newargs == NULL) + return NULL; + args = newargs; + } + result = PyObject_Call(lz->func, args, NULL); + Py_DECREF(args); + return result; } PyDoc_STRVAR(starmap_doc, @@ -1381,152 +1381,152 @@ with a argument tuple taken from the given sequence."); static PyTypeObject starmap_type = { - PyVarObject_HEAD_INIT(NULL, 0) - "itertools.starmap", /* tp_name */ - sizeof(starmapobject), /* tp_basicsize */ - 0, /* tp_itemsize */ - /* methods */ - (destructor)starmap_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 | - Py_TPFLAGS_BASETYPE, /* tp_flags */ - starmap_doc, /* tp_doc */ - (traverseproc)starmap_traverse, /* tp_traverse */ - 0, /* tp_clear */ - 0, /* tp_richcompare */ - 0, /* tp_weaklistoffset */ - PyObject_SelfIter, /* tp_iter */ - (iternextfunc)starmap_next, /* tp_iternext */ - 0, /* tp_methods */ - 0, /* tp_members */ - 0, /* tp_getset */ - 0, /* tp_base */ - 0, /* tp_dict */ - 0, /* tp_descr_get */ - 0, /* tp_descr_set */ - 0, /* tp_dictoffset */ - 0, /* tp_init */ - 0, /* tp_alloc */ - starmap_new, /* tp_new */ - PyObject_GC_Del, /* tp_free */ + PyVarObject_HEAD_INIT(NULL, 0) + "itertools.starmap", /* tp_name */ + sizeof(starmapobject), /* tp_basicsize */ + 0, /* tp_itemsize */ + /* methods */ + (destructor)starmap_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 | + Py_TPFLAGS_BASETYPE, /* tp_flags */ + starmap_doc, /* tp_doc */ + (traverseproc)starmap_traverse, /* tp_traverse */ + 0, /* tp_clear */ + 0, /* tp_richcompare */ + 0, /* tp_weaklistoffset */ + PyObject_SelfIter, /* tp_iter */ + (iternextfunc)starmap_next, /* tp_iternext */ + 0, /* tp_methods */ + 0, /* tp_members */ + 0, /* tp_getset */ + 0, /* tp_base */ + 0, /* tp_dict */ + 0, /* tp_descr_get */ + 0, /* tp_descr_set */ + 0, /* tp_dictoffset */ + 0, /* tp_init */ + 0, /* tp_alloc */ + starmap_new, /* tp_new */ + PyObject_GC_Del, /* tp_free */ }; /* chain object ************************************************************/ typedef struct { - PyObject_HEAD - PyObject *source; /* Iterator over input iterables */ - PyObject *active; /* Currently running input iterator */ + PyObject_HEAD + PyObject *source; /* Iterator over input iterables */ + PyObject *active; /* Currently running input iterator */ } chainobject; static PyTypeObject chain_type; -static PyObject * +static PyObject * chain_new_internal(PyTypeObject *type, PyObject *source) { - chainobject *lz; + chainobject *lz; - lz = (chainobject *)type->tp_alloc(type, 0); - if (lz == NULL) { - Py_DECREF(source); - return NULL; - } - - lz->source = source; - lz->active = NULL; - return (PyObject *)lz; + lz = (chainobject *)type->tp_alloc(type, 0); + if (lz == NULL) { + Py_DECREF(source); + return NULL; + } + + lz->source = source; + lz->active = NULL; + return (PyObject *)lz; } static PyObject * chain_new(PyTypeObject *type, PyObject *args, PyObject *kwds) { - PyObject *source; + PyObject *source; + + if (type == &chain_type && !_PyArg_NoKeywords("chain()", kwds)) + return NULL; - if (type == &chain_type && !_PyArg_NoKeywords("chain()", kwds)) - return NULL; - - source = PyObject_GetIter(args); - if (source == NULL) - return NULL; + source = PyObject_GetIter(args); + if (source == NULL) + return NULL; - return chain_new_internal(type, source); + return chain_new_internal(type, source); } static PyObject * chain_new_from_iterable(PyTypeObject *type, PyObject *arg) { - PyObject *source; - - source = PyObject_GetIter(arg); - if (source == NULL) - return NULL; + PyObject *source; + + source = PyObject_GetIter(arg); + if (source == NULL) + return NULL; - return chain_new_internal(type, source); + return chain_new_internal(type, source); } static void chain_dealloc(chainobject *lz) { - PyObject_GC_UnTrack(lz); - Py_XDECREF(lz->active); - Py_XDECREF(lz->source); - Py_TYPE(lz)->tp_free(lz); + PyObject_GC_UnTrack(lz); + Py_XDECREF(lz->active); + Py_XDECREF(lz->source); + Py_TYPE(lz)->tp_free(lz); } static int chain_traverse(chainobject *lz, visitproc visit, void *arg) { - Py_VISIT(lz->source); - Py_VISIT(lz->active); - return 0; + Py_VISIT(lz->source); + Py_VISIT(lz->active); + return 0; } static PyObject * chain_next(chainobject *lz) { - PyObject *item; + PyObject *item; - if (lz->source == NULL) - return NULL; /* already stopped */ + if (lz->source == NULL) + return NULL; /* already stopped */ - if (lz->active == NULL) { - PyObject *iterable = PyIter_Next(lz->source); - if (iterable == NULL) { - Py_CLEAR(lz->source); - return NULL; /* no more input sources */ - } - lz->active = PyObject_GetIter(iterable); - Py_DECREF(iterable); - if (lz->active == NULL) { - Py_CLEAR(lz->source); - return NULL; /* input not iterable */ - } - } - item = PyIter_Next(lz->active); - if (item != NULL) - return item; - if (PyErr_Occurred()) { - if (PyErr_ExceptionMatches(PyExc_StopIteration)) - PyErr_Clear(); - else - return NULL; /* input raised an exception */ - } - Py_CLEAR(lz->active); - return chain_next(lz); /* recurse and use next active */ + if (lz->active == NULL) { + PyObject *iterable = PyIter_Next(lz->source); + if (iterable == NULL) { + Py_CLEAR(lz->source); + return NULL; /* no more input sources */ + } + lz->active = PyObject_GetIter(iterable); + Py_DECREF(iterable); + if (lz->active == NULL) { + Py_CLEAR(lz->source); + return NULL; /* input not iterable */ + } + } + item = PyIter_Next(lz->active); + if (item != NULL) + return item; + if (PyErr_Occurred()) { + if (PyErr_ExceptionMatches(PyExc_StopIteration)) + PyErr_Clear(); + else + return NULL; /* input raised an exception */ + } + Py_CLEAR(lz->active); + return chain_next(lz); /* recurse and use next active */ } PyDoc_STRVAR(chain_doc, @@ -1543,64 +1543,64 @@ that evaluates lazily."); static PyMethodDef chain_methods[] = { - {"from_iterable", (PyCFunction) chain_new_from_iterable, METH_O | METH_CLASS, - chain_from_iterable_doc}, - {NULL, NULL} /* sentinel */ + {"from_iterable", (PyCFunction) chain_new_from_iterable, METH_O | METH_CLASS, + chain_from_iterable_doc}, + {NULL, NULL} /* sentinel */ }; static PyTypeObject chain_type = { - PyVarObject_HEAD_INIT(NULL, 0) - "itertools.chain", /* tp_name */ - sizeof(chainobject), /* tp_basicsize */ - 0, /* tp_itemsize */ - /* methods */ - (destructor)chain_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 | - Py_TPFLAGS_BASETYPE, /* tp_flags */ - chain_doc, /* tp_doc */ - (traverseproc)chain_traverse, /* tp_traverse */ - 0, /* tp_clear */ - 0, /* tp_richcompare */ - 0, /* tp_weaklistoffset */ - PyObject_SelfIter, /* tp_iter */ - (iternextfunc)chain_next, /* tp_iternext */ - chain_methods, /* tp_methods */ - 0, /* tp_members */ - 0, /* tp_getset */ - 0, /* tp_base */ - 0, /* tp_dict */ - 0, /* tp_descr_get */ - 0, /* tp_descr_set */ - 0, /* tp_dictoffset */ - 0, /* tp_init */ - 0, /* tp_alloc */ - chain_new, /* tp_new */ - PyObject_GC_Del, /* tp_free */ + PyVarObject_HEAD_INIT(NULL, 0) + "itertools.chain", /* tp_name */ + sizeof(chainobject), /* tp_basicsize */ + 0, /* tp_itemsize */ + /* methods */ + (destructor)chain_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 | + Py_TPFLAGS_BASETYPE, /* tp_flags */ + chain_doc, /* tp_doc */ + (traverseproc)chain_traverse, /* tp_traverse */ + 0, /* tp_clear */ + 0, /* tp_richcompare */ + 0, /* tp_weaklistoffset */ + PyObject_SelfIter, /* tp_iter */ + (iternextfunc)chain_next, /* tp_iternext */ + chain_methods, /* tp_methods */ + 0, /* tp_members */ + 0, /* tp_getset */ + 0, /* tp_base */ + 0, /* tp_dict */ + 0, /* tp_descr_get */ + 0, /* tp_descr_set */ + 0, /* tp_dictoffset */ + 0, /* tp_init */ + 0, /* tp_alloc */ + chain_new, /* tp_new */ + PyObject_GC_Del, /* tp_free */ }; /* product object ************************************************************/ typedef struct { - PyObject_HEAD - PyObject *pools; /* tuple of pool tuples */ - Py_ssize_t *indices; /* one index per pool */ - PyObject *result; /* most recently returned result tuple */ - int stopped; /* set to 1 when the product iterator is exhausted */ + PyObject_HEAD + PyObject *pools; /* tuple of pool tuples */ + Py_ssize_t *indices; /* one index per pool */ + PyObject *result; /* most recently returned result tuple */ + int stopped; /* set to 1 when the product iterator is exhausted */ } productobject; static PyTypeObject product_type; @@ -1608,181 +1608,181 @@ static PyObject * product_new(PyTypeObject *type, PyObject *args, PyObject *kwds) { - productobject *lz; - Py_ssize_t nargs, npools, repeat=1; - PyObject *pools = NULL; - Py_ssize_t *indices = NULL; - Py_ssize_t i; - - if (kwds != NULL) { - char *kwlist[] = {"repeat", 0}; - PyObject *tmpargs = PyTuple_New(0); - if (tmpargs == NULL) - return NULL; - if (!PyArg_ParseTupleAndKeywords(tmpargs, kwds, "|n:product", kwlist, &repeat)) { - Py_DECREF(tmpargs); - return NULL; - } - Py_DECREF(tmpargs); - if (repeat < 0) { - PyErr_SetString(PyExc_ValueError, - "repeat argument cannot be negative"); - return NULL; - } - } - - assert(PyTuple_Check(args)); - nargs = (repeat == 0) ? 0 : PyTuple_GET_SIZE(args); - npools = nargs * repeat; - - indices = PyMem_Malloc(npools * sizeof(Py_ssize_t)); - if (indices == NULL) { - PyErr_NoMemory(); - goto error; - } - - pools = PyTuple_New(npools); - if (pools == NULL) - goto error; - - for (i=0; i < nargs ; ++i) { - PyObject *item = PyTuple_GET_ITEM(args, i); - PyObject *pool = PySequence_Tuple(item); - if (pool == NULL) - goto error; - PyTuple_SET_ITEM(pools, i, pool); - indices[i] = 0; - } - for ( ; i < npools; ++i) { - PyObject *pool = PyTuple_GET_ITEM(pools, i - nargs); - Py_INCREF(pool); - PyTuple_SET_ITEM(pools, i, pool); - indices[i] = 0; - } - - /* create productobject structure */ - lz = (productobject *)type->tp_alloc(type, 0); - if (lz == NULL) - goto error; - - lz->pools = pools; - lz->indices = indices; - lz->result = NULL; - lz->stopped = 0; + productobject *lz; + Py_ssize_t nargs, npools, repeat=1; + PyObject *pools = NULL; + Py_ssize_t *indices = NULL; + Py_ssize_t i; + + if (kwds != NULL) { + char *kwlist[] = {"repeat", 0}; + PyObject *tmpargs = PyTuple_New(0); + if (tmpargs == NULL) + return NULL; + if (!PyArg_ParseTupleAndKeywords(tmpargs, kwds, "|n:product", kwlist, &repeat)) { + Py_DECREF(tmpargs); + return NULL; + } + Py_DECREF(tmpargs); + if (repeat < 0) { + PyErr_SetString(PyExc_ValueError, + "repeat argument cannot be negative"); + return NULL; + } + } + + assert(PyTuple_Check(args)); + nargs = (repeat == 0) ? 0 : PyTuple_GET_SIZE(args); + npools = nargs * repeat; + + indices = PyMem_Malloc(npools * sizeof(Py_ssize_t)); + if (indices == NULL) { + PyErr_NoMemory(); + goto error; + } + + pools = PyTuple_New(npools); + if (pools == NULL) + goto error; + + for (i=0; i < nargs ; ++i) { + PyObject *item = PyTuple_GET_ITEM(args, i); + PyObject *pool = PySequence_Tuple(item); + if (pool == NULL) + goto error; + PyTuple_SET_ITEM(pools, i, pool); + indices[i] = 0; + } + for ( ; i < npools; ++i) { + PyObject *pool = PyTuple_GET_ITEM(pools, i - nargs); + Py_INCREF(pool); + PyTuple_SET_ITEM(pools, i, pool); + indices[i] = 0; + } + + /* create productobject structure */ + lz = (productobject *)type->tp_alloc(type, 0); + if (lz == NULL) + goto error; + + lz->pools = pools; + lz->indices = indices; + lz->result = NULL; + lz->stopped = 0; - return (PyObject *)lz; + return (PyObject *)lz; error: - if (indices != NULL) - PyMem_Free(indices); - Py_XDECREF(pools); - return NULL; + if (indices != NULL) + PyMem_Free(indices); + Py_XDECREF(pools); + return NULL; } static void product_dealloc(productobject *lz) { - PyObject_GC_UnTrack(lz); - Py_XDECREF(lz->pools); - Py_XDECREF(lz->result); - if (lz->indices != NULL) - PyMem_Free(lz->indices); - Py_TYPE(lz)->tp_free(lz); + PyObject_GC_UnTrack(lz); + Py_XDECREF(lz->pools); + Py_XDECREF(lz->result); + if (lz->indices != NULL) + PyMem_Free(lz->indices); + Py_TYPE(lz)->tp_free(lz); } static int product_traverse(productobject *lz, visitproc visit, void *arg) { - Py_VISIT(lz->pools); - Py_VISIT(lz->result); - return 0; + Py_VISIT(lz->pools); + Py_VISIT(lz->result); + return 0; } static PyObject * product_next(productobject *lz) { - PyObject *pool; - PyObject *elem; - PyObject *oldelem; - PyObject *pools = lz->pools; - PyObject *result = lz->result; - Py_ssize_t npools = PyTuple_GET_SIZE(pools); - Py_ssize_t i; - - if (lz->stopped) - return NULL; - - if (result == NULL) { - /* On the first pass, return an initial tuple filled with the - first element from each pool. */ - result = PyTuple_New(npools); - if (result == NULL) - goto empty; - lz->result = result; - for (i=0; i < npools; i++) { - pool = PyTuple_GET_ITEM(pools, i); - if (PyTuple_GET_SIZE(pool) == 0) - goto empty; - elem = PyTuple_GET_ITEM(pool, 0); - Py_INCREF(elem); - PyTuple_SET_ITEM(result, i, elem); - } - } else { - Py_ssize_t *indices = lz->indices; - - /* Copy the previous result tuple or re-use it if available */ - if (Py_REFCNT(result) > 1) { - PyObject *old_result = result; - result = PyTuple_New(npools); - if (result == NULL) - goto empty; - lz->result = result; - for (i=0; i < npools; i++) { - elem = PyTuple_GET_ITEM(old_result, i); - Py_INCREF(elem); - PyTuple_SET_ITEM(result, i, elem); - } - Py_DECREF(old_result); - } - /* Now, we've got the only copy so we can update it in-place */ - assert (npools==0 || Py_REFCNT(result) == 1); - - /* Update the pool indices right-to-left. Only advance to the - next pool when the previous one rolls-over */ - for (i=npools-1 ; i >= 0 ; i--) { - pool = PyTuple_GET_ITEM(pools, i); - indices[i]++; - if (indices[i] == PyTuple_GET_SIZE(pool)) { - /* Roll-over and advance to next pool */ - indices[i] = 0; - elem = PyTuple_GET_ITEM(pool, 0); - Py_INCREF(elem); - oldelem = PyTuple_GET_ITEM(result, i); - PyTuple_SET_ITEM(result, i, elem); - Py_DECREF(oldelem); - } else { - /* No rollover. Just increment and stop here. */ - elem = PyTuple_GET_ITEM(pool, indices[i]); - Py_INCREF(elem); - oldelem = PyTuple_GET_ITEM(result, i); - PyTuple_SET_ITEM(result, i, elem); - Py_DECREF(oldelem); - break; - } - } - - /* If i is negative, then the indices have all rolled-over - and we're done. */ - if (i < 0) - goto empty; - } + PyObject *pool; + PyObject *elem; + PyObject *oldelem; + PyObject *pools = lz->pools; + PyObject *result = lz->result; + Py_ssize_t npools = PyTuple_GET_SIZE(pools); + Py_ssize_t i; + + if (lz->stopped) + return NULL; + + if (result == NULL) { + /* On the first pass, return an initial tuple filled with the + first element from each pool. */ + result = PyTuple_New(npools); + if (result == NULL) + goto empty; + lz->result = result; + for (i=0; i < npools; i++) { + pool = PyTuple_GET_ITEM(pools, i); + if (PyTuple_GET_SIZE(pool) == 0) + goto empty; + elem = PyTuple_GET_ITEM(pool, 0); + Py_INCREF(elem); + PyTuple_SET_ITEM(result, i, elem); + } + } else { + Py_ssize_t *indices = lz->indices; + + /* Copy the previous result tuple or re-use it if available */ + if (Py_REFCNT(result) > 1) { + PyObject *old_result = result; + result = PyTuple_New(npools); + if (result == NULL) + goto empty; + lz->result = result; + for (i=0; i < npools; i++) { + elem = PyTuple_GET_ITEM(old_result, i); + Py_INCREF(elem); + PyTuple_SET_ITEM(result, i, elem); + } + Py_DECREF(old_result); + } + /* Now, we've got the only copy so we can update it in-place */ + assert (npools==0 || Py_REFCNT(result) == 1); + + /* Update the pool indices right-to-left. Only advance to the + next pool when the previous one rolls-over */ + for (i=npools-1 ; i >= 0 ; i--) { + pool = PyTuple_GET_ITEM(pools, i); + indices[i]++; + if (indices[i] == PyTuple_GET_SIZE(pool)) { + /* Roll-over and advance to next pool */ + indices[i] = 0; + elem = PyTuple_GET_ITEM(pool, 0); + Py_INCREF(elem); + oldelem = PyTuple_GET_ITEM(result, i); + PyTuple_SET_ITEM(result, i, elem); + Py_DECREF(oldelem); + } else { + /* No rollover. Just increment and stop here. */ + elem = PyTuple_GET_ITEM(pool, indices[i]); + Py_INCREF(elem); + oldelem = PyTuple_GET_ITEM(result, i); + PyTuple_SET_ITEM(result, i, elem); + Py_DECREF(oldelem); + break; + } + } - Py_INCREF(result); - return result; + /* If i is negative, then the indices have all rolled-over + and we're done. */ + if (i < 0) + goto empty; + } + + Py_INCREF(result); + return result; empty: - lz->stopped = 1; - return NULL; + lz->stopped = 1; + return NULL; } PyDoc_STRVAR(product_doc, @@ -1800,59 +1800,59 @@ product((0,1), (0,1), (0,1)) --> (0,0,0) (0,0,1) (0,1,0) (0,1,1) (1,0,0) ..."); static PyTypeObject product_type = { - PyVarObject_HEAD_INIT(NULL, 0) - "itertools.product", /* tp_name */ - sizeof(productobject), /* tp_basicsize */ - 0, /* tp_itemsize */ - /* methods */ - (destructor)product_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 | - Py_TPFLAGS_BASETYPE, /* tp_flags */ - product_doc, /* tp_doc */ - (traverseproc)product_traverse, /* tp_traverse */ - 0, /* tp_clear */ - 0, /* tp_richcompare */ - 0, /* tp_weaklistoffset */ - PyObject_SelfIter, /* tp_iter */ - (iternextfunc)product_next, /* tp_iternext */ - 0, /* tp_methods */ - 0, /* tp_members */ - 0, /* tp_getset */ - 0, /* tp_base */ - 0, /* tp_dict */ - 0, /* tp_descr_get */ - 0, /* tp_descr_set */ - 0, /* tp_dictoffset */ - 0, /* tp_init */ - 0, /* tp_alloc */ - product_new, /* tp_new */ - PyObject_GC_Del, /* tp_free */ + PyVarObject_HEAD_INIT(NULL, 0) + "itertools.product", /* tp_name */ + sizeof(productobject), /* tp_basicsize */ + 0, /* tp_itemsize */ + /* methods */ + (destructor)product_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 | + Py_TPFLAGS_BASETYPE, /* tp_flags */ + product_doc, /* tp_doc */ + (traverseproc)product_traverse, /* tp_traverse */ + 0, /* tp_clear */ + 0, /* tp_richcompare */ + 0, /* tp_weaklistoffset */ + PyObject_SelfIter, /* tp_iter */ + (iternextfunc)product_next, /* tp_iternext */ + 0, /* tp_methods */ + 0, /* tp_members */ + 0, /* tp_getset */ + 0, /* tp_base */ + 0, /* tp_dict */ + 0, /* tp_descr_get */ + 0, /* tp_descr_set */ + 0, /* tp_dictoffset */ + 0, /* tp_init */ + 0, /* tp_alloc */ + product_new, /* tp_new */ + PyObject_GC_Del, /* tp_free */ }; /* combinations object ************************************************************/ typedef struct { - PyObject_HEAD - PyObject *pool; /* input converted to a tuple */ - Py_ssize_t *indices; /* one index per result element */ - PyObject *result; /* most recently returned result tuple */ - Py_ssize_t r; /* size of result tuple */ - int stopped; /* set to 1 when the combinations iterator is exhausted */ + PyObject_HEAD + PyObject *pool; /* input converted to a tuple */ + Py_ssize_t *indices; /* one index per result element */ + PyObject *result; /* most recently returned result tuple */ + Py_ssize_t r; /* size of result tuple */ + int stopped; /* set to 1 when the combinations iterator is exhausted */ } combinationsobject; static PyTypeObject combinations_type; @@ -1860,160 +1860,160 @@ static PyObject * combinations_new(PyTypeObject *type, PyObject *args, PyObject *kwds) { - combinationsobject *co; - Py_ssize_t n; - Py_ssize_t r; - PyObject *pool = NULL; - PyObject *iterable = NULL; - Py_ssize_t *indices = NULL; - Py_ssize_t i; - static char *kwargs[] = {"iterable", "r", NULL}; - - if (!PyArg_ParseTupleAndKeywords(args, kwds, "On:combinations", kwargs, - &iterable, &r)) - return NULL; - - pool = PySequence_Tuple(iterable); - if (pool == NULL) - goto error; - n = PyTuple_GET_SIZE(pool); - if (r < 0) { - PyErr_SetString(PyExc_ValueError, "r must be non-negative"); - goto error; - } - - indices = PyMem_Malloc(r * sizeof(Py_ssize_t)); - if (indices == NULL) { - PyErr_NoMemory(); - goto error; - } - - for (i=0 ; itp_alloc(type, 0); - if (co == NULL) - goto error; - - co->pool = pool; - co->indices = indices; - co->result = NULL; - co->r = r; - co->stopped = r > n ? 1 : 0; + combinationsobject *co; + Py_ssize_t n; + Py_ssize_t r; + PyObject *pool = NULL; + PyObject *iterable = NULL; + Py_ssize_t *indices = NULL; + Py_ssize_t i; + static char *kwargs[] = {"iterable", "r", NULL}; + + if (!PyArg_ParseTupleAndKeywords(args, kwds, "On:combinations", kwargs, + &iterable, &r)) + return NULL; + + pool = PySequence_Tuple(iterable); + if (pool == NULL) + goto error; + n = PyTuple_GET_SIZE(pool); + if (r < 0) { + PyErr_SetString(PyExc_ValueError, "r must be non-negative"); + goto error; + } + + indices = PyMem_Malloc(r * sizeof(Py_ssize_t)); + if (indices == NULL) { + PyErr_NoMemory(); + goto error; + } + + for (i=0 ; itp_alloc(type, 0); + if (co == NULL) + goto error; + + co->pool = pool; + co->indices = indices; + co->result = NULL; + co->r = r; + co->stopped = r > n ? 1 : 0; - return (PyObject *)co; + return (PyObject *)co; error: - if (indices != NULL) - PyMem_Free(indices); - Py_XDECREF(pool); - return NULL; + if (indices != NULL) + PyMem_Free(indices); + Py_XDECREF(pool); + return NULL; } static void combinations_dealloc(combinationsobject *co) { - PyObject_GC_UnTrack(co); - Py_XDECREF(co->pool); - Py_XDECREF(co->result); - if (co->indices != NULL) - PyMem_Free(co->indices); - Py_TYPE(co)->tp_free(co); + PyObject_GC_UnTrack(co); + Py_XDECREF(co->pool); + Py_XDECREF(co->result); + if (co->indices != NULL) + PyMem_Free(co->indices); + Py_TYPE(co)->tp_free(co); } static int combinations_traverse(combinationsobject *co, visitproc visit, void *arg) { - Py_VISIT(co->pool); - Py_VISIT(co->result); - return 0; + Py_VISIT(co->pool); + Py_VISIT(co->result); + return 0; } static PyObject * combinations_next(combinationsobject *co) { - PyObject *elem; - PyObject *oldelem; - PyObject *pool = co->pool; - Py_ssize_t *indices = co->indices; - PyObject *result = co->result; - Py_ssize_t n = PyTuple_GET_SIZE(pool); - Py_ssize_t r = co->r; - Py_ssize_t i, j, index; - - if (co->stopped) - return NULL; - - if (result == NULL) { - /* On the first pass, initialize result tuple using the indices */ - result = PyTuple_New(r); - if (result == NULL) - goto empty; - co->result = result; - for (i=0; i 1) { - PyObject *old_result = result; - result = PyTuple_New(r); - if (result == NULL) - goto empty; - co->result = result; - for (i=0; i= 0 && indices[i] == i+n-r ; i--) - ; - - /* If i is negative, then the indices are all at - their maximum value and we're done. */ - if (i < 0) - goto empty; - - /* Increment the current index which we know is not at its - maximum. Then move back to the right setting each index - to its lowest possible value (one higher than the index - to its left -- this maintains the sort order invariant). */ - indices[i]++; - for (j=i+1 ; jpool; + Py_ssize_t *indices = co->indices; + PyObject *result = co->result; + Py_ssize_t n = PyTuple_GET_SIZE(pool); + Py_ssize_t r = co->r; + Py_ssize_t i, j, index; + + if (co->stopped) + return NULL; + + if (result == NULL) { + /* On the first pass, initialize result tuple using the indices */ + result = PyTuple_New(r); + if (result == NULL) + goto empty; + co->result = result; + for (i=0; i 1) { + PyObject *old_result = result; + result = PyTuple_New(r); + if (result == NULL) + goto empty; + co->result = result; + for (i=0; i= 0 && indices[i] == i+n-r ; i--) + ; + + /* If i is negative, then the indices are all at + their maximum value and we're done. */ + if (i < 0) + goto empty; + + /* Increment the current index which we know is not at its + maximum. Then move back to the right setting each index + to its lowest possible value (one higher than the index + to its left -- this maintains the sort order invariant). */ + indices[i]++; + for (j=i+1 ; jstopped = 1; - return NULL; + co->stopped = 1; + return NULL; } PyDoc_STRVAR(combinations_doc, @@ -2023,47 +2023,47 @@ combinations(range(4), 3) --> (0,1,2), (0,1,3), (0,2,3), (1,2,3)"); static PyTypeObject combinations_type = { - PyVarObject_HEAD_INIT(NULL, 0) - "itertools.combinations", /* tp_name */ - sizeof(combinationsobject), /* tp_basicsize */ - 0, /* tp_itemsize */ - /* methods */ - (destructor)combinations_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 | - Py_TPFLAGS_BASETYPE, /* tp_flags */ - combinations_doc, /* tp_doc */ - (traverseproc)combinations_traverse, /* tp_traverse */ - 0, /* tp_clear */ - 0, /* tp_richcompare */ - 0, /* tp_weaklistoffset */ - PyObject_SelfIter, /* tp_iter */ - (iternextfunc)combinations_next, /* tp_iternext */ - 0, /* tp_methods */ - 0, /* tp_members */ - 0, /* tp_getset */ - 0, /* tp_base */ - 0, /* tp_dict */ - 0, /* tp_descr_get */ - 0, /* tp_descr_set */ - 0, /* tp_dictoffset */ - 0, /* tp_init */ - 0, /* tp_alloc */ - combinations_new, /* tp_new */ - PyObject_GC_Del, /* tp_free */ + PyVarObject_HEAD_INIT(NULL, 0) + "itertools.combinations", /* tp_name */ + sizeof(combinationsobject), /* tp_basicsize */ + 0, /* tp_itemsize */ + /* methods */ + (destructor)combinations_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 | + Py_TPFLAGS_BASETYPE, /* tp_flags */ + combinations_doc, /* tp_doc */ + (traverseproc)combinations_traverse, /* tp_traverse */ + 0, /* tp_clear */ + 0, /* tp_richcompare */ + 0, /* tp_weaklistoffset */ + PyObject_SelfIter, /* tp_iter */ + (iternextfunc)combinations_next, /* tp_iternext */ + 0, /* tp_methods */ + 0, /* tp_members */ + 0, /* tp_getset */ + 0, /* tp_base */ + 0, /* tp_dict */ + 0, /* tp_descr_get */ + 0, /* tp_descr_set */ + 0, /* tp_dictoffset */ + 0, /* tp_init */ + 0, /* tp_alloc */ + combinations_new, /* tp_new */ + PyObject_GC_Del, /* tp_free */ }; @@ -2071,37 +2071,37 @@ /* Equivalent to: - def combinations_with_replacement(iterable, r): - "combinations_with_replacement('ABC', 2) --> AA AB AC BB BC CC" - # number items returned: (n+r-1)! / r! / (n-1)! - pool = tuple(iterable) - n = len(pool) - indices = [0] * r - yield tuple(pool[i] for i in indices) - while 1: - for i in reversed(range(r)): - if indices[i] != n - 1: - break - else: - return - indices[i:] = [indices[i] + 1] * (r - i) - yield tuple(pool[i] for i in indices) - - def combinations_with_replacement2(iterable, r): - 'Alternate version that filters from product()' - pool = tuple(iterable) - n = len(pool) - for indices in product(range(n), repeat=r): - if sorted(indices) == list(indices): - yield tuple(pool[i] for i in indices) + def combinations_with_replacement(iterable, r): + "combinations_with_replacement('ABC', 2) --> AA AB AC BB BC CC" + # number items returned: (n+r-1)! / r! / (n-1)! + pool = tuple(iterable) + n = len(pool) + indices = [0] * r + yield tuple(pool[i] for i in indices) + while 1: + for i in reversed(range(r)): + if indices[i] != n - 1: + break + else: + return + indices[i:] = [indices[i] + 1] * (r - i) + yield tuple(pool[i] for i in indices) + + def combinations_with_replacement2(iterable, r): + 'Alternate version that filters from product()' + pool = tuple(iterable) + n = len(pool) + for indices in product(range(n), repeat=r): + if sorted(indices) == list(indices): + yield tuple(pool[i] for i in indices) */ typedef struct { - PyObject_HEAD - PyObject *pool; /* input converted to a tuple */ - Py_ssize_t *indices; /* one index per result element */ - PyObject *result; /* most recently returned result tuple */ - Py_ssize_t r; /* size of result tuple */ - int stopped; /* set to 1 when the cwr iterator is exhausted */ + PyObject_HEAD + PyObject *pool; /* input converted to a tuple */ + Py_ssize_t *indices; /* one index per result element */ + PyObject *result; /* most recently returned result tuple */ + Py_ssize_t r; /* size of result tuple */ + int stopped; /* set to 1 when the cwr iterator is exhausted */ } cwrobject; static PyTypeObject cwr_type; @@ -2109,156 +2109,156 @@ static PyObject * cwr_new(PyTypeObject *type, PyObject *args, PyObject *kwds) { - cwrobject *co; - Py_ssize_t n; - Py_ssize_t r; - PyObject *pool = NULL; - PyObject *iterable = NULL; - Py_ssize_t *indices = NULL; - Py_ssize_t i; - static char *kwargs[] = {"iterable", "r", NULL}; - - if (!PyArg_ParseTupleAndKeywords(args, kwds, "On:combinations_with_replacement", kwargs, - &iterable, &r)) - return NULL; - - pool = PySequence_Tuple(iterable); - if (pool == NULL) - goto error; - n = PyTuple_GET_SIZE(pool); - if (r < 0) { - PyErr_SetString(PyExc_ValueError, "r must be non-negative"); - goto error; - } - - indices = PyMem_Malloc(r * sizeof(Py_ssize_t)); - if (indices == NULL) { - PyErr_NoMemory(); - goto error; - } - - for (i=0 ; itp_alloc(type, 0); - if (co == NULL) - goto error; - - co->pool = pool; - co->indices = indices; - co->result = NULL; - co->r = r; - co->stopped = !n && r; + cwrobject *co; + Py_ssize_t n; + Py_ssize_t r; + PyObject *pool = NULL; + PyObject *iterable = NULL; + Py_ssize_t *indices = NULL; + Py_ssize_t i; + static char *kwargs[] = {"iterable", "r", NULL}; + + if (!PyArg_ParseTupleAndKeywords(args, kwds, "On:combinations_with_replacement", kwargs, + &iterable, &r)) + return NULL; + + pool = PySequence_Tuple(iterable); + if (pool == NULL) + goto error; + n = PyTuple_GET_SIZE(pool); + if (r < 0) { + PyErr_SetString(PyExc_ValueError, "r must be non-negative"); + goto error; + } + + indices = PyMem_Malloc(r * sizeof(Py_ssize_t)); + if (indices == NULL) { + PyErr_NoMemory(); + goto error; + } + + for (i=0 ; itp_alloc(type, 0); + if (co == NULL) + goto error; + + co->pool = pool; + co->indices = indices; + co->result = NULL; + co->r = r; + co->stopped = !n && r; - return (PyObject *)co; + return (PyObject *)co; error: - if (indices != NULL) - PyMem_Free(indices); - Py_XDECREF(pool); - return NULL; + if (indices != NULL) + PyMem_Free(indices); + Py_XDECREF(pool); + return NULL; } static void cwr_dealloc(cwrobject *co) { - PyObject_GC_UnTrack(co); - Py_XDECREF(co->pool); - Py_XDECREF(co->result); - if (co->indices != NULL) - PyMem_Free(co->indices); - Py_TYPE(co)->tp_free(co); + PyObject_GC_UnTrack(co); + Py_XDECREF(co->pool); + Py_XDECREF(co->result); + if (co->indices != NULL) + PyMem_Free(co->indices); + Py_TYPE(co)->tp_free(co); } static int cwr_traverse(cwrobject *co, visitproc visit, void *arg) { - Py_VISIT(co->pool); - Py_VISIT(co->result); - return 0; + Py_VISIT(co->pool); + Py_VISIT(co->result); + return 0; } static PyObject * cwr_next(cwrobject *co) { - PyObject *elem; - PyObject *oldelem; - PyObject *pool = co->pool; - Py_ssize_t *indices = co->indices; - PyObject *result = co->result; - Py_ssize_t n = PyTuple_GET_SIZE(pool); - Py_ssize_t r = co->r; - Py_ssize_t i, j, index; - - if (co->stopped) - return NULL; - - if (result == NULL) { - /* On the first pass, initialize result tuple using the indices */ - result = PyTuple_New(r); - if (result == NULL) - goto empty; - co->result = result; - for (i=0; i 1) { - PyObject *old_result = result; - result = PyTuple_New(r); - if (result == NULL) - goto empty; - co->result = result; - for (i=0; i= 0 && indices[i] == n-1; i--) - ; - - /* If i is negative, then the indices are all at - their maximum value and we're done. */ - if (i < 0) - goto empty; - - /* Increment the current index which we know is not at its - maximum. Then set all to the right to the same value. */ - indices[i]++; - for (j=i+1 ; jpool; + Py_ssize_t *indices = co->indices; + PyObject *result = co->result; + Py_ssize_t n = PyTuple_GET_SIZE(pool); + Py_ssize_t r = co->r; + Py_ssize_t i, j, index; + + if (co->stopped) + return NULL; + + if (result == NULL) { + /* On the first pass, initialize result tuple using the indices */ + result = PyTuple_New(r); + if (result == NULL) + goto empty; + co->result = result; + for (i=0; i 1) { + PyObject *old_result = result; + result = PyTuple_New(r); + if (result == NULL) + goto empty; + co->result = result; + for (i=0; i= 0 && indices[i] == n-1; i--) + ; + + /* If i is negative, then the indices are all at + their maximum value and we're done. */ + if (i < 0) + goto empty; + + /* Increment the current index which we know is not at its + maximum. Then set all to the right to the same value. */ + indices[i]++; + for (j=i+1 ; jstopped = 1; - return NULL; + co->stopped = 1; + return NULL; } PyDoc_STRVAR(cwr_doc, @@ -2269,52 +2269,52 @@ combinations_with_replacement('ABC', 2) --> AA AB AC BB BC CC"); static PyTypeObject cwr_type = { - PyVarObject_HEAD_INIT(NULL, 0) - "itertools.combinations_with_replacement", /* tp_name */ - sizeof(cwrobject), /* tp_basicsize */ - 0, /* tp_itemsize */ - /* methods */ - (destructor)cwr_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 | - Py_TPFLAGS_BASETYPE, /* tp_flags */ - cwr_doc, /* tp_doc */ - (traverseproc)cwr_traverse, /* tp_traverse */ - 0, /* tp_clear */ - 0, /* tp_richcompare */ - 0, /* tp_weaklistoffset */ - PyObject_SelfIter, /* tp_iter */ - (iternextfunc)cwr_next, /* tp_iternext */ - 0, /* tp_methods */ - 0, /* tp_members */ - 0, /* tp_getset */ - 0, /* tp_base */ - 0, /* tp_dict */ - 0, /* tp_descr_get */ - 0, /* tp_descr_set */ - 0, /* tp_dictoffset */ - 0, /* tp_init */ - 0, /* tp_alloc */ - cwr_new, /* tp_new */ - PyObject_GC_Del, /* tp_free */ + PyVarObject_HEAD_INIT(NULL, 0) + "itertools.combinations_with_replacement", /* tp_name */ + sizeof(cwrobject), /* tp_basicsize */ + 0, /* tp_itemsize */ + /* methods */ + (destructor)cwr_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 | + Py_TPFLAGS_BASETYPE, /* tp_flags */ + cwr_doc, /* tp_doc */ + (traverseproc)cwr_traverse, /* tp_traverse */ + 0, /* tp_clear */ + 0, /* tp_richcompare */ + 0, /* tp_weaklistoffset */ + PyObject_SelfIter, /* tp_iter */ + (iternextfunc)cwr_next, /* tp_iternext */ + 0, /* tp_methods */ + 0, /* tp_members */ + 0, /* tp_getset */ + 0, /* tp_base */ + 0, /* tp_dict */ + 0, /* tp_descr_get */ + 0, /* tp_descr_set */ + 0, /* tp_dictoffset */ + 0, /* tp_init */ + 0, /* tp_alloc */ + cwr_new, /* tp_new */ + PyObject_GC_Del, /* tp_free */ }; /* permutations object ************************************************************ - + def permutations(iterable, r=None): 'permutations(range(3), 2) --> (0,1) (0,2) (1,0) (1,2) (2,0) (2,1)' pool = tuple(iterable) @@ -2324,28 +2324,28 @@ cycles = range(n-r+1, n+1)[::-1] yield tuple(pool[i] for i in indices[:r]) while n: - for i in reversed(range(r)): - cycles[i] -= 1 - if cycles[i] == 0: - indices[i:] = indices[i+1:] + indices[i:i+1] - cycles[i] = n - i - else: - j = cycles[i] - indices[i], indices[-j] = indices[-j], indices[i] - yield tuple(pool[i] for i in indices[:r]) - break + for i in reversed(range(r)): + cycles[i] -= 1 + if cycles[i] == 0: + indices[i:] = indices[i+1:] + indices[i:i+1] + cycles[i] = n - i else: - return + j = cycles[i] + indices[i], indices[-j] = indices[-j], indices[i] + yield tuple(pool[i] for i in indices[:r]) + break + else: + return */ typedef struct { - PyObject_HEAD - PyObject *pool; /* input converted to a tuple */ - Py_ssize_t *indices; /* one index per element in the pool */ - Py_ssize_t *cycles; /* one rollover counter per element in the result */ - PyObject *result; /* most recently returned result tuple */ - Py_ssize_t r; /* size of result tuple */ - int stopped; /* set to 1 when the permutations iterator is exhausted */ + PyObject_HEAD + PyObject *pool; /* input converted to a tuple */ + Py_ssize_t *indices; /* one index per element in the pool */ + Py_ssize_t *cycles; /* one rollover counter per element in the result */ + PyObject *result; /* most recently returned result tuple */ + Py_ssize_t r; /* size of result tuple */ + int stopped; /* set to 1 when the permutations iterator is exhausted */ } permutationsobject; static PyTypeObject permutations_type; @@ -2353,184 +2353,184 @@ static PyObject * permutations_new(PyTypeObject *type, PyObject *args, PyObject *kwds) { - permutationsobject *po; - Py_ssize_t n; - Py_ssize_t r; - PyObject *robj = Py_None; - PyObject *pool = NULL; - PyObject *iterable = NULL; - Py_ssize_t *indices = NULL; - Py_ssize_t *cycles = NULL; - Py_ssize_t i; - static char *kwargs[] = {"iterable", "r", NULL}; - - if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|O:permutations", kwargs, - &iterable, &robj)) - return NULL; - - pool = PySequence_Tuple(iterable); - if (pool == NULL) - goto error; - n = PyTuple_GET_SIZE(pool); - - r = n; - if (robj != Py_None) { - if (!PyLong_Check(robj)) { - PyErr_SetString(PyExc_TypeError, "Expected int as r"); - goto error; - } - r = PyLong_AsSsize_t(robj); - if (r == -1 && PyErr_Occurred()) - goto error; - } - if (r < 0) { - PyErr_SetString(PyExc_ValueError, "r must be non-negative"); - goto error; - } - - indices = PyMem_Malloc(n * sizeof(Py_ssize_t)); - cycles = PyMem_Malloc(r * sizeof(Py_ssize_t)); - if (indices == NULL || cycles == NULL) { - PyErr_NoMemory(); - goto error; - } - - for (i=0 ; itp_alloc(type, 0); - if (po == NULL) - goto error; - - po->pool = pool; - po->indices = indices; - po->cycles = cycles; - po->result = NULL; - po->r = r; - po->stopped = r > n ? 1 : 0; + permutationsobject *po; + Py_ssize_t n; + Py_ssize_t r; + PyObject *robj = Py_None; + PyObject *pool = NULL; + PyObject *iterable = NULL; + Py_ssize_t *indices = NULL; + Py_ssize_t *cycles = NULL; + Py_ssize_t i; + static char *kwargs[] = {"iterable", "r", NULL}; + + if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|O:permutations", kwargs, + &iterable, &robj)) + return NULL; + + pool = PySequence_Tuple(iterable); + if (pool == NULL) + goto error; + n = PyTuple_GET_SIZE(pool); + + r = n; + if (robj != Py_None) { + if (!PyLong_Check(robj)) { + PyErr_SetString(PyExc_TypeError, "Expected int as r"); + goto error; + } + r = PyLong_AsSsize_t(robj); + if (r == -1 && PyErr_Occurred()) + goto error; + } + if (r < 0) { + PyErr_SetString(PyExc_ValueError, "r must be non-negative"); + goto error; + } + + indices = PyMem_Malloc(n * sizeof(Py_ssize_t)); + cycles = PyMem_Malloc(r * sizeof(Py_ssize_t)); + if (indices == NULL || cycles == NULL) { + PyErr_NoMemory(); + goto error; + } + + for (i=0 ; itp_alloc(type, 0); + if (po == NULL) + goto error; + + po->pool = pool; + po->indices = indices; + po->cycles = cycles; + po->result = NULL; + po->r = r; + po->stopped = r > n ? 1 : 0; - return (PyObject *)po; + return (PyObject *)po; error: - if (indices != NULL) - PyMem_Free(indices); - if (cycles != NULL) - PyMem_Free(cycles); - Py_XDECREF(pool); - return NULL; + if (indices != NULL) + PyMem_Free(indices); + if (cycles != NULL) + PyMem_Free(cycles); + Py_XDECREF(pool); + return NULL; } static void permutations_dealloc(permutationsobject *po) { - PyObject_GC_UnTrack(po); - Py_XDECREF(po->pool); - Py_XDECREF(po->result); - PyMem_Free(po->indices); - PyMem_Free(po->cycles); - Py_TYPE(po)->tp_free(po); + PyObject_GC_UnTrack(po); + Py_XDECREF(po->pool); + Py_XDECREF(po->result); + PyMem_Free(po->indices); + PyMem_Free(po->cycles); + Py_TYPE(po)->tp_free(po); } static int permutations_traverse(permutationsobject *po, visitproc visit, void *arg) { - Py_VISIT(po->pool); - Py_VISIT(po->result); - return 0; + Py_VISIT(po->pool); + Py_VISIT(po->result); + return 0; } static PyObject * permutations_next(permutationsobject *po) { - PyObject *elem; - PyObject *oldelem; - PyObject *pool = po->pool; - Py_ssize_t *indices = po->indices; - Py_ssize_t *cycles = po->cycles; - PyObject *result = po->result; - Py_ssize_t n = PyTuple_GET_SIZE(pool); - Py_ssize_t r = po->r; - Py_ssize_t i, j, k, index; - - if (po->stopped) - return NULL; - - if (result == NULL) { - /* On the first pass, initialize result tuple using the indices */ - result = PyTuple_New(r); - if (result == NULL) - goto empty; - po->result = result; - for (i=0; i 1) { - PyObject *old_result = result; - result = PyTuple_New(r); - if (result == NULL) - goto empty; - po->result = result; - for (i=0; i=0 ; i--) { - cycles[i] -= 1; - if (cycles[i] == 0) { - /* rotatation: indices[i:] = indices[i+1:] + indices[i:i+1] */ - index = indices[i]; - for (j=i ; jpool; + Py_ssize_t *indices = po->indices; + Py_ssize_t *cycles = po->cycles; + PyObject *result = po->result; + Py_ssize_t n = PyTuple_GET_SIZE(pool); + Py_ssize_t r = po->r; + Py_ssize_t i, j, k, index; + + if (po->stopped) + return NULL; + + if (result == NULL) { + /* On the first pass, initialize result tuple using the indices */ + result = PyTuple_New(r); + if (result == NULL) + goto empty; + po->result = result; + for (i=0; i 1) { + PyObject *old_result = result; + result = PyTuple_New(r); + if (result == NULL) + goto empty; + po->result = result; + for (i=0; i=0 ; i--) { + cycles[i] -= 1; + if (cycles[i] == 0) { + /* rotatation: indices[i:] = indices[i+1:] + indices[i:i+1] */ + index = indices[i]; + for (j=i ; jstopped = 1; - return NULL; + po->stopped = 1; + return NULL; } PyDoc_STRVAR(permutations_doc, @@ -2540,47 +2540,47 @@ permutations(range(3), 2) --> (0,1), (0,2), (1,0), (1,2), (2,0), (2,1)"); static PyTypeObject permutations_type = { - PyVarObject_HEAD_INIT(NULL, 0) - "itertools.permutations", /* tp_name */ - sizeof(permutationsobject), /* tp_basicsize */ - 0, /* tp_itemsize */ - /* methods */ - (destructor)permutations_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 | - Py_TPFLAGS_BASETYPE, /* tp_flags */ - permutations_doc, /* tp_doc */ - (traverseproc)permutations_traverse, /* tp_traverse */ - 0, /* tp_clear */ - 0, /* tp_richcompare */ - 0, /* tp_weaklistoffset */ - PyObject_SelfIter, /* tp_iter */ - (iternextfunc)permutations_next, /* tp_iternext */ - 0, /* tp_methods */ - 0, /* tp_members */ - 0, /* tp_getset */ - 0, /* tp_base */ - 0, /* tp_dict */ - 0, /* tp_descr_get */ - 0, /* tp_descr_set */ - 0, /* tp_dictoffset */ - 0, /* tp_init */ - 0, /* tp_alloc */ - permutations_new, /* tp_new */ - PyObject_GC_Del, /* tp_free */ + PyVarObject_HEAD_INIT(NULL, 0) + "itertools.permutations", /* tp_name */ + sizeof(permutationsobject), /* tp_basicsize */ + 0, /* tp_itemsize */ + /* methods */ + (destructor)permutations_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 | + Py_TPFLAGS_BASETYPE, /* tp_flags */ + permutations_doc, /* tp_doc */ + (traverseproc)permutations_traverse, /* tp_traverse */ + 0, /* tp_clear */ + 0, /* tp_richcompare */ + 0, /* tp_weaklistoffset */ + PyObject_SelfIter, /* tp_iter */ + (iternextfunc)permutations_next, /* tp_iternext */ + 0, /* tp_methods */ + 0, /* tp_members */ + 0, /* tp_getset */ + 0, /* tp_base */ + 0, /* tp_dict */ + 0, /* tp_descr_get */ + 0, /* tp_descr_set */ + 0, /* tp_dictoffset */ + 0, /* tp_init */ + 0, /* tp_alloc */ + permutations_new, /* tp_new */ + PyObject_GC_Del, /* tp_free */ }; @@ -2588,15 +2588,15 @@ /* Equivalent to: - def compress(data, selectors): - "compress('ABCDEF', [1,0,1,0,1,1]) --> A C E F" - return (d for d, s in zip(data, selectors) if s) + def compress(data, selectors): + "compress('ABCDEF', [1,0,1,0,1,1]) --> A C E F" + return (d for d, s in zip(data, selectors) if s) */ typedef struct { - PyObject_HEAD - PyObject *data; - PyObject *selectors; + PyObject_HEAD + PyObject *data; + PyObject *selectors; } compressobject; static PyTypeObject compress_type; @@ -2604,86 +2604,86 @@ static PyObject * compress_new(PyTypeObject *type, PyObject *args, PyObject *kwds) { - PyObject *seq1, *seq2; - PyObject *data=NULL, *selectors=NULL; - compressobject *lz; - static char *kwargs[] = {"data", "selectors", NULL}; - - if (!PyArg_ParseTupleAndKeywords(args, kwds, "OO:compress", kwargs, &seq1, &seq2)) - return NULL; - - data = PyObject_GetIter(seq1); - if (data == NULL) - goto fail; - selectors = PyObject_GetIter(seq2); - if (selectors == NULL) - goto fail; - - /* create compressobject structure */ - lz = (compressobject *)type->tp_alloc(type, 0); - if (lz == NULL) - goto fail; - lz->data = data; - lz->selectors = selectors; - return (PyObject *)lz; + PyObject *seq1, *seq2; + PyObject *data=NULL, *selectors=NULL; + compressobject *lz; + static char *kwargs[] = {"data", "selectors", NULL}; + + if (!PyArg_ParseTupleAndKeywords(args, kwds, "OO:compress", kwargs, &seq1, &seq2)) + return NULL; + + data = PyObject_GetIter(seq1); + if (data == NULL) + goto fail; + selectors = PyObject_GetIter(seq2); + if (selectors == NULL) + goto fail; + + /* create compressobject structure */ + lz = (compressobject *)type->tp_alloc(type, 0); + if (lz == NULL) + goto fail; + lz->data = data; + lz->selectors = selectors; + return (PyObject *)lz; fail: - Py_XDECREF(data); - Py_XDECREF(selectors); - return NULL; + Py_XDECREF(data); + Py_XDECREF(selectors); + return NULL; } static void compress_dealloc(compressobject *lz) { - PyObject_GC_UnTrack(lz); - Py_XDECREF(lz->data); - Py_XDECREF(lz->selectors); - Py_TYPE(lz)->tp_free(lz); + PyObject_GC_UnTrack(lz); + Py_XDECREF(lz->data); + Py_XDECREF(lz->selectors); + Py_TYPE(lz)->tp_free(lz); } static int compress_traverse(compressobject *lz, visitproc visit, void *arg) { - Py_VISIT(lz->data); - Py_VISIT(lz->selectors); - return 0; + Py_VISIT(lz->data); + Py_VISIT(lz->selectors); + return 0; } static PyObject * compress_next(compressobject *lz) { - PyObject *data = lz->data, *selectors = lz->selectors; - PyObject *datum, *selector; - PyObject *(*datanext)(PyObject *) = *Py_TYPE(data)->tp_iternext; - PyObject *(*selectornext)(PyObject *) = *Py_TYPE(selectors)->tp_iternext; - int ok; - - while (1) { - /* Steps: get datum, get selector, evaluate selector. - Order is important (to match the pure python version - in terms of which input gets a chance to raise an - exception first). - */ - - datum = datanext(data); - if (datum == NULL) - return NULL; - - selector = selectornext(selectors); - if (selector == NULL) { - Py_DECREF(datum); - return NULL; - } - - ok = PyObject_IsTrue(selector); - Py_DECREF(selector); - if (ok == 1) - return datum; - Py_DECREF(datum); - if (ok == -1) - return NULL; - } + PyObject *data = lz->data, *selectors = lz->selectors; + PyObject *datum, *selector; + PyObject *(*datanext)(PyObject *) = *Py_TYPE(data)->tp_iternext; + PyObject *(*selectornext)(PyObject *) = *Py_TYPE(selectors)->tp_iternext; + int ok; + + while (1) { + /* Steps: get datum, get selector, evaluate selector. + Order is important (to match the pure python version + in terms of which input gets a chance to raise an + exception first). + */ + + datum = datanext(data); + if (datum == NULL) + return NULL; + + selector = selectornext(selectors); + if (selector == NULL) { + Py_DECREF(datum); + return NULL; + } + + ok = PyObject_IsTrue(selector); + Py_DECREF(selector); + if (ok == 1) + return datum; + Py_DECREF(datum); + if (ok == -1) + return NULL; + } } PyDoc_STRVAR(compress_doc, @@ -2694,56 +2694,56 @@ selectors to choose the data elements."); static PyTypeObject compress_type = { - PyVarObject_HEAD_INIT(NULL, 0) - "itertools.compress", /* tp_name */ - sizeof(compressobject), /* tp_basicsize */ - 0, /* tp_itemsize */ - /* methods */ - (destructor)compress_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 | - Py_TPFLAGS_BASETYPE, /* tp_flags */ - compress_doc, /* tp_doc */ - (traverseproc)compress_traverse, /* tp_traverse */ - 0, /* tp_clear */ - 0, /* tp_richcompare */ - 0, /* tp_weaklistoffset */ - PyObject_SelfIter, /* tp_iter */ - (iternextfunc)compress_next, /* tp_iternext */ - 0, /* tp_methods */ - 0, /* tp_members */ - 0, /* tp_getset */ - 0, /* tp_base */ - 0, /* tp_dict */ - 0, /* tp_descr_get */ - 0, /* tp_descr_set */ - 0, /* tp_dictoffset */ - 0, /* tp_init */ - 0, /* tp_alloc */ - compress_new, /* tp_new */ - PyObject_GC_Del, /* tp_free */ + PyVarObject_HEAD_INIT(NULL, 0) + "itertools.compress", /* tp_name */ + sizeof(compressobject), /* tp_basicsize */ + 0, /* tp_itemsize */ + /* methods */ + (destructor)compress_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 | + Py_TPFLAGS_BASETYPE, /* tp_flags */ + compress_doc, /* tp_doc */ + (traverseproc)compress_traverse, /* tp_traverse */ + 0, /* tp_clear */ + 0, /* tp_richcompare */ + 0, /* tp_weaklistoffset */ + PyObject_SelfIter, /* tp_iter */ + (iternextfunc)compress_next, /* tp_iternext */ + 0, /* tp_methods */ + 0, /* tp_members */ + 0, /* tp_getset */ + 0, /* tp_base */ + 0, /* tp_dict */ + 0, /* tp_descr_get */ + 0, /* tp_descr_set */ + 0, /* tp_dictoffset */ + 0, /* tp_init */ + 0, /* tp_alloc */ + compress_new, /* tp_new */ + PyObject_GC_Del, /* tp_free */ }; /* filterfalse object ************************************************************/ typedef struct { - PyObject_HEAD - PyObject *func; - PyObject *it; + PyObject_HEAD + PyObject *func; + PyObject *it; } filterfalseobject; static PyTypeObject filterfalse_type; @@ -2751,83 +2751,83 @@ static PyObject * filterfalse_new(PyTypeObject *type, PyObject *args, PyObject *kwds) { - PyObject *func, *seq; - PyObject *it; - filterfalseobject *lz; - - if (type == &filterfalse_type && - !_PyArg_NoKeywords("filterfalse()", kwds)) - return NULL; - - if (!PyArg_UnpackTuple(args, "filterfalse", 2, 2, &func, &seq)) - return NULL; - - /* Get iterator. */ - it = PyObject_GetIter(seq); - if (it == NULL) - return NULL; - - /* create filterfalseobject structure */ - lz = (filterfalseobject *)type->tp_alloc(type, 0); - if (lz == NULL) { - Py_DECREF(it); - return NULL; - } - Py_INCREF(func); - lz->func = func; - lz->it = it; + PyObject *func, *seq; + PyObject *it; + filterfalseobject *lz; + + if (type == &filterfalse_type && + !_PyArg_NoKeywords("filterfalse()", kwds)) + return NULL; + + if (!PyArg_UnpackTuple(args, "filterfalse", 2, 2, &func, &seq)) + return NULL; + + /* Get iterator. */ + it = PyObject_GetIter(seq); + if (it == NULL) + return NULL; + + /* create filterfalseobject structure */ + lz = (filterfalseobject *)type->tp_alloc(type, 0); + if (lz == NULL) { + Py_DECREF(it); + return NULL; + } + Py_INCREF(func); + lz->func = func; + lz->it = it; - return (PyObject *)lz; + return (PyObject *)lz; } static void filterfalse_dealloc(filterfalseobject *lz) { - PyObject_GC_UnTrack(lz); - Py_XDECREF(lz->func); - Py_XDECREF(lz->it); - Py_TYPE(lz)->tp_free(lz); + PyObject_GC_UnTrack(lz); + Py_XDECREF(lz->func); + Py_XDECREF(lz->it); + Py_TYPE(lz)->tp_free(lz); } static int filterfalse_traverse(filterfalseobject *lz, visitproc visit, void *arg) { - Py_VISIT(lz->it); - Py_VISIT(lz->func); - return 0; + Py_VISIT(lz->it); + Py_VISIT(lz->func); + return 0; } static PyObject * filterfalse_next(filterfalseobject *lz) { - PyObject *item; - PyObject *it = lz->it; - long ok; - PyObject *(*iternext)(PyObject *); - - iternext = *Py_TYPE(it)->tp_iternext; - for (;;) { - item = iternext(it); - if (item == NULL) - return NULL; - - if (lz->func == Py_None || lz->func == (PyObject *)&PyBool_Type) { - ok = PyObject_IsTrue(item); - } else { - PyObject *good; - good = PyObject_CallFunctionObjArgs(lz->func, - item, NULL); - if (good == NULL) { - Py_DECREF(item); - return NULL; - } - ok = PyObject_IsTrue(good); - Py_DECREF(good); - } - if (!ok) - return item; - Py_DECREF(item); - } + PyObject *item; + PyObject *it = lz->it; + long ok; + PyObject *(*iternext)(PyObject *); + + iternext = *Py_TYPE(it)->tp_iternext; + for (;;) { + item = iternext(it); + if (item == NULL) + return NULL; + + if (lz->func == Py_None || lz->func == (PyObject *)&PyBool_Type) { + ok = PyObject_IsTrue(item); + } else { + PyObject *good; + good = PyObject_CallFunctionObjArgs(lz->func, + item, NULL); + if (good == NULL) { + Py_DECREF(item); + return NULL; + } + ok = PyObject_IsTrue(good); + Py_DECREF(good); + } + if (!ok) + return item; + Py_DECREF(item); + } } PyDoc_STRVAR(filterfalse_doc, @@ -2837,74 +2837,74 @@ If function is None, return the items that are false."); static PyTypeObject filterfalse_type = { - PyVarObject_HEAD_INIT(NULL, 0) - "itertools.filterfalse", /* tp_name */ - sizeof(filterfalseobject), /* tp_basicsize */ - 0, /* tp_itemsize */ - /* methods */ - (destructor)filterfalse_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 | - Py_TPFLAGS_BASETYPE, /* tp_flags */ - filterfalse_doc, /* tp_doc */ - (traverseproc)filterfalse_traverse, /* tp_traverse */ - 0, /* tp_clear */ - 0, /* tp_richcompare */ - 0, /* tp_weaklistoffset */ - PyObject_SelfIter, /* tp_iter */ - (iternextfunc)filterfalse_next, /* tp_iternext */ - 0, /* tp_methods */ - 0, /* tp_members */ - 0, /* tp_getset */ - 0, /* tp_base */ - 0, /* tp_dict */ - 0, /* tp_descr_get */ - 0, /* tp_descr_set */ - 0, /* tp_dictoffset */ - 0, /* tp_init */ - 0, /* tp_alloc */ - filterfalse_new, /* tp_new */ - PyObject_GC_Del, /* tp_free */ + PyVarObject_HEAD_INIT(NULL, 0) + "itertools.filterfalse", /* tp_name */ + sizeof(filterfalseobject), /* tp_basicsize */ + 0, /* tp_itemsize */ + /* methods */ + (destructor)filterfalse_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 | + Py_TPFLAGS_BASETYPE, /* tp_flags */ + filterfalse_doc, /* tp_doc */ + (traverseproc)filterfalse_traverse, /* tp_traverse */ + 0, /* tp_clear */ + 0, /* tp_richcompare */ + 0, /* tp_weaklistoffset */ + PyObject_SelfIter, /* tp_iter */ + (iternextfunc)filterfalse_next, /* tp_iternext */ + 0, /* tp_methods */ + 0, /* tp_members */ + 0, /* tp_getset */ + 0, /* tp_base */ + 0, /* tp_dict */ + 0, /* tp_descr_get */ + 0, /* tp_descr_set */ + 0, /* tp_dictoffset */ + 0, /* tp_init */ + 0, /* tp_alloc */ + filterfalse_new, /* tp_new */ + PyObject_GC_Del, /* tp_free */ }; /* count object ************************************************************/ typedef struct { - PyObject_HEAD - Py_ssize_t cnt; - PyObject *long_cnt; - PyObject *long_step; + PyObject_HEAD + Py_ssize_t cnt; + PyObject *long_cnt; + PyObject *long_step; } countobject; /* Counting logic and invariants: fast_mode: when cnt an integer < PY_SSIZE_T_MAX and no step is specified. - assert(cnt != PY_SSIZE_T_MAX && long_cnt == NULL && long_step==PyInt(1)); - Advances with: cnt += 1 - When count hits Y_SSIZE_T_MAX, switch to slow_mode. + assert(cnt != PY_SSIZE_T_MAX && long_cnt == NULL && long_step==PyInt(1)); + Advances with: cnt += 1 + When count hits Y_SSIZE_T_MAX, switch to slow_mode. slow_mode: when cnt == PY_SSIZE_T_MAX, step is not int(1), or cnt is a float. - assert(cnt == PY_SSIZE_T_MAX && long_cnt != NULL && long_step != NULL); - All counting is done with python objects (no overflows or underflows). - Advances with: long_cnt += long_step - Step may be zero -- effectively a slow version of repeat(cnt). - Either long_cnt or long_step may be a float, Fraction, or Decimal. + assert(cnt == PY_SSIZE_T_MAX && long_cnt != NULL && long_step != NULL); + All counting is done with python objects (no overflows or underflows). + Advances with: long_cnt += long_step + Step may be zero -- effectively a slow version of repeat(cnt). + Either long_cnt or long_step may be a float, Fraction, or Decimal. */ static PyTypeObject count_type; @@ -2912,221 +2912,221 @@ static PyObject * count_new(PyTypeObject *type, PyObject *args, PyObject *kwds) { - countobject *lz; - int slow_mode = 0; - Py_ssize_t cnt = 0; - PyObject *long_cnt = NULL; - PyObject *long_step = NULL; - static char *kwlist[] = {"start", "step", 0}; - - if (!PyArg_ParseTupleAndKeywords(args, kwds, "|OO:count", - kwlist, &long_cnt, &long_step)) - return NULL; - - if ((long_cnt != NULL && !PyNumber_Check(long_cnt)) || - (long_step != NULL && !PyNumber_Check(long_step))) { - PyErr_SetString(PyExc_TypeError, "a number is required"); - return NULL; - } - - if (long_cnt != NULL) { - cnt = PyLong_AsSsize_t(long_cnt); - if ((cnt == -1 && PyErr_Occurred()) || !PyLong_Check(long_cnt)) { - PyErr_Clear(); - slow_mode = 1; - } - Py_INCREF(long_cnt); - } else { - cnt = 0; - long_cnt = PyLong_FromLong(0); - } - - /* If not specified, step defaults to 1 */ - if (long_step == NULL) { - long_step = PyLong_FromLong(1); - if (long_step == NULL) { - Py_DECREF(long_cnt); - return NULL; - } - } else - Py_INCREF(long_step); - - assert(long_cnt != NULL && long_step != NULL); - - /* Fast mode only works when the step is 1 */ - if (!PyLong_Check(long_step) || - PyLong_AS_LONG(long_step) != 1) { - slow_mode = 1; - } - - if (slow_mode) - cnt = PY_SSIZE_T_MAX; - else - Py_CLEAR(long_cnt); - - assert((cnt != PY_SSIZE_T_MAX && long_cnt == NULL && !slow_mode) || - (cnt == PY_SSIZE_T_MAX && long_cnt != NULL && slow_mode)); - assert(slow_mode || - (PyLong_Check(long_step) && PyLong_AS_LONG(long_step) == 1)); - - /* create countobject structure */ - lz = (countobject *)type->tp_alloc(type, 0); - if (lz == NULL) { - Py_XDECREF(long_cnt); - return NULL; - } - lz->cnt = cnt; - lz->long_cnt = long_cnt; - lz->long_step = long_step; + countobject *lz; + int slow_mode = 0; + Py_ssize_t cnt = 0; + PyObject *long_cnt = NULL; + PyObject *long_step = NULL; + static char *kwlist[] = {"start", "step", 0}; + + if (!PyArg_ParseTupleAndKeywords(args, kwds, "|OO:count", + kwlist, &long_cnt, &long_step)) + return NULL; + + if ((long_cnt != NULL && !PyNumber_Check(long_cnt)) || + (long_step != NULL && !PyNumber_Check(long_step))) { + PyErr_SetString(PyExc_TypeError, "a number is required"); + return NULL; + } + + if (long_cnt != NULL) { + cnt = PyLong_AsSsize_t(long_cnt); + if ((cnt == -1 && PyErr_Occurred()) || !PyLong_Check(long_cnt)) { + PyErr_Clear(); + slow_mode = 1; + } + Py_INCREF(long_cnt); + } else { + cnt = 0; + long_cnt = PyLong_FromLong(0); + } + + /* If not specified, step defaults to 1 */ + if (long_step == NULL) { + long_step = PyLong_FromLong(1); + if (long_step == NULL) { + Py_DECREF(long_cnt); + return NULL; + } + } else + Py_INCREF(long_step); - return (PyObject *)lz; + assert(long_cnt != NULL && long_step != NULL); + + /* Fast mode only works when the step is 1 */ + if (!PyLong_Check(long_step) || + PyLong_AS_LONG(long_step) != 1) { + slow_mode = 1; + } + + if (slow_mode) + cnt = PY_SSIZE_T_MAX; + else + Py_CLEAR(long_cnt); + + assert((cnt != PY_SSIZE_T_MAX && long_cnt == NULL && !slow_mode) || + (cnt == PY_SSIZE_T_MAX && long_cnt != NULL && slow_mode)); + assert(slow_mode || + (PyLong_Check(long_step) && PyLong_AS_LONG(long_step) == 1)); + + /* create countobject structure */ + lz = (countobject *)type->tp_alloc(type, 0); + if (lz == NULL) { + Py_XDECREF(long_cnt); + return NULL; + } + lz->cnt = cnt; + lz->long_cnt = long_cnt; + lz->long_step = long_step; + + return (PyObject *)lz; } static void count_dealloc(countobject *lz) { - PyObject_GC_UnTrack(lz); - Py_XDECREF(lz->long_cnt); - Py_XDECREF(lz->long_step); - Py_TYPE(lz)->tp_free(lz); + PyObject_GC_UnTrack(lz); + Py_XDECREF(lz->long_cnt); + Py_XDECREF(lz->long_step); + Py_TYPE(lz)->tp_free(lz); } static int count_traverse(countobject *lz, visitproc visit, void *arg) { - Py_VISIT(lz->long_cnt); - Py_VISIT(lz->long_step); - return 0; + Py_VISIT(lz->long_cnt); + Py_VISIT(lz->long_step); + return 0; } static PyObject * count_nextlong(countobject *lz) { - PyObject *long_cnt; - PyObject *stepped_up; + PyObject *long_cnt; + PyObject *stepped_up; - long_cnt = lz->long_cnt; - if (long_cnt == NULL) { - /* Switch to slow_mode */ - long_cnt = PyLong_FromSsize_t(PY_SSIZE_T_MAX); - if (long_cnt == NULL) - return NULL; - } - assert(lz->cnt == PY_SSIZE_T_MAX && long_cnt != NULL); - - stepped_up = PyNumber_Add(long_cnt, lz->long_step); - if (stepped_up == NULL) - return NULL; - lz->long_cnt = stepped_up; - return long_cnt; + long_cnt = lz->long_cnt; + if (long_cnt == NULL) { + /* Switch to slow_mode */ + long_cnt = PyLong_FromSsize_t(PY_SSIZE_T_MAX); + if (long_cnt == NULL) + return NULL; + } + assert(lz->cnt == PY_SSIZE_T_MAX && long_cnt != NULL); + + stepped_up = PyNumber_Add(long_cnt, lz->long_step); + if (stepped_up == NULL) + return NULL; + lz->long_cnt = stepped_up; + return long_cnt; } static PyObject * count_next(countobject *lz) { - if (lz->cnt == PY_SSIZE_T_MAX) - return count_nextlong(lz); - return PyLong_FromSsize_t(lz->cnt++); + if (lz->cnt == PY_SSIZE_T_MAX) + return count_nextlong(lz); + return PyLong_FromSsize_t(lz->cnt++); } static PyObject * count_repr(countobject *lz) { - if (lz->cnt != PY_SSIZE_T_MAX) - return PyUnicode_FromFormat("count(%zd)", lz->cnt); + if (lz->cnt != PY_SSIZE_T_MAX) + return PyUnicode_FromFormat("count(%zd)", lz->cnt); - if (PyLong_Check(lz->long_step)) { - long step = PyLong_AsLong(lz->long_step); - if (step == -1 && PyErr_Occurred()) { - PyErr_Clear(); - } - if (step == 1) { - /* Don't display step when it is an integer equal to 1 */ - return PyUnicode_FromFormat("count(%R)", lz->long_cnt); - } - } - return PyUnicode_FromFormat("count(%R, %R)", - lz->long_cnt, lz->long_step); + if (PyLong_Check(lz->long_step)) { + long step = PyLong_AsLong(lz->long_step); + if (step == -1 && PyErr_Occurred()) { + PyErr_Clear(); + } + if (step == 1) { + /* Don't display step when it is an integer equal to 1 */ + return PyUnicode_FromFormat("count(%R)", lz->long_cnt); + } + } + return PyUnicode_FromFormat("count(%R, %R)", + lz->long_cnt, lz->long_step); } static PyObject * count_reduce(countobject *lz) { - if (lz->cnt == PY_SSIZE_T_MAX) - return Py_BuildValue("O(OO)", Py_TYPE(lz), lz->long_cnt, lz->long_step); - return Py_BuildValue("O(n)", Py_TYPE(lz), lz->cnt); + if (lz->cnt == PY_SSIZE_T_MAX) + return Py_BuildValue("O(OO)", Py_TYPE(lz), lz->long_cnt, lz->long_step); + return Py_BuildValue("O(n)", Py_TYPE(lz), lz->cnt); } PyDoc_STRVAR(count_reduce_doc, "Return state information for pickling."); static PyMethodDef count_methods[] = { - {"__reduce__", (PyCFunction)count_reduce, METH_NOARGS, - count_reduce_doc}, - {NULL, NULL} /* sentinel */ + {"__reduce__", (PyCFunction)count_reduce, METH_NOARGS, + count_reduce_doc}, + {NULL, NULL} /* sentinel */ }; PyDoc_STRVAR(count_doc, - "count(start=0, step=1]) --> count object\n\ + "count(start=0, step=1]) --> count object\n\ \n\ Return a count object whose .__next__() method returns consecutive values.\n\ Equivalent to:\n\n\ def count(firstval=0, step=1):\n\ - x = firstval\n\ - while 1:\n\ - yield x\n\ - x += step\n"); + x = firstval\n\ + while 1:\n\ + yield x\n\ + x += step\n"); static PyTypeObject count_type = { - PyVarObject_HEAD_INIT(NULL, 0) - "itertools.count", /* tp_name */ - sizeof(countobject), /* tp_basicsize */ - 0, /* tp_itemsize */ - /* methods */ - (destructor)count_dealloc, /* tp_dealloc */ - 0, /* tp_print */ - 0, /* tp_getattr */ - 0, /* tp_setattr */ - 0, /* tp_reserved */ - (reprfunc)count_repr, /* 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 | - Py_TPFLAGS_BASETYPE, /* tp_flags */ - count_doc, /* tp_doc */ - (traverseproc)count_traverse, /* tp_traverse */ - 0, /* tp_clear */ - 0, /* tp_richcompare */ - 0, /* tp_weaklistoffset */ - PyObject_SelfIter, /* tp_iter */ - (iternextfunc)count_next, /* tp_iternext */ - count_methods, /* tp_methods */ - 0, /* tp_members */ - 0, /* tp_getset */ - 0, /* tp_base */ - 0, /* tp_dict */ - 0, /* tp_descr_get */ - 0, /* tp_descr_set */ - 0, /* tp_dictoffset */ - 0, /* tp_init */ - 0, /* tp_alloc */ - count_new, /* tp_new */ - PyObject_GC_Del, /* tp_free */ + PyVarObject_HEAD_INIT(NULL, 0) + "itertools.count", /* tp_name */ + sizeof(countobject), /* tp_basicsize */ + 0, /* tp_itemsize */ + /* methods */ + (destructor)count_dealloc, /* tp_dealloc */ + 0, /* tp_print */ + 0, /* tp_getattr */ + 0, /* tp_setattr */ + 0, /* tp_reserved */ + (reprfunc)count_repr, /* 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 | + Py_TPFLAGS_BASETYPE, /* tp_flags */ + count_doc, /* tp_doc */ + (traverseproc)count_traverse, /* tp_traverse */ + 0, /* tp_clear */ + 0, /* tp_richcompare */ + 0, /* tp_weaklistoffset */ + PyObject_SelfIter, /* tp_iter */ + (iternextfunc)count_next, /* tp_iternext */ + count_methods, /* tp_methods */ + 0, /* tp_members */ + 0, /* tp_getset */ + 0, /* tp_base */ + 0, /* tp_dict */ + 0, /* tp_descr_get */ + 0, /* tp_descr_set */ + 0, /* tp_dictoffset */ + 0, /* tp_init */ + 0, /* tp_alloc */ + count_new, /* tp_new */ + PyObject_GC_Del, /* tp_free */ }; /* repeat object ************************************************************/ typedef struct { - PyObject_HEAD - PyObject *element; - Py_ssize_t cnt; + PyObject_HEAD + PyObject *element; + Py_ssize_t cnt; } repeatobject; static PyTypeObject repeat_type; @@ -3134,77 +3134,77 @@ static PyObject * repeat_new(PyTypeObject *type, PyObject *args, PyObject *kwds) { - repeatobject *ro; - PyObject *element; - Py_ssize_t cnt = -1; - static char *kwargs[] = {"object", "times", NULL}; - - if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|n:repeat", kwargs, - &element, &cnt)) - return NULL; - - if (PyTuple_Size(args) == 2 && cnt < 0) - cnt = 0; - - ro = (repeatobject *)type->tp_alloc(type, 0); - if (ro == NULL) - return NULL; - Py_INCREF(element); - ro->element = element; - ro->cnt = cnt; - return (PyObject *)ro; + repeatobject *ro; + PyObject *element; + Py_ssize_t cnt = -1; + static char *kwargs[] = {"object", "times", NULL}; + + if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|n:repeat", kwargs, + &element, &cnt)) + return NULL; + + if (PyTuple_Size(args) == 2 && cnt < 0) + cnt = 0; + + ro = (repeatobject *)type->tp_alloc(type, 0); + if (ro == NULL) + return NULL; + Py_INCREF(element); + ro->element = element; + ro->cnt = cnt; + return (PyObject *)ro; } static void repeat_dealloc(repeatobject *ro) { - PyObject_GC_UnTrack(ro); - Py_XDECREF(ro->element); - Py_TYPE(ro)->tp_free(ro); + PyObject_GC_UnTrack(ro); + Py_XDECREF(ro->element); + Py_TYPE(ro)->tp_free(ro); } static int repeat_traverse(repeatobject *ro, visitproc visit, void *arg) { - Py_VISIT(ro->element); - return 0; + Py_VISIT(ro->element); + return 0; } static PyObject * repeat_next(repeatobject *ro) { - if (ro->cnt == 0) - return NULL; - if (ro->cnt > 0) - ro->cnt--; - Py_INCREF(ro->element); - return ro->element; + if (ro->cnt == 0) + return NULL; + if (ro->cnt > 0) + ro->cnt--; + Py_INCREF(ro->element); + return ro->element; } static PyObject * repeat_repr(repeatobject *ro) { - if (ro->cnt == -1) - return PyUnicode_FromFormat("repeat(%R)", ro->element); - else - return PyUnicode_FromFormat("repeat(%R, %zd)", ro->element, ro->cnt); -} + if (ro->cnt == -1) + return PyUnicode_FromFormat("repeat(%R)", ro->element); + else + return PyUnicode_FromFormat("repeat(%R, %zd)", ro->element, ro->cnt); +} static PyObject * repeat_len(repeatobject *ro) { - if (ro->cnt == -1) { - PyErr_SetString(PyExc_TypeError, "len() of unsized object"); - return NULL; - } - return PyLong_FromSize_t(ro->cnt); + if (ro->cnt == -1) { + PyErr_SetString(PyExc_TypeError, "len() of unsized object"); + return NULL; + } + return PyLong_FromSize_t(ro->cnt); } PyDoc_STRVAR(length_hint_doc, "Private method returning an estimate of len(list(it))."); static PyMethodDef repeat_methods[] = { - {"__length_hint__", (PyCFunction)repeat_len, METH_NOARGS, length_hint_doc}, - {NULL, NULL} /* sentinel */ + {"__length_hint__", (PyCFunction)repeat_len, METH_NOARGS, length_hint_doc}, + {NULL, NULL} /* sentinel */ }; PyDoc_STRVAR(repeat_doc, @@ -3213,47 +3213,47 @@ endlessly."); static PyTypeObject repeat_type = { - PyVarObject_HEAD_INIT(NULL, 0) - "itertools.repeat", /* tp_name */ - sizeof(repeatobject), /* tp_basicsize */ - 0, /* tp_itemsize */ - /* methods */ - (destructor)repeat_dealloc, /* tp_dealloc */ - 0, /* tp_print */ - 0, /* tp_getattr */ - 0, /* tp_setattr */ - 0, /* tp_reserved */ - (reprfunc)repeat_repr, /* 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 | - Py_TPFLAGS_BASETYPE, /* tp_flags */ - repeat_doc, /* tp_doc */ - (traverseproc)repeat_traverse, /* tp_traverse */ - 0, /* tp_clear */ - 0, /* tp_richcompare */ - 0, /* tp_weaklistoffset */ - PyObject_SelfIter, /* tp_iter */ - (iternextfunc)repeat_next, /* tp_iternext */ - repeat_methods, /* tp_methods */ - 0, /* tp_members */ - 0, /* tp_getset */ - 0, /* tp_base */ - 0, /* tp_dict */ - 0, /* tp_descr_get */ - 0, /* tp_descr_set */ - 0, /* tp_dictoffset */ - 0, /* tp_init */ - 0, /* tp_alloc */ - repeat_new, /* tp_new */ - PyObject_GC_Del, /* tp_free */ + PyVarObject_HEAD_INIT(NULL, 0) + "itertools.repeat", /* tp_name */ + sizeof(repeatobject), /* tp_basicsize */ + 0, /* tp_itemsize */ + /* methods */ + (destructor)repeat_dealloc, /* tp_dealloc */ + 0, /* tp_print */ + 0, /* tp_getattr */ + 0, /* tp_setattr */ + 0, /* tp_reserved */ + (reprfunc)repeat_repr, /* 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 | + Py_TPFLAGS_BASETYPE, /* tp_flags */ + repeat_doc, /* tp_doc */ + (traverseproc)repeat_traverse, /* tp_traverse */ + 0, /* tp_clear */ + 0, /* tp_richcompare */ + 0, /* tp_weaklistoffset */ + PyObject_SelfIter, /* tp_iter */ + (iternextfunc)repeat_next, /* tp_iternext */ + repeat_methods, /* tp_methods */ + 0, /* tp_members */ + 0, /* tp_getset */ + 0, /* tp_base */ + 0, /* tp_dict */ + 0, /* tp_descr_get */ + 0, /* tp_descr_set */ + 0, /* tp_dictoffset */ + 0, /* tp_init */ + 0, /* tp_alloc */ + repeat_new, /* tp_new */ + PyObject_GC_Del, /* tp_free */ }; /* ziplongest object ************************************************************/ @@ -3261,12 +3261,12 @@ #include "Python.h" typedef struct { - PyObject_HEAD - Py_ssize_t tuplesize; - Py_ssize_t numactive; - PyObject *ittuple; /* tuple of iterators */ - PyObject *result; - PyObject *fillvalue; + PyObject_HEAD + Py_ssize_t tuplesize; + Py_ssize_t numactive; + PyObject *ittuple; /* tuple of iterators */ + PyObject *result; + PyObject *fillvalue; } ziplongestobject; static PyTypeObject ziplongest_type; @@ -3274,159 +3274,159 @@ static PyObject * zip_longest_new(PyTypeObject *type, PyObject *args, PyObject *kwds) { - ziplongestobject *lz; - Py_ssize_t i; - PyObject *ittuple; /* tuple of iterators */ - PyObject *result; - PyObject *fillvalue = Py_None; - Py_ssize_t tuplesize = PySequence_Length(args); - - if (kwds != NULL && PyDict_CheckExact(kwds) && PyDict_Size(kwds) > 0) { - fillvalue = PyDict_GetItemString(kwds, "fillvalue"); - if (fillvalue == NULL || PyDict_Size(kwds) > 1) { - PyErr_SetString(PyExc_TypeError, - "zip_longest() got an unexpected keyword argument"); - return NULL; - } + ziplongestobject *lz; + Py_ssize_t i; + PyObject *ittuple; /* tuple of iterators */ + PyObject *result; + PyObject *fillvalue = Py_None; + Py_ssize_t tuplesize = PySequence_Length(args); + + if (kwds != NULL && PyDict_CheckExact(kwds) && PyDict_Size(kwds) > 0) { + fillvalue = PyDict_GetItemString(kwds, "fillvalue"); + if (fillvalue == NULL || PyDict_Size(kwds) > 1) { + PyErr_SetString(PyExc_TypeError, + "zip_longest() got an unexpected keyword argument"); + return NULL; } + } + + /* args must be a tuple */ + assert(PyTuple_Check(args)); - /* args must be a tuple */ - assert(PyTuple_Check(args)); + /* obtain iterators */ + ittuple = PyTuple_New(tuplesize); + if (ittuple == NULL) + return NULL; + for (i=0; i < tuplesize; ++i) { + PyObject *item = PyTuple_GET_ITEM(args, i); + PyObject *it = PyObject_GetIter(item); + if (it == NULL) { + if (PyErr_ExceptionMatches(PyExc_TypeError)) + PyErr_Format(PyExc_TypeError, + "zip_longest argument #%zd must support iteration", + i+1); + Py_DECREF(ittuple); + return NULL; + } + PyTuple_SET_ITEM(ittuple, i, it); + } - /* obtain iterators */ - ittuple = PyTuple_New(tuplesize); - if (ittuple == NULL) - return NULL; - for (i=0; i < tuplesize; ++i) { - PyObject *item = PyTuple_GET_ITEM(args, i); - PyObject *it = PyObject_GetIter(item); - if (it == NULL) { - if (PyErr_ExceptionMatches(PyExc_TypeError)) - PyErr_Format(PyExc_TypeError, - "zip_longest argument #%zd must support iteration", - i+1); - Py_DECREF(ittuple); - return NULL; - } - PyTuple_SET_ITEM(ittuple, i, it); - } - - /* create a result holder */ - result = PyTuple_New(tuplesize); - if (result == NULL) { - Py_DECREF(ittuple); - return NULL; - } - for (i=0 ; i < tuplesize ; i++) { - Py_INCREF(Py_None); - PyTuple_SET_ITEM(result, i, Py_None); - } - - /* create ziplongestobject structure */ - lz = (ziplongestobject *)type->tp_alloc(type, 0); - if (lz == NULL) { - Py_DECREF(ittuple); - Py_DECREF(result); - return NULL; - } - lz->ittuple = ittuple; - lz->tuplesize = tuplesize; - lz->numactive = tuplesize; - lz->result = result; - Py_INCREF(fillvalue); - lz->fillvalue = fillvalue; - return (PyObject *)lz; + /* create a result holder */ + result = PyTuple_New(tuplesize); + if (result == NULL) { + Py_DECREF(ittuple); + return NULL; + } + for (i=0 ; i < tuplesize ; i++) { + Py_INCREF(Py_None); + PyTuple_SET_ITEM(result, i, Py_None); + } + + /* create ziplongestobject structure */ + lz = (ziplongestobject *)type->tp_alloc(type, 0); + if (lz == NULL) { + Py_DECREF(ittuple); + Py_DECREF(result); + return NULL; + } + lz->ittuple = ittuple; + lz->tuplesize = tuplesize; + lz->numactive = tuplesize; + lz->result = result; + Py_INCREF(fillvalue); + lz->fillvalue = fillvalue; + return (PyObject *)lz; } static void zip_longest_dealloc(ziplongestobject *lz) { - PyObject_GC_UnTrack(lz); - Py_XDECREF(lz->ittuple); - Py_XDECREF(lz->result); - Py_XDECREF(lz->fillvalue); - Py_TYPE(lz)->tp_free(lz); + PyObject_GC_UnTrack(lz); + Py_XDECREF(lz->ittuple); + Py_XDECREF(lz->result); + Py_XDECREF(lz->fillvalue); + Py_TYPE(lz)->tp_free(lz); } static int zip_longest_traverse(ziplongestobject *lz, visitproc visit, void *arg) { - Py_VISIT(lz->ittuple); - Py_VISIT(lz->result); - Py_VISIT(lz->fillvalue); - return 0; + Py_VISIT(lz->ittuple); + Py_VISIT(lz->result); + Py_VISIT(lz->fillvalue); + return 0; } static PyObject * zip_longest_next(ziplongestobject *lz) { - Py_ssize_t i; - Py_ssize_t tuplesize = lz->tuplesize; - PyObject *result = lz->result; - PyObject *it; - PyObject *item; - PyObject *olditem; - - if (tuplesize == 0) - return NULL; - if (lz->numactive == 0) - return NULL; - if (Py_REFCNT(result) == 1) { - Py_INCREF(result); - for (i=0 ; i < tuplesize ; i++) { - it = PyTuple_GET_ITEM(lz->ittuple, i); - if (it == NULL) { - Py_INCREF(lz->fillvalue); - item = lz->fillvalue; - } else { - item = PyIter_Next(it); - if (item == NULL) { - lz->numactive -= 1; - if (lz->numactive == 0 || PyErr_Occurred()) { - lz->numactive = 0; - Py_DECREF(result); - return NULL; - } else { - Py_INCREF(lz->fillvalue); - item = lz->fillvalue; - PyTuple_SET_ITEM(lz->ittuple, i, NULL); - Py_DECREF(it); - } - } - } - olditem = PyTuple_GET_ITEM(result, i); - PyTuple_SET_ITEM(result, i, item); - Py_DECREF(olditem); + Py_ssize_t i; + Py_ssize_t tuplesize = lz->tuplesize; + PyObject *result = lz->result; + PyObject *it; + PyObject *item; + PyObject *olditem; + + if (tuplesize == 0) + return NULL; + if (lz->numactive == 0) + return NULL; + if (Py_REFCNT(result) == 1) { + Py_INCREF(result); + for (i=0 ; i < tuplesize ; i++) { + it = PyTuple_GET_ITEM(lz->ittuple, i); + if (it == NULL) { + Py_INCREF(lz->fillvalue); + item = lz->fillvalue; + } else { + item = PyIter_Next(it); + if (item == NULL) { + lz->numactive -= 1; + if (lz->numactive == 0 || PyErr_Occurred()) { + lz->numactive = 0; + Py_DECREF(result); + return NULL; + } else { + Py_INCREF(lz->fillvalue); + item = lz->fillvalue; + PyTuple_SET_ITEM(lz->ittuple, i, NULL); + Py_DECREF(it); + } } - } else { - result = PyTuple_New(tuplesize); - if (result == NULL) + } + olditem = PyTuple_GET_ITEM(result, i); + PyTuple_SET_ITEM(result, i, item); + Py_DECREF(olditem); + } + } else { + result = PyTuple_New(tuplesize); + if (result == NULL) + return NULL; + for (i=0 ; i < tuplesize ; i++) { + it = PyTuple_GET_ITEM(lz->ittuple, i); + if (it == NULL) { + Py_INCREF(lz->fillvalue); + item = lz->fillvalue; + } else { + item = PyIter_Next(it); + if (item == NULL) { + lz->numactive -= 1; + if (lz->numactive == 0 || PyErr_Occurred()) { + lz->numactive = 0; + Py_DECREF(result); return NULL; - for (i=0 ; i < tuplesize ; i++) { - it = PyTuple_GET_ITEM(lz->ittuple, i); - if (it == NULL) { - Py_INCREF(lz->fillvalue); - item = lz->fillvalue; - } else { - item = PyIter_Next(it); - if (item == NULL) { - lz->numactive -= 1; - if (lz->numactive == 0 || PyErr_Occurred()) { - lz->numactive = 0; - Py_DECREF(result); - return NULL; - } else { - Py_INCREF(lz->fillvalue); - item = lz->fillvalue; - PyTuple_SET_ITEM(lz->ittuple, i, NULL); - Py_DECREF(it); - } - } - } - PyTuple_SET_ITEM(result, i, item); + } else { + Py_INCREF(lz->fillvalue); + item = lz->fillvalue; + PyTuple_SET_ITEM(lz->ittuple, i, NULL); + Py_DECREF(it); + } } + } + PyTuple_SET_ITEM(result, i, item); } - return result; + } + return result; } PyDoc_STRVAR(zip_longest_doc, @@ -3441,47 +3441,47 @@ "); static PyTypeObject ziplongest_type = { - PyVarObject_HEAD_INIT(NULL, 0) - "itertools.zip_longest", /* tp_name */ - sizeof(ziplongestobject), /* tp_basicsize */ - 0, /* tp_itemsize */ - /* methods */ - (destructor)zip_longest_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 | - Py_TPFLAGS_BASETYPE, /* tp_flags */ - zip_longest_doc, /* tp_doc */ - (traverseproc)zip_longest_traverse, /* tp_traverse */ - 0, /* tp_clear */ - 0, /* tp_richcompare */ - 0, /* tp_weaklistoffset */ - PyObject_SelfIter, /* tp_iter */ - (iternextfunc)zip_longest_next, /* tp_iternext */ - 0, /* tp_methods */ - 0, /* tp_members */ - 0, /* tp_getset */ - 0, /* tp_base */ - 0, /* tp_dict */ - 0, /* tp_descr_get */ - 0, /* tp_descr_set */ - 0, /* tp_dictoffset */ - 0, /* tp_init */ - 0, /* tp_alloc */ - zip_longest_new, /* tp_new */ - PyObject_GC_Del, /* tp_free */ + PyVarObject_HEAD_INIT(NULL, 0) + "itertools.zip_longest", /* tp_name */ + sizeof(ziplongestobject), /* tp_basicsize */ + 0, /* tp_itemsize */ + /* methods */ + (destructor)zip_longest_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 | + Py_TPFLAGS_BASETYPE, /* tp_flags */ + zip_longest_doc, /* tp_doc */ + (traverseproc)zip_longest_traverse, /* tp_traverse */ + 0, /* tp_clear */ + 0, /* tp_richcompare */ + 0, /* tp_weaklistoffset */ + PyObject_SelfIter, /* tp_iter */ + (iternextfunc)zip_longest_next, /* tp_iternext */ + 0, /* tp_methods */ + 0, /* tp_members */ + 0, /* tp_getset */ + 0, /* tp_base */ + 0, /* tp_dict */ + 0, /* tp_descr_get */ + 0, /* tp_descr_set */ + 0, /* tp_dictoffset */ + 0, /* tp_init */ + 0, /* tp_alloc */ + zip_longest_new, /* tp_new */ + PyObject_GC_Del, /* tp_free */ }; /* module level code ********************************************************/ @@ -3516,68 +3516,68 @@ static PyMethodDef module_methods[] = { - {"tee", (PyCFunction)tee, METH_VARARGS, tee_doc}, - {NULL, NULL} /* sentinel */ + {"tee", (PyCFunction)tee, METH_VARARGS, tee_doc}, + {NULL, NULL} /* sentinel */ }; static struct PyModuleDef itertoolsmodule = { - PyModuleDef_HEAD_INIT, - "itertools", - module_doc, - -1, - module_methods, - NULL, - NULL, - NULL, - NULL + PyModuleDef_HEAD_INIT, + "itertools", + module_doc, + -1, + module_methods, + NULL, + NULL, + NULL, + NULL }; PyMODINIT_FUNC PyInit_itertools(void) { - int i; - PyObject *m; - char *name; - PyTypeObject *typelist[] = { - &combinations_type, - &cwr_type, - &cycle_type, - &dropwhile_type, - &takewhile_type, - &islice_type, - &starmap_type, - &chain_type, - &compress_type, - &filterfalse_type, - &count_type, - &ziplongest_type, - &permutations_type, - &product_type, - &repeat_type, - &groupby_type, - NULL - }; - - Py_TYPE(&teedataobject_type) = &PyType_Type; - m = PyModule_Create(&itertoolsmodule); - if (m == NULL) - return NULL; - - for (i=0 ; typelist[i] != NULL ; i++) { - if (PyType_Ready(typelist[i]) < 0) - return NULL; - name = strchr(typelist[i]->tp_name, '.'); - assert (name != NULL); - Py_INCREF(typelist[i]); - PyModule_AddObject(m, name+1, (PyObject *)typelist[i]); - } - - if (PyType_Ready(&teedataobject_type) < 0) - return NULL; - if (PyType_Ready(&tee_type) < 0) - return NULL; - if (PyType_Ready(&_grouper_type) < 0) - return NULL; - return m; + int i; + PyObject *m; + char *name; + PyTypeObject *typelist[] = { + &combinations_type, + &cwr_type, + &cycle_type, + &dropwhile_type, + &takewhile_type, + &islice_type, + &starmap_type, + &chain_type, + &compress_type, + &filterfalse_type, + &count_type, + &ziplongest_type, + &permutations_type, + &product_type, + &repeat_type, + &groupby_type, + NULL + }; + + Py_TYPE(&teedataobject_type) = &PyType_Type; + m = PyModule_Create(&itertoolsmodule); + if (m == NULL) + return NULL; + + for (i=0 ; typelist[i] != NULL ; i++) { + if (PyType_Ready(typelist[i]) < 0) + return NULL; + name = strchr(typelist[i]->tp_name, '.'); + assert (name != NULL); + Py_INCREF(typelist[i]); + PyModule_AddObject(m, name+1, (PyObject *)typelist[i]); + } + + if (PyType_Ready(&teedataobject_type) < 0) + return NULL; + if (PyType_Ready(&tee_type) < 0) + return NULL; + if (PyType_Ready(&_grouper_type) < 0) + return NULL; + return m; } Modified: python/branches/py3k-jit/Modules/main.c ============================================================================== --- python/branches/py3k-jit/Modules/main.c (original) +++ python/branches/py3k-jit/Modules/main.c Mon May 10 23:55:43 2010 @@ -105,20 +105,20 @@ static FILE* _wfopen(const wchar_t *path, const wchar_t *mode) { - char cpath[PATH_MAX]; - char cmode[10]; - size_t r; - r = wcstombs(cpath, path, PATH_MAX); - if (r == (size_t)-1 || r >= PATH_MAX) { - errno = EINVAL; - return NULL; - } - r = wcstombs(cmode, mode, 10); - if (r == (size_t)-1 || r >= 10) { - errno = EINVAL; - return NULL; - } - return fopen(cpath, cmode); + char cpath[PATH_MAX]; + char cmode[10]; + size_t r; + r = wcstombs(cpath, path, PATH_MAX); + if (r == (size_t)-1 || r >= PATH_MAX) { + errno = EINVAL; + return NULL; + } + r = wcstombs(cmode, mode, 10); + if (r == (size_t)-1 || r >= 10) { + errno = EINVAL; + return NULL; + } + return fopen(cpath, cmode); } #endif @@ -126,131 +126,131 @@ static int usage(int exitcode, wchar_t* program) { - FILE *f = exitcode ? stderr : stdout; + FILE *f = exitcode ? stderr : stdout; - fprintf(f, usage_line, program); - if (exitcode) - fprintf(f, "Try `python -h' for more information.\n"); - else { - fputs(usage_1, f); - fputs(usage_2, f); - fputs(usage_3, f); - fprintf(f, usage_4, DELIM); - fprintf(f, usage_5, DELIM, PYTHONHOMEHELP); - } + fprintf(f, usage_line, program); + if (exitcode) + fprintf(f, "Try `python -h' for more information.\n"); + else { + fputs(usage_1, f); + fputs(usage_2, f); + fputs(usage_3, f); + fprintf(f, usage_4, DELIM); + fprintf(f, usage_5, DELIM, PYTHONHOMEHELP); + } #if defined(__VMS) - if (exitcode == 0) { - /* suppress 'error' message */ - return 1; - } - else { - /* STS$M_INHIB_MSG + SS$_ABORT */ - return 0x1000002c; - } + if (exitcode == 0) { + /* suppress 'error' message */ + return 1; + } + else { + /* STS$M_INHIB_MSG + SS$_ABORT */ + return 0x1000002c; + } #else - return exitcode; + return exitcode; #endif - /*NOTREACHED*/ + /*NOTREACHED*/ } static void RunStartupFile(PyCompilerFlags *cf) { - char *startup = Py_GETENV("PYTHONSTARTUP"); - if (startup != NULL && startup[0] != '\0') { - FILE *fp = fopen(startup, "r"); - if (fp != NULL) { - (void) PyRun_SimpleFileExFlags(fp, startup, 0, cf); - PyErr_Clear(); - fclose(fp); - } else { - int save_errno; - - save_errno = errno; - PySys_WriteStderr("Could not open PYTHONSTARTUP\n"); - errno = save_errno; - PyErr_SetFromErrnoWithFilename(PyExc_IOError, - startup); - PyErr_Print(); - PyErr_Clear(); - } - } + char *startup = Py_GETENV("PYTHONSTARTUP"); + if (startup != NULL && startup[0] != '\0') { + FILE *fp = fopen(startup, "r"); + if (fp != NULL) { + (void) PyRun_SimpleFileExFlags(fp, startup, 0, cf); + PyErr_Clear(); + fclose(fp); + } else { + int save_errno; + + save_errno = errno; + PySys_WriteStderr("Could not open PYTHONSTARTUP\n"); + errno = save_errno; + PyErr_SetFromErrnoWithFilename(PyExc_IOError, + startup); + PyErr_Print(); + PyErr_Clear(); + } + } } static int RunModule(wchar_t *modname, int set_argv0) { - PyObject *module, *runpy, *runmodule, *runargs, *result; - runpy = PyImport_ImportModule("runpy"); - if (runpy == NULL) { - fprintf(stderr, "Could not import runpy module\n"); - return -1; - } - runmodule = PyObject_GetAttrString(runpy, "_run_module_as_main"); - if (runmodule == NULL) { - fprintf(stderr, "Could not access runpy._run_module_as_main\n"); - Py_DECREF(runpy); - return -1; - } - module = PyUnicode_FromWideChar(modname, wcslen(modname)); - if (module == NULL) { - fprintf(stderr, "Could not convert module name to unicode\n"); - Py_DECREF(runpy); - Py_DECREF(runmodule); - return -1; - } - runargs = Py_BuildValue("(Oi)", module, set_argv0); - if (runargs == NULL) { - fprintf(stderr, - "Could not create arguments for runpy._run_module_as_main\n"); - Py_DECREF(runpy); - Py_DECREF(runmodule); - Py_DECREF(module); - return -1; - } - result = PyObject_Call(runmodule, runargs, NULL); - if (result == NULL) { - PyErr_Print(); - } - Py_DECREF(runpy); - Py_DECREF(runmodule); - Py_DECREF(module); - Py_DECREF(runargs); - if (result == NULL) { - return -1; - } - Py_DECREF(result); - return 0; + PyObject *module, *runpy, *runmodule, *runargs, *result; + runpy = PyImport_ImportModule("runpy"); + if (runpy == NULL) { + fprintf(stderr, "Could not import runpy module\n"); + return -1; + } + runmodule = PyObject_GetAttrString(runpy, "_run_module_as_main"); + if (runmodule == NULL) { + fprintf(stderr, "Could not access runpy._run_module_as_main\n"); + Py_DECREF(runpy); + return -1; + } + module = PyUnicode_FromWideChar(modname, wcslen(modname)); + if (module == NULL) { + fprintf(stderr, "Could not convert module name to unicode\n"); + Py_DECREF(runpy); + Py_DECREF(runmodule); + return -1; + } + runargs = Py_BuildValue("(Oi)", module, set_argv0); + if (runargs == NULL) { + fprintf(stderr, + "Could not create arguments for runpy._run_module_as_main\n"); + Py_DECREF(runpy); + Py_DECREF(runmodule); + Py_DECREF(module); + return -1; + } + result = PyObject_Call(runmodule, runargs, NULL); + if (result == NULL) { + PyErr_Print(); + } + Py_DECREF(runpy); + Py_DECREF(runmodule); + Py_DECREF(module); + Py_DECREF(runargs); + if (result == NULL) { + return -1; + } + Py_DECREF(result); + return 0; } static int RunMainFromImporter(wchar_t *filename) { - PyObject *argv0 = NULL, *importer = NULL; + PyObject *argv0 = NULL, *importer = NULL; - if ((argv0 = PyUnicode_FromWideChar(filename,wcslen(filename))) && - (importer = PyImport_GetImporter(argv0)) && - (importer->ob_type != &PyNullImporter_Type)) - { - /* argv0 is usable as an import source, so - put it in sys.path[0] and import __main__ */ - PyObject *sys_path = NULL; - if ((sys_path = PySys_GetObject("path")) && - !PyList_SetItem(sys_path, 0, argv0)) - { - Py_INCREF(argv0); - Py_DECREF(importer); - sys_path = NULL; - return RunModule(L"__main__", 0) != 0; - } - } - Py_XDECREF(argv0); - Py_XDECREF(importer); - if (PyErr_Occurred()) { - PyErr_Print(); - return 1; - } - else { - return -1; - } + if ((argv0 = PyUnicode_FromWideChar(filename,wcslen(filename))) && + (importer = PyImport_GetImporter(argv0)) && + (importer->ob_type != &PyNullImporter_Type)) + { + /* argv0 is usable as an import source, so + put it in sys.path[0] and import __main__ */ + PyObject *sys_path = NULL; + if ((sys_path = PySys_GetObject("path")) && + !PyList_SetItem(sys_path, 0, argv0)) + { + Py_INCREF(argv0); + Py_DECREF(importer); + sys_path = NULL; + return RunModule(L"__main__", 0) != 0; + } + } + Py_XDECREF(argv0); + Py_XDECREF(importer); + if (PyErr_Occurred()) { + PyErr_Print(); + return 1; + } + else { + return -1; + } } @@ -259,437 +259,437 @@ int Py_Main(int argc, wchar_t **argv) { - int c; - int sts; - wchar_t *command = NULL; - wchar_t *filename = NULL; - wchar_t *module = NULL; - FILE *fp = stdin; - char *p; + int c; + int sts; + wchar_t *command = NULL; + wchar_t *filename = NULL; + wchar_t *module = NULL; + FILE *fp = stdin; + char *p; #ifdef MS_WINDOWS - wchar_t *wp; + wchar_t *wp; #endif - int skipfirstline = 0; - int stdin_is_interactive = 0; - int help = 0; - int version = 0; - int saw_unbuffered_flag = 0; - PyCompilerFlags cf; - - cf.cf_flags = 0; - - orig_argc = argc; /* For Py_GetArgcArgv() */ - orig_argv = argv; - - PySys_ResetWarnOptions(); - - while ((c = _PyOS_GetOpt(argc, argv, PROGRAM_OPTS)) != EOF) { - if (c == 'c') { - size_t len; - /* -c is the last option; following arguments - that look like options are left for the - command to interpret. */ - - len = wcslen(_PyOS_optarg) + 1 + 1; - command = (wchar_t *)malloc(sizeof(wchar_t) * len); - if (command == NULL) - Py_FatalError( - "not enough memory to copy -c argument"); - wcscpy(command, _PyOS_optarg); - command[len - 2] = '\n'; - command[len - 1] = 0; - break; - } - - if (c == 'm') { - /* -m is the last option; following arguments - that look like options are left for the - module to interpret. */ - module = _PyOS_optarg; - break; - } - - switch (c) { - case 'b': - Py_BytesWarningFlag++; - break; - - case 'd': - Py_DebugFlag++; - break; - - case 'i': - Py_InspectFlag++; - Py_InteractiveFlag++; - break; - - /* case 'J': reserved for Jython */ - - case 'O': - Py_OptimizeFlag++; - break; - - case 'B': - Py_DontWriteBytecodeFlag++; - break; - - case 's': - Py_NoUserSiteDirectory++; - break; - - case 'S': - Py_NoSiteFlag++; - break; - - case 'E': - Py_IgnoreEnvironmentFlag++; - break; - - case 't': - /* ignored for backwards compatibility */ - break; - - case 'u': - Py_UnbufferedStdioFlag = 1; - saw_unbuffered_flag = 1; - break; - - case 'v': - Py_VerboseFlag++; - break; - - case 'x': - skipfirstline = 1; - break; - - /* case 'X': reserved for implementation-specific arguments */ - - case 'h': - case '?': - help++; - break; - - case 'V': - version++; - break; - - case 'W': - PySys_AddWarnOption(_PyOS_optarg); - break; - - /* This space reserved for other options */ - - default: - return usage(2, argv[0]); - /*NOTREACHED*/ - - } - } - - if (help) - return usage(0, argv[0]); - - if (version) { - fprintf(stderr, "Python %s\n", PY_VERSION); - return 0; - } - - if (!Py_InspectFlag && - (p = Py_GETENV("PYTHONINSPECT")) && *p != '\0') - Py_InspectFlag = 1; - if (!saw_unbuffered_flag && - (p = Py_GETENV("PYTHONUNBUFFERED")) && *p != '\0') - Py_UnbufferedStdioFlag = 1; - - if (!Py_NoUserSiteDirectory && - (p = Py_GETENV("PYTHONNOUSERSITE")) && *p != '\0') - Py_NoUserSiteDirectory = 1; + int skipfirstline = 0; + int stdin_is_interactive = 0; + int help = 0; + int version = 0; + int saw_unbuffered_flag = 0; + PyCompilerFlags cf; + + cf.cf_flags = 0; + + orig_argc = argc; /* For Py_GetArgcArgv() */ + orig_argv = argv; + + PySys_ResetWarnOptions(); + + while ((c = _PyOS_GetOpt(argc, argv, PROGRAM_OPTS)) != EOF) { + if (c == 'c') { + size_t len; + /* -c is the last option; following arguments + that look like options are left for the + command to interpret. */ + + len = wcslen(_PyOS_optarg) + 1 + 1; + command = (wchar_t *)malloc(sizeof(wchar_t) * len); + if (command == NULL) + Py_FatalError( + "not enough memory to copy -c argument"); + wcscpy(command, _PyOS_optarg); + command[len - 2] = '\n'; + command[len - 1] = 0; + break; + } + + if (c == 'm') { + /* -m is the last option; following arguments + that look like options are left for the + module to interpret. */ + module = _PyOS_optarg; + break; + } + + switch (c) { + case 'b': + Py_BytesWarningFlag++; + break; + + case 'd': + Py_DebugFlag++; + break; + + case 'i': + Py_InspectFlag++; + Py_InteractiveFlag++; + break; + + /* case 'J': reserved for Jython */ + + case 'O': + Py_OptimizeFlag++; + break; + + case 'B': + Py_DontWriteBytecodeFlag++; + break; + + case 's': + Py_NoUserSiteDirectory++; + break; + + case 'S': + Py_NoSiteFlag++; + break; + + case 'E': + Py_IgnoreEnvironmentFlag++; + break; + + case 't': + /* ignored for backwards compatibility */ + break; + + case 'u': + Py_UnbufferedStdioFlag = 1; + saw_unbuffered_flag = 1; + break; + + case 'v': + Py_VerboseFlag++; + break; + + case 'x': + skipfirstline = 1; + break; + + /* case 'X': reserved for implementation-specific arguments */ + + case 'h': + case '?': + help++; + break; + + case 'V': + version++; + break; + + case 'W': + PySys_AddWarnOption(_PyOS_optarg); + break; + + /* This space reserved for other options */ + + default: + return usage(2, argv[0]); + /*NOTREACHED*/ + + } + } + + if (help) + return usage(0, argv[0]); + + if (version) { + fprintf(stderr, "Python %s\n", PY_VERSION); + return 0; + } + + if (!Py_InspectFlag && + (p = Py_GETENV("PYTHONINSPECT")) && *p != '\0') + Py_InspectFlag = 1; + if (!saw_unbuffered_flag && + (p = Py_GETENV("PYTHONUNBUFFERED")) && *p != '\0') + Py_UnbufferedStdioFlag = 1; + + if (!Py_NoUserSiteDirectory && + (p = Py_GETENV("PYTHONNOUSERSITE")) && *p != '\0') + Py_NoUserSiteDirectory = 1; #ifdef MS_WINDOWS - if (!Py_IgnoreEnvironmentFlag && (wp = _wgetenv(L"PYTHONWARNINGS")) && - *wp != L'\0') { - wchar_t *buf, *warning; - - buf = (wchar_t *)malloc((wcslen(wp) + 1) * sizeof(wchar_t)); - if (buf == NULL) - Py_FatalError( - "not enough memory to copy PYTHONWARNINGS"); - wcscpy(buf, wp); - for (warning = wcstok(buf, L","); - warning != NULL; - warning = wcstok(NULL, L",")) { - PySys_AddWarnOption(warning); - } - free(buf); - } + if (!Py_IgnoreEnvironmentFlag && (wp = _wgetenv(L"PYTHONWARNINGS")) && + *wp != L'\0') { + wchar_t *buf, *warning; + + buf = (wchar_t *)malloc((wcslen(wp) + 1) * sizeof(wchar_t)); + if (buf == NULL) + Py_FatalError( + "not enough memory to copy PYTHONWARNINGS"); + wcscpy(buf, wp); + for (warning = wcstok(buf, L","); + warning != NULL; + warning = wcstok(NULL, L",")) { + PySys_AddWarnOption(warning); + } + free(buf); + } #else - if ((p = Py_GETENV("PYTHONWARNINGS")) && *p != '\0') { - char *buf, *oldloc; - wchar_t *warning; - - /* settle for strtok here as there's no one standard - C89 wcstok */ - buf = (char *)malloc(strlen(p) + 1); - if (buf == NULL) - Py_FatalError( - "not enough memory to copy PYTHONWARNINGS"); - strcpy(buf, p); - oldloc = strdup(setlocale(LC_ALL, NULL)); - setlocale(LC_ALL, ""); - for (p = strtok(buf, ","); p != NULL; p = strtok(NULL, ",")) { - if ((warning = _Py_char2wchar(p)) != NULL) { - PySys_AddWarnOption(warning); - PyMem_Free(warning); - } - } - setlocale(LC_ALL, oldloc); - free(oldloc); - free(buf); - } -#endif - - if (command == NULL && module == NULL && _PyOS_optind < argc && - wcscmp(argv[_PyOS_optind], L"-") != 0) - { + if ((p = Py_GETENV("PYTHONWARNINGS")) && *p != '\0') { + char *buf, *oldloc; + wchar_t *warning; + + /* settle for strtok here as there's no one standard + C89 wcstok */ + buf = (char *)malloc(strlen(p) + 1); + if (buf == NULL) + Py_FatalError( + "not enough memory to copy PYTHONWARNINGS"); + strcpy(buf, p); + oldloc = strdup(setlocale(LC_ALL, NULL)); + setlocale(LC_ALL, ""); + for (p = strtok(buf, ","); p != NULL; p = strtok(NULL, ",")) { + if ((warning = _Py_char2wchar(p)) != NULL) { + PySys_AddWarnOption(warning); + PyMem_Free(warning); + } + } + setlocale(LC_ALL, oldloc); + free(oldloc); + free(buf); + } +#endif + + if (command == NULL && module == NULL && _PyOS_optind < argc && + wcscmp(argv[_PyOS_optind], L"-") != 0) + { #ifdef __VMS - filename = decc$translate_vms(argv[_PyOS_optind]); - if (filename == (char *)0 || filename == (char *)-1) - filename = argv[_PyOS_optind]; + filename = decc$translate_vms(argv[_PyOS_optind]); + if (filename == (char *)0 || filename == (char *)-1) + filename = argv[_PyOS_optind]; #else - filename = argv[_PyOS_optind]; + filename = argv[_PyOS_optind]; #endif - } + } - stdin_is_interactive = Py_FdIsInteractive(stdin, (char *)0); + stdin_is_interactive = Py_FdIsInteractive(stdin, (char *)0); - if (Py_UnbufferedStdioFlag) { + if (Py_UnbufferedStdioFlag) { #if defined(MS_WINDOWS) || defined(__CYGWIN__) - _setmode(fileno(stdin), O_BINARY); - _setmode(fileno(stdout), O_BINARY); + _setmode(fileno(stdin), O_BINARY); + _setmode(fileno(stdout), O_BINARY); #endif #ifdef HAVE_SETVBUF - setvbuf(stdin, (char *)NULL, _IONBF, BUFSIZ); - setvbuf(stdout, (char *)NULL, _IONBF, BUFSIZ); - setvbuf(stderr, (char *)NULL, _IONBF, BUFSIZ); + setvbuf(stdin, (char *)NULL, _IONBF, BUFSIZ); + setvbuf(stdout, (char *)NULL, _IONBF, BUFSIZ); + setvbuf(stderr, (char *)NULL, _IONBF, BUFSIZ); #else /* !HAVE_SETVBUF */ - setbuf(stdin, (char *)NULL); - setbuf(stdout, (char *)NULL); - setbuf(stderr, (char *)NULL); + setbuf(stdin, (char *)NULL); + setbuf(stdout, (char *)NULL); + setbuf(stderr, (char *)NULL); #endif /* !HAVE_SETVBUF */ - } - else if (Py_InteractiveFlag) { + } + else if (Py_InteractiveFlag) { #ifdef MS_WINDOWS - /* Doesn't have to have line-buffered -- use unbuffered */ - /* Any set[v]buf(stdin, ...) screws up Tkinter :-( */ - setvbuf(stdout, (char *)NULL, _IONBF, BUFSIZ); + /* Doesn't have to have line-buffered -- use unbuffered */ + /* Any set[v]buf(stdin, ...) screws up Tkinter :-( */ + setvbuf(stdout, (char *)NULL, _IONBF, BUFSIZ); #else /* !MS_WINDOWS */ #ifdef HAVE_SETVBUF - setvbuf(stdin, (char *)NULL, _IOLBF, BUFSIZ); - setvbuf(stdout, (char *)NULL, _IOLBF, BUFSIZ); + setvbuf(stdin, (char *)NULL, _IOLBF, BUFSIZ); + setvbuf(stdout, (char *)NULL, _IOLBF, BUFSIZ); #endif /* HAVE_SETVBUF */ #endif /* !MS_WINDOWS */ - /* Leave stderr alone - it should be unbuffered anyway. */ - } + /* Leave stderr alone - it should be unbuffered anyway. */ + } #ifdef __VMS - else { - setvbuf (stdout, (char *)NULL, _IOLBF, BUFSIZ); - } + else { + setvbuf (stdout, (char *)NULL, _IOLBF, BUFSIZ); + } #endif /* __VMS */ #ifdef __APPLE__ - /* On MacOS X, when the Python interpreter is embedded in an - application bundle, it gets executed by a bootstrapping script - that does os.execve() with an argv[0] that's different from the - actual Python executable. This is needed to keep the Finder happy, - or rather, to work around Apple's overly strict requirements of - the process name. However, we still need a usable sys.executable, - so the actual executable path is passed in an environment variable. - See Lib/plat-mac/bundlebuiler.py for details about the bootstrap - script. */ - if ((p = Py_GETENV("PYTHONEXECUTABLE")) && *p != '\0') { - wchar_t* buffer; - size_t len = strlen(p); - size_t r; - - buffer = malloc(len * sizeof(wchar_t)); - if (buffer == NULL) { - Py_FatalError( - "not enough memory to copy PYTHONEXECUTABLE"); - } - - r = mbstowcs(buffer, p, len); - Py_SetProgramName(buffer); - /* buffer is now handed off - do not free */ - } else { - Py_SetProgramName(argv[0]); - } + /* On MacOS X, when the Python interpreter is embedded in an + application bundle, it gets executed by a bootstrapping script + that does os.execve() with an argv[0] that's different from the + actual Python executable. This is needed to keep the Finder happy, + or rather, to work around Apple's overly strict requirements of + the process name. However, we still need a usable sys.executable, + so the actual executable path is passed in an environment variable. + See Lib/plat-mac/bundlebuiler.py for details about the bootstrap + script. */ + if ((p = Py_GETENV("PYTHONEXECUTABLE")) && *p != '\0') { + wchar_t* buffer; + size_t len = strlen(p); + size_t r; + + buffer = malloc(len * sizeof(wchar_t)); + if (buffer == NULL) { + Py_FatalError( + "not enough memory to copy PYTHONEXECUTABLE"); + } + + r = mbstowcs(buffer, p, len); + Py_SetProgramName(buffer); + /* buffer is now handed off - do not free */ + } else { + Py_SetProgramName(argv[0]); + } #else - Py_SetProgramName(argv[0]); + Py_SetProgramName(argv[0]); #endif - Py_Initialize(); + Py_Initialize(); - if (Py_VerboseFlag || - (command == NULL && filename == NULL && module == NULL && stdin_is_interactive)) { - fprintf(stderr, "Python %s on %s\n", - Py_GetVersion(), Py_GetPlatform()); - if (!Py_NoSiteFlag) - fprintf(stderr, "%s\n", COPYRIGHT); - } - - if (command != NULL) { - /* Backup _PyOS_optind and force sys.argv[0] = '-c' */ - _PyOS_optind--; - argv[_PyOS_optind] = L"-c"; - } - - if (module != NULL) { - /* Backup _PyOS_optind and force sys.argv[0] = '-c' - so that PySys_SetArgv correctly sets sys.path[0] to ''*/ - _PyOS_optind--; - argv[_PyOS_optind] = L"-c"; - } - - PySys_SetArgv(argc-_PyOS_optind, argv+_PyOS_optind); - - if ((Py_InspectFlag || (command == NULL && filename == NULL && module == NULL)) && - isatty(fileno(stdin))) { - PyObject *v; - v = PyImport_ImportModule("readline"); - if (v == NULL) - PyErr_Clear(); - else - Py_DECREF(v); - } - - if (command) { - PyObject *commandObj = PyUnicode_FromWideChar( - command, wcslen(command)); - free(command); - if (commandObj != NULL) { - sts = PyRun_SimpleStringFlags( - _PyUnicode_AsString(commandObj), &cf) != 0; - } - else { - PyErr_Print(); - sts = 1; - } - Py_DECREF(commandObj); - } else if (module) { - sts = RunModule(module, 1); - } - else { - - if (filename == NULL && stdin_is_interactive) { - Py_InspectFlag = 0; /* do exit on SystemExit */ - RunStartupFile(&cf); - } - /* XXX */ - - sts = -1; /* keep track of whether we've already run __main__ */ - - if (filename != NULL) { - sts = RunMainFromImporter(filename); - } - - if (sts==-1 && filename!=NULL) { - if ((fp = _wfopen(filename, L"r")) == NULL) { - char cfilename[PATH_MAX]; - size_t r = wcstombs(cfilename, filename, PATH_MAX); - if (r == PATH_MAX) - /* cfilename is not null-terminated; - * forcefully null-terminating it - * might break the shift state */ - strcpy(cfilename, ""); - if (r == ((size_t)-1)) - strcpy(cfilename, ""); - fprintf(stderr, "%ls: can't open file '%s': [Errno %d] %s\n", - argv[0], cfilename, errno, strerror(errno)); - - return 2; - } - else if (skipfirstline) { - int ch; - /* Push back first newline so line numbers - remain the same */ - while ((ch = getc(fp)) != EOF) { - if (ch == '\n') { - (void)ungetc(ch, fp); - break; - } - } - } - { - /* XXX: does this work on Win/Win64? (see posix_fstat) */ - struct stat sb; - if (fstat(fileno(fp), &sb) == 0 && - S_ISDIR(sb.st_mode)) { - fprintf(stderr, "%ls: '%ls' is a directory, cannot continue\n", argv[0], filename); - fclose(fp); - return 1; - } - } - } - - if (sts==-1) { - PyObject *filenameObj = NULL; - char *p_cfilename = ""; - if (filename) { - filenameObj = PyUnicode_FromWideChar( - filename, wcslen(filename)); - if (filenameObj != NULL) - p_cfilename = _PyUnicode_AsString(filenameObj); - else - p_cfilename = ""; - } - /* call pending calls like signal handlers (SIGINT) */ - if (Py_MakePendingCalls() == -1) { - PyErr_Print(); - sts = 1; - } else { - sts = PyRun_AnyFileExFlags( - fp, - p_cfilename, - filename != NULL, &cf) != 0; - } - Py_XDECREF(filenameObj); - } - - } - - /* Check this environment variable at the end, to give programs the - * opportunity to set it from Python. - */ - if (!Py_InspectFlag && - (p = Py_GETENV("PYTHONINSPECT")) && *p != '\0') - { - Py_InspectFlag = 1; - } - - if (Py_InspectFlag && stdin_is_interactive && - (filename != NULL || command != NULL || module != NULL)) { - Py_InspectFlag = 0; - /* XXX */ - sts = PyRun_AnyFileFlags(stdin, "", &cf) != 0; - } + if (Py_VerboseFlag || + (command == NULL && filename == NULL && module == NULL && stdin_is_interactive)) { + fprintf(stderr, "Python %s on %s\n", + Py_GetVersion(), Py_GetPlatform()); + if (!Py_NoSiteFlag) + fprintf(stderr, "%s\n", COPYRIGHT); + } + + if (command != NULL) { + /* Backup _PyOS_optind and force sys.argv[0] = '-c' */ + _PyOS_optind--; + argv[_PyOS_optind] = L"-c"; + } + + if (module != NULL) { + /* Backup _PyOS_optind and force sys.argv[0] = '-c' + so that PySys_SetArgv correctly sets sys.path[0] to ''*/ + _PyOS_optind--; + argv[_PyOS_optind] = L"-c"; + } + + PySys_SetArgv(argc-_PyOS_optind, argv+_PyOS_optind); + + if ((Py_InspectFlag || (command == NULL && filename == NULL && module == NULL)) && + isatty(fileno(stdin))) { + PyObject *v; + v = PyImport_ImportModule("readline"); + if (v == NULL) + PyErr_Clear(); + else + Py_DECREF(v); + } + + if (command) { + PyObject *commandObj = PyUnicode_FromWideChar( + command, wcslen(command)); + free(command); + if (commandObj != NULL) { + sts = PyRun_SimpleStringFlags( + _PyUnicode_AsString(commandObj), &cf) != 0; + } + else { + PyErr_Print(); + sts = 1; + } + Py_DECREF(commandObj); + } else if (module) { + sts = RunModule(module, 1); + } + else { + + if (filename == NULL && stdin_is_interactive) { + Py_InspectFlag = 0; /* do exit on SystemExit */ + RunStartupFile(&cf); + } + /* XXX */ + + sts = -1; /* keep track of whether we've already run __main__ */ + + if (filename != NULL) { + sts = RunMainFromImporter(filename); + } + + if (sts==-1 && filename!=NULL) { + if ((fp = _wfopen(filename, L"r")) == NULL) { + char cfilename[PATH_MAX]; + size_t r = wcstombs(cfilename, filename, PATH_MAX); + if (r == PATH_MAX) + /* cfilename is not null-terminated; + * forcefully null-terminating it + * might break the shift state */ + strcpy(cfilename, ""); + if (r == ((size_t)-1)) + strcpy(cfilename, ""); + fprintf(stderr, "%ls: can't open file '%s': [Errno %d] %s\n", + argv[0], cfilename, errno, strerror(errno)); + + return 2; + } + else if (skipfirstline) { + int ch; + /* Push back first newline so line numbers + remain the same */ + while ((ch = getc(fp)) != EOF) { + if (ch == '\n') { + (void)ungetc(ch, fp); + break; + } + } + } + { + /* XXX: does this work on Win/Win64? (see posix_fstat) */ + struct stat sb; + if (fstat(fileno(fp), &sb) == 0 && + S_ISDIR(sb.st_mode)) { + fprintf(stderr, "%ls: '%ls' is a directory, cannot continue\n", argv[0], filename); + fclose(fp); + return 1; + } + } + } + + if (sts==-1) { + PyObject *filenameObj = NULL; + char *p_cfilename = ""; + if (filename) { + filenameObj = PyUnicode_FromWideChar( + filename, wcslen(filename)); + if (filenameObj != NULL) + p_cfilename = _PyUnicode_AsString(filenameObj); + else + p_cfilename = ""; + } + /* call pending calls like signal handlers (SIGINT) */ + if (Py_MakePendingCalls() == -1) { + PyErr_Print(); + sts = 1; + } else { + sts = PyRun_AnyFileExFlags( + fp, + p_cfilename, + filename != NULL, &cf) != 0; + } + Py_XDECREF(filenameObj); + } + + } - Py_Finalize(); + /* Check this environment variable at the end, to give programs the + * opportunity to set it from Python. + */ + if (!Py_InspectFlag && + (p = Py_GETENV("PYTHONINSPECT")) && *p != '\0') + { + Py_InspectFlag = 1; + } + + if (Py_InspectFlag && stdin_is_interactive && + (filename != NULL || command != NULL || module != NULL)) { + Py_InspectFlag = 0; + /* XXX */ + sts = PyRun_AnyFileFlags(stdin, "", &cf) != 0; + } + + Py_Finalize(); #ifdef __INSURE__ - /* Insure++ is a memory analysis tool that aids in discovering - * memory leaks and other memory problems. On Python exit, the - * interned string dictionaries are flagged as being in use at exit - * (which it is). Under normal circumstances, this is fine because - * the memory will be automatically reclaimed by the system. Under - * memory debugging, it's a huge source of useless noise, so we - * trade off slower shutdown for less distraction in the memory - * reports. -baw - */ - _Py_ReleaseInternedStrings(); - _Py_ReleaseInternedUnicodeStrings(); + /* Insure++ is a memory analysis tool that aids in discovering + * memory leaks and other memory problems. On Python exit, the + * interned string dictionaries are flagged as being in use at exit + * (which it is). Under normal circumstances, this is fine because + * the memory will be automatically reclaimed by the system. Under + * memory debugging, it's a huge source of useless noise, so we + * trade off slower shutdown for less distraction in the memory + * reports. -baw + */ + _Py_ReleaseInternedStrings(); + _Py_ReleaseInternedUnicodeStrings(); #endif /* __INSURE__ */ - return sts; + return sts; } /* this is gonna seem *real weird*, but if you put some other code between @@ -702,112 +702,112 @@ void Py_GetArgcArgv(int *argc, wchar_t ***argv) { - *argc = orig_argc; - *argv = orig_argv; + *argc = orig_argc; + *argv = orig_argv; } wchar_t* _Py_char2wchar(char* arg) { - wchar_t *res; + wchar_t *res; #ifdef HAVE_BROKEN_MBSTOWCS - /* Some platforms have a broken implementation of - * mbstowcs which does not count the characters that - * would result from conversion. Use an upper bound. - */ - size_t argsize = strlen(arg); + /* Some platforms have a broken implementation of + * mbstowcs which does not count the characters that + * would result from conversion. Use an upper bound. + */ + size_t argsize = strlen(arg); #else - size_t argsize = mbstowcs(NULL, arg, 0); + size_t argsize = mbstowcs(NULL, arg, 0); #endif - size_t count; - unsigned char *in; - wchar_t *out; + size_t count; + unsigned char *in; + wchar_t *out; #ifdef HAVE_MBRTOWC - mbstate_t mbs; + mbstate_t mbs; #endif - if (argsize != (size_t)-1) { - res = (wchar_t *)PyMem_Malloc((argsize+1)*sizeof(wchar_t)); - if (!res) - goto oom; - count = mbstowcs(res, arg, argsize+1); - if (count != (size_t)-1) { - wchar_t *tmp; - /* Only use the result if it contains no - surrogate characters. */ - for (tmp = res; *tmp != 0 && - (*tmp < 0xd800 || *tmp > 0xdfff); tmp++) - ; - if (*tmp == 0) - return res; - } - PyMem_Free(res); - } - /* Conversion failed. Fall back to escaping with surrogateescape. */ + if (argsize != (size_t)-1) { + res = (wchar_t *)PyMem_Malloc((argsize+1)*sizeof(wchar_t)); + if (!res) + goto oom; + count = mbstowcs(res, arg, argsize+1); + if (count != (size_t)-1) { + wchar_t *tmp; + /* Only use the result if it contains no + surrogate characters. */ + for (tmp = res; *tmp != 0 && + (*tmp < 0xd800 || *tmp > 0xdfff); tmp++) + ; + if (*tmp == 0) + return res; + } + PyMem_Free(res); + } + /* Conversion failed. Fall back to escaping with surrogateescape. */ #ifdef HAVE_MBRTOWC - /* Try conversion with mbrtwoc (C99), and escape non-decodable bytes. */ - - /* Overallocate; as multi-byte characters are in the argument, the - actual output could use less memory. */ - argsize = strlen(arg) + 1; - res = (wchar_t*)PyMem_Malloc(argsize*sizeof(wchar_t)); - if (!res) goto oom; - in = (unsigned char*)arg; - out = res; - memset(&mbs, 0, sizeof mbs); - while (argsize) { - size_t converted = mbrtowc(out, (char*)in, argsize, &mbs); - if (converted == 0) - /* Reached end of string; null char stored. */ - break; - if (converted == (size_t)-2) { - /* Incomplete character. This should never happen, - since we provide everything that we have - - unless there is a bug in the C library, or I - misunderstood how mbrtowc works. */ - fprintf(stderr, "unexpected mbrtowc result -2\n"); - return NULL; - } - if (converted == (size_t)-1) { - /* Conversion error. Escape as UTF-8b, and start over - in the initial shift state. */ - *out++ = 0xdc00 + *in++; - argsize--; - memset(&mbs, 0, sizeof mbs); - continue; - } - if (*out >= 0xd800 && *out <= 0xdfff) { - /* Surrogate character. Escape the original - byte sequence with surrogateescape. */ - argsize -= converted; - while (converted--) - *out++ = 0xdc00 + *in++; - continue; - } - /* successfully converted some bytes */ - in += converted; - argsize -= converted; - out++; - } + /* Try conversion with mbrtwoc (C99), and escape non-decodable bytes. */ + + /* Overallocate; as multi-byte characters are in the argument, the + actual output could use less memory. */ + argsize = strlen(arg) + 1; + res = (wchar_t*)PyMem_Malloc(argsize*sizeof(wchar_t)); + if (!res) goto oom; + in = (unsigned char*)arg; + out = res; + memset(&mbs, 0, sizeof mbs); + while (argsize) { + size_t converted = mbrtowc(out, (char*)in, argsize, &mbs); + if (converted == 0) + /* Reached end of string; null char stored. */ + break; + if (converted == (size_t)-2) { + /* Incomplete character. This should never happen, + since we provide everything that we have - + unless there is a bug in the C library, or I + misunderstood how mbrtowc works. */ + fprintf(stderr, "unexpected mbrtowc result -2\n"); + return NULL; + } + if (converted == (size_t)-1) { + /* Conversion error. Escape as UTF-8b, and start over + in the initial shift state. */ + *out++ = 0xdc00 + *in++; + argsize--; + memset(&mbs, 0, sizeof mbs); + continue; + } + if (*out >= 0xd800 && *out <= 0xdfff) { + /* Surrogate character. Escape the original + byte sequence with surrogateescape. */ + argsize -= converted; + while (converted--) + *out++ = 0xdc00 + *in++; + continue; + } + /* successfully converted some bytes */ + in += converted; + argsize -= converted; + out++; + } #else - /* Cannot use C locale for escaping; manually escape as if charset - is ASCII (i.e. escape all bytes > 128. This will still roundtrip - correctly in the locale's charset, which must be an ASCII superset. */ - res = PyMem_Malloc((strlen(arg)+1)*sizeof(wchar_t)); - if (!res) goto oom; - in = (unsigned char*)arg; - out = res; - while(*in) - if(*in < 128) - *out++ = *in++; - else - *out++ = 0xdc00 + *in++; - *out = 0; + /* Cannot use C locale for escaping; manually escape as if charset + is ASCII (i.e. escape all bytes > 128. This will still roundtrip + correctly in the locale's charset, which must be an ASCII superset. */ + res = PyMem_Malloc((strlen(arg)+1)*sizeof(wchar_t)); + if (!res) goto oom; + in = (unsigned char*)arg; + out = res; + while(*in) + if(*in < 128) + *out++ = *in++; + else + *out++ = 0xdc00 + *in++; + *out = 0; #endif - return res; + return res; oom: - fprintf(stderr, "out of memory\n"); - return NULL; + fprintf(stderr, "out of memory\n"); + return NULL; } #ifdef __cplusplus Modified: python/branches/py3k-jit/Modules/mathmodule.c ============================================================================== --- python/branches/py3k-jit/Modules/mathmodule.c (original) +++ python/branches/py3k-jit/Modules/mathmodule.c Mon May 10 23:55:43 2010 @@ -73,36 +73,36 @@ static double sinpi(double x) { - double y, r; - int n; - /* this function should only ever be called for finite arguments */ - assert(Py_IS_FINITE(x)); - y = fmod(fabs(x), 2.0); - n = (int)round(2.0*y); - assert(0 <= n && n <= 4); - switch (n) { - case 0: - r = sin(pi*y); - break; - case 1: - r = cos(pi*(y-0.5)); - break; - case 2: - /* N.B. -sin(pi*(y-1.0)) is *not* equivalent: it would give - -0.0 instead of 0.0 when y == 1.0. */ - r = sin(pi*(1.0-y)); - break; - case 3: - r = -cos(pi*(y-1.5)); - break; - case 4: - r = sin(pi*(y-2.0)); - break; - default: - assert(0); /* should never get here */ - r = -1.23e200; /* silence gcc warning */ - } - return copysign(1.0, x)*r; + double y, r; + int n; + /* this function should only ever be called for finite arguments */ + assert(Py_IS_FINITE(x)); + y = fmod(fabs(x), 2.0); + n = (int)round(2.0*y); + assert(0 <= n && n <= 4); + switch (n) { + case 0: + r = sin(pi*y); + break; + case 1: + r = cos(pi*(y-0.5)); + break; + case 2: + /* N.B. -sin(pi*(y-1.0)) is *not* equivalent: it would give + -0.0 instead of 0.0 when y == 1.0. */ + r = sin(pi*(1.0-y)); + break; + case 3: + r = -cos(pi*(y-1.5)); + break; + case 4: + r = sin(pi*(y-2.0)); + break; + default: + assert(0); /* should never get here */ + r = -1.23e200; /* silence gcc warning */ + } + return copysign(1.0, x)*r; } /* Implementation of the real gamma function. In extensive but non-exhaustive @@ -166,34 +166,34 @@ static const double lanczos_g = 6.024680040776729583740234375; static const double lanczos_g_minus_half = 5.524680040776729583740234375; static const double lanczos_num_coeffs[LANCZOS_N] = { - 23531376880.410759688572007674451636754734846804940, - 42919803642.649098768957899047001988850926355848959, - 35711959237.355668049440185451547166705960488635843, - 17921034426.037209699919755754458931112671403265390, - 6039542586.3520280050642916443072979210699388420708, - 1439720407.3117216736632230727949123939715485786772, - 248874557.86205415651146038641322942321632125127801, - 31426415.585400194380614231628318205362874684987640, - 2876370.6289353724412254090516208496135991145378768, - 186056.26539522349504029498971604569928220784236328, - 8071.6720023658162106380029022722506138218516325024, - 210.82427775157934587250973392071336271166969580291, - 2.5066282746310002701649081771338373386264310793408 + 23531376880.410759688572007674451636754734846804940, + 42919803642.649098768957899047001988850926355848959, + 35711959237.355668049440185451547166705960488635843, + 17921034426.037209699919755754458931112671403265390, + 6039542586.3520280050642916443072979210699388420708, + 1439720407.3117216736632230727949123939715485786772, + 248874557.86205415651146038641322942321632125127801, + 31426415.585400194380614231628318205362874684987640, + 2876370.6289353724412254090516208496135991145378768, + 186056.26539522349504029498971604569928220784236328, + 8071.6720023658162106380029022722506138218516325024, + 210.82427775157934587250973392071336271166969580291, + 2.5066282746310002701649081771338373386264310793408 }; /* denominator is x*(x+1)*...*(x+LANCZOS_N-2) */ static const double lanczos_den_coeffs[LANCZOS_N] = { - 0.0, 39916800.0, 120543840.0, 150917976.0, 105258076.0, 45995730.0, - 13339535.0, 2637558.0, 357423.0, 32670.0, 1925.0, 66.0, 1.0}; + 0.0, 39916800.0, 120543840.0, 150917976.0, 105258076.0, 45995730.0, + 13339535.0, 2637558.0, 357423.0, 32670.0, 1925.0, 66.0, 1.0}; /* gamma values for small positive integers, 1 though NGAMMA_INTEGRAL */ #define NGAMMA_INTEGRAL 23 static const double gamma_integral[NGAMMA_INTEGRAL] = { - 1.0, 1.0, 2.0, 6.0, 24.0, 120.0, 720.0, 5040.0, 40320.0, 362880.0, - 3628800.0, 39916800.0, 479001600.0, 6227020800.0, 87178291200.0, - 1307674368000.0, 20922789888000.0, 355687428096000.0, - 6402373705728000.0, 121645100408832000.0, 2432902008176640000.0, - 51090942171709440000.0, 1124000727777607680000.0, + 1.0, 1.0, 2.0, 6.0, 24.0, 120.0, 720.0, 5040.0, 40320.0, 362880.0, + 3628800.0, 39916800.0, 479001600.0, 6227020800.0, 87178291200.0, + 1307674368000.0, 20922789888000.0, 355687428096000.0, + 6402373705728000.0, 121645100408832000.0, 2432902008176640000.0, + 51090942171709440000.0, 1124000727777607680000.0, }; /* Lanczos' sum L_g(x), for positive x */ @@ -201,125 +201,125 @@ static double lanczos_sum(double x) { - double num = 0.0, den = 0.0; - int i; - assert(x > 0.0); - /* evaluate the rational function lanczos_sum(x). For large - x, the obvious algorithm risks overflow, so we instead - rescale the denominator and numerator of the rational - function by x**(1-LANCZOS_N) and treat this as a - rational function in 1/x. This also reduces the error for - larger x values. The choice of cutoff point (5.0 below) is - somewhat arbitrary; in tests, smaller cutoff values than - this resulted in lower accuracy. */ - if (x < 5.0) { - for (i = LANCZOS_N; --i >= 0; ) { - num = num * x + lanczos_num_coeffs[i]; - den = den * x + lanczos_den_coeffs[i]; - } - } - else { - for (i = 0; i < LANCZOS_N; i++) { - num = num / x + lanczos_num_coeffs[i]; - den = den / x + lanczos_den_coeffs[i]; - } - } - return num/den; + double num = 0.0, den = 0.0; + int i; + assert(x > 0.0); + /* evaluate the rational function lanczos_sum(x). For large + x, the obvious algorithm risks overflow, so we instead + rescale the denominator and numerator of the rational + function by x**(1-LANCZOS_N) and treat this as a + rational function in 1/x. This also reduces the error for + larger x values. The choice of cutoff point (5.0 below) is + somewhat arbitrary; in tests, smaller cutoff values than + this resulted in lower accuracy. */ + if (x < 5.0) { + for (i = LANCZOS_N; --i >= 0; ) { + num = num * x + lanczos_num_coeffs[i]; + den = den * x + lanczos_den_coeffs[i]; + } + } + else { + for (i = 0; i < LANCZOS_N; i++) { + num = num / x + lanczos_num_coeffs[i]; + den = den / x + lanczos_den_coeffs[i]; + } + } + return num/den; } static double m_tgamma(double x) { - double absx, r, y, z, sqrtpow; + double absx, r, y, z, sqrtpow; - /* special cases */ - if (!Py_IS_FINITE(x)) { - if (Py_IS_NAN(x) || x > 0.0) - return x; /* tgamma(nan) = nan, tgamma(inf) = inf */ - else { - errno = EDOM; - return Py_NAN; /* tgamma(-inf) = nan, invalid */ - } - } - if (x == 0.0) { - errno = EDOM; - return 1.0/x; /* tgamma(+-0.0) = +-inf, divide-by-zero */ - } - - /* integer arguments */ - if (x == floor(x)) { - if (x < 0.0) { - errno = EDOM; /* tgamma(n) = nan, invalid for */ - return Py_NAN; /* negative integers n */ - } - if (x <= NGAMMA_INTEGRAL) - return gamma_integral[(int)x - 1]; - } - absx = fabs(x); - - /* tiny arguments: tgamma(x) ~ 1/x for x near 0 */ - if (absx < 1e-20) { - r = 1.0/x; - if (Py_IS_INFINITY(r)) - errno = ERANGE; - return r; - } - - /* large arguments: assuming IEEE 754 doubles, tgamma(x) overflows for - x > 200, and underflows to +-0.0 for x < -200, not a negative - integer. */ - if (absx > 200.0) { - if (x < 0.0) { - return 0.0/sinpi(x); - } - else { - errno = ERANGE; - return Py_HUGE_VAL; - } - } - - y = absx + lanczos_g_minus_half; - /* compute error in sum */ - if (absx > lanczos_g_minus_half) { - /* note: the correction can be foiled by an optimizing - compiler that (incorrectly) thinks that an expression like - a + b - a - b can be optimized to 0.0. This shouldn't - happen in a standards-conforming compiler. */ - double q = y - absx; - z = q - lanczos_g_minus_half; - } - else { - double q = y - lanczos_g_minus_half; - z = q - absx; - } - z = z * lanczos_g / y; - if (x < 0.0) { - r = -pi / sinpi(absx) / absx * exp(y) / lanczos_sum(absx); - r -= z * r; - if (absx < 140.0) { - r /= pow(y, absx - 0.5); - } - else { - sqrtpow = pow(y, absx / 2.0 - 0.25); - r /= sqrtpow; - r /= sqrtpow; - } - } - else { - r = lanczos_sum(absx) / exp(y); - r += z * r; - if (absx < 140.0) { - r *= pow(y, absx - 0.5); - } - else { - sqrtpow = pow(y, absx / 2.0 - 0.25); - r *= sqrtpow; - r *= sqrtpow; - } - } - if (Py_IS_INFINITY(r)) - errno = ERANGE; - return r; + /* special cases */ + if (!Py_IS_FINITE(x)) { + if (Py_IS_NAN(x) || x > 0.0) + return x; /* tgamma(nan) = nan, tgamma(inf) = inf */ + else { + errno = EDOM; + return Py_NAN; /* tgamma(-inf) = nan, invalid */ + } + } + if (x == 0.0) { + errno = EDOM; + return 1.0/x; /* tgamma(+-0.0) = +-inf, divide-by-zero */ + } + + /* integer arguments */ + if (x == floor(x)) { + if (x < 0.0) { + errno = EDOM; /* tgamma(n) = nan, invalid for */ + return Py_NAN; /* negative integers n */ + } + if (x <= NGAMMA_INTEGRAL) + return gamma_integral[(int)x - 1]; + } + absx = fabs(x); + + /* tiny arguments: tgamma(x) ~ 1/x for x near 0 */ + if (absx < 1e-20) { + r = 1.0/x; + if (Py_IS_INFINITY(r)) + errno = ERANGE; + return r; + } + + /* large arguments: assuming IEEE 754 doubles, tgamma(x) overflows for + x > 200, and underflows to +-0.0 for x < -200, not a negative + integer. */ + if (absx > 200.0) { + if (x < 0.0) { + return 0.0/sinpi(x); + } + else { + errno = ERANGE; + return Py_HUGE_VAL; + } + } + + y = absx + lanczos_g_minus_half; + /* compute error in sum */ + if (absx > lanczos_g_minus_half) { + /* note: the correction can be foiled by an optimizing + compiler that (incorrectly) thinks that an expression like + a + b - a - b can be optimized to 0.0. This shouldn't + happen in a standards-conforming compiler. */ + double q = y - absx; + z = q - lanczos_g_minus_half; + } + else { + double q = y - lanczos_g_minus_half; + z = q - absx; + } + z = z * lanczos_g / y; + if (x < 0.0) { + r = -pi / sinpi(absx) / absx * exp(y) / lanczos_sum(absx); + r -= z * r; + if (absx < 140.0) { + r /= pow(y, absx - 0.5); + } + else { + sqrtpow = pow(y, absx / 2.0 - 0.25); + r /= sqrtpow; + r /= sqrtpow; + } + } + else { + r = lanczos_sum(absx) / exp(y); + r += z * r; + if (absx < 140.0) { + r *= pow(y, absx - 0.5); + } + else { + sqrtpow = pow(y, absx / 2.0 - 0.25); + r *= sqrtpow; + r *= sqrtpow; + } + } + if (Py_IS_INFINITY(r)) + errno = ERANGE; + return r; } /* @@ -330,49 +330,49 @@ static double m_lgamma(double x) { - double r, absx; + double r, absx; - /* special cases */ - if (!Py_IS_FINITE(x)) { - if (Py_IS_NAN(x)) - return x; /* lgamma(nan) = nan */ - else - return Py_HUGE_VAL; /* lgamma(+-inf) = +inf */ - } - - /* integer arguments */ - if (x == floor(x) && x <= 2.0) { - if (x <= 0.0) { - errno = EDOM; /* lgamma(n) = inf, divide-by-zero for */ - return Py_HUGE_VAL; /* integers n <= 0 */ - } - else { - return 0.0; /* lgamma(1) = lgamma(2) = 0.0 */ - } - } - - absx = fabs(x); - /* tiny arguments: lgamma(x) ~ -log(fabs(x)) for small x */ - if (absx < 1e-20) - return -log(absx); - - /* Lanczos' formula */ - if (x > 0.0) { - /* we could save a fraction of a ulp in accuracy by having a - second set of numerator coefficients for lanczos_sum that - absorbed the exp(-lanczos_g) term, and throwing out the - lanczos_g subtraction below; it's probably not worth it. */ - r = log(lanczos_sum(x)) - lanczos_g + - (x-0.5)*(log(x+lanczos_g-0.5)-1); - } - else { - r = log(pi) - log(fabs(sinpi(absx))) - log(absx) - - (log(lanczos_sum(absx)) - lanczos_g + - (absx-0.5)*(log(absx+lanczos_g-0.5)-1)); - } - if (Py_IS_INFINITY(r)) - errno = ERANGE; - return r; + /* special cases */ + if (!Py_IS_FINITE(x)) { + if (Py_IS_NAN(x)) + return x; /* lgamma(nan) = nan */ + else + return Py_HUGE_VAL; /* lgamma(+-inf) = +inf */ + } + + /* integer arguments */ + if (x == floor(x) && x <= 2.0) { + if (x <= 0.0) { + errno = EDOM; /* lgamma(n) = inf, divide-by-zero for */ + return Py_HUGE_VAL; /* integers n <= 0 */ + } + else { + return 0.0; /* lgamma(1) = lgamma(2) = 0.0 */ + } + } + + absx = fabs(x); + /* tiny arguments: lgamma(x) ~ -log(fabs(x)) for small x */ + if (absx < 1e-20) + return -log(absx); + + /* Lanczos' formula */ + if (x > 0.0) { + /* we could save a fraction of a ulp in accuracy by having a + second set of numerator coefficients for lanczos_sum that + absorbed the exp(-lanczos_g) term, and throwing out the + lanczos_g subtraction below; it's probably not worth it. */ + r = log(lanczos_sum(x)) - lanczos_g + + (x-0.5)*(log(x+lanczos_g-0.5)-1); + } + else { + r = log(pi) - log(fabs(sinpi(absx))) - log(absx) - + (log(lanczos_sum(absx)) - lanczos_g + + (absx-0.5)*(log(absx+lanczos_g-0.5)-1)); + } + if (Py_IS_INFINITY(r)) + errno = ERANGE; + return r; } /* @@ -428,17 +428,17 @@ static double m_erf_series(double x) { - double x2, acc, fk; - int i; + double x2, acc, fk; + int i; - x2 = x * x; - acc = 0.0; - fk = (double)ERF_SERIES_TERMS + 0.5; - for (i = 0; i < ERF_SERIES_TERMS; i++) { - acc = 2.0 + x2 * acc / fk; - fk -= 1.0; - } - return acc * x * exp(-x2) / sqrtpi; + x2 = x * x; + acc = 0.0; + fk = (double)ERF_SERIES_TERMS + 0.5; + for (i = 0; i < ERF_SERIES_TERMS; i++) { + acc = 2.0 + x2 * acc / fk; + fk -= 1.0; + } + return acc * x * exp(-x2) / sqrtpi; } /* @@ -453,26 +453,26 @@ static double m_erfc_contfrac(double x) { - double x2, a, da, p, p_last, q, q_last, b; - int i; + double x2, a, da, p, p_last, q, q_last, b; + int i; - if (x >= ERFC_CONTFRAC_CUTOFF) - return 0.0; + if (x >= ERFC_CONTFRAC_CUTOFF) + return 0.0; - x2 = x*x; - a = 0.0; - da = 0.5; - p = 1.0; p_last = 0.0; - q = da + x2; q_last = 1.0; - for (i = 0; i < ERFC_CONTFRAC_TERMS; i++) { - double temp; - a += da; - da += 2.0; - b = da + x2; - temp = p; p = b*p - a*p_last; p_last = temp; - temp = q; q = b*q - a*q_last; q_last = temp; - } - return p / q * x * exp(-x2) / sqrtpi; + x2 = x*x; + a = 0.0; + da = 0.5; + p = 1.0; p_last = 0.0; + q = da + x2; q_last = 1.0; + for (i = 0; i < ERFC_CONTFRAC_TERMS; i++) { + double temp; + a += da; + da += 2.0; + b = da + x2; + temp = p; p = b*p - a*p_last; p_last = temp; + temp = q; q = b*q - a*q_last; q_last = temp; + } + return p / q * x * exp(-x2) / sqrtpi; } /* Error function erf(x), for general x */ @@ -480,17 +480,17 @@ static double m_erf(double x) { - double absx, cf; + double absx, cf; - if (Py_IS_NAN(x)) - return x; - absx = fabs(x); - if (absx < ERF_SERIES_CUTOFF) - return m_erf_series(x); - else { - cf = m_erfc_contfrac(absx); - return x > 0.0 ? 1.0 - cf : cf - 1.0; - } + if (Py_IS_NAN(x)) + return x; + absx = fabs(x); + if (absx < ERF_SERIES_CUTOFF) + return m_erf_series(x); + else { + cf = m_erfc_contfrac(absx); + return x > 0.0 ? 1.0 - cf : cf - 1.0; + } } /* Complementary error function erfc(x), for general x. */ @@ -498,17 +498,17 @@ static double m_erfc(double x) { - double absx, cf; + double absx, cf; - if (Py_IS_NAN(x)) - return x; - absx = fabs(x); - if (absx < ERF_SERIES_CUTOFF) - return 1.0 - m_erf_series(x); - else { - cf = m_erfc_contfrac(absx); - return x > 0.0 ? cf : 2.0 - cf; - } + if (Py_IS_NAN(x)) + return x; + absx = fabs(x); + if (absx < ERF_SERIES_CUTOFF) + return 1.0 - m_erf_series(x); + else { + cf = m_erfc_contfrac(absx); + return x > 0.0 ? cf : 2.0 - cf; + } } /* @@ -522,29 +522,29 @@ static double m_atan2(double y, double x) { - if (Py_IS_NAN(x) || Py_IS_NAN(y)) - return Py_NAN; - if (Py_IS_INFINITY(y)) { - if (Py_IS_INFINITY(x)) { - if (copysign(1., x) == 1.) - /* atan2(+-inf, +inf) == +-pi/4 */ - return copysign(0.25*Py_MATH_PI, y); - else - /* atan2(+-inf, -inf) == +-pi*3/4 */ - return copysign(0.75*Py_MATH_PI, y); - } - /* atan2(+-inf, x) == +-pi/2 for finite x */ - return copysign(0.5*Py_MATH_PI, y); - } - if (Py_IS_INFINITY(x) || y == 0.) { - if (copysign(1., x) == 1.) - /* atan2(+-y, +inf) = atan2(+-0, +x) = +-0. */ - return copysign(0., y); - else - /* atan2(+-y, -inf) = atan2(+-0., -x) = +-pi. */ - return copysign(Py_MATH_PI, y); - } - return atan2(y, x); + if (Py_IS_NAN(x) || Py_IS_NAN(y)) + return Py_NAN; + if (Py_IS_INFINITY(y)) { + if (Py_IS_INFINITY(x)) { + if (copysign(1., x) == 1.) + /* atan2(+-inf, +inf) == +-pi/4 */ + return copysign(0.25*Py_MATH_PI, y); + else + /* atan2(+-inf, -inf) == +-pi*3/4 */ + return copysign(0.75*Py_MATH_PI, y); + } + /* atan2(+-inf, x) == +-pi/2 for finite x */ + return copysign(0.5*Py_MATH_PI, y); + } + if (Py_IS_INFINITY(x) || y == 0.) { + if (copysign(1., x) == 1.) + /* atan2(+-y, +inf) = atan2(+-0, +x) = +-0. */ + return copysign(0., y); + else + /* atan2(+-y, -inf) = atan2(+-0., -x) = +-pi. */ + return copysign(Py_MATH_PI, y); + } + return atan2(y, x); } /* @@ -557,45 +557,45 @@ static double m_log(double x) { - if (Py_IS_FINITE(x)) { - if (x > 0.0) - return log(x); - errno = EDOM; - if (x == 0.0) - return -Py_HUGE_VAL; /* log(0) = -inf */ - else - return Py_NAN; /* log(-ve) = nan */ - } - else if (Py_IS_NAN(x)) - return x; /* log(nan) = nan */ - else if (x > 0.0) - return x; /* log(inf) = inf */ - else { - errno = EDOM; - return Py_NAN; /* log(-inf) = nan */ - } + if (Py_IS_FINITE(x)) { + if (x > 0.0) + return log(x); + errno = EDOM; + if (x == 0.0) + return -Py_HUGE_VAL; /* log(0) = -inf */ + else + return Py_NAN; /* log(-ve) = nan */ + } + else if (Py_IS_NAN(x)) + return x; /* log(nan) = nan */ + else if (x > 0.0) + return x; /* log(inf) = inf */ + else { + errno = EDOM; + return Py_NAN; /* log(-inf) = nan */ + } } static double m_log10(double x) { - if (Py_IS_FINITE(x)) { - if (x > 0.0) - return log10(x); - errno = EDOM; - if (x == 0.0) - return -Py_HUGE_VAL; /* log10(0) = -inf */ - else - return Py_NAN; /* log10(-ve) = nan */ - } - else if (Py_IS_NAN(x)) - return x; /* log10(nan) = nan */ - else if (x > 0.0) - return x; /* log10(inf) = inf */ - else { - errno = EDOM; - return Py_NAN; /* log10(-inf) = nan */ - } + if (Py_IS_FINITE(x)) { + if (x > 0.0) + return log10(x); + errno = EDOM; + if (x == 0.0) + return -Py_HUGE_VAL; /* log10(0) = -inf */ + else + return Py_NAN; /* log10(-ve) = nan */ + } + else if (Py_IS_NAN(x)) + return x; /* log10(nan) = nan */ + else if (x > 0.0) + return x; /* log10(inf) = inf */ + else { + errno = EDOM; + return Py_NAN; /* log10(-inf) = nan */ + } } @@ -606,37 +606,37 @@ static int is_error(double x) { - int result = 1; /* presumption of guilt */ - assert(errno); /* non-zero errno is a precondition for calling */ - if (errno == EDOM) - PyErr_SetString(PyExc_ValueError, "math domain error"); - - else if (errno == ERANGE) { - /* ANSI C generally requires libm functions to set ERANGE - * on overflow, but also generally *allows* them to set - * ERANGE on underflow too. There's no consistency about - * the latter across platforms. - * Alas, C99 never requires that errno be set. - * Here we suppress the underflow errors (libm functions - * should return a zero on underflow, and +- HUGE_VAL on - * overflow, so testing the result for zero suffices to - * distinguish the cases). - * - * On some platforms (Ubuntu/ia64) it seems that errno can be - * set to ERANGE for subnormal results that do *not* underflow - * to zero. So to be safe, we'll ignore ERANGE whenever the - * function result is less than one in absolute value. - */ - if (fabs(x) < 1.0) - result = 0; - else - PyErr_SetString(PyExc_OverflowError, - "math range error"); - } - else - /* Unexpected math error */ - PyErr_SetFromErrno(PyExc_ValueError); - return result; + int result = 1; /* presumption of guilt */ + assert(errno); /* non-zero errno is a precondition for calling */ + if (errno == EDOM) + PyErr_SetString(PyExc_ValueError, "math domain error"); + + else if (errno == ERANGE) { + /* ANSI C generally requires libm functions to set ERANGE + * on overflow, but also generally *allows* them to set + * ERANGE on underflow too. There's no consistency about + * the latter across platforms. + * Alas, C99 never requires that errno be set. + * Here we suppress the underflow errors (libm functions + * should return a zero on underflow, and +- HUGE_VAL on + * overflow, so testing the result for zero suffices to + * distinguish the cases). + * + * On some platforms (Ubuntu/ia64) it seems that errno can be + * set to ERANGE for subnormal results that do *not* underflow + * to zero. So to be safe, we'll ignore ERANGE whenever the + * function result is less than one in absolute value. + */ + if (fabs(x) < 1.0) + result = 0; + else + PyErr_SetString(PyExc_OverflowError, + "math range error"); + } + else + /* Unexpected math error */ + PyErr_SetFromErrno(PyExc_ValueError); + return result; } /* @@ -674,33 +674,33 @@ PyObject *(*from_double_func) (double), int can_overflow) { - double x, r; - x = PyFloat_AsDouble(arg); - if (x == -1.0 && PyErr_Occurred()) - return NULL; - errno = 0; - PyFPE_START_PROTECT("in math_1", return 0); - r = (*func)(x); - PyFPE_END_PROTECT(r); - if (Py_IS_NAN(r) && !Py_IS_NAN(x)) { - PyErr_SetString(PyExc_ValueError, - "math domain error"); /* invalid arg */ - return NULL; - } - if (Py_IS_INFINITY(r) && Py_IS_FINITE(x)) { - if (can_overflow) - PyErr_SetString(PyExc_OverflowError, - "math range error"); /* overflow */ - else - PyErr_SetString(PyExc_ValueError, - "math domain error"); /* singularity */ - return NULL; - } - if (Py_IS_FINITE(r) && errno && is_error(r)) - /* this branch unnecessary on most platforms */ - return NULL; + double x, r; + x = PyFloat_AsDouble(arg); + if (x == -1.0 && PyErr_Occurred()) + return NULL; + errno = 0; + PyFPE_START_PROTECT("in math_1", return 0); + r = (*func)(x); + PyFPE_END_PROTECT(r); + if (Py_IS_NAN(r) && !Py_IS_NAN(x)) { + PyErr_SetString(PyExc_ValueError, + "math domain error"); /* invalid arg */ + return NULL; + } + if (Py_IS_INFINITY(r) && Py_IS_FINITE(x)) { + if (can_overflow) + PyErr_SetString(PyExc_OverflowError, + "math range error"); /* overflow */ + else + PyErr_SetString(PyExc_ValueError, + "math domain error"); /* singularity */ + return NULL; + } + if (Py_IS_FINITE(r) && errno && is_error(r)) + /* this branch unnecessary on most platforms */ + return NULL; - return (*from_double_func)(r); + return (*from_double_func)(r); } /* variant of math_1, to be used when the function being wrapped is known to @@ -710,17 +710,17 @@ static PyObject * math_1a(PyObject *arg, double (*func) (double)) { - double x, r; - x = PyFloat_AsDouble(arg); - if (x == -1.0 && PyErr_Occurred()) - return NULL; - errno = 0; - PyFPE_START_PROTECT("in math_1a", return 0); - r = (*func)(x); - PyFPE_END_PROTECT(r); - if (errno && is_error(r)) - return NULL; - return PyFloat_FromDouble(r); + double x, r; + x = PyFloat_AsDouble(arg); + if (x == -1.0 && PyErr_Occurred()) + return NULL; + errno = 0; + PyFPE_START_PROTECT("in math_1a", return 0); + r = (*func)(x); + PyFPE_END_PROTECT(r); + if (errno && is_error(r)) + return NULL; + return PyFloat_FromDouble(r); } /* @@ -753,65 +753,65 @@ static PyObject * math_1(PyObject *arg, double (*func) (double), int can_overflow) { - return math_1_to_whatever(arg, func, PyFloat_FromDouble, can_overflow); + return math_1_to_whatever(arg, func, PyFloat_FromDouble, can_overflow); } static PyObject * math_1_to_int(PyObject *arg, double (*func) (double), int can_overflow) { - return math_1_to_whatever(arg, func, PyLong_FromDouble, can_overflow); + return math_1_to_whatever(arg, func, PyLong_FromDouble, can_overflow); } static PyObject * math_2(PyObject *args, double (*func) (double, double), char *funcname) { - PyObject *ox, *oy; - double x, y, r; - if (! PyArg_UnpackTuple(args, funcname, 2, 2, &ox, &oy)) - return NULL; - x = PyFloat_AsDouble(ox); - y = PyFloat_AsDouble(oy); - if ((x == -1.0 || y == -1.0) && PyErr_Occurred()) - return NULL; - errno = 0; - PyFPE_START_PROTECT("in math_2", return 0); - r = (*func)(x, y); - PyFPE_END_PROTECT(r); - if (Py_IS_NAN(r)) { - if (!Py_IS_NAN(x) && !Py_IS_NAN(y)) - errno = EDOM; - else - errno = 0; - } - else if (Py_IS_INFINITY(r)) { - if (Py_IS_FINITE(x) && Py_IS_FINITE(y)) - errno = ERANGE; - else - errno = 0; - } - if (errno && is_error(r)) - return NULL; - else - return PyFloat_FromDouble(r); -} - -#define FUNC1(funcname, func, can_overflow, docstring) \ - static PyObject * math_##funcname(PyObject *self, PyObject *args) { \ - return math_1(args, func, can_overflow); \ - }\ - PyDoc_STRVAR(math_##funcname##_doc, docstring); - -#define FUNC1A(funcname, func, docstring) \ - static PyObject * math_##funcname(PyObject *self, PyObject *args) { \ - return math_1a(args, func); \ - }\ - PyDoc_STRVAR(math_##funcname##_doc, docstring); + PyObject *ox, *oy; + double x, y, r; + if (! PyArg_UnpackTuple(args, funcname, 2, 2, &ox, &oy)) + return NULL; + x = PyFloat_AsDouble(ox); + y = PyFloat_AsDouble(oy); + if ((x == -1.0 || y == -1.0) && PyErr_Occurred()) + return NULL; + errno = 0; + PyFPE_START_PROTECT("in math_2", return 0); + r = (*func)(x, y); + PyFPE_END_PROTECT(r); + if (Py_IS_NAN(r)) { + if (!Py_IS_NAN(x) && !Py_IS_NAN(y)) + errno = EDOM; + else + errno = 0; + } + else if (Py_IS_INFINITY(r)) { + if (Py_IS_FINITE(x) && Py_IS_FINITE(y)) + errno = ERANGE; + else + errno = 0; + } + if (errno && is_error(r)) + return NULL; + else + return PyFloat_FromDouble(r); +} + +#define FUNC1(funcname, func, can_overflow, docstring) \ + static PyObject * math_##funcname(PyObject *self, PyObject *args) { \ + return math_1(args, func, can_overflow); \ + }\ + PyDoc_STRVAR(math_##funcname##_doc, docstring); + +#define FUNC1A(funcname, func, docstring) \ + static PyObject * math_##funcname(PyObject *self, PyObject *args) { \ + return math_1a(args, func); \ + }\ + PyDoc_STRVAR(math_##funcname##_doc, docstring); #define FUNC2(funcname, func, docstring) \ - static PyObject * math_##funcname(PyObject *self, PyObject *args) { \ - return math_2(args, func, #funcname); \ - }\ - PyDoc_STRVAR(math_##funcname##_doc, docstring); + static PyObject * math_##funcname(PyObject *self, PyObject *args) { \ + return math_2(args, func, #funcname); \ + }\ + PyDoc_STRVAR(math_##funcname##_doc, docstring); FUNC1(acos, acos, 0, "acos(x)\n\nReturn the arc cosine (measured in radians) of x.") @@ -830,25 +830,25 @@ "atanh(x)\n\nReturn the hyperbolic arc tangent (measured in radians) of x.") static PyObject * math_ceil(PyObject *self, PyObject *number) { - static PyObject *ceil_str = NULL; - PyObject *method; + static PyObject *ceil_str = NULL; + PyObject *method; - if (ceil_str == NULL) { - ceil_str = PyUnicode_InternFromString("__ceil__"); - if (ceil_str == NULL) - return NULL; - } - - method = _PyType_Lookup(Py_TYPE(number), ceil_str); - if (method == NULL) - return math_1_to_int(number, ceil, 0); - else - return PyObject_CallFunction(method, "O", number); + if (ceil_str == NULL) { + ceil_str = PyUnicode_InternFromString("__ceil__"); + if (ceil_str == NULL) + return NULL; + } + + method = _PyType_Lookup(Py_TYPE(number), ceil_str); + if (method == NULL) + return math_1_to_int(number, ceil, 0); + else + return PyObject_CallFunction(method, "O", number); } PyDoc_STRVAR(math_ceil_doc, - "ceil(x)\n\nReturn the ceiling of x as an int.\n" - "This is the smallest integral value >= x."); + "ceil(x)\n\nReturn the ceiling of x as an int.\n" + "This is the smallest integral value >= x."); FUNC2(copysign, copysign, "copysign(x, y)\n\nReturn x with the sign of y.") @@ -870,25 +870,25 @@ "fabs(x)\n\nReturn the absolute value of the float x.") static PyObject * math_floor(PyObject *self, PyObject *number) { - static PyObject *floor_str = NULL; - PyObject *method; + static PyObject *floor_str = NULL; + PyObject *method; - if (floor_str == NULL) { - floor_str = PyUnicode_InternFromString("__floor__"); - if (floor_str == NULL) - return NULL; - } - - method = _PyType_Lookup(Py_TYPE(number), floor_str); - if (method == NULL) - return math_1_to_int(number, floor, 0); - else - return PyObject_CallFunction(method, "O", number); + if (floor_str == NULL) { + floor_str = PyUnicode_InternFromString("__floor__"); + if (floor_str == NULL) + return NULL; + } + + method = _PyType_Lookup(Py_TYPE(number), floor_str); + if (method == NULL) + return math_1_to_int(number, floor, 0); + else + return PyObject_CallFunction(method, "O", number); } PyDoc_STRVAR(math_floor_doc, - "floor(x)\n\nReturn the floor of x as an int.\n" - "This is the largest integral value <= x."); + "floor(x)\n\nReturn the floor of x as an int.\n" + "This is the largest integral value <= x."); FUNC1A(gamma, m_tgamma, "gamma(x)\n\nGamma function at x.") @@ -928,7 +928,7 @@ Also, the volatile declaration forces the values to be stored in memory as regular doubles instead of extended long precision (80-bit) values. This prevents double rounding because any addition or subtraction of two doubles - can be resolved exactly into double-sized hi and lo values. As long as the + can be resolved exactly into double-sized hi and lo values. As long as the hi value gets forced into a double before yr and lo are computed, the extra bits in downstream extended precision operations (x87 for example) will be exactly zero and therefore can be losslessly stored back into a double, @@ -951,27 +951,27 @@ _fsum_realloc(double **p_ptr, Py_ssize_t n, double *ps, Py_ssize_t *m_ptr) { - void *v = NULL; - Py_ssize_t m = *m_ptr; + void *v = NULL; + Py_ssize_t m = *m_ptr; - m += m; /* double */ - if (n < m && m < (PY_SSIZE_T_MAX / sizeof(double))) { - double *p = *p_ptr; - if (p == ps) { - v = PyMem_Malloc(sizeof(double) * m); - if (v != NULL) - memcpy(v, ps, sizeof(double) * n); - } - else - v = PyMem_Realloc(p, sizeof(double) * m); - } - if (v == NULL) { /* size overflow or no memory */ - PyErr_SetString(PyExc_MemoryError, "math.fsum partials"); - return 1; - } - *p_ptr = (double*) v; - *m_ptr = m; - return 0; + m += m; /* double */ + if (n < m && m < (PY_SSIZE_T_MAX / sizeof(double))) { + double *p = *p_ptr; + if (p == ps) { + v = PyMem_Malloc(sizeof(double) * m); + if (v != NULL) + memcpy(v, ps, sizeof(double) * n); + } + else + v = PyMem_Realloc(p, sizeof(double) * m); + } + if (v == NULL) { /* size overflow or no memory */ + PyErr_SetString(PyExc_MemoryError, "math.fsum partials"); + return 1; + } + *p_ptr = (double*) v; + *m_ptr = m; + return 0; } /* Full precision summation of a sequence of floats. @@ -979,17 +979,17 @@ def msum(iterable): partials = [] # sorted, non-overlapping partial sums for x in iterable: - i = 0 - for y in partials: - if abs(x) < abs(y): - x, y = y, x - hi = x + y - lo = y - (hi - x) - if lo: - partials[i] = lo - i += 1 - x = hi - partials[i:] = [x] + i = 0 + for y in partials: + if abs(x) < abs(y): + x, y = y, x + hi = x + y + lo = y - (hi - x) + if lo: + partials[i] = lo + i += 1 + x = hi + partials[i:] = [x] return sum_exact(partials) Rounded x+y stored in hi with the roundoff stored in lo. Together hi+lo @@ -1007,119 +1007,119 @@ static PyObject* math_fsum(PyObject *self, PyObject *seq) { - PyObject *item, *iter, *sum = NULL; - Py_ssize_t i, j, n = 0, m = NUM_PARTIALS; - double x, y, t, ps[NUM_PARTIALS], *p = ps; - double xsave, special_sum = 0.0, inf_sum = 0.0; - volatile double hi, yr, lo; - - iter = PyObject_GetIter(seq); - if (iter == NULL) - return NULL; - - PyFPE_START_PROTECT("fsum", Py_DECREF(iter); return NULL) - - for(;;) { /* for x in iterable */ - assert(0 <= n && n <= m); - assert((m == NUM_PARTIALS && p == ps) || - (m > NUM_PARTIALS && p != NULL)); - - item = PyIter_Next(iter); - if (item == NULL) { - if (PyErr_Occurred()) - goto _fsum_error; - break; - } - x = PyFloat_AsDouble(item); - Py_DECREF(item); - if (PyErr_Occurred()) - goto _fsum_error; - - xsave = x; - for (i = j = 0; j < n; j++) { /* for y in partials */ - y = p[j]; - if (fabs(x) < fabs(y)) { - t = x; x = y; y = t; - } - hi = x + y; - yr = hi - x; - lo = y - yr; - if (lo != 0.0) - p[i++] = lo; - x = hi; - } - - n = i; /* ps[i:] = [x] */ - if (x != 0.0) { - if (! Py_IS_FINITE(x)) { - /* a nonfinite x could arise either as - a result of intermediate overflow, or - as a result of a nan or inf in the - summands */ - if (Py_IS_FINITE(xsave)) { - PyErr_SetString(PyExc_OverflowError, - "intermediate overflow in fsum"); - goto _fsum_error; - } - if (Py_IS_INFINITY(xsave)) - inf_sum += xsave; - special_sum += xsave; - /* reset partials */ - n = 0; - } - else if (n >= m && _fsum_realloc(&p, n, ps, &m)) - goto _fsum_error; - else - p[n++] = x; - } - } - - if (special_sum != 0.0) { - if (Py_IS_NAN(inf_sum)) - PyErr_SetString(PyExc_ValueError, - "-inf + inf in fsum"); - else - sum = PyFloat_FromDouble(special_sum); - goto _fsum_error; - } - - hi = 0.0; - if (n > 0) { - hi = p[--n]; - /* sum_exact(ps, hi) from the top, stop when the sum becomes - inexact. */ - while (n > 0) { - x = hi; - y = p[--n]; - assert(fabs(y) < fabs(x)); - hi = x + y; - yr = hi - x; - lo = y - yr; - if (lo != 0.0) - break; - } - /* Make half-even rounding work across multiple partials. - Needed so that sum([1e-16, 1, 1e16]) will round-up the last - digit to two instead of down to zero (the 1e-16 makes the 1 - slightly closer to two). With a potential 1 ULP rounding - error fixed-up, math.fsum() can guarantee commutativity. */ - if (n > 0 && ((lo < 0.0 && p[n-1] < 0.0) || - (lo > 0.0 && p[n-1] > 0.0))) { - y = lo * 2.0; - x = hi + y; - yr = x - hi; - if (y == yr) - hi = x; - } - } - sum = PyFloat_FromDouble(hi); + PyObject *item, *iter, *sum = NULL; + Py_ssize_t i, j, n = 0, m = NUM_PARTIALS; + double x, y, t, ps[NUM_PARTIALS], *p = ps; + double xsave, special_sum = 0.0, inf_sum = 0.0; + volatile double hi, yr, lo; + + iter = PyObject_GetIter(seq); + if (iter == NULL) + return NULL; + + PyFPE_START_PROTECT("fsum", Py_DECREF(iter); return NULL) + + for(;;) { /* for x in iterable */ + assert(0 <= n && n <= m); + assert((m == NUM_PARTIALS && p == ps) || + (m > NUM_PARTIALS && p != NULL)); + + item = PyIter_Next(iter); + if (item == NULL) { + if (PyErr_Occurred()) + goto _fsum_error; + break; + } + x = PyFloat_AsDouble(item); + Py_DECREF(item); + if (PyErr_Occurred()) + goto _fsum_error; + + xsave = x; + for (i = j = 0; j < n; j++) { /* for y in partials */ + y = p[j]; + if (fabs(x) < fabs(y)) { + t = x; x = y; y = t; + } + hi = x + y; + yr = hi - x; + lo = y - yr; + if (lo != 0.0) + p[i++] = lo; + x = hi; + } + + n = i; /* ps[i:] = [x] */ + if (x != 0.0) { + if (! Py_IS_FINITE(x)) { + /* a nonfinite x could arise either as + a result of intermediate overflow, or + as a result of a nan or inf in the + summands */ + if (Py_IS_FINITE(xsave)) { + PyErr_SetString(PyExc_OverflowError, + "intermediate overflow in fsum"); + goto _fsum_error; + } + if (Py_IS_INFINITY(xsave)) + inf_sum += xsave; + special_sum += xsave; + /* reset partials */ + n = 0; + } + else if (n >= m && _fsum_realloc(&p, n, ps, &m)) + goto _fsum_error; + else + p[n++] = x; + } + } + + if (special_sum != 0.0) { + if (Py_IS_NAN(inf_sum)) + PyErr_SetString(PyExc_ValueError, + "-inf + inf in fsum"); + else + sum = PyFloat_FromDouble(special_sum); + goto _fsum_error; + } + + hi = 0.0; + if (n > 0) { + hi = p[--n]; + /* sum_exact(ps, hi) from the top, stop when the sum becomes + inexact. */ + while (n > 0) { + x = hi; + y = p[--n]; + assert(fabs(y) < fabs(x)); + hi = x + y; + yr = hi - x; + lo = y - yr; + if (lo != 0.0) + break; + } + /* Make half-even rounding work across multiple partials. + Needed so that sum([1e-16, 1, 1e16]) will round-up the last + digit to two instead of down to zero (the 1e-16 makes the 1 + slightly closer to two). With a potential 1 ULP rounding + error fixed-up, math.fsum() can guarantee commutativity. */ + if (n > 0 && ((lo < 0.0 && p[n-1] < 0.0) || + (lo > 0.0 && p[n-1] > 0.0))) { + y = lo * 2.0; + x = hi + y; + yr = x - hi; + if (y == yr) + hi = x; + } + } + sum = PyFloat_FromDouble(hi); _fsum_error: - PyFPE_END_PROTECT(hi) - Py_DECREF(iter); - if (p != ps) - PyMem_Free(p); - return sum; + PyFPE_END_PROTECT(hi) + Py_DECREF(iter); + if (p != ps) + PyMem_Free(p); + return sum; } #undef NUM_PARTIALS @@ -1132,53 +1132,53 @@ static PyObject * math_factorial(PyObject *self, PyObject *arg) { - long i, x; - PyObject *result, *iobj, *newresult; + long i, x; + PyObject *result, *iobj, *newresult; - if (PyFloat_Check(arg)) { - PyObject *lx; - double dx = PyFloat_AS_DOUBLE((PyFloatObject *)arg); - if (!(Py_IS_FINITE(dx) && dx == floor(dx))) { - PyErr_SetString(PyExc_ValueError, - "factorial() only accepts integral values"); - return NULL; - } - lx = PyLong_FromDouble(dx); - if (lx == NULL) - return NULL; - x = PyLong_AsLong(lx); - Py_DECREF(lx); - } - else - x = PyLong_AsLong(arg); - - if (x == -1 && PyErr_Occurred()) - return NULL; - if (x < 0) { - PyErr_SetString(PyExc_ValueError, - "factorial() not defined for negative values"); - return NULL; - } - - result = (PyObject *)PyLong_FromLong(1); - if (result == NULL) - return NULL; - for (i=1 ; i<=x ; i++) { - iobj = (PyObject *)PyLong_FromLong(i); - if (iobj == NULL) - goto error; - newresult = PyNumber_Multiply(result, iobj); - Py_DECREF(iobj); - if (newresult == NULL) - goto error; - Py_DECREF(result); - result = newresult; - } - return result; + if (PyFloat_Check(arg)) { + PyObject *lx; + double dx = PyFloat_AS_DOUBLE((PyFloatObject *)arg); + if (!(Py_IS_FINITE(dx) && dx == floor(dx))) { + PyErr_SetString(PyExc_ValueError, + "factorial() only accepts integral values"); + return NULL; + } + lx = PyLong_FromDouble(dx); + if (lx == NULL) + return NULL; + x = PyLong_AsLong(lx); + Py_DECREF(lx); + } + else + x = PyLong_AsLong(arg); + + if (x == -1 && PyErr_Occurred()) + return NULL; + if (x < 0) { + PyErr_SetString(PyExc_ValueError, + "factorial() not defined for negative values"); + return NULL; + } + + result = (PyObject *)PyLong_FromLong(1); + if (result == NULL) + return NULL; + for (i=1 ; i<=x ; i++) { + iobj = (PyObject *)PyLong_FromLong(i); + if (iobj == NULL) + goto error; + newresult = PyNumber_Multiply(result, iobj); + Py_DECREF(iobj); + if (newresult == NULL) + goto error; + Py_DECREF(result); + result = newresult; + } + return result; error: - Py_DECREF(result); - return NULL; + Py_DECREF(result); + return NULL; } PyDoc_STRVAR(math_factorial_doc, @@ -1189,28 +1189,28 @@ static PyObject * math_trunc(PyObject *self, PyObject *number) { - static PyObject *trunc_str = NULL; - PyObject *trunc; + static PyObject *trunc_str = NULL; + PyObject *trunc; - if (Py_TYPE(number)->tp_dict == NULL) { - if (PyType_Ready(Py_TYPE(number)) < 0) - return NULL; - } - - if (trunc_str == NULL) { - trunc_str = PyUnicode_InternFromString("__trunc__"); - if (trunc_str == NULL) - return NULL; - } - - trunc = _PyType_Lookup(Py_TYPE(number), trunc_str); - if (trunc == NULL) { - PyErr_Format(PyExc_TypeError, - "type %.100s doesn't define __trunc__ method", - Py_TYPE(number)->tp_name); - return NULL; - } - return PyObject_CallFunctionObjArgs(trunc, number, NULL); + if (Py_TYPE(number)->tp_dict == NULL) { + if (PyType_Ready(Py_TYPE(number)) < 0) + return NULL; + } + + if (trunc_str == NULL) { + trunc_str = PyUnicode_InternFromString("__trunc__"); + if (trunc_str == NULL) + return NULL; + } + + trunc = _PyType_Lookup(Py_TYPE(number), trunc_str); + if (trunc == NULL) { + PyErr_Format(PyExc_TypeError, + "type %.100s doesn't define __trunc__ method", + Py_TYPE(number)->tp_name); + return NULL; + } + return PyObject_CallFunctionObjArgs(trunc, number, NULL); } PyDoc_STRVAR(math_trunc_doc, @@ -1221,21 +1221,21 @@ static PyObject * math_frexp(PyObject *self, PyObject *arg) { - int i; - double x = PyFloat_AsDouble(arg); - if (x == -1.0 && PyErr_Occurred()) - return NULL; - /* deal with special cases directly, to sidestep platform - differences */ - if (Py_IS_NAN(x) || Py_IS_INFINITY(x) || !x) { - i = 0; - } - else { - PyFPE_START_PROTECT("in math_frexp", return 0); - x = frexp(x, &i); - PyFPE_END_PROTECT(x); - } - return Py_BuildValue("(di)", x, i); + int i; + double x = PyFloat_AsDouble(arg); + if (x == -1.0 && PyErr_Occurred()) + return NULL; + /* deal with special cases directly, to sidestep platform + differences */ + if (Py_IS_NAN(x) || Py_IS_INFINITY(x) || !x) { + i = 0; + } + else { + PyFPE_START_PROTECT("in math_frexp", return 0); + x = frexp(x, &i); + PyFPE_END_PROTECT(x); + } + return Py_BuildValue("(di)", x, i); } PyDoc_STRVAR(math_frexp_doc, @@ -1248,53 +1248,53 @@ static PyObject * math_ldexp(PyObject *self, PyObject *args) { - double x, r; - PyObject *oexp; - long exp; - int overflow; - if (! PyArg_ParseTuple(args, "dO:ldexp", &x, &oexp)) - return NULL; - - if (PyLong_Check(oexp)) { - /* on overflow, replace exponent with either LONG_MAX - or LONG_MIN, depending on the sign. */ - exp = PyLong_AsLongAndOverflow(oexp, &overflow); - if (exp == -1 && PyErr_Occurred()) - return NULL; - if (overflow) - exp = overflow < 0 ? LONG_MIN : LONG_MAX; - } - else { - PyErr_SetString(PyExc_TypeError, - "Expected an int or long as second argument " - "to ldexp."); - return NULL; - } - - if (x == 0. || !Py_IS_FINITE(x)) { - /* NaNs, zeros and infinities are returned unchanged */ - r = x; - errno = 0; - } else if (exp > INT_MAX) { - /* overflow */ - r = copysign(Py_HUGE_VAL, x); - errno = ERANGE; - } else if (exp < INT_MIN) { - /* underflow to +-0 */ - r = copysign(0., x); - errno = 0; - } else { - errno = 0; - PyFPE_START_PROTECT("in math_ldexp", return 0); - r = ldexp(x, (int)exp); - PyFPE_END_PROTECT(r); - if (Py_IS_INFINITY(r)) - errno = ERANGE; - } - - if (errno && is_error(r)) - return NULL; - return PyFloat_FromDouble(r); + double x, r; + PyObject *oexp; + long exp; + int overflow; + if (! PyArg_ParseTuple(args, "dO:ldexp", &x, &oexp)) + return NULL; + + if (PyLong_Check(oexp)) { + /* on overflow, replace exponent with either LONG_MAX + or LONG_MIN, depending on the sign. */ + exp = PyLong_AsLongAndOverflow(oexp, &overflow); + if (exp == -1 && PyErr_Occurred()) + return NULL; + if (overflow) + exp = overflow < 0 ? LONG_MIN : LONG_MAX; + } + else { + PyErr_SetString(PyExc_TypeError, + "Expected an int or long as second argument " + "to ldexp."); + return NULL; + } + + if (x == 0. || !Py_IS_FINITE(x)) { + /* NaNs, zeros and infinities are returned unchanged */ + r = x; + errno = 0; + } else if (exp > INT_MAX) { + /* overflow */ + r = copysign(Py_HUGE_VAL, x); + errno = ERANGE; + } else if (exp < INT_MIN) { + /* underflow to +-0 */ + r = copysign(0., x); + errno = 0; + } else { + errno = 0; + PyFPE_START_PROTECT("in math_ldexp", return 0); + r = ldexp(x, (int)exp); + PyFPE_END_PROTECT(r); + if (Py_IS_INFINITY(r)) + errno = ERANGE; + } + + if (errno && is_error(r)) + return NULL; + return PyFloat_FromDouble(r); } PyDoc_STRVAR(math_ldexp_doc, @@ -1304,23 +1304,23 @@ static PyObject * math_modf(PyObject *self, PyObject *arg) { - double y, x = PyFloat_AsDouble(arg); - if (x == -1.0 && PyErr_Occurred()) - return NULL; - /* some platforms don't do the right thing for NaNs and - infinities, so we take care of special cases directly. */ - if (!Py_IS_FINITE(x)) { - if (Py_IS_INFINITY(x)) - return Py_BuildValue("(dd)", copysign(0., x), x); - else if (Py_IS_NAN(x)) - return Py_BuildValue("(dd)", x, x); - } - - errno = 0; - PyFPE_START_PROTECT("in math_modf", return 0); - x = modf(x, &y); - PyFPE_END_PROTECT(x); - return Py_BuildValue("(dd)", x, y); + double y, x = PyFloat_AsDouble(arg); + if (x == -1.0 && PyErr_Occurred()) + return NULL; + /* some platforms don't do the right thing for NaNs and + infinities, so we take care of special cases directly. */ + if (!Py_IS_FINITE(x)) { + if (Py_IS_INFINITY(x)) + return Py_BuildValue("(dd)", copysign(0., x), x); + else if (Py_IS_NAN(x)) + return Py_BuildValue("(dd)", x, x); + } + + errno = 0; + PyFPE_START_PROTECT("in math_modf", return 0); + x = modf(x, &y); + PyFPE_END_PROTECT(x); + return Py_BuildValue("(dd)", x, y); } PyDoc_STRVAR(math_modf_doc, @@ -1341,56 +1341,56 @@ static PyObject* loghelper(PyObject* arg, double (*func)(double), char *funcname) { - /* If it is long, do it ourselves. */ - if (PyLong_Check(arg)) { - double x; - Py_ssize_t e; - x = _PyLong_Frexp((PyLongObject *)arg, &e); - if (x == -1.0 && PyErr_Occurred()) - return NULL; - if (x <= 0.0) { - PyErr_SetString(PyExc_ValueError, - "math domain error"); - return NULL; - } - /* Special case for log(1), to make sure we get an - exact result there. */ - if (e == 1 && x == 0.5) - return PyFloat_FromDouble(0.0); - /* Value is ~= x * 2**e, so the log ~= log(x) + log(2) * e. */ - x = func(x) + func(2.0) * e; - return PyFloat_FromDouble(x); - } + /* If it is long, do it ourselves. */ + if (PyLong_Check(arg)) { + double x; + Py_ssize_t e; + x = _PyLong_Frexp((PyLongObject *)arg, &e); + if (x == -1.0 && PyErr_Occurred()) + return NULL; + if (x <= 0.0) { + PyErr_SetString(PyExc_ValueError, + "math domain error"); + return NULL; + } + /* Special case for log(1), to make sure we get an + exact result there. */ + if (e == 1 && x == 0.5) + return PyFloat_FromDouble(0.0); + /* Value is ~= x * 2**e, so the log ~= log(x) + log(2) * e. */ + x = func(x) + func(2.0) * e; + return PyFloat_FromDouble(x); + } - /* Else let libm handle it by itself. */ - return math_1(arg, func, 0); + /* Else let libm handle it by itself. */ + return math_1(arg, func, 0); } static PyObject * math_log(PyObject *self, PyObject *args) { - PyObject *arg; - PyObject *base = NULL; - PyObject *num, *den; - PyObject *ans; - - if (!PyArg_UnpackTuple(args, "log", 1, 2, &arg, &base)) - return NULL; - - num = loghelper(arg, m_log, "log"); - if (num == NULL || base == NULL) - return num; - - den = loghelper(base, m_log, "log"); - if (den == NULL) { - Py_DECREF(num); - return NULL; - } - - ans = PyNumber_TrueDivide(num, den); - Py_DECREF(num); - Py_DECREF(den); - return ans; + PyObject *arg; + PyObject *base = NULL; + PyObject *num, *den; + PyObject *ans; + + if (!PyArg_UnpackTuple(args, "log", 1, 2, &arg, &base)) + return NULL; + + num = loghelper(arg, m_log, "log"); + if (num == NULL || base == NULL) + return num; + + den = loghelper(base, m_log, "log"); + if (den == NULL) { + Py_DECREF(num); + return NULL; + } + + ans = PyNumber_TrueDivide(num, den); + Py_DECREF(num); + Py_DECREF(den); + return ans; } PyDoc_STRVAR(math_log_doc, @@ -1401,7 +1401,7 @@ static PyObject * math_log10(PyObject *self, PyObject *arg) { - return loghelper(arg, m_log10, "log10"); + return loghelper(arg, m_log10, "log10"); } PyDoc_STRVAR(math_log10_doc, @@ -1410,31 +1410,31 @@ static PyObject * math_fmod(PyObject *self, PyObject *args) { - PyObject *ox, *oy; - double r, x, y; - if (! PyArg_UnpackTuple(args, "fmod", 2, 2, &ox, &oy)) - return NULL; - x = PyFloat_AsDouble(ox); - y = PyFloat_AsDouble(oy); - if ((x == -1.0 || y == -1.0) && PyErr_Occurred()) - return NULL; - /* fmod(x, +/-Inf) returns x for finite x. */ - if (Py_IS_INFINITY(y) && Py_IS_FINITE(x)) - return PyFloat_FromDouble(x); - errno = 0; - PyFPE_START_PROTECT("in math_fmod", return 0); - r = fmod(x, y); - PyFPE_END_PROTECT(r); - if (Py_IS_NAN(r)) { - if (!Py_IS_NAN(x) && !Py_IS_NAN(y)) - errno = EDOM; - else - errno = 0; - } - if (errno && is_error(r)) - return NULL; - else - return PyFloat_FromDouble(r); + PyObject *ox, *oy; + double r, x, y; + if (! PyArg_UnpackTuple(args, "fmod", 2, 2, &ox, &oy)) + return NULL; + x = PyFloat_AsDouble(ox); + y = PyFloat_AsDouble(oy); + if ((x == -1.0 || y == -1.0) && PyErr_Occurred()) + return NULL; + /* fmod(x, +/-Inf) returns x for finite x. */ + if (Py_IS_INFINITY(y) && Py_IS_FINITE(x)) + return PyFloat_FromDouble(x); + errno = 0; + PyFPE_START_PROTECT("in math_fmod", return 0); + r = fmod(x, y); + PyFPE_END_PROTECT(r); + if (Py_IS_NAN(r)) { + if (!Py_IS_NAN(x) && !Py_IS_NAN(y)) + errno = EDOM; + else + errno = 0; + } + if (errno && is_error(r)) + return NULL; + else + return PyFloat_FromDouble(r); } PyDoc_STRVAR(math_fmod_doc, @@ -1444,39 +1444,39 @@ static PyObject * math_hypot(PyObject *self, PyObject *args) { - PyObject *ox, *oy; - double r, x, y; - if (! PyArg_UnpackTuple(args, "hypot", 2, 2, &ox, &oy)) - return NULL; - x = PyFloat_AsDouble(ox); - y = PyFloat_AsDouble(oy); - if ((x == -1.0 || y == -1.0) && PyErr_Occurred()) - return NULL; - /* hypot(x, +/-Inf) returns Inf, even if x is a NaN. */ - if (Py_IS_INFINITY(x)) - return PyFloat_FromDouble(fabs(x)); - if (Py_IS_INFINITY(y)) - return PyFloat_FromDouble(fabs(y)); - errno = 0; - PyFPE_START_PROTECT("in math_hypot", return 0); - r = hypot(x, y); - PyFPE_END_PROTECT(r); - if (Py_IS_NAN(r)) { - if (!Py_IS_NAN(x) && !Py_IS_NAN(y)) - errno = EDOM; - else - errno = 0; - } - else if (Py_IS_INFINITY(r)) { - if (Py_IS_FINITE(x) && Py_IS_FINITE(y)) - errno = ERANGE; - else - errno = 0; - } - if (errno && is_error(r)) - return NULL; - else - return PyFloat_FromDouble(r); + PyObject *ox, *oy; + double r, x, y; + if (! PyArg_UnpackTuple(args, "hypot", 2, 2, &ox, &oy)) + return NULL; + x = PyFloat_AsDouble(ox); + y = PyFloat_AsDouble(oy); + if ((x == -1.0 || y == -1.0) && PyErr_Occurred()) + return NULL; + /* hypot(x, +/-Inf) returns Inf, even if x is a NaN. */ + if (Py_IS_INFINITY(x)) + return PyFloat_FromDouble(fabs(x)); + if (Py_IS_INFINITY(y)) + return PyFloat_FromDouble(fabs(y)); + errno = 0; + PyFPE_START_PROTECT("in math_hypot", return 0); + r = hypot(x, y); + PyFPE_END_PROTECT(r); + if (Py_IS_NAN(r)) { + if (!Py_IS_NAN(x) && !Py_IS_NAN(y)) + errno = EDOM; + else + errno = 0; + } + else if (Py_IS_INFINITY(r)) { + if (Py_IS_FINITE(x) && Py_IS_FINITE(y)) + errno = ERANGE; + else + errno = 0; + } + if (errno && is_error(r)) + return NULL; + else + return PyFloat_FromDouble(r); } PyDoc_STRVAR(math_hypot_doc, @@ -1491,79 +1491,79 @@ static PyObject * math_pow(PyObject *self, PyObject *args) { - PyObject *ox, *oy; - double r, x, y; - int odd_y; - - if (! PyArg_UnpackTuple(args, "pow", 2, 2, &ox, &oy)) - return NULL; - x = PyFloat_AsDouble(ox); - y = PyFloat_AsDouble(oy); - if ((x == -1.0 || y == -1.0) && PyErr_Occurred()) - return NULL; - - /* deal directly with IEEE specials, to cope with problems on various - platforms whose semantics don't exactly match C99 */ - r = 0.; /* silence compiler warning */ - if (!Py_IS_FINITE(x) || !Py_IS_FINITE(y)) { - errno = 0; - if (Py_IS_NAN(x)) - r = y == 0. ? 1. : x; /* NaN**0 = 1 */ - else if (Py_IS_NAN(y)) - r = x == 1. ? 1. : y; /* 1**NaN = 1 */ - else if (Py_IS_INFINITY(x)) { - odd_y = Py_IS_FINITE(y) && fmod(fabs(y), 2.0) == 1.0; - if (y > 0.) - r = odd_y ? x : fabs(x); - else if (y == 0.) - r = 1.; - else /* y < 0. */ - r = odd_y ? copysign(0., x) : 0.; - } - else if (Py_IS_INFINITY(y)) { - if (fabs(x) == 1.0) - r = 1.; - else if (y > 0. && fabs(x) > 1.0) - r = y; - else if (y < 0. && fabs(x) < 1.0) { - r = -y; /* result is +inf */ - if (x == 0.) /* 0**-inf: divide-by-zero */ - errno = EDOM; - } - else - r = 0.; - } - } - else { - /* let libm handle finite**finite */ - errno = 0; - PyFPE_START_PROTECT("in math_pow", return 0); - r = pow(x, y); - PyFPE_END_PROTECT(r); - /* a NaN result should arise only from (-ve)**(finite - non-integer); in this case we want to raise ValueError. */ - if (!Py_IS_FINITE(r)) { - if (Py_IS_NAN(r)) { - errno = EDOM; - } - /* - an infinite result here arises either from: - (A) (+/-0.)**negative (-> divide-by-zero) - (B) overflow of x**y with x and y finite - */ - else if (Py_IS_INFINITY(r)) { - if (x == 0.) - errno = EDOM; - else - errno = ERANGE; - } - } - } - - if (errno && is_error(r)) - return NULL; - else - return PyFloat_FromDouble(r); + PyObject *ox, *oy; + double r, x, y; + int odd_y; + + if (! PyArg_UnpackTuple(args, "pow", 2, 2, &ox, &oy)) + return NULL; + x = PyFloat_AsDouble(ox); + y = PyFloat_AsDouble(oy); + if ((x == -1.0 || y == -1.0) && PyErr_Occurred()) + return NULL; + + /* deal directly with IEEE specials, to cope with problems on various + platforms whose semantics don't exactly match C99 */ + r = 0.; /* silence compiler warning */ + if (!Py_IS_FINITE(x) || !Py_IS_FINITE(y)) { + errno = 0; + if (Py_IS_NAN(x)) + r = y == 0. ? 1. : x; /* NaN**0 = 1 */ + else if (Py_IS_NAN(y)) + r = x == 1. ? 1. : y; /* 1**NaN = 1 */ + else if (Py_IS_INFINITY(x)) { + odd_y = Py_IS_FINITE(y) && fmod(fabs(y), 2.0) == 1.0; + if (y > 0.) + r = odd_y ? x : fabs(x); + else if (y == 0.) + r = 1.; + else /* y < 0. */ + r = odd_y ? copysign(0., x) : 0.; + } + else if (Py_IS_INFINITY(y)) { + if (fabs(x) == 1.0) + r = 1.; + else if (y > 0. && fabs(x) > 1.0) + r = y; + else if (y < 0. && fabs(x) < 1.0) { + r = -y; /* result is +inf */ + if (x == 0.) /* 0**-inf: divide-by-zero */ + errno = EDOM; + } + else + r = 0.; + } + } + else { + /* let libm handle finite**finite */ + errno = 0; + PyFPE_START_PROTECT("in math_pow", return 0); + r = pow(x, y); + PyFPE_END_PROTECT(r); + /* a NaN result should arise only from (-ve)**(finite + non-integer); in this case we want to raise ValueError. */ + if (!Py_IS_FINITE(r)) { + if (Py_IS_NAN(r)) { + errno = EDOM; + } + /* + an infinite result here arises either from: + (A) (+/-0.)**negative (-> divide-by-zero) + (B) overflow of x**y with x and y finite + */ + else if (Py_IS_INFINITY(r)) { + if (x == 0.) + errno = EDOM; + else + errno = ERANGE; + } + } + } + + if (errno && is_error(r)) + return NULL; + else + return PyFloat_FromDouble(r); } PyDoc_STRVAR(math_pow_doc, @@ -1575,10 +1575,10 @@ static PyObject * math_degrees(PyObject *self, PyObject *arg) { - double x = PyFloat_AsDouble(arg); - if (x == -1.0 && PyErr_Occurred()) - return NULL; - return PyFloat_FromDouble(x * radToDeg); + double x = PyFloat_AsDouble(arg); + if (x == -1.0 && PyErr_Occurred()) + return NULL; + return PyFloat_FromDouble(x * radToDeg); } PyDoc_STRVAR(math_degrees_doc, @@ -1588,10 +1588,10 @@ static PyObject * math_radians(PyObject *self, PyObject *arg) { - double x = PyFloat_AsDouble(arg); - if (x == -1.0 && PyErr_Occurred()) - return NULL; - return PyFloat_FromDouble(x * degToRad); + double x = PyFloat_AsDouble(arg); + if (x == -1.0 && PyErr_Occurred()) + return NULL; + return PyFloat_FromDouble(x * degToRad); } PyDoc_STRVAR(math_radians_doc, @@ -1601,10 +1601,10 @@ static PyObject * math_isnan(PyObject *self, PyObject *arg) { - double x = PyFloat_AsDouble(arg); - if (x == -1.0 && PyErr_Occurred()) - return NULL; - return PyBool_FromLong((long)Py_IS_NAN(x)); + double x = PyFloat_AsDouble(arg); + if (x == -1.0 && PyErr_Occurred()) + return NULL; + return PyBool_FromLong((long)Py_IS_NAN(x)); } PyDoc_STRVAR(math_isnan_doc, @@ -1614,10 +1614,10 @@ static PyObject * math_isinf(PyObject *self, PyObject *arg) { - double x = PyFloat_AsDouble(arg); - if (x == -1.0 && PyErr_Occurred()) - return NULL; - return PyBool_FromLong((long)Py_IS_INFINITY(x)); + double x = PyFloat_AsDouble(arg); + if (x == -1.0 && PyErr_Occurred()) + return NULL; + return PyBool_FromLong((long)Py_IS_INFINITY(x)); } PyDoc_STRVAR(math_isinf_doc, @@ -1625,47 +1625,47 @@ Check if float x is infinite (positive or negative)."); static PyMethodDef math_methods[] = { - {"acos", math_acos, METH_O, math_acos_doc}, - {"acosh", math_acosh, METH_O, math_acosh_doc}, - {"asin", math_asin, METH_O, math_asin_doc}, - {"asinh", math_asinh, METH_O, math_asinh_doc}, - {"atan", math_atan, METH_O, math_atan_doc}, - {"atan2", math_atan2, METH_VARARGS, math_atan2_doc}, - {"atanh", math_atanh, METH_O, math_atanh_doc}, - {"ceil", math_ceil, METH_O, math_ceil_doc}, - {"copysign", math_copysign, METH_VARARGS, math_copysign_doc}, - {"cos", math_cos, METH_O, math_cos_doc}, - {"cosh", math_cosh, METH_O, math_cosh_doc}, - {"degrees", math_degrees, METH_O, math_degrees_doc}, - {"erf", math_erf, METH_O, math_erf_doc}, - {"erfc", math_erfc, METH_O, math_erfc_doc}, - {"exp", math_exp, METH_O, math_exp_doc}, - {"expm1", math_expm1, METH_O, math_expm1_doc}, - {"fabs", math_fabs, METH_O, math_fabs_doc}, - {"factorial", math_factorial, METH_O, math_factorial_doc}, - {"floor", math_floor, METH_O, math_floor_doc}, - {"fmod", math_fmod, METH_VARARGS, math_fmod_doc}, - {"frexp", math_frexp, METH_O, math_frexp_doc}, - {"fsum", math_fsum, METH_O, math_fsum_doc}, - {"gamma", math_gamma, METH_O, math_gamma_doc}, - {"hypot", math_hypot, METH_VARARGS, math_hypot_doc}, - {"isinf", math_isinf, METH_O, math_isinf_doc}, - {"isnan", math_isnan, METH_O, math_isnan_doc}, - {"ldexp", math_ldexp, METH_VARARGS, math_ldexp_doc}, - {"lgamma", math_lgamma, METH_O, math_lgamma_doc}, - {"log", math_log, METH_VARARGS, math_log_doc}, - {"log1p", math_log1p, METH_O, math_log1p_doc}, - {"log10", math_log10, METH_O, math_log10_doc}, - {"modf", math_modf, METH_O, math_modf_doc}, - {"pow", math_pow, METH_VARARGS, math_pow_doc}, - {"radians", math_radians, METH_O, math_radians_doc}, - {"sin", math_sin, METH_O, math_sin_doc}, - {"sinh", math_sinh, METH_O, math_sinh_doc}, - {"sqrt", math_sqrt, METH_O, math_sqrt_doc}, - {"tan", math_tan, METH_O, math_tan_doc}, - {"tanh", math_tanh, METH_O, math_tanh_doc}, - {"trunc", math_trunc, METH_O, math_trunc_doc}, - {NULL, NULL} /* sentinel */ + {"acos", math_acos, METH_O, math_acos_doc}, + {"acosh", math_acosh, METH_O, math_acosh_doc}, + {"asin", math_asin, METH_O, math_asin_doc}, + {"asinh", math_asinh, METH_O, math_asinh_doc}, + {"atan", math_atan, METH_O, math_atan_doc}, + {"atan2", math_atan2, METH_VARARGS, math_atan2_doc}, + {"atanh", math_atanh, METH_O, math_atanh_doc}, + {"ceil", math_ceil, METH_O, math_ceil_doc}, + {"copysign", math_copysign, METH_VARARGS, math_copysign_doc}, + {"cos", math_cos, METH_O, math_cos_doc}, + {"cosh", math_cosh, METH_O, math_cosh_doc}, + {"degrees", math_degrees, METH_O, math_degrees_doc}, + {"erf", math_erf, METH_O, math_erf_doc}, + {"erfc", math_erfc, METH_O, math_erfc_doc}, + {"exp", math_exp, METH_O, math_exp_doc}, + {"expm1", math_expm1, METH_O, math_expm1_doc}, + {"fabs", math_fabs, METH_O, math_fabs_doc}, + {"factorial", math_factorial, METH_O, math_factorial_doc}, + {"floor", math_floor, METH_O, math_floor_doc}, + {"fmod", math_fmod, METH_VARARGS, math_fmod_doc}, + {"frexp", math_frexp, METH_O, math_frexp_doc}, + {"fsum", math_fsum, METH_O, math_fsum_doc}, + {"gamma", math_gamma, METH_O, math_gamma_doc}, + {"hypot", math_hypot, METH_VARARGS, math_hypot_doc}, + {"isinf", math_isinf, METH_O, math_isinf_doc}, + {"isnan", math_isnan, METH_O, math_isnan_doc}, + {"ldexp", math_ldexp, METH_VARARGS, math_ldexp_doc}, + {"lgamma", math_lgamma, METH_O, math_lgamma_doc}, + {"log", math_log, METH_VARARGS, math_log_doc}, + {"log1p", math_log1p, METH_O, math_log1p_doc}, + {"log10", math_log10, METH_O, math_log10_doc}, + {"modf", math_modf, METH_O, math_modf_doc}, + {"pow", math_pow, METH_VARARGS, math_pow_doc}, + {"radians", math_radians, METH_O, math_radians_doc}, + {"sin", math_sin, METH_O, math_sin_doc}, + {"sinh", math_sinh, METH_O, math_sinh_doc}, + {"sqrt", math_sqrt, METH_O, math_sqrt_doc}, + {"tan", math_tan, METH_O, math_tan_doc}, + {"tanh", math_tanh, METH_O, math_tanh_doc}, + {"trunc", math_trunc, METH_O, math_trunc_doc}, + {NULL, NULL} /* sentinel */ }; @@ -1675,29 +1675,29 @@ static struct PyModuleDef mathmodule = { - PyModuleDef_HEAD_INIT, - "math", - module_doc, - -1, - math_methods, - NULL, - NULL, - NULL, - NULL + PyModuleDef_HEAD_INIT, + "math", + module_doc, + -1, + math_methods, + NULL, + NULL, + NULL, + NULL }; PyMODINIT_FUNC PyInit_math(void) { - PyObject *m; + PyObject *m; - m = PyModule_Create(&mathmodule); - if (m == NULL) - goto finally; + m = PyModule_Create(&mathmodule); + if (m == NULL) + goto finally; - PyModule_AddObject(m, "pi", PyFloat_FromDouble(Py_MATH_PI)); - PyModule_AddObject(m, "e", PyFloat_FromDouble(Py_MATH_E)); + PyModule_AddObject(m, "pi", PyFloat_FromDouble(Py_MATH_PI)); + PyModule_AddObject(m, "e", PyFloat_FromDouble(Py_MATH_E)); finally: - return m; + return m; } Modified: python/branches/py3k-jit/Modules/md5module.c ============================================================================== --- python/branches/py3k-jit/Modules/md5module.c (original) +++ python/branches/py3k-jit/Modules/md5module.c Mon May 10 23:55:43 2010 @@ -23,8 +23,8 @@ /* Some useful types */ #if SIZEOF_INT == 4 -typedef unsigned int MD5_INT32; /* 32-bit integer */ -typedef PY_LONG_LONG MD5_INT64; /* 64-bit integer */ +typedef unsigned int MD5_INT32; /* 32-bit integer */ +typedef PY_LONG_LONG MD5_INT64; /* 64-bit integer */ #else /* not defined. compilation will die. */ #endif @@ -127,7 +127,7 @@ for (i = 0; i < 16; i++) { LOAD32L(W[i], buf + (4*i)); } - + /* copy state */ a = md5->state[0]; b = md5->state[1]; @@ -386,21 +386,21 @@ /* Create a new string */ retval = PyUnicode_FromStringAndSize(NULL, MD5_DIGESTSIZE * 2); if (!retval) - return NULL; + return NULL; hex_digest = PyUnicode_AS_UNICODE(retval); if (!hex_digest) { - Py_DECREF(retval); - return NULL; + Py_DECREF(retval); + return NULL; } /* Make hex version of the digest */ for(i=j=0; i> 4) & 0xf; - c = (c>9) ? c+'a'-10 : c + '0'; + c = (c>9) ? c+'a'-10 : c + '0'; hex_digest[j++] = c; c = (digest[i] & 0xf); - c = (c>9) ? c+'a'-10 : c + '0'; + c = (c>9) ? c+'a'-10 : c + '0'; hex_digest[j++] = c; } return retval; @@ -414,7 +414,7 @@ { PyObject *obj; Py_buffer buf; - + if (!PyArg_ParseTuple(args, "O:update", &obj)) return NULL; @@ -428,11 +428,11 @@ } static PyMethodDef MD5_methods[] = { - {"copy", (PyCFunction)MD5_copy, METH_NOARGS, MD5_copy__doc__}, - {"digest", (PyCFunction)MD5_digest, METH_NOARGS, MD5_digest__doc__}, + {"copy", (PyCFunction)MD5_copy, METH_NOARGS, MD5_copy__doc__}, + {"digest", (PyCFunction)MD5_digest, METH_NOARGS, MD5_digest__doc__}, {"hexdigest", (PyCFunction)MD5_hexdigest, METH_NOARGS, MD5_hexdigest__doc__}, - {"update", (PyCFunction)MD5_update, METH_VARARGS, MD5_update__doc__}, - {NULL, NULL} /* sentinel */ + {"update", (PyCFunction)MD5_update, METH_VARARGS, MD5_update__doc__}, + {NULL, NULL} /* sentinel */ }; static PyObject * @@ -472,13 +472,13 @@ static PyTypeObject MD5type = { PyVarObject_HEAD_INIT(NULL, 0) - "_md5.md5", /*tp_name*/ - sizeof(MD5object), /*tp_size*/ - 0, /*tp_itemsize*/ + "_md5.md5", /*tp_name*/ + sizeof(MD5object), /*tp_size*/ + 0, /*tp_itemsize*/ /* methods */ - MD5_dealloc, /*tp_dealloc*/ - 0, /*tp_print*/ - 0, /*tp_getattr*/ + MD5_dealloc, /*tp_dealloc*/ + 0, /*tp_print*/ + 0, /*tp_getattr*/ 0, /*tp_setattr*/ 0, /*tp_reserved*/ 0, /*tp_repr*/ @@ -494,13 +494,13 @@ Py_TPFLAGS_DEFAULT, /*tp_flags*/ 0, /*tp_doc*/ 0, /*tp_traverse*/ - 0, /*tp_clear*/ - 0, /*tp_richcompare*/ - 0, /*tp_weaklistoffset*/ - 0, /*tp_iter*/ - 0, /*tp_iternext*/ - MD5_methods, /* tp_methods */ - NULL, /* tp_members */ + 0, /*tp_clear*/ + 0, /*tp_richcompare*/ + 0, /*tp_weaklistoffset*/ + 0, /*tp_iter*/ + 0, /*tp_iternext*/ + MD5_methods, /* tp_methods */ + NULL, /* tp_members */ MD5_getseters, /* tp_getset */ }; @@ -553,7 +553,7 @@ static struct PyMethodDef MD5_functions[] = { {"md5", (PyCFunction)MD5_new, METH_VARARGS|METH_KEYWORDS, MD5_new__doc__}, - {NULL, NULL} /* Sentinel */ + {NULL, NULL} /* Sentinel */ }; @@ -563,15 +563,15 @@ static struct PyModuleDef _md5module = { - PyModuleDef_HEAD_INIT, - "_md5", - NULL, - -1, - MD5_functions, - NULL, - NULL, - NULL, - NULL + PyModuleDef_HEAD_INIT, + "_md5", + NULL, + -1, + MD5_functions, + NULL, + NULL, + NULL, + NULL }; PyMODINIT_FUNC Modified: python/branches/py3k-jit/Modules/mmapmodule.c ============================================================================== --- python/branches/py3k-jit/Modules/mmapmodule.c (original) +++ python/branches/py3k-jit/Modules/mmapmodule.c Mon May 10 23:55:43 2010 @@ -30,18 +30,18 @@ static int my_getpagesize(void) { - SYSTEM_INFO si; - GetSystemInfo(&si); - return si.dwPageSize; + SYSTEM_INFO si; + GetSystemInfo(&si); + return si.dwPageSize; } static int my_getallocationgranularity (void) { - SYSTEM_INFO si; - GetSystemInfo(&si); - return si.dwAllocationGranularity; + SYSTEM_INFO si; + GetSystemInfo(&si); + return si.dwAllocationGranularity; } #endif @@ -54,7 +54,7 @@ static int my_getpagesize(void) { - return sysconf(_SC_PAGESIZE); + return sysconf(_SC_PAGESIZE); } #define my_getallocationgranularity my_getpagesize @@ -79,31 +79,31 @@ typedef enum { - ACCESS_DEFAULT, - ACCESS_READ, - ACCESS_WRITE, - ACCESS_COPY + ACCESS_DEFAULT, + ACCESS_READ, + ACCESS_WRITE, + ACCESS_COPY } access_mode; typedef struct { - PyObject_HEAD - char * data; - size_t size; - size_t pos; /* relative to offset */ - size_t offset; - int exports; + PyObject_HEAD + char * data; + size_t size; + size_t pos; /* relative to offset */ + size_t offset; + int exports; #ifdef MS_WINDOWS - HANDLE map_handle; - HANDLE file_handle; - char * tagname; + HANDLE map_handle; + HANDLE file_handle; + char * tagname; #endif #ifdef UNIX - int fd; + int fd; #endif - access_mode access; + access_mode access; } mmap_object; @@ -111,331 +111,331 @@ mmap_object_dealloc(mmap_object *m_obj) { #ifdef MS_WINDOWS - if (m_obj->data != NULL) - UnmapViewOfFile (m_obj->data); - if (m_obj->map_handle != NULL) - CloseHandle (m_obj->map_handle); - if (m_obj->file_handle != INVALID_HANDLE_VALUE) - CloseHandle (m_obj->file_handle); - if (m_obj->tagname) - PyMem_Free(m_obj->tagname); + if (m_obj->data != NULL) + UnmapViewOfFile (m_obj->data); + if (m_obj->map_handle != NULL) + CloseHandle (m_obj->map_handle); + if (m_obj->file_handle != INVALID_HANDLE_VALUE) + CloseHandle (m_obj->file_handle); + if (m_obj->tagname) + PyMem_Free(m_obj->tagname); #endif /* MS_WINDOWS */ #ifdef UNIX - if (m_obj->fd >= 0) - (void) close(m_obj->fd); - if (m_obj->data!=NULL) { - msync(m_obj->data, m_obj->size, MS_SYNC); - munmap(m_obj->data, m_obj->size); - } + if (m_obj->fd >= 0) + (void) close(m_obj->fd); + if (m_obj->data!=NULL) { + msync(m_obj->data, m_obj->size, MS_SYNC); + munmap(m_obj->data, m_obj->size); + } #endif /* UNIX */ - Py_TYPE(m_obj)->tp_free((PyObject*)m_obj); + Py_TYPE(m_obj)->tp_free((PyObject*)m_obj); } static PyObject * mmap_close_method(mmap_object *self, PyObject *unused) { - if (self->exports > 0) { - PyErr_SetString(PyExc_BufferError, "cannot close "\ - "exported pointers exist"); - return NULL; - } + if (self->exports > 0) { + PyErr_SetString(PyExc_BufferError, "cannot close "\ + "exported pointers exist"); + return NULL; + } #ifdef MS_WINDOWS - /* For each resource we maintain, we need to check - the value is valid, and if so, free the resource - and set the member value to an invalid value so - the dealloc does not attempt to resource clearing - again. - TODO - should we check for errors in the close operations??? - */ - if (self->data != NULL) { - UnmapViewOfFile(self->data); - self->data = NULL; - } - if (self->map_handle != NULL) { - CloseHandle(self->map_handle); - self->map_handle = NULL; - } - if (self->file_handle != INVALID_HANDLE_VALUE) { - CloseHandle(self->file_handle); - self->file_handle = INVALID_HANDLE_VALUE; - } + /* For each resource we maintain, we need to check + the value is valid, and if so, free the resource + and set the member value to an invalid value so + the dealloc does not attempt to resource clearing + again. + TODO - should we check for errors in the close operations??? + */ + if (self->data != NULL) { + UnmapViewOfFile(self->data); + self->data = NULL; + } + if (self->map_handle != NULL) { + CloseHandle(self->map_handle); + self->map_handle = NULL; + } + if (self->file_handle != INVALID_HANDLE_VALUE) { + CloseHandle(self->file_handle); + self->file_handle = INVALID_HANDLE_VALUE; + } #endif /* MS_WINDOWS */ #ifdef UNIX - if (0 <= self->fd) - (void) close(self->fd); - self->fd = -1; - if (self->data != NULL) { - munmap(self->data, self->size); - self->data = NULL; - } + if (0 <= self->fd) + (void) close(self->fd); + self->fd = -1; + if (self->data != NULL) { + munmap(self->data, self->size); + self->data = NULL; + } #endif - Py_INCREF(Py_None); - return Py_None; + Py_INCREF(Py_None); + return Py_None; } #ifdef MS_WINDOWS -#define CHECK_VALID(err) \ -do { \ - if (self->map_handle == NULL) { \ - PyErr_SetString(PyExc_ValueError, "mmap closed or invalid"); \ - return err; \ - } \ +#define CHECK_VALID(err) \ +do { \ + if (self->map_handle == NULL) { \ + PyErr_SetString(PyExc_ValueError, "mmap closed or invalid"); \ + return err; \ + } \ } while (0) #endif /* MS_WINDOWS */ #ifdef UNIX -#define CHECK_VALID(err) \ -do { \ - if (self->data == NULL) { \ - PyErr_SetString(PyExc_ValueError, "mmap closed or invalid"); \ - return err; \ - } \ +#define CHECK_VALID(err) \ +do { \ + if (self->data == NULL) { \ + PyErr_SetString(PyExc_ValueError, "mmap closed or invalid"); \ + return err; \ + } \ } while (0) #endif /* UNIX */ static PyObject * mmap_read_byte_method(mmap_object *self, - PyObject *unused) + PyObject *unused) { - CHECK_VALID(NULL); - if (self->pos < self->size) { - char value = self->data[self->pos]; - self->pos += 1; - return Py_BuildValue("b", value); - } else { - PyErr_SetString(PyExc_ValueError, "read byte out of range"); - return NULL; - } + CHECK_VALID(NULL); + if (self->pos < self->size) { + char value = self->data[self->pos]; + self->pos += 1; + return Py_BuildValue("b", value); + } else { + PyErr_SetString(PyExc_ValueError, "read byte out of range"); + return NULL; + } } static PyObject * mmap_read_line_method(mmap_object *self, - PyObject *unused) + PyObject *unused) { - char *start = self->data+self->pos; - char *eof = self->data+self->size; - char *eol; - PyObject *result; - - CHECK_VALID(NULL); - - eol = memchr(start, '\n', self->size - self->pos); - if (!eol) - eol = eof; - else - ++eol; /* we're interested in the position after the - newline. */ - result = PyBytes_FromStringAndSize(start, (eol - start)); - self->pos += (eol - start); - return result; + char *start = self->data+self->pos; + char *eof = self->data+self->size; + char *eol; + PyObject *result; + + CHECK_VALID(NULL); + + eol = memchr(start, '\n', self->size - self->pos); + if (!eol) + eol = eof; + else + ++eol; /* we're interested in the position after the + newline. */ + result = PyBytes_FromStringAndSize(start, (eol - start)); + self->pos += (eol - start); + return result; } static PyObject * mmap_read_method(mmap_object *self, - PyObject *args) + PyObject *args) { - Py_ssize_t num_bytes, n; - PyObject *result; + Py_ssize_t num_bytes, n; + PyObject *result; - CHECK_VALID(NULL); - if (!PyArg_ParseTuple(args, "n:read", &num_bytes)) - return(NULL); - - /* silently 'adjust' out-of-range requests */ - assert(self->size >= self->pos); - n = self->size - self->pos; - /* The difference can overflow, only if self->size is greater than - * PY_SSIZE_T_MAX. But then the operation cannot possibly succeed, - * because the mapped area and the returned string each need more - * than half of the addressable memory. So we clip the size, and let - * the code below raise MemoryError. - */ - if (n < 0) - n = PY_SSIZE_T_MAX; - if (num_bytes < 0 || num_bytes > n) { - num_bytes = n; - } - result = PyBytes_FromStringAndSize(self->data+self->pos, num_bytes); - self->pos += num_bytes; - return result; + CHECK_VALID(NULL); + if (!PyArg_ParseTuple(args, "n:read", &num_bytes)) + return(NULL); + + /* silently 'adjust' out-of-range requests */ + assert(self->size >= self->pos); + n = self->size - self->pos; + /* The difference can overflow, only if self->size is greater than + * PY_SSIZE_T_MAX. But then the operation cannot possibly succeed, + * because the mapped area and the returned string each need more + * than half of the addressable memory. So we clip the size, and let + * the code below raise MemoryError. + */ + if (n < 0) + n = PY_SSIZE_T_MAX; + if (num_bytes < 0 || num_bytes > n) { + num_bytes = n; + } + result = PyBytes_FromStringAndSize(self->data+self->pos, num_bytes); + self->pos += num_bytes; + return result; } static PyObject * mmap_gfind(mmap_object *self, - PyObject *args, - int reverse) + PyObject *args, + int reverse) { - Py_ssize_t start = self->pos; - Py_ssize_t end = self->size; - const char *needle; - Py_ssize_t len; - - CHECK_VALID(NULL); - if (!PyArg_ParseTuple(args, reverse ? "y#|nn:rfind" : "y#|nn:find", - &needle, &len, &start, &end)) { - return NULL; - } else { - const char *p, *start_p, *end_p; - int sign = reverse ? -1 : 1; - - if (start < 0) - start += self->size; - if (start < 0) - start = 0; - else if ((size_t)start > self->size) - start = self->size; - - if (end < 0) - end += self->size; - if (end < 0) - end = 0; - else if ((size_t)end > self->size) - end = self->size; - - start_p = self->data + start; - end_p = self->data + end; - - for (p = (reverse ? end_p - len : start_p); - (p >= start_p) && (p + len <= end_p); p += sign) { - Py_ssize_t i; - for (i = 0; i < len && needle[i] == p[i]; ++i) - /* nothing */; - if (i == len) { - return PyLong_FromSsize_t(p - self->data); - } - } - return PyLong_FromLong(-1); - } + Py_ssize_t start = self->pos; + Py_ssize_t end = self->size; + const char *needle; + Py_ssize_t len; + + CHECK_VALID(NULL); + if (!PyArg_ParseTuple(args, reverse ? "y#|nn:rfind" : "y#|nn:find", + &needle, &len, &start, &end)) { + return NULL; + } else { + const char *p, *start_p, *end_p; + int sign = reverse ? -1 : 1; + + if (start < 0) + start += self->size; + if (start < 0) + start = 0; + else if ((size_t)start > self->size) + start = self->size; + + if (end < 0) + end += self->size; + if (end < 0) + end = 0; + else if ((size_t)end > self->size) + end = self->size; + + start_p = self->data + start; + end_p = self->data + end; + + for (p = (reverse ? end_p - len : start_p); + (p >= start_p) && (p + len <= end_p); p += sign) { + Py_ssize_t i; + for (i = 0; i < len && needle[i] == p[i]; ++i) + /* nothing */; + if (i == len) { + return PyLong_FromSsize_t(p - self->data); + } + } + return PyLong_FromLong(-1); + } } static PyObject * mmap_find_method(mmap_object *self, - PyObject *args) + PyObject *args) { - return mmap_gfind(self, args, 0); + return mmap_gfind(self, args, 0); } static PyObject * mmap_rfind_method(mmap_object *self, - PyObject *args) + PyObject *args) { - return mmap_gfind(self, args, 1); + return mmap_gfind(self, args, 1); } static int is_writable(mmap_object *self) { - if (self->access != ACCESS_READ) - return 1; - PyErr_Format(PyExc_TypeError, "mmap can't modify a readonly memory map."); - return 0; + if (self->access != ACCESS_READ) + return 1; + PyErr_Format(PyExc_TypeError, "mmap can't modify a readonly memory map."); + return 0; } static int is_resizeable(mmap_object *self) { - if (self->exports > 0) { - PyErr_SetString(PyExc_BufferError, - "mmap can't resize with extant buffers exported."); - return 0; - } - if ((self->access == ACCESS_WRITE) || (self->access == ACCESS_DEFAULT)) - return 1; - PyErr_Format(PyExc_TypeError, - "mmap can't resize a readonly or copy-on-write memory map."); - return 0; + if (self->exports > 0) { + PyErr_SetString(PyExc_BufferError, + "mmap can't resize with extant buffers exported."); + return 0; + } + if ((self->access == ACCESS_WRITE) || (self->access == ACCESS_DEFAULT)) + return 1; + PyErr_Format(PyExc_TypeError, + "mmap can't resize a readonly or copy-on-write memory map."); + return 0; } static PyObject * mmap_write_method(mmap_object *self, - PyObject *args) + PyObject *args) { - Py_ssize_t length; - char *data; + Py_ssize_t length; + char *data; - CHECK_VALID(NULL); - if (!PyArg_ParseTuple(args, "y#:write", &data, &length)) - return(NULL); - - if (!is_writable(self)) - return NULL; - - if ((self->pos + length) > self->size) { - PyErr_SetString(PyExc_ValueError, "data out of range"); - return NULL; - } - memcpy(self->data+self->pos, data, length); - self->pos = self->pos+length; - Py_INCREF(Py_None); - return Py_None; + CHECK_VALID(NULL); + if (!PyArg_ParseTuple(args, "y#:write", &data, &length)) + return(NULL); + + if (!is_writable(self)) + return NULL; + + if ((self->pos + length) > self->size) { + PyErr_SetString(PyExc_ValueError, "data out of range"); + return NULL; + } + memcpy(self->data+self->pos, data, length); + self->pos = self->pos+length; + Py_INCREF(Py_None); + return Py_None; } static PyObject * mmap_write_byte_method(mmap_object *self, - PyObject *args) + PyObject *args) { - char value; + char value; - CHECK_VALID(NULL); - if (!PyArg_ParseTuple(args, "b:write_byte", &value)) - return(NULL); - - if (!is_writable(self)) - return NULL; - - if (self->pos < self->size) { - *(self->data+self->pos) = value; - self->pos += 1; - Py_INCREF(Py_None); - return Py_None; - } - else { - PyErr_SetString(PyExc_ValueError, "write byte out of range"); - return NULL; - } + CHECK_VALID(NULL); + if (!PyArg_ParseTuple(args, "b:write_byte", &value)) + return(NULL); + + if (!is_writable(self)) + return NULL; + + if (self->pos < self->size) { + *(self->data+self->pos) = value; + self->pos += 1; + Py_INCREF(Py_None); + return Py_None; + } + else { + PyErr_SetString(PyExc_ValueError, "write byte out of range"); + return NULL; + } } static PyObject * mmap_size_method(mmap_object *self, - PyObject *unused) + PyObject *unused) { - CHECK_VALID(NULL); + CHECK_VALID(NULL); #ifdef MS_WINDOWS - if (self->file_handle != INVALID_HANDLE_VALUE) { - DWORD low,high; - PY_LONG_LONG size; - low = GetFileSize(self->file_handle, &high); - if (low == INVALID_FILE_SIZE) { - /* It might be that the function appears to have failed, - when indeed its size equals INVALID_FILE_SIZE */ - DWORD error = GetLastError(); - if (error != NO_ERROR) - return PyErr_SetFromWindowsErr(error); - } - if (!high && low < LONG_MAX) - return PyLong_FromLong((long)low); - size = (((PY_LONG_LONG)high)<<32) + low; - return PyLong_FromLongLong(size); - } else { - return PyLong_FromSsize_t(self->size); - } + if (self->file_handle != INVALID_HANDLE_VALUE) { + DWORD low,high; + PY_LONG_LONG size; + low = GetFileSize(self->file_handle, &high); + if (low == INVALID_FILE_SIZE) { + /* It might be that the function appears to have failed, + when indeed its size equals INVALID_FILE_SIZE */ + DWORD error = GetLastError(); + if (error != NO_ERROR) + return PyErr_SetFromWindowsErr(error); + } + if (!high && low < LONG_MAX) + return PyLong_FromLong((long)low); + size = (((PY_LONG_LONG)high)<<32) + low; + return PyLong_FromLongLong(size); + } else { + return PyLong_FromSsize_t(self->size); + } #endif /* MS_WINDOWS */ #ifdef UNIX - { - struct stat buf; - if (-1 == fstat(self->fd, &buf)) { - PyErr_SetFromErrno(mmap_module_error); - return NULL; - } - return PyLong_FromSsize_t(buf.st_size); - } + { + struct stat buf; + if (-1 == fstat(self->fd, &buf)) { + PyErr_SetFromErrno(mmap_module_error); + return NULL; + } + return PyLong_FromSsize_t(buf.st_size); + } #endif /* UNIX */ } @@ -450,223 +450,223 @@ static PyObject * mmap_resize_method(mmap_object *self, - PyObject *args) + PyObject *args) { - Py_ssize_t new_size; - CHECK_VALID(NULL); - if (!PyArg_ParseTuple(args, "n:resize", &new_size) || - !is_resizeable(self)) { - return NULL; + Py_ssize_t new_size; + CHECK_VALID(NULL); + if (!PyArg_ParseTuple(args, "n:resize", &new_size) || + !is_resizeable(self)) { + return NULL; #ifdef MS_WINDOWS - } else { - DWORD dwErrCode = 0; - DWORD off_hi, off_lo, newSizeLow, newSizeHigh; - /* First, unmap the file view */ - UnmapViewOfFile(self->data); - self->data = NULL; - /* Close the mapping object */ - CloseHandle(self->map_handle); - self->map_handle = NULL; - /* Move to the desired EOF position */ + } else { + DWORD dwErrCode = 0; + DWORD off_hi, off_lo, newSizeLow, newSizeHigh; + /* First, unmap the file view */ + UnmapViewOfFile(self->data); + self->data = NULL; + /* Close the mapping object */ + CloseHandle(self->map_handle); + self->map_handle = NULL; + /* Move to the desired EOF position */ #if SIZEOF_SIZE_T > 4 - newSizeHigh = (DWORD)((self->offset + new_size) >> 32); - newSizeLow = (DWORD)((self->offset + new_size) & 0xFFFFFFFF); - off_hi = (DWORD)(self->offset >> 32); - off_lo = (DWORD)(self->offset & 0xFFFFFFFF); + newSizeHigh = (DWORD)((self->offset + new_size) >> 32); + newSizeLow = (DWORD)((self->offset + new_size) & 0xFFFFFFFF); + off_hi = (DWORD)(self->offset >> 32); + off_lo = (DWORD)(self->offset & 0xFFFFFFFF); #else - newSizeHigh = 0; - newSizeLow = (DWORD)(self->offset + new_size); - off_hi = 0; - off_lo = (DWORD)self->offset; -#endif - SetFilePointer(self->file_handle, - newSizeLow, &newSizeHigh, FILE_BEGIN); - /* Change the size of the file */ - SetEndOfFile(self->file_handle); - /* Create another mapping object and remap the file view */ - self->map_handle = CreateFileMapping( - self->file_handle, - NULL, - PAGE_READWRITE, - 0, - 0, - self->tagname); - if (self->map_handle != NULL) { - self->data = (char *) MapViewOfFile(self->map_handle, - FILE_MAP_WRITE, - off_hi, - off_lo, - new_size); - if (self->data != NULL) { - self->size = new_size; - Py_INCREF(Py_None); - return Py_None; - } else { - dwErrCode = GetLastError(); - CloseHandle(self->map_handle); - self->map_handle = NULL; - } - } else { - dwErrCode = GetLastError(); - } - PyErr_SetFromWindowsErr(dwErrCode); - return NULL; + newSizeHigh = 0; + newSizeLow = (DWORD)(self->offset + new_size); + off_hi = 0; + off_lo = (DWORD)self->offset; +#endif + SetFilePointer(self->file_handle, + newSizeLow, &newSizeHigh, FILE_BEGIN); + /* Change the size of the file */ + SetEndOfFile(self->file_handle); + /* Create another mapping object and remap the file view */ + self->map_handle = CreateFileMapping( + self->file_handle, + NULL, + PAGE_READWRITE, + 0, + 0, + self->tagname); + if (self->map_handle != NULL) { + self->data = (char *) MapViewOfFile(self->map_handle, + FILE_MAP_WRITE, + off_hi, + off_lo, + new_size); + if (self->data != NULL) { + self->size = new_size; + Py_INCREF(Py_None); + return Py_None; + } else { + dwErrCode = GetLastError(); + CloseHandle(self->map_handle); + self->map_handle = NULL; + } + } else { + dwErrCode = GetLastError(); + } + PyErr_SetFromWindowsErr(dwErrCode); + return NULL; #endif /* MS_WINDOWS */ #ifdef UNIX #ifndef HAVE_MREMAP - } else { - PyErr_SetString(PyExc_SystemError, - "mmap: resizing not available--no mremap()"); - return NULL; + } else { + PyErr_SetString(PyExc_SystemError, + "mmap: resizing not available--no mremap()"); + return NULL; #else - } else { - void *newmap; + } else { + void *newmap; - if (ftruncate(self->fd, self->offset + new_size) == -1) { - PyErr_SetFromErrno(mmap_module_error); - return NULL; - } + if (ftruncate(self->fd, self->offset + new_size) == -1) { + PyErr_SetFromErrno(mmap_module_error); + return NULL; + } #ifdef MREMAP_MAYMOVE - newmap = mremap(self->data, self->size, new_size, MREMAP_MAYMOVE); + newmap = mremap(self->data, self->size, new_size, MREMAP_MAYMOVE); #else - #if defined(__NetBSD__) - newmap = mremap(self->data, self->size, self->data, new_size, 0); - #else - newmap = mremap(self->data, self->size, new_size, 0); - #endif /* __NetBSD__ */ -#endif - if (newmap == (void *)-1) - { - PyErr_SetFromErrno(mmap_module_error); - return NULL; - } - self->data = newmap; - self->size = new_size; - Py_INCREF(Py_None); - return Py_None; + #if defined(__NetBSD__) + newmap = mremap(self->data, self->size, self->data, new_size, 0); + #else + newmap = mremap(self->data, self->size, new_size, 0); + #endif /* __NetBSD__ */ +#endif + if (newmap == (void *)-1) + { + PyErr_SetFromErrno(mmap_module_error); + return NULL; + } + self->data = newmap; + self->size = new_size; + Py_INCREF(Py_None); + return Py_None; #endif /* HAVE_MREMAP */ #endif /* UNIX */ - } + } } static PyObject * mmap_tell_method(mmap_object *self, PyObject *unused) { - CHECK_VALID(NULL); - return PyLong_FromSize_t(self->pos); + CHECK_VALID(NULL); + return PyLong_FromSize_t(self->pos); } static PyObject * mmap_flush_method(mmap_object *self, PyObject *args) { - Py_ssize_t offset = 0; - Py_ssize_t size = self->size; - CHECK_VALID(NULL); - if (!PyArg_ParseTuple(args, "|nn:flush", &offset, &size)) - return NULL; - if ((size_t)(offset + size) > self->size) { - PyErr_SetString(PyExc_ValueError, "flush values out of range"); - return NULL; - } + Py_ssize_t offset = 0; + Py_ssize_t size = self->size; + CHECK_VALID(NULL); + if (!PyArg_ParseTuple(args, "|nn:flush", &offset, &size)) + return NULL; + if ((size_t)(offset + size) > self->size) { + PyErr_SetString(PyExc_ValueError, "flush values out of range"); + return NULL; + } #ifdef MS_WINDOWS - return PyLong_FromLong((long) FlushViewOfFile(self->data+offset, size)); + return PyLong_FromLong((long) FlushViewOfFile(self->data+offset, size)); #elif defined(UNIX) - /* XXX semantics of return value? */ - /* XXX flags for msync? */ - if (-1 == msync(self->data + offset, size, MS_SYNC)) { - PyErr_SetFromErrno(mmap_module_error); - return NULL; - } - return PyLong_FromLong(0); + /* XXX semantics of return value? */ + /* XXX flags for msync? */ + if (-1 == msync(self->data + offset, size, MS_SYNC)) { + PyErr_SetFromErrno(mmap_module_error); + return NULL; + } + return PyLong_FromLong(0); #else - PyErr_SetString(PyExc_ValueError, "flush not supported on this system"); - return NULL; + PyErr_SetString(PyExc_ValueError, "flush not supported on this system"); + return NULL; #endif } static PyObject * mmap_seek_method(mmap_object *self, PyObject *args) { - Py_ssize_t dist; - int how=0; - CHECK_VALID(NULL); - if (!PyArg_ParseTuple(args, "n|i:seek", &dist, &how)) - return NULL; - else { - size_t where; - switch (how) { - case 0: /* relative to start */ - if (dist < 0) - goto onoutofrange; - where = dist; - break; - case 1: /* relative to current position */ - if ((Py_ssize_t)self->pos + dist < 0) - goto onoutofrange; - where = self->pos + dist; - break; - case 2: /* relative to end */ - if ((Py_ssize_t)self->size + dist < 0) - goto onoutofrange; - where = self->size + dist; - break; - default: - PyErr_SetString(PyExc_ValueError, "unknown seek type"); - return NULL; - } - if (where > self->size) - goto onoutofrange; - self->pos = where; - Py_INCREF(Py_None); - return Py_None; - } + Py_ssize_t dist; + int how=0; + CHECK_VALID(NULL); + if (!PyArg_ParseTuple(args, "n|i:seek", &dist, &how)) + return NULL; + else { + size_t where; + switch (how) { + case 0: /* relative to start */ + if (dist < 0) + goto onoutofrange; + where = dist; + break; + case 1: /* relative to current position */ + if ((Py_ssize_t)self->pos + dist < 0) + goto onoutofrange; + where = self->pos + dist; + break; + case 2: /* relative to end */ + if ((Py_ssize_t)self->size + dist < 0) + goto onoutofrange; + where = self->size + dist; + break; + default: + PyErr_SetString(PyExc_ValueError, "unknown seek type"); + return NULL; + } + if (where > self->size) + goto onoutofrange; + self->pos = where; + Py_INCREF(Py_None); + return Py_None; + } onoutofrange: - PyErr_SetString(PyExc_ValueError, "seek out of range"); - return NULL; + PyErr_SetString(PyExc_ValueError, "seek out of range"); + return NULL; } static PyObject * mmap_move_method(mmap_object *self, PyObject *args) { - unsigned long dest, src, cnt; - CHECK_VALID(NULL); - if (!PyArg_ParseTuple(args, "kkk:move", &dest, &src, &cnt) || - !is_writable(self)) { - return NULL; - } else { - /* bounds check the values */ - if (cnt < 0 || (cnt + dest) < cnt || (cnt + src) < cnt || - src < 0 || src > self->size || (src + cnt) > self->size || - dest < 0 || dest > self->size || (dest + cnt) > self->size) { - PyErr_SetString(PyExc_ValueError, - "source, destination, or count out of range"); - return NULL; - } - memmove(self->data+dest, self->data+src, cnt); - Py_INCREF(Py_None); - return Py_None; - } + unsigned long dest, src, cnt; + CHECK_VALID(NULL); + if (!PyArg_ParseTuple(args, "kkk:move", &dest, &src, &cnt) || + !is_writable(self)) { + return NULL; + } else { + /* bounds check the values */ + if (cnt < 0 || (cnt + dest) < cnt || (cnt + src) < cnt || + src < 0 || src > self->size || (src + cnt) > self->size || + dest < 0 || dest > self->size || (dest + cnt) > self->size) { + PyErr_SetString(PyExc_ValueError, + "source, destination, or count out of range"); + return NULL; + } + memmove(self->data+dest, self->data+src, cnt); + Py_INCREF(Py_None); + return Py_None; + } } static struct PyMethodDef mmap_object_methods[] = { - {"close", (PyCFunction) mmap_close_method, METH_NOARGS}, - {"find", (PyCFunction) mmap_find_method, METH_VARARGS}, - {"rfind", (PyCFunction) mmap_rfind_method, METH_VARARGS}, - {"flush", (PyCFunction) mmap_flush_method, METH_VARARGS}, - {"move", (PyCFunction) mmap_move_method, METH_VARARGS}, - {"read", (PyCFunction) mmap_read_method, METH_VARARGS}, - {"read_byte", (PyCFunction) mmap_read_byte_method, METH_NOARGS}, - {"readline", (PyCFunction) mmap_read_line_method, METH_NOARGS}, - {"resize", (PyCFunction) mmap_resize_method, METH_VARARGS}, - {"seek", (PyCFunction) mmap_seek_method, METH_VARARGS}, - {"size", (PyCFunction) mmap_size_method, METH_NOARGS}, - {"tell", (PyCFunction) mmap_tell_method, METH_NOARGS}, - {"write", (PyCFunction) mmap_write_method, METH_VARARGS}, - {"write_byte", (PyCFunction) mmap_write_byte_method, METH_VARARGS}, - {NULL, NULL} /* sentinel */ + {"close", (PyCFunction) mmap_close_method, METH_NOARGS}, + {"find", (PyCFunction) mmap_find_method, METH_VARARGS}, + {"rfind", (PyCFunction) mmap_rfind_method, METH_VARARGS}, + {"flush", (PyCFunction) mmap_flush_method, METH_VARARGS}, + {"move", (PyCFunction) mmap_move_method, METH_VARARGS}, + {"read", (PyCFunction) mmap_read_method, METH_VARARGS}, + {"read_byte", (PyCFunction) mmap_read_byte_method, METH_NOARGS}, + {"readline", (PyCFunction) mmap_read_line_method, METH_NOARGS}, + {"resize", (PyCFunction) mmap_resize_method, METH_VARARGS}, + {"seek", (PyCFunction) mmap_seek_method, METH_VARARGS}, + {"size", (PyCFunction) mmap_size_method, METH_NOARGS}, + {"tell", (PyCFunction) mmap_tell_method, METH_NOARGS}, + {"write", (PyCFunction) mmap_write_method, METH_VARARGS}, + {"write_byte", (PyCFunction) mmap_write_byte_method, METH_VARARGS}, + {NULL, NULL} /* sentinel */ }; /* Functions for treating an mmap'ed file as a buffer */ @@ -674,247 +674,247 @@ static int mmap_buffer_getbuf(mmap_object *self, Py_buffer *view, int flags) { - CHECK_VALID(-1); - if (PyBuffer_FillInfo(view, (PyObject*)self, self->data, self->size, - (self->access == ACCESS_READ), flags) < 0) - return -1; - self->exports++; - return 0; + CHECK_VALID(-1); + if (PyBuffer_FillInfo(view, (PyObject*)self, self->data, self->size, + (self->access == ACCESS_READ), flags) < 0) + return -1; + self->exports++; + return 0; } static void mmap_buffer_releasebuf(mmap_object *self, Py_buffer *view) { - self->exports--; + self->exports--; } static Py_ssize_t mmap_length(mmap_object *self) { - CHECK_VALID(-1); - return self->size; + CHECK_VALID(-1); + return self->size; } static PyObject * mmap_item(mmap_object *self, Py_ssize_t i) { - CHECK_VALID(NULL); - if (i < 0 || (size_t)i >= self->size) { - PyErr_SetString(PyExc_IndexError, "mmap index out of range"); - return NULL; - } - return PyBytes_FromStringAndSize(self->data + i, 1); + CHECK_VALID(NULL); + if (i < 0 || (size_t)i >= self->size) { + PyErr_SetString(PyExc_IndexError, "mmap index out of range"); + return NULL; + } + return PyBytes_FromStringAndSize(self->data + i, 1); } static PyObject * mmap_subscript(mmap_object *self, PyObject *item) { - CHECK_VALID(NULL); - 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 += self->size; - if (i < 0 || (size_t)i >= self->size) { - PyErr_SetString(PyExc_IndexError, - "mmap index out of range"); - return NULL; - } - return PyLong_FromLong(Py_CHARMASK(self->data[i])); - } - else if (PySlice_Check(item)) { - Py_ssize_t start, stop, step, slicelen; - - if (PySlice_GetIndicesEx((PySliceObject *)item, self->size, - &start, &stop, &step, &slicelen) < 0) { - return NULL; - } - - if (slicelen <= 0) - return PyBytes_FromStringAndSize("", 0); - else if (step == 1) - return PyBytes_FromStringAndSize(self->data + start, - slicelen); - else { - char *result_buf = (char *)PyMem_Malloc(slicelen); - Py_ssize_t cur, i; - PyObject *result; - - if (result_buf == NULL) - return PyErr_NoMemory(); - for (cur = start, i = 0; i < slicelen; - cur += step, i++) { - result_buf[i] = self->data[cur]; - } - result = PyBytes_FromStringAndSize(result_buf, - slicelen); - PyMem_Free(result_buf); - return result; - } - } - else { - PyErr_SetString(PyExc_TypeError, - "mmap indices must be integers"); - return NULL; - } + CHECK_VALID(NULL); + 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 += self->size; + if (i < 0 || (size_t)i >= self->size) { + PyErr_SetString(PyExc_IndexError, + "mmap index out of range"); + return NULL; + } + return PyLong_FromLong(Py_CHARMASK(self->data[i])); + } + else if (PySlice_Check(item)) { + Py_ssize_t start, stop, step, slicelen; + + if (PySlice_GetIndicesEx((PySliceObject *)item, self->size, + &start, &stop, &step, &slicelen) < 0) { + return NULL; + } + + if (slicelen <= 0) + return PyBytes_FromStringAndSize("", 0); + else if (step == 1) + return PyBytes_FromStringAndSize(self->data + start, + slicelen); + else { + char *result_buf = (char *)PyMem_Malloc(slicelen); + Py_ssize_t cur, i; + PyObject *result; + + if (result_buf == NULL) + return PyErr_NoMemory(); + for (cur = start, i = 0; i < slicelen; + cur += step, i++) { + result_buf[i] = self->data[cur]; + } + result = PyBytes_FromStringAndSize(result_buf, + slicelen); + PyMem_Free(result_buf); + return result; + } + } + else { + PyErr_SetString(PyExc_TypeError, + "mmap indices must be integers"); + return NULL; + } } static PyObject * mmap_concat(mmap_object *self, PyObject *bb) { - CHECK_VALID(NULL); - PyErr_SetString(PyExc_SystemError, - "mmaps don't support concatenation"); - return NULL; + 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; + CHECK_VALID(NULL); + PyErr_SetString(PyExc_SystemError, + "mmaps don't support repeat operation"); + return NULL; } static int mmap_ass_item(mmap_object *self, Py_ssize_t i, PyObject *v) { - const char *buf; + const char *buf; - CHECK_VALID(-1); - if (i < 0 || (size_t)i >= self->size) { - PyErr_SetString(PyExc_IndexError, "mmap index out of range"); - return -1; - } - if (v == NULL) { - PyErr_SetString(PyExc_TypeError, - "mmap object doesn't support item deletion"); - return -1; - } - if (! (PyBytes_Check(v) && PyBytes_Size(v)==1) ) { - PyErr_SetString(PyExc_IndexError, - "mmap assignment must be length-1 bytes()"); - return -1; - } - if (!is_writable(self)) - return -1; - buf = PyBytes_AsString(v); - self->data[i] = buf[0]; - return 0; + CHECK_VALID(-1); + if (i < 0 || (size_t)i >= self->size) { + PyErr_SetString(PyExc_IndexError, "mmap index out of range"); + return -1; + } + if (v == NULL) { + PyErr_SetString(PyExc_TypeError, + "mmap object doesn't support item deletion"); + return -1; + } + if (! (PyBytes_Check(v) && PyBytes_Size(v)==1) ) { + PyErr_SetString(PyExc_IndexError, + "mmap assignment must be length-1 bytes()"); + return -1; + } + if (!is_writable(self)) + return -1; + buf = PyBytes_AsString(v); + self->data[i] = buf[0]; + return 0; } static int mmap_ass_subscript(mmap_object *self, PyObject *item, PyObject *value) { - CHECK_VALID(-1); + CHECK_VALID(-1); + + if (!is_writable(self)) + return -1; + + if (PyIndex_Check(item)) { + Py_ssize_t i = PyNumber_AsSsize_t(item, PyExc_IndexError); + Py_ssize_t v; + + if (i == -1 && PyErr_Occurred()) + return -1; + if (i < 0) + i += self->size; + if (i < 0 || (size_t)i >= self->size) { + PyErr_SetString(PyExc_IndexError, + "mmap index out of range"); + return -1; + } + if (value == NULL) { + PyErr_SetString(PyExc_TypeError, + "mmap doesn't support item deletion"); + return -1; + } + if (!PyIndex_Check(value)) { + PyErr_SetString(PyExc_TypeError, + "mmap item value must be an int"); + return -1; + } + v = PyNumber_AsSsize_t(value, PyExc_TypeError); + if (v == -1 && PyErr_Occurred()) + return -1; + if (v < 0 || v > 255) { + PyErr_SetString(PyExc_ValueError, + "mmap item value must be " + "in range(0, 256)"); + return -1; + } + self->data[i] = v; + return 0; + } + else if (PySlice_Check(item)) { + Py_ssize_t start, stop, step, slicelen; + Py_buffer vbuf; + + if (PySlice_GetIndicesEx((PySliceObject *)item, + self->size, &start, &stop, + &step, &slicelen) < 0) { + return -1; + } + if (value == NULL) { + PyErr_SetString(PyExc_TypeError, + "mmap object doesn't support slice deletion"); + return -1; + } + if (PyObject_GetBuffer(value, &vbuf, PyBUF_SIMPLE) < 0) + return -1; + if (vbuf.len != slicelen) { + PyErr_SetString(PyExc_IndexError, + "mmap slice assignment is wrong size"); + PyBuffer_Release(&vbuf); + return -1; + } - if (!is_writable(self)) - return -1; + if (slicelen == 0) { + } + else if (step == 1) { + memcpy(self->data + start, vbuf.buf, slicelen); + } + else { + Py_ssize_t cur, i; - if (PyIndex_Check(item)) { - Py_ssize_t i = PyNumber_AsSsize_t(item, PyExc_IndexError); - Py_ssize_t v; - - if (i == -1 && PyErr_Occurred()) - return -1; - if (i < 0) - i += self->size; - if (i < 0 || (size_t)i >= self->size) { - PyErr_SetString(PyExc_IndexError, - "mmap index out of range"); - return -1; - } - if (value == NULL) { - PyErr_SetString(PyExc_TypeError, - "mmap doesn't support item deletion"); - return -1; - } - if (!PyIndex_Check(value)) { - PyErr_SetString(PyExc_TypeError, - "mmap item value must be an int"); - return -1; - } - v = PyNumber_AsSsize_t(value, PyExc_TypeError); - if (v == -1 && PyErr_Occurred()) - return -1; - if (v < 0 || v > 255) { - PyErr_SetString(PyExc_ValueError, - "mmap item value must be " - "in range(0, 256)"); - return -1; - } - self->data[i] = v; - return 0; - } - else if (PySlice_Check(item)) { - Py_ssize_t start, stop, step, slicelen; - Py_buffer vbuf; - - if (PySlice_GetIndicesEx((PySliceObject *)item, - self->size, &start, &stop, - &step, &slicelen) < 0) { - return -1; - } - if (value == NULL) { - PyErr_SetString(PyExc_TypeError, - "mmap object doesn't support slice deletion"); - return -1; - } - if (PyObject_GetBuffer(value, &vbuf, PyBUF_SIMPLE) < 0) - return -1; - if (vbuf.len != slicelen) { - PyErr_SetString(PyExc_IndexError, - "mmap slice assignment is wrong size"); - PyBuffer_Release(&vbuf); - return -1; - } - - if (slicelen == 0) { - } - else if (step == 1) { - memcpy(self->data + start, vbuf.buf, slicelen); - } - else { - Py_ssize_t cur, i; - - for (cur = start, i = 0; - i < slicelen; - cur += step, i++) - { - self->data[cur] = ((char *)vbuf.buf)[i]; - } - } - PyBuffer_Release(&vbuf); - return 0; - } - else { - PyErr_SetString(PyExc_TypeError, - "mmap indices must be integer"); - return -1; - } + for (cur = start, i = 0; + i < slicelen; + cur += step, i++) + { + self->data[cur] = ((char *)vbuf.buf)[i]; + } + } + PyBuffer_Release(&vbuf); + return 0; + } + else { + PyErr_SetString(PyExc_TypeError, + "mmap indices must be integer"); + return -1; + } } 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_slice*/ - (ssizeobjargproc)mmap_ass_item, /*sq_ass_item*/ - 0, /*sq_ass_slice*/ + (lenfunc)mmap_length, /*sq_length*/ + (binaryfunc)mmap_concat, /*sq_concat*/ + (ssizeargfunc)mmap_repeat, /*sq_repeat*/ + (ssizeargfunc)mmap_item, /*sq_item*/ + 0, /*sq_slice*/ + (ssizeobjargproc)mmap_ass_item, /*sq_ass_item*/ + 0, /*sq_ass_slice*/ }; static PyMappingMethods mmap_as_mapping = { - (lenfunc)mmap_length, - (binaryfunc)mmap_subscript, - (objobjargproc)mmap_ass_subscript, + (lenfunc)mmap_length, + (binaryfunc)mmap_subscript, + (objobjargproc)mmap_ass_subscript, }; static PyBufferProcs mmap_as_buffer = { - (getbufferproc)mmap_buffer_getbuf, - (releasebufferproc)mmap_buffer_releasebuf, + (getbufferproc)mmap_buffer_getbuf, + (releasebufferproc)mmap_buffer_releasebuf, }; static PyObject * @@ -945,46 +945,46 @@ static PyTypeObject mmap_object_type = { - PyVarObject_HEAD_INIT(NULL, 0) - "mmap.mmap", /* tp_name */ - sizeof(mmap_object), /* tp_size */ - 0, /* tp_itemsize */ - /* methods */ - (destructor) mmap_object_dealloc, /* tp_dealloc */ - 0, /* tp_print */ - 0, /* tp_getattr */ - 0, /* tp_setattr */ - 0, /* tp_reserved */ - 0, /* tp_repr */ - 0, /* tp_as_number */ - &mmap_as_sequence, /*tp_as_sequence*/ - &mmap_as_mapping, /*tp_as_mapping*/ - 0, /*tp_hash*/ - 0, /*tp_call*/ - 0, /*tp_str*/ - PyObject_GenericGetAttr, /*tp_getattro*/ - 0, /*tp_setattro*/ - &mmap_as_buffer, /*tp_as_buffer*/ - Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /*tp_flags*/ - mmap_doc, /*tp_doc*/ - 0, /* tp_traverse */ - 0, /* tp_clear */ - 0, /* tp_richcompare */ - 0, /* tp_weaklistoffset */ - 0, /* tp_iter */ - 0, /* tp_iternext */ - mmap_object_methods, /* tp_methods */ - 0, /* tp_members */ - 0, /* tp_getset */ - 0, /* tp_base */ - 0, /* tp_dict */ - 0, /* tp_descr_get */ - 0, /* tp_descr_set */ - 0, /* tp_dictoffset */ - 0, /* tp_init */ - PyType_GenericAlloc, /* tp_alloc */ - new_mmap_object, /* tp_new */ - PyObject_Del, /* tp_free */ + PyVarObject_HEAD_INIT(NULL, 0) + "mmap.mmap", /* tp_name */ + sizeof(mmap_object), /* tp_size */ + 0, /* tp_itemsize */ + /* methods */ + (destructor) mmap_object_dealloc, /* tp_dealloc */ + 0, /* tp_print */ + 0, /* tp_getattr */ + 0, /* tp_setattr */ + 0, /* tp_reserved */ + 0, /* tp_repr */ + 0, /* tp_as_number */ + &mmap_as_sequence, /*tp_as_sequence*/ + &mmap_as_mapping, /*tp_as_mapping*/ + 0, /*tp_hash*/ + 0, /*tp_call*/ + 0, /*tp_str*/ + PyObject_GenericGetAttr, /*tp_getattro*/ + 0, /*tp_setattro*/ + &mmap_as_buffer, /*tp_as_buffer*/ + Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /*tp_flags*/ + mmap_doc, /*tp_doc*/ + 0, /* tp_traverse */ + 0, /* tp_clear */ + 0, /* tp_richcompare */ + 0, /* tp_weaklistoffset */ + 0, /* tp_iter */ + 0, /* tp_iternext */ + mmap_object_methods, /* tp_methods */ + 0, /* tp_members */ + 0, /* tp_getset */ + 0, /* tp_base */ + 0, /* tp_dict */ + 0, /* tp_descr_get */ + 0, /* tp_descr_set */ + 0, /* tp_dictoffset */ + 0, /* tp_init */ + PyType_GenericAlloc, /* tp_alloc */ + new_mmap_object, /* tp_new */ + PyObject_Del, /* tp_free */ }; @@ -995,23 +995,23 @@ static Py_ssize_t _GetMapSize(PyObject *o, const char* param) { - if (o == NULL) - return 0; - if (PyIndex_Check(o)) { - Py_ssize_t i = PyNumber_AsSsize_t(o, PyExc_OverflowError); - if (i==-1 && PyErr_Occurred()) - return -1; - if (i < 0) { - PyErr_Format(PyExc_OverflowError, - "memory mapped %s must be positive", - param); - return -1; - } - return i; - } + if (o == NULL) + return 0; + if (PyIndex_Check(o)) { + Py_ssize_t i = PyNumber_AsSsize_t(o, PyExc_OverflowError); + if (i==-1 && PyErr_Occurred()) + return -1; + if (i < 0) { + PyErr_Format(PyExc_OverflowError, + "memory mapped %s must be positive", + param); + return -1; + } + return i; + } - PyErr_SetString(PyExc_TypeError, "map size must be an integral value"); - return -1; + PyErr_SetString(PyExc_TypeError, "map size must be an integral value"); + return -1; } #ifdef UNIX @@ -1019,125 +1019,125 @@ new_mmap_object(PyTypeObject *type, PyObject *args, PyObject *kwdict) { #ifdef HAVE_FSTAT - struct stat st; + struct stat st; #endif - mmap_object *m_obj; - PyObject *map_size_obj = NULL, *offset_obj = NULL; - Py_ssize_t map_size, offset; - int fd, flags = MAP_SHARED, prot = PROT_WRITE | PROT_READ; - int devzero = -1; - int access = (int)ACCESS_DEFAULT; - static char *keywords[] = {"fileno", "length", - "flags", "prot", - "access", "offset", NULL}; - - if (!PyArg_ParseTupleAndKeywords(args, kwdict, "iO|iiiO", keywords, - &fd, &map_size_obj, &flags, &prot, - &access, &offset_obj)) - return NULL; - map_size = _GetMapSize(map_size_obj, "size"); - if (map_size < 0) - return NULL; - offset = _GetMapSize(offset_obj, "offset"); - if (offset < 0) - return NULL; - - if ((access != (int)ACCESS_DEFAULT) && - ((flags != MAP_SHARED) || (prot != (PROT_WRITE | PROT_READ)))) - return PyErr_Format(PyExc_ValueError, - "mmap can't specify both access and flags, prot."); - switch ((access_mode)access) { - case ACCESS_READ: - flags = MAP_SHARED; - prot = PROT_READ; - break; - case ACCESS_WRITE: - flags = MAP_SHARED; - prot = PROT_READ | PROT_WRITE; - break; - case ACCESS_COPY: - flags = MAP_PRIVATE; - prot = PROT_READ | PROT_WRITE; - break; - case ACCESS_DEFAULT: - /* use the specified or default values of flags and prot */ - break; - default: - return PyErr_Format(PyExc_ValueError, - "mmap invalid access parameter."); - } + mmap_object *m_obj; + PyObject *map_size_obj = NULL, *offset_obj = NULL; + Py_ssize_t map_size, offset; + int fd, flags = MAP_SHARED, prot = PROT_WRITE | PROT_READ; + int devzero = -1; + int access = (int)ACCESS_DEFAULT; + static char *keywords[] = {"fileno", "length", + "flags", "prot", + "access", "offset", NULL}; + + if (!PyArg_ParseTupleAndKeywords(args, kwdict, "iO|iiiO", keywords, + &fd, &map_size_obj, &flags, &prot, + &access, &offset_obj)) + return NULL; + map_size = _GetMapSize(map_size_obj, "size"); + if (map_size < 0) + return NULL; + offset = _GetMapSize(offset_obj, "offset"); + if (offset < 0) + return NULL; + + if ((access != (int)ACCESS_DEFAULT) && + ((flags != MAP_SHARED) || (prot != (PROT_WRITE | PROT_READ)))) + return PyErr_Format(PyExc_ValueError, + "mmap can't specify both access and flags, prot."); + switch ((access_mode)access) { + case ACCESS_READ: + flags = MAP_SHARED; + prot = PROT_READ; + break; + case ACCESS_WRITE: + flags = MAP_SHARED; + prot = PROT_READ | PROT_WRITE; + break; + case ACCESS_COPY: + flags = MAP_PRIVATE; + prot = PROT_READ | PROT_WRITE; + break; + case ACCESS_DEFAULT: + /* use the specified or default values of flags and prot */ + break; + default: + return PyErr_Format(PyExc_ValueError, + "mmap invalid access parameter."); + } if (prot == PROT_READ) { - access = ACCESS_READ; + access = ACCESS_READ; } #ifdef HAVE_FSTAT # ifdef __VMS - /* on OpenVMS we must ensure that all bytes are written to the file */ - if (fd != -1) { - fsync(fd); - } + /* on OpenVMS we must ensure that all bytes are written to the file */ + if (fd != -1) { + fsync(fd); + } # endif - if (fd != -1 && fstat(fd, &st) == 0 && S_ISREG(st.st_mode)) { - if (map_size == 0) { - map_size = st.st_size; - } else if ((size_t)offset + (size_t)map_size > st.st_size) { - PyErr_SetString(PyExc_ValueError, - "mmap length is greater than file size"); - return NULL; - } - } -#endif - m_obj = (mmap_object *)type->tp_alloc(type, 0); - if (m_obj == NULL) {return NULL;} - m_obj->data = NULL; - m_obj->size = (size_t) map_size; - m_obj->pos = (size_t) 0; - m_obj->exports = 0; - m_obj->offset = offset; - if (fd == -1) { - m_obj->fd = -1; - /* Assume the caller wants to map anonymous memory. - This is the same behaviour as Windows. mmap.mmap(-1, size) - on both Windows and Unix map anonymous memory. - */ + if (fd != -1 && fstat(fd, &st) == 0 && S_ISREG(st.st_mode)) { + if (map_size == 0) { + map_size = st.st_size; + } else if ((size_t)offset + (size_t)map_size > st.st_size) { + PyErr_SetString(PyExc_ValueError, + "mmap length is greater than file size"); + return NULL; + } + } +#endif + m_obj = (mmap_object *)type->tp_alloc(type, 0); + if (m_obj == NULL) {return NULL;} + m_obj->data = NULL; + m_obj->size = (size_t) map_size; + m_obj->pos = (size_t) 0; + m_obj->exports = 0; + m_obj->offset = offset; + if (fd == -1) { + m_obj->fd = -1; + /* Assume the caller wants to map anonymous memory. + This is the same behaviour as Windows. mmap.mmap(-1, size) + on both Windows and Unix map anonymous memory. + */ #ifdef MAP_ANONYMOUS - /* BSD way to map anonymous memory */ - flags |= MAP_ANONYMOUS; + /* BSD way to map anonymous memory */ + flags |= MAP_ANONYMOUS; #else - /* SVR4 method to map anonymous memory is to open /dev/zero */ - fd = devzero = open("/dev/zero", O_RDWR); - if (devzero == -1) { - Py_DECREF(m_obj); - PyErr_SetFromErrno(mmap_module_error); - return NULL; - } -#endif - } else { - m_obj->fd = dup(fd); - if (m_obj->fd == -1) { - Py_DECREF(m_obj); - PyErr_SetFromErrno(mmap_module_error); - return NULL; - } - } - - m_obj->data = mmap(NULL, map_size, - prot, flags, - fd, offset); - - if (devzero != -1) { - close(devzero); - } - - if (m_obj->data == (char *)-1) { - m_obj->data = NULL; - Py_DECREF(m_obj); - PyErr_SetFromErrno(mmap_module_error); - return NULL; - } - m_obj->access = (access_mode)access; - return (PyObject *)m_obj; + /* SVR4 method to map anonymous memory is to open /dev/zero */ + fd = devzero = open("/dev/zero", O_RDWR); + if (devzero == -1) { + Py_DECREF(m_obj); + PyErr_SetFromErrno(mmap_module_error); + return NULL; + } +#endif + } else { + m_obj->fd = dup(fd); + if (m_obj->fd == -1) { + Py_DECREF(m_obj); + PyErr_SetFromErrno(mmap_module_error); + return NULL; + } + } + + m_obj->data = mmap(NULL, map_size, + prot, flags, + fd, offset); + + if (devzero != -1) { + close(devzero); + } + + if (m_obj->data == (char *)-1) { + m_obj->data = NULL; + Py_DECREF(m_obj); + PyErr_SetFromErrno(mmap_module_error); + return NULL; + } + m_obj->access = (access_mode)access; + return (PyObject *)m_obj; } #endif /* UNIX */ @@ -1145,266 +1145,266 @@ static PyObject * new_mmap_object(PyTypeObject *type, PyObject *args, PyObject *kwdict) { - mmap_object *m_obj; - PyObject *map_size_obj = NULL, *offset_obj = NULL; - Py_ssize_t map_size, offset; - DWORD off_hi; /* upper 32 bits of offset */ - DWORD off_lo; /* lower 32 bits of offset */ - DWORD size_hi; /* upper 32 bits of size */ - DWORD size_lo; /* lower 32 bits of size */ - char *tagname = ""; - DWORD dwErr = 0; - int fileno; - HANDLE fh = 0; - int access = (access_mode)ACCESS_DEFAULT; - DWORD flProtect, dwDesiredAccess; - static char *keywords[] = { "fileno", "length", - "tagname", - "access", "offset", NULL }; - - if (!PyArg_ParseTupleAndKeywords(args, kwdict, "iO|ziO", keywords, - &fileno, &map_size_obj, - &tagname, &access, &offset_obj)) { - return NULL; - } - - switch((access_mode)access) { - case ACCESS_READ: - flProtect = PAGE_READONLY; - dwDesiredAccess = FILE_MAP_READ; - break; - case ACCESS_DEFAULT: case ACCESS_WRITE: - flProtect = PAGE_READWRITE; - dwDesiredAccess = FILE_MAP_WRITE; - break; - case ACCESS_COPY: - flProtect = PAGE_WRITECOPY; - dwDesiredAccess = FILE_MAP_COPY; - break; - default: - return PyErr_Format(PyExc_ValueError, - "mmap invalid access parameter."); - } - - map_size = _GetMapSize(map_size_obj, "size"); - if (map_size < 0) - return NULL; - offset = _GetMapSize(offset_obj, "offset"); - if (offset < 0) - return NULL; - - /* assume -1 and 0 both mean invalid filedescriptor - to 'anonymously' map memory. - XXX: fileno == 0 is a valid fd, but was accepted prior to 2.5. - XXX: Should this code be added? - if (fileno == 0) - PyErr_WarnEx(PyExc_DeprecationWarning, - "don't use 0 for anonymous memory", - 1); - */ - if (fileno != -1 && fileno != 0) { - fh = (HANDLE)_get_osfhandle(fileno); - if (fh==(HANDLE)-1) { - PyErr_SetFromErrno(mmap_module_error); - return NULL; - } - /* Win9x appears to need us seeked to zero */ - lseek(fileno, 0, SEEK_SET); - } - - m_obj = (mmap_object *)type->tp_alloc(type, 0); - if (m_obj == NULL) - return NULL; - /* Set every field to an invalid marker, so we can safely - destruct the object in the face of failure */ - m_obj->data = NULL; - m_obj->file_handle = INVALID_HANDLE_VALUE; - m_obj->map_handle = NULL; - m_obj->tagname = NULL; - m_obj->offset = offset; - - if (fh) { - /* It is necessary to duplicate the handle, so the - Python code can close it on us */ - if (!DuplicateHandle( - GetCurrentProcess(), /* source process handle */ - fh, /* handle to be duplicated */ - GetCurrentProcess(), /* target proc handle */ - (LPHANDLE)&m_obj->file_handle, /* result */ - 0, /* access - ignored due to options value */ - FALSE, /* inherited by child processes? */ - DUPLICATE_SAME_ACCESS)) { /* options */ - dwErr = GetLastError(); - Py_DECREF(m_obj); - PyErr_SetFromWindowsErr(dwErr); - return NULL; - } - if (!map_size) { - DWORD low,high; - low = GetFileSize(fh, &high); - /* low might just happen to have the value INVALID_FILE_SIZE; - so we need to check the last error also. */ - if (low == INVALID_FILE_SIZE && - (dwErr = GetLastError()) != NO_ERROR) { - Py_DECREF(m_obj); - return PyErr_SetFromWindowsErr(dwErr); - } + mmap_object *m_obj; + PyObject *map_size_obj = NULL, *offset_obj = NULL; + Py_ssize_t map_size, offset; + DWORD off_hi; /* upper 32 bits of offset */ + DWORD off_lo; /* lower 32 bits of offset */ + DWORD size_hi; /* upper 32 bits of size */ + DWORD size_lo; /* lower 32 bits of size */ + char *tagname = ""; + DWORD dwErr = 0; + int fileno; + HANDLE fh = 0; + int access = (access_mode)ACCESS_DEFAULT; + DWORD flProtect, dwDesiredAccess; + static char *keywords[] = { "fileno", "length", + "tagname", + "access", "offset", NULL }; + + if (!PyArg_ParseTupleAndKeywords(args, kwdict, "iO|ziO", keywords, + &fileno, &map_size_obj, + &tagname, &access, &offset_obj)) { + return NULL; + } + + switch((access_mode)access) { + case ACCESS_READ: + flProtect = PAGE_READONLY; + dwDesiredAccess = FILE_MAP_READ; + break; + case ACCESS_DEFAULT: case ACCESS_WRITE: + flProtect = PAGE_READWRITE; + dwDesiredAccess = FILE_MAP_WRITE; + break; + case ACCESS_COPY: + flProtect = PAGE_WRITECOPY; + dwDesiredAccess = FILE_MAP_COPY; + break; + default: + return PyErr_Format(PyExc_ValueError, + "mmap invalid access parameter."); + } + + map_size = _GetMapSize(map_size_obj, "size"); + if (map_size < 0) + return NULL; + offset = _GetMapSize(offset_obj, "offset"); + if (offset < 0) + return NULL; + + /* assume -1 and 0 both mean invalid filedescriptor + to 'anonymously' map memory. + XXX: fileno == 0 is a valid fd, but was accepted prior to 2.5. + XXX: Should this code be added? + if (fileno == 0) + PyErr_WarnEx(PyExc_DeprecationWarning, + "don't use 0 for anonymous memory", + 1); + */ + if (fileno != -1 && fileno != 0) { + fh = (HANDLE)_get_osfhandle(fileno); + if (fh==(HANDLE)-1) { + PyErr_SetFromErrno(mmap_module_error); + return NULL; + } + /* Win9x appears to need us seeked to zero */ + lseek(fileno, 0, SEEK_SET); + } + + m_obj = (mmap_object *)type->tp_alloc(type, 0); + if (m_obj == NULL) + return NULL; + /* Set every field to an invalid marker, so we can safely + destruct the object in the face of failure */ + m_obj->data = NULL; + m_obj->file_handle = INVALID_HANDLE_VALUE; + m_obj->map_handle = NULL; + m_obj->tagname = NULL; + m_obj->offset = offset; + + if (fh) { + /* It is necessary to duplicate the handle, so the + Python code can close it on us */ + if (!DuplicateHandle( + GetCurrentProcess(), /* source process handle */ + fh, /* handle to be duplicated */ + GetCurrentProcess(), /* target proc handle */ + (LPHANDLE)&m_obj->file_handle, /* result */ + 0, /* access - ignored due to options value */ + FALSE, /* inherited by child processes? */ + DUPLICATE_SAME_ACCESS)) { /* options */ + dwErr = GetLastError(); + Py_DECREF(m_obj); + PyErr_SetFromWindowsErr(dwErr); + return NULL; + } + if (!map_size) { + DWORD low,high; + low = GetFileSize(fh, &high); + /* low might just happen to have the value INVALID_FILE_SIZE; + so we need to check the last error also. */ + if (low == INVALID_FILE_SIZE && + (dwErr = GetLastError()) != NO_ERROR) { + Py_DECREF(m_obj); + return PyErr_SetFromWindowsErr(dwErr); + } #if SIZEOF_SIZE_T > 4 - m_obj->size = (((size_t)high)<<32) + low; + m_obj->size = (((size_t)high)<<32) + low; #else - if (high) - /* File is too large to map completely */ - m_obj->size = (size_t)-1; - else - m_obj->size = low; -#endif - } else { - m_obj->size = map_size; - } - } - else { - m_obj->size = map_size; - } - - /* set the initial position */ - m_obj->pos = (size_t) 0; - - m_obj->exports = 0; - /* set the tag name */ - if (tagname != NULL && *tagname != '\0') { - m_obj->tagname = PyMem_Malloc(strlen(tagname)+1); - if (m_obj->tagname == NULL) { - PyErr_NoMemory(); - Py_DECREF(m_obj); - return NULL; - } - strcpy(m_obj->tagname, tagname); - } - else - m_obj->tagname = NULL; - - m_obj->access = (access_mode)access; - /* DWORD is a 4-byte int. If we're on a box where size_t consumes - * more than 4 bytes, we need to break it apart. Else (size_t - * consumes 4 bytes), C doesn't define what happens if we shift - * right by 32, so we need different code. - */ + if (high) + /* File is too large to map completely */ + m_obj->size = (size_t)-1; + else + m_obj->size = low; +#endif + } else { + m_obj->size = map_size; + } + } + else { + m_obj->size = map_size; + } + + /* set the initial position */ + m_obj->pos = (size_t) 0; + + m_obj->exports = 0; + /* set the tag name */ + if (tagname != NULL && *tagname != '\0') { + m_obj->tagname = PyMem_Malloc(strlen(tagname)+1); + if (m_obj->tagname == NULL) { + PyErr_NoMemory(); + Py_DECREF(m_obj); + return NULL; + } + strcpy(m_obj->tagname, tagname); + } + else + m_obj->tagname = NULL; + + m_obj->access = (access_mode)access; + /* DWORD is a 4-byte int. If we're on a box where size_t consumes + * more than 4 bytes, we need to break it apart. Else (size_t + * consumes 4 bytes), C doesn't define what happens if we shift + * right by 32, so we need different code. + */ #if SIZEOF_SIZE_T > 4 - size_hi = (DWORD)((offset + m_obj->size) >> 32); - size_lo = (DWORD)((offset + m_obj->size) & 0xFFFFFFFF); - off_hi = (DWORD)(offset >> 32); - off_lo = (DWORD)(offset & 0xFFFFFFFF); + size_hi = (DWORD)((offset + m_obj->size) >> 32); + size_lo = (DWORD)((offset + m_obj->size) & 0xFFFFFFFF); + off_hi = (DWORD)(offset >> 32); + off_lo = (DWORD)(offset & 0xFFFFFFFF); #else - size_hi = 0; - size_lo = (DWORD)(offset + m_obj->size); - off_hi = 0; - off_lo = (DWORD)offset; -#endif - /* For files, it would be sufficient to pass 0 as size. - For anonymous maps, we have to pass the size explicitly. */ - m_obj->map_handle = CreateFileMapping(m_obj->file_handle, - NULL, - flProtect, - size_hi, - size_lo, - m_obj->tagname); - if (m_obj->map_handle != NULL) { - m_obj->data = (char *) MapViewOfFile(m_obj->map_handle, - dwDesiredAccess, - off_hi, - off_lo, - m_obj->size); - if (m_obj->data != NULL) - return (PyObject *)m_obj; - else { - dwErr = GetLastError(); - CloseHandle(m_obj->map_handle); - m_obj->map_handle = NULL; - } - } else - dwErr = GetLastError(); - Py_DECREF(m_obj); - PyErr_SetFromWindowsErr(dwErr); - return NULL; + size_hi = 0; + size_lo = (DWORD)(offset + m_obj->size); + off_hi = 0; + off_lo = (DWORD)offset; +#endif + /* For files, it would be sufficient to pass 0 as size. + For anonymous maps, we have to pass the size explicitly. */ + m_obj->map_handle = CreateFileMapping(m_obj->file_handle, + NULL, + flProtect, + size_hi, + size_lo, + m_obj->tagname); + if (m_obj->map_handle != NULL) { + m_obj->data = (char *) MapViewOfFile(m_obj->map_handle, + dwDesiredAccess, + off_hi, + off_lo, + m_obj->size); + if (m_obj->data != NULL) + return (PyObject *)m_obj; + else { + dwErr = GetLastError(); + CloseHandle(m_obj->map_handle); + m_obj->map_handle = NULL; + } + } else + dwErr = GetLastError(); + Py_DECREF(m_obj); + PyErr_SetFromWindowsErr(dwErr); + return NULL; } #endif /* MS_WINDOWS */ static void setint(PyObject *d, const char *name, long value) { - PyObject *o = PyLong_FromLong(value); - if (o && PyDict_SetItemString(d, name, o) == 0) { - Py_DECREF(o); - } + PyObject *o = PyLong_FromLong(value); + if (o && PyDict_SetItemString(d, name, o) == 0) { + Py_DECREF(o); + } } static struct PyModuleDef mmapmodule = { - PyModuleDef_HEAD_INIT, - "mmap", - NULL, - -1, - NULL, - NULL, - NULL, - NULL, - NULL + PyModuleDef_HEAD_INIT, + "mmap", + NULL, + -1, + NULL, + NULL, + NULL, + NULL, + NULL }; PyMODINIT_FUNC PyInit_mmap(void) { - PyObject *dict, *module; + PyObject *dict, *module; - if (PyType_Ready(&mmap_object_type) < 0) - return NULL; + if (PyType_Ready(&mmap_object_type) < 0) + return NULL; - module = PyModule_Create(&mmapmodule); - if (module == NULL) - return NULL; - dict = PyModule_GetDict(module); - if (!dict) - return NULL; - mmap_module_error = PyErr_NewException("mmap.error", - PyExc_EnvironmentError , NULL); - if (mmap_module_error == NULL) - return NULL; - PyDict_SetItemString(dict, "error", mmap_module_error); - PyDict_SetItemString(dict, "mmap", (PyObject*) &mmap_object_type); + module = PyModule_Create(&mmapmodule); + if (module == NULL) + return NULL; + dict = PyModule_GetDict(module); + if (!dict) + return NULL; + mmap_module_error = PyErr_NewException("mmap.error", + PyExc_EnvironmentError , NULL); + if (mmap_module_error == NULL) + return NULL; + PyDict_SetItemString(dict, "error", mmap_module_error); + PyDict_SetItemString(dict, "mmap", (PyObject*) &mmap_object_type); #ifdef PROT_EXEC - setint(dict, "PROT_EXEC", PROT_EXEC); + setint(dict, "PROT_EXEC", PROT_EXEC); #endif #ifdef PROT_READ - setint(dict, "PROT_READ", PROT_READ); + setint(dict, "PROT_READ", PROT_READ); #endif #ifdef PROT_WRITE - setint(dict, "PROT_WRITE", PROT_WRITE); + setint(dict, "PROT_WRITE", PROT_WRITE); #endif #ifdef MAP_SHARED - setint(dict, "MAP_SHARED", MAP_SHARED); + setint(dict, "MAP_SHARED", MAP_SHARED); #endif #ifdef MAP_PRIVATE - setint(dict, "MAP_PRIVATE", MAP_PRIVATE); + setint(dict, "MAP_PRIVATE", MAP_PRIVATE); #endif #ifdef MAP_DENYWRITE - setint(dict, "MAP_DENYWRITE", MAP_DENYWRITE); + setint(dict, "MAP_DENYWRITE", MAP_DENYWRITE); #endif #ifdef MAP_EXECUTABLE - setint(dict, "MAP_EXECUTABLE", MAP_EXECUTABLE); + setint(dict, "MAP_EXECUTABLE", MAP_EXECUTABLE); #endif #ifdef MAP_ANONYMOUS - setint(dict, "MAP_ANON", MAP_ANONYMOUS); - setint(dict, "MAP_ANONYMOUS", MAP_ANONYMOUS); + setint(dict, "MAP_ANON", MAP_ANONYMOUS); + setint(dict, "MAP_ANONYMOUS", MAP_ANONYMOUS); #endif - setint(dict, "PAGESIZE", (long)my_getpagesize()); + setint(dict, "PAGESIZE", (long)my_getpagesize()); - setint(dict, "ALLOCATIONGRANULARITY", (long)my_getallocationgranularity()); + setint(dict, "ALLOCATIONGRANULARITY", (long)my_getallocationgranularity()); - setint(dict, "ACCESS_READ", ACCESS_READ); - setint(dict, "ACCESS_WRITE", ACCESS_WRITE); - setint(dict, "ACCESS_COPY", ACCESS_COPY); - return module; + setint(dict, "ACCESS_READ", ACCESS_READ); + setint(dict, "ACCESS_WRITE", ACCESS_WRITE); + setint(dict, "ACCESS_COPY", ACCESS_COPY); + return module; } Modified: python/branches/py3k-jit/Modules/nismodule.c ============================================================================== --- python/branches/py3k-jit/Modules/nismodule.c (original) +++ python/branches/py3k-jit/Modules/nismodule.c Mon May 10 23:55:43 2010 @@ -1,11 +1,11 @@ /*********************************************************** Written by: - Fred Gansevles - B&O group, - Faculteit der Informatica, - Universiteit Twente, - Enschede, - the Netherlands. + Fred Gansevles + B&O group, + Faculteit der Informatica, + Universiteit Twente, + Enschede, + the Netherlands. ******************************************************************/ /* NIS module implementation */ @@ -23,7 +23,7 @@ extern int yp_get_default_domain(char **); #endif -PyDoc_STRVAR(get_default_domain__doc__, +PyDoc_STRVAR(get_default_domain__doc__, "get_default_domain() -> str\n\ Corresponds to the C library yp_get_default_domain() call, returning\n\ the default NIS domain.\n"); @@ -49,44 +49,44 @@ static PyObject * nis_error (int err) { - PyErr_SetString(NisError, yperr_string(err)); - return NULL; + PyErr_SetString(NisError, yperr_string(err)); + return NULL; } static struct nis_map { - char *alias; - char *map; - int fix; + char *alias; + char *map; + int fix; } aliases [] = { - {"passwd", "passwd.byname", 0}, - {"group", "group.byname", 0}, - {"networks", "networks.byaddr", 0}, - {"hosts", "hosts.byname", 0}, - {"protocols", "protocols.bynumber", 0}, - {"services", "services.byname", 0}, - {"aliases", "mail.aliases", 1}, /* created with 'makedbm -a' */ - {"ethers", "ethers.byname", 0}, - {0L, 0L, 0} + {"passwd", "passwd.byname", 0}, + {"group", "group.byname", 0}, + {"networks", "networks.byaddr", 0}, + {"hosts", "hosts.byname", 0}, + {"protocols", "protocols.bynumber", 0}, + {"services", "services.byname", 0}, + {"aliases", "mail.aliases", 1}, /* created with 'makedbm -a' */ + {"ethers", "ethers.byname", 0}, + {0L, 0L, 0} }; static char * nis_mapname (char *map, int *pfix) { - int i; + int i; - *pfix = 0; - for (i=0; aliases[i].alias != 0L; i++) { - if (!strcmp (aliases[i].alias, map)) { - *pfix = aliases[i].fix; - return aliases[i].map; - } - if (!strcmp (aliases[i].map, map)) { - *pfix = aliases[i].fix; - return aliases[i].map; - } - } + *pfix = 0; + for (i=0; aliases[i].alias != 0L; i++) { + if (!strcmp (aliases[i].alias, map)) { + *pfix = aliases[i].fix; + return aliases[i].map; + } + if (!strcmp (aliases[i].map, map)) { + *pfix = aliases[i].fix; + return aliases[i].map; + } + } - return map; + return map; } #if defined(__APPLE__) || defined(__OpenBSD__) || defined(__FreeBSD__) @@ -96,168 +96,168 @@ #endif struct ypcallback_data { - PyObject *dict; - int fix; - PyThreadState *state; + PyObject *dict; + int fix; + PyThreadState *state; }; static int nis_foreach (int instatus, char *inkey, int inkeylen, char *inval, int invallen, struct ypcallback_data *indata) { - if (instatus == YP_TRUE) { - PyObject *key; - PyObject *val; - int err; - - PyEval_RestoreThread(indata->state); - if (indata->fix) { - if (inkeylen > 0 && inkey[inkeylen-1] == '\0') - inkeylen--; - if (invallen > 0 && inval[invallen-1] == '\0') - invallen--; - } - key = PyUnicode_FromStringAndSize(inkey, inkeylen); - val = PyUnicode_FromStringAndSize(inval, invallen); - if (key == NULL || val == NULL) { - /* XXX error -- don't know how to handle */ - PyErr_Clear(); - Py_XDECREF(key); - Py_XDECREF(val); - return 1; - } - err = PyDict_SetItem(indata->dict, key, val); - Py_DECREF(key); - Py_DECREF(val); - if (err != 0) - PyErr_Clear(); - indata->state = PyEval_SaveThread(); - if (err != 0) - return 1; - return 0; - } - return 1; + if (instatus == YP_TRUE) { + PyObject *key; + PyObject *val; + int err; + + PyEval_RestoreThread(indata->state); + if (indata->fix) { + if (inkeylen > 0 && inkey[inkeylen-1] == '\0') + inkeylen--; + if (invallen > 0 && inval[invallen-1] == '\0') + invallen--; + } + key = PyUnicode_FromStringAndSize(inkey, inkeylen); + val = PyUnicode_FromStringAndSize(inval, invallen); + if (key == NULL || val == NULL) { + /* XXX error -- don't know how to handle */ + PyErr_Clear(); + Py_XDECREF(key); + Py_XDECREF(val); + return 1; + } + err = PyDict_SetItem(indata->dict, key, val); + Py_DECREF(key); + Py_DECREF(val); + if (err != 0) + PyErr_Clear(); + indata->state = PyEval_SaveThread(); + if (err != 0) + return 1; + return 0; + } + return 1; } static PyObject * nis_get_default_domain (PyObject *self) { - char *domain; - int err; - PyObject *res; + char *domain; + int err; + PyObject *res; - if ((err = yp_get_default_domain(&domain)) != 0) - return nis_error(err); + if ((err = yp_get_default_domain(&domain)) != 0) + return nis_error(err); - res = PyUnicode_FromStringAndSize (domain, strlen(domain)); - return res; + res = PyUnicode_FromStringAndSize (domain, strlen(domain)); + return res; } static PyObject * nis_match (PyObject *self, PyObject *args, PyObject *kwdict) { - char *match; - char *domain = NULL; - int keylen, len; - char *key, *map; - int err; - PyObject *res; - int fix; - static char *kwlist[] = {"key", "map", "domain", NULL}; - - if (!PyArg_ParseTupleAndKeywords(args, kwdict, - "s#s|s:match", kwlist, - &key, &keylen, &map, &domain)) - return NULL; - if (!domain && ((err = yp_get_default_domain(&domain)) != 0)) - return nis_error(err); - map = nis_mapname (map, &fix); - if (fix) - keylen++; - Py_BEGIN_ALLOW_THREADS - err = yp_match (domain, map, key, keylen, &match, &len); - Py_END_ALLOW_THREADS - if (fix) - len--; - if (err != 0) - return nis_error(err); - res = PyUnicode_FromStringAndSize (match, len); - free (match); - return res; + char *match; + char *domain = NULL; + int keylen, len; + char *key, *map; + int err; + PyObject *res; + int fix; + static char *kwlist[] = {"key", "map", "domain", NULL}; + + if (!PyArg_ParseTupleAndKeywords(args, kwdict, + "s#s|s:match", kwlist, + &key, &keylen, &map, &domain)) + return NULL; + if (!domain && ((err = yp_get_default_domain(&domain)) != 0)) + return nis_error(err); + map = nis_mapname (map, &fix); + if (fix) + keylen++; + Py_BEGIN_ALLOW_THREADS + err = yp_match (domain, map, key, keylen, &match, &len); + Py_END_ALLOW_THREADS + if (fix) + len--; + if (err != 0) + return nis_error(err); + res = PyUnicode_FromStringAndSize (match, len); + free (match); + return res; } static PyObject * nis_cat (PyObject *self, PyObject *args, PyObject *kwdict) { - char *domain = NULL; - char *map; - struct ypall_callback cb; - struct ypcallback_data data; - PyObject *dict; - int err; - static char *kwlist[] = {"map", "domain", NULL}; - - if (!PyArg_ParseTupleAndKeywords(args, kwdict, "s|s:cat", - kwlist, &map, &domain)) - return NULL; - if (!domain && ((err = yp_get_default_domain(&domain)) != 0)) - return nis_error(err); - dict = PyDict_New (); - if (dict == NULL) - return NULL; - cb.foreach = (foreachfunc)nis_foreach; - data.dict = dict; - map = nis_mapname (map, &data.fix); - cb.data = (char *)&data; - data.state = PyEval_SaveThread(); - err = yp_all (domain, map, &cb); - PyEval_RestoreThread(data.state); - if (err != 0) { - Py_DECREF(dict); - return nis_error(err); - } - return dict; + char *domain = NULL; + char *map; + struct ypall_callback cb; + struct ypcallback_data data; + PyObject *dict; + int err; + static char *kwlist[] = {"map", "domain", NULL}; + + if (!PyArg_ParseTupleAndKeywords(args, kwdict, "s|s:cat", + kwlist, &map, &domain)) + return NULL; + if (!domain && ((err = yp_get_default_domain(&domain)) != 0)) + return nis_error(err); + dict = PyDict_New (); + if (dict == NULL) + return NULL; + cb.foreach = (foreachfunc)nis_foreach; + data.dict = dict; + map = nis_mapname (map, &data.fix); + cb.data = (char *)&data; + data.state = PyEval_SaveThread(); + err = yp_all (domain, map, &cb); + PyEval_RestoreThread(data.state); + if (err != 0) { + Py_DECREF(dict); + return nis_error(err); + } + return dict; } /* These should be u_long on Sun h/w but not on 64-bit h/w. This is not portable to machines with 16-bit ints and no prototypes */ #ifndef YPPROC_MAPLIST -#define YPPROC_MAPLIST 11 +#define YPPROC_MAPLIST 11 #endif #ifndef YPPROG -#define YPPROG 100004 +#define YPPROG 100004 #endif #ifndef YPVERS -#define YPVERS 2 +#define YPVERS 2 #endif typedef char *domainname; typedef char *mapname; enum nisstat { - NIS_TRUE = 1, - NIS_NOMORE = 2, - NIS_FALSE = 0, - NIS_NOMAP = -1, - NIS_NODOM = -2, - NIS_NOKEY = -3, - NIS_BADOP = -4, - NIS_BADDB = -5, - NIS_YPERR = -6, - NIS_BADARGS = -7, - NIS_VERS = -8 + NIS_TRUE = 1, + NIS_NOMORE = 2, + NIS_FALSE = 0, + NIS_NOMAP = -1, + NIS_NODOM = -2, + NIS_NOKEY = -3, + NIS_BADOP = -4, + NIS_BADDB = -5, + NIS_YPERR = -6, + NIS_BADARGS = -7, + NIS_VERS = -8 }; typedef enum nisstat nisstat; struct nismaplist { - mapname map; - struct nismaplist *next; + mapname map; + struct nismaplist *next; }; typedef struct nismaplist nismaplist; struct nisresp_maplist { - nisstat stat; - nismaplist *maps; + nisstat stat; + nismaplist *maps; }; typedef struct nisresp_maplist nisresp_maplist; @@ -267,45 +267,45 @@ bool_t nis_xdr_domainname(XDR *xdrs, domainname *objp) { - if (!xdr_string(xdrs, objp, YPMAXDOMAIN)) { - return (FALSE); - } - return (TRUE); + if (!xdr_string(xdrs, objp, YPMAXDOMAIN)) { + return (FALSE); + } + return (TRUE); } static bool_t nis_xdr_mapname(XDR *xdrs, mapname *objp) { - if (!xdr_string(xdrs, objp, YPMAXMAP)) { - return (FALSE); - } - return (TRUE); + if (!xdr_string(xdrs, objp, YPMAXMAP)) { + return (FALSE); + } + return (TRUE); } static bool_t nis_xdr_ypmaplist(XDR *xdrs, nismaplist *objp) { - if (!nis_xdr_mapname(xdrs, &objp->map)) { - return (FALSE); - } - if (!xdr_pointer(xdrs, (char **)&objp->next, - sizeof(nismaplist), (xdrproc_t)nis_xdr_ypmaplist)) - { - return (FALSE); - } - return (TRUE); + if (!nis_xdr_mapname(xdrs, &objp->map)) { + return (FALSE); + } + if (!xdr_pointer(xdrs, (char **)&objp->next, + sizeof(nismaplist), (xdrproc_t)nis_xdr_ypmaplist)) + { + return (FALSE); + } + return (TRUE); } static bool_t nis_xdr_ypstat(XDR *xdrs, nisstat *objp) { - if (!xdr_enum(xdrs, (enum_t *)objp)) { - return (FALSE); - } - return (TRUE); + if (!xdr_enum(xdrs, (enum_t *)objp)) { + return (FALSE); + } + return (TRUE); } @@ -313,15 +313,15 @@ bool_t nis_xdr_ypresp_maplist(XDR *xdrs, nisresp_maplist *objp) { - if (!nis_xdr_ypstat(xdrs, &objp->stat)) { - return (FALSE); - } - if (!xdr_pointer(xdrs, (char **)&objp->maps, - sizeof(nismaplist), (xdrproc_t)nis_xdr_ypmaplist)) - { - return (FALSE); - } - return (TRUE); + if (!nis_xdr_ypstat(xdrs, &objp->stat)) { + return (FALSE); + } + if (!xdr_pointer(xdrs, (char **)&objp->maps, + sizeof(nismaplist), (xdrproc_t)nis_xdr_ypmaplist)) + { + return (FALSE); + } + return (TRUE); } @@ -329,132 +329,132 @@ nisresp_maplist * nisproc_maplist_2(domainname *argp, CLIENT *clnt) { - static nisresp_maplist res; + static nisresp_maplist res; - memset(&res, 0, sizeof(res)); - if (clnt_call(clnt, YPPROC_MAPLIST, - (xdrproc_t)nis_xdr_domainname, (caddr_t)argp, - (xdrproc_t)nis_xdr_ypresp_maplist, (caddr_t)&res, - TIMEOUT) != RPC_SUCCESS) - { - return (NULL); - } - return (&res); + memset(&res, 0, sizeof(res)); + if (clnt_call(clnt, YPPROC_MAPLIST, + (xdrproc_t)nis_xdr_domainname, (caddr_t)argp, + (xdrproc_t)nis_xdr_ypresp_maplist, (caddr_t)&res, + TIMEOUT) != RPC_SUCCESS) + { + return (NULL); + } + return (&res); } static nismaplist * nis_maplist (char *dom) { - nisresp_maplist *list; - CLIENT *cl; - char *server = NULL; - int mapi = 0; - - while (!server && aliases[mapi].map != 0L) { - yp_master (dom, aliases[mapi].map, &server); - mapi++; - } - if (!server) { - PyErr_SetString(NisError, "No NIS master found for any map"); - return NULL; - } - cl = clnt_create(server, YPPROG, YPVERS, "tcp"); - if (cl == NULL) { - PyErr_SetString(NisError, clnt_spcreateerror(server)); - goto finally; - } - list = nisproc_maplist_2 (&dom, cl); - clnt_destroy(cl); - if (list == NULL) - goto finally; - if (list->stat != NIS_TRUE) - goto finally; + nisresp_maplist *list; + CLIENT *cl; + char *server = NULL; + int mapi = 0; + + while (!server && aliases[mapi].map != 0L) { + yp_master (dom, aliases[mapi].map, &server); + mapi++; + } + if (!server) { + PyErr_SetString(NisError, "No NIS master found for any map"); + return NULL; + } + cl = clnt_create(server, YPPROG, YPVERS, "tcp"); + if (cl == NULL) { + PyErr_SetString(NisError, clnt_spcreateerror(server)); + goto finally; + } + list = nisproc_maplist_2 (&dom, cl); + clnt_destroy(cl); + if (list == NULL) + goto finally; + if (list->stat != NIS_TRUE) + goto finally; - free(server); - return list->maps; + free(server); + return list->maps; finally: - free(server); - return NULL; + free(server); + return NULL; } static PyObject * nis_maps (PyObject *self, PyObject *args, PyObject *kwdict) { - char *domain = NULL; - nismaplist *maps; - PyObject *list; - int err; - static char *kwlist[] = {"domain", NULL}; - - if (!PyArg_ParseTupleAndKeywords(args, kwdict, - "|s:maps", kwlist, &domain)) - return NULL; - if (!domain && ((err = yp_get_default_domain (&domain)) != 0)) { - nis_error(err); - return NULL; - } - - if ((maps = nis_maplist (domain)) == NULL) - return NULL; - if ((list = PyList_New(0)) == NULL) - return NULL; - for (maps = maps; maps; maps = maps->next) { - PyObject *str = PyUnicode_FromString(maps->map); - if (!str || PyList_Append(list, str) < 0) - { - Py_DECREF(list); - list = NULL; - break; - } - Py_DECREF(str); - } - /* XXX Shouldn't we free the list of maps now? */ - return list; + char *domain = NULL; + nismaplist *maps; + PyObject *list; + int err; + static char *kwlist[] = {"domain", NULL}; + + if (!PyArg_ParseTupleAndKeywords(args, kwdict, + "|s:maps", kwlist, &domain)) + return NULL; + if (!domain && ((err = yp_get_default_domain (&domain)) != 0)) { + nis_error(err); + return NULL; + } + + if ((maps = nis_maplist (domain)) == NULL) + return NULL; + if ((list = PyList_New(0)) == NULL) + return NULL; + for (maps = maps; maps; maps = maps->next) { + PyObject *str = PyUnicode_FromString(maps->map); + if (!str || PyList_Append(list, str) < 0) + { + Py_DECREF(list); + list = NULL; + break; + } + Py_DECREF(str); + } + /* XXX Shouldn't we free the list of maps now? */ + return list; } static PyMethodDef nis_methods[] = { - {"match", (PyCFunction)nis_match, - METH_VARARGS | METH_KEYWORDS, - match__doc__}, - {"cat", (PyCFunction)nis_cat, - METH_VARARGS | METH_KEYWORDS, - cat__doc__}, - {"maps", (PyCFunction)nis_maps, - METH_VARARGS | METH_KEYWORDS, - maps__doc__}, - {"get_default_domain", (PyCFunction)nis_get_default_domain, - METH_NOARGS, - get_default_domain__doc__}, - {NULL, NULL} /* Sentinel */ + {"match", (PyCFunction)nis_match, + METH_VARARGS | METH_KEYWORDS, + match__doc__}, + {"cat", (PyCFunction)nis_cat, + METH_VARARGS | METH_KEYWORDS, + cat__doc__}, + {"maps", (PyCFunction)nis_maps, + METH_VARARGS | METH_KEYWORDS, + maps__doc__}, + {"get_default_domain", (PyCFunction)nis_get_default_domain, + METH_NOARGS, + get_default_domain__doc__}, + {NULL, NULL} /* Sentinel */ }; PyDoc_STRVAR(nis__doc__, "This module contains functions for accessing NIS maps.\n"); static struct PyModuleDef nismodule = { - PyModuleDef_HEAD_INIT, - "nis", - nis__doc__, - -1, - nis_methods, - NULL, - NULL, - NULL, - NULL + PyModuleDef_HEAD_INIT, + "nis", + nis__doc__, + -1, + nis_methods, + NULL, + NULL, + NULL, + NULL }; PyObject* PyInit_nis (void) { - PyObject *m, *d; - m = PyModule_Create(&nismodule); - if (m == NULL) - return NULL; - d = PyModule_GetDict(m); - NisError = PyErr_NewException("nis.error", NULL, NULL); - if (NisError != NULL) - PyDict_SetItemString(d, "error", NisError); - return m; + PyObject *m, *d; + m = PyModule_Create(&nismodule); + if (m == NULL) + return NULL; + d = PyModule_GetDict(m); + NisError = PyErr_NewException("nis.error", NULL, NULL); + if (NisError != NULL) + PyDict_SetItemString(d, "error", NisError); + return m; } Modified: python/branches/py3k-jit/Modules/operator.c ============================================================================== --- python/branches/py3k-jit/Modules/operator.c (original) +++ python/branches/py3k-jit/Modules/operator.c Mon May 10 23:55:43 2010 @@ -112,47 +112,47 @@ static PyObject* op_pow(PyObject *s, PyObject *a) { - PyObject *a1, *a2; - if (PyArg_UnpackTuple(a,"pow", 2, 2, &a1, &a2)) - return PyNumber_Power(a1, a2, Py_None); - return NULL; + PyObject *a1, *a2; + if (PyArg_UnpackTuple(a,"pow", 2, 2, &a1, &a2)) + return PyNumber_Power(a1, a2, Py_None); + return NULL; } static PyObject* op_ipow(PyObject *s, PyObject *a) { - PyObject *a1, *a2; - if (PyArg_UnpackTuple(a,"ipow", 2, 2, &a1, &a2)) - return PyNumber_InPlacePower(a1, a2, Py_None); - return NULL; + PyObject *a1, *a2; + if (PyArg_UnpackTuple(a,"ipow", 2, 2, &a1, &a2)) + return PyNumber_InPlacePower(a1, a2, Py_None); + return NULL; } static PyObject * op_index(PyObject *s, PyObject *a) { - return PyNumber_Index(a); + return PyNumber_Index(a); } static PyObject* is_(PyObject *s, PyObject *a) { - PyObject *a1, *a2, *result = NULL; - if (PyArg_UnpackTuple(a,"is_", 2, 2, &a1, &a2)) { - result = (a1 == a2) ? Py_True : Py_False; - Py_INCREF(result); - } - return result; + PyObject *a1, *a2, *result = NULL; + if (PyArg_UnpackTuple(a,"is_", 2, 2, &a1, &a2)) { + result = (a1 == a2) ? Py_True : Py_False; + Py_INCREF(result); + } + return result; } static PyObject* is_not(PyObject *s, PyObject *a) { - PyObject *a1, *a2, *result = NULL; - if (PyArg_UnpackTuple(a,"is_not", 2, 2, &a1, &a2)) { - result = (a1 != a2) ? Py_True : Py_False; - Py_INCREF(result); - } - return result; + PyObject *a1, *a2, *result = NULL; + if (PyArg_UnpackTuple(a,"is_not", 2, 2, &a1, &a2)) { + result = (a1 != a2) ? Py_True : Py_False; + Py_INCREF(result); + } + return result; } #undef spam1 @@ -161,10 +161,10 @@ #undef spam1o #define spam1(OP,DOC) {#OP, OP, METH_VARARGS, PyDoc_STR(DOC)}, #define spam2(OP,ALTOP,DOC) {#OP, op_##OP, METH_VARARGS, PyDoc_STR(DOC)}, \ - {#ALTOP, op_##OP, METH_VARARGS, PyDoc_STR(DOC)}, + {#ALTOP, op_##OP, METH_VARARGS, PyDoc_STR(DOC)}, #define spam1o(OP,DOC) {#OP, OP, METH_O, PyDoc_STR(DOC)}, #define spam2o(OP,ALTOP,DOC) {#OP, op_##OP, METH_O, PyDoc_STR(DOC)}, \ - {#ALTOP, op_##OP, METH_O, PyDoc_STR(DOC)}, + {#ALTOP, op_##OP, METH_O, PyDoc_STR(DOC)}, static struct PyMethodDef operator_methods[] = { @@ -227,16 +227,16 @@ spam2(gt,__gt__, "gt(a, b) -- Same as a>b.") spam2(ge,__ge__, "ge(a, b) -- Same as a>=b.") - {NULL, NULL} /* sentinel */ + {NULL, NULL} /* sentinel */ }; /* itemgetter object **********************************************************/ typedef struct { - PyObject_HEAD - Py_ssize_t nitems; - PyObject *item; + PyObject_HEAD + Py_ssize_t nitems; + PyObject *item; } itemgetterobject; static PyTypeObject itemgetter_type; @@ -244,77 +244,77 @@ static PyObject * itemgetter_new(PyTypeObject *type, PyObject *args, PyObject *kwds) { - itemgetterobject *ig; - PyObject *item; - Py_ssize_t nitems; - - if (!_PyArg_NoKeywords("itemgetter()", kwds)) - return NULL; - - nitems = PyTuple_GET_SIZE(args); - if (nitems <= 1) { - if (!PyArg_UnpackTuple(args, "itemgetter", 1, 1, &item)) - return NULL; - } else - item = args; - - /* create itemgetterobject structure */ - ig = PyObject_GC_New(itemgetterobject, &itemgetter_type); - if (ig == NULL) - return NULL; - - Py_INCREF(item); - ig->item = item; - ig->nitems = nitems; + itemgetterobject *ig; + PyObject *item; + Py_ssize_t nitems; + + if (!_PyArg_NoKeywords("itemgetter()", kwds)) + return NULL; + + nitems = PyTuple_GET_SIZE(args); + if (nitems <= 1) { + if (!PyArg_UnpackTuple(args, "itemgetter", 1, 1, &item)) + return NULL; + } else + item = args; + + /* create itemgetterobject structure */ + ig = PyObject_GC_New(itemgetterobject, &itemgetter_type); + if (ig == NULL) + return NULL; + + Py_INCREF(item); + ig->item = item; + ig->nitems = nitems; - PyObject_GC_Track(ig); - return (PyObject *)ig; + PyObject_GC_Track(ig); + return (PyObject *)ig; } static void itemgetter_dealloc(itemgetterobject *ig) { - PyObject_GC_UnTrack(ig); - Py_XDECREF(ig->item); - PyObject_GC_Del(ig); + PyObject_GC_UnTrack(ig); + Py_XDECREF(ig->item); + PyObject_GC_Del(ig); } static int itemgetter_traverse(itemgetterobject *ig, visitproc visit, void *arg) { - Py_VISIT(ig->item); - return 0; + Py_VISIT(ig->item); + return 0; } static PyObject * itemgetter_call(itemgetterobject *ig, PyObject *args, PyObject *kw) { - PyObject *obj, *result; - Py_ssize_t i, nitems=ig->nitems; + PyObject *obj, *result; + Py_ssize_t i, nitems=ig->nitems; - if (!PyArg_UnpackTuple(args, "itemgetter", 1, 1, &obj)) - return NULL; - if (nitems == 1) - return PyObject_GetItem(obj, ig->item); - - assert(PyTuple_Check(ig->item)); - assert(PyTuple_GET_SIZE(ig->item) == nitems); - - result = PyTuple_New(nitems); - if (result == NULL) - return NULL; - - for (i=0 ; i < nitems ; i++) { - PyObject *item, *val; - item = PyTuple_GET_ITEM(ig->item, i); - val = PyObject_GetItem(obj, item); - if (val == NULL) { - Py_DECREF(result); - return NULL; - } - PyTuple_SET_ITEM(result, i, val); - } - return result; + if (!PyArg_UnpackTuple(args, "itemgetter", 1, 1, &obj)) + return NULL; + if (nitems == 1) + return PyObject_GetItem(obj, ig->item); + + assert(PyTuple_Check(ig->item)); + assert(PyTuple_GET_SIZE(ig->item) == nitems); + + result = PyTuple_New(nitems); + if (result == NULL) + return NULL; + + for (i=0 ; i < nitems ; i++) { + PyObject *item, *val; + item = PyTuple_GET_ITEM(ig->item, i); + val = PyObject_GetItem(obj, item); + if (val == NULL) { + Py_DECREF(result); + return NULL; + } + PyTuple_SET_ITEM(result, i, val); + } + return result; } PyDoc_STRVAR(itemgetter_doc, @@ -325,55 +325,55 @@ After, g=itemgetter(2,5,3), the call g(r) returns (r[2], r[5], r[3])"); static PyTypeObject itemgetter_type = { - PyVarObject_HEAD_INIT(NULL, 0) - "operator.itemgetter", /* tp_name */ - sizeof(itemgetterobject), /* tp_basicsize */ - 0, /* tp_itemsize */ - /* methods */ - (destructor)itemgetter_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 */ - (ternaryfunc)itemgetter_call, /* 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 */ - itemgetter_doc, /* tp_doc */ - (traverseproc)itemgetter_traverse, /* tp_traverse */ - 0, /* tp_clear */ - 0, /* tp_richcompare */ - 0, /* tp_weaklistoffset */ - 0, /* tp_iter */ - 0, /* tp_iternext */ - 0, /* tp_methods */ - 0, /* tp_members */ - 0, /* tp_getset */ - 0, /* tp_base */ - 0, /* tp_dict */ - 0, /* tp_descr_get */ - 0, /* tp_descr_set */ - 0, /* tp_dictoffset */ - 0, /* tp_init */ - 0, /* tp_alloc */ - itemgetter_new, /* tp_new */ - 0, /* tp_free */ + PyVarObject_HEAD_INIT(NULL, 0) + "operator.itemgetter", /* tp_name */ + sizeof(itemgetterobject), /* tp_basicsize */ + 0, /* tp_itemsize */ + /* methods */ + (destructor)itemgetter_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 */ + (ternaryfunc)itemgetter_call, /* 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 */ + itemgetter_doc, /* tp_doc */ + (traverseproc)itemgetter_traverse, /* tp_traverse */ + 0, /* tp_clear */ + 0, /* tp_richcompare */ + 0, /* tp_weaklistoffset */ + 0, /* tp_iter */ + 0, /* tp_iternext */ + 0, /* tp_methods */ + 0, /* tp_members */ + 0, /* tp_getset */ + 0, /* tp_base */ + 0, /* tp_dict */ + 0, /* tp_descr_get */ + 0, /* tp_descr_set */ + 0, /* tp_dictoffset */ + 0, /* tp_init */ + 0, /* tp_alloc */ + itemgetter_new, /* tp_new */ + 0, /* tp_free */ }; /* attrgetter object **********************************************************/ typedef struct { - PyObject_HEAD - Py_ssize_t nattrs; - PyObject *attr; + PyObject_HEAD + Py_ssize_t nattrs; + PyObject *attr; } attrgetterobject; static PyTypeObject attrgetter_type; @@ -381,112 +381,112 @@ static PyObject * attrgetter_new(PyTypeObject *type, PyObject *args, PyObject *kwds) { - attrgetterobject *ag; - PyObject *attr; - Py_ssize_t nattrs; - - if (!_PyArg_NoKeywords("attrgetter()", kwds)) - return NULL; - - nattrs = PyTuple_GET_SIZE(args); - if (nattrs <= 1) { - if (!PyArg_UnpackTuple(args, "attrgetter", 1, 1, &attr)) - return NULL; - } else - attr = args; - - /* create attrgetterobject structure */ - ag = PyObject_GC_New(attrgetterobject, &attrgetter_type); - if (ag == NULL) - return NULL; - - Py_INCREF(attr); - ag->attr = attr; - ag->nattrs = nattrs; + attrgetterobject *ag; + PyObject *attr; + Py_ssize_t nattrs; + + if (!_PyArg_NoKeywords("attrgetter()", kwds)) + return NULL; + + nattrs = PyTuple_GET_SIZE(args); + if (nattrs <= 1) { + if (!PyArg_UnpackTuple(args, "attrgetter", 1, 1, &attr)) + return NULL; + } else + attr = args; + + /* create attrgetterobject structure */ + ag = PyObject_GC_New(attrgetterobject, &attrgetter_type); + if (ag == NULL) + return NULL; + + Py_INCREF(attr); + ag->attr = attr; + ag->nattrs = nattrs; - PyObject_GC_Track(ag); - return (PyObject *)ag; + PyObject_GC_Track(ag); + return (PyObject *)ag; } static void attrgetter_dealloc(attrgetterobject *ag) { - PyObject_GC_UnTrack(ag); - Py_XDECREF(ag->attr); - PyObject_GC_Del(ag); + PyObject_GC_UnTrack(ag); + Py_XDECREF(ag->attr); + PyObject_GC_Del(ag); } static int attrgetter_traverse(attrgetterobject *ag, visitproc visit, void *arg) { - Py_VISIT(ag->attr); - return 0; + Py_VISIT(ag->attr); + return 0; } static PyObject * dotted_getattr(PyObject *obj, PyObject *attr) { - char *s, *p; + char *s, *p; - if (!PyUnicode_Check(attr)) { - PyErr_SetString(PyExc_TypeError, - "attribute name must be a string"); - return NULL; - } - - s = _PyUnicode_AsString(attr); - Py_INCREF(obj); - for (;;) { - PyObject *newobj, *str; - p = strchr(s, '.'); - str = p ? PyUnicode_FromStringAndSize(s, (p-s)) : - PyUnicode_FromString(s); - if (str == NULL) { - Py_DECREF(obj); - return NULL; - } - newobj = PyObject_GetAttr(obj, str); - Py_DECREF(str); - Py_DECREF(obj); - if (newobj == NULL) - return NULL; - obj = newobj; - if (p == NULL) break; - s = p+1; - } + if (!PyUnicode_Check(attr)) { + PyErr_SetString(PyExc_TypeError, + "attribute name must be a string"); + return NULL; + } + + s = _PyUnicode_AsString(attr); + Py_INCREF(obj); + for (;;) { + PyObject *newobj, *str; + p = strchr(s, '.'); + str = p ? PyUnicode_FromStringAndSize(s, (p-s)) : + PyUnicode_FromString(s); + if (str == NULL) { + Py_DECREF(obj); + return NULL; + } + newobj = PyObject_GetAttr(obj, str); + Py_DECREF(str); + Py_DECREF(obj); + if (newobj == NULL) + return NULL; + obj = newobj; + if (p == NULL) break; + s = p+1; + } - return obj; + return obj; } static PyObject * attrgetter_call(attrgetterobject *ag, PyObject *args, PyObject *kw) { - PyObject *obj, *result; - Py_ssize_t i, nattrs=ag->nattrs; + PyObject *obj, *result; + Py_ssize_t i, nattrs=ag->nattrs; - if (!PyArg_UnpackTuple(args, "attrgetter", 1, 1, &obj)) - return NULL; - if (ag->nattrs == 1) - return dotted_getattr(obj, ag->attr); - - assert(PyTuple_Check(ag->attr)); - assert(PyTuple_GET_SIZE(ag->attr) == nattrs); - - result = PyTuple_New(nattrs); - if (result == NULL) - return NULL; - - for (i=0 ; i < nattrs ; i++) { - PyObject *attr, *val; - attr = PyTuple_GET_ITEM(ag->attr, i); - val = dotted_getattr(obj, attr); - if (val == NULL) { - Py_DECREF(result); - return NULL; - } - PyTuple_SET_ITEM(result, i, val); - } - return result; + if (!PyArg_UnpackTuple(args, "attrgetter", 1, 1, &obj)) + return NULL; + if (ag->nattrs == 1) + return dotted_getattr(obj, ag->attr); + + assert(PyTuple_Check(ag->attr)); + assert(PyTuple_GET_SIZE(ag->attr) == nattrs); + + result = PyTuple_New(nattrs); + if (result == NULL) + return NULL; + + for (i=0 ; i < nattrs ; i++) { + PyObject *attr, *val; + attr = PyTuple_GET_ITEM(ag->attr, i); + val = dotted_getattr(obj, attr); + if (val == NULL) { + Py_DECREF(result); + return NULL; + } + PyTuple_SET_ITEM(result, i, val); + } + return result; } PyDoc_STRVAR(attrgetter_doc, @@ -499,56 +499,56 @@ (r.name.first, r.name.last)."); static PyTypeObject attrgetter_type = { - PyVarObject_HEAD_INIT(NULL, 0) - "operator.attrgetter", /* tp_name */ - sizeof(attrgetterobject), /* tp_basicsize */ - 0, /* tp_itemsize */ - /* methods */ - (destructor)attrgetter_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 */ - (ternaryfunc)attrgetter_call, /* 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 */ - attrgetter_doc, /* tp_doc */ - (traverseproc)attrgetter_traverse, /* tp_traverse */ - 0, /* tp_clear */ - 0, /* tp_richcompare */ - 0, /* tp_weaklistoffset */ - 0, /* tp_iter */ - 0, /* tp_iternext */ - 0, /* tp_methods */ - 0, /* tp_members */ - 0, /* tp_getset */ - 0, /* tp_base */ - 0, /* tp_dict */ - 0, /* tp_descr_get */ - 0, /* tp_descr_set */ - 0, /* tp_dictoffset */ - 0, /* tp_init */ - 0, /* tp_alloc */ - attrgetter_new, /* tp_new */ - 0, /* tp_free */ + PyVarObject_HEAD_INIT(NULL, 0) + "operator.attrgetter", /* tp_name */ + sizeof(attrgetterobject), /* tp_basicsize */ + 0, /* tp_itemsize */ + /* methods */ + (destructor)attrgetter_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 */ + (ternaryfunc)attrgetter_call, /* 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 */ + attrgetter_doc, /* tp_doc */ + (traverseproc)attrgetter_traverse, /* tp_traverse */ + 0, /* tp_clear */ + 0, /* tp_richcompare */ + 0, /* tp_weaklistoffset */ + 0, /* tp_iter */ + 0, /* tp_iternext */ + 0, /* tp_methods */ + 0, /* tp_members */ + 0, /* tp_getset */ + 0, /* tp_base */ + 0, /* tp_dict */ + 0, /* tp_descr_get */ + 0, /* tp_descr_set */ + 0, /* tp_dictoffset */ + 0, /* tp_init */ + 0, /* tp_alloc */ + attrgetter_new, /* tp_new */ + 0, /* tp_free */ }; /* methodcaller object **********************************************************/ typedef struct { - PyObject_HEAD - PyObject *name; - PyObject *args; - PyObject *kwds; + PyObject_HEAD + PyObject *name; + PyObject *args; + PyObject *kwds; } methodcallerobject; static PyTypeObject methodcaller_type; @@ -556,69 +556,69 @@ static PyObject * methodcaller_new(PyTypeObject *type, PyObject *args, PyObject *kwds) { - methodcallerobject *mc; - PyObject *name, *newargs; + methodcallerobject *mc; + PyObject *name, *newargs; - if (PyTuple_GET_SIZE(args) < 1) { - PyErr_SetString(PyExc_TypeError, "methodcaller needs at least " - "one argument, the method name"); - return NULL; - } - - /* create methodcallerobject structure */ - mc = PyObject_GC_New(methodcallerobject, &methodcaller_type); - if (mc == NULL) - return NULL; - - newargs = PyTuple_GetSlice(args, 1, PyTuple_GET_SIZE(args)); - if (newargs == NULL) { - Py_DECREF(mc); - return NULL; - } - mc->args = newargs; - - name = PyTuple_GET_ITEM(args, 0); - Py_INCREF(name); - mc->name = name; + if (PyTuple_GET_SIZE(args) < 1) { + PyErr_SetString(PyExc_TypeError, "methodcaller needs at least " + "one argument, the method name"); + return NULL; + } + + /* create methodcallerobject structure */ + mc = PyObject_GC_New(methodcallerobject, &methodcaller_type); + if (mc == NULL) + return NULL; + + newargs = PyTuple_GetSlice(args, 1, PyTuple_GET_SIZE(args)); + if (newargs == NULL) { + Py_DECREF(mc); + return NULL; + } + mc->args = newargs; + + name = PyTuple_GET_ITEM(args, 0); + Py_INCREF(name); + mc->name = name; - Py_XINCREF(kwds); - mc->kwds = kwds; + Py_XINCREF(kwds); + mc->kwds = kwds; - PyObject_GC_Track(mc); - return (PyObject *)mc; + PyObject_GC_Track(mc); + return (PyObject *)mc; } static void methodcaller_dealloc(methodcallerobject *mc) { - PyObject_GC_UnTrack(mc); - Py_XDECREF(mc->name); - Py_XDECREF(mc->args); - Py_XDECREF(mc->kwds); - PyObject_GC_Del(mc); + PyObject_GC_UnTrack(mc); + Py_XDECREF(mc->name); + Py_XDECREF(mc->args); + Py_XDECREF(mc->kwds); + PyObject_GC_Del(mc); } static int methodcaller_traverse(methodcallerobject *mc, visitproc visit, void *arg) { - Py_VISIT(mc->args); - Py_VISIT(mc->kwds); - return 0; + Py_VISIT(mc->args); + Py_VISIT(mc->kwds); + return 0; } static PyObject * methodcaller_call(methodcallerobject *mc, PyObject *args, PyObject *kw) { - PyObject *method, *obj, *result; + PyObject *method, *obj, *result; - if (!PyArg_UnpackTuple(args, "methodcaller", 1, 1, &obj)) - return NULL; - method = PyObject_GetAttr(obj, mc->name); - if (method == NULL) - return NULL; - result = PyObject_Call(method, mc->args, mc->kwds); - Py_DECREF(method); - return result; + if (!PyArg_UnpackTuple(args, "methodcaller", 1, 1, &obj)) + return NULL; + method = PyObject_GetAttr(obj, mc->name); + if (method == NULL) + return NULL; + result = PyObject_Call(method, mc->args, mc->kwds); + Py_DECREF(method); + return result; } PyDoc_STRVAR(methodcaller_doc, @@ -630,46 +630,46 @@ r.name('date', foo=1)."); static PyTypeObject methodcaller_type = { - PyVarObject_HEAD_INIT(NULL, 0) - "operator.methodcaller", /* tp_name */ - sizeof(methodcallerobject), /* tp_basicsize */ - 0, /* tp_itemsize */ - /* methods */ - (destructor)methodcaller_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 */ - (ternaryfunc)methodcaller_call, /* 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 */ - methodcaller_doc, /* tp_doc */ - (traverseproc)methodcaller_traverse, /* tp_traverse */ - 0, /* tp_clear */ - 0, /* tp_richcompare */ - 0, /* tp_weaklistoffset */ - 0, /* tp_iter */ - 0, /* tp_iternext */ - 0, /* tp_methods */ - 0, /* tp_members */ - 0, /* tp_getset */ - 0, /* tp_base */ - 0, /* tp_dict */ - 0, /* tp_descr_get */ - 0, /* tp_descr_set */ - 0, /* tp_dictoffset */ - 0, /* tp_init */ - 0, /* tp_alloc */ - methodcaller_new, /* tp_new */ - 0, /* tp_free */ + PyVarObject_HEAD_INIT(NULL, 0) + "operator.methodcaller", /* tp_name */ + sizeof(methodcallerobject), /* tp_basicsize */ + 0, /* tp_itemsize */ + /* methods */ + (destructor)methodcaller_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 */ + (ternaryfunc)methodcaller_call, /* 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 */ + methodcaller_doc, /* tp_doc */ + (traverseproc)methodcaller_traverse, /* tp_traverse */ + 0, /* tp_clear */ + 0, /* tp_richcompare */ + 0, /* tp_weaklistoffset */ + 0, /* tp_iter */ + 0, /* tp_iternext */ + 0, /* tp_methods */ + 0, /* tp_members */ + 0, /* tp_getset */ + 0, /* tp_base */ + 0, /* tp_dict */ + 0, /* tp_descr_get */ + 0, /* tp_descr_set */ + 0, /* tp_dictoffset */ + 0, /* tp_init */ + 0, /* tp_alloc */ + methodcaller_new, /* tp_new */ + 0, /* tp_free */ }; @@ -677,40 +677,40 @@ static struct PyModuleDef operatormodule = { - PyModuleDef_HEAD_INIT, - "operator", - operator_doc, - -1, - operator_methods, - NULL, - NULL, - NULL, - NULL + PyModuleDef_HEAD_INIT, + "operator", + operator_doc, + -1, + operator_methods, + NULL, + NULL, + NULL, + NULL }; PyMODINIT_FUNC PyInit_operator(void) { - PyObject *m; - - /* Create the module and add the functions */ - m = PyModule_Create(&operatormodule); - if (m == NULL) - return NULL; - - if (PyType_Ready(&itemgetter_type) < 0) - return NULL; - Py_INCREF(&itemgetter_type); - PyModule_AddObject(m, "itemgetter", (PyObject *)&itemgetter_type); - - if (PyType_Ready(&attrgetter_type) < 0) - return NULL; - Py_INCREF(&attrgetter_type); - PyModule_AddObject(m, "attrgetter", (PyObject *)&attrgetter_type); - - if (PyType_Ready(&methodcaller_type) < 0) - return NULL; - Py_INCREF(&methodcaller_type); - PyModule_AddObject(m, "methodcaller", (PyObject *)&methodcaller_type); - return m; + PyObject *m; + + /* Create the module and add the functions */ + m = PyModule_Create(&operatormodule); + if (m == NULL) + return NULL; + + if (PyType_Ready(&itemgetter_type) < 0) + return NULL; + Py_INCREF(&itemgetter_type); + PyModule_AddObject(m, "itemgetter", (PyObject *)&itemgetter_type); + + if (PyType_Ready(&attrgetter_type) < 0) + return NULL; + Py_INCREF(&attrgetter_type); + PyModule_AddObject(m, "attrgetter", (PyObject *)&attrgetter_type); + + if (PyType_Ready(&methodcaller_type) < 0) + return NULL; + Py_INCREF(&methodcaller_type); + PyModule_AddObject(m, "methodcaller", (PyObject *)&methodcaller_type); + return m; } Modified: python/branches/py3k-jit/Modules/ossaudiodev.c ============================================================================== --- python/branches/py3k-jit/Modules/ossaudiodev.c (original) +++ python/branches/py3k-jit/Modules/ossaudiodev.c Mon May 10 23:55:43 2010 @@ -809,8 +809,8 @@ PyObject * rval = NULL; if (PyUnicode_Check(nameobj)) - name = _PyUnicode_AsString(nameobj); - + name = _PyUnicode_AsString(nameobj); + if (strcmp(name, "closed") == 0) { rval = (self->fd == -1) ? Py_True : Py_False; Py_INCREF(rval); @@ -975,15 +975,15 @@ static struct PyModuleDef ossaudiodevmodule = { - PyModuleDef_HEAD_INIT, - "ossaudiodev", - NULL, - -1, - ossaudiodev_methods, - NULL, - NULL, - NULL, - NULL + PyModuleDef_HEAD_INIT, + "ossaudiodev", + NULL, + -1, + ossaudiodev_methods, + NULL, + NULL, + NULL, + NULL }; PyMODINIT_FUNC @@ -999,10 +999,10 @@ m = PyModule_Create(&ossaudiodevmodule); if (m == NULL) - return NULL; + return NULL; OSSAudioError = PyErr_NewException("ossaudiodev.OSSAudioError", - NULL, NULL); + NULL, NULL); if (OSSAudioError) { /* Each call to PyModule_AddObject decrefs it; compensate: */ Py_INCREF(OSSAudioError); Modified: python/branches/py3k-jit/Modules/parsermodule.c ============================================================================== --- python/branches/py3k-jit/Modules/parsermodule.c (original) +++ python/branches/py3k-jit/Modules/parsermodule.c Mon May 10 23:55:43 2010 @@ -578,8 +578,8 @@ ? eval_input : file_input, &err, &flags); - if (n) { - res = parser_newstobject(n, type); + if (n) { + res = parser_newstobject(n, type); if (res) ((PyST_Object *)res)->st_flags.cf_flags = flags & PyCF_MASK; } @@ -784,7 +784,7 @@ PyErr_Format(parser_error, "third item in terminal node must be an" " integer, found %s", - Py_TYPE(temp)->tp_name); + Py_TYPE(temp)->tp_name); Py_DECREF(o); Py_DECREF(temp); Py_DECREF(elem); @@ -1051,7 +1051,7 @@ { int nch = NCH(tree); int res = (validate_ntype(tree, classdef) && - ((nch == 4) || (nch == 6) || (nch == 7))); + ((nch == 4) || (nch == 6) || (nch == 7))); if (res) { res = (validate_name(CHILD(tree, 0), "class") @@ -1064,15 +1064,15 @@ } if (res) { - if (nch == 7) { - res = ((validate_lparen(CHILD(tree, 2)) && - validate_arglist(CHILD(tree, 3)) && - validate_rparen(CHILD(tree, 4)))); - } - else if (nch == 6) { - res = (validate_lparen(CHILD(tree,2)) && - validate_rparen(CHILD(tree,3))); - } + if (nch == 7) { + res = ((validate_lparen(CHILD(tree, 2)) && + validate_arglist(CHILD(tree, 3)) && + validate_rparen(CHILD(tree, 4)))); + } + else if (nch == 6) { + res = (validate_lparen(CHILD(tree,2)) && + validate_rparen(CHILD(tree,3))); + } } return (res); } @@ -1244,10 +1244,10 @@ else { /* skip over vfpdef (',' vfpdef ['=' test])* */ i = start + 1; - if (TYPE(CHILD(tree, i)) == vfpdef || - TYPE(CHILD(tree, i)) == tfpdef) { /* skip over vfpdef or tfpdef */ - i += 1; - } + if (TYPE(CHILD(tree, i)) == vfpdef || + TYPE(CHILD(tree, i)) == tfpdef) { /* skip over vfpdef or tfpdef */ + i += 1; + } while (res && i+1 < nch) { /* validate (',' vfpdef ['=' test])* */ res = validate_comma(CHILD(tree, i)); if (TYPE(CHILD(tree, i+1)) == DOUBLESTAR) @@ -1718,14 +1718,14 @@ static int validate_dotted_as_names(node *tree) { - int nch = NCH(tree); - int res = is_odd(nch) && validate_dotted_as_name(CHILD(tree, 0)); - int i; - - for (i = 1; res && (i < nch); i += 2) - res = (validate_comma(CHILD(tree, i)) - && validate_dotted_as_name(CHILD(tree, i + 1))); - return (res); + int nch = NCH(tree); + int res = is_odd(nch) && validate_dotted_as_name(CHILD(tree, 0)); + int i; + + for (i = 1; res && (i < nch); i += 2) + res = (validate_comma(CHILD(tree, i)) + && validate_dotted_as_name(CHILD(tree, i + 1))); + return (res); } @@ -1738,8 +1738,8 @@ int i; for (i = 1; res && (i + 1 < nch); i += 2) - res = (validate_comma(CHILD(tree, i)) - && validate_import_as_name(CHILD(tree, i + 1))); + res = (validate_comma(CHILD(tree, i)) + && validate_import_as_name(CHILD(tree, i + 1))); return (res); } @@ -1748,10 +1748,10 @@ static int validate_import_name(node *tree) { - return (validate_ntype(tree, import_name) - && validate_numnodes(tree, 2, "import_name") - && validate_name(CHILD(tree, 0), "import") - && validate_dotted_as_names(CHILD(tree, 1))); + return (validate_ntype(tree, import_name) + && validate_numnodes(tree, 2, "import_name") + && validate_name(CHILD(tree, 0), "import") + && validate_dotted_as_names(CHILD(tree, 1))); } /* Helper function to count the number of leading dots in @@ -1762,8 +1762,8 @@ { int i; for (i = 1; i < NCH(tree); i++) - if (TYPE(CHILD(tree, i)) != DOT) - break; + if (TYPE(CHILD(tree, i)) != DOT) + break; return i-1; } @@ -1773,24 +1773,24 @@ static int validate_import_from(node *tree) { - int nch = NCH(tree); - int ndots = count_from_dots(tree); - int havename = (TYPE(CHILD(tree, ndots + 1)) == dotted_name); - int offset = ndots + havename; - int res = validate_ntype(tree, import_from) - && (nch >= 4 + ndots) - && validate_name(CHILD(tree, 0), "from") - && (!havename || validate_dotted_name(CHILD(tree, ndots + 1))) - && validate_name(CHILD(tree, offset + 1), "import"); - - if (res && TYPE(CHILD(tree, offset + 2)) == LPAR) - res = ((nch == offset + 5) - && validate_lparen(CHILD(tree, offset + 2)) - && validate_import_as_names(CHILD(tree, offset + 3)) - && validate_rparen(CHILD(tree, offset + 4))); - else if (res && TYPE(CHILD(tree, offset + 2)) != STAR) - res = validate_import_as_names(CHILD(tree, offset + 2)); - return (res); + int nch = NCH(tree); + int ndots = count_from_dots(tree); + int havename = (TYPE(CHILD(tree, ndots + 1)) == dotted_name); + int offset = ndots + havename; + int res = validate_ntype(tree, import_from) + && (nch >= 4 + ndots) + && validate_name(CHILD(tree, 0), "from") + && (!havename || validate_dotted_name(CHILD(tree, ndots + 1))) + && validate_name(CHILD(tree, offset + 1), "import"); + + if (res && TYPE(CHILD(tree, offset + 2)) == LPAR) + res = ((nch == offset + 5) + && validate_lparen(CHILD(tree, offset + 2)) + && validate_import_as_names(CHILD(tree, offset + 3)) + && validate_rparen(CHILD(tree, offset + 4))); + else if (res && TYPE(CHILD(tree, offset + 2)) != STAR) + res = validate_import_as_names(CHILD(tree, offset + 2)); + return (res); } @@ -1802,9 +1802,9 @@ int res = validate_numnodes(tree, 1, "import_stmt"); if (res) { - int ntype = TYPE(CHILD(tree, 0)); + int ntype = TYPE(CHILD(tree, 0)); - if (ntype == import_name || ntype == import_from) + if (ntype == import_name || ntype == import_from) res = validate_node(CHILD(tree, 0)); else { res = 0; @@ -2323,11 +2323,11 @@ && (validate_rparen(CHILD(tree, nch - 1)))); if (res && (nch == 3)) { - if (TYPE(CHILD(tree, 1))==yield_expr) - res = validate_yield_expr(CHILD(tree, 1)); - else - res = validate_testlist_comp(CHILD(tree, 1)); - } + if (TYPE(CHILD(tree, 1))==yield_expr) + res = validate_yield_expr(CHILD(tree, 1)); + else + res = validate_testlist_comp(CHILD(tree, 1)); + } break; case LSQB: if (nch == 2) @@ -2355,11 +2355,11 @@ for (pos = 1; res && (pos < nch); ++pos) res = validate_ntype(CHILD(tree, pos), STRING); break; - case DOT: - res = (nch == 3 && - validate_ntype(CHILD(tree, 1), DOT) && - validate_ntype(CHILD(tree, 2), DOT)); - break; + case DOT: + res = (nch == 3 && + validate_ntype(CHILD(tree, 1), DOT) && + validate_ntype(CHILD(tree, 2), DOT)); + break; default: res = 0; break; @@ -2416,17 +2416,17 @@ int ok; int nch = NCH(tree); ok = (validate_ntype(tree, decorator) && - (nch == 3 || nch == 5 || nch == 6) && - validate_at(CHILD(tree, 0)) && - validate_dotted_name(CHILD(tree, 1)) && - validate_newline(RCHILD(tree, -1))); + (nch == 3 || nch == 5 || nch == 6) && + validate_at(CHILD(tree, 0)) && + validate_dotted_name(CHILD(tree, 1)) && + validate_newline(RCHILD(tree, -1))); if (ok && nch != 3) { - ok = (validate_lparen(CHILD(tree, 2)) && - validate_rparen(RCHILD(tree, -2))); + ok = (validate_lparen(CHILD(tree, 2)) && + validate_rparen(RCHILD(tree, -2))); - if (ok && nch == 6) - ok = validate_arglist(CHILD(tree, 3)); + if (ok && nch == 6) + ok = validate_arglist(CHILD(tree, 3)); } return ok; @@ -2443,7 +2443,7 @@ ok = validate_ntype(tree, decorators) && nch >= 1; for (i = 0; ok && i < nch; ++i) - ok = validate_decorator(CHILD(tree, i)); + ok = validate_decorator(CHILD(tree, i)); return ok; } @@ -2458,7 +2458,7 @@ int ok = (validate_ntype(tree, with_item) && (nch == 1 || nch == 3) && validate_test(CHILD(tree, 0))); - if (ok && nch == 3) + if (ok && nch == 3) ok = (validate_name(CHILD(tree, 1), "as") && validate_expr(CHILD(tree, 2))); return ok; @@ -2493,12 +2493,12 @@ { int nch = NCH(tree); int ok = (validate_ntype(tree, funcdef) - && (nch == 5) - && validate_name(RCHILD(tree, -5), "def") - && validate_ntype(RCHILD(tree, -4), NAME) - && validate_colon(RCHILD(tree, -2)) - && validate_parameters(RCHILD(tree, -3)) - && validate_suite(RCHILD(tree, -1))); + && (nch == 5) + && validate_name(RCHILD(tree, -5), "def") + && validate_ntype(RCHILD(tree, -4), NAME) + && validate_colon(RCHILD(tree, -2)) + && validate_parameters(RCHILD(tree, -3)) + && validate_suite(RCHILD(tree, -1))); return ok; } @@ -2511,11 +2511,11 @@ { int nch = NCH(tree); int ok = (validate_ntype(tree, decorated) - && (nch == 2) - && validate_decorators(RCHILD(tree, -2)) - && (validate_funcdef(RCHILD(tree, -1)) - || validate_class(RCHILD(tree, -1))) - ); + && (nch == 2) + && validate_decorators(RCHILD(tree, -2)) + && (validate_funcdef(RCHILD(tree, -1)) + || validate_class(RCHILD(tree, -1))) + ); return ok; } @@ -2882,9 +2882,9 @@ case classdef: res = validate_class(tree); break; - case decorated: - res = validate_decorated(tree); - break; + case decorated: + res = validate_decorated(tree); + break; /* * "Trivial" parse tree nodes. * (Why did I call these trivial?) @@ -2953,12 +2953,12 @@ case import_stmt: res = validate_import_stmt(tree); break; - case import_name: - res = validate_import_name(tree); - break; - case import_from: - res = validate_import_from(tree); - break; + case import_name: + res = validate_import_name(tree); + break; + case import_from: + res = validate_import_from(tree); + break; case global_stmt: res = validate_global_stmt(tree); break; @@ -3170,15 +3170,15 @@ static struct PyModuleDef parsermodule = { - PyModuleDef_HEAD_INIT, - "parser", - NULL, - -1, - parser_functions, - NULL, - NULL, - NULL, - NULL + PyModuleDef_HEAD_INIT, + "parser", + NULL, + -1, + parser_functions, + NULL, + NULL, + NULL, + NULL }; PyMODINIT_FUNC PyInit_parser(void); /* supply a prototype */ @@ -3192,7 +3192,7 @@ return NULL; module = PyModule_Create(&parsermodule); if (module == NULL) - return NULL; + return NULL; if (parser_error == 0) parser_error = PyErr_NewException("parser.ParserError", NULL, NULL); Modified: python/branches/py3k-jit/Modules/pwdmodule.c ============================================================================== --- python/branches/py3k-jit/Modules/pwdmodule.c (original) +++ python/branches/py3k-jit/Modules/pwdmodule.c Mon May 10 23:55:43 2010 @@ -8,14 +8,14 @@ #include static PyStructSequence_Field struct_pwd_type_fields[] = { - {"pw_name", "user name"}, - {"pw_passwd", "password"}, - {"pw_uid", "user id"}, - {"pw_gid", "group id"}, - {"pw_gecos", "real name"}, - {"pw_dir", "home directory"}, - {"pw_shell", "shell program"}, - {0} + {"pw_name", "user name"}, + {"pw_passwd", "password"}, + {"pw_uid", "user id"}, + {"pw_gid", "group id"}, + {"pw_gecos", "real name"}, + {"pw_dir", "home directory"}, + {"pw_shell", "shell program"}, + {0} }; PyDoc_STRVAR(struct_passwd__doc__, @@ -25,10 +25,10 @@ or via the object attributes as named in the above tuple."); static PyStructSequence_Desc struct_pwd_type_desc = { - "pwd.struct_passwd", - struct_passwd__doc__, - struct_pwd_type_fields, - 7, + "pwd.struct_passwd", + struct_passwd__doc__, + struct_pwd_type_fields, + 7, }; PyDoc_STRVAR(pwd__doc__, @@ -41,7 +41,7 @@ The uid and gid items are integers, all others are strings. An\n\ exception is raised if the entry asked for cannot be found."); - + static int initialized; static PyTypeObject StructPwdType; @@ -49,51 +49,51 @@ sets(PyObject *v, int i, const char* val) { if (val) { - PyObject *o = PyUnicode_DecodeFSDefault(val); - PyStructSequence_SET_ITEM(v, i, o); + PyObject *o = PyUnicode_DecodeFSDefault(val); + PyStructSequence_SET_ITEM(v, i, o); } else { - PyStructSequence_SET_ITEM(v, i, Py_None); - Py_INCREF(Py_None); + PyStructSequence_SET_ITEM(v, i, Py_None); + Py_INCREF(Py_None); } } static PyObject * mkpwent(struct passwd *p) { - int setIndex = 0; - PyObject *v = PyStructSequence_New(&StructPwdType); - if (v == NULL) - return NULL; + int setIndex = 0; + PyObject *v = PyStructSequence_New(&StructPwdType); + if (v == NULL) + return NULL; #define SETI(i,val) PyStructSequence_SET_ITEM(v, i, PyLong_FromLong((long) val)) #define SETS(i,val) sets(v, i, val) - SETS(setIndex++, p->pw_name); + SETS(setIndex++, p->pw_name); #ifdef __VMS - SETS(setIndex++, ""); + SETS(setIndex++, ""); #else - SETS(setIndex++, p->pw_passwd); + SETS(setIndex++, p->pw_passwd); #endif - SETI(setIndex++, p->pw_uid); - SETI(setIndex++, p->pw_gid); + SETI(setIndex++, p->pw_uid); + SETI(setIndex++, p->pw_gid); #ifdef __VMS - SETS(setIndex++, ""); + SETS(setIndex++, ""); #else - SETS(setIndex++, p->pw_gecos); + SETS(setIndex++, p->pw_gecos); #endif - SETS(setIndex++, p->pw_dir); - SETS(setIndex++, p->pw_shell); + SETS(setIndex++, p->pw_dir); + SETS(setIndex++, p->pw_shell); #undef SETS #undef SETI - if (PyErr_Occurred()) { - Py_XDECREF(v); - return NULL; - } + if (PyErr_Occurred()) { + Py_XDECREF(v); + return NULL; + } - return v; + return v; } PyDoc_STRVAR(pwd_getpwuid__doc__, @@ -105,16 +105,16 @@ static PyObject * pwd_getpwuid(PyObject *self, PyObject *args) { - unsigned int uid; - struct passwd *p; - if (!PyArg_ParseTuple(args, "I:getpwuid", &uid)) - return NULL; - if ((p = getpwuid(uid)) == NULL) { - PyErr_Format(PyExc_KeyError, - "getpwuid(): uid not found: %d", uid); - return NULL; - } - return mkpwent(p); + unsigned int uid; + struct passwd *p; + if (!PyArg_ParseTuple(args, "I:getpwuid", &uid)) + return NULL; + if ((p = getpwuid(uid)) == NULL) { + PyErr_Format(PyExc_KeyError, + "getpwuid(): uid not found: %d", uid); + return NULL; + } + return mkpwent(p); } PyDoc_STRVAR(pwd_getpwnam__doc__, @@ -126,27 +126,27 @@ static PyObject * pwd_getpwnam(PyObject *self, PyObject *args) { - char *name; - struct passwd *p; - PyObject *arg, *bytes, *retval = NULL; - - if (!PyArg_ParseTuple(args, "U:getpwnam", &arg)) - return NULL; - if ((bytes = PyUnicode_AsEncodedString(arg, - Py_FileSystemDefaultEncoding, - "surrogateescape")) == NULL) - return NULL; - if (PyBytes_AsStringAndSize(bytes, &name, NULL) == -1) - goto out; - if ((p = getpwnam(name)) == NULL) { - PyErr_Format(PyExc_KeyError, - "getpwnam(): name not found: %s", name); - goto out; - } - retval = mkpwent(p); + char *name; + struct passwd *p; + PyObject *arg, *bytes, *retval = NULL; + + if (!PyArg_ParseTuple(args, "U:getpwnam", &arg)) + return NULL; + if ((bytes = PyUnicode_AsEncodedString(arg, + Py_FileSystemDefaultEncoding, + "surrogateescape")) == NULL) + return NULL; + if (PyBytes_AsStringAndSize(bytes, &name, NULL) == -1) + goto out; + if ((p = getpwnam(name)) == NULL) { + PyErr_Format(PyExc_KeyError, + "getpwnam(): name not found: %s", name); + goto out; + } + retval = mkpwent(p); out: - Py_DECREF(bytes); - return retval; + Py_DECREF(bytes); + return retval; } #ifdef HAVE_GETPWENT @@ -159,67 +159,67 @@ static PyObject * pwd_getpwall(PyObject *self) { - PyObject *d; - struct passwd *p; - if ((d = PyList_New(0)) == NULL) - return NULL; + PyObject *d; + struct passwd *p; + if ((d = PyList_New(0)) == NULL) + return NULL; #if defined(PYOS_OS2) && defined(PYCC_GCC) - if ((p = getpwuid(0)) != NULL) { + if ((p = getpwuid(0)) != NULL) { #else - setpwent(); - while ((p = getpwent()) != NULL) { + setpwent(); + while ((p = getpwent()) != NULL) { #endif - PyObject *v = mkpwent(p); - if (v == NULL || PyList_Append(d, v) != 0) { - Py_XDECREF(v); - Py_DECREF(d); - endpwent(); - return NULL; - } - Py_DECREF(v); - } - endpwent(); - return d; + PyObject *v = mkpwent(p); + if (v == NULL || PyList_Append(d, v) != 0) { + Py_XDECREF(v); + Py_DECREF(d); + endpwent(); + return NULL; + } + Py_DECREF(v); + } + endpwent(); + return d; } #endif static PyMethodDef pwd_methods[] = { - {"getpwuid", pwd_getpwuid, METH_VARARGS, pwd_getpwuid__doc__}, - {"getpwnam", pwd_getpwnam, METH_VARARGS, pwd_getpwnam__doc__}, + {"getpwuid", pwd_getpwuid, METH_VARARGS, pwd_getpwuid__doc__}, + {"getpwnam", pwd_getpwnam, METH_VARARGS, pwd_getpwnam__doc__}, #ifdef HAVE_GETPWENT - {"getpwall", (PyCFunction)pwd_getpwall, - METH_NOARGS, pwd_getpwall__doc__}, + {"getpwall", (PyCFunction)pwd_getpwall, + METH_NOARGS, pwd_getpwall__doc__}, #endif - {NULL, NULL} /* sentinel */ + {NULL, NULL} /* sentinel */ }; static struct PyModuleDef pwdmodule = { - PyModuleDef_HEAD_INIT, - "pwd", - pwd__doc__, - -1, - pwd_methods, - NULL, - NULL, - NULL, - NULL + PyModuleDef_HEAD_INIT, + "pwd", + pwd__doc__, + -1, + pwd_methods, + NULL, + NULL, + NULL, + NULL }; PyMODINIT_FUNC PyInit_pwd(void) { - PyObject *m; - m = PyModule_Create(&pwdmodule); - if (m == NULL) - return NULL; - - if (!initialized) { - PyStructSequence_InitType(&StructPwdType, - &struct_pwd_type_desc); - initialized = 1; - } - Py_INCREF((PyObject *) &StructPwdType); - PyModule_AddObject(m, "struct_passwd", (PyObject *) &StructPwdType); - return m; + PyObject *m; + m = PyModule_Create(&pwdmodule); + if (m == NULL) + return NULL; + + if (!initialized) { + PyStructSequence_InitType(&StructPwdType, + &struct_pwd_type_desc); + initialized = 1; + } + Py_INCREF((PyObject *) &StructPwdType); + PyModule_AddObject(m, "struct_passwd", (PyObject *) &StructPwdType); + return m; } Modified: python/branches/py3k-jit/Modules/pyexpat.c ============================================================================== --- python/branches/py3k-jit/Modules/pyexpat.c (original) +++ python/branches/py3k-jit/Modules/pyexpat.c Mon May 10 23:55:43 2010 @@ -193,7 +193,7 @@ used only from the character data handler trampoline, and must be used right after `flag_error()` is called. */ static void -noop_character_data_handler(void *userData, const XML_Char *data, int len) +noop_character_data_handler(void *userData, const XML_Char *data, int len) { /* Do nothing. */ } @@ -222,25 +222,25 @@ { int result = 0; if (!tstate->use_tracing || tstate->tracing) - return 0; + return 0; if (tstate->c_profilefunc != NULL) { - tstate->tracing++; - result = tstate->c_profilefunc(tstate->c_profileobj, - f, code , val); - tstate->use_tracing = ((tstate->c_tracefunc != NULL) - || (tstate->c_profilefunc != NULL)); - tstate->tracing--; - if (result) - return result; + tstate->tracing++; + result = tstate->c_profilefunc(tstate->c_profileobj, + f, code , val); + tstate->use_tracing = ((tstate->c_tracefunc != NULL) + || (tstate->c_profilefunc != NULL)); + tstate->tracing--; + if (result) + return result; } if (tstate->c_tracefunc != NULL) { - tstate->tracing++; - result = tstate->c_tracefunc(tstate->c_traceobj, - f, code , val); - tstate->use_tracing = ((tstate->c_tracefunc != NULL) - || (tstate->c_profilefunc != NULL)); - tstate->tracing--; - } + tstate->tracing++; + result = tstate->c_tracefunc(tstate->c_traceobj, + f, code , val); + tstate->use_tracing = ((tstate->c_tracefunc != NULL) + || (tstate->c_profilefunc != NULL)); + tstate->tracing--; + } return result; } @@ -251,12 +251,12 @@ int err; if (tstate->c_tracefunc == NULL) - return 0; + return 0; PyErr_Fetch(&type, &value, &traceback); if (value == NULL) { - value = Py_None; - Py_INCREF(value); + value = Py_None; + Py_INCREF(value); } #if PY_VERSION_HEX < 0x02040000 arg = Py_BuildValue("(OOO)", type, value, traceback); @@ -264,17 +264,17 @@ arg = PyTuple_Pack(3, type, value, traceback); #endif if (arg == NULL) { - PyErr_Restore(type, value, traceback); - return 0; + PyErr_Restore(type, value, traceback); + return 0; } err = trace_frame(tstate, f, PyTrace_EXCEPTION, arg); Py_DECREF(arg); if (err == 0) - PyErr_Restore(type, value, traceback); + PyErr_Restore(type, value, traceback); else { - Py_XDECREF(type); - Py_XDECREF(value); - Py_XDECREF(traceback); + Py_XDECREF(type); + Py_XDECREF(value); + Py_XDECREF(traceback); } return err; } @@ -290,31 +290,31 @@ if (c == NULL) return NULL; - + f = PyFrame_New(tstate, c, PyEval_GetGlobals(), NULL); if (f == NULL) return NULL; tstate->frame = f; #ifdef FIX_TRACE if (trace_frame(tstate, f, PyTrace_CALL, Py_None) < 0) { - return NULL; + return NULL; } #endif res = PyEval_CallObject(func, args); if (res == NULL) { - if (tstate->curexc_traceback == NULL) - PyTraceBack_Here(f); + if (tstate->curexc_traceback == NULL) + PyTraceBack_Here(f); XML_StopParser(self->itself, XML_FALSE); #ifdef FIX_TRACE - if (trace_frame_exc(tstate, f) < 0) { - return NULL; - } + if (trace_frame_exc(tstate, f) < 0) { + return NULL; + } } else { - if (trace_frame(tstate, f, PyTrace_RETURN, res) < 0) { - Py_XDECREF(res); - res = NULL; - } + if (trace_frame(tstate, f, PyTrace_RETURN, res) < 0) { + Py_XDECREF(res); + res = NULL; + } } #else } @@ -331,12 +331,12 @@ PyObject *value; /* result can be NULL if the unicode conversion failed. */ if (!result) - return result; + return result; if (!self->intern) - return result; + return result; value = PyDict_GetItem(self->intern, result); if (!value) { - if (PyDict_SetItem(self->intern, result, result) == 0) + if (PyDict_SetItem(self->intern, result, result) == 0) return result; else return NULL; @@ -396,7 +396,7 @@ } static void -my_CharacterDataHandler(void *userData, const XML_Char *data, int len) +my_CharacterDataHandler(void *userData, const XML_Char *data, int len) { xmlparseobject *self = (xmlparseobject *) userData; if (self->buffer == NULL) @@ -536,13 +536,13 @@ } #define VOID_HANDLER(NAME, PARAMS, PARAM_FORMAT) \ - RC_HANDLER(void, NAME, PARAMS, ;, PARAM_FORMAT, ;, ;,\ - (xmlparseobject *)userData) + RC_HANDLER(void, NAME, PARAMS, ;, PARAM_FORMAT, ;, ;,\ + (xmlparseobject *)userData) #define INT_HANDLER(NAME, PARAMS, PARAM_FORMAT)\ - RC_HANDLER(int, NAME, PARAMS, int rc=0;, PARAM_FORMAT, \ - rc = PyLong_AsLong(rv);, rc, \ - (xmlparseobject *)userData) + RC_HANDLER(int, NAME, PARAMS, int rc=0;, PARAM_FORMAT, \ + rc = PyLong_AsLong(rv);, rc, \ + (xmlparseobject *)userData) VOID_HANDLER(EndElement, (void *userData, const XML_Char *name), @@ -687,25 +687,25 @@ #endif VOID_HANDLER(NotationDecl, - (void *userData, - const XML_Char *notationName, - const XML_Char *base, - const XML_Char *systemId, - const XML_Char *publicId), + (void *userData, + const XML_Char *notationName, + const XML_Char *base, + const XML_Char *systemId, + const XML_Char *publicId), ("(NNNN)", - string_intern(self, notationName), string_intern(self, base), - string_intern(self, systemId), string_intern(self, publicId))) + string_intern(self, notationName), string_intern(self, base), + string_intern(self, systemId), string_intern(self, publicId))) VOID_HANDLER(StartNamespaceDecl, - (void *userData, - const XML_Char *prefix, - const XML_Char *uri), + (void *userData, + const XML_Char *prefix, + const XML_Char *uri), ("(NN)", string_intern(self, prefix), string_intern(self, uri))) VOID_HANDLER(EndNamespaceDecl, - (void *userData, - const XML_Char *prefix), + (void *userData, + const XML_Char *prefix), ("(N)", string_intern(self, prefix))) VOID_HANDLER(Comment, @@ -714,36 +714,36 @@ VOID_HANDLER(StartCdataSection, (void *userData), - ("()")) + ("()")) VOID_HANDLER(EndCdataSection, (void *userData), - ("()")) + ("()")) VOID_HANDLER(Default, - (void *userData, const XML_Char *s, int len), - ("(N)", (conv_string_len_to_unicode(s,len)))) + (void *userData, const XML_Char *s, int len), + ("(N)", (conv_string_len_to_unicode(s,len)))) VOID_HANDLER(DefaultHandlerExpand, - (void *userData, const XML_Char *s, int len), - ("(N)", (conv_string_len_to_unicode(s,len)))) + (void *userData, const XML_Char *s, int len), + ("(N)", (conv_string_len_to_unicode(s,len)))) INT_HANDLER(NotStandalone, - (void *userData), - ("()")) + (void *userData), + ("()")) RC_HANDLER(int, ExternalEntityRef, - (XML_Parser parser, - const XML_Char *context, - const XML_Char *base, - const XML_Char *systemId, - const XML_Char *publicId), - int rc=0;, + (XML_Parser parser, + const XML_Char *context, + const XML_Char *base, + const XML_Char *systemId, + const XML_Char *publicId), + int rc=0;, ("(O&NNN)", - conv_string_to_unicode ,context, string_intern(self, base), - string_intern(self, systemId), string_intern(self, publicId)), - rc = PyLong_AsLong(rv);, rc, - XML_GetUserData(parser)) + conv_string_to_unicode ,context, string_intern(self, base), + string_intern(self, systemId), string_intern(self, publicId)), + rc = PyLong_AsLong(rv);, rc, + XML_GetUserData(parser)) /* XXX UnknownEncodingHandler */ @@ -915,7 +915,7 @@ if (!PyArg_ParseTuple(args, "s:SetBase", &base)) return NULL; if (!XML_SetBase(self->itself, base)) { - return PyErr_NoMemory(); + return PyErr_NoMemory(); } Py_INCREF(Py_None); return Py_None; @@ -1005,7 +1005,7 @@ new_parser->in_callback = 0; new_parser->ns_prefixes = self->ns_prefixes; new_parser->itself = XML_ExternalEntityParserCreate(self->itself, context, - encoding); + encoding); new_parser->handlers = 0; new_parser->intern = self->intern; Py_XINCREF(new_parser->intern); @@ -1096,26 +1096,26 @@ static PyObject *xmlparse_dir(PyObject *self, PyObject* noargs); static struct PyMethodDef xmlparse_methods[] = { - {"Parse", (PyCFunction)xmlparse_Parse, - METH_VARARGS, xmlparse_Parse__doc__}, + {"Parse", (PyCFunction)xmlparse_Parse, + METH_VARARGS, xmlparse_Parse__doc__}, {"ParseFile", (PyCFunction)xmlparse_ParseFile, - METH_O, xmlparse_ParseFile__doc__}, + METH_O, xmlparse_ParseFile__doc__}, {"SetBase", (PyCFunction)xmlparse_SetBase, - METH_VARARGS, xmlparse_SetBase__doc__}, + METH_VARARGS, xmlparse_SetBase__doc__}, {"GetBase", (PyCFunction)xmlparse_GetBase, - METH_NOARGS, xmlparse_GetBase__doc__}, + METH_NOARGS, xmlparse_GetBase__doc__}, {"ExternalEntityParserCreate", (PyCFunction)xmlparse_ExternalEntityParserCreate, - METH_VARARGS, xmlparse_ExternalEntityParserCreate__doc__}, + METH_VARARGS, xmlparse_ExternalEntityParserCreate__doc__}, {"SetParamEntityParsing", (PyCFunction)xmlparse_SetParamEntityParsing, - METH_VARARGS, xmlparse_SetParamEntityParsing__doc__}, + METH_VARARGS, xmlparse_SetParamEntityParsing__doc__}, {"GetInputContext", (PyCFunction)xmlparse_GetInputContext, - METH_NOARGS, xmlparse_GetInputContext__doc__}, + METH_NOARGS, xmlparse_GetInputContext__doc__}, #if XML_COMBINED_VERSION >= 19505 {"UseForeignDTD", (PyCFunction)xmlparse_UseForeignDTD, - METH_VARARGS, xmlparse_UseForeignDTD__doc__}, + METH_VARARGS, xmlparse_UseForeignDTD__doc__}, #endif {"__dir__", xmlparse_dir, METH_NOARGS}, - {NULL, NULL} /* sentinel */ + {NULL, NULL} /* sentinel */ }; /* ---------- */ @@ -1133,7 +1133,7 @@ { int i; for (i = 0; i < 256; i++) { - template_buffer[i] = i; + template_buffer[i] = i; } template_buffer[256] = 0; } @@ -1152,15 +1152,15 @@ PyUnicode_Decode(template_buffer, 256, name, "replace"); if (_u_string == NULL) - return result; + return result; for (i = 0; i < 256; i++) { - /* Stupid to access directly, but fast */ - Py_UNICODE c = _u_string->str[i]; - if (c == Py_UNICODE_REPLACEMENT_CHARACTER) - info->map[i] = -1; - else - info->map[i] = c; + /* Stupid to access directly, but fast */ + Py_UNICODE c = _u_string->str[i]; + if (c == Py_UNICODE_REPLACEMENT_CHARACTER) + info->map[i] = -1; + else + info->map[i] = c; } info->data = NULL; info->convert = NULL; @@ -1295,8 +1295,8 @@ int handlernum = -1; if (PyUnicode_Check(nameobj)) - name = _PyUnicode_AsString(nameobj); - + name = _PyUnicode_AsString(nameobj); + handlernum = handlername2int(name); if (handlernum != -1) { @@ -1362,18 +1362,18 @@ static PyObject * xmlparse_dir(PyObject *self, PyObject* noargs) { -#define APPEND(list, str) \ - do { \ - PyObject *o = PyUnicode_FromString(str); \ - if (o != NULL) \ - PyList_Append(list, o); \ - Py_XDECREF(o); \ +#define APPEND(list, str) \ + do { \ + PyObject *o = PyUnicode_FromString(str); \ + if (o != NULL) \ + PyList_Append(list, o); \ + Py_XDECREF(o); \ } while (0) int i; PyObject *rc = PyList_New(0); if (!rc) - return NULL; + return NULL; for (i = 0; handler_info[i].name != NULL; i++) { PyObject *o = get_handler_name(&handler_info[i]); if (o != NULL) @@ -1494,42 +1494,42 @@ if (strcmp(name, "buffer_size") == 0) { long new_buffer_size; if (!PyLong_Check(v)) { - PyErr_SetString(PyExc_TypeError, "buffer_size must be an integer"); - return -1; + PyErr_SetString(PyExc_TypeError, "buffer_size must be an integer"); + return -1; } new_buffer_size=PyLong_AS_LONG(v); /* trivial case -- no change */ if (new_buffer_size == self->buffer_size) { - return 0; + return 0; } if (new_buffer_size <= 0) { - PyErr_SetString(PyExc_ValueError, "buffer_size must be greater than zero"); - return -1; + PyErr_SetString(PyExc_ValueError, "buffer_size must be greater than zero"); + return -1; } /* check maximum */ if (new_buffer_size > INT_MAX) { - char errmsg[100]; - sprintf(errmsg, "buffer_size must not be greater than %i", INT_MAX); - PyErr_SetString(PyExc_ValueError, errmsg); - return -1; + char errmsg[100]; + sprintf(errmsg, "buffer_size must not be greater than %i", INT_MAX); + PyErr_SetString(PyExc_ValueError, errmsg); + return -1; } if (self->buffer != NULL) { - /* there is already a buffer */ - if (self->buffer_used != 0) { - flush_character_buffer(self); - } - /* free existing buffer */ - free(self->buffer); + /* there is already a buffer */ + if (self->buffer_used != 0) { + flush_character_buffer(self); + } + /* free existing buffer */ + free(self->buffer); } self->buffer = malloc(new_buffer_size); if (self->buffer == NULL) { - PyErr_NoMemory(); - return -1; - } + PyErr_NoMemory(); + return -1; + } self->buffer_size = new_buffer_size; return 0; } @@ -1570,39 +1570,39 @@ PyDoc_STRVAR(Xmlparsetype__doc__, "XML parser"); static PyTypeObject Xmlparsetype = { - PyVarObject_HEAD_INIT(NULL, 0) - "pyexpat.xmlparser", /*tp_name*/ - sizeof(xmlparseobject) + PyGC_HEAD_SIZE,/*tp_basicsize*/ - 0, /*tp_itemsize*/ - /* methods */ - (destructor)xmlparse_dealloc, /*tp_dealloc*/ - (printfunc)0, /*tp_print*/ - 0, /*tp_getattr*/ - (setattrfunc)xmlparse_setattr, /*tp_setattr*/ - 0, /*tp_reserved*/ - (reprfunc)0, /*tp_repr*/ - 0, /*tp_as_number*/ - 0, /*tp_as_sequence*/ - 0, /*tp_as_mapping*/ - (hashfunc)0, /*tp_hash*/ - (ternaryfunc)0, /*tp_call*/ - (reprfunc)0, /*tp_str*/ - (getattrofunc)xmlparse_getattro, /* tp_getattro */ - 0, /* tp_setattro */ - 0, /* tp_as_buffer */ + PyVarObject_HEAD_INIT(NULL, 0) + "pyexpat.xmlparser", /*tp_name*/ + sizeof(xmlparseobject) + PyGC_HEAD_SIZE,/*tp_basicsize*/ + 0, /*tp_itemsize*/ + /* methods */ + (destructor)xmlparse_dealloc, /*tp_dealloc*/ + (printfunc)0, /*tp_print*/ + 0, /*tp_getattr*/ + (setattrfunc)xmlparse_setattr, /*tp_setattr*/ + 0, /*tp_reserved*/ + (reprfunc)0, /*tp_repr*/ + 0, /*tp_as_number*/ + 0, /*tp_as_sequence*/ + 0, /*tp_as_mapping*/ + (hashfunc)0, /*tp_hash*/ + (ternaryfunc)0, /*tp_call*/ + (reprfunc)0, /*tp_str*/ + (getattrofunc)xmlparse_getattro, /* tp_getattro */ + 0, /* tp_setattro */ + 0, /* tp_as_buffer */ #ifdef Py_TPFLAGS_HAVE_GC - Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC, /*tp_flags*/ + Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC, /*tp_flags*/ #else - Py_TPFLAGS_DEFAULT | Py_TPFLAGS_GC, /*tp_flags*/ + Py_TPFLAGS_DEFAULT | Py_TPFLAGS_GC, /*tp_flags*/ #endif - Xmlparsetype__doc__, /* tp_doc - Documentation string */ - (traverseproc)xmlparse_traverse, /* tp_traverse */ - (inquiry)xmlparse_clear, /* tp_clear */ - 0, /* tp_richcompare */ - 0, /* tp_weaklistoffset */ - 0, /* tp_iter */ - 0, /* tp_iternext */ - xmlparse_methods, /* tp_methods */ + Xmlparsetype__doc__, /* tp_doc - Documentation string */ + (traverseproc)xmlparse_traverse, /* tp_traverse */ + (inquiry)xmlparse_clear, /* tp_clear */ + 0, /* tp_richcompare */ + 0, /* tp_weaklistoffset */ + 0, /* tp_iter */ + 0, /* tp_iternext */ + xmlparse_methods, /* tp_methods */ }; /* End of code for xmlparser objects */ @@ -1636,21 +1636,21 @@ /* Explicitly passing None means no interning is desired. Not passing anything means that a new dictionary is used. */ if (intern == Py_None) - intern = NULL; + intern = NULL; else if (intern == NULL) { - intern = PyDict_New(); - if (!intern) - return NULL; - intern_decref = 1; + intern = PyDict_New(); + if (!intern) + return NULL; + intern_decref = 1; } else if (!PyDict_Check(intern)) { - PyErr_SetString(PyExc_TypeError, "intern must be a dictionary"); - return NULL; + PyErr_SetString(PyExc_TypeError, "intern must be a dictionary"); + return NULL; } result = newxmlparseobject(encoding, namespace_separator, intern); if (intern_decref) { - Py_DECREF(intern); + Py_DECREF(intern); } return result; } @@ -1672,12 +1672,12 @@ /* List of methods defined in the module */ static struct PyMethodDef pyexpat_methods[] = { - {"ParserCreate", (PyCFunction)pyexpat_ParserCreate, + {"ParserCreate", (PyCFunction)pyexpat_ParserCreate, METH_VARARGS|METH_KEYWORDS, pyexpat_ParserCreate__doc__}, - {"ErrorString", (PyCFunction)pyexpat_ErrorString, - METH_VARARGS, pyexpat_ErrorString__doc__}, + {"ErrorString", (PyCFunction)pyexpat_ErrorString, + METH_VARARGS, pyexpat_ErrorString__doc__}, - {NULL, (PyCFunction)NULL, 0, NULL} /* sentinel */ + {NULL, (PyCFunction)NULL, 0, NULL} /* sentinel */ }; /* Module docstring */ @@ -1726,15 +1726,15 @@ PyMODINIT_FUNC MODULE_INITFUNC(void); /* avoid compiler warnings */ static struct PyModuleDef pyexpatmodule = { - PyModuleDef_HEAD_INIT, - MODULE_NAME, - pyexpat_module_documentation, - -1, - pyexpat_methods, - NULL, - NULL, - NULL, - NULL + PyModuleDef_HEAD_INIT, + MODULE_NAME, + pyexpat_module_documentation, + -1, + pyexpat_methods, + NULL, + NULL, + NULL, + NULL }; PyMODINIT_FUNC @@ -1756,12 +1756,12 @@ return NULL; if (PyType_Ready(&Xmlparsetype) < 0) - return NULL; + return NULL; /* Create the module and add the functions */ m = PyModule_Create(&pyexpatmodule); if (m == NULL) - return NULL; + return NULL; /* Add some symbolic constants to the module */ if (ErrorObject == NULL) { @@ -1818,7 +1818,7 @@ if (errors_module == NULL || model_module == NULL) /* Don't core dump later! */ return NULL; - + #if XML_COMBINED_VERSION > 19505 { const XML_Feature *features = XML_GetFeatureList(); @@ -1943,7 +1943,7 @@ capi.SetProcessingInstructionHandler = XML_SetProcessingInstructionHandler; capi.SetUnknownEncodingHandler = XML_SetUnknownEncodingHandler; capi.SetUserData = XML_SetUserData; - + /* export using capsule */ capi_object = PyCapsule_New(&capi, PyExpat_CAPSULE_NAME, NULL); if (capi_object) @@ -1959,12 +1959,12 @@ for (; handler_info[i].name != NULL; i++) { if (initial) - self->handlers[i] = NULL; - else { + self->handlers[i] = NULL; + else { temp = self->handlers[i]; self->handlers[i] = NULL; Py_XDECREF(temp); - handler_info[i].setter(self->itself, NULL); + handler_info[i].setter(self->itself, NULL); } } } Modified: python/branches/py3k-jit/Modules/python.c ============================================================================== --- python/branches/py3k-jit/Modules/python.c (original) +++ python/branches/py3k-jit/Modules/python.c Mon May 10 23:55:43 2010 @@ -11,48 +11,48 @@ int wmain(int argc, wchar_t **argv) { - return Py_Main(argc, argv); + return Py_Main(argc, argv); } #else int main(int argc, char **argv) { - wchar_t **argv_copy = (wchar_t **)PyMem_Malloc(sizeof(wchar_t*)*argc); - /* We need a second copies, as Python might modify the first one. */ - wchar_t **argv_copy2 = (wchar_t **)PyMem_Malloc(sizeof(wchar_t*)*argc); - int i, res; - char *oldloc; - /* 754 requires that FP exceptions run in "no stop" mode by default, - * and until C vendors implement C99's ways to control FP exceptions, - * Python requires non-stop mode. Alas, some platforms enable FP - * exceptions by default. Here we disable them. - */ + wchar_t **argv_copy = (wchar_t **)PyMem_Malloc(sizeof(wchar_t*)*argc); + /* We need a second copies, as Python might modify the first one. */ + wchar_t **argv_copy2 = (wchar_t **)PyMem_Malloc(sizeof(wchar_t*)*argc); + int i, res; + char *oldloc; + /* 754 requires that FP exceptions run in "no stop" mode by default, + * and until C vendors implement C99's ways to control FP exceptions, + * Python requires non-stop mode. Alas, some platforms enable FP + * exceptions by default. Here we disable them. + */ #ifdef __FreeBSD__ - fp_except_t m; + fp_except_t m; - m = fpgetmask(); - fpsetmask(m & ~FP_X_OFL); + m = fpgetmask(); + fpsetmask(m & ~FP_X_OFL); #endif - if (!argv_copy || !argv_copy2) { - fprintf(stderr, "out of memory\n"); - return 1; - } - oldloc = strdup(setlocale(LC_ALL, NULL)); - setlocale(LC_ALL, ""); - for (i = 0; i < argc; i++) { - argv_copy2[i] = argv_copy[i] = _Py_char2wchar(argv[i]); - if (!argv_copy[i]) - return 1; - } - setlocale(LC_ALL, oldloc); - free(oldloc); - res = Py_Main(argc, argv_copy); - for (i = 0; i < argc; i++) { - PyMem_Free(argv_copy2[i]); - } - PyMem_Free(argv_copy); - PyMem_Free(argv_copy2); - return res; + if (!argv_copy || !argv_copy2) { + fprintf(stderr, "out of memory\n"); + return 1; + } + oldloc = strdup(setlocale(LC_ALL, NULL)); + setlocale(LC_ALL, ""); + for (i = 0; i < argc; i++) { + argv_copy2[i] = argv_copy[i] = _Py_char2wchar(argv[i]); + if (!argv_copy[i]) + return 1; + } + setlocale(LC_ALL, oldloc); + free(oldloc); + res = Py_Main(argc, argv_copy); + for (i = 0; i < argc; i++) { + PyMem_Free(argv_copy2[i]); + } + PyMem_Free(argv_copy); + PyMem_Free(argv_copy2); + return res; } #endif Modified: python/branches/py3k-jit/Modules/readline.c ============================================================================== --- python/branches/py3k-jit/Modules/readline.c (original) +++ python/branches/py3k-jit/Modules/readline.c Mon May 10 23:55:43 2010 @@ -23,7 +23,7 @@ #ifdef SAVE_LOCALE # define RESTORE_LOCALE(sl) { setlocale(LC_CTYPE, sl); free(sl); } #else -# define RESTORE_LOCALE(sl) +# define RESTORE_LOCALE(sl) #endif /* GNU readline definitions */ @@ -33,7 +33,7 @@ #ifdef HAVE_RL_COMPLETION_MATCHES #define completion_matches(x, y) \ - rl_completion_matches((x), ((rl_compentry_func_t *)(y))) + rl_completion_matches((x), ((rl_compentry_func_t *)(y))) #else #if defined(_RL_FUNCTION_TYPEDEF) extern char **completion_matches(char *, rl_compentry_func_t *); @@ -48,13 +48,13 @@ #ifdef __APPLE__ /* * It is possible to link the readline module to the readline - * emulation library of editline/libedit. - * + * emulation library of editline/libedit. + * * On OSX this emulation library is not 100% API compatible * with the "real" readline and cannot be detected at compile-time, * hence we use a runtime check to detect if we're using libedit * - * Currently there is one know API incompatibility: + * Currently there is one know API incompatibility: * - 'get_history' has a 1-based index with GNU readline, and a 0-based * index with libedit's emulation. * - Note that replace_history and remove_history use a 0-based index @@ -66,7 +66,7 @@ static void on_completion_display_matches_hook(char **matches, - int num_matches, int max_length); + int num_matches, int max_length); /* Exported function to send one line to readline's init file parser */ @@ -74,18 +74,18 @@ static PyObject * parse_and_bind(PyObject *self, PyObject *args) { - char *s, *copy; - if (!PyArg_ParseTuple(args, "s:parse_and_bind", &s)) - return NULL; - /* Make a copy -- rl_parse_and_bind() modifies its argument */ - /* Bernard Herzog */ - copy = malloc(1 + strlen(s)); - if (copy == NULL) - return PyErr_NoMemory(); - strcpy(copy, s); - rl_parse_and_bind(copy); - free(copy); /* Free the copy */ - Py_RETURN_NONE; + char *s, *copy; + if (!PyArg_ParseTuple(args, "s:parse_and_bind", &s)) + return NULL; + /* Make a copy -- rl_parse_and_bind() modifies its argument */ + /* Bernard Herzog */ + copy = malloc(1 + strlen(s)); + if (copy == NULL) + return PyErr_NoMemory(); + strcpy(copy, s); + rl_parse_and_bind(copy); + free(copy); /* Free the copy */ + Py_RETURN_NONE; } PyDoc_STRVAR(doc_parse_and_bind, @@ -98,13 +98,13 @@ static PyObject * read_init_file(PyObject *self, PyObject *args) { - char *s = NULL; - if (!PyArg_ParseTuple(args, "|z:read_init_file", &s)) - return NULL; - errno = rl_read_init_file(s); - if (errno) - return PyErr_SetFromErrno(PyExc_IOError); - Py_RETURN_NONE; + char *s = NULL; + if (!PyArg_ParseTuple(args, "|z:read_init_file", &s)) + return NULL; + errno = rl_read_init_file(s); + if (errno) + return PyErr_SetFromErrno(PyExc_IOError); + Py_RETURN_NONE; } PyDoc_STRVAR(doc_read_init_file, @@ -118,13 +118,13 @@ static PyObject * read_history_file(PyObject *self, PyObject *args) { - char *s = NULL; - if (!PyArg_ParseTuple(args, "|z:read_history_file", &s)) - return NULL; - errno = read_history(s); - if (errno) - return PyErr_SetFromErrno(PyExc_IOError); - Py_RETURN_NONE; + char *s = NULL; + if (!PyArg_ParseTuple(args, "|z:read_history_file", &s)) + return NULL; + errno = read_history(s); + if (errno) + return PyErr_SetFromErrno(PyExc_IOError); + Py_RETURN_NONE; } static int _history_length = -1; /* do not truncate history by default */ @@ -139,15 +139,15 @@ static PyObject * write_history_file(PyObject *self, PyObject *args) { - char *s = NULL; - if (!PyArg_ParseTuple(args, "|z:write_history_file", &s)) - return NULL; - errno = write_history(s); - if (!errno && _history_length >= 0) - history_truncate_file(s, _history_length); - if (errno) - return PyErr_SetFromErrno(PyExc_IOError); - Py_RETURN_NONE; + char *s = NULL; + if (!PyArg_ParseTuple(args, "|z:write_history_file", &s)) + return NULL; + errno = write_history(s); + if (!errno && _history_length >= 0) + history_truncate_file(s, _history_length); + if (errno) + return PyErr_SetFromErrno(PyExc_IOError); + Py_RETURN_NONE; } PyDoc_STRVAR(doc_write_history_file, @@ -161,11 +161,11 @@ static PyObject* set_history_length(PyObject *self, PyObject *args) { - int length = _history_length; - if (!PyArg_ParseTuple(args, "i:set_history_length", &length)) - return NULL; - _history_length = length; - Py_RETURN_NONE; + int length = _history_length; + if (!PyArg_ParseTuple(args, "i:set_history_length", &length)) + return NULL; + _history_length = length; + Py_RETURN_NONE; } PyDoc_STRVAR(set_history_length_doc, @@ -180,7 +180,7 @@ static PyObject* get_history_length(PyObject *self, PyObject *noarg) { - return PyLong_FromLong(_history_length); + return PyLong_FromLong(_history_length); } PyDoc_STRVAR(get_history_length_doc, @@ -194,29 +194,29 @@ static PyObject * set_hook(const char *funcname, PyObject **hook_var, PyObject *args) { - PyObject *function = Py_None; - char buf[80]; - PyOS_snprintf(buf, sizeof(buf), "|O:set_%.50s", funcname); - if (!PyArg_ParseTuple(args, buf, &function)) - return NULL; - if (function == Py_None) { - Py_XDECREF(*hook_var); - *hook_var = NULL; - } - else if (PyCallable_Check(function)) { - PyObject *tmp = *hook_var; - Py_INCREF(function); - *hook_var = function; - Py_XDECREF(tmp); - } - else { - PyOS_snprintf(buf, sizeof(buf), - "set_%.50s(func): argument not callable", - funcname); - PyErr_SetString(PyExc_TypeError, buf); - return NULL; - } - Py_RETURN_NONE; + PyObject *function = Py_None; + char buf[80]; + PyOS_snprintf(buf, sizeof(buf), "|O:set_%.50s", funcname); + if (!PyArg_ParseTuple(args, buf, &function)) + return NULL; + if (function == Py_None) { + Py_XDECREF(*hook_var); + *hook_var = NULL; + } + else if (PyCallable_Check(function)) { + PyObject *tmp = *hook_var; + Py_INCREF(function); + *hook_var = function; + Py_XDECREF(tmp); + } + else { + PyOS_snprintf(buf, sizeof(buf), + "set_%.50s(func): argument not callable", + funcname); + PyErr_SetString(PyExc_TypeError, buf); + return NULL; + } + Py_RETURN_NONE; } @@ -232,20 +232,20 @@ static PyObject * set_completion_display_matches_hook(PyObject *self, PyObject *args) { - PyObject *result = set_hook("completion_display_matches_hook", - &completion_display_matches_hook, args); + PyObject *result = set_hook("completion_display_matches_hook", + &completion_display_matches_hook, args); #ifdef HAVE_RL_COMPLETION_DISPLAY_MATCHES_HOOK - /* We cannot set this hook globally, since it replaces the - default completion display. */ - rl_completion_display_matches_hook = - completion_display_matches_hook ? + /* We cannot set this hook globally, since it replaces the + default completion display. */ + rl_completion_display_matches_hook = + completion_display_matches_hook ? #if defined(_RL_FUNCTION_TYPEDEF) - (rl_compdisp_func_t *)on_completion_display_matches_hook : 0; + (rl_compdisp_func_t *)on_completion_display_matches_hook : 0; #else - (VFunction *)on_completion_display_matches_hook : 0; + (VFunction *)on_completion_display_matches_hook : 0; #endif #endif - return result; + return result; } @@ -259,7 +259,7 @@ static PyObject * set_startup_hook(PyObject *self, PyObject *args) { - return set_hook("startup_hook", &startup_hook, args); + return set_hook("startup_hook", &startup_hook, args); } PyDoc_STRVAR(doc_set_startup_hook, @@ -276,7 +276,7 @@ static PyObject * set_pre_input_hook(PyObject *self, PyObject *args) { - return set_hook("pre_input_hook", &pre_input_hook, args); + return set_hook("pre_input_hook", &pre_input_hook, args); } PyDoc_STRVAR(doc_set_pre_input_hook, @@ -314,8 +314,8 @@ static PyObject * get_begidx(PyObject *self, PyObject *noarg) { - Py_INCREF(begidx); - return begidx; + Py_INCREF(begidx); + return begidx; } PyDoc_STRVAR(doc_get_begidx, @@ -328,8 +328,8 @@ static PyObject * get_endidx(PyObject *self, PyObject *noarg) { - Py_INCREF(endidx); - return endidx; + Py_INCREF(endidx); + return endidx; } PyDoc_STRVAR(doc_get_endidx, @@ -342,14 +342,14 @@ static PyObject * set_completer_delims(PyObject *self, PyObject *args) { - char *break_chars; + char *break_chars; - if(!PyArg_ParseTuple(args, "s:set_completer_delims", &break_chars)) { - return NULL; - } - free((void*)rl_completer_word_break_characters); - rl_completer_word_break_characters = strdup(break_chars); - Py_RETURN_NONE; + if(!PyArg_ParseTuple(args, "s:set_completer_delims", &break_chars)) { + return NULL; + } + free((void*)rl_completer_word_break_characters); + rl_completer_word_break_characters = strdup(break_chars); + Py_RETURN_NONE; } PyDoc_STRVAR(doc_set_completer_delims, @@ -359,31 +359,31 @@ static PyObject * py_remove_history(PyObject *self, PyObject *args) { - int entry_number; - HIST_ENTRY *entry; + int entry_number; + HIST_ENTRY *entry; - if (!PyArg_ParseTuple(args, "i:remove_history", &entry_number)) - return NULL; - if (entry_number < 0) { - PyErr_SetString(PyExc_ValueError, - "History index cannot be negative"); - return NULL; - } - entry = remove_history(entry_number); - if (!entry) { - PyErr_Format(PyExc_ValueError, - "No history item at position %d", - entry_number); - return NULL; - } - /* free memory allocated for the history entry */ - if (entry->line) - free(entry->line); - if (entry->data) - free(entry->data); - free(entry); + if (!PyArg_ParseTuple(args, "i:remove_history", &entry_number)) + return NULL; + if (entry_number < 0) { + PyErr_SetString(PyExc_ValueError, + "History index cannot be negative"); + return NULL; + } + entry = remove_history(entry_number); + if (!entry) { + PyErr_Format(PyExc_ValueError, + "No history item at position %d", + entry_number); + return NULL; + } + /* free memory allocated for the history entry */ + if (entry->line) + free(entry->line); + if (entry->data) + free(entry->data); + free(entry); - Py_RETURN_NONE; + Py_RETURN_NONE; } PyDoc_STRVAR(doc_remove_history, @@ -393,34 +393,34 @@ static PyObject * py_replace_history(PyObject *self, PyObject *args) { - int entry_number; - char *line; - HIST_ENTRY *old_entry; - - if (!PyArg_ParseTuple(args, "is:replace_history", &entry_number, - &line)) { - return NULL; - } - if (entry_number < 0) { - PyErr_SetString(PyExc_ValueError, - "History index cannot be negative"); - return NULL; - } - old_entry = replace_history_entry(entry_number, line, (void *)NULL); - if (!old_entry) { - PyErr_Format(PyExc_ValueError, - "No history item at position %d", - entry_number); - return NULL; - } - /* free memory allocated for the old history entry */ - if (old_entry->line) - free(old_entry->line); - if (old_entry->data) - free(old_entry->data); - free(old_entry); + int entry_number; + char *line; + HIST_ENTRY *old_entry; + + if (!PyArg_ParseTuple(args, "is:replace_history", &entry_number, + &line)) { + return NULL; + } + if (entry_number < 0) { + PyErr_SetString(PyExc_ValueError, + "History index cannot be negative"); + return NULL; + } + old_entry = replace_history_entry(entry_number, line, (void *)NULL); + if (!old_entry) { + PyErr_Format(PyExc_ValueError, + "No history item at position %d", + entry_number); + return NULL; + } + /* free memory allocated for the old history entry */ + if (old_entry->line) + free(old_entry->line); + if (old_entry->data) + free(old_entry->data); + free(old_entry); - Py_RETURN_NONE; + Py_RETURN_NONE; } PyDoc_STRVAR(doc_replace_history, @@ -432,13 +432,13 @@ static PyObject * py_add_history(PyObject *self, PyObject *args) { - char *line; + char *line; - if(!PyArg_ParseTuple(args, "s:add_history", &line)) { - return NULL; - } - add_history(line); - Py_RETURN_NONE; + if(!PyArg_ParseTuple(args, "s:add_history", &line)) { + return NULL; + } + add_history(line); + Py_RETURN_NONE; } PyDoc_STRVAR(doc_add_history, @@ -451,7 +451,7 @@ static PyObject * get_completer_delims(PyObject *self, PyObject *noarg) { - return PyUnicode_FromString(rl_completer_word_break_characters); + return PyUnicode_FromString(rl_completer_word_break_characters); } PyDoc_STRVAR(doc_get_completer_delims, @@ -464,7 +464,7 @@ static PyObject * set_completer(PyObject *self, PyObject *args) { - return set_hook("completer", &completer, args); + return set_hook("completer", &completer, args); } PyDoc_STRVAR(doc_set_completer, @@ -478,11 +478,11 @@ static PyObject * get_completer(PyObject *self, PyObject *noargs) { - if (completer == NULL) { - Py_RETURN_NONE; - } - Py_INCREF(completer); - return completer; + if (completer == NULL) { + Py_RETURN_NONE; + } + Py_INCREF(completer); + return completer; } PyDoc_STRVAR(doc_get_completer, @@ -495,39 +495,39 @@ static PyObject * get_history_item(PyObject *self, PyObject *args) { - int idx = 0; - HIST_ENTRY *hist_ent; + int idx = 0; + HIST_ENTRY *hist_ent; - if (!PyArg_ParseTuple(args, "i:index", &idx)) - return NULL; + if (!PyArg_ParseTuple(args, "i:index", &idx)) + return NULL; #ifdef __APPLE__ - if (using_libedit_emulation) { - /* Libedit emulation uses 0-based indexes, - * the real one uses 1-based indexes, - * adjust the index to ensure that Python - * code doesn't have to worry about the - * difference. - */ - HISTORY_STATE *hist_st; - hist_st = history_get_history_state(); - - idx --; - - /* - * Apple's readline emulation crashes when - * the index is out of range, therefore - * test for that and fail gracefully. - */ - if (idx < 0 || idx >= hist_st->length) { - Py_RETURN_NONE; - } - } + if (using_libedit_emulation) { + /* Libedit emulation uses 0-based indexes, + * the real one uses 1-based indexes, + * adjust the index to ensure that Python + * code doesn't have to worry about the + * difference. + */ + HISTORY_STATE *hist_st; + hist_st = history_get_history_state(); + + idx --; + + /* + * Apple's readline emulation crashes when + * the index is out of range, therefore + * test for that and fail gracefully. + */ + if (idx < 0 || idx >= hist_st->length) { + Py_RETURN_NONE; + } + } #endif /* __APPLE__ */ - if ((hist_ent = history_get(idx))) - return PyUnicode_FromString(hist_ent->line); - else { - Py_RETURN_NONE; - } + if ((hist_ent = history_get(idx))) + return PyUnicode_FromString(hist_ent->line); + else { + Py_RETURN_NONE; + } } PyDoc_STRVAR(doc_get_history_item, @@ -540,10 +540,10 @@ static PyObject * get_current_history_length(PyObject *self, PyObject *noarg) { - HISTORY_STATE *hist_st; + HISTORY_STATE *hist_st; - hist_st = history_get_history_state(); - return PyLong_FromLong(hist_st ? (long) hist_st->length : (long) 0); + hist_st = history_get_history_state(); + return PyLong_FromLong(hist_st ? (long) hist_st->length : (long) 0); } PyDoc_STRVAR(doc_get_current_history_length, @@ -556,7 +556,7 @@ static PyObject * get_line_buffer(PyObject *self, PyObject *noarg) { - return PyUnicode_FromString(rl_line_buffer); + return PyUnicode_FromString(rl_line_buffer); } PyDoc_STRVAR(doc_get_line_buffer, @@ -571,8 +571,8 @@ static PyObject * py_clear_history(PyObject *self, PyObject *noarg) { - clear_history(); - Py_RETURN_NONE; + clear_history(); + Py_RETURN_NONE; } PyDoc_STRVAR(doc_clear_history, @@ -586,11 +586,11 @@ static PyObject * insert_text(PyObject *self, PyObject *args) { - char *s; - if (!PyArg_ParseTuple(args, "s:insert_text", &s)) - return NULL; - rl_insert_text(s); - Py_RETURN_NONE; + char *s; + if (!PyArg_ParseTuple(args, "s:insert_text", &s)) + return NULL; + rl_insert_text(s); + Py_RETURN_NONE; } PyDoc_STRVAR(doc_insert_text, @@ -603,8 +603,8 @@ static PyObject * redisplay(PyObject *self, PyObject *noarg) { - rl_redisplay(); - Py_RETURN_NONE; + rl_redisplay(); + Py_RETURN_NONE; } PyDoc_STRVAR(doc_redisplay, @@ -617,50 +617,50 @@ static struct PyMethodDef readline_methods[] = { - {"parse_and_bind", parse_and_bind, METH_VARARGS, doc_parse_and_bind}, - {"get_line_buffer", get_line_buffer, METH_NOARGS, doc_get_line_buffer}, - {"insert_text", insert_text, METH_VARARGS, doc_insert_text}, - {"redisplay", redisplay, METH_NOARGS, doc_redisplay}, - {"read_init_file", read_init_file, METH_VARARGS, doc_read_init_file}, - {"read_history_file", read_history_file, - METH_VARARGS, doc_read_history_file}, - {"write_history_file", write_history_file, - METH_VARARGS, doc_write_history_file}, - {"get_history_item", get_history_item, - METH_VARARGS, doc_get_history_item}, - {"get_current_history_length", (PyCFunction)get_current_history_length, - METH_NOARGS, doc_get_current_history_length}, - {"set_history_length", set_history_length, - METH_VARARGS, set_history_length_doc}, - {"get_history_length", get_history_length, - METH_NOARGS, get_history_length_doc}, - {"set_completer", set_completer, METH_VARARGS, doc_set_completer}, - {"get_completer", get_completer, METH_NOARGS, doc_get_completer}, - {"get_completion_type", get_completion_type, - METH_NOARGS, doc_get_completion_type}, - {"get_begidx", get_begidx, METH_NOARGS, doc_get_begidx}, - {"get_endidx", get_endidx, METH_NOARGS, doc_get_endidx}, - - {"set_completer_delims", set_completer_delims, - METH_VARARGS, doc_set_completer_delims}, - {"add_history", py_add_history, METH_VARARGS, doc_add_history}, - {"remove_history_item", py_remove_history, METH_VARARGS, doc_remove_history}, - {"replace_history_item", py_replace_history, METH_VARARGS, doc_replace_history}, - {"get_completer_delims", get_completer_delims, - METH_NOARGS, doc_get_completer_delims}, - - {"set_completion_display_matches_hook", set_completion_display_matches_hook, - METH_VARARGS, doc_set_completion_display_matches_hook}, - {"set_startup_hook", set_startup_hook, - METH_VARARGS, doc_set_startup_hook}, + {"parse_and_bind", parse_and_bind, METH_VARARGS, doc_parse_and_bind}, + {"get_line_buffer", get_line_buffer, METH_NOARGS, doc_get_line_buffer}, + {"insert_text", insert_text, METH_VARARGS, doc_insert_text}, + {"redisplay", redisplay, METH_NOARGS, doc_redisplay}, + {"read_init_file", read_init_file, METH_VARARGS, doc_read_init_file}, + {"read_history_file", read_history_file, + METH_VARARGS, doc_read_history_file}, + {"write_history_file", write_history_file, + METH_VARARGS, doc_write_history_file}, + {"get_history_item", get_history_item, + METH_VARARGS, doc_get_history_item}, + {"get_current_history_length", (PyCFunction)get_current_history_length, + METH_NOARGS, doc_get_current_history_length}, + {"set_history_length", set_history_length, + METH_VARARGS, set_history_length_doc}, + {"get_history_length", get_history_length, + METH_NOARGS, get_history_length_doc}, + {"set_completer", set_completer, METH_VARARGS, doc_set_completer}, + {"get_completer", get_completer, METH_NOARGS, doc_get_completer}, + {"get_completion_type", get_completion_type, + METH_NOARGS, doc_get_completion_type}, + {"get_begidx", get_begidx, METH_NOARGS, doc_get_begidx}, + {"get_endidx", get_endidx, METH_NOARGS, doc_get_endidx}, + + {"set_completer_delims", set_completer_delims, + METH_VARARGS, doc_set_completer_delims}, + {"add_history", py_add_history, METH_VARARGS, doc_add_history}, + {"remove_history_item", py_remove_history, METH_VARARGS, doc_remove_history}, + {"replace_history_item", py_replace_history, METH_VARARGS, doc_replace_history}, + {"get_completer_delims", get_completer_delims, + METH_NOARGS, doc_get_completer_delims}, + + {"set_completion_display_matches_hook", set_completion_display_matches_hook, + METH_VARARGS, doc_set_completion_display_matches_hook}, + {"set_startup_hook", set_startup_hook, + METH_VARARGS, doc_set_startup_hook}, #ifdef HAVE_RL_PRE_INPUT_HOOK - {"set_pre_input_hook", set_pre_input_hook, - METH_VARARGS, doc_set_pre_input_hook}, + {"set_pre_input_hook", set_pre_input_hook, + METH_VARARGS, doc_set_pre_input_hook}, #endif #ifdef HAVE_RL_COMPLETION_APPEND_CHARACTER - {"clear_history", py_clear_history, METH_NOARGS, doc_clear_history}, + {"clear_history", py_clear_history, METH_NOARGS, doc_clear_history}, #endif - {0, 0} + {0, 0} }; @@ -669,47 +669,47 @@ static int on_hook(PyObject *func) { - int result = 0; - if (func != NULL) { - PyObject *r; + int result = 0; + if (func != NULL) { + PyObject *r; #ifdef WITH_THREAD - PyGILState_STATE gilstate = PyGILState_Ensure(); + PyGILState_STATE gilstate = PyGILState_Ensure(); #endif - r = PyObject_CallFunction(func, NULL); - if (r == NULL) - goto error; - if (r == Py_None) - result = 0; - else { - result = PyLong_AsLong(r); - if (result == -1 && PyErr_Occurred()) - goto error; - } - Py_DECREF(r); - goto done; - error: - PyErr_Clear(); - Py_XDECREF(r); - done: + r = PyObject_CallFunction(func, NULL); + if (r == NULL) + goto error; + if (r == Py_None) + result = 0; + else { + result = PyLong_AsLong(r); + if (result == -1 && PyErr_Occurred()) + goto error; + } + Py_DECREF(r); + goto done; + error: + PyErr_Clear(); + Py_XDECREF(r); + done: #ifdef WITH_THREAD - PyGILState_Release(gilstate); + PyGILState_Release(gilstate); #endif - return result; - } - return result; + return result; + } + return result; } static int on_startup_hook(void) { - return on_hook(startup_hook); + return on_hook(startup_hook); } #ifdef HAVE_RL_PRE_INPUT_HOOK static int on_pre_input_hook(void) { - return on_hook(pre_input_hook); + return on_hook(pre_input_hook); } #endif @@ -718,42 +718,42 @@ static void on_completion_display_matches_hook(char **matches, - int num_matches, int max_length) + int num_matches, int max_length) { - int i; - PyObject *m=NULL, *s=NULL, *r=NULL; + int i; + PyObject *m=NULL, *s=NULL, *r=NULL; #ifdef WITH_THREAD - PyGILState_STATE gilstate = PyGILState_Ensure(); + PyGILState_STATE gilstate = PyGILState_Ensure(); #endif - m = PyList_New(num_matches); - if (m == NULL) - goto error; - for (i = 0; i < num_matches; i++) { - s = PyUnicode_FromString(matches[i+1]); - if (s == NULL) - goto error; - if (PyList_SetItem(m, i, s) == -1) - goto error; - } - r = PyObject_CallFunction(completion_display_matches_hook, - "sOi", matches[0], m, max_length); - - Py_DECREF(m); m=NULL; - - if (r == NULL || - (r != Py_None && PyLong_AsLong(r) == -1 && PyErr_Occurred())) { - goto error; - } - Py_XDECREF(r); r=NULL; - - if (0) { - error: - PyErr_Clear(); - Py_XDECREF(m); - Py_XDECREF(r); - } + m = PyList_New(num_matches); + if (m == NULL) + goto error; + for (i = 0; i < num_matches; i++) { + s = PyUnicode_FromString(matches[i+1]); + if (s == NULL) + goto error; + if (PyList_SetItem(m, i, s) == -1) + goto error; + } + r = PyObject_CallFunction(completion_display_matches_hook, + "sOi", matches[0], m, max_length); + + Py_DECREF(m); m=NULL; + + if (r == NULL || + (r != Py_None && PyLong_AsLong(r) == -1 && PyErr_Occurred())) { + goto error; + } + Py_XDECREF(r); r=NULL; + + if (0) { + error: + PyErr_Clear(); + Py_XDECREF(m); + Py_XDECREF(r); + } #ifdef WITH_THREAD - PyGILState_Release(gilstate); + PyGILState_Release(gilstate); #endif } @@ -763,37 +763,37 @@ static char * on_completion(const char *text, int state) { - char *result = NULL; - if (completer != NULL) { - PyObject *r; + char *result = NULL; + if (completer != NULL) { + PyObject *r; #ifdef WITH_THREAD - PyGILState_STATE gilstate = PyGILState_Ensure(); + PyGILState_STATE gilstate = PyGILState_Ensure(); #endif - rl_attempted_completion_over = 1; - r = PyObject_CallFunction(completer, "si", text, state); - if (r == NULL) - goto error; - if (r == Py_None) { - result = NULL; - } - else { - char *s = _PyUnicode_AsString(r); - if (s == NULL) - goto error; - result = strdup(s); - } - Py_DECREF(r); - goto done; - error: - PyErr_Clear(); - Py_XDECREF(r); - done: + rl_attempted_completion_over = 1; + r = PyObject_CallFunction(completer, "si", text, state); + if (r == NULL) + goto error; + if (r == Py_None) { + result = NULL; + } + else { + char *s = _PyUnicode_AsString(r); + if (s == NULL) + goto error; + result = strdup(s); + } + Py_DECREF(r); + goto done; + error: + PyErr_Clear(); + Py_XDECREF(r); + done: #ifdef WITH_THREAD - PyGILState_Release(gilstate); + PyGILState_Release(gilstate); #endif - return result; - } - return result; + return result; + } + return result; } @@ -804,16 +804,16 @@ flex_complete(char *text, int start, int end) { #ifdef HAVE_RL_COMPLETION_APPEND_CHARACTER - rl_completion_append_character ='\0'; + rl_completion_append_character ='\0'; #endif #ifdef HAVE_RL_COMPLETION_SUPPRESS_APPEND - rl_completion_suppress_append = 0; + rl_completion_suppress_append = 0; #endif - Py_XDECREF(begidx); - Py_XDECREF(endidx); - begidx = PyLong_FromLong((long) start); - endidx = PyLong_FromLong((long) end); - return completion_matches(text, *on_completion); + Py_XDECREF(begidx); + Py_XDECREF(endidx); + begidx = PyLong_FromLong((long) start); + endidx = PyLong_FromLong((long) end); + return completion_matches(text, *on_completion); } @@ -823,45 +823,45 @@ setup_readline(void) { #ifdef SAVE_LOCALE - char *saved_locale = strdup(setlocale(LC_CTYPE, NULL)); - if (!saved_locale) - Py_FatalError("not enough memory to save locale"); + char *saved_locale = strdup(setlocale(LC_CTYPE, NULL)); + if (!saved_locale) + Py_FatalError("not enough memory to save locale"); #endif - using_history(); + using_history(); - rl_readline_name = "python"; + rl_readline_name = "python"; #if defined(PYOS_OS2) && defined(PYCC_GCC) - /* Allow $if term= in .inputrc to work */ - rl_terminal_name = getenv("TERM"); + /* Allow $if term= in .inputrc to work */ + rl_terminal_name = getenv("TERM"); #endif - /* Force rebind of TAB to insert-tab */ - rl_bind_key('\t', rl_insert); - /* Bind both ESC-TAB and ESC-ESC to the completion function */ - rl_bind_key_in_map ('\t', rl_complete, emacs_meta_keymap); - rl_bind_key_in_map ('\033', rl_complete, emacs_meta_keymap); - /* Set our hook functions */ - rl_startup_hook = (Function *)on_startup_hook; + /* Force rebind of TAB to insert-tab */ + rl_bind_key('\t', rl_insert); + /* Bind both ESC-TAB and ESC-ESC to the completion function */ + rl_bind_key_in_map ('\t', rl_complete, emacs_meta_keymap); + rl_bind_key_in_map ('\033', rl_complete, emacs_meta_keymap); + /* Set our hook functions */ + rl_startup_hook = (Function *)on_startup_hook; #ifdef HAVE_RL_PRE_INPUT_HOOK - rl_pre_input_hook = (Function *)on_pre_input_hook; + rl_pre_input_hook = (Function *)on_pre_input_hook; #endif - /* Set our completion function */ - rl_attempted_completion_function = (CPPFunction *)flex_complete; - /* Set Python word break characters */ - rl_completer_word_break_characters = - strdup(" \t\n`~!@#$%^&*()-=+[{]}\\|;:'\",<>/?"); - /* All nonalphanums except '.' */ - - begidx = PyLong_FromLong(0L); - endidx = PyLong_FromLong(0L); - /* Initialize (allows .inputrc to override) - * - * XXX: A bug in the readline-2.2 library causes a memory leak - * inside this function. Nothing we can do about it. - */ - rl_initialize(); + /* Set our completion function */ + rl_attempted_completion_function = (CPPFunction *)flex_complete; + /* Set Python word break characters */ + rl_completer_word_break_characters = + strdup(" \t\n`~!@#$%^&*()-=+[{]}\\|;:'\",<>/?"); + /* All nonalphanums except '.' */ + + begidx = PyLong_FromLong(0L); + endidx = PyLong_FromLong(0L); + /* Initialize (allows .inputrc to override) + * + * XXX: A bug in the readline-2.2 library causes a memory leak + * inside this function. Nothing we can do about it. + */ + rl_initialize(); - RESTORE_LOCALE(saved_locale) + RESTORE_LOCALE(saved_locale) } /* Wrapper around GNU readline that handles signals differently. */ @@ -869,12 +869,12 @@ #if defined(HAVE_RL_CALLBACK) && defined(HAVE_SELECT) -static char *completed_input_string; +static char *completed_input_string; static void rlhandler(char *text) { - completed_input_string = text; - rl_callback_handler_remove(); + completed_input_string = text; + rl_callback_handler_remove(); } extern PyThreadState* _PyOS_ReadlineTState; @@ -882,60 +882,60 @@ static char * readline_until_enter_or_signal(char *prompt, int *signal) { - char * not_done_reading = ""; - fd_set selectset; + char * not_done_reading = ""; + fd_set selectset; - *signal = 0; + *signal = 0; #ifdef HAVE_RL_CATCH_SIGNAL - rl_catch_signals = 0; + rl_catch_signals = 0; #endif - rl_callback_handler_install (prompt, rlhandler); - FD_ZERO(&selectset); - - completed_input_string = not_done_reading; - - while (completed_input_string == not_done_reading) { - int has_input = 0; - - while (!has_input) - { struct timeval timeout = {0, 100000}; /* 0.1 seconds */ - - /* [Bug #1552726] Only limit the pause if an input hook has been - defined. */ - struct timeval *timeoutp = NULL; - if (PyOS_InputHook) - timeoutp = &timeout; - FD_SET(fileno(rl_instream), &selectset); - /* select resets selectset if no input was available */ - has_input = select(fileno(rl_instream) + 1, &selectset, - NULL, NULL, timeoutp); - if(PyOS_InputHook) PyOS_InputHook(); - } - - if(has_input > 0) { - rl_callback_read_char(); - } - else if (errno == EINTR) { - int s; + rl_callback_handler_install (prompt, rlhandler); + FD_ZERO(&selectset); + + completed_input_string = not_done_reading; + + while (completed_input_string == not_done_reading) { + int has_input = 0; + + while (!has_input) + { struct timeval timeout = {0, 100000}; /* 0.1 seconds */ + + /* [Bug #1552726] Only limit the pause if an input hook has been + defined. */ + struct timeval *timeoutp = NULL; + if (PyOS_InputHook) + timeoutp = &timeout; + FD_SET(fileno(rl_instream), &selectset); + /* select resets selectset if no input was available */ + has_input = select(fileno(rl_instream) + 1, &selectset, + NULL, NULL, timeoutp); + if(PyOS_InputHook) PyOS_InputHook(); + } + + if(has_input > 0) { + rl_callback_read_char(); + } + else if (errno == EINTR) { + int s; #ifdef WITH_THREAD - PyEval_RestoreThread(_PyOS_ReadlineTState); + PyEval_RestoreThread(_PyOS_ReadlineTState); #endif - s = PyErr_CheckSignals(); + s = PyErr_CheckSignals(); #ifdef WITH_THREAD - PyEval_SaveThread(); + PyEval_SaveThread(); #endif - if (s < 0) { - rl_free_line_state(); - rl_cleanup_after_signal(); - rl_callback_handler_remove(); - *signal = 1; - completed_input_string = NULL; - } - } - } + if (s < 0) { + rl_free_line_state(); + rl_cleanup_after_signal(); + rl_callback_handler_remove(); + *signal = 1; + completed_input_string = NULL; + } + } + } - return completed_input_string; + return completed_input_string; } @@ -949,31 +949,31 @@ static void onintr(int sig) { - longjmp(jbuf, 1); + longjmp(jbuf, 1); } static char * readline_until_enter_or_signal(char *prompt, int *signal) { - PyOS_sighandler_t old_inthandler; - char *p; - - *signal = 0; + PyOS_sighandler_t old_inthandler; + char *p; - old_inthandler = PyOS_setsig(SIGINT, onintr); - if (setjmp(jbuf)) { + *signal = 0; + + old_inthandler = PyOS_setsig(SIGINT, onintr); + if (setjmp(jbuf)) { #ifdef HAVE_SIGRELSE - /* This seems necessary on SunOS 4.1 (Rasmus Hahn) */ - sigrelse(SIGINT); + /* This seems necessary on SunOS 4.1 (Rasmus Hahn) */ + sigrelse(SIGINT); #endif - PyOS_setsig(SIGINT, old_inthandler); - *signal = 1; - return NULL; - } - rl_event_hook = PyOS_InputHook; - p = readline(prompt); - PyOS_setsig(SIGINT, old_inthandler); + PyOS_setsig(SIGINT, old_inthandler); + *signal = 1; + return NULL; + } + rl_event_hook = PyOS_InputHook; + p = readline(prompt); + PyOS_setsig(SIGINT, old_inthandler); return p; } @@ -983,82 +983,82 @@ static char * call_readline(FILE *sys_stdin, FILE *sys_stdout, char *prompt) { - size_t n; - char *p, *q; - int signal; + size_t n; + char *p, *q; + int signal; #ifdef SAVE_LOCALE - char *saved_locale = strdup(setlocale(LC_CTYPE, NULL)); - if (!saved_locale) - Py_FatalError("not enough memory to save locale"); - setlocale(LC_CTYPE, ""); + char *saved_locale = strdup(setlocale(LC_CTYPE, NULL)); + if (!saved_locale) + Py_FatalError("not enough memory to save locale"); + setlocale(LC_CTYPE, ""); #endif - if (sys_stdin != rl_instream || sys_stdout != rl_outstream) { - rl_instream = sys_stdin; - rl_outstream = sys_stdout; + if (sys_stdin != rl_instream || sys_stdout != rl_outstream) { + rl_instream = sys_stdin; + rl_outstream = sys_stdout; #ifdef HAVE_RL_COMPLETION_APPEND_CHARACTER - rl_prep_terminal (1); + rl_prep_terminal (1); #endif - } + } + + p = readline_until_enter_or_signal(prompt, &signal); - p = readline_until_enter_or_signal(prompt, &signal); - - /* we got an interrupt signal */ - if (signal) { - RESTORE_LOCALE(saved_locale) - return NULL; - } - - /* We got an EOF, return a empty string. */ - if (p == NULL) { - p = PyMem_Malloc(1); - if (p != NULL) - *p = '\0'; - RESTORE_LOCALE(saved_locale) - return p; - } - - /* we have a valid line */ - n = strlen(p); - if (n > 0) { - char *line; - HISTORY_STATE *state = history_get_history_state(); - if (state->length > 0) + /* we got an interrupt signal */ + if (signal) { + RESTORE_LOCALE(saved_locale) + return NULL; + } + + /* We got an EOF, return a empty string. */ + if (p == NULL) { + p = PyMem_Malloc(1); + if (p != NULL) + *p = '\0'; + RESTORE_LOCALE(saved_locale) + return p; + } + + /* we have a valid line */ + n = strlen(p); + if (n > 0) { + char *line; + HISTORY_STATE *state = history_get_history_state(); + if (state->length > 0) #ifdef __APPLE__ - if (using_libedit_emulation) { - /* - * Libedit's emulation uses 0-based indexes, - * the real readline uses 1-based indexes. - */ - line = history_get(state->length - 1)->line; - } else + if (using_libedit_emulation) { + /* + * Libedit's emulation uses 0-based indexes, + * the real readline uses 1-based indexes. + */ + line = history_get(state->length - 1)->line; + } else #endif /* __APPLE__ */ - line = history_get(state->length)->line; - else - line = ""; - if (strcmp(p, line)) - add_history(p); - /* the history docs don't say so, but the address of state - changes each time history_get_history_state is called - which makes me think it's freshly malloc'd memory... - on the other hand, the address of the last line stays the - same as long as history isn't extended, so it appears to - be malloc'd but managed by the history package... */ - free(state); - } - /* Copy the malloc'ed buffer into a PyMem_Malloc'ed one and - release the original. */ - q = p; - p = PyMem_Malloc(n+2); - if (p != NULL) { - strncpy(p, q, n); - p[n] = '\n'; - p[n+1] = '\0'; - } - free(q); - RESTORE_LOCALE(saved_locale) - return p; + line = history_get(state->length)->line; + else + line = ""; + if (strcmp(p, line)) + add_history(p); + /* the history docs don't say so, but the address of state + changes each time history_get_history_state is called + which makes me think it's freshly malloc'd memory... + on the other hand, the address of the last line stays the + same as long as history isn't extended, so it appears to + be malloc'd but managed by the history package... */ + free(state); + } + /* Copy the malloc'ed buffer into a PyMem_Malloc'ed one and + release the original. */ + q = p; + p = PyMem_Malloc(n+2); + if (p != NULL) { + strncpy(p, q, n); + p[n] = '\n'; + p[n+1] = '\0'; + } + free(q); + RESTORE_LOCALE(saved_locale) + return p; } @@ -1073,41 +1073,41 @@ #endif /* __APPLE__ */ static struct PyModuleDef readlinemodule = { - PyModuleDef_HEAD_INIT, - "readline", - doc_module, - -1, - readline_methods, - NULL, - NULL, - NULL, - NULL + PyModuleDef_HEAD_INIT, + "readline", + doc_module, + -1, + readline_methods, + NULL, + NULL, + NULL, + NULL }; PyMODINIT_FUNC PyInit_readline(void) { - PyObject *m; + PyObject *m; #ifdef __APPLE__ - if (strncmp(rl_library_version, libedit_version_tag, strlen(libedit_version_tag)) == 0) { - using_libedit_emulation = 1; - } + if (strncmp(rl_library_version, libedit_version_tag, strlen(libedit_version_tag)) == 0) { + using_libedit_emulation = 1; + } - if (using_libedit_emulation) - readlinemodule.m_doc = doc_module_le; + if (using_libedit_emulation) + readlinemodule.m_doc = doc_module_le; #endif /* __APPLE__ */ - m = PyModule_Create(&readlinemodule); + m = PyModule_Create(&readlinemodule); - if (m == NULL) - return NULL; + if (m == NULL) + return NULL; - PyOS_ReadlineFunctionPointer = call_readline; - setup_readline(); - return m; + PyOS_ReadlineFunctionPointer = call_readline; + setup_readline(); + return m; } Modified: python/branches/py3k-jit/Modules/resource.c ============================================================================== --- python/branches/py3k-jit/Modules/resource.c (original) +++ python/branches/py3k-jit/Modules/resource.c Mon May 10 23:55:43 2010 @@ -29,30 +29,30 @@ "or via the attributes ru_utime, ru_stime, ru_maxrss, and so on."); static PyStructSequence_Field struct_rusage_fields[] = { - {"ru_utime", "user time used"}, - {"ru_stime", "system time used"}, - {"ru_maxrss", "max. resident set size"}, - {"ru_ixrss", "shared memory size"}, - {"ru_idrss", "unshared data size"}, - {"ru_isrss", "unshared stack size"}, - {"ru_minflt", "page faults not requiring I/O"}, - {"ru_majflt", "page faults requiring I/O"}, - {"ru_nswap", "number of swap outs"}, - {"ru_inblock", "block input operations"}, - {"ru_oublock", "block output operations"}, - {"ru_msgsnd", "IPC messages sent"}, - {"ru_msgrcv", "IPC messages received"}, - {"ru_nsignals", "signals received"}, - {"ru_nvcsw", "voluntary context switches"}, - {"ru_nivcsw", "involuntary context switches"}, - {0} + {"ru_utime", "user time used"}, + {"ru_stime", "system time used"}, + {"ru_maxrss", "max. resident set size"}, + {"ru_ixrss", "shared memory size"}, + {"ru_idrss", "unshared data size"}, + {"ru_isrss", "unshared stack size"}, + {"ru_minflt", "page faults not requiring I/O"}, + {"ru_majflt", "page faults requiring I/O"}, + {"ru_nswap", "number of swap outs"}, + {"ru_inblock", "block input operations"}, + {"ru_oublock", "block output operations"}, + {"ru_msgsnd", "IPC messages sent"}, + {"ru_msgrcv", "IPC messages received"}, + {"ru_nsignals", "signals received"}, + {"ru_nvcsw", "voluntary context switches"}, + {"ru_nivcsw", "involuntary context switches"}, + {0} }; static PyStructSequence_Desc struct_rusage_desc = { - "resource.struct_rusage", /* name */ - struct_rusage__doc__, /* doc */ - struct_rusage_fields, /* fields */ - 16 /* n_in_sequence */ + "resource.struct_rusage", /* name */ + struct_rusage__doc__, /* doc */ + struct_rusage_fields, /* fields */ + 16 /* n_in_sequence */ }; static int initialized; @@ -61,151 +61,151 @@ static PyObject * resource_getrusage(PyObject *self, PyObject *args) { - int who; - struct rusage ru; - PyObject *result; - - if (!PyArg_ParseTuple(args, "i:getrusage", &who)) - return NULL; - - if (getrusage(who, &ru) == -1) { - if (errno == EINVAL) { - PyErr_SetString(PyExc_ValueError, - "invalid who parameter"); - return NULL; - } - PyErr_SetFromErrno(ResourceError); - return NULL; - } - - result = PyStructSequence_New(&StructRUsageType); - if (!result) - return NULL; - - PyStructSequence_SET_ITEM(result, 0, - PyFloat_FromDouble(doubletime(ru.ru_utime))); - PyStructSequence_SET_ITEM(result, 1, - PyFloat_FromDouble(doubletime(ru.ru_stime))); - PyStructSequence_SET_ITEM(result, 2, PyLong_FromLong(ru.ru_maxrss)); - PyStructSequence_SET_ITEM(result, 3, PyLong_FromLong(ru.ru_ixrss)); - PyStructSequence_SET_ITEM(result, 4, PyLong_FromLong(ru.ru_idrss)); - PyStructSequence_SET_ITEM(result, 5, PyLong_FromLong(ru.ru_isrss)); - PyStructSequence_SET_ITEM(result, 6, PyLong_FromLong(ru.ru_minflt)); - PyStructSequence_SET_ITEM(result, 7, PyLong_FromLong(ru.ru_majflt)); - PyStructSequence_SET_ITEM(result, 8, PyLong_FromLong(ru.ru_nswap)); - PyStructSequence_SET_ITEM(result, 9, PyLong_FromLong(ru.ru_inblock)); - PyStructSequence_SET_ITEM(result, 10, PyLong_FromLong(ru.ru_oublock)); - PyStructSequence_SET_ITEM(result, 11, PyLong_FromLong(ru.ru_msgsnd)); - PyStructSequence_SET_ITEM(result, 12, PyLong_FromLong(ru.ru_msgrcv)); - PyStructSequence_SET_ITEM(result, 13, PyLong_FromLong(ru.ru_nsignals)); - PyStructSequence_SET_ITEM(result, 14, PyLong_FromLong(ru.ru_nvcsw)); - PyStructSequence_SET_ITEM(result, 15, PyLong_FromLong(ru.ru_nivcsw)); - - if (PyErr_Occurred()) { - Py_DECREF(result); - return NULL; - } + int who; + struct rusage ru; + PyObject *result; + + if (!PyArg_ParseTuple(args, "i:getrusage", &who)) + return NULL; + + if (getrusage(who, &ru) == -1) { + if (errno == EINVAL) { + PyErr_SetString(PyExc_ValueError, + "invalid who parameter"); + return NULL; + } + PyErr_SetFromErrno(ResourceError); + return NULL; + } + + result = PyStructSequence_New(&StructRUsageType); + if (!result) + return NULL; + + PyStructSequence_SET_ITEM(result, 0, + PyFloat_FromDouble(doubletime(ru.ru_utime))); + PyStructSequence_SET_ITEM(result, 1, + PyFloat_FromDouble(doubletime(ru.ru_stime))); + PyStructSequence_SET_ITEM(result, 2, PyLong_FromLong(ru.ru_maxrss)); + PyStructSequence_SET_ITEM(result, 3, PyLong_FromLong(ru.ru_ixrss)); + PyStructSequence_SET_ITEM(result, 4, PyLong_FromLong(ru.ru_idrss)); + PyStructSequence_SET_ITEM(result, 5, PyLong_FromLong(ru.ru_isrss)); + PyStructSequence_SET_ITEM(result, 6, PyLong_FromLong(ru.ru_minflt)); + PyStructSequence_SET_ITEM(result, 7, PyLong_FromLong(ru.ru_majflt)); + PyStructSequence_SET_ITEM(result, 8, PyLong_FromLong(ru.ru_nswap)); + PyStructSequence_SET_ITEM(result, 9, PyLong_FromLong(ru.ru_inblock)); + PyStructSequence_SET_ITEM(result, 10, PyLong_FromLong(ru.ru_oublock)); + PyStructSequence_SET_ITEM(result, 11, PyLong_FromLong(ru.ru_msgsnd)); + PyStructSequence_SET_ITEM(result, 12, PyLong_FromLong(ru.ru_msgrcv)); + PyStructSequence_SET_ITEM(result, 13, PyLong_FromLong(ru.ru_nsignals)); + PyStructSequence_SET_ITEM(result, 14, PyLong_FromLong(ru.ru_nvcsw)); + PyStructSequence_SET_ITEM(result, 15, PyLong_FromLong(ru.ru_nivcsw)); + + if (PyErr_Occurred()) { + Py_DECREF(result); + return NULL; + } - return result; + return result; } static PyObject * resource_getrlimit(PyObject *self, PyObject *args) { - struct rlimit rl; - int resource; + struct rlimit rl; + int resource; - if (!PyArg_ParseTuple(args, "i:getrlimit", &resource)) - return NULL; + if (!PyArg_ParseTuple(args, "i:getrlimit", &resource)) + return NULL; - if (resource < 0 || resource >= RLIM_NLIMITS) { - PyErr_SetString(PyExc_ValueError, - "invalid resource specified"); - return NULL; - } - - if (getrlimit(resource, &rl) == -1) { - PyErr_SetFromErrno(ResourceError); - return NULL; - } + if (resource < 0 || resource >= RLIM_NLIMITS) { + PyErr_SetString(PyExc_ValueError, + "invalid resource specified"); + return NULL; + } + + if (getrlimit(resource, &rl) == -1) { + PyErr_SetFromErrno(ResourceError); + return NULL; + } #if defined(HAVE_LONG_LONG) - if (sizeof(rl.rlim_cur) > sizeof(long)) { - return Py_BuildValue("LL", - (PY_LONG_LONG) rl.rlim_cur, - (PY_LONG_LONG) rl.rlim_max); - } + if (sizeof(rl.rlim_cur) > sizeof(long)) { + return Py_BuildValue("LL", + (PY_LONG_LONG) rl.rlim_cur, + (PY_LONG_LONG) rl.rlim_max); + } #endif - return Py_BuildValue("ll", (long) rl.rlim_cur, (long) rl.rlim_max); + return Py_BuildValue("ll", (long) rl.rlim_cur, (long) rl.rlim_max); } static PyObject * resource_setrlimit(PyObject *self, PyObject *args) { - struct rlimit rl; - int resource; - PyObject *curobj, *maxobj; - - if (!PyArg_ParseTuple(args, "i(OO):setrlimit", - &resource, &curobj, &maxobj)) - return NULL; - - if (resource < 0 || resource >= RLIM_NLIMITS) { - PyErr_SetString(PyExc_ValueError, - "invalid resource specified"); - return NULL; - } + struct rlimit rl; + int resource; + PyObject *curobj, *maxobj; + + if (!PyArg_ParseTuple(args, "i(OO):setrlimit", + &resource, &curobj, &maxobj)) + return NULL; + + if (resource < 0 || resource >= RLIM_NLIMITS) { + PyErr_SetString(PyExc_ValueError, + "invalid resource specified"); + return NULL; + } #if !defined(HAVE_LARGEFILE_SUPPORT) - rl.rlim_cur = PyLong_AsLong(curobj); - if (rl.rlim_cur == (rlim_t)-1 && PyErr_Occurred()) - return NULL; - rl.rlim_max = PyLong_AsLong(maxobj); - if (rl.rlim_max == (rlim_t)-1 && PyErr_Occurred()) - return NULL; + rl.rlim_cur = PyLong_AsLong(curobj); + if (rl.rlim_cur == (rlim_t)-1 && PyErr_Occurred()) + return NULL; + rl.rlim_max = PyLong_AsLong(maxobj); + if (rl.rlim_max == (rlim_t)-1 && PyErr_Occurred()) + return NULL; #else - /* The limits are probably bigger than a long */ - rl.rlim_cur = PyLong_AsLongLong(curobj); - if (rl.rlim_cur == (rlim_t)-1 && PyErr_Occurred()) - return NULL; - rl.rlim_max = PyLong_AsLongLong(maxobj); - if (rl.rlim_max == (rlim_t)-1 && PyErr_Occurred()) - return NULL; -#endif - - rl.rlim_cur = rl.rlim_cur & RLIM_INFINITY; - rl.rlim_max = rl.rlim_max & RLIM_INFINITY; - if (setrlimit(resource, &rl) == -1) { - if (errno == EINVAL) - PyErr_SetString(PyExc_ValueError, - "current limit exceeds maximum limit"); - else if (errno == EPERM) - PyErr_SetString(PyExc_ValueError, - "not allowed to raise maximum limit"); - else - PyErr_SetFromErrno(ResourceError); - return NULL; - } - Py_INCREF(Py_None); - return Py_None; + /* The limits are probably bigger than a long */ + rl.rlim_cur = PyLong_AsLongLong(curobj); + if (rl.rlim_cur == (rlim_t)-1 && PyErr_Occurred()) + return NULL; + rl.rlim_max = PyLong_AsLongLong(maxobj); + if (rl.rlim_max == (rlim_t)-1 && PyErr_Occurred()) + return NULL; +#endif + + rl.rlim_cur = rl.rlim_cur & RLIM_INFINITY; + rl.rlim_max = rl.rlim_max & RLIM_INFINITY; + if (setrlimit(resource, &rl) == -1) { + if (errno == EINVAL) + PyErr_SetString(PyExc_ValueError, + "current limit exceeds maximum limit"); + else if (errno == EPERM) + PyErr_SetString(PyExc_ValueError, + "not allowed to raise maximum limit"); + else + PyErr_SetFromErrno(ResourceError); + return NULL; + } + Py_INCREF(Py_None); + return Py_None; } static PyObject * resource_getpagesize(PyObject *self, PyObject *unused) { - long pagesize = 0; + long pagesize = 0; #if defined(HAVE_GETPAGESIZE) - pagesize = getpagesize(); + pagesize = getpagesize(); #elif defined(HAVE_SYSCONF) #if defined(_SC_PAGE_SIZE) - pagesize = sysconf(_SC_PAGE_SIZE); + pagesize = sysconf(_SC_PAGE_SIZE); #else - /* Irix 5.3 has _SC_PAGESIZE, but not _SC_PAGE_SIZE */ - pagesize = sysconf(_SC_PAGESIZE); + /* Irix 5.3 has _SC_PAGESIZE, but not _SC_PAGE_SIZE */ + pagesize = sysconf(_SC_PAGESIZE); #endif #endif - return Py_BuildValue("i", pagesize); + return Py_BuildValue("i", pagesize); } @@ -213,11 +213,11 @@ static struct PyMethodDef resource_methods[] = { - {"getrusage", resource_getrusage, METH_VARARGS}, - {"getrlimit", resource_getrlimit, METH_VARARGS}, - {"setrlimit", resource_setrlimit, METH_VARARGS}, - {"getpagesize", resource_getpagesize, METH_NOARGS}, - {NULL, NULL} /* sentinel */ + {"getrusage", resource_getrusage, METH_VARARGS}, + {"getrlimit", resource_getrlimit, METH_VARARGS}, + {"setrlimit", resource_setrlimit, METH_VARARGS}, + {"getpagesize", resource_getpagesize, METH_NOARGS}, + {NULL, NULL} /* sentinel */ }; @@ -225,117 +225,117 @@ static struct PyModuleDef resourcemodule = { - PyModuleDef_HEAD_INIT, - "resource", - NULL, - -1, - resource_methods, - NULL, - NULL, - NULL, - NULL + PyModuleDef_HEAD_INIT, + "resource", + NULL, + -1, + resource_methods, + NULL, + NULL, + NULL, + NULL }; PyMODINIT_FUNC PyInit_resource(void) { - PyObject *m, *v; + PyObject *m, *v; - /* Create the module and add the functions */ - m = PyModule_Create(&resourcemodule); - if (m == NULL) - return NULL; - - /* Add some symbolic constants to the module */ - if (ResourceError == NULL) { - ResourceError = PyErr_NewException("resource.error", - NULL, NULL); - } - Py_INCREF(ResourceError); - PyModule_AddObject(m, "error", ResourceError); - if (!initialized) - PyStructSequence_InitType(&StructRUsageType, - &struct_rusage_desc); - Py_INCREF(&StructRUsageType); - PyModule_AddObject(m, "struct_rusage", - (PyObject*) &StructRUsageType); + /* Create the module and add the functions */ + m = PyModule_Create(&resourcemodule); + if (m == NULL) + return NULL; + + /* Add some symbolic constants to the module */ + if (ResourceError == NULL) { + ResourceError = PyErr_NewException("resource.error", + NULL, NULL); + } + Py_INCREF(ResourceError); + PyModule_AddObject(m, "error", ResourceError); + if (!initialized) + PyStructSequence_InitType(&StructRUsageType, + &struct_rusage_desc); + Py_INCREF(&StructRUsageType); + PyModule_AddObject(m, "struct_rusage", + (PyObject*) &StructRUsageType); - /* insert constants */ + /* insert constants */ #ifdef RLIMIT_CPU - PyModule_AddIntConstant(m, "RLIMIT_CPU", RLIMIT_CPU); + PyModule_AddIntConstant(m, "RLIMIT_CPU", RLIMIT_CPU); #endif #ifdef RLIMIT_FSIZE - PyModule_AddIntConstant(m, "RLIMIT_FSIZE", RLIMIT_FSIZE); + PyModule_AddIntConstant(m, "RLIMIT_FSIZE", RLIMIT_FSIZE); #endif #ifdef RLIMIT_DATA - PyModule_AddIntConstant(m, "RLIMIT_DATA", RLIMIT_DATA); + PyModule_AddIntConstant(m, "RLIMIT_DATA", RLIMIT_DATA); #endif #ifdef RLIMIT_STACK - PyModule_AddIntConstant(m, "RLIMIT_STACK", RLIMIT_STACK); + PyModule_AddIntConstant(m, "RLIMIT_STACK", RLIMIT_STACK); #endif #ifdef RLIMIT_CORE - PyModule_AddIntConstant(m, "RLIMIT_CORE", RLIMIT_CORE); + PyModule_AddIntConstant(m, "RLIMIT_CORE", RLIMIT_CORE); #endif #ifdef RLIMIT_NOFILE - PyModule_AddIntConstant(m, "RLIMIT_NOFILE", RLIMIT_NOFILE); + PyModule_AddIntConstant(m, "RLIMIT_NOFILE", RLIMIT_NOFILE); #endif #ifdef RLIMIT_OFILE - PyModule_AddIntConstant(m, "RLIMIT_OFILE", RLIMIT_OFILE); + PyModule_AddIntConstant(m, "RLIMIT_OFILE", RLIMIT_OFILE); #endif #ifdef RLIMIT_VMEM - PyModule_AddIntConstant(m, "RLIMIT_VMEM", RLIMIT_VMEM); + PyModule_AddIntConstant(m, "RLIMIT_VMEM", RLIMIT_VMEM); #endif #ifdef RLIMIT_AS - PyModule_AddIntConstant(m, "RLIMIT_AS", RLIMIT_AS); + PyModule_AddIntConstant(m, "RLIMIT_AS", RLIMIT_AS); #endif #ifdef RLIMIT_RSS - PyModule_AddIntConstant(m, "RLIMIT_RSS", RLIMIT_RSS); + PyModule_AddIntConstant(m, "RLIMIT_RSS", RLIMIT_RSS); #endif #ifdef RLIMIT_NPROC - PyModule_AddIntConstant(m, "RLIMIT_NPROC", RLIMIT_NPROC); + PyModule_AddIntConstant(m, "RLIMIT_NPROC", RLIMIT_NPROC); #endif #ifdef RLIMIT_MEMLOCK - PyModule_AddIntConstant(m, "RLIMIT_MEMLOCK", RLIMIT_MEMLOCK); + PyModule_AddIntConstant(m, "RLIMIT_MEMLOCK", RLIMIT_MEMLOCK); #endif #ifdef RLIMIT_SBSIZE - PyModule_AddIntConstant(m, "RLIMIT_SBSIZE", RLIMIT_SBSIZE); + PyModule_AddIntConstant(m, "RLIMIT_SBSIZE", RLIMIT_SBSIZE); #endif #ifdef RUSAGE_SELF - PyModule_AddIntConstant(m, "RUSAGE_SELF", RUSAGE_SELF); + PyModule_AddIntConstant(m, "RUSAGE_SELF", RUSAGE_SELF); #endif #ifdef RUSAGE_CHILDREN - PyModule_AddIntConstant(m, "RUSAGE_CHILDREN", RUSAGE_CHILDREN); + PyModule_AddIntConstant(m, "RUSAGE_CHILDREN", RUSAGE_CHILDREN); #endif #ifdef RUSAGE_BOTH - PyModule_AddIntConstant(m, "RUSAGE_BOTH", RUSAGE_BOTH); + PyModule_AddIntConstant(m, "RUSAGE_BOTH", RUSAGE_BOTH); #endif #if defined(HAVE_LONG_LONG) - if (sizeof(RLIM_INFINITY) > sizeof(long)) { - v = PyLong_FromLongLong((PY_LONG_LONG) RLIM_INFINITY); - } else -#endif - { - v = PyLong_FromLong((long) RLIM_INFINITY); - } - if (v) { - PyModule_AddObject(m, "RLIM_INFINITY", v); - } - initialized = 1; - return m; + if (sizeof(RLIM_INFINITY) > sizeof(long)) { + v = PyLong_FromLongLong((PY_LONG_LONG) RLIM_INFINITY); + } else +#endif + { + v = PyLong_FromLong((long) RLIM_INFINITY); + } + if (v) { + PyModule_AddObject(m, "RLIM_INFINITY", v); + } + initialized = 1; + return m; } Modified: python/branches/py3k-jit/Modules/rotatingtree.c ============================================================================== --- python/branches/py3k-jit/Modules/rotatingtree.c (original) +++ python/branches/py3k-jit/Modules/rotatingtree.c Mon May 10 23:55:43 2010 @@ -14,14 +14,14 @@ static int randombits(int bits) { - int result; - if (random_stream < (1U << bits)) { - random_value *= 1082527; - random_stream = random_value; - } - result = random_stream & ((1<>= bits; - return result; + int result; + if (random_stream < (1U << bits)) { + random_value *= 1082527; + random_stream = random_value; + } + result = random_stream & ((1<>= bits; + return result; } @@ -30,15 +30,15 @@ void RotatingTree_Add(rotating_node_t **root, rotating_node_t *node) { - while (*root != NULL) { - if (KEY_LOWER_THAN(node->key, (*root)->key)) - root = &((*root)->left); - else - root = &((*root)->right); - } - node->left = NULL; - node->right = NULL; - *root = node; + while (*root != NULL) { + if (KEY_LOWER_THAN(node->key, (*root)->key)) + root = &((*root)->left); + else + root = &((*root)->right); + } + node->left = NULL; + node->right = NULL; + *root = node; } /* Locate the node with the given key. This is the most complicated @@ -47,57 +47,57 @@ rotating_node_t * RotatingTree_Get(rotating_node_t **root, void *key) { - if (randombits(3) != 4) { - /* Fast path, no rebalancing */ - rotating_node_t *node = *root; - while (node != NULL) { - if (node->key == key) - return node; - if (KEY_LOWER_THAN(key, node->key)) - node = node->left; - else - node = node->right; - } - return NULL; - } - else { - rotating_node_t **pnode = root; - rotating_node_t *node = *pnode; - rotating_node_t *next; - int rotate; - if (node == NULL) - return NULL; - while (1) { - if (node->key == key) - return node; - rotate = !randombits(1); - if (KEY_LOWER_THAN(key, node->key)) { - next = node->left; - if (next == NULL) - return NULL; - if (rotate) { - node->left = next->right; - next->right = node; - *pnode = next; - } - else - pnode = &(node->left); - } - else { - next = node->right; - if (next == NULL) - return NULL; - if (rotate) { - node->right = next->left; - next->left = node; - *pnode = next; - } - else - pnode = &(node->right); - } - node = next; - } - } + if (randombits(3) != 4) { + /* Fast path, no rebalancing */ + rotating_node_t *node = *root; + while (node != NULL) { + if (node->key == key) + return node; + if (KEY_LOWER_THAN(key, node->key)) + node = node->left; + else + node = node->right; + } + return NULL; + } + else { + rotating_node_t **pnode = root; + rotating_node_t *node = *pnode; + rotating_node_t *next; + int rotate; + if (node == NULL) + return NULL; + while (1) { + if (node->key == key) + return node; + rotate = !randombits(1); + if (KEY_LOWER_THAN(key, node->key)) { + next = node->left; + if (next == NULL) + return NULL; + if (rotate) { + node->left = next->right; + next->right = node; + *pnode = next; + } + else + pnode = &(node->left); + } + else { + next = node->right; + if (next == NULL) + return NULL; + if (rotate) { + node->right = next->left; + next->left = node; + *pnode = next; + } + else + pnode = &(node->right); + } + node = next; + } + } } /* Enumerate all nodes in the tree. The callback enumfn() should return @@ -105,17 +105,17 @@ A non-zero value is directly returned by RotatingTree_Enum(). */ int RotatingTree_Enum(rotating_node_t *root, rotating_tree_enum_fn enumfn, - void *arg) + void *arg) { - int result; - rotating_node_t *node; - while (root != NULL) { - result = RotatingTree_Enum(root->left, enumfn, arg); - if (result != 0) return result; - node = root->right; - result = enumfn(root, arg); - if (result != 0) return result; - root = node; - } - return 0; + int result; + rotating_node_t *node; + while (root != NULL) { + result = RotatingTree_Enum(root->left, enumfn, arg); + if (result != 0) return result; + node = root->right; + result = enumfn(root, arg); + if (result != 0) return result; + root = node; + } + return 0; } Modified: python/branches/py3k-jit/Modules/selectmodule.c ============================================================================== --- python/branches/py3k-jit/Modules/selectmodule.c (original) +++ python/branches/py3k-jit/Modules/selectmodule.c Mon May 10 23:55:43 2010 @@ -22,7 +22,7 @@ */ #if defined(MS_WINDOWS) && !defined(FD_SETSIZE) #define FD_SETSIZE 512 -#endif +#endif #if defined(HAVE_POLL_H) #include @@ -58,20 +58,20 @@ /* list of Python objects and their file descriptor */ typedef struct { - PyObject *obj; /* owned reference */ - SOCKET fd; - int sentinel; /* -1 == sentinel */ + PyObject *obj; /* owned reference */ + SOCKET fd; + int sentinel; /* -1 == sentinel */ } pylist; static void reap_obj(pylist fd2obj[FD_SETSIZE + 1]) { - int i; - for (i = 0; i < FD_SETSIZE + 1 && fd2obj[i].sentinel >= 0; i++) { - Py_XDECREF(fd2obj[i].obj); - fd2obj[i].obj = NULL; - } - fd2obj[0].sentinel = -1; + int i; + for (i = 0; i < FD_SETSIZE + 1 && fd2obj[i].sentinel >= 0; i++) { + Py_XDECREF(fd2obj[i].obj); + fd2obj[i].obj = NULL; + } + fd2obj[0].sentinel = -1; } @@ -81,106 +81,106 @@ static int seq2set(PyObject *seq, fd_set *set, pylist fd2obj[FD_SETSIZE + 1]) { - int i; - int max = -1; - int index = 0; - int len = -1; - PyObject* fast_seq = NULL; - PyObject* o = NULL; - - fd2obj[0].obj = (PyObject*)0; /* set list to zero size */ - FD_ZERO(set); + int i; + int max = -1; + int index = 0; + int len = -1; + PyObject* fast_seq = NULL; + PyObject* o = NULL; + + fd2obj[0].obj = (PyObject*)0; /* set list to zero size */ + FD_ZERO(set); + + fast_seq=PySequence_Fast(seq, "arguments 1-3 must be sequences"); + if (!fast_seq) + return -1; - fast_seq=PySequence_Fast(seq, "arguments 1-3 must be sequences"); - if (!fast_seq) - return -1; + len = PySequence_Fast_GET_SIZE(fast_seq); - len = PySequence_Fast_GET_SIZE(fast_seq); + for (i = 0; i < len; i++) { + SOCKET v; - for (i = 0; i < len; i++) { - SOCKET v; + /* any intervening fileno() calls could decr this refcnt */ + if (!(o = PySequence_Fast_GET_ITEM(fast_seq, i))) + return -1; - /* any intervening fileno() calls could decr this refcnt */ - if (!(o = PySequence_Fast_GET_ITEM(fast_seq, i))) - return -1; - - Py_INCREF(o); - v = PyObject_AsFileDescriptor( o ); - if (v == -1) goto finally; + Py_INCREF(o); + v = PyObject_AsFileDescriptor( o ); + if (v == -1) goto finally; #if defined(_MSC_VER) - max = 0; /* not used for Win32 */ + max = 0; /* not used for Win32 */ #else /* !_MSC_VER */ - if (v < 0 || v >= FD_SETSIZE) { - PyErr_SetString(PyExc_ValueError, - "filedescriptor out of range in select()"); - goto finally; - } - if (v > max) - max = v; + if (v < 0 || v >= FD_SETSIZE) { + PyErr_SetString(PyExc_ValueError, + "filedescriptor out of range in select()"); + goto finally; + } + if (v > max) + max = v; #endif /* _MSC_VER */ - FD_SET(v, set); + FD_SET(v, set); - /* add object and its file descriptor to the list */ - if (index >= FD_SETSIZE) { - PyErr_SetString(PyExc_ValueError, - "too many file descriptors in select()"); - goto finally; - } - fd2obj[index].obj = o; - fd2obj[index].fd = v; - fd2obj[index].sentinel = 0; - fd2obj[++index].sentinel = -1; - } - Py_DECREF(fast_seq); - return max+1; + /* add object and its file descriptor to the list */ + if (index >= FD_SETSIZE) { + PyErr_SetString(PyExc_ValueError, + "too many file descriptors in select()"); + goto finally; + } + fd2obj[index].obj = o; + fd2obj[index].fd = v; + fd2obj[index].sentinel = 0; + fd2obj[++index].sentinel = -1; + } + Py_DECREF(fast_seq); + return max+1; finally: - Py_XDECREF(o); - Py_DECREF(fast_seq); - return -1; + Py_XDECREF(o); + Py_DECREF(fast_seq); + return -1; } /* returns NULL and sets the Python exception if an error occurred */ static PyObject * set2list(fd_set *set, pylist fd2obj[FD_SETSIZE + 1]) { - int i, j, count=0; - PyObject *list, *o; - SOCKET fd; - - for (j = 0; fd2obj[j].sentinel >= 0; j++) { - if (FD_ISSET(fd2obj[j].fd, set)) - count++; - } - list = PyList_New(count); - if (!list) - return NULL; - - i = 0; - for (j = 0; fd2obj[j].sentinel >= 0; j++) { - fd = fd2obj[j].fd; - if (FD_ISSET(fd, set)) { + int i, j, count=0; + PyObject *list, *o; + SOCKET fd; + + for (j = 0; fd2obj[j].sentinel >= 0; j++) { + if (FD_ISSET(fd2obj[j].fd, set)) + count++; + } + list = PyList_New(count); + if (!list) + return NULL; + + i = 0; + for (j = 0; fd2obj[j].sentinel >= 0; j++) { + fd = fd2obj[j].fd; + if (FD_ISSET(fd, set)) { #ifndef _MSC_VER - if (fd > FD_SETSIZE) { - PyErr_SetString(PyExc_SystemError, - "filedescriptor out of range returned in select()"); - goto finally; - } -#endif - o = fd2obj[j].obj; - fd2obj[j].obj = NULL; - /* transfer ownership */ - if (PyList_SetItem(list, i, o) < 0) - goto finally; - - i++; - } - } - return list; + if (fd > FD_SETSIZE) { + PyErr_SetString(PyExc_SystemError, + "filedescriptor out of range returned in select()"); + goto finally; + } +#endif + o = fd2obj[j].obj; + fd2obj[j].obj = NULL; + /* transfer ownership */ + if (PyList_SetItem(list, i, o) < 0) + goto finally; + + i++; + } + } + return list; finally: - Py_DECREF(list); - return NULL; + Py_DECREF(list); + return NULL; } #undef SELECT_USES_HEAP @@ -192,170 +192,170 @@ select_select(PyObject *self, PyObject *args) { #ifdef SELECT_USES_HEAP - pylist *rfd2obj, *wfd2obj, *efd2obj; + pylist *rfd2obj, *wfd2obj, *efd2obj; #else /* !SELECT_USES_HEAP */ - /* XXX: All this should probably be implemented as follows: - * - find the highest descriptor we're interested in - * - add one - * - that's the size - * See: Stevens, APitUE, $12.5.1 - */ - pylist rfd2obj[FD_SETSIZE + 1]; - pylist wfd2obj[FD_SETSIZE + 1]; - pylist efd2obj[FD_SETSIZE + 1]; + /* XXX: All this should probably be implemented as follows: + * - find the highest descriptor we're interested in + * - add one + * - that's the size + * See: Stevens, APitUE, $12.5.1 + */ + pylist rfd2obj[FD_SETSIZE + 1]; + pylist wfd2obj[FD_SETSIZE + 1]; + pylist efd2obj[FD_SETSIZE + 1]; #endif /* SELECT_USES_HEAP */ - PyObject *ifdlist, *ofdlist, *efdlist; - PyObject *ret = NULL; - PyObject *tout = Py_None; - fd_set ifdset, ofdset, efdset; - double timeout; - struct timeval tv, *tvp; - long seconds; - int imax, omax, emax, max; - int n; - - /* convert arguments */ - if (!PyArg_UnpackTuple(args, "select", 3, 4, - &ifdlist, &ofdlist, &efdlist, &tout)) - return NULL; - - if (tout == Py_None) - tvp = (struct timeval *)0; - else if (!PyNumber_Check(tout)) { - PyErr_SetString(PyExc_TypeError, - "timeout must be a float or None"); - return NULL; - } - else { - timeout = PyFloat_AsDouble(tout); - if (timeout == -1 && PyErr_Occurred()) - return NULL; - if (timeout > (double)LONG_MAX) { - PyErr_SetString(PyExc_OverflowError, - "timeout period too long"); - return NULL; - } - seconds = (long)timeout; - timeout = timeout - (double)seconds; - tv.tv_sec = seconds; - tv.tv_usec = (long)(timeout * 1E6); - tvp = &tv; - } + PyObject *ifdlist, *ofdlist, *efdlist; + PyObject *ret = NULL; + PyObject *tout = Py_None; + fd_set ifdset, ofdset, efdset; + double timeout; + struct timeval tv, *tvp; + long seconds; + int imax, omax, emax, max; + int n; + + /* convert arguments */ + if (!PyArg_UnpackTuple(args, "select", 3, 4, + &ifdlist, &ofdlist, &efdlist, &tout)) + return NULL; + + if (tout == Py_None) + tvp = (struct timeval *)0; + else if (!PyNumber_Check(tout)) { + PyErr_SetString(PyExc_TypeError, + "timeout must be a float or None"); + return NULL; + } + else { + timeout = PyFloat_AsDouble(tout); + if (timeout == -1 && PyErr_Occurred()) + return NULL; + if (timeout > (double)LONG_MAX) { + PyErr_SetString(PyExc_OverflowError, + "timeout period too long"); + return NULL; + } + seconds = (long)timeout; + timeout = timeout - (double)seconds; + tv.tv_sec = seconds; + tv.tv_usec = (long)(timeout * 1E6); + tvp = &tv; + } #ifdef SELECT_USES_HEAP - /* Allocate memory for the lists */ - rfd2obj = PyMem_NEW(pylist, FD_SETSIZE + 1); - wfd2obj = PyMem_NEW(pylist, FD_SETSIZE + 1); - efd2obj = PyMem_NEW(pylist, FD_SETSIZE + 1); - if (rfd2obj == NULL || wfd2obj == NULL || efd2obj == NULL) { - if (rfd2obj) PyMem_DEL(rfd2obj); - if (wfd2obj) PyMem_DEL(wfd2obj); - if (efd2obj) PyMem_DEL(efd2obj); - return PyErr_NoMemory(); - } + /* Allocate memory for the lists */ + rfd2obj = PyMem_NEW(pylist, FD_SETSIZE + 1); + wfd2obj = PyMem_NEW(pylist, FD_SETSIZE + 1); + efd2obj = PyMem_NEW(pylist, FD_SETSIZE + 1); + if (rfd2obj == NULL || wfd2obj == NULL || efd2obj == NULL) { + if (rfd2obj) PyMem_DEL(rfd2obj); + if (wfd2obj) PyMem_DEL(wfd2obj); + if (efd2obj) PyMem_DEL(efd2obj); + return PyErr_NoMemory(); + } #endif /* SELECT_USES_HEAP */ - /* Convert sequences to fd_sets, and get maximum fd number - * propagates the Python exception set in seq2set() - */ - rfd2obj[0].sentinel = -1; - wfd2obj[0].sentinel = -1; - efd2obj[0].sentinel = -1; - if ((imax=seq2set(ifdlist, &ifdset, rfd2obj)) < 0) - goto finally; - if ((omax=seq2set(ofdlist, &ofdset, wfd2obj)) < 0) - goto finally; - if ((emax=seq2set(efdlist, &efdset, efd2obj)) < 0) - goto finally; - max = imax; - if (omax > max) max = omax; - if (emax > max) max = emax; - - Py_BEGIN_ALLOW_THREADS - n = select(max, &ifdset, &ofdset, &efdset, tvp); - Py_END_ALLOW_THREADS + /* Convert sequences to fd_sets, and get maximum fd number + * propagates the Python exception set in seq2set() + */ + rfd2obj[0].sentinel = -1; + wfd2obj[0].sentinel = -1; + efd2obj[0].sentinel = -1; + if ((imax=seq2set(ifdlist, &ifdset, rfd2obj)) < 0) + goto finally; + if ((omax=seq2set(ofdlist, &ofdset, wfd2obj)) < 0) + goto finally; + if ((emax=seq2set(efdlist, &efdset, efd2obj)) < 0) + goto finally; + max = imax; + if (omax > max) max = omax; + if (emax > max) max = emax; + + Py_BEGIN_ALLOW_THREADS + n = select(max, &ifdset, &ofdset, &efdset, tvp); + Py_END_ALLOW_THREADS #ifdef MS_WINDOWS - if (n == SOCKET_ERROR) { - PyErr_SetExcFromWindowsErr(SelectError, WSAGetLastError()); - } + if (n == SOCKET_ERROR) { + PyErr_SetExcFromWindowsErr(SelectError, WSAGetLastError()); + } #else - if (n < 0) { - PyErr_SetFromErrno(SelectError); - } -#endif - else { - /* any of these three calls can raise an exception. it's more - convenient to test for this after all three calls... but - is that acceptable? - */ - ifdlist = set2list(&ifdset, rfd2obj); - ofdlist = set2list(&ofdset, wfd2obj); - efdlist = set2list(&efdset, efd2obj); - if (PyErr_Occurred()) - ret = NULL; - else - ret = PyTuple_Pack(3, ifdlist, ofdlist, efdlist); - - Py_DECREF(ifdlist); - Py_DECREF(ofdlist); - Py_DECREF(efdlist); - } - + if (n < 0) { + PyErr_SetFromErrno(SelectError); + } +#endif + else { + /* any of these three calls can raise an exception. it's more + convenient to test for this after all three calls... but + is that acceptable? + */ + ifdlist = set2list(&ifdset, rfd2obj); + ofdlist = set2list(&ofdset, wfd2obj); + efdlist = set2list(&efdset, efd2obj); + if (PyErr_Occurred()) + ret = NULL; + else + ret = PyTuple_Pack(3, ifdlist, ofdlist, efdlist); + + Py_DECREF(ifdlist); + Py_DECREF(ofdlist); + Py_DECREF(efdlist); + } + finally: - reap_obj(rfd2obj); - reap_obj(wfd2obj); - reap_obj(efd2obj); + reap_obj(rfd2obj); + reap_obj(wfd2obj); + reap_obj(efd2obj); #ifdef SELECT_USES_HEAP - PyMem_DEL(rfd2obj); - PyMem_DEL(wfd2obj); - PyMem_DEL(efd2obj); + PyMem_DEL(rfd2obj); + PyMem_DEL(wfd2obj); + PyMem_DEL(efd2obj); #endif /* SELECT_USES_HEAP */ - return ret; + return ret; } #if defined(HAVE_POLL) && !defined(HAVE_BROKEN_POLL) -/* +/* * poll() support */ typedef struct { - PyObject_HEAD - PyObject *dict; - int ufd_uptodate; - int ufd_len; - struct pollfd *ufds; + PyObject_HEAD + PyObject *dict; + int ufd_uptodate; + int ufd_len; + struct pollfd *ufds; } pollObject; static PyTypeObject poll_Type; -/* Update the malloc'ed array of pollfds to match the dictionary +/* Update the malloc'ed array of pollfds to match the dictionary contained within a pollObject. Return 1 on success, 0 on an error. */ static int update_ufd_array(pollObject *self) { - Py_ssize_t i, pos; - PyObject *key, *value; - struct pollfd *old_ufds = self->ufds; - - self->ufd_len = PyDict_Size(self->dict); - PyMem_RESIZE(self->ufds, struct pollfd, self->ufd_len); - if (self->ufds == NULL) { - self->ufds = old_ufds; - PyErr_NoMemory(); - return 0; - } - - i = pos = 0; - while (PyDict_Next(self->dict, &pos, &key, &value)) { - self->ufds[i].fd = PyLong_AsLong(key); - self->ufds[i].events = (short)PyLong_AsLong(value); - i++; - } - self->ufd_uptodate = 1; - return 1; + Py_ssize_t i, pos; + PyObject *key, *value; + struct pollfd *old_ufds = self->ufds; + + self->ufd_len = PyDict_Size(self->dict); + PyMem_RESIZE(self->ufds, struct pollfd, self->ufd_len); + if (self->ufds == NULL) { + self->ufds = old_ufds; + PyErr_NoMemory(); + return 0; + } + + i = pos = 0; + while (PyDict_Next(self->dict, &pos, &key, &value)) { + self->ufds[i].fd = PyLong_AsLong(key); + self->ufds[i].events = (short)PyLong_AsLong(value); + i++; + } + self->ufd_uptodate = 1; + return 1; } PyDoc_STRVAR(poll_register_doc, @@ -366,39 +366,39 @@ events -- an optional bitmask describing the type of events to check for"); static PyObject * -poll_register(pollObject *self, PyObject *args) +poll_register(pollObject *self, PyObject *args) { - PyObject *o, *key, *value; - int fd, events = POLLIN | POLLPRI | POLLOUT; - int err; - - if (!PyArg_ParseTuple(args, "O|i:register", &o, &events)) { - return NULL; - } - - fd = PyObject_AsFileDescriptor(o); - if (fd == -1) return NULL; - - /* Add entry to the internal dictionary: the key is the - file descriptor, and the value is the event mask. */ - key = PyLong_FromLong(fd); - if (key == NULL) - return NULL; - value = PyLong_FromLong(events); - if (value == NULL) { - Py_DECREF(key); - return NULL; - } - err = PyDict_SetItem(self->dict, key, value); - Py_DECREF(key); - Py_DECREF(value); - if (err < 0) - return NULL; + PyObject *o, *key, *value; + int fd, events = POLLIN | POLLPRI | POLLOUT; + int err; + + if (!PyArg_ParseTuple(args, "O|i:register", &o, &events)) { + return NULL; + } + + fd = PyObject_AsFileDescriptor(o); + if (fd == -1) return NULL; + + /* Add entry to the internal dictionary: the key is the + file descriptor, and the value is the event mask. */ + key = PyLong_FromLong(fd); + if (key == NULL) + return NULL; + value = PyLong_FromLong(events); + if (value == NULL) { + Py_DECREF(key); + return NULL; + } + err = PyDict_SetItem(self->dict, key, value); + Py_DECREF(key); + Py_DECREF(value); + if (err < 0) + return NULL; - self->ufd_uptodate = 0; + self->ufd_uptodate = 0; - Py_INCREF(Py_None); - return Py_None; + Py_INCREF(Py_None); + return Py_None; } PyDoc_STRVAR(poll_modify_doc, @@ -411,41 +411,41 @@ static PyObject * poll_modify(pollObject *self, PyObject *args) { - PyObject *o, *key, *value; - int fd, events; - int err; - - if (!PyArg_ParseTuple(args, "Oi:modify", &o, &events)) { - return NULL; - } - - fd = PyObject_AsFileDescriptor(o); - if (fd == -1) return NULL; - - /* Modify registered fd */ - key = PyLong_FromLong(fd); - if (key == NULL) - return NULL; - if (PyDict_GetItem(self->dict, key) == NULL) { - errno = ENOENT; - PyErr_SetFromErrno(PyExc_IOError); - return NULL; - } - value = PyLong_FromLong(events); - if (value == NULL) { - Py_DECREF(key); - return NULL; - } - err = PyDict_SetItem(self->dict, key, value); - Py_DECREF(key); - Py_DECREF(value); - if (err < 0) - return NULL; + PyObject *o, *key, *value; + int fd, events; + int err; + + if (!PyArg_ParseTuple(args, "Oi:modify", &o, &events)) { + return NULL; + } + + fd = PyObject_AsFileDescriptor(o); + if (fd == -1) return NULL; + + /* Modify registered fd */ + key = PyLong_FromLong(fd); + if (key == NULL) + return NULL; + if (PyDict_GetItem(self->dict, key) == NULL) { + errno = ENOENT; + PyErr_SetFromErrno(PyExc_IOError); + return NULL; + } + value = PyLong_FromLong(events); + if (value == NULL) { + Py_DECREF(key); + return NULL; + } + err = PyDict_SetItem(self->dict, key, value); + Py_DECREF(key); + Py_DECREF(value); + if (err < 0) + return NULL; - self->ufd_uptodate = 0; + self->ufd_uptodate = 0; - Py_INCREF(Py_None); - return Py_None; + Py_INCREF(Py_None); + return Py_None; } @@ -454,32 +454,32 @@ Remove a file descriptor being tracked by the polling object."); static PyObject * -poll_unregister(pollObject *self, PyObject *o) +poll_unregister(pollObject *self, PyObject *o) { - PyObject *key; - int fd; + PyObject *key; + int fd; - fd = PyObject_AsFileDescriptor( o ); - if (fd == -1) - return NULL; - - /* Check whether the fd is already in the array */ - key = PyLong_FromLong(fd); - if (key == NULL) - return NULL; - - if (PyDict_DelItem(self->dict, key) == -1) { - Py_DECREF(key); - /* This will simply raise the KeyError set by PyDict_DelItem - if the file descriptor isn't registered. */ - return NULL; - } + fd = PyObject_AsFileDescriptor( o ); + if (fd == -1) + return NULL; + + /* Check whether the fd is already in the array */ + key = PyLong_FromLong(fd); + if (key == NULL) + return NULL; + + if (PyDict_DelItem(self->dict, key) == -1) { + Py_DECREF(key); + /* This will simply raise the KeyError set by PyDict_DelItem + if the file descriptor isn't registered. */ + return NULL; + } - Py_DECREF(key); - self->ufd_uptodate = 0; + Py_DECREF(key); + self->ufd_uptodate = 0; - Py_INCREF(Py_None); - return Py_None; + Py_INCREF(Py_None); + return Py_None; } PyDoc_STRVAR(poll_poll_doc, @@ -488,169 +488,169 @@ any descriptors that have events or errors to report."); static PyObject * -poll_poll(pollObject *self, PyObject *args) +poll_poll(pollObject *self, PyObject *args) { - PyObject *result_list = NULL, *tout = NULL; - int timeout = 0, poll_result, i, j; - PyObject *value = NULL, *num = NULL; - - if (!PyArg_UnpackTuple(args, "poll", 0, 1, &tout)) { - return NULL; - } - - /* Check values for timeout */ - if (tout == NULL || tout == Py_None) - timeout = -1; - else if (!PyNumber_Check(tout)) { - PyErr_SetString(PyExc_TypeError, - "timeout must be an integer or None"); - return NULL; - } - else { - tout = PyNumber_Long(tout); - if (!tout) - return NULL; - timeout = PyLong_AsLong(tout); - Py_DECREF(tout); - if (timeout == -1 && PyErr_Occurred()) - return NULL; - } - - /* Ensure the ufd array is up to date */ - if (!self->ufd_uptodate) - if (update_ufd_array(self) == 0) - return NULL; - - /* call poll() */ - Py_BEGIN_ALLOW_THREADS - poll_result = poll(self->ufds, self->ufd_len, timeout); - Py_END_ALLOW_THREADS - - if (poll_result < 0) { - PyErr_SetFromErrno(SelectError); - return NULL; - } - - /* build the result list */ - - result_list = PyList_New(poll_result); - if (!result_list) - return NULL; - else { - for (i = 0, j = 0; j < poll_result; j++) { - /* skip to the next fired descriptor */ - while (!self->ufds[i].revents) { - i++; - } - /* if we hit a NULL return, set value to NULL - and break out of loop; code at end will - clean up result_list */ - value = PyTuple_New(2); - if (value == NULL) - goto error; - num = PyLong_FromLong(self->ufds[i].fd); - if (num == NULL) { - Py_DECREF(value); - goto error; - } - PyTuple_SET_ITEM(value, 0, num); - - /* The &0xffff is a workaround for AIX. 'revents' - is a 16-bit short, and IBM assigned POLLNVAL - to be 0x8000, so the conversion to int results - in a negative number. See SF bug #923315. */ - num = PyLong_FromLong(self->ufds[i].revents & 0xffff); - if (num == NULL) { - Py_DECREF(value); - goto error; - } - PyTuple_SET_ITEM(value, 1, num); - if ((PyList_SetItem(result_list, j, value)) == -1) { - Py_DECREF(value); - goto error; - } - i++; - } - } - return result_list; + PyObject *result_list = NULL, *tout = NULL; + int timeout = 0, poll_result, i, j; + PyObject *value = NULL, *num = NULL; + + if (!PyArg_UnpackTuple(args, "poll", 0, 1, &tout)) { + return NULL; + } + + /* Check values for timeout */ + if (tout == NULL || tout == Py_None) + timeout = -1; + else if (!PyNumber_Check(tout)) { + PyErr_SetString(PyExc_TypeError, + "timeout must be an integer or None"); + return NULL; + } + else { + tout = PyNumber_Long(tout); + if (!tout) + return NULL; + timeout = PyLong_AsLong(tout); + Py_DECREF(tout); + if (timeout == -1 && PyErr_Occurred()) + return NULL; + } + + /* Ensure the ufd array is up to date */ + if (!self->ufd_uptodate) + if (update_ufd_array(self) == 0) + return NULL; + + /* call poll() */ + Py_BEGIN_ALLOW_THREADS + poll_result = poll(self->ufds, self->ufd_len, timeout); + Py_END_ALLOW_THREADS + + if (poll_result < 0) { + PyErr_SetFromErrno(SelectError); + return NULL; + } + + /* build the result list */ + + result_list = PyList_New(poll_result); + if (!result_list) + return NULL; + else { + for (i = 0, j = 0; j < poll_result; j++) { + /* skip to the next fired descriptor */ + while (!self->ufds[i].revents) { + i++; + } + /* if we hit a NULL return, set value to NULL + and break out of loop; code at end will + clean up result_list */ + value = PyTuple_New(2); + if (value == NULL) + goto error; + num = PyLong_FromLong(self->ufds[i].fd); + if (num == NULL) { + Py_DECREF(value); + goto error; + } + PyTuple_SET_ITEM(value, 0, num); + + /* The &0xffff is a workaround for AIX. 'revents' + is a 16-bit short, and IBM assigned POLLNVAL + to be 0x8000, so the conversion to int results + in a negative number. See SF bug #923315. */ + num = PyLong_FromLong(self->ufds[i].revents & 0xffff); + if (num == NULL) { + Py_DECREF(value); + goto error; + } + PyTuple_SET_ITEM(value, 1, num); + if ((PyList_SetItem(result_list, j, value)) == -1) { + Py_DECREF(value); + goto error; + } + i++; + } + } + return result_list; error: - Py_DECREF(result_list); - return NULL; + Py_DECREF(result_list); + return NULL; } static PyMethodDef poll_methods[] = { - {"register", (PyCFunction)poll_register, - METH_VARARGS, poll_register_doc}, - {"modify", (PyCFunction)poll_modify, - METH_VARARGS, poll_modify_doc}, - {"unregister", (PyCFunction)poll_unregister, - METH_O, poll_unregister_doc}, - {"poll", (PyCFunction)poll_poll, - METH_VARARGS, poll_poll_doc}, - {NULL, NULL} /* sentinel */ + {"register", (PyCFunction)poll_register, + METH_VARARGS, poll_register_doc}, + {"modify", (PyCFunction)poll_modify, + METH_VARARGS, poll_modify_doc}, + {"unregister", (PyCFunction)poll_unregister, + METH_O, poll_unregister_doc}, + {"poll", (PyCFunction)poll_poll, + METH_VARARGS, poll_poll_doc}, + {NULL, NULL} /* sentinel */ }; static pollObject * newPollObject(void) { - pollObject *self; - self = PyObject_New(pollObject, &poll_Type); - if (self == NULL) - return NULL; - /* ufd_uptodate is a Boolean, denoting whether the - array pointed to by ufds matches the contents of the dictionary. */ - self->ufd_uptodate = 0; - self->ufds = NULL; - self->dict = PyDict_New(); - if (self->dict == NULL) { - Py_DECREF(self); - return NULL; - } - return self; + pollObject *self; + self = PyObject_New(pollObject, &poll_Type); + if (self == NULL) + return NULL; + /* ufd_uptodate is a Boolean, denoting whether the + array pointed to by ufds matches the contents of the dictionary. */ + self->ufd_uptodate = 0; + self->ufds = NULL; + self->dict = PyDict_New(); + if (self->dict == NULL) { + Py_DECREF(self); + return NULL; + } + return self; } static void poll_dealloc(pollObject *self) { - if (self->ufds != NULL) - PyMem_DEL(self->ufds); - Py_XDECREF(self->dict); - PyObject_Del(self); + if (self->ufds != NULL) + PyMem_DEL(self->ufds); + Py_XDECREF(self->dict); + PyObject_Del(self); } static PyTypeObject poll_Type = { - /* The ob_type field must be initialized in the module init function - * to be portable to Windows without using C++. */ - PyVarObject_HEAD_INIT(NULL, 0) - "select.poll", /*tp_name*/ - sizeof(pollObject), /*tp_basicsize*/ - 0, /*tp_itemsize*/ - /* methods */ - (destructor)poll_dealloc, /*tp_dealloc*/ - 0, /*tp_print*/ - 0, /*tp_getattr*/ - 0, /*tp_setattr*/ - 0, /*tp_reserved*/ - 0, /*tp_repr*/ - 0, /*tp_as_number*/ - 0, /*tp_as_sequence*/ - 0, /*tp_as_mapping*/ - 0, /*tp_hash*/ - 0, /*tp_call*/ - 0, /*tp_str*/ - 0, /*tp_getattro*/ - 0, /*tp_setattro*/ - 0, /*tp_as_buffer*/ - Py_TPFLAGS_DEFAULT, /*tp_flags*/ - 0, /*tp_doc*/ - 0, /*tp_traverse*/ - 0, /*tp_clear*/ - 0, /*tp_richcompare*/ - 0, /*tp_weaklistoffset*/ - 0, /*tp_iter*/ - 0, /*tp_iternext*/ - poll_methods, /*tp_methods*/ + /* The ob_type field must be initialized in the module init function + * to be portable to Windows without using C++. */ + PyVarObject_HEAD_INIT(NULL, 0) + "select.poll", /*tp_name*/ + sizeof(pollObject), /*tp_basicsize*/ + 0, /*tp_itemsize*/ + /* methods */ + (destructor)poll_dealloc, /*tp_dealloc*/ + 0, /*tp_print*/ + 0, /*tp_getattr*/ + 0, /*tp_setattr*/ + 0, /*tp_reserved*/ + 0, /*tp_repr*/ + 0, /*tp_as_number*/ + 0, /*tp_as_sequence*/ + 0, /*tp_as_mapping*/ + 0, /*tp_hash*/ + 0, /*tp_call*/ + 0, /*tp_str*/ + 0, /*tp_getattro*/ + 0, /*tp_setattro*/ + 0, /*tp_as_buffer*/ + Py_TPFLAGS_DEFAULT, /*tp_flags*/ + 0, /*tp_doc*/ + 0, /*tp_traverse*/ + 0, /*tp_clear*/ + 0, /*tp_richcompare*/ + 0, /*tp_weaklistoffset*/ + 0, /*tp_iter*/ + 0, /*tp_iternext*/ + poll_methods, /*tp_methods*/ }; PyDoc_STRVAR(poll_doc, @@ -660,36 +660,36 @@ static PyObject * select_poll(PyObject *self, PyObject *unused) { - return (PyObject *)newPollObject(); + return (PyObject *)newPollObject(); } #ifdef __APPLE__ -/* +/* * On some systems poll() sets errno on invalid file descriptors. We test * for this at runtime because this bug may be fixed or introduced between * OS releases. */ static int select_have_broken_poll(void) { - int poll_test; - int filedes[2]; + int poll_test; + int filedes[2]; - struct pollfd poll_struct = { 0, POLLIN|POLLPRI|POLLOUT, 0 }; + struct pollfd poll_struct = { 0, POLLIN|POLLPRI|POLLOUT, 0 }; - /* Create a file descriptor to make invalid */ - if (pipe(filedes) < 0) { - return 1; - } - poll_struct.fd = filedes[0]; - close(filedes[0]); - close(filedes[1]); - poll_test = poll(&poll_struct, 1, 0); - if (poll_test < 0) { - return 1; - } else if (poll_test == 0 && poll_struct.revents != POLLNVAL) { - return 1; - } - return 0; + /* Create a file descriptor to make invalid */ + if (pipe(filedes) < 0) { + return 1; + } + poll_struct.fd = filedes[0]; + close(filedes[0]); + close(filedes[1]); + poll_test = poll(&poll_struct, 1, 0); + if (poll_test < 0) { + return 1; + } else if (poll_test == 0 && poll_struct.revents != POLLNVAL) { + return 1; + } + return 0; } #endif /* __APPLE__ */ @@ -708,8 +708,8 @@ #endif typedef struct { - PyObject_HEAD - SOCKET epfd; /* epoll control file descriptor */ + PyObject_HEAD + SOCKET epfd; /* epoll control file descriptor */ } pyEpoll_Object; static PyTypeObject pyEpoll_Type; @@ -718,92 +718,92 @@ static PyObject * pyepoll_err_closed(void) { - PyErr_SetString(PyExc_ValueError, "I/O operation on closed epoll fd"); - return NULL; + PyErr_SetString(PyExc_ValueError, "I/O operation on closed epoll fd"); + return NULL; } static int pyepoll_internal_close(pyEpoll_Object *self) { - int save_errno = 0; - if (self->epfd >= 0) { - int epfd = self->epfd; - self->epfd = -1; - Py_BEGIN_ALLOW_THREADS - if (close(epfd) < 0) - save_errno = errno; - Py_END_ALLOW_THREADS - } - return save_errno; + int save_errno = 0; + if (self->epfd >= 0) { + int epfd = self->epfd; + self->epfd = -1; + Py_BEGIN_ALLOW_THREADS + if (close(epfd) < 0) + save_errno = errno; + Py_END_ALLOW_THREADS + } + return save_errno; } static PyObject * newPyEpoll_Object(PyTypeObject *type, int sizehint, SOCKET fd) { - pyEpoll_Object *self; - - if (sizehint == -1) { - sizehint = FD_SETSIZE-1; - } - else if (sizehint < 1) { - PyErr_Format(PyExc_ValueError, - "sizehint must be greater zero, got %d", - sizehint); - return NULL; - } - - assert(type != NULL && type->tp_alloc != NULL); - self = (pyEpoll_Object *) type->tp_alloc(type, 0); - if (self == NULL) - return NULL; - - if (fd == -1) { - Py_BEGIN_ALLOW_THREADS - self->epfd = epoll_create(sizehint); - Py_END_ALLOW_THREADS - } - else { - self->epfd = fd; - } - if (self->epfd < 0) { - Py_DECREF(self); - PyErr_SetFromErrno(PyExc_IOError); - return NULL; - } - return (PyObject *)self; + pyEpoll_Object *self; + + if (sizehint == -1) { + sizehint = FD_SETSIZE-1; + } + else if (sizehint < 1) { + PyErr_Format(PyExc_ValueError, + "sizehint must be greater zero, got %d", + sizehint); + return NULL; + } + + assert(type != NULL && type->tp_alloc != NULL); + self = (pyEpoll_Object *) type->tp_alloc(type, 0); + if (self == NULL) + return NULL; + + if (fd == -1) { + Py_BEGIN_ALLOW_THREADS + self->epfd = epoll_create(sizehint); + Py_END_ALLOW_THREADS + } + else { + self->epfd = fd; + } + if (self->epfd < 0) { + Py_DECREF(self); + PyErr_SetFromErrno(PyExc_IOError); + return NULL; + } + return (PyObject *)self; } static PyObject * pyepoll_new(PyTypeObject *type, PyObject *args, PyObject *kwds) { - int sizehint = -1; - static char *kwlist[] = {"sizehint", NULL}; + int sizehint = -1; + static char *kwlist[] = {"sizehint", NULL}; - if (!PyArg_ParseTupleAndKeywords(args, kwds, "|i:epoll", kwlist, - &sizehint)) - return NULL; + if (!PyArg_ParseTupleAndKeywords(args, kwds, "|i:epoll", kwlist, + &sizehint)) + return NULL; - return newPyEpoll_Object(type, sizehint, -1); + return newPyEpoll_Object(type, sizehint, -1); } static void pyepoll_dealloc(pyEpoll_Object *self) { - (void)pyepoll_internal_close(self); - Py_TYPE(self)->tp_free(self); + (void)pyepoll_internal_close(self); + Py_TYPE(self)->tp_free(self); } static PyObject* pyepoll_close(pyEpoll_Object *self) { - errno = pyepoll_internal_close(self); - if (errno < 0) { - PyErr_SetFromErrno(PyExc_IOError); - return NULL; - } - Py_RETURN_NONE; + errno = pyepoll_internal_close(self); + if (errno < 0) { + PyErr_SetFromErrno(PyExc_IOError); + return NULL; + } + Py_RETURN_NONE; } PyDoc_STRVAR(pyepoll_close_doc, @@ -815,18 +815,18 @@ static PyObject* pyepoll_get_closed(pyEpoll_Object *self) { - if (self->epfd < 0) - Py_RETURN_TRUE; - else - Py_RETURN_FALSE; + if (self->epfd < 0) + Py_RETURN_TRUE; + else + Py_RETURN_FALSE; } static PyObject* pyepoll_fileno(pyEpoll_Object *self) { - if (self->epfd < 0) - return pyepoll_err_closed(); - return PyLong_FromLong(self->epfd); + if (self->epfd < 0) + return pyepoll_err_closed(); + return PyLong_FromLong(self->epfd); } PyDoc_STRVAR(pyepoll_fileno_doc, @@ -837,12 +837,12 @@ static PyObject* pyepoll_fromfd(PyObject *cls, PyObject *args) { - SOCKET fd; + SOCKET fd; - if (!PyArg_ParseTuple(args, "i:fromfd", &fd)) - return NULL; + if (!PyArg_ParseTuple(args, "i:fromfd", &fd)) + return NULL; - return newPyEpoll_Object((PyTypeObject*)cls, -1, fd); + return newPyEpoll_Object((PyTypeObject*)cls, -1, fd); } PyDoc_STRVAR(pyepoll_fromfd_doc, @@ -853,65 +853,65 @@ static PyObject * pyepoll_internal_ctl(int epfd, int op, PyObject *pfd, unsigned int events) { - struct epoll_event ev; - int result; - int fd; - - if (epfd < 0) - return pyepoll_err_closed(); - - fd = PyObject_AsFileDescriptor(pfd); - if (fd == -1) { - return NULL; - } - - switch(op) { - case EPOLL_CTL_ADD: - case EPOLL_CTL_MOD: - ev.events = events; - ev.data.fd = fd; - Py_BEGIN_ALLOW_THREADS - result = epoll_ctl(epfd, op, fd, &ev); - Py_END_ALLOW_THREADS - break; - case EPOLL_CTL_DEL: - /* In kernel versions before 2.6.9, the EPOLL_CTL_DEL - * operation required a non-NULL pointer in event, even - * though this argument is ignored. */ - Py_BEGIN_ALLOW_THREADS - result = epoll_ctl(epfd, op, fd, &ev); - if (errno == EBADF) { - /* fd already closed */ - result = 0; - errno = 0; - } - Py_END_ALLOW_THREADS - break; - default: - result = -1; - errno = EINVAL; - } - - if (result < 0) { - PyErr_SetFromErrno(PyExc_IOError); - return NULL; - } - Py_RETURN_NONE; + struct epoll_event ev; + int result; + int fd; + + if (epfd < 0) + return pyepoll_err_closed(); + + fd = PyObject_AsFileDescriptor(pfd); + if (fd == -1) { + return NULL; + } + + switch(op) { + case EPOLL_CTL_ADD: + case EPOLL_CTL_MOD: + ev.events = events; + ev.data.fd = fd; + Py_BEGIN_ALLOW_THREADS + result = epoll_ctl(epfd, op, fd, &ev); + Py_END_ALLOW_THREADS + break; + case EPOLL_CTL_DEL: + /* In kernel versions before 2.6.9, the EPOLL_CTL_DEL + * operation required a non-NULL pointer in event, even + * though this argument is ignored. */ + Py_BEGIN_ALLOW_THREADS + result = epoll_ctl(epfd, op, fd, &ev); + if (errno == EBADF) { + /* fd already closed */ + result = 0; + errno = 0; + } + Py_END_ALLOW_THREADS + break; + default: + result = -1; + errno = EINVAL; + } + + if (result < 0) { + PyErr_SetFromErrno(PyExc_IOError); + return NULL; + } + Py_RETURN_NONE; } static PyObject * pyepoll_register(pyEpoll_Object *self, PyObject *args, PyObject *kwds) { - PyObject *pfd; - unsigned int events = EPOLLIN | EPOLLOUT | EPOLLPRI; - static char *kwlist[] = {"fd", "eventmask", NULL}; - - if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|I:register", kwlist, - &pfd, &events)) { - return NULL; - } + PyObject *pfd; + unsigned int events = EPOLLIN | EPOLLOUT | EPOLLPRI; + static char *kwlist[] = {"fd", "eventmask", NULL}; + + if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|I:register", kwlist, + &pfd, &events)) { + return NULL; + } - return pyepoll_internal_ctl(self->epfd, EPOLL_CTL_ADD, pfd, events); + return pyepoll_internal_ctl(self->epfd, EPOLL_CTL_ADD, pfd, events); } PyDoc_STRVAR(pyepoll_register_doc, @@ -928,16 +928,16 @@ static PyObject * pyepoll_modify(pyEpoll_Object *self, PyObject *args, PyObject *kwds) { - PyObject *pfd; - unsigned int events; - static char *kwlist[] = {"fd", "eventmask", NULL}; - - if (!PyArg_ParseTupleAndKeywords(args, kwds, "OI:modify", kwlist, - &pfd, &events)) { - return NULL; - } + PyObject *pfd; + unsigned int events; + static char *kwlist[] = {"fd", "eventmask", NULL}; + + if (!PyArg_ParseTupleAndKeywords(args, kwds, "OI:modify", kwlist, + &pfd, &events)) { + return NULL; + } - return pyepoll_internal_ctl(self->epfd, EPOLL_CTL_MOD, pfd, events); + return pyepoll_internal_ctl(self->epfd, EPOLL_CTL_MOD, pfd, events); } PyDoc_STRVAR(pyepoll_modify_doc, @@ -949,15 +949,15 @@ static PyObject * pyepoll_unregister(pyEpoll_Object *self, PyObject *args, PyObject *kwds) { - PyObject *pfd; - static char *kwlist[] = {"fd", NULL}; + PyObject *pfd; + static char *kwlist[] = {"fd", NULL}; - if (!PyArg_ParseTupleAndKeywords(args, kwds, "O:unregister", kwlist, - &pfd)) { - return NULL; - } + if (!PyArg_ParseTupleAndKeywords(args, kwds, "O:unregister", kwlist, + &pfd)) { + return NULL; + } - return pyepoll_internal_ctl(self->epfd, EPOLL_CTL_DEL, pfd, 0); + return pyepoll_internal_ctl(self->epfd, EPOLL_CTL_DEL, pfd, 0); } PyDoc_STRVAR(pyepoll_unregister_doc, @@ -968,76 +968,76 @@ static PyObject * pyepoll_poll(pyEpoll_Object *self, PyObject *args, PyObject *kwds) { - double dtimeout = -1.; - int timeout; - int maxevents = -1; - int nfds, i; - PyObject *elist = NULL, *etuple = NULL; - struct epoll_event *evs = NULL; - static char *kwlist[] = {"timeout", "maxevents", NULL}; - - if (self->epfd < 0) - return pyepoll_err_closed(); - - if (!PyArg_ParseTupleAndKeywords(args, kwds, "|di:poll", kwlist, - &dtimeout, &maxevents)) { - return NULL; - } - - if (dtimeout < 0) { - timeout = -1; - } - else if (dtimeout * 1000.0 > INT_MAX) { - PyErr_SetString(PyExc_OverflowError, - "timeout is too large"); - return NULL; - } - else { - timeout = (int)(dtimeout * 1000.0); - } - - if (maxevents == -1) { - maxevents = FD_SETSIZE-1; - } - else if (maxevents < 1) { - PyErr_Format(PyExc_ValueError, - "maxevents must be greater than 0, got %d", - maxevents); - return NULL; - } - - evs = PyMem_New(struct epoll_event, maxevents); - if (evs == NULL) { - Py_DECREF(self); - PyErr_NoMemory(); - return NULL; - } - - Py_BEGIN_ALLOW_THREADS - nfds = epoll_wait(self->epfd, evs, maxevents, timeout); - Py_END_ALLOW_THREADS - if (nfds < 0) { - PyErr_SetFromErrno(PyExc_IOError); - goto error; - } - - elist = PyList_New(nfds); - if (elist == NULL) { - goto error; - } - - for (i = 0; i < nfds; i++) { - etuple = Py_BuildValue("iI", evs[i].data.fd, evs[i].events); - if (etuple == NULL) { - Py_CLEAR(elist); - goto error; - } - PyList_SET_ITEM(elist, i, etuple); - } + double dtimeout = -1.; + int timeout; + int maxevents = -1; + int nfds, i; + PyObject *elist = NULL, *etuple = NULL; + struct epoll_event *evs = NULL; + static char *kwlist[] = {"timeout", "maxevents", NULL}; + + if (self->epfd < 0) + return pyepoll_err_closed(); + + if (!PyArg_ParseTupleAndKeywords(args, kwds, "|di:poll", kwlist, + &dtimeout, &maxevents)) { + return NULL; + } + + if (dtimeout < 0) { + timeout = -1; + } + else if (dtimeout * 1000.0 > INT_MAX) { + PyErr_SetString(PyExc_OverflowError, + "timeout is too large"); + return NULL; + } + else { + timeout = (int)(dtimeout * 1000.0); + } + + if (maxevents == -1) { + maxevents = FD_SETSIZE-1; + } + else if (maxevents < 1) { + PyErr_Format(PyExc_ValueError, + "maxevents must be greater than 0, got %d", + maxevents); + return NULL; + } + + evs = PyMem_New(struct epoll_event, maxevents); + if (evs == NULL) { + Py_DECREF(self); + PyErr_NoMemory(); + return NULL; + } + + Py_BEGIN_ALLOW_THREADS + nfds = epoll_wait(self->epfd, evs, maxevents, timeout); + Py_END_ALLOW_THREADS + if (nfds < 0) { + PyErr_SetFromErrno(PyExc_IOError); + goto error; + } + + elist = PyList_New(nfds); + if (elist == NULL) { + goto error; + } + + for (i = 0; i < nfds; i++) { + etuple = Py_BuildValue("iI", evs[i].data.fd, evs[i].events); + if (etuple == NULL) { + Py_CLEAR(elist); + goto error; + } + PyList_SET_ITEM(elist, i, etuple); + } error: - PyMem_Free(evs); - return elist; + PyMem_Free(evs); + return elist; } PyDoc_STRVAR(pyepoll_poll_doc, @@ -1048,27 +1048,27 @@ Up to maxevents are returned to the caller."); static PyMethodDef pyepoll_methods[] = { - {"fromfd", (PyCFunction)pyepoll_fromfd, - METH_VARARGS | METH_CLASS, pyepoll_fromfd_doc}, - {"close", (PyCFunction)pyepoll_close, METH_NOARGS, - pyepoll_close_doc}, - {"fileno", (PyCFunction)pyepoll_fileno, METH_NOARGS, - pyepoll_fileno_doc}, - {"modify", (PyCFunction)pyepoll_modify, - METH_VARARGS | METH_KEYWORDS, pyepoll_modify_doc}, - {"register", (PyCFunction)pyepoll_register, - METH_VARARGS | METH_KEYWORDS, pyepoll_register_doc}, - {"unregister", (PyCFunction)pyepoll_unregister, - METH_VARARGS | METH_KEYWORDS, pyepoll_unregister_doc}, - {"poll", (PyCFunction)pyepoll_poll, - METH_VARARGS | METH_KEYWORDS, pyepoll_poll_doc}, - {NULL, NULL}, + {"fromfd", (PyCFunction)pyepoll_fromfd, + METH_VARARGS | METH_CLASS, pyepoll_fromfd_doc}, + {"close", (PyCFunction)pyepoll_close, METH_NOARGS, + pyepoll_close_doc}, + {"fileno", (PyCFunction)pyepoll_fileno, METH_NOARGS, + pyepoll_fileno_doc}, + {"modify", (PyCFunction)pyepoll_modify, + METH_VARARGS | METH_KEYWORDS, pyepoll_modify_doc}, + {"register", (PyCFunction)pyepoll_register, + METH_VARARGS | METH_KEYWORDS, pyepoll_register_doc}, + {"unregister", (PyCFunction)pyepoll_unregister, + METH_VARARGS | METH_KEYWORDS, pyepoll_unregister_doc}, + {"poll", (PyCFunction)pyepoll_poll, + METH_VARARGS | METH_KEYWORDS, pyepoll_poll_doc}, + {NULL, NULL}, }; static PyGetSetDef pyepoll_getsetlist[] = { - {"closed", (getter)pyepoll_get_closed, NULL, - "True if the epoll handler is closed"}, - {0}, + {"closed", (getter)pyepoll_get_closed, NULL, + "True if the epoll handler is closed"}, + {0}, }; PyDoc_STRVAR(pyepoll_doc, @@ -1081,45 +1081,45 @@ the maximum number of monitored events."); static PyTypeObject pyEpoll_Type = { - PyVarObject_HEAD_INIT(NULL, 0) - "select.epoll", /* tp_name */ - sizeof(pyEpoll_Object), /* tp_basicsize */ - 0, /* tp_itemsize */ - (destructor)pyepoll_dealloc, /* tp_dealloc */ - 0, /* tp_print */ - 0, /* tp_getattr */ - 0, /* tp_setattr */ - 0, /* tp_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, /* tp_flags */ - pyepoll_doc, /* tp_doc */ - 0, /* tp_traverse */ - 0, /* tp_clear */ - 0, /* tp_richcompare */ - 0, /* tp_weaklistoffset */ - 0, /* tp_iter */ - 0, /* tp_iternext */ - pyepoll_methods, /* tp_methods */ - 0, /* tp_members */ - pyepoll_getsetlist, /* tp_getset */ - 0, /* tp_base */ - 0, /* tp_dict */ - 0, /* tp_descr_get */ - 0, /* tp_descr_set */ - 0, /* tp_dictoffset */ - 0, /* tp_init */ - 0, /* tp_alloc */ - pyepoll_new, /* tp_new */ - 0, /* tp_free */ + PyVarObject_HEAD_INIT(NULL, 0) + "select.epoll", /* tp_name */ + sizeof(pyEpoll_Object), /* tp_basicsize */ + 0, /* tp_itemsize */ + (destructor)pyepoll_dealloc, /* tp_dealloc */ + 0, /* tp_print */ + 0, /* tp_getattr */ + 0, /* tp_setattr */ + 0, /* tp_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, /* tp_flags */ + pyepoll_doc, /* tp_doc */ + 0, /* tp_traverse */ + 0, /* tp_clear */ + 0, /* tp_richcompare */ + 0, /* tp_weaklistoffset */ + 0, /* tp_iter */ + 0, /* tp_iternext */ + pyepoll_methods, /* tp_methods */ + 0, /* tp_members */ + pyepoll_getsetlist, /* tp_getset */ + 0, /* tp_base */ + 0, /* tp_dict */ + 0, /* tp_descr_get */ + 0, /* tp_descr_set */ + 0, /* tp_dictoffset */ + 0, /* tp_init */ + 0, /* tp_alloc */ + pyepoll_new, /* tp_new */ + 0, /* tp_free */ }; #endif /* HAVE_EPOLL */ @@ -1174,8 +1174,8 @@ udata->object mapping."); typedef struct { - PyObject_HEAD - struct kevent e; + PyObject_HEAD + struct kevent e; } kqueue_event_Object; static PyTypeObject kqueue_event_Type; @@ -1183,8 +1183,8 @@ #define kqueue_event_Check(op) (PyObject_TypeCheck((op), &kqueue_event_Type)) typedef struct { - PyObject_HEAD - SOCKET kqfd; /* kqueue control fd */ + PyObject_HEAD + SOCKET kqfd; /* kqueue control fd */ } kqueue_queue_Object; static PyTypeObject kqueue_queue_Type; @@ -1222,13 +1222,13 @@ #define KQ_OFF(x) offsetof(kqueue_event_Object, x) static struct PyMemberDef kqueue_event_members[] = { - {"ident", T_UINTPTRT, KQ_OFF(e.ident)}, - {"filter", T_SHORT, KQ_OFF(e.filter)}, - {"flags", T_USHORT, KQ_OFF(e.flags)}, - {"fflags", T_UINT, KQ_OFF(e.fflags)}, - {"data", T_INTPTRT, KQ_OFF(e.data)}, - {"udata", T_UINTPTRT, KQ_OFF(e.udata)}, - {NULL} /* Sentinel */ + {"ident", T_UINTPTRT, KQ_OFF(e.ident)}, + {"filter", T_SHORT, KQ_OFF(e.filter)}, + {"flags", T_USHORT, KQ_OFF(e.flags)}, + {"fflags", T_UINT, KQ_OFF(e.fflags)}, + {"data", T_INTPTRT, KQ_OFF(e.data)}, + {"udata", T_UINTPTRT, KQ_OFF(e.udata)}, + {NULL} /* Sentinel */ }; #undef KQ_OFF @@ -1236,214 +1236,214 @@ kqueue_event_repr(kqueue_event_Object *s) { - char buf[1024]; - PyOS_snprintf( - buf, sizeof(buf), - "", - (size_t)(s->e.ident), s->e.filter, s->e.flags, - s->e.fflags, (Py_ssize_t)(s->e.data), s->e.udata); - return PyUnicode_FromString(buf); + char buf[1024]; + PyOS_snprintf( + buf, sizeof(buf), + "", + (size_t)(s->e.ident), s->e.filter, s->e.flags, + s->e.fflags, (Py_ssize_t)(s->e.data), s->e.udata); + return PyUnicode_FromString(buf); } static int kqueue_event_init(kqueue_event_Object *self, PyObject *args, PyObject *kwds) { - PyObject *pfd; - static char *kwlist[] = {"ident", "filter", "flags", "fflags", - "data", "udata", NULL}; - static char *fmt = "O|hhi" INTPTRT_FMT_UNIT UINTPTRT_FMT_UNIT ":kevent"; - - EV_SET(&(self->e), 0, EVFILT_READ, EV_ADD, 0, 0, 0); /* defaults */ - - if (!PyArg_ParseTupleAndKeywords(args, kwds, fmt, kwlist, - &pfd, &(self->e.filter), &(self->e.flags), - &(self->e.fflags), &(self->e.data), &(self->e.udata))) { - return -1; - } - - if (PyLong_Check(pfd)) { - self->e.ident = PyLong_AsUintptr_t(pfd); - } - else { - self->e.ident = PyObject_AsFileDescriptor(pfd); - } - if (PyErr_Occurred()) { - return -1; - } - return 0; + PyObject *pfd; + static char *kwlist[] = {"ident", "filter", "flags", "fflags", + "data", "udata", NULL}; + static char *fmt = "O|hhi" INTPTRT_FMT_UNIT UINTPTRT_FMT_UNIT ":kevent"; + + EV_SET(&(self->e), 0, EVFILT_READ, EV_ADD, 0, 0, 0); /* defaults */ + + if (!PyArg_ParseTupleAndKeywords(args, kwds, fmt, kwlist, + &pfd, &(self->e.filter), &(self->e.flags), + &(self->e.fflags), &(self->e.data), &(self->e.udata))) { + return -1; + } + + if (PyLong_Check(pfd)) { + self->e.ident = PyLong_AsUintptr_t(pfd); + } + else { + self->e.ident = PyObject_AsFileDescriptor(pfd); + } + if (PyErr_Occurred()) { + return -1; + } + return 0; } static PyObject * kqueue_event_richcompare(kqueue_event_Object *s, kqueue_event_Object *o, - int op) + int op) { - Py_intptr_t result = 0; + Py_intptr_t result = 0; - if (!kqueue_event_Check(o)) { - if (op == Py_EQ || op == Py_NE) { - PyObject *res = op == Py_EQ ? Py_False : Py_True; - Py_INCREF(res); - return res; - } - PyErr_Format(PyExc_TypeError, - "can't compare %.200s to %.200s", - Py_TYPE(s)->tp_name, Py_TYPE(o)->tp_name); - return NULL; - } - if (((result = s->e.ident - o->e.ident) == 0) && - ((result = s->e.filter - o->e.filter) == 0) && - ((result = s->e.flags - o->e.flags) == 0) && - ((result = s->e.fflags - o->e.fflags) == 0) && - ((result = s->e.data - o->e.data) == 0) && - ((result = s->e.udata - o->e.udata) == 0) - ) { - result = 0; - } - - switch (op) { - case Py_EQ: - result = (result == 0); - break; - case Py_NE: - result = (result != 0); - break; - case Py_LE: - result = (result <= 0); - break; - case Py_GE: - result = (result >= 0); - break; - case Py_LT: - result = (result < 0); - break; - case Py_GT: - result = (result > 0); - break; - } - return PyBool_FromLong((long)result); + if (!kqueue_event_Check(o)) { + if (op == Py_EQ || op == Py_NE) { + PyObject *res = op == Py_EQ ? Py_False : Py_True; + Py_INCREF(res); + return res; + } + PyErr_Format(PyExc_TypeError, + "can't compare %.200s to %.200s", + Py_TYPE(s)->tp_name, Py_TYPE(o)->tp_name); + return NULL; + } + if (((result = s->e.ident - o->e.ident) == 0) && + ((result = s->e.filter - o->e.filter) == 0) && + ((result = s->e.flags - o->e.flags) == 0) && + ((result = s->e.fflags - o->e.fflags) == 0) && + ((result = s->e.data - o->e.data) == 0) && + ((result = s->e.udata - o->e.udata) == 0) + ) { + result = 0; + } + + switch (op) { + case Py_EQ: + result = (result == 0); + break; + case Py_NE: + result = (result != 0); + break; + case Py_LE: + result = (result <= 0); + break; + case Py_GE: + result = (result >= 0); + break; + case Py_LT: + result = (result < 0); + break; + case Py_GT: + result = (result > 0); + break; + } + return PyBool_FromLong((long)result); } static PyTypeObject kqueue_event_Type = { - PyVarObject_HEAD_INIT(NULL, 0) - "select.kevent", /* tp_name */ - sizeof(kqueue_event_Object), /* tp_basicsize */ - 0, /* tp_itemsize */ - 0, /* tp_dealloc */ - 0, /* tp_print */ - 0, /* tp_getattr */ - 0, /* tp_setattr */ - 0, /* tp_reserved */ - (reprfunc)kqueue_event_repr, /* tp_repr */ - 0, /* tp_as_number */ - 0, /* tp_as_sequence */ - 0, /* tp_as_mapping */ - 0, /* tp_hash */ - 0, /* tp_call */ - 0, /* tp_str */ - 0, /* tp_getattro */ - 0, /* tp_setattro */ - 0, /* tp_as_buffer */ - Py_TPFLAGS_DEFAULT, /* tp_flags */ - kqueue_event_doc, /* tp_doc */ - 0, /* tp_traverse */ - 0, /* tp_clear */ - (richcmpfunc)kqueue_event_richcompare, /* tp_richcompare */ - 0, /* tp_weaklistoffset */ - 0, /* tp_iter */ - 0, /* tp_iternext */ - 0, /* tp_methods */ - kqueue_event_members, /* tp_members */ - 0, /* tp_getset */ - 0, /* tp_base */ - 0, /* tp_dict */ - 0, /* tp_descr_get */ - 0, /* tp_descr_set */ - 0, /* tp_dictoffset */ - (initproc)kqueue_event_init, /* tp_init */ - 0, /* tp_alloc */ - 0, /* tp_new */ - 0, /* tp_free */ + PyVarObject_HEAD_INIT(NULL, 0) + "select.kevent", /* tp_name */ + sizeof(kqueue_event_Object), /* tp_basicsize */ + 0, /* tp_itemsize */ + 0, /* tp_dealloc */ + 0, /* tp_print */ + 0, /* tp_getattr */ + 0, /* tp_setattr */ + 0, /* tp_reserved */ + (reprfunc)kqueue_event_repr, /* tp_repr */ + 0, /* tp_as_number */ + 0, /* tp_as_sequence */ + 0, /* tp_as_mapping */ + 0, /* tp_hash */ + 0, /* tp_call */ + 0, /* tp_str */ + 0, /* tp_getattro */ + 0, /* tp_setattro */ + 0, /* tp_as_buffer */ + Py_TPFLAGS_DEFAULT, /* tp_flags */ + kqueue_event_doc, /* tp_doc */ + 0, /* tp_traverse */ + 0, /* tp_clear */ + (richcmpfunc)kqueue_event_richcompare, /* tp_richcompare */ + 0, /* tp_weaklistoffset */ + 0, /* tp_iter */ + 0, /* tp_iternext */ + 0, /* tp_methods */ + kqueue_event_members, /* tp_members */ + 0, /* tp_getset */ + 0, /* tp_base */ + 0, /* tp_dict */ + 0, /* tp_descr_get */ + 0, /* tp_descr_set */ + 0, /* tp_dictoffset */ + (initproc)kqueue_event_init, /* tp_init */ + 0, /* tp_alloc */ + 0, /* tp_new */ + 0, /* tp_free */ }; static PyObject * kqueue_queue_err_closed(void) { - PyErr_SetString(PyExc_ValueError, "I/O operation on closed kqueue fd"); - return NULL; + PyErr_SetString(PyExc_ValueError, "I/O operation on closed kqueue fd"); + return NULL; } static int kqueue_queue_internal_close(kqueue_queue_Object *self) { - int save_errno = 0; - if (self->kqfd >= 0) { - int kqfd = self->kqfd; - self->kqfd = -1; - Py_BEGIN_ALLOW_THREADS - if (close(kqfd) < 0) - save_errno = errno; - Py_END_ALLOW_THREADS - } - return save_errno; + int save_errno = 0; + if (self->kqfd >= 0) { + int kqfd = self->kqfd; + self->kqfd = -1; + Py_BEGIN_ALLOW_THREADS + if (close(kqfd) < 0) + save_errno = errno; + Py_END_ALLOW_THREADS + } + return save_errno; } static PyObject * newKqueue_Object(PyTypeObject *type, SOCKET fd) { - kqueue_queue_Object *self; - assert(type != NULL && type->tp_alloc != NULL); - self = (kqueue_queue_Object *) type->tp_alloc(type, 0); - if (self == NULL) { - return NULL; - } - - if (fd == -1) { - Py_BEGIN_ALLOW_THREADS - self->kqfd = kqueue(); - Py_END_ALLOW_THREADS - } - else { - self->kqfd = fd; - } - if (self->kqfd < 0) { - Py_DECREF(self); - PyErr_SetFromErrno(PyExc_IOError); - return NULL; - } - return (PyObject *)self; + kqueue_queue_Object *self; + assert(type != NULL && type->tp_alloc != NULL); + self = (kqueue_queue_Object *) type->tp_alloc(type, 0); + if (self == NULL) { + return NULL; + } + + if (fd == -1) { + Py_BEGIN_ALLOW_THREADS + self->kqfd = kqueue(); + Py_END_ALLOW_THREADS + } + else { + self->kqfd = fd; + } + if (self->kqfd < 0) { + Py_DECREF(self); + PyErr_SetFromErrno(PyExc_IOError); + return NULL; + } + return (PyObject *)self; } static PyObject * kqueue_queue_new(PyTypeObject *type, PyObject *args, PyObject *kwds) { - if ((args != NULL && PyObject_Size(args)) || - (kwds != NULL && PyObject_Size(kwds))) { - PyErr_SetString(PyExc_ValueError, - "select.kqueue doesn't accept arguments"); - return NULL; - } + if ((args != NULL && PyObject_Size(args)) || + (kwds != NULL && PyObject_Size(kwds))) { + PyErr_SetString(PyExc_ValueError, + "select.kqueue doesn't accept arguments"); + return NULL; + } - return newKqueue_Object(type, -1); + return newKqueue_Object(type, -1); } static void kqueue_queue_dealloc(kqueue_queue_Object *self) { - kqueue_queue_internal_close(self); - Py_TYPE(self)->tp_free(self); + kqueue_queue_internal_close(self); + Py_TYPE(self)->tp_free(self); } static PyObject* kqueue_queue_close(kqueue_queue_Object *self) { - errno = kqueue_queue_internal_close(self); - if (errno < 0) { - PyErr_SetFromErrno(PyExc_IOError); - return NULL; - } - Py_RETURN_NONE; + errno = kqueue_queue_internal_close(self); + if (errno < 0) { + PyErr_SetFromErrno(PyExc_IOError); + return NULL; + } + Py_RETURN_NONE; } PyDoc_STRVAR(kqueue_queue_close_doc, @@ -1455,18 +1455,18 @@ static PyObject* kqueue_queue_get_closed(kqueue_queue_Object *self) { - if (self->kqfd < 0) - Py_RETURN_TRUE; - else - Py_RETURN_FALSE; + if (self->kqfd < 0) + Py_RETURN_TRUE; + else + Py_RETURN_FALSE; } static PyObject* kqueue_queue_fileno(kqueue_queue_Object *self) { - if (self->kqfd < 0) - return kqueue_queue_err_closed(); - return PyLong_FromLong(self->kqfd); + if (self->kqfd < 0) + return kqueue_queue_err_closed(); + return PyLong_FromLong(self->kqfd); } PyDoc_STRVAR(kqueue_queue_fileno_doc, @@ -1477,12 +1477,12 @@ static PyObject* kqueue_queue_fromfd(PyObject *cls, PyObject *args) { - SOCKET fd; + SOCKET fd; - if (!PyArg_ParseTuple(args, "i:fromfd", &fd)) - return NULL; + if (!PyArg_ParseTuple(args, "i:fromfd", &fd)) + return NULL; - return newKqueue_Object((PyTypeObject*)cls, fd); + return newKqueue_Object((PyTypeObject*)cls, fd); } PyDoc_STRVAR(kqueue_queue_fromfd_doc, @@ -1493,144 +1493,144 @@ static PyObject * kqueue_queue_control(kqueue_queue_Object *self, PyObject *args) { - int nevents = 0; - int gotevents = 0; - int nchanges = 0; - int i = 0; - PyObject *otimeout = NULL; - PyObject *ch = NULL; - PyObject *it = NULL, *ei = NULL; - PyObject *result = NULL; - struct kevent *evl = NULL; - struct kevent *chl = NULL; - struct timespec timeoutspec; - struct timespec *ptimeoutspec; - - if (self->kqfd < 0) - return kqueue_queue_err_closed(); - - if (!PyArg_ParseTuple(args, "Oi|O:control", &ch, &nevents, &otimeout)) - return NULL; - - if (nevents < 0) { - PyErr_Format(PyExc_ValueError, - "Length of eventlist must be 0 or positive, got %d", - nevents); - return NULL; - } - - if (otimeout == Py_None || otimeout == NULL) { - ptimeoutspec = NULL; - } - else if (PyNumber_Check(otimeout)) { - double timeout; - long seconds; - - timeout = PyFloat_AsDouble(otimeout); - if (timeout == -1 && PyErr_Occurred()) - return NULL; - if (timeout > (double)LONG_MAX) { - PyErr_SetString(PyExc_OverflowError, - "timeout period too long"); - return NULL; - } - if (timeout < 0) { - PyErr_SetString(PyExc_ValueError, - "timeout must be positive or None"); - return NULL; - } - - seconds = (long)timeout; - timeout = timeout - (double)seconds; - timeoutspec.tv_sec = seconds; - timeoutspec.tv_nsec = (long)(timeout * 1E9); - ptimeoutspec = &timeoutspec; - } - else { - PyErr_Format(PyExc_TypeError, - "timeout argument must be an number " - "or None, got %.200s", - Py_TYPE(otimeout)->tp_name); - return NULL; - } - - if (ch != NULL && ch != Py_None) { - it = PyObject_GetIter(ch); - if (it == NULL) { - PyErr_SetString(PyExc_TypeError, - "changelist is not iterable"); - return NULL; - } - nchanges = PyObject_Size(ch); - if (nchanges < 0) { - goto error; - } - - chl = PyMem_New(struct kevent, nchanges); - if (chl == NULL) { - PyErr_NoMemory(); - goto error; - } - i = 0; - while ((ei = PyIter_Next(it)) != NULL) { - if (!kqueue_event_Check(ei)) { - Py_DECREF(ei); - PyErr_SetString(PyExc_TypeError, - "changelist must be an iterable of " - "select.kevent objects"); - goto error; - } else { - chl[i++] = ((kqueue_event_Object *)ei)->e; - } - Py_DECREF(ei); - } - } - Py_CLEAR(it); - - /* event list */ - if (nevents) { - evl = PyMem_New(struct kevent, nevents); - if (evl == NULL) { - PyErr_NoMemory(); - goto error; - } - } - - Py_BEGIN_ALLOW_THREADS - gotevents = kevent(self->kqfd, chl, nchanges, - evl, nevents, ptimeoutspec); - Py_END_ALLOW_THREADS - - if (gotevents == -1) { - PyErr_SetFromErrno(PyExc_OSError); - goto error; - } - - result = PyList_New(gotevents); - if (result == NULL) { - goto error; - } - - for (i = 0; i < gotevents; i++) { - kqueue_event_Object *ch; - - ch = PyObject_New(kqueue_event_Object, &kqueue_event_Type); - if (ch == NULL) { - goto error; - } - ch->e = evl[i]; - PyList_SET_ITEM(result, i, (PyObject *)ch); - } - PyMem_Free(chl); - PyMem_Free(evl); - return result; + int nevents = 0; + int gotevents = 0; + int nchanges = 0; + int i = 0; + PyObject *otimeout = NULL; + PyObject *ch = NULL; + PyObject *it = NULL, *ei = NULL; + PyObject *result = NULL; + struct kevent *evl = NULL; + struct kevent *chl = NULL; + struct timespec timeoutspec; + struct timespec *ptimeoutspec; + + if (self->kqfd < 0) + return kqueue_queue_err_closed(); + + if (!PyArg_ParseTuple(args, "Oi|O:control", &ch, &nevents, &otimeout)) + return NULL; + + if (nevents < 0) { + PyErr_Format(PyExc_ValueError, + "Length of eventlist must be 0 or positive, got %d", + nevents); + return NULL; + } + + if (otimeout == Py_None || otimeout == NULL) { + ptimeoutspec = NULL; + } + else if (PyNumber_Check(otimeout)) { + double timeout; + long seconds; + + timeout = PyFloat_AsDouble(otimeout); + if (timeout == -1 && PyErr_Occurred()) + return NULL; + if (timeout > (double)LONG_MAX) { + PyErr_SetString(PyExc_OverflowError, + "timeout period too long"); + return NULL; + } + if (timeout < 0) { + PyErr_SetString(PyExc_ValueError, + "timeout must be positive or None"); + return NULL; + } + + seconds = (long)timeout; + timeout = timeout - (double)seconds; + timeoutspec.tv_sec = seconds; + timeoutspec.tv_nsec = (long)(timeout * 1E9); + ptimeoutspec = &timeoutspec; + } + else { + PyErr_Format(PyExc_TypeError, + "timeout argument must be an number " + "or None, got %.200s", + Py_TYPE(otimeout)->tp_name); + return NULL; + } + + if (ch != NULL && ch != Py_None) { + it = PyObject_GetIter(ch); + if (it == NULL) { + PyErr_SetString(PyExc_TypeError, + "changelist is not iterable"); + return NULL; + } + nchanges = PyObject_Size(ch); + if (nchanges < 0) { + goto error; + } + + chl = PyMem_New(struct kevent, nchanges); + if (chl == NULL) { + PyErr_NoMemory(); + goto error; + } + i = 0; + while ((ei = PyIter_Next(it)) != NULL) { + if (!kqueue_event_Check(ei)) { + Py_DECREF(ei); + PyErr_SetString(PyExc_TypeError, + "changelist must be an iterable of " + "select.kevent objects"); + goto error; + } else { + chl[i++] = ((kqueue_event_Object *)ei)->e; + } + Py_DECREF(ei); + } + } + Py_CLEAR(it); + + /* event list */ + if (nevents) { + evl = PyMem_New(struct kevent, nevents); + if (evl == NULL) { + PyErr_NoMemory(); + goto error; + } + } + + Py_BEGIN_ALLOW_THREADS + gotevents = kevent(self->kqfd, chl, nchanges, + evl, nevents, ptimeoutspec); + Py_END_ALLOW_THREADS + + if (gotevents == -1) { + PyErr_SetFromErrno(PyExc_OSError); + goto error; + } + + result = PyList_New(gotevents); + if (result == NULL) { + goto error; + } + + for (i = 0; i < gotevents; i++) { + kqueue_event_Object *ch; + + ch = PyObject_New(kqueue_event_Object, &kqueue_event_Type); + if (ch == NULL) { + goto error; + } + ch->e = evl[i]; + PyList_SET_ITEM(result, i, (PyObject *)ch); + } + PyMem_Free(chl); + PyMem_Free(evl); + return result; error: - PyMem_Free(chl); - PyMem_Free(evl); - Py_XDECREF(result); - Py_XDECREF(it); - return NULL; + PyMem_Free(chl); + PyMem_Free(evl); + Py_XDECREF(result); + Py_XDECREF(it); + return NULL; } PyDoc_STRVAR(kqueue_queue_control_doc, @@ -1646,21 +1646,21 @@ static PyMethodDef kqueue_queue_methods[] = { - {"fromfd", (PyCFunction)kqueue_queue_fromfd, - METH_VARARGS | METH_CLASS, kqueue_queue_fromfd_doc}, - {"close", (PyCFunction)kqueue_queue_close, METH_NOARGS, - kqueue_queue_close_doc}, - {"fileno", (PyCFunction)kqueue_queue_fileno, METH_NOARGS, - kqueue_queue_fileno_doc}, - {"control", (PyCFunction)kqueue_queue_control, - METH_VARARGS , kqueue_queue_control_doc}, - {NULL, NULL}, + {"fromfd", (PyCFunction)kqueue_queue_fromfd, + METH_VARARGS | METH_CLASS, kqueue_queue_fromfd_doc}, + {"close", (PyCFunction)kqueue_queue_close, METH_NOARGS, + kqueue_queue_close_doc}, + {"fileno", (PyCFunction)kqueue_queue_fileno, METH_NOARGS, + kqueue_queue_fileno_doc}, + {"control", (PyCFunction)kqueue_queue_control, + METH_VARARGS , kqueue_queue_control_doc}, + {NULL, NULL}, }; static PyGetSetDef kqueue_queue_getsetlist[] = { - {"closed", (getter)kqueue_queue_get_closed, NULL, - "True if the kqueue handler is closed"}, - {0}, + {"closed", (getter)kqueue_queue_get_closed, NULL, + "True if the kqueue handler is closed"}, + {0}, }; PyDoc_STRVAR(kqueue_queue_doc, @@ -1679,45 +1679,45 @@ >>> kq.control([kevent(sock, KQ_FILTER_WRITE, KQ_EV_DELETE)], 0)"); static PyTypeObject kqueue_queue_Type = { - PyVarObject_HEAD_INIT(NULL, 0) - "select.kqueue", /* tp_name */ - sizeof(kqueue_queue_Object), /* tp_basicsize */ - 0, /* tp_itemsize */ - (destructor)kqueue_queue_dealloc, /* tp_dealloc */ - 0, /* tp_print */ - 0, /* tp_getattr */ - 0, /* tp_setattr */ - 0, /* tp_reserved */ - 0, /* tp_repr */ - 0, /* tp_as_number */ - 0, /* tp_as_sequence */ - 0, /* tp_as_mapping */ - 0, /* tp_hash */ - 0, /* tp_call */ - 0, /* tp_str */ - 0, /* tp_getattro */ - 0, /* tp_setattro */ - 0, /* tp_as_buffer */ - Py_TPFLAGS_DEFAULT, /* tp_flags */ - kqueue_queue_doc, /* tp_doc */ - 0, /* tp_traverse */ - 0, /* tp_clear */ - 0, /* tp_richcompare */ - 0, /* tp_weaklistoffset */ - 0, /* tp_iter */ - 0, /* tp_iternext */ - kqueue_queue_methods, /* tp_methods */ - 0, /* tp_members */ - kqueue_queue_getsetlist, /* tp_getset */ - 0, /* tp_base */ - 0, /* tp_dict */ - 0, /* tp_descr_get */ - 0, /* tp_descr_set */ - 0, /* tp_dictoffset */ - 0, /* tp_init */ - 0, /* tp_alloc */ - kqueue_queue_new, /* tp_new */ - 0, /* tp_free */ + PyVarObject_HEAD_INIT(NULL, 0) + "select.kqueue", /* tp_name */ + sizeof(kqueue_queue_Object), /* tp_basicsize */ + 0, /* tp_itemsize */ + (destructor)kqueue_queue_dealloc, /* tp_dealloc */ + 0, /* tp_print */ + 0, /* tp_getattr */ + 0, /* tp_setattr */ + 0, /* tp_reserved */ + 0, /* tp_repr */ + 0, /* tp_as_number */ + 0, /* tp_as_sequence */ + 0, /* tp_as_mapping */ + 0, /* tp_hash */ + 0, /* tp_call */ + 0, /* tp_str */ + 0, /* tp_getattro */ + 0, /* tp_setattro */ + 0, /* tp_as_buffer */ + Py_TPFLAGS_DEFAULT, /* tp_flags */ + kqueue_queue_doc, /* tp_doc */ + 0, /* tp_traverse */ + 0, /* tp_clear */ + 0, /* tp_richcompare */ + 0, /* tp_weaklistoffset */ + 0, /* tp_iter */ + 0, /* tp_iternext */ + kqueue_queue_methods, /* tp_methods */ + 0, /* tp_members */ + kqueue_queue_getsetlist, /* tp_getset */ + 0, /* tp_base */ + 0, /* tp_dict */ + 0, /* tp_descr_get */ + 0, /* tp_descr_set */ + 0, /* tp_dictoffset */ + 0, /* tp_init */ + 0, /* tp_alloc */ + kqueue_queue_new, /* tp_new */ + 0, /* tp_free */ }; #endif /* HAVE_KQUEUE */ @@ -1748,11 +1748,11 @@ descriptors can be used."); static PyMethodDef select_methods[] = { - {"select", select_select, METH_VARARGS, select_doc}, + {"select", select_select, METH_VARARGS, select_doc}, #ifdef HAVE_POLL - {"poll", select_poll, METH_NOARGS, poll_doc}, + {"poll", select_poll, METH_NOARGS, poll_doc}, #endif /* HAVE_POLL */ - {0, 0}, /* sentinel */ + {0, 0}, /* sentinel */ }; PyDoc_STRVAR(module_doc, @@ -1763,167 +1763,167 @@ static struct PyModuleDef selectmodule = { - PyModuleDef_HEAD_INIT, - "select", - module_doc, - -1, - select_methods, - NULL, - NULL, - NULL, - NULL + PyModuleDef_HEAD_INIT, + "select", + module_doc, + -1, + select_methods, + NULL, + NULL, + NULL, + NULL }; PyMODINIT_FUNC PyInit_select(void) { - PyObject *m; - m = PyModule_Create(&selectmodule); - if (m == NULL) - return NULL; - - SelectError = PyErr_NewException("select.error", NULL, NULL); - Py_INCREF(SelectError); - PyModule_AddObject(m, "error", SelectError); + PyObject *m; + m = PyModule_Create(&selectmodule); + if (m == NULL) + return NULL; + + SelectError = PyErr_NewException("select.error", NULL, NULL); + Py_INCREF(SelectError); + PyModule_AddObject(m, "error", SelectError); #ifdef PIPE_BUF - PyModule_AddIntConstant(m, "PIPE_BUF", PIPE_BUF); + PyModule_AddIntConstant(m, "PIPE_BUF", PIPE_BUF); #endif #if defined(HAVE_POLL) #ifdef __APPLE__ - if (select_have_broken_poll()) { - if (PyObject_DelAttrString(m, "poll") == -1) { - PyErr_Clear(); - } - } else { + if (select_have_broken_poll()) { + if (PyObject_DelAttrString(m, "poll") == -1) { + PyErr_Clear(); + } + } else { #else - { + { #endif - if (PyType_Ready(&poll_Type) < 0) - return NULL; - PyModule_AddIntConstant(m, "POLLIN", POLLIN); - PyModule_AddIntConstant(m, "POLLPRI", POLLPRI); - PyModule_AddIntConstant(m, "POLLOUT", POLLOUT); - PyModule_AddIntConstant(m, "POLLERR", POLLERR); - PyModule_AddIntConstant(m, "POLLHUP", POLLHUP); - PyModule_AddIntConstant(m, "POLLNVAL", POLLNVAL); + if (PyType_Ready(&poll_Type) < 0) + return NULL; + PyModule_AddIntConstant(m, "POLLIN", POLLIN); + PyModule_AddIntConstant(m, "POLLPRI", POLLPRI); + PyModule_AddIntConstant(m, "POLLOUT", POLLOUT); + PyModule_AddIntConstant(m, "POLLERR", POLLERR); + PyModule_AddIntConstant(m, "POLLHUP", POLLHUP); + PyModule_AddIntConstant(m, "POLLNVAL", POLLNVAL); #ifdef POLLRDNORM - PyModule_AddIntConstant(m, "POLLRDNORM", POLLRDNORM); + PyModule_AddIntConstant(m, "POLLRDNORM", POLLRDNORM); #endif #ifdef POLLRDBAND - PyModule_AddIntConstant(m, "POLLRDBAND", POLLRDBAND); + PyModule_AddIntConstant(m, "POLLRDBAND", POLLRDBAND); #endif #ifdef POLLWRNORM - PyModule_AddIntConstant(m, "POLLWRNORM", POLLWRNORM); + PyModule_AddIntConstant(m, "POLLWRNORM", POLLWRNORM); #endif #ifdef POLLWRBAND - PyModule_AddIntConstant(m, "POLLWRBAND", POLLWRBAND); + PyModule_AddIntConstant(m, "POLLWRBAND", POLLWRBAND); #endif #ifdef POLLMSG - PyModule_AddIntConstant(m, "POLLMSG", POLLMSG); + PyModule_AddIntConstant(m, "POLLMSG", POLLMSG); #endif - } + } #endif /* HAVE_POLL */ #ifdef HAVE_EPOLL - Py_TYPE(&pyEpoll_Type) = &PyType_Type; - if (PyType_Ready(&pyEpoll_Type) < 0) - return NULL; - - Py_INCREF(&pyEpoll_Type); - PyModule_AddObject(m, "epoll", (PyObject *) &pyEpoll_Type); - - PyModule_AddIntConstant(m, "EPOLLIN", EPOLLIN); - PyModule_AddIntConstant(m, "EPOLLOUT", EPOLLOUT); - PyModule_AddIntConstant(m, "EPOLLPRI", EPOLLPRI); - PyModule_AddIntConstant(m, "EPOLLERR", EPOLLERR); - PyModule_AddIntConstant(m, "EPOLLHUP", EPOLLHUP); - PyModule_AddIntConstant(m, "EPOLLET", EPOLLET); + Py_TYPE(&pyEpoll_Type) = &PyType_Type; + if (PyType_Ready(&pyEpoll_Type) < 0) + return NULL; + + Py_INCREF(&pyEpoll_Type); + PyModule_AddObject(m, "epoll", (PyObject *) &pyEpoll_Type); + + PyModule_AddIntConstant(m, "EPOLLIN", EPOLLIN); + PyModule_AddIntConstant(m, "EPOLLOUT", EPOLLOUT); + PyModule_AddIntConstant(m, "EPOLLPRI", EPOLLPRI); + PyModule_AddIntConstant(m, "EPOLLERR", EPOLLERR); + PyModule_AddIntConstant(m, "EPOLLHUP", EPOLLHUP); + PyModule_AddIntConstant(m, "EPOLLET", EPOLLET); #ifdef EPOLLONESHOT - /* Kernel 2.6.2+ */ - PyModule_AddIntConstant(m, "EPOLLONESHOT", EPOLLONESHOT); + /* Kernel 2.6.2+ */ + PyModule_AddIntConstant(m, "EPOLLONESHOT", EPOLLONESHOT); #endif - /* PyModule_AddIntConstant(m, "EPOLL_RDHUP", EPOLLRDHUP); */ - PyModule_AddIntConstant(m, "EPOLLRDNORM", EPOLLRDNORM); - PyModule_AddIntConstant(m, "EPOLLRDBAND", EPOLLRDBAND); - PyModule_AddIntConstant(m, "EPOLLWRNORM", EPOLLWRNORM); - PyModule_AddIntConstant(m, "EPOLLWRBAND", EPOLLWRBAND); - PyModule_AddIntConstant(m, "EPOLLMSG", EPOLLMSG); + /* PyModule_AddIntConstant(m, "EPOLL_RDHUP", EPOLLRDHUP); */ + PyModule_AddIntConstant(m, "EPOLLRDNORM", EPOLLRDNORM); + PyModule_AddIntConstant(m, "EPOLLRDBAND", EPOLLRDBAND); + PyModule_AddIntConstant(m, "EPOLLWRNORM", EPOLLWRNORM); + PyModule_AddIntConstant(m, "EPOLLWRBAND", EPOLLWRBAND); + PyModule_AddIntConstant(m, "EPOLLMSG", EPOLLMSG); #endif /* HAVE_EPOLL */ #ifdef HAVE_KQUEUE - kqueue_event_Type.tp_new = PyType_GenericNew; - Py_TYPE(&kqueue_event_Type) = &PyType_Type; - if(PyType_Ready(&kqueue_event_Type) < 0) - return NULL; - - Py_INCREF(&kqueue_event_Type); - PyModule_AddObject(m, "kevent", (PyObject *)&kqueue_event_Type); - - Py_TYPE(&kqueue_queue_Type) = &PyType_Type; - if(PyType_Ready(&kqueue_queue_Type) < 0) - return NULL; - Py_INCREF(&kqueue_queue_Type); - PyModule_AddObject(m, "kqueue", (PyObject *)&kqueue_queue_Type); - - /* event filters */ - PyModule_AddIntConstant(m, "KQ_FILTER_READ", EVFILT_READ); - PyModule_AddIntConstant(m, "KQ_FILTER_WRITE", EVFILT_WRITE); - PyModule_AddIntConstant(m, "KQ_FILTER_AIO", EVFILT_AIO); - PyModule_AddIntConstant(m, "KQ_FILTER_VNODE", EVFILT_VNODE); - PyModule_AddIntConstant(m, "KQ_FILTER_PROC", EVFILT_PROC); + kqueue_event_Type.tp_new = PyType_GenericNew; + Py_TYPE(&kqueue_event_Type) = &PyType_Type; + if(PyType_Ready(&kqueue_event_Type) < 0) + return NULL; + + Py_INCREF(&kqueue_event_Type); + PyModule_AddObject(m, "kevent", (PyObject *)&kqueue_event_Type); + + Py_TYPE(&kqueue_queue_Type) = &PyType_Type; + if(PyType_Ready(&kqueue_queue_Type) < 0) + return NULL; + Py_INCREF(&kqueue_queue_Type); + PyModule_AddObject(m, "kqueue", (PyObject *)&kqueue_queue_Type); + + /* event filters */ + PyModule_AddIntConstant(m, "KQ_FILTER_READ", EVFILT_READ); + PyModule_AddIntConstant(m, "KQ_FILTER_WRITE", EVFILT_WRITE); + PyModule_AddIntConstant(m, "KQ_FILTER_AIO", EVFILT_AIO); + PyModule_AddIntConstant(m, "KQ_FILTER_VNODE", EVFILT_VNODE); + PyModule_AddIntConstant(m, "KQ_FILTER_PROC", EVFILT_PROC); #ifdef EVFILT_NETDEV - PyModule_AddIntConstant(m, "KQ_FILTER_NETDEV", EVFILT_NETDEV); + PyModule_AddIntConstant(m, "KQ_FILTER_NETDEV", EVFILT_NETDEV); #endif - PyModule_AddIntConstant(m, "KQ_FILTER_SIGNAL", EVFILT_SIGNAL); - PyModule_AddIntConstant(m, "KQ_FILTER_TIMER", EVFILT_TIMER); + PyModule_AddIntConstant(m, "KQ_FILTER_SIGNAL", EVFILT_SIGNAL); + PyModule_AddIntConstant(m, "KQ_FILTER_TIMER", EVFILT_TIMER); - /* event flags */ - PyModule_AddIntConstant(m, "KQ_EV_ADD", EV_ADD); - PyModule_AddIntConstant(m, "KQ_EV_DELETE", EV_DELETE); - PyModule_AddIntConstant(m, "KQ_EV_ENABLE", EV_ENABLE); - PyModule_AddIntConstant(m, "KQ_EV_DISABLE", EV_DISABLE); - PyModule_AddIntConstant(m, "KQ_EV_ONESHOT", EV_ONESHOT); - PyModule_AddIntConstant(m, "KQ_EV_CLEAR", EV_CLEAR); - - PyModule_AddIntConstant(m, "KQ_EV_SYSFLAGS", EV_SYSFLAGS); - PyModule_AddIntConstant(m, "KQ_EV_FLAG1", EV_FLAG1); - - PyModule_AddIntConstant(m, "KQ_EV_EOF", EV_EOF); - PyModule_AddIntConstant(m, "KQ_EV_ERROR", EV_ERROR); - - /* READ WRITE filter flag */ - PyModule_AddIntConstant(m, "KQ_NOTE_LOWAT", NOTE_LOWAT); - - /* VNODE filter flags */ - PyModule_AddIntConstant(m, "KQ_NOTE_DELETE", NOTE_DELETE); - PyModule_AddIntConstant(m, "KQ_NOTE_WRITE", NOTE_WRITE); - PyModule_AddIntConstant(m, "KQ_NOTE_EXTEND", NOTE_EXTEND); - PyModule_AddIntConstant(m, "KQ_NOTE_ATTRIB", NOTE_ATTRIB); - PyModule_AddIntConstant(m, "KQ_NOTE_LINK", NOTE_LINK); - PyModule_AddIntConstant(m, "KQ_NOTE_RENAME", NOTE_RENAME); - PyModule_AddIntConstant(m, "KQ_NOTE_REVOKE", NOTE_REVOKE); - - /* PROC filter flags */ - PyModule_AddIntConstant(m, "KQ_NOTE_EXIT", NOTE_EXIT); - PyModule_AddIntConstant(m, "KQ_NOTE_FORK", NOTE_FORK); - PyModule_AddIntConstant(m, "KQ_NOTE_EXEC", NOTE_EXEC); - PyModule_AddIntConstant(m, "KQ_NOTE_PCTRLMASK", NOTE_PCTRLMASK); - PyModule_AddIntConstant(m, "KQ_NOTE_PDATAMASK", NOTE_PDATAMASK); - - PyModule_AddIntConstant(m, "KQ_NOTE_TRACK", NOTE_TRACK); - PyModule_AddIntConstant(m, "KQ_NOTE_CHILD", NOTE_CHILD); - PyModule_AddIntConstant(m, "KQ_NOTE_TRACKERR", NOTE_TRACKERR); + /* event flags */ + PyModule_AddIntConstant(m, "KQ_EV_ADD", EV_ADD); + PyModule_AddIntConstant(m, "KQ_EV_DELETE", EV_DELETE); + PyModule_AddIntConstant(m, "KQ_EV_ENABLE", EV_ENABLE); + PyModule_AddIntConstant(m, "KQ_EV_DISABLE", EV_DISABLE); + PyModule_AddIntConstant(m, "KQ_EV_ONESHOT", EV_ONESHOT); + PyModule_AddIntConstant(m, "KQ_EV_CLEAR", EV_CLEAR); + + PyModule_AddIntConstant(m, "KQ_EV_SYSFLAGS", EV_SYSFLAGS); + PyModule_AddIntConstant(m, "KQ_EV_FLAG1", EV_FLAG1); + + PyModule_AddIntConstant(m, "KQ_EV_EOF", EV_EOF); + PyModule_AddIntConstant(m, "KQ_EV_ERROR", EV_ERROR); + + /* READ WRITE filter flag */ + PyModule_AddIntConstant(m, "KQ_NOTE_LOWAT", NOTE_LOWAT); + + /* VNODE filter flags */ + PyModule_AddIntConstant(m, "KQ_NOTE_DELETE", NOTE_DELETE); + PyModule_AddIntConstant(m, "KQ_NOTE_WRITE", NOTE_WRITE); + PyModule_AddIntConstant(m, "KQ_NOTE_EXTEND", NOTE_EXTEND); + PyModule_AddIntConstant(m, "KQ_NOTE_ATTRIB", NOTE_ATTRIB); + PyModule_AddIntConstant(m, "KQ_NOTE_LINK", NOTE_LINK); + PyModule_AddIntConstant(m, "KQ_NOTE_RENAME", NOTE_RENAME); + PyModule_AddIntConstant(m, "KQ_NOTE_REVOKE", NOTE_REVOKE); + + /* PROC filter flags */ + PyModule_AddIntConstant(m, "KQ_NOTE_EXIT", NOTE_EXIT); + PyModule_AddIntConstant(m, "KQ_NOTE_FORK", NOTE_FORK); + PyModule_AddIntConstant(m, "KQ_NOTE_EXEC", NOTE_EXEC); + PyModule_AddIntConstant(m, "KQ_NOTE_PCTRLMASK", NOTE_PCTRLMASK); + PyModule_AddIntConstant(m, "KQ_NOTE_PDATAMASK", NOTE_PDATAMASK); + + PyModule_AddIntConstant(m, "KQ_NOTE_TRACK", NOTE_TRACK); + PyModule_AddIntConstant(m, "KQ_NOTE_CHILD", NOTE_CHILD); + PyModule_AddIntConstant(m, "KQ_NOTE_TRACKERR", NOTE_TRACKERR); - /* NETDEV filter flags */ + /* NETDEV filter flags */ #ifdef EVFILT_NETDEV - PyModule_AddIntConstant(m, "KQ_NOTE_LINKUP", NOTE_LINKUP); - PyModule_AddIntConstant(m, "KQ_NOTE_LINKDOWN", NOTE_LINKDOWN); - PyModule_AddIntConstant(m, "KQ_NOTE_LINKINV", NOTE_LINKINV); + PyModule_AddIntConstant(m, "KQ_NOTE_LINKUP", NOTE_LINKUP); + PyModule_AddIntConstant(m, "KQ_NOTE_LINKDOWN", NOTE_LINKDOWN); + PyModule_AddIntConstant(m, "KQ_NOTE_LINKINV", NOTE_LINKINV); #endif #endif /* HAVE_KQUEUE */ - return m; + return m; } Modified: python/branches/py3k-jit/Modules/sha1module.c ============================================================================== --- python/branches/py3k-jit/Modules/sha1module.c (original) +++ python/branches/py3k-jit/Modules/sha1module.c Mon May 10 23:55:43 2010 @@ -23,8 +23,8 @@ /* Some useful types */ #if SIZEOF_INT == 4 -typedef unsigned int SHA1_INT32; /* 32-bit integer */ -typedef PY_LONG_LONG SHA1_INT64; /* 64-bit integer */ +typedef unsigned int SHA1_INT32; /* 32-bit integer */ +typedef PY_LONG_LONG SHA1_INT64; /* 64-bit integer */ #else /* not defined. compilation will die. */ #endif @@ -122,7 +122,7 @@ /* expand it */ for (i = 16; i < 80; i++) { - W[i] = ROL(W[i-3] ^ W[i-8] ^ W[i-14] ^ W[i-16], 1); + W[i] = ROL(W[i-3] ^ W[i-8] ^ W[i-14] ^ W[i-16], 1); } /* compress */ @@ -131,7 +131,7 @@ #define FF1(a,b,c,d,e,i) e = (ROLc(a, 5) + F1(b,c,d) + e + W[i] + 0x6ed9eba1UL); b = ROLc(b, 30); #define FF2(a,b,c,d,e,i) e = (ROLc(a, 5) + F2(b,c,d) + e + W[i] + 0x8f1bbcdcUL); b = ROLc(b, 30); #define FF3(a,b,c,d,e,i) e = (ROLc(a, 5) + F3(b,c,d) + e + W[i] + 0xca62c1d6UL); b = ROLc(b, 30); - + for (i = 0; i < 20; ) { FF0(a,b,c,d,e,i++); FF0(e,a,b,c,d,i++); @@ -141,7 +141,7 @@ } /* round two */ - for (; i < 40; ) { + for (; i < 40; ) { FF1(a,b,c,d,e,i++); FF1(e,a,b,c,d,i++); FF1(d,e,a,b,c,i++); @@ -150,7 +150,7 @@ } /* round three */ - for (; i < 60; ) { + for (; i < 60; ) { FF2(a,b,c,d,e,i++); FF2(e,a,b,c,d,i++); FF2(d,e,a,b,c,i++); @@ -159,7 +159,7 @@ } /* round four */ - for (; i < 80; ) { + for (; i < 80; ) { FF3(a,b,c,d,e,i++); FF3(e,a,b,c,d,i++); FF3(d,e,a,b,c,i++); @@ -362,21 +362,21 @@ /* Create a new string */ retval = PyUnicode_FromStringAndSize(NULL, SHA1_DIGESTSIZE * 2); if (!retval) - return NULL; + return NULL; hex_digest = PyUnicode_AS_UNICODE(retval); if (!hex_digest) { - Py_DECREF(retval); - return NULL; + Py_DECREF(retval); + return NULL; } /* Make hex version of the digest */ for(i=j=0; i> 4) & 0xf; - c = (c>9) ? c+'a'-10 : c + '0'; + c = (c>9) ? c+'a'-10 : c + '0'; hex_digest[j++] = c; c = (digest[i] & 0xf); - c = (c>9) ? c+'a'-10 : c + '0'; + c = (c>9) ? c+'a'-10 : c + '0'; hex_digest[j++] = c; } return retval; @@ -404,11 +404,11 @@ } static PyMethodDef SHA1_methods[] = { - {"copy", (PyCFunction)SHA1_copy, METH_NOARGS, SHA1_copy__doc__}, - {"digest", (PyCFunction)SHA1_digest, METH_NOARGS, SHA1_digest__doc__}, + {"copy", (PyCFunction)SHA1_copy, METH_NOARGS, SHA1_copy__doc__}, + {"digest", (PyCFunction)SHA1_digest, METH_NOARGS, SHA1_digest__doc__}, {"hexdigest", (PyCFunction)SHA1_hexdigest, METH_NOARGS, SHA1_hexdigest__doc__}, - {"update", (PyCFunction)SHA1_update, METH_VARARGS, SHA1_update__doc__}, - {NULL, NULL} /* sentinel */ + {"update", (PyCFunction)SHA1_update, METH_VARARGS, SHA1_update__doc__}, + {NULL, NULL} /* sentinel */ }; static PyObject * @@ -448,13 +448,13 @@ static PyTypeObject SHA1type = { PyVarObject_HEAD_INIT(NULL, 0) - "_sha1.sha1", /*tp_name*/ - sizeof(SHA1object), /*tp_size*/ - 0, /*tp_itemsize*/ + "_sha1.sha1", /*tp_name*/ + sizeof(SHA1object), /*tp_size*/ + 0, /*tp_itemsize*/ /* methods */ - SHA1_dealloc, /*tp_dealloc*/ - 0, /*tp_print*/ - 0, /*tp_getattr*/ + SHA1_dealloc, /*tp_dealloc*/ + 0, /*tp_print*/ + 0, /*tp_getattr*/ 0, /*tp_setattr*/ 0, /*tp_reserved*/ 0, /*tp_repr*/ @@ -470,13 +470,13 @@ Py_TPFLAGS_DEFAULT, /*tp_flags*/ 0, /*tp_doc*/ 0, /*tp_traverse*/ - 0, /*tp_clear*/ - 0, /*tp_richcompare*/ - 0, /*tp_weaklistoffset*/ - 0, /*tp_iter*/ - 0, /*tp_iternext*/ - SHA1_methods, /* tp_methods */ - NULL, /* tp_members */ + 0, /*tp_clear*/ + 0, /*tp_richcompare*/ + 0, /*tp_weaklistoffset*/ + 0, /*tp_iter*/ + 0, /*tp_iternext*/ + SHA1_methods, /* tp_methods */ + NULL, /* tp_members */ SHA1_getseters, /* tp_getset */ }; @@ -529,7 +529,7 @@ static struct PyMethodDef SHA1_functions[] = { {"sha1",(PyCFunction)SHA1_new, METH_VARARGS|METH_KEYWORDS,SHA1_new__doc__}, - {NULL, NULL} /* Sentinel */ + {NULL, NULL} /* Sentinel */ }; @@ -539,15 +539,15 @@ static struct PyModuleDef _sha1module = { - PyModuleDef_HEAD_INIT, - "_sha1", - NULL, - -1, - SHA1_functions, - NULL, - NULL, - NULL, - NULL + PyModuleDef_HEAD_INIT, + "_sha1", + NULL, + -1, + SHA1_functions, + NULL, + NULL, + NULL, + NULL }; PyMODINIT_FUNC Modified: python/branches/py3k-jit/Modules/sha256module.c ============================================================================== --- python/branches/py3k-jit/Modules/sha256module.c (original) +++ python/branches/py3k-jit/Modules/sha256module.c Mon May 10 23:55:43 2010 @@ -23,7 +23,7 @@ /* Endianness testing and definitions */ #define TestEndianness(variable) {int i=1; variable=PCT_BIG_ENDIAN;\ - if (*((char*)&i)==1) variable=PCT_LITTLE_ENDIAN;} + if (*((char*)&i)==1) variable=PCT_LITTLE_ENDIAN;} #define PCT_LITTLE_ENDIAN 1 #define PCT_BIG_ENDIAN 0 @@ -33,7 +33,7 @@ typedef unsigned char SHA_BYTE; #if SIZEOF_INT == 4 -typedef unsigned int SHA_INT32; /* 32-bit integer */ +typedef unsigned int SHA_INT32; /* 32-bit integer */ #else /* not defined. compilation will die. */ #endif @@ -47,11 +47,11 @@ typedef struct { PyObject_HEAD - SHA_INT32 digest[8]; /* Message digest */ - SHA_INT32 count_lo, count_hi; /* 64-bit bit count */ - SHA_BYTE data[SHA_BLOCKSIZE]; /* SHA data buffer */ + SHA_INT32 digest[8]; /* Message digest */ + SHA_INT32 count_lo, count_hi; /* 64-bit bit count */ + SHA_BYTE data[SHA_BLOCKSIZE]; /* SHA data buffer */ int Endianness; - int local; /* unprocessed amount in data */ + int local; /* unprocessed amount in data */ int digestsize; } SHAobject; @@ -63,7 +63,7 @@ SHA_INT32 value; if ( Endianness == PCT_BIG_ENDIAN ) - return; + return; byteCount /= sizeof(*buffer); while (byteCount--) { @@ -115,7 +115,7 @@ ( ((((unsigned long)(x)&0xFFFFFFFFUL)>>(unsigned long)((y)&31)) | \ ((unsigned long)(x)<<(unsigned long)(32-((y)&31)))) & 0xFFFFFFFFUL) #define Ch(x,y,z) (z ^ (x & (y ^ z))) -#define Maj(x,y,z) (((x | y) & z) | (x & y)) +#define Maj(x,y,z) (((x | y) & z) | (x & y)) #define S(x, n) ROR((x),(n)) #define R(x, n) (((x)&0xFFFFFFFFUL)>>(n)) #define Sigma0(x) (S(x, 2) ^ S(x, 13) ^ S(x, 22)) @@ -128,13 +128,13 @@ sha_transform(SHAobject *sha_info) { int i; - SHA_INT32 S[8], W[64], t0, t1; + SHA_INT32 S[8], W[64], t0, t1; memcpy(W, sha_info->data, sizeof(sha_info->data)); longReverse(W, (int)sizeof(sha_info->data), sha_info->Endianness); for (i = 16; i < 64; ++i) { - W[i] = Gamma1(W[i - 2]) + W[i - 7] + Gamma0(W[i - 15]) + W[i - 16]; + W[i] = Gamma1(W[i - 2]) + W[i - 7] + Gamma0(W[i - 15]) + W[i - 16]; } for (i = 0; i < 8; ++i) { S[i] = sha_info->digest[i]; @@ -212,8 +212,8 @@ RND(S[2],S[3],S[4],S[5],S[6],S[7],S[0],S[1],62,0xbef9a3f7); RND(S[1],S[2],S[3],S[4],S[5],S[6],S[7],S[0],63,0xc67178f2); -#undef RND - +#undef RND + /* feedback */ for (i = 0; i < 8; i++) { sha_info->digest[i] = sha_info->digest[i] + S[i]; @@ -315,14 +315,14 @@ count = (int) ((lo_bit_count >> 3) & 0x3f); ((SHA_BYTE *) sha_info->data)[count++] = 0x80; if (count > SHA_BLOCKSIZE - 8) { - memset(((SHA_BYTE *) sha_info->data) + count, 0, - SHA_BLOCKSIZE - count); - sha_transform(sha_info); - memset((SHA_BYTE *) sha_info->data, 0, SHA_BLOCKSIZE - 8); + memset(((SHA_BYTE *) sha_info->data) + count, 0, + SHA_BLOCKSIZE - count); + sha_transform(sha_info); + memset((SHA_BYTE *) sha_info->data, 0, SHA_BLOCKSIZE - 8); } else { - memset(((SHA_BYTE *) sha_info->data) + count, 0, - SHA_BLOCKSIZE - 8 - count); + memset(((SHA_BYTE *) sha_info->data) + count, 0, + SHA_BLOCKSIZE - 8 - count); } /* GJS: note that we add the hi/lo in big-endian. sha_transform will @@ -455,21 +455,21 @@ /* Create a new string */ retval = PyUnicode_FromStringAndSize(NULL, self->digestsize * 2); if (!retval) - return NULL; + return NULL; hex_digest = PyUnicode_AS_UNICODE(retval); if (!hex_digest) { - Py_DECREF(retval); - return NULL; + Py_DECREF(retval); + return NULL; } /* Make hex version of the digest */ for(i=j=0; idigestsize; i++) { char c; c = (digest[i] >> 4) & 0xf; - c = (c>9) ? c+'a'-10 : c + '0'; + c = (c>9) ? c+'a'-10 : c + '0'; hex_digest[j++] = c; c = (digest[i] & 0xf); - c = (c>9) ? c+'a'-10 : c + '0'; + c = (c>9) ? c+'a'-10 : c + '0'; hex_digest[j++] = c; } return retval; @@ -497,11 +497,11 @@ } static PyMethodDef SHA_methods[] = { - {"copy", (PyCFunction)SHA256_copy, METH_NOARGS, SHA256_copy__doc__}, - {"digest", (PyCFunction)SHA256_digest, METH_NOARGS, SHA256_digest__doc__}, + {"copy", (PyCFunction)SHA256_copy, METH_NOARGS, SHA256_copy__doc__}, + {"digest", (PyCFunction)SHA256_digest, METH_NOARGS, SHA256_digest__doc__}, {"hexdigest", (PyCFunction)SHA256_hexdigest, METH_NOARGS, SHA256_hexdigest__doc__}, - {"update", (PyCFunction)SHA256_update, METH_VARARGS, SHA256_update__doc__}, - {NULL, NULL} /* sentinel */ + {"update", (PyCFunction)SHA256_update, METH_VARARGS, SHA256_update__doc__}, + {NULL, NULL} /* sentinel */ }; static PyObject * @@ -538,13 +538,13 @@ static PyTypeObject SHA224type = { PyVarObject_HEAD_INIT(NULL, 0) - "_sha256.sha224", /*tp_name*/ - sizeof(SHAobject), /*tp_size*/ - 0, /*tp_itemsize*/ + "_sha256.sha224", /*tp_name*/ + sizeof(SHAobject), /*tp_size*/ + 0, /*tp_itemsize*/ /* methods */ - SHA_dealloc, /*tp_dealloc*/ - 0, /*tp_print*/ - 0, /*tp_getattr*/ + SHA_dealloc, /*tp_dealloc*/ + 0, /*tp_print*/ + 0, /*tp_getattr*/ 0, /*tp_setattr*/ 0, /*tp_reserved*/ 0, /*tp_repr*/ @@ -560,25 +560,25 @@ Py_TPFLAGS_DEFAULT, /*tp_flags*/ 0, /*tp_doc*/ 0, /*tp_traverse*/ - 0, /*tp_clear*/ - 0, /*tp_richcompare*/ - 0, /*tp_weaklistoffset*/ - 0, /*tp_iter*/ - 0, /*tp_iternext*/ - SHA_methods, /* tp_methods */ - SHA_members, /* tp_members */ + 0, /*tp_clear*/ + 0, /*tp_richcompare*/ + 0, /*tp_weaklistoffset*/ + 0, /*tp_iter*/ + 0, /*tp_iternext*/ + SHA_methods, /* tp_methods */ + SHA_members, /* tp_members */ SHA_getseters, /* tp_getset */ }; static PyTypeObject SHA256type = { PyVarObject_HEAD_INIT(NULL, 0) - "_sha256.sha256", /*tp_name*/ - sizeof(SHAobject), /*tp_size*/ - 0, /*tp_itemsize*/ + "_sha256.sha256", /*tp_name*/ + sizeof(SHAobject), /*tp_size*/ + 0, /*tp_itemsize*/ /* methods */ - SHA_dealloc, /*tp_dealloc*/ - 0, /*tp_print*/ - 0, /*tp_getattr*/ + SHA_dealloc, /*tp_dealloc*/ + 0, /*tp_print*/ + 0, /*tp_getattr*/ 0, /*tp_setattr*/ 0, /*tp_reserved*/ 0, /*tp_repr*/ @@ -594,13 +594,13 @@ Py_TPFLAGS_DEFAULT, /*tp_flags*/ 0, /*tp_doc*/ 0, /*tp_traverse*/ - 0, /*tp_clear*/ - 0, /*tp_richcompare*/ - 0, /*tp_weaklistoffset*/ - 0, /*tp_iter*/ - 0, /*tp_iternext*/ - SHA_methods, /* tp_methods */ - SHA_members, /* tp_members */ + 0, /*tp_clear*/ + 0, /*tp_richcompare*/ + 0, /*tp_weaklistoffset*/ + 0, /*tp_iter*/ + 0, /*tp_iternext*/ + SHA_methods, /* tp_methods */ + SHA_members, /* tp_members */ SHA_getseters, /* tp_getset */ }; @@ -695,7 +695,7 @@ static struct PyMethodDef SHA_functions[] = { {"sha256", (PyCFunction)SHA256_new, METH_VARARGS|METH_KEYWORDS, SHA256_new__doc__}, {"sha224", (PyCFunction)SHA224_new, METH_VARARGS|METH_KEYWORDS, SHA224_new__doc__}, - {NULL, NULL} /* Sentinel */ + {NULL, NULL} /* Sentinel */ }; @@ -705,15 +705,15 @@ static struct PyModuleDef _sha256module = { - PyModuleDef_HEAD_INIT, - "_sha256", - NULL, - -1, - SHA_functions, - NULL, - NULL, - NULL, - NULL + PyModuleDef_HEAD_INIT, + "_sha256", + NULL, + -1, + SHA_functions, + NULL, + NULL, + NULL, + NULL }; PyMODINIT_FUNC Modified: python/branches/py3k-jit/Modules/sha512module.c ============================================================================== --- python/branches/py3k-jit/Modules/sha512module.c (original) +++ python/branches/py3k-jit/Modules/sha512module.c Mon May 10 23:55:43 2010 @@ -24,7 +24,7 @@ /* Endianness testing and definitions */ #define TestEndianness(variable) {int i=1; variable=PCT_BIG_ENDIAN;\ - if (*((char*)&i)==1) variable=PCT_LITTLE_ENDIAN;} + if (*((char*)&i)==1) variable=PCT_LITTLE_ENDIAN;} #define PCT_LITTLE_ENDIAN 1 #define PCT_BIG_ENDIAN 0 @@ -34,8 +34,8 @@ typedef unsigned char SHA_BYTE; #if SIZEOF_INT == 4 -typedef unsigned int SHA_INT32; /* 32-bit integer */ -typedef unsigned PY_LONG_LONG SHA_INT64; /* 64-bit integer */ +typedef unsigned int SHA_INT32; /* 32-bit integer */ +typedef unsigned PY_LONG_LONG SHA_INT64; /* 64-bit integer */ #else /* not defined. compilation will die. */ #endif @@ -49,11 +49,11 @@ typedef struct { PyObject_HEAD - SHA_INT64 digest[8]; /* Message digest */ - SHA_INT32 count_lo, count_hi; /* 64-bit bit count */ - SHA_BYTE data[SHA_BLOCKSIZE]; /* SHA data buffer */ + SHA_INT64 digest[8]; /* Message digest */ + SHA_INT32 count_lo, count_hi; /* 64-bit bit count */ + SHA_BYTE data[SHA_BLOCKSIZE]; /* SHA data buffer */ int Endianness; - int local; /* unprocessed amount in data */ + int local; /* unprocessed amount in data */ int digestsize; } SHAobject; @@ -65,22 +65,22 @@ SHA_INT64 value; if ( Endianness == PCT_BIG_ENDIAN ) - return; + return; byteCount /= sizeof(*buffer); while (byteCount--) { value = *buffer; - ((unsigned char*)buffer)[0] = (unsigned char)(value >> 56) & 0xff; - ((unsigned char*)buffer)[1] = (unsigned char)(value >> 48) & 0xff; - ((unsigned char*)buffer)[2] = (unsigned char)(value >> 40) & 0xff; - ((unsigned char*)buffer)[3] = (unsigned char)(value >> 32) & 0xff; - ((unsigned char*)buffer)[4] = (unsigned char)(value >> 24) & 0xff; - ((unsigned char*)buffer)[5] = (unsigned char)(value >> 16) & 0xff; - ((unsigned char*)buffer)[6] = (unsigned char)(value >> 8) & 0xff; - ((unsigned char*)buffer)[7] = (unsigned char)(value ) & 0xff; - - buffer++; + ((unsigned char*)buffer)[0] = (unsigned char)(value >> 56) & 0xff; + ((unsigned char*)buffer)[1] = (unsigned char)(value >> 48) & 0xff; + ((unsigned char*)buffer)[2] = (unsigned char)(value >> 40) & 0xff; + ((unsigned char*)buffer)[3] = (unsigned char)(value >> 32) & 0xff; + ((unsigned char*)buffer)[4] = (unsigned char)(value >> 24) & 0xff; + ((unsigned char*)buffer)[5] = (unsigned char)(value >> 16) & 0xff; + ((unsigned char*)buffer)[6] = (unsigned char)(value >> 8) & 0xff; + ((unsigned char*)buffer)[7] = (unsigned char)(value ) & 0xff; + + buffer++; } } @@ -125,7 +125,7 @@ ( ((((x) & Py_ULL(0xFFFFFFFFFFFFFFFF))>>((unsigned PY_LONG_LONG)(y) & 63)) | \ ((x)<<((unsigned PY_LONG_LONG)(64-((y) & 63))))) & Py_ULL(0xFFFFFFFFFFFFFFFF)) #define Ch(x,y,z) (z ^ (x & (y ^ z))) -#define Maj(x,y,z) (((x | y) & z) | (x & y)) +#define Maj(x,y,z) (((x | y) & z) | (x & y)) #define S(x, n) ROR64((x),(n)) #define R(x, n) (((x) & Py_ULL(0xFFFFFFFFFFFFFFFF)) >> ((unsigned PY_LONG_LONG)n)) #define Sigma0(x) (S(x, 28) ^ S(x, 34) ^ S(x, 39)) @@ -144,7 +144,7 @@ longReverse(W, (int)sizeof(sha_info->data), sha_info->Endianness); for (i = 16; i < 80; ++i) { - W[i] = Gamma1(W[i - 2]) + W[i - 7] + Gamma0(W[i - 15]) + W[i - 16]; + W[i] = Gamma1(W[i - 2]) + W[i - 7] + Gamma0(W[i - 15]) + W[i - 16]; } for (i = 0; i < 8; ++i) { S[i] = sha_info->digest[i]; @@ -238,8 +238,8 @@ RND(S[2],S[3],S[4],S[5],S[6],S[7],S[0],S[1],78,Py_ULL(0x5fcb6fab3ad6faec)); RND(S[1],S[2],S[3],S[4],S[5],S[6],S[7],S[0],79,Py_ULL(0x6c44198c4a475817)); -#undef RND - +#undef RND + /* feedback */ for (i = 0; i < 8; i++) { sha_info->digest[i] = sha_info->digest[i] + S[i]; @@ -341,14 +341,14 @@ count = (int) ((lo_bit_count >> 3) & 0x7f); ((SHA_BYTE *) sha_info->data)[count++] = 0x80; if (count > SHA_BLOCKSIZE - 16) { - memset(((SHA_BYTE *) sha_info->data) + count, 0, - SHA_BLOCKSIZE - count); - sha512_transform(sha_info); - memset((SHA_BYTE *) sha_info->data, 0, SHA_BLOCKSIZE - 16); + memset(((SHA_BYTE *) sha_info->data) + count, 0, + SHA_BLOCKSIZE - count); + sha512_transform(sha_info); + memset((SHA_BYTE *) sha_info->data, 0, SHA_BLOCKSIZE - 16); } else { - memset(((SHA_BYTE *) sha_info->data) + count, 0, - SHA_BLOCKSIZE - 16 - count); + memset(((SHA_BYTE *) sha_info->data) + count, 0, + SHA_BLOCKSIZE - 16 - count); } /* GJS: note that we add the hi/lo in big-endian. sha512_transform will @@ -521,21 +521,21 @@ /* Create a new string */ retval = PyUnicode_FromStringAndSize(NULL, self->digestsize * 2); if (!retval) - return NULL; + return NULL; hex_digest = PyUnicode_AS_UNICODE(retval); if (!hex_digest) { - Py_DECREF(retval); - return NULL; + Py_DECREF(retval); + return NULL; } /* Make hex version of the digest */ for (i=j=0; idigestsize; i++) { char c; c = (digest[i] >> 4) & 0xf; - c = (c>9) ? c+'a'-10 : c + '0'; + c = (c>9) ? c+'a'-10 : c + '0'; hex_digest[j++] = c; c = (digest[i] & 0xf); - c = (c>9) ? c+'a'-10 : c + '0'; + c = (c>9) ? c+'a'-10 : c + '0'; hex_digest[j++] = c; } return retval; @@ -563,11 +563,11 @@ } static PyMethodDef SHA_methods[] = { - {"copy", (PyCFunction)SHA512_copy, METH_NOARGS, SHA512_copy__doc__}, - {"digest", (PyCFunction)SHA512_digest, METH_NOARGS, SHA512_digest__doc__}, + {"copy", (PyCFunction)SHA512_copy, METH_NOARGS, SHA512_copy__doc__}, + {"digest", (PyCFunction)SHA512_digest, METH_NOARGS, SHA512_digest__doc__}, {"hexdigest", (PyCFunction)SHA512_hexdigest, METH_NOARGS, SHA512_hexdigest__doc__}, - {"update", (PyCFunction)SHA512_update, METH_VARARGS, SHA512_update__doc__}, - {NULL, NULL} /* sentinel */ + {"update", (PyCFunction)SHA512_update, METH_VARARGS, SHA512_update__doc__}, + {NULL, NULL} /* sentinel */ }; static PyObject * @@ -604,13 +604,13 @@ static PyTypeObject SHA384type = { PyVarObject_HEAD_INIT(NULL, 0) - "_sha512.sha384", /*tp_name*/ - sizeof(SHAobject), /*tp_size*/ - 0, /*tp_itemsize*/ + "_sha512.sha384", /*tp_name*/ + sizeof(SHAobject), /*tp_size*/ + 0, /*tp_itemsize*/ /* methods */ - SHA512_dealloc, /*tp_dealloc*/ - 0, /*tp_print*/ - 0, /*tp_getattr*/ + SHA512_dealloc, /*tp_dealloc*/ + 0, /*tp_print*/ + 0, /*tp_getattr*/ 0, /*tp_setattr*/ 0, /*tp_reserved*/ 0, /*tp_repr*/ @@ -626,25 +626,25 @@ Py_TPFLAGS_DEFAULT, /*tp_flags*/ 0, /*tp_doc*/ 0, /*tp_traverse*/ - 0, /*tp_clear*/ - 0, /*tp_richcompare*/ - 0, /*tp_weaklistoffset*/ - 0, /*tp_iter*/ - 0, /*tp_iternext*/ - SHA_methods, /* tp_methods */ - SHA_members, /* tp_members */ + 0, /*tp_clear*/ + 0, /*tp_richcompare*/ + 0, /*tp_weaklistoffset*/ + 0, /*tp_iter*/ + 0, /*tp_iternext*/ + SHA_methods, /* tp_methods */ + SHA_members, /* tp_members */ SHA_getseters, /* tp_getset */ }; static PyTypeObject SHA512type = { PyVarObject_HEAD_INIT(NULL, 0) - "_sha512.sha512", /*tp_name*/ - sizeof(SHAobject), /*tp_size*/ - 0, /*tp_itemsize*/ + "_sha512.sha512", /*tp_name*/ + sizeof(SHAobject), /*tp_size*/ + 0, /*tp_itemsize*/ /* methods */ - SHA512_dealloc, /*tp_dealloc*/ - 0, /*tp_print*/ - 0, /*tp_getattr*/ + SHA512_dealloc, /*tp_dealloc*/ + 0, /*tp_print*/ + 0, /*tp_getattr*/ 0, /*tp_setattr*/ 0, /*tp_reserved*/ 0, /*tp_repr*/ @@ -660,13 +660,13 @@ Py_TPFLAGS_DEFAULT, /*tp_flags*/ 0, /*tp_doc*/ 0, /*tp_traverse*/ - 0, /*tp_clear*/ - 0, /*tp_richcompare*/ - 0, /*tp_weaklistoffset*/ - 0, /*tp_iter*/ - 0, /*tp_iternext*/ - SHA_methods, /* tp_methods */ - SHA_members, /* tp_members */ + 0, /*tp_clear*/ + 0, /*tp_richcompare*/ + 0, /*tp_weaklistoffset*/ + 0, /*tp_iter*/ + 0, /*tp_iternext*/ + SHA_methods, /* tp_methods */ + SHA_members, /* tp_members */ SHA_getseters, /* tp_getset */ }; @@ -761,7 +761,7 @@ static struct PyMethodDef SHA_functions[] = { {"sha512", (PyCFunction)SHA512_new, METH_VARARGS|METH_KEYWORDS, SHA512_new__doc__}, {"sha384", (PyCFunction)SHA384_new, METH_VARARGS|METH_KEYWORDS, SHA384_new__doc__}, - {NULL, NULL} /* Sentinel */ + {NULL, NULL} /* Sentinel */ }; @@ -771,15 +771,15 @@ static struct PyModuleDef _sha512module = { - PyModuleDef_HEAD_INIT, - "_sha512", - NULL, - -1, - SHA_functions, - NULL, - NULL, - NULL, - NULL + PyModuleDef_HEAD_INIT, + "_sha512", + NULL, + -1, + SHA_functions, + NULL, + NULL, + NULL, + NULL }; PyMODINIT_FUNC Modified: python/branches/py3k-jit/Modules/signalmodule.c ============================================================================== --- python/branches/py3k-jit/Modules/signalmodule.c (original) +++ python/branches/py3k-jit/Modules/signalmodule.c Mon May 10 23:55:43 2010 @@ -34,13 +34,13 @@ #ifndef NSIG # if defined(_NSIG) -# define NSIG _NSIG /* For BSD/SysV */ +# define NSIG _NSIG /* For BSD/SysV */ # elif defined(_SIGMAX) -# define NSIG (_SIGMAX + 1) /* For QNX */ +# define NSIG (_SIGMAX + 1) /* For QNX */ # elif defined(SIGMAX) -# define NSIG (SIGMAX + 1) /* For djgpp */ +# define NSIG (SIGMAX + 1) /* For djgpp */ # else -# define NSIG 64 /* Use a reasonable default value */ +# define NSIG 64 /* Use a reasonable default value */ # endif #endif @@ -82,8 +82,8 @@ #endif static struct { - int tripped; - PyObject *func; + int tripped; + PyObject *func; } Handlers[NSIG]; static sig_atomic_t wakeup_fd = -1; @@ -126,18 +126,18 @@ r = PyTuple_New(2); if (r == NULL) - return NULL; + return NULL; if(!(v = PyFloat_FromDouble(double_from_timeval(&iv->it_value)))) { - Py_DECREF(r); - return NULL; + Py_DECREF(r); + return NULL; } PyTuple_SET_ITEM(r, 0, v); if(!(v = PyFloat_FromDouble(double_from_timeval(&iv->it_interval)))) { - Py_DECREF(r); - return NULL; + Py_DECREF(r); + return NULL; } PyTuple_SET_ITEM(r, 1, v); @@ -149,8 +149,8 @@ static PyObject * signal_default_int_handler(PyObject *self, PyObject *args) { - PyErr_SetNone(PyExc_KeyboardInterrupt); - return NULL; + PyErr_SetNone(PyExc_KeyboardInterrupt); + return NULL; } PyDoc_STRVAR(default_int_handler_doc, @@ -163,7 +163,7 @@ static int checksignals_witharg(void * unused) { - return PyErr_CheckSignals(); + return PyErr_CheckSignals(); } static void @@ -171,38 +171,38 @@ { #ifdef WITH_THREAD #ifdef WITH_PTH - if (PyThread_get_thread_ident() != main_thread) { - pth_raise(*(pth_t *) main_thread, sig_num); - return; - } -#endif - /* See NOTES section above */ - if (getpid() == main_pid) { -#endif - Handlers[sig_num].tripped = 1; - /* Set is_tripped after setting .tripped, as it gets - cleared in PyErr_CheckSignals() before .tripped. */ - is_tripped = 1; - Py_AddPendingCall(checksignals_witharg, NULL); - if (wakeup_fd != -1) - write(wakeup_fd, "\0", 1); + if (PyThread_get_thread_ident() != main_thread) { + pth_raise(*(pth_t *) main_thread, sig_num); + return; + } +#endif + /* See NOTES section above */ + if (getpid() == main_pid) { +#endif + Handlers[sig_num].tripped = 1; + /* Set is_tripped after setting .tripped, as it gets + cleared in PyErr_CheckSignals() before .tripped. */ + is_tripped = 1; + Py_AddPendingCall(checksignals_witharg, NULL); + if (wakeup_fd != -1) + write(wakeup_fd, "\0", 1); #ifdef WITH_THREAD - } + } #endif #ifdef SIGCHLD - if (sig_num == SIGCHLD) { - /* To avoid infinite recursion, this signal remains - reset until explicit re-instated. - Don't clear the 'func' field as it is our pointer - to the Python handler... */ - return; - } + if (sig_num == SIGCHLD) { + /* To avoid infinite recursion, this signal remains + reset until explicit re-instated. + Don't clear the 'func' field as it is our pointer + to the Python handler... */ + return; + } #endif #ifndef HAVE_SIGACTION - /* If the handler was not set up with sigaction, reinstall it. See - * Python/pythonrun.c for the implementation of PyOS_setsig which - * makes this true. See also issue8354. */ - PyOS_setsig(sig_num, signal_handler); + /* If the handler was not set up with sigaction, reinstall it. See + * Python/pythonrun.c for the implementation of PyOS_setsig which + * makes this true. See also issue8354. */ + PyOS_setsig(sig_num, signal_handler); #endif } @@ -211,11 +211,11 @@ static PyObject * signal_alarm(PyObject *self, PyObject *args) { - int t; - if (!PyArg_ParseTuple(args, "i:alarm", &t)) - return NULL; - /* alarm() returns the number of seconds remaining */ - return PyLong_FromLong((long)alarm(t)); + int t; + if (!PyArg_ParseTuple(args, "i:alarm", &t)) + return NULL; + /* alarm() returns the number of seconds remaining */ + return PyLong_FromLong((long)alarm(t)); } PyDoc_STRVAR(alarm_doc, @@ -228,17 +228,17 @@ static PyObject * signal_pause(PyObject *self) { - Py_BEGIN_ALLOW_THREADS - (void)pause(); - Py_END_ALLOW_THREADS - /* make sure that any exceptions that got raised are propagated - * back into Python - */ - if (PyErr_CheckSignals()) - return NULL; + Py_BEGIN_ALLOW_THREADS + (void)pause(); + Py_END_ALLOW_THREADS + /* make sure that any exceptions that got raised are propagated + * back into Python + */ + if (PyErr_CheckSignals()) + return NULL; - Py_INCREF(Py_None); - return Py_None; + Py_INCREF(Py_None); + return Py_None; } PyDoc_STRVAR(pause_doc, "pause()\n\ @@ -251,44 +251,44 @@ static PyObject * signal_signal(PyObject *self, PyObject *args) { - PyObject *obj; - int sig_num; - PyObject *old_handler; - void (*func)(int); - if (!PyArg_ParseTuple(args, "iO:signal", &sig_num, &obj)) - return NULL; + PyObject *obj; + int sig_num; + PyObject *old_handler; + void (*func)(int); + if (!PyArg_ParseTuple(args, "iO:signal", &sig_num, &obj)) + return NULL; #ifdef WITH_THREAD - if (PyThread_get_thread_ident() != main_thread) { - PyErr_SetString(PyExc_ValueError, - "signal only works in main thread"); - return NULL; - } -#endif - if (sig_num < 1 || sig_num >= NSIG) { - PyErr_SetString(PyExc_ValueError, - "signal number out of range"); - return NULL; - } - if (obj == IgnoreHandler) - func = SIG_IGN; - else if (obj == DefaultHandler) - func = SIG_DFL; - else if (!PyCallable_Check(obj)) { - PyErr_SetString(PyExc_TypeError, + if (PyThread_get_thread_ident() != main_thread) { + PyErr_SetString(PyExc_ValueError, + "signal only works in main thread"); + return NULL; + } +#endif + if (sig_num < 1 || sig_num >= NSIG) { + PyErr_SetString(PyExc_ValueError, + "signal number out of range"); + return NULL; + } + if (obj == IgnoreHandler) + func = SIG_IGN; + else if (obj == DefaultHandler) + func = SIG_DFL; + else if (!PyCallable_Check(obj)) { + PyErr_SetString(PyExc_TypeError, "signal handler must be signal.SIG_IGN, signal.SIG_DFL, or a callable object"); - return NULL; - } - else - func = signal_handler; - if (PyOS_setsig(sig_num, func) == SIG_ERR) { - PyErr_SetFromErrno(PyExc_RuntimeError); - return NULL; - } - old_handler = Handlers[sig_num].func; - Handlers[sig_num].tripped = 0; - Py_INCREF(obj); - Handlers[sig_num].func = obj; - return old_handler; + return NULL; + } + else + func = signal_handler; + if (PyOS_setsig(sig_num, func) == SIG_ERR) { + PyErr_SetFromErrno(PyExc_RuntimeError); + return NULL; + } + old_handler = Handlers[sig_num].func; + Handlers[sig_num].tripped = 0; + Py_INCREF(obj); + Handlers[sig_num].func = obj; + return old_handler; } PyDoc_STRVAR(signal_doc, @@ -306,18 +306,18 @@ static PyObject * signal_getsignal(PyObject *self, PyObject *args) { - int sig_num; - PyObject *old_handler; - if (!PyArg_ParseTuple(args, "i:getsignal", &sig_num)) - return NULL; - if (sig_num < 1 || sig_num >= NSIG) { - PyErr_SetString(PyExc_ValueError, - "signal number out of range"); - return NULL; - } - old_handler = Handlers[sig_num].func; - Py_INCREF(old_handler); - return old_handler; + int sig_num; + PyObject *old_handler; + if (!PyArg_ParseTuple(args, "i:getsignal", &sig_num)) + return NULL; + if (sig_num < 1 || sig_num >= NSIG) { + PyErr_SetString(PyExc_ValueError, + "signal number out of range"); + return NULL; + } + old_handler = Handlers[sig_num].func; + Py_INCREF(old_handler); + return old_handler; } PyDoc_STRVAR(getsignal_doc, @@ -339,23 +339,23 @@ static PyObject * signal_siginterrupt(PyObject *self, PyObject *args) { - int sig_num; - int flag; + int sig_num; + int flag; - if (!PyArg_ParseTuple(args, "ii:siginterrupt", &sig_num, &flag)) - return NULL; - if (sig_num < 1 || sig_num >= NSIG) { - PyErr_SetString(PyExc_ValueError, - "signal number out of range"); - return NULL; - } - if (siginterrupt(sig_num, flag)<0) { - PyErr_SetFromErrno(PyExc_RuntimeError); - return NULL; - } + if (!PyArg_ParseTuple(args, "ii:siginterrupt", &sig_num, &flag)) + return NULL; + if (sig_num < 1 || sig_num >= NSIG) { + PyErr_SetString(PyExc_ValueError, + "signal number out of range"); + return NULL; + } + if (siginterrupt(sig_num, flag)<0) { + PyErr_SetFromErrno(PyExc_RuntimeError); + return NULL; + } - Py_INCREF(Py_None); - return Py_None; + Py_INCREF(Py_None); + return Py_None; } #endif @@ -363,24 +363,24 @@ static PyObject * signal_set_wakeup_fd(PyObject *self, PyObject *args) { - struct stat buf; - int fd, old_fd; - if (!PyArg_ParseTuple(args, "i:set_wakeup_fd", &fd)) - return NULL; + struct stat buf; + int fd, old_fd; + if (!PyArg_ParseTuple(args, "i:set_wakeup_fd", &fd)) + return NULL; #ifdef WITH_THREAD - if (PyThread_get_thread_ident() != main_thread) { - PyErr_SetString(PyExc_ValueError, - "set_wakeup_fd only works in main thread"); - return NULL; - } -#endif - if (fd != -1 && fstat(fd, &buf) != 0) { - PyErr_SetString(PyExc_ValueError, "invalid fd"); - return NULL; - } - old_fd = wakeup_fd; - wakeup_fd = fd; - return PyLong_FromLong(old_fd); + if (PyThread_get_thread_ident() != main_thread) { + PyErr_SetString(PyExc_ValueError, + "set_wakeup_fd only works in main thread"); + return NULL; + } +#endif + if (fd != -1 && fstat(fd, &buf) != 0) { + PyErr_SetString(PyExc_ValueError, "invalid fd"); + return NULL; + } + old_fd = wakeup_fd; + wakeup_fd = fd; + return PyLong_FromLong(old_fd); } PyDoc_STRVAR(set_wakeup_fd_doc, @@ -396,11 +396,11 @@ int PySignal_SetWakeupFd(int fd) { - int old_fd = wakeup_fd; - if (fd < 0) - fd = -1; - wakeup_fd = fd; - return old_fd; + int old_fd = wakeup_fd; + if (fd < 0) + fd = -1; + wakeup_fd = fd; + return old_fd; } @@ -414,14 +414,14 @@ struct itimerval new, old; if(!PyArg_ParseTuple(args, "id|d:setitimer", &which, &first, &interval)) - return NULL; + return NULL; timeval_from_double(first, &new.it_value); timeval_from_double(interval, &new.it_interval); /* Let OS check "which" value */ if (setitimer(which, &new, &old) != 0) { - PyErr_SetFromErrno(ItimerError); - return NULL; + PyErr_SetFromErrno(ItimerError); + return NULL; } return itimer_retval(&old); @@ -447,11 +447,11 @@ struct itimerval old; if (!PyArg_ParseTuple(args, "i:getitimer", &which)) - return NULL; + return NULL; if (getitimer(which, &old) != 0) { - PyErr_SetFromErrno(ItimerError); - return NULL; + PyErr_SetFromErrno(ItimerError); + return NULL; } return itimer_retval(&old); @@ -467,27 +467,27 @@ /* List of functions defined in the module */ static PyMethodDef signal_methods[] = { #ifdef HAVE_ALARM - {"alarm", signal_alarm, METH_VARARGS, alarm_doc}, + {"alarm", signal_alarm, METH_VARARGS, alarm_doc}, #endif #ifdef HAVE_SETITIMER {"setitimer", signal_setitimer, METH_VARARGS, setitimer_doc}, #endif #ifdef HAVE_GETITIMER - {"getitimer", signal_getitimer, METH_VARARGS, getitimer_doc}, + {"getitimer", signal_getitimer, METH_VARARGS, getitimer_doc}, #endif - {"signal", signal_signal, METH_VARARGS, signal_doc}, - {"getsignal", signal_getsignal, METH_VARARGS, getsignal_doc}, - {"set_wakeup_fd", signal_set_wakeup_fd, METH_VARARGS, set_wakeup_fd_doc}, + {"signal", signal_signal, METH_VARARGS, signal_doc}, + {"getsignal", signal_getsignal, METH_VARARGS, getsignal_doc}, + {"set_wakeup_fd", signal_set_wakeup_fd, METH_VARARGS, set_wakeup_fd_doc}, #ifdef HAVE_SIGINTERRUPT - {"siginterrupt", signal_siginterrupt, METH_VARARGS, siginterrupt_doc}, + {"siginterrupt", signal_siginterrupt, METH_VARARGS, siginterrupt_doc}, #endif #ifdef HAVE_PAUSE - {"pause", (PyCFunction)signal_pause, - METH_NOARGS,pause_doc}, + {"pause", (PyCFunction)signal_pause, + METH_NOARGS,pause_doc}, #endif - {"default_int_handler", signal_default_int_handler, - METH_VARARGS, default_int_handler_doc}, - {NULL, NULL} /* sentinel */ + {"default_int_handler", signal_default_int_handler, + METH_VARARGS, default_int_handler_doc}, + {NULL, NULL} /* sentinel */ }; @@ -528,264 +528,264 @@ the first is the signal number, the second is the interrupted stack frame."); static struct PyModuleDef signalmodule = { - PyModuleDef_HEAD_INIT, - "signal", - module_doc, - -1, - signal_methods, - NULL, - NULL, - NULL, - NULL + PyModuleDef_HEAD_INIT, + "signal", + module_doc, + -1, + signal_methods, + NULL, + NULL, + NULL, + NULL }; PyMODINIT_FUNC PyInit_signal(void) { - PyObject *m, *d, *x; - int i; + PyObject *m, *d, *x; + int i; #ifdef WITH_THREAD - main_thread = PyThread_get_thread_ident(); - main_pid = getpid(); + main_thread = PyThread_get_thread_ident(); + main_pid = getpid(); #endif - /* Create the module and add the functions */ - m = PyModule_Create(&signalmodule); - if (m == NULL) - return NULL; - - /* Add some symbolic constants to the module */ - d = PyModule_GetDict(m); - - x = DefaultHandler = PyLong_FromVoidPtr((void *)SIG_DFL); - if (!x || PyDict_SetItemString(d, "SIG_DFL", x) < 0) - goto finally; - - x = IgnoreHandler = PyLong_FromVoidPtr((void *)SIG_IGN); - if (!x || PyDict_SetItemString(d, "SIG_IGN", x) < 0) - goto finally; - - x = PyLong_FromLong((long)NSIG); - if (!x || PyDict_SetItemString(d, "NSIG", x) < 0) - goto finally; - Py_DECREF(x); - - x = IntHandler = PyDict_GetItemString(d, "default_int_handler"); - if (!x) - goto finally; - Py_INCREF(IntHandler); - - Handlers[0].tripped = 0; - for (i = 1; i < NSIG; i++) { - void (*t)(int); - t = PyOS_getsig(i); - Handlers[i].tripped = 0; - if (t == SIG_DFL) - Handlers[i].func = DefaultHandler; - else if (t == SIG_IGN) - Handlers[i].func = IgnoreHandler; - else - Handlers[i].func = Py_None; /* None of our business */ - Py_INCREF(Handlers[i].func); - } - if (Handlers[SIGINT].func == DefaultHandler) { - /* Install default int handler */ - Py_INCREF(IntHandler); - Py_DECREF(Handlers[SIGINT].func); - Handlers[SIGINT].func = IntHandler; - old_siginthandler = PyOS_setsig(SIGINT, signal_handler); - } + /* Create the module and add the functions */ + m = PyModule_Create(&signalmodule); + if (m == NULL) + return NULL; + + /* Add some symbolic constants to the module */ + d = PyModule_GetDict(m); + + x = DefaultHandler = PyLong_FromVoidPtr((void *)SIG_DFL); + if (!x || PyDict_SetItemString(d, "SIG_DFL", x) < 0) + goto finally; + + x = IgnoreHandler = PyLong_FromVoidPtr((void *)SIG_IGN); + if (!x || PyDict_SetItemString(d, "SIG_IGN", x) < 0) + goto finally; + + x = PyLong_FromLong((long)NSIG); + if (!x || PyDict_SetItemString(d, "NSIG", x) < 0) + goto finally; + Py_DECREF(x); + + x = IntHandler = PyDict_GetItemString(d, "default_int_handler"); + if (!x) + goto finally; + Py_INCREF(IntHandler); + + Handlers[0].tripped = 0; + for (i = 1; i < NSIG; i++) { + void (*t)(int); + t = PyOS_getsig(i); + Handlers[i].tripped = 0; + if (t == SIG_DFL) + Handlers[i].func = DefaultHandler; + else if (t == SIG_IGN) + Handlers[i].func = IgnoreHandler; + else + Handlers[i].func = Py_None; /* None of our business */ + Py_INCREF(Handlers[i].func); + } + if (Handlers[SIGINT].func == DefaultHandler) { + /* Install default int handler */ + Py_INCREF(IntHandler); + Py_DECREF(Handlers[SIGINT].func); + Handlers[SIGINT].func = IntHandler; + old_siginthandler = PyOS_setsig(SIGINT, signal_handler); + } #ifdef SIGHUP - x = PyLong_FromLong(SIGHUP); - PyDict_SetItemString(d, "SIGHUP", x); - Py_XDECREF(x); + x = PyLong_FromLong(SIGHUP); + PyDict_SetItemString(d, "SIGHUP", x); + Py_XDECREF(x); #endif #ifdef SIGINT - x = PyLong_FromLong(SIGINT); - PyDict_SetItemString(d, "SIGINT", x); - Py_XDECREF(x); + x = PyLong_FromLong(SIGINT); + PyDict_SetItemString(d, "SIGINT", x); + Py_XDECREF(x); #endif #ifdef SIGBREAK - x = PyLong_FromLong(SIGBREAK); - PyDict_SetItemString(d, "SIGBREAK", x); - Py_XDECREF(x); + x = PyLong_FromLong(SIGBREAK); + PyDict_SetItemString(d, "SIGBREAK", x); + Py_XDECREF(x); #endif #ifdef SIGQUIT - x = PyLong_FromLong(SIGQUIT); - PyDict_SetItemString(d, "SIGQUIT", x); - Py_XDECREF(x); + x = PyLong_FromLong(SIGQUIT); + PyDict_SetItemString(d, "SIGQUIT", x); + Py_XDECREF(x); #endif #ifdef SIGILL - x = PyLong_FromLong(SIGILL); - PyDict_SetItemString(d, "SIGILL", x); - Py_XDECREF(x); + x = PyLong_FromLong(SIGILL); + PyDict_SetItemString(d, "SIGILL", x); + Py_XDECREF(x); #endif #ifdef SIGTRAP - x = PyLong_FromLong(SIGTRAP); - PyDict_SetItemString(d, "SIGTRAP", x); - Py_XDECREF(x); + x = PyLong_FromLong(SIGTRAP); + PyDict_SetItemString(d, "SIGTRAP", x); + Py_XDECREF(x); #endif #ifdef SIGIOT - x = PyLong_FromLong(SIGIOT); - PyDict_SetItemString(d, "SIGIOT", x); - Py_XDECREF(x); + x = PyLong_FromLong(SIGIOT); + PyDict_SetItemString(d, "SIGIOT", x); + Py_XDECREF(x); #endif #ifdef SIGABRT - x = PyLong_FromLong(SIGABRT); - PyDict_SetItemString(d, "SIGABRT", x); - Py_XDECREF(x); + x = PyLong_FromLong(SIGABRT); + PyDict_SetItemString(d, "SIGABRT", x); + Py_XDECREF(x); #endif #ifdef SIGEMT - x = PyLong_FromLong(SIGEMT); - PyDict_SetItemString(d, "SIGEMT", x); - Py_XDECREF(x); + x = PyLong_FromLong(SIGEMT); + PyDict_SetItemString(d, "SIGEMT", x); + Py_XDECREF(x); #endif #ifdef SIGFPE - x = PyLong_FromLong(SIGFPE); - PyDict_SetItemString(d, "SIGFPE", x); - Py_XDECREF(x); + x = PyLong_FromLong(SIGFPE); + PyDict_SetItemString(d, "SIGFPE", x); + Py_XDECREF(x); #endif #ifdef SIGKILL - x = PyLong_FromLong(SIGKILL); - PyDict_SetItemString(d, "SIGKILL", x); - Py_XDECREF(x); + x = PyLong_FromLong(SIGKILL); + PyDict_SetItemString(d, "SIGKILL", x); + Py_XDECREF(x); #endif #ifdef SIGBUS - x = PyLong_FromLong(SIGBUS); - PyDict_SetItemString(d, "SIGBUS", x); - Py_XDECREF(x); + x = PyLong_FromLong(SIGBUS); + PyDict_SetItemString(d, "SIGBUS", x); + Py_XDECREF(x); #endif #ifdef SIGSEGV - x = PyLong_FromLong(SIGSEGV); - PyDict_SetItemString(d, "SIGSEGV", x); - Py_XDECREF(x); + x = PyLong_FromLong(SIGSEGV); + PyDict_SetItemString(d, "SIGSEGV", x); + Py_XDECREF(x); #endif #ifdef SIGSYS - x = PyLong_FromLong(SIGSYS); - PyDict_SetItemString(d, "SIGSYS", x); - Py_XDECREF(x); + x = PyLong_FromLong(SIGSYS); + PyDict_SetItemString(d, "SIGSYS", x); + Py_XDECREF(x); #endif #ifdef SIGPIPE - x = PyLong_FromLong(SIGPIPE); - PyDict_SetItemString(d, "SIGPIPE", x); - Py_XDECREF(x); + x = PyLong_FromLong(SIGPIPE); + PyDict_SetItemString(d, "SIGPIPE", x); + Py_XDECREF(x); #endif #ifdef SIGALRM - x = PyLong_FromLong(SIGALRM); - PyDict_SetItemString(d, "SIGALRM", x); - Py_XDECREF(x); + x = PyLong_FromLong(SIGALRM); + PyDict_SetItemString(d, "SIGALRM", x); + Py_XDECREF(x); #endif #ifdef SIGTERM - x = PyLong_FromLong(SIGTERM); - PyDict_SetItemString(d, "SIGTERM", x); - Py_XDECREF(x); + x = PyLong_FromLong(SIGTERM); + PyDict_SetItemString(d, "SIGTERM", x); + Py_XDECREF(x); #endif #ifdef SIGUSR1 - x = PyLong_FromLong(SIGUSR1); - PyDict_SetItemString(d, "SIGUSR1", x); - Py_XDECREF(x); + x = PyLong_FromLong(SIGUSR1); + PyDict_SetItemString(d, "SIGUSR1", x); + Py_XDECREF(x); #endif #ifdef SIGUSR2 - x = PyLong_FromLong(SIGUSR2); - PyDict_SetItemString(d, "SIGUSR2", x); - Py_XDECREF(x); + x = PyLong_FromLong(SIGUSR2); + PyDict_SetItemString(d, "SIGUSR2", x); + Py_XDECREF(x); #endif #ifdef SIGCLD - x = PyLong_FromLong(SIGCLD); - PyDict_SetItemString(d, "SIGCLD", x); - Py_XDECREF(x); + x = PyLong_FromLong(SIGCLD); + PyDict_SetItemString(d, "SIGCLD", x); + Py_XDECREF(x); #endif #ifdef SIGCHLD - x = PyLong_FromLong(SIGCHLD); - PyDict_SetItemString(d, "SIGCHLD", x); - Py_XDECREF(x); + x = PyLong_FromLong(SIGCHLD); + PyDict_SetItemString(d, "SIGCHLD", x); + Py_XDECREF(x); #endif #ifdef SIGPWR - x = PyLong_FromLong(SIGPWR); - PyDict_SetItemString(d, "SIGPWR", x); - Py_XDECREF(x); + x = PyLong_FromLong(SIGPWR); + PyDict_SetItemString(d, "SIGPWR", x); + Py_XDECREF(x); #endif #ifdef SIGIO - x = PyLong_FromLong(SIGIO); - PyDict_SetItemString(d, "SIGIO", x); - Py_XDECREF(x); + x = PyLong_FromLong(SIGIO); + PyDict_SetItemString(d, "SIGIO", x); + Py_XDECREF(x); #endif #ifdef SIGURG - x = PyLong_FromLong(SIGURG); - PyDict_SetItemString(d, "SIGURG", x); - Py_XDECREF(x); + x = PyLong_FromLong(SIGURG); + PyDict_SetItemString(d, "SIGURG", x); + Py_XDECREF(x); #endif #ifdef SIGWINCH - x = PyLong_FromLong(SIGWINCH); - PyDict_SetItemString(d, "SIGWINCH", x); - Py_XDECREF(x); + x = PyLong_FromLong(SIGWINCH); + PyDict_SetItemString(d, "SIGWINCH", x); + Py_XDECREF(x); #endif #ifdef SIGPOLL - x = PyLong_FromLong(SIGPOLL); - PyDict_SetItemString(d, "SIGPOLL", x); - Py_XDECREF(x); + x = PyLong_FromLong(SIGPOLL); + PyDict_SetItemString(d, "SIGPOLL", x); + Py_XDECREF(x); #endif #ifdef SIGSTOP - x = PyLong_FromLong(SIGSTOP); - PyDict_SetItemString(d, "SIGSTOP", x); - Py_XDECREF(x); + x = PyLong_FromLong(SIGSTOP); + PyDict_SetItemString(d, "SIGSTOP", x); + Py_XDECREF(x); #endif #ifdef SIGTSTP - x = PyLong_FromLong(SIGTSTP); - PyDict_SetItemString(d, "SIGTSTP", x); - Py_XDECREF(x); + x = PyLong_FromLong(SIGTSTP); + PyDict_SetItemString(d, "SIGTSTP", x); + Py_XDECREF(x); #endif #ifdef SIGCONT - x = PyLong_FromLong(SIGCONT); - PyDict_SetItemString(d, "SIGCONT", x); - Py_XDECREF(x); + x = PyLong_FromLong(SIGCONT); + PyDict_SetItemString(d, "SIGCONT", x); + Py_XDECREF(x); #endif #ifdef SIGTTIN - x = PyLong_FromLong(SIGTTIN); - PyDict_SetItemString(d, "SIGTTIN", x); - Py_XDECREF(x); + x = PyLong_FromLong(SIGTTIN); + PyDict_SetItemString(d, "SIGTTIN", x); + Py_XDECREF(x); #endif #ifdef SIGTTOU - x = PyLong_FromLong(SIGTTOU); - PyDict_SetItemString(d, "SIGTTOU", x); - Py_XDECREF(x); + x = PyLong_FromLong(SIGTTOU); + PyDict_SetItemString(d, "SIGTTOU", x); + Py_XDECREF(x); #endif #ifdef SIGVTALRM - x = PyLong_FromLong(SIGVTALRM); - PyDict_SetItemString(d, "SIGVTALRM", x); - Py_XDECREF(x); + x = PyLong_FromLong(SIGVTALRM); + PyDict_SetItemString(d, "SIGVTALRM", x); + Py_XDECREF(x); #endif #ifdef SIGPROF - x = PyLong_FromLong(SIGPROF); - PyDict_SetItemString(d, "SIGPROF", x); - Py_XDECREF(x); + x = PyLong_FromLong(SIGPROF); + PyDict_SetItemString(d, "SIGPROF", x); + Py_XDECREF(x); #endif #ifdef SIGXCPU - x = PyLong_FromLong(SIGXCPU); - PyDict_SetItemString(d, "SIGXCPU", x); - Py_XDECREF(x); + x = PyLong_FromLong(SIGXCPU); + PyDict_SetItemString(d, "SIGXCPU", x); + Py_XDECREF(x); #endif #ifdef SIGXFSZ - x = PyLong_FromLong(SIGXFSZ); - PyDict_SetItemString(d, "SIGXFSZ", x); - Py_XDECREF(x); + x = PyLong_FromLong(SIGXFSZ); + PyDict_SetItemString(d, "SIGXFSZ", x); + Py_XDECREF(x); #endif #ifdef SIGRTMIN - x = PyLong_FromLong(SIGRTMIN); - PyDict_SetItemString(d, "SIGRTMIN", x); - Py_XDECREF(x); + x = PyLong_FromLong(SIGRTMIN); + PyDict_SetItemString(d, "SIGRTMIN", x); + Py_XDECREF(x); #endif #ifdef SIGRTMAX - x = PyLong_FromLong(SIGRTMAX); - PyDict_SetItemString(d, "SIGRTMAX", x); - Py_XDECREF(x); + x = PyLong_FromLong(SIGRTMAX); + PyDict_SetItemString(d, "SIGRTMAX", x); + Py_XDECREF(x); #endif #ifdef SIGINFO - x = PyLong_FromLong(SIGINFO); - PyDict_SetItemString(d, "SIGINFO", x); - Py_XDECREF(x); + x = PyLong_FromLong(SIGINFO); + PyDict_SetItemString(d, "SIGINFO", x); + Py_XDECREF(x); #endif #ifdef ITIMER_REAL @@ -805,10 +805,10 @@ #endif #if defined (HAVE_SETITIMER) || defined (HAVE_GETITIMER) - ItimerError = PyErr_NewException("signal.ItimerError", - PyExc_IOError, NULL); + ItimerError = PyErr_NewException("signal.ItimerError", + PyExc_IOError, NULL); if (ItimerError != NULL) - PyDict_SetItemString(d, "ItimerError", ItimerError); + PyDict_SetItemString(d, "ItimerError", ItimerError); #endif #ifdef CTRL_C_EVENT @@ -824,8 +824,8 @@ #endif if (PyErr_Occurred()) { - Py_DECREF(m); - m = NULL; + Py_DECREF(m); + m = NULL; } finally: @@ -835,28 +835,28 @@ static void finisignal(void) { - int i; - PyObject *func; + int i; + PyObject *func; - PyOS_setsig(SIGINT, old_siginthandler); - old_siginthandler = SIG_DFL; + 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 && - func != DefaultHandler && func != IgnoreHandler) - PyOS_setsig(i, SIG_DFL); - Py_XDECREF(func); - } - - Py_XDECREF(IntHandler); - IntHandler = NULL; - Py_XDECREF(DefaultHandler); - DefaultHandler = NULL; - Py_XDECREF(IgnoreHandler); - IgnoreHandler = NULL; + 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 && + func != DefaultHandler && func != IgnoreHandler) + PyOS_setsig(i, SIG_DFL); + Py_XDECREF(func); + } + + Py_XDECREF(IntHandler); + IntHandler = NULL; + Py_XDECREF(DefaultHandler); + DefaultHandler = NULL; + Py_XDECREF(IgnoreHandler); + IgnoreHandler = NULL; } @@ -864,55 +864,55 @@ int PyErr_CheckSignals(void) { - int i; - PyObject *f; + int i; + PyObject *f; - if (!is_tripped) - return 0; + if (!is_tripped) + return 0; #ifdef WITH_THREAD - if (PyThread_get_thread_ident() != main_thread) - return 0; + if (PyThread_get_thread_ident() != main_thread) + return 0; #endif - /* - * The is_tripped variable is meant to speed up the calls to - * PyErr_CheckSignals (both directly or via pending calls) when no - * signal has arrived. This variable is set to 1 when a signal arrives - * and it is set to 0 here, when we know some signals arrived. This way - * we can run the registered handlers with no signals blocked. - * - * NOTE: with this approach we can have a situation where is_tripped is - * 1 but we have no more signals to handle (Handlers[i].tripped - * is 0 for every signal i). This won't do us any harm (except - * we're gonna spent some cycles for nothing). This happens when - * we receive a signal i after we zero is_tripped and before we - * check Handlers[i].tripped. - */ - is_tripped = 0; - - if (!(f = (PyObject *)PyEval_GetFrame())) - f = Py_None; - - for (i = 1; i < NSIG; i++) { - if (Handlers[i].tripped) { - PyObject *result = NULL; - PyObject *arglist = Py_BuildValue("(iO)", i, f); - Handlers[i].tripped = 0; - - if (arglist) { - result = PyEval_CallObject(Handlers[i].func, - arglist); - Py_DECREF(arglist); - } - if (!result) - return -1; - - Py_DECREF(result); - } - } + /* + * The is_tripped variable is meant to speed up the calls to + * PyErr_CheckSignals (both directly or via pending calls) when no + * signal has arrived. This variable is set to 1 when a signal arrives + * and it is set to 0 here, when we know some signals arrived. This way + * we can run the registered handlers with no signals blocked. + * + * NOTE: with this approach we can have a situation where is_tripped is + * 1 but we have no more signals to handle (Handlers[i].tripped + * is 0 for every signal i). This won't do us any harm (except + * we're gonna spent some cycles for nothing). This happens when + * we receive a signal i after we zero is_tripped and before we + * check Handlers[i].tripped. + */ + is_tripped = 0; + + if (!(f = (PyObject *)PyEval_GetFrame())) + f = Py_None; + + for (i = 1; i < NSIG; i++) { + if (Handlers[i].tripped) { + PyObject *result = NULL; + PyObject *arglist = Py_BuildValue("(iO)", i, f); + Handlers[i].tripped = 0; + + if (arglist) { + result = PyEval_CallObject(Handlers[i].func, + arglist); + Py_DECREF(arglist); + } + if (!result) + return -1; + + Py_DECREF(result); + } + } - return 0; + return 0; } @@ -922,49 +922,49 @@ void PyErr_SetInterrupt(void) { - is_tripped = 1; - Handlers[SIGINT].tripped = 1; - Py_AddPendingCall((int (*)(void *))PyErr_CheckSignals, NULL); + is_tripped = 1; + Handlers[SIGINT].tripped = 1; + Py_AddPendingCall((int (*)(void *))PyErr_CheckSignals, NULL); } void PyOS_InitInterrupts(void) { - PyObject *m = PyInit_signal(); - if (m) { - _PyImport_FixupExtension(m, "signal", "signal"); - Py_DECREF(m); - } + PyObject *m = PyInit_signal(); + if (m) { + _PyImport_FixupExtension(m, "signal", "signal"); + Py_DECREF(m); + } } void PyOS_FiniInterrupts(void) { - finisignal(); + finisignal(); } int PyOS_InterruptOccurred(void) { - if (Handlers[SIGINT].tripped) { + if (Handlers[SIGINT].tripped) { #ifdef WITH_THREAD - if (PyThread_get_thread_ident() != main_thread) - return 0; + if (PyThread_get_thread_ident() != main_thread) + return 0; #endif - Handlers[SIGINT].tripped = 0; - return 1; - } - return 0; + Handlers[SIGINT].tripped = 0; + return 1; + } + return 0; } void PyOS_AfterFork(void) { #ifdef WITH_THREAD - PyEval_ReInitThreads(); - main_thread = PyThread_get_thread_ident(); - main_pid = getpid(); - _PyImport_ReInitLock(); - PyThread_ReInitTLS(); + PyEval_ReInitThreads(); + main_thread = PyThread_get_thread_ident(); + main_pid = getpid(); + _PyImport_ReInitLock(); + PyThread_ReInitTLS(); #endif } Modified: python/branches/py3k-jit/Modules/socketmodule.c ============================================================================== --- python/branches/py3k-jit/Modules/socketmodule.c (original) +++ python/branches/py3k-jit/Modules/socketmodule.c Mon May 10 23:55:43 2010 @@ -17,9 +17,9 @@ - socket.error: exception raised for socket specific errors - socket.gaierror: exception raised for getaddrinfo/getnameinfo errors, - a subclass of socket.error + a subclass of socket.error - socket.herror: exception raised for gethostby* errors, - a subclass of socket.error + a subclass of socket.error - socket.gethostbyname(hostname) --> host IP address (string: 'dd.dd.dd.dd') - socket.gethostbyaddr(IP address) --> (hostname, [alias, ...], [IP addr, ...]) - socket.gethostname() --> host name (string: 'spam' or 'spam.domain.com') @@ -27,14 +27,14 @@ - socket.getservbyname(servicename[, protocolname]) --> port number - socket.getservbyport(portnumber[, protocolname]) --> service name - socket.socket([family[, type [, proto, fileno]]]) --> new socket object - (fileno specifies a pre-existing socket file descriptor) + (fileno specifies a pre-existing socket file descriptor) - socket.socketpair([family[, type [, proto]]]) --> (socket, socket) - socket.ntohs(16 bit value) --> new int object - socket.ntohl(32 bit value) --> new int object - socket.htons(16 bit value) --> new int object - socket.htonl(32 bit value) --> new int object - socket.getaddrinfo(host, port [, family, socktype, proto, flags]) - --> List of (family, socktype, proto, canonname, sockaddr) + --> List of (family, socktype, proto, canonname, sockaddr) - socket.getnameinfo(sockaddr, flags) --> (host, port) - socket.AF_INET, socket.SOCK_STREAM, etc.: constants from - socket.has_ipv6: boolean value indicating if IPv6 is supported @@ -54,22 +54,22 @@ specify packet-type and ha-type/addr. - an AF_TIPC socket address is expressed as (addr_type, v1, v2, v3 [, scope]); where addr_type can be one of: - TIPC_ADDR_NAMESEQ, TIPC_ADDR_NAME, and TIPC_ADDR_ID; + TIPC_ADDR_NAMESEQ, TIPC_ADDR_NAME, and TIPC_ADDR_ID; and scope can be one of: - TIPC_ZONE_SCOPE, TIPC_CLUSTER_SCOPE, and TIPC_NODE_SCOPE. + TIPC_ZONE_SCOPE, TIPC_CLUSTER_SCOPE, and TIPC_NODE_SCOPE. The meaning of v1, v2 and v3 depends on the value of addr_type: - if addr_type is TIPC_ADDR_NAME: - v1 is the server type - v2 is the port identifier - v3 is ignored - if addr_type is TIPC_ADDR_NAMESEQ: - v1 is the server type - v2 is the lower port number - v3 is the upper port number - if addr_type is TIPC_ADDR_ID: - v1 is the node - v2 is the ref - v3 is ignored + if addr_type is TIPC_ADDR_NAME: + v1 is the server type + v2 is the port identifier + v3 is ignored + if addr_type is TIPC_ADDR_NAMESEQ: + v1 is the server type + v2 is the lower port number + v3 is the upper port number + if addr_type is TIPC_ADDR_ID: + v1 is the node + v2 is the ref + v3 is ignored Local naming conventions: @@ -283,7 +283,7 @@ #include #ifndef offsetof -# define offsetof(type, member) ((size_t)(&((type *)0)->member)) +# define offsetof(type, member) ((size_t)(&((type *)0)->member)) #endif #ifndef O_NONBLOCK @@ -351,16 +351,16 @@ static SOCKET dup_socket(SOCKET handle) { - HANDLE newhandle; + HANDLE newhandle; - if (!DuplicateHandle(GetCurrentProcess(), (HANDLE)handle, - GetCurrentProcess(), &newhandle, - 0, FALSE, DUPLICATE_SAME_ACCESS)) - { - WSASetLastError(GetLastError()); - return INVALID_SOCKET; - } - return (SOCKET)newhandle; + if (!DuplicateHandle(GetCurrentProcess(), (HANDLE)handle, + GetCurrentProcess(), &newhandle, + 0, FALSE, DUPLICATE_SAME_ACCESS)) + { + WSASetLastError(GetLastError()); + return INVALID_SOCKET; + } + return (SOCKET)newhandle; } #define SOCKETCLOSE closesocket #else @@ -418,7 +418,7 @@ #define SEGMENT_SIZE (32 * 1024 -1) #endif -#define SAS2SA(x) ((struct sockaddr *)(x)) +#define SAS2SA(x) ((struct sockaddr *)(x)) /* * Constants for getnameinfo() @@ -473,8 +473,8 @@ static PyObject* select_error(void) { - PyErr_SetString(socket_error, "unable to select on socket"); - return NULL; + PyErr_SetString(socket_error, "unable to select on socket"); + return NULL; } /* Convenience function to raise an error according to errno @@ -484,95 +484,95 @@ set_error(void) { #ifdef MS_WINDOWS - int err_no = WSAGetLastError(); - /* PyErr_SetExcFromWindowsErr() invokes FormatMessage() which - recognizes the error codes used by both GetLastError() and - WSAGetLastError */ - if (err_no) - return PyErr_SetExcFromWindowsErr(socket_error, err_no); + int err_no = WSAGetLastError(); + /* PyErr_SetExcFromWindowsErr() invokes FormatMessage() which + recognizes the error codes used by both GetLastError() and + WSAGetLastError */ + if (err_no) + return PyErr_SetExcFromWindowsErr(socket_error, err_no); #endif #if defined(PYOS_OS2) && !defined(PYCC_GCC) - if (sock_errno() != NO_ERROR) { - APIRET rc; - ULONG msglen; - char outbuf[100]; - int myerrorcode = sock_errno(); - - /* Retrieve socket-related error message from MPTN.MSG file */ - rc = DosGetMessage(NULL, 0, outbuf, sizeof(outbuf), - myerrorcode - SOCBASEERR + 26, - "mptn.msg", - &msglen); - if (rc == NO_ERROR) { - PyObject *v; - - /* OS/2 doesn't guarantee a terminator */ - outbuf[msglen] = '\0'; - if (strlen(outbuf) > 0) { - /* If non-empty msg, trim CRLF */ - char *lastc = &outbuf[ strlen(outbuf)-1 ]; - while (lastc > outbuf && - isspace(Py_CHARMASK(*lastc))) { - /* Trim trailing whitespace (CRLF) */ - *lastc-- = '\0'; - } - } - v = Py_BuildValue("(is)", myerrorcode, outbuf); - if (v != NULL) { - PyErr_SetObject(socket_error, v); - Py_DECREF(v); - } - return NULL; - } - } + if (sock_errno() != NO_ERROR) { + APIRET rc; + ULONG msglen; + char outbuf[100]; + int myerrorcode = sock_errno(); + + /* Retrieve socket-related error message from MPTN.MSG file */ + rc = DosGetMessage(NULL, 0, outbuf, sizeof(outbuf), + myerrorcode - SOCBASEERR + 26, + "mptn.msg", + &msglen); + if (rc == NO_ERROR) { + PyObject *v; + + /* OS/2 doesn't guarantee a terminator */ + outbuf[msglen] = '\0'; + if (strlen(outbuf) > 0) { + /* If non-empty msg, trim CRLF */ + char *lastc = &outbuf[ strlen(outbuf)-1 ]; + while (lastc > outbuf && + isspace(Py_CHARMASK(*lastc))) { + /* Trim trailing whitespace (CRLF) */ + *lastc-- = '\0'; + } + } + v = Py_BuildValue("(is)", myerrorcode, outbuf); + if (v != NULL) { + PyErr_SetObject(socket_error, v); + Py_DECREF(v); + } + return NULL; + } + } #endif - return PyErr_SetFromErrno(socket_error); + return PyErr_SetFromErrno(socket_error); } static PyObject * set_herror(int h_error) { - PyObject *v; + PyObject *v; #ifdef HAVE_HSTRERROR - v = Py_BuildValue("(is)", h_error, (char *)hstrerror(h_error)); + v = Py_BuildValue("(is)", h_error, (char *)hstrerror(h_error)); #else - v = Py_BuildValue("(is)", h_error, "host not found"); + v = Py_BuildValue("(is)", h_error, "host not found"); #endif - if (v != NULL) { - PyErr_SetObject(socket_herror, v); - Py_DECREF(v); - } + if (v != NULL) { + PyErr_SetObject(socket_herror, v); + Py_DECREF(v); + } - return NULL; + return NULL; } static PyObject * set_gaierror(int error) { - PyObject *v; + PyObject *v; #ifdef EAI_SYSTEM - /* EAI_SYSTEM is not available on Windows XP. */ - if (error == EAI_SYSTEM) - return set_error(); + /* EAI_SYSTEM is not available on Windows XP. */ + if (error == EAI_SYSTEM) + return set_error(); #endif #ifdef HAVE_GAI_STRERROR - v = Py_BuildValue("(is)", error, gai_strerror(error)); + v = Py_BuildValue("(is)", error, gai_strerror(error)); #else - v = Py_BuildValue("(is)", error, "getaddrinfo failed"); + v = Py_BuildValue("(is)", error, "getaddrinfo failed"); #endif - if (v != NULL) { - PyErr_SetObject(socket_gaierror, v); - Py_DECREF(v); - } + if (v != NULL) { + PyErr_SetObject(socket_gaierror, v); + Py_DECREF(v); + } - return NULL; + return NULL; } #ifdef __VMS @@ -580,22 +580,22 @@ static int sendsegmented(int sock_fd, char *buf, int len, int flags) { - int n = 0; - int remaining = len; + int n = 0; + int remaining = len; - while (remaining > 0) { - unsigned int segment; + while (remaining > 0) { + unsigned int segment; - segment = (remaining >= SEGMENT_SIZE ? SEGMENT_SIZE : remaining); - n = send(sock_fd, buf, segment, flags); - if (n < 0) { - return n; - } - remaining -= segment; - buf += segment; - } /* end while */ + segment = (remaining >= SEGMENT_SIZE ? SEGMENT_SIZE : remaining); + n = send(sock_fd, buf, segment, flags); + if (n < 0) { + return n; + } + remaining -= segment; + buf += segment; + } /* end while */ - return len; + return len; } #endif @@ -605,33 +605,33 @@ internal_setblocking(PySocketSockObject *s, int block) { #ifndef MS_WINDOWS - int delay_flag; + int delay_flag; #endif - Py_BEGIN_ALLOW_THREADS + Py_BEGIN_ALLOW_THREADS #ifndef MS_WINDOWS #if defined(PYOS_OS2) && !defined(PYCC_GCC) - block = !block; - ioctl(s->sock_fd, FIONBIO, (caddr_t)&block, sizeof(block)); + block = !block; + ioctl(s->sock_fd, FIONBIO, (caddr_t)&block, sizeof(block)); #elif defined(__VMS) - block = !block; - ioctl(s->sock_fd, FIONBIO, (unsigned int *)&block); + block = !block; + ioctl(s->sock_fd, FIONBIO, (unsigned int *)&block); #else /* !PYOS_OS2 && !__VMS */ - delay_flag = fcntl(s->sock_fd, F_GETFL, 0); - if (block) - delay_flag &= (~O_NONBLOCK); - else - delay_flag |= O_NONBLOCK; - fcntl(s->sock_fd, F_SETFL, delay_flag); + delay_flag = fcntl(s->sock_fd, F_GETFL, 0); + if (block) + delay_flag &= (~O_NONBLOCK); + else + delay_flag |= O_NONBLOCK; + fcntl(s->sock_fd, F_SETFL, delay_flag); #endif /* !PYOS_OS2 */ #else /* MS_WINDOWS */ - block = !block; - ioctlsocket(s->sock_fd, FIONBIO, (u_long*)&block); + block = !block; + ioctlsocket(s->sock_fd, FIONBIO, (u_long*)&block); #endif /* MS_WINDOWS */ - Py_END_ALLOW_THREADS + Py_END_ALLOW_THREADS - /* Since these don't return anything */ - return 1; + /* Since these don't return anything */ + return 1; } /* Do a select()/poll() on the socket, if necessary (sock_timeout > 0). @@ -642,53 +642,53 @@ static int internal_select(PySocketSockObject *s, int writing) { - int n; + int n; - /* Nothing to do unless we're in timeout mode (not non-blocking) */ - if (s->sock_timeout <= 0.0) - return 0; - - /* Guard against closed socket */ - if (s->sock_fd < 0) - return 0; + /* Nothing to do unless we're in timeout mode (not non-blocking) */ + if (s->sock_timeout <= 0.0) + return 0; + + /* Guard against closed socket */ + if (s->sock_fd < 0) + return 0; - /* Prefer poll, if available, since you can poll() any fd - * which can't be done with select(). */ + /* Prefer poll, if available, since you can poll() any fd + * which can't be done with select(). */ #ifdef HAVE_POLL - { - struct pollfd pollfd; - int timeout; - - pollfd.fd = s->sock_fd; - pollfd.events = writing ? POLLOUT : POLLIN; - - /* s->sock_timeout is in seconds, timeout in ms */ - timeout = (int)(s->sock_timeout * 1000 + 0.5); - n = poll(&pollfd, 1, timeout); - } -#else - { - /* Construct the arguments to select */ - fd_set fds; - struct timeval tv; - tv.tv_sec = (int)s->sock_timeout; - tv.tv_usec = (int)((s->sock_timeout - tv.tv_sec) * 1e6); - FD_ZERO(&fds); - FD_SET(s->sock_fd, &fds); - - /* See if the socket is ready */ - if (writing) - n = select(s->sock_fd+1, NULL, &fds, NULL, &tv); - else - n = select(s->sock_fd+1, &fds, NULL, NULL, &tv); - } -#endif - - if (n < 0) - return -1; - if (n == 0) - return 1; - return 0; + { + struct pollfd pollfd; + int timeout; + + pollfd.fd = s->sock_fd; + pollfd.events = writing ? POLLOUT : POLLIN; + + /* s->sock_timeout is in seconds, timeout in ms */ + timeout = (int)(s->sock_timeout * 1000 + 0.5); + n = poll(&pollfd, 1, timeout); + } +#else + { + /* Construct the arguments to select */ + fd_set fds; + struct timeval tv; + tv.tv_sec = (int)s->sock_timeout; + tv.tv_usec = (int)((s->sock_timeout - tv.tv_sec) * 1e6); + FD_ZERO(&fds); + FD_SET(s->sock_fd, &fds); + + /* See if the socket is ready */ + if (writing) + n = select(s->sock_fd+1, NULL, &fds, NULL, &tv); + else + n = select(s->sock_fd+1, &fds, NULL, NULL, &tv); + } +#endif + + if (n < 0) + return -1; + if (n == 0) + return 1; + return 0; } /* Initialize a new socket object. */ @@ -697,18 +697,18 @@ static void init_sockobject(PySocketSockObject *s, - SOCKET_T fd, int family, int type, int proto) + SOCKET_T fd, int family, int type, int proto) { - s->sock_fd = fd; - s->sock_family = family; - s->sock_type = type; - s->sock_proto = proto; - s->sock_timeout = defaulttimeout; + s->sock_fd = fd; + s->sock_family = family; + s->sock_type = type; + s->sock_proto = proto; + s->sock_timeout = defaulttimeout; - s->errorhandler = &set_error; + s->errorhandler = &set_error; - if (defaulttimeout >= 0.0) - internal_setblocking(s, 0); + if (defaulttimeout >= 0.0) + internal_setblocking(s, 0); } @@ -721,12 +721,12 @@ static PySocketSockObject * new_sockobject(SOCKET_T fd, int family, int type, int proto) { - PySocketSockObject *s; - s = (PySocketSockObject *) - PyType_GenericNew(&sock_type, NULL, NULL); - if (s != NULL) - init_sockobject(s, fd, family, type, proto); - return s; + PySocketSockObject *s; + s = (PySocketSockObject *) + PyType_GenericNew(&sock_type, NULL, NULL); + if (s != NULL) + init_sockobject(s, fd, family, type, proto); + return s; } @@ -746,122 +746,122 @@ static int setipaddr(char *name, struct sockaddr *addr_ret, size_t addr_ret_size, int af) { - struct addrinfo hints, *res; - int error; - int d1, d2, d3, d4; - char ch; - - memset((void *) addr_ret, '\0', sizeof(*addr_ret)); - if (name[0] == '\0') { - int siz; - memset(&hints, 0, sizeof(hints)); - hints.ai_family = af; - hints.ai_socktype = SOCK_DGRAM; /*dummy*/ - hints.ai_flags = AI_PASSIVE; - Py_BEGIN_ALLOW_THREADS - ACQUIRE_GETADDRINFO_LOCK - error = getaddrinfo(NULL, "0", &hints, &res); - Py_END_ALLOW_THREADS - /* We assume that those thread-unsafe getaddrinfo() versions - *are* safe regarding their return value, ie. that a - subsequent call to getaddrinfo() does not destroy the - outcome of the first call. */ - RELEASE_GETADDRINFO_LOCK - if (error) { - set_gaierror(error); - return -1; - } - switch (res->ai_family) { - case AF_INET: - siz = 4; - break; + struct addrinfo hints, *res; + int error; + int d1, d2, d3, d4; + char ch; + + memset((void *) addr_ret, '\0', sizeof(*addr_ret)); + if (name[0] == '\0') { + int siz; + memset(&hints, 0, sizeof(hints)); + hints.ai_family = af; + hints.ai_socktype = SOCK_DGRAM; /*dummy*/ + hints.ai_flags = AI_PASSIVE; + Py_BEGIN_ALLOW_THREADS + ACQUIRE_GETADDRINFO_LOCK + error = getaddrinfo(NULL, "0", &hints, &res); + Py_END_ALLOW_THREADS + /* We assume that those thread-unsafe getaddrinfo() versions + *are* safe regarding their return value, ie. that a + subsequent call to getaddrinfo() does not destroy the + outcome of the first call. */ + RELEASE_GETADDRINFO_LOCK + if (error) { + set_gaierror(error); + return -1; + } + switch (res->ai_family) { + case AF_INET: + siz = 4; + break; #ifdef ENABLE_IPV6 - case AF_INET6: - siz = 16; - break; -#endif - default: - freeaddrinfo(res); - PyErr_SetString(socket_error, - "unsupported address family"); - return -1; - } - if (res->ai_next) { - freeaddrinfo(res); - PyErr_SetString(socket_error, - "wildcard resolved to multiple address"); - return -1; - } - if (res->ai_addrlen < addr_ret_size) - addr_ret_size = res->ai_addrlen; - memcpy(addr_ret, res->ai_addr, addr_ret_size); - freeaddrinfo(res); - return siz; - } - if (name[0] == '<' && strcmp(name, "") == 0) { - struct sockaddr_in *sin; - if (af != AF_INET && af != AF_UNSPEC) { - PyErr_SetString(socket_error, - "address family mismatched"); - return -1; - } - sin = (struct sockaddr_in *)addr_ret; - memset((void *) sin, '\0', sizeof(*sin)); - sin->sin_family = AF_INET; + case AF_INET6: + siz = 16; + break; +#endif + default: + freeaddrinfo(res); + PyErr_SetString(socket_error, + "unsupported address family"); + return -1; + } + if (res->ai_next) { + freeaddrinfo(res); + PyErr_SetString(socket_error, + "wildcard resolved to multiple address"); + return -1; + } + if (res->ai_addrlen < addr_ret_size) + addr_ret_size = res->ai_addrlen; + memcpy(addr_ret, res->ai_addr, addr_ret_size); + freeaddrinfo(res); + return siz; + } + if (name[0] == '<' && strcmp(name, "") == 0) { + struct sockaddr_in *sin; + if (af != AF_INET && af != AF_UNSPEC) { + PyErr_SetString(socket_error, + "address family mismatched"); + return -1; + } + sin = (struct sockaddr_in *)addr_ret; + memset((void *) sin, '\0', sizeof(*sin)); + sin->sin_family = AF_INET; #ifdef HAVE_SOCKADDR_SA_LEN - sin->sin_len = sizeof(*sin); + sin->sin_len = sizeof(*sin); #endif - sin->sin_addr.s_addr = INADDR_BROADCAST; - return sizeof(sin->sin_addr); - } - if (sscanf(name, "%d.%d.%d.%d%c", &d1, &d2, &d3, &d4, &ch) == 4 && - 0 <= d1 && d1 <= 255 && 0 <= d2 && d2 <= 255 && - 0 <= d3 && d3 <= 255 && 0 <= d4 && d4 <= 255) { - struct sockaddr_in *sin; - sin = (struct sockaddr_in *)addr_ret; - sin->sin_addr.s_addr = htonl( - ((long) d1 << 24) | ((long) d2 << 16) | - ((long) d3 << 8) | ((long) d4 << 0)); - sin->sin_family = AF_INET; + sin->sin_addr.s_addr = INADDR_BROADCAST; + return sizeof(sin->sin_addr); + } + if (sscanf(name, "%d.%d.%d.%d%c", &d1, &d2, &d3, &d4, &ch) == 4 && + 0 <= d1 && d1 <= 255 && 0 <= d2 && d2 <= 255 && + 0 <= d3 && d3 <= 255 && 0 <= d4 && d4 <= 255) { + struct sockaddr_in *sin; + sin = (struct sockaddr_in *)addr_ret; + sin->sin_addr.s_addr = htonl( + ((long) d1 << 24) | ((long) d2 << 16) | + ((long) d3 << 8) | ((long) d4 << 0)); + sin->sin_family = AF_INET; #ifdef HAVE_SOCKADDR_SA_LEN - sin->sin_len = sizeof(*sin); + sin->sin_len = sizeof(*sin); #endif - return 4; - } - memset(&hints, 0, sizeof(hints)); - hints.ai_family = af; - Py_BEGIN_ALLOW_THREADS - ACQUIRE_GETADDRINFO_LOCK - error = getaddrinfo(name, NULL, &hints, &res); + return 4; + } + memset(&hints, 0, sizeof(hints)); + hints.ai_family = af; + Py_BEGIN_ALLOW_THREADS + ACQUIRE_GETADDRINFO_LOCK + error = getaddrinfo(name, NULL, &hints, &res); #if defined(__digital__) && defined(__unix__) - if (error == EAI_NONAME && af == AF_UNSPEC) { - /* On Tru64 V5.1, numeric-to-addr conversion fails - if no address family is given. Assume IPv4 for now.*/ - hints.ai_family = AF_INET; - error = getaddrinfo(name, NULL, &hints, &res); - } -#endif - Py_END_ALLOW_THREADS - RELEASE_GETADDRINFO_LOCK /* see comment in setipaddr() */ - if (error) { - set_gaierror(error); - return -1; - } - if (res->ai_addrlen < addr_ret_size) - addr_ret_size = res->ai_addrlen; - memcpy((char *) addr_ret, res->ai_addr, addr_ret_size); - freeaddrinfo(res); - switch (addr_ret->sa_family) { - case AF_INET: - return 4; + if (error == EAI_NONAME && af == AF_UNSPEC) { + /* On Tru64 V5.1, numeric-to-addr conversion fails + if no address family is given. Assume IPv4 for now.*/ + hints.ai_family = AF_INET; + error = getaddrinfo(name, NULL, &hints, &res); + } +#endif + Py_END_ALLOW_THREADS + RELEASE_GETADDRINFO_LOCK /* see comment in setipaddr() */ + if (error) { + set_gaierror(error); + return -1; + } + if (res->ai_addrlen < addr_ret_size) + addr_ret_size = res->ai_addrlen; + memcpy((char *) addr_ret, res->ai_addr, addr_ret_size); + freeaddrinfo(res); + switch (addr_ret->sa_family) { + case AF_INET: + return 4; #ifdef ENABLE_IPV6 - case AF_INET6: - return 16; + case AF_INET6: + return 16; #endif - default: - PyErr_SetString(socket_error, "unknown address family"); - return -1; - } + default: + PyErr_SetString(socket_error, "unknown address family"); + return -1; + } } @@ -872,16 +872,16 @@ static PyObject * makeipaddr(struct sockaddr *addr, int addrlen) { - char buf[NI_MAXHOST]; - int error; + char buf[NI_MAXHOST]; + int error; - error = getnameinfo(addr, addrlen, buf, sizeof(buf), NULL, 0, - NI_NUMERICHOST); - if (error) { - set_gaierror(error); - return NULL; - } - return PyUnicode_FromString(buf); + error = getnameinfo(addr, addrlen, buf, sizeof(buf), NULL, 0, + NI_NUMERICHOST); + if (error) { + set_gaierror(error); + return NULL; + } + return PyUnicode_FromString(buf); } @@ -893,24 +893,24 @@ static int setbdaddr(char *name, bdaddr_t *bdaddr) { - unsigned int b0, b1, b2, b3, b4, b5; - char ch; - int n; - - n = sscanf(name, "%X:%X:%X:%X:%X:%X%c", - &b5, &b4, &b3, &b2, &b1, &b0, &ch); - if (n == 6 && (b0 | b1 | b2 | b3 | b4 | b5) < 256) { - bdaddr->b[0] = b0; - bdaddr->b[1] = b1; - bdaddr->b[2] = b2; - bdaddr->b[3] = b3; - bdaddr->b[4] = b4; - bdaddr->b[5] = b5; - return 6; - } else { - PyErr_SetString(socket_error, "bad bluetooth address"); - return -1; - } + unsigned int b0, b1, b2, b3, b4, b5; + char ch; + int n; + + n = sscanf(name, "%X:%X:%X:%X:%X:%X%c", + &b5, &b4, &b3, &b2, &b1, &b0, &ch); + if (n == 6 && (b0 | b1 | b2 | b3 | b4 | b5) < 256) { + bdaddr->b[0] = b0; + bdaddr->b[1] = b1; + bdaddr->b[2] = b2; + bdaddr->b[3] = b3; + bdaddr->b[4] = b4; + bdaddr->b[5] = b5; + return 6; + } else { + PyErr_SetString(socket_error, "bad bluetooth address"); + return -1; + } } /* Create a string representation of the Bluetooth address. This is always a @@ -920,12 +920,12 @@ static PyObject * makebdaddr(bdaddr_t *bdaddr) { - char buf[(6 * 2) + 5 + 1]; + char buf[(6 * 2) + 5 + 1]; - sprintf(buf, "%02X:%02X:%02X:%02X:%02X:%02X", - bdaddr->b[5], bdaddr->b[4], bdaddr->b[3], - bdaddr->b[2], bdaddr->b[1], bdaddr->b[0]); - return PyUnicode_FromString(buf); + sprintf(buf, "%02X:%02X:%02X:%02X:%02X:%02X", + bdaddr->b[5], bdaddr->b[4], bdaddr->b[3], + bdaddr->b[2], bdaddr->b[1], bdaddr->b[0]); + return PyUnicode_FromString(buf); } #endif @@ -939,193 +939,193 @@ static PyObject * makesockaddr(int sockfd, struct sockaddr *addr, int addrlen, int proto) { - if (addrlen == 0) { - /* No address -- may be recvfrom() from known socket */ - Py_INCREF(Py_None); - return Py_None; - } - - switch (addr->sa_family) { - - case AF_INET: - { - struct sockaddr_in *a; - PyObject *addrobj = makeipaddr(addr, sizeof(*a)); - PyObject *ret = NULL; - if (addrobj) { - a = (struct sockaddr_in *)addr; - ret = Py_BuildValue("Oi", addrobj, ntohs(a->sin_port)); - Py_DECREF(addrobj); - } - return ret; - } + if (addrlen == 0) { + /* No address -- may be recvfrom() from known socket */ + Py_INCREF(Py_None); + return Py_None; + } + + switch (addr->sa_family) { + + case AF_INET: + { + struct sockaddr_in *a; + PyObject *addrobj = makeipaddr(addr, sizeof(*a)); + PyObject *ret = NULL; + if (addrobj) { + a = (struct sockaddr_in *)addr; + ret = Py_BuildValue("Oi", addrobj, ntohs(a->sin_port)); + Py_DECREF(addrobj); + } + return ret; + } #if defined(AF_UNIX) - case AF_UNIX: - { - struct sockaddr_un *a = (struct sockaddr_un *) addr; + case AF_UNIX: + { + struct sockaddr_un *a = (struct sockaddr_un *) addr; #ifdef linux - if (a->sun_path[0] == 0) { /* Linux abstract namespace */ - addrlen -= offsetof(struct sockaddr_un, sun_path); - return PyBytes_FromStringAndSize(a->sun_path, addrlen); - } - else + if (a->sun_path[0] == 0) { /* Linux abstract namespace */ + addrlen -= offsetof(struct sockaddr_un, sun_path); + return PyBytes_FromStringAndSize(a->sun_path, addrlen); + } + else #endif /* linux */ - { - /* regular NULL-terminated string */ - return PyUnicode_FromString(a->sun_path); - } - } + { + /* regular NULL-terminated string */ + return PyUnicode_FromString(a->sun_path); + } + } #endif /* AF_UNIX */ #if defined(AF_NETLINK) case AF_NETLINK: { - struct sockaddr_nl *a = (struct sockaddr_nl *) addr; - return Py_BuildValue("II", a->nl_pid, a->nl_groups); + struct sockaddr_nl *a = (struct sockaddr_nl *) addr; + return Py_BuildValue("II", a->nl_pid, a->nl_groups); } #endif /* AF_NETLINK */ #ifdef ENABLE_IPV6 - case AF_INET6: - { - struct sockaddr_in6 *a; - PyObject *addrobj = makeipaddr(addr, sizeof(*a)); - PyObject *ret = NULL; - if (addrobj) { - a = (struct sockaddr_in6 *)addr; - ret = Py_BuildValue("Oiii", - addrobj, - ntohs(a->sin6_port), - a->sin6_flowinfo, - a->sin6_scope_id); - Py_DECREF(addrobj); - } - return ret; - } + case AF_INET6: + { + struct sockaddr_in6 *a; + PyObject *addrobj = makeipaddr(addr, sizeof(*a)); + PyObject *ret = NULL; + if (addrobj) { + a = (struct sockaddr_in6 *)addr; + ret = Py_BuildValue("Oiii", + addrobj, + ntohs(a->sin6_port), + a->sin6_flowinfo, + a->sin6_scope_id); + Py_DECREF(addrobj); + } + return ret; + } #endif #ifdef USE_BLUETOOTH - case AF_BLUETOOTH: - switch (proto) { + case AF_BLUETOOTH: + switch (proto) { - case BTPROTO_L2CAP: - { - struct sockaddr_l2 *a = (struct sockaddr_l2 *) addr; - PyObject *addrobj = makebdaddr(&_BT_L2_MEMB(a, bdaddr)); - PyObject *ret = NULL; - if (addrobj) { - ret = Py_BuildValue("Oi", - addrobj, - _BT_L2_MEMB(a, psm)); - Py_DECREF(addrobj); - } - return ret; - } - - case BTPROTO_RFCOMM: - { - struct sockaddr_rc *a = (struct sockaddr_rc *) addr; - PyObject *addrobj = makebdaddr(&_BT_RC_MEMB(a, bdaddr)); - PyObject *ret = NULL; - if (addrobj) { - ret = Py_BuildValue("Oi", - addrobj, - _BT_RC_MEMB(a, channel)); - Py_DECREF(addrobj); - } - return ret; - } - - case BTPROTO_HCI: - { - struct sockaddr_hci *a = (struct sockaddr_hci *) addr; - PyObject *ret = NULL; - ret = Py_BuildValue("i", _BT_HCI_MEMB(a, dev)); - return ret; - } + case BTPROTO_L2CAP: + { + struct sockaddr_l2 *a = (struct sockaddr_l2 *) addr; + PyObject *addrobj = makebdaddr(&_BT_L2_MEMB(a, bdaddr)); + PyObject *ret = NULL; + if (addrobj) { + ret = Py_BuildValue("Oi", + addrobj, + _BT_L2_MEMB(a, psm)); + Py_DECREF(addrobj); + } + return ret; + } + + case BTPROTO_RFCOMM: + { + struct sockaddr_rc *a = (struct sockaddr_rc *) addr; + PyObject *addrobj = makebdaddr(&_BT_RC_MEMB(a, bdaddr)); + PyObject *ret = NULL; + if (addrobj) { + ret = Py_BuildValue("Oi", + addrobj, + _BT_RC_MEMB(a, channel)); + Py_DECREF(addrobj); + } + return ret; + } + + case BTPROTO_HCI: + { + struct sockaddr_hci *a = (struct sockaddr_hci *) addr; + PyObject *ret = NULL; + ret = Py_BuildValue("i", _BT_HCI_MEMB(a, dev)); + return ret; + } #if !defined(__FreeBSD__) - case BTPROTO_SCO: - { - struct sockaddr_sco *a = (struct sockaddr_sco *) addr; - return makebdaddr(&_BT_SCO_MEMB(a, bdaddr)); - } + case BTPROTO_SCO: + { + struct sockaddr_sco *a = (struct sockaddr_sco *) addr; + return makebdaddr(&_BT_SCO_MEMB(a, bdaddr)); + } #endif - default: - PyErr_SetString(PyExc_ValueError, - "Unknown Bluetooth protocol"); - return NULL; - } + default: + PyErr_SetString(PyExc_ValueError, + "Unknown Bluetooth protocol"); + return NULL; + } #endif #ifdef HAVE_NETPACKET_PACKET_H - case AF_PACKET: - { - struct sockaddr_ll *a = (struct sockaddr_ll *)addr; - char *ifname = ""; - struct ifreq ifr; - /* need to look up interface name give index */ - if (a->sll_ifindex) { - ifr.ifr_ifindex = a->sll_ifindex; - if (ioctl(sockfd, SIOCGIFNAME, &ifr) == 0) - ifname = ifr.ifr_name; - } - return Py_BuildValue("shbhy#", - ifname, - ntohs(a->sll_protocol), - a->sll_pkttype, - a->sll_hatype, - a->sll_addr, - a->sll_halen); - } + case AF_PACKET: + { + struct sockaddr_ll *a = (struct sockaddr_ll *)addr; + char *ifname = ""; + struct ifreq ifr; + /* need to look up interface name give index */ + if (a->sll_ifindex) { + ifr.ifr_ifindex = a->sll_ifindex; + if (ioctl(sockfd, SIOCGIFNAME, &ifr) == 0) + ifname = ifr.ifr_name; + } + return Py_BuildValue("shbhy#", + ifname, + ntohs(a->sll_protocol), + a->sll_pkttype, + a->sll_hatype, + a->sll_addr, + a->sll_halen); + } #endif #ifdef HAVE_LINUX_TIPC_H - case AF_TIPC: - { - struct sockaddr_tipc *a = (struct sockaddr_tipc *) addr; - if (a->addrtype == TIPC_ADDR_NAMESEQ) { - return Py_BuildValue("IIIII", - a->addrtype, - a->addr.nameseq.type, - a->addr.nameseq.lower, - a->addr.nameseq.upper, - a->scope); - } else if (a->addrtype == TIPC_ADDR_NAME) { - return Py_BuildValue("IIIII", - a->addrtype, - a->addr.name.name.type, - a->addr.name.name.instance, - a->addr.name.name.instance, - a->scope); - } else if (a->addrtype == TIPC_ADDR_ID) { - return Py_BuildValue("IIIII", - a->addrtype, - a->addr.id.node, - a->addr.id.ref, - 0, - a->scope); - } else { - PyErr_SetString(PyExc_ValueError, - "Invalid address type"); - return NULL; - } - } -#endif - - /* More cases here... */ - - default: - /* If we don't know the address family, don't raise an - exception -- return it as an (int, bytes) tuple. */ - return Py_BuildValue("iy#", - addr->sa_family, - addr->sa_data, - sizeof(addr->sa_data)); + case AF_TIPC: + { + struct sockaddr_tipc *a = (struct sockaddr_tipc *) addr; + if (a->addrtype == TIPC_ADDR_NAMESEQ) { + return Py_BuildValue("IIIII", + a->addrtype, + a->addr.nameseq.type, + a->addr.nameseq.lower, + a->addr.nameseq.upper, + a->scope); + } else if (a->addrtype == TIPC_ADDR_NAME) { + return Py_BuildValue("IIIII", + a->addrtype, + a->addr.name.name.type, + a->addr.name.name.instance, + a->addr.name.name.instance, + a->scope); + } else if (a->addrtype == TIPC_ADDR_ID) { + return Py_BuildValue("IIIII", + a->addrtype, + a->addr.id.node, + a->addr.id.ref, + 0, + a->scope); + } else { + PyErr_SetString(PyExc_ValueError, + "Invalid address type"); + return NULL; + } + } +#endif + + /* More cases here... */ + + default: + /* If we don't know the address family, don't raise an + exception -- return it as an (int, bytes) tuple. */ + return Py_BuildValue("iy#", + addr->sa_family, + addr->sa_data, + sizeof(addr->sa_data)); - } + } } @@ -1136,346 +1136,346 @@ static int getsockaddrarg(PySocketSockObject *s, PyObject *args, - struct sockaddr *addr_ret, int *len_ret) + struct sockaddr *addr_ret, int *len_ret) { - switch (s->sock_family) { + switch (s->sock_family) { #if defined(AF_UNIX) - case AF_UNIX: - { - struct sockaddr_un* addr; - char *path; - int len; - if (!PyArg_Parse(args, "s#", &path, &len)) - return 0; + case AF_UNIX: + { + struct sockaddr_un* addr; + char *path; + int len; + if (!PyArg_Parse(args, "s#", &path, &len)) + return 0; - addr = (struct sockaddr_un*)addr_ret; + addr = (struct sockaddr_un*)addr_ret; #ifdef linux - if (len > 0 && path[0] == 0) { - /* Linux abstract namespace extension */ - if (len > sizeof addr->sun_path) { - PyErr_SetString(socket_error, - "AF_UNIX path too long"); - return 0; - } - } - else + if (len > 0 && path[0] == 0) { + /* Linux abstract namespace extension */ + if (len > sizeof addr->sun_path) { + PyErr_SetString(socket_error, + "AF_UNIX path too long"); + return 0; + } + } + else #endif /* linux */ - { - /* regular NULL-terminated string */ - if (len >= sizeof addr->sun_path) { - PyErr_SetString(socket_error, - "AF_UNIX path too long"); - return 0; - } - addr->sun_path[len] = 0; - } - addr->sun_family = s->sock_family; - memcpy(addr->sun_path, path, len); + { + /* regular NULL-terminated string */ + if (len >= sizeof addr->sun_path) { + PyErr_SetString(socket_error, + "AF_UNIX path too long"); + return 0; + } + addr->sun_path[len] = 0; + } + addr->sun_family = s->sock_family; + memcpy(addr->sun_path, path, len); #if defined(PYOS_OS2) - *len_ret = sizeof(*addr); + *len_ret = sizeof(*addr); #else - *len_ret = len + offsetof(struct sockaddr_un, sun_path); + *len_ret = len + offsetof(struct sockaddr_un, sun_path); #endif - return 1; - } + return 1; + } #endif /* AF_UNIX */ #if defined(AF_NETLINK) - case AF_NETLINK: - { - struct sockaddr_nl* addr; - int pid, groups; - addr = (struct sockaddr_nl *)addr_ret; - if (!PyTuple_Check(args)) { - PyErr_Format( - PyExc_TypeError, - "getsockaddrarg: " - "AF_NETLINK address must be tuple, not %.500s", - Py_TYPE(args)->tp_name); - return 0; - } - if (!PyArg_ParseTuple(args, "II:getsockaddrarg", &pid, &groups)) - return 0; - addr->nl_family = AF_NETLINK; - addr->nl_pid = pid; - addr->nl_groups = groups; - *len_ret = sizeof(*addr); - return 1; - } -#endif - - case AF_INET: - { - struct sockaddr_in* addr; - char *host; - int port, result; - if (!PyTuple_Check(args)) { - PyErr_Format( - PyExc_TypeError, - "getsockaddrarg: " - "AF_INET address must be tuple, not %.500s", - Py_TYPE(args)->tp_name); - return 0; - } - if (!PyArg_ParseTuple(args, "eti:getsockaddrarg", - "idna", &host, &port)) - return 0; - addr=(struct sockaddr_in*)addr_ret; - result = setipaddr(host, (struct sockaddr *)addr, - sizeof(*addr), AF_INET); - PyMem_Free(host); - if (result < 0) - return 0; - if (port < 0 || port > 0xffff) { - PyErr_SetString( - PyExc_OverflowError, - "getsockaddrarg: port must be 0-65535."); - return 0; - } - addr->sin_family = AF_INET; - addr->sin_port = htons((short)port); - *len_ret = sizeof *addr; - return 1; - } + case AF_NETLINK: + { + struct sockaddr_nl* addr; + int pid, groups; + addr = (struct sockaddr_nl *)addr_ret; + if (!PyTuple_Check(args)) { + PyErr_Format( + PyExc_TypeError, + "getsockaddrarg: " + "AF_NETLINK address must be tuple, not %.500s", + Py_TYPE(args)->tp_name); + return 0; + } + if (!PyArg_ParseTuple(args, "II:getsockaddrarg", &pid, &groups)) + return 0; + addr->nl_family = AF_NETLINK; + addr->nl_pid = pid; + addr->nl_groups = groups; + *len_ret = sizeof(*addr); + return 1; + } +#endif + + case AF_INET: + { + struct sockaddr_in* addr; + char *host; + int port, result; + if (!PyTuple_Check(args)) { + PyErr_Format( + PyExc_TypeError, + "getsockaddrarg: " + "AF_INET address must be tuple, not %.500s", + Py_TYPE(args)->tp_name); + return 0; + } + if (!PyArg_ParseTuple(args, "eti:getsockaddrarg", + "idna", &host, &port)) + return 0; + addr=(struct sockaddr_in*)addr_ret; + result = setipaddr(host, (struct sockaddr *)addr, + sizeof(*addr), AF_INET); + PyMem_Free(host); + if (result < 0) + return 0; + if (port < 0 || port > 0xffff) { + PyErr_SetString( + PyExc_OverflowError, + "getsockaddrarg: port must be 0-65535."); + return 0; + } + addr->sin_family = AF_INET; + addr->sin_port = htons((short)port); + *len_ret = sizeof *addr; + return 1; + } #ifdef ENABLE_IPV6 - case AF_INET6: - { - struct sockaddr_in6* addr; - char *host; - int port, flowinfo, scope_id, result; - flowinfo = scope_id = 0; - if (!PyTuple_Check(args)) { - PyErr_Format( - PyExc_TypeError, - "getsockaddrarg: " - "AF_INET6 address must be tuple, not %.500s", - Py_TYPE(args)->tp_name); - return 0; - } - if (!PyArg_ParseTuple(args, "eti|ii", - "idna", &host, &port, &flowinfo, - &scope_id)) { - return 0; - } - addr = (struct sockaddr_in6*)addr_ret; - result = setipaddr(host, (struct sockaddr *)addr, - sizeof(*addr), AF_INET6); - PyMem_Free(host); - if (result < 0) - return 0; - if (port < 0 || port > 0xffff) { - PyErr_SetString( - PyExc_OverflowError, - "getsockaddrarg: port must be 0-65535."); - return 0; - } - addr->sin6_family = s->sock_family; - addr->sin6_port = htons((short)port); - addr->sin6_flowinfo = flowinfo; - addr->sin6_scope_id = scope_id; - *len_ret = sizeof *addr; - return 1; - } + case AF_INET6: + { + struct sockaddr_in6* addr; + char *host; + int port, flowinfo, scope_id, result; + flowinfo = scope_id = 0; + if (!PyTuple_Check(args)) { + PyErr_Format( + PyExc_TypeError, + "getsockaddrarg: " + "AF_INET6 address must be tuple, not %.500s", + Py_TYPE(args)->tp_name); + return 0; + } + if (!PyArg_ParseTuple(args, "eti|ii", + "idna", &host, &port, &flowinfo, + &scope_id)) { + return 0; + } + addr = (struct sockaddr_in6*)addr_ret; + result = setipaddr(host, (struct sockaddr *)addr, + sizeof(*addr), AF_INET6); + PyMem_Free(host); + if (result < 0) + return 0; + if (port < 0 || port > 0xffff) { + PyErr_SetString( + PyExc_OverflowError, + "getsockaddrarg: port must be 0-65535."); + return 0; + } + addr->sin6_family = s->sock_family; + addr->sin6_port = htons((short)port); + addr->sin6_flowinfo = flowinfo; + addr->sin6_scope_id = scope_id; + *len_ret = sizeof *addr; + return 1; + } #endif #ifdef USE_BLUETOOTH - case AF_BLUETOOTH: - { - switch (s->sock_proto) { - case BTPROTO_L2CAP: - { - struct sockaddr_l2 *addr; - char *straddr; - - addr = (struct sockaddr_l2 *)addr_ret; - memset(addr, 0, sizeof(struct sockaddr_l2)); - _BT_L2_MEMB(addr, family) = AF_BLUETOOTH; - if (!PyArg_ParseTuple(args, "si", &straddr, - &_BT_L2_MEMB(addr, psm))) { - PyErr_SetString(socket_error, "getsockaddrarg: " - "wrong format"); - return 0; - } - if (setbdaddr(straddr, &_BT_L2_MEMB(addr, bdaddr)) < 0) - return 0; - - *len_ret = sizeof *addr; - return 1; - } - case BTPROTO_RFCOMM: - { - struct sockaddr_rc *addr; - char *straddr; - - addr = (struct sockaddr_rc *)addr_ret; - _BT_RC_MEMB(addr, family) = AF_BLUETOOTH; - if (!PyArg_ParseTuple(args, "si", &straddr, - &_BT_RC_MEMB(addr, channel))) { - PyErr_SetString(socket_error, "getsockaddrarg: " - "wrong format"); - return 0; - } - if (setbdaddr(straddr, &_BT_RC_MEMB(addr, bdaddr)) < 0) - return 0; - - *len_ret = sizeof *addr; - return 1; - } - case BTPROTO_HCI: - { - struct sockaddr_hci *addr = (struct sockaddr_hci *)addr_ret; - _BT_HCI_MEMB(addr, family) = AF_BLUETOOTH; - if (!PyArg_ParseTuple(args, "i", &_BT_HCI_MEMB(addr, dev))) { - PyErr_SetString(socket_error, "getsockaddrarg: " - "wrong format"); - return 0; - } - *len_ret = sizeof *addr; - return 1; - } + case AF_BLUETOOTH: + { + switch (s->sock_proto) { + case BTPROTO_L2CAP: + { + struct sockaddr_l2 *addr; + char *straddr; + + addr = (struct sockaddr_l2 *)addr_ret; + memset(addr, 0, sizeof(struct sockaddr_l2)); + _BT_L2_MEMB(addr, family) = AF_BLUETOOTH; + if (!PyArg_ParseTuple(args, "si", &straddr, + &_BT_L2_MEMB(addr, psm))) { + PyErr_SetString(socket_error, "getsockaddrarg: " + "wrong format"); + return 0; + } + if (setbdaddr(straddr, &_BT_L2_MEMB(addr, bdaddr)) < 0) + return 0; + + *len_ret = sizeof *addr; + return 1; + } + case BTPROTO_RFCOMM: + { + struct sockaddr_rc *addr; + char *straddr; + + addr = (struct sockaddr_rc *)addr_ret; + _BT_RC_MEMB(addr, family) = AF_BLUETOOTH; + if (!PyArg_ParseTuple(args, "si", &straddr, + &_BT_RC_MEMB(addr, channel))) { + PyErr_SetString(socket_error, "getsockaddrarg: " + "wrong format"); + return 0; + } + if (setbdaddr(straddr, &_BT_RC_MEMB(addr, bdaddr)) < 0) + return 0; + + *len_ret = sizeof *addr; + return 1; + } + case BTPROTO_HCI: + { + struct sockaddr_hci *addr = (struct sockaddr_hci *)addr_ret; + _BT_HCI_MEMB(addr, family) = AF_BLUETOOTH; + if (!PyArg_ParseTuple(args, "i", &_BT_HCI_MEMB(addr, dev))) { + PyErr_SetString(socket_error, "getsockaddrarg: " + "wrong format"); + return 0; + } + *len_ret = sizeof *addr; + return 1; + } #if !defined(__FreeBSD__) - case BTPROTO_SCO: - { - struct sockaddr_sco *addr; - char *straddr; - - addr = (struct sockaddr_sco *)addr_ret; - _BT_SCO_MEMB(addr, family) = AF_BLUETOOTH; - if (!PyBytes_Check(args)) { - PyErr_SetString(socket_error, "getsockaddrarg: " - "wrong format"); - return 0; - } - straddr = PyBytes_AS_STRING(args); - if (setbdaddr(straddr, &_BT_SCO_MEMB(addr, bdaddr)) < 0) - return 0; - - *len_ret = sizeof *addr; - return 1; - } -#endif - default: - PyErr_SetString(socket_error, "getsockaddrarg: unknown Bluetooth protocol"); - return 0; - } - } + case BTPROTO_SCO: + { + struct sockaddr_sco *addr; + char *straddr; + + addr = (struct sockaddr_sco *)addr_ret; + _BT_SCO_MEMB(addr, family) = AF_BLUETOOTH; + if (!PyBytes_Check(args)) { + PyErr_SetString(socket_error, "getsockaddrarg: " + "wrong format"); + return 0; + } + straddr = PyBytes_AS_STRING(args); + if (setbdaddr(straddr, &_BT_SCO_MEMB(addr, bdaddr)) < 0) + return 0; + + *len_ret = sizeof *addr; + return 1; + } +#endif + default: + PyErr_SetString(socket_error, "getsockaddrarg: unknown Bluetooth protocol"); + return 0; + } + } #endif #ifdef HAVE_NETPACKET_PACKET_H - case AF_PACKET: - { - struct sockaddr_ll* addr; - struct ifreq ifr; - char *interfaceName; - int protoNumber; - int hatype = 0; - int pkttype = 0; - char *haddr = NULL; - unsigned int halen = 0; - - if (!PyTuple_Check(args)) { - PyErr_Format( - PyExc_TypeError, - "getsockaddrarg: " - "AF_PACKET address must be tuple, not %.500s", - Py_TYPE(args)->tp_name); - return 0; - } - if (!PyArg_ParseTuple(args, "si|iiy#", &interfaceName, - &protoNumber, &pkttype, &hatype, - &haddr, &halen)) - return 0; - strncpy(ifr.ifr_name, interfaceName, sizeof(ifr.ifr_name)); - ifr.ifr_name[(sizeof(ifr.ifr_name))-1] = '\0'; - if (ioctl(s->sock_fd, SIOCGIFINDEX, &ifr) < 0) { - s->errorhandler(); - return 0; - } - if (halen > 8) { - PyErr_SetString(PyExc_ValueError, - "Hardware address must be 8 bytes or less"); - return 0; - } - if (protoNumber < 0 || protoNumber > 0xffff) { - PyErr_SetString( - PyExc_OverflowError, - "getsockaddrarg: protoNumber must be 0-65535."); - return 0; - } - addr = (struct sockaddr_ll*)addr_ret; - addr->sll_family = AF_PACKET; - addr->sll_protocol = htons((short)protoNumber); - addr->sll_ifindex = ifr.ifr_ifindex; - addr->sll_pkttype = pkttype; - addr->sll_hatype = hatype; - if (halen != 0) { - memcpy(&addr->sll_addr, haddr, halen); - } - addr->sll_halen = halen; - *len_ret = sizeof *addr; - return 1; - } + case AF_PACKET: + { + struct sockaddr_ll* addr; + struct ifreq ifr; + char *interfaceName; + int protoNumber; + int hatype = 0; + int pkttype = 0; + char *haddr = NULL; + unsigned int halen = 0; + + if (!PyTuple_Check(args)) { + PyErr_Format( + PyExc_TypeError, + "getsockaddrarg: " + "AF_PACKET address must be tuple, not %.500s", + Py_TYPE(args)->tp_name); + return 0; + } + if (!PyArg_ParseTuple(args, "si|iiy#", &interfaceName, + &protoNumber, &pkttype, &hatype, + &haddr, &halen)) + return 0; + strncpy(ifr.ifr_name, interfaceName, sizeof(ifr.ifr_name)); + ifr.ifr_name[(sizeof(ifr.ifr_name))-1] = '\0'; + if (ioctl(s->sock_fd, SIOCGIFINDEX, &ifr) < 0) { + s->errorhandler(); + return 0; + } + if (halen > 8) { + PyErr_SetString(PyExc_ValueError, + "Hardware address must be 8 bytes or less"); + return 0; + } + if (protoNumber < 0 || protoNumber > 0xffff) { + PyErr_SetString( + PyExc_OverflowError, + "getsockaddrarg: protoNumber must be 0-65535."); + return 0; + } + addr = (struct sockaddr_ll*)addr_ret; + addr->sll_family = AF_PACKET; + addr->sll_protocol = htons((short)protoNumber); + addr->sll_ifindex = ifr.ifr_ifindex; + addr->sll_pkttype = pkttype; + addr->sll_hatype = hatype; + if (halen != 0) { + memcpy(&addr->sll_addr, haddr, halen); + } + addr->sll_halen = halen; + *len_ret = sizeof *addr; + return 1; + } #endif #ifdef HAVE_LINUX_TIPC_H - case AF_TIPC: - { - unsigned int atype, v1, v2, v3; - unsigned int scope = TIPC_CLUSTER_SCOPE; - struct sockaddr_tipc *addr; - - if (!PyTuple_Check(args)) { - PyErr_Format( - PyExc_TypeError, - "getsockaddrarg: " - "AF_TIPC address must be tuple, not %.500s", - Py_TYPE(args)->tp_name); - return 0; - } - - if (!PyArg_ParseTuple(args, - "IIII|I;Invalid TIPC address format", - &atype, &v1, &v2, &v3, &scope)) - return 0; - - addr = (struct sockaddr_tipc *) addr_ret; - memset(addr, 0, sizeof(struct sockaddr_tipc)); - - addr->family = AF_TIPC; - addr->scope = scope; - addr->addrtype = atype; - - if (atype == TIPC_ADDR_NAMESEQ) { - addr->addr.nameseq.type = v1; - addr->addr.nameseq.lower = v2; - addr->addr.nameseq.upper = v3; - } else if (atype == TIPC_ADDR_NAME) { - addr->addr.name.name.type = v1; - addr->addr.name.name.instance = v2; - } else if (atype == TIPC_ADDR_ID) { - addr->addr.id.node = v1; - addr->addr.id.ref = v2; - } else { - /* Shouldn't happen */ - PyErr_SetString(PyExc_TypeError, "Invalid address type"); - return 0; - } - - *len_ret = sizeof(*addr); - - return 1; - } -#endif - - /* More cases here... */ - - default: - PyErr_SetString(socket_error, "getsockaddrarg: bad family"); - return 0; + case AF_TIPC: + { + unsigned int atype, v1, v2, v3; + unsigned int scope = TIPC_CLUSTER_SCOPE; + struct sockaddr_tipc *addr; + + if (!PyTuple_Check(args)) { + PyErr_Format( + PyExc_TypeError, + "getsockaddrarg: " + "AF_TIPC address must be tuple, not %.500s", + Py_TYPE(args)->tp_name); + return 0; + } + + if (!PyArg_ParseTuple(args, + "IIII|I;Invalid TIPC address format", + &atype, &v1, &v2, &v3, &scope)) + return 0; + + addr = (struct sockaddr_tipc *) addr_ret; + memset(addr, 0, sizeof(struct sockaddr_tipc)); + + addr->family = AF_TIPC; + addr->scope = scope; + addr->addrtype = atype; + + if (atype == TIPC_ADDR_NAMESEQ) { + addr->addr.nameseq.type = v1; + addr->addr.nameseq.lower = v2; + addr->addr.nameseq.upper = v3; + } else if (atype == TIPC_ADDR_NAME) { + addr->addr.name.name.type = v1; + addr->addr.name.name.instance = v2; + } else if (atype == TIPC_ADDR_ID) { + addr->addr.id.node = v1; + addr->addr.id.ref = v2; + } else { + /* Shouldn't happen */ + PyErr_SetString(PyExc_TypeError, "Invalid address type"); + return 0; + } + + *len_ret = sizeof(*addr); + + return 1; + } +#endif + + /* More cases here... */ + + default: + PyErr_SetString(socket_error, "getsockaddrarg: bad family"); + return 0; - } + } } @@ -1486,89 +1486,89 @@ static int getsockaddrlen(PySocketSockObject *s, socklen_t *len_ret) { - switch (s->sock_family) { + switch (s->sock_family) { #if defined(AF_UNIX) - case AF_UNIX: - { - *len_ret = sizeof (struct sockaddr_un); - return 1; - } + case AF_UNIX: + { + *len_ret = sizeof (struct sockaddr_un); + return 1; + } #endif /* AF_UNIX */ #if defined(AF_NETLINK) case AF_NETLINK: { - *len_ret = sizeof (struct sockaddr_nl); - return 1; + *len_ret = sizeof (struct sockaddr_nl); + return 1; } #endif - case AF_INET: - { - *len_ret = sizeof (struct sockaddr_in); - return 1; - } + case AF_INET: + { + *len_ret = sizeof (struct sockaddr_in); + return 1; + } #ifdef ENABLE_IPV6 - case AF_INET6: - { - *len_ret = sizeof (struct sockaddr_in6); - return 1; - } + case AF_INET6: + { + *len_ret = sizeof (struct sockaddr_in6); + return 1; + } #endif #ifdef USE_BLUETOOTH - case AF_BLUETOOTH: - { - switch(s->sock_proto) - { - - case BTPROTO_L2CAP: - *len_ret = sizeof (struct sockaddr_l2); - return 1; - case BTPROTO_RFCOMM: - *len_ret = sizeof (struct sockaddr_rc); - return 1; - case BTPROTO_HCI: - *len_ret = sizeof (struct sockaddr_hci); - return 1; + case AF_BLUETOOTH: + { + switch(s->sock_proto) + { + + case BTPROTO_L2CAP: + *len_ret = sizeof (struct sockaddr_l2); + return 1; + case BTPROTO_RFCOMM: + *len_ret = sizeof (struct sockaddr_rc); + return 1; + case BTPROTO_HCI: + *len_ret = sizeof (struct sockaddr_hci); + return 1; #if !defined(__FreeBSD__) - case BTPROTO_SCO: - *len_ret = sizeof (struct sockaddr_sco); - return 1; -#endif - default: - PyErr_SetString(socket_error, "getsockaddrlen: " - "unknown BT protocol"); - return 0; + case BTPROTO_SCO: + *len_ret = sizeof (struct sockaddr_sco); + return 1; +#endif + default: + PyErr_SetString(socket_error, "getsockaddrlen: " + "unknown BT protocol"); + return 0; - } - } + } + } #endif #ifdef HAVE_NETPACKET_PACKET_H - case AF_PACKET: - { - *len_ret = sizeof (struct sockaddr_ll); - return 1; - } + case AF_PACKET: + { + *len_ret = sizeof (struct sockaddr_ll); + return 1; + } #endif #ifdef HAVE_LINUX_TIPC_H - case AF_TIPC: - { - *len_ret = sizeof (struct sockaddr_tipc); - return 1; - } + case AF_TIPC: + { + *len_ret = sizeof (struct sockaddr_tipc); + return 1; + } #endif - /* More cases here... */ + /* More cases here... */ - default: - PyErr_SetString(socket_error, "getsockaddrlen: bad family"); - return 0; + default: + PyErr_SetString(socket_error, "getsockaddrlen: bad family"); + return 0; - } + } } @@ -1577,52 +1577,52 @@ static PyObject * sock_accept(PySocketSockObject *s) { - sock_addr_t addrbuf; - SOCKET_T newfd = INVALID_SOCKET; - socklen_t addrlen; - PyObject *sock = NULL; - PyObject *addr = NULL; - PyObject *res = NULL; - int timeout; - - if (!getsockaddrlen(s, &addrlen)) - return NULL; - memset(&addrbuf, 0, addrlen); - - if (!IS_SELECTABLE(s)) - return select_error(); - - Py_BEGIN_ALLOW_THREADS - timeout = internal_select(s, 0); - if (!timeout) - newfd = accept(s->sock_fd, SAS2SA(&addrbuf), &addrlen); - Py_END_ALLOW_THREADS - - if (timeout == 1) { - PyErr_SetString(socket_timeout, "timed out"); - return NULL; - } - - if (newfd == INVALID_SOCKET) - return s->errorhandler(); - - sock = PyLong_FromSocket_t(newfd); - if (sock == NULL) { - SOCKETCLOSE(newfd); - goto finally; - } - - addr = makesockaddr(s->sock_fd, SAS2SA(&addrbuf), - addrlen, s->sock_proto); - if (addr == NULL) - goto finally; + sock_addr_t addrbuf; + SOCKET_T newfd = INVALID_SOCKET; + socklen_t addrlen; + PyObject *sock = NULL; + PyObject *addr = NULL; + PyObject *res = NULL; + int timeout; + + if (!getsockaddrlen(s, &addrlen)) + return NULL; + memset(&addrbuf, 0, addrlen); + + if (!IS_SELECTABLE(s)) + return select_error(); + + Py_BEGIN_ALLOW_THREADS + timeout = internal_select(s, 0); + if (!timeout) + newfd = accept(s->sock_fd, SAS2SA(&addrbuf), &addrlen); + Py_END_ALLOW_THREADS + + if (timeout == 1) { + PyErr_SetString(socket_timeout, "timed out"); + return NULL; + } + + if (newfd == INVALID_SOCKET) + return s->errorhandler(); + + sock = PyLong_FromSocket_t(newfd); + if (sock == NULL) { + SOCKETCLOSE(newfd); + goto finally; + } + + addr = makesockaddr(s->sock_fd, SAS2SA(&addrbuf), + addrlen, s->sock_proto); + if (addr == NULL) + goto finally; - res = PyTuple_Pack(2, sock, addr); + res = PyTuple_Pack(2, sock, addr); finally: - Py_XDECREF(sock); - Py_XDECREF(addr); - return res; + Py_XDECREF(sock); + Py_XDECREF(addr); + return res; } PyDoc_STRVAR(accept_doc, @@ -1640,17 +1640,17 @@ static PyObject * sock_setblocking(PySocketSockObject *s, PyObject *arg) { - int block; + int block; - block = PyLong_AsLong(arg); - if (block == -1 && PyErr_Occurred()) - return NULL; + block = PyLong_AsLong(arg); + if (block == -1 && PyErr_Occurred()) + return NULL; - s->sock_timeout = block ? -1.0 : 0.0; - internal_setblocking(s, block); + s->sock_timeout = block ? -1.0 : 0.0; + internal_setblocking(s, block); - Py_INCREF(Py_None); - return Py_None; + Py_INCREF(Py_None); + return Py_None; } PyDoc_STRVAR(setblocking_doc, @@ -1669,25 +1669,25 @@ static PyObject * sock_settimeout(PySocketSockObject *s, PyObject *arg) { - double timeout; + double timeout; - if (arg == Py_None) - timeout = -1.0; - else { - timeout = PyFloat_AsDouble(arg); - if (timeout < 0.0) { - if (!PyErr_Occurred()) - PyErr_SetString(PyExc_ValueError, - "Timeout value out of range"); - return NULL; - } - } + if (arg == Py_None) + timeout = -1.0; + else { + timeout = PyFloat_AsDouble(arg); + if (timeout < 0.0) { + if (!PyErr_Occurred()) + PyErr_SetString(PyExc_ValueError, + "Timeout value out of range"); + return NULL; + } + } - s->sock_timeout = timeout; - internal_setblocking(s, timeout < 0.0); + s->sock_timeout = timeout; + internal_setblocking(s, timeout < 0.0); - Py_INCREF(Py_None); - return Py_None; + Py_INCREF(Py_None); + return Py_None; } PyDoc_STRVAR(settimeout_doc, @@ -1703,12 +1703,12 @@ static PyObject * sock_gettimeout(PySocketSockObject *s) { - if (s->sock_timeout < 0.0) { - Py_INCREF(Py_None); - return Py_None; - } - else - return PyFloat_FromDouble(s->sock_timeout); + if (s->sock_timeout < 0.0) { + Py_INCREF(Py_None); + return Py_None; + } + else + return PyFloat_FromDouble(s->sock_timeout); } PyDoc_STRVAR(gettimeout_doc, @@ -1726,29 +1726,29 @@ static PyObject * sock_setsockopt(PySocketSockObject *s, PyObject *args) { - int level; - int optname; - int res; - char *buf; - int buflen; - int flag; - - if (PyArg_ParseTuple(args, "iii:setsockopt", - &level, &optname, &flag)) { - buf = (char *) &flag; - buflen = sizeof flag; - } - else { - PyErr_Clear(); - if (!PyArg_ParseTuple(args, "iiy#:setsockopt", - &level, &optname, &buf, &buflen)) - return NULL; - } - res = setsockopt(s->sock_fd, level, optname, (void *)buf, buflen); - if (res < 0) - return s->errorhandler(); - Py_INCREF(Py_None); - return Py_None; + int level; + int optname; + int res; + char *buf; + int buflen; + int flag; + + if (PyArg_ParseTuple(args, "iii:setsockopt", + &level, &optname, &flag)) { + buf = (char *) &flag; + buflen = sizeof flag; + } + else { + PyErr_Clear(); + if (!PyArg_ParseTuple(args, "iiy#:setsockopt", + &level, &optname, &buf, &buflen)) + return NULL; + } + res = setsockopt(s->sock_fd, level, optname, (void *)buf, buflen); + if (res < 0) + return s->errorhandler(); + Py_INCREF(Py_None); + return Py_None; } PyDoc_STRVAR(setsockopt_doc, @@ -1766,47 +1766,47 @@ static PyObject * sock_getsockopt(PySocketSockObject *s, PyObject *args) { - int level; - int optname; - int res; - PyObject *buf; - socklen_t buflen = 0; - - if (!PyArg_ParseTuple(args, "ii|i:getsockopt", - &level, &optname, &buflen)) - return NULL; - - if (buflen == 0) { - int flag = 0; - socklen_t flagsize = sizeof flag; - res = getsockopt(s->sock_fd, level, optname, - (void *)&flag, &flagsize); - if (res < 0) - return s->errorhandler(); - return PyLong_FromLong(flag); - } + int level; + int optname; + int res; + PyObject *buf; + socklen_t buflen = 0; + + if (!PyArg_ParseTuple(args, "ii|i:getsockopt", + &level, &optname, &buflen)) + return NULL; + + if (buflen == 0) { + int flag = 0; + socklen_t flagsize = sizeof flag; + res = getsockopt(s->sock_fd, level, optname, + (void *)&flag, &flagsize); + if (res < 0) + return s->errorhandler(); + return PyLong_FromLong(flag); + } #ifdef __VMS - /* socklen_t is unsigned so no negative test is needed, - test buflen == 0 is previously done */ - if (buflen > 1024) { -#else - if (buflen <= 0 || buflen > 1024) { -#endif - PyErr_SetString(socket_error, - "getsockopt buflen out of range"); - return NULL; - } - buf = PyBytes_FromStringAndSize((char *)NULL, buflen); - if (buf == NULL) - return NULL; - res = getsockopt(s->sock_fd, level, optname, - (void *)PyBytes_AS_STRING(buf), &buflen); - if (res < 0) { - Py_DECREF(buf); - return s->errorhandler(); - } - _PyBytes_Resize(&buf, buflen); - return buf; + /* socklen_t is unsigned so no negative test is needed, + test buflen == 0 is previously done */ + if (buflen > 1024) { +#else + if (buflen <= 0 || buflen > 1024) { +#endif + PyErr_SetString(socket_error, + "getsockopt buflen out of range"); + return NULL; + } + buf = PyBytes_FromStringAndSize((char *)NULL, buflen); + if (buf == NULL) + return NULL; + res = getsockopt(s->sock_fd, level, optname, + (void *)PyBytes_AS_STRING(buf), &buflen); + if (res < 0) { + Py_DECREF(buf); + return s->errorhandler(); + } + _PyBytes_Resize(&buf, buflen); + return buf; } PyDoc_STRVAR(getsockopt_doc, @@ -1822,19 +1822,19 @@ static PyObject * sock_bind(PySocketSockObject *s, PyObject *addro) { - sock_addr_t addrbuf; - int addrlen; - int res; - - if (!getsockaddrarg(s, addro, SAS2SA(&addrbuf), &addrlen)) - return NULL; - Py_BEGIN_ALLOW_THREADS - res = bind(s->sock_fd, SAS2SA(&addrbuf), addrlen); - Py_END_ALLOW_THREADS - if (res < 0) - return s->errorhandler(); - Py_INCREF(Py_None); - return Py_None; + sock_addr_t addrbuf; + int addrlen; + int res; + + if (!getsockaddrarg(s, addro, SAS2SA(&addrbuf), &addrlen)) + return NULL; + Py_BEGIN_ALLOW_THREADS + res = bind(s->sock_fd, SAS2SA(&addrbuf), addrlen); + Py_END_ALLOW_THREADS + if (res < 0) + return s->errorhandler(); + Py_INCREF(Py_None); + return Py_None; } PyDoc_STRVAR(bind_doc, @@ -1852,16 +1852,16 @@ static PyObject * sock_close(PySocketSockObject *s) { - SOCKET_T fd; + SOCKET_T fd; - if ((fd = s->sock_fd) != -1) { - s->sock_fd = -1; - Py_BEGIN_ALLOW_THREADS - (void) SOCKETCLOSE(fd); - Py_END_ALLOW_THREADS - } - Py_INCREF(Py_None); - return Py_None; + if ((fd = s->sock_fd) != -1) { + s->sock_fd = -1; + Py_BEGIN_ALLOW_THREADS + (void) SOCKETCLOSE(fd); + Py_END_ALLOW_THREADS + } + Py_INCREF(Py_None); + return Py_None; } PyDoc_STRVAR(close_doc, @@ -1871,90 +1871,90 @@ static int internal_connect(PySocketSockObject *s, struct sockaddr *addr, int addrlen, - int *timeoutp) + int *timeoutp) { - int res, timeout; + int res, timeout; - timeout = 0; - res = connect(s->sock_fd, addr, addrlen); + timeout = 0; + res = connect(s->sock_fd, addr, addrlen); #ifdef MS_WINDOWS - if (s->sock_timeout > 0.0) { - if (res < 0 && WSAGetLastError() == WSAEWOULDBLOCK && - IS_SELECTABLE(s)) { - /* This is a mess. Best solution: trust select */ - fd_set fds; - fd_set fds_exc; - struct timeval tv; - tv.tv_sec = (int)s->sock_timeout; - tv.tv_usec = (int)((s->sock_timeout - tv.tv_sec) * 1e6); - FD_ZERO(&fds); - FD_SET(s->sock_fd, &fds); - FD_ZERO(&fds_exc); - FD_SET(s->sock_fd, &fds_exc); - res = select(s->sock_fd+1, NULL, &fds, &fds_exc, &tv); - if (res == 0) { - res = WSAEWOULDBLOCK; - timeout = 1; - } else if (res > 0) { - if (FD_ISSET(s->sock_fd, &fds)) - /* The socket is in the writable set - this - means connected */ - res = 0; - else { - /* As per MS docs, we need to call getsockopt() - to get the underlying error */ - int res_size = sizeof res; - /* It must be in the exception set */ - assert(FD_ISSET(s->sock_fd, &fds_exc)); - if (0 == getsockopt(s->sock_fd, SOL_SOCKET, SO_ERROR, - (char *)&res, &res_size)) - /* getsockopt also clears WSAGetLastError, - so reset it back. */ - WSASetLastError(res); - else - res = WSAGetLastError(); - } - } - /* else if (res < 0) an error occurred */ - } - } - - if (res < 0) - res = WSAGetLastError(); - -#else - - if (s->sock_timeout > 0.0) { - if (res < 0 && errno == EINPROGRESS && IS_SELECTABLE(s)) { - timeout = internal_select(s, 1); - if (timeout == 0) { - /* Bug #1019808: in case of an EINPROGRESS, - use getsockopt(SO_ERROR) to get the real - error. */ - socklen_t res_size = sizeof res; - (void)getsockopt(s->sock_fd, SOL_SOCKET, - SO_ERROR, &res, &res_size); - if (res == EISCONN) - res = 0; - errno = res; - } - else if (timeout == -1) { - res = errno; /* had error */ - } - else - res = EWOULDBLOCK; /* timed out */ - } - } + if (s->sock_timeout > 0.0) { + if (res < 0 && WSAGetLastError() == WSAEWOULDBLOCK && + IS_SELECTABLE(s)) { + /* This is a mess. Best solution: trust select */ + fd_set fds; + fd_set fds_exc; + struct timeval tv; + tv.tv_sec = (int)s->sock_timeout; + tv.tv_usec = (int)((s->sock_timeout - tv.tv_sec) * 1e6); + FD_ZERO(&fds); + FD_SET(s->sock_fd, &fds); + FD_ZERO(&fds_exc); + FD_SET(s->sock_fd, &fds_exc); + res = select(s->sock_fd+1, NULL, &fds, &fds_exc, &tv); + if (res == 0) { + res = WSAEWOULDBLOCK; + timeout = 1; + } else if (res > 0) { + if (FD_ISSET(s->sock_fd, &fds)) + /* The socket is in the writable set - this + means connected */ + res = 0; + else { + /* As per MS docs, we need to call getsockopt() + to get the underlying error */ + int res_size = sizeof res; + /* It must be in the exception set */ + assert(FD_ISSET(s->sock_fd, &fds_exc)); + if (0 == getsockopt(s->sock_fd, SOL_SOCKET, SO_ERROR, + (char *)&res, &res_size)) + /* getsockopt also clears WSAGetLastError, + so reset it back. */ + WSASetLastError(res); + else + res = WSAGetLastError(); + } + } + /* else if (res < 0) an error occurred */ + } + } + + if (res < 0) + res = WSAGetLastError(); + +#else + + if (s->sock_timeout > 0.0) { + if (res < 0 && errno == EINPROGRESS && IS_SELECTABLE(s)) { + timeout = internal_select(s, 1); + if (timeout == 0) { + /* Bug #1019808: in case of an EINPROGRESS, + use getsockopt(SO_ERROR) to get the real + error. */ + socklen_t res_size = sizeof res; + (void)getsockopt(s->sock_fd, SOL_SOCKET, + SO_ERROR, &res, &res_size); + if (res == EISCONN) + res = 0; + errno = res; + } + else if (timeout == -1) { + res = errno; /* had error */ + } + else + res = EWOULDBLOCK; /* timed out */ + } + } - if (res < 0) - res = errno; + if (res < 0) + res = errno; #endif - *timeoutp = timeout; + *timeoutp = timeout; - return res; + return res; } /* s.connect(sockaddr) method */ @@ -1962,26 +1962,26 @@ static PyObject * sock_connect(PySocketSockObject *s, PyObject *addro) { - sock_addr_t addrbuf; - int addrlen; - int res; - int timeout; - - if (!getsockaddrarg(s, addro, SAS2SA(&addrbuf), &addrlen)) - return NULL; - - Py_BEGIN_ALLOW_THREADS - res = internal_connect(s, SAS2SA(&addrbuf), addrlen, &timeout); - Py_END_ALLOW_THREADS - - if (timeout == 1) { - PyErr_SetString(socket_timeout, "timed out"); - return NULL; - } - if (res != 0) - return s->errorhandler(); - Py_INCREF(Py_None); - return Py_None; + sock_addr_t addrbuf; + int addrlen; + int res; + int timeout; + + if (!getsockaddrarg(s, addro, SAS2SA(&addrbuf), &addrlen)) + return NULL; + + Py_BEGIN_ALLOW_THREADS + res = internal_connect(s, SAS2SA(&addrbuf), addrlen, &timeout); + Py_END_ALLOW_THREADS + + if (timeout == 1) { + PyErr_SetString(socket_timeout, "timed out"); + return NULL; + } + if (res != 0) + return s->errorhandler(); + Py_INCREF(Py_None); + return Py_None; } PyDoc_STRVAR(connect_doc, @@ -1996,26 +1996,26 @@ static PyObject * sock_connect_ex(PySocketSockObject *s, PyObject *addro) { - sock_addr_t addrbuf; - int addrlen; - int res; - int timeout; - - if (!getsockaddrarg(s, addro, SAS2SA(&addrbuf), &addrlen)) - return NULL; - - Py_BEGIN_ALLOW_THREADS - res = internal_connect(s, SAS2SA(&addrbuf), addrlen, &timeout); - Py_END_ALLOW_THREADS + sock_addr_t addrbuf; + int addrlen; + int res; + int timeout; + + if (!getsockaddrarg(s, addro, SAS2SA(&addrbuf), &addrlen)) + return NULL; + + Py_BEGIN_ALLOW_THREADS + res = internal_connect(s, SAS2SA(&addrbuf), addrlen, &timeout); + Py_END_ALLOW_THREADS - /* Signals are not errors (though they may raise exceptions). Adapted - from PyErr_SetFromErrnoWithFilenameObject(). */ + /* Signals are not errors (though they may raise exceptions). Adapted + from PyErr_SetFromErrnoWithFilenameObject(). */ #ifdef EINTR - if (res == EINTR && PyErr_CheckSignals()) - return NULL; + if (res == EINTR && PyErr_CheckSignals()) + return NULL; #endif - return PyLong_FromLong((long) res); + return PyLong_FromLong((long) res); } PyDoc_STRVAR(connect_ex_doc, @@ -2030,7 +2030,7 @@ static PyObject * sock_fileno(PySocketSockObject *s) { - return PyLong_FromSocket_t(s->sock_fd); + return PyLong_FromSocket_t(s->sock_fd); } PyDoc_STRVAR(fileno_doc, @@ -2044,20 +2044,20 @@ static PyObject * sock_getsockname(PySocketSockObject *s) { - sock_addr_t addrbuf; - int res; - socklen_t addrlen; - - if (!getsockaddrlen(s, &addrlen)) - return NULL; - memset(&addrbuf, 0, addrlen); - Py_BEGIN_ALLOW_THREADS - res = getsockname(s->sock_fd, SAS2SA(&addrbuf), &addrlen); - Py_END_ALLOW_THREADS - if (res < 0) - return s->errorhandler(); - return makesockaddr(s->sock_fd, SAS2SA(&addrbuf), addrlen, - s->sock_proto); + sock_addr_t addrbuf; + int res; + socklen_t addrlen; + + if (!getsockaddrlen(s, &addrlen)) + return NULL; + memset(&addrbuf, 0, addrlen); + Py_BEGIN_ALLOW_THREADS + res = getsockname(s->sock_fd, SAS2SA(&addrbuf), &addrlen); + Py_END_ALLOW_THREADS + if (res < 0) + return s->errorhandler(); + return makesockaddr(s->sock_fd, SAS2SA(&addrbuf), addrlen, + s->sock_proto); } PyDoc_STRVAR(getsockname_doc, @@ -2067,26 +2067,26 @@ info is a pair (hostaddr, port)."); -#ifdef HAVE_GETPEERNAME /* Cray APP doesn't have this :-( */ +#ifdef HAVE_GETPEERNAME /* Cray APP doesn't have this :-( */ /* s.getpeername() method */ static PyObject * sock_getpeername(PySocketSockObject *s) { - sock_addr_t addrbuf; - int res; - socklen_t addrlen; - - if (!getsockaddrlen(s, &addrlen)) - return NULL; - memset(&addrbuf, 0, addrlen); - Py_BEGIN_ALLOW_THREADS - res = getpeername(s->sock_fd, SAS2SA(&addrbuf), &addrlen); - Py_END_ALLOW_THREADS - if (res < 0) - return s->errorhandler(); - return makesockaddr(s->sock_fd, SAS2SA(&addrbuf), addrlen, - s->sock_proto); + sock_addr_t addrbuf; + int res; + socklen_t addrlen; + + if (!getsockaddrlen(s, &addrlen)) + return NULL; + memset(&addrbuf, 0, addrlen); + Py_BEGIN_ALLOW_THREADS + res = getpeername(s->sock_fd, SAS2SA(&addrbuf), &addrlen); + Py_END_ALLOW_THREADS + if (res < 0) + return s->errorhandler(); + return makesockaddr(s->sock_fd, SAS2SA(&addrbuf), addrlen, + s->sock_proto); } PyDoc_STRVAR(getpeername_doc, @@ -2103,21 +2103,21 @@ static PyObject * sock_listen(PySocketSockObject *s, PyObject *arg) { - int backlog; - int res; + int backlog; + int res; - backlog = PyLong_AsLong(arg); - if (backlog == -1 && PyErr_Occurred()) - return NULL; - Py_BEGIN_ALLOW_THREADS - if (backlog < 1) - backlog = 1; - res = listen(s->sock_fd, backlog); - Py_END_ALLOW_THREADS - if (res < 0) - return s->errorhandler(); - Py_INCREF(Py_None); - return Py_None; + backlog = PyLong_AsLong(arg); + if (backlog == -1 && PyErr_Occurred()) + return NULL; + Py_BEGIN_ALLOW_THREADS + if (backlog < 1) + backlog = 1; + res = listen(s->sock_fd, backlog); + Py_END_ALLOW_THREADS + if (res < 0) + return s->errorhandler(); + Py_INCREF(Py_None); + return Py_None; } PyDoc_STRVAR(listen_doc, @@ -2139,80 +2139,80 @@ static ssize_t sock_recv_guts(PySocketSockObject *s, char* cbuf, int len, int flags) { - ssize_t outlen = -1; - int timeout; + ssize_t outlen = -1; + int timeout; #ifdef __VMS - int remaining; - char *read_buf; + int remaining; + char *read_buf; #endif - if (!IS_SELECTABLE(s)) { - select_error(); - return -1; - } - if (len == 0) { - /* If 0 bytes were requested, do nothing. */ - return 0; - } + if (!IS_SELECTABLE(s)) { + select_error(); + return -1; + } + if (len == 0) { + /* If 0 bytes were requested, do nothing. */ + return 0; + } #ifndef __VMS - Py_BEGIN_ALLOW_THREADS - timeout = internal_select(s, 0); - if (!timeout) - outlen = recv(s->sock_fd, cbuf, len, flags); - Py_END_ALLOW_THREADS - - if (timeout == 1) { - PyErr_SetString(socket_timeout, "timed out"); - return -1; - } - if (outlen < 0) { - /* Note: the call to errorhandler() ALWAYS indirectly returned - NULL, so ignore its return value */ - s->errorhandler(); - return -1; - } -#else - read_buf = cbuf; - remaining = len; - while (remaining != 0) { - unsigned int segment; - int nread = -1; - - segment = remaining /SEGMENT_SIZE; - if (segment != 0) { - segment = SEGMENT_SIZE; - } - else { - segment = remaining; - } - - Py_BEGIN_ALLOW_THREADS - timeout = internal_select(s, 0); - if (!timeout) - nread = recv(s->sock_fd, read_buf, segment, flags); - Py_END_ALLOW_THREADS - - if (timeout == 1) { - PyErr_SetString(socket_timeout, "timed out"); - return -1; - } - if (nread < 0) { - s->errorhandler(); - return -1; - } - if (nread != remaining) { - read_buf += nread; - break; - } - - remaining -= segment; - read_buf += segment; - } - outlen = read_buf - cbuf; + Py_BEGIN_ALLOW_THREADS + timeout = internal_select(s, 0); + if (!timeout) + outlen = recv(s->sock_fd, cbuf, len, flags); + Py_END_ALLOW_THREADS + + if (timeout == 1) { + PyErr_SetString(socket_timeout, "timed out"); + return -1; + } + if (outlen < 0) { + /* Note: the call to errorhandler() ALWAYS indirectly returned + NULL, so ignore its return value */ + s->errorhandler(); + return -1; + } +#else + read_buf = cbuf; + remaining = len; + while (remaining != 0) { + unsigned int segment; + int nread = -1; + + segment = remaining /SEGMENT_SIZE; + if (segment != 0) { + segment = SEGMENT_SIZE; + } + else { + segment = remaining; + } + + Py_BEGIN_ALLOW_THREADS + timeout = internal_select(s, 0); + if (!timeout) + nread = recv(s->sock_fd, read_buf, segment, flags); + Py_END_ALLOW_THREADS + + if (timeout == 1) { + PyErr_SetString(socket_timeout, "timed out"); + return -1; + } + if (nread < 0) { + s->errorhandler(); + return -1; + } + if (nread != remaining) { + read_buf += nread; + break; + } + + remaining -= segment; + read_buf += segment; + } + outlen = read_buf - cbuf; #endif /* !__VMS */ - return outlen; + return outlen; } @@ -2221,39 +2221,39 @@ static PyObject * sock_recv(PySocketSockObject *s, PyObject *args) { - int recvlen, flags = 0; - ssize_t outlen; - PyObject *buf; - - if (!PyArg_ParseTuple(args, "i|i:recv", &recvlen, &flags)) - return NULL; - - if (recvlen < 0) { - PyErr_SetString(PyExc_ValueError, - "negative buffersize in recv"); - return NULL; - } - - /* Allocate a new string. */ - buf = PyBytes_FromStringAndSize((char *) 0, recvlen); - if (buf == NULL) - return NULL; - - /* Call the guts */ - outlen = sock_recv_guts(s, PyBytes_AS_STRING(buf), recvlen, flags); - if (outlen < 0) { - /* An error occurred, release the string and return an - error. */ - Py_DECREF(buf); - return NULL; - } - if (outlen != recvlen) { - /* We did not read as many bytes as we anticipated, resize the - string if possible and be successful. */ - _PyBytes_Resize(&buf, outlen); - } + int recvlen, flags = 0; + ssize_t outlen; + PyObject *buf; + + if (!PyArg_ParseTuple(args, "i|i:recv", &recvlen, &flags)) + return NULL; + + if (recvlen < 0) { + PyErr_SetString(PyExc_ValueError, + "negative buffersize in recv"); + return NULL; + } + + /* Allocate a new string. */ + buf = PyBytes_FromStringAndSize((char *) 0, recvlen); + if (buf == NULL) + return NULL; + + /* Call the guts */ + outlen = sock_recv_guts(s, PyBytes_AS_STRING(buf), recvlen, flags); + if (outlen < 0) { + /* An error occurred, release the string and return an + error. */ + Py_DECREF(buf); + return NULL; + } + if (outlen != recvlen) { + /* We did not read as many bytes as we anticipated, resize the + string if possible and be successful. */ + _PyBytes_Resize(&buf, outlen); + } - return buf; + return buf; } PyDoc_STRVAR(recv_doc, @@ -2270,52 +2270,52 @@ static PyObject* sock_recv_into(PySocketSockObject *s, PyObject *args, PyObject *kwds) { - static char *kwlist[] = {"buffer", "nbytes", "flags", 0}; + static char *kwlist[] = {"buffer", "nbytes", "flags", 0}; - int recvlen = 0, flags = 0; - ssize_t readlen; - Py_buffer pbuf; - char *buf; - int buflen; - - /* Get the buffer's memory */ - if (!PyArg_ParseTupleAndKeywords(args, kwds, "w*|ii:recv_into", kwlist, - &pbuf, &recvlen, &flags)) - return NULL; - buf = pbuf.buf; - buflen = pbuf.len; - - if (recvlen < 0) { - PyBuffer_Release(&pbuf); - PyErr_SetString(PyExc_ValueError, - "negative buffersize in recv_into"); - return NULL; - } - if (recvlen == 0) { - /* If nbytes was not specified, use the buffer's length */ - recvlen = buflen; - } - - /* Check if the buffer is large enough */ - if (buflen < recvlen) { - PyBuffer_Release(&pbuf); - PyErr_SetString(PyExc_ValueError, - "buffer too small for requested bytes"); - return NULL; - } - - /* Call the guts */ - readlen = sock_recv_guts(s, buf, recvlen, flags); - if (readlen < 0) { - /* Return an error. */ - PyBuffer_Release(&pbuf); - return NULL; - } - - PyBuffer_Release(&pbuf); - /* Return the number of bytes read. Note that we do not do anything - special here in the case that readlen < recvlen. */ - return PyLong_FromSsize_t(readlen); + int recvlen = 0, flags = 0; + ssize_t readlen; + Py_buffer pbuf; + char *buf; + int buflen; + + /* Get the buffer's memory */ + if (!PyArg_ParseTupleAndKeywords(args, kwds, "w*|ii:recv_into", kwlist, + &pbuf, &recvlen, &flags)) + return NULL; + buf = pbuf.buf; + buflen = pbuf.len; + + if (recvlen < 0) { + PyBuffer_Release(&pbuf); + PyErr_SetString(PyExc_ValueError, + "negative buffersize in recv_into"); + return NULL; + } + if (recvlen == 0) { + /* If nbytes was not specified, use the buffer's length */ + recvlen = buflen; + } + + /* Check if the buffer is large enough */ + if (buflen < recvlen) { + PyBuffer_Release(&pbuf); + PyErr_SetString(PyExc_ValueError, + "buffer too small for requested bytes"); + return NULL; + } + + /* Call the guts */ + readlen = sock_recv_guts(s, buf, recvlen, flags); + if (readlen < 0) { + /* Return an error. */ + PyBuffer_Release(&pbuf); + return NULL; + } + + PyBuffer_Release(&pbuf); + /* Return the number of bytes read. Note that we do not do anything + special here in the case that readlen < recvlen. */ + return PyLong_FromSsize_t(readlen); } PyDoc_STRVAR(recv_into_doc, @@ -2341,56 +2341,56 @@ */ static ssize_t sock_recvfrom_guts(PySocketSockObject *s, char* cbuf, int len, int flags, - PyObject** addr) + PyObject** addr) { - sock_addr_t addrbuf; - int timeout; - ssize_t n = -1; - socklen_t addrlen; - - *addr = NULL; - - if (!getsockaddrlen(s, &addrlen)) - return -1; - - if (!IS_SELECTABLE(s)) { - select_error(); - return -1; - } - - Py_BEGIN_ALLOW_THREADS - memset(&addrbuf, 0, addrlen); - timeout = internal_select(s, 0); - if (!timeout) { + sock_addr_t addrbuf; + int timeout; + ssize_t n = -1; + socklen_t addrlen; + + *addr = NULL; + + if (!getsockaddrlen(s, &addrlen)) + return -1; + + if (!IS_SELECTABLE(s)) { + select_error(); + return -1; + } + + Py_BEGIN_ALLOW_THREADS + memset(&addrbuf, 0, addrlen); + timeout = internal_select(s, 0); + if (!timeout) { #ifndef MS_WINDOWS #if defined(PYOS_OS2) && !defined(PYCC_GCC) - n = recvfrom(s->sock_fd, cbuf, len, flags, - SAS2SA(&addrbuf), &addrlen); + n = recvfrom(s->sock_fd, cbuf, len, flags, + SAS2SA(&addrbuf), &addrlen); #else - n = recvfrom(s->sock_fd, cbuf, len, flags, - (void *) &addrbuf, &addrlen); + n = recvfrom(s->sock_fd, cbuf, len, flags, + (void *) &addrbuf, &addrlen); #endif #else - n = recvfrom(s->sock_fd, cbuf, len, flags, - SAS2SA(&addrbuf), &addrlen); + n = recvfrom(s->sock_fd, cbuf, len, flags, + SAS2SA(&addrbuf), &addrlen); #endif - } - Py_END_ALLOW_THREADS + } + Py_END_ALLOW_THREADS - if (timeout == 1) { - PyErr_SetString(socket_timeout, "timed out"); - return -1; - } - if (n < 0) { - s->errorhandler(); - return -1; - } + if (timeout == 1) { + PyErr_SetString(socket_timeout, "timed out"); + return -1; + } + if (n < 0) { + s->errorhandler(); + return -1; + } - if (!(*addr = makesockaddr(s->sock_fd, SAS2SA(&addrbuf), - addrlen, s->sock_proto))) - return -1; + if (!(*addr = makesockaddr(s->sock_fd, SAS2SA(&addrbuf), + addrlen, s->sock_proto))) + return -1; - return n; + return n; } /* s.recvfrom(nbytes [,flags]) method */ @@ -2398,45 +2398,45 @@ static PyObject * sock_recvfrom(PySocketSockObject *s, PyObject *args) { - PyObject *buf = NULL; - PyObject *addr = NULL; - PyObject *ret = NULL; - int recvlen, flags = 0; - ssize_t outlen; - - if (!PyArg_ParseTuple(args, "i|i:recvfrom", &recvlen, &flags)) - return NULL; - - if (recvlen < 0) { - PyErr_SetString(PyExc_ValueError, - "negative buffersize in recvfrom"); - return NULL; - } - - buf = PyBytes_FromStringAndSize((char *) 0, recvlen); - if (buf == NULL) - return NULL; - - outlen = sock_recvfrom_guts(s, PyBytes_AS_STRING(buf), - recvlen, flags, &addr); - if (outlen < 0) { - goto finally; - } - - if (outlen != recvlen) { - /* We did not read as many bytes as we anticipated, resize the - string if possible and be succesful. */ - if (_PyBytes_Resize(&buf, outlen) < 0) - /* Oopsy, not so succesful after all. */ - goto finally; - } + PyObject *buf = NULL; + PyObject *addr = NULL; + PyObject *ret = NULL; + int recvlen, flags = 0; + ssize_t outlen; + + if (!PyArg_ParseTuple(args, "i|i:recvfrom", &recvlen, &flags)) + return NULL; + + if (recvlen < 0) { + PyErr_SetString(PyExc_ValueError, + "negative buffersize in recvfrom"); + return NULL; + } + + buf = PyBytes_FromStringAndSize((char *) 0, recvlen); + if (buf == NULL) + return NULL; + + outlen = sock_recvfrom_guts(s, PyBytes_AS_STRING(buf), + recvlen, flags, &addr); + if (outlen < 0) { + goto finally; + } + + if (outlen != recvlen) { + /* We did not read as many bytes as we anticipated, resize the + string if possible and be succesful. */ + if (_PyBytes_Resize(&buf, outlen) < 0) + /* Oopsy, not so succesful after all. */ + goto finally; + } - ret = PyTuple_Pack(2, buf, addr); + ret = PyTuple_Pack(2, buf, addr); finally: - Py_XDECREF(buf); - Py_XDECREF(addr); - return ret; + Py_XDECREF(buf); + Py_XDECREF(addr); + return ret; } PyDoc_STRVAR(recvfrom_doc, @@ -2450,47 +2450,47 @@ static PyObject * sock_recvfrom_into(PySocketSockObject *s, PyObject *args, PyObject* kwds) { - static char *kwlist[] = {"buffer", "nbytes", "flags", 0}; + static char *kwlist[] = {"buffer", "nbytes", "flags", 0}; - int recvlen = 0, flags = 0; - ssize_t readlen; - Py_buffer pbuf; - char *buf; - int buflen; - - PyObject *addr = NULL; - - if (!PyArg_ParseTupleAndKeywords(args, kwds, "w*|ii:recvfrom_into", - kwlist, &pbuf, - &recvlen, &flags)) - return NULL; - buf = pbuf.buf; - buflen = pbuf.len; - assert(buf != 0 && buflen > 0); - - if (recvlen < 0) { - PyBuffer_Release(&pbuf); - PyErr_SetString(PyExc_ValueError, - "negative buffersize in recvfrom_into"); - return NULL; - } - if (recvlen == 0) { - /* If nbytes was not specified, use the buffer's length */ - recvlen = buflen; - } - - readlen = sock_recvfrom_guts(s, buf, recvlen, flags, &addr); - if (readlen < 0) { - PyBuffer_Release(&pbuf); - /* Return an error */ - Py_XDECREF(addr); - return NULL; - } - - PyBuffer_Release(&pbuf); - /* Return the number of bytes read and the address. Note that we do - not do anything special here in the case that readlen < recvlen. */ - return Py_BuildValue("lN", readlen, addr); + int recvlen = 0, flags = 0; + ssize_t readlen; + Py_buffer pbuf; + char *buf; + int buflen; + + PyObject *addr = NULL; + + if (!PyArg_ParseTupleAndKeywords(args, kwds, "w*|ii:recvfrom_into", + kwlist, &pbuf, + &recvlen, &flags)) + return NULL; + buf = pbuf.buf; + buflen = pbuf.len; + assert(buf != 0 && buflen > 0); + + if (recvlen < 0) { + PyBuffer_Release(&pbuf); + PyErr_SetString(PyExc_ValueError, + "negative buffersize in recvfrom_into"); + return NULL; + } + if (recvlen == 0) { + /* If nbytes was not specified, use the buffer's length */ + recvlen = buflen; + } + + readlen = sock_recvfrom_guts(s, buf, recvlen, flags, &addr); + if (readlen < 0) { + PyBuffer_Release(&pbuf); + /* Return an error */ + Py_XDECREF(addr); + return NULL; + } + + PyBuffer_Release(&pbuf); + /* Return the number of bytes read and the address. Note that we do + not do anything special here in the case that readlen < recvlen. */ + return Py_BuildValue("lN", readlen, addr); } PyDoc_STRVAR(recvfrom_into_doc, @@ -2504,39 +2504,39 @@ static PyObject * sock_send(PySocketSockObject *s, PyObject *args) { - char *buf; - int len, n = -1, flags = 0, timeout; - Py_buffer pbuf; - - if (!PyArg_ParseTuple(args, "y*|i:send", &pbuf, &flags)) - return NULL; - - if (!IS_SELECTABLE(s)) { - PyBuffer_Release(&pbuf); - return select_error(); - } - buf = pbuf.buf; - len = pbuf.len; - - Py_BEGIN_ALLOW_THREADS - timeout = internal_select(s, 1); - if (!timeout) + char *buf; + int len, n = -1, flags = 0, timeout; + Py_buffer pbuf; + + if (!PyArg_ParseTuple(args, "y*|i:send", &pbuf, &flags)) + return NULL; + + if (!IS_SELECTABLE(s)) { + PyBuffer_Release(&pbuf); + return select_error(); + } + buf = pbuf.buf; + len = pbuf.len; + + Py_BEGIN_ALLOW_THREADS + timeout = internal_select(s, 1); + if (!timeout) #ifdef __VMS - n = sendsegmented(s->sock_fd, buf, len, flags); + n = sendsegmented(s->sock_fd, buf, len, flags); #else - n = send(s->sock_fd, buf, len, flags); + n = send(s->sock_fd, buf, len, flags); #endif - Py_END_ALLOW_THREADS + Py_END_ALLOW_THREADS - PyBuffer_Release(&pbuf); + PyBuffer_Release(&pbuf); - if (timeout == 1) { - PyErr_SetString(socket_timeout, "timed out"); - return NULL; - } - if (n < 0) - return s->errorhandler(); - return PyLong_FromLong((long)n); + if (timeout == 1) { + PyErr_SetString(socket_timeout, "timed out"); + return NULL; + } + if (n < 0) + return s->errorhandler(); + return PyLong_FromLong((long)n); } PyDoc_STRVAR(send_doc, @@ -2552,61 +2552,61 @@ static PyObject * sock_sendall(PySocketSockObject *s, PyObject *args) { - char *buf; - int len, n = -1, flags = 0, timeout; - Py_buffer pbuf; - - if (!PyArg_ParseTuple(args, "y*|i:sendall", &pbuf, &flags)) - return NULL; - buf = pbuf.buf; - len = pbuf.len; - - if (!IS_SELECTABLE(s)) { - PyBuffer_Release(&pbuf); - return select_error(); - } - - Py_BEGIN_ALLOW_THREADS - do { - timeout = internal_select(s, 1); - n = -1; - if (timeout) - break; + char *buf; + int len, n = -1, flags = 0, timeout; + Py_buffer pbuf; + + if (!PyArg_ParseTuple(args, "y*|i:sendall", &pbuf, &flags)) + return NULL; + buf = pbuf.buf; + len = pbuf.len; + + if (!IS_SELECTABLE(s)) { + PyBuffer_Release(&pbuf); + return select_error(); + } + + Py_BEGIN_ALLOW_THREADS + do { + timeout = internal_select(s, 1); + n = -1; + if (timeout) + break; #ifdef __VMS - n = sendsegmented(s->sock_fd, buf, len, flags); + n = sendsegmented(s->sock_fd, buf, len, flags); #else - n = send(s->sock_fd, buf, len, flags); + n = send(s->sock_fd, buf, len, flags); #endif - if (n < 0) { + if (n < 0) { #ifdef EINTR - /* We must handle EINTR here as there is no way for - * the caller to know how much was sent otherwise. */ - if (errno == EINTR) { - /* Run signal handlers. If an exception was - * raised, abort and leave this socket in - * an unknown state. */ - if (PyErr_CheckSignals()) - return NULL; - continue; - } -#endif - break; - } - buf += n; - len -= n; - } while (len > 0); - Py_END_ALLOW_THREADS - PyBuffer_Release(&pbuf); - - if (timeout == 1) { - PyErr_SetString(socket_timeout, "timed out"); - return NULL; - } - if (n < 0) - return s->errorhandler(); + /* We must handle EINTR here as there is no way for + * the caller to know how much was sent otherwise. */ + if (errno == EINTR) { + /* Run signal handlers. If an exception was + * raised, abort and leave this socket in + * an unknown state. */ + if (PyErr_CheckSignals()) + return NULL; + continue; + } +#endif + break; + } + buf += n; + len -= n; + } while (len > 0); + Py_END_ALLOW_THREADS + PyBuffer_Release(&pbuf); + + if (timeout == 1) { + PyErr_SetString(socket_timeout, "timed out"); + return NULL; + } + if (n < 0) + return s->errorhandler(); - Py_INCREF(Py_None); - return Py_None; + Py_INCREF(Py_None); + return Py_None; } PyDoc_STRVAR(sendall_doc, @@ -2623,47 +2623,47 @@ static PyObject * sock_sendto(PySocketSockObject *s, PyObject *args) { - Py_buffer pbuf; - PyObject *addro; - char *buf; - Py_ssize_t len; - sock_addr_t addrbuf; - int addrlen, n = -1, flags, timeout; - - flags = 0; - if (!PyArg_ParseTuple(args, "y*O:sendto", &pbuf, &addro)) { - PyErr_Clear(); - if (!PyArg_ParseTuple(args, "y*iO:sendto", - &pbuf, &flags, &addro)) - return NULL; - } - buf = pbuf.buf; - len = pbuf.len; - - if (!IS_SELECTABLE(s)) { - PyBuffer_Release(&pbuf); - return select_error(); - } - - if (!getsockaddrarg(s, addro, SAS2SA(&addrbuf), &addrlen)) { - PyBuffer_Release(&pbuf); - return NULL; - } - - Py_BEGIN_ALLOW_THREADS - timeout = internal_select(s, 1); - if (!timeout) - n = sendto(s->sock_fd, buf, len, flags, SAS2SA(&addrbuf), addrlen); - Py_END_ALLOW_THREADS - - PyBuffer_Release(&pbuf); - if (timeout == 1) { - PyErr_SetString(socket_timeout, "timed out"); - return NULL; - } - if (n < 0) - return s->errorhandler(); - return PyLong_FromLong((long)n); + Py_buffer pbuf; + PyObject *addro; + char *buf; + Py_ssize_t len; + sock_addr_t addrbuf; + int addrlen, n = -1, flags, timeout; + + flags = 0; + if (!PyArg_ParseTuple(args, "y*O:sendto", &pbuf, &addro)) { + PyErr_Clear(); + if (!PyArg_ParseTuple(args, "y*iO:sendto", + &pbuf, &flags, &addro)) + return NULL; + } + buf = pbuf.buf; + len = pbuf.len; + + if (!IS_SELECTABLE(s)) { + PyBuffer_Release(&pbuf); + return select_error(); + } + + if (!getsockaddrarg(s, addro, SAS2SA(&addrbuf), &addrlen)) { + PyBuffer_Release(&pbuf); + return NULL; + } + + Py_BEGIN_ALLOW_THREADS + timeout = internal_select(s, 1); + if (!timeout) + n = sendto(s->sock_fd, buf, len, flags, SAS2SA(&addrbuf), addrlen); + Py_END_ALLOW_THREADS + + PyBuffer_Release(&pbuf); + if (timeout == 1) { + PyErr_SetString(socket_timeout, "timed out"); + return NULL; + } + if (n < 0) + return s->errorhandler(); + return PyLong_FromLong((long)n); } PyDoc_STRVAR(sendto_doc, @@ -2678,19 +2678,19 @@ static PyObject * sock_shutdown(PySocketSockObject *s, PyObject *arg) { - int how; - int res; + int how; + int res; - how = PyLong_AsLong(arg); - if (how == -1 && PyErr_Occurred()) - return NULL; - Py_BEGIN_ALLOW_THREADS - res = shutdown(s->sock_fd, how); - Py_END_ALLOW_THREADS - if (res < 0) - return s->errorhandler(); - Py_INCREF(Py_None); - return Py_None; + how = PyLong_AsLong(arg); + if (how == -1 && PyErr_Occurred()) + return NULL; + Py_BEGIN_ALLOW_THREADS + res = shutdown(s->sock_fd, how); + Py_END_ALLOW_THREADS + if (res < 0) + return s->errorhandler(); + Py_INCREF(Py_None); + return Py_None; } PyDoc_STRVAR(shutdown_doc, @@ -2703,37 +2703,37 @@ static PyObject* sock_ioctl(PySocketSockObject *s, PyObject *arg) { - unsigned long cmd = SIO_RCVALL; - PyObject *argO; - DWORD recv; - - if (!PyArg_ParseTuple(arg, "kO:ioctl", &cmd, &argO)) - return NULL; - - switch (cmd) { - case SIO_RCVALL: { - unsigned int option = RCVALL_ON; - if (!PyArg_ParseTuple(arg, "kI:ioctl", &cmd, &option)) - return NULL; - if (WSAIoctl(s->sock_fd, cmd, &option, sizeof(option), - NULL, 0, &recv, NULL, NULL) == SOCKET_ERROR) { - return set_error(); - } - return PyLong_FromUnsignedLong(recv); } - case SIO_KEEPALIVE_VALS: { - struct tcp_keepalive ka; - if (!PyArg_ParseTuple(arg, "k(kkk):ioctl", &cmd, - &ka.onoff, &ka.keepalivetime, &ka.keepaliveinterval)) - return NULL; - if (WSAIoctl(s->sock_fd, cmd, &ka, sizeof(ka), - NULL, 0, &recv, NULL, NULL) == SOCKET_ERROR) { - return set_error(); - } - return PyLong_FromUnsignedLong(recv); } - default: - PyErr_Format(PyExc_ValueError, "invalid ioctl command %d", cmd); - return NULL; - } + unsigned long cmd = SIO_RCVALL; + PyObject *argO; + DWORD recv; + + if (!PyArg_ParseTuple(arg, "kO:ioctl", &cmd, &argO)) + return NULL; + + switch (cmd) { + case SIO_RCVALL: { + unsigned int option = RCVALL_ON; + if (!PyArg_ParseTuple(arg, "kI:ioctl", &cmd, &option)) + return NULL; + if (WSAIoctl(s->sock_fd, cmd, &option, sizeof(option), + NULL, 0, &recv, NULL, NULL) == SOCKET_ERROR) { + return set_error(); + } + return PyLong_FromUnsignedLong(recv); } + case SIO_KEEPALIVE_VALS: { + struct tcp_keepalive ka; + if (!PyArg_ParseTuple(arg, "k(kkk):ioctl", &cmd, + &ka.onoff, &ka.keepalivetime, &ka.keepaliveinterval)) + return NULL; + if (WSAIoctl(s->sock_fd, cmd, &ka, sizeof(ka), + NULL, 0, &recv, NULL, NULL) == SOCKET_ERROR) { + return set_error(); + } + return PyLong_FromUnsignedLong(recv); } + default: + PyErr_Format(PyExc_ValueError, "invalid ioctl command %d", cmd); + return NULL; + } } PyDoc_STRVAR(sock_ioctl_doc, "ioctl(cmd, option) -> long\n\ @@ -2747,57 +2747,57 @@ /* List of methods for socket objects */ static PyMethodDef sock_methods[] = { - {"_accept", (PyCFunction)sock_accept, METH_NOARGS, - accept_doc}, - {"bind", (PyCFunction)sock_bind, METH_O, - bind_doc}, - {"close", (PyCFunction)sock_close, METH_NOARGS, - close_doc}, - {"connect", (PyCFunction)sock_connect, METH_O, - connect_doc}, - {"connect_ex", (PyCFunction)sock_connect_ex, METH_O, - connect_ex_doc}, - {"fileno", (PyCFunction)sock_fileno, METH_NOARGS, - fileno_doc}, + {"_accept", (PyCFunction)sock_accept, METH_NOARGS, + accept_doc}, + {"bind", (PyCFunction)sock_bind, METH_O, + bind_doc}, + {"close", (PyCFunction)sock_close, METH_NOARGS, + close_doc}, + {"connect", (PyCFunction)sock_connect, METH_O, + connect_doc}, + {"connect_ex", (PyCFunction)sock_connect_ex, METH_O, + connect_ex_doc}, + {"fileno", (PyCFunction)sock_fileno, METH_NOARGS, + fileno_doc}, #ifdef HAVE_GETPEERNAME - {"getpeername", (PyCFunction)sock_getpeername, - METH_NOARGS, getpeername_doc}, + {"getpeername", (PyCFunction)sock_getpeername, + METH_NOARGS, getpeername_doc}, #endif - {"getsockname", (PyCFunction)sock_getsockname, - METH_NOARGS, getsockname_doc}, - {"getsockopt", (PyCFunction)sock_getsockopt, METH_VARARGS, - getsockopt_doc}, + {"getsockname", (PyCFunction)sock_getsockname, + METH_NOARGS, getsockname_doc}, + {"getsockopt", (PyCFunction)sock_getsockopt, METH_VARARGS, + getsockopt_doc}, #if defined(MS_WINDOWS) && defined(SIO_RCVALL) - {"ioctl", (PyCFunction)sock_ioctl, METH_VARARGS, - sock_ioctl_doc}, + {"ioctl", (PyCFunction)sock_ioctl, METH_VARARGS, + sock_ioctl_doc}, #endif - {"listen", (PyCFunction)sock_listen, METH_O, - listen_doc}, - {"recv", (PyCFunction)sock_recv, METH_VARARGS, - recv_doc}, - {"recv_into", (PyCFunction)sock_recv_into, METH_VARARGS | METH_KEYWORDS, - recv_into_doc}, - {"recvfrom", (PyCFunction)sock_recvfrom, METH_VARARGS, - recvfrom_doc}, - {"recvfrom_into", (PyCFunction)sock_recvfrom_into, METH_VARARGS | METH_KEYWORDS, - recvfrom_into_doc}, - {"send", (PyCFunction)sock_send, METH_VARARGS, - send_doc}, - {"sendall", (PyCFunction)sock_sendall, METH_VARARGS, - sendall_doc}, - {"sendto", (PyCFunction)sock_sendto, METH_VARARGS, - sendto_doc}, - {"setblocking", (PyCFunction)sock_setblocking, METH_O, - setblocking_doc}, - {"settimeout", (PyCFunction)sock_settimeout, METH_O, - settimeout_doc}, - {"gettimeout", (PyCFunction)sock_gettimeout, METH_NOARGS, - gettimeout_doc}, - {"setsockopt", (PyCFunction)sock_setsockopt, METH_VARARGS, - setsockopt_doc}, - {"shutdown", (PyCFunction)sock_shutdown, METH_O, - shutdown_doc}, - {NULL, NULL} /* sentinel */ + {"listen", (PyCFunction)sock_listen, METH_O, + listen_doc}, + {"recv", (PyCFunction)sock_recv, METH_VARARGS, + recv_doc}, + {"recv_into", (PyCFunction)sock_recv_into, METH_VARARGS | METH_KEYWORDS, + recv_into_doc}, + {"recvfrom", (PyCFunction)sock_recvfrom, METH_VARARGS, + recvfrom_doc}, + {"recvfrom_into", (PyCFunction)sock_recvfrom_into, METH_VARARGS | METH_KEYWORDS, + recvfrom_into_doc}, + {"send", (PyCFunction)sock_send, METH_VARARGS, + send_doc}, + {"sendall", (PyCFunction)sock_sendall, METH_VARARGS, + sendall_doc}, + {"sendto", (PyCFunction)sock_sendto, METH_VARARGS, + sendto_doc}, + {"setblocking", (PyCFunction)sock_setblocking, METH_O, + setblocking_doc}, + {"settimeout", (PyCFunction)sock_settimeout, METH_O, + settimeout_doc}, + {"gettimeout", (PyCFunction)sock_gettimeout, METH_NOARGS, + gettimeout_doc}, + {"setsockopt", (PyCFunction)sock_setsockopt, METH_VARARGS, + setsockopt_doc}, + {"shutdown", (PyCFunction)sock_shutdown, METH_O, + shutdown_doc}, + {NULL, NULL} /* sentinel */ }; /* SockObject members */ @@ -2815,9 +2815,9 @@ static void sock_dealloc(PySocketSockObject *s) { - if (s->sock_fd != -1) - (void) SOCKETCLOSE(s->sock_fd); - Py_TYPE(s)->tp_free((PyObject *)s); + if (s->sock_fd != -1) + (void) SOCKETCLOSE(s->sock_fd); + Py_TYPE(s)->tp_free((PyObject *)s); } @@ -2825,21 +2825,21 @@ sock_repr(PySocketSockObject *s) { #if SIZEOF_SOCKET_T > SIZEOF_LONG - if (s->sock_fd > LONG_MAX) { - /* this can occur on Win64, and actually there is a special - ugly printf formatter for decimal pointer length integer - printing, only bother if necessary*/ - PyErr_SetString(PyExc_OverflowError, - "no printf formatter to display " - "the socket descriptor in decimal"); - return NULL; - } -#endif - return PyUnicode_FromFormat( - "", - (long)s->sock_fd, s->sock_family, - s->sock_type, - s->sock_proto); + if (s->sock_fd > LONG_MAX) { + /* this can occur on Win64, and actually there is a special + ugly printf formatter for decimal pointer length integer + printing, only bother if necessary*/ + PyErr_SetString(PyExc_OverflowError, + "no printf formatter to display " + "the socket descriptor in decimal"); + return NULL; + } +#endif + return PyUnicode_FromFormat( + "", + (long)s->sock_fd, s->sock_family, + s->sock_type, + s->sock_proto); } @@ -2848,15 +2848,15 @@ static PyObject * sock_new(PyTypeObject *type, PyObject *args, PyObject *kwds) { - PyObject *new; + PyObject *new; - new = type->tp_alloc(type, 0); - if (new != NULL) { - ((PySocketSockObject *)new)->sock_fd = -1; - ((PySocketSockObject *)new)->sock_timeout = -1.0; - ((PySocketSockObject *)new)->errorhandler = &set_error; - } - return new; + new = type->tp_alloc(type, 0); + if (new != NULL) { + ((PySocketSockObject *)new)->sock_fd = -1; + ((PySocketSockObject *)new)->sock_timeout = -1.0; + ((PySocketSockObject *)new)->errorhandler = &set_error; + } + return new; } @@ -2866,40 +2866,40 @@ static int sock_initobj(PyObject *self, PyObject *args, PyObject *kwds) { - PySocketSockObject *s = (PySocketSockObject *)self; - PyObject *fdobj = NULL; - SOCKET_T fd = INVALID_SOCKET; - int family = AF_INET, type = SOCK_STREAM, proto = 0; - static char *keywords[] = {"family", "type", "proto", "fileno", 0}; - - if (!PyArg_ParseTupleAndKeywords(args, kwds, - "|iiiO:socket", keywords, - &family, &type, &proto, &fdobj)) - return -1; - - if (fdobj != NULL && fdobj != Py_None) { - fd = PyLong_AsSocket_t(fdobj); - if (fd == (SOCKET_T)(-1) && PyErr_Occurred()) - return -1; - if (fd == INVALID_SOCKET) { - PyErr_SetString(PyExc_ValueError, - "can't use invalid socket value"); - return -1; - } - } - else { - Py_BEGIN_ALLOW_THREADS - fd = socket(family, type, proto); - Py_END_ALLOW_THREADS - - if (fd == INVALID_SOCKET) { - set_error(); - return -1; - } - } - init_sockobject(s, fd, family, type, proto); + PySocketSockObject *s = (PySocketSockObject *)self; + PyObject *fdobj = NULL; + SOCKET_T fd = INVALID_SOCKET; + int family = AF_INET, type = SOCK_STREAM, proto = 0; + static char *keywords[] = {"family", "type", "proto", "fileno", 0}; + + if (!PyArg_ParseTupleAndKeywords(args, kwds, + "|iiiO:socket", keywords, + &family, &type, &proto, &fdobj)) + return -1; + + if (fdobj != NULL && fdobj != Py_None) { + fd = PyLong_AsSocket_t(fdobj); + if (fd == (SOCKET_T)(-1) && PyErr_Occurred()) + return -1; + if (fd == INVALID_SOCKET) { + PyErr_SetString(PyExc_ValueError, + "can't use invalid socket value"); + return -1; + } + } + else { + Py_BEGIN_ALLOW_THREADS + fd = socket(family, type, proto); + Py_END_ALLOW_THREADS + + if (fd == INVALID_SOCKET) { + set_error(); + return -1; + } + } + init_sockobject(s, fd, family, type, proto); - return 0; + return 0; } @@ -2907,45 +2907,45 @@ /* Type object for socket objects. */ static PyTypeObject sock_type = { - PyVarObject_HEAD_INIT(0, 0) /* Must fill in type value later */ - "_socket.socket", /* tp_name */ - sizeof(PySocketSockObject), /* tp_basicsize */ - 0, /* tp_itemsize */ - (destructor)sock_dealloc, /* tp_dealloc */ - 0, /* tp_print */ - 0, /* tp_getattr */ - 0, /* tp_setattr */ - 0, /* tp_reserved */ - (reprfunc)sock_repr, /* 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_BASETYPE, /* tp_flags */ - sock_doc, /* tp_doc */ - 0, /* tp_traverse */ - 0, /* tp_clear */ - 0, /* tp_richcompare */ - 0, /* tp_weaklistoffset */ - 0, /* tp_iter */ - 0, /* tp_iternext */ - sock_methods, /* tp_methods */ - sock_memberlist, /* tp_members */ - 0, /* tp_getset */ - 0, /* tp_base */ - 0, /* tp_dict */ - 0, /* tp_descr_get */ - 0, /* tp_descr_set */ - 0, /* tp_dictoffset */ - sock_initobj, /* tp_init */ - PyType_GenericAlloc, /* tp_alloc */ - sock_new, /* tp_new */ - PyObject_Del, /* tp_free */ + PyVarObject_HEAD_INIT(0, 0) /* Must fill in type value later */ + "_socket.socket", /* tp_name */ + sizeof(PySocketSockObject), /* tp_basicsize */ + 0, /* tp_itemsize */ + (destructor)sock_dealloc, /* tp_dealloc */ + 0, /* tp_print */ + 0, /* tp_getattr */ + 0, /* tp_setattr */ + 0, /* tp_reserved */ + (reprfunc)sock_repr, /* 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_BASETYPE, /* tp_flags */ + sock_doc, /* tp_doc */ + 0, /* tp_traverse */ + 0, /* tp_clear */ + 0, /* tp_richcompare */ + 0, /* tp_weaklistoffset */ + 0, /* tp_iter */ + 0, /* tp_iternext */ + sock_methods, /* tp_methods */ + sock_memberlist, /* tp_members */ + 0, /* tp_getset */ + 0, /* tp_base */ + 0, /* tp_dict */ + 0, /* tp_descr_get */ + 0, /* tp_descr_set */ + 0, /* tp_dictoffset */ + sock_initobj, /* tp_init */ + PyType_GenericAlloc, /* tp_alloc */ + sock_new, /* tp_new */ + PyObject_Del, /* tp_free */ }; @@ -2955,15 +2955,15 @@ static PyObject * socket_gethostname(PyObject *self, PyObject *unused) { - char buf[1024]; - int res; - Py_BEGIN_ALLOW_THREADS - res = gethostname(buf, (int) sizeof buf - 1); - Py_END_ALLOW_THREADS - if (res < 0) - return set_error(); - buf[sizeof buf - 1] = '\0'; - return PyUnicode_FromString(buf); + char buf[1024]; + int res; + Py_BEGIN_ALLOW_THREADS + res = gethostname(buf, (int) sizeof buf - 1); + Py_END_ALLOW_THREADS + if (res < 0) + return set_error(); + buf[sizeof buf - 1] = '\0'; + return PyUnicode_FromString(buf); } PyDoc_STRVAR(gethostname_doc, @@ -2978,14 +2978,14 @@ static PyObject * socket_gethostbyname(PyObject *self, PyObject *args) { - char *name; - sock_addr_t addrbuf; + char *name; + sock_addr_t addrbuf; - if (!PyArg_ParseTuple(args, "s:gethostbyname", &name)) - return NULL; - if (setipaddr(name, SAS2SA(&addrbuf), sizeof(addrbuf), AF_INET) < 0) - return NULL; - return makeipaddr(SAS2SA(&addrbuf), sizeof(struct sockaddr_in)); + if (!PyArg_ParseTuple(args, "s:gethostbyname", &name)) + return NULL; + if (setipaddr(name, SAS2SA(&addrbuf), sizeof(addrbuf), AF_INET) < 0) + return NULL; + return makeipaddr(SAS2SA(&addrbuf), sizeof(struct sockaddr_in)); } PyDoc_STRVAR(gethostbyname_doc, @@ -2999,126 +2999,126 @@ static PyObject * gethost_common(struct hostent *h, struct sockaddr *addr, int alen, int af) { - char **pch; - PyObject *rtn_tuple = (PyObject *)NULL; - PyObject *name_list = (PyObject *)NULL; - PyObject *addr_list = (PyObject *)NULL; - PyObject *tmp; - - if (h == NULL) { - /* Let's get real error message to return */ - set_herror(h_errno); - return NULL; - } - - if (h->h_addrtype != af) { - /* Let's get real error message to return */ - PyErr_SetString(socket_error, - (char *)strerror(EAFNOSUPPORT)); - - return NULL; - } - - switch (af) { - - case AF_INET: - if (alen < sizeof(struct sockaddr_in)) - return NULL; - break; + char **pch; + PyObject *rtn_tuple = (PyObject *)NULL; + PyObject *name_list = (PyObject *)NULL; + PyObject *addr_list = (PyObject *)NULL; + PyObject *tmp; + + if (h == NULL) { + /* Let's get real error message to return */ + set_herror(h_errno); + return NULL; + } + + if (h->h_addrtype != af) { + /* Let's get real error message to return */ + PyErr_SetString(socket_error, + (char *)strerror(EAFNOSUPPORT)); + + return NULL; + } + + switch (af) { + + case AF_INET: + if (alen < sizeof(struct sockaddr_in)) + return NULL; + break; #ifdef ENABLE_IPV6 - case AF_INET6: - if (alen < sizeof(struct sockaddr_in6)) - return NULL; - break; -#endif - - } - - if ((name_list = PyList_New(0)) == NULL) - goto err; - - if ((addr_list = PyList_New(0)) == NULL) - goto err; - - /* SF #1511317: h_aliases can be NULL */ - if (h->h_aliases) { - for (pch = h->h_aliases; *pch != NULL; pch++) { - int status; - tmp = PyUnicode_FromString(*pch); - if (tmp == NULL) - goto err; - - status = PyList_Append(name_list, tmp); - Py_DECREF(tmp); - - if (status) - goto err; - } - } - - for (pch = h->h_addr_list; *pch != NULL; pch++) { - int status; - - switch (af) { - - case AF_INET: - { - struct sockaddr_in sin; - memset(&sin, 0, sizeof(sin)); - sin.sin_family = af; + case AF_INET6: + if (alen < sizeof(struct sockaddr_in6)) + return NULL; + break; +#endif + + } + + if ((name_list = PyList_New(0)) == NULL) + goto err; + + if ((addr_list = PyList_New(0)) == NULL) + goto err; + + /* SF #1511317: h_aliases can be NULL */ + if (h->h_aliases) { + for (pch = h->h_aliases; *pch != NULL; pch++) { + int status; + tmp = PyUnicode_FromString(*pch); + if (tmp == NULL) + goto err; + + status = PyList_Append(name_list, tmp); + Py_DECREF(tmp); + + if (status) + goto err; + } + } + + for (pch = h->h_addr_list; *pch != NULL; pch++) { + int status; + + switch (af) { + + case AF_INET: + { + struct sockaddr_in sin; + memset(&sin, 0, sizeof(sin)); + sin.sin_family = af; #ifdef HAVE_SOCKADDR_SA_LEN - sin.sin_len = sizeof(sin); + sin.sin_len = sizeof(sin); #endif - memcpy(&sin.sin_addr, *pch, sizeof(sin.sin_addr)); - tmp = makeipaddr((struct sockaddr *)&sin, sizeof(sin)); + memcpy(&sin.sin_addr, *pch, sizeof(sin.sin_addr)); + tmp = makeipaddr((struct sockaddr *)&sin, sizeof(sin)); - if (pch == h->h_addr_list && alen >= sizeof(sin)) - memcpy((char *) addr, &sin, sizeof(sin)); - break; - } + if (pch == h->h_addr_list && alen >= sizeof(sin)) + memcpy((char *) addr, &sin, sizeof(sin)); + break; + } #ifdef ENABLE_IPV6 - case AF_INET6: - { - struct sockaddr_in6 sin6; - memset(&sin6, 0, sizeof(sin6)); - sin6.sin6_family = af; + case AF_INET6: + { + struct sockaddr_in6 sin6; + memset(&sin6, 0, sizeof(sin6)); + sin6.sin6_family = af; #ifdef HAVE_SOCKADDR_SA_LEN - sin6.sin6_len = sizeof(sin6); + sin6.sin6_len = sizeof(sin6); #endif - memcpy(&sin6.sin6_addr, *pch, sizeof(sin6.sin6_addr)); - tmp = makeipaddr((struct sockaddr *)&sin6, - sizeof(sin6)); + memcpy(&sin6.sin6_addr, *pch, sizeof(sin6.sin6_addr)); + tmp = makeipaddr((struct sockaddr *)&sin6, + sizeof(sin6)); - if (pch == h->h_addr_list && alen >= sizeof(sin6)) - memcpy((char *) addr, &sin6, sizeof(sin6)); - break; - } + if (pch == h->h_addr_list && alen >= sizeof(sin6)) + memcpy((char *) addr, &sin6, sizeof(sin6)); + break; + } #endif - default: /* can't happen */ - PyErr_SetString(socket_error, - "unsupported address family"); - return NULL; - } + default: /* can't happen */ + PyErr_SetString(socket_error, + "unsupported address family"); + return NULL; + } - if (tmp == NULL) - goto err; + if (tmp == NULL) + goto err; - status = PyList_Append(addr_list, tmp); - Py_DECREF(tmp); + status = PyList_Append(addr_list, tmp); + Py_DECREF(tmp); - if (status) - goto err; - } + if (status) + goto err; + } - rtn_tuple = Py_BuildValue("sOO", h->h_name, name_list, addr_list); + rtn_tuple = Py_BuildValue("sOO", h->h_name, name_list, addr_list); err: - Py_XDECREF(name_list); - Py_XDECREF(addr_list); - return rtn_tuple; + Py_XDECREF(name_list); + Py_XDECREF(addr_list); + return rtn_tuple; } @@ -3128,63 +3128,63 @@ static PyObject * socket_gethostbyname_ex(PyObject *self, PyObject *args) { - char *name; - struct hostent *h; + char *name; + struct hostent *h; #ifdef ENABLE_IPV6 - struct sockaddr_storage addr; + struct sockaddr_storage addr; #else - struct sockaddr_in addr; + struct sockaddr_in addr; #endif - struct sockaddr *sa; - PyObject *ret; + struct sockaddr *sa; + PyObject *ret; #ifdef HAVE_GETHOSTBYNAME_R - struct hostent hp_allocated; + struct hostent hp_allocated; #ifdef HAVE_GETHOSTBYNAME_R_3_ARG - struct hostent_data data; + struct hostent_data data; #else - char buf[16384]; - int buf_len = (sizeof buf) - 1; - int errnop; + char buf[16384]; + int buf_len = (sizeof buf) - 1; + int errnop; #endif #if defined(HAVE_GETHOSTBYNAME_R_3_ARG) || defined(HAVE_GETHOSTBYNAME_R_6_ARG) - int result; + int result; #endif #endif /* HAVE_GETHOSTBYNAME_R */ - if (!PyArg_ParseTuple(args, "s:gethostbyname_ex", &name)) - return NULL; - if (setipaddr(name, (struct sockaddr *)&addr, sizeof(addr), AF_INET) < 0) - return NULL; - Py_BEGIN_ALLOW_THREADS + if (!PyArg_ParseTuple(args, "s:gethostbyname_ex", &name)) + return NULL; + if (setipaddr(name, (struct sockaddr *)&addr, sizeof(addr), AF_INET) < 0) + return NULL; + Py_BEGIN_ALLOW_THREADS #ifdef HAVE_GETHOSTBYNAME_R #if defined(HAVE_GETHOSTBYNAME_R_6_ARG) - result = gethostbyname_r(name, &hp_allocated, buf, buf_len, - &h, &errnop); + result = gethostbyname_r(name, &hp_allocated, buf, buf_len, + &h, &errnop); #elif defined(HAVE_GETHOSTBYNAME_R_5_ARG) - h = gethostbyname_r(name, &hp_allocated, buf, buf_len, &errnop); + h = gethostbyname_r(name, &hp_allocated, buf, buf_len, &errnop); #else /* HAVE_GETHOSTBYNAME_R_3_ARG */ - memset((void *) &data, '\0', sizeof(data)); - result = gethostbyname_r(name, &hp_allocated, &data); - h = (result != 0) ? NULL : &hp_allocated; + memset((void *) &data, '\0', sizeof(data)); + result = gethostbyname_r(name, &hp_allocated, &data); + h = (result != 0) ? NULL : &hp_allocated; #endif #else /* not HAVE_GETHOSTBYNAME_R */ #ifdef USE_GETHOSTBYNAME_LOCK - PyThread_acquire_lock(netdb_lock, 1); + PyThread_acquire_lock(netdb_lock, 1); #endif - h = gethostbyname(name); + h = gethostbyname(name); #endif /* HAVE_GETHOSTBYNAME_R */ - Py_END_ALLOW_THREADS - /* Some C libraries would require addr.__ss_family instead of - addr.ss_family. - Therefore, we cast the sockaddr_storage into sockaddr to - access sa_family. */ - sa = (struct sockaddr*)&addr; - ret = gethost_common(h, (struct sockaddr *)&addr, sizeof(addr), - sa->sa_family); + Py_END_ALLOW_THREADS + /* Some C libraries would require addr.__ss_family instead of + addr.ss_family. + Therefore, we cast the sockaddr_storage into sockaddr to + access sa_family. */ + sa = (struct sockaddr*)&addr; + ret = gethost_common(h, (struct sockaddr *)&addr, sizeof(addr), + sa->sa_family); #ifdef USE_GETHOSTBYNAME_LOCK - PyThread_release_lock(netdb_lock); + PyThread_release_lock(netdb_lock); #endif - return ret; + return ret; } PyDoc_STRVAR(ghbn_ex_doc, @@ -3201,84 +3201,84 @@ socket_gethostbyaddr(PyObject *self, PyObject *args) { #ifdef ENABLE_IPV6 - struct sockaddr_storage addr; + struct sockaddr_storage addr; #else - struct sockaddr_in addr; + struct sockaddr_in addr; #endif - struct sockaddr *sa = (struct sockaddr *)&addr; - char *ip_num; - struct hostent *h; - PyObject *ret; + struct sockaddr *sa = (struct sockaddr *)&addr; + char *ip_num; + struct hostent *h; + PyObject *ret; #ifdef HAVE_GETHOSTBYNAME_R - struct hostent hp_allocated; + struct hostent hp_allocated; #ifdef HAVE_GETHOSTBYNAME_R_3_ARG - struct hostent_data data; + struct hostent_data data; #else - /* glibcs up to 2.10 assume that the buf argument to - gethostbyaddr_r is 8-byte aligned, which at least llvm-gcc - does not ensure. The attribute below instructs the compiler - to maintain this alignment. */ - char buf[16384] Py_ALIGNED(8); - int buf_len = (sizeof buf) - 1; - int errnop; + /* glibcs up to 2.10 assume that the buf argument to + gethostbyaddr_r is 8-byte aligned, which at least llvm-gcc + does not ensure. The attribute below instructs the compiler + to maintain this alignment. */ + char buf[16384] Py_ALIGNED(8); + int buf_len = (sizeof buf) - 1; + int errnop; #endif #if defined(HAVE_GETHOSTBYNAME_R_3_ARG) || defined(HAVE_GETHOSTBYNAME_R_6_ARG) - int result; + int result; #endif #endif /* HAVE_GETHOSTBYNAME_R */ - char *ap; - int al; - int af; - - if (!PyArg_ParseTuple(args, "s:gethostbyaddr", &ip_num)) - return NULL; - af = AF_UNSPEC; - if (setipaddr(ip_num, sa, sizeof(addr), af) < 0) - return NULL; - af = sa->sa_family; - ap = NULL; - al = 0; - switch (af) { - case AF_INET: - ap = (char *)&((struct sockaddr_in *)sa)->sin_addr; - al = sizeof(((struct sockaddr_in *)sa)->sin_addr); - break; + char *ap; + int al; + int af; + + if (!PyArg_ParseTuple(args, "s:gethostbyaddr", &ip_num)) + return NULL; + af = AF_UNSPEC; + if (setipaddr(ip_num, sa, sizeof(addr), af) < 0) + return NULL; + af = sa->sa_family; + ap = NULL; + al = 0; + switch (af) { + case AF_INET: + ap = (char *)&((struct sockaddr_in *)sa)->sin_addr; + al = sizeof(((struct sockaddr_in *)sa)->sin_addr); + break; #ifdef ENABLE_IPV6 - case AF_INET6: - ap = (char *)&((struct sockaddr_in6 *)sa)->sin6_addr; - al = sizeof(((struct sockaddr_in6 *)sa)->sin6_addr); - break; -#endif - default: - PyErr_SetString(socket_error, "unsupported address family"); - return NULL; - } - Py_BEGIN_ALLOW_THREADS + case AF_INET6: + ap = (char *)&((struct sockaddr_in6 *)sa)->sin6_addr; + al = sizeof(((struct sockaddr_in6 *)sa)->sin6_addr); + break; +#endif + default: + PyErr_SetString(socket_error, "unsupported address family"); + return NULL; + } + Py_BEGIN_ALLOW_THREADS #ifdef HAVE_GETHOSTBYNAME_R #if defined(HAVE_GETHOSTBYNAME_R_6_ARG) - result = gethostbyaddr_r(ap, al, af, - &hp_allocated, buf, buf_len, - &h, &errnop); + result = gethostbyaddr_r(ap, al, af, + &hp_allocated, buf, buf_len, + &h, &errnop); #elif defined(HAVE_GETHOSTBYNAME_R_5_ARG) - h = gethostbyaddr_r(ap, al, af, - &hp_allocated, buf, buf_len, &errnop); + h = gethostbyaddr_r(ap, al, af, + &hp_allocated, buf, buf_len, &errnop); #else /* HAVE_GETHOSTBYNAME_R_3_ARG */ - memset((void *) &data, '\0', sizeof(data)); - result = gethostbyaddr_r(ap, al, af, &hp_allocated, &data); - h = (result != 0) ? NULL : &hp_allocated; + memset((void *) &data, '\0', sizeof(data)); + result = gethostbyaddr_r(ap, al, af, &hp_allocated, &data); + h = (result != 0) ? NULL : &hp_allocated; #endif #else /* not HAVE_GETHOSTBYNAME_R */ #ifdef USE_GETHOSTBYNAME_LOCK - PyThread_acquire_lock(netdb_lock, 1); + PyThread_acquire_lock(netdb_lock, 1); #endif - h = gethostbyaddr(ap, al, af); + h = gethostbyaddr(ap, al, af); #endif /* HAVE_GETHOSTBYNAME_R */ - Py_END_ALLOW_THREADS - ret = gethost_common(h, (struct sockaddr *)&addr, sizeof(addr), af); + Py_END_ALLOW_THREADS + ret = gethost_common(h, (struct sockaddr *)&addr, sizeof(addr), af); #ifdef USE_GETHOSTBYNAME_LOCK - PyThread_release_lock(netdb_lock); + PyThread_release_lock(netdb_lock); #endif - return ret; + return ret; } PyDoc_STRVAR(gethostbyaddr_doc, @@ -3296,18 +3296,18 @@ static PyObject * socket_getservbyname(PyObject *self, PyObject *args) { - char *name, *proto=NULL; - struct servent *sp; - if (!PyArg_ParseTuple(args, "s|s:getservbyname", &name, &proto)) - return NULL; - Py_BEGIN_ALLOW_THREADS - sp = getservbyname(name, proto); - Py_END_ALLOW_THREADS - if (sp == NULL) { - PyErr_SetString(socket_error, "service/proto not found"); - return NULL; - } - return PyLong_FromLong((long) ntohs(sp->s_port)); + char *name, *proto=NULL; + struct servent *sp; + if (!PyArg_ParseTuple(args, "s|s:getservbyname", &name, &proto)) + return NULL; + Py_BEGIN_ALLOW_THREADS + sp = getservbyname(name, proto); + Py_END_ALLOW_THREADS + if (sp == NULL) { + PyErr_SetString(socket_error, "service/proto not found"); + return NULL; + } + return PyLong_FromLong((long) ntohs(sp->s_port)); } PyDoc_STRVAR(getservbyname_doc, @@ -3326,25 +3326,25 @@ static PyObject * socket_getservbyport(PyObject *self, PyObject *args) { - int port; - char *proto=NULL; - struct servent *sp; - if (!PyArg_ParseTuple(args, "i|s:getservbyport", &port, &proto)) - return NULL; - if (port < 0 || port > 0xffff) { - PyErr_SetString( - PyExc_OverflowError, - "getservbyport: port must be 0-65535."); - return NULL; - } - Py_BEGIN_ALLOW_THREADS - sp = getservbyport(htons((short)port), proto); - Py_END_ALLOW_THREADS - if (sp == NULL) { - PyErr_SetString(socket_error, "port/proto not found"); - return NULL; - } - return PyUnicode_FromString(sp->s_name); + int port; + char *proto=NULL; + struct servent *sp; + if (!PyArg_ParseTuple(args, "i|s:getservbyport", &port, &proto)) + return NULL; + if (port < 0 || port > 0xffff) { + PyErr_SetString( + PyExc_OverflowError, + "getservbyport: port must be 0-65535."); + return NULL; + } + Py_BEGIN_ALLOW_THREADS + sp = getservbyport(htons((short)port), proto); + Py_END_ALLOW_THREADS + if (sp == NULL) { + PyErr_SetString(socket_error, "port/proto not found"); + return NULL; + } + return PyUnicode_FromString(sp->s_name); } PyDoc_STRVAR(getservbyport_doc, @@ -3362,18 +3362,18 @@ static PyObject * socket_getprotobyname(PyObject *self, PyObject *args) { - char *name; - struct protoent *sp; - if (!PyArg_ParseTuple(args, "s:getprotobyname", &name)) - return NULL; - Py_BEGIN_ALLOW_THREADS - sp = getprotobyname(name); - Py_END_ALLOW_THREADS - if (sp == NULL) { - PyErr_SetString(socket_error, "protocol not found"); - return NULL; - } - return PyLong_FromLong((long) sp->p_proto); + char *name; + struct protoent *sp; + if (!PyArg_ParseTuple(args, "s:getprotobyname", &name)) + return NULL; + Py_BEGIN_ALLOW_THREADS + sp = getprotobyname(name); + Py_END_ALLOW_THREADS + if (sp == NULL) { + PyErr_SetString(socket_error, "protocol not found"); + return NULL; + } + return PyLong_FromLong((long) sp->p_proto); } PyDoc_STRVAR(getprotobyname_doc, @@ -3388,22 +3388,22 @@ static PyObject * socket_dup(PyObject *self, PyObject *fdobj) { - SOCKET_T fd, newfd; - PyObject *newfdobj; + SOCKET_T fd, newfd; + PyObject *newfdobj; - fd = PyLong_AsSocket_t(fdobj); - if (fd == (SOCKET_T)(-1) && PyErr_Occurred()) - return NULL; - - newfd = dup_socket(fd); - if (newfd == INVALID_SOCKET) - return set_error(); - - newfdobj = PyLong_FromSocket_t(newfd); - if (newfdobj == NULL) - SOCKETCLOSE(newfd); - return newfdobj; + fd = PyLong_AsSocket_t(fdobj); + if (fd == (SOCKET_T)(-1) && PyErr_Occurred()) + return NULL; + + newfd = dup_socket(fd); + if (newfd == INVALID_SOCKET) + return set_error(); + + newfdobj = PyLong_FromSocket_t(newfd); + if (newfdobj == NULL) + SOCKETCLOSE(newfd); + return newfdobj; } PyDoc_STRVAR(dup_doc, @@ -3423,40 +3423,40 @@ static PyObject * socket_socketpair(PyObject *self, PyObject *args) { - PySocketSockObject *s0 = NULL, *s1 = NULL; - SOCKET_T sv[2]; - int family, type = SOCK_STREAM, proto = 0; - PyObject *res = NULL; + PySocketSockObject *s0 = NULL, *s1 = NULL; + SOCKET_T sv[2]; + int family, type = SOCK_STREAM, proto = 0; + PyObject *res = NULL; #if defined(AF_UNIX) - family = AF_UNIX; + family = AF_UNIX; #else - family = AF_INET; + family = AF_INET; #endif - if (!PyArg_ParseTuple(args, "|iii:socketpair", - &family, &type, &proto)) - return NULL; - /* Create a pair of socket fds */ - if (socketpair(family, type, proto, sv) < 0) - return set_error(); - s0 = new_sockobject(sv[0], family, type, proto); - if (s0 == NULL) - goto finally; - s1 = new_sockobject(sv[1], family, type, proto); - if (s1 == NULL) - goto finally; - res = PyTuple_Pack(2, s0, s1); + if (!PyArg_ParseTuple(args, "|iii:socketpair", + &family, &type, &proto)) + return NULL; + /* Create a pair of socket fds */ + if (socketpair(family, type, proto, sv) < 0) + return set_error(); + s0 = new_sockobject(sv[0], family, type, proto); + if (s0 == NULL) + goto finally; + s1 = new_sockobject(sv[1], family, type, proto); + if (s1 == NULL) + goto finally; + res = PyTuple_Pack(2, s0, s1); finally: - if (res == NULL) { - if (s0 == NULL) - SOCKETCLOSE(sv[0]); - if (s1 == NULL) - SOCKETCLOSE(sv[1]); - } - Py_XDECREF(s0); - Py_XDECREF(s1); - return res; + if (res == NULL) { + if (s0 == NULL) + SOCKETCLOSE(sv[0]); + if (s1 == NULL) + SOCKETCLOSE(sv[1]); + } + Py_XDECREF(s0); + Py_XDECREF(s1); + return res; } PyDoc_STRVAR(socketpair_doc, @@ -3473,18 +3473,18 @@ static PyObject * socket_ntohs(PyObject *self, PyObject *args) { - int x1, x2; + int x1, x2; - if (!PyArg_ParseTuple(args, "i:ntohs", &x1)) { - return NULL; - } - if (x1 < 0) { - PyErr_SetString(PyExc_OverflowError, - "can't convert negative number to unsigned long"); - return NULL; - } - x2 = (unsigned int)ntohs((unsigned short)x1); - return PyLong_FromLong(x2); + if (!PyArg_ParseTuple(args, "i:ntohs", &x1)) { + return NULL; + } + if (x1 < 0) { + PyErr_SetString(PyExc_OverflowError, + "can't convert negative number to unsigned long"); + return NULL; + } + x2 = (unsigned int)ntohs((unsigned short)x1); + return PyLong_FromLong(x2); } PyDoc_STRVAR(ntohs_doc, @@ -3496,31 +3496,31 @@ static PyObject * socket_ntohl(PyObject *self, PyObject *arg) { - unsigned long x; + unsigned long x; - if (PyLong_Check(arg)) { - x = PyLong_AsUnsignedLong(arg); - if (x == (unsigned long) -1 && PyErr_Occurred()) - return NULL; + if (PyLong_Check(arg)) { + x = PyLong_AsUnsignedLong(arg); + if (x == (unsigned long) -1 && PyErr_Occurred()) + return NULL; #if SIZEOF_LONG > 4 - { - unsigned long y; - /* only want the trailing 32 bits */ - y = x & 0xFFFFFFFFUL; - if (y ^ x) - return PyErr_Format(PyExc_OverflowError, - "long int larger than 32 bits"); - x = y; - } -#endif - } - else - return PyErr_Format(PyExc_TypeError, - "expected int/long, %s found", - Py_TYPE(arg)->tp_name); - if (x == (unsigned long) -1 && PyErr_Occurred()) - return NULL; - return PyLong_FromUnsignedLong(ntohl(x)); + { + unsigned long y; + /* only want the trailing 32 bits */ + y = x & 0xFFFFFFFFUL; + if (y ^ x) + return PyErr_Format(PyExc_OverflowError, + "long int larger than 32 bits"); + x = y; + } +#endif + } + else + return PyErr_Format(PyExc_TypeError, + "expected int/long, %s found", + Py_TYPE(arg)->tp_name); + if (x == (unsigned long) -1 && PyErr_Occurred()) + return NULL; + return PyLong_FromUnsignedLong(ntohl(x)); } PyDoc_STRVAR(ntohl_doc, @@ -3532,18 +3532,18 @@ static PyObject * socket_htons(PyObject *self, PyObject *args) { - int x1, x2; + int x1, x2; - if (!PyArg_ParseTuple(args, "i:htons", &x1)) { - return NULL; - } - if (x1 < 0) { - PyErr_SetString(PyExc_OverflowError, - "can't convert negative number to unsigned long"); - return NULL; - } - x2 = (unsigned int)htons((unsigned short)x1); - return PyLong_FromLong(x2); + if (!PyArg_ParseTuple(args, "i:htons", &x1)) { + return NULL; + } + if (x1 < 0) { + PyErr_SetString(PyExc_OverflowError, + "can't convert negative number to unsigned long"); + return NULL; + } + x2 = (unsigned int)htons((unsigned short)x1); + return PyLong_FromLong(x2); } PyDoc_STRVAR(htons_doc, @@ -3555,29 +3555,29 @@ static PyObject * socket_htonl(PyObject *self, PyObject *arg) { - unsigned long x; + unsigned long x; - if (PyLong_Check(arg)) { - x = PyLong_AsUnsignedLong(arg); - if (x == (unsigned long) -1 && PyErr_Occurred()) - return NULL; + if (PyLong_Check(arg)) { + x = PyLong_AsUnsignedLong(arg); + if (x == (unsigned long) -1 && PyErr_Occurred()) + return NULL; #if SIZEOF_LONG > 4 - { - unsigned long y; - /* only want the trailing 32 bits */ - y = x & 0xFFFFFFFFUL; - if (y ^ x) - return PyErr_Format(PyExc_OverflowError, - "long int larger than 32 bits"); - x = y; - } -#endif - } - else - return PyErr_Format(PyExc_TypeError, - "expected int/long, %s found", - Py_TYPE(arg)->tp_name); - return PyLong_FromUnsignedLong(htonl((unsigned long)x)); + { + unsigned long y; + /* only want the trailing 32 bits */ + y = x & 0xFFFFFFFFUL; + if (y ^ x) + return PyErr_Format(PyExc_OverflowError, + "long int larger than 32 bits"); + x = y; + } +#endif + } + else + return PyErr_Format(PyExc_TypeError, + "expected int/long, %s found", + Py_TYPE(arg)->tp_name); + return PyLong_FromUnsignedLong(htonl((unsigned long)x)); } PyDoc_STRVAR(htonl_doc, @@ -3600,20 +3600,20 @@ #define INADDR_NONE (-1) #endif #ifdef HAVE_INET_ATON - struct in_addr buf; + struct in_addr buf; #endif #if !defined(HAVE_INET_ATON) || defined(USE_INET_ATON_WEAKLINK) #if (SIZEOF_INT != 4) #error "Not sure if in_addr_t exists and int is not 32-bits." #endif - /* Have to use inet_addr() instead */ - unsigned int packed_addr; + /* Have to use inet_addr() instead */ + unsigned int packed_addr; #endif - char *ip_addr; + char *ip_addr; - if (!PyArg_ParseTuple(args, "s:inet_aton", &ip_addr)) - return NULL; + if (!PyArg_ParseTuple(args, "s:inet_aton", &ip_addr)) + return NULL; #ifdef HAVE_INET_ATON @@ -3621,13 +3621,13 @@ #ifdef USE_INET_ATON_WEAKLINK if (inet_aton != NULL) { #endif - if (inet_aton(ip_addr, &buf)) - return PyBytes_FromStringAndSize((char *)(&buf), - sizeof(buf)); - - PyErr_SetString(socket_error, - "illegal IP address string passed to inet_aton"); - return NULL; + if (inet_aton(ip_addr, &buf)) + return PyBytes_FromStringAndSize((char *)(&buf), + sizeof(buf)); + + PyErr_SetString(socket_error, + "illegal IP address string passed to inet_aton"); + return NULL; #ifdef USE_INET_ATON_WEAKLINK } else { @@ -3637,22 +3637,22 @@ #if !defined(HAVE_INET_ATON) || defined(USE_INET_ATON_WEAKLINK) - /* special-case this address as inet_addr might return INADDR_NONE - * for this */ - if (strcmp(ip_addr, "255.255.255.255") == 0) { - packed_addr = 0xFFFFFFFF; - } else { - - packed_addr = inet_addr(ip_addr); - - if (packed_addr == INADDR_NONE) { /* invalid address */ - PyErr_SetString(socket_error, - "illegal IP address string passed to inet_aton"); - return NULL; - } - } - return PyBytes_FromStringAndSize((char *) &packed_addr, - sizeof(packed_addr)); + /* special-case this address as inet_addr might return INADDR_NONE + * for this */ + if (strcmp(ip_addr, "255.255.255.255") == 0) { + packed_addr = 0xFFFFFFFF; + } else { + + packed_addr = inet_addr(ip_addr); + + if (packed_addr == INADDR_NONE) { /* invalid address */ + PyErr_SetString(socket_error, + "illegal IP address string passed to inet_aton"); + return NULL; + } + } + return PyBytes_FromStringAndSize((char *) &packed_addr, + sizeof(packed_addr)); #ifdef USE_INET_ATON_WEAKLINK } @@ -3669,23 +3669,23 @@ static PyObject* socket_inet_ntoa(PyObject *self, PyObject *args) { - char *packed_str; - int addr_len; - struct in_addr packed_addr; - - if (!PyArg_ParseTuple(args, "y#:inet_ntoa", &packed_str, &addr_len)) { - return NULL; - } - - if (addr_len != sizeof(packed_addr)) { - PyErr_SetString(socket_error, - "packed IP wrong length for inet_ntoa"); - return NULL; - } + char *packed_str; + int addr_len; + struct in_addr packed_addr; + + if (!PyArg_ParseTuple(args, "y#:inet_ntoa", &packed_str, &addr_len)) { + return NULL; + } + + if (addr_len != sizeof(packed_addr)) { + PyErr_SetString(socket_error, + "packed IP wrong length for inet_ntoa"); + return NULL; + } - memcpy(&packed_addr, packed_str, addr_len); + memcpy(&packed_addr, packed_str, addr_len); - return PyUnicode_FromString(inet_ntoa(packed_addr)); + return PyUnicode_FromString(inet_ntoa(packed_addr)); } #ifdef HAVE_INET_PTON @@ -3699,46 +3699,46 @@ static PyObject * socket_inet_pton(PyObject *self, PyObject *args) { - int af; - char* ip; - int retval; + int af; + char* ip; + int retval; #ifdef ENABLE_IPV6 - char packed[MAX(sizeof(struct in_addr), sizeof(struct in6_addr))]; + char packed[MAX(sizeof(struct in_addr), sizeof(struct in6_addr))]; #else - char packed[sizeof(struct in_addr)]; + char packed[sizeof(struct in_addr)]; #endif - if (!PyArg_ParseTuple(args, "is:inet_pton", &af, &ip)) { - return NULL; - } + if (!PyArg_ParseTuple(args, "is:inet_pton", &af, &ip)) { + return NULL; + } #if !defined(ENABLE_IPV6) && defined(AF_INET6) - if(af == AF_INET6) { - PyErr_SetString(socket_error, - "can't use AF_INET6, IPv6 is disabled"); - return NULL; - } -#endif - - retval = inet_pton(af, ip, packed); - if (retval < 0) { - PyErr_SetFromErrno(socket_error); - return NULL; - } else if (retval == 0) { - PyErr_SetString(socket_error, - "illegal IP address string passed to inet_pton"); - return NULL; - } else if (af == AF_INET) { - return PyBytes_FromStringAndSize(packed, - sizeof(struct in_addr)); + if(af == AF_INET6) { + PyErr_SetString(socket_error, + "can't use AF_INET6, IPv6 is disabled"); + return NULL; + } +#endif + + retval = inet_pton(af, ip, packed); + if (retval < 0) { + PyErr_SetFromErrno(socket_error); + return NULL; + } else if (retval == 0) { + PyErr_SetString(socket_error, + "illegal IP address string passed to inet_pton"); + return NULL; + } else if (af == AF_INET) { + return PyBytes_FromStringAndSize(packed, + sizeof(struct in_addr)); #ifdef ENABLE_IPV6 - } else if (af == AF_INET6) { - return PyBytes_FromStringAndSize(packed, - sizeof(struct in6_addr)); -#endif - } else { - PyErr_SetString(socket_error, "unknown address family"); - return NULL; - } + } else if (af == AF_INET6) { + return PyBytes_FromStringAndSize(packed, + sizeof(struct in6_addr)); +#endif + } else { + PyErr_SetString(socket_error, "unknown address family"); + return NULL; + } } PyDoc_STRVAR(inet_ntop_doc, @@ -3749,54 +3749,54 @@ static PyObject * socket_inet_ntop(PyObject *self, PyObject *args) { - int af; - char* packed; - int len; - const char* retval; + int af; + char* packed; + int len; + const char* retval; #ifdef ENABLE_IPV6 - char ip[MAX(INET_ADDRSTRLEN, INET6_ADDRSTRLEN) + 1]; + char ip[MAX(INET_ADDRSTRLEN, INET6_ADDRSTRLEN) + 1]; #else - char ip[INET_ADDRSTRLEN + 1]; + char ip[INET_ADDRSTRLEN + 1]; #endif - /* Guarantee NUL-termination for PyUnicode_FromString() below */ - memset((void *) &ip[0], '\0', sizeof(ip)); + /* Guarantee NUL-termination for PyUnicode_FromString() below */ + memset((void *) &ip[0], '\0', sizeof(ip)); - if (!PyArg_ParseTuple(args, "iy#:inet_ntop", &af, &packed, &len)) { - return NULL; - } + if (!PyArg_ParseTuple(args, "iy#:inet_ntop", &af, &packed, &len)) { + return NULL; + } - if (af == AF_INET) { - if (len != sizeof(struct in_addr)) { - PyErr_SetString(PyExc_ValueError, - "invalid length of packed IP address string"); - return NULL; - } + if (af == AF_INET) { + if (len != sizeof(struct in_addr)) { + PyErr_SetString(PyExc_ValueError, + "invalid length of packed IP address string"); + return NULL; + } #ifdef ENABLE_IPV6 - } else if (af == AF_INET6) { - if (len != sizeof(struct in6_addr)) { - PyErr_SetString(PyExc_ValueError, - "invalid length of packed IP address string"); - return NULL; - } -#endif - } else { - PyErr_Format(PyExc_ValueError, - "unknown address family %d", af); - return NULL; - } - - retval = inet_ntop(af, packed, ip, sizeof(ip)); - if (!retval) { - PyErr_SetFromErrno(socket_error); - return NULL; - } else { - return PyUnicode_FromString(retval); - } - - /* NOTREACHED */ - PyErr_SetString(PyExc_RuntimeError, "invalid handling of inet_ntop"); - return NULL; + } else if (af == AF_INET6) { + if (len != sizeof(struct in6_addr)) { + PyErr_SetString(PyExc_ValueError, + "invalid length of packed IP address string"); + return NULL; + } +#endif + } else { + PyErr_Format(PyExc_ValueError, + "unknown address family %d", af); + return NULL; + } + + retval = inet_ntop(af, packed, ip, sizeof(ip)); + if (!retval) { + PyErr_SetFromErrno(socket_error); + return NULL; + } else { + return PyUnicode_FromString(retval); + } + + /* NOTREACHED */ + PyErr_SetString(PyExc_RuntimeError, "invalid handling of inet_ntop"); + return NULL; } #endif /* HAVE_INET_PTON */ @@ -3807,100 +3807,100 @@ static PyObject * socket_getaddrinfo(PyObject *self, PyObject *args) { - struct addrinfo hints, *res; - struct addrinfo *res0 = NULL; - PyObject *hobj = NULL; - PyObject *pobj = (PyObject *)NULL; - char pbuf[30]; - char *hptr, *pptr; - int family, socktype, protocol, flags; - int error; - PyObject *all = (PyObject *)NULL; - PyObject *idna = NULL; - - family = socktype = protocol = flags = 0; - family = AF_UNSPEC; - if (!PyArg_ParseTuple(args, "OO|iiii:getaddrinfo", - &hobj, &pobj, &family, &socktype, - &protocol, &flags)) { - return NULL; - } - if (hobj == Py_None) { - hptr = NULL; - } else if (PyUnicode_Check(hobj)) { - idna = PyObject_CallMethod(hobj, "encode", "s", "idna"); - if (!idna) - return NULL; - assert(PyBytes_Check(idna)); - hptr = PyBytes_AS_STRING(idna); - } else if (PyBytes_Check(hobj)) { - hptr = PyBytes_AsString(hobj); - } else { - PyErr_SetString(PyExc_TypeError, - "getaddrinfo() argument 1 must be string or None"); - return NULL; - } - if (PyLong_CheckExact(pobj)) { - long value = PyLong_AsLong(pobj); - if (value == -1 && PyErr_Occurred()) - goto err; - PyOS_snprintf(pbuf, sizeof(pbuf), "%ld", value); - pptr = pbuf; - } else if (PyUnicode_Check(pobj)) { - pptr = _PyUnicode_AsString(pobj); - } else if (PyBytes_Check(pobj)) { - pptr = PyBytes_AsString(pobj); - } else if (pobj == Py_None) { - pptr = (char *)NULL; - } else { - PyErr_SetString(socket_error, "Int or String expected"); - goto err; - } - memset(&hints, 0, sizeof(hints)); - hints.ai_family = family; - hints.ai_socktype = socktype; - hints.ai_protocol = protocol; - hints.ai_flags = flags; - Py_BEGIN_ALLOW_THREADS - ACQUIRE_GETADDRINFO_LOCK - error = getaddrinfo(hptr, pptr, &hints, &res0); - Py_END_ALLOW_THREADS - RELEASE_GETADDRINFO_LOCK /* see comment in setipaddr() */ - if (error) { - set_gaierror(error); - goto err; - } - - if ((all = PyList_New(0)) == NULL) - goto err; - for (res = res0; res; res = res->ai_next) { - PyObject *single; - PyObject *addr = - makesockaddr(-1, res->ai_addr, res->ai_addrlen, protocol); - if (addr == NULL) - goto err; - single = Py_BuildValue("iiisO", res->ai_family, - res->ai_socktype, res->ai_protocol, - res->ai_canonname ? res->ai_canonname : "", - addr); - Py_DECREF(addr); - if (single == NULL) - goto err; - - if (PyList_Append(all, single)) - goto err; - Py_XDECREF(single); - } - Py_XDECREF(idna); - if (res0) - freeaddrinfo(res0); - return all; + struct addrinfo hints, *res; + struct addrinfo *res0 = NULL; + PyObject *hobj = NULL; + PyObject *pobj = (PyObject *)NULL; + char pbuf[30]; + char *hptr, *pptr; + int family, socktype, protocol, flags; + int error; + PyObject *all = (PyObject *)NULL; + PyObject *idna = NULL; + + family = socktype = protocol = flags = 0; + family = AF_UNSPEC; + if (!PyArg_ParseTuple(args, "OO|iiii:getaddrinfo", + &hobj, &pobj, &family, &socktype, + &protocol, &flags)) { + return NULL; + } + if (hobj == Py_None) { + hptr = NULL; + } else if (PyUnicode_Check(hobj)) { + idna = PyObject_CallMethod(hobj, "encode", "s", "idna"); + if (!idna) + return NULL; + assert(PyBytes_Check(idna)); + hptr = PyBytes_AS_STRING(idna); + } else if (PyBytes_Check(hobj)) { + hptr = PyBytes_AsString(hobj); + } else { + PyErr_SetString(PyExc_TypeError, + "getaddrinfo() argument 1 must be string or None"); + return NULL; + } + if (PyLong_CheckExact(pobj)) { + long value = PyLong_AsLong(pobj); + if (value == -1 && PyErr_Occurred()) + goto err; + PyOS_snprintf(pbuf, sizeof(pbuf), "%ld", value); + pptr = pbuf; + } else if (PyUnicode_Check(pobj)) { + pptr = _PyUnicode_AsString(pobj); + } else if (PyBytes_Check(pobj)) { + pptr = PyBytes_AsString(pobj); + } else if (pobj == Py_None) { + pptr = (char *)NULL; + } else { + PyErr_SetString(socket_error, "Int or String expected"); + goto err; + } + memset(&hints, 0, sizeof(hints)); + hints.ai_family = family; + hints.ai_socktype = socktype; + hints.ai_protocol = protocol; + hints.ai_flags = flags; + Py_BEGIN_ALLOW_THREADS + ACQUIRE_GETADDRINFO_LOCK + error = getaddrinfo(hptr, pptr, &hints, &res0); + Py_END_ALLOW_THREADS + RELEASE_GETADDRINFO_LOCK /* see comment in setipaddr() */ + if (error) { + set_gaierror(error); + goto err; + } + + if ((all = PyList_New(0)) == NULL) + goto err; + for (res = res0; res; res = res->ai_next) { + PyObject *single; + PyObject *addr = + makesockaddr(-1, res->ai_addr, res->ai_addrlen, protocol); + if (addr == NULL) + goto err; + single = Py_BuildValue("iiisO", res->ai_family, + res->ai_socktype, res->ai_protocol, + res->ai_canonname ? res->ai_canonname : "", + addr); + Py_DECREF(addr); + if (single == NULL) + goto err; + + if (PyList_Append(all, single)) + goto err; + Py_XDECREF(single); + } + Py_XDECREF(idna); + if (res0) + freeaddrinfo(res0); + return all; err: - Py_XDECREF(all); - Py_XDECREF(idna); - if (res0) - freeaddrinfo(res0); - return (PyObject *)NULL; + Py_XDECREF(all); + Py_XDECREF(idna); + if (res0) + freeaddrinfo(res0); + return (PyObject *)NULL; } PyDoc_STRVAR(getaddrinfo_doc, @@ -3915,77 +3915,77 @@ static PyObject * socket_getnameinfo(PyObject *self, PyObject *args) { - PyObject *sa = (PyObject *)NULL; - int flags; - char *hostp; - int port, flowinfo, scope_id; - char hbuf[NI_MAXHOST], pbuf[NI_MAXSERV]; - struct addrinfo hints, *res = NULL; - int error; - PyObject *ret = (PyObject *)NULL; - - flags = flowinfo = scope_id = 0; - if (!PyArg_ParseTuple(args, "Oi:getnameinfo", &sa, &flags)) - return NULL; - if (!PyTuple_Check(sa)) { - PyErr_SetString(PyExc_TypeError, - "getnameinfo() argument 1 must be a tuple"); - return NULL; - } - if (!PyArg_ParseTuple(sa, "si|ii", - &hostp, &port, &flowinfo, &scope_id)) - return NULL; - PyOS_snprintf(pbuf, sizeof(pbuf), "%d", port); - memset(&hints, 0, sizeof(hints)); - hints.ai_family = AF_UNSPEC; - hints.ai_socktype = SOCK_DGRAM; /* make numeric port happy */ - Py_BEGIN_ALLOW_THREADS - ACQUIRE_GETADDRINFO_LOCK - error = getaddrinfo(hostp, pbuf, &hints, &res); - Py_END_ALLOW_THREADS - RELEASE_GETADDRINFO_LOCK /* see comment in setipaddr() */ - if (error) { - set_gaierror(error); - goto fail; - } - if (res->ai_next) { - PyErr_SetString(socket_error, - "sockaddr resolved to multiple addresses"); - goto fail; - } - switch (res->ai_family) { - case AF_INET: - { - if (PyTuple_GET_SIZE(sa) != 2) { - PyErr_SetString(socket_error, - "IPv4 sockaddr must be 2 tuple"); - goto fail; - } - break; - } + PyObject *sa = (PyObject *)NULL; + int flags; + char *hostp; + int port, flowinfo, scope_id; + char hbuf[NI_MAXHOST], pbuf[NI_MAXSERV]; + struct addrinfo hints, *res = NULL; + int error; + PyObject *ret = (PyObject *)NULL; + + flags = flowinfo = scope_id = 0; + if (!PyArg_ParseTuple(args, "Oi:getnameinfo", &sa, &flags)) + return NULL; + if (!PyTuple_Check(sa)) { + PyErr_SetString(PyExc_TypeError, + "getnameinfo() argument 1 must be a tuple"); + return NULL; + } + if (!PyArg_ParseTuple(sa, "si|ii", + &hostp, &port, &flowinfo, &scope_id)) + return NULL; + PyOS_snprintf(pbuf, sizeof(pbuf), "%d", port); + memset(&hints, 0, sizeof(hints)); + hints.ai_family = AF_UNSPEC; + hints.ai_socktype = SOCK_DGRAM; /* make numeric port happy */ + Py_BEGIN_ALLOW_THREADS + ACQUIRE_GETADDRINFO_LOCK + error = getaddrinfo(hostp, pbuf, &hints, &res); + Py_END_ALLOW_THREADS + RELEASE_GETADDRINFO_LOCK /* see comment in setipaddr() */ + if (error) { + set_gaierror(error); + goto fail; + } + if (res->ai_next) { + PyErr_SetString(socket_error, + "sockaddr resolved to multiple addresses"); + goto fail; + } + switch (res->ai_family) { + case AF_INET: + { + if (PyTuple_GET_SIZE(sa) != 2) { + PyErr_SetString(socket_error, + "IPv4 sockaddr must be 2 tuple"); + goto fail; + } + break; + } #ifdef ENABLE_IPV6 - case AF_INET6: - { - struct sockaddr_in6 *sin6; - sin6 = (struct sockaddr_in6 *)res->ai_addr; - sin6->sin6_flowinfo = flowinfo; - sin6->sin6_scope_id = scope_id; - break; - } -#endif - } - error = getnameinfo(res->ai_addr, res->ai_addrlen, - hbuf, sizeof(hbuf), pbuf, sizeof(pbuf), flags); - if (error) { - set_gaierror(error); - goto fail; - } - ret = Py_BuildValue("ss", hbuf, pbuf); + case AF_INET6: + { + struct sockaddr_in6 *sin6; + sin6 = (struct sockaddr_in6 *)res->ai_addr; + sin6->sin6_flowinfo = flowinfo; + sin6->sin6_scope_id = scope_id; + break; + } +#endif + } + error = getnameinfo(res->ai_addr, res->ai_addrlen, + hbuf, sizeof(hbuf), pbuf, sizeof(pbuf), flags); + if (error) { + set_gaierror(error); + goto fail; + } + ret = Py_BuildValue("ss", hbuf, pbuf); fail: - if (res) - freeaddrinfo(res); - return ret; + if (res) + freeaddrinfo(res); + return ret; } PyDoc_STRVAR(getnameinfo_doc, @@ -3999,12 +3999,12 @@ static PyObject * socket_getdefaulttimeout(PyObject *self) { - if (defaulttimeout < 0.0) { - Py_INCREF(Py_None); - return Py_None; - } - else - return PyFloat_FromDouble(defaulttimeout); + if (defaulttimeout < 0.0) { + Py_INCREF(Py_None); + return Py_None; + } + else + return PyFloat_FromDouble(defaulttimeout); } PyDoc_STRVAR(getdefaulttimeout_doc, @@ -4017,24 +4017,24 @@ static PyObject * socket_setdefaulttimeout(PyObject *self, PyObject *arg) { - double timeout; + double timeout; - if (arg == Py_None) - timeout = -1.0; - else { - timeout = PyFloat_AsDouble(arg); - if (timeout < 0.0) { - if (!PyErr_Occurred()) - PyErr_SetString(PyExc_ValueError, - "Timeout value out of range"); - return NULL; - } - } + if (arg == Py_None) + timeout = -1.0; + else { + timeout = PyFloat_AsDouble(arg); + if (timeout < 0.0) { + if (!PyErr_Occurred()) + PyErr_SetString(PyExc_ValueError, + "Timeout value out of range"); + return NULL; + } + } - defaulttimeout = timeout; + defaulttimeout = timeout; - Py_INCREF(Py_None); - return Py_None; + Py_INCREF(Py_None); + return Py_None; } PyDoc_STRVAR(setdefaulttimeout_doc, @@ -4048,55 +4048,55 @@ /* List of functions exported by this module. */ static PyMethodDef socket_methods[] = { - {"gethostbyname", socket_gethostbyname, - METH_VARARGS, gethostbyname_doc}, - {"gethostbyname_ex", socket_gethostbyname_ex, - METH_VARARGS, ghbn_ex_doc}, - {"gethostbyaddr", socket_gethostbyaddr, - METH_VARARGS, gethostbyaddr_doc}, - {"gethostname", socket_gethostname, - METH_NOARGS, gethostname_doc}, - {"getservbyname", socket_getservbyname, - METH_VARARGS, getservbyname_doc}, - {"getservbyport", socket_getservbyport, - METH_VARARGS, getservbyport_doc}, - {"getprotobyname", socket_getprotobyname, - METH_VARARGS, getprotobyname_doc}, + {"gethostbyname", socket_gethostbyname, + METH_VARARGS, gethostbyname_doc}, + {"gethostbyname_ex", socket_gethostbyname_ex, + METH_VARARGS, ghbn_ex_doc}, + {"gethostbyaddr", socket_gethostbyaddr, + METH_VARARGS, gethostbyaddr_doc}, + {"gethostname", socket_gethostname, + METH_NOARGS, gethostname_doc}, + {"getservbyname", socket_getservbyname, + METH_VARARGS, getservbyname_doc}, + {"getservbyport", socket_getservbyport, + METH_VARARGS, getservbyport_doc}, + {"getprotobyname", socket_getprotobyname, + METH_VARARGS, getprotobyname_doc}, #ifndef NO_DUP - {"dup", socket_dup, - METH_O, dup_doc}, + {"dup", socket_dup, + METH_O, dup_doc}, #endif #ifdef HAVE_SOCKETPAIR - {"socketpair", socket_socketpair, - METH_VARARGS, socketpair_doc}, + {"socketpair", socket_socketpair, + METH_VARARGS, socketpair_doc}, #endif - {"ntohs", socket_ntohs, - METH_VARARGS, ntohs_doc}, - {"ntohl", socket_ntohl, - METH_O, ntohl_doc}, - {"htons", socket_htons, - METH_VARARGS, htons_doc}, - {"htonl", socket_htonl, - METH_O, htonl_doc}, - {"inet_aton", socket_inet_aton, - METH_VARARGS, inet_aton_doc}, - {"inet_ntoa", socket_inet_ntoa, - METH_VARARGS, inet_ntoa_doc}, + {"ntohs", socket_ntohs, + METH_VARARGS, ntohs_doc}, + {"ntohl", socket_ntohl, + METH_O, ntohl_doc}, + {"htons", socket_htons, + METH_VARARGS, htons_doc}, + {"htonl", socket_htonl, + METH_O, htonl_doc}, + {"inet_aton", socket_inet_aton, + METH_VARARGS, inet_aton_doc}, + {"inet_ntoa", socket_inet_ntoa, + METH_VARARGS, inet_ntoa_doc}, #ifdef HAVE_INET_PTON - {"inet_pton", socket_inet_pton, - METH_VARARGS, inet_pton_doc}, - {"inet_ntop", socket_inet_ntop, - METH_VARARGS, inet_ntop_doc}, -#endif - {"getaddrinfo", socket_getaddrinfo, - METH_VARARGS, getaddrinfo_doc}, - {"getnameinfo", socket_getnameinfo, - METH_VARARGS, getnameinfo_doc}, - {"getdefaulttimeout", (PyCFunction)socket_getdefaulttimeout, - METH_NOARGS, getdefaulttimeout_doc}, - {"setdefaulttimeout", socket_setdefaulttimeout, - METH_O, setdefaulttimeout_doc}, - {NULL, NULL} /* Sentinel */ + {"inet_pton", socket_inet_pton, + METH_VARARGS, inet_pton_doc}, + {"inet_ntop", socket_inet_ntop, + METH_VARARGS, inet_ntop_doc}, +#endif + {"getaddrinfo", socket_getaddrinfo, + METH_VARARGS, getaddrinfo_doc}, + {"getnameinfo", socket_getnameinfo, + METH_VARARGS, getnameinfo_doc}, + {"getdefaulttimeout", (PyCFunction)socket_getdefaulttimeout, + METH_NOARGS, getdefaulttimeout_doc}, + {"setdefaulttimeout", socket_setdefaulttimeout, + METH_O, setdefaulttimeout_doc}, + {NULL, NULL} /* Sentinel */ }; @@ -4108,34 +4108,34 @@ static void os_cleanup(void) { - WSACleanup(); + WSACleanup(); } static int os_init(void) { - WSADATA WSAData; - int ret; - ret = WSAStartup(0x0101, &WSAData); - switch (ret) { - case 0: /* No error */ - Py_AtExit(os_cleanup); - return 1; /* Success */ - case WSASYSNOTREADY: - PyErr_SetString(PyExc_ImportError, - "WSAStartup failed: network not ready"); - break; - case WSAVERNOTSUPPORTED: - case WSAEINVAL: - PyErr_SetString( - PyExc_ImportError, - "WSAStartup failed: requested version not supported"); - break; - default: - PyErr_Format(PyExc_ImportError, "WSAStartup failed: error code %d", ret); - break; - } - return 0; /* Failure */ + WSADATA WSAData; + int ret; + ret = WSAStartup(0x0101, &WSAData); + switch (ret) { + case 0: /* No error */ + Py_AtExit(os_cleanup); + return 1; /* Success */ + case WSASYSNOTREADY: + PyErr_SetString(PyExc_ImportError, + "WSAStartup failed: network not ready"); + break; + case WSAVERNOTSUPPORTED: + case WSAEINVAL: + PyErr_SetString( + PyExc_ImportError, + "WSAStartup failed: requested version not supported"); + break; + default: + PyErr_Format(PyExc_ImportError, "WSAStartup failed: error code %d", ret); + break; + } + return 0; /* Failure */ } #endif /* MS_WINDOWS */ @@ -4150,18 +4150,18 @@ os_init(void) { #ifndef PYCC_GCC - int rc = sock_init(); + int rc = sock_init(); - if (rc == 0) { - return 1; /* Success */ - } + if (rc == 0) { + return 1; /* Success */ + } - PyErr_Format(PyExc_ImportError, "OS/2 TCP/IP Error# %d", sock_errno()); + PyErr_Format(PyExc_ImportError, "OS/2 TCP/IP Error# %d", sock_errno()); - return 0; /* Failure */ + return 0; /* Failure */ #else - /* No need to initialise sockets with GCC/EMX */ - return 1; /* Success */ + /* No need to initialise sockets with GCC/EMX */ + return 1; /* Success */ #endif } @@ -4172,7 +4172,7 @@ static int os_init(void) { - return 1; /* Success */ + return 1; /* Success */ } #endif @@ -4182,8 +4182,8 @@ static PySocketModule_APIObject PySocketModuleAPI = { - &sock_type, - NULL + &sock_type, + NULL }; @@ -4203,931 +4203,931 @@ See the socket module for documentation."); static struct PyModuleDef socketmodule = { - PyModuleDef_HEAD_INIT, - PySocket_MODULE_NAME, - socket_doc, - -1, - socket_methods, - NULL, - NULL, - NULL, - NULL + PyModuleDef_HEAD_INIT, + PySocket_MODULE_NAME, + socket_doc, + -1, + socket_methods, + NULL, + NULL, + NULL, + NULL }; PyMODINIT_FUNC PyInit__socket(void) { - PyObject *m, *has_ipv6; + PyObject *m, *has_ipv6; - if (!os_init()) - return NULL; + if (!os_init()) + return NULL; - Py_TYPE(&sock_type) = &PyType_Type; - m = PyModule_Create(&socketmodule); - if (m == NULL) - return NULL; - - socket_error = PyErr_NewException("socket.error", - PyExc_IOError, NULL); - if (socket_error == NULL) - return NULL; - PySocketModuleAPI.error = socket_error; - Py_INCREF(socket_error); - PyModule_AddObject(m, "error", socket_error); - socket_herror = PyErr_NewException("socket.herror", - socket_error, NULL); - if (socket_herror == NULL) - return NULL; - Py_INCREF(socket_herror); - PyModule_AddObject(m, "herror", socket_herror); - socket_gaierror = PyErr_NewException("socket.gaierror", socket_error, - NULL); - if (socket_gaierror == NULL) - return NULL; - Py_INCREF(socket_gaierror); - PyModule_AddObject(m, "gaierror", socket_gaierror); - socket_timeout = PyErr_NewException("socket.timeout", - socket_error, NULL); - if (socket_timeout == NULL) - return NULL; - Py_INCREF(socket_timeout); - PyModule_AddObject(m, "timeout", socket_timeout); - Py_INCREF((PyObject *)&sock_type); - if (PyModule_AddObject(m, "SocketType", - (PyObject *)&sock_type) != 0) - return NULL; - Py_INCREF((PyObject *)&sock_type); - if (PyModule_AddObject(m, "socket", - (PyObject *)&sock_type) != 0) - return NULL; + Py_TYPE(&sock_type) = &PyType_Type; + m = PyModule_Create(&socketmodule); + if (m == NULL) + return NULL; + + socket_error = PyErr_NewException("socket.error", + PyExc_IOError, NULL); + if (socket_error == NULL) + return NULL; + PySocketModuleAPI.error = socket_error; + Py_INCREF(socket_error); + PyModule_AddObject(m, "error", socket_error); + socket_herror = PyErr_NewException("socket.herror", + socket_error, NULL); + if (socket_herror == NULL) + return NULL; + Py_INCREF(socket_herror); + PyModule_AddObject(m, "herror", socket_herror); + socket_gaierror = PyErr_NewException("socket.gaierror", socket_error, + NULL); + if (socket_gaierror == NULL) + return NULL; + Py_INCREF(socket_gaierror); + PyModule_AddObject(m, "gaierror", socket_gaierror); + socket_timeout = PyErr_NewException("socket.timeout", + socket_error, NULL); + if (socket_timeout == NULL) + return NULL; + Py_INCREF(socket_timeout); + PyModule_AddObject(m, "timeout", socket_timeout); + Py_INCREF((PyObject *)&sock_type); + if (PyModule_AddObject(m, "SocketType", + (PyObject *)&sock_type) != 0) + return NULL; + Py_INCREF((PyObject *)&sock_type); + if (PyModule_AddObject(m, "socket", + (PyObject *)&sock_type) != 0) + return NULL; #ifdef ENABLE_IPV6 - has_ipv6 = Py_True; + has_ipv6 = Py_True; #else - has_ipv6 = Py_False; + has_ipv6 = Py_False; #endif - Py_INCREF(has_ipv6); - PyModule_AddObject(m, "has_ipv6", has_ipv6); + Py_INCREF(has_ipv6); + PyModule_AddObject(m, "has_ipv6", has_ipv6); - /* Export C API */ - if (PyModule_AddObject(m, PySocket_CAPI_NAME, - PyCapsule_New(&PySocketModuleAPI, PySocket_CAPSULE_NAME, NULL) - ) != 0) - return NULL; + /* Export C API */ + if (PyModule_AddObject(m, PySocket_CAPI_NAME, + PyCapsule_New(&PySocketModuleAPI, PySocket_CAPSULE_NAME, NULL) + ) != 0) + return NULL; - /* Address families (we only support AF_INET and AF_UNIX) */ + /* Address families (we only support AF_INET and AF_UNIX) */ #ifdef AF_UNSPEC - PyModule_AddIntConstant(m, "AF_UNSPEC", AF_UNSPEC); + PyModule_AddIntConstant(m, "AF_UNSPEC", AF_UNSPEC); #endif - PyModule_AddIntConstant(m, "AF_INET", AF_INET); + PyModule_AddIntConstant(m, "AF_INET", AF_INET); #ifdef AF_INET6 - PyModule_AddIntConstant(m, "AF_INET6", AF_INET6); + PyModule_AddIntConstant(m, "AF_INET6", AF_INET6); #endif /* AF_INET6 */ #if defined(AF_UNIX) - PyModule_AddIntConstant(m, "AF_UNIX", AF_UNIX); + PyModule_AddIntConstant(m, "AF_UNIX", AF_UNIX); #endif /* AF_UNIX */ #ifdef AF_AX25 - /* Amateur Radio AX.25 */ - PyModule_AddIntConstant(m, "AF_AX25", AF_AX25); + /* Amateur Radio AX.25 */ + PyModule_AddIntConstant(m, "AF_AX25", AF_AX25); #endif #ifdef AF_IPX - PyModule_AddIntConstant(m, "AF_IPX", AF_IPX); /* Novell IPX */ + PyModule_AddIntConstant(m, "AF_IPX", AF_IPX); /* Novell IPX */ #endif #ifdef AF_APPLETALK - /* Appletalk DDP */ - PyModule_AddIntConstant(m, "AF_APPLETALK", AF_APPLETALK); + /* Appletalk DDP */ + PyModule_AddIntConstant(m, "AF_APPLETALK", AF_APPLETALK); #endif #ifdef AF_NETROM - /* Amateur radio NetROM */ - PyModule_AddIntConstant(m, "AF_NETROM", AF_NETROM); + /* Amateur radio NetROM */ + PyModule_AddIntConstant(m, "AF_NETROM", AF_NETROM); #endif #ifdef AF_BRIDGE - /* Multiprotocol bridge */ - PyModule_AddIntConstant(m, "AF_BRIDGE", AF_BRIDGE); + /* Multiprotocol bridge */ + PyModule_AddIntConstant(m, "AF_BRIDGE", AF_BRIDGE); #endif #ifdef AF_ATMPVC - /* ATM PVCs */ - PyModule_AddIntConstant(m, "AF_ATMPVC", AF_ATMPVC); + /* ATM PVCs */ + PyModule_AddIntConstant(m, "AF_ATMPVC", AF_ATMPVC); #endif #ifdef AF_AAL5 - /* Reserved for Werner's ATM */ - PyModule_AddIntConstant(m, "AF_AAL5", AF_AAL5); + /* Reserved for Werner's ATM */ + PyModule_AddIntConstant(m, "AF_AAL5", AF_AAL5); #endif #ifdef AF_X25 - /* Reserved for X.25 project */ - PyModule_AddIntConstant(m, "AF_X25", AF_X25); + /* Reserved for X.25 project */ + PyModule_AddIntConstant(m, "AF_X25", AF_X25); #endif #ifdef AF_INET6 - PyModule_AddIntConstant(m, "AF_INET6", AF_INET6); /* IP version 6 */ + PyModule_AddIntConstant(m, "AF_INET6", AF_INET6); /* IP version 6 */ #endif #ifdef AF_ROSE - /* Amateur Radio X.25 PLP */ - PyModule_AddIntConstant(m, "AF_ROSE", AF_ROSE); + /* Amateur Radio X.25 PLP */ + PyModule_AddIntConstant(m, "AF_ROSE", AF_ROSE); #endif #ifdef AF_DECnet - /* Reserved for DECnet project */ - PyModule_AddIntConstant(m, "AF_DECnet", AF_DECnet); + /* Reserved for DECnet project */ + PyModule_AddIntConstant(m, "AF_DECnet", AF_DECnet); #endif #ifdef AF_NETBEUI - /* Reserved for 802.2LLC project */ - PyModule_AddIntConstant(m, "AF_NETBEUI", AF_NETBEUI); + /* Reserved for 802.2LLC project */ + PyModule_AddIntConstant(m, "AF_NETBEUI", AF_NETBEUI); #endif #ifdef AF_SECURITY - /* Security callback pseudo AF */ - PyModule_AddIntConstant(m, "AF_SECURITY", AF_SECURITY); + /* Security callback pseudo AF */ + PyModule_AddIntConstant(m, "AF_SECURITY", AF_SECURITY); #endif #ifdef AF_KEY - /* PF_KEY key management API */ - PyModule_AddIntConstant(m, "AF_KEY", AF_KEY); + /* PF_KEY key management API */ + PyModule_AddIntConstant(m, "AF_KEY", AF_KEY); #endif #ifdef AF_NETLINK - /* */ - PyModule_AddIntConstant(m, "AF_NETLINK", AF_NETLINK); - PyModule_AddIntConstant(m, "NETLINK_ROUTE", NETLINK_ROUTE); + /* */ + PyModule_AddIntConstant(m, "AF_NETLINK", AF_NETLINK); + PyModule_AddIntConstant(m, "NETLINK_ROUTE", NETLINK_ROUTE); #ifdef NETLINK_SKIP - PyModule_AddIntConstant(m, "NETLINK_SKIP", NETLINK_SKIP); + PyModule_AddIntConstant(m, "NETLINK_SKIP", NETLINK_SKIP); #endif #ifdef NETLINK_W1 - PyModule_AddIntConstant(m, "NETLINK_W1", NETLINK_W1); + PyModule_AddIntConstant(m, "NETLINK_W1", NETLINK_W1); #endif - PyModule_AddIntConstant(m, "NETLINK_USERSOCK", NETLINK_USERSOCK); - PyModule_AddIntConstant(m, "NETLINK_FIREWALL", NETLINK_FIREWALL); + PyModule_AddIntConstant(m, "NETLINK_USERSOCK", NETLINK_USERSOCK); + PyModule_AddIntConstant(m, "NETLINK_FIREWALL", NETLINK_FIREWALL); #ifdef NETLINK_TCPDIAG - PyModule_AddIntConstant(m, "NETLINK_TCPDIAG", NETLINK_TCPDIAG); + PyModule_AddIntConstant(m, "NETLINK_TCPDIAG", NETLINK_TCPDIAG); #endif #ifdef NETLINK_NFLOG - PyModule_AddIntConstant(m, "NETLINK_NFLOG", NETLINK_NFLOG); + PyModule_AddIntConstant(m, "NETLINK_NFLOG", NETLINK_NFLOG); #endif #ifdef NETLINK_XFRM - PyModule_AddIntConstant(m, "NETLINK_XFRM", NETLINK_XFRM); + PyModule_AddIntConstant(m, "NETLINK_XFRM", NETLINK_XFRM); #endif #ifdef NETLINK_ARPD - PyModule_AddIntConstant(m, "NETLINK_ARPD", NETLINK_ARPD); + PyModule_AddIntConstant(m, "NETLINK_ARPD", NETLINK_ARPD); #endif #ifdef NETLINK_ROUTE6 - PyModule_AddIntConstant(m, "NETLINK_ROUTE6", NETLINK_ROUTE6); + PyModule_AddIntConstant(m, "NETLINK_ROUTE6", NETLINK_ROUTE6); #endif - PyModule_AddIntConstant(m, "NETLINK_IP6_FW", NETLINK_IP6_FW); + PyModule_AddIntConstant(m, "NETLINK_IP6_FW", NETLINK_IP6_FW); #ifdef NETLINK_DNRTMSG - PyModule_AddIntConstant(m, "NETLINK_DNRTMSG", NETLINK_DNRTMSG); + PyModule_AddIntConstant(m, "NETLINK_DNRTMSG", NETLINK_DNRTMSG); #endif #ifdef NETLINK_TAPBASE - PyModule_AddIntConstant(m, "NETLINK_TAPBASE", NETLINK_TAPBASE); + PyModule_AddIntConstant(m, "NETLINK_TAPBASE", NETLINK_TAPBASE); #endif #endif /* AF_NETLINK */ #ifdef AF_ROUTE - /* Alias to emulate 4.4BSD */ - PyModule_AddIntConstant(m, "AF_ROUTE", AF_ROUTE); + /* Alias to emulate 4.4BSD */ + PyModule_AddIntConstant(m, "AF_ROUTE", AF_ROUTE); #endif #ifdef AF_ASH - /* Ash */ - PyModule_AddIntConstant(m, "AF_ASH", AF_ASH); + /* Ash */ + PyModule_AddIntConstant(m, "AF_ASH", AF_ASH); #endif #ifdef AF_ECONET - /* Acorn Econet */ - PyModule_AddIntConstant(m, "AF_ECONET", AF_ECONET); + /* Acorn Econet */ + PyModule_AddIntConstant(m, "AF_ECONET", AF_ECONET); #endif #ifdef AF_ATMSVC - /* ATM SVCs */ - PyModule_AddIntConstant(m, "AF_ATMSVC", AF_ATMSVC); + /* ATM SVCs */ + PyModule_AddIntConstant(m, "AF_ATMSVC", AF_ATMSVC); #endif #ifdef AF_SNA - /* Linux SNA Project (nutters!) */ - PyModule_AddIntConstant(m, "AF_SNA", AF_SNA); + /* Linux SNA Project (nutters!) */ + PyModule_AddIntConstant(m, "AF_SNA", AF_SNA); #endif #ifdef AF_IRDA - /* IRDA sockets */ - PyModule_AddIntConstant(m, "AF_IRDA", AF_IRDA); + /* IRDA sockets */ + PyModule_AddIntConstant(m, "AF_IRDA", AF_IRDA); #endif #ifdef AF_PPPOX - /* PPPoX sockets */ - PyModule_AddIntConstant(m, "AF_PPPOX", AF_PPPOX); + /* PPPoX sockets */ + PyModule_AddIntConstant(m, "AF_PPPOX", AF_PPPOX); #endif #ifdef AF_WANPIPE - /* Wanpipe API Sockets */ - PyModule_AddIntConstant(m, "AF_WANPIPE", AF_WANPIPE); + /* Wanpipe API Sockets */ + PyModule_AddIntConstant(m, "AF_WANPIPE", AF_WANPIPE); #endif #ifdef AF_LLC - /* Linux LLC */ - PyModule_AddIntConstant(m, "AF_LLC", AF_LLC); + /* Linux LLC */ + PyModule_AddIntConstant(m, "AF_LLC", AF_LLC); #endif #ifdef USE_BLUETOOTH - PyModule_AddIntConstant(m, "AF_BLUETOOTH", AF_BLUETOOTH); - PyModule_AddIntConstant(m, "BTPROTO_L2CAP", BTPROTO_L2CAP); - PyModule_AddIntConstant(m, "BTPROTO_HCI", BTPROTO_HCI); - PyModule_AddIntConstant(m, "SOL_HCI", SOL_HCI); - PyModule_AddIntConstant(m, "HCI_FILTER", HCI_FILTER); + PyModule_AddIntConstant(m, "AF_BLUETOOTH", AF_BLUETOOTH); + PyModule_AddIntConstant(m, "BTPROTO_L2CAP", BTPROTO_L2CAP); + PyModule_AddIntConstant(m, "BTPROTO_HCI", BTPROTO_HCI); + PyModule_AddIntConstant(m, "SOL_HCI", SOL_HCI); + PyModule_AddIntConstant(m, "HCI_FILTER", HCI_FILTER); #if !defined(__FreeBSD__) - PyModule_AddIntConstant(m, "HCI_TIME_STAMP", HCI_TIME_STAMP); - PyModule_AddIntConstant(m, "HCI_DATA_DIR", HCI_DATA_DIR); - PyModule_AddIntConstant(m, "BTPROTO_SCO", BTPROTO_SCO); -#endif - PyModule_AddIntConstant(m, "BTPROTO_RFCOMM", BTPROTO_RFCOMM); - PyModule_AddStringConstant(m, "BDADDR_ANY", "00:00:00:00:00:00"); - PyModule_AddStringConstant(m, "BDADDR_LOCAL", "00:00:00:FF:FF:FF"); + PyModule_AddIntConstant(m, "HCI_TIME_STAMP", HCI_TIME_STAMP); + PyModule_AddIntConstant(m, "HCI_DATA_DIR", HCI_DATA_DIR); + PyModule_AddIntConstant(m, "BTPROTO_SCO", BTPROTO_SCO); +#endif + PyModule_AddIntConstant(m, "BTPROTO_RFCOMM", BTPROTO_RFCOMM); + PyModule_AddStringConstant(m, "BDADDR_ANY", "00:00:00:00:00:00"); + PyModule_AddStringConstant(m, "BDADDR_LOCAL", "00:00:00:FF:FF:FF"); #endif #ifdef HAVE_NETPACKET_PACKET_H - PyModule_AddIntConstant(m, "AF_PACKET", AF_PACKET); - PyModule_AddIntConstant(m, "PF_PACKET", PF_PACKET); - PyModule_AddIntConstant(m, "PACKET_HOST", PACKET_HOST); - PyModule_AddIntConstant(m, "PACKET_BROADCAST", PACKET_BROADCAST); - PyModule_AddIntConstant(m, "PACKET_MULTICAST", PACKET_MULTICAST); - PyModule_AddIntConstant(m, "PACKET_OTHERHOST", PACKET_OTHERHOST); - PyModule_AddIntConstant(m, "PACKET_OUTGOING", PACKET_OUTGOING); - PyModule_AddIntConstant(m, "PACKET_LOOPBACK", PACKET_LOOPBACK); - PyModule_AddIntConstant(m, "PACKET_FASTROUTE", PACKET_FASTROUTE); + PyModule_AddIntConstant(m, "AF_PACKET", AF_PACKET); + PyModule_AddIntConstant(m, "PF_PACKET", PF_PACKET); + PyModule_AddIntConstant(m, "PACKET_HOST", PACKET_HOST); + PyModule_AddIntConstant(m, "PACKET_BROADCAST", PACKET_BROADCAST); + PyModule_AddIntConstant(m, "PACKET_MULTICAST", PACKET_MULTICAST); + PyModule_AddIntConstant(m, "PACKET_OTHERHOST", PACKET_OTHERHOST); + PyModule_AddIntConstant(m, "PACKET_OUTGOING", PACKET_OUTGOING); + PyModule_AddIntConstant(m, "PACKET_LOOPBACK", PACKET_LOOPBACK); + PyModule_AddIntConstant(m, "PACKET_FASTROUTE", PACKET_FASTROUTE); #endif #ifdef HAVE_LINUX_TIPC_H - PyModule_AddIntConstant(m, "AF_TIPC", AF_TIPC); + PyModule_AddIntConstant(m, "AF_TIPC", AF_TIPC); - /* for addresses */ - PyModule_AddIntConstant(m, "TIPC_ADDR_NAMESEQ", TIPC_ADDR_NAMESEQ); - PyModule_AddIntConstant(m, "TIPC_ADDR_NAME", TIPC_ADDR_NAME); - PyModule_AddIntConstant(m, "TIPC_ADDR_ID", TIPC_ADDR_ID); - - PyModule_AddIntConstant(m, "TIPC_ZONE_SCOPE", TIPC_ZONE_SCOPE); - PyModule_AddIntConstant(m, "TIPC_CLUSTER_SCOPE", TIPC_CLUSTER_SCOPE); - PyModule_AddIntConstant(m, "TIPC_NODE_SCOPE", TIPC_NODE_SCOPE); - - /* for setsockopt() */ - PyModule_AddIntConstant(m, "SOL_TIPC", SOL_TIPC); - PyModule_AddIntConstant(m, "TIPC_IMPORTANCE", TIPC_IMPORTANCE); - PyModule_AddIntConstant(m, "TIPC_SRC_DROPPABLE", TIPC_SRC_DROPPABLE); - PyModule_AddIntConstant(m, "TIPC_DEST_DROPPABLE", - TIPC_DEST_DROPPABLE); - PyModule_AddIntConstant(m, "TIPC_CONN_TIMEOUT", TIPC_CONN_TIMEOUT); - - PyModule_AddIntConstant(m, "TIPC_LOW_IMPORTANCE", - TIPC_LOW_IMPORTANCE); - PyModule_AddIntConstant(m, "TIPC_MEDIUM_IMPORTANCE", - TIPC_MEDIUM_IMPORTANCE); - PyModule_AddIntConstant(m, "TIPC_HIGH_IMPORTANCE", - TIPC_HIGH_IMPORTANCE); - PyModule_AddIntConstant(m, "TIPC_CRITICAL_IMPORTANCE", - TIPC_CRITICAL_IMPORTANCE); - - /* for subscriptions */ - PyModule_AddIntConstant(m, "TIPC_SUB_PORTS", TIPC_SUB_PORTS); - PyModule_AddIntConstant(m, "TIPC_SUB_SERVICE", TIPC_SUB_SERVICE); + /* for addresses */ + PyModule_AddIntConstant(m, "TIPC_ADDR_NAMESEQ", TIPC_ADDR_NAMESEQ); + PyModule_AddIntConstant(m, "TIPC_ADDR_NAME", TIPC_ADDR_NAME); + PyModule_AddIntConstant(m, "TIPC_ADDR_ID", TIPC_ADDR_ID); + + PyModule_AddIntConstant(m, "TIPC_ZONE_SCOPE", TIPC_ZONE_SCOPE); + PyModule_AddIntConstant(m, "TIPC_CLUSTER_SCOPE", TIPC_CLUSTER_SCOPE); + PyModule_AddIntConstant(m, "TIPC_NODE_SCOPE", TIPC_NODE_SCOPE); + + /* for setsockopt() */ + PyModule_AddIntConstant(m, "SOL_TIPC", SOL_TIPC); + PyModule_AddIntConstant(m, "TIPC_IMPORTANCE", TIPC_IMPORTANCE); + PyModule_AddIntConstant(m, "TIPC_SRC_DROPPABLE", TIPC_SRC_DROPPABLE); + PyModule_AddIntConstant(m, "TIPC_DEST_DROPPABLE", + TIPC_DEST_DROPPABLE); + PyModule_AddIntConstant(m, "TIPC_CONN_TIMEOUT", TIPC_CONN_TIMEOUT); + + PyModule_AddIntConstant(m, "TIPC_LOW_IMPORTANCE", + TIPC_LOW_IMPORTANCE); + PyModule_AddIntConstant(m, "TIPC_MEDIUM_IMPORTANCE", + TIPC_MEDIUM_IMPORTANCE); + PyModule_AddIntConstant(m, "TIPC_HIGH_IMPORTANCE", + TIPC_HIGH_IMPORTANCE); + PyModule_AddIntConstant(m, "TIPC_CRITICAL_IMPORTANCE", + TIPC_CRITICAL_IMPORTANCE); + + /* for subscriptions */ + PyModule_AddIntConstant(m, "TIPC_SUB_PORTS", TIPC_SUB_PORTS); + PyModule_AddIntConstant(m, "TIPC_SUB_SERVICE", TIPC_SUB_SERVICE); #ifdef TIPC_SUB_CANCEL - /* doesn't seem to be available everywhere */ - PyModule_AddIntConstant(m, "TIPC_SUB_CANCEL", TIPC_SUB_CANCEL); + /* doesn't seem to be available everywhere */ + PyModule_AddIntConstant(m, "TIPC_SUB_CANCEL", TIPC_SUB_CANCEL); #endif - PyModule_AddIntConstant(m, "TIPC_WAIT_FOREVER", TIPC_WAIT_FOREVER); - PyModule_AddIntConstant(m, "TIPC_PUBLISHED", TIPC_PUBLISHED); - PyModule_AddIntConstant(m, "TIPC_WITHDRAWN", TIPC_WITHDRAWN); - PyModule_AddIntConstant(m, "TIPC_SUBSCR_TIMEOUT", TIPC_SUBSCR_TIMEOUT); - PyModule_AddIntConstant(m, "TIPC_CFG_SRV", TIPC_CFG_SRV); - PyModule_AddIntConstant(m, "TIPC_TOP_SRV", TIPC_TOP_SRV); + PyModule_AddIntConstant(m, "TIPC_WAIT_FOREVER", TIPC_WAIT_FOREVER); + PyModule_AddIntConstant(m, "TIPC_PUBLISHED", TIPC_PUBLISHED); + PyModule_AddIntConstant(m, "TIPC_WITHDRAWN", TIPC_WITHDRAWN); + PyModule_AddIntConstant(m, "TIPC_SUBSCR_TIMEOUT", TIPC_SUBSCR_TIMEOUT); + PyModule_AddIntConstant(m, "TIPC_CFG_SRV", TIPC_CFG_SRV); + PyModule_AddIntConstant(m, "TIPC_TOP_SRV", TIPC_TOP_SRV); #endif - /* Socket types */ - PyModule_AddIntConstant(m, "SOCK_STREAM", SOCK_STREAM); - PyModule_AddIntConstant(m, "SOCK_DGRAM", SOCK_DGRAM); + /* Socket types */ + PyModule_AddIntConstant(m, "SOCK_STREAM", SOCK_STREAM); + PyModule_AddIntConstant(m, "SOCK_DGRAM", SOCK_DGRAM); /* We have incomplete socket support. */ - PyModule_AddIntConstant(m, "SOCK_RAW", SOCK_RAW); - PyModule_AddIntConstant(m, "SOCK_SEQPACKET", SOCK_SEQPACKET); + PyModule_AddIntConstant(m, "SOCK_RAW", SOCK_RAW); + PyModule_AddIntConstant(m, "SOCK_SEQPACKET", SOCK_SEQPACKET); #if defined(SOCK_RDM) - PyModule_AddIntConstant(m, "SOCK_RDM", SOCK_RDM); + PyModule_AddIntConstant(m, "SOCK_RDM", SOCK_RDM); #endif -#ifdef SO_DEBUG - PyModule_AddIntConstant(m, "SO_DEBUG", SO_DEBUG); +#ifdef SO_DEBUG + PyModule_AddIntConstant(m, "SO_DEBUG", SO_DEBUG); #endif -#ifdef SO_ACCEPTCONN - PyModule_AddIntConstant(m, "SO_ACCEPTCONN", SO_ACCEPTCONN); +#ifdef SO_ACCEPTCONN + PyModule_AddIntConstant(m, "SO_ACCEPTCONN", SO_ACCEPTCONN); #endif -#ifdef SO_REUSEADDR - PyModule_AddIntConstant(m, "SO_REUSEADDR", SO_REUSEADDR); +#ifdef SO_REUSEADDR + PyModule_AddIntConstant(m, "SO_REUSEADDR", SO_REUSEADDR); #endif #ifdef SO_EXCLUSIVEADDRUSE - PyModule_AddIntConstant(m, "SO_EXCLUSIVEADDRUSE", SO_EXCLUSIVEADDRUSE); + PyModule_AddIntConstant(m, "SO_EXCLUSIVEADDRUSE", SO_EXCLUSIVEADDRUSE); #endif -#ifdef SO_KEEPALIVE - PyModule_AddIntConstant(m, "SO_KEEPALIVE", SO_KEEPALIVE); +#ifdef SO_KEEPALIVE + PyModule_AddIntConstant(m, "SO_KEEPALIVE", SO_KEEPALIVE); #endif -#ifdef SO_DONTROUTE - PyModule_AddIntConstant(m, "SO_DONTROUTE", SO_DONTROUTE); +#ifdef SO_DONTROUTE + PyModule_AddIntConstant(m, "SO_DONTROUTE", SO_DONTROUTE); #endif -#ifdef SO_BROADCAST - PyModule_AddIntConstant(m, "SO_BROADCAST", SO_BROADCAST); +#ifdef SO_BROADCAST + PyModule_AddIntConstant(m, "SO_BROADCAST", SO_BROADCAST); #endif -#ifdef SO_USELOOPBACK - PyModule_AddIntConstant(m, "SO_USELOOPBACK", SO_USELOOPBACK); +#ifdef SO_USELOOPBACK + PyModule_AddIntConstant(m, "SO_USELOOPBACK", SO_USELOOPBACK); #endif -#ifdef SO_LINGER - PyModule_AddIntConstant(m, "SO_LINGER", SO_LINGER); +#ifdef SO_LINGER + PyModule_AddIntConstant(m, "SO_LINGER", SO_LINGER); #endif -#ifdef SO_OOBINLINE - PyModule_AddIntConstant(m, "SO_OOBINLINE", SO_OOBINLINE); +#ifdef SO_OOBINLINE + PyModule_AddIntConstant(m, "SO_OOBINLINE", SO_OOBINLINE); #endif -#ifdef SO_REUSEPORT - PyModule_AddIntConstant(m, "SO_REUSEPORT", SO_REUSEPORT); +#ifdef SO_REUSEPORT + PyModule_AddIntConstant(m, "SO_REUSEPORT", SO_REUSEPORT); #endif -#ifdef SO_SNDBUF - PyModule_AddIntConstant(m, "SO_SNDBUF", SO_SNDBUF); +#ifdef SO_SNDBUF + PyModule_AddIntConstant(m, "SO_SNDBUF", SO_SNDBUF); #endif -#ifdef SO_RCVBUF - PyModule_AddIntConstant(m, "SO_RCVBUF", SO_RCVBUF); +#ifdef SO_RCVBUF + PyModule_AddIntConstant(m, "SO_RCVBUF", SO_RCVBUF); #endif -#ifdef SO_SNDLOWAT - PyModule_AddIntConstant(m, "SO_SNDLOWAT", SO_SNDLOWAT); +#ifdef SO_SNDLOWAT + PyModule_AddIntConstant(m, "SO_SNDLOWAT", SO_SNDLOWAT); #endif -#ifdef SO_RCVLOWAT - PyModule_AddIntConstant(m, "SO_RCVLOWAT", SO_RCVLOWAT); +#ifdef SO_RCVLOWAT + PyModule_AddIntConstant(m, "SO_RCVLOWAT", SO_RCVLOWAT); #endif -#ifdef SO_SNDTIMEO - PyModule_AddIntConstant(m, "SO_SNDTIMEO", SO_SNDTIMEO); +#ifdef SO_SNDTIMEO + PyModule_AddIntConstant(m, "SO_SNDTIMEO", SO_SNDTIMEO); #endif -#ifdef SO_RCVTIMEO - PyModule_AddIntConstant(m, "SO_RCVTIMEO", SO_RCVTIMEO); +#ifdef SO_RCVTIMEO + PyModule_AddIntConstant(m, "SO_RCVTIMEO", SO_RCVTIMEO); #endif -#ifdef SO_ERROR - PyModule_AddIntConstant(m, "SO_ERROR", SO_ERROR); +#ifdef SO_ERROR + PyModule_AddIntConstant(m, "SO_ERROR", SO_ERROR); #endif -#ifdef SO_TYPE - PyModule_AddIntConstant(m, "SO_TYPE", SO_TYPE); +#ifdef SO_TYPE + PyModule_AddIntConstant(m, "SO_TYPE", SO_TYPE); #endif -#ifdef SO_SETFIB - PyModule_AddIntConstant(m, "SO_SETFIB", SO_SETFIB); +#ifdef SO_SETFIB + PyModule_AddIntConstant(m, "SO_SETFIB", SO_SETFIB); #endif - /* Maximum number of connections for "listen" */ -#ifdef SOMAXCONN - PyModule_AddIntConstant(m, "SOMAXCONN", SOMAXCONN); + /* Maximum number of connections for "listen" */ +#ifdef SOMAXCONN + PyModule_AddIntConstant(m, "SOMAXCONN", SOMAXCONN); #else - PyModule_AddIntConstant(m, "SOMAXCONN", 5); /* Common value */ + PyModule_AddIntConstant(m, "SOMAXCONN", 5); /* Common value */ #endif - /* Flags for send, recv */ -#ifdef MSG_OOB - PyModule_AddIntConstant(m, "MSG_OOB", MSG_OOB); + /* Flags for send, recv */ +#ifdef MSG_OOB + PyModule_AddIntConstant(m, "MSG_OOB", MSG_OOB); #endif -#ifdef MSG_PEEK - PyModule_AddIntConstant(m, "MSG_PEEK", MSG_PEEK); +#ifdef MSG_PEEK + PyModule_AddIntConstant(m, "MSG_PEEK", MSG_PEEK); #endif -#ifdef MSG_DONTROUTE - PyModule_AddIntConstant(m, "MSG_DONTROUTE", MSG_DONTROUTE); +#ifdef MSG_DONTROUTE + PyModule_AddIntConstant(m, "MSG_DONTROUTE", MSG_DONTROUTE); #endif -#ifdef MSG_DONTWAIT - PyModule_AddIntConstant(m, "MSG_DONTWAIT", MSG_DONTWAIT); +#ifdef MSG_DONTWAIT + PyModule_AddIntConstant(m, "MSG_DONTWAIT", MSG_DONTWAIT); #endif -#ifdef MSG_EOR - PyModule_AddIntConstant(m, "MSG_EOR", MSG_EOR); +#ifdef MSG_EOR + PyModule_AddIntConstant(m, "MSG_EOR", MSG_EOR); #endif -#ifdef MSG_TRUNC - PyModule_AddIntConstant(m, "MSG_TRUNC", MSG_TRUNC); +#ifdef MSG_TRUNC + PyModule_AddIntConstant(m, "MSG_TRUNC", MSG_TRUNC); #endif -#ifdef MSG_CTRUNC - PyModule_AddIntConstant(m, "MSG_CTRUNC", MSG_CTRUNC); +#ifdef MSG_CTRUNC + PyModule_AddIntConstant(m, "MSG_CTRUNC", MSG_CTRUNC); #endif -#ifdef MSG_WAITALL - PyModule_AddIntConstant(m, "MSG_WAITALL", MSG_WAITALL); +#ifdef MSG_WAITALL + PyModule_AddIntConstant(m, "MSG_WAITALL", MSG_WAITALL); #endif -#ifdef MSG_BTAG - PyModule_AddIntConstant(m, "MSG_BTAG", MSG_BTAG); +#ifdef MSG_BTAG + PyModule_AddIntConstant(m, "MSG_BTAG", MSG_BTAG); #endif -#ifdef MSG_ETAG - PyModule_AddIntConstant(m, "MSG_ETAG", MSG_ETAG); +#ifdef MSG_ETAG + PyModule_AddIntConstant(m, "MSG_ETAG", MSG_ETAG); #endif - /* Protocol level and numbers, usable for [gs]etsockopt */ -#ifdef SOL_SOCKET - PyModule_AddIntConstant(m, "SOL_SOCKET", SOL_SOCKET); + /* Protocol level and numbers, usable for [gs]etsockopt */ +#ifdef SOL_SOCKET + PyModule_AddIntConstant(m, "SOL_SOCKET", SOL_SOCKET); #endif -#ifdef SOL_IP - PyModule_AddIntConstant(m, "SOL_IP", SOL_IP); +#ifdef SOL_IP + PyModule_AddIntConstant(m, "SOL_IP", SOL_IP); #else - PyModule_AddIntConstant(m, "SOL_IP", 0); + PyModule_AddIntConstant(m, "SOL_IP", 0); #endif -#ifdef SOL_IPX - PyModule_AddIntConstant(m, "SOL_IPX", SOL_IPX); +#ifdef SOL_IPX + PyModule_AddIntConstant(m, "SOL_IPX", SOL_IPX); #endif -#ifdef SOL_AX25 - PyModule_AddIntConstant(m, "SOL_AX25", SOL_AX25); +#ifdef SOL_AX25 + PyModule_AddIntConstant(m, "SOL_AX25", SOL_AX25); #endif -#ifdef SOL_ATALK - PyModule_AddIntConstant(m, "SOL_ATALK", SOL_ATALK); +#ifdef SOL_ATALK + PyModule_AddIntConstant(m, "SOL_ATALK", SOL_ATALK); #endif -#ifdef SOL_NETROM - PyModule_AddIntConstant(m, "SOL_NETROM", SOL_NETROM); +#ifdef SOL_NETROM + PyModule_AddIntConstant(m, "SOL_NETROM", SOL_NETROM); #endif -#ifdef SOL_ROSE - PyModule_AddIntConstant(m, "SOL_ROSE", SOL_ROSE); +#ifdef SOL_ROSE + PyModule_AddIntConstant(m, "SOL_ROSE", SOL_ROSE); #endif -#ifdef SOL_TCP - PyModule_AddIntConstant(m, "SOL_TCP", SOL_TCP); +#ifdef SOL_TCP + PyModule_AddIntConstant(m, "SOL_TCP", SOL_TCP); #else - PyModule_AddIntConstant(m, "SOL_TCP", 6); + PyModule_AddIntConstant(m, "SOL_TCP", 6); #endif -#ifdef SOL_UDP - PyModule_AddIntConstant(m, "SOL_UDP", SOL_UDP); +#ifdef SOL_UDP + PyModule_AddIntConstant(m, "SOL_UDP", SOL_UDP); #else - PyModule_AddIntConstant(m, "SOL_UDP", 17); + PyModule_AddIntConstant(m, "SOL_UDP", 17); #endif -#ifdef IPPROTO_IP - PyModule_AddIntConstant(m, "IPPROTO_IP", IPPROTO_IP); +#ifdef IPPROTO_IP + PyModule_AddIntConstant(m, "IPPROTO_IP", IPPROTO_IP); #else - PyModule_AddIntConstant(m, "IPPROTO_IP", 0); + PyModule_AddIntConstant(m, "IPPROTO_IP", 0); #endif -#ifdef IPPROTO_HOPOPTS - PyModule_AddIntConstant(m, "IPPROTO_HOPOPTS", IPPROTO_HOPOPTS); +#ifdef IPPROTO_HOPOPTS + PyModule_AddIntConstant(m, "IPPROTO_HOPOPTS", IPPROTO_HOPOPTS); #endif -#ifdef IPPROTO_ICMP - PyModule_AddIntConstant(m, "IPPROTO_ICMP", IPPROTO_ICMP); +#ifdef IPPROTO_ICMP + PyModule_AddIntConstant(m, "IPPROTO_ICMP", IPPROTO_ICMP); #else - PyModule_AddIntConstant(m, "IPPROTO_ICMP", 1); + PyModule_AddIntConstant(m, "IPPROTO_ICMP", 1); #endif -#ifdef IPPROTO_IGMP - PyModule_AddIntConstant(m, "IPPROTO_IGMP", IPPROTO_IGMP); +#ifdef IPPROTO_IGMP + PyModule_AddIntConstant(m, "IPPROTO_IGMP", IPPROTO_IGMP); #endif -#ifdef IPPROTO_GGP - PyModule_AddIntConstant(m, "IPPROTO_GGP", IPPROTO_GGP); +#ifdef IPPROTO_GGP + PyModule_AddIntConstant(m, "IPPROTO_GGP", IPPROTO_GGP); #endif -#ifdef IPPROTO_IPV4 - PyModule_AddIntConstant(m, "IPPROTO_IPV4", IPPROTO_IPV4); +#ifdef IPPROTO_IPV4 + PyModule_AddIntConstant(m, "IPPROTO_IPV4", IPPROTO_IPV4); #endif -#ifdef IPPROTO_IPV6 - PyModule_AddIntConstant(m, "IPPROTO_IPV6", IPPROTO_IPV6); +#ifdef IPPROTO_IPV6 + PyModule_AddIntConstant(m, "IPPROTO_IPV6", IPPROTO_IPV6); #endif -#ifdef IPPROTO_IPIP - PyModule_AddIntConstant(m, "IPPROTO_IPIP", IPPROTO_IPIP); +#ifdef IPPROTO_IPIP + PyModule_AddIntConstant(m, "IPPROTO_IPIP", IPPROTO_IPIP); #endif -#ifdef IPPROTO_TCP - PyModule_AddIntConstant(m, "IPPROTO_TCP", IPPROTO_TCP); +#ifdef IPPROTO_TCP + PyModule_AddIntConstant(m, "IPPROTO_TCP", IPPROTO_TCP); #else - PyModule_AddIntConstant(m, "IPPROTO_TCP", 6); + PyModule_AddIntConstant(m, "IPPROTO_TCP", 6); #endif -#ifdef IPPROTO_EGP - PyModule_AddIntConstant(m, "IPPROTO_EGP", IPPROTO_EGP); +#ifdef IPPROTO_EGP + PyModule_AddIntConstant(m, "IPPROTO_EGP", IPPROTO_EGP); #endif -#ifdef IPPROTO_PUP - PyModule_AddIntConstant(m, "IPPROTO_PUP", IPPROTO_PUP); +#ifdef IPPROTO_PUP + PyModule_AddIntConstant(m, "IPPROTO_PUP", IPPROTO_PUP); #endif -#ifdef IPPROTO_UDP - PyModule_AddIntConstant(m, "IPPROTO_UDP", IPPROTO_UDP); +#ifdef IPPROTO_UDP + PyModule_AddIntConstant(m, "IPPROTO_UDP", IPPROTO_UDP); #else - PyModule_AddIntConstant(m, "IPPROTO_UDP", 17); + PyModule_AddIntConstant(m, "IPPROTO_UDP", 17); #endif -#ifdef IPPROTO_IDP - PyModule_AddIntConstant(m, "IPPROTO_IDP", IPPROTO_IDP); +#ifdef IPPROTO_IDP + PyModule_AddIntConstant(m, "IPPROTO_IDP", IPPROTO_IDP); #endif -#ifdef IPPROTO_HELLO - PyModule_AddIntConstant(m, "IPPROTO_HELLO", IPPROTO_HELLO); +#ifdef IPPROTO_HELLO + PyModule_AddIntConstant(m, "IPPROTO_HELLO", IPPROTO_HELLO); #endif -#ifdef IPPROTO_ND - PyModule_AddIntConstant(m, "IPPROTO_ND", IPPROTO_ND); +#ifdef IPPROTO_ND + PyModule_AddIntConstant(m, "IPPROTO_ND", IPPROTO_ND); #endif -#ifdef IPPROTO_TP - PyModule_AddIntConstant(m, "IPPROTO_TP", IPPROTO_TP); +#ifdef IPPROTO_TP + PyModule_AddIntConstant(m, "IPPROTO_TP", IPPROTO_TP); #endif -#ifdef IPPROTO_IPV6 - PyModule_AddIntConstant(m, "IPPROTO_IPV6", IPPROTO_IPV6); +#ifdef IPPROTO_IPV6 + PyModule_AddIntConstant(m, "IPPROTO_IPV6", IPPROTO_IPV6); #endif -#ifdef IPPROTO_ROUTING - PyModule_AddIntConstant(m, "IPPROTO_ROUTING", IPPROTO_ROUTING); +#ifdef IPPROTO_ROUTING + PyModule_AddIntConstant(m, "IPPROTO_ROUTING", IPPROTO_ROUTING); #endif -#ifdef IPPROTO_FRAGMENT - PyModule_AddIntConstant(m, "IPPROTO_FRAGMENT", IPPROTO_FRAGMENT); +#ifdef IPPROTO_FRAGMENT + PyModule_AddIntConstant(m, "IPPROTO_FRAGMENT", IPPROTO_FRAGMENT); #endif -#ifdef IPPROTO_RSVP - PyModule_AddIntConstant(m, "IPPROTO_RSVP", IPPROTO_RSVP); +#ifdef IPPROTO_RSVP + PyModule_AddIntConstant(m, "IPPROTO_RSVP", IPPROTO_RSVP); #endif -#ifdef IPPROTO_GRE - PyModule_AddIntConstant(m, "IPPROTO_GRE", IPPROTO_GRE); +#ifdef IPPROTO_GRE + PyModule_AddIntConstant(m, "IPPROTO_GRE", IPPROTO_GRE); #endif -#ifdef IPPROTO_ESP - PyModule_AddIntConstant(m, "IPPROTO_ESP", IPPROTO_ESP); +#ifdef IPPROTO_ESP + PyModule_AddIntConstant(m, "IPPROTO_ESP", IPPROTO_ESP); #endif -#ifdef IPPROTO_AH - PyModule_AddIntConstant(m, "IPPROTO_AH", IPPROTO_AH); +#ifdef IPPROTO_AH + PyModule_AddIntConstant(m, "IPPROTO_AH", IPPROTO_AH); #endif -#ifdef IPPROTO_MOBILE - PyModule_AddIntConstant(m, "IPPROTO_MOBILE", IPPROTO_MOBILE); +#ifdef IPPROTO_MOBILE + PyModule_AddIntConstant(m, "IPPROTO_MOBILE", IPPROTO_MOBILE); #endif -#ifdef IPPROTO_ICMPV6 - PyModule_AddIntConstant(m, "IPPROTO_ICMPV6", IPPROTO_ICMPV6); +#ifdef IPPROTO_ICMPV6 + PyModule_AddIntConstant(m, "IPPROTO_ICMPV6", IPPROTO_ICMPV6); #endif -#ifdef IPPROTO_NONE - PyModule_AddIntConstant(m, "IPPROTO_NONE", IPPROTO_NONE); +#ifdef IPPROTO_NONE + PyModule_AddIntConstant(m, "IPPROTO_NONE", IPPROTO_NONE); #endif -#ifdef IPPROTO_DSTOPTS - PyModule_AddIntConstant(m, "IPPROTO_DSTOPTS", IPPROTO_DSTOPTS); +#ifdef IPPROTO_DSTOPTS + PyModule_AddIntConstant(m, "IPPROTO_DSTOPTS", IPPROTO_DSTOPTS); #endif -#ifdef IPPROTO_XTP - PyModule_AddIntConstant(m, "IPPROTO_XTP", IPPROTO_XTP); +#ifdef IPPROTO_XTP + PyModule_AddIntConstant(m, "IPPROTO_XTP", IPPROTO_XTP); #endif -#ifdef IPPROTO_EON - PyModule_AddIntConstant(m, "IPPROTO_EON", IPPROTO_EON); +#ifdef IPPROTO_EON + PyModule_AddIntConstant(m, "IPPROTO_EON", IPPROTO_EON); #endif -#ifdef IPPROTO_PIM - PyModule_AddIntConstant(m, "IPPROTO_PIM", IPPROTO_PIM); +#ifdef IPPROTO_PIM + PyModule_AddIntConstant(m, "IPPROTO_PIM", IPPROTO_PIM); #endif -#ifdef IPPROTO_IPCOMP - PyModule_AddIntConstant(m, "IPPROTO_IPCOMP", IPPROTO_IPCOMP); +#ifdef IPPROTO_IPCOMP + PyModule_AddIntConstant(m, "IPPROTO_IPCOMP", IPPROTO_IPCOMP); #endif -#ifdef IPPROTO_VRRP - PyModule_AddIntConstant(m, "IPPROTO_VRRP", IPPROTO_VRRP); +#ifdef IPPROTO_VRRP + PyModule_AddIntConstant(m, "IPPROTO_VRRP", IPPROTO_VRRP); #endif -#ifdef IPPROTO_BIP - PyModule_AddIntConstant(m, "IPPROTO_BIP", IPPROTO_BIP); +#ifdef IPPROTO_BIP + PyModule_AddIntConstant(m, "IPPROTO_BIP", IPPROTO_BIP); #endif /**/ -#ifdef IPPROTO_RAW - PyModule_AddIntConstant(m, "IPPROTO_RAW", IPPROTO_RAW); +#ifdef IPPROTO_RAW + PyModule_AddIntConstant(m, "IPPROTO_RAW", IPPROTO_RAW); #else - PyModule_AddIntConstant(m, "IPPROTO_RAW", 255); + PyModule_AddIntConstant(m, "IPPROTO_RAW", 255); #endif -#ifdef IPPROTO_MAX - PyModule_AddIntConstant(m, "IPPROTO_MAX", IPPROTO_MAX); +#ifdef IPPROTO_MAX + PyModule_AddIntConstant(m, "IPPROTO_MAX", IPPROTO_MAX); #endif - /* Some port configuration */ -#ifdef IPPORT_RESERVED - PyModule_AddIntConstant(m, "IPPORT_RESERVED", IPPORT_RESERVED); + /* Some port configuration */ +#ifdef IPPORT_RESERVED + PyModule_AddIntConstant(m, "IPPORT_RESERVED", IPPORT_RESERVED); #else - PyModule_AddIntConstant(m, "IPPORT_RESERVED", 1024); + PyModule_AddIntConstant(m, "IPPORT_RESERVED", 1024); #endif -#ifdef IPPORT_USERRESERVED - PyModule_AddIntConstant(m, "IPPORT_USERRESERVED", IPPORT_USERRESERVED); +#ifdef IPPORT_USERRESERVED + PyModule_AddIntConstant(m, "IPPORT_USERRESERVED", IPPORT_USERRESERVED); #else - PyModule_AddIntConstant(m, "IPPORT_USERRESERVED", 5000); + PyModule_AddIntConstant(m, "IPPORT_USERRESERVED", 5000); #endif - /* Some reserved IP v.4 addresses */ -#ifdef INADDR_ANY - PyModule_AddIntConstant(m, "INADDR_ANY", INADDR_ANY); + /* Some reserved IP v.4 addresses */ +#ifdef INADDR_ANY + PyModule_AddIntConstant(m, "INADDR_ANY", INADDR_ANY); #else - PyModule_AddIntConstant(m, "INADDR_ANY", 0x00000000); + PyModule_AddIntConstant(m, "INADDR_ANY", 0x00000000); #endif -#ifdef INADDR_BROADCAST - PyModule_AddIntConstant(m, "INADDR_BROADCAST", INADDR_BROADCAST); +#ifdef INADDR_BROADCAST + PyModule_AddIntConstant(m, "INADDR_BROADCAST", INADDR_BROADCAST); #else - PyModule_AddIntConstant(m, "INADDR_BROADCAST", 0xffffffff); + PyModule_AddIntConstant(m, "INADDR_BROADCAST", 0xffffffff); #endif -#ifdef INADDR_LOOPBACK - PyModule_AddIntConstant(m, "INADDR_LOOPBACK", INADDR_LOOPBACK); +#ifdef INADDR_LOOPBACK + PyModule_AddIntConstant(m, "INADDR_LOOPBACK", INADDR_LOOPBACK); #else - PyModule_AddIntConstant(m, "INADDR_LOOPBACK", 0x7F000001); + PyModule_AddIntConstant(m, "INADDR_LOOPBACK", 0x7F000001); #endif -#ifdef INADDR_UNSPEC_GROUP - PyModule_AddIntConstant(m, "INADDR_UNSPEC_GROUP", INADDR_UNSPEC_GROUP); +#ifdef INADDR_UNSPEC_GROUP + PyModule_AddIntConstant(m, "INADDR_UNSPEC_GROUP", INADDR_UNSPEC_GROUP); #else - PyModule_AddIntConstant(m, "INADDR_UNSPEC_GROUP", 0xe0000000); + PyModule_AddIntConstant(m, "INADDR_UNSPEC_GROUP", 0xe0000000); #endif -#ifdef INADDR_ALLHOSTS_GROUP - PyModule_AddIntConstant(m, "INADDR_ALLHOSTS_GROUP", - INADDR_ALLHOSTS_GROUP); +#ifdef INADDR_ALLHOSTS_GROUP + PyModule_AddIntConstant(m, "INADDR_ALLHOSTS_GROUP", + INADDR_ALLHOSTS_GROUP); #else - PyModule_AddIntConstant(m, "INADDR_ALLHOSTS_GROUP", 0xe0000001); + PyModule_AddIntConstant(m, "INADDR_ALLHOSTS_GROUP", 0xe0000001); #endif -#ifdef INADDR_MAX_LOCAL_GROUP - PyModule_AddIntConstant(m, "INADDR_MAX_LOCAL_GROUP", - INADDR_MAX_LOCAL_GROUP); +#ifdef INADDR_MAX_LOCAL_GROUP + PyModule_AddIntConstant(m, "INADDR_MAX_LOCAL_GROUP", + INADDR_MAX_LOCAL_GROUP); #else - PyModule_AddIntConstant(m, "INADDR_MAX_LOCAL_GROUP", 0xe00000ff); + PyModule_AddIntConstant(m, "INADDR_MAX_LOCAL_GROUP", 0xe00000ff); #endif -#ifdef INADDR_NONE - PyModule_AddIntConstant(m, "INADDR_NONE", INADDR_NONE); +#ifdef INADDR_NONE + PyModule_AddIntConstant(m, "INADDR_NONE", INADDR_NONE); #else - PyModule_AddIntConstant(m, "INADDR_NONE", 0xffffffff); + PyModule_AddIntConstant(m, "INADDR_NONE", 0xffffffff); #endif - /* IPv4 [gs]etsockopt options */ -#ifdef IP_OPTIONS - PyModule_AddIntConstant(m, "IP_OPTIONS", IP_OPTIONS); + /* IPv4 [gs]etsockopt options */ +#ifdef IP_OPTIONS + PyModule_AddIntConstant(m, "IP_OPTIONS", IP_OPTIONS); #endif -#ifdef IP_HDRINCL - PyModule_AddIntConstant(m, "IP_HDRINCL", IP_HDRINCL); +#ifdef IP_HDRINCL + PyModule_AddIntConstant(m, "IP_HDRINCL", IP_HDRINCL); #endif -#ifdef IP_TOS - PyModule_AddIntConstant(m, "IP_TOS", IP_TOS); +#ifdef IP_TOS + PyModule_AddIntConstant(m, "IP_TOS", IP_TOS); #endif -#ifdef IP_TTL - PyModule_AddIntConstant(m, "IP_TTL", IP_TTL); +#ifdef IP_TTL + PyModule_AddIntConstant(m, "IP_TTL", IP_TTL); #endif -#ifdef IP_RECVOPTS - PyModule_AddIntConstant(m, "IP_RECVOPTS", IP_RECVOPTS); +#ifdef IP_RECVOPTS + PyModule_AddIntConstant(m, "IP_RECVOPTS", IP_RECVOPTS); #endif -#ifdef IP_RECVRETOPTS - PyModule_AddIntConstant(m, "IP_RECVRETOPTS", IP_RECVRETOPTS); +#ifdef IP_RECVRETOPTS + PyModule_AddIntConstant(m, "IP_RECVRETOPTS", IP_RECVRETOPTS); #endif -#ifdef IP_RECVDSTADDR - PyModule_AddIntConstant(m, "IP_RECVDSTADDR", IP_RECVDSTADDR); +#ifdef IP_RECVDSTADDR + PyModule_AddIntConstant(m, "IP_RECVDSTADDR", IP_RECVDSTADDR); #endif -#ifdef IP_RETOPTS - PyModule_AddIntConstant(m, "IP_RETOPTS", IP_RETOPTS); +#ifdef IP_RETOPTS + PyModule_AddIntConstant(m, "IP_RETOPTS", IP_RETOPTS); #endif -#ifdef IP_MULTICAST_IF - PyModule_AddIntConstant(m, "IP_MULTICAST_IF", IP_MULTICAST_IF); +#ifdef IP_MULTICAST_IF + PyModule_AddIntConstant(m, "IP_MULTICAST_IF", IP_MULTICAST_IF); #endif -#ifdef IP_MULTICAST_TTL - PyModule_AddIntConstant(m, "IP_MULTICAST_TTL", IP_MULTICAST_TTL); +#ifdef IP_MULTICAST_TTL + PyModule_AddIntConstant(m, "IP_MULTICAST_TTL", IP_MULTICAST_TTL); #endif -#ifdef IP_MULTICAST_LOOP - PyModule_AddIntConstant(m, "IP_MULTICAST_LOOP", IP_MULTICAST_LOOP); +#ifdef IP_MULTICAST_LOOP + PyModule_AddIntConstant(m, "IP_MULTICAST_LOOP", IP_MULTICAST_LOOP); #endif -#ifdef IP_ADD_MEMBERSHIP - PyModule_AddIntConstant(m, "IP_ADD_MEMBERSHIP", IP_ADD_MEMBERSHIP); +#ifdef IP_ADD_MEMBERSHIP + PyModule_AddIntConstant(m, "IP_ADD_MEMBERSHIP", IP_ADD_MEMBERSHIP); #endif -#ifdef IP_DROP_MEMBERSHIP - PyModule_AddIntConstant(m, "IP_DROP_MEMBERSHIP", IP_DROP_MEMBERSHIP); +#ifdef IP_DROP_MEMBERSHIP + PyModule_AddIntConstant(m, "IP_DROP_MEMBERSHIP", IP_DROP_MEMBERSHIP); #endif -#ifdef IP_DEFAULT_MULTICAST_TTL - PyModule_AddIntConstant(m, "IP_DEFAULT_MULTICAST_TTL", - IP_DEFAULT_MULTICAST_TTL); +#ifdef IP_DEFAULT_MULTICAST_TTL + PyModule_AddIntConstant(m, "IP_DEFAULT_MULTICAST_TTL", + IP_DEFAULT_MULTICAST_TTL); #endif -#ifdef IP_DEFAULT_MULTICAST_LOOP - PyModule_AddIntConstant(m, "IP_DEFAULT_MULTICAST_LOOP", - IP_DEFAULT_MULTICAST_LOOP); +#ifdef IP_DEFAULT_MULTICAST_LOOP + PyModule_AddIntConstant(m, "IP_DEFAULT_MULTICAST_LOOP", + IP_DEFAULT_MULTICAST_LOOP); #endif -#ifdef IP_MAX_MEMBERSHIPS - PyModule_AddIntConstant(m, "IP_MAX_MEMBERSHIPS", IP_MAX_MEMBERSHIPS); +#ifdef IP_MAX_MEMBERSHIPS + PyModule_AddIntConstant(m, "IP_MAX_MEMBERSHIPS", IP_MAX_MEMBERSHIPS); #endif - /* IPv6 [gs]etsockopt options, defined in RFC2553 */ -#ifdef IPV6_JOIN_GROUP - PyModule_AddIntConstant(m, "IPV6_JOIN_GROUP", IPV6_JOIN_GROUP); + /* IPv6 [gs]etsockopt options, defined in RFC2553 */ +#ifdef IPV6_JOIN_GROUP + PyModule_AddIntConstant(m, "IPV6_JOIN_GROUP", IPV6_JOIN_GROUP); #endif -#ifdef IPV6_LEAVE_GROUP - PyModule_AddIntConstant(m, "IPV6_LEAVE_GROUP", IPV6_LEAVE_GROUP); +#ifdef IPV6_LEAVE_GROUP + PyModule_AddIntConstant(m, "IPV6_LEAVE_GROUP", IPV6_LEAVE_GROUP); #endif -#ifdef IPV6_MULTICAST_HOPS - PyModule_AddIntConstant(m, "IPV6_MULTICAST_HOPS", IPV6_MULTICAST_HOPS); +#ifdef IPV6_MULTICAST_HOPS + PyModule_AddIntConstant(m, "IPV6_MULTICAST_HOPS", IPV6_MULTICAST_HOPS); #endif -#ifdef IPV6_MULTICAST_IF - PyModule_AddIntConstant(m, "IPV6_MULTICAST_IF", IPV6_MULTICAST_IF); +#ifdef IPV6_MULTICAST_IF + PyModule_AddIntConstant(m, "IPV6_MULTICAST_IF", IPV6_MULTICAST_IF); #endif -#ifdef IPV6_MULTICAST_LOOP - PyModule_AddIntConstant(m, "IPV6_MULTICAST_LOOP", IPV6_MULTICAST_LOOP); +#ifdef IPV6_MULTICAST_LOOP + PyModule_AddIntConstant(m, "IPV6_MULTICAST_LOOP", IPV6_MULTICAST_LOOP); #endif -#ifdef IPV6_UNICAST_HOPS - PyModule_AddIntConstant(m, "IPV6_UNICAST_HOPS", IPV6_UNICAST_HOPS); +#ifdef IPV6_UNICAST_HOPS + PyModule_AddIntConstant(m, "IPV6_UNICAST_HOPS", IPV6_UNICAST_HOPS); #endif - /* Additional IPV6 socket options, defined in RFC 3493 */ + /* Additional IPV6 socket options, defined in RFC 3493 */ #ifdef IPV6_V6ONLY - PyModule_AddIntConstant(m, "IPV6_V6ONLY", IPV6_V6ONLY); + PyModule_AddIntConstant(m, "IPV6_V6ONLY", IPV6_V6ONLY); #endif - /* Advanced IPV6 socket options, from RFC 3542 */ + /* Advanced IPV6 socket options, from RFC 3542 */ #ifdef IPV6_CHECKSUM - PyModule_AddIntConstant(m, "IPV6_CHECKSUM", IPV6_CHECKSUM); + PyModule_AddIntConstant(m, "IPV6_CHECKSUM", IPV6_CHECKSUM); #endif #ifdef IPV6_DONTFRAG - PyModule_AddIntConstant(m, "IPV6_DONTFRAG", IPV6_DONTFRAG); + PyModule_AddIntConstant(m, "IPV6_DONTFRAG", IPV6_DONTFRAG); #endif #ifdef IPV6_DSTOPTS - PyModule_AddIntConstant(m, "IPV6_DSTOPTS", IPV6_DSTOPTS); + PyModule_AddIntConstant(m, "IPV6_DSTOPTS", IPV6_DSTOPTS); #endif #ifdef IPV6_HOPLIMIT - PyModule_AddIntConstant(m, "IPV6_HOPLIMIT", IPV6_HOPLIMIT); + PyModule_AddIntConstant(m, "IPV6_HOPLIMIT", IPV6_HOPLIMIT); #endif #ifdef IPV6_HOPOPTS - PyModule_AddIntConstant(m, "IPV6_HOPOPTS", IPV6_HOPOPTS); + PyModule_AddIntConstant(m, "IPV6_HOPOPTS", IPV6_HOPOPTS); #endif #ifdef IPV6_NEXTHOP - PyModule_AddIntConstant(m, "IPV6_NEXTHOP", IPV6_NEXTHOP); + PyModule_AddIntConstant(m, "IPV6_NEXTHOP", IPV6_NEXTHOP); #endif #ifdef IPV6_PATHMTU - PyModule_AddIntConstant(m, "IPV6_PATHMTU", IPV6_PATHMTU); + PyModule_AddIntConstant(m, "IPV6_PATHMTU", IPV6_PATHMTU); #endif #ifdef IPV6_PKTINFO - PyModule_AddIntConstant(m, "IPV6_PKTINFO", IPV6_PKTINFO); + PyModule_AddIntConstant(m, "IPV6_PKTINFO", IPV6_PKTINFO); #endif #ifdef IPV6_RECVDSTOPTS - PyModule_AddIntConstant(m, "IPV6_RECVDSTOPTS", IPV6_RECVDSTOPTS); + PyModule_AddIntConstant(m, "IPV6_RECVDSTOPTS", IPV6_RECVDSTOPTS); #endif #ifdef IPV6_RECVHOPLIMIT - PyModule_AddIntConstant(m, "IPV6_RECVHOPLIMIT", IPV6_RECVHOPLIMIT); + PyModule_AddIntConstant(m, "IPV6_RECVHOPLIMIT", IPV6_RECVHOPLIMIT); #endif #ifdef IPV6_RECVHOPOPTS - PyModule_AddIntConstant(m, "IPV6_RECVHOPOPTS", IPV6_RECVHOPOPTS); + PyModule_AddIntConstant(m, "IPV6_RECVHOPOPTS", IPV6_RECVHOPOPTS); #endif #ifdef IPV6_RECVPKTINFO - PyModule_AddIntConstant(m, "IPV6_RECVPKTINFO", IPV6_RECVPKTINFO); + PyModule_AddIntConstant(m, "IPV6_RECVPKTINFO", IPV6_RECVPKTINFO); #endif #ifdef IPV6_RECVRTHDR - PyModule_AddIntConstant(m, "IPV6_RECVRTHDR", IPV6_RECVRTHDR); + PyModule_AddIntConstant(m, "IPV6_RECVRTHDR", IPV6_RECVRTHDR); #endif #ifdef IPV6_RECVTCLASS - PyModule_AddIntConstant(m, "IPV6_RECVTCLASS", IPV6_RECVTCLASS); + PyModule_AddIntConstant(m, "IPV6_RECVTCLASS", IPV6_RECVTCLASS); #endif #ifdef IPV6_RTHDR - PyModule_AddIntConstant(m, "IPV6_RTHDR", IPV6_RTHDR); + PyModule_AddIntConstant(m, "IPV6_RTHDR", IPV6_RTHDR); #endif #ifdef IPV6_RTHDRDSTOPTS - PyModule_AddIntConstant(m, "IPV6_RTHDRDSTOPTS", IPV6_RTHDRDSTOPTS); + PyModule_AddIntConstant(m, "IPV6_RTHDRDSTOPTS", IPV6_RTHDRDSTOPTS); #endif #ifdef IPV6_RTHDR_TYPE_0 - PyModule_AddIntConstant(m, "IPV6_RTHDR_TYPE_0", IPV6_RTHDR_TYPE_0); + PyModule_AddIntConstant(m, "IPV6_RTHDR_TYPE_0", IPV6_RTHDR_TYPE_0); #endif #ifdef IPV6_RECVPATHMTU - PyModule_AddIntConstant(m, "IPV6_RECVPATHMTU", IPV6_RECVPATHMTU); + PyModule_AddIntConstant(m, "IPV6_RECVPATHMTU", IPV6_RECVPATHMTU); #endif #ifdef IPV6_TCLASS - PyModule_AddIntConstant(m, "IPV6_TCLASS", IPV6_TCLASS); + PyModule_AddIntConstant(m, "IPV6_TCLASS", IPV6_TCLASS); #endif #ifdef IPV6_USE_MIN_MTU - PyModule_AddIntConstant(m, "IPV6_USE_MIN_MTU", IPV6_USE_MIN_MTU); + PyModule_AddIntConstant(m, "IPV6_USE_MIN_MTU", IPV6_USE_MIN_MTU); #endif - /* TCP options */ -#ifdef TCP_NODELAY - PyModule_AddIntConstant(m, "TCP_NODELAY", TCP_NODELAY); + /* TCP options */ +#ifdef TCP_NODELAY + PyModule_AddIntConstant(m, "TCP_NODELAY", TCP_NODELAY); #endif -#ifdef TCP_MAXSEG - PyModule_AddIntConstant(m, "TCP_MAXSEG", TCP_MAXSEG); +#ifdef TCP_MAXSEG + PyModule_AddIntConstant(m, "TCP_MAXSEG", TCP_MAXSEG); #endif -#ifdef TCP_CORK - PyModule_AddIntConstant(m, "TCP_CORK", TCP_CORK); +#ifdef TCP_CORK + PyModule_AddIntConstant(m, "TCP_CORK", TCP_CORK); #endif -#ifdef TCP_KEEPIDLE - PyModule_AddIntConstant(m, "TCP_KEEPIDLE", TCP_KEEPIDLE); +#ifdef TCP_KEEPIDLE + PyModule_AddIntConstant(m, "TCP_KEEPIDLE", TCP_KEEPIDLE); #endif -#ifdef TCP_KEEPINTVL - PyModule_AddIntConstant(m, "TCP_KEEPINTVL", TCP_KEEPINTVL); +#ifdef TCP_KEEPINTVL + PyModule_AddIntConstant(m, "TCP_KEEPINTVL", TCP_KEEPINTVL); #endif -#ifdef TCP_KEEPCNT - PyModule_AddIntConstant(m, "TCP_KEEPCNT", TCP_KEEPCNT); +#ifdef TCP_KEEPCNT + PyModule_AddIntConstant(m, "TCP_KEEPCNT", TCP_KEEPCNT); #endif -#ifdef TCP_SYNCNT - PyModule_AddIntConstant(m, "TCP_SYNCNT", TCP_SYNCNT); +#ifdef TCP_SYNCNT + PyModule_AddIntConstant(m, "TCP_SYNCNT", TCP_SYNCNT); #endif -#ifdef TCP_LINGER2 - PyModule_AddIntConstant(m, "TCP_LINGER2", TCP_LINGER2); +#ifdef TCP_LINGER2 + PyModule_AddIntConstant(m, "TCP_LINGER2", TCP_LINGER2); #endif -#ifdef TCP_DEFER_ACCEPT - PyModule_AddIntConstant(m, "TCP_DEFER_ACCEPT", TCP_DEFER_ACCEPT); +#ifdef TCP_DEFER_ACCEPT + PyModule_AddIntConstant(m, "TCP_DEFER_ACCEPT", TCP_DEFER_ACCEPT); #endif -#ifdef TCP_WINDOW_CLAMP - PyModule_AddIntConstant(m, "TCP_WINDOW_CLAMP", TCP_WINDOW_CLAMP); +#ifdef TCP_WINDOW_CLAMP + PyModule_AddIntConstant(m, "TCP_WINDOW_CLAMP", TCP_WINDOW_CLAMP); #endif -#ifdef TCP_INFO - PyModule_AddIntConstant(m, "TCP_INFO", TCP_INFO); +#ifdef TCP_INFO + PyModule_AddIntConstant(m, "TCP_INFO", TCP_INFO); #endif -#ifdef TCP_QUICKACK - PyModule_AddIntConstant(m, "TCP_QUICKACK", TCP_QUICKACK); +#ifdef TCP_QUICKACK + PyModule_AddIntConstant(m, "TCP_QUICKACK", TCP_QUICKACK); #endif - /* IPX options */ -#ifdef IPX_TYPE - PyModule_AddIntConstant(m, "IPX_TYPE", IPX_TYPE); + /* IPX options */ +#ifdef IPX_TYPE + PyModule_AddIntConstant(m, "IPX_TYPE", IPX_TYPE); #endif - /* get{addr,name}info parameters */ + /* get{addr,name}info parameters */ #ifdef EAI_ADDRFAMILY - PyModule_AddIntConstant(m, "EAI_ADDRFAMILY", EAI_ADDRFAMILY); + PyModule_AddIntConstant(m, "EAI_ADDRFAMILY", EAI_ADDRFAMILY); #endif #ifdef EAI_AGAIN - PyModule_AddIntConstant(m, "EAI_AGAIN", EAI_AGAIN); + PyModule_AddIntConstant(m, "EAI_AGAIN", EAI_AGAIN); #endif #ifdef EAI_BADFLAGS - PyModule_AddIntConstant(m, "EAI_BADFLAGS", EAI_BADFLAGS); + PyModule_AddIntConstant(m, "EAI_BADFLAGS", EAI_BADFLAGS); #endif #ifdef EAI_FAIL - PyModule_AddIntConstant(m, "EAI_FAIL", EAI_FAIL); + PyModule_AddIntConstant(m, "EAI_FAIL", EAI_FAIL); #endif #ifdef EAI_FAMILY - PyModule_AddIntConstant(m, "EAI_FAMILY", EAI_FAMILY); + PyModule_AddIntConstant(m, "EAI_FAMILY", EAI_FAMILY); #endif #ifdef EAI_MEMORY - PyModule_AddIntConstant(m, "EAI_MEMORY", EAI_MEMORY); + PyModule_AddIntConstant(m, "EAI_MEMORY", EAI_MEMORY); #endif #ifdef EAI_NODATA - PyModule_AddIntConstant(m, "EAI_NODATA", EAI_NODATA); + PyModule_AddIntConstant(m, "EAI_NODATA", EAI_NODATA); #endif #ifdef EAI_NONAME - PyModule_AddIntConstant(m, "EAI_NONAME", EAI_NONAME); + PyModule_AddIntConstant(m, "EAI_NONAME", EAI_NONAME); #endif #ifdef EAI_OVERFLOW - PyModule_AddIntConstant(m, "EAI_OVERFLOW", EAI_OVERFLOW); + PyModule_AddIntConstant(m, "EAI_OVERFLOW", EAI_OVERFLOW); #endif #ifdef EAI_SERVICE - PyModule_AddIntConstant(m, "EAI_SERVICE", EAI_SERVICE); + PyModule_AddIntConstant(m, "EAI_SERVICE", EAI_SERVICE); #endif #ifdef EAI_SOCKTYPE - PyModule_AddIntConstant(m, "EAI_SOCKTYPE", EAI_SOCKTYPE); + PyModule_AddIntConstant(m, "EAI_SOCKTYPE", EAI_SOCKTYPE); #endif #ifdef EAI_SYSTEM - PyModule_AddIntConstant(m, "EAI_SYSTEM", EAI_SYSTEM); + PyModule_AddIntConstant(m, "EAI_SYSTEM", EAI_SYSTEM); #endif #ifdef EAI_BADHINTS - PyModule_AddIntConstant(m, "EAI_BADHINTS", EAI_BADHINTS); + PyModule_AddIntConstant(m, "EAI_BADHINTS", EAI_BADHINTS); #endif #ifdef EAI_PROTOCOL - PyModule_AddIntConstant(m, "EAI_PROTOCOL", EAI_PROTOCOL); + PyModule_AddIntConstant(m, "EAI_PROTOCOL", EAI_PROTOCOL); #endif #ifdef EAI_MAX - PyModule_AddIntConstant(m, "EAI_MAX", EAI_MAX); + PyModule_AddIntConstant(m, "EAI_MAX", EAI_MAX); #endif #ifdef AI_PASSIVE - PyModule_AddIntConstant(m, "AI_PASSIVE", AI_PASSIVE); + PyModule_AddIntConstant(m, "AI_PASSIVE", AI_PASSIVE); #endif #ifdef AI_CANONNAME - PyModule_AddIntConstant(m, "AI_CANONNAME", AI_CANONNAME); + PyModule_AddIntConstant(m, "AI_CANONNAME", AI_CANONNAME); #endif #ifdef AI_NUMERICHOST - PyModule_AddIntConstant(m, "AI_NUMERICHOST", AI_NUMERICHOST); + PyModule_AddIntConstant(m, "AI_NUMERICHOST", AI_NUMERICHOST); #endif #ifdef AI_NUMERICSERV - PyModule_AddIntConstant(m, "AI_NUMERICSERV", AI_NUMERICSERV); + PyModule_AddIntConstant(m, "AI_NUMERICSERV", AI_NUMERICSERV); #endif #ifdef AI_MASK - PyModule_AddIntConstant(m, "AI_MASK", AI_MASK); + PyModule_AddIntConstant(m, "AI_MASK", AI_MASK); #endif #ifdef AI_ALL - PyModule_AddIntConstant(m, "AI_ALL", AI_ALL); + PyModule_AddIntConstant(m, "AI_ALL", AI_ALL); #endif #ifdef AI_V4MAPPED_CFG - PyModule_AddIntConstant(m, "AI_V4MAPPED_CFG", AI_V4MAPPED_CFG); + PyModule_AddIntConstant(m, "AI_V4MAPPED_CFG", AI_V4MAPPED_CFG); #endif #ifdef AI_ADDRCONFIG - PyModule_AddIntConstant(m, "AI_ADDRCONFIG", AI_ADDRCONFIG); + PyModule_AddIntConstant(m, "AI_ADDRCONFIG", AI_ADDRCONFIG); #endif #ifdef AI_V4MAPPED - PyModule_AddIntConstant(m, "AI_V4MAPPED", AI_V4MAPPED); + PyModule_AddIntConstant(m, "AI_V4MAPPED", AI_V4MAPPED); #endif #ifdef AI_DEFAULT - PyModule_AddIntConstant(m, "AI_DEFAULT", AI_DEFAULT); + PyModule_AddIntConstant(m, "AI_DEFAULT", AI_DEFAULT); #endif #ifdef NI_MAXHOST - PyModule_AddIntConstant(m, "NI_MAXHOST", NI_MAXHOST); + PyModule_AddIntConstant(m, "NI_MAXHOST", NI_MAXHOST); #endif #ifdef NI_MAXSERV - PyModule_AddIntConstant(m, "NI_MAXSERV", NI_MAXSERV); + PyModule_AddIntConstant(m, "NI_MAXSERV", NI_MAXSERV); #endif #ifdef NI_NOFQDN - PyModule_AddIntConstant(m, "NI_NOFQDN", NI_NOFQDN); + PyModule_AddIntConstant(m, "NI_NOFQDN", NI_NOFQDN); #endif #ifdef NI_NUMERICHOST - PyModule_AddIntConstant(m, "NI_NUMERICHOST", NI_NUMERICHOST); + PyModule_AddIntConstant(m, "NI_NUMERICHOST", NI_NUMERICHOST); #endif #ifdef NI_NAMEREQD - PyModule_AddIntConstant(m, "NI_NAMEREQD", NI_NAMEREQD); + PyModule_AddIntConstant(m, "NI_NAMEREQD", NI_NAMEREQD); #endif #ifdef NI_NUMERICSERV - PyModule_AddIntConstant(m, "NI_NUMERICSERV", NI_NUMERICSERV); + PyModule_AddIntConstant(m, "NI_NUMERICSERV", NI_NUMERICSERV); #endif #ifdef NI_DGRAM - PyModule_AddIntConstant(m, "NI_DGRAM", NI_DGRAM); + PyModule_AddIntConstant(m, "NI_DGRAM", NI_DGRAM); #endif - /* shutdown() parameters */ + /* shutdown() parameters */ #ifdef SHUT_RD - PyModule_AddIntConstant(m, "SHUT_RD", SHUT_RD); + PyModule_AddIntConstant(m, "SHUT_RD", SHUT_RD); #elif defined(SD_RECEIVE) - PyModule_AddIntConstant(m, "SHUT_RD", SD_RECEIVE); + PyModule_AddIntConstant(m, "SHUT_RD", SD_RECEIVE); #else - PyModule_AddIntConstant(m, "SHUT_RD", 0); + PyModule_AddIntConstant(m, "SHUT_RD", 0); #endif #ifdef SHUT_WR - PyModule_AddIntConstant(m, "SHUT_WR", SHUT_WR); + PyModule_AddIntConstant(m, "SHUT_WR", SHUT_WR); #elif defined(SD_SEND) - PyModule_AddIntConstant(m, "SHUT_WR", SD_SEND); + PyModule_AddIntConstant(m, "SHUT_WR", SD_SEND); #else - PyModule_AddIntConstant(m, "SHUT_WR", 1); + PyModule_AddIntConstant(m, "SHUT_WR", 1); #endif #ifdef SHUT_RDWR - PyModule_AddIntConstant(m, "SHUT_RDWR", SHUT_RDWR); + PyModule_AddIntConstant(m, "SHUT_RDWR", SHUT_RDWR); #elif defined(SD_BOTH) - PyModule_AddIntConstant(m, "SHUT_RDWR", SD_BOTH); + PyModule_AddIntConstant(m, "SHUT_RDWR", SD_BOTH); #else - PyModule_AddIntConstant(m, "SHUT_RDWR", 2); + PyModule_AddIntConstant(m, "SHUT_RDWR", 2); #endif #ifdef SIO_RCVALL - { - DWORD codes[] = {SIO_RCVALL, SIO_KEEPALIVE_VALS}; - const char *names[] = {"SIO_RCVALL", "SIO_KEEPALIVE_VALS"}; - int i; - for(i = 0; i /* VC6 is shipped with old platform headers, and does not have MSTcpIP.h * Separate SDKs have all the functions we want, but older ones don't have - * any version information. + * any version information. * I use SIO_GET_MULTICAST_FILTER to detect a decent SDK. */ # ifdef SIO_GET_MULTICAST_FILTER @@ -76,44 +76,44 @@ #endif /* Python module and C API name */ -#define PySocket_MODULE_NAME "_socket" -#define PySocket_CAPI_NAME "CAPI" -#define PySocket_CAPSULE_NAME PySocket_MODULE_NAME "." PySocket_CAPI_NAME +#define PySocket_MODULE_NAME "_socket" +#define PySocket_CAPI_NAME "CAPI" +#define PySocket_CAPSULE_NAME PySocket_MODULE_NAME "." PySocket_CAPI_NAME /* Abstract the socket file descriptor type */ #ifdef MS_WINDOWS typedef SOCKET SOCKET_T; -# ifdef MS_WIN64 -# define SIZEOF_SOCKET_T 8 -# else -# define SIZEOF_SOCKET_T 4 -# endif +# ifdef MS_WIN64 +# define SIZEOF_SOCKET_T 8 +# else +# define SIZEOF_SOCKET_T 4 +# endif #else typedef int SOCKET_T; -# define SIZEOF_SOCKET_T SIZEOF_INT +# define SIZEOF_SOCKET_T SIZEOF_INT #endif /* Socket address */ typedef union sock_addr { - struct sockaddr_in in; + struct sockaddr_in in; #ifdef AF_UNIX - struct sockaddr_un un; + struct sockaddr_un un; #endif #ifdef AF_NETLINK - struct sockaddr_nl nl; + struct sockaddr_nl nl; #endif #ifdef ENABLE_IPV6 - struct sockaddr_in6 in6; - struct sockaddr_storage storage; + struct sockaddr_in6 in6; + struct sockaddr_storage storage; #endif #ifdef HAVE_BLUETOOTH_BLUETOOTH_H - struct sockaddr_l2 bt_l2; - struct sockaddr_rc bt_rc; - struct sockaddr_sco bt_sco; - struct sockaddr_hci bt_hci; + struct sockaddr_l2 bt_l2; + struct sockaddr_rc bt_rc; + struct sockaddr_sco bt_sco; + struct sockaddr_hci bt_hci; #endif #ifdef HAVE_NETPACKET_PACKET_H - struct sockaddr_ll ll; + struct sockaddr_ll ll; #endif } sock_addr_t; @@ -122,16 +122,16 @@ arguments properly. */ typedef struct { - PyObject_HEAD - SOCKET_T sock_fd; /* Socket file descriptor */ - int sock_family; /* Address family, e.g., AF_INET */ - int sock_type; /* Socket type, e.g., SOCK_STREAM */ - int sock_proto; /* Protocol type, usually 0 */ - PyObject *(*errorhandler)(void); /* Error handler; checks - errno, returns NULL and - sets a Python exception */ - double sock_timeout; /* Operation timeout in seconds; - 0.0 means non-blocking */ + PyObject_HEAD + SOCKET_T sock_fd; /* Socket file descriptor */ + int sock_family; /* Address family, e.g., AF_INET */ + int sock_type; /* Socket type, e.g., SOCK_STREAM */ + int sock_proto; /* Protocol type, usually 0 */ + PyObject *(*errorhandler)(void); /* Error handler; checks + errno, returns NULL and + sets a Python exception */ + double sock_timeout; /* Operation timeout in seconds; + 0.0 means non-blocking */ } PySocketSockObject; /* --- C API ----------------------------------------------------*/ @@ -139,7 +139,7 @@ /* Short explanation of what this C API export mechanism does and how it works: - The _ssl module needs access to the type object defined in + The _ssl module needs access to the type object defined in the _socket module. Since cross-DLL linking introduces a lot of problems on many platforms, the "trick" is to wrap the C API of a module in a struct which then gets exported to @@ -161,24 +161,24 @@ Load _socket module and its C API; this sets up the global PySocketModule: - - if (PySocketModule_ImportModuleAndAPI()) - return; + + if (PySocketModule_ImportModuleAndAPI()) + return; Now use the C API as if it were defined in the using module: - if (!PyArg_ParseTuple(args, "O!|zz:ssl", + if (!PyArg_ParseTuple(args, "O!|zz:ssl", - PySocketModule.Sock_Type, + PySocketModule.Sock_Type, - (PyObject*)&Sock, - &key_file, &cert_file)) - return NULL; + (PyObject*)&Sock, + &key_file, &cert_file)) + return NULL; Support could easily be extended to export more C APIs/symbols - this way. Currently, only the type object is exported, + this way. Currently, only the type object is exported, other candidates would be socket constructors and socket access functions. @@ -186,8 +186,8 @@ /* C API for usage by other Python modules */ typedef struct { - PyTypeObject *Sock_Type; - PyObject *error; + PyTypeObject *Sock_Type; + PyObject *error; } PySocketModule_APIObject; #define PySocketModule_ImportModuleAndAPI() PyCapsule_Import(PySocket_CAPSULE_NAME, 1) Modified: python/branches/py3k-jit/Modules/spwdmodule.c ============================================================================== --- python/branches/py3k-jit/Modules/spwdmodule.c (original) +++ python/branches/py3k-jit/Modules/spwdmodule.c Mon May 10 23:55:43 2010 @@ -27,16 +27,16 @@ #if defined(HAVE_GETSPNAM) || defined(HAVE_GETSPENT) static PyStructSequence_Field struct_spwd_type_fields[] = { - {"sp_nam", "login name"}, - {"sp_pwd", "encrypted password"}, - {"sp_lstchg", "date of last change"}, - {"sp_min", "min #days between changes"}, - {"sp_max", "max #days between changes"}, - {"sp_warn", "#days before pw expires to warn user about it"}, - {"sp_inact", "#days after pw expires until account is blocked"}, - {"sp_expire", "#days since 1970-01-01 until account is disabled"}, - {"sp_flag", "reserved"}, - {0} + {"sp_nam", "login name"}, + {"sp_pwd", "encrypted password"}, + {"sp_lstchg", "date of last change"}, + {"sp_min", "min #days between changes"}, + {"sp_max", "max #days between changes"}, + {"sp_warn", "#days before pw expires to warn user about it"}, + {"sp_inact", "#days after pw expires until account is blocked"}, + {"sp_expire", "#days since 1970-01-01 until account is disabled"}, + {"sp_flag", "reserved"}, + {0} }; PyDoc_STRVAR(struct_spwd__doc__, @@ -46,10 +46,10 @@ or via the object attributes as named in the above tuple."); static PyStructSequence_Desc struct_spwd_type_desc = { - "spwd.struct_spwd", - struct_spwd__doc__, - struct_spwd_type_fields, - 9, + "spwd.struct_spwd", + struct_spwd__doc__, + struct_spwd_type_fields, + 9, }; static int initialized; @@ -60,43 +60,43 @@ sets(PyObject *v, int i, const char* val) { if (val) { - PyObject *o = PyUnicode_DecodeFSDefault(val); - PyStructSequence_SET_ITEM(v, i, o); + PyObject *o = PyUnicode_DecodeFSDefault(val); + PyStructSequence_SET_ITEM(v, i, o); } else { - PyStructSequence_SET_ITEM(v, i, Py_None); - Py_INCREF(Py_None); + PyStructSequence_SET_ITEM(v, i, Py_None); + Py_INCREF(Py_None); } } static PyObject *mkspent(struct spwd *p) { - int setIndex = 0; - PyObject *v = PyStructSequence_New(&StructSpwdType); - if (v == NULL) - return NULL; + int setIndex = 0; + PyObject *v = PyStructSequence_New(&StructSpwdType); + if (v == NULL) + return NULL; #define SETI(i,val) PyStructSequence_SET_ITEM(v, i, PyLong_FromLong((long) val)) #define SETS(i,val) sets(v, i, val) - SETS(setIndex++, p->sp_namp); - SETS(setIndex++, p->sp_pwdp); - SETI(setIndex++, p->sp_lstchg); - SETI(setIndex++, p->sp_min); - SETI(setIndex++, p->sp_max); - SETI(setIndex++, p->sp_warn); - SETI(setIndex++, p->sp_inact); - SETI(setIndex++, p->sp_expire); - SETI(setIndex++, p->sp_flag); + SETS(setIndex++, p->sp_namp); + SETS(setIndex++, p->sp_pwdp); + SETI(setIndex++, p->sp_lstchg); + SETI(setIndex++, p->sp_min); + SETI(setIndex++, p->sp_max); + SETI(setIndex++, p->sp_warn); + SETI(setIndex++, p->sp_inact); + SETI(setIndex++, p->sp_expire); + SETI(setIndex++, p->sp_flag); #undef SETS #undef SETI - if (PyErr_Occurred()) { - Py_DECREF(v); - return NULL; - } + if (PyErr_Occurred()) { + Py_DECREF(v); + return NULL; + } - return v; + return v; } #endif /* HAVE_GETSPNAM || HAVE_GETSPENT */ @@ -112,26 +112,26 @@ static PyObject* spwd_getspnam(PyObject *self, PyObject *args) { - char *name; - struct spwd *p; - PyObject *arg, *bytes, *retval = NULL; - - if (!PyArg_ParseTuple(args, "U:getspnam", &arg)) - return NULL; - if ((bytes = PyUnicode_AsEncodedString(arg, - Py_FileSystemDefaultEncoding, - "surrogateescape")) == NULL) - return NULL; - if (PyBytes_AsStringAndSize(bytes, &name, NULL) == -1) - goto out; - if ((p = getspnam(name)) == NULL) { - PyErr_SetString(PyExc_KeyError, "getspnam(): name not found"); - goto out; - } - retval = mkspent(p); + char *name; + struct spwd *p; + PyObject *arg, *bytes, *retval = NULL; + + if (!PyArg_ParseTuple(args, "U:getspnam", &arg)) + return NULL; + if ((bytes = PyUnicode_AsEncodedString(arg, + Py_FileSystemDefaultEncoding, + "surrogateescape")) == NULL) + return NULL; + if (PyBytes_AsStringAndSize(bytes, &name, NULL) == -1) + goto out; + if ((p = getspnam(name)) == NULL) { + PyErr_SetString(PyExc_KeyError, "getspnam(): name not found"); + goto out; + } + retval = mkspent(p); out: - Py_DECREF(bytes); - return retval; + Py_DECREF(bytes); + return retval; } #endif /* HAVE_GETSPNAM */ @@ -147,63 +147,63 @@ static PyObject * spwd_getspall(PyObject *self, PyObject *args) { - PyObject *d; - struct spwd *p; - if ((d = PyList_New(0)) == NULL) - return NULL; - setspent(); - while ((p = getspent()) != NULL) { - PyObject *v = mkspent(p); - if (v == NULL || PyList_Append(d, v) != 0) { - Py_XDECREF(v); - Py_DECREF(d); - endspent(); - return NULL; - } - Py_DECREF(v); - } - endspent(); - return d; + PyObject *d; + struct spwd *p; + if ((d = PyList_New(0)) == NULL) + return NULL; + setspent(); + while ((p = getspent()) != NULL) { + PyObject *v = mkspent(p); + if (v == NULL || PyList_Append(d, v) != 0) { + Py_XDECREF(v); + Py_DECREF(d); + endspent(); + return NULL; + } + Py_DECREF(v); + } + endspent(); + return d; } #endif /* HAVE_GETSPENT */ static PyMethodDef spwd_methods[] = { -#ifdef HAVE_GETSPNAM - {"getspnam", spwd_getspnam, METH_VARARGS, spwd_getspnam__doc__}, +#ifdef HAVE_GETSPNAM + {"getspnam", spwd_getspnam, METH_VARARGS, spwd_getspnam__doc__}, #endif #ifdef HAVE_GETSPENT - {"getspall", spwd_getspall, METH_NOARGS, spwd_getspall__doc__}, + {"getspall", spwd_getspall, METH_NOARGS, spwd_getspall__doc__}, #endif - {NULL, NULL} /* sentinel */ + {NULL, NULL} /* sentinel */ }; static struct PyModuleDef spwdmodule = { - PyModuleDef_HEAD_INIT, - "spwd", - spwd__doc__, - -1, - spwd_methods, - NULL, - NULL, - NULL, - NULL + PyModuleDef_HEAD_INIT, + "spwd", + spwd__doc__, + -1, + spwd_methods, + NULL, + NULL, + NULL, + NULL }; PyMODINIT_FUNC PyInit_spwd(void) { - PyObject *m; - m=PyModule_Create(&spwdmodule); - if (m == NULL) - return NULL; - if (!initialized) - PyStructSequence_InitType(&StructSpwdType, - &struct_spwd_type_desc); - Py_INCREF((PyObject *) &StructSpwdType); - PyModule_AddObject(m, "struct_spwd", (PyObject *) &StructSpwdType); - initialized = 1; - return m; + PyObject *m; + m=PyModule_Create(&spwdmodule); + if (m == NULL) + return NULL; + if (!initialized) + PyStructSequence_InitType(&StructSpwdType, + &struct_spwd_type_desc); + Py_INCREF((PyObject *) &StructSpwdType); + PyModule_AddObject(m, "struct_spwd", (PyObject *) &StructSpwdType); + initialized = 1; + return m; } Modified: python/branches/py3k-jit/Modules/symtablemodule.c ============================================================================== --- python/branches/py3k-jit/Modules/symtablemodule.c (original) +++ python/branches/py3k-jit/Modules/symtablemodule.c Mon May 10 23:55:43 2010 @@ -8,93 +8,93 @@ static PyObject * symtable_symtable(PyObject *self, PyObject *args) { - struct symtable *st; - PyObject *t; + struct symtable *st; + PyObject *t; - char *str; - char *filename; - char *startstr; - int start; - - if (!PyArg_ParseTuple(args, "sss:symtable", &str, &filename, - &startstr)) - return NULL; - if (strcmp(startstr, "exec") == 0) - start = Py_file_input; - else if (strcmp(startstr, "eval") == 0) - start = Py_eval_input; - else if (strcmp(startstr, "single") == 0) - start = Py_single_input; - else { - PyErr_SetString(PyExc_ValueError, - "symtable() arg 3 must be 'exec' or 'eval' or 'single'"); - return NULL; - } - st = Py_SymtableString(str, filename, start); - if (st == NULL) - return NULL; - t = st->st_blocks; - Py_INCREF(t); - PyMem_Free((void *)st->st_future); - PySymtable_Free(st); - return t; + char *str; + char *filename; + char *startstr; + int start; + + if (!PyArg_ParseTuple(args, "sss:symtable", &str, &filename, + &startstr)) + return NULL; + if (strcmp(startstr, "exec") == 0) + start = Py_file_input; + else if (strcmp(startstr, "eval") == 0) + start = Py_eval_input; + else if (strcmp(startstr, "single") == 0) + start = Py_single_input; + else { + PyErr_SetString(PyExc_ValueError, + "symtable() arg 3 must be 'exec' or 'eval' or 'single'"); + return NULL; + } + st = Py_SymtableString(str, filename, start); + if (st == NULL) + return NULL; + t = st->st_blocks; + Py_INCREF(t); + PyMem_Free((void *)st->st_future); + PySymtable_Free(st); + return t; } static PyMethodDef symtable_methods[] = { - {"symtable", symtable_symtable, METH_VARARGS, - PyDoc_STR("Return symbol and scope dictionaries" - " used internally by compiler.")}, - {NULL, NULL} /* sentinel */ + {"symtable", symtable_symtable, METH_VARARGS, + PyDoc_STR("Return symbol and scope dictionaries" + " used internally by compiler.")}, + {NULL, NULL} /* sentinel */ }; static struct PyModuleDef symtablemodule = { - PyModuleDef_HEAD_INIT, - "_symtable", - NULL, - -1, - symtable_methods, - NULL, - NULL, - NULL, - NULL + PyModuleDef_HEAD_INIT, + "_symtable", + NULL, + -1, + symtable_methods, + NULL, + NULL, + NULL, + NULL }; PyMODINIT_FUNC PyInit__symtable(void) { - PyObject *m; + PyObject *m; - m = PyModule_Create(&symtablemodule); - if (m == NULL) - return NULL; - PyModule_AddIntConstant(m, "USE", USE); - PyModule_AddIntConstant(m, "DEF_GLOBAL", DEF_GLOBAL); - PyModule_AddIntConstant(m, "DEF_LOCAL", DEF_LOCAL); - PyModule_AddIntConstant(m, "DEF_PARAM", DEF_PARAM); - PyModule_AddIntConstant(m, "DEF_FREE", DEF_FREE); - PyModule_AddIntConstant(m, "DEF_FREE_CLASS", DEF_FREE_CLASS); - PyModule_AddIntConstant(m, "DEF_IMPORT", DEF_IMPORT); - PyModule_AddIntConstant(m, "DEF_BOUND", DEF_BOUND); - - PyModule_AddIntConstant(m, "TYPE_FUNCTION", FunctionBlock); - PyModule_AddIntConstant(m, "TYPE_CLASS", ClassBlock); - PyModule_AddIntConstant(m, "TYPE_MODULE", ModuleBlock); - - PyModule_AddIntConstant(m, "OPT_IMPORT_STAR", OPT_IMPORT_STAR); - PyModule_AddIntConstant(m, "OPT_TOPLEVEL", OPT_TOPLEVEL); - - PyModule_AddIntConstant(m, "LOCAL", LOCAL); - PyModule_AddIntConstant(m, "GLOBAL_EXPLICIT", GLOBAL_EXPLICIT); - PyModule_AddIntConstant(m, "GLOBAL_IMPLICIT", GLOBAL_IMPLICIT); - PyModule_AddIntConstant(m, "FREE", FREE); - PyModule_AddIntConstant(m, "CELL", CELL); - - PyModule_AddIntConstant(m, "SCOPE_OFF", SCOPE_OFFSET); - PyModule_AddIntConstant(m, "SCOPE_MASK", SCOPE_MASK); - - if (PyErr_Occurred()) { - Py_DECREF(m); - m = 0; - } - return m; + m = PyModule_Create(&symtablemodule); + if (m == NULL) + return NULL; + PyModule_AddIntConstant(m, "USE", USE); + PyModule_AddIntConstant(m, "DEF_GLOBAL", DEF_GLOBAL); + PyModule_AddIntConstant(m, "DEF_LOCAL", DEF_LOCAL); + PyModule_AddIntConstant(m, "DEF_PARAM", DEF_PARAM); + PyModule_AddIntConstant(m, "DEF_FREE", DEF_FREE); + PyModule_AddIntConstant(m, "DEF_FREE_CLASS", DEF_FREE_CLASS); + PyModule_AddIntConstant(m, "DEF_IMPORT", DEF_IMPORT); + PyModule_AddIntConstant(m, "DEF_BOUND", DEF_BOUND); + + PyModule_AddIntConstant(m, "TYPE_FUNCTION", FunctionBlock); + PyModule_AddIntConstant(m, "TYPE_CLASS", ClassBlock); + PyModule_AddIntConstant(m, "TYPE_MODULE", ModuleBlock); + + PyModule_AddIntConstant(m, "OPT_IMPORT_STAR", OPT_IMPORT_STAR); + PyModule_AddIntConstant(m, "OPT_TOPLEVEL", OPT_TOPLEVEL); + + PyModule_AddIntConstant(m, "LOCAL", LOCAL); + PyModule_AddIntConstant(m, "GLOBAL_EXPLICIT", GLOBAL_EXPLICIT); + PyModule_AddIntConstant(m, "GLOBAL_IMPLICIT", GLOBAL_IMPLICIT); + PyModule_AddIntConstant(m, "FREE", FREE); + PyModule_AddIntConstant(m, "CELL", CELL); + + PyModule_AddIntConstant(m, "SCOPE_OFF", SCOPE_OFFSET); + PyModule_AddIntConstant(m, "SCOPE_MASK", SCOPE_MASK); + + if (PyErr_Occurred()) { + Py_DECREF(m); + m = 0; + } + return m; } Modified: python/branches/py3k-jit/Modules/syslogmodule.c ============================================================================== --- python/branches/py3k-jit/Modules/syslogmodule.c (original) +++ python/branches/py3k-jit/Modules/syslogmodule.c Mon May 10 23:55:43 2010 @@ -4,20 +4,20 @@ All Rights Reserved -Permission to use, copy, modify, and distribute this software and its -documentation for any purpose and without fee is hereby granted, +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 +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 +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 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 +FITNESS, IN NO EVENT SHALL LANCE ELLINGHOUSE 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. ******************************************************************/ @@ -55,272 +55,272 @@ #include /* only one instance, only one syslog, so globals should be ok */ -static PyObject *S_ident_o = NULL; /* identifier, held by openlog() */ +static PyObject *S_ident_o = NULL; /* identifier, held by openlog() */ static char S_log_open = 0; static PyObject * syslog_get_argv(void) { - /* Figure out what to use for as the program "ident" for openlog(). - * This swallows exceptions and continues rather than failing out, - * because the syslog module can still be used because openlog(3) - * is optional. - */ - - Py_ssize_t argv_len; - PyObject *scriptobj; - char *atslash; - PyObject *argv = PySys_GetObject("argv"); - - if (argv == NULL) { - return(NULL); - } - - argv_len = PyList_Size(argv); - if (argv_len == -1) { - PyErr_Clear(); - return(NULL); - } - if (argv_len == 0) { - return(NULL); - } - - scriptobj = PyList_GetItem(argv, 0); - if (!PyUnicode_Check(scriptobj)) { - return(NULL); - } - if (PyUnicode_GET_SIZE(scriptobj) == 0) { - return(NULL); - } - - atslash = strrchr(_PyUnicode_AsString(scriptobj), SEP); - if (atslash) { - return(PyUnicode_FromString(atslash + 1)); - } else { - Py_INCREF(scriptobj); - return(scriptobj); - } + /* Figure out what to use for as the program "ident" for openlog(). + * This swallows exceptions and continues rather than failing out, + * because the syslog module can still be used because openlog(3) + * is optional. + */ + + Py_ssize_t argv_len; + PyObject *scriptobj; + char *atslash; + PyObject *argv = PySys_GetObject("argv"); + + if (argv == NULL) { + return(NULL); + } + + argv_len = PyList_Size(argv); + if (argv_len == -1) { + PyErr_Clear(); + return(NULL); + } + if (argv_len == 0) { + return(NULL); + } + + scriptobj = PyList_GetItem(argv, 0); + if (!PyUnicode_Check(scriptobj)) { + return(NULL); + } + if (PyUnicode_GET_SIZE(scriptobj) == 0) { + return(NULL); + } + + atslash = strrchr(_PyUnicode_AsString(scriptobj), SEP); + if (atslash) { + return(PyUnicode_FromString(atslash + 1)); + } else { + Py_INCREF(scriptobj); + return(scriptobj); + } - return(NULL); + return(NULL); } -static PyObject * +static PyObject * syslog_openlog(PyObject * self, PyObject * args, PyObject *kwds) { - long logopt = 0; - long facility = LOG_USER; - PyObject *new_S_ident_o = NULL; - static char *keywords[] = {"ident", "logoption", "facility", 0}; - - if (!PyArg_ParseTupleAndKeywords(args, kwds, - "|Ull:openlog", keywords, &new_S_ident_o, &logopt, &facility)) - return NULL; - - if (new_S_ident_o) { - Py_INCREF(new_S_ident_o); - } - - /* get sys.argv[0] or NULL if we can't for some reason */ - if (!new_S_ident_o) { - new_S_ident_o = syslog_get_argv(); - } - - Py_XDECREF(S_ident_o); - S_ident_o = new_S_ident_o; - - /* At this point, S_ident_o should be INCREF()ed. openlog(3) does not - * make a copy, and syslog(3) later uses it. We can't garbagecollect it - * If NULL, just let openlog figure it out (probably using C argv[0]). - */ - - openlog(S_ident_o ? _PyUnicode_AsString(S_ident_o) : NULL, logopt, facility); - S_log_open = 1; + long logopt = 0; + long facility = LOG_USER; + PyObject *new_S_ident_o = NULL; + static char *keywords[] = {"ident", "logoption", "facility", 0}; + + if (!PyArg_ParseTupleAndKeywords(args, kwds, + "|Ull:openlog", keywords, &new_S_ident_o, &logopt, &facility)) + return NULL; + + if (new_S_ident_o) { + Py_INCREF(new_S_ident_o); + } + + /* get sys.argv[0] or NULL if we can't for some reason */ + if (!new_S_ident_o) { + new_S_ident_o = syslog_get_argv(); + } + + Py_XDECREF(S_ident_o); + S_ident_o = new_S_ident_o; + + /* At this point, S_ident_o should be INCREF()ed. openlog(3) does not + * make a copy, and syslog(3) later uses it. We can't garbagecollect it + * If NULL, just let openlog figure it out (probably using C argv[0]). + */ + + openlog(S_ident_o ? _PyUnicode_AsString(S_ident_o) : NULL, logopt, facility); + S_log_open = 1; - Py_INCREF(Py_None); - return Py_None; + Py_INCREF(Py_None); + return Py_None; } -static PyObject * +static PyObject * syslog_syslog(PyObject * self, PyObject * args) { - PyObject *message_object; - const char *message; - int priority = LOG_INFO; - - if (!PyArg_ParseTuple(args, "iU;[priority,] message string", - &priority, &message_object)) { - PyErr_Clear(); - if (!PyArg_ParseTuple(args, "U;[priority,] message string", - &message_object)) - return NULL; - } - - message = _PyUnicode_AsString(message_object); - if (message == NULL) - return NULL; - - /* if log is not opened, open it now */ - if (!S_log_open) { - PyObject *openargs; - - /* Continue even if PyTuple_New fails, because openlog(3) is optional. - * So, we can still do loggin in the unlikely event things are so hosed - * that we can't do this tuple. - */ - if ((openargs = PyTuple_New(0))) { - PyObject *openlog_ret = syslog_openlog(self, openargs, NULL); - Py_XDECREF(openlog_ret); - Py_DECREF(openargs); - } - } - - Py_BEGIN_ALLOW_THREADS; - syslog(priority, "%s", message); - Py_END_ALLOW_THREADS; - Py_RETURN_NONE; + PyObject *message_object; + const char *message; + int priority = LOG_INFO; + + if (!PyArg_ParseTuple(args, "iU;[priority,] message string", + &priority, &message_object)) { + PyErr_Clear(); + if (!PyArg_ParseTuple(args, "U;[priority,] message string", + &message_object)) + return NULL; + } + + message = _PyUnicode_AsString(message_object); + if (message == NULL) + return NULL; + + /* if log is not opened, open it now */ + if (!S_log_open) { + PyObject *openargs; + + /* Continue even if PyTuple_New fails, because openlog(3) is optional. + * So, we can still do loggin in the unlikely event things are so hosed + * that we can't do this tuple. + */ + if ((openargs = PyTuple_New(0))) { + PyObject *openlog_ret = syslog_openlog(self, openargs, NULL); + Py_XDECREF(openlog_ret); + Py_DECREF(openargs); + } + } + + Py_BEGIN_ALLOW_THREADS; + syslog(priority, "%s", message); + Py_END_ALLOW_THREADS; + Py_RETURN_NONE; } -static PyObject * +static PyObject * syslog_closelog(PyObject *self, PyObject *unused) { - if (S_log_open) { - closelog(); - Py_XDECREF(S_ident_o); - S_ident_o = NULL; - S_log_open = 0; - } - Py_INCREF(Py_None); - return Py_None; + if (S_log_open) { + closelog(); + Py_XDECREF(S_ident_o); + S_ident_o = NULL; + S_log_open = 0; + } + Py_INCREF(Py_None); + return Py_None; } -static PyObject * +static PyObject * syslog_setlogmask(PyObject *self, PyObject *args) { - long maskpri, omaskpri; + long maskpri, omaskpri; - if (!PyArg_ParseTuple(args, "l;mask for priority", &maskpri)) - return NULL; - omaskpri = setlogmask(maskpri); - return PyLong_FromLong(omaskpri); + if (!PyArg_ParseTuple(args, "l;mask for priority", &maskpri)) + return NULL; + omaskpri = setlogmask(maskpri); + return PyLong_FromLong(omaskpri); } -static PyObject * +static PyObject * syslog_log_mask(PyObject *self, PyObject *args) { - long mask; - long pri; - if (!PyArg_ParseTuple(args, "l:LOG_MASK", &pri)) - return NULL; - mask = LOG_MASK(pri); - return PyLong_FromLong(mask); + long mask; + long pri; + if (!PyArg_ParseTuple(args, "l:LOG_MASK", &pri)) + return NULL; + mask = LOG_MASK(pri); + return PyLong_FromLong(mask); } -static PyObject * +static PyObject * syslog_log_upto(PyObject *self, PyObject *args) { - long mask; - long pri; - if (!PyArg_ParseTuple(args, "l:LOG_UPTO", &pri)) - return NULL; - mask = LOG_UPTO(pri); - return PyLong_FromLong(mask); + long mask; + long pri; + if (!PyArg_ParseTuple(args, "l:LOG_UPTO", &pri)) + return NULL; + mask = LOG_UPTO(pri); + return PyLong_FromLong(mask); } /* List of functions defined in the module */ static PyMethodDef syslog_methods[] = { - {"openlog", (PyCFunction) syslog_openlog, METH_VARARGS | METH_KEYWORDS}, - {"closelog", syslog_closelog, METH_NOARGS}, - {"syslog", syslog_syslog, METH_VARARGS}, - {"setlogmask", syslog_setlogmask, METH_VARARGS}, - {"LOG_MASK", syslog_log_mask, METH_VARARGS}, - {"LOG_UPTO", syslog_log_upto, METH_VARARGS}, - {NULL, NULL, 0} + {"openlog", (PyCFunction) syslog_openlog, METH_VARARGS | METH_KEYWORDS}, + {"closelog", syslog_closelog, METH_NOARGS}, + {"syslog", syslog_syslog, METH_VARARGS}, + {"setlogmask", syslog_setlogmask, METH_VARARGS}, + {"LOG_MASK", syslog_log_mask, METH_VARARGS}, + {"LOG_UPTO", syslog_log_upto, METH_VARARGS}, + {NULL, NULL, 0} }; /* Initialization function for the module */ static struct PyModuleDef syslogmodule = { - PyModuleDef_HEAD_INIT, - "syslog", - NULL, - -1, - syslog_methods, - NULL, - NULL, - NULL, - NULL + PyModuleDef_HEAD_INIT, + "syslog", + NULL, + -1, + syslog_methods, + NULL, + NULL, + NULL, + NULL }; PyMODINIT_FUNC PyInit_syslog(void) { - PyObject *m; + PyObject *m; - /* Create the module and add the functions */ - m = PyModule_Create(&syslogmodule); - if (m == NULL) - return NULL; - - /* Add some symbolic constants to the module */ - - /* Priorities */ - PyModule_AddIntConstant(m, "LOG_EMERG", LOG_EMERG); - PyModule_AddIntConstant(m, "LOG_ALERT", LOG_ALERT); - PyModule_AddIntConstant(m, "LOG_CRIT", LOG_CRIT); - PyModule_AddIntConstant(m, "LOG_ERR", LOG_ERR); - PyModule_AddIntConstant(m, "LOG_WARNING", LOG_WARNING); - PyModule_AddIntConstant(m, "LOG_NOTICE", LOG_NOTICE); - PyModule_AddIntConstant(m, "LOG_INFO", LOG_INFO); - PyModule_AddIntConstant(m, "LOG_DEBUG", LOG_DEBUG); - - /* openlog() option flags */ - PyModule_AddIntConstant(m, "LOG_PID", LOG_PID); - PyModule_AddIntConstant(m, "LOG_CONS", LOG_CONS); - PyModule_AddIntConstant(m, "LOG_NDELAY", LOG_NDELAY); + /* Create the module and add the functions */ + m = PyModule_Create(&syslogmodule); + if (m == NULL) + return NULL; + + /* Add some symbolic constants to the module */ + + /* Priorities */ + PyModule_AddIntConstant(m, "LOG_EMERG", LOG_EMERG); + PyModule_AddIntConstant(m, "LOG_ALERT", LOG_ALERT); + PyModule_AddIntConstant(m, "LOG_CRIT", LOG_CRIT); + PyModule_AddIntConstant(m, "LOG_ERR", LOG_ERR); + PyModule_AddIntConstant(m, "LOG_WARNING", LOG_WARNING); + PyModule_AddIntConstant(m, "LOG_NOTICE", LOG_NOTICE); + PyModule_AddIntConstant(m, "LOG_INFO", LOG_INFO); + PyModule_AddIntConstant(m, "LOG_DEBUG", LOG_DEBUG); + + /* openlog() option flags */ + PyModule_AddIntConstant(m, "LOG_PID", LOG_PID); + PyModule_AddIntConstant(m, "LOG_CONS", LOG_CONS); + PyModule_AddIntConstant(m, "LOG_NDELAY", LOG_NDELAY); #ifdef LOG_NOWAIT - PyModule_AddIntConstant(m, "LOG_NOWAIT", LOG_NOWAIT); + PyModule_AddIntConstant(m, "LOG_NOWAIT", LOG_NOWAIT); #endif #ifdef LOG_PERROR - PyModule_AddIntConstant(m, "LOG_PERROR", LOG_PERROR); + PyModule_AddIntConstant(m, "LOG_PERROR", LOG_PERROR); #endif - /* Facilities */ - PyModule_AddIntConstant(m, "LOG_KERN", LOG_KERN); - PyModule_AddIntConstant(m, "LOG_USER", LOG_USER); - PyModule_AddIntConstant(m, "LOG_MAIL", LOG_MAIL); - PyModule_AddIntConstant(m, "LOG_DAEMON", LOG_DAEMON); - PyModule_AddIntConstant(m, "LOG_AUTH", LOG_AUTH); - PyModule_AddIntConstant(m, "LOG_LPR", LOG_LPR); - PyModule_AddIntConstant(m, "LOG_LOCAL0", LOG_LOCAL0); - PyModule_AddIntConstant(m, "LOG_LOCAL1", LOG_LOCAL1); - PyModule_AddIntConstant(m, "LOG_LOCAL2", LOG_LOCAL2); - PyModule_AddIntConstant(m, "LOG_LOCAL3", LOG_LOCAL3); - PyModule_AddIntConstant(m, "LOG_LOCAL4", LOG_LOCAL4); - PyModule_AddIntConstant(m, "LOG_LOCAL5", LOG_LOCAL5); - PyModule_AddIntConstant(m, "LOG_LOCAL6", LOG_LOCAL6); - PyModule_AddIntConstant(m, "LOG_LOCAL7", LOG_LOCAL7); + /* Facilities */ + PyModule_AddIntConstant(m, "LOG_KERN", LOG_KERN); + PyModule_AddIntConstant(m, "LOG_USER", LOG_USER); + PyModule_AddIntConstant(m, "LOG_MAIL", LOG_MAIL); + PyModule_AddIntConstant(m, "LOG_DAEMON", LOG_DAEMON); + PyModule_AddIntConstant(m, "LOG_AUTH", LOG_AUTH); + PyModule_AddIntConstant(m, "LOG_LPR", LOG_LPR); + PyModule_AddIntConstant(m, "LOG_LOCAL0", LOG_LOCAL0); + PyModule_AddIntConstant(m, "LOG_LOCAL1", LOG_LOCAL1); + PyModule_AddIntConstant(m, "LOG_LOCAL2", LOG_LOCAL2); + PyModule_AddIntConstant(m, "LOG_LOCAL3", LOG_LOCAL3); + PyModule_AddIntConstant(m, "LOG_LOCAL4", LOG_LOCAL4); + PyModule_AddIntConstant(m, "LOG_LOCAL5", LOG_LOCAL5); + PyModule_AddIntConstant(m, "LOG_LOCAL6", LOG_LOCAL6); + PyModule_AddIntConstant(m, "LOG_LOCAL7", LOG_LOCAL7); #ifndef LOG_SYSLOG -#define LOG_SYSLOG LOG_DAEMON +#define LOG_SYSLOG LOG_DAEMON #endif #ifndef LOG_NEWS -#define LOG_NEWS LOG_MAIL +#define LOG_NEWS LOG_MAIL #endif #ifndef LOG_UUCP -#define LOG_UUCP LOG_MAIL +#define LOG_UUCP LOG_MAIL #endif #ifndef LOG_CRON -#define LOG_CRON LOG_DAEMON +#define LOG_CRON LOG_DAEMON #endif - PyModule_AddIntConstant(m, "LOG_SYSLOG", LOG_SYSLOG); - PyModule_AddIntConstant(m, "LOG_CRON", LOG_CRON); - PyModule_AddIntConstant(m, "LOG_UUCP", LOG_UUCP); - PyModule_AddIntConstant(m, "LOG_NEWS", LOG_NEWS); - return m; + PyModule_AddIntConstant(m, "LOG_SYSLOG", LOG_SYSLOG); + PyModule_AddIntConstant(m, "LOG_CRON", LOG_CRON); + PyModule_AddIntConstant(m, "LOG_UUCP", LOG_UUCP); + PyModule_AddIntConstant(m, "LOG_NEWS", LOG_NEWS); + return m; } Modified: python/branches/py3k-jit/Modules/termios.c ============================================================================== --- python/branches/py3k-jit/Modules/termios.c (original) +++ python/branches/py3k-jit/Modules/termios.c Mon May 10 23:55:43 2010 @@ -42,14 +42,14 @@ static int fdconv(PyObject* obj, void* p) { - int fd; + int fd; - fd = PyObject_AsFileDescriptor(obj); - if (fd >= 0) { - *(int*)p = fd; - return 1; - } - return 0; + fd = PyObject_AsFileDescriptor(obj); + if (fd >= 0) { + *(int*)p = fd; + return 1; + } + return 0; } PyDoc_STRVAR(termios_tcgetattr__doc__, @@ -66,67 +66,67 @@ static PyObject * termios_tcgetattr(PyObject *self, PyObject *args) { - int fd; - struct termios mode; - PyObject *cc; - speed_t ispeed, ospeed; - PyObject *v; - int i; - char ch; - - if (!PyArg_ParseTuple(args, "O&:tcgetattr", - fdconv, (void*)&fd)) - return NULL; - - if (tcgetattr(fd, &mode) == -1) - return PyErr_SetFromErrno(TermiosError); - - ispeed = cfgetispeed(&mode); - ospeed = cfgetospeed(&mode); - - cc = PyList_New(NCCS); - if (cc == NULL) - return NULL; - for (i = 0; i < NCCS; i++) { - ch = (char)mode.c_cc[i]; - v = PyBytes_FromStringAndSize(&ch, 1); - if (v == NULL) - goto err; - PyList_SetItem(cc, i, v); - } - - /* Convert the MIN and TIME slots to integer. On some systems, the - MIN and TIME slots are the same as the EOF and EOL slots. So we - only do this in noncanonical input mode. */ - if ((mode.c_lflag & ICANON) == 0) { - v = PyLong_FromLong((long)mode.c_cc[VMIN]); - if (v == NULL) - goto err; - PyList_SetItem(cc, VMIN, v); - v = PyLong_FromLong((long)mode.c_cc[VTIME]); - if (v == NULL) - goto err; - PyList_SetItem(cc, VTIME, v); - } - - if (!(v = PyList_New(7))) - goto err; - - PyList_SetItem(v, 0, PyLong_FromLong((long)mode.c_iflag)); - PyList_SetItem(v, 1, PyLong_FromLong((long)mode.c_oflag)); - PyList_SetItem(v, 2, PyLong_FromLong((long)mode.c_cflag)); - PyList_SetItem(v, 3, PyLong_FromLong((long)mode.c_lflag)); - PyList_SetItem(v, 4, PyLong_FromLong((long)ispeed)); - PyList_SetItem(v, 5, PyLong_FromLong((long)ospeed)); - PyList_SetItem(v, 6, cc); - if (PyErr_Occurred()){ - Py_DECREF(v); - goto err; - } - return v; + int fd; + struct termios mode; + PyObject *cc; + speed_t ispeed, ospeed; + PyObject *v; + int i; + char ch; + + if (!PyArg_ParseTuple(args, "O&:tcgetattr", + fdconv, (void*)&fd)) + return NULL; + + if (tcgetattr(fd, &mode) == -1) + return PyErr_SetFromErrno(TermiosError); + + ispeed = cfgetispeed(&mode); + ospeed = cfgetospeed(&mode); + + cc = PyList_New(NCCS); + if (cc == NULL) + return NULL; + for (i = 0; i < NCCS; i++) { + ch = (char)mode.c_cc[i]; + v = PyBytes_FromStringAndSize(&ch, 1); + if (v == NULL) + goto err; + PyList_SetItem(cc, i, v); + } + + /* Convert the MIN and TIME slots to integer. On some systems, the + MIN and TIME slots are the same as the EOF and EOL slots. So we + only do this in noncanonical input mode. */ + if ((mode.c_lflag & ICANON) == 0) { + v = PyLong_FromLong((long)mode.c_cc[VMIN]); + if (v == NULL) + goto err; + PyList_SetItem(cc, VMIN, v); + v = PyLong_FromLong((long)mode.c_cc[VTIME]); + if (v == NULL) + goto err; + PyList_SetItem(cc, VTIME, v); + } + + if (!(v = PyList_New(7))) + goto err; + + PyList_SetItem(v, 0, PyLong_FromLong((long)mode.c_iflag)); + PyList_SetItem(v, 1, PyLong_FromLong((long)mode.c_oflag)); + PyList_SetItem(v, 2, PyLong_FromLong((long)mode.c_cflag)); + PyList_SetItem(v, 3, PyLong_FromLong((long)mode.c_lflag)); + PyList_SetItem(v, 4, PyLong_FromLong((long)ispeed)); + PyList_SetItem(v, 5, PyLong_FromLong((long)ospeed)); + PyList_SetItem(v, 6, cc); + if (PyErr_Occurred()){ + Py_DECREF(v); + goto err; + } + return v; err: - Py_DECREF(cc); - return NULL; + Py_DECREF(cc); + return NULL; } PyDoc_STRVAR(termios_tcsetattr__doc__, @@ -143,64 +143,64 @@ static PyObject * termios_tcsetattr(PyObject *self, PyObject *args) { - int fd, when; - struct termios mode; - speed_t ispeed, ospeed; - PyObject *term, *cc, *v; - int i; - - if (!PyArg_ParseTuple(args, "O&iO:tcsetattr", - fdconv, &fd, &when, &term)) - return NULL; - if (!PyList_Check(term) || PyList_Size(term) != 7) { - PyErr_SetString(PyExc_TypeError, - "tcsetattr, arg 3: must be 7 element list"); - return NULL; - } - - /* Get the old mode, in case there are any hidden fields... */ - if (tcgetattr(fd, &mode) == -1) - return PyErr_SetFromErrno(TermiosError); - mode.c_iflag = (tcflag_t) PyLong_AsLong(PyList_GetItem(term, 0)); - mode.c_oflag = (tcflag_t) PyLong_AsLong(PyList_GetItem(term, 1)); - mode.c_cflag = (tcflag_t) PyLong_AsLong(PyList_GetItem(term, 2)); - mode.c_lflag = (tcflag_t) PyLong_AsLong(PyList_GetItem(term, 3)); - ispeed = (speed_t) PyLong_AsLong(PyList_GetItem(term, 4)); - ospeed = (speed_t) PyLong_AsLong(PyList_GetItem(term, 5)); - cc = PyList_GetItem(term, 6); - if (PyErr_Occurred()) - return NULL; - - if (!PyList_Check(cc) || PyList_Size(cc) != NCCS) { - PyErr_Format(PyExc_TypeError, - "tcsetattr: attributes[6] must be %d element list", - NCCS); - return NULL; - } - - for (i = 0; i < NCCS; i++) { - v = PyList_GetItem(cc, i); - - if (PyBytes_Check(v) && PyBytes_Size(v) == 1) - mode.c_cc[i] = (cc_t) * PyBytes_AsString(v); - else if (PyLong_Check(v)) - mode.c_cc[i] = (cc_t) PyLong_AsLong(v); - else { - PyErr_SetString(PyExc_TypeError, + int fd, when; + struct termios mode; + speed_t ispeed, ospeed; + PyObject *term, *cc, *v; + int i; + + if (!PyArg_ParseTuple(args, "O&iO:tcsetattr", + fdconv, &fd, &when, &term)) + return NULL; + if (!PyList_Check(term) || PyList_Size(term) != 7) { + PyErr_SetString(PyExc_TypeError, + "tcsetattr, arg 3: must be 7 element list"); + return NULL; + } + + /* Get the old mode, in case there are any hidden fields... */ + if (tcgetattr(fd, &mode) == -1) + return PyErr_SetFromErrno(TermiosError); + mode.c_iflag = (tcflag_t) PyLong_AsLong(PyList_GetItem(term, 0)); + mode.c_oflag = (tcflag_t) PyLong_AsLong(PyList_GetItem(term, 1)); + mode.c_cflag = (tcflag_t) PyLong_AsLong(PyList_GetItem(term, 2)); + mode.c_lflag = (tcflag_t) PyLong_AsLong(PyList_GetItem(term, 3)); + ispeed = (speed_t) PyLong_AsLong(PyList_GetItem(term, 4)); + ospeed = (speed_t) PyLong_AsLong(PyList_GetItem(term, 5)); + cc = PyList_GetItem(term, 6); + if (PyErr_Occurred()) + return NULL; + + if (!PyList_Check(cc) || PyList_Size(cc) != NCCS) { + PyErr_Format(PyExc_TypeError, + "tcsetattr: attributes[6] must be %d element list", + NCCS); + return NULL; + } + + for (i = 0; i < NCCS; i++) { + v = PyList_GetItem(cc, i); + + if (PyBytes_Check(v) && PyBytes_Size(v) == 1) + mode.c_cc[i] = (cc_t) * PyBytes_AsString(v); + else if (PyLong_Check(v)) + mode.c_cc[i] = (cc_t) PyLong_AsLong(v); + else { + PyErr_SetString(PyExc_TypeError, "tcsetattr: elements of attributes must be characters or integers"); - return NULL; - } - } - - if (cfsetispeed(&mode, (speed_t) ispeed) == -1) - return PyErr_SetFromErrno(TermiosError); - if (cfsetospeed(&mode, (speed_t) ospeed) == -1) - return PyErr_SetFromErrno(TermiosError); - if (tcsetattr(fd, when, &mode) == -1) - return PyErr_SetFromErrno(TermiosError); + return NULL; + } + } + + if (cfsetispeed(&mode, (speed_t) ispeed) == -1) + return PyErr_SetFromErrno(TermiosError); + if (cfsetospeed(&mode, (speed_t) ospeed) == -1) + return PyErr_SetFromErrno(TermiosError); + if (tcsetattr(fd, when, &mode) == -1) + return PyErr_SetFromErrno(TermiosError); - Py_INCREF(Py_None); - return Py_None; + Py_INCREF(Py_None); + return Py_None; } PyDoc_STRVAR(termios_tcsendbreak__doc__, @@ -213,16 +213,16 @@ static PyObject * termios_tcsendbreak(PyObject *self, PyObject *args) { - int fd, duration; + int fd, duration; - if (!PyArg_ParseTuple(args, "O&i:tcsendbreak", - fdconv, &fd, &duration)) - return NULL; - if (tcsendbreak(fd, duration) == -1) - return PyErr_SetFromErrno(TermiosError); + if (!PyArg_ParseTuple(args, "O&i:tcsendbreak", + fdconv, &fd, &duration)) + return NULL; + if (tcsendbreak(fd, duration) == -1) + return PyErr_SetFromErrno(TermiosError); - Py_INCREF(Py_None); - return Py_None; + Py_INCREF(Py_None); + return Py_None; } PyDoc_STRVAR(termios_tcdrain__doc__, @@ -233,16 +233,16 @@ static PyObject * termios_tcdrain(PyObject *self, PyObject *args) { - int fd; + int fd; - if (!PyArg_ParseTuple(args, "O&:tcdrain", - fdconv, &fd)) - return NULL; - if (tcdrain(fd) == -1) - return PyErr_SetFromErrno(TermiosError); + if (!PyArg_ParseTuple(args, "O&:tcdrain", + fdconv, &fd)) + return NULL; + if (tcdrain(fd) == -1) + return PyErr_SetFromErrno(TermiosError); - Py_INCREF(Py_None); - return Py_None; + Py_INCREF(Py_None); + return Py_None; } PyDoc_STRVAR(termios_tcflush__doc__, @@ -256,16 +256,16 @@ static PyObject * termios_tcflush(PyObject *self, PyObject *args) { - int fd, queue; + int fd, queue; - if (!PyArg_ParseTuple(args, "O&i:tcflush", - fdconv, &fd, &queue)) - return NULL; - if (tcflush(fd, queue) == -1) - return PyErr_SetFromErrno(TermiosError); + if (!PyArg_ParseTuple(args, "O&i:tcflush", + fdconv, &fd, &queue)) + return NULL; + if (tcflush(fd, queue) == -1) + return PyErr_SetFromErrno(TermiosError); - Py_INCREF(Py_None); - return Py_None; + Py_INCREF(Py_None); + return Py_None; } PyDoc_STRVAR(termios_tcflow__doc__, @@ -279,33 +279,33 @@ static PyObject * termios_tcflow(PyObject *self, PyObject *args) { - int fd, action; + int fd, action; - if (!PyArg_ParseTuple(args, "O&i:tcflow", - fdconv, &fd, &action)) - return NULL; - if (tcflow(fd, action) == -1) - return PyErr_SetFromErrno(TermiosError); + if (!PyArg_ParseTuple(args, "O&i:tcflow", + fdconv, &fd, &action)) + return NULL; + if (tcflow(fd, action) == -1) + return PyErr_SetFromErrno(TermiosError); - Py_INCREF(Py_None); - return Py_None; + Py_INCREF(Py_None); + return Py_None; } static PyMethodDef termios_methods[] = { - {"tcgetattr", termios_tcgetattr, - METH_VARARGS, termios_tcgetattr__doc__}, - {"tcsetattr", termios_tcsetattr, - METH_VARARGS, termios_tcsetattr__doc__}, - {"tcsendbreak", termios_tcsendbreak, - METH_VARARGS, termios_tcsendbreak__doc__}, - {"tcdrain", termios_tcdrain, - METH_VARARGS, termios_tcdrain__doc__}, - {"tcflush", termios_tcflush, - METH_VARARGS, termios_tcflush__doc__}, - {"tcflow", termios_tcflow, - METH_VARARGS, termios_tcflow__doc__}, - {NULL, NULL} + {"tcgetattr", termios_tcgetattr, + METH_VARARGS, termios_tcgetattr__doc__}, + {"tcsetattr", termios_tcsetattr, + METH_VARARGS, termios_tcsetattr__doc__}, + {"tcsendbreak", termios_tcsendbreak, + METH_VARARGS, termios_tcsendbreak__doc__}, + {"tcdrain", termios_tcdrain, + METH_VARARGS, termios_tcdrain__doc__}, + {"tcflush", termios_tcflush, + METH_VARARGS, termios_tcflush__doc__}, + {"tcflow", termios_tcflow, + METH_VARARGS, termios_tcflow__doc__}, + {NULL, NULL} }; @@ -318,622 +318,622 @@ #endif static struct constant { - char *name; - long value; + char *name; + long value; } termios_constants[] = { - /* cfgetospeed(), cfsetospeed() constants */ - {"B0", B0}, - {"B50", B50}, - {"B75", B75}, - {"B110", B110}, - {"B134", B134}, - {"B150", B150}, - {"B200", B200}, - {"B300", B300}, - {"B600", B600}, - {"B1200", B1200}, - {"B1800", B1800}, - {"B2400", B2400}, - {"B4800", B4800}, - {"B9600", B9600}, - {"B19200", B19200}, - {"B38400", B38400}, + /* cfgetospeed(), cfsetospeed() constants */ + {"B0", B0}, + {"B50", B50}, + {"B75", B75}, + {"B110", B110}, + {"B134", B134}, + {"B150", B150}, + {"B200", B200}, + {"B300", B300}, + {"B600", B600}, + {"B1200", B1200}, + {"B1800", B1800}, + {"B2400", B2400}, + {"B4800", B4800}, + {"B9600", B9600}, + {"B19200", B19200}, + {"B38400", B38400}, #ifdef B57600 - {"B57600", B57600}, + {"B57600", B57600}, #endif #ifdef B115200 - {"B115200", B115200}, + {"B115200", B115200}, #endif #ifdef B230400 - {"B230400", B230400}, + {"B230400", B230400}, #endif #ifdef CBAUDEX - {"CBAUDEX", CBAUDEX}, + {"CBAUDEX", CBAUDEX}, #endif - /* tcsetattr() constants */ - {"TCSANOW", TCSANOW}, - {"TCSADRAIN", TCSADRAIN}, - {"TCSAFLUSH", TCSAFLUSH}, + /* tcsetattr() constants */ + {"TCSANOW", TCSANOW}, + {"TCSADRAIN", TCSADRAIN}, + {"TCSAFLUSH", TCSAFLUSH}, #ifdef TCSASOFT - {"TCSASOFT", TCSASOFT}, + {"TCSASOFT", TCSASOFT}, #endif - /* tcflush() constants */ - {"TCIFLUSH", TCIFLUSH}, - {"TCOFLUSH", TCOFLUSH}, - {"TCIOFLUSH", TCIOFLUSH}, - - /* tcflow() constants */ - {"TCOOFF", TCOOFF}, - {"TCOON", TCOON}, - {"TCIOFF", TCIOFF}, - {"TCION", TCION}, - - /* struct termios.c_iflag constants */ - {"IGNBRK", IGNBRK}, - {"BRKINT", BRKINT}, - {"IGNPAR", IGNPAR}, - {"PARMRK", PARMRK}, - {"INPCK", INPCK}, - {"ISTRIP", ISTRIP}, - {"INLCR", INLCR}, - {"IGNCR", IGNCR}, - {"ICRNL", ICRNL}, + /* tcflush() constants */ + {"TCIFLUSH", TCIFLUSH}, + {"TCOFLUSH", TCOFLUSH}, + {"TCIOFLUSH", TCIOFLUSH}, + + /* tcflow() constants */ + {"TCOOFF", TCOOFF}, + {"TCOON", TCOON}, + {"TCIOFF", TCIOFF}, + {"TCION", TCION}, + + /* struct termios.c_iflag constants */ + {"IGNBRK", IGNBRK}, + {"BRKINT", BRKINT}, + {"IGNPAR", IGNPAR}, + {"PARMRK", PARMRK}, + {"INPCK", INPCK}, + {"ISTRIP", ISTRIP}, + {"INLCR", INLCR}, + {"IGNCR", IGNCR}, + {"ICRNL", ICRNL}, #ifdef IUCLC - {"IUCLC", IUCLC}, + {"IUCLC", IUCLC}, #endif - {"IXON", IXON}, - {"IXANY", IXANY}, - {"IXOFF", IXOFF}, + {"IXON", IXON}, + {"IXANY", IXANY}, + {"IXOFF", IXOFF}, #ifdef IMAXBEL - {"IMAXBEL", IMAXBEL}, + {"IMAXBEL", IMAXBEL}, #endif - /* struct termios.c_oflag constants */ - {"OPOST", OPOST}, + /* struct termios.c_oflag constants */ + {"OPOST", OPOST}, #ifdef OLCUC - {"OLCUC", OLCUC}, + {"OLCUC", OLCUC}, #endif #ifdef ONLCR - {"ONLCR", ONLCR}, + {"ONLCR", ONLCR}, #endif #ifdef OCRNL - {"OCRNL", OCRNL}, + {"OCRNL", OCRNL}, #endif #ifdef ONOCR - {"ONOCR", ONOCR}, + {"ONOCR", ONOCR}, #endif #ifdef ONLRET - {"ONLRET", ONLRET}, + {"ONLRET", ONLRET}, #endif #ifdef OFILL - {"OFILL", OFILL}, + {"OFILL", OFILL}, #endif #ifdef OFDEL - {"OFDEL", OFDEL}, + {"OFDEL", OFDEL}, #endif #ifdef NLDLY - {"NLDLY", NLDLY}, + {"NLDLY", NLDLY}, #endif #ifdef CRDLY - {"CRDLY", CRDLY}, + {"CRDLY", CRDLY}, #endif #ifdef TABDLY - {"TABDLY", TABDLY}, + {"TABDLY", TABDLY}, #endif #ifdef BSDLY - {"BSDLY", BSDLY}, + {"BSDLY", BSDLY}, #endif #ifdef VTDLY - {"VTDLY", VTDLY}, + {"VTDLY", VTDLY}, #endif #ifdef FFDLY - {"FFDLY", FFDLY}, + {"FFDLY", FFDLY}, #endif - /* struct termios.c_oflag-related values (delay mask) */ + /* struct termios.c_oflag-related values (delay mask) */ #ifdef NL0 - {"NL0", NL0}, + {"NL0", NL0}, #endif #ifdef NL1 - {"NL1", NL1}, + {"NL1", NL1}, #endif #ifdef CR0 - {"CR0", CR0}, + {"CR0", CR0}, #endif #ifdef CR1 - {"CR1", CR1}, + {"CR1", CR1}, #endif #ifdef CR2 - {"CR2", CR2}, + {"CR2", CR2}, #endif #ifdef CR3 - {"CR3", CR3}, + {"CR3", CR3}, #endif #ifdef TAB0 - {"TAB0", TAB0}, + {"TAB0", TAB0}, #endif #ifdef TAB1 - {"TAB1", TAB1}, + {"TAB1", TAB1}, #endif #ifdef TAB2 - {"TAB2", TAB2}, + {"TAB2", TAB2}, #endif #ifdef TAB3 - {"TAB3", TAB3}, + {"TAB3", TAB3}, #endif #ifdef XTABS - {"XTABS", XTABS}, + {"XTABS", XTABS}, #endif #ifdef BS0 - {"BS0", BS0}, + {"BS0", BS0}, #endif #ifdef BS1 - {"BS1", BS1}, + {"BS1", BS1}, #endif #ifdef VT0 - {"VT0", VT0}, + {"VT0", VT0}, #endif #ifdef VT1 - {"VT1", VT1}, + {"VT1", VT1}, #endif #ifdef FF0 - {"FF0", FF0}, + {"FF0", FF0}, #endif #ifdef FF1 - {"FF1", FF1}, + {"FF1", FF1}, #endif - /* struct termios.c_cflag constants */ - {"CSIZE", CSIZE}, - {"CSTOPB", CSTOPB}, - {"CREAD", CREAD}, - {"PARENB", PARENB}, - {"PARODD", PARODD}, - {"HUPCL", HUPCL}, - {"CLOCAL", CLOCAL}, + /* struct termios.c_cflag constants */ + {"CSIZE", CSIZE}, + {"CSTOPB", CSTOPB}, + {"CREAD", CREAD}, + {"PARENB", PARENB}, + {"PARODD", PARODD}, + {"HUPCL", HUPCL}, + {"CLOCAL", CLOCAL}, #ifdef CIBAUD - {"CIBAUD", CIBAUD}, + {"CIBAUD", CIBAUD}, #endif #ifdef CRTSCTS - {"CRTSCTS", (long)CRTSCTS}, + {"CRTSCTS", (long)CRTSCTS}, #endif - /* struct termios.c_cflag-related values (character size) */ - {"CS5", CS5}, - {"CS6", CS6}, - {"CS7", CS7}, - {"CS8", CS8}, - - /* struct termios.c_lflag constants */ - {"ISIG", ISIG}, - {"ICANON", ICANON}, + /* struct termios.c_cflag-related values (character size) */ + {"CS5", CS5}, + {"CS6", CS6}, + {"CS7", CS7}, + {"CS8", CS8}, + + /* struct termios.c_lflag constants */ + {"ISIG", ISIG}, + {"ICANON", ICANON}, #ifdef XCASE - {"XCASE", XCASE}, + {"XCASE", XCASE}, #endif - {"ECHO", ECHO}, - {"ECHOE", ECHOE}, - {"ECHOK", ECHOK}, - {"ECHONL", ECHONL}, + {"ECHO", ECHO}, + {"ECHOE", ECHOE}, + {"ECHOK", ECHOK}, + {"ECHONL", ECHONL}, #ifdef ECHOCTL - {"ECHOCTL", ECHOCTL}, + {"ECHOCTL", ECHOCTL}, #endif #ifdef ECHOPRT - {"ECHOPRT", ECHOPRT}, + {"ECHOPRT", ECHOPRT}, #endif #ifdef ECHOKE - {"ECHOKE", ECHOKE}, + {"ECHOKE", ECHOKE}, #endif #ifdef FLUSHO - {"FLUSHO", FLUSHO}, + {"FLUSHO", FLUSHO}, #endif - {"NOFLSH", NOFLSH}, - {"TOSTOP", TOSTOP}, + {"NOFLSH", NOFLSH}, + {"TOSTOP", TOSTOP}, #ifdef PENDIN - {"PENDIN", PENDIN}, + {"PENDIN", PENDIN}, #endif - {"IEXTEN", IEXTEN}, + {"IEXTEN", IEXTEN}, - /* indexes into the control chars array returned by tcgetattr() */ - {"VINTR", VINTR}, - {"VQUIT", VQUIT}, - {"VERASE", VERASE}, - {"VKILL", VKILL}, - {"VEOF", VEOF}, - {"VTIME", VTIME}, - {"VMIN", VMIN}, + /* indexes into the control chars array returned by tcgetattr() */ + {"VINTR", VINTR}, + {"VQUIT", VQUIT}, + {"VERASE", VERASE}, + {"VKILL", VKILL}, + {"VEOF", VEOF}, + {"VTIME", VTIME}, + {"VMIN", VMIN}, #ifdef VSWTC - /* The #defines above ensure that if either is defined, both are, - * but both may be omitted by the system headers. ;-( */ - {"VSWTC", VSWTC}, - {"VSWTCH", VSWTCH}, -#endif - {"VSTART", VSTART}, - {"VSTOP", VSTOP}, - {"VSUSP", VSUSP}, - {"VEOL", VEOL}, + /* The #defines above ensure that if either is defined, both are, + * but both may be omitted by the system headers. ;-( */ + {"VSWTC", VSWTC}, + {"VSWTCH", VSWTCH}, +#endif + {"VSTART", VSTART}, + {"VSTOP", VSTOP}, + {"VSUSP", VSUSP}, + {"VEOL", VEOL}, #ifdef VREPRINT - {"VREPRINT", VREPRINT}, + {"VREPRINT", VREPRINT}, #endif #ifdef VDISCARD - {"VDISCARD", VDISCARD}, + {"VDISCARD", VDISCARD}, #endif #ifdef VWERASE - {"VWERASE", VWERASE}, + {"VWERASE", VWERASE}, #endif #ifdef VLNEXT - {"VLNEXT", VLNEXT}, + {"VLNEXT", VLNEXT}, #endif #ifdef VEOL2 - {"VEOL2", VEOL2}, + {"VEOL2", VEOL2}, #endif #ifdef B460800 - {"B460800", B460800}, + {"B460800", B460800}, #endif #ifdef CBAUD - {"CBAUD", CBAUD}, + {"CBAUD", CBAUD}, #endif #ifdef CDEL - {"CDEL", CDEL}, + {"CDEL", CDEL}, #endif #ifdef CDSUSP - {"CDSUSP", CDSUSP}, + {"CDSUSP", CDSUSP}, #endif #ifdef CEOF - {"CEOF", CEOF}, + {"CEOF", CEOF}, #endif #ifdef CEOL - {"CEOL", CEOL}, + {"CEOL", CEOL}, #endif #ifdef CEOL2 - {"CEOL2", CEOL2}, + {"CEOL2", CEOL2}, #endif #ifdef CEOT - {"CEOT", CEOT}, + {"CEOT", CEOT}, #endif #ifdef CERASE - {"CERASE", CERASE}, + {"CERASE", CERASE}, #endif #ifdef CESC - {"CESC", CESC}, + {"CESC", CESC}, #endif #ifdef CFLUSH - {"CFLUSH", CFLUSH}, + {"CFLUSH", CFLUSH}, #endif #ifdef CINTR - {"CINTR", CINTR}, + {"CINTR", CINTR}, #endif #ifdef CKILL - {"CKILL", CKILL}, + {"CKILL", CKILL}, #endif #ifdef CLNEXT - {"CLNEXT", CLNEXT}, + {"CLNEXT", CLNEXT}, #endif #ifdef CNUL - {"CNUL", CNUL}, + {"CNUL", CNUL}, #endif #ifdef COMMON - {"COMMON", COMMON}, + {"COMMON", COMMON}, #endif #ifdef CQUIT - {"CQUIT", CQUIT}, + {"CQUIT", CQUIT}, #endif #ifdef CRPRNT - {"CRPRNT", CRPRNT}, + {"CRPRNT", CRPRNT}, #endif #ifdef CSTART - {"CSTART", CSTART}, + {"CSTART", CSTART}, #endif #ifdef CSTOP - {"CSTOP", CSTOP}, + {"CSTOP", CSTOP}, #endif #ifdef CSUSP - {"CSUSP", CSUSP}, + {"CSUSP", CSUSP}, #endif #ifdef CSWTCH - {"CSWTCH", CSWTCH}, + {"CSWTCH", CSWTCH}, #endif #ifdef CWERASE - {"CWERASE", CWERASE}, + {"CWERASE", CWERASE}, #endif #ifdef EXTA - {"EXTA", EXTA}, + {"EXTA", EXTA}, #endif #ifdef EXTB - {"EXTB", EXTB}, + {"EXTB", EXTB}, #endif #ifdef FIOASYNC - {"FIOASYNC", FIOASYNC}, + {"FIOASYNC", FIOASYNC}, #endif #ifdef FIOCLEX - {"FIOCLEX", FIOCLEX}, + {"FIOCLEX", FIOCLEX}, #endif #ifdef FIONBIO - {"FIONBIO", FIONBIO}, + {"FIONBIO", FIONBIO}, #endif #ifdef FIONCLEX - {"FIONCLEX", FIONCLEX}, + {"FIONCLEX", FIONCLEX}, #endif #ifdef FIONREAD - {"FIONREAD", FIONREAD}, + {"FIONREAD", FIONREAD}, #endif #ifdef IBSHIFT - {"IBSHIFT", IBSHIFT}, + {"IBSHIFT", IBSHIFT}, #endif #ifdef INIT_C_CC - {"INIT_C_CC", INIT_C_CC}, + {"INIT_C_CC", INIT_C_CC}, #endif #ifdef IOCSIZE_MASK - {"IOCSIZE_MASK", IOCSIZE_MASK}, + {"IOCSIZE_MASK", IOCSIZE_MASK}, #endif #ifdef IOCSIZE_SHIFT - {"IOCSIZE_SHIFT", IOCSIZE_SHIFT}, + {"IOCSIZE_SHIFT", IOCSIZE_SHIFT}, #endif #ifdef NCC - {"NCC", NCC}, + {"NCC", NCC}, #endif #ifdef NCCS - {"NCCS", NCCS}, + {"NCCS", NCCS}, #endif #ifdef NSWTCH - {"NSWTCH", NSWTCH}, + {"NSWTCH", NSWTCH}, #endif #ifdef N_MOUSE - {"N_MOUSE", N_MOUSE}, + {"N_MOUSE", N_MOUSE}, #endif #ifdef N_PPP - {"N_PPP", N_PPP}, + {"N_PPP", N_PPP}, #endif #ifdef N_SLIP - {"N_SLIP", N_SLIP}, + {"N_SLIP", N_SLIP}, #endif #ifdef N_STRIP - {"N_STRIP", N_STRIP}, + {"N_STRIP", N_STRIP}, #endif #ifdef N_TTY - {"N_TTY", N_TTY}, + {"N_TTY", N_TTY}, #endif #ifdef TCFLSH - {"TCFLSH", TCFLSH}, + {"TCFLSH", TCFLSH}, #endif #ifdef TCGETA - {"TCGETA", TCGETA}, + {"TCGETA", TCGETA}, #endif #ifdef TCGETS - {"TCGETS", TCGETS}, + {"TCGETS", TCGETS}, #endif #ifdef TCSBRK - {"TCSBRK", TCSBRK}, + {"TCSBRK", TCSBRK}, #endif #ifdef TCSBRKP - {"TCSBRKP", TCSBRKP}, + {"TCSBRKP", TCSBRKP}, #endif #ifdef TCSETA - {"TCSETA", TCSETA}, + {"TCSETA", TCSETA}, #endif #ifdef TCSETAF - {"TCSETAF", TCSETAF}, + {"TCSETAF", TCSETAF}, #endif #ifdef TCSETAW - {"TCSETAW", TCSETAW}, + {"TCSETAW", TCSETAW}, #endif #ifdef TCSETS - {"TCSETS", TCSETS}, + {"TCSETS", TCSETS}, #endif #ifdef TCSETSF - {"TCSETSF", TCSETSF}, + {"TCSETSF", TCSETSF}, #endif #ifdef TCSETSW - {"TCSETSW", TCSETSW}, + {"TCSETSW", TCSETSW}, #endif #ifdef TCXONC - {"TCXONC", TCXONC}, + {"TCXONC", TCXONC}, #endif #ifdef TIOCCONS - {"TIOCCONS", TIOCCONS}, + {"TIOCCONS", TIOCCONS}, #endif #ifdef TIOCEXCL - {"TIOCEXCL", TIOCEXCL}, + {"TIOCEXCL", TIOCEXCL}, #endif #ifdef TIOCGETD - {"TIOCGETD", TIOCGETD}, + {"TIOCGETD", TIOCGETD}, #endif #ifdef TIOCGICOUNT - {"TIOCGICOUNT", TIOCGICOUNT}, + {"TIOCGICOUNT", TIOCGICOUNT}, #endif #ifdef TIOCGLCKTRMIOS - {"TIOCGLCKTRMIOS", TIOCGLCKTRMIOS}, + {"TIOCGLCKTRMIOS", TIOCGLCKTRMIOS}, #endif #ifdef TIOCGPGRP - {"TIOCGPGRP", TIOCGPGRP}, + {"TIOCGPGRP", TIOCGPGRP}, #endif #ifdef TIOCGSERIAL - {"TIOCGSERIAL", TIOCGSERIAL}, + {"TIOCGSERIAL", TIOCGSERIAL}, #endif #ifdef TIOCGSOFTCAR - {"TIOCGSOFTCAR", TIOCGSOFTCAR}, + {"TIOCGSOFTCAR", TIOCGSOFTCAR}, #endif #ifdef TIOCGWINSZ - {"TIOCGWINSZ", TIOCGWINSZ}, + {"TIOCGWINSZ", TIOCGWINSZ}, #endif #ifdef TIOCINQ - {"TIOCINQ", TIOCINQ}, + {"TIOCINQ", TIOCINQ}, #endif #ifdef TIOCLINUX - {"TIOCLINUX", TIOCLINUX}, + {"TIOCLINUX", TIOCLINUX}, #endif #ifdef TIOCMBIC - {"TIOCMBIC", TIOCMBIC}, + {"TIOCMBIC", TIOCMBIC}, #endif #ifdef TIOCMBIS - {"TIOCMBIS", TIOCMBIS}, + {"TIOCMBIS", TIOCMBIS}, #endif #ifdef TIOCMGET - {"TIOCMGET", TIOCMGET}, + {"TIOCMGET", TIOCMGET}, #endif #ifdef TIOCMIWAIT - {"TIOCMIWAIT", TIOCMIWAIT}, + {"TIOCMIWAIT", TIOCMIWAIT}, #endif #ifdef TIOCMSET - {"TIOCMSET", TIOCMSET}, + {"TIOCMSET", TIOCMSET}, #endif #ifdef TIOCM_CAR - {"TIOCM_CAR", TIOCM_CAR}, + {"TIOCM_CAR", TIOCM_CAR}, #endif #ifdef TIOCM_CD - {"TIOCM_CD", TIOCM_CD}, + {"TIOCM_CD", TIOCM_CD}, #endif #ifdef TIOCM_CTS - {"TIOCM_CTS", TIOCM_CTS}, + {"TIOCM_CTS", TIOCM_CTS}, #endif #ifdef TIOCM_DSR - {"TIOCM_DSR", TIOCM_DSR}, + {"TIOCM_DSR", TIOCM_DSR}, #endif #ifdef TIOCM_DTR - {"TIOCM_DTR", TIOCM_DTR}, + {"TIOCM_DTR", TIOCM_DTR}, #endif #ifdef TIOCM_LE - {"TIOCM_LE", TIOCM_LE}, + {"TIOCM_LE", TIOCM_LE}, #endif #ifdef TIOCM_RI - {"TIOCM_RI", TIOCM_RI}, + {"TIOCM_RI", TIOCM_RI}, #endif #ifdef TIOCM_RNG - {"TIOCM_RNG", TIOCM_RNG}, + {"TIOCM_RNG", TIOCM_RNG}, #endif #ifdef TIOCM_RTS - {"TIOCM_RTS", TIOCM_RTS}, + {"TIOCM_RTS", TIOCM_RTS}, #endif #ifdef TIOCM_SR - {"TIOCM_SR", TIOCM_SR}, + {"TIOCM_SR", TIOCM_SR}, #endif #ifdef TIOCM_ST - {"TIOCM_ST", TIOCM_ST}, + {"TIOCM_ST", TIOCM_ST}, #endif #ifdef TIOCNOTTY - {"TIOCNOTTY", TIOCNOTTY}, + {"TIOCNOTTY", TIOCNOTTY}, #endif #ifdef TIOCNXCL - {"TIOCNXCL", TIOCNXCL}, + {"TIOCNXCL", TIOCNXCL}, #endif #ifdef TIOCOUTQ - {"TIOCOUTQ", TIOCOUTQ}, + {"TIOCOUTQ", TIOCOUTQ}, #endif #ifdef TIOCPKT - {"TIOCPKT", TIOCPKT}, + {"TIOCPKT", TIOCPKT}, #endif #ifdef TIOCPKT_DATA - {"TIOCPKT_DATA", TIOCPKT_DATA}, + {"TIOCPKT_DATA", TIOCPKT_DATA}, #endif #ifdef TIOCPKT_DOSTOP - {"TIOCPKT_DOSTOP", TIOCPKT_DOSTOP}, + {"TIOCPKT_DOSTOP", TIOCPKT_DOSTOP}, #endif #ifdef TIOCPKT_FLUSHREAD - {"TIOCPKT_FLUSHREAD", TIOCPKT_FLUSHREAD}, + {"TIOCPKT_FLUSHREAD", TIOCPKT_FLUSHREAD}, #endif #ifdef TIOCPKT_FLUSHWRITE - {"TIOCPKT_FLUSHWRITE", TIOCPKT_FLUSHWRITE}, + {"TIOCPKT_FLUSHWRITE", TIOCPKT_FLUSHWRITE}, #endif #ifdef TIOCPKT_NOSTOP - {"TIOCPKT_NOSTOP", TIOCPKT_NOSTOP}, + {"TIOCPKT_NOSTOP", TIOCPKT_NOSTOP}, #endif #ifdef TIOCPKT_START - {"TIOCPKT_START", TIOCPKT_START}, + {"TIOCPKT_START", TIOCPKT_START}, #endif #ifdef TIOCPKT_STOP - {"TIOCPKT_STOP", TIOCPKT_STOP}, + {"TIOCPKT_STOP", TIOCPKT_STOP}, #endif #ifdef TIOCSCTTY - {"TIOCSCTTY", TIOCSCTTY}, + {"TIOCSCTTY", TIOCSCTTY}, #endif #ifdef TIOCSERCONFIG - {"TIOCSERCONFIG", TIOCSERCONFIG}, + {"TIOCSERCONFIG", TIOCSERCONFIG}, #endif #ifdef TIOCSERGETLSR - {"TIOCSERGETLSR", TIOCSERGETLSR}, + {"TIOCSERGETLSR", TIOCSERGETLSR}, #endif #ifdef TIOCSERGETMULTI - {"TIOCSERGETMULTI", TIOCSERGETMULTI}, + {"TIOCSERGETMULTI", TIOCSERGETMULTI}, #endif #ifdef TIOCSERGSTRUCT - {"TIOCSERGSTRUCT", TIOCSERGSTRUCT}, + {"TIOCSERGSTRUCT", TIOCSERGSTRUCT}, #endif #ifdef TIOCSERGWILD - {"TIOCSERGWILD", TIOCSERGWILD}, + {"TIOCSERGWILD", TIOCSERGWILD}, #endif #ifdef TIOCSERSETMULTI - {"TIOCSERSETMULTI", TIOCSERSETMULTI}, + {"TIOCSERSETMULTI", TIOCSERSETMULTI}, #endif #ifdef TIOCSERSWILD - {"TIOCSERSWILD", TIOCSERSWILD}, + {"TIOCSERSWILD", TIOCSERSWILD}, #endif #ifdef TIOCSER_TEMT - {"TIOCSER_TEMT", TIOCSER_TEMT}, + {"TIOCSER_TEMT", TIOCSER_TEMT}, #endif #ifdef TIOCSETD - {"TIOCSETD", TIOCSETD}, + {"TIOCSETD", TIOCSETD}, #endif #ifdef TIOCSLCKTRMIOS - {"TIOCSLCKTRMIOS", TIOCSLCKTRMIOS}, + {"TIOCSLCKTRMIOS", TIOCSLCKTRMIOS}, #endif #ifdef TIOCSPGRP - {"TIOCSPGRP", TIOCSPGRP}, + {"TIOCSPGRP", TIOCSPGRP}, #endif #ifdef TIOCSSERIAL - {"TIOCSSERIAL", TIOCSSERIAL}, + {"TIOCSSERIAL", TIOCSSERIAL}, #endif #ifdef TIOCSSOFTCAR - {"TIOCSSOFTCAR", TIOCSSOFTCAR}, + {"TIOCSSOFTCAR", TIOCSSOFTCAR}, #endif #ifdef TIOCSTI - {"TIOCSTI", TIOCSTI}, + {"TIOCSTI", TIOCSTI}, #endif #ifdef TIOCSWINSZ - {"TIOCSWINSZ", TIOCSWINSZ}, + {"TIOCSWINSZ", TIOCSWINSZ}, #endif #ifdef TIOCTTYGSTRUCT - {"TIOCTTYGSTRUCT", TIOCTTYGSTRUCT}, + {"TIOCTTYGSTRUCT", TIOCTTYGSTRUCT}, #endif - /* sentinel */ - {NULL, 0} + /* sentinel */ + {NULL, 0} }; static struct PyModuleDef termiosmodule = { - PyModuleDef_HEAD_INIT, - "termios", - termios__doc__, - -1, - termios_methods, - NULL, - NULL, - NULL, - NULL + PyModuleDef_HEAD_INIT, + "termios", + termios__doc__, + -1, + termios_methods, + NULL, + NULL, + NULL, + NULL }; PyMODINIT_FUNC PyInit_termios(void) { - PyObject *m; - struct constant *constant = termios_constants; + PyObject *m; + struct constant *constant = termios_constants; - m = PyModule_Create(&termiosmodule); - if (m == NULL) - return NULL; - - if (TermiosError == NULL) { - TermiosError = PyErr_NewException("termios.error", NULL, NULL); - } - Py_INCREF(TermiosError); - PyModule_AddObject(m, "error", TermiosError); - - while (constant->name != NULL) { - PyModule_AddIntConstant(m, constant->name, constant->value); - ++constant; - } - return m; + m = PyModule_Create(&termiosmodule); + if (m == NULL) + return NULL; + + if (TermiosError == NULL) { + TermiosError = PyErr_NewException("termios.error", NULL, NULL); + } + Py_INCREF(TermiosError); + PyModule_AddObject(m, "error", TermiosError); + + while (constant->name != NULL) { + PyModule_AddIntConstant(m, constant->name, constant->value); + ++constant; + } + return m; } Modified: python/branches/py3k-jit/Modules/testcapi_long.h ============================================================================== --- python/branches/py3k-jit/Modules/testcapi_long.h (original) +++ python/branches/py3k-jit/Modules/testcapi_long.h Mon May 10 23:55:43 2010 @@ -1,182 +1,182 @@ /* Poor-man's template. Macros used: - TESTNAME name of the test (like test_long_api_inner) - TYPENAME the signed type (like long) - F_S_TO_PY convert signed to pylong; TYPENAME -> PyObject* - F_PY_TO_S convert pylong to signed; PyObject* -> TYPENAME - F_U_TO_PY convert unsigned to pylong; unsigned TYPENAME -> PyObject* + TESTNAME name of the test (like test_long_api_inner) + TYPENAME the signed type (like long) + F_S_TO_PY convert signed to pylong; TYPENAME -> PyObject* + F_PY_TO_S convert pylong to signed; PyObject* -> TYPENAME + F_U_TO_PY convert unsigned to pylong; unsigned TYPENAME -> PyObject* F_PY_TO_U convert pylong to unsigned; PyObject* -> unsigned TYPENAME */ static PyObject * TESTNAME(PyObject *error(const char*)) { - const int NBITS = sizeof(TYPENAME) * 8; - unsigned TYPENAME base; - PyObject *pyresult; - int i; - - /* Note: This test lets PyObjects leak if an error is raised. Since - an error should never be raised, leaks are impossible . */ - - /* Test native -> PyLong -> native roundtrip identity. - * Generate all powers of 2, and test them and their negations, - * plus the numbers +-1 off from them. - */ - base = 1; - for (i = 0; - i < NBITS + 1; /* on last, base overflows to 0 */ - ++i, base <<= 1) - { - int j; - for (j = 0; j < 6; ++j) { - TYPENAME in, out; - unsigned TYPENAME uin, uout; - - /* For 0, 1, 2 use base; for 3, 4, 5 use -base */ - uin = j < 3 ? base - : (unsigned TYPENAME)(-(TYPENAME)base); - - /* For 0 & 3, subtract 1. - * For 1 & 4, leave alone. - * For 2 & 5, add 1. - */ - uin += (unsigned TYPENAME)(TYPENAME)(j % 3 - 1); - - pyresult = F_U_TO_PY(uin); - if (pyresult == NULL) - return error( - "unsigned unexpected null result"); - - uout = F_PY_TO_U(pyresult); - if (uout == (unsigned TYPENAME)-1 && PyErr_Occurred()) - return error( - "unsigned unexpected -1 result"); - if (uout != uin) - return error( - "unsigned output != input"); - UNBIND(pyresult); - - in = (TYPENAME)uin; - pyresult = F_S_TO_PY(in); - if (pyresult == NULL) - return error( - "signed unexpected null result"); - - out = F_PY_TO_S(pyresult); - if (out == (TYPENAME)-1 && PyErr_Occurred()) - return error( - "signed unexpected -1 result"); - if (out != in) - return error( - "signed output != input"); - UNBIND(pyresult); - } - } - - /* Overflow tests. The loop above ensured that all limit cases that - * should not overflow don't overflow, so all we need to do here is - * provoke one-over-the-limit cases (not exhaustive, but sharp). - */ - { - PyObject *one, *x, *y; - TYPENAME out; - unsigned TYPENAME uout; - - one = PyLong_FromLong(1); - if (one == NULL) - return error( - "unexpected NULL from PyLong_FromLong"); - - /* Unsigned complains about -1? */ - x = PyNumber_Negative(one); - if (x == NULL) - return error( - "unexpected NULL from PyNumber_Negative"); - - uout = F_PY_TO_U(x); - if (uout != (unsigned TYPENAME)-1 || !PyErr_Occurred()) - return error( - "PyLong_AsUnsignedXXX(-1) didn't complain"); - if (!PyErr_ExceptionMatches(PyExc_OverflowError)) - return error( - "PyLong_AsUnsignedXXX(-1) raised " - "something other than OverflowError"); - PyErr_Clear(); - UNBIND(x); - - /* Unsigned complains about 2**NBITS? */ - y = PyLong_FromLong((long)NBITS); - if (y == NULL) - return error( - "unexpected NULL from PyLong_FromLong"); - - x = PyNumber_Lshift(one, y); /* 1L << NBITS, == 2**NBITS */ - UNBIND(y); - if (x == NULL) - return error( - "unexpected NULL from PyNumber_Lshift"); - - uout = F_PY_TO_U(x); - if (uout != (unsigned TYPENAME)-1 || !PyErr_Occurred()) - return error( - "PyLong_AsUnsignedXXX(2**NBITS) didn't " - "complain"); - if (!PyErr_ExceptionMatches(PyExc_OverflowError)) - return error( - "PyLong_AsUnsignedXXX(2**NBITS) raised " - "something other than OverflowError"); - PyErr_Clear(); - - /* Signed complains about 2**(NBITS-1)? - x still has 2**NBITS. */ - y = PyNumber_Rshift(x, one); /* 2**(NBITS-1) */ - UNBIND(x); - if (y == NULL) - return error( - "unexpected NULL from PyNumber_Rshift"); - - out = F_PY_TO_S(y); - if (out != (TYPENAME)-1 || !PyErr_Occurred()) - return error( - "PyLong_AsXXX(2**(NBITS-1)) didn't " - "complain"); - if (!PyErr_ExceptionMatches(PyExc_OverflowError)) - return error( - "PyLong_AsXXX(2**(NBITS-1)) raised " - "something other than OverflowError"); - PyErr_Clear(); - - /* Signed complains about -2**(NBITS-1)-1?; - y still has 2**(NBITS-1). */ - x = PyNumber_Negative(y); /* -(2**(NBITS-1)) */ - UNBIND(y); - if (x == NULL) - return error( - "unexpected NULL from PyNumber_Negative"); - - y = PyNumber_Subtract(x, one); /* -(2**(NBITS-1))-1 */ - UNBIND(x); - if (y == NULL) - return error( - "unexpected NULL from PyNumber_Subtract"); - - out = F_PY_TO_S(y); - if (out != (TYPENAME)-1 || !PyErr_Occurred()) - return error( - "PyLong_AsXXX(-2**(NBITS-1)-1) didn't " - "complain"); - if (!PyErr_ExceptionMatches(PyExc_OverflowError)) - return error( - "PyLong_AsXXX(-2**(NBITS-1)-1) raised " - "something other than OverflowError"); - PyErr_Clear(); - UNBIND(y); - - Py_XDECREF(x); - Py_XDECREF(y); - Py_DECREF(one); - } + const int NBITS = sizeof(TYPENAME) * 8; + unsigned TYPENAME base; + PyObject *pyresult; + int i; + + /* Note: This test lets PyObjects leak if an error is raised. Since + an error should never be raised, leaks are impossible . */ + + /* Test native -> PyLong -> native roundtrip identity. + * Generate all powers of 2, and test them and their negations, + * plus the numbers +-1 off from them. + */ + base = 1; + for (i = 0; + i < NBITS + 1; /* on last, base overflows to 0 */ + ++i, base <<= 1) + { + int j; + for (j = 0; j < 6; ++j) { + TYPENAME in, out; + unsigned TYPENAME uin, uout; + + /* For 0, 1, 2 use base; for 3, 4, 5 use -base */ + uin = j < 3 ? base + : (unsigned TYPENAME)(-(TYPENAME)base); + + /* For 0 & 3, subtract 1. + * For 1 & 4, leave alone. + * For 2 & 5, add 1. + */ + uin += (unsigned TYPENAME)(TYPENAME)(j % 3 - 1); + + pyresult = F_U_TO_PY(uin); + if (pyresult == NULL) + return error( + "unsigned unexpected null result"); + + uout = F_PY_TO_U(pyresult); + if (uout == (unsigned TYPENAME)-1 && PyErr_Occurred()) + return error( + "unsigned unexpected -1 result"); + if (uout != uin) + return error( + "unsigned output != input"); + UNBIND(pyresult); + + in = (TYPENAME)uin; + pyresult = F_S_TO_PY(in); + if (pyresult == NULL) + return error( + "signed unexpected null result"); + + out = F_PY_TO_S(pyresult); + if (out == (TYPENAME)-1 && PyErr_Occurred()) + return error( + "signed unexpected -1 result"); + if (out != in) + return error( + "signed output != input"); + UNBIND(pyresult); + } + } + + /* Overflow tests. The loop above ensured that all limit cases that + * should not overflow don't overflow, so all we need to do here is + * provoke one-over-the-limit cases (not exhaustive, but sharp). + */ + { + PyObject *one, *x, *y; + TYPENAME out; + unsigned TYPENAME uout; + + one = PyLong_FromLong(1); + if (one == NULL) + return error( + "unexpected NULL from PyLong_FromLong"); + + /* Unsigned complains about -1? */ + x = PyNumber_Negative(one); + if (x == NULL) + return error( + "unexpected NULL from PyNumber_Negative"); + + uout = F_PY_TO_U(x); + if (uout != (unsigned TYPENAME)-1 || !PyErr_Occurred()) + return error( + "PyLong_AsUnsignedXXX(-1) didn't complain"); + if (!PyErr_ExceptionMatches(PyExc_OverflowError)) + return error( + "PyLong_AsUnsignedXXX(-1) raised " + "something other than OverflowError"); + PyErr_Clear(); + UNBIND(x); + + /* Unsigned complains about 2**NBITS? */ + y = PyLong_FromLong((long)NBITS); + if (y == NULL) + return error( + "unexpected NULL from PyLong_FromLong"); + + x = PyNumber_Lshift(one, y); /* 1L << NBITS, == 2**NBITS */ + UNBIND(y); + if (x == NULL) + return error( + "unexpected NULL from PyNumber_Lshift"); + + uout = F_PY_TO_U(x); + if (uout != (unsigned TYPENAME)-1 || !PyErr_Occurred()) + return error( + "PyLong_AsUnsignedXXX(2**NBITS) didn't " + "complain"); + if (!PyErr_ExceptionMatches(PyExc_OverflowError)) + return error( + "PyLong_AsUnsignedXXX(2**NBITS) raised " + "something other than OverflowError"); + PyErr_Clear(); + + /* Signed complains about 2**(NBITS-1)? + x still has 2**NBITS. */ + y = PyNumber_Rshift(x, one); /* 2**(NBITS-1) */ + UNBIND(x); + if (y == NULL) + return error( + "unexpected NULL from PyNumber_Rshift"); + + out = F_PY_TO_S(y); + if (out != (TYPENAME)-1 || !PyErr_Occurred()) + return error( + "PyLong_AsXXX(2**(NBITS-1)) didn't " + "complain"); + if (!PyErr_ExceptionMatches(PyExc_OverflowError)) + return error( + "PyLong_AsXXX(2**(NBITS-1)) raised " + "something other than OverflowError"); + PyErr_Clear(); + + /* Signed complains about -2**(NBITS-1)-1?; + y still has 2**(NBITS-1). */ + x = PyNumber_Negative(y); /* -(2**(NBITS-1)) */ + UNBIND(y); + if (x == NULL) + return error( + "unexpected NULL from PyNumber_Negative"); + + y = PyNumber_Subtract(x, one); /* -(2**(NBITS-1))-1 */ + UNBIND(x); + if (y == NULL) + return error( + "unexpected NULL from PyNumber_Subtract"); + + out = F_PY_TO_S(y); + if (out != (TYPENAME)-1 || !PyErr_Occurred()) + return error( + "PyLong_AsXXX(-2**(NBITS-1)-1) didn't " + "complain"); + if (!PyErr_ExceptionMatches(PyExc_OverflowError)) + return error( + "PyLong_AsXXX(-2**(NBITS-1)-1) raised " + "something other than OverflowError"); + PyErr_Clear(); + UNBIND(y); + + Py_XDECREF(x); + Py_XDECREF(y); + Py_DECREF(one); + } - Py_INCREF(Py_None); - return Py_None; + Py_INCREF(Py_None); + return Py_None; } Modified: python/branches/py3k-jit/Modules/timemodule.c ============================================================================== --- python/branches/py3k-jit/Modules/timemodule.c (original) +++ python/branches/py3k-jit/Modules/timemodule.c Mon May 10 23:55:43 2010 @@ -48,12 +48,12 @@ static HANDLE hInterruptEvent = NULL; static BOOL WINAPI PyCtrlHandler(DWORD dwCtrlType) { - SetEvent(hInterruptEvent); - /* allow other default handlers to be called. - Default Python handler will setup the - KeyboardInterrupt exception. - */ - return FALSE; + SetEvent(hInterruptEvent); + /* allow other default handlers to be called. + Default Python handler will setup the + KeyboardInterrupt exception. + */ + return FALSE; } static long main_thread; @@ -94,38 +94,38 @@ time_t _PyTime_DoubleToTimet(double x) { - time_t result; - double diff; + time_t result; + double diff; - result = (time_t)x; - /* How much info did we lose? time_t may be an integral or - * floating type, and we don't know which. If it's integral, - * we don't know whether C truncates, rounds, returns the floor, - * etc. If we lost a second or more, the C rounding is - * unreasonable, or the input just doesn't fit in a time_t; - * call it an error regardless. Note that the original cast to - * time_t can cause a C error too, but nothing we can do to - * worm around that. - */ - diff = x - (double)result; - if (diff <= -1.0 || diff >= 1.0) { - PyErr_SetString(PyExc_ValueError, - "timestamp out of range for platform time_t"); - result = (time_t)-1; - } - return result; + result = (time_t)x; + /* How much info did we lose? time_t may be an integral or + * floating type, and we don't know which. If it's integral, + * we don't know whether C truncates, rounds, returns the floor, + * etc. If we lost a second or more, the C rounding is + * unreasonable, or the input just doesn't fit in a time_t; + * call it an error regardless. Note that the original cast to + * time_t can cause a C error too, but nothing we can do to + * worm around that. + */ + diff = x - (double)result; + if (diff <= -1.0 || diff >= 1.0) { + PyErr_SetString(PyExc_ValueError, + "timestamp out of range for platform time_t"); + result = (time_t)-1; + } + return result; } static PyObject * time_time(PyObject *self, PyObject *unused) { - double secs; - secs = floattime(); - if (secs == 0.0) { - PyErr_SetFromErrno(PyExc_IOError); - return NULL; - } - return PyFloat_FromDouble(secs); + double secs; + secs = floattime(); + if (secs == 0.0) { + PyErr_SetFromErrno(PyExc_IOError); + return NULL; + } + return PyFloat_FromDouble(secs); } PyDoc_STRVAR(time_doc, @@ -147,7 +147,7 @@ static PyObject * time_clock(PyObject *self, PyObject *unused) { - return PyFloat_FromDouble(((double)clock()) / CLOCKS_PER_SEC); + return PyFloat_FromDouble(((double)clock()) / CLOCKS_PER_SEC); } #endif /* HAVE_CLOCK */ @@ -156,25 +156,25 @@ static PyObject * time_clock(PyObject *self, PyObject *unused) { - static LARGE_INTEGER ctrStart; - static double divisor = 0.0; - LARGE_INTEGER now; - double diff; - - if (divisor == 0.0) { - LARGE_INTEGER freq; - QueryPerformanceCounter(&ctrStart); - if (!QueryPerformanceFrequency(&freq) || freq.QuadPart == 0) { - /* Unlikely to happen - this works on all intel - machines at least! Revert to clock() */ - return PyFloat_FromDouble(((double)clock()) / - CLOCKS_PER_SEC); - } - divisor = (double)freq.QuadPart; - } - QueryPerformanceCounter(&now); - diff = (double)(now.QuadPart - ctrStart.QuadPart); - return PyFloat_FromDouble(diff / divisor); + static LARGE_INTEGER ctrStart; + static double divisor = 0.0; + LARGE_INTEGER now; + double diff; + + if (divisor == 0.0) { + LARGE_INTEGER freq; + QueryPerformanceCounter(&ctrStart); + if (!QueryPerformanceFrequency(&freq) || freq.QuadPart == 0) { + /* Unlikely to happen - this works on all intel + machines at least! Revert to clock() */ + return PyFloat_FromDouble(((double)clock()) / + CLOCKS_PER_SEC); + } + divisor = (double)freq.QuadPart; + } + QueryPerformanceCounter(&now); + diff = (double)(now.QuadPart - ctrStart.QuadPart); + return PyFloat_FromDouble(diff / divisor); } #define HAVE_CLOCK /* So it gets included in the methods */ @@ -192,13 +192,13 @@ static PyObject * time_sleep(PyObject *self, PyObject *args) { - double secs; - if (!PyArg_ParseTuple(args, "d:sleep", &secs)) - return NULL; - if (floatsleep(secs) != 0) - return NULL; - Py_INCREF(Py_None); - return Py_None; + double secs; + if (!PyArg_ParseTuple(args, "d:sleep", &secs)) + return NULL; + if (floatsleep(secs) != 0) + return NULL; + Py_INCREF(Py_None); + return Py_None; } PyDoc_STRVAR(sleep_doc, @@ -208,23 +208,23 @@ a floating point number for subsecond precision."); static PyStructSequence_Field struct_time_type_fields[] = { - {"tm_year", NULL}, - {"tm_mon", NULL}, - {"tm_mday", NULL}, - {"tm_hour", NULL}, - {"tm_min", NULL}, - {"tm_sec", NULL}, - {"tm_wday", NULL}, - {"tm_yday", NULL}, - {"tm_isdst", NULL}, - {0} + {"tm_year", NULL}, + {"tm_mon", NULL}, + {"tm_mday", NULL}, + {"tm_hour", NULL}, + {"tm_min", NULL}, + {"tm_sec", NULL}, + {"tm_wday", NULL}, + {"tm_yday", NULL}, + {"tm_isdst", NULL}, + {0} }; static PyStructSequence_Desc struct_time_type_desc = { - "time.struct_time", - NULL, - struct_time_type_fields, - 9, + "time.struct_time", + NULL, + struct_time_type_fields, + 9, }; static int initialized; @@ -233,71 +233,71 @@ static PyObject * tmtotuple(struct tm *p) { - PyObject *v = PyStructSequence_New(&StructTimeType); - if (v == NULL) - return NULL; + PyObject *v = PyStructSequence_New(&StructTimeType); + if (v == NULL) + return NULL; #define SET(i,val) PyStructSequence_SET_ITEM(v, i, PyLong_FromLong((long) val)) - SET(0, p->tm_year + 1900); - SET(1, p->tm_mon + 1); /* Want January == 1 */ - SET(2, p->tm_mday); - SET(3, p->tm_hour); - SET(4, p->tm_min); - SET(5, p->tm_sec); - SET(6, (p->tm_wday + 6) % 7); /* Want Monday == 0 */ - SET(7, p->tm_yday + 1); /* Want January, 1 == 1 */ - SET(8, p->tm_isdst); + SET(0, p->tm_year + 1900); + SET(1, p->tm_mon + 1); /* Want January == 1 */ + SET(2, p->tm_mday); + SET(3, p->tm_hour); + SET(4, p->tm_min); + SET(5, p->tm_sec); + SET(6, (p->tm_wday + 6) % 7); /* Want Monday == 0 */ + SET(7, p->tm_yday + 1); /* Want January, 1 == 1 */ + SET(8, p->tm_isdst); #undef SET - if (PyErr_Occurred()) { - Py_XDECREF(v); - return NULL; - } + if (PyErr_Occurred()) { + Py_XDECREF(v); + return NULL; + } - return v; + return v; } static PyObject * structtime_totuple(PyObject *t) { - PyObject *x = NULL; - unsigned int i; - PyObject *v = PyTuple_New(9); - if (v == NULL) - return NULL; - - for (i=0; i<9; i++) { - x = PyStructSequence_GET_ITEM(t, i); - Py_INCREF(x); - PyTuple_SET_ITEM(v, i, x); - } - - if (PyErr_Occurred()) { - Py_XDECREF(v); - return NULL; - } + PyObject *x = NULL; + unsigned int i; + PyObject *v = PyTuple_New(9); + if (v == NULL) + return NULL; + + for (i=0; i<9; i++) { + x = PyStructSequence_GET_ITEM(t, i); + Py_INCREF(x); + PyTuple_SET_ITEM(v, i, x); + } + + if (PyErr_Occurred()) { + Py_XDECREF(v); + return NULL; + } - return v; + return v; } static PyObject * time_convert(double when, struct tm * (*function)(const time_t *)) { - struct tm *p; - time_t whent = _PyTime_DoubleToTimet(when); + struct tm *p; + time_t whent = _PyTime_DoubleToTimet(when); - if (whent == (time_t)-1 && PyErr_Occurred()) - return NULL; - errno = 0; - p = function(&whent); - if (p == NULL) { + if (whent == (time_t)-1 && PyErr_Occurred()) + return NULL; + errno = 0; + p = function(&whent); + if (p == NULL) { #ifdef EINVAL - if (errno == 0) - errno = EINVAL; + if (errno == 0) + errno = EINVAL; #endif - return PyErr_SetFromErrno(PyExc_ValueError); - } - return tmtotuple(p); + return PyErr_SetFromErrno(PyExc_ValueError); + } + return tmtotuple(p); } /* Parse arg tuple that can contain an optional float-or-None value; @@ -307,28 +307,28 @@ static int parse_time_double_args(PyObject *args, char *format, double *pwhen) { - PyObject *ot = NULL; + PyObject *ot = NULL; - if (!PyArg_ParseTuple(args, format, &ot)) - return 0; - if (ot == NULL || ot == Py_None) - *pwhen = floattime(); - else { - double when = PyFloat_AsDouble(ot); - if (PyErr_Occurred()) - return 0; - *pwhen = when; - } - return 1; + if (!PyArg_ParseTuple(args, format, &ot)) + return 0; + if (ot == NULL || ot == Py_None) + *pwhen = floattime(); + else { + double when = PyFloat_AsDouble(ot); + if (PyErr_Occurred()) + return 0; + *pwhen = when; + } + return 1; } static PyObject * time_gmtime(PyObject *self, PyObject *args) { - double when; - if (!parse_time_double_args(args, "|O:gmtime", &when)) - return NULL; - return time_convert(when, gmtime); + double when; + if (!parse_time_double_args(args, "|O:gmtime", &when)) + return NULL; + return time_convert(when, gmtime); } PyDoc_STRVAR(gmtime_doc, @@ -341,15 +341,15 @@ static PyObject * time_localtime(PyObject *self, PyObject *args) { - double when; - if (!parse_time_double_args(args, "|O:localtime", &when)) - return NULL; - return time_convert(when, localtime); + double when; + if (!parse_time_double_args(args, "|O:localtime", &when)) + return NULL; + return time_convert(when, localtime); } PyDoc_STRVAR(localtime_doc, "localtime([seconds]) -> (tm_year,tm_mon,tm_mday,tm_hour,tm_min,\n\ - tm_sec,tm_wday,tm_yday,tm_isdst)\n\ + tm_sec,tm_wday,tm_yday,tm_isdst)\n\ \n\ Convert seconds since the Epoch to a time tuple expressing local time.\n\ When 'seconds' is not passed in, convert the current time instead."); @@ -357,63 +357,63 @@ static int gettmarg(PyObject *args, struct tm *p) { - int y; - PyObject *t = NULL; + int y; + PyObject *t = NULL; - memset((void *) p, '\0', sizeof(struct tm)); + memset((void *) p, '\0', sizeof(struct tm)); - if (PyTuple_Check(args)) { - t = args; - Py_INCREF(t); - } - else if (Py_TYPE(args) == &StructTimeType) { - t = structtime_totuple(args); - } - else { - PyErr_SetString(PyExc_TypeError, - "Tuple or struct_time argument required"); - return 0; - } - - if (t == NULL || !PyArg_ParseTuple(t, "iiiiiiiii", - &y, - &p->tm_mon, - &p->tm_mday, - &p->tm_hour, - &p->tm_min, - &p->tm_sec, - &p->tm_wday, - &p->tm_yday, - &p->tm_isdst)) { - Py_XDECREF(t); - return 0; - } - Py_DECREF(t); - - if (y < 1900) { - PyObject *accept = PyDict_GetItemString(moddict, - "accept2dyear"); - if (accept == NULL || !PyLong_CheckExact(accept) || - !PyObject_IsTrue(accept)) { - PyErr_SetString(PyExc_ValueError, - "year >= 1900 required"); - return 0; - } - if (69 <= y && y <= 99) - y += 1900; - else if (0 <= y && y <= 68) - y += 2000; - else { - PyErr_SetString(PyExc_ValueError, - "year out of range"); - return 0; - } - } - p->tm_year = y - 1900; - p->tm_mon--; - p->tm_wday = (p->tm_wday + 1) % 7; - p->tm_yday--; - return 1; + if (PyTuple_Check(args)) { + t = args; + Py_INCREF(t); + } + else if (Py_TYPE(args) == &StructTimeType) { + t = structtime_totuple(args); + } + else { + PyErr_SetString(PyExc_TypeError, + "Tuple or struct_time argument required"); + return 0; + } + + if (t == NULL || !PyArg_ParseTuple(t, "iiiiiiiii", + &y, + &p->tm_mon, + &p->tm_mday, + &p->tm_hour, + &p->tm_min, + &p->tm_sec, + &p->tm_wday, + &p->tm_yday, + &p->tm_isdst)) { + Py_XDECREF(t); + return 0; + } + Py_DECREF(t); + + if (y < 1900) { + PyObject *accept = PyDict_GetItemString(moddict, + "accept2dyear"); + if (accept == NULL || !PyLong_CheckExact(accept) || + !PyObject_IsTrue(accept)) { + PyErr_SetString(PyExc_ValueError, + "year >= 1900 required"); + return 0; + } + if (69 <= y && y <= 99) + y += 1900; + else if (0 <= y && y <= 68) + y += 2000; + else { + PyErr_SetString(PyExc_ValueError, + "year out of range"); + return 0; + } + } + p->tm_year = y - 1900; + p->tm_mon--; + p->tm_wday = (p->tm_wday + 1) % 7; + p->tm_yday--; + return 1; } #ifdef HAVE_STRFTIME @@ -430,174 +430,174 @@ static PyObject * time_strftime(PyObject *self, PyObject *args) { - PyObject *tup = NULL; - struct tm buf; - const time_char *fmt; - PyObject *format, *tmpfmt; - size_t fmtlen, buflen; - time_char *outbuf = 0; - size_t i; - - memset((void *) &buf, '\0', sizeof(buf)); - - /* Will always expect a unicode string to be passed as format. - Given that there's no str type anymore in py3k this seems safe. - */ - if (!PyArg_ParseTuple(args, "U|O:strftime", &format, &tup)) - return NULL; - - if (tup == NULL) { - time_t tt = time(NULL); - buf = *localtime(&tt); - } else if (!gettmarg(tup, &buf)) - return NULL; - - /* Checks added to make sure strftime() does not crash Python by - indexing blindly into some array for a textual representation - by some bad index (fixes bug #897625). - - Also support values of zero from Python code for arguments in which - that is out of range by forcing that value to the lowest value that - is valid (fixed bug #1520914). - - Valid ranges based on what is allowed in struct tm: - - - tm_year: [0, max(int)] (1) - - tm_mon: [0, 11] (2) - - tm_mday: [1, 31] - - tm_hour: [0, 23] - - tm_min: [0, 59] - - tm_sec: [0, 60] - - tm_wday: [0, 6] (1) - - tm_yday: [0, 365] (2) - - tm_isdst: [-max(int), max(int)] - - (1) gettmarg() handles bounds-checking. - (2) Python's acceptable range is one greater than the range in C, - thus need to check against automatic decrement by gettmarg(). - */ - if (buf.tm_mon == -1) - buf.tm_mon = 0; - else if (buf.tm_mon < 0 || buf.tm_mon > 11) { - PyErr_SetString(PyExc_ValueError, "month out of range"); - return NULL; - } - if (buf.tm_mday == 0) - buf.tm_mday = 1; - else if (buf.tm_mday < 0 || buf.tm_mday > 31) { - PyErr_SetString(PyExc_ValueError, "day of month out of range"); - return NULL; - } - if (buf.tm_hour < 0 || buf.tm_hour > 23) { - PyErr_SetString(PyExc_ValueError, "hour out of range"); - return NULL; - } - if (buf.tm_min < 0 || buf.tm_min > 59) { - PyErr_SetString(PyExc_ValueError, "minute out of range"); - return NULL; - } - if (buf.tm_sec < 0 || buf.tm_sec > 61) { - PyErr_SetString(PyExc_ValueError, "seconds out of range"); - return NULL; - } - /* tm_wday does not need checking of its upper-bound since taking - ``% 7`` in gettmarg() automatically restricts the range. */ - if (buf.tm_wday < 0) { - PyErr_SetString(PyExc_ValueError, "day of week out of range"); - return NULL; - } - if (buf.tm_yday == -1) - buf.tm_yday = 0; - else if (buf.tm_yday < 0 || buf.tm_yday > 365) { - PyErr_SetString(PyExc_ValueError, "day of year out of range"); - return NULL; - } - /* Normalize tm_isdst just in case someone foolishly implements %Z - based on the assumption that tm_isdst falls within the range of - [-1, 1] */ - if (buf.tm_isdst < -1) - buf.tm_isdst = -1; - else if (buf.tm_isdst > 1) - buf.tm_isdst = 1; + PyObject *tup = NULL; + struct tm buf; + const time_char *fmt; + PyObject *format, *tmpfmt; + size_t fmtlen, buflen; + time_char *outbuf = 0; + size_t i; + + memset((void *) &buf, '\0', sizeof(buf)); + + /* Will always expect a unicode string to be passed as format. + Given that there's no str type anymore in py3k this seems safe. + */ + if (!PyArg_ParseTuple(args, "U|O:strftime", &format, &tup)) + return NULL; + + if (tup == NULL) { + time_t tt = time(NULL); + buf = *localtime(&tt); + } else if (!gettmarg(tup, &buf)) + return NULL; + + /* Checks added to make sure strftime() does not crash Python by + indexing blindly into some array for a textual representation + by some bad index (fixes bug #897625). + + Also support values of zero from Python code for arguments in which + that is out of range by forcing that value to the lowest value that + is valid (fixed bug #1520914). + + Valid ranges based on what is allowed in struct tm: + + - tm_year: [0, max(int)] (1) + - tm_mon: [0, 11] (2) + - tm_mday: [1, 31] + - tm_hour: [0, 23] + - tm_min: [0, 59] + - tm_sec: [0, 60] + - tm_wday: [0, 6] (1) + - tm_yday: [0, 365] (2) + - tm_isdst: [-max(int), max(int)] + + (1) gettmarg() handles bounds-checking. + (2) Python's acceptable range is one greater than the range in C, + thus need to check against automatic decrement by gettmarg(). + */ + if (buf.tm_mon == -1) + buf.tm_mon = 0; + else if (buf.tm_mon < 0 || buf.tm_mon > 11) { + PyErr_SetString(PyExc_ValueError, "month out of range"); + return NULL; + } + if (buf.tm_mday == 0) + buf.tm_mday = 1; + else if (buf.tm_mday < 0 || buf.tm_mday > 31) { + PyErr_SetString(PyExc_ValueError, "day of month out of range"); + return NULL; + } + if (buf.tm_hour < 0 || buf.tm_hour > 23) { + PyErr_SetString(PyExc_ValueError, "hour out of range"); + return NULL; + } + if (buf.tm_min < 0 || buf.tm_min > 59) { + PyErr_SetString(PyExc_ValueError, "minute out of range"); + return NULL; + } + if (buf.tm_sec < 0 || buf.tm_sec > 61) { + PyErr_SetString(PyExc_ValueError, "seconds out of range"); + return NULL; + } + /* tm_wday does not need checking of its upper-bound since taking + ``% 7`` in gettmarg() automatically restricts the range. */ + if (buf.tm_wday < 0) { + PyErr_SetString(PyExc_ValueError, "day of week out of range"); + return NULL; + } + if (buf.tm_yday == -1) + buf.tm_yday = 0; + else if (buf.tm_yday < 0 || buf.tm_yday > 365) { + PyErr_SetString(PyExc_ValueError, "day of year out of range"); + return NULL; + } + /* Normalize tm_isdst just in case someone foolishly implements %Z + based on the assumption that tm_isdst falls within the range of + [-1, 1] */ + if (buf.tm_isdst < -1) + buf.tm_isdst = -1; + else if (buf.tm_isdst > 1) + buf.tm_isdst = 1; #ifdef HAVE_WCSFTIME - tmpfmt = PyBytes_FromStringAndSize(NULL, - sizeof(wchar_t) * (PyUnicode_GetSize(format)+1)); - if (!tmpfmt) - return NULL; - /* This assumes that PyUnicode_AsWideChar doesn't do any UTF-16 - expansion. */ - if (PyUnicode_AsWideChar((PyUnicodeObject*)format, - (wchar_t*)PyBytes_AS_STRING(tmpfmt), - PyUnicode_GetSize(format)+1) == (size_t)-1) - /* This shouldn't fail. */ - Py_FatalError("PyUnicode_AsWideChar failed"); - format = tmpfmt; - fmt = (wchar_t*)PyBytes_AS_STRING(format); + tmpfmt = PyBytes_FromStringAndSize(NULL, + sizeof(wchar_t) * (PyUnicode_GetSize(format)+1)); + if (!tmpfmt) + return NULL; + /* This assumes that PyUnicode_AsWideChar doesn't do any UTF-16 + expansion. */ + if (PyUnicode_AsWideChar((PyUnicodeObject*)format, + (wchar_t*)PyBytes_AS_STRING(tmpfmt), + PyUnicode_GetSize(format)+1) == (size_t)-1) + /* This shouldn't fail. */ + Py_FatalError("PyUnicode_AsWideChar failed"); + format = tmpfmt; + fmt = (wchar_t*)PyBytes_AS_STRING(format); #else - /* Convert the unicode string to an ascii one */ - format = PyUnicode_AsEncodedString(format, TZNAME_ENCODING, NULL); - if (format == NULL) - return NULL; - fmt = PyBytes_AS_STRING(format); + /* Convert the unicode string to an ascii one */ + format = PyUnicode_AsEncodedString(format, TZNAME_ENCODING, NULL); + if (format == NULL) + return NULL; + fmt = PyBytes_AS_STRING(format); #endif #if defined(MS_WINDOWS) && defined(HAVE_WCSFTIME) - /* check that the format string contains only valid directives */ - for(outbuf = wcschr(fmt, L'%'); - outbuf != NULL; - outbuf = wcschr(outbuf+2, L'%')) - { - if (outbuf[1]=='#') - ++outbuf; /* not documented by python, */ - if (outbuf[1]=='\0' || - !wcschr(L"aAbBcdfHIjmMpSUwWxXyYzZ%", outbuf[1])) - { - PyErr_SetString(PyExc_ValueError, "Invalid format string"); - return 0; - } - } + /* check that the format string contains only valid directives */ + for(outbuf = wcschr(fmt, L'%'); + outbuf != NULL; + outbuf = wcschr(outbuf+2, L'%')) + { + if (outbuf[1]=='#') + ++outbuf; /* not documented by python, */ + if (outbuf[1]=='\0' || + !wcschr(L"aAbBcdfHIjmMpSUwWxXyYzZ%", outbuf[1])) + { + PyErr_SetString(PyExc_ValueError, "Invalid format string"); + return 0; + } + } #endif - fmtlen = time_strlen(fmt); + fmtlen = time_strlen(fmt); - /* I hate these functions that presume you know how big the output - * will be ahead of time... - */ - for (i = 1024; ; i += i) { - outbuf = (time_char *)PyMem_Malloc(i*sizeof(time_char)); - if (outbuf == NULL) { - Py_DECREF(format); - return PyErr_NoMemory(); - } - buflen = format_time(outbuf, i, fmt, &buf); - if (buflen > 0 || i >= 256 * fmtlen) { - /* If the buffer is 256 times as long as the format, - it's probably not failing for lack of room! - More likely, the format yields an empty result, - e.g. an empty format, or %Z when the timezone - is unknown. */ - PyObject *ret; + /* I hate these functions that presume you know how big the output + * will be ahead of time... + */ + for (i = 1024; ; i += i) { + outbuf = (time_char *)PyMem_Malloc(i*sizeof(time_char)); + if (outbuf == NULL) { + Py_DECREF(format); + return PyErr_NoMemory(); + } + buflen = format_time(outbuf, i, fmt, &buf); + if (buflen > 0 || i >= 256 * fmtlen) { + /* If the buffer is 256 times as long as the format, + it's probably not failing for lack of room! + More likely, the format yields an empty result, + e.g. an empty format, or %Z when the timezone + is unknown. */ + PyObject *ret; #ifdef HAVE_WCSFTIME - ret = PyUnicode_FromWideChar(outbuf, buflen); + ret = PyUnicode_FromWideChar(outbuf, buflen); #else - ret = PyUnicode_Decode(outbuf, buflen, - TZNAME_ENCODING, NULL); + ret = PyUnicode_Decode(outbuf, buflen, + TZNAME_ENCODING, NULL); #endif - PyMem_Free(outbuf); - Py_DECREF(format); - return ret; - } - PyMem_Free(outbuf); + PyMem_Free(outbuf); + Py_DECREF(format); + return ret; + } + PyMem_Free(outbuf); #if defined _MSC_VER && _MSC_VER >= 1400 && defined(__STDC_SECURE_LIB__) - /* VisualStudio .NET 2005 does this properly */ - if (buflen == 0 && errno == EINVAL) { - PyErr_SetString(PyExc_ValueError, "Invalid format string"); - Py_DECREF(format); - return 0; - } + /* VisualStudio .NET 2005 does this properly */ + if (buflen == 0 && errno == EINVAL) { + PyErr_SetString(PyExc_ValueError, "Invalid format string"); + Py_DECREF(format); + return 0; + } #endif - } + } } #undef time_char @@ -614,15 +614,15 @@ static PyObject * time_strptime(PyObject *self, PyObject *args) { - PyObject *strptime_module = PyImport_ImportModuleNoBlock("_strptime"); - PyObject *strptime_result; + PyObject *strptime_module = PyImport_ImportModuleNoBlock("_strptime"); + PyObject *strptime_result; - if (!strptime_module) - return NULL; - strptime_result = PyObject_CallMethod(strptime_module, - "_strptime_time", "O", args); - Py_DECREF(strptime_module); - return strptime_result; + if (!strptime_module) + return NULL; + strptime_result = PyObject_CallMethod(strptime_module, + "_strptime_time", "O", args); + Py_DECREF(strptime_module); + return strptime_result; } PyDoc_STRVAR(strptime_doc, @@ -635,20 +635,20 @@ static PyObject * time_asctime(PyObject *self, PyObject *args) { - PyObject *tup = NULL; - struct tm buf; - char *p; - if (!PyArg_UnpackTuple(args, "asctime", 0, 1, &tup)) - return NULL; - if (tup == NULL) { - time_t tt = time(NULL); - buf = *localtime(&tt); - } else if (!gettmarg(tup, &buf)) - return NULL; - p = asctime(&buf); - if (p[24] == '\n') - p[24] = '\0'; - return PyUnicode_FromString(p); + PyObject *tup = NULL; + struct tm buf; + char *p; + if (!PyArg_UnpackTuple(args, "asctime", 0, 1, &tup)) + return NULL; + if (tup == NULL) { + time_t tt = time(NULL); + buf = *localtime(&tt); + } else if (!gettmarg(tup, &buf)) + return NULL; + p = asctime(&buf); + if (p[24] == '\n') + p[24] = '\0'; + return PyUnicode_FromString(p); } PyDoc_STRVAR(asctime_doc, @@ -661,30 +661,30 @@ static PyObject * time_ctime(PyObject *self, PyObject *args) { - PyObject *ot = NULL; - time_t tt; - char *p; - - if (!PyArg_UnpackTuple(args, "ctime", 0, 1, &ot)) - return NULL; - if (ot == NULL || ot == Py_None) - tt = time(NULL); - else { - double dt = PyFloat_AsDouble(ot); - if (PyErr_Occurred()) - return NULL; - tt = _PyTime_DoubleToTimet(dt); - if (tt == (time_t)-1 && PyErr_Occurred()) - return NULL; - } - p = ctime(&tt); - if (p == NULL) { - PyErr_SetString(PyExc_ValueError, "unconvertible time"); - return NULL; - } - if (p[24] == '\n') - p[24] = '\0'; - return PyUnicode_FromString(p); + PyObject *ot = NULL; + time_t tt; + char *p; + + if (!PyArg_UnpackTuple(args, "ctime", 0, 1, &ot)) + return NULL; + if (ot == NULL || ot == Py_None) + tt = time(NULL); + else { + double dt = PyFloat_AsDouble(ot); + if (PyErr_Occurred()) + return NULL; + tt = _PyTime_DoubleToTimet(dt); + if (tt == (time_t)-1 && PyErr_Occurred()) + return NULL; + } + p = ctime(&tt); + if (p == NULL) { + PyErr_SetString(PyExc_ValueError, "unconvertible time"); + return NULL; + } + if (p[24] == '\n') + p[24] = '\0'; + return PyUnicode_FromString(p); } PyDoc_STRVAR(ctime_doc, @@ -698,17 +698,17 @@ static PyObject * time_mktime(PyObject *self, PyObject *tup) { - struct tm buf; - time_t tt; - if (!gettmarg(tup, &buf)) - return NULL; - tt = mktime(&buf); - if (tt == (time_t)(-1)) { - PyErr_SetString(PyExc_OverflowError, - "mktime argument out of range"); - return NULL; - } - return PyFloat_FromDouble((double)tt); + struct tm buf; + time_t tt; + if (!gettmarg(tup, &buf)) + return NULL; + tt = mktime(&buf); + if (tt == (time_t)(-1)) { + PyErr_SetString(PyExc_OverflowError, + "mktime argument out of range"); + return NULL; + } + return PyFloat_FromDouble((double)tt); } PyDoc_STRVAR(mktime_doc, @@ -723,21 +723,21 @@ static PyObject * time_tzset(PyObject *self, PyObject *unused) { - PyObject* m; + PyObject* m; - m = PyImport_ImportModuleNoBlock("time"); - if (m == NULL) { - return NULL; - } + m = PyImport_ImportModuleNoBlock("time"); + if (m == NULL) { + return NULL; + } - tzset(); + tzset(); - /* Reset timezone, altzone, daylight and tzname */ - PyInit_timezone(m); - Py_DECREF(m); + /* Reset timezone, altzone, daylight and tzname */ + PyInit_timezone(m); + Py_DECREF(m); - Py_INCREF(Py_None); - return Py_None; + Py_INCREF(Py_None); + return Py_None; } PyDoc_STRVAR(tzset_doc, @@ -757,115 +757,115 @@ static void PyInit_timezone(PyObject *m) { /* This code moved from PyInit_time wholesale to allow calling it from - time_tzset. In the future, some parts of it can be moved back - (for platforms that don't HAVE_WORKING_TZSET, when we know what they - are), and the extraneous calls to tzset(3) should be removed. - I haven't done this yet, as I don't want to change this code as - little as possible when introducing the time.tzset and time.tzsetwall - methods. This should simply be a method of doing the following once, - at the top of this function and removing the call to tzset() from - time_tzset(): - - #ifdef HAVE_TZSET - tzset() - #endif + time_tzset. In the future, some parts of it can be moved back + (for platforms that don't HAVE_WORKING_TZSET, when we know what they + are), and the extraneous calls to tzset(3) should be removed. + I haven't done this yet, as I don't want to change this code as + little as possible when introducing the time.tzset and time.tzsetwall + methods. This should simply be a method of doing the following once, + at the top of this function and removing the call to tzset() from + time_tzset(): + + #ifdef HAVE_TZSET + tzset() + #endif - And I'm lazy and hate C so nyer. + And I'm lazy and hate C so nyer. */ #if defined(HAVE_TZNAME) && !defined(__GLIBC__) && !defined(__CYGWIN__) - PyObject *otz0, *otz1; - tzset(); + PyObject *otz0, *otz1; + tzset(); #ifdef PYOS_OS2 - PyModule_AddIntConstant(m, "timezone", _timezone); + PyModule_AddIntConstant(m, "timezone", _timezone); #else /* !PYOS_OS2 */ - PyModule_AddIntConstant(m, "timezone", timezone); + PyModule_AddIntConstant(m, "timezone", timezone); #endif /* PYOS_OS2 */ #ifdef HAVE_ALTZONE - PyModule_AddIntConstant(m, "altzone", altzone); + PyModule_AddIntConstant(m, "altzone", altzone); #else #ifdef PYOS_OS2 - PyModule_AddIntConstant(m, "altzone", _timezone-3600); + PyModule_AddIntConstant(m, "altzone", _timezone-3600); #else /* !PYOS_OS2 */ - PyModule_AddIntConstant(m, "altzone", timezone-3600); + PyModule_AddIntConstant(m, "altzone", timezone-3600); #endif /* PYOS_OS2 */ #endif - PyModule_AddIntConstant(m, "daylight", daylight); - otz0 = PyUnicode_Decode(tzname[0], strlen(tzname[0]), TZNAME_ENCODING, NULL); - otz1 = PyUnicode_Decode(tzname[1], strlen(tzname[1]), TZNAME_ENCODING, NULL); - PyModule_AddObject(m, "tzname", Py_BuildValue("(NN)", otz0, otz1)); + PyModule_AddIntConstant(m, "daylight", daylight); + otz0 = PyUnicode_Decode(tzname[0], strlen(tzname[0]), TZNAME_ENCODING, NULL); + otz1 = PyUnicode_Decode(tzname[1], strlen(tzname[1]), TZNAME_ENCODING, NULL); + PyModule_AddObject(m, "tzname", Py_BuildValue("(NN)", otz0, otz1)); #else /* !HAVE_TZNAME || __GLIBC__ || __CYGWIN__*/ #ifdef HAVE_STRUCT_TM_TM_ZONE - { + { #define YEAR ((time_t)((365 * 24 + 6) * 3600)) - time_t t; - struct tm *p; - long janzone, julyzone; - char janname[10], julyname[10]; - t = (time((time_t *)0) / YEAR) * YEAR; - p = localtime(&t); - janzone = -p->tm_gmtoff; - strncpy(janname, p->tm_zone ? p->tm_zone : " ", 9); - janname[9] = '\0'; - t += YEAR/2; - p = localtime(&t); - julyzone = -p->tm_gmtoff; - strncpy(julyname, p->tm_zone ? p->tm_zone : " ", 9); - julyname[9] = '\0'; - - if( janzone < julyzone ) { - /* DST is reversed in the southern hemisphere */ - PyModule_AddIntConstant(m, "timezone", julyzone); - PyModule_AddIntConstant(m, "altzone", janzone); - PyModule_AddIntConstant(m, "daylight", - janzone != julyzone); - PyModule_AddObject(m, "tzname", - Py_BuildValue("(zz)", - julyname, janname)); - } else { - PyModule_AddIntConstant(m, "timezone", janzone); - PyModule_AddIntConstant(m, "altzone", julyzone); - PyModule_AddIntConstant(m, "daylight", - janzone != julyzone); - PyModule_AddObject(m, "tzname", - Py_BuildValue("(zz)", - janname, julyname)); - } - } + time_t t; + struct tm *p; + long janzone, julyzone; + char janname[10], julyname[10]; + t = (time((time_t *)0) / YEAR) * YEAR; + p = localtime(&t); + janzone = -p->tm_gmtoff; + strncpy(janname, p->tm_zone ? p->tm_zone : " ", 9); + janname[9] = '\0'; + t += YEAR/2; + p = localtime(&t); + julyzone = -p->tm_gmtoff; + strncpy(julyname, p->tm_zone ? p->tm_zone : " ", 9); + julyname[9] = '\0'; + + if( janzone < julyzone ) { + /* DST is reversed in the southern hemisphere */ + PyModule_AddIntConstant(m, "timezone", julyzone); + PyModule_AddIntConstant(m, "altzone", janzone); + PyModule_AddIntConstant(m, "daylight", + janzone != julyzone); + PyModule_AddObject(m, "tzname", + Py_BuildValue("(zz)", + julyname, janname)); + } else { + PyModule_AddIntConstant(m, "timezone", janzone); + PyModule_AddIntConstant(m, "altzone", julyzone); + PyModule_AddIntConstant(m, "daylight", + janzone != julyzone); + PyModule_AddObject(m, "tzname", + Py_BuildValue("(zz)", + janname, julyname)); + } + } #else #endif /* HAVE_STRUCT_TM_TM_ZONE */ #ifdef __CYGWIN__ - tzset(); - PyModule_AddIntConstant(m, "timezone", _timezone); - PyModule_AddIntConstant(m, "altzone", _timezone-3600); - PyModule_AddIntConstant(m, "daylight", _daylight); - PyModule_AddObject(m, "tzname", - Py_BuildValue("(zz)", _tzname[0], _tzname[1])); + tzset(); + PyModule_AddIntConstant(m, "timezone", _timezone); + PyModule_AddIntConstant(m, "altzone", _timezone-3600); + PyModule_AddIntConstant(m, "daylight", _daylight); + PyModule_AddObject(m, "tzname", + Py_BuildValue("(zz)", _tzname[0], _tzname[1])); #endif /* __CYGWIN__ */ #endif /* !HAVE_TZNAME || __GLIBC__ || __CYGWIN__*/ } static PyMethodDef time_methods[] = { - {"time", time_time, METH_NOARGS, time_doc}, + {"time", time_time, METH_NOARGS, time_doc}, #ifdef HAVE_CLOCK - {"clock", time_clock, METH_NOARGS, clock_doc}, + {"clock", time_clock, METH_NOARGS, clock_doc}, #endif - {"sleep", time_sleep, METH_VARARGS, sleep_doc}, - {"gmtime", time_gmtime, METH_VARARGS, gmtime_doc}, - {"localtime", time_localtime, METH_VARARGS, localtime_doc}, - {"asctime", time_asctime, METH_VARARGS, asctime_doc}, - {"ctime", time_ctime, METH_VARARGS, ctime_doc}, + {"sleep", time_sleep, METH_VARARGS, sleep_doc}, + {"gmtime", time_gmtime, METH_VARARGS, gmtime_doc}, + {"localtime", time_localtime, METH_VARARGS, localtime_doc}, + {"asctime", time_asctime, METH_VARARGS, asctime_doc}, + {"ctime", time_ctime, METH_VARARGS, ctime_doc}, #ifdef HAVE_MKTIME - {"mktime", time_mktime, METH_O, mktime_doc}, + {"mktime", time_mktime, METH_O, mktime_doc}, #endif #ifdef HAVE_STRFTIME - {"strftime", time_strftime, METH_VARARGS, strftime_doc}, + {"strftime", time_strftime, METH_VARARGS, strftime_doc}, #endif - {"strptime", time_strptime, METH_VARARGS, strptime_doc}, + {"strptime", time_strptime, METH_VARARGS, strptime_doc}, #ifdef HAVE_WORKING_TZSET - {"tzset", time_tzset, METH_NOARGS, tzset_doc}, + {"tzset", time_tzset, METH_NOARGS, tzset_doc}, #endif - {NULL, NULL} /* sentinel */ + {NULL, NULL} /* sentinel */ }; @@ -917,53 +917,53 @@ static struct PyModuleDef timemodule = { - PyModuleDef_HEAD_INIT, - "time", - module_doc, - -1, - time_methods, - NULL, - NULL, - NULL, - NULL + PyModuleDef_HEAD_INIT, + "time", + module_doc, + -1, + time_methods, + NULL, + NULL, + NULL, + NULL }; PyMODINIT_FUNC PyInit_time(void) { - PyObject *m; - char *p; - m = PyModule_Create(&timemodule); - if (m == NULL) - return NULL; - - /* Accept 2-digit dates unless PYTHONY2K is set and non-empty */ - p = Py_GETENV("PYTHONY2K"); - PyModule_AddIntConstant(m, "accept2dyear", (long) (!p || !*p)); - /* Squirrel away the module's dictionary for the y2k check */ - moddict = PyModule_GetDict(m); - Py_INCREF(moddict); + PyObject *m; + char *p; + m = PyModule_Create(&timemodule); + if (m == NULL) + return NULL; + + /* Accept 2-digit dates unless PYTHONY2K is set and non-empty */ + p = Py_GETENV("PYTHONY2K"); + PyModule_AddIntConstant(m, "accept2dyear", (long) (!p || !*p)); + /* Squirrel away the module's dictionary for the y2k check */ + moddict = PyModule_GetDict(m); + Py_INCREF(moddict); - /* Set, or reset, module variables like time.timezone */ - PyInit_timezone(m); + /* Set, or reset, module variables like time.timezone */ + PyInit_timezone(m); #ifdef MS_WINDOWS - /* Helper to allow interrupts for Windows. - If Ctrl+C event delivered while not sleeping - it will be ignored. - */ - main_thread = PyThread_get_thread_ident(); - hInterruptEvent = CreateEvent(NULL, TRUE, FALSE, NULL); - SetConsoleCtrlHandler( PyCtrlHandler, TRUE); + /* Helper to allow interrupts for Windows. + If Ctrl+C event delivered while not sleeping + it will be ignored. + */ + main_thread = PyThread_get_thread_ident(); + hInterruptEvent = CreateEvent(NULL, TRUE, FALSE, NULL); + SetConsoleCtrlHandler( PyCtrlHandler, TRUE); #endif /* MS_WINDOWS */ - if (!initialized) { - PyStructSequence_InitType(&StructTimeType, - &struct_time_type_desc); - } - Py_INCREF(&StructTimeType); - PyModule_AddObject(m, "struct_time", (PyObject*) &StructTimeType); - initialized = 1; - return m; + if (!initialized) { + PyStructSequence_InitType(&StructTimeType, + &struct_time_type_desc); + } + Py_INCREF(&StructTimeType); + PyModule_AddObject(m, "struct_time", (PyObject*) &StructTimeType); + initialized = 1; + return m; } @@ -972,38 +972,38 @@ static double floattime(void) { - /* There are three ways to get the time: - (1) gettimeofday() -- resolution in microseconds - (2) ftime() -- resolution in milliseconds - (3) time() -- resolution in seconds - In all cases the return value is a float in seconds. - Since on some systems (e.g. SCO ODT 3.0) gettimeofday() may - fail, so we fall back on ftime() or time(). - Note: clock resolution does not imply clock accuracy! */ + /* There are three ways to get the time: + (1) gettimeofday() -- resolution in microseconds + (2) ftime() -- resolution in milliseconds + (3) time() -- resolution in seconds + In all cases the return value is a float in seconds. + Since on some systems (e.g. SCO ODT 3.0) gettimeofday() may + fail, so we fall back on ftime() or time(). + Note: clock resolution does not imply clock accuracy! */ #ifdef HAVE_GETTIMEOFDAY - { - struct timeval t; + { + struct timeval t; #ifdef GETTIMEOFDAY_NO_TZ - if (gettimeofday(&t) == 0) - return (double)t.tv_sec + t.tv_usec*0.000001; + if (gettimeofday(&t) == 0) + return (double)t.tv_sec + t.tv_usec*0.000001; #else /* !GETTIMEOFDAY_NO_TZ */ - if (gettimeofday(&t, (struct timezone *)NULL) == 0) - return (double)t.tv_sec + t.tv_usec*0.000001; + if (gettimeofday(&t, (struct timezone *)NULL) == 0) + return (double)t.tv_sec + t.tv_usec*0.000001; #endif /* !GETTIMEOFDAY_NO_TZ */ - } + } #endif /* !HAVE_GETTIMEOFDAY */ - { + { #if defined(HAVE_FTIME) - struct timeb t; - ftime(&t); - return (double)t.time + (double)t.millitm * (double)0.001; + struct timeb t; + ftime(&t); + return (double)t.time + (double)t.millitm * (double)0.001; #else /* !HAVE_FTIME */ - time_t secs; - time(&secs); - return (double)secs; + time_t secs; + time(&secs); + return (double)secs; #endif /* !HAVE_FTIME */ - } + } } @@ -1016,80 +1016,80 @@ { /* XXX Should test for MS_WINDOWS first! */ #if defined(HAVE_SELECT) && !defined(__EMX__) - struct timeval t; - double frac; - frac = fmod(secs, 1.0); - secs = floor(secs); - t.tv_sec = (long)secs; - t.tv_usec = (long)(frac*1000000.0); - Py_BEGIN_ALLOW_THREADS - if (select(0, (fd_set *)0, (fd_set *)0, (fd_set *)0, &t) != 0) { + struct timeval t; + double frac; + frac = fmod(secs, 1.0); + secs = floor(secs); + t.tv_sec = (long)secs; + t.tv_usec = (long)(frac*1000000.0); + Py_BEGIN_ALLOW_THREADS + if (select(0, (fd_set *)0, (fd_set *)0, (fd_set *)0, &t) != 0) { #ifdef EINTR - if (errno != EINTR) { + if (errno != EINTR) { #else - if (1) { + if (1) { #endif - Py_BLOCK_THREADS - PyErr_SetFromErrno(PyExc_IOError); - return -1; - } - } - Py_END_ALLOW_THREADS + Py_BLOCK_THREADS + PyErr_SetFromErrno(PyExc_IOError); + return -1; + } + } + Py_END_ALLOW_THREADS #elif defined(__WATCOMC__) && !defined(__QNX__) - /* XXX Can't interrupt this sleep */ - Py_BEGIN_ALLOW_THREADS - delay((int)(secs * 1000 + 0.5)); /* delay() uses milliseconds */ - Py_END_ALLOW_THREADS + /* XXX Can't interrupt this sleep */ + Py_BEGIN_ALLOW_THREADS + delay((int)(secs * 1000 + 0.5)); /* delay() uses milliseconds */ + Py_END_ALLOW_THREADS #elif defined(MS_WINDOWS) - { - double millisecs = secs * 1000.0; - unsigned long ul_millis; - - if (millisecs > (double)ULONG_MAX) { - PyErr_SetString(PyExc_OverflowError, - "sleep length is too large"); - return -1; - } - Py_BEGIN_ALLOW_THREADS - /* Allow sleep(0) to maintain win32 semantics, and as decreed - * by Guido, only the main thread can be interrupted. - */ - ul_millis = (unsigned long)millisecs; - if (ul_millis == 0 || - main_thread != PyThread_get_thread_ident()) - Sleep(ul_millis); - else { - DWORD rc; - ResetEvent(hInterruptEvent); - rc = WaitForSingleObject(hInterruptEvent, ul_millis); - if (rc == WAIT_OBJECT_0) { - /* Yield to make sure real Python signal - * handler called. - */ - Sleep(1); - Py_BLOCK_THREADS - errno = EINTR; - PyErr_SetFromErrno(PyExc_IOError); - return -1; - } - } - Py_END_ALLOW_THREADS - } + { + double millisecs = secs * 1000.0; + unsigned long ul_millis; + + if (millisecs > (double)ULONG_MAX) { + PyErr_SetString(PyExc_OverflowError, + "sleep length is too large"); + return -1; + } + Py_BEGIN_ALLOW_THREADS + /* Allow sleep(0) to maintain win32 semantics, and as decreed + * by Guido, only the main thread can be interrupted. + */ + ul_millis = (unsigned long)millisecs; + if (ul_millis == 0 || + main_thread != PyThread_get_thread_ident()) + Sleep(ul_millis); + else { + DWORD rc; + ResetEvent(hInterruptEvent); + rc = WaitForSingleObject(hInterruptEvent, ul_millis); + if (rc == WAIT_OBJECT_0) { + /* Yield to make sure real Python signal + * handler called. + */ + Sleep(1); + Py_BLOCK_THREADS + errno = EINTR; + PyErr_SetFromErrno(PyExc_IOError); + return -1; + } + } + Py_END_ALLOW_THREADS + } #elif defined(PYOS_OS2) - /* This Sleep *IS* Interruptable by Exceptions */ - Py_BEGIN_ALLOW_THREADS - if (DosSleep(secs * 1000) != NO_ERROR) { - Py_BLOCK_THREADS - PyErr_SetFromErrno(PyExc_IOError); - return -1; - } - Py_END_ALLOW_THREADS + /* This Sleep *IS* Interruptable by Exceptions */ + Py_BEGIN_ALLOW_THREADS + if (DosSleep(secs * 1000) != NO_ERROR) { + Py_BLOCK_THREADS + PyErr_SetFromErrno(PyExc_IOError); + return -1; + } + Py_END_ALLOW_THREADS #else - /* XXX Can't interrupt this sleep */ - Py_BEGIN_ALLOW_THREADS - sleep((int)secs); - Py_END_ALLOW_THREADS + /* XXX Can't interrupt this sleep */ + Py_BEGIN_ALLOW_THREADS + sleep((int)secs); + Py_END_ALLOW_THREADS #endif - return 0; + return 0; } Modified: python/branches/py3k-jit/Modules/tkappinit.c ============================================================================== --- python/branches/py3k-jit/Modules/tkappinit.c (original) +++ python/branches/py3k-jit/Modules/tkappinit.c Mon May 10 23:55:43 2010 @@ -26,154 +26,154 @@ int Tcl_AppInit(Tcl_Interp *interp) { - Tk_Window main_window; - const char *_tkinter_skip_tk_init; + Tk_Window main_window; + const char *_tkinter_skip_tk_init; #ifdef TKINTER_PROTECT_LOADTK - const char *_tkinter_tk_failed; + const char *_tkinter_tk_failed; #endif #ifdef TK_AQUA #ifndef MAX_PATH_LEN #define MAX_PATH_LEN 1024 #endif - char tclLibPath[MAX_PATH_LEN], tkLibPath[MAX_PATH_LEN]; - Tcl_Obj* pathPtr; + char tclLibPath[MAX_PATH_LEN], tkLibPath[MAX_PATH_LEN]; + Tcl_Obj* pathPtr; - /* pre- Tcl_Init code copied from tkMacOSXAppInit.c */ - Tk_MacOSXOpenBundleResources (interp, "com.tcltk.tcllibrary", - tclLibPath, MAX_PATH_LEN, 0); - - if (tclLibPath[0] != '\0') { - Tcl_SetVar(interp, "tcl_library", tclLibPath, TCL_GLOBAL_ONLY); - Tcl_SetVar(interp, "tclDefaultLibrary", tclLibPath, TCL_GLOBAL_ONLY); - Tcl_SetVar(interp, "tcl_pkgPath", tclLibPath, TCL_GLOBAL_ONLY); - } - - if (tclLibPath[0] != '\0') { - Tcl_SetVar(interp, "tcl_library", tclLibPath, TCL_GLOBAL_ONLY); - Tcl_SetVar(interp, "tclDefaultLibrary", tclLibPath, TCL_GLOBAL_ONLY); - Tcl_SetVar(interp, "tcl_pkgPath", tclLibPath, TCL_GLOBAL_ONLY); - } + /* pre- Tcl_Init code copied from tkMacOSXAppInit.c */ + Tk_MacOSXOpenBundleResources (interp, "com.tcltk.tcllibrary", + tclLibPath, MAX_PATH_LEN, 0); + + if (tclLibPath[0] != '\0') { + Tcl_SetVar(interp, "tcl_library", tclLibPath, TCL_GLOBAL_ONLY); + Tcl_SetVar(interp, "tclDefaultLibrary", tclLibPath, TCL_GLOBAL_ONLY); + Tcl_SetVar(interp, "tcl_pkgPath", tclLibPath, TCL_GLOBAL_ONLY); + } + + if (tclLibPath[0] != '\0') { + Tcl_SetVar(interp, "tcl_library", tclLibPath, TCL_GLOBAL_ONLY); + Tcl_SetVar(interp, "tclDefaultLibrary", tclLibPath, TCL_GLOBAL_ONLY); + Tcl_SetVar(interp, "tcl_pkgPath", tclLibPath, TCL_GLOBAL_ONLY); + } #endif - if (Tcl_Init (interp) == TCL_ERROR) - return TCL_ERROR; + if (Tcl_Init (interp) == TCL_ERROR) + return TCL_ERROR; #ifdef TK_AQUA - /* pre- Tk_Init code copied from tkMacOSXAppInit.c */ - Tk_MacOSXOpenBundleResources (interp, "com.tcltk.tklibrary", - tkLibPath, MAX_PATH_LEN, 1); - - if (tclLibPath[0] != '\0') { - pathPtr = Tcl_NewStringObj(tclLibPath, -1); - } else { - Tcl_Obj *pathPtr = TclGetLibraryPath(); - } - - if (tkLibPath[0] != '\0') { - Tcl_Obj *objPtr; - - Tcl_SetVar(interp, "tk_library", tkLibPath, TCL_GLOBAL_ONLY); - objPtr = Tcl_NewStringObj(tkLibPath, -1); - Tcl_ListObjAppendElement(NULL, pathPtr, objPtr); - } + /* pre- Tk_Init code copied from tkMacOSXAppInit.c */ + Tk_MacOSXOpenBundleResources (interp, "com.tcltk.tklibrary", + tkLibPath, MAX_PATH_LEN, 1); + + if (tclLibPath[0] != '\0') { + pathPtr = Tcl_NewStringObj(tclLibPath, -1); + } else { + Tcl_Obj *pathPtr = TclGetLibraryPath(); + } + + if (tkLibPath[0] != '\0') { + Tcl_Obj *objPtr; + + Tcl_SetVar(interp, "tk_library", tkLibPath, TCL_GLOBAL_ONLY); + objPtr = Tcl_NewStringObj(tkLibPath, -1); + Tcl_ListObjAppendElement(NULL, pathPtr, objPtr); + } - TclSetLibraryPath(pathPtr); + TclSetLibraryPath(pathPtr); #endif #ifdef WITH_XXX - /* Initialize modules that don't require Tk */ + /* Initialize modules that don't require Tk */ #endif - _tkinter_skip_tk_init = Tcl_GetVar(interp, - "_tkinter_skip_tk_init", TCL_GLOBAL_ONLY); - if (_tkinter_skip_tk_init != NULL && - strcmp(_tkinter_skip_tk_init, "1") == 0) { - return TCL_OK; - } + _tkinter_skip_tk_init = Tcl_GetVar(interp, + "_tkinter_skip_tk_init", TCL_GLOBAL_ONLY); + if (_tkinter_skip_tk_init != NULL && + strcmp(_tkinter_skip_tk_init, "1") == 0) { + return TCL_OK; + } #ifdef TKINTER_PROTECT_LOADTK - _tkinter_tk_failed = Tcl_GetVar(interp, - "_tkinter_tk_failed", TCL_GLOBAL_ONLY); + _tkinter_tk_failed = Tcl_GetVar(interp, + "_tkinter_tk_failed", TCL_GLOBAL_ONLY); - if (tk_load_failed || ( - _tkinter_tk_failed != NULL && - strcmp(_tkinter_tk_failed, "1") == 0)) { - Tcl_SetResult(interp, TKINTER_LOADTK_ERRMSG, TCL_STATIC); - return TCL_ERROR; - } + if (tk_load_failed || ( + _tkinter_tk_failed != NULL && + strcmp(_tkinter_tk_failed, "1") == 0)) { + Tcl_SetResult(interp, TKINTER_LOADTK_ERRMSG, TCL_STATIC); + return TCL_ERROR; + } #endif - if (Tk_Init(interp) == TCL_ERROR) { + if (Tk_Init(interp) == TCL_ERROR) { #ifdef TKINTER_PROTECT_LOADTK - tk_load_failed = 1; - Tcl_SetVar(interp, "_tkinter_tk_failed", "1", TCL_GLOBAL_ONLY); + tk_load_failed = 1; + Tcl_SetVar(interp, "_tkinter_tk_failed", "1", TCL_GLOBAL_ONLY); #endif - return TCL_ERROR; - } + return TCL_ERROR; + } - main_window = Tk_MainWindow(interp); + main_window = Tk_MainWindow(interp); #ifdef TK_AQUA - TkMacOSXInitAppleEvents(interp); - TkMacOSXInitMenus(interp); + TkMacOSXInitAppleEvents(interp); + TkMacOSXInitMenus(interp); #endif - + #ifdef WITH_MOREBUTTONS - { - extern Tcl_CmdProc studButtonCmd; - extern Tcl_CmdProc triButtonCmd; - - Tcl_CreateCommand(interp, "studbutton", studButtonCmd, - (ClientData) main_window, NULL); - Tcl_CreateCommand(interp, "tributton", triButtonCmd, - (ClientData) main_window, NULL); - } + { + extern Tcl_CmdProc studButtonCmd; + extern Tcl_CmdProc triButtonCmd; + + Tcl_CreateCommand(interp, "studbutton", studButtonCmd, + (ClientData) main_window, NULL); + Tcl_CreateCommand(interp, "tributton", triButtonCmd, + (ClientData) main_window, NULL); + } #endif #ifdef WITH_PIL /* 0.2b5 and later -- not yet released as of May 14 */ - { - extern void TkImaging_Init(Tcl_Interp *); - TkImaging_Init(interp); - /* XXX TkImaging_Init() doesn't have the right return type */ - /*Tcl_StaticPackage(interp, "Imaging", TkImaging_Init, NULL);*/ - } + { + extern void TkImaging_Init(Tcl_Interp *); + TkImaging_Init(interp); + /* XXX TkImaging_Init() doesn't have the right return type */ + /*Tcl_StaticPackage(interp, "Imaging", TkImaging_Init, NULL);*/ + } #endif #ifdef WITH_PIL_OLD /* 0.2b4 and earlier */ - { - extern void TkImaging_Init(void); - /* XXX TkImaging_Init() doesn't have the right prototype */ - /*Tcl_StaticPackage(interp, "Imaging", TkImaging_Init, NULL);*/ - } + { + extern void TkImaging_Init(void); + /* XXX TkImaging_Init() doesn't have the right prototype */ + /*Tcl_StaticPackage(interp, "Imaging", TkImaging_Init, NULL);*/ + } #endif #ifdef WITH_TIX - { - extern int Tix_Init(Tcl_Interp *interp); - extern int Tix_SafeInit(Tcl_Interp *interp); - Tcl_StaticPackage(NULL, "Tix", Tix_Init, Tix_SafeInit); - } + { + extern int Tix_Init(Tcl_Interp *interp); + extern int Tix_SafeInit(Tcl_Interp *interp); + Tcl_StaticPackage(NULL, "Tix", Tix_Init, Tix_SafeInit); + } #endif #ifdef WITH_BLT - { - extern int Blt_Init(Tcl_Interp *); - extern int Blt_SafeInit(Tcl_Interp *); - Tcl_StaticPackage(NULL, "Blt", Blt_Init, Blt_SafeInit); - } + { + extern int Blt_Init(Tcl_Interp *); + extern int Blt_SafeInit(Tcl_Interp *); + Tcl_StaticPackage(NULL, "Blt", Blt_Init, Blt_SafeInit); + } #endif #ifdef WITH_TOGL - { - /* XXX I've heard rumors that this doesn't work */ - extern int Togl_Init(Tcl_Interp *); - /* XXX Is there no Togl_SafeInit? */ - Tcl_StaticPackage(NULL, "Togl", Togl_Init, NULL); - } + { + /* XXX I've heard rumors that this doesn't work */ + extern int Togl_Init(Tcl_Interp *); + /* XXX Is there no Togl_SafeInit? */ + Tcl_StaticPackage(NULL, "Togl", Togl_Init, NULL); + } #endif #ifdef WITH_XXX #endif - return TCL_OK; + return TCL_OK; } Modified: python/branches/py3k-jit/Modules/unicodedata.c ============================================================================== --- python/branches/py3k-jit/Modules/unicodedata.c (original) +++ python/branches/py3k-jit/Modules/unicodedata.c Mon May 10 23:55:43 2010 @@ -19,14 +19,14 @@ /* character properties */ typedef struct { - const unsigned char category; /* index into - _PyUnicode_CategoryNames */ - const unsigned char combining; /* combining class value 0 - 255 */ - const unsigned char bidirectional; /* index into - _PyUnicode_BidirectionalNames */ - const unsigned char mirrored; /* true if mirrored in bidir mode */ - const unsigned char east_asian_width; /* index into - _PyUnicode_EastAsianWidth */ + const unsigned char category; /* index into + _PyUnicode_CategoryNames */ + const unsigned char combining; /* combining class value 0 - 255 */ + const unsigned char bidirectional; /* index into + _PyUnicode_BidirectionalNames */ + const unsigned char mirrored; /* true if mirrored in bidir mode */ + const unsigned char east_asian_width; /* index into + _PyUnicode_EastAsianWidth */ const unsigned char normalization_quick_check; /* see is_normalized() */ } _PyUnicode_DatabaseRecord; @@ -67,7 +67,7 @@ #define get_old_record(self, v) ((((PreviousDBVersion*)self)->getrecord)(v)) static PyMemberDef DB_members[] = { - {"unidata_version", T_STRING, offsetof(PreviousDBVersion, name), READONLY}, + {"unidata_version", T_STRING, offsetof(PreviousDBVersion, name), READONLY}, {NULL} }; @@ -79,14 +79,14 @@ new_previous_version(const char*name, const change_record* (*getrecord)(Py_UCS4), Py_UCS4 (*normalization)(Py_UCS4)) { - PreviousDBVersion *self; - self = PyObject_New(PreviousDBVersion, &UCD_Type); - if (self == NULL) - return NULL; - self->name = name; - self->getrecord = getrecord; + PreviousDBVersion *self; + self = PyObject_New(PreviousDBVersion, &UCD_Type); + if (self == NULL) + return NULL; + self->name = name; + self->getrecord = getrecord; self->normalization = normalization; - return (PyObject*)self; + return (PyObject*)self; } @@ -95,12 +95,12 @@ Py_UNICODE *v = PyUnicode_AS_UNICODE(obj); if (PyUnicode_GET_SIZE(obj) == 1) - return *v; + return *v; #ifndef Py_UNICODE_WIDE else if ((PyUnicode_GET_SIZE(obj) == 2) && (0xD800 <= v[0] && v[0] <= 0xDBFF) && (0xDC00 <= v[1] && v[1] <= 0xDFFF)) - return (((v[0] & 0x3FF)<<10) | (v[1] & 0x3FF)) + 0x10000; + return (((v[0] & 0x3FF)<<10) | (v[1] & 0x3FF)) + 0x10000; #endif PyErr_SetString(PyExc_TypeError, "need a single Unicode character as parameter"); @@ -137,7 +137,7 @@ /* unassigned */ have_old = 1; rc = -1; - } + } else if (old->decimal_changed != 0xFF) { have_old = 1; rc = old->decimal_changed; @@ -147,15 +147,15 @@ if (!have_old) rc = Py_UNICODE_TODECIMAL(c); if (rc < 0) { - if (defobj == NULL) { - PyErr_SetString(PyExc_ValueError, - "not a decimal"); + if (defobj == NULL) { + PyErr_SetString(PyExc_ValueError, + "not a decimal"); return NULL; - } - else { - Py_INCREF(defobj); - return defobj; - } + } + else { + Py_INCREF(defobj); + return defobj; + } } return PyLong_FromLong(rc); } @@ -182,14 +182,14 @@ return NULL; rc = Py_UNICODE_TODIGIT(c); if (rc < 0) { - if (defobj == NULL) { - PyErr_SetString(PyExc_ValueError, "not a digit"); + if (defobj == NULL) { + PyErr_SetString(PyExc_ValueError, "not a digit"); return NULL; - } - else { - Py_INCREF(defobj); - return defobj; - } + } + else { + Py_INCREF(defobj); + return defobj; + } } return PyLong_FromLong(rc); } @@ -222,7 +222,7 @@ /* unassigned */ have_old = 1; rc = -1.0; - } + } else if (old->decimal_changed != 0xFF) { have_old = 1; rc = old->decimal_changed; @@ -232,14 +232,14 @@ if (!have_old) rc = Py_UNICODE_TONUMERIC(c); if (rc == -1.0) { - if (defobj == NULL) { - PyErr_SetString(PyExc_ValueError, "not a numeric character"); - return NULL; - } - else { - Py_INCREF(defobj); - return defobj; - } + if (defobj == NULL) { + PyErr_SetString(PyExc_ValueError, "not a numeric character"); + return NULL; + } + else { + Py_INCREF(defobj); + return defobj; + } } return PyFloat_FromDouble(rc); } @@ -258,8 +258,8 @@ Py_UCS4 c; if (!PyArg_ParseTuple(args, "O!:category", - &PyUnicode_Type, &v)) - return NULL; + &PyUnicode_Type, &v)) + return NULL; c = getuchar(v); if (c == (Py_UCS4)-1) return NULL; @@ -287,8 +287,8 @@ Py_UCS4 c; if (!PyArg_ParseTuple(args, "O!:bidirectional", - &PyUnicode_Type, &v)) - return NULL; + &PyUnicode_Type, &v)) + return NULL; c = getuchar(v); if (c == (Py_UCS4)-1) return NULL; @@ -318,8 +318,8 @@ Py_UCS4 c; if (!PyArg_ParseTuple(args, "O!:combining", - &PyUnicode_Type, &v)) - return NULL; + &PyUnicode_Type, &v)) + return NULL; c = getuchar(v); if (c == (Py_UCS4)-1) return NULL; @@ -347,8 +347,8 @@ Py_UCS4 c; if (!PyArg_ParseTuple(args, "O!:mirrored", - &PyUnicode_Type, &v)) - return NULL; + &PyUnicode_Type, &v)) + return NULL; c = getuchar(v); if (c == (Py_UCS4)-1) return NULL; @@ -377,8 +377,8 @@ Py_UCS4 c; if (!PyArg_ParseTuple(args, "O!:east_asian_width", - &PyUnicode_Type, &v)) - return NULL; + &PyUnicode_Type, &v)) + return NULL; c = getuchar(v); if (c == (Py_UCS4)-1) return NULL; @@ -408,8 +408,8 @@ Py_UCS4 c; if (!PyArg_ParseTuple(args, "O!:decomposition", - &PyUnicode_Type, &v)) - return NULL; + &PyUnicode_Type, &v)) + return NULL; c = getuchar(v); if (c == (Py_UCS4)-1) return NULL; @@ -455,7 +455,7 @@ decomp_data[++index]); i += strlen(decomp + i); } - + decomp[i] = '\0'; return PyUnicode_FromString(decomp); @@ -466,7 +466,7 @@ { if (code >= 0x110000) { *index = 0; - } else if (self && UCD_Check(self) && + } else if (self && UCD_Check(self) && get_old_record(self, code)->category_changed==0) { /* unassigned in old version */ *index = 0; @@ -476,7 +476,7 @@ *index = decomp_index2[(*index<> 8; @@ -501,11 +501,11 @@ PyObject *result; Py_UNICODE *i, *end, *o; /* Longest decomposition in Unicode 3.2: U+FDFA */ - Py_UNICODE stack[20]; + Py_UNICODE stack[20]; Py_ssize_t space, isize; int index, prefix, count, stackptr; unsigned char prev, cur; - + stackptr = 0; isize = PyUnicode_GET_SIZE(input); /* Overallocate atmost 10 characters. */ @@ -642,12 +642,12 @@ i = PyUnicode_AS_UNICODE(result); end = i + PyUnicode_GET_SIZE(result); o = PyUnicode_AS_UNICODE(result); - + again: while (i < end) { for (index = 0; index < cskipped; index++) { if (skipped[index] == i) { - /* *i character is skipped. + /* *i character is skipped. Remove from list. */ skipped[index] = skipped[cskipped-1]; cskipped--; @@ -658,7 +658,7 @@ /* Hangul Composition. We don't need to check for pairs, since we always have decomposed data. */ if (LBase <= *i && *i < (LBase+LCount) && - i + 1 < end && + i + 1 < end && VBase <= i[1] && i[1] <= (VBase+VCount)) { int LIndex, VIndex; LIndex = i[0] - LBase; @@ -707,7 +707,7 @@ (index&((1<category_changed == 0) { /* unassigned */ return 0; - } + } } if (SBase <= code && code < SBase+SCount) { - /* Hangul syllable. */ - int SIndex = code - SBase; - int L = SIndex / NCount; - int V = (SIndex % NCount) / TCount; - int T = SIndex % TCount; - - if (buflen < 27) - /* Worst case: HANGUL SYLLABLE <10chars>. */ - return 0; - strcpy(buffer, "HANGUL SYLLABLE "); - buffer += 16; - strcpy(buffer, hangul_syllables[L][0]); - buffer += strlen(hangul_syllables[L][0]); - strcpy(buffer, hangul_syllables[V][1]); - buffer += strlen(hangul_syllables[V][1]); - strcpy(buffer, hangul_syllables[T][2]); - buffer += strlen(hangul_syllables[T][2]); - *buffer = '\0'; - return 1; + /* Hangul syllable. */ + int SIndex = code - SBase; + int L = SIndex / NCount; + int V = (SIndex % NCount) / TCount; + int T = SIndex % TCount; + + if (buflen < 27) + /* Worst case: HANGUL SYLLABLE <10chars>. */ + return 0; + strcpy(buffer, "HANGUL SYLLABLE "); + buffer += 16; + strcpy(buffer, hangul_syllables[L][0]); + buffer += strlen(hangul_syllables[L][0]); + strcpy(buffer, hangul_syllables[V][1]); + buffer += strlen(hangul_syllables[V][1]); + strcpy(buffer, hangul_syllables[T][2]); + buffer += strlen(hangul_syllables[T][2]); + *buffer = '\0'; + return 1; } if (is_unified_ideograph(code)) { @@ -980,23 +980,23 @@ return buffer[namelen] == '\0'; } -static void +static void find_syllable(const char *str, int *len, int *pos, int count, int column) { int i, len1; *len = -1; for (i = 0; i < count; i++) { - char *s = hangul_syllables[i][column]; - len1 = strlen(s); - if (len1 <= *len) - continue; - if (strncmp(str, s, len1) == 0) { - *len = len1; - *pos = i; - } + char *s = hangul_syllables[i][column]; + len1 = strlen(s); + if (len1 <= *len) + continue; + if (strncmp(str, s, len1) == 0) { + *len = len1; + *pos = i; + } } if (*len == -1) { - *len = 0; + *len = 0; } } @@ -1009,18 +1009,18 @@ /* Check for hangul syllables. */ if (strncmp(name, "HANGUL SYLLABLE ", 16) == 0) { - int len, L = -1, V = -1, T = -1; - const char *pos = name + 16; - find_syllable(pos, &len, &L, LCount, 0); - pos += len; - find_syllable(pos, &len, &V, VCount, 1); - pos += len; - find_syllable(pos, &len, &T, TCount, 2); - pos += len; - if (L != -1 && V != -1 && T != -1 && pos-name == namelen) { - *code = SBase + (L*VCount+V)*TCount + T; - return 1; - } + int len, L = -1, V = -1, T = -1; + const char *pos = name + 16; + find_syllable(pos, &len, &L, LCount, 0); + pos += len; + find_syllable(pos, &len, &V, VCount, 1); + pos += len; + find_syllable(pos, &len, &T, TCount, 2); + pos += len; + if (L != -1 && V != -1 && T != -1 && pos-name == namelen) { + *code = SBase + (L*VCount+V)*TCount + T; + return 1; + } /* Otherwise, it's an illegal syllable name. */ return 0; } @@ -1080,7 +1080,7 @@ } } -static const _PyUnicode_Name_CAPI hashAPI = +static const _PyUnicode_Name_CAPI hashAPI = { sizeof(_PyUnicode_Name_CAPI), _getucname, @@ -1112,14 +1112,14 @@ return NULL; if (!_getucname(self, c, name, sizeof(name))) { - if (defobj == NULL) { - PyErr_SetString(PyExc_ValueError, "no such name"); + if (defobj == NULL) { + PyErr_SetString(PyExc_ValueError, "no such name"); return NULL; - } - else { - Py_INCREF(defobj); - return defobj; - } + } + else { + Py_INCREF(defobj); + return defobj; + } } return PyUnicode_FromString(name); @@ -1157,7 +1157,7 @@ } #endif str[0] = (Py_UNICODE) code; - return PyUnicode_FromUnicode(str, 1); + return PyUnicode_FromUnicode(str, 1); } /* XXX Add doc strings. */ @@ -1182,27 +1182,27 @@ {"lookup", unicodedata_lookup, METH_VARARGS, unicodedata_lookup__doc__}, {"normalize", unicodedata_normalize, METH_VARARGS, unicodedata_normalize__doc__}, - {NULL, NULL} /* sentinel */ + {NULL, NULL} /* sentinel */ }; static PyTypeObject UCD_Type = { - /* The ob_type field must be initialized in the module init function - * to be portable to Windows without using C++. */ - PyVarObject_HEAD_INIT(NULL, 0) - "unicodedata.UCD", /*tp_name*/ - sizeof(PreviousDBVersion), /*tp_basicsize*/ - 0, /*tp_itemsize*/ - /* methods */ - (destructor)PyObject_Del, /*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*/ + /* The ob_type field must be initialized in the module init function + * to be portable to Windows without using C++. */ + PyVarObject_HEAD_INIT(NULL, 0) + "unicodedata.UCD", /*tp_name*/ + sizeof(PreviousDBVersion), /*tp_basicsize*/ + 0, /*tp_itemsize*/ + /* methods */ + (destructor)PyObject_Del, /*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*/ @@ -1243,15 +1243,15 @@ static struct PyModuleDef unicodedatamodule = { - PyModuleDef_HEAD_INIT, - "unicodedata", - unicodedata_docstring, - -1, - unicodedata_functions, - NULL, - NULL, - NULL, - NULL + PyModuleDef_HEAD_INIT, + "unicodedata", + unicodedata_docstring, + -1, + unicodedata_functions, + NULL, + NULL, + NULL, + NULL }; PyMODINIT_FUNC @@ -1281,7 +1281,7 @@ return m; } -/* +/* Local variables: c-basic-offset: 4 indent-tabs-mode: nil Modified: python/branches/py3k-jit/Modules/xxmodule.c ============================================================================== --- python/branches/py3k-jit/Modules/xxmodule.c (original) +++ python/branches/py3k-jit/Modules/xxmodule.c Mon May 10 23:55:43 2010 @@ -19,23 +19,23 @@ static PyObject *ErrorObject; typedef struct { - PyObject_HEAD - PyObject *x_attr; /* Attributes dictionary */ + PyObject_HEAD + PyObject *x_attr; /* Attributes dictionary */ } XxoObject; static PyTypeObject Xxo_Type; -#define XxoObject_Check(v) (Py_TYPE(v) == &Xxo_Type) +#define XxoObject_Check(v) (Py_TYPE(v) == &Xxo_Type) static XxoObject * newXxoObject(PyObject *arg) { - XxoObject *self; - self = PyObject_New(XxoObject, &Xxo_Type); - if (self == NULL) - return NULL; - self->x_attr = NULL; - return self; + XxoObject *self; + self = PyObject_New(XxoObject, &Xxo_Type); + if (self == NULL) + return NULL; + self->x_attr = NULL; + return self; } /* Xxo methods */ @@ -43,101 +43,101 @@ static void Xxo_dealloc(XxoObject *self) { - Py_XDECREF(self->x_attr); - PyObject_Del(self); + Py_XDECREF(self->x_attr); + PyObject_Del(self); } static PyObject * Xxo_demo(XxoObject *self, PyObject *args) { - if (!PyArg_ParseTuple(args, ":demo")) - return NULL; - Py_INCREF(Py_None); - return Py_None; + if (!PyArg_ParseTuple(args, ":demo")) + return NULL; + Py_INCREF(Py_None); + return Py_None; } static PyMethodDef Xxo_methods[] = { - {"demo", (PyCFunction)Xxo_demo, METH_VARARGS, - PyDoc_STR("demo() -> None")}, - {NULL, NULL} /* sentinel */ + {"demo", (PyCFunction)Xxo_demo, METH_VARARGS, + PyDoc_STR("demo() -> None")}, + {NULL, NULL} /* sentinel */ }; static PyObject * Xxo_getattro(XxoObject *self, PyObject *name) { - if (self->x_attr != NULL) { - PyObject *v = PyDict_GetItem(self->x_attr, name); - if (v != NULL) { - Py_INCREF(v); - return v; - } - } - return PyObject_GenericGetAttr((PyObject *)self, name); + if (self->x_attr != NULL) { + PyObject *v = PyDict_GetItem(self->x_attr, name); + if (v != NULL) { + Py_INCREF(v); + return v; + } + } + return PyObject_GenericGetAttr((PyObject *)self, name); } static int Xxo_setattr(XxoObject *self, char *name, PyObject *v) { - if (self->x_attr == NULL) { - self->x_attr = PyDict_New(); - if (self->x_attr == NULL) - return -1; - } - if (v == NULL) { - int rv = PyDict_DelItemString(self->x_attr, name); - if (rv < 0) - PyErr_SetString(PyExc_AttributeError, - "delete non-existing Xxo attribute"); - return rv; - } - else - return PyDict_SetItemString(self->x_attr, name, v); + if (self->x_attr == NULL) { + self->x_attr = PyDict_New(); + if (self->x_attr == NULL) + return -1; + } + if (v == NULL) { + int rv = PyDict_DelItemString(self->x_attr, name); + if (rv < 0) + PyErr_SetString(PyExc_AttributeError, + "delete non-existing Xxo attribute"); + return rv; + } + else + return PyDict_SetItemString(self->x_attr, name, v); } static PyTypeObject Xxo_Type = { - /* The ob_type field must be initialized in the module init function - * to be portable to Windows without using C++. */ - PyVarObject_HEAD_INIT(NULL, 0) - "xxmodule.Xxo", /*tp_name*/ - sizeof(XxoObject), /*tp_basicsize*/ - 0, /*tp_itemsize*/ - /* methods */ - (destructor)Xxo_dealloc, /*tp_dealloc*/ - 0, /*tp_print*/ - (getattrfunc)0, /*tp_getattr*/ - (setattrfunc)Xxo_setattr, /*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*/ - (getattrofunc)Xxo_getattro, /*tp_getattro*/ - 0, /*tp_setattro*/ - 0, /*tp_as_buffer*/ - Py_TPFLAGS_DEFAULT, /*tp_flags*/ - 0, /*tp_doc*/ - 0, /*tp_traverse*/ - 0, /*tp_clear*/ - 0, /*tp_richcompare*/ - 0, /*tp_weaklistoffset*/ - 0, /*tp_iter*/ - 0, /*tp_iternext*/ - Xxo_methods, /*tp_methods*/ - 0, /*tp_members*/ - 0, /*tp_getset*/ - 0, /*tp_base*/ - 0, /*tp_dict*/ - 0, /*tp_descr_get*/ - 0, /*tp_descr_set*/ - 0, /*tp_dictoffset*/ - 0, /*tp_init*/ - 0, /*tp_alloc*/ - 0, /*tp_new*/ - 0, /*tp_free*/ - 0, /*tp_is_gc*/ + /* The ob_type field must be initialized in the module init function + * to be portable to Windows without using C++. */ + PyVarObject_HEAD_INIT(NULL, 0) + "xxmodule.Xxo", /*tp_name*/ + sizeof(XxoObject), /*tp_basicsize*/ + 0, /*tp_itemsize*/ + /* methods */ + (destructor)Xxo_dealloc, /*tp_dealloc*/ + 0, /*tp_print*/ + (getattrfunc)0, /*tp_getattr*/ + (setattrfunc)Xxo_setattr, /*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*/ + (getattrofunc)Xxo_getattro, /*tp_getattro*/ + 0, /*tp_setattro*/ + 0, /*tp_as_buffer*/ + Py_TPFLAGS_DEFAULT, /*tp_flags*/ + 0, /*tp_doc*/ + 0, /*tp_traverse*/ + 0, /*tp_clear*/ + 0, /*tp_richcompare*/ + 0, /*tp_weaklistoffset*/ + 0, /*tp_iter*/ + 0, /*tp_iternext*/ + Xxo_methods, /*tp_methods*/ + 0, /*tp_members*/ + 0, /*tp_getset*/ + 0, /*tp_base*/ + 0, /*tp_dict*/ + 0, /*tp_descr_get*/ + 0, /*tp_descr_set*/ + 0, /*tp_dictoffset*/ + 0, /*tp_init*/ + 0, /*tp_alloc*/ + 0, /*tp_new*/ + 0, /*tp_free*/ + 0, /*tp_is_gc*/ }; /* --------------------------------------------------------------------- */ @@ -151,12 +151,12 @@ static PyObject * xx_foo(PyObject *self, PyObject *args) { - long i, j; - long res; - if (!PyArg_ParseTuple(args, "ll:foo", &i, &j)) - return NULL; - res = i+j; /* XXX Do something here */ - return PyLong_FromLong(res); + long i, j; + long res; + if (!PyArg_ParseTuple(args, "ll:foo", &i, &j)) + return NULL; + res = i+j; /* XXX Do something here */ + return PyLong_FromLong(res); } @@ -165,14 +165,14 @@ static PyObject * xx_new(PyObject *self, PyObject *args) { - XxoObject *rv; + XxoObject *rv; - if (!PyArg_ParseTuple(args, ":new")) - return NULL; - rv = newXxoObject(args); - if (rv == NULL) - return NULL; - return (PyObject *)rv; + if (!PyArg_ParseTuple(args, ":new")) + return NULL; + rv = newXxoObject(args); + if (rv == NULL) + return NULL; + return (PyObject *)rv; } /* Example with subtle bug from extensions manual ("Thin Ice"). */ @@ -180,20 +180,20 @@ static PyObject * xx_bug(PyObject *self, PyObject *args) { - PyObject *list, *item; + PyObject *list, *item; - if (!PyArg_ParseTuple(args, "O:bug", &list)) - return NULL; + if (!PyArg_ParseTuple(args, "O:bug", &list)) + return NULL; - item = PyList_GetItem(list, 0); - /* Py_INCREF(item); */ - PyList_SetItem(list, 1, PyLong_FromLong(0L)); - PyObject_Print(item, stdout, 0); - printf("\n"); - /* Py_DECREF(item); */ + item = PyList_GetItem(list, 0); + /* Py_INCREF(item); */ + PyList_SetItem(list, 1, PyLong_FromLong(0L)); + PyObject_Print(item, stdout, 0); + printf("\n"); + /* Py_DECREF(item); */ - Py_INCREF(Py_None); - return Py_None; + Py_INCREF(Py_None); + return Py_None; } /* Test bad format character */ @@ -201,61 +201,61 @@ static PyObject * xx_roj(PyObject *self, PyObject *args) { - PyObject *a; - long b; - if (!PyArg_ParseTuple(args, "O#:roj", &a, &b)) - return NULL; - Py_INCREF(Py_None); - return Py_None; + PyObject *a; + long b; + if (!PyArg_ParseTuple(args, "O#:roj", &a, &b)) + return NULL; + Py_INCREF(Py_None); + return Py_None; } /* ---------- */ static PyTypeObject Str_Type = { - /* The ob_type field must be initialized in the module init function - * to be portable to Windows without using C++. */ - PyVarObject_HEAD_INIT(NULL, 0) - "xxmodule.Str", /*tp_name*/ - 0, /*tp_basicsize*/ - 0, /*tp_itemsize*/ - /* methods */ - 0, /*tp_dealloc*/ - 0, /*tp_print*/ - 0, /*tp_getattr*/ - 0, /*tp_setattr*/ - 0, /*tp_reserved*/ - 0, /*tp_repr*/ - 0, /*tp_as_number*/ - 0, /*tp_as_sequence*/ - 0, /*tp_as_mapping*/ - 0, /*tp_hash*/ - 0, /*tp_call*/ - 0, /*tp_str*/ - 0, /*tp_getattro*/ - 0, /*tp_setattro*/ - 0, /*tp_as_buffer*/ - Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /*tp_flags*/ - 0, /*tp_doc*/ - 0, /*tp_traverse*/ - 0, /*tp_clear*/ - 0, /*tp_richcompare*/ - 0, /*tp_weaklistoffset*/ - 0, /*tp_iter*/ - 0, /*tp_iternext*/ - 0, /*tp_methods*/ - 0, /*tp_members*/ - 0, /*tp_getset*/ - 0, /* see PyInit_xx */ /*tp_base*/ - 0, /*tp_dict*/ - 0, /*tp_descr_get*/ - 0, /*tp_descr_set*/ - 0, /*tp_dictoffset*/ - 0, /*tp_init*/ - 0, /*tp_alloc*/ - 0, /*tp_new*/ - 0, /*tp_free*/ - 0, /*tp_is_gc*/ + /* The ob_type field must be initialized in the module init function + * to be portable to Windows without using C++. */ + PyVarObject_HEAD_INIT(NULL, 0) + "xxmodule.Str", /*tp_name*/ + 0, /*tp_basicsize*/ + 0, /*tp_itemsize*/ + /* methods */ + 0, /*tp_dealloc*/ + 0, /*tp_print*/ + 0, /*tp_getattr*/ + 0, /*tp_setattr*/ + 0, /*tp_reserved*/ + 0, /*tp_repr*/ + 0, /*tp_as_number*/ + 0, /*tp_as_sequence*/ + 0, /*tp_as_mapping*/ + 0, /*tp_hash*/ + 0, /*tp_call*/ + 0, /*tp_str*/ + 0, /*tp_getattro*/ + 0, /*tp_setattro*/ + 0, /*tp_as_buffer*/ + Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /*tp_flags*/ + 0, /*tp_doc*/ + 0, /*tp_traverse*/ + 0, /*tp_clear*/ + 0, /*tp_richcompare*/ + 0, /*tp_weaklistoffset*/ + 0, /*tp_iter*/ + 0, /*tp_iternext*/ + 0, /*tp_methods*/ + 0, /*tp_members*/ + 0, /*tp_getset*/ + 0, /* see PyInit_xx */ /*tp_base*/ + 0, /*tp_dict*/ + 0, /*tp_descr_get*/ + 0, /*tp_descr_set*/ + 0, /*tp_dictoffset*/ + 0, /*tp_init*/ + 0, /*tp_alloc*/ + 0, /*tp_new*/ + 0, /*tp_free*/ + 0, /*tp_is_gc*/ }; /* ---------- */ @@ -263,54 +263,54 @@ static PyObject * null_richcompare(PyObject *self, PyObject *other, int op) { - Py_INCREF(Py_NotImplemented); - return Py_NotImplemented; + Py_INCREF(Py_NotImplemented); + return Py_NotImplemented; } static PyTypeObject Null_Type = { - /* The ob_type field must be initialized in the module init function - * to be portable to Windows without using C++. */ - PyVarObject_HEAD_INIT(NULL, 0) - "xxmodule.Null", /*tp_name*/ - 0, /*tp_basicsize*/ - 0, /*tp_itemsize*/ - /* methods */ - 0, /*tp_dealloc*/ - 0, /*tp_print*/ - 0, /*tp_getattr*/ - 0, /*tp_setattr*/ - 0, /*tp_reserved*/ - 0, /*tp_repr*/ - 0, /*tp_as_number*/ - 0, /*tp_as_sequence*/ - 0, /*tp_as_mapping*/ - 0, /*tp_hash*/ - 0, /*tp_call*/ - 0, /*tp_str*/ - 0, /*tp_getattro*/ - 0, /*tp_setattro*/ - 0, /*tp_as_buffer*/ - Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /*tp_flags*/ - 0, /*tp_doc*/ - 0, /*tp_traverse*/ - 0, /*tp_clear*/ - null_richcompare, /*tp_richcompare*/ - 0, /*tp_weaklistoffset*/ - 0, /*tp_iter*/ - 0, /*tp_iternext*/ - 0, /*tp_methods*/ - 0, /*tp_members*/ - 0, /*tp_getset*/ - 0, /* see PyInit_xx */ /*tp_base*/ - 0, /*tp_dict*/ - 0, /*tp_descr_get*/ - 0, /*tp_descr_set*/ - 0, /*tp_dictoffset*/ - 0, /*tp_init*/ - 0, /*tp_alloc*/ - 0, /* see PyInit_xx */ /*tp_new*/ - 0, /*tp_free*/ - 0, /*tp_is_gc*/ + /* The ob_type field must be initialized in the module init function + * to be portable to Windows without using C++. */ + PyVarObject_HEAD_INIT(NULL, 0) + "xxmodule.Null", /*tp_name*/ + 0, /*tp_basicsize*/ + 0, /*tp_itemsize*/ + /* methods */ + 0, /*tp_dealloc*/ + 0, /*tp_print*/ + 0, /*tp_getattr*/ + 0, /*tp_setattr*/ + 0, /*tp_reserved*/ + 0, /*tp_repr*/ + 0, /*tp_as_number*/ + 0, /*tp_as_sequence*/ + 0, /*tp_as_mapping*/ + 0, /*tp_hash*/ + 0, /*tp_call*/ + 0, /*tp_str*/ + 0, /*tp_getattro*/ + 0, /*tp_setattro*/ + 0, /*tp_as_buffer*/ + Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /*tp_flags*/ + 0, /*tp_doc*/ + 0, /*tp_traverse*/ + 0, /*tp_clear*/ + null_richcompare, /*tp_richcompare*/ + 0, /*tp_weaklistoffset*/ + 0, /*tp_iter*/ + 0, /*tp_iternext*/ + 0, /*tp_methods*/ + 0, /*tp_members*/ + 0, /*tp_getset*/ + 0, /* see PyInit_xx */ /*tp_base*/ + 0, /*tp_dict*/ + 0, /*tp_descr_get*/ + 0, /*tp_descr_set*/ + 0, /*tp_dictoffset*/ + 0, /*tp_init*/ + 0, /*tp_alloc*/ + 0, /* see PyInit_xx */ /*tp_new*/ + 0, /*tp_free*/ + 0, /*tp_is_gc*/ }; @@ -320,15 +320,15 @@ /* List of functions defined in the module */ static PyMethodDef xx_methods[] = { - {"roj", xx_roj, METH_VARARGS, - PyDoc_STR("roj(a,b) -> None")}, - {"foo", xx_foo, METH_VARARGS, - xx_foo_doc}, - {"new", xx_new, METH_VARARGS, - PyDoc_STR("new() -> new Xx object")}, - {"bug", xx_bug, METH_VARARGS, - PyDoc_STR("bug(o) -> None")}, - {NULL, NULL} /* sentinel */ + {"roj", xx_roj, METH_VARARGS, + PyDoc_STR("roj(a,b) -> None")}, + {"foo", xx_foo, METH_VARARGS, + xx_foo_doc}, + {"new", xx_new, METH_VARARGS, + PyDoc_STR("new() -> new Xx object")}, + {"bug", xx_bug, METH_VARARGS, + PyDoc_STR("bug(o) -> None")}, + {NULL, NULL} /* sentinel */ }; PyDoc_STRVAR(module_doc, @@ -338,59 +338,59 @@ static struct PyModuleDef xxmodule = { - PyModuleDef_HEAD_INIT, - "xx", - module_doc, - -1, - xx_methods, - NULL, - NULL, - NULL, - NULL + PyModuleDef_HEAD_INIT, + "xx", + module_doc, + -1, + xx_methods, + NULL, + NULL, + NULL, + NULL }; PyMODINIT_FUNC PyInit_xx(void) { - PyObject *m = NULL; + PyObject *m = NULL; - /* Due to cross platform compiler issues the slots must be filled - * here. It's required for portability to Windows without requiring - * C++. */ - Null_Type.tp_base = &PyBaseObject_Type; - Null_Type.tp_new = PyType_GenericNew; - Str_Type.tp_base = &PyUnicode_Type; - - /* Finalize the type object including setting type of the new type - * object; doing it here is required for portability, too. */ - if (PyType_Ready(&Xxo_Type) < 0) - goto fail; - - /* Create the module and add the functions */ - m = PyModule_Create(&xxmodule); - if (m == NULL) - goto fail; - - /* Add some symbolic constants to the module */ - if (ErrorObject == NULL) { - ErrorObject = PyErr_NewException("xx.error", NULL, NULL); - if (ErrorObject == NULL) - goto fail; - } - Py_INCREF(ErrorObject); - PyModule_AddObject(m, "error", ErrorObject); - - /* Add Str */ - if (PyType_Ready(&Str_Type) < 0) - goto fail; - PyModule_AddObject(m, "Str", (PyObject *)&Str_Type); - - /* Add Null */ - if (PyType_Ready(&Null_Type) < 0) - goto fail; - PyModule_AddObject(m, "Null", (PyObject *)&Null_Type); - return m; + /* Due to cross platform compiler issues the slots must be filled + * here. It's required for portability to Windows without requiring + * C++. */ + Null_Type.tp_base = &PyBaseObject_Type; + Null_Type.tp_new = PyType_GenericNew; + Str_Type.tp_base = &PyUnicode_Type; + + /* Finalize the type object including setting type of the new type + * object; doing it here is required for portability, too. */ + if (PyType_Ready(&Xxo_Type) < 0) + goto fail; + + /* Create the module and add the functions */ + m = PyModule_Create(&xxmodule); + if (m == NULL) + goto fail; + + /* Add some symbolic constants to the module */ + if (ErrorObject == NULL) { + ErrorObject = PyErr_NewException("xx.error", NULL, NULL); + if (ErrorObject == NULL) + goto fail; + } + Py_INCREF(ErrorObject); + PyModule_AddObject(m, "error", ErrorObject); + + /* Add Str */ + if (PyType_Ready(&Str_Type) < 0) + goto fail; + PyModule_AddObject(m, "Str", (PyObject *)&Str_Type); + + /* Add Null */ + if (PyType_Ready(&Null_Type) < 0) + goto fail; + PyModule_AddObject(m, "Null", (PyObject *)&Null_Type); + return m; fail: - Py_XDECREF(m); - return NULL; + Py_XDECREF(m); + return NULL; } Modified: python/branches/py3k-jit/Modules/xxsubtype.c ============================================================================== --- python/branches/py3k-jit/Modules/xxsubtype.c (original) +++ python/branches/py3k-jit/Modules/xxsubtype.c Mon May 10 23:55:43 2010 @@ -19,291 +19,291 @@ /* spamlist -- a list subtype */ typedef struct { - PyListObject list; - int state; + PyListObject list; + int state; } spamlistobject; static PyObject * spamlist_getstate(spamlistobject *self, PyObject *args) { - if (!PyArg_ParseTuple(args, ":getstate")) - return NULL; - return PyLong_FromLong(self->state); + if (!PyArg_ParseTuple(args, ":getstate")) + return NULL; + return PyLong_FromLong(self->state); } static PyObject * spamlist_setstate(spamlistobject *self, PyObject *args) { - int state; + int state; - if (!PyArg_ParseTuple(args, "i:setstate", &state)) - return NULL; - self->state = state; - Py_INCREF(Py_None); - return Py_None; + if (!PyArg_ParseTuple(args, "i:setstate", &state)) + return NULL; + self->state = state; + Py_INCREF(Py_None); + return Py_None; } static PyObject * spamlist_specialmeth(PyObject *self, PyObject *args, PyObject *kw) { - PyObject *result = PyTuple_New(3); + PyObject *result = PyTuple_New(3); - if (result != NULL) { - if (self == NULL) - self = Py_None; - if (kw == NULL) - kw = Py_None; - Py_INCREF(self); - PyTuple_SET_ITEM(result, 0, self); - Py_INCREF(args); - PyTuple_SET_ITEM(result, 1, args); - Py_INCREF(kw); - PyTuple_SET_ITEM(result, 2, kw); - } - return result; + if (result != NULL) { + if (self == NULL) + self = Py_None; + if (kw == NULL) + kw = Py_None; + Py_INCREF(self); + PyTuple_SET_ITEM(result, 0, self); + Py_INCREF(args); + PyTuple_SET_ITEM(result, 1, args); + Py_INCREF(kw); + PyTuple_SET_ITEM(result, 2, kw); + } + return result; } static PyMethodDef spamlist_methods[] = { - {"getstate", (PyCFunction)spamlist_getstate, METH_VARARGS, - PyDoc_STR("getstate() -> state")}, - {"setstate", (PyCFunction)spamlist_setstate, METH_VARARGS, - PyDoc_STR("setstate(state)")}, - /* These entries differ only in the flags; they are used by the tests - in test.test_descr. */ - {"classmeth", (PyCFunction)spamlist_specialmeth, - METH_VARARGS | METH_KEYWORDS | METH_CLASS, - PyDoc_STR("classmeth(*args, **kw)")}, - {"staticmeth", (PyCFunction)spamlist_specialmeth, - METH_VARARGS | METH_KEYWORDS | METH_STATIC, - PyDoc_STR("staticmeth(*args, **kw)")}, - {NULL, NULL}, + {"getstate", (PyCFunction)spamlist_getstate, METH_VARARGS, + PyDoc_STR("getstate() -> state")}, + {"setstate", (PyCFunction)spamlist_setstate, METH_VARARGS, + PyDoc_STR("setstate(state)")}, + /* These entries differ only in the flags; they are used by the tests + in test.test_descr. */ + {"classmeth", (PyCFunction)spamlist_specialmeth, + METH_VARARGS | METH_KEYWORDS | METH_CLASS, + PyDoc_STR("classmeth(*args, **kw)")}, + {"staticmeth", (PyCFunction)spamlist_specialmeth, + METH_VARARGS | METH_KEYWORDS | METH_STATIC, + PyDoc_STR("staticmeth(*args, **kw)")}, + {NULL, NULL}, }; static int spamlist_init(spamlistobject *self, PyObject *args, PyObject *kwds) { - if (PyList_Type.tp_init((PyObject *)self, args, kwds) < 0) - return -1; - self->state = 0; - return 0; + if (PyList_Type.tp_init((PyObject *)self, args, kwds) < 0) + return -1; + self->state = 0; + return 0; } static PyObject * spamlist_state_get(spamlistobject *self) { - return PyLong_FromLong(self->state); + return PyLong_FromLong(self->state); } static PyGetSetDef spamlist_getsets[] = { - {"state", (getter)spamlist_state_get, NULL, - PyDoc_STR("an int variable for demonstration purposes")}, - {0} + {"state", (getter)spamlist_state_get, NULL, + PyDoc_STR("an int variable for demonstration purposes")}, + {0} }; static PyTypeObject spamlist_type = { - PyVarObject_HEAD_INIT(DEFERRED_ADDRESS(&PyType_Type), 0) - "xxsubtype.spamlist", - sizeof(spamlistobject), - 0, - 0, /* tp_dealloc */ - 0, /* tp_print */ - 0, /* tp_getattr */ - 0, /* tp_setattr */ - 0, /* tp_reserved */ - 0, /* tp_repr */ - 0, /* tp_as_number */ - 0, /* tp_as_sequence */ - 0, /* tp_as_mapping */ - 0, /* tp_hash */ - 0, /* tp_call */ - 0, /* tp_str */ - 0, /* tp_getattro */ - 0, /* tp_setattro */ - 0, /* tp_as_buffer */ - Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */ - 0, /* tp_doc */ - 0, /* tp_traverse */ - 0, /* tp_clear */ - 0, /* tp_richcompare */ - 0, /* tp_weaklistoffset */ - 0, /* tp_iter */ - 0, /* tp_iternext */ - spamlist_methods, /* tp_methods */ - 0, /* tp_members */ - spamlist_getsets, /* tp_getset */ - DEFERRED_ADDRESS(&PyList_Type), /* tp_base */ - 0, /* tp_dict */ - 0, /* tp_descr_get */ - 0, /* tp_descr_set */ - 0, /* tp_dictoffset */ - (initproc)spamlist_init, /* tp_init */ - 0, /* tp_alloc */ - 0, /* tp_new */ + PyVarObject_HEAD_INIT(DEFERRED_ADDRESS(&PyType_Type), 0) + "xxsubtype.spamlist", + sizeof(spamlistobject), + 0, + 0, /* tp_dealloc */ + 0, /* tp_print */ + 0, /* tp_getattr */ + 0, /* tp_setattr */ + 0, /* tp_reserved */ + 0, /* tp_repr */ + 0, /* tp_as_number */ + 0, /* tp_as_sequence */ + 0, /* tp_as_mapping */ + 0, /* tp_hash */ + 0, /* tp_call */ + 0, /* tp_str */ + 0, /* tp_getattro */ + 0, /* tp_setattro */ + 0, /* tp_as_buffer */ + Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */ + 0, /* tp_doc */ + 0, /* tp_traverse */ + 0, /* tp_clear */ + 0, /* tp_richcompare */ + 0, /* tp_weaklistoffset */ + 0, /* tp_iter */ + 0, /* tp_iternext */ + spamlist_methods, /* tp_methods */ + 0, /* tp_members */ + spamlist_getsets, /* tp_getset */ + DEFERRED_ADDRESS(&PyList_Type), /* tp_base */ + 0, /* tp_dict */ + 0, /* tp_descr_get */ + 0, /* tp_descr_set */ + 0, /* tp_dictoffset */ + (initproc)spamlist_init, /* tp_init */ + 0, /* tp_alloc */ + 0, /* tp_new */ }; /* spamdict -- a dict subtype */ typedef struct { - PyDictObject dict; - int state; + PyDictObject dict; + int state; } spamdictobject; static PyObject * spamdict_getstate(spamdictobject *self, PyObject *args) { - if (!PyArg_ParseTuple(args, ":getstate")) - return NULL; - return PyLong_FromLong(self->state); + if (!PyArg_ParseTuple(args, ":getstate")) + return NULL; + return PyLong_FromLong(self->state); } static PyObject * spamdict_setstate(spamdictobject *self, PyObject *args) { - int state; + int state; - if (!PyArg_ParseTuple(args, "i:setstate", &state)) - return NULL; - self->state = state; - Py_INCREF(Py_None); - return Py_None; + if (!PyArg_ParseTuple(args, "i:setstate", &state)) + return NULL; + self->state = state; + Py_INCREF(Py_None); + return Py_None; } static PyMethodDef spamdict_methods[] = { - {"getstate", (PyCFunction)spamdict_getstate, METH_VARARGS, - PyDoc_STR("getstate() -> state")}, - {"setstate", (PyCFunction)spamdict_setstate, METH_VARARGS, - PyDoc_STR("setstate(state)")}, - {NULL, NULL}, + {"getstate", (PyCFunction)spamdict_getstate, METH_VARARGS, + PyDoc_STR("getstate() -> state")}, + {"setstate", (PyCFunction)spamdict_setstate, METH_VARARGS, + PyDoc_STR("setstate(state)")}, + {NULL, NULL}, }; static int spamdict_init(spamdictobject *self, PyObject *args, PyObject *kwds) { - if (PyDict_Type.tp_init((PyObject *)self, args, kwds) < 0) - return -1; - self->state = 0; - return 0; + if (PyDict_Type.tp_init((PyObject *)self, args, kwds) < 0) + return -1; + self->state = 0; + return 0; } static PyMemberDef spamdict_members[] = { - {"state", T_INT, offsetof(spamdictobject, state), READONLY, - PyDoc_STR("an int variable for demonstration purposes")}, - {0} + {"state", T_INT, offsetof(spamdictobject, state), READONLY, + PyDoc_STR("an int variable for demonstration purposes")}, + {0} }; static PyTypeObject spamdict_type = { - PyVarObject_HEAD_INIT(DEFERRED_ADDRESS(&PyType_Type), 0) - "xxsubtype.spamdict", - sizeof(spamdictobject), - 0, - 0, /* tp_dealloc */ - 0, /* tp_print */ - 0, /* tp_getattr */ - 0, /* tp_setattr */ - 0, /* tp_reserved */ - 0, /* tp_repr */ - 0, /* tp_as_number */ - 0, /* tp_as_sequence */ - 0, /* tp_as_mapping */ - 0, /* tp_hash */ - 0, /* tp_call */ - 0, /* tp_str */ - 0, /* tp_getattro */ - 0, /* tp_setattro */ - 0, /* tp_as_buffer */ - Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */ - 0, /* tp_doc */ - 0, /* tp_traverse */ - 0, /* tp_clear */ - 0, /* tp_richcompare */ - 0, /* tp_weaklistoffset */ - 0, /* tp_iter */ - 0, /* tp_iternext */ - spamdict_methods, /* tp_methods */ - spamdict_members, /* tp_members */ - 0, /* tp_getset */ - DEFERRED_ADDRESS(&PyDict_Type), /* tp_base */ - 0, /* tp_dict */ - 0, /* tp_descr_get */ - 0, /* tp_descr_set */ - 0, /* tp_dictoffset */ - (initproc)spamdict_init, /* tp_init */ - 0, /* tp_alloc */ - 0, /* tp_new */ + PyVarObject_HEAD_INIT(DEFERRED_ADDRESS(&PyType_Type), 0) + "xxsubtype.spamdict", + sizeof(spamdictobject), + 0, + 0, /* tp_dealloc */ + 0, /* tp_print */ + 0, /* tp_getattr */ + 0, /* tp_setattr */ + 0, /* tp_reserved */ + 0, /* tp_repr */ + 0, /* tp_as_number */ + 0, /* tp_as_sequence */ + 0, /* tp_as_mapping */ + 0, /* tp_hash */ + 0, /* tp_call */ + 0, /* tp_str */ + 0, /* tp_getattro */ + 0, /* tp_setattro */ + 0, /* tp_as_buffer */ + Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */ + 0, /* tp_doc */ + 0, /* tp_traverse */ + 0, /* tp_clear */ + 0, /* tp_richcompare */ + 0, /* tp_weaklistoffset */ + 0, /* tp_iter */ + 0, /* tp_iternext */ + spamdict_methods, /* tp_methods */ + spamdict_members, /* tp_members */ + 0, /* tp_getset */ + DEFERRED_ADDRESS(&PyDict_Type), /* tp_base */ + 0, /* tp_dict */ + 0, /* tp_descr_get */ + 0, /* tp_descr_set */ + 0, /* tp_dictoffset */ + (initproc)spamdict_init, /* tp_init */ + 0, /* tp_alloc */ + 0, /* tp_new */ }; static PyObject * spam_bench(PyObject *self, PyObject *args) { - PyObject *obj, *name, *res; - int n = 1000; - time_t t0, t1; - - if (!PyArg_ParseTuple(args, "OS|i", &obj, &name, &n)) - return NULL; - t0 = clock(); - while (--n >= 0) { - res = PyObject_GetAttr(obj, name); - if (res == NULL) - return NULL; - Py_DECREF(res); - } - t1 = clock(); - return PyFloat_FromDouble((double)(t1-t0) / CLOCKS_PER_SEC); + PyObject *obj, *name, *res; + int n = 1000; + time_t t0, t1; + + if (!PyArg_ParseTuple(args, "OS|i", &obj, &name, &n)) + return NULL; + t0 = clock(); + while (--n >= 0) { + res = PyObject_GetAttr(obj, name); + if (res == NULL) + return NULL; + Py_DECREF(res); + } + t1 = clock(); + return PyFloat_FromDouble((double)(t1-t0) / CLOCKS_PER_SEC); } static PyMethodDef xxsubtype_functions[] = { - {"bench", spam_bench, METH_VARARGS}, - {NULL, NULL} /* sentinel */ + {"bench", spam_bench, METH_VARARGS}, + {NULL, NULL} /* sentinel */ }; static struct PyModuleDef xxsubtypemodule = { - PyModuleDef_HEAD_INIT, - "xxsubtype", - xxsubtype__doc__, - -1, - xxsubtype_functions, - NULL, - NULL, - NULL, - NULL + PyModuleDef_HEAD_INIT, + "xxsubtype", + xxsubtype__doc__, + -1, + xxsubtype_functions, + NULL, + NULL, + NULL, + NULL }; PyMODINIT_FUNC PyInit_xxsubtype(void) { - PyObject *m; + PyObject *m; - /* Fill in deferred data addresses. This must be done before - PyType_Ready() is called. Note that PyType_Ready() automatically - initializes the ob.ob_type field to &PyType_Type if it's NULL, - so it's not necessary to fill in ob_type first. */ - spamdict_type.tp_base = &PyDict_Type; - if (PyType_Ready(&spamdict_type) < 0) - return NULL; - - spamlist_type.tp_base = &PyList_Type; - if (PyType_Ready(&spamlist_type) < 0) - return NULL; - - m = PyModule_Create(&xxsubtypemodule); - if (m == NULL) - return NULL; - - if (PyType_Ready(&spamlist_type) < 0) - return NULL; - if (PyType_Ready(&spamdict_type) < 0) - return NULL; - - Py_INCREF(&spamlist_type); - if (PyModule_AddObject(m, "spamlist", - (PyObject *) &spamlist_type) < 0) - return NULL; - - Py_INCREF(&spamdict_type); - if (PyModule_AddObject(m, "spamdict", - (PyObject *) &spamdict_type) < 0) - return NULL; - return m; + /* Fill in deferred data addresses. This must be done before + PyType_Ready() is called. Note that PyType_Ready() automatically + initializes the ob.ob_type field to &PyType_Type if it's NULL, + so it's not necessary to fill in ob_type first. */ + spamdict_type.tp_base = &PyDict_Type; + if (PyType_Ready(&spamdict_type) < 0) + return NULL; + + spamlist_type.tp_base = &PyList_Type; + if (PyType_Ready(&spamlist_type) < 0) + return NULL; + + m = PyModule_Create(&xxsubtypemodule); + if (m == NULL) + return NULL; + + if (PyType_Ready(&spamlist_type) < 0) + return NULL; + if (PyType_Ready(&spamdict_type) < 0) + return NULL; + + Py_INCREF(&spamlist_type); + if (PyModule_AddObject(m, "spamlist", + (PyObject *) &spamlist_type) < 0) + return NULL; + + Py_INCREF(&spamdict_type); + if (PyModule_AddObject(m, "spamdict", + (PyObject *) &spamdict_type) < 0) + return NULL; + return m; } Modified: python/branches/py3k-jit/Modules/zipimport.c ============================================================================== --- python/branches/py3k-jit/Modules/zipimport.c (original) +++ python/branches/py3k-jit/Modules/zipimport.c Mon May 10 23:55:43 2010 @@ -10,8 +10,8 @@ #define IS_PACKAGE 0x2 struct st_zip_searchorder { - char suffix[14]; - int type; + char suffix[14]; + int type; }; /* zip_searchorder defines how we search for a module in the Zip @@ -20,13 +20,13 @@ are swapped by initzipimport() if we run in optimized mode. Also, '/' is replaced by SEP there. */ static struct st_zip_searchorder zip_searchorder[] = { - {"/__init__.pyc", IS_PACKAGE | IS_BYTECODE}, - {"/__init__.pyo", IS_PACKAGE | IS_BYTECODE}, - {"/__init__.py", IS_PACKAGE | IS_SOURCE}, - {".pyc", IS_BYTECODE}, - {".pyo", IS_BYTECODE}, - {".py", IS_SOURCE}, - {"", 0} + {"/__init__.pyc", IS_PACKAGE | IS_BYTECODE}, + {"/__init__.pyo", IS_PACKAGE | IS_BYTECODE}, + {"/__init__.py", IS_PACKAGE | IS_SOURCE}, + {".pyc", IS_BYTECODE}, + {".pyo", IS_BYTECODE}, + {".py", IS_SOURCE}, + {"", 0} }; /* zipimporter object definition and support */ @@ -34,10 +34,10 @@ typedef struct _zipimporter ZipImporter; struct _zipimporter { - PyObject_HEAD - PyObject *archive; /* pathname of the Zip archive */ - PyObject *prefix; /* file prefix: "a/sub/directory/" */ - PyObject *files; /* dict with file info {path: toc_entry} */ + PyObject_HEAD + PyObject *archive; /* pathname of the Zip archive */ + PyObject *prefix; /* file prefix: "a/sub/directory/" */ + PyObject *files; /* dict with file info {path: toc_entry} */ }; static PyObject *ZipImportError; @@ -47,7 +47,7 @@ static PyObject *read_directory(char *archive); static PyObject *get_data(char *archive, PyObject *toc_entry); static PyObject *get_module_code(ZipImporter *self, char *fullname, - int *p_ispackage, char **p_modpath); + int *p_ispackage, char **p_modpath); #define ZipImporter_Check(op) PyObject_TypeCheck(op, &ZipImporter_Type) @@ -60,147 +60,147 @@ static int zipimporter_init(ZipImporter *self, PyObject *args, PyObject *kwds) { - char *path, *p, *prefix, buf[MAXPATHLEN+2]; - size_t len; + char *path, *p, *prefix, buf[MAXPATHLEN+2]; + size_t len; - if (!_PyArg_NoKeywords("zipimporter()", kwds)) - return -1; + if (!_PyArg_NoKeywords("zipimporter()", kwds)) + return -1; - if (!PyArg_ParseTuple(args, "s:zipimporter", &path)) - return -1; + if (!PyArg_ParseTuple(args, "s:zipimporter", &path)) + return -1; - len = strlen(path); - if (len == 0) { - PyErr_SetString(ZipImportError, "archive path is empty"); - return -1; - } - if (len >= MAXPATHLEN) { - PyErr_SetString(ZipImportError, - "archive path too long"); - return -1; - } - strcpy(buf, path); + len = strlen(path); + if (len == 0) { + PyErr_SetString(ZipImportError, "archive path is empty"); + return -1; + } + if (len >= MAXPATHLEN) { + PyErr_SetString(ZipImportError, + "archive path too long"); + return -1; + } + strcpy(buf, path); #ifdef ALTSEP - for (p = buf; *p; p++) { - if (*p == ALTSEP) - *p = SEP; - } + for (p = buf; *p; p++) { + if (*p == ALTSEP) + *p = SEP; + } #endif - path = NULL; - prefix = NULL; - for (;;) { - struct stat statbuf; - int rv; - - rv = stat(buf, &statbuf); - if (rv == 0) { - /* it exists */ - if (S_ISREG(statbuf.st_mode)) - /* it's a file */ - path = buf; - break; - } - /* back up one path element */ - p = strrchr(buf, SEP); - if (prefix != NULL) - *prefix = SEP; - if (p == NULL) - break; - *p = '\0'; - prefix = p; - } - if (path != NULL) { - PyObject *files; - files = PyDict_GetItemString(zip_directory_cache, path); - if (files == NULL) { - files = read_directory(buf); - if (files == NULL) - return -1; - if (PyDict_SetItemString(zip_directory_cache, path, - files) != 0) - return -1; - } - else - Py_INCREF(files); - self->files = files; - } - else { - PyErr_SetString(ZipImportError, "not a Zip file"); - return -1; - } - - if (prefix == NULL) - prefix = ""; - else { - prefix++; - len = strlen(prefix); - if (prefix[len-1] != SEP) { - /* add trailing SEP */ - prefix[len] = SEP; - prefix[len + 1] = '\0'; - } - } - - self->archive = PyUnicode_FromString(buf); - if (self->archive == NULL) - return -1; - - self->prefix = PyUnicode_FromString(prefix); - if (self->prefix == NULL) - return -1; + path = NULL; + prefix = NULL; + for (;;) { + struct stat statbuf; + int rv; + + rv = stat(buf, &statbuf); + if (rv == 0) { + /* it exists */ + if (S_ISREG(statbuf.st_mode)) + /* it's a file */ + path = buf; + break; + } + /* back up one path element */ + p = strrchr(buf, SEP); + if (prefix != NULL) + *prefix = SEP; + if (p == NULL) + break; + *p = '\0'; + prefix = p; + } + if (path != NULL) { + PyObject *files; + files = PyDict_GetItemString(zip_directory_cache, path); + if (files == NULL) { + files = read_directory(buf); + if (files == NULL) + return -1; + if (PyDict_SetItemString(zip_directory_cache, path, + files) != 0) + return -1; + } + else + Py_INCREF(files); + self->files = files; + } + else { + PyErr_SetString(ZipImportError, "not a Zip file"); + return -1; + } + + if (prefix == NULL) + prefix = ""; + else { + prefix++; + len = strlen(prefix); + if (prefix[len-1] != SEP) { + /* add trailing SEP */ + prefix[len] = SEP; + prefix[len + 1] = '\0'; + } + } + + self->archive = PyUnicode_FromString(buf); + if (self->archive == NULL) + return -1; + + self->prefix = PyUnicode_FromString(prefix); + if (self->prefix == NULL) + return -1; - return 0; + return 0; } /* GC support. */ static int zipimporter_traverse(PyObject *obj, visitproc visit, void *arg) { - ZipImporter *self = (ZipImporter *)obj; - Py_VISIT(self->files); - return 0; + ZipImporter *self = (ZipImporter *)obj; + Py_VISIT(self->files); + return 0; } static void zipimporter_dealloc(ZipImporter *self) { - PyObject_GC_UnTrack(self); - Py_XDECREF(self->archive); - Py_XDECREF(self->prefix); - Py_XDECREF(self->files); - Py_TYPE(self)->tp_free((PyObject *)self); + PyObject_GC_UnTrack(self); + Py_XDECREF(self->archive); + Py_XDECREF(self->prefix); + Py_XDECREF(self->files); + Py_TYPE(self)->tp_free((PyObject *)self); } static PyObject * zipimporter_repr(ZipImporter *self) { - char *archive = "???"; - char *prefix = ""; + char *archive = "???"; + char *prefix = ""; - if (self->archive != NULL && PyUnicode_Check(self->archive)) - archive = _PyUnicode_AsString(self->archive); - if (self->prefix != NULL && PyUnicode_Check(self->prefix)) - prefix = _PyUnicode_AsString(self->prefix); - if (prefix != NULL && *prefix) - return PyUnicode_FromFormat("", - archive, SEP, prefix); - else - return PyUnicode_FromFormat("", - archive); + if (self->archive != NULL && PyUnicode_Check(self->archive)) + archive = _PyUnicode_AsString(self->archive); + if (self->prefix != NULL && PyUnicode_Check(self->prefix)) + prefix = _PyUnicode_AsString(self->prefix); + if (prefix != NULL && *prefix) + return PyUnicode_FromFormat("", + archive, SEP, prefix); + else + return PyUnicode_FromFormat("", + archive); } /* return fullname.split(".")[-1] */ static char * get_subname(char *fullname) { - char *subname = strrchr(fullname, '.'); - if (subname == NULL) - subname = fullname; - else - subname++; - return subname; + char *subname = strrchr(fullname, '.'); + if (subname == NULL) + subname = fullname; + else + subname++; + return subname; } /* Given a (sub)modulename, write the potential file path in the @@ -209,59 +209,59 @@ static int make_filename(char *prefix, char *name, char *path) { - size_t len; - char *p; + size_t len; + char *p; - len = strlen(prefix); + len = strlen(prefix); - /* self.prefix + name [+ SEP + "__init__"] + ".py[co]" */ - if (len + strlen(name) + 13 >= MAXPATHLEN) { - PyErr_SetString(ZipImportError, "path too long"); - return -1; - } - - strcpy(path, prefix); - strcpy(path + len, name); - for (p = path + len; *p; p++) { - if (*p == '.') - *p = SEP; - } - len += strlen(name); - assert(len < INT_MAX); - return (int)len; + /* self.prefix + name [+ SEP + "__init__"] + ".py[co]" */ + if (len + strlen(name) + 13 >= MAXPATHLEN) { + PyErr_SetString(ZipImportError, "path too long"); + return -1; + } + + strcpy(path, prefix); + strcpy(path + len, name); + for (p = path + len; *p; p++) { + if (*p == '.') + *p = SEP; + } + len += strlen(name); + assert(len < INT_MAX); + return (int)len; } enum zi_module_info { - MI_ERROR, - MI_NOT_FOUND, - MI_MODULE, - MI_PACKAGE + MI_ERROR, + MI_NOT_FOUND, + MI_MODULE, + MI_PACKAGE }; /* Return some information about a module. */ static enum zi_module_info get_module_info(ZipImporter *self, char *fullname) { - char *subname, path[MAXPATHLEN + 1]; - int len; - struct st_zip_searchorder *zso; - - subname = get_subname(fullname); - - len = make_filename(_PyUnicode_AsString(self->prefix), subname, path); - if (len < 0) - return MI_ERROR; - - for (zso = zip_searchorder; *zso->suffix; zso++) { - strcpy(path + len, zso->suffix); - if (PyDict_GetItemString(self->files, path) != NULL) { - if (zso->type & IS_PACKAGE) - return MI_PACKAGE; - else - return MI_MODULE; - } - } - return MI_NOT_FOUND; + char *subname, path[MAXPATHLEN + 1]; + int len; + struct st_zip_searchorder *zso; + + subname = get_subname(fullname); + + len = make_filename(_PyUnicode_AsString(self->prefix), subname, path); + if (len < 0) + return MI_ERROR; + + for (zso = zip_searchorder; *zso->suffix; zso++) { + strcpy(path + len, zso->suffix); + if (PyDict_GetItemString(self->files, path) != NULL) { + if (zso->type & IS_PACKAGE) + return MI_PACKAGE; + else + return MI_MODULE; + } + } + return MI_NOT_FOUND; } /* Check whether we can satisfy the import of the module named by @@ -269,86 +269,86 @@ static PyObject * zipimporter_find_module(PyObject *obj, PyObject *args) { - ZipImporter *self = (ZipImporter *)obj; - PyObject *path = NULL; - char *fullname; - enum zi_module_info mi; - - if (!PyArg_ParseTuple(args, "s|O:zipimporter.find_module", - &fullname, &path)) - return NULL; - - mi = get_module_info(self, fullname); - if (mi == MI_ERROR) - return NULL; - if (mi == MI_NOT_FOUND) { - Py_INCREF(Py_None); - return Py_None; - } - Py_INCREF(self); - return (PyObject *)self; + ZipImporter *self = (ZipImporter *)obj; + PyObject *path = NULL; + char *fullname; + enum zi_module_info mi; + + if (!PyArg_ParseTuple(args, "s|O:zipimporter.find_module", + &fullname, &path)) + return NULL; + + mi = get_module_info(self, fullname); + if (mi == MI_ERROR) + return NULL; + if (mi == MI_NOT_FOUND) { + Py_INCREF(Py_None); + return Py_None; + } + Py_INCREF(self); + return (PyObject *)self; } /* Load and return the module named by 'fullname'. */ static PyObject * zipimporter_load_module(PyObject *obj, PyObject *args) { - ZipImporter *self = (ZipImporter *)obj; - PyObject *code, *mod, *dict; - char *fullname, *modpath; - int ispackage; - - if (!PyArg_ParseTuple(args, "s:zipimporter.load_module", - &fullname)) - return NULL; - - code = get_module_code(self, fullname, &ispackage, &modpath); - if (code == NULL) - return NULL; - - mod = PyImport_AddModule(fullname); - if (mod == NULL) { - Py_DECREF(code); - return NULL; - } - dict = PyModule_GetDict(mod); - - /* mod.__loader__ = self */ - if (PyDict_SetItemString(dict, "__loader__", (PyObject *)self) != 0) - goto error; - - if (ispackage) { - /* add __path__ to the module *before* the code gets - executed */ - PyObject *pkgpath, *fullpath; - char *subname = get_subname(fullname); - int err; - - fullpath = PyUnicode_FromFormat("%U%c%U%s", - self->archive, SEP, - self->prefix, subname); - if (fullpath == NULL) - goto error; - - pkgpath = Py_BuildValue("[O]", fullpath); - Py_DECREF(fullpath); - if (pkgpath == NULL) - goto error; - err = PyDict_SetItemString(dict, "__path__", pkgpath); - Py_DECREF(pkgpath); - if (err != 0) - goto error; - } - mod = PyImport_ExecCodeModuleEx(fullname, code, modpath); - Py_DECREF(code); - if (Py_VerboseFlag) - PySys_WriteStderr("import %s # loaded from Zip %s\n", - fullname, modpath); - return mod; + ZipImporter *self = (ZipImporter *)obj; + PyObject *code, *mod, *dict; + char *fullname, *modpath; + int ispackage; + + if (!PyArg_ParseTuple(args, "s:zipimporter.load_module", + &fullname)) + return NULL; + + code = get_module_code(self, fullname, &ispackage, &modpath); + if (code == NULL) + return NULL; + + mod = PyImport_AddModule(fullname); + if (mod == NULL) { + Py_DECREF(code); + return NULL; + } + dict = PyModule_GetDict(mod); + + /* mod.__loader__ = self */ + if (PyDict_SetItemString(dict, "__loader__", (PyObject *)self) != 0) + goto error; + + if (ispackage) { + /* add __path__ to the module *before* the code gets + executed */ + PyObject *pkgpath, *fullpath; + char *subname = get_subname(fullname); + int err; + + fullpath = PyUnicode_FromFormat("%U%c%U%s", + self->archive, SEP, + self->prefix, subname); + if (fullpath == NULL) + goto error; + + pkgpath = Py_BuildValue("[O]", fullpath); + Py_DECREF(fullpath); + if (pkgpath == NULL) + goto error; + err = PyDict_SetItemString(dict, "__path__", pkgpath); + Py_DECREF(pkgpath); + if (err != 0) + goto error; + } + mod = PyImport_ExecCodeModuleEx(fullname, code, modpath); + Py_DECREF(code); + if (Py_VerboseFlag) + PySys_WriteStderr("import %s # loaded from Zip %s\n", + fullname, modpath); + return mod; error: - Py_DECREF(code); - Py_DECREF(mod); - return NULL; + Py_DECREF(code); + Py_DECREF(mod); + return NULL; } /* Return a string matching __file__ for the named module */ @@ -362,13 +362,13 @@ if (!PyArg_ParseTuple(args, "s:zipimporter.get_filename", &fullname)) - return NULL; + return NULL; /* Deciding the filename requires working out where the code would come from if the module was actually loaded */ code = get_module_code(self, fullname, &ispackage, &modpath); if (code == NULL) - return NULL; + return NULL; Py_DECREF(code); /* Only need the path info */ return PyUnicode_FromString(modpath); @@ -378,123 +378,123 @@ static PyObject * zipimporter_is_package(PyObject *obj, PyObject *args) { - ZipImporter *self = (ZipImporter *)obj; - char *fullname; - enum zi_module_info mi; - - if (!PyArg_ParseTuple(args, "s:zipimporter.is_package", - &fullname)) - return NULL; - - mi = get_module_info(self, fullname); - if (mi == MI_ERROR) - return NULL; - if (mi == MI_NOT_FOUND) { - PyErr_Format(ZipImportError, "can't find module '%.200s'", - fullname); - return NULL; - } - return PyBool_FromLong(mi == MI_PACKAGE); + ZipImporter *self = (ZipImporter *)obj; + char *fullname; + enum zi_module_info mi; + + if (!PyArg_ParseTuple(args, "s:zipimporter.is_package", + &fullname)) + return NULL; + + mi = get_module_info(self, fullname); + if (mi == MI_ERROR) + return NULL; + if (mi == MI_NOT_FOUND) { + PyErr_Format(ZipImportError, "can't find module '%.200s'", + fullname); + return NULL; + } + return PyBool_FromLong(mi == MI_PACKAGE); } static PyObject * zipimporter_get_data(PyObject *obj, PyObject *args) { - ZipImporter *self = (ZipImporter *)obj; - char *path; + ZipImporter *self = (ZipImporter *)obj; + char *path; #ifdef ALTSEP - char *p, buf[MAXPATHLEN + 1]; + char *p, buf[MAXPATHLEN + 1]; #endif - PyObject *toc_entry; - Py_ssize_t len; - char *archive_str; + PyObject *toc_entry; + Py_ssize_t len; + char *archive_str; - if (!PyArg_ParseTuple(args, "s:zipimporter.get_data", &path)) - return NULL; + if (!PyArg_ParseTuple(args, "s:zipimporter.get_data", &path)) + return NULL; #ifdef ALTSEP - if (strlen(path) >= MAXPATHLEN) { - PyErr_SetString(ZipImportError, "path too long"); - return NULL; - } - strcpy(buf, path); - for (p = buf; *p; p++) { - if (*p == ALTSEP) - *p = SEP; - } - path = buf; + if (strlen(path) >= MAXPATHLEN) { + PyErr_SetString(ZipImportError, "path too long"); + return NULL; + } + strcpy(buf, path); + for (p = buf; *p; p++) { + if (*p == ALTSEP) + *p = SEP; + } + path = buf; #endif - archive_str = _PyUnicode_AsStringAndSize(self->archive, &len); - if ((size_t)len < strlen(path) && - strncmp(path, archive_str, len) == 0 && - path[len] == SEP) { - path = path + len + 1; - } - - toc_entry = PyDict_GetItemString(self->files, path); - if (toc_entry == NULL) { - PyErr_SetFromErrnoWithFilename(PyExc_IOError, path); - return NULL; - } - return get_data(archive_str, toc_entry); + archive_str = _PyUnicode_AsStringAndSize(self->archive, &len); + if ((size_t)len < strlen(path) && + strncmp(path, archive_str, len) == 0 && + path[len] == SEP) { + path = path + len + 1; + } + + toc_entry = PyDict_GetItemString(self->files, path); + if (toc_entry == NULL) { + PyErr_SetFromErrnoWithFilename(PyExc_IOError, path); + return NULL; + } + return get_data(archive_str, toc_entry); } static PyObject * zipimporter_get_code(PyObject *obj, PyObject *args) { - ZipImporter *self = (ZipImporter *)obj; - char *fullname; + ZipImporter *self = (ZipImporter *)obj; + char *fullname; - if (!PyArg_ParseTuple(args, "s:zipimporter.get_code", &fullname)) - return NULL; + if (!PyArg_ParseTuple(args, "s:zipimporter.get_code", &fullname)) + return NULL; - return get_module_code(self, fullname, NULL, NULL); + return get_module_code(self, fullname, NULL, NULL); } static PyObject * zipimporter_get_source(PyObject *obj, PyObject *args) { - ZipImporter *self = (ZipImporter *)obj; - PyObject *toc_entry; - char *fullname, *subname, path[MAXPATHLEN+1]; - int len; - enum zi_module_info mi; - - if (!PyArg_ParseTuple(args, "s:zipimporter.get_source", &fullname)) - return NULL; - - mi = get_module_info(self, fullname); - if (mi == MI_ERROR) - return NULL; - if (mi == MI_NOT_FOUND) { - PyErr_Format(ZipImportError, "can't find module '%.200s'", - fullname); - return NULL; - } - subname = get_subname(fullname); - - len = make_filename(_PyUnicode_AsString(self->prefix), subname, path); - if (len < 0) - return NULL; - - if (mi == MI_PACKAGE) { - path[len] = SEP; - strcpy(path + len + 1, "__init__.py"); - } - else - strcpy(path + len, ".py"); - - toc_entry = PyDict_GetItemString(self->files, path); - if (toc_entry != NULL) { - PyObject *bytes = get_data(_PyUnicode_AsString(self->archive), toc_entry); - PyObject *res = PyUnicode_FromString(PyBytes_AsString(bytes)); - Py_XDECREF(bytes); - return res; - } - - /* we have the module, but no source */ - Py_INCREF(Py_None); - return Py_None; + ZipImporter *self = (ZipImporter *)obj; + PyObject *toc_entry; + char *fullname, *subname, path[MAXPATHLEN+1]; + int len; + enum zi_module_info mi; + + if (!PyArg_ParseTuple(args, "s:zipimporter.get_source", &fullname)) + return NULL; + + mi = get_module_info(self, fullname); + if (mi == MI_ERROR) + return NULL; + if (mi == MI_NOT_FOUND) { + PyErr_Format(ZipImportError, "can't find module '%.200s'", + fullname); + return NULL; + } + subname = get_subname(fullname); + + len = make_filename(_PyUnicode_AsString(self->prefix), subname, path); + if (len < 0) + return NULL; + + if (mi == MI_PACKAGE) { + path[len] = SEP; + strcpy(path + len + 1, "__init__.py"); + } + else + strcpy(path + len, ".py"); + + toc_entry = PyDict_GetItemString(self->files, path); + if (toc_entry != NULL) { + PyObject *bytes = get_data(_PyUnicode_AsString(self->archive), toc_entry); + PyObject *res = PyUnicode_FromString(PyBytes_AsString(bytes)); + Py_XDECREF(bytes); + return res; + } + + /* we have the module, but no source */ + Py_INCREF(Py_None); + return Py_None; } PyDoc_STRVAR(doc_find_module, @@ -545,28 +545,28 @@ Return the filename for the specified module."); static PyMethodDef zipimporter_methods[] = { - {"find_module", zipimporter_find_module, METH_VARARGS, - doc_find_module}, - {"load_module", zipimporter_load_module, METH_VARARGS, - doc_load_module}, - {"get_data", zipimporter_get_data, METH_VARARGS, - doc_get_data}, - {"get_code", zipimporter_get_code, METH_VARARGS, - doc_get_code}, - {"get_source", zipimporter_get_source, METH_VARARGS, - doc_get_source}, - {"get_filename", zipimporter_get_filename, METH_VARARGS, - doc_get_filename}, - {"is_package", zipimporter_is_package, METH_VARARGS, - doc_is_package}, - {NULL, NULL} /* sentinel */ + {"find_module", zipimporter_find_module, METH_VARARGS, + doc_find_module}, + {"load_module", zipimporter_load_module, METH_VARARGS, + doc_load_module}, + {"get_data", zipimporter_get_data, METH_VARARGS, + doc_get_data}, + {"get_code", zipimporter_get_code, METH_VARARGS, + doc_get_code}, + {"get_source", zipimporter_get_source, METH_VARARGS, + doc_get_source}, + {"get_filename", zipimporter_get_filename, METH_VARARGS, + doc_get_filename}, + {"is_package", zipimporter_is_package, METH_VARARGS, + doc_is_package}, + {NULL, NULL} /* sentinel */ }; static PyMemberDef zipimporter_members[] = { - {"archive", T_OBJECT, offsetof(ZipImporter, archive), READONLY}, - {"prefix", T_OBJECT, offsetof(ZipImporter, prefix), READONLY}, - {"_files", T_OBJECT, offsetof(ZipImporter, files), READONLY}, - {NULL} + {"archive", T_OBJECT, offsetof(ZipImporter, archive), READONLY}, + {"prefix", T_OBJECT, offsetof(ZipImporter, prefix), READONLY}, + {"_files", T_OBJECT, offsetof(ZipImporter, files), READONLY}, + {NULL} }; PyDoc_STRVAR(zipimporter_doc, @@ -586,46 +586,46 @@ #define DEFERRED_ADDRESS(ADDR) 0 static PyTypeObject ZipImporter_Type = { - PyVarObject_HEAD_INIT(DEFERRED_ADDRESS(&PyType_Type), 0) - "zipimport.zipimporter", - sizeof(ZipImporter), - 0, /* tp_itemsize */ - (destructor)zipimporter_dealloc, /* tp_dealloc */ - 0, /* tp_print */ - 0, /* tp_getattr */ - 0, /* tp_setattr */ - 0, /* tp_reserved */ - (reprfunc)zipimporter_repr, /* 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_BASETYPE | - Py_TPFLAGS_HAVE_GC, /* tp_flags */ - zipimporter_doc, /* tp_doc */ - zipimporter_traverse, /* tp_traverse */ - 0, /* tp_clear */ - 0, /* tp_richcompare */ - 0, /* tp_weaklistoffset */ - 0, /* tp_iter */ - 0, /* tp_iternext */ - zipimporter_methods, /* tp_methods */ - zipimporter_members, /* tp_members */ - 0, /* tp_getset */ - 0, /* tp_base */ - 0, /* tp_dict */ - 0, /* tp_descr_get */ - 0, /* tp_descr_set */ - 0, /* tp_dictoffset */ - (initproc)zipimporter_init, /* tp_init */ - PyType_GenericAlloc, /* tp_alloc */ - PyType_GenericNew, /* tp_new */ - PyObject_GC_Del, /* tp_free */ + PyVarObject_HEAD_INIT(DEFERRED_ADDRESS(&PyType_Type), 0) + "zipimport.zipimporter", + sizeof(ZipImporter), + 0, /* tp_itemsize */ + (destructor)zipimporter_dealloc, /* tp_dealloc */ + 0, /* tp_print */ + 0, /* tp_getattr */ + 0, /* tp_setattr */ + 0, /* tp_reserved */ + (reprfunc)zipimporter_repr, /* 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_BASETYPE | + Py_TPFLAGS_HAVE_GC, /* tp_flags */ + zipimporter_doc, /* tp_doc */ + zipimporter_traverse, /* tp_traverse */ + 0, /* tp_clear */ + 0, /* tp_richcompare */ + 0, /* tp_weaklistoffset */ + 0, /* tp_iter */ + 0, /* tp_iternext */ + zipimporter_methods, /* tp_methods */ + zipimporter_members, /* tp_members */ + 0, /* tp_getset */ + 0, /* tp_base */ + 0, /* tp_dict */ + 0, /* tp_descr_get */ + 0, /* tp_descr_set */ + 0, /* tp_dictoffset */ + (initproc)zipimporter_init, /* tp_init */ + PyType_GenericAlloc, /* tp_alloc */ + PyType_GenericNew, /* tp_new */ + PyObject_GC_Del, /* tp_free */ }; @@ -636,16 +636,16 @@ marshal.c:r_long() */ static long get_long(unsigned char *buf) { - long x; - x = buf[0]; - x |= (long)buf[1] << 8; - x |= (long)buf[2] << 16; - x |= (long)buf[3] << 24; + long x; + x = buf[0]; + x |= (long)buf[1] << 8; + x |= (long)buf[2] << 16; + x |= (long)buf[3] << 24; #if SIZEOF_LONG > 4 - /* Sign extension for 64-bit machines */ - x |= -(x & 0x80000000L); + /* Sign extension for 64-bit machines */ + x |= -(x & 0x80000000L); #endif - return x; + return x; } /* @@ -657,13 +657,13 @@ A toc_entry is a tuple: (__file__, # value to use for __file__, available for all files - compress, # compression kind; 0 for uncompressed - data_size, # size of compressed data on disk - file_size, # size of decompressed data - file_offset, # offset of file header from start of archive - time, # mod time of file (in dos format) - date, # mod data of file (in dos format) - crc, # crc checksum of the data + compress, # compression kind; 0 for uncompressed + data_size, # size of compressed data on disk + file_size, # size of decompressed data + file_offset, # offset of file header from start of archive + time, # mod time of file (in dos format) + date, # mod data of file (in dos format) + crc, # crc checksum of the data ) Directories can be recognized by the trailing SEP in the name, @@ -672,115 +672,115 @@ static PyObject * read_directory(char *archive) { - PyObject *files = NULL; - FILE *fp; - long compress, crc, data_size, file_size, file_offset, date, time; - long header_offset, name_size, header_size, header_position; - long i, l, count; - size_t length; - char path[MAXPATHLEN + 5]; - char name[MAXPATHLEN + 5]; - char *p, endof_central_dir[22]; - long arc_offset; /* offset from beginning of file to start of zip-archive */ - - if (strlen(archive) > MAXPATHLEN) { - PyErr_SetString(PyExc_OverflowError, - "Zip path name is too long"); - return NULL; - } - strcpy(path, archive); - - fp = fopen(archive, "rb"); - if (fp == NULL) { - PyErr_Format(ZipImportError, "can't open Zip file: " - "'%.200s'", archive); - return NULL; - } - fseek(fp, -22, SEEK_END); - header_position = ftell(fp); - if (fread(endof_central_dir, 1, 22, fp) != 22) { - fclose(fp); - PyErr_Format(ZipImportError, "can't read Zip file: " - "'%.200s'", archive); - return NULL; - } - if (get_long((unsigned char *)endof_central_dir) != 0x06054B50) { - /* Bad: End of Central Dir signature */ - fclose(fp); - PyErr_Format(ZipImportError, "not a Zip file: " - "'%.200s'", archive); - return NULL; - } - - header_size = get_long((unsigned char *)endof_central_dir + 12); - header_offset = get_long((unsigned char *)endof_central_dir + 16); - arc_offset = header_position - header_offset - header_size; - header_offset += arc_offset; - - files = PyDict_New(); - if (files == NULL) - goto error; - - length = (long)strlen(path); - path[length] = SEP; - - /* Start of Central Directory */ - count = 0; - for (;;) { - PyObject *t; - int err; - - fseek(fp, header_offset, 0); /* Start of file header */ - l = PyMarshal_ReadLongFromFile(fp); - if (l != 0x02014B50) - break; /* Bad: Central Dir File Header */ - fseek(fp, header_offset + 10, 0); - compress = PyMarshal_ReadShortFromFile(fp); - time = PyMarshal_ReadShortFromFile(fp); - date = PyMarshal_ReadShortFromFile(fp); - crc = PyMarshal_ReadLongFromFile(fp); - data_size = PyMarshal_ReadLongFromFile(fp); - file_size = PyMarshal_ReadLongFromFile(fp); - name_size = PyMarshal_ReadShortFromFile(fp); - header_size = 46 + name_size + - PyMarshal_ReadShortFromFile(fp) + - PyMarshal_ReadShortFromFile(fp); - fseek(fp, header_offset + 42, 0); - file_offset = PyMarshal_ReadLongFromFile(fp) + arc_offset; - if (name_size > MAXPATHLEN) - name_size = MAXPATHLEN; - - p = name; - for (i = 0; i < name_size; i++) { - *p = (char)getc(fp); - if (*p == '/') - *p = SEP; - p++; - } - *p = 0; /* Add terminating null byte */ - header_offset += header_size; - - strncpy(path + length + 1, name, MAXPATHLEN - length - 1); - - t = Py_BuildValue("siiiiiii", path, compress, data_size, - file_size, file_offset, time, date, crc); - if (t == NULL) - goto error; - err = PyDict_SetItemString(files, name, t); - Py_DECREF(t); - if (err != 0) - goto error; - count++; - } - fclose(fp); - if (Py_VerboseFlag) - PySys_WriteStderr("# zipimport: found %ld names in %s\n", - count, archive); - return files; + PyObject *files = NULL; + FILE *fp; + long compress, crc, data_size, file_size, file_offset, date, time; + long header_offset, name_size, header_size, header_position; + long i, l, count; + size_t length; + char path[MAXPATHLEN + 5]; + char name[MAXPATHLEN + 5]; + char *p, endof_central_dir[22]; + long arc_offset; /* offset from beginning of file to start of zip-archive */ + + if (strlen(archive) > MAXPATHLEN) { + PyErr_SetString(PyExc_OverflowError, + "Zip path name is too long"); + return NULL; + } + strcpy(path, archive); + + fp = fopen(archive, "rb"); + if (fp == NULL) { + PyErr_Format(ZipImportError, "can't open Zip file: " + "'%.200s'", archive); + return NULL; + } + fseek(fp, -22, SEEK_END); + header_position = ftell(fp); + if (fread(endof_central_dir, 1, 22, fp) != 22) { + fclose(fp); + PyErr_Format(ZipImportError, "can't read Zip file: " + "'%.200s'", archive); + return NULL; + } + if (get_long((unsigned char *)endof_central_dir) != 0x06054B50) { + /* Bad: End of Central Dir signature */ + fclose(fp); + PyErr_Format(ZipImportError, "not a Zip file: " + "'%.200s'", archive); + return NULL; + } + + header_size = get_long((unsigned char *)endof_central_dir + 12); + header_offset = get_long((unsigned char *)endof_central_dir + 16); + arc_offset = header_position - header_offset - header_size; + header_offset += arc_offset; + + files = PyDict_New(); + if (files == NULL) + goto error; + + length = (long)strlen(path); + path[length] = SEP; + + /* Start of Central Directory */ + count = 0; + for (;;) { + PyObject *t; + int err; + + fseek(fp, header_offset, 0); /* Start of file header */ + l = PyMarshal_ReadLongFromFile(fp); + if (l != 0x02014B50) + break; /* Bad: Central Dir File Header */ + fseek(fp, header_offset + 10, 0); + compress = PyMarshal_ReadShortFromFile(fp); + time = PyMarshal_ReadShortFromFile(fp); + date = PyMarshal_ReadShortFromFile(fp); + crc = PyMarshal_ReadLongFromFile(fp); + data_size = PyMarshal_ReadLongFromFile(fp); + file_size = PyMarshal_ReadLongFromFile(fp); + name_size = PyMarshal_ReadShortFromFile(fp); + header_size = 46 + name_size + + PyMarshal_ReadShortFromFile(fp) + + PyMarshal_ReadShortFromFile(fp); + fseek(fp, header_offset + 42, 0); + file_offset = PyMarshal_ReadLongFromFile(fp) + arc_offset; + if (name_size > MAXPATHLEN) + name_size = MAXPATHLEN; + + p = name; + for (i = 0; i < name_size; i++) { + *p = (char)getc(fp); + if (*p == '/') + *p = SEP; + p++; + } + *p = 0; /* Add terminating null byte */ + header_offset += header_size; + + strncpy(path + length + 1, name, MAXPATHLEN - length - 1); + + t = Py_BuildValue("siiiiiii", path, compress, data_size, + file_size, file_offset, time, date, crc); + if (t == NULL) + goto error; + err = PyDict_SetItemString(files, name, t); + Py_DECREF(t); + if (err != 0) + goto error; + count++; + } + fclose(fp); + if (Py_VerboseFlag) + PySys_WriteStderr("# zipimport: found %ld names in %s\n", + count, archive); + return files; error: - fclose(fp); - Py_XDECREF(files); - return NULL; + fclose(fp); + Py_XDECREF(files); + return NULL; } /* Return the zlib.decompress function object, or NULL if zlib couldn't @@ -790,31 +790,31 @@ static PyObject * get_decompress_func(void) { - static PyObject *decompress = NULL; + static PyObject *decompress = NULL; - if (decompress == NULL) { - PyObject *zlib; - static int importing_zlib = 0; - - if (importing_zlib != 0) - /* Someone has a zlib.py[co] in their Zip file; - let's avoid a stack overflow. */ - return NULL; - importing_zlib = 1; - zlib = PyImport_ImportModuleNoBlock("zlib"); - importing_zlib = 0; - if (zlib != NULL) { - decompress = PyObject_GetAttrString(zlib, - "decompress"); - Py_DECREF(zlib); - } - else - PyErr_Clear(); - if (Py_VerboseFlag) - PySys_WriteStderr("# zipimport: zlib %s\n", - zlib != NULL ? "available": "UNAVAILABLE"); - } - return decompress; + if (decompress == NULL) { + PyObject *zlib; + static int importing_zlib = 0; + + if (importing_zlib != 0) + /* Someone has a zlib.py[co] in their Zip file; + let's avoid a stack overflow. */ + return NULL; + importing_zlib = 1; + zlib = PyImport_ImportModuleNoBlock("zlib"); + importing_zlib = 0; + if (zlib != NULL) { + decompress = PyObject_GetAttrString(zlib, + "decompress"); + Py_DECREF(zlib); + } + else + PyErr_Clear(); + if (Py_VerboseFlag) + PySys_WriteStderr("# zipimport: zlib %s\n", + zlib != NULL ? "available": "UNAVAILABLE"); + } + return decompress; } /* Given a path to a Zip file and a toc_entry, return the (uncompressed) @@ -822,91 +822,91 @@ static PyObject * get_data(char *archive, PyObject *toc_entry) { - PyObject *raw_data, *data = NULL, *decompress; - char *buf; - FILE *fp; - int err; - Py_ssize_t bytes_read = 0; - long l; - char *datapath; - long compress, data_size, file_size, file_offset, bytes_size; - long time, date, crc; - - if (!PyArg_ParseTuple(toc_entry, "slllllll", &datapath, &compress, - &data_size, &file_size, &file_offset, &time, - &date, &crc)) { - return NULL; - } - - fp = fopen(archive, "rb"); - if (!fp) { - PyErr_Format(PyExc_IOError, - "zipimport: can not open file %s", archive); - return NULL; - } - - /* Check to make sure the local file header is correct */ - fseek(fp, file_offset, 0); - l = PyMarshal_ReadLongFromFile(fp); - if (l != 0x04034B50) { - /* Bad: Local File Header */ - PyErr_Format(ZipImportError, - "bad local file header in %s", - archive); - fclose(fp); - return NULL; - } - fseek(fp, file_offset + 26, 0); - l = 30 + PyMarshal_ReadShortFromFile(fp) + - PyMarshal_ReadShortFromFile(fp); /* local header size */ - file_offset += l; /* Start of file data */ - - bytes_size = compress == 0 ? data_size : data_size + 1; - if (bytes_size == 0) - bytes_size++; - raw_data = PyBytes_FromStringAndSize((char *)NULL, bytes_size); - - if (raw_data == NULL) { - fclose(fp); - return NULL; - } - buf = PyBytes_AsString(raw_data); - - err = fseek(fp, file_offset, 0); - if (err == 0) - bytes_read = fread(buf, 1, data_size, fp); - fclose(fp); - if (err || bytes_read != data_size) { - PyErr_SetString(PyExc_IOError, - "zipimport: can't read data"); - Py_DECREF(raw_data); - return NULL; - } - - if (compress != 0) { - buf[data_size] = 'Z'; /* saw this in zipfile.py */ - data_size++; - } - buf[data_size] = '\0'; - - if (compress == 0) { /* data is not compressed */ - data = PyBytes_FromStringAndSize(buf, data_size); - Py_DECREF(raw_data); - return data; - } - - /* Decompress with zlib */ - decompress = get_decompress_func(); - if (decompress == NULL) { - PyErr_SetString(ZipImportError, - "can't decompress data; " - "zlib not available"); - goto error; - } - data = PyObject_CallFunction(decompress, "Oi", raw_data, -15); + PyObject *raw_data, *data = NULL, *decompress; + char *buf; + FILE *fp; + int err; + Py_ssize_t bytes_read = 0; + long l; + char *datapath; + long compress, data_size, file_size, file_offset, bytes_size; + long time, date, crc; + + if (!PyArg_ParseTuple(toc_entry, "slllllll", &datapath, &compress, + &data_size, &file_size, &file_offset, &time, + &date, &crc)) { + return NULL; + } + + fp = fopen(archive, "rb"); + if (!fp) { + PyErr_Format(PyExc_IOError, + "zipimport: can not open file %s", archive); + return NULL; + } + + /* Check to make sure the local file header is correct */ + fseek(fp, file_offset, 0); + l = PyMarshal_ReadLongFromFile(fp); + if (l != 0x04034B50) { + /* Bad: Local File Header */ + PyErr_Format(ZipImportError, + "bad local file header in %s", + archive); + fclose(fp); + return NULL; + } + fseek(fp, file_offset + 26, 0); + l = 30 + PyMarshal_ReadShortFromFile(fp) + + PyMarshal_ReadShortFromFile(fp); /* local header size */ + file_offset += l; /* Start of file data */ + + bytes_size = compress == 0 ? data_size : data_size + 1; + if (bytes_size == 0) + bytes_size++; + raw_data = PyBytes_FromStringAndSize((char *)NULL, bytes_size); + + if (raw_data == NULL) { + fclose(fp); + return NULL; + } + buf = PyBytes_AsString(raw_data); + + err = fseek(fp, file_offset, 0); + if (err == 0) + bytes_read = fread(buf, 1, data_size, fp); + fclose(fp); + if (err || bytes_read != data_size) { + PyErr_SetString(PyExc_IOError, + "zipimport: can't read data"); + Py_DECREF(raw_data); + return NULL; + } + + if (compress != 0) { + buf[data_size] = 'Z'; /* saw this in zipfile.py */ + data_size++; + } + buf[data_size] = '\0'; + + if (compress == 0) { /* data is not compressed */ + data = PyBytes_FromStringAndSize(buf, data_size); + Py_DECREF(raw_data); + return data; + } + + /* Decompress with zlib */ + decompress = get_decompress_func(); + if (decompress == NULL) { + PyErr_SetString(ZipImportError, + "can't decompress data; " + "zlib not available"); + goto error; + } + data = PyObject_CallFunction(decompress, "Oi", raw_data, -15); error: - Py_DECREF(raw_data); - return data; + Py_DECREF(raw_data); + return data; } /* Lenient date/time comparison function. The precision of the mtime @@ -915,11 +915,11 @@ static int eq_mtime(time_t t1, time_t t2) { - time_t d = t1 - t2; - if (d < 0) - d = -d; - /* dostime only stores even seconds, so be lenient */ - return d <= 1; + time_t d = t1 - t2; + if (d < 0) + d = -d; + /* dostime only stores even seconds, so be lenient */ + return d <= 1; } /* Given the contents of a .py[co] file in a buffer, unmarshal the data @@ -930,44 +930,44 @@ static PyObject * unmarshal_code(char *pathname, PyObject *data, time_t mtime) { - PyObject *code; - char *buf = PyBytes_AsString(data); - Py_ssize_t size = PyBytes_Size(data); - - if (size <= 9) { - PyErr_SetString(ZipImportError, - "bad pyc data"); - return NULL; - } - - if (get_long((unsigned char *)buf) != PyImport_GetMagicNumber()) { - if (Py_VerboseFlag) - PySys_WriteStderr("# %s has bad magic\n", - pathname); - Py_INCREF(Py_None); - return Py_None; /* signal caller to try alternative */ - } - - if (mtime != 0 && !eq_mtime(get_long((unsigned char *)buf + 4), - mtime)) { - if (Py_VerboseFlag) - PySys_WriteStderr("# %s has bad mtime\n", - pathname); - Py_INCREF(Py_None); - return Py_None; /* signal caller to try alternative */ - } - - code = PyMarshal_ReadObjectFromString(buf + 8, size - 8); - if (code == NULL) - return NULL; - if (!PyCode_Check(code)) { - Py_DECREF(code); - PyErr_Format(PyExc_TypeError, - "compiled module %.200s is not a code object", - pathname); - return NULL; - } - return code; + PyObject *code; + char *buf = PyBytes_AsString(data); + Py_ssize_t size = PyBytes_Size(data); + + if (size <= 9) { + PyErr_SetString(ZipImportError, + "bad pyc data"); + return NULL; + } + + if (get_long((unsigned char *)buf) != PyImport_GetMagicNumber()) { + if (Py_VerboseFlag) + PySys_WriteStderr("# %s has bad magic\n", + pathname); + Py_INCREF(Py_None); + return Py_None; /* signal caller to try alternative */ + } + + if (mtime != 0 && !eq_mtime(get_long((unsigned char *)buf + 4), + mtime)) { + if (Py_VerboseFlag) + PySys_WriteStderr("# %s has bad mtime\n", + pathname); + Py_INCREF(Py_None); + return Py_None; /* signal caller to try alternative */ + } + + code = PyMarshal_ReadObjectFromString(buf + 8, size - 8); + if (code == NULL) + return NULL; + if (!PyCode_Check(code)) { + Py_DECREF(code); + PyErr_Format(PyExc_TypeError, + "compiled module %.200s is not a code object", + pathname); + return NULL; + } + return code; } /* Replace any occurances of "\r\n?" in the input string with "\n". @@ -977,38 +977,38 @@ static PyObject * normalize_line_endings(PyObject *source) { - char *buf, *q, *p = PyBytes_AsString(source); - PyObject *fixed_source; - int len = 0; - - if (!p) { - return PyBytes_FromStringAndSize("\n\0", 2); - } - - /* one char extra for trailing \n and one for terminating \0 */ - buf = (char *)PyMem_Malloc(PyBytes_Size(source) + 2); - if (buf == NULL) { - PyErr_SetString(PyExc_MemoryError, - "zipimport: no memory to allocate " - "source buffer"); - return NULL; - } - /* replace "\r\n?" by "\n" */ - for (q = buf; *p != '\0'; p++) { - if (*p == '\r') { - *q++ = '\n'; - if (*(p + 1) == '\n') - p++; - } - else - *q++ = *p; - len++; - } - *q++ = '\n'; /* add trailing \n */ - *q = '\0'; - fixed_source = PyBytes_FromStringAndSize(buf, len + 2); - PyMem_Free(buf); - return fixed_source; + char *buf, *q, *p = PyBytes_AsString(source); + PyObject *fixed_source; + int len = 0; + + if (!p) { + return PyBytes_FromStringAndSize("\n\0", 2); + } + + /* one char extra for trailing \n and one for terminating \0 */ + buf = (char *)PyMem_Malloc(PyBytes_Size(source) + 2); + if (buf == NULL) { + PyErr_SetString(PyExc_MemoryError, + "zipimport: no memory to allocate " + "source buffer"); + return NULL; + } + /* replace "\r\n?" by "\n" */ + for (q = buf; *p != '\0'; p++) { + if (*p == '\r') { + *q++ = '\n'; + if (*(p + 1) == '\n') + p++; + } + else + *q++ = *p; + len++; + } + *q++ = '\n'; /* add trailing \n */ + *q = '\0'; + fixed_source = PyBytes_FromStringAndSize(buf, len + 2); + PyMem_Free(buf); + return fixed_source; } /* Given a string buffer containing Python source code, compile it @@ -1016,16 +1016,16 @@ static PyObject * compile_source(char *pathname, PyObject *source) { - PyObject *code, *fixed_source; + PyObject *code, *fixed_source; - fixed_source = normalize_line_endings(source); - if (fixed_source == NULL) - return NULL; - - code = Py_CompileString(PyBytes_AsString(fixed_source), pathname, - Py_file_input); - Py_DECREF(fixed_source); - return code; + fixed_source = normalize_line_endings(source); + if (fixed_source == NULL) + return NULL; + + code = Py_CompileString(PyBytes_AsString(fixed_source), pathname, + Py_file_input); + Py_DECREF(fixed_source); + return code; } /* Convert the date/time values found in the Zip archive to a value @@ -1033,19 +1033,19 @@ static time_t parse_dostime(int dostime, int dosdate) { - struct tm stm; + struct tm stm; - memset((void *) &stm, '\0', sizeof(stm)); + memset((void *) &stm, '\0', sizeof(stm)); - stm.tm_sec = (dostime & 0x1f) * 2; - stm.tm_min = (dostime >> 5) & 0x3f; - stm.tm_hour = (dostime >> 11) & 0x1f; - stm.tm_mday = dosdate & 0x1f; - stm.tm_mon = ((dosdate >> 5) & 0x0f) - 1; - stm.tm_year = ((dosdate >> 9) & 0x7f) + 80; - stm.tm_isdst = -1; /* wday/yday is ignored */ + stm.tm_sec = (dostime & 0x1f) * 2; + stm.tm_min = (dostime >> 5) & 0x3f; + stm.tm_hour = (dostime >> 11) & 0x1f; + stm.tm_mday = dosdate & 0x1f; + stm.tm_mon = ((dosdate >> 5) & 0x0f) - 1; + stm.tm_year = ((dosdate >> 9) & 0x7f) + 80; + stm.tm_isdst = -1; /* wday/yday is ignored */ - return mktime(&stm); + return mktime(&stm); } /* Given a path to a .pyc or .pyo file in the archive, return the @@ -1054,106 +1054,106 @@ static time_t get_mtime_of_source(ZipImporter *self, char *path) { - PyObject *toc_entry; - time_t mtime = 0; - Py_ssize_t lastchar = strlen(path) - 1; - char savechar = path[lastchar]; - path[lastchar] = '\0'; /* strip 'c' or 'o' from *.py[co] */ - toc_entry = PyDict_GetItemString(self->files, path); - if (toc_entry != NULL && PyTuple_Check(toc_entry) && - PyTuple_Size(toc_entry) == 8) { - /* fetch the time stamp of the .py file for comparison - with an embedded pyc time stamp */ - int time, date; - time = PyLong_AsLong(PyTuple_GetItem(toc_entry, 5)); - date = PyLong_AsLong(PyTuple_GetItem(toc_entry, 6)); - mtime = parse_dostime(time, date); - } - path[lastchar] = savechar; - return mtime; + PyObject *toc_entry; + time_t mtime = 0; + Py_ssize_t lastchar = strlen(path) - 1; + char savechar = path[lastchar]; + path[lastchar] = '\0'; /* strip 'c' or 'o' from *.py[co] */ + toc_entry = PyDict_GetItemString(self->files, path); + if (toc_entry != NULL && PyTuple_Check(toc_entry) && + PyTuple_Size(toc_entry) == 8) { + /* fetch the time stamp of the .py file for comparison + with an embedded pyc time stamp */ + int time, date; + time = PyLong_AsLong(PyTuple_GetItem(toc_entry, 5)); + date = PyLong_AsLong(PyTuple_GetItem(toc_entry, 6)); + mtime = parse_dostime(time, date); + } + path[lastchar] = savechar; + return mtime; } /* Return the code object for the module named by 'fullname' from the Zip archive as a new reference. */ static PyObject * get_code_from_data(ZipImporter *self, int ispackage, int isbytecode, - time_t mtime, PyObject *toc_entry) + time_t mtime, PyObject *toc_entry) { - PyObject *data, *code; - char *modpath; - char *archive = _PyUnicode_AsString(self->archive); - - if (archive == NULL) - return NULL; - - data = get_data(archive, toc_entry); - if (data == NULL) - return NULL; - - modpath = _PyUnicode_AsString(PyTuple_GetItem(toc_entry, 0)); - - if (isbytecode) { - code = unmarshal_code(modpath, data, mtime); - } - else { - code = compile_source(modpath, data); - } - Py_DECREF(data); - return code; + PyObject *data, *code; + char *modpath; + char *archive = _PyUnicode_AsString(self->archive); + + if (archive == NULL) + return NULL; + + data = get_data(archive, toc_entry); + if (data == NULL) + return NULL; + + modpath = _PyUnicode_AsString(PyTuple_GetItem(toc_entry, 0)); + + if (isbytecode) { + code = unmarshal_code(modpath, data, mtime); + } + else { + code = compile_source(modpath, data); + } + Py_DECREF(data); + return code; } /* Get the code object assoiciated with the module specified by 'fullname'. */ static PyObject * get_module_code(ZipImporter *self, char *fullname, - int *p_ispackage, char **p_modpath) + int *p_ispackage, char **p_modpath) { - PyObject *toc_entry; - char *subname, path[MAXPATHLEN + 1]; - int len; - struct st_zip_searchorder *zso; - - subname = get_subname(fullname); - - len = make_filename(_PyUnicode_AsString(self->prefix), subname, path); - if (len < 0) - return NULL; - - for (zso = zip_searchorder; *zso->suffix; zso++) { - PyObject *code = NULL; - - strcpy(path + len, zso->suffix); - if (Py_VerboseFlag > 1) - PySys_WriteStderr("# trying %s%c%s\n", - _PyUnicode_AsString(self->archive), - (int)SEP, path); - toc_entry = PyDict_GetItemString(self->files, path); - if (toc_entry != NULL) { - time_t mtime = 0; - int ispackage = zso->type & IS_PACKAGE; - int isbytecode = zso->type & IS_BYTECODE; - - if (isbytecode) - mtime = get_mtime_of_source(self, path); - if (p_ispackage != NULL) - *p_ispackage = ispackage; - code = get_code_from_data(self, ispackage, - isbytecode, mtime, - toc_entry); - if (code == Py_None) { - /* bad magic number or non-matching mtime - in byte code, try next */ - Py_DECREF(code); - continue; - } - if (code != NULL && p_modpath != NULL) - *p_modpath = _PyUnicode_AsString( - PyTuple_GetItem(toc_entry, 0)); - return code; - } - } - PyErr_Format(ZipImportError, "can't find module '%.200s'", fullname); - return NULL; + PyObject *toc_entry; + char *subname, path[MAXPATHLEN + 1]; + int len; + struct st_zip_searchorder *zso; + + subname = get_subname(fullname); + + len = make_filename(_PyUnicode_AsString(self->prefix), subname, path); + if (len < 0) + return NULL; + + for (zso = zip_searchorder; *zso->suffix; zso++) { + PyObject *code = NULL; + + strcpy(path + len, zso->suffix); + if (Py_VerboseFlag > 1) + PySys_WriteStderr("# trying %s%c%s\n", + _PyUnicode_AsString(self->archive), + (int)SEP, path); + toc_entry = PyDict_GetItemString(self->files, path); + if (toc_entry != NULL) { + time_t mtime = 0; + int ispackage = zso->type & IS_PACKAGE; + int isbytecode = zso->type & IS_BYTECODE; + + if (isbytecode) + mtime = get_mtime_of_source(self, path); + if (p_ispackage != NULL) + *p_ispackage = ispackage; + code = get_code_from_data(self, ispackage, + isbytecode, mtime, + toc_entry); + if (code == Py_None) { + /* bad magic number or non-matching mtime + in byte code, try next */ + Py_DECREF(code); + continue; + } + if (code != NULL && p_modpath != NULL) + *p_modpath = _PyUnicode_AsString( + PyTuple_GetItem(toc_entry, 0)); + return code; + } + } + PyErr_Format(ZipImportError, "can't find module '%.200s'", fullname); + return NULL; } @@ -1174,65 +1174,65 @@ to Zip archives."); static struct PyModuleDef zipimportmodule = { - PyModuleDef_HEAD_INIT, - "zipimport", - zipimport_doc, - -1, - NULL, - NULL, - NULL, - NULL, - NULL + PyModuleDef_HEAD_INIT, + "zipimport", + zipimport_doc, + -1, + NULL, + NULL, + NULL, + NULL, + NULL }; PyMODINIT_FUNC PyInit_zipimport(void) { - PyObject *mod; + PyObject *mod; + + if (PyType_Ready(&ZipImporter_Type) < 0) + return NULL; + + /* Correct directory separator */ + zip_searchorder[0].suffix[0] = SEP; + zip_searchorder[1].suffix[0] = SEP; + zip_searchorder[2].suffix[0] = SEP; + if (Py_OptimizeFlag) { + /* Reverse *.pyc and *.pyo */ + struct st_zip_searchorder tmp; + tmp = zip_searchorder[0]; + zip_searchorder[0] = zip_searchorder[1]; + zip_searchorder[1] = tmp; + tmp = zip_searchorder[3]; + zip_searchorder[3] = zip_searchorder[4]; + zip_searchorder[4] = tmp; + } + + mod = PyModule_Create(&zipimportmodule); + if (mod == NULL) + return NULL; - if (PyType_Ready(&ZipImporter_Type) < 0) - return NULL; + ZipImportError = PyErr_NewException("zipimport.ZipImportError", + PyExc_ImportError, NULL); + if (ZipImportError == NULL) + return NULL; - /* Correct directory separator */ - zip_searchorder[0].suffix[0] = SEP; - zip_searchorder[1].suffix[0] = SEP; - zip_searchorder[2].suffix[0] = SEP; - if (Py_OptimizeFlag) { - /* Reverse *.pyc and *.pyo */ - struct st_zip_searchorder tmp; - tmp = zip_searchorder[0]; - zip_searchorder[0] = zip_searchorder[1]; - zip_searchorder[1] = tmp; - tmp = zip_searchorder[3]; - zip_searchorder[3] = zip_searchorder[4]; - zip_searchorder[4] = tmp; - } - - mod = PyModule_Create(&zipimportmodule); - if (mod == NULL) - return NULL; - - ZipImportError = PyErr_NewException("zipimport.ZipImportError", - PyExc_ImportError, NULL); - if (ZipImportError == NULL) - return NULL; - - Py_INCREF(ZipImportError); - if (PyModule_AddObject(mod, "ZipImportError", - ZipImportError) < 0) - return NULL; - - Py_INCREF(&ZipImporter_Type); - if (PyModule_AddObject(mod, "zipimporter", - (PyObject *)&ZipImporter_Type) < 0) - return NULL; - - zip_directory_cache = PyDict_New(); - if (zip_directory_cache == NULL) - return NULL; - Py_INCREF(zip_directory_cache); - if (PyModule_AddObject(mod, "_zip_directory_cache", - zip_directory_cache) < 0) - return NULL; - return mod; + Py_INCREF(ZipImportError); + if (PyModule_AddObject(mod, "ZipImportError", + ZipImportError) < 0) + return NULL; + + Py_INCREF(&ZipImporter_Type); + if (PyModule_AddObject(mod, "zipimporter", + (PyObject *)&ZipImporter_Type) < 0) + return NULL; + + zip_directory_cache = PyDict_New(); + if (zip_directory_cache == NULL) + return NULL; + Py_INCREF(zip_directory_cache); + if (PyModule_AddObject(mod, "_zip_directory_cache", + zip_directory_cache) < 0) + return NULL; + return mod; } Modified: python/branches/py3k-jit/Modules/zlibmodule.c ============================================================================== --- python/branches/py3k-jit/Modules/zlibmodule.c (original) +++ python/branches/py3k-jit/Modules/zlibmodule.c Mon May 10 23:55:43 2010 @@ -53,9 +53,9 @@ zlib_error(z_stream zst, int err, char *msg) { if (zst.msg == Z_NULL) - PyErr_Format(ZlibError, "Error %d %s", err, msg); + PyErr_Format(ZlibError, "Error %d %s", err, msg); else - PyErr_Format(ZlibError, "Error %d %s: %.200s", err, msg, zst.msg); + PyErr_Format(ZlibError, "Error %d %s: %.200s", err, msg, zst.msg); } PyDoc_STRVAR(compressobj__doc__, @@ -74,17 +74,17 @@ compobject *self; self = PyObject_New(compobject, type); if (self == NULL) - return NULL; + return NULL; self->is_initialised = 0; self->unused_data = PyBytes_FromStringAndSize("", 0); if (self->unused_data == NULL) { - Py_DECREF(self); - return NULL; + Py_DECREF(self); + return NULL; } self->unconsumed_tail = PyBytes_FromStringAndSize("", 0); if (self->unconsumed_tail == NULL) { - Py_DECREF(self); - return NULL; + Py_DECREF(self); + return NULL; } #ifdef WITH_THREAD self->lock = PyThread_allocate_lock(); @@ -108,7 +108,7 @@ /* require Python string object, optional 'level' arg */ if (!PyArg_ParseTuple(args, "y*|i:compress", &pinput, &level)) - return NULL; + return NULL; input = pinput.buf; length = pinput.len; @@ -116,10 +116,10 @@ output = (Byte*)malloc(zst.avail_out); if (output == NULL) { - PyBuffer_Release(&pinput); - PyErr_SetString(PyExc_MemoryError, - "Can't allocate memory to compress data"); - return NULL; + PyBuffer_Release(&pinput); + PyErr_SetString(PyExc_MemoryError, + "Can't allocate memory to compress data"); + return NULL; } /* Past the point of no return. From here on out, we need to make sure @@ -134,19 +134,19 @@ switch(err) { case(Z_OK): - break; + break; case(Z_MEM_ERROR): - PyErr_SetString(PyExc_MemoryError, - "Out of memory while compressing data"); - goto error; + PyErr_SetString(PyExc_MemoryError, + "Out of memory while compressing data"); + goto error; case(Z_STREAM_ERROR): - PyErr_SetString(ZlibError, - "Bad compression level"); - goto error; + PyErr_SetString(ZlibError, + "Bad compression level"); + goto error; default: deflateEnd(&zst); - zlib_error(zst, err, "while compressing data"); - goto error; + zlib_error(zst, err, "while compressing data"); + goto error; } Py_BEGIN_ALLOW_THREADS; @@ -154,17 +154,17 @@ Py_END_ALLOW_THREADS; if (err != Z_STREAM_END) { - zlib_error(zst, err, "while compressing data"); - deflateEnd(&zst); - goto error; + zlib_error(zst, err, "while compressing data"); + deflateEnd(&zst); + goto error; } err=deflateEnd(&zst); if (err == Z_OK) - ReturnVal = PyBytes_FromStringAndSize((char *)output, + ReturnVal = PyBytes_FromStringAndSize((char *)output, zst.total_out); else - zlib_error(zst, err, "while finishing compression"); + zlib_error(zst, err, "while finishing compression"); error: PyBuffer_Release(&pinput); @@ -191,20 +191,20 @@ z_stream zst; if (!PyArg_ParseTuple(args, "y*|in:decompress", - &pinput, &wsize, &r_strlen)) - return NULL; + &pinput, &wsize, &r_strlen)) + return NULL; input = pinput.buf; length = pinput.len; if (r_strlen <= 0) - r_strlen = 1; + r_strlen = 1; zst.avail_in = length; zst.avail_out = r_strlen; if (!(result_str = PyBytes_FromStringAndSize(NULL, r_strlen))) { - PyBuffer_Release(&pinput); - return NULL; + PyBuffer_Release(&pinput); + return NULL; } zst.zalloc = (alloc_func)NULL; @@ -215,60 +215,60 @@ switch(err) { case(Z_OK): - break; + break; case(Z_MEM_ERROR): - PyErr_SetString(PyExc_MemoryError, - "Out of memory while decompressing data"); - goto error; + PyErr_SetString(PyExc_MemoryError, + "Out of memory while decompressing data"); + goto error; default: inflateEnd(&zst); - zlib_error(zst, err, "while preparing to decompress data"); - goto error; + zlib_error(zst, err, "while preparing to decompress data"); + goto error; } do { - Py_BEGIN_ALLOW_THREADS - err=inflate(&zst, Z_FINISH); - Py_END_ALLOW_THREADS - - switch(err) { - case(Z_STREAM_END): - break; - case(Z_BUF_ERROR): - /* - * If there is at least 1 byte of room according to zst.avail_out - * and we get this error, assume that it means zlib cannot - * process the inflate call() due to an error in the data. - */ - if (zst.avail_out > 0) { - PyErr_Format(ZlibError, "Error %i while decompressing data", - err); - inflateEnd(&zst); - goto error; - } - /* fall through */ - case(Z_OK): - /* need more memory */ - if (_PyBytes_Resize(&result_str, r_strlen << 1) < 0) { - inflateEnd(&zst); - goto error; - } - zst.next_out = + Py_BEGIN_ALLOW_THREADS + err=inflate(&zst, Z_FINISH); + Py_END_ALLOW_THREADS + + switch(err) { + case(Z_STREAM_END): + break; + case(Z_BUF_ERROR): + /* + * If there is at least 1 byte of room according to zst.avail_out + * and we get this error, assume that it means zlib cannot + * process the inflate call() due to an error in the data. + */ + if (zst.avail_out > 0) { + PyErr_Format(ZlibError, "Error %i while decompressing data", + err); + inflateEnd(&zst); + goto error; + } + /* fall through */ + case(Z_OK): + /* need more memory */ + if (_PyBytes_Resize(&result_str, r_strlen << 1) < 0) { + inflateEnd(&zst); + goto error; + } + zst.next_out = (unsigned char *)PyBytes_AS_STRING(result_str) + r_strlen; - zst.avail_out = r_strlen; - r_strlen = r_strlen << 1; - break; - default: - inflateEnd(&zst); - zlib_error(zst, err, "while decompressing data"); - goto error; - } + zst.avail_out = r_strlen; + r_strlen = r_strlen << 1; + break; + default: + inflateEnd(&zst); + zlib_error(zst, err, "while decompressing data"); + goto error; + } } while (err != Z_STREAM_END); err = inflateEnd(&zst); if (err != Z_OK) { - zlib_error(zst, err, "while finishing data decompression"); - goto error; + zlib_error(zst, err, "while finishing data decompression"); + goto error; } if (_PyBytes_Resize(&result_str, zst.total_out) < 0) @@ -291,12 +291,12 @@ int wbits=MAX_WBITS, memLevel=DEF_MEM_LEVEL, strategy=0, err; if (!PyArg_ParseTuple(args, "|iiiii:compressobj", &level, &method, &wbits, - &memLevel, &strategy)) - return NULL; + &memLevel, &strategy)) + return NULL; self = newcompobject(&Comptype); if (self==NULL) - return(NULL); + return(NULL); self->zst.zalloc = (alloc_func)NULL; self->zst.zfree = (free_func)Z_NULL; self->zst.next_in = NULL; @@ -304,21 +304,21 @@ err = deflateInit2(&self->zst, level, method, wbits, memLevel, strategy); switch(err) { case (Z_OK): - self->is_initialised = 1; - return (PyObject*)self; + self->is_initialised = 1; + return (PyObject*)self; case (Z_MEM_ERROR): - Py_DECREF(self); - PyErr_SetString(PyExc_MemoryError, - "Can't allocate memory for compression object"); - return NULL; + Py_DECREF(self); + PyErr_SetString(PyExc_MemoryError, + "Can't allocate memory for compression object"); + return NULL; case(Z_STREAM_ERROR): - Py_DECREF(self); - PyErr_SetString(PyExc_ValueError, "Invalid initialization option"); - return NULL; + Py_DECREF(self); + PyErr_SetString(PyExc_ValueError, "Invalid initialization option"); + return NULL; default: - zlib_error(self->zst, err, "while creating compression object"); + zlib_error(self->zst, err, "while creating compression object"); Py_DECREF(self); - return NULL; + return NULL; } } @@ -328,11 +328,11 @@ int wbits=DEF_WBITS, err; compobject *self; if (!PyArg_ParseTuple(args, "|i:decompressobj", &wbits)) - return NULL; + return NULL; self = newcompobject(&Decomptype); if (self == NULL) - return(NULL); + return(NULL); self->zst.zalloc = (alloc_func)NULL; self->zst.zfree = (free_func)Z_NULL; self->zst.next_in = NULL; @@ -340,21 +340,21 @@ err = inflateInit2(&self->zst, wbits); switch(err) { case (Z_OK): - self->is_initialised = 1; - return (PyObject*)self; + self->is_initialised = 1; + return (PyObject*)self; case(Z_STREAM_ERROR): - Py_DECREF(self); - PyErr_SetString(PyExc_ValueError, "Invalid initialization option"); - return NULL; + Py_DECREF(self); + PyErr_SetString(PyExc_ValueError, "Invalid initialization option"); + return NULL; case (Z_MEM_ERROR): - Py_DECREF(self); - PyErr_SetString(PyExc_MemoryError, - "Can't allocate memory for decompression object"); - return NULL; + Py_DECREF(self); + PyErr_SetString(PyExc_MemoryError, + "Can't allocate memory for decompression object"); + return NULL; default: - zlib_error(self->zst, err, "while creating decompression object"); + zlib_error(self->zst, err, "while creating decompression object"); Py_DECREF(self); - return NULL; + return NULL; } } @@ -404,13 +404,13 @@ unsigned long start_total_out; if (!PyArg_ParseTuple(args, "y*:compress", &pinput)) - return NULL; + return NULL; input = pinput.buf; inplen = pinput.len; if (!(RetVal = PyBytes_FromStringAndSize(NULL, length))) { - PyBuffer_Release(&pinput); - return NULL; + PyBuffer_Release(&pinput); + return NULL; } ENTER_ZLIB(self); @@ -428,19 +428,19 @@ /* while Z_OK and the output buffer is full, there might be more output, so extend the output buffer and try again */ while (err == Z_OK && self->zst.avail_out == 0) { - if (_PyBytes_Resize(&RetVal, length << 1) < 0) { + if (_PyBytes_Resize(&RetVal, length << 1) < 0) { Py_DECREF(RetVal); RetVal = NULL; - goto error; + goto error; } - self->zst.next_out = + self->zst.next_out = (unsigned char *)PyBytes_AS_STRING(RetVal) + length; - self->zst.avail_out = length; - length = length << 1; + self->zst.avail_out = length; + length = length << 1; - Py_BEGIN_ALLOW_THREADS - err = deflate(&(self->zst), Z_NO_FLUSH); - Py_END_ALLOW_THREADS + Py_BEGIN_ALLOW_THREADS + err = deflate(&(self->zst), Z_NO_FLUSH); + Py_END_ALLOW_THREADS } /* We will only get Z_BUF_ERROR if the output buffer was full but there wasn't more output when we tried again, so it is not an error @@ -448,10 +448,10 @@ */ if (err != Z_OK && err != Z_BUF_ERROR) { - zlib_error(self->zst, err, "while compressing"); - Py_DECREF(RetVal); - RetVal = NULL; - goto error; + zlib_error(self->zst, err, "while compressing"); + Py_DECREF(RetVal); + RetVal = NULL; + goto error; } if (_PyBytes_Resize(&RetVal, self->zst.total_out - start_total_out) < 0) { Py_DECREF(RetVal); @@ -486,23 +486,23 @@ unsigned long start_total_out; if (!PyArg_ParseTuple(args, "y*|i:decompress", &pinput, - &max_length)) - return NULL; + &max_length)) + return NULL; input = pinput.buf; inplen = pinput.len; if (max_length < 0) { - PyBuffer_Release(&pinput); - PyErr_SetString(PyExc_ValueError, - "max_length must be greater than zero"); - return NULL; + PyBuffer_Release(&pinput); + PyErr_SetString(PyExc_ValueError, + "max_length must be greater than zero"); + return NULL; } /* limit amount of data allocated to max_length */ if (max_length && length > max_length) - length = max_length; + length = max_length; if (!(RetVal = PyBytes_FromStringAndSize(NULL, length))) { - PyBuffer_Release(&pinput); - return NULL; + PyBuffer_Release(&pinput); + return NULL; } ENTER_ZLIB(self); @@ -521,43 +521,43 @@ So extend the output buffer and try again. */ while (err == Z_OK && self->zst.avail_out == 0) { - /* If max_length set, don't continue decompressing if we've already - reached the limit. - */ - if (max_length && length >= max_length) - break; - - /* otherwise, ... */ - old_length = length; - length = length << 1; - if (max_length && length > max_length) - length = max_length; + /* If max_length set, don't continue decompressing if we've already + reached the limit. + */ + if (max_length && length >= max_length) + break; + + /* otherwise, ... */ + old_length = length; + length = length << 1; + if (max_length && length > max_length) + length = max_length; - if (_PyBytes_Resize(&RetVal, length) < 0) { + if (_PyBytes_Resize(&RetVal, length) < 0) { Py_DECREF(RetVal); RetVal = NULL; - goto error; + goto error; } - self->zst.next_out = + self->zst.next_out = (unsigned char *)PyBytes_AS_STRING(RetVal) + old_length; - self->zst.avail_out = length - old_length; + self->zst.avail_out = length - old_length; - Py_BEGIN_ALLOW_THREADS - err = inflate(&(self->zst), Z_SYNC_FLUSH); - Py_END_ALLOW_THREADS + Py_BEGIN_ALLOW_THREADS + err = inflate(&(self->zst), Z_SYNC_FLUSH); + Py_END_ALLOW_THREADS } /* Not all of the compressed data could be accommodated in the output buffer of specified size. Return the unconsumed tail in an attribute.*/ if(max_length) { - Py_DECREF(self->unconsumed_tail); - self->unconsumed_tail = PyBytes_FromStringAndSize((char *)self->zst.next_in, - self->zst.avail_in); - if(!self->unconsumed_tail) { - Py_DECREF(RetVal); - RetVal = NULL; - goto error; - } + Py_DECREF(self->unconsumed_tail); + self->unconsumed_tail = PyBytes_FromStringAndSize((char *)self->zst.next_in, + self->zst.avail_in); + if(!self->unconsumed_tail) { + Py_DECREF(RetVal); + RetVal = NULL; + goto error; + } } /* The end of the compressed data has been reached, so set the @@ -567,22 +567,22 @@ preserved. */ if (err == Z_STREAM_END) { - Py_XDECREF(self->unused_data); /* Free original empty string */ - self->unused_data = PyBytes_FromStringAndSize( - (char *)self->zst.next_in, self->zst.avail_in); - if (self->unused_data == NULL) { - Py_DECREF(RetVal); - goto error; - } - /* We will only get Z_BUF_ERROR if the output buffer was full - but there wasn't more output when we tried again, so it is - not an error condition. - */ + Py_XDECREF(self->unused_data); /* Free original empty string */ + self->unused_data = PyBytes_FromStringAndSize( + (char *)self->zst.next_in, self->zst.avail_in); + if (self->unused_data == NULL) { + Py_DECREF(RetVal); + goto error; + } + /* We will only get Z_BUF_ERROR if the output buffer was full + but there wasn't more output when we tried again, so it is + not an error condition. + */ } else if (err != Z_OK && err != Z_BUF_ERROR) { - zlib_error(self->zst, err, "while decompressing"); - Py_DECREF(RetVal); - RetVal = NULL; - goto error; + zlib_error(self->zst, err, "while decompressing"); + Py_DECREF(RetVal); + RetVal = NULL; + goto error; } if (_PyBytes_Resize(&RetVal, self->zst.total_out - start_total_out) < 0) { @@ -613,16 +613,16 @@ unsigned long start_total_out; if (!PyArg_ParseTuple(args, "|i:flush", &flushmode)) - return NULL; + return NULL; /* Flushing with Z_NO_FLUSH is a no-op, so there's no point in doing any work at all; just return an empty string. */ if (flushmode == Z_NO_FLUSH) { - return PyBytes_FromStringAndSize(NULL, 0); + return PyBytes_FromStringAndSize(NULL, 0); } if (!(RetVal = PyBytes_FromStringAndSize(NULL, length))) - return NULL; + return NULL; ENTER_ZLIB(self); @@ -638,44 +638,44 @@ /* while Z_OK and the output buffer is full, there might be more output, so extend the output buffer and try again */ while (err == Z_OK && self->zst.avail_out == 0) { - if (_PyBytes_Resize(&RetVal, length << 1) < 0) { + if (_PyBytes_Resize(&RetVal, length << 1) < 0) { Py_DECREF(RetVal); RetVal = NULL; - goto error; + goto error; } - self->zst.next_out = + self->zst.next_out = (unsigned char *)PyBytes_AS_STRING(RetVal) + length; - self->zst.avail_out = length; - length = length << 1; + self->zst.avail_out = length; + length = length << 1; - Py_BEGIN_ALLOW_THREADS - err = deflate(&(self->zst), flushmode); - Py_END_ALLOW_THREADS + Py_BEGIN_ALLOW_THREADS + err = deflate(&(self->zst), flushmode); + Py_END_ALLOW_THREADS } /* If flushmode is Z_FINISH, we also have to call deflateEnd() to free various data structures. Note we should only get Z_STREAM_END when flushmode is Z_FINISH, but checking both for safety*/ if (err == Z_STREAM_END && flushmode == Z_FINISH) { - err = deflateEnd(&(self->zst)); - if (err != Z_OK) { - zlib_error(self->zst, err, "from deflateEnd()"); - Py_DECREF(RetVal); - RetVal = NULL; - goto error; - } - else - self->is_initialised = 0; - - /* We will only get Z_BUF_ERROR if the output buffer was full - but there wasn't more output when we tried again, so it is - not an error condition. - */ + err = deflateEnd(&(self->zst)); + if (err != Z_OK) { + zlib_error(self->zst, err, "from deflateEnd()"); + Py_DECREF(RetVal); + RetVal = NULL; + goto error; + } + else + self->is_initialised = 0; + + /* We will only get Z_BUF_ERROR if the output buffer was full + but there wasn't more output when we tried again, so it is + not an error condition. + */ } else if (err!=Z_OK && err!=Z_BUF_ERROR) { - zlib_error(self->zst, err, "while flushing"); - Py_DECREF(RetVal); - RetVal = NULL; - goto error; + zlib_error(self->zst, err, "while flushing"); + Py_DECREF(RetVal); + RetVal = NULL; + goto error; } if (_PyBytes_Resize(&RetVal, self->zst.total_out - start_total_out) < 0) { @@ -807,13 +807,13 @@ unsigned long start_total_out; if (!PyArg_ParseTuple(args, "|i:flush", &length)) - return NULL; + return NULL; if (length <= 0) { - PyErr_SetString(PyExc_ValueError, "length must be greater than zero"); - return NULL; + PyErr_SetString(PyExc_ValueError, "length must be greater than zero"); + return NULL; } if (!(retval = PyBytes_FromStringAndSize(NULL, length))) - return NULL; + return NULL; ENTER_ZLIB(self); @@ -829,32 +829,32 @@ /* while Z_OK and the output buffer is full, there might be more output, so extend the output buffer and try again */ while ((err == Z_OK || err == Z_BUF_ERROR) && self->zst.avail_out == 0) { - if (_PyBytes_Resize(&retval, length << 1) < 0) { + if (_PyBytes_Resize(&retval, length << 1) < 0) { Py_DECREF(retval); retval = NULL; - goto error; + goto error; } - self->zst.next_out = (Byte *)PyBytes_AS_STRING(retval) + length; - self->zst.avail_out = length; - length = length << 1; - - Py_BEGIN_ALLOW_THREADS - err = inflate(&(self->zst), Z_FINISH); - Py_END_ALLOW_THREADS + self->zst.next_out = (Byte *)PyBytes_AS_STRING(retval) + length; + self->zst.avail_out = length; + length = length << 1; + + Py_BEGIN_ALLOW_THREADS + err = inflate(&(self->zst), Z_FINISH); + Py_END_ALLOW_THREADS } /* If flushmode is Z_FINISH, we also have to call deflateEnd() to free various data structures. Note we should only get Z_STREAM_END when flushmode is Z_FINISH */ if (err == Z_STREAM_END) { - err = inflateEnd(&(self->zst)); + err = inflateEnd(&(self->zst)); self->is_initialised = 0; - if (err != Z_OK) { - zlib_error(self->zst, err, "from inflateEnd()"); - Py_DECREF(retval); - retval = NULL; - goto error; - } + if (err != Z_OK) { + zlib_error(self->zst, err, "from inflateEnd()"); + Py_DECREF(retval); + retval = NULL; + goto error; + } } if (_PyBytes_Resize(&retval, self->zst.total_out - start_total_out) < 0) { Py_DECREF(retval); @@ -942,7 +942,7 @@ int signed_val; if (!PyArg_ParseTuple(args, "y*|I:crc32", &pbuf, &crc32val)) - return NULL; + return NULL; /* Releasing the GIL for very small buffers is inefficient and may lower performance */ if (pbuf.len > 1024*5) { @@ -950,7 +950,7 @@ signed_val = crc32(crc32val, pbuf.buf, pbuf.len); Py_END_ALLOW_THREADS } else { - signed_val = crc32(crc32val, pbuf.buf, pbuf.len); + signed_val = crc32(crc32val, pbuf.buf, pbuf.len); } PyBuffer_Release(&pbuf); return PyLong_FromUnsignedLong(signed_val & 0xffffffffU); @@ -1053,15 +1053,15 @@ "objects support decompress() and flush()."); static struct PyModuleDef zlibmodule = { - PyModuleDef_HEAD_INIT, - "zlib", - zlib_module_documentation, - -1, - zlib_methods, - NULL, - NULL, - NULL, - NULL + PyModuleDef_HEAD_INIT, + "zlib", + zlib_module_documentation, + -1, + zlib_methods, + NULL, + NULL, + NULL, + NULL }; PyMODINIT_FUNC @@ -1069,17 +1069,17 @@ { PyObject *m, *ver; if (PyType_Ready(&Comptype) < 0) - return NULL; + return NULL; if (PyType_Ready(&Decomptype) < 0) - return NULL; + return NULL; m = PyModule_Create(&zlibmodule); if (m == NULL) - return NULL; + return NULL; ZlibError = PyErr_NewException("zlib.error", NULL, NULL); if (ZlibError != NULL) { Py_INCREF(ZlibError); - PyModule_AddObject(m, "error", ZlibError); + PyModule_AddObject(m, "error", ZlibError); } PyModule_AddIntConstant(m, "MAX_WBITS", MAX_WBITS); PyModule_AddIntConstant(m, "DEFLATED", DEFLATED); @@ -1098,7 +1098,7 @@ ver = PyUnicode_FromString(ZLIB_VERSION); if (ver != NULL) - PyModule_AddObject(m, "ZLIB_VERSION", ver); + PyModule_AddObject(m, "ZLIB_VERSION", ver); PyModule_AddStringConstant(m, "__version__", "1.0"); Modified: python/branches/py3k-jit/Objects/abstract.c ============================================================================== --- python/branches/py3k-jit/Objects/abstract.c (original) +++ python/branches/py3k-jit/Objects/abstract.c Mon May 10 23:55:43 2010 @@ -12,17 +12,17 @@ static PyObject * type_error(const char *msg, PyObject *obj) { - PyErr_Format(PyExc_TypeError, msg, obj->ob_type->tp_name); - return NULL; + PyErr_Format(PyExc_TypeError, msg, obj->ob_type->tp_name); + return NULL; } static PyObject * null_error(void) { - if (!PyErr_Occurred()) - PyErr_SetString(PyExc_SystemError, - "null argument to internal routine"); - return NULL; + if (!PyErr_Occurred()) + PyErr_SetString(PyExc_SystemError, + "null argument to internal routine"); + return NULL; } /* Operations on any object */ @@ -30,37 +30,37 @@ PyObject * PyObject_Type(PyObject *o) { - PyObject *v; + PyObject *v; - if (o == NULL) - return null_error(); - v = (PyObject *)o->ob_type; - Py_INCREF(v); - return v; + if (o == NULL) + return null_error(); + v = (PyObject *)o->ob_type; + Py_INCREF(v); + return v; } Py_ssize_t PyObject_Size(PyObject *o) { - PySequenceMethods *m; + PySequenceMethods *m; - if (o == NULL) { - null_error(); - return -1; - } - - m = o->ob_type->tp_as_sequence; - if (m && m->sq_length) - return m->sq_length(o); + if (o == NULL) { + null_error(); + return -1; + } + + m = o->ob_type->tp_as_sequence; + if (m && m->sq_length) + return m->sq_length(o); - return PyMapping_Size(o); + return PyMapping_Size(o); } #undef PyObject_Length Py_ssize_t PyObject_Length(PyObject *o) { - return PyObject_Size(o); + return PyObject_Size(o); } #define PyObject_Length PyObject_Size @@ -74,149 +74,149 @@ Py_ssize_t _PyObject_LengthHint(PyObject *o, Py_ssize_t defaultvalue) { - static PyObject *hintstrobj = NULL; - PyObject *ro, *hintmeth; - Py_ssize_t rv; - - /* try o.__len__() */ - rv = PyObject_Size(o); - if (rv >= 0) - return rv; - if (PyErr_Occurred()) { - if (!PyErr_ExceptionMatches(PyExc_TypeError)) - return -1; - PyErr_Clear(); - } - - /* try o.__length_hint__() */ - hintmeth = _PyObject_LookupSpecial(o, "__length_hint__", &hintstrobj); - if (hintmeth == NULL) { - if (PyErr_Occurred()) - return -1; - else - return defaultvalue; - } - ro = PyObject_CallFunctionObjArgs(hintmeth, NULL); - Py_DECREF(hintmeth); - if (ro == NULL) { - if (!PyErr_ExceptionMatches(PyExc_TypeError)) - return -1; - PyErr_Clear(); - return defaultvalue; - } - rv = PyLong_Check(ro) ? PyLong_AsSsize_t(ro) : defaultvalue; - Py_DECREF(ro); - return rv; + static PyObject *hintstrobj = NULL; + PyObject *ro, *hintmeth; + Py_ssize_t rv; + + /* try o.__len__() */ + rv = PyObject_Size(o); + if (rv >= 0) + return rv; + if (PyErr_Occurred()) { + if (!PyErr_ExceptionMatches(PyExc_TypeError)) + return -1; + PyErr_Clear(); + } + + /* try o.__length_hint__() */ + hintmeth = _PyObject_LookupSpecial(o, "__length_hint__", &hintstrobj); + if (hintmeth == NULL) { + if (PyErr_Occurred()) + return -1; + else + return defaultvalue; + } + ro = PyObject_CallFunctionObjArgs(hintmeth, NULL); + Py_DECREF(hintmeth); + if (ro == NULL) { + if (!PyErr_ExceptionMatches(PyExc_TypeError)) + return -1; + PyErr_Clear(); + return defaultvalue; + } + rv = PyLong_Check(ro) ? PyLong_AsSsize_t(ro) : defaultvalue; + Py_DECREF(ro); + return rv; } PyObject * PyObject_GetItem(PyObject *o, PyObject *key) { - PyMappingMethods *m; + PyMappingMethods *m; - if (o == NULL || key == NULL) - return null_error(); + if (o == NULL || key == NULL) + return null_error(); - m = o->ob_type->tp_as_mapping; - if (m && m->mp_subscript) - return m->mp_subscript(o, key); - - if (o->ob_type->tp_as_sequence) { - if (PyIndex_Check(key)) { - Py_ssize_t key_value; - key_value = PyNumber_AsSsize_t(key, PyExc_IndexError); - if (key_value == -1 && PyErr_Occurred()) - return NULL; - return PySequence_GetItem(o, key_value); - } - else if (o->ob_type->tp_as_sequence->sq_item) - return type_error("sequence index must " - "be integer, not '%.200s'", key); - } + m = o->ob_type->tp_as_mapping; + if (m && m->mp_subscript) + return m->mp_subscript(o, key); + + if (o->ob_type->tp_as_sequence) { + if (PyIndex_Check(key)) { + Py_ssize_t key_value; + key_value = PyNumber_AsSsize_t(key, PyExc_IndexError); + if (key_value == -1 && PyErr_Occurred()) + return NULL; + return PySequence_GetItem(o, key_value); + } + else if (o->ob_type->tp_as_sequence->sq_item) + return type_error("sequence index must " + "be integer, not '%.200s'", key); + } - return type_error("'%.200s' object is not subscriptable", o); + return type_error("'%.200s' object is not subscriptable", o); } int PyObject_SetItem(PyObject *o, PyObject *key, PyObject *value) { - PyMappingMethods *m; + PyMappingMethods *m; - if (o == NULL || key == NULL || value == NULL) { - null_error(); - return -1; - } - m = o->ob_type->tp_as_mapping; - if (m && m->mp_ass_subscript) - return m->mp_ass_subscript(o, key, value); - - if (o->ob_type->tp_as_sequence) { - if (PyIndex_Check(key)) { - Py_ssize_t key_value; - key_value = PyNumber_AsSsize_t(key, PyExc_IndexError); - if (key_value == -1 && PyErr_Occurred()) - return -1; - return PySequence_SetItem(o, key_value, value); - } - else if (o->ob_type->tp_as_sequence->sq_ass_item) { - type_error("sequence index must be " - "integer, not '%.200s'", key); - return -1; - } - } + if (o == NULL || key == NULL || value == NULL) { + null_error(); + return -1; + } + m = o->ob_type->tp_as_mapping; + if (m && m->mp_ass_subscript) + return m->mp_ass_subscript(o, key, value); + + if (o->ob_type->tp_as_sequence) { + if (PyIndex_Check(key)) { + Py_ssize_t key_value; + key_value = PyNumber_AsSsize_t(key, PyExc_IndexError); + if (key_value == -1 && PyErr_Occurred()) + return -1; + return PySequence_SetItem(o, key_value, value); + } + else if (o->ob_type->tp_as_sequence->sq_ass_item) { + type_error("sequence index must be " + "integer, not '%.200s'", key); + return -1; + } + } - type_error("'%.200s' object does not support item assignment", o); - return -1; + type_error("'%.200s' object does not support item assignment", o); + return -1; } int PyObject_DelItem(PyObject *o, PyObject *key) { - PyMappingMethods *m; + PyMappingMethods *m; - if (o == NULL || key == NULL) { - null_error(); - return -1; - } - m = o->ob_type->tp_as_mapping; - if (m && m->mp_ass_subscript) - return m->mp_ass_subscript(o, key, (PyObject*)NULL); - - if (o->ob_type->tp_as_sequence) { - if (PyIndex_Check(key)) { - Py_ssize_t key_value; - key_value = PyNumber_AsSsize_t(key, PyExc_IndexError); - if (key_value == -1 && PyErr_Occurred()) - return -1; - return PySequence_DelItem(o, key_value); - } - else if (o->ob_type->tp_as_sequence->sq_ass_item) { - type_error("sequence index must be " - "integer, not '%.200s'", key); - return -1; - } - } + if (o == NULL || key == NULL) { + null_error(); + return -1; + } + m = o->ob_type->tp_as_mapping; + if (m && m->mp_ass_subscript) + return m->mp_ass_subscript(o, key, (PyObject*)NULL); + + if (o->ob_type->tp_as_sequence) { + if (PyIndex_Check(key)) { + Py_ssize_t key_value; + key_value = PyNumber_AsSsize_t(key, PyExc_IndexError); + if (key_value == -1 && PyErr_Occurred()) + return -1; + return PySequence_DelItem(o, key_value); + } + else if (o->ob_type->tp_as_sequence->sq_ass_item) { + type_error("sequence index must be " + "integer, not '%.200s'", key); + return -1; + } + } - type_error("'%.200s' object does not support item deletion", o); - return -1; + type_error("'%.200s' object does not support item deletion", o); + return -1; } int PyObject_DelItemString(PyObject *o, char *key) { - PyObject *okey; - int ret; + PyObject *okey; + int ret; - if (o == NULL || key == NULL) { - null_error(); - return -1; - } - okey = PyUnicode_FromString(key); - if (okey == NULL) - return -1; - ret = PyObject_DelItem(o, okey); - Py_DECREF(okey); - return ret; + if (o == NULL || key == NULL) { + null_error(); + return -1; + } + okey = PyUnicode_FromString(key); + if (okey == NULL) + return -1; + ret = PyObject_DelItem(o, okey); + Py_DECREF(okey); + return ret; } /* We release the buffer right after use of this function which could @@ -224,104 +224,104 @@ */ int PyObject_AsCharBuffer(PyObject *obj, - const char **buffer, - Py_ssize_t *buffer_len) + const char **buffer, + Py_ssize_t *buffer_len) { - PyBufferProcs *pb; - Py_buffer view; + PyBufferProcs *pb; + Py_buffer view; - if (obj == NULL || buffer == NULL || buffer_len == NULL) { - null_error(); - return -1; - } - pb = obj->ob_type->tp_as_buffer; - if (pb == NULL || pb->bf_getbuffer == NULL) { - PyErr_SetString(PyExc_TypeError, - "expected an object with the buffer interface"); - return -1; - } - if ((*pb->bf_getbuffer)(obj, &view, PyBUF_SIMPLE)) return -1; - - *buffer = view.buf; - *buffer_len = view.len; - if (pb->bf_releasebuffer != NULL) - (*pb->bf_releasebuffer)(obj, &view); - Py_XDECREF(view.obj); - return 0; + if (obj == NULL || buffer == NULL || buffer_len == NULL) { + null_error(); + return -1; + } + pb = obj->ob_type->tp_as_buffer; + if (pb == NULL || pb->bf_getbuffer == NULL) { + PyErr_SetString(PyExc_TypeError, + "expected an object with the buffer interface"); + return -1; + } + if ((*pb->bf_getbuffer)(obj, &view, PyBUF_SIMPLE)) return -1; + + *buffer = view.buf; + *buffer_len = view.len; + if (pb->bf_releasebuffer != NULL) + (*pb->bf_releasebuffer)(obj, &view); + Py_XDECREF(view.obj); + return 0; } int PyObject_CheckReadBuffer(PyObject *obj) { - PyBufferProcs *pb = obj->ob_type->tp_as_buffer; - Py_buffer view; + PyBufferProcs *pb = obj->ob_type->tp_as_buffer; + Py_buffer view; - if (pb == NULL || - pb->bf_getbuffer == NULL) - return 0; - if ((*pb->bf_getbuffer)(obj, &view, PyBUF_SIMPLE) == -1) { - PyErr_Clear(); - return 0; - } - PyBuffer_Release(&view); - return 1; + if (pb == NULL || + pb->bf_getbuffer == NULL) + return 0; + if ((*pb->bf_getbuffer)(obj, &view, PyBUF_SIMPLE) == -1) { + PyErr_Clear(); + return 0; + } + PyBuffer_Release(&view); + return 1; } int PyObject_AsReadBuffer(PyObject *obj, - const void **buffer, - Py_ssize_t *buffer_len) + const void **buffer, + Py_ssize_t *buffer_len) { - PyBufferProcs *pb; - Py_buffer view; + PyBufferProcs *pb; + Py_buffer view; + + if (obj == NULL || buffer == NULL || buffer_len == NULL) { + null_error(); + return -1; + } + pb = obj->ob_type->tp_as_buffer; + if (pb == NULL || + pb->bf_getbuffer == NULL) { + PyErr_SetString(PyExc_TypeError, + "expected an object with a buffer interface"); + return -1; + } + + if ((*pb->bf_getbuffer)(obj, &view, PyBUF_SIMPLE)) return -1; - if (obj == NULL || buffer == NULL || buffer_len == NULL) { - null_error(); - return -1; - } - pb = obj->ob_type->tp_as_buffer; - if (pb == NULL || - pb->bf_getbuffer == NULL) { - PyErr_SetString(PyExc_TypeError, - "expected an object with a buffer interface"); - return -1; - } - - if ((*pb->bf_getbuffer)(obj, &view, PyBUF_SIMPLE)) return -1; - - *buffer = view.buf; - *buffer_len = view.len; - if (pb->bf_releasebuffer != NULL) - (*pb->bf_releasebuffer)(obj, &view); - Py_XDECREF(view.obj); - return 0; + *buffer = view.buf; + *buffer_len = view.len; + if (pb->bf_releasebuffer != NULL) + (*pb->bf_releasebuffer)(obj, &view); + Py_XDECREF(view.obj); + return 0; } int PyObject_AsWriteBuffer(PyObject *obj, - void **buffer, - Py_ssize_t *buffer_len) + void **buffer, + Py_ssize_t *buffer_len) { - PyBufferProcs *pb; - Py_buffer view; + PyBufferProcs *pb; + Py_buffer view; - if (obj == NULL || buffer == NULL || buffer_len == NULL) { - null_error(); - return -1; - } - pb = obj->ob_type->tp_as_buffer; - if (pb == NULL || - pb->bf_getbuffer == NULL || - ((*pb->bf_getbuffer)(obj, &view, PyBUF_WRITABLE) != 0)) { - PyErr_SetString(PyExc_TypeError, - "expected an object with a writable buffer interface"); - return -1; - } - - *buffer = view.buf; - *buffer_len = view.len; - if (pb->bf_releasebuffer != NULL) - (*pb->bf_releasebuffer)(obj, &view); - Py_XDECREF(view.obj); - return 0; + if (obj == NULL || buffer == NULL || buffer_len == NULL) { + null_error(); + return -1; + } + pb = obj->ob_type->tp_as_buffer; + if (pb == NULL || + pb->bf_getbuffer == NULL || + ((*pb->bf_getbuffer)(obj, &view, PyBUF_WRITABLE) != 0)) { + PyErr_SetString(PyExc_TypeError, + "expected an object with a writable buffer interface"); + return -1; + } + + *buffer = view.buf; + *buffer_len = view.len; + if (pb->bf_releasebuffer != NULL) + (*pb->bf_releasebuffer)(obj, &view); + Py_XDECREF(view.obj); + return 0; } /* Buffer C-API for Python 3.0 */ @@ -329,119 +329,119 @@ int PyObject_GetBuffer(PyObject *obj, Py_buffer *view, int flags) { - if (!PyObject_CheckBuffer(obj)) { - PyErr_Format(PyExc_TypeError, - "'%100s' does not support the buffer interface", - Py_TYPE(obj)->tp_name); - return -1; - } - return (*(obj->ob_type->tp_as_buffer->bf_getbuffer))(obj, view, flags); + if (!PyObject_CheckBuffer(obj)) { + PyErr_Format(PyExc_TypeError, + "'%100s' does not support the buffer interface", + Py_TYPE(obj)->tp_name); + return -1; + } + return (*(obj->ob_type->tp_as_buffer->bf_getbuffer))(obj, view, flags); } static int _IsFortranContiguous(Py_buffer *view) { - Py_ssize_t sd, dim; - int i; + Py_ssize_t sd, dim; + int i; - if (view->ndim == 0) return 1; - if (view->strides == NULL) return (view->ndim == 1); + if (view->ndim == 0) return 1; + if (view->strides == NULL) return (view->ndim == 1); - sd = view->itemsize; - if (view->ndim == 1) return (view->shape[0] == 1 || - sd == view->strides[0]); - for (i=0; indim; i++) { - dim = view->shape[i]; - if (dim == 0) return 1; - if (view->strides[i] != sd) return 0; - sd *= dim; - } - return 1; + sd = view->itemsize; + if (view->ndim == 1) return (view->shape[0] == 1 || + sd == view->strides[0]); + for (i=0; indim; i++) { + dim = view->shape[i]; + if (dim == 0) return 1; + if (view->strides[i] != sd) return 0; + sd *= dim; + } + return 1; } static int _IsCContiguous(Py_buffer *view) { - Py_ssize_t sd, dim; - int i; + Py_ssize_t sd, dim; + int i; - if (view->ndim == 0) return 1; - if (view->strides == NULL) return 1; + if (view->ndim == 0) return 1; + if (view->strides == NULL) return 1; - sd = view->itemsize; - if (view->ndim == 1) return (view->shape[0] == 1 || - sd == view->strides[0]); - for (i=view->ndim-1; i>=0; i--) { - dim = view->shape[i]; - if (dim == 0) return 1; - if (view->strides[i] != sd) return 0; - sd *= dim; - } - return 1; + sd = view->itemsize; + if (view->ndim == 1) return (view->shape[0] == 1 || + sd == view->strides[0]); + for (i=view->ndim-1; i>=0; i--) { + dim = view->shape[i]; + if (dim == 0) return 1; + if (view->strides[i] != sd) return 0; + sd *= dim; + } + return 1; } int PyBuffer_IsContiguous(Py_buffer *view, char fort) { - if (view->suboffsets != NULL) return 0; + if (view->suboffsets != NULL) return 0; - if (fort == 'C') - return _IsCContiguous(view); - else if (fort == 'F') - return _IsFortranContiguous(view); - else if (fort == 'A') - return (_IsCContiguous(view) || _IsFortranContiguous(view)); - return 0; + if (fort == 'C') + return _IsCContiguous(view); + else if (fort == 'F') + return _IsFortranContiguous(view); + else if (fort == 'A') + return (_IsCContiguous(view) || _IsFortranContiguous(view)); + return 0; } void* PyBuffer_GetPointer(Py_buffer *view, Py_ssize_t *indices) { - char* pointer; - int i; - pointer = (char *)view->buf; - for (i = 0; i < view->ndim; i++) { - pointer += view->strides[i]*indices[i]; - if ((view->suboffsets != NULL) && (view->suboffsets[i] >= 0)) { - pointer = *((char**)pointer) + view->suboffsets[i]; - } - } - return (void*)pointer; + char* pointer; + int i; + pointer = (char *)view->buf; + for (i = 0; i < view->ndim; i++) { + pointer += view->strides[i]*indices[i]; + if ((view->suboffsets != NULL) && (view->suboffsets[i] >= 0)) { + pointer = *((char**)pointer) + view->suboffsets[i]; + } + } + return (void*)pointer; } void _add_one_to_index_F(int nd, Py_ssize_t *index, Py_ssize_t *shape) { - int k; + int k; - for (k=0; k=0; k--) { - if (index[k] < shape[k]-1) { - index[k]++; - break; - } - else { - index[k] = 0; - } - } + for (k=nd-1; k>=0; k--) { + if (index[k] < shape[k]-1) { + index[k]++; + break; + } + else { + index[k] = 0; + } + } } /* view is not checked for consistency in either of these. It is @@ -452,242 +452,242 @@ int PyBuffer_ToContiguous(void *buf, Py_buffer *view, Py_ssize_t len, char fort) { - int k; - void (*addone)(int, Py_ssize_t *, Py_ssize_t *); - Py_ssize_t *indices, elements; - char *dest, *ptr; - - if (len > view->len) { - len = view->len; - } - - if (PyBuffer_IsContiguous(view, fort)) { - /* simplest copy is all that is needed */ - memcpy(buf, view->buf, len); - return 0; - } - - /* Otherwise a more elaborate scheme is needed */ - - /* XXX(nnorwitz): need to check for overflow! */ - indices = (Py_ssize_t *)PyMem_Malloc(sizeof(Py_ssize_t)*(view->ndim)); - if (indices == NULL) { - PyErr_NoMemory(); - return -1; - } - for (k=0; kndim;k++) { - indices[k] = 0; - } - - if (fort == 'F') { - addone = _add_one_to_index_F; - } - else { - addone = _add_one_to_index_C; - } - dest = buf; - /* XXX : This is not going to be the fastest code in the world - several optimizations are possible. - */ - elements = len / view->itemsize; - while (elements--) { - addone(view->ndim, indices, view->shape); - ptr = PyBuffer_GetPointer(view, indices); - memcpy(dest, ptr, view->itemsize); - dest += view->itemsize; - } - PyMem_Free(indices); - return 0; + int k; + void (*addone)(int, Py_ssize_t *, Py_ssize_t *); + Py_ssize_t *indices, elements; + char *dest, *ptr; + + if (len > view->len) { + len = view->len; + } + + if (PyBuffer_IsContiguous(view, fort)) { + /* simplest copy is all that is needed */ + memcpy(buf, view->buf, len); + return 0; + } + + /* Otherwise a more elaborate scheme is needed */ + + /* XXX(nnorwitz): need to check for overflow! */ + indices = (Py_ssize_t *)PyMem_Malloc(sizeof(Py_ssize_t)*(view->ndim)); + if (indices == NULL) { + PyErr_NoMemory(); + return -1; + } + for (k=0; kndim;k++) { + indices[k] = 0; + } + + if (fort == 'F') { + addone = _add_one_to_index_F; + } + else { + addone = _add_one_to_index_C; + } + dest = buf; + /* XXX : This is not going to be the fastest code in the world + several optimizations are possible. + */ + elements = len / view->itemsize; + while (elements--) { + addone(view->ndim, indices, view->shape); + ptr = PyBuffer_GetPointer(view, indices); + memcpy(dest, ptr, view->itemsize); + dest += view->itemsize; + } + PyMem_Free(indices); + return 0; } int PyBuffer_FromContiguous(Py_buffer *view, void *buf, Py_ssize_t len, char fort) { - int k; - void (*addone)(int, Py_ssize_t *, Py_ssize_t *); - Py_ssize_t *indices, elements; - char *src, *ptr; - - if (len > view->len) { - len = view->len; - } - - if (PyBuffer_IsContiguous(view, fort)) { - /* simplest copy is all that is needed */ - memcpy(view->buf, buf, len); - return 0; - } - - /* Otherwise a more elaborate scheme is needed */ - - /* XXX(nnorwitz): need to check for overflow! */ - indices = (Py_ssize_t *)PyMem_Malloc(sizeof(Py_ssize_t)*(view->ndim)); - if (indices == NULL) { - PyErr_NoMemory(); - return -1; - } - for (k=0; kndim;k++) { - indices[k] = 0; - } - - if (fort == 'F') { - addone = _add_one_to_index_F; - } - else { - addone = _add_one_to_index_C; - } - src = buf; - /* XXX : This is not going to be the fastest code in the world - several optimizations are possible. - */ - elements = len / view->itemsize; - while (elements--) { - addone(view->ndim, indices, view->shape); - ptr = PyBuffer_GetPointer(view, indices); - memcpy(ptr, src, view->itemsize); - src += view->itemsize; - } + int k; + void (*addone)(int, Py_ssize_t *, Py_ssize_t *); + Py_ssize_t *indices, elements; + char *src, *ptr; + + if (len > view->len) { + len = view->len; + } + + if (PyBuffer_IsContiguous(view, fort)) { + /* simplest copy is all that is needed */ + memcpy(view->buf, buf, len); + return 0; + } + + /* Otherwise a more elaborate scheme is needed */ + + /* XXX(nnorwitz): need to check for overflow! */ + indices = (Py_ssize_t *)PyMem_Malloc(sizeof(Py_ssize_t)*(view->ndim)); + if (indices == NULL) { + PyErr_NoMemory(); + return -1; + } + for (k=0; kndim;k++) { + indices[k] = 0; + } - PyMem_Free(indices); - return 0; + if (fort == 'F') { + addone = _add_one_to_index_F; + } + else { + addone = _add_one_to_index_C; + } + src = buf; + /* XXX : This is not going to be the fastest code in the world + several optimizations are possible. + */ + elements = len / view->itemsize; + while (elements--) { + addone(view->ndim, indices, view->shape); + ptr = PyBuffer_GetPointer(view, indices); + memcpy(ptr, src, view->itemsize); + src += view->itemsize; + } + + PyMem_Free(indices); + return 0; } int PyObject_CopyData(PyObject *dest, PyObject *src) { - Py_buffer view_dest, view_src; - int k; - Py_ssize_t *indices, elements; - char *dptr, *sptr; - - if (!PyObject_CheckBuffer(dest) || - !PyObject_CheckBuffer(src)) { - PyErr_SetString(PyExc_TypeError, - "both destination and source must have the "\ - "buffer interface"); - return -1; - } - - if (PyObject_GetBuffer(dest, &view_dest, PyBUF_FULL) != 0) return -1; - if (PyObject_GetBuffer(src, &view_src, PyBUF_FULL_RO) != 0) { - PyBuffer_Release(&view_dest); - return -1; - } - - if (view_dest.len < view_src.len) { - PyErr_SetString(PyExc_BufferError, - "destination is too small to receive data from source"); - PyBuffer_Release(&view_dest); - PyBuffer_Release(&view_src); - return -1; - } - - if ((PyBuffer_IsContiguous(&view_dest, 'C') && - PyBuffer_IsContiguous(&view_src, 'C')) || - (PyBuffer_IsContiguous(&view_dest, 'F') && - PyBuffer_IsContiguous(&view_src, 'F'))) { - /* simplest copy is all that is needed */ - memcpy(view_dest.buf, view_src.buf, view_src.len); - PyBuffer_Release(&view_dest); - PyBuffer_Release(&view_src); - return 0; - } - - /* Otherwise a more elaborate copy scheme is needed */ - - /* XXX(nnorwitz): need to check for overflow! */ - indices = (Py_ssize_t *)PyMem_Malloc(sizeof(Py_ssize_t)*view_src.ndim); - if (indices == NULL) { - PyErr_NoMemory(); - PyBuffer_Release(&view_dest); - PyBuffer_Release(&view_src); - return -1; - } - for (k=0; k=0; k--) { - strides[k] = sd; - sd *= shape[k]; - } - } - return; + sd = itemsize; + if (fort == 'F') { + for (k=0; k=0; k--) { + strides[k] = sd; + sd *= shape[k]; + } + } + return; } int PyBuffer_FillInfo(Py_buffer *view, PyObject *obj, void *buf, Py_ssize_t len, - int readonly, int flags) + int readonly, int flags) { - if (view == NULL) return 0; - if (((flags & PyBUF_WRITABLE) == PyBUF_WRITABLE) && - (readonly == 1)) { - PyErr_SetString(PyExc_BufferError, - "Object is not writable."); - return -1; - } - - view->obj = obj; - if (obj) - Py_INCREF(obj); - view->buf = buf; - view->len = len; - view->readonly = readonly; - view->itemsize = 1; - view->format = NULL; - if ((flags & PyBUF_FORMAT) == PyBUF_FORMAT) - view->format = "B"; - view->ndim = 1; - view->shape = NULL; - if ((flags & PyBUF_ND) == PyBUF_ND) - view->shape = &(view->len); - view->strides = NULL; - if ((flags & PyBUF_STRIDES) == PyBUF_STRIDES) - view->strides = &(view->itemsize); - view->suboffsets = NULL; - view->internal = NULL; - return 0; + if (view == NULL) return 0; + if (((flags & PyBUF_WRITABLE) == PyBUF_WRITABLE) && + (readonly == 1)) { + PyErr_SetString(PyExc_BufferError, + "Object is not writable."); + return -1; + } + + view->obj = obj; + if (obj) + Py_INCREF(obj); + view->buf = buf; + view->len = len; + view->readonly = readonly; + view->itemsize = 1; + view->format = NULL; + if ((flags & PyBUF_FORMAT) == PyBUF_FORMAT) + view->format = "B"; + view->ndim = 1; + view->shape = NULL; + if ((flags & PyBUF_ND) == PyBUF_ND) + view->shape = &(view->len); + view->strides = NULL; + if ((flags & PyBUF_STRIDES) == PyBUF_STRIDES) + view->strides = &(view->itemsize); + view->suboffsets = NULL; + view->internal = NULL; + return 0; } void PyBuffer_Release(Py_buffer *view) { - PyObject *obj = view->obj; - if (obj && Py_TYPE(obj)->tp_as_buffer && Py_TYPE(obj)->tp_as_buffer->bf_releasebuffer) - Py_TYPE(obj)->tp_as_buffer->bf_releasebuffer(obj, view); - Py_XDECREF(obj); - view->obj = NULL; + PyObject *obj = view->obj; + if (obj && Py_TYPE(obj)->tp_as_buffer && Py_TYPE(obj)->tp_as_buffer->bf_releasebuffer) + Py_TYPE(obj)->tp_as_buffer->bf_releasebuffer(obj, view); + Py_XDECREF(obj); + view->obj = NULL; } PyObject * @@ -700,41 +700,41 @@ /* Initialize cached value */ if (str__format__ == NULL) { - /* Initialize static variable needed by _PyType_Lookup */ - str__format__ = PyUnicode_FromString("__format__"); - if (str__format__ == NULL) - goto done; + /* Initialize static variable needed by _PyType_Lookup */ + str__format__ = PyUnicode_FromString("__format__"); + if (str__format__ == NULL) + goto done; } /* If no format_spec is provided, use an empty string */ if (format_spec == NULL) { - empty = PyUnicode_FromUnicode(NULL, 0); - format_spec = empty; + empty = PyUnicode_FromUnicode(NULL, 0); + format_spec = empty; } /* Make sure the type is initialized. float gets initialized late */ if (Py_TYPE(obj)->tp_dict == NULL) - if (PyType_Ready(Py_TYPE(obj)) < 0) - goto done; + if (PyType_Ready(Py_TYPE(obj)) < 0) + goto done; /* Find the (unbound!) __format__ method (a borrowed reference) */ meth = _PyType_Lookup(Py_TYPE(obj), str__format__); if (meth == NULL) { - PyErr_Format(PyExc_TypeError, - "Type %.100s doesn't define __format__", - Py_TYPE(obj)->tp_name); - goto done; + PyErr_Format(PyExc_TypeError, + "Type %.100s doesn't define __format__", + Py_TYPE(obj)->tp_name); + goto done; } /* And call it, binding it to the value */ result = PyObject_CallFunctionObjArgs(meth, obj, format_spec, NULL); if (result && !PyUnicode_Check(result)) { - PyErr_SetString(PyExc_TypeError, - "__format__ method did not return string"); - Py_DECREF(result); - result = NULL; - goto done; + PyErr_SetString(PyExc_TypeError, + "__format__ method did not return string"); + Py_DECREF(result); + result = NULL; + goto done; } done: @@ -746,24 +746,24 @@ int PyNumber_Check(PyObject *o) { - return o && o->ob_type->tp_as_number && - (o->ob_type->tp_as_number->nb_int || - o->ob_type->tp_as_number->nb_float); + return o && o->ob_type->tp_as_number && + (o->ob_type->tp_as_number->nb_int || + o->ob_type->tp_as_number->nb_float); } /* Binary operators */ #define NB_SLOT(x) offsetof(PyNumberMethods, x) #define NB_BINOP(nb_methods, slot) \ - (*(binaryfunc*)(& ((char*)nb_methods)[slot])) + (*(binaryfunc*)(& ((char*)nb_methods)[slot])) #define NB_TERNOP(nb_methods, slot) \ - (*(ternaryfunc*)(& ((char*)nb_methods)[slot])) + (*(ternaryfunc*)(& ((char*)nb_methods)[slot])) /* Calling scheme used for binary operations: Order operations are tried until either a valid result or error: - w.op(v,w)[*], v.op(v,w), w.op(v,w) + w.op(v,w)[*], v.op(v,w), w.op(v,w) [*] only when v->ob_type != w->ob_type && w->ob_type is a subclass of v->ob_type @@ -772,62 +772,62 @@ static PyObject * binary_op1(PyObject *v, PyObject *w, const int op_slot) { - PyObject *x; - binaryfunc slotv = NULL; - binaryfunc slotw = NULL; - - if (v->ob_type->tp_as_number != NULL) - slotv = NB_BINOP(v->ob_type->tp_as_number, op_slot); - if (w->ob_type != v->ob_type && - w->ob_type->tp_as_number != NULL) { - slotw = NB_BINOP(w->ob_type->tp_as_number, op_slot); - if (slotw == slotv) - slotw = NULL; - } - if (slotv) { - if (slotw && PyType_IsSubtype(w->ob_type, v->ob_type)) { - x = slotw(v, w); - if (x != Py_NotImplemented) - return x; - Py_DECREF(x); /* can't do it */ - slotw = NULL; - } - x = slotv(v, w); - if (x != Py_NotImplemented) - return x; - Py_DECREF(x); /* can't do it */ - } - if (slotw) { - x = slotw(v, w); - if (x != Py_NotImplemented) - return x; - Py_DECREF(x); /* can't do it */ - } - Py_INCREF(Py_NotImplemented); - return Py_NotImplemented; + PyObject *x; + binaryfunc slotv = NULL; + binaryfunc slotw = NULL; + + if (v->ob_type->tp_as_number != NULL) + slotv = NB_BINOP(v->ob_type->tp_as_number, op_slot); + if (w->ob_type != v->ob_type && + w->ob_type->tp_as_number != NULL) { + slotw = NB_BINOP(w->ob_type->tp_as_number, op_slot); + if (slotw == slotv) + slotw = NULL; + } + if (slotv) { + if (slotw && PyType_IsSubtype(w->ob_type, v->ob_type)) { + x = slotw(v, w); + if (x != Py_NotImplemented) + return x; + Py_DECREF(x); /* can't do it */ + slotw = NULL; + } + x = slotv(v, w); + if (x != Py_NotImplemented) + return x; + Py_DECREF(x); /* can't do it */ + } + if (slotw) { + x = slotw(v, w); + if (x != Py_NotImplemented) + return x; + Py_DECREF(x); /* can't do it */ + } + Py_INCREF(Py_NotImplemented); + return Py_NotImplemented; } static PyObject * binop_type_error(PyObject *v, PyObject *w, const char *op_name) { - PyErr_Format(PyExc_TypeError, - "unsupported operand type(s) for %.100s: " - "'%.100s' and '%.100s'", - op_name, - v->ob_type->tp_name, - w->ob_type->tp_name); - return NULL; + PyErr_Format(PyExc_TypeError, + "unsupported operand type(s) for %.100s: " + "'%.100s' and '%.100s'", + op_name, + v->ob_type->tp_name, + w->ob_type->tp_name); + return NULL; } static PyObject * binary_op(PyObject *v, PyObject *w, const int op_slot, const char *op_name) { - PyObject *result = binary_op1(v, w, op_slot); - if (result == Py_NotImplemented) { - Py_DECREF(result); - return binop_type_error(v, w, op_name); - } - return result; + PyObject *result = binary_op1(v, w, op_slot); + if (result == Py_NotImplemented) { + Py_DECREF(result); + return binop_type_error(v, w, op_name); + } + return result; } @@ -835,86 +835,86 @@ Calling scheme used for ternary operations: Order operations are tried until either a valid result or error: - v.op(v,w,z), w.op(v,w,z), z.op(v,w,z) + v.op(v,w,z), w.op(v,w,z), z.op(v,w,z) */ static PyObject * ternary_op(PyObject *v, - PyObject *w, - PyObject *z, - const int op_slot, - const char *op_name) -{ - PyNumberMethods *mv, *mw, *mz; - PyObject *x = NULL; - ternaryfunc slotv = NULL; - ternaryfunc slotw = NULL; - ternaryfunc slotz = NULL; - - mv = v->ob_type->tp_as_number; - mw = w->ob_type->tp_as_number; - if (mv != NULL) - slotv = NB_TERNOP(mv, op_slot); - if (w->ob_type != v->ob_type && - mw != NULL) { - slotw = NB_TERNOP(mw, op_slot); - if (slotw == slotv) - slotw = NULL; - } - if (slotv) { - if (slotw && PyType_IsSubtype(w->ob_type, v->ob_type)) { - x = slotw(v, w, z); - if (x != Py_NotImplemented) - return x; - Py_DECREF(x); /* can't do it */ - slotw = NULL; - } - x = slotv(v, w, z); - if (x != Py_NotImplemented) - return x; - Py_DECREF(x); /* can't do it */ - } - if (slotw) { - x = slotw(v, w, z); - if (x != Py_NotImplemented) - return x; - Py_DECREF(x); /* can't do it */ - } - mz = z->ob_type->tp_as_number; - if (mz != NULL) { - slotz = NB_TERNOP(mz, op_slot); - if (slotz == slotv || slotz == slotw) - slotz = NULL; - if (slotz) { - x = slotz(v, w, z); - if (x != Py_NotImplemented) - return x; - Py_DECREF(x); /* can't do it */ - } - } - - if (z == Py_None) - PyErr_Format( - PyExc_TypeError, - "unsupported operand type(s) for ** or pow(): " - "'%.100s' and '%.100s'", - v->ob_type->tp_name, - w->ob_type->tp_name); - else - PyErr_Format( - PyExc_TypeError, - "unsupported operand type(s) for pow(): " - "'%.100s', '%.100s', '%.100s'", - v->ob_type->tp_name, - w->ob_type->tp_name, - z->ob_type->tp_name); - return NULL; + PyObject *w, + PyObject *z, + const int op_slot, + const char *op_name) +{ + PyNumberMethods *mv, *mw, *mz; + PyObject *x = NULL; + ternaryfunc slotv = NULL; + ternaryfunc slotw = NULL; + ternaryfunc slotz = NULL; + + mv = v->ob_type->tp_as_number; + mw = w->ob_type->tp_as_number; + if (mv != NULL) + slotv = NB_TERNOP(mv, op_slot); + if (w->ob_type != v->ob_type && + mw != NULL) { + slotw = NB_TERNOP(mw, op_slot); + if (slotw == slotv) + slotw = NULL; + } + if (slotv) { + if (slotw && PyType_IsSubtype(w->ob_type, v->ob_type)) { + x = slotw(v, w, z); + if (x != Py_NotImplemented) + return x; + Py_DECREF(x); /* can't do it */ + slotw = NULL; + } + x = slotv(v, w, z); + if (x != Py_NotImplemented) + return x; + Py_DECREF(x); /* can't do it */ + } + if (slotw) { + x = slotw(v, w, z); + if (x != Py_NotImplemented) + return x; + Py_DECREF(x); /* can't do it */ + } + mz = z->ob_type->tp_as_number; + if (mz != NULL) { + slotz = NB_TERNOP(mz, op_slot); + if (slotz == slotv || slotz == slotw) + slotz = NULL; + if (slotz) { + x = slotz(v, w, z); + if (x != Py_NotImplemented) + return x; + Py_DECREF(x); /* can't do it */ + } + } + + if (z == Py_None) + PyErr_Format( + PyExc_TypeError, + "unsupported operand type(s) for ** or pow(): " + "'%.100s' and '%.100s'", + v->ob_type->tp_name, + w->ob_type->tp_name); + else + PyErr_Format( + PyExc_TypeError, + "unsupported operand type(s) for pow(): " + "'%.100s', '%.100s', '%.100s'", + v->ob_type->tp_name, + w->ob_type->tp_name, + z->ob_type->tp_name); + return NULL; } #define BINARY_FUNC(func, op, op_name) \ PyObject * \ func(PyObject *v, PyObject *w) { \ - return binary_op(v, w, NB_SLOT(op), op_name); \ + return binary_op(v, w, NB_SLOT(op), op_name); \ } BINARY_FUNC(PyNumber_Or, nb_or, "|") @@ -928,75 +928,75 @@ PyObject * PyNumber_Add(PyObject *v, PyObject *w) { - PyObject *result = binary_op1(v, w, NB_SLOT(nb_add)); - if (result == Py_NotImplemented) { - PySequenceMethods *m = v->ob_type->tp_as_sequence; - Py_DECREF(result); - if (m && m->sq_concat) { - return (*m->sq_concat)(v, w); - } - result = binop_type_error(v, w, "+"); - } - return result; + PyObject *result = binary_op1(v, w, NB_SLOT(nb_add)); + if (result == Py_NotImplemented) { + PySequenceMethods *m = v->ob_type->tp_as_sequence; + Py_DECREF(result); + if (m && m->sq_concat) { + return (*m->sq_concat)(v, w); + } + result = binop_type_error(v, w, "+"); + } + return result; } static PyObject * sequence_repeat(ssizeargfunc repeatfunc, PyObject *seq, PyObject *n) { - Py_ssize_t count; - if (PyIndex_Check(n)) { - count = PyNumber_AsSsize_t(n, PyExc_OverflowError); - if (count == -1 && PyErr_Occurred()) - return NULL; - } - else { - return type_error("can't multiply sequence by " - "non-int of type '%.200s'", n); - } - return (*repeatfunc)(seq, count); + Py_ssize_t count; + if (PyIndex_Check(n)) { + count = PyNumber_AsSsize_t(n, PyExc_OverflowError); + if (count == -1 && PyErr_Occurred()) + return NULL; + } + else { + return type_error("can't multiply sequence by " + "non-int of type '%.200s'", n); + } + return (*repeatfunc)(seq, count); } PyObject * PyNumber_Multiply(PyObject *v, PyObject *w) { - PyObject *result = binary_op1(v, w, NB_SLOT(nb_multiply)); - if (result == Py_NotImplemented) { - PySequenceMethods *mv = v->ob_type->tp_as_sequence; - PySequenceMethods *mw = w->ob_type->tp_as_sequence; - Py_DECREF(result); - if (mv && mv->sq_repeat) { - return sequence_repeat(mv->sq_repeat, v, w); - } - else if (mw && mw->sq_repeat) { - return sequence_repeat(mw->sq_repeat, w, v); - } - result = binop_type_error(v, w, "*"); - } - return result; + PyObject *result = binary_op1(v, w, NB_SLOT(nb_multiply)); + if (result == Py_NotImplemented) { + PySequenceMethods *mv = v->ob_type->tp_as_sequence; + PySequenceMethods *mw = w->ob_type->tp_as_sequence; + Py_DECREF(result); + if (mv && mv->sq_repeat) { + return sequence_repeat(mv->sq_repeat, v, w); + } + else if (mw && mw->sq_repeat) { + return sequence_repeat(mw->sq_repeat, w, v); + } + result = binop_type_error(v, w, "*"); + } + return result; } PyObject * PyNumber_FloorDivide(PyObject *v, PyObject *w) { - return binary_op(v, w, NB_SLOT(nb_floor_divide), "//"); + return binary_op(v, w, NB_SLOT(nb_floor_divide), "//"); } PyObject * PyNumber_TrueDivide(PyObject *v, PyObject *w) { - return binary_op(v, w, NB_SLOT(nb_true_divide), "/"); + return binary_op(v, w, NB_SLOT(nb_true_divide), "/"); } PyObject * PyNumber_Remainder(PyObject *v, PyObject *w) { - return binary_op(v, w, NB_SLOT(nb_remainder), "%"); + return binary_op(v, w, NB_SLOT(nb_remainder), "%"); } PyObject * PyNumber_Power(PyObject *v, PyObject *w, PyObject *z) { - return ternary_op(v, w, z, NB_SLOT(nb_power), "** or pow()"); + return ternary_op(v, w, z, NB_SLOT(nb_power), "** or pow()"); } /* Binary in-place operators */ @@ -1018,37 +1018,37 @@ static PyObject * binary_iop1(PyObject *v, PyObject *w, const int iop_slot, const int op_slot) { - PyNumberMethods *mv = v->ob_type->tp_as_number; - if (mv != NULL) { - binaryfunc slot = NB_BINOP(mv, iop_slot); - if (slot) { - PyObject *x = (slot)(v, w); - if (x != Py_NotImplemented) { - return x; - } - Py_DECREF(x); - } - } - return binary_op1(v, w, op_slot); + PyNumberMethods *mv = v->ob_type->tp_as_number; + if (mv != NULL) { + binaryfunc slot = NB_BINOP(mv, iop_slot); + if (slot) { + PyObject *x = (slot)(v, w); + if (x != Py_NotImplemented) { + return x; + } + Py_DECREF(x); + } + } + return binary_op1(v, w, op_slot); } static PyObject * binary_iop(PyObject *v, PyObject *w, const int iop_slot, const int op_slot, - const char *op_name) + const char *op_name) { - PyObject *result = binary_iop1(v, w, iop_slot, op_slot); - if (result == Py_NotImplemented) { - Py_DECREF(result); - return binop_type_error(v, w, op_name); - } - return result; + PyObject *result = binary_iop1(v, w, iop_slot, op_slot); + if (result == Py_NotImplemented) { + Py_DECREF(result); + return binop_type_error(v, w, op_name); + } + return result; } #define INPLACE_BINOP(func, iop, op, op_name) \ - PyObject * \ - func(PyObject *v, PyObject *w) { \ - return binary_iop(v, w, NB_SLOT(iop), NB_SLOT(op), op_name); \ - } + PyObject * \ + func(PyObject *v, PyObject *w) { \ + return binary_iop(v, w, NB_SLOT(iop), NB_SLOT(op), op_name); \ + } INPLACE_BINOP(PyNumber_InPlaceOr, nb_inplace_or, nb_or, "|=") INPLACE_BINOP(PyNumber_InPlaceXor, nb_inplace_xor, nb_xor, "^=") @@ -1060,84 +1060,84 @@ PyObject * PyNumber_InPlaceFloorDivide(PyObject *v, PyObject *w) { - return binary_iop(v, w, NB_SLOT(nb_inplace_floor_divide), - NB_SLOT(nb_floor_divide), "//="); + return binary_iop(v, w, NB_SLOT(nb_inplace_floor_divide), + NB_SLOT(nb_floor_divide), "//="); } PyObject * PyNumber_InPlaceTrueDivide(PyObject *v, PyObject *w) { - return binary_iop(v, w, NB_SLOT(nb_inplace_true_divide), - NB_SLOT(nb_true_divide), "/="); + return binary_iop(v, w, NB_SLOT(nb_inplace_true_divide), + NB_SLOT(nb_true_divide), "/="); } PyObject * PyNumber_InPlaceAdd(PyObject *v, PyObject *w) { - PyObject *result = binary_iop1(v, w, NB_SLOT(nb_inplace_add), - NB_SLOT(nb_add)); - if (result == Py_NotImplemented) { - PySequenceMethods *m = v->ob_type->tp_as_sequence; - Py_DECREF(result); - if (m != NULL) { - binaryfunc f = NULL; - f = m->sq_inplace_concat; - if (f == NULL) - f = m->sq_concat; - if (f != NULL) - return (*f)(v, w); - } - result = binop_type_error(v, w, "+="); - } - return result; + PyObject *result = binary_iop1(v, w, NB_SLOT(nb_inplace_add), + NB_SLOT(nb_add)); + if (result == Py_NotImplemented) { + PySequenceMethods *m = v->ob_type->tp_as_sequence; + Py_DECREF(result); + if (m != NULL) { + binaryfunc f = NULL; + f = m->sq_inplace_concat; + if (f == NULL) + f = m->sq_concat; + if (f != NULL) + return (*f)(v, w); + } + result = binop_type_error(v, w, "+="); + } + return result; } PyObject * PyNumber_InPlaceMultiply(PyObject *v, PyObject *w) { - PyObject *result = binary_iop1(v, w, NB_SLOT(nb_inplace_multiply), - NB_SLOT(nb_multiply)); - if (result == Py_NotImplemented) { - ssizeargfunc f = NULL; - PySequenceMethods *mv = v->ob_type->tp_as_sequence; - PySequenceMethods *mw = w->ob_type->tp_as_sequence; - Py_DECREF(result); - if (mv != NULL) { - f = mv->sq_inplace_repeat; - if (f == NULL) - f = mv->sq_repeat; - if (f != NULL) - return sequence_repeat(f, v, w); - } - else if (mw != NULL) { - /* Note that the right hand operand should not be - * mutated in this case so sq_inplace_repeat is not - * used. */ - if (mw->sq_repeat) - return sequence_repeat(mw->sq_repeat, w, v); - } - result = binop_type_error(v, w, "*="); - } - return result; + PyObject *result = binary_iop1(v, w, NB_SLOT(nb_inplace_multiply), + NB_SLOT(nb_multiply)); + if (result == Py_NotImplemented) { + ssizeargfunc f = NULL; + PySequenceMethods *mv = v->ob_type->tp_as_sequence; + PySequenceMethods *mw = w->ob_type->tp_as_sequence; + Py_DECREF(result); + if (mv != NULL) { + f = mv->sq_inplace_repeat; + if (f == NULL) + f = mv->sq_repeat; + if (f != NULL) + return sequence_repeat(f, v, w); + } + else if (mw != NULL) { + /* Note that the right hand operand should not be + * mutated in this case so sq_inplace_repeat is not + * used. */ + if (mw->sq_repeat) + return sequence_repeat(mw->sq_repeat, w, v); + } + result = binop_type_error(v, w, "*="); + } + return result; } PyObject * PyNumber_InPlaceRemainder(PyObject *v, PyObject *w) { - return binary_iop(v, w, NB_SLOT(nb_inplace_remainder), - NB_SLOT(nb_remainder), "%="); + return binary_iop(v, w, NB_SLOT(nb_inplace_remainder), + NB_SLOT(nb_remainder), "%="); } PyObject * PyNumber_InPlacePower(PyObject *v, PyObject *w, PyObject *z) { - if (v->ob_type->tp_as_number && - v->ob_type->tp_as_number->nb_inplace_power != NULL) { - return ternary_op(v, w, z, NB_SLOT(nb_inplace_power), "**="); - } - else { - return ternary_op(v, w, z, NB_SLOT(nb_power), "**="); - } + if (v->ob_type->tp_as_number && + v->ob_type->tp_as_number->nb_inplace_power != NULL) { + return ternary_op(v, w, z, NB_SLOT(nb_inplace_power), "**="); + } + else { + return ternary_op(v, w, z, NB_SLOT(nb_power), "**="); + } } @@ -1146,57 +1146,57 @@ PyObject * PyNumber_Negative(PyObject *o) { - PyNumberMethods *m; + PyNumberMethods *m; - if (o == NULL) - return null_error(); - m = o->ob_type->tp_as_number; - if (m && m->nb_negative) - return (*m->nb_negative)(o); + if (o == NULL) + return null_error(); + m = o->ob_type->tp_as_number; + if (m && m->nb_negative) + return (*m->nb_negative)(o); - return type_error("bad operand type for unary -: '%.200s'", o); + return type_error("bad operand type for unary -: '%.200s'", o); } PyObject * PyNumber_Positive(PyObject *o) { - PyNumberMethods *m; + PyNumberMethods *m; - if (o == NULL) - return null_error(); - m = o->ob_type->tp_as_number; - if (m && m->nb_positive) - return (*m->nb_positive)(o); + if (o == NULL) + return null_error(); + m = o->ob_type->tp_as_number; + if (m && m->nb_positive) + return (*m->nb_positive)(o); - return type_error("bad operand type for unary +: '%.200s'", o); + return type_error("bad operand type for unary +: '%.200s'", o); } PyObject * PyNumber_Invert(PyObject *o) { - PyNumberMethods *m; + PyNumberMethods *m; - if (o == NULL) - return null_error(); - m = o->ob_type->tp_as_number; - if (m && m->nb_invert) - return (*m->nb_invert)(o); + if (o == NULL) + return null_error(); + m = o->ob_type->tp_as_number; + if (m && m->nb_invert) + return (*m->nb_invert)(o); - return type_error("bad operand type for unary ~: '%.200s'", o); + return type_error("bad operand type for unary ~: '%.200s'", o); } PyObject * PyNumber_Absolute(PyObject *o) { - PyNumberMethods *m; + PyNumberMethods *m; - if (o == NULL) - return null_error(); - m = o->ob_type->tp_as_number; - if (m && m->nb_absolute) - return m->nb_absolute(o); + if (o == NULL) + return null_error(); + m = o->ob_type->tp_as_number; + if (m && m->nb_absolute) + return m->nb_absolute(o); - return type_error("bad operand type for abs(): '%.200s'", o); + return type_error("bad operand type for abs(): '%.200s'", o); } /* Return a Python Int or Long from the object item @@ -1206,30 +1206,30 @@ PyObject * PyNumber_Index(PyObject *item) { - PyObject *result = NULL; - if (item == NULL) - return null_error(); - if (PyLong_Check(item)) { - Py_INCREF(item); - return item; - } - if (PyIndex_Check(item)) { - result = item->ob_type->tp_as_number->nb_index(item); - if (result && !PyLong_Check(result)) { - PyErr_Format(PyExc_TypeError, - "__index__ returned non-int " - "(type %.200s)", - result->ob_type->tp_name); - Py_DECREF(result); - return NULL; - } - } - else { - PyErr_Format(PyExc_TypeError, - "'%.200s' object cannot be interpreted " - "as an integer", item->ob_type->tp_name); - } - return result; + PyObject *result = NULL; + if (item == NULL) + return null_error(); + if (PyLong_Check(item)) { + Py_INCREF(item); + return item; + } + if (PyIndex_Check(item)) { + result = item->ob_type->tp_as_number->nb_index(item); + if (result && !PyLong_Check(result)) { + PyErr_Format(PyExc_TypeError, + "__index__ returned non-int " + "(type %.200s)", + result->ob_type->tp_name); + Py_DECREF(result); + return NULL; + } + } + else { + PyErr_Format(PyExc_TypeError, + "'%.200s' object cannot be interpreted " + "as an integer", item->ob_type->tp_name); + } + return result; } /* Return an error on Overflow only if err is not NULL*/ @@ -1237,79 +1237,79 @@ Py_ssize_t PyNumber_AsSsize_t(PyObject *item, PyObject *err) { - Py_ssize_t result; - PyObject *runerr; - PyObject *value = PyNumber_Index(item); - if (value == NULL) - return -1; - - /* We're done if PyLong_AsSsize_t() returns without error. */ - result = PyLong_AsSsize_t(value); - if (result != -1 || !(runerr = PyErr_Occurred())) - goto finish; - - /* Error handling code -- only manage OverflowError differently */ - if (!PyErr_GivenExceptionMatches(runerr, PyExc_OverflowError)) - goto finish; - - PyErr_Clear(); - /* If no error-handling desired then the default clipping - is sufficient. - */ - if (!err) { - assert(PyLong_Check(value)); - /* Whether or not it is less than or equal to - zero is determined by the sign of ob_size - */ - if (_PyLong_Sign(value) < 0) - result = PY_SSIZE_T_MIN; - else - result = PY_SSIZE_T_MAX; - } - else { - /* Otherwise replace the error with caller's error object. */ - PyErr_Format(err, - "cannot fit '%.200s' into an index-sized integer", - item->ob_type->tp_name); - } + Py_ssize_t result; + PyObject *runerr; + PyObject *value = PyNumber_Index(item); + if (value == NULL) + return -1; + + /* We're done if PyLong_AsSsize_t() returns without error. */ + result = PyLong_AsSsize_t(value); + if (result != -1 || !(runerr = PyErr_Occurred())) + goto finish; + + /* Error handling code -- only manage OverflowError differently */ + if (!PyErr_GivenExceptionMatches(runerr, PyExc_OverflowError)) + goto finish; + + PyErr_Clear(); + /* If no error-handling desired then the default clipping + is sufficient. + */ + if (!err) { + assert(PyLong_Check(value)); + /* Whether or not it is less than or equal to + zero is determined by the sign of ob_size + */ + if (_PyLong_Sign(value) < 0) + result = PY_SSIZE_T_MIN; + else + result = PY_SSIZE_T_MAX; + } + else { + /* Otherwise replace the error with caller's error object. */ + PyErr_Format(err, + "cannot fit '%.200s' into an index-sized integer", + item->ob_type->tp_name); + } finish: - Py_DECREF(value); - return result; + Py_DECREF(value); + return result; } PyObject * _PyNumber_ConvertIntegralToInt(PyObject *integral, const char* error_format) { - static PyObject *int_name = NULL; - if (int_name == NULL) { - int_name = PyUnicode_InternFromString("__int__"); - if (int_name == NULL) - return NULL; - } - - if (integral && !PyLong_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); - if (int_func == NULL) { - PyErr_Clear(); /* Raise a different error. */ - goto non_integral_error; - } - Py_DECREF(integral); - integral = PyEval_CallObject(int_func, NULL); - Py_DECREF(int_func); - if (integral && !PyLong_Check(integral)) { - goto non_integral_error; - } - } - return integral; + static PyObject *int_name = NULL; + if (int_name == NULL) { + int_name = PyUnicode_InternFromString("__int__"); + if (int_name == NULL) + return NULL; + } + + if (integral && !PyLong_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); + if (int_func == NULL) { + PyErr_Clear(); /* Raise a different error. */ + goto non_integral_error; + } + Py_DECREF(integral); + integral = PyEval_CallObject(int_func, NULL); + Py_DECREF(int_func); + if (integral && !PyLong_Check(integral)) { + goto non_integral_error; + } + } + return integral; non_integral_error: - PyErr_Format(PyExc_TypeError, error_format, Py_TYPE(integral)->tp_name); - Py_DECREF(integral); - return NULL; + PyErr_Format(PyExc_TypeError, error_format, Py_TYPE(integral)->tp_name); + Py_DECREF(integral); + return NULL; } @@ -1317,134 +1317,134 @@ static PyObject * long_from_string(const char *s, Py_ssize_t len) { - char *end; - PyObject *x; + char *end; + PyObject *x; - x = PyLong_FromString((char*)s, &end, 10); - if (x == NULL) - return NULL; - if (end != s + len) { - PyErr_SetString(PyExc_ValueError, - "null byte in argument for int()"); - Py_DECREF(x); - return NULL; - } - return x; + x = PyLong_FromString((char*)s, &end, 10); + if (x == NULL) + return NULL; + if (end != s + len) { + PyErr_SetString(PyExc_ValueError, + "null byte in argument for int()"); + Py_DECREF(x); + return NULL; + } + return x; } PyObject * PyNumber_Long(PyObject *o) { - PyNumberMethods *m; - static PyObject *trunc_name = NULL; - PyObject *trunc_func; - const char *buffer; - Py_ssize_t buffer_len; - - if (trunc_name == NULL) { - trunc_name = PyUnicode_InternFromString("__trunc__"); - if (trunc_name == NULL) - return NULL; - } - - if (o == NULL) - return null_error(); - if (PyLong_CheckExact(o)) { - Py_INCREF(o); - return o; - } - m = o->ob_type->tp_as_number; - if (m && m->nb_int) { /* This should include subclasses of int */ - PyObject *res = m->nb_int(o); - if (res && !PyLong_Check(res)) { - PyErr_Format(PyExc_TypeError, - "__int__ returned non-int (type %.200s)", - res->ob_type->tp_name); - Py_DECREF(res); - return NULL; - } - return res; - } - if (PyLong_Check(o)) /* An int subclass without nb_int */ - return _PyLong_Copy((PyLongObject *)o); - trunc_func = PyObject_GetAttr(o, trunc_name); - if (trunc_func) { - PyObject *truncated = PyEval_CallObject(trunc_func, NULL); - PyObject *int_instance; - Py_DECREF(trunc_func); - /* __trunc__ is specified to return an Integral type, - but long() needs to return a long. */ - int_instance = _PyNumber_ConvertIntegralToInt( - truncated, - "__trunc__ returned non-Integral (type %.200s)"); - return int_instance; - } - PyErr_Clear(); /* It's not an error if o.__trunc__ doesn't exist. */ - - if (PyBytes_Check(o)) - /* need to do extra error checking that PyLong_FromString() - * doesn't do. In particular long('9.5') must raise an - * exception, not truncate the float. - */ - return long_from_string(PyBytes_AS_STRING(o), - PyBytes_GET_SIZE(o)); - if (PyUnicode_Check(o)) - /* The above check is done in PyLong_FromUnicode(). */ - return PyLong_FromUnicode(PyUnicode_AS_UNICODE(o), - PyUnicode_GET_SIZE(o), - 10); - if (!PyObject_AsCharBuffer(o, &buffer, &buffer_len)) - return long_from_string(buffer, buffer_len); + PyNumberMethods *m; + static PyObject *trunc_name = NULL; + PyObject *trunc_func; + const char *buffer; + Py_ssize_t buffer_len; + + if (trunc_name == NULL) { + trunc_name = PyUnicode_InternFromString("__trunc__"); + if (trunc_name == NULL) + return NULL; + } - return type_error("int() argument must be a string or a " - "number, not '%.200s'", o); + if (o == NULL) + return null_error(); + if (PyLong_CheckExact(o)) { + Py_INCREF(o); + return o; + } + m = o->ob_type->tp_as_number; + if (m && m->nb_int) { /* This should include subclasses of int */ + PyObject *res = m->nb_int(o); + if (res && !PyLong_Check(res)) { + PyErr_Format(PyExc_TypeError, + "__int__ returned non-int (type %.200s)", + res->ob_type->tp_name); + Py_DECREF(res); + return NULL; + } + return res; + } + if (PyLong_Check(o)) /* An int subclass without nb_int */ + return _PyLong_Copy((PyLongObject *)o); + trunc_func = PyObject_GetAttr(o, trunc_name); + if (trunc_func) { + PyObject *truncated = PyEval_CallObject(trunc_func, NULL); + PyObject *int_instance; + Py_DECREF(trunc_func); + /* __trunc__ is specified to return an Integral type, + but long() needs to return a long. */ + int_instance = _PyNumber_ConvertIntegralToInt( + truncated, + "__trunc__ returned non-Integral (type %.200s)"); + return int_instance; + } + PyErr_Clear(); /* It's not an error if o.__trunc__ doesn't exist. */ + + if (PyBytes_Check(o)) + /* need to do extra error checking that PyLong_FromString() + * doesn't do. In particular long('9.5') must raise an + * exception, not truncate the float. + */ + return long_from_string(PyBytes_AS_STRING(o), + PyBytes_GET_SIZE(o)); + if (PyUnicode_Check(o)) + /* The above check is done in PyLong_FromUnicode(). */ + return PyLong_FromUnicode(PyUnicode_AS_UNICODE(o), + PyUnicode_GET_SIZE(o), + 10); + if (!PyObject_AsCharBuffer(o, &buffer, &buffer_len)) + return long_from_string(buffer, buffer_len); + + return type_error("int() argument must be a string or a " + "number, not '%.200s'", o); } PyObject * PyNumber_Float(PyObject *o) { - PyNumberMethods *m; + PyNumberMethods *m; - if (o == NULL) - return null_error(); - m = o->ob_type->tp_as_number; - if (m && m->nb_float) { /* This should include subclasses of float */ - PyObject *res = m->nb_float(o); - if (res && !PyFloat_Check(res)) { - PyErr_Format(PyExc_TypeError, - "__float__ returned non-float (type %.200s)", - res->ob_type->tp_name); - Py_DECREF(res); - return NULL; - } - return res; - } - if (PyFloat_Check(o)) { /* A float subclass with nb_float == NULL */ - PyFloatObject *po = (PyFloatObject *)o; - return PyFloat_FromDouble(po->ob_fval); - } - return PyFloat_FromString(o); + if (o == NULL) + return null_error(); + m = o->ob_type->tp_as_number; + if (m && m->nb_float) { /* This should include subclasses of float */ + PyObject *res = m->nb_float(o); + if (res && !PyFloat_Check(res)) { + PyErr_Format(PyExc_TypeError, + "__float__ returned non-float (type %.200s)", + res->ob_type->tp_name); + Py_DECREF(res); + return NULL; + } + return res; + } + if (PyFloat_Check(o)) { /* A float subclass with nb_float == NULL */ + PyFloatObject *po = (PyFloatObject *)o; + return PyFloat_FromDouble(po->ob_fval); + } + return PyFloat_FromString(o); } PyObject * PyNumber_ToBase(PyObject *n, int base) { - PyObject *res = NULL; - PyObject *index = PyNumber_Index(n); + PyObject *res = NULL; + PyObject *index = PyNumber_Index(n); - if (!index) - return NULL; - if (PyLong_Check(index)) - res = _PyLong_Format(index, base); - else - /* It should not be possible to get here, as - PyNumber_Index already has a check for the same - condition */ - PyErr_SetString(PyExc_ValueError, "PyNumber_ToBase: index not " - "int or long"); - Py_DECREF(index); - return res; + if (!index) + return NULL; + if (PyLong_Check(index)) + res = _PyLong_Format(index, base); + else + /* It should not be possible to get here, as + PyNumber_Index already has a check for the same + condition */ + PyErr_SetString(PyExc_ValueError, "PyNumber_ToBase: index not " + "int or long"); + Py_DECREF(index); + return res; } @@ -1453,507 +1453,507 @@ int PySequence_Check(PyObject *s) { - if (PyDict_Check(s)) - return 0; - return s != NULL && s->ob_type->tp_as_sequence && - s->ob_type->tp_as_sequence->sq_item != NULL; + if (PyDict_Check(s)) + return 0; + return s != NULL && s->ob_type->tp_as_sequence && + s->ob_type->tp_as_sequence->sq_item != NULL; } Py_ssize_t PySequence_Size(PyObject *s) { - PySequenceMethods *m; + PySequenceMethods *m; + + if (s == NULL) { + null_error(); + return -1; + } - if (s == NULL) { - null_error(); - return -1; - } - - m = s->ob_type->tp_as_sequence; - if (m && m->sq_length) - return m->sq_length(s); + m = s->ob_type->tp_as_sequence; + if (m && m->sq_length) + return m->sq_length(s); - type_error("object of type '%.200s' has no len()", s); - return -1; + type_error("object of type '%.200s' has no len()", s); + return -1; } #undef PySequence_Length Py_ssize_t PySequence_Length(PyObject *s) { - return PySequence_Size(s); + return PySequence_Size(s); } #define PySequence_Length PySequence_Size PyObject * PySequence_Concat(PyObject *s, PyObject *o) { - PySequenceMethods *m; + PySequenceMethods *m; - if (s == NULL || o == NULL) - return null_error(); + if (s == NULL || o == NULL) + return null_error(); - m = s->ob_type->tp_as_sequence; - if (m && m->sq_concat) - return m->sq_concat(s, o); - - /* Instances of user classes defining an __add__() method only - have an nb_add slot, not an sq_concat slot. So we fall back - to nb_add if both arguments appear to be sequences. */ - if (PySequence_Check(s) && PySequence_Check(o)) { - PyObject *result = binary_op1(s, o, NB_SLOT(nb_add)); - if (result != Py_NotImplemented) - return result; - Py_DECREF(result); - } - return type_error("'%.200s' object can't be concatenated", s); + m = s->ob_type->tp_as_sequence; + if (m && m->sq_concat) + return m->sq_concat(s, o); + + /* Instances of user classes defining an __add__() method only + have an nb_add slot, not an sq_concat slot. So we fall back + to nb_add if both arguments appear to be sequences. */ + if (PySequence_Check(s) && PySequence_Check(o)) { + PyObject *result = binary_op1(s, o, NB_SLOT(nb_add)); + if (result != Py_NotImplemented) + return result; + Py_DECREF(result); + } + return type_error("'%.200s' object can't be concatenated", s); } PyObject * PySequence_Repeat(PyObject *o, Py_ssize_t count) { - PySequenceMethods *m; + PySequenceMethods *m; - if (o == NULL) - return null_error(); + if (o == NULL) + return null_error(); - m = o->ob_type->tp_as_sequence; - if (m && m->sq_repeat) - return m->sq_repeat(o, count); - - /* Instances of user classes defining a __mul__() method only - have an nb_multiply slot, not an sq_repeat slot. so we fall back - to nb_multiply if o appears to be a sequence. */ - if (PySequence_Check(o)) { - PyObject *n, *result; - n = PyLong_FromSsize_t(count); - if (n == NULL) - return NULL; - result = binary_op1(o, n, NB_SLOT(nb_multiply)); - Py_DECREF(n); - if (result != Py_NotImplemented) - return result; - Py_DECREF(result); - } - return type_error("'%.200s' object can't be repeated", o); + m = o->ob_type->tp_as_sequence; + if (m && m->sq_repeat) + return m->sq_repeat(o, count); + + /* Instances of user classes defining a __mul__() method only + have an nb_multiply slot, not an sq_repeat slot. so we fall back + to nb_multiply if o appears to be a sequence. */ + if (PySequence_Check(o)) { + PyObject *n, *result; + n = PyLong_FromSsize_t(count); + if (n == NULL) + return NULL; + result = binary_op1(o, n, NB_SLOT(nb_multiply)); + Py_DECREF(n); + if (result != Py_NotImplemented) + return result; + Py_DECREF(result); + } + return type_error("'%.200s' object can't be repeated", o); } PyObject * PySequence_InPlaceConcat(PyObject *s, PyObject *o) { - PySequenceMethods *m; + PySequenceMethods *m; - if (s == NULL || o == NULL) - return null_error(); + if (s == NULL || o == NULL) + return null_error(); - m = s->ob_type->tp_as_sequence; - if (m && m->sq_inplace_concat) - return m->sq_inplace_concat(s, o); - if (m && m->sq_concat) - return m->sq_concat(s, o); - - if (PySequence_Check(s) && PySequence_Check(o)) { - PyObject *result = binary_iop1(s, o, NB_SLOT(nb_inplace_add), - NB_SLOT(nb_add)); - if (result != Py_NotImplemented) - return result; - Py_DECREF(result); - } - return type_error("'%.200s' object can't be concatenated", s); + m = s->ob_type->tp_as_sequence; + if (m && m->sq_inplace_concat) + return m->sq_inplace_concat(s, o); + if (m && m->sq_concat) + return m->sq_concat(s, o); + + if (PySequence_Check(s) && PySequence_Check(o)) { + PyObject *result = binary_iop1(s, o, NB_SLOT(nb_inplace_add), + NB_SLOT(nb_add)); + if (result != Py_NotImplemented) + return result; + Py_DECREF(result); + } + return type_error("'%.200s' object can't be concatenated", s); } PyObject * PySequence_InPlaceRepeat(PyObject *o, Py_ssize_t count) { - PySequenceMethods *m; + PySequenceMethods *m; - if (o == NULL) - return null_error(); + if (o == NULL) + return null_error(); - m = o->ob_type->tp_as_sequence; - if (m && m->sq_inplace_repeat) - return m->sq_inplace_repeat(o, count); - if (m && m->sq_repeat) - return m->sq_repeat(o, count); - - if (PySequence_Check(o)) { - PyObject *n, *result; - n = PyLong_FromSsize_t(count); - if (n == NULL) - return NULL; - result = binary_iop1(o, n, NB_SLOT(nb_inplace_multiply), - NB_SLOT(nb_multiply)); - Py_DECREF(n); - if (result != Py_NotImplemented) - return result; - Py_DECREF(result); - } - return type_error("'%.200s' object can't be repeated", o); + m = o->ob_type->tp_as_sequence; + if (m && m->sq_inplace_repeat) + return m->sq_inplace_repeat(o, count); + if (m && m->sq_repeat) + return m->sq_repeat(o, count); + + if (PySequence_Check(o)) { + PyObject *n, *result; + n = PyLong_FromSsize_t(count); + if (n == NULL) + return NULL; + result = binary_iop1(o, n, NB_SLOT(nb_inplace_multiply), + NB_SLOT(nb_multiply)); + Py_DECREF(n); + if (result != Py_NotImplemented) + return result; + Py_DECREF(result); + } + return type_error("'%.200s' object can't be repeated", o); } PyObject * PySequence_GetItem(PyObject *s, Py_ssize_t i) { - PySequenceMethods *m; + PySequenceMethods *m; - if (s == NULL) - return null_error(); + if (s == NULL) + return null_error(); - m = s->ob_type->tp_as_sequence; - if (m && m->sq_item) { - if (i < 0) { - if (m->sq_length) { - Py_ssize_t l = (*m->sq_length)(s); - if (l < 0) - return NULL; - i += l; - } - } - return m->sq_item(s, i); - } + m = s->ob_type->tp_as_sequence; + if (m && m->sq_item) { + if (i < 0) { + if (m->sq_length) { + Py_ssize_t l = (*m->sq_length)(s); + if (l < 0) + return NULL; + i += l; + } + } + return m->sq_item(s, i); + } - return type_error("'%.200s' object does not support indexing", s); + return type_error("'%.200s' object does not support indexing", s); } PyObject * PySequence_GetSlice(PyObject *s, Py_ssize_t i1, Py_ssize_t i2) { - PyMappingMethods *mp; + PyMappingMethods *mp; - if (!s) return null_error(); + if (!s) return null_error(); - mp = s->ob_type->tp_as_mapping; - if (mp->mp_subscript) { - PyObject *res; - PyObject *slice = _PySlice_FromIndices(i1, i2); - if (!slice) - return NULL; - res = mp->mp_subscript(s, slice); - Py_DECREF(slice); - return res; - } + mp = s->ob_type->tp_as_mapping; + if (mp->mp_subscript) { + PyObject *res; + PyObject *slice = _PySlice_FromIndices(i1, i2); + if (!slice) + return NULL; + res = mp->mp_subscript(s, slice); + Py_DECREF(slice); + return res; + } - return type_error("'%.200s' object is unsliceable", s); + return type_error("'%.200s' object is unsliceable", s); } int PySequence_SetItem(PyObject *s, Py_ssize_t i, PyObject *o) { - PySequenceMethods *m; + PySequenceMethods *m; + + if (s == NULL) { + null_error(); + return -1; + } - if (s == NULL) { - null_error(); - return -1; - } - - m = s->ob_type->tp_as_sequence; - if (m && m->sq_ass_item) { - if (i < 0) { - if (m->sq_length) { - Py_ssize_t l = (*m->sq_length)(s); - if (l < 0) - return -1; - i += l; - } - } - return m->sq_ass_item(s, i, o); - } + m = s->ob_type->tp_as_sequence; + if (m && m->sq_ass_item) { + if (i < 0) { + if (m->sq_length) { + Py_ssize_t l = (*m->sq_length)(s); + if (l < 0) + return -1; + i += l; + } + } + return m->sq_ass_item(s, i, o); + } - type_error("'%.200s' object does not support item assignment", s); - return -1; + type_error("'%.200s' object does not support item assignment", s); + return -1; } int PySequence_DelItem(PyObject *s, Py_ssize_t i) { - PySequenceMethods *m; + PySequenceMethods *m; - if (s == NULL) { - null_error(); - return -1; - } - - m = s->ob_type->tp_as_sequence; - if (m && m->sq_ass_item) { - if (i < 0) { - if (m->sq_length) { - Py_ssize_t l = (*m->sq_length)(s); - if (l < 0) - return -1; - i += l; - } - } - return m->sq_ass_item(s, i, (PyObject *)NULL); - } + if (s == NULL) { + null_error(); + return -1; + } - type_error("'%.200s' object doesn't support item deletion", s); - return -1; + m = s->ob_type->tp_as_sequence; + if (m && m->sq_ass_item) { + if (i < 0) { + if (m->sq_length) { + Py_ssize_t l = (*m->sq_length)(s); + if (l < 0) + return -1; + i += l; + } + } + return m->sq_ass_item(s, i, (PyObject *)NULL); + } + + type_error("'%.200s' object doesn't support item deletion", s); + return -1; } int PySequence_SetSlice(PyObject *s, Py_ssize_t i1, Py_ssize_t i2, PyObject *o) { - PyMappingMethods *mp; + PyMappingMethods *mp; + + if (s == NULL) { + null_error(); + return -1; + } - if (s == NULL) { - null_error(); - return -1; - } - - mp = s->ob_type->tp_as_mapping; - if (mp->mp_ass_subscript) { - int res; - PyObject *slice = _PySlice_FromIndices(i1, i2); - if (!slice) - return -1; - res = mp->mp_ass_subscript(s, slice, o); - Py_DECREF(slice); - return res; - } + mp = s->ob_type->tp_as_mapping; + if (mp->mp_ass_subscript) { + int res; + PyObject *slice = _PySlice_FromIndices(i1, i2); + if (!slice) + return -1; + res = mp->mp_ass_subscript(s, slice, o); + Py_DECREF(slice); + return res; + } - type_error("'%.200s' object doesn't support slice assignment", s); - return -1; + type_error("'%.200s' object doesn't support slice assignment", s); + return -1; } int PySequence_DelSlice(PyObject *s, Py_ssize_t i1, Py_ssize_t i2) { - PyMappingMethods *mp; + PyMappingMethods *mp; + + if (s == NULL) { + null_error(); + return -1; + } - if (s == NULL) { - null_error(); - return -1; - } - - mp = s->ob_type->tp_as_mapping; - if (mp->mp_ass_subscript) { - int res; - PyObject *slice = _PySlice_FromIndices(i1, i2); - if (!slice) - return -1; - res = mp->mp_ass_subscript(s, slice, NULL); - Py_DECREF(slice); - return res; - } - type_error("'%.200s' object doesn't support slice deletion", s); - return -1; + mp = s->ob_type->tp_as_mapping; + if (mp->mp_ass_subscript) { + int res; + PyObject *slice = _PySlice_FromIndices(i1, i2); + if (!slice) + return -1; + res = mp->mp_ass_subscript(s, slice, NULL); + Py_DECREF(slice); + return res; + } + type_error("'%.200s' object doesn't support slice deletion", s); + return -1; } PyObject * PySequence_Tuple(PyObject *v) { - PyObject *it; /* iter(v) */ - Py_ssize_t n; /* guess for result tuple size */ - PyObject *result = NULL; - Py_ssize_t j; - - if (v == NULL) - return null_error(); - - /* Special-case the common tuple and list cases, for efficiency. */ - if (PyTuple_CheckExact(v)) { - /* Note that we can't know whether it's safe to return - a tuple *subclass* instance as-is, hence the restriction - to exact tuples here. In contrast, lists always make - a copy, so there's no need for exactness below. */ - Py_INCREF(v); - return v; - } - if (PyList_Check(v)) - return PyList_AsTuple(v); - - /* Get iterator. */ - it = PyObject_GetIter(v); - if (it == NULL) - return NULL; - - /* Guess result size and allocate space. */ - n = _PyObject_LengthHint(v, 10); - if (n == -1) - goto Fail; - result = PyTuple_New(n); - if (result == NULL) - goto Fail; - - /* Fill the tuple. */ - for (j = 0; ; ++j) { - PyObject *item = PyIter_Next(it); - if (item == NULL) { - if (PyErr_Occurred()) - goto Fail; - break; - } - if (j >= n) { - Py_ssize_t oldn = n; - /* The over-allocation strategy can grow a bit faster - than for lists because unlike lists the - over-allocation isn't permanent -- we reclaim - the excess before the end of this routine. - So, grow by ten and then add 25%. - */ - n += 10; - n += n >> 2; - if (n < oldn) { - /* Check for overflow */ - PyErr_NoMemory(); - Py_DECREF(item); - goto Fail; - } - if (_PyTuple_Resize(&result, n) != 0) { - Py_DECREF(item); - goto Fail; - } - } - PyTuple_SET_ITEM(result, j, item); - } - - /* Cut tuple back if guess was too large. */ - if (j < n && - _PyTuple_Resize(&result, j) != 0) - goto Fail; + PyObject *it; /* iter(v) */ + Py_ssize_t n; /* guess for result tuple size */ + PyObject *result = NULL; + Py_ssize_t j; + + if (v == NULL) + return null_error(); + + /* Special-case the common tuple and list cases, for efficiency. */ + if (PyTuple_CheckExact(v)) { + /* Note that we can't know whether it's safe to return + a tuple *subclass* instance as-is, hence the restriction + to exact tuples here. In contrast, lists always make + a copy, so there's no need for exactness below. */ + Py_INCREF(v); + return v; + } + if (PyList_Check(v)) + return PyList_AsTuple(v); + + /* Get iterator. */ + it = PyObject_GetIter(v); + if (it == NULL) + return NULL; + + /* Guess result size and allocate space. */ + n = _PyObject_LengthHint(v, 10); + if (n == -1) + goto Fail; + result = PyTuple_New(n); + if (result == NULL) + goto Fail; + + /* Fill the tuple. */ + for (j = 0; ; ++j) { + PyObject *item = PyIter_Next(it); + if (item == NULL) { + if (PyErr_Occurred()) + goto Fail; + break; + } + if (j >= n) { + Py_ssize_t oldn = n; + /* The over-allocation strategy can grow a bit faster + than for lists because unlike lists the + over-allocation isn't permanent -- we reclaim + the excess before the end of this routine. + So, grow by ten and then add 25%. + */ + n += 10; + n += n >> 2; + if (n < oldn) { + /* Check for overflow */ + PyErr_NoMemory(); + Py_DECREF(item); + goto Fail; + } + if (_PyTuple_Resize(&result, n) != 0) { + Py_DECREF(item); + goto Fail; + } + } + PyTuple_SET_ITEM(result, j, item); + } - Py_DECREF(it); - return result; + /* Cut tuple back if guess was too large. */ + if (j < n && + _PyTuple_Resize(&result, j) != 0) + goto Fail; + + Py_DECREF(it); + return result; Fail: - Py_XDECREF(result); - Py_DECREF(it); - return NULL; + Py_XDECREF(result); + Py_DECREF(it); + return NULL; } PyObject * PySequence_List(PyObject *v) { - PyObject *result; /* result list */ - PyObject *rv; /* return value from PyList_Extend */ + PyObject *result; /* result list */ + PyObject *rv; /* return value from PyList_Extend */ + + if (v == NULL) + return null_error(); - if (v == NULL) - return null_error(); + result = PyList_New(0); + if (result == NULL) + return NULL; - result = PyList_New(0); - if (result == NULL) - return NULL; - - rv = _PyList_Extend((PyListObject *)result, v); - if (rv == NULL) { - Py_DECREF(result); - return NULL; - } - Py_DECREF(rv); - return result; + rv = _PyList_Extend((PyListObject *)result, v); + if (rv == NULL) { + Py_DECREF(result); + return NULL; + } + Py_DECREF(rv); + return result; } PyObject * PySequence_Fast(PyObject *v, const char *m) { - PyObject *it; + PyObject *it; - if (v == NULL) - return null_error(); + if (v == NULL) + return null_error(); + + if (PyList_CheckExact(v) || PyTuple_CheckExact(v)) { + Py_INCREF(v); + return v; + } - if (PyList_CheckExact(v) || PyTuple_CheckExact(v)) { - Py_INCREF(v); - return v; - } - - it = PyObject_GetIter(v); - if (it == NULL) { - if (PyErr_ExceptionMatches(PyExc_TypeError)) - PyErr_SetString(PyExc_TypeError, m); - return NULL; - } + it = PyObject_GetIter(v); + if (it == NULL) { + if (PyErr_ExceptionMatches(PyExc_TypeError)) + PyErr_SetString(PyExc_TypeError, m); + return NULL; + } - v = PySequence_List(it); - Py_DECREF(it); + v = PySequence_List(it); + Py_DECREF(it); - return v; + return v; } /* Iterate over seq. Result depends on the operation: - PY_ITERSEARCH_COUNT: -1 if error, else # of times obj appears in seq. - PY_ITERSEARCH_INDEX: 0-based index of first occurrence of obj in seq; - set ValueError and return -1 if none found; also return -1 on error. + PY_ITERSEARCH_COUNT: -1 if error, else # of times obj appears in seq. + PY_ITERSEARCH_INDEX: 0-based index of first occurrence of obj in seq; + set ValueError and return -1 if none found; also return -1 on error. Py_ITERSEARCH_CONTAINS: return 1 if obj in seq, else 0; -1 on error. */ Py_ssize_t _PySequence_IterSearch(PyObject *seq, PyObject *obj, int operation) { - Py_ssize_t n; - int wrapped; /* for PY_ITERSEARCH_INDEX, true iff n wrapped around */ - PyObject *it; /* iter(seq) */ - - if (seq == NULL || obj == NULL) { - null_error(); - return -1; - } - - it = PyObject_GetIter(seq); - if (it == NULL) { - type_error("argument of type '%.200s' is not iterable", seq); - return -1; - } - - n = wrapped = 0; - for (;;) { - int cmp; - PyObject *item = PyIter_Next(it); - if (item == NULL) { - if (PyErr_Occurred()) - goto Fail; - break; - } - - cmp = PyObject_RichCompareBool(obj, item, Py_EQ); - Py_DECREF(item); - if (cmp < 0) - goto Fail; - if (cmp > 0) { - switch (operation) { - case PY_ITERSEARCH_COUNT: - if (n == PY_SSIZE_T_MAX) { - PyErr_SetString(PyExc_OverflowError, - "count exceeds C integer size"); - goto Fail; - } - ++n; - break; - - case PY_ITERSEARCH_INDEX: - if (wrapped) { - PyErr_SetString(PyExc_OverflowError, - "index exceeds C integer size"); - goto Fail; - } - goto Done; - - case PY_ITERSEARCH_CONTAINS: - n = 1; - goto Done; - - default: - assert(!"unknown operation"); - } - } - - if (operation == PY_ITERSEARCH_INDEX) { - if (n == PY_SSIZE_T_MAX) - wrapped = 1; - ++n; - } - } - - if (operation != PY_ITERSEARCH_INDEX) - goto Done; - - PyErr_SetString(PyExc_ValueError, - "sequence.index(x): x not in sequence"); - /* fall into failure code */ + Py_ssize_t n; + int wrapped; /* for PY_ITERSEARCH_INDEX, true iff n wrapped around */ + PyObject *it; /* iter(seq) */ + + if (seq == NULL || obj == NULL) { + null_error(); + return -1; + } + + it = PyObject_GetIter(seq); + if (it == NULL) { + type_error("argument of type '%.200s' is not iterable", seq); + return -1; + } + + n = wrapped = 0; + for (;;) { + int cmp; + PyObject *item = PyIter_Next(it); + if (item == NULL) { + if (PyErr_Occurred()) + goto Fail; + break; + } + + cmp = PyObject_RichCompareBool(obj, item, Py_EQ); + Py_DECREF(item); + if (cmp < 0) + goto Fail; + if (cmp > 0) { + switch (operation) { + case PY_ITERSEARCH_COUNT: + if (n == PY_SSIZE_T_MAX) { + PyErr_SetString(PyExc_OverflowError, + "count exceeds C integer size"); + goto Fail; + } + ++n; + break; + + case PY_ITERSEARCH_INDEX: + if (wrapped) { + PyErr_SetString(PyExc_OverflowError, + "index exceeds C integer size"); + goto Fail; + } + goto Done; + + case PY_ITERSEARCH_CONTAINS: + n = 1; + goto Done; + + default: + assert(!"unknown operation"); + } + } + + if (operation == PY_ITERSEARCH_INDEX) { + if (n == PY_SSIZE_T_MAX) + wrapped = 1; + ++n; + } + } + + if (operation != PY_ITERSEARCH_INDEX) + goto Done; + + PyErr_SetString(PyExc_ValueError, + "sequence.index(x): x not in sequence"); + /* fall into failure code */ Fail: - n = -1; - /* fall through */ + n = -1; + /* fall through */ Done: - Py_DECREF(it); - return n; + Py_DECREF(it); + return n; } @@ -1961,7 +1961,7 @@ Py_ssize_t PySequence_Count(PyObject *s, PyObject *o) { - return _PySequence_IterSearch(s, o, PY_ITERSEARCH_COUNT); + return _PySequence_IterSearch(s, o, PY_ITERSEARCH_COUNT); } /* Return -1 if error; 1 if ob in seq; 0 if ob not in seq. @@ -1970,12 +1970,12 @@ int PySequence_Contains(PyObject *seq, PyObject *ob) { - Py_ssize_t result; - PySequenceMethods *sqm = seq->ob_type->tp_as_sequence; - if (sqm != NULL && sqm->sq_contains != NULL) - return (*sqm->sq_contains)(seq, ob); - result = _PySequence_IterSearch(seq, ob, PY_ITERSEARCH_CONTAINS); - return Py_SAFE_DOWNCAST(result, Py_ssize_t, int); + Py_ssize_t result; + PySequenceMethods *sqm = seq->ob_type->tp_as_sequence; + if (sqm != NULL && sqm->sq_contains != NULL) + return (*sqm->sq_contains)(seq, ob); + result = _PySequence_IterSearch(seq, ob, PY_ITERSEARCH_CONTAINS); + return Py_SAFE_DOWNCAST(result, Py_ssize_t, int); } /* Backwards compatibility */ @@ -1983,13 +1983,13 @@ int PySequence_In(PyObject *w, PyObject *v) { - return PySequence_Contains(w, v); + return PySequence_Contains(w, v); } Py_ssize_t PySequence_Index(PyObject *s, PyObject *o) { - return _PySequence_IterSearch(s, o, PY_ITERSEARCH_INDEX); + return _PySequence_IterSearch(s, o, PY_ITERSEARCH_INDEX); } /* Operations on mappings */ @@ -1997,145 +1997,145 @@ int PyMapping_Check(PyObject *o) { - return o && o->ob_type->tp_as_mapping && - o->ob_type->tp_as_mapping->mp_subscript; + return o && o->ob_type->tp_as_mapping && + o->ob_type->tp_as_mapping->mp_subscript; } Py_ssize_t PyMapping_Size(PyObject *o) { - PyMappingMethods *m; + PyMappingMethods *m; - if (o == NULL) { - null_error(); - return -1; - } - - m = o->ob_type->tp_as_mapping; - if (m && m->mp_length) - return m->mp_length(o); + if (o == NULL) { + null_error(); + return -1; + } + + m = o->ob_type->tp_as_mapping; + if (m && m->mp_length) + return m->mp_length(o); - type_error("object of type '%.200s' has no len()", o); - return -1; + type_error("object of type '%.200s' has no len()", o); + return -1; } #undef PyMapping_Length Py_ssize_t PyMapping_Length(PyObject *o) { - return PyMapping_Size(o); + return PyMapping_Size(o); } #define PyMapping_Length PyMapping_Size PyObject * PyMapping_GetItemString(PyObject *o, char *key) { - PyObject *okey, *r; + PyObject *okey, *r; - if (key == NULL) - return null_error(); + if (key == NULL) + return null_error(); - okey = PyUnicode_FromString(key); - if (okey == NULL) - return NULL; - r = PyObject_GetItem(o, okey); - Py_DECREF(okey); - return r; + okey = PyUnicode_FromString(key); + if (okey == NULL) + return NULL; + r = PyObject_GetItem(o, okey); + Py_DECREF(okey); + return r; } int PyMapping_SetItemString(PyObject *o, char *key, PyObject *value) { - PyObject *okey; - int r; + PyObject *okey; + int r; - if (key == NULL) { - null_error(); - return -1; - } - - okey = PyUnicode_FromString(key); - if (okey == NULL) - return -1; - r = PyObject_SetItem(o, okey, value); - Py_DECREF(okey); - return r; + if (key == NULL) { + null_error(); + return -1; + } + + okey = PyUnicode_FromString(key); + if (okey == NULL) + return -1; + r = PyObject_SetItem(o, okey, value); + Py_DECREF(okey); + return r; } int PyMapping_HasKeyString(PyObject *o, char *key) { - PyObject *v; + PyObject *v; - v = PyMapping_GetItemString(o, key); - if (v) { - Py_DECREF(v); - return 1; - } - PyErr_Clear(); - return 0; + v = PyMapping_GetItemString(o, key); + if (v) { + Py_DECREF(v); + return 1; + } + PyErr_Clear(); + return 0; } int PyMapping_HasKey(PyObject *o, PyObject *key) { - PyObject *v; + PyObject *v; - v = PyObject_GetItem(o, key); - if (v) { - Py_DECREF(v); - return 1; - } - PyErr_Clear(); - return 0; + v = PyObject_GetItem(o, key); + if (v) { + Py_DECREF(v); + return 1; + } + PyErr_Clear(); + return 0; } PyObject * PyMapping_Keys(PyObject *o) { - PyObject *keys; - PyObject *fast; + PyObject *keys; + PyObject *fast; - if (PyDict_CheckExact(o)) - return PyDict_Keys(o); - keys = PyObject_CallMethod(o, "keys", NULL); - if (keys == NULL) - return NULL; - fast = PySequence_Fast(keys, "o.keys() are not iterable"); - Py_DECREF(keys); - return fast; + if (PyDict_CheckExact(o)) + return PyDict_Keys(o); + keys = PyObject_CallMethod(o, "keys", NULL); + if (keys == NULL) + return NULL; + fast = PySequence_Fast(keys, "o.keys() are not iterable"); + Py_DECREF(keys); + return fast; } PyObject * PyMapping_Items(PyObject *o) { - PyObject *items; - PyObject *fast; + PyObject *items; + PyObject *fast; - if (PyDict_CheckExact(o)) - return PyDict_Items(o); - items = PyObject_CallMethod(o, "items", NULL); - if (items == NULL) - return NULL; - fast = PySequence_Fast(items, "o.items() are not iterable"); - Py_DECREF(items); - return fast; + if (PyDict_CheckExact(o)) + return PyDict_Items(o); + items = PyObject_CallMethod(o, "items", NULL); + if (items == NULL) + return NULL; + fast = PySequence_Fast(items, "o.items() are not iterable"); + Py_DECREF(items); + return fast; } PyObject * PyMapping_Values(PyObject *o) { - PyObject *values; - PyObject *fast; + PyObject *values; + PyObject *fast; - if (PyDict_CheckExact(o)) - return PyDict_Values(o); - values = PyObject_CallMethod(o, "values", NULL); - if (values == NULL) - return NULL; - fast = PySequence_Fast(values, "o.values() are not iterable"); - Py_DECREF(values); - return fast; + if (PyDict_CheckExact(o)) + return PyDict_Values(o); + values = PyObject_CallMethod(o, "values", NULL); + if (values == NULL) + return NULL; + fast = PySequence_Fast(values, "o.values() are not iterable"); + Py_DECREF(values); + return fast; } /* Operations on callable objects */ @@ -2145,253 +2145,253 @@ PyObject * PyObject_CallObject(PyObject *o, PyObject *a) { - return PyEval_CallObjectWithKeywords(o, a, NULL); + return PyEval_CallObjectWithKeywords(o, a, NULL); } PyObject * PyObject_Call(PyObject *func, PyObject *arg, PyObject *kw) { - ternaryfunc call; + ternaryfunc call; - if ((call = func->ob_type->tp_call) != NULL) { - PyObject *result; - if (Py_EnterRecursiveCall(" while calling a Python object")) - return NULL; - result = (*call)(func, arg, kw); - Py_LeaveRecursiveCall(); - if (result == NULL && !PyErr_Occurred()) - PyErr_SetString( - PyExc_SystemError, - "NULL result without error in PyObject_Call"); - return result; - } - PyErr_Format(PyExc_TypeError, "'%.200s' object is not callable", - func->ob_type->tp_name); - return NULL; + if ((call = func->ob_type->tp_call) != NULL) { + PyObject *result; + if (Py_EnterRecursiveCall(" while calling a Python object")) + return NULL; + result = (*call)(func, arg, kw); + Py_LeaveRecursiveCall(); + if (result == NULL && !PyErr_Occurred()) + PyErr_SetString( + PyExc_SystemError, + "NULL result without error in PyObject_Call"); + return result; + } + PyErr_Format(PyExc_TypeError, "'%.200s' object is not callable", + func->ob_type->tp_name); + return NULL; } static PyObject* call_function_tail(PyObject *callable, PyObject *args) { - PyObject *retval; + PyObject *retval; - if (args == NULL) - return NULL; + if (args == NULL) + return NULL; - if (!PyTuple_Check(args)) { - PyObject *a; + if (!PyTuple_Check(args)) { + PyObject *a; - a = PyTuple_New(1); - if (a == NULL) { - Py_DECREF(args); - return NULL; - } - PyTuple_SET_ITEM(a, 0, args); - args = a; - } - retval = PyObject_Call(callable, args, NULL); + a = PyTuple_New(1); + if (a == NULL) { + Py_DECREF(args); + return NULL; + } + PyTuple_SET_ITEM(a, 0, args); + args = a; + } + retval = PyObject_Call(callable, args, NULL); - Py_DECREF(args); + Py_DECREF(args); - return retval; + return retval; } PyObject * PyObject_CallFunction(PyObject *callable, char *format, ...) { - va_list va; - PyObject *args; + va_list va; + PyObject *args; - if (callable == NULL) - return null_error(); + if (callable == NULL) + return null_error(); - if (format && *format) { - va_start(va, format); - args = Py_VaBuildValue(format, va); - va_end(va); - } - else - args = PyTuple_New(0); + if (format && *format) { + va_start(va, format); + args = Py_VaBuildValue(format, va); + va_end(va); + } + else + args = PyTuple_New(0); - return call_function_tail(callable, args); + return call_function_tail(callable, args); } PyObject * _PyObject_CallFunction_SizeT(PyObject *callable, char *format, ...) { - va_list va; - PyObject *args; + va_list va; + PyObject *args; - if (callable == NULL) - return null_error(); + if (callable == NULL) + return null_error(); - if (format && *format) { - va_start(va, format); - args = _Py_VaBuildValue_SizeT(format, va); - va_end(va); - } - else - args = PyTuple_New(0); + if (format && *format) { + va_start(va, format); + args = _Py_VaBuildValue_SizeT(format, va); + va_end(va); + } + else + args = PyTuple_New(0); - return call_function_tail(callable, args); + return call_function_tail(callable, args); } PyObject * PyObject_CallMethod(PyObject *o, char *name, char *format, ...) { - va_list va; - PyObject *args; - PyObject *func = NULL; - PyObject *retval = NULL; - - if (o == NULL || name == NULL) - return null_error(); - - func = PyObject_GetAttrString(o, name); - if (func == NULL) { - PyErr_SetString(PyExc_AttributeError, name); - return 0; - } - - if (!PyCallable_Check(func)) { - type_error("attribute of type '%.200s' is not callable", func); - goto exit; - } - - if (format && *format) { - va_start(va, format); - args = Py_VaBuildValue(format, va); - va_end(va); - } - else - args = PyTuple_New(0); + va_list va; + PyObject *args; + PyObject *func = NULL; + PyObject *retval = NULL; + + if (o == NULL || name == NULL) + return null_error(); + + func = PyObject_GetAttrString(o, name); + if (func == NULL) { + PyErr_SetString(PyExc_AttributeError, name); + return 0; + } + + if (!PyCallable_Check(func)) { + type_error("attribute of type '%.200s' is not callable", func); + goto exit; + } - retval = call_function_tail(func, args); + if (format && *format) { + va_start(va, format); + args = Py_VaBuildValue(format, va); + va_end(va); + } + else + args = PyTuple_New(0); + + retval = call_function_tail(func, args); exit: - /* args gets consumed in call_function_tail */ - Py_XDECREF(func); + /* args gets consumed in call_function_tail */ + Py_XDECREF(func); - return retval; + return retval; } PyObject * _PyObject_CallMethod_SizeT(PyObject *o, char *name, char *format, ...) { - va_list va; - PyObject *args; - PyObject *func = NULL; - PyObject *retval = NULL; - - if (o == NULL || name == NULL) - return null_error(); - - func = PyObject_GetAttrString(o, name); - if (func == NULL) { - PyErr_SetString(PyExc_AttributeError, name); - return 0; - } - - if (!PyCallable_Check(func)) { - type_error("attribute of type '%.200s' is not callable", func); - goto exit; - } - - if (format && *format) { - va_start(va, format); - args = _Py_VaBuildValue_SizeT(format, va); - va_end(va); - } - else - args = PyTuple_New(0); + va_list va; + PyObject *args; + PyObject *func = NULL; + PyObject *retval = NULL; + + if (o == NULL || name == NULL) + return null_error(); + + func = PyObject_GetAttrString(o, name); + if (func == NULL) { + PyErr_SetString(PyExc_AttributeError, name); + return 0; + } - retval = call_function_tail(func, args); + if (!PyCallable_Check(func)) { + type_error("attribute of type '%.200s' is not callable", func); + goto exit; + } + + if (format && *format) { + va_start(va, format); + args = _Py_VaBuildValue_SizeT(format, va); + va_end(va); + } + else + args = PyTuple_New(0); + + retval = call_function_tail(func, args); exit: - /* args gets consumed in call_function_tail */ - Py_XDECREF(func); + /* args gets consumed in call_function_tail */ + Py_XDECREF(func); - return retval; + return retval; } static PyObject * objargs_mktuple(va_list va) { - int i, n = 0; - va_list countva; - PyObject *result, *tmp; + int i, n = 0; + va_list countva; + PyObject *result, *tmp; #ifdef VA_LIST_IS_ARRAY - memcpy(countva, va, sizeof(va_list)); + memcpy(countva, va, sizeof(va_list)); #else #ifdef __va_copy - __va_copy(countva, va); + __va_copy(countva, va); #else - countva = va; + countva = va; #endif #endif - while (((PyObject *)va_arg(countva, PyObject *)) != NULL) - ++n; - result = PyTuple_New(n); - if (result != NULL && n > 0) { - for (i = 0; i < n; ++i) { - tmp = (PyObject *)va_arg(va, PyObject *); - PyTuple_SET_ITEM(result, i, tmp); - Py_INCREF(tmp); - } - } - return result; + while (((PyObject *)va_arg(countva, PyObject *)) != NULL) + ++n; + result = PyTuple_New(n); + if (result != NULL && n > 0) { + for (i = 0; i < n; ++i) { + tmp = (PyObject *)va_arg(va, PyObject *); + PyTuple_SET_ITEM(result, i, tmp); + Py_INCREF(tmp); + } + } + return result; } PyObject * PyObject_CallMethodObjArgs(PyObject *callable, PyObject *name, ...) { - PyObject *args, *tmp; - va_list vargs; + PyObject *args, *tmp; + va_list vargs; - if (callable == NULL || name == NULL) - return null_error(); + if (callable == NULL || name == NULL) + return null_error(); - callable = PyObject_GetAttr(callable, name); - if (callable == NULL) - return NULL; - - /* count the args */ - va_start(vargs, name); - args = objargs_mktuple(vargs); - va_end(vargs); - if (args == NULL) { - Py_DECREF(callable); - return NULL; - } - tmp = PyObject_Call(callable, args, NULL); - Py_DECREF(args); - Py_DECREF(callable); + callable = PyObject_GetAttr(callable, name); + if (callable == NULL) + return NULL; + + /* count the args */ + va_start(vargs, name); + args = objargs_mktuple(vargs); + va_end(vargs); + if (args == NULL) { + Py_DECREF(callable); + return NULL; + } + tmp = PyObject_Call(callable, args, NULL); + Py_DECREF(args); + Py_DECREF(callable); - return tmp; + return tmp; } PyObject * PyObject_CallFunctionObjArgs(PyObject *callable, ...) { - PyObject *args, *tmp; - va_list vargs; + PyObject *args, *tmp; + va_list vargs; - if (callable == NULL) - return null_error(); + if (callable == NULL) + return null_error(); - /* count the args */ - va_start(vargs, callable); - args = objargs_mktuple(vargs); - va_end(vargs); - if (args == NULL) - return NULL; - tmp = PyObject_Call(callable, args, NULL); - Py_DECREF(args); + /* count the args */ + va_start(vargs, callable); + args = objargs_mktuple(vargs); + va_end(vargs); + if (args == NULL) + return NULL; + tmp = PyObject_Call(callable, args, NULL); + Py_DECREF(args); - return tmp; + return tmp; } @@ -2415,7 +2415,7 @@ * produce exactly the same results: NULL is returned and no error is set. * * If some exception other than AttributeError is raised, then NULL is also - * returned, but the exception is not cleared. That's because we want the + * returned, but the exception is not cleared. That's because we want the * exception to be propagated along. * * Callers are expected to test for PyErr_Occurred() when the return value @@ -2426,282 +2426,282 @@ static PyObject * abstract_get_bases(PyObject *cls) { - static PyObject *__bases__ = NULL; - PyObject *bases; + static PyObject *__bases__ = NULL; + PyObject *bases; - if (__bases__ == NULL) { - __bases__ = PyUnicode_InternFromString("__bases__"); - if (__bases__ == NULL) - return NULL; - } - Py_ALLOW_RECURSION - bases = PyObject_GetAttr(cls, __bases__); - Py_END_ALLOW_RECURSION - if (bases == NULL) { - if (PyErr_ExceptionMatches(PyExc_AttributeError)) - PyErr_Clear(); - return NULL; - } - if (!PyTuple_Check(bases)) { - Py_DECREF(bases); - return NULL; - } - return bases; + if (__bases__ == NULL) { + __bases__ = PyUnicode_InternFromString("__bases__"); + if (__bases__ == NULL) + return NULL; + } + Py_ALLOW_RECURSION + bases = PyObject_GetAttr(cls, __bases__); + Py_END_ALLOW_RECURSION + if (bases == NULL) { + if (PyErr_ExceptionMatches(PyExc_AttributeError)) + PyErr_Clear(); + return NULL; + } + if (!PyTuple_Check(bases)) { + Py_DECREF(bases); + return NULL; + } + return bases; } static int abstract_issubclass(PyObject *derived, PyObject *cls) { - PyObject *bases = NULL; - Py_ssize_t i, n; - int r = 0; - - while (1) { - if (derived == cls) - return 1; - bases = abstract_get_bases(derived); - if (bases == NULL) { - if (PyErr_Occurred()) - return -1; - return 0; - } - n = PyTuple_GET_SIZE(bases); - if (n == 0) { - Py_DECREF(bases); - return 0; - } - /* Avoid recursivity in the single inheritance case */ - if (n == 1) { - derived = PyTuple_GET_ITEM(bases, 0); - Py_DECREF(bases); - continue; - } - for (i = 0; i < n; i++) { - r = abstract_issubclass(PyTuple_GET_ITEM(bases, i), cls); - if (r != 0) - break; - } - Py_DECREF(bases); - return r; - } + PyObject *bases = NULL; + Py_ssize_t i, n; + int r = 0; + + while (1) { + if (derived == cls) + return 1; + bases = abstract_get_bases(derived); + if (bases == NULL) { + if (PyErr_Occurred()) + return -1; + return 0; + } + n = PyTuple_GET_SIZE(bases); + if (n == 0) { + Py_DECREF(bases); + return 0; + } + /* Avoid recursivity in the single inheritance case */ + if (n == 1) { + derived = PyTuple_GET_ITEM(bases, 0); + Py_DECREF(bases); + continue; + } + for (i = 0; i < n; i++) { + r = abstract_issubclass(PyTuple_GET_ITEM(bases, i), cls); + if (r != 0) + break; + } + Py_DECREF(bases); + return r; + } } static int check_class(PyObject *cls, const char *error) { - PyObject *bases = abstract_get_bases(cls); - if (bases == NULL) { - /* Do not mask errors. */ - if (!PyErr_Occurred()) - PyErr_SetString(PyExc_TypeError, error); - return 0; - } - Py_DECREF(bases); - return -1; + PyObject *bases = abstract_get_bases(cls); + if (bases == NULL) { + /* Do not mask errors. */ + if (!PyErr_Occurred()) + PyErr_SetString(PyExc_TypeError, error); + return 0; + } + Py_DECREF(bases); + return -1; } static int recursive_isinstance(PyObject *inst, PyObject *cls) { - PyObject *icls; - static PyObject *__class__ = NULL; - int retval = 0; - - if (__class__ == NULL) { - __class__ = PyUnicode_InternFromString("__class__"); - if (__class__ == NULL) - return -1; - } - - if (PyType_Check(cls)) { - retval = PyObject_TypeCheck(inst, (PyTypeObject *)cls); - if (retval == 0) { - PyObject *c = PyObject_GetAttr(inst, __class__); - if (c == NULL) { - PyErr_Clear(); - } - else { - if (c != (PyObject *)(inst->ob_type) && - PyType_Check(c)) - retval = PyType_IsSubtype( - (PyTypeObject *)c, - (PyTypeObject *)cls); - Py_DECREF(c); - } - } - } - else { - if (!check_class(cls, - "isinstance() arg 2 must be a class, type," - " or tuple of classes and types")) - return -1; - icls = PyObject_GetAttr(inst, __class__); - if (icls == NULL) { - PyErr_Clear(); - retval = 0; - } - else { - retval = abstract_issubclass(icls, cls); - Py_DECREF(icls); - } - } + PyObject *icls; + static PyObject *__class__ = NULL; + int retval = 0; + + if (__class__ == NULL) { + __class__ = PyUnicode_InternFromString("__class__"); + if (__class__ == NULL) + return -1; + } + + if (PyType_Check(cls)) { + retval = PyObject_TypeCheck(inst, (PyTypeObject *)cls); + if (retval == 0) { + PyObject *c = PyObject_GetAttr(inst, __class__); + if (c == NULL) { + PyErr_Clear(); + } + else { + if (c != (PyObject *)(inst->ob_type) && + PyType_Check(c)) + retval = PyType_IsSubtype( + (PyTypeObject *)c, + (PyTypeObject *)cls); + Py_DECREF(c); + } + } + } + else { + if (!check_class(cls, + "isinstance() arg 2 must be a class, type," + " or tuple of classes and types")) + return -1; + icls = PyObject_GetAttr(inst, __class__); + if (icls == NULL) { + PyErr_Clear(); + retval = 0; + } + else { + retval = abstract_issubclass(icls, cls); + Py_DECREF(icls); + } + } - return retval; + return retval; } int PyObject_IsInstance(PyObject *inst, PyObject *cls) { - static PyObject *name = NULL; - PyObject *checker; + static PyObject *name = NULL; + PyObject *checker; + + /* Quick test for an exact match */ + if (Py_TYPE(inst) == (PyTypeObject *)cls) + return 1; + + if (PyTuple_Check(cls)) { + Py_ssize_t i; + Py_ssize_t n; + int r = 0; + + if (Py_EnterRecursiveCall(" in __instancecheck__")) + return -1; + n = PyTuple_GET_SIZE(cls); + for (i = 0; i < n; ++i) { + PyObject *item = PyTuple_GET_ITEM(cls, i); + r = PyObject_IsInstance(inst, item); + if (r != 0) + /* either found it, or got an error */ + break; + } + Py_LeaveRecursiveCall(); + return r; + } - /* Quick test for an exact match */ - if (Py_TYPE(inst) == (PyTypeObject *)cls) - return 1; - - if (PyTuple_Check(cls)) { - Py_ssize_t i; - Py_ssize_t n; - int r = 0; - - if (Py_EnterRecursiveCall(" in __instancecheck__")) - return -1; - n = PyTuple_GET_SIZE(cls); - for (i = 0; i < n; ++i) { - PyObject *item = PyTuple_GET_ITEM(cls, i); - r = PyObject_IsInstance(inst, item); - if (r != 0) - /* either found it, or got an error */ - break; - } - Py_LeaveRecursiveCall(); - return r; - } - - checker = _PyObject_LookupSpecial(cls, "__instancecheck__", &name); - if (checker != NULL) { - PyObject *res; - int ok = -1; - if (Py_EnterRecursiveCall(" in __instancecheck__")) { - Py_DECREF(checker); - return ok; - } - res = PyObject_CallFunctionObjArgs(checker, inst, NULL); - Py_LeaveRecursiveCall(); - Py_DECREF(checker); - if (res != NULL) { - ok = PyObject_IsTrue(res); - Py_DECREF(res); - } - return ok; - } - else if (PyErr_Occurred()) - return -1; - return recursive_isinstance(inst, cls); + checker = _PyObject_LookupSpecial(cls, "__instancecheck__", &name); + if (checker != NULL) { + PyObject *res; + int ok = -1; + if (Py_EnterRecursiveCall(" in __instancecheck__")) { + Py_DECREF(checker); + return ok; + } + res = PyObject_CallFunctionObjArgs(checker, inst, NULL); + Py_LeaveRecursiveCall(); + Py_DECREF(checker); + if (res != NULL) { + ok = PyObject_IsTrue(res); + Py_DECREF(res); + } + return ok; + } + else if (PyErr_Occurred()) + return -1; + return recursive_isinstance(inst, cls); } -static int +static int recursive_issubclass(PyObject *derived, PyObject *cls) { - if (PyType_Check(cls) && PyType_Check(derived)) { - /* Fast path (non-recursive) */ - return PyType_IsSubtype((PyTypeObject *)derived, (PyTypeObject *)cls); - } - if (!check_class(derived, - "issubclass() arg 1 must be a class")) - return -1; - if (!check_class(cls, - "issubclass() arg 2 must be a class" - " or tuple of classes")) - return -1; + if (PyType_Check(cls) && PyType_Check(derived)) { + /* Fast path (non-recursive) */ + return PyType_IsSubtype((PyTypeObject *)derived, (PyTypeObject *)cls); + } + if (!check_class(derived, + "issubclass() arg 1 must be a class")) + return -1; + if (!check_class(cls, + "issubclass() arg 2 must be a class" + " or tuple of classes")) + return -1; - return abstract_issubclass(derived, cls); + return abstract_issubclass(derived, cls); } int PyObject_IsSubclass(PyObject *derived, PyObject *cls) { - static PyObject *name = NULL; - PyObject *checker; + static PyObject *name = NULL; + PyObject *checker; + + if (PyTuple_Check(cls)) { + Py_ssize_t i; + Py_ssize_t n; + int r = 0; + + if (Py_EnterRecursiveCall(" in __subclasscheck__")) + return -1; + n = PyTuple_GET_SIZE(cls); + for (i = 0; i < n; ++i) { + PyObject *item = PyTuple_GET_ITEM(cls, i); + r = PyObject_IsSubclass(derived, item); + if (r != 0) + /* either found it, or got an error */ + break; + } + Py_LeaveRecursiveCall(); + return r; + } - if (PyTuple_Check(cls)) { - Py_ssize_t i; - Py_ssize_t n; - int r = 0; - - if (Py_EnterRecursiveCall(" in __subclasscheck__")) - return -1; - n = PyTuple_GET_SIZE(cls); - for (i = 0; i < n; ++i) { - PyObject *item = PyTuple_GET_ITEM(cls, i); - r = PyObject_IsSubclass(derived, item); - if (r != 0) - /* either found it, or got an error */ - break; - } - Py_LeaveRecursiveCall(); - return r; - } - - checker = _PyObject_LookupSpecial(cls, "__subclasscheck__", &name); - if (checker != NULL) { - PyObject *res; - int ok = -1; - if (Py_EnterRecursiveCall(" in __subclasscheck__")) { - Py_DECREF(checker); - return ok; - } - res = PyObject_CallFunctionObjArgs(checker, derived, NULL); - Py_LeaveRecursiveCall(); - Py_DECREF(checker); - if (res != NULL) { - ok = PyObject_IsTrue(res); - Py_DECREF(res); - } - return ok; - } - else if (PyErr_Occurred()) - return -1; - return recursive_issubclass(derived, cls); + checker = _PyObject_LookupSpecial(cls, "__subclasscheck__", &name); + if (checker != NULL) { + PyObject *res; + int ok = -1; + if (Py_EnterRecursiveCall(" in __subclasscheck__")) { + Py_DECREF(checker); + return ok; + } + res = PyObject_CallFunctionObjArgs(checker, derived, NULL); + Py_LeaveRecursiveCall(); + Py_DECREF(checker); + if (res != NULL) { + ok = PyObject_IsTrue(res); + Py_DECREF(res); + } + return ok; + } + else if (PyErr_Occurred()) + return -1; + return recursive_issubclass(derived, cls); } int _PyObject_RealIsInstance(PyObject *inst, PyObject *cls) { - return recursive_isinstance(inst, cls); + return recursive_isinstance(inst, cls); } int _PyObject_RealIsSubclass(PyObject *derived, PyObject *cls) { - return recursive_issubclass(derived, cls); + return recursive_issubclass(derived, cls); } PyObject * PyObject_GetIter(PyObject *o) { - PyTypeObject *t = o->ob_type; - getiterfunc f = NULL; - f = t->tp_iter; - if (f == NULL) { - if (PySequence_Check(o)) - return PySeqIter_New(o); - return type_error("'%.200s' object is not iterable", o); - } - else { - PyObject *res = (*f)(o); - if (res != NULL && !PyIter_Check(res)) { - PyErr_Format(PyExc_TypeError, - "iter() returned non-iterator " - "of type '%.100s'", - res->ob_type->tp_name); - Py_DECREF(res); - res = NULL; - } - return res; - } + PyTypeObject *t = o->ob_type; + getiterfunc f = NULL; + f = t->tp_iter; + if (f == NULL) { + if (PySequence_Check(o)) + return PySeqIter_New(o); + return type_error("'%.200s' object is not iterable", o); + } + else { + PyObject *res = (*f)(o); + if (res != NULL && !PyIter_Check(res)) { + PyErr_Format(PyExc_TypeError, + "iter() returned non-iterator " + "of type '%.100s'", + res->ob_type->tp_name); + Py_DECREF(res); + res = NULL; + } + return res; + } } /* Return next item. @@ -2709,18 +2709,18 @@ * If the iteration terminates normally, return NULL and clear the * PyExc_StopIteration exception (if it was set). PyErr_Occurred() * will be false. - * Else return the next object. PyErr_Occurred() will be false. + * Else return the next object. PyErr_Occurred() will be false. */ PyObject * PyIter_Next(PyObject *iter) { - PyObject *result; - result = (*iter->ob_type->tp_iternext)(iter); - if (result == NULL && - PyErr_Occurred() && - PyErr_ExceptionMatches(PyExc_StopIteration)) - PyErr_Clear(); - return result; + PyObject *result; + result = (*iter->ob_type->tp_iternext)(iter); + if (result == NULL && + PyErr_Occurred() && + PyErr_ExceptionMatches(PyExc_StopIteration)) + PyErr_Clear(); + return result; } @@ -2735,43 +2735,43 @@ char *const * _PySequence_BytesToCharpArray(PyObject* self) { - char **array; - Py_ssize_t i, argc; - PyObject *item = NULL; - - argc = PySequence_Size(self); - if (argc == -1) - return NULL; - - array = malloc((argc + 1) * sizeof(char *)); - if (array == NULL) { - PyErr_NoMemory(); - return NULL; - } - for (i = 0; i < argc; ++i) { - char *data; - item = PySequence_GetItem(self, i); - data = PyBytes_AsString(item); - if (data == NULL) { - /* NULL terminate before freeing. */ - array[i] = NULL; - goto fail; - } - array[i] = strdup(data); - if (!array[i]) { - PyErr_NoMemory(); - goto fail; - } - Py_DECREF(item); - } - array[argc] = NULL; + char **array; + Py_ssize_t i, argc; + PyObject *item = NULL; + + argc = PySequence_Size(self); + if (argc == -1) + return NULL; + + array = malloc((argc + 1) * sizeof(char *)); + if (array == NULL) { + PyErr_NoMemory(); + return NULL; + } + for (i = 0; i < argc; ++i) { + char *data; + item = PySequence_GetItem(self, i); + data = PyBytes_AsString(item); + if (data == NULL) { + /* NULL terminate before freeing. */ + array[i] = NULL; + goto fail; + } + array[i] = strdup(data); + if (!array[i]) { + PyErr_NoMemory(); + goto fail; + } + Py_DECREF(item); + } + array[argc] = NULL; - return array; + return array; fail: - Py_XDECREF(item); - _Py_FreeCharPArray(array); - return NULL; + Py_XDECREF(item); + _Py_FreeCharPArray(array); + return NULL; } @@ -2779,9 +2779,9 @@ void _Py_FreeCharPArray(char *const array[]) { - Py_ssize_t i; - for (i = 0; array[i] != NULL; ++i) { - free(array[i]); - } - free((void*)array); + Py_ssize_t i; + for (i = 0; array[i] != NULL; ++i) { + free(array[i]); + } + free((void*)array); } Modified: python/branches/py3k-jit/Objects/boolobject.c ============================================================================== --- python/branches/py3k-jit/Objects/boolobject.c (original) +++ python/branches/py3k-jit/Objects/boolobject.c Mon May 10 23:55:43 2010 @@ -11,30 +11,30 @@ static PyObject * bool_repr(PyObject *self) { - PyObject *s; + PyObject *s; - if (self == Py_True) - s = true_str ? true_str : - (true_str = PyUnicode_InternFromString("True")); - else - s = false_str ? false_str : - (false_str = PyUnicode_InternFromString("False")); - Py_XINCREF(s); - return s; + if (self == Py_True) + s = true_str ? true_str : + (true_str = PyUnicode_InternFromString("True")); + else + s = false_str ? false_str : + (false_str = PyUnicode_InternFromString("False")); + Py_XINCREF(s); + return s; } /* Function to return a bool from a C long */ PyObject *PyBool_FromLong(long ok) { - PyObject *result; + PyObject *result; - if (ok) - result = Py_True; - else - result = Py_False; - Py_INCREF(result); - return result; + if (ok) + result = Py_True; + else + result = Py_False; + Py_INCREF(result); + return result; } /* We define bool_new to always return either Py_True or Py_False */ @@ -42,16 +42,16 @@ static PyObject * bool_new(PyTypeObject *type, PyObject *args, PyObject *kwds) { - static char *kwlist[] = {"x", 0}; - PyObject *x = Py_False; - long ok; - - if (!PyArg_ParseTupleAndKeywords(args, kwds, "|O:bool", kwlist, &x)) - return NULL; - ok = PyObject_IsTrue(x); - if (ok < 0) - return NULL; - return PyBool_FromLong(ok); + static char *kwlist[] = {"x", 0}; + PyObject *x = Py_False; + long ok; + + if (!PyArg_ParseTupleAndKeywords(args, kwds, "|O:bool", kwlist, &x)) + return NULL; + ok = PyObject_IsTrue(x); + if (ok < 0) + return NULL; + return PyBool_FromLong(ok); } /* Arithmetic operations redefined to return bool if both args are bool. */ @@ -59,25 +59,25 @@ static PyObject * bool_and(PyObject *a, PyObject *b) { - if (!PyBool_Check(a) || !PyBool_Check(b)) - return PyLong_Type.tp_as_number->nb_and(a, b); - return PyBool_FromLong((a == Py_True) & (b == Py_True)); + if (!PyBool_Check(a) || !PyBool_Check(b)) + return PyLong_Type.tp_as_number->nb_and(a, b); + return PyBool_FromLong((a == Py_True) & (b == Py_True)); } static PyObject * bool_or(PyObject *a, PyObject *b) { - if (!PyBool_Check(a) || !PyBool_Check(b)) - return PyLong_Type.tp_as_number->nb_or(a, b); - return PyBool_FromLong((a == Py_True) | (b == Py_True)); + if (!PyBool_Check(a) || !PyBool_Check(b)) + return PyLong_Type.tp_as_number->nb_or(a, b); + return PyBool_FromLong((a == Py_True) | (b == Py_True)); } static PyObject * bool_xor(PyObject *a, PyObject *b) { - if (!PyBool_Check(a) || !PyBool_Check(b)) - return PyLong_Type.tp_as_number->nb_xor(a, b); - return PyBool_FromLong((a == Py_True) ^ (b == Py_True)); + if (!PyBool_Check(a) || !PyBool_Check(b)) + return PyLong_Type.tp_as_number->nb_xor(a, b); + return PyBool_FromLong((a == Py_True) ^ (b == Py_True)); } /* Doc string */ @@ -92,93 +92,93 @@ /* Arithmetic methods -- only so we can override &, |, ^. */ static PyNumberMethods bool_as_number = { - 0, /* nb_add */ - 0, /* nb_subtract */ - 0, /* nb_multiply */ - 0, /* nb_remainder */ - 0, /* nb_divmod */ - 0, /* nb_power */ - 0, /* nb_negative */ - 0, /* nb_positive */ - 0, /* nb_absolute */ - 0, /* nb_bool */ - 0, /* nb_invert */ - 0, /* nb_lshift */ - 0, /* nb_rshift */ - bool_and, /* nb_and */ - bool_xor, /* nb_xor */ - bool_or, /* nb_or */ - 0, /* nb_int */ - 0, /* nb_reserved */ - 0, /* nb_float */ - 0, /* nb_inplace_add */ - 0, /* nb_inplace_subtract */ - 0, /* nb_inplace_multiply */ - 0, /* nb_inplace_remainder */ - 0, /* nb_inplace_power */ - 0, /* nb_inplace_lshift */ - 0, /* nb_inplace_rshift */ - 0, /* nb_inplace_and */ - 0, /* nb_inplace_xor */ - 0, /* nb_inplace_or */ - 0, /* nb_floor_divide */ - 0, /* nb_true_divide */ - 0, /* nb_inplace_floor_divide */ - 0, /* nb_inplace_true_divide */ - 0, /* nb_index */ + 0, /* nb_add */ + 0, /* nb_subtract */ + 0, /* nb_multiply */ + 0, /* nb_remainder */ + 0, /* nb_divmod */ + 0, /* nb_power */ + 0, /* nb_negative */ + 0, /* nb_positive */ + 0, /* nb_absolute */ + 0, /* nb_bool */ + 0, /* nb_invert */ + 0, /* nb_lshift */ + 0, /* nb_rshift */ + bool_and, /* nb_and */ + bool_xor, /* nb_xor */ + bool_or, /* nb_or */ + 0, /* nb_int */ + 0, /* nb_reserved */ + 0, /* nb_float */ + 0, /* nb_inplace_add */ + 0, /* nb_inplace_subtract */ + 0, /* nb_inplace_multiply */ + 0, /* nb_inplace_remainder */ + 0, /* nb_inplace_power */ + 0, /* nb_inplace_lshift */ + 0, /* nb_inplace_rshift */ + 0, /* nb_inplace_and */ + 0, /* nb_inplace_xor */ + 0, /* nb_inplace_or */ + 0, /* nb_floor_divide */ + 0, /* nb_true_divide */ + 0, /* nb_inplace_floor_divide */ + 0, /* nb_inplace_true_divide */ + 0, /* nb_index */ }; /* The type object for bool. Note that this cannot be subclassed! */ PyTypeObject PyBool_Type = { - PyVarObject_HEAD_INIT(&PyType_Type, 0) - "bool", - sizeof(struct _longobject), - 0, - 0, /* tp_dealloc */ - 0, /* tp_print */ - 0, /* tp_getattr */ - 0, /* tp_setattr */ - 0, /* tp_reserved */ - bool_repr, /* tp_repr */ - &bool_as_number, /* tp_as_number */ - 0, /* tp_as_sequence */ - 0, /* tp_as_mapping */ - 0, /* tp_hash */ - 0, /* tp_call */ - bool_repr, /* tp_str */ - 0, /* tp_getattro */ - 0, /* tp_setattro */ - 0, /* tp_as_buffer */ - Py_TPFLAGS_DEFAULT, /* tp_flags */ - bool_doc, /* tp_doc */ - 0, /* tp_traverse */ - 0, /* tp_clear */ - 0, /* tp_richcompare */ - 0, /* tp_weaklistoffset */ - 0, /* tp_iter */ - 0, /* tp_iternext */ - 0, /* tp_methods */ - 0, /* tp_members */ - 0, /* tp_getset */ - &PyLong_Type, /* tp_base */ - 0, /* tp_dict */ - 0, /* tp_descr_get */ - 0, /* tp_descr_set */ - 0, /* tp_dictoffset */ - 0, /* tp_init */ - 0, /* tp_alloc */ - bool_new, /* tp_new */ + PyVarObject_HEAD_INIT(&PyType_Type, 0) + "bool", + sizeof(struct _longobject), + 0, + 0, /* tp_dealloc */ + 0, /* tp_print */ + 0, /* tp_getattr */ + 0, /* tp_setattr */ + 0, /* tp_reserved */ + bool_repr, /* tp_repr */ + &bool_as_number, /* tp_as_number */ + 0, /* tp_as_sequence */ + 0, /* tp_as_mapping */ + 0, /* tp_hash */ + 0, /* tp_call */ + bool_repr, /* tp_str */ + 0, /* tp_getattro */ + 0, /* tp_setattro */ + 0, /* tp_as_buffer */ + Py_TPFLAGS_DEFAULT, /* tp_flags */ + bool_doc, /* tp_doc */ + 0, /* tp_traverse */ + 0, /* tp_clear */ + 0, /* tp_richcompare */ + 0, /* tp_weaklistoffset */ + 0, /* tp_iter */ + 0, /* tp_iternext */ + 0, /* tp_methods */ + 0, /* tp_members */ + 0, /* tp_getset */ + &PyLong_Type, /* tp_base */ + 0, /* tp_dict */ + 0, /* tp_descr_get */ + 0, /* tp_descr_set */ + 0, /* tp_dictoffset */ + 0, /* tp_init */ + 0, /* tp_alloc */ + bool_new, /* tp_new */ }; /* The objects representing bool values False and True */ struct _longobject _Py_FalseStruct = { - PyVarObject_HEAD_INIT(&PyBool_Type, 0) - { 0 } + PyVarObject_HEAD_INIT(&PyBool_Type, 0) + { 0 } }; struct _longobject _Py_TrueStruct = { - PyVarObject_HEAD_INIT(&PyBool_Type, 1) - { 1 } + PyVarObject_HEAD_INIT(&PyBool_Type, 1) + { 1 } }; Modified: python/branches/py3k-jit/Objects/bytes_methods.c ============================================================================== --- python/branches/py3k-jit/Objects/bytes_methods.c (original) +++ python/branches/py3k-jit/Objects/bytes_methods.c Mon May 10 23:55:43 2010 @@ -24,7 +24,7 @@ e = p + len; for (; p < e; p++) { - if (!Py_ISSPACE(*p)) + if (!Py_ISSPACE(*p)) Py_RETURN_FALSE; } Py_RETURN_TRUE; @@ -46,16 +46,16 @@ /* Shortcut for single character strings */ if (len == 1 && Py_ISALPHA(*p)) - Py_RETURN_TRUE; + Py_RETURN_TRUE; /* Special case for empty strings */ if (len == 0) - Py_RETURN_FALSE; + Py_RETURN_FALSE; e = p + len; for (; p < e; p++) { - if (!Py_ISALPHA(*p)) - Py_RETURN_FALSE; + if (!Py_ISALPHA(*p)) + Py_RETURN_FALSE; } Py_RETURN_TRUE; } @@ -76,16 +76,16 @@ /* Shortcut for single character strings */ if (len == 1 && Py_ISALNUM(*p)) - Py_RETURN_TRUE; + Py_RETURN_TRUE; /* Special case for empty strings */ if (len == 0) - Py_RETURN_FALSE; + Py_RETURN_FALSE; e = p + len; for (; p < e; p++) { - if (!Py_ISALNUM(*p)) - Py_RETURN_FALSE; + if (!Py_ISALNUM(*p)) + Py_RETURN_FALSE; } Py_RETURN_TRUE; } @@ -106,16 +106,16 @@ /* Shortcut for single character strings */ if (len == 1 && Py_ISDIGIT(*p)) - Py_RETURN_TRUE; + Py_RETURN_TRUE; /* Special case for empty strings */ if (len == 0) - Py_RETURN_FALSE; + Py_RETURN_FALSE; e = p + len; for (; p < e; p++) { - if (!Py_ISDIGIT(*p)) - Py_RETURN_FALSE; + if (!Py_ISDIGIT(*p)) + Py_RETURN_FALSE; } Py_RETURN_TRUE; } @@ -137,19 +137,19 @@ /* Shortcut for single character strings */ if (len == 1) - return PyBool_FromLong(Py_ISLOWER(*p)); + return PyBool_FromLong(Py_ISLOWER(*p)); /* Special case for empty strings */ if (len == 0) - Py_RETURN_FALSE; + Py_RETURN_FALSE; e = p + len; cased = 0; for (; p < e; p++) { - if (Py_ISUPPER(*p)) - Py_RETURN_FALSE; - else if (!cased && Py_ISLOWER(*p)) - cased = 1; + if (Py_ISUPPER(*p)) + Py_RETURN_FALSE; + else if (!cased && Py_ISLOWER(*p)) + cased = 1; } return PyBool_FromLong(cased); } @@ -171,19 +171,19 @@ /* Shortcut for single character strings */ if (len == 1) - return PyBool_FromLong(Py_ISUPPER(*p)); + return PyBool_FromLong(Py_ISUPPER(*p)); /* Special case for empty strings */ if (len == 0) - Py_RETURN_FALSE; + Py_RETURN_FALSE; e = p + len; cased = 0; for (; p < e; p++) { - if (Py_ISLOWER(*p)) - Py_RETURN_FALSE; - else if (!cased && Py_ISUPPER(*p)) - cased = 1; + if (Py_ISLOWER(*p)) + Py_RETURN_FALSE; + else if (!cased && Py_ISUPPER(*p)) + cased = 1; } return PyBool_FromLong(cased); } @@ -207,32 +207,32 @@ /* Shortcut for single character strings */ if (len == 1) - return PyBool_FromLong(Py_ISUPPER(*p)); + return PyBool_FromLong(Py_ISUPPER(*p)); /* Special case for empty strings */ if (len == 0) - Py_RETURN_FALSE; + Py_RETURN_FALSE; e = p + len; cased = 0; previous_is_cased = 0; for (; p < e; p++) { - register const unsigned char ch = *p; + register const unsigned char ch = *p; - if (Py_ISUPPER(ch)) { - if (previous_is_cased) - Py_RETURN_FALSE; - previous_is_cased = 1; - cased = 1; - } - else if (Py_ISLOWER(ch)) { - if (!previous_is_cased) - Py_RETURN_FALSE; - previous_is_cased = 1; - cased = 1; - } - else - previous_is_cased = 0; + if (Py_ISUPPER(ch)) { + if (previous_is_cased) + Py_RETURN_FALSE; + previous_is_cased = 1; + cased = 1; + } + else if (Py_ISLOWER(ch)) { + if (!previous_is_cased) + Py_RETURN_FALSE; + previous_is_cased = 1; + cased = 1; + } + else + previous_is_cased = 0; } return PyBool_FromLong(cased); } @@ -246,23 +246,23 @@ void _Py_bytes_lower(char *result, const char *cptr, Py_ssize_t len) { - Py_ssize_t i; + Py_ssize_t i; /* - newobj = PyBytes_FromStringAndSize(NULL, len); - if (!newobj) - return NULL; + newobj = PyBytes_FromStringAndSize(NULL, len); + if (!newobj) + return NULL; - s = PyBytes_AS_STRING(newobj); + s = PyBytes_AS_STRING(newobj); */ - Py_MEMCPY(result, cptr, len); + Py_MEMCPY(result, cptr, len); - for (i = 0; i < len; i++) { - int c = Py_CHARMASK(result[i]); - if (Py_ISUPPER(c)) - result[i] = Py_TOLOWER(c); - } + for (i = 0; i < len; i++) { + int c = Py_CHARMASK(result[i]); + if (Py_ISUPPER(c)) + result[i] = Py_TOLOWER(c); + } } @@ -274,23 +274,23 @@ void _Py_bytes_upper(char *result, const char *cptr, Py_ssize_t len) { - Py_ssize_t i; + Py_ssize_t i; /* - newobj = PyBytes_FromStringAndSize(NULL, len); - if (!newobj) - return NULL; + newobj = PyBytes_FromStringAndSize(NULL, len); + if (!newobj) + return NULL; - s = PyBytes_AS_STRING(newobj); + s = PyBytes_AS_STRING(newobj); */ - Py_MEMCPY(result, cptr, len); + Py_MEMCPY(result, cptr, len); - for (i = 0; i < len; i++) { - int c = Py_CHARMASK(result[i]); - if (Py_ISLOWER(c)) - result[i] = Py_TOUPPER(c); - } + for (i = 0; i < len; i++) { + int c = Py_CHARMASK(result[i]); + if (Py_ISLOWER(c)) + result[i] = Py_TOUPPER(c); + } } @@ -303,29 +303,29 @@ void _Py_bytes_title(char *result, char *s, Py_ssize_t len) { - Py_ssize_t i; - int previous_is_cased = 0; + Py_ssize_t i; + int previous_is_cased = 0; /* - newobj = PyBytes_FromStringAndSize(NULL, len); - if (newobj == NULL) - return NULL; - s_new = PyBytes_AsString(newobj); + newobj = PyBytes_FromStringAndSize(NULL, len); + if (newobj == NULL) + return NULL; + s_new = PyBytes_AsString(newobj); */ - for (i = 0; i < len; i++) { - int c = Py_CHARMASK(*s++); - if (Py_ISLOWER(c)) { - if (!previous_is_cased) - c = Py_TOUPPER(c); - previous_is_cased = 1; - } else if (Py_ISUPPER(c)) { - if (previous_is_cased) - c = Py_TOLOWER(c); - previous_is_cased = 1; - } else - previous_is_cased = 0; - *result++ = c; - } + for (i = 0; i < len; i++) { + int c = Py_CHARMASK(*s++); + if (Py_ISLOWER(c)) { + if (!previous_is_cased) + c = Py_TOUPPER(c); + previous_is_cased = 1; + } else if (Py_ISUPPER(c)) { + if (previous_is_cased) + c = Py_TOLOWER(c); + previous_is_cased = 1; + } else + previous_is_cased = 0; + *result++ = c; + } } @@ -337,30 +337,30 @@ void _Py_bytes_capitalize(char *result, char *s, Py_ssize_t len) { - Py_ssize_t i; + Py_ssize_t i; /* - newobj = PyBytes_FromStringAndSize(NULL, len); - if (newobj == NULL) - return NULL; - s_new = PyBytes_AsString(newobj); + newobj = PyBytes_FromStringAndSize(NULL, len); + if (newobj == NULL) + return NULL; + s_new = PyBytes_AsString(newobj); */ - if (0 < len) { - int c = Py_CHARMASK(*s++); - if (Py_ISLOWER(c)) - *result = Py_TOUPPER(c); - else - *result = c; - result++; - } - for (i = 1; i < len; i++) { - int c = Py_CHARMASK(*s++); - if (Py_ISUPPER(c)) - *result = Py_TOLOWER(c); - else - *result = c; - result++; - } + if (0 < len) { + int c = Py_CHARMASK(*s++); + if (Py_ISLOWER(c)) + *result = Py_TOUPPER(c); + else + *result = c; + result++; + } + for (i = 1; i < len; i++) { + int c = Py_CHARMASK(*s++); + if (Py_ISUPPER(c)) + *result = Py_TOLOWER(c); + else + *result = c; + result++; + } } @@ -373,26 +373,26 @@ void _Py_bytes_swapcase(char *result, char *s, Py_ssize_t len) { - Py_ssize_t i; + Py_ssize_t i; /* - newobj = PyBytes_FromStringAndSize(NULL, len); - if (newobj == NULL) - return NULL; - s_new = PyBytes_AsString(newobj); + newobj = PyBytes_FromStringAndSize(NULL, len); + if (newobj == NULL) + return NULL; + s_new = PyBytes_AsString(newobj); */ - for (i = 0; i < len; i++) { - int c = Py_CHARMASK(*s++); - if (Py_ISLOWER(c)) { - *result = Py_TOUPPER(c); - } - else if (Py_ISUPPER(c)) { - *result = Py_TOLOWER(c); - } - else - *result = c; - result++; - } + for (i = 0; i < len; i++) { + int c = Py_CHARMASK(*s++); + if (Py_ISLOWER(c)) { + *result = Py_TOUPPER(c); + } + else if (Py_ISUPPER(c)) { + *result = Py_TOLOWER(c); + } + else + *result = c; + result++; + } } @@ -425,40 +425,40 @@ PyObject * _Py_bytes_maketrans(PyObject *args) { - PyObject *frm, *to, *res = NULL; - Py_buffer bfrm, bto; - Py_ssize_t i; - char *p; - - bfrm.len = -1; - bto.len = -1; - - if (!PyArg_ParseTuple(args, "OO:maketrans", &frm, &to)) - return NULL; - if (_getbuffer(frm, &bfrm) < 0) - return NULL; - if (_getbuffer(to, &bto) < 0) - goto done; - if (bfrm.len != bto.len) { - PyErr_Format(PyExc_ValueError, - "maketrans arguments must have same length"); - goto done; - } - res = PyBytes_FromStringAndSize(NULL, 256); - if (!res) { - goto done; - } - p = PyBytes_AS_STRING(res); - for (i = 0; i < 256; i++) - p[i] = i; - for (i = 0; i < bfrm.len; i++) { - p[((unsigned char *)bfrm.buf)[i]] = ((char *)bto.buf)[i]; - } + PyObject *frm, *to, *res = NULL; + Py_buffer bfrm, bto; + Py_ssize_t i; + char *p; + + bfrm.len = -1; + bto.len = -1; + + if (!PyArg_ParseTuple(args, "OO:maketrans", &frm, &to)) + return NULL; + if (_getbuffer(frm, &bfrm) < 0) + return NULL; + if (_getbuffer(to, &bto) < 0) + goto done; + if (bfrm.len != bto.len) { + PyErr_Format(PyExc_ValueError, + "maketrans arguments must have same length"); + goto done; + } + res = PyBytes_FromStringAndSize(NULL, 256); + if (!res) { + goto done; + } + p = PyBytes_AS_STRING(res); + for (i = 0; i < 256; i++) + p[i] = i; + for (i = 0; i < bfrm.len; i++) { + p[((unsigned char *)bfrm.buf)[i]] = ((char *)bto.buf)[i]; + } done: - if (bfrm.len != -1) - PyBuffer_Release(&bfrm); - if (bto.len != -1) - PyBuffer_Release(&bto); - return res; + if (bfrm.len != -1) + PyBuffer_Release(&bfrm); + if (bto.len != -1) + PyBuffer_Release(&bto); + return res; } Modified: python/branches/py3k-jit/Objects/bytesobject.c ============================================================================== --- python/branches/py3k-jit/Objects/bytesobject.c (original) +++ python/branches/py3k-jit/Objects/bytesobject.c Mon May 10 23:55:43 2010 @@ -14,14 +14,14 @@ if (buffer == NULL || buffer->bf_getbuffer == NULL) { - PyErr_Format(PyExc_TypeError, - "Type %.100s doesn't support the buffer API", - Py_TYPE(obj)->tp_name); - return -1; + PyErr_Format(PyExc_TypeError, + "Type %.100s doesn't support the buffer API", + Py_TYPE(obj)->tp_name); + return -1; } if (buffer->bf_getbuffer(obj, view, PyBUF_SIMPLE) < 0) - return -1; + return -1; return view->len; } @@ -69,305 +69,305 @@ PyObject * PyBytes_FromStringAndSize(const char *str, Py_ssize_t size) { - register PyBytesObject *op; - if (size < 0) { - PyErr_SetString(PyExc_SystemError, - "Negative size passed to PyBytes_FromStringAndSize"); - return NULL; - } - if (size == 0 && (op = nullstring) != NULL) { + register PyBytesObject *op; + if (size < 0) { + PyErr_SetString(PyExc_SystemError, + "Negative size passed to PyBytes_FromStringAndSize"); + return NULL; + } + if (size == 0 && (op = nullstring) != NULL) { #ifdef COUNT_ALLOCS - null_strings++; + null_strings++; #endif - Py_INCREF(op); - return (PyObject *)op; - } - if (size == 1 && str != NULL && - (op = characters[*str & UCHAR_MAX]) != NULL) - { + Py_INCREF(op); + return (PyObject *)op; + } + if (size == 1 && str != NULL && + (op = characters[*str & UCHAR_MAX]) != NULL) + { #ifdef COUNT_ALLOCS - one_strings++; + one_strings++; #endif - Py_INCREF(op); - return (PyObject *)op; - } - - if (size > PY_SSIZE_T_MAX - PyBytesObject_SIZE) { - PyErr_SetString(PyExc_OverflowError, - "byte string is too large"); - return NULL; - } - - /* Inline PyObject_NewVar */ - op = (PyBytesObject *)PyObject_MALLOC(PyBytesObject_SIZE + size); - if (op == NULL) - return PyErr_NoMemory(); - PyObject_INIT_VAR(op, &PyBytes_Type, size); - op->ob_shash = -1; - if (str != NULL) - Py_MEMCPY(op->ob_sval, str, size); - op->ob_sval[size] = '\0'; - /* share short strings */ - if (size == 0) { - nullstring = op; - Py_INCREF(op); - } else if (size == 1 && str != NULL) { - characters[*str & UCHAR_MAX] = op; - Py_INCREF(op); - } - return (PyObject *) op; + Py_INCREF(op); + return (PyObject *)op; + } + + if (size > PY_SSIZE_T_MAX - PyBytesObject_SIZE) { + PyErr_SetString(PyExc_OverflowError, + "byte string is too large"); + return NULL; + } + + /* Inline PyObject_NewVar */ + op = (PyBytesObject *)PyObject_MALLOC(PyBytesObject_SIZE + size); + if (op == NULL) + return PyErr_NoMemory(); + PyObject_INIT_VAR(op, &PyBytes_Type, size); + op->ob_shash = -1; + if (str != NULL) + Py_MEMCPY(op->ob_sval, str, size); + op->ob_sval[size] = '\0'; + /* share short strings */ + if (size == 0) { + nullstring = op; + Py_INCREF(op); + } else if (size == 1 && str != NULL) { + characters[*str & UCHAR_MAX] = op; + Py_INCREF(op); + } + return (PyObject *) op; } PyObject * PyBytes_FromString(const char *str) { - register size_t size; - register PyBytesObject *op; + register size_t size; + register 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) { + 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++; + null_strings++; #endif - Py_INCREF(op); - return (PyObject *)op; - } - if (size == 1 && (op = characters[*str & UCHAR_MAX]) != NULL) { + Py_INCREF(op); + return (PyObject *)op; + } + if (size == 1 && (op = characters[*str & UCHAR_MAX]) != NULL) { #ifdef COUNT_ALLOCS - one_strings++; + 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(); - PyObject_INIT_VAR(op, &PyBytes_Type, size); - op->ob_shash = -1; - Py_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; + Py_INCREF(op); + return (PyObject *)op; + } + + /* Inline PyObject_NewVar */ + op = (PyBytesObject *)PyObject_MALLOC(PyBytesObject_SIZE + size); + if (op == NULL) + return PyErr_NoMemory(); + PyObject_INIT_VAR(op, &PyBytes_Type, size); + op->ob_shash = -1; + Py_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) { - va_list count; - Py_ssize_t n = 0; - const char* f; - char *s; - PyObject* string; + va_list count; + Py_ssize_t n = 0; + const char* f; + char *s; + PyObject* string; #ifdef VA_LIST_IS_ARRAY - Py_MEMCPY(count, vargs, sizeof(va_list)); + Py_MEMCPY(count, vargs, sizeof(va_list)); #else #ifdef __va_copy - __va_copy(count, vargs); + __va_copy(count, vargs); #else - count = vargs; + count = vargs; #endif #endif - /* step 1: figure out how large a buffer we need */ - for (f = format; *f; f++) { - if (*f == '%') { - const char* p = f; - while (*++f && *f != '%' && !ISALPHA(*f)) - ; - - /* skip the 'l' or 'z' in {%ld, %zd, %lu, %zu} since - * they don't affect the amount of space we reserve. - */ - if ((*f == 'l' || *f == 'z') && - (f[1] == 'd' || f[1] == 'u')) - ++f; - - switch (*f) { - case 'c': - (void)va_arg(count, int); - /* fall through... */ - case '%': - n++; - break; - case 'd': case 'u': case 'i': case 'x': - (void) va_arg(count, int); - /* 20 bytes is enough to hold a 64-bit - integer. Decimal takes the most space. - This isn't enough for octal. */ - n += 20; - break; - case 's': - s = va_arg(count, char*); - n += strlen(s); - break; - case 'p': - (void) va_arg(count, int); - /* maximum 64-bit pointer representation: - * 0xffffffffffffffff - * so 19 characters is enough. - * XXX I count 18 -- what's the extra for? - */ - n += 19; - break; - default: - /* if we stumble upon an unknown - formatting code, copy the rest of - the format string to the output - string. (we cannot just skip the - code, since there's no way to know - what's in the argument list) */ - n += strlen(p); - goto expand; - } - } else - n++; - } + /* step 1: figure out how large a buffer we need */ + for (f = format; *f; f++) { + if (*f == '%') { + const char* p = f; + while (*++f && *f != '%' && !ISALPHA(*f)) + ; + + /* skip the 'l' or 'z' in {%ld, %zd, %lu, %zu} since + * they don't affect the amount of space we reserve. + */ + if ((*f == 'l' || *f == 'z') && + (f[1] == 'd' || f[1] == 'u')) + ++f; + + switch (*f) { + case 'c': + (void)va_arg(count, int); + /* fall through... */ + case '%': + n++; + break; + case 'd': case 'u': case 'i': case 'x': + (void) va_arg(count, int); + /* 20 bytes is enough to hold a 64-bit + integer. Decimal takes the most space. + This isn't enough for octal. */ + n += 20; + break; + case 's': + s = va_arg(count, char*); + n += strlen(s); + break; + case 'p': + (void) va_arg(count, int); + /* maximum 64-bit pointer representation: + * 0xffffffffffffffff + * so 19 characters is enough. + * XXX I count 18 -- what's the extra for? + */ + n += 19; + break; + default: + /* if we stumble upon an unknown + formatting code, copy the rest of + the format string to the output + string. (we cannot just skip the + code, since there's no way to know + what's in the argument list) */ + n += strlen(p); + goto expand; + } + } else + n++; + } expand: - /* step 2: fill the buffer */ - /* Since we've analyzed how much space we need for the worst case, - use sprintf directly instead of the slower PyOS_snprintf. */ - string = PyBytes_FromStringAndSize(NULL, n); - if (!string) - return NULL; - - s = PyBytes_AsString(string); - - for (f = format; *f; f++) { - if (*f == '%') { - const char* p = f++; - Py_ssize_t i; - int longflag = 0; - int size_tflag = 0; - /* parse the width.precision part (we're only - interested in the precision value, if any) */ - n = 0; - while (ISDIGIT(*f)) - n = (n*10) + *f++ - '0'; - if (*f == '.') { - f++; - n = 0; - while (ISDIGIT(*f)) - n = (n*10) + *f++ - '0'; - } - while (*f && *f != '%' && !ISALPHA(*f)) - f++; - /* handle the long flag, but only for %ld and %lu. - others can be added when necessary. */ - if (*f == 'l' && (f[1] == 'd' || f[1] == 'u')) { - longflag = 1; - ++f; - } - /* handle the size_t flag. */ - if (*f == 'z' && (f[1] == 'd' || f[1] == 'u')) { - size_tflag = 1; - ++f; - } - - switch (*f) { - case 'c': - *s++ = va_arg(vargs, int); - break; - case 'd': - if (longflag) - sprintf(s, "%ld", va_arg(vargs, long)); - else if (size_tflag) - sprintf(s, "%" PY_FORMAT_SIZE_T "d", - va_arg(vargs, Py_ssize_t)); - else - sprintf(s, "%d", va_arg(vargs, int)); - s += strlen(s); - break; - case 'u': - if (longflag) - sprintf(s, "%lu", - va_arg(vargs, unsigned long)); - else if (size_tflag) - sprintf(s, "%" PY_FORMAT_SIZE_T "u", - va_arg(vargs, size_t)); - else - sprintf(s, "%u", - va_arg(vargs, unsigned int)); - s += strlen(s); - break; - case 'i': - sprintf(s, "%i", va_arg(vargs, int)); - s += strlen(s); - break; - case 'x': - sprintf(s, "%x", va_arg(vargs, int)); - s += strlen(s); - break; - case 's': - p = va_arg(vargs, char*); - i = strlen(p); - if (n > 0 && i > n) - i = n; - Py_MEMCPY(s, p, i); - s += i; - break; - case 'p': - sprintf(s, "%p", va_arg(vargs, void*)); - /* %p is ill-defined: ensure leading 0x. */ - if (s[1] == 'X') - s[1] = 'x'; - else if (s[1] != 'x') { - memmove(s+2, s, strlen(s)+1); - s[0] = '0'; - s[1] = 'x'; - } - s += strlen(s); - break; - case '%': - *s++ = '%'; - break; - default: - strcpy(s, p); - s += strlen(s); - goto end; - } - } else - *s++ = *f; - } + /* step 2: fill the buffer */ + /* Since we've analyzed how much space we need for the worst case, + use sprintf directly instead of the slower PyOS_snprintf. */ + string = PyBytes_FromStringAndSize(NULL, n); + if (!string) + return NULL; + + s = PyBytes_AsString(string); + + for (f = format; *f; f++) { + if (*f == '%') { + const char* p = f++; + Py_ssize_t i; + int longflag = 0; + int size_tflag = 0; + /* parse the width.precision part (we're only + interested in the precision value, if any) */ + n = 0; + while (ISDIGIT(*f)) + n = (n*10) + *f++ - '0'; + if (*f == '.') { + f++; + n = 0; + while (ISDIGIT(*f)) + n = (n*10) + *f++ - '0'; + } + while (*f && *f != '%' && !ISALPHA(*f)) + f++; + /* handle the long flag, but only for %ld and %lu. + others can be added when necessary. */ + if (*f == 'l' && (f[1] == 'd' || f[1] == 'u')) { + longflag = 1; + ++f; + } + /* handle the size_t flag. */ + if (*f == 'z' && (f[1] == 'd' || f[1] == 'u')) { + size_tflag = 1; + ++f; + } + + switch (*f) { + case 'c': + *s++ = va_arg(vargs, int); + break; + case 'd': + if (longflag) + sprintf(s, "%ld", va_arg(vargs, long)); + else if (size_tflag) + sprintf(s, "%" PY_FORMAT_SIZE_T "d", + va_arg(vargs, Py_ssize_t)); + else + sprintf(s, "%d", va_arg(vargs, int)); + s += strlen(s); + break; + case 'u': + if (longflag) + sprintf(s, "%lu", + va_arg(vargs, unsigned long)); + else if (size_tflag) + sprintf(s, "%" PY_FORMAT_SIZE_T "u", + va_arg(vargs, size_t)); + else + sprintf(s, "%u", + va_arg(vargs, unsigned int)); + s += strlen(s); + break; + case 'i': + sprintf(s, "%i", va_arg(vargs, int)); + s += strlen(s); + break; + case 'x': + sprintf(s, "%x", va_arg(vargs, int)); + s += strlen(s); + break; + case 's': + p = va_arg(vargs, char*); + i = strlen(p); + if (n > 0 && i > n) + i = n; + Py_MEMCPY(s, p, i); + s += i; + break; + case 'p': + sprintf(s, "%p", va_arg(vargs, void*)); + /* %p is ill-defined: ensure leading 0x. */ + if (s[1] == 'X') + s[1] = 'x'; + else if (s[1] != 'x') { + memmove(s+2, s, strlen(s)+1); + s[0] = '0'; + s[1] = 'x'; + } + s += strlen(s); + break; + case '%': + *s++ = '%'; + break; + default: + strcpy(s, p); + s += strlen(s); + goto end; + } + } else + *s++ = *f; + } end: - _PyBytes_Resize(&string, s - PyBytes_AS_STRING(string)); - return string; + _PyBytes_Resize(&string, s - PyBytes_AS_STRING(string)); + return string; } PyObject * PyBytes_FromFormat(const char *format, ...) { - PyObject* ret; - va_list vargs; + PyObject* ret; + va_list vargs; #ifdef HAVE_STDARG_PROTOTYPES - va_start(vargs, format); + va_start(vargs, format); #else - va_start(vargs); + va_start(vargs); #endif - ret = PyBytes_FromFormatV(format, vargs); - va_end(vargs); - return ret; + ret = PyBytes_FromFormatV(format, vargs); + va_end(vargs); + return ret; } static void bytes_dealloc(PyObject *op) { - Py_TYPE(op)->tp_free(op); + Py_TYPE(op)->tp_free(op); } /* Unescape a backslash-escaped string. If unicode is non-zero, @@ -376,135 +376,135 @@ specified encoding. */ PyObject *PyBytes_DecodeEscape(const char *s, - Py_ssize_t len, - const char *errors, - Py_ssize_t unicode, - const char *recode_encoding) -{ - int c; - char *p, *buf; - const char *end; - PyObject *v; - Py_ssize_t newlen = recode_encoding ? 4*len:len; - v = PyBytes_FromStringAndSize((char *)NULL, newlen); - if (v == NULL) - return NULL; - p = buf = PyBytes_AsString(v); - end = s + len; - while (s < end) { - if (*s != '\\') { - non_esc: - if (recode_encoding && (*s & 0x80)) { - PyObject *u, *w; - char *r; - const char* t; - Py_ssize_t rn; - t = s; - /* Decode non-ASCII bytes as UTF-8. */ - while (t < end && (*t & 0x80)) t++; - u = PyUnicode_DecodeUTF8(s, t - s, errors); - if(!u) goto failed; - - /* Recode them in target encoding. */ - w = PyUnicode_AsEncodedString( - u, recode_encoding, errors); - Py_DECREF(u); - if (!w) goto failed; - - /* Append bytes to output buffer. */ - assert(PyBytes_Check(w)); - r = PyBytes_AS_STRING(w); - rn = PyBytes_GET_SIZE(w); - Py_MEMCPY(p, r, rn); - p += rn; - Py_DECREF(w); - s = t; - } else { - *p++ = *s++; - } - 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 && ISXDIGIT(s[0]) && ISXDIGIT(s[1])) { - unsigned int x = 0; - c = Py_CHARMASK(*s); - s++; - if (ISDIGIT(c)) - x = c - '0'; - else if (ISLOWER(c)) - x = 10 + c - 'a'; - else - x = 10 + c - 'A'; - x = x << 4; - c = Py_CHARMASK(*s); - s++; - if (ISDIGIT(c)) - x += c - '0'; - else if (ISLOWER(c)) - x += 10 + c - 'a'; - else - x += 10 + c - 'A'; - *p++ = x; - break; - } - if (!errors || strcmp(errors, "strict") == 0) { - PyErr_SetString(PyExc_ValueError, - "invalid \\x escape"); - 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; - } - default: - *p++ = '\\'; - s--; - goto non_esc; /* an arbitry number of unescaped - UTF-8 bytes may follow. */ - } - } - if (p-buf < newlen) - _PyBytes_Resize(&v, p - buf); - return v; + Py_ssize_t len, + const char *errors, + Py_ssize_t unicode, + const char *recode_encoding) +{ + int c; + char *p, *buf; + const char *end; + PyObject *v; + Py_ssize_t newlen = recode_encoding ? 4*len:len; + v = PyBytes_FromStringAndSize((char *)NULL, newlen); + if (v == NULL) + return NULL; + p = buf = PyBytes_AsString(v); + end = s + len; + while (s < end) { + if (*s != '\\') { + non_esc: + if (recode_encoding && (*s & 0x80)) { + PyObject *u, *w; + char *r; + const char* t; + Py_ssize_t rn; + t = s; + /* Decode non-ASCII bytes as UTF-8. */ + while (t < end && (*t & 0x80)) t++; + u = PyUnicode_DecodeUTF8(s, t - s, errors); + if(!u) goto failed; + + /* Recode them in target encoding. */ + w = PyUnicode_AsEncodedString( + u, recode_encoding, errors); + Py_DECREF(u); + if (!w) goto failed; + + /* Append bytes to output buffer. */ + assert(PyBytes_Check(w)); + r = PyBytes_AS_STRING(w); + rn = PyBytes_GET_SIZE(w); + Py_MEMCPY(p, r, rn); + p += rn; + Py_DECREF(w); + s = t; + } else { + *p++ = *s++; + } + 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 && ISXDIGIT(s[0]) && ISXDIGIT(s[1])) { + unsigned int x = 0; + c = Py_CHARMASK(*s); + s++; + if (ISDIGIT(c)) + x = c - '0'; + else if (ISLOWER(c)) + x = 10 + c - 'a'; + else + x = 10 + c - 'A'; + x = x << 4; + c = Py_CHARMASK(*s); + s++; + if (ISDIGIT(c)) + x += c - '0'; + else if (ISLOWER(c)) + x += 10 + c - 'a'; + else + x += 10 + c - 'A'; + *p++ = x; + break; + } + if (!errors || strcmp(errors, "strict") == 0) { + PyErr_SetString(PyExc_ValueError, + "invalid \\x escape"); + 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; + } + default: + *p++ = '\\'; + s--; + goto non_esc; /* an arbitry number of unescaped + UTF-8 bytes may follow. */ + } + } + if (p-buf < newlen) + _PyBytes_Resize(&v, p - buf); + return v; failed: - Py_DECREF(v); - return NULL; + Py_DECREF(v); + return NULL; } /* -------------------------------------------------------------------- */ @@ -513,50 +513,50 @@ Py_ssize_t PyBytes_Size(register 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); + 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(register 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; + 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(register PyObject *obj, - register char **s, - register Py_ssize_t *len) + register char **s, + register 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_TypeError, - "expected bytes with no null"); - return -1; - } - return 0; + 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_TypeError, + "expected bytes with no null"); + return -1; + } + return 0; } /* -------------------------------------------------------------------- */ @@ -576,199 +576,199 @@ PyObject * PyBytes_Repr(PyObject *obj, int smartquotes) { - static const char *hexdigits = "0123456789abcdef"; - register PyBytesObject* op = (PyBytesObject*) obj; - Py_ssize_t length = Py_SIZE(op); - size_t newsize = 3 + 4 * length; - PyObject *v; - if (newsize > PY_SSIZE_T_MAX || (newsize-3) / 4 != length) { - PyErr_SetString(PyExc_OverflowError, - "bytes object is too large to make repr"); - return NULL; - } - v = PyUnicode_FromUnicode(NULL, newsize); - if (v == NULL) { - return NULL; - } - else { - register Py_ssize_t i; - register Py_UNICODE c; - register Py_UNICODE *p = PyUnicode_AS_UNICODE(v); - int quote; - - /* Figure out which quote to use; single is preferred */ - quote = '\''; - if (smartquotes) { - char *test, *start; - start = PyBytes_AS_STRING(op); - for (test = start; test < start+length; ++test) { - if (*test == '"') { - quote = '\''; /* back to single */ - goto decided; - } - else if (*test == '\'') - quote = '"'; - } - decided: - ; - } - - *p++ = 'b', *p++ = quote; - for (i = 0; i < length; i++) { - /* There's at least enough room for a hex escape - and a closing quote. */ - assert(newsize - (p - PyUnicode_AS_UNICODE(v)) >= 5); - 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++ = hexdigits[(c & 0xf0) >> 4]; - *p++ = hexdigits[c & 0xf]; - } - else - *p++ = c; - } - assert(newsize - (p - PyUnicode_AS_UNICODE(v)) >= 1); - *p++ = quote; - *p = '\0'; - if (PyUnicode_Resize(&v, (p - PyUnicode_AS_UNICODE(v)))) { - Py_DECREF(v); - return NULL; - } - return v; - } + static const char *hexdigits = "0123456789abcdef"; + register PyBytesObject* op = (PyBytesObject*) obj; + Py_ssize_t length = Py_SIZE(op); + size_t newsize = 3 + 4 * length; + PyObject *v; + if (newsize > PY_SSIZE_T_MAX || (newsize-3) / 4 != length) { + PyErr_SetString(PyExc_OverflowError, + "bytes object is too large to make repr"); + return NULL; + } + v = PyUnicode_FromUnicode(NULL, newsize); + if (v == NULL) { + return NULL; + } + else { + register Py_ssize_t i; + register Py_UNICODE c; + register Py_UNICODE *p = PyUnicode_AS_UNICODE(v); + int quote; + + /* Figure out which quote to use; single is preferred */ + quote = '\''; + if (smartquotes) { + char *test, *start; + start = PyBytes_AS_STRING(op); + for (test = start; test < start+length; ++test) { + if (*test == '"') { + quote = '\''; /* back to single */ + goto decided; + } + else if (*test == '\'') + quote = '"'; + } + decided: + ; + } + + *p++ = 'b', *p++ = quote; + for (i = 0; i < length; i++) { + /* There's at least enough room for a hex escape + and a closing quote. */ + assert(newsize - (p - PyUnicode_AS_UNICODE(v)) >= 5); + 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++ = hexdigits[(c & 0xf0) >> 4]; + *p++ = hexdigits[c & 0xf]; + } + else + *p++ = c; + } + assert(newsize - (p - PyUnicode_AS_UNICODE(v)) >= 1); + *p++ = quote; + *p = '\0'; + if (PyUnicode_Resize(&v, (p - PyUnicode_AS_UNICODE(v)))) { + Py_DECREF(v); + return NULL; + } + return v; + } } static PyObject * bytes_repr(PyObject *op) { - return PyBytes_Repr(op, 1); + 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); + 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); + return Py_SIZE(a); } /* This is also used by PyBytes_Concat() */ static PyObject * bytes_concat(PyObject *a, PyObject *b) { - Py_ssize_t size; - Py_buffer va, vb; - PyObject *result = NULL; - - va.len = -1; - vb.len = -1; - if (_getbuffer(a, &va) < 0 || - _getbuffer(b, &vb) < 0) { - PyErr_Format(PyExc_TypeError, "can't concat %.100s to %.100s", - Py_TYPE(a)->tp_name, Py_TYPE(b)->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; - } - - size = va.len + vb.len; - if (size < 0) { - PyErr_NoMemory(); - goto done; - } - - result = PyBytes_FromStringAndSize(NULL, size); - if (result != NULL) { - memcpy(PyBytes_AS_STRING(result), va.buf, va.len); - memcpy(PyBytes_AS_STRING(result) + va.len, vb.buf, vb.len); - } + Py_ssize_t size; + Py_buffer va, vb; + PyObject *result = NULL; + + va.len = -1; + vb.len = -1; + if (_getbuffer(a, &va) < 0 || + _getbuffer(b, &vb) < 0) { + PyErr_Format(PyExc_TypeError, "can't concat %.100s to %.100s", + Py_TYPE(a)->tp_name, Py_TYPE(b)->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; + } + + size = va.len + vb.len; + if (size < 0) { + PyErr_NoMemory(); + goto done; + } + + result = PyBytes_FromStringAndSize(NULL, size); + 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; + if (va.len != -1) + PyBuffer_Release(&va); + if (vb.len != -1) + PyBuffer_Release(&vb); + return result; } static PyObject * bytes_repeat(register PyBytesObject *a, register Py_ssize_t n) { - register Py_ssize_t i; - register Py_ssize_t j; - register Py_ssize_t size; - register 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 - */ - size = Py_SIZE(a) * n; - if (n && size / n != Py_SIZE(a)) { - PyErr_SetString(PyExc_OverflowError, - "repeated bytes are too long"); - return NULL; - } - 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(); - 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) { - Py_MEMCPY(op->ob_sval, a->ob_sval, Py_SIZE(a)); - i = Py_SIZE(a); - } - while (i < size) { - j = (i <= size-i) ? i : size-i; - Py_MEMCPY(op->ob_sval+i, op->ob_sval, j); - i += j; - } - return (PyObject *) op; + register Py_ssize_t i; + register Py_ssize_t j; + register Py_ssize_t size; + register 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 + */ + size = Py_SIZE(a) * n; + if (n && size / n != Py_SIZE(a)) { + PyErr_SetString(PyExc_OverflowError, + "repeated bytes are too long"); + return NULL; + } + 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(); + 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) { + Py_MEMCPY(op->ob_sval, a->ob_sval, Py_SIZE(a)); + i = Py_SIZE(a); + } + while (i < size) { + j = (i <= size-i) ? i : size-i; + Py_MEMCPY(op->ob_sval+i, op->ob_sval, j); + i += j; + } + return (PyObject *) op; } static int @@ -776,19 +776,19 @@ { Py_ssize_t ival = PyNumber_AsSsize_t(arg, PyExc_ValueError); if (ival == -1 && PyErr_Occurred()) { - Py_buffer varg; - int pos; - PyErr_Clear(); - if (_getbuffer(arg, &varg) < 0) - return -1; - pos = stringlib_find(PyBytes_AS_STRING(self), Py_SIZE(self), - varg.buf, varg.len, 0); - PyBuffer_Release(&varg); - return pos >= 0; + Py_buffer varg; + int pos; + PyErr_Clear(); + if (_getbuffer(arg, &varg) < 0) + return -1; + pos = stringlib_find(PyBytes_AS_STRING(self), Py_SIZE(self), + varg.buf, varg.len, 0); + PyBuffer_Release(&varg); + return pos >= 0; } if (ival < 0 || ival >= 256) { - PyErr_SetString(PyExc_ValueError, "byte must be in range(0, 256)"); - return -1; + PyErr_SetString(PyExc_ValueError, "byte must be in range(0, 256)"); + return -1; } return memchr(PyBytes_AS_STRING(self), ival, Py_SIZE(self)) != NULL; @@ -797,197 +797,197 @@ static PyObject * bytes_item(PyBytesObject *a, register 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]); + 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 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; - - /* Make sure both arguments are strings. */ - if (!(PyBytes_Check(a) && PyBytes_Check(b))) { - if (Py_BytesWarningFlag && (op == Py_EQ || op == Py_NE) && - (PyObject_IsInstance((PyObject*)a, - (PyObject*)&PyUnicode_Type) || - PyObject_IsInstance((PyObject*)b, - (PyObject*)&PyUnicode_Type))) { - if (PyErr_WarnEx(PyExc_BytesWarning, - "Comparison between bytes and string", 1)) - return NULL; - } - result = Py_NotImplemented; - goto out; - } - if (a == b) { - switch (op) { - case Py_EQ:case Py_LE:case Py_GE: - result = Py_True; - goto out; - case Py_NE:case Py_LT:case Py_GT: - result = Py_False; - goto out; - } - } - if (op == Py_EQ) { - /* Supporting Py_NE here as well does not save - much time, since Py_NE is rarely used. */ - if (Py_SIZE(a) == Py_SIZE(b) - && (a->ob_sval[0] == b->ob_sval[0] - && memcmp(a->ob_sval, b->ob_sval, Py_SIZE(a)) == 0)) { - result = Py_True; - } else { - result = Py_False; - } - goto out; - } - len_a = Py_SIZE(a); len_b = Py_SIZE(b); - min_len = (len_a < len_b) ? 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_EQ: assert(0); break; /* unreachable */ - case Py_NE: c = c != 0; break; - case Py_GT: c = c > 0; break; - case Py_GE: c = c >= 0; break; - default: - result = Py_NotImplemented; - goto out; - } - result = c ? Py_True : Py_False; + int c; + Py_ssize_t len_a, len_b; + Py_ssize_t min_len; + PyObject *result; + + /* Make sure both arguments are strings. */ + if (!(PyBytes_Check(a) && PyBytes_Check(b))) { + if (Py_BytesWarningFlag && (op == Py_EQ || op == Py_NE) && + (PyObject_IsInstance((PyObject*)a, + (PyObject*)&PyUnicode_Type) || + PyObject_IsInstance((PyObject*)b, + (PyObject*)&PyUnicode_Type))) { + if (PyErr_WarnEx(PyExc_BytesWarning, + "Comparison between bytes and string", 1)) + return NULL; + } + result = Py_NotImplemented; + goto out; + } + if (a == b) { + switch (op) { + case Py_EQ:case Py_LE:case Py_GE: + result = Py_True; + goto out; + case Py_NE:case Py_LT:case Py_GT: + result = Py_False; + goto out; + } + } + if (op == Py_EQ) { + /* Supporting Py_NE here as well does not save + much time, since Py_NE is rarely used. */ + if (Py_SIZE(a) == Py_SIZE(b) + && (a->ob_sval[0] == b->ob_sval[0] + && memcmp(a->ob_sval, b->ob_sval, Py_SIZE(a)) == 0)) { + result = Py_True; + } else { + result = Py_False; + } + goto out; + } + len_a = Py_SIZE(a); len_b = Py_SIZE(b); + min_len = (len_a < len_b) ? 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_EQ: assert(0); break; /* unreachable */ + case Py_NE: c = c != 0; break; + case Py_GT: c = c > 0; break; + case Py_GE: c = c >= 0; break; + default: + result = Py_NotImplemented; + goto out; + } + result = c ? Py_True : Py_False; out: - Py_INCREF(result); - return result; + Py_INCREF(result); + return result; } static long bytes_hash(PyBytesObject *a) { - register Py_ssize_t len; - register unsigned char *p; - register long x; - - if (a->ob_shash != -1) - return a->ob_shash; - len = Py_SIZE(a); - p = (unsigned char *) a->ob_sval; - x = *p << 7; - while (--len >= 0) - x = (1000003*x) ^ *p++; - x ^= Py_SIZE(a); - if (x == -1) - x = -2; - a->ob_shash = x; - return x; + register Py_ssize_t len; + register unsigned char *p; + register long x; + + if (a->ob_shash != -1) + return a->ob_shash; + len = Py_SIZE(a); + p = (unsigned char *) a->ob_sval; + x = *p << 7; + while (--len >= 0) + x = (1000003*x) ^ *p++; + x ^= Py_SIZE(a); + if (x == -1) + x = -2; + a->ob_shash = x; + return x; } 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_GetIndicesEx((PySliceObject*)item, - PyBytes_GET_SIZE(self), - &start, &stop, &step, &slicelength) < 0) { - return NULL; - } - - 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, not %.200s", - Py_TYPE(item)->tp_name); - return NULL; - } + 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_GetIndicesEx((PySliceObject*)item, + PyBytes_GET_SIZE(self), + &start, &stop, &step, &slicelength) < 0) { + return NULL; + } + + 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, 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); + 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*/ + (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, + (lenfunc)bytes_length, + (binaryfunc)bytes_subscript, + 0, }; static PyBufferProcs bytes_as_buffer = { - (getbufferproc)bytes_buffer_getbuffer, - NULL, + (getbufferproc)bytes_buffer_getbuffer, + NULL, }; @@ -1011,26 +1011,26 @@ static PyObject * bytes_split(PyBytesObject *self, PyObject *args) { - Py_ssize_t len = PyBytes_GET_SIZE(self), n; - Py_ssize_t maxsplit = -1; - const char *s = PyBytes_AS_STRING(self), *sub; - Py_buffer vsub; - PyObject *list, *subobj = Py_None; - - if (!PyArg_ParseTuple(args, "|On:split", &subobj, &maxsplit)) - return NULL; - if (maxsplit < 0) - maxsplit = PY_SSIZE_T_MAX; - if (subobj == Py_None) - return stringlib_split_whitespace((PyObject*) self, s, len, maxsplit); - if (_getbuffer(subobj, &vsub) < 0) - return NULL; - sub = vsub.buf; - n = vsub.len; - - list = stringlib_split((PyObject*) self, s, len, sub, n, maxsplit); - PyBuffer_Release(&vsub); - return list; + Py_ssize_t len = PyBytes_GET_SIZE(self), n; + Py_ssize_t maxsplit = -1; + const char *s = PyBytes_AS_STRING(self), *sub; + Py_buffer vsub; + PyObject *list, *subobj = Py_None; + + if (!PyArg_ParseTuple(args, "|On:split", &subobj, &maxsplit)) + return NULL; + if (maxsplit < 0) + maxsplit = PY_SSIZE_T_MAX; + if (subobj == Py_None) + return stringlib_split_whitespace((PyObject*) self, s, len, maxsplit); + if (_getbuffer(subobj, &vsub) < 0) + return NULL; + sub = vsub.buf; + n = vsub.len; + + list = stringlib_split((PyObject*) self, s, len, sub, n, maxsplit); + PyBuffer_Release(&vsub); + return list; } PyDoc_STRVAR(partition__doc__, @@ -1043,21 +1043,21 @@ static PyObject * bytes_partition(PyBytesObject *self, PyObject *sep_obj) { - const char *sep; - Py_ssize_t sep_len; + const char *sep; + Py_ssize_t sep_len; + + if (PyBytes_Check(sep_obj)) { + sep = PyBytes_AS_STRING(sep_obj); + sep_len = PyBytes_GET_SIZE(sep_obj); + } + else if (PyObject_AsCharBuffer(sep_obj, &sep, &sep_len)) + return NULL; - if (PyBytes_Check(sep_obj)) { - sep = PyBytes_AS_STRING(sep_obj); - sep_len = PyBytes_GET_SIZE(sep_obj); - } - else if (PyObject_AsCharBuffer(sep_obj, &sep, &sep_len)) - return NULL; - - return stringlib_partition( - (PyObject*) self, - PyBytes_AS_STRING(self), PyBytes_GET_SIZE(self), - sep_obj, sep, sep_len - ); + return stringlib_partition( + (PyObject*) self, + PyBytes_AS_STRING(self), PyBytes_GET_SIZE(self), + sep_obj, sep, sep_len + ); } PyDoc_STRVAR(rpartition__doc__, @@ -1071,21 +1071,21 @@ static PyObject * bytes_rpartition(PyBytesObject *self, PyObject *sep_obj) { - const char *sep; - Py_ssize_t sep_len; + const char *sep; + Py_ssize_t sep_len; - if (PyBytes_Check(sep_obj)) { - sep = PyBytes_AS_STRING(sep_obj); - sep_len = PyBytes_GET_SIZE(sep_obj); - } - else if (PyObject_AsCharBuffer(sep_obj, &sep, &sep_len)) - return NULL; - - return stringlib_rpartition( - (PyObject*) self, - PyBytes_AS_STRING(self), PyBytes_GET_SIZE(self), - sep_obj, sep, sep_len - ); + if (PyBytes_Check(sep_obj)) { + sep = PyBytes_AS_STRING(sep_obj); + sep_len = PyBytes_GET_SIZE(sep_obj); + } + else if (PyObject_AsCharBuffer(sep_obj, &sep, &sep_len)) + return NULL; + + return stringlib_rpartition( + (PyObject*) self, + PyBytes_AS_STRING(self), PyBytes_GET_SIZE(self), + sep_obj, sep, sep_len + ); } PyDoc_STRVAR(rsplit__doc__, @@ -1101,26 +1101,26 @@ static PyObject * bytes_rsplit(PyBytesObject *self, PyObject *args) { - Py_ssize_t len = PyBytes_GET_SIZE(self), n; - Py_ssize_t maxsplit = -1; - const char *s = PyBytes_AS_STRING(self), *sub; - Py_buffer vsub; - PyObject *list, *subobj = Py_None; - - if (!PyArg_ParseTuple(args, "|On:rsplit", &subobj, &maxsplit)) - return NULL; - if (maxsplit < 0) - maxsplit = PY_SSIZE_T_MAX; - if (subobj == Py_None) - return stringlib_rsplit_whitespace((PyObject*) self, s, len, maxsplit); - if (_getbuffer(subobj, &vsub) < 0) - return NULL; - sub = vsub.buf; - n = vsub.len; - - list = stringlib_rsplit((PyObject*) self, s, len, sub, n, maxsplit); - PyBuffer_Release(&vsub); - return list; + Py_ssize_t len = PyBytes_GET_SIZE(self), n; + Py_ssize_t maxsplit = -1; + const char *s = PyBytes_AS_STRING(self), *sub; + Py_buffer vsub; + PyObject *list, *subobj = Py_None; + + if (!PyArg_ParseTuple(args, "|On:rsplit", &subobj, &maxsplit)) + return NULL; + if (maxsplit < 0) + maxsplit = PY_SSIZE_T_MAX; + if (subobj == Py_None) + return stringlib_rsplit_whitespace((PyObject*) self, s, len, maxsplit); + if (_getbuffer(subobj, &vsub) < 0) + return NULL; + sub = vsub.buf; + n = vsub.len; + + list = stringlib_rsplit((PyObject*) self, s, len, sub, n, maxsplit); + PyBuffer_Release(&vsub); + return list; } @@ -1133,156 +1133,156 @@ static PyObject * bytes_join(PyObject *self, PyObject *orig) { - char *sep = PyBytes_AS_STRING(self); - const Py_ssize_t seplen = PyBytes_GET_SIZE(self); - PyObject *res = NULL; - char *p; - Py_ssize_t seqlen = 0; - size_t sz = 0; - Py_ssize_t i; - PyObject *seq, *item; - - seq = PySequence_Fast(orig, ""); - if (seq == NULL) { - return NULL; - } - - seqlen = PySequence_Size(seq); - if (seqlen == 0) { - Py_DECREF(seq); - return PyBytes_FromString(""); - } - if (seqlen == 1) { - item = PySequence_Fast_GET_ITEM(seq, 0); - if (PyBytes_CheckExact(item)) { - Py_INCREF(item); - Py_DECREF(seq); - return item; - } - } - - /* There are at least two things to join, or else we have a subclass - * of the builtin types in the sequence. - * Do a pre-pass to figure out the total amount of space we'll - * need (sz), and see whether all argument are bytes. - */ - /* XXX Shouldn't we use _getbuffer() on these items instead? */ - for (i = 0; i < seqlen; i++) { - const size_t old_sz = sz; - item = PySequence_Fast_GET_ITEM(seq, i); - if (!PyBytes_Check(item) && !PyByteArray_Check(item)) { - PyErr_Format(PyExc_TypeError, - "sequence item %zd: expected bytes," - " %.80s found", - i, Py_TYPE(item)->tp_name); - Py_DECREF(seq); - return NULL; - } - sz += Py_SIZE(item); - if (i != 0) - sz += seplen; - if (sz < old_sz || sz > PY_SSIZE_T_MAX) { - PyErr_SetString(PyExc_OverflowError, - "join() result is too long for bytes"); - Py_DECREF(seq); - return NULL; - } - } - - /* Allocate result space. */ - res = PyBytes_FromStringAndSize((char*)NULL, sz); - if (res == NULL) { - Py_DECREF(seq); - return NULL; - } - - /* Catenate everything. */ - /* I'm not worried about a PyByteArray item growing because there's - nowhere in this function where we release the GIL. */ - p = PyBytes_AS_STRING(res); - for (i = 0; i < seqlen; ++i) { - size_t n; - char *q; - if (i) { - Py_MEMCPY(p, sep, seplen); - p += seplen; - } - item = PySequence_Fast_GET_ITEM(seq, i); - n = Py_SIZE(item); - if (PyBytes_Check(item)) - q = PyBytes_AS_STRING(item); - else - q = PyByteArray_AS_STRING(item); - Py_MEMCPY(p, q, n); - p += n; - } + char *sep = PyBytes_AS_STRING(self); + const Py_ssize_t seplen = PyBytes_GET_SIZE(self); + PyObject *res = NULL; + char *p; + Py_ssize_t seqlen = 0; + size_t sz = 0; + Py_ssize_t i; + PyObject *seq, *item; + + seq = PySequence_Fast(orig, ""); + if (seq == NULL) { + return NULL; + } - Py_DECREF(seq); - return res; + seqlen = PySequence_Size(seq); + if (seqlen == 0) { + Py_DECREF(seq); + return PyBytes_FromString(""); + } + if (seqlen == 1) { + item = PySequence_Fast_GET_ITEM(seq, 0); + if (PyBytes_CheckExact(item)) { + Py_INCREF(item); + Py_DECREF(seq); + return item; + } + } + + /* There are at least two things to join, or else we have a subclass + * of the builtin types in the sequence. + * Do a pre-pass to figure out the total amount of space we'll + * need (sz), and see whether all argument are bytes. + */ + /* XXX Shouldn't we use _getbuffer() on these items instead? */ + for (i = 0; i < seqlen; i++) { + const size_t old_sz = sz; + item = PySequence_Fast_GET_ITEM(seq, i); + if (!PyBytes_Check(item) && !PyByteArray_Check(item)) { + PyErr_Format(PyExc_TypeError, + "sequence item %zd: expected bytes," + " %.80s found", + i, Py_TYPE(item)->tp_name); + Py_DECREF(seq); + return NULL; + } + sz += Py_SIZE(item); + if (i != 0) + sz += seplen; + if (sz < old_sz || sz > PY_SSIZE_T_MAX) { + PyErr_SetString(PyExc_OverflowError, + "join() result is too long for bytes"); + Py_DECREF(seq); + return NULL; + } + } + + /* Allocate result space. */ + res = PyBytes_FromStringAndSize((char*)NULL, sz); + if (res == NULL) { + Py_DECREF(seq); + return NULL; + } + + /* Catenate everything. */ + /* I'm not worried about a PyByteArray item growing because there's + nowhere in this function where we release the GIL. */ + p = PyBytes_AS_STRING(res); + for (i = 0; i < seqlen; ++i) { + size_t n; + char *q; + if (i) { + Py_MEMCPY(p, sep, seplen); + p += seplen; + } + item = PySequence_Fast_GET_ITEM(seq, i); + n = Py_SIZE(item); + if (PyBytes_Check(item)) + q = PyBytes_AS_STRING(item); + else + q = PyByteArray_AS_STRING(item); + Py_MEMCPY(p, q, n); + p += n; + } + + Py_DECREF(seq); + return res; } PyObject * _PyBytes_Join(PyObject *sep, PyObject *x) { - assert(sep != NULL && PyBytes_Check(sep)); - assert(x != NULL); - return bytes_join(sep, x); + assert(sep != NULL && PyBytes_Check(sep)); + assert(x != NULL); + return bytes_join(sep, x); } /* helper macro to fixup start/end slice values */ #define ADJUST_INDICES(start, end, len) \ - if (end > len) \ - end = len; \ - else if (end < 0) { \ - end += len; \ - if (end < 0) \ - end = 0; \ - } \ - if (start < 0) { \ - start += len; \ - if (start < 0) \ - start = 0; \ - } + if (end > len) \ + end = len; \ + else if (end < 0) { \ + end += len; \ + if (end < 0) \ + end = 0; \ + } \ + if (start < 0) { \ + start += len; \ + if (start < 0) \ + start = 0; \ + } Py_LOCAL_INLINE(Py_ssize_t) bytes_find_internal(PyBytesObject *self, PyObject *args, int dir) { - PyObject *subobj; - const char *sub; - Py_ssize_t sub_len; - Py_ssize_t start=0, end=PY_SSIZE_T_MAX; - PyObject *obj_start=Py_None, *obj_end=Py_None; - - if (!PyArg_ParseTuple(args, "O|OO:find/rfind/index/rindex", &subobj, - &obj_start, &obj_end)) - return -2; - /* To support None in "start" and "end" arguments, meaning - the same as if they were not passed. - */ - if (obj_start != Py_None) - if (!_PyEval_SliceIndex(obj_start, &start)) - return -2; - if (obj_end != Py_None) - if (!_PyEval_SliceIndex(obj_end, &end)) - return -2; - - if (PyBytes_Check(subobj)) { - sub = PyBytes_AS_STRING(subobj); - sub_len = PyBytes_GET_SIZE(subobj); - } - else if (PyObject_AsCharBuffer(subobj, &sub, &sub_len)) - /* XXX - the "expected a character buffer object" is pretty - confusing for a non-expert. remap to something else ? */ - return -2; - - if (dir > 0) - return stringlib_find_slice( - PyBytes_AS_STRING(self), PyBytes_GET_SIZE(self), - sub, sub_len, start, end); - else - return stringlib_rfind_slice( - PyBytes_AS_STRING(self), PyBytes_GET_SIZE(self), - sub, sub_len, start, end); + PyObject *subobj; + const char *sub; + Py_ssize_t sub_len; + Py_ssize_t start=0, end=PY_SSIZE_T_MAX; + PyObject *obj_start=Py_None, *obj_end=Py_None; + + if (!PyArg_ParseTuple(args, "O|OO:find/rfind/index/rindex", &subobj, + &obj_start, &obj_end)) + return -2; + /* To support None in "start" and "end" arguments, meaning + the same as if they were not passed. + */ + if (obj_start != Py_None) + if (!_PyEval_SliceIndex(obj_start, &start)) + return -2; + if (obj_end != Py_None) + if (!_PyEval_SliceIndex(obj_end, &end)) + return -2; + + if (PyBytes_Check(subobj)) { + sub = PyBytes_AS_STRING(subobj); + sub_len = PyBytes_GET_SIZE(subobj); + } + else if (PyObject_AsCharBuffer(subobj, &sub, &sub_len)) + /* XXX - the "expected a character buffer object" is pretty + confusing for a non-expert. remap to something else ? */ + return -2; + + if (dir > 0) + return stringlib_find_slice( + PyBytes_AS_STRING(self), PyBytes_GET_SIZE(self), + sub, sub_len, start, end); + else + return stringlib_rfind_slice( + PyBytes_AS_STRING(self), PyBytes_GET_SIZE(self), + sub, sub_len, start, end); } @@ -1298,10 +1298,10 @@ static PyObject * bytes_find(PyBytesObject *self, PyObject *args) { - Py_ssize_t result = bytes_find_internal(self, args, +1); - if (result == -2) - return NULL; - return PyLong_FromSsize_t(result); + Py_ssize_t result = bytes_find_internal(self, args, +1); + if (result == -2) + return NULL; + return PyLong_FromSsize_t(result); } @@ -1313,15 +1313,15 @@ static PyObject * bytes_index(PyBytesObject *self, PyObject *args) { - Py_ssize_t result = bytes_find_internal(self, args, +1); - if (result == -2) - return NULL; - if (result == -1) { - PyErr_SetString(PyExc_ValueError, - "substring not found"); - return NULL; - } - return PyLong_FromSsize_t(result); + Py_ssize_t result = bytes_find_internal(self, args, +1); + if (result == -2) + return NULL; + if (result == -1) { + PyErr_SetString(PyExc_ValueError, + "substring not found"); + return NULL; + } + return PyLong_FromSsize_t(result); } @@ -1337,10 +1337,10 @@ static PyObject * bytes_rfind(PyBytesObject *self, PyObject *args) { - Py_ssize_t result = bytes_find_internal(self, args, -1); - if (result == -2) - return NULL; - return PyLong_FromSsize_t(result); + Py_ssize_t result = bytes_find_internal(self, args, -1); + if (result == -2) + return NULL; + return PyLong_FromSsize_t(result); } @@ -1352,101 +1352,101 @@ static PyObject * bytes_rindex(PyBytesObject *self, PyObject *args) { - Py_ssize_t result = bytes_find_internal(self, args, -1); - if (result == -2) - return NULL; - if (result == -1) { - PyErr_SetString(PyExc_ValueError, - "substring not found"); - return NULL; - } - return PyLong_FromSsize_t(result); + Py_ssize_t result = bytes_find_internal(self, args, -1); + if (result == -2) + return NULL; + if (result == -1) { + PyErr_SetString(PyExc_ValueError, + "substring not found"); + return NULL; + } + return PyLong_FromSsize_t(result); } 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 (_getbuffer(sepobj, &vsep) < 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_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 (_getbuffer(sepobj, &vsep) < 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; + char *s = PyBytes_AS_STRING(self); + Py_ssize_t len = PyBytes_GET_SIZE(self), i, j; + + i = 0; + if (striptype != RIGHTSTRIP) { + while (i < len && ISSPACE(s[i])) { + i++; + } + } + + j = len; + if (striptype != LEFTSTRIP) { + do { + j--; + } while (j >= i && ISSPACE(s[j])); + j++; + } - i = 0; - if (striptype != RIGHTSTRIP) { - while (i < len && ISSPACE(s[i])) { - i++; - } - } - - j = len; - if (striptype != LEFTSTRIP) { - do { - j--; - } while (j >= i && 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); + 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 *args) { - PyObject *sep = NULL; + PyObject *sep = NULL; - if (!PyArg_ParseTuple(args, (char *)stripformat[striptype], &sep)) - return NULL; + if (!PyArg_ParseTuple(args, (char *)stripformat[striptype], &sep)) + return NULL; - if (sep != NULL && sep != Py_None) { - return do_xstrip(self, striptype, sep); - } - return do_strip(self, striptype); + if (sep != NULL && sep != Py_None) { + return do_xstrip(self, striptype, sep); + } + return do_strip(self, striptype); } @@ -1458,10 +1458,10 @@ static PyObject * bytes_strip(PyBytesObject *self, PyObject *args) { - if (PyTuple_GET_SIZE(args) == 0) - return do_strip(self, BOTHSTRIP); /* Common case */ - else - return do_argstrip(self, BOTHSTRIP, args); + if (PyTuple_GET_SIZE(args) == 0) + return do_strip(self, BOTHSTRIP); /* Common case */ + else + return do_argstrip(self, BOTHSTRIP, args); } @@ -1473,10 +1473,10 @@ static PyObject * bytes_lstrip(PyBytesObject *self, PyObject *args) { - if (PyTuple_GET_SIZE(args) == 0) - return do_strip(self, LEFTSTRIP); /* Common case */ - else - return do_argstrip(self, LEFTSTRIP, args); + if (PyTuple_GET_SIZE(args) == 0) + return do_strip(self, LEFTSTRIP); /* Common case */ + else + return do_argstrip(self, LEFTSTRIP, args); } @@ -1488,10 +1488,10 @@ static PyObject * bytes_rstrip(PyBytesObject *self, PyObject *args) { - if (PyTuple_GET_SIZE(args) == 0) - return do_strip(self, RIGHTSTRIP); /* Common case */ - else - return do_argstrip(self, RIGHTSTRIP, args); + if (PyTuple_GET_SIZE(args) == 0) + return do_strip(self, RIGHTSTRIP); /* Common case */ + else + return do_argstrip(self, RIGHTSTRIP, args); } @@ -1505,27 +1505,27 @@ static PyObject * bytes_count(PyBytesObject *self, PyObject *args) { - PyObject *sub_obj; - const char *str = PyBytes_AS_STRING(self), *sub; - Py_ssize_t sub_len; - Py_ssize_t start = 0, end = PY_SSIZE_T_MAX; - - if (!PyArg_ParseTuple(args, "O|O&O&:count", &sub_obj, - _PyEval_SliceIndex, &start, _PyEval_SliceIndex, &end)) - return NULL; - - if (PyBytes_Check(sub_obj)) { - sub = PyBytes_AS_STRING(sub_obj); - sub_len = PyBytes_GET_SIZE(sub_obj); - } - else if (PyObject_AsCharBuffer(sub_obj, &sub, &sub_len)) - return NULL; - - ADJUST_INDICES(start, end, PyBytes_GET_SIZE(self)); - - return PyLong_FromSsize_t( - stringlib_count(str + start, end - start, sub, sub_len, PY_SSIZE_T_MAX) - ); + PyObject *sub_obj; + const char *str = PyBytes_AS_STRING(self), *sub; + Py_ssize_t sub_len; + Py_ssize_t start = 0, end = PY_SSIZE_T_MAX; + + if (!PyArg_ParseTuple(args, "O|O&O&:count", &sub_obj, + _PyEval_SliceIndex, &start, _PyEval_SliceIndex, &end)) + return NULL; + + if (PyBytes_Check(sub_obj)) { + sub = PyBytes_AS_STRING(sub_obj); + sub_len = PyBytes_GET_SIZE(sub_obj); + } + else if (PyObject_AsCharBuffer(sub_obj, &sub, &sub_len)) + return NULL; + + ADJUST_INDICES(start, end, PyBytes_GET_SIZE(self)); + + return PyLong_FromSsize_t( + stringlib_count(str + start, end - start, sub, sub_len, PY_SSIZE_T_MAX) + ); } @@ -1540,110 +1540,110 @@ static PyObject * bytes_translate(PyBytesObject *self, PyObject *args) { - register char *input, *output; - const char *table; - register Py_ssize_t i, c, changed = 0; - PyObject *input_obj = (PyObject*)self; - const char *output_start, *del_table=NULL; - Py_ssize_t inlen, tablen, dellen = 0; - PyObject *result; - int trans_table[256]; - PyObject *tableobj, *delobj = NULL; - - if (!PyArg_UnpackTuple(args, "translate", 1, 2, - &tableobj, &delobj)) - return NULL; - - if (PyBytes_Check(tableobj)) { - table = PyBytes_AS_STRING(tableobj); - tablen = PyBytes_GET_SIZE(tableobj); - } - else if (tableobj == Py_None) { - table = NULL; - tablen = 256; - } - else if (PyObject_AsCharBuffer(tableobj, &table, &tablen)) - return NULL; - - if (tablen != 256) { - PyErr_SetString(PyExc_ValueError, - "translation table must be 256 characters long"); - return NULL; - } - - if (delobj != NULL) { - if (PyBytes_Check(delobj)) { - del_table = PyBytes_AS_STRING(delobj); - dellen = PyBytes_GET_SIZE(delobj); - } - else if (PyObject_AsCharBuffer(delobj, &del_table, &dellen)) - return NULL; - } - else { - del_table = NULL; - dellen = 0; - } - - inlen = PyBytes_GET_SIZE(input_obj); - result = PyBytes_FromStringAndSize((char *)NULL, inlen); - if (result == NULL) - return NULL; - output_start = output = PyBytes_AsString(result); - input = PyBytes_AS_STRING(input_obj); - - if (dellen == 0 && table != NULL) { - /* If no deletions are required, use faster code */ - for (i = inlen; --i >= 0; ) { - c = Py_CHARMASK(*input++); - if (Py_CHARMASK((*output++ = table[c])) != c) - changed = 1; - } - if (changed || !PyBytes_CheckExact(input_obj)) - return result; - Py_DECREF(result); - Py_INCREF(input_obj); - return input_obj; - } - - if (table == 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[i]); - } - - for (i = 0; i < dellen; i++) - trans_table[(int) Py_CHARMASK(del_table[i])] = -1; - - 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; + register char *input, *output; + const char *table; + register Py_ssize_t i, c, changed = 0; + PyObject *input_obj = (PyObject*)self; + const char *output_start, *del_table=NULL; + Py_ssize_t inlen, tablen, dellen = 0; + PyObject *result; + int trans_table[256]; + PyObject *tableobj, *delobj = NULL; + + if (!PyArg_UnpackTuple(args, "translate", 1, 2, + &tableobj, &delobj)) + return NULL; + + if (PyBytes_Check(tableobj)) { + table = PyBytes_AS_STRING(tableobj); + tablen = PyBytes_GET_SIZE(tableobj); + } + else if (tableobj == Py_None) { + table = NULL; + tablen = 256; + } + else if (PyObject_AsCharBuffer(tableobj, &table, &tablen)) + return NULL; + + if (tablen != 256) { + PyErr_SetString(PyExc_ValueError, + "translation table must be 256 characters long"); + return NULL; + } + + if (delobj != NULL) { + if (PyBytes_Check(delobj)) { + del_table = PyBytes_AS_STRING(delobj); + dellen = PyBytes_GET_SIZE(delobj); + } + else if (PyObject_AsCharBuffer(delobj, &del_table, &dellen)) + return NULL; + } + else { + del_table = NULL; + dellen = 0; + } + + inlen = PyBytes_GET_SIZE(input_obj); + result = PyBytes_FromStringAndSize((char *)NULL, inlen); + if (result == NULL) + return NULL; + output_start = output = PyBytes_AsString(result); + input = PyBytes_AS_STRING(input_obj); + + if (dellen == 0 && table != NULL) { + /* If no deletions are required, use faster code */ + for (i = inlen; --i >= 0; ) { + c = Py_CHARMASK(*input++); + if (Py_CHARMASK((*output++ = table[c])) != c) + changed = 1; + } + if (changed || !PyBytes_CheckExact(input_obj)) + return result; + Py_DECREF(result); + Py_INCREF(input_obj); + return input_obj; + } + + if (table == 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[i]); + } + + for (i = 0; i < dellen; i++) + trans_table[(int) Py_CHARMASK(del_table[i])] = -1; + + 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; } static PyObject * bytes_maketrans(PyObject *null, PyObject *args) { - return _Py_bytes_maketrans(args); + return _Py_bytes_maketrans(args); } /* find and count characters and substrings */ -#define findchar(target, target_len, c) \ +#define findchar(target, target_len, c) \ ((char *)memchr((const void *)(target), c, target_len)) /* String ops must return a string. */ @@ -1651,29 +1651,29 @@ Py_LOCAL(PyBytesObject *) return_self(PyBytesObject *self) { - if (PyBytes_CheckExact(self)) { - Py_INCREF(self); - return self; - } - return (PyBytesObject *)PyBytes_FromStringAndSize( - PyBytes_AS_STRING(self), - PyBytes_GET_SIZE(self)); + if (PyBytes_CheckExact(self)) { + Py_INCREF(self); + return self; + } + return (PyBytesObject *)PyBytes_FromStringAndSize( + PyBytes_AS_STRING(self), + PyBytes_GET_SIZE(self)); } Py_LOCAL_INLINE(Py_ssize_t) countchar(const char *target, int target_len, char c, Py_ssize_t maxcount) { - Py_ssize_t count=0; - const char *start=target; - const char *end=target+target_len; - - while ( (start=findchar(start, end-start, c)) != NULL ) { - count++; - if (count >= maxcount) - break; - start += 1; - } - return count; + Py_ssize_t count=0; + const char *start=target; + const char *end=target+target_len; + + while ( (start=findchar(start, end-start, c)) != NULL ) { + count++; + if (count >= maxcount) + break; + start += 1; + } + return count; } @@ -1682,467 +1682,467 @@ /* len(self)>=1, from="", len(to)>=1, maxcount>=1 */ Py_LOCAL(PyBytesObject *) replace_interleave(PyBytesObject *self, - const char *to_s, Py_ssize_t to_len, - Py_ssize_t maxcount) + const char *to_s, Py_ssize_t to_len, + Py_ssize_t maxcount) { - char *self_s, *result_s; - Py_ssize_t self_len, result_len; - Py_ssize_t count, i, product; - PyBytesObject *result; - - self_len = PyBytes_GET_SIZE(self); - - /* 1 at the end plus 1 after every character */ - count = self_len+1; - if (maxcount < count) - count = maxcount; - - /* Check for overflow */ - /* result_len = count * to_len + self_len; */ - product = count * to_len; - if (product / to_len != count) { - PyErr_SetString(PyExc_OverflowError, - "replacement bytes are too long"); - return NULL; - } - result_len = product + self_len; - if (result_len < 0) { - PyErr_SetString(PyExc_OverflowError, - "replacement bytes are too long"); - return NULL; - } - - if (! (result = (PyBytesObject *) - PyBytes_FromStringAndSize(NULL, result_len)) ) - return NULL; - - self_s = PyBytes_AS_STRING(self); - result_s = PyBytes_AS_STRING(result); - - /* TODO: special case single character, which doesn't need memcpy */ - - /* Lay the first one down (guaranteed this will occur) */ - Py_MEMCPY(result_s, to_s, to_len); - result_s += to_len; - count -= 1; - - for (i=0; i=1, len(from)==1, to="", maxcount>=1 */ Py_LOCAL(PyBytesObject *) replace_delete_single_character(PyBytesObject *self, - char from_c, Py_ssize_t maxcount) + char from_c, Py_ssize_t maxcount) { - char *self_s, *result_s; - char *start, *next, *end; - Py_ssize_t self_len, result_len; - Py_ssize_t count; - PyBytesObject *result; - - self_len = PyBytes_GET_SIZE(self); - self_s = PyBytes_AS_STRING(self); - - count = countchar(self_s, self_len, from_c, maxcount); - if (count == 0) { - return return_self(self); - } - - result_len = self_len - count; /* from_len == 1 */ - assert(result_len>=0); - - if ( (result = (PyBytesObject *) - PyBytes_FromStringAndSize(NULL, result_len)) == NULL) - return NULL; - result_s = PyBytes_AS_STRING(result); - - start = self_s; - end = self_s + self_len; - while (count-- > 0) { - next = findchar(start, end-start, from_c); - if (next == NULL) - break; - Py_MEMCPY(result_s, start, next-start); - result_s += (next-start); - start = next+1; - } - Py_MEMCPY(result_s, start, end-start); + char *self_s, *result_s; + char *start, *next, *end; + Py_ssize_t self_len, result_len; + Py_ssize_t count; + PyBytesObject *result; + + self_len = PyBytes_GET_SIZE(self); + self_s = PyBytes_AS_STRING(self); + + count = countchar(self_s, self_len, from_c, maxcount); + if (count == 0) { + return return_self(self); + } + + result_len = self_len - count; /* from_len == 1 */ + assert(result_len>=0); - return result; + if ( (result = (PyBytesObject *) + PyBytes_FromStringAndSize(NULL, result_len)) == NULL) + return NULL; + result_s = PyBytes_AS_STRING(result); + + start = self_s; + end = self_s + self_len; + while (count-- > 0) { + next = findchar(start, end-start, from_c); + if (next == NULL) + break; + Py_MEMCPY(result_s, start, next-start); + result_s += (next-start); + start = next+1; + } + Py_MEMCPY(result_s, start, end-start); + + return result; } /* len(self)>=1, len(from)>=2, to="", maxcount>=1 */ Py_LOCAL(PyBytesObject *) replace_delete_substring(PyBytesObject *self, - const char *from_s, Py_ssize_t from_len, - Py_ssize_t maxcount) { - char *self_s, *result_s; - char *start, *next, *end; - Py_ssize_t self_len, result_len; - Py_ssize_t count, offset; - PyBytesObject *result; - - self_len = PyBytes_GET_SIZE(self); - self_s = PyBytes_AS_STRING(self); - - count = stringlib_count(self_s, self_len, - from_s, from_len, - maxcount); - - if (count == 0) { - /* no matches */ - return return_self(self); - } - - result_len = self_len - (count * from_len); - assert (result_len>=0); - - if ( (result = (PyBytesObject *) - PyBytes_FromStringAndSize(NULL, result_len)) == NULL ) - return NULL; - - result_s = PyBytes_AS_STRING(result); - - start = self_s; - end = self_s + self_len; - while (count-- > 0) { - offset = stringlib_find(start, end-start, - from_s, from_len, - 0); - if (offset == -1) - break; - next = start + offset; - - Py_MEMCPY(result_s, start, next-start); - - result_s += (next-start); - start = next+from_len; - } - Py_MEMCPY(result_s, start, end-start); - return result; + const char *from_s, Py_ssize_t from_len, + Py_ssize_t maxcount) { + char *self_s, *result_s; + char *start, *next, *end; + Py_ssize_t self_len, result_len; + Py_ssize_t count, offset; + PyBytesObject *result; + + self_len = PyBytes_GET_SIZE(self); + self_s = PyBytes_AS_STRING(self); + + count = stringlib_count(self_s, self_len, + from_s, from_len, + maxcount); + + if (count == 0) { + /* no matches */ + return return_self(self); + } + + result_len = self_len - (count * from_len); + assert (result_len>=0); + + if ( (result = (PyBytesObject *) + PyBytes_FromStringAndSize(NULL, result_len)) == NULL ) + return NULL; + + result_s = PyBytes_AS_STRING(result); + + start = self_s; + end = self_s + self_len; + while (count-- > 0) { + offset = stringlib_find(start, end-start, + from_s, from_len, + 0); + if (offset == -1) + break; + next = start + offset; + + Py_MEMCPY(result_s, start, next-start); + + result_s += (next-start); + start = next+from_len; + } + Py_MEMCPY(result_s, start, end-start); + return result; } /* len(self)>=1, len(from)==len(to)==1, maxcount>=1 */ Py_LOCAL(PyBytesObject *) replace_single_character_in_place(PyBytesObject *self, - char from_c, char to_c, - Py_ssize_t maxcount) + char from_c, char to_c, + Py_ssize_t maxcount) { - char *self_s, *result_s, *start, *end, *next; - Py_ssize_t self_len; - PyBytesObject *result; - - /* The result string will be the same size */ - self_s = PyBytes_AS_STRING(self); - self_len = PyBytes_GET_SIZE(self); - - next = findchar(self_s, self_len, from_c); - - if (next == NULL) { - /* No matches; return the original string */ - return return_self(self); - } - - /* Need to make a new string */ - result = (PyBytesObject *) PyBytes_FromStringAndSize(NULL, self_len); - if (result == NULL) - return NULL; - result_s = PyBytes_AS_STRING(result); - Py_MEMCPY(result_s, self_s, self_len); - - /* change everything in-place, starting with this one */ - start = result_s + (next-self_s); - *start = to_c; - start++; - end = result_s + self_len; - - while (--maxcount > 0) { - next = findchar(start, end-start, from_c); - if (next == NULL) - break; - *next = to_c; - start = next+1; - } + char *self_s, *result_s, *start, *end, *next; + Py_ssize_t self_len; + PyBytesObject *result; + + /* The result string will be the same size */ + self_s = PyBytes_AS_STRING(self); + self_len = PyBytes_GET_SIZE(self); + + next = findchar(self_s, self_len, from_c); + + if (next == NULL) { + /* No matches; return the original string */ + return return_self(self); + } - return result; + /* Need to make a new string */ + result = (PyBytesObject *) PyBytes_FromStringAndSize(NULL, self_len); + if (result == NULL) + return NULL; + result_s = PyBytes_AS_STRING(result); + Py_MEMCPY(result_s, self_s, self_len); + + /* change everything in-place, starting with this one */ + start = result_s + (next-self_s); + *start = to_c; + start++; + end = result_s + self_len; + + while (--maxcount > 0) { + next = findchar(start, end-start, from_c); + if (next == NULL) + break; + *next = to_c; + start = next+1; + } + + return result; } /* len(self)>=1, len(from)==len(to)>=2, maxcount>=1 */ Py_LOCAL(PyBytesObject *) replace_substring_in_place(PyBytesObject *self, - const char *from_s, Py_ssize_t from_len, - const char *to_s, Py_ssize_t to_len, - Py_ssize_t maxcount) -{ - char *result_s, *start, *end; - char *self_s; - Py_ssize_t self_len, offset; - PyBytesObject *result; - - /* The result string will be the same size */ - - self_s = PyBytes_AS_STRING(self); - self_len = PyBytes_GET_SIZE(self); - - offset = stringlib_find(self_s, self_len, - from_s, from_len, - 0); - if (offset == -1) { - /* No matches; return the original string */ - return return_self(self); - } - - /* Need to make a new string */ - result = (PyBytesObject *) PyBytes_FromStringAndSize(NULL, self_len); - if (result == NULL) - return NULL; - result_s = PyBytes_AS_STRING(result); - Py_MEMCPY(result_s, self_s, self_len); - - /* change everything in-place, starting with this one */ - start = result_s + offset; - Py_MEMCPY(start, to_s, from_len); - start += from_len; - end = result_s + self_len; - - while ( --maxcount > 0) { - offset = stringlib_find(start, end-start, - from_s, from_len, - 0); - if (offset==-1) - break; - Py_MEMCPY(start+offset, to_s, from_len); - start += offset+from_len; - } + const char *from_s, Py_ssize_t from_len, + const char *to_s, Py_ssize_t to_len, + Py_ssize_t maxcount) +{ + char *result_s, *start, *end; + char *self_s; + Py_ssize_t self_len, offset; + PyBytesObject *result; + + /* The result string will be the same size */ + + self_s = PyBytes_AS_STRING(self); + self_len = PyBytes_GET_SIZE(self); + + offset = stringlib_find(self_s, self_len, + from_s, from_len, + 0); + if (offset == -1) { + /* No matches; return the original string */ + return return_self(self); + } - return result; + /* Need to make a new string */ + result = (PyBytesObject *) PyBytes_FromStringAndSize(NULL, self_len); + if (result == NULL) + return NULL; + result_s = PyBytes_AS_STRING(result); + Py_MEMCPY(result_s, self_s, self_len); + + /* change everything in-place, starting with this one */ + start = result_s + offset; + Py_MEMCPY(start, to_s, from_len); + start += from_len; + end = result_s + self_len; + + while ( --maxcount > 0) { + offset = stringlib_find(start, end-start, + from_s, from_len, + 0); + if (offset==-1) + break; + Py_MEMCPY(start+offset, to_s, from_len); + start += offset+from_len; + } + + return result; } /* len(self)>=1, len(from)==1, len(to)>=2, maxcount>=1 */ Py_LOCAL(PyBytesObject *) replace_single_character(PyBytesObject *self, - char from_c, - const char *to_s, Py_ssize_t to_len, - Py_ssize_t maxcount) -{ - char *self_s, *result_s; - char *start, *next, *end; - Py_ssize_t self_len, result_len; - Py_ssize_t count, product; - PyBytesObject *result; - - self_s = PyBytes_AS_STRING(self); - self_len = PyBytes_GET_SIZE(self); - - count = countchar(self_s, self_len, from_c, maxcount); - if (count == 0) { - /* no matches, return unchanged */ - return return_self(self); - } - - /* use the difference between current and new, hence the "-1" */ - /* result_len = self_len + count * (to_len-1) */ - product = count * (to_len-1); - if (product / (to_len-1) != count) { - PyErr_SetString(PyExc_OverflowError, - "replacement bytes are too long"); - return NULL; - } - result_len = self_len + product; - if (result_len < 0) { - PyErr_SetString(PyExc_OverflowError, - "replacment bytes are too long"); - return NULL; - } - - if ( (result = (PyBytesObject *) - PyBytes_FromStringAndSize(NULL, result_len)) == NULL) - return NULL; - result_s = PyBytes_AS_STRING(result); - - start = self_s; - end = self_s + self_len; - while (count-- > 0) { - next = findchar(start, end-start, from_c); - if (next == NULL) - break; - - if (next == start) { - /* replace with the 'to' */ - Py_MEMCPY(result_s, to_s, to_len); - result_s += to_len; - start += 1; - } else { - /* copy the unchanged old then the 'to' */ - Py_MEMCPY(result_s, start, next-start); - result_s += (next-start); - Py_MEMCPY(result_s, to_s, to_len); - result_s += to_len; - start = next+1; - } - } - /* Copy the remainder of the remaining string */ - Py_MEMCPY(result_s, start, end-start); + char from_c, + const char *to_s, Py_ssize_t to_len, + Py_ssize_t maxcount) +{ + char *self_s, *result_s; + char *start, *next, *end; + Py_ssize_t self_len, result_len; + Py_ssize_t count, product; + PyBytesObject *result; + + self_s = PyBytes_AS_STRING(self); + self_len = PyBytes_GET_SIZE(self); + + count = countchar(self_s, self_len, from_c, maxcount); + if (count == 0) { + /* no matches, return unchanged */ + return return_self(self); + } + + /* use the difference between current and new, hence the "-1" */ + /* result_len = self_len + count * (to_len-1) */ + product = count * (to_len-1); + if (product / (to_len-1) != count) { + PyErr_SetString(PyExc_OverflowError, + "replacement bytes are too long"); + return NULL; + } + result_len = self_len + product; + if (result_len < 0) { + PyErr_SetString(PyExc_OverflowError, + "replacment bytes are too long"); + return NULL; + } - return result; + if ( (result = (PyBytesObject *) + PyBytes_FromStringAndSize(NULL, result_len)) == NULL) + return NULL; + result_s = PyBytes_AS_STRING(result); + + start = self_s; + end = self_s + self_len; + while (count-- > 0) { + next = findchar(start, end-start, from_c); + if (next == NULL) + break; + + if (next == start) { + /* replace with the 'to' */ + Py_MEMCPY(result_s, to_s, to_len); + result_s += to_len; + start += 1; + } else { + /* copy the unchanged old then the 'to' */ + Py_MEMCPY(result_s, start, next-start); + result_s += (next-start); + Py_MEMCPY(result_s, to_s, to_len); + result_s += to_len; + start = next+1; + } + } + /* Copy the remainder of the remaining string */ + Py_MEMCPY(result_s, start, end-start); + + return result; } /* len(self)>=1, len(from)>=2, len(to)>=2, maxcount>=1 */ Py_LOCAL(PyBytesObject *) replace_substring(PyBytesObject *self, - const char *from_s, Py_ssize_t from_len, - const char *to_s, Py_ssize_t to_len, - Py_ssize_t maxcount) { - char *self_s, *result_s; - char *start, *next, *end; - Py_ssize_t self_len, result_len; - Py_ssize_t count, offset, product; - PyBytesObject *result; - - self_s = PyBytes_AS_STRING(self); - self_len = PyBytes_GET_SIZE(self); - - count = stringlib_count(self_s, self_len, - from_s, from_len, - maxcount); - - if (count == 0) { - /* no matches, return unchanged */ - return return_self(self); - } - - /* Check for overflow */ - /* result_len = self_len + count * (to_len-from_len) */ - product = count * (to_len-from_len); - if (product / (to_len-from_len) != count) { - PyErr_SetString(PyExc_OverflowError, - "replacement bytes are too long"); - return NULL; - } - result_len = self_len + product; - if (result_len < 0) { - PyErr_SetString(PyExc_OverflowError, - "replacement bytes are too long"); - return NULL; - } - - if ( (result = (PyBytesObject *) - PyBytes_FromStringAndSize(NULL, result_len)) == NULL) - return NULL; - result_s = PyBytes_AS_STRING(result); - - start = self_s; - end = self_s + self_len; - while (count-- > 0) { - offset = stringlib_find(start, end-start, - from_s, from_len, - 0); - if (offset == -1) - break; - next = start+offset; - if (next == start) { - /* replace with the 'to' */ - Py_MEMCPY(result_s, to_s, to_len); - result_s += to_len; - start += from_len; - } else { - /* copy the unchanged old then the 'to' */ - Py_MEMCPY(result_s, start, next-start); - result_s += (next-start); - Py_MEMCPY(result_s, to_s, to_len); - result_s += to_len; - start = next+from_len; - } - } - /* Copy the remainder of the remaining string */ - Py_MEMCPY(result_s, start, end-start); + const char *from_s, Py_ssize_t from_len, + const char *to_s, Py_ssize_t to_len, + Py_ssize_t maxcount) { + char *self_s, *result_s; + char *start, *next, *end; + Py_ssize_t self_len, result_len; + Py_ssize_t count, offset, product; + PyBytesObject *result; + + self_s = PyBytes_AS_STRING(self); + self_len = PyBytes_GET_SIZE(self); + + count = stringlib_count(self_s, self_len, + from_s, from_len, + maxcount); + + if (count == 0) { + /* no matches, return unchanged */ + return return_self(self); + } + + /* Check for overflow */ + /* result_len = self_len + count * (to_len-from_len) */ + product = count * (to_len-from_len); + if (product / (to_len-from_len) != count) { + PyErr_SetString(PyExc_OverflowError, + "replacement bytes are too long"); + return NULL; + } + result_len = self_len + product; + if (result_len < 0) { + PyErr_SetString(PyExc_OverflowError, + "replacement bytes are too long"); + return NULL; + } + + if ( (result = (PyBytesObject *) + PyBytes_FromStringAndSize(NULL, result_len)) == NULL) + return NULL; + result_s = PyBytes_AS_STRING(result); + + start = self_s; + end = self_s + self_len; + while (count-- > 0) { + offset = stringlib_find(start, end-start, + from_s, from_len, + 0); + if (offset == -1) + break; + next = start+offset; + if (next == start) { + /* replace with the 'to' */ + Py_MEMCPY(result_s, to_s, to_len); + result_s += to_len; + start += from_len; + } else { + /* copy the unchanged old then the 'to' */ + Py_MEMCPY(result_s, start, next-start); + result_s += (next-start); + Py_MEMCPY(result_s, to_s, to_len); + result_s += to_len; + start = next+from_len; + } + } + /* Copy the remainder of the remaining string */ + Py_MEMCPY(result_s, start, end-start); - return result; + return result; } Py_LOCAL(PyBytesObject *) replace(PyBytesObject *self, - const char *from_s, Py_ssize_t from_len, - const char *to_s, Py_ssize_t to_len, - Py_ssize_t maxcount) -{ - if (maxcount < 0) { - maxcount = PY_SSIZE_T_MAX; - } else if (maxcount == 0 || PyBytes_GET_SIZE(self) == 0) { - /* nothing to do; return the original string */ - return return_self(self); - } - - if (maxcount == 0 || - (from_len == 0 && to_len == 0)) { - /* nothing to do; return the original string */ - return return_self(self); - } - - /* Handle zero-length special cases */ - - if (from_len == 0) { - /* insert the 'to' string everywhere. */ - /* >>> "Python".replace("", ".") */ - /* '.P.y.t.h.o.n.' */ - return replace_interleave(self, to_s, to_len, maxcount); - } - - /* Except for "".replace("", "A") == "A" there is no way beyond this */ - /* point for an empty self string to generate a non-empty string */ - /* Special case so the remaining code always gets a non-empty string */ - if (PyBytes_GET_SIZE(self) == 0) { - return return_self(self); - } - - if (to_len == 0) { - /* delete all occurrences of 'from' string */ - if (from_len == 1) { - return replace_delete_single_character( - self, from_s[0], maxcount); - } else { - return replace_delete_substring(self, from_s, - from_len, maxcount); - } - } - - /* Handle special case where both strings have the same length */ - - if (from_len == to_len) { - if (from_len == 1) { - return replace_single_character_in_place( - self, - from_s[0], - to_s[0], - maxcount); - } else { - return replace_substring_in_place( - self, from_s, from_len, to_s, to_len, - maxcount); - } - } - - /* Otherwise use the more generic algorithms */ - if (from_len == 1) { - return replace_single_character(self, from_s[0], - to_s, to_len, maxcount); - } else { - /* len('from')>=2, len('to')>=1 */ - return replace_substring(self, from_s, from_len, to_s, to_len, - maxcount); - } + const char *from_s, Py_ssize_t from_len, + const char *to_s, Py_ssize_t to_len, + Py_ssize_t maxcount) +{ + if (maxcount < 0) { + maxcount = PY_SSIZE_T_MAX; + } else if (maxcount == 0 || PyBytes_GET_SIZE(self) == 0) { + /* nothing to do; return the original string */ + return return_self(self); + } + + if (maxcount == 0 || + (from_len == 0 && to_len == 0)) { + /* nothing to do; return the original string */ + return return_self(self); + } + + /* Handle zero-length special cases */ + + if (from_len == 0) { + /* insert the 'to' string everywhere. */ + /* >>> "Python".replace("", ".") */ + /* '.P.y.t.h.o.n.' */ + return replace_interleave(self, to_s, to_len, maxcount); + } + + /* Except for "".replace("", "A") == "A" there is no way beyond this */ + /* point for an empty self string to generate a non-empty string */ + /* Special case so the remaining code always gets a non-empty string */ + if (PyBytes_GET_SIZE(self) == 0) { + return return_self(self); + } + + if (to_len == 0) { + /* delete all occurrences of 'from' string */ + if (from_len == 1) { + return replace_delete_single_character( + self, from_s[0], maxcount); + } else { + return replace_delete_substring(self, from_s, + from_len, maxcount); + } + } + + /* Handle special case where both strings have the same length */ + + if (from_len == to_len) { + if (from_len == 1) { + return replace_single_character_in_place( + self, + from_s[0], + to_s[0], + maxcount); + } else { + return replace_substring_in_place( + self, from_s, from_len, to_s, to_len, + maxcount); + } + } + + /* Otherwise use the more generic algorithms */ + if (from_len == 1) { + return replace_single_character(self, from_s[0], + to_s, to_len, maxcount); + } else { + /* len('from')>=2, len('to')>=1 */ + return replace_substring(self, from_s, from_len, to_s, to_len, + maxcount); + } } PyDoc_STRVAR(replace__doc__, @@ -2155,31 +2155,31 @@ static PyObject * bytes_replace(PyBytesObject *self, PyObject *args) { - Py_ssize_t count = -1; - PyObject *from, *to; - const char *from_s, *to_s; - Py_ssize_t from_len, to_len; - - if (!PyArg_ParseTuple(args, "OO|n:replace", &from, &to, &count)) - return NULL; - - if (PyBytes_Check(from)) { - from_s = PyBytes_AS_STRING(from); - from_len = PyBytes_GET_SIZE(from); - } - else if (PyObject_AsCharBuffer(from, &from_s, &from_len)) - return NULL; - - if (PyBytes_Check(to)) { - to_s = PyBytes_AS_STRING(to); - to_len = PyBytes_GET_SIZE(to); - } - else if (PyObject_AsCharBuffer(to, &to_s, &to_len)) - return NULL; - - return (PyObject *)replace((PyBytesObject *) self, - from_s, from_len, - to_s, to_len, count); + Py_ssize_t count = -1; + PyObject *from, *to; + const char *from_s, *to_s; + Py_ssize_t from_len, to_len; + + if (!PyArg_ParseTuple(args, "OO|n:replace", &from, &to, &count)) + return NULL; + + if (PyBytes_Check(from)) { + from_s = PyBytes_AS_STRING(from); + from_len = PyBytes_GET_SIZE(from); + } + else if (PyObject_AsCharBuffer(from, &from_s, &from_len)) + return NULL; + + if (PyBytes_Check(to)) { + to_s = PyBytes_AS_STRING(to); + to_len = PyBytes_GET_SIZE(to); + } + else if (PyObject_AsCharBuffer(to, &to_s, &to_len)) + return NULL; + + return (PyObject *)replace((PyBytesObject *) self, + from_s, from_len, + to_s, to_len, count); } /** End DALKE **/ @@ -2190,38 +2190,38 @@ */ Py_LOCAL(int) _bytes_tailmatch(PyBytesObject *self, PyObject *substr, Py_ssize_t start, - Py_ssize_t end, int direction) + Py_ssize_t end, int direction) { - Py_ssize_t len = PyBytes_GET_SIZE(self); - Py_ssize_t slen; - const char* sub; - const char* str; - - if (PyBytes_Check(substr)) { - sub = PyBytes_AS_STRING(substr); - slen = PyBytes_GET_SIZE(substr); - } - else if (PyObject_AsCharBuffer(substr, &sub, &slen)) - return -1; - str = PyBytes_AS_STRING(self); - - ADJUST_INDICES(start, end, len); - - if (direction < 0) { - /* startswith */ - if (start+slen > len) - return 0; - } else { - /* endswith */ - if (end-start < slen || start > len) - return 0; - - if (end-slen > start) - start = end - slen; - } - if (end-start >= slen) - return ! memcmp(str+start, sub, slen); - return 0; + Py_ssize_t len = PyBytes_GET_SIZE(self); + Py_ssize_t slen; + const char* sub; + const char* str; + + if (PyBytes_Check(substr)) { + sub = PyBytes_AS_STRING(substr); + slen = PyBytes_GET_SIZE(substr); + } + else if (PyObject_AsCharBuffer(substr, &sub, &slen)) + return -1; + str = PyBytes_AS_STRING(self); + + ADJUST_INDICES(start, end, len); + + if (direction < 0) { + /* startswith */ + if (start+slen > len) + return 0; + } else { + /* endswith */ + if (end-start < slen || start > len) + return 0; + + if (end-slen > start) + start = end - slen; + } + if (end-start >= slen) + return ! memcmp(str+start, sub, slen); + return 0; } @@ -2236,33 +2236,33 @@ static PyObject * bytes_startswith(PyBytesObject *self, PyObject *args) { - Py_ssize_t start = 0; - Py_ssize_t end = PY_SSIZE_T_MAX; - PyObject *subobj; - int result; - - if (!PyArg_ParseTuple(args, "O|O&O&:startswith", &subobj, - _PyEval_SliceIndex, &start, _PyEval_SliceIndex, &end)) - return NULL; - if (PyTuple_Check(subobj)) { - Py_ssize_t i; - for (i = 0; i < PyTuple_GET_SIZE(subobj); i++) { - result = _bytes_tailmatch(self, - PyTuple_GET_ITEM(subobj, i), - start, end, -1); - if (result == -1) - return NULL; - else if (result) { - Py_RETURN_TRUE; - } - } - Py_RETURN_FALSE; - } - result = _bytes_tailmatch(self, subobj, start, end, -1); - if (result == -1) - return NULL; - else - return PyBool_FromLong(result); + Py_ssize_t start = 0; + Py_ssize_t end = PY_SSIZE_T_MAX; + PyObject *subobj; + int result; + + if (!PyArg_ParseTuple(args, "O|O&O&:startswith", &subobj, + _PyEval_SliceIndex, &start, _PyEval_SliceIndex, &end)) + return NULL; + if (PyTuple_Check(subobj)) { + Py_ssize_t i; + for (i = 0; i < PyTuple_GET_SIZE(subobj); i++) { + result = _bytes_tailmatch(self, + PyTuple_GET_ITEM(subobj, i), + start, end, -1); + if (result == -1) + return NULL; + else if (result) { + Py_RETURN_TRUE; + } + } + Py_RETURN_FALSE; + } + result = _bytes_tailmatch(self, subobj, start, end, -1); + if (result == -1) + return NULL; + else + return PyBool_FromLong(result); } @@ -2277,33 +2277,33 @@ static PyObject * bytes_endswith(PyBytesObject *self, PyObject *args) { - Py_ssize_t start = 0; - Py_ssize_t end = PY_SSIZE_T_MAX; - PyObject *subobj; - int result; - - if (!PyArg_ParseTuple(args, "O|O&O&:endswith", &subobj, - _PyEval_SliceIndex, &start, _PyEval_SliceIndex, &end)) - return NULL; - if (PyTuple_Check(subobj)) { - Py_ssize_t i; - for (i = 0; i < PyTuple_GET_SIZE(subobj); i++) { - result = _bytes_tailmatch(self, - PyTuple_GET_ITEM(subobj, i), - start, end, +1); - if (result == -1) - return NULL; - else if (result) { - Py_RETURN_TRUE; - } - } - Py_RETURN_FALSE; - } - result = _bytes_tailmatch(self, subobj, start, end, +1); - if (result == -1) - return NULL; - else - return PyBool_FromLong(result); + Py_ssize_t start = 0; + Py_ssize_t end = PY_SSIZE_T_MAX; + PyObject *subobj; + int result; + + if (!PyArg_ParseTuple(args, "O|O&O&:endswith", &subobj, + _PyEval_SliceIndex, &start, _PyEval_SliceIndex, &end)) + return NULL; + if (PyTuple_Check(subobj)) { + Py_ssize_t i; + for (i = 0; i < PyTuple_GET_SIZE(subobj); i++) { + result = _bytes_tailmatch(self, + PyTuple_GET_ITEM(subobj, i), + start, end, +1); + if (result == -1) + return NULL; + else if (result) { + Py_RETURN_TRUE; + } + } + Py_RETURN_FALSE; + } + result = _bytes_tailmatch(self, subobj, start, end, +1); + if (result == -1) + return NULL; + else + return PyBool_FromLong(result); } @@ -2320,15 +2320,15 @@ static PyObject * bytes_decode(PyObject *self, PyObject *args, PyObject *kwargs) { - const char *encoding = NULL; - const char *errors = NULL; - static char *kwlist[] = {"encoding", "errors", 0}; - - if (!PyArg_ParseTupleAndKeywords(args, kwargs, "|ss:decode", kwlist, &encoding, &errors)) - return NULL; - if (encoding == NULL) - encoding = PyUnicode_GetDefaultEncoding(); - return PyUnicode_FromEncodedObject(self, encoding, errors); + const char *encoding = NULL; + const char *errors = NULL; + static char *kwlist[] = {"encoding", "errors", 0}; + + if (!PyArg_ParseTupleAndKeywords(args, kwargs, "|ss:decode", kwlist, &encoding, &errors)) + return NULL; + if (encoding == NULL) + encoding = PyUnicode_GetDefaultEncoding(); + return PyUnicode_FromEncodedObject(self, encoding, errors); } @@ -2345,12 +2345,12 @@ int keepends = 0; if (!PyArg_ParseTuple(args, "|i:splitlines", &keepends)) - return NULL; + return NULL; return stringlib_splitlines( - (PyObject*) self, PyBytes_AS_STRING(self), - PyBytes_GET_SIZE(self), keepends - ); + (PyObject*) self, PyBytes_AS_STRING(self), + PyBytes_GET_SIZE(self), keepends + ); } @@ -2364,61 +2364,61 @@ static int hex_digit_to_int(Py_UNICODE c) { - if (c >= 128) - return -1; - if (ISDIGIT(c)) - return c - '0'; - else { - if (ISUPPER(c)) - c = TOLOWER(c); - if (c >= 'a' && c <= 'f') - return c - 'a' + 10; - } - return -1; + if (c >= 128) + return -1; + if (ISDIGIT(c)) + return c - '0'; + else { + if (ISUPPER(c)) + c = TOLOWER(c); + if (c >= 'a' && c <= 'f') + return c - 'a' + 10; + } + return -1; } static PyObject * bytes_fromhex(PyObject *cls, PyObject *args) { - PyObject *newstring, *hexobj; - char *buf; - Py_UNICODE *hex; - Py_ssize_t hexlen, byteslen, i, j; - int top, bot; - - if (!PyArg_ParseTuple(args, "U:fromhex", &hexobj)) - return NULL; - assert(PyUnicode_Check(hexobj)); - hexlen = PyUnicode_GET_SIZE(hexobj); - hex = PyUnicode_AS_UNICODE(hexobj); - byteslen = hexlen/2; /* This overestimates if there are spaces */ - newstring = PyBytes_FromStringAndSize(NULL, byteslen); - if (!newstring) - return NULL; - buf = PyBytes_AS_STRING(newstring); - for (i = j = 0; i < hexlen; i += 2) { - /* skip over spaces in the input */ - while (hex[i] == ' ') - i++; - if (i >= hexlen) - break; - top = hex_digit_to_int(hex[i]); - bot = hex_digit_to_int(hex[i+1]); - if (top == -1 || bot == -1) { - PyErr_Format(PyExc_ValueError, - "non-hexadecimal number found in " - "fromhex() arg at position %zd", i); - goto error; - } - buf[j++] = (top << 4) + bot; - } - if (j != byteslen && _PyBytes_Resize(&newstring, j) < 0) - goto error; - return newstring; + PyObject *newstring, *hexobj; + char *buf; + Py_UNICODE *hex; + Py_ssize_t hexlen, byteslen, i, j; + int top, bot; + + if (!PyArg_ParseTuple(args, "U:fromhex", &hexobj)) + return NULL; + assert(PyUnicode_Check(hexobj)); + hexlen = PyUnicode_GET_SIZE(hexobj); + hex = PyUnicode_AS_UNICODE(hexobj); + byteslen = hexlen/2; /* This overestimates if there are spaces */ + newstring = PyBytes_FromStringAndSize(NULL, byteslen); + if (!newstring) + return NULL; + buf = PyBytes_AS_STRING(newstring); + for (i = j = 0; i < hexlen; i += 2) { + /* skip over spaces in the input */ + while (hex[i] == ' ') + i++; + if (i >= hexlen) + break; + top = hex_digit_to_int(hex[i]); + bot = hex_digit_to_int(hex[i+1]); + if (top == -1 || bot == -1) { + PyErr_Format(PyExc_ValueError, + "non-hexadecimal number found in " + "fromhex() arg at position %zd", i); + goto error; + } + buf[j++] = (top << 4) + bot; + } + if (j != byteslen && _PyBytes_Resize(&newstring, j) < 0) + goto error; + return newstring; error: - Py_XDECREF(newstring); - return NULL; + Py_XDECREF(newstring); + return NULL; } PyDoc_STRVAR(sizeof__doc__, @@ -2427,80 +2427,80 @@ static PyObject * bytes_sizeof(PyBytesObject *v) { - Py_ssize_t res; - res = PyBytesObject_SIZE + Py_SIZE(v) * Py_TYPE(v)->tp_itemsize; - return PyLong_FromSsize_t(res); + Py_ssize_t res; + res = PyBytesObject_SIZE + Py_SIZE(v) * Py_TYPE(v)->tp_itemsize; + return PyLong_FromSsize_t(res); } static PyObject * bytes_getnewargs(PyBytesObject *v) { - return Py_BuildValue("(y#)", v->ob_sval, Py_SIZE(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, center__doc__}, - {"count", (PyCFunction)bytes_count, METH_VARARGS, count__doc__}, - {"decode", (PyCFunction)bytes_decode, METH_VARARGS | METH_KEYWORDS, decode__doc__}, - {"endswith", (PyCFunction)bytes_endswith, METH_VARARGS, - endswith__doc__}, - {"expandtabs", (PyCFunction)stringlib_expandtabs, METH_VARARGS, - expandtabs__doc__}, - {"find", (PyCFunction)bytes_find, METH_VARARGS, find__doc__}, - {"fromhex", (PyCFunction)bytes_fromhex, METH_VARARGS|METH_CLASS, - fromhex_doc}, - {"index", (PyCFunction)bytes_index, METH_VARARGS, 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__}, - {"join", (PyCFunction)bytes_join, METH_O, join__doc__}, - {"ljust", (PyCFunction)stringlib_ljust, METH_VARARGS, ljust__doc__}, - {"lower", (PyCFunction)stringlib_lower, METH_NOARGS, _Py_lower__doc__}, - {"lstrip", (PyCFunction)bytes_lstrip, METH_VARARGS, lstrip__doc__}, - {"maketrans", (PyCFunction)bytes_maketrans, METH_VARARGS|METH_STATIC, - _Py_maketrans__doc__}, - {"partition", (PyCFunction)bytes_partition, METH_O, partition__doc__}, - {"replace", (PyCFunction)bytes_replace, METH_VARARGS, replace__doc__}, - {"rfind", (PyCFunction)bytes_rfind, METH_VARARGS, rfind__doc__}, - {"rindex", (PyCFunction)bytes_rindex, METH_VARARGS, rindex__doc__}, - {"rjust", (PyCFunction)stringlib_rjust, METH_VARARGS, rjust__doc__}, - {"rpartition", (PyCFunction)bytes_rpartition, METH_O, - rpartition__doc__}, - {"rsplit", (PyCFunction)bytes_rsplit, METH_VARARGS, rsplit__doc__}, - {"rstrip", (PyCFunction)bytes_rstrip, METH_VARARGS, rstrip__doc__}, - {"split", (PyCFunction)bytes_split, METH_VARARGS, split__doc__}, - {"splitlines", (PyCFunction)bytes_splitlines, METH_VARARGS, - splitlines__doc__}, - {"startswith", (PyCFunction)bytes_startswith, METH_VARARGS, - startswith__doc__}, - {"strip", (PyCFunction)bytes_strip, METH_VARARGS, strip__doc__}, - {"swapcase", (PyCFunction)stringlib_swapcase, METH_NOARGS, - _Py_swapcase__doc__}, - {"title", (PyCFunction)stringlib_title, METH_NOARGS, _Py_title__doc__}, - {"translate", (PyCFunction)bytes_translate, METH_VARARGS, - translate__doc__}, - {"upper", (PyCFunction)stringlib_upper, METH_NOARGS, _Py_upper__doc__}, - {"zfill", (PyCFunction)stringlib_zfill, METH_VARARGS, zfill__doc__}, - {"__sizeof__", (PyCFunction)bytes_sizeof, METH_NOARGS, - sizeof__doc__}, - {NULL, NULL} /* sentinel */ + {"__getnewargs__", (PyCFunction)bytes_getnewargs, METH_NOARGS}, + {"capitalize", (PyCFunction)stringlib_capitalize, METH_NOARGS, + _Py_capitalize__doc__}, + {"center", (PyCFunction)stringlib_center, METH_VARARGS, center__doc__}, + {"count", (PyCFunction)bytes_count, METH_VARARGS, count__doc__}, + {"decode", (PyCFunction)bytes_decode, METH_VARARGS | METH_KEYWORDS, decode__doc__}, + {"endswith", (PyCFunction)bytes_endswith, METH_VARARGS, + endswith__doc__}, + {"expandtabs", (PyCFunction)stringlib_expandtabs, METH_VARARGS, + expandtabs__doc__}, + {"find", (PyCFunction)bytes_find, METH_VARARGS, find__doc__}, + {"fromhex", (PyCFunction)bytes_fromhex, METH_VARARGS|METH_CLASS, + fromhex_doc}, + {"index", (PyCFunction)bytes_index, METH_VARARGS, 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__}, + {"join", (PyCFunction)bytes_join, METH_O, join__doc__}, + {"ljust", (PyCFunction)stringlib_ljust, METH_VARARGS, ljust__doc__}, + {"lower", (PyCFunction)stringlib_lower, METH_NOARGS, _Py_lower__doc__}, + {"lstrip", (PyCFunction)bytes_lstrip, METH_VARARGS, lstrip__doc__}, + {"maketrans", (PyCFunction)bytes_maketrans, METH_VARARGS|METH_STATIC, + _Py_maketrans__doc__}, + {"partition", (PyCFunction)bytes_partition, METH_O, partition__doc__}, + {"replace", (PyCFunction)bytes_replace, METH_VARARGS, replace__doc__}, + {"rfind", (PyCFunction)bytes_rfind, METH_VARARGS, rfind__doc__}, + {"rindex", (PyCFunction)bytes_rindex, METH_VARARGS, rindex__doc__}, + {"rjust", (PyCFunction)stringlib_rjust, METH_VARARGS, rjust__doc__}, + {"rpartition", (PyCFunction)bytes_rpartition, METH_O, + rpartition__doc__}, + {"rsplit", (PyCFunction)bytes_rsplit, METH_VARARGS, rsplit__doc__}, + {"rstrip", (PyCFunction)bytes_rstrip, METH_VARARGS, rstrip__doc__}, + {"split", (PyCFunction)bytes_split, METH_VARARGS, split__doc__}, + {"splitlines", (PyCFunction)bytes_splitlines, METH_VARARGS, + splitlines__doc__}, + {"startswith", (PyCFunction)bytes_startswith, METH_VARARGS, + startswith__doc__}, + {"strip", (PyCFunction)bytes_strip, METH_VARARGS, strip__doc__}, + {"swapcase", (PyCFunction)stringlib_swapcase, METH_NOARGS, + _Py_swapcase__doc__}, + {"title", (PyCFunction)stringlib_title, METH_NOARGS, _Py_title__doc__}, + {"translate", (PyCFunction)bytes_translate, METH_VARARGS, + translate__doc__}, + {"upper", (PyCFunction)stringlib_upper, METH_NOARGS, _Py_upper__doc__}, + {"zfill", (PyCFunction)stringlib_zfill, METH_VARARGS, zfill__doc__}, + {"__sizeof__", (PyCFunction)bytes_sizeof, METH_NOARGS, + sizeof__doc__}, + {NULL, NULL} /* sentinel */ }; static PyObject * @@ -2509,236 +2509,236 @@ static PyObject * bytes_new(PyTypeObject *type, PyObject *args, PyObject *kwds) { - PyObject *x = NULL; - const char *encoding = NULL; - const char *errors = NULL; - PyObject *new = NULL; - Py_ssize_t size; - static char *kwlist[] = {"source", "encoding", "errors", 0}; - - if (type != &PyBytes_Type) - return str_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_FromString(""); - } - - if (PyUnicode_Check(x)) { - /* Encode via the codec registry */ - if (encoding == NULL) { - PyErr_SetString(PyExc_TypeError, - "string argument without an encoding"); - return NULL; - } - new = PyUnicode_AsEncodedString(x, encoding, errors); - if (new == NULL) - return NULL; - assert(PyBytes_Check(new)); - return new; - } - /* Is it an integer? */ - size = PyNumber_AsSsize_t(x, PyExc_OverflowError); - if (size == -1 && PyErr_Occurred()) { - if (PyErr_ExceptionMatches(PyExc_OverflowError)) - return NULL; - PyErr_Clear(); - } - else if (size < 0) { - PyErr_SetString(PyExc_ValueError, "negative count"); - return NULL; - } - else { - new = PyBytes_FromStringAndSize(NULL, size); - if (new == NULL) { - return NULL; - } - if (size > 0) { - memset(((PyBytesObject*)new)->ob_sval, 0, size); - } - return new; - } - - /* If it's not unicode, there can't be encoding or errors */ - if (encoding != NULL || errors != NULL) { - PyErr_SetString(PyExc_TypeError, - "encoding or errors without a string argument"); - return NULL; - } - return PyObject_Bytes(x); + PyObject *x = NULL; + const char *encoding = NULL; + const char *errors = NULL; + PyObject *new = NULL; + Py_ssize_t size; + static char *kwlist[] = {"source", "encoding", "errors", 0}; + + if (type != &PyBytes_Type) + return str_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_FromString(""); + } + + if (PyUnicode_Check(x)) { + /* Encode via the codec registry */ + if (encoding == NULL) { + PyErr_SetString(PyExc_TypeError, + "string argument without an encoding"); + return NULL; + } + new = PyUnicode_AsEncodedString(x, encoding, errors); + if (new == NULL) + return NULL; + assert(PyBytes_Check(new)); + return new; + } + /* Is it an integer? */ + size = PyNumber_AsSsize_t(x, PyExc_OverflowError); + if (size == -1 && PyErr_Occurred()) { + if (PyErr_ExceptionMatches(PyExc_OverflowError)) + return NULL; + PyErr_Clear(); + } + else if (size < 0) { + PyErr_SetString(PyExc_ValueError, "negative count"); + return NULL; + } + else { + new = PyBytes_FromStringAndSize(NULL, size); + if (new == NULL) { + return NULL; + } + if (size > 0) { + memset(((PyBytesObject*)new)->ob_sval, 0, size); + } + return new; + } + + /* If it's not unicode, there can't be encoding or errors */ + if (encoding != NULL || errors != NULL) { + PyErr_SetString(PyExc_TypeError, + "encoding or errors without a string argument"); + return NULL; + } + return PyObject_Bytes(x); } PyObject * PyBytes_FromObject(PyObject *x) { - PyObject *new, *it; - Py_ssize_t i, size; + PyObject *new, *it; + Py_ssize_t i, size; + + if (x == NULL) { + PyErr_BadInternalCall(); + return NULL; + } + /* Use the modern buffer interface */ + if (PyObject_CheckBuffer(x)) { + Py_buffer view; + if (PyObject_GetBuffer(x, &view, PyBUF_FULL_RO) < 0) + return NULL; + new = PyBytes_FromStringAndSize(NULL, view.len); + if (!new) + goto fail; + /* XXX(brett.cannon): Better way to get to internal buffer? */ + 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; + } + if (PyUnicode_Check(x)) { + PyErr_SetString(PyExc_TypeError, + "cannot convert unicode object to bytes"); + return NULL; + } + + if (PyList_CheckExact(x)) { + new = PyBytes_FromStringAndSize(NULL, Py_SIZE(x)); + if (new == NULL) + return NULL; + for (i = 0; i < Py_SIZE(x); i++) { + Py_ssize_t value = PyNumber_AsSsize_t( + PyList_GET_ITEM(x, i), PyExc_ValueError); + if (value == -1 && PyErr_Occurred()) { + Py_DECREF(new); + return NULL; + } + if (value < 0 || value >= 256) { + PyErr_SetString(PyExc_ValueError, + "bytes must be in range(0, 256)"); + Py_DECREF(new); + return NULL; + } + ((PyBytesObject *)new)->ob_sval[i] = value; + } + return new; + } + if (PyTuple_CheckExact(x)) { + new = PyBytes_FromStringAndSize(NULL, Py_SIZE(x)); + if (new == NULL) + return NULL; + for (i = 0; i < Py_SIZE(x); i++) { + Py_ssize_t value = PyNumber_AsSsize_t( + PyTuple_GET_ITEM(x, i), PyExc_ValueError); + if (value == -1 && PyErr_Occurred()) { + Py_DECREF(new); + return NULL; + } + if (value < 0 || value >= 256) { + PyErr_SetString(PyExc_ValueError, + "bytes must be in range(0, 256)"); + Py_DECREF(new); + return NULL; + } + ((PyBytesObject *)new)->ob_sval[i] = value; + } + return new; + } - if (x == NULL) { - PyErr_BadInternalCall(); - return NULL; - } - /* Use the modern buffer interface */ - if (PyObject_CheckBuffer(x)) { - Py_buffer view; - if (PyObject_GetBuffer(x, &view, PyBUF_FULL_RO) < 0) - return NULL; - new = PyBytes_FromStringAndSize(NULL, view.len); - if (!new) - goto fail; - /* XXX(brett.cannon): Better way to get to internal buffer? */ - 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; - } - if (PyUnicode_Check(x)) { - PyErr_SetString(PyExc_TypeError, - "cannot convert unicode object to bytes"); - return NULL; - } - - if (PyList_CheckExact(x)) { - new = PyBytes_FromStringAndSize(NULL, Py_SIZE(x)); - if (new == NULL) - return NULL; - for (i = 0; i < Py_SIZE(x); i++) { - Py_ssize_t value = PyNumber_AsSsize_t( - PyList_GET_ITEM(x, i), PyExc_ValueError); - if (value == -1 && PyErr_Occurred()) { - Py_DECREF(new); - return NULL; - } - if (value < 0 || value >= 256) { - PyErr_SetString(PyExc_ValueError, - "bytes must be in range(0, 256)"); - Py_DECREF(new); - return NULL; - } - ((PyBytesObject *)new)->ob_sval[i] = value; - } - return new; - } - if (PyTuple_CheckExact(x)) { - new = PyBytes_FromStringAndSize(NULL, Py_SIZE(x)); - if (new == NULL) - return NULL; - for (i = 0; i < Py_SIZE(x); i++) { - Py_ssize_t value = PyNumber_AsSsize_t( - PyTuple_GET_ITEM(x, i), PyExc_ValueError); - if (value == -1 && PyErr_Occurred()) { - Py_DECREF(new); - return NULL; - } - if (value < 0 || value >= 256) { - PyErr_SetString(PyExc_ValueError, - "bytes must be in range(0, 256)"); - Py_DECREF(new); - return NULL; - } - ((PyBytesObject *)new)->ob_sval[i] = value; - } - return new; - } - - /* For iterator version, create a string object and resize as needed */ - size = _PyObject_LengthHint(x, 64); - if (size == -1 && PyErr_Occurred()) - return NULL; - /* Allocate an extra byte to prevent PyBytes_FromStringAndSize() from - returning a shared empty bytes string. This required because we - want to call _PyBytes_Resize() the returned object, which we can - only do on bytes objects with refcount == 1. */ - size += 1; - new = PyBytes_FromStringAndSize(NULL, size); - if (new == NULL) - return NULL; - - /* Get the iterator */ - it = PyObject_GetIter(x); - if (it == NULL) - goto error; - - /* 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, PyExc_ValueError); - 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) { - size = 2 * size + 1; - if (_PyBytes_Resize(&new, size) < 0) - goto error; - } - ((PyBytesObject *)new)->ob_sval[i] = value; - } - _PyBytes_Resize(&new, i); - - /* Clean up and return success */ - Py_DECREF(it); - return new; + /* For iterator version, create a string object and resize as needed */ + size = _PyObject_LengthHint(x, 64); + if (size == -1 && PyErr_Occurred()) + return NULL; + /* Allocate an extra byte to prevent PyBytes_FromStringAndSize() from + returning a shared empty bytes string. This required because we + want to call _PyBytes_Resize() the returned object, which we can + only do on bytes objects with refcount == 1. */ + size += 1; + new = PyBytes_FromStringAndSize(NULL, size); + if (new == NULL) + return NULL; + + /* Get the iterator */ + it = PyObject_GetIter(x); + if (it == NULL) + goto error; + + /* 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, PyExc_ValueError); + 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) { + size = 2 * size + 1; + if (_PyBytes_Resize(&new, size) < 0) + goto error; + } + ((PyBytesObject *)new)->ob_sval[i] = value; + } + _PyBytes_Resize(&new, i); + + /* Clean up and return success */ + Py_DECREF(it); + return new; error: - /* Error handling when new != NULL */ - Py_XDECREF(it); - Py_DECREF(new); - return NULL; + /* Error handling when new != NULL */ + Py_XDECREF(it); + Py_DECREF(new); + return NULL; } static PyObject * str_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds) { - PyObject *tmp, *pnew; - Py_ssize_t n; + 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_CheckExact(tmp)); - n = PyBytes_GET_SIZE(tmp); - pnew = type->tp_alloc(type, n); - if (pnew != NULL) { - Py_MEMCPY(PyBytes_AS_STRING(pnew), - PyBytes_AS_STRING(tmp), n+1); - ((PyBytesObject *)pnew)->ob_shash = - ((PyBytesObject *)tmp)->ob_shash; - } - Py_DECREF(tmp); - return pnew; + assert(PyType_IsSubtype(type, &PyBytes_Type)); + tmp = bytes_new(&PyBytes_Type, args, kwds); + if (tmp == NULL) + return NULL; + assert(PyBytes_CheckExact(tmp)); + n = PyBytes_GET_SIZE(tmp); + pnew = type->tp_alloc(type, n); + if (pnew != NULL) { + Py_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, @@ -2756,70 +2756,70 @@ 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 */ - 0, /* 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 */ + 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 */ + 0, /* 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(register PyObject **pv, register PyObject *w) { - register PyObject *v; - assert(pv != NULL); - if (*pv == NULL) - return; - if (w == NULL) { - Py_DECREF(*pv); - *pv = NULL; - return; - } - v = bytes_concat(*pv, w); - Py_DECREF(*pv); - *pv = v; + register PyObject *v; + assert(pv != NULL); + if (*pv == NULL) + return; + if (w == NULL) { + Py_DECREF(*pv); + *pv = NULL; + return; + } + v = bytes_concat(*pv, w); + Py_DECREF(*pv); + *pv = v; } void PyBytes_ConcatAndDel(register PyObject **pv, register PyObject *w) { - PyBytes_Concat(pv, w); - Py_XDECREF(w); + PyBytes_Concat(pv, w); + Py_XDECREF(w); } @@ -2840,31 +2840,31 @@ int _PyBytes_Resize(PyObject **pv, Py_ssize_t newsize) { - register PyObject *v; - register PyBytesObject *sv; - v = *pv; - if (!PyBytes_Check(v) || Py_REFCNT(v) != 1 || newsize < 0) { - *pv = 0; - Py_DECREF(v); - PyErr_BadInternalCall(); - return -1; - } - /* XXX UNREF/NEWREF interface should be more symmetrical */ - _Py_DEC_REFTOTAL; - _Py_ForgetReference(v); - *pv = (PyObject *) - PyObject_REALLOC((char *)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; + register PyObject *v; + register PyBytesObject *sv; + v = *pv; + if (!PyBytes_Check(v) || Py_REFCNT(v) != 1 || newsize < 0) { + *pv = 0; + Py_DECREF(v); + PyErr_BadInternalCall(); + return -1; + } + /* XXX UNREF/NEWREF interface should be more symmetrical */ + _Py_DEC_REFTOTAL; + _Py_ForgetReference(v); + *pv = (PyObject *) + PyObject_REALLOC((char *)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; } /* _PyBytes_FormatLong emulates the format codes d, u, o, x and X, and @@ -2880,262 +2880,262 @@ * set in flags. The case of hex digits will be correct, * There will be at least prec digits, zero-filled on the left if * necessary to get that many. - * val object to be converted - * flags bitmask of format flags; only F_ALT is looked at - * prec minimum number of digits; 0-fill on left if needed - * type a character in [duoxX]; u acts the same as d + * val object to be converted + * flags bitmask of format flags; only F_ALT is looked at + * prec minimum number of digits; 0-fill on left if needed + * type a character in [duoxX]; u acts the same as d * * CAUTION: o, x and X conversions on regular ints can never * produce a '-' sign, but can for Python's unbounded ints. */ PyObject* _PyBytes_FormatLong(PyObject *val, int flags, int prec, int type, - char **pbuf, int *plen) + char **pbuf, int *plen) { - PyObject *result = NULL; - char *buf; - Py_ssize_t i; - int sign; /* 1 if '-', else 0 */ - int len; /* number of characters */ - Py_ssize_t llen; - int numdigits; /* len == numnondigits + numdigits */ - int numnondigits = 0; - - /* Avoid exceeding SSIZE_T_MAX */ - if (prec > INT_MAX-3) { - PyErr_SetString(PyExc_OverflowError, - "precision too large"); - return NULL; - } - - switch (type) { - case 'd': - case 'u': - /* Special-case boolean: we want 0/1 */ - if (PyBool_Check(val)) - result = PyNumber_ToBase(val, 10); - else - result = Py_TYPE(val)->tp_str(val); - break; - case 'o': - numnondigits = 2; - result = PyNumber_ToBase(val, 8); - break; - case 'x': - case 'X': - numnondigits = 2; - result = PyNumber_ToBase(val, 16); - break; - default: - assert(!"'type' not in [duoxX]"); - } - if (!result) - return NULL; - - buf = _PyUnicode_AsString(result); - if (!buf) { - Py_DECREF(result); - return NULL; - } - - /* To modify the string in-place, there can only be one reference. */ - if (Py_REFCNT(result) != 1) { - PyErr_BadInternalCall(); - return NULL; - } - llen = PyUnicode_GetSize(result); - if (llen > INT_MAX) { - PyErr_SetString(PyExc_ValueError, - "string too large in _PyBytes_FormatLong"); - return NULL; - } - len = (int)llen; - if (buf[len-1] == 'L') { - --len; - buf[len] = '\0'; - } - sign = buf[0] == '-'; - numnondigits += sign; - numdigits = len - numnondigits; - assert(numdigits > 0); - - /* Get rid of base marker unless F_ALT */ - if (((flags & F_ALT) == 0 && - (type == 'o' || type == 'x' || type == 'X'))) { - assert(buf[sign] == '0'); - assert(buf[sign+1] == 'x' || buf[sign+1] == 'X' || - buf[sign+1] == 'o'); - numnondigits -= 2; - buf += 2; - len -= 2; - if (sign) - buf[0] = '-'; - assert(len == numnondigits + numdigits); - assert(numdigits > 0); - } - - /* Fill with leading zeroes to meet minimum width. */ - if (prec > numdigits) { - PyObject *r1 = PyBytes_FromStringAndSize(NULL, - numnondigits + prec); - char *b1; - if (!r1) { - Py_DECREF(result); - return NULL; - } - b1 = PyBytes_AS_STRING(r1); - for (i = 0; i < numnondigits; ++i) - *b1++ = *buf++; - for (i = 0; i < prec - numdigits; i++) - *b1++ = '0'; - for (i = 0; i < numdigits; i++) - *b1++ = *buf++; - *b1 = '\0'; - Py_DECREF(result); - result = r1; - buf = PyBytes_AS_STRING(result); - len = numnondigits + prec; - } - - /* Fix up case for hex conversions. */ - if (type == 'X') { - /* Need to convert all lower case letters to upper case. - and need to convert 0x to 0X (and -0x to -0X). */ - for (i = 0; i < len; i++) - if (buf[i] >= 'a' && buf[i] <= 'x') - buf[i] -= 'a'-'A'; - } - *pbuf = buf; - *plen = len; - return result; + PyObject *result = NULL; + char *buf; + Py_ssize_t i; + int sign; /* 1 if '-', else 0 */ + int len; /* number of characters */ + Py_ssize_t llen; + int numdigits; /* len == numnondigits + numdigits */ + int numnondigits = 0; + + /* Avoid exceeding SSIZE_T_MAX */ + if (prec > INT_MAX-3) { + PyErr_SetString(PyExc_OverflowError, + "precision too large"); + return NULL; + } + + switch (type) { + case 'd': + case 'u': + /* Special-case boolean: we want 0/1 */ + if (PyBool_Check(val)) + result = PyNumber_ToBase(val, 10); + else + result = Py_TYPE(val)->tp_str(val); + break; + case 'o': + numnondigits = 2; + result = PyNumber_ToBase(val, 8); + break; + case 'x': + case 'X': + numnondigits = 2; + result = PyNumber_ToBase(val, 16); + break; + default: + assert(!"'type' not in [duoxX]"); + } + if (!result) + return NULL; + + buf = _PyUnicode_AsString(result); + if (!buf) { + Py_DECREF(result); + return NULL; + } + + /* To modify the string in-place, there can only be one reference. */ + if (Py_REFCNT(result) != 1) { + PyErr_BadInternalCall(); + return NULL; + } + llen = PyUnicode_GetSize(result); + if (llen > INT_MAX) { + PyErr_SetString(PyExc_ValueError, + "string too large in _PyBytes_FormatLong"); + return NULL; + } + len = (int)llen; + if (buf[len-1] == 'L') { + --len; + buf[len] = '\0'; + } + sign = buf[0] == '-'; + numnondigits += sign; + numdigits = len - numnondigits; + assert(numdigits > 0); + + /* Get rid of base marker unless F_ALT */ + if (((flags & F_ALT) == 0 && + (type == 'o' || type == 'x' || type == 'X'))) { + assert(buf[sign] == '0'); + assert(buf[sign+1] == 'x' || buf[sign+1] == 'X' || + buf[sign+1] == 'o'); + numnondigits -= 2; + buf += 2; + len -= 2; + if (sign) + buf[0] = '-'; + assert(len == numnondigits + numdigits); + assert(numdigits > 0); + } + + /* Fill with leading zeroes to meet minimum width. */ + if (prec > numdigits) { + PyObject *r1 = PyBytes_FromStringAndSize(NULL, + numnondigits + prec); + char *b1; + if (!r1) { + Py_DECREF(result); + return NULL; + } + b1 = PyBytes_AS_STRING(r1); + for (i = 0; i < numnondigits; ++i) + *b1++ = *buf++; + for (i = 0; i < prec - numdigits; i++) + *b1++ = '0'; + for (i = 0; i < numdigits; i++) + *b1++ = *buf++; + *b1 = '\0'; + Py_DECREF(result); + result = r1; + buf = PyBytes_AS_STRING(result); + len = numnondigits + prec; + } + + /* Fix up case for hex conversions. */ + if (type == 'X') { + /* Need to convert all lower case letters to upper case. + and need to convert 0x to 0X (and -0x to -0X). */ + for (i = 0; i < len; i++) + if (buf[i] >= 'a' && buf[i] <= 'x') + buf[i] -= 'a'-'A'; + } + *pbuf = buf; + *plen = len; + return result; } void PyBytes_Fini(void) { - int i; - for (i = 0; i < UCHAR_MAX + 1; i++) { - Py_XDECREF(characters[i]); - characters[i] = NULL; - } - Py_XDECREF(nullstring); - nullstring = NULL; + int i; + for (i = 0; i < UCHAR_MAX + 1; i++) { + Py_XDECREF(characters[i]); + characters[i] = NULL; + } + Py_XDECREF(nullstring); + nullstring = NULL; } /*********************** Bytes Iterator ****************************/ typedef struct { - PyObject_HEAD - Py_ssize_t it_index; - PyBytesObject *it_seq; /* Set to NULL when iterator is exhausted */ + 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); + _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; + Py_VISIT(it->it_seq); + return 0; } static PyObject * striter_next(striterobject *it) { - PyBytesObject *seq; - PyObject *item; + PyBytesObject *seq; + PyObject *item; + + assert(it != NULL); + seq = it->it_seq; + if (seq == NULL) + return NULL; + assert(PyBytes_Check(seq)); - 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; - } - - Py_DECREF(seq); - it->it_seq = NULL; - return NULL; + 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; + } + + Py_DECREF(seq); + it->it_seq = NULL; + 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); + 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))."); + "Private method returning an estimate of len(list(it))."); static PyMethodDef striter_methods[] = { - {"__length_hint__", (PyCFunction)striter_len, METH_NOARGS, - length_hint_doc}, - {NULL, NULL} /* sentinel */ + {"__length_hint__", (PyCFunction)striter_len, METH_NOARGS, + length_hint_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, + 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; + 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; + 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; } Modified: python/branches/py3k-jit/Objects/cellobject.c ============================================================================== --- python/branches/py3k-jit/Objects/cellobject.c (original) +++ python/branches/py3k-jit/Objects/cellobject.c Mon May 10 23:55:43 2010 @@ -5,50 +5,50 @@ PyObject * PyCell_New(PyObject *obj) { - PyCellObject *op; + PyCellObject *op; - op = (PyCellObject *)PyObject_GC_New(PyCellObject, &PyCell_Type); - if (op == NULL) - return NULL; - op->ob_ref = obj; - Py_XINCREF(obj); + op = (PyCellObject *)PyObject_GC_New(PyCellObject, &PyCell_Type); + if (op == NULL) + return NULL; + op->ob_ref = obj; + Py_XINCREF(obj); - _PyObject_GC_TRACK(op); - return (PyObject *)op; + _PyObject_GC_TRACK(op); + return (PyObject *)op; } PyObject * PyCell_Get(PyObject *op) { - if (!PyCell_Check(op)) { - PyErr_BadInternalCall(); - return NULL; - } - Py_XINCREF(((PyCellObject*)op)->ob_ref); - return PyCell_GET(op); + if (!PyCell_Check(op)) { + PyErr_BadInternalCall(); + return NULL; + } + Py_XINCREF(((PyCellObject*)op)->ob_ref); + return PyCell_GET(op); } int PyCell_Set(PyObject *op, PyObject *obj) { - PyObject* oldobj; - if (!PyCell_Check(op)) { - PyErr_BadInternalCall(); - return -1; - } - oldobj = PyCell_GET(op); - Py_XINCREF(obj); - PyCell_SET(op, obj); - Py_XDECREF(oldobj); - return 0; + PyObject* oldobj; + if (!PyCell_Check(op)) { + PyErr_BadInternalCall(); + return -1; + } + oldobj = PyCell_GET(op); + Py_XINCREF(obj); + PyCell_SET(op, obj); + Py_XDECREF(oldobj); + return 0; } static void cell_dealloc(PyCellObject *op) { - _PyObject_GC_UNTRACK(op); - Py_XDECREF(op->ob_ref); - PyObject_GC_Del(op); + _PyObject_GC_UNTRACK(op); + Py_XDECREF(op->ob_ref); + PyObject_GC_Del(op); } #define TEST_COND(cond) ((cond) ? Py_True : Py_False) @@ -56,124 +56,124 @@ static PyObject * cell_richcompare(PyObject *a, PyObject *b, int op) { - int result; - PyObject *v; + int result; + PyObject *v; - /* neither argument should be NULL, unless something's gone wrong */ - assert(a != NULL && b != NULL); + /* neither argument should be NULL, unless something's gone wrong */ + assert(a != NULL && b != NULL); - /* both arguments should be instances of PyCellObject */ - if (!PyCell_Check(a) || !PyCell_Check(b)) { - v = Py_NotImplemented; - Py_INCREF(v); - return v; - } - - /* compare cells by contents; empty cells come before anything else */ - a = ((PyCellObject *)a)->ob_ref; - b = ((PyCellObject *)b)->ob_ref; - if (a != NULL && b != NULL) - return PyObject_RichCompare(a, b, op); - - result = (b == NULL) - (a == NULL); - switch (op) { - case Py_EQ: - v = TEST_COND(result == 0); - break; - case Py_NE: - v = TEST_COND(result != 0); - break; - case Py_LE: - v = TEST_COND(result <= 0); - break; - case Py_GE: - v = TEST_COND(result >= 0); - break; - case Py_LT: - v = TEST_COND(result < 0); - break; - case Py_GT: - v = TEST_COND(result > 0); - break; - default: - PyErr_BadArgument(); - return NULL; - } - Py_INCREF(v); - return v; + /* both arguments should be instances of PyCellObject */ + if (!PyCell_Check(a) || !PyCell_Check(b)) { + v = Py_NotImplemented; + Py_INCREF(v); + return v; + } + + /* compare cells by contents; empty cells come before anything else */ + a = ((PyCellObject *)a)->ob_ref; + b = ((PyCellObject *)b)->ob_ref; + if (a != NULL && b != NULL) + return PyObject_RichCompare(a, b, op); + + result = (b == NULL) - (a == NULL); + switch (op) { + case Py_EQ: + v = TEST_COND(result == 0); + break; + case Py_NE: + v = TEST_COND(result != 0); + break; + case Py_LE: + v = TEST_COND(result <= 0); + break; + case Py_GE: + v = TEST_COND(result >= 0); + break; + case Py_LT: + v = TEST_COND(result < 0); + break; + case Py_GT: + v = TEST_COND(result > 0); + break; + default: + PyErr_BadArgument(); + return NULL; + } + Py_INCREF(v); + return v; } static PyObject * cell_repr(PyCellObject *op) { - if (op->ob_ref == NULL) - return PyUnicode_FromFormat("", op); + if (op->ob_ref == NULL) + return PyUnicode_FromFormat("", op); - return PyUnicode_FromFormat("", - op, op->ob_ref->ob_type->tp_name, - op->ob_ref); + return PyUnicode_FromFormat("", + op, op->ob_ref->ob_type->tp_name, + op->ob_ref); } static int cell_traverse(PyCellObject *op, visitproc visit, void *arg) { - Py_VISIT(op->ob_ref); - return 0; + Py_VISIT(op->ob_ref); + return 0; } static int cell_clear(PyCellObject *op) { - Py_CLEAR(op->ob_ref); - return 0; + Py_CLEAR(op->ob_ref); + return 0; } static PyObject * cell_get_contents(PyCellObject *op, void *closure) { - if (op->ob_ref == NULL) - { - PyErr_SetString(PyExc_ValueError, "Cell is empty"); - return NULL; - } - Py_INCREF(op->ob_ref); - return op->ob_ref; + if (op->ob_ref == NULL) + { + PyErr_SetString(PyExc_ValueError, "Cell is empty"); + return NULL; + } + Py_INCREF(op->ob_ref); + return op->ob_ref; } static PyGetSetDef cell_getsetlist[] = { - {"cell_contents", (getter)cell_get_contents, NULL}, - {NULL} /* sentinel */ + {"cell_contents", (getter)cell_get_contents, NULL}, + {NULL} /* sentinel */ }; PyTypeObject PyCell_Type = { - PyVarObject_HEAD_INIT(&PyType_Type, 0) - "cell", - sizeof(PyCellObject), - 0, - (destructor)cell_dealloc, /* tp_dealloc */ - 0, /* tp_print */ - 0, /* tp_getattr */ - 0, /* tp_setattr */ - 0, /* tp_reserved */ - (reprfunc)cell_repr, /* 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)cell_traverse, /* tp_traverse */ - (inquiry)cell_clear, /* tp_clear */ - cell_richcompare, /* tp_richcompare */ - 0, /* tp_weaklistoffset */ - 0, /* tp_iter */ - 0, /* tp_iternext */ - 0, /* tp_methods */ - 0, /* tp_members */ - cell_getsetlist, /* tp_getset */ + PyVarObject_HEAD_INIT(&PyType_Type, 0) + "cell", + sizeof(PyCellObject), + 0, + (destructor)cell_dealloc, /* tp_dealloc */ + 0, /* tp_print */ + 0, /* tp_getattr */ + 0, /* tp_setattr */ + 0, /* tp_reserved */ + (reprfunc)cell_repr, /* 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)cell_traverse, /* tp_traverse */ + (inquiry)cell_clear, /* tp_clear */ + cell_richcompare, /* tp_richcompare */ + 0, /* tp_weaklistoffset */ + 0, /* tp_iter */ + 0, /* tp_iternext */ + 0, /* tp_methods */ + 0, /* tp_members */ + cell_getsetlist, /* tp_getset */ }; Modified: python/branches/py3k-jit/Objects/classobject.c ============================================================================== --- python/branches/py3k-jit/Objects/classobject.c (original) +++ python/branches/py3k-jit/Objects/classobject.c Mon May 10 23:55:43 2010 @@ -17,21 +17,21 @@ PyObject * PyMethod_Function(PyObject *im) { - if (!PyMethod_Check(im)) { - PyErr_BadInternalCall(); - return NULL; - } - return ((PyMethodObject *)im)->im_func; + if (!PyMethod_Check(im)) { + PyErr_BadInternalCall(); + return NULL; + } + return ((PyMethodObject *)im)->im_func; } PyObject * PyMethod_Self(PyObject *im) { - if (!PyMethod_Check(im)) { - PyErr_BadInternalCall(); - return NULL; - } - return ((PyMethodObject *)im)->im_self; + if (!PyMethod_Check(im)) { + PyErr_BadInternalCall(); + return NULL; + } + return ((PyMethodObject *)im)->im_self; } /* Method objects are used for bound instance methods returned by @@ -42,29 +42,29 @@ PyObject * PyMethod_New(PyObject *func, PyObject *self) { - register PyMethodObject *im; - if (self == NULL) { - PyErr_BadInternalCall(); - return NULL; - } - im = free_list; - if (im != NULL) { - free_list = (PyMethodObject *)(im->im_self); - PyObject_INIT(im, &PyMethod_Type); - numfree--; - } - else { - im = PyObject_GC_New(PyMethodObject, &PyMethod_Type); - if (im == NULL) - return NULL; - } - im->im_weakreflist = NULL; - Py_INCREF(func); - im->im_func = func; - Py_XINCREF(self); - im->im_self = self; - _PyObject_GC_TRACK(im); - return (PyObject *)im; + register PyMethodObject *im; + if (self == NULL) { + PyErr_BadInternalCall(); + return NULL; + } + im = free_list; + if (im != NULL) { + free_list = (PyMethodObject *)(im->im_self); + PyObject_INIT(im, &PyMethod_Type); + numfree--; + } + else { + im = PyObject_GC_New(PyMethodObject, &PyMethod_Type); + if (im == NULL) + return NULL; + } + im->im_weakreflist = NULL; + Py_INCREF(func); + im->im_func = func; + Py_XINCREF(self); + im->im_self = self; + _PyObject_GC_TRACK(im); + return (PyObject *)im; } /* Descriptors for PyMethod attributes */ @@ -74,11 +74,11 @@ #define MO_OFF(x) offsetof(PyMethodObject, x) static PyMemberDef method_memberlist[] = { - {"__func__", T_OBJECT, MO_OFF(im_func), READONLY|RESTRICTED, - "the function (or other callable) implementing a method"}, - {"__self__", T_OBJECT, MO_OFF(im_self), READONLY|RESTRICTED, - "the instance to which a method is bound"}, - {NULL} /* Sentinel */ + {"__func__", T_OBJECT, MO_OFF(im_func), READONLY|RESTRICTED, + "the function (or other callable) implementing a method"}, + {"__self__", T_OBJECT, MO_OFF(im_self), READONLY|RESTRICTED, + "the instance to which a method is bound"}, + {NULL} /* Sentinel */ }; /* Christian Tismer argued convincingly that method attributes should @@ -89,46 +89,46 @@ static PyObject * method_get_doc(PyMethodObject *im, void *context) { - static PyObject *docstr; - if (docstr == NULL) { - docstr= PyUnicode_InternFromString("__doc__"); - if (docstr == NULL) - return NULL; - } - return PyObject_GetAttr(im->im_func, docstr); + static PyObject *docstr; + if (docstr == NULL) { + docstr= PyUnicode_InternFromString("__doc__"); + if (docstr == NULL) + return NULL; + } + return PyObject_GetAttr(im->im_func, docstr); } static PyGetSetDef method_getset[] = { - {"__doc__", (getter)method_get_doc, NULL, NULL}, - {0} + {"__doc__", (getter)method_get_doc, NULL, NULL}, + {0} }; static PyObject * method_getattro(PyObject *obj, PyObject *name) { - PyMethodObject *im = (PyMethodObject *)obj; - PyTypeObject *tp = obj->ob_type; - PyObject *descr = NULL; - - { - if (tp->tp_dict == NULL) { - if (PyType_Ready(tp) < 0) - return NULL; - } - descr = _PyType_Lookup(tp, name); - } - - if (descr != NULL) { - descrgetfunc f = TP_DESCR_GET(descr->ob_type); - if (f != NULL) - return f(descr, obj, (PyObject *)obj->ob_type); - else { - Py_INCREF(descr); - return descr; - } - } + PyMethodObject *im = (PyMethodObject *)obj; + PyTypeObject *tp = obj->ob_type; + PyObject *descr = NULL; + + { + if (tp->tp_dict == NULL) { + if (PyType_Ready(tp) < 0) + return NULL; + } + descr = _PyType_Lookup(tp, name); + } + + if (descr != NULL) { + descrgetfunc f = TP_DESCR_GET(descr->ob_type); + if (f != NULL) + return f(descr, obj, (PyObject *)obj->ob_type); + else { + Py_INCREF(descr); + return descr; + } + } - return PyObject_GetAttr(im->im_func, name); + return PyObject_GetAttr(im->im_func, name); } PyDoc_STRVAR(method_doc, @@ -139,241 +139,241 @@ static PyObject * method_new(PyTypeObject* type, PyObject* args, PyObject *kw) { - PyObject *func; - PyObject *self; + PyObject *func; + PyObject *self; - if (!_PyArg_NoKeywords("method", kw)) - return NULL; - if (!PyArg_UnpackTuple(args, "method", 2, 2, - &func, &self)) - return NULL; - if (!PyCallable_Check(func)) { - PyErr_SetString(PyExc_TypeError, - "first argument must be callable"); - return NULL; - } - if (self == NULL || self == Py_None) { - PyErr_SetString(PyExc_TypeError, - "self must not be None"); - return NULL; - } + if (!_PyArg_NoKeywords("method", kw)) + return NULL; + if (!PyArg_UnpackTuple(args, "method", 2, 2, + &func, &self)) + return NULL; + if (!PyCallable_Check(func)) { + PyErr_SetString(PyExc_TypeError, + "first argument must be callable"); + return NULL; + } + if (self == NULL || self == Py_None) { + PyErr_SetString(PyExc_TypeError, + "self must not be None"); + return NULL; + } - return PyMethod_New(func, self); + return PyMethod_New(func, self); } static void method_dealloc(register PyMethodObject *im) { - _PyObject_GC_UNTRACK(im); - if (im->im_weakreflist != NULL) - PyObject_ClearWeakRefs((PyObject *)im); - Py_DECREF(im->im_func); - Py_XDECREF(im->im_self); - if (numfree < PyMethod_MAXFREELIST) { - im->im_self = (PyObject *)free_list; - free_list = im; - numfree++; - } - else { - PyObject_GC_Del(im); - } + _PyObject_GC_UNTRACK(im); + if (im->im_weakreflist != NULL) + PyObject_ClearWeakRefs((PyObject *)im); + Py_DECREF(im->im_func); + Py_XDECREF(im->im_self); + if (numfree < PyMethod_MAXFREELIST) { + im->im_self = (PyObject *)free_list; + free_list = im; + numfree++; + } + else { + PyObject_GC_Del(im); + } } static PyObject * method_richcompare(PyObject *self, PyObject *other, int op) { - PyMethodObject *a, *b; - PyObject *res; - int eq; - - if ((op != Py_EQ && op != Py_NE) || - !PyMethod_Check(self) || - !PyMethod_Check(other)) - { - Py_INCREF(Py_NotImplemented); - return Py_NotImplemented; - } - a = (PyMethodObject *)self; - b = (PyMethodObject *)other; - eq = PyObject_RichCompareBool(a->im_func, b->im_func, Py_EQ); - if (eq == 1) { - if (a->im_self == NULL || b->im_self == NULL) - eq = a->im_self == b->im_self; - else - eq = PyObject_RichCompareBool(a->im_self, b->im_self, - Py_EQ); - } - if (eq < 0) - return NULL; - if (op == Py_EQ) - res = eq ? Py_True : Py_False; - else - res = eq ? Py_False : Py_True; - Py_INCREF(res); - return res; + PyMethodObject *a, *b; + PyObject *res; + int eq; + + if ((op != Py_EQ && op != Py_NE) || + !PyMethod_Check(self) || + !PyMethod_Check(other)) + { + Py_INCREF(Py_NotImplemented); + return Py_NotImplemented; + } + a = (PyMethodObject *)self; + b = (PyMethodObject *)other; + eq = PyObject_RichCompareBool(a->im_func, b->im_func, Py_EQ); + if (eq == 1) { + if (a->im_self == NULL || b->im_self == NULL) + eq = a->im_self == b->im_self; + else + eq = PyObject_RichCompareBool(a->im_self, b->im_self, + Py_EQ); + } + if (eq < 0) + return NULL; + if (op == Py_EQ) + res = eq ? Py_True : Py_False; + else + res = eq ? Py_False : Py_True; + Py_INCREF(res); + return res; } static PyObject * method_repr(PyMethodObject *a) { - PyObject *self = a->im_self; - PyObject *func = a->im_func; - PyObject *klass = (PyObject*)Py_TYPE(self); - PyObject *funcname = NULL ,*klassname = NULL, *result = NULL; - char *defname = "?"; - - if (self == NULL) { - PyErr_BadInternalCall(); - return NULL; - } - - funcname = PyObject_GetAttrString(func, "__name__"); - if (funcname == NULL) { - if (!PyErr_ExceptionMatches(PyExc_AttributeError)) - return NULL; - PyErr_Clear(); - } - else if (!PyUnicode_Check(funcname)) { - Py_DECREF(funcname); - funcname = NULL; - } - - if (klass == NULL) - klassname = NULL; - else { - klassname = PyObject_GetAttrString(klass, "__name__"); - if (klassname == NULL) { - if (!PyErr_ExceptionMatches(PyExc_AttributeError)) - return NULL; - PyErr_Clear(); - } - else if (!PyUnicode_Check(klassname)) { - Py_DECREF(klassname); - klassname = NULL; - } - } - - /* XXX Shouldn't use repr()/%R here! */ - result = PyUnicode_FromFormat("", - klassname, defname, - funcname, defname, self); - - Py_XDECREF(funcname); - Py_XDECREF(klassname); - return result; + PyObject *self = a->im_self; + PyObject *func = a->im_func; + PyObject *klass = (PyObject*)Py_TYPE(self); + PyObject *funcname = NULL ,*klassname = NULL, *result = NULL; + char *defname = "?"; + + if (self == NULL) { + PyErr_BadInternalCall(); + return NULL; + } + + funcname = PyObject_GetAttrString(func, "__name__"); + if (funcname == NULL) { + if (!PyErr_ExceptionMatches(PyExc_AttributeError)) + return NULL; + PyErr_Clear(); + } + else if (!PyUnicode_Check(funcname)) { + Py_DECREF(funcname); + funcname = NULL; + } + + if (klass == NULL) + klassname = NULL; + else { + klassname = PyObject_GetAttrString(klass, "__name__"); + if (klassname == NULL) { + if (!PyErr_ExceptionMatches(PyExc_AttributeError)) + return NULL; + PyErr_Clear(); + } + else if (!PyUnicode_Check(klassname)) { + Py_DECREF(klassname); + klassname = NULL; + } + } + + /* XXX Shouldn't use repr()/%R here! */ + result = PyUnicode_FromFormat("", + klassname, defname, + funcname, defname, self); + + Py_XDECREF(funcname); + Py_XDECREF(klassname); + return result; } static long method_hash(PyMethodObject *a) { - long x, y; - if (a->im_self == NULL) - x = PyObject_Hash(Py_None); - else - x = PyObject_Hash(a->im_self); - if (x == -1) - return -1; - y = PyObject_Hash(a->im_func); - if (y == -1) - return -1; - x = x ^ y; - if (x == -1) - x = -2; - return x; + long x, y; + if (a->im_self == NULL) + x = PyObject_Hash(Py_None); + else + x = PyObject_Hash(a->im_self); + if (x == -1) + return -1; + y = PyObject_Hash(a->im_func); + if (y == -1) + return -1; + x = x ^ y; + if (x == -1) + x = -2; + return x; } static int method_traverse(PyMethodObject *im, visitproc visit, void *arg) { - Py_VISIT(im->im_func); - Py_VISIT(im->im_self); - return 0; + Py_VISIT(im->im_func); + Py_VISIT(im->im_self); + return 0; } static PyObject * method_call(PyObject *func, PyObject *arg, PyObject *kw) { - PyObject *self = PyMethod_GET_SELF(func); - PyObject *result; + PyObject *self = PyMethod_GET_SELF(func); + PyObject *result; - func = PyMethod_GET_FUNCTION(func); - if (self == NULL) { - PyErr_BadInternalCall(); - return NULL; - } - else { - Py_ssize_t argcount = PyTuple_Size(arg); - PyObject *newarg = PyTuple_New(argcount + 1); - int i; - if (newarg == NULL) - return NULL; - Py_INCREF(self); - PyTuple_SET_ITEM(newarg, 0, self); - for (i = 0; i < argcount; i++) { - PyObject *v = PyTuple_GET_ITEM(arg, i); - Py_XINCREF(v); - PyTuple_SET_ITEM(newarg, i+1, v); - } - arg = newarg; - } - result = PyObject_Call((PyObject *)func, arg, kw); - Py_DECREF(arg); - return result; + func = PyMethod_GET_FUNCTION(func); + if (self == NULL) { + PyErr_BadInternalCall(); + return NULL; + } + else { + Py_ssize_t argcount = PyTuple_Size(arg); + PyObject *newarg = PyTuple_New(argcount + 1); + int i; + if (newarg == NULL) + return NULL; + Py_INCREF(self); + PyTuple_SET_ITEM(newarg, 0, self); + for (i = 0; i < argcount; i++) { + PyObject *v = PyTuple_GET_ITEM(arg, i); + Py_XINCREF(v); + PyTuple_SET_ITEM(newarg, i+1, v); + } + arg = newarg; + } + result = PyObject_Call((PyObject *)func, arg, kw); + Py_DECREF(arg); + return result; } static PyObject * method_descr_get(PyObject *meth, PyObject *obj, PyObject *cls) { - /* Don't rebind an already bound method of a class that's not a base - class of cls. */ - if (PyMethod_GET_SELF(meth) != NULL) { - /* Already bound */ - Py_INCREF(meth); - return meth; - } - /* Bind it to obj */ - return PyMethod_New(PyMethod_GET_FUNCTION(meth), obj); + /* Don't rebind an already bound method of a class that's not a base + class of cls. */ + if (PyMethod_GET_SELF(meth) != NULL) { + /* Already bound */ + Py_INCREF(meth); + return meth; + } + /* Bind it to obj */ + return PyMethod_New(PyMethod_GET_FUNCTION(meth), obj); } PyTypeObject PyMethod_Type = { - PyVarObject_HEAD_INIT(&PyType_Type, 0) - "method", - sizeof(PyMethodObject), - 0, - (destructor)method_dealloc, /* tp_dealloc */ - 0, /* tp_print */ - 0, /* tp_getattr */ - 0, /* tp_setattr */ - 0, /* tp_reserved */ - (reprfunc)method_repr, /* tp_repr */ - 0, /* tp_as_number */ - 0, /* tp_as_sequence */ - 0, /* tp_as_mapping */ - (hashfunc)method_hash, /* tp_hash */ - method_call, /* tp_call */ - 0, /* tp_str */ - method_getattro, /* tp_getattro */ - PyObject_GenericSetAttr, /* tp_setattro */ - 0, /* tp_as_buffer */ - Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC, /* tp_flags */ - method_doc, /* tp_doc */ - (traverseproc)method_traverse, /* tp_traverse */ - 0, /* tp_clear */ - method_richcompare, /* tp_richcompare */ - offsetof(PyMethodObject, im_weakreflist), /* tp_weaklistoffset */ - 0, /* tp_iter */ - 0, /* tp_iternext */ - 0, /* tp_methods */ - method_memberlist, /* tp_members */ - method_getset, /* tp_getset */ - 0, /* tp_base */ - 0, /* tp_dict */ - method_descr_get, /* tp_descr_get */ - 0, /* tp_descr_set */ - 0, /* tp_dictoffset */ - 0, /* tp_init */ - 0, /* tp_alloc */ - method_new, /* tp_new */ + PyVarObject_HEAD_INIT(&PyType_Type, 0) + "method", + sizeof(PyMethodObject), + 0, + (destructor)method_dealloc, /* tp_dealloc */ + 0, /* tp_print */ + 0, /* tp_getattr */ + 0, /* tp_setattr */ + 0, /* tp_reserved */ + (reprfunc)method_repr, /* tp_repr */ + 0, /* tp_as_number */ + 0, /* tp_as_sequence */ + 0, /* tp_as_mapping */ + (hashfunc)method_hash, /* tp_hash */ + method_call, /* tp_call */ + 0, /* tp_str */ + method_getattro, /* tp_getattro */ + PyObject_GenericSetAttr, /* tp_setattro */ + 0, /* tp_as_buffer */ + Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC, /* tp_flags */ + method_doc, /* tp_doc */ + (traverseproc)method_traverse, /* tp_traverse */ + 0, /* tp_clear */ + method_richcompare, /* tp_richcompare */ + offsetof(PyMethodObject, im_weakreflist), /* tp_weaklistoffset */ + 0, /* tp_iter */ + 0, /* tp_iternext */ + 0, /* tp_methods */ + method_memberlist, /* tp_members */ + method_getset, /* tp_getset */ + 0, /* tp_base */ + 0, /* tp_dict */ + method_descr_get, /* tp_descr_get */ + 0, /* tp_descr_set */ + 0, /* tp_dictoffset */ + 0, /* tp_init */ + 0, /* tp_alloc */ + method_new, /* tp_new */ }; /* Clear out the free list */ @@ -381,22 +381,22 @@ int PyMethod_ClearFreeList(void) { - int freelist_size = numfree; - - while (free_list) { - PyMethodObject *im = free_list; - free_list = (PyMethodObject *)(im->im_self); - PyObject_GC_Del(im); - numfree--; - } - assert(numfree == 0); - return freelist_size; + int freelist_size = numfree; + + while (free_list) { + PyMethodObject *im = free_list; + free_list = (PyMethodObject *)(im->im_self); + PyObject_GC_Del(im); + numfree--; + } + assert(numfree == 0); + return freelist_size; } void PyMethod_Fini(void) { - (void)PyMethod_ClearFreeList(); + (void)PyMethod_ClearFreeList(); } /* ------------------------------------------------------------------------ @@ -405,176 +405,176 @@ PyObject * PyInstanceMethod_New(PyObject *func) { - PyInstanceMethodObject *method; - method = PyObject_GC_New(PyInstanceMethodObject, - &PyInstanceMethod_Type); - if (method == NULL) return NULL; - Py_INCREF(func); - method->func = func; - _PyObject_GC_TRACK(method); - return (PyObject *)method; + PyInstanceMethodObject *method; + method = PyObject_GC_New(PyInstanceMethodObject, + &PyInstanceMethod_Type); + if (method == NULL) return NULL; + Py_INCREF(func); + method->func = func; + _PyObject_GC_TRACK(method); + return (PyObject *)method; } PyObject * PyInstanceMethod_Function(PyObject *im) { - if (!PyInstanceMethod_Check(im)) { - PyErr_BadInternalCall(); - return NULL; - } - return PyInstanceMethod_GET_FUNCTION(im); + if (!PyInstanceMethod_Check(im)) { + PyErr_BadInternalCall(); + return NULL; + } + return PyInstanceMethod_GET_FUNCTION(im); } #define IMO_OFF(x) offsetof(PyInstanceMethodObject, x) static PyMemberDef instancemethod_memberlist[] = { - {"__func__", T_OBJECT, IMO_OFF(func), READONLY|RESTRICTED, - "the function (or other callable) implementing a method"}, - {NULL} /* Sentinel */ + {"__func__", T_OBJECT, IMO_OFF(func), READONLY|RESTRICTED, + "the function (or other callable) implementing a method"}, + {NULL} /* Sentinel */ }; static PyObject * instancemethod_get_doc(PyObject *self, void *context) { - static PyObject *docstr; - if (docstr == NULL) { - docstr = PyUnicode_InternFromString("__doc__"); - if (docstr == NULL) - return NULL; - } - return PyObject_GetAttr(PyInstanceMethod_GET_FUNCTION(self), docstr); + static PyObject *docstr; + if (docstr == NULL) { + docstr = PyUnicode_InternFromString("__doc__"); + if (docstr == NULL) + return NULL; + } + return PyObject_GetAttr(PyInstanceMethod_GET_FUNCTION(self), docstr); } static PyGetSetDef instancemethod_getset[] = { - {"__doc__", (getter)instancemethod_get_doc, NULL, NULL}, - {0} + {"__doc__", (getter)instancemethod_get_doc, NULL, NULL}, + {0} }; static PyObject * instancemethod_getattro(PyObject *self, PyObject *name) { - PyTypeObject *tp = self->ob_type; - PyObject *descr = NULL; + PyTypeObject *tp = self->ob_type; + PyObject *descr = NULL; - if (tp->tp_dict == NULL) { - if (PyType_Ready(tp) < 0) - return NULL; - } - descr = _PyType_Lookup(tp, name); - - if (descr != NULL) { - descrgetfunc f = TP_DESCR_GET(descr->ob_type); - if (f != NULL) - return f(descr, self, (PyObject *)self->ob_type); - else { - Py_INCREF(descr); - return descr; - } - } + if (tp->tp_dict == NULL) { + if (PyType_Ready(tp) < 0) + return NULL; + } + descr = _PyType_Lookup(tp, name); + + if (descr != NULL) { + descrgetfunc f = TP_DESCR_GET(descr->ob_type); + if (f != NULL) + return f(descr, self, (PyObject *)self->ob_type); + else { + Py_INCREF(descr); + return descr; + } + } - return PyObject_GetAttr(PyInstanceMethod_GET_FUNCTION(self), name); + return PyObject_GetAttr(PyInstanceMethod_GET_FUNCTION(self), name); } static void instancemethod_dealloc(PyObject *self) { - _PyObject_GC_UNTRACK(self); - Py_DECREF(PyInstanceMethod_GET_FUNCTION(self)); - PyObject_GC_Del(self); + _PyObject_GC_UNTRACK(self); + Py_DECREF(PyInstanceMethod_GET_FUNCTION(self)); + PyObject_GC_Del(self); } static int instancemethod_traverse(PyObject *self, visitproc visit, void *arg) { - Py_VISIT(PyInstanceMethod_GET_FUNCTION(self)); - return 0; + Py_VISIT(PyInstanceMethod_GET_FUNCTION(self)); + return 0; } static PyObject * instancemethod_call(PyObject *self, PyObject *arg, PyObject *kw) { - return PyObject_Call(PyMethod_GET_FUNCTION(self), arg, kw); + return PyObject_Call(PyMethod_GET_FUNCTION(self), arg, kw); } static PyObject * instancemethod_descr_get(PyObject *descr, PyObject *obj, PyObject *type) { - register PyObject *func = PyInstanceMethod_GET_FUNCTION(descr); - if (obj == NULL) { - Py_INCREF(func); - return func; - } - else - return PyMethod_New(func, obj); + register PyObject *func = PyInstanceMethod_GET_FUNCTION(descr); + if (obj == NULL) { + Py_INCREF(func); + return func; + } + else + return PyMethod_New(func, obj); } static PyObject * instancemethod_richcompare(PyObject *self, PyObject *other, int op) { - PyInstanceMethodObject *a, *b; - PyObject *res; - int eq; - - if ((op != Py_EQ && op != Py_NE) || - !PyInstanceMethod_Check(self) || - !PyInstanceMethod_Check(other)) - { - Py_INCREF(Py_NotImplemented); - return Py_NotImplemented; - } - a = (PyInstanceMethodObject *)self; - b = (PyInstanceMethodObject *)other; - eq = PyObject_RichCompareBool(a->func, b->func, Py_EQ); - if (eq < 0) - return NULL; - if (op == Py_EQ) - res = eq ? Py_True : Py_False; - else - res = eq ? Py_False : Py_True; - Py_INCREF(res); - return res; + PyInstanceMethodObject *a, *b; + PyObject *res; + int eq; + + if ((op != Py_EQ && op != Py_NE) || + !PyInstanceMethod_Check(self) || + !PyInstanceMethod_Check(other)) + { + Py_INCREF(Py_NotImplemented); + return Py_NotImplemented; + } + a = (PyInstanceMethodObject *)self; + b = (PyInstanceMethodObject *)other; + eq = PyObject_RichCompareBool(a->func, b->func, Py_EQ); + if (eq < 0) + return NULL; + if (op == Py_EQ) + res = eq ? Py_True : Py_False; + else + res = eq ? Py_False : Py_True; + Py_INCREF(res); + return res; } static PyObject * instancemethod_repr(PyObject *self) { - PyObject *func = PyInstanceMethod_Function(self); - PyObject *funcname = NULL , *result = NULL; - char *defname = "?"; - - if (func == NULL) { - PyErr_BadInternalCall(); - return NULL; - } - - funcname = PyObject_GetAttrString(func, "__name__"); - if (funcname == NULL) { - if (!PyErr_ExceptionMatches(PyExc_AttributeError)) - return NULL; - PyErr_Clear(); - } - else if (!PyUnicode_Check(funcname)) { - Py_DECREF(funcname); - funcname = NULL; - } + PyObject *func = PyInstanceMethod_Function(self); + PyObject *funcname = NULL , *result = NULL; + char *defname = "?"; + + if (func == NULL) { + PyErr_BadInternalCall(); + return NULL; + } + + funcname = PyObject_GetAttrString(func, "__name__"); + if (funcname == NULL) { + if (!PyErr_ExceptionMatches(PyExc_AttributeError)) + return NULL; + PyErr_Clear(); + } + else if (!PyUnicode_Check(funcname)) { + Py_DECREF(funcname); + funcname = NULL; + } - result = PyUnicode_FromFormat("", - funcname, defname, self); + result = PyUnicode_FromFormat("", + funcname, defname, self); - Py_XDECREF(funcname); - return result; + Py_XDECREF(funcname); + return result; } /* static long instancemethod_hash(PyObject *self) { - long x, y; - x = (long)self; - y = PyObject_Hash(PyInstanceMethod_GET_FUNCTION(self)); - if (y == -1) - return -1; - x = x ^ y; - if (x == -1) - x = -2; - return x; + long x, y; + x = (long)self; + y = PyObject_Hash(PyInstanceMethod_GET_FUNCTION(self)); + if (y == -1) + return -1; + x = x ^ y; + if (x == -1) + x = -2; + return x; } */ @@ -586,59 +586,59 @@ static PyObject * instancemethod_new(PyTypeObject* type, PyObject* args, PyObject *kw) { - PyObject *func; + PyObject *func; - if (!_PyArg_NoKeywords("instancemethod", kw)) - return NULL; - if (!PyArg_UnpackTuple(args, "instancemethod", 1, 1, &func)) - return NULL; - if (!PyCallable_Check(func)) { - PyErr_SetString(PyExc_TypeError, - "first argument must be callable"); - return NULL; - } + if (!_PyArg_NoKeywords("instancemethod", kw)) + return NULL; + if (!PyArg_UnpackTuple(args, "instancemethod", 1, 1, &func)) + return NULL; + if (!PyCallable_Check(func)) { + PyErr_SetString(PyExc_TypeError, + "first argument must be callable"); + return NULL; + } - return PyInstanceMethod_New(func); + return PyInstanceMethod_New(func); } PyTypeObject PyInstanceMethod_Type = { - PyVarObject_HEAD_INIT(&PyType_Type, 0) - "instancemethod", /* tp_name */ - sizeof(PyInstanceMethodObject), /* tp_basicsize */ - 0, /* tp_itemsize */ - instancemethod_dealloc, /* tp_dealloc */ - 0, /* tp_print */ - 0, /* tp_getattr */ - 0, /* tp_setattr */ - 0, /* tp_reserved */ - (reprfunc)instancemethod_repr, /* tp_repr */ - 0, /* tp_as_number */ - 0, /* tp_as_sequence */ - 0, /* tp_as_mapping */ - 0, /*(hashfunc)instancemethod_hash, tp_hash */ - instancemethod_call, /* tp_call */ - 0, /* tp_str */ - instancemethod_getattro, /* tp_getattro */ - PyObject_GenericSetAttr, /* tp_setattro */ - 0, /* tp_as_buffer */ - Py_TPFLAGS_DEFAULT - | Py_TPFLAGS_HAVE_GC, /* tp_flags */ - instancemethod_doc, /* tp_doc */ - instancemethod_traverse, /* tp_traverse */ - 0, /* tp_clear */ - instancemethod_richcompare, /* tp_richcompare */ - 0, /* tp_weaklistoffset */ - 0, /* tp_iter */ - 0, /* tp_iternext */ - 0, /* tp_methods */ - instancemethod_memberlist, /* tp_members */ - instancemethod_getset, /* tp_getset */ - 0, /* tp_base */ - 0, /* tp_dict */ - instancemethod_descr_get, /* tp_descr_get */ - 0, /* tp_descr_set */ - 0, /* tp_dictoffset */ - 0, /* tp_init */ - 0, /* tp_alloc */ - instancemethod_new, /* tp_new */ + PyVarObject_HEAD_INIT(&PyType_Type, 0) + "instancemethod", /* tp_name */ + sizeof(PyInstanceMethodObject), /* tp_basicsize */ + 0, /* tp_itemsize */ + instancemethod_dealloc, /* tp_dealloc */ + 0, /* tp_print */ + 0, /* tp_getattr */ + 0, /* tp_setattr */ + 0, /* tp_reserved */ + (reprfunc)instancemethod_repr, /* tp_repr */ + 0, /* tp_as_number */ + 0, /* tp_as_sequence */ + 0, /* tp_as_mapping */ + 0, /*(hashfunc)instancemethod_hash, tp_hash */ + instancemethod_call, /* tp_call */ + 0, /* tp_str */ + instancemethod_getattro, /* tp_getattro */ + PyObject_GenericSetAttr, /* tp_setattro */ + 0, /* tp_as_buffer */ + Py_TPFLAGS_DEFAULT + | Py_TPFLAGS_HAVE_GC, /* tp_flags */ + instancemethod_doc, /* tp_doc */ + instancemethod_traverse, /* tp_traverse */ + 0, /* tp_clear */ + instancemethod_richcompare, /* tp_richcompare */ + 0, /* tp_weaklistoffset */ + 0, /* tp_iter */ + 0, /* tp_iternext */ + 0, /* tp_methods */ + instancemethod_memberlist, /* tp_members */ + instancemethod_getset, /* tp_getset */ + 0, /* tp_base */ + 0, /* tp_dict */ + instancemethod_descr_get, /* tp_descr_get */ + 0, /* tp_descr_set */ + 0, /* tp_dictoffset */ + 0, /* tp_init */ + 0, /* tp_alloc */ + instancemethod_new, /* tp_new */ }; Modified: python/branches/py3k-jit/Objects/codeobject.c ============================================================================== --- python/branches/py3k-jit/Objects/codeobject.c (original) +++ python/branches/py3k-jit/Objects/codeobject.c Mon May 10 23:55:43 2010 @@ -3,183 +3,183 @@ #include "structmember.h" #define NAME_CHARS \ - "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ_abcdefghijklmnopqrstuvwxyz" + "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ_abcdefghijklmnopqrstuvwxyz" /* all_name_chars(s): true iff all chars in s are valid NAME_CHARS */ static int all_name_chars(Py_UNICODE *s) { - static char ok_name_char[256]; - static unsigned char *name_chars = (unsigned char *)NAME_CHARS; + static char ok_name_char[256]; + static unsigned char *name_chars = (unsigned char *)NAME_CHARS; - if (ok_name_char[*name_chars] == 0) { - unsigned char *p; - for (p = name_chars; *p; p++) - ok_name_char[*p] = 1; - } - while (*s) { - if (*s >= 128) - return 0; - if (ok_name_char[*s++] == 0) - return 0; - } - return 1; + if (ok_name_char[*name_chars] == 0) { + unsigned char *p; + for (p = name_chars; *p; p++) + ok_name_char[*p] = 1; + } + while (*s) { + if (*s >= 128) + return 0; + if (ok_name_char[*s++] == 0) + return 0; + } + return 1; } static void intern_strings(PyObject *tuple) { - Py_ssize_t i; + Py_ssize_t i; - for (i = PyTuple_GET_SIZE(tuple); --i >= 0; ) { - PyObject *v = PyTuple_GET_ITEM(tuple, i); - if (v == NULL || !PyUnicode_CheckExact(v)) { - Py_FatalError("non-string found in code slot"); - } - PyUnicode_InternInPlace(&PyTuple_GET_ITEM(tuple, i)); - } + for (i = PyTuple_GET_SIZE(tuple); --i >= 0; ) { + PyObject *v = PyTuple_GET_ITEM(tuple, i); + if (v == NULL || !PyUnicode_CheckExact(v)) { + Py_FatalError("non-string found in code slot"); + } + PyUnicode_InternInPlace(&PyTuple_GET_ITEM(tuple, i)); + } } PyCodeObject * PyCode_New(int argcount, int kwonlyargcount, - int nlocals, int stacksize, int flags, - PyObject *code, PyObject *consts, PyObject *names, - PyObject *varnames, PyObject *freevars, PyObject *cellvars, - PyObject *filename, PyObject *name, int firstlineno, - PyObject *lnotab) -{ - PyCodeObject *co; - Py_ssize_t i; - - /* Check argument types */ - if (argcount < 0 || kwonlyargcount < 0 || nlocals < 0 || - code == NULL || - consts == NULL || !PyTuple_Check(consts) || - names == NULL || !PyTuple_Check(names) || - varnames == NULL || !PyTuple_Check(varnames) || - freevars == NULL || !PyTuple_Check(freevars) || - cellvars == NULL || !PyTuple_Check(cellvars) || - name == NULL || !PyUnicode_Check(name) || - filename == NULL || !PyUnicode_Check(filename) || - lnotab == NULL || !PyBytes_Check(lnotab) || - !PyObject_CheckReadBuffer(code)) { - PyErr_BadInternalCall(); - return NULL; - } - intern_strings(names); - intern_strings(varnames); - intern_strings(freevars); - intern_strings(cellvars); - /* Intern selected string constants */ - for (i = PyTuple_Size(consts); --i >= 0; ) { - PyObject *v = PyTuple_GetItem(consts, i); - if (!PyUnicode_Check(v)) - continue; - if (!all_name_chars(PyUnicode_AS_UNICODE(v))) - continue; - PyUnicode_InternInPlace(&PyTuple_GET_ITEM(consts, i)); - } - co = PyObject_NEW(PyCodeObject, &PyCode_Type); - if (co != NULL) { - co->co_argcount = argcount; - co->co_kwonlyargcount = kwonlyargcount; - co->co_nlocals = nlocals; - co->co_stacksize = stacksize; - co->co_flags = flags; - Py_INCREF(code); - co->co_code = code; - Py_INCREF(consts); - co->co_consts = consts; - Py_INCREF(names); - co->co_names = names; - Py_INCREF(varnames); - co->co_varnames = varnames; - Py_INCREF(freevars); - co->co_freevars = freevars; - Py_INCREF(cellvars); - co->co_cellvars = cellvars; - Py_INCREF(filename); - co->co_filename = filename; - Py_INCREF(name); - co->co_name = name; - co->co_firstlineno = firstlineno; - Py_INCREF(lnotab); - co->co_lnotab = lnotab; - co->co_zombieframe = NULL; - co->co_weakreflist = NULL; - } - return co; + int nlocals, int stacksize, int flags, + PyObject *code, PyObject *consts, PyObject *names, + PyObject *varnames, PyObject *freevars, PyObject *cellvars, + PyObject *filename, PyObject *name, int firstlineno, + PyObject *lnotab) +{ + PyCodeObject *co; + Py_ssize_t i; + + /* Check argument types */ + if (argcount < 0 || kwonlyargcount < 0 || nlocals < 0 || + code == NULL || + consts == NULL || !PyTuple_Check(consts) || + names == NULL || !PyTuple_Check(names) || + varnames == NULL || !PyTuple_Check(varnames) || + freevars == NULL || !PyTuple_Check(freevars) || + cellvars == NULL || !PyTuple_Check(cellvars) || + name == NULL || !PyUnicode_Check(name) || + filename == NULL || !PyUnicode_Check(filename) || + lnotab == NULL || !PyBytes_Check(lnotab) || + !PyObject_CheckReadBuffer(code)) { + PyErr_BadInternalCall(); + return NULL; + } + intern_strings(names); + intern_strings(varnames); + intern_strings(freevars); + intern_strings(cellvars); + /* Intern selected string constants */ + for (i = PyTuple_Size(consts); --i >= 0; ) { + PyObject *v = PyTuple_GetItem(consts, i); + if (!PyUnicode_Check(v)) + continue; + if (!all_name_chars(PyUnicode_AS_UNICODE(v))) + continue; + PyUnicode_InternInPlace(&PyTuple_GET_ITEM(consts, i)); + } + co = PyObject_NEW(PyCodeObject, &PyCode_Type); + if (co != NULL) { + co->co_argcount = argcount; + co->co_kwonlyargcount = kwonlyargcount; + co->co_nlocals = nlocals; + co->co_stacksize = stacksize; + co->co_flags = flags; + Py_INCREF(code); + co->co_code = code; + Py_INCREF(consts); + co->co_consts = consts; + Py_INCREF(names); + co->co_names = names; + Py_INCREF(varnames); + co->co_varnames = varnames; + Py_INCREF(freevars); + co->co_freevars = freevars; + Py_INCREF(cellvars); + co->co_cellvars = cellvars; + Py_INCREF(filename); + co->co_filename = filename; + Py_INCREF(name); + co->co_name = name; + co->co_firstlineno = firstlineno; + Py_INCREF(lnotab); + co->co_lnotab = lnotab; + co->co_zombieframe = NULL; + co->co_weakreflist = NULL; + } + return co; } PyCodeObject * PyCode_NewEmpty(const char *filename, const char *funcname, int firstlineno) { - static PyObject *emptystring = NULL; - static PyObject *nulltuple = NULL; - PyObject *filename_ob = NULL; - PyObject *funcname_ob = NULL; - PyCodeObject *result = NULL; - if (emptystring == NULL) { - emptystring = PyBytes_FromString(""); - if (emptystring == NULL) - goto failed; - } - if (nulltuple == NULL) { - nulltuple = PyTuple_New(0); - if (nulltuple == NULL) - goto failed; - } - funcname_ob = PyUnicode_FromString(funcname); - if (funcname_ob == NULL) - goto failed; - filename_ob = PyUnicode_DecodeFSDefault(filename); - if (filename_ob == NULL) - goto failed; - - result = PyCode_New(0, /* argcount */ - 0, /* kwonlyargcount */ - 0, /* nlocals */ - 0, /* stacksize */ - 0, /* flags */ - emptystring, /* code */ - nulltuple, /* consts */ - nulltuple, /* names */ - nulltuple, /* varnames */ - nulltuple, /* freevars */ - nulltuple, /* cellvars */ - filename_ob, /* filename */ - funcname_ob, /* name */ - firstlineno, /* firstlineno */ - emptystring /* lnotab */ - ); + static PyObject *emptystring = NULL; + static PyObject *nulltuple = NULL; + PyObject *filename_ob = NULL; + PyObject *funcname_ob = NULL; + PyCodeObject *result = NULL; + if (emptystring == NULL) { + emptystring = PyBytes_FromString(""); + if (emptystring == NULL) + goto failed; + } + if (nulltuple == NULL) { + nulltuple = PyTuple_New(0); + if (nulltuple == NULL) + goto failed; + } + funcname_ob = PyUnicode_FromString(funcname); + if (funcname_ob == NULL) + goto failed; + filename_ob = PyUnicode_DecodeFSDefault(filename); + if (filename_ob == NULL) + goto failed; + + result = PyCode_New(0, /* argcount */ + 0, /* kwonlyargcount */ + 0, /* nlocals */ + 0, /* stacksize */ + 0, /* flags */ + emptystring, /* code */ + nulltuple, /* consts */ + nulltuple, /* names */ + nulltuple, /* varnames */ + nulltuple, /* freevars */ + nulltuple, /* cellvars */ + filename_ob, /* filename */ + funcname_ob, /* name */ + firstlineno, /* firstlineno */ + emptystring /* lnotab */ + ); failed: - Py_XDECREF(funcname_ob); - Py_XDECREF(filename_ob); - return result; + Py_XDECREF(funcname_ob); + Py_XDECREF(filename_ob); + return result; } #define OFF(x) offsetof(PyCodeObject, x) static PyMemberDef code_memberlist[] = { - {"co_argcount", T_INT, OFF(co_argcount), READONLY}, - {"co_kwonlyargcount", T_INT, OFF(co_kwonlyargcount), READONLY}, - {"co_nlocals", T_INT, OFF(co_nlocals), READONLY}, - {"co_stacksize",T_INT, OFF(co_stacksize), READONLY}, - {"co_flags", T_INT, OFF(co_flags), READONLY}, - {"co_code", T_OBJECT, OFF(co_code), READONLY}, - {"co_consts", T_OBJECT, OFF(co_consts), READONLY}, - {"co_names", T_OBJECT, OFF(co_names), READONLY}, - {"co_varnames", T_OBJECT, OFF(co_varnames), READONLY}, - {"co_freevars", T_OBJECT, OFF(co_freevars), READONLY}, - {"co_cellvars", T_OBJECT, OFF(co_cellvars), READONLY}, - {"co_filename", T_OBJECT, OFF(co_filename), READONLY}, - {"co_name", T_OBJECT, OFF(co_name), READONLY}, - {"co_firstlineno", T_INT, OFF(co_firstlineno), READONLY}, - {"co_lnotab", T_OBJECT, OFF(co_lnotab), READONLY}, - {NULL} /* Sentinel */ + {"co_argcount", T_INT, OFF(co_argcount), READONLY}, + {"co_kwonlyargcount", T_INT, OFF(co_kwonlyargcount), READONLY}, + {"co_nlocals", T_INT, OFF(co_nlocals), READONLY}, + {"co_stacksize",T_INT, OFF(co_stacksize), READONLY}, + {"co_flags", T_INT, OFF(co_flags), READONLY}, + {"co_code", T_OBJECT, OFF(co_code), READONLY}, + {"co_consts", T_OBJECT, OFF(co_consts), READONLY}, + {"co_names", T_OBJECT, OFF(co_names), READONLY}, + {"co_varnames", T_OBJECT, OFF(co_varnames), READONLY}, + {"co_freevars", T_OBJECT, OFF(co_freevars), READONLY}, + {"co_cellvars", T_OBJECT, OFF(co_cellvars), READONLY}, + {"co_filename", T_OBJECT, OFF(co_filename), READONLY}, + {"co_name", T_OBJECT, OFF(co_name), READONLY}, + {"co_firstlineno", T_INT, OFF(co_firstlineno), READONLY}, + {"co_lnotab", T_OBJECT, OFF(co_lnotab), READONLY}, + {NULL} /* Sentinel */ }; /* Helper for code_new: return a shallow copy of a tuple that is @@ -188,42 +188,42 @@ static PyObject* validate_and_copy_tuple(PyObject *tup) { - PyObject *newtuple; - PyObject *item; - Py_ssize_t i, len; - - len = PyTuple_GET_SIZE(tup); - newtuple = PyTuple_New(len); - if (newtuple == NULL) - return NULL; - - for (i = 0; i < len; i++) { - item = PyTuple_GET_ITEM(tup, i); - if (PyUnicode_CheckExact(item)) { - Py_INCREF(item); - } - else if (!PyUnicode_Check(item)) { - PyErr_Format( - PyExc_TypeError, - "name tuples must contain only " - "strings, not '%.500s'", - item->ob_type->tp_name); - Py_DECREF(newtuple); - return NULL; - } - else { - item = PyUnicode_FromUnicode( - PyUnicode_AS_UNICODE(item), - PyUnicode_GET_SIZE(item)); - if (item == NULL) { - Py_DECREF(newtuple); - return NULL; - } - } - PyTuple_SET_ITEM(newtuple, i, item); - } + PyObject *newtuple; + PyObject *item; + Py_ssize_t i, len; + + len = PyTuple_GET_SIZE(tup); + newtuple = PyTuple_New(len); + if (newtuple == NULL) + return NULL; + + for (i = 0; i < len; i++) { + item = PyTuple_GET_ITEM(tup, i); + if (PyUnicode_CheckExact(item)) { + Py_INCREF(item); + } + else if (!PyUnicode_Check(item)) { + PyErr_Format( + PyExc_TypeError, + "name tuples must contain only " + "strings, not '%.500s'", + item->ob_type->tp_name); + Py_DECREF(newtuple); + return NULL; + } + else { + item = PyUnicode_FromUnicode( + PyUnicode_AS_UNICODE(item), + PyUnicode_GET_SIZE(item)); + if (item == NULL) { + Py_DECREF(newtuple); + return NULL; + } + } + PyTuple_SET_ITEM(newtuple, i, item); + } - return newtuple; + return newtuple; } PyDoc_STRVAR(code_doc, @@ -236,253 +236,253 @@ static PyObject * code_new(PyTypeObject *type, PyObject *args, PyObject *kw) { - int argcount; - int kwonlyargcount; - int nlocals; - int stacksize; - int flags; - PyObject *co = NULL; - PyObject *code; - PyObject *consts; - PyObject *names, *ournames = NULL; - PyObject *varnames, *ourvarnames = NULL; - PyObject *freevars = NULL, *ourfreevars = NULL; - PyObject *cellvars = NULL, *ourcellvars = NULL; - PyObject *filename; - PyObject *name; - int firstlineno; - PyObject *lnotab; - - if (!PyArg_ParseTuple(args, "iiiiiSO!O!O!UUiS|O!O!:code", - &argcount, &kwonlyargcount, - &nlocals, &stacksize, &flags, - &code, - &PyTuple_Type, &consts, - &PyTuple_Type, &names, - &PyTuple_Type, &varnames, - &filename, &name, - &firstlineno, &lnotab, - &PyTuple_Type, &freevars, - &PyTuple_Type, &cellvars)) - return NULL; - - if (argcount < 0) { - PyErr_SetString( - PyExc_ValueError, - "code: argcount must not be negative"); - goto cleanup; - } - - if (kwonlyargcount < 0) { - PyErr_SetString( - PyExc_ValueError, - "code: kwonlyargcount must not be negative"); - goto cleanup; - } - if (nlocals < 0) { - PyErr_SetString( - PyExc_ValueError, - "code: nlocals must not be negative"); - goto cleanup; - } - - ournames = validate_and_copy_tuple(names); - if (ournames == NULL) - goto cleanup; - ourvarnames = validate_and_copy_tuple(varnames); - if (ourvarnames == NULL) - goto cleanup; - if (freevars) - ourfreevars = validate_and_copy_tuple(freevars); - else - ourfreevars = PyTuple_New(0); - if (ourfreevars == NULL) - goto cleanup; - if (cellvars) - ourcellvars = validate_and_copy_tuple(cellvars); - else - ourcellvars = PyTuple_New(0); - if (ourcellvars == NULL) - goto cleanup; - - co = (PyObject *)PyCode_New(argcount, kwonlyargcount, - nlocals, stacksize, flags, - code, consts, ournames, ourvarnames, - ourfreevars, ourcellvars, filename, - name, firstlineno, lnotab); + int argcount; + int kwonlyargcount; + int nlocals; + int stacksize; + int flags; + PyObject *co = NULL; + PyObject *code; + PyObject *consts; + PyObject *names, *ournames = NULL; + PyObject *varnames, *ourvarnames = NULL; + PyObject *freevars = NULL, *ourfreevars = NULL; + PyObject *cellvars = NULL, *ourcellvars = NULL; + PyObject *filename; + PyObject *name; + int firstlineno; + PyObject *lnotab; + + if (!PyArg_ParseTuple(args, "iiiiiSO!O!O!UUiS|O!O!:code", + &argcount, &kwonlyargcount, + &nlocals, &stacksize, &flags, + &code, + &PyTuple_Type, &consts, + &PyTuple_Type, &names, + &PyTuple_Type, &varnames, + &filename, &name, + &firstlineno, &lnotab, + &PyTuple_Type, &freevars, + &PyTuple_Type, &cellvars)) + return NULL; + + if (argcount < 0) { + PyErr_SetString( + PyExc_ValueError, + "code: argcount must not be negative"); + goto cleanup; + } + + if (kwonlyargcount < 0) { + PyErr_SetString( + PyExc_ValueError, + "code: kwonlyargcount must not be negative"); + goto cleanup; + } + if (nlocals < 0) { + PyErr_SetString( + PyExc_ValueError, + "code: nlocals must not be negative"); + goto cleanup; + } + + ournames = validate_and_copy_tuple(names); + if (ournames == NULL) + goto cleanup; + ourvarnames = validate_and_copy_tuple(varnames); + if (ourvarnames == NULL) + goto cleanup; + if (freevars) + ourfreevars = validate_and_copy_tuple(freevars); + else + ourfreevars = PyTuple_New(0); + if (ourfreevars == NULL) + goto cleanup; + if (cellvars) + ourcellvars = validate_and_copy_tuple(cellvars); + else + ourcellvars = PyTuple_New(0); + if (ourcellvars == NULL) + goto cleanup; + + co = (PyObject *)PyCode_New(argcount, kwonlyargcount, + nlocals, stacksize, flags, + code, consts, ournames, ourvarnames, + ourfreevars, ourcellvars, filename, + name, firstlineno, lnotab); cleanup: - Py_XDECREF(ournames); - Py_XDECREF(ourvarnames); - Py_XDECREF(ourfreevars); - Py_XDECREF(ourcellvars); - return co; + Py_XDECREF(ournames); + Py_XDECREF(ourvarnames); + Py_XDECREF(ourfreevars); + Py_XDECREF(ourcellvars); + return co; } static void code_dealloc(PyCodeObject *co) { - Py_XDECREF(co->co_code); - Py_XDECREF(co->co_consts); - Py_XDECREF(co->co_names); - Py_XDECREF(co->co_varnames); - Py_XDECREF(co->co_freevars); - Py_XDECREF(co->co_cellvars); - Py_XDECREF(co->co_filename); - Py_XDECREF(co->co_name); - Py_XDECREF(co->co_lnotab); - if (co->co_zombieframe != NULL) - PyObject_GC_Del(co->co_zombieframe); - if (co->co_weakreflist != NULL) - PyObject_ClearWeakRefs((PyObject*)co); - PyObject_DEL(co); + Py_XDECREF(co->co_code); + Py_XDECREF(co->co_consts); + Py_XDECREF(co->co_names); + Py_XDECREF(co->co_varnames); + Py_XDECREF(co->co_freevars); + Py_XDECREF(co->co_cellvars); + Py_XDECREF(co->co_filename); + Py_XDECREF(co->co_name); + Py_XDECREF(co->co_lnotab); + if (co->co_zombieframe != NULL) + PyObject_GC_Del(co->co_zombieframe); + if (co->co_weakreflist != NULL) + PyObject_ClearWeakRefs((PyObject*)co); + PyObject_DEL(co); } static PyObject * code_repr(PyCodeObject *co) { - int lineno; - if (co->co_firstlineno != 0) - lineno = co->co_firstlineno; - else - lineno = -1; - if (co->co_filename && PyUnicode_Check(co->co_filename)) { - return PyUnicode_FromFormat( - "", - co->co_name, co, co->co_filename, lineno); - } else { - return PyUnicode_FromFormat( - "", - co->co_name, co, lineno); - } + int lineno; + if (co->co_firstlineno != 0) + lineno = co->co_firstlineno; + else + lineno = -1; + if (co->co_filename && PyUnicode_Check(co->co_filename)) { + return PyUnicode_FromFormat( + "", + co->co_name, co, co->co_filename, lineno); + } else { + return PyUnicode_FromFormat( + "", + co->co_name, co, lineno); + } } static PyObject * code_richcompare(PyObject *self, PyObject *other, int op) { - PyCodeObject *co, *cp; - int eq; - PyObject *res; - - if ((op != Py_EQ && op != Py_NE) || - !PyCode_Check(self) || - !PyCode_Check(other)) { - Py_INCREF(Py_NotImplemented); - return Py_NotImplemented; - } - - co = (PyCodeObject *)self; - cp = (PyCodeObject *)other; - - eq = PyObject_RichCompareBool(co->co_name, cp->co_name, Py_EQ); - if (eq <= 0) goto unequal; - eq = co->co_argcount == cp->co_argcount; - if (!eq) goto unequal; - eq = co->co_kwonlyargcount == cp->co_kwonlyargcount; - if (!eq) goto unequal; - eq = co->co_nlocals == cp->co_nlocals; - if (!eq) goto unequal; - eq = co->co_flags == cp->co_flags; - if (!eq) goto unequal; - eq = co->co_firstlineno == cp->co_firstlineno; - if (!eq) goto unequal; - eq = PyObject_RichCompareBool(co->co_code, cp->co_code, Py_EQ); - if (eq <= 0) goto unequal; - eq = PyObject_RichCompareBool(co->co_consts, cp->co_consts, Py_EQ); - if (eq <= 0) goto unequal; - eq = PyObject_RichCompareBool(co->co_names, cp->co_names, Py_EQ); - if (eq <= 0) goto unequal; - eq = PyObject_RichCompareBool(co->co_varnames, cp->co_varnames, Py_EQ); - if (eq <= 0) goto unequal; - eq = PyObject_RichCompareBool(co->co_freevars, cp->co_freevars, Py_EQ); - if (eq <= 0) goto unequal; - eq = PyObject_RichCompareBool(co->co_cellvars, cp->co_cellvars, Py_EQ); - if (eq <= 0) goto unequal; - - if (op == Py_EQ) - res = Py_True; - else - res = Py_False; - goto done; + PyCodeObject *co, *cp; + int eq; + PyObject *res; + + if ((op != Py_EQ && op != Py_NE) || + !PyCode_Check(self) || + !PyCode_Check(other)) { + Py_INCREF(Py_NotImplemented); + return Py_NotImplemented; + } + + co = (PyCodeObject *)self; + cp = (PyCodeObject *)other; + + eq = PyObject_RichCompareBool(co->co_name, cp->co_name, Py_EQ); + if (eq <= 0) goto unequal; + eq = co->co_argcount == cp->co_argcount; + if (!eq) goto unequal; + eq = co->co_kwonlyargcount == cp->co_kwonlyargcount; + if (!eq) goto unequal; + eq = co->co_nlocals == cp->co_nlocals; + if (!eq) goto unequal; + eq = co->co_flags == cp->co_flags; + if (!eq) goto unequal; + eq = co->co_firstlineno == cp->co_firstlineno; + if (!eq) goto unequal; + eq = PyObject_RichCompareBool(co->co_code, cp->co_code, Py_EQ); + if (eq <= 0) goto unequal; + eq = PyObject_RichCompareBool(co->co_consts, cp->co_consts, Py_EQ); + if (eq <= 0) goto unequal; + eq = PyObject_RichCompareBool(co->co_names, cp->co_names, Py_EQ); + if (eq <= 0) goto unequal; + eq = PyObject_RichCompareBool(co->co_varnames, cp->co_varnames, Py_EQ); + if (eq <= 0) goto unequal; + eq = PyObject_RichCompareBool(co->co_freevars, cp->co_freevars, Py_EQ); + if (eq <= 0) goto unequal; + eq = PyObject_RichCompareBool(co->co_cellvars, cp->co_cellvars, Py_EQ); + if (eq <= 0) goto unequal; + + if (op == Py_EQ) + res = Py_True; + else + res = Py_False; + goto done; unequal: - if (eq < 0) - return NULL; - if (op == Py_NE) - res = Py_True; - else - res = Py_False; + if (eq < 0) + return NULL; + if (op == Py_NE) + res = Py_True; + else + res = Py_False; done: - Py_INCREF(res); - return res; + Py_INCREF(res); + return res; } static long code_hash(PyCodeObject *co) { - long h, h0, h1, h2, h3, h4, h5, h6; - h0 = PyObject_Hash(co->co_name); - if (h0 == -1) return -1; - h1 = PyObject_Hash(co->co_code); - if (h1 == -1) return -1; - h2 = PyObject_Hash(co->co_consts); - if (h2 == -1) return -1; - h3 = PyObject_Hash(co->co_names); - if (h3 == -1) return -1; - h4 = PyObject_Hash(co->co_varnames); - if (h4 == -1) return -1; - h5 = PyObject_Hash(co->co_freevars); - if (h5 == -1) return -1; - h6 = PyObject_Hash(co->co_cellvars); - if (h6 == -1) return -1; - h = h0 ^ h1 ^ h2 ^ h3 ^ h4 ^ h5 ^ h6 ^ - co->co_argcount ^ co->co_kwonlyargcount ^ - co->co_nlocals ^ co->co_flags; - if (h == -1) h = -2; - return h; + long h, h0, h1, h2, h3, h4, h5, h6; + h0 = PyObject_Hash(co->co_name); + if (h0 == -1) return -1; + h1 = PyObject_Hash(co->co_code); + if (h1 == -1) return -1; + h2 = PyObject_Hash(co->co_consts); + if (h2 == -1) return -1; + h3 = PyObject_Hash(co->co_names); + if (h3 == -1) return -1; + h4 = PyObject_Hash(co->co_varnames); + if (h4 == -1) return -1; + h5 = PyObject_Hash(co->co_freevars); + if (h5 == -1) return -1; + h6 = PyObject_Hash(co->co_cellvars); + if (h6 == -1) return -1; + h = h0 ^ h1 ^ h2 ^ h3 ^ h4 ^ h5 ^ h6 ^ + co->co_argcount ^ co->co_kwonlyargcount ^ + co->co_nlocals ^ co->co_flags; + if (h == -1) h = -2; + return h; } /* XXX code objects need to participate in GC? */ PyTypeObject PyCode_Type = { - PyVarObject_HEAD_INIT(&PyType_Type, 0) - "code", - sizeof(PyCodeObject), - 0, - (destructor)code_dealloc, /* tp_dealloc */ - 0, /* tp_print */ - 0, /* tp_getattr */ - 0, /* tp_setattr */ - 0, /* tp_reserved */ - (reprfunc)code_repr, /* tp_repr */ - 0, /* tp_as_number */ - 0, /* tp_as_sequence */ - 0, /* tp_as_mapping */ - (hashfunc)code_hash, /* tp_hash */ - 0, /* tp_call */ - 0, /* tp_str */ - PyObject_GenericGetAttr, /* tp_getattro */ - 0, /* tp_setattro */ - 0, /* tp_as_buffer */ - Py_TPFLAGS_DEFAULT, /* tp_flags */ - code_doc, /* tp_doc */ - 0, /* tp_traverse */ - 0, /* tp_clear */ - code_richcompare, /* tp_richcompare */ - offsetof(PyCodeObject, co_weakreflist), /* tp_weaklistoffset */ - 0, /* tp_iter */ - 0, /* tp_iternext */ - 0, /* tp_methods */ - code_memberlist, /* tp_members */ - 0, /* tp_getset */ - 0, /* tp_base */ - 0, /* tp_dict */ - 0, /* tp_descr_get */ - 0, /* tp_descr_set */ - 0, /* tp_dictoffset */ - 0, /* tp_init */ - 0, /* tp_alloc */ - code_new, /* tp_new */ + PyVarObject_HEAD_INIT(&PyType_Type, 0) + "code", + sizeof(PyCodeObject), + 0, + (destructor)code_dealloc, /* tp_dealloc */ + 0, /* tp_print */ + 0, /* tp_getattr */ + 0, /* tp_setattr */ + 0, /* tp_reserved */ + (reprfunc)code_repr, /* tp_repr */ + 0, /* tp_as_number */ + 0, /* tp_as_sequence */ + 0, /* tp_as_mapping */ + (hashfunc)code_hash, /* tp_hash */ + 0, /* tp_call */ + 0, /* tp_str */ + PyObject_GenericGetAttr, /* tp_getattro */ + 0, /* tp_setattro */ + 0, /* tp_as_buffer */ + Py_TPFLAGS_DEFAULT, /* tp_flags */ + code_doc, /* tp_doc */ + 0, /* tp_traverse */ + 0, /* tp_clear */ + code_richcompare, /* tp_richcompare */ + offsetof(PyCodeObject, co_weakreflist), /* tp_weaklistoffset */ + 0, /* tp_iter */ + 0, /* tp_iternext */ + 0, /* tp_methods */ + code_memberlist, /* tp_members */ + 0, /* tp_getset */ + 0, /* tp_base */ + 0, /* tp_dict */ + 0, /* tp_descr_get */ + 0, /* tp_descr_set */ + 0, /* tp_dictoffset */ + 0, /* tp_init */ + 0, /* tp_alloc */ + code_new, /* tp_new */ }; /* Use co_lnotab to compute the line number from a bytecode index, addrq. See @@ -492,17 +492,17 @@ int PyCode_Addr2Line(PyCodeObject *co, int addrq) { - int size = PyBytes_Size(co->co_lnotab) / 2; - unsigned char *p = (unsigned char*)PyBytes_AsString(co->co_lnotab); - int line = co->co_firstlineno; - int addr = 0; - while (--size >= 0) { - addr += *p++; - if (addr > addrq) - break; - line += *p++; - } - return line; + int size = PyBytes_Size(co->co_lnotab) / 2; + unsigned char *p = (unsigned char*)PyBytes_AsString(co->co_lnotab); + int line = co->co_firstlineno; + int addr = 0; + while (--size >= 0) { + addr += *p++; + if (addr > addrq) + break; + line += *p++; + } + return line; } /* Update *bounds to describe the first and one-past-the-last instructions in @@ -510,47 +510,47 @@ int _PyCode_CheckLineNumber(PyCodeObject* co, int lasti, PyAddrPair *bounds) { - int size, addr, line; - unsigned char* p; + int size, addr, line; + unsigned char* p; - p = (unsigned char*)PyBytes_AS_STRING(co->co_lnotab); - size = PyBytes_GET_SIZE(co->co_lnotab) / 2; + p = (unsigned char*)PyBytes_AS_STRING(co->co_lnotab); + size = PyBytes_GET_SIZE(co->co_lnotab) / 2; - addr = 0; - line = co->co_firstlineno; - assert(line > 0); - - /* possible optimization: if f->f_lasti == instr_ub - (likely to be a common case) then we already know - instr_lb -- if we stored the matching value of p - somwhere we could skip the first while loop. */ - - /* See lnotab_notes.txt for the description of - co_lnotab. A point to remember: increments to p - come in (addr, line) pairs. */ - - bounds->ap_lower = 0; - while (size > 0) { - if (addr + *p > lasti) - break; - addr += *p++; - if (*p) - bounds->ap_lower = addr; - line += *p++; - --size; - } - - if (size > 0) { - while (--size >= 0) { - addr += *p++; - if (*p++) - break; - } - bounds->ap_upper = addr; - } - else { - bounds->ap_upper = INT_MAX; + addr = 0; + line = co->co_firstlineno; + assert(line > 0); + + /* possible optimization: if f->f_lasti == instr_ub + (likely to be a common case) then we already know + instr_lb -- if we stored the matching value of p + somwhere we could skip the first while loop. */ + + /* See lnotab_notes.txt for the description of + co_lnotab. A point to remember: increments to p + come in (addr, line) pairs. */ + + bounds->ap_lower = 0; + while (size > 0) { + if (addr + *p > lasti) + break; + addr += *p++; + if (*p) + bounds->ap_lower = addr; + line += *p++; + --size; + } + + if (size > 0) { + while (--size >= 0) { + addr += *p++; + if (*p++) + break; } + bounds->ap_upper = addr; + } + else { + bounds->ap_upper = INT_MAX; + } - return line; + return line; } Modified: python/branches/py3k-jit/Objects/complexobject.c ============================================================================== --- python/branches/py3k-jit/Objects/complexobject.c (original) +++ python/branches/py3k-jit/Objects/complexobject.c Mon May 10 23:55:43 2010 @@ -15,377 +15,377 @@ Py_complex c_sum(Py_complex a, Py_complex b) { - Py_complex r; - r.real = a.real + b.real; - r.imag = a.imag + b.imag; - return r; + Py_complex r; + r.real = a.real + b.real; + r.imag = a.imag + b.imag; + return r; } Py_complex c_diff(Py_complex a, Py_complex b) { - Py_complex r; - r.real = a.real - b.real; - r.imag = a.imag - b.imag; - return r; + Py_complex r; + r.real = a.real - b.real; + r.imag = a.imag - b.imag; + return r; } Py_complex c_neg(Py_complex a) { - Py_complex r; - r.real = -a.real; - r.imag = -a.imag; - return r; + Py_complex r; + r.real = -a.real; + r.imag = -a.imag; + return r; } Py_complex c_prod(Py_complex a, Py_complex b) { - Py_complex r; - r.real = a.real*b.real - a.imag*b.imag; - r.imag = a.real*b.imag + a.imag*b.real; - return r; + Py_complex r; + r.real = a.real*b.real - a.imag*b.imag; + r.imag = a.real*b.imag + a.imag*b.real; + return r; } Py_complex c_quot(Py_complex a, Py_complex b) { - /****************************************************************** - This was the original algorithm. It's grossly prone to spurious - overflow and underflow errors. It also merrily divides by 0 despite - checking for that(!). The code still serves a doc purpose here, as - the algorithm following is a simple by-cases transformation of this - one: - - Py_complex r; - double d = b.real*b.real + b.imag*b.imag; - if (d == 0.) - errno = EDOM; - r.real = (a.real*b.real + a.imag*b.imag)/d; - r.imag = (a.imag*b.real - a.real*b.imag)/d; - return r; - ******************************************************************/ - - /* This algorithm is better, and is pretty obvious: first divide the - * numerators and denominator by whichever of {b.real, b.imag} has - * larger magnitude. The earliest reference I found was to CACM - * Algorithm 116 (Complex Division, Robert L. Smith, Stanford - * University). As usual, though, we're still ignoring all IEEE - * endcases. - */ - Py_complex r; /* the result */ - const double abs_breal = b.real < 0 ? -b.real : b.real; - const double abs_bimag = b.imag < 0 ? -b.imag : b.imag; - - if (abs_breal >= abs_bimag) { - /* divide tops and bottom by b.real */ - if (abs_breal == 0.0) { - errno = EDOM; - r.real = r.imag = 0.0; - } - else { - const double ratio = b.imag / b.real; - const double denom = b.real + b.imag * ratio; - r.real = (a.real + a.imag * ratio) / denom; - r.imag = (a.imag - a.real * ratio) / denom; - } - } - else { - /* divide tops and bottom by b.imag */ - const double ratio = b.real / b.imag; - const double denom = b.real * ratio + b.imag; - assert(b.imag != 0.0); - r.real = (a.real * ratio + a.imag) / denom; - r.imag = (a.imag * ratio - a.real) / denom; - } - return r; + /****************************************************************** + This was the original algorithm. It's grossly prone to spurious + overflow and underflow errors. It also merrily divides by 0 despite + checking for that(!). The code still serves a doc purpose here, as + the algorithm following is a simple by-cases transformation of this + one: + + Py_complex r; + double d = b.real*b.real + b.imag*b.imag; + if (d == 0.) + errno = EDOM; + r.real = (a.real*b.real + a.imag*b.imag)/d; + r.imag = (a.imag*b.real - a.real*b.imag)/d; + return r; + ******************************************************************/ + + /* This algorithm is better, and is pretty obvious: first divide the + * numerators and denominator by whichever of {b.real, b.imag} has + * larger magnitude. The earliest reference I found was to CACM + * Algorithm 116 (Complex Division, Robert L. Smith, Stanford + * University). As usual, though, we're still ignoring all IEEE + * endcases. + */ + Py_complex r; /* the result */ + const double abs_breal = b.real < 0 ? -b.real : b.real; + const double abs_bimag = b.imag < 0 ? -b.imag : b.imag; + + if (abs_breal >= abs_bimag) { + /* divide tops and bottom by b.real */ + if (abs_breal == 0.0) { + errno = EDOM; + r.real = r.imag = 0.0; + } + else { + const double ratio = b.imag / b.real; + const double denom = b.real + b.imag * ratio; + r.real = (a.real + a.imag * ratio) / denom; + r.imag = (a.imag - a.real * ratio) / denom; + } + } + else { + /* divide tops and bottom by b.imag */ + const double ratio = b.real / b.imag; + const double denom = b.real * ratio + b.imag; + assert(b.imag != 0.0); + r.real = (a.real * ratio + a.imag) / denom; + r.imag = (a.imag * ratio - a.real) / denom; + } + return r; } Py_complex c_pow(Py_complex a, Py_complex b) { - Py_complex r; - double vabs,len,at,phase; - if (b.real == 0. && b.imag == 0.) { - r.real = 1.; - r.imag = 0.; - } - else if (a.real == 0. && a.imag == 0.) { - if (b.imag != 0. || b.real < 0.) - errno = EDOM; - r.real = 0.; - r.imag = 0.; - } - else { - vabs = hypot(a.real,a.imag); - len = pow(vabs,b.real); - at = atan2(a.imag, a.real); - phase = at*b.real; - if (b.imag != 0.0) { - len /= exp(at*b.imag); - phase += b.imag*log(vabs); - } - r.real = len*cos(phase); - r.imag = len*sin(phase); - } - return r; + Py_complex r; + double vabs,len,at,phase; + if (b.real == 0. && b.imag == 0.) { + r.real = 1.; + r.imag = 0.; + } + else if (a.real == 0. && a.imag == 0.) { + if (b.imag != 0. || b.real < 0.) + errno = EDOM; + r.real = 0.; + r.imag = 0.; + } + else { + vabs = hypot(a.real,a.imag); + len = pow(vabs,b.real); + at = atan2(a.imag, a.real); + phase = at*b.real; + if (b.imag != 0.0) { + len /= exp(at*b.imag); + phase += b.imag*log(vabs); + } + r.real = len*cos(phase); + r.imag = len*sin(phase); + } + return r; } static Py_complex c_powu(Py_complex x, long n) { - Py_complex r, p; - long mask = 1; - r = c_1; - p = x; - while (mask > 0 && n >= mask) { - if (n & mask) - r = c_prod(r,p); - mask <<= 1; - p = c_prod(p,p); - } - return r; + Py_complex r, p; + long mask = 1; + r = c_1; + p = x; + while (mask > 0 && n >= mask) { + if (n & mask) + r = c_prod(r,p); + mask <<= 1; + p = c_prod(p,p); + } + return r; } static Py_complex c_powi(Py_complex x, long n) { - Py_complex cn; + Py_complex cn; - if (n > 100 || n < -100) { - cn.real = (double) n; - cn.imag = 0.; - return c_pow(x,cn); - } - else if (n > 0) - return c_powu(x,n); - else - return c_quot(c_1,c_powu(x,-n)); + if (n > 100 || n < -100) { + cn.real = (double) n; + cn.imag = 0.; + return c_pow(x,cn); + } + else if (n > 0) + return c_powu(x,n); + else + return c_quot(c_1,c_powu(x,-n)); } double c_abs(Py_complex z) { - /* sets errno = ERANGE on overflow; otherwise errno = 0 */ - double result; + /* sets errno = ERANGE on overflow; otherwise errno = 0 */ + double result; - if (!Py_IS_FINITE(z.real) || !Py_IS_FINITE(z.imag)) { - /* C99 rules: if either the real or the imaginary part is an - infinity, return infinity, even if the other part is a - NaN. */ - if (Py_IS_INFINITY(z.real)) { - result = fabs(z.real); - errno = 0; - return result; - } - if (Py_IS_INFINITY(z.imag)) { - result = fabs(z.imag); - errno = 0; - return result; - } - /* either the real or imaginary part is a NaN, - and neither is infinite. Result should be NaN. */ - return Py_NAN; - } - result = hypot(z.real, z.imag); - if (!Py_IS_FINITE(result)) - errno = ERANGE; - else - errno = 0; - return result; + if (!Py_IS_FINITE(z.real) || !Py_IS_FINITE(z.imag)) { + /* C99 rules: if either the real or the imaginary part is an + infinity, return infinity, even if the other part is a + NaN. */ + if (Py_IS_INFINITY(z.real)) { + result = fabs(z.real); + errno = 0; + return result; + } + if (Py_IS_INFINITY(z.imag)) { + result = fabs(z.imag); + errno = 0; + return result; + } + /* either the real or imaginary part is a NaN, + and neither is infinite. Result should be NaN. */ + return Py_NAN; + } + result = hypot(z.real, z.imag); + if (!Py_IS_FINITE(result)) + errno = ERANGE; + else + errno = 0; + return result; } static PyObject * complex_subtype_from_c_complex(PyTypeObject *type, Py_complex cval) { - PyObject *op; + PyObject *op; - op = type->tp_alloc(type, 0); - if (op != NULL) - ((PyComplexObject *)op)->cval = cval; - return op; + op = type->tp_alloc(type, 0); + if (op != NULL) + ((PyComplexObject *)op)->cval = cval; + return op; } PyObject * PyComplex_FromCComplex(Py_complex cval) { - register PyComplexObject *op; + register PyComplexObject *op; - /* Inline PyObject_New */ - op = (PyComplexObject *) PyObject_MALLOC(sizeof(PyComplexObject)); - if (op == NULL) - return PyErr_NoMemory(); - PyObject_INIT(op, &PyComplex_Type); - op->cval = cval; - return (PyObject *) op; + /* Inline PyObject_New */ + op = (PyComplexObject *) PyObject_MALLOC(sizeof(PyComplexObject)); + if (op == NULL) + return PyErr_NoMemory(); + PyObject_INIT(op, &PyComplex_Type); + op->cval = cval; + return (PyObject *) op; } static PyObject * complex_subtype_from_doubles(PyTypeObject *type, double real, double imag) { - Py_complex c; - c.real = real; - c.imag = imag; - return complex_subtype_from_c_complex(type, c); + Py_complex c; + c.real = real; + c.imag = imag; + return complex_subtype_from_c_complex(type, c); } PyObject * PyComplex_FromDoubles(double real, double imag) { - Py_complex c; - c.real = real; - c.imag = imag; - return PyComplex_FromCComplex(c); + Py_complex c; + c.real = real; + c.imag = imag; + return PyComplex_FromCComplex(c); } double PyComplex_RealAsDouble(PyObject *op) { - if (PyComplex_Check(op)) { - return ((PyComplexObject *)op)->cval.real; - } - else { - return PyFloat_AsDouble(op); - } + if (PyComplex_Check(op)) { + return ((PyComplexObject *)op)->cval.real; + } + else { + return PyFloat_AsDouble(op); + } } double PyComplex_ImagAsDouble(PyObject *op) { - if (PyComplex_Check(op)) { - return ((PyComplexObject *)op)->cval.imag; - } - else { - return 0.0; - } + if (PyComplex_Check(op)) { + return ((PyComplexObject *)op)->cval.imag; + } + else { + return 0.0; + } } static PyObject * try_complex_special_method(PyObject *op) { - PyObject *f; - static PyObject *complexstr; + PyObject *f; + static PyObject *complexstr; - f = _PyObject_LookupSpecial(op, "__complex__", &complexstr); - if (f) { - PyObject *res = PyObject_CallFunctionObjArgs(f, NULL); - Py_DECREF(f); - return res; - } - return NULL; + f = _PyObject_LookupSpecial(op, "__complex__", &complexstr); + if (f) { + PyObject *res = PyObject_CallFunctionObjArgs(f, NULL); + Py_DECREF(f); + return res; + } + return NULL; } Py_complex PyComplex_AsCComplex(PyObject *op) { - Py_complex cv; - PyObject *newop = NULL; + Py_complex cv; + PyObject *newop = NULL; - assert(op); - /* If op is already of type PyComplex_Type, return its value */ - if (PyComplex_Check(op)) { - return ((PyComplexObject *)op)->cval; - } - /* If not, use op's __complex__ method, if it exists */ - - /* return -1 on failure */ - cv.real = -1.; - cv.imag = 0.; - - newop = try_complex_special_method(op); - - if (newop) { - if (!PyComplex_Check(newop)) { - PyErr_SetString(PyExc_TypeError, - "__complex__ should return a complex object"); - Py_DECREF(newop); - return cv; - } - cv = ((PyComplexObject *)newop)->cval; - Py_DECREF(newop); - return cv; - } - else if (PyErr_Occurred()) { - return cv; - } - /* If neither of the above works, interpret op as a float giving the - real part of the result, and fill in the imaginary part as 0. */ - else { - /* PyFloat_AsDouble will return -1 on failure */ - cv.real = PyFloat_AsDouble(op); - return cv; - } + assert(op); + /* If op is already of type PyComplex_Type, return its value */ + if (PyComplex_Check(op)) { + return ((PyComplexObject *)op)->cval; + } + /* If not, use op's __complex__ method, if it exists */ + + /* return -1 on failure */ + cv.real = -1.; + cv.imag = 0.; + + newop = try_complex_special_method(op); + + if (newop) { + if (!PyComplex_Check(newop)) { + PyErr_SetString(PyExc_TypeError, + "__complex__ should return a complex object"); + Py_DECREF(newop); + return cv; + } + cv = ((PyComplexObject *)newop)->cval; + Py_DECREF(newop); + return cv; + } + else if (PyErr_Occurred()) { + return cv; + } + /* If neither of the above works, interpret op as a float giving the + real part of the result, and fill in the imaginary part as 0. */ + else { + /* PyFloat_AsDouble will return -1 on failure */ + cv.real = PyFloat_AsDouble(op); + return cv; + } } static void complex_dealloc(PyObject *op) { - op->ob_type->tp_free(op); + op->ob_type->tp_free(op); } static PyObject * complex_format(PyComplexObject *v, int precision, char format_code) { - PyObject *result = NULL; - Py_ssize_t len; + PyObject *result = NULL; + Py_ssize_t len; - /* If these are non-NULL, they'll need to be freed. */ - char *pre = NULL; - char *im = NULL; - char *buf = NULL; - - /* These do not need to be freed. re is either an alias - for pre or a pointer to a constant. lead and tail - are pointers to constants. */ - char *re = NULL; - char *lead = ""; - char *tail = ""; - - if (v->cval.real == 0. && copysign(1.0, v->cval.real)==1.0) { - re = ""; - im = PyOS_double_to_string(v->cval.imag, format_code, - precision, 0, NULL); - if (!im) { - PyErr_NoMemory(); - goto done; - } - } else { - /* Format imaginary part with sign, real part without */ - pre = PyOS_double_to_string(v->cval.real, format_code, - precision, 0, NULL); - if (!pre) { - PyErr_NoMemory(); - goto done; - } - re = pre; - - im = PyOS_double_to_string(v->cval.imag, format_code, - precision, Py_DTSF_SIGN, NULL); - if (!im) { - PyErr_NoMemory(); - goto done; - } - lead = "("; - tail = ")"; - } - /* Alloc the final buffer. Add one for the "j" in the format string, - and one for the trailing zero. */ - len = strlen(lead) + strlen(re) + strlen(im) + strlen(tail) + 2; - buf = PyMem_Malloc(len); - if (!buf) { - PyErr_NoMemory(); - goto done; - } - PyOS_snprintf(buf, len, "%s%s%sj%s", lead, re, im, tail); - result = PyUnicode_FromString(buf); + /* If these are non-NULL, they'll need to be freed. */ + char *pre = NULL; + char *im = NULL; + char *buf = NULL; + + /* These do not need to be freed. re is either an alias + for pre or a pointer to a constant. lead and tail + are pointers to constants. */ + char *re = NULL; + char *lead = ""; + char *tail = ""; + + if (v->cval.real == 0. && copysign(1.0, v->cval.real)==1.0) { + re = ""; + im = PyOS_double_to_string(v->cval.imag, format_code, + precision, 0, NULL); + if (!im) { + PyErr_NoMemory(); + goto done; + } + } else { + /* Format imaginary part with sign, real part without */ + pre = PyOS_double_to_string(v->cval.real, format_code, + precision, 0, NULL); + if (!pre) { + PyErr_NoMemory(); + goto done; + } + re = pre; + + im = PyOS_double_to_string(v->cval.imag, format_code, + precision, Py_DTSF_SIGN, NULL); + if (!im) { + PyErr_NoMemory(); + goto done; + } + lead = "("; + tail = ")"; + } + /* Alloc the final buffer. Add one for the "j" in the format string, + and one for the trailing zero. */ + len = strlen(lead) + strlen(re) + strlen(im) + strlen(tail) + 2; + buf = PyMem_Malloc(len); + if (!buf) { + PyErr_NoMemory(); + goto done; + } + PyOS_snprintf(buf, len, "%s%s%sj%s", lead, re, im, tail); + result = PyUnicode_FromString(buf); done: - PyMem_Free(im); - PyMem_Free(pre); - PyMem_Free(buf); + PyMem_Free(im); + PyMem_Free(pre); + PyMem_Free(buf); - return result; + return result; } static PyObject * @@ -403,264 +403,264 @@ static long complex_hash(PyComplexObject *v) { - long hashreal, hashimag, combined; - hashreal = _Py_HashDouble(v->cval.real); - if (hashreal == -1) - return -1; - hashimag = _Py_HashDouble(v->cval.imag); - if (hashimag == -1) - return -1; - /* Note: if the imaginary part is 0, hashimag is 0 now, - * so the following returns hashreal unchanged. This is - * important because numbers of different types that - * compare equal must have the same hash value, so that - * hash(x + 0*j) must equal hash(x). - */ - combined = hashreal + 1000003 * hashimag; - if (combined == -1) - combined = -2; - return combined; + long hashreal, hashimag, combined; + hashreal = _Py_HashDouble(v->cval.real); + if (hashreal == -1) + return -1; + hashimag = _Py_HashDouble(v->cval.imag); + if (hashimag == -1) + return -1; + /* Note: if the imaginary part is 0, hashimag is 0 now, + * so the following returns hashreal unchanged. This is + * important because numbers of different types that + * compare equal must have the same hash value, so that + * hash(x + 0*j) must equal hash(x). + */ + combined = hashreal + 1000003 * hashimag; + if (combined == -1) + combined = -2; + return combined; } /* This macro may return! */ #define TO_COMPLEX(obj, c) \ - if (PyComplex_Check(obj)) \ - c = ((PyComplexObject *)(obj))->cval; \ - else if (to_complex(&(obj), &(c)) < 0) \ - return (obj) + if (PyComplex_Check(obj)) \ + c = ((PyComplexObject *)(obj))->cval; \ + else if (to_complex(&(obj), &(c)) < 0) \ + return (obj) static int to_complex(PyObject **pobj, Py_complex *pc) { - PyObject *obj = *pobj; + PyObject *obj = *pobj; - pc->real = pc->imag = 0.0; - if (PyLong_Check(obj)) { - pc->real = PyLong_AsDouble(obj); - if (pc->real == -1.0 && PyErr_Occurred()) { - *pobj = NULL; - return -1; - } - return 0; - } - if (PyFloat_Check(obj)) { - pc->real = PyFloat_AsDouble(obj); - return 0; - } - Py_INCREF(Py_NotImplemented); - *pobj = Py_NotImplemented; - return -1; + pc->real = pc->imag = 0.0; + if (PyLong_Check(obj)) { + pc->real = PyLong_AsDouble(obj); + if (pc->real == -1.0 && PyErr_Occurred()) { + *pobj = NULL; + return -1; + } + return 0; + } + if (PyFloat_Check(obj)) { + pc->real = PyFloat_AsDouble(obj); + return 0; + } + Py_INCREF(Py_NotImplemented); + *pobj = Py_NotImplemented; + return -1; } - + static PyObject * complex_add(PyObject *v, PyObject *w) { - Py_complex result; - Py_complex a, b; - TO_COMPLEX(v, a); - TO_COMPLEX(w, b); - PyFPE_START_PROTECT("complex_add", return 0) - result = c_sum(a, b); - PyFPE_END_PROTECT(result) - return PyComplex_FromCComplex(result); + Py_complex result; + Py_complex a, b; + TO_COMPLEX(v, a); + TO_COMPLEX(w, b); + PyFPE_START_PROTECT("complex_add", return 0) + result = c_sum(a, b); + PyFPE_END_PROTECT(result) + return PyComplex_FromCComplex(result); } static PyObject * complex_sub(PyObject *v, PyObject *w) { - Py_complex result; - Py_complex a, b; - TO_COMPLEX(v, a); - TO_COMPLEX(w, b); - PyFPE_START_PROTECT("complex_sub", return 0) - result = c_diff(a, b); - PyFPE_END_PROTECT(result) - return PyComplex_FromCComplex(result); + Py_complex result; + Py_complex a, b; + TO_COMPLEX(v, a); + TO_COMPLEX(w, b); + PyFPE_START_PROTECT("complex_sub", return 0) + result = c_diff(a, b); + PyFPE_END_PROTECT(result) + return PyComplex_FromCComplex(result); } static PyObject * complex_mul(PyObject *v, PyObject *w) { - Py_complex result; - Py_complex a, b; - TO_COMPLEX(v, a); - TO_COMPLEX(w, b); - PyFPE_START_PROTECT("complex_mul", return 0) - result = c_prod(a, b); - PyFPE_END_PROTECT(result) - return PyComplex_FromCComplex(result); + Py_complex result; + Py_complex a, b; + TO_COMPLEX(v, a); + TO_COMPLEX(w, b); + PyFPE_START_PROTECT("complex_mul", return 0) + result = c_prod(a, b); + PyFPE_END_PROTECT(result) + return PyComplex_FromCComplex(result); } static PyObject * complex_div(PyObject *v, PyObject *w) { - Py_complex quot; - Py_complex a, b; - TO_COMPLEX(v, a); - TO_COMPLEX(w, b); - PyFPE_START_PROTECT("complex_div", return 0) - errno = 0; - quot = c_quot(a, b); - PyFPE_END_PROTECT(quot) - if (errno == EDOM) { - PyErr_SetString(PyExc_ZeroDivisionError, "complex division by zero"); - return NULL; - } - return PyComplex_FromCComplex(quot); + Py_complex quot; + Py_complex a, b; + TO_COMPLEX(v, a); + TO_COMPLEX(w, b); + PyFPE_START_PROTECT("complex_div", return 0) + errno = 0; + quot = c_quot(a, b); + PyFPE_END_PROTECT(quot) + if (errno == EDOM) { + PyErr_SetString(PyExc_ZeroDivisionError, "complex division by zero"); + return NULL; + } + return PyComplex_FromCComplex(quot); } static PyObject * complex_remainder(PyObject *v, PyObject *w) { - PyErr_SetString(PyExc_TypeError, - "can't mod complex numbers."); - return NULL; + PyErr_SetString(PyExc_TypeError, + "can't mod complex numbers."); + return NULL; } static PyObject * complex_divmod(PyObject *v, PyObject *w) { - PyErr_SetString(PyExc_TypeError, - "can't take floor or mod of complex number."); - return NULL; + PyErr_SetString(PyExc_TypeError, + "can't take floor or mod of complex number."); + return NULL; } static PyObject * complex_pow(PyObject *v, PyObject *w, PyObject *z) { - Py_complex p; - Py_complex exponent; - long int_exponent; - Py_complex a, b; - TO_COMPLEX(v, a); - TO_COMPLEX(w, b); - - if (z != Py_None) { - PyErr_SetString(PyExc_ValueError, "complex modulo"); - return NULL; - } - PyFPE_START_PROTECT("complex_pow", return 0) - errno = 0; - exponent = b; - int_exponent = (long)exponent.real; - if (exponent.imag == 0. && exponent.real == int_exponent) - p = c_powi(a, int_exponent); - else - p = c_pow(a, exponent); - - PyFPE_END_PROTECT(p) - Py_ADJUST_ERANGE2(p.real, p.imag); - if (errno == EDOM) { - PyErr_SetString(PyExc_ZeroDivisionError, - "0.0 to a negative or complex power"); - return NULL; - } - else if (errno == ERANGE) { - PyErr_SetString(PyExc_OverflowError, - "complex exponentiation"); - return NULL; - } - return PyComplex_FromCComplex(p); + Py_complex p; + Py_complex exponent; + long int_exponent; + Py_complex a, b; + TO_COMPLEX(v, a); + TO_COMPLEX(w, b); + + if (z != Py_None) { + PyErr_SetString(PyExc_ValueError, "complex modulo"); + return NULL; + } + PyFPE_START_PROTECT("complex_pow", return 0) + errno = 0; + exponent = b; + int_exponent = (long)exponent.real; + if (exponent.imag == 0. && exponent.real == int_exponent) + p = c_powi(a, int_exponent); + else + p = c_pow(a, exponent); + + PyFPE_END_PROTECT(p) + Py_ADJUST_ERANGE2(p.real, p.imag); + if (errno == EDOM) { + PyErr_SetString(PyExc_ZeroDivisionError, + "0.0 to a negative or complex power"); + return NULL; + } + else if (errno == ERANGE) { + PyErr_SetString(PyExc_OverflowError, + "complex exponentiation"); + return NULL; + } + return PyComplex_FromCComplex(p); } static PyObject * complex_int_div(PyObject *v, PyObject *w) { - PyErr_SetString(PyExc_TypeError, - "can't take floor of complex number."); - return NULL; + PyErr_SetString(PyExc_TypeError, + "can't take floor of complex number."); + return NULL; } static PyObject * complex_neg(PyComplexObject *v) { - Py_complex neg; - neg.real = -v->cval.real; - neg.imag = -v->cval.imag; - return PyComplex_FromCComplex(neg); + Py_complex neg; + neg.real = -v->cval.real; + neg.imag = -v->cval.imag; + return PyComplex_FromCComplex(neg); } static PyObject * complex_pos(PyComplexObject *v) { - if (PyComplex_CheckExact(v)) { - Py_INCREF(v); - return (PyObject *)v; - } - else - return PyComplex_FromCComplex(v->cval); + if (PyComplex_CheckExact(v)) { + Py_INCREF(v); + return (PyObject *)v; + } + else + return PyComplex_FromCComplex(v->cval); } static PyObject * complex_abs(PyComplexObject *v) { - double result; + double result; - PyFPE_START_PROTECT("complex_abs", return 0) - result = c_abs(v->cval); - PyFPE_END_PROTECT(result) - - if (errno == ERANGE) { - PyErr_SetString(PyExc_OverflowError, - "absolute value too large"); - return NULL; - } - return PyFloat_FromDouble(result); + PyFPE_START_PROTECT("complex_abs", return 0) + result = c_abs(v->cval); + PyFPE_END_PROTECT(result) + + if (errno == ERANGE) { + PyErr_SetString(PyExc_OverflowError, + "absolute value too large"); + return NULL; + } + return PyFloat_FromDouble(result); } static int complex_bool(PyComplexObject *v) { - return v->cval.real != 0.0 || v->cval.imag != 0.0; + return v->cval.real != 0.0 || v->cval.imag != 0.0; } static PyObject * complex_richcompare(PyObject *v, PyObject *w, int op) { - PyObject *res; - Py_complex i, j; - TO_COMPLEX(v, i); - TO_COMPLEX(w, j); - - if (op != Py_EQ && op != Py_NE) { - Py_INCREF(Py_NotImplemented); - return Py_NotImplemented; - } - - if ((i.real == j.real && i.imag == j.imag) == (op == Py_EQ)) - res = Py_True; - else - res = Py_False; + PyObject *res; + Py_complex i, j; + TO_COMPLEX(v, i); + TO_COMPLEX(w, j); + + if (op != Py_EQ && op != Py_NE) { + Py_INCREF(Py_NotImplemented); + return Py_NotImplemented; + } + + if ((i.real == j.real && i.imag == j.imag) == (op == Py_EQ)) + res = Py_True; + else + res = Py_False; - Py_INCREF(res); - return res; + Py_INCREF(res); + return res; } static PyObject * complex_int(PyObject *v) { - PyErr_SetString(PyExc_TypeError, - "can't convert complex to int"); - return NULL; + PyErr_SetString(PyExc_TypeError, + "can't convert complex to int"); + return NULL; } static PyObject * complex_float(PyObject *v) { - PyErr_SetString(PyExc_TypeError, - "can't convert complex to float"); - return NULL; + PyErr_SetString(PyExc_TypeError, + "can't convert complex to float"); + return NULL; } static PyObject * complex_conjugate(PyObject *self) { - Py_complex c; - c = ((PyComplexObject *)self)->cval; - c.imag = -c.imag; - return PyComplex_FromCComplex(c); + Py_complex c; + c = ((PyComplexObject *)self)->cval; + c.imag = -c.imag; + return PyComplex_FromCComplex(c); } PyDoc_STRVAR(complex_conjugate_doc, @@ -671,8 +671,8 @@ static PyObject * complex_getnewargs(PyComplexObject *v) { - Py_complex c = v->cval; - return Py_BuildValue("(dd)", c.real, c.imag); + Py_complex c = v->cval; + return Py_BuildValue("(dd)", c.real, c.imag); } PyDoc_STRVAR(complex__format__doc, @@ -686,7 +686,7 @@ PyObject *format_spec; if (!PyArg_ParseTuple(args, "U:__format__", &format_spec)) - return NULL; + return NULL; return _PyComplex_FormatAdvanced(self, PyUnicode_AS_UNICODE(format_spec), PyUnicode_GET_SIZE(format_spec)); @@ -696,10 +696,10 @@ static PyObject * complex_is_finite(PyObject *self) { - Py_complex c; - c = ((PyComplexObject *)self)->cval; - return PyBool_FromLong((long)(Py_IS_FINITE(c.real) && - Py_IS_FINITE(c.imag))); + Py_complex c; + c = ((PyComplexObject *)self)->cval; + return PyBool_FromLong((long)(Py_IS_FINITE(c.real) && + Py_IS_FINITE(c.imag))); } PyDoc_STRVAR(complex_is_finite_doc, @@ -709,305 +709,305 @@ #endif static PyMethodDef complex_methods[] = { - {"conjugate", (PyCFunction)complex_conjugate, METH_NOARGS, - complex_conjugate_doc}, + {"conjugate", (PyCFunction)complex_conjugate, METH_NOARGS, + complex_conjugate_doc}, #if 0 - {"is_finite", (PyCFunction)complex_is_finite, METH_NOARGS, - complex_is_finite_doc}, + {"is_finite", (PyCFunction)complex_is_finite, METH_NOARGS, + complex_is_finite_doc}, #endif - {"__getnewargs__", (PyCFunction)complex_getnewargs, METH_NOARGS}, - {"__format__", (PyCFunction)complex__format__, - METH_VARARGS, complex__format__doc}, - {NULL, NULL} /* sentinel */ + {"__getnewargs__", (PyCFunction)complex_getnewargs, METH_NOARGS}, + {"__format__", (PyCFunction)complex__format__, + METH_VARARGS, complex__format__doc}, + {NULL, NULL} /* sentinel */ }; static PyMemberDef complex_members[] = { - {"real", T_DOUBLE, offsetof(PyComplexObject, cval.real), READONLY, - "the real part of a complex number"}, - {"imag", T_DOUBLE, offsetof(PyComplexObject, cval.imag), READONLY, - "the imaginary part of a complex number"}, - {0}, + {"real", T_DOUBLE, offsetof(PyComplexObject, cval.real), READONLY, + "the real part of a complex number"}, + {"imag", T_DOUBLE, offsetof(PyComplexObject, cval.imag), READONLY, + "the imaginary part of a complex number"}, + {0}, }; static PyObject * complex_subtype_from_string(PyTypeObject *type, PyObject *v) { - const char *s, *start; - char *end; - double x=0.0, y=0.0, z; - int got_bracket=0; - char *s_buffer = NULL; - Py_ssize_t len; - - if (PyUnicode_Check(v)) { - s_buffer = (char *)PyMem_MALLOC(PyUnicode_GET_SIZE(v) + 1); - if (s_buffer == NULL) - return PyErr_NoMemory(); - if (PyUnicode_EncodeDecimal(PyUnicode_AS_UNICODE(v), - PyUnicode_GET_SIZE(v), - s_buffer, - NULL)) - goto error; - s = s_buffer; - len = strlen(s); - } - else if (PyObject_AsCharBuffer(v, &s, &len)) { - PyErr_SetString(PyExc_TypeError, - "complex() arg is not a string"); - return NULL; - } - - /* position on first nonblank */ - start = s; - while (Py_ISSPACE(*s)) - s++; - if (*s == '(') { - /* Skip over possible bracket from repr(). */ - got_bracket = 1; - s++; - while (Py_ISSPACE(*s)) - s++; - } - - /* a valid complex string usually takes one of the three forms: - - - real part only - j - imaginary part only - j - real and imaginary parts - - where represents any numeric string that's accepted by the - float constructor (including 'nan', 'inf', 'infinity', etc.), and - is any string of the form whose first - character is '+' or '-'. - - For backwards compatibility, the extra forms - - j - j - j - - are also accepted, though support for these forms may be removed from - a future version of Python. - */ - - /* first look for forms starting with */ - z = PyOS_string_to_double(s, &end, NULL); - if (z == -1.0 && PyErr_Occurred()) { - if (PyErr_ExceptionMatches(PyExc_ValueError)) - PyErr_Clear(); - else - goto error; - } - if (end != s) { - /* all 4 forms starting with land here */ - s = end; - if (*s == '+' || *s == '-') { - /* j | j */ - x = z; - y = PyOS_string_to_double(s, &end, NULL); - if (y == -1.0 && PyErr_Occurred()) { - if (PyErr_ExceptionMatches(PyExc_ValueError)) - PyErr_Clear(); - else - goto error; - } - if (end != s) - /* j */ - s = end; - else { - /* j */ - y = *s == '+' ? 1.0 : -1.0; - s++; - } - if (!(*s == 'j' || *s == 'J')) - goto parse_error; - s++; - } - else if (*s == 'j' || *s == 'J') { - /* j */ - s++; - y = z; - } - else - /* */ - x = z; - } - else { - /* not starting with ; must be j or j */ - if (*s == '+' || *s == '-') { - /* j */ - y = *s == '+' ? 1.0 : -1.0; - s++; - } - else - /* j */ - y = 1.0; - if (!(*s == 'j' || *s == 'J')) - goto parse_error; - s++; - } - - /* trailing whitespace and closing bracket */ - while (Py_ISSPACE(*s)) - s++; - if (got_bracket) { - /* if there was an opening parenthesis, then the corresponding - closing parenthesis should be right here */ - if (*s != ')') - goto parse_error; - s++; - while (Py_ISSPACE(*s)) - s++; - } - - /* we should now be at the end of the string */ - if (s-start != len) - goto parse_error; - - if (s_buffer) - PyMem_FREE(s_buffer); - return complex_subtype_from_doubles(type, x, y); + const char *s, *start; + char *end; + double x=0.0, y=0.0, z; + int got_bracket=0; + char *s_buffer = NULL; + Py_ssize_t len; + + if (PyUnicode_Check(v)) { + s_buffer = (char *)PyMem_MALLOC(PyUnicode_GET_SIZE(v) + 1); + if (s_buffer == NULL) + return PyErr_NoMemory(); + if (PyUnicode_EncodeDecimal(PyUnicode_AS_UNICODE(v), + PyUnicode_GET_SIZE(v), + s_buffer, + NULL)) + goto error; + s = s_buffer; + len = strlen(s); + } + else if (PyObject_AsCharBuffer(v, &s, &len)) { + PyErr_SetString(PyExc_TypeError, + "complex() arg is not a string"); + return NULL; + } + + /* position on first nonblank */ + start = s; + while (Py_ISSPACE(*s)) + s++; + if (*s == '(') { + /* Skip over possible bracket from repr(). */ + got_bracket = 1; + s++; + while (Py_ISSPACE(*s)) + s++; + } + + /* a valid complex string usually takes one of the three forms: + + - real part only + j - imaginary part only + j - real and imaginary parts + + where represents any numeric string that's accepted by the + float constructor (including 'nan', 'inf', 'infinity', etc.), and + is any string of the form whose first + character is '+' or '-'. + + For backwards compatibility, the extra forms + + j + j + j + + are also accepted, though support for these forms may be removed from + a future version of Python. + */ + + /* first look for forms starting with */ + z = PyOS_string_to_double(s, &end, NULL); + if (z == -1.0 && PyErr_Occurred()) { + if (PyErr_ExceptionMatches(PyExc_ValueError)) + PyErr_Clear(); + else + goto error; + } + if (end != s) { + /* all 4 forms starting with land here */ + s = end; + if (*s == '+' || *s == '-') { + /* j | j */ + x = z; + y = PyOS_string_to_double(s, &end, NULL); + if (y == -1.0 && PyErr_Occurred()) { + if (PyErr_ExceptionMatches(PyExc_ValueError)) + PyErr_Clear(); + else + goto error; + } + if (end != s) + /* j */ + s = end; + else { + /* j */ + y = *s == '+' ? 1.0 : -1.0; + s++; + } + if (!(*s == 'j' || *s == 'J')) + goto parse_error; + s++; + } + else if (*s == 'j' || *s == 'J') { + /* j */ + s++; + y = z; + } + else + /* */ + x = z; + } + else { + /* not starting with ; must be j or j */ + if (*s == '+' || *s == '-') { + /* j */ + y = *s == '+' ? 1.0 : -1.0; + s++; + } + else + /* j */ + y = 1.0; + if (!(*s == 'j' || *s == 'J')) + goto parse_error; + s++; + } + + /* trailing whitespace and closing bracket */ + while (Py_ISSPACE(*s)) + s++; + if (got_bracket) { + /* if there was an opening parenthesis, then the corresponding + closing parenthesis should be right here */ + if (*s != ')') + goto parse_error; + s++; + while (Py_ISSPACE(*s)) + s++; + } + + /* we should now be at the end of the string */ + if (s-start != len) + goto parse_error; + + if (s_buffer) + PyMem_FREE(s_buffer); + return complex_subtype_from_doubles(type, x, y); parse_error: - PyErr_SetString(PyExc_ValueError, - "complex() arg is a malformed string"); + PyErr_SetString(PyExc_ValueError, + "complex() arg is a malformed string"); error: - if (s_buffer) - PyMem_FREE(s_buffer); - return NULL; + if (s_buffer) + PyMem_FREE(s_buffer); + return NULL; } static PyObject * complex_new(PyTypeObject *type, PyObject *args, PyObject *kwds) { - PyObject *r, *i, *tmp; - PyNumberMethods *nbr, *nbi = NULL; - Py_complex cr, ci; - int own_r = 0; - int cr_is_complex = 0; - int ci_is_complex = 0; - static char *kwlist[] = {"real", "imag", 0}; - - r = Py_False; - i = NULL; - if (!PyArg_ParseTupleAndKeywords(args, kwds, "|OO:complex", kwlist, - &r, &i)) - return NULL; - - /* Special-case for a single argument when type(arg) is complex. */ - if (PyComplex_CheckExact(r) && i == NULL && - type == &PyComplex_Type) { - /* Note that we can't know whether it's safe to return - a complex *subclass* instance as-is, hence the restriction - to exact complexes here. If either the input or the - output is a complex subclass, it will be handled below - as a non-orthogonal vector. */ - Py_INCREF(r); - return r; - } - if (PyUnicode_Check(r)) { - if (i != NULL) { - PyErr_SetString(PyExc_TypeError, - "complex() can't take second arg" - " if first is a string"); - return NULL; - } - return complex_subtype_from_string(type, r); - } - if (i != NULL && PyUnicode_Check(i)) { - PyErr_SetString(PyExc_TypeError, - "complex() second arg can't be a string"); - return NULL; - } - - tmp = try_complex_special_method(r); - if (tmp) { - r = tmp; - own_r = 1; - } - else if (PyErr_Occurred()) { - return NULL; - } - - nbr = r->ob_type->tp_as_number; - if (i != NULL) - nbi = i->ob_type->tp_as_number; - if (nbr == NULL || nbr->nb_float == NULL || - ((i != NULL) && (nbi == NULL || nbi->nb_float == NULL))) { - PyErr_SetString(PyExc_TypeError, - "complex() argument must be a string or a number"); - if (own_r) { - Py_DECREF(r); - } - return NULL; - } - - /* If we get this far, then the "real" and "imag" parts should - both be treated as numbers, and the constructor should return a - complex number equal to (real + imag*1j). - - Note that we do NOT assume the input to already be in canonical - form; the "real" and "imag" parts might themselves be complex - numbers, which slightly complicates the code below. */ - if (PyComplex_Check(r)) { - /* Note that if r is of a complex subtype, we're only - retaining its real & imag parts here, and the return - value is (properly) of the builtin complex type. */ - cr = ((PyComplexObject*)r)->cval; - cr_is_complex = 1; - if (own_r) { - Py_DECREF(r); - } - } - else { - /* The "real" part really is entirely real, and contributes - nothing in the imaginary direction. - Just treat it as a double. */ - tmp = PyNumber_Float(r); - if (own_r) { - /* r was a newly created complex number, rather - than the original "real" argument. */ - Py_DECREF(r); - } - if (tmp == NULL) - return NULL; - if (!PyFloat_Check(tmp)) { - PyErr_SetString(PyExc_TypeError, - "float(r) didn't return a float"); - Py_DECREF(tmp); - return NULL; - } - cr.real = PyFloat_AsDouble(tmp); - cr.imag = 0.0; /* Shut up compiler warning */ - Py_DECREF(tmp); - } - if (i == NULL) { - ci.real = 0.0; - } - else if (PyComplex_Check(i)) { - ci = ((PyComplexObject*)i)->cval; - ci_is_complex = 1; - } else { - /* The "imag" part really is entirely imaginary, and - contributes nothing in the real direction. - Just treat it as a double. */ - tmp = (*nbi->nb_float)(i); - if (tmp == NULL) - return NULL; - ci.real = PyFloat_AsDouble(tmp); - Py_DECREF(tmp); - } - /* If the input was in canonical form, then the "real" and "imag" - parts are real numbers, so that ci.imag and cr.imag are zero. - We need this correction in case they were not real numbers. */ - - if (ci_is_complex) { - cr.real -= ci.imag; - } - if (cr_is_complex) { - ci.real += cr.imag; - } - return complex_subtype_from_doubles(type, cr.real, ci.real); + PyObject *r, *i, *tmp; + PyNumberMethods *nbr, *nbi = NULL; + Py_complex cr, ci; + int own_r = 0; + int cr_is_complex = 0; + int ci_is_complex = 0; + static char *kwlist[] = {"real", "imag", 0}; + + r = Py_False; + i = NULL; + if (!PyArg_ParseTupleAndKeywords(args, kwds, "|OO:complex", kwlist, + &r, &i)) + return NULL; + + /* Special-case for a single argument when type(arg) is complex. */ + if (PyComplex_CheckExact(r) && i == NULL && + type == &PyComplex_Type) { + /* Note that we can't know whether it's safe to return + a complex *subclass* instance as-is, hence the restriction + to exact complexes here. If either the input or the + output is a complex subclass, it will be handled below + as a non-orthogonal vector. */ + Py_INCREF(r); + return r; + } + if (PyUnicode_Check(r)) { + if (i != NULL) { + PyErr_SetString(PyExc_TypeError, + "complex() can't take second arg" + " if first is a string"); + return NULL; + } + return complex_subtype_from_string(type, r); + } + if (i != NULL && PyUnicode_Check(i)) { + PyErr_SetString(PyExc_TypeError, + "complex() second arg can't be a string"); + return NULL; + } + + tmp = try_complex_special_method(r); + if (tmp) { + r = tmp; + own_r = 1; + } + else if (PyErr_Occurred()) { + return NULL; + } + + nbr = r->ob_type->tp_as_number; + if (i != NULL) + nbi = i->ob_type->tp_as_number; + if (nbr == NULL || nbr->nb_float == NULL || + ((i != NULL) && (nbi == NULL || nbi->nb_float == NULL))) { + PyErr_SetString(PyExc_TypeError, + "complex() argument must be a string or a number"); + if (own_r) { + Py_DECREF(r); + } + return NULL; + } + + /* If we get this far, then the "real" and "imag" parts should + both be treated as numbers, and the constructor should return a + complex number equal to (real + imag*1j). + + Note that we do NOT assume the input to already be in canonical + form; the "real" and "imag" parts might themselves be complex + numbers, which slightly complicates the code below. */ + if (PyComplex_Check(r)) { + /* Note that if r is of a complex subtype, we're only + retaining its real & imag parts here, and the return + value is (properly) of the builtin complex type. */ + cr = ((PyComplexObject*)r)->cval; + cr_is_complex = 1; + if (own_r) { + Py_DECREF(r); + } + } + else { + /* The "real" part really is entirely real, and contributes + nothing in the imaginary direction. + Just treat it as a double. */ + tmp = PyNumber_Float(r); + if (own_r) { + /* r was a newly created complex number, rather + than the original "real" argument. */ + Py_DECREF(r); + } + if (tmp == NULL) + return NULL; + if (!PyFloat_Check(tmp)) { + PyErr_SetString(PyExc_TypeError, + "float(r) didn't return a float"); + Py_DECREF(tmp); + return NULL; + } + cr.real = PyFloat_AsDouble(tmp); + cr.imag = 0.0; /* Shut up compiler warning */ + Py_DECREF(tmp); + } + if (i == NULL) { + ci.real = 0.0; + } + else if (PyComplex_Check(i)) { + ci = ((PyComplexObject*)i)->cval; + ci_is_complex = 1; + } else { + /* The "imag" part really is entirely imaginary, and + contributes nothing in the real direction. + Just treat it as a double. */ + tmp = (*nbi->nb_float)(i); + if (tmp == NULL) + return NULL; + ci.real = PyFloat_AsDouble(tmp); + Py_DECREF(tmp); + } + /* If the input was in canonical form, then the "real" and "imag" + parts are real numbers, so that ci.imag and cr.imag are zero. + We need this correction in case they were not real numbers. */ + + if (ci_is_complex) { + cr.real -= ci.imag; + } + if (cr_is_complex) { + ci.real += cr.imag; + } + return complex_subtype_from_doubles(type, cr.real, ci.real); } PyDoc_STRVAR(complex_doc, @@ -1017,79 +1017,79 @@ "This is equivalent to (real + imag*1j) where imag defaults to 0."); static PyNumberMethods complex_as_number = { - (binaryfunc)complex_add, /* nb_add */ - (binaryfunc)complex_sub, /* nb_subtract */ - (binaryfunc)complex_mul, /* nb_multiply */ - (binaryfunc)complex_remainder, /* nb_remainder */ - (binaryfunc)complex_divmod, /* nb_divmod */ - (ternaryfunc)complex_pow, /* nb_power */ - (unaryfunc)complex_neg, /* nb_negative */ - (unaryfunc)complex_pos, /* nb_positive */ - (unaryfunc)complex_abs, /* nb_absolute */ - (inquiry)complex_bool, /* nb_bool */ - 0, /* nb_invert */ - 0, /* nb_lshift */ - 0, /* nb_rshift */ - 0, /* nb_and */ - 0, /* nb_xor */ - 0, /* nb_or */ - complex_int, /* nb_int */ - 0, /* nb_reserved */ - complex_float, /* nb_float */ - 0, /* nb_inplace_add */ - 0, /* nb_inplace_subtract */ - 0, /* nb_inplace_multiply*/ - 0, /* nb_inplace_remainder */ - 0, /* nb_inplace_power */ - 0, /* nb_inplace_lshift */ - 0, /* nb_inplace_rshift */ - 0, /* nb_inplace_and */ - 0, /* nb_inplace_xor */ - 0, /* nb_inplace_or */ - (binaryfunc)complex_int_div, /* nb_floor_divide */ - (binaryfunc)complex_div, /* nb_true_divide */ - 0, /* nb_inplace_floor_divide */ - 0, /* nb_inplace_true_divide */ + (binaryfunc)complex_add, /* nb_add */ + (binaryfunc)complex_sub, /* nb_subtract */ + (binaryfunc)complex_mul, /* nb_multiply */ + (binaryfunc)complex_remainder, /* nb_remainder */ + (binaryfunc)complex_divmod, /* nb_divmod */ + (ternaryfunc)complex_pow, /* nb_power */ + (unaryfunc)complex_neg, /* nb_negative */ + (unaryfunc)complex_pos, /* nb_positive */ + (unaryfunc)complex_abs, /* nb_absolute */ + (inquiry)complex_bool, /* nb_bool */ + 0, /* nb_invert */ + 0, /* nb_lshift */ + 0, /* nb_rshift */ + 0, /* nb_and */ + 0, /* nb_xor */ + 0, /* nb_or */ + complex_int, /* nb_int */ + 0, /* nb_reserved */ + complex_float, /* nb_float */ + 0, /* nb_inplace_add */ + 0, /* nb_inplace_subtract */ + 0, /* nb_inplace_multiply*/ + 0, /* nb_inplace_remainder */ + 0, /* nb_inplace_power */ + 0, /* nb_inplace_lshift */ + 0, /* nb_inplace_rshift */ + 0, /* nb_inplace_and */ + 0, /* nb_inplace_xor */ + 0, /* nb_inplace_or */ + (binaryfunc)complex_int_div, /* nb_floor_divide */ + (binaryfunc)complex_div, /* nb_true_divide */ + 0, /* nb_inplace_floor_divide */ + 0, /* nb_inplace_true_divide */ }; PyTypeObject PyComplex_Type = { - PyVarObject_HEAD_INIT(&PyType_Type, 0) - "complex", - sizeof(PyComplexObject), - 0, - complex_dealloc, /* tp_dealloc */ - 0, /* tp_print */ - 0, /* tp_getattr */ - 0, /* tp_setattr */ - 0, /* tp_reserved */ - (reprfunc)complex_repr, /* tp_repr */ - &complex_as_number, /* tp_as_number */ - 0, /* tp_as_sequence */ - 0, /* tp_as_mapping */ - (hashfunc)complex_hash, /* tp_hash */ - 0, /* tp_call */ - (reprfunc)complex_str, /* tp_str */ - PyObject_GenericGetAttr, /* tp_getattro */ - 0, /* tp_setattro */ - 0, /* tp_as_buffer */ - Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */ - complex_doc, /* tp_doc */ - 0, /* tp_traverse */ - 0, /* tp_clear */ - complex_richcompare, /* tp_richcompare */ - 0, /* tp_weaklistoffset */ - 0, /* tp_iter */ - 0, /* tp_iternext */ - complex_methods, /* tp_methods */ - complex_members, /* tp_members */ - 0, /* tp_getset */ - 0, /* tp_base */ - 0, /* tp_dict */ - 0, /* tp_descr_get */ - 0, /* tp_descr_set */ - 0, /* tp_dictoffset */ - 0, /* tp_init */ - PyType_GenericAlloc, /* tp_alloc */ - complex_new, /* tp_new */ - PyObject_Del, /* tp_free */ + PyVarObject_HEAD_INIT(&PyType_Type, 0) + "complex", + sizeof(PyComplexObject), + 0, + complex_dealloc, /* tp_dealloc */ + 0, /* tp_print */ + 0, /* tp_getattr */ + 0, /* tp_setattr */ + 0, /* tp_reserved */ + (reprfunc)complex_repr, /* tp_repr */ + &complex_as_number, /* tp_as_number */ + 0, /* tp_as_sequence */ + 0, /* tp_as_mapping */ + (hashfunc)complex_hash, /* tp_hash */ + 0, /* tp_call */ + (reprfunc)complex_str, /* tp_str */ + PyObject_GenericGetAttr, /* tp_getattro */ + 0, /* tp_setattro */ + 0, /* tp_as_buffer */ + Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */ + complex_doc, /* tp_doc */ + 0, /* tp_traverse */ + 0, /* tp_clear */ + complex_richcompare, /* tp_richcompare */ + 0, /* tp_weaklistoffset */ + 0, /* tp_iter */ + 0, /* tp_iternext */ + complex_methods, /* tp_methods */ + complex_members, /* tp_members */ + 0, /* tp_getset */ + 0, /* tp_base */ + 0, /* tp_dict */ + 0, /* tp_descr_get */ + 0, /* tp_descr_set */ + 0, /* tp_dictoffset */ + 0, /* tp_init */ + PyType_GenericAlloc, /* tp_alloc */ + complex_new, /* tp_new */ + PyObject_Del, /* tp_free */ }; Modified: python/branches/py3k-jit/Objects/descrobject.c ============================================================================== --- python/branches/py3k-jit/Objects/descrobject.c (original) +++ python/branches/py3k-jit/Objects/descrobject.c Mon May 10 23:55:43 2010 @@ -6,647 +6,647 @@ static void descr_dealloc(PyDescrObject *descr) { - _PyObject_GC_UNTRACK(descr); - Py_XDECREF(descr->d_type); - Py_XDECREF(descr->d_name); - PyObject_GC_Del(descr); + _PyObject_GC_UNTRACK(descr); + Py_XDECREF(descr->d_type); + Py_XDECREF(descr->d_name); + PyObject_GC_Del(descr); } static PyObject * descr_name(PyDescrObject *descr) { - if (descr->d_name != NULL && PyUnicode_Check(descr->d_name)) - return descr->d_name; - return NULL; + if (descr->d_name != NULL && PyUnicode_Check(descr->d_name)) + return descr->d_name; + return NULL; } static PyObject * descr_repr(PyDescrObject *descr, char *format) { - PyObject *name = NULL; - if (descr->d_name != NULL && PyUnicode_Check(descr->d_name)) - name = descr->d_name; + PyObject *name = NULL; + if (descr->d_name != NULL && PyUnicode_Check(descr->d_name)) + name = descr->d_name; - return PyUnicode_FromFormat(format, name, "?", descr->d_type->tp_name); + return PyUnicode_FromFormat(format, name, "?", descr->d_type->tp_name); } static PyObject * method_repr(PyMethodDescrObject *descr) { - return descr_repr((PyDescrObject *)descr, - ""); + return descr_repr((PyDescrObject *)descr, + ""); } static PyObject * member_repr(PyMemberDescrObject *descr) { - return descr_repr((PyDescrObject *)descr, - ""); + return descr_repr((PyDescrObject *)descr, + ""); } static PyObject * getset_repr(PyGetSetDescrObject *descr) { - return descr_repr((PyDescrObject *)descr, - ""); + return descr_repr((PyDescrObject *)descr, + ""); } static PyObject * wrapperdescr_repr(PyWrapperDescrObject *descr) { - return descr_repr((PyDescrObject *)descr, - ""); + return descr_repr((PyDescrObject *)descr, + ""); } static int descr_check(PyDescrObject *descr, PyObject *obj, PyObject **pres) { - if (obj == NULL) { - Py_INCREF(descr); - *pres = (PyObject *)descr; - return 1; - } - if (!PyObject_TypeCheck(obj, descr->d_type)) { - PyErr_Format(PyExc_TypeError, - "descriptor '%V' for '%s' objects " - "doesn't apply to '%s' object", - descr_name((PyDescrObject *)descr), "?", - descr->d_type->tp_name, - obj->ob_type->tp_name); - *pres = NULL; - return 1; - } - return 0; + if (obj == NULL) { + Py_INCREF(descr); + *pres = (PyObject *)descr; + return 1; + } + if (!PyObject_TypeCheck(obj, descr->d_type)) { + PyErr_Format(PyExc_TypeError, + "descriptor '%V' for '%s' objects " + "doesn't apply to '%s' object", + descr_name((PyDescrObject *)descr), "?", + descr->d_type->tp_name, + obj->ob_type->tp_name); + *pres = NULL; + return 1; + } + return 0; } static PyObject * classmethod_get(PyMethodDescrObject *descr, PyObject *obj, PyObject *type) { - /* Ensure a valid type. Class methods ignore obj. */ - if (type == NULL) { - if (obj != NULL) - type = (PyObject *)obj->ob_type; - else { - /* Wot - no type?! */ - PyErr_Format(PyExc_TypeError, - "descriptor '%V' for type '%s' " - "needs either an object or a type", - descr_name((PyDescrObject *)descr), "?", - PyDescr_TYPE(descr)->tp_name); - return NULL; - } - } - if (!PyType_Check(type)) { - PyErr_Format(PyExc_TypeError, - "descriptor '%V' for type '%s' " - "needs a type, not a '%s' as arg 2", - descr_name((PyDescrObject *)descr), "?", - PyDescr_TYPE(descr)->tp_name, - type->ob_type->tp_name); - return NULL; - } - if (!PyType_IsSubtype((PyTypeObject *)type, PyDescr_TYPE(descr))) { - PyErr_Format(PyExc_TypeError, - "descriptor '%V' for type '%s' " - "doesn't apply to type '%s'", - descr_name((PyDescrObject *)descr), "?", - PyDescr_TYPE(descr)->tp_name, - ((PyTypeObject *)type)->tp_name); - return NULL; - } - return PyCFunction_New(descr->d_method, type); + /* Ensure a valid type. Class methods ignore obj. */ + if (type == NULL) { + if (obj != NULL) + type = (PyObject *)obj->ob_type; + else { + /* Wot - no type?! */ + PyErr_Format(PyExc_TypeError, + "descriptor '%V' for type '%s' " + "needs either an object or a type", + descr_name((PyDescrObject *)descr), "?", + PyDescr_TYPE(descr)->tp_name); + return NULL; + } + } + if (!PyType_Check(type)) { + PyErr_Format(PyExc_TypeError, + "descriptor '%V' for type '%s' " + "needs a type, not a '%s' as arg 2", + descr_name((PyDescrObject *)descr), "?", + PyDescr_TYPE(descr)->tp_name, + type->ob_type->tp_name); + return NULL; + } + if (!PyType_IsSubtype((PyTypeObject *)type, PyDescr_TYPE(descr))) { + PyErr_Format(PyExc_TypeError, + "descriptor '%V' for type '%s' " + "doesn't apply to type '%s'", + descr_name((PyDescrObject *)descr), "?", + PyDescr_TYPE(descr)->tp_name, + ((PyTypeObject *)type)->tp_name); + return NULL; + } + return PyCFunction_New(descr->d_method, type); } static PyObject * method_get(PyMethodDescrObject *descr, PyObject *obj, PyObject *type) { - PyObject *res; + PyObject *res; - if (descr_check((PyDescrObject *)descr, obj, &res)) - return res; - return PyCFunction_New(descr->d_method, obj); + if (descr_check((PyDescrObject *)descr, obj, &res)) + return res; + return PyCFunction_New(descr->d_method, obj); } static PyObject * member_get(PyMemberDescrObject *descr, PyObject *obj, PyObject *type) { - PyObject *res; + PyObject *res; - if (descr_check((PyDescrObject *)descr, obj, &res)) - return res; - return PyMember_GetOne((char *)obj, descr->d_member); + if (descr_check((PyDescrObject *)descr, obj, &res)) + return res; + return PyMember_GetOne((char *)obj, descr->d_member); } static PyObject * getset_get(PyGetSetDescrObject *descr, PyObject *obj, PyObject *type) { - PyObject *res; + PyObject *res; - if (descr_check((PyDescrObject *)descr, obj, &res)) - return res; - if (descr->d_getset->get != NULL) - return descr->d_getset->get(obj, descr->d_getset->closure); - PyErr_Format(PyExc_AttributeError, - "attribute '%V' of '%.100s' objects is not readable", - descr_name((PyDescrObject *)descr), "?", - PyDescr_TYPE(descr)->tp_name); - return NULL; + if (descr_check((PyDescrObject *)descr, obj, &res)) + return res; + if (descr->d_getset->get != NULL) + return descr->d_getset->get(obj, descr->d_getset->closure); + PyErr_Format(PyExc_AttributeError, + "attribute '%V' of '%.100s' objects is not readable", + descr_name((PyDescrObject *)descr), "?", + PyDescr_TYPE(descr)->tp_name); + return NULL; } static PyObject * wrapperdescr_get(PyWrapperDescrObject *descr, PyObject *obj, PyObject *type) { - PyObject *res; + PyObject *res; - if (descr_check((PyDescrObject *)descr, obj, &res)) - return res; - return PyWrapper_New((PyObject *)descr, obj); + if (descr_check((PyDescrObject *)descr, obj, &res)) + return res; + return PyWrapper_New((PyObject *)descr, obj); } static int descr_setcheck(PyDescrObject *descr, PyObject *obj, PyObject *value, - int *pres) + int *pres) { - assert(obj != NULL); - if (!PyObject_TypeCheck(obj, descr->d_type)) { - PyErr_Format(PyExc_TypeError, - "descriptor '%V' for '%.100s' objects " - "doesn't apply to '%.100s' object", - descr_name(descr), "?", - descr->d_type->tp_name, - obj->ob_type->tp_name); - *pres = -1; - return 1; - } - return 0; + assert(obj != NULL); + if (!PyObject_TypeCheck(obj, descr->d_type)) { + PyErr_Format(PyExc_TypeError, + "descriptor '%V' for '%.100s' objects " + "doesn't apply to '%.100s' object", + descr_name(descr), "?", + descr->d_type->tp_name, + obj->ob_type->tp_name); + *pres = -1; + return 1; + } + return 0; } static int member_set(PyMemberDescrObject *descr, PyObject *obj, PyObject *value) { - int res; + int res; - if (descr_setcheck((PyDescrObject *)descr, obj, value, &res)) - return res; - return PyMember_SetOne((char *)obj, descr->d_member, value); + if (descr_setcheck((PyDescrObject *)descr, obj, value, &res)) + return res; + return PyMember_SetOne((char *)obj, descr->d_member, value); } static int getset_set(PyGetSetDescrObject *descr, PyObject *obj, PyObject *value) { - int res; + int res; - if (descr_setcheck((PyDescrObject *)descr, obj, value, &res)) - return res; - if (descr->d_getset->set != NULL) - return descr->d_getset->set(obj, value, - descr->d_getset->closure); - PyErr_Format(PyExc_AttributeError, - "attribute '%V' of '%.100s' objects is not writable", - descr_name((PyDescrObject *)descr), "?", - PyDescr_TYPE(descr)->tp_name); - return -1; + if (descr_setcheck((PyDescrObject *)descr, obj, value, &res)) + return res; + if (descr->d_getset->set != NULL) + return descr->d_getset->set(obj, value, + descr->d_getset->closure); + PyErr_Format(PyExc_AttributeError, + "attribute '%V' of '%.100s' objects is not writable", + descr_name((PyDescrObject *)descr), "?", + PyDescr_TYPE(descr)->tp_name); + return -1; } static PyObject * methoddescr_call(PyMethodDescrObject *descr, PyObject *args, PyObject *kwds) { - Py_ssize_t argc; - PyObject *self, *func, *result; + Py_ssize_t argc; + PyObject *self, *func, *result; - /* Make sure that the first argument is acceptable as 'self' */ - assert(PyTuple_Check(args)); - argc = PyTuple_GET_SIZE(args); - if (argc < 1) { - PyErr_Format(PyExc_TypeError, - "descriptor '%V' of '%.100s' " - "object needs an argument", - descr_name((PyDescrObject *)descr), "?", - PyDescr_TYPE(descr)->tp_name); - return NULL; - } - self = PyTuple_GET_ITEM(args, 0); - if (!PyObject_IsInstance(self, (PyObject *)PyDescr_TYPE(descr))) { - PyErr_Format(PyExc_TypeError, - "descriptor '%V' " - "requires a '%.100s' object " - "but received a '%.100s'", - descr_name((PyDescrObject *)descr), "?", - PyDescr_TYPE(descr)->tp_name, - self->ob_type->tp_name); - return NULL; - } - - func = PyCFunction_New(descr->d_method, self); - if (func == NULL) - return NULL; - args = PyTuple_GetSlice(args, 1, argc); - if (args == NULL) { - Py_DECREF(func); - return NULL; - } - result = PyEval_CallObjectWithKeywords(func, args, kwds); - Py_DECREF(args); - Py_DECREF(func); - return result; + /* Make sure that the first argument is acceptable as 'self' */ + assert(PyTuple_Check(args)); + argc = PyTuple_GET_SIZE(args); + if (argc < 1) { + PyErr_Format(PyExc_TypeError, + "descriptor '%V' of '%.100s' " + "object needs an argument", + descr_name((PyDescrObject *)descr), "?", + PyDescr_TYPE(descr)->tp_name); + return NULL; + } + self = PyTuple_GET_ITEM(args, 0); + if (!PyObject_IsInstance(self, (PyObject *)PyDescr_TYPE(descr))) { + PyErr_Format(PyExc_TypeError, + "descriptor '%V' " + "requires a '%.100s' object " + "but received a '%.100s'", + descr_name((PyDescrObject *)descr), "?", + PyDescr_TYPE(descr)->tp_name, + self->ob_type->tp_name); + return NULL; + } + + func = PyCFunction_New(descr->d_method, self); + if (func == NULL) + return NULL; + args = PyTuple_GetSlice(args, 1, argc); + if (args == NULL) { + Py_DECREF(func); + return NULL; + } + result = PyEval_CallObjectWithKeywords(func, args, kwds); + Py_DECREF(args); + Py_DECREF(func); + return result; } static PyObject * classmethoddescr_call(PyMethodDescrObject *descr, PyObject *args, - PyObject *kwds) + PyObject *kwds) { - PyObject *func, *result; + PyObject *func, *result; - func = PyCFunction_New(descr->d_method, (PyObject *)PyDescr_TYPE(descr)); - if (func == NULL) - return NULL; + func = PyCFunction_New(descr->d_method, (PyObject *)PyDescr_TYPE(descr)); + if (func == NULL) + return NULL; - result = PyEval_CallObjectWithKeywords(func, args, kwds); - Py_DECREF(func); - return result; + result = PyEval_CallObjectWithKeywords(func, args, kwds); + Py_DECREF(func); + return result; } static PyObject * wrapperdescr_call(PyWrapperDescrObject *descr, PyObject *args, PyObject *kwds) { - Py_ssize_t argc; - PyObject *self, *func, *result; + Py_ssize_t argc; + PyObject *self, *func, *result; - /* Make sure that the first argument is acceptable as 'self' */ - assert(PyTuple_Check(args)); - argc = PyTuple_GET_SIZE(args); - if (argc < 1) { - PyErr_Format(PyExc_TypeError, - "descriptor '%V' of '%.100s' " - "object needs an argument", - descr_name((PyDescrObject *)descr), "?", - PyDescr_TYPE(descr)->tp_name); - return NULL; - } - self = PyTuple_GET_ITEM(args, 0); - if (!PyObject_IsInstance(self, (PyObject *)PyDescr_TYPE(descr))) { - PyErr_Format(PyExc_TypeError, - "descriptor '%V' " - "requires a '%.100s' object " - "but received a '%.100s'", - descr_name((PyDescrObject *)descr), "?", - PyDescr_TYPE(descr)->tp_name, - self->ob_type->tp_name); - return NULL; - } - - func = PyWrapper_New((PyObject *)descr, self); - if (func == NULL) - return NULL; - args = PyTuple_GetSlice(args, 1, argc); - if (args == NULL) { - Py_DECREF(func); - return NULL; - } - result = PyEval_CallObjectWithKeywords(func, args, kwds); - Py_DECREF(args); - Py_DECREF(func); - return result; + /* Make sure that the first argument is acceptable as 'self' */ + assert(PyTuple_Check(args)); + argc = PyTuple_GET_SIZE(args); + if (argc < 1) { + PyErr_Format(PyExc_TypeError, + "descriptor '%V' of '%.100s' " + "object needs an argument", + descr_name((PyDescrObject *)descr), "?", + PyDescr_TYPE(descr)->tp_name); + return NULL; + } + self = PyTuple_GET_ITEM(args, 0); + if (!PyObject_IsInstance(self, (PyObject *)PyDescr_TYPE(descr))) { + PyErr_Format(PyExc_TypeError, + "descriptor '%V' " + "requires a '%.100s' object " + "but received a '%.100s'", + descr_name((PyDescrObject *)descr), "?", + PyDescr_TYPE(descr)->tp_name, + self->ob_type->tp_name); + return NULL; + } + + func = PyWrapper_New((PyObject *)descr, self); + if (func == NULL) + return NULL; + args = PyTuple_GetSlice(args, 1, argc); + if (args == NULL) { + Py_DECREF(func); + return NULL; + } + result = PyEval_CallObjectWithKeywords(func, args, kwds); + Py_DECREF(args); + Py_DECREF(func); + return result; } static PyObject * method_get_doc(PyMethodDescrObject *descr, void *closure) { - if (descr->d_method->ml_doc == NULL) { - Py_INCREF(Py_None); - return Py_None; - } - return PyUnicode_FromString(descr->d_method->ml_doc); + if (descr->d_method->ml_doc == NULL) { + Py_INCREF(Py_None); + return Py_None; + } + return PyUnicode_FromString(descr->d_method->ml_doc); } static PyMemberDef descr_members[] = { - {"__objclass__", T_OBJECT, offsetof(PyDescrObject, d_type), READONLY}, - {"__name__", T_OBJECT, offsetof(PyDescrObject, d_name), READONLY}, - {0} + {"__objclass__", T_OBJECT, offsetof(PyDescrObject, d_type), READONLY}, + {"__name__", T_OBJECT, offsetof(PyDescrObject, d_name), READONLY}, + {0} }; static PyGetSetDef method_getset[] = { - {"__doc__", (getter)method_get_doc}, - {0} + {"__doc__", (getter)method_get_doc}, + {0} }; static PyObject * member_get_doc(PyMemberDescrObject *descr, void *closure) { - if (descr->d_member->doc == NULL) { - Py_INCREF(Py_None); - return Py_None; - } - return PyUnicode_FromString(descr->d_member->doc); + if (descr->d_member->doc == NULL) { + Py_INCREF(Py_None); + return Py_None; + } + return PyUnicode_FromString(descr->d_member->doc); } static PyGetSetDef member_getset[] = { - {"__doc__", (getter)member_get_doc}, - {0} + {"__doc__", (getter)member_get_doc}, + {0} }; static PyObject * getset_get_doc(PyGetSetDescrObject *descr, void *closure) { - if (descr->d_getset->doc == NULL) { - Py_INCREF(Py_None); - return Py_None; - } - return PyUnicode_FromString(descr->d_getset->doc); + if (descr->d_getset->doc == NULL) { + Py_INCREF(Py_None); + return Py_None; + } + return PyUnicode_FromString(descr->d_getset->doc); } static PyGetSetDef getset_getset[] = { - {"__doc__", (getter)getset_get_doc}, - {0} + {"__doc__", (getter)getset_get_doc}, + {0} }; static PyObject * wrapperdescr_get_doc(PyWrapperDescrObject *descr, void *closure) { - if (descr->d_base->doc == NULL) { - Py_INCREF(Py_None); - return Py_None; - } - return PyUnicode_FromString(descr->d_base->doc); + if (descr->d_base->doc == NULL) { + Py_INCREF(Py_None); + return Py_None; + } + return PyUnicode_FromString(descr->d_base->doc); } static PyGetSetDef wrapperdescr_getset[] = { - {"__doc__", (getter)wrapperdescr_get_doc}, - {0} + {"__doc__", (getter)wrapperdescr_get_doc}, + {0} }; static int descr_traverse(PyObject *self, visitproc visit, void *arg) { - PyDescrObject *descr = (PyDescrObject *)self; - Py_VISIT(descr->d_type); - return 0; + PyDescrObject *descr = (PyDescrObject *)self; + Py_VISIT(descr->d_type); + return 0; } PyTypeObject PyMethodDescr_Type = { - PyVarObject_HEAD_INIT(&PyType_Type, 0) - "method_descriptor", - sizeof(PyMethodDescrObject), - 0, - (destructor)descr_dealloc, /* tp_dealloc */ - 0, /* tp_print */ - 0, /* tp_getattr */ - 0, /* tp_setattr */ - 0, /* tp_reserved */ - (reprfunc)method_repr, /* tp_repr */ - 0, /* tp_as_number */ - 0, /* tp_as_sequence */ - 0, /* tp_as_mapping */ - 0, /* tp_hash */ - (ternaryfunc)methoddescr_call, /* 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 */ - descr_traverse, /* tp_traverse */ - 0, /* tp_clear */ - 0, /* tp_richcompare */ - 0, /* tp_weaklistoffset */ - 0, /* tp_iter */ - 0, /* tp_iternext */ - 0, /* tp_methods */ - descr_members, /* tp_members */ - method_getset, /* tp_getset */ - 0, /* tp_base */ - 0, /* tp_dict */ - (descrgetfunc)method_get, /* tp_descr_get */ - 0, /* tp_descr_set */ + PyVarObject_HEAD_INIT(&PyType_Type, 0) + "method_descriptor", + sizeof(PyMethodDescrObject), + 0, + (destructor)descr_dealloc, /* tp_dealloc */ + 0, /* tp_print */ + 0, /* tp_getattr */ + 0, /* tp_setattr */ + 0, /* tp_reserved */ + (reprfunc)method_repr, /* tp_repr */ + 0, /* tp_as_number */ + 0, /* tp_as_sequence */ + 0, /* tp_as_mapping */ + 0, /* tp_hash */ + (ternaryfunc)methoddescr_call, /* 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 */ + descr_traverse, /* tp_traverse */ + 0, /* tp_clear */ + 0, /* tp_richcompare */ + 0, /* tp_weaklistoffset */ + 0, /* tp_iter */ + 0, /* tp_iternext */ + 0, /* tp_methods */ + descr_members, /* tp_members */ + method_getset, /* tp_getset */ + 0, /* tp_base */ + 0, /* tp_dict */ + (descrgetfunc)method_get, /* tp_descr_get */ + 0, /* tp_descr_set */ }; /* This is for METH_CLASS in C, not for "f = classmethod(f)" in Python! */ PyTypeObject PyClassMethodDescr_Type = { - PyVarObject_HEAD_INIT(&PyType_Type, 0) - "classmethod_descriptor", - sizeof(PyMethodDescrObject), - 0, - (destructor)descr_dealloc, /* tp_dealloc */ - 0, /* tp_print */ - 0, /* tp_getattr */ - 0, /* tp_setattr */ - 0, /* tp_reserved */ - (reprfunc)method_repr, /* tp_repr */ - 0, /* tp_as_number */ - 0, /* tp_as_sequence */ - 0, /* tp_as_mapping */ - 0, /* tp_hash */ - (ternaryfunc)classmethoddescr_call, /* 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 */ - descr_traverse, /* tp_traverse */ - 0, /* tp_clear */ - 0, /* tp_richcompare */ - 0, /* tp_weaklistoffset */ - 0, /* tp_iter */ - 0, /* tp_iternext */ - 0, /* tp_methods */ - descr_members, /* tp_members */ - method_getset, /* tp_getset */ - 0, /* tp_base */ - 0, /* tp_dict */ - (descrgetfunc)classmethod_get, /* tp_descr_get */ - 0, /* tp_descr_set */ + PyVarObject_HEAD_INIT(&PyType_Type, 0) + "classmethod_descriptor", + sizeof(PyMethodDescrObject), + 0, + (destructor)descr_dealloc, /* tp_dealloc */ + 0, /* tp_print */ + 0, /* tp_getattr */ + 0, /* tp_setattr */ + 0, /* tp_reserved */ + (reprfunc)method_repr, /* tp_repr */ + 0, /* tp_as_number */ + 0, /* tp_as_sequence */ + 0, /* tp_as_mapping */ + 0, /* tp_hash */ + (ternaryfunc)classmethoddescr_call, /* 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 */ + descr_traverse, /* tp_traverse */ + 0, /* tp_clear */ + 0, /* tp_richcompare */ + 0, /* tp_weaklistoffset */ + 0, /* tp_iter */ + 0, /* tp_iternext */ + 0, /* tp_methods */ + descr_members, /* tp_members */ + method_getset, /* tp_getset */ + 0, /* tp_base */ + 0, /* tp_dict */ + (descrgetfunc)classmethod_get, /* tp_descr_get */ + 0, /* tp_descr_set */ }; PyTypeObject PyMemberDescr_Type = { - PyVarObject_HEAD_INIT(&PyType_Type, 0) - "member_descriptor", - sizeof(PyMemberDescrObject), - 0, - (destructor)descr_dealloc, /* tp_dealloc */ - 0, /* tp_print */ - 0, /* tp_getattr */ - 0, /* tp_setattr */ - 0, /* tp_reserved */ - (reprfunc)member_repr, /* 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 */ - descr_traverse, /* tp_traverse */ - 0, /* tp_clear */ - 0, /* tp_richcompare */ - 0, /* tp_weaklistoffset */ - 0, /* tp_iter */ - 0, /* tp_iternext */ - 0, /* tp_methods */ - descr_members, /* tp_members */ - member_getset, /* tp_getset */ - 0, /* tp_base */ - 0, /* tp_dict */ - (descrgetfunc)member_get, /* tp_descr_get */ - (descrsetfunc)member_set, /* tp_descr_set */ + PyVarObject_HEAD_INIT(&PyType_Type, 0) + "member_descriptor", + sizeof(PyMemberDescrObject), + 0, + (destructor)descr_dealloc, /* tp_dealloc */ + 0, /* tp_print */ + 0, /* tp_getattr */ + 0, /* tp_setattr */ + 0, /* tp_reserved */ + (reprfunc)member_repr, /* 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 */ + descr_traverse, /* tp_traverse */ + 0, /* tp_clear */ + 0, /* tp_richcompare */ + 0, /* tp_weaklistoffset */ + 0, /* tp_iter */ + 0, /* tp_iternext */ + 0, /* tp_methods */ + descr_members, /* tp_members */ + member_getset, /* tp_getset */ + 0, /* tp_base */ + 0, /* tp_dict */ + (descrgetfunc)member_get, /* tp_descr_get */ + (descrsetfunc)member_set, /* tp_descr_set */ }; PyTypeObject PyGetSetDescr_Type = { - PyVarObject_HEAD_INIT(&PyType_Type, 0) - "getset_descriptor", - sizeof(PyGetSetDescrObject), - 0, - (destructor)descr_dealloc, /* tp_dealloc */ - 0, /* tp_print */ - 0, /* tp_getattr */ - 0, /* tp_setattr */ - 0, /* tp_reserved */ - (reprfunc)getset_repr, /* 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 */ - descr_traverse, /* tp_traverse */ - 0, /* tp_clear */ - 0, /* tp_richcompare */ - 0, /* tp_weaklistoffset */ - 0, /* tp_iter */ - 0, /* tp_iternext */ - 0, /* tp_methods */ - descr_members, /* tp_members */ - getset_getset, /* tp_getset */ - 0, /* tp_base */ - 0, /* tp_dict */ - (descrgetfunc)getset_get, /* tp_descr_get */ - (descrsetfunc)getset_set, /* tp_descr_set */ + PyVarObject_HEAD_INIT(&PyType_Type, 0) + "getset_descriptor", + sizeof(PyGetSetDescrObject), + 0, + (destructor)descr_dealloc, /* tp_dealloc */ + 0, /* tp_print */ + 0, /* tp_getattr */ + 0, /* tp_setattr */ + 0, /* tp_reserved */ + (reprfunc)getset_repr, /* 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 */ + descr_traverse, /* tp_traverse */ + 0, /* tp_clear */ + 0, /* tp_richcompare */ + 0, /* tp_weaklistoffset */ + 0, /* tp_iter */ + 0, /* tp_iternext */ + 0, /* tp_methods */ + descr_members, /* tp_members */ + getset_getset, /* tp_getset */ + 0, /* tp_base */ + 0, /* tp_dict */ + (descrgetfunc)getset_get, /* tp_descr_get */ + (descrsetfunc)getset_set, /* tp_descr_set */ }; PyTypeObject PyWrapperDescr_Type = { - PyVarObject_HEAD_INIT(&PyType_Type, 0) - "wrapper_descriptor", - sizeof(PyWrapperDescrObject), - 0, - (destructor)descr_dealloc, /* tp_dealloc */ - 0, /* tp_print */ - 0, /* tp_getattr */ - 0, /* tp_setattr */ - 0, /* tp_reserved */ - (reprfunc)wrapperdescr_repr, /* tp_repr */ - 0, /* tp_as_number */ - 0, /* tp_as_sequence */ - 0, /* tp_as_mapping */ - 0, /* tp_hash */ - (ternaryfunc)wrapperdescr_call, /* 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 */ - descr_traverse, /* tp_traverse */ - 0, /* tp_clear */ - 0, /* tp_richcompare */ - 0, /* tp_weaklistoffset */ - 0, /* tp_iter */ - 0, /* tp_iternext */ - 0, /* tp_methods */ - descr_members, /* tp_members */ - wrapperdescr_getset, /* tp_getset */ - 0, /* tp_base */ - 0, /* tp_dict */ - (descrgetfunc)wrapperdescr_get, /* tp_descr_get */ - 0, /* tp_descr_set */ + PyVarObject_HEAD_INIT(&PyType_Type, 0) + "wrapper_descriptor", + sizeof(PyWrapperDescrObject), + 0, + (destructor)descr_dealloc, /* tp_dealloc */ + 0, /* tp_print */ + 0, /* tp_getattr */ + 0, /* tp_setattr */ + 0, /* tp_reserved */ + (reprfunc)wrapperdescr_repr, /* tp_repr */ + 0, /* tp_as_number */ + 0, /* tp_as_sequence */ + 0, /* tp_as_mapping */ + 0, /* tp_hash */ + (ternaryfunc)wrapperdescr_call, /* 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 */ + descr_traverse, /* tp_traverse */ + 0, /* tp_clear */ + 0, /* tp_richcompare */ + 0, /* tp_weaklistoffset */ + 0, /* tp_iter */ + 0, /* tp_iternext */ + 0, /* tp_methods */ + descr_members, /* tp_members */ + wrapperdescr_getset, /* tp_getset */ + 0, /* tp_base */ + 0, /* tp_dict */ + (descrgetfunc)wrapperdescr_get, /* tp_descr_get */ + 0, /* tp_descr_set */ }; static PyDescrObject * descr_new(PyTypeObject *descrtype, PyTypeObject *type, const char *name) { - PyDescrObject *descr; + PyDescrObject *descr; - descr = (PyDescrObject *)PyType_GenericAlloc(descrtype, 0); - if (descr != NULL) { - Py_XINCREF(type); - descr->d_type = type; - descr->d_name = PyUnicode_InternFromString(name); - if (descr->d_name == NULL) { - Py_DECREF(descr); - descr = NULL; - } - } - return descr; + descr = (PyDescrObject *)PyType_GenericAlloc(descrtype, 0); + if (descr != NULL) { + Py_XINCREF(type); + descr->d_type = type; + descr->d_name = PyUnicode_InternFromString(name); + if (descr->d_name == NULL) { + Py_DECREF(descr); + descr = NULL; + } + } + return descr; } PyObject * PyDescr_NewMethod(PyTypeObject *type, PyMethodDef *method) { - PyMethodDescrObject *descr; + PyMethodDescrObject *descr; - descr = (PyMethodDescrObject *)descr_new(&PyMethodDescr_Type, - type, method->ml_name); - if (descr != NULL) - descr->d_method = method; - return (PyObject *)descr; + descr = (PyMethodDescrObject *)descr_new(&PyMethodDescr_Type, + type, method->ml_name); + if (descr != NULL) + descr->d_method = method; + return (PyObject *)descr; } PyObject * PyDescr_NewClassMethod(PyTypeObject *type, PyMethodDef *method) { - PyMethodDescrObject *descr; + PyMethodDescrObject *descr; - descr = (PyMethodDescrObject *)descr_new(&PyClassMethodDescr_Type, - type, method->ml_name); - if (descr != NULL) - descr->d_method = method; - return (PyObject *)descr; + descr = (PyMethodDescrObject *)descr_new(&PyClassMethodDescr_Type, + type, method->ml_name); + if (descr != NULL) + descr->d_method = method; + return (PyObject *)descr; } PyObject * PyDescr_NewMember(PyTypeObject *type, PyMemberDef *member) { - PyMemberDescrObject *descr; + PyMemberDescrObject *descr; - descr = (PyMemberDescrObject *)descr_new(&PyMemberDescr_Type, - type, member->name); - if (descr != NULL) - descr->d_member = member; - return (PyObject *)descr; + descr = (PyMemberDescrObject *)descr_new(&PyMemberDescr_Type, + type, member->name); + if (descr != NULL) + descr->d_member = member; + return (PyObject *)descr; } PyObject * PyDescr_NewGetSet(PyTypeObject *type, PyGetSetDef *getset) { - PyGetSetDescrObject *descr; + PyGetSetDescrObject *descr; - descr = (PyGetSetDescrObject *)descr_new(&PyGetSetDescr_Type, - type, getset->name); - if (descr != NULL) - descr->d_getset = getset; - return (PyObject *)descr; + descr = (PyGetSetDescrObject *)descr_new(&PyGetSetDescr_Type, + type, getset->name); + if (descr != NULL) + descr->d_getset = getset; + return (PyObject *)descr; } PyObject * PyDescr_NewWrapper(PyTypeObject *type, struct wrapperbase *base, void *wrapped) { - PyWrapperDescrObject *descr; + PyWrapperDescrObject *descr; - descr = (PyWrapperDescrObject *)descr_new(&PyWrapperDescr_Type, - type, base->name); - if (descr != NULL) { - descr->d_base = base; - descr->d_wrapped = wrapped; - } - return (PyObject *)descr; + descr = (PyWrapperDescrObject *)descr_new(&PyWrapperDescr_Type, + type, base->name); + if (descr != NULL) { + descr->d_base = base; + descr->d_wrapped = wrapped; + } + return (PyObject *)descr; } @@ -656,180 +656,180 @@ bit of a pain */ typedef struct { - PyObject_HEAD - PyObject *dict; + PyObject_HEAD + PyObject *dict; } proxyobject; static Py_ssize_t proxy_len(proxyobject *pp) { - return PyObject_Size(pp->dict); + return PyObject_Size(pp->dict); } static PyObject * proxy_getitem(proxyobject *pp, PyObject *key) { - return PyObject_GetItem(pp->dict, key); + return PyObject_GetItem(pp->dict, key); } static PyMappingMethods proxy_as_mapping = { - (lenfunc)proxy_len, /* mp_length */ - (binaryfunc)proxy_getitem, /* mp_subscript */ - 0, /* mp_ass_subscript */ + (lenfunc)proxy_len, /* mp_length */ + (binaryfunc)proxy_getitem, /* mp_subscript */ + 0, /* mp_ass_subscript */ }; static int proxy_contains(proxyobject *pp, PyObject *key) { - return PyDict_Contains(pp->dict, key); + return PyDict_Contains(pp->dict, key); } static PySequenceMethods proxy_as_sequence = { - 0, /* sq_length */ - 0, /* sq_concat */ - 0, /* sq_repeat */ - 0, /* sq_item */ - 0, /* sq_slice */ - 0, /* sq_ass_item */ - 0, /* sq_ass_slice */ - (objobjproc)proxy_contains, /* sq_contains */ - 0, /* sq_inplace_concat */ - 0, /* sq_inplace_repeat */ + 0, /* sq_length */ + 0, /* sq_concat */ + 0, /* sq_repeat */ + 0, /* sq_item */ + 0, /* sq_slice */ + 0, /* sq_ass_item */ + 0, /* sq_ass_slice */ + (objobjproc)proxy_contains, /* sq_contains */ + 0, /* sq_inplace_concat */ + 0, /* sq_inplace_repeat */ }; static PyObject * proxy_get(proxyobject *pp, PyObject *args) { - PyObject *key, *def = Py_None; + PyObject *key, *def = Py_None; - if (!PyArg_UnpackTuple(args, "get", 1, 2, &key, &def)) - return NULL; - return PyObject_CallMethod(pp->dict, "get", "(OO)", key, def); + if (!PyArg_UnpackTuple(args, "get", 1, 2, &key, &def)) + return NULL; + return PyObject_CallMethod(pp->dict, "get", "(OO)", key, def); } static PyObject * proxy_keys(proxyobject *pp) { - return PyMapping_Keys(pp->dict); + return PyMapping_Keys(pp->dict); } static PyObject * proxy_values(proxyobject *pp) { - return PyMapping_Values(pp->dict); + return PyMapping_Values(pp->dict); } static PyObject * proxy_items(proxyobject *pp) { - return PyMapping_Items(pp->dict); + return PyMapping_Items(pp->dict); } static PyObject * proxy_copy(proxyobject *pp) { - return PyObject_CallMethod(pp->dict, "copy", NULL); + return PyObject_CallMethod(pp->dict, "copy", NULL); } static PyMethodDef proxy_methods[] = { - {"get", (PyCFunction)proxy_get, METH_VARARGS, - PyDoc_STR("D.get(k[,d]) -> D[k] if k in D, else d." - " d defaults to None.")}, - {"keys", (PyCFunction)proxy_keys, METH_NOARGS, - PyDoc_STR("D.keys() -> list of D's keys")}, - {"values", (PyCFunction)proxy_values, METH_NOARGS, - PyDoc_STR("D.values() -> list of D's values")}, - {"items", (PyCFunction)proxy_items, METH_NOARGS, - PyDoc_STR("D.items() -> list of D's (key, value) pairs, as 2-tuples")}, - {"copy", (PyCFunction)proxy_copy, METH_NOARGS, - PyDoc_STR("D.copy() -> a shallow copy of D")}, - {0} + {"get", (PyCFunction)proxy_get, METH_VARARGS, + PyDoc_STR("D.get(k[,d]) -> D[k] if k in D, else d." + " d defaults to None.")}, + {"keys", (PyCFunction)proxy_keys, METH_NOARGS, + PyDoc_STR("D.keys() -> list of D's keys")}, + {"values", (PyCFunction)proxy_values, METH_NOARGS, + PyDoc_STR("D.values() -> list of D's values")}, + {"items", (PyCFunction)proxy_items, METH_NOARGS, + PyDoc_STR("D.items() -> list of D's (key, value) pairs, as 2-tuples")}, + {"copy", (PyCFunction)proxy_copy, METH_NOARGS, + PyDoc_STR("D.copy() -> a shallow copy of D")}, + {0} }; static void proxy_dealloc(proxyobject *pp) { - _PyObject_GC_UNTRACK(pp); - Py_DECREF(pp->dict); - PyObject_GC_Del(pp); + _PyObject_GC_UNTRACK(pp); + Py_DECREF(pp->dict); + PyObject_GC_Del(pp); } static PyObject * proxy_getiter(proxyobject *pp) { - return PyObject_GetIter(pp->dict); + return PyObject_GetIter(pp->dict); } static PyObject * proxy_str(proxyobject *pp) { - return PyObject_Str(pp->dict); + return PyObject_Str(pp->dict); } static int proxy_traverse(PyObject *self, visitproc visit, void *arg) { - proxyobject *pp = (proxyobject *)self; - Py_VISIT(pp->dict); - return 0; + proxyobject *pp = (proxyobject *)self; + Py_VISIT(pp->dict); + return 0; } static PyObject * proxy_richcompare(proxyobject *v, PyObject *w, int op) { - return PyObject_RichCompare(v->dict, w, op); + return PyObject_RichCompare(v->dict, w, op); } PyTypeObject PyDictProxy_Type = { - PyVarObject_HEAD_INIT(&PyType_Type, 0) - "dict_proxy", /* tp_name */ - sizeof(proxyobject), /* tp_basicsize */ - 0, /* tp_itemsize */ - /* methods */ - (destructor)proxy_dealloc, /* tp_dealloc */ - 0, /* tp_print */ - 0, /* tp_getattr */ - 0, /* tp_setattr */ - 0, /* tp_reserved */ - 0, /* tp_repr */ - 0, /* tp_as_number */ - &proxy_as_sequence, /* tp_as_sequence */ - &proxy_as_mapping, /* tp_as_mapping */ - 0, /* tp_hash */ - 0, /* tp_call */ - (reprfunc)proxy_str, /* 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 */ - proxy_traverse, /* tp_traverse */ - 0, /* tp_clear */ - (richcmpfunc)proxy_richcompare, /* tp_richcompare */ - 0, /* tp_weaklistoffset */ - (getiterfunc)proxy_getiter, /* tp_iter */ - 0, /* tp_iternext */ - proxy_methods, /* tp_methods */ - 0, /* tp_members */ - 0, /* tp_getset */ - 0, /* tp_base */ - 0, /* tp_dict */ - 0, /* tp_descr_get */ - 0, /* tp_descr_set */ + PyVarObject_HEAD_INIT(&PyType_Type, 0) + "dict_proxy", /* tp_name */ + sizeof(proxyobject), /* tp_basicsize */ + 0, /* tp_itemsize */ + /* methods */ + (destructor)proxy_dealloc, /* tp_dealloc */ + 0, /* tp_print */ + 0, /* tp_getattr */ + 0, /* tp_setattr */ + 0, /* tp_reserved */ + 0, /* tp_repr */ + 0, /* tp_as_number */ + &proxy_as_sequence, /* tp_as_sequence */ + &proxy_as_mapping, /* tp_as_mapping */ + 0, /* tp_hash */ + 0, /* tp_call */ + (reprfunc)proxy_str, /* 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 */ + proxy_traverse, /* tp_traverse */ + 0, /* tp_clear */ + (richcmpfunc)proxy_richcompare, /* tp_richcompare */ + 0, /* tp_weaklistoffset */ + (getiterfunc)proxy_getiter, /* tp_iter */ + 0, /* tp_iternext */ + proxy_methods, /* tp_methods */ + 0, /* tp_members */ + 0, /* tp_getset */ + 0, /* tp_base */ + 0, /* tp_dict */ + 0, /* tp_descr_get */ + 0, /* tp_descr_set */ }; PyObject * PyDictProxy_New(PyObject *dict) { - proxyobject *pp; + proxyobject *pp; - pp = PyObject_GC_New(proxyobject, &PyDictProxy_Type); - if (pp != NULL) { - Py_INCREF(dict); - pp->dict = dict; - _PyObject_GC_TRACK(pp); - } - return (PyObject *)pp; + pp = PyObject_GC_New(proxyobject, &PyDictProxy_Type); + if (pp != NULL) { + Py_INCREF(dict); + pp->dict = dict; + _PyObject_GC_TRACK(pp); + } + return (PyObject *)pp; } @@ -842,9 +842,9 @@ static PyTypeObject wrappertype; typedef struct { - PyObject_HEAD - PyWrapperDescrObject *descr; - PyObject *self; + PyObject_HEAD + PyWrapperDescrObject *descr; + PyObject *self; } wrapperobject; #define Wrapper_Check(v) (Py_TYPE(v) == &wrappertype) @@ -852,12 +852,12 @@ static void wrapper_dealloc(wrapperobject *wp) { - PyObject_GC_UnTrack(wp); - Py_TRASHCAN_SAFE_BEGIN(wp) - Py_XDECREF(wp->descr); - Py_XDECREF(wp->self); - PyObject_GC_Del(wp); - Py_TRASHCAN_SAFE_END(wp) + PyObject_GC_UnTrack(wp); + Py_TRASHCAN_SAFE_BEGIN(wp) + Py_XDECREF(wp->descr); + Py_XDECREF(wp->self); + PyObject_GC_Del(wp); + Py_TRASHCAN_SAFE_END(wp) } #define TEST_COND(cond) ((cond) ? Py_True : Py_False) @@ -865,211 +865,211 @@ static PyObject * wrapper_richcompare(PyObject *a, PyObject *b, int op) { - int result; - PyObject *v; - PyWrapperDescrObject *a_descr, *b_descr; - - assert(a != NULL && b != NULL); - - /* both arguments should be wrapperobjects */ - if (!Wrapper_Check(a) || !Wrapper_Check(b)) { - v = Py_NotImplemented; - Py_INCREF(v); - return v; - } - - /* compare by descriptor address; if the descriptors are the same, - compare by the objects they're bound to */ - a_descr = ((wrapperobject *)a)->descr; - b_descr = ((wrapperobject *)b)->descr; - if (a_descr == b_descr) { - a = ((wrapperobject *)a)->self; - b = ((wrapperobject *)b)->self; - return PyObject_RichCompare(a, b, op); - } - - result = a_descr - b_descr; - switch (op) { - case Py_EQ: - v = TEST_COND(result == 0); - break; - case Py_NE: - v = TEST_COND(result != 0); - break; - case Py_LE: - v = TEST_COND(result <= 0); - break; - case Py_GE: - v = TEST_COND(result >= 0); - break; - case Py_LT: - v = TEST_COND(result < 0); - break; - case Py_GT: - v = TEST_COND(result > 0); - break; - default: - PyErr_BadArgument(); - return NULL; - } - Py_INCREF(v); - return v; + int result; + PyObject *v; + PyWrapperDescrObject *a_descr, *b_descr; + + assert(a != NULL && b != NULL); + + /* both arguments should be wrapperobjects */ + if (!Wrapper_Check(a) || !Wrapper_Check(b)) { + v = Py_NotImplemented; + Py_INCREF(v); + return v; + } + + /* compare by descriptor address; if the descriptors are the same, + compare by the objects they're bound to */ + a_descr = ((wrapperobject *)a)->descr; + b_descr = ((wrapperobject *)b)->descr; + if (a_descr == b_descr) { + a = ((wrapperobject *)a)->self; + b = ((wrapperobject *)b)->self; + return PyObject_RichCompare(a, b, op); + } + + result = a_descr - b_descr; + switch (op) { + case Py_EQ: + v = TEST_COND(result == 0); + break; + case Py_NE: + v = TEST_COND(result != 0); + break; + case Py_LE: + v = TEST_COND(result <= 0); + break; + case Py_GE: + v = TEST_COND(result >= 0); + break; + case Py_LT: + v = TEST_COND(result < 0); + break; + case Py_GT: + v = TEST_COND(result > 0); + break; + default: + PyErr_BadArgument(); + return NULL; + } + Py_INCREF(v); + return v; } static long wrapper_hash(wrapperobject *wp) { - int x, y; - x = _Py_HashPointer(wp->descr); - if (x == -1) - return -1; - y = PyObject_Hash(wp->self); - if (y == -1) - return -1; - x = x ^ y; - if (x == -1) - x = -2; - return x; + int x, y; + x = _Py_HashPointer(wp->descr); + if (x == -1) + return -1; + y = PyObject_Hash(wp->self); + if (y == -1) + return -1; + x = x ^ y; + if (x == -1) + x = -2; + return x; } static PyObject * wrapper_repr(wrapperobject *wp) { - return PyUnicode_FromFormat("", - wp->descr->d_base->name, - wp->self->ob_type->tp_name, - wp->self); + return PyUnicode_FromFormat("", + wp->descr->d_base->name, + wp->self->ob_type->tp_name, + wp->self); } static PyMemberDef wrapper_members[] = { - {"__self__", T_OBJECT, offsetof(wrapperobject, self), READONLY}, - {0} + {"__self__", T_OBJECT, offsetof(wrapperobject, self), READONLY}, + {0} }; static PyObject * wrapper_objclass(wrapperobject *wp) { - PyObject *c = (PyObject *)PyDescr_TYPE(wp->descr); + PyObject *c = (PyObject *)PyDescr_TYPE(wp->descr); - Py_INCREF(c); - return c; + Py_INCREF(c); + return c; } static PyObject * wrapper_name(wrapperobject *wp) { - const char *s = wp->descr->d_base->name; + const char *s = wp->descr->d_base->name; - return PyUnicode_FromString(s); + return PyUnicode_FromString(s); } static PyObject * wrapper_doc(wrapperobject *wp) { - const char *s = wp->descr->d_base->doc; + const char *s = wp->descr->d_base->doc; - if (s == NULL) { - Py_INCREF(Py_None); - return Py_None; - } - else { - return PyUnicode_FromString(s); - } + if (s == NULL) { + Py_INCREF(Py_None); + return Py_None; + } + else { + return PyUnicode_FromString(s); + } } static PyGetSetDef wrapper_getsets[] = { - {"__objclass__", (getter)wrapper_objclass}, - {"__name__", (getter)wrapper_name}, - {"__doc__", (getter)wrapper_doc}, - {0} + {"__objclass__", (getter)wrapper_objclass}, + {"__name__", (getter)wrapper_name}, + {"__doc__", (getter)wrapper_doc}, + {0} }; static PyObject * wrapper_call(wrapperobject *wp, PyObject *args, PyObject *kwds) { - wrapperfunc wrapper = wp->descr->d_base->wrapper; - PyObject *self = wp->self; + wrapperfunc wrapper = wp->descr->d_base->wrapper; + PyObject *self = wp->self; - if (wp->descr->d_base->flags & PyWrapperFlag_KEYWORDS) { - wrapperfunc_kwds wk = (wrapperfunc_kwds)wrapper; - return (*wk)(self, args, wp->descr->d_wrapped, kwds); - } - - if (kwds != NULL && (!PyDict_Check(kwds) || PyDict_Size(kwds) != 0)) { - PyErr_Format(PyExc_TypeError, - "wrapper %s doesn't take keyword arguments", - wp->descr->d_base->name); - return NULL; - } - return (*wrapper)(self, args, wp->descr->d_wrapped); + if (wp->descr->d_base->flags & PyWrapperFlag_KEYWORDS) { + wrapperfunc_kwds wk = (wrapperfunc_kwds)wrapper; + return (*wk)(self, args, wp->descr->d_wrapped, kwds); + } + + if (kwds != NULL && (!PyDict_Check(kwds) || PyDict_Size(kwds) != 0)) { + PyErr_Format(PyExc_TypeError, + "wrapper %s doesn't take keyword arguments", + wp->descr->d_base->name); + return NULL; + } + return (*wrapper)(self, args, wp->descr->d_wrapped); } static int wrapper_traverse(PyObject *self, visitproc visit, void *arg) { - wrapperobject *wp = (wrapperobject *)self; - Py_VISIT(wp->descr); - Py_VISIT(wp->self); - return 0; + wrapperobject *wp = (wrapperobject *)self; + Py_VISIT(wp->descr); + Py_VISIT(wp->self); + return 0; } static PyTypeObject wrappertype = { - PyVarObject_HEAD_INIT(&PyType_Type, 0) - "method-wrapper", /* tp_name */ - sizeof(wrapperobject), /* tp_basicsize */ - 0, /* tp_itemsize */ - /* methods */ - (destructor)wrapper_dealloc, /* tp_dealloc */ - 0, /* tp_print */ - 0, /* tp_getattr */ - 0, /* tp_setattr */ - 0, /* tp_reserved */ - (reprfunc)wrapper_repr, /* tp_repr */ - 0, /* tp_as_number */ - 0, /* tp_as_sequence */ - 0, /* tp_as_mapping */ - (hashfunc)wrapper_hash, /* tp_hash */ - (ternaryfunc)wrapper_call, /* 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 */ - wrapper_traverse, /* tp_traverse */ - 0, /* tp_clear */ - wrapper_richcompare, /* tp_richcompare */ - 0, /* tp_weaklistoffset */ - 0, /* tp_iter */ - 0, /* tp_iternext */ - 0, /* tp_methods */ - wrapper_members, /* tp_members */ - wrapper_getsets, /* tp_getset */ - 0, /* tp_base */ - 0, /* tp_dict */ - 0, /* tp_descr_get */ - 0, /* tp_descr_set */ + PyVarObject_HEAD_INIT(&PyType_Type, 0) + "method-wrapper", /* tp_name */ + sizeof(wrapperobject), /* tp_basicsize */ + 0, /* tp_itemsize */ + /* methods */ + (destructor)wrapper_dealloc, /* tp_dealloc */ + 0, /* tp_print */ + 0, /* tp_getattr */ + 0, /* tp_setattr */ + 0, /* tp_reserved */ + (reprfunc)wrapper_repr, /* tp_repr */ + 0, /* tp_as_number */ + 0, /* tp_as_sequence */ + 0, /* tp_as_mapping */ + (hashfunc)wrapper_hash, /* tp_hash */ + (ternaryfunc)wrapper_call, /* 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 */ + wrapper_traverse, /* tp_traverse */ + 0, /* tp_clear */ + wrapper_richcompare, /* tp_richcompare */ + 0, /* tp_weaklistoffset */ + 0, /* tp_iter */ + 0, /* tp_iternext */ + 0, /* tp_methods */ + wrapper_members, /* tp_members */ + wrapper_getsets, /* tp_getset */ + 0, /* tp_base */ + 0, /* tp_dict */ + 0, /* tp_descr_get */ + 0, /* tp_descr_set */ }; PyObject * PyWrapper_New(PyObject *d, PyObject *self) { - wrapperobject *wp; - PyWrapperDescrObject *descr; + wrapperobject *wp; + PyWrapperDescrObject *descr; - assert(PyObject_TypeCheck(d, &PyWrapperDescr_Type)); - descr = (PyWrapperDescrObject *)d; - assert(PyObject_IsInstance(self, (PyObject *)PyDescr_TYPE(descr))); - - wp = PyObject_GC_New(wrapperobject, &wrappertype); - if (wp != NULL) { - Py_INCREF(descr); - wp->descr = descr; - Py_INCREF(self); - wp->self = self; - _PyObject_GC_TRACK(wp); - } - return (PyObject *)wp; + assert(PyObject_TypeCheck(d, &PyWrapperDescr_Type)); + descr = (PyWrapperDescrObject *)d; + assert(PyObject_IsInstance(self, (PyObject *)PyDescr_TYPE(descr))); + + wp = PyObject_GC_New(wrapperobject, &wrappertype); + if (wp != NULL) { + Py_INCREF(descr); + wp->descr = descr; + Py_INCREF(self); + wp->self = self; + _PyObject_GC_TRACK(wp); + } + return (PyObject *)wp; } @@ -1078,247 +1078,247 @@ /* class property(object): - def __init__(self, fget=None, fset=None, fdel=None, doc=None): - if doc is None and fget is not None and hasattr(fget, "__doc__"): - doc = fget.__doc__ - self.__get = fget - self.__set = fset - self.__del = fdel - self.__doc__ = doc - - def __get__(self, inst, type=None): - if inst is None: - return self - if self.__get is None: - raise AttributeError, "unreadable attribute" - return self.__get(inst) - - def __set__(self, inst, value): - if self.__set is None: - raise AttributeError, "can't set attribute" - return self.__set(inst, value) - - def __delete__(self, inst): - if self.__del is None: - raise AttributeError, "can't delete attribute" - return self.__del(inst) + def __init__(self, fget=None, fset=None, fdel=None, doc=None): + if doc is None and fget is not None and hasattr(fget, "__doc__"): + doc = fget.__doc__ + self.__get = fget + self.__set = fset + self.__del = fdel + self.__doc__ = doc + + def __get__(self, inst, type=None): + if inst is None: + return self + if self.__get is None: + raise AttributeError, "unreadable attribute" + return self.__get(inst) + + def __set__(self, inst, value): + if self.__set is None: + raise AttributeError, "can't set attribute" + return self.__set(inst, value) + + def __delete__(self, inst): + if self.__del is None: + raise AttributeError, "can't delete attribute" + return self.__del(inst) */ typedef struct { - PyObject_HEAD - PyObject *prop_get; - PyObject *prop_set; - PyObject *prop_del; - PyObject *prop_doc; - int getter_doc; + PyObject_HEAD + PyObject *prop_get; + PyObject *prop_set; + PyObject *prop_del; + PyObject *prop_doc; + int getter_doc; } propertyobject; static PyObject * property_copy(PyObject *, PyObject *, PyObject *, - PyObject *, PyObject *); + PyObject *, PyObject *); static PyMemberDef property_members[] = { - {"fget", T_OBJECT, offsetof(propertyobject, prop_get), READONLY}, - {"fset", T_OBJECT, offsetof(propertyobject, prop_set), READONLY}, - {"fdel", T_OBJECT, offsetof(propertyobject, prop_del), READONLY}, - {"__doc__", T_OBJECT, offsetof(propertyobject, prop_doc), READONLY}, - {0} + {"fget", T_OBJECT, offsetof(propertyobject, prop_get), READONLY}, + {"fset", T_OBJECT, offsetof(propertyobject, prop_set), READONLY}, + {"fdel", T_OBJECT, offsetof(propertyobject, prop_del), READONLY}, + {"__doc__", T_OBJECT, offsetof(propertyobject, prop_doc), READONLY}, + {0} }; PyDoc_STRVAR(getter_doc, - "Descriptor to change the getter on a property."); + "Descriptor to change the getter on a property."); static PyObject * property_getter(PyObject *self, PyObject *getter) { - return property_copy(self, getter, NULL, NULL, NULL); + return property_copy(self, getter, NULL, NULL, NULL); } PyDoc_STRVAR(setter_doc, - "Descriptor to change the setter on a property."); + "Descriptor to change the setter on a property."); static PyObject * property_setter(PyObject *self, PyObject *setter) { - return property_copy(self, NULL, setter, NULL, NULL); + return property_copy(self, NULL, setter, NULL, NULL); } PyDoc_STRVAR(deleter_doc, - "Descriptor to change the deleter on a property."); + "Descriptor to change the deleter on a property."); static PyObject * property_deleter(PyObject *self, PyObject *deleter) { - return property_copy(self, NULL, NULL, deleter, NULL); + return property_copy(self, NULL, NULL, deleter, NULL); } static PyMethodDef property_methods[] = { - {"getter", property_getter, METH_O, getter_doc}, - {"setter", property_setter, METH_O, setter_doc}, - {"deleter", property_deleter, METH_O, deleter_doc}, - {0} + {"getter", property_getter, METH_O, getter_doc}, + {"setter", property_setter, METH_O, setter_doc}, + {"deleter", property_deleter, METH_O, deleter_doc}, + {0} }; static void property_dealloc(PyObject *self) { - propertyobject *gs = (propertyobject *)self; + propertyobject *gs = (propertyobject *)self; - _PyObject_GC_UNTRACK(self); - Py_XDECREF(gs->prop_get); - Py_XDECREF(gs->prop_set); - Py_XDECREF(gs->prop_del); - Py_XDECREF(gs->prop_doc); - self->ob_type->tp_free(self); + _PyObject_GC_UNTRACK(self); + Py_XDECREF(gs->prop_get); + Py_XDECREF(gs->prop_set); + Py_XDECREF(gs->prop_del); + Py_XDECREF(gs->prop_doc); + self->ob_type->tp_free(self); } static PyObject * property_descr_get(PyObject *self, PyObject *obj, PyObject *type) { - propertyobject *gs = (propertyobject *)self; + propertyobject *gs = (propertyobject *)self; - if (obj == NULL || obj == Py_None) { - Py_INCREF(self); - return self; - } - if (gs->prop_get == NULL) { - PyErr_SetString(PyExc_AttributeError, "unreadable attribute"); - return NULL; - } - return PyObject_CallFunction(gs->prop_get, "(O)", obj); + if (obj == NULL || obj == Py_None) { + Py_INCREF(self); + return self; + } + if (gs->prop_get == NULL) { + PyErr_SetString(PyExc_AttributeError, "unreadable attribute"); + return NULL; + } + return PyObject_CallFunction(gs->prop_get, "(O)", obj); } static int property_descr_set(PyObject *self, PyObject *obj, PyObject *value) { - propertyobject *gs = (propertyobject *)self; - PyObject *func, *res; + propertyobject *gs = (propertyobject *)self; + PyObject *func, *res; - if (value == NULL) - func = gs->prop_del; - else - func = gs->prop_set; - if (func == NULL) { - PyErr_SetString(PyExc_AttributeError, - value == NULL ? - "can't delete attribute" : - "can't set attribute"); - return -1; - } - if (value == NULL) - res = PyObject_CallFunction(func, "(O)", obj); - else - res = PyObject_CallFunction(func, "(OO)", obj, value); - if (res == NULL) - return -1; - Py_DECREF(res); - return 0; + if (value == NULL) + func = gs->prop_del; + else + func = gs->prop_set; + if (func == NULL) { + PyErr_SetString(PyExc_AttributeError, + value == NULL ? + "can't delete attribute" : + "can't set attribute"); + return -1; + } + if (value == NULL) + res = PyObject_CallFunction(func, "(O)", obj); + else + res = PyObject_CallFunction(func, "(OO)", obj, value); + if (res == NULL) + return -1; + Py_DECREF(res); + return 0; } static PyObject * property_copy(PyObject *old, PyObject *get, PyObject *set, PyObject *del, - PyObject *doc) + PyObject *doc) { - propertyobject *pold = (propertyobject *)old; - PyObject *new, *type; + propertyobject *pold = (propertyobject *)old; + PyObject *new, *type; - type = PyObject_Type(old); - if (type == NULL) - return NULL; - - if (get == NULL || get == Py_None) { - Py_XDECREF(get); - get = pold->prop_get ? pold->prop_get : Py_None; - } - if (set == NULL || set == Py_None) { - Py_XDECREF(set); - set = pold->prop_set ? pold->prop_set : Py_None; - } - if (del == NULL || del == Py_None) { - Py_XDECREF(del); - del = pold->prop_del ? pold->prop_del : Py_None; - } - if (doc == NULL || doc == Py_None) { - Py_XDECREF(doc); - if (pold->getter_doc && get != Py_None) { - /* make _init use __doc__ from getter */ - doc = Py_None; - } - else { - doc = pold->prop_doc ? pold->prop_doc : Py_None; - } - } - - new = PyObject_CallFunction(type, "OOOO", get, set, del, doc); - Py_DECREF(type); - if (new == NULL) - return NULL; - return new; + type = PyObject_Type(old); + if (type == NULL) + return NULL; + + if (get == NULL || get == Py_None) { + Py_XDECREF(get); + get = pold->prop_get ? pold->prop_get : Py_None; + } + if (set == NULL || set == Py_None) { + Py_XDECREF(set); + set = pold->prop_set ? pold->prop_set : Py_None; + } + if (del == NULL || del == Py_None) { + Py_XDECREF(del); + del = pold->prop_del ? pold->prop_del : Py_None; + } + if (doc == NULL || doc == Py_None) { + Py_XDECREF(doc); + if (pold->getter_doc && get != Py_None) { + /* make _init use __doc__ from getter */ + doc = Py_None; + } + else { + doc = pold->prop_doc ? pold->prop_doc : Py_None; + } + } + + new = PyObject_CallFunction(type, "OOOO", get, set, del, doc); + Py_DECREF(type); + if (new == NULL) + return NULL; + return new; } static int property_init(PyObject *self, PyObject *args, PyObject *kwds) { - PyObject *get = NULL, *set = NULL, *del = NULL, *doc = NULL; - static char *kwlist[] = {"fget", "fset", "fdel", "doc", 0}; - propertyobject *prop = (propertyobject *)self; - - if (!PyArg_ParseTupleAndKeywords(args, kwds, "|OOOO:property", - kwlist, &get, &set, &del, &doc)) - return -1; - - if (get == Py_None) - get = NULL; - if (set == Py_None) - set = NULL; - if (del == Py_None) - del = NULL; - - Py_XINCREF(get); - Py_XINCREF(set); - Py_XINCREF(del); - Py_XINCREF(doc); - - prop->prop_get = get; - prop->prop_set = set; - prop->prop_del = del; - prop->prop_doc = doc; - prop->getter_doc = 0; - - /* if no docstring given and the getter has one, use that one */ - if ((doc == NULL || doc == Py_None) && get != NULL) { - PyObject *get_doc = PyObject_GetAttrString(get, "__doc__"); - if (get_doc) { - if (Py_TYPE(self) == &PyProperty_Type) { - Py_XDECREF(prop->prop_doc); - prop->prop_doc = get_doc; - } - else { - /* If this is a property subclass, put __doc__ - in dict of the subclass instance instead, - otherwise it gets shadowed by __doc__ in the - class's dict. */ - int err = PyObject_SetAttrString(self, "__doc__", get_doc); - Py_DECREF(get_doc); - if (err < 0) - return -1; - } - prop->getter_doc = 1; - } - else if (PyErr_ExceptionMatches(PyExc_Exception)) { - PyErr_Clear(); - } - else { - return -1; - } - } + PyObject *get = NULL, *set = NULL, *del = NULL, *doc = NULL; + static char *kwlist[] = {"fget", "fset", "fdel", "doc", 0}; + propertyobject *prop = (propertyobject *)self; + + if (!PyArg_ParseTupleAndKeywords(args, kwds, "|OOOO:property", + kwlist, &get, &set, &del, &doc)) + return -1; + + if (get == Py_None) + get = NULL; + if (set == Py_None) + set = NULL; + if (del == Py_None) + del = NULL; + + Py_XINCREF(get); + Py_XINCREF(set); + Py_XINCREF(del); + Py_XINCREF(doc); + + prop->prop_get = get; + prop->prop_set = set; + prop->prop_del = del; + prop->prop_doc = doc; + prop->getter_doc = 0; + + /* if no docstring given and the getter has one, use that one */ + if ((doc == NULL || doc == Py_None) && get != NULL) { + PyObject *get_doc = PyObject_GetAttrString(get, "__doc__"); + if (get_doc) { + if (Py_TYPE(self) == &PyProperty_Type) { + Py_XDECREF(prop->prop_doc); + prop->prop_doc = get_doc; + } + else { + /* If this is a property subclass, put __doc__ + in dict of the subclass instance instead, + otherwise it gets shadowed by __doc__ in the + class's dict. */ + int err = PyObject_SetAttrString(self, "__doc__", get_doc); + Py_DECREF(get_doc); + if (err < 0) + return -1; + } + prop->getter_doc = 1; + } + else if (PyErr_ExceptionMatches(PyExc_Exception)) { + PyErr_Clear(); + } + else { + return -1; + } + } - return 0; + return 0; } PyDoc_STRVAR(property_doc, @@ -1346,54 +1346,54 @@ static int property_traverse(PyObject *self, visitproc visit, void *arg) { - propertyobject *pp = (propertyobject *)self; - Py_VISIT(pp->prop_get); - Py_VISIT(pp->prop_set); - Py_VISIT(pp->prop_del); - Py_VISIT(pp->prop_doc); - return 0; + propertyobject *pp = (propertyobject *)self; + Py_VISIT(pp->prop_get); + Py_VISIT(pp->prop_set); + Py_VISIT(pp->prop_del); + Py_VISIT(pp->prop_doc); + return 0; } PyTypeObject PyProperty_Type = { - PyVarObject_HEAD_INIT(&PyType_Type, 0) - "property", /* tp_name */ - sizeof(propertyobject), /* tp_basicsize */ - 0, /* tp_itemsize */ - /* methods */ - property_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 | - Py_TPFLAGS_BASETYPE, /* tp_flags */ - property_doc, /* tp_doc */ - property_traverse, /* tp_traverse */ - 0, /* tp_clear */ - 0, /* tp_richcompare */ - 0, /* tp_weaklistoffset */ - 0, /* tp_iter */ - 0, /* tp_iternext */ - property_methods, /* tp_methods */ - property_members, /* tp_members */ - 0, /* tp_getset */ - 0, /* tp_base */ - 0, /* tp_dict */ - property_descr_get, /* tp_descr_get */ - property_descr_set, /* tp_descr_set */ - 0, /* tp_dictoffset */ - property_init, /* tp_init */ - PyType_GenericAlloc, /* tp_alloc */ - PyType_GenericNew, /* tp_new */ - PyObject_GC_Del, /* tp_free */ + PyVarObject_HEAD_INIT(&PyType_Type, 0) + "property", /* tp_name */ + sizeof(propertyobject), /* tp_basicsize */ + 0, /* tp_itemsize */ + /* methods */ + property_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 | + Py_TPFLAGS_BASETYPE, /* tp_flags */ + property_doc, /* tp_doc */ + property_traverse, /* tp_traverse */ + 0, /* tp_clear */ + 0, /* tp_richcompare */ + 0, /* tp_weaklistoffset */ + 0, /* tp_iter */ + 0, /* tp_iternext */ + property_methods, /* tp_methods */ + property_members, /* tp_members */ + 0, /* tp_getset */ + 0, /* tp_base */ + 0, /* tp_dict */ + property_descr_get, /* tp_descr_get */ + property_descr_set, /* tp_descr_set */ + 0, /* tp_dictoffset */ + property_init, /* tp_init */ + PyType_GenericAlloc, /* tp_alloc */ + PyType_GenericNew, /* tp_new */ + PyObject_GC_Del, /* tp_free */ }; Modified: python/branches/py3k-jit/Objects/dictobject.c ============================================================================== --- python/branches/py3k-jit/Objects/dictobject.c (original) +++ python/branches/py3k-jit/Objects/dictobject.c Mon May 10 23:55:43 2010 @@ -17,12 +17,12 @@ static void set_key_error(PyObject *arg) { - PyObject *tup; - tup = PyTuple_Pack(1, arg); - if (!tup) - return; /* caller will expect error to be set anyway */ - PyErr_SetObject(PyExc_KeyError, tup); - Py_DECREF(tup); + PyObject *tup; + tup = PyTuple_Pack(1, arg); + if (!tup) + return; /* caller will expect error to be set anyway */ + PyErr_SetObject(PyExc_KeyError, tup); + Py_DECREF(tup); } /* Define this out if you don't want conversion statistics on exit. */ @@ -52,7 +52,7 @@ OTOH, when collisions occur, the tendency to fill contiguous slices of the hash table makes a good collision resolution strategy crucial. Taking only the last i bits of the hash code is also vulnerable: for example, consider -the list [i << 16 for i in range(20000)] as a set of keys. Since ints are +the list [i << 16 for i in range(20000)] as a set of keys. Since ints are their own hash codes, and this fits in a dict of size 2**15, the last 15 bits of every hash code are all 0: they *all* map to the same table index. @@ -142,7 +142,7 @@ PyObject * _PyDict_Dummy(void) { - return dummy; + return dummy; } #endif @@ -157,9 +157,9 @@ static void show_counts(void) { - fprintf(stderr, "created %ld string dicts\n", created); - fprintf(stderr, "converted %ld to normal dicts\n", converted); - fprintf(stderr, "%.2f%% conversion rate\n", (100.0*converted)/created); + fprintf(stderr, "created %ld string dicts\n", created); + fprintf(stderr, "converted %ld to normal dicts\n", converted); + fprintf(stderr, "%.2f%% conversion rate\n", (100.0*converted)/created); } #endif @@ -172,12 +172,12 @@ static void show_alloc(void) { - fprintf(stderr, "Dict allocations: %" PY_FORMAT_SIZE_T "d\n", - count_alloc); - fprintf(stderr, "Dict reuse through freelist: %" PY_FORMAT_SIZE_T - "d\n", count_reuse); - fprintf(stderr, "%.2f%% reuse rate\n\n", - (100.0*count_reuse/(count_alloc+count_reuse))); + fprintf(stderr, "Dict allocations: %" PY_FORMAT_SIZE_T "d\n", + count_alloc); + fprintf(stderr, "Dict reuse through freelist: %" PY_FORMAT_SIZE_T + "d\n", count_reuse); + fprintf(stderr, "%.2f%% reuse rate\n\n", + (100.0*count_reuse/(count_alloc+count_reuse))); } #endif @@ -189,12 +189,12 @@ static void show_track(void) { - fprintf(stderr, "Dicts created: %" PY_FORMAT_SIZE_T "d\n", - count_tracked + count_untracked); - fprintf(stderr, "Dicts tracked by the GC: %" PY_FORMAT_SIZE_T - "d\n", count_tracked); - fprintf(stderr, "%.2f%% dict tracking rate\n\n", - (100.0*count_tracked/(count_untracked+count_tracked))); + fprintf(stderr, "Dicts created: %" PY_FORMAT_SIZE_T "d\n", + count_tracked + count_untracked); + fprintf(stderr, "Dicts tracked by the GC: %" PY_FORMAT_SIZE_T + "d\n", count_tracked); + fprintf(stderr, "%.2f%% dict tracking rate\n\n", + (100.0*count_tracked/(count_untracked+count_tracked))); } #endif @@ -208,15 +208,15 @@ an excellent reason not to). */ -#define INIT_NONZERO_DICT_SLOTS(mp) do { \ - (mp)->ma_table = (mp)->ma_smalltable; \ - (mp)->ma_mask = PyDict_MINSIZE - 1; \ +#define INIT_NONZERO_DICT_SLOTS(mp) do { \ + (mp)->ma_table = (mp)->ma_smalltable; \ + (mp)->ma_mask = PyDict_MINSIZE - 1; \ } while(0) -#define EMPTY_TO_MINSIZE(mp) do { \ - memset((mp)->ma_smalltable, 0, sizeof((mp)->ma_smalltable)); \ - (mp)->ma_used = (mp)->ma_fill = 0; \ - INIT_NONZERO_DICT_SLOTS(mp); \ +#define EMPTY_TO_MINSIZE(mp) do { \ + memset((mp)->ma_smalltable, 0, sizeof((mp)->ma_smalltable)); \ + (mp)->ma_used = (mp)->ma_fill = 0; \ + INIT_NONZERO_DICT_SLOTS(mp); \ } while(0) /* Dictionary reuse scheme to save calls to malloc, free, and memset */ @@ -229,68 +229,68 @@ void PyDict_Fini(void) { - PyDictObject *op; + PyDictObject *op; - while (numfree) { - op = free_list[--numfree]; - assert(PyDict_CheckExact(op)); - PyObject_GC_Del(op); - } + while (numfree) { + op = free_list[--numfree]; + assert(PyDict_CheckExact(op)); + PyObject_GC_Del(op); + } } PyObject * PyDict_New(void) { - register PyDictObject *mp; - if (dummy == NULL) { /* Auto-initialize dummy */ - dummy = PyUnicode_FromString(""); - if (dummy == NULL) - return NULL; + register PyDictObject *mp; + if (dummy == NULL) { /* Auto-initialize dummy */ + dummy = PyUnicode_FromString(""); + if (dummy == NULL) + return NULL; #ifdef SHOW_CONVERSION_COUNTS - Py_AtExit(show_counts); + Py_AtExit(show_counts); #endif #ifdef SHOW_ALLOC_COUNT - Py_AtExit(show_alloc); + Py_AtExit(show_alloc); #endif #ifdef SHOW_TRACK_COUNT - Py_AtExit(show_track); + Py_AtExit(show_track); #endif - } - if (numfree) { - mp = free_list[--numfree]; - assert (mp != NULL); - assert (Py_TYPE(mp) == &PyDict_Type); - _Py_NewReference((PyObject *)mp); - if (mp->ma_fill) { - EMPTY_TO_MINSIZE(mp); - } else { - /* At least set ma_table and ma_mask; these are wrong - if an empty but presized dict is added to freelist */ - INIT_NONZERO_DICT_SLOTS(mp); - } - assert (mp->ma_used == 0); - assert (mp->ma_table == mp->ma_smalltable); - assert (mp->ma_mask == PyDict_MINSIZE - 1); + } + if (numfree) { + mp = free_list[--numfree]; + assert (mp != NULL); + assert (Py_TYPE(mp) == &PyDict_Type); + _Py_NewReference((PyObject *)mp); + if (mp->ma_fill) { + EMPTY_TO_MINSIZE(mp); + } else { + /* At least set ma_table and ma_mask; these are wrong + if an empty but presized dict is added to freelist */ + INIT_NONZERO_DICT_SLOTS(mp); + } + assert (mp->ma_used == 0); + assert (mp->ma_table == mp->ma_smalltable); + assert (mp->ma_mask == PyDict_MINSIZE - 1); #ifdef SHOW_ALLOC_COUNT - count_reuse++; + count_reuse++; #endif - } else { - mp = PyObject_GC_New(PyDictObject, &PyDict_Type); - if (mp == NULL) - return NULL; - EMPTY_TO_MINSIZE(mp); + } else { + mp = PyObject_GC_New(PyDictObject, &PyDict_Type); + if (mp == NULL) + return NULL; + EMPTY_TO_MINSIZE(mp); #ifdef SHOW_ALLOC_COUNT - count_alloc++; + count_alloc++; #endif - } - mp->ma_lookup = lookdict_unicode; + } + mp->ma_lookup = lookdict_unicode; #ifdef SHOW_TRACK_COUNT - count_untracked++; + count_untracked++; #endif #ifdef SHOW_CONVERSION_COUNTS - ++created; + ++created; #endif - return (PyObject *)mp; + return (PyObject *)mp; } /* @@ -320,80 +320,80 @@ static PyDictEntry * lookdict(PyDictObject *mp, PyObject *key, register long hash) { - register size_t i; - register size_t perturb; - register PyDictEntry *freeslot; - register size_t mask = (size_t)mp->ma_mask; - PyDictEntry *ep0 = mp->ma_table; - register PyDictEntry *ep; - register int cmp; - PyObject *startkey; - - i = (size_t)hash & mask; - ep = &ep0[i]; - if (ep->me_key == NULL || ep->me_key == key) - return ep; - - if (ep->me_key == dummy) - freeslot = ep; - else { - if (ep->me_hash == hash) { - startkey = ep->me_key; - Py_INCREF(startkey); - cmp = PyObject_RichCompareBool(startkey, key, Py_EQ); - Py_DECREF(startkey); - if (cmp < 0) - return NULL; - if (ep0 == mp->ma_table && ep->me_key == startkey) { - if (cmp > 0) - return ep; - } - else { - /* The compare did major nasty stuff to the - * dict: start over. - * XXX A clever adversary could prevent this - * XXX from terminating. - */ - return lookdict(mp, key, hash); - } - } - freeslot = NULL; - } - - /* In the loop, me_key == dummy is by far (factor of 100s) the - least likely outcome, so test for that last. */ - for (perturb = hash; ; perturb >>= PERTURB_SHIFT) { - i = (i << 2) + i + perturb + 1; - ep = &ep0[i & mask]; - if (ep->me_key == NULL) - return freeslot == NULL ? ep : freeslot; - if (ep->me_key == key) - return ep; - if (ep->me_hash == hash && ep->me_key != dummy) { - startkey = ep->me_key; - Py_INCREF(startkey); - cmp = PyObject_RichCompareBool(startkey, key, Py_EQ); - Py_DECREF(startkey); - if (cmp < 0) - return NULL; - if (ep0 == mp->ma_table && ep->me_key == startkey) { - if (cmp > 0) - return ep; - } - else { - /* The compare did major nasty stuff to the - * dict: start over. - * XXX A clever adversary could prevent this - * XXX from terminating. - */ - return lookdict(mp, key, hash); - } - } - else if (ep->me_key == dummy && freeslot == NULL) - freeslot = ep; - } - assert(0); /* NOT REACHED */ - return 0; + register size_t i; + register size_t perturb; + register PyDictEntry *freeslot; + register size_t mask = (size_t)mp->ma_mask; + PyDictEntry *ep0 = mp->ma_table; + register PyDictEntry *ep; + register int cmp; + PyObject *startkey; + + i = (size_t)hash & mask; + ep = &ep0[i]; + if (ep->me_key == NULL || ep->me_key == key) + return ep; + + if (ep->me_key == dummy) + freeslot = ep; + else { + if (ep->me_hash == hash) { + startkey = ep->me_key; + Py_INCREF(startkey); + cmp = PyObject_RichCompareBool(startkey, key, Py_EQ); + Py_DECREF(startkey); + if (cmp < 0) + return NULL; + if (ep0 == mp->ma_table && ep->me_key == startkey) { + if (cmp > 0) + return ep; + } + else { + /* The compare did major nasty stuff to the + * dict: start over. + * XXX A clever adversary could prevent this + * XXX from terminating. + */ + return lookdict(mp, key, hash); + } + } + freeslot = NULL; + } + + /* In the loop, me_key == dummy is by far (factor of 100s) the + least likely outcome, so test for that last. */ + for (perturb = hash; ; perturb >>= PERTURB_SHIFT) { + i = (i << 2) + i + perturb + 1; + ep = &ep0[i & mask]; + if (ep->me_key == NULL) + return freeslot == NULL ? ep : freeslot; + if (ep->me_key == key) + return ep; + if (ep->me_hash == hash && ep->me_key != dummy) { + startkey = ep->me_key; + Py_INCREF(startkey); + cmp = PyObject_RichCompareBool(startkey, key, Py_EQ); + Py_DECREF(startkey); + if (cmp < 0) + return NULL; + if (ep0 == mp->ma_table && ep->me_key == startkey) { + if (cmp > 0) + return ep; + } + else { + /* The compare did major nasty stuff to the + * dict: start over. + * XXX A clever adversary could prevent this + * XXX from terminating. + */ + return lookdict(mp, key, hash); + } + } + else if (ep->me_key == dummy && freeslot == NULL) + freeslot = ep; + } + assert(0); /* NOT REACHED */ + return 0; } /* @@ -409,114 +409,114 @@ static PyDictEntry * lookdict_unicode(PyDictObject *mp, PyObject *key, register long hash) { - register size_t i; - register size_t perturb; - register PyDictEntry *freeslot; - register size_t mask = (size_t)mp->ma_mask; - PyDictEntry *ep0 = mp->ma_table; - register PyDictEntry *ep; - - /* Make sure this function doesn't have to handle non-unicode keys, - including subclasses of str; e.g., one reason to subclass - unicodes is to override __eq__, and for speed we don't cater to - that here. */ - if (!PyUnicode_CheckExact(key)) { + register size_t i; + register size_t perturb; + register PyDictEntry *freeslot; + register size_t mask = (size_t)mp->ma_mask; + PyDictEntry *ep0 = mp->ma_table; + register PyDictEntry *ep; + + /* Make sure this function doesn't have to handle non-unicode keys, + including subclasses of str; e.g., one reason to subclass + unicodes is to override __eq__, and for speed we don't cater to + that here. */ + if (!PyUnicode_CheckExact(key)) { #ifdef SHOW_CONVERSION_COUNTS - ++converted; + ++converted; #endif - mp->ma_lookup = lookdict; - return lookdict(mp, key, hash); - } - i = hash & mask; - ep = &ep0[i]; - if (ep->me_key == NULL || ep->me_key == key) - return ep; - if (ep->me_key == dummy) - freeslot = ep; - else { - if (ep->me_hash == hash && unicode_eq(ep->me_key, key)) - return ep; - freeslot = NULL; - } - - /* In the loop, me_key == dummy is by far (factor of 100s) the - least likely outcome, so test for that last. */ - for (perturb = hash; ; perturb >>= PERTURB_SHIFT) { - i = (i << 2) + i + perturb + 1; - ep = &ep0[i & mask]; - if (ep->me_key == NULL) - return freeslot == NULL ? ep : freeslot; - if (ep->me_key == key - || (ep->me_hash == hash - && ep->me_key != dummy - && unicode_eq(ep->me_key, key))) - return ep; - if (ep->me_key == dummy && freeslot == NULL) - freeslot = ep; - } - assert(0); /* NOT REACHED */ - return 0; + mp->ma_lookup = lookdict; + return lookdict(mp, key, hash); + } + i = hash & mask; + ep = &ep0[i]; + if (ep->me_key == NULL || ep->me_key == key) + return ep; + if (ep->me_key == dummy) + freeslot = ep; + else { + if (ep->me_hash == hash && unicode_eq(ep->me_key, key)) + return ep; + freeslot = NULL; + } + + /* In the loop, me_key == dummy is by far (factor of 100s) the + least likely outcome, so test for that last. */ + for (perturb = hash; ; perturb >>= PERTURB_SHIFT) { + i = (i << 2) + i + perturb + 1; + ep = &ep0[i & mask]; + if (ep->me_key == NULL) + return freeslot == NULL ? ep : freeslot; + if (ep->me_key == key + || (ep->me_hash == hash + && ep->me_key != dummy + && unicode_eq(ep->me_key, key))) + return ep; + if (ep->me_key == dummy && freeslot == NULL) + freeslot = ep; + } + assert(0); /* NOT REACHED */ + return 0; } int _PyDict_HasOnlyStringKeys(PyObject *dict) { - Py_ssize_t pos = 0; - PyObject *key, *value; - assert(PyDict_CheckExact(dict)); - /* Shortcut */ - if (((PyDictObject *)dict)->ma_lookup == lookdict_unicode) - return 1; - while (PyDict_Next(dict, &pos, &key, &value)) - if (!PyUnicode_Check(key)) - return 0; - return 1; + Py_ssize_t pos = 0; + PyObject *key, *value; + assert(PyDict_CheckExact(dict)); + /* Shortcut */ + if (((PyDictObject *)dict)->ma_lookup == lookdict_unicode) + return 1; + while (PyDict_Next(dict, &pos, &key, &value)) + if (!PyUnicode_Check(key)) + return 0; + return 1; } #ifdef SHOW_TRACK_COUNT #define INCREASE_TRACK_COUNT \ - (count_tracked++, count_untracked--); + (count_tracked++, count_untracked--); #define DECREASE_TRACK_COUNT \ - (count_tracked--, count_untracked++); + (count_tracked--, count_untracked++); #else #define INCREASE_TRACK_COUNT #define DECREASE_TRACK_COUNT #endif #define MAINTAIN_TRACKING(mp, key, value) \ - do { \ - if (!_PyObject_GC_IS_TRACKED(mp)) { \ - if (_PyObject_GC_MAY_BE_TRACKED(key) || \ - _PyObject_GC_MAY_BE_TRACKED(value)) { \ - _PyObject_GC_TRACK(mp); \ - INCREASE_TRACK_COUNT \ - } \ - } \ - } while(0) + do { \ + if (!_PyObject_GC_IS_TRACKED(mp)) { \ + if (_PyObject_GC_MAY_BE_TRACKED(key) || \ + _PyObject_GC_MAY_BE_TRACKED(value)) { \ + _PyObject_GC_TRACK(mp); \ + INCREASE_TRACK_COUNT \ + } \ + } \ + } while(0) void _PyDict_MaybeUntrack(PyObject *op) { - PyDictObject *mp; - PyObject *value; - Py_ssize_t mask, i; - PyDictEntry *ep; - - if (!PyDict_CheckExact(op) || !_PyObject_GC_IS_TRACKED(op)) - return; - - mp = (PyDictObject *) op; - ep = mp->ma_table; - mask = mp->ma_mask; - for (i = 0; i <= mask; i++) { - if ((value = ep[i].me_value) == NULL) - continue; - if (_PyObject_GC_MAY_BE_TRACKED(value) || - _PyObject_GC_MAY_BE_TRACKED(ep[i].me_key)) - return; - } - DECREASE_TRACK_COUNT - _PyObject_GC_UNTRACK(op); + PyDictObject *mp; + PyObject *value; + Py_ssize_t mask, i; + PyDictEntry *ep; + + if (!PyDict_CheckExact(op) || !_PyObject_GC_IS_TRACKED(op)) + return; + + mp = (PyDictObject *) op; + ep = mp->ma_table; + mask = mp->ma_mask; + for (i = 0; i <= mask; i++) { + if ((value = ep[i].me_value) == NULL) + continue; + if (_PyObject_GC_MAY_BE_TRACKED(value) || + _PyObject_GC_MAY_BE_TRACKED(ep[i].me_key)) + return; + } + DECREASE_TRACK_COUNT + _PyObject_GC_UNTRACK(op); } @@ -529,37 +529,37 @@ static int insertdict(register PyDictObject *mp, PyObject *key, long hash, PyObject *value) { - PyObject *old_value; - register PyDictEntry *ep; - typedef PyDictEntry *(*lookupfunc)(PyDictObject *, PyObject *, long); - - assert(mp->ma_lookup != NULL); - ep = mp->ma_lookup(mp, key, hash); - if (ep == NULL) { - Py_DECREF(key); - Py_DECREF(value); - return -1; - } - MAINTAIN_TRACKING(mp, key, value); - if (ep->me_value != NULL) { - old_value = ep->me_value; - ep->me_value = value; - Py_DECREF(old_value); /* which **CAN** re-enter */ - Py_DECREF(key); - } - else { - if (ep->me_key == NULL) - mp->ma_fill++; - else { - assert(ep->me_key == dummy); - Py_DECREF(dummy); - } - ep->me_key = key; - ep->me_hash = (Py_ssize_t)hash; - ep->me_value = value; - mp->ma_used++; - } - return 0; + PyObject *old_value; + register PyDictEntry *ep; + typedef PyDictEntry *(*lookupfunc)(PyDictObject *, PyObject *, long); + + assert(mp->ma_lookup != NULL); + ep = mp->ma_lookup(mp, key, hash); + if (ep == NULL) { + Py_DECREF(key); + Py_DECREF(value); + return -1; + } + MAINTAIN_TRACKING(mp, key, value); + if (ep->me_value != NULL) { + old_value = ep->me_value; + ep->me_value = value; + Py_DECREF(old_value); /* which **CAN** re-enter */ + Py_DECREF(key); + } + else { + if (ep->me_key == NULL) + mp->ma_fill++; + else { + assert(ep->me_key == dummy); + Py_DECREF(dummy); + } + ep->me_key = key; + ep->me_hash = (Py_ssize_t)hash; + ep->me_value = value; + mp->ma_used++; + } + return 0; } /* @@ -572,27 +572,27 @@ */ static void insertdict_clean(register PyDictObject *mp, PyObject *key, long hash, - PyObject *value) + PyObject *value) { - register size_t i; - register size_t perturb; - register size_t mask = (size_t)mp->ma_mask; - PyDictEntry *ep0 = mp->ma_table; - register PyDictEntry *ep; - - MAINTAIN_TRACKING(mp, key, value); - i = hash & mask; - ep = &ep0[i]; - for (perturb = hash; ep->me_key != NULL; perturb >>= PERTURB_SHIFT) { - i = (i << 2) + i + perturb + 1; - ep = &ep0[i & mask]; - } - assert(ep->me_value == NULL); - mp->ma_fill++; - ep->me_key = key; - ep->me_hash = (Py_ssize_t)hash; - ep->me_value = value; - mp->ma_used++; + register size_t i; + register size_t perturb; + register size_t mask = (size_t)mp->ma_mask; + PyDictEntry *ep0 = mp->ma_table; + register PyDictEntry *ep; + + MAINTAIN_TRACKING(mp, key, value); + i = hash & mask; + ep = &ep0[i]; + for (perturb = hash; ep->me_key != NULL; perturb >>= PERTURB_SHIFT) { + i = (i << 2) + i + perturb + 1; + ep = &ep0[i & mask]; + } + assert(ep->me_value == NULL); + mp->ma_fill++; + ep->me_key = key; + ep->me_hash = (Py_ssize_t)hash; + ep->me_value = value; + mp->ma_used++; } /* @@ -603,84 +603,84 @@ static int dictresize(PyDictObject *mp, Py_ssize_t minused) { - Py_ssize_t newsize; - PyDictEntry *oldtable, *newtable, *ep; - Py_ssize_t i; - int is_oldtable_malloced; - PyDictEntry small_copy[PyDict_MINSIZE]; - - assert(minused >= 0); - - /* Find the smallest table size > minused. */ - for (newsize = PyDict_MINSIZE; - newsize <= minused && newsize > 0; - newsize <<= 1) - ; - if (newsize <= 0) { - PyErr_NoMemory(); - return -1; - } - - /* Get space for a new table. */ - oldtable = mp->ma_table; - assert(oldtable != NULL); - is_oldtable_malloced = oldtable != mp->ma_smalltable; - - if (newsize == PyDict_MINSIZE) { - /* A large table is shrinking, or we can't get any smaller. */ - newtable = mp->ma_smalltable; - if (newtable == oldtable) { - if (mp->ma_fill == mp->ma_used) { - /* No dummies, so no point doing anything. */ - return 0; - } - /* We're not going to resize it, but rebuild the - table anyway to purge old dummy entries. - Subtle: This is *necessary* if fill==size, - as lookdict needs at least one virgin slot to - terminate failing searches. If fill < size, it's - merely desirable, as dummies slow searches. */ - assert(mp->ma_fill > mp->ma_used); - memcpy(small_copy, oldtable, sizeof(small_copy)); - oldtable = small_copy; - } - } - else { - newtable = PyMem_NEW(PyDictEntry, newsize); - if (newtable == NULL) { - PyErr_NoMemory(); - return -1; - } - } - - /* Make the dict empty, using the new table. */ - assert(newtable != oldtable); - mp->ma_table = newtable; - mp->ma_mask = newsize - 1; - memset(newtable, 0, sizeof(PyDictEntry) * newsize); - mp->ma_used = 0; - i = mp->ma_fill; - mp->ma_fill = 0; - - /* Copy the data over; this is refcount-neutral for active entries; - dummy entries aren't copied over, of course */ - for (ep = oldtable; i > 0; ep++) { - if (ep->me_value != NULL) { /* active entry */ - --i; - insertdict_clean(mp, ep->me_key, (long)ep->me_hash, - ep->me_value); - } - else if (ep->me_key != NULL) { /* dummy entry */ - --i; - assert(ep->me_key == dummy); - Py_DECREF(ep->me_key); - } - /* else key == value == NULL: nothing to do */ - } - - if (is_oldtable_malloced) - PyMem_DEL(oldtable); - return 0; + Py_ssize_t newsize; + PyDictEntry *oldtable, *newtable, *ep; + Py_ssize_t i; + int is_oldtable_malloced; + PyDictEntry small_copy[PyDict_MINSIZE]; + + assert(minused >= 0); + + /* Find the smallest table size > minused. */ + for (newsize = PyDict_MINSIZE; + newsize <= minused && newsize > 0; + newsize <<= 1) + ; + if (newsize <= 0) { + PyErr_NoMemory(); + return -1; + } + + /* Get space for a new table. */ + oldtable = mp->ma_table; + assert(oldtable != NULL); + is_oldtable_malloced = oldtable != mp->ma_smalltable; + + if (newsize == PyDict_MINSIZE) { + /* A large table is shrinking, or we can't get any smaller. */ + newtable = mp->ma_smalltable; + if (newtable == oldtable) { + if (mp->ma_fill == mp->ma_used) { + /* No dummies, so no point doing anything. */ + return 0; + } + /* We're not going to resize it, but rebuild the + table anyway to purge old dummy entries. + Subtle: This is *necessary* if fill==size, + as lookdict needs at least one virgin slot to + terminate failing searches. If fill < size, it's + merely desirable, as dummies slow searches. */ + assert(mp->ma_fill > mp->ma_used); + memcpy(small_copy, oldtable, sizeof(small_copy)); + oldtable = small_copy; + } + } + else { + newtable = PyMem_NEW(PyDictEntry, newsize); + if (newtable == NULL) { + PyErr_NoMemory(); + return -1; + } + } + + /* Make the dict empty, using the new table. */ + assert(newtable != oldtable); + mp->ma_table = newtable; + mp->ma_mask = newsize - 1; + memset(newtable, 0, sizeof(PyDictEntry) * newsize); + mp->ma_used = 0; + i = mp->ma_fill; + mp->ma_fill = 0; + + /* Copy the data over; this is refcount-neutral for active entries; + dummy entries aren't copied over, of course */ + for (ep = oldtable; i > 0; ep++) { + if (ep->me_value != NULL) { /* active entry */ + --i; + insertdict_clean(mp, ep->me_key, (long)ep->me_hash, + ep->me_value); + } + else if (ep->me_key != NULL) { /* dummy entry */ + --i; + assert(ep->me_key == dummy); + Py_DECREF(ep->me_key); + } + /* else key == value == NULL: nothing to do */ + } + + if (is_oldtable_malloced) + PyMem_DEL(oldtable); + return 0; } /* Create a new dictionary pre-sized to hold an estimated number of elements. @@ -691,13 +691,13 @@ PyObject * _PyDict_NewPresized(Py_ssize_t minused) { - PyObject *op = PyDict_New(); + PyObject *op = PyDict_New(); - if (minused>5 && op != NULL && dictresize((PyDictObject *)op, minused) == -1) { - Py_DECREF(op); - return NULL; - } - return op; + if (minused>5 && op != NULL && dictresize((PyDictObject *)op, minused) == -1) { + Py_DECREF(op); + return NULL; + } + return op; } /* Note that, for historical reasons, PyDict_GetItem() suppresses all errors @@ -713,47 +713,47 @@ PyObject * PyDict_GetItem(PyObject *op, PyObject *key) { - long hash; - PyDictObject *mp = (PyDictObject *)op; - PyDictEntry *ep; - PyThreadState *tstate; - if (!PyDict_Check(op)) - return NULL; - if (!PyUnicode_CheckExact(key) || - (hash = ((PyUnicodeObject *) key)->hash) == -1) - { - hash = PyObject_Hash(key); - if (hash == -1) { - PyErr_Clear(); - return NULL; - } - } - - /* We can arrive here with a NULL tstate during initialization: try - running "python -Wi" for an example related to string interning. - Let's just hope that no exception occurs then... This must be - _PyThreadState_Current and not PyThreadState_GET() because in debug - mode, the latter complains if tstate is NULL. */ - tstate = (PyThreadState*)_Py_atomic_load_relaxed( - &_PyThreadState_Current); - if (tstate != NULL && tstate->curexc_type != NULL) { - /* preserve the existing exception */ - PyObject *err_type, *err_value, *err_tb; - PyErr_Fetch(&err_type, &err_value, &err_tb); - ep = (mp->ma_lookup)(mp, key, hash); - /* ignore errors */ - PyErr_Restore(err_type, err_value, err_tb); - if (ep == NULL) - return NULL; - } - else { - ep = (mp->ma_lookup)(mp, key, hash); - if (ep == NULL) { - PyErr_Clear(); - return NULL; - } - } - return ep->me_value; + long hash; + PyDictObject *mp = (PyDictObject *)op; + PyDictEntry *ep; + PyThreadState *tstate; + if (!PyDict_Check(op)) + return NULL; + if (!PyUnicode_CheckExact(key) || + (hash = ((PyUnicodeObject *) key)->hash) == -1) + { + hash = PyObject_Hash(key); + if (hash == -1) { + PyErr_Clear(); + return NULL; + } + } + + /* We can arrive here with a NULL tstate during initialization: try + running "python -Wi" for an example related to string interning. + Let's just hope that no exception occurs then... This must be + _PyThreadState_Current and not PyThreadState_GET() because in debug + mode, the latter complains if tstate is NULL. */ + tstate = (PyThreadState*)_Py_atomic_load_relaxed( + &_PyThreadState_Current); + if (tstate != NULL && tstate->curexc_type != NULL) { + /* preserve the existing exception */ + PyObject *err_type, *err_value, *err_tb; + PyErr_Fetch(&err_type, &err_value, &err_tb); + ep = (mp->ma_lookup)(mp, key, hash); + /* ignore errors */ + PyErr_Restore(err_type, err_value, err_tb); + if (ep == NULL) + return NULL; + } + else { + ep = (mp->ma_lookup)(mp, key, hash); + if (ep == NULL) { + PyErr_Clear(); + return NULL; + } + } + return ep->me_value; } /* Variant of PyDict_GetItem() that doesn't suppress exceptions. @@ -763,27 +763,27 @@ PyObject * PyDict_GetItemWithError(PyObject *op, PyObject *key) { - long hash; - PyDictObject*mp = (PyDictObject *)op; - PyDictEntry *ep; - - if (!PyDict_Check(op)) { - PyErr_BadInternalCall(); - return NULL; - } - if (!PyUnicode_CheckExact(key) || - (hash = ((PyUnicodeObject *) key)->hash) == -1) - { - hash = PyObject_Hash(key); - if (hash == -1) { - return NULL; - } - } - - ep = (mp->ma_lookup)(mp, key, hash); - if (ep == NULL) - return NULL; - return ep->me_value; + long hash; + PyDictObject*mp = (PyDictObject *)op; + PyDictEntry *ep; + + if (!PyDict_Check(op)) { + PyErr_BadInternalCall(); + return NULL; + } + if (!PyUnicode_CheckExact(key) || + (hash = ((PyUnicodeObject *) key)->hash) == -1) + { + hash = PyObject_Hash(key); + if (hash == -1) { + return NULL; + } + } + + ep = (mp->ma_lookup)(mp, key, hash); + if (ep == NULL) + return NULL; + return ep->me_value; } /* CAUTION: PyDict_SetItem() must guarantee that it won't resize the @@ -795,154 +795,154 @@ int PyDict_SetItem(register PyObject *op, PyObject *key, PyObject *value) { - register PyDictObject *mp; - register long hash; - register Py_ssize_t n_used; - - if (!PyDict_Check(op)) { - PyErr_BadInternalCall(); - return -1; - } - assert(key); - assert(value); - mp = (PyDictObject *)op; - if (!PyUnicode_CheckExact(key) || - (hash = ((PyUnicodeObject *) key)->hash) == -1) - { - hash = PyObject_Hash(key); - if (hash == -1) - return -1; - } - assert(mp->ma_fill <= mp->ma_mask); /* at least one empty slot */ - n_used = mp->ma_used; - Py_INCREF(value); - Py_INCREF(key); - if (insertdict(mp, key, hash, value) != 0) - return -1; - /* If we added a key, we can safely resize. Otherwise just return! - * If fill >= 2/3 size, adjust size. Normally, this doubles or - * quaduples the size, but it's also possible for the dict to shrink - * (if ma_fill is much larger than ma_used, meaning a lot of dict - * keys have been * deleted). - * - * Quadrupling the size improves average dictionary sparseness - * (reducing collisions) at the cost of some memory and iteration - * speed (which loops over every possible entry). It also halves - * the number of expensive resize operations in a growing dictionary. - * - * Very large dictionaries (over 50K items) use doubling instead. - * This may help applications with severe memory constraints. - */ - if (!(mp->ma_used > n_used && mp->ma_fill*3 >= (mp->ma_mask+1)*2)) - return 0; - return dictresize(mp, (mp->ma_used > 50000 ? 2 : 4) * mp->ma_used); + register PyDictObject *mp; + register long hash; + register Py_ssize_t n_used; + + if (!PyDict_Check(op)) { + PyErr_BadInternalCall(); + return -1; + } + assert(key); + assert(value); + mp = (PyDictObject *)op; + if (!PyUnicode_CheckExact(key) || + (hash = ((PyUnicodeObject *) key)->hash) == -1) + { + hash = PyObject_Hash(key); + if (hash == -1) + return -1; + } + assert(mp->ma_fill <= mp->ma_mask); /* at least one empty slot */ + n_used = mp->ma_used; + Py_INCREF(value); + Py_INCREF(key); + if (insertdict(mp, key, hash, value) != 0) + return -1; + /* If we added a key, we can safely resize. Otherwise just return! + * If fill >= 2/3 size, adjust size. Normally, this doubles or + * quaduples the size, but it's also possible for the dict to shrink + * (if ma_fill is much larger than ma_used, meaning a lot of dict + * keys have been * deleted). + * + * Quadrupling the size improves average dictionary sparseness + * (reducing collisions) at the cost of some memory and iteration + * speed (which loops over every possible entry). It also halves + * the number of expensive resize operations in a growing dictionary. + * + * Very large dictionaries (over 50K items) use doubling instead. + * This may help applications with severe memory constraints. + */ + if (!(mp->ma_used > n_used && mp->ma_fill*3 >= (mp->ma_mask+1)*2)) + return 0; + return dictresize(mp, (mp->ma_used > 50000 ? 2 : 4) * mp->ma_used); } int PyDict_DelItem(PyObject *op, PyObject *key) { - register PyDictObject *mp; - register long hash; - register PyDictEntry *ep; - PyObject *old_value, *old_key; - - if (!PyDict_Check(op)) { - PyErr_BadInternalCall(); - return -1; - } - assert(key); - if (!PyUnicode_CheckExact(key) || - (hash = ((PyUnicodeObject *) key)->hash) == -1) { - hash = PyObject_Hash(key); - if (hash == -1) - return -1; - } - mp = (PyDictObject *)op; - ep = (mp->ma_lookup)(mp, key, hash); - if (ep == NULL) - return -1; - if (ep->me_value == NULL) { - set_key_error(key); - return -1; - } - old_key = ep->me_key; - Py_INCREF(dummy); - ep->me_key = dummy; - old_value = ep->me_value; - ep->me_value = NULL; - mp->ma_used--; - Py_DECREF(old_value); - Py_DECREF(old_key); - return 0; + register PyDictObject *mp; + register long hash; + register PyDictEntry *ep; + PyObject *old_value, *old_key; + + if (!PyDict_Check(op)) { + PyErr_BadInternalCall(); + return -1; + } + assert(key); + if (!PyUnicode_CheckExact(key) || + (hash = ((PyUnicodeObject *) key)->hash) == -1) { + hash = PyObject_Hash(key); + if (hash == -1) + return -1; + } + mp = (PyDictObject *)op; + ep = (mp->ma_lookup)(mp, key, hash); + if (ep == NULL) + return -1; + if (ep->me_value == NULL) { + set_key_error(key); + return -1; + } + old_key = ep->me_key; + Py_INCREF(dummy); + ep->me_key = dummy; + old_value = ep->me_value; + ep->me_value = NULL; + mp->ma_used--; + Py_DECREF(old_value); + Py_DECREF(old_key); + return 0; } void PyDict_Clear(PyObject *op) { - PyDictObject *mp; - PyDictEntry *ep, *table; - int table_is_malloced; - Py_ssize_t fill; - PyDictEntry small_copy[PyDict_MINSIZE]; + PyDictObject *mp; + PyDictEntry *ep, *table; + int table_is_malloced; + Py_ssize_t fill; + PyDictEntry small_copy[PyDict_MINSIZE]; #ifdef Py_DEBUG - Py_ssize_t i, n; + Py_ssize_t i, n; #endif - if (!PyDict_Check(op)) - return; - mp = (PyDictObject *)op; + if (!PyDict_Check(op)) + return; + mp = (PyDictObject *)op; #ifdef Py_DEBUG - n = mp->ma_mask + 1; - i = 0; + n = mp->ma_mask + 1; + i = 0; #endif - table = mp->ma_table; - assert(table != NULL); - table_is_malloced = table != mp->ma_smalltable; - - /* This is delicate. During the process of clearing the dict, - * decrefs can cause the dict to mutate. To avoid fatal confusion - * (voice of experience), we have to make the dict empty before - * clearing the slots, and never refer to anything via mp->xxx while - * clearing. - */ - fill = mp->ma_fill; - if (table_is_malloced) - EMPTY_TO_MINSIZE(mp); - - else if (fill > 0) { - /* It's a small table with something that needs to be cleared. - * Afraid the only safe way is to copy the dict entries into - * another small table first. - */ - memcpy(small_copy, table, sizeof(small_copy)); - table = small_copy; - EMPTY_TO_MINSIZE(mp); - } - /* else it's a small table that's already empty */ - - /* Now we can finally clear things. If C had refcounts, we could - * assert that the refcount on table is 1 now, i.e. that this function - * has unique access to it, so decref side-effects can't alter it. - */ - for (ep = table; fill > 0; ++ep) { + table = mp->ma_table; + assert(table != NULL); + table_is_malloced = table != mp->ma_smalltable; + + /* This is delicate. During the process of clearing the dict, + * decrefs can cause the dict to mutate. To avoid fatal confusion + * (voice of experience), we have to make the dict empty before + * clearing the slots, and never refer to anything via mp->xxx while + * clearing. + */ + fill = mp->ma_fill; + if (table_is_malloced) + EMPTY_TO_MINSIZE(mp); + + else if (fill > 0) { + /* It's a small table with something that needs to be cleared. + * Afraid the only safe way is to copy the dict entries into + * another small table first. + */ + memcpy(small_copy, table, sizeof(small_copy)); + table = small_copy; + EMPTY_TO_MINSIZE(mp); + } + /* else it's a small table that's already empty */ + + /* Now we can finally clear things. If C had refcounts, we could + * assert that the refcount on table is 1 now, i.e. that this function + * has unique access to it, so decref side-effects can't alter it. + */ + for (ep = table; fill > 0; ++ep) { #ifdef Py_DEBUG - assert(i < n); - ++i; + assert(i < n); + ++i; #endif - if (ep->me_key) { - --fill; - Py_DECREF(ep->me_key); - Py_XDECREF(ep->me_value); - } + if (ep->me_key) { + --fill; + Py_DECREF(ep->me_key); + Py_XDECREF(ep->me_value); + } #ifdef Py_DEBUG - else - assert(ep->me_value == NULL); + else + assert(ep->me_value == NULL); #endif - } + } - if (table_is_malloced) - PyMem_DEL(table); + if (table_is_malloced) + PyMem_DEL(table); } /* @@ -963,55 +963,55 @@ int PyDict_Next(PyObject *op, Py_ssize_t *ppos, PyObject **pkey, PyObject **pvalue) { - register Py_ssize_t i; - register Py_ssize_t mask; - register PyDictEntry *ep; - - if (!PyDict_Check(op)) - return 0; - i = *ppos; - if (i < 0) - return 0; - ep = ((PyDictObject *)op)->ma_table; - mask = ((PyDictObject *)op)->ma_mask; - while (i <= mask && ep[i].me_value == NULL) - i++; - *ppos = i+1; - if (i > mask) - return 0; - if (pkey) - *pkey = ep[i].me_key; - if (pvalue) - *pvalue = ep[i].me_value; - return 1; + register Py_ssize_t i; + register Py_ssize_t mask; + register PyDictEntry *ep; + + if (!PyDict_Check(op)) + return 0; + i = *ppos; + if (i < 0) + return 0; + ep = ((PyDictObject *)op)->ma_table; + mask = ((PyDictObject *)op)->ma_mask; + while (i <= mask && ep[i].me_value == NULL) + i++; + *ppos = i+1; + if (i > mask) + return 0; + if (pkey) + *pkey = ep[i].me_key; + if (pvalue) + *pvalue = ep[i].me_value; + return 1; } /* Internal version of PyDict_Next that returns a hash value in addition to the key and value.*/ int _PyDict_Next(PyObject *op, Py_ssize_t *ppos, PyObject **pkey, PyObject **pvalue, long *phash) { - register Py_ssize_t i; - register Py_ssize_t mask; - register PyDictEntry *ep; - - if (!PyDict_Check(op)) - return 0; - i = *ppos; - if (i < 0) - return 0; - ep = ((PyDictObject *)op)->ma_table; - mask = ((PyDictObject *)op)->ma_mask; - while (i <= mask && ep[i].me_value == NULL) - i++; - *ppos = i+1; - if (i > mask) - return 0; - *phash = (long)(ep[i].me_hash); - if (pkey) - *pkey = ep[i].me_key; - if (pvalue) - *pvalue = ep[i].me_value; - return 1; + register Py_ssize_t i; + register Py_ssize_t mask; + register PyDictEntry *ep; + + if (!PyDict_Check(op)) + return 0; + i = *ppos; + if (i < 0) + return 0; + ep = ((PyDictObject *)op)->ma_table; + mask = ((PyDictObject *)op)->ma_mask; + while (i <= mask && ep[i].me_value == NULL) + i++; + *ppos = i+1; + if (i > mask) + return 0; + *phash = (long)(ep[i].me_hash); + if (pkey) + *pkey = ep[i].me_key; + if (pvalue) + *pvalue = ep[i].me_value; + return 1; } /* Methods */ @@ -1019,404 +1019,404 @@ static void dict_dealloc(register PyDictObject *mp) { - register PyDictEntry *ep; - Py_ssize_t fill = mp->ma_fill; - PyObject_GC_UnTrack(mp); - Py_TRASHCAN_SAFE_BEGIN(mp) - for (ep = mp->ma_table; fill > 0; ep++) { - if (ep->me_key) { - --fill; - Py_DECREF(ep->me_key); - Py_XDECREF(ep->me_value); - } - } - if (mp->ma_table != mp->ma_smalltable) - PyMem_DEL(mp->ma_table); - if (numfree < PyDict_MAXFREELIST && Py_TYPE(mp) == &PyDict_Type) - free_list[numfree++] = mp; - else - Py_TYPE(mp)->tp_free((PyObject *)mp); - Py_TRASHCAN_SAFE_END(mp) + register PyDictEntry *ep; + Py_ssize_t fill = mp->ma_fill; + PyObject_GC_UnTrack(mp); + Py_TRASHCAN_SAFE_BEGIN(mp) + for (ep = mp->ma_table; fill > 0; ep++) { + if (ep->me_key) { + --fill; + Py_DECREF(ep->me_key); + Py_XDECREF(ep->me_value); + } + } + if (mp->ma_table != mp->ma_smalltable) + PyMem_DEL(mp->ma_table); + if (numfree < PyDict_MAXFREELIST && Py_TYPE(mp) == &PyDict_Type) + free_list[numfree++] = mp; + else + Py_TYPE(mp)->tp_free((PyObject *)mp); + Py_TRASHCAN_SAFE_END(mp) } static PyObject * dict_repr(PyDictObject *mp) { - Py_ssize_t i; - PyObject *s, *temp, *colon = NULL; - PyObject *pieces = NULL, *result = NULL; - PyObject *key, *value; - - i = Py_ReprEnter((PyObject *)mp); - if (i != 0) { - return i > 0 ? PyUnicode_FromString("{...}") : NULL; - } - - if (mp->ma_used == 0) { - result = PyUnicode_FromString("{}"); - goto Done; - } - - pieces = PyList_New(0); - if (pieces == NULL) - goto Done; - - colon = PyUnicode_FromString(": "); - if (colon == NULL) - goto Done; - - /* Do repr() on each key+value pair, and insert ": " between them. - Note that repr may mutate the dict. */ - i = 0; - while (PyDict_Next((PyObject *)mp, &i, &key, &value)) { - int status; - /* Prevent repr from deleting value during key format. */ - Py_INCREF(value); - s = PyObject_Repr(key); - PyUnicode_Append(&s, colon); - PyUnicode_AppendAndDel(&s, PyObject_Repr(value)); - Py_DECREF(value); - if (s == NULL) - goto Done; - status = PyList_Append(pieces, s); - Py_DECREF(s); /* append created a new ref */ - if (status < 0) - goto Done; - } - - /* Add "{}" decorations to the first and last items. */ - assert(PyList_GET_SIZE(pieces) > 0); - s = PyUnicode_FromString("{"); - if (s == NULL) - goto Done; - temp = PyList_GET_ITEM(pieces, 0); - PyUnicode_AppendAndDel(&s, temp); - PyList_SET_ITEM(pieces, 0, s); - if (s == NULL) - goto Done; - - s = PyUnicode_FromString("}"); - if (s == NULL) - goto Done; - temp = PyList_GET_ITEM(pieces, PyList_GET_SIZE(pieces) - 1); - PyUnicode_AppendAndDel(&temp, s); - PyList_SET_ITEM(pieces, PyList_GET_SIZE(pieces) - 1, temp); - if (temp == NULL) - goto Done; - - /* Paste them all together with ", " between. */ - s = PyUnicode_FromString(", "); - if (s == NULL) - goto Done; - result = PyUnicode_Join(s, pieces); - Py_DECREF(s); + Py_ssize_t i; + PyObject *s, *temp, *colon = NULL; + PyObject *pieces = NULL, *result = NULL; + PyObject *key, *value; + + i = Py_ReprEnter((PyObject *)mp); + if (i != 0) { + return i > 0 ? PyUnicode_FromString("{...}") : NULL; + } + + if (mp->ma_used == 0) { + result = PyUnicode_FromString("{}"); + goto Done; + } + + pieces = PyList_New(0); + if (pieces == NULL) + goto Done; + + colon = PyUnicode_FromString(": "); + if (colon == NULL) + goto Done; + + /* Do repr() on each key+value pair, and insert ": " between them. + Note that repr may mutate the dict. */ + i = 0; + while (PyDict_Next((PyObject *)mp, &i, &key, &value)) { + int status; + /* Prevent repr from deleting value during key format. */ + Py_INCREF(value); + s = PyObject_Repr(key); + PyUnicode_Append(&s, colon); + PyUnicode_AppendAndDel(&s, PyObject_Repr(value)); + Py_DECREF(value); + if (s == NULL) + goto Done; + status = PyList_Append(pieces, s); + Py_DECREF(s); /* append created a new ref */ + if (status < 0) + goto Done; + } + + /* Add "{}" decorations to the first and last items. */ + assert(PyList_GET_SIZE(pieces) > 0); + s = PyUnicode_FromString("{"); + if (s == NULL) + goto Done; + temp = PyList_GET_ITEM(pieces, 0); + PyUnicode_AppendAndDel(&s, temp); + PyList_SET_ITEM(pieces, 0, s); + if (s == NULL) + goto Done; + + s = PyUnicode_FromString("}"); + if (s == NULL) + goto Done; + temp = PyList_GET_ITEM(pieces, PyList_GET_SIZE(pieces) - 1); + PyUnicode_AppendAndDel(&temp, s); + PyList_SET_ITEM(pieces, PyList_GET_SIZE(pieces) - 1, temp); + if (temp == NULL) + goto Done; + + /* Paste them all together with ", " between. */ + s = PyUnicode_FromString(", "); + if (s == NULL) + goto Done; + result = PyUnicode_Join(s, pieces); + Py_DECREF(s); Done: - Py_XDECREF(pieces); - Py_XDECREF(colon); - Py_ReprLeave((PyObject *)mp); - return result; + Py_XDECREF(pieces); + Py_XDECREF(colon); + Py_ReprLeave((PyObject *)mp); + return result; } static Py_ssize_t dict_length(PyDictObject *mp) { - return mp->ma_used; + return mp->ma_used; } static PyObject * dict_subscript(PyDictObject *mp, register PyObject *key) { - PyObject *v; - long hash; - PyDictEntry *ep; - assert(mp->ma_table != NULL); - if (!PyUnicode_CheckExact(key) || - (hash = ((PyUnicodeObject *) key)->hash) == -1) { - hash = PyObject_Hash(key); - if (hash == -1) - return NULL; - } - ep = (mp->ma_lookup)(mp, key, hash); - if (ep == NULL) - return NULL; - v = ep->me_value; - if (v == NULL) { - if (!PyDict_CheckExact(mp)) { - /* Look up __missing__ method if we're a subclass. */ - PyObject *missing, *res; - static PyObject *missing_str = NULL; - missing = _PyObject_LookupSpecial((PyObject *)mp, - "__missing__", - &missing_str); - if (missing != NULL) { - res = PyObject_CallFunctionObjArgs(missing, - key, NULL); - Py_DECREF(missing); - return res; - } - else if (PyErr_Occurred()) - return NULL; - } - set_key_error(key); - return NULL; - } - else - Py_INCREF(v); - return v; + PyObject *v; + long hash; + PyDictEntry *ep; + assert(mp->ma_table != NULL); + if (!PyUnicode_CheckExact(key) || + (hash = ((PyUnicodeObject *) key)->hash) == -1) { + hash = PyObject_Hash(key); + if (hash == -1) + return NULL; + } + ep = (mp->ma_lookup)(mp, key, hash); + if (ep == NULL) + return NULL; + v = ep->me_value; + if (v == NULL) { + if (!PyDict_CheckExact(mp)) { + /* Look up __missing__ method if we're a subclass. */ + PyObject *missing, *res; + static PyObject *missing_str = NULL; + missing = _PyObject_LookupSpecial((PyObject *)mp, + "__missing__", + &missing_str); + if (missing != NULL) { + res = PyObject_CallFunctionObjArgs(missing, + key, NULL); + Py_DECREF(missing); + return res; + } + else if (PyErr_Occurred()) + return NULL; + } + set_key_error(key); + return NULL; + } + else + Py_INCREF(v); + return v; } static int dict_ass_sub(PyDictObject *mp, PyObject *v, PyObject *w) { - if (w == NULL) - return PyDict_DelItem((PyObject *)mp, v); - else - return PyDict_SetItem((PyObject *)mp, v, w); + if (w == NULL) + return PyDict_DelItem((PyObject *)mp, v); + else + return PyDict_SetItem((PyObject *)mp, v, w); } static PyMappingMethods dict_as_mapping = { - (lenfunc)dict_length, /*mp_length*/ - (binaryfunc)dict_subscript, /*mp_subscript*/ - (objobjargproc)dict_ass_sub, /*mp_ass_subscript*/ + (lenfunc)dict_length, /*mp_length*/ + (binaryfunc)dict_subscript, /*mp_subscript*/ + (objobjargproc)dict_ass_sub, /*mp_ass_subscript*/ }; static PyObject * dict_keys(register PyDictObject *mp) { - register PyObject *v; - register Py_ssize_t i, j; - PyDictEntry *ep; - Py_ssize_t mask, n; + register PyObject *v; + register Py_ssize_t i, j; + PyDictEntry *ep; + Py_ssize_t mask, n; again: - n = mp->ma_used; - v = PyList_New(n); - if (v == NULL) - return NULL; - if (n != mp->ma_used) { - /* Durnit. The allocations caused the dict to resize. - * Just start over, this shouldn't normally happen. - */ - Py_DECREF(v); - goto again; - } - ep = mp->ma_table; - mask = mp->ma_mask; - for (i = 0, j = 0; i <= mask; i++) { - if (ep[i].me_value != NULL) { - PyObject *key = ep[i].me_key; - Py_INCREF(key); - PyList_SET_ITEM(v, j, key); - j++; - } - } - assert(j == n); - return v; + n = mp->ma_used; + v = PyList_New(n); + if (v == NULL) + return NULL; + if (n != mp->ma_used) { + /* Durnit. The allocations caused the dict to resize. + * Just start over, this shouldn't normally happen. + */ + Py_DECREF(v); + goto again; + } + ep = mp->ma_table; + mask = mp->ma_mask; + for (i = 0, j = 0; i <= mask; i++) { + if (ep[i].me_value != NULL) { + PyObject *key = ep[i].me_key; + Py_INCREF(key); + PyList_SET_ITEM(v, j, key); + j++; + } + } + assert(j == n); + return v; } static PyObject * dict_values(register PyDictObject *mp) { - register PyObject *v; - register Py_ssize_t i, j; - PyDictEntry *ep; - Py_ssize_t mask, n; + register PyObject *v; + register Py_ssize_t i, j; + PyDictEntry *ep; + Py_ssize_t mask, n; again: - n = mp->ma_used; - v = PyList_New(n); - if (v == NULL) - return NULL; - if (n != mp->ma_used) { - /* Durnit. The allocations caused the dict to resize. - * Just start over, this shouldn't normally happen. - */ - Py_DECREF(v); - goto again; - } - ep = mp->ma_table; - mask = mp->ma_mask; - for (i = 0, j = 0; i <= mask; i++) { - if (ep[i].me_value != NULL) { - PyObject *value = ep[i].me_value; - Py_INCREF(value); - PyList_SET_ITEM(v, j, value); - j++; - } - } - assert(j == n); - return v; + n = mp->ma_used; + v = PyList_New(n); + if (v == NULL) + return NULL; + if (n != mp->ma_used) { + /* Durnit. The allocations caused the dict to resize. + * Just start over, this shouldn't normally happen. + */ + Py_DECREF(v); + goto again; + } + ep = mp->ma_table; + mask = mp->ma_mask; + for (i = 0, j = 0; i <= mask; i++) { + if (ep[i].me_value != NULL) { + PyObject *value = ep[i].me_value; + Py_INCREF(value); + PyList_SET_ITEM(v, j, value); + j++; + } + } + assert(j == n); + return v; } static PyObject * dict_items(register PyDictObject *mp) { - register PyObject *v; - register Py_ssize_t i, j, n; - Py_ssize_t mask; - PyObject *item, *key, *value; - PyDictEntry *ep; - - /* Preallocate the list of tuples, to avoid allocations during - * the loop over the items, which could trigger GC, which - * could resize the dict. :-( - */ + register PyObject *v; + register Py_ssize_t i, j, n; + Py_ssize_t mask; + PyObject *item, *key, *value; + PyDictEntry *ep; + + /* Preallocate the list of tuples, to avoid allocations during + * the loop over the items, which could trigger GC, which + * could resize the dict. :-( + */ again: - n = mp->ma_used; - v = PyList_New(n); - if (v == NULL) - return NULL; - for (i = 0; i < n; i++) { - item = PyTuple_New(2); - if (item == NULL) { - Py_DECREF(v); - return NULL; - } - PyList_SET_ITEM(v, i, item); - } - if (n != mp->ma_used) { - /* Durnit. The allocations caused the dict to resize. - * Just start over, this shouldn't normally happen. - */ - Py_DECREF(v); - goto again; - } - /* Nothing we do below makes any function calls. */ - ep = mp->ma_table; - mask = mp->ma_mask; - for (i = 0, j = 0; i <= mask; i++) { - if ((value=ep[i].me_value) != NULL) { - key = ep[i].me_key; - item = PyList_GET_ITEM(v, j); - Py_INCREF(key); - PyTuple_SET_ITEM(item, 0, key); - Py_INCREF(value); - PyTuple_SET_ITEM(item, 1, value); - j++; - } - } - assert(j == n); - return v; + n = mp->ma_used; + v = PyList_New(n); + if (v == NULL) + return NULL; + for (i = 0; i < n; i++) { + item = PyTuple_New(2); + if (item == NULL) { + Py_DECREF(v); + return NULL; + } + PyList_SET_ITEM(v, i, item); + } + if (n != mp->ma_used) { + /* Durnit. The allocations caused the dict to resize. + * Just start over, this shouldn't normally happen. + */ + Py_DECREF(v); + goto again; + } + /* Nothing we do below makes any function calls. */ + ep = mp->ma_table; + mask = mp->ma_mask; + for (i = 0, j = 0; i <= mask; i++) { + if ((value=ep[i].me_value) != NULL) { + key = ep[i].me_key; + item = PyList_GET_ITEM(v, j); + Py_INCREF(key); + PyTuple_SET_ITEM(item, 0, key); + Py_INCREF(value); + PyTuple_SET_ITEM(item, 1, value); + j++; + } + } + assert(j == n); + return v; } static PyObject * dict_fromkeys(PyObject *cls, PyObject *args) { - PyObject *seq; - PyObject *value = Py_None; - PyObject *it; /* iter(seq) */ - PyObject *key; - PyObject *d; - int status; - - if (!PyArg_UnpackTuple(args, "fromkeys", 1, 2, &seq, &value)) - return NULL; - - d = PyObject_CallObject(cls, NULL); - if (d == NULL) - return NULL; - - if (PyDict_CheckExact(d) && PyDict_CheckExact(seq)) { - PyDictObject *mp = (PyDictObject *)d; - PyObject *oldvalue; - Py_ssize_t pos = 0; - PyObject *key; - long hash; - - if (dictresize(mp, Py_SIZE(seq))) - return NULL; - - while (_PyDict_Next(seq, &pos, &key, &oldvalue, &hash)) { - Py_INCREF(key); - Py_INCREF(value); - if (insertdict(mp, key, hash, value)) - return NULL; - } - return d; - } - - if (PyDict_CheckExact(d) && PyAnySet_CheckExact(seq)) { - PyDictObject *mp = (PyDictObject *)d; - Py_ssize_t pos = 0; - PyObject *key; - long hash; - - if (dictresize(mp, PySet_GET_SIZE(seq))) - return NULL; - - while (_PySet_NextEntry(seq, &pos, &key, &hash)) { - Py_INCREF(key); - Py_INCREF(value); - if (insertdict(mp, key, hash, value)) - return NULL; - } - return d; - } - - it = PyObject_GetIter(seq); - if (it == NULL){ - Py_DECREF(d); - return NULL; - } - - if (PyDict_CheckExact(d)) { - while ((key = PyIter_Next(it)) != NULL) { - status = PyDict_SetItem(d, key, value); - Py_DECREF(key); - if (status < 0) - goto Fail; - } - } else { - while ((key = PyIter_Next(it)) != NULL) { - status = PyObject_SetItem(d, key, value); - Py_DECREF(key); - if (status < 0) - goto Fail; - } - } - - if (PyErr_Occurred()) - goto Fail; - Py_DECREF(it); - return d; + PyObject *seq; + PyObject *value = Py_None; + PyObject *it; /* iter(seq) */ + PyObject *key; + PyObject *d; + int status; + + if (!PyArg_UnpackTuple(args, "fromkeys", 1, 2, &seq, &value)) + return NULL; + + d = PyObject_CallObject(cls, NULL); + if (d == NULL) + return NULL; + + if (PyDict_CheckExact(d) && PyDict_CheckExact(seq)) { + PyDictObject *mp = (PyDictObject *)d; + PyObject *oldvalue; + Py_ssize_t pos = 0; + PyObject *key; + long hash; + + if (dictresize(mp, Py_SIZE(seq))) + return NULL; + + while (_PyDict_Next(seq, &pos, &key, &oldvalue, &hash)) { + Py_INCREF(key); + Py_INCREF(value); + if (insertdict(mp, key, hash, value)) + return NULL; + } + return d; + } + + if (PyDict_CheckExact(d) && PyAnySet_CheckExact(seq)) { + PyDictObject *mp = (PyDictObject *)d; + Py_ssize_t pos = 0; + PyObject *key; + long hash; + + if (dictresize(mp, PySet_GET_SIZE(seq))) + return NULL; + + while (_PySet_NextEntry(seq, &pos, &key, &hash)) { + Py_INCREF(key); + Py_INCREF(value); + if (insertdict(mp, key, hash, value)) + return NULL; + } + return d; + } + + it = PyObject_GetIter(seq); + if (it == NULL){ + Py_DECREF(d); + return NULL; + } + + if (PyDict_CheckExact(d)) { + while ((key = PyIter_Next(it)) != NULL) { + status = PyDict_SetItem(d, key, value); + Py_DECREF(key); + if (status < 0) + goto Fail; + } + } else { + while ((key = PyIter_Next(it)) != NULL) { + status = PyObject_SetItem(d, key, value); + Py_DECREF(key); + if (status < 0) + goto Fail; + } + } + + if (PyErr_Occurred()) + goto Fail; + Py_DECREF(it); + return d; Fail: - Py_DECREF(it); - Py_DECREF(d); - return NULL; + Py_DECREF(it); + Py_DECREF(d); + return NULL; } static int dict_update_common(PyObject *self, PyObject *args, PyObject *kwds, char *methname) { - PyObject *arg = NULL; - int result = 0; + PyObject *arg = NULL; + int result = 0; - if (!PyArg_UnpackTuple(args, methname, 0, 1, &arg)) - result = -1; + if (!PyArg_UnpackTuple(args, methname, 0, 1, &arg)) + result = -1; - else if (arg != NULL) { - if (PyObject_HasAttrString(arg, "keys")) - result = PyDict_Merge(self, arg, 1); - else - result = PyDict_MergeFromSeq2(self, arg, 1); - } - if (result == 0 && kwds != NULL) { - if (PyArg_ValidateKeywordArguments(kwds)) - result = PyDict_Merge(self, kwds, 1); - else - result = -1; - } - return result; + else if (arg != NULL) { + if (PyObject_HasAttrString(arg, "keys")) + result = PyDict_Merge(self, arg, 1); + else + result = PyDict_MergeFromSeq2(self, arg, 1); + } + if (result == 0 && kwds != NULL) { + if (PyArg_ValidateKeywordArguments(kwds)) + result = PyDict_Merge(self, kwds, 1); + else + result = -1; + } + return result; } static PyObject * dict_update(PyObject *self, PyObject *args, PyObject *kwds) { - if (dict_update_common(self, args, kwds, "update") != -1) - Py_RETURN_NONE; - return NULL; + if (dict_update_common(self, args, kwds, "update") != -1) + Py_RETURN_NONE; + return NULL; } /* Update unconditionally replaces existing items. @@ -1432,238 +1432,238 @@ int PyDict_MergeFromSeq2(PyObject *d, PyObject *seq2, int override) { - PyObject *it; /* iter(seq2) */ - Py_ssize_t i; /* index into seq2 of current element */ - PyObject *item; /* seq2[i] */ - PyObject *fast; /* item as a 2-tuple or 2-list */ - - assert(d != NULL); - assert(PyDict_Check(d)); - assert(seq2 != NULL); - - it = PyObject_GetIter(seq2); - if (it == NULL) - return -1; - - for (i = 0; ; ++i) { - PyObject *key, *value; - Py_ssize_t n; - - fast = NULL; - item = PyIter_Next(it); - if (item == NULL) { - if (PyErr_Occurred()) - goto Fail; - break; - } - - /* Convert item to sequence, and verify length 2. */ - fast = PySequence_Fast(item, ""); - if (fast == NULL) { - if (PyErr_ExceptionMatches(PyExc_TypeError)) - PyErr_Format(PyExc_TypeError, - "cannot convert dictionary update " - "sequence element #%zd to a sequence", - i); - goto Fail; - } - n = PySequence_Fast_GET_SIZE(fast); - if (n != 2) { - PyErr_Format(PyExc_ValueError, - "dictionary update sequence element #%zd " - "has length %zd; 2 is required", - i, n); - goto Fail; - } - - /* Update/merge with this (key, value) pair. */ - key = PySequence_Fast_GET_ITEM(fast, 0); - value = PySequence_Fast_GET_ITEM(fast, 1); - if (override || PyDict_GetItem(d, key) == NULL) { - int status = PyDict_SetItem(d, key, value); - if (status < 0) - goto Fail; - } - Py_DECREF(fast); - Py_DECREF(item); - } + PyObject *it; /* iter(seq2) */ + Py_ssize_t i; /* index into seq2 of current element */ + PyObject *item; /* seq2[i] */ + PyObject *fast; /* item as a 2-tuple or 2-list */ + + assert(d != NULL); + assert(PyDict_Check(d)); + assert(seq2 != NULL); + + it = PyObject_GetIter(seq2); + if (it == NULL) + return -1; + + for (i = 0; ; ++i) { + PyObject *key, *value; + Py_ssize_t n; + + fast = NULL; + item = PyIter_Next(it); + if (item == NULL) { + if (PyErr_Occurred()) + goto Fail; + break; + } + + /* Convert item to sequence, and verify length 2. */ + fast = PySequence_Fast(item, ""); + if (fast == NULL) { + if (PyErr_ExceptionMatches(PyExc_TypeError)) + PyErr_Format(PyExc_TypeError, + "cannot convert dictionary update " + "sequence element #%zd to a sequence", + i); + goto Fail; + } + n = PySequence_Fast_GET_SIZE(fast); + if (n != 2) { + PyErr_Format(PyExc_ValueError, + "dictionary update sequence element #%zd " + "has length %zd; 2 is required", + i, n); + goto Fail; + } + + /* Update/merge with this (key, value) pair. */ + key = PySequence_Fast_GET_ITEM(fast, 0); + value = PySequence_Fast_GET_ITEM(fast, 1); + if (override || PyDict_GetItem(d, key) == NULL) { + int status = PyDict_SetItem(d, key, value); + if (status < 0) + goto Fail; + } + Py_DECREF(fast); + Py_DECREF(item); + } - i = 0; - goto Return; + i = 0; + goto Return; Fail: - Py_XDECREF(item); - Py_XDECREF(fast); - i = -1; + Py_XDECREF(item); + Py_XDECREF(fast); + i = -1; Return: - Py_DECREF(it); - return Py_SAFE_DOWNCAST(i, Py_ssize_t, int); + Py_DECREF(it); + return Py_SAFE_DOWNCAST(i, Py_ssize_t, int); } int PyDict_Update(PyObject *a, PyObject *b) { - return PyDict_Merge(a, b, 1); + return PyDict_Merge(a, b, 1); } int PyDict_Merge(PyObject *a, PyObject *b, int override) { - register PyDictObject *mp, *other; - register Py_ssize_t i; - PyDictEntry *entry; - - /* We accept for the argument either a concrete dictionary object, - * or an abstract "mapping" object. For the former, we can do - * things quite efficiently. For the latter, we only require that - * PyMapping_Keys() and PyObject_GetItem() be supported. - */ - if (a == NULL || !PyDict_Check(a) || b == NULL) { - PyErr_BadInternalCall(); - return -1; - } - mp = (PyDictObject*)a; - if (PyDict_Check(b)) { - other = (PyDictObject*)b; - if (other == mp || other->ma_used == 0) - /* a.update(a) or a.update({}); nothing to do */ - return 0; - if (mp->ma_used == 0) - /* Since the target dict is empty, PyDict_GetItem() - * always returns NULL. Setting override to 1 - * skips the unnecessary test. - */ - override = 1; - /* Do one big resize at the start, rather than - * incrementally resizing as we insert new items. Expect - * that there will be no (or few) overlapping keys. - */ - if ((mp->ma_fill + other->ma_used)*3 >= (mp->ma_mask+1)*2) { - if (dictresize(mp, (mp->ma_used + other->ma_used)*2) != 0) - return -1; - } - for (i = 0; i <= other->ma_mask; i++) { - entry = &other->ma_table[i]; - if (entry->me_value != NULL && - (override || - PyDict_GetItem(a, entry->me_key) == NULL)) { - Py_INCREF(entry->me_key); - Py_INCREF(entry->me_value); - if (insertdict(mp, entry->me_key, - (long)entry->me_hash, - entry->me_value) != 0) - return -1; - } - } - } - else { - /* Do it the generic, slower way */ - PyObject *keys = PyMapping_Keys(b); - PyObject *iter; - PyObject *key, *value; - int status; - - if (keys == NULL) - /* Docstring says this is equivalent to E.keys() so - * if E doesn't have a .keys() method we want - * AttributeError to percolate up. Might as well - * do the same for any other error. - */ - return -1; - - iter = PyObject_GetIter(keys); - Py_DECREF(keys); - if (iter == NULL) - return -1; - - for (key = PyIter_Next(iter); key; key = PyIter_Next(iter)) { - if (!override && PyDict_GetItem(a, key) != NULL) { - Py_DECREF(key); - continue; - } - value = PyObject_GetItem(b, key); - if (value == NULL) { - Py_DECREF(iter); - Py_DECREF(key); - return -1; - } - status = PyDict_SetItem(a, key, value); - Py_DECREF(key); - Py_DECREF(value); - if (status < 0) { - Py_DECREF(iter); - return -1; - } - } - Py_DECREF(iter); - if (PyErr_Occurred()) - /* Iterator completed, via error */ - return -1; - } - return 0; + register PyDictObject *mp, *other; + register Py_ssize_t i; + PyDictEntry *entry; + + /* We accept for the argument either a concrete dictionary object, + * or an abstract "mapping" object. For the former, we can do + * things quite efficiently. For the latter, we only require that + * PyMapping_Keys() and PyObject_GetItem() be supported. + */ + if (a == NULL || !PyDict_Check(a) || b == NULL) { + PyErr_BadInternalCall(); + return -1; + } + mp = (PyDictObject*)a; + if (PyDict_Check(b)) { + other = (PyDictObject*)b; + if (other == mp || other->ma_used == 0) + /* a.update(a) or a.update({}); nothing to do */ + return 0; + if (mp->ma_used == 0) + /* Since the target dict is empty, PyDict_GetItem() + * always returns NULL. Setting override to 1 + * skips the unnecessary test. + */ + override = 1; + /* Do one big resize at the start, rather than + * incrementally resizing as we insert new items. Expect + * that there will be no (or few) overlapping keys. + */ + if ((mp->ma_fill + other->ma_used)*3 >= (mp->ma_mask+1)*2) { + if (dictresize(mp, (mp->ma_used + other->ma_used)*2) != 0) + return -1; + } + for (i = 0; i <= other->ma_mask; i++) { + entry = &other->ma_table[i]; + if (entry->me_value != NULL && + (override || + PyDict_GetItem(a, entry->me_key) == NULL)) { + Py_INCREF(entry->me_key); + Py_INCREF(entry->me_value); + if (insertdict(mp, entry->me_key, + (long)entry->me_hash, + entry->me_value) != 0) + return -1; + } + } + } + else { + /* Do it the generic, slower way */ + PyObject *keys = PyMapping_Keys(b); + PyObject *iter; + PyObject *key, *value; + int status; + + if (keys == NULL) + /* Docstring says this is equivalent to E.keys() so + * if E doesn't have a .keys() method we want + * AttributeError to percolate up. Might as well + * do the same for any other error. + */ + return -1; + + iter = PyObject_GetIter(keys); + Py_DECREF(keys); + if (iter == NULL) + return -1; + + for (key = PyIter_Next(iter); key; key = PyIter_Next(iter)) { + if (!override && PyDict_GetItem(a, key) != NULL) { + Py_DECREF(key); + continue; + } + value = PyObject_GetItem(b, key); + if (value == NULL) { + Py_DECREF(iter); + Py_DECREF(key); + return -1; + } + status = PyDict_SetItem(a, key, value); + Py_DECREF(key); + Py_DECREF(value); + if (status < 0) { + Py_DECREF(iter); + return -1; + } + } + Py_DECREF(iter); + if (PyErr_Occurred()) + /* Iterator completed, via error */ + return -1; + } + return 0; } static PyObject * dict_copy(register PyDictObject *mp) { - return PyDict_Copy((PyObject*)mp); + return PyDict_Copy((PyObject*)mp); } PyObject * PyDict_Copy(PyObject *o) { - PyObject *copy; + PyObject *copy; - if (o == NULL || !PyDict_Check(o)) { - PyErr_BadInternalCall(); - return NULL; - } - copy = PyDict_New(); - if (copy == NULL) - return NULL; - if (PyDict_Merge(copy, o, 1) == 0) - return copy; - Py_DECREF(copy); - return NULL; + if (o == NULL || !PyDict_Check(o)) { + PyErr_BadInternalCall(); + return NULL; + } + copy = PyDict_New(); + if (copy == NULL) + return NULL; + if (PyDict_Merge(copy, o, 1) == 0) + return copy; + Py_DECREF(copy); + return NULL; } Py_ssize_t PyDict_Size(PyObject *mp) { - if (mp == NULL || !PyDict_Check(mp)) { - PyErr_BadInternalCall(); - return -1; - } - return ((PyDictObject *)mp)->ma_used; + if (mp == NULL || !PyDict_Check(mp)) { + PyErr_BadInternalCall(); + return -1; + } + return ((PyDictObject *)mp)->ma_used; } PyObject * PyDict_Keys(PyObject *mp) { - if (mp == NULL || !PyDict_Check(mp)) { - PyErr_BadInternalCall(); - return NULL; - } - return dict_keys((PyDictObject *)mp); + if (mp == NULL || !PyDict_Check(mp)) { + PyErr_BadInternalCall(); + return NULL; + } + return dict_keys((PyDictObject *)mp); } PyObject * PyDict_Values(PyObject *mp) { - if (mp == NULL || !PyDict_Check(mp)) { - PyErr_BadInternalCall(); - return NULL; - } - return dict_values((PyDictObject *)mp); + if (mp == NULL || !PyDict_Check(mp)) { + PyErr_BadInternalCall(); + return NULL; + } + return dict_values((PyDictObject *)mp); } PyObject * PyDict_Items(PyObject *mp) { - if (mp == NULL || !PyDict_Check(mp)) { - PyErr_BadInternalCall(); - return NULL; - } - return dict_items((PyDictObject *)mp); + if (mp == NULL || !PyDict_Check(mp)) { + PyErr_BadInternalCall(); + return NULL; + } + return dict_items((PyDictObject *)mp); } /* Return 1 if dicts equal, 0 if not, -1 if error. @@ -1673,271 +1673,271 @@ static int dict_equal(PyDictObject *a, PyDictObject *b) { - Py_ssize_t i; + Py_ssize_t i; - if (a->ma_used != b->ma_used) - /* can't be equal if # of entries differ */ - return 0; - - /* Same # of entries -- check all of 'em. Exit early on any diff. */ - for (i = 0; i <= a->ma_mask; i++) { - PyObject *aval = a->ma_table[i].me_value; - if (aval != NULL) { - int cmp; - PyObject *bval; - PyObject *key = a->ma_table[i].me_key; - /* temporarily bump aval's refcount to ensure it stays - alive until we're done with it */ - Py_INCREF(aval); - /* ditto for key */ - Py_INCREF(key); - bval = PyDict_GetItemWithError((PyObject *)b, key); - Py_DECREF(key); - if (bval == NULL) { - Py_DECREF(aval); - if (PyErr_Occurred()) - return -1; - return 0; - } - cmp = PyObject_RichCompareBool(aval, bval, Py_EQ); - Py_DECREF(aval); - if (cmp <= 0) /* error or not equal */ - return cmp; - } - } - return 1; + if (a->ma_used != b->ma_used) + /* can't be equal if # of entries differ */ + return 0; + + /* Same # of entries -- check all of 'em. Exit early on any diff. */ + for (i = 0; i <= a->ma_mask; i++) { + PyObject *aval = a->ma_table[i].me_value; + if (aval != NULL) { + int cmp; + PyObject *bval; + PyObject *key = a->ma_table[i].me_key; + /* temporarily bump aval's refcount to ensure it stays + alive until we're done with it */ + Py_INCREF(aval); + /* ditto for key */ + Py_INCREF(key); + bval = PyDict_GetItemWithError((PyObject *)b, key); + Py_DECREF(key); + if (bval == NULL) { + Py_DECREF(aval); + if (PyErr_Occurred()) + return -1; + return 0; + } + cmp = PyObject_RichCompareBool(aval, bval, Py_EQ); + Py_DECREF(aval); + if (cmp <= 0) /* error or not equal */ + return cmp; + } + } + return 1; } static PyObject * dict_richcompare(PyObject *v, PyObject *w, int op) { - int cmp; - PyObject *res; + int cmp; + PyObject *res; - if (!PyDict_Check(v) || !PyDict_Check(w)) { - res = Py_NotImplemented; - } - else if (op == Py_EQ || op == Py_NE) { - cmp = dict_equal((PyDictObject *)v, (PyDictObject *)w); - if (cmp < 0) - return NULL; - res = (cmp == (op == Py_EQ)) ? Py_True : Py_False; - } - else - res = Py_NotImplemented; - Py_INCREF(res); - return res; + if (!PyDict_Check(v) || !PyDict_Check(w)) { + res = Py_NotImplemented; + } + else if (op == Py_EQ || op == Py_NE) { + cmp = dict_equal((PyDictObject *)v, (PyDictObject *)w); + if (cmp < 0) + return NULL; + res = (cmp == (op == Py_EQ)) ? Py_True : Py_False; + } + else + res = Py_NotImplemented; + Py_INCREF(res); + return res; } static PyObject * dict_contains(register PyDictObject *mp, PyObject *key) { - long hash; - PyDictEntry *ep; + long hash; + PyDictEntry *ep; - if (!PyUnicode_CheckExact(key) || - (hash = ((PyUnicodeObject *) key)->hash) == -1) { - hash = PyObject_Hash(key); - if (hash == -1) - return NULL; - } - ep = (mp->ma_lookup)(mp, key, hash); - if (ep == NULL) - return NULL; - return PyBool_FromLong(ep->me_value != NULL); + if (!PyUnicode_CheckExact(key) || + (hash = ((PyUnicodeObject *) key)->hash) == -1) { + hash = PyObject_Hash(key); + if (hash == -1) + return NULL; + } + ep = (mp->ma_lookup)(mp, key, hash); + if (ep == NULL) + return NULL; + return PyBool_FromLong(ep->me_value != NULL); } static PyObject * dict_get(register PyDictObject *mp, PyObject *args) { - PyObject *key; - PyObject *failobj = Py_None; - PyObject *val = NULL; - long hash; - PyDictEntry *ep; - - if (!PyArg_UnpackTuple(args, "get", 1, 2, &key, &failobj)) - return NULL; - - if (!PyUnicode_CheckExact(key) || - (hash = ((PyUnicodeObject *) key)->hash) == -1) { - hash = PyObject_Hash(key); - if (hash == -1) - return NULL; - } - ep = (mp->ma_lookup)(mp, key, hash); - if (ep == NULL) - return NULL; - val = ep->me_value; - if (val == NULL) - val = failobj; - Py_INCREF(val); - return val; + PyObject *key; + PyObject *failobj = Py_None; + PyObject *val = NULL; + long hash; + PyDictEntry *ep; + + if (!PyArg_UnpackTuple(args, "get", 1, 2, &key, &failobj)) + return NULL; + + if (!PyUnicode_CheckExact(key) || + (hash = ((PyUnicodeObject *) key)->hash) == -1) { + hash = PyObject_Hash(key); + if (hash == -1) + return NULL; + } + ep = (mp->ma_lookup)(mp, key, hash); + if (ep == NULL) + return NULL; + val = ep->me_value; + if (val == NULL) + val = failobj; + Py_INCREF(val); + return val; } static PyObject * dict_setdefault(register PyDictObject *mp, PyObject *args) { - PyObject *key; - PyObject *failobj = Py_None; - PyObject *val = NULL; - long hash; - PyDictEntry *ep; - - if (!PyArg_UnpackTuple(args, "setdefault", 1, 2, &key, &failobj)) - return NULL; - - if (!PyUnicode_CheckExact(key) || - (hash = ((PyUnicodeObject *) key)->hash) == -1) { - hash = PyObject_Hash(key); - if (hash == -1) - return NULL; - } - ep = (mp->ma_lookup)(mp, key, hash); - if (ep == NULL) - return NULL; - val = ep->me_value; - if (val == NULL) { - val = failobj; - if (PyDict_SetItem((PyObject*)mp, key, failobj)) - val = NULL; - } - Py_XINCREF(val); - return val; + PyObject *key; + PyObject *failobj = Py_None; + PyObject *val = NULL; + long hash; + PyDictEntry *ep; + + if (!PyArg_UnpackTuple(args, "setdefault", 1, 2, &key, &failobj)) + return NULL; + + if (!PyUnicode_CheckExact(key) || + (hash = ((PyUnicodeObject *) key)->hash) == -1) { + hash = PyObject_Hash(key); + if (hash == -1) + return NULL; + } + ep = (mp->ma_lookup)(mp, key, hash); + if (ep == NULL) + return NULL; + val = ep->me_value; + if (val == NULL) { + val = failobj; + if (PyDict_SetItem((PyObject*)mp, key, failobj)) + val = NULL; + } + Py_XINCREF(val); + return val; } static PyObject * dict_clear(register PyDictObject *mp) { - PyDict_Clear((PyObject *)mp); - Py_RETURN_NONE; + PyDict_Clear((PyObject *)mp); + Py_RETURN_NONE; } static PyObject * dict_pop(PyDictObject *mp, PyObject *args) { - long hash; - PyDictEntry *ep; - PyObject *old_value, *old_key; - PyObject *key, *deflt = NULL; - - if(!PyArg_UnpackTuple(args, "pop", 1, 2, &key, &deflt)) - return NULL; - if (mp->ma_used == 0) { - if (deflt) { - Py_INCREF(deflt); - return deflt; - } - PyErr_SetString(PyExc_KeyError, - "pop(): dictionary is empty"); - return NULL; - } - if (!PyUnicode_CheckExact(key) || - (hash = ((PyUnicodeObject *) key)->hash) == -1) { - hash = PyObject_Hash(key); - if (hash == -1) - return NULL; - } - ep = (mp->ma_lookup)(mp, key, hash); - if (ep == NULL) - return NULL; - if (ep->me_value == NULL) { - if (deflt) { - Py_INCREF(deflt); - return deflt; - } - set_key_error(key); - return NULL; - } - old_key = ep->me_key; - Py_INCREF(dummy); - ep->me_key = dummy; - old_value = ep->me_value; - ep->me_value = NULL; - mp->ma_used--; - Py_DECREF(old_key); - return old_value; + long hash; + PyDictEntry *ep; + PyObject *old_value, *old_key; + PyObject *key, *deflt = NULL; + + if(!PyArg_UnpackTuple(args, "pop", 1, 2, &key, &deflt)) + return NULL; + if (mp->ma_used == 0) { + if (deflt) { + Py_INCREF(deflt); + return deflt; + } + PyErr_SetString(PyExc_KeyError, + "pop(): dictionary is empty"); + return NULL; + } + if (!PyUnicode_CheckExact(key) || + (hash = ((PyUnicodeObject *) key)->hash) == -1) { + hash = PyObject_Hash(key); + if (hash == -1) + return NULL; + } + ep = (mp->ma_lookup)(mp, key, hash); + if (ep == NULL) + return NULL; + if (ep->me_value == NULL) { + if (deflt) { + Py_INCREF(deflt); + return deflt; + } + set_key_error(key); + return NULL; + } + old_key = ep->me_key; + Py_INCREF(dummy); + ep->me_key = dummy; + old_value = ep->me_value; + ep->me_value = NULL; + mp->ma_used--; + Py_DECREF(old_key); + return old_value; } static PyObject * dict_popitem(PyDictObject *mp) { - Py_ssize_t i = 0; - PyDictEntry *ep; - PyObject *res; - - /* Allocate the result tuple before checking the size. Believe it - * or not, this allocation could trigger a garbage collection which - * could empty the dict, so if we checked the size first and that - * happened, the result would be an infinite loop (searching for an - * entry that no longer exists). Note that the usual popitem() - * idiom is "while d: k, v = d.popitem()". so needing to throw the - * tuple away if the dict *is* empty isn't a significant - * inefficiency -- possible, but unlikely in practice. - */ - res = PyTuple_New(2); - if (res == NULL) - return NULL; - if (mp->ma_used == 0) { - Py_DECREF(res); - PyErr_SetString(PyExc_KeyError, - "popitem(): dictionary is empty"); - return NULL; - } - /* Set ep to "the first" dict entry with a value. We abuse the hash - * field of slot 0 to hold a search finger: - * If slot 0 has a value, use slot 0. - * Else slot 0 is being used to hold a search finger, - * and we use its hash value as the first index to look. - */ - ep = &mp->ma_table[0]; - if (ep->me_value == NULL) { - i = ep->me_hash; - /* The hash field may be a real hash value, or it may be a - * legit search finger, or it may be a once-legit search - * finger that's out of bounds now because it wrapped around - * or the table shrunk -- simply make sure it's in bounds now. - */ - if (i > mp->ma_mask || i < 1) - i = 1; /* skip slot 0 */ - while ((ep = &mp->ma_table[i])->me_value == NULL) { - i++; - if (i > mp->ma_mask) - i = 1; - } - } - PyTuple_SET_ITEM(res, 0, ep->me_key); - PyTuple_SET_ITEM(res, 1, ep->me_value); - Py_INCREF(dummy); - ep->me_key = dummy; - ep->me_value = NULL; - mp->ma_used--; - assert(mp->ma_table[0].me_value == NULL); - mp->ma_table[0].me_hash = i + 1; /* next place to start */ - return res; + Py_ssize_t i = 0; + PyDictEntry *ep; + PyObject *res; + + /* Allocate the result tuple before checking the size. Believe it + * or not, this allocation could trigger a garbage collection which + * could empty the dict, so if we checked the size first and that + * happened, the result would be an infinite loop (searching for an + * entry that no longer exists). Note that the usual popitem() + * idiom is "while d: k, v = d.popitem()". so needing to throw the + * tuple away if the dict *is* empty isn't a significant + * inefficiency -- possible, but unlikely in practice. + */ + res = PyTuple_New(2); + if (res == NULL) + return NULL; + if (mp->ma_used == 0) { + Py_DECREF(res); + PyErr_SetString(PyExc_KeyError, + "popitem(): dictionary is empty"); + return NULL; + } + /* Set ep to "the first" dict entry with a value. We abuse the hash + * field of slot 0 to hold a search finger: + * If slot 0 has a value, use slot 0. + * Else slot 0 is being used to hold a search finger, + * and we use its hash value as the first index to look. + */ + ep = &mp->ma_table[0]; + if (ep->me_value == NULL) { + i = ep->me_hash; + /* The hash field may be a real hash value, or it may be a + * legit search finger, or it may be a once-legit search + * finger that's out of bounds now because it wrapped around + * or the table shrunk -- simply make sure it's in bounds now. + */ + if (i > mp->ma_mask || i < 1) + i = 1; /* skip slot 0 */ + while ((ep = &mp->ma_table[i])->me_value == NULL) { + i++; + if (i > mp->ma_mask) + i = 1; + } + } + PyTuple_SET_ITEM(res, 0, ep->me_key); + PyTuple_SET_ITEM(res, 1, ep->me_value); + Py_INCREF(dummy); + ep->me_key = dummy; + ep->me_value = NULL; + mp->ma_used--; + assert(mp->ma_table[0].me_value == NULL); + mp->ma_table[0].me_hash = i + 1; /* next place to start */ + return res; } static int dict_traverse(PyObject *op, visitproc visit, void *arg) { - Py_ssize_t i = 0; - PyObject *pk; - PyObject *pv; - - while (PyDict_Next(op, &i, &pk, &pv)) { - Py_VISIT(pk); - Py_VISIT(pv); - } - return 0; + Py_ssize_t i = 0; + PyObject *pk; + PyObject *pv; + + while (PyDict_Next(op, &i, &pk, &pv)) { + Py_VISIT(pk); + Py_VISIT(pv); + } + return 0; } static int dict_tp_clear(PyObject *op) { - PyDict_Clear(op); - return 0; + PyDict_Clear(op); + return 0; } static PyObject *dictiter_new(PyDictObject *, PyTypeObject *); @@ -1945,12 +1945,12 @@ static PyObject * dict_sizeof(PyDictObject *mp) { - Py_ssize_t res; + Py_ssize_t res; - res = sizeof(PyDictObject); - if (mp->ma_table != mp->ma_smalltable) - res = res + (mp->ma_mask + 1) * sizeof(PyDictEntry); - return PyLong_FromSsize_t(res); + res = sizeof(PyDictObject); + if (mp->ma_table != mp->ma_smalltable) + res = res + (mp->ma_mask + 1) * sizeof(PyDictEntry); + return PyLong_FromSsize_t(res); } PyDoc_STRVAR(contains__doc__, @@ -1997,126 +1997,126 @@ static PyObject *dictvalues_new(PyObject *); PyDoc_STRVAR(keys__doc__, - "D.keys() -> a set-like object providing a view on D's keys"); + "D.keys() -> a set-like object providing a view on D's keys"); PyDoc_STRVAR(items__doc__, - "D.items() -> a set-like object providing a view on D's items"); + "D.items() -> a set-like object providing a view on D's items"); PyDoc_STRVAR(values__doc__, - "D.values() -> an object providing a view on D's values"); + "D.values() -> an object providing a view on D's values"); static PyMethodDef mapp_methods[] = { - {"__contains__",(PyCFunction)dict_contains, METH_O | METH_COEXIST, - contains__doc__}, - {"__getitem__", (PyCFunction)dict_subscript, METH_O | METH_COEXIST, - getitem__doc__}, - {"__sizeof__", (PyCFunction)dict_sizeof, METH_NOARGS, - sizeof__doc__}, - {"get", (PyCFunction)dict_get, METH_VARARGS, - get__doc__}, - {"setdefault", (PyCFunction)dict_setdefault, METH_VARARGS, - setdefault_doc__}, - {"pop", (PyCFunction)dict_pop, METH_VARARGS, - pop__doc__}, - {"popitem", (PyCFunction)dict_popitem, METH_NOARGS, - popitem__doc__}, - {"keys", (PyCFunction)dictkeys_new, METH_NOARGS, - keys__doc__}, - {"items", (PyCFunction)dictitems_new, METH_NOARGS, - items__doc__}, - {"values", (PyCFunction)dictvalues_new, METH_NOARGS, - values__doc__}, - {"update", (PyCFunction)dict_update, METH_VARARGS | METH_KEYWORDS, - update__doc__}, - {"fromkeys", (PyCFunction)dict_fromkeys, METH_VARARGS | METH_CLASS, - fromkeys__doc__}, - {"clear", (PyCFunction)dict_clear, METH_NOARGS, - clear__doc__}, - {"copy", (PyCFunction)dict_copy, METH_NOARGS, - copy__doc__}, - {NULL, NULL} /* sentinel */ + {"__contains__",(PyCFunction)dict_contains, METH_O | METH_COEXIST, + contains__doc__}, + {"__getitem__", (PyCFunction)dict_subscript, METH_O | METH_COEXIST, + getitem__doc__}, + {"__sizeof__", (PyCFunction)dict_sizeof, METH_NOARGS, + sizeof__doc__}, + {"get", (PyCFunction)dict_get, METH_VARARGS, + get__doc__}, + {"setdefault", (PyCFunction)dict_setdefault, METH_VARARGS, + setdefault_doc__}, + {"pop", (PyCFunction)dict_pop, METH_VARARGS, + pop__doc__}, + {"popitem", (PyCFunction)dict_popitem, METH_NOARGS, + popitem__doc__}, + {"keys", (PyCFunction)dictkeys_new, METH_NOARGS, + keys__doc__}, + {"items", (PyCFunction)dictitems_new, METH_NOARGS, + items__doc__}, + {"values", (PyCFunction)dictvalues_new, METH_NOARGS, + values__doc__}, + {"update", (PyCFunction)dict_update, METH_VARARGS | METH_KEYWORDS, + update__doc__}, + {"fromkeys", (PyCFunction)dict_fromkeys, METH_VARARGS | METH_CLASS, + fromkeys__doc__}, + {"clear", (PyCFunction)dict_clear, METH_NOARGS, + clear__doc__}, + {"copy", (PyCFunction)dict_copy, METH_NOARGS, + copy__doc__}, + {NULL, NULL} /* sentinel */ }; /* Return 1 if `key` is in dict `op`, 0 if not, and -1 on error. */ int PyDict_Contains(PyObject *op, PyObject *key) { - long hash; - PyDictObject *mp = (PyDictObject *)op; - PyDictEntry *ep; - - if (!PyUnicode_CheckExact(key) || - (hash = ((PyUnicodeObject *) key)->hash) == -1) { - hash = PyObject_Hash(key); - if (hash == -1) - return -1; - } - ep = (mp->ma_lookup)(mp, key, hash); - return ep == NULL ? -1 : (ep->me_value != NULL); + long hash; + PyDictObject *mp = (PyDictObject *)op; + PyDictEntry *ep; + + if (!PyUnicode_CheckExact(key) || + (hash = ((PyUnicodeObject *) key)->hash) == -1) { + hash = PyObject_Hash(key); + if (hash == -1) + return -1; + } + ep = (mp->ma_lookup)(mp, key, hash); + return ep == NULL ? -1 : (ep->me_value != NULL); } /* Internal version of PyDict_Contains used when the hash value is already known */ int _PyDict_Contains(PyObject *op, PyObject *key, long hash) { - PyDictObject *mp = (PyDictObject *)op; - PyDictEntry *ep; + PyDictObject *mp = (PyDictObject *)op; + PyDictEntry *ep; - ep = (mp->ma_lookup)(mp, key, hash); - return ep == NULL ? -1 : (ep->me_value != NULL); + ep = (mp->ma_lookup)(mp, key, hash); + return ep == NULL ? -1 : (ep->me_value != NULL); } /* Hack to implement "key in dict" */ static PySequenceMethods dict_as_sequence = { - 0, /* sq_length */ - 0, /* sq_concat */ - 0, /* sq_repeat */ - 0, /* sq_item */ - 0, /* sq_slice */ - 0, /* sq_ass_item */ - 0, /* sq_ass_slice */ - PyDict_Contains, /* sq_contains */ - 0, /* sq_inplace_concat */ - 0, /* sq_inplace_repeat */ + 0, /* sq_length */ + 0, /* sq_concat */ + 0, /* sq_repeat */ + 0, /* sq_item */ + 0, /* sq_slice */ + 0, /* sq_ass_item */ + 0, /* sq_ass_slice */ + PyDict_Contains, /* sq_contains */ + 0, /* sq_inplace_concat */ + 0, /* sq_inplace_repeat */ }; static PyObject * dict_new(PyTypeObject *type, PyObject *args, PyObject *kwds) { - PyObject *self; + PyObject *self; - assert(type != NULL && type->tp_alloc != NULL); - self = type->tp_alloc(type, 0); - if (self != NULL) { - PyDictObject *d = (PyDictObject *)self; - /* It's guaranteed that tp->alloc zeroed out the struct. */ - assert(d->ma_table == NULL && d->ma_fill == 0 && d->ma_used == 0); - INIT_NONZERO_DICT_SLOTS(d); - d->ma_lookup = lookdict_unicode; - /* The object has been implicitely tracked by tp_alloc */ - if (type == &PyDict_Type) - _PyObject_GC_UNTRACK(d); + assert(type != NULL && type->tp_alloc != NULL); + self = type->tp_alloc(type, 0); + if (self != NULL) { + PyDictObject *d = (PyDictObject *)self; + /* It's guaranteed that tp->alloc zeroed out the struct. */ + assert(d->ma_table == NULL && d->ma_fill == 0 && d->ma_used == 0); + INIT_NONZERO_DICT_SLOTS(d); + d->ma_lookup = lookdict_unicode; + /* The object has been implicitely tracked by tp_alloc */ + if (type == &PyDict_Type) + _PyObject_GC_UNTRACK(d); #ifdef SHOW_CONVERSION_COUNTS - ++created; + ++created; #endif #ifdef SHOW_TRACK_COUNT - if (_PyObject_GC_IS_TRACKED(d)) - count_tracked++; - else - count_untracked++; + if (_PyObject_GC_IS_TRACKED(d)) + count_tracked++; + else + count_untracked++; #endif - } - return self; + } + return self; } static int dict_init(PyObject *self, PyObject *args, PyObject *kwds) { - return dict_update_common(self, args, kwds, "dict"); + return dict_update_common(self, args, kwds, "dict"); } static PyObject * dict_iter(PyDictObject *dict) { - return dictiter_new(dict, &PyDictIterKey_Type); + return dictiter_new(dict, &PyDictIterKey_Type); } PyDoc_STRVAR(dictionary_doc, @@ -2131,46 +2131,46 @@ " in the keyword argument list. For example: dict(one=1, two=2)"); PyTypeObject PyDict_Type = { - PyVarObject_HEAD_INIT(&PyType_Type, 0) - "dict", - sizeof(PyDictObject), - 0, - (destructor)dict_dealloc, /* tp_dealloc */ - 0, /* tp_print */ - 0, /* tp_getattr */ - 0, /* tp_setattr */ - 0, /* tp_reserved */ - (reprfunc)dict_repr, /* tp_repr */ - 0, /* tp_as_number */ - &dict_as_sequence, /* tp_as_sequence */ - &dict_as_mapping, /* tp_as_mapping */ - (hashfunc)PyObject_HashNotImplemented, /* 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 | - Py_TPFLAGS_BASETYPE | Py_TPFLAGS_DICT_SUBCLASS, /* tp_flags */ - dictionary_doc, /* tp_doc */ - dict_traverse, /* tp_traverse */ - dict_tp_clear, /* tp_clear */ - dict_richcompare, /* tp_richcompare */ - 0, /* tp_weaklistoffset */ - (getiterfunc)dict_iter, /* tp_iter */ - 0, /* tp_iternext */ - mapp_methods, /* tp_methods */ - 0, /* tp_members */ - 0, /* tp_getset */ - 0, /* tp_base */ - 0, /* tp_dict */ - 0, /* tp_descr_get */ - 0, /* tp_descr_set */ - 0, /* tp_dictoffset */ - dict_init, /* tp_init */ - PyType_GenericAlloc, /* tp_alloc */ - dict_new, /* tp_new */ - PyObject_GC_Del, /* tp_free */ + PyVarObject_HEAD_INIT(&PyType_Type, 0) + "dict", + sizeof(PyDictObject), + 0, + (destructor)dict_dealloc, /* tp_dealloc */ + 0, /* tp_print */ + 0, /* tp_getattr */ + 0, /* tp_setattr */ + 0, /* tp_reserved */ + (reprfunc)dict_repr, /* tp_repr */ + 0, /* tp_as_number */ + &dict_as_sequence, /* tp_as_sequence */ + &dict_as_mapping, /* tp_as_mapping */ + (hashfunc)PyObject_HashNotImplemented, /* 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 | + Py_TPFLAGS_BASETYPE | Py_TPFLAGS_DICT_SUBCLASS, /* tp_flags */ + dictionary_doc, /* tp_doc */ + dict_traverse, /* tp_traverse */ + dict_tp_clear, /* tp_clear */ + dict_richcompare, /* tp_richcompare */ + 0, /* tp_weaklistoffset */ + (getiterfunc)dict_iter, /* tp_iter */ + 0, /* tp_iternext */ + mapp_methods, /* tp_methods */ + 0, /* tp_members */ + 0, /* tp_getset */ + 0, /* tp_base */ + 0, /* tp_dict */ + 0, /* tp_descr_get */ + 0, /* tp_descr_set */ + 0, /* tp_dictoffset */ + dict_init, /* tp_init */ + PyType_GenericAlloc, /* tp_alloc */ + dict_new, /* tp_new */ + PyObject_GC_Del, /* tp_free */ }; /* For backward compatibility with old dictionary interface */ @@ -2178,340 +2178,340 @@ PyObject * PyDict_GetItemString(PyObject *v, const char *key) { - PyObject *kv, *rv; - kv = PyUnicode_FromString(key); - if (kv == NULL) - return NULL; - rv = PyDict_GetItem(v, kv); - Py_DECREF(kv); - return rv; + PyObject *kv, *rv; + kv = PyUnicode_FromString(key); + if (kv == NULL) + return NULL; + rv = PyDict_GetItem(v, kv); + Py_DECREF(kv); + return rv; } int PyDict_SetItemString(PyObject *v, const char *key, PyObject *item) { - PyObject *kv; - int err; - kv = PyUnicode_FromString(key); - if (kv == NULL) - return -1; - PyUnicode_InternInPlace(&kv); /* XXX Should we really? */ - err = PyDict_SetItem(v, kv, item); - Py_DECREF(kv); - return err; + PyObject *kv; + int err; + kv = PyUnicode_FromString(key); + if (kv == NULL) + return -1; + PyUnicode_InternInPlace(&kv); /* XXX Should we really? */ + err = PyDict_SetItem(v, kv, item); + Py_DECREF(kv); + return err; } int PyDict_DelItemString(PyObject *v, const char *key) { - PyObject *kv; - int err; - kv = PyUnicode_FromString(key); - if (kv == NULL) - return -1; - err = PyDict_DelItem(v, kv); - Py_DECREF(kv); - return err; + PyObject *kv; + int err; + kv = PyUnicode_FromString(key); + if (kv == NULL) + return -1; + err = PyDict_DelItem(v, kv); + Py_DECREF(kv); + return err; } /* Dictionary iterator types */ typedef struct { - PyObject_HEAD - PyDictObject *di_dict; /* Set to NULL when iterator is exhausted */ - Py_ssize_t di_used; - Py_ssize_t di_pos; - PyObject* di_result; /* reusable result tuple for iteritems */ - Py_ssize_t len; + PyObject_HEAD + PyDictObject *di_dict; /* Set to NULL when iterator is exhausted */ + Py_ssize_t di_used; + Py_ssize_t di_pos; + PyObject* di_result; /* reusable result tuple for iteritems */ + Py_ssize_t len; } dictiterobject; static PyObject * dictiter_new(PyDictObject *dict, PyTypeObject *itertype) { - dictiterobject *di; - di = PyObject_GC_New(dictiterobject, itertype); - if (di == NULL) - return NULL; - Py_INCREF(dict); - di->di_dict = dict; - di->di_used = dict->ma_used; - di->di_pos = 0; - di->len = dict->ma_used; - if (itertype == &PyDictIterItem_Type) { - di->di_result = PyTuple_Pack(2, Py_None, Py_None); - if (di->di_result == NULL) { - Py_DECREF(di); - return NULL; - } - } - else - di->di_result = NULL; - _PyObject_GC_TRACK(di); - return (PyObject *)di; + dictiterobject *di; + di = PyObject_GC_New(dictiterobject, itertype); + if (di == NULL) + return NULL; + Py_INCREF(dict); + di->di_dict = dict; + di->di_used = dict->ma_used; + di->di_pos = 0; + di->len = dict->ma_used; + if (itertype == &PyDictIterItem_Type) { + di->di_result = PyTuple_Pack(2, Py_None, Py_None); + if (di->di_result == NULL) { + Py_DECREF(di); + return NULL; + } + } + else + di->di_result = NULL; + _PyObject_GC_TRACK(di); + return (PyObject *)di; } static void dictiter_dealloc(dictiterobject *di) { - Py_XDECREF(di->di_dict); - Py_XDECREF(di->di_result); - PyObject_GC_Del(di); + Py_XDECREF(di->di_dict); + Py_XDECREF(di->di_result); + PyObject_GC_Del(di); } static int dictiter_traverse(dictiterobject *di, visitproc visit, void *arg) { - Py_VISIT(di->di_dict); - Py_VISIT(di->di_result); - return 0; + Py_VISIT(di->di_dict); + Py_VISIT(di->di_result); + return 0; } static PyObject * dictiter_len(dictiterobject *di) { - Py_ssize_t len = 0; - if (di->di_dict != NULL && di->di_used == di->di_dict->ma_used) - len = di->len; - return PyLong_FromSize_t(len); + Py_ssize_t len = 0; + if (di->di_dict != NULL && di->di_used == di->di_dict->ma_used) + len = di->len; + return PyLong_FromSize_t(len); } PyDoc_STRVAR(length_hint_doc, "Private method returning an estimate of len(list(it))."); static PyMethodDef dictiter_methods[] = { - {"__length_hint__", (PyCFunction)dictiter_len, METH_NOARGS, - length_hint_doc}, - {NULL, NULL} /* sentinel */ + {"__length_hint__", (PyCFunction)dictiter_len, METH_NOARGS, + length_hint_doc}, + {NULL, NULL} /* sentinel */ }; static PyObject *dictiter_iternextkey(dictiterobject *di) { - PyObject *key; - register Py_ssize_t i, mask; - register PyDictEntry *ep; - PyDictObject *d = di->di_dict; - - if (d == NULL) - return NULL; - assert (PyDict_Check(d)); - - if (di->di_used != d->ma_used) { - PyErr_SetString(PyExc_RuntimeError, - "dictionary changed size during iteration"); - di->di_used = -1; /* Make this state sticky */ - return NULL; - } - - i = di->di_pos; - if (i < 0) - goto fail; - ep = d->ma_table; - mask = d->ma_mask; - while (i <= mask && ep[i].me_value == NULL) - i++; - di->di_pos = i+1; - if (i > mask) - goto fail; - di->len--; - key = ep[i].me_key; - Py_INCREF(key); - return key; + PyObject *key; + register Py_ssize_t i, mask; + register PyDictEntry *ep; + PyDictObject *d = di->di_dict; + + if (d == NULL) + return NULL; + assert (PyDict_Check(d)); + + if (di->di_used != d->ma_used) { + PyErr_SetString(PyExc_RuntimeError, + "dictionary changed size during iteration"); + di->di_used = -1; /* Make this state sticky */ + return NULL; + } + + i = di->di_pos; + if (i < 0) + goto fail; + ep = d->ma_table; + mask = d->ma_mask; + while (i <= mask && ep[i].me_value == NULL) + i++; + di->di_pos = i+1; + if (i > mask) + goto fail; + di->len--; + key = ep[i].me_key; + Py_INCREF(key); + return key; fail: - Py_DECREF(d); - di->di_dict = NULL; - return NULL; + Py_DECREF(d); + di->di_dict = NULL; + return NULL; } PyTypeObject PyDictIterKey_Type = { - PyVarObject_HEAD_INIT(&PyType_Type, 0) - "dict_keyiterator", /* tp_name */ - sizeof(dictiterobject), /* tp_basicsize */ - 0, /* tp_itemsize */ - /* methods */ - (destructor)dictiter_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)dictiter_traverse, /* tp_traverse */ - 0, /* tp_clear */ - 0, /* tp_richcompare */ - 0, /* tp_weaklistoffset */ - PyObject_SelfIter, /* tp_iter */ - (iternextfunc)dictiter_iternextkey, /* tp_iternext */ - dictiter_methods, /* tp_methods */ - 0, + PyVarObject_HEAD_INIT(&PyType_Type, 0) + "dict_keyiterator", /* tp_name */ + sizeof(dictiterobject), /* tp_basicsize */ + 0, /* tp_itemsize */ + /* methods */ + (destructor)dictiter_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)dictiter_traverse, /* tp_traverse */ + 0, /* tp_clear */ + 0, /* tp_richcompare */ + 0, /* tp_weaklistoffset */ + PyObject_SelfIter, /* tp_iter */ + (iternextfunc)dictiter_iternextkey, /* tp_iternext */ + dictiter_methods, /* tp_methods */ + 0, }; static PyObject *dictiter_iternextvalue(dictiterobject *di) { - PyObject *value; - register Py_ssize_t i, mask; - register PyDictEntry *ep; - PyDictObject *d = di->di_dict; - - if (d == NULL) - return NULL; - assert (PyDict_Check(d)); - - if (di->di_used != d->ma_used) { - PyErr_SetString(PyExc_RuntimeError, - "dictionary changed size during iteration"); - di->di_used = -1; /* Make this state sticky */ - return NULL; - } - - i = di->di_pos; - mask = d->ma_mask; - if (i < 0 || i > mask) - goto fail; - ep = d->ma_table; - while ((value=ep[i].me_value) == NULL) { - i++; - if (i > mask) - goto fail; - } - di->di_pos = i+1; - di->len--; - Py_INCREF(value); - return value; + PyObject *value; + register Py_ssize_t i, mask; + register PyDictEntry *ep; + PyDictObject *d = di->di_dict; + + if (d == NULL) + return NULL; + assert (PyDict_Check(d)); + + if (di->di_used != d->ma_used) { + PyErr_SetString(PyExc_RuntimeError, + "dictionary changed size during iteration"); + di->di_used = -1; /* Make this state sticky */ + return NULL; + } + + i = di->di_pos; + mask = d->ma_mask; + if (i < 0 || i > mask) + goto fail; + ep = d->ma_table; + while ((value=ep[i].me_value) == NULL) { + i++; + if (i > mask) + goto fail; + } + di->di_pos = i+1; + di->len--; + Py_INCREF(value); + return value; fail: - Py_DECREF(d); - di->di_dict = NULL; - return NULL; + Py_DECREF(d); + di->di_dict = NULL; + return NULL; } PyTypeObject PyDictIterValue_Type = { - PyVarObject_HEAD_INIT(&PyType_Type, 0) - "dict_valueiterator", /* tp_name */ - sizeof(dictiterobject), /* tp_basicsize */ - 0, /* tp_itemsize */ - /* methods */ - (destructor)dictiter_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)dictiter_traverse, /* tp_traverse */ - 0, /* tp_clear */ - 0, /* tp_richcompare */ - 0, /* tp_weaklistoffset */ - PyObject_SelfIter, /* tp_iter */ - (iternextfunc)dictiter_iternextvalue, /* tp_iternext */ - dictiter_methods, /* tp_methods */ - 0, + PyVarObject_HEAD_INIT(&PyType_Type, 0) + "dict_valueiterator", /* tp_name */ + sizeof(dictiterobject), /* tp_basicsize */ + 0, /* tp_itemsize */ + /* methods */ + (destructor)dictiter_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)dictiter_traverse, /* tp_traverse */ + 0, /* tp_clear */ + 0, /* tp_richcompare */ + 0, /* tp_weaklistoffset */ + PyObject_SelfIter, /* tp_iter */ + (iternextfunc)dictiter_iternextvalue, /* tp_iternext */ + dictiter_methods, /* tp_methods */ + 0, }; static PyObject *dictiter_iternextitem(dictiterobject *di) { - PyObject *key, *value, *result = di->di_result; - register Py_ssize_t i, mask; - register PyDictEntry *ep; - PyDictObject *d = di->di_dict; - - if (d == NULL) - return NULL; - assert (PyDict_Check(d)); - - if (di->di_used != d->ma_used) { - PyErr_SetString(PyExc_RuntimeError, - "dictionary changed size during iteration"); - di->di_used = -1; /* Make this state sticky */ - return NULL; - } - - i = di->di_pos; - if (i < 0) - goto fail; - ep = d->ma_table; - mask = d->ma_mask; - while (i <= mask && ep[i].me_value == NULL) - i++; - di->di_pos = i+1; - if (i > mask) - goto fail; - - if (result->ob_refcnt == 1) { - Py_INCREF(result); - Py_DECREF(PyTuple_GET_ITEM(result, 0)); - Py_DECREF(PyTuple_GET_ITEM(result, 1)); - } else { - result = PyTuple_New(2); - if (result == NULL) - return NULL; - } - di->len--; - key = ep[i].me_key; - value = ep[i].me_value; - Py_INCREF(key); - Py_INCREF(value); - PyTuple_SET_ITEM(result, 0, key); - PyTuple_SET_ITEM(result, 1, value); - return result; + PyObject *key, *value, *result = di->di_result; + register Py_ssize_t i, mask; + register PyDictEntry *ep; + PyDictObject *d = di->di_dict; + + if (d == NULL) + return NULL; + assert (PyDict_Check(d)); + + if (di->di_used != d->ma_used) { + PyErr_SetString(PyExc_RuntimeError, + "dictionary changed size during iteration"); + di->di_used = -1; /* Make this state sticky */ + return NULL; + } + + i = di->di_pos; + if (i < 0) + goto fail; + ep = d->ma_table; + mask = d->ma_mask; + while (i <= mask && ep[i].me_value == NULL) + i++; + di->di_pos = i+1; + if (i > mask) + goto fail; + + if (result->ob_refcnt == 1) { + Py_INCREF(result); + Py_DECREF(PyTuple_GET_ITEM(result, 0)); + Py_DECREF(PyTuple_GET_ITEM(result, 1)); + } else { + result = PyTuple_New(2); + if (result == NULL) + return NULL; + } + di->len--; + key = ep[i].me_key; + value = ep[i].me_value; + Py_INCREF(key); + Py_INCREF(value); + PyTuple_SET_ITEM(result, 0, key); + PyTuple_SET_ITEM(result, 1, value); + return result; fail: - Py_DECREF(d); - di->di_dict = NULL; - return NULL; + Py_DECREF(d); + di->di_dict = NULL; + return NULL; } PyTypeObject PyDictIterItem_Type = { - PyVarObject_HEAD_INIT(&PyType_Type, 0) - "dict_itemiterator", /* tp_name */ - sizeof(dictiterobject), /* tp_basicsize */ - 0, /* tp_itemsize */ - /* methods */ - (destructor)dictiter_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)dictiter_traverse, /* tp_traverse */ - 0, /* tp_clear */ - 0, /* tp_richcompare */ - 0, /* tp_weaklistoffset */ - PyObject_SelfIter, /* tp_iter */ - (iternextfunc)dictiter_iternextitem, /* tp_iternext */ - dictiter_methods, /* tp_methods */ - 0, + PyVarObject_HEAD_INIT(&PyType_Type, 0) + "dict_itemiterator", /* tp_name */ + sizeof(dictiterobject), /* tp_basicsize */ + 0, /* tp_itemsize */ + /* methods */ + (destructor)dictiter_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)dictiter_traverse, /* tp_traverse */ + 0, /* tp_clear */ + 0, /* tp_richcompare */ + 0, /* tp_weaklistoffset */ + PyObject_SelfIter, /* tp_iter */ + (iternextfunc)dictiter_iternextitem, /* tp_iternext */ + dictiter_methods, /* tp_methods */ + 0, }; @@ -2522,56 +2522,56 @@ /* The instance lay-out is the same for all three; but the type differs. */ typedef struct { - PyObject_HEAD - PyDictObject *dv_dict; + PyObject_HEAD + PyDictObject *dv_dict; } dictviewobject; static void dictview_dealloc(dictviewobject *dv) { - Py_XDECREF(dv->dv_dict); - PyObject_GC_Del(dv); + Py_XDECREF(dv->dv_dict); + PyObject_GC_Del(dv); } static int dictview_traverse(dictviewobject *dv, visitproc visit, void *arg) { - Py_VISIT(dv->dv_dict); - return 0; + Py_VISIT(dv->dv_dict); + return 0; } static Py_ssize_t dictview_len(dictviewobject *dv) { - Py_ssize_t len = 0; - if (dv->dv_dict != NULL) - len = dv->dv_dict->ma_used; - return len; + Py_ssize_t len = 0; + if (dv->dv_dict != NULL) + len = dv->dv_dict->ma_used; + return len; } static PyObject * dictview_new(PyObject *dict, PyTypeObject *type) { - dictviewobject *dv; - if (dict == NULL) { - PyErr_BadInternalCall(); - return NULL; - } - if (!PyDict_Check(dict)) { - /* XXX Get rid of this restriction later */ - PyErr_Format(PyExc_TypeError, - "%s() requires a dict argument, not '%s'", - type->tp_name, dict->ob_type->tp_name); - return NULL; - } - dv = PyObject_GC_New(dictviewobject, type); - if (dv == NULL) - return NULL; - Py_INCREF(dict); - dv->dv_dict = (PyDictObject *)dict; - _PyObject_GC_TRACK(dv); - return (PyObject *)dv; + dictviewobject *dv; + if (dict == NULL) { + PyErr_BadInternalCall(); + return NULL; + } + if (!PyDict_Check(dict)) { + /* XXX Get rid of this restriction later */ + PyErr_Format(PyExc_TypeError, + "%s() requires a dict argument, not '%s'", + type->tp_name, dict->ob_type->tp_name); + return NULL; + } + dv = PyObject_GC_New(dictviewobject, type); + if (dv == NULL) + return NULL; + Py_INCREF(dict); + dv->dv_dict = (PyDictObject *)dict; + _PyObject_GC_TRACK(dv); + return (PyObject *)dv; } /* TODO(guido): The views objects are not complete: @@ -2587,102 +2587,102 @@ static int all_contained_in(PyObject *self, PyObject *other) { - PyObject *iter = PyObject_GetIter(self); - int ok = 1; + PyObject *iter = PyObject_GetIter(self); + int ok = 1; - if (iter == NULL) - return -1; - for (;;) { - PyObject *next = PyIter_Next(iter); - if (next == NULL) { - if (PyErr_Occurred()) - ok = -1; - break; - } - ok = PySequence_Contains(other, next); - Py_DECREF(next); - if (ok <= 0) - break; - } - Py_DECREF(iter); - return ok; + if (iter == NULL) + return -1; + for (;;) { + PyObject *next = PyIter_Next(iter); + if (next == NULL) { + if (PyErr_Occurred()) + ok = -1; + break; + } + ok = PySequence_Contains(other, next); + Py_DECREF(next); + if (ok <= 0) + break; + } + Py_DECREF(iter); + return ok; } static PyObject * dictview_richcompare(PyObject *self, PyObject *other, int op) { - Py_ssize_t len_self, len_other; - int ok; - PyObject *result; - - assert(self != NULL); - assert(PyDictViewSet_Check(self)); - assert(other != NULL); - - if (!PyAnySet_Check(other) && !PyDictViewSet_Check(other)) { - Py_INCREF(Py_NotImplemented); - return Py_NotImplemented; - } - - len_self = PyObject_Size(self); - if (len_self < 0) - return NULL; - len_other = PyObject_Size(other); - if (len_other < 0) - return NULL; - - ok = 0; - switch(op) { - - case Py_NE: - case Py_EQ: - if (len_self == len_other) - ok = all_contained_in(self, other); - if (op == Py_NE && ok >= 0) - ok = !ok; - break; - - case Py_LT: - if (len_self < len_other) - ok = all_contained_in(self, other); - break; - - case Py_LE: - if (len_self <= len_other) - ok = all_contained_in(self, other); - break; - - case Py_GT: - if (len_self > len_other) - ok = all_contained_in(other, self); - break; - - case Py_GE: - if (len_self >= len_other) - ok = all_contained_in(other, self); - break; - - } - if (ok < 0) - return NULL; - result = ok ? Py_True : Py_False; - Py_INCREF(result); - return result; + Py_ssize_t len_self, len_other; + int ok; + PyObject *result; + + assert(self != NULL); + assert(PyDictViewSet_Check(self)); + assert(other != NULL); + + if (!PyAnySet_Check(other) && !PyDictViewSet_Check(other)) { + Py_INCREF(Py_NotImplemented); + return Py_NotImplemented; + } + + len_self = PyObject_Size(self); + if (len_self < 0) + return NULL; + len_other = PyObject_Size(other); + if (len_other < 0) + return NULL; + + ok = 0; + switch(op) { + + case Py_NE: + case Py_EQ: + if (len_self == len_other) + ok = all_contained_in(self, other); + if (op == Py_NE && ok >= 0) + ok = !ok; + break; + + case Py_LT: + if (len_self < len_other) + ok = all_contained_in(self, other); + break; + + case Py_LE: + if (len_self <= len_other) + ok = all_contained_in(self, other); + break; + + case Py_GT: + if (len_self > len_other) + ok = all_contained_in(other, self); + break; + + case Py_GE: + if (len_self >= len_other) + ok = all_contained_in(other, self); + break; + + } + if (ok < 0) + return NULL; + result = ok ? Py_True : Py_False; + Py_INCREF(result); + return result; } static PyObject * dictview_repr(dictviewobject *dv) { - PyObject *seq; - PyObject *result; - - seq = PySequence_List((PyObject *)dv); - if (seq == NULL) - return NULL; - - result = PyUnicode_FromFormat("%s(%R)", Py_TYPE(dv)->tp_name, seq); - Py_DECREF(seq); - return result; + PyObject *seq; + PyObject *result; + + seq = PySequence_List((PyObject *)dv); + if (seq == NULL) + return NULL; + + result = PyUnicode_FromFormat("%s(%R)", Py_TYPE(dv)->tp_name, seq); + Py_DECREF(seq); + return result; } /*** dict_keys ***/ @@ -2690,164 +2690,164 @@ static PyObject * dictkeys_iter(dictviewobject *dv) { - if (dv->dv_dict == NULL) { - Py_RETURN_NONE; - } - return dictiter_new(dv->dv_dict, &PyDictIterKey_Type); + if (dv->dv_dict == NULL) { + Py_RETURN_NONE; + } + return dictiter_new(dv->dv_dict, &PyDictIterKey_Type); } static int dictkeys_contains(dictviewobject *dv, PyObject *obj) { - if (dv->dv_dict == NULL) - return 0; - return PyDict_Contains((PyObject *)dv->dv_dict, obj); + if (dv->dv_dict == NULL) + return 0; + return PyDict_Contains((PyObject *)dv->dv_dict, obj); } static PySequenceMethods dictkeys_as_sequence = { - (lenfunc)dictview_len, /* sq_length */ - 0, /* sq_concat */ - 0, /* sq_repeat */ - 0, /* sq_item */ - 0, /* sq_slice */ - 0, /* sq_ass_item */ - 0, /* sq_ass_slice */ - (objobjproc)dictkeys_contains, /* sq_contains */ + (lenfunc)dictview_len, /* sq_length */ + 0, /* sq_concat */ + 0, /* sq_repeat */ + 0, /* sq_item */ + 0, /* sq_slice */ + 0, /* sq_ass_item */ + 0, /* sq_ass_slice */ + (objobjproc)dictkeys_contains, /* sq_contains */ }; static PyObject* dictviews_sub(PyObject* self, PyObject *other) { - PyObject *result = PySet_New(self); - PyObject *tmp; - if (result == NULL) - return NULL; - - tmp = PyObject_CallMethod(result, "difference_update", "O", other); - if (tmp == NULL) { - Py_DECREF(result); - return NULL; - } + PyObject *result = PySet_New(self); + PyObject *tmp; + if (result == NULL) + return NULL; + + tmp = PyObject_CallMethod(result, "difference_update", "O", other); + if (tmp == NULL) { + Py_DECREF(result); + return NULL; + } - Py_DECREF(tmp); - return result; + Py_DECREF(tmp); + return result; } static PyObject* dictviews_and(PyObject* self, PyObject *other) { - PyObject *result = PySet_New(self); - PyObject *tmp; - if (result == NULL) - return NULL; - - tmp = PyObject_CallMethod(result, "intersection_update", "O", other); - if (tmp == NULL) { - Py_DECREF(result); - return NULL; - } + PyObject *result = PySet_New(self); + PyObject *tmp; + if (result == NULL) + return NULL; + + tmp = PyObject_CallMethod(result, "intersection_update", "O", other); + if (tmp == NULL) { + Py_DECREF(result); + return NULL; + } - Py_DECREF(tmp); - return result; + Py_DECREF(tmp); + return result; } static PyObject* dictviews_or(PyObject* self, PyObject *other) { - PyObject *result = PySet_New(self); - PyObject *tmp; - if (result == NULL) - return NULL; - - tmp = PyObject_CallMethod(result, "update", "O", other); - if (tmp == NULL) { - Py_DECREF(result); - return NULL; - } + PyObject *result = PySet_New(self); + PyObject *tmp; + if (result == NULL) + return NULL; + + tmp = PyObject_CallMethod(result, "update", "O", other); + if (tmp == NULL) { + Py_DECREF(result); + return NULL; + } - Py_DECREF(tmp); - return result; + Py_DECREF(tmp); + return result; } static PyObject* dictviews_xor(PyObject* self, PyObject *other) { - PyObject *result = PySet_New(self); - PyObject *tmp; - if (result == NULL) - return NULL; - - tmp = PyObject_CallMethod(result, "symmetric_difference_update", "O", - other); - if (tmp == NULL) { - Py_DECREF(result); - return NULL; - } + PyObject *result = PySet_New(self); + PyObject *tmp; + if (result == NULL) + return NULL; + + tmp = PyObject_CallMethod(result, "symmetric_difference_update", "O", + other); + if (tmp == NULL) { + Py_DECREF(result); + return NULL; + } - Py_DECREF(tmp); - return result; + Py_DECREF(tmp); + return result; } static PyNumberMethods dictviews_as_number = { - 0, /*nb_add*/ - (binaryfunc)dictviews_sub, /*nb_subtract*/ - 0, /*nb_multiply*/ - 0, /*nb_remainder*/ - 0, /*nb_divmod*/ - 0, /*nb_power*/ - 0, /*nb_negative*/ - 0, /*nb_positive*/ - 0, /*nb_absolute*/ - 0, /*nb_bool*/ - 0, /*nb_invert*/ - 0, /*nb_lshift*/ - 0, /*nb_rshift*/ - (binaryfunc)dictviews_and, /*nb_and*/ - (binaryfunc)dictviews_xor, /*nb_xor*/ - (binaryfunc)dictviews_or, /*nb_or*/ + 0, /*nb_add*/ + (binaryfunc)dictviews_sub, /*nb_subtract*/ + 0, /*nb_multiply*/ + 0, /*nb_remainder*/ + 0, /*nb_divmod*/ + 0, /*nb_power*/ + 0, /*nb_negative*/ + 0, /*nb_positive*/ + 0, /*nb_absolute*/ + 0, /*nb_bool*/ + 0, /*nb_invert*/ + 0, /*nb_lshift*/ + 0, /*nb_rshift*/ + (binaryfunc)dictviews_and, /*nb_and*/ + (binaryfunc)dictviews_xor, /*nb_xor*/ + (binaryfunc)dictviews_or, /*nb_or*/ }; static PyMethodDef dictkeys_methods[] = { - {NULL, NULL} /* sentinel */ + {NULL, NULL} /* sentinel */ }; PyTypeObject PyDictKeys_Type = { - PyVarObject_HEAD_INIT(&PyType_Type, 0) - "dict_keys", /* tp_name */ - sizeof(dictviewobject), /* tp_basicsize */ - 0, /* tp_itemsize */ - /* methods */ - (destructor)dictview_dealloc, /* tp_dealloc */ - 0, /* tp_print */ - 0, /* tp_getattr */ - 0, /* tp_setattr */ - 0, /* tp_reserved */ - (reprfunc)dictview_repr, /* tp_repr */ - &dictviews_as_number, /* tp_as_number */ - &dictkeys_as_sequence, /* 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)dictview_traverse, /* tp_traverse */ - 0, /* tp_clear */ - dictview_richcompare, /* tp_richcompare */ - 0, /* tp_weaklistoffset */ - (getiterfunc)dictkeys_iter, /* tp_iter */ - 0, /* tp_iternext */ - dictkeys_methods, /* tp_methods */ - 0, + PyVarObject_HEAD_INIT(&PyType_Type, 0) + "dict_keys", /* tp_name */ + sizeof(dictviewobject), /* tp_basicsize */ + 0, /* tp_itemsize */ + /* methods */ + (destructor)dictview_dealloc, /* tp_dealloc */ + 0, /* tp_print */ + 0, /* tp_getattr */ + 0, /* tp_setattr */ + 0, /* tp_reserved */ + (reprfunc)dictview_repr, /* tp_repr */ + &dictviews_as_number, /* tp_as_number */ + &dictkeys_as_sequence, /* 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)dictview_traverse, /* tp_traverse */ + 0, /* tp_clear */ + dictview_richcompare, /* tp_richcompare */ + 0, /* tp_weaklistoffset */ + (getiterfunc)dictkeys_iter, /* tp_iter */ + 0, /* tp_iternext */ + dictkeys_methods, /* tp_methods */ + 0, }; static PyObject * dictkeys_new(PyObject *dict) { - return dictview_new(dict, &PyDictKeys_Type); + return dictview_new(dict, &PyDictKeys_Type); } /*** dict_items ***/ @@ -2855,83 +2855,83 @@ static PyObject * dictitems_iter(dictviewobject *dv) { - if (dv->dv_dict == NULL) { - Py_RETURN_NONE; - } - return dictiter_new(dv->dv_dict, &PyDictIterItem_Type); + if (dv->dv_dict == NULL) { + Py_RETURN_NONE; + } + return dictiter_new(dv->dv_dict, &PyDictIterItem_Type); } static int dictitems_contains(dictviewobject *dv, PyObject *obj) { - PyObject *key, *value, *found; - if (dv->dv_dict == NULL) - return 0; - if (!PyTuple_Check(obj) || PyTuple_GET_SIZE(obj) != 2) - return 0; - key = PyTuple_GET_ITEM(obj, 0); - value = PyTuple_GET_ITEM(obj, 1); - found = PyDict_GetItem((PyObject *)dv->dv_dict, key); - if (found == NULL) { - if (PyErr_Occurred()) - return -1; - return 0; - } - return PyObject_RichCompareBool(value, found, Py_EQ); + PyObject *key, *value, *found; + if (dv->dv_dict == NULL) + return 0; + if (!PyTuple_Check(obj) || PyTuple_GET_SIZE(obj) != 2) + return 0; + key = PyTuple_GET_ITEM(obj, 0); + value = PyTuple_GET_ITEM(obj, 1); + found = PyDict_GetItem((PyObject *)dv->dv_dict, key); + if (found == NULL) { + if (PyErr_Occurred()) + return -1; + return 0; + } + return PyObject_RichCompareBool(value, found, Py_EQ); } static PySequenceMethods dictitems_as_sequence = { - (lenfunc)dictview_len, /* sq_length */ - 0, /* sq_concat */ - 0, /* sq_repeat */ - 0, /* sq_item */ - 0, /* sq_slice */ - 0, /* sq_ass_item */ - 0, /* sq_ass_slice */ - (objobjproc)dictitems_contains, /* sq_contains */ + (lenfunc)dictview_len, /* sq_length */ + 0, /* sq_concat */ + 0, /* sq_repeat */ + 0, /* sq_item */ + 0, /* sq_slice */ + 0, /* sq_ass_item */ + 0, /* sq_ass_slice */ + (objobjproc)dictitems_contains, /* sq_contains */ }; static PyMethodDef dictitems_methods[] = { - {NULL, NULL} /* sentinel */ + {NULL, NULL} /* sentinel */ }; PyTypeObject PyDictItems_Type = { - PyVarObject_HEAD_INIT(&PyType_Type, 0) - "dict_items", /* tp_name */ - sizeof(dictviewobject), /* tp_basicsize */ - 0, /* tp_itemsize */ - /* methods */ - (destructor)dictview_dealloc, /* tp_dealloc */ - 0, /* tp_print */ - 0, /* tp_getattr */ - 0, /* tp_setattr */ - 0, /* tp_reserved */ - (reprfunc)dictview_repr, /* tp_repr */ - &dictviews_as_number, /* tp_as_number */ - &dictitems_as_sequence, /* 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)dictview_traverse, /* tp_traverse */ - 0, /* tp_clear */ - dictview_richcompare, /* tp_richcompare */ - 0, /* tp_weaklistoffset */ - (getiterfunc)dictitems_iter, /* tp_iter */ - 0, /* tp_iternext */ - dictitems_methods, /* tp_methods */ - 0, + PyVarObject_HEAD_INIT(&PyType_Type, 0) + "dict_items", /* tp_name */ + sizeof(dictviewobject), /* tp_basicsize */ + 0, /* tp_itemsize */ + /* methods */ + (destructor)dictview_dealloc, /* tp_dealloc */ + 0, /* tp_print */ + 0, /* tp_getattr */ + 0, /* tp_setattr */ + 0, /* tp_reserved */ + (reprfunc)dictview_repr, /* tp_repr */ + &dictviews_as_number, /* tp_as_number */ + &dictitems_as_sequence, /* 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)dictview_traverse, /* tp_traverse */ + 0, /* tp_clear */ + dictview_richcompare, /* tp_richcompare */ + 0, /* tp_weaklistoffset */ + (getiterfunc)dictitems_iter, /* tp_iter */ + 0, /* tp_iternext */ + dictitems_methods, /* tp_methods */ + 0, }; static PyObject * dictitems_new(PyObject *dict) { - return dictview_new(dict, &PyDictItems_Type); + return dictview_new(dict, &PyDictItems_Type); } /*** dict_values ***/ @@ -2939,62 +2939,62 @@ static PyObject * dictvalues_iter(dictviewobject *dv) { - if (dv->dv_dict == NULL) { - Py_RETURN_NONE; - } - return dictiter_new(dv->dv_dict, &PyDictIterValue_Type); + if (dv->dv_dict == NULL) { + Py_RETURN_NONE; + } + return dictiter_new(dv->dv_dict, &PyDictIterValue_Type); } static PySequenceMethods dictvalues_as_sequence = { - (lenfunc)dictview_len, /* sq_length */ - 0, /* sq_concat */ - 0, /* sq_repeat */ - 0, /* sq_item */ - 0, /* sq_slice */ - 0, /* sq_ass_item */ - 0, /* sq_ass_slice */ - (objobjproc)0, /* sq_contains */ + (lenfunc)dictview_len, /* sq_length */ + 0, /* sq_concat */ + 0, /* sq_repeat */ + 0, /* sq_item */ + 0, /* sq_slice */ + 0, /* sq_ass_item */ + 0, /* sq_ass_slice */ + (objobjproc)0, /* sq_contains */ }; static PyMethodDef dictvalues_methods[] = { - {NULL, NULL} /* sentinel */ + {NULL, NULL} /* sentinel */ }; PyTypeObject PyDictValues_Type = { - PyVarObject_HEAD_INIT(&PyType_Type, 0) - "dict_values", /* tp_name */ - sizeof(dictviewobject), /* tp_basicsize */ - 0, /* tp_itemsize */ - /* methods */ - (destructor)dictview_dealloc, /* tp_dealloc */ - 0, /* tp_print */ - 0, /* tp_getattr */ - 0, /* tp_setattr */ - 0, /* tp_reserved */ - (reprfunc)dictview_repr, /* tp_repr */ - 0, /* tp_as_number */ - &dictvalues_as_sequence, /* 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)dictview_traverse, /* tp_traverse */ - 0, /* tp_clear */ - 0, /* tp_richcompare */ - 0, /* tp_weaklistoffset */ - (getiterfunc)dictvalues_iter, /* tp_iter */ - 0, /* tp_iternext */ - dictvalues_methods, /* tp_methods */ - 0, + PyVarObject_HEAD_INIT(&PyType_Type, 0) + "dict_values", /* tp_name */ + sizeof(dictviewobject), /* tp_basicsize */ + 0, /* tp_itemsize */ + /* methods */ + (destructor)dictview_dealloc, /* tp_dealloc */ + 0, /* tp_print */ + 0, /* tp_getattr */ + 0, /* tp_setattr */ + 0, /* tp_reserved */ + (reprfunc)dictview_repr, /* tp_repr */ + 0, /* tp_as_number */ + &dictvalues_as_sequence, /* 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)dictview_traverse, /* tp_traverse */ + 0, /* tp_clear */ + 0, /* tp_richcompare */ + 0, /* tp_weaklistoffset */ + (getiterfunc)dictvalues_iter, /* tp_iter */ + 0, /* tp_iternext */ + dictvalues_methods, /* tp_methods */ + 0, }; static PyObject * dictvalues_new(PyObject *dict) { - return dictview_new(dict, &PyDictValues_Type); + return dictview_new(dict, &PyDictValues_Type); } Modified: python/branches/py3k-jit/Objects/enumobject.c ============================================================================== --- python/branches/py3k-jit/Objects/enumobject.c (original) +++ python/branches/py3k-jit/Objects/enumobject.c Mon May 10 23:55:43 2010 @@ -3,159 +3,159 @@ #include "Python.h" typedef struct { - PyObject_HEAD - Py_ssize_t en_index; /* current index of enumeration */ - PyObject* en_sit; /* secondary iterator of enumeration */ - PyObject* en_result; /* result tuple */ - PyObject* en_longindex; /* index for sequences >= PY_SSIZE_T_MAX */ + PyObject_HEAD + Py_ssize_t en_index; /* current index of enumeration */ + PyObject* en_sit; /* secondary iterator of enumeration */ + PyObject* en_result; /* result tuple */ + PyObject* en_longindex; /* index for sequences >= PY_SSIZE_T_MAX */ } enumobject; static PyObject * enum_new(PyTypeObject *type, PyObject *args, PyObject *kwds) { - enumobject *en; - PyObject *seq = NULL; - PyObject *start = NULL; - static char *kwlist[] = {"iterable", "start", 0}; - - if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|O:enumerate", kwlist, - &seq, &start)) - return NULL; - - en = (enumobject *)type->tp_alloc(type, 0); - if (en == NULL) - return NULL; - if (start != NULL) { - start = PyNumber_Index(start); - if (start == NULL) { - Py_DECREF(en); - return NULL; - } - assert(PyLong_Check(start)); - en->en_index = PyLong_AsSsize_t(start); - if (en->en_index == -1 && PyErr_Occurred()) { - PyErr_Clear(); - en->en_index = PY_SSIZE_T_MAX; - en->en_longindex = start; - } else { - en->en_longindex = NULL; - Py_DECREF(start); - } - } else { - en->en_index = 0; - en->en_longindex = NULL; - } - en->en_sit = PyObject_GetIter(seq); - if (en->en_sit == NULL) { - Py_DECREF(en); - return NULL; - } - en->en_result = PyTuple_Pack(2, Py_None, Py_None); - if (en->en_result == NULL) { - Py_DECREF(en); - return NULL; - } - return (PyObject *)en; + enumobject *en; + PyObject *seq = NULL; + PyObject *start = NULL; + static char *kwlist[] = {"iterable", "start", 0}; + + if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|O:enumerate", kwlist, + &seq, &start)) + return NULL; + + en = (enumobject *)type->tp_alloc(type, 0); + if (en == NULL) + return NULL; + if (start != NULL) { + start = PyNumber_Index(start); + if (start == NULL) { + Py_DECREF(en); + return NULL; + } + assert(PyLong_Check(start)); + en->en_index = PyLong_AsSsize_t(start); + if (en->en_index == -1 && PyErr_Occurred()) { + PyErr_Clear(); + en->en_index = PY_SSIZE_T_MAX; + en->en_longindex = start; + } else { + en->en_longindex = NULL; + Py_DECREF(start); + } + } else { + en->en_index = 0; + en->en_longindex = NULL; + } + en->en_sit = PyObject_GetIter(seq); + if (en->en_sit == NULL) { + Py_DECREF(en); + return NULL; + } + en->en_result = PyTuple_Pack(2, Py_None, Py_None); + if (en->en_result == NULL) { + Py_DECREF(en); + return NULL; + } + return (PyObject *)en; } static void enum_dealloc(enumobject *en) { - PyObject_GC_UnTrack(en); - Py_XDECREF(en->en_sit); - Py_XDECREF(en->en_result); - Py_XDECREF(en->en_longindex); - Py_TYPE(en)->tp_free(en); + PyObject_GC_UnTrack(en); + Py_XDECREF(en->en_sit); + Py_XDECREF(en->en_result); + Py_XDECREF(en->en_longindex); + Py_TYPE(en)->tp_free(en); } static int enum_traverse(enumobject *en, visitproc visit, void *arg) { - Py_VISIT(en->en_sit); - Py_VISIT(en->en_result); - Py_VISIT(en->en_longindex); - return 0; + Py_VISIT(en->en_sit); + Py_VISIT(en->en_result); + Py_VISIT(en->en_longindex); + return 0; } static PyObject * enum_next_long(enumobject *en, PyObject* next_item) { - static PyObject *one = NULL; - PyObject *result = en->en_result; - PyObject *next_index; - PyObject *stepped_up; - - if (en->en_longindex == NULL) { - en->en_longindex = PyLong_FromSsize_t(PY_SSIZE_T_MAX); - if (en->en_longindex == NULL) - return NULL; - } - if (one == NULL) { - one = PyLong_FromLong(1); - if (one == NULL) - return NULL; - } - next_index = en->en_longindex; - assert(next_index != NULL); - stepped_up = PyNumber_Add(next_index, one); - if (stepped_up == NULL) - return NULL; - en->en_longindex = stepped_up; - - if (result->ob_refcnt == 1) { - Py_INCREF(result); - Py_DECREF(PyTuple_GET_ITEM(result, 0)); - Py_DECREF(PyTuple_GET_ITEM(result, 1)); - } else { - result = PyTuple_New(2); - if (result == NULL) { - Py_DECREF(next_index); - Py_DECREF(next_item); - return NULL; - } - } - PyTuple_SET_ITEM(result, 0, next_index); - PyTuple_SET_ITEM(result, 1, next_item); - return result; + static PyObject *one = NULL; + PyObject *result = en->en_result; + PyObject *next_index; + PyObject *stepped_up; + + if (en->en_longindex == NULL) { + en->en_longindex = PyLong_FromSsize_t(PY_SSIZE_T_MAX); + if (en->en_longindex == NULL) + return NULL; + } + if (one == NULL) { + one = PyLong_FromLong(1); + if (one == NULL) + return NULL; + } + next_index = en->en_longindex; + assert(next_index != NULL); + stepped_up = PyNumber_Add(next_index, one); + if (stepped_up == NULL) + return NULL; + en->en_longindex = stepped_up; + + if (result->ob_refcnt == 1) { + Py_INCREF(result); + Py_DECREF(PyTuple_GET_ITEM(result, 0)); + Py_DECREF(PyTuple_GET_ITEM(result, 1)); + } else { + result = PyTuple_New(2); + if (result == NULL) { + Py_DECREF(next_index); + Py_DECREF(next_item); + return NULL; + } + } + PyTuple_SET_ITEM(result, 0, next_index); + PyTuple_SET_ITEM(result, 1, next_item); + return result; } static PyObject * enum_next(enumobject *en) { - PyObject *next_index; - PyObject *next_item; - PyObject *result = en->en_result; - PyObject *it = en->en_sit; - - next_item = (*Py_TYPE(it)->tp_iternext)(it); - if (next_item == NULL) - return NULL; - - if (en->en_index == PY_SSIZE_T_MAX) - return enum_next_long(en, next_item); - - next_index = PyLong_FromSsize_t(en->en_index); - if (next_index == NULL) { - Py_DECREF(next_item); - return NULL; - } - en->en_index++; - - if (result->ob_refcnt == 1) { - Py_INCREF(result); - Py_DECREF(PyTuple_GET_ITEM(result, 0)); - Py_DECREF(PyTuple_GET_ITEM(result, 1)); - } else { - result = PyTuple_New(2); - if (result == NULL) { - Py_DECREF(next_index); - Py_DECREF(next_item); - return NULL; - } - } - PyTuple_SET_ITEM(result, 0, next_index); - PyTuple_SET_ITEM(result, 1, next_item); - return result; + PyObject *next_index; + PyObject *next_item; + PyObject *result = en->en_result; + PyObject *it = en->en_sit; + + next_item = (*Py_TYPE(it)->tp_iternext)(it); + if (next_item == NULL) + return NULL; + + if (en->en_index == PY_SSIZE_T_MAX) + return enum_next_long(en, next_item); + + next_index = PyLong_FromSsize_t(en->en_index); + if (next_index == NULL) { + Py_DECREF(next_item); + return NULL; + } + en->en_index++; + + if (result->ob_refcnt == 1) { + Py_INCREF(result); + Py_DECREF(PyTuple_GET_ITEM(result, 0)); + Py_DECREF(PyTuple_GET_ITEM(result, 1)); + } else { + result = PyTuple_New(2); + if (result == NULL) { + Py_DECREF(next_index); + Py_DECREF(next_item); + return NULL; + } + } + PyTuple_SET_ITEM(result, 0, next_index); + PyTuple_SET_ITEM(result, 1, next_item); + return result; } PyDoc_STRVAR(enum_doc, @@ -167,134 +167,134 @@ "for obtaining an indexed list: (0, seq[0]), (1, seq[1]), (2, seq[2]), ..."); PyTypeObject PyEnum_Type = { - PyVarObject_HEAD_INIT(&PyType_Type, 0) - "enumerate", /* tp_name */ - sizeof(enumobject), /* tp_basicsize */ - 0, /* tp_itemsize */ - /* methods */ - (destructor)enum_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 | - Py_TPFLAGS_BASETYPE, /* tp_flags */ - enum_doc, /* tp_doc */ - (traverseproc)enum_traverse, /* tp_traverse */ - 0, /* tp_clear */ - 0, /* tp_richcompare */ - 0, /* tp_weaklistoffset */ - PyObject_SelfIter, /* tp_iter */ - (iternextfunc)enum_next, /* tp_iternext */ - 0, /* tp_methods */ - 0, /* tp_members */ - 0, /* tp_getset */ - 0, /* tp_base */ - 0, /* tp_dict */ - 0, /* tp_descr_get */ - 0, /* tp_descr_set */ - 0, /* tp_dictoffset */ - 0, /* tp_init */ - PyType_GenericAlloc, /* tp_alloc */ - enum_new, /* tp_new */ - PyObject_GC_Del, /* tp_free */ + PyVarObject_HEAD_INIT(&PyType_Type, 0) + "enumerate", /* tp_name */ + sizeof(enumobject), /* tp_basicsize */ + 0, /* tp_itemsize */ + /* methods */ + (destructor)enum_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 | + Py_TPFLAGS_BASETYPE, /* tp_flags */ + enum_doc, /* tp_doc */ + (traverseproc)enum_traverse, /* tp_traverse */ + 0, /* tp_clear */ + 0, /* tp_richcompare */ + 0, /* tp_weaklistoffset */ + PyObject_SelfIter, /* tp_iter */ + (iternextfunc)enum_next, /* tp_iternext */ + 0, /* tp_methods */ + 0, /* tp_members */ + 0, /* tp_getset */ + 0, /* tp_base */ + 0, /* tp_dict */ + 0, /* tp_descr_get */ + 0, /* tp_descr_set */ + 0, /* tp_dictoffset */ + 0, /* tp_init */ + PyType_GenericAlloc, /* tp_alloc */ + enum_new, /* tp_new */ + PyObject_GC_Del, /* tp_free */ }; /* Reversed Object ***************************************************************/ typedef struct { - PyObject_HEAD - Py_ssize_t index; - PyObject* seq; + PyObject_HEAD + Py_ssize_t index; + PyObject* seq; } reversedobject; static PyObject * reversed_new(PyTypeObject *type, PyObject *args, PyObject *kwds) { - Py_ssize_t n; - PyObject *seq, *reversed_meth; - static PyObject *reversed_cache = NULL; - reversedobject *ro; - - if (type == &PyReversed_Type && !_PyArg_NoKeywords("reversed()", kwds)) - return NULL; - - if (!PyArg_UnpackTuple(args, "reversed", 1, 1, &seq) ) - return NULL; - - reversed_meth = _PyObject_LookupSpecial(seq, "__reversed__", &reversed_cache); - if (reversed_meth != NULL) { - PyObject *res = PyObject_CallFunctionObjArgs(reversed_meth, NULL); - Py_DECREF(reversed_meth); - return res; - } - else if (PyErr_Occurred()) - return NULL; - - if (!PySequence_Check(seq)) { - PyErr_SetString(PyExc_TypeError, - "argument to reversed() must be a sequence"); - return NULL; - } - - n = PySequence_Size(seq); - if (n == -1) - return NULL; - - ro = (reversedobject *)type->tp_alloc(type, 0); - if (ro == NULL) - return NULL; - - ro->index = n-1; - Py_INCREF(seq); - ro->seq = seq; - return (PyObject *)ro; + Py_ssize_t n; + PyObject *seq, *reversed_meth; + static PyObject *reversed_cache = NULL; + reversedobject *ro; + + if (type == &PyReversed_Type && !_PyArg_NoKeywords("reversed()", kwds)) + return NULL; + + if (!PyArg_UnpackTuple(args, "reversed", 1, 1, &seq) ) + return NULL; + + reversed_meth = _PyObject_LookupSpecial(seq, "__reversed__", &reversed_cache); + if (reversed_meth != NULL) { + PyObject *res = PyObject_CallFunctionObjArgs(reversed_meth, NULL); + Py_DECREF(reversed_meth); + return res; + } + else if (PyErr_Occurred()) + return NULL; + + if (!PySequence_Check(seq)) { + PyErr_SetString(PyExc_TypeError, + "argument to reversed() must be a sequence"); + return NULL; + } + + n = PySequence_Size(seq); + if (n == -1) + return NULL; + + ro = (reversedobject *)type->tp_alloc(type, 0); + if (ro == NULL) + return NULL; + + ro->index = n-1; + Py_INCREF(seq); + ro->seq = seq; + return (PyObject *)ro; } static void reversed_dealloc(reversedobject *ro) { - PyObject_GC_UnTrack(ro); - Py_XDECREF(ro->seq); - Py_TYPE(ro)->tp_free(ro); + PyObject_GC_UnTrack(ro); + Py_XDECREF(ro->seq); + Py_TYPE(ro)->tp_free(ro); } static int reversed_traverse(reversedobject *ro, visitproc visit, void *arg) { - Py_VISIT(ro->seq); - return 0; + Py_VISIT(ro->seq); + return 0; } static PyObject * reversed_next(reversedobject *ro) { - PyObject *item; - Py_ssize_t index = ro->index; + PyObject *item; + Py_ssize_t index = ro->index; - if (index >= 0) { - item = PySequence_GetItem(ro->seq, index); - if (item != NULL) { - ro->index--; - return item; - } - if (PyErr_ExceptionMatches(PyExc_IndexError) || - PyErr_ExceptionMatches(PyExc_StopIteration)) - PyErr_Clear(); - } - ro->index = -1; - Py_CLEAR(ro->seq); - return NULL; + if (index >= 0) { + item = PySequence_GetItem(ro->seq, index); + if (item != NULL) { + ro->index--; + return item; + } + if (PyErr_ExceptionMatches(PyExc_IndexError) || + PyErr_ExceptionMatches(PyExc_StopIteration)) + PyErr_Clear(); + } + ro->index = -1; + Py_CLEAR(ro->seq); + return NULL; } PyDoc_STRVAR(reversed_doc, @@ -305,64 +305,64 @@ static PyObject * reversed_len(reversedobject *ro) { - Py_ssize_t position, seqsize; + Py_ssize_t position, seqsize; - if (ro->seq == NULL) - return PyLong_FromLong(0); - seqsize = PySequence_Size(ro->seq); - if (seqsize == -1) - return NULL; - position = ro->index + 1; - return PyLong_FromSsize_t((seqsize < position) ? 0 : position); + if (ro->seq == NULL) + return PyLong_FromLong(0); + seqsize = PySequence_Size(ro->seq); + if (seqsize == -1) + return NULL; + position = ro->index + 1; + return PyLong_FromSsize_t((seqsize < position) ? 0 : position); } PyDoc_STRVAR(length_hint_doc, "Private method returning an estimate of len(list(it))."); static PyMethodDef reversediter_methods[] = { - {"__length_hint__", (PyCFunction)reversed_len, METH_NOARGS, length_hint_doc}, - {NULL, NULL} /* sentinel */ + {"__length_hint__", (PyCFunction)reversed_len, METH_NOARGS, length_hint_doc}, + {NULL, NULL} /* sentinel */ }; PyTypeObject PyReversed_Type = { - PyVarObject_HEAD_INIT(&PyType_Type, 0) - "reversed", /* tp_name */ - sizeof(reversedobject), /* tp_basicsize */ - 0, /* tp_itemsize */ - /* methods */ - (destructor)reversed_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 | - Py_TPFLAGS_BASETYPE, /* tp_flags */ - reversed_doc, /* tp_doc */ - (traverseproc)reversed_traverse,/* tp_traverse */ - 0, /* tp_clear */ - 0, /* tp_richcompare */ - 0, /* tp_weaklistoffset */ - PyObject_SelfIter, /* tp_iter */ - (iternextfunc)reversed_next, /* tp_iternext */ - reversediter_methods, /* tp_methods */ - 0, /* tp_members */ - 0, /* tp_getset */ - 0, /* tp_base */ - 0, /* tp_dict */ - 0, /* tp_descr_get */ - 0, /* tp_descr_set */ - 0, /* tp_dictoffset */ - 0, /* tp_init */ - PyType_GenericAlloc, /* tp_alloc */ - reversed_new, /* tp_new */ - PyObject_GC_Del, /* tp_free */ + PyVarObject_HEAD_INIT(&PyType_Type, 0) + "reversed", /* tp_name */ + sizeof(reversedobject), /* tp_basicsize */ + 0, /* tp_itemsize */ + /* methods */ + (destructor)reversed_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 | + Py_TPFLAGS_BASETYPE, /* tp_flags */ + reversed_doc, /* tp_doc */ + (traverseproc)reversed_traverse,/* tp_traverse */ + 0, /* tp_clear */ + 0, /* tp_richcompare */ + 0, /* tp_weaklistoffset */ + PyObject_SelfIter, /* tp_iter */ + (iternextfunc)reversed_next, /* tp_iternext */ + reversediter_methods, /* tp_methods */ + 0, /* tp_members */ + 0, /* tp_getset */ + 0, /* tp_base */ + 0, /* tp_dict */ + 0, /* tp_descr_get */ + 0, /* tp_descr_set */ + 0, /* tp_dictoffset */ + 0, /* tp_init */ + PyType_GenericAlloc, /* tp_alloc */ + reversed_new, /* tp_new */ + PyObject_GC_Del, /* tp_free */ }; Modified: python/branches/py3k-jit/Objects/exceptions.c ============================================================================== --- python/branches/py3k-jit/Objects/exceptions.c (original) +++ python/branches/py3k-jit/Objects/exceptions.c Mon May 10 23:55:43 2010 @@ -270,7 +270,7 @@ } else { /* PyException_SetContext steals this reference */ Py_INCREF(arg); - } + } PyException_SetContext(self, arg); return 0; } @@ -296,7 +296,7 @@ } else { /* PyException_SetCause steals this reference */ Py_INCREF(arg); - } + } PyException_SetCause(self, arg); return 0; } @@ -379,7 +379,7 @@ PyObject_GenericSetAttr, /*tp_setattro*/ 0, /*tp_as_buffer*/ Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC | - Py_TPFLAGS_BASE_EXC_SUBCLASS, /*tp_flags*/ + Py_TPFLAGS_BASE_EXC_SUBCLASS, /*tp_flags*/ PyDoc_STR("Common base class for all exceptions"), /* tp_doc */ (traverseproc)BaseException_traverse, /* tp_traverse */ (inquiry)BaseException_clear, /* tp_clear */ @@ -1013,7 +1013,7 @@ result = PyUnicode_FromFormat("%S (%U, line %ld)", self->msg ? self->msg : Py_None, filename, - PyLong_AsLongAndOverflow(self->lineno, &overflow)); + PyLong_AsLongAndOverflow(self->lineno, &overflow)); else if (filename) result = PyUnicode_FromFormat("%S (%U)", self->msg ? self->msg : Py_None, @@ -2011,25 +2011,25 @@ PyExc_RecursionErrorInst = BaseException_new(&_PyExc_RuntimeError, NULL, NULL); if (!PyExc_RecursionErrorInst) - Py_FatalError("Cannot pre-allocate RuntimeError instance for " - "recursion errors"); + Py_FatalError("Cannot pre-allocate RuntimeError instance for " + "recursion errors"); else { - PyBaseExceptionObject *err_inst = - (PyBaseExceptionObject *)PyExc_RecursionErrorInst; - PyObject *args_tuple; - PyObject *exc_message; - exc_message = PyUnicode_FromString("maximum recursion depth exceeded"); - if (!exc_message) - Py_FatalError("cannot allocate argument for RuntimeError " - "pre-allocation"); - args_tuple = PyTuple_Pack(1, exc_message); - if (!args_tuple) - Py_FatalError("cannot allocate tuple for RuntimeError " - "pre-allocation"); - Py_DECREF(exc_message); - if (BaseException_init(err_inst, args_tuple, NULL)) - Py_FatalError("init of pre-allocated RuntimeError failed"); - Py_DECREF(args_tuple); + PyBaseExceptionObject *err_inst = + (PyBaseExceptionObject *)PyExc_RecursionErrorInst; + PyObject *args_tuple; + PyObject *exc_message; + exc_message = PyUnicode_FromString("maximum recursion depth exceeded"); + if (!exc_message) + Py_FatalError("cannot allocate argument for RuntimeError " + "pre-allocation"); + args_tuple = PyTuple_Pack(1, exc_message); + if (!args_tuple) + Py_FatalError("cannot allocate tuple for RuntimeError " + "pre-allocation"); + Py_DECREF(exc_message); + if (BaseException_init(err_inst, args_tuple, NULL)) + Py_FatalError("init of pre-allocated RuntimeError failed"); + Py_DECREF(args_tuple); } Py_DECREF(bltinmod); Modified: python/branches/py3k-jit/Objects/fileobject.c ============================================================================== --- python/branches/py3k-jit/Objects/fileobject.c (original) +++ python/branches/py3k-jit/Objects/fileobject.c Mon May 10 23:55:43 2010 @@ -14,10 +14,10 @@ #endif /* Newline flags */ -#define NEWLINE_UNKNOWN 0 /* No newline seen, yet */ -#define NEWLINE_CR 1 /* \r newline seen */ -#define NEWLINE_LF 2 /* \n newline seen */ -#define NEWLINE_CRLF 4 /* \r\n newline seen */ +#define NEWLINE_UNKNOWN 0 /* No newline seen, yet */ +#define NEWLINE_CR 1 /* \r newline seen */ +#define NEWLINE_LF 2 /* \n newline seen */ +#define NEWLINE_CRLF 4 /* \r\n newline seen */ #ifdef __cplusplus extern "C" { @@ -27,110 +27,110 @@ PyObject * PyFile_FromFd(int fd, char *name, char *mode, int buffering, char *encoding, - char *errors, char *newline, int closefd) + char *errors, char *newline, int closefd) { - PyObject *io, *stream, *nameobj = NULL; + PyObject *io, *stream, *nameobj = NULL; - io = PyImport_ImportModule("io"); - if (io == NULL) - return NULL; - stream = PyObject_CallMethod(io, "open", "isisssi", fd, mode, - buffering, encoding, errors, - newline, closefd); - Py_DECREF(io); - if (stream == NULL) - return NULL; - if (name != NULL) { - nameobj = PyUnicode_DecodeFSDefault(name); - if (nameobj == NULL) - PyErr_Clear(); - else { - if (PyObject_SetAttrString(stream, "name", nameobj) < 0) - PyErr_Clear(); - Py_DECREF(nameobj); - } - } - return stream; + io = PyImport_ImportModule("io"); + if (io == NULL) + return NULL; + stream = PyObject_CallMethod(io, "open", "isisssi", fd, mode, + buffering, encoding, errors, + newline, closefd); + Py_DECREF(io); + if (stream == NULL) + return NULL; + if (name != NULL) { + nameobj = PyUnicode_DecodeFSDefault(name); + if (nameobj == NULL) + PyErr_Clear(); + else { + if (PyObject_SetAttrString(stream, "name", nameobj) < 0) + PyErr_Clear(); + Py_DECREF(nameobj); + } + } + return stream; } PyObject * PyFile_GetLine(PyObject *f, int n) { - PyObject *result; + PyObject *result; - if (f == NULL) { - PyErr_BadInternalCall(); - return NULL; - } - - { - PyObject *reader; - PyObject *args; - - reader = PyObject_GetAttrString(f, "readline"); - if (reader == NULL) - return NULL; - if (n <= 0) - args = PyTuple_New(0); - else - args = Py_BuildValue("(i)", n); - if (args == NULL) { - Py_DECREF(reader); - return NULL; - } - result = PyEval_CallObject(reader, args); - Py_DECREF(reader); - Py_DECREF(args); - if (result != NULL && !PyBytes_Check(result) && - !PyUnicode_Check(result)) { - Py_DECREF(result); - result = NULL; - PyErr_SetString(PyExc_TypeError, - "object.readline() returned non-string"); - } - } - - if (n < 0 && result != NULL && PyBytes_Check(result)) { - char *s = PyBytes_AS_STRING(result); - Py_ssize_t len = PyBytes_GET_SIZE(result); - if (len == 0) { - Py_DECREF(result); - result = NULL; - PyErr_SetString(PyExc_EOFError, - "EOF when reading a line"); - } - else if (s[len-1] == '\n') { - if (result->ob_refcnt == 1) - _PyBytes_Resize(&result, len-1); - else { - PyObject *v; - v = PyBytes_FromStringAndSize(s, len-1); - Py_DECREF(result); - result = v; - } - } - } - if (n < 0 && result != NULL && PyUnicode_Check(result)) { - Py_UNICODE *s = PyUnicode_AS_UNICODE(result); - Py_ssize_t len = PyUnicode_GET_SIZE(result); - if (len == 0) { - Py_DECREF(result); - result = NULL; - PyErr_SetString(PyExc_EOFError, - "EOF when reading a line"); - } - else if (s[len-1] == '\n') { - if (result->ob_refcnt == 1) - PyUnicode_Resize(&result, len-1); - else { - PyObject *v; - v = PyUnicode_FromUnicode(s, len-1); - Py_DECREF(result); - result = v; - } - } - } - return result; + if (f == NULL) { + PyErr_BadInternalCall(); + return NULL; + } + + { + PyObject *reader; + PyObject *args; + + reader = PyObject_GetAttrString(f, "readline"); + if (reader == NULL) + return NULL; + if (n <= 0) + args = PyTuple_New(0); + else + args = Py_BuildValue("(i)", n); + if (args == NULL) { + Py_DECREF(reader); + return NULL; + } + result = PyEval_CallObject(reader, args); + Py_DECREF(reader); + Py_DECREF(args); + if (result != NULL && !PyBytes_Check(result) && + !PyUnicode_Check(result)) { + Py_DECREF(result); + result = NULL; + PyErr_SetString(PyExc_TypeError, + "object.readline() returned non-string"); + } + } + + if (n < 0 && result != NULL && PyBytes_Check(result)) { + char *s = PyBytes_AS_STRING(result); + Py_ssize_t len = PyBytes_GET_SIZE(result); + if (len == 0) { + Py_DECREF(result); + result = NULL; + PyErr_SetString(PyExc_EOFError, + "EOF when reading a line"); + } + else if (s[len-1] == '\n') { + if (result->ob_refcnt == 1) + _PyBytes_Resize(&result, len-1); + else { + PyObject *v; + v = PyBytes_FromStringAndSize(s, len-1); + Py_DECREF(result); + result = v; + } + } + } + if (n < 0 && result != NULL && PyUnicode_Check(result)) { + Py_UNICODE *s = PyUnicode_AS_UNICODE(result); + Py_ssize_t len = PyUnicode_GET_SIZE(result); + if (len == 0) { + Py_DECREF(result); + result = NULL; + PyErr_SetString(PyExc_EOFError, + "EOF when reading a line"); + } + else if (s[len-1] == '\n') { + if (result->ob_refcnt == 1) + PyUnicode_Resize(&result, len-1); + else { + PyObject *v; + v = PyUnicode_FromUnicode(s, len-1); + Py_DECREF(result); + result = v; + } + } + } + return result; } /* Interfaces to write objects/strings to file-like objects */ @@ -138,60 +138,60 @@ int PyFile_WriteObject(PyObject *v, PyObject *f, int flags) { - PyObject *writer, *value, *args, *result; - if (f == NULL) { - PyErr_SetString(PyExc_TypeError, "writeobject with NULL file"); - return -1; - } - writer = PyObject_GetAttrString(f, "write"); - if (writer == NULL) - return -1; - if (flags & Py_PRINT_RAW) { - value = PyObject_Str(v); - } - else - value = PyObject_Repr(v); - if (value == NULL) { - Py_DECREF(writer); - return -1; - } - args = PyTuple_Pack(1, value); - if (args == NULL) { - Py_DECREF(value); - Py_DECREF(writer); - return -1; - } - result = PyEval_CallObject(writer, args); - Py_DECREF(args); - Py_DECREF(value); - Py_DECREF(writer); - if (result == NULL) - return -1; - Py_DECREF(result); - return 0; + PyObject *writer, *value, *args, *result; + if (f == NULL) { + PyErr_SetString(PyExc_TypeError, "writeobject with NULL file"); + return -1; + } + writer = PyObject_GetAttrString(f, "write"); + if (writer == NULL) + return -1; + if (flags & Py_PRINT_RAW) { + value = PyObject_Str(v); + } + else + value = PyObject_Repr(v); + if (value == NULL) { + Py_DECREF(writer); + return -1; + } + args = PyTuple_Pack(1, value); + if (args == NULL) { + Py_DECREF(value); + Py_DECREF(writer); + return -1; + } + result = PyEval_CallObject(writer, args); + Py_DECREF(args); + Py_DECREF(value); + Py_DECREF(writer); + if (result == NULL) + return -1; + Py_DECREF(result); + return 0; } int PyFile_WriteString(const char *s, PyObject *f) { - if (f == NULL) { - /* Should be caused by a pre-existing error */ - if (!PyErr_Occurred()) - PyErr_SetString(PyExc_SystemError, - "null file for PyFile_WriteString"); - return -1; - } - else if (!PyErr_Occurred()) { - PyObject *v = PyUnicode_FromString(s); - int err; - if (v == NULL) - return -1; - err = PyFile_WriteObject(v, f, Py_PRINT_RAW); - Py_DECREF(v); - return err; - } - else - return -1; + if (f == NULL) { + /* Should be caused by a pre-existing error */ + if (!PyErr_Occurred()) + PyErr_SetString(PyExc_SystemError, + "null file for PyFile_WriteString"); + return -1; + } + else if (!PyErr_Occurred()) { + PyObject *v = PyUnicode_FromString(s); + int err; + if (v == NULL) + return -1; + err = PyFile_WriteObject(v, f, Py_PRINT_RAW); + Py_DECREF(v); + return err; + } + else + return -1; } /* Try to get a file-descriptor from a Python object. If the object @@ -204,45 +204,45 @@ int PyObject_AsFileDescriptor(PyObject *o) { - int fd; - PyObject *meth; + int fd; + PyObject *meth; - if (PyLong_Check(o)) { - fd = PyLong_AsLong(o); - } - else if ((meth = PyObject_GetAttrString(o, "fileno")) != NULL) - { - PyObject *fno = PyEval_CallObject(meth, NULL); - Py_DECREF(meth); - if (fno == NULL) - return -1; - - if (PyLong_Check(fno)) { - fd = PyLong_AsLong(fno); - Py_DECREF(fno); - } - else { - PyErr_SetString(PyExc_TypeError, - "fileno() returned a non-integer"); - Py_DECREF(fno); - return -1; - } - } - else { - PyErr_SetString(PyExc_TypeError, - "argument must be an int, or have a fileno() method."); - return -1; - } - - if (fd == -1 && PyErr_Occurred()) - return -1; - if (fd < 0) { - PyErr_Format(PyExc_ValueError, - "file descriptor cannot be a negative integer (%i)", - fd); - return -1; - } - return fd; + if (PyLong_Check(o)) { + fd = PyLong_AsLong(o); + } + else if ((meth = PyObject_GetAttrString(o, "fileno")) != NULL) + { + PyObject *fno = PyEval_CallObject(meth, NULL); + Py_DECREF(meth); + if (fno == NULL) + return -1; + + if (PyLong_Check(fno)) { + fd = PyLong_AsLong(fno); + Py_DECREF(fno); + } + else { + PyErr_SetString(PyExc_TypeError, + "fileno() returned a non-integer"); + Py_DECREF(fno); + return -1; + } + } + else { + PyErr_SetString(PyExc_TypeError, + "argument must be an int, or have a fileno() method."); + return -1; + } + + if (fd == -1 && PyErr_Occurred()) + return -1; + if (fd < 0) { + PyErr_Format(PyExc_ValueError, + "file descriptor cannot be a negative integer (%i)", + fd); + return -1; + } + return fd; } /* @@ -262,68 +262,68 @@ char * Py_UniversalNewlineFgets(char *buf, int n, FILE *stream, PyObject *fobj) { - char *p = buf; - int c; - int newlinetypes = 0; - int skipnextlf = 0; - - if (fobj) { - errno = ENXIO; /* What can you do... */ - return NULL; - } - FLOCKFILE(stream); - c = 'x'; /* Shut up gcc warning */ - while (--n > 0 && (c = GETC(stream)) != EOF ) { - if (skipnextlf ) { - skipnextlf = 0; - if (c == '\n') { - /* Seeing a \n here with skipnextlf true - ** means we saw a \r before. - */ - newlinetypes |= NEWLINE_CRLF; - c = GETC(stream); - if (c == EOF) break; - } else { - /* - ** Note that c == EOF also brings us here, - ** so we're okay if the last char in the file - ** is a CR. - */ - newlinetypes |= NEWLINE_CR; - } - } - if (c == '\r') { - /* A \r is translated into a \n, and we skip - ** an adjacent \n, if any. We don't set the - ** newlinetypes flag until we've seen the next char. - */ - skipnextlf = 1; - c = '\n'; - } else if ( c == '\n') { - newlinetypes |= NEWLINE_LF; - } - *p++ = c; - if (c == '\n') break; - } - if ( c == EOF && skipnextlf ) - newlinetypes |= NEWLINE_CR; - FUNLOCKFILE(stream); - *p = '\0'; - if ( skipnextlf ) { - /* If we have no file object we cannot save the - ** skipnextlf flag. We have to readahead, which - ** will cause a pause if we're reading from an - ** interactive stream, but that is very unlikely - ** unless we're doing something silly like - ** exec(open("/dev/tty").read()). - */ - c = GETC(stream); - if ( c != '\n' ) - ungetc(c, stream); - } - if (p == buf) - return NULL; - return buf; + char *p = buf; + int c; + int newlinetypes = 0; + int skipnextlf = 0; + + if (fobj) { + errno = ENXIO; /* What can you do... */ + return NULL; + } + FLOCKFILE(stream); + c = 'x'; /* Shut up gcc warning */ + while (--n > 0 && (c = GETC(stream)) != EOF ) { + if (skipnextlf ) { + skipnextlf = 0; + if (c == '\n') { + /* Seeing a \n here with skipnextlf true + ** means we saw a \r before. + */ + newlinetypes |= NEWLINE_CRLF; + c = GETC(stream); + if (c == EOF) break; + } else { + /* + ** Note that c == EOF also brings us here, + ** so we're okay if the last char in the file + ** is a CR. + */ + newlinetypes |= NEWLINE_CR; + } + } + if (c == '\r') { + /* A \r is translated into a \n, and we skip + ** an adjacent \n, if any. We don't set the + ** newlinetypes flag until we've seen the next char. + */ + skipnextlf = 1; + c = '\n'; + } else if ( c == '\n') { + newlinetypes |= NEWLINE_LF; + } + *p++ = c; + if (c == '\n') break; + } + if ( c == EOF && skipnextlf ) + newlinetypes |= NEWLINE_CR; + FUNLOCKFILE(stream); + *p = '\0'; + if ( skipnextlf ) { + /* If we have no file object we cannot save the + ** skipnextlf flag. We have to readahead, which + ** will cause a pause if we're reading from an + ** interactive stream, but that is very unlikely + ** unless we're doing something silly like + ** exec(open("/dev/tty").read()). + */ + c = GETC(stream); + if ( c != '\n' ) + ungetc(c, stream); + } + if (p == buf) + return NULL; + return buf; } /* **************************** std printer **************************** @@ -332,195 +332,195 @@ */ typedef struct { - PyObject_HEAD - int fd; + PyObject_HEAD + int fd; } PyStdPrinter_Object; static PyObject * stdprinter_new(PyTypeObject *type, PyObject *args, PyObject *kews) { - PyStdPrinter_Object *self; + PyStdPrinter_Object *self; - assert(type != NULL && type->tp_alloc != NULL); + assert(type != NULL && type->tp_alloc != NULL); - self = (PyStdPrinter_Object *) type->tp_alloc(type, 0); - if (self != NULL) { - self->fd = -1; - } + self = (PyStdPrinter_Object *) type->tp_alloc(type, 0); + if (self != NULL) { + self->fd = -1; + } - return (PyObject *) self; + return (PyObject *) self; } static int fileio_init(PyObject *self, PyObject *args, PyObject *kwds) { - PyErr_SetString(PyExc_TypeError, - "cannot create 'stderrprinter' instances"); - return -1; + PyErr_SetString(PyExc_TypeError, + "cannot create 'stderrprinter' instances"); + return -1; } PyObject * PyFile_NewStdPrinter(int fd) { - PyStdPrinter_Object *self; + PyStdPrinter_Object *self; - if (fd != fileno(stdout) && fd != fileno(stderr)) { - /* not enough infrastructure for PyErr_BadInternalCall() */ - return NULL; - } - - self = PyObject_New(PyStdPrinter_Object, - &PyStdPrinter_Type); - if (self != NULL) { - self->fd = fd; - } - return (PyObject*)self; + if (fd != fileno(stdout) && fd != fileno(stderr)) { + /* not enough infrastructure for PyErr_BadInternalCall() */ + return NULL; + } + + self = PyObject_New(PyStdPrinter_Object, + &PyStdPrinter_Type); + if (self != NULL) { + self->fd = fd; + } + return (PyObject*)self; } static PyObject * stdprinter_write(PyStdPrinter_Object *self, PyObject *args) { - char *c; - Py_ssize_t n; + char *c; + Py_ssize_t n; - if (self->fd < 0) { - /* fd might be invalid on Windows - * I can't raise an exception here. It may lead to an - * unlimited recursion in the case stderr is invalid. - */ - Py_RETURN_NONE; - } - - if (!PyArg_ParseTuple(args, "s", &c)) { - return NULL; - } - n = strlen(c); - - Py_BEGIN_ALLOW_THREADS - errno = 0; - n = write(self->fd, c, n); - Py_END_ALLOW_THREADS - - if (n < 0) { - if (errno == EAGAIN) - Py_RETURN_NONE; - PyErr_SetFromErrno(PyExc_IOError); - return NULL; - } + if (self->fd < 0) { + /* fd might be invalid on Windows + * I can't raise an exception here. It may lead to an + * unlimited recursion in the case stderr is invalid. + */ + Py_RETURN_NONE; + } + + if (!PyArg_ParseTuple(args, "s", &c)) { + return NULL; + } + n = strlen(c); + + Py_BEGIN_ALLOW_THREADS + errno = 0; + n = write(self->fd, c, n); + Py_END_ALLOW_THREADS + + if (n < 0) { + if (errno == EAGAIN) + Py_RETURN_NONE; + PyErr_SetFromErrno(PyExc_IOError); + return NULL; + } - return PyLong_FromSsize_t(n); + return PyLong_FromSsize_t(n); } static PyObject * stdprinter_fileno(PyStdPrinter_Object *self) { - return PyLong_FromLong((long) self->fd); + return PyLong_FromLong((long) self->fd); } static PyObject * stdprinter_repr(PyStdPrinter_Object *self) { - return PyUnicode_FromFormat("", - self->fd, self); + return PyUnicode_FromFormat("", + self->fd, self); } static PyObject * stdprinter_noop(PyStdPrinter_Object *self) { - Py_RETURN_NONE; + Py_RETURN_NONE; } static PyObject * stdprinter_isatty(PyStdPrinter_Object *self) { - long res; - if (self->fd < 0) { - Py_RETURN_FALSE; - } - - Py_BEGIN_ALLOW_THREADS - res = isatty(self->fd); - Py_END_ALLOW_THREADS + long res; + if (self->fd < 0) { + Py_RETURN_FALSE; + } + + Py_BEGIN_ALLOW_THREADS + res = isatty(self->fd); + Py_END_ALLOW_THREADS - return PyBool_FromLong(res); + return PyBool_FromLong(res); } static PyMethodDef stdprinter_methods[] = { - {"close", (PyCFunction)stdprinter_noop, METH_NOARGS, ""}, - {"flush", (PyCFunction)stdprinter_noop, METH_NOARGS, ""}, - {"fileno", (PyCFunction)stdprinter_fileno, METH_NOARGS, ""}, - {"isatty", (PyCFunction)stdprinter_isatty, METH_NOARGS, ""}, - {"write", (PyCFunction)stdprinter_write, METH_VARARGS, ""}, - {NULL, NULL} /*sentinel */ + {"close", (PyCFunction)stdprinter_noop, METH_NOARGS, ""}, + {"flush", (PyCFunction)stdprinter_noop, METH_NOARGS, ""}, + {"fileno", (PyCFunction)stdprinter_fileno, METH_NOARGS, ""}, + {"isatty", (PyCFunction)stdprinter_isatty, METH_NOARGS, ""}, + {"write", (PyCFunction)stdprinter_write, METH_VARARGS, ""}, + {NULL, NULL} /*sentinel */ }; static PyObject * get_closed(PyStdPrinter_Object *self, void *closure) { - Py_INCREF(Py_False); - return Py_False; + Py_INCREF(Py_False); + return Py_False; } static PyObject * get_mode(PyStdPrinter_Object *self, void *closure) { - return PyUnicode_FromString("w"); + return PyUnicode_FromString("w"); } static PyObject * get_encoding(PyStdPrinter_Object *self, void *closure) { - Py_RETURN_NONE; + Py_RETURN_NONE; } static PyGetSetDef stdprinter_getsetlist[] = { - {"closed", (getter)get_closed, NULL, "True if the file is closed"}, - {"encoding", (getter)get_encoding, NULL, "Encoding of the file"}, - {"mode", (getter)get_mode, NULL, "String giving the file mode"}, - {0}, + {"closed", (getter)get_closed, NULL, "True if the file is closed"}, + {"encoding", (getter)get_encoding, NULL, "Encoding of the file"}, + {"mode", (getter)get_mode, NULL, "String giving the file mode"}, + {0}, }; PyTypeObject PyStdPrinter_Type = { - PyVarObject_HEAD_INIT(&PyType_Type, 0) - "stderrprinter", /* tp_name */ - sizeof(PyStdPrinter_Object), /* tp_basicsize */ - 0, /* tp_itemsize */ - /* methods */ - 0, /* tp_dealloc */ - 0, /* tp_print */ - 0, /* tp_getattr */ - 0, /* tp_setattr */ - 0, /* tp_reserved */ - (reprfunc)stdprinter_repr, /* tp_repr */ - 0, /* tp_as_number */ - 0, /* tp_as_sequence */ - 0, /* tp_as_mapping */ - 0, /* tp_hash */ - 0, /* tp_call */ - 0, /* tp_str */ - PyObject_GenericGetAttr, /* tp_getattro */ - 0, /* tp_setattro */ - 0, /* tp_as_buffer */ - Py_TPFLAGS_DEFAULT, /* tp_flags */ - 0, /* tp_doc */ - 0, /* tp_traverse */ - 0, /* tp_clear */ - 0, /* tp_richcompare */ - 0, /* tp_weaklistoffset */ - 0, /* tp_iter */ - 0, /* tp_iternext */ - stdprinter_methods, /* tp_methods */ - 0, /* tp_members */ - stdprinter_getsetlist, /* tp_getset */ - 0, /* tp_base */ - 0, /* tp_dict */ - 0, /* tp_descr_get */ - 0, /* tp_descr_set */ - 0, /* tp_dictoffset */ - fileio_init, /* tp_init */ - PyType_GenericAlloc, /* tp_alloc */ - stdprinter_new, /* tp_new */ - PyObject_Del, /* tp_free */ + PyVarObject_HEAD_INIT(&PyType_Type, 0) + "stderrprinter", /* tp_name */ + sizeof(PyStdPrinter_Object), /* tp_basicsize */ + 0, /* tp_itemsize */ + /* methods */ + 0, /* tp_dealloc */ + 0, /* tp_print */ + 0, /* tp_getattr */ + 0, /* tp_setattr */ + 0, /* tp_reserved */ + (reprfunc)stdprinter_repr, /* tp_repr */ + 0, /* tp_as_number */ + 0, /* tp_as_sequence */ + 0, /* tp_as_mapping */ + 0, /* tp_hash */ + 0, /* tp_call */ + 0, /* tp_str */ + PyObject_GenericGetAttr, /* tp_getattro */ + 0, /* tp_setattro */ + 0, /* tp_as_buffer */ + Py_TPFLAGS_DEFAULT, /* tp_flags */ + 0, /* tp_doc */ + 0, /* tp_traverse */ + 0, /* tp_clear */ + 0, /* tp_richcompare */ + 0, /* tp_weaklistoffset */ + 0, /* tp_iter */ + 0, /* tp_iternext */ + stdprinter_methods, /* tp_methods */ + 0, /* tp_members */ + stdprinter_getsetlist, /* tp_getset */ + 0, /* tp_base */ + 0, /* tp_dict */ + 0, /* tp_descr_get */ + 0, /* tp_descr_set */ + 0, /* tp_dictoffset */ + fileio_init, /* tp_init */ + PyType_GenericAlloc, /* tp_alloc */ + stdprinter_new, /* tp_new */ + PyObject_Del, /* tp_free */ }; Modified: python/branches/py3k-jit/Objects/floatobject.c ============================================================================== --- python/branches/py3k-jit/Objects/floatobject.c (original) +++ python/branches/py3k-jit/Objects/floatobject.c Mon May 10 23:55:43 2010 @@ -22,13 +22,13 @@ #endif /* Special free list -- see comments for same code in intobject.c. */ -#define BLOCK_SIZE 1000 /* 1K less typical malloc overhead */ -#define BHEAD_SIZE 8 /* Enough for a 64-bit pointer */ -#define N_FLOATOBJECTS ((BLOCK_SIZE - BHEAD_SIZE) / sizeof(PyFloatObject)) +#define BLOCK_SIZE 1000 /* 1K less typical malloc overhead */ +#define BHEAD_SIZE 8 /* Enough for a 64-bit pointer */ +#define N_FLOATOBJECTS ((BLOCK_SIZE - BHEAD_SIZE) / sizeof(PyFloatObject)) struct _floatblock { - struct _floatblock *next; - PyFloatObject objects[N_FLOATOBJECTS]; + struct _floatblock *next; + PyFloatObject objects[N_FLOATOBJECTS]; }; typedef struct _floatblock PyFloatBlock; @@ -39,31 +39,31 @@ static PyFloatObject * fill_free_list(void) { - PyFloatObject *p, *q; - /* XXX Float blocks escape the object heap. Use PyObject_MALLOC ??? */ - p = (PyFloatObject *) PyMem_MALLOC(sizeof(PyFloatBlock)); - if (p == NULL) - return (PyFloatObject *) PyErr_NoMemory(); - ((PyFloatBlock *)p)->next = block_list; - block_list = (PyFloatBlock *)p; - p = &((PyFloatBlock *)p)->objects[0]; - q = p + N_FLOATOBJECTS; - while (--q > p) - Py_TYPE(q) = (struct _typeobject *)(q-1); - Py_TYPE(q) = NULL; - return p + N_FLOATOBJECTS - 1; + PyFloatObject *p, *q; + /* XXX Float blocks escape the object heap. Use PyObject_MALLOC ??? */ + p = (PyFloatObject *) PyMem_MALLOC(sizeof(PyFloatBlock)); + if (p == NULL) + return (PyFloatObject *) PyErr_NoMemory(); + ((PyFloatBlock *)p)->next = block_list; + block_list = (PyFloatBlock *)p; + p = &((PyFloatBlock *)p)->objects[0]; + q = p + N_FLOATOBJECTS; + while (--q > p) + Py_TYPE(q) = (struct _typeobject *)(q-1); + Py_TYPE(q) = NULL; + return p + N_FLOATOBJECTS - 1; } double PyFloat_GetMax(void) { - return DBL_MAX; + return DBL_MAX; } double PyFloat_GetMin(void) { - return DBL_MIN; + return DBL_MIN; } static PyTypeObject FloatInfoType; @@ -76,183 +76,183 @@ your system's :file:`float.h` for more information."); static PyStructSequence_Field floatinfo_fields[] = { - {"max", "DBL_MAX -- maximum representable finite float"}, - {"max_exp", "DBL_MAX_EXP -- maximum int e such that radix**(e-1) " - "is representable"}, - {"max_10_exp", "DBL_MAX_10_EXP -- maximum int e such that 10**e " - "is representable"}, - {"min", "DBL_MIN -- Minimum positive normalizer float"}, - {"min_exp", "DBL_MIN_EXP -- minimum int e such that radix**(e-1) " - "is a normalized float"}, - {"min_10_exp", "DBL_MIN_10_EXP -- minimum int e such that 10**e is " - "a normalized"}, - {"dig", "DBL_DIG -- digits"}, - {"mant_dig", "DBL_MANT_DIG -- mantissa digits"}, - {"epsilon", "DBL_EPSILON -- Difference between 1 and the next " - "representable float"}, - {"radix", "FLT_RADIX -- radix of exponent"}, - {"rounds", "FLT_ROUNDS -- addition rounds"}, - {0} + {"max", "DBL_MAX -- maximum representable finite float"}, + {"max_exp", "DBL_MAX_EXP -- maximum int e such that radix**(e-1) " + "is representable"}, + {"max_10_exp", "DBL_MAX_10_EXP -- maximum int e such that 10**e " + "is representable"}, + {"min", "DBL_MIN -- Minimum positive normalizer float"}, + {"min_exp", "DBL_MIN_EXP -- minimum int e such that radix**(e-1) " + "is a normalized float"}, + {"min_10_exp", "DBL_MIN_10_EXP -- minimum int e such that 10**e is " + "a normalized"}, + {"dig", "DBL_DIG -- digits"}, + {"mant_dig", "DBL_MANT_DIG -- mantissa digits"}, + {"epsilon", "DBL_EPSILON -- Difference between 1 and the next " + "representable float"}, + {"radix", "FLT_RADIX -- radix of exponent"}, + {"rounds", "FLT_ROUNDS -- addition rounds"}, + {0} }; static PyStructSequence_Desc floatinfo_desc = { - "sys.float_info", /* name */ - floatinfo__doc__, /* doc */ - floatinfo_fields, /* fields */ - 11 + "sys.float_info", /* name */ + floatinfo__doc__, /* doc */ + floatinfo_fields, /* fields */ + 11 }; PyObject * PyFloat_GetInfo(void) { - PyObject* floatinfo; - int pos = 0; + PyObject* floatinfo; + int pos = 0; - floatinfo = PyStructSequence_New(&FloatInfoType); - if (floatinfo == NULL) { - return NULL; - } + floatinfo = PyStructSequence_New(&FloatInfoType); + if (floatinfo == NULL) { + return NULL; + } #define SetIntFlag(flag) \ - PyStructSequence_SET_ITEM(floatinfo, pos++, PyLong_FromLong(flag)) + PyStructSequence_SET_ITEM(floatinfo, pos++, PyLong_FromLong(flag)) #define SetDblFlag(flag) \ - PyStructSequence_SET_ITEM(floatinfo, pos++, PyFloat_FromDouble(flag)) + PyStructSequence_SET_ITEM(floatinfo, pos++, PyFloat_FromDouble(flag)) - SetDblFlag(DBL_MAX); - SetIntFlag(DBL_MAX_EXP); - SetIntFlag(DBL_MAX_10_EXP); - SetDblFlag(DBL_MIN); - SetIntFlag(DBL_MIN_EXP); - SetIntFlag(DBL_MIN_10_EXP); - SetIntFlag(DBL_DIG); - SetIntFlag(DBL_MANT_DIG); - SetDblFlag(DBL_EPSILON); - SetIntFlag(FLT_RADIX); - SetIntFlag(FLT_ROUNDS); + SetDblFlag(DBL_MAX); + SetIntFlag(DBL_MAX_EXP); + SetIntFlag(DBL_MAX_10_EXP); + SetDblFlag(DBL_MIN); + SetIntFlag(DBL_MIN_EXP); + SetIntFlag(DBL_MIN_10_EXP); + SetIntFlag(DBL_DIG); + SetIntFlag(DBL_MANT_DIG); + SetDblFlag(DBL_EPSILON); + SetIntFlag(FLT_RADIX); + SetIntFlag(FLT_ROUNDS); #undef SetIntFlag #undef SetDblFlag - - if (PyErr_Occurred()) { - Py_CLEAR(floatinfo); - return NULL; - } - return floatinfo; + + if (PyErr_Occurred()) { + Py_CLEAR(floatinfo); + return NULL; + } + return floatinfo; } PyObject * PyFloat_FromDouble(double fval) { - register PyFloatObject *op; - if (free_list == NULL) { - if ((free_list = fill_free_list()) == NULL) - return NULL; - } - /* Inline PyObject_New */ - op = free_list; - free_list = (PyFloatObject *)Py_TYPE(op); - PyObject_INIT(op, &PyFloat_Type); - op->ob_fval = fval; - return (PyObject *) op; + register PyFloatObject *op; + if (free_list == NULL) { + if ((free_list = fill_free_list()) == NULL) + return NULL; + } + /* Inline PyObject_New */ + op = free_list; + free_list = (PyFloatObject *)Py_TYPE(op); + PyObject_INIT(op, &PyFloat_Type); + op->ob_fval = fval; + return (PyObject *) op; } PyObject * PyFloat_FromString(PyObject *v) { - const char *s, *last, *end; - double x; - char buffer[256]; /* for errors */ - char *s_buffer = NULL; - Py_ssize_t len; - PyObject *result = NULL; - - if (PyUnicode_Check(v)) { - s_buffer = (char *)PyMem_MALLOC(PyUnicode_GET_SIZE(v)+1); - if (s_buffer == NULL) - return PyErr_NoMemory(); - if (PyUnicode_EncodeDecimal(PyUnicode_AS_UNICODE(v), - PyUnicode_GET_SIZE(v), - s_buffer, - NULL)) - goto error; - s = s_buffer; - len = strlen(s); - } - else if (PyObject_AsCharBuffer(v, &s, &len)) { - PyErr_SetString(PyExc_TypeError, - "float() argument must be a string or a number"); - return NULL; - } - last = s + len; - - while (Py_ISSPACE(*s)) - s++; - /* We don't care about overflow or underflow. If the platform - * supports them, infinities and signed zeroes (on underflow) are - * fine. */ - x = PyOS_string_to_double(s, (char **)&end, NULL); - if (x == -1.0 && PyErr_Occurred()) - goto error; - while (Py_ISSPACE(*end)) - end++; - if (end == last) - result = PyFloat_FromDouble(x); - else { - PyOS_snprintf(buffer, sizeof(buffer), - "invalid literal for float(): %.200s", s); - PyErr_SetString(PyExc_ValueError, buffer); - result = NULL; - } + const char *s, *last, *end; + double x; + char buffer[256]; /* for errors */ + char *s_buffer = NULL; + Py_ssize_t len; + PyObject *result = NULL; + + if (PyUnicode_Check(v)) { + s_buffer = (char *)PyMem_MALLOC(PyUnicode_GET_SIZE(v)+1); + if (s_buffer == NULL) + return PyErr_NoMemory(); + if (PyUnicode_EncodeDecimal(PyUnicode_AS_UNICODE(v), + PyUnicode_GET_SIZE(v), + s_buffer, + NULL)) + goto error; + s = s_buffer; + len = strlen(s); + } + else if (PyObject_AsCharBuffer(v, &s, &len)) { + PyErr_SetString(PyExc_TypeError, + "float() argument must be a string or a number"); + return NULL; + } + last = s + len; + + while (Py_ISSPACE(*s)) + s++; + /* We don't care about overflow or underflow. If the platform + * supports them, infinities and signed zeroes (on underflow) are + * fine. */ + x = PyOS_string_to_double(s, (char **)&end, NULL); + if (x == -1.0 && PyErr_Occurred()) + goto error; + while (Py_ISSPACE(*end)) + end++; + if (end == last) + result = PyFloat_FromDouble(x); + else { + PyOS_snprintf(buffer, sizeof(buffer), + "invalid literal for float(): %.200s", s); + PyErr_SetString(PyExc_ValueError, buffer); + result = NULL; + } error: - if (s_buffer) - PyMem_FREE(s_buffer); - return result; + if (s_buffer) + PyMem_FREE(s_buffer); + return result; } static void float_dealloc(PyFloatObject *op) { - if (PyFloat_CheckExact(op)) { - Py_TYPE(op) = (struct _typeobject *)free_list; - free_list = op; - } - else - Py_TYPE(op)->tp_free((PyObject *)op); + if (PyFloat_CheckExact(op)) { + Py_TYPE(op) = (struct _typeobject *)free_list; + free_list = op; + } + else + Py_TYPE(op)->tp_free((PyObject *)op); } double PyFloat_AsDouble(PyObject *op) { - PyNumberMethods *nb; - PyFloatObject *fo; - double val; - - if (op && PyFloat_Check(op)) - return PyFloat_AS_DOUBLE((PyFloatObject*) op); - - if (op == NULL) { - PyErr_BadArgument(); - return -1; - } - - if ((nb = Py_TYPE(op)->tp_as_number) == NULL || nb->nb_float == NULL) { - PyErr_SetString(PyExc_TypeError, "a float is required"); - return -1; - } - - fo = (PyFloatObject*) (*nb->nb_float) (op); - if (fo == NULL) - return -1; - if (!PyFloat_Check(fo)) { - PyErr_SetString(PyExc_TypeError, - "nb_float should return float object"); - return -1; - } + PyNumberMethods *nb; + PyFloatObject *fo; + double val; + + if (op && PyFloat_Check(op)) + return PyFloat_AS_DOUBLE((PyFloatObject*) op); + + if (op == NULL) { + PyErr_BadArgument(); + return -1; + } + + if ((nb = Py_TYPE(op)->tp_as_number) == NULL || nb->nb_float == NULL) { + PyErr_SetString(PyExc_TypeError, "a float is required"); + return -1; + } + + fo = (PyFloatObject*) (*nb->nb_float) (op); + if (fo == NULL) + return -1; + if (!PyFloat_Check(fo)) { + PyErr_SetString(PyExc_TypeError, + "nb_float should return float object"); + return -1; + } - val = PyFloat_AS_DOUBLE(fo); - Py_DECREF(fo); + val = PyFloat_AS_DOUBLE(fo); + Py_DECREF(fo); - return val; + return val; } /* Macro and helper that convert PyObject obj to a C double and store @@ -261,32 +261,32 @@ obj is not of float, int or long type, Py_NotImplemented is incref'ed, stored in obj, and returned from the function invoking this macro. */ -#define CONVERT_TO_DOUBLE(obj, dbl) \ - if (PyFloat_Check(obj)) \ - dbl = PyFloat_AS_DOUBLE(obj); \ - else if (convert_to_double(&(obj), &(dbl)) < 0) \ - return obj; +#define CONVERT_TO_DOUBLE(obj, dbl) \ + if (PyFloat_Check(obj)) \ + dbl = PyFloat_AS_DOUBLE(obj); \ + else if (convert_to_double(&(obj), &(dbl)) < 0) \ + return obj; /* Methods */ static int convert_to_double(PyObject **v, double *dbl) { - register PyObject *obj = *v; + register PyObject *obj = *v; - if (PyLong_Check(obj)) { - *dbl = PyLong_AsDouble(obj); - if (*dbl == -1.0 && PyErr_Occurred()) { - *v = NULL; - return -1; - } - } - else { - Py_INCREF(Py_NotImplemented); - *v = Py_NotImplemented; - return -1; - } - return 0; + if (PyLong_Check(obj)) { + *dbl = PyLong_AsDouble(obj); + if (*dbl == -1.0 && PyErr_Occurred()) { + *v = NULL; + return -1; + } + } + else { + Py_INCREF(Py_NotImplemented); + *v = Py_NotImplemented; + return -1; + } + return 0; } static PyObject * @@ -298,7 +298,7 @@ Py_DTSF_ADD_DOT_0, NULL); if (!buf) - return PyErr_NoMemory(); + return PyErr_NoMemory(); result = PyUnicode_FromString(buf); PyMem_Free(buf); return result; @@ -334,341 +334,341 @@ static PyObject* float_richcompare(PyObject *v, PyObject *w, int op) { - double i, j; - int r = 0; + double i, j; + int r = 0; - assert(PyFloat_Check(v)); - i = PyFloat_AS_DOUBLE(v); + assert(PyFloat_Check(v)); + i = PyFloat_AS_DOUBLE(v); - /* Switch on the type of w. Set i and j to doubles to be compared, - * and op to the richcomp to use. - */ - if (PyFloat_Check(w)) - j = PyFloat_AS_DOUBLE(w); - - else if (!Py_IS_FINITE(i)) { - if (PyLong_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. - */ - j = 0.0; - else - goto Unimplemented; - } - - else if (PyLong_Check(w)) { - int vsign = i == 0.0 ? 0 : i < 0.0 ? -1 : 1; - int wsign = _PyLong_Sign(w); - size_t nbits; - int exponent; - - if (vsign != wsign) { - /* Magnitudes are irrelevant -- the signs alone - * determine the outcome. - */ - i = (double)vsign; - j = (double)wsign; - goto Compare; - } - /* The signs are the same. */ - /* Convert w to a double if it fits. In particular, 0 fits. */ - nbits = _PyLong_NumBits(w); - if (nbits == (size_t)-1 && PyErr_Occurred()) { - /* This long is so large that size_t isn't big enough - * to hold the # of bits. Replace with little doubles - * that give the same outcome -- w is so large that - * its magnitude must exceed the magnitude of any - * finite float. - */ - PyErr_Clear(); - i = (double)vsign; - assert(wsign != 0); - j = wsign * 2.0; - goto Compare; - } - if (nbits <= 48) { - j = PyLong_AsDouble(w); - /* It's impossible that <= 48 bits overflowed. */ - assert(j != -1.0 || ! PyErr_Occurred()); - goto Compare; - } - assert(wsign != 0); /* else nbits was 0 */ - assert(vsign != 0); /* if vsign were 0, then since wsign is - * not 0, we would have taken the - * vsign != wsign branch at the start */ - /* We want to work with non-negative numbers. */ - if (vsign < 0) { - /* "Multiply both sides" by -1; this also swaps the - * comparator. - */ - i = -i; - op = _Py_SwappedOp[op]; - } - assert(i > 0.0); - (void) frexp(i, &exponent); - /* exponent is the # of bits in v before the radix point; - * we know that nbits (the # of bits in w) > 48 at this point - */ - if (exponent < 0 || (size_t)exponent < nbits) { - i = 1.0; - j = 2.0; - goto Compare; - } - if ((size_t)exponent > nbits) { - i = 2.0; - j = 1.0; - goto Compare; - } - /* v and w have the same number of bits before the radix - * point. Construct two longs that have the same comparison - * outcome. - */ - { - double fracpart; - double intpart; - PyObject *result = NULL; - PyObject *one = NULL; - PyObject *vv = NULL; - PyObject *ww = w; - - if (wsign < 0) { - ww = PyNumber_Negative(w); - if (ww == NULL) - goto Error; - } - else - Py_INCREF(ww); - - fracpart = modf(i, &intpart); - vv = PyLong_FromDouble(intpart); - if (vv == NULL) - goto Error; - - if (fracpart != 0.0) { - /* Shift left, and or a 1 bit into vv - * to represent the lost fraction. - */ - PyObject *temp; - - one = PyLong_FromLong(1); - if (one == NULL) - goto Error; - - temp = PyNumber_Lshift(ww, one); - if (temp == NULL) - goto Error; - Py_DECREF(ww); - ww = temp; - - temp = PyNumber_Lshift(vv, one); - if (temp == NULL) - goto Error; - Py_DECREF(vv); - vv = temp; - - temp = PyNumber_Or(vv, one); - if (temp == NULL) - goto Error; - Py_DECREF(vv); - vv = temp; - } - - r = PyObject_RichCompareBool(vv, ww, op); - if (r < 0) - goto Error; - result = PyBool_FromLong(r); - Error: - Py_XDECREF(vv); - Py_XDECREF(ww); - Py_XDECREF(one); - return result; - } - } /* else if (PyLong_Check(w)) */ + /* Switch on the type of w. Set i and j to doubles to be compared, + * and op to the richcomp to use. + */ + if (PyFloat_Check(w)) + j = PyFloat_AS_DOUBLE(w); + + else if (!Py_IS_FINITE(i)) { + if (PyLong_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. + */ + j = 0.0; + else + goto Unimplemented; + } + + else if (PyLong_Check(w)) { + int vsign = i == 0.0 ? 0 : i < 0.0 ? -1 : 1; + int wsign = _PyLong_Sign(w); + size_t nbits; + int exponent; + + if (vsign != wsign) { + /* Magnitudes are irrelevant -- the signs alone + * determine the outcome. + */ + i = (double)vsign; + j = (double)wsign; + goto Compare; + } + /* The signs are the same. */ + /* Convert w to a double if it fits. In particular, 0 fits. */ + nbits = _PyLong_NumBits(w); + if (nbits == (size_t)-1 && PyErr_Occurred()) { + /* This long is so large that size_t isn't big enough + * to hold the # of bits. Replace with little doubles + * that give the same outcome -- w is so large that + * its magnitude must exceed the magnitude of any + * finite float. + */ + PyErr_Clear(); + i = (double)vsign; + assert(wsign != 0); + j = wsign * 2.0; + goto Compare; + } + if (nbits <= 48) { + j = PyLong_AsDouble(w); + /* It's impossible that <= 48 bits overflowed. */ + assert(j != -1.0 || ! PyErr_Occurred()); + goto Compare; + } + assert(wsign != 0); /* else nbits was 0 */ + assert(vsign != 0); /* if vsign were 0, then since wsign is + * not 0, we would have taken the + * vsign != wsign branch at the start */ + /* We want to work with non-negative numbers. */ + if (vsign < 0) { + /* "Multiply both sides" by -1; this also swaps the + * comparator. + */ + i = -i; + op = _Py_SwappedOp[op]; + } + assert(i > 0.0); + (void) frexp(i, &exponent); + /* exponent is the # of bits in v before the radix point; + * we know that nbits (the # of bits in w) > 48 at this point + */ + if (exponent < 0 || (size_t)exponent < nbits) { + i = 1.0; + j = 2.0; + goto Compare; + } + if ((size_t)exponent > nbits) { + i = 2.0; + j = 1.0; + goto Compare; + } + /* v and w have the same number of bits before the radix + * point. Construct two longs that have the same comparison + * outcome. + */ + { + double fracpart; + double intpart; + PyObject *result = NULL; + PyObject *one = NULL; + PyObject *vv = NULL; + PyObject *ww = w; + + if (wsign < 0) { + ww = PyNumber_Negative(w); + if (ww == NULL) + goto Error; + } + else + Py_INCREF(ww); + + fracpart = modf(i, &intpart); + vv = PyLong_FromDouble(intpart); + if (vv == NULL) + goto Error; + + if (fracpart != 0.0) { + /* Shift left, and or a 1 bit into vv + * to represent the lost fraction. + */ + PyObject *temp; + + one = PyLong_FromLong(1); + if (one == NULL) + goto Error; + + temp = PyNumber_Lshift(ww, one); + if (temp == NULL) + goto Error; + Py_DECREF(ww); + ww = temp; + + temp = PyNumber_Lshift(vv, one); + if (temp == NULL) + goto Error; + Py_DECREF(vv); + vv = temp; + + temp = PyNumber_Or(vv, one); + if (temp == NULL) + goto Error; + Py_DECREF(vv); + vv = temp; + } + + r = PyObject_RichCompareBool(vv, ww, op); + if (r < 0) + goto Error; + result = PyBool_FromLong(r); + Error: + Py_XDECREF(vv); + Py_XDECREF(ww); + Py_XDECREF(one); + return result; + } + } /* else if (PyLong_Check(w)) */ - else /* w isn't float, int, or long */ - goto Unimplemented; + else /* w isn't float, int, or long */ + goto Unimplemented; Compare: - PyFPE_START_PROTECT("richcompare", return NULL) - switch (op) { - case Py_EQ: - r = i == j; - break; - case Py_NE: - r = i != j; - break; - case Py_LE: - r = i <= j; - break; - case Py_GE: - r = i >= j; - break; - case Py_LT: - r = i < j; - break; - case Py_GT: - r = i > j; - break; - } - PyFPE_END_PROTECT(r) - return PyBool_FromLong(r); + PyFPE_START_PROTECT("richcompare", return NULL) + switch (op) { + case Py_EQ: + r = i == j; + break; + case Py_NE: + r = i != j; + break; + case Py_LE: + r = i <= j; + break; + case Py_GE: + r = i >= j; + break; + case Py_LT: + r = i < j; + break; + case Py_GT: + r = i > j; + break; + } + PyFPE_END_PROTECT(r) + return PyBool_FromLong(r); Unimplemented: - Py_INCREF(Py_NotImplemented); - return Py_NotImplemented; + Py_INCREF(Py_NotImplemented); + return Py_NotImplemented; } static long float_hash(PyFloatObject *v) { - return _Py_HashDouble(v->ob_fval); + return _Py_HashDouble(v->ob_fval); } static PyObject * float_add(PyObject *v, PyObject *w) { - double a,b; - CONVERT_TO_DOUBLE(v, a); - CONVERT_TO_DOUBLE(w, b); - PyFPE_START_PROTECT("add", return 0) - a = a + b; - PyFPE_END_PROTECT(a) - return PyFloat_FromDouble(a); + double a,b; + CONVERT_TO_DOUBLE(v, a); + CONVERT_TO_DOUBLE(w, b); + PyFPE_START_PROTECT("add", return 0) + a = a + b; + PyFPE_END_PROTECT(a) + return PyFloat_FromDouble(a); } static PyObject * float_sub(PyObject *v, PyObject *w) { - double a,b; - CONVERT_TO_DOUBLE(v, a); - CONVERT_TO_DOUBLE(w, b); - PyFPE_START_PROTECT("subtract", return 0) - a = a - b; - PyFPE_END_PROTECT(a) - return PyFloat_FromDouble(a); + double a,b; + CONVERT_TO_DOUBLE(v, a); + CONVERT_TO_DOUBLE(w, b); + PyFPE_START_PROTECT("subtract", return 0) + a = a - b; + PyFPE_END_PROTECT(a) + return PyFloat_FromDouble(a); } static PyObject * float_mul(PyObject *v, PyObject *w) { - double a,b; - CONVERT_TO_DOUBLE(v, a); - CONVERT_TO_DOUBLE(w, b); - PyFPE_START_PROTECT("multiply", return 0) - a = a * b; - PyFPE_END_PROTECT(a) - return PyFloat_FromDouble(a); + double a,b; + CONVERT_TO_DOUBLE(v, a); + CONVERT_TO_DOUBLE(w, b); + PyFPE_START_PROTECT("multiply", return 0) + a = a * b; + PyFPE_END_PROTECT(a) + return PyFloat_FromDouble(a); } static PyObject * float_div(PyObject *v, PyObject *w) { - double a,b; - CONVERT_TO_DOUBLE(v, a); - CONVERT_TO_DOUBLE(w, b); + double a,b; + CONVERT_TO_DOUBLE(v, a); + CONVERT_TO_DOUBLE(w, b); #ifdef Py_NAN - if (b == 0.0) { - PyErr_SetString(PyExc_ZeroDivisionError, - "float division by zero"); - return NULL; - } + if (b == 0.0) { + PyErr_SetString(PyExc_ZeroDivisionError, + "float division by zero"); + return NULL; + } #endif - PyFPE_START_PROTECT("divide", return 0) - a = a / b; - PyFPE_END_PROTECT(a) - return PyFloat_FromDouble(a); + PyFPE_START_PROTECT("divide", return 0) + a = a / b; + PyFPE_END_PROTECT(a) + return PyFloat_FromDouble(a); } static PyObject * float_rem(PyObject *v, PyObject *w) { - double vx, wx; - double mod; - CONVERT_TO_DOUBLE(v, vx); - CONVERT_TO_DOUBLE(w, wx); + double vx, wx; + double mod; + CONVERT_TO_DOUBLE(v, vx); + CONVERT_TO_DOUBLE(w, wx); #ifdef Py_NAN - if (wx == 0.0) { - PyErr_SetString(PyExc_ZeroDivisionError, - "float modulo"); - return NULL; - } + if (wx == 0.0) { + PyErr_SetString(PyExc_ZeroDivisionError, + "float modulo"); + return NULL; + } #endif - PyFPE_START_PROTECT("modulo", return 0) - mod = fmod(vx, wx); - /* note: checking mod*wx < 0 is incorrect -- underflows to - 0 if wx < sqrt(smallest nonzero double) */ - if (mod && ((wx < 0) != (mod < 0))) { - mod += wx; - } - PyFPE_END_PROTECT(mod) - return PyFloat_FromDouble(mod); + PyFPE_START_PROTECT("modulo", return 0) + mod = fmod(vx, wx); + /* note: checking mod*wx < 0 is incorrect -- underflows to + 0 if wx < sqrt(smallest nonzero double) */ + if (mod && ((wx < 0) != (mod < 0))) { + mod += wx; + } + PyFPE_END_PROTECT(mod) + return PyFloat_FromDouble(mod); } static PyObject * float_divmod(PyObject *v, PyObject *w) { - double vx, wx; - double div, mod, floordiv; - CONVERT_TO_DOUBLE(v, vx); - CONVERT_TO_DOUBLE(w, wx); - if (wx == 0.0) { - PyErr_SetString(PyExc_ZeroDivisionError, "float divmod()"); - return NULL; - } - PyFPE_START_PROTECT("divmod", return 0) - mod = fmod(vx, wx); - /* fmod is typically exact, so vx-mod is *mathematically* an - exact multiple of wx. But this is fp arithmetic, and fp - vx - mod is an approximation; the result is that div may - not be an exact integral value after the division, although - it will always be very close to one. - */ - div = (vx - mod) / wx; - if (mod) { - /* ensure the remainder has the same sign as the denominator */ - if ((wx < 0) != (mod < 0)) { - mod += wx; - div -= 1.0; - } - } - else { - /* the remainder is zero, and in the presence of signed zeroes - fmod returns different results across platforms; ensure - it has the same sign as the denominator; we'd like to do - "mod = wx * 0.0", but that may get optimized away */ - mod *= mod; /* hide "mod = +0" from optimizer */ - if (wx < 0.0) - mod = -mod; - } - /* snap quotient to nearest integral value */ - if (div) { - floordiv = floor(div); - if (div - floordiv > 0.5) - floordiv += 1.0; - } - else { - /* div is zero - get the same sign as the true quotient */ - div *= div; /* hide "div = +0" from optimizers */ - floordiv = div * vx / wx; /* zero w/ sign of vx/wx */ - } - PyFPE_END_PROTECT(floordiv) - return Py_BuildValue("(dd)", floordiv, mod); + double vx, wx; + double div, mod, floordiv; + CONVERT_TO_DOUBLE(v, vx); + CONVERT_TO_DOUBLE(w, wx); + if (wx == 0.0) { + PyErr_SetString(PyExc_ZeroDivisionError, "float divmod()"); + return NULL; + } + PyFPE_START_PROTECT("divmod", return 0) + mod = fmod(vx, wx); + /* fmod is typically exact, so vx-mod is *mathematically* an + exact multiple of wx. But this is fp arithmetic, and fp + vx - mod is an approximation; the result is that div may + not be an exact integral value after the division, although + it will always be very close to one. + */ + div = (vx - mod) / wx; + if (mod) { + /* ensure the remainder has the same sign as the denominator */ + if ((wx < 0) != (mod < 0)) { + mod += wx; + div -= 1.0; + } + } + else { + /* the remainder is zero, and in the presence of signed zeroes + fmod returns different results across platforms; ensure + it has the same sign as the denominator; we'd like to do + "mod = wx * 0.0", but that may get optimized away */ + mod *= mod; /* hide "mod = +0" from optimizer */ + if (wx < 0.0) + mod = -mod; + } + /* snap quotient to nearest integral value */ + if (div) { + floordiv = floor(div); + if (div - floordiv > 0.5) + floordiv += 1.0; + } + else { + /* div is zero - get the same sign as the true quotient */ + div *= div; /* hide "div = +0" from optimizers */ + floordiv = div * vx / wx; /* zero w/ sign of vx/wx */ + } + PyFPE_END_PROTECT(floordiv) + return Py_BuildValue("(dd)", floordiv, mod); } static PyObject * float_floor_div(PyObject *v, PyObject *w) { - PyObject *t, *r; + PyObject *t, *r; - t = float_divmod(v, w); - if (t == NULL || t == Py_NotImplemented) - return t; - assert(PyTuple_CheckExact(t)); - r = PyTuple_GET_ITEM(t, 0); - Py_INCREF(r); - Py_DECREF(t); - return r; + t = float_divmod(v, w); + if (t == NULL || t == Py_NotImplemented) + return t; + assert(PyTuple_CheckExact(t)); + r = PyTuple_GET_ITEM(t, 0); + Py_INCREF(r); + Py_DECREF(t); + return r; } /* determine whether x is an odd integer or not; assumes that @@ -678,123 +678,123 @@ static PyObject * float_pow(PyObject *v, PyObject *w, PyObject *z) { - double iv, iw, ix; - int negate_result = 0; + double iv, iw, ix; + int negate_result = 0; - if ((PyObject *)z != Py_None) { - PyErr_SetString(PyExc_TypeError, "pow() 3rd argument not " - "allowed unless all arguments are integers"); - return NULL; - } - - CONVERT_TO_DOUBLE(v, iv); - CONVERT_TO_DOUBLE(w, iw); - - /* Sort out special cases here instead of relying on pow() */ - if (iw == 0) { /* v**0 is 1, even 0**0 */ - return PyFloat_FromDouble(1.0); - } - if (Py_IS_NAN(iv)) { /* nan**w = nan, unless w == 0 */ - return PyFloat_FromDouble(iv); - } - if (Py_IS_NAN(iw)) { /* v**nan = nan, unless v == 1; 1**nan = 1 */ - return PyFloat_FromDouble(iv == 1.0 ? 1.0 : iw); - } - if (Py_IS_INFINITY(iw)) { - /* v**inf is: 0.0 if abs(v) < 1; 1.0 if abs(v) == 1; inf if - * abs(v) > 1 (including case where v infinite) - * - * v**-inf is: inf if abs(v) < 1; 1.0 if abs(v) == 1; 0.0 if - * abs(v) > 1 (including case where v infinite) - */ - iv = fabs(iv); - if (iv == 1.0) - return PyFloat_FromDouble(1.0); - else if ((iw > 0.0) == (iv > 1.0)) - return PyFloat_FromDouble(fabs(iw)); /* return inf */ - else - return PyFloat_FromDouble(0.0); - } - if (Py_IS_INFINITY(iv)) { - /* (+-inf)**w is: inf for w positive, 0 for w negative; in - * both cases, we need to add the appropriate sign if w is - * an odd integer. - */ - int iw_is_odd = DOUBLE_IS_ODD_INTEGER(iw); - if (iw > 0.0) - return PyFloat_FromDouble(iw_is_odd ? iv : fabs(iv)); - else - return PyFloat_FromDouble(iw_is_odd ? - copysign(0.0, iv) : 0.0); - } - if (iv == 0.0) { /* 0**w is: 0 for w positive, 1 for w zero - (already dealt with above), and an error - if w is negative. */ - int iw_is_odd = DOUBLE_IS_ODD_INTEGER(iw); - if (iw < 0.0) { - PyErr_SetString(PyExc_ZeroDivisionError, - "0.0 cannot be raised to a " - "negative power"); - return NULL; - } - /* use correct sign if iw is odd */ - return PyFloat_FromDouble(iw_is_odd ? iv : 0.0); - } - - if (iv < 0.0) { - /* Whether this is an error is a mess, and bumps into libm - * bugs so we have to figure it out ourselves. - */ - if (iw != floor(iw)) { - /* Negative numbers raised to fractional powers - * become complex. - */ - return PyComplex_Type.tp_as_number->nb_power(v, w, z); - } - /* iw is an exact integer, albeit perhaps a very large - * one. Replace iv by its absolute value and remember - * to negate the pow result if iw is odd. - */ - iv = -iv; - negate_result = DOUBLE_IS_ODD_INTEGER(iw); - } - - if (iv == 1.0) { /* 1**w is 1, even 1**inf and 1**nan */ - /* (-1) ** large_integer also ends up here. Here's an - * extract from the comments for the previous - * implementation explaining why this special case is - * necessary: - * - * -1 raised to an exact integer should never be exceptional. - * Alas, some libms (chiefly glibc as of early 2003) return - * NaN and set EDOM on pow(-1, large_int) if the int doesn't - * happen to be representable in a *C* integer. That's a - * bug. - */ - return PyFloat_FromDouble(negate_result ? -1.0 : 1.0); - } - - /* Now iv and iw are finite, iw is nonzero, and iv is - * positive and not equal to 1.0. We finally allow - * the platform pow to step in and do the rest. - */ - errno = 0; - PyFPE_START_PROTECT("pow", return NULL) - ix = pow(iv, iw); - PyFPE_END_PROTECT(ix) - Py_ADJUST_ERANGE1(ix); - if (negate_result) - ix = -ix; - - if (errno != 0) { - /* We don't expect any errno value other than ERANGE, but - * the range of libm bugs appears unbounded. - */ - PyErr_SetFromErrno(errno == ERANGE ? PyExc_OverflowError : - PyExc_ValueError); - return NULL; - } - return PyFloat_FromDouble(ix); + if ((PyObject *)z != Py_None) { + PyErr_SetString(PyExc_TypeError, "pow() 3rd argument not " + "allowed unless all arguments are integers"); + return NULL; + } + + CONVERT_TO_DOUBLE(v, iv); + CONVERT_TO_DOUBLE(w, iw); + + /* Sort out special cases here instead of relying on pow() */ + if (iw == 0) { /* v**0 is 1, even 0**0 */ + return PyFloat_FromDouble(1.0); + } + if (Py_IS_NAN(iv)) { /* nan**w = nan, unless w == 0 */ + return PyFloat_FromDouble(iv); + } + if (Py_IS_NAN(iw)) { /* v**nan = nan, unless v == 1; 1**nan = 1 */ + return PyFloat_FromDouble(iv == 1.0 ? 1.0 : iw); + } + if (Py_IS_INFINITY(iw)) { + /* v**inf is: 0.0 if abs(v) < 1; 1.0 if abs(v) == 1; inf if + * abs(v) > 1 (including case where v infinite) + * + * v**-inf is: inf if abs(v) < 1; 1.0 if abs(v) == 1; 0.0 if + * abs(v) > 1 (including case where v infinite) + */ + iv = fabs(iv); + if (iv == 1.0) + return PyFloat_FromDouble(1.0); + else if ((iw > 0.0) == (iv > 1.0)) + return PyFloat_FromDouble(fabs(iw)); /* return inf */ + else + return PyFloat_FromDouble(0.0); + } + if (Py_IS_INFINITY(iv)) { + /* (+-inf)**w is: inf for w positive, 0 for w negative; in + * both cases, we need to add the appropriate sign if w is + * an odd integer. + */ + int iw_is_odd = DOUBLE_IS_ODD_INTEGER(iw); + if (iw > 0.0) + return PyFloat_FromDouble(iw_is_odd ? iv : fabs(iv)); + else + return PyFloat_FromDouble(iw_is_odd ? + copysign(0.0, iv) : 0.0); + } + if (iv == 0.0) { /* 0**w is: 0 for w positive, 1 for w zero + (already dealt with above), and an error + if w is negative. */ + int iw_is_odd = DOUBLE_IS_ODD_INTEGER(iw); + if (iw < 0.0) { + PyErr_SetString(PyExc_ZeroDivisionError, + "0.0 cannot be raised to a " + "negative power"); + return NULL; + } + /* use correct sign if iw is odd */ + return PyFloat_FromDouble(iw_is_odd ? iv : 0.0); + } + + if (iv < 0.0) { + /* Whether this is an error is a mess, and bumps into libm + * bugs so we have to figure it out ourselves. + */ + if (iw != floor(iw)) { + /* Negative numbers raised to fractional powers + * become complex. + */ + return PyComplex_Type.tp_as_number->nb_power(v, w, z); + } + /* iw is an exact integer, albeit perhaps a very large + * one. Replace iv by its absolute value and remember + * to negate the pow result if iw is odd. + */ + iv = -iv; + negate_result = DOUBLE_IS_ODD_INTEGER(iw); + } + + if (iv == 1.0) { /* 1**w is 1, even 1**inf and 1**nan */ + /* (-1) ** large_integer also ends up here. Here's an + * extract from the comments for the previous + * implementation explaining why this special case is + * necessary: + * + * -1 raised to an exact integer should never be exceptional. + * Alas, some libms (chiefly glibc as of early 2003) return + * NaN and set EDOM on pow(-1, large_int) if the int doesn't + * happen to be representable in a *C* integer. That's a + * bug. + */ + return PyFloat_FromDouble(negate_result ? -1.0 : 1.0); + } + + /* Now iv and iw are finite, iw is nonzero, and iv is + * positive and not equal to 1.0. We finally allow + * the platform pow to step in and do the rest. + */ + errno = 0; + PyFPE_START_PROTECT("pow", return NULL) + ix = pow(iv, iw); + PyFPE_END_PROTECT(ix) + Py_ADJUST_ERANGE1(ix); + if (negate_result) + ix = -ix; + + if (errno != 0) { + /* We don't expect any errno value other than ERANGE, but + * the range of libm bugs appears unbounded. + */ + PyErr_SetFromErrno(errno == ERANGE ? PyExc_OverflowError : + PyExc_ValueError); + return NULL; + } + return PyFloat_FromDouble(ix); } #undef DOUBLE_IS_ODD_INTEGER @@ -802,97 +802,97 @@ static PyObject * float_neg(PyFloatObject *v) { - return PyFloat_FromDouble(-v->ob_fval); + return PyFloat_FromDouble(-v->ob_fval); } static PyObject * float_abs(PyFloatObject *v) { - return PyFloat_FromDouble(fabs(v->ob_fval)); + return PyFloat_FromDouble(fabs(v->ob_fval)); } static int float_bool(PyFloatObject *v) { - return v->ob_fval != 0.0; + return v->ob_fval != 0.0; } static PyObject * float_is_integer(PyObject *v) { - double x = PyFloat_AsDouble(v); - PyObject *o; - - if (x == -1.0 && PyErr_Occurred()) - return NULL; - if (!Py_IS_FINITE(x)) - Py_RETURN_FALSE; - errno = 0; - PyFPE_START_PROTECT("is_integer", return NULL) - o = (floor(x) == x) ? Py_True : Py_False; - PyFPE_END_PROTECT(x) - if (errno != 0) { - PyErr_SetFromErrno(errno == ERANGE ? PyExc_OverflowError : - PyExc_ValueError); - return NULL; - } - Py_INCREF(o); - return o; + double x = PyFloat_AsDouble(v); + PyObject *o; + + if (x == -1.0 && PyErr_Occurred()) + return NULL; + if (!Py_IS_FINITE(x)) + Py_RETURN_FALSE; + errno = 0; + PyFPE_START_PROTECT("is_integer", return NULL) + o = (floor(x) == x) ? Py_True : Py_False; + PyFPE_END_PROTECT(x) + if (errno != 0) { + PyErr_SetFromErrno(errno == ERANGE ? PyExc_OverflowError : + PyExc_ValueError); + return NULL; + } + Py_INCREF(o); + return o; } #if 0 static PyObject * float_is_inf(PyObject *v) { - double x = PyFloat_AsDouble(v); - if (x == -1.0 && PyErr_Occurred()) - return NULL; - return PyBool_FromLong((long)Py_IS_INFINITY(x)); + double x = PyFloat_AsDouble(v); + if (x == -1.0 && PyErr_Occurred()) + return NULL; + return PyBool_FromLong((long)Py_IS_INFINITY(x)); } static PyObject * float_is_nan(PyObject *v) { - double x = PyFloat_AsDouble(v); - if (x == -1.0 && PyErr_Occurred()) - return NULL; - return PyBool_FromLong((long)Py_IS_NAN(x)); + double x = PyFloat_AsDouble(v); + if (x == -1.0 && PyErr_Occurred()) + return NULL; + return PyBool_FromLong((long)Py_IS_NAN(x)); } static PyObject * float_is_finite(PyObject *v) { - double x = PyFloat_AsDouble(v); - if (x == -1.0 && PyErr_Occurred()) - return NULL; - return PyBool_FromLong((long)Py_IS_FINITE(x)); + double x = PyFloat_AsDouble(v); + if (x == -1.0 && PyErr_Occurred()) + return NULL; + return PyBool_FromLong((long)Py_IS_FINITE(x)); } #endif static PyObject * float_trunc(PyObject *v) { - double x = PyFloat_AsDouble(v); - double wholepart; /* integral portion of x, rounded toward 0 */ + double x = PyFloat_AsDouble(v); + double wholepart; /* integral portion of x, rounded toward 0 */ - (void)modf(x, &wholepart); - /* Try to get out cheap if this fits in a Python int. The attempt - * to cast to long must be protected, as C doesn't define what - * happens if the double is too big to fit in a long. Some rare - * systems raise an exception then (RISCOS was mentioned as one, - * and someone using a non-default option on Sun also bumped into - * that). Note that checking for >= and <= LONG_{MIN,MAX} would - * still be vulnerable: if a long has more bits of precision than - * a double, casting MIN/MAX to double may yield an approximation, - * and if that's rounded up, then, e.g., wholepart=LONG_MAX+1 would - * yield true from the C expression wholepart<=LONG_MAX, despite - * that wholepart is actually greater than LONG_MAX. - */ - if (LONG_MIN < wholepart && wholepart < LONG_MAX) { - const long aslong = (long)wholepart; - return PyLong_FromLong(aslong); - } - return PyLong_FromDouble(wholepart); + (void)modf(x, &wholepart); + /* Try to get out cheap if this fits in a Python int. The attempt + * to cast to long must be protected, as C doesn't define what + * happens if the double is too big to fit in a long. Some rare + * systems raise an exception then (RISCOS was mentioned as one, + * and someone using a non-default option on Sun also bumped into + * that). Note that checking for >= and <= LONG_{MIN,MAX} would + * still be vulnerable: if a long has more bits of precision than + * a double, casting MIN/MAX to double may yield an approximation, + * and if that's rounded up, then, e.g., wholepart=LONG_MAX+1 would + * yield true from the C expression wholepart<=LONG_MAX, despite + * that wholepart is actually greater than LONG_MAX. + */ + if (LONG_MIN < wholepart && wholepart < LONG_MAX) { + const long aslong = (long)wholepart; + return PyLong_FromLong(aslong); + } + return PyLong_FromDouble(wholepart); } /* double_round: rounds a finite double to the closest multiple of @@ -907,49 +907,49 @@ static PyObject * double_round(double x, int ndigits) { - double rounded; - Py_ssize_t buflen, mybuflen=100; - char *buf, *buf_end, shortbuf[100], *mybuf=shortbuf; - int decpt, sign; - PyObject *result = NULL; - - /* round to a decimal string */ - buf = _Py_dg_dtoa(x, 3, ndigits, &decpt, &sign, &buf_end); - if (buf == NULL) { - PyErr_NoMemory(); - return NULL; - } - - /* Get new buffer if shortbuf is too small. Space needed <= buf_end - - buf + 8: (1 extra for '0', 1 for sign, 5 for exp, 1 for '\0'). */ - buflen = buf_end - buf; - if (buflen + 8 > mybuflen) { - mybuflen = buflen+8; - mybuf = (char *)PyMem_Malloc(mybuflen); - if (mybuf == NULL) { - PyErr_NoMemory(); - goto exit; - } - } - /* copy buf to mybuf, adding exponent, sign and leading 0 */ - PyOS_snprintf(mybuf, mybuflen, "%s0%se%d", (sign ? "-" : ""), - buf, decpt - (int)buflen); - - /* and convert the resulting string back to a double */ - errno = 0; - rounded = _Py_dg_strtod(mybuf, NULL); - if (errno == ERANGE && fabs(rounded) >= 1.) - PyErr_SetString(PyExc_OverflowError, - "rounded value too large to represent"); - else - result = PyFloat_FromDouble(rounded); - - /* done computing value; now clean up */ - if (mybuf != shortbuf) - PyMem_Free(mybuf); + double rounded; + Py_ssize_t buflen, mybuflen=100; + char *buf, *buf_end, shortbuf[100], *mybuf=shortbuf; + int decpt, sign; + PyObject *result = NULL; + + /* round to a decimal string */ + buf = _Py_dg_dtoa(x, 3, ndigits, &decpt, &sign, &buf_end); + if (buf == NULL) { + PyErr_NoMemory(); + return NULL; + } + + /* Get new buffer if shortbuf is too small. Space needed <= buf_end - + buf + 8: (1 extra for '0', 1 for sign, 5 for exp, 1 for '\0'). */ + buflen = buf_end - buf; + if (buflen + 8 > mybuflen) { + mybuflen = buflen+8; + mybuf = (char *)PyMem_Malloc(mybuflen); + if (mybuf == NULL) { + PyErr_NoMemory(); + goto exit; + } + } + /* copy buf to mybuf, adding exponent, sign and leading 0 */ + PyOS_snprintf(mybuf, mybuflen, "%s0%se%d", (sign ? "-" : ""), + buf, decpt - (int)buflen); + + /* and convert the resulting string back to a double */ + errno = 0; + rounded = _Py_dg_strtod(mybuf, NULL); + if (errno == ERANGE && fabs(rounded) >= 1.) + PyErr_SetString(PyExc_OverflowError, + "rounded value too large to represent"); + else + result = PyFloat_FromDouble(rounded); + + /* done computing value; now clean up */ + if (mybuf != shortbuf) + PyMem_Free(mybuf); exit: - _Py_dg_freedtoa(buf); - return result; + _Py_dg_freedtoa(buf); + return result; } #else /* PY_NO_SHORT_FLOAT_REPR */ @@ -959,47 +959,47 @@ static PyObject * double_round(double x, int ndigits) { - double pow1, pow2, y, z; - if (ndigits >= 0) { - if (ndigits > 22) { - /* pow1 and pow2 are each safe from overflow, but - pow1*pow2 ~= pow(10.0, ndigits) might overflow */ - pow1 = pow(10.0, (double)(ndigits-22)); - pow2 = 1e22; - } - else { - pow1 = pow(10.0, (double)ndigits); - pow2 = 1.0; - } - y = (x*pow1)*pow2; - /* if y overflows, then rounded value is exactly x */ - if (!Py_IS_FINITE(y)) - return PyFloat_FromDouble(x); - } - else { - pow1 = pow(10.0, (double)-ndigits); - pow2 = 1.0; /* unused; silences a gcc compiler warning */ - y = x / pow1; - } - - z = round(y); - if (fabs(y-z) == 0.5) - /* halfway between two integers; use round-half-even */ - z = 2.0*round(y/2.0); - - if (ndigits >= 0) - z = (z / pow2) / pow1; - else - z *= pow1; - - /* if computation resulted in overflow, raise OverflowError */ - if (!Py_IS_FINITE(z)) { - PyErr_SetString(PyExc_OverflowError, - "overflow occurred during round"); - return NULL; - } + double pow1, pow2, y, z; + if (ndigits >= 0) { + if (ndigits > 22) { + /* pow1 and pow2 are each safe from overflow, but + pow1*pow2 ~= pow(10.0, ndigits) might overflow */ + pow1 = pow(10.0, (double)(ndigits-22)); + pow2 = 1e22; + } + else { + pow1 = pow(10.0, (double)ndigits); + pow2 = 1.0; + } + y = (x*pow1)*pow2; + /* if y overflows, then rounded value is exactly x */ + if (!Py_IS_FINITE(y)) + return PyFloat_FromDouble(x); + } + else { + pow1 = pow(10.0, (double)-ndigits); + pow2 = 1.0; /* unused; silences a gcc compiler warning */ + y = x / pow1; + } + + z = round(y); + if (fabs(y-z) == 0.5) + /* halfway between two integers; use round-half-even */ + z = 2.0*round(y/2.0); + + if (ndigits >= 0) + z = (z / pow2) / pow1; + else + z *= pow1; + + /* if computation resulted in overflow, raise OverflowError */ + if (!Py_IS_FINITE(z)) { + PyErr_SetString(PyExc_OverflowError, + "overflow occurred during round"); + return NULL; + } - return PyFloat_FromDouble(z); + return PyFloat_FromDouble(z); } #endif /* PY_NO_SHORT_FLOAT_REPR */ @@ -1009,45 +1009,45 @@ static PyObject * float_round(PyObject *v, PyObject *args) { - double x, rounded; - PyObject *o_ndigits = NULL; - Py_ssize_t ndigits; - - x = PyFloat_AsDouble(v); - if (!PyArg_ParseTuple(args, "|O", &o_ndigits)) - return NULL; - if (o_ndigits == NULL) { - /* single-argument round: round to nearest integer */ - rounded = round(x); - if (fabs(x-rounded) == 0.5) - /* halfway case: round to even */ - rounded = 2.0*round(x/2.0); - return PyLong_FromDouble(rounded); - } - - /* interpret second argument as a Py_ssize_t; clips on overflow */ - ndigits = PyNumber_AsSsize_t(o_ndigits, NULL); - if (ndigits == -1 && PyErr_Occurred()) - return NULL; - - /* nans and infinities round to themselves */ - if (!Py_IS_FINITE(x)) - return PyFloat_FromDouble(x); - - /* Deal with extreme values for ndigits. For ndigits > NDIGITS_MAX, x - always rounds to itself. For ndigits < NDIGITS_MIN, x always - rounds to +-0.0. Here 0.30103 is an upper bound for log10(2). */ + double x, rounded; + PyObject *o_ndigits = NULL; + Py_ssize_t ndigits; + + x = PyFloat_AsDouble(v); + if (!PyArg_ParseTuple(args, "|O", &o_ndigits)) + return NULL; + if (o_ndigits == NULL) { + /* single-argument round: round to nearest integer */ + rounded = round(x); + if (fabs(x-rounded) == 0.5) + /* halfway case: round to even */ + rounded = 2.0*round(x/2.0); + return PyLong_FromDouble(rounded); + } + + /* interpret second argument as a Py_ssize_t; clips on overflow */ + ndigits = PyNumber_AsSsize_t(o_ndigits, NULL); + if (ndigits == -1 && PyErr_Occurred()) + return NULL; + + /* nans and infinities round to themselves */ + if (!Py_IS_FINITE(x)) + return PyFloat_FromDouble(x); + + /* Deal with extreme values for ndigits. For ndigits > NDIGITS_MAX, x + always rounds to itself. For ndigits < NDIGITS_MIN, x always + rounds to +-0.0. Here 0.30103 is an upper bound for log10(2). */ #define NDIGITS_MAX ((int)((DBL_MANT_DIG-DBL_MIN_EXP) * 0.30103)) #define NDIGITS_MIN (-(int)((DBL_MAX_EXP + 1) * 0.30103)) - if (ndigits > NDIGITS_MAX) - /* return x */ - return PyFloat_FromDouble(x); - else if (ndigits < NDIGITS_MIN) - /* return 0.0, but with sign of x */ - return PyFloat_FromDouble(0.0*x); - else - /* finite x, and ndigits is not unreasonably large */ - return double_round(x, (int)ndigits); + if (ndigits > NDIGITS_MAX) + /* return x */ + return PyFloat_FromDouble(x); + else if (ndigits < NDIGITS_MIN) + /* return 0.0, but with sign of x */ + return PyFloat_FromDouble(0.0*x); + else + /* finite x, and ndigits is not unreasonably large */ + return double_round(x, (int)ndigits); #undef NDIGITS_MAX #undef NDIGITS_MIN } @@ -1055,11 +1055,11 @@ static PyObject * float_float(PyObject *v) { - if (PyFloat_CheckExact(v)) - Py_INCREF(v); - else - v = PyFloat_FromDouble(((PyFloatObject *)v)->ob_fval); - return v; + if (PyFloat_CheckExact(v)) + Py_INCREF(v); + else + v = PyFloat_FromDouble(((PyFloatObject *)v)->ob_fval); + return v; } /* turn ASCII hex characters into integer values and vice versa */ @@ -1067,73 +1067,73 @@ static char char_from_hex(int x) { - assert(0 <= x && x < 16); - return "0123456789abcdef"[x]; + assert(0 <= x && x < 16); + return "0123456789abcdef"[x]; } static int hex_from_char(char c) { - int x; - switch(c) { - case '0': - x = 0; - break; - case '1': - x = 1; - break; - case '2': - x = 2; - break; - case '3': - x = 3; - break; - case '4': - x = 4; - break; - case '5': - x = 5; - break; - case '6': - x = 6; - break; - case '7': - x = 7; - break; - case '8': - x = 8; - break; - case '9': - x = 9; - break; - case 'a': - case 'A': - x = 10; - break; - case 'b': - case 'B': - x = 11; - break; - case 'c': - case 'C': - x = 12; - break; - case 'd': - case 'D': - x = 13; - break; - case 'e': - case 'E': - x = 14; - break; - case 'f': - case 'F': - x = 15; - break; - default: - x = -1; - break; - } - return x; + int x; + switch(c) { + case '0': + x = 0; + break; + case '1': + x = 1; + break; + case '2': + x = 2; + break; + case '3': + x = 3; + break; + case '4': + x = 4; + break; + case '5': + x = 5; + break; + case '6': + x = 6; + break; + case '7': + x = 7; + break; + case '8': + x = 8; + break; + case '9': + x = 9; + break; + case 'a': + case 'A': + x = 10; + break; + case 'b': + case 'B': + x = 11; + break; + case 'c': + case 'C': + x = 12; + break; + case 'd': + case 'D': + x = 13; + break; + case 'e': + case 'E': + x = 14; + break; + case 'f': + case 'F': + x = 15; + break; + default: + x = -1; + break; + } + return x; } /* convert a float to a hexadecimal string */ @@ -1145,54 +1145,54 @@ static PyObject * float_hex(PyObject *v) { - double x, m; - int e, shift, i, si, esign; - /* Space for 1+(TOHEX_NBITS-1)/4 digits, a decimal point, and the - trailing NUL byte. */ - char s[(TOHEX_NBITS-1)/4+3]; - - CONVERT_TO_DOUBLE(v, x); - - if (Py_IS_NAN(x) || Py_IS_INFINITY(x)) - return float_str((PyFloatObject *)v); - - if (x == 0.0) { - if(copysign(1.0, x) == -1.0) - return PyUnicode_FromString("-0x0.0p+0"); - else - return PyUnicode_FromString("0x0.0p+0"); - } - - m = frexp(fabs(x), &e); - shift = 1 - MAX(DBL_MIN_EXP - e, 0); - m = ldexp(m, shift); - e -= shift; - - si = 0; - s[si] = char_from_hex((int)m); - si++; - m -= (int)m; - s[si] = '.'; - si++; - for (i=0; i < (TOHEX_NBITS-1)/4; i++) { - m *= 16.0; - s[si] = char_from_hex((int)m); - si++; - m -= (int)m; - } - s[si] = '\0'; - - if (e < 0) { - esign = (int)'-'; - e = -e; - } - else - esign = (int)'+'; - - if (x < 0.0) - return PyUnicode_FromFormat("-0x%sp%c%d", s, esign, e); - else - return PyUnicode_FromFormat("0x%sp%c%d", s, esign, e); + double x, m; + int e, shift, i, si, esign; + /* Space for 1+(TOHEX_NBITS-1)/4 digits, a decimal point, and the + trailing NUL byte. */ + char s[(TOHEX_NBITS-1)/4+3]; + + CONVERT_TO_DOUBLE(v, x); + + if (Py_IS_NAN(x) || Py_IS_INFINITY(x)) + return float_str((PyFloatObject *)v); + + if (x == 0.0) { + if(copysign(1.0, x) == -1.0) + return PyUnicode_FromString("-0x0.0p+0"); + else + return PyUnicode_FromString("0x0.0p+0"); + } + + m = frexp(fabs(x), &e); + shift = 1 - MAX(DBL_MIN_EXP - e, 0); + m = ldexp(m, shift); + e -= shift; + + si = 0; + s[si] = char_from_hex((int)m); + si++; + m -= (int)m; + s[si] = '.'; + si++; + for (i=0; i < (TOHEX_NBITS-1)/4; i++) { + m *= 16.0; + s[si] = char_from_hex((int)m); + si++; + m -= (int)m; + } + s[si] = '\0'; + + if (e < 0) { + esign = (int)'-'; + e = -e; + } + else + esign = (int)'+'; + + if (x < 0.0) + return PyUnicode_FromFormat("-0x%sp%c%d", s, esign, e); + else + return PyUnicode_FromFormat("0x%sp%c%d", s, esign, e); } PyDoc_STRVAR(float_hex_doc, @@ -1209,242 +1209,242 @@ static PyObject * float_fromhex(PyObject *cls, PyObject *arg) { - PyObject *result_as_float, *result; - double x; - long exp, top_exp, lsb, key_digit; - char *s, *coeff_start, *s_store, *coeff_end, *exp_start, *s_end; - int half_eps, digit, round_up, negate=0; - Py_ssize_t length, ndigits, fdigits, i; - - /* - * For the sake of simplicity and correctness, we impose an artificial - * limit on ndigits, the total number of hex digits in the coefficient - * The limit is chosen to ensure that, writing exp for the exponent, - * - * (1) if exp > LONG_MAX/2 then the value of the hex string is - * guaranteed to overflow (provided it's nonzero) - * - * (2) if exp < LONG_MIN/2 then the value of the hex string is - * guaranteed to underflow to 0. - * - * (3) if LONG_MIN/2 <= exp <= LONG_MAX/2 then there's no danger of - * overflow in the calculation of exp and top_exp below. - * - * More specifically, ndigits is assumed to satisfy the following - * inequalities: - * - * 4*ndigits <= DBL_MIN_EXP - DBL_MANT_DIG - LONG_MIN/2 - * 4*ndigits <= LONG_MAX/2 + 1 - DBL_MAX_EXP - * - * If either of these inequalities is not satisfied, a ValueError is - * raised. Otherwise, write x for the value of the hex string, and - * assume x is nonzero. Then - * - * 2**(exp-4*ndigits) <= |x| < 2**(exp+4*ndigits). - * - * Now if exp > LONG_MAX/2 then: - * - * exp - 4*ndigits >= LONG_MAX/2 + 1 - (LONG_MAX/2 + 1 - DBL_MAX_EXP) - * = DBL_MAX_EXP - * - * so |x| >= 2**DBL_MAX_EXP, which is too large to be stored in C - * double, so overflows. If exp < LONG_MIN/2, then - * - * exp + 4*ndigits <= LONG_MIN/2 - 1 + ( - * DBL_MIN_EXP - DBL_MANT_DIG - LONG_MIN/2) - * = DBL_MIN_EXP - DBL_MANT_DIG - 1 - * - * and so |x| < 2**(DBL_MIN_EXP-DBL_MANT_DIG-1), hence underflows to 0 - * when converted to a C double. - * - * It's easy to show that if LONG_MIN/2 <= exp <= LONG_MAX/2 then both - * exp+4*ndigits and exp-4*ndigits are within the range of a long. - */ - - s = _PyUnicode_AsStringAndSize(arg, &length); - if (s == NULL) - return NULL; - s_end = s + length; - - /******************** - * Parse the string * - ********************/ - - /* leading whitespace */ - while (Py_ISSPACE(*s)) - s++; - - /* infinities and nans */ - x = _Py_parse_inf_or_nan(s, &coeff_end); - if (coeff_end != s) { - s = coeff_end; - goto finished; - } - - /* optional sign */ - if (*s == '-') { - s++; - negate = 1; - } - else if (*s == '+') - s++; - - /* [0x] */ - s_store = s; - if (*s == '0') { - s++; - if (*s == 'x' || *s == 'X') - s++; - else - s = s_store; - } - - /* coefficient: [. ] */ - coeff_start = s; - while (hex_from_char(*s) >= 0) - s++; - s_store = s; - if (*s == '.') { - s++; - while (hex_from_char(*s) >= 0) - s++; - coeff_end = s-1; - } - else - coeff_end = s; - - /* ndigits = total # of hex digits; fdigits = # after point */ - ndigits = coeff_end - coeff_start; - fdigits = coeff_end - s_store; - if (ndigits == 0) - goto parse_error; - if (ndigits > MIN(DBL_MIN_EXP - DBL_MANT_DIG - LONG_MIN/2, - LONG_MAX/2 + 1 - DBL_MAX_EXP)/4) - goto insane_length_error; - - /* [p ] */ - if (*s == 'p' || *s == 'P') { - s++; - exp_start = s; - if (*s == '-' || *s == '+') - s++; - if (!('0' <= *s && *s <= '9')) - goto parse_error; - s++; - while ('0' <= *s && *s <= '9') - s++; - exp = strtol(exp_start, NULL, 10); - } - else - exp = 0; + PyObject *result_as_float, *result; + double x; + long exp, top_exp, lsb, key_digit; + char *s, *coeff_start, *s_store, *coeff_end, *exp_start, *s_end; + int half_eps, digit, round_up, negate=0; + Py_ssize_t length, ndigits, fdigits, i; + + /* + * For the sake of simplicity and correctness, we impose an artificial + * limit on ndigits, the total number of hex digits in the coefficient + * The limit is chosen to ensure that, writing exp for the exponent, + * + * (1) if exp > LONG_MAX/2 then the value of the hex string is + * guaranteed to overflow (provided it's nonzero) + * + * (2) if exp < LONG_MIN/2 then the value of the hex string is + * guaranteed to underflow to 0. + * + * (3) if LONG_MIN/2 <= exp <= LONG_MAX/2 then there's no danger of + * overflow in the calculation of exp and top_exp below. + * + * More specifically, ndigits is assumed to satisfy the following + * inequalities: + * + * 4*ndigits <= DBL_MIN_EXP - DBL_MANT_DIG - LONG_MIN/2 + * 4*ndigits <= LONG_MAX/2 + 1 - DBL_MAX_EXP + * + * If either of these inequalities is not satisfied, a ValueError is + * raised. Otherwise, write x for the value of the hex string, and + * assume x is nonzero. Then + * + * 2**(exp-4*ndigits) <= |x| < 2**(exp+4*ndigits). + * + * Now if exp > LONG_MAX/2 then: + * + * exp - 4*ndigits >= LONG_MAX/2 + 1 - (LONG_MAX/2 + 1 - DBL_MAX_EXP) + * = DBL_MAX_EXP + * + * so |x| >= 2**DBL_MAX_EXP, which is too large to be stored in C + * double, so overflows. If exp < LONG_MIN/2, then + * + * exp + 4*ndigits <= LONG_MIN/2 - 1 + ( + * DBL_MIN_EXP - DBL_MANT_DIG - LONG_MIN/2) + * = DBL_MIN_EXP - DBL_MANT_DIG - 1 + * + * and so |x| < 2**(DBL_MIN_EXP-DBL_MANT_DIG-1), hence underflows to 0 + * when converted to a C double. + * + * It's easy to show that if LONG_MIN/2 <= exp <= LONG_MAX/2 then both + * exp+4*ndigits and exp-4*ndigits are within the range of a long. + */ + + s = _PyUnicode_AsStringAndSize(arg, &length); + if (s == NULL) + return NULL; + s_end = s + length; + + /******************** + * Parse the string * + ********************/ + + /* leading whitespace */ + while (Py_ISSPACE(*s)) + s++; + + /* infinities and nans */ + x = _Py_parse_inf_or_nan(s, &coeff_end); + if (coeff_end != s) { + s = coeff_end; + goto finished; + } + + /* optional sign */ + if (*s == '-') { + s++; + negate = 1; + } + else if (*s == '+') + s++; + + /* [0x] */ + s_store = s; + if (*s == '0') { + s++; + if (*s == 'x' || *s == 'X') + s++; + else + s = s_store; + } + + /* coefficient: [. ] */ + coeff_start = s; + while (hex_from_char(*s) >= 0) + s++; + s_store = s; + if (*s == '.') { + s++; + while (hex_from_char(*s) >= 0) + s++; + coeff_end = s-1; + } + else + coeff_end = s; + + /* ndigits = total # of hex digits; fdigits = # after point */ + ndigits = coeff_end - coeff_start; + fdigits = coeff_end - s_store; + if (ndigits == 0) + goto parse_error; + if (ndigits > MIN(DBL_MIN_EXP - DBL_MANT_DIG - LONG_MIN/2, + LONG_MAX/2 + 1 - DBL_MAX_EXP)/4) + goto insane_length_error; + + /* [p ] */ + if (*s == 'p' || *s == 'P') { + s++; + exp_start = s; + if (*s == '-' || *s == '+') + s++; + if (!('0' <= *s && *s <= '9')) + goto parse_error; + s++; + while ('0' <= *s && *s <= '9') + s++; + exp = strtol(exp_start, NULL, 10); + } + else + exp = 0; /* for 0 <= j < ndigits, HEX_DIGIT(j) gives the jth most significant digit */ -#define HEX_DIGIT(j) hex_from_char(*((j) < fdigits ? \ - coeff_end-(j) : \ - coeff_end-1-(j))) - - /******************************************* - * Compute rounded value of the hex string * - *******************************************/ - - /* Discard leading zeros, and catch extreme overflow and underflow */ - while (ndigits > 0 && HEX_DIGIT(ndigits-1) == 0) - ndigits--; - if (ndigits == 0 || exp < LONG_MIN/2) { - x = 0.0; - goto finished; - } - if (exp > LONG_MAX/2) - goto overflow_error; - - /* Adjust exponent for fractional part. */ - exp = exp - 4*((long)fdigits); - - /* top_exp = 1 more than exponent of most sig. bit of coefficient */ - top_exp = exp + 4*((long)ndigits - 1); - for (digit = HEX_DIGIT(ndigits-1); digit != 0; digit /= 2) - top_exp++; - - /* catch almost all nonextreme cases of overflow and underflow here */ - if (top_exp < DBL_MIN_EXP - DBL_MANT_DIG) { - x = 0.0; - goto finished; - } - if (top_exp > DBL_MAX_EXP) - goto overflow_error; - - /* lsb = exponent of least significant bit of the *rounded* value. - This is top_exp - DBL_MANT_DIG unless result is subnormal. */ - lsb = MAX(top_exp, (long)DBL_MIN_EXP) - DBL_MANT_DIG; - - x = 0.0; - if (exp >= lsb) { - /* no rounding required */ - for (i = ndigits-1; i >= 0; i--) - x = 16.0*x + HEX_DIGIT(i); - x = ldexp(x, (int)(exp)); - goto finished; - } - /* rounding required. key_digit is the index of the hex digit - containing the first bit to be rounded away. */ - half_eps = 1 << (int)((lsb - exp - 1) % 4); - key_digit = (lsb - exp - 1) / 4; - for (i = ndigits-1; i > key_digit; i--) - x = 16.0*x + HEX_DIGIT(i); - digit = HEX_DIGIT(key_digit); - x = 16.0*x + (double)(digit & (16-2*half_eps)); - - /* round-half-even: round up if bit lsb-1 is 1 and at least one of - bits lsb, lsb-2, lsb-3, lsb-4, ... is 1. */ - if ((digit & half_eps) != 0) { - round_up = 0; - if ((digit & (3*half_eps-1)) != 0 || - (half_eps == 8 && (HEX_DIGIT(key_digit+1) & 1) != 0)) - round_up = 1; - else - for (i = key_digit-1; i >= 0; i--) - if (HEX_DIGIT(i) != 0) { - round_up = 1; - break; - } - if (round_up == 1) { - x += 2*half_eps; - if (top_exp == DBL_MAX_EXP && - x == ldexp((double)(2*half_eps), DBL_MANT_DIG)) - /* overflow corner case: pre-rounded value < - 2**DBL_MAX_EXP; rounded=2**DBL_MAX_EXP. */ - goto overflow_error; - } - } - x = ldexp(x, (int)(exp+4*key_digit)); +#define HEX_DIGIT(j) hex_from_char(*((j) < fdigits ? \ + coeff_end-(j) : \ + coeff_end-1-(j))) + + /******************************************* + * Compute rounded value of the hex string * + *******************************************/ + + /* Discard leading zeros, and catch extreme overflow and underflow */ + while (ndigits > 0 && HEX_DIGIT(ndigits-1) == 0) + ndigits--; + if (ndigits == 0 || exp < LONG_MIN/2) { + x = 0.0; + goto finished; + } + if (exp > LONG_MAX/2) + goto overflow_error; + + /* Adjust exponent for fractional part. */ + exp = exp - 4*((long)fdigits); + + /* top_exp = 1 more than exponent of most sig. bit of coefficient */ + top_exp = exp + 4*((long)ndigits - 1); + for (digit = HEX_DIGIT(ndigits-1); digit != 0; digit /= 2) + top_exp++; + + /* catch almost all nonextreme cases of overflow and underflow here */ + if (top_exp < DBL_MIN_EXP - DBL_MANT_DIG) { + x = 0.0; + goto finished; + } + if (top_exp > DBL_MAX_EXP) + goto overflow_error; + + /* lsb = exponent of least significant bit of the *rounded* value. + This is top_exp - DBL_MANT_DIG unless result is subnormal. */ + lsb = MAX(top_exp, (long)DBL_MIN_EXP) - DBL_MANT_DIG; + + x = 0.0; + if (exp >= lsb) { + /* no rounding required */ + for (i = ndigits-1; i >= 0; i--) + x = 16.0*x + HEX_DIGIT(i); + x = ldexp(x, (int)(exp)); + goto finished; + } + /* rounding required. key_digit is the index of the hex digit + containing the first bit to be rounded away. */ + half_eps = 1 << (int)((lsb - exp - 1) % 4); + key_digit = (lsb - exp - 1) / 4; + for (i = ndigits-1; i > key_digit; i--) + x = 16.0*x + HEX_DIGIT(i); + digit = HEX_DIGIT(key_digit); + x = 16.0*x + (double)(digit & (16-2*half_eps)); + + /* round-half-even: round up if bit lsb-1 is 1 and at least one of + bits lsb, lsb-2, lsb-3, lsb-4, ... is 1. */ + if ((digit & half_eps) != 0) { + round_up = 0; + if ((digit & (3*half_eps-1)) != 0 || + (half_eps == 8 && (HEX_DIGIT(key_digit+1) & 1) != 0)) + round_up = 1; + else + for (i = key_digit-1; i >= 0; i--) + if (HEX_DIGIT(i) != 0) { + round_up = 1; + break; + } + if (round_up == 1) { + x += 2*half_eps; + if (top_exp == DBL_MAX_EXP && + x == ldexp((double)(2*half_eps), DBL_MANT_DIG)) + /* overflow corner case: pre-rounded value < + 2**DBL_MAX_EXP; rounded=2**DBL_MAX_EXP. */ + goto overflow_error; + } + } + x = ldexp(x, (int)(exp+4*key_digit)); finished: - /* optional trailing whitespace leading to the end of the string */ - while (Py_ISSPACE(*s)) - s++; - if (s != s_end) - goto parse_error; - result_as_float = Py_BuildValue("(d)", negate ? -x : x); - if (result_as_float == NULL) - return NULL; - result = PyObject_CallObject(cls, result_as_float); - Py_DECREF(result_as_float); - return result; + /* optional trailing whitespace leading to the end of the string */ + while (Py_ISSPACE(*s)) + s++; + if (s != s_end) + goto parse_error; + result_as_float = Py_BuildValue("(d)", negate ? -x : x); + if (result_as_float == NULL) + return NULL; + result = PyObject_CallObject(cls, result_as_float); + Py_DECREF(result_as_float); + return result; overflow_error: - PyErr_SetString(PyExc_OverflowError, - "hexadecimal value too large to represent as a float"); - return NULL; + PyErr_SetString(PyExc_OverflowError, + "hexadecimal value too large to represent as a float"); + return NULL; parse_error: - PyErr_SetString(PyExc_ValueError, - "invalid hexadecimal floating-point string"); - return NULL; + PyErr_SetString(PyExc_ValueError, + "invalid hexadecimal floating-point string"); + return NULL; insane_length_error: - PyErr_SetString(PyExc_ValueError, - "hexadecimal string too long to convert"); - return NULL; + PyErr_SetString(PyExc_ValueError, + "hexadecimal string too long to convert"); + return NULL; } PyDoc_STRVAR(float_fromhex_doc, @@ -1460,79 +1460,79 @@ static PyObject * float_as_integer_ratio(PyObject *v, PyObject *unused) { - double self; - double float_part; - int exponent; - int i; - - PyObject *prev; - PyObject *py_exponent = NULL; - PyObject *numerator = NULL; - PyObject *denominator = NULL; - PyObject *result_pair = NULL; - PyNumberMethods *long_methods = PyLong_Type.tp_as_number; + double self; + double float_part; + int exponent; + int i; + + PyObject *prev; + PyObject *py_exponent = NULL; + PyObject *numerator = NULL; + PyObject *denominator = NULL; + PyObject *result_pair = NULL; + PyNumberMethods *long_methods = PyLong_Type.tp_as_number; #define INPLACE_UPDATE(obj, call) \ - prev = obj; \ - obj = call; \ - Py_DECREF(prev); \ - - CONVERT_TO_DOUBLE(v, self); - - if (Py_IS_INFINITY(self)) { - PyErr_SetString(PyExc_OverflowError, - "Cannot pass infinity to float.as_integer_ratio."); - return NULL; - } + prev = obj; \ + obj = call; \ + Py_DECREF(prev); \ + + CONVERT_TO_DOUBLE(v, self); + + if (Py_IS_INFINITY(self)) { + PyErr_SetString(PyExc_OverflowError, + "Cannot pass infinity to float.as_integer_ratio."); + return NULL; + } #ifdef Py_NAN - if (Py_IS_NAN(self)) { - PyErr_SetString(PyExc_ValueError, - "Cannot pass NaN to float.as_integer_ratio."); - return NULL; - } + if (Py_IS_NAN(self)) { + PyErr_SetString(PyExc_ValueError, + "Cannot pass NaN to float.as_integer_ratio."); + return NULL; + } #endif - PyFPE_START_PROTECT("as_integer_ratio", goto error); - float_part = frexp(self, &exponent); /* self == float_part * 2**exponent exactly */ - PyFPE_END_PROTECT(float_part); - - for (i=0; i<300 && float_part != floor(float_part) ; i++) { - float_part *= 2.0; - exponent--; - } - /* self == float_part * 2**exponent exactly and float_part is integral. - If FLT_RADIX != 2, the 300 steps may leave a tiny fractional part - to be truncated by PyLong_FromDouble(). */ - - numerator = PyLong_FromDouble(float_part); - if (numerator == NULL) goto error; - - /* fold in 2**exponent */ - denominator = PyLong_FromLong(1); - py_exponent = PyLong_FromLong(labs((long)exponent)); - if (py_exponent == NULL) goto error; - INPLACE_UPDATE(py_exponent, - long_methods->nb_lshift(denominator, py_exponent)); - if (py_exponent == NULL) goto error; - if (exponent > 0) { - INPLACE_UPDATE(numerator, - long_methods->nb_multiply(numerator, py_exponent)); - if (numerator == NULL) goto error; - } - else { - Py_DECREF(denominator); - denominator = py_exponent; - py_exponent = NULL; - } + PyFPE_START_PROTECT("as_integer_ratio", goto error); + float_part = frexp(self, &exponent); /* self == float_part * 2**exponent exactly */ + PyFPE_END_PROTECT(float_part); + + for (i=0; i<300 && float_part != floor(float_part) ; i++) { + float_part *= 2.0; + exponent--; + } + /* self == float_part * 2**exponent exactly and float_part is integral. + If FLT_RADIX != 2, the 300 steps may leave a tiny fractional part + to be truncated by PyLong_FromDouble(). */ + + numerator = PyLong_FromDouble(float_part); + if (numerator == NULL) goto error; + + /* fold in 2**exponent */ + denominator = PyLong_FromLong(1); + py_exponent = PyLong_FromLong(labs((long)exponent)); + if (py_exponent == NULL) goto error; + INPLACE_UPDATE(py_exponent, + long_methods->nb_lshift(denominator, py_exponent)); + if (py_exponent == NULL) goto error; + if (exponent > 0) { + INPLACE_UPDATE(numerator, + long_methods->nb_multiply(numerator, py_exponent)); + if (numerator == NULL) goto error; + } + else { + Py_DECREF(denominator); + denominator = py_exponent; + py_exponent = NULL; + } - result_pair = PyTuple_Pack(2, numerator, denominator); + result_pair = PyTuple_Pack(2, numerator, denominator); #undef INPLACE_UPDATE error: - Py_XDECREF(py_exponent); - Py_XDECREF(denominator); - Py_XDECREF(numerator); - return result_pair; + Py_XDECREF(py_exponent); + Py_XDECREF(denominator); + Py_XDECREF(numerator); + return result_pair; } PyDoc_STRVAR(float_as_integer_ratio_doc, @@ -1556,18 +1556,18 @@ static PyObject * float_new(PyTypeObject *type, PyObject *args, PyObject *kwds) { - PyObject *x = Py_False; /* Integer zero */ - static char *kwlist[] = {"x", 0}; + PyObject *x = Py_False; /* Integer zero */ + static char *kwlist[] = {"x", 0}; - if (type != &PyFloat_Type) - return float_subtype_new(type, args, kwds); /* Wimp out */ - if (!PyArg_ParseTupleAndKeywords(args, kwds, "|O:float", kwlist, &x)) - return NULL; - /* If it's a string, but not a string subclass, use - PyFloat_FromString. */ - if (PyUnicode_CheckExact(x)) - return PyFloat_FromString(x); - return PyNumber_Float(x); + if (type != &PyFloat_Type) + return float_subtype_new(type, args, kwds); /* Wimp out */ + if (!PyArg_ParseTupleAndKeywords(args, kwds, "|O:float", kwlist, &x)) + return NULL; + /* If it's a string, but not a string subclass, use + PyFloat_FromString. */ + if (PyUnicode_CheckExact(x)) + return PyFloat_FromString(x); + return PyNumber_Float(x); } /* Wimpy, slow approach to tp_new calls for subtypes of float: @@ -1578,33 +1578,33 @@ static PyObject * float_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds) { - PyObject *tmp, *newobj; + PyObject *tmp, *newobj; - assert(PyType_IsSubtype(type, &PyFloat_Type)); - tmp = float_new(&PyFloat_Type, args, kwds); - if (tmp == NULL) - return NULL; - assert(PyFloat_CheckExact(tmp)); - newobj = type->tp_alloc(type, 0); - if (newobj == NULL) { - Py_DECREF(tmp); - return NULL; - } - ((PyFloatObject *)newobj)->ob_fval = ((PyFloatObject *)tmp)->ob_fval; - Py_DECREF(tmp); - return newobj; + assert(PyType_IsSubtype(type, &PyFloat_Type)); + tmp = float_new(&PyFloat_Type, args, kwds); + if (tmp == NULL) + return NULL; + assert(PyFloat_CheckExact(tmp)); + newobj = type->tp_alloc(type, 0); + if (newobj == NULL) { + Py_DECREF(tmp); + return NULL; + } + ((PyFloatObject *)newobj)->ob_fval = ((PyFloatObject *)tmp)->ob_fval; + Py_DECREF(tmp); + return newobj; } static PyObject * float_getnewargs(PyFloatObject *v) { - return Py_BuildValue("(d)", v->ob_fval); + return Py_BuildValue("(d)", v->ob_fval); } /* this is for the benefit of the pack/unpack routines below */ typedef enum { - unknown_format, ieee_big_endian_format, ieee_little_endian_format + unknown_format, ieee_big_endian_format, ieee_little_endian_format } float_format_type; static float_format_type double_format, float_format; @@ -1613,42 +1613,42 @@ static PyObject * float_getformat(PyTypeObject *v, PyObject* arg) { - char* s; - float_format_type r; + char* s; + float_format_type r; - if (!PyUnicode_Check(arg)) { - PyErr_Format(PyExc_TypeError, - "__getformat__() argument must be string, not %.500s", - Py_TYPE(arg)->tp_name); - return NULL; - } - s = _PyUnicode_AsString(arg); - if (s == NULL) - return NULL; - if (strcmp(s, "double") == 0) { - r = double_format; - } - else if (strcmp(s, "float") == 0) { - r = float_format; - } - else { - PyErr_SetString(PyExc_ValueError, - "__getformat__() argument 1 must be " - "'double' or 'float'"); - return NULL; - } - - switch (r) { - case unknown_format: - return PyUnicode_FromString("unknown"); - case ieee_little_endian_format: - return PyUnicode_FromString("IEEE, little-endian"); - case ieee_big_endian_format: - return PyUnicode_FromString("IEEE, big-endian"); - default: - Py_FatalError("insane float_format or double_format"); - return NULL; - } + if (!PyUnicode_Check(arg)) { + PyErr_Format(PyExc_TypeError, + "__getformat__() argument must be string, not %.500s", + Py_TYPE(arg)->tp_name); + return NULL; + } + s = _PyUnicode_AsString(arg); + if (s == NULL) + return NULL; + if (strcmp(s, "double") == 0) { + r = double_format; + } + else if (strcmp(s, "float") == 0) { + r = float_format; + } + else { + PyErr_SetString(PyExc_ValueError, + "__getformat__() argument 1 must be " + "'double' or 'float'"); + return NULL; + } + + switch (r) { + case unknown_format: + return PyUnicode_FromString("unknown"); + case ieee_little_endian_format: + return PyUnicode_FromString("IEEE, little-endian"); + case ieee_big_endian_format: + return PyUnicode_FromString("IEEE, big-endian"); + default: + Py_FatalError("insane float_format or double_format"); + return NULL; + } } PyDoc_STRVAR(float_getformat_doc, @@ -1664,57 +1664,57 @@ static PyObject * float_setformat(PyTypeObject *v, PyObject* args) { - char* typestr; - char* format; - float_format_type f; - float_format_type detected; - float_format_type *p; - - if (!PyArg_ParseTuple(args, "ss:__setformat__", &typestr, &format)) - return NULL; - - if (strcmp(typestr, "double") == 0) { - p = &double_format; - detected = detected_double_format; - } - else if (strcmp(typestr, "float") == 0) { - p = &float_format; - detected = detected_float_format; - } - else { - PyErr_SetString(PyExc_ValueError, - "__setformat__() argument 1 must " - "be 'double' or 'float'"); - return NULL; - } - - if (strcmp(format, "unknown") == 0) { - f = unknown_format; - } - else if (strcmp(format, "IEEE, little-endian") == 0) { - f = ieee_little_endian_format; - } - else if (strcmp(format, "IEEE, big-endian") == 0) { - f = ieee_big_endian_format; - } - else { - PyErr_SetString(PyExc_ValueError, - "__setformat__() argument 2 must be " - "'unknown', 'IEEE, little-endian' or " - "'IEEE, big-endian'"); - return NULL; - - } - - if (f != unknown_format && f != detected) { - PyErr_Format(PyExc_ValueError, - "can only set %s format to 'unknown' or the " - "detected platform value", typestr); - return NULL; - } + char* typestr; + char* format; + float_format_type f; + float_format_type detected; + float_format_type *p; + + if (!PyArg_ParseTuple(args, "ss:__setformat__", &typestr, &format)) + return NULL; + + if (strcmp(typestr, "double") == 0) { + p = &double_format; + detected = detected_double_format; + } + else if (strcmp(typestr, "float") == 0) { + p = &float_format; + detected = detected_float_format; + } + else { + PyErr_SetString(PyExc_ValueError, + "__setformat__() argument 1 must " + "be 'double' or 'float'"); + return NULL; + } + + if (strcmp(format, "unknown") == 0) { + f = unknown_format; + } + else if (strcmp(format, "IEEE, little-endian") == 0) { + f = ieee_little_endian_format; + } + else if (strcmp(format, "IEEE, big-endian") == 0) { + f = ieee_big_endian_format; + } + else { + PyErr_SetString(PyExc_ValueError, + "__setformat__() argument 2 must be " + "'unknown', 'IEEE, little-endian' or " + "'IEEE, big-endian'"); + return NULL; + + } + + if (f != unknown_format && f != detected) { + PyErr_Format(PyExc_ValueError, + "can only set %s format to 'unknown' or the " + "detected platform value", typestr); + return NULL; + } - *p = f; - Py_RETURN_NONE; + *p = f; + Py_RETURN_NONE; } PyDoc_STRVAR(float_setformat_doc, @@ -1733,19 +1733,19 @@ static PyObject * float_getzero(PyObject *v, void *closure) { - return PyFloat_FromDouble(0.0); + return PyFloat_FromDouble(0.0); } static PyObject * float__format__(PyObject *self, PyObject *args) { - PyObject *format_spec; + PyObject *format_spec; - if (!PyArg_ParseTuple(args, "U:__format__", &format_spec)) - return NULL; - return _PyFloat_FormatAdvanced(self, - PyUnicode_AS_UNICODE(format_spec), - PyUnicode_GET_SIZE(format_spec)); + if (!PyArg_ParseTuple(args, "U:__format__", &format_spec)) + return NULL; + return _PyFloat_FormatAdvanced(self, + PyUnicode_AS_UNICODE(format_spec), + PyUnicode_GET_SIZE(format_spec)); } PyDoc_STRVAR(float__format__doc, @@ -1755,45 +1755,45 @@ static PyMethodDef float_methods[] = { - {"conjugate", (PyCFunction)float_float, METH_NOARGS, - "Returns self, the complex conjugate of any float."}, - {"__trunc__", (PyCFunction)float_trunc, METH_NOARGS, - "Returns the Integral closest to x between 0 and x."}, - {"__round__", (PyCFunction)float_round, METH_VARARGS, - "Returns the Integral closest to x, rounding half toward even.\n" - "When an argument is passed, works like built-in round(x, ndigits)."}, - {"as_integer_ratio", (PyCFunction)float_as_integer_ratio, METH_NOARGS, - float_as_integer_ratio_doc}, - {"fromhex", (PyCFunction)float_fromhex, - METH_O|METH_CLASS, float_fromhex_doc}, - {"hex", (PyCFunction)float_hex, - METH_NOARGS, float_hex_doc}, - {"is_integer", (PyCFunction)float_is_integer, METH_NOARGS, - "Returns True if the float is an integer."}, + {"conjugate", (PyCFunction)float_float, METH_NOARGS, + "Returns self, the complex conjugate of any float."}, + {"__trunc__", (PyCFunction)float_trunc, METH_NOARGS, + "Returns the Integral closest to x between 0 and x."}, + {"__round__", (PyCFunction)float_round, METH_VARARGS, + "Returns the Integral closest to x, rounding half toward even.\n" + "When an argument is passed, works like built-in round(x, ndigits)."}, + {"as_integer_ratio", (PyCFunction)float_as_integer_ratio, METH_NOARGS, + float_as_integer_ratio_doc}, + {"fromhex", (PyCFunction)float_fromhex, + METH_O|METH_CLASS, float_fromhex_doc}, + {"hex", (PyCFunction)float_hex, + METH_NOARGS, float_hex_doc}, + {"is_integer", (PyCFunction)float_is_integer, METH_NOARGS, + "Returns True if the float is an integer."}, #if 0 - {"is_inf", (PyCFunction)float_is_inf, METH_NOARGS, - "Returns True if the float is positive or negative infinite."}, - {"is_finite", (PyCFunction)float_is_finite, METH_NOARGS, - "Returns True if the float is finite, neither infinite nor NaN."}, - {"is_nan", (PyCFunction)float_is_nan, METH_NOARGS, - "Returns True if the float is not a number (NaN)."}, + {"is_inf", (PyCFunction)float_is_inf, METH_NOARGS, + "Returns True if the float is positive or negative infinite."}, + {"is_finite", (PyCFunction)float_is_finite, METH_NOARGS, + "Returns True if the float is finite, neither infinite nor NaN."}, + {"is_nan", (PyCFunction)float_is_nan, METH_NOARGS, + "Returns True if the float is not a number (NaN)."}, #endif - {"__getnewargs__", (PyCFunction)float_getnewargs, METH_NOARGS}, - {"__getformat__", (PyCFunction)float_getformat, - METH_O|METH_CLASS, float_getformat_doc}, - {"__setformat__", (PyCFunction)float_setformat, - METH_VARARGS|METH_CLASS, float_setformat_doc}, - {"__format__", (PyCFunction)float__format__, - METH_VARARGS, float__format__doc}, - {NULL, NULL} /* sentinel */ + {"__getnewargs__", (PyCFunction)float_getnewargs, METH_NOARGS}, + {"__getformat__", (PyCFunction)float_getformat, + METH_O|METH_CLASS, float_getformat_doc}, + {"__setformat__", (PyCFunction)float_setformat, + METH_VARARGS|METH_CLASS, float_setformat_doc}, + {"__format__", (PyCFunction)float__format__, + METH_VARARGS, float__format__doc}, + {NULL, NULL} /* sentinel */ }; static PyGetSetDef float_getset[] = { - {"real", + {"real", (getter)float_float, (setter)NULL, "the real part of a complex number", NULL}, - {"imag", + {"imag", (getter)float_getzero, (setter)NULL, "the imaginary part of a complex number", NULL}, @@ -1807,229 +1807,229 @@ static PyNumberMethods float_as_number = { - float_add, /*nb_add*/ - float_sub, /*nb_subtract*/ - float_mul, /*nb_multiply*/ - float_rem, /*nb_remainder*/ - float_divmod, /*nb_divmod*/ - float_pow, /*nb_power*/ - (unaryfunc)float_neg, /*nb_negative*/ - (unaryfunc)float_float, /*nb_positive*/ - (unaryfunc)float_abs, /*nb_absolute*/ - (inquiry)float_bool, /*nb_bool*/ - 0, /*nb_invert*/ - 0, /*nb_lshift*/ - 0, /*nb_rshift*/ - 0, /*nb_and*/ - 0, /*nb_xor*/ - 0, /*nb_or*/ - float_trunc, /*nb_int*/ - 0, /*nb_reserved*/ - float_float, /*nb_float*/ - 0, /* nb_inplace_add */ - 0, /* nb_inplace_subtract */ - 0, /* nb_inplace_multiply */ - 0, /* nb_inplace_remainder */ - 0, /* nb_inplace_power */ - 0, /* nb_inplace_lshift */ - 0, /* nb_inplace_rshift */ - 0, /* nb_inplace_and */ - 0, /* nb_inplace_xor */ - 0, /* nb_inplace_or */ - float_floor_div, /* nb_floor_divide */ - float_div, /* nb_true_divide */ - 0, /* nb_inplace_floor_divide */ - 0, /* nb_inplace_true_divide */ + float_add, /*nb_add*/ + float_sub, /*nb_subtract*/ + float_mul, /*nb_multiply*/ + float_rem, /*nb_remainder*/ + float_divmod, /*nb_divmod*/ + float_pow, /*nb_power*/ + (unaryfunc)float_neg, /*nb_negative*/ + (unaryfunc)float_float, /*nb_positive*/ + (unaryfunc)float_abs, /*nb_absolute*/ + (inquiry)float_bool, /*nb_bool*/ + 0, /*nb_invert*/ + 0, /*nb_lshift*/ + 0, /*nb_rshift*/ + 0, /*nb_and*/ + 0, /*nb_xor*/ + 0, /*nb_or*/ + float_trunc, /*nb_int*/ + 0, /*nb_reserved*/ + float_float, /*nb_float*/ + 0, /* nb_inplace_add */ + 0, /* nb_inplace_subtract */ + 0, /* nb_inplace_multiply */ + 0, /* nb_inplace_remainder */ + 0, /* nb_inplace_power */ + 0, /* nb_inplace_lshift */ + 0, /* nb_inplace_rshift */ + 0, /* nb_inplace_and */ + 0, /* nb_inplace_xor */ + 0, /* nb_inplace_or */ + float_floor_div, /* nb_floor_divide */ + float_div, /* nb_true_divide */ + 0, /* nb_inplace_floor_divide */ + 0, /* nb_inplace_true_divide */ }; PyTypeObject PyFloat_Type = { - PyVarObject_HEAD_INIT(&PyType_Type, 0) - "float", - sizeof(PyFloatObject), - 0, - (destructor)float_dealloc, /* tp_dealloc */ - 0, /* tp_print */ - 0, /* tp_getattr */ - 0, /* tp_setattr */ - 0, /* tp_reserved */ - (reprfunc)float_repr, /* tp_repr */ - &float_as_number, /* tp_as_number */ - 0, /* tp_as_sequence */ - 0, /* tp_as_mapping */ - (hashfunc)float_hash, /* tp_hash */ - 0, /* tp_call */ - (reprfunc)float_str, /* tp_str */ - PyObject_GenericGetAttr, /* tp_getattro */ - 0, /* tp_setattro */ - 0, /* tp_as_buffer */ - Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */ - float_doc, /* tp_doc */ - 0, /* tp_traverse */ - 0, /* tp_clear */ - float_richcompare, /* tp_richcompare */ - 0, /* tp_weaklistoffset */ - 0, /* tp_iter */ - 0, /* tp_iternext */ - float_methods, /* tp_methods */ - 0, /* tp_members */ - float_getset, /* tp_getset */ - 0, /* tp_base */ - 0, /* tp_dict */ - 0, /* tp_descr_get */ - 0, /* tp_descr_set */ - 0, /* tp_dictoffset */ - 0, /* tp_init */ - 0, /* tp_alloc */ - float_new, /* tp_new */ + PyVarObject_HEAD_INIT(&PyType_Type, 0) + "float", + sizeof(PyFloatObject), + 0, + (destructor)float_dealloc, /* tp_dealloc */ + 0, /* tp_print */ + 0, /* tp_getattr */ + 0, /* tp_setattr */ + 0, /* tp_reserved */ + (reprfunc)float_repr, /* tp_repr */ + &float_as_number, /* tp_as_number */ + 0, /* tp_as_sequence */ + 0, /* tp_as_mapping */ + (hashfunc)float_hash, /* tp_hash */ + 0, /* tp_call */ + (reprfunc)float_str, /* tp_str */ + PyObject_GenericGetAttr, /* tp_getattro */ + 0, /* tp_setattro */ + 0, /* tp_as_buffer */ + Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */ + float_doc, /* tp_doc */ + 0, /* tp_traverse */ + 0, /* tp_clear */ + float_richcompare, /* tp_richcompare */ + 0, /* tp_weaklistoffset */ + 0, /* tp_iter */ + 0, /* tp_iternext */ + float_methods, /* tp_methods */ + 0, /* tp_members */ + float_getset, /* tp_getset */ + 0, /* tp_base */ + 0, /* tp_dict */ + 0, /* tp_descr_get */ + 0, /* tp_descr_set */ + 0, /* tp_dictoffset */ + 0, /* tp_init */ + 0, /* tp_alloc */ + float_new, /* tp_new */ }; void _PyFloat_Init(void) { - /* We attempt to determine if this machine is using IEEE - floating point formats by peering at the bits of some - carefully chosen values. If it looks like we are on an - IEEE platform, the float packing/unpacking routines can - just copy bits, if not they resort to arithmetic & shifts - and masks. The shifts & masks approach works on all finite - values, but what happens to infinities, NaNs and signed - zeroes on packing is an accident, and attempting to unpack - a NaN or an infinity will raise an exception. - - Note that if we're on some whacked-out platform which uses - IEEE formats but isn't strictly little-endian or big- - endian, we will fall back to the portable shifts & masks - method. */ + /* We attempt to determine if this machine is using IEEE + floating point formats by peering at the bits of some + carefully chosen values. If it looks like we are on an + IEEE platform, the float packing/unpacking routines can + just copy bits, if not they resort to arithmetic & shifts + and masks. The shifts & masks approach works on all finite + values, but what happens to infinities, NaNs and signed + zeroes on packing is an accident, and attempting to unpack + a NaN or an infinity will raise an exception. + + Note that if we're on some whacked-out platform which uses + IEEE formats but isn't strictly little-endian or big- + endian, we will fall back to the portable shifts & masks + method. */ #if SIZEOF_DOUBLE == 8 - { - double x = 9006104071832581.0; - if (memcmp(&x, "\x43\x3f\xff\x01\x02\x03\x04\x05", 8) == 0) - detected_double_format = ieee_big_endian_format; - else if (memcmp(&x, "\x05\x04\x03\x02\x01\xff\x3f\x43", 8) == 0) - detected_double_format = ieee_little_endian_format; - else - detected_double_format = unknown_format; - } + { + double x = 9006104071832581.0; + if (memcmp(&x, "\x43\x3f\xff\x01\x02\x03\x04\x05", 8) == 0) + detected_double_format = ieee_big_endian_format; + else if (memcmp(&x, "\x05\x04\x03\x02\x01\xff\x3f\x43", 8) == 0) + detected_double_format = ieee_little_endian_format; + else + detected_double_format = unknown_format; + } #else - detected_double_format = unknown_format; + detected_double_format = unknown_format; #endif #if SIZEOF_FLOAT == 4 - { - float y = 16711938.0; - if (memcmp(&y, "\x4b\x7f\x01\x02", 4) == 0) - detected_float_format = ieee_big_endian_format; - else if (memcmp(&y, "\x02\x01\x7f\x4b", 4) == 0) - detected_float_format = ieee_little_endian_format; - else - detected_float_format = unknown_format; - } + { + float y = 16711938.0; + if (memcmp(&y, "\x4b\x7f\x01\x02", 4) == 0) + detected_float_format = ieee_big_endian_format; + else if (memcmp(&y, "\x02\x01\x7f\x4b", 4) == 0) + detected_float_format = ieee_little_endian_format; + else + detected_float_format = unknown_format; + } #else - detected_float_format = unknown_format; + detected_float_format = unknown_format; #endif - double_format = detected_double_format; - float_format = detected_float_format; + double_format = detected_double_format; + float_format = detected_float_format; - /* Init float info */ - if (FloatInfoType.tp_name == 0) - PyStructSequence_InitType(&FloatInfoType, &floatinfo_desc); + /* Init float info */ + if (FloatInfoType.tp_name == 0) + PyStructSequence_InitType(&FloatInfoType, &floatinfo_desc); } int PyFloat_ClearFreeList(void) { - PyFloatObject *p; - PyFloatBlock *list, *next; - int i; - int u; /* remaining unfreed floats per block */ - int freelist_size = 0; - - list = block_list; - block_list = NULL; - free_list = NULL; - while (list != NULL) { - u = 0; - for (i = 0, p = &list->objects[0]; - i < N_FLOATOBJECTS; - i++, p++) { - if (PyFloat_CheckExact(p) && Py_REFCNT(p) != 0) - u++; - } - next = list->next; - if (u) { - list->next = block_list; - block_list = list; - for (i = 0, p = &list->objects[0]; - i < N_FLOATOBJECTS; - i++, p++) { - if (!PyFloat_CheckExact(p) || - Py_REFCNT(p) == 0) { - Py_TYPE(p) = (struct _typeobject *) - free_list; - free_list = p; - } - } - } - else { - PyMem_FREE(list); - } - freelist_size += u; - list = next; - } - return freelist_size; + PyFloatObject *p; + PyFloatBlock *list, *next; + int i; + int u; /* remaining unfreed floats per block */ + int freelist_size = 0; + + list = block_list; + block_list = NULL; + free_list = NULL; + while (list != NULL) { + u = 0; + for (i = 0, p = &list->objects[0]; + i < N_FLOATOBJECTS; + i++, p++) { + if (PyFloat_CheckExact(p) && Py_REFCNT(p) != 0) + u++; + } + next = list->next; + if (u) { + list->next = block_list; + block_list = list; + for (i = 0, p = &list->objects[0]; + i < N_FLOATOBJECTS; + i++, p++) { + if (!PyFloat_CheckExact(p) || + Py_REFCNT(p) == 0) { + Py_TYPE(p) = (struct _typeobject *) + free_list; + free_list = p; + } + } + } + else { + PyMem_FREE(list); + } + freelist_size += u; + list = next; + } + return freelist_size; } void PyFloat_Fini(void) { - PyFloatObject *p; - PyFloatBlock *list; - int i; - int u; /* total unfreed floats per block */ - - u = PyFloat_ClearFreeList(); - - if (!Py_VerboseFlag) - return; - fprintf(stderr, "# cleanup floats"); - if (!u) { - fprintf(stderr, "\n"); - } - else { - fprintf(stderr, - ": %d unfreed float%s\n", - u, u == 1 ? "" : "s"); - } - if (Py_VerboseFlag > 1) { - list = block_list; - while (list != NULL) { - for (i = 0, p = &list->objects[0]; - i < N_FLOATOBJECTS; - i++, p++) { - if (PyFloat_CheckExact(p) && - Py_REFCNT(p) != 0) { - char *buf = PyOS_double_to_string( - PyFloat_AS_DOUBLE(p), 'r', - 0, 0, NULL); - if (buf) { - /* XXX(twouters) cast - refcount to long - until %zd is - universally - available - */ - fprintf(stderr, - "# \n", - p, (long)Py_REFCNT(p), buf); - PyMem_Free(buf); - } - } - } - list = list->next; - } - } + PyFloatObject *p; + PyFloatBlock *list; + int i; + int u; /* total unfreed floats per block */ + + u = PyFloat_ClearFreeList(); + + if (!Py_VerboseFlag) + return; + fprintf(stderr, "# cleanup floats"); + if (!u) { + fprintf(stderr, "\n"); + } + else { + fprintf(stderr, + ": %d unfreed float%s\n", + u, u == 1 ? "" : "s"); + } + if (Py_VerboseFlag > 1) { + list = block_list; + while (list != NULL) { + for (i = 0, p = &list->objects[0]; + i < N_FLOATOBJECTS; + i++, p++) { + if (PyFloat_CheckExact(p) && + Py_REFCNT(p) != 0) { + char *buf = PyOS_double_to_string( + PyFloat_AS_DOUBLE(p), 'r', + 0, 0, NULL); + if (buf) { + /* XXX(twouters) cast + refcount to long + until %zd is + universally + available + */ + fprintf(stderr, + "# \n", + p, (long)Py_REFCNT(p), buf); + PyMem_Free(buf); + } + } + } + list = list->next; + } + } } /*---------------------------------------------------------------------------- @@ -2038,406 +2038,406 @@ int _PyFloat_Pack4(double x, unsigned char *p, int le) { - if (float_format == unknown_format) { - unsigned char sign; - int e; - double f; - unsigned int fbits; - int incr = 1; - - if (le) { - p += 3; - incr = -1; - } - - if (x < 0) { - sign = 1; - x = -x; - } - else - sign = 0; - - f = frexp(x, &e); - - /* Normalize f to be in the range [1.0, 2.0) */ - if (0.5 <= f && f < 1.0) { - f *= 2.0; - e--; - } - else if (f == 0.0) - e = 0; - else { - PyErr_SetString(PyExc_SystemError, - "frexp() result out of range"); - return -1; - } - - if (e >= 128) - goto Overflow; - else if (e < -126) { - /* Gradual underflow */ - f = ldexp(f, 126 + e); - e = 0; - } - else if (!(e == 0 && f == 0.0)) { - e += 127; - f -= 1.0; /* Get rid of leading 1 */ - } - - f *= 8388608.0; /* 2**23 */ - fbits = (unsigned int)(f + 0.5); /* Round */ - assert(fbits <= 8388608); - if (fbits >> 23) { - /* The carry propagated out of a string of 23 1 bits. */ - fbits = 0; - ++e; - if (e >= 255) - goto Overflow; - } - - /* First byte */ - *p = (sign << 7) | (e >> 1); - p += incr; - - /* Second byte */ - *p = (char) (((e & 1) << 7) | (fbits >> 16)); - p += incr; - - /* Third byte */ - *p = (fbits >> 8) & 0xFF; - p += incr; - - /* Fourth byte */ - *p = fbits & 0xFF; - - /* Done */ - return 0; - - } - else { - float y = (float)x; - const char *s = (char*)&y; - int i, incr = 1; - - if (Py_IS_INFINITY(y) && !Py_IS_INFINITY(x)) - goto Overflow; - - if ((float_format == ieee_little_endian_format && !le) - || (float_format == ieee_big_endian_format && le)) { - p += 3; - incr = -1; - } - - for (i = 0; i < 4; i++) { - *p = *s++; - p += incr; - } - return 0; - } + if (float_format == unknown_format) { + unsigned char sign; + int e; + double f; + unsigned int fbits; + int incr = 1; + + if (le) { + p += 3; + incr = -1; + } + + if (x < 0) { + sign = 1; + x = -x; + } + else + sign = 0; + + f = frexp(x, &e); + + /* Normalize f to be in the range [1.0, 2.0) */ + if (0.5 <= f && f < 1.0) { + f *= 2.0; + e--; + } + else if (f == 0.0) + e = 0; + else { + PyErr_SetString(PyExc_SystemError, + "frexp() result out of range"); + return -1; + } + + if (e >= 128) + goto Overflow; + else if (e < -126) { + /* Gradual underflow */ + f = ldexp(f, 126 + e); + e = 0; + } + else if (!(e == 0 && f == 0.0)) { + e += 127; + f -= 1.0; /* Get rid of leading 1 */ + } + + f *= 8388608.0; /* 2**23 */ + fbits = (unsigned int)(f + 0.5); /* Round */ + assert(fbits <= 8388608); + if (fbits >> 23) { + /* The carry propagated out of a string of 23 1 bits. */ + fbits = 0; + ++e; + if (e >= 255) + goto Overflow; + } + + /* First byte */ + *p = (sign << 7) | (e >> 1); + p += incr; + + /* Second byte */ + *p = (char) (((e & 1) << 7) | (fbits >> 16)); + p += incr; + + /* Third byte */ + *p = (fbits >> 8) & 0xFF; + p += incr; + + /* Fourth byte */ + *p = fbits & 0xFF; + + /* Done */ + return 0; + + } + else { + float y = (float)x; + const char *s = (char*)&y; + int i, incr = 1; + + if (Py_IS_INFINITY(y) && !Py_IS_INFINITY(x)) + goto Overflow; + + if ((float_format == ieee_little_endian_format && !le) + || (float_format == ieee_big_endian_format && le)) { + p += 3; + incr = -1; + } + + for (i = 0; i < 4; i++) { + *p = *s++; + p += incr; + } + return 0; + } Overflow: - PyErr_SetString(PyExc_OverflowError, - "float too large to pack with f format"); - return -1; + PyErr_SetString(PyExc_OverflowError, + "float too large to pack with f format"); + return -1; } int _PyFloat_Pack8(double x, unsigned char *p, int le) { - if (double_format == unknown_format) { - unsigned char sign; - int e; - double f; - unsigned int fhi, flo; - int incr = 1; - - if (le) { - p += 7; - incr = -1; - } - - if (x < 0) { - sign = 1; - x = -x; - } - else - sign = 0; - - f = frexp(x, &e); - - /* Normalize f to be in the range [1.0, 2.0) */ - if (0.5 <= f && f < 1.0) { - f *= 2.0; - e--; - } - else if (f == 0.0) - e = 0; - else { - PyErr_SetString(PyExc_SystemError, - "frexp() result out of range"); - return -1; - } - - if (e >= 1024) - goto Overflow; - else if (e < -1022) { - /* Gradual underflow */ - f = ldexp(f, 1022 + e); - e = 0; - } - else if (!(e == 0 && f == 0.0)) { - e += 1023; - f -= 1.0; /* Get rid of leading 1 */ - } - - /* fhi receives the high 28 bits; flo the low 24 bits (== 52 bits) */ - f *= 268435456.0; /* 2**28 */ - fhi = (unsigned int)f; /* Truncate */ - assert(fhi < 268435456); - - f -= (double)fhi; - f *= 16777216.0; /* 2**24 */ - flo = (unsigned int)(f + 0.5); /* Round */ - assert(flo <= 16777216); - if (flo >> 24) { - /* The carry propagated out of a string of 24 1 bits. */ - flo = 0; - ++fhi; - if (fhi >> 28) { - /* And it also progagated out of the next 28 bits. */ - fhi = 0; - ++e; - if (e >= 2047) - goto Overflow; - } - } - - /* First byte */ - *p = (sign << 7) | (e >> 4); - p += incr; - - /* Second byte */ - *p = (unsigned char) (((e & 0xF) << 4) | (fhi >> 24)); - p += incr; - - /* Third byte */ - *p = (fhi >> 16) & 0xFF; - p += incr; - - /* Fourth byte */ - *p = (fhi >> 8) & 0xFF; - p += incr; - - /* Fifth byte */ - *p = fhi & 0xFF; - p += incr; - - /* Sixth byte */ - *p = (flo >> 16) & 0xFF; - p += incr; - - /* Seventh byte */ - *p = (flo >> 8) & 0xFF; - p += incr; - - /* Eighth byte */ - *p = flo & 0xFF; - p += incr; - - /* Done */ - return 0; - - Overflow: - PyErr_SetString(PyExc_OverflowError, - "float too large to pack with d format"); - return -1; - } - else { - const char *s = (char*)&x; - int i, incr = 1; - - if ((double_format == ieee_little_endian_format && !le) - || (double_format == ieee_big_endian_format && le)) { - p += 7; - incr = -1; - } - - for (i = 0; i < 8; i++) { - *p = *s++; - p += incr; - } - return 0; - } + if (double_format == unknown_format) { + unsigned char sign; + int e; + double f; + unsigned int fhi, flo; + int incr = 1; + + if (le) { + p += 7; + incr = -1; + } + + if (x < 0) { + sign = 1; + x = -x; + } + else + sign = 0; + + f = frexp(x, &e); + + /* Normalize f to be in the range [1.0, 2.0) */ + if (0.5 <= f && f < 1.0) { + f *= 2.0; + e--; + } + else if (f == 0.0) + e = 0; + else { + PyErr_SetString(PyExc_SystemError, + "frexp() result out of range"); + return -1; + } + + if (e >= 1024) + goto Overflow; + else if (e < -1022) { + /* Gradual underflow */ + f = ldexp(f, 1022 + e); + e = 0; + } + else if (!(e == 0 && f == 0.0)) { + e += 1023; + f -= 1.0; /* Get rid of leading 1 */ + } + + /* fhi receives the high 28 bits; flo the low 24 bits (== 52 bits) */ + f *= 268435456.0; /* 2**28 */ + fhi = (unsigned int)f; /* Truncate */ + assert(fhi < 268435456); + + f -= (double)fhi; + f *= 16777216.0; /* 2**24 */ + flo = (unsigned int)(f + 0.5); /* Round */ + assert(flo <= 16777216); + if (flo >> 24) { + /* The carry propagated out of a string of 24 1 bits. */ + flo = 0; + ++fhi; + if (fhi >> 28) { + /* And it also progagated out of the next 28 bits. */ + fhi = 0; + ++e; + if (e >= 2047) + goto Overflow; + } + } + + /* First byte */ + *p = (sign << 7) | (e >> 4); + p += incr; + + /* Second byte */ + *p = (unsigned char) (((e & 0xF) << 4) | (fhi >> 24)); + p += incr; + + /* Third byte */ + *p = (fhi >> 16) & 0xFF; + p += incr; + + /* Fourth byte */ + *p = (fhi >> 8) & 0xFF; + p += incr; + + /* Fifth byte */ + *p = fhi & 0xFF; + p += incr; + + /* Sixth byte */ + *p = (flo >> 16) & 0xFF; + p += incr; + + /* Seventh byte */ + *p = (flo >> 8) & 0xFF; + p += incr; + + /* Eighth byte */ + *p = flo & 0xFF; + p += incr; + + /* Done */ + return 0; + + Overflow: + PyErr_SetString(PyExc_OverflowError, + "float too large to pack with d format"); + return -1; + } + else { + const char *s = (char*)&x; + int i, incr = 1; + + if ((double_format == ieee_little_endian_format && !le) + || (double_format == ieee_big_endian_format && le)) { + p += 7; + incr = -1; + } + + for (i = 0; i < 8; i++) { + *p = *s++; + p += incr; + } + return 0; + } } double _PyFloat_Unpack4(const unsigned char *p, int le) { - if (float_format == unknown_format) { - unsigned char sign; - int e; - unsigned int f; - double x; - int incr = 1; - - if (le) { - p += 3; - incr = -1; - } - - /* First byte */ - sign = (*p >> 7) & 1; - e = (*p & 0x7F) << 1; - p += incr; - - /* Second byte */ - e |= (*p >> 7) & 1; - f = (*p & 0x7F) << 16; - p += incr; - - if (e == 255) { - PyErr_SetString( - PyExc_ValueError, - "can't unpack IEEE 754 special value " - "on non-IEEE platform"); - return -1; - } - - /* Third byte */ - f |= *p << 8; - p += incr; - - /* Fourth byte */ - f |= *p; - - x = (double)f / 8388608.0; - - /* XXX This sadly ignores Inf/NaN issues */ - if (e == 0) - e = -126; - else { - x += 1.0; - e -= 127; - } - x = ldexp(x, e); - - if (sign) - x = -x; - - return x; - } - else { - float x; - - if ((float_format == ieee_little_endian_format && !le) - || (float_format == ieee_big_endian_format && le)) { - char buf[4]; - char *d = &buf[3]; - int i; - - for (i = 0; i < 4; i++) { - *d-- = *p++; - } - memcpy(&x, buf, 4); - } - else { - memcpy(&x, p, 4); - } + if (float_format == unknown_format) { + unsigned char sign; + int e; + unsigned int f; + double x; + int incr = 1; + + if (le) { + p += 3; + incr = -1; + } + + /* First byte */ + sign = (*p >> 7) & 1; + e = (*p & 0x7F) << 1; + p += incr; + + /* Second byte */ + e |= (*p >> 7) & 1; + f = (*p & 0x7F) << 16; + p += incr; + + if (e == 255) { + PyErr_SetString( + PyExc_ValueError, + "can't unpack IEEE 754 special value " + "on non-IEEE platform"); + return -1; + } + + /* Third byte */ + f |= *p << 8; + p += incr; + + /* Fourth byte */ + f |= *p; + + x = (double)f / 8388608.0; + + /* XXX This sadly ignores Inf/NaN issues */ + if (e == 0) + e = -126; + else { + x += 1.0; + e -= 127; + } + x = ldexp(x, e); + + if (sign) + x = -x; + + return x; + } + else { + float x; + + if ((float_format == ieee_little_endian_format && !le) + || (float_format == ieee_big_endian_format && le)) { + char buf[4]; + char *d = &buf[3]; + int i; + + for (i = 0; i < 4; i++) { + *d-- = *p++; + } + memcpy(&x, buf, 4); + } + else { + memcpy(&x, p, 4); + } - return x; - } + return x; + } } double _PyFloat_Unpack8(const unsigned char *p, int le) { - if (double_format == unknown_format) { - unsigned char sign; - int e; - unsigned int fhi, flo; - double x; - int incr = 1; - - if (le) { - p += 7; - incr = -1; - } - - /* First byte */ - sign = (*p >> 7) & 1; - e = (*p & 0x7F) << 4; - - p += incr; - - /* Second byte */ - e |= (*p >> 4) & 0xF; - fhi = (*p & 0xF) << 24; - p += incr; - - if (e == 2047) { - PyErr_SetString( - PyExc_ValueError, - "can't unpack IEEE 754 special value " - "on non-IEEE platform"); - return -1.0; - } - - /* Third byte */ - fhi |= *p << 16; - p += incr; - - /* Fourth byte */ - fhi |= *p << 8; - p += incr; - - /* Fifth byte */ - fhi |= *p; - p += incr; - - /* Sixth byte */ - flo = *p << 16; - p += incr; - - /* Seventh byte */ - flo |= *p << 8; - p += incr; - - /* Eighth byte */ - flo |= *p; - - x = (double)fhi + (double)flo / 16777216.0; /* 2**24 */ - x /= 268435456.0; /* 2**28 */ - - if (e == 0) - e = -1022; - else { - x += 1.0; - e -= 1023; - } - x = ldexp(x, e); - - if (sign) - x = -x; - - return x; - } - else { - double x; - - if ((double_format == ieee_little_endian_format && !le) - || (double_format == ieee_big_endian_format && le)) { - char buf[8]; - char *d = &buf[7]; - int i; - - for (i = 0; i < 8; i++) { - *d-- = *p++; - } - memcpy(&x, buf, 8); - } - else { - memcpy(&x, p, 8); - } + if (double_format == unknown_format) { + unsigned char sign; + int e; + unsigned int fhi, flo; + double x; + int incr = 1; + + if (le) { + p += 7; + incr = -1; + } + + /* First byte */ + sign = (*p >> 7) & 1; + e = (*p & 0x7F) << 4; + + p += incr; + + /* Second byte */ + e |= (*p >> 4) & 0xF; + fhi = (*p & 0xF) << 24; + p += incr; + + if (e == 2047) { + PyErr_SetString( + PyExc_ValueError, + "can't unpack IEEE 754 special value " + "on non-IEEE platform"); + return -1.0; + } + + /* Third byte */ + fhi |= *p << 16; + p += incr; + + /* Fourth byte */ + fhi |= *p << 8; + p += incr; + + /* Fifth byte */ + fhi |= *p; + p += incr; + + /* Sixth byte */ + flo = *p << 16; + p += incr; + + /* Seventh byte */ + flo |= *p << 8; + p += incr; + + /* Eighth byte */ + flo |= *p; + + x = (double)fhi + (double)flo / 16777216.0; /* 2**24 */ + x /= 268435456.0; /* 2**28 */ + + if (e == 0) + e = -1022; + else { + x += 1.0; + e -= 1023; + } + x = ldexp(x, e); + + if (sign) + x = -x; + + return x; + } + else { + double x; + + if ((double_format == ieee_little_endian_format && !le) + || (double_format == ieee_big_endian_format && le)) { + char buf[8]; + char *d = &buf[7]; + int i; + + for (i = 0; i < 8; i++) { + *d-- = *p++; + } + memcpy(&x, buf, 8); + } + else { + memcpy(&x, p, 8); + } - return x; - } + return x; + } } Modified: python/branches/py3k-jit/Objects/frameobject.c ============================================================================== --- python/branches/py3k-jit/Objects/frameobject.c (original) +++ python/branches/py3k-jit/Objects/frameobject.c Mon May 10 23:55:43 2010 @@ -15,39 +15,39 @@ #define OFF(x) offsetof(PyFrameObject, x) static PyMemberDef frame_memberlist[] = { - {"f_back", T_OBJECT, OFF(f_back), READONLY}, - {"f_code", T_OBJECT, OFF(f_code), READONLY}, - {"f_builtins", T_OBJECT, OFF(f_builtins),READONLY}, - {"f_globals", T_OBJECT, OFF(f_globals), READONLY}, - {"f_lasti", T_INT, OFF(f_lasti), READONLY}, - {NULL} /* Sentinel */ + {"f_back", T_OBJECT, OFF(f_back), READONLY}, + {"f_code", T_OBJECT, OFF(f_code), READONLY}, + {"f_builtins", T_OBJECT, OFF(f_builtins),READONLY}, + {"f_globals", T_OBJECT, OFF(f_globals), READONLY}, + {"f_lasti", T_INT, OFF(f_lasti), READONLY}, + {NULL} /* Sentinel */ }; static PyObject * frame_getlocals(PyFrameObject *f, void *closure) { - PyFrame_FastToLocals(f); - Py_INCREF(f->f_locals); - return f->f_locals; + PyFrame_FastToLocals(f); + Py_INCREF(f->f_locals); + return f->f_locals; } int PyFrame_GetLineNumber(PyFrameObject *f) { - if (f->f_trace) - return f->f_lineno; - else - return PyCode_Addr2Line(f->f_code, f->f_lasti); + if (f->f_trace) + return f->f_lineno; + else + return PyCode_Addr2Line(f->f_code, f->f_lasti); } static PyObject * frame_getlineno(PyFrameObject *f, void *closure) { - return PyLong_FromLong(PyFrame_GetLineNumber(f)); + return PyLong_FromLong(PyFrame_GetLineNumber(f)); } /* Setter for f_lineno - you can set f_lineno from within a trace function in - * order to jump to a given line of code, subject to some restrictions. Most + * order to jump to a given line of code, subject to some restrictions. Most * lines are OK to jump to because they don't make any assumptions about the * state of the stack (obvious because you could remove the line and the code * would still work without any stack errors), but there are some constructs @@ -64,309 +64,309 @@ static int frame_setlineno(PyFrameObject *f, PyObject* p_new_lineno) { - int new_lineno = 0; /* The new value of f_lineno */ - long l_new_lineno; - int overflow; - int new_lasti = 0; /* The new value of f_lasti */ - int new_iblock = 0; /* The new value of f_iblock */ - unsigned char *code = NULL; /* The bytecode for the frame... */ - Py_ssize_t code_len = 0; /* ...and its length */ - unsigned char *lnotab = NULL; /* Iterating over co_lnotab */ - Py_ssize_t lnotab_len = 0; /* (ditto) */ - int offset = 0; /* (ditto) */ - int line = 0; /* (ditto) */ - int addr = 0; /* (ditto) */ - int min_addr = 0; /* Scanning the SETUPs and POPs */ - int max_addr = 0; /* (ditto) */ - int delta_iblock = 0; /* (ditto) */ - int min_delta_iblock = 0; /* (ditto) */ - int min_iblock = 0; /* (ditto) */ - int f_lasti_setup_addr = 0; /* Policing no-jump-into-finally */ - int new_lasti_setup_addr = 0; /* (ditto) */ - int blockstack[CO_MAXBLOCKS]; /* Walking the 'finally' blocks */ - int in_finally[CO_MAXBLOCKS]; /* (ditto) */ - int blockstack_top = 0; /* (ditto) */ - unsigned char setup_op = 0; /* (ditto) */ - - /* f_lineno must be an integer. */ - if (!PyLong_CheckExact(p_new_lineno)) { - PyErr_SetString(PyExc_ValueError, - "lineno must be an integer"); - return -1; - } - - /* You can only do this from within a trace function, not via - * _getframe or similar hackery. */ - if (!f->f_trace) - { - PyErr_Format(PyExc_ValueError, - "f_lineno can only be set by a" - " line trace function"); - return -1; - } - - /* Fail if the line comes before the start of the code block. */ - l_new_lineno = PyLong_AsLongAndOverflow(p_new_lineno, &overflow); - if (overflow + int new_lineno = 0; /* The new value of f_lineno */ + long l_new_lineno; + int overflow; + int new_lasti = 0; /* The new value of f_lasti */ + int new_iblock = 0; /* The new value of f_iblock */ + unsigned char *code = NULL; /* The bytecode for the frame... */ + Py_ssize_t code_len = 0; /* ...and its length */ + unsigned char *lnotab = NULL; /* Iterating over co_lnotab */ + Py_ssize_t lnotab_len = 0; /* (ditto) */ + int offset = 0; /* (ditto) */ + int line = 0; /* (ditto) */ + int addr = 0; /* (ditto) */ + int min_addr = 0; /* Scanning the SETUPs and POPs */ + int max_addr = 0; /* (ditto) */ + int delta_iblock = 0; /* (ditto) */ + int min_delta_iblock = 0; /* (ditto) */ + int min_iblock = 0; /* (ditto) */ + int f_lasti_setup_addr = 0; /* Policing no-jump-into-finally */ + int new_lasti_setup_addr = 0; /* (ditto) */ + int blockstack[CO_MAXBLOCKS]; /* Walking the 'finally' blocks */ + int in_finally[CO_MAXBLOCKS]; /* (ditto) */ + int blockstack_top = 0; /* (ditto) */ + unsigned char setup_op = 0; /* (ditto) */ + + /* f_lineno must be an integer. */ + if (!PyLong_CheckExact(p_new_lineno)) { + PyErr_SetString(PyExc_ValueError, + "lineno must be an integer"); + return -1; + } + + /* You can only do this from within a trace function, not via + * _getframe or similar hackery. */ + if (!f->f_trace) + { + PyErr_Format(PyExc_ValueError, + "f_lineno can only be set by a" + " line trace function"); + return -1; + } + + /* Fail if the line comes before the start of the code block. */ + l_new_lineno = PyLong_AsLongAndOverflow(p_new_lineno, &overflow); + if (overflow #if SIZEOF_LONG > SIZEOF_INT - || l_new_lineno > INT_MAX - || l_new_lineno < INT_MIN + || l_new_lineno > INT_MAX + || l_new_lineno < INT_MIN #endif - ) { - PyErr_SetString(PyExc_ValueError, - "lineno out of range"); - return -1; - } - new_lineno = (int)l_new_lineno; - - if (new_lineno < f->f_code->co_firstlineno) { - PyErr_Format(PyExc_ValueError, - "line %d comes before the current code block", - new_lineno); - return -1; - } - else if (new_lineno == f->f_code->co_firstlineno) { - new_lasti = 0; - new_lineno = f->f_code->co_firstlineno; - } - else { - /* Find the bytecode offset for the start of the given - * line, or the first code-owning line after it. */ - char *tmp; - PyBytes_AsStringAndSize(f->f_code->co_lnotab, - &tmp, &lnotab_len); - lnotab = (unsigned char *) tmp; - addr = 0; - line = f->f_code->co_firstlineno; - new_lasti = -1; - for (offset = 0; offset < lnotab_len; offset += 2) { - addr += lnotab[offset]; - line += lnotab[offset+1]; - if (line >= new_lineno) { - new_lasti = addr; - new_lineno = line; - break; - } - } - } - - /* If we didn't reach the requested line, return an error. */ - if (new_lasti == -1) { - PyErr_Format(PyExc_ValueError, - "line %d comes after the current code block", - new_lineno); - return -1; - } - - /* We're now ready to look at the bytecode. */ - PyBytes_AsStringAndSize(f->f_code->co_code, (char **)&code, &code_len); - min_addr = MIN(new_lasti, f->f_lasti); - max_addr = MAX(new_lasti, f->f_lasti); - - /* You can't jump onto a line with an 'except' statement on it - - * they expect to have an exception on the top of the stack, which - * won't be true if you jump to them. They always start with code - * that either pops the exception using POP_TOP (plain 'except:' - * lines do this) or duplicates the exception on the stack using - * DUP_TOP (if there's an exception type specified). See compile.c, - * 'com_try_except' for the full details. There aren't any other - * cases (AFAIK) where a line's code can start with DUP_TOP or - * POP_TOP, but if any ever appear, they'll be subject to the same - * restriction (but with a different error message). */ - if (code[new_lasti] == DUP_TOP || code[new_lasti] == POP_TOP) { - PyErr_SetString(PyExc_ValueError, - "can't jump to 'except' line as there's no exception"); - return -1; - } - - /* You can't jump into or out of a 'finally' block because the 'try' - * block leaves something on the stack for the END_FINALLY to clean - * up. So we walk the bytecode, maintaining a simulated blockstack. - * When we reach the old or new address and it's in a 'finally' block - * we note the address of the corresponding SETUP_FINALLY. The jump - * is only legal if neither address is in a 'finally' block or - * they're both in the same one. 'blockstack' is a stack of the - * bytecode addresses of the SETUP_X opcodes, and 'in_finally' tracks - * whether we're in a 'finally' block at each blockstack level. */ - f_lasti_setup_addr = -1; - new_lasti_setup_addr = -1; - memset(blockstack, '\0', sizeof(blockstack)); - memset(in_finally, '\0', sizeof(in_finally)); - blockstack_top = 0; - for (addr = 0; addr < code_len; addr++) { - unsigned char op = code[addr]; - switch (op) { - case SETUP_LOOP: - case SETUP_EXCEPT: - case SETUP_FINALLY: - blockstack[blockstack_top++] = addr; - in_finally[blockstack_top-1] = 0; - break; - - case POP_BLOCK: - assert(blockstack_top > 0); - setup_op = code[blockstack[blockstack_top-1]]; - if (setup_op == SETUP_FINALLY) { - in_finally[blockstack_top-1] = 1; - } - else { - blockstack_top--; - } - break; - - case END_FINALLY: - /* Ignore END_FINALLYs for SETUP_EXCEPTs - they exist - * in the bytecode but don't correspond to an actual - * 'finally' block. (If blockstack_top is 0, we must - * be seeing such an END_FINALLY.) */ - if (blockstack_top > 0) { - setup_op = code[blockstack[blockstack_top-1]]; - if (setup_op == SETUP_FINALLY) { - blockstack_top--; - } - } - break; - } - - /* For the addresses we're interested in, see whether they're - * within a 'finally' block and if so, remember the address - * of the SETUP_FINALLY. */ - if (addr == new_lasti || addr == f->f_lasti) { - int i = 0; - int setup_addr = -1; - for (i = blockstack_top-1; i >= 0; i--) { - if (in_finally[i]) { - setup_addr = blockstack[i]; - break; - } - } - - if (setup_addr != -1) { - if (addr == new_lasti) { - new_lasti_setup_addr = setup_addr; - } - - if (addr == f->f_lasti) { - f_lasti_setup_addr = setup_addr; - } - } - } - - if (op >= HAVE_ARGUMENT) { - addr += 2; - } - } - - /* Verify that the blockstack tracking code didn't get lost. */ - assert(blockstack_top == 0); - - /* After all that, are we jumping into / out of a 'finally' block? */ - if (new_lasti_setup_addr != f_lasti_setup_addr) { - PyErr_SetString(PyExc_ValueError, - "can't jump into or out of a 'finally' block"); - return -1; - } - - - /* Police block-jumping (you can't jump into the middle of a block) - * and ensure that the blockstack finishes up in a sensible state (by - * popping any blocks we're jumping out of). We look at all the - * blockstack operations between the current position and the new - * one, and keep track of how many blocks we drop out of on the way. - * By also keeping track of the lowest blockstack position we see, we - * can tell whether the jump goes into any blocks without coming out - * again - in that case we raise an exception below. */ - delta_iblock = 0; - for (addr = min_addr; addr < max_addr; addr++) { - unsigned char op = code[addr]; - switch (op) { - case SETUP_LOOP: - case SETUP_EXCEPT: - case SETUP_FINALLY: - delta_iblock++; - break; - - case POP_BLOCK: - delta_iblock--; - break; - } - - min_delta_iblock = MIN(min_delta_iblock, delta_iblock); - - if (op >= HAVE_ARGUMENT) { - addr += 2; - } - } - - /* Derive the absolute iblock values from the deltas. */ - min_iblock = f->f_iblock + min_delta_iblock; - if (new_lasti > f->f_lasti) { - /* Forwards jump. */ - new_iblock = f->f_iblock + delta_iblock; - } - else { - /* Backwards jump. */ - new_iblock = f->f_iblock - delta_iblock; - } - - /* Are we jumping into a block? */ - if (new_iblock > min_iblock) { - PyErr_SetString(PyExc_ValueError, - "can't jump into the middle of a block"); - return -1; - } - - /* Pop any blocks that we're jumping out of. */ - while (f->f_iblock > new_iblock) { - PyTryBlock *b = &f->f_blockstack[--f->f_iblock]; - while ((f->f_stacktop - f->f_valuestack) > b->b_level) { - PyObject *v = (*--f->f_stacktop); - Py_DECREF(v); - } - } - - /* Finally set the new f_lineno and f_lasti and return OK. */ - f->f_lineno = new_lineno; - f->f_lasti = new_lasti; - return 0; + ) { + PyErr_SetString(PyExc_ValueError, + "lineno out of range"); + return -1; + } + new_lineno = (int)l_new_lineno; + + if (new_lineno < f->f_code->co_firstlineno) { + PyErr_Format(PyExc_ValueError, + "line %d comes before the current code block", + new_lineno); + return -1; + } + else if (new_lineno == f->f_code->co_firstlineno) { + new_lasti = 0; + new_lineno = f->f_code->co_firstlineno; + } + else { + /* Find the bytecode offset for the start of the given + * line, or the first code-owning line after it. */ + char *tmp; + PyBytes_AsStringAndSize(f->f_code->co_lnotab, + &tmp, &lnotab_len); + lnotab = (unsigned char *) tmp; + addr = 0; + line = f->f_code->co_firstlineno; + new_lasti = -1; + for (offset = 0; offset < lnotab_len; offset += 2) { + addr += lnotab[offset]; + line += lnotab[offset+1]; + if (line >= new_lineno) { + new_lasti = addr; + new_lineno = line; + break; + } + } + } + + /* If we didn't reach the requested line, return an error. */ + if (new_lasti == -1) { + PyErr_Format(PyExc_ValueError, + "line %d comes after the current code block", + new_lineno); + return -1; + } + + /* We're now ready to look at the bytecode. */ + PyBytes_AsStringAndSize(f->f_code->co_code, (char **)&code, &code_len); + min_addr = MIN(new_lasti, f->f_lasti); + max_addr = MAX(new_lasti, f->f_lasti); + + /* You can't jump onto a line with an 'except' statement on it - + * they expect to have an exception on the top of the stack, which + * won't be true if you jump to them. They always start with code + * that either pops the exception using POP_TOP (plain 'except:' + * lines do this) or duplicates the exception on the stack using + * DUP_TOP (if there's an exception type specified). See compile.c, + * 'com_try_except' for the full details. There aren't any other + * cases (AFAIK) where a line's code can start with DUP_TOP or + * POP_TOP, but if any ever appear, they'll be subject to the same + * restriction (but with a different error message). */ + if (code[new_lasti] == DUP_TOP || code[new_lasti] == POP_TOP) { + PyErr_SetString(PyExc_ValueError, + "can't jump to 'except' line as there's no exception"); + return -1; + } + + /* You can't jump into or out of a 'finally' block because the 'try' + * block leaves something on the stack for the END_FINALLY to clean + * up. So we walk the bytecode, maintaining a simulated blockstack. + * When we reach the old or new address and it's in a 'finally' block + * we note the address of the corresponding SETUP_FINALLY. The jump + * is only legal if neither address is in a 'finally' block or + * they're both in the same one. 'blockstack' is a stack of the + * bytecode addresses of the SETUP_X opcodes, and 'in_finally' tracks + * whether we're in a 'finally' block at each blockstack level. */ + f_lasti_setup_addr = -1; + new_lasti_setup_addr = -1; + memset(blockstack, '\0', sizeof(blockstack)); + memset(in_finally, '\0', sizeof(in_finally)); + blockstack_top = 0; + for (addr = 0; addr < code_len; addr++) { + unsigned char op = code[addr]; + switch (op) { + case SETUP_LOOP: + case SETUP_EXCEPT: + case SETUP_FINALLY: + blockstack[blockstack_top++] = addr; + in_finally[blockstack_top-1] = 0; + break; + + case POP_BLOCK: + assert(blockstack_top > 0); + setup_op = code[blockstack[blockstack_top-1]]; + if (setup_op == SETUP_FINALLY) { + in_finally[blockstack_top-1] = 1; + } + else { + blockstack_top--; + } + break; + + case END_FINALLY: + /* Ignore END_FINALLYs for SETUP_EXCEPTs - they exist + * in the bytecode but don't correspond to an actual + * 'finally' block. (If blockstack_top is 0, we must + * be seeing such an END_FINALLY.) */ + if (blockstack_top > 0) { + setup_op = code[blockstack[blockstack_top-1]]; + if (setup_op == SETUP_FINALLY) { + blockstack_top--; + } + } + break; + } + + /* For the addresses we're interested in, see whether they're + * within a 'finally' block and if so, remember the address + * of the SETUP_FINALLY. */ + if (addr == new_lasti || addr == f->f_lasti) { + int i = 0; + int setup_addr = -1; + for (i = blockstack_top-1; i >= 0; i--) { + if (in_finally[i]) { + setup_addr = blockstack[i]; + break; + } + } + + if (setup_addr != -1) { + if (addr == new_lasti) { + new_lasti_setup_addr = setup_addr; + } + + if (addr == f->f_lasti) { + f_lasti_setup_addr = setup_addr; + } + } + } + + if (op >= HAVE_ARGUMENT) { + addr += 2; + } + } + + /* Verify that the blockstack tracking code didn't get lost. */ + assert(blockstack_top == 0); + + /* After all that, are we jumping into / out of a 'finally' block? */ + if (new_lasti_setup_addr != f_lasti_setup_addr) { + PyErr_SetString(PyExc_ValueError, + "can't jump into or out of a 'finally' block"); + return -1; + } + + + /* Police block-jumping (you can't jump into the middle of a block) + * and ensure that the blockstack finishes up in a sensible state (by + * popping any blocks we're jumping out of). We look at all the + * blockstack operations between the current position and the new + * one, and keep track of how many blocks we drop out of on the way. + * By also keeping track of the lowest blockstack position we see, we + * can tell whether the jump goes into any blocks without coming out + * again - in that case we raise an exception below. */ + delta_iblock = 0; + for (addr = min_addr; addr < max_addr; addr++) { + unsigned char op = code[addr]; + switch (op) { + case SETUP_LOOP: + case SETUP_EXCEPT: + case SETUP_FINALLY: + delta_iblock++; + break; + + case POP_BLOCK: + delta_iblock--; + break; + } + + min_delta_iblock = MIN(min_delta_iblock, delta_iblock); + + if (op >= HAVE_ARGUMENT) { + addr += 2; + } + } + + /* Derive the absolute iblock values from the deltas. */ + min_iblock = f->f_iblock + min_delta_iblock; + if (new_lasti > f->f_lasti) { + /* Forwards jump. */ + new_iblock = f->f_iblock + delta_iblock; + } + else { + /* Backwards jump. */ + new_iblock = f->f_iblock - delta_iblock; + } + + /* Are we jumping into a block? */ + if (new_iblock > min_iblock) { + PyErr_SetString(PyExc_ValueError, + "can't jump into the middle of a block"); + return -1; + } + + /* Pop any blocks that we're jumping out of. */ + while (f->f_iblock > new_iblock) { + PyTryBlock *b = &f->f_blockstack[--f->f_iblock]; + while ((f->f_stacktop - f->f_valuestack) > b->b_level) { + PyObject *v = (*--f->f_stacktop); + Py_DECREF(v); + } + } + + /* Finally set the new f_lineno and f_lasti and return OK. */ + f->f_lineno = new_lineno; + f->f_lasti = new_lasti; + return 0; } static PyObject * frame_gettrace(PyFrameObject *f, void *closure) { - PyObject* trace = f->f_trace; + PyObject* trace = f->f_trace; - if (trace == NULL) - trace = Py_None; + if (trace == NULL) + trace = Py_None; - Py_INCREF(trace); + Py_INCREF(trace); - return trace; + return trace; } static int frame_settrace(PyFrameObject *f, PyObject* v, void *closure) { - PyObject* old_value; + PyObject* old_value; - /* We rely on f_lineno being accurate when f_trace is set. */ - f->f_lineno = PyFrame_GetLineNumber(f); + /* We rely on f_lineno being accurate when f_trace is set. */ + f->f_lineno = PyFrame_GetLineNumber(f); - old_value = f->f_trace; - Py_XINCREF(v); - f->f_trace = v; - Py_XDECREF(old_value); + old_value = f->f_trace; + Py_XINCREF(v); + f->f_trace = v; + Py_XDECREF(old_value); - return 0; + return 0; } static PyGetSetDef frame_getsetlist[] = { - {"f_locals", (getter)frame_getlocals, NULL, NULL}, - {"f_lineno", (getter)frame_getlineno, - (setter)frame_setlineno, NULL}, - {"f_trace", (getter)frame_gettrace, (setter)frame_settrace, NULL}, - {0} + {"f_locals", (getter)frame_getlocals, NULL, NULL}, + {"f_lineno", (getter)frame_getlineno, + (setter)frame_setlineno, NULL}, + {"f_trace", (getter)frame_gettrace, (setter)frame_settrace, NULL}, + {0} }; /* Stack frames are allocated and deallocated at a considerable rate. @@ -383,7 +383,7 @@ the following fields are still valid: * ob_type, ob_size, f_code, f_valuestack; - + * f_locals, f_trace, f_exc_type, f_exc_value, f_exc_traceback are NULL; @@ -394,10 +394,10 @@ integers are allocated in a special way -- see intobject.c). When a stack frame is on the free list, only the following members have a meaning: - ob_type == &Frametype - f_back next item on free list, or NULL - f_stacksize size of value stack - ob_size size of localsplus + ob_type == &Frametype + f_back next item on free list, or NULL + f_stacksize size of value stack + ob_size size of localsplus Note that the value and block stacks are preserved -- this can save another malloc() call or two (and two free() calls as well!). Also note that, unlike for integers, each frame object is a @@ -413,307 +413,307 @@ */ static PyFrameObject *free_list = NULL; -static int numfree = 0; /* number of frames currently in free_list */ +static int numfree = 0; /* number of frames currently in free_list */ /* max value for numfree */ -#define PyFrame_MAXFREELIST 200 +#define PyFrame_MAXFREELIST 200 static void frame_dealloc(PyFrameObject *f) { - PyObject **p, **valuestack; - PyCodeObject *co; + PyObject **p, **valuestack; + PyCodeObject *co; - PyObject_GC_UnTrack(f); - Py_TRASHCAN_SAFE_BEGIN(f) - /* Kill all local variables */ - valuestack = f->f_valuestack; - for (p = f->f_localsplus; p < valuestack; p++) - Py_CLEAR(*p); - - /* Free stack */ - if (f->f_stacktop != NULL) { - for (p = valuestack; p < f->f_stacktop; p++) - Py_XDECREF(*p); - } - - Py_XDECREF(f->f_back); - Py_DECREF(f->f_builtins); - Py_DECREF(f->f_globals); - Py_CLEAR(f->f_locals); - Py_CLEAR(f->f_trace); - Py_CLEAR(f->f_exc_type); - Py_CLEAR(f->f_exc_value); - Py_CLEAR(f->f_exc_traceback); - - co = f->f_code; - if (co->co_zombieframe == NULL) - co->co_zombieframe = f; - else if (numfree < PyFrame_MAXFREELIST) { - ++numfree; - f->f_back = free_list; - free_list = f; - } - else - PyObject_GC_Del(f); + PyObject_GC_UnTrack(f); + Py_TRASHCAN_SAFE_BEGIN(f) + /* Kill all local variables */ + valuestack = f->f_valuestack; + for (p = f->f_localsplus; p < valuestack; p++) + Py_CLEAR(*p); + + /* Free stack */ + if (f->f_stacktop != NULL) { + for (p = valuestack; p < f->f_stacktop; p++) + Py_XDECREF(*p); + } + + Py_XDECREF(f->f_back); + Py_DECREF(f->f_builtins); + Py_DECREF(f->f_globals); + Py_CLEAR(f->f_locals); + Py_CLEAR(f->f_trace); + Py_CLEAR(f->f_exc_type); + Py_CLEAR(f->f_exc_value); + Py_CLEAR(f->f_exc_traceback); + + co = f->f_code; + if (co->co_zombieframe == NULL) + co->co_zombieframe = f; + else if (numfree < PyFrame_MAXFREELIST) { + ++numfree; + f->f_back = free_list; + free_list = f; + } + else + PyObject_GC_Del(f); - Py_DECREF(co); - Py_TRASHCAN_SAFE_END(f) + Py_DECREF(co); + Py_TRASHCAN_SAFE_END(f) } static int frame_traverse(PyFrameObject *f, visitproc visit, void *arg) { - PyObject **fastlocals, **p; - int i, slots; + PyObject **fastlocals, **p; + int i, slots; - Py_VISIT(f->f_back); - Py_VISIT(f->f_code); - Py_VISIT(f->f_builtins); - Py_VISIT(f->f_globals); - Py_VISIT(f->f_locals); - Py_VISIT(f->f_trace); - Py_VISIT(f->f_exc_type); - Py_VISIT(f->f_exc_value); - Py_VISIT(f->f_exc_traceback); - - /* locals */ - slots = f->f_code->co_nlocals + PyTuple_GET_SIZE(f->f_code->co_cellvars) + PyTuple_GET_SIZE(f->f_code->co_freevars); - fastlocals = f->f_localsplus; - for (i = slots; --i >= 0; ++fastlocals) - Py_VISIT(*fastlocals); - - /* stack */ - if (f->f_stacktop != NULL) { - for (p = f->f_valuestack; p < f->f_stacktop; p++) - Py_VISIT(*p); - } - return 0; + Py_VISIT(f->f_back); + Py_VISIT(f->f_code); + Py_VISIT(f->f_builtins); + Py_VISIT(f->f_globals); + Py_VISIT(f->f_locals); + Py_VISIT(f->f_trace); + Py_VISIT(f->f_exc_type); + Py_VISIT(f->f_exc_value); + Py_VISIT(f->f_exc_traceback); + + /* locals */ + slots = f->f_code->co_nlocals + PyTuple_GET_SIZE(f->f_code->co_cellvars) + PyTuple_GET_SIZE(f->f_code->co_freevars); + fastlocals = f->f_localsplus; + for (i = slots; --i >= 0; ++fastlocals) + Py_VISIT(*fastlocals); + + /* stack */ + if (f->f_stacktop != NULL) { + for (p = f->f_valuestack; p < f->f_stacktop; p++) + Py_VISIT(*p); + } + return 0; } static void frame_clear(PyFrameObject *f) { - PyObject **fastlocals, **p, **oldtop; - int i, slots; + PyObject **fastlocals, **p, **oldtop; + int i, slots; - /* Before anything else, make sure that this frame is clearly marked - * as being defunct! Else, e.g., a generator reachable from this - * frame may also point to this frame, believe itself to still be - * active, and try cleaning up this frame again. - */ - oldtop = f->f_stacktop; - f->f_stacktop = NULL; - - Py_CLEAR(f->f_exc_type); - Py_CLEAR(f->f_exc_value); - Py_CLEAR(f->f_exc_traceback); - Py_CLEAR(f->f_trace); - - /* locals */ - slots = f->f_code->co_nlocals + PyTuple_GET_SIZE(f->f_code->co_cellvars) + PyTuple_GET_SIZE(f->f_code->co_freevars); - fastlocals = f->f_localsplus; - for (i = slots; --i >= 0; ++fastlocals) - Py_CLEAR(*fastlocals); - - /* stack */ - if (oldtop != NULL) { - for (p = f->f_valuestack; p < oldtop; p++) - Py_CLEAR(*p); - } + /* Before anything else, make sure that this frame is clearly marked + * as being defunct! Else, e.g., a generator reachable from this + * frame may also point to this frame, believe itself to still be + * active, and try cleaning up this frame again. + */ + oldtop = f->f_stacktop; + f->f_stacktop = NULL; + + Py_CLEAR(f->f_exc_type); + Py_CLEAR(f->f_exc_value); + Py_CLEAR(f->f_exc_traceback); + Py_CLEAR(f->f_trace); + + /* locals */ + slots = f->f_code->co_nlocals + PyTuple_GET_SIZE(f->f_code->co_cellvars) + PyTuple_GET_SIZE(f->f_code->co_freevars); + fastlocals = f->f_localsplus; + for (i = slots; --i >= 0; ++fastlocals) + Py_CLEAR(*fastlocals); + + /* stack */ + if (oldtop != NULL) { + for (p = f->f_valuestack; p < oldtop; p++) + Py_CLEAR(*p); + } } static PyObject * frame_sizeof(PyFrameObject *f) { - Py_ssize_t res, extras, ncells, nfrees; + Py_ssize_t res, extras, ncells, nfrees; - ncells = PyTuple_GET_SIZE(f->f_code->co_cellvars); - nfrees = PyTuple_GET_SIZE(f->f_code->co_freevars); - extras = f->f_code->co_stacksize + f->f_code->co_nlocals + - ncells + nfrees; - /* subtract one as it is already included in PyFrameObject */ - res = sizeof(PyFrameObject) + (extras-1) * sizeof(PyObject *); + ncells = PyTuple_GET_SIZE(f->f_code->co_cellvars); + nfrees = PyTuple_GET_SIZE(f->f_code->co_freevars); + extras = f->f_code->co_stacksize + f->f_code->co_nlocals + + ncells + nfrees; + /* subtract one as it is already included in PyFrameObject */ + res = sizeof(PyFrameObject) + (extras-1) * sizeof(PyObject *); - return PyLong_FromSsize_t(res); + return PyLong_FromSsize_t(res); } PyDoc_STRVAR(sizeof__doc__, "F.__sizeof__() -> size of F in memory, in bytes"); static PyMethodDef frame_methods[] = { - {"__sizeof__", (PyCFunction)frame_sizeof, METH_NOARGS, - sizeof__doc__}, - {NULL, NULL} /* sentinel */ + {"__sizeof__", (PyCFunction)frame_sizeof, METH_NOARGS, + sizeof__doc__}, + {NULL, NULL} /* sentinel */ }; PyTypeObject PyFrame_Type = { - PyVarObject_HEAD_INIT(&PyType_Type, 0) - "frame", - sizeof(PyFrameObject), - sizeof(PyObject *), - (destructor)frame_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 */ - PyObject_GenericSetAttr, /* tp_setattro */ - 0, /* tp_as_buffer */ - Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */ - 0, /* tp_doc */ - (traverseproc)frame_traverse, /* tp_traverse */ - (inquiry)frame_clear, /* tp_clear */ - 0, /* tp_richcompare */ - 0, /* tp_weaklistoffset */ - 0, /* tp_iter */ - 0, /* tp_iternext */ - frame_methods, /* tp_methods */ - frame_memberlist, /* tp_members */ - frame_getsetlist, /* tp_getset */ - 0, /* tp_base */ - 0, /* tp_dict */ + PyVarObject_HEAD_INIT(&PyType_Type, 0) + "frame", + sizeof(PyFrameObject), + sizeof(PyObject *), + (destructor)frame_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 */ + PyObject_GenericSetAttr, /* tp_setattro */ + 0, /* tp_as_buffer */ + Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */ + 0, /* tp_doc */ + (traverseproc)frame_traverse, /* tp_traverse */ + (inquiry)frame_clear, /* tp_clear */ + 0, /* tp_richcompare */ + 0, /* tp_weaklistoffset */ + 0, /* tp_iter */ + 0, /* tp_iternext */ + frame_methods, /* tp_methods */ + frame_memberlist, /* tp_members */ + frame_getsetlist, /* tp_getset */ + 0, /* tp_base */ + 0, /* tp_dict */ }; static PyObject *builtin_object; int _PyFrame_Init() { - builtin_object = PyUnicode_InternFromString("__builtins__"); - if (builtin_object == NULL) - return 0; - return 1; + builtin_object = PyUnicode_InternFromString("__builtins__"); + if (builtin_object == NULL) + return 0; + return 1; } PyFrameObject * PyFrame_New(PyThreadState *tstate, PyCodeObject *code, PyObject *globals, - PyObject *locals) + PyObject *locals) { - PyFrameObject *back = tstate->frame; - PyFrameObject *f; - PyObject *builtins; - Py_ssize_t i; + PyFrameObject *back = tstate->frame; + PyFrameObject *f; + PyObject *builtins; + Py_ssize_t i; #ifdef Py_DEBUG - if (code == NULL || globals == NULL || !PyDict_Check(globals) || - (locals != NULL && !PyMapping_Check(locals))) { - PyErr_BadInternalCall(); - return NULL; - } + if (code == NULL || globals == NULL || !PyDict_Check(globals) || + (locals != NULL && !PyMapping_Check(locals))) { + PyErr_BadInternalCall(); + return NULL; + } #endif - if (back == NULL || back->f_globals != globals) { - builtins = PyDict_GetItem(globals, builtin_object); - if (builtins) { - if (PyModule_Check(builtins)) { - builtins = PyModule_GetDict(builtins); - assert(!builtins || PyDict_Check(builtins)); - } - else if (!PyDict_Check(builtins)) - builtins = NULL; - } - if (builtins == NULL) { - /* No builtins! Make up a minimal one - Give them 'None', at least. */ - builtins = PyDict_New(); - if (builtins == NULL || - PyDict_SetItemString( - builtins, "None", Py_None) < 0) - return NULL; - } - else - Py_INCREF(builtins); - - } - else { - /* If we share the globals, we share the builtins. - Save a lookup and a call. */ - builtins = back->f_builtins; - assert(builtins != NULL && PyDict_Check(builtins)); - Py_INCREF(builtins); - } - if (code->co_zombieframe != NULL) { - f = code->co_zombieframe; - code->co_zombieframe = NULL; - _Py_NewReference((PyObject *)f); - assert(f->f_code == code); - } - else { - Py_ssize_t extras, ncells, nfrees; - ncells = PyTuple_GET_SIZE(code->co_cellvars); - nfrees = PyTuple_GET_SIZE(code->co_freevars); - extras = code->co_stacksize + code->co_nlocals + ncells + - nfrees; - if (free_list == NULL) { - f = PyObject_GC_NewVar(PyFrameObject, &PyFrame_Type, - extras); - if (f == NULL) { - Py_DECREF(builtins); - return NULL; - } - } - else { - assert(numfree > 0); - --numfree; - f = free_list; - free_list = free_list->f_back; - if (Py_SIZE(f) < extras) { - f = PyObject_GC_Resize(PyFrameObject, f, extras); - if (f == NULL) { - Py_DECREF(builtins); - return NULL; - } - } - _Py_NewReference((PyObject *)f); - } - - f->f_code = code; - extras = code->co_nlocals + ncells + nfrees; - f->f_valuestack = f->f_localsplus + extras; - for (i=0; if_localsplus[i] = NULL; - f->f_locals = NULL; - f->f_trace = NULL; - f->f_exc_type = f->f_exc_value = f->f_exc_traceback = NULL; - } - f->f_stacktop = f->f_valuestack; - f->f_builtins = builtins; - Py_XINCREF(back); - f->f_back = back; - Py_INCREF(code); - Py_INCREF(globals); - f->f_globals = globals; - /* Most functions have CO_NEWLOCALS and CO_OPTIMIZED set. */ - if ((code->co_flags & (CO_NEWLOCALS | CO_OPTIMIZED)) == - (CO_NEWLOCALS | CO_OPTIMIZED)) - ; /* f_locals = NULL; will be set by PyFrame_FastToLocals() */ - else if (code->co_flags & CO_NEWLOCALS) { - locals = PyDict_New(); - if (locals == NULL) { - Py_DECREF(f); - return NULL; - } - f->f_locals = locals; - } - else { - if (locals == NULL) - locals = globals; - Py_INCREF(locals); - f->f_locals = locals; - } - f->f_tstate = tstate; - - f->f_lasti = -1; - f->f_lineno = code->co_firstlineno; - f->f_iblock = 0; + if (back == NULL || back->f_globals != globals) { + builtins = PyDict_GetItem(globals, builtin_object); + if (builtins) { + if (PyModule_Check(builtins)) { + builtins = PyModule_GetDict(builtins); + assert(!builtins || PyDict_Check(builtins)); + } + else if (!PyDict_Check(builtins)) + builtins = NULL; + } + if (builtins == NULL) { + /* No builtins! Make up a minimal one + Give them 'None', at least. */ + builtins = PyDict_New(); + if (builtins == NULL || + PyDict_SetItemString( + builtins, "None", Py_None) < 0) + return NULL; + } + else + Py_INCREF(builtins); + + } + else { + /* If we share the globals, we share the builtins. + Save a lookup and a call. */ + builtins = back->f_builtins; + assert(builtins != NULL && PyDict_Check(builtins)); + Py_INCREF(builtins); + } + if (code->co_zombieframe != NULL) { + f = code->co_zombieframe; + code->co_zombieframe = NULL; + _Py_NewReference((PyObject *)f); + assert(f->f_code == code); + } + else { + Py_ssize_t extras, ncells, nfrees; + ncells = PyTuple_GET_SIZE(code->co_cellvars); + nfrees = PyTuple_GET_SIZE(code->co_freevars); + extras = code->co_stacksize + code->co_nlocals + ncells + + nfrees; + if (free_list == NULL) { + f = PyObject_GC_NewVar(PyFrameObject, &PyFrame_Type, + extras); + if (f == NULL) { + Py_DECREF(builtins); + return NULL; + } + } + else { + assert(numfree > 0); + --numfree; + f = free_list; + free_list = free_list->f_back; + if (Py_SIZE(f) < extras) { + f = PyObject_GC_Resize(PyFrameObject, f, extras); + if (f == NULL) { + Py_DECREF(builtins); + return NULL; + } + } + _Py_NewReference((PyObject *)f); + } + + f->f_code = code; + extras = code->co_nlocals + ncells + nfrees; + f->f_valuestack = f->f_localsplus + extras; + for (i=0; if_localsplus[i] = NULL; + f->f_locals = NULL; + f->f_trace = NULL; + f->f_exc_type = f->f_exc_value = f->f_exc_traceback = NULL; + } + f->f_stacktop = f->f_valuestack; + f->f_builtins = builtins; + Py_XINCREF(back); + f->f_back = back; + Py_INCREF(code); + Py_INCREF(globals); + f->f_globals = globals; + /* Most functions have CO_NEWLOCALS and CO_OPTIMIZED set. */ + if ((code->co_flags & (CO_NEWLOCALS | CO_OPTIMIZED)) == + (CO_NEWLOCALS | CO_OPTIMIZED)) + ; /* f_locals = NULL; will be set by PyFrame_FastToLocals() */ + else if (code->co_flags & CO_NEWLOCALS) { + locals = PyDict_New(); + if (locals == NULL) { + Py_DECREF(f); + return NULL; + } + f->f_locals = locals; + } + else { + if (locals == NULL) + locals = globals; + Py_INCREF(locals); + f->f_locals = locals; + } + f->f_tstate = tstate; + + f->f_lasti = -1; + f->f_lineno = code->co_firstlineno; + f->f_iblock = 0; - _PyObject_GC_TRACK(f); - return f; + _PyObject_GC_TRACK(f); + return f; } /* Block management */ @@ -721,28 +721,28 @@ void PyFrame_BlockSetup(PyFrameObject *f, int type, int handler, int level) { - PyTryBlock *b; - if (f->f_iblock >= CO_MAXBLOCKS) - Py_FatalError("XXX block stack overflow"); - b = &f->f_blockstack[f->f_iblock++]; - b->b_type = type; - b->b_level = level; - b->b_handler = handler; + PyTryBlock *b; + if (f->f_iblock >= CO_MAXBLOCKS) + Py_FatalError("XXX block stack overflow"); + b = &f->f_blockstack[f->f_iblock++]; + b->b_type = type; + b->b_level = level; + b->b_handler = handler; } PyTryBlock * PyFrame_BlockPop(PyFrameObject *f) { - PyTryBlock *b; - if (f->f_iblock <= 0) - Py_FatalError("XXX block stack underflow"); - b = &f->f_blockstack[--f->f_iblock]; - return b; + PyTryBlock *b; + if (f->f_iblock <= 0) + Py_FatalError("XXX block stack underflow"); + b = &f->f_blockstack[--f->f_iblock]; + return b; } /* Convert between "fast" version of locals and dictionary version. - - map and values are input arguments. map is a tuple of strings. + + map and values are input arguments. map is a tuple of strings. values is an array of PyObject*. At index i, map[i] is the name of the variable with value values[i]. The function copies the first nmap variable from map/values into dict. If values[i] is NULL, @@ -758,29 +758,29 @@ static void map_to_dict(PyObject *map, Py_ssize_t nmap, PyObject *dict, PyObject **values, - int deref) + int deref) { - Py_ssize_t j; - assert(PyTuple_Check(map)); - assert(PyDict_Check(dict)); - assert(PyTuple_Size(map) >= nmap); - for (j = nmap; --j >= 0; ) { - PyObject *key = PyTuple_GET_ITEM(map, j); - PyObject *value = values[j]; - assert(PyUnicode_Check(key)); - if (deref) { - assert(PyCell_Check(value)); - value = PyCell_GET(value); - } - if (value == NULL) { - if (PyObject_DelItem(dict, key) != 0) - PyErr_Clear(); - } - else { - if (PyObject_SetItem(dict, key, value) != 0) - PyErr_Clear(); - } - } + Py_ssize_t j; + assert(PyTuple_Check(map)); + assert(PyDict_Check(dict)); + assert(PyTuple_Size(map) >= nmap); + for (j = nmap; --j >= 0; ) { + PyObject *key = PyTuple_GET_ITEM(map, j); + PyObject *value = values[j]; + assert(PyUnicode_Check(key)); + if (deref) { + assert(PyCell_Check(value)); + value = PyCell_GET(value); + } + if (value == NULL) { + if (PyObject_DelItem(dict, key) != 0) + PyErr_Clear(); + } + else { + if (PyObject_SetItem(dict, key, value) != 0) + PyErr_Clear(); + } + } } /* Copy values from the "locals" dict into the fast locals. @@ -788,7 +788,7 @@ dict is an input argument containing string keys representing variables names and arbitrary PyObject* as values. - map and values are input arguments. map is a tuple of strings. + map and values are input arguments. map is a tuple of strings. values is an array of PyObject*. At index i, map[i] is the name of the variable with value values[i]. The function copies the first nmap variable from map/values into dict. If values[i] is NULL, @@ -806,150 +806,150 @@ static void dict_to_map(PyObject *map, Py_ssize_t nmap, PyObject *dict, PyObject **values, - int deref, int clear) + int deref, int clear) { - Py_ssize_t j; - assert(PyTuple_Check(map)); - assert(PyDict_Check(dict)); - assert(PyTuple_Size(map) >= nmap); - for (j = nmap; --j >= 0; ) { - PyObject *key = PyTuple_GET_ITEM(map, j); - PyObject *value = PyObject_GetItem(dict, key); - assert(PyUnicode_Check(key)); - /* We only care about NULLs if clear is true. */ - if (value == NULL) { - PyErr_Clear(); - if (!clear) - continue; - } - if (deref) { - assert(PyCell_Check(values[j])); - if (PyCell_GET(values[j]) != value) { - if (PyCell_Set(values[j], value) < 0) - PyErr_Clear(); - } - } else if (values[j] != value) { - Py_XINCREF(value); - Py_XDECREF(values[j]); - values[j] = value; - } - Py_XDECREF(value); - } + Py_ssize_t j; + assert(PyTuple_Check(map)); + assert(PyDict_Check(dict)); + assert(PyTuple_Size(map) >= nmap); + for (j = nmap; --j >= 0; ) { + PyObject *key = PyTuple_GET_ITEM(map, j); + PyObject *value = PyObject_GetItem(dict, key); + assert(PyUnicode_Check(key)); + /* We only care about NULLs if clear is true. */ + if (value == NULL) { + PyErr_Clear(); + if (!clear) + continue; + } + if (deref) { + assert(PyCell_Check(values[j])); + if (PyCell_GET(values[j]) != value) { + if (PyCell_Set(values[j], value) < 0) + PyErr_Clear(); + } + } else if (values[j] != value) { + Py_XINCREF(value); + Py_XDECREF(values[j]); + values[j] = value; + } + Py_XDECREF(value); + } } void PyFrame_FastToLocals(PyFrameObject *f) { - /* Merge fast locals into f->f_locals */ - PyObject *locals, *map; - PyObject **fast; - PyObject *error_type, *error_value, *error_traceback; - PyCodeObject *co; - Py_ssize_t j; - int ncells, nfreevars; - if (f == NULL) - return; - locals = f->f_locals; - if (locals == NULL) { - locals = f->f_locals = PyDict_New(); - if (locals == NULL) { - PyErr_Clear(); /* Can't report it :-( */ - return; - } - } - co = f->f_code; - map = co->co_varnames; - if (!PyTuple_Check(map)) - return; - PyErr_Fetch(&error_type, &error_value, &error_traceback); - fast = f->f_localsplus; - j = PyTuple_GET_SIZE(map); - if (j > co->co_nlocals) - j = co->co_nlocals; - if (co->co_nlocals) - map_to_dict(map, j, locals, fast, 0); - ncells = PyTuple_GET_SIZE(co->co_cellvars); - nfreevars = PyTuple_GET_SIZE(co->co_freevars); - if (ncells || nfreevars) { - map_to_dict(co->co_cellvars, ncells, - locals, fast + co->co_nlocals, 1); - /* If the namespace is unoptimized, then one of the - following cases applies: - 1. It does not contain free variables, because it - uses import * or is a top-level namespace. - 2. It is a class namespace. - We don't want to accidentally copy free variables - into the locals dict used by the class. - */ - if (co->co_flags & CO_OPTIMIZED) { - map_to_dict(co->co_freevars, nfreevars, - locals, fast + co->co_nlocals + ncells, 1); - } - } - PyErr_Restore(error_type, error_value, error_traceback); + /* Merge fast locals into f->f_locals */ + PyObject *locals, *map; + PyObject **fast; + PyObject *error_type, *error_value, *error_traceback; + PyCodeObject *co; + Py_ssize_t j; + int ncells, nfreevars; + if (f == NULL) + return; + locals = f->f_locals; + if (locals == NULL) { + locals = f->f_locals = PyDict_New(); + if (locals == NULL) { + PyErr_Clear(); /* Can't report it :-( */ + return; + } + } + co = f->f_code; + map = co->co_varnames; + if (!PyTuple_Check(map)) + return; + PyErr_Fetch(&error_type, &error_value, &error_traceback); + fast = f->f_localsplus; + j = PyTuple_GET_SIZE(map); + if (j > co->co_nlocals) + j = co->co_nlocals; + if (co->co_nlocals) + map_to_dict(map, j, locals, fast, 0); + ncells = PyTuple_GET_SIZE(co->co_cellvars); + nfreevars = PyTuple_GET_SIZE(co->co_freevars); + if (ncells || nfreevars) { + map_to_dict(co->co_cellvars, ncells, + locals, fast + co->co_nlocals, 1); + /* If the namespace is unoptimized, then one of the + following cases applies: + 1. It does not contain free variables, because it + uses import * or is a top-level namespace. + 2. It is a class namespace. + We don't want to accidentally copy free variables + into the locals dict used by the class. + */ + if (co->co_flags & CO_OPTIMIZED) { + map_to_dict(co->co_freevars, nfreevars, + locals, fast + co->co_nlocals + ncells, 1); + } + } + PyErr_Restore(error_type, error_value, error_traceback); } void PyFrame_LocalsToFast(PyFrameObject *f, int clear) { - /* Merge f->f_locals into fast locals */ - PyObject *locals, *map; - PyObject **fast; - PyObject *error_type, *error_value, *error_traceback; - PyCodeObject *co; - Py_ssize_t j; - int ncells, nfreevars; - if (f == NULL) - return; - locals = f->f_locals; - co = f->f_code; - map = co->co_varnames; - if (locals == NULL) - return; - if (!PyTuple_Check(map)) - return; - PyErr_Fetch(&error_type, &error_value, &error_traceback); - fast = f->f_localsplus; - j = PyTuple_GET_SIZE(map); - if (j > co->co_nlocals) - j = co->co_nlocals; - if (co->co_nlocals) - dict_to_map(co->co_varnames, j, locals, fast, 0, clear); - ncells = PyTuple_GET_SIZE(co->co_cellvars); - nfreevars = PyTuple_GET_SIZE(co->co_freevars); - if (ncells || nfreevars) { - dict_to_map(co->co_cellvars, ncells, - locals, fast + co->co_nlocals, 1, clear); - /* Same test as in PyFrame_FastToLocals() above. */ - if (co->co_flags & CO_OPTIMIZED) { - dict_to_map(co->co_freevars, nfreevars, - locals, fast + co->co_nlocals + ncells, 1, - clear); - } - } - PyErr_Restore(error_type, error_value, error_traceback); + /* Merge f->f_locals into fast locals */ + PyObject *locals, *map; + PyObject **fast; + PyObject *error_type, *error_value, *error_traceback; + PyCodeObject *co; + Py_ssize_t j; + int ncells, nfreevars; + if (f == NULL) + return; + locals = f->f_locals; + co = f->f_code; + map = co->co_varnames; + if (locals == NULL) + return; + if (!PyTuple_Check(map)) + return; + PyErr_Fetch(&error_type, &error_value, &error_traceback); + fast = f->f_localsplus; + j = PyTuple_GET_SIZE(map); + if (j > co->co_nlocals) + j = co->co_nlocals; + if (co->co_nlocals) + dict_to_map(co->co_varnames, j, locals, fast, 0, clear); + ncells = PyTuple_GET_SIZE(co->co_cellvars); + nfreevars = PyTuple_GET_SIZE(co->co_freevars); + if (ncells || nfreevars) { + dict_to_map(co->co_cellvars, ncells, + locals, fast + co->co_nlocals, 1, clear); + /* Same test as in PyFrame_FastToLocals() above. */ + if (co->co_flags & CO_OPTIMIZED) { + dict_to_map(co->co_freevars, nfreevars, + locals, fast + co->co_nlocals + ncells, 1, + clear); + } + } + PyErr_Restore(error_type, error_value, error_traceback); } /* Clear out the free list */ int PyFrame_ClearFreeList(void) { - int freelist_size = numfree; - - while (free_list != NULL) { - PyFrameObject *f = free_list; - free_list = free_list->f_back; - PyObject_GC_Del(f); - --numfree; - } - assert(numfree == 0); - return freelist_size; + int freelist_size = numfree; + + while (free_list != NULL) { + PyFrameObject *f = free_list; + free_list = free_list->f_back; + PyObject_GC_Del(f); + --numfree; + } + assert(numfree == 0); + return freelist_size; } void PyFrame_Fini(void) { - (void)PyFrame_ClearFreeList(); - Py_XDECREF(builtin_object); - builtin_object = NULL; + (void)PyFrame_ClearFreeList(); + Py_XDECREF(builtin_object); + builtin_object = NULL; } Modified: python/branches/py3k-jit/Objects/funcobject.c ============================================================================== --- python/branches/py3k-jit/Objects/funcobject.c (original) +++ python/branches/py3k-jit/Objects/funcobject.c Mon May 10 23:55:43 2010 @@ -9,215 +9,215 @@ PyObject * PyFunction_New(PyObject *code, PyObject *globals) { - PyFunctionObject *op = PyObject_GC_New(PyFunctionObject, - &PyFunction_Type); - static PyObject *__name__ = 0; - if (op != NULL) { - PyObject *doc; - PyObject *consts; - PyObject *module; - op->func_weakreflist = NULL; - Py_INCREF(code); - op->func_code = code; - Py_INCREF(globals); - op->func_globals = globals; - op->func_name = ((PyCodeObject *)code)->co_name; - Py_INCREF(op->func_name); - op->func_defaults = NULL; /* No default arguments */ - op->func_kwdefaults = NULL; /* No keyword only defaults */ - op->func_closure = NULL; - consts = ((PyCodeObject *)code)->co_consts; - if (PyTuple_Size(consts) >= 1) { - doc = PyTuple_GetItem(consts, 0); - if (!PyUnicode_Check(doc)) - doc = Py_None; - } - else - doc = Py_None; - Py_INCREF(doc); - op->func_doc = doc; - op->func_dict = NULL; - op->func_module = NULL; - op->func_annotations = NULL; - - /* __module__: If module name is in globals, use it. - Otherwise, use None. - */ - if (!__name__) { - __name__ = PyUnicode_InternFromString("__name__"); - if (!__name__) { - Py_DECREF(op); - return NULL; - } - } - module = PyDict_GetItem(globals, __name__); - if (module) { - Py_INCREF(module); - op->func_module = module; - } - } - else - return NULL; - _PyObject_GC_TRACK(op); - return (PyObject *)op; + PyFunctionObject *op = PyObject_GC_New(PyFunctionObject, + &PyFunction_Type); + static PyObject *__name__ = 0; + if (op != NULL) { + PyObject *doc; + PyObject *consts; + PyObject *module; + op->func_weakreflist = NULL; + Py_INCREF(code); + op->func_code = code; + Py_INCREF(globals); + op->func_globals = globals; + op->func_name = ((PyCodeObject *)code)->co_name; + Py_INCREF(op->func_name); + op->func_defaults = NULL; /* No default arguments */ + op->func_kwdefaults = NULL; /* No keyword only defaults */ + op->func_closure = NULL; + consts = ((PyCodeObject *)code)->co_consts; + if (PyTuple_Size(consts) >= 1) { + doc = PyTuple_GetItem(consts, 0); + if (!PyUnicode_Check(doc)) + doc = Py_None; + } + else + doc = Py_None; + Py_INCREF(doc); + op->func_doc = doc; + op->func_dict = NULL; + op->func_module = NULL; + op->func_annotations = NULL; + + /* __module__: If module name is in globals, use it. + Otherwise, use None. + */ + if (!__name__) { + __name__ = PyUnicode_InternFromString("__name__"); + if (!__name__) { + Py_DECREF(op); + return NULL; + } + } + module = PyDict_GetItem(globals, __name__); + if (module) { + Py_INCREF(module); + op->func_module = module; + } + } + else + return NULL; + _PyObject_GC_TRACK(op); + return (PyObject *)op; } PyObject * PyFunction_GetCode(PyObject *op) { - if (!PyFunction_Check(op)) { - PyErr_BadInternalCall(); - return NULL; - } - return ((PyFunctionObject *) op) -> func_code; + if (!PyFunction_Check(op)) { + PyErr_BadInternalCall(); + return NULL; + } + return ((PyFunctionObject *) op) -> func_code; } PyObject * PyFunction_GetGlobals(PyObject *op) { - if (!PyFunction_Check(op)) { - PyErr_BadInternalCall(); - return NULL; - } - return ((PyFunctionObject *) op) -> func_globals; + if (!PyFunction_Check(op)) { + PyErr_BadInternalCall(); + return NULL; + } + return ((PyFunctionObject *) op) -> func_globals; } PyObject * PyFunction_GetModule(PyObject *op) { - if (!PyFunction_Check(op)) { - PyErr_BadInternalCall(); - return NULL; - } - return ((PyFunctionObject *) op) -> func_module; + if (!PyFunction_Check(op)) { + PyErr_BadInternalCall(); + return NULL; + } + return ((PyFunctionObject *) op) -> func_module; } PyObject * PyFunction_GetDefaults(PyObject *op) { - if (!PyFunction_Check(op)) { - PyErr_BadInternalCall(); - return NULL; - } - return ((PyFunctionObject *) op) -> func_defaults; + if (!PyFunction_Check(op)) { + PyErr_BadInternalCall(); + return NULL; + } + return ((PyFunctionObject *) op) -> func_defaults; } int PyFunction_SetDefaults(PyObject *op, PyObject *defaults) { - if (!PyFunction_Check(op)) { - PyErr_BadInternalCall(); - return -1; - } - if (defaults == Py_None) - defaults = NULL; - else if (defaults && PyTuple_Check(defaults)) { - Py_INCREF(defaults); - } - else { - PyErr_SetString(PyExc_SystemError, "non-tuple default args"); - return -1; - } - Py_XDECREF(((PyFunctionObject *) op) -> func_defaults); - ((PyFunctionObject *) op) -> func_defaults = defaults; - return 0; + if (!PyFunction_Check(op)) { + PyErr_BadInternalCall(); + return -1; + } + if (defaults == Py_None) + defaults = NULL; + else if (defaults && PyTuple_Check(defaults)) { + Py_INCREF(defaults); + } + else { + PyErr_SetString(PyExc_SystemError, "non-tuple default args"); + return -1; + } + Py_XDECREF(((PyFunctionObject *) op) -> func_defaults); + ((PyFunctionObject *) op) -> func_defaults = defaults; + return 0; } PyObject * PyFunction_GetKwDefaults(PyObject *op) { - if (!PyFunction_Check(op)) { - PyErr_BadInternalCall(); - return NULL; - } - return ((PyFunctionObject *) op) -> func_kwdefaults; + if (!PyFunction_Check(op)) { + PyErr_BadInternalCall(); + return NULL; + } + return ((PyFunctionObject *) op) -> func_kwdefaults; } int PyFunction_SetKwDefaults(PyObject *op, PyObject *defaults) { - if (!PyFunction_Check(op)) { - PyErr_BadInternalCall(); - return -1; - } - if (defaults == Py_None) - defaults = NULL; - else if (defaults && PyDict_Check(defaults)) { - Py_INCREF(defaults); - } - else { - PyErr_SetString(PyExc_SystemError, - "non-dict keyword only default args"); - return -1; - } - Py_XDECREF(((PyFunctionObject *)op) -> func_kwdefaults); - ((PyFunctionObject *) op) -> func_kwdefaults = defaults; - return 0; + if (!PyFunction_Check(op)) { + PyErr_BadInternalCall(); + return -1; + } + if (defaults == Py_None) + defaults = NULL; + else if (defaults && PyDict_Check(defaults)) { + Py_INCREF(defaults); + } + else { + PyErr_SetString(PyExc_SystemError, + "non-dict keyword only default args"); + return -1; + } + Py_XDECREF(((PyFunctionObject *)op) -> func_kwdefaults); + ((PyFunctionObject *) op) -> func_kwdefaults = defaults; + return 0; } PyObject * PyFunction_GetClosure(PyObject *op) { - if (!PyFunction_Check(op)) { - PyErr_BadInternalCall(); - return NULL; - } - return ((PyFunctionObject *) op) -> func_closure; + if (!PyFunction_Check(op)) { + PyErr_BadInternalCall(); + return NULL; + } + return ((PyFunctionObject *) op) -> func_closure; } int PyFunction_SetClosure(PyObject *op, PyObject *closure) { - if (!PyFunction_Check(op)) { - PyErr_BadInternalCall(); - return -1; - } - if (closure == Py_None) - closure = NULL; - else if (PyTuple_Check(closure)) { - Py_INCREF(closure); - } - else { - PyErr_Format(PyExc_SystemError, - "expected tuple for closure, got '%.100s'", - closure->ob_type->tp_name); - return -1; - } - Py_XDECREF(((PyFunctionObject *) op) -> func_closure); - ((PyFunctionObject *) op) -> func_closure = closure; - return 0; + if (!PyFunction_Check(op)) { + PyErr_BadInternalCall(); + return -1; + } + if (closure == Py_None) + closure = NULL; + else if (PyTuple_Check(closure)) { + Py_INCREF(closure); + } + else { + PyErr_Format(PyExc_SystemError, + "expected tuple for closure, got '%.100s'", + closure->ob_type->tp_name); + return -1; + } + Py_XDECREF(((PyFunctionObject *) op) -> func_closure); + ((PyFunctionObject *) op) -> func_closure = closure; + return 0; } PyObject * PyFunction_GetAnnotations(PyObject *op) { - if (!PyFunction_Check(op)) { - PyErr_BadInternalCall(); - return NULL; - } - return ((PyFunctionObject *) op) -> func_annotations; + if (!PyFunction_Check(op)) { + PyErr_BadInternalCall(); + return NULL; + } + return ((PyFunctionObject *) op) -> func_annotations; } int PyFunction_SetAnnotations(PyObject *op, PyObject *annotations) { - if (!PyFunction_Check(op)) { - PyErr_BadInternalCall(); - return -1; - } - if (annotations == Py_None) - annotations = NULL; - else if (annotations && PyDict_Check(annotations)) { - Py_INCREF(annotations); - } - else { - PyErr_SetString(PyExc_SystemError, - "non-dict annotations"); - return -1; - } - Py_XDECREF(((PyFunctionObject *)op) -> func_annotations); - ((PyFunctionObject *) op) -> func_annotations = annotations; - return 0; + if (!PyFunction_Check(op)) { + PyErr_BadInternalCall(); + return -1; + } + if (annotations == Py_None) + annotations = NULL; + else if (annotations && PyDict_Check(annotations)) { + Py_INCREF(annotations); + } + else { + PyErr_SetString(PyExc_SystemError, + "non-dict annotations"); + return -1; + } + Py_XDECREF(((PyFunctionObject *)op) -> func_annotations); + ((PyFunctionObject *) op) -> func_annotations = annotations; + return 0; } /* Methods */ @@ -225,224 +225,224 @@ #define OFF(x) offsetof(PyFunctionObject, x) static PyMemberDef func_memberlist[] = { - {"__closure__", T_OBJECT, OFF(func_closure), - RESTRICTED|READONLY}, - {"__doc__", T_OBJECT, OFF(func_doc), PY_WRITE_RESTRICTED}, - {"__globals__", T_OBJECT, OFF(func_globals), - RESTRICTED|READONLY}, - {"__module__", T_OBJECT, OFF(func_module), PY_WRITE_RESTRICTED}, - {NULL} /* Sentinel */ + {"__closure__", T_OBJECT, OFF(func_closure), + RESTRICTED|READONLY}, + {"__doc__", T_OBJECT, OFF(func_doc), PY_WRITE_RESTRICTED}, + {"__globals__", T_OBJECT, OFF(func_globals), + RESTRICTED|READONLY}, + {"__module__", T_OBJECT, OFF(func_module), PY_WRITE_RESTRICTED}, + {NULL} /* Sentinel */ }; static PyObject * func_get_dict(PyFunctionObject *op) { - if (op->func_dict == NULL) { - op->func_dict = PyDict_New(); - if (op->func_dict == NULL) - return NULL; - } - Py_INCREF(op->func_dict); - return op->func_dict; + if (op->func_dict == NULL) { + op->func_dict = PyDict_New(); + if (op->func_dict == NULL) + return NULL; + } + Py_INCREF(op->func_dict); + return op->func_dict; } static int func_set_dict(PyFunctionObject *op, PyObject *value) { - PyObject *tmp; + PyObject *tmp; - /* It is illegal to del f.func_dict */ - if (value == NULL) { - PyErr_SetString(PyExc_TypeError, - "function's dictionary may not be deleted"); - return -1; - } - /* Can only set func_dict to a dictionary */ - if (!PyDict_Check(value)) { - PyErr_SetString(PyExc_TypeError, - "setting function's dictionary to a non-dict"); - return -1; - } - tmp = op->func_dict; - Py_INCREF(value); - op->func_dict = value; - Py_XDECREF(tmp); - return 0; + /* It is illegal to del f.func_dict */ + if (value == NULL) { + PyErr_SetString(PyExc_TypeError, + "function's dictionary may not be deleted"); + return -1; + } + /* Can only set func_dict to a dictionary */ + if (!PyDict_Check(value)) { + PyErr_SetString(PyExc_TypeError, + "setting function's dictionary to a non-dict"); + return -1; + } + tmp = op->func_dict; + Py_INCREF(value); + op->func_dict = value; + Py_XDECREF(tmp); + return 0; } static PyObject * func_get_code(PyFunctionObject *op) { - Py_INCREF(op->func_code); - return op->func_code; + Py_INCREF(op->func_code); + return op->func_code; } static int func_set_code(PyFunctionObject *op, PyObject *value) { - PyObject *tmp; - Py_ssize_t nfree, nclosure; + PyObject *tmp; + Py_ssize_t nfree, nclosure; - /* Not legal to del f.func_code or to set it to anything - * other than a code object. */ - if (value == NULL || !PyCode_Check(value)) { - PyErr_SetString(PyExc_TypeError, - "__code__ must be set to a code object"); - return -1; - } - nfree = PyCode_GetNumFree((PyCodeObject *)value); - nclosure = (op->func_closure == NULL ? 0 : - PyTuple_GET_SIZE(op->func_closure)); - if (nclosure != nfree) { - PyErr_Format(PyExc_ValueError, - "%U() requires a code object with %zd free vars," - " not %zd", - op->func_name, - nclosure, nfree); - return -1; - } - tmp = op->func_code; - Py_INCREF(value); - op->func_code = value; - Py_DECREF(tmp); - return 0; + /* Not legal to del f.func_code or to set it to anything + * other than a code object. */ + if (value == NULL || !PyCode_Check(value)) { + PyErr_SetString(PyExc_TypeError, + "__code__ must be set to a code object"); + return -1; + } + nfree = PyCode_GetNumFree((PyCodeObject *)value); + nclosure = (op->func_closure == NULL ? 0 : + PyTuple_GET_SIZE(op->func_closure)); + if (nclosure != nfree) { + PyErr_Format(PyExc_ValueError, + "%U() requires a code object with %zd free vars," + " not %zd", + op->func_name, + nclosure, nfree); + return -1; + } + tmp = op->func_code; + Py_INCREF(value); + op->func_code = value; + Py_DECREF(tmp); + return 0; } static PyObject * func_get_name(PyFunctionObject *op) { - Py_INCREF(op->func_name); - return op->func_name; + Py_INCREF(op->func_name); + return op->func_name; } static int func_set_name(PyFunctionObject *op, PyObject *value) { - PyObject *tmp; + PyObject *tmp; - /* Not legal to del f.func_name or to set it to anything - * other than a string object. */ - if (value == NULL || !PyUnicode_Check(value)) { - PyErr_SetString(PyExc_TypeError, - "__name__ must be set to a string object"); - return -1; - } - tmp = op->func_name; - Py_INCREF(value); - op->func_name = value; - Py_DECREF(tmp); - return 0; + /* Not legal to del f.func_name or to set it to anything + * other than a string object. */ + if (value == NULL || !PyUnicode_Check(value)) { + PyErr_SetString(PyExc_TypeError, + "__name__ must be set to a string object"); + return -1; + } + tmp = op->func_name; + Py_INCREF(value); + op->func_name = value; + Py_DECREF(tmp); + return 0; } static PyObject * func_get_defaults(PyFunctionObject *op) { - if (op->func_defaults == NULL) { - Py_INCREF(Py_None); - return Py_None; - } - Py_INCREF(op->func_defaults); - return op->func_defaults; + if (op->func_defaults == NULL) { + Py_INCREF(Py_None); + return Py_None; + } + Py_INCREF(op->func_defaults); + return op->func_defaults; } static int func_set_defaults(PyFunctionObject *op, PyObject *value) { - PyObject *tmp; + PyObject *tmp; - /* Legal to del f.func_defaults. - * Can only set func_defaults to NULL or a tuple. */ - if (value == Py_None) - value = NULL; - if (value != NULL && !PyTuple_Check(value)) { - PyErr_SetString(PyExc_TypeError, - "__defaults__ must be set to a tuple object"); - return -1; - } - tmp = op->func_defaults; - Py_XINCREF(value); - op->func_defaults = value; - Py_XDECREF(tmp); - return 0; + /* Legal to del f.func_defaults. + * Can only set func_defaults to NULL or a tuple. */ + if (value == Py_None) + value = NULL; + if (value != NULL && !PyTuple_Check(value)) { + PyErr_SetString(PyExc_TypeError, + "__defaults__ must be set to a tuple object"); + return -1; + } + tmp = op->func_defaults; + Py_XINCREF(value); + op->func_defaults = value; + Py_XDECREF(tmp); + return 0; } static PyObject * func_get_kwdefaults(PyFunctionObject *op) { - if (op->func_kwdefaults == NULL) { - Py_INCREF(Py_None); - return Py_None; - } - Py_INCREF(op->func_kwdefaults); - return op->func_kwdefaults; + if (op->func_kwdefaults == NULL) { + Py_INCREF(Py_None); + return Py_None; + } + Py_INCREF(op->func_kwdefaults); + return op->func_kwdefaults; } static int func_set_kwdefaults(PyFunctionObject *op, PyObject *value) { - PyObject *tmp; + PyObject *tmp; - if (value == Py_None) - value = NULL; - /* Legal to del f.func_kwdefaults. - * Can only set func_kwdefaults to NULL or a dict. */ - if (value != NULL && !PyDict_Check(value)) { - PyErr_SetString(PyExc_TypeError, - "__kwdefaults__ must be set to a dict object"); - return -1; - } - tmp = op->func_kwdefaults; - Py_XINCREF(value); - op->func_kwdefaults = value; - Py_XDECREF(tmp); - return 0; + if (value == Py_None) + value = NULL; + /* Legal to del f.func_kwdefaults. + * Can only set func_kwdefaults to NULL or a dict. */ + if (value != NULL && !PyDict_Check(value)) { + PyErr_SetString(PyExc_TypeError, + "__kwdefaults__ must be set to a dict object"); + return -1; + } + tmp = op->func_kwdefaults; + Py_XINCREF(value); + op->func_kwdefaults = value; + Py_XDECREF(tmp); + return 0; } static PyObject * func_get_annotations(PyFunctionObject *op) { - if (op->func_annotations == NULL) { - op->func_annotations = PyDict_New(); - if (op->func_annotations == NULL) - return NULL; - } - Py_INCREF(op->func_annotations); - return op->func_annotations; + if (op->func_annotations == NULL) { + op->func_annotations = PyDict_New(); + if (op->func_annotations == NULL) + return NULL; + } + Py_INCREF(op->func_annotations); + return op->func_annotations; } static int func_set_annotations(PyFunctionObject *op, PyObject *value) { - PyObject *tmp; + PyObject *tmp; - if (value == Py_None) - value = NULL; - /* Legal to del f.func_annotations. - * Can only set func_annotations to NULL (through C api) - * or a dict. */ - if (value != NULL && !PyDict_Check(value)) { - PyErr_SetString(PyExc_TypeError, - "__annotations__ must be set to a dict object"); - return -1; - } - tmp = op->func_annotations; - Py_XINCREF(value); - op->func_annotations = value; - Py_XDECREF(tmp); - return 0; + if (value == Py_None) + value = NULL; + /* Legal to del f.func_annotations. + * Can only set func_annotations to NULL (through C api) + * or a dict. */ + if (value != NULL && !PyDict_Check(value)) { + PyErr_SetString(PyExc_TypeError, + "__annotations__ must be set to a dict object"); + return -1; + } + tmp = op->func_annotations; + Py_XINCREF(value); + op->func_annotations = value; + Py_XDECREF(tmp); + return 0; } static PyGetSetDef func_getsetlist[] = { - {"__code__", (getter)func_get_code, (setter)func_set_code}, - {"__defaults__", (getter)func_get_defaults, - (setter)func_set_defaults}, - {"__kwdefaults__", (getter)func_get_kwdefaults, - (setter)func_set_kwdefaults}, - {"__annotations__", (getter)func_get_annotations, - (setter)func_set_annotations}, - {"__dict__", (getter)func_get_dict, (setter)func_set_dict}, - {"__name__", (getter)func_get_name, (setter)func_set_name}, - {NULL} /* Sentinel */ + {"__code__", (getter)func_get_code, (setter)func_set_code}, + {"__defaults__", (getter)func_get_defaults, + (setter)func_set_defaults}, + {"__kwdefaults__", (getter)func_get_kwdefaults, + (setter)func_set_kwdefaults}, + {"__annotations__", (getter)func_get_annotations, + (setter)func_set_annotations}, + {"__dict__", (getter)func_get_dict, (setter)func_set_dict}, + {"__name__", (getter)func_get_name, (setter)func_set_name}, + {NULL} /* Sentinel */ }; PyDoc_STRVAR(func_doc, @@ -455,241 +455,241 @@ /* func_new() maintains the following invariants for closures. The closure must correspond to the free variables of the code object. - - if len(code.co_freevars) == 0: - closure = NULL + + if len(code.co_freevars) == 0: + closure = NULL else: - len(closure) == len(code.co_freevars) + len(closure) == len(code.co_freevars) for every elt in closure, type(elt) == cell */ static PyObject * func_new(PyTypeObject* type, PyObject* args, PyObject* kw) { - PyCodeObject *code; - PyObject *globals; - PyObject *name = Py_None; - PyObject *defaults = Py_None; - PyObject *closure = Py_None; - PyFunctionObject *newfunc; - Py_ssize_t nfree, nclosure; - static char *kwlist[] = {"code", "globals", "name", - "argdefs", "closure", 0}; - - if (!PyArg_ParseTupleAndKeywords(args, kw, "O!O!|OOO:function", - kwlist, - &PyCode_Type, &code, - &PyDict_Type, &globals, - &name, &defaults, &closure)) - return NULL; - if (name != Py_None && !PyUnicode_Check(name)) { - PyErr_SetString(PyExc_TypeError, - "arg 3 (name) must be None or string"); - return NULL; - } - if (defaults != Py_None && !PyTuple_Check(defaults)) { - PyErr_SetString(PyExc_TypeError, - "arg 4 (defaults) must be None or tuple"); - return NULL; - } - nfree = PyTuple_GET_SIZE(code->co_freevars); - if (!PyTuple_Check(closure)) { - if (nfree && closure == Py_None) { - PyErr_SetString(PyExc_TypeError, - "arg 5 (closure) must be tuple"); - return NULL; - } - else if (closure != Py_None) { - PyErr_SetString(PyExc_TypeError, - "arg 5 (closure) must be None or tuple"); - return NULL; - } - } - - /* check that the closure is well-formed */ - nclosure = closure == Py_None ? 0 : PyTuple_GET_SIZE(closure); - if (nfree != nclosure) - return PyErr_Format(PyExc_ValueError, - "%U requires closure of length %zd, not %zd", - code->co_name, nfree, nclosure); - if (nclosure) { - Py_ssize_t i; - for (i = 0; i < nclosure; i++) { - PyObject *o = PyTuple_GET_ITEM(closure, i); - if (!PyCell_Check(o)) { - return PyErr_Format(PyExc_TypeError, - "arg 5 (closure) expected cell, found %s", - o->ob_type->tp_name); - } - } - } - - newfunc = (PyFunctionObject *)PyFunction_New((PyObject *)code, - globals); - if (newfunc == NULL) - return NULL; - - if (name != Py_None) { - Py_INCREF(name); - Py_DECREF(newfunc->func_name); - newfunc->func_name = name; - } - if (defaults != Py_None) { - Py_INCREF(defaults); - newfunc->func_defaults = defaults; - } - if (closure != Py_None) { - Py_INCREF(closure); - newfunc->func_closure = closure; - } + PyCodeObject *code; + PyObject *globals; + PyObject *name = Py_None; + PyObject *defaults = Py_None; + PyObject *closure = Py_None; + PyFunctionObject *newfunc; + Py_ssize_t nfree, nclosure; + static char *kwlist[] = {"code", "globals", "name", + "argdefs", "closure", 0}; + + if (!PyArg_ParseTupleAndKeywords(args, kw, "O!O!|OOO:function", + kwlist, + &PyCode_Type, &code, + &PyDict_Type, &globals, + &name, &defaults, &closure)) + return NULL; + if (name != Py_None && !PyUnicode_Check(name)) { + PyErr_SetString(PyExc_TypeError, + "arg 3 (name) must be None or string"); + return NULL; + } + if (defaults != Py_None && !PyTuple_Check(defaults)) { + PyErr_SetString(PyExc_TypeError, + "arg 4 (defaults) must be None or tuple"); + return NULL; + } + nfree = PyTuple_GET_SIZE(code->co_freevars); + if (!PyTuple_Check(closure)) { + if (nfree && closure == Py_None) { + PyErr_SetString(PyExc_TypeError, + "arg 5 (closure) must be tuple"); + return NULL; + } + else if (closure != Py_None) { + PyErr_SetString(PyExc_TypeError, + "arg 5 (closure) must be None or tuple"); + return NULL; + } + } + + /* check that the closure is well-formed */ + nclosure = closure == Py_None ? 0 : PyTuple_GET_SIZE(closure); + if (nfree != nclosure) + return PyErr_Format(PyExc_ValueError, + "%U requires closure of length %zd, not %zd", + code->co_name, nfree, nclosure); + if (nclosure) { + Py_ssize_t i; + for (i = 0; i < nclosure; i++) { + PyObject *o = PyTuple_GET_ITEM(closure, i); + if (!PyCell_Check(o)) { + return PyErr_Format(PyExc_TypeError, + "arg 5 (closure) expected cell, found %s", + o->ob_type->tp_name); + } + } + } + + newfunc = (PyFunctionObject *)PyFunction_New((PyObject *)code, + globals); + if (newfunc == NULL) + return NULL; + + if (name != Py_None) { + Py_INCREF(name); + Py_DECREF(newfunc->func_name); + newfunc->func_name = name; + } + if (defaults != Py_None) { + Py_INCREF(defaults); + newfunc->func_defaults = defaults; + } + if (closure != Py_None) { + Py_INCREF(closure); + newfunc->func_closure = closure; + } - return (PyObject *)newfunc; + return (PyObject *)newfunc; } static void func_dealloc(PyFunctionObject *op) { - _PyObject_GC_UNTRACK(op); - if (op->func_weakreflist != NULL) - PyObject_ClearWeakRefs((PyObject *) op); - Py_DECREF(op->func_code); - Py_DECREF(op->func_globals); - Py_XDECREF(op->func_module); - Py_DECREF(op->func_name); - Py_XDECREF(op->func_defaults); - Py_XDECREF(op->func_kwdefaults); - Py_XDECREF(op->func_doc); - Py_XDECREF(op->func_dict); - Py_XDECREF(op->func_closure); - Py_XDECREF(op->func_annotations); - PyObject_GC_Del(op); + _PyObject_GC_UNTRACK(op); + if (op->func_weakreflist != NULL) + PyObject_ClearWeakRefs((PyObject *) op); + Py_DECREF(op->func_code); + Py_DECREF(op->func_globals); + Py_XDECREF(op->func_module); + Py_DECREF(op->func_name); + Py_XDECREF(op->func_defaults); + Py_XDECREF(op->func_kwdefaults); + Py_XDECREF(op->func_doc); + Py_XDECREF(op->func_dict); + Py_XDECREF(op->func_closure); + Py_XDECREF(op->func_annotations); + PyObject_GC_Del(op); } static PyObject* func_repr(PyFunctionObject *op) { - return PyUnicode_FromFormat("", - op->func_name, op); + return PyUnicode_FromFormat("", + op->func_name, op); } static int func_traverse(PyFunctionObject *f, visitproc visit, void *arg) { - Py_VISIT(f->func_code); - Py_VISIT(f->func_globals); - Py_VISIT(f->func_module); - Py_VISIT(f->func_defaults); - Py_VISIT(f->func_kwdefaults); - Py_VISIT(f->func_doc); - Py_VISIT(f->func_name); - Py_VISIT(f->func_dict); - Py_VISIT(f->func_closure); - Py_VISIT(f->func_annotations); - return 0; + Py_VISIT(f->func_code); + Py_VISIT(f->func_globals); + Py_VISIT(f->func_module); + Py_VISIT(f->func_defaults); + Py_VISIT(f->func_kwdefaults); + Py_VISIT(f->func_doc); + Py_VISIT(f->func_name); + Py_VISIT(f->func_dict); + Py_VISIT(f->func_closure); + Py_VISIT(f->func_annotations); + return 0; } static PyObject * function_call(PyObject *func, PyObject *arg, PyObject *kw) { - PyObject *result; - PyObject *argdefs; - PyObject *kwtuple = NULL; - PyObject **d, **k; - Py_ssize_t nk, nd; - - argdefs = PyFunction_GET_DEFAULTS(func); - if (argdefs != NULL && PyTuple_Check(argdefs)) { - d = &PyTuple_GET_ITEM((PyTupleObject *)argdefs, 0); - nd = PyTuple_GET_SIZE(argdefs); - } - else { - d = NULL; - nd = 0; - } - - if (kw != NULL && PyDict_Check(kw)) { - Py_ssize_t pos, i; - nk = PyDict_Size(kw); - kwtuple = PyTuple_New(2*nk); - if (kwtuple == NULL) - return NULL; - k = &PyTuple_GET_ITEM(kwtuple, 0); - pos = i = 0; - while (PyDict_Next(kw, &pos, &k[i], &k[i+1])) { - Py_INCREF(k[i]); - Py_INCREF(k[i+1]); - i += 2; - } - nk = i/2; - } - else { - k = NULL; - nk = 0; - } - - result = PyEval_EvalCodeEx( - (PyCodeObject *)PyFunction_GET_CODE(func), - PyFunction_GET_GLOBALS(func), (PyObject *)NULL, - &PyTuple_GET_ITEM(arg, 0), PyTuple_GET_SIZE(arg), - k, nk, d, nd, - PyFunction_GET_KW_DEFAULTS(func), - PyFunction_GET_CLOSURE(func)); + PyObject *result; + PyObject *argdefs; + PyObject *kwtuple = NULL; + PyObject **d, **k; + Py_ssize_t nk, nd; + + argdefs = PyFunction_GET_DEFAULTS(func); + if (argdefs != NULL && PyTuple_Check(argdefs)) { + d = &PyTuple_GET_ITEM((PyTupleObject *)argdefs, 0); + nd = PyTuple_GET_SIZE(argdefs); + } + else { + d = NULL; + nd = 0; + } + + if (kw != NULL && PyDict_Check(kw)) { + Py_ssize_t pos, i; + nk = PyDict_Size(kw); + kwtuple = PyTuple_New(2*nk); + if (kwtuple == NULL) + return NULL; + k = &PyTuple_GET_ITEM(kwtuple, 0); + pos = i = 0; + while (PyDict_Next(kw, &pos, &k[i], &k[i+1])) { + Py_INCREF(k[i]); + Py_INCREF(k[i+1]); + i += 2; + } + nk = i/2; + } + else { + k = NULL; + nk = 0; + } + + result = PyEval_EvalCodeEx( + (PyCodeObject *)PyFunction_GET_CODE(func), + PyFunction_GET_GLOBALS(func), (PyObject *)NULL, + &PyTuple_GET_ITEM(arg, 0), PyTuple_GET_SIZE(arg), + k, nk, d, nd, + PyFunction_GET_KW_DEFAULTS(func), + PyFunction_GET_CLOSURE(func)); - Py_XDECREF(kwtuple); + Py_XDECREF(kwtuple); - return result; + return result; } /* Bind a function to an object */ static PyObject * func_descr_get(PyObject *func, PyObject *obj, PyObject *type) { - if (obj == Py_None || obj == NULL) { - Py_INCREF(func); - return func; - } - return PyMethod_New(func, obj); + if (obj == Py_None || obj == NULL) { + Py_INCREF(func); + return func; + } + return PyMethod_New(func, obj); } PyTypeObject PyFunction_Type = { - PyVarObject_HEAD_INIT(&PyType_Type, 0) - "function", - sizeof(PyFunctionObject), - 0, - (destructor)func_dealloc, /* tp_dealloc */ - 0, /* tp_print */ - 0, /* tp_getattr */ - 0, /* tp_setattr */ - 0, /* tp_reserved */ - (reprfunc)func_repr, /* tp_repr */ - 0, /* tp_as_number */ - 0, /* tp_as_sequence */ - 0, /* tp_as_mapping */ - 0, /* tp_hash */ - function_call, /* tp_call */ - 0, /* tp_str */ - PyObject_GenericGetAttr, /* tp_getattro */ - PyObject_GenericSetAttr, /* tp_setattro */ - 0, /* tp_as_buffer */ - Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */ - func_doc, /* tp_doc */ - (traverseproc)func_traverse, /* tp_traverse */ - 0, /* tp_clear */ - 0, /* tp_richcompare */ - offsetof(PyFunctionObject, func_weakreflist), /* tp_weaklistoffset */ - 0, /* tp_iter */ - 0, /* tp_iternext */ - 0, /* tp_methods */ - func_memberlist, /* tp_members */ - func_getsetlist, /* tp_getset */ - 0, /* tp_base */ - 0, /* tp_dict */ - func_descr_get, /* tp_descr_get */ - 0, /* tp_descr_set */ - offsetof(PyFunctionObject, func_dict), /* tp_dictoffset */ - 0, /* tp_init */ - 0, /* tp_alloc */ - func_new, /* tp_new */ + PyVarObject_HEAD_INIT(&PyType_Type, 0) + "function", + sizeof(PyFunctionObject), + 0, + (destructor)func_dealloc, /* tp_dealloc */ + 0, /* tp_print */ + 0, /* tp_getattr */ + 0, /* tp_setattr */ + 0, /* tp_reserved */ + (reprfunc)func_repr, /* tp_repr */ + 0, /* tp_as_number */ + 0, /* tp_as_sequence */ + 0, /* tp_as_mapping */ + 0, /* tp_hash */ + function_call, /* tp_call */ + 0, /* tp_str */ + PyObject_GenericGetAttr, /* tp_getattro */ + PyObject_GenericSetAttr, /* tp_setattro */ + 0, /* tp_as_buffer */ + Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */ + func_doc, /* tp_doc */ + (traverseproc)func_traverse, /* tp_traverse */ + 0, /* tp_clear */ + 0, /* tp_richcompare */ + offsetof(PyFunctionObject, func_weakreflist), /* tp_weaklistoffset */ + 0, /* tp_iter */ + 0, /* tp_iternext */ + 0, /* tp_methods */ + func_memberlist, /* tp_members */ + func_getsetlist, /* tp_getset */ + 0, /* tp_base */ + 0, /* tp_dict */ + func_descr_get, /* tp_descr_get */ + 0, /* tp_descr_set */ + offsetof(PyFunctionObject, func_dict), /* tp_dictoffset */ + 0, /* tp_init */ + 0, /* tp_alloc */ + func_new, /* tp_new */ }; @@ -700,9 +700,9 @@ To declare a class method, use this idiom: class C: - def f(cls, arg1, arg2, ...): ... - f = classmethod(f) - + def f(cls, arg1, arg2, ...): ... + f = classmethod(f) + It can be called either on the class (e.g. C.f()) or on an instance (e.g. C().f()); the instance is ignored except for its class. If a class method is called for a derived class, the derived class @@ -713,66 +713,66 @@ */ typedef struct { - PyObject_HEAD - PyObject *cm_callable; + PyObject_HEAD + PyObject *cm_callable; } classmethod; static void cm_dealloc(classmethod *cm) { - _PyObject_GC_UNTRACK((PyObject *)cm); - Py_XDECREF(cm->cm_callable); - Py_TYPE(cm)->tp_free((PyObject *)cm); + _PyObject_GC_UNTRACK((PyObject *)cm); + Py_XDECREF(cm->cm_callable); + Py_TYPE(cm)->tp_free((PyObject *)cm); } static int cm_traverse(classmethod *cm, visitproc visit, void *arg) { - Py_VISIT(cm->cm_callable); - return 0; + Py_VISIT(cm->cm_callable); + return 0; } static int cm_clear(classmethod *cm) { - Py_CLEAR(cm->cm_callable); - return 0; + Py_CLEAR(cm->cm_callable); + return 0; } static PyObject * cm_descr_get(PyObject *self, PyObject *obj, PyObject *type) { - classmethod *cm = (classmethod *)self; + classmethod *cm = (classmethod *)self; - if (cm->cm_callable == NULL) { - PyErr_SetString(PyExc_RuntimeError, - "uninitialized classmethod object"); - return NULL; - } - if (type == NULL) - type = (PyObject *)(Py_TYPE(obj)); - return PyMethod_New(cm->cm_callable, type); + if (cm->cm_callable == NULL) { + PyErr_SetString(PyExc_RuntimeError, + "uninitialized classmethod object"); + return NULL; + } + if (type == NULL) + type = (PyObject *)(Py_TYPE(obj)); + return PyMethod_New(cm->cm_callable, type); } static int cm_init(PyObject *self, PyObject *args, PyObject *kwds) { - classmethod *cm = (classmethod *)self; - PyObject *callable; + classmethod *cm = (classmethod *)self; + PyObject *callable; - if (!PyArg_UnpackTuple(args, "classmethod", 1, 1, &callable)) - return -1; - if (!_PyArg_NoKeywords("classmethod", kwds)) - return -1; - Py_INCREF(callable); - cm->cm_callable = callable; - return 0; + if (!PyArg_UnpackTuple(args, "classmethod", 1, 1, &callable)) + return -1; + if (!_PyArg_NoKeywords("classmethod", kwds)) + return -1; + Py_INCREF(callable); + cm->cm_callable = callable; + return 0; } static PyMemberDef cm_memberlist[] = { - {"__func__", T_OBJECT, offsetof(classmethod, cm_callable), READONLY}, - {NULL} /* Sentinel */ + {"__func__", T_OBJECT, offsetof(classmethod, cm_callable), READONLY}, + {NULL} /* Sentinel */ }; PyDoc_STRVAR(classmethod_doc, @@ -797,57 +797,57 @@ If you want those, see the staticmethod builtin."); PyTypeObject PyClassMethod_Type = { - PyVarObject_HEAD_INIT(&PyType_Type, 0) - "classmethod", - sizeof(classmethod), - 0, - (destructor)cm_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_BASETYPE | Py_TPFLAGS_HAVE_GC, - classmethod_doc, /* tp_doc */ - (traverseproc)cm_traverse, /* tp_traverse */ - (inquiry)cm_clear, /* tp_clear */ - 0, /* tp_richcompare */ - 0, /* tp_weaklistoffset */ - 0, /* tp_iter */ - 0, /* tp_iternext */ - 0, /* tp_methods */ - cm_memberlist, /* tp_members */ - 0, /* tp_getset */ - 0, /* tp_base */ - 0, /* tp_dict */ - cm_descr_get, /* tp_descr_get */ - 0, /* tp_descr_set */ - 0, /* tp_dictoffset */ - cm_init, /* tp_init */ - PyType_GenericAlloc, /* tp_alloc */ - PyType_GenericNew, /* tp_new */ - PyObject_GC_Del, /* tp_free */ + PyVarObject_HEAD_INIT(&PyType_Type, 0) + "classmethod", + sizeof(classmethod), + 0, + (destructor)cm_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_BASETYPE | Py_TPFLAGS_HAVE_GC, + classmethod_doc, /* tp_doc */ + (traverseproc)cm_traverse, /* tp_traverse */ + (inquiry)cm_clear, /* tp_clear */ + 0, /* tp_richcompare */ + 0, /* tp_weaklistoffset */ + 0, /* tp_iter */ + 0, /* tp_iternext */ + 0, /* tp_methods */ + cm_memberlist, /* tp_members */ + 0, /* tp_getset */ + 0, /* tp_base */ + 0, /* tp_dict */ + cm_descr_get, /* tp_descr_get */ + 0, /* tp_descr_set */ + 0, /* tp_dictoffset */ + cm_init, /* tp_init */ + PyType_GenericAlloc, /* tp_alloc */ + PyType_GenericNew, /* tp_new */ + PyObject_GC_Del, /* tp_free */ }; PyObject * PyClassMethod_New(PyObject *callable) { - classmethod *cm = (classmethod *) - PyType_GenericAlloc(&PyClassMethod_Type, 0); - if (cm != NULL) { - Py_INCREF(callable); - cm->cm_callable = callable; - } - return (PyObject *)cm; + classmethod *cm = (classmethod *) + PyType_GenericAlloc(&PyClassMethod_Type, 0); + if (cm != NULL) { + Py_INCREF(callable); + cm->cm_callable = callable; + } + return (PyObject *)cm; } @@ -857,8 +857,8 @@ To declare a static method, use this idiom: class C: - def f(arg1, arg2, ...): ... - f = staticmethod(f) + def f(arg1, arg2, ...): ... + f = staticmethod(f) It can be called either on the class (e.g. C.f()) or on an instance (e.g. C().f()); the instance is ignored except for its class. @@ -868,66 +868,66 @@ */ typedef struct { - PyObject_HEAD - PyObject *sm_callable; + PyObject_HEAD + PyObject *sm_callable; } staticmethod; static void sm_dealloc(staticmethod *sm) { - _PyObject_GC_UNTRACK((PyObject *)sm); - Py_XDECREF(sm->sm_callable); - Py_TYPE(sm)->tp_free((PyObject *)sm); + _PyObject_GC_UNTRACK((PyObject *)sm); + Py_XDECREF(sm->sm_callable); + Py_TYPE(sm)->tp_free((PyObject *)sm); } static int sm_traverse(staticmethod *sm, visitproc visit, void *arg) { - Py_VISIT(sm->sm_callable); - return 0; + Py_VISIT(sm->sm_callable); + return 0; } static int sm_clear(staticmethod *sm) { - Py_XDECREF(sm->sm_callable); - sm->sm_callable = NULL; + Py_XDECREF(sm->sm_callable); + sm->sm_callable = NULL; - return 0; + return 0; } static PyObject * sm_descr_get(PyObject *self, PyObject *obj, PyObject *type) { - staticmethod *sm = (staticmethod *)self; + staticmethod *sm = (staticmethod *)self; - if (sm->sm_callable == NULL) { - PyErr_SetString(PyExc_RuntimeError, - "uninitialized staticmethod object"); - return NULL; - } - Py_INCREF(sm->sm_callable); - return sm->sm_callable; + if (sm->sm_callable == NULL) { + PyErr_SetString(PyExc_RuntimeError, + "uninitialized staticmethod object"); + return NULL; + } + Py_INCREF(sm->sm_callable); + return sm->sm_callable; } static int sm_init(PyObject *self, PyObject *args, PyObject *kwds) { - staticmethod *sm = (staticmethod *)self; - PyObject *callable; + staticmethod *sm = (staticmethod *)self; + PyObject *callable; - if (!PyArg_UnpackTuple(args, "staticmethod", 1, 1, &callable)) - return -1; - if (!_PyArg_NoKeywords("staticmethod", kwds)) - return -1; - Py_INCREF(callable); - sm->sm_callable = callable; - return 0; + if (!PyArg_UnpackTuple(args, "staticmethod", 1, 1, &callable)) + return -1; + if (!_PyArg_NoKeywords("staticmethod", kwds)) + return -1; + Py_INCREF(callable); + sm->sm_callable = callable; + return 0; } static PyMemberDef sm_memberlist[] = { - {"__func__", T_OBJECT, offsetof(staticmethod, sm_callable), READONLY}, - {NULL} /* Sentinel */ + {"__func__", T_OBJECT, offsetof(staticmethod, sm_callable), READONLY}, + {NULL} /* Sentinel */ }; PyDoc_STRVAR(staticmethod_doc, @@ -939,8 +939,8 @@ To declare a static method, use this idiom:\n\ \n\ class C:\n\ - def f(arg1, arg2, ...): ...\n\ - f = staticmethod(f)\n\ + def f(arg1, arg2, ...): ...\n\ + f = staticmethod(f)\n\ \n\ It can be called either on the class (e.g. C.f()) or on an instance\n\ (e.g. C().f()). The instance is ignored except for its class.\n\ @@ -949,55 +949,55 @@ For a more advanced concept, see the classmethod builtin."); PyTypeObject PyStaticMethod_Type = { - PyVarObject_HEAD_INIT(&PyType_Type, 0) - "staticmethod", - sizeof(staticmethod), - 0, - (destructor)sm_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_BASETYPE | Py_TPFLAGS_HAVE_GC, - staticmethod_doc, /* tp_doc */ - (traverseproc)sm_traverse, /* tp_traverse */ - (inquiry)sm_clear, /* tp_clear */ - 0, /* tp_richcompare */ - 0, /* tp_weaklistoffset */ - 0, /* tp_iter */ - 0, /* tp_iternext */ - 0, /* tp_methods */ - sm_memberlist, /* tp_members */ - 0, /* tp_getset */ - 0, /* tp_base */ - 0, /* tp_dict */ - sm_descr_get, /* tp_descr_get */ - 0, /* tp_descr_set */ - 0, /* tp_dictoffset */ - sm_init, /* tp_init */ - PyType_GenericAlloc, /* tp_alloc */ - PyType_GenericNew, /* tp_new */ - PyObject_GC_Del, /* tp_free */ + PyVarObject_HEAD_INIT(&PyType_Type, 0) + "staticmethod", + sizeof(staticmethod), + 0, + (destructor)sm_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_BASETYPE | Py_TPFLAGS_HAVE_GC, + staticmethod_doc, /* tp_doc */ + (traverseproc)sm_traverse, /* tp_traverse */ + (inquiry)sm_clear, /* tp_clear */ + 0, /* tp_richcompare */ + 0, /* tp_weaklistoffset */ + 0, /* tp_iter */ + 0, /* tp_iternext */ + 0, /* tp_methods */ + sm_memberlist, /* tp_members */ + 0, /* tp_getset */ + 0, /* tp_base */ + 0, /* tp_dict */ + sm_descr_get, /* tp_descr_get */ + 0, /* tp_descr_set */ + 0, /* tp_dictoffset */ + sm_init, /* tp_init */ + PyType_GenericAlloc, /* tp_alloc */ + PyType_GenericNew, /* tp_new */ + PyObject_GC_Del, /* tp_free */ }; PyObject * PyStaticMethod_New(PyObject *callable) { - staticmethod *sm = (staticmethod *) - PyType_GenericAlloc(&PyStaticMethod_Type, 0); - if (sm != NULL) { - Py_INCREF(callable); - sm->sm_callable = callable; - } - return (PyObject *)sm; + staticmethod *sm = (staticmethod *) + PyType_GenericAlloc(&PyStaticMethod_Type, 0); + if (sm != NULL) { + Py_INCREF(callable); + sm->sm_callable = callable; + } + return (PyObject *)sm; } Modified: python/branches/py3k-jit/Objects/genobject.c ============================================================================== --- python/branches/py3k-jit/Objects/genobject.c (original) +++ python/branches/py3k-jit/Objects/genobject.c Mon May 10 23:55:43 2010 @@ -10,103 +10,103 @@ static int gen_traverse(PyGenObject *gen, visitproc visit, void *arg) { - Py_VISIT((PyObject *)gen->gi_frame); - Py_VISIT(gen->gi_code); - return 0; + Py_VISIT((PyObject *)gen->gi_frame); + Py_VISIT(gen->gi_code); + return 0; } static void gen_dealloc(PyGenObject *gen) { - PyObject *self = (PyObject *) gen; + PyObject *self = (PyObject *) gen; - _PyObject_GC_UNTRACK(gen); + _PyObject_GC_UNTRACK(gen); - if (gen->gi_weakreflist != NULL) - PyObject_ClearWeakRefs(self); + if (gen->gi_weakreflist != NULL) + PyObject_ClearWeakRefs(self); - _PyObject_GC_TRACK(self); + _PyObject_GC_TRACK(self); - if (gen->gi_frame != NULL && gen->gi_frame->f_stacktop != NULL) { - /* Generator is paused, so we need to close */ - Py_TYPE(gen)->tp_del(self); - if (self->ob_refcnt > 0) - return; /* resurrected. :( */ - } - - _PyObject_GC_UNTRACK(self); - Py_CLEAR(gen->gi_frame); - Py_CLEAR(gen->gi_code); - PyObject_GC_Del(gen); + if (gen->gi_frame != NULL && gen->gi_frame->f_stacktop != NULL) { + /* Generator is paused, so we need to close */ + Py_TYPE(gen)->tp_del(self); + if (self->ob_refcnt > 0) + return; /* resurrected. :( */ + } + + _PyObject_GC_UNTRACK(self); + Py_CLEAR(gen->gi_frame); + Py_CLEAR(gen->gi_code); + PyObject_GC_Del(gen); } static PyObject * gen_send_ex(PyGenObject *gen, PyObject *arg, int exc) { - PyThreadState *tstate = PyThreadState_GET(); - PyFrameObject *f = gen->gi_frame; - PyObject *result; - - if (gen->gi_running) { - PyErr_SetString(PyExc_ValueError, - "generator already executing"); - return NULL; - } - if (f==NULL || f->f_stacktop == NULL) { - /* Only set exception if called from send() */ - if (arg && !exc) - PyErr_SetNone(PyExc_StopIteration); - return NULL; - } - - if (f->f_lasti == -1) { - if (arg && arg != Py_None) { - PyErr_SetString(PyExc_TypeError, - "can't send non-None value to a " - "just-started generator"); - return NULL; - } - } else { - /* Push arg onto the frame's value stack */ - result = arg ? arg : Py_None; - Py_INCREF(result); - *(f->f_stacktop++) = result; - } - - /* Generators always return to their most recent caller, not - * necessarily their creator. */ - Py_XINCREF(tstate->frame); - assert(f->f_back == NULL); - f->f_back = tstate->frame; - - gen->gi_running = 1; - result = PyEval_EvalFrameEx(f, exc); - gen->gi_running = 0; - - /* Don't keep the reference to f_back any longer than necessary. It - * may keep a chain of frames alive or it could create a reference - * cycle. */ - assert(f->f_back == tstate->frame); - Py_CLEAR(f->f_back); - - /* If the generator just returned (as opposed to yielding), signal - * that the generator is exhausted. */ - if (result == Py_None && f->f_stacktop == NULL) { - Py_DECREF(result); - result = NULL; - /* Set exception if not called by gen_iternext() */ - if (arg) - PyErr_SetNone(PyExc_StopIteration); - } - - if (!result || f->f_stacktop == NULL) { - /* generator can't be rerun, so release the frame */ - Py_DECREF(f); - gen->gi_frame = NULL; - } + PyThreadState *tstate = PyThreadState_GET(); + PyFrameObject *f = gen->gi_frame; + PyObject *result; + + if (gen->gi_running) { + PyErr_SetString(PyExc_ValueError, + "generator already executing"); + return NULL; + } + if (f==NULL || f->f_stacktop == NULL) { + /* Only set exception if called from send() */ + if (arg && !exc) + PyErr_SetNone(PyExc_StopIteration); + return NULL; + } + + if (f->f_lasti == -1) { + if (arg && arg != Py_None) { + PyErr_SetString(PyExc_TypeError, + "can't send non-None value to a " + "just-started generator"); + return NULL; + } + } else { + /* Push arg onto the frame's value stack */ + result = arg ? arg : Py_None; + Py_INCREF(result); + *(f->f_stacktop++) = result; + } + + /* Generators always return to their most recent caller, not + * necessarily their creator. */ + Py_XINCREF(tstate->frame); + assert(f->f_back == NULL); + f->f_back = tstate->frame; + + gen->gi_running = 1; + result = PyEval_EvalFrameEx(f, exc); + gen->gi_running = 0; + + /* Don't keep the reference to f_back any longer than necessary. It + * may keep a chain of frames alive or it could create a reference + * cycle. */ + assert(f->f_back == tstate->frame); + Py_CLEAR(f->f_back); + + /* If the generator just returned (as opposed to yielding), signal + * that the generator is exhausted. */ + if (result == Py_None && f->f_stacktop == NULL) { + Py_DECREF(result); + result = NULL; + /* Set exception if not called by gen_iternext() */ + if (arg) + PyErr_SetNone(PyExc_StopIteration); + } + + if (!result || f->f_stacktop == NULL) { + /* generator can't be rerun, so release the frame */ + Py_DECREF(f); + gen->gi_frame = NULL; + } - return result; + return result; } PyDoc_STRVAR(send_doc, @@ -116,7 +116,7 @@ static PyObject * gen_send(PyGenObject *gen, PyObject *arg) { - return gen_send_ex(gen, arg, 0); + return gen_send_ex(gen, arg, 0); } PyDoc_STRVAR(close_doc, @@ -125,83 +125,83 @@ static PyObject * gen_close(PyGenObject *gen, PyObject *args) { - PyObject *retval; - PyErr_SetNone(PyExc_GeneratorExit); - retval = gen_send_ex(gen, Py_None, 1); - if (retval) { - Py_DECREF(retval); - PyErr_SetString(PyExc_RuntimeError, - "generator ignored GeneratorExit"); - return NULL; - } - if (PyErr_ExceptionMatches(PyExc_StopIteration) - || PyErr_ExceptionMatches(PyExc_GeneratorExit)) - { - PyErr_Clear(); /* ignore these errors */ - Py_INCREF(Py_None); - return Py_None; - } - return NULL; + PyObject *retval; + PyErr_SetNone(PyExc_GeneratorExit); + retval = gen_send_ex(gen, Py_None, 1); + if (retval) { + Py_DECREF(retval); + PyErr_SetString(PyExc_RuntimeError, + "generator ignored GeneratorExit"); + return NULL; + } + if (PyErr_ExceptionMatches(PyExc_StopIteration) + || PyErr_ExceptionMatches(PyExc_GeneratorExit)) + { + PyErr_Clear(); /* ignore these errors */ + Py_INCREF(Py_None); + return Py_None; + } + return NULL; } static void gen_del(PyObject *self) { - PyObject *res; - PyObject *error_type, *error_value, *error_traceback; - PyGenObject *gen = (PyGenObject *)self; - - if (gen->gi_frame == NULL || gen->gi_frame->f_stacktop == NULL) - /* Generator isn't paused, so no need to close */ - return; - - /* Temporarily resurrect the object. */ - assert(self->ob_refcnt == 0); - self->ob_refcnt = 1; - - /* Save the current exception, if any. */ - PyErr_Fetch(&error_type, &error_value, &error_traceback); - - res = gen_close(gen, NULL); - - if (res == NULL) - PyErr_WriteUnraisable(self); - else - Py_DECREF(res); - - /* Restore the saved exception. */ - PyErr_Restore(error_type, error_value, error_traceback); - - /* Undo the temporary resurrection; can't use DECREF here, it would - * cause a recursive call. - */ - assert(self->ob_refcnt > 0); - if (--self->ob_refcnt == 0) - return; /* this is the normal path out */ - - /* close() resurrected it! Make it look like the original Py_DECREF - * never happened. - */ - { - Py_ssize_t refcnt = self->ob_refcnt; - _Py_NewReference(self); - self->ob_refcnt = refcnt; - } - assert(PyType_IS_GC(self->ob_type) && - _Py_AS_GC(self)->gc.gc_refs != _PyGC_REFS_UNTRACKED); - - /* If Py_REF_DEBUG, _Py_NewReference bumped _Py_RefTotal, so - * we need to undo that. */ - _Py_DEC_REFTOTAL; - /* If Py_TRACE_REFS, _Py_NewReference re-added self to the object - * chain, so no more to do there. - * If COUNT_ALLOCS, the original decref bumped tp_frees, and - * _Py_NewReference bumped tp_allocs: both of those need to be - * undone. - */ + PyObject *res; + PyObject *error_type, *error_value, *error_traceback; + PyGenObject *gen = (PyGenObject *)self; + + if (gen->gi_frame == NULL || gen->gi_frame->f_stacktop == NULL) + /* Generator isn't paused, so no need to close */ + return; + + /* Temporarily resurrect the object. */ + assert(self->ob_refcnt == 0); + self->ob_refcnt = 1; + + /* Save the current exception, if any. */ + PyErr_Fetch(&error_type, &error_value, &error_traceback); + + res = gen_close(gen, NULL); + + if (res == NULL) + PyErr_WriteUnraisable(self); + else + Py_DECREF(res); + + /* Restore the saved exception. */ + PyErr_Restore(error_type, error_value, error_traceback); + + /* Undo the temporary resurrection; can't use DECREF here, it would + * cause a recursive call. + */ + assert(self->ob_refcnt > 0); + if (--self->ob_refcnt == 0) + return; /* this is the normal path out */ + + /* close() resurrected it! Make it look like the original Py_DECREF + * never happened. + */ + { + Py_ssize_t refcnt = self->ob_refcnt; + _Py_NewReference(self); + self->ob_refcnt = refcnt; + } + assert(PyType_IS_GC(self->ob_type) && + _Py_AS_GC(self)->gc.gc_refs != _PyGC_REFS_UNTRACKED); + + /* If Py_REF_DEBUG, _Py_NewReference bumped _Py_RefTotal, so + * we need to undo that. */ + _Py_DEC_REFTOTAL; + /* If Py_TRACE_REFS, _Py_NewReference re-added self to the object + * chain, so no more to do there. + * If COUNT_ALLOCS, the original decref bumped tp_frees, and + * _Py_NewReference bumped tp_allocs: both of those need to be + * undone. + */ #ifdef COUNT_ALLOCS - --self->ob_type->tp_frees; - --self->ob_type->tp_allocs; + --self->ob_type->tp_frees; + --self->ob_type->tp_allocs; #endif } @@ -214,89 +214,89 @@ static PyObject * gen_throw(PyGenObject *gen, PyObject *args) { - PyObject *typ; - PyObject *tb = NULL; - PyObject *val = NULL; - - if (!PyArg_UnpackTuple(args, "throw", 1, 3, &typ, &val, &tb)) - return NULL; - - /* First, check the traceback argument, replacing None with - NULL. */ - if (tb == Py_None) - tb = NULL; - else if (tb != NULL && !PyTraceBack_Check(tb)) { - PyErr_SetString(PyExc_TypeError, - "throw() third argument must be a traceback object"); - return NULL; - } - - Py_INCREF(typ); - Py_XINCREF(val); - Py_XINCREF(tb); - - if (PyExceptionClass_Check(typ)) { - PyErr_NormalizeException(&typ, &val, &tb); - } - - else if (PyExceptionInstance_Check(typ)) { - /* Raising an instance. The value should be a dummy. */ - if (val && val != Py_None) { - PyErr_SetString(PyExc_TypeError, - "instance exception may not have a separate value"); - goto failed_throw; - } - else { - /* Normalize to raise , */ - Py_XDECREF(val); - val = typ; - typ = PyExceptionInstance_Class(typ); - Py_INCREF(typ); - } - } - else { - /* Not something you can raise. throw() fails. */ - PyErr_Format(PyExc_TypeError, - "exceptions must be classes or instances " - "deriving from BaseException, not %s", - typ->ob_type->tp_name); - goto failed_throw; - } + PyObject *typ; + PyObject *tb = NULL; + PyObject *val = NULL; + + if (!PyArg_UnpackTuple(args, "throw", 1, 3, &typ, &val, &tb)) + return NULL; + + /* First, check the traceback argument, replacing None with + NULL. */ + if (tb == Py_None) + tb = NULL; + else if (tb != NULL && !PyTraceBack_Check(tb)) { + PyErr_SetString(PyExc_TypeError, + "throw() third argument must be a traceback object"); + return NULL; + } + + Py_INCREF(typ); + Py_XINCREF(val); + Py_XINCREF(tb); + + if (PyExceptionClass_Check(typ)) { + PyErr_NormalizeException(&typ, &val, &tb); + } + + else if (PyExceptionInstance_Check(typ)) { + /* Raising an instance. The value should be a dummy. */ + if (val && val != Py_None) { + PyErr_SetString(PyExc_TypeError, + "instance exception may not have a separate value"); + goto failed_throw; + } + else { + /* Normalize to raise , */ + Py_XDECREF(val); + val = typ; + typ = PyExceptionInstance_Class(typ); + Py_INCREF(typ); + } + } + else { + /* Not something you can raise. throw() fails. */ + PyErr_Format(PyExc_TypeError, + "exceptions must be classes or instances " + "deriving from BaseException, not %s", + typ->ob_type->tp_name); + goto failed_throw; + } - PyErr_Restore(typ, val, tb); - return gen_send_ex(gen, Py_None, 1); + PyErr_Restore(typ, val, tb); + return gen_send_ex(gen, Py_None, 1); failed_throw: - /* Didn't use our arguments, so restore their original refcounts */ - Py_DECREF(typ); - Py_XDECREF(val); - Py_XDECREF(tb); - return NULL; + /* Didn't use our arguments, so restore their original refcounts */ + Py_DECREF(typ); + Py_XDECREF(val); + Py_XDECREF(tb); + return NULL; } static PyObject * gen_iternext(PyGenObject *gen) { - return gen_send_ex(gen, NULL, 0); + return gen_send_ex(gen, NULL, 0); } static PyObject * gen_repr(PyGenObject *gen) { - return PyUnicode_FromFormat("", - ((PyCodeObject *)gen->gi_code)->co_name, - gen); + return PyUnicode_FromFormat("", + ((PyCodeObject *)gen->gi_code)->co_name, + gen); } static PyObject * gen_get_name(PyGenObject *gen) { - PyObject *name = ((PyCodeObject *)gen->gi_code)->co_name; - Py_INCREF(name); - return name; + PyObject *name = ((PyCodeObject *)gen->gi_code)->co_name; + Py_INCREF(name); + return name; } @@ -304,109 +304,109 @@ "Return the name of the generator's associated code object."); static PyGetSetDef gen_getsetlist[] = { - {"__name__", (getter)gen_get_name, NULL, gen__name__doc__}, - {NULL} + {"__name__", (getter)gen_get_name, NULL, gen__name__doc__}, + {NULL} }; static PyMemberDef gen_memberlist[] = { - {"gi_frame", T_OBJECT, offsetof(PyGenObject, gi_frame), READONLY}, - {"gi_running", T_INT, offsetof(PyGenObject, gi_running), READONLY}, - {"gi_code", T_OBJECT, offsetof(PyGenObject, gi_code), READONLY}, - {NULL} /* Sentinel */ + {"gi_frame", T_OBJECT, offsetof(PyGenObject, gi_frame), READONLY}, + {"gi_running", T_INT, offsetof(PyGenObject, gi_running), READONLY}, + {"gi_code", T_OBJECT, offsetof(PyGenObject, gi_code), READONLY}, + {NULL} /* Sentinel */ }; static PyMethodDef gen_methods[] = { - {"send",(PyCFunction)gen_send, METH_O, send_doc}, - {"throw",(PyCFunction)gen_throw, METH_VARARGS, throw_doc}, - {"close",(PyCFunction)gen_close, METH_NOARGS, close_doc}, - {NULL, NULL} /* Sentinel */ + {"send",(PyCFunction)gen_send, METH_O, send_doc}, + {"throw",(PyCFunction)gen_throw, METH_VARARGS, throw_doc}, + {"close",(PyCFunction)gen_close, METH_NOARGS, close_doc}, + {NULL, NULL} /* Sentinel */ }; PyTypeObject PyGen_Type = { - PyVarObject_HEAD_INIT(&PyType_Type, 0) - "generator", /* tp_name */ - sizeof(PyGenObject), /* tp_basicsize */ - 0, /* tp_itemsize */ - /* methods */ - (destructor)gen_dealloc, /* tp_dealloc */ - 0, /* tp_print */ - 0, /* tp_getattr */ - 0, /* tp_setattr */ - 0, /* tp_reserved */ - (reprfunc)gen_repr, /* 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)gen_traverse, /* tp_traverse */ - 0, /* tp_clear */ - 0, /* tp_richcompare */ - offsetof(PyGenObject, gi_weakreflist), /* tp_weaklistoffset */ - PyObject_SelfIter, /* tp_iter */ - (iternextfunc)gen_iternext, /* tp_iternext */ - gen_methods, /* tp_methods */ - gen_memberlist, /* tp_members */ - gen_getsetlist, /* tp_getset */ - 0, /* tp_base */ - 0, /* tp_dict */ - - 0, /* tp_descr_get */ - 0, /* tp_descr_set */ - 0, /* tp_dictoffset */ - 0, /* tp_init */ - 0, /* tp_alloc */ - 0, /* tp_new */ - 0, /* tp_free */ - 0, /* tp_is_gc */ - 0, /* tp_bases */ - 0, /* tp_mro */ - 0, /* tp_cache */ - 0, /* tp_subclasses */ - 0, /* tp_weaklist */ - gen_del, /* tp_del */ + PyVarObject_HEAD_INIT(&PyType_Type, 0) + "generator", /* tp_name */ + sizeof(PyGenObject), /* tp_basicsize */ + 0, /* tp_itemsize */ + /* methods */ + (destructor)gen_dealloc, /* tp_dealloc */ + 0, /* tp_print */ + 0, /* tp_getattr */ + 0, /* tp_setattr */ + 0, /* tp_reserved */ + (reprfunc)gen_repr, /* 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)gen_traverse, /* tp_traverse */ + 0, /* tp_clear */ + 0, /* tp_richcompare */ + offsetof(PyGenObject, gi_weakreflist), /* tp_weaklistoffset */ + PyObject_SelfIter, /* tp_iter */ + (iternextfunc)gen_iternext, /* tp_iternext */ + gen_methods, /* tp_methods */ + gen_memberlist, /* tp_members */ + gen_getsetlist, /* tp_getset */ + 0, /* tp_base */ + 0, /* tp_dict */ + + 0, /* tp_descr_get */ + 0, /* tp_descr_set */ + 0, /* tp_dictoffset */ + 0, /* tp_init */ + 0, /* tp_alloc */ + 0, /* tp_new */ + 0, /* tp_free */ + 0, /* tp_is_gc */ + 0, /* tp_bases */ + 0, /* tp_mro */ + 0, /* tp_cache */ + 0, /* tp_subclasses */ + 0, /* tp_weaklist */ + gen_del, /* tp_del */ }; PyObject * PyGen_New(PyFrameObject *f) { - PyGenObject *gen = PyObject_GC_New(PyGenObject, &PyGen_Type); - if (gen == NULL) { - Py_DECREF(f); - return NULL; - } - gen->gi_frame = f; - Py_INCREF(f->f_code); - gen->gi_code = (PyObject *)(f->f_code); - gen->gi_running = 0; - gen->gi_weakreflist = NULL; - _PyObject_GC_TRACK(gen); - return (PyObject *)gen; + PyGenObject *gen = PyObject_GC_New(PyGenObject, &PyGen_Type); + if (gen == NULL) { + Py_DECREF(f); + return NULL; + } + gen->gi_frame = f; + Py_INCREF(f->f_code); + gen->gi_code = (PyObject *)(f->f_code); + gen->gi_running = 0; + gen->gi_weakreflist = NULL; + _PyObject_GC_TRACK(gen); + return (PyObject *)gen; } int PyGen_NeedsFinalizing(PyGenObject *gen) { - int i; - PyFrameObject *f = gen->gi_frame; + int i; + PyFrameObject *f = gen->gi_frame; - if (f == NULL || f->f_stacktop == NULL || f->f_iblock <= 0) - return 0; /* no frame or empty blockstack == no finalization */ + if (f == NULL || f->f_stacktop == NULL || f->f_iblock <= 0) + return 0; /* no frame or empty blockstack == no finalization */ - /* Any block type besides a loop requires cleanup. */ - i = f->f_iblock; - while (--i >= 0) { - if (f->f_blockstack[i].b_type != SETUP_LOOP) - return 1; - } + /* Any block type besides a loop requires cleanup. */ + i = f->f_iblock; + while (--i >= 0) { + if (f->f_blockstack[i].b_type != SETUP_LOOP) + return 1; + } - /* No blocks except loops, it's safe to skip finalization. */ - return 0; + /* No blocks except loops, it's safe to skip finalization. */ + return 0; } Modified: python/branches/py3k-jit/Objects/iterobject.c ============================================================================== --- python/branches/py3k-jit/Objects/iterobject.c (original) +++ python/branches/py3k-jit/Objects/iterobject.c Mon May 10 23:55:43 2010 @@ -3,230 +3,230 @@ #include "Python.h" typedef struct { - PyObject_HEAD - long it_index; - PyObject *it_seq; /* Set to NULL when iterator is exhausted */ + PyObject_HEAD + long it_index; + PyObject *it_seq; /* Set to NULL when iterator is exhausted */ } seqiterobject; PyObject * PySeqIter_New(PyObject *seq) { - seqiterobject *it; + seqiterobject *it; - if (!PySequence_Check(seq)) { - PyErr_BadInternalCall(); - return NULL; - } - it = PyObject_GC_New(seqiterobject, &PySeqIter_Type); - if (it == NULL) - return NULL; - it->it_index = 0; - Py_INCREF(seq); - it->it_seq = seq; - _PyObject_GC_TRACK(it); - return (PyObject *)it; + if (!PySequence_Check(seq)) { + PyErr_BadInternalCall(); + return NULL; + } + it = PyObject_GC_New(seqiterobject, &PySeqIter_Type); + if (it == NULL) + return NULL; + it->it_index = 0; + Py_INCREF(seq); + it->it_seq = seq; + _PyObject_GC_TRACK(it); + return (PyObject *)it; } static void iter_dealloc(seqiterobject *it) { - _PyObject_GC_UNTRACK(it); - Py_XDECREF(it->it_seq); - PyObject_GC_Del(it); + _PyObject_GC_UNTRACK(it); + Py_XDECREF(it->it_seq); + PyObject_GC_Del(it); } static int iter_traverse(seqiterobject *it, visitproc visit, void *arg) { - Py_VISIT(it->it_seq); - return 0; + Py_VISIT(it->it_seq); + return 0; } static PyObject * iter_iternext(PyObject *iterator) { - seqiterobject *it; - PyObject *seq; - PyObject *result; - - assert(PySeqIter_Check(iterator)); - it = (seqiterobject *)iterator; - seq = it->it_seq; - if (seq == NULL) - return NULL; - - result = PySequence_GetItem(seq, it->it_index); - if (result != NULL) { - it->it_index++; - return result; - } - if (PyErr_ExceptionMatches(PyExc_IndexError) || - PyErr_ExceptionMatches(PyExc_StopIteration)) - { - PyErr_Clear(); - Py_DECREF(seq); - it->it_seq = NULL; - } - return NULL; + seqiterobject *it; + PyObject *seq; + PyObject *result; + + assert(PySeqIter_Check(iterator)); + it = (seqiterobject *)iterator; + seq = it->it_seq; + if (seq == NULL) + return NULL; + + result = PySequence_GetItem(seq, it->it_index); + if (result != NULL) { + it->it_index++; + return result; + } + if (PyErr_ExceptionMatches(PyExc_IndexError) || + PyErr_ExceptionMatches(PyExc_StopIteration)) + { + PyErr_Clear(); + Py_DECREF(seq); + it->it_seq = NULL; + } + return NULL; } static PyObject * iter_len(seqiterobject *it) { - Py_ssize_t seqsize, len; + Py_ssize_t seqsize, len; - if (it->it_seq) { - seqsize = PySequence_Size(it->it_seq); - if (seqsize == -1) - return NULL; - len = seqsize - it->it_index; - if (len >= 0) - return PyLong_FromSsize_t(len); - } - return PyLong_FromLong(0); + if (it->it_seq) { + seqsize = PySequence_Size(it->it_seq); + if (seqsize == -1) + return NULL; + len = seqsize - it->it_index; + if (len >= 0) + return PyLong_FromSsize_t(len); + } + return PyLong_FromLong(0); } PyDoc_STRVAR(length_hint_doc, "Private method returning an estimate of len(list(it))."); static PyMethodDef seqiter_methods[] = { - {"__length_hint__", (PyCFunction)iter_len, METH_NOARGS, length_hint_doc}, - {NULL, NULL} /* sentinel */ + {"__length_hint__", (PyCFunction)iter_len, METH_NOARGS, length_hint_doc}, + {NULL, NULL} /* sentinel */ }; PyTypeObject PySeqIter_Type = { - PyVarObject_HEAD_INIT(&PyType_Type, 0) - "iterator", /* tp_name */ - sizeof(seqiterobject), /* tp_basicsize */ - 0, /* tp_itemsize */ - /* methods */ - (destructor)iter_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)iter_traverse, /* tp_traverse */ - 0, /* tp_clear */ - 0, /* tp_richcompare */ - 0, /* tp_weaklistoffset */ - PyObject_SelfIter, /* tp_iter */ - iter_iternext, /* tp_iternext */ - seqiter_methods, /* tp_methods */ - 0, /* tp_members */ + PyVarObject_HEAD_INIT(&PyType_Type, 0) + "iterator", /* tp_name */ + sizeof(seqiterobject), /* tp_basicsize */ + 0, /* tp_itemsize */ + /* methods */ + (destructor)iter_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)iter_traverse, /* tp_traverse */ + 0, /* tp_clear */ + 0, /* tp_richcompare */ + 0, /* tp_weaklistoffset */ + PyObject_SelfIter, /* tp_iter */ + iter_iternext, /* tp_iternext */ + seqiter_methods, /* tp_methods */ + 0, /* tp_members */ }; /* -------------------------------------- */ typedef struct { - PyObject_HEAD - PyObject *it_callable; /* Set to NULL when iterator is exhausted */ - PyObject *it_sentinel; /* Set to NULL when iterator is exhausted */ + PyObject_HEAD + PyObject *it_callable; /* Set to NULL when iterator is exhausted */ + PyObject *it_sentinel; /* Set to NULL when iterator is exhausted */ } calliterobject; PyObject * PyCallIter_New(PyObject *callable, PyObject *sentinel) { - calliterobject *it; - it = PyObject_GC_New(calliterobject, &PyCallIter_Type); - if (it == NULL) - return NULL; - Py_INCREF(callable); - it->it_callable = callable; - Py_INCREF(sentinel); - it->it_sentinel = sentinel; - _PyObject_GC_TRACK(it); - return (PyObject *)it; + calliterobject *it; + it = PyObject_GC_New(calliterobject, &PyCallIter_Type); + if (it == NULL) + return NULL; + Py_INCREF(callable); + it->it_callable = callable; + Py_INCREF(sentinel); + it->it_sentinel = sentinel; + _PyObject_GC_TRACK(it); + return (PyObject *)it; } static void calliter_dealloc(calliterobject *it) { - _PyObject_GC_UNTRACK(it); - Py_XDECREF(it->it_callable); - Py_XDECREF(it->it_sentinel); - PyObject_GC_Del(it); + _PyObject_GC_UNTRACK(it); + Py_XDECREF(it->it_callable); + Py_XDECREF(it->it_sentinel); + PyObject_GC_Del(it); } static int calliter_traverse(calliterobject *it, visitproc visit, void *arg) { - Py_VISIT(it->it_callable); - Py_VISIT(it->it_sentinel); - return 0; + Py_VISIT(it->it_callable); + Py_VISIT(it->it_sentinel); + return 0; } static PyObject * calliter_iternext(calliterobject *it) { - if (it->it_callable != NULL) { - PyObject *args = PyTuple_New(0); - PyObject *result; - if (args == NULL) - return NULL; - result = PyObject_Call(it->it_callable, args, NULL); - Py_DECREF(args); - if (result != NULL) { - int ok; - ok = PyObject_RichCompareBool(result, - it->it_sentinel, - Py_EQ); - if (ok == 0) - return result; /* Common case, fast path */ - Py_DECREF(result); - if (ok > 0) { - Py_CLEAR(it->it_callable); - Py_CLEAR(it->it_sentinel); - } - } - else if (PyErr_ExceptionMatches(PyExc_StopIteration)) { - PyErr_Clear(); - Py_CLEAR(it->it_callable); - Py_CLEAR(it->it_sentinel); - } - } - return NULL; + if (it->it_callable != NULL) { + PyObject *args = PyTuple_New(0); + PyObject *result; + if (args == NULL) + return NULL; + result = PyObject_Call(it->it_callable, args, NULL); + Py_DECREF(args); + if (result != NULL) { + int ok; + ok = PyObject_RichCompareBool(result, + it->it_sentinel, + Py_EQ); + if (ok == 0) + return result; /* Common case, fast path */ + Py_DECREF(result); + if (ok > 0) { + Py_CLEAR(it->it_callable); + Py_CLEAR(it->it_sentinel); + } + } + else if (PyErr_ExceptionMatches(PyExc_StopIteration)) { + PyErr_Clear(); + Py_CLEAR(it->it_callable); + Py_CLEAR(it->it_sentinel); + } + } + return NULL; } PyTypeObject PyCallIter_Type = { - PyVarObject_HEAD_INIT(&PyType_Type, 0) - "callable_iterator", /* tp_name */ - sizeof(calliterobject), /* tp_basicsize */ - 0, /* tp_itemsize */ - /* methods */ - (destructor)calliter_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)calliter_traverse, /* tp_traverse */ - 0, /* tp_clear */ - 0, /* tp_richcompare */ - 0, /* tp_weaklistoffset */ - PyObject_SelfIter, /* tp_iter */ - (iternextfunc)calliter_iternext, /* tp_iternext */ - 0, /* tp_methods */ + PyVarObject_HEAD_INIT(&PyType_Type, 0) + "callable_iterator", /* tp_name */ + sizeof(calliterobject), /* tp_basicsize */ + 0, /* tp_itemsize */ + /* methods */ + (destructor)calliter_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)calliter_traverse, /* tp_traverse */ + 0, /* tp_clear */ + 0, /* tp_richcompare */ + 0, /* tp_weaklistoffset */ + PyObject_SelfIter, /* tp_iter */ + (iternextfunc)calliter_iternext, /* tp_iternext */ + 0, /* tp_methods */ }; Modified: python/branches/py3k-jit/Objects/listobject.c ============================================================================== --- python/branches/py3k-jit/Objects/listobject.c (original) +++ python/branches/py3k-jit/Objects/listobject.c Mon May 10 23:55:43 2010 @@ -5,7 +5,7 @@ #ifdef STDC_HEADERS #include #else -#include /* For size_t */ +#include /* For size_t */ #endif /* Ensure ob_item has room for at least newsize elements, and set @@ -24,52 +24,52 @@ static int list_resize(PyListObject *self, Py_ssize_t newsize) { - PyObject **items; - size_t new_allocated; - Py_ssize_t allocated = self->allocated; - - /* Bypass realloc() when a previous overallocation is large enough - to accommodate the newsize. If the newsize falls lower than half - the allocated size, then proceed with the realloc() to shrink the list. - */ - if (allocated >= newsize && newsize >= (allocated >> 1)) { - assert(self->ob_item != NULL || newsize == 0); - Py_SIZE(self) = newsize; - return 0; - } - - /* This over-allocates proportional to the list size, making room - * for additional growth. The over-allocation is mild, but is - * enough to give linear-time amortized behavior over a long - * sequence of appends() in the presence of a poorly-performing - * system realloc(). - * The growth pattern is: 0, 4, 8, 16, 25, 35, 46, 58, 72, 88, ... - */ - new_allocated = (newsize >> 3) + (newsize < 9 ? 3 : 6); - - /* check for integer overflow */ - if (new_allocated > PY_SIZE_MAX - newsize) { - PyErr_NoMemory(); - return -1; - } else { - new_allocated += newsize; - } - - if (newsize == 0) - new_allocated = 0; - items = self->ob_item; - if (new_allocated <= ((~(size_t)0) / sizeof(PyObject *))) - PyMem_RESIZE(items, PyObject *, new_allocated); - else - items = NULL; - if (items == NULL) { - PyErr_NoMemory(); - return -1; - } - self->ob_item = items; - Py_SIZE(self) = newsize; - self->allocated = new_allocated; - return 0; + PyObject **items; + size_t new_allocated; + Py_ssize_t allocated = self->allocated; + + /* Bypass realloc() when a previous overallocation is large enough + to accommodate the newsize. If the newsize falls lower than half + the allocated size, then proceed with the realloc() to shrink the list. + */ + if (allocated >= newsize && newsize >= (allocated >> 1)) { + assert(self->ob_item != NULL || newsize == 0); + Py_SIZE(self) = newsize; + return 0; + } + + /* This over-allocates proportional to the list size, making room + * for additional growth. The over-allocation is mild, but is + * enough to give linear-time amortized behavior over a long + * sequence of appends() in the presence of a poorly-performing + * system realloc(). + * The growth pattern is: 0, 4, 8, 16, 25, 35, 46, 58, 72, 88, ... + */ + new_allocated = (newsize >> 3) + (newsize < 9 ? 3 : 6); + + /* check for integer overflow */ + if (new_allocated > PY_SIZE_MAX - newsize) { + PyErr_NoMemory(); + return -1; + } else { + new_allocated += newsize; + } + + if (newsize == 0) + new_allocated = 0; + items = self->ob_item; + if (new_allocated <= ((~(size_t)0) / sizeof(PyObject *))) + PyMem_RESIZE(items, PyObject *, new_allocated); + else + items = NULL; + if (items == NULL) { + PyErr_NoMemory(); + return -1; + } + self->ob_item = items; + Py_SIZE(self) = newsize; + self->allocated = new_allocated; + return 0; } /* Debug statistic to compare allocations with reuse through the free list */ @@ -81,12 +81,12 @@ static void show_alloc(void) { - fprintf(stderr, "List allocations: %" PY_FORMAT_SIZE_T "d\n", - count_alloc); - fprintf(stderr, "List reuse through freelist: %" PY_FORMAT_SIZE_T - "d\n", count_reuse); - fprintf(stderr, "%.2f%% reuse rate\n\n", - (100.0*count_reuse/(count_alloc+count_reuse))); + fprintf(stderr, "List allocations: %" PY_FORMAT_SIZE_T "d\n", + count_alloc); + fprintf(stderr, "List reuse through freelist: %" PY_FORMAT_SIZE_T + "d\n", count_reuse); + fprintf(stderr, "%.2f%% reuse rate\n\n", + (100.0*count_reuse/(count_alloc+count_reuse))); } #endif @@ -100,77 +100,77 @@ void PyList_Fini(void) { - PyListObject *op; + PyListObject *op; - while (numfree) { - op = free_list[--numfree]; - assert(PyList_CheckExact(op)); - PyObject_GC_Del(op); - } + while (numfree) { + op = free_list[--numfree]; + assert(PyList_CheckExact(op)); + PyObject_GC_Del(op); + } } PyObject * PyList_New(Py_ssize_t size) { - PyListObject *op; - size_t nbytes; + PyListObject *op; + size_t nbytes; #ifdef SHOW_ALLOC_COUNT - static int initialized = 0; - if (!initialized) { - Py_AtExit(show_alloc); - initialized = 1; - } + static int initialized = 0; + if (!initialized) { + Py_AtExit(show_alloc); + initialized = 1; + } #endif - if (size < 0) { - PyErr_BadInternalCall(); - return NULL; - } - /* Check for overflow without an actual overflow, - * which can cause compiler to optimise out */ - if ((size_t)size > PY_SIZE_MAX / sizeof(PyObject *)) - return PyErr_NoMemory(); - nbytes = size * sizeof(PyObject *); - if (numfree) { - numfree--; - op = free_list[numfree]; - _Py_NewReference((PyObject *)op); + if (size < 0) { + PyErr_BadInternalCall(); + return NULL; + } + /* Check for overflow without an actual overflow, + * which can cause compiler to optimise out */ + if ((size_t)size > PY_SIZE_MAX / sizeof(PyObject *)) + return PyErr_NoMemory(); + nbytes = size * sizeof(PyObject *); + if (numfree) { + numfree--; + op = free_list[numfree]; + _Py_NewReference((PyObject *)op); #ifdef SHOW_ALLOC_COUNT - count_reuse++; + count_reuse++; #endif - } else { - op = PyObject_GC_New(PyListObject, &PyList_Type); - if (op == NULL) - return NULL; + } else { + op = PyObject_GC_New(PyListObject, &PyList_Type); + if (op == NULL) + return NULL; #ifdef SHOW_ALLOC_COUNT - count_alloc++; + count_alloc++; #endif - } - if (size <= 0) - op->ob_item = NULL; - else { - op->ob_item = (PyObject **) PyMem_MALLOC(nbytes); - if (op->ob_item == NULL) { - Py_DECREF(op); - return PyErr_NoMemory(); - } - memset(op->ob_item, 0, nbytes); - } - Py_SIZE(op) = size; - op->allocated = size; - _PyObject_GC_TRACK(op); - return (PyObject *) op; + } + if (size <= 0) + op->ob_item = NULL; + else { + op->ob_item = (PyObject **) PyMem_MALLOC(nbytes); + if (op->ob_item == NULL) { + Py_DECREF(op); + return PyErr_NoMemory(); + } + memset(op->ob_item, 0, nbytes); + } + Py_SIZE(op) = size; + op->allocated = size; + _PyObject_GC_TRACK(op); + return (PyObject *) op; } Py_ssize_t PyList_Size(PyObject *op) { - if (!PyList_Check(op)) { - PyErr_BadInternalCall(); - return -1; - } - else - return Py_SIZE(op); + if (!PyList_Check(op)) { + PyErr_BadInternalCall(); + return -1; + } + else + return Py_SIZE(op); } static PyObject *indexerr = NULL; @@ -178,117 +178,117 @@ PyObject * PyList_GetItem(PyObject *op, Py_ssize_t i) { - if (!PyList_Check(op)) { - PyErr_BadInternalCall(); - return NULL; - } - if (i < 0 || i >= Py_SIZE(op)) { - if (indexerr == NULL) { - indexerr = PyUnicode_FromString( - "list index out of range"); - if (indexerr == NULL) - return NULL; - } - PyErr_SetObject(PyExc_IndexError, indexerr); - return NULL; - } - return ((PyListObject *)op) -> ob_item[i]; + if (!PyList_Check(op)) { + PyErr_BadInternalCall(); + return NULL; + } + if (i < 0 || i >= Py_SIZE(op)) { + if (indexerr == NULL) { + indexerr = PyUnicode_FromString( + "list index out of range"); + if (indexerr == NULL) + return NULL; + } + PyErr_SetObject(PyExc_IndexError, indexerr); + return NULL; + } + return ((PyListObject *)op) -> ob_item[i]; } int PyList_SetItem(register PyObject *op, register Py_ssize_t i, register PyObject *newitem) { - register PyObject *olditem; - register PyObject **p; - if (!PyList_Check(op)) { - Py_XDECREF(newitem); - PyErr_BadInternalCall(); - return -1; - } - if (i < 0 || i >= Py_SIZE(op)) { - Py_XDECREF(newitem); - PyErr_SetString(PyExc_IndexError, - "list assignment index out of range"); - return -1; - } - p = ((PyListObject *)op) -> ob_item + i; - olditem = *p; - *p = newitem; - Py_XDECREF(olditem); - return 0; + register PyObject *olditem; + register PyObject **p; + if (!PyList_Check(op)) { + Py_XDECREF(newitem); + PyErr_BadInternalCall(); + return -1; + } + if (i < 0 || i >= Py_SIZE(op)) { + Py_XDECREF(newitem); + PyErr_SetString(PyExc_IndexError, + "list assignment index out of range"); + return -1; + } + p = ((PyListObject *)op) -> ob_item + i; + olditem = *p; + *p = newitem; + Py_XDECREF(olditem); + return 0; } static int ins1(PyListObject *self, Py_ssize_t where, PyObject *v) { - Py_ssize_t i, n = Py_SIZE(self); - PyObject **items; - if (v == NULL) { - PyErr_BadInternalCall(); - return -1; - } - if (n == PY_SSIZE_T_MAX) { - PyErr_SetString(PyExc_OverflowError, - "cannot add more objects to list"); - return -1; - } - - if (list_resize(self, n+1) == -1) - return -1; - - if (where < 0) { - where += n; - if (where < 0) - where = 0; - } - if (where > n) - where = n; - items = self->ob_item; - for (i = n; --i >= where; ) - items[i+1] = items[i]; - Py_INCREF(v); - items[where] = v; - return 0; + Py_ssize_t i, n = Py_SIZE(self); + PyObject **items; + if (v == NULL) { + PyErr_BadInternalCall(); + return -1; + } + if (n == PY_SSIZE_T_MAX) { + PyErr_SetString(PyExc_OverflowError, + "cannot add more objects to list"); + return -1; + } + + if (list_resize(self, n+1) == -1) + return -1; + + if (where < 0) { + where += n; + if (where < 0) + where = 0; + } + if (where > n) + where = n; + items = self->ob_item; + for (i = n; --i >= where; ) + items[i+1] = items[i]; + Py_INCREF(v); + items[where] = v; + return 0; } int PyList_Insert(PyObject *op, Py_ssize_t where, PyObject *newitem) { - if (!PyList_Check(op)) { - PyErr_BadInternalCall(); - return -1; - } - return ins1((PyListObject *)op, where, newitem); + if (!PyList_Check(op)) { + PyErr_BadInternalCall(); + return -1; + } + return ins1((PyListObject *)op, where, newitem); } static int app1(PyListObject *self, PyObject *v) { - Py_ssize_t n = PyList_GET_SIZE(self); + Py_ssize_t n = PyList_GET_SIZE(self); - assert (v != NULL); - if (n == PY_SSIZE_T_MAX) { - PyErr_SetString(PyExc_OverflowError, - "cannot add more objects to list"); - return -1; - } - - if (list_resize(self, n+1) == -1) - return -1; - - Py_INCREF(v); - PyList_SET_ITEM(self, n, v); - return 0; + assert (v != NULL); + if (n == PY_SSIZE_T_MAX) { + PyErr_SetString(PyExc_OverflowError, + "cannot add more objects to list"); + return -1; + } + + if (list_resize(self, n+1) == -1) + return -1; + + Py_INCREF(v); + PyList_SET_ITEM(self, n, v); + return 0; } int PyList_Append(PyObject *op, PyObject *newitem) { - if (PyList_Check(op) && (newitem != NULL)) - return app1((PyListObject *)op, newitem); - PyErr_BadInternalCall(); - return -1; + if (PyList_Check(op) && (newitem != NULL)) + return app1((PyListObject *)op, newitem); + PyErr_BadInternalCall(); + return -1; } /* Methods */ @@ -296,271 +296,271 @@ static void list_dealloc(PyListObject *op) { - Py_ssize_t i; - PyObject_GC_UnTrack(op); - Py_TRASHCAN_SAFE_BEGIN(op) - if (op->ob_item != NULL) { - /* Do it backwards, for Christian Tismer. - There's a simple test case where somehow this reduces - thrashing when a *very* large list is created and - immediately deleted. */ - i = Py_SIZE(op); - while (--i >= 0) { - Py_XDECREF(op->ob_item[i]); - } - PyMem_FREE(op->ob_item); - } - if (numfree < PyList_MAXFREELIST && PyList_CheckExact(op)) - free_list[numfree++] = op; - else - Py_TYPE(op)->tp_free((PyObject *)op); - Py_TRASHCAN_SAFE_END(op) + Py_ssize_t i; + PyObject_GC_UnTrack(op); + Py_TRASHCAN_SAFE_BEGIN(op) + if (op->ob_item != NULL) { + /* Do it backwards, for Christian Tismer. + There's a simple test case where somehow this reduces + thrashing when a *very* large list is created and + immediately deleted. */ + i = Py_SIZE(op); + while (--i >= 0) { + Py_XDECREF(op->ob_item[i]); + } + PyMem_FREE(op->ob_item); + } + if (numfree < PyList_MAXFREELIST && PyList_CheckExact(op)) + free_list[numfree++] = op; + else + Py_TYPE(op)->tp_free((PyObject *)op); + Py_TRASHCAN_SAFE_END(op) } static PyObject * list_repr(PyListObject *v) { - Py_ssize_t i; - PyObject *s, *temp; - PyObject *pieces = NULL, *result = NULL; - - i = Py_ReprEnter((PyObject*)v); - if (i != 0) { - return i > 0 ? PyUnicode_FromString("[...]") : NULL; - } - - if (Py_SIZE(v) == 0) { - result = PyUnicode_FromString("[]"); - goto Done; - } - - pieces = PyList_New(0); - if (pieces == NULL) - goto Done; - - /* Do repr() on each element. Note that this may mutate the list, - so must refetch the list size on each iteration. */ - for (i = 0; i < Py_SIZE(v); ++i) { - int status; - if (Py_EnterRecursiveCall(" while getting the repr of a list")) - goto Done; - s = PyObject_Repr(v->ob_item[i]); - Py_LeaveRecursiveCall(); - if (s == NULL) - goto Done; - status = PyList_Append(pieces, s); - Py_DECREF(s); /* append created a new ref */ - if (status < 0) - goto Done; - } - - /* Add "[]" decorations to the first and last items. */ - assert(PyList_GET_SIZE(pieces) > 0); - s = PyUnicode_FromString("["); - if (s == NULL) - goto Done; - temp = PyList_GET_ITEM(pieces, 0); - PyUnicode_AppendAndDel(&s, temp); - PyList_SET_ITEM(pieces, 0, s); - if (s == NULL) - goto Done; - - s = PyUnicode_FromString("]"); - if (s == NULL) - goto Done; - temp = PyList_GET_ITEM(pieces, PyList_GET_SIZE(pieces) - 1); - PyUnicode_AppendAndDel(&temp, s); - PyList_SET_ITEM(pieces, PyList_GET_SIZE(pieces) - 1, temp); - if (temp == NULL) - goto Done; - - /* Paste them all together with ", " between. */ - s = PyUnicode_FromString(", "); - if (s == NULL) - goto Done; - result = PyUnicode_Join(s, pieces); - Py_DECREF(s); + Py_ssize_t i; + PyObject *s, *temp; + PyObject *pieces = NULL, *result = NULL; + + i = Py_ReprEnter((PyObject*)v); + if (i != 0) { + return i > 0 ? PyUnicode_FromString("[...]") : NULL; + } + + if (Py_SIZE(v) == 0) { + result = PyUnicode_FromString("[]"); + goto Done; + } + + pieces = PyList_New(0); + if (pieces == NULL) + goto Done; + + /* Do repr() on each element. Note that this may mutate the list, + so must refetch the list size on each iteration. */ + for (i = 0; i < Py_SIZE(v); ++i) { + int status; + if (Py_EnterRecursiveCall(" while getting the repr of a list")) + goto Done; + s = PyObject_Repr(v->ob_item[i]); + Py_LeaveRecursiveCall(); + if (s == NULL) + goto Done; + status = PyList_Append(pieces, s); + Py_DECREF(s); /* append created a new ref */ + if (status < 0) + goto Done; + } + + /* Add "[]" decorations to the first and last items. */ + assert(PyList_GET_SIZE(pieces) > 0); + s = PyUnicode_FromString("["); + if (s == NULL) + goto Done; + temp = PyList_GET_ITEM(pieces, 0); + PyUnicode_AppendAndDel(&s, temp); + PyList_SET_ITEM(pieces, 0, s); + if (s == NULL) + goto Done; + + s = PyUnicode_FromString("]"); + if (s == NULL) + goto Done; + temp = PyList_GET_ITEM(pieces, PyList_GET_SIZE(pieces) - 1); + PyUnicode_AppendAndDel(&temp, s); + PyList_SET_ITEM(pieces, PyList_GET_SIZE(pieces) - 1, temp); + if (temp == NULL) + goto Done; + + /* Paste them all together with ", " between. */ + s = PyUnicode_FromString(", "); + if (s == NULL) + goto Done; + result = PyUnicode_Join(s, pieces); + Py_DECREF(s); Done: - Py_XDECREF(pieces); - Py_ReprLeave((PyObject *)v); - return result; + Py_XDECREF(pieces); + Py_ReprLeave((PyObject *)v); + return result; } static Py_ssize_t list_length(PyListObject *a) { - return Py_SIZE(a); + return Py_SIZE(a); } static int list_contains(PyListObject *a, PyObject *el) { - Py_ssize_t i; - int cmp; + Py_ssize_t i; + int cmp; - for (i = 0, cmp = 0 ; cmp == 0 && i < Py_SIZE(a); ++i) - cmp = PyObject_RichCompareBool(el, PyList_GET_ITEM(a, i), - Py_EQ); - return cmp; + for (i = 0, cmp = 0 ; cmp == 0 && i < Py_SIZE(a); ++i) + cmp = PyObject_RichCompareBool(el, PyList_GET_ITEM(a, i), + Py_EQ); + return cmp; } static PyObject * list_item(PyListObject *a, Py_ssize_t i) { - if (i < 0 || i >= Py_SIZE(a)) { - if (indexerr == NULL) { - indexerr = PyUnicode_FromString( - "list index out of range"); - if (indexerr == NULL) - return NULL; - } - PyErr_SetObject(PyExc_IndexError, indexerr); - return NULL; - } - Py_INCREF(a->ob_item[i]); - return a->ob_item[i]; + if (i < 0 || i >= Py_SIZE(a)) { + if (indexerr == NULL) { + indexerr = PyUnicode_FromString( + "list index out of range"); + if (indexerr == NULL) + return NULL; + } + PyErr_SetObject(PyExc_IndexError, indexerr); + return NULL; + } + Py_INCREF(a->ob_item[i]); + return a->ob_item[i]; } static PyObject * list_slice(PyListObject *a, Py_ssize_t ilow, Py_ssize_t ihigh) { - PyListObject *np; - PyObject **src, **dest; - Py_ssize_t i, len; - if (ilow < 0) - ilow = 0; - else if (ilow > Py_SIZE(a)) - ilow = Py_SIZE(a); - if (ihigh < ilow) - ihigh = ilow; - else if (ihigh > Py_SIZE(a)) - ihigh = Py_SIZE(a); - len = ihigh - ilow; - np = (PyListObject *) PyList_New(len); - if (np == NULL) - return NULL; - - src = a->ob_item + ilow; - dest = np->ob_item; - for (i = 0; i < len; i++) { - PyObject *v = src[i]; - Py_INCREF(v); - dest[i] = v; - } - return (PyObject *)np; + PyListObject *np; + PyObject **src, **dest; + Py_ssize_t i, len; + if (ilow < 0) + ilow = 0; + else if (ilow > Py_SIZE(a)) + ilow = Py_SIZE(a); + if (ihigh < ilow) + ihigh = ilow; + else if (ihigh > Py_SIZE(a)) + ihigh = Py_SIZE(a); + len = ihigh - ilow; + np = (PyListObject *) PyList_New(len); + if (np == NULL) + return NULL; + + src = a->ob_item + ilow; + dest = np->ob_item; + for (i = 0; i < len; i++) { + PyObject *v = src[i]; + Py_INCREF(v); + dest[i] = v; + } + return (PyObject *)np; } PyObject * PyList_GetSlice(PyObject *a, Py_ssize_t ilow, Py_ssize_t ihigh) { - if (!PyList_Check(a)) { - PyErr_BadInternalCall(); - return NULL; - } - return list_slice((PyListObject *)a, ilow, ihigh); + if (!PyList_Check(a)) { + PyErr_BadInternalCall(); + return NULL; + } + return list_slice((PyListObject *)a, ilow, ihigh); } static PyObject * list_concat(PyListObject *a, PyObject *bb) { - Py_ssize_t size; - Py_ssize_t i; - PyObject **src, **dest; - PyListObject *np; - if (!PyList_Check(bb)) { - PyErr_Format(PyExc_TypeError, - "can only concatenate list (not \"%.200s\") to list", - bb->ob_type->tp_name); - return NULL; - } + Py_ssize_t size; + Py_ssize_t i; + PyObject **src, **dest; + PyListObject *np; + if (!PyList_Check(bb)) { + PyErr_Format(PyExc_TypeError, + "can only concatenate list (not \"%.200s\") to list", + bb->ob_type->tp_name); + return NULL; + } #define b ((PyListObject *)bb) - size = Py_SIZE(a) + Py_SIZE(b); - if (size < 0) - return PyErr_NoMemory(); - np = (PyListObject *) PyList_New(size); - if (np == NULL) { - return NULL; - } - src = a->ob_item; - dest = np->ob_item; - for (i = 0; i < Py_SIZE(a); i++) { - PyObject *v = src[i]; - Py_INCREF(v); - dest[i] = v; - } - src = b->ob_item; - dest = np->ob_item + Py_SIZE(a); - for (i = 0; i < Py_SIZE(b); i++) { - PyObject *v = src[i]; - Py_INCREF(v); - dest[i] = v; - } - return (PyObject *)np; + size = Py_SIZE(a) + Py_SIZE(b); + if (size < 0) + return PyErr_NoMemory(); + np = (PyListObject *) PyList_New(size); + if (np == NULL) { + return NULL; + } + src = a->ob_item; + dest = np->ob_item; + for (i = 0; i < Py_SIZE(a); i++) { + PyObject *v = src[i]; + Py_INCREF(v); + dest[i] = v; + } + src = b->ob_item; + dest = np->ob_item + Py_SIZE(a); + for (i = 0; i < Py_SIZE(b); i++) { + PyObject *v = src[i]; + Py_INCREF(v); + dest[i] = v; + } + return (PyObject *)np; #undef b } static PyObject * list_repeat(PyListObject *a, Py_ssize_t n) { - Py_ssize_t i, j; - Py_ssize_t size; - PyListObject *np; - PyObject **p, **items; - PyObject *elem; - if (n < 0) - n = 0; - size = Py_SIZE(a) * n; - if (n && size/n != Py_SIZE(a)) - return PyErr_NoMemory(); - if (size == 0) - return PyList_New(0); - np = (PyListObject *) PyList_New(size); - if (np == NULL) - return NULL; - - items = np->ob_item; - if (Py_SIZE(a) == 1) { - elem = a->ob_item[0]; - for (i = 0; i < n; i++) { - items[i] = elem; - Py_INCREF(elem); - } - return (PyObject *) np; - } - p = np->ob_item; - items = a->ob_item; - for (i = 0; i < n; i++) { - for (j = 0; j < Py_SIZE(a); j++) { - *p = items[j]; - Py_INCREF(*p); - p++; - } - } - return (PyObject *) np; + Py_ssize_t i, j; + Py_ssize_t size; + PyListObject *np; + PyObject **p, **items; + PyObject *elem; + if (n < 0) + n = 0; + size = Py_SIZE(a) * n; + if (n && size/n != Py_SIZE(a)) + return PyErr_NoMemory(); + if (size == 0) + return PyList_New(0); + np = (PyListObject *) PyList_New(size); + if (np == NULL) + return NULL; + + items = np->ob_item; + if (Py_SIZE(a) == 1) { + elem = a->ob_item[0]; + for (i = 0; i < n; i++) { + items[i] = elem; + Py_INCREF(elem); + } + return (PyObject *) np; + } + p = np->ob_item; + items = a->ob_item; + for (i = 0; i < n; i++) { + for (j = 0; j < Py_SIZE(a); j++) { + *p = items[j]; + Py_INCREF(*p); + p++; + } + } + return (PyObject *) np; } static int list_clear(PyListObject *a) { - Py_ssize_t i; - PyObject **item = a->ob_item; - if (item != NULL) { - /* Because XDECREF can recursively invoke operations on - this list, we make it empty first. */ - i = Py_SIZE(a); - Py_SIZE(a) = 0; - a->ob_item = NULL; - a->allocated = 0; - while (--i >= 0) { - Py_XDECREF(item[i]); - } - PyMem_FREE(item); - } - /* Never fails; the return value can be ignored. - Note that there is no guarantee that the list is actually empty - at this point, because XDECREF may have populated it again! */ - return 0; + Py_ssize_t i; + PyObject **item = a->ob_item; + if (item != NULL) { + /* Because XDECREF can recursively invoke operations on + this list, we make it empty first. */ + i = Py_SIZE(a); + Py_SIZE(a) = 0; + a->ob_item = NULL; + a->allocated = 0; + while (--i >= 0) { + Py_XDECREF(item[i]); + } + PyMem_FREE(item); + } + /* Never fails; the return value can be ignored. + Note that there is no guarantee that the list is actually empty + at this point, because XDECREF may have populated it again! */ + return 0; } /* a[ilow:ihigh] = v if v != NULL. @@ -572,368 +572,368 @@ static int list_ass_slice(PyListObject *a, Py_ssize_t ilow, Py_ssize_t ihigh, PyObject *v) { - /* Because [X]DECREF can recursively invoke list operations on - this list, we must postpone all [X]DECREF activity until - after the list is back in its canonical shape. Therefore - we must allocate an additional array, 'recycle', into which - we temporarily copy the items that are deleted from the - list. :-( */ - PyObject *recycle_on_stack[8]; - PyObject **recycle = recycle_on_stack; /* will allocate more if needed */ - PyObject **item; - PyObject **vitem = NULL; - PyObject *v_as_SF = NULL; /* PySequence_Fast(v) */ - Py_ssize_t n; /* # of elements in replacement list */ - Py_ssize_t norig; /* # of elements in list getting replaced */ - Py_ssize_t d; /* Change in size */ - Py_ssize_t k; - size_t s; - int result = -1; /* guilty until proved innocent */ + /* Because [X]DECREF can recursively invoke list operations on + this list, we must postpone all [X]DECREF activity until + after the list is back in its canonical shape. Therefore + we must allocate an additional array, 'recycle', into which + we temporarily copy the items that are deleted from the + list. :-( */ + PyObject *recycle_on_stack[8]; + PyObject **recycle = recycle_on_stack; /* will allocate more if needed */ + PyObject **item; + PyObject **vitem = NULL; + PyObject *v_as_SF = NULL; /* PySequence_Fast(v) */ + Py_ssize_t n; /* # of elements in replacement list */ + Py_ssize_t norig; /* # of elements in list getting replaced */ + Py_ssize_t d; /* Change in size */ + Py_ssize_t k; + size_t s; + int result = -1; /* guilty until proved innocent */ #define b ((PyListObject *)v) - if (v == NULL) - n = 0; - else { - if (a == b) { - /* Special case "a[i:j] = a" -- copy b first */ - v = list_slice(b, 0, Py_SIZE(b)); - if (v == NULL) - return result; - result = list_ass_slice(a, ilow, ihigh, v); - Py_DECREF(v); - return result; - } - v_as_SF = PySequence_Fast(v, "can only assign an iterable"); - if(v_as_SF == NULL) - goto Error; - n = PySequence_Fast_GET_SIZE(v_as_SF); - vitem = PySequence_Fast_ITEMS(v_as_SF); - } - if (ilow < 0) - ilow = 0; - else if (ilow > Py_SIZE(a)) - ilow = Py_SIZE(a); - - if (ihigh < ilow) - ihigh = ilow; - else if (ihigh > Py_SIZE(a)) - ihigh = Py_SIZE(a); - - norig = ihigh - ilow; - assert(norig >= 0); - d = n - norig; - if (Py_SIZE(a) + d == 0) { - Py_XDECREF(v_as_SF); - return list_clear(a); - } - item = a->ob_item; - /* recycle the items that we are about to remove */ - s = norig * sizeof(PyObject *); - if (s > sizeof(recycle_on_stack)) { - recycle = (PyObject **)PyMem_MALLOC(s); - if (recycle == NULL) { - PyErr_NoMemory(); - goto Error; - } - } - memcpy(recycle, &item[ilow], s); - - if (d < 0) { /* Delete -d items */ - memmove(&item[ihigh+d], &item[ihigh], - (Py_SIZE(a) - ihigh)*sizeof(PyObject *)); - list_resize(a, Py_SIZE(a) + d); - item = a->ob_item; - } - else if (d > 0) { /* Insert d items */ - k = Py_SIZE(a); - if (list_resize(a, k+d) < 0) - goto Error; - item = a->ob_item; - memmove(&item[ihigh+d], &item[ihigh], - (k - ihigh)*sizeof(PyObject *)); - } - for (k = 0; k < n; k++, ilow++) { - PyObject *w = vitem[k]; - Py_XINCREF(w); - item[ilow] = w; - } - for (k = norig - 1; k >= 0; --k) - Py_XDECREF(recycle[k]); - result = 0; + if (v == NULL) + n = 0; + else { + if (a == b) { + /* Special case "a[i:j] = a" -- copy b first */ + v = list_slice(b, 0, Py_SIZE(b)); + if (v == NULL) + return result; + result = list_ass_slice(a, ilow, ihigh, v); + Py_DECREF(v); + return result; + } + v_as_SF = PySequence_Fast(v, "can only assign an iterable"); + if(v_as_SF == NULL) + goto Error; + n = PySequence_Fast_GET_SIZE(v_as_SF); + vitem = PySequence_Fast_ITEMS(v_as_SF); + } + if (ilow < 0) + ilow = 0; + else if (ilow > Py_SIZE(a)) + ilow = Py_SIZE(a); + + if (ihigh < ilow) + ihigh = ilow; + else if (ihigh > Py_SIZE(a)) + ihigh = Py_SIZE(a); + + norig = ihigh - ilow; + assert(norig >= 0); + d = n - norig; + if (Py_SIZE(a) + d == 0) { + Py_XDECREF(v_as_SF); + return list_clear(a); + } + item = a->ob_item; + /* recycle the items that we are about to remove */ + s = norig * sizeof(PyObject *); + if (s > sizeof(recycle_on_stack)) { + recycle = (PyObject **)PyMem_MALLOC(s); + if (recycle == NULL) { + PyErr_NoMemory(); + goto Error; + } + } + memcpy(recycle, &item[ilow], s); + + if (d < 0) { /* Delete -d items */ + memmove(&item[ihigh+d], &item[ihigh], + (Py_SIZE(a) - ihigh)*sizeof(PyObject *)); + list_resize(a, Py_SIZE(a) + d); + item = a->ob_item; + } + else if (d > 0) { /* Insert d items */ + k = Py_SIZE(a); + if (list_resize(a, k+d) < 0) + goto Error; + item = a->ob_item; + memmove(&item[ihigh+d], &item[ihigh], + (k - ihigh)*sizeof(PyObject *)); + } + for (k = 0; k < n; k++, ilow++) { + PyObject *w = vitem[k]; + Py_XINCREF(w); + item[ilow] = w; + } + for (k = norig - 1; k >= 0; --k) + Py_XDECREF(recycle[k]); + result = 0; Error: - if (recycle != recycle_on_stack) - PyMem_FREE(recycle); - Py_XDECREF(v_as_SF); - return result; + if (recycle != recycle_on_stack) + PyMem_FREE(recycle); + Py_XDECREF(v_as_SF); + return result; #undef b } int PyList_SetSlice(PyObject *a, Py_ssize_t ilow, Py_ssize_t ihigh, PyObject *v) { - if (!PyList_Check(a)) { - PyErr_BadInternalCall(); - return -1; - } - return list_ass_slice((PyListObject *)a, ilow, ihigh, v); + if (!PyList_Check(a)) { + PyErr_BadInternalCall(); + return -1; + } + return list_ass_slice((PyListObject *)a, ilow, ihigh, v); } static PyObject * list_inplace_repeat(PyListObject *self, Py_ssize_t n) { - PyObject **items; - Py_ssize_t size, i, j, p; + PyObject **items; + Py_ssize_t size, i, j, p; - size = PyList_GET_SIZE(self); - if (size == 0 || n == 1) { - Py_INCREF(self); - return (PyObject *)self; - } - - if (n < 1) { - (void)list_clear(self); - Py_INCREF(self); - return (PyObject *)self; - } - - if (size > PY_SSIZE_T_MAX / n) { - return PyErr_NoMemory(); - } - - if (list_resize(self, size*n) == -1) - return NULL; - - p = size; - items = self->ob_item; - for (i = 1; i < n; i++) { /* Start counting at 1, not 0 */ - for (j = 0; j < size; j++) { - PyObject *o = items[j]; - Py_INCREF(o); - items[p++] = o; - } - } - Py_INCREF(self); - return (PyObject *)self; + size = PyList_GET_SIZE(self); + if (size == 0 || n == 1) { + Py_INCREF(self); + return (PyObject *)self; + } + + if (n < 1) { + (void)list_clear(self); + Py_INCREF(self); + return (PyObject *)self; + } + + if (size > PY_SSIZE_T_MAX / n) { + return PyErr_NoMemory(); + } + + if (list_resize(self, size*n) == -1) + return NULL; + + p = size; + items = self->ob_item; + for (i = 1; i < n; i++) { /* Start counting at 1, not 0 */ + for (j = 0; j < size; j++) { + PyObject *o = items[j]; + Py_INCREF(o); + items[p++] = o; + } + } + Py_INCREF(self); + return (PyObject *)self; } static int list_ass_item(PyListObject *a, Py_ssize_t i, PyObject *v) { - PyObject *old_value; - if (i < 0 || i >= Py_SIZE(a)) { - PyErr_SetString(PyExc_IndexError, - "list assignment index out of range"); - return -1; - } - if (v == NULL) - return list_ass_slice(a, i, i+1, v); - Py_INCREF(v); - old_value = a->ob_item[i]; - a->ob_item[i] = v; - Py_DECREF(old_value); - return 0; + PyObject *old_value; + if (i < 0 || i >= Py_SIZE(a)) { + PyErr_SetString(PyExc_IndexError, + "list assignment index out of range"); + return -1; + } + if (v == NULL) + return list_ass_slice(a, i, i+1, v); + Py_INCREF(v); + old_value = a->ob_item[i]; + a->ob_item[i] = v; + Py_DECREF(old_value); + return 0; } static PyObject * listinsert(PyListObject *self, PyObject *args) { - Py_ssize_t i; - PyObject *v; - if (!PyArg_ParseTuple(args, "nO:insert", &i, &v)) - return NULL; - if (ins1(self, i, v) == 0) - Py_RETURN_NONE; - return NULL; + Py_ssize_t i; + PyObject *v; + if (!PyArg_ParseTuple(args, "nO:insert", &i, &v)) + return NULL; + if (ins1(self, i, v) == 0) + Py_RETURN_NONE; + return NULL; } static PyObject * listappend(PyListObject *self, PyObject *v) { - if (app1(self, v) == 0) - Py_RETURN_NONE; - return NULL; + if (app1(self, v) == 0) + Py_RETURN_NONE; + return NULL; } static PyObject * listextend(PyListObject *self, PyObject *b) { - PyObject *it; /* iter(v) */ - Py_ssize_t m; /* size of self */ - Py_ssize_t n; /* guess for size of b */ - Py_ssize_t mn; /* m + n */ - Py_ssize_t i; - PyObject *(*iternext)(PyObject *); - - /* Special cases: - 1) lists and tuples which can use PySequence_Fast ops - 2) extending self to self requires making a copy first - */ - if (PyList_CheckExact(b) || PyTuple_CheckExact(b) || (PyObject *)self == b) { - PyObject **src, **dest; - b = PySequence_Fast(b, "argument must be iterable"); - if (!b) - return NULL; - n = PySequence_Fast_GET_SIZE(b); - if (n == 0) { - /* short circuit when b is empty */ - Py_DECREF(b); - Py_RETURN_NONE; - } - m = Py_SIZE(self); - if (list_resize(self, m + n) == -1) { - Py_DECREF(b); - return NULL; - } - /* note that we may still have self == b here for the - * situation a.extend(a), but the following code works - * in that case too. Just make sure to resize self - * before calling PySequence_Fast_ITEMS. - */ - /* populate the end of self with b's items */ - src = PySequence_Fast_ITEMS(b); - dest = self->ob_item + m; - for (i = 0; i < n; i++) { - PyObject *o = src[i]; - Py_INCREF(o); - dest[i] = o; - } - Py_DECREF(b); - Py_RETURN_NONE; - } - - it = PyObject_GetIter(b); - if (it == NULL) - return NULL; - iternext = *it->ob_type->tp_iternext; - - /* Guess a result list size. */ - n = _PyObject_LengthHint(b, 8); - if (n == -1) { - Py_DECREF(it); - return NULL; - } - m = Py_SIZE(self); - mn = m + n; - if (mn >= m) { - /* Make room. */ - if (list_resize(self, mn) == -1) - goto error; - /* Make the list sane again. */ - Py_SIZE(self) = m; - } - /* Else m + n overflowed; on the chance that n lied, and there really - * is enough room, ignore it. If n was telling the truth, we'll - * eventually run out of memory during the loop. - */ - - /* Run iterator to exhaustion. */ - for (;;) { - PyObject *item = iternext(it); - if (item == NULL) { - if (PyErr_Occurred()) { - if (PyErr_ExceptionMatches(PyExc_StopIteration)) - PyErr_Clear(); - else - goto error; - } - break; - } - if (Py_SIZE(self) < self->allocated) { - /* steals ref */ - PyList_SET_ITEM(self, Py_SIZE(self), item); - ++Py_SIZE(self); - } - else { - int status = app1(self, item); - Py_DECREF(item); /* append creates a new ref */ - if (status < 0) - goto error; - } - } - - /* Cut back result list if initial guess was too large. */ - if (Py_SIZE(self) < self->allocated) - list_resize(self, Py_SIZE(self)); /* shrinking can't fail */ + PyObject *it; /* iter(v) */ + Py_ssize_t m; /* size of self */ + Py_ssize_t n; /* guess for size of b */ + Py_ssize_t mn; /* m + n */ + Py_ssize_t i; + PyObject *(*iternext)(PyObject *); + + /* Special cases: + 1) lists and tuples which can use PySequence_Fast ops + 2) extending self to self requires making a copy first + */ + if (PyList_CheckExact(b) || PyTuple_CheckExact(b) || (PyObject *)self == b) { + PyObject **src, **dest; + b = PySequence_Fast(b, "argument must be iterable"); + if (!b) + return NULL; + n = PySequence_Fast_GET_SIZE(b); + if (n == 0) { + /* short circuit when b is empty */ + Py_DECREF(b); + Py_RETURN_NONE; + } + m = Py_SIZE(self); + if (list_resize(self, m + n) == -1) { + Py_DECREF(b); + return NULL; + } + /* note that we may still have self == b here for the + * situation a.extend(a), but the following code works + * in that case too. Just make sure to resize self + * before calling PySequence_Fast_ITEMS. + */ + /* populate the end of self with b's items */ + src = PySequence_Fast_ITEMS(b); + dest = self->ob_item + m; + for (i = 0; i < n; i++) { + PyObject *o = src[i]; + Py_INCREF(o); + dest[i] = o; + } + Py_DECREF(b); + Py_RETURN_NONE; + } + + it = PyObject_GetIter(b); + if (it == NULL) + return NULL; + iternext = *it->ob_type->tp_iternext; + + /* Guess a result list size. */ + n = _PyObject_LengthHint(b, 8); + if (n == -1) { + Py_DECREF(it); + return NULL; + } + m = Py_SIZE(self); + mn = m + n; + if (mn >= m) { + /* Make room. */ + if (list_resize(self, mn) == -1) + goto error; + /* Make the list sane again. */ + Py_SIZE(self) = m; + } + /* Else m + n overflowed; on the chance that n lied, and there really + * is enough room, ignore it. If n was telling the truth, we'll + * eventually run out of memory during the loop. + */ + + /* Run iterator to exhaustion. */ + for (;;) { + PyObject *item = iternext(it); + if (item == NULL) { + if (PyErr_Occurred()) { + if (PyErr_ExceptionMatches(PyExc_StopIteration)) + PyErr_Clear(); + else + goto error; + } + break; + } + if (Py_SIZE(self) < self->allocated) { + /* steals ref */ + PyList_SET_ITEM(self, Py_SIZE(self), item); + ++Py_SIZE(self); + } + else { + int status = app1(self, item); + Py_DECREF(item); /* append creates a new ref */ + if (status < 0) + goto error; + } + } + + /* Cut back result list if initial guess was too large. */ + if (Py_SIZE(self) < self->allocated) + list_resize(self, Py_SIZE(self)); /* shrinking can't fail */ - Py_DECREF(it); - Py_RETURN_NONE; + Py_DECREF(it); + Py_RETURN_NONE; error: - Py_DECREF(it); - return NULL; + Py_DECREF(it); + return NULL; } PyObject * _PyList_Extend(PyListObject *self, PyObject *b) { - return listextend(self, b); + return listextend(self, b); } static PyObject * list_inplace_concat(PyListObject *self, PyObject *other) { - PyObject *result; + PyObject *result; - result = listextend(self, other); - if (result == NULL) - return result; - Py_DECREF(result); - Py_INCREF(self); - return (PyObject *)self; + result = listextend(self, other); + if (result == NULL) + return result; + Py_DECREF(result); + Py_INCREF(self); + return (PyObject *)self; } static PyObject * listpop(PyListObject *self, PyObject *args) { - Py_ssize_t i = -1; - PyObject *v; - int status; - - if (!PyArg_ParseTuple(args, "|n:pop", &i)) - return NULL; - - if (Py_SIZE(self) == 0) { - /* Special-case most common failure cause */ - PyErr_SetString(PyExc_IndexError, "pop from empty list"); - return NULL; - } - if (i < 0) - i += Py_SIZE(self); - if (i < 0 || i >= Py_SIZE(self)) { - PyErr_SetString(PyExc_IndexError, "pop index out of range"); - return NULL; - } - v = self->ob_item[i]; - if (i == Py_SIZE(self) - 1) { - status = list_resize(self, Py_SIZE(self) - 1); - assert(status >= 0); - return v; /* and v now owns the reference the list had */ - } - Py_INCREF(v); - status = list_ass_slice(self, i, i+1, (PyObject *)NULL); - assert(status >= 0); - /* Use status, so that in a release build compilers don't - * complain about the unused name. - */ - (void) status; + Py_ssize_t i = -1; + PyObject *v; + int status; + + if (!PyArg_ParseTuple(args, "|n:pop", &i)) + return NULL; + + if (Py_SIZE(self) == 0) { + /* Special-case most common failure cause */ + PyErr_SetString(PyExc_IndexError, "pop from empty list"); + return NULL; + } + if (i < 0) + i += Py_SIZE(self); + if (i < 0 || i >= Py_SIZE(self)) { + PyErr_SetString(PyExc_IndexError, "pop index out of range"); + return NULL; + } + v = self->ob_item[i]; + if (i == Py_SIZE(self) - 1) { + status = list_resize(self, Py_SIZE(self) - 1); + assert(status >= 0); + return v; /* and v now owns the reference the list had */ + } + Py_INCREF(v); + status = list_ass_slice(self, i, i+1, (PyObject *)NULL); + assert(status >= 0); + /* Use status, so that in a release build compilers don't + * complain about the unused name. + */ + (void) status; - return v; + return v; } /* Reverse a slice of a list in place, from lo up to (exclusive) hi. */ static void reverse_slice(PyObject **lo, PyObject **hi) { - assert(lo && hi); + assert(lo && hi); - --hi; - while (lo < hi) { - PyObject *t = *lo; - *lo = *hi; - *hi = t; - ++lo; - --hi; - } + --hi; + while (lo < hi) { + PyObject *t = *lo; + *lo = *hi; + *hi = t; + ++lo; + --hi; + } } /* Lots of code for an adaptive, stable, natural mergesort. There are many @@ -951,7 +951,7 @@ started. It makes more sense in context . X and Y are PyObject*s. */ #define IFLT(X, Y) if ((k = ISLT(X, Y)) < 0) goto fail; \ - if (k) + if (k) /* binarysort is the best method for sorting small arrays: it does few compares, but can do data movement quadratic in the number of @@ -967,48 +967,48 @@ static int binarysort(PyObject **lo, PyObject **hi, PyObject **start) { - register Py_ssize_t k; - register PyObject **l, **p, **r; - register PyObject *pivot; - - assert(lo <= start && start <= hi); - /* assert [lo, start) is sorted */ - if (lo == start) - ++start; - for (; start < hi; ++start) { - /* set l to where *start belongs */ - l = lo; - r = start; - pivot = *r; - /* Invariants: - * pivot >= all in [lo, l). - * pivot < all in [r, start). - * The second is vacuously true at the start. - */ - assert(l < r); - do { - p = l + ((r - l) >> 1); - IFLT(pivot, *p) - r = p; - else - l = p+1; - } while (l < r); - assert(l == r); - /* The invariants still hold, so pivot >= all in [lo, l) and - pivot < all in [l, start), so pivot belongs at l. Note - that if there are elements equal to pivot, l points to the - first slot after them -- that's why this sort is stable. - Slide over to make room. - Caution: using memmove is much slower under MSVC 5; - we're not usually moving many slots. */ - for (p = start; p > l; --p) - *p = *(p-1); - *l = pivot; - } - return 0; + register Py_ssize_t k; + register PyObject **l, **p, **r; + register PyObject *pivot; + + assert(lo <= start && start <= hi); + /* assert [lo, start) is sorted */ + if (lo == start) + ++start; + for (; start < hi; ++start) { + /* set l to where *start belongs */ + l = lo; + r = start; + pivot = *r; + /* Invariants: + * pivot >= all in [lo, l). + * pivot < all in [r, start). + * The second is vacuously true at the start. + */ + assert(l < r); + do { + p = l + ((r - l) >> 1); + IFLT(pivot, *p) + r = p; + else + l = p+1; + } while (l < r); + assert(l == r); + /* The invariants still hold, so pivot >= all in [lo, l) and + pivot < all in [l, start), so pivot belongs at l. Note + that if there are elements equal to pivot, l points to the + first slot after them -- that's why this sort is stable. + Slide over to make room. + Caution: using memmove is much slower under MSVC 5; + we're not usually moving many slots. */ + for (p = start; p > l; --p) + *p = *(p-1); + *l = pivot; + } + return 0; fail: - return -1; + return -1; } /* @@ -1032,35 +1032,35 @@ static Py_ssize_t count_run(PyObject **lo, PyObject **hi, int *descending) { - Py_ssize_t k; - Py_ssize_t n; + Py_ssize_t k; + Py_ssize_t n; - assert(lo < hi); - *descending = 0; - ++lo; - if (lo == hi) - return 1; - - n = 2; - IFLT(*lo, *(lo-1)) { - *descending = 1; - for (lo = lo+1; lo < hi; ++lo, ++n) { - IFLT(*lo, *(lo-1)) - ; - else - break; - } - } - else { - for (lo = lo+1; lo < hi; ++lo, ++n) { - IFLT(*lo, *(lo-1)) - break; - } - } + assert(lo < hi); + *descending = 0; + ++lo; + if (lo == hi) + return 1; + + n = 2; + IFLT(*lo, *(lo-1)) { + *descending = 1; + for (lo = lo+1; lo < hi; ++lo, ++n) { + IFLT(*lo, *(lo-1)) + ; + else + break; + } + } + else { + for (lo = lo+1; lo < hi; ++lo, ++n) { + IFLT(*lo, *(lo-1)) + break; + } + } - return n; + return n; fail: - return -1; + return -1; } /* @@ -1087,78 +1087,78 @@ static Py_ssize_t gallop_left(PyObject *key, PyObject **a, Py_ssize_t n, Py_ssize_t hint) { - Py_ssize_t ofs; - Py_ssize_t lastofs; - Py_ssize_t k; - - assert(key && a && n > 0 && hint >= 0 && hint < n); - - a += hint; - lastofs = 0; - ofs = 1; - IFLT(*a, key) { - /* a[hint] < key -- gallop right, until - * a[hint + lastofs] < key <= a[hint + ofs] - */ - const Py_ssize_t maxofs = n - hint; /* &a[n-1] is highest */ - while (ofs < maxofs) { - IFLT(a[ofs], key) { - lastofs = ofs; - ofs = (ofs << 1) + 1; - if (ofs <= 0) /* int overflow */ - ofs = maxofs; - } - else /* key <= a[hint + ofs] */ - break; - } - if (ofs > maxofs) - ofs = maxofs; - /* Translate back to offsets relative to &a[0]. */ - lastofs += hint; - ofs += hint; - } - else { - /* key <= a[hint] -- gallop left, until - * a[hint - ofs] < key <= a[hint - lastofs] - */ - const Py_ssize_t maxofs = hint + 1; /* &a[0] is lowest */ - while (ofs < maxofs) { - IFLT(*(a-ofs), key) - break; - /* key <= a[hint - ofs] */ - lastofs = ofs; - ofs = (ofs << 1) + 1; - if (ofs <= 0) /* int overflow */ - ofs = maxofs; - } - if (ofs > maxofs) - ofs = maxofs; - /* Translate back to positive offsets relative to &a[0]. */ - k = lastofs; - lastofs = hint - ofs; - ofs = hint - k; - } - a -= hint; - - assert(-1 <= lastofs && lastofs < ofs && ofs <= n); - /* Now a[lastofs] < key <= a[ofs], so key belongs somewhere to the - * right of lastofs but no farther right than ofs. Do a binary - * search, with invariant a[lastofs-1] < key <= a[ofs]. - */ - ++lastofs; - while (lastofs < ofs) { - Py_ssize_t m = lastofs + ((ofs - lastofs) >> 1); - - IFLT(a[m], key) - lastofs = m+1; /* a[m] < key */ - else - ofs = m; /* key <= a[m] */ - } - assert(lastofs == ofs); /* so a[ofs-1] < key <= a[ofs] */ - return ofs; + Py_ssize_t ofs; + Py_ssize_t lastofs; + Py_ssize_t k; + + assert(key && a && n > 0 && hint >= 0 && hint < n); + + a += hint; + lastofs = 0; + ofs = 1; + IFLT(*a, key) { + /* a[hint] < key -- gallop right, until + * a[hint + lastofs] < key <= a[hint + ofs] + */ + const Py_ssize_t maxofs = n - hint; /* &a[n-1] is highest */ + while (ofs < maxofs) { + IFLT(a[ofs], key) { + lastofs = ofs; + ofs = (ofs << 1) + 1; + if (ofs <= 0) /* int overflow */ + ofs = maxofs; + } + else /* key <= a[hint + ofs] */ + break; + } + if (ofs > maxofs) + ofs = maxofs; + /* Translate back to offsets relative to &a[0]. */ + lastofs += hint; + ofs += hint; + } + else { + /* key <= a[hint] -- gallop left, until + * a[hint - ofs] < key <= a[hint - lastofs] + */ + const Py_ssize_t maxofs = hint + 1; /* &a[0] is lowest */ + while (ofs < maxofs) { + IFLT(*(a-ofs), key) + break; + /* key <= a[hint - ofs] */ + lastofs = ofs; + ofs = (ofs << 1) + 1; + if (ofs <= 0) /* int overflow */ + ofs = maxofs; + } + if (ofs > maxofs) + ofs = maxofs; + /* Translate back to positive offsets relative to &a[0]. */ + k = lastofs; + lastofs = hint - ofs; + ofs = hint - k; + } + a -= hint; + + assert(-1 <= lastofs && lastofs < ofs && ofs <= n); + /* Now a[lastofs] < key <= a[ofs], so key belongs somewhere to the + * right of lastofs but no farther right than ofs. Do a binary + * search, with invariant a[lastofs-1] < key <= a[ofs]. + */ + ++lastofs; + while (lastofs < ofs) { + Py_ssize_t m = lastofs + ((ofs - lastofs) >> 1); + + IFLT(a[m], key) + lastofs = m+1; /* a[m] < key */ + else + ofs = m; /* key <= a[m] */ + } + assert(lastofs == ofs); /* so a[ofs-1] < key <= a[ofs] */ + return ofs; fail: - return -1; + return -1; } /* @@ -1178,78 +1178,78 @@ static Py_ssize_t gallop_right(PyObject *key, PyObject **a, Py_ssize_t n, Py_ssize_t hint) { - Py_ssize_t ofs; - Py_ssize_t lastofs; - Py_ssize_t k; - - assert(key && a && n > 0 && hint >= 0 && hint < n); - - a += hint; - lastofs = 0; - ofs = 1; - IFLT(key, *a) { - /* key < a[hint] -- gallop left, until - * a[hint - ofs] <= key < a[hint - lastofs] - */ - const Py_ssize_t maxofs = hint + 1; /* &a[0] is lowest */ - while (ofs < maxofs) { - IFLT(key, *(a-ofs)) { - lastofs = ofs; - ofs = (ofs << 1) + 1; - if (ofs <= 0) /* int overflow */ - ofs = maxofs; - } - else /* a[hint - ofs] <= key */ - break; - } - if (ofs > maxofs) - ofs = maxofs; - /* Translate back to positive offsets relative to &a[0]. */ - k = lastofs; - lastofs = hint - ofs; - ofs = hint - k; - } - else { - /* a[hint] <= key -- gallop right, until - * a[hint + lastofs] <= key < a[hint + ofs] - */ - const Py_ssize_t maxofs = n - hint; /* &a[n-1] is highest */ - while (ofs < maxofs) { - IFLT(key, a[ofs]) - break; - /* a[hint + ofs] <= key */ - lastofs = ofs; - ofs = (ofs << 1) + 1; - if (ofs <= 0) /* int overflow */ - ofs = maxofs; - } - if (ofs > maxofs) - ofs = maxofs; - /* Translate back to offsets relative to &a[0]. */ - lastofs += hint; - ofs += hint; - } - a -= hint; - - assert(-1 <= lastofs && lastofs < ofs && ofs <= n); - /* Now a[lastofs] <= key < a[ofs], so key belongs somewhere to the - * right of lastofs but no farther right than ofs. Do a binary - * search, with invariant a[lastofs-1] <= key < a[ofs]. - */ - ++lastofs; - while (lastofs < ofs) { - Py_ssize_t m = lastofs + ((ofs - lastofs) >> 1); - - IFLT(key, a[m]) - ofs = m; /* key < a[m] */ - else - lastofs = m+1; /* a[m] <= key */ - } - assert(lastofs == ofs); /* so a[ofs-1] <= key < a[ofs] */ - return ofs; + Py_ssize_t ofs; + Py_ssize_t lastofs; + Py_ssize_t k; + + assert(key && a && n > 0 && hint >= 0 && hint < n); + + a += hint; + lastofs = 0; + ofs = 1; + IFLT(key, *a) { + /* key < a[hint] -- gallop left, until + * a[hint - ofs] <= key < a[hint - lastofs] + */ + const Py_ssize_t maxofs = hint + 1; /* &a[0] is lowest */ + while (ofs < maxofs) { + IFLT(key, *(a-ofs)) { + lastofs = ofs; + ofs = (ofs << 1) + 1; + if (ofs <= 0) /* int overflow */ + ofs = maxofs; + } + else /* a[hint - ofs] <= key */ + break; + } + if (ofs > maxofs) + ofs = maxofs; + /* Translate back to positive offsets relative to &a[0]. */ + k = lastofs; + lastofs = hint - ofs; + ofs = hint - k; + } + else { + /* a[hint] <= key -- gallop right, until + * a[hint + lastofs] <= key < a[hint + ofs] + */ + const Py_ssize_t maxofs = n - hint; /* &a[n-1] is highest */ + while (ofs < maxofs) { + IFLT(key, a[ofs]) + break; + /* a[hint + ofs] <= key */ + lastofs = ofs; + ofs = (ofs << 1) + 1; + if (ofs <= 0) /* int overflow */ + ofs = maxofs; + } + if (ofs > maxofs) + ofs = maxofs; + /* Translate back to offsets relative to &a[0]. */ + lastofs += hint; + ofs += hint; + } + a -= hint; + + assert(-1 <= lastofs && lastofs < ofs && ofs <= n); + /* Now a[lastofs] <= key < a[ofs], so key belongs somewhere to the + * right of lastofs but no farther right than ofs. Do a binary + * search, with invariant a[lastofs-1] <= key < a[ofs]. + */ + ++lastofs; + while (lastofs < ofs) { + Py_ssize_t m = lastofs + ((ofs - lastofs) >> 1); + + IFLT(key, a[m]) + ofs = m; /* key < a[m] */ + else + lastofs = m+1; /* a[m] <= key */ + } + assert(lastofs == ofs); /* so a[ofs-1] <= key < a[ofs] */ + return ofs; fail: - return -1; + return -1; } /* The maximum number of entries in a MergeState's pending-runs stack. @@ -1272,48 +1272,48 @@ * a convenient way to pass state around among the helper functions. */ struct s_slice { - PyObject **base; - Py_ssize_t len; + PyObject **base; + Py_ssize_t len; }; typedef struct s_MergeState { - /* This controls when we get *into* galloping mode. It's initialized - * to MIN_GALLOP. merge_lo and merge_hi tend to nudge it higher for - * random data, and lower for highly structured data. - */ - Py_ssize_t min_gallop; - - /* 'a' is temp storage to help with merges. It contains room for - * alloced entries. - */ - PyObject **a; /* may point to temparray below */ - Py_ssize_t alloced; - - /* A stack of n pending runs yet to be merged. Run #i starts at - * address base[i] and extends for len[i] elements. It's always - * true (so long as the indices are in bounds) that - * - * pending[i].base + pending[i].len == pending[i+1].base - * - * so we could cut the storage for this, but it's a minor amount, - * and keeping all the info explicit simplifies the code. - */ - int n; - struct s_slice pending[MAX_MERGE_PENDING]; + /* This controls when we get *into* galloping mode. It's initialized + * to MIN_GALLOP. merge_lo and merge_hi tend to nudge it higher for + * random data, and lower for highly structured data. + */ + Py_ssize_t min_gallop; + + /* 'a' is temp storage to help with merges. It contains room for + * alloced entries. + */ + PyObject **a; /* may point to temparray below */ + Py_ssize_t alloced; + + /* A stack of n pending runs yet to be merged. Run #i starts at + * address base[i] and extends for len[i] elements. It's always + * true (so long as the indices are in bounds) that + * + * pending[i].base + pending[i].len == pending[i+1].base + * + * so we could cut the storage for this, but it's a minor amount, + * and keeping all the info explicit simplifies the code. + */ + int n; + struct s_slice pending[MAX_MERGE_PENDING]; - /* 'a' points to this when possible, rather than muck with malloc. */ - PyObject *temparray[MERGESTATE_TEMP_SIZE]; + /* 'a' points to this when possible, rather than muck with malloc. */ + PyObject *temparray[MERGESTATE_TEMP_SIZE]; } MergeState; /* Conceptually a MergeState's constructor. */ static void merge_init(MergeState *ms) { - assert(ms != NULL); - ms->a = ms->temparray; - ms->alloced = MERGESTATE_TEMP_SIZE; - ms->n = 0; - ms->min_gallop = MIN_GALLOP; + assert(ms != NULL); + ms->a = ms->temparray; + ms->alloced = MERGESTATE_TEMP_SIZE; + ms->n = 0; + ms->min_gallop = MIN_GALLOP; } /* Free all the temp memory owned by the MergeState. This must be called @@ -1323,11 +1323,11 @@ static void merge_freemem(MergeState *ms) { - assert(ms != NULL); - if (ms->a != ms->temparray) - PyMem_Free(ms->a); - ms->a = ms->temparray; - ms->alloced = MERGESTATE_TEMP_SIZE; + assert(ms != NULL); + if (ms->a != ms->temparray) + PyMem_Free(ms->a); + ms->a = ms->temparray; + ms->alloced = MERGESTATE_TEMP_SIZE; } /* Ensure enough temp memory for 'need' array slots is available. @@ -1336,28 +1336,28 @@ static int merge_getmem(MergeState *ms, Py_ssize_t need) { - assert(ms != NULL); - if (need <= ms->alloced) - return 0; - /* Don't realloc! That can cost cycles to copy the old data, but - * we don't care what's in the block. - */ - merge_freemem(ms); - if ((size_t)need > PY_SSIZE_T_MAX / sizeof(PyObject*)) { - PyErr_NoMemory(); - return -1; - } - ms->a = (PyObject **)PyMem_Malloc(need * sizeof(PyObject*)); - if (ms->a) { - ms->alloced = need; - return 0; - } - PyErr_NoMemory(); - merge_freemem(ms); /* reset to sane state */ - return -1; + assert(ms != NULL); + if (need <= ms->alloced) + return 0; + /* Don't realloc! That can cost cycles to copy the old data, but + * we don't care what's in the block. + */ + merge_freemem(ms); + if ((size_t)need > PY_SSIZE_T_MAX / sizeof(PyObject*)) { + PyErr_NoMemory(); + return -1; + } + ms->a = (PyObject **)PyMem_Malloc(need * sizeof(PyObject*)); + if (ms->a) { + ms->alloced = need; + return 0; + } + PyErr_NoMemory(); + merge_freemem(ms); /* reset to sane state */ + return -1; } -#define MERGE_GETMEM(MS, NEED) ((NEED) <= (MS)->alloced ? 0 : \ - merge_getmem(MS, NEED)) +#define MERGE_GETMEM(MS, NEED) ((NEED) <= (MS)->alloced ? 0 : \ + merge_getmem(MS, NEED)) /* Merge the na elements starting at pa with the nb elements starting at pb * in a stable way, in-place. na and nb must be > 0, and pa + na == pb. @@ -1369,125 +1369,125 @@ merge_lo(MergeState *ms, PyObject **pa, Py_ssize_t na, PyObject **pb, Py_ssize_t nb) { - Py_ssize_t k; - PyObject **dest; - int result = -1; /* guilty until proved innocent */ - Py_ssize_t min_gallop; - - assert(ms && pa && pb && na > 0 && nb > 0 && pa + na == pb); - if (MERGE_GETMEM(ms, na) < 0) - return -1; - memcpy(ms->a, pa, na * sizeof(PyObject*)); - dest = pa; - pa = ms->a; - - *dest++ = *pb++; - --nb; - if (nb == 0) - goto Succeed; - if (na == 1) - goto CopyB; - - min_gallop = ms->min_gallop; - for (;;) { - Py_ssize_t acount = 0; /* # of times A won in a row */ - Py_ssize_t bcount = 0; /* # of times B won in a row */ - - /* Do the straightforward thing until (if ever) one run - * appears to win consistently. - */ - for (;;) { - assert(na > 1 && nb > 0); - k = ISLT(*pb, *pa); - if (k) { - if (k < 0) - goto Fail; - *dest++ = *pb++; - ++bcount; - acount = 0; - --nb; - if (nb == 0) - goto Succeed; - if (bcount >= min_gallop) - break; - } - else { - *dest++ = *pa++; - ++acount; - bcount = 0; - --na; - if (na == 1) - goto CopyB; - if (acount >= min_gallop) - break; - } - } - - /* One run is winning so consistently that galloping may - * be a huge win. So try that, and continue galloping until - * (if ever) neither run appears to be winning consistently - * anymore. - */ - ++min_gallop; - do { - assert(na > 1 && nb > 0); - min_gallop -= min_gallop > 1; - ms->min_gallop = min_gallop; - k = gallop_right(*pb, pa, na, 0); - acount = k; - if (k) { - if (k < 0) - goto Fail; - memcpy(dest, pa, k * sizeof(PyObject *)); - dest += k; - pa += k; - na -= k; - if (na == 1) - goto CopyB; - /* na==0 is impossible now if the comparison - * function is consistent, but we can't assume - * that it is. - */ - if (na == 0) - goto Succeed; - } - *dest++ = *pb++; - --nb; - if (nb == 0) - goto Succeed; - - k = gallop_left(*pa, pb, nb, 0); - bcount = k; - if (k) { - if (k < 0) - goto Fail; - memmove(dest, pb, k * sizeof(PyObject *)); - dest += k; - pb += k; - nb -= k; - if (nb == 0) - goto Succeed; - } - *dest++ = *pa++; - --na; - if (na == 1) - goto CopyB; - } while (acount >= MIN_GALLOP || bcount >= MIN_GALLOP); - ++min_gallop; /* penalize it for leaving galloping mode */ - ms->min_gallop = min_gallop; - } + Py_ssize_t k; + PyObject **dest; + int result = -1; /* guilty until proved innocent */ + Py_ssize_t min_gallop; + + assert(ms && pa && pb && na > 0 && nb > 0 && pa + na == pb); + if (MERGE_GETMEM(ms, na) < 0) + return -1; + memcpy(ms->a, pa, na * sizeof(PyObject*)); + dest = pa; + pa = ms->a; + + *dest++ = *pb++; + --nb; + if (nb == 0) + goto Succeed; + if (na == 1) + goto CopyB; + + min_gallop = ms->min_gallop; + for (;;) { + Py_ssize_t acount = 0; /* # of times A won in a row */ + Py_ssize_t bcount = 0; /* # of times B won in a row */ + + /* Do the straightforward thing until (if ever) one run + * appears to win consistently. + */ + for (;;) { + assert(na > 1 && nb > 0); + k = ISLT(*pb, *pa); + if (k) { + if (k < 0) + goto Fail; + *dest++ = *pb++; + ++bcount; + acount = 0; + --nb; + if (nb == 0) + goto Succeed; + if (bcount >= min_gallop) + break; + } + else { + *dest++ = *pa++; + ++acount; + bcount = 0; + --na; + if (na == 1) + goto CopyB; + if (acount >= min_gallop) + break; + } + } + + /* One run is winning so consistently that galloping may + * be a huge win. So try that, and continue galloping until + * (if ever) neither run appears to be winning consistently + * anymore. + */ + ++min_gallop; + do { + assert(na > 1 && nb > 0); + min_gallop -= min_gallop > 1; + ms->min_gallop = min_gallop; + k = gallop_right(*pb, pa, na, 0); + acount = k; + if (k) { + if (k < 0) + goto Fail; + memcpy(dest, pa, k * sizeof(PyObject *)); + dest += k; + pa += k; + na -= k; + if (na == 1) + goto CopyB; + /* na==0 is impossible now if the comparison + * function is consistent, but we can't assume + * that it is. + */ + if (na == 0) + goto Succeed; + } + *dest++ = *pb++; + --nb; + if (nb == 0) + goto Succeed; + + k = gallop_left(*pa, pb, nb, 0); + bcount = k; + if (k) { + if (k < 0) + goto Fail; + memmove(dest, pb, k * sizeof(PyObject *)); + dest += k; + pb += k; + nb -= k; + if (nb == 0) + goto Succeed; + } + *dest++ = *pa++; + --na; + if (na == 1) + goto CopyB; + } while (acount >= MIN_GALLOP || bcount >= MIN_GALLOP); + ++min_gallop; /* penalize it for leaving galloping mode */ + ms->min_gallop = min_gallop; + } Succeed: - result = 0; + result = 0; Fail: - if (na) - memcpy(dest, pa, na * sizeof(PyObject*)); - return result; + if (na) + memcpy(dest, pa, na * sizeof(PyObject*)); + return result; CopyB: - assert(na == 1 && nb > 0); - /* The last element of pa belongs at the end of the merge. */ - memmove(dest, pb, nb * sizeof(PyObject *)); - dest[nb] = *pa; - return 0; + assert(na == 1 && nb > 0); + /* The last element of pa belongs at the end of the merge. */ + memmove(dest, pb, nb * sizeof(PyObject *)); + dest[nb] = *pa; + return 0; } /* Merge the na elements starting at pa with the nb elements starting at pb @@ -1499,134 +1499,134 @@ static Py_ssize_t merge_hi(MergeState *ms, PyObject **pa, Py_ssize_t na, PyObject **pb, Py_ssize_t nb) { - Py_ssize_t k; - PyObject **dest; - int result = -1; /* guilty until proved innocent */ - PyObject **basea; - PyObject **baseb; - Py_ssize_t min_gallop; - - assert(ms && pa && pb && na > 0 && nb > 0 && pa + na == pb); - if (MERGE_GETMEM(ms, nb) < 0) - return -1; - dest = pb + nb - 1; - memcpy(ms->a, pb, nb * sizeof(PyObject*)); - basea = pa; - baseb = ms->a; - pb = ms->a + nb - 1; - pa += na - 1; - - *dest-- = *pa--; - --na; - if (na == 0) - goto Succeed; - if (nb == 1) - goto CopyA; - - min_gallop = ms->min_gallop; - for (;;) { - Py_ssize_t acount = 0; /* # of times A won in a row */ - Py_ssize_t bcount = 0; /* # of times B won in a row */ - - /* Do the straightforward thing until (if ever) one run - * appears to win consistently. - */ - for (;;) { - assert(na > 0 && nb > 1); - k = ISLT(*pb, *pa); - if (k) { - if (k < 0) - goto Fail; - *dest-- = *pa--; - ++acount; - bcount = 0; - --na; - if (na == 0) - goto Succeed; - if (acount >= min_gallop) - break; - } - else { - *dest-- = *pb--; - ++bcount; - acount = 0; - --nb; - if (nb == 1) - goto CopyA; - if (bcount >= min_gallop) - break; - } - } - - /* One run is winning so consistently that galloping may - * be a huge win. So try that, and continue galloping until - * (if ever) neither run appears to be winning consistently - * anymore. - */ - ++min_gallop; - do { - assert(na > 0 && nb > 1); - min_gallop -= min_gallop > 1; - ms->min_gallop = min_gallop; - k = gallop_right(*pb, basea, na, na-1); - if (k < 0) - goto Fail; - k = na - k; - acount = k; - if (k) { - dest -= k; - pa -= k; - memmove(dest+1, pa+1, k * sizeof(PyObject *)); - na -= k; - if (na == 0) - goto Succeed; - } - *dest-- = *pb--; - --nb; - if (nb == 1) - goto CopyA; - - k = gallop_left(*pa, baseb, nb, nb-1); - if (k < 0) - goto Fail; - k = nb - k; - bcount = k; - if (k) { - dest -= k; - pb -= k; - memcpy(dest+1, pb+1, k * sizeof(PyObject *)); - nb -= k; - if (nb == 1) - goto CopyA; - /* nb==0 is impossible now if the comparison - * function is consistent, but we can't assume - * that it is. - */ - if (nb == 0) - goto Succeed; - } - *dest-- = *pa--; - --na; - if (na == 0) - goto Succeed; - } while (acount >= MIN_GALLOP || bcount >= MIN_GALLOP); - ++min_gallop; /* penalize it for leaving galloping mode */ - ms->min_gallop = min_gallop; - } + Py_ssize_t k; + PyObject **dest; + int result = -1; /* guilty until proved innocent */ + PyObject **basea; + PyObject **baseb; + Py_ssize_t min_gallop; + + assert(ms && pa && pb && na > 0 && nb > 0 && pa + na == pb); + if (MERGE_GETMEM(ms, nb) < 0) + return -1; + dest = pb + nb - 1; + memcpy(ms->a, pb, nb * sizeof(PyObject*)); + basea = pa; + baseb = ms->a; + pb = ms->a + nb - 1; + pa += na - 1; + + *dest-- = *pa--; + --na; + if (na == 0) + goto Succeed; + if (nb == 1) + goto CopyA; + + min_gallop = ms->min_gallop; + for (;;) { + Py_ssize_t acount = 0; /* # of times A won in a row */ + Py_ssize_t bcount = 0; /* # of times B won in a row */ + + /* Do the straightforward thing until (if ever) one run + * appears to win consistently. + */ + for (;;) { + assert(na > 0 && nb > 1); + k = ISLT(*pb, *pa); + if (k) { + if (k < 0) + goto Fail; + *dest-- = *pa--; + ++acount; + bcount = 0; + --na; + if (na == 0) + goto Succeed; + if (acount >= min_gallop) + break; + } + else { + *dest-- = *pb--; + ++bcount; + acount = 0; + --nb; + if (nb == 1) + goto CopyA; + if (bcount >= min_gallop) + break; + } + } + + /* One run is winning so consistently that galloping may + * be a huge win. So try that, and continue galloping until + * (if ever) neither run appears to be winning consistently + * anymore. + */ + ++min_gallop; + do { + assert(na > 0 && nb > 1); + min_gallop -= min_gallop > 1; + ms->min_gallop = min_gallop; + k = gallop_right(*pb, basea, na, na-1); + if (k < 0) + goto Fail; + k = na - k; + acount = k; + if (k) { + dest -= k; + pa -= k; + memmove(dest+1, pa+1, k * sizeof(PyObject *)); + na -= k; + if (na == 0) + goto Succeed; + } + *dest-- = *pb--; + --nb; + if (nb == 1) + goto CopyA; + + k = gallop_left(*pa, baseb, nb, nb-1); + if (k < 0) + goto Fail; + k = nb - k; + bcount = k; + if (k) { + dest -= k; + pb -= k; + memcpy(dest+1, pb+1, k * sizeof(PyObject *)); + nb -= k; + if (nb == 1) + goto CopyA; + /* nb==0 is impossible now if the comparison + * function is consistent, but we can't assume + * that it is. + */ + if (nb == 0) + goto Succeed; + } + *dest-- = *pa--; + --na; + if (na == 0) + goto Succeed; + } while (acount >= MIN_GALLOP || bcount >= MIN_GALLOP); + ++min_gallop; /* penalize it for leaving galloping mode */ + ms->min_gallop = min_gallop; + } Succeed: - result = 0; + result = 0; Fail: - if (nb) - memcpy(dest-(nb-1), baseb, nb * sizeof(PyObject*)); - return result; + if (nb) + memcpy(dest-(nb-1), baseb, nb * sizeof(PyObject*)); + return result; CopyA: - assert(nb == 1 && na > 0); - /* The first element of pb belongs at the front of the merge. */ - dest -= na; - pa -= na; - memmove(dest+1, pa+1, na * sizeof(PyObject *)); - *dest = *pb; - return 0; + assert(nb == 1 && na > 0); + /* The first element of pb belongs at the front of the merge. */ + dest -= na; + pa -= na; + memmove(dest+1, pa+1, na * sizeof(PyObject *)); + *dest = *pb; + return 0; } /* Merge the two runs at stack indices i and i+1. @@ -1635,56 +1635,56 @@ static Py_ssize_t merge_at(MergeState *ms, Py_ssize_t i) { - PyObject **pa, **pb; - Py_ssize_t na, nb; - Py_ssize_t k; - - assert(ms != NULL); - assert(ms->n >= 2); - assert(i >= 0); - assert(i == ms->n - 2 || i == ms->n - 3); - - pa = ms->pending[i].base; - na = ms->pending[i].len; - pb = ms->pending[i+1].base; - nb = ms->pending[i+1].len; - assert(na > 0 && nb > 0); - assert(pa + na == pb); - - /* Record the length of the combined runs; if i is the 3rd-last - * run now, also slide over the last run (which isn't involved - * in this merge). The current run i+1 goes away in any case. - */ - ms->pending[i].len = na + nb; - if (i == ms->n - 3) - ms->pending[i+1] = ms->pending[i+2]; - --ms->n; - - /* Where does b start in a? Elements in a before that can be - * ignored (already in place). - */ - k = gallop_right(*pb, pa, na, 0); - if (k < 0) - return -1; - pa += k; - na -= k; - if (na == 0) - return 0; - - /* Where does a end in b? Elements in b after that can be - * ignored (already in place). - */ - nb = gallop_left(pa[na-1], pb, nb, nb-1); - if (nb <= 0) - return nb; - - /* Merge what remains of the runs, using a temp array with - * min(na, nb) elements. - */ - if (na <= nb) - return merge_lo(ms, pa, na, pb, nb); - else - return merge_hi(ms, pa, na, pb, nb); + PyObject **pa, **pb; + Py_ssize_t na, nb; + Py_ssize_t k; + + assert(ms != NULL); + assert(ms->n >= 2); + assert(i >= 0); + assert(i == ms->n - 2 || i == ms->n - 3); + + pa = ms->pending[i].base; + na = ms->pending[i].len; + pb = ms->pending[i+1].base; + nb = ms->pending[i+1].len; + assert(na > 0 && nb > 0); + assert(pa + na == pb); + + /* Record the length of the combined runs; if i is the 3rd-last + * run now, also slide over the last run (which isn't involved + * in this merge). The current run i+1 goes away in any case. + */ + ms->pending[i].len = na + nb; + if (i == ms->n - 3) + ms->pending[i+1] = ms->pending[i+2]; + --ms->n; + + /* Where does b start in a? Elements in a before that can be + * ignored (already in place). + */ + k = gallop_right(*pb, pa, na, 0); + if (k < 0) + return -1; + pa += k; + na -= k; + if (na == 0) + return 0; + + /* Where does a end in b? Elements in b after that can be + * ignored (already in place). + */ + nb = gallop_left(pa[na-1], pb, nb, nb-1); + if (nb <= 0) + return nb; + + /* Merge what remains of the runs, using a temp array with + * min(na, nb) elements. + */ + if (na <= nb) + return merge_lo(ms, pa, na, pb, nb); + else + return merge_hi(ms, pa, na, pb, nb); } /* Examine the stack of runs waiting to be merged, merging adjacent runs @@ -1700,25 +1700,25 @@ static int merge_collapse(MergeState *ms) { - struct s_slice *p = ms->pending; + struct s_slice *p = ms->pending; - assert(ms); - while (ms->n > 1) { - Py_ssize_t n = ms->n - 2; - if (n > 0 && p[n-1].len <= p[n].len + p[n+1].len) { - if (p[n-1].len < p[n+1].len) - --n; - if (merge_at(ms, n) < 0) - return -1; - } - else if (p[n].len <= p[n+1].len) { - if (merge_at(ms, n) < 0) - return -1; - } - else - break; - } - return 0; + assert(ms); + while (ms->n > 1) { + Py_ssize_t n = ms->n - 2; + if (n > 0 && p[n-1].len <= p[n].len + p[n+1].len) { + if (p[n-1].len < p[n+1].len) + --n; + if (merge_at(ms, n) < 0) + return -1; + } + else if (p[n].len <= p[n+1].len) { + if (merge_at(ms, n) < 0) + return -1; + } + else + break; + } + return 0; } /* Regardless of invariants, merge all runs on the stack until only one @@ -1729,17 +1729,17 @@ static int merge_force_collapse(MergeState *ms) { - struct s_slice *p = ms->pending; + struct s_slice *p = ms->pending; - assert(ms); - while (ms->n > 1) { - Py_ssize_t n = ms->n - 2; - if (n > 0 && p[n-1].len < p[n+1].len) - --n; - if (merge_at(ms, n) < 0) - return -1; - } - return 0; + assert(ms); + while (ms->n > 1) { + Py_ssize_t n = ms->n - 2; + if (n > 0 && p[n-1].len < p[n+1].len) + --n; + if (merge_at(ms, n) < 0) + return -1; + } + return 0; } /* Compute a good value for the minimum run length; natural runs shorter @@ -1755,14 +1755,14 @@ static Py_ssize_t merge_compute_minrun(Py_ssize_t n) { - Py_ssize_t r = 0; /* becomes 1 if any 1 bits are shifted off */ + Py_ssize_t r = 0; /* becomes 1 if any 1 bits are shifted off */ - assert(n >= 0); - while (n >= 64) { - r |= n & 1; - n >>= 1; - } - return n + r; + assert(n >= 0); + while (n >= 64) { + r |= n & 1; + n >>= 1; + } + return n + r; } /* Special wrapper to support stable sorting using the decorate-sort-undecorate @@ -1773,9 +1773,9 @@ a full record. */ typedef struct { - PyObject_HEAD - PyObject *key; - PyObject *value; + PyObject_HEAD + PyObject *key; + PyObject *value; } sortwrapperobject; PyDoc_STRVAR(sortwrapper_doc, "Object wrapper with a custom sort key."); @@ -1785,51 +1785,51 @@ sortwrapper_dealloc(sortwrapperobject *); PyTypeObject PySortWrapper_Type = { - PyVarObject_HEAD_INIT(&PyType_Type, 0) - "sortwrapper", /* tp_name */ - sizeof(sortwrapperobject), /* tp_basicsize */ - 0, /* tp_itemsize */ - /* methods */ - (destructor)sortwrapper_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, /* tp_flags */ - sortwrapper_doc, /* tp_doc */ - 0, /* tp_traverse */ - 0, /* tp_clear */ - (richcmpfunc)sortwrapper_richcompare, /* tp_richcompare */ + PyVarObject_HEAD_INIT(&PyType_Type, 0) + "sortwrapper", /* tp_name */ + sizeof(sortwrapperobject), /* tp_basicsize */ + 0, /* tp_itemsize */ + /* methods */ + (destructor)sortwrapper_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, /* tp_flags */ + sortwrapper_doc, /* tp_doc */ + 0, /* tp_traverse */ + 0, /* tp_clear */ + (richcmpfunc)sortwrapper_richcompare, /* tp_richcompare */ }; static PyObject * sortwrapper_richcompare(sortwrapperobject *a, sortwrapperobject *b, int op) { - if (!PyObject_TypeCheck(b, &PySortWrapper_Type)) { - PyErr_SetString(PyExc_TypeError, - "expected a sortwrapperobject"); - return NULL; - } - return PyObject_RichCompare(a->key, b->key, op); + if (!PyObject_TypeCheck(b, &PySortWrapper_Type)) { + PyErr_SetString(PyExc_TypeError, + "expected a sortwrapperobject"); + return NULL; + } + return PyObject_RichCompare(a->key, b->key, op); } static void sortwrapper_dealloc(sortwrapperobject *so) { - Py_XDECREF(so->key); - Py_XDECREF(so->value); - PyObject_Del(so); + Py_XDECREF(so->key); + Py_XDECREF(so->value); + PyObject_Del(so); } /* Returns a new reference to a sortwrapper. @@ -1838,30 +1838,30 @@ static PyObject * build_sortwrapper(PyObject *key, PyObject *value) { - sortwrapperobject *so; + sortwrapperobject *so; - so = PyObject_New(sortwrapperobject, &PySortWrapper_Type); - if (so == NULL) - return NULL; - so->key = key; - so->value = value; - return (PyObject *)so; + so = PyObject_New(sortwrapperobject, &PySortWrapper_Type); + if (so == NULL) + return NULL; + so->key = key; + so->value = value; + return (PyObject *)so; } /* Returns a new reference to the value underlying the wrapper. */ static PyObject * sortwrapper_getvalue(PyObject *so) { - PyObject *value; + PyObject *value; - if (!PyObject_TypeCheck(so, &PySortWrapper_Type)) { - PyErr_SetString(PyExc_TypeError, - "expected a sortwrapperobject"); - return NULL; - } - value = ((sortwrapperobject *)so)->value; - Py_INCREF(value); - return value; + if (!PyObject_TypeCheck(so, &PySortWrapper_Type)) { + PyErr_SetString(PyExc_TypeError, + "expected a sortwrapperobject"); + return NULL; + } + value = ((sortwrapperobject *)so)->value; + Py_INCREF(value); + return value; } /* An adaptive, stable, natural mergesort. See listsort.txt. @@ -1872,163 +1872,163 @@ static PyObject * listsort(PyListObject *self, PyObject *args, PyObject *kwds) { - MergeState ms; - PyObject **lo, **hi; - Py_ssize_t nremaining; - Py_ssize_t minrun; - Py_ssize_t saved_ob_size, saved_allocated; - PyObject **saved_ob_item; - PyObject **final_ob_item; - PyObject *result = NULL; /* guilty until proved innocent */ - int reverse = 0; - PyObject *keyfunc = NULL; - Py_ssize_t i; - PyObject *key, *value, *kvpair; - static char *kwlist[] = {"key", "reverse", 0}; - - assert(self != NULL); - assert (PyList_Check(self)); - if (args != NULL) { - if (!PyArg_ParseTupleAndKeywords(args, kwds, "|Oi:sort", - kwlist, &keyfunc, &reverse)) - return NULL; - if (Py_SIZE(args) > 0) { - PyErr_SetString(PyExc_TypeError, - "must use keyword argument for key function"); - return NULL; - } - } - if (keyfunc == Py_None) - keyfunc = NULL; - - /* The list is temporarily made empty, so that mutations performed - * by comparison functions can't affect the slice of memory we're - * sorting (allowing mutations during sorting is a core-dump - * factory, since ob_item may change). - */ - saved_ob_size = Py_SIZE(self); - saved_ob_item = self->ob_item; - saved_allocated = self->allocated; - Py_SIZE(self) = 0; - self->ob_item = NULL; - self->allocated = -1; /* any operation will reset it to >= 0 */ - - if (keyfunc != NULL) { - for (i=0 ; i < saved_ob_size ; i++) { - value = saved_ob_item[i]; - key = PyObject_CallFunctionObjArgs(keyfunc, value, - NULL); - if (key == NULL) { - for (i=i-1 ; i>=0 ; i--) { - kvpair = saved_ob_item[i]; - value = sortwrapper_getvalue(kvpair); - saved_ob_item[i] = value; - Py_DECREF(kvpair); - } - goto dsu_fail; - } - kvpair = build_sortwrapper(key, value); - if (kvpair == NULL) - goto dsu_fail; - saved_ob_item[i] = kvpair; - } - } - - /* Reverse sort stability achieved by initially reversing the list, - applying a stable forward sort, then reversing the final result. */ - if (reverse && saved_ob_size > 1) - reverse_slice(saved_ob_item, saved_ob_item + saved_ob_size); - - merge_init(&ms); - - nremaining = saved_ob_size; - if (nremaining < 2) - goto succeed; - - /* March over the array once, left to right, finding natural runs, - * and extending short natural runs to minrun elements. - */ - lo = saved_ob_item; - hi = lo + nremaining; - minrun = merge_compute_minrun(nremaining); - do { - int descending; - Py_ssize_t n; - - /* Identify next run. */ - n = count_run(lo, hi, &descending); - if (n < 0) - goto fail; - if (descending) - reverse_slice(lo, lo + n); - /* If short, extend to min(minrun, nremaining). */ - if (n < minrun) { - const Py_ssize_t force = nremaining <= minrun ? - nremaining : minrun; - if (binarysort(lo, lo + force, lo + n) < 0) - goto fail; - n = force; - } - /* Push run onto pending-runs stack, and maybe merge. */ - assert(ms.n < MAX_MERGE_PENDING); - ms.pending[ms.n].base = lo; - ms.pending[ms.n].len = n; - ++ms.n; - if (merge_collapse(&ms) < 0) - goto fail; - /* Advance to find next run. */ - lo += n; - nremaining -= n; - } while (nremaining); - assert(lo == hi); - - if (merge_force_collapse(&ms) < 0) - goto fail; - assert(ms.n == 1); - assert(ms.pending[0].base == saved_ob_item); - assert(ms.pending[0].len == saved_ob_size); + MergeState ms; + PyObject **lo, **hi; + Py_ssize_t nremaining; + Py_ssize_t minrun; + Py_ssize_t saved_ob_size, saved_allocated; + PyObject **saved_ob_item; + PyObject **final_ob_item; + PyObject *result = NULL; /* guilty until proved innocent */ + int reverse = 0; + PyObject *keyfunc = NULL; + Py_ssize_t i; + PyObject *key, *value, *kvpair; + static char *kwlist[] = {"key", "reverse", 0}; + + assert(self != NULL); + assert (PyList_Check(self)); + if (args != NULL) { + if (!PyArg_ParseTupleAndKeywords(args, kwds, "|Oi:sort", + kwlist, &keyfunc, &reverse)) + return NULL; + if (Py_SIZE(args) > 0) { + PyErr_SetString(PyExc_TypeError, + "must use keyword argument for key function"); + return NULL; + } + } + if (keyfunc == Py_None) + keyfunc = NULL; + + /* The list is temporarily made empty, so that mutations performed + * by comparison functions can't affect the slice of memory we're + * sorting (allowing mutations during sorting is a core-dump + * factory, since ob_item may change). + */ + saved_ob_size = Py_SIZE(self); + saved_ob_item = self->ob_item; + saved_allocated = self->allocated; + Py_SIZE(self) = 0; + self->ob_item = NULL; + self->allocated = -1; /* any operation will reset it to >= 0 */ + + if (keyfunc != NULL) { + for (i=0 ; i < saved_ob_size ; i++) { + value = saved_ob_item[i]; + key = PyObject_CallFunctionObjArgs(keyfunc, value, + NULL); + if (key == NULL) { + for (i=i-1 ; i>=0 ; i--) { + kvpair = saved_ob_item[i]; + value = sortwrapper_getvalue(kvpair); + saved_ob_item[i] = value; + Py_DECREF(kvpair); + } + goto dsu_fail; + } + kvpair = build_sortwrapper(key, value); + if (kvpair == NULL) + goto dsu_fail; + saved_ob_item[i] = kvpair; + } + } + + /* Reverse sort stability achieved by initially reversing the list, + applying a stable forward sort, then reversing the final result. */ + if (reverse && saved_ob_size > 1) + reverse_slice(saved_ob_item, saved_ob_item + saved_ob_size); + + merge_init(&ms); + + nremaining = saved_ob_size; + if (nremaining < 2) + goto succeed; + + /* March over the array once, left to right, finding natural runs, + * and extending short natural runs to minrun elements. + */ + lo = saved_ob_item; + hi = lo + nremaining; + minrun = merge_compute_minrun(nremaining); + do { + int descending; + Py_ssize_t n; + + /* Identify next run. */ + n = count_run(lo, hi, &descending); + if (n < 0) + goto fail; + if (descending) + reverse_slice(lo, lo + n); + /* If short, extend to min(minrun, nremaining). */ + if (n < minrun) { + const Py_ssize_t force = nremaining <= minrun ? + nremaining : minrun; + if (binarysort(lo, lo + force, lo + n) < 0) + goto fail; + n = force; + } + /* Push run onto pending-runs stack, and maybe merge. */ + assert(ms.n < MAX_MERGE_PENDING); + ms.pending[ms.n].base = lo; + ms.pending[ms.n].len = n; + ++ms.n; + if (merge_collapse(&ms) < 0) + goto fail; + /* Advance to find next run. */ + lo += n; + nremaining -= n; + } while (nremaining); + assert(lo == hi); + + if (merge_force_collapse(&ms) < 0) + goto fail; + assert(ms.n == 1); + assert(ms.pending[0].base == saved_ob_item); + assert(ms.pending[0].len == saved_ob_size); succeed: - result = Py_None; + result = Py_None; fail: - if (keyfunc != NULL) { - for (i=0 ; i < saved_ob_size ; i++) { - kvpair = saved_ob_item[i]; - value = sortwrapper_getvalue(kvpair); - saved_ob_item[i] = value; - Py_DECREF(kvpair); - } - } - - if (self->allocated != -1 && result != NULL) { - /* The user mucked with the list during the sort, - * and we don't already have another error to report. - */ - PyErr_SetString(PyExc_ValueError, "list modified during sort"); - result = NULL; - } + if (keyfunc != NULL) { + for (i=0 ; i < saved_ob_size ; i++) { + kvpair = saved_ob_item[i]; + value = sortwrapper_getvalue(kvpair); + saved_ob_item[i] = value; + Py_DECREF(kvpair); + } + } + + if (self->allocated != -1 && result != NULL) { + /* The user mucked with the list during the sort, + * and we don't already have another error to report. + */ + PyErr_SetString(PyExc_ValueError, "list modified during sort"); + result = NULL; + } - if (reverse && saved_ob_size > 1) - reverse_slice(saved_ob_item, saved_ob_item + saved_ob_size); + if (reverse && saved_ob_size > 1) + reverse_slice(saved_ob_item, saved_ob_item + saved_ob_size); - merge_freemem(&ms); + merge_freemem(&ms); dsu_fail: - final_ob_item = self->ob_item; - i = Py_SIZE(self); - Py_SIZE(self) = saved_ob_size; - self->ob_item = saved_ob_item; - self->allocated = saved_allocated; - if (final_ob_item != NULL) { - /* we cannot use list_clear() for this because it does not - guarantee that the list is really empty when it returns */ - while (--i >= 0) { - Py_XDECREF(final_ob_item[i]); - } - PyMem_FREE(final_ob_item); - } - Py_XINCREF(result); - return result; + final_ob_item = self->ob_item; + i = Py_SIZE(self); + Py_SIZE(self) = saved_ob_size; + self->ob_item = saved_ob_item; + self->allocated = saved_allocated; + if (final_ob_item != NULL) { + /* we cannot use list_clear() for this because it does not + guarantee that the list is really empty when it returns */ + while (--i >= 0) { + Py_XDECREF(final_ob_item[i]); + } + PyMem_FREE(final_ob_item); + } + Py_XINCREF(result); + return result; } #undef IFLT #undef ISLT @@ -2036,262 +2036,262 @@ int PyList_Sort(PyObject *v) { - if (v == NULL || !PyList_Check(v)) { - PyErr_BadInternalCall(); - return -1; - } - v = listsort((PyListObject *)v, (PyObject *)NULL, (PyObject *)NULL); - if (v == NULL) - return -1; - Py_DECREF(v); - return 0; + if (v == NULL || !PyList_Check(v)) { + PyErr_BadInternalCall(); + return -1; + } + v = listsort((PyListObject *)v, (PyObject *)NULL, (PyObject *)NULL); + if (v == NULL) + return -1; + Py_DECREF(v); + return 0; } static PyObject * listreverse(PyListObject *self) { - if (Py_SIZE(self) > 1) - reverse_slice(self->ob_item, self->ob_item + Py_SIZE(self)); - Py_RETURN_NONE; + if (Py_SIZE(self) > 1) + reverse_slice(self->ob_item, self->ob_item + Py_SIZE(self)); + Py_RETURN_NONE; } int PyList_Reverse(PyObject *v) { - PyListObject *self = (PyListObject *)v; + PyListObject *self = (PyListObject *)v; - if (v == NULL || !PyList_Check(v)) { - PyErr_BadInternalCall(); - return -1; - } - if (Py_SIZE(self) > 1) - reverse_slice(self->ob_item, self->ob_item + Py_SIZE(self)); - return 0; + if (v == NULL || !PyList_Check(v)) { + PyErr_BadInternalCall(); + return -1; + } + if (Py_SIZE(self) > 1) + reverse_slice(self->ob_item, self->ob_item + Py_SIZE(self)); + return 0; } PyObject * PyList_AsTuple(PyObject *v) { - PyObject *w; - PyObject **p, **q; - Py_ssize_t n; - if (v == NULL || !PyList_Check(v)) { - PyErr_BadInternalCall(); - return NULL; - } - n = Py_SIZE(v); - w = PyTuple_New(n); - if (w == NULL) - return NULL; - p = ((PyTupleObject *)w)->ob_item; - q = ((PyListObject *)v)->ob_item; - while (--n >= 0) { - Py_INCREF(*q); - *p = *q; - p++; - q++; - } - return w; + PyObject *w; + PyObject **p, **q; + Py_ssize_t n; + if (v == NULL || !PyList_Check(v)) { + PyErr_BadInternalCall(); + return NULL; + } + n = Py_SIZE(v); + w = PyTuple_New(n); + if (w == NULL) + return NULL; + p = ((PyTupleObject *)w)->ob_item; + q = ((PyListObject *)v)->ob_item; + while (--n >= 0) { + Py_INCREF(*q); + *p = *q; + p++; + q++; + } + return w; } static PyObject * listindex(PyListObject *self, PyObject *args) { - Py_ssize_t i, start=0, stop=Py_SIZE(self); - PyObject *v, *format_tuple, *err_string; - static PyObject *err_format = NULL; - - if (!PyArg_ParseTuple(args, "O|O&O&:index", &v, - _PyEval_SliceIndex, &start, - _PyEval_SliceIndex, &stop)) - return NULL; - if (start < 0) { - start += Py_SIZE(self); - if (start < 0) - start = 0; - } - if (stop < 0) { - stop += Py_SIZE(self); - if (stop < 0) - stop = 0; - } - for (i = start; i < stop && i < Py_SIZE(self); i++) { - int cmp = PyObject_RichCompareBool(self->ob_item[i], v, Py_EQ); - if (cmp > 0) - return PyLong_FromSsize_t(i); - else if (cmp < 0) - return NULL; - } - if (err_format == NULL) { - err_format = PyUnicode_FromString("%r is not in list"); - if (err_format == NULL) - return NULL; - } - format_tuple = PyTuple_Pack(1, v); - if (format_tuple == NULL) - return NULL; - err_string = PyUnicode_Format(err_format, format_tuple); - Py_DECREF(format_tuple); - if (err_string == NULL) - return NULL; - PyErr_SetObject(PyExc_ValueError, err_string); - Py_DECREF(err_string); - return NULL; + Py_ssize_t i, start=0, stop=Py_SIZE(self); + PyObject *v, *format_tuple, *err_string; + static PyObject *err_format = NULL; + + if (!PyArg_ParseTuple(args, "O|O&O&:index", &v, + _PyEval_SliceIndex, &start, + _PyEval_SliceIndex, &stop)) + return NULL; + if (start < 0) { + start += Py_SIZE(self); + if (start < 0) + start = 0; + } + if (stop < 0) { + stop += Py_SIZE(self); + if (stop < 0) + stop = 0; + } + for (i = start; i < stop && i < Py_SIZE(self); i++) { + int cmp = PyObject_RichCompareBool(self->ob_item[i], v, Py_EQ); + if (cmp > 0) + return PyLong_FromSsize_t(i); + else if (cmp < 0) + return NULL; + } + if (err_format == NULL) { + err_format = PyUnicode_FromString("%r is not in list"); + if (err_format == NULL) + return NULL; + } + format_tuple = PyTuple_Pack(1, v); + if (format_tuple == NULL) + return NULL; + err_string = PyUnicode_Format(err_format, format_tuple); + Py_DECREF(format_tuple); + if (err_string == NULL) + return NULL; + PyErr_SetObject(PyExc_ValueError, err_string); + Py_DECREF(err_string); + return NULL; } static PyObject * listcount(PyListObject *self, PyObject *v) { - Py_ssize_t count = 0; - Py_ssize_t i; + Py_ssize_t count = 0; + Py_ssize_t i; - for (i = 0; i < Py_SIZE(self); i++) { - int cmp = PyObject_RichCompareBool(self->ob_item[i], v, Py_EQ); - if (cmp > 0) - count++; - else if (cmp < 0) - return NULL; - } - return PyLong_FromSsize_t(count); + for (i = 0; i < Py_SIZE(self); i++) { + int cmp = PyObject_RichCompareBool(self->ob_item[i], v, Py_EQ); + if (cmp > 0) + count++; + else if (cmp < 0) + return NULL; + } + return PyLong_FromSsize_t(count); } static PyObject * listremove(PyListObject *self, PyObject *v) { - Py_ssize_t i; + Py_ssize_t i; - for (i = 0; i < Py_SIZE(self); i++) { - int cmp = PyObject_RichCompareBool(self->ob_item[i], v, Py_EQ); - if (cmp > 0) { - if (list_ass_slice(self, i, i+1, - (PyObject *)NULL) == 0) - Py_RETURN_NONE; - return NULL; - } - else if (cmp < 0) - return NULL; - } - PyErr_SetString(PyExc_ValueError, "list.remove(x): x not in list"); - return NULL; + for (i = 0; i < Py_SIZE(self); i++) { + int cmp = PyObject_RichCompareBool(self->ob_item[i], v, Py_EQ); + if (cmp > 0) { + if (list_ass_slice(self, i, i+1, + (PyObject *)NULL) == 0) + Py_RETURN_NONE; + return NULL; + } + else if (cmp < 0) + return NULL; + } + PyErr_SetString(PyExc_ValueError, "list.remove(x): x not in list"); + return NULL; } static int list_traverse(PyListObject *o, visitproc visit, void *arg) { - Py_ssize_t i; + Py_ssize_t i; - for (i = Py_SIZE(o); --i >= 0; ) - Py_VISIT(o->ob_item[i]); - return 0; + for (i = Py_SIZE(o); --i >= 0; ) + Py_VISIT(o->ob_item[i]); + return 0; } static PyObject * list_richcompare(PyObject *v, PyObject *w, int op) { - PyListObject *vl, *wl; - Py_ssize_t i; + PyListObject *vl, *wl; + Py_ssize_t i; - if (!PyList_Check(v) || !PyList_Check(w)) { - Py_INCREF(Py_NotImplemented); - return Py_NotImplemented; - } - - vl = (PyListObject *)v; - wl = (PyListObject *)w; - - if (Py_SIZE(vl) != Py_SIZE(wl) && (op == Py_EQ || op == Py_NE)) { - /* Shortcut: if the lengths differ, the lists differ */ - PyObject *res; - if (op == Py_EQ) - res = Py_False; - else - res = Py_True; - Py_INCREF(res); - return res; - } - - /* Search for the first index where items are different */ - for (i = 0; i < Py_SIZE(vl) && i < Py_SIZE(wl); i++) { - int k = PyObject_RichCompareBool(vl->ob_item[i], - wl->ob_item[i], Py_EQ); - if (k < 0) - return NULL; - if (!k) - break; - } - - if (i >= Py_SIZE(vl) || i >= Py_SIZE(wl)) { - /* No more items to compare -- compare sizes */ - Py_ssize_t vs = Py_SIZE(vl); - Py_ssize_t ws = Py_SIZE(wl); - int cmp; - PyObject *res; - switch (op) { - case Py_LT: cmp = vs < ws; break; - case Py_LE: cmp = vs <= ws; break; - case Py_EQ: cmp = vs == ws; break; - case Py_NE: cmp = vs != ws; break; - case Py_GT: cmp = vs > ws; break; - case Py_GE: cmp = vs >= ws; break; - default: return NULL; /* cannot happen */ - } - if (cmp) - res = Py_True; - else - res = Py_False; - Py_INCREF(res); - return res; - } - - /* We have an item that differs -- shortcuts for EQ/NE */ - if (op == Py_EQ) { - Py_INCREF(Py_False); - return Py_False; - } - if (op == Py_NE) { - Py_INCREF(Py_True); - return Py_True; - } + if (!PyList_Check(v) || !PyList_Check(w)) { + Py_INCREF(Py_NotImplemented); + return Py_NotImplemented; + } + + vl = (PyListObject *)v; + wl = (PyListObject *)w; + + if (Py_SIZE(vl) != Py_SIZE(wl) && (op == Py_EQ || op == Py_NE)) { + /* Shortcut: if the lengths differ, the lists differ */ + PyObject *res; + if (op == Py_EQ) + res = Py_False; + else + res = Py_True; + Py_INCREF(res); + return res; + } + + /* Search for the first index where items are different */ + for (i = 0; i < Py_SIZE(vl) && i < Py_SIZE(wl); i++) { + int k = PyObject_RichCompareBool(vl->ob_item[i], + wl->ob_item[i], Py_EQ); + if (k < 0) + return NULL; + if (!k) + break; + } + + if (i >= Py_SIZE(vl) || i >= Py_SIZE(wl)) { + /* No more items to compare -- compare sizes */ + Py_ssize_t vs = Py_SIZE(vl); + Py_ssize_t ws = Py_SIZE(wl); + int cmp; + PyObject *res; + switch (op) { + case Py_LT: cmp = vs < ws; break; + case Py_LE: cmp = vs <= ws; break; + case Py_EQ: cmp = vs == ws; break; + case Py_NE: cmp = vs != ws; break; + case Py_GT: cmp = vs > ws; break; + case Py_GE: cmp = vs >= ws; break; + default: return NULL; /* cannot happen */ + } + if (cmp) + res = Py_True; + else + res = Py_False; + Py_INCREF(res); + return res; + } + + /* We have an item that differs -- shortcuts for EQ/NE */ + if (op == Py_EQ) { + Py_INCREF(Py_False); + return Py_False; + } + if (op == Py_NE) { + Py_INCREF(Py_True); + return Py_True; + } - /* Compare the final item again using the proper operator */ - return PyObject_RichCompare(vl->ob_item[i], wl->ob_item[i], op); + /* Compare the final item again using the proper operator */ + return PyObject_RichCompare(vl->ob_item[i], wl->ob_item[i], op); } static int list_init(PyListObject *self, PyObject *args, PyObject *kw) { - PyObject *arg = NULL; - static char *kwlist[] = {"sequence", 0}; + PyObject *arg = NULL; + static char *kwlist[] = {"sequence", 0}; - if (!PyArg_ParseTupleAndKeywords(args, kw, "|O:list", kwlist, &arg)) - return -1; + if (!PyArg_ParseTupleAndKeywords(args, kw, "|O:list", kwlist, &arg)) + return -1; - /* Verify list invariants established by PyType_GenericAlloc() */ - assert(0 <= Py_SIZE(self)); - assert(Py_SIZE(self) <= self->allocated || self->allocated == -1); - assert(self->ob_item != NULL || - self->allocated == 0 || self->allocated == -1); - - /* Empty previous contents */ - if (self->ob_item != NULL) { - (void)list_clear(self); - } - if (arg != NULL) { - PyObject *rv = listextend(self, arg); - if (rv == NULL) - return -1; - Py_DECREF(rv); - } - return 0; + /* Verify list invariants established by PyType_GenericAlloc() */ + assert(0 <= Py_SIZE(self)); + assert(Py_SIZE(self) <= self->allocated || self->allocated == -1); + assert(self->ob_item != NULL || + self->allocated == 0 || self->allocated == -1); + + /* Empty previous contents */ + if (self->ob_item != NULL) { + (void)list_clear(self); + } + if (arg != NULL) { + PyObject *rv = listextend(self, arg); + if (rv == NULL) + return -1; + Py_DECREF(rv); + } + return 0; } static PyObject * list_sizeof(PyListObject *self) { - Py_ssize_t res; + Py_ssize_t res; - res = sizeof(PyListObject) + self->allocated * sizeof(void*); - return PyLong_FromSsize_t(res); + res = sizeof(PyListObject) + self->allocated * sizeof(void*); + return PyLong_FromSsize_t(res); } static PyObject *list_iter(PyObject *seq); @@ -2328,32 +2328,32 @@ static PyObject *list_subscript(PyListObject*, PyObject*); static PyMethodDef list_methods[] = { - {"__getitem__", (PyCFunction)list_subscript, METH_O|METH_COEXIST, getitem_doc}, - {"__reversed__",(PyCFunction)list_reversed, METH_NOARGS, reversed_doc}, - {"__sizeof__", (PyCFunction)list_sizeof, METH_NOARGS, sizeof_doc}, - {"append", (PyCFunction)listappend, METH_O, append_doc}, - {"insert", (PyCFunction)listinsert, METH_VARARGS, insert_doc}, - {"extend", (PyCFunction)listextend, METH_O, extend_doc}, - {"pop", (PyCFunction)listpop, METH_VARARGS, pop_doc}, - {"remove", (PyCFunction)listremove, METH_O, remove_doc}, - {"index", (PyCFunction)listindex, METH_VARARGS, index_doc}, - {"count", (PyCFunction)listcount, METH_O, count_doc}, - {"reverse", (PyCFunction)listreverse, METH_NOARGS, reverse_doc}, - {"sort", (PyCFunction)listsort, METH_VARARGS | METH_KEYWORDS, sort_doc}, - {NULL, NULL} /* sentinel */ + {"__getitem__", (PyCFunction)list_subscript, METH_O|METH_COEXIST, getitem_doc}, + {"__reversed__",(PyCFunction)list_reversed, METH_NOARGS, reversed_doc}, + {"__sizeof__", (PyCFunction)list_sizeof, METH_NOARGS, sizeof_doc}, + {"append", (PyCFunction)listappend, METH_O, append_doc}, + {"insert", (PyCFunction)listinsert, METH_VARARGS, insert_doc}, + {"extend", (PyCFunction)listextend, METH_O, extend_doc}, + {"pop", (PyCFunction)listpop, METH_VARARGS, pop_doc}, + {"remove", (PyCFunction)listremove, METH_O, remove_doc}, + {"index", (PyCFunction)listindex, METH_VARARGS, index_doc}, + {"count", (PyCFunction)listcount, METH_O, count_doc}, + {"reverse", (PyCFunction)listreverse, METH_NOARGS, reverse_doc}, + {"sort", (PyCFunction)listsort, METH_VARARGS | METH_KEYWORDS, sort_doc}, + {NULL, NULL} /* sentinel */ }; static PySequenceMethods list_as_sequence = { - (lenfunc)list_length, /* sq_length */ - (binaryfunc)list_concat, /* sq_concat */ - (ssizeargfunc)list_repeat, /* sq_repeat */ - (ssizeargfunc)list_item, /* sq_item */ - 0, /* sq_slice */ - (ssizeobjargproc)list_ass_item, /* sq_ass_item */ - 0, /* sq_ass_slice */ - (objobjproc)list_contains, /* sq_contains */ - (binaryfunc)list_inplace_concat, /* sq_inplace_concat */ - (ssizeargfunc)list_inplace_repeat, /* sq_inplace_repeat */ + (lenfunc)list_length, /* sq_length */ + (binaryfunc)list_concat, /* sq_concat */ + (ssizeargfunc)list_repeat, /* sq_repeat */ + (ssizeargfunc)list_item, /* sq_item */ + 0, /* sq_slice */ + (ssizeobjargproc)list_ass_item, /* sq_ass_item */ + 0, /* sq_ass_slice */ + (objobjproc)list_contains, /* sq_contains */ + (binaryfunc)list_inplace_concat, /* sq_inplace_concat */ + (ssizeargfunc)list_inplace_repeat, /* sq_inplace_repeat */ }; PyDoc_STRVAR(list_doc, @@ -2363,275 +2363,275 @@ static PyObject * list_subscript(PyListObject* self, PyObject* item) { - if (PyIndex_Check(item)) { - Py_ssize_t i; - i = PyNumber_AsSsize_t(item, PyExc_IndexError); - if (i == -1 && PyErr_Occurred()) - return NULL; - if (i < 0) - i += PyList_GET_SIZE(self); - return list_item(self, i); - } - else if (PySlice_Check(item)) { - Py_ssize_t start, stop, step, slicelength, cur, i; - PyObject* result; - PyObject* it; - PyObject **src, **dest; - - if (PySlice_GetIndicesEx((PySliceObject*)item, Py_SIZE(self), - &start, &stop, &step, &slicelength) < 0) { - return NULL; - } - - if (slicelength <= 0) { - return PyList_New(0); - } - else if (step == 1) { - return list_slice(self, start, stop); - } - else { - result = PyList_New(slicelength); - if (!result) return NULL; - - src = self->ob_item; - dest = ((PyListObject *)result)->ob_item; - for (cur = start, i = 0; i < slicelength; - cur += step, i++) { - it = src[cur]; - Py_INCREF(it); - dest[i] = it; - } - - return result; - } - } - else { - PyErr_Format(PyExc_TypeError, - "list indices must be integers, not %.200s", - item->ob_type->tp_name); - return NULL; - } + if (PyIndex_Check(item)) { + Py_ssize_t i; + i = PyNumber_AsSsize_t(item, PyExc_IndexError); + if (i == -1 && PyErr_Occurred()) + return NULL; + if (i < 0) + i += PyList_GET_SIZE(self); + return list_item(self, i); + } + else if (PySlice_Check(item)) { + Py_ssize_t start, stop, step, slicelength, cur, i; + PyObject* result; + PyObject* it; + PyObject **src, **dest; + + if (PySlice_GetIndicesEx((PySliceObject*)item, Py_SIZE(self), + &start, &stop, &step, &slicelength) < 0) { + return NULL; + } + + if (slicelength <= 0) { + return PyList_New(0); + } + else if (step == 1) { + return list_slice(self, start, stop); + } + else { + result = PyList_New(slicelength); + if (!result) return NULL; + + src = self->ob_item; + dest = ((PyListObject *)result)->ob_item; + for (cur = start, i = 0; i < slicelength; + cur += step, i++) { + it = src[cur]; + Py_INCREF(it); + dest[i] = it; + } + + return result; + } + } + else { + PyErr_Format(PyExc_TypeError, + "list indices must be integers, not %.200s", + item->ob_type->tp_name); + return NULL; + } } static int list_ass_subscript(PyListObject* self, PyObject* item, PyObject* value) { - if (PyIndex_Check(item)) { - Py_ssize_t i = PyNumber_AsSsize_t(item, PyExc_IndexError); - if (i == -1 && PyErr_Occurred()) - return -1; - if (i < 0) - i += PyList_GET_SIZE(self); - return list_ass_item(self, i, value); - } - else if (PySlice_Check(item)) { - Py_ssize_t start, stop, step, slicelength; - - if (PySlice_GetIndicesEx((PySliceObject*)item, Py_SIZE(self), - &start, &stop, &step, &slicelength) < 0) { - return -1; - } - - if (step == 1) - return list_ass_slice(self, start, stop, value); - - /* Make sure s[5:2] = [..] inserts at the right place: - before 5, not before 2. */ - if ((step < 0 && start < stop) || - (step > 0 && start > stop)) - stop = start; - - if (value == NULL) { - /* delete slice */ - PyObject **garbage; - size_t cur; - Py_ssize_t i; - - if (slicelength <= 0) - return 0; - - if (step < 0) { - stop = start + 1; - start = stop + step*(slicelength - 1) - 1; - step = -step; - } - - assert((size_t)slicelength <= - PY_SIZE_MAX / sizeof(PyObject*)); - - garbage = (PyObject**) - PyMem_MALLOC(slicelength*sizeof(PyObject*)); - if (!garbage) { - PyErr_NoMemory(); - return -1; - } - - /* drawing pictures might help understand these for - loops. Basically, we memmove the parts of the - list that are *not* part of the slice: step-1 - items for each item that is part of the slice, - and then tail end of the list that was not - covered by the slice */ - for (cur = start, i = 0; - cur < (size_t)stop; - cur += step, i++) { - Py_ssize_t lim = step - 1; - - garbage[i] = PyList_GET_ITEM(self, cur); - - if (cur + step >= (size_t)Py_SIZE(self)) { - lim = Py_SIZE(self) - cur - 1; - } - - memmove(self->ob_item + cur - i, - self->ob_item + cur + 1, - lim * sizeof(PyObject *)); - } - cur = start + slicelength*step; - if (cur < (size_t)Py_SIZE(self)) { - memmove(self->ob_item + cur - slicelength, - self->ob_item + cur, - (Py_SIZE(self) - cur) * - sizeof(PyObject *)); - } - - Py_SIZE(self) -= slicelength; - list_resize(self, Py_SIZE(self)); - - for (i = 0; i < slicelength; i++) { - Py_DECREF(garbage[i]); - } - PyMem_FREE(garbage); - - return 0; - } - else { - /* assign slice */ - PyObject *ins, *seq; - PyObject **garbage, **seqitems, **selfitems; - Py_ssize_t cur, i; - - /* protect against a[::-1] = a */ - if (self == (PyListObject*)value) { - seq = list_slice((PyListObject*)value, 0, - PyList_GET_SIZE(value)); - } - else { - seq = PySequence_Fast(value, - "must assign iterable " - "to extended slice"); - } - if (!seq) - return -1; - - if (PySequence_Fast_GET_SIZE(seq) != slicelength) { - PyErr_Format(PyExc_ValueError, - "attempt to assign sequence of " - "size %zd to extended slice of " - "size %zd", - PySequence_Fast_GET_SIZE(seq), - slicelength); - Py_DECREF(seq); - return -1; - } - - if (!slicelength) { - Py_DECREF(seq); - return 0; - } - - garbage = (PyObject**) - PyMem_MALLOC(slicelength*sizeof(PyObject*)); - if (!garbage) { - Py_DECREF(seq); - PyErr_NoMemory(); - return -1; - } - - selfitems = self->ob_item; - seqitems = PySequence_Fast_ITEMS(seq); - for (cur = start, i = 0; i < slicelength; - cur += step, i++) { - garbage[i] = selfitems[cur]; - ins = seqitems[i]; - Py_INCREF(ins); - selfitems[cur] = ins; - } - - for (i = 0; i < slicelength; i++) { - Py_DECREF(garbage[i]); - } - - PyMem_FREE(garbage); - Py_DECREF(seq); - - return 0; - } - } - else { - PyErr_Format(PyExc_TypeError, - "list indices must be integers, not %.200s", - item->ob_type->tp_name); - return -1; - } + if (PyIndex_Check(item)) { + Py_ssize_t i = PyNumber_AsSsize_t(item, PyExc_IndexError); + if (i == -1 && PyErr_Occurred()) + return -1; + if (i < 0) + i += PyList_GET_SIZE(self); + return list_ass_item(self, i, value); + } + else if (PySlice_Check(item)) { + Py_ssize_t start, stop, step, slicelength; + + if (PySlice_GetIndicesEx((PySliceObject*)item, Py_SIZE(self), + &start, &stop, &step, &slicelength) < 0) { + return -1; + } + + if (step == 1) + return list_ass_slice(self, start, stop, value); + + /* Make sure s[5:2] = [..] inserts at the right place: + before 5, not before 2. */ + if ((step < 0 && start < stop) || + (step > 0 && start > stop)) + stop = start; + + if (value == NULL) { + /* delete slice */ + PyObject **garbage; + size_t cur; + Py_ssize_t i; + + if (slicelength <= 0) + return 0; + + if (step < 0) { + stop = start + 1; + start = stop + step*(slicelength - 1) - 1; + step = -step; + } + + assert((size_t)slicelength <= + PY_SIZE_MAX / sizeof(PyObject*)); + + garbage = (PyObject**) + PyMem_MALLOC(slicelength*sizeof(PyObject*)); + if (!garbage) { + PyErr_NoMemory(); + return -1; + } + + /* drawing pictures might help understand these for + loops. Basically, we memmove the parts of the + list that are *not* part of the slice: step-1 + items for each item that is part of the slice, + and then tail end of the list that was not + covered by the slice */ + for (cur = start, i = 0; + cur < (size_t)stop; + cur += step, i++) { + Py_ssize_t lim = step - 1; + + garbage[i] = PyList_GET_ITEM(self, cur); + + if (cur + step >= (size_t)Py_SIZE(self)) { + lim = Py_SIZE(self) - cur - 1; + } + + memmove(self->ob_item + cur - i, + self->ob_item + cur + 1, + lim * sizeof(PyObject *)); + } + cur = start + slicelength*step; + if (cur < (size_t)Py_SIZE(self)) { + memmove(self->ob_item + cur - slicelength, + self->ob_item + cur, + (Py_SIZE(self) - cur) * + sizeof(PyObject *)); + } + + Py_SIZE(self) -= slicelength; + list_resize(self, Py_SIZE(self)); + + for (i = 0; i < slicelength; i++) { + Py_DECREF(garbage[i]); + } + PyMem_FREE(garbage); + + return 0; + } + else { + /* assign slice */ + PyObject *ins, *seq; + PyObject **garbage, **seqitems, **selfitems; + Py_ssize_t cur, i; + + /* protect against a[::-1] = a */ + if (self == (PyListObject*)value) { + seq = list_slice((PyListObject*)value, 0, + PyList_GET_SIZE(value)); + } + else { + seq = PySequence_Fast(value, + "must assign iterable " + "to extended slice"); + } + if (!seq) + return -1; + + if (PySequence_Fast_GET_SIZE(seq) != slicelength) { + PyErr_Format(PyExc_ValueError, + "attempt to assign sequence of " + "size %zd to extended slice of " + "size %zd", + PySequence_Fast_GET_SIZE(seq), + slicelength); + Py_DECREF(seq); + return -1; + } + + if (!slicelength) { + Py_DECREF(seq); + return 0; + } + + garbage = (PyObject**) + PyMem_MALLOC(slicelength*sizeof(PyObject*)); + if (!garbage) { + Py_DECREF(seq); + PyErr_NoMemory(); + return -1; + } + + selfitems = self->ob_item; + seqitems = PySequence_Fast_ITEMS(seq); + for (cur = start, i = 0; i < slicelength; + cur += step, i++) { + garbage[i] = selfitems[cur]; + ins = seqitems[i]; + Py_INCREF(ins); + selfitems[cur] = ins; + } + + for (i = 0; i < slicelength; i++) { + Py_DECREF(garbage[i]); + } + + PyMem_FREE(garbage); + Py_DECREF(seq); + + return 0; + } + } + else { + PyErr_Format(PyExc_TypeError, + "list indices must be integers, not %.200s", + item->ob_type->tp_name); + return -1; + } } static PyMappingMethods list_as_mapping = { - (lenfunc)list_length, - (binaryfunc)list_subscript, - (objobjargproc)list_ass_subscript + (lenfunc)list_length, + (binaryfunc)list_subscript, + (objobjargproc)list_ass_subscript }; PyTypeObject PyList_Type = { - PyVarObject_HEAD_INIT(&PyType_Type, 0) - "list", - sizeof(PyListObject), - 0, - (destructor)list_dealloc, /* tp_dealloc */ - 0, /* tp_print */ - 0, /* tp_getattr */ - 0, /* tp_setattr */ - 0, /* tp_reserved */ - (reprfunc)list_repr, /* tp_repr */ - 0, /* tp_as_number */ - &list_as_sequence, /* tp_as_sequence */ - &list_as_mapping, /* tp_as_mapping */ - (hashfunc)PyObject_HashNotImplemented, /* 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 | - Py_TPFLAGS_BASETYPE | Py_TPFLAGS_LIST_SUBCLASS, /* tp_flags */ - list_doc, /* tp_doc */ - (traverseproc)list_traverse, /* tp_traverse */ - (inquiry)list_clear, /* tp_clear */ - list_richcompare, /* tp_richcompare */ - 0, /* tp_weaklistoffset */ - list_iter, /* tp_iter */ - 0, /* tp_iternext */ - list_methods, /* tp_methods */ - 0, /* tp_members */ - 0, /* tp_getset */ - 0, /* tp_base */ - 0, /* tp_dict */ - 0, /* tp_descr_get */ - 0, /* tp_descr_set */ - 0, /* tp_dictoffset */ - (initproc)list_init, /* tp_init */ - PyType_GenericAlloc, /* tp_alloc */ - PyType_GenericNew, /* tp_new */ - PyObject_GC_Del, /* tp_free */ + PyVarObject_HEAD_INIT(&PyType_Type, 0) + "list", + sizeof(PyListObject), + 0, + (destructor)list_dealloc, /* tp_dealloc */ + 0, /* tp_print */ + 0, /* tp_getattr */ + 0, /* tp_setattr */ + 0, /* tp_reserved */ + (reprfunc)list_repr, /* tp_repr */ + 0, /* tp_as_number */ + &list_as_sequence, /* tp_as_sequence */ + &list_as_mapping, /* tp_as_mapping */ + (hashfunc)PyObject_HashNotImplemented, /* 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 | + Py_TPFLAGS_BASETYPE | Py_TPFLAGS_LIST_SUBCLASS, /* tp_flags */ + list_doc, /* tp_doc */ + (traverseproc)list_traverse, /* tp_traverse */ + (inquiry)list_clear, /* tp_clear */ + list_richcompare, /* tp_richcompare */ + 0, /* tp_weaklistoffset */ + list_iter, /* tp_iter */ + 0, /* tp_iternext */ + list_methods, /* tp_methods */ + 0, /* tp_members */ + 0, /* tp_getset */ + 0, /* tp_base */ + 0, /* tp_dict */ + 0, /* tp_descr_get */ + 0, /* tp_descr_set */ + 0, /* tp_dictoffset */ + (initproc)list_init, /* tp_init */ + PyType_GenericAlloc, /* tp_alloc */ + PyType_GenericNew, /* tp_new */ + PyObject_GC_Del, /* tp_free */ }; /*********************** List Iterator **************************/ typedef struct { - PyObject_HEAD - long it_index; - PyListObject *it_seq; /* Set to NULL when iterator is exhausted */ + PyObject_HEAD + long it_index; + PyListObject *it_seq; /* Set to NULL when iterator is exhausted */ } listiterobject; static PyObject *list_iter(PyObject *); @@ -2643,119 +2643,119 @@ PyDoc_STRVAR(length_hint_doc, "Private method returning an estimate of len(list(it))."); static PyMethodDef listiter_methods[] = { - {"__length_hint__", (PyCFunction)listiter_len, METH_NOARGS, length_hint_doc}, - {NULL, NULL} /* sentinel */ + {"__length_hint__", (PyCFunction)listiter_len, METH_NOARGS, length_hint_doc}, + {NULL, NULL} /* sentinel */ }; PyTypeObject PyListIter_Type = { - PyVarObject_HEAD_INIT(&PyType_Type, 0) - "list_iterator", /* tp_name */ - sizeof(listiterobject), /* tp_basicsize */ - 0, /* tp_itemsize */ - /* methods */ - (destructor)listiter_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)listiter_traverse, /* tp_traverse */ - 0, /* tp_clear */ - 0, /* tp_richcompare */ - 0, /* tp_weaklistoffset */ - PyObject_SelfIter, /* tp_iter */ - (iternextfunc)listiter_next, /* tp_iternext */ - listiter_methods, /* tp_methods */ - 0, /* tp_members */ + PyVarObject_HEAD_INIT(&PyType_Type, 0) + "list_iterator", /* tp_name */ + sizeof(listiterobject), /* tp_basicsize */ + 0, /* tp_itemsize */ + /* methods */ + (destructor)listiter_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)listiter_traverse, /* tp_traverse */ + 0, /* tp_clear */ + 0, /* tp_richcompare */ + 0, /* tp_weaklistoffset */ + PyObject_SelfIter, /* tp_iter */ + (iternextfunc)listiter_next, /* tp_iternext */ + listiter_methods, /* tp_methods */ + 0, /* tp_members */ }; static PyObject * list_iter(PyObject *seq) { - listiterobject *it; + listiterobject *it; - if (!PyList_Check(seq)) { - PyErr_BadInternalCall(); - return NULL; - } - it = PyObject_GC_New(listiterobject, &PyListIter_Type); - if (it == NULL) - return NULL; - it->it_index = 0; - Py_INCREF(seq); - it->it_seq = (PyListObject *)seq; - _PyObject_GC_TRACK(it); - return (PyObject *)it; + if (!PyList_Check(seq)) { + PyErr_BadInternalCall(); + return NULL; + } + it = PyObject_GC_New(listiterobject, &PyListIter_Type); + if (it == NULL) + return NULL; + it->it_index = 0; + Py_INCREF(seq); + it->it_seq = (PyListObject *)seq; + _PyObject_GC_TRACK(it); + return (PyObject *)it; } static void listiter_dealloc(listiterobject *it) { - _PyObject_GC_UNTRACK(it); - Py_XDECREF(it->it_seq); - PyObject_GC_Del(it); + _PyObject_GC_UNTRACK(it); + Py_XDECREF(it->it_seq); + PyObject_GC_Del(it); } static int listiter_traverse(listiterobject *it, visitproc visit, void *arg) { - Py_VISIT(it->it_seq); - return 0; + Py_VISIT(it->it_seq); + return 0; } static PyObject * listiter_next(listiterobject *it) { - PyListObject *seq; - PyObject *item; + PyListObject *seq; + PyObject *item; - assert(it != NULL); - seq = it->it_seq; - if (seq == NULL) - return NULL; - assert(PyList_Check(seq)); - - if (it->it_index < PyList_GET_SIZE(seq)) { - item = PyList_GET_ITEM(seq, it->it_index); - ++it->it_index; - Py_INCREF(item); - return item; - } - - Py_DECREF(seq); - it->it_seq = NULL; - return NULL; + assert(it != NULL); + seq = it->it_seq; + if (seq == NULL) + return NULL; + assert(PyList_Check(seq)); + + if (it->it_index < PyList_GET_SIZE(seq)) { + item = PyList_GET_ITEM(seq, it->it_index); + ++it->it_index; + Py_INCREF(item); + return item; + } + + Py_DECREF(seq); + it->it_seq = NULL; + return NULL; } static PyObject * listiter_len(listiterobject *it) { - Py_ssize_t len; - if (it->it_seq) { - len = PyList_GET_SIZE(it->it_seq) - it->it_index; - if (len >= 0) - return PyLong_FromSsize_t(len); - } - return PyLong_FromLong(0); + Py_ssize_t len; + if (it->it_seq) { + len = PyList_GET_SIZE(it->it_seq) - it->it_index; + if (len >= 0) + return PyLong_FromSsize_t(len); + } + return PyLong_FromLong(0); } /*********************** List Reverse Iterator **************************/ typedef struct { - PyObject_HEAD - Py_ssize_t it_index; - PyListObject *it_seq; /* Set to NULL when iterator is exhausted */ + PyObject_HEAD + Py_ssize_t it_index; + PyListObject *it_seq; /* Set to NULL when iterator is exhausted */ } listreviterobject; static PyObject *list_reversed(PyListObject *, PyObject *); @@ -2765,101 +2765,101 @@ static PyObject *listreviter_len(listreviterobject *); static PyMethodDef listreviter_methods[] = { - {"__length_hint__", (PyCFunction)listreviter_len, METH_NOARGS, length_hint_doc}, - {NULL, NULL} /* sentinel */ + {"__length_hint__", (PyCFunction)listreviter_len, METH_NOARGS, length_hint_doc}, + {NULL, NULL} /* sentinel */ }; PyTypeObject PyListRevIter_Type = { - PyVarObject_HEAD_INIT(&PyType_Type, 0) - "list_reverseiterator", /* tp_name */ - sizeof(listreviterobject), /* tp_basicsize */ - 0, /* tp_itemsize */ - /* methods */ - (destructor)listreviter_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)listreviter_traverse, /* tp_traverse */ - 0, /* tp_clear */ - 0, /* tp_richcompare */ - 0, /* tp_weaklistoffset */ - PyObject_SelfIter, /* tp_iter */ - (iternextfunc)listreviter_next, /* tp_iternext */ - listreviter_methods, /* tp_methods */ - 0, + PyVarObject_HEAD_INIT(&PyType_Type, 0) + "list_reverseiterator", /* tp_name */ + sizeof(listreviterobject), /* tp_basicsize */ + 0, /* tp_itemsize */ + /* methods */ + (destructor)listreviter_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)listreviter_traverse, /* tp_traverse */ + 0, /* tp_clear */ + 0, /* tp_richcompare */ + 0, /* tp_weaklistoffset */ + PyObject_SelfIter, /* tp_iter */ + (iternextfunc)listreviter_next, /* tp_iternext */ + listreviter_methods, /* tp_methods */ + 0, }; static PyObject * list_reversed(PyListObject *seq, PyObject *unused) { - listreviterobject *it; + listreviterobject *it; - it = PyObject_GC_New(listreviterobject, &PyListRevIter_Type); - if (it == NULL) - return NULL; - assert(PyList_Check(seq)); - it->it_index = PyList_GET_SIZE(seq) - 1; - Py_INCREF(seq); - it->it_seq = seq; - PyObject_GC_Track(it); - return (PyObject *)it; + it = PyObject_GC_New(listreviterobject, &PyListRevIter_Type); + if (it == NULL) + return NULL; + assert(PyList_Check(seq)); + it->it_index = PyList_GET_SIZE(seq) - 1; + Py_INCREF(seq); + it->it_seq = seq; + PyObject_GC_Track(it); + return (PyObject *)it; } static void listreviter_dealloc(listreviterobject *it) { - PyObject_GC_UnTrack(it); - Py_XDECREF(it->it_seq); - PyObject_GC_Del(it); + PyObject_GC_UnTrack(it); + Py_XDECREF(it->it_seq); + PyObject_GC_Del(it); } static int listreviter_traverse(listreviterobject *it, visitproc visit, void *arg) { - Py_VISIT(it->it_seq); - return 0; + Py_VISIT(it->it_seq); + return 0; } static PyObject * listreviter_next(listreviterobject *it) { - PyObject *item; - Py_ssize_t index = it->it_index; - PyListObject *seq = it->it_seq; - - if (index>=0 && index < PyList_GET_SIZE(seq)) { - item = PyList_GET_ITEM(seq, index); - it->it_index--; - Py_INCREF(item); - return item; - } - it->it_index = -1; - if (seq != NULL) { - it->it_seq = NULL; - Py_DECREF(seq); - } - return NULL; + PyObject *item; + Py_ssize_t index = it->it_index; + PyListObject *seq = it->it_seq; + + if (index>=0 && index < PyList_GET_SIZE(seq)) { + item = PyList_GET_ITEM(seq, index); + it->it_index--; + Py_INCREF(item); + return item; + } + it->it_index = -1; + if (seq != NULL) { + it->it_seq = NULL; + Py_DECREF(seq); + } + return NULL; } static PyObject * listreviter_len(listreviterobject *it) { - Py_ssize_t len = it->it_index + 1; - if (it->it_seq == NULL || PyList_GET_SIZE(it->it_seq) < len) - len = 0; - return PyLong_FromSsize_t(len); + Py_ssize_t len = it->it_index + 1; + if (it->it_seq == NULL || PyList_GET_SIZE(it->it_seq) < len) + len = 0; + return PyLong_FromSsize_t(len); } Modified: python/branches/py3k-jit/Objects/longobject.c ============================================================================== --- python/branches/py3k-jit/Objects/longobject.c (original) +++ python/branches/py3k-jit/Objects/longobject.c Mon May 10 23:55:43 2010 @@ -11,16 +11,16 @@ #include #ifndef NSMALLPOSINTS -#define NSMALLPOSINTS 257 +#define NSMALLPOSINTS 257 #endif #ifndef NSMALLNEGINTS -#define NSMALLNEGINTS 5 +#define NSMALLNEGINTS 5 #endif /* convert a PyLong of size 1, 0 or -1 to an sdigit */ -#define MEDIUM_VALUE(x) (Py_SIZE(x) < 0 ? -(sdigit)(x)->ob_digit[0] : \ - (Py_SIZE(x) == 0 ? (sdigit)0 : \ - (sdigit)(x)->ob_digit[0])) +#define MEDIUM_VALUE(x) (Py_SIZE(x) < 0 ? -(sdigit)(x)->ob_digit[0] : \ + (Py_SIZE(x) == 0 ? (sdigit)0 : \ + (sdigit)(x)->ob_digit[0])) #define ABS(x) ((x) < 0 ? -(x) : (x)) #if NSMALLNEGINTS + NSMALLPOSINTS > 0 @@ -37,32 +37,32 @@ static PyObject * get_small_int(sdigit ival) { - PyObject *v = (PyObject*)(small_ints + ival + NSMALLNEGINTS); - Py_INCREF(v); + PyObject *v = (PyObject*)(small_ints + ival + NSMALLNEGINTS); + Py_INCREF(v); #ifdef COUNT_ALLOCS - if (ival >= 0) - quick_int_allocs++; - else - quick_neg_int_allocs++; + if (ival >= 0) + quick_int_allocs++; + else + quick_neg_int_allocs++; #endif - return v; + return v; } #define CHECK_SMALL_INT(ival) \ - do if (-NSMALLNEGINTS <= ival && ival < NSMALLPOSINTS) { \ - return get_small_int((sdigit)ival); \ - } while(0) + do if (-NSMALLNEGINTS <= ival && ival < NSMALLPOSINTS) { \ + return get_small_int((sdigit)ival); \ + } while(0) -static PyLongObject * +static PyLongObject * maybe_small_long(PyLongObject *v) { - if (v && ABS(Py_SIZE(v)) <= 1) { - sdigit ival = MEDIUM_VALUE(v); - if (-NSMALLNEGINTS <= ival && ival < NSMALLPOSINTS) { - Py_DECREF(v); - return (PyLongObject *)get_small_int(ival); - } - } - return v; + if (v && ABS(Py_SIZE(v)) <= 1) { + sdigit ival = MEDIUM_VALUE(v); + if (-NSMALLNEGINTS <= ival && ival < NSMALLPOSINTS) { + Py_DECREF(v); + return (PyLongObject *)get_small_int(ival); + } + } + return v; } #else #define CHECK_SMALL_INT(ival) @@ -72,10 +72,10 @@ /* If a freshly-allocated long is already shared, it must be a small integer, so negating it must go to PyLong_FromLong */ #define NEGATE(x) \ - do if (Py_REFCNT(x) == 1) Py_SIZE(x) = -Py_SIZE(x); \ - else { PyObject* tmp=PyLong_FromLong(-MEDIUM_VALUE(x)); \ - Py_DECREF(x); (x) = (PyLongObject*)tmp; } \ - while(0) + do if (Py_REFCNT(x) == 1) Py_SIZE(x) = -Py_SIZE(x); \ + else { PyObject* tmp=PyLong_FromLong(-MEDIUM_VALUE(x)); \ + Py_DECREF(x); (x) = (PyLongObject*)tmp; } \ + while(0) /* For long multiplication, use the O(N**2) school algorithm unless * both operands contain more than KARATSUBA_CUTOFF digits (this * being an internal Python long digit, in base BASE). @@ -96,7 +96,7 @@ #define MIN(x, y) ((x) > (y) ? (y) : (x)) #define SIGCHECK(PyTryBlock) \ - if (PyErr_CheckSignals()) PyTryBlock \ + if (PyErr_CheckSignals()) PyTryBlock \ /* Normalize (remove leading zeros from) a long int object. Doesn't attempt to free the storage--in most cases, due to the nature @@ -105,68 +105,68 @@ static PyLongObject * long_normalize(register PyLongObject *v) { - Py_ssize_t j = ABS(Py_SIZE(v)); - Py_ssize_t i = j; + Py_ssize_t j = ABS(Py_SIZE(v)); + Py_ssize_t i = j; - while (i > 0 && v->ob_digit[i-1] == 0) - --i; - if (i != j) - Py_SIZE(v) = (Py_SIZE(v) < 0) ? -(i) : i; - return v; + while (i > 0 && v->ob_digit[i-1] == 0) + --i; + if (i != j) + Py_SIZE(v) = (Py_SIZE(v) < 0) ? -(i) : i; + return v; } /* Allocate a new long int object with size digits. Return NULL and set exception if we run out of memory. */ #define MAX_LONG_DIGITS \ - ((PY_SSIZE_T_MAX - offsetof(PyLongObject, ob_digit))/sizeof(digit)) + ((PY_SSIZE_T_MAX - offsetof(PyLongObject, ob_digit))/sizeof(digit)) PyLongObject * _PyLong_New(Py_ssize_t size) { - PyLongObject *result; - /* Number of bytes needed is: offsetof(PyLongObject, ob_digit) + - sizeof(digit)*size. Previous incarnations of this code used - sizeof(PyVarObject) instead of the offsetof, but this risks being - incorrect in the presence of padding between the PyVarObject header - and the digits. */ - if (size > (Py_ssize_t)MAX_LONG_DIGITS) { - PyErr_SetString(PyExc_OverflowError, - "too many digits in integer"); - return NULL; - } - result = PyObject_MALLOC(offsetof(PyLongObject, ob_digit) + - size*sizeof(digit)); - if (!result) { - PyErr_NoMemory(); - return NULL; - } - return (PyLongObject*)PyObject_INIT_VAR(result, &PyLong_Type, size); + PyLongObject *result; + /* Number of bytes needed is: offsetof(PyLongObject, ob_digit) + + sizeof(digit)*size. Previous incarnations of this code used + sizeof(PyVarObject) instead of the offsetof, but this risks being + incorrect in the presence of padding between the PyVarObject header + and the digits. */ + if (size > (Py_ssize_t)MAX_LONG_DIGITS) { + PyErr_SetString(PyExc_OverflowError, + "too many digits in integer"); + return NULL; + } + result = PyObject_MALLOC(offsetof(PyLongObject, ob_digit) + + size*sizeof(digit)); + if (!result) { + PyErr_NoMemory(); + return NULL; + } + return (PyLongObject*)PyObject_INIT_VAR(result, &PyLong_Type, size); } PyObject * _PyLong_Copy(PyLongObject *src) { - PyLongObject *result; - Py_ssize_t i; + PyLongObject *result; + Py_ssize_t i; - assert(src != NULL); - i = Py_SIZE(src); - if (i < 0) - i = -(i); - if (i < 2) { - sdigit ival = src->ob_digit[0]; - if (Py_SIZE(src) < 0) - ival = -ival; - CHECK_SMALL_INT(ival); - } - result = _PyLong_New(i); - if (result != NULL) { - Py_SIZE(result) = Py_SIZE(src); - while (--i >= 0) - result->ob_digit[i] = src->ob_digit[i]; - } - return (PyObject *)result; + assert(src != NULL); + i = Py_SIZE(src); + if (i < 0) + i = -(i); + if (i < 2) { + sdigit ival = src->ob_digit[0]; + if (Py_SIZE(src) < 0) + ival = -ival; + CHECK_SMALL_INT(ival); + } + result = _PyLong_New(i); + if (result != NULL) { + Py_SIZE(result) = Py_SIZE(src); + while (--i >= 0) + result->ob_digit[i] = src->ob_digit[i]; + } + return (PyObject *)result; } /* Create a new long int object from a C long int */ @@ -174,68 +174,68 @@ PyObject * PyLong_FromLong(long ival) { - PyLongObject *v; - unsigned long abs_ival; - unsigned long t; /* unsigned so >> doesn't propagate sign bit */ - int ndigits = 0; - int sign = 1; - - CHECK_SMALL_INT(ival); - - if (ival < 0) { - /* negate: can't write this as abs_ival = -ival since that - invokes undefined behaviour when ival is LONG_MIN */ - abs_ival = 0U-(unsigned long)ival; - sign = -1; - } - else { - abs_ival = (unsigned long)ival; - } - - /* Fast path for single-digit ints */ - if (!(abs_ival >> PyLong_SHIFT)) { - v = _PyLong_New(1); - if (v) { - Py_SIZE(v) = sign; - v->ob_digit[0] = Py_SAFE_DOWNCAST( - abs_ival, unsigned long, digit); - } - return (PyObject*)v; - } + PyLongObject *v; + unsigned long abs_ival; + unsigned long t; /* unsigned so >> doesn't propagate sign bit */ + int ndigits = 0; + int sign = 1; + + CHECK_SMALL_INT(ival); + + if (ival < 0) { + /* negate: can't write this as abs_ival = -ival since that + invokes undefined behaviour when ival is LONG_MIN */ + abs_ival = 0U-(unsigned long)ival; + sign = -1; + } + else { + abs_ival = (unsigned long)ival; + } + + /* Fast path for single-digit ints */ + if (!(abs_ival >> PyLong_SHIFT)) { + v = _PyLong_New(1); + if (v) { + Py_SIZE(v) = sign; + v->ob_digit[0] = Py_SAFE_DOWNCAST( + abs_ival, unsigned long, digit); + } + return (PyObject*)v; + } #if PyLong_SHIFT==15 - /* 2 digits */ - if (!(abs_ival >> 2*PyLong_SHIFT)) { - v = _PyLong_New(2); - if (v) { - Py_SIZE(v) = 2*sign; - v->ob_digit[0] = Py_SAFE_DOWNCAST( - abs_ival & PyLong_MASK, unsigned long, digit); - v->ob_digit[1] = Py_SAFE_DOWNCAST( - abs_ival >> PyLong_SHIFT, unsigned long, digit); - } - return (PyObject*)v; - } + /* 2 digits */ + if (!(abs_ival >> 2*PyLong_SHIFT)) { + v = _PyLong_New(2); + if (v) { + Py_SIZE(v) = 2*sign; + v->ob_digit[0] = Py_SAFE_DOWNCAST( + abs_ival & PyLong_MASK, unsigned long, digit); + v->ob_digit[1] = Py_SAFE_DOWNCAST( + abs_ival >> PyLong_SHIFT, unsigned long, digit); + } + return (PyObject*)v; + } #endif - /* Larger numbers: loop to determine number of digits */ - t = abs_ival; - while (t) { - ++ndigits; - t >>= PyLong_SHIFT; - } - v = _PyLong_New(ndigits); - if (v != NULL) { - digit *p = v->ob_digit; - Py_SIZE(v) = ndigits*sign; - t = abs_ival; - while (t) { - *p++ = Py_SAFE_DOWNCAST( - t & PyLong_MASK, unsigned long, digit); - t >>= PyLong_SHIFT; - } - } - return (PyObject *)v; + /* Larger numbers: loop to determine number of digits */ + t = abs_ival; + while (t) { + ++ndigits; + t >>= PyLong_SHIFT; + } + v = _PyLong_New(ndigits); + if (v != NULL) { + digit *p = v->ob_digit; + Py_SIZE(v) = ndigits*sign; + t = abs_ival; + while (t) { + *p++ = Py_SAFE_DOWNCAST( + t & PyLong_MASK, unsigned long, digit); + t >>= PyLong_SHIFT; + } + } + return (PyObject *)v; } /* Create a new long int object from a C unsigned long int */ @@ -243,28 +243,28 @@ PyObject * PyLong_FromUnsignedLong(unsigned long ival) { - PyLongObject *v; - unsigned long t; - int ndigits = 0; - - if (ival < PyLong_BASE) - return PyLong_FromLong(ival); - /* Count the number of Python digits. */ - t = (unsigned long)ival; - while (t) { - ++ndigits; - t >>= PyLong_SHIFT; - } - v = _PyLong_New(ndigits); - if (v != NULL) { - digit *p = v->ob_digit; - Py_SIZE(v) = ndigits; - while (ival) { - *p++ = (digit)(ival & PyLong_MASK); - ival >>= PyLong_SHIFT; - } - } - return (PyObject *)v; + PyLongObject *v; + unsigned long t; + int ndigits = 0; + + if (ival < PyLong_BASE) + return PyLong_FromLong(ival); + /* Count the number of Python digits. */ + t = (unsigned long)ival; + while (t) { + ++ndigits; + t >>= PyLong_SHIFT; + } + v = _PyLong_New(ndigits); + if (v != NULL) { + digit *p = v->ob_digit; + Py_SIZE(v) = ndigits; + while (ival) { + *p++ = (digit)(ival & PyLong_MASK); + ival >>= PyLong_SHIFT; + } + } + return (PyObject *)v; } /* Create a new long int object from a C double */ @@ -272,41 +272,41 @@ PyObject * PyLong_FromDouble(double dval) { - PyLongObject *v; - double frac; - int i, ndig, expo, neg; - neg = 0; - if (Py_IS_INFINITY(dval)) { - PyErr_SetString(PyExc_OverflowError, - "cannot convert float infinity to integer"); - return NULL; - } - if (Py_IS_NAN(dval)) { - PyErr_SetString(PyExc_ValueError, - "cannot convert float NaN to integer"); - return NULL; - } - if (dval < 0.0) { - neg = 1; - dval = -dval; - } - frac = frexp(dval, &expo); /* dval = frac*2**expo; 0.0 <= frac < 1.0 */ - if (expo <= 0) - return PyLong_FromLong(0L); - ndig = (expo-1) / PyLong_SHIFT + 1; /* Number of 'digits' in result */ - v = _PyLong_New(ndig); - if (v == NULL) - return NULL; - frac = ldexp(frac, (expo-1) % PyLong_SHIFT + 1); - for (i = ndig; --i >= 0; ) { - digit bits = (digit)frac; - v->ob_digit[i] = bits; - frac = frac - (double)bits; - frac = ldexp(frac, PyLong_SHIFT); - } - if (neg) - Py_SIZE(v) = -(Py_SIZE(v)); - return (PyObject *)v; + PyLongObject *v; + double frac; + int i, ndig, expo, neg; + neg = 0; + if (Py_IS_INFINITY(dval)) { + PyErr_SetString(PyExc_OverflowError, + "cannot convert float infinity to integer"); + return NULL; + } + if (Py_IS_NAN(dval)) { + PyErr_SetString(PyExc_ValueError, + "cannot convert float NaN to integer"); + return NULL; + } + if (dval < 0.0) { + neg = 1; + dval = -dval; + } + frac = frexp(dval, &expo); /* dval = frac*2**expo; 0.0 <= frac < 1.0 */ + if (expo <= 0) + return PyLong_FromLong(0L); + ndig = (expo-1) / PyLong_SHIFT + 1; /* Number of 'digits' in result */ + v = _PyLong_New(ndig); + if (v == NULL) + return NULL; + frac = ldexp(frac, (expo-1) % PyLong_SHIFT + 1); + for (i = ndig; --i >= 0; ) { + digit bits = (digit)frac; + v->ob_digit[i] = bits; + frac = frac - (double)bits; + frac = ldexp(frac, PyLong_SHIFT); + } + if (neg) + Py_SIZE(v) = -(Py_SIZE(v)); + return (PyObject *)v; } /* Checking for overflow in PyLong_AsLong is a PITA since C doesn't define @@ -318,8 +318,8 @@ * However, some other compilers warn about applying unary minus to an * unsigned operand. Hence the weird "0-". */ -#define PY_ABS_LONG_MIN (0-(unsigned long)LONG_MIN) -#define PY_ABS_SSIZE_T_MIN (0-(size_t)PY_SSIZE_T_MIN) +#define PY_ABS_LONG_MIN (0-(unsigned long)LONG_MIN) +#define PY_ABS_SSIZE_T_MIN (0-(size_t)PY_SSIZE_T_MIN) /* Get a C long int from a long int object. Returns -1 and sets an error condition if overflow occurs. */ @@ -327,102 +327,102 @@ long PyLong_AsLongAndOverflow(PyObject *vv, int *overflow) { - /* This version by Tim Peters */ - register PyLongObject *v; - unsigned long x, prev; - long res; - Py_ssize_t i; - int sign; - int do_decref = 0; /* if nb_int was called */ - - *overflow = 0; - if (vv == NULL) { - PyErr_BadInternalCall(); - return -1; - } - - if (!PyLong_Check(vv)) { - PyNumberMethods *nb; - nb = vv->ob_type->tp_as_number; - if (nb == NULL || nb->nb_int == NULL) { - PyErr_SetString(PyExc_TypeError, - "an integer is required"); - return -1; - } - vv = (*nb->nb_int) (vv); - if (vv == NULL) - return -1; - do_decref = 1; - if (!PyLong_Check(vv)) { - Py_DECREF(vv); - PyErr_SetString(PyExc_TypeError, - "nb_int should return int object"); - return -1; - } - } - - res = -1; - v = (PyLongObject *)vv; - i = Py_SIZE(v); - - switch (i) { - case -1: - res = -(sdigit)v->ob_digit[0]; - break; - case 0: - res = 0; - break; - case 1: - res = v->ob_digit[0]; - break; - default: - sign = 1; - x = 0; - if (i < 0) { - sign = -1; - i = -(i); - } - while (--i >= 0) { - prev = x; - x = (x << PyLong_SHIFT) | v->ob_digit[i]; - if ((x >> PyLong_SHIFT) != prev) { - *overflow = sign; - goto exit; - } - } - /* Haven't lost any bits, but casting to long requires extra - * care (see comment above). - */ - if (x <= (unsigned long)LONG_MAX) { - res = (long)x * sign; - } - else if (sign < 0 && x == PY_ABS_LONG_MIN) { - res = LONG_MIN; - } - else { - *overflow = sign; - /* res is already set to -1 */ - } - } + /* This version by Tim Peters */ + register PyLongObject *v; + unsigned long x, prev; + long res; + Py_ssize_t i; + int sign; + int do_decref = 0; /* if nb_int was called */ + + *overflow = 0; + if (vv == NULL) { + PyErr_BadInternalCall(); + return -1; + } + + if (!PyLong_Check(vv)) { + PyNumberMethods *nb; + nb = vv->ob_type->tp_as_number; + if (nb == NULL || nb->nb_int == NULL) { + PyErr_SetString(PyExc_TypeError, + "an integer is required"); + return -1; + } + vv = (*nb->nb_int) (vv); + if (vv == NULL) + return -1; + do_decref = 1; + if (!PyLong_Check(vv)) { + Py_DECREF(vv); + PyErr_SetString(PyExc_TypeError, + "nb_int should return int object"); + return -1; + } + } + + res = -1; + v = (PyLongObject *)vv; + i = Py_SIZE(v); + + switch (i) { + case -1: + res = -(sdigit)v->ob_digit[0]; + break; + case 0: + res = 0; + break; + case 1: + res = v->ob_digit[0]; + break; + default: + sign = 1; + x = 0; + if (i < 0) { + sign = -1; + i = -(i); + } + while (--i >= 0) { + prev = x; + x = (x << PyLong_SHIFT) | v->ob_digit[i]; + if ((x >> PyLong_SHIFT) != prev) { + *overflow = sign; + goto exit; + } + } + /* Haven't lost any bits, but casting to long requires extra + * care (see comment above). + */ + if (x <= (unsigned long)LONG_MAX) { + res = (long)x * sign; + } + else if (sign < 0 && x == PY_ABS_LONG_MIN) { + res = LONG_MIN; + } + else { + *overflow = sign; + /* res is already set to -1 */ + } + } exit: - if (do_decref) { - Py_DECREF(vv); - } - return res; + if (do_decref) { + Py_DECREF(vv); + } + return res; } -long +long PyLong_AsLong(PyObject *obj) { - int overflow; - long result = PyLong_AsLongAndOverflow(obj, &overflow); - if (overflow) { - /* XXX: could be cute and give a different - message for overflow == -1 */ - PyErr_SetString(PyExc_OverflowError, - "Python int too large to convert to C long"); - } - return result; + int overflow; + long result = PyLong_AsLongAndOverflow(obj, &overflow); + if (overflow) { + /* XXX: could be cute and give a different + message for overflow == -1 */ + PyErr_SetString(PyExc_OverflowError, + "Python int too large to convert to C long"); + } + return result; } /* Get a Py_ssize_t from a long int object. @@ -430,54 +430,54 @@ Py_ssize_t PyLong_AsSsize_t(PyObject *vv) { - register PyLongObject *v; - size_t x, prev; - Py_ssize_t i; - int sign; - - if (vv == NULL) { - PyErr_BadInternalCall(); - return -1; - } - if (!PyLong_Check(vv)) { - PyErr_SetString(PyExc_TypeError, "an integer is required"); - return -1; - } - - v = (PyLongObject *)vv; - i = Py_SIZE(v); - switch (i) { - case -1: return -(sdigit)v->ob_digit[0]; - case 0: return 0; - case 1: return v->ob_digit[0]; - } - sign = 1; - x = 0; - if (i < 0) { - sign = -1; - i = -(i); - } - while (--i >= 0) { - prev = x; - x = (x << PyLong_SHIFT) | v->ob_digit[i]; - if ((x >> PyLong_SHIFT) != prev) - goto overflow; - } - /* Haven't lost any bits, but casting to a signed type requires - * extra care (see comment above). - */ - if (x <= (size_t)PY_SSIZE_T_MAX) { - return (Py_ssize_t)x * sign; - } - else if (sign < 0 && x == PY_ABS_SSIZE_T_MIN) { - return PY_SSIZE_T_MIN; - } - /* else overflow */ + register PyLongObject *v; + size_t x, prev; + Py_ssize_t i; + int sign; + + if (vv == NULL) { + PyErr_BadInternalCall(); + return -1; + } + if (!PyLong_Check(vv)) { + PyErr_SetString(PyExc_TypeError, "an integer is required"); + return -1; + } + + v = (PyLongObject *)vv; + i = Py_SIZE(v); + switch (i) { + case -1: return -(sdigit)v->ob_digit[0]; + case 0: return 0; + case 1: return v->ob_digit[0]; + } + sign = 1; + x = 0; + if (i < 0) { + sign = -1; + i = -(i); + } + while (--i >= 0) { + prev = x; + x = (x << PyLong_SHIFT) | v->ob_digit[i]; + if ((x >> PyLong_SHIFT) != prev) + goto overflow; + } + /* Haven't lost any bits, but casting to a signed type requires + * extra care (see comment above). + */ + if (x <= (size_t)PY_SSIZE_T_MAX) { + return (Py_ssize_t)x * sign; + } + else if (sign < 0 && x == PY_ABS_SSIZE_T_MIN) { + return PY_SSIZE_T_MIN; + } + /* else overflow */ overflow: - PyErr_SetString(PyExc_OverflowError, - "Python int too large to convert to C ssize_t"); - return -1; + PyErr_SetString(PyExc_OverflowError, + "Python int too large to convert to C ssize_t"); + return -1; } /* Get a C unsigned long int from a long int object. @@ -486,41 +486,41 @@ unsigned long PyLong_AsUnsignedLong(PyObject *vv) { - register PyLongObject *v; - unsigned long x, prev; - Py_ssize_t i; - - if (vv == NULL) { - PyErr_BadInternalCall(); - return (unsigned long)-1; - } - if (!PyLong_Check(vv)) { - PyErr_SetString(PyExc_TypeError, "an integer is required"); - return (unsigned long)-1; - } - - v = (PyLongObject *)vv; - i = Py_SIZE(v); - x = 0; - if (i < 0) { - PyErr_SetString(PyExc_OverflowError, - "can't convert negative value to unsigned int"); - return (unsigned long) -1; - } - switch (i) { - case 0: return 0; - case 1: return v->ob_digit[0]; - } - while (--i >= 0) { - prev = x; - x = (x << PyLong_SHIFT) | v->ob_digit[i]; - if ((x >> PyLong_SHIFT) != prev) { - PyErr_SetString(PyExc_OverflowError, - "python int too large to convert to C unsigned long"); - return (unsigned long) -1; - } - } - return x; + register PyLongObject *v; + unsigned long x, prev; + Py_ssize_t i; + + if (vv == NULL) { + PyErr_BadInternalCall(); + return (unsigned long)-1; + } + if (!PyLong_Check(vv)) { + PyErr_SetString(PyExc_TypeError, "an integer is required"); + return (unsigned long)-1; + } + + v = (PyLongObject *)vv; + i = Py_SIZE(v); + x = 0; + if (i < 0) { + PyErr_SetString(PyExc_OverflowError, + "can't convert negative value to unsigned int"); + return (unsigned long) -1; + } + switch (i) { + case 0: return 0; + case 1: return v->ob_digit[0]; + } + while (--i >= 0) { + prev = x; + x = (x << PyLong_SHIFT) | v->ob_digit[i]; + if ((x >> PyLong_SHIFT) != prev) { + PyErr_SetString(PyExc_OverflowError, + "python int too large to convert to C unsigned long"); + return (unsigned long) -1; + } + } + return x; } /* Get a C unsigned long int from a long int object. @@ -529,41 +529,41 @@ size_t PyLong_AsSize_t(PyObject *vv) { - register PyLongObject *v; - size_t x, prev; - Py_ssize_t i; - - if (vv == NULL) { - PyErr_BadInternalCall(); - return (size_t) -1; - } - if (!PyLong_Check(vv)) { - PyErr_SetString(PyExc_TypeError, "an integer is required"); - return (size_t)-1; - } - - v = (PyLongObject *)vv; - i = Py_SIZE(v); - x = 0; - if (i < 0) { - PyErr_SetString(PyExc_OverflowError, - "can't convert negative value to size_t"); - return (size_t) -1; - } - switch (i) { - case 0: return 0; - case 1: return v->ob_digit[0]; - } - while (--i >= 0) { - prev = x; - x = (x << PyLong_SHIFT) | v->ob_digit[i]; - if ((x >> PyLong_SHIFT) != prev) { - PyErr_SetString(PyExc_OverflowError, - "Python int too large to convert to C size_t"); - return (unsigned long) -1; - } - } - return x; + register PyLongObject *v; + size_t x, prev; + Py_ssize_t i; + + if (vv == NULL) { + PyErr_BadInternalCall(); + return (size_t) -1; + } + if (!PyLong_Check(vv)) { + PyErr_SetString(PyExc_TypeError, "an integer is required"); + return (size_t)-1; + } + + v = (PyLongObject *)vv; + i = Py_SIZE(v); + x = 0; + if (i < 0) { + PyErr_SetString(PyExc_OverflowError, + "can't convert negative value to size_t"); + return (size_t) -1; + } + switch (i) { + case 0: return 0; + case 1: return v->ob_digit[0]; + } + while (--i >= 0) { + prev = x; + x = (x << PyLong_SHIFT) | v->ob_digit[i]; + if ((x >> PyLong_SHIFT) != prev) { + PyErr_SetString(PyExc_OverflowError, + "Python int too large to convert to C size_t"); + return (unsigned long) -1; + } + } + return x; } /* Get a C unsigned long int from a long int object, ignoring the high bits. @@ -572,354 +572,354 @@ static unsigned long _PyLong_AsUnsignedLongMask(PyObject *vv) { - register PyLongObject *v; - unsigned long x; - Py_ssize_t i; - int sign; - - if (vv == NULL || !PyLong_Check(vv)) { - PyErr_BadInternalCall(); - return (unsigned long) -1; - } - v = (PyLongObject *)vv; - i = Py_SIZE(v); - switch (i) { - case 0: return 0; - case 1: return v->ob_digit[0]; - } - sign = 1; - x = 0; - if (i < 0) { - sign = -1; - i = -i; - } - while (--i >= 0) { - x = (x << PyLong_SHIFT) | v->ob_digit[i]; - } - return x * sign; + register PyLongObject *v; + unsigned long x; + Py_ssize_t i; + int sign; + + if (vv == NULL || !PyLong_Check(vv)) { + PyErr_BadInternalCall(); + return (unsigned long) -1; + } + v = (PyLongObject *)vv; + i = Py_SIZE(v); + switch (i) { + case 0: return 0; + case 1: return v->ob_digit[0]; + } + sign = 1; + x = 0; + if (i < 0) { + sign = -1; + i = -i; + } + while (--i >= 0) { + x = (x << PyLong_SHIFT) | v->ob_digit[i]; + } + return x * sign; } unsigned long PyLong_AsUnsignedLongMask(register PyObject *op) { - PyNumberMethods *nb; - PyLongObject *lo; - unsigned long val; - - if (op && PyLong_Check(op)) - return _PyLong_AsUnsignedLongMask(op); - - if (op == NULL || (nb = op->ob_type->tp_as_number) == NULL || - nb->nb_int == NULL) { - PyErr_SetString(PyExc_TypeError, "an integer is required"); - return (unsigned long)-1; - } - - lo = (PyLongObject*) (*nb->nb_int) (op); - if (lo == NULL) - return (unsigned long)-1; - if (PyLong_Check(lo)) { - val = _PyLong_AsUnsignedLongMask((PyObject *)lo); - Py_DECREF(lo); - if (PyErr_Occurred()) - return (unsigned long)-1; - return val; - } - else - { - Py_DECREF(lo); - PyErr_SetString(PyExc_TypeError, - "nb_int should return int object"); - return (unsigned long)-1; - } + PyNumberMethods *nb; + PyLongObject *lo; + unsigned long val; + + if (op && PyLong_Check(op)) + return _PyLong_AsUnsignedLongMask(op); + + if (op == NULL || (nb = op->ob_type->tp_as_number) == NULL || + nb->nb_int == NULL) { + PyErr_SetString(PyExc_TypeError, "an integer is required"); + return (unsigned long)-1; + } + + lo = (PyLongObject*) (*nb->nb_int) (op); + if (lo == NULL) + return (unsigned long)-1; + if (PyLong_Check(lo)) { + val = _PyLong_AsUnsignedLongMask((PyObject *)lo); + Py_DECREF(lo); + if (PyErr_Occurred()) + return (unsigned long)-1; + return val; + } + else + { + Py_DECREF(lo); + PyErr_SetString(PyExc_TypeError, + "nb_int should return int object"); + return (unsigned long)-1; + } } int _PyLong_Sign(PyObject *vv) { - PyLongObject *v = (PyLongObject *)vv; + PyLongObject *v = (PyLongObject *)vv; - assert(v != NULL); - assert(PyLong_Check(v)); + assert(v != NULL); + assert(PyLong_Check(v)); - return Py_SIZE(v) == 0 ? 0 : (Py_SIZE(v) < 0 ? -1 : 1); + return Py_SIZE(v) == 0 ? 0 : (Py_SIZE(v) < 0 ? -1 : 1); } size_t _PyLong_NumBits(PyObject *vv) { - PyLongObject *v = (PyLongObject *)vv; - size_t result = 0; - Py_ssize_t ndigits; - - assert(v != NULL); - assert(PyLong_Check(v)); - ndigits = ABS(Py_SIZE(v)); - assert(ndigits == 0 || v->ob_digit[ndigits - 1] != 0); - if (ndigits > 0) { - digit msd = v->ob_digit[ndigits - 1]; - - result = (ndigits - 1) * PyLong_SHIFT; - if (result / PyLong_SHIFT != (size_t)(ndigits - 1)) - goto Overflow; - do { - ++result; - if (result == 0) - goto Overflow; - msd >>= 1; - } while (msd); - } - return result; + PyLongObject *v = (PyLongObject *)vv; + size_t result = 0; + Py_ssize_t ndigits; + + assert(v != NULL); + assert(PyLong_Check(v)); + ndigits = ABS(Py_SIZE(v)); + assert(ndigits == 0 || v->ob_digit[ndigits - 1] != 0); + if (ndigits > 0) { + digit msd = v->ob_digit[ndigits - 1]; + + result = (ndigits - 1) * PyLong_SHIFT; + if (result / PyLong_SHIFT != (size_t)(ndigits - 1)) + goto Overflow; + do { + ++result; + if (result == 0) + goto Overflow; + msd >>= 1; + } while (msd); + } + return result; Overflow: - PyErr_SetString(PyExc_OverflowError, "int has too many bits " - "to express in a platform size_t"); - return (size_t)-1; + PyErr_SetString(PyExc_OverflowError, "int has too many bits " + "to express in a platform size_t"); + return (size_t)-1; } PyObject * _PyLong_FromByteArray(const unsigned char* bytes, size_t n, - int little_endian, int is_signed) + int little_endian, int is_signed) { - const unsigned char* pstartbyte;/* LSB of bytes */ - int incr; /* direction to move pstartbyte */ - const unsigned char* pendbyte; /* MSB of bytes */ - size_t numsignificantbytes; /* number of bytes that matter */ - Py_ssize_t ndigits; /* number of Python long digits */ - PyLongObject* v; /* result */ - Py_ssize_t idigit = 0; /* next free index in v->ob_digit */ - - if (n == 0) - return PyLong_FromLong(0L); - - if (little_endian) { - pstartbyte = bytes; - pendbyte = bytes + n - 1; - incr = 1; - } - else { - pstartbyte = bytes + n - 1; - pendbyte = bytes; - incr = -1; - } - - if (is_signed) - is_signed = *pendbyte >= 0x80; - - /* Compute numsignificantbytes. This consists of finding the most - significant byte. Leading 0 bytes are insignficant if the number - is positive, and leading 0xff bytes if negative. */ - { - size_t i; - const unsigned char* p = pendbyte; - const int pincr = -incr; /* search MSB to LSB */ - const unsigned char insignficant = is_signed ? 0xff : 0x00; - - for (i = 0; i < n; ++i, p += pincr) { - if (*p != insignficant) - break; - } - numsignificantbytes = n - i; - /* 2's-comp is a bit tricky here, e.g. 0xff00 == -0x0100, so - actually has 2 significant bytes. OTOH, 0xff0001 == - -0x00ffff, so we wouldn't *need* to bump it there; but we - do for 0xffff = -0x0001. To be safe without bothering to - check every case, bump it regardless. */ - if (is_signed && numsignificantbytes < n) - ++numsignificantbytes; - } - - /* How many Python long digits do we need? We have - 8*numsignificantbytes bits, and each Python long digit has - PyLong_SHIFT bits, so it's the ceiling of the quotient. */ - /* catch overflow before it happens */ - if (numsignificantbytes > (PY_SSIZE_T_MAX - PyLong_SHIFT) / 8) { - PyErr_SetString(PyExc_OverflowError, - "byte array too long to convert to int"); - return NULL; - } - ndigits = (numsignificantbytes * 8 + PyLong_SHIFT - 1) / PyLong_SHIFT; - v = _PyLong_New(ndigits); - if (v == NULL) - return NULL; - - /* Copy the bits over. The tricky parts are computing 2's-comp on - the fly for signed numbers, and dealing with the mismatch between - 8-bit bytes and (probably) 15-bit Python digits.*/ - { - size_t i; - twodigits carry = 1; /* for 2's-comp calculation */ - twodigits accum = 0; /* sliding register */ - unsigned int accumbits = 0; /* number of bits in accum */ - const unsigned char* p = pstartbyte; - - for (i = 0; i < numsignificantbytes; ++i, p += incr) { - twodigits thisbyte = *p; - /* Compute correction for 2's comp, if needed. */ - if (is_signed) { - thisbyte = (0xff ^ thisbyte) + carry; - carry = thisbyte >> 8; - thisbyte &= 0xff; - } - /* Because we're going LSB to MSB, thisbyte is - more significant than what's already in accum, - so needs to be prepended to accum. */ - accum |= (twodigits)thisbyte << accumbits; - accumbits += 8; - if (accumbits >= PyLong_SHIFT) { - /* There's enough to fill a Python digit. */ - assert(idigit < ndigits); - v->ob_digit[idigit] = (digit)(accum & - PyLong_MASK); - ++idigit; - accum >>= PyLong_SHIFT; - accumbits -= PyLong_SHIFT; - assert(accumbits < PyLong_SHIFT); - } - } - assert(accumbits < PyLong_SHIFT); - if (accumbits) { - assert(idigit < ndigits); - v->ob_digit[idigit] = (digit)accum; - ++idigit; - } - } + const unsigned char* pstartbyte;/* LSB of bytes */ + int incr; /* direction to move pstartbyte */ + const unsigned char* pendbyte; /* MSB of bytes */ + size_t numsignificantbytes; /* number of bytes that matter */ + Py_ssize_t ndigits; /* number of Python long digits */ + PyLongObject* v; /* result */ + Py_ssize_t idigit = 0; /* next free index in v->ob_digit */ + + if (n == 0) + return PyLong_FromLong(0L); + + if (little_endian) { + pstartbyte = bytes; + pendbyte = bytes + n - 1; + incr = 1; + } + else { + pstartbyte = bytes + n - 1; + pendbyte = bytes; + incr = -1; + } + + if (is_signed) + is_signed = *pendbyte >= 0x80; + + /* Compute numsignificantbytes. This consists of finding the most + significant byte. Leading 0 bytes are insignficant if the number + is positive, and leading 0xff bytes if negative. */ + { + size_t i; + const unsigned char* p = pendbyte; + const int pincr = -incr; /* search MSB to LSB */ + const unsigned char insignficant = is_signed ? 0xff : 0x00; + + for (i = 0; i < n; ++i, p += pincr) { + if (*p != insignficant) + break; + } + numsignificantbytes = n - i; + /* 2's-comp is a bit tricky here, e.g. 0xff00 == -0x0100, so + actually has 2 significant bytes. OTOH, 0xff0001 == + -0x00ffff, so we wouldn't *need* to bump it there; but we + do for 0xffff = -0x0001. To be safe without bothering to + check every case, bump it regardless. */ + if (is_signed && numsignificantbytes < n) + ++numsignificantbytes; + } + + /* How many Python long digits do we need? We have + 8*numsignificantbytes bits, and each Python long digit has + PyLong_SHIFT bits, so it's the ceiling of the quotient. */ + /* catch overflow before it happens */ + if (numsignificantbytes > (PY_SSIZE_T_MAX - PyLong_SHIFT) / 8) { + PyErr_SetString(PyExc_OverflowError, + "byte array too long to convert to int"); + return NULL; + } + ndigits = (numsignificantbytes * 8 + PyLong_SHIFT - 1) / PyLong_SHIFT; + v = _PyLong_New(ndigits); + if (v == NULL) + return NULL; + + /* Copy the bits over. The tricky parts are computing 2's-comp on + the fly for signed numbers, and dealing with the mismatch between + 8-bit bytes and (probably) 15-bit Python digits.*/ + { + size_t i; + twodigits carry = 1; /* for 2's-comp calculation */ + twodigits accum = 0; /* sliding register */ + unsigned int accumbits = 0; /* number of bits in accum */ + const unsigned char* p = pstartbyte; + + for (i = 0; i < numsignificantbytes; ++i, p += incr) { + twodigits thisbyte = *p; + /* Compute correction for 2's comp, if needed. */ + if (is_signed) { + thisbyte = (0xff ^ thisbyte) + carry; + carry = thisbyte >> 8; + thisbyte &= 0xff; + } + /* Because we're going LSB to MSB, thisbyte is + more significant than what's already in accum, + so needs to be prepended to accum. */ + accum |= (twodigits)thisbyte << accumbits; + accumbits += 8; + if (accumbits >= PyLong_SHIFT) { + /* There's enough to fill a Python digit. */ + assert(idigit < ndigits); + v->ob_digit[idigit] = (digit)(accum & + PyLong_MASK); + ++idigit; + accum >>= PyLong_SHIFT; + accumbits -= PyLong_SHIFT; + assert(accumbits < PyLong_SHIFT); + } + } + assert(accumbits < PyLong_SHIFT); + if (accumbits) { + assert(idigit < ndigits); + v->ob_digit[idigit] = (digit)accum; + ++idigit; + } + } - Py_SIZE(v) = is_signed ? -idigit : idigit; - return (PyObject *)long_normalize(v); + Py_SIZE(v) = is_signed ? -idigit : idigit; + return (PyObject *)long_normalize(v); } int _PyLong_AsByteArray(PyLongObject* v, - unsigned char* bytes, size_t n, - int little_endian, int is_signed) + unsigned char* bytes, size_t n, + int little_endian, int is_signed) { - Py_ssize_t i; /* index into v->ob_digit */ - Py_ssize_t ndigits; /* |v->ob_size| */ - twodigits accum; /* sliding register */ - unsigned int accumbits; /* # bits in accum */ - int do_twos_comp; /* store 2's-comp? is_signed and v < 0 */ - digit carry; /* for computing 2's-comp */ - size_t j; /* # bytes filled */ - unsigned char* p; /* pointer to next byte in bytes */ - int pincr; /* direction to move p */ - - assert(v != NULL && PyLong_Check(v)); - - if (Py_SIZE(v) < 0) { - ndigits = -(Py_SIZE(v)); - if (!is_signed) { - PyErr_SetString(PyExc_OverflowError, - "can't convert negative int to unsigned"); - return -1; - } - do_twos_comp = 1; - } - else { - ndigits = Py_SIZE(v); - do_twos_comp = 0; - } - - if (little_endian) { - p = bytes; - pincr = 1; - } - else { - p = bytes + n - 1; - pincr = -1; - } - - /* Copy over all the Python digits. - It's crucial that every Python digit except for the MSD contribute - exactly PyLong_SHIFT bits to the total, so first assert that the long is - normalized. */ - assert(ndigits == 0 || v->ob_digit[ndigits - 1] != 0); - j = 0; - accum = 0; - accumbits = 0; - carry = do_twos_comp ? 1 : 0; - for (i = 0; i < ndigits; ++i) { - digit thisdigit = v->ob_digit[i]; - if (do_twos_comp) { - thisdigit = (thisdigit ^ PyLong_MASK) + carry; - carry = thisdigit >> PyLong_SHIFT; - thisdigit &= PyLong_MASK; - } - /* Because we're going LSB to MSB, thisdigit is more - significant than what's already in accum, so needs to be - prepended to accum. */ - accum |= (twodigits)thisdigit << accumbits; - - /* The most-significant digit may be (probably is) at least - partly empty. */ - if (i == ndigits - 1) { - /* Count # of sign bits -- they needn't be stored, - * although for signed conversion we need later to - * make sure at least one sign bit gets stored. */ - digit s = do_twos_comp ? thisdigit ^ PyLong_MASK : - thisdigit; - while (s != 0) { - s >>= 1; - accumbits++; - } - } - else - accumbits += PyLong_SHIFT; - - /* Store as many bytes as possible. */ - while (accumbits >= 8) { - if (j >= n) - goto Overflow; - ++j; - *p = (unsigned char)(accum & 0xff); - p += pincr; - accumbits -= 8; - accum >>= 8; - } - } - - /* Store the straggler (if any). */ - assert(accumbits < 8); - assert(carry == 0); /* else do_twos_comp and *every* digit was 0 */ - if (accumbits > 0) { - if (j >= n) - goto Overflow; - ++j; - if (do_twos_comp) { - /* Fill leading bits of the byte with sign bits - (appropriately pretending that the long had an - infinite supply of sign bits). */ - accum |= (~(twodigits)0) << accumbits; - } - *p = (unsigned char)(accum & 0xff); - p += pincr; - } - else if (j == n && n > 0 && is_signed) { - /* The main loop filled the byte array exactly, so the code - just above didn't get to ensure there's a sign bit, and the - loop below wouldn't add one either. Make sure a sign bit - exists. */ - unsigned char msb = *(p - pincr); - int sign_bit_set = msb >= 0x80; - assert(accumbits == 0); - if (sign_bit_set == do_twos_comp) - return 0; - else - goto Overflow; - } - - /* Fill remaining bytes with copies of the sign bit. */ - { - unsigned char signbyte = do_twos_comp ? 0xffU : 0U; - for ( ; j < n; ++j, p += pincr) - *p = signbyte; - } + Py_ssize_t i; /* index into v->ob_digit */ + Py_ssize_t ndigits; /* |v->ob_size| */ + twodigits accum; /* sliding register */ + unsigned int accumbits; /* # bits in accum */ + int do_twos_comp; /* store 2's-comp? is_signed and v < 0 */ + digit carry; /* for computing 2's-comp */ + size_t j; /* # bytes filled */ + unsigned char* p; /* pointer to next byte in bytes */ + int pincr; /* direction to move p */ + + assert(v != NULL && PyLong_Check(v)); + + if (Py_SIZE(v) < 0) { + ndigits = -(Py_SIZE(v)); + if (!is_signed) { + PyErr_SetString(PyExc_OverflowError, + "can't convert negative int to unsigned"); + return -1; + } + do_twos_comp = 1; + } + else { + ndigits = Py_SIZE(v); + do_twos_comp = 0; + } + + if (little_endian) { + p = bytes; + pincr = 1; + } + else { + p = bytes + n - 1; + pincr = -1; + } + + /* Copy over all the Python digits. + It's crucial that every Python digit except for the MSD contribute + exactly PyLong_SHIFT bits to the total, so first assert that the long is + normalized. */ + assert(ndigits == 0 || v->ob_digit[ndigits - 1] != 0); + j = 0; + accum = 0; + accumbits = 0; + carry = do_twos_comp ? 1 : 0; + for (i = 0; i < ndigits; ++i) { + digit thisdigit = v->ob_digit[i]; + if (do_twos_comp) { + thisdigit = (thisdigit ^ PyLong_MASK) + carry; + carry = thisdigit >> PyLong_SHIFT; + thisdigit &= PyLong_MASK; + } + /* Because we're going LSB to MSB, thisdigit is more + significant than what's already in accum, so needs to be + prepended to accum. */ + accum |= (twodigits)thisdigit << accumbits; + + /* The most-significant digit may be (probably is) at least + partly empty. */ + if (i == ndigits - 1) { + /* Count # of sign bits -- they needn't be stored, + * although for signed conversion we need later to + * make sure at least one sign bit gets stored. */ + digit s = do_twos_comp ? thisdigit ^ PyLong_MASK : + thisdigit; + while (s != 0) { + s >>= 1; + accumbits++; + } + } + else + accumbits += PyLong_SHIFT; + + /* Store as many bytes as possible. */ + while (accumbits >= 8) { + if (j >= n) + goto Overflow; + ++j; + *p = (unsigned char)(accum & 0xff); + p += pincr; + accumbits -= 8; + accum >>= 8; + } + } + + /* Store the straggler (if any). */ + assert(accumbits < 8); + assert(carry == 0); /* else do_twos_comp and *every* digit was 0 */ + if (accumbits > 0) { + if (j >= n) + goto Overflow; + ++j; + if (do_twos_comp) { + /* Fill leading bits of the byte with sign bits + (appropriately pretending that the long had an + infinite supply of sign bits). */ + accum |= (~(twodigits)0) << accumbits; + } + *p = (unsigned char)(accum & 0xff); + p += pincr; + } + else if (j == n && n > 0 && is_signed) { + /* The main loop filled the byte array exactly, so the code + just above didn't get to ensure there's a sign bit, and the + loop below wouldn't add one either. Make sure a sign bit + exists. */ + unsigned char msb = *(p - pincr); + int sign_bit_set = msb >= 0x80; + assert(accumbits == 0); + if (sign_bit_set == do_twos_comp) + return 0; + else + goto Overflow; + } + + /* Fill remaining bytes with copies of the sign bit. */ + { + unsigned char signbyte = do_twos_comp ? 0xffU : 0U; + for ( ; j < n; ++j, p += pincr) + *p = signbyte; + } - return 0; + return 0; Overflow: - PyErr_SetString(PyExc_OverflowError, "int too big to convert"); - return -1; + PyErr_SetString(PyExc_OverflowError, "int too big to convert"); + return -1; } @@ -934,10 +934,10 @@ #if SIZEOF_LONG_LONG < SIZEOF_VOID_P # error "PyLong_FromVoidPtr: sizeof(PY_LONG_LONG) < sizeof(void*)" #endif - /* special-case null pointer */ - if (!p) - return PyLong_FromLong(0); - return PyLong_FromUnsignedLongLong((unsigned PY_LONG_LONG)(Py_uintptr_t)p); + /* special-case null pointer */ + if (!p) + return PyLong_FromLong(0); + return PyLong_FromUnsignedLongLong((unsigned PY_LONG_LONG)(Py_uintptr_t)p); } @@ -946,17 +946,17 @@ void * PyLong_AsVoidPtr(PyObject *vv) { - /* This function will allow int or long objects. If vv is neither, - then the PyLong_AsLong*() functions will raise the exception: - PyExc_SystemError, "bad argument to internal function" - */ + /* This function will allow int or long objects. If vv is neither, + then the PyLong_AsLong*() functions will raise the exception: + PyExc_SystemError, "bad argument to internal function" + */ #if SIZEOF_VOID_P <= SIZEOF_LONG - long x; + long x; - if (PyLong_Check(vv) && _PyLong_Sign(vv) < 0) - x = PyLong_AsLong(vv); - else - x = PyLong_AsUnsignedLong(vv); + if (PyLong_Check(vv) && _PyLong_Sign(vv) < 0) + x = PyLong_AsLong(vv); + else + x = PyLong_AsUnsignedLong(vv); #else #ifndef HAVE_LONG_LONG @@ -965,18 +965,18 @@ #if SIZEOF_LONG_LONG < SIZEOF_VOID_P # error "PyLong_AsVoidPtr: sizeof(PY_LONG_LONG) < sizeof(void*)" #endif - PY_LONG_LONG x; + PY_LONG_LONG x; - if (PyLong_Check(vv) && _PyLong_Sign(vv) < 0) - x = PyLong_AsLongLong(vv); - else - x = PyLong_AsUnsignedLongLong(vv); + if (PyLong_Check(vv) && _PyLong_Sign(vv) < 0) + x = PyLong_AsLongLong(vv); + else + x = PyLong_AsUnsignedLongLong(vv); #endif /* SIZEOF_VOID_P <= SIZEOF_LONG */ - if (x == -1 && PyErr_Occurred()) - return NULL; - return (void *)x; + if (x == -1 && PyErr_Occurred()) + return NULL; + return (void *)x; } #ifdef HAVE_LONG_LONG @@ -986,50 +986,50 @@ */ #define IS_LITTLE_ENDIAN (int)*(unsigned char*)&one -#define PY_ABS_LLONG_MIN (0-(unsigned PY_LONG_LONG)PY_LLONG_MIN) +#define PY_ABS_LLONG_MIN (0-(unsigned PY_LONG_LONG)PY_LLONG_MIN) /* Create a new long int object from a C PY_LONG_LONG int. */ PyObject * PyLong_FromLongLong(PY_LONG_LONG ival) { - PyLongObject *v; - unsigned PY_LONG_LONG abs_ival; - unsigned PY_LONG_LONG t; /* unsigned so >> doesn't propagate sign bit */ - int ndigits = 0; - int negative = 0; - - CHECK_SMALL_INT(ival); - if (ival < 0) { - /* avoid signed overflow on negation; see comments - in PyLong_FromLong above. */ - abs_ival = (unsigned PY_LONG_LONG)(-1-ival) + 1; - negative = 1; - } - else { - abs_ival = (unsigned PY_LONG_LONG)ival; - } - - /* Count the number of Python digits. - We used to pick 5 ("big enough for anything"), but that's a - waste of time and space given that 5*15 = 75 bits are rarely - needed. */ - t = abs_ival; - while (t) { - ++ndigits; - t >>= PyLong_SHIFT; - } - v = _PyLong_New(ndigits); - if (v != NULL) { - digit *p = v->ob_digit; - Py_SIZE(v) = negative ? -ndigits : ndigits; - t = abs_ival; - while (t) { - *p++ = (digit)(t & PyLong_MASK); - t >>= PyLong_SHIFT; - } - } - return (PyObject *)v; + PyLongObject *v; + unsigned PY_LONG_LONG abs_ival; + unsigned PY_LONG_LONG t; /* unsigned so >> doesn't propagate sign bit */ + int ndigits = 0; + int negative = 0; + + CHECK_SMALL_INT(ival); + if (ival < 0) { + /* avoid signed overflow on negation; see comments + in PyLong_FromLong above. */ + abs_ival = (unsigned PY_LONG_LONG)(-1-ival) + 1; + negative = 1; + } + else { + abs_ival = (unsigned PY_LONG_LONG)ival; + } + + /* Count the number of Python digits. + We used to pick 5 ("big enough for anything"), but that's a + waste of time and space given that 5*15 = 75 bits are rarely + needed. */ + t = abs_ival; + while (t) { + ++ndigits; + t >>= PyLong_SHIFT; + } + v = _PyLong_New(ndigits); + if (v != NULL) { + digit *p = v->ob_digit; + Py_SIZE(v) = negative ? -ndigits : ndigits; + t = abs_ival; + while (t) { + *p++ = (digit)(t & PyLong_MASK); + t >>= PyLong_SHIFT; + } + } + return (PyObject *)v; } /* Create a new long int object from a C unsigned PY_LONG_LONG int. */ @@ -1037,28 +1037,28 @@ PyObject * PyLong_FromUnsignedLongLong(unsigned PY_LONG_LONG ival) { - PyLongObject *v; - unsigned PY_LONG_LONG t; - int ndigits = 0; - - if (ival < PyLong_BASE) - return PyLong_FromLong((long)ival); - /* Count the number of Python digits. */ - t = (unsigned PY_LONG_LONG)ival; - while (t) { - ++ndigits; - t >>= PyLong_SHIFT; - } - v = _PyLong_New(ndigits); - if (v != NULL) { - digit *p = v->ob_digit; - Py_SIZE(v) = ndigits; - while (ival) { - *p++ = (digit)(ival & PyLong_MASK); - ival >>= PyLong_SHIFT; - } - } - return (PyObject *)v; + PyLongObject *v; + unsigned PY_LONG_LONG t; + int ndigits = 0; + + if (ival < PyLong_BASE) + return PyLong_FromLong((long)ival); + /* Count the number of Python digits. */ + t = (unsigned PY_LONG_LONG)ival; + while (t) { + ++ndigits; + t >>= PyLong_SHIFT; + } + v = _PyLong_New(ndigits); + if (v != NULL) { + digit *p = v->ob_digit; + Py_SIZE(v) = ndigits; + while (ival) { + *p++ = (digit)(ival & PyLong_MASK); + ival >>= PyLong_SHIFT; + } + } + return (PyObject *)v; } /* Create a new long int object from a C Py_ssize_t. */ @@ -1066,39 +1066,39 @@ PyObject * PyLong_FromSsize_t(Py_ssize_t ival) { - PyLongObject *v; - size_t abs_ival; - size_t t; /* unsigned so >> doesn't propagate sign bit */ - int ndigits = 0; - int negative = 0; - - CHECK_SMALL_INT(ival); - if (ival < 0) { - /* avoid signed overflow when ival = SIZE_T_MIN */ - abs_ival = (size_t)(-1-ival)+1; - negative = 1; - } - else { - abs_ival = (size_t)ival; - } - - /* Count the number of Python digits. */ - t = abs_ival; - while (t) { - ++ndigits; - t >>= PyLong_SHIFT; - } - v = _PyLong_New(ndigits); - if (v != NULL) { - digit *p = v->ob_digit; - Py_SIZE(v) = negative ? -ndigits : ndigits; - t = abs_ival; - while (t) { - *p++ = (digit)(t & PyLong_MASK); - t >>= PyLong_SHIFT; - } - } - return (PyObject *)v; + PyLongObject *v; + size_t abs_ival; + size_t t; /* unsigned so >> doesn't propagate sign bit */ + int ndigits = 0; + int negative = 0; + + CHECK_SMALL_INT(ival); + if (ival < 0) { + /* avoid signed overflow when ival = SIZE_T_MIN */ + abs_ival = (size_t)(-1-ival)+1; + negative = 1; + } + else { + abs_ival = (size_t)ival; + } + + /* Count the number of Python digits. */ + t = abs_ival; + while (t) { + ++ndigits; + t >>= PyLong_SHIFT; + } + v = _PyLong_New(ndigits); + if (v != NULL) { + digit *p = v->ob_digit; + Py_SIZE(v) = negative ? -ndigits : ndigits; + t = abs_ival; + while (t) { + *p++ = (digit)(t & PyLong_MASK); + t >>= PyLong_SHIFT; + } + } + return (PyObject *)v; } /* Create a new long int object from a C size_t. */ @@ -1106,28 +1106,28 @@ PyObject * PyLong_FromSize_t(size_t ival) { - PyLongObject *v; - size_t t; - int ndigits = 0; - - if (ival < PyLong_BASE) - return PyLong_FromLong((long)ival); - /* Count the number of Python digits. */ - t = ival; - while (t) { - ++ndigits; - t >>= PyLong_SHIFT; - } - v = _PyLong_New(ndigits); - if (v != NULL) { - digit *p = v->ob_digit; - Py_SIZE(v) = ndigits; - while (ival) { - *p++ = (digit)(ival & PyLong_MASK); - ival >>= PyLong_SHIFT; - } - } - return (PyObject *)v; + PyLongObject *v; + size_t t; + int ndigits = 0; + + if (ival < PyLong_BASE) + return PyLong_FromLong((long)ival); + /* Count the number of Python digits. */ + t = ival; + while (t) { + ++ndigits; + t >>= PyLong_SHIFT; + } + v = _PyLong_New(ndigits); + if (v != NULL) { + digit *p = v->ob_digit; + Py_SIZE(v) = ndigits; + while (ival) { + *p++ = (digit)(ival & PyLong_MASK); + ival >>= PyLong_SHIFT; + } + } + return (PyObject *)v; } /* Get a C PY_LONG_LONG int from a long int object. @@ -1136,51 +1136,51 @@ PY_LONG_LONG PyLong_AsLongLong(PyObject *vv) { - PyLongObject *v; - PY_LONG_LONG bytes; - int one = 1; - int res; - - if (vv == NULL) { - PyErr_BadInternalCall(); - return -1; - } - if (!PyLong_Check(vv)) { - PyNumberMethods *nb; - PyObject *io; - if ((nb = vv->ob_type->tp_as_number) == NULL || - nb->nb_int == NULL) { - PyErr_SetString(PyExc_TypeError, "an integer is required"); - return -1; - } - io = (*nb->nb_int) (vv); - if (io == NULL) - return -1; - if (PyLong_Check(io)) { - bytes = PyLong_AsLongLong(io); - Py_DECREF(io); - return bytes; - } - Py_DECREF(io); - PyErr_SetString(PyExc_TypeError, "integer conversion failed"); - return -1; - } - - v = (PyLongObject*)vv; - switch(Py_SIZE(v)) { - case -1: return -(sdigit)v->ob_digit[0]; - case 0: return 0; - case 1: return v->ob_digit[0]; - } - res = _PyLong_AsByteArray( - (PyLongObject *)vv, (unsigned char *)&bytes, - SIZEOF_LONG_LONG, IS_LITTLE_ENDIAN, 1); - - /* Plan 9 can't handle PY_LONG_LONG in ? : expressions */ - if (res < 0) - return (PY_LONG_LONG)-1; - else - return bytes; + PyLongObject *v; + PY_LONG_LONG bytes; + int one = 1; + int res; + + if (vv == NULL) { + PyErr_BadInternalCall(); + return -1; + } + if (!PyLong_Check(vv)) { + PyNumberMethods *nb; + PyObject *io; + if ((nb = vv->ob_type->tp_as_number) == NULL || + nb->nb_int == NULL) { + PyErr_SetString(PyExc_TypeError, "an integer is required"); + return -1; + } + io = (*nb->nb_int) (vv); + if (io == NULL) + return -1; + if (PyLong_Check(io)) { + bytes = PyLong_AsLongLong(io); + Py_DECREF(io); + return bytes; + } + Py_DECREF(io); + PyErr_SetString(PyExc_TypeError, "integer conversion failed"); + return -1; + } + + v = (PyLongObject*)vv; + switch(Py_SIZE(v)) { + case -1: return -(sdigit)v->ob_digit[0]; + case 0: return 0; + case 1: return v->ob_digit[0]; + } + res = _PyLong_AsByteArray( + (PyLongObject *)vv, (unsigned char *)&bytes, + SIZEOF_LONG_LONG, IS_LITTLE_ENDIAN, 1); + + /* Plan 9 can't handle PY_LONG_LONG in ? : expressions */ + if (res < 0) + return (PY_LONG_LONG)-1; + else + return bytes; } /* Get a C unsigned PY_LONG_LONG int from a long int object. @@ -1189,31 +1189,31 @@ unsigned PY_LONG_LONG PyLong_AsUnsignedLongLong(PyObject *vv) { - PyLongObject *v; - unsigned PY_LONG_LONG bytes; - int one = 1; - int res; - - if (vv == NULL || !PyLong_Check(vv)) { - PyErr_BadInternalCall(); - return (unsigned PY_LONG_LONG)-1; - } - - v = (PyLongObject*)vv; - switch(Py_SIZE(v)) { - case 0: return 0; - case 1: return v->ob_digit[0]; - } - - res = _PyLong_AsByteArray( - (PyLongObject *)vv, (unsigned char *)&bytes, - SIZEOF_LONG_LONG, IS_LITTLE_ENDIAN, 0); - - /* Plan 9 can't handle PY_LONG_LONG in ? : expressions */ - if (res < 0) - return (unsigned PY_LONG_LONG)res; - else - return bytes; + PyLongObject *v; + unsigned PY_LONG_LONG bytes; + int one = 1; + int res; + + if (vv == NULL || !PyLong_Check(vv)) { + PyErr_BadInternalCall(); + return (unsigned PY_LONG_LONG)-1; + } + + v = (PyLongObject*)vv; + switch(Py_SIZE(v)) { + case 0: return 0; + case 1: return v->ob_digit[0]; + } + + res = _PyLong_AsByteArray( + (PyLongObject *)vv, (unsigned char *)&bytes, + SIZEOF_LONG_LONG, IS_LITTLE_ENDIAN, 0); + + /* Plan 9 can't handle PY_LONG_LONG in ? : expressions */ + if (res < 0) + return (unsigned PY_LONG_LONG)res; + else + return bytes; } /* Get a C unsigned long int from a long int object, ignoring the high bits. @@ -1222,66 +1222,66 @@ static unsigned PY_LONG_LONG _PyLong_AsUnsignedLongLongMask(PyObject *vv) { - register PyLongObject *v; - unsigned PY_LONG_LONG x; - Py_ssize_t i; - int sign; - - if (vv == NULL || !PyLong_Check(vv)) { - PyErr_BadInternalCall(); - return (unsigned long) -1; - } - v = (PyLongObject *)vv; - switch(Py_SIZE(v)) { - case 0: return 0; - case 1: return v->ob_digit[0]; - } - i = Py_SIZE(v); - sign = 1; - x = 0; - if (i < 0) { - sign = -1; - i = -i; - } - while (--i >= 0) { - x = (x << PyLong_SHIFT) | v->ob_digit[i]; - } - return x * sign; + register PyLongObject *v; + unsigned PY_LONG_LONG x; + Py_ssize_t i; + int sign; + + if (vv == NULL || !PyLong_Check(vv)) { + PyErr_BadInternalCall(); + return (unsigned long) -1; + } + v = (PyLongObject *)vv; + switch(Py_SIZE(v)) { + case 0: return 0; + case 1: return v->ob_digit[0]; + } + i = Py_SIZE(v); + sign = 1; + x = 0; + if (i < 0) { + sign = -1; + i = -i; + } + while (--i >= 0) { + x = (x << PyLong_SHIFT) | v->ob_digit[i]; + } + return x * sign; } unsigned PY_LONG_LONG PyLong_AsUnsignedLongLongMask(register PyObject *op) { - PyNumberMethods *nb; - PyLongObject *lo; - unsigned PY_LONG_LONG val; - - if (op && PyLong_Check(op)) - return _PyLong_AsUnsignedLongLongMask(op); - - if (op == NULL || (nb = op->ob_type->tp_as_number) == NULL || - nb->nb_int == NULL) { - PyErr_SetString(PyExc_TypeError, "an integer is required"); - return (unsigned PY_LONG_LONG)-1; - } - - lo = (PyLongObject*) (*nb->nb_int) (op); - if (lo == NULL) - return (unsigned PY_LONG_LONG)-1; - if (PyLong_Check(lo)) { - val = _PyLong_AsUnsignedLongLongMask((PyObject *)lo); - Py_DECREF(lo); - if (PyErr_Occurred()) - return (unsigned PY_LONG_LONG)-1; - return val; - } - else - { - Py_DECREF(lo); - PyErr_SetString(PyExc_TypeError, - "nb_int should return int object"); - return (unsigned PY_LONG_LONG)-1; - } + PyNumberMethods *nb; + PyLongObject *lo; + unsigned PY_LONG_LONG val; + + if (op && PyLong_Check(op)) + return _PyLong_AsUnsignedLongLongMask(op); + + if (op == NULL || (nb = op->ob_type->tp_as_number) == NULL || + nb->nb_int == NULL) { + PyErr_SetString(PyExc_TypeError, "an integer is required"); + return (unsigned PY_LONG_LONG)-1; + } + + lo = (PyLongObject*) (*nb->nb_int) (op); + if (lo == NULL) + return (unsigned PY_LONG_LONG)-1; + if (PyLong_Check(lo)) { + val = _PyLong_AsUnsignedLongLongMask((PyObject *)lo); + Py_DECREF(lo); + if (PyErr_Occurred()) + return (unsigned PY_LONG_LONG)-1; + return val; + } + else + { + Py_DECREF(lo); + PyErr_SetString(PyExc_TypeError, + "nb_int should return int object"); + return (unsigned PY_LONG_LONG)-1; + } } #undef IS_LITTLE_ENDIAN @@ -1296,116 +1296,116 @@ PY_LONG_LONG PyLong_AsLongLongAndOverflow(PyObject *vv, int *overflow) { - /* This version by Tim Peters */ - register PyLongObject *v; - unsigned PY_LONG_LONG x, prev; - PY_LONG_LONG res; - Py_ssize_t i; - int sign; - int do_decref = 0; /* if nb_int was called */ - - *overflow = 0; - if (vv == NULL) { - PyErr_BadInternalCall(); - return -1; - } - - if (!PyLong_Check(vv)) { - PyNumberMethods *nb; - nb = vv->ob_type->tp_as_number; - if (nb == NULL || nb->nb_int == NULL) { - PyErr_SetString(PyExc_TypeError, - "an integer is required"); - return -1; - } - vv = (*nb->nb_int) (vv); - if (vv == NULL) - return -1; - do_decref = 1; - if (!PyLong_Check(vv)) { - Py_DECREF(vv); - PyErr_SetString(PyExc_TypeError, - "nb_int should return int object"); - return -1; - } - } - - res = -1; - v = (PyLongObject *)vv; - i = Py_SIZE(v); - - switch (i) { - case -1: - res = -(sdigit)v->ob_digit[0]; - break; - case 0: - res = 0; - break; - case 1: - res = v->ob_digit[0]; - break; - default: - sign = 1; - x = 0; - if (i < 0) { - sign = -1; - i = -(i); - } - while (--i >= 0) { - prev = x; - x = (x << PyLong_SHIFT) + v->ob_digit[i]; - if ((x >> PyLong_SHIFT) != prev) { - *overflow = sign; - goto exit; - } - } - /* Haven't lost any bits, but casting to long requires extra - * care (see comment above). - */ - if (x <= (unsigned PY_LONG_LONG)PY_LLONG_MAX) { - res = (PY_LONG_LONG)x * sign; - } - else if (sign < 0 && x == PY_ABS_LLONG_MIN) { - res = PY_LLONG_MIN; - } - else { - *overflow = sign; - /* res is already set to -1 */ - } - } + /* This version by Tim Peters */ + register PyLongObject *v; + unsigned PY_LONG_LONG x, prev; + PY_LONG_LONG res; + Py_ssize_t i; + int sign; + int do_decref = 0; /* if nb_int was called */ + + *overflow = 0; + if (vv == NULL) { + PyErr_BadInternalCall(); + return -1; + } + + if (!PyLong_Check(vv)) { + PyNumberMethods *nb; + nb = vv->ob_type->tp_as_number; + if (nb == NULL || nb->nb_int == NULL) { + PyErr_SetString(PyExc_TypeError, + "an integer is required"); + return -1; + } + vv = (*nb->nb_int) (vv); + if (vv == NULL) + return -1; + do_decref = 1; + if (!PyLong_Check(vv)) { + Py_DECREF(vv); + PyErr_SetString(PyExc_TypeError, + "nb_int should return int object"); + return -1; + } + } + + res = -1; + v = (PyLongObject *)vv; + i = Py_SIZE(v); + + switch (i) { + case -1: + res = -(sdigit)v->ob_digit[0]; + break; + case 0: + res = 0; + break; + case 1: + res = v->ob_digit[0]; + break; + default: + sign = 1; + x = 0; + if (i < 0) { + sign = -1; + i = -(i); + } + while (--i >= 0) { + prev = x; + x = (x << PyLong_SHIFT) + v->ob_digit[i]; + if ((x >> PyLong_SHIFT) != prev) { + *overflow = sign; + goto exit; + } + } + /* Haven't lost any bits, but casting to long requires extra + * care (see comment above). + */ + if (x <= (unsigned PY_LONG_LONG)PY_LLONG_MAX) { + res = (PY_LONG_LONG)x * sign; + } + else if (sign < 0 && x == PY_ABS_LLONG_MIN) { + res = PY_LLONG_MIN; + } + else { + *overflow = sign; + /* res is already set to -1 */ + } + } exit: - if (do_decref) { - Py_DECREF(vv); - } - return res; + if (do_decref) { + Py_DECREF(vv); + } + return res; } #endif /* HAVE_LONG_LONG */ #define CHECK_BINOP(v,w) \ - if (!PyLong_Check(v) || !PyLong_Check(w)) { \ - Py_INCREF(Py_NotImplemented); \ - return Py_NotImplemented; \ - } + if (!PyLong_Check(v) || !PyLong_Check(w)) { \ + Py_INCREF(Py_NotImplemented); \ + return Py_NotImplemented; \ + } /* bits_in_digit(d) returns the unique integer k such that 2**(k-1) <= d < 2**k if d is nonzero, else 0. */ static const unsigned char BitLengthTable[32] = { - 0, 1, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 4, 4, 4, 4, - 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5 + 0, 1, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 4, 4, 4, 4, + 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5 }; static int bits_in_digit(digit d) { - int d_bits = 0; - while (d >= 32) { - d_bits += 6; - d >>= 6; - } - d_bits += (int)BitLengthTable[d]; - return d_bits; + int d_bits = 0; + while (d >= 32) { + d_bits += 6; + d >>= 6; + } + d_bits += (int)BitLengthTable[d]; + return d_bits; } /* x[0:m] and y[0:n] are digit vectors, LSD first, m >= n required. x[0:n] @@ -1415,23 +1415,23 @@ static digit v_iadd(digit *x, Py_ssize_t m, digit *y, Py_ssize_t n) { - Py_ssize_t i; - digit carry = 0; + Py_ssize_t i; + digit carry = 0; - assert(m >= n); - for (i = 0; i < n; ++i) { - carry += x[i] + y[i]; - x[i] = carry & PyLong_MASK; - carry >>= PyLong_SHIFT; - assert((carry & 1) == carry); - } - for (; carry && i < m; ++i) { - carry += x[i]; - x[i] = carry & PyLong_MASK; - carry >>= PyLong_SHIFT; - assert((carry & 1) == carry); - } - return carry; + assert(m >= n); + for (i = 0; i < n; ++i) { + carry += x[i] + y[i]; + x[i] = carry & PyLong_MASK; + carry >>= PyLong_SHIFT; + assert((carry & 1) == carry); + } + for (; carry && i < m; ++i) { + carry += x[i]; + x[i] = carry & PyLong_MASK; + carry >>= PyLong_SHIFT; + assert((carry & 1) == carry); + } + return carry; } /* x[0:m] and y[0:n] are digit vectors, LSD first, m >= n required. x[0:n] @@ -1441,23 +1441,23 @@ static digit v_isub(digit *x, Py_ssize_t m, digit *y, Py_ssize_t n) { - Py_ssize_t i; - digit borrow = 0; + Py_ssize_t i; + digit borrow = 0; - assert(m >= n); - for (i = 0; i < n; ++i) { - borrow = x[i] - y[i] - borrow; - x[i] = borrow & PyLong_MASK; - borrow >>= PyLong_SHIFT; - borrow &= 1; /* keep only 1 sign bit */ - } - for (; borrow && i < m; ++i) { - borrow = x[i] - borrow; - x[i] = borrow & PyLong_MASK; - borrow >>= PyLong_SHIFT; - borrow &= 1; - } - return borrow; + assert(m >= n); + for (i = 0; i < n; ++i) { + borrow = x[i] - y[i] - borrow; + x[i] = borrow & PyLong_MASK; + borrow >>= PyLong_SHIFT; + borrow &= 1; /* keep only 1 sign bit */ + } + for (; borrow && i < m; ++i) { + borrow = x[i] - borrow; + x[i] = borrow & PyLong_MASK; + borrow >>= PyLong_SHIFT; + borrow &= 1; + } + return borrow; } /* Shift digit vector a[0:m] d bits left, with 0 <= d < PyLong_SHIFT. Put @@ -1466,16 +1466,16 @@ static digit v_lshift(digit *z, digit *a, Py_ssize_t m, int d) { - Py_ssize_t i; - digit carry = 0; + Py_ssize_t i; + digit carry = 0; - assert(0 <= d && d < PyLong_SHIFT); - for (i=0; i < m; i++) { - twodigits acc = (twodigits)a[i] << d | carry; - z[i] = (digit)acc & PyLong_MASK; - carry = (digit)(acc >> PyLong_SHIFT); - } - return carry; + assert(0 <= d && d < PyLong_SHIFT); + for (i=0; i < m; i++) { + twodigits acc = (twodigits)a[i] << d | carry; + z[i] = (digit)acc & PyLong_MASK; + carry = (digit)(acc >> PyLong_SHIFT); + } + return carry; } /* Shift digit vector a[0:m] d bits right, with 0 <= d < PyLong_SHIFT. Put @@ -1484,17 +1484,17 @@ static digit v_rshift(digit *z, digit *a, Py_ssize_t m, int d) { - Py_ssize_t i; - digit carry = 0; - digit mask = ((digit)1 << d) - 1U; - - assert(0 <= d && d < PyLong_SHIFT); - for (i=m; i-- > 0;) { - twodigits acc = (twodigits)carry << PyLong_SHIFT | a[i]; - carry = (digit)acc & mask; - z[i] = (digit)(acc >> d); - } - return carry; + Py_ssize_t i; + digit carry = 0; + digit mask = ((digit)1 << d) - 1U; + + assert(0 <= d && d < PyLong_SHIFT); + for (i=m; i-- > 0;) { + twodigits acc = (twodigits)carry << PyLong_SHIFT | a[i]; + carry = (digit)acc & mask; + z[i] = (digit)(acc >> d); + } + return carry; } /* Divide long pin, w/ size digits, by non-zero digit n, storing quotient @@ -1506,18 +1506,18 @@ static digit inplace_divrem1(digit *pout, digit *pin, Py_ssize_t size, digit n) { - twodigits rem = 0; + twodigits rem = 0; - assert(n > 0 && n <= PyLong_MASK); - pin += size; - pout += size; - while (--size >= 0) { - digit hi; - rem = (rem << PyLong_SHIFT) | *--pin; - *--pout = hi = (digit)(rem / n); - rem -= (twodigits)hi * n; - } - return (digit)rem; + assert(n > 0 && n <= PyLong_MASK); + pin += size; + pout += size; + while (--size >= 0) { + digit hi; + rem = (rem << PyLong_SHIFT) | *--pin; + *--pout = hi = (digit)(rem / n); + rem -= (twodigits)hi * n; + } + return (digit)rem; } /* Divide a long integer by a digit, returning both the quotient @@ -1527,15 +1527,15 @@ static PyLongObject * divrem1(PyLongObject *a, digit n, digit *prem) { - const Py_ssize_t size = ABS(Py_SIZE(a)); - PyLongObject *z; + const Py_ssize_t size = ABS(Py_SIZE(a)); + PyLongObject *z; - assert(n > 0 && n <= PyLong_MASK); - z = _PyLong_New(size); - if (z == NULL) - return NULL; - *prem = inplace_divrem1(z->ob_digit, a->ob_digit, size, n); - return long_normalize(z); + assert(n > 0 && n <= PyLong_MASK); + z = _PyLong_New(size); + if (z == NULL) + return NULL; + *prem = inplace_divrem1(z->ob_digit, a->ob_digit, size, n); + return long_normalize(z); } /* Convert a long integer to a base 10 string. Returns a new non-shared @@ -1545,111 +1545,111 @@ static PyObject * long_to_decimal_string(PyObject *aa) { - PyLongObject *scratch, *a; - PyObject *str; - Py_ssize_t size, strlen, size_a, i, j; - digit *pout, *pin, rem, tenpow; - Py_UNICODE *p; - int negative; - - a = (PyLongObject *)aa; - if (a == NULL || !PyLong_Check(a)) { - PyErr_BadInternalCall(); - return NULL; - } - size_a = ABS(Py_SIZE(a)); - negative = Py_SIZE(a) < 0; - - /* quick and dirty upper bound for the number of digits - required to express a in base _PyLong_DECIMAL_BASE: - - #digits = 1 + floor(log2(a) / log2(_PyLong_DECIMAL_BASE)) - - But log2(a) < size_a * PyLong_SHIFT, and - log2(_PyLong_DECIMAL_BASE) = log2(10) * _PyLong_DECIMAL_SHIFT - > 3 * _PyLong_DECIMAL_SHIFT - */ - if (size_a > PY_SSIZE_T_MAX / PyLong_SHIFT) { - PyErr_SetString(PyExc_OverflowError, - "long is too large to format"); - return NULL; - } - /* the expression size_a * PyLong_SHIFT is now safe from overflow */ - size = 1 + size_a * PyLong_SHIFT / (3 * _PyLong_DECIMAL_SHIFT); - scratch = _PyLong_New(size); - if (scratch == NULL) - return NULL; - - /* convert array of base _PyLong_BASE digits in pin to an array of - base _PyLong_DECIMAL_BASE digits in pout, following Knuth (TAOCP, - Volume 2 (3rd edn), section 4.4, Method 1b). */ - pin = a->ob_digit; - pout = scratch->ob_digit; - size = 0; - for (i = size_a; --i >= 0; ) { - digit hi = pin[i]; - for (j = 0; j < size; j++) { - twodigits z = (twodigits)pout[j] << PyLong_SHIFT | hi; - hi = (digit)(z / _PyLong_DECIMAL_BASE); - pout[j] = (digit)(z - (twodigits)hi * - _PyLong_DECIMAL_BASE); - } - while (hi) { - pout[size++] = hi % _PyLong_DECIMAL_BASE; - hi /= _PyLong_DECIMAL_BASE; - } - /* check for keyboard interrupt */ - SIGCHECK({ - Py_DECREF(scratch); - return NULL; - }) - } - /* pout should have at least one digit, so that the case when a = 0 - works correctly */ - if (size == 0) - pout[size++] = 0; - - /* calculate exact length of output string, and allocate */ - strlen = negative + 1 + (size - 1) * _PyLong_DECIMAL_SHIFT; - tenpow = 10; - rem = pout[size-1]; - while (rem >= tenpow) { - tenpow *= 10; - strlen++; - } - str = PyUnicode_FromUnicode(NULL, strlen); - if (str == NULL) { - Py_DECREF(scratch); - return NULL; - } - - /* fill the string right-to-left */ - p = PyUnicode_AS_UNICODE(str) + strlen; - *p = '\0'; - /* pout[0] through pout[size-2] contribute exactly - _PyLong_DECIMAL_SHIFT digits each */ - for (i=0; i < size - 1; i++) { - rem = pout[i]; - for (j = 0; j < _PyLong_DECIMAL_SHIFT; j++) { - *--p = '0' + rem % 10; - rem /= 10; - } - } - /* pout[size-1]: always produce at least one decimal digit */ - rem = pout[i]; - do { - *--p = '0' + rem % 10; - rem /= 10; - } while (rem != 0); - - /* and sign */ - if (negative) - *--p = '-'; - - /* check we've counted correctly */ - assert(p == PyUnicode_AS_UNICODE(str)); - Py_DECREF(scratch); - return (PyObject *)str; + PyLongObject *scratch, *a; + PyObject *str; + Py_ssize_t size, strlen, size_a, i, j; + digit *pout, *pin, rem, tenpow; + Py_UNICODE *p; + int negative; + + a = (PyLongObject *)aa; + if (a == NULL || !PyLong_Check(a)) { + PyErr_BadInternalCall(); + return NULL; + } + size_a = ABS(Py_SIZE(a)); + negative = Py_SIZE(a) < 0; + + /* quick and dirty upper bound for the number of digits + required to express a in base _PyLong_DECIMAL_BASE: + + #digits = 1 + floor(log2(a) / log2(_PyLong_DECIMAL_BASE)) + + But log2(a) < size_a * PyLong_SHIFT, and + log2(_PyLong_DECIMAL_BASE) = log2(10) * _PyLong_DECIMAL_SHIFT + > 3 * _PyLong_DECIMAL_SHIFT + */ + if (size_a > PY_SSIZE_T_MAX / PyLong_SHIFT) { + PyErr_SetString(PyExc_OverflowError, + "long is too large to format"); + return NULL; + } + /* the expression size_a * PyLong_SHIFT is now safe from overflow */ + size = 1 + size_a * PyLong_SHIFT / (3 * _PyLong_DECIMAL_SHIFT); + scratch = _PyLong_New(size); + if (scratch == NULL) + return NULL; + + /* convert array of base _PyLong_BASE digits in pin to an array of + base _PyLong_DECIMAL_BASE digits in pout, following Knuth (TAOCP, + Volume 2 (3rd edn), section 4.4, Method 1b). */ + pin = a->ob_digit; + pout = scratch->ob_digit; + size = 0; + for (i = size_a; --i >= 0; ) { + digit hi = pin[i]; + for (j = 0; j < size; j++) { + twodigits z = (twodigits)pout[j] << PyLong_SHIFT | hi; + hi = (digit)(z / _PyLong_DECIMAL_BASE); + pout[j] = (digit)(z - (twodigits)hi * + _PyLong_DECIMAL_BASE); + } + while (hi) { + pout[size++] = hi % _PyLong_DECIMAL_BASE; + hi /= _PyLong_DECIMAL_BASE; + } + /* check for keyboard interrupt */ + SIGCHECK({ + Py_DECREF(scratch); + return NULL; + }) + } + /* pout should have at least one digit, so that the case when a = 0 + works correctly */ + if (size == 0) + pout[size++] = 0; + + /* calculate exact length of output string, and allocate */ + strlen = negative + 1 + (size - 1) * _PyLong_DECIMAL_SHIFT; + tenpow = 10; + rem = pout[size-1]; + while (rem >= tenpow) { + tenpow *= 10; + strlen++; + } + str = PyUnicode_FromUnicode(NULL, strlen); + if (str == NULL) { + Py_DECREF(scratch); + return NULL; + } + + /* fill the string right-to-left */ + p = PyUnicode_AS_UNICODE(str) + strlen; + *p = '\0'; + /* pout[0] through pout[size-2] contribute exactly + _PyLong_DECIMAL_SHIFT digits each */ + for (i=0; i < size - 1; i++) { + rem = pout[i]; + for (j = 0; j < _PyLong_DECIMAL_SHIFT; j++) { + *--p = '0' + rem % 10; + rem /= 10; + } + } + /* pout[size-1]: always produce at least one decimal digit */ + rem = pout[i]; + do { + *--p = '0' + rem % 10; + rem /= 10; + } while (rem != 0); + + /* and sign */ + if (negative) + *--p = '-'; + + /* check we've counted correctly */ + assert(p == PyUnicode_AS_UNICODE(str)); + Py_DECREF(scratch); + return (PyObject *)str; } /* Convert a long int object to a string, using a given conversion base, @@ -1659,102 +1659,102 @@ PyObject * _PyLong_Format(PyObject *aa, int base) { - register PyLongObject *a = (PyLongObject *)aa; - PyObject *str; - Py_ssize_t i, sz; - Py_ssize_t size_a; - Py_UNICODE *p, sign = '\0'; - int bits; - - assert(base == 2 || base == 8 || base == 10 || base == 16); - if (base == 10) - return long_to_decimal_string((PyObject *)a); - - if (a == NULL || !PyLong_Check(a)) { - PyErr_BadInternalCall(); - return NULL; - } - size_a = ABS(Py_SIZE(a)); - - /* Compute a rough upper bound for the length of the string */ - switch (base) { - case 16: - bits = 4; - break; - case 8: - bits = 3; - break; - case 2: - bits = 1; - break; - default: - assert(0); /* shouldn't ever get here */ - bits = 0; /* to silence gcc warning */ - } - /* compute length of output string: allow 2 characters for prefix and - 1 for possible '-' sign. */ - if (size_a > (PY_SSIZE_T_MAX - 3) / PyLong_SHIFT) { - PyErr_SetString(PyExc_OverflowError, - "int is too large to format"); - return NULL; - } - /* now size_a * PyLong_SHIFT + 3 <= PY_SSIZE_T_MAX, so the RHS below - is safe from overflow */ - sz = 3 + (size_a * PyLong_SHIFT + (bits - 1)) / bits; - assert(sz >= 0); - str = PyUnicode_FromUnicode(NULL, sz); - if (str == NULL) - return NULL; - p = PyUnicode_AS_UNICODE(str) + sz; - *p = '\0'; - if (Py_SIZE(a) < 0) - sign = '-'; - - if (Py_SIZE(a) == 0) { - *--p = '0'; - } - else { - /* JRH: special case for power-of-2 bases */ - twodigits accum = 0; - int accumbits = 0; /* # of bits in accum */ - for (i = 0; i < size_a; ++i) { - accum |= (twodigits)a->ob_digit[i] << accumbits; - accumbits += PyLong_SHIFT; - assert(accumbits >= bits); - do { - Py_UNICODE cdigit; - cdigit = (Py_UNICODE)(accum & (base - 1)); - cdigit += (cdigit < 10) ? '0' : 'a'-10; - assert(p > PyUnicode_AS_UNICODE(str)); - *--p = cdigit; - accumbits -= bits; - accum >>= bits; - } while (i < size_a-1 ? accumbits >= bits : accum > 0); - } - } - - if (base == 16) - *--p = 'x'; - else if (base == 8) - *--p = 'o'; - else /* (base == 2) */ - *--p = 'b'; - *--p = '0'; - if (sign) - *--p = sign; - if (p != PyUnicode_AS_UNICODE(str)) { - Py_UNICODE *q = PyUnicode_AS_UNICODE(str); - assert(p > q); - do { - } while ((*q++ = *p++) != '\0'); - q--; - if (PyUnicode_Resize(&str,(Py_ssize_t) (q - - PyUnicode_AS_UNICODE(str)))) { - Py_DECREF(str); - return NULL; - } - } - return (PyObject *)str; + register PyLongObject *a = (PyLongObject *)aa; + PyObject *str; + Py_ssize_t i, sz; + Py_ssize_t size_a; + Py_UNICODE *p, sign = '\0'; + int bits; + + assert(base == 2 || base == 8 || base == 10 || base == 16); + if (base == 10) + return long_to_decimal_string((PyObject *)a); + + if (a == NULL || !PyLong_Check(a)) { + PyErr_BadInternalCall(); + return NULL; + } + size_a = ABS(Py_SIZE(a)); + + /* Compute a rough upper bound for the length of the string */ + switch (base) { + case 16: + bits = 4; + break; + case 8: + bits = 3; + break; + case 2: + bits = 1; + break; + default: + assert(0); /* shouldn't ever get here */ + bits = 0; /* to silence gcc warning */ + } + /* compute length of output string: allow 2 characters for prefix and + 1 for possible '-' sign. */ + if (size_a > (PY_SSIZE_T_MAX - 3) / PyLong_SHIFT) { + PyErr_SetString(PyExc_OverflowError, + "int is too large to format"); + return NULL; + } + /* now size_a * PyLong_SHIFT + 3 <= PY_SSIZE_T_MAX, so the RHS below + is safe from overflow */ + sz = 3 + (size_a * PyLong_SHIFT + (bits - 1)) / bits; + assert(sz >= 0); + str = PyUnicode_FromUnicode(NULL, sz); + if (str == NULL) + return NULL; + p = PyUnicode_AS_UNICODE(str) + sz; + *p = '\0'; + if (Py_SIZE(a) < 0) + sign = '-'; + + if (Py_SIZE(a) == 0) { + *--p = '0'; + } + else { + /* JRH: special case for power-of-2 bases */ + twodigits accum = 0; + int accumbits = 0; /* # of bits in accum */ + for (i = 0; i < size_a; ++i) { + accum |= (twodigits)a->ob_digit[i] << accumbits; + accumbits += PyLong_SHIFT; + assert(accumbits >= bits); + do { + Py_UNICODE cdigit; + cdigit = (Py_UNICODE)(accum & (base - 1)); + cdigit += (cdigit < 10) ? '0' : 'a'-10; + assert(p > PyUnicode_AS_UNICODE(str)); + *--p = cdigit; + accumbits -= bits; + accum >>= bits; + } while (i < size_a-1 ? accumbits >= bits : accum > 0); + } + } + + if (base == 16) + *--p = 'x'; + else if (base == 8) + *--p = 'o'; + else /* (base == 2) */ + *--p = 'b'; + *--p = '0'; + if (sign) + *--p = sign; + if (p != PyUnicode_AS_UNICODE(str)) { + Py_UNICODE *q = PyUnicode_AS_UNICODE(str); + assert(p > q); + do { + } while ((*q++ = *p++) != '\0'); + q--; + if (PyUnicode_Resize(&str,(Py_ssize_t) (q - + PyUnicode_AS_UNICODE(str)))) { + Py_DECREF(str); + return NULL; + } + } + return (PyObject *)str; } /* Table of digit values for 8-bit string -> integer conversion. @@ -1765,22 +1765,22 @@ * base B digit iff _PyLong_DigitValue[Py_CHARPyLong_MASK(c)] < B. */ unsigned char _PyLong_DigitValue[256] = { - 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, - 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, - 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, - 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 37, 37, 37, 37, 37, 37, - 37, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, - 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 37, 37, 37, 37, 37, - 37, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, - 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 37, 37, 37, 37, 37, - 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, - 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, - 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, - 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, - 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, - 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, - 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, - 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, + 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, + 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, + 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, + 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 37, 37, 37, 37, 37, 37, + 37, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, + 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 37, 37, 37, 37, 37, + 37, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, + 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 37, 37, 37, 37, 37, + 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, + 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, + 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, + 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, + 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, + 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, + 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, + 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, }; /* *str points to the first digit in a string of base `base` digits. base @@ -1792,111 +1792,111 @@ static PyLongObject * long_from_binary_base(char **str, int base) { - char *p = *str; - char *start = p; - int bits_per_char; - Py_ssize_t n; - PyLongObject *z; - twodigits accum; - int bits_in_accum; - digit *pdigit; - - assert(base >= 2 && base <= 32 && (base & (base - 1)) == 0); - n = base; - for (bits_per_char = -1; n; ++bits_per_char) - n >>= 1; - /* n <- total # of bits needed, while setting p to end-of-string */ - while (_PyLong_DigitValue[Py_CHARMASK(*p)] < base) - ++p; - *str = p; - /* n <- # of Python digits needed, = ceiling(n/PyLong_SHIFT). */ - n = (p - start) * bits_per_char + PyLong_SHIFT - 1; - if (n / bits_per_char < p - start) { - PyErr_SetString(PyExc_ValueError, - "int string too large to convert"); - return NULL; - } - n = n / PyLong_SHIFT; - z = _PyLong_New(n); - if (z == NULL) - return NULL; - /* Read string from right, and fill in long from left; i.e., - * from least to most significant in both. - */ - accum = 0; - bits_in_accum = 0; - pdigit = z->ob_digit; - while (--p >= start) { - int k = (int)_PyLong_DigitValue[Py_CHARMASK(*p)]; - assert(k >= 0 && k < base); - accum |= (twodigits)k << bits_in_accum; - bits_in_accum += bits_per_char; - if (bits_in_accum >= PyLong_SHIFT) { - *pdigit++ = (digit)(accum & PyLong_MASK); - assert(pdigit - z->ob_digit <= n); - accum >>= PyLong_SHIFT; - bits_in_accum -= PyLong_SHIFT; - assert(bits_in_accum < PyLong_SHIFT); - } - } - if (bits_in_accum) { - assert(bits_in_accum <= PyLong_SHIFT); - *pdigit++ = (digit)accum; - assert(pdigit - z->ob_digit <= n); - } - while (pdigit - z->ob_digit < n) - *pdigit++ = 0; - return long_normalize(z); + char *p = *str; + char *start = p; + int bits_per_char; + Py_ssize_t n; + PyLongObject *z; + twodigits accum; + int bits_in_accum; + digit *pdigit; + + assert(base >= 2 && base <= 32 && (base & (base - 1)) == 0); + n = base; + for (bits_per_char = -1; n; ++bits_per_char) + n >>= 1; + /* n <- total # of bits needed, while setting p to end-of-string */ + while (_PyLong_DigitValue[Py_CHARMASK(*p)] < base) + ++p; + *str = p; + /* n <- # of Python digits needed, = ceiling(n/PyLong_SHIFT). */ + n = (p - start) * bits_per_char + PyLong_SHIFT - 1; + if (n / bits_per_char < p - start) { + PyErr_SetString(PyExc_ValueError, + "int string too large to convert"); + return NULL; + } + n = n / PyLong_SHIFT; + z = _PyLong_New(n); + if (z == NULL) + return NULL; + /* Read string from right, and fill in long from left; i.e., + * from least to most significant in both. + */ + accum = 0; + bits_in_accum = 0; + pdigit = z->ob_digit; + while (--p >= start) { + int k = (int)_PyLong_DigitValue[Py_CHARMASK(*p)]; + assert(k >= 0 && k < base); + accum |= (twodigits)k << bits_in_accum; + bits_in_accum += bits_per_char; + if (bits_in_accum >= PyLong_SHIFT) { + *pdigit++ = (digit)(accum & PyLong_MASK); + assert(pdigit - z->ob_digit <= n); + accum >>= PyLong_SHIFT; + bits_in_accum -= PyLong_SHIFT; + assert(bits_in_accum < PyLong_SHIFT); + } + } + if (bits_in_accum) { + assert(bits_in_accum <= PyLong_SHIFT); + *pdigit++ = (digit)accum; + assert(pdigit - z->ob_digit <= n); + } + while (pdigit - z->ob_digit < n) + *pdigit++ = 0; + return long_normalize(z); } PyObject * PyLong_FromString(char *str, char **pend, int base) { - int sign = 1, error_if_nonzero = 0; - char *start, *orig_str = str; - PyLongObject *z = NULL; - PyObject *strobj; - Py_ssize_t slen; - - if ((base != 0 && base < 2) || base > 36) { - PyErr_SetString(PyExc_ValueError, - "int() arg 2 must be >= 2 and <= 36"); - return NULL; - } - while (*str != '\0' && isspace(Py_CHARMASK(*str))) - str++; - if (*str == '+') - ++str; - else if (*str == '-') { - ++str; - sign = -1; - } - if (base == 0) { - if (str[0] != '0') - base = 10; - else if (str[1] == 'x' || str[1] == 'X') - base = 16; - else if (str[1] == 'o' || str[1] == 'O') - base = 8; - else if (str[1] == 'b' || str[1] == 'B') - base = 2; - else { - /* "old" (C-style) octal literal, now invalid. - it might still be zero though */ - error_if_nonzero = 1; - base = 10; - } - } - if (str[0] == '0' && - ((base == 16 && (str[1] == 'x' || str[1] == 'X')) || - (base == 8 && (str[1] == 'o' || str[1] == 'O')) || - (base == 2 && (str[1] == 'b' || str[1] == 'B')))) - str += 2; - - start = str; - if ((base & (base - 1)) == 0) - z = long_from_binary_base(&str, base); - else { + int sign = 1, error_if_nonzero = 0; + char *start, *orig_str = str; + PyLongObject *z = NULL; + PyObject *strobj; + Py_ssize_t slen; + + if ((base != 0 && base < 2) || base > 36) { + PyErr_SetString(PyExc_ValueError, + "int() arg 2 must be >= 2 and <= 36"); + return NULL; + } + while (*str != '\0' && isspace(Py_CHARMASK(*str))) + str++; + if (*str == '+') + ++str; + else if (*str == '-') { + ++str; + sign = -1; + } + if (base == 0) { + if (str[0] != '0') + base = 10; + else if (str[1] == 'x' || str[1] == 'X') + base = 16; + else if (str[1] == 'o' || str[1] == 'O') + base = 8; + else if (str[1] == 'b' || str[1] == 'B') + base = 2; + else { + /* "old" (C-style) octal literal, now invalid. + it might still be zero though */ + error_if_nonzero = 1; + base = 10; + } + } + if (str[0] == '0' && + ((base == 16 && (str[1] == 'x' || str[1] == 'X')) || + (base == 8 && (str[1] == 'o' || str[1] == 'O')) || + (base == 2 && (str[1] == 'b' || str[1] == 'B')))) + str += 2; + + start = str; + if ((base & (base - 1)) == 0) + z = long_from_binary_base(&str, base); + else { /*** Binary bases can be converted in time linear in the number of digits, because Python's representation base is binary. Other bases (including decimal!) use @@ -1982,227 +1982,227 @@ just 1 digit at the start, so that the copying code was exercised for every digit beyond the first. ***/ - register twodigits c; /* current input character */ - Py_ssize_t size_z; - int i; - int convwidth; - twodigits convmultmax, convmult; - digit *pz, *pzstop; - char* scan; - - static double log_base_BASE[37] = {0.0e0,}; - static int convwidth_base[37] = {0,}; - static twodigits convmultmax_base[37] = {0,}; - - if (log_base_BASE[base] == 0.0) { - twodigits convmax = base; - int i = 1; - - log_base_BASE[base] = log((double)base) / - log((double)PyLong_BASE); - for (;;) { - twodigits next = convmax * base; - if (next > PyLong_BASE) - break; - convmax = next; - ++i; - } - convmultmax_base[base] = convmax; - assert(i > 0); - convwidth_base[base] = i; - } - - /* Find length of the string of numeric characters. */ - scan = str; - while (_PyLong_DigitValue[Py_CHARMASK(*scan)] < base) - ++scan; - - /* Create a long object that can contain the largest possible - * integer with this base and length. Note that there's no - * need to initialize z->ob_digit -- no slot is read up before - * being stored into. - */ - size_z = (Py_ssize_t)((scan - str) * log_base_BASE[base]) + 1; - /* Uncomment next line to test exceedingly rare copy code */ - /* size_z = 1; */ - assert(size_z > 0); - z = _PyLong_New(size_z); - if (z == NULL) - return NULL; - Py_SIZE(z) = 0; - - /* `convwidth` consecutive input digits are treated as a single - * digit in base `convmultmax`. - */ - convwidth = convwidth_base[base]; - convmultmax = convmultmax_base[base]; - - /* Work ;-) */ - while (str < scan) { - /* grab up to convwidth digits from the input string */ - c = (digit)_PyLong_DigitValue[Py_CHARMASK(*str++)]; - for (i = 1; i < convwidth && str != scan; ++i, ++str) { - c = (twodigits)(c * base + - (int)_PyLong_DigitValue[Py_CHARMASK(*str)]); - assert(c < PyLong_BASE); - } - - convmult = convmultmax; - /* Calculate the shift only if we couldn't get - * convwidth digits. - */ - if (i != convwidth) { - convmult = base; - for ( ; i > 1; --i) - convmult *= base; - } - - /* Multiply z by convmult, and add c. */ - pz = z->ob_digit; - pzstop = pz + Py_SIZE(z); - for (; pz < pzstop; ++pz) { - c += (twodigits)*pz * convmult; - *pz = (digit)(c & PyLong_MASK); - c >>= PyLong_SHIFT; - } - /* carry off the current end? */ - if (c) { - assert(c < PyLong_BASE); - if (Py_SIZE(z) < size_z) { - *pz = (digit)c; - ++Py_SIZE(z); - } - else { - PyLongObject *tmp; - /* Extremely rare. Get more space. */ - assert(Py_SIZE(z) == size_z); - tmp = _PyLong_New(size_z + 1); - if (tmp == NULL) { - Py_DECREF(z); - return NULL; - } - memcpy(tmp->ob_digit, - z->ob_digit, - sizeof(digit) * size_z); - Py_DECREF(z); - z = tmp; - z->ob_digit[size_z] = (digit)c; - ++size_z; - } - } - } - } - if (z == NULL) - return NULL; - if (error_if_nonzero) { - /* reset the base to 0, else the exception message - doesn't make too much sense */ - base = 0; - if (Py_SIZE(z) != 0) - goto onError; - /* there might still be other problems, therefore base - remains zero here for the same reason */ - } - if (str == start) - goto onError; - if (sign < 0) - Py_SIZE(z) = -(Py_SIZE(z)); - while (*str && isspace(Py_CHARMASK(*str))) - str++; - if (*str != '\0') - goto onError; - if (pend) - *pend = str; - long_normalize(z); - return (PyObject *) maybe_small_long(z); + register twodigits c; /* current input character */ + Py_ssize_t size_z; + int i; + int convwidth; + twodigits convmultmax, convmult; + digit *pz, *pzstop; + char* scan; + + static double log_base_BASE[37] = {0.0e0,}; + static int convwidth_base[37] = {0,}; + static twodigits convmultmax_base[37] = {0,}; + + if (log_base_BASE[base] == 0.0) { + twodigits convmax = base; + int i = 1; + + log_base_BASE[base] = log((double)base) / + log((double)PyLong_BASE); + for (;;) { + twodigits next = convmax * base; + if (next > PyLong_BASE) + break; + convmax = next; + ++i; + } + convmultmax_base[base] = convmax; + assert(i > 0); + convwidth_base[base] = i; + } + + /* Find length of the string of numeric characters. */ + scan = str; + while (_PyLong_DigitValue[Py_CHARMASK(*scan)] < base) + ++scan; + + /* Create a long object that can contain the largest possible + * integer with this base and length. Note that there's no + * need to initialize z->ob_digit -- no slot is read up before + * being stored into. + */ + size_z = (Py_ssize_t)((scan - str) * log_base_BASE[base]) + 1; + /* Uncomment next line to test exceedingly rare copy code */ + /* size_z = 1; */ + assert(size_z > 0); + z = _PyLong_New(size_z); + if (z == NULL) + return NULL; + Py_SIZE(z) = 0; + + /* `convwidth` consecutive input digits are treated as a single + * digit in base `convmultmax`. + */ + convwidth = convwidth_base[base]; + convmultmax = convmultmax_base[base]; + + /* Work ;-) */ + while (str < scan) { + /* grab up to convwidth digits from the input string */ + c = (digit)_PyLong_DigitValue[Py_CHARMASK(*str++)]; + for (i = 1; i < convwidth && str != scan; ++i, ++str) { + c = (twodigits)(c * base + + (int)_PyLong_DigitValue[Py_CHARMASK(*str)]); + assert(c < PyLong_BASE); + } + + convmult = convmultmax; + /* Calculate the shift only if we couldn't get + * convwidth digits. + */ + if (i != convwidth) { + convmult = base; + for ( ; i > 1; --i) + convmult *= base; + } + + /* Multiply z by convmult, and add c. */ + pz = z->ob_digit; + pzstop = pz + Py_SIZE(z); + for (; pz < pzstop; ++pz) { + c += (twodigits)*pz * convmult; + *pz = (digit)(c & PyLong_MASK); + c >>= PyLong_SHIFT; + } + /* carry off the current end? */ + if (c) { + assert(c < PyLong_BASE); + if (Py_SIZE(z) < size_z) { + *pz = (digit)c; + ++Py_SIZE(z); + } + else { + PyLongObject *tmp; + /* Extremely rare. Get more space. */ + assert(Py_SIZE(z) == size_z); + tmp = _PyLong_New(size_z + 1); + if (tmp == NULL) { + Py_DECREF(z); + return NULL; + } + memcpy(tmp->ob_digit, + z->ob_digit, + sizeof(digit) * size_z); + Py_DECREF(z); + z = tmp; + z->ob_digit[size_z] = (digit)c; + ++size_z; + } + } + } + } + if (z == NULL) + return NULL; + if (error_if_nonzero) { + /* reset the base to 0, else the exception message + doesn't make too much sense */ + base = 0; + if (Py_SIZE(z) != 0) + goto onError; + /* there might still be other problems, therefore base + remains zero here for the same reason */ + } + if (str == start) + goto onError; + if (sign < 0) + Py_SIZE(z) = -(Py_SIZE(z)); + while (*str && isspace(Py_CHARMASK(*str))) + str++; + if (*str != '\0') + goto onError; + if (pend) + *pend = str; + long_normalize(z); + return (PyObject *) maybe_small_long(z); onError: - Py_XDECREF(z); - slen = strlen(orig_str) < 200 ? strlen(orig_str) : 200; - strobj = PyUnicode_FromStringAndSize(orig_str, slen); - if (strobj == NULL) - return NULL; - PyErr_Format(PyExc_ValueError, - "invalid literal for int() with base %d: %R", - base, strobj); - Py_DECREF(strobj); - return NULL; + Py_XDECREF(z); + slen = strlen(orig_str) < 200 ? strlen(orig_str) : 200; + strobj = PyUnicode_FromStringAndSize(orig_str, slen); + if (strobj == NULL) + return NULL; + PyErr_Format(PyExc_ValueError, + "invalid literal for int() with base %d: %R", + base, strobj); + Py_DECREF(strobj); + return NULL; } PyObject * PyLong_FromUnicode(Py_UNICODE *u, Py_ssize_t length, int base) { - PyObject *result; - char *buffer = (char *)PyMem_MALLOC(length+1); + PyObject *result; + char *buffer = (char *)PyMem_MALLOC(length+1); - if (buffer == NULL) - return NULL; + if (buffer == NULL) + return NULL; - if (PyUnicode_EncodeDecimal(u, length, buffer, NULL)) { - PyMem_FREE(buffer); - return NULL; - } - result = PyLong_FromString(buffer, NULL, base); - PyMem_FREE(buffer); - return result; + if (PyUnicode_EncodeDecimal(u, length, buffer, NULL)) { + PyMem_FREE(buffer); + return NULL; + } + result = PyLong_FromString(buffer, NULL, base); + PyMem_FREE(buffer); + return result; } /* forward */ static PyLongObject *x_divrem - (PyLongObject *, PyLongObject *, PyLongObject **); + (PyLongObject *, PyLongObject *, PyLongObject **); static PyObject *long_long(PyObject *v); /* Long division with remainder, top-level routine */ static int long_divrem(PyLongObject *a, PyLongObject *b, - PyLongObject **pdiv, PyLongObject **prem) + PyLongObject **pdiv, PyLongObject **prem) { - Py_ssize_t size_a = ABS(Py_SIZE(a)), size_b = ABS(Py_SIZE(b)); - PyLongObject *z; + Py_ssize_t size_a = ABS(Py_SIZE(a)), size_b = ABS(Py_SIZE(b)); + PyLongObject *z; - if (size_b == 0) { - PyErr_SetString(PyExc_ZeroDivisionError, - "integer division or modulo by zero"); - return -1; - } - if (size_a < size_b || - (size_a == size_b && - a->ob_digit[size_a-1] < b->ob_digit[size_b-1])) { - /* |a| < |b|. */ - *pdiv = (PyLongObject*)PyLong_FromLong(0); - if (*pdiv == NULL) - return -1; - Py_INCREF(a); - *prem = (PyLongObject *) a; - return 0; - } - if (size_b == 1) { - digit rem = 0; - z = divrem1(a, b->ob_digit[0], &rem); - if (z == NULL) - return -1; - *prem = (PyLongObject *) PyLong_FromLong((long)rem); - if (*prem == NULL) { - Py_DECREF(z); - return -1; - } - } - else { - z = x_divrem(a, b, prem); - if (z == NULL) - return -1; - } - /* Set the signs. - The quotient z has the sign of a*b; - the remainder r has the sign of a, - so a = b*z + r. */ - if ((Py_SIZE(a) < 0) != (Py_SIZE(b) < 0)) - NEGATE(z); - if (Py_SIZE(a) < 0 && Py_SIZE(*prem) != 0) - NEGATE(*prem); - *pdiv = maybe_small_long(z); - return 0; + if (size_b == 0) { + PyErr_SetString(PyExc_ZeroDivisionError, + "integer division or modulo by zero"); + return -1; + } + if (size_a < size_b || + (size_a == size_b && + a->ob_digit[size_a-1] < b->ob_digit[size_b-1])) { + /* |a| < |b|. */ + *pdiv = (PyLongObject*)PyLong_FromLong(0); + if (*pdiv == NULL) + return -1; + Py_INCREF(a); + *prem = (PyLongObject *) a; + return 0; + } + if (size_b == 1) { + digit rem = 0; + z = divrem1(a, b->ob_digit[0], &rem); + if (z == NULL) + return -1; + *prem = (PyLongObject *) PyLong_FromLong((long)rem); + if (*prem == NULL) { + Py_DECREF(z); + return -1; + } + } + else { + z = x_divrem(a, b, prem); + if (z == NULL) + return -1; + } + /* Set the signs. + The quotient z has the sign of a*b; + the remainder r has the sign of a, + so a = b*z + r. */ + if ((Py_SIZE(a) < 0) != (Py_SIZE(b) < 0)) + NEGATE(z); + if (Py_SIZE(a) < 0 && Py_SIZE(*prem) != 0) + NEGATE(*prem); + *pdiv = maybe_small_long(z); + return 0; } /* Unsigned long division with remainder -- the algorithm. The arguments v1 @@ -2211,125 +2211,125 @@ static PyLongObject * x_divrem(PyLongObject *v1, PyLongObject *w1, PyLongObject **prem) { - PyLongObject *v, *w, *a; - Py_ssize_t i, k, size_v, size_w; - int d; - digit wm1, wm2, carry, q, r, vtop, *v0, *vk, *w0, *ak; - twodigits vv; - sdigit zhi; - stwodigits z; - - /* We follow Knuth [The Art of Computer Programming, Vol. 2 (3rd - edn.), section 4.3.1, Algorithm D], except that we don't explicitly - handle the special case when the initial estimate q for a quotient - digit is >= PyLong_BASE: the max value for q is PyLong_BASE+1, and - that won't overflow a digit. */ - - /* allocate space; w will also be used to hold the final remainder */ - size_v = ABS(Py_SIZE(v1)); - size_w = ABS(Py_SIZE(w1)); - assert(size_v >= size_w && size_w >= 2); /* Assert checks by div() */ - v = _PyLong_New(size_v+1); - if (v == NULL) { - *prem = NULL; - return NULL; - } - w = _PyLong_New(size_w); - if (w == NULL) { - Py_DECREF(v); - *prem = NULL; - return NULL; - } - - /* normalize: shift w1 left so that its top digit is >= PyLong_BASE/2. - shift v1 left by the same amount. Results go into w and v. */ - d = PyLong_SHIFT - bits_in_digit(w1->ob_digit[size_w-1]); - carry = v_lshift(w->ob_digit, w1->ob_digit, size_w, d); - assert(carry == 0); - carry = v_lshift(v->ob_digit, v1->ob_digit, size_v, d); - if (carry != 0 || v->ob_digit[size_v-1] >= w->ob_digit[size_w-1]) { - v->ob_digit[size_v] = carry; - size_v++; - } - - /* Now v->ob_digit[size_v-1] < w->ob_digit[size_w-1], so quotient has - at most (and usually exactly) k = size_v - size_w digits. */ - k = size_v - size_w; - assert(k >= 0); - a = _PyLong_New(k); - if (a == NULL) { - Py_DECREF(w); - Py_DECREF(v); - *prem = NULL; - return NULL; - } - v0 = v->ob_digit; - w0 = w->ob_digit; - wm1 = w0[size_w-1]; - wm2 = w0[size_w-2]; - for (vk = v0+k, ak = a->ob_digit + k; vk-- > v0;) { - /* inner loop: divide vk[0:size_w+1] by w0[0:size_w], giving - single-digit quotient q, remainder in vk[0:size_w]. */ - - SIGCHECK({ - Py_DECREF(a); - Py_DECREF(w); - Py_DECREF(v); - *prem = NULL; - return NULL; - }) - - /* estimate quotient digit q; may overestimate by 1 (rare) */ - vtop = vk[size_w]; - assert(vtop <= wm1); - vv = ((twodigits)vtop << PyLong_SHIFT) | vk[size_w-1]; - q = (digit)(vv / wm1); - r = (digit)(vv - (twodigits)wm1 * q); /* r = vv % wm1 */ - while ((twodigits)wm2 * q > (((twodigits)r << PyLong_SHIFT) - | vk[size_w-2])) { - --q; - r += wm1; - if (r >= PyLong_BASE) - break; - } - assert(q <= PyLong_BASE); - - /* subtract q*w0[0:size_w] from vk[0:size_w+1] */ - zhi = 0; - for (i = 0; i < size_w; ++i) { - /* invariants: -PyLong_BASE <= -q <= zhi <= 0; - -PyLong_BASE * q <= z < PyLong_BASE */ - z = (sdigit)vk[i] + zhi - - (stwodigits)q * (stwodigits)w0[i]; - vk[i] = (digit)z & PyLong_MASK; - zhi = (sdigit)Py_ARITHMETIC_RIGHT_SHIFT(stwodigits, - z, PyLong_SHIFT); - } - - /* add w back if q was too large (this branch taken rarely) */ - assert((sdigit)vtop + zhi == -1 || (sdigit)vtop + zhi == 0); - if ((sdigit)vtop + zhi < 0) { - carry = 0; - for (i = 0; i < size_w; ++i) { - carry += vk[i] + w0[i]; - vk[i] = carry & PyLong_MASK; - carry >>= PyLong_SHIFT; - } - --q; - } - - /* store quotient digit */ - assert(q < PyLong_BASE); - *--ak = q; - } - - /* unshift remainder; we reuse w to store the result */ - carry = v_rshift(w0, v0, size_w, d); - assert(carry==0); - Py_DECREF(v); + PyLongObject *v, *w, *a; + Py_ssize_t i, k, size_v, size_w; + int d; + digit wm1, wm2, carry, q, r, vtop, *v0, *vk, *w0, *ak; + twodigits vv; + sdigit zhi; + stwodigits z; + + /* We follow Knuth [The Art of Computer Programming, Vol. 2 (3rd + edn.), section 4.3.1, Algorithm D], except that we don't explicitly + handle the special case when the initial estimate q for a quotient + digit is >= PyLong_BASE: the max value for q is PyLong_BASE+1, and + that won't overflow a digit. */ + + /* allocate space; w will also be used to hold the final remainder */ + size_v = ABS(Py_SIZE(v1)); + size_w = ABS(Py_SIZE(w1)); + assert(size_v >= size_w && size_w >= 2); /* Assert checks by div() */ + v = _PyLong_New(size_v+1); + if (v == NULL) { + *prem = NULL; + return NULL; + } + w = _PyLong_New(size_w); + if (w == NULL) { + Py_DECREF(v); + *prem = NULL; + return NULL; + } + + /* normalize: shift w1 left so that its top digit is >= PyLong_BASE/2. + shift v1 left by the same amount. Results go into w and v. */ + d = PyLong_SHIFT - bits_in_digit(w1->ob_digit[size_w-1]); + carry = v_lshift(w->ob_digit, w1->ob_digit, size_w, d); + assert(carry == 0); + carry = v_lshift(v->ob_digit, v1->ob_digit, size_v, d); + if (carry != 0 || v->ob_digit[size_v-1] >= w->ob_digit[size_w-1]) { + v->ob_digit[size_v] = carry; + size_v++; + } + + /* Now v->ob_digit[size_v-1] < w->ob_digit[size_w-1], so quotient has + at most (and usually exactly) k = size_v - size_w digits. */ + k = size_v - size_w; + assert(k >= 0); + a = _PyLong_New(k); + if (a == NULL) { + Py_DECREF(w); + Py_DECREF(v); + *prem = NULL; + return NULL; + } + v0 = v->ob_digit; + w0 = w->ob_digit; + wm1 = w0[size_w-1]; + wm2 = w0[size_w-2]; + for (vk = v0+k, ak = a->ob_digit + k; vk-- > v0;) { + /* inner loop: divide vk[0:size_w+1] by w0[0:size_w], giving + single-digit quotient q, remainder in vk[0:size_w]. */ + + SIGCHECK({ + Py_DECREF(a); + Py_DECREF(w); + Py_DECREF(v); + *prem = NULL; + return NULL; + }) + + /* estimate quotient digit q; may overestimate by 1 (rare) */ + vtop = vk[size_w]; + assert(vtop <= wm1); + vv = ((twodigits)vtop << PyLong_SHIFT) | vk[size_w-1]; + q = (digit)(vv / wm1); + r = (digit)(vv - (twodigits)wm1 * q); /* r = vv % wm1 */ + while ((twodigits)wm2 * q > (((twodigits)r << PyLong_SHIFT) + | vk[size_w-2])) { + --q; + r += wm1; + if (r >= PyLong_BASE) + break; + } + assert(q <= PyLong_BASE); + + /* subtract q*w0[0:size_w] from vk[0:size_w+1] */ + zhi = 0; + for (i = 0; i < size_w; ++i) { + /* invariants: -PyLong_BASE <= -q <= zhi <= 0; + -PyLong_BASE * q <= z < PyLong_BASE */ + z = (sdigit)vk[i] + zhi - + (stwodigits)q * (stwodigits)w0[i]; + vk[i] = (digit)z & PyLong_MASK; + zhi = (sdigit)Py_ARITHMETIC_RIGHT_SHIFT(stwodigits, + z, PyLong_SHIFT); + } + + /* add w back if q was too large (this branch taken rarely) */ + assert((sdigit)vtop + zhi == -1 || (sdigit)vtop + zhi == 0); + if ((sdigit)vtop + zhi < 0) { + carry = 0; + for (i = 0; i < size_w; ++i) { + carry += vk[i] + w0[i]; + vk[i] = carry & PyLong_MASK; + carry >>= PyLong_SHIFT; + } + --q; + } + + /* store quotient digit */ + assert(q < PyLong_BASE); + *--ak = q; + } + + /* unshift remainder; we reuse w to store the result */ + carry = v_rshift(w0, v0, size_w, d); + assert(carry==0); + Py_DECREF(v); - *prem = long_normalize(w); - return long_normalize(a); + *prem = long_normalize(w); + return long_normalize(a); } /* For a nonzero PyLong a, express a in the form x * 2**e, with 0.5 <= @@ -2349,111 +2349,111 @@ double _PyLong_Frexp(PyLongObject *a, Py_ssize_t *e) { - Py_ssize_t a_size, a_bits, shift_digits, shift_bits, x_size; - /* See below for why x_digits is always large enough. */ - digit rem, x_digits[2 + (DBL_MANT_DIG + 1) / PyLong_SHIFT]; - double dx; - /* Correction term for round-half-to-even rounding. For a digit x, - "x + half_even_correction[x & 7]" gives x rounded to the nearest - multiple of 4, rounding ties to a multiple of 8. */ - static const int half_even_correction[8] = {0, -1, -2, 1, 0, -1, 2, 1}; - - a_size = ABS(Py_SIZE(a)); - if (a_size == 0) { - /* Special case for 0: significand 0.0, exponent 0. */ - *e = 0; - return 0.0; - } - a_bits = bits_in_digit(a->ob_digit[a_size-1]); - /* The following is an overflow-free version of the check - "if ((a_size - 1) * PyLong_SHIFT + a_bits > PY_SSIZE_T_MAX) ..." */ - if (a_size >= (PY_SSIZE_T_MAX - 1) / PyLong_SHIFT + 1 && - (a_size > (PY_SSIZE_T_MAX - 1) / PyLong_SHIFT + 1 || - a_bits > (PY_SSIZE_T_MAX - 1) % PyLong_SHIFT + 1)) - goto overflow; - a_bits = (a_size - 1) * PyLong_SHIFT + a_bits; - - /* Shift the first DBL_MANT_DIG + 2 bits of a into x_digits[0:x_size] - (shifting left if a_bits <= DBL_MANT_DIG + 2). - - Number of digits needed for result: write // for floor division. - Then if shifting left, we end up using - - 1 + a_size + (DBL_MANT_DIG + 2 - a_bits) // PyLong_SHIFT - - digits. If shifting right, we use - - a_size - (a_bits - DBL_MANT_DIG - 2) // PyLong_SHIFT - - digits. Using a_size = 1 + (a_bits - 1) // PyLong_SHIFT along with - the inequalities - - m // PyLong_SHIFT + n // PyLong_SHIFT <= (m + n) // PyLong_SHIFT - m // PyLong_SHIFT - n // PyLong_SHIFT <= - 1 + (m - n - 1) // PyLong_SHIFT, - - valid for any integers m and n, we find that x_size satisfies - - x_size <= 2 + (DBL_MANT_DIG + 1) // PyLong_SHIFT - - in both cases. - */ - if (a_bits <= DBL_MANT_DIG + 2) { - shift_digits = (DBL_MANT_DIG + 2 - a_bits) / PyLong_SHIFT; - shift_bits = (DBL_MANT_DIG + 2 - a_bits) % PyLong_SHIFT; - x_size = 0; - while (x_size < shift_digits) - x_digits[x_size++] = 0; - rem = v_lshift(x_digits + x_size, a->ob_digit, a_size, - (int)shift_bits); - x_size += a_size; - x_digits[x_size++] = rem; - } - else { - shift_digits = (a_bits - DBL_MANT_DIG - 2) / PyLong_SHIFT; - shift_bits = (a_bits - DBL_MANT_DIG - 2) % PyLong_SHIFT; - rem = v_rshift(x_digits, a->ob_digit + shift_digits, - a_size - shift_digits, (int)shift_bits); - x_size = a_size - shift_digits; - /* For correct rounding below, we need the least significant - bit of x to be 'sticky' for this shift: if any of the bits - shifted out was nonzero, we set the least significant bit - of x. */ - if (rem) - x_digits[0] |= 1; - else - while (shift_digits > 0) - if (a->ob_digit[--shift_digits]) { - x_digits[0] |= 1; - break; - } - } - assert(1 <= x_size && x_size <= (Py_ssize_t)(sizeof(x_digits)/sizeof(digit))); - - /* Round, and convert to double. */ - x_digits[0] += half_even_correction[x_digits[0] & 7]; - dx = x_digits[--x_size]; - while (x_size > 0) - dx = dx * PyLong_BASE + x_digits[--x_size]; - - /* Rescale; make correction if result is 1.0. */ - dx /= 4.0 * EXP2_DBL_MANT_DIG; - if (dx == 1.0) { - if (a_bits == PY_SSIZE_T_MAX) - goto overflow; - dx = 0.5; - a_bits += 1; - } + Py_ssize_t a_size, a_bits, shift_digits, shift_bits, x_size; + /* See below for why x_digits is always large enough. */ + digit rem, x_digits[2 + (DBL_MANT_DIG + 1) / PyLong_SHIFT]; + double dx; + /* Correction term for round-half-to-even rounding. For a digit x, + "x + half_even_correction[x & 7]" gives x rounded to the nearest + multiple of 4, rounding ties to a multiple of 8. */ + static const int half_even_correction[8] = {0, -1, -2, 1, 0, -1, 2, 1}; + + a_size = ABS(Py_SIZE(a)); + if (a_size == 0) { + /* Special case for 0: significand 0.0, exponent 0. */ + *e = 0; + return 0.0; + } + a_bits = bits_in_digit(a->ob_digit[a_size-1]); + /* The following is an overflow-free version of the check + "if ((a_size - 1) * PyLong_SHIFT + a_bits > PY_SSIZE_T_MAX) ..." */ + if (a_size >= (PY_SSIZE_T_MAX - 1) / PyLong_SHIFT + 1 && + (a_size > (PY_SSIZE_T_MAX - 1) / PyLong_SHIFT + 1 || + a_bits > (PY_SSIZE_T_MAX - 1) % PyLong_SHIFT + 1)) + goto overflow; + a_bits = (a_size - 1) * PyLong_SHIFT + a_bits; + + /* Shift the first DBL_MANT_DIG + 2 bits of a into x_digits[0:x_size] + (shifting left if a_bits <= DBL_MANT_DIG + 2). + + Number of digits needed for result: write // for floor division. + Then if shifting left, we end up using + + 1 + a_size + (DBL_MANT_DIG + 2 - a_bits) // PyLong_SHIFT + + digits. If shifting right, we use + + a_size - (a_bits - DBL_MANT_DIG - 2) // PyLong_SHIFT + + digits. Using a_size = 1 + (a_bits - 1) // PyLong_SHIFT along with + the inequalities + + m // PyLong_SHIFT + n // PyLong_SHIFT <= (m + n) // PyLong_SHIFT + m // PyLong_SHIFT - n // PyLong_SHIFT <= + 1 + (m - n - 1) // PyLong_SHIFT, + + valid for any integers m and n, we find that x_size satisfies + + x_size <= 2 + (DBL_MANT_DIG + 1) // PyLong_SHIFT + + in both cases. + */ + if (a_bits <= DBL_MANT_DIG + 2) { + shift_digits = (DBL_MANT_DIG + 2 - a_bits) / PyLong_SHIFT; + shift_bits = (DBL_MANT_DIG + 2 - a_bits) % PyLong_SHIFT; + x_size = 0; + while (x_size < shift_digits) + x_digits[x_size++] = 0; + rem = v_lshift(x_digits + x_size, a->ob_digit, a_size, + (int)shift_bits); + x_size += a_size; + x_digits[x_size++] = rem; + } + else { + shift_digits = (a_bits - DBL_MANT_DIG - 2) / PyLong_SHIFT; + shift_bits = (a_bits - DBL_MANT_DIG - 2) % PyLong_SHIFT; + rem = v_rshift(x_digits, a->ob_digit + shift_digits, + a_size - shift_digits, (int)shift_bits); + x_size = a_size - shift_digits; + /* For correct rounding below, we need the least significant + bit of x to be 'sticky' for this shift: if any of the bits + shifted out was nonzero, we set the least significant bit + of x. */ + if (rem) + x_digits[0] |= 1; + else + while (shift_digits > 0) + if (a->ob_digit[--shift_digits]) { + x_digits[0] |= 1; + break; + } + } + assert(1 <= x_size && x_size <= (Py_ssize_t)(sizeof(x_digits)/sizeof(digit))); + + /* Round, and convert to double. */ + x_digits[0] += half_even_correction[x_digits[0] & 7]; + dx = x_digits[--x_size]; + while (x_size > 0) + dx = dx * PyLong_BASE + x_digits[--x_size]; + + /* Rescale; make correction if result is 1.0. */ + dx /= 4.0 * EXP2_DBL_MANT_DIG; + if (dx == 1.0) { + if (a_bits == PY_SSIZE_T_MAX) + goto overflow; + dx = 0.5; + a_bits += 1; + } - *e = a_bits; - return Py_SIZE(a) < 0 ? -dx : dx; + *e = a_bits; + return Py_SIZE(a) < 0 ? -dx : dx; overflow: - /* exponent > PY_SSIZE_T_MAX */ - PyErr_SetString(PyExc_OverflowError, - "huge integer: number of bits overflows a Py_ssize_t"); - *e = 0; - return -1.0; + /* exponent > PY_SSIZE_T_MAX */ + PyErr_SetString(PyExc_OverflowError, + "huge integer: number of bits overflows a Py_ssize_t"); + *e = 0; + return -1.0; } /* Get a C double from a long int object. Rounds to the nearest double, @@ -2462,20 +2462,20 @@ double PyLong_AsDouble(PyObject *v) { - Py_ssize_t exponent; - double x; + Py_ssize_t exponent; + double x; - if (v == NULL || !PyLong_Check(v)) { - PyErr_BadInternalCall(); - return -1.0; - } - x = _PyLong_Frexp((PyLongObject *)v, &exponent); - if ((x == -1.0 && PyErr_Occurred()) || exponent > DBL_MAX_EXP) { - PyErr_SetString(PyExc_OverflowError, - "long int too large to convert to float"); - return -1.0; - } - return ldexp(x, (int)exponent); + if (v == NULL || !PyLong_Check(v)) { + PyErr_BadInternalCall(); + return -1.0; + } + x = _PyLong_Frexp((PyLongObject *)v, &exponent); + if ((x == -1.0 && PyErr_Occurred()) || exponent > DBL_MAX_EXP) { + PyErr_SetString(PyExc_OverflowError, + "long int too large to convert to float"); + return -1.0; + } + return ldexp(x, (int)exponent); } /* Methods */ @@ -2483,109 +2483,109 @@ static void long_dealloc(PyObject *v) { - Py_TYPE(v)->tp_free(v); + Py_TYPE(v)->tp_free(v); } static int long_compare(PyLongObject *a, PyLongObject *b) { - Py_ssize_t sign; + Py_ssize_t sign; - if (Py_SIZE(a) != Py_SIZE(b)) { - sign = Py_SIZE(a) - Py_SIZE(b); - } - else { - Py_ssize_t i = ABS(Py_SIZE(a)); - while (--i >= 0 && a->ob_digit[i] == b->ob_digit[i]) - ; - if (i < 0) - sign = 0; - else { - sign = (sdigit)a->ob_digit[i] - (sdigit)b->ob_digit[i]; - if (Py_SIZE(a) < 0) - sign = -sign; - } - } - return sign < 0 ? -1 : sign > 0 ? 1 : 0; + if (Py_SIZE(a) != Py_SIZE(b)) { + sign = Py_SIZE(a) - Py_SIZE(b); + } + else { + Py_ssize_t i = ABS(Py_SIZE(a)); + while (--i >= 0 && a->ob_digit[i] == b->ob_digit[i]) + ; + if (i < 0) + sign = 0; + else { + sign = (sdigit)a->ob_digit[i] - (sdigit)b->ob_digit[i]; + if (Py_SIZE(a) < 0) + sign = -sign; + } + } + return sign < 0 ? -1 : sign > 0 ? 1 : 0; } #define TEST_COND(cond) \ - ((cond) ? Py_True : Py_False) + ((cond) ? Py_True : Py_False) static PyObject * long_richcompare(PyObject *self, PyObject *other, int op) { - int result; - PyObject *v; - CHECK_BINOP(self, other); - if (self == other) - result = 0; - else - result = long_compare((PyLongObject*)self, (PyLongObject*)other); - /* Convert the return value to a Boolean */ - switch (op) { - case Py_EQ: - v = TEST_COND(result == 0); - break; - case Py_NE: - v = TEST_COND(result != 0); - break; - case Py_LE: - v = TEST_COND(result <= 0); - break; - case Py_GE: - v = TEST_COND(result >= 0); - break; - case Py_LT: - v = TEST_COND(result == -1); - break; - case Py_GT: - v = TEST_COND(result == 1); - break; - default: - PyErr_BadArgument(); - return NULL; - } - Py_INCREF(v); - return v; + int result; + PyObject *v; + CHECK_BINOP(self, other); + if (self == other) + result = 0; + else + result = long_compare((PyLongObject*)self, (PyLongObject*)other); + /* Convert the return value to a Boolean */ + switch (op) { + case Py_EQ: + v = TEST_COND(result == 0); + break; + case Py_NE: + v = TEST_COND(result != 0); + break; + case Py_LE: + v = TEST_COND(result <= 0); + break; + case Py_GE: + v = TEST_COND(result >= 0); + break; + case Py_LT: + v = TEST_COND(result == -1); + break; + case Py_GT: + v = TEST_COND(result == 1); + break; + default: + PyErr_BadArgument(); + return NULL; + } + Py_INCREF(v); + return v; } static long long_hash(PyLongObject *v) { - unsigned long x; - Py_ssize_t i; - int sign; - - i = Py_SIZE(v); - switch(i) { - case -1: return v->ob_digit[0]==1 ? -2 : -(sdigit)v->ob_digit[0]; - case 0: return 0; - case 1: return v->ob_digit[0]; - } - sign = 1; - x = 0; - if (i < 0) { - sign = -1; - i = -(i); - } - /* The following loop produces a C unsigned long x such that x is - congruent to the absolute value of v modulo ULONG_MAX. The - resulting x is nonzero if and only if v is. */ - while (--i >= 0) { - /* Force a native long #-bits (32 or 64) circular shift */ - x = (x >> (8*SIZEOF_LONG-PyLong_SHIFT)) | (x << PyLong_SHIFT); - x += v->ob_digit[i]; - /* If the addition above overflowed we compensate by - incrementing. This preserves the value modulo - ULONG_MAX. */ - if (x < v->ob_digit[i]) - x++; - } - x = x * sign; - if (x == (unsigned long)-1) - x = (unsigned long)-2; - return (long)x; + unsigned long x; + Py_ssize_t i; + int sign; + + i = Py_SIZE(v); + switch(i) { + case -1: return v->ob_digit[0]==1 ? -2 : -(sdigit)v->ob_digit[0]; + case 0: return 0; + case 1: return v->ob_digit[0]; + } + sign = 1; + x = 0; + if (i < 0) { + sign = -1; + i = -(i); + } + /* The following loop produces a C unsigned long x such that x is + congruent to the absolute value of v modulo ULONG_MAX. The + resulting x is nonzero if and only if v is. */ + while (--i >= 0) { + /* Force a native long #-bits (32 or 64) circular shift */ + x = (x >> (8*SIZEOF_LONG-PyLong_SHIFT)) | (x << PyLong_SHIFT); + x += v->ob_digit[i]; + /* If the addition above overflowed we compensate by + incrementing. This preserves the value modulo + ULONG_MAX. */ + if (x < v->ob_digit[i]) + x++; + } + x = x * sign; + if (x == (unsigned long)-1) + x = (unsigned long)-2; + return (long)x; } @@ -2594,33 +2594,33 @@ static PyLongObject * x_add(PyLongObject *a, PyLongObject *b) { - Py_ssize_t size_a = ABS(Py_SIZE(a)), size_b = ABS(Py_SIZE(b)); - PyLongObject *z; - Py_ssize_t i; - digit carry = 0; - - /* Ensure a is the larger of the two: */ - if (size_a < size_b) { - { PyLongObject *temp = a; a = b; b = temp; } - { Py_ssize_t size_temp = size_a; - size_a = size_b; - size_b = size_temp; } - } - z = _PyLong_New(size_a+1); - if (z == NULL) - return NULL; - for (i = 0; i < size_b; ++i) { - carry += a->ob_digit[i] + b->ob_digit[i]; - z->ob_digit[i] = carry & PyLong_MASK; - carry >>= PyLong_SHIFT; - } - for (; i < size_a; ++i) { - carry += a->ob_digit[i]; - z->ob_digit[i] = carry & PyLong_MASK; - carry >>= PyLong_SHIFT; - } - z->ob_digit[i] = carry; - return long_normalize(z); + Py_ssize_t size_a = ABS(Py_SIZE(a)), size_b = ABS(Py_SIZE(b)); + PyLongObject *z; + Py_ssize_t i; + digit carry = 0; + + /* Ensure a is the larger of the two: */ + if (size_a < size_b) { + { PyLongObject *temp = a; a = b; b = temp; } + { Py_ssize_t size_temp = size_a; + size_a = size_b; + size_b = size_temp; } + } + z = _PyLong_New(size_a+1); + if (z == NULL) + return NULL; + for (i = 0; i < size_b; ++i) { + carry += a->ob_digit[i] + b->ob_digit[i]; + z->ob_digit[i] = carry & PyLong_MASK; + carry >>= PyLong_SHIFT; + } + for (; i < size_a; ++i) { + carry += a->ob_digit[i]; + z->ob_digit[i] = carry & PyLong_MASK; + carry >>= PyLong_SHIFT; + } + z->ob_digit[i] = carry; + return long_normalize(z); } /* Subtract the absolute values of two integers. */ @@ -2628,113 +2628,113 @@ static PyLongObject * x_sub(PyLongObject *a, PyLongObject *b) { - Py_ssize_t size_a = ABS(Py_SIZE(a)), size_b = ABS(Py_SIZE(b)); - PyLongObject *z; - Py_ssize_t i; - int sign = 1; - digit borrow = 0; - - /* Ensure a is the larger of the two: */ - if (size_a < size_b) { - sign = -1; - { PyLongObject *temp = a; a = b; b = temp; } - { Py_ssize_t size_temp = size_a; - size_a = size_b; - size_b = size_temp; } - } - else if (size_a == size_b) { - /* Find highest digit where a and b differ: */ - i = size_a; - while (--i >= 0 && a->ob_digit[i] == b->ob_digit[i]) - ; - if (i < 0) - return (PyLongObject *)PyLong_FromLong(0); - if (a->ob_digit[i] < b->ob_digit[i]) { - sign = -1; - { PyLongObject *temp = a; a = b; b = temp; } - } - size_a = size_b = i+1; - } - z = _PyLong_New(size_a); - if (z == NULL) - return NULL; - for (i = 0; i < size_b; ++i) { - /* The following assumes unsigned arithmetic - works module 2**N for some N>PyLong_SHIFT. */ - borrow = a->ob_digit[i] - b->ob_digit[i] - borrow; - z->ob_digit[i] = borrow & PyLong_MASK; - borrow >>= PyLong_SHIFT; - borrow &= 1; /* Keep only one sign bit */ - } - for (; i < size_a; ++i) { - borrow = a->ob_digit[i] - borrow; - z->ob_digit[i] = borrow & PyLong_MASK; - borrow >>= PyLong_SHIFT; - borrow &= 1; /* Keep only one sign bit */ - } - assert(borrow == 0); - if (sign < 0) - NEGATE(z); - return long_normalize(z); + Py_ssize_t size_a = ABS(Py_SIZE(a)), size_b = ABS(Py_SIZE(b)); + PyLongObject *z; + Py_ssize_t i; + int sign = 1; + digit borrow = 0; + + /* Ensure a is the larger of the two: */ + if (size_a < size_b) { + sign = -1; + { PyLongObject *temp = a; a = b; b = temp; } + { Py_ssize_t size_temp = size_a; + size_a = size_b; + size_b = size_temp; } + } + else if (size_a == size_b) { + /* Find highest digit where a and b differ: */ + i = size_a; + while (--i >= 0 && a->ob_digit[i] == b->ob_digit[i]) + ; + if (i < 0) + return (PyLongObject *)PyLong_FromLong(0); + if (a->ob_digit[i] < b->ob_digit[i]) { + sign = -1; + { PyLongObject *temp = a; a = b; b = temp; } + } + size_a = size_b = i+1; + } + z = _PyLong_New(size_a); + if (z == NULL) + return NULL; + for (i = 0; i < size_b; ++i) { + /* The following assumes unsigned arithmetic + works module 2**N for some N>PyLong_SHIFT. */ + borrow = a->ob_digit[i] - b->ob_digit[i] - borrow; + z->ob_digit[i] = borrow & PyLong_MASK; + borrow >>= PyLong_SHIFT; + borrow &= 1; /* Keep only one sign bit */ + } + for (; i < size_a; ++i) { + borrow = a->ob_digit[i] - borrow; + z->ob_digit[i] = borrow & PyLong_MASK; + borrow >>= PyLong_SHIFT; + borrow &= 1; /* Keep only one sign bit */ + } + assert(borrow == 0); + if (sign < 0) + NEGATE(z); + return long_normalize(z); } static PyObject * long_add(PyLongObject *a, PyLongObject *b) { - PyLongObject *z; + PyLongObject *z; - CHECK_BINOP(a, b); + CHECK_BINOP(a, b); - if (ABS(Py_SIZE(a)) <= 1 && ABS(Py_SIZE(b)) <= 1) { - PyObject *result = PyLong_FromLong(MEDIUM_VALUE(a) + - MEDIUM_VALUE(b)); - return result; - } - if (Py_SIZE(a) < 0) { - if (Py_SIZE(b) < 0) { - z = x_add(a, b); - if (z != NULL && Py_SIZE(z) != 0) - Py_SIZE(z) = -(Py_SIZE(z)); - } - else - z = x_sub(b, a); - } - else { - if (Py_SIZE(b) < 0) - z = x_sub(a, b); - else - z = x_add(a, b); - } - return (PyObject *)z; + if (ABS(Py_SIZE(a)) <= 1 && ABS(Py_SIZE(b)) <= 1) { + PyObject *result = PyLong_FromLong(MEDIUM_VALUE(a) + + MEDIUM_VALUE(b)); + return result; + } + if (Py_SIZE(a) < 0) { + if (Py_SIZE(b) < 0) { + z = x_add(a, b); + if (z != NULL && Py_SIZE(z) != 0) + Py_SIZE(z) = -(Py_SIZE(z)); + } + else + z = x_sub(b, a); + } + else { + if (Py_SIZE(b) < 0) + z = x_sub(a, b); + else + z = x_add(a, b); + } + return (PyObject *)z; } static PyObject * long_sub(PyLongObject *a, PyLongObject *b) { - PyLongObject *z; + PyLongObject *z; - CHECK_BINOP(a, b); + CHECK_BINOP(a, b); - if (ABS(Py_SIZE(a)) <= 1 && ABS(Py_SIZE(b)) <= 1) { - PyObject* r; - r = PyLong_FromLong(MEDIUM_VALUE(a)-MEDIUM_VALUE(b)); - return r; - } - if (Py_SIZE(a) < 0) { - if (Py_SIZE(b) < 0) - z = x_sub(a, b); - else - z = x_add(a, b); - if (z != NULL && Py_SIZE(z) != 0) - Py_SIZE(z) = -(Py_SIZE(z)); - } - else { - if (Py_SIZE(b) < 0) - z = x_add(a, b); - else - z = x_sub(a, b); - } - return (PyObject *)z; + if (ABS(Py_SIZE(a)) <= 1 && ABS(Py_SIZE(b)) <= 1) { + PyObject* r; + r = PyLong_FromLong(MEDIUM_VALUE(a)-MEDIUM_VALUE(b)); + return r; + } + if (Py_SIZE(a) < 0) { + if (Py_SIZE(b) < 0) + z = x_sub(a, b); + else + z = x_add(a, b); + if (z != NULL && Py_SIZE(z) != 0) + Py_SIZE(z) = -(Py_SIZE(z)); + } + else { + if (Py_SIZE(b) < 0) + z = x_add(a, b); + else + z = x_sub(a, b); + } + return (PyObject *)z; } /* Grade school multiplication, ignoring the signs. @@ -2743,85 +2743,85 @@ static PyLongObject * x_mul(PyLongObject *a, PyLongObject *b) { - PyLongObject *z; - Py_ssize_t size_a = ABS(Py_SIZE(a)); - Py_ssize_t size_b = ABS(Py_SIZE(b)); - Py_ssize_t i; - - z = _PyLong_New(size_a + size_b); - if (z == NULL) - return NULL; - - memset(z->ob_digit, 0, Py_SIZE(z) * sizeof(digit)); - if (a == b) { - /* Efficient squaring per HAC, Algorithm 14.16: - * http://www.cacr.math.uwaterloo.ca/hac/about/chap14.pdf - * Gives slightly less than a 2x speedup when a == b, - * via exploiting that each entry in the multiplication - * pyramid appears twice (except for the size_a squares). - */ - for (i = 0; i < size_a; ++i) { - twodigits carry; - twodigits f = a->ob_digit[i]; - digit *pz = z->ob_digit + (i << 1); - digit *pa = a->ob_digit + i + 1; - digit *paend = a->ob_digit + size_a; - - SIGCHECK({ - Py_DECREF(z); - return NULL; - }) - - carry = *pz + f * f; - *pz++ = (digit)(carry & PyLong_MASK); - carry >>= PyLong_SHIFT; - assert(carry <= PyLong_MASK); - - /* Now f is added in twice in each column of the - * pyramid it appears. Same as adding f<<1 once. - */ - f <<= 1; - while (pa < paend) { - carry += *pz + *pa++ * f; - *pz++ = (digit)(carry & PyLong_MASK); - carry >>= PyLong_SHIFT; - assert(carry <= (PyLong_MASK << 1)); - } - if (carry) { - carry += *pz; - *pz++ = (digit)(carry & PyLong_MASK); - carry >>= PyLong_SHIFT; - } - if (carry) - *pz += (digit)(carry & PyLong_MASK); - assert((carry >> PyLong_SHIFT) == 0); - } - } - else { /* a is not the same as b -- gradeschool long mult */ - for (i = 0; i < size_a; ++i) { - twodigits carry = 0; - twodigits f = a->ob_digit[i]; - digit *pz = z->ob_digit + i; - digit *pb = b->ob_digit; - digit *pbend = b->ob_digit + size_b; - - SIGCHECK({ - Py_DECREF(z); - return NULL; - }) - - while (pb < pbend) { - carry += *pz + *pb++ * f; - *pz++ = (digit)(carry & PyLong_MASK); - carry >>= PyLong_SHIFT; - assert(carry <= PyLong_MASK); - } - if (carry) - *pz += (digit)(carry & PyLong_MASK); - assert((carry >> PyLong_SHIFT) == 0); - } - } - return long_normalize(z); + PyLongObject *z; + Py_ssize_t size_a = ABS(Py_SIZE(a)); + Py_ssize_t size_b = ABS(Py_SIZE(b)); + Py_ssize_t i; + + z = _PyLong_New(size_a + size_b); + if (z == NULL) + return NULL; + + memset(z->ob_digit, 0, Py_SIZE(z) * sizeof(digit)); + if (a == b) { + /* Efficient squaring per HAC, Algorithm 14.16: + * http://www.cacr.math.uwaterloo.ca/hac/about/chap14.pdf + * Gives slightly less than a 2x speedup when a == b, + * via exploiting that each entry in the multiplication + * pyramid appears twice (except for the size_a squares). + */ + for (i = 0; i < size_a; ++i) { + twodigits carry; + twodigits f = a->ob_digit[i]; + digit *pz = z->ob_digit + (i << 1); + digit *pa = a->ob_digit + i + 1; + digit *paend = a->ob_digit + size_a; + + SIGCHECK({ + Py_DECREF(z); + return NULL; + }) + + carry = *pz + f * f; + *pz++ = (digit)(carry & PyLong_MASK); + carry >>= PyLong_SHIFT; + assert(carry <= PyLong_MASK); + + /* Now f is added in twice in each column of the + * pyramid it appears. Same as adding f<<1 once. + */ + f <<= 1; + while (pa < paend) { + carry += *pz + *pa++ * f; + *pz++ = (digit)(carry & PyLong_MASK); + carry >>= PyLong_SHIFT; + assert(carry <= (PyLong_MASK << 1)); + } + if (carry) { + carry += *pz; + *pz++ = (digit)(carry & PyLong_MASK); + carry >>= PyLong_SHIFT; + } + if (carry) + *pz += (digit)(carry & PyLong_MASK); + assert((carry >> PyLong_SHIFT) == 0); + } + } + else { /* a is not the same as b -- gradeschool long mult */ + for (i = 0; i < size_a; ++i) { + twodigits carry = 0; + twodigits f = a->ob_digit[i]; + digit *pz = z->ob_digit + i; + digit *pb = b->ob_digit; + digit *pbend = b->ob_digit + size_b; + + SIGCHECK({ + Py_DECREF(z); + return NULL; + }) + + while (pb < pbend) { + carry += *pz + *pb++ * f; + *pz++ = (digit)(carry & PyLong_MASK); + carry >>= PyLong_SHIFT; + assert(carry <= PyLong_MASK); + } + if (carry) + *pz += (digit)(carry & PyLong_MASK); + assert((carry >> PyLong_SHIFT) == 0); + } + } + return long_normalize(z); } /* A helper for Karatsuba multiplication (k_mul). @@ -2834,26 +2834,26 @@ static int kmul_split(PyLongObject *n, Py_ssize_t size, PyLongObject **high, PyLongObject **low) { - PyLongObject *hi, *lo; - Py_ssize_t size_lo, size_hi; - const Py_ssize_t size_n = ABS(Py_SIZE(n)); - - size_lo = MIN(size_n, size); - size_hi = size_n - size_lo; - - if ((hi = _PyLong_New(size_hi)) == NULL) - return -1; - if ((lo = _PyLong_New(size_lo)) == NULL) { - Py_DECREF(hi); - return -1; - } - - memcpy(lo->ob_digit, n->ob_digit, size_lo * sizeof(digit)); - memcpy(hi->ob_digit, n->ob_digit + size_lo, size_hi * sizeof(digit)); - - *high = long_normalize(hi); - *low = long_normalize(lo); - return 0; + PyLongObject *hi, *lo; + Py_ssize_t size_lo, size_hi; + const Py_ssize_t size_n = ABS(Py_SIZE(n)); + + size_lo = MIN(size_n, size); + size_hi = size_n - size_lo; + + if ((hi = _PyLong_New(size_hi)) == NULL) + return -1; + if ((lo = _PyLong_New(size_lo)) == NULL) { + Py_DECREF(hi); + return -1; + } + + memcpy(lo->ob_digit, n->ob_digit, size_lo * sizeof(digit)); + memcpy(hi->ob_digit, n->ob_digit + size_lo, size_hi * sizeof(digit)); + + *high = long_normalize(hi); + *low = long_normalize(lo); + return 0; } static PyLongObject *k_lopsided_mul(PyLongObject *a, PyLongObject *b); @@ -2865,169 +2865,169 @@ static PyLongObject * k_mul(PyLongObject *a, PyLongObject *b) { - Py_ssize_t asize = ABS(Py_SIZE(a)); - Py_ssize_t bsize = ABS(Py_SIZE(b)); - PyLongObject *ah = NULL; - PyLongObject *al = NULL; - PyLongObject *bh = NULL; - PyLongObject *bl = NULL; - PyLongObject *ret = NULL; - PyLongObject *t1, *t2, *t3; - Py_ssize_t shift; /* the number of digits we split off */ - Py_ssize_t i; - - /* (ah*X+al)(bh*X+bl) = ah*bh*X*X + (ah*bl + al*bh)*X + al*bl - * Let k = (ah+al)*(bh+bl) = ah*bl + al*bh + ah*bh + al*bl - * Then the original product is - * ah*bh*X*X + (k - ah*bh - al*bl)*X + al*bl - * By picking X to be a power of 2, "*X" is just shifting, and it's - * been reduced to 3 multiplies on numbers half the size. - */ - - /* We want to split based on the larger number; fiddle so that b - * is largest. - */ - if (asize > bsize) { - t1 = a; - a = b; - b = t1; - - i = asize; - asize = bsize; - bsize = i; - } - - /* Use gradeschool math when either number is too small. */ - i = a == b ? KARATSUBA_SQUARE_CUTOFF : KARATSUBA_CUTOFF; - if (asize <= i) { - if (asize == 0) - return (PyLongObject *)PyLong_FromLong(0); - else - return x_mul(a, b); - } - - /* If a is small compared to b, splitting on b gives a degenerate - * case with ah==0, and Karatsuba may be (even much) less efficient - * than "grade school" then. However, we can still win, by viewing - * b as a string of "big digits", each of width a->ob_size. That - * leads to a sequence of balanced calls to k_mul. - */ - if (2 * asize <= bsize) - return k_lopsided_mul(a, b); - - /* Split a & b into hi & lo pieces. */ - shift = bsize >> 1; - if (kmul_split(a, shift, &ah, &al) < 0) goto fail; - assert(Py_SIZE(ah) > 0); /* the split isn't degenerate */ - - if (a == b) { - bh = ah; - bl = al; - Py_INCREF(bh); - Py_INCREF(bl); - } - else if (kmul_split(b, shift, &bh, &bl) < 0) goto fail; - - /* The plan: - * 1. Allocate result space (asize + bsize digits: that's always - * enough). - * 2. Compute ah*bh, and copy into result at 2*shift. - * 3. Compute al*bl, and copy into result at 0. Note that this - * can't overlap with #2. - * 4. Subtract al*bl from the result, starting at shift. This may - * underflow (borrow out of the high digit), but we don't care: - * we're effectively doing unsigned arithmetic mod - * BASE**(sizea + sizeb), and so long as the *final* result fits, - * borrows and carries out of the high digit can be ignored. - * 5. Subtract ah*bh from the result, starting at shift. - * 6. Compute (ah+al)*(bh+bl), and add it into the result starting - * at shift. - */ - - /* 1. Allocate result space. */ - ret = _PyLong_New(asize + bsize); - if (ret == NULL) goto fail; + Py_ssize_t asize = ABS(Py_SIZE(a)); + Py_ssize_t bsize = ABS(Py_SIZE(b)); + PyLongObject *ah = NULL; + PyLongObject *al = NULL; + PyLongObject *bh = NULL; + PyLongObject *bl = NULL; + PyLongObject *ret = NULL; + PyLongObject *t1, *t2, *t3; + Py_ssize_t shift; /* the number of digits we split off */ + Py_ssize_t i; + + /* (ah*X+al)(bh*X+bl) = ah*bh*X*X + (ah*bl + al*bh)*X + al*bl + * Let k = (ah+al)*(bh+bl) = ah*bl + al*bh + ah*bh + al*bl + * Then the original product is + * ah*bh*X*X + (k - ah*bh - al*bl)*X + al*bl + * By picking X to be a power of 2, "*X" is just shifting, and it's + * been reduced to 3 multiplies on numbers half the size. + */ + + /* We want to split based on the larger number; fiddle so that b + * is largest. + */ + if (asize > bsize) { + t1 = a; + a = b; + b = t1; + + i = asize; + asize = bsize; + bsize = i; + } + + /* Use gradeschool math when either number is too small. */ + i = a == b ? KARATSUBA_SQUARE_CUTOFF : KARATSUBA_CUTOFF; + if (asize <= i) { + if (asize == 0) + return (PyLongObject *)PyLong_FromLong(0); + else + return x_mul(a, b); + } + + /* If a is small compared to b, splitting on b gives a degenerate + * case with ah==0, and Karatsuba may be (even much) less efficient + * than "grade school" then. However, we can still win, by viewing + * b as a string of "big digits", each of width a->ob_size. That + * leads to a sequence of balanced calls to k_mul. + */ + if (2 * asize <= bsize) + return k_lopsided_mul(a, b); + + /* Split a & b into hi & lo pieces. */ + shift = bsize >> 1; + if (kmul_split(a, shift, &ah, &al) < 0) goto fail; + assert(Py_SIZE(ah) > 0); /* the split isn't degenerate */ + + if (a == b) { + bh = ah; + bl = al; + Py_INCREF(bh); + Py_INCREF(bl); + } + else if (kmul_split(b, shift, &bh, &bl) < 0) goto fail; + + /* The plan: + * 1. Allocate result space (asize + bsize digits: that's always + * enough). + * 2. Compute ah*bh, and copy into result at 2*shift. + * 3. Compute al*bl, and copy into result at 0. Note that this + * can't overlap with #2. + * 4. Subtract al*bl from the result, starting at shift. This may + * underflow (borrow out of the high digit), but we don't care: + * we're effectively doing unsigned arithmetic mod + * BASE**(sizea + sizeb), and so long as the *final* result fits, + * borrows and carries out of the high digit can be ignored. + * 5. Subtract ah*bh from the result, starting at shift. + * 6. Compute (ah+al)*(bh+bl), and add it into the result starting + * at shift. + */ + + /* 1. Allocate result space. */ + ret = _PyLong_New(asize + bsize); + if (ret == NULL) goto fail; #ifdef Py_DEBUG - /* Fill with trash, to catch reference to uninitialized digits. */ - memset(ret->ob_digit, 0xDF, Py_SIZE(ret) * sizeof(digit)); + /* Fill with trash, to catch reference to uninitialized digits. */ + memset(ret->ob_digit, 0xDF, Py_SIZE(ret) * sizeof(digit)); #endif - /* 2. t1 <- ah*bh, and copy into high digits of result. */ - if ((t1 = k_mul(ah, bh)) == NULL) goto fail; - assert(Py_SIZE(t1) >= 0); - assert(2*shift + Py_SIZE(t1) <= Py_SIZE(ret)); - memcpy(ret->ob_digit + 2*shift, t1->ob_digit, - Py_SIZE(t1) * sizeof(digit)); - - /* Zero-out the digits higher than the ah*bh copy. */ - i = Py_SIZE(ret) - 2*shift - Py_SIZE(t1); - if (i) - memset(ret->ob_digit + 2*shift + Py_SIZE(t1), 0, - i * sizeof(digit)); - - /* 3. t2 <- al*bl, and copy into the low digits. */ - if ((t2 = k_mul(al, bl)) == NULL) { - Py_DECREF(t1); - goto fail; - } - assert(Py_SIZE(t2) >= 0); - assert(Py_SIZE(t2) <= 2*shift); /* no overlap with high digits */ - memcpy(ret->ob_digit, t2->ob_digit, Py_SIZE(t2) * sizeof(digit)); - - /* Zero out remaining digits. */ - i = 2*shift - Py_SIZE(t2); /* number of uninitialized digits */ - if (i) - memset(ret->ob_digit + Py_SIZE(t2), 0, i * sizeof(digit)); - - /* 4 & 5. Subtract ah*bh (t1) and al*bl (t2). We do al*bl first - * because it's fresher in cache. - */ - i = Py_SIZE(ret) - shift; /* # digits after shift */ - (void)v_isub(ret->ob_digit + shift, i, t2->ob_digit, Py_SIZE(t2)); - Py_DECREF(t2); - - (void)v_isub(ret->ob_digit + shift, i, t1->ob_digit, Py_SIZE(t1)); - Py_DECREF(t1); - - /* 6. t3 <- (ah+al)(bh+bl), and add into result. */ - if ((t1 = x_add(ah, al)) == NULL) goto fail; - Py_DECREF(ah); - Py_DECREF(al); - ah = al = NULL; - - if (a == b) { - t2 = t1; - Py_INCREF(t2); - } - else if ((t2 = x_add(bh, bl)) == NULL) { - Py_DECREF(t1); - goto fail; - } - Py_DECREF(bh); - Py_DECREF(bl); - bh = bl = NULL; - - t3 = k_mul(t1, t2); - Py_DECREF(t1); - Py_DECREF(t2); - if (t3 == NULL) goto fail; - assert(Py_SIZE(t3) >= 0); - - /* Add t3. It's not obvious why we can't run out of room here. - * See the (*) comment after this function. - */ - (void)v_iadd(ret->ob_digit + shift, i, t3->ob_digit, Py_SIZE(t3)); - Py_DECREF(t3); + /* 2. t1 <- ah*bh, and copy into high digits of result. */ + if ((t1 = k_mul(ah, bh)) == NULL) goto fail; + assert(Py_SIZE(t1) >= 0); + assert(2*shift + Py_SIZE(t1) <= Py_SIZE(ret)); + memcpy(ret->ob_digit + 2*shift, t1->ob_digit, + Py_SIZE(t1) * sizeof(digit)); + + /* Zero-out the digits higher than the ah*bh copy. */ + i = Py_SIZE(ret) - 2*shift - Py_SIZE(t1); + if (i) + memset(ret->ob_digit + 2*shift + Py_SIZE(t1), 0, + i * sizeof(digit)); + + /* 3. t2 <- al*bl, and copy into the low digits. */ + if ((t2 = k_mul(al, bl)) == NULL) { + Py_DECREF(t1); + goto fail; + } + assert(Py_SIZE(t2) >= 0); + assert(Py_SIZE(t2) <= 2*shift); /* no overlap with high digits */ + memcpy(ret->ob_digit, t2->ob_digit, Py_SIZE(t2) * sizeof(digit)); + + /* Zero out remaining digits. */ + i = 2*shift - Py_SIZE(t2); /* number of uninitialized digits */ + if (i) + memset(ret->ob_digit + Py_SIZE(t2), 0, i * sizeof(digit)); + + /* 4 & 5. Subtract ah*bh (t1) and al*bl (t2). We do al*bl first + * because it's fresher in cache. + */ + i = Py_SIZE(ret) - shift; /* # digits after shift */ + (void)v_isub(ret->ob_digit + shift, i, t2->ob_digit, Py_SIZE(t2)); + Py_DECREF(t2); + + (void)v_isub(ret->ob_digit + shift, i, t1->ob_digit, Py_SIZE(t1)); + Py_DECREF(t1); + + /* 6. t3 <- (ah+al)(bh+bl), and add into result. */ + if ((t1 = x_add(ah, al)) == NULL) goto fail; + Py_DECREF(ah); + Py_DECREF(al); + ah = al = NULL; + + if (a == b) { + t2 = t1; + Py_INCREF(t2); + } + else if ((t2 = x_add(bh, bl)) == NULL) { + Py_DECREF(t1); + goto fail; + } + Py_DECREF(bh); + Py_DECREF(bl); + bh = bl = NULL; + + t3 = k_mul(t1, t2); + Py_DECREF(t1); + Py_DECREF(t2); + if (t3 == NULL) goto fail; + assert(Py_SIZE(t3) >= 0); + + /* Add t3. It's not obvious why we can't run out of room here. + * See the (*) comment after this function. + */ + (void)v_iadd(ret->ob_digit + shift, i, t3->ob_digit, Py_SIZE(t3)); + Py_DECREF(t3); - return long_normalize(ret); + return long_normalize(ret); fail: - Py_XDECREF(ret); - Py_XDECREF(ah); - Py_XDECREF(al); - Py_XDECREF(bh); - Py_XDECREF(bl); - return NULL; + Py_XDECREF(ret); + Py_XDECREF(ah); + Py_XDECREF(al); + Py_XDECREF(bh); + Py_XDECREF(bl); + return NULL; } /* (*) Why adding t3 can't "run out of room" above. @@ -3086,85 +3086,85 @@ static PyLongObject * k_lopsided_mul(PyLongObject *a, PyLongObject *b) { - const Py_ssize_t asize = ABS(Py_SIZE(a)); - Py_ssize_t bsize = ABS(Py_SIZE(b)); - Py_ssize_t nbdone; /* # of b digits already multiplied */ - PyLongObject *ret; - PyLongObject *bslice = NULL; - - assert(asize > KARATSUBA_CUTOFF); - assert(2 * asize <= bsize); - - /* Allocate result space, and zero it out. */ - ret = _PyLong_New(asize + bsize); - if (ret == NULL) - return NULL; - memset(ret->ob_digit, 0, Py_SIZE(ret) * sizeof(digit)); - - /* Successive slices of b are copied into bslice. */ - bslice = _PyLong_New(asize); - if (bslice == NULL) - goto fail; - - nbdone = 0; - while (bsize > 0) { - PyLongObject *product; - const Py_ssize_t nbtouse = MIN(bsize, asize); - - /* Multiply the next slice of b by a. */ - memcpy(bslice->ob_digit, b->ob_digit + nbdone, - nbtouse * sizeof(digit)); - Py_SIZE(bslice) = nbtouse; - product = k_mul(a, bslice); - if (product == NULL) - goto fail; - - /* Add into result. */ - (void)v_iadd(ret->ob_digit + nbdone, Py_SIZE(ret) - nbdone, - product->ob_digit, Py_SIZE(product)); - Py_DECREF(product); - - bsize -= nbtouse; - nbdone += nbtouse; - } + const Py_ssize_t asize = ABS(Py_SIZE(a)); + Py_ssize_t bsize = ABS(Py_SIZE(b)); + Py_ssize_t nbdone; /* # of b digits already multiplied */ + PyLongObject *ret; + PyLongObject *bslice = NULL; + + assert(asize > KARATSUBA_CUTOFF); + assert(2 * asize <= bsize); + + /* Allocate result space, and zero it out. */ + ret = _PyLong_New(asize + bsize); + if (ret == NULL) + return NULL; + memset(ret->ob_digit, 0, Py_SIZE(ret) * sizeof(digit)); + + /* Successive slices of b are copied into bslice. */ + bslice = _PyLong_New(asize); + if (bslice == NULL) + goto fail; + + nbdone = 0; + while (bsize > 0) { + PyLongObject *product; + const Py_ssize_t nbtouse = MIN(bsize, asize); + + /* Multiply the next slice of b by a. */ + memcpy(bslice->ob_digit, b->ob_digit + nbdone, + nbtouse * sizeof(digit)); + Py_SIZE(bslice) = nbtouse; + product = k_mul(a, bslice); + if (product == NULL) + goto fail; + + /* Add into result. */ + (void)v_iadd(ret->ob_digit + nbdone, Py_SIZE(ret) - nbdone, + product->ob_digit, Py_SIZE(product)); + Py_DECREF(product); + + bsize -= nbtouse; + nbdone += nbtouse; + } - Py_DECREF(bslice); - return long_normalize(ret); + Py_DECREF(bslice); + return long_normalize(ret); fail: - Py_DECREF(ret); - Py_XDECREF(bslice); - return NULL; + Py_DECREF(ret); + Py_XDECREF(bslice); + return NULL; } static PyObject * long_mul(PyLongObject *a, PyLongObject *b) { - PyLongObject *z; + PyLongObject *z; - CHECK_BINOP(a, b); + CHECK_BINOP(a, b); - /* fast path for single-digit multiplication */ - if (ABS(Py_SIZE(a)) <= 1 && ABS(Py_SIZE(b)) <= 1) { - stwodigits v = (stwodigits)(MEDIUM_VALUE(a)) * MEDIUM_VALUE(b); + /* fast path for single-digit multiplication */ + if (ABS(Py_SIZE(a)) <= 1 && ABS(Py_SIZE(b)) <= 1) { + stwodigits v = (stwodigits)(MEDIUM_VALUE(a)) * MEDIUM_VALUE(b); #ifdef HAVE_LONG_LONG - return PyLong_FromLongLong((PY_LONG_LONG)v); + return PyLong_FromLongLong((PY_LONG_LONG)v); #else - /* if we don't have long long then we're almost certainly - using 15-bit digits, so v will fit in a long. In the - unlikely event that we're using 30-bit digits on a platform - without long long, a large v will just cause us to fall - through to the general multiplication code below. */ - if (v >= LONG_MIN && v <= LONG_MAX) - return PyLong_FromLong((long)v); + /* if we don't have long long then we're almost certainly + using 15-bit digits, so v will fit in a long. In the + unlikely event that we're using 30-bit digits on a platform + without long long, a large v will just cause us to fall + through to the general multiplication code below. */ + if (v >= LONG_MIN && v <= LONG_MAX) + return PyLong_FromLong((long)v); #endif - } + } - z = k_mul(a, b); - /* Negate if exactly one of the inputs is negative. */ - if (((Py_SIZE(a) ^ Py_SIZE(b)) < 0) && z) - NEGATE(z); - return (PyObject *)z; + z = k_mul(a, b); + /* Negate if exactly one of the inputs is negative. */ + if (((Py_SIZE(a) ^ Py_SIZE(b)) < 0) && z) + NEGATE(z); + return (PyObject *)z; } /* The / and % operators are now defined in terms of divmod(). @@ -3173,11 +3173,11 @@ |a| by |b|, with the sign of a. This is also expressed as a - b*trunc(a/b), if trunc truncates towards zero. Some examples: - a b a rem b a mod b - 13 10 3 3 - -13 10 -3 7 - 13 -10 3 -7 - -13 -10 -3 -3 + a b a rem b a mod b + 13 10 3 3 + -13 10 -3 7 + 13 -10 3 -7 + -13 -10 -3 -3 So, to get from rem to mod, we have to add b if a and b have different signs. We then subtract one from the 'div' part of the outcome to keep the invariant intact. */ @@ -3190,57 +3190,57 @@ */ static int l_divmod(PyLongObject *v, PyLongObject *w, - PyLongObject **pdiv, PyLongObject **pmod) + PyLongObject **pdiv, PyLongObject **pmod) { - PyLongObject *div, *mod; + PyLongObject *div, *mod; - if (long_divrem(v, w, &div, &mod) < 0) - return -1; - if ((Py_SIZE(mod) < 0 && Py_SIZE(w) > 0) || - (Py_SIZE(mod) > 0 && Py_SIZE(w) < 0)) { - PyLongObject *temp; - PyLongObject *one; - temp = (PyLongObject *) long_add(mod, w); - Py_DECREF(mod); - mod = temp; - if (mod == NULL) { - Py_DECREF(div); - return -1; - } - one = (PyLongObject *) PyLong_FromLong(1L); - if (one == NULL || - (temp = (PyLongObject *) long_sub(div, one)) == NULL) { - Py_DECREF(mod); - Py_DECREF(div); - Py_XDECREF(one); - return -1; - } - Py_DECREF(one); - Py_DECREF(div); - div = temp; - } - if (pdiv != NULL) - *pdiv = div; - else - Py_DECREF(div); - - if (pmod != NULL) - *pmod = mod; - else - Py_DECREF(mod); + if (long_divrem(v, w, &div, &mod) < 0) + return -1; + if ((Py_SIZE(mod) < 0 && Py_SIZE(w) > 0) || + (Py_SIZE(mod) > 0 && Py_SIZE(w) < 0)) { + PyLongObject *temp; + PyLongObject *one; + temp = (PyLongObject *) long_add(mod, w); + Py_DECREF(mod); + mod = temp; + if (mod == NULL) { + Py_DECREF(div); + return -1; + } + one = (PyLongObject *) PyLong_FromLong(1L); + if (one == NULL || + (temp = (PyLongObject *) long_sub(div, one)) == NULL) { + Py_DECREF(mod); + Py_DECREF(div); + Py_XDECREF(one); + return -1; + } + Py_DECREF(one); + Py_DECREF(div); + div = temp; + } + if (pdiv != NULL) + *pdiv = div; + else + Py_DECREF(div); + + if (pmod != NULL) + *pmod = mod; + else + Py_DECREF(mod); - return 0; + return 0; } static PyObject * long_div(PyObject *a, PyObject *b) { - PyLongObject *div; + PyLongObject *div; - CHECK_BINOP(a, b); - if (l_divmod((PyLongObject*)a, (PyLongObject*)b, &div, NULL) < 0) - div = NULL; - return (PyObject *)div; + CHECK_BINOP(a, b); + if (l_divmod((PyLongObject*)a, (PyLongObject*)b, &div, NULL) < 0) + div = NULL; + return (PyObject *)div; } /* PyLong/PyLong -> float, with correctly rounded result. */ @@ -3251,631 +3251,631 @@ static PyObject * long_true_divide(PyObject *v, PyObject *w) { - PyLongObject *a, *b, *x; - Py_ssize_t a_size, b_size, shift, extra_bits, diff, x_size, x_bits; - digit mask, low; - int inexact, negate, a_is_small, b_is_small; - double dx, result; - - CHECK_BINOP(v, w); - a = (PyLongObject *)v; - b = (PyLongObject *)w; - - /* - Method in a nutshell: - - 0. reduce to case a, b > 0; filter out obvious underflow/overflow - 1. choose a suitable integer 'shift' - 2. use integer arithmetic to compute x = floor(2**-shift*a/b) - 3. adjust x for correct rounding - 4. convert x to a double dx with the same value - 5. return ldexp(dx, shift). - - In more detail: - - 0. For any a, a/0 raises ZeroDivisionError; for nonzero b, 0/b - returns either 0.0 or -0.0, depending on the sign of b. For a and - b both nonzero, ignore signs of a and b, and add the sign back in - at the end. Now write a_bits and b_bits for the bit lengths of a - and b respectively (that is, a_bits = 1 + floor(log_2(a)); likewise - for b). Then - - 2**(a_bits - b_bits - 1) < a/b < 2**(a_bits - b_bits + 1). - - So if a_bits - b_bits > DBL_MAX_EXP then a/b > 2**DBL_MAX_EXP and - so overflows. Similarly, if a_bits - b_bits < DBL_MIN_EXP - - DBL_MANT_DIG - 1 then a/b underflows to 0. With these cases out of - the way, we can assume that - - DBL_MIN_EXP - DBL_MANT_DIG - 1 <= a_bits - b_bits <= DBL_MAX_EXP. - - 1. The integer 'shift' is chosen so that x has the right number of - bits for a double, plus two or three extra bits that will be used - in the rounding decisions. Writing a_bits and b_bits for the - number of significant bits in a and b respectively, a - straightforward formula for shift is: - - shift = a_bits - b_bits - DBL_MANT_DIG - 2 - - This is fine in the usual case, but if a/b is smaller than the - smallest normal float then it can lead to double rounding on an - IEEE 754 platform, giving incorrectly rounded results. So we - adjust the formula slightly. The actual formula used is: - - shift = MAX(a_bits - b_bits, DBL_MIN_EXP) - DBL_MANT_DIG - 2 - - 2. The quantity x is computed by first shifting a (left -shift bits - if shift <= 0, right shift bits if shift > 0) and then dividing by - b. For both the shift and the division, we keep track of whether - the result is inexact, in a flag 'inexact'; this information is - needed at the rounding stage. - - With the choice of shift above, together with our assumption that - a_bits - b_bits >= DBL_MIN_EXP - DBL_MANT_DIG - 1, it follows - that x >= 1. - - 3. Now x * 2**shift <= a/b < (x+1) * 2**shift. We want to replace - this with an exactly representable float of the form - - round(x/2**extra_bits) * 2**(extra_bits+shift). - - For float representability, we need x/2**extra_bits < - 2**DBL_MANT_DIG and extra_bits + shift >= DBL_MIN_EXP - - DBL_MANT_DIG. This translates to the condition: - - extra_bits >= MAX(x_bits, DBL_MIN_EXP - shift) - DBL_MANT_DIG - - To round, we just modify the bottom digit of x in-place; this can - end up giving a digit with value > PyLONG_MASK, but that's not a - problem since digits can hold values up to 2*PyLONG_MASK+1. - - With the original choices for shift above, extra_bits will always - be 2 or 3. Then rounding under the round-half-to-even rule, we - round up iff the most significant of the extra bits is 1, and - either: (a) the computation of x in step 2 had an inexact result, - or (b) at least one other of the extra bits is 1, or (c) the least - significant bit of x (above those to be rounded) is 1. - - 4. Conversion to a double is straightforward; all floating-point - operations involved in the conversion are exact, so there's no - danger of rounding errors. - - 5. Use ldexp(x, shift) to compute x*2**shift, the final result. - The result will always be exactly representable as a double, except - in the case that it overflows. To avoid dependence on the exact - behaviour of ldexp on overflow, we check for overflow before - applying ldexp. The result of ldexp is adjusted for sign before - returning. - */ - - /* Reduce to case where a and b are both positive. */ - a_size = ABS(Py_SIZE(a)); - b_size = ABS(Py_SIZE(b)); - negate = (Py_SIZE(a) < 0) ^ (Py_SIZE(b) < 0); - if (b_size == 0) { - PyErr_SetString(PyExc_ZeroDivisionError, - "division by zero"); - goto error; - } - if (a_size == 0) - goto underflow_or_zero; - - /* Fast path for a and b small (exactly representable in a double). - Relies on floating-point division being correctly rounded; results - may be subject to double rounding on x86 machines that operate with - the x87 FPU set to 64-bit precision. */ - a_is_small = a_size <= MANT_DIG_DIGITS || - (a_size == MANT_DIG_DIGITS+1 && - a->ob_digit[MANT_DIG_DIGITS] >> MANT_DIG_BITS == 0); - b_is_small = b_size <= MANT_DIG_DIGITS || - (b_size == MANT_DIG_DIGITS+1 && - b->ob_digit[MANT_DIG_DIGITS] >> MANT_DIG_BITS == 0); - if (a_is_small && b_is_small) { - double da, db; - da = a->ob_digit[--a_size]; - while (a_size > 0) - da = da * PyLong_BASE + a->ob_digit[--a_size]; - db = b->ob_digit[--b_size]; - while (b_size > 0) - db = db * PyLong_BASE + b->ob_digit[--b_size]; - result = da / db; - goto success; - } - - /* Catch obvious cases of underflow and overflow */ - diff = a_size - b_size; - if (diff > PY_SSIZE_T_MAX/PyLong_SHIFT - 1) - /* Extreme overflow */ - goto overflow; - else if (diff < 1 - PY_SSIZE_T_MAX/PyLong_SHIFT) - /* Extreme underflow */ - goto underflow_or_zero; - /* Next line is now safe from overflowing a Py_ssize_t */ - diff = diff * PyLong_SHIFT + bits_in_digit(a->ob_digit[a_size - 1]) - - bits_in_digit(b->ob_digit[b_size - 1]); - /* Now diff = a_bits - b_bits. */ - if (diff > DBL_MAX_EXP) - goto overflow; - else if (diff < DBL_MIN_EXP - DBL_MANT_DIG - 1) - goto underflow_or_zero; - - /* Choose value for shift; see comments for step 1 above. */ - shift = MAX(diff, DBL_MIN_EXP) - DBL_MANT_DIG - 2; - - inexact = 0; - - /* x = abs(a * 2**-shift) */ - if (shift <= 0) { - Py_ssize_t i, shift_digits = -shift / PyLong_SHIFT; - digit rem; - /* x = a << -shift */ - if (a_size >= PY_SSIZE_T_MAX - 1 - shift_digits) { - /* In practice, it's probably impossible to end up - here. Both a and b would have to be enormous, - using close to SIZE_T_MAX bytes of memory each. */ - PyErr_SetString(PyExc_OverflowError, - "intermediate overflow during division"); - goto error; - } - x = _PyLong_New(a_size + shift_digits + 1); - if (x == NULL) - goto error; - for (i = 0; i < shift_digits; i++) - x->ob_digit[i] = 0; - rem = v_lshift(x->ob_digit + shift_digits, a->ob_digit, - a_size, -shift % PyLong_SHIFT); - x->ob_digit[a_size + shift_digits] = rem; - } - else { - Py_ssize_t shift_digits = shift / PyLong_SHIFT; - digit rem; - /* x = a >> shift */ - assert(a_size >= shift_digits); - x = _PyLong_New(a_size - shift_digits); - if (x == NULL) - goto error; - rem = v_rshift(x->ob_digit, a->ob_digit + shift_digits, - a_size - shift_digits, shift % PyLong_SHIFT); - /* set inexact if any of the bits shifted out is nonzero */ - if (rem) - inexact = 1; - while (!inexact && shift_digits > 0) - if (a->ob_digit[--shift_digits]) - inexact = 1; - } - long_normalize(x); - x_size = Py_SIZE(x); - - /* x //= b. If the remainder is nonzero, set inexact. We own the only - reference to x, so it's safe to modify it in-place. */ - if (b_size == 1) { - digit rem = inplace_divrem1(x->ob_digit, x->ob_digit, x_size, - b->ob_digit[0]); - long_normalize(x); - if (rem) - inexact = 1; - } - else { - PyLongObject *div, *rem; - div = x_divrem(x, b, &rem); - Py_DECREF(x); - x = div; - if (x == NULL) - goto error; - if (Py_SIZE(rem)) - inexact = 1; - Py_DECREF(rem); - } - x_size = ABS(Py_SIZE(x)); - assert(x_size > 0); /* result of division is never zero */ - x_bits = (x_size-1)*PyLong_SHIFT+bits_in_digit(x->ob_digit[x_size-1]); - - /* The number of extra bits that have to be rounded away. */ - extra_bits = MAX(x_bits, DBL_MIN_EXP - shift) - DBL_MANT_DIG; - assert(extra_bits == 2 || extra_bits == 3); - - /* Round by directly modifying the low digit of x. */ - mask = (digit)1 << (extra_bits - 1); - low = x->ob_digit[0] | inexact; - if (low & mask && low & (3*mask-1)) - low += mask; - x->ob_digit[0] = low & ~(mask-1U); - - /* Convert x to a double dx; the conversion is exact. */ - dx = x->ob_digit[--x_size]; - while (x_size > 0) - dx = dx * PyLong_BASE + x->ob_digit[--x_size]; - Py_DECREF(x); - - /* Check whether ldexp result will overflow a double. */ - if (shift + x_bits >= DBL_MAX_EXP && - (shift + x_bits > DBL_MAX_EXP || dx == ldexp(1.0, (int)x_bits))) - goto overflow; - result = ldexp(dx, (int)shift); + PyLongObject *a, *b, *x; + Py_ssize_t a_size, b_size, shift, extra_bits, diff, x_size, x_bits; + digit mask, low; + int inexact, negate, a_is_small, b_is_small; + double dx, result; + + CHECK_BINOP(v, w); + a = (PyLongObject *)v; + b = (PyLongObject *)w; + + /* + Method in a nutshell: + + 0. reduce to case a, b > 0; filter out obvious underflow/overflow + 1. choose a suitable integer 'shift' + 2. use integer arithmetic to compute x = floor(2**-shift*a/b) + 3. adjust x for correct rounding + 4. convert x to a double dx with the same value + 5. return ldexp(dx, shift). + + In more detail: + + 0. For any a, a/0 raises ZeroDivisionError; for nonzero b, 0/b + returns either 0.0 or -0.0, depending on the sign of b. For a and + b both nonzero, ignore signs of a and b, and add the sign back in + at the end. Now write a_bits and b_bits for the bit lengths of a + and b respectively (that is, a_bits = 1 + floor(log_2(a)); likewise + for b). Then + + 2**(a_bits - b_bits - 1) < a/b < 2**(a_bits - b_bits + 1). + + So if a_bits - b_bits > DBL_MAX_EXP then a/b > 2**DBL_MAX_EXP and + so overflows. Similarly, if a_bits - b_bits < DBL_MIN_EXP - + DBL_MANT_DIG - 1 then a/b underflows to 0. With these cases out of + the way, we can assume that + + DBL_MIN_EXP - DBL_MANT_DIG - 1 <= a_bits - b_bits <= DBL_MAX_EXP. + + 1. The integer 'shift' is chosen so that x has the right number of + bits for a double, plus two or three extra bits that will be used + in the rounding decisions. Writing a_bits and b_bits for the + number of significant bits in a and b respectively, a + straightforward formula for shift is: + + shift = a_bits - b_bits - DBL_MANT_DIG - 2 + + This is fine in the usual case, but if a/b is smaller than the + smallest normal float then it can lead to double rounding on an + IEEE 754 platform, giving incorrectly rounded results. So we + adjust the formula slightly. The actual formula used is: + + shift = MAX(a_bits - b_bits, DBL_MIN_EXP) - DBL_MANT_DIG - 2 + + 2. The quantity x is computed by first shifting a (left -shift bits + if shift <= 0, right shift bits if shift > 0) and then dividing by + b. For both the shift and the division, we keep track of whether + the result is inexact, in a flag 'inexact'; this information is + needed at the rounding stage. + + With the choice of shift above, together with our assumption that + a_bits - b_bits >= DBL_MIN_EXP - DBL_MANT_DIG - 1, it follows + that x >= 1. + + 3. Now x * 2**shift <= a/b < (x+1) * 2**shift. We want to replace + this with an exactly representable float of the form + + round(x/2**extra_bits) * 2**(extra_bits+shift). + + For float representability, we need x/2**extra_bits < + 2**DBL_MANT_DIG and extra_bits + shift >= DBL_MIN_EXP - + DBL_MANT_DIG. This translates to the condition: + + extra_bits >= MAX(x_bits, DBL_MIN_EXP - shift) - DBL_MANT_DIG + + To round, we just modify the bottom digit of x in-place; this can + end up giving a digit with value > PyLONG_MASK, but that's not a + problem since digits can hold values up to 2*PyLONG_MASK+1. + + With the original choices for shift above, extra_bits will always + be 2 or 3. Then rounding under the round-half-to-even rule, we + round up iff the most significant of the extra bits is 1, and + either: (a) the computation of x in step 2 had an inexact result, + or (b) at least one other of the extra bits is 1, or (c) the least + significant bit of x (above those to be rounded) is 1. + + 4. Conversion to a double is straightforward; all floating-point + operations involved in the conversion are exact, so there's no + danger of rounding errors. + + 5. Use ldexp(x, shift) to compute x*2**shift, the final result. + The result will always be exactly representable as a double, except + in the case that it overflows. To avoid dependence on the exact + behaviour of ldexp on overflow, we check for overflow before + applying ldexp. The result of ldexp is adjusted for sign before + returning. + */ + + /* Reduce to case where a and b are both positive. */ + a_size = ABS(Py_SIZE(a)); + b_size = ABS(Py_SIZE(b)); + negate = (Py_SIZE(a) < 0) ^ (Py_SIZE(b) < 0); + if (b_size == 0) { + PyErr_SetString(PyExc_ZeroDivisionError, + "division by zero"); + goto error; + } + if (a_size == 0) + goto underflow_or_zero; + + /* Fast path for a and b small (exactly representable in a double). + Relies on floating-point division being correctly rounded; results + may be subject to double rounding on x86 machines that operate with + the x87 FPU set to 64-bit precision. */ + a_is_small = a_size <= MANT_DIG_DIGITS || + (a_size == MANT_DIG_DIGITS+1 && + a->ob_digit[MANT_DIG_DIGITS] >> MANT_DIG_BITS == 0); + b_is_small = b_size <= MANT_DIG_DIGITS || + (b_size == MANT_DIG_DIGITS+1 && + b->ob_digit[MANT_DIG_DIGITS] >> MANT_DIG_BITS == 0); + if (a_is_small && b_is_small) { + double da, db; + da = a->ob_digit[--a_size]; + while (a_size > 0) + da = da * PyLong_BASE + a->ob_digit[--a_size]; + db = b->ob_digit[--b_size]; + while (b_size > 0) + db = db * PyLong_BASE + b->ob_digit[--b_size]; + result = da / db; + goto success; + } + + /* Catch obvious cases of underflow and overflow */ + diff = a_size - b_size; + if (diff > PY_SSIZE_T_MAX/PyLong_SHIFT - 1) + /* Extreme overflow */ + goto overflow; + else if (diff < 1 - PY_SSIZE_T_MAX/PyLong_SHIFT) + /* Extreme underflow */ + goto underflow_or_zero; + /* Next line is now safe from overflowing a Py_ssize_t */ + diff = diff * PyLong_SHIFT + bits_in_digit(a->ob_digit[a_size - 1]) - + bits_in_digit(b->ob_digit[b_size - 1]); + /* Now diff = a_bits - b_bits. */ + if (diff > DBL_MAX_EXP) + goto overflow; + else if (diff < DBL_MIN_EXP - DBL_MANT_DIG - 1) + goto underflow_or_zero; + + /* Choose value for shift; see comments for step 1 above. */ + shift = MAX(diff, DBL_MIN_EXP) - DBL_MANT_DIG - 2; + + inexact = 0; + + /* x = abs(a * 2**-shift) */ + if (shift <= 0) { + Py_ssize_t i, shift_digits = -shift / PyLong_SHIFT; + digit rem; + /* x = a << -shift */ + if (a_size >= PY_SSIZE_T_MAX - 1 - shift_digits) { + /* In practice, it's probably impossible to end up + here. Both a and b would have to be enormous, + using close to SIZE_T_MAX bytes of memory each. */ + PyErr_SetString(PyExc_OverflowError, + "intermediate overflow during division"); + goto error; + } + x = _PyLong_New(a_size + shift_digits + 1); + if (x == NULL) + goto error; + for (i = 0; i < shift_digits; i++) + x->ob_digit[i] = 0; + rem = v_lshift(x->ob_digit + shift_digits, a->ob_digit, + a_size, -shift % PyLong_SHIFT); + x->ob_digit[a_size + shift_digits] = rem; + } + else { + Py_ssize_t shift_digits = shift / PyLong_SHIFT; + digit rem; + /* x = a >> shift */ + assert(a_size >= shift_digits); + x = _PyLong_New(a_size - shift_digits); + if (x == NULL) + goto error; + rem = v_rshift(x->ob_digit, a->ob_digit + shift_digits, + a_size - shift_digits, shift % PyLong_SHIFT); + /* set inexact if any of the bits shifted out is nonzero */ + if (rem) + inexact = 1; + while (!inexact && shift_digits > 0) + if (a->ob_digit[--shift_digits]) + inexact = 1; + } + long_normalize(x); + x_size = Py_SIZE(x); + + /* x //= b. If the remainder is nonzero, set inexact. We own the only + reference to x, so it's safe to modify it in-place. */ + if (b_size == 1) { + digit rem = inplace_divrem1(x->ob_digit, x->ob_digit, x_size, + b->ob_digit[0]); + long_normalize(x); + if (rem) + inexact = 1; + } + else { + PyLongObject *div, *rem; + div = x_divrem(x, b, &rem); + Py_DECREF(x); + x = div; + if (x == NULL) + goto error; + if (Py_SIZE(rem)) + inexact = 1; + Py_DECREF(rem); + } + x_size = ABS(Py_SIZE(x)); + assert(x_size > 0); /* result of division is never zero */ + x_bits = (x_size-1)*PyLong_SHIFT+bits_in_digit(x->ob_digit[x_size-1]); + + /* The number of extra bits that have to be rounded away. */ + extra_bits = MAX(x_bits, DBL_MIN_EXP - shift) - DBL_MANT_DIG; + assert(extra_bits == 2 || extra_bits == 3); + + /* Round by directly modifying the low digit of x. */ + mask = (digit)1 << (extra_bits - 1); + low = x->ob_digit[0] | inexact; + if (low & mask && low & (3*mask-1)) + low += mask; + x->ob_digit[0] = low & ~(mask-1U); + + /* Convert x to a double dx; the conversion is exact. */ + dx = x->ob_digit[--x_size]; + while (x_size > 0) + dx = dx * PyLong_BASE + x->ob_digit[--x_size]; + Py_DECREF(x); + + /* Check whether ldexp result will overflow a double. */ + if (shift + x_bits >= DBL_MAX_EXP && + (shift + x_bits > DBL_MAX_EXP || dx == ldexp(1.0, (int)x_bits))) + goto overflow; + result = ldexp(dx, (int)shift); success: - return PyFloat_FromDouble(negate ? -result : result); + return PyFloat_FromDouble(negate ? -result : result); underflow_or_zero: - return PyFloat_FromDouble(negate ? -0.0 : 0.0); + return PyFloat_FromDouble(negate ? -0.0 : 0.0); overflow: - PyErr_SetString(PyExc_OverflowError, - "integer division result too large for a float"); + PyErr_SetString(PyExc_OverflowError, + "integer division result too large for a float"); error: - return NULL; + return NULL; } static PyObject * long_mod(PyObject *a, PyObject *b) { - PyLongObject *mod; - - CHECK_BINOP(a, b); - - if (l_divmod((PyLongObject*)a, (PyLongObject*)b, NULL, &mod) < 0) - mod = NULL; - return (PyObject *)mod; + PyLongObject *mod; + + CHECK_BINOP(a, b); + + if (l_divmod((PyLongObject*)a, (PyLongObject*)b, NULL, &mod) < 0) + mod = NULL; + return (PyObject *)mod; } static PyObject * long_divmod(PyObject *a, PyObject *b) { - PyLongObject *div, *mod; - PyObject *z; + PyLongObject *div, *mod; + PyObject *z; - CHECK_BINOP(a, b); + CHECK_BINOP(a, b); - if (l_divmod((PyLongObject*)a, (PyLongObject*)b, &div, &mod) < 0) { - return NULL; - } - z = PyTuple_New(2); - if (z != NULL) { - PyTuple_SetItem(z, 0, (PyObject *) div); - PyTuple_SetItem(z, 1, (PyObject *) mod); - } - else { - Py_DECREF(div); - Py_DECREF(mod); - } - return z; + if (l_divmod((PyLongObject*)a, (PyLongObject*)b, &div, &mod) < 0) { + return NULL; + } + z = PyTuple_New(2); + if (z != NULL) { + PyTuple_SetItem(z, 0, (PyObject *) div); + PyTuple_SetItem(z, 1, (PyObject *) mod); + } + else { + Py_DECREF(div); + Py_DECREF(mod); + } + return z; } /* pow(v, w, x) */ static PyObject * long_pow(PyObject *v, PyObject *w, PyObject *x) { - PyLongObject *a, *b, *c; /* a,b,c = v,w,x */ - int negativeOutput = 0; /* if x<0 return negative output */ + PyLongObject *a, *b, *c; /* a,b,c = v,w,x */ + int negativeOutput = 0; /* if x<0 return negative output */ - PyLongObject *z = NULL; /* accumulated result */ - Py_ssize_t i, j, k; /* counters */ - PyLongObject *temp = NULL; - - /* 5-ary values. If the exponent is large enough, table is - * precomputed so that table[i] == a**i % c for i in range(32). - */ - PyLongObject *table[32] = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, - 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0}; - - /* a, b, c = v, w, x */ - CHECK_BINOP(v, w); - a = (PyLongObject*)v; Py_INCREF(a); - b = (PyLongObject*)w; Py_INCREF(b); - if (PyLong_Check(x)) { - c = (PyLongObject *)x; - Py_INCREF(x); - } - else if (x == Py_None) - c = NULL; - else { - Py_DECREF(a); - Py_DECREF(b); - Py_INCREF(Py_NotImplemented); - return Py_NotImplemented; - } - - if (Py_SIZE(b) < 0) { /* if exponent is negative */ - if (c) { - PyErr_SetString(PyExc_TypeError, "pow() 2nd argument " - "cannot be negative when 3rd argument specified"); - goto Error; - } - else { - /* else return a float. This works because we know - that this calls float_pow() which converts its - arguments to double. */ - Py_DECREF(a); - Py_DECREF(b); - return PyFloat_Type.tp_as_number->nb_power(v, w, x); - } - } - - if (c) { - /* if modulus == 0: - raise ValueError() */ - if (Py_SIZE(c) == 0) { - PyErr_SetString(PyExc_ValueError, - "pow() 3rd argument cannot be 0"); - goto Error; - } - - /* if modulus < 0: - negativeOutput = True - modulus = -modulus */ - if (Py_SIZE(c) < 0) { - negativeOutput = 1; - temp = (PyLongObject *)_PyLong_Copy(c); - if (temp == NULL) - goto Error; - Py_DECREF(c); - c = temp; - temp = NULL; - NEGATE(c); - } - - /* if modulus == 1: - return 0 */ - if ((Py_SIZE(c) == 1) && (c->ob_digit[0] == 1)) { - z = (PyLongObject *)PyLong_FromLong(0L); - goto Done; - } - - /* if base < 0: - base = base % modulus - Having the base positive just makes things easier. */ - if (Py_SIZE(a) < 0) { - if (l_divmod(a, c, NULL, &temp) < 0) - goto Error; - Py_DECREF(a); - a = temp; - temp = NULL; - } - } - - /* At this point a, b, and c are guaranteed non-negative UNLESS - c is NULL, in which case a may be negative. */ - - z = (PyLongObject *)PyLong_FromLong(1L); - if (z == NULL) - goto Error; - - /* Perform a modular reduction, X = X % c, but leave X alone if c - * is NULL. - */ -#define REDUCE(X) \ - if (c != NULL) { \ - if (l_divmod(X, c, NULL, &temp) < 0) \ - goto Error; \ - Py_XDECREF(X); \ - X = temp; \ - temp = NULL; \ - } - - /* Multiply two values, then reduce the result: - result = X*Y % c. If c is NULL, skip the mod. */ -#define MULT(X, Y, result) \ -{ \ - temp = (PyLongObject *)long_mul(X, Y); \ - if (temp == NULL) \ - goto Error; \ - Py_XDECREF(result); \ - result = temp; \ - temp = NULL; \ - REDUCE(result) \ -} - - if (Py_SIZE(b) <= FIVEARY_CUTOFF) { - /* Left-to-right binary exponentiation (HAC Algorithm 14.79) */ - /* http://www.cacr.math.uwaterloo.ca/hac/about/chap14.pdf */ - for (i = Py_SIZE(b) - 1; i >= 0; --i) { - digit bi = b->ob_digit[i]; - - for (j = (digit)1 << (PyLong_SHIFT-1); j != 0; j >>= 1) { - MULT(z, z, z) - if (bi & j) - MULT(z, a, z) - } - } - } - else { - /* Left-to-right 5-ary exponentiation (HAC Algorithm 14.82) */ - Py_INCREF(z); /* still holds 1L */ - table[0] = z; - for (i = 1; i < 32; ++i) - MULT(table[i-1], a, table[i]) - - for (i = Py_SIZE(b) - 1; i >= 0; --i) { - const digit bi = b->ob_digit[i]; - - for (j = PyLong_SHIFT - 5; j >= 0; j -= 5) { - const int index = (bi >> j) & 0x1f; - for (k = 0; k < 5; ++k) - MULT(z, z, z) - if (index) - MULT(z, table[index], z) - } - } - } - - if (negativeOutput && (Py_SIZE(z) != 0)) { - temp = (PyLongObject *)long_sub(z, c); - if (temp == NULL) - goto Error; - Py_DECREF(z); - z = temp; - temp = NULL; - } - goto Done; + PyLongObject *z = NULL; /* accumulated result */ + Py_ssize_t i, j, k; /* counters */ + PyLongObject *temp = NULL; + + /* 5-ary values. If the exponent is large enough, table is + * precomputed so that table[i] == a**i % c for i in range(32). + */ + PyLongObject *table[32] = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, + 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0}; + + /* a, b, c = v, w, x */ + CHECK_BINOP(v, w); + a = (PyLongObject*)v; Py_INCREF(a); + b = (PyLongObject*)w; Py_INCREF(b); + if (PyLong_Check(x)) { + c = (PyLongObject *)x; + Py_INCREF(x); + } + else if (x == Py_None) + c = NULL; + else { + Py_DECREF(a); + Py_DECREF(b); + Py_INCREF(Py_NotImplemented); + return Py_NotImplemented; + } + + if (Py_SIZE(b) < 0) { /* if exponent is negative */ + if (c) { + PyErr_SetString(PyExc_TypeError, "pow() 2nd argument " + "cannot be negative when 3rd argument specified"); + goto Error; + } + else { + /* else return a float. This works because we know + that this calls float_pow() which converts its + arguments to double. */ + Py_DECREF(a); + Py_DECREF(b); + return PyFloat_Type.tp_as_number->nb_power(v, w, x); + } + } + + if (c) { + /* if modulus == 0: + raise ValueError() */ + if (Py_SIZE(c) == 0) { + PyErr_SetString(PyExc_ValueError, + "pow() 3rd argument cannot be 0"); + goto Error; + } + + /* if modulus < 0: + negativeOutput = True + modulus = -modulus */ + if (Py_SIZE(c) < 0) { + negativeOutput = 1; + temp = (PyLongObject *)_PyLong_Copy(c); + if (temp == NULL) + goto Error; + Py_DECREF(c); + c = temp; + temp = NULL; + NEGATE(c); + } + + /* if modulus == 1: + return 0 */ + if ((Py_SIZE(c) == 1) && (c->ob_digit[0] == 1)) { + z = (PyLongObject *)PyLong_FromLong(0L); + goto Done; + } + + /* if base < 0: + base = base % modulus + Having the base positive just makes things easier. */ + if (Py_SIZE(a) < 0) { + if (l_divmod(a, c, NULL, &temp) < 0) + goto Error; + Py_DECREF(a); + a = temp; + temp = NULL; + } + } + + /* At this point a, b, and c are guaranteed non-negative UNLESS + c is NULL, in which case a may be negative. */ + + z = (PyLongObject *)PyLong_FromLong(1L); + if (z == NULL) + goto Error; + + /* Perform a modular reduction, X = X % c, but leave X alone if c + * is NULL. + */ +#define REDUCE(X) \ + if (c != NULL) { \ + if (l_divmod(X, c, NULL, &temp) < 0) \ + goto Error; \ + Py_XDECREF(X); \ + X = temp; \ + temp = NULL; \ + } + + /* Multiply two values, then reduce the result: + result = X*Y % c. If c is NULL, skip the mod. */ +#define MULT(X, Y, result) \ +{ \ + temp = (PyLongObject *)long_mul(X, Y); \ + if (temp == NULL) \ + goto Error; \ + Py_XDECREF(result); \ + result = temp; \ + temp = NULL; \ + REDUCE(result) \ +} + + if (Py_SIZE(b) <= FIVEARY_CUTOFF) { + /* Left-to-right binary exponentiation (HAC Algorithm 14.79) */ + /* http://www.cacr.math.uwaterloo.ca/hac/about/chap14.pdf */ + for (i = Py_SIZE(b) - 1; i >= 0; --i) { + digit bi = b->ob_digit[i]; + + for (j = (digit)1 << (PyLong_SHIFT-1); j != 0; j >>= 1) { + MULT(z, z, z) + if (bi & j) + MULT(z, a, z) + } + } + } + else { + /* Left-to-right 5-ary exponentiation (HAC Algorithm 14.82) */ + Py_INCREF(z); /* still holds 1L */ + table[0] = z; + for (i = 1; i < 32; ++i) + MULT(table[i-1], a, table[i]) + + for (i = Py_SIZE(b) - 1; i >= 0; --i) { + const digit bi = b->ob_digit[i]; + + for (j = PyLong_SHIFT - 5; j >= 0; j -= 5) { + const int index = (bi >> j) & 0x1f; + for (k = 0; k < 5; ++k) + MULT(z, z, z) + if (index) + MULT(z, table[index], z) + } + } + } + + if (negativeOutput && (Py_SIZE(z) != 0)) { + temp = (PyLongObject *)long_sub(z, c); + if (temp == NULL) + goto Error; + Py_DECREF(z); + z = temp; + temp = NULL; + } + goto Done; Error: - if (z != NULL) { - Py_DECREF(z); - z = NULL; - } - /* fall through */ + if (z != NULL) { + Py_DECREF(z); + z = NULL; + } + /* fall through */ Done: - if (Py_SIZE(b) > FIVEARY_CUTOFF) { - for (i = 0; i < 32; ++i) - Py_XDECREF(table[i]); - } - Py_DECREF(a); - Py_DECREF(b); - Py_XDECREF(c); - Py_XDECREF(temp); - return (PyObject *)z; + if (Py_SIZE(b) > FIVEARY_CUTOFF) { + for (i = 0; i < 32; ++i) + Py_XDECREF(table[i]); + } + Py_DECREF(a); + Py_DECREF(b); + Py_XDECREF(c); + Py_XDECREF(temp); + return (PyObject *)z; } static PyObject * long_invert(PyLongObject *v) { - /* Implement ~x as -(x+1) */ - PyLongObject *x; - PyLongObject *w; - if (ABS(Py_SIZE(v)) <=1) - return PyLong_FromLong(-(MEDIUM_VALUE(v)+1)); - w = (PyLongObject *)PyLong_FromLong(1L); - if (w == NULL) - return NULL; - x = (PyLongObject *) long_add(v, w); - Py_DECREF(w); - if (x == NULL) - return NULL; - Py_SIZE(x) = -(Py_SIZE(x)); - return (PyObject *)maybe_small_long(x); + /* Implement ~x as -(x+1) */ + PyLongObject *x; + PyLongObject *w; + if (ABS(Py_SIZE(v)) <=1) + return PyLong_FromLong(-(MEDIUM_VALUE(v)+1)); + w = (PyLongObject *)PyLong_FromLong(1L); + if (w == NULL) + return NULL; + x = (PyLongObject *) long_add(v, w); + Py_DECREF(w); + if (x == NULL) + return NULL; + Py_SIZE(x) = -(Py_SIZE(x)); + return (PyObject *)maybe_small_long(x); } static PyObject * long_neg(PyLongObject *v) { - PyLongObject *z; - if (ABS(Py_SIZE(v)) <= 1) - return PyLong_FromLong(-MEDIUM_VALUE(v)); - z = (PyLongObject *)_PyLong_Copy(v); - if (z != NULL) - Py_SIZE(z) = -(Py_SIZE(v)); - return (PyObject *)z; + PyLongObject *z; + if (ABS(Py_SIZE(v)) <= 1) + return PyLong_FromLong(-MEDIUM_VALUE(v)); + z = (PyLongObject *)_PyLong_Copy(v); + if (z != NULL) + Py_SIZE(z) = -(Py_SIZE(v)); + return (PyObject *)z; } static PyObject * long_abs(PyLongObject *v) { - if (Py_SIZE(v) < 0) - return long_neg(v); - else - return long_long((PyObject *)v); + if (Py_SIZE(v) < 0) + return long_neg(v); + else + return long_long((PyObject *)v); } static int long_bool(PyLongObject *v) { - return Py_SIZE(v) != 0; + return Py_SIZE(v) != 0; } static PyObject * long_rshift(PyLongObject *a, PyLongObject *b) { - PyLongObject *z = NULL; - Py_ssize_t shiftby, newsize, wordshift, loshift, hishift, i, j; - digit lomask, himask; - - CHECK_BINOP(a, b); - - if (Py_SIZE(a) < 0) { - /* Right shifting negative numbers is harder */ - PyLongObject *a1, *a2; - a1 = (PyLongObject *) long_invert(a); - if (a1 == NULL) - goto rshift_error; - a2 = (PyLongObject *) long_rshift(a1, b); - Py_DECREF(a1); - if (a2 == NULL) - goto rshift_error; - z = (PyLongObject *) long_invert(a2); - Py_DECREF(a2); - } - else { - shiftby = PyLong_AsSsize_t((PyObject *)b); - if (shiftby == -1L && PyErr_Occurred()) - goto rshift_error; - if (shiftby < 0) { - PyErr_SetString(PyExc_ValueError, - "negative shift count"); - goto rshift_error; - } - wordshift = shiftby / PyLong_SHIFT; - newsize = ABS(Py_SIZE(a)) - wordshift; - if (newsize <= 0) - return PyLong_FromLong(0); - loshift = shiftby % PyLong_SHIFT; - hishift = PyLong_SHIFT - loshift; - lomask = ((digit)1 << hishift) - 1; - himask = PyLong_MASK ^ lomask; - z = _PyLong_New(newsize); - if (z == NULL) - goto rshift_error; - if (Py_SIZE(a) < 0) - Py_SIZE(z) = -(Py_SIZE(z)); - for (i = 0, j = wordshift; i < newsize; i++, j++) { - z->ob_digit[i] = (a->ob_digit[j] >> loshift) & lomask; - if (i+1 < newsize) - z->ob_digit[i] |= - (a->ob_digit[j+1] << hishift) & himask; - } - z = long_normalize(z); - } + PyLongObject *z = NULL; + Py_ssize_t shiftby, newsize, wordshift, loshift, hishift, i, j; + digit lomask, himask; + + CHECK_BINOP(a, b); + + if (Py_SIZE(a) < 0) { + /* Right shifting negative numbers is harder */ + PyLongObject *a1, *a2; + a1 = (PyLongObject *) long_invert(a); + if (a1 == NULL) + goto rshift_error; + a2 = (PyLongObject *) long_rshift(a1, b); + Py_DECREF(a1); + if (a2 == NULL) + goto rshift_error; + z = (PyLongObject *) long_invert(a2); + Py_DECREF(a2); + } + else { + shiftby = PyLong_AsSsize_t((PyObject *)b); + if (shiftby == -1L && PyErr_Occurred()) + goto rshift_error; + if (shiftby < 0) { + PyErr_SetString(PyExc_ValueError, + "negative shift count"); + goto rshift_error; + } + wordshift = shiftby / PyLong_SHIFT; + newsize = ABS(Py_SIZE(a)) - wordshift; + if (newsize <= 0) + return PyLong_FromLong(0); + loshift = shiftby % PyLong_SHIFT; + hishift = PyLong_SHIFT - loshift; + lomask = ((digit)1 << hishift) - 1; + himask = PyLong_MASK ^ lomask; + z = _PyLong_New(newsize); + if (z == NULL) + goto rshift_error; + if (Py_SIZE(a) < 0) + Py_SIZE(z) = -(Py_SIZE(z)); + for (i = 0, j = wordshift; i < newsize; i++, j++) { + z->ob_digit[i] = (a->ob_digit[j] >> loshift) & lomask; + if (i+1 < newsize) + z->ob_digit[i] |= + (a->ob_digit[j+1] << hishift) & himask; + } + z = long_normalize(z); + } rshift_error: - return (PyObject *) maybe_small_long(z); + return (PyObject *) maybe_small_long(z); } static PyObject * long_lshift(PyObject *v, PyObject *w) { - /* This version due to Tim Peters */ - PyLongObject *a = (PyLongObject*)v; - PyLongObject *b = (PyLongObject*)w; - PyLongObject *z = NULL; - Py_ssize_t shiftby, oldsize, newsize, wordshift, remshift, i, j; - twodigits accum; - - CHECK_BINOP(a, b); - - shiftby = PyLong_AsSsize_t((PyObject *)b); - if (shiftby == -1L && PyErr_Occurred()) - goto lshift_error; - if (shiftby < 0) { - PyErr_SetString(PyExc_ValueError, "negative shift count"); - goto lshift_error; - } - /* wordshift, remshift = divmod(shiftby, PyLong_SHIFT) */ - wordshift = shiftby / PyLong_SHIFT; - remshift = shiftby - wordshift * PyLong_SHIFT; - - oldsize = ABS(Py_SIZE(a)); - newsize = oldsize + wordshift; - if (remshift) - ++newsize; - z = _PyLong_New(newsize); - if (z == NULL) - goto lshift_error; - if (Py_SIZE(a) < 0) - NEGATE(z); - for (i = 0; i < wordshift; i++) - z->ob_digit[i] = 0; - accum = 0; - for (i = wordshift, j = 0; j < oldsize; i++, j++) { - accum |= (twodigits)a->ob_digit[j] << remshift; - z->ob_digit[i] = (digit)(accum & PyLong_MASK); - accum >>= PyLong_SHIFT; - } - if (remshift) - z->ob_digit[newsize-1] = (digit)accum; - else - assert(!accum); - z = long_normalize(z); + /* This version due to Tim Peters */ + PyLongObject *a = (PyLongObject*)v; + PyLongObject *b = (PyLongObject*)w; + PyLongObject *z = NULL; + Py_ssize_t shiftby, oldsize, newsize, wordshift, remshift, i, j; + twodigits accum; + + CHECK_BINOP(a, b); + + shiftby = PyLong_AsSsize_t((PyObject *)b); + if (shiftby == -1L && PyErr_Occurred()) + goto lshift_error; + if (shiftby < 0) { + PyErr_SetString(PyExc_ValueError, "negative shift count"); + goto lshift_error; + } + /* wordshift, remshift = divmod(shiftby, PyLong_SHIFT) */ + wordshift = shiftby / PyLong_SHIFT; + remshift = shiftby - wordshift * PyLong_SHIFT; + + oldsize = ABS(Py_SIZE(a)); + newsize = oldsize + wordshift; + if (remshift) + ++newsize; + z = _PyLong_New(newsize); + if (z == NULL) + goto lshift_error; + if (Py_SIZE(a) < 0) + NEGATE(z); + for (i = 0; i < wordshift; i++) + z->ob_digit[i] = 0; + accum = 0; + for (i = wordshift, j = 0; j < oldsize; i++, j++) { + accum |= (twodigits)a->ob_digit[j] << remshift; + z->ob_digit[i] = (digit)(accum & PyLong_MASK); + accum >>= PyLong_SHIFT; + } + if (remshift) + z->ob_digit[newsize-1] = (digit)accum; + else + assert(!accum); + z = long_normalize(z); lshift_error: - return (PyObject *) maybe_small_long(z); + return (PyObject *) maybe_small_long(z); } /* Compute two's complement of digit vector a[0:m], writing result to @@ -3885,186 +3885,186 @@ static void v_complement(digit *z, digit *a, Py_ssize_t m) { - Py_ssize_t i; - digit carry = 1; - for (i = 0; i < m; ++i) { - carry += a[i] ^ PyLong_MASK; - z[i] = carry & PyLong_MASK; - carry >>= PyLong_SHIFT; - } - assert(carry == 0); + Py_ssize_t i; + digit carry = 1; + for (i = 0; i < m; ++i) { + carry += a[i] ^ PyLong_MASK; + z[i] = carry & PyLong_MASK; + carry >>= PyLong_SHIFT; + } + assert(carry == 0); } /* Bitwise and/xor/or operations */ static PyObject * long_bitwise(PyLongObject *a, - int op, /* '&', '|', '^' */ - PyLongObject *b) + int op, /* '&', '|', '^' */ + PyLongObject *b) { - int nega, negb, negz; - Py_ssize_t size_a, size_b, size_z, i; - PyLongObject *z; - - /* Bitwise operations for negative numbers operate as though - on a two's complement representation. So convert arguments - from sign-magnitude to two's complement, and convert the - result back to sign-magnitude at the end. */ - - /* If a is negative, replace it by its two's complement. */ - size_a = ABS(Py_SIZE(a)); - nega = Py_SIZE(a) < 0; - if (nega) { - z = _PyLong_New(size_a); - if (z == NULL) - return NULL; - v_complement(z->ob_digit, a->ob_digit, size_a); - a = z; - } - else - /* Keep reference count consistent. */ - Py_INCREF(a); - - /* Same for b. */ - size_b = ABS(Py_SIZE(b)); - negb = Py_SIZE(b) < 0; - if (negb) { - z = _PyLong_New(size_b); - if (z == NULL) { - Py_DECREF(a); - return NULL; - } - v_complement(z->ob_digit, b->ob_digit, size_b); - b = z; - } - else - Py_INCREF(b); - - /* Swap a and b if necessary to ensure size_a >= size_b. */ - if (size_a < size_b) { - z = a; a = b; b = z; - size_z = size_a; size_a = size_b; size_b = size_z; - negz = nega; nega = negb; negb = negz; - } - - /* JRH: The original logic here was to allocate the result value (z) - as the longer of the two operands. However, there are some cases - where the result is guaranteed to be shorter than that: AND of two - positives, OR of two negatives: use the shorter number. AND with - mixed signs: use the positive number. OR with mixed signs: use the - negative number. - */ - switch (op) { - case '^': - negz = nega ^ negb; - size_z = size_a; - break; - case '&': - negz = nega & negb; - size_z = negb ? size_a : size_b; - break; - case '|': - negz = nega | negb; - size_z = negb ? size_b : size_a; - break; - default: - PyErr_BadArgument(); - return NULL; - } - - /* We allow an extra digit if z is negative, to make sure that - the final two's complement of z doesn't overflow. */ - z = _PyLong_New(size_z + negz); - if (z == NULL) { - Py_DECREF(a); - Py_DECREF(b); - return NULL; - } - - /* Compute digits for overlap of a and b. */ - switch(op) { - case '&': - for (i = 0; i < size_b; ++i) - z->ob_digit[i] = a->ob_digit[i] & b->ob_digit[i]; - break; - case '|': - for (i = 0; i < size_b; ++i) - z->ob_digit[i] = a->ob_digit[i] | b->ob_digit[i]; - break; - case '^': - for (i = 0; i < size_b; ++i) - z->ob_digit[i] = a->ob_digit[i] ^ b->ob_digit[i]; - break; - default: - PyErr_BadArgument(); - return NULL; - } - - /* Copy any remaining digits of a, inverting if necessary. */ - if (op == '^' && negb) - for (; i < size_z; ++i) - z->ob_digit[i] = a->ob_digit[i] ^ PyLong_MASK; - else if (i < size_z) - memcpy(&z->ob_digit[i], &a->ob_digit[i], - (size_z-i)*sizeof(digit)); - - /* Complement result if negative. */ - if (negz) { - Py_SIZE(z) = -(Py_SIZE(z)); - z->ob_digit[size_z] = PyLong_MASK; - v_complement(z->ob_digit, z->ob_digit, size_z+1); - } - - Py_DECREF(a); - Py_DECREF(b); - return (PyObject *)maybe_small_long(long_normalize(z)); + int nega, negb, negz; + Py_ssize_t size_a, size_b, size_z, i; + PyLongObject *z; + + /* Bitwise operations for negative numbers operate as though + on a two's complement representation. So convert arguments + from sign-magnitude to two's complement, and convert the + result back to sign-magnitude at the end. */ + + /* If a is negative, replace it by its two's complement. */ + size_a = ABS(Py_SIZE(a)); + nega = Py_SIZE(a) < 0; + if (nega) { + z = _PyLong_New(size_a); + if (z == NULL) + return NULL; + v_complement(z->ob_digit, a->ob_digit, size_a); + a = z; + } + else + /* Keep reference count consistent. */ + Py_INCREF(a); + + /* Same for b. */ + size_b = ABS(Py_SIZE(b)); + negb = Py_SIZE(b) < 0; + if (negb) { + z = _PyLong_New(size_b); + if (z == NULL) { + Py_DECREF(a); + return NULL; + } + v_complement(z->ob_digit, b->ob_digit, size_b); + b = z; + } + else + Py_INCREF(b); + + /* Swap a and b if necessary to ensure size_a >= size_b. */ + if (size_a < size_b) { + z = a; a = b; b = z; + size_z = size_a; size_a = size_b; size_b = size_z; + negz = nega; nega = negb; negb = negz; + } + + /* JRH: The original logic here was to allocate the result value (z) + as the longer of the two operands. However, there are some cases + where the result is guaranteed to be shorter than that: AND of two + positives, OR of two negatives: use the shorter number. AND with + mixed signs: use the positive number. OR with mixed signs: use the + negative number. + */ + switch (op) { + case '^': + negz = nega ^ negb; + size_z = size_a; + break; + case '&': + negz = nega & negb; + size_z = negb ? size_a : size_b; + break; + case '|': + negz = nega | negb; + size_z = negb ? size_b : size_a; + break; + default: + PyErr_BadArgument(); + return NULL; + } + + /* We allow an extra digit if z is negative, to make sure that + the final two's complement of z doesn't overflow. */ + z = _PyLong_New(size_z + negz); + if (z == NULL) { + Py_DECREF(a); + Py_DECREF(b); + return NULL; + } + + /* Compute digits for overlap of a and b. */ + switch(op) { + case '&': + for (i = 0; i < size_b; ++i) + z->ob_digit[i] = a->ob_digit[i] & b->ob_digit[i]; + break; + case '|': + for (i = 0; i < size_b; ++i) + z->ob_digit[i] = a->ob_digit[i] | b->ob_digit[i]; + break; + case '^': + for (i = 0; i < size_b; ++i) + z->ob_digit[i] = a->ob_digit[i] ^ b->ob_digit[i]; + break; + default: + PyErr_BadArgument(); + return NULL; + } + + /* Copy any remaining digits of a, inverting if necessary. */ + if (op == '^' && negb) + for (; i < size_z; ++i) + z->ob_digit[i] = a->ob_digit[i] ^ PyLong_MASK; + else if (i < size_z) + memcpy(&z->ob_digit[i], &a->ob_digit[i], + (size_z-i)*sizeof(digit)); + + /* Complement result if negative. */ + if (negz) { + Py_SIZE(z) = -(Py_SIZE(z)); + z->ob_digit[size_z] = PyLong_MASK; + v_complement(z->ob_digit, z->ob_digit, size_z+1); + } + + Py_DECREF(a); + Py_DECREF(b); + return (PyObject *)maybe_small_long(long_normalize(z)); } static PyObject * long_and(PyObject *a, PyObject *b) { - PyObject *c; - CHECK_BINOP(a, b); - c = long_bitwise((PyLongObject*)a, '&', (PyLongObject*)b); - return c; + PyObject *c; + CHECK_BINOP(a, b); + c = long_bitwise((PyLongObject*)a, '&', (PyLongObject*)b); + return c; } static PyObject * long_xor(PyObject *a, PyObject *b) { - PyObject *c; - CHECK_BINOP(a, b); - c = long_bitwise((PyLongObject*)a, '^', (PyLongObject*)b); - return c; + PyObject *c; + CHECK_BINOP(a, b); + c = long_bitwise((PyLongObject*)a, '^', (PyLongObject*)b); + return c; } static PyObject * long_or(PyObject *a, PyObject *b) { - PyObject *c; - CHECK_BINOP(a, b); - c = long_bitwise((PyLongObject*)a, '|', (PyLongObject*)b); - return c; + PyObject *c; + CHECK_BINOP(a, b); + c = long_bitwise((PyLongObject*)a, '|', (PyLongObject*)b); + return c; } static PyObject * long_long(PyObject *v) { - if (PyLong_CheckExact(v)) - Py_INCREF(v); - else - v = _PyLong_Copy((PyLongObject *)v); - return v; + if (PyLong_CheckExact(v)) + Py_INCREF(v); + else + v = _PyLong_Copy((PyLongObject *)v); + return v; } static PyObject * long_float(PyObject *v) { - double result; - result = PyLong_AsDouble(v); - if (result == -1.0 && PyErr_Occurred()) - return NULL; - return PyFloat_FromDouble(result); + double result; + result = PyLong_AsDouble(v); + if (result == -1.0 && PyErr_Occurred()) + return NULL; + return PyFloat_FromDouble(result); } static PyObject * @@ -4073,47 +4073,47 @@ static PyObject * long_new(PyTypeObject *type, PyObject *args, PyObject *kwds) { - PyObject *x = NULL; - int base = -909; /* unlikely! */ - static char *kwlist[] = {"x", "base", 0}; - - if (type != &PyLong_Type) - return long_subtype_new(type, args, kwds); /* Wimp out */ - if (!PyArg_ParseTupleAndKeywords(args, kwds, "|Oi:int", kwlist, - &x, &base)) - return NULL; - if (x == NULL) - return PyLong_FromLong(0L); - if (base == -909) - return PyNumber_Long(x); - else if (PyUnicode_Check(x)) - return PyLong_FromUnicode(PyUnicode_AS_UNICODE(x), - PyUnicode_GET_SIZE(x), - base); - else if (PyByteArray_Check(x) || PyBytes_Check(x)) { - /* Since PyLong_FromString doesn't have a length parameter, - * check here for possible NULs in the string. */ - char *string; - Py_ssize_t size = Py_SIZE(x); - if (PyByteArray_Check(x)) - string = PyByteArray_AS_STRING(x); - else - string = PyBytes_AS_STRING(x); - if (strlen(string) != (size_t)size) { - /* We only see this if there's a null byte in x, - x is a bytes or buffer, *and* a base is given. */ - PyErr_Format(PyExc_ValueError, - "invalid literal for int() with base %d: %R", - base, x); - return NULL; - } - return PyLong_FromString(string, NULL, base); - } - else { - PyErr_SetString(PyExc_TypeError, - "int() can't convert non-string with explicit base"); - return NULL; - } + PyObject *x = NULL; + int base = -909; /* unlikely! */ + static char *kwlist[] = {"x", "base", 0}; + + if (type != &PyLong_Type) + return long_subtype_new(type, args, kwds); /* Wimp out */ + if (!PyArg_ParseTupleAndKeywords(args, kwds, "|Oi:int", kwlist, + &x, &base)) + return NULL; + if (x == NULL) + return PyLong_FromLong(0L); + if (base == -909) + return PyNumber_Long(x); + else if (PyUnicode_Check(x)) + return PyLong_FromUnicode(PyUnicode_AS_UNICODE(x), + PyUnicode_GET_SIZE(x), + base); + else if (PyByteArray_Check(x) || PyBytes_Check(x)) { + /* Since PyLong_FromString doesn't have a length parameter, + * check here for possible NULs in the string. */ + char *string; + Py_ssize_t size = Py_SIZE(x); + if (PyByteArray_Check(x)) + string = PyByteArray_AS_STRING(x); + else + string = PyBytes_AS_STRING(x); + if (strlen(string) != (size_t)size) { + /* We only see this if there's a null byte in x, + x is a bytes or buffer, *and* a base is given. */ + PyErr_Format(PyExc_ValueError, + "invalid literal for int() with base %d: %R", + base, x); + return NULL; + } + return PyLong_FromString(string, NULL, base); + } + else { + PyErr_SetString(PyExc_TypeError, + "int() can't convert non-string with explicit base"); + return NULL; + } } /* Wimpy, slow approach to tp_new calls for subtypes of long: @@ -4124,256 +4124,256 @@ static PyObject * long_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds) { - PyLongObject *tmp, *newobj; - Py_ssize_t i, n; + PyLongObject *tmp, *newobj; + Py_ssize_t i, n; - assert(PyType_IsSubtype(type, &PyLong_Type)); - tmp = (PyLongObject *)long_new(&PyLong_Type, args, kwds); - if (tmp == NULL) - return NULL; - assert(PyLong_CheckExact(tmp)); - n = Py_SIZE(tmp); - if (n < 0) - n = -n; - newobj = (PyLongObject *)type->tp_alloc(type, n); - if (newobj == NULL) { - Py_DECREF(tmp); - return NULL; - } - assert(PyLong_Check(newobj)); - Py_SIZE(newobj) = Py_SIZE(tmp); - for (i = 0; i < n; i++) - newobj->ob_digit[i] = tmp->ob_digit[i]; - Py_DECREF(tmp); - return (PyObject *)newobj; + assert(PyType_IsSubtype(type, &PyLong_Type)); + tmp = (PyLongObject *)long_new(&PyLong_Type, args, kwds); + if (tmp == NULL) + return NULL; + assert(PyLong_CheckExact(tmp)); + n = Py_SIZE(tmp); + if (n < 0) + n = -n; + newobj = (PyLongObject *)type->tp_alloc(type, n); + if (newobj == NULL) { + Py_DECREF(tmp); + return NULL; + } + assert(PyLong_Check(newobj)); + Py_SIZE(newobj) = Py_SIZE(tmp); + for (i = 0; i < n; i++) + newobj->ob_digit[i] = tmp->ob_digit[i]; + Py_DECREF(tmp); + return (PyObject *)newobj; } static PyObject * long_getnewargs(PyLongObject *v) { - return Py_BuildValue("(N)", _PyLong_Copy(v)); + return Py_BuildValue("(N)", _PyLong_Copy(v)); } static PyObject * long_get0(PyLongObject *v, void *context) { - return PyLong_FromLong(0L); + return PyLong_FromLong(0L); } static PyObject * long_get1(PyLongObject *v, void *context) { - return PyLong_FromLong(1L); + return PyLong_FromLong(1L); } static PyObject * long__format__(PyObject *self, PyObject *args) { - PyObject *format_spec; + PyObject *format_spec; - if (!PyArg_ParseTuple(args, "U:__format__", &format_spec)) - return NULL; - return _PyLong_FormatAdvanced(self, - PyUnicode_AS_UNICODE(format_spec), - PyUnicode_GET_SIZE(format_spec)); + if (!PyArg_ParseTuple(args, "U:__format__", &format_spec)) + return NULL; + return _PyLong_FormatAdvanced(self, + PyUnicode_AS_UNICODE(format_spec), + PyUnicode_GET_SIZE(format_spec)); } static PyObject * long_round(PyObject *self, PyObject *args) { - PyObject *o_ndigits=NULL, *temp; - PyLongObject *pow=NULL, *q=NULL, *r=NULL, *ndigits=NULL, *one; - int errcode; - digit q_mod_4; - - /* Notes on the algorithm: to round to the nearest 10**n (n positive), - the straightforward method is: - - (1) divide by 10**n - (2) round to nearest integer (round to even in case of tie) - (3) multiply result by 10**n. - - But the rounding step involves examining the fractional part of the - quotient to see whether it's greater than 0.5 or not. Since we - want to do the whole calculation in integer arithmetic, it's - simpler to do: - - (1) divide by (10**n)/2 - (2) round to nearest multiple of 2 (multiple of 4 in case of tie) - (3) multiply result by (10**n)/2. - - Then all we need to know about the fractional part of the quotient - arising in step (2) is whether it's zero or not. - - Doing both a multiplication and division is wasteful, and is easily - avoided if we just figure out how much to adjust the original input - by to do the rounding. - - Here's the whole algorithm expressed in Python. - - def round(self, ndigits = None): - """round(int, int) -> int""" - if ndigits is None or ndigits >= 0: - return self - pow = 10**-ndigits >> 1 - q, r = divmod(self, pow) - self -= r - if (q & 1 != 0): - if (q & 2 == r == 0): - self -= pow - else: - self += pow - return self - - */ - if (!PyArg_ParseTuple(args, "|O", &o_ndigits)) - return NULL; - if (o_ndigits == NULL) - return long_long(self); - - ndigits = (PyLongObject *)PyNumber_Index(o_ndigits); - if (ndigits == NULL) - return NULL; - - if (Py_SIZE(ndigits) >= 0) { - Py_DECREF(ndigits); - return long_long(self); - } - - Py_INCREF(self); /* to keep refcounting simple */ - /* we now own references to self, ndigits */ - - /* pow = 10 ** -ndigits >> 1 */ - pow = (PyLongObject *)PyLong_FromLong(10L); - if (pow == NULL) - goto error; - temp = long_neg(ndigits); - Py_DECREF(ndigits); - ndigits = (PyLongObject *)temp; - if (ndigits == NULL) - goto error; - temp = long_pow((PyObject *)pow, (PyObject *)ndigits, Py_None); - Py_DECREF(pow); - pow = (PyLongObject *)temp; - if (pow == NULL) - goto error; - assert(PyLong_Check(pow)); /* check long_pow returned a long */ - one = (PyLongObject *)PyLong_FromLong(1L); - if (one == NULL) - goto error; - temp = long_rshift(pow, one); - Py_DECREF(one); - Py_DECREF(pow); - pow = (PyLongObject *)temp; - if (pow == NULL) - goto error; - - /* q, r = divmod(self, pow) */ - errcode = l_divmod((PyLongObject *)self, pow, &q, &r); - if (errcode == -1) - goto error; - - /* self -= r */ - temp = long_sub((PyLongObject *)self, r); - Py_DECREF(self); - self = temp; - if (self == NULL) - goto error; - - /* get value of quotient modulo 4 */ - if (Py_SIZE(q) == 0) - q_mod_4 = 0; - else if (Py_SIZE(q) > 0) - q_mod_4 = q->ob_digit[0] & 3; - else - q_mod_4 = (PyLong_BASE-q->ob_digit[0]) & 3; - - if ((q_mod_4 & 1) == 1) { - /* q is odd; round self up or down by adding or subtracting pow */ - if (q_mod_4 == 1 && Py_SIZE(r) == 0) - temp = (PyObject *)long_sub((PyLongObject *)self, pow); - else - temp = (PyObject *)long_add((PyLongObject *)self, pow); - Py_DECREF(self); - self = temp; - if (self == NULL) - goto error; - } - Py_DECREF(q); - Py_DECREF(r); - Py_DECREF(pow); - Py_DECREF(ndigits); - return self; + PyObject *o_ndigits=NULL, *temp; + PyLongObject *pow=NULL, *q=NULL, *r=NULL, *ndigits=NULL, *one; + int errcode; + digit q_mod_4; + + /* Notes on the algorithm: to round to the nearest 10**n (n positive), + the straightforward method is: + + (1) divide by 10**n + (2) round to nearest integer (round to even in case of tie) + (3) multiply result by 10**n. + + But the rounding step involves examining the fractional part of the + quotient to see whether it's greater than 0.5 or not. Since we + want to do the whole calculation in integer arithmetic, it's + simpler to do: + + (1) divide by (10**n)/2 + (2) round to nearest multiple of 2 (multiple of 4 in case of tie) + (3) multiply result by (10**n)/2. + + Then all we need to know about the fractional part of the quotient + arising in step (2) is whether it's zero or not. + + Doing both a multiplication and division is wasteful, and is easily + avoided if we just figure out how much to adjust the original input + by to do the rounding. + + Here's the whole algorithm expressed in Python. + + def round(self, ndigits = None): + """round(int, int) -> int""" + if ndigits is None or ndigits >= 0: + return self + pow = 10**-ndigits >> 1 + q, r = divmod(self, pow) + self -= r + if (q & 1 != 0): + if (q & 2 == r == 0): + self -= pow + else: + self += pow + return self + + */ + if (!PyArg_ParseTuple(args, "|O", &o_ndigits)) + return NULL; + if (o_ndigits == NULL) + return long_long(self); + + ndigits = (PyLongObject *)PyNumber_Index(o_ndigits); + if (ndigits == NULL) + return NULL; + + if (Py_SIZE(ndigits) >= 0) { + Py_DECREF(ndigits); + return long_long(self); + } + + Py_INCREF(self); /* to keep refcounting simple */ + /* we now own references to self, ndigits */ + + /* pow = 10 ** -ndigits >> 1 */ + pow = (PyLongObject *)PyLong_FromLong(10L); + if (pow == NULL) + goto error; + temp = long_neg(ndigits); + Py_DECREF(ndigits); + ndigits = (PyLongObject *)temp; + if (ndigits == NULL) + goto error; + temp = long_pow((PyObject *)pow, (PyObject *)ndigits, Py_None); + Py_DECREF(pow); + pow = (PyLongObject *)temp; + if (pow == NULL) + goto error; + assert(PyLong_Check(pow)); /* check long_pow returned a long */ + one = (PyLongObject *)PyLong_FromLong(1L); + if (one == NULL) + goto error; + temp = long_rshift(pow, one); + Py_DECREF(one); + Py_DECREF(pow); + pow = (PyLongObject *)temp; + if (pow == NULL) + goto error; + + /* q, r = divmod(self, pow) */ + errcode = l_divmod((PyLongObject *)self, pow, &q, &r); + if (errcode == -1) + goto error; + + /* self -= r */ + temp = long_sub((PyLongObject *)self, r); + Py_DECREF(self); + self = temp; + if (self == NULL) + goto error; + + /* get value of quotient modulo 4 */ + if (Py_SIZE(q) == 0) + q_mod_4 = 0; + else if (Py_SIZE(q) > 0) + q_mod_4 = q->ob_digit[0] & 3; + else + q_mod_4 = (PyLong_BASE-q->ob_digit[0]) & 3; + + if ((q_mod_4 & 1) == 1) { + /* q is odd; round self up or down by adding or subtracting pow */ + if (q_mod_4 == 1 && Py_SIZE(r) == 0) + temp = (PyObject *)long_sub((PyLongObject *)self, pow); + else + temp = (PyObject *)long_add((PyLongObject *)self, pow); + Py_DECREF(self); + self = temp; + if (self == NULL) + goto error; + } + Py_DECREF(q); + Py_DECREF(r); + Py_DECREF(pow); + Py_DECREF(ndigits); + return self; error: - Py_XDECREF(q); - Py_XDECREF(r); - Py_XDECREF(pow); - Py_XDECREF(self); - Py_XDECREF(ndigits); - return NULL; + Py_XDECREF(q); + Py_XDECREF(r); + Py_XDECREF(pow); + Py_XDECREF(self); + Py_XDECREF(ndigits); + return NULL; } static PyObject * long_sizeof(PyLongObject *v) { - Py_ssize_t res; + Py_ssize_t res; - res = offsetof(PyLongObject, ob_digit) + ABS(Py_SIZE(v))*sizeof(digit); - return PyLong_FromSsize_t(res); + res = offsetof(PyLongObject, ob_digit) + ABS(Py_SIZE(v))*sizeof(digit); + return PyLong_FromSsize_t(res); } static PyObject * long_bit_length(PyLongObject *v) { - PyLongObject *result, *x, *y; - Py_ssize_t ndigits, msd_bits = 0; - digit msd; - - assert(v != NULL); - assert(PyLong_Check(v)); - - ndigits = ABS(Py_SIZE(v)); - if (ndigits == 0) - return PyLong_FromLong(0); - - msd = v->ob_digit[ndigits-1]; - while (msd >= 32) { - msd_bits += 6; - msd >>= 6; - } - msd_bits += (long)(BitLengthTable[msd]); - - if (ndigits <= PY_SSIZE_T_MAX/PyLong_SHIFT) - return PyLong_FromSsize_t((ndigits-1)*PyLong_SHIFT + msd_bits); - - /* expression above may overflow; use Python integers instead */ - result = (PyLongObject *)PyLong_FromSsize_t(ndigits - 1); - if (result == NULL) - return NULL; - x = (PyLongObject *)PyLong_FromLong(PyLong_SHIFT); - if (x == NULL) - goto error; - y = (PyLongObject *)long_mul(result, x); - Py_DECREF(x); - if (y == NULL) - goto error; - Py_DECREF(result); - result = y; - - x = (PyLongObject *)PyLong_FromLong((long)msd_bits); - if (x == NULL) - goto error; - y = (PyLongObject *)long_add(result, x); - Py_DECREF(x); - if (y == NULL) - goto error; - Py_DECREF(result); - result = y; + PyLongObject *result, *x, *y; + Py_ssize_t ndigits, msd_bits = 0; + digit msd; + + assert(v != NULL); + assert(PyLong_Check(v)); + + ndigits = ABS(Py_SIZE(v)); + if (ndigits == 0) + return PyLong_FromLong(0); + + msd = v->ob_digit[ndigits-1]; + while (msd >= 32) { + msd_bits += 6; + msd >>= 6; + } + msd_bits += (long)(BitLengthTable[msd]); + + if (ndigits <= PY_SSIZE_T_MAX/PyLong_SHIFT) + return PyLong_FromSsize_t((ndigits-1)*PyLong_SHIFT + msd_bits); + + /* expression above may overflow; use Python integers instead */ + result = (PyLongObject *)PyLong_FromSsize_t(ndigits - 1); + if (result == NULL) + return NULL; + x = (PyLongObject *)PyLong_FromLong(PyLong_SHIFT); + if (x == NULL) + goto error; + y = (PyLongObject *)long_mul(result, x); + Py_DECREF(x); + if (y == NULL) + goto error; + Py_DECREF(result); + result = y; + + x = (PyLongObject *)PyLong_FromLong((long)msd_bits); + if (x == NULL) + goto error; + y = (PyLongObject *)long_add(result, x); + Py_DECREF(x); + if (y == NULL) + goto error; + Py_DECREF(result); + result = y; - return (PyObject *)result; + return (PyObject *)result; error: - Py_DECREF(result); - return NULL; + Py_DECREF(result); + return NULL; } PyDoc_STRVAR(long_bit_length_doc, @@ -4389,7 +4389,7 @@ static PyObject * long_is_finite(PyObject *v) { - Py_RETURN_TRUE; + Py_RETURN_TRUE; } #endif @@ -4397,64 +4397,64 @@ static PyObject * long_to_bytes(PyLongObject *v, PyObject *args, PyObject *kwds) { - PyObject *byteorder_str; - PyObject *is_signed_obj = NULL; - Py_ssize_t length; - int little_endian; - int is_signed; - PyObject *bytes; - static char *kwlist[] = {"length", "byteorder", "signed", NULL}; - - if (!PyArg_ParseTupleAndKeywords(args, kwds, "nU|O:to_bytes", kwlist, - &length, &byteorder_str, - &is_signed_obj)) - return NULL; - - if (args != NULL && Py_SIZE(args) > 2) { - PyErr_SetString(PyExc_TypeError, - "'signed' is a keyword-only argument"); - return NULL; - } - - if (!PyUnicode_CompareWithASCIIString(byteorder_str, "little")) - little_endian = 1; - else if (!PyUnicode_CompareWithASCIIString(byteorder_str, "big")) - little_endian = 0; - else { - PyErr_SetString(PyExc_ValueError, - "byteorder must be either 'little' or 'big'"); - return NULL; - } - - if (is_signed_obj != NULL) { - int cmp = PyObject_IsTrue(is_signed_obj); - if (cmp < 0) - return NULL; - is_signed = cmp ? 1 : 0; - } - else { - /* If the signed argument was omitted, use False as the - default. */ - is_signed = 0; - } - - if (length < 0) { - PyErr_SetString(PyExc_ValueError, - "length argument must be non-negative"); - return NULL; - } - - bytes = PyBytes_FromStringAndSize(NULL, length); - if (bytes == NULL) - return NULL; - - if (_PyLong_AsByteArray(v, (unsigned char *)PyBytes_AS_STRING(bytes), - length, little_endian, is_signed) < 0) { - Py_DECREF(bytes); - return NULL; - } + PyObject *byteorder_str; + PyObject *is_signed_obj = NULL; + Py_ssize_t length; + int little_endian; + int is_signed; + PyObject *bytes; + static char *kwlist[] = {"length", "byteorder", "signed", NULL}; + + if (!PyArg_ParseTupleAndKeywords(args, kwds, "nU|O:to_bytes", kwlist, + &length, &byteorder_str, + &is_signed_obj)) + return NULL; + + if (args != NULL && Py_SIZE(args) > 2) { + PyErr_SetString(PyExc_TypeError, + "'signed' is a keyword-only argument"); + return NULL; + } + + if (!PyUnicode_CompareWithASCIIString(byteorder_str, "little")) + little_endian = 1; + else if (!PyUnicode_CompareWithASCIIString(byteorder_str, "big")) + little_endian = 0; + else { + PyErr_SetString(PyExc_ValueError, + "byteorder must be either 'little' or 'big'"); + return NULL; + } + + if (is_signed_obj != NULL) { + int cmp = PyObject_IsTrue(is_signed_obj); + if (cmp < 0) + return NULL; + is_signed = cmp ? 1 : 0; + } + else { + /* If the signed argument was omitted, use False as the + default. */ + is_signed = 0; + } + + if (length < 0) { + PyErr_SetString(PyExc_ValueError, + "length argument must be non-negative"); + return NULL; + } + + bytes = PyBytes_FromStringAndSize(NULL, length); + if (bytes == NULL) + return NULL; + + if (_PyLong_AsByteArray(v, (unsigned char *)PyBytes_AS_STRING(bytes), + length, little_endian, is_signed) < 0) { + Py_DECREF(bytes); + return NULL; + } - return bytes; + return bytes; } PyDoc_STRVAR(long_to_bytes_doc, @@ -4462,7 +4462,7 @@ \n\ Return an array of bytes representing an integer.\n\ \n\ -The integer is represented using length bytes. An OverflowError is\n\ +The integer is represented using length bytes. An OverflowError is\n\ raised if the integer is not representable with the given number of\n\ bytes.\n\ \n\ @@ -4473,87 +4473,87 @@ byte order of the host system, use `sys.byteorder' as the byte order value.\n\ \n\ The signed keyword-only argument determines whether two's complement is\n\ -used to represent the integer. If signed is False and a negative integer\n\ +used to represent the integer. If signed is False and a negative integer\n\ is given, an OverflowError is raised."); static PyObject * long_from_bytes(PyTypeObject *type, PyObject *args, PyObject *kwds) { - PyObject *byteorder_str; - PyObject *is_signed_obj = NULL; - int little_endian; - int is_signed; - PyObject *obj; - PyObject *bytes; - PyObject *long_obj; - static char *kwlist[] = {"bytes", "byteorder", "signed", NULL}; - - if (!PyArg_ParseTupleAndKeywords(args, kwds, "OU|O:from_bytes", kwlist, - &obj, &byteorder_str, - &is_signed_obj)) - return NULL; - - if (args != NULL && Py_SIZE(args) > 2) { - PyErr_SetString(PyExc_TypeError, - "'signed' is a keyword-only argument"); - return NULL; - } - - if (!PyUnicode_CompareWithASCIIString(byteorder_str, "little")) - little_endian = 1; - else if (!PyUnicode_CompareWithASCIIString(byteorder_str, "big")) - little_endian = 0; - else { - PyErr_SetString(PyExc_ValueError, - "byteorder must be either 'little' or 'big'"); - return NULL; - } - - if (is_signed_obj != NULL) { - int cmp = PyObject_IsTrue(is_signed_obj); - if (cmp < 0) - return NULL; - is_signed = cmp ? 1 : 0; - } - else { - /* If the signed argument was omitted, use False as the - default. */ - is_signed = 0; - } - - bytes = PyObject_Bytes(obj); - if (bytes == NULL) - return NULL; - - long_obj = _PyLong_FromByteArray( - (unsigned char *)PyBytes_AS_STRING(bytes), Py_SIZE(bytes), - little_endian, is_signed); - Py_DECREF(bytes); - - /* If from_bytes() was used on subclass, allocate new subclass - * instance, initialize it with decoded long value and return it. - */ - if (type != &PyLong_Type && PyType_IsSubtype(type, &PyLong_Type)) { - PyLongObject *newobj; - int i; - Py_ssize_t n = ABS(Py_SIZE(long_obj)); - - newobj = (PyLongObject *)type->tp_alloc(type, n); - if (newobj == NULL) { - Py_DECREF(long_obj); - return NULL; - } - assert(PyLong_Check(newobj)); - Py_SIZE(newobj) = Py_SIZE(long_obj); - for (i = 0; i < n; i++) { - newobj->ob_digit[i] = - ((PyLongObject *)long_obj)->ob_digit[i]; - } - Py_DECREF(long_obj); - return (PyObject *)newobj; - } + PyObject *byteorder_str; + PyObject *is_signed_obj = NULL; + int little_endian; + int is_signed; + PyObject *obj; + PyObject *bytes; + PyObject *long_obj; + static char *kwlist[] = {"bytes", "byteorder", "signed", NULL}; + + if (!PyArg_ParseTupleAndKeywords(args, kwds, "OU|O:from_bytes", kwlist, + &obj, &byteorder_str, + &is_signed_obj)) + return NULL; + + if (args != NULL && Py_SIZE(args) > 2) { + PyErr_SetString(PyExc_TypeError, + "'signed' is a keyword-only argument"); + return NULL; + } + + if (!PyUnicode_CompareWithASCIIString(byteorder_str, "little")) + little_endian = 1; + else if (!PyUnicode_CompareWithASCIIString(byteorder_str, "big")) + little_endian = 0; + else { + PyErr_SetString(PyExc_ValueError, + "byteorder must be either 'little' or 'big'"); + return NULL; + } + + if (is_signed_obj != NULL) { + int cmp = PyObject_IsTrue(is_signed_obj); + if (cmp < 0) + return NULL; + is_signed = cmp ? 1 : 0; + } + else { + /* If the signed argument was omitted, use False as the + default. */ + is_signed = 0; + } + + bytes = PyObject_Bytes(obj); + if (bytes == NULL) + return NULL; + + long_obj = _PyLong_FromByteArray( + (unsigned char *)PyBytes_AS_STRING(bytes), Py_SIZE(bytes), + little_endian, is_signed); + Py_DECREF(bytes); + + /* If from_bytes() was used on subclass, allocate new subclass + * instance, initialize it with decoded long value and return it. + */ + if (type != &PyLong_Type && PyType_IsSubtype(type, &PyLong_Type)) { + PyLongObject *newobj; + int i; + Py_ssize_t n = ABS(Py_SIZE(long_obj)); + + newobj = (PyLongObject *)type->tp_alloc(type, n); + if (newobj == NULL) { + Py_DECREF(long_obj); + return NULL; + } + assert(PyLong_Check(newobj)); + Py_SIZE(newobj) = Py_SIZE(long_obj); + for (i = 0; i < n; i++) { + newobj->ob_digit[i] = + ((PyLongObject *)long_obj)->ob_digit[i]; + } + Py_DECREF(long_obj); + return (PyObject *)newobj; + } - return long_obj; + return long_obj; } PyDoc_STRVAR(long_from_bytes_doc, @@ -4575,32 +4575,32 @@ used to represent the integer."); static PyMethodDef long_methods[] = { - {"conjugate", (PyCFunction)long_long, METH_NOARGS, - "Returns self, the complex conjugate of any int."}, - {"bit_length", (PyCFunction)long_bit_length, METH_NOARGS, - long_bit_length_doc}, + {"conjugate", (PyCFunction)long_long, METH_NOARGS, + "Returns self, the complex conjugate of any int."}, + {"bit_length", (PyCFunction)long_bit_length, METH_NOARGS, + long_bit_length_doc}, #if 0 - {"is_finite", (PyCFunction)long_is_finite, METH_NOARGS, - "Returns always True."}, + {"is_finite", (PyCFunction)long_is_finite, METH_NOARGS, + "Returns always True."}, #endif - {"to_bytes", (PyCFunction)long_to_bytes, - METH_VARARGS|METH_KEYWORDS, long_to_bytes_doc}, - {"from_bytes", (PyCFunction)long_from_bytes, - METH_VARARGS|METH_KEYWORDS|METH_CLASS, long_from_bytes_doc}, - {"__trunc__", (PyCFunction)long_long, METH_NOARGS, - "Truncating an Integral returns itself."}, - {"__floor__", (PyCFunction)long_long, METH_NOARGS, - "Flooring an Integral returns itself."}, - {"__ceil__", (PyCFunction)long_long, METH_NOARGS, - "Ceiling of an Integral returns itself."}, - {"__round__", (PyCFunction)long_round, METH_VARARGS, - "Rounding an Integral returns itself.\n" - "Rounding with an ndigits argument also returns an integer."}, - {"__getnewargs__", (PyCFunction)long_getnewargs, METH_NOARGS}, - {"__format__", (PyCFunction)long__format__, METH_VARARGS}, - {"__sizeof__", (PyCFunction)long_sizeof, METH_NOARGS, - "Returns size in memory, in bytes"}, - {NULL, NULL} /* sentinel */ + {"to_bytes", (PyCFunction)long_to_bytes, + METH_VARARGS|METH_KEYWORDS, long_to_bytes_doc}, + {"from_bytes", (PyCFunction)long_from_bytes, + METH_VARARGS|METH_KEYWORDS|METH_CLASS, long_from_bytes_doc}, + {"__trunc__", (PyCFunction)long_long, METH_NOARGS, + "Truncating an Integral returns itself."}, + {"__floor__", (PyCFunction)long_long, METH_NOARGS, + "Flooring an Integral returns itself."}, + {"__ceil__", (PyCFunction)long_long, METH_NOARGS, + "Ceiling of an Integral returns itself."}, + {"__round__", (PyCFunction)long_round, METH_VARARGS, + "Rounding an Integral returns itself.\n" + "Rounding with an ndigits argument also returns an integer."}, + {"__getnewargs__", (PyCFunction)long_getnewargs, METH_NOARGS}, + {"__format__", (PyCFunction)long__format__, METH_VARARGS}, + {"__sizeof__", (PyCFunction)long_sizeof, METH_NOARGS, + "Returns size in memory, in bytes"}, + {NULL, NULL} /* sentinel */ }; static PyGetSetDef long_getset[] = { @@ -4633,83 +4633,83 @@ converting a non-string."); static PyNumberMethods long_as_number = { - (binaryfunc) long_add, /*nb_add*/ - (binaryfunc) long_sub, /*nb_subtract*/ - (binaryfunc) long_mul, /*nb_multiply*/ - long_mod, /*nb_remainder*/ - long_divmod, /*nb_divmod*/ - long_pow, /*nb_power*/ - (unaryfunc) long_neg, /*nb_negative*/ - (unaryfunc) long_long, /*tp_positive*/ - (unaryfunc) long_abs, /*tp_absolute*/ - (inquiry) long_bool, /*tp_bool*/ - (unaryfunc) long_invert, /*nb_invert*/ - long_lshift, /*nb_lshift*/ - (binaryfunc) long_rshift, /*nb_rshift*/ - long_and, /*nb_and*/ - long_xor, /*nb_xor*/ - long_or, /*nb_or*/ - long_long, /*nb_int*/ - 0, /*nb_reserved*/ - long_float, /*nb_float*/ - 0, /* nb_inplace_add */ - 0, /* nb_inplace_subtract */ - 0, /* nb_inplace_multiply */ - 0, /* nb_inplace_remainder */ - 0, /* nb_inplace_power */ - 0, /* nb_inplace_lshift */ - 0, /* nb_inplace_rshift */ - 0, /* nb_inplace_and */ - 0, /* nb_inplace_xor */ - 0, /* nb_inplace_or */ - long_div, /* nb_floor_divide */ - long_true_divide, /* nb_true_divide */ - 0, /* nb_inplace_floor_divide */ - 0, /* nb_inplace_true_divide */ - long_long, /* nb_index */ + (binaryfunc) long_add, /*nb_add*/ + (binaryfunc) long_sub, /*nb_subtract*/ + (binaryfunc) long_mul, /*nb_multiply*/ + long_mod, /*nb_remainder*/ + long_divmod, /*nb_divmod*/ + long_pow, /*nb_power*/ + (unaryfunc) long_neg, /*nb_negative*/ + (unaryfunc) long_long, /*tp_positive*/ + (unaryfunc) long_abs, /*tp_absolute*/ + (inquiry) long_bool, /*tp_bool*/ + (unaryfunc) long_invert, /*nb_invert*/ + long_lshift, /*nb_lshift*/ + (binaryfunc) long_rshift, /*nb_rshift*/ + long_and, /*nb_and*/ + long_xor, /*nb_xor*/ + long_or, /*nb_or*/ + long_long, /*nb_int*/ + 0, /*nb_reserved*/ + long_float, /*nb_float*/ + 0, /* nb_inplace_add */ + 0, /* nb_inplace_subtract */ + 0, /* nb_inplace_multiply */ + 0, /* nb_inplace_remainder */ + 0, /* nb_inplace_power */ + 0, /* nb_inplace_lshift */ + 0, /* nb_inplace_rshift */ + 0, /* nb_inplace_and */ + 0, /* nb_inplace_xor */ + 0, /* nb_inplace_or */ + long_div, /* nb_floor_divide */ + long_true_divide, /* nb_true_divide */ + 0, /* nb_inplace_floor_divide */ + 0, /* nb_inplace_true_divide */ + long_long, /* nb_index */ }; PyTypeObject PyLong_Type = { - PyVarObject_HEAD_INIT(&PyType_Type, 0) - "int", /* tp_name */ - offsetof(PyLongObject, ob_digit), /* tp_basicsize */ - sizeof(digit), /* tp_itemsize */ - long_dealloc, /* tp_dealloc */ - 0, /* tp_print */ - 0, /* tp_getattr */ - 0, /* tp_setattr */ - 0, /* tp_reserved */ - long_to_decimal_string, /* tp_repr */ - &long_as_number, /* tp_as_number */ - 0, /* tp_as_sequence */ - 0, /* tp_as_mapping */ - (hashfunc)long_hash, /* tp_hash */ - 0, /* tp_call */ - long_to_decimal_string, /* tp_str */ - PyObject_GenericGetAttr, /* tp_getattro */ - 0, /* tp_setattro */ - 0, /* tp_as_buffer */ - Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | - Py_TPFLAGS_LONG_SUBCLASS, /* tp_flags */ - long_doc, /* tp_doc */ - 0, /* tp_traverse */ - 0, /* tp_clear */ - long_richcompare, /* tp_richcompare */ - 0, /* tp_weaklistoffset */ - 0, /* tp_iter */ - 0, /* tp_iternext */ - long_methods, /* tp_methods */ - 0, /* tp_members */ - long_getset, /* tp_getset */ - 0, /* tp_base */ - 0, /* tp_dict */ - 0, /* tp_descr_get */ - 0, /* tp_descr_set */ - 0, /* tp_dictoffset */ - 0, /* tp_init */ - 0, /* tp_alloc */ - long_new, /* tp_new */ - PyObject_Del, /* tp_free */ + PyVarObject_HEAD_INIT(&PyType_Type, 0) + "int", /* tp_name */ + offsetof(PyLongObject, ob_digit), /* tp_basicsize */ + sizeof(digit), /* tp_itemsize */ + long_dealloc, /* tp_dealloc */ + 0, /* tp_print */ + 0, /* tp_getattr */ + 0, /* tp_setattr */ + 0, /* tp_reserved */ + long_to_decimal_string, /* tp_repr */ + &long_as_number, /* tp_as_number */ + 0, /* tp_as_sequence */ + 0, /* tp_as_mapping */ + (hashfunc)long_hash, /* tp_hash */ + 0, /* tp_call */ + long_to_decimal_string, /* tp_str */ + PyObject_GenericGetAttr, /* tp_getattro */ + 0, /* tp_setattro */ + 0, /* tp_as_buffer */ + Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | + Py_TPFLAGS_LONG_SUBCLASS, /* tp_flags */ + long_doc, /* tp_doc */ + 0, /* tp_traverse */ + 0, /* tp_clear */ + long_richcompare, /* tp_richcompare */ + 0, /* tp_weaklistoffset */ + 0, /* tp_iter */ + 0, /* tp_iternext */ + long_methods, /* tp_methods */ + 0, /* tp_members */ + long_getset, /* tp_getset */ + 0, /* tp_base */ + 0, /* tp_dict */ + 0, /* tp_descr_get */ + 0, /* tp_descr_set */ + 0, /* tp_dictoffset */ + 0, /* tp_init */ + 0, /* tp_alloc */ + long_new, /* tp_new */ + PyObject_Del, /* tp_free */ }; static PyTypeObject Int_InfoType; @@ -4721,89 +4721,89 @@ internal representation of integers. The attributes are read only."); static PyStructSequence_Field int_info_fields[] = { - {"bits_per_digit", "size of a digit in bits"}, - {"sizeof_digit", "size in bytes of the C type used to " - "represent a digit"}, - {NULL, NULL} + {"bits_per_digit", "size of a digit in bits"}, + {"sizeof_digit", "size in bytes of the C type used to " + "represent a digit"}, + {NULL, NULL} }; static PyStructSequence_Desc int_info_desc = { - "sys.int_info", /* name */ - int_info__doc__, /* doc */ - int_info_fields, /* fields */ - 2 /* number of fields */ + "sys.int_info", /* name */ + int_info__doc__, /* doc */ + int_info_fields, /* fields */ + 2 /* number of fields */ }; PyObject * PyLong_GetInfo(void) { - PyObject* int_info; - int field = 0; - int_info = PyStructSequence_New(&Int_InfoType); - if (int_info == NULL) - return NULL; - PyStructSequence_SET_ITEM(int_info, field++, - PyLong_FromLong(PyLong_SHIFT)); - PyStructSequence_SET_ITEM(int_info, field++, - PyLong_FromLong(sizeof(digit))); - if (PyErr_Occurred()) { - Py_CLEAR(int_info); - return NULL; - } - return int_info; + PyObject* int_info; + int field = 0; + int_info = PyStructSequence_New(&Int_InfoType); + if (int_info == NULL) + return NULL; + PyStructSequence_SET_ITEM(int_info, field++, + PyLong_FromLong(PyLong_SHIFT)); + PyStructSequence_SET_ITEM(int_info, field++, + PyLong_FromLong(sizeof(digit))); + if (PyErr_Occurred()) { + Py_CLEAR(int_info); + return NULL; + } + return int_info; } int _PyLong_Init(void) { #if NSMALLNEGINTS + NSMALLPOSINTS > 0 - int ival, size; - PyLongObject *v = small_ints; + int ival, size; + PyLongObject *v = small_ints; - for (ival = -NSMALLNEGINTS; ival < NSMALLPOSINTS; ival++, v++) { - size = (ival < 0) ? -1 : ((ival == 0) ? 0 : 1); - if (Py_TYPE(v) == &PyLong_Type) { - /* The element is already initialized, most likely - * the Python interpreter was initialized before. - */ - Py_ssize_t refcnt; - PyObject* op = (PyObject*)v; - - refcnt = Py_REFCNT(op) < 0 ? 0 : Py_REFCNT(op); - _Py_NewReference(op); - /* _Py_NewReference sets the ref count to 1 but - * the ref count might be larger. Set the refcnt - * to the original refcnt + 1 */ - Py_REFCNT(op) = refcnt + 1; - assert(Py_SIZE(op) == size); - assert(v->ob_digit[0] == abs(ival)); - } - else { - PyObject_INIT(v, &PyLong_Type); - } - Py_SIZE(v) = size; - v->ob_digit[0] = abs(ival); - } + for (ival = -NSMALLNEGINTS; ival < NSMALLPOSINTS; ival++, v++) { + size = (ival < 0) ? -1 : ((ival == 0) ? 0 : 1); + if (Py_TYPE(v) == &PyLong_Type) { + /* The element is already initialized, most likely + * the Python interpreter was initialized before. + */ + Py_ssize_t refcnt; + PyObject* op = (PyObject*)v; + + refcnt = Py_REFCNT(op) < 0 ? 0 : Py_REFCNT(op); + _Py_NewReference(op); + /* _Py_NewReference sets the ref count to 1 but + * the ref count might be larger. Set the refcnt + * to the original refcnt + 1 */ + Py_REFCNT(op) = refcnt + 1; + assert(Py_SIZE(op) == size); + assert(v->ob_digit[0] == abs(ival)); + } + else { + PyObject_INIT(v, &PyLong_Type); + } + Py_SIZE(v) = size; + v->ob_digit[0] = abs(ival); + } #endif - /* initialize int_info */ - if (Int_InfoType.tp_name == 0) - PyStructSequence_InitType(&Int_InfoType, &int_info_desc); + /* initialize int_info */ + if (Int_InfoType.tp_name == 0) + PyStructSequence_InitType(&Int_InfoType, &int_info_desc); - return 1; + return 1; } void PyLong_Fini(void) { - /* Integers are currently statically allocated. Py_DECREF is not - needed, but Python must forget about the reference or multiple - reinitializations will fail. */ + /* Integers are currently statically allocated. Py_DECREF is not + needed, but Python must forget about the reference or multiple + reinitializations will fail. */ #if NSMALLNEGINTS + NSMALLPOSINTS > 0 - int i; - PyLongObject *v = small_ints; - for (i = 0; i < NSMALLNEGINTS + NSMALLPOSINTS; i++, v++) { - _Py_DEC_REFTOTAL; - _Py_ForgetReference((PyObject*)v); - } + int i; + PyLongObject *v = small_ints; + for (i = 0; i < NSMALLNEGINTS + NSMALLPOSINTS; i++, v++) { + _Py_DEC_REFTOTAL; + _Py_ForgetReference((PyObject*)v); + } #endif } Modified: python/branches/py3k-jit/Objects/methodobject.c ============================================================================== --- python/branches/py3k-jit/Objects/methodobject.c (original) +++ python/branches/py3k-jit/Objects/methodobject.c Mon May 10 23:55:43 2010 @@ -16,104 +16,104 @@ PyObject * PyCFunction_NewEx(PyMethodDef *ml, PyObject *self, PyObject *module) { - PyCFunctionObject *op; - op = free_list; - if (op != NULL) { - free_list = (PyCFunctionObject *)(op->m_self); - PyObject_INIT(op, &PyCFunction_Type); - numfree--; - } - else { - op = PyObject_GC_New(PyCFunctionObject, &PyCFunction_Type); - if (op == NULL) - return NULL; - } - op->m_ml = ml; - Py_XINCREF(self); - op->m_self = self; - Py_XINCREF(module); - op->m_module = module; - _PyObject_GC_TRACK(op); - return (PyObject *)op; + PyCFunctionObject *op; + op = free_list; + if (op != NULL) { + free_list = (PyCFunctionObject *)(op->m_self); + PyObject_INIT(op, &PyCFunction_Type); + numfree--; + } + else { + op = PyObject_GC_New(PyCFunctionObject, &PyCFunction_Type); + if (op == NULL) + return NULL; + } + op->m_ml = ml; + Py_XINCREF(self); + op->m_self = self; + Py_XINCREF(module); + op->m_module = module; + _PyObject_GC_TRACK(op); + return (PyObject *)op; } PyCFunction PyCFunction_GetFunction(PyObject *op) { - if (!PyCFunction_Check(op)) { - PyErr_BadInternalCall(); - return NULL; - } - return ((PyCFunctionObject *)op) -> m_ml -> ml_meth; + if (!PyCFunction_Check(op)) { + PyErr_BadInternalCall(); + return NULL; + } + return ((PyCFunctionObject *)op) -> m_ml -> ml_meth; } PyObject * PyCFunction_GetSelf(PyObject *op) { - if (!PyCFunction_Check(op)) { - PyErr_BadInternalCall(); - return NULL; - } - return ((PyCFunctionObject *)op) -> m_self; + if (!PyCFunction_Check(op)) { + PyErr_BadInternalCall(); + return NULL; + } + return ((PyCFunctionObject *)op) -> m_self; } int PyCFunction_GetFlags(PyObject *op) { - if (!PyCFunction_Check(op)) { - PyErr_BadInternalCall(); - return -1; - } - return ((PyCFunctionObject *)op) -> m_ml -> ml_flags; + if (!PyCFunction_Check(op)) { + PyErr_BadInternalCall(); + return -1; + } + return ((PyCFunctionObject *)op) -> m_ml -> ml_flags; } PyObject * PyCFunction_Call(PyObject *func, PyObject *arg, PyObject *kw) { - PyCFunctionObject* f = (PyCFunctionObject*)func; - PyCFunction meth = PyCFunction_GET_FUNCTION(func); - PyObject *self = PyCFunction_GET_SELF(func); - Py_ssize_t size; - - switch (PyCFunction_GET_FLAGS(func) & ~(METH_CLASS | METH_STATIC | METH_COEXIST)) { - case METH_VARARGS: - if (kw == NULL || PyDict_Size(kw) == 0) - return (*meth)(self, arg); - break; - case METH_VARARGS | METH_KEYWORDS: - return (*(PyCFunctionWithKeywords)meth)(self, arg, kw); - case METH_NOARGS: - if (kw == NULL || PyDict_Size(kw) == 0) { - size = PyTuple_GET_SIZE(arg); - if (size == 0) - return (*meth)(self, NULL); - PyErr_Format(PyExc_TypeError, - "%.200s() takes no arguments (%zd given)", - f->m_ml->ml_name, size); - return NULL; - } - break; - case METH_O: - if (kw == NULL || PyDict_Size(kw) == 0) { - size = PyTuple_GET_SIZE(arg); - if (size == 1) - return (*meth)(self, PyTuple_GET_ITEM(arg, 0)); - PyErr_Format(PyExc_TypeError, - "%.200s() takes exactly one argument (%zd given)", - f->m_ml->ml_name, size); - return NULL; - } - break; - default: - PyErr_SetString(PyExc_SystemError, "Bad call flags in " - "PyCFunction_Call. METH_OLDARGS is no " - "longer supported!"); - - return NULL; - } - PyErr_Format(PyExc_TypeError, "%.200s() takes no keyword arguments", - f->m_ml->ml_name); - return NULL; + PyCFunctionObject* f = (PyCFunctionObject*)func; + PyCFunction meth = PyCFunction_GET_FUNCTION(func); + PyObject *self = PyCFunction_GET_SELF(func); + Py_ssize_t size; + + switch (PyCFunction_GET_FLAGS(func) & ~(METH_CLASS | METH_STATIC | METH_COEXIST)) { + case METH_VARARGS: + if (kw == NULL || PyDict_Size(kw) == 0) + return (*meth)(self, arg); + break; + case METH_VARARGS | METH_KEYWORDS: + return (*(PyCFunctionWithKeywords)meth)(self, arg, kw); + case METH_NOARGS: + if (kw == NULL || PyDict_Size(kw) == 0) { + size = PyTuple_GET_SIZE(arg); + if (size == 0) + return (*meth)(self, NULL); + PyErr_Format(PyExc_TypeError, + "%.200s() takes no arguments (%zd given)", + f->m_ml->ml_name, size); + return NULL; + } + break; + case METH_O: + if (kw == NULL || PyDict_Size(kw) == 0) { + size = PyTuple_GET_SIZE(arg); + if (size == 1) + return (*meth)(self, PyTuple_GET_ITEM(arg, 0)); + PyErr_Format(PyExc_TypeError, + "%.200s() takes exactly one argument (%zd given)", + f->m_ml->ml_name, size); + return NULL; + } + break; + default: + PyErr_SetString(PyExc_SystemError, "Bad call flags in " + "PyCFunction_Call. METH_OLDARGS is no " + "longer supported!"); + + return NULL; + } + PyErr_Format(PyExc_TypeError, "%.200s() takes no keyword arguments", + f->m_ml->ml_name); + return NULL; } /* Methods (the standard built-in methods, that is) */ @@ -121,163 +121,163 @@ static void meth_dealloc(PyCFunctionObject *m) { - _PyObject_GC_UNTRACK(m); - Py_XDECREF(m->m_self); - Py_XDECREF(m->m_module); - if (numfree < PyCFunction_MAXFREELIST) { - m->m_self = (PyObject *)free_list; - free_list = m; - numfree++; - } - else { - PyObject_GC_Del(m); - } + _PyObject_GC_UNTRACK(m); + Py_XDECREF(m->m_self); + Py_XDECREF(m->m_module); + if (numfree < PyCFunction_MAXFREELIST) { + m->m_self = (PyObject *)free_list; + free_list = m; + numfree++; + } + else { + PyObject_GC_Del(m); + } } static PyObject * meth_get__doc__(PyCFunctionObject *m, void *closure) { - const char *doc = m->m_ml->ml_doc; + const char *doc = m->m_ml->ml_doc; - if (doc != NULL) - return PyUnicode_FromString(doc); - Py_INCREF(Py_None); - return Py_None; + if (doc != NULL) + return PyUnicode_FromString(doc); + Py_INCREF(Py_None); + return Py_None; } static PyObject * meth_get__name__(PyCFunctionObject *m, void *closure) { - return PyUnicode_FromString(m->m_ml->ml_name); + return PyUnicode_FromString(m->m_ml->ml_name); } static int meth_traverse(PyCFunctionObject *m, visitproc visit, void *arg) { - Py_VISIT(m->m_self); - Py_VISIT(m->m_module); - return 0; + Py_VISIT(m->m_self); + Py_VISIT(m->m_module); + return 0; } static PyObject * meth_get__self__(PyCFunctionObject *m, void *closure) { - PyObject *self; + PyObject *self; - self = m->m_self; - if (self == NULL) - self = Py_None; - Py_INCREF(self); - return self; + self = m->m_self; + if (self == NULL) + self = Py_None; + Py_INCREF(self); + return self; } static PyGetSetDef meth_getsets [] = { - {"__doc__", (getter)meth_get__doc__, NULL, NULL}, - {"__name__", (getter)meth_get__name__, NULL, NULL}, - {"__self__", (getter)meth_get__self__, NULL, NULL}, - {0} + {"__doc__", (getter)meth_get__doc__, NULL, NULL}, + {"__name__", (getter)meth_get__name__, NULL, NULL}, + {"__self__", (getter)meth_get__self__, NULL, NULL}, + {0} }; #define OFF(x) offsetof(PyCFunctionObject, x) static PyMemberDef meth_members[] = { - {"__module__", T_OBJECT, OFF(m_module), PY_WRITE_RESTRICTED}, - {NULL} + {"__module__", T_OBJECT, OFF(m_module), PY_WRITE_RESTRICTED}, + {NULL} }; static PyObject * meth_repr(PyCFunctionObject *m) { - if (m->m_self == NULL || PyModule_Check(m->m_self)) - return PyUnicode_FromFormat("", - m->m_ml->ml_name); - return PyUnicode_FromFormat("", - m->m_ml->ml_name, - m->m_self->ob_type->tp_name, - m->m_self); + if (m->m_self == NULL || PyModule_Check(m->m_self)) + return PyUnicode_FromFormat("", + m->m_ml->ml_name); + return PyUnicode_FromFormat("", + m->m_ml->ml_name, + m->m_self->ob_type->tp_name, + m->m_self); } static PyObject * meth_richcompare(PyObject *self, PyObject *other, int op) { - PyCFunctionObject *a, *b; - PyObject *res; - int eq; - - if ((op != Py_EQ && op != Py_NE) || - !PyCFunction_Check(self) || - !PyCFunction_Check(other)) - { - Py_INCREF(Py_NotImplemented); - return Py_NotImplemented; - } - a = (PyCFunctionObject *)self; - b = (PyCFunctionObject *)other; - eq = a->m_self == b->m_self; - if (eq) - eq = a->m_ml->ml_meth == b->m_ml->ml_meth; - if (op == Py_EQ) - res = eq ? Py_True : Py_False; - else - res = eq ? Py_False : Py_True; - Py_INCREF(res); - return res; + PyCFunctionObject *a, *b; + PyObject *res; + int eq; + + if ((op != Py_EQ && op != Py_NE) || + !PyCFunction_Check(self) || + !PyCFunction_Check(other)) + { + Py_INCREF(Py_NotImplemented); + return Py_NotImplemented; + } + a = (PyCFunctionObject *)self; + b = (PyCFunctionObject *)other; + eq = a->m_self == b->m_self; + if (eq) + eq = a->m_ml->ml_meth == b->m_ml->ml_meth; + if (op == Py_EQ) + res = eq ? Py_True : Py_False; + else + res = eq ? Py_False : Py_True; + Py_INCREF(res); + return res; } static long meth_hash(PyCFunctionObject *a) { - long x,y; - if (a->m_self == NULL) - x = 0; - else { - x = PyObject_Hash(a->m_self); - if (x == -1) - return -1; - } - y = _Py_HashPointer((void*)(a->m_ml->ml_meth)); - if (y == -1) - return -1; - x ^= y; - if (x == -1) - x = -2; - return x; + long x,y; + if (a->m_self == NULL) + x = 0; + else { + x = PyObject_Hash(a->m_self); + if (x == -1) + return -1; + } + y = _Py_HashPointer((void*)(a->m_ml->ml_meth)); + if (y == -1) + return -1; + x ^= y; + if (x == -1) + x = -2; + return x; } PyTypeObject PyCFunction_Type = { - PyVarObject_HEAD_INIT(&PyType_Type, 0) - "builtin_function_or_method", - sizeof(PyCFunctionObject), - 0, - (destructor)meth_dealloc, /* tp_dealloc */ - 0, /* tp_print */ - 0, /* tp_getattr */ - 0, /* tp_setattr */ - 0, /* tp_reserved */ - (reprfunc)meth_repr, /* tp_repr */ - 0, /* tp_as_number */ - 0, /* tp_as_sequence */ - 0, /* tp_as_mapping */ - (hashfunc)meth_hash, /* tp_hash */ - PyCFunction_Call, /* 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)meth_traverse, /* tp_traverse */ - 0, /* tp_clear */ - meth_richcompare, /* tp_richcompare */ - 0, /* tp_weaklistoffset */ - 0, /* tp_iter */ - 0, /* tp_iternext */ - 0, /* tp_methods */ - meth_members, /* tp_members */ - meth_getsets, /* tp_getset */ - 0, /* tp_base */ - 0, /* tp_dict */ + PyVarObject_HEAD_INIT(&PyType_Type, 0) + "builtin_function_or_method", + sizeof(PyCFunctionObject), + 0, + (destructor)meth_dealloc, /* tp_dealloc */ + 0, /* tp_print */ + 0, /* tp_getattr */ + 0, /* tp_setattr */ + 0, /* tp_reserved */ + (reprfunc)meth_repr, /* tp_repr */ + 0, /* tp_as_number */ + 0, /* tp_as_sequence */ + 0, /* tp_as_mapping */ + (hashfunc)meth_hash, /* tp_hash */ + PyCFunction_Call, /* 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)meth_traverse, /* tp_traverse */ + 0, /* tp_clear */ + meth_richcompare, /* tp_richcompare */ + 0, /* tp_weaklistoffset */ + 0, /* tp_iter */ + 0, /* tp_iternext */ + 0, /* tp_methods */ + meth_members, /* tp_members */ + meth_getsets, /* tp_getset */ + 0, /* tp_base */ + 0, /* tp_dict */ }; /* Clear out the free list */ @@ -285,22 +285,22 @@ int PyCFunction_ClearFreeList(void) { - int freelist_size = numfree; - - while (free_list) { - PyCFunctionObject *v = free_list; - free_list = (PyCFunctionObject *)(v->m_self); - PyObject_GC_Del(v); - numfree--; - } - assert(numfree == 0); - return freelist_size; + int freelist_size = numfree; + + while (free_list) { + PyCFunctionObject *v = free_list; + free_list = (PyCFunctionObject *)(v->m_self); + PyObject_GC_Del(v); + numfree--; + } + assert(numfree == 0); + return freelist_size; } void PyCFunction_Fini(void) { - (void)PyCFunction_ClearFreeList(); + (void)PyCFunction_ClearFreeList(); } /* PyCFunction_New() is now just a macro that calls PyCFunction_NewEx(), @@ -314,5 +314,5 @@ PyObject * PyCFunction_New(PyMethodDef *ml, PyObject *self) { - return PyCFunction_NewEx(ml, self, NULL); + return PyCFunction_NewEx(ml, self, NULL); } Modified: python/branches/py3k-jit/Objects/moduleobject.c ============================================================================== --- python/branches/py3k-jit/Objects/moduleobject.c (original) +++ python/branches/py3k-jit/Objects/moduleobject.c Mon May 10 23:55:43 2010 @@ -7,53 +7,53 @@ static Py_ssize_t max_module_number; typedef struct { - PyObject_HEAD - PyObject *md_dict; - struct PyModuleDef *md_def; - void *md_state; + PyObject_HEAD + PyObject *md_dict; + struct PyModuleDef *md_def; + void *md_state; } PyModuleObject; static PyMemberDef module_members[] = { - {"__dict__", T_OBJECT, offsetof(PyModuleObject, md_dict), READONLY}, - {0} + {"__dict__", T_OBJECT, offsetof(PyModuleObject, md_dict), READONLY}, + {0} }; static PyTypeObject moduledef_type = { - PyVarObject_HEAD_INIT(&PyType_Type, 0) - "moduledef", /* tp_name */ - sizeof(struct PyModuleDef), /* tp_size */ - 0, /* tp_itemsize */ + PyVarObject_HEAD_INIT(&PyType_Type, 0) + "moduledef", /* tp_name */ + sizeof(struct PyModuleDef), /* tp_size */ + 0, /* tp_itemsize */ }; PyObject * PyModule_New(const char *name) { - PyModuleObject *m; - PyObject *nameobj; - m = PyObject_GC_New(PyModuleObject, &PyModule_Type); - if (m == NULL) - return NULL; - m->md_def = NULL; - m->md_state = NULL; - nameobj = PyUnicode_FromString(name); - m->md_dict = PyDict_New(); - if (m->md_dict == NULL || nameobj == NULL) - goto fail; - if (PyDict_SetItemString(m->md_dict, "__name__", nameobj) != 0) - goto fail; - if (PyDict_SetItemString(m->md_dict, "__doc__", Py_None) != 0) - goto fail; - if (PyDict_SetItemString(m->md_dict, "__package__", Py_None) != 0) - goto fail; - Py_DECREF(nameobj); - PyObject_GC_Track(m); - return (PyObject *)m; + PyModuleObject *m; + PyObject *nameobj; + m = PyObject_GC_New(PyModuleObject, &PyModule_Type); + if (m == NULL) + return NULL; + m->md_def = NULL; + m->md_state = NULL; + nameobj = PyUnicode_FromString(name); + m->md_dict = PyDict_New(); + if (m->md_dict == NULL || nameobj == NULL) + goto fail; + if (PyDict_SetItemString(m->md_dict, "__name__", nameobj) != 0) + goto fail; + if (PyDict_SetItemString(m->md_dict, "__doc__", Py_None) != 0) + goto fail; + if (PyDict_SetItemString(m->md_dict, "__package__", Py_None) != 0) + goto fail; + Py_DECREF(nameobj); + PyObject_GC_Track(m); + return (PyObject *)m; fail: - Py_XDECREF(nameobj); - Py_DECREF(m); - return NULL; + Py_XDECREF(nameobj); + Py_DECREF(m); + return NULL; } static char api_version_warning[] = @@ -63,231 +63,231 @@ PyObject * PyModule_Create2(struct PyModuleDef* module, int module_api_version) { - PyObject *d, *v, *n; - PyMethodDef *ml; - const char* name; - PyModuleObject *m; - if (!Py_IsInitialized()) - Py_FatalError("Interpreter not initialized (version mismatch?)"); - if (PyType_Ready(&moduledef_type) < 0) - return NULL; - if (module->m_base.m_index == 0) { - max_module_number++; - Py_REFCNT(module) = 1; - Py_TYPE(module) = &moduledef_type; - module->m_base.m_index = max_module_number; - } - name = module->m_name; - if (module_api_version != PYTHON_API_VERSION) { - char message[512]; - PyOS_snprintf(message, sizeof(message), - api_version_warning, name, - PYTHON_API_VERSION, name, - module_api_version); - if (PyErr_WarnEx(PyExc_RuntimeWarning, message, 1)) - return NULL; - } - /* Make sure name is fully qualified. - - This is a bit of a hack: when the shared library is loaded, - the module name is "package.module", but the module calls - PyModule_Create*() with just "module" for the name. The shared - library loader squirrels away the true name of the module in - _Py_PackageContext, and PyModule_Create*() will substitute this - (if the name actually matches). - */ - if (_Py_PackageContext != NULL) { - char *p = strrchr(_Py_PackageContext, '.'); - if (p != NULL && strcmp(module->m_name, p+1) == 0) { - name = _Py_PackageContext; - _Py_PackageContext = NULL; - } - } - if ((m = (PyModuleObject*)PyModule_New(name)) == NULL) - return NULL; - - if (module->m_size > 0) { - m->md_state = PyMem_MALLOC(module->m_size); - if (!m->md_state) { - PyErr_NoMemory(); - Py_DECREF(m); - return NULL; - } - memset(m->md_state, 0, module->m_size); - } - - d = PyModule_GetDict((PyObject*)m); - if (module->m_methods != NULL) { - n = PyUnicode_FromString(name); - if (n == NULL) - return NULL; - for (ml = module->m_methods; ml->ml_name != NULL; ml++) { - if ((ml->ml_flags & METH_CLASS) || - (ml->ml_flags & METH_STATIC)) { - PyErr_SetString(PyExc_ValueError, - "module functions cannot set" - " METH_CLASS or METH_STATIC"); - Py_DECREF(n); - return NULL; - } - v = PyCFunction_NewEx(ml, (PyObject*)m, n); - if (v == NULL) { - Py_DECREF(n); - return NULL; - } - if (PyDict_SetItemString(d, ml->ml_name, v) != 0) { - Py_DECREF(v); - Py_DECREF(n); - return NULL; - } - Py_DECREF(v); - } - Py_DECREF(n); - } - if (module->m_doc != NULL) { - v = PyUnicode_FromString(module->m_doc); - if (v == NULL || PyDict_SetItemString(d, "__doc__", v) != 0) { - Py_XDECREF(v); - return NULL; - } - Py_DECREF(v); - } - m->md_def = module; - return (PyObject*)m; + PyObject *d, *v, *n; + PyMethodDef *ml; + const char* name; + PyModuleObject *m; + if (!Py_IsInitialized()) + Py_FatalError("Interpreter not initialized (version mismatch?)"); + if (PyType_Ready(&moduledef_type) < 0) + return NULL; + if (module->m_base.m_index == 0) { + max_module_number++; + Py_REFCNT(module) = 1; + Py_TYPE(module) = &moduledef_type; + module->m_base.m_index = max_module_number; + } + name = module->m_name; + if (module_api_version != PYTHON_API_VERSION) { + char message[512]; + PyOS_snprintf(message, sizeof(message), + api_version_warning, name, + PYTHON_API_VERSION, name, + module_api_version); + if (PyErr_WarnEx(PyExc_RuntimeWarning, message, 1)) + return NULL; + } + /* Make sure name is fully qualified. + + This is a bit of a hack: when the shared library is loaded, + the module name is "package.module", but the module calls + PyModule_Create*() with just "module" for the name. The shared + library loader squirrels away the true name of the module in + _Py_PackageContext, and PyModule_Create*() will substitute this + (if the name actually matches). + */ + if (_Py_PackageContext != NULL) { + char *p = strrchr(_Py_PackageContext, '.'); + if (p != NULL && strcmp(module->m_name, p+1) == 0) { + name = _Py_PackageContext; + _Py_PackageContext = NULL; + } + } + if ((m = (PyModuleObject*)PyModule_New(name)) == NULL) + return NULL; + + if (module->m_size > 0) { + m->md_state = PyMem_MALLOC(module->m_size); + if (!m->md_state) { + PyErr_NoMemory(); + Py_DECREF(m); + return NULL; + } + memset(m->md_state, 0, module->m_size); + } + + d = PyModule_GetDict((PyObject*)m); + if (module->m_methods != NULL) { + n = PyUnicode_FromString(name); + if (n == NULL) + return NULL; + for (ml = module->m_methods; ml->ml_name != NULL; ml++) { + if ((ml->ml_flags & METH_CLASS) || + (ml->ml_flags & METH_STATIC)) { + PyErr_SetString(PyExc_ValueError, + "module functions cannot set" + " METH_CLASS or METH_STATIC"); + Py_DECREF(n); + return NULL; + } + v = PyCFunction_NewEx(ml, (PyObject*)m, n); + if (v == NULL) { + Py_DECREF(n); + return NULL; + } + if (PyDict_SetItemString(d, ml->ml_name, v) != 0) { + Py_DECREF(v); + Py_DECREF(n); + return NULL; + } + Py_DECREF(v); + } + Py_DECREF(n); + } + if (module->m_doc != NULL) { + v = PyUnicode_FromString(module->m_doc); + if (v == NULL || PyDict_SetItemString(d, "__doc__", v) != 0) { + Py_XDECREF(v); + return NULL; + } + Py_DECREF(v); + } + m->md_def = module; + return (PyObject*)m; } PyObject * PyModule_GetDict(PyObject *m) { - PyObject *d; - if (!PyModule_Check(m)) { - PyErr_BadInternalCall(); - return NULL; - } - d = ((PyModuleObject *)m) -> md_dict; - if (d == NULL) - ((PyModuleObject *)m) -> md_dict = d = PyDict_New(); - return d; + PyObject *d; + if (!PyModule_Check(m)) { + PyErr_BadInternalCall(); + return NULL; + } + d = ((PyModuleObject *)m) -> md_dict; + if (d == NULL) + ((PyModuleObject *)m) -> md_dict = d = PyDict_New(); + return d; } const char * PyModule_GetName(PyObject *m) { - PyObject *d; - PyObject *nameobj; - if (!PyModule_Check(m)) { - PyErr_BadArgument(); - return NULL; - } - d = ((PyModuleObject *)m)->md_dict; - if (d == NULL || - (nameobj = PyDict_GetItemString(d, "__name__")) == NULL || - !PyUnicode_Check(nameobj)) - { - PyErr_SetString(PyExc_SystemError, "nameless module"); - return NULL; - } - return _PyUnicode_AsString(nameobj); + PyObject *d; + PyObject *nameobj; + if (!PyModule_Check(m)) { + PyErr_BadArgument(); + return NULL; + } + d = ((PyModuleObject *)m)->md_dict; + if (d == NULL || + (nameobj = PyDict_GetItemString(d, "__name__")) == NULL || + !PyUnicode_Check(nameobj)) + { + PyErr_SetString(PyExc_SystemError, "nameless module"); + return NULL; + } + return _PyUnicode_AsString(nameobj); } static PyObject* module_getfilename(PyObject *m) { - PyObject *d; - PyObject *fileobj; - if (!PyModule_Check(m)) { - PyErr_BadArgument(); - return NULL; - } - d = ((PyModuleObject *)m)->md_dict; - if (d == NULL || - (fileobj = PyDict_GetItemString(d, "__file__")) == NULL || - !PyUnicode_Check(fileobj)) - { - PyErr_SetString(PyExc_SystemError, "module filename missing"); - return NULL; - } - return fileobj; + PyObject *d; + PyObject *fileobj; + if (!PyModule_Check(m)) { + PyErr_BadArgument(); + return NULL; + } + d = ((PyModuleObject *)m)->md_dict; + if (d == NULL || + (fileobj = PyDict_GetItemString(d, "__file__")) == NULL || + !PyUnicode_Check(fileobj)) + { + PyErr_SetString(PyExc_SystemError, "module filename missing"); + return NULL; + } + return fileobj; } const char * PyModule_GetFilename(PyObject *m) { - PyObject *fileobj; - fileobj = module_getfilename(m); - if (fileobj == NULL) - return NULL; - return _PyUnicode_AsString(fileobj); + PyObject *fileobj; + fileobj = module_getfilename(m); + if (fileobj == NULL) + return NULL; + return _PyUnicode_AsString(fileobj); } PyModuleDef* PyModule_GetDef(PyObject* m) { - if (!PyModule_Check(m)) { - PyErr_BadArgument(); - return NULL; - } - return ((PyModuleObject *)m)->md_def; + if (!PyModule_Check(m)) { + PyErr_BadArgument(); + return NULL; + } + return ((PyModuleObject *)m)->md_def; } void* PyModule_GetState(PyObject* m) { - if (!PyModule_Check(m)) { - PyErr_BadArgument(); - return NULL; - } - return ((PyModuleObject *)m)->md_state; + if (!PyModule_Check(m)) { + PyErr_BadArgument(); + return NULL; + } + return ((PyModuleObject *)m)->md_state; } void _PyModule_Clear(PyObject *m) { - /* To make the execution order of destructors for global - objects a bit more predictable, we first zap all objects - whose name starts with a single underscore, before we clear - the entire dictionary. We zap them by replacing them with - None, rather than deleting them from the dictionary, to - avoid rehashing the dictionary (to some extent). */ - - Py_ssize_t pos; - PyObject *key, *value; - PyObject *d; - - d = ((PyModuleObject *)m)->md_dict; - if (d == NULL) - return; - - /* First, clear only names starting with a single underscore */ - pos = 0; - while (PyDict_Next(d, &pos, &key, &value)) { - if (value != Py_None && PyUnicode_Check(key)) { - const char *s = _PyUnicode_AsString(key); - if (s[0] == '_' && s[1] != '_') { - if (Py_VerboseFlag > 1) - PySys_WriteStderr("# clear[1] %s\n", s); - PyDict_SetItem(d, key, Py_None); - } - } - } - - /* Next, clear all names except for __builtins__ */ - pos = 0; - while (PyDict_Next(d, &pos, &key, &value)) { - if (value != Py_None && PyUnicode_Check(key)) { - const char *s = _PyUnicode_AsString(key); - if (s[0] != '_' || strcmp(s, "__builtins__") != 0) { - if (Py_VerboseFlag > 1) - PySys_WriteStderr("# clear[2] %s\n", s); - PyDict_SetItem(d, key, Py_None); - } - } - } - - /* Note: we leave __builtins__ in place, so that destructors - of non-global objects defined in this module can still use - builtins, in particularly 'None'. */ + /* To make the execution order of destructors for global + objects a bit more predictable, we first zap all objects + whose name starts with a single underscore, before we clear + the entire dictionary. We zap them by replacing them with + None, rather than deleting them from the dictionary, to + avoid rehashing the dictionary (to some extent). */ + + Py_ssize_t pos; + PyObject *key, *value; + PyObject *d; + + d = ((PyModuleObject *)m)->md_dict; + if (d == NULL) + return; + + /* First, clear only names starting with a single underscore */ + pos = 0; + while (PyDict_Next(d, &pos, &key, &value)) { + if (value != Py_None && PyUnicode_Check(key)) { + const char *s = _PyUnicode_AsString(key); + if (s[0] == '_' && s[1] != '_') { + if (Py_VerboseFlag > 1) + PySys_WriteStderr("# clear[1] %s\n", s); + PyDict_SetItem(d, key, Py_None); + } + } + } + + /* Next, clear all names except for __builtins__ */ + pos = 0; + while (PyDict_Next(d, &pos, &key, &value)) { + if (value != Py_None && PyUnicode_Check(key)) { + const char *s = _PyUnicode_AsString(key); + if (s[0] != '_' || strcmp(s, "__builtins__") != 0) { + if (Py_VerboseFlag > 1) + PySys_WriteStderr("# clear[2] %s\n", s); + PyDict_SetItem(d, key, Py_None); + } + } + } + + /* Note: we leave __builtins__ in place, so that destructors + of non-global objects defined in this module can still use + builtins, in particularly 'None'. */ } @@ -296,86 +296,86 @@ static int module_init(PyModuleObject *m, PyObject *args, PyObject *kwds) { - static char *kwlist[] = {"name", "doc", NULL}; - PyObject *dict, *name = Py_None, *doc = Py_None; - if (!PyArg_ParseTupleAndKeywords(args, kwds, "U|O:module.__init__", - kwlist, &name, &doc)) - return -1; - dict = m->md_dict; - if (dict == NULL) { - dict = PyDict_New(); - if (dict == NULL) - return -1; - m->md_dict = dict; - } - if (PyDict_SetItemString(dict, "__name__", name) < 0) - return -1; - if (PyDict_SetItemString(dict, "__doc__", doc) < 0) - return -1; - return 0; + static char *kwlist[] = {"name", "doc", NULL}; + PyObject *dict, *name = Py_None, *doc = Py_None; + if (!PyArg_ParseTupleAndKeywords(args, kwds, "U|O:module.__init__", + kwlist, &name, &doc)) + return -1; + dict = m->md_dict; + if (dict == NULL) { + dict = PyDict_New(); + if (dict == NULL) + return -1; + m->md_dict = dict; + } + if (PyDict_SetItemString(dict, "__name__", name) < 0) + return -1; + if (PyDict_SetItemString(dict, "__doc__", doc) < 0) + return -1; + return 0; } static void module_dealloc(PyModuleObject *m) { - PyObject_GC_UnTrack(m); - if (m->md_def && m->md_def->m_free) - m->md_def->m_free(m); - if (m->md_dict != NULL) { - /* If we are the only ones holding a reference, we can clear - the dictionary. */ - if (Py_REFCNT(m->md_dict) == 1) - _PyModule_Clear((PyObject *)m); - Py_DECREF(m->md_dict); - } - if (m->md_state != NULL) - PyMem_FREE(m->md_state); - Py_TYPE(m)->tp_free((PyObject *)m); + PyObject_GC_UnTrack(m); + if (m->md_def && m->md_def->m_free) + m->md_def->m_free(m); + if (m->md_dict != NULL) { + /* If we are the only ones holding a reference, we can clear + the dictionary. */ + if (Py_REFCNT(m->md_dict) == 1) + _PyModule_Clear((PyObject *)m); + Py_DECREF(m->md_dict); + } + if (m->md_state != NULL) + PyMem_FREE(m->md_state); + Py_TYPE(m)->tp_free((PyObject *)m); } static PyObject * module_repr(PyModuleObject *m) { - const char *name; - PyObject *filename; + const char *name; + PyObject *filename; - name = PyModule_GetName((PyObject *)m); - if (name == NULL) { - PyErr_Clear(); - name = "?"; - } - filename = module_getfilename((PyObject *)m); - if (filename == NULL) { - PyErr_Clear(); - return PyUnicode_FromFormat("", name); - } - return PyUnicode_FromFormat("", name, filename); + name = PyModule_GetName((PyObject *)m); + if (name == NULL) { + PyErr_Clear(); + name = "?"; + } + filename = module_getfilename((PyObject *)m); + if (filename == NULL) { + PyErr_Clear(); + return PyUnicode_FromFormat("", name); + } + return PyUnicode_FromFormat("", name, filename); } static int module_traverse(PyModuleObject *m, visitproc visit, void *arg) { - if (m->md_def && m->md_def->m_traverse) { - int res = m->md_def->m_traverse((PyObject*)m, visit, arg); - if (res) - return res; - } - Py_VISIT(m->md_dict); - return 0; + if (m->md_def && m->md_def->m_traverse) { + int res = m->md_def->m_traverse((PyObject*)m, visit, arg); + if (res) + return res; + } + Py_VISIT(m->md_dict); + return 0; } static int module_clear(PyModuleObject *m) { - if (m->md_def && m->md_def->m_clear) { - int res = m->md_def->m_clear((PyObject*)m); - if (res) - return res; - } - Py_CLEAR(m->md_dict); - return 0; + if (m->md_def && m->md_def->m_clear) { + int res = m->md_def->m_clear((PyObject*)m); + if (res) + return res; + } + Py_CLEAR(m->md_dict); + return 0; } - + PyDoc_STRVAR(module_doc, "module(name[, doc])\n\ @@ -384,44 +384,44 @@ 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 */ - 0, /* tp_itemsize */ - (destructor)module_dealloc, /* tp_dealloc */ - 0, /* tp_print */ - 0, /* tp_getattr */ - 0, /* tp_setattr */ - 0, /* tp_reserved */ - (reprfunc)module_repr, /* 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 */ - PyObject_GenericSetAttr, /* tp_setattro */ - 0, /* tp_as_buffer */ - Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC | - Py_TPFLAGS_BASETYPE, /* tp_flags */ - module_doc, /* tp_doc */ - (traverseproc)module_traverse, /* tp_traverse */ - (inquiry)module_clear, /* tp_clear */ - 0, /* tp_richcompare */ - 0, /* tp_weaklistoffset */ - 0, /* tp_iter */ - 0, /* tp_iternext */ - 0, /* tp_methods */ - module_members, /* tp_members */ - 0, /* tp_getset */ - 0, /* tp_base */ - 0, /* tp_dict */ - 0, /* tp_descr_get */ - 0, /* tp_descr_set */ - offsetof(PyModuleObject, md_dict), /* tp_dictoffset */ - (initproc)module_init, /* tp_init */ - PyType_GenericAlloc, /* tp_alloc */ - PyType_GenericNew, /* tp_new */ - PyObject_GC_Del, /* tp_free */ + PyVarObject_HEAD_INIT(&PyType_Type, 0) + "module", /* tp_name */ + sizeof(PyModuleObject), /* tp_size */ + 0, /* tp_itemsize */ + (destructor)module_dealloc, /* tp_dealloc */ + 0, /* tp_print */ + 0, /* tp_getattr */ + 0, /* tp_setattr */ + 0, /* tp_reserved */ + (reprfunc)module_repr, /* 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 */ + PyObject_GenericSetAttr, /* tp_setattro */ + 0, /* tp_as_buffer */ + Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC | + Py_TPFLAGS_BASETYPE, /* tp_flags */ + module_doc, /* tp_doc */ + (traverseproc)module_traverse, /* tp_traverse */ + (inquiry)module_clear, /* tp_clear */ + 0, /* tp_richcompare */ + 0, /* tp_weaklistoffset */ + 0, /* tp_iter */ + 0, /* tp_iternext */ + 0, /* tp_methods */ + module_members, /* tp_members */ + 0, /* tp_getset */ + 0, /* tp_base */ + 0, /* tp_dict */ + 0, /* tp_descr_get */ + 0, /* tp_descr_set */ + offsetof(PyModuleObject, md_dict), /* tp_dictoffset */ + (initproc)module_init, /* tp_init */ + PyType_GenericAlloc, /* tp_alloc */ + PyType_GenericNew, /* tp_new */ + PyObject_GC_Del, /* tp_free */ }; Modified: python/branches/py3k-jit/Objects/object.c ============================================================================== --- python/branches/py3k-jit/Objects/object.c (original) +++ python/branches/py3k-jit/Objects/object.c Mon May 10 23:55:43 2010 @@ -15,18 +15,18 @@ Py_ssize_t _Py_GetRefTotal(void) { - PyObject *o; - Py_ssize_t total = _Py_RefTotal; - /* ignore the references to the dummy object of the dicts and sets - because they are not reliable and not useful (now that the - hash table code is well-tested) */ - o = _PyDict_Dummy(); - if (o != NULL) - total -= o->ob_refcnt; - o = _PySet_Dummy(); - if (o != NULL) - total -= o->ob_refcnt; - return total; + PyObject *o; + Py_ssize_t total = _Py_RefTotal; + /* ignore the references to the dummy object of the dicts and sets + because they are not reliable and not useful (now that the + hash table code is well-tested) */ + o = _PyDict_Dummy(); + if (o != NULL) + total -= o->ob_refcnt; + o = _PySet_Dummy(); + if (o != NULL) + total -= o->ob_refcnt; + return total; } #endif /* Py_REF_DEBUG */ @@ -58,21 +58,21 @@ _Py_AddToAllObjects(PyObject *op, int force) { #ifdef Py_DEBUG - if (!force) { - /* If it's initialized memory, op must be in or out of - * the list unambiguously. - */ - assert((op->_ob_prev == NULL) == (op->_ob_next == NULL)); - } + if (!force) { + /* If it's initialized memory, op must be in or out of + * the list unambiguously. + */ + assert((op->_ob_prev == NULL) == (op->_ob_next == NULL)); + } #endif - if (force || op->_ob_prev == NULL) { - op->_ob_next = refchain._ob_next; - op->_ob_prev = &refchain; - refchain._ob_next->_ob_prev = op; - refchain._ob_next = op; - } + if (force || op->_ob_prev == NULL) { + op->_ob_next = refchain._ob_next; + op->_ob_prev = &refchain; + refchain._ob_next->_ob_prev = op; + refchain._ob_next = op; + } } -#endif /* Py_TRACE_REFS */ +#endif /* Py_TRACE_REFS */ #ifdef COUNT_ALLOCS static PyTypeObject *type_list; @@ -89,99 +89,99 @@ void dump_counts(FILE* f) { - PyTypeObject *tp; + PyTypeObject *tp; - for (tp = type_list; tp; tp = tp->tp_next) - fprintf(f, "%s alloc'd: %" PY_FORMAT_SIZE_T "d, " - "freed: %" PY_FORMAT_SIZE_T "d, " - "max in use: %" PY_FORMAT_SIZE_T "d\n", - tp->tp_name, tp->tp_allocs, tp->tp_frees, - tp->tp_maxalloc); - fprintf(f, "fast tuple allocs: %" PY_FORMAT_SIZE_T "d, " - "empty: %" PY_FORMAT_SIZE_T "d\n", - fast_tuple_allocs, tuple_zero_allocs); - fprintf(f, "fast int allocs: pos: %" PY_FORMAT_SIZE_T "d, " - "neg: %" PY_FORMAT_SIZE_T "d\n", - quick_int_allocs, quick_neg_int_allocs); - fprintf(f, "null strings: %" PY_FORMAT_SIZE_T "d, " - "1-strings: %" PY_FORMAT_SIZE_T "d\n", - null_strings, one_strings); + for (tp = type_list; tp; tp = tp->tp_next) + fprintf(f, "%s alloc'd: %" PY_FORMAT_SIZE_T "d, " + "freed: %" PY_FORMAT_SIZE_T "d, " + "max in use: %" PY_FORMAT_SIZE_T "d\n", + tp->tp_name, tp->tp_allocs, tp->tp_frees, + tp->tp_maxalloc); + fprintf(f, "fast tuple allocs: %" PY_FORMAT_SIZE_T "d, " + "empty: %" PY_FORMAT_SIZE_T "d\n", + fast_tuple_allocs, tuple_zero_allocs); + fprintf(f, "fast int allocs: pos: %" PY_FORMAT_SIZE_T "d, " + "neg: %" PY_FORMAT_SIZE_T "d\n", + quick_int_allocs, quick_neg_int_allocs); + fprintf(f, "null strings: %" PY_FORMAT_SIZE_T "d, " + "1-strings: %" PY_FORMAT_SIZE_T "d\n", + null_strings, one_strings); } PyObject * get_counts(void) { - PyTypeObject *tp; - PyObject *result; - PyObject *v; - - result = PyList_New(0); - if (result == NULL) - return NULL; - for (tp = type_list; tp; tp = tp->tp_next) { - v = Py_BuildValue("(snnn)", tp->tp_name, tp->tp_allocs, - tp->tp_frees, tp->tp_maxalloc); - if (v == NULL) { - Py_DECREF(result); - return NULL; - } - if (PyList_Append(result, v) < 0) { - Py_DECREF(v); - Py_DECREF(result); - return NULL; - } - Py_DECREF(v); - } - return result; + PyTypeObject *tp; + PyObject *result; + PyObject *v; + + result = PyList_New(0); + if (result == NULL) + return NULL; + for (tp = type_list; tp; tp = tp->tp_next) { + v = Py_BuildValue("(snnn)", tp->tp_name, tp->tp_allocs, + tp->tp_frees, tp->tp_maxalloc); + if (v == NULL) { + Py_DECREF(result); + return NULL; + } + if (PyList_Append(result, v) < 0) { + Py_DECREF(v); + Py_DECREF(result); + return NULL; + } + Py_DECREF(v); + } + return result; } void inc_count(PyTypeObject *tp) { - if (tp->tp_next == NULL && tp->tp_prev == NULL) { - /* first time; insert in linked list */ - if (tp->tp_next != NULL) /* sanity check */ - Py_FatalError("XXX inc_count sanity check"); - if (type_list) - type_list->tp_prev = tp; - tp->tp_next = type_list; - /* Note that as of Python 2.2, heap-allocated type objects - * can go away, but this code requires that they stay alive - * until program exit. That's why we're careful with - * refcounts here. type_list gets a new reference to tp, - * while ownership of the reference type_list used to hold - * (if any) was transferred to tp->tp_next in the line above. - * tp is thus effectively immortal after this. - */ - Py_INCREF(tp); - type_list = tp; + if (tp->tp_next == NULL && tp->tp_prev == NULL) { + /* first time; insert in linked list */ + if (tp->tp_next != NULL) /* sanity check */ + Py_FatalError("XXX inc_count sanity check"); + if (type_list) + type_list->tp_prev = tp; + tp->tp_next = type_list; + /* Note that as of Python 2.2, heap-allocated type objects + * can go away, but this code requires that they stay alive + * until program exit. That's why we're careful with + * refcounts here. type_list gets a new reference to tp, + * while ownership of the reference type_list used to hold + * (if any) was transferred to tp->tp_next in the line above. + * tp is thus effectively immortal after this. + */ + Py_INCREF(tp); + type_list = tp; #ifdef Py_TRACE_REFS - /* Also insert in the doubly-linked list of all objects, - * if not already there. - */ - _Py_AddToAllObjects((PyObject *)tp, 0); + /* Also insert in the doubly-linked list of all objects, + * if not already there. + */ + _Py_AddToAllObjects((PyObject *)tp, 0); #endif - } - tp->tp_allocs++; - if (tp->tp_allocs - tp->tp_frees > tp->tp_maxalloc) - tp->tp_maxalloc = tp->tp_allocs - tp->tp_frees; + } + tp->tp_allocs++; + if (tp->tp_allocs - tp->tp_frees > tp->tp_maxalloc) + tp->tp_maxalloc = tp->tp_allocs - tp->tp_frees; } void dec_count(PyTypeObject *tp) { - tp->tp_frees++; - if (unlist_types_without_objects && - tp->tp_allocs == tp->tp_frees) { - /* unlink the type from type_list */ - if (tp->tp_prev) - tp->tp_prev->tp_next = tp->tp_next; - else - type_list = tp->tp_next; - if (tp->tp_next) - tp->tp_next->tp_prev = tp->tp_prev; - tp->tp_next = tp->tp_prev = NULL; - Py_DECREF(tp); - } + tp->tp_frees++; + if (unlist_types_without_objects && + tp->tp_allocs == tp->tp_frees) { + /* unlink the type from type_list */ + if (tp->tp_prev) + tp->tp_prev->tp_next = tp->tp_next; + else + type_list = tp->tp_next; + if (tp->tp_next) + tp->tp_next->tp_prev = tp->tp_prev; + tp->tp_next = tp->tp_prev = NULL; + Py_DECREF(tp); + } } #endif @@ -191,13 +191,13 @@ void _Py_NegativeRefcount(const char *fname, int lineno, PyObject *op) { - char buf[300]; + char buf[300]; - PyOS_snprintf(buf, sizeof(buf), - "%s:%i object at %p has negative ref count " - "%" PY_FORMAT_SIZE_T "d", - fname, lineno, op, op->ob_refcnt); - Py_FatalError(buf); + PyOS_snprintf(buf, sizeof(buf), + "%s:%i object at %p has negative ref count " + "%" PY_FORMAT_SIZE_T "d", + fname, lineno, op, op->ob_refcnt); + Py_FatalError(buf); } #endif /* Py_REF_DEBUG */ @@ -217,123 +217,123 @@ PyObject * PyObject_Init(PyObject *op, PyTypeObject *tp) { - if (op == NULL) - return PyErr_NoMemory(); - /* Any changes should be reflected in PyObject_INIT (objimpl.h) */ - Py_TYPE(op) = tp; - _Py_NewReference(op); - return op; + if (op == NULL) + return PyErr_NoMemory(); + /* Any changes should be reflected in PyObject_INIT (objimpl.h) */ + Py_TYPE(op) = tp; + _Py_NewReference(op); + return op; } PyVarObject * PyObject_InitVar(PyVarObject *op, PyTypeObject *tp, Py_ssize_t size) { - if (op == NULL) - return (PyVarObject *) PyErr_NoMemory(); - /* Any changes should be reflected in PyObject_INIT_VAR */ - op->ob_size = size; - Py_TYPE(op) = tp; - _Py_NewReference((PyObject *)op); - return op; + if (op == NULL) + return (PyVarObject *) PyErr_NoMemory(); + /* Any changes should be reflected in PyObject_INIT_VAR */ + op->ob_size = size; + Py_TYPE(op) = tp; + _Py_NewReference((PyObject *)op); + return op; } PyObject * _PyObject_New(PyTypeObject *tp) { - PyObject *op; - op = (PyObject *) PyObject_MALLOC(_PyObject_SIZE(tp)); - if (op == NULL) - return PyErr_NoMemory(); - return PyObject_INIT(op, tp); + PyObject *op; + op = (PyObject *) PyObject_MALLOC(_PyObject_SIZE(tp)); + if (op == NULL) + return PyErr_NoMemory(); + return PyObject_INIT(op, tp); } PyVarObject * _PyObject_NewVar(PyTypeObject *tp, Py_ssize_t nitems) { - PyVarObject *op; - const size_t size = _PyObject_VAR_SIZE(tp, nitems); - op = (PyVarObject *) PyObject_MALLOC(size); - if (op == NULL) - return (PyVarObject *)PyErr_NoMemory(); - return PyObject_INIT_VAR(op, tp, nitems); + PyVarObject *op; + const size_t size = _PyObject_VAR_SIZE(tp, nitems); + op = (PyVarObject *) PyObject_MALLOC(size); + if (op == NULL) + return (PyVarObject *)PyErr_NoMemory(); + return PyObject_INIT_VAR(op, tp, nitems); } /* Implementation of PyObject_Print with recursion checking */ static int internal_print(PyObject *op, FILE *fp, int flags, int nesting) { - int ret = 0; - if (nesting > 10) { - PyErr_SetString(PyExc_RuntimeError, "print recursion"); - return -1; - } - if (PyErr_CheckSignals()) - return -1; + int ret = 0; + if (nesting > 10) { + PyErr_SetString(PyExc_RuntimeError, "print recursion"); + return -1; + } + if (PyErr_CheckSignals()) + return -1; #ifdef USE_STACKCHECK - if (PyOS_CheckStack()) { - PyErr_SetString(PyExc_MemoryError, "stack overflow"); - return -1; - } + if (PyOS_CheckStack()) { + PyErr_SetString(PyExc_MemoryError, "stack overflow"); + return -1; + } #endif - clearerr(fp); /* Clear any previous error condition */ - if (op == NULL) { - Py_BEGIN_ALLOW_THREADS - fprintf(fp, ""); - Py_END_ALLOW_THREADS - } - else { - if (op->ob_refcnt <= 0) - /* XXX(twouters) cast refcount to long until %zd is - universally available */ - Py_BEGIN_ALLOW_THREADS - fprintf(fp, "", - (long)op->ob_refcnt, op); - Py_END_ALLOW_THREADS - else { - PyObject *s; - if (flags & Py_PRINT_RAW) - s = PyObject_Str(op); - else - s = PyObject_Repr(op); - if (s == NULL) - ret = -1; - else if (PyBytes_Check(s)) { - fwrite(PyBytes_AS_STRING(s), 1, - PyBytes_GET_SIZE(s), fp); - } - else if (PyUnicode_Check(s)) { - PyObject *t; - t = _PyUnicode_AsDefaultEncodedString(s, NULL); - if (t == NULL) - ret = 0; - else { - fwrite(PyBytes_AS_STRING(t), 1, - PyBytes_GET_SIZE(t), fp); - } - } - else { - PyErr_Format(PyExc_TypeError, - "str() or repr() returned '%.100s'", - s->ob_type->tp_name); - ret = -1; - } - Py_XDECREF(s); - } - } - if (ret == 0) { - if (ferror(fp)) { - PyErr_SetFromErrno(PyExc_IOError); - clearerr(fp); - ret = -1; - } - } - return ret; + clearerr(fp); /* Clear any previous error condition */ + if (op == NULL) { + Py_BEGIN_ALLOW_THREADS + fprintf(fp, ""); + Py_END_ALLOW_THREADS + } + else { + if (op->ob_refcnt <= 0) + /* XXX(twouters) cast refcount to long until %zd is + universally available */ + Py_BEGIN_ALLOW_THREADS + fprintf(fp, "", + (long)op->ob_refcnt, op); + Py_END_ALLOW_THREADS + else { + PyObject *s; + if (flags & Py_PRINT_RAW) + s = PyObject_Str(op); + else + s = PyObject_Repr(op); + if (s == NULL) + ret = -1; + else if (PyBytes_Check(s)) { + fwrite(PyBytes_AS_STRING(s), 1, + PyBytes_GET_SIZE(s), fp); + } + else if (PyUnicode_Check(s)) { + PyObject *t; + t = _PyUnicode_AsDefaultEncodedString(s, NULL); + if (t == NULL) + ret = 0; + else { + fwrite(PyBytes_AS_STRING(t), 1, + PyBytes_GET_SIZE(t), fp); + } + } + else { + PyErr_Format(PyExc_TypeError, + "str() or repr() returned '%.100s'", + s->ob_type->tp_name); + ret = -1; + } + Py_XDECREF(s); + } + } + if (ret == 0) { + if (ferror(fp)) { + PyErr_SetFromErrno(PyExc_IOError); + clearerr(fp); + ret = -1; + } + } + return ret; } int PyObject_Print(PyObject *op, FILE *fp, int flags) { - return internal_print(op, fp, flags, 0); + return internal_print(op, fp, flags, 0); } /* For debugging convenience. Set a breakpoint here and call it from your DLL */ @@ -347,159 +347,159 @@ void _PyObject_Dump(PyObject* op) { - if (op == NULL) - fprintf(stderr, "NULL\n"); - else { + if (op == NULL) + fprintf(stderr, "NULL\n"); + else { #ifdef WITH_THREAD - PyGILState_STATE gil; + PyGILState_STATE gil; #endif - fprintf(stderr, "object : "); + fprintf(stderr, "object : "); #ifdef WITH_THREAD - gil = PyGILState_Ensure(); + gil = PyGILState_Ensure(); #endif - (void)PyObject_Print(op, stderr, 0); + (void)PyObject_Print(op, stderr, 0); #ifdef WITH_THREAD - PyGILState_Release(gil); + PyGILState_Release(gil); #endif - /* XXX(twouters) cast refcount to long until %zd is - universally available */ - fprintf(stderr, "\n" - "type : %s\n" - "refcount: %ld\n" - "address : %p\n", - Py_TYPE(op)==NULL ? "NULL" : Py_TYPE(op)->tp_name, - (long)op->ob_refcnt, - op); - } + /* XXX(twouters) cast refcount to long until %zd is + universally available */ + fprintf(stderr, "\n" + "type : %s\n" + "refcount: %ld\n" + "address : %p\n", + Py_TYPE(op)==NULL ? "NULL" : Py_TYPE(op)->tp_name, + (long)op->ob_refcnt, + op); + } } PyObject * PyObject_Repr(PyObject *v) { - PyObject *res; - if (PyErr_CheckSignals()) - return NULL; + PyObject *res; + if (PyErr_CheckSignals()) + return NULL; #ifdef USE_STACKCHECK - if (PyOS_CheckStack()) { - PyErr_SetString(PyExc_MemoryError, "stack overflow"); - return NULL; - } + if (PyOS_CheckStack()) { + PyErr_SetString(PyExc_MemoryError, "stack overflow"); + return NULL; + } #endif - if (v == NULL) - return PyUnicode_FromString(""); - if (Py_TYPE(v)->tp_repr == NULL) - return PyUnicode_FromFormat("<%s object at %p>", - v->ob_type->tp_name, v); - res = (*v->ob_type->tp_repr)(v); - if (res != NULL && !PyUnicode_Check(res)) { - PyErr_Format(PyExc_TypeError, - "__repr__ returned non-string (type %.200s)", - res->ob_type->tp_name); - Py_DECREF(res); - return NULL; - } - return res; + if (v == NULL) + return PyUnicode_FromString(""); + if (Py_TYPE(v)->tp_repr == NULL) + return PyUnicode_FromFormat("<%s object at %p>", + v->ob_type->tp_name, v); + res = (*v->ob_type->tp_repr)(v); + if (res != NULL && !PyUnicode_Check(res)) { + PyErr_Format(PyExc_TypeError, + "__repr__ returned non-string (type %.200s)", + res->ob_type->tp_name); + Py_DECREF(res); + return NULL; + } + return res; } PyObject * PyObject_Str(PyObject *v) { - PyObject *res; - if (PyErr_CheckSignals()) - return NULL; + PyObject *res; + if (PyErr_CheckSignals()) + return NULL; #ifdef USE_STACKCHECK - if (PyOS_CheckStack()) { - PyErr_SetString(PyExc_MemoryError, "stack overflow"); - return NULL; - } + if (PyOS_CheckStack()) { + PyErr_SetString(PyExc_MemoryError, "stack overflow"); + return NULL; + } #endif - if (v == NULL) - return PyUnicode_FromString(""); - if (PyUnicode_CheckExact(v)) { - Py_INCREF(v); - return v; - } - if (Py_TYPE(v)->tp_str == NULL) - return PyObject_Repr(v); - - /* It is possible for a type to have a tp_str representation that loops - infinitely. */ - if (Py_EnterRecursiveCall(" while getting the str of an object")) - return NULL; - res = (*Py_TYPE(v)->tp_str)(v); - Py_LeaveRecursiveCall(); - if (res == NULL) - return NULL; - if (!PyUnicode_Check(res)) { - PyErr_Format(PyExc_TypeError, - "__str__ returned non-string (type %.200s)", - Py_TYPE(res)->tp_name); - Py_DECREF(res); - return NULL; - } - return res; + if (v == NULL) + return PyUnicode_FromString(""); + if (PyUnicode_CheckExact(v)) { + Py_INCREF(v); + return v; + } + if (Py_TYPE(v)->tp_str == NULL) + return PyObject_Repr(v); + + /* It is possible for a type to have a tp_str representation that loops + infinitely. */ + if (Py_EnterRecursiveCall(" while getting the str of an object")) + return NULL; + res = (*Py_TYPE(v)->tp_str)(v); + Py_LeaveRecursiveCall(); + if (res == NULL) + return NULL; + if (!PyUnicode_Check(res)) { + PyErr_Format(PyExc_TypeError, + "__str__ returned non-string (type %.200s)", + Py_TYPE(res)->tp_name); + Py_DECREF(res); + return NULL; + } + return res; } PyObject * PyObject_ASCII(PyObject *v) { - PyObject *repr, *ascii, *res; - - repr = PyObject_Repr(v); - if (repr == NULL) - return NULL; - - /* repr is guaranteed to be a PyUnicode object by PyObject_Repr */ - ascii = PyUnicode_EncodeASCII( - PyUnicode_AS_UNICODE(repr), - PyUnicode_GET_SIZE(repr), - "backslashreplace"); - - Py_DECREF(repr); - if (ascii == NULL) - return NULL; - - res = PyUnicode_DecodeASCII( - PyBytes_AS_STRING(ascii), - PyBytes_GET_SIZE(ascii), - NULL); + PyObject *repr, *ascii, *res; - Py_DECREF(ascii); - return res; + repr = PyObject_Repr(v); + if (repr == NULL) + return NULL; + + /* repr is guaranteed to be a PyUnicode object by PyObject_Repr */ + ascii = PyUnicode_EncodeASCII( + PyUnicode_AS_UNICODE(repr), + PyUnicode_GET_SIZE(repr), + "backslashreplace"); + + Py_DECREF(repr); + if (ascii == NULL) + return NULL; + + res = PyUnicode_DecodeASCII( + PyBytes_AS_STRING(ascii), + PyBytes_GET_SIZE(ascii), + NULL); + + Py_DECREF(ascii); + return res; } PyObject * PyObject_Bytes(PyObject *v) { - PyObject *result, *func; - static PyObject *bytesstring = NULL; + PyObject *result, *func; + static PyObject *bytesstring = NULL; - if (v == NULL) - return PyBytes_FromString(""); + if (v == NULL) + return PyBytes_FromString(""); - if (PyBytes_CheckExact(v)) { - Py_INCREF(v); - return v; - } - - func = _PyObject_LookupSpecial(v, "__bytes__", &bytesstring); - if (func != NULL) { - result = PyObject_CallFunctionObjArgs(func, NULL); - 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; - } - return result; - } - else if (PyErr_Occurred()) - return NULL; - return PyBytes_FromObject(v); + if (PyBytes_CheckExact(v)) { + Py_INCREF(v); + return v; + } + + func = _PyObject_LookupSpecial(v, "__bytes__", &bytesstring); + if (func != NULL) { + result = PyObject_CallFunctionObjArgs(func, NULL); + 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; + } + return result; + } + else if (PyErr_Occurred()) + return NULL; + return PyBytes_FromObject(v); } /* For Python 3.0.1 and later, the old three-way comparison has been @@ -542,51 +542,51 @@ static PyObject * do_richcompare(PyObject *v, PyObject *w, int op) { - richcmpfunc f; - PyObject *res; - int checked_reverse_op = 0; - - if (v->ob_type != w->ob_type && - PyType_IsSubtype(w->ob_type, v->ob_type) && - (f = w->ob_type->tp_richcompare) != NULL) { - checked_reverse_op = 1; - res = (*f)(w, v, _Py_SwappedOp[op]); - if (res != Py_NotImplemented) - return res; - Py_DECREF(res); - } - if ((f = v->ob_type->tp_richcompare) != NULL) { - res = (*f)(v, w, op); - if (res != Py_NotImplemented) - return res; - Py_DECREF(res); - } - if (!checked_reverse_op && (f = w->ob_type->tp_richcompare) != NULL) { - res = (*f)(w, v, _Py_SwappedOp[op]); - if (res != Py_NotImplemented) - return res; - Py_DECREF(res); - } - /* If neither object implements it, provide a sensible default - for == and !=, but raise an exception for ordering. */ - switch (op) { - case Py_EQ: - res = (v == w) ? Py_True : Py_False; - break; - case Py_NE: - res = (v != w) ? Py_True : Py_False; - break; - default: - /* XXX Special-case None so it doesn't show as NoneType() */ - PyErr_Format(PyExc_TypeError, - "unorderable types: %.100s() %s %.100s()", - v->ob_type->tp_name, - opstrings[op], - w->ob_type->tp_name); - return NULL; - } - Py_INCREF(res); - return res; + richcmpfunc f; + PyObject *res; + int checked_reverse_op = 0; + + if (v->ob_type != w->ob_type && + PyType_IsSubtype(w->ob_type, v->ob_type) && + (f = w->ob_type->tp_richcompare) != NULL) { + checked_reverse_op = 1; + res = (*f)(w, v, _Py_SwappedOp[op]); + if (res != Py_NotImplemented) + return res; + Py_DECREF(res); + } + if ((f = v->ob_type->tp_richcompare) != NULL) { + res = (*f)(v, w, op); + if (res != Py_NotImplemented) + return res; + Py_DECREF(res); + } + if (!checked_reverse_op && (f = w->ob_type->tp_richcompare) != NULL) { + res = (*f)(w, v, _Py_SwappedOp[op]); + if (res != Py_NotImplemented) + return res; + Py_DECREF(res); + } + /* If neither object implements it, provide a sensible default + for == and !=, but raise an exception for ordering. */ + switch (op) { + case Py_EQ: + res = (v == w) ? Py_True : Py_False; + break; + case Py_NE: + res = (v != w) ? Py_True : Py_False; + break; + default: + /* XXX Special-case None so it doesn't show as NoneType() */ + PyErr_Format(PyExc_TypeError, + "unorderable types: %.100s() %s %.100s()", + v->ob_type->tp_name, + opstrings[op], + w->ob_type->tp_name); + return NULL; + } + Py_INCREF(res); + return res; } /* Perform a rich comparison with object result. This wraps do_richcompare() @@ -595,19 +595,19 @@ PyObject * PyObject_RichCompare(PyObject *v, PyObject *w, int op) { - PyObject *res; + PyObject *res; - assert(Py_LT <= op && op <= Py_GE); - if (v == NULL || w == NULL) { - if (!PyErr_Occurred()) - PyErr_BadInternalCall(); - return NULL; - } - if (Py_EnterRecursiveCall(" in comparison")) - return NULL; - res = do_richcompare(v, w, op); - Py_LeaveRecursiveCall(); - return res; + assert(Py_LT <= op && op <= Py_GE); + if (v == NULL || w == NULL) { + if (!PyErr_Occurred()) + PyErr_BadInternalCall(); + return NULL; + } + if (Py_EnterRecursiveCall(" in comparison")) + return NULL; + res = do_richcompare(v, w, op); + Py_LeaveRecursiveCall(); + return res; } /* Perform a rich comparison with integer result. This wraps @@ -615,31 +615,31 @@ int PyObject_RichCompareBool(PyObject *v, PyObject *w, int op) { - PyObject *res; - int ok; + PyObject *res; + int ok; - /* Quick result when objects are the same. - Guarantees that identity implies equality. */ - if (v == w) { - if (op == Py_EQ) - return 1; - else if (op == Py_NE) - return 0; - } - - res = PyObject_RichCompare(v, w, op); - if (res == NULL) - return -1; - if (PyBool_Check(res)) - ok = (res == Py_True); - else - ok = PyObject_IsTrue(res); - Py_DECREF(res); - return ok; + /* Quick result when objects are the same. + Guarantees that identity implies equality. */ + if (v == w) { + if (op == Py_EQ) + return 1; + else if (op == Py_NE) + return 0; + } + + res = PyObject_RichCompare(v, w, op); + if (res == NULL) + return -1; + if (PyBool_Check(res)) + ok = (res == Py_True); + else + ok = PyObject_IsTrue(res); + Py_DECREF(res); + return ok; } /* Set of hash utility functions to help maintaining the invariant that - if a==b then hash(a)==hash(b) + if a==b then hash(a)==hash(b) All the utility functions (_Py_Hash*()) return "-1" to signify an error. */ @@ -647,230 +647,230 @@ long _Py_HashDouble(double v) { - double intpart, fractpart; - int expo; - long hipart; - long x; /* the final hash value */ - /* This is designed so that Python numbers of different types - * that compare equal hash to the same value; otherwise comparisons - * of mapping keys will turn out weird. - */ - - if (!Py_IS_FINITE(v)) { - if (Py_IS_INFINITY(v)) - return v < 0 ? -271828 : 314159; - else - return 0; - } - fractpart = modf(v, &intpart); - if (fractpart == 0.0) { - /* This must return the same hash as an equal int or long. */ - if (intpart > LONG_MAX/2 || -intpart > LONG_MAX/2) { - /* Convert to long and use its hash. */ - PyObject *plong; /* converted to Python long */ - plong = PyLong_FromDouble(v); - if (plong == NULL) - return -1; - x = PyObject_Hash(plong); - Py_DECREF(plong); - return x; - } - /* Fits in a C long == a Python int, so is its own hash. */ - x = (long)intpart; - if (x == -1) - x = -2; - return x; - } - /* The fractional part is non-zero, so we don't have to worry about - * making this match the hash of some other type. - * Use frexp to get at the bits in the double. - * Since the VAX D double format has 56 mantissa bits, which is the - * most of any double format in use, each of these parts may have as - * many as (but no more than) 56 significant bits. - * So, assuming sizeof(long) >= 4, each part can be broken into two - * longs; frexp and multiplication are used to do that. - * Also, since the Cray double format has 15 exponent bits, which is - * the most of any double format in use, shifting the exponent field - * left by 15 won't overflow a long (again assuming sizeof(long) >= 4). - */ - v = frexp(v, &expo); - v *= 2147483648.0; /* 2**31 */ - hipart = (long)v; /* take the top 32 bits */ - v = (v - (double)hipart) * 2147483648.0; /* get the next 32 bits */ - x = hipart + (long)v + (expo << 15); - if (x == -1) - x = -2; - return x; + double intpart, fractpart; + int expo; + long hipart; + long x; /* the final hash value */ + /* This is designed so that Python numbers of different types + * that compare equal hash to the same value; otherwise comparisons + * of mapping keys will turn out weird. + */ + + if (!Py_IS_FINITE(v)) { + if (Py_IS_INFINITY(v)) + return v < 0 ? -271828 : 314159; + else + return 0; + } + fractpart = modf(v, &intpart); + if (fractpart == 0.0) { + /* This must return the same hash as an equal int or long. */ + if (intpart > LONG_MAX/2 || -intpart > LONG_MAX/2) { + /* Convert to long and use its hash. */ + PyObject *plong; /* converted to Python long */ + plong = PyLong_FromDouble(v); + if (plong == NULL) + return -1; + x = PyObject_Hash(plong); + Py_DECREF(plong); + return x; + } + /* Fits in a C long == a Python int, so is its own hash. */ + x = (long)intpart; + if (x == -1) + x = -2; + return x; + } + /* The fractional part is non-zero, so we don't have to worry about + * making this match the hash of some other type. + * Use frexp to get at the bits in the double. + * Since the VAX D double format has 56 mantissa bits, which is the + * most of any double format in use, each of these parts may have as + * many as (but no more than) 56 significant bits. + * So, assuming sizeof(long) >= 4, each part can be broken into two + * longs; frexp and multiplication are used to do that. + * Also, since the Cray double format has 15 exponent bits, which is + * the most of any double format in use, shifting the exponent field + * left by 15 won't overflow a long (again assuming sizeof(long) >= 4). + */ + v = frexp(v, &expo); + v *= 2147483648.0; /* 2**31 */ + hipart = (long)v; /* take the top 32 bits */ + v = (v - (double)hipart) * 2147483648.0; /* get the next 32 bits */ + x = hipart + (long)v + (expo << 15); + if (x == -1) + x = -2; + return x; } long _Py_HashPointer(void *p) { - long x; - size_t y = (size_t)p; - /* bottom 3 or 4 bits are likely to be 0; rotate y by 4 to avoid - excessive hash collisions for dicts and sets */ - y = (y >> 4) | (y << (8 * SIZEOF_VOID_P - 4)); - x = (long)y; - if (x == -1) - x = -2; - return x; + long x; + size_t y = (size_t)p; + /* bottom 3 or 4 bits are likely to be 0; rotate y by 4 to avoid + excessive hash collisions for dicts and sets */ + y = (y >> 4) | (y << (8 * SIZEOF_VOID_P - 4)); + x = (long)y; + if (x == -1) + x = -2; + return x; } long PyObject_HashNotImplemented(PyObject *v) { - PyErr_Format(PyExc_TypeError, "unhashable type: '%.200s'", - Py_TYPE(v)->tp_name); - return -1; + PyErr_Format(PyExc_TypeError, "unhashable type: '%.200s'", + Py_TYPE(v)->tp_name); + return -1; } long PyObject_Hash(PyObject *v) { - PyTypeObject *tp = Py_TYPE(v); - if (tp->tp_hash != NULL) - return (*tp->tp_hash)(v); - /* To keep to the general practice that inheriting - * solely from object in C code should work without - * an explicit call to PyType_Ready, we implicitly call - * PyType_Ready here and then check the tp_hash slot again - */ - if (tp->tp_dict == NULL) { - if (PyType_Ready(tp) < 0) - return -1; - if (tp->tp_hash != NULL) - return (*tp->tp_hash)(v); - } - /* Otherwise, the object can't be hashed */ - return PyObject_HashNotImplemented(v); + PyTypeObject *tp = Py_TYPE(v); + if (tp->tp_hash != NULL) + return (*tp->tp_hash)(v); + /* To keep to the general practice that inheriting + * solely from object in C code should work without + * an explicit call to PyType_Ready, we implicitly call + * PyType_Ready here and then check the tp_hash slot again + */ + if (tp->tp_dict == NULL) { + if (PyType_Ready(tp) < 0) + return -1; + if (tp->tp_hash != NULL) + return (*tp->tp_hash)(v); + } + /* Otherwise, the object can't be hashed */ + return PyObject_HashNotImplemented(v); } PyObject * PyObject_GetAttrString(PyObject *v, const char *name) { - PyObject *w, *res; + PyObject *w, *res; - if (Py_TYPE(v)->tp_getattr != NULL) - return (*Py_TYPE(v)->tp_getattr)(v, (char*)name); - w = PyUnicode_InternFromString(name); - if (w == NULL) - return NULL; - res = PyObject_GetAttr(v, w); - Py_XDECREF(w); - return res; + if (Py_TYPE(v)->tp_getattr != NULL) + return (*Py_TYPE(v)->tp_getattr)(v, (char*)name); + w = PyUnicode_InternFromString(name); + if (w == NULL) + return NULL; + res = PyObject_GetAttr(v, w); + Py_XDECREF(w); + return res; } int PyObject_HasAttrString(PyObject *v, const char *name) { - PyObject *res = PyObject_GetAttrString(v, name); - if (res != NULL) { - Py_DECREF(res); - return 1; - } - PyErr_Clear(); - return 0; + PyObject *res = PyObject_GetAttrString(v, name); + if (res != NULL) { + Py_DECREF(res); + return 1; + } + PyErr_Clear(); + return 0; } int PyObject_SetAttrString(PyObject *v, const char *name, PyObject *w) { - PyObject *s; - int res; + PyObject *s; + int res; - if (Py_TYPE(v)->tp_setattr != NULL) - return (*Py_TYPE(v)->tp_setattr)(v, (char*)name, w); - s = PyUnicode_InternFromString(name); - if (s == NULL) - return -1; - res = PyObject_SetAttr(v, s, w); - Py_XDECREF(s); - return res; + if (Py_TYPE(v)->tp_setattr != NULL) + return (*Py_TYPE(v)->tp_setattr)(v, (char*)name, w); + s = PyUnicode_InternFromString(name); + if (s == NULL) + return -1; + res = PyObject_SetAttr(v, s, w); + Py_XDECREF(s); + return res; } PyObject * PyObject_GetAttr(PyObject *v, PyObject *name) { - PyTypeObject *tp = Py_TYPE(v); + PyTypeObject *tp = Py_TYPE(v); - if (!PyUnicode_Check(name)) { - PyErr_Format(PyExc_TypeError, - "attribute name must be string, not '%.200s'", - name->ob_type->tp_name); - return NULL; - } - if (tp->tp_getattro != NULL) - return (*tp->tp_getattro)(v, name); - if (tp->tp_getattr != NULL) { - char *name_str = _PyUnicode_AsString(name); - if (name_str == NULL) - return NULL; - return (*tp->tp_getattr)(v, name_str); - } - PyErr_Format(PyExc_AttributeError, - "'%.50s' object has no attribute '%U'", - tp->tp_name, name); - return NULL; + if (!PyUnicode_Check(name)) { + PyErr_Format(PyExc_TypeError, + "attribute name must be string, not '%.200s'", + name->ob_type->tp_name); + return NULL; + } + if (tp->tp_getattro != NULL) + return (*tp->tp_getattro)(v, name); + if (tp->tp_getattr != NULL) { + char *name_str = _PyUnicode_AsString(name); + if (name_str == NULL) + return NULL; + return (*tp->tp_getattr)(v, name_str); + } + PyErr_Format(PyExc_AttributeError, + "'%.50s' object has no attribute '%U'", + tp->tp_name, name); + return NULL; } int PyObject_HasAttr(PyObject *v, PyObject *name) { - PyObject *res = PyObject_GetAttr(v, name); - if (res != NULL) { - Py_DECREF(res); - return 1; - } - PyErr_Clear(); - return 0; + PyObject *res = PyObject_GetAttr(v, name); + if (res != NULL) { + Py_DECREF(res); + return 1; + } + PyErr_Clear(); + return 0; } int PyObject_SetAttr(PyObject *v, PyObject *name, PyObject *value) { - PyTypeObject *tp = Py_TYPE(v); - int err; + PyTypeObject *tp = Py_TYPE(v); + int err; - if (!PyUnicode_Check(name)) { - PyErr_Format(PyExc_TypeError, - "attribute name must be string, not '%.200s'", - name->ob_type->tp_name); - return -1; - } - Py_INCREF(name); - - PyUnicode_InternInPlace(&name); - if (tp->tp_setattro != NULL) { - err = (*tp->tp_setattro)(v, name, value); - Py_DECREF(name); - return err; - } - if (tp->tp_setattr != NULL) { - char *name_str = _PyUnicode_AsString(name); - if (name_str == NULL) - return -1; - err = (*tp->tp_setattr)(v, name_str, value); - Py_DECREF(name); - return err; - } - Py_DECREF(name); - assert(name->ob_refcnt >= 1); - if (tp->tp_getattr == NULL && tp->tp_getattro == NULL) - PyErr_Format(PyExc_TypeError, - "'%.100s' object has no attributes " - "(%s .%U)", - tp->tp_name, - value==NULL ? "del" : "assign to", - name); - else - PyErr_Format(PyExc_TypeError, - "'%.100s' object has only read-only attributes " - "(%s .%U)", - tp->tp_name, - value==NULL ? "del" : "assign to", - name); - return -1; + if (!PyUnicode_Check(name)) { + PyErr_Format(PyExc_TypeError, + "attribute name must be string, not '%.200s'", + name->ob_type->tp_name); + return -1; + } + Py_INCREF(name); + + PyUnicode_InternInPlace(&name); + if (tp->tp_setattro != NULL) { + err = (*tp->tp_setattro)(v, name, value); + Py_DECREF(name); + return err; + } + if (tp->tp_setattr != NULL) { + char *name_str = _PyUnicode_AsString(name); + if (name_str == NULL) + return -1; + err = (*tp->tp_setattr)(v, name_str, value); + Py_DECREF(name); + return err; + } + Py_DECREF(name); + assert(name->ob_refcnt >= 1); + if (tp->tp_getattr == NULL && tp->tp_getattro == NULL) + PyErr_Format(PyExc_TypeError, + "'%.100s' object has no attributes " + "(%s .%U)", + tp->tp_name, + value==NULL ? "del" : "assign to", + name); + else + PyErr_Format(PyExc_TypeError, + "'%.100s' object has only read-only attributes " + "(%s .%U)", + tp->tp_name, + value==NULL ? "del" : "assign to", + name); + return -1; } /* Helper to get a pointer to an object's __dict__ slot, if any */ @@ -878,33 +878,33 @@ PyObject ** _PyObject_GetDictPtr(PyObject *obj) { - Py_ssize_t dictoffset; - PyTypeObject *tp = Py_TYPE(obj); + Py_ssize_t dictoffset; + PyTypeObject *tp = Py_TYPE(obj); - dictoffset = tp->tp_dictoffset; - if (dictoffset == 0) - return NULL; - if (dictoffset < 0) { - Py_ssize_t tsize; - size_t size; - - tsize = ((PyVarObject *)obj)->ob_size; - if (tsize < 0) - tsize = -tsize; - size = _PyObject_VAR_SIZE(tp, tsize); - - dictoffset += (long)size; - assert(dictoffset > 0); - assert(dictoffset % SIZEOF_VOID_P == 0); - } - return (PyObject **) ((char *)obj + dictoffset); + dictoffset = tp->tp_dictoffset; + if (dictoffset == 0) + return NULL; + if (dictoffset < 0) { + Py_ssize_t tsize; + size_t size; + + tsize = ((PyVarObject *)obj)->ob_size; + if (tsize < 0) + tsize = -tsize; + size = _PyObject_VAR_SIZE(tp, tsize); + + dictoffset += (long)size; + assert(dictoffset > 0); + assert(dictoffset % SIZEOF_VOID_P == 0); + } + return (PyObject **) ((char *)obj + dictoffset); } PyObject * PyObject_SelfIter(PyObject *obj) { - Py_INCREF(obj); - return obj; + Py_INCREF(obj); + return obj; } /* Helper used when the __next__ method is removed from a type: @@ -915,10 +915,10 @@ PyObject * _PyObject_NextNotImplemented(PyObject *self) { - PyErr_Format(PyExc_TypeError, - "'%.200s' object is not iterable", - Py_TYPE(self)->tp_name); - return NULL; + PyErr_Format(PyExc_TypeError, + "'%.200s' object is not iterable", + Py_TYPE(self)->tp_name); + return NULL; } /* Generic GetAttr functions - put these in your tp_[gs]etattro slot */ @@ -926,189 +926,189 @@ PyObject * PyObject_GenericGetAttr(PyObject *obj, PyObject *name) { - PyTypeObject *tp = Py_TYPE(obj); - PyObject *descr = NULL; - PyObject *res = NULL; - descrgetfunc f; - Py_ssize_t dictoffset; - PyObject **dictptr; - - if (!PyUnicode_Check(name)){ - PyErr_Format(PyExc_TypeError, - "attribute name must be string, not '%.200s'", - name->ob_type->tp_name); - return NULL; - } - else - Py_INCREF(name); - - if (tp->tp_dict == NULL) { - if (PyType_Ready(tp) < 0) - goto done; - } + PyTypeObject *tp = Py_TYPE(obj); + PyObject *descr = NULL; + PyObject *res = NULL; + descrgetfunc f; + Py_ssize_t dictoffset; + PyObject **dictptr; + + if (!PyUnicode_Check(name)){ + PyErr_Format(PyExc_TypeError, + "attribute name must be string, not '%.200s'", + name->ob_type->tp_name); + return NULL; + } + else + Py_INCREF(name); + + if (tp->tp_dict == NULL) { + if (PyType_Ready(tp) < 0) + goto done; + } #if 0 /* XXX this is not quite _PyType_Lookup anymore */ - /* Inline _PyType_Lookup */ - { - Py_ssize_t i, n; - PyObject *mro, *base, *dict; - - /* Look in tp_dict of types in MRO */ - mro = tp->tp_mro; - assert(mro != NULL); - assert(PyTuple_Check(mro)); - n = PyTuple_GET_SIZE(mro); - for (i = 0; i < n; i++) { - base = PyTuple_GET_ITEM(mro, i); - assert(PyType_Check(base)); - dict = ((PyTypeObject *)base)->tp_dict; - assert(dict && PyDict_Check(dict)); - descr = PyDict_GetItem(dict, name); - if (descr != NULL) - break; - } - } + /* Inline _PyType_Lookup */ + { + Py_ssize_t i, n; + PyObject *mro, *base, *dict; + + /* Look in tp_dict of types in MRO */ + mro = tp->tp_mro; + assert(mro != NULL); + assert(PyTuple_Check(mro)); + n = PyTuple_GET_SIZE(mro); + for (i = 0; i < n; i++) { + base = PyTuple_GET_ITEM(mro, i); + assert(PyType_Check(base)); + dict = ((PyTypeObject *)base)->tp_dict; + assert(dict && PyDict_Check(dict)); + descr = PyDict_GetItem(dict, name); + if (descr != NULL) + break; + } + } #else - descr = _PyType_Lookup(tp, name); + descr = _PyType_Lookup(tp, name); #endif - Py_XINCREF(descr); + Py_XINCREF(descr); + + f = NULL; + if (descr != NULL) { + f = descr->ob_type->tp_descr_get; + if (f != NULL && PyDescr_IsData(descr)) { + res = f(descr, obj, (PyObject *)obj->ob_type); + Py_DECREF(descr); + goto done; + } + } - f = NULL; - if (descr != NULL) { - f = descr->ob_type->tp_descr_get; - if (f != NULL && PyDescr_IsData(descr)) { - res = f(descr, obj, (PyObject *)obj->ob_type); - Py_DECREF(descr); - goto done; - } - } - - /* Inline _PyObject_GetDictPtr */ - dictoffset = tp->tp_dictoffset; - if (dictoffset != 0) { - PyObject *dict; - if (dictoffset < 0) { - Py_ssize_t tsize; - size_t size; - - tsize = ((PyVarObject *)obj)->ob_size; - if (tsize < 0) - tsize = -tsize; - size = _PyObject_VAR_SIZE(tp, tsize); - - dictoffset += (long)size; - assert(dictoffset > 0); - assert(dictoffset % SIZEOF_VOID_P == 0); - } - dictptr = (PyObject **) ((char *)obj + dictoffset); - dict = *dictptr; - if (dict != NULL) { - Py_INCREF(dict); - res = PyDict_GetItem(dict, name); - if (res != NULL) { - Py_INCREF(res); - Py_XDECREF(descr); - Py_DECREF(dict); - goto done; - } - Py_DECREF(dict); - } - } - - if (f != NULL) { - res = f(descr, obj, (PyObject *)Py_TYPE(obj)); - Py_DECREF(descr); - goto done; - } - - if (descr != NULL) { - res = descr; - /* descr was already increfed above */ - goto done; - } - - PyErr_Format(PyExc_AttributeError, - "'%.50s' object has no attribute '%U'", - tp->tp_name, name); + /* Inline _PyObject_GetDictPtr */ + dictoffset = tp->tp_dictoffset; + if (dictoffset != 0) { + PyObject *dict; + if (dictoffset < 0) { + Py_ssize_t tsize; + size_t size; + + tsize = ((PyVarObject *)obj)->ob_size; + if (tsize < 0) + tsize = -tsize; + size = _PyObject_VAR_SIZE(tp, tsize); + + dictoffset += (long)size; + assert(dictoffset > 0); + assert(dictoffset % SIZEOF_VOID_P == 0); + } + dictptr = (PyObject **) ((char *)obj + dictoffset); + dict = *dictptr; + if (dict != NULL) { + Py_INCREF(dict); + res = PyDict_GetItem(dict, name); + if (res != NULL) { + Py_INCREF(res); + Py_XDECREF(descr); + Py_DECREF(dict); + goto done; + } + Py_DECREF(dict); + } + } + + if (f != NULL) { + res = f(descr, obj, (PyObject *)Py_TYPE(obj)); + Py_DECREF(descr); + goto done; + } + + if (descr != NULL) { + res = descr; + /* descr was already increfed above */ + goto done; + } + + PyErr_Format(PyExc_AttributeError, + "'%.50s' object has no attribute '%U'", + tp->tp_name, name); done: - Py_DECREF(name); - return res; + Py_DECREF(name); + return res; } int PyObject_GenericSetAttr(PyObject *obj, PyObject *name, PyObject *value) { - PyTypeObject *tp = Py_TYPE(obj); - PyObject *descr; - descrsetfunc f; - PyObject **dictptr; - int res = -1; - - if (!PyUnicode_Check(name)){ - PyErr_Format(PyExc_TypeError, - "attribute name must be string, not '%.200s'", - name->ob_type->tp_name); - return -1; - } - else - Py_INCREF(name); - - if (tp->tp_dict == NULL) { - if (PyType_Ready(tp) < 0) - goto done; - } - - descr = _PyType_Lookup(tp, name); - f = NULL; - if (descr != NULL) { - f = descr->ob_type->tp_descr_set; - if (f != NULL && PyDescr_IsData(descr)) { - res = f(descr, obj, value); - goto done; - } - } - - dictptr = _PyObject_GetDictPtr(obj); - if (dictptr != NULL) { - PyObject *dict = *dictptr; - if (dict == NULL && value != NULL) { - dict = PyDict_New(); - if (dict == NULL) - goto done; - *dictptr = dict; - } - if (dict != NULL) { - Py_INCREF(dict); - if (value == NULL) - res = PyDict_DelItem(dict, name); - else - res = PyDict_SetItem(dict, name, value); - if (res < 0 && PyErr_ExceptionMatches(PyExc_KeyError)) - PyErr_SetObject(PyExc_AttributeError, name); - Py_DECREF(dict); - goto done; - } - } - - if (f != NULL) { - res = f(descr, obj, value); - goto done; - } - - if (descr == NULL) { - PyErr_Format(PyExc_AttributeError, - "'%.100s' object has no attribute '%U'", - tp->tp_name, name); - goto done; - } - - PyErr_Format(PyExc_AttributeError, - "'%.50s' object attribute '%U' is read-only", - tp->tp_name, name); + PyTypeObject *tp = Py_TYPE(obj); + PyObject *descr; + descrsetfunc f; + PyObject **dictptr; + int res = -1; + + if (!PyUnicode_Check(name)){ + PyErr_Format(PyExc_TypeError, + "attribute name must be string, not '%.200s'", + name->ob_type->tp_name); + return -1; + } + else + Py_INCREF(name); + + if (tp->tp_dict == NULL) { + if (PyType_Ready(tp) < 0) + goto done; + } + + descr = _PyType_Lookup(tp, name); + f = NULL; + if (descr != NULL) { + f = descr->ob_type->tp_descr_set; + if (f != NULL && PyDescr_IsData(descr)) { + res = f(descr, obj, value); + goto done; + } + } + + dictptr = _PyObject_GetDictPtr(obj); + if (dictptr != NULL) { + PyObject *dict = *dictptr; + if (dict == NULL && value != NULL) { + dict = PyDict_New(); + if (dict == NULL) + goto done; + *dictptr = dict; + } + if (dict != NULL) { + Py_INCREF(dict); + if (value == NULL) + res = PyDict_DelItem(dict, name); + else + res = PyDict_SetItem(dict, name, value); + if (res < 0 && PyErr_ExceptionMatches(PyExc_KeyError)) + PyErr_SetObject(PyExc_AttributeError, name); + Py_DECREF(dict); + goto done; + } + } + + if (f != NULL) { + res = f(descr, obj, value); + goto done; + } + + if (descr == NULL) { + PyErr_Format(PyExc_AttributeError, + "'%.100s' object has no attribute '%U'", + tp->tp_name, name); + goto done; + } + + PyErr_Format(PyExc_AttributeError, + "'%.50s' object attribute '%U' is read-only", + tp->tp_name, name); done: - Py_DECREF(name); - return res; + Py_DECREF(name); + return res; } /* Test a value used as condition, e.g., in a for or if statement. @@ -1117,26 +1117,26 @@ int PyObject_IsTrue(PyObject *v) { - Py_ssize_t res; - if (v == Py_True) - return 1; - if (v == Py_False) - return 0; - if (v == Py_None) - return 0; - else if (v->ob_type->tp_as_number != NULL && - v->ob_type->tp_as_number->nb_bool != NULL) - res = (*v->ob_type->tp_as_number->nb_bool)(v); - else if (v->ob_type->tp_as_mapping != NULL && - v->ob_type->tp_as_mapping->mp_length != NULL) - res = (*v->ob_type->tp_as_mapping->mp_length)(v); - else if (v->ob_type->tp_as_sequence != NULL && - v->ob_type->tp_as_sequence->sq_length != NULL) - res = (*v->ob_type->tp_as_sequence->sq_length)(v); - else - return 1; - /* if it is negative, it should be either -1 or -2 */ - return (res > 0) ? 1 : Py_SAFE_DOWNCAST(res, Py_ssize_t, int); + Py_ssize_t res; + if (v == Py_True) + return 1; + if (v == Py_False) + return 0; + if (v == Py_None) + return 0; + else if (v->ob_type->tp_as_number != NULL && + v->ob_type->tp_as_number->nb_bool != NULL) + res = (*v->ob_type->tp_as_number->nb_bool)(v); + else if (v->ob_type->tp_as_mapping != NULL && + v->ob_type->tp_as_mapping->mp_length != NULL) + res = (*v->ob_type->tp_as_mapping->mp_length)(v); + else if (v->ob_type->tp_as_sequence != NULL && + v->ob_type->tp_as_sequence->sq_length != NULL) + res = (*v->ob_type->tp_as_sequence->sq_length)(v); + else + return 1; + /* if it is negative, it should be either -1 or -2 */ + return (res > 0) ? 1 : Py_SAFE_DOWNCAST(res, Py_ssize_t, int); } /* equivalent of 'not v' @@ -1145,11 +1145,11 @@ int PyObject_Not(PyObject *v) { - int res; - res = PyObject_IsTrue(v); - if (res < 0) - return res; - return res == 0; + int res; + res = PyObject_IsTrue(v); + if (res < 0) + return res; + return res == 0; } /* Test whether an object can be called */ @@ -1157,9 +1157,9 @@ int PyCallable_Check(PyObject *x) { - if (x == NULL) - return 0; - return x->ob_type->tp_call != NULL; + if (x == NULL) + return 0; + return x->ob_type->tp_call != NULL; } /* ------------------------- PyObject_Dir() helpers ------------------------- */ @@ -1175,78 +1175,78 @@ static int merge_class_dict(PyObject* dict, PyObject* aclass) { - PyObject *classdict; - PyObject *bases; + PyObject *classdict; + PyObject *bases; - assert(PyDict_Check(dict)); - assert(aclass); + assert(PyDict_Check(dict)); + assert(aclass); - /* Merge in the type's dict (if any). */ - classdict = PyObject_GetAttrString(aclass, "__dict__"); - if (classdict == NULL) - PyErr_Clear(); - else { - int status = PyDict_Update(dict, classdict); - Py_DECREF(classdict); - if (status < 0) - return -1; - } - - /* Recursively merge in the base types' (if any) dicts. */ - bases = PyObject_GetAttrString(aclass, "__bases__"); - if (bases == NULL) - PyErr_Clear(); - else { - /* We have no guarantee that bases is a real tuple */ - Py_ssize_t i, n; - n = PySequence_Size(bases); /* This better be right */ - if (n < 0) - PyErr_Clear(); - else { - for (i = 0; i < n; i++) { - int status; - PyObject *base = PySequence_GetItem(bases, i); - if (base == NULL) { - Py_DECREF(bases); - return -1; - } - status = merge_class_dict(dict, base); - Py_DECREF(base); - if (status < 0) { - Py_DECREF(bases); - return -1; - } - } - } - Py_DECREF(bases); - } - return 0; + /* Merge in the type's dict (if any). */ + classdict = PyObject_GetAttrString(aclass, "__dict__"); + if (classdict == NULL) + PyErr_Clear(); + else { + int status = PyDict_Update(dict, classdict); + Py_DECREF(classdict); + if (status < 0) + return -1; + } + + /* Recursively merge in the base types' (if any) dicts. */ + bases = PyObject_GetAttrString(aclass, "__bases__"); + if (bases == NULL) + PyErr_Clear(); + else { + /* We have no guarantee that bases is a real tuple */ + Py_ssize_t i, n; + n = PySequence_Size(bases); /* This better be right */ + if (n < 0) + PyErr_Clear(); + else { + for (i = 0; i < n; i++) { + int status; + PyObject *base = PySequence_GetItem(bases, i); + if (base == NULL) { + Py_DECREF(bases); + return -1; + } + status = merge_class_dict(dict, base); + Py_DECREF(base); + if (status < 0) { + Py_DECREF(bases); + return -1; + } + } + } + Py_DECREF(bases); + } + return 0; } /* Helper for PyObject_Dir without arguments: returns the local scope. */ static PyObject * _dir_locals(void) { - PyObject *names; - PyObject *locals = PyEval_GetLocals(); + PyObject *names; + PyObject *locals = PyEval_GetLocals(); - if (locals == NULL) { - PyErr_SetString(PyExc_SystemError, "frame does not exist"); - return NULL; - } - - names = PyMapping_Keys(locals); - if (!names) - return NULL; - if (!PyList_Check(names)) { - PyErr_Format(PyExc_TypeError, - "dir(): expected keys() of locals to be a list, " - "not '%.200s'", Py_TYPE(names)->tp_name); - Py_DECREF(names); - return NULL; - } - /* the locals don't need to be DECREF'd */ - return names; + if (locals == NULL) { + PyErr_SetString(PyExc_SystemError, "frame does not exist"); + return NULL; + } + + names = PyMapping_Keys(locals); + if (!names) + return NULL; + if (!PyList_Check(names)) { + PyErr_Format(PyExc_TypeError, + "dir(): expected keys() of locals to be a list, " + "not '%.200s'", Py_TYPE(names)->tp_name); + Py_DECREF(names); + return NULL; + } + /* the locals don't need to be DECREF'd */ + return names; } /* Helper for PyObject_Dir of type objects: returns __dict__ and __bases__. @@ -1256,37 +1256,37 @@ static PyObject * _specialized_dir_type(PyObject *obj) { - PyObject *result = NULL; - PyObject *dict = PyDict_New(); + PyObject *result = NULL; + PyObject *dict = PyDict_New(); - if (dict != NULL && merge_class_dict(dict, obj) == 0) - result = PyDict_Keys(dict); + if (dict != NULL && merge_class_dict(dict, obj) == 0) + result = PyDict_Keys(dict); - Py_XDECREF(dict); - return result; + Py_XDECREF(dict); + return result; } /* Helper for PyObject_Dir of module objects: returns the module's __dict__. */ static PyObject * _specialized_dir_module(PyObject *obj) { - PyObject *result = NULL; - PyObject *dict = PyObject_GetAttrString(obj, "__dict__"); + PyObject *result = NULL; + PyObject *dict = PyObject_GetAttrString(obj, "__dict__"); - if (dict != NULL) { - if (PyDict_Check(dict)) - result = PyDict_Keys(dict); - else { - const char *name = PyModule_GetName(obj); - if (name) - PyErr_Format(PyExc_TypeError, - "%.200s.__dict__ is not a dictionary", - name); - } - } + if (dict != NULL) { + if (PyDict_Check(dict)) + result = PyDict_Keys(dict); + else { + const char *name = PyModule_GetName(obj); + if (name) + PyErr_Format(PyExc_TypeError, + "%.200s.__dict__ is not a dictionary", + name); + } + } - Py_XDECREF(dict); - return result; + Py_XDECREF(dict); + return result; } /* Helper for PyObject_Dir of generic objects: returns __dict__, __class__, @@ -1295,47 +1295,47 @@ static PyObject * _generic_dir(PyObject *obj) { - PyObject *result = NULL; - PyObject *dict = NULL; - PyObject *itsclass = NULL; - - /* Get __dict__ (which may or may not be a real dict...) */ - dict = PyObject_GetAttrString(obj, "__dict__"); - if (dict == NULL) { - PyErr_Clear(); - dict = PyDict_New(); - } - else if (!PyDict_Check(dict)) { - Py_DECREF(dict); - dict = PyDict_New(); - } - else { - /* Copy __dict__ to avoid mutating it. */ - PyObject *temp = PyDict_Copy(dict); - Py_DECREF(dict); - dict = temp; - } - - if (dict == NULL) - goto error; - - /* Merge in attrs reachable from its class. */ - itsclass = PyObject_GetAttrString(obj, "__class__"); - if (itsclass == NULL) - /* XXX(tomer): Perhaps fall back to obj->ob_type if no - __class__ exists? */ - PyErr_Clear(); - else { - if (merge_class_dict(dict, itsclass) != 0) - goto error; - } + PyObject *result = NULL; + PyObject *dict = NULL; + PyObject *itsclass = NULL; + + /* Get __dict__ (which may or may not be a real dict...) */ + dict = PyObject_GetAttrString(obj, "__dict__"); + if (dict == NULL) { + PyErr_Clear(); + dict = PyDict_New(); + } + else if (!PyDict_Check(dict)) { + Py_DECREF(dict); + dict = PyDict_New(); + } + else { + /* Copy __dict__ to avoid mutating it. */ + PyObject *temp = PyDict_Copy(dict); + Py_DECREF(dict); + dict = temp; + } + + if (dict == NULL) + goto error; + + /* Merge in attrs reachable from its class. */ + itsclass = PyObject_GetAttrString(obj, "__class__"); + if (itsclass == NULL) + /* XXX(tomer): Perhaps fall back to obj->ob_type if no + __class__ exists? */ + PyErr_Clear(); + else { + if (merge_class_dict(dict, itsclass) != 0) + goto error; + } - result = PyDict_Keys(dict); - /* fall through */ + result = PyDict_Keys(dict); + /* fall through */ error: - Py_XDECREF(itsclass); - Py_XDECREF(dict); - return result; + Py_XDECREF(itsclass); + Py_XDECREF(dict); + return result; } /* Helper for PyObject_Dir: object introspection. @@ -1344,40 +1344,40 @@ static PyObject * _dir_object(PyObject *obj) { - PyObject * result = NULL; - PyObject * dirfunc = PyObject_GetAttrString((PyObject*)obj->ob_type, - "__dir__"); - - assert(obj); - if (dirfunc == NULL) { - /* use default implementation */ - PyErr_Clear(); - if (PyModule_Check(obj)) - result = _specialized_dir_module(obj); - else if (PyType_Check(obj)) - result = _specialized_dir_type(obj); - else - result = _generic_dir(obj); - } - else { - /* use __dir__ */ - result = PyObject_CallFunctionObjArgs(dirfunc, obj, NULL); - Py_DECREF(dirfunc); - if (result == NULL) - return NULL; - - /* result must be a list */ - /* XXX(gbrandl): could also check if all items are strings */ - if (!PyList_Check(result)) { - PyErr_Format(PyExc_TypeError, - "__dir__() must return a list, not %.200s", - Py_TYPE(result)->tp_name); - Py_DECREF(result); - result = NULL; - } - } + PyObject * result = NULL; + PyObject * dirfunc = PyObject_GetAttrString((PyObject*)obj->ob_type, + "__dir__"); + + assert(obj); + if (dirfunc == NULL) { + /* use default implementation */ + PyErr_Clear(); + if (PyModule_Check(obj)) + result = _specialized_dir_module(obj); + else if (PyType_Check(obj)) + result = _specialized_dir_type(obj); + else + result = _generic_dir(obj); + } + else { + /* use __dir__ */ + result = PyObject_CallFunctionObjArgs(dirfunc, obj, NULL); + Py_DECREF(dirfunc); + if (result == NULL) + return NULL; + + /* result must be a list */ + /* XXX(gbrandl): could also check if all items are strings */ + if (!PyList_Check(result)) { + PyErr_Format(PyExc_TypeError, + "__dir__() must return a list, not %.200s", + Py_TYPE(result)->tp_name); + Py_DECREF(result); + result = NULL; + } + } - return result; + return result; } /* Implementation of dir() -- if obj is NULL, returns the names in the current @@ -1387,24 +1387,24 @@ PyObject * PyObject_Dir(PyObject *obj) { - PyObject * result; + PyObject * result; - if (obj == NULL) - /* no object -- introspect the locals */ - result = _dir_locals(); - else - /* object -- introspect the object */ - result = _dir_object(obj); - - assert(result == NULL || PyList_Check(result)); - - if (result != NULL && PyList_Sort(result) != 0) { - /* sorting the list failed */ - Py_DECREF(result); - result = NULL; - } + if (obj == NULL) + /* no object -- introspect the locals */ + result = _dir_locals(); + else + /* object -- introspect the object */ + result = _dir_object(obj); + + assert(result == NULL || PyList_Check(result)); + + if (result != NULL && PyList_Sort(result) != 0) { + /* sorting the list failed */ + Py_DECREF(result); + result = NULL; + } - return result; + return result; } /* @@ -1418,35 +1418,35 @@ static PyObject * none_repr(PyObject *op) { - return PyUnicode_FromString("None"); + return PyUnicode_FromString("None"); } /* ARGUSED */ static void none_dealloc(PyObject* ignore) { - /* This should never get called, but we also don't want to SEGV if - * we accidentally decref None out of existence. - */ - Py_FatalError("deallocating None"); + /* This should never get called, but we also don't want to SEGV if + * we accidentally decref None out of existence. + */ + Py_FatalError("deallocating None"); } static PyTypeObject PyNone_Type = { - PyVarObject_HEAD_INIT(&PyType_Type, 0) - "NoneType", - 0, - 0, - none_dealloc, /*tp_dealloc*/ /*never called*/ - 0, /*tp_print*/ - 0, /*tp_getattr*/ - 0, /*tp_setattr*/ - 0, /*tp_reserved*/ - none_repr, /*tp_repr*/ - 0, /*tp_as_number*/ - 0, /*tp_as_sequence*/ - 0, /*tp_as_mapping*/ - 0, /*tp_hash */ + PyVarObject_HEAD_INIT(&PyType_Type, 0) + "NoneType", + 0, + 0, + none_dealloc, /*tp_dealloc*/ /*never called*/ + 0, /*tp_print*/ + 0, /*tp_getattr*/ + 0, /*tp_setattr*/ + 0, /*tp_reserved*/ + none_repr, /*tp_repr*/ + 0, /*tp_as_number*/ + 0, /*tp_as_sequence*/ + 0, /*tp_as_mapping*/ + 0, /*tp_hash */ }; PyObject _Py_NoneStruct = { @@ -1460,165 +1460,165 @@ static PyObject * NotImplemented_repr(PyObject *op) { - return PyUnicode_FromString("NotImplemented"); + return PyUnicode_FromString("NotImplemented"); } static PyTypeObject PyNotImplemented_Type = { - PyVarObject_HEAD_INIT(&PyType_Type, 0) - "NotImplementedType", - 0, - 0, - none_dealloc, /*tp_dealloc*/ /*never called*/ - 0, /*tp_print*/ - 0, /*tp_getattr*/ - 0, /*tp_setattr*/ - 0, /*tp_reserved*/ - NotImplemented_repr, /*tp_repr*/ - 0, /*tp_as_number*/ - 0, /*tp_as_sequence*/ - 0, /*tp_as_mapping*/ - 0, /*tp_hash */ + PyVarObject_HEAD_INIT(&PyType_Type, 0) + "NotImplementedType", + 0, + 0, + none_dealloc, /*tp_dealloc*/ /*never called*/ + 0, /*tp_print*/ + 0, /*tp_getattr*/ + 0, /*tp_setattr*/ + 0, /*tp_reserved*/ + NotImplemented_repr, /*tp_repr*/ + 0, /*tp_as_number*/ + 0, /*tp_as_sequence*/ + 0, /*tp_as_mapping*/ + 0, /*tp_hash */ }; PyObject _Py_NotImplementedStruct = { - _PyObject_EXTRA_INIT - 1, &PyNotImplemented_Type + _PyObject_EXTRA_INIT + 1, &PyNotImplemented_Type }; void _Py_ReadyTypes(void) { - if (PyType_Ready(&PyType_Type) < 0) - Py_FatalError("Can't initialize type type"); + if (PyType_Ready(&PyType_Type) < 0) + Py_FatalError("Can't initialize type type"); - if (PyType_Ready(&_PyWeakref_RefType) < 0) - Py_FatalError("Can't initialize weakref type"); + if (PyType_Ready(&_PyWeakref_RefType) < 0) + Py_FatalError("Can't initialize weakref type"); - if (PyType_Ready(&_PyWeakref_CallableProxyType) < 0) - Py_FatalError("Can't initialize callable weakref proxy type"); + if (PyType_Ready(&_PyWeakref_CallableProxyType) < 0) + Py_FatalError("Can't initialize callable weakref proxy type"); - if (PyType_Ready(&_PyWeakref_ProxyType) < 0) - Py_FatalError("Can't initialize weakref proxy type"); + if (PyType_Ready(&_PyWeakref_ProxyType) < 0) + Py_FatalError("Can't initialize weakref proxy type"); - if (PyType_Ready(&PyBool_Type) < 0) - Py_FatalError("Can't initialize bool type"); + if (PyType_Ready(&PyBool_Type) < 0) + Py_FatalError("Can't initialize bool type"); - if (PyType_Ready(&PyByteArray_Type) < 0) - Py_FatalError("Can't initialize bytearray type"); + if (PyType_Ready(&PyByteArray_Type) < 0) + Py_FatalError("Can't initialize bytearray type"); - if (PyType_Ready(&PyBytes_Type) < 0) - Py_FatalError("Can't initialize 'str'"); + if (PyType_Ready(&PyBytes_Type) < 0) + Py_FatalError("Can't initialize 'str'"); - if (PyType_Ready(&PyList_Type) < 0) - Py_FatalError("Can't initialize list type"); + if (PyType_Ready(&PyList_Type) < 0) + Py_FatalError("Can't initialize list type"); - if (PyType_Ready(&PyNone_Type) < 0) - Py_FatalError("Can't initialize None type"); + if (PyType_Ready(&PyNone_Type) < 0) + Py_FatalError("Can't initialize None type"); - if (PyType_Ready(Py_Ellipsis->ob_type) < 0) - Py_FatalError("Can't initialize type(Ellipsis)"); + if (PyType_Ready(Py_Ellipsis->ob_type) < 0) + Py_FatalError("Can't initialize type(Ellipsis)"); - if (PyType_Ready(&PyNotImplemented_Type) < 0) - Py_FatalError("Can't initialize NotImplemented type"); + if (PyType_Ready(&PyNotImplemented_Type) < 0) + Py_FatalError("Can't initialize NotImplemented type"); - if (PyType_Ready(&PyTraceBack_Type) < 0) - Py_FatalError("Can't initialize traceback type"); + if (PyType_Ready(&PyTraceBack_Type) < 0) + Py_FatalError("Can't initialize traceback type"); - if (PyType_Ready(&PySuper_Type) < 0) - Py_FatalError("Can't initialize super type"); + if (PyType_Ready(&PySuper_Type) < 0) + Py_FatalError("Can't initialize super type"); - if (PyType_Ready(&PyBaseObject_Type) < 0) - Py_FatalError("Can't initialize object type"); + if (PyType_Ready(&PyBaseObject_Type) < 0) + Py_FatalError("Can't initialize object type"); - if (PyType_Ready(&PyRange_Type) < 0) - Py_FatalError("Can't initialize range type"); + if (PyType_Ready(&PyRange_Type) < 0) + Py_FatalError("Can't initialize range type"); - if (PyType_Ready(&PyDict_Type) < 0) - Py_FatalError("Can't initialize dict type"); + if (PyType_Ready(&PyDict_Type) < 0) + Py_FatalError("Can't initialize dict type"); - if (PyType_Ready(&PySet_Type) < 0) - Py_FatalError("Can't initialize set type"); + if (PyType_Ready(&PySet_Type) < 0) + Py_FatalError("Can't initialize set type"); - if (PyType_Ready(&PyUnicode_Type) < 0) - Py_FatalError("Can't initialize str type"); + if (PyType_Ready(&PyUnicode_Type) < 0) + Py_FatalError("Can't initialize str type"); - if (PyType_Ready(&PySlice_Type) < 0) - Py_FatalError("Can't initialize slice type"); + if (PyType_Ready(&PySlice_Type) < 0) + Py_FatalError("Can't initialize slice type"); - if (PyType_Ready(&PyStaticMethod_Type) < 0) - Py_FatalError("Can't initialize static method type"); + if (PyType_Ready(&PyStaticMethod_Type) < 0) + Py_FatalError("Can't initialize static method type"); - if (PyType_Ready(&PyComplex_Type) < 0) - Py_FatalError("Can't initialize complex type"); + if (PyType_Ready(&PyComplex_Type) < 0) + Py_FatalError("Can't initialize complex type"); - if (PyType_Ready(&PyFloat_Type) < 0) - Py_FatalError("Can't initialize float type"); + if (PyType_Ready(&PyFloat_Type) < 0) + Py_FatalError("Can't initialize float type"); - if (PyType_Ready(&PyLong_Type) < 0) - Py_FatalError("Can't initialize int type"); + if (PyType_Ready(&PyLong_Type) < 0) + Py_FatalError("Can't initialize int type"); - if (PyType_Ready(&PyFrozenSet_Type) < 0) - Py_FatalError("Can't initialize frozenset type"); + if (PyType_Ready(&PyFrozenSet_Type) < 0) + Py_FatalError("Can't initialize frozenset type"); - if (PyType_Ready(&PyProperty_Type) < 0) - Py_FatalError("Can't initialize property type"); + if (PyType_Ready(&PyProperty_Type) < 0) + Py_FatalError("Can't initialize property type"); - if (PyType_Ready(&PyMemoryView_Type) < 0) - Py_FatalError("Can't initialize memoryview type"); + if (PyType_Ready(&PyMemoryView_Type) < 0) + Py_FatalError("Can't initialize memoryview type"); - if (PyType_Ready(&PyTuple_Type) < 0) - Py_FatalError("Can't initialize tuple type"); + if (PyType_Ready(&PyTuple_Type) < 0) + Py_FatalError("Can't initialize tuple type"); - if (PyType_Ready(&PyEnum_Type) < 0) - Py_FatalError("Can't initialize enumerate type"); + if (PyType_Ready(&PyEnum_Type) < 0) + Py_FatalError("Can't initialize enumerate type"); - if (PyType_Ready(&PyReversed_Type) < 0) - Py_FatalError("Can't initialize reversed type"); + if (PyType_Ready(&PyReversed_Type) < 0) + Py_FatalError("Can't initialize reversed type"); - if (PyType_Ready(&PyStdPrinter_Type) < 0) - Py_FatalError("Can't initialize StdPrinter"); + if (PyType_Ready(&PyStdPrinter_Type) < 0) + Py_FatalError("Can't initialize StdPrinter"); - if (PyType_Ready(&PyCode_Type) < 0) - Py_FatalError("Can't initialize code type"); + if (PyType_Ready(&PyCode_Type) < 0) + Py_FatalError("Can't initialize code type"); - if (PyType_Ready(&PyFrame_Type) < 0) - Py_FatalError("Can't initialize frame type"); + if (PyType_Ready(&PyFrame_Type) < 0) + Py_FatalError("Can't initialize frame type"); - if (PyType_Ready(&PyCFunction_Type) < 0) - Py_FatalError("Can't initialize builtin function type"); + if (PyType_Ready(&PyCFunction_Type) < 0) + Py_FatalError("Can't initialize builtin function type"); - if (PyType_Ready(&PyMethod_Type) < 0) - Py_FatalError("Can't initialize method type"); + if (PyType_Ready(&PyMethod_Type) < 0) + Py_FatalError("Can't initialize method type"); - if (PyType_Ready(&PyFunction_Type) < 0) - Py_FatalError("Can't initialize function type"); + if (PyType_Ready(&PyFunction_Type) < 0) + Py_FatalError("Can't initialize function type"); - if (PyType_Ready(&PyDictProxy_Type) < 0) - Py_FatalError("Can't initialize dict proxy type"); + if (PyType_Ready(&PyDictProxy_Type) < 0) + Py_FatalError("Can't initialize dict proxy type"); - if (PyType_Ready(&PyGen_Type) < 0) - Py_FatalError("Can't initialize generator type"); + if (PyType_Ready(&PyGen_Type) < 0) + Py_FatalError("Can't initialize generator type"); - if (PyType_Ready(&PyGetSetDescr_Type) < 0) - Py_FatalError("Can't initialize get-set descriptor type"); + if (PyType_Ready(&PyGetSetDescr_Type) < 0) + Py_FatalError("Can't initialize get-set descriptor type"); - if (PyType_Ready(&PyWrapperDescr_Type) < 0) - Py_FatalError("Can't initialize wrapper type"); + if (PyType_Ready(&PyWrapperDescr_Type) < 0) + Py_FatalError("Can't initialize wrapper type"); - if (PyType_Ready(&PyEllipsis_Type) < 0) - Py_FatalError("Can't initialize ellipsis type"); + if (PyType_Ready(&PyEllipsis_Type) < 0) + Py_FatalError("Can't initialize ellipsis type"); - if (PyType_Ready(&PyMemberDescr_Type) < 0) - Py_FatalError("Can't initialize member descriptor type"); + if (PyType_Ready(&PyMemberDescr_Type) < 0) + Py_FatalError("Can't initialize member descriptor type"); - if (PyType_Ready(&PyFilter_Type) < 0) - Py_FatalError("Can't initialize filter type"); + if (PyType_Ready(&PyFilter_Type) < 0) + Py_FatalError("Can't initialize filter type"); - if (PyType_Ready(&PyMap_Type) < 0) - Py_FatalError("Can't initialize map type"); + if (PyType_Ready(&PyMap_Type) < 0) + Py_FatalError("Can't initialize map type"); - if (PyType_Ready(&PyZip_Type) < 0) - Py_FatalError("Can't initialize zip type"); + if (PyType_Ready(&PyZip_Type) < 0) + Py_FatalError("Can't initialize zip type"); } @@ -1627,50 +1627,50 @@ void _Py_NewReference(PyObject *op) { - _Py_INC_REFTOTAL; - op->ob_refcnt = 1; - _Py_AddToAllObjects(op, 1); - _Py_INC_TPALLOCS(op); + _Py_INC_REFTOTAL; + op->ob_refcnt = 1; + _Py_AddToAllObjects(op, 1); + _Py_INC_TPALLOCS(op); } void _Py_ForgetReference(register PyObject *op) { #ifdef SLOW_UNREF_CHECK - register PyObject *p; + register PyObject *p; #endif - if (op->ob_refcnt < 0) - Py_FatalError("UNREF negative refcnt"); - if (op == &refchain || - op->_ob_prev->_ob_next != op || op->_ob_next->_ob_prev != op) { - fprintf(stderr, "* ob\n"); - _PyObject_Dump(op); - fprintf(stderr, "* op->_ob_prev->_ob_next\n"); - _PyObject_Dump(op->_ob_prev->_ob_next); - fprintf(stderr, "* op->_ob_next->_ob_prev\n"); - _PyObject_Dump(op->_ob_next->_ob_prev); - Py_FatalError("UNREF invalid object"); - } + if (op->ob_refcnt < 0) + Py_FatalError("UNREF negative refcnt"); + if (op == &refchain || + op->_ob_prev->_ob_next != op || op->_ob_next->_ob_prev != op) { + fprintf(stderr, "* ob\n"); + _PyObject_Dump(op); + fprintf(stderr, "* op->_ob_prev->_ob_next\n"); + _PyObject_Dump(op->_ob_prev->_ob_next); + fprintf(stderr, "* op->_ob_next->_ob_prev\n"); + _PyObject_Dump(op->_ob_next->_ob_prev); + Py_FatalError("UNREF invalid object"); + } #ifdef SLOW_UNREF_CHECK - for (p = refchain._ob_next; p != &refchain; p = p->_ob_next) { - if (p == op) - break; - } - if (p == &refchain) /* Not found */ - Py_FatalError("UNREF unknown object"); + for (p = refchain._ob_next; p != &refchain; p = p->_ob_next) { + if (p == op) + break; + } + if (p == &refchain) /* Not found */ + Py_FatalError("UNREF unknown object"); #endif - op->_ob_next->_ob_prev = op->_ob_prev; - op->_ob_prev->_ob_next = op->_ob_next; - op->_ob_next = op->_ob_prev = NULL; - _Py_INC_TPFREES(op); + op->_ob_next->_ob_prev = op->_ob_prev; + op->_ob_prev->_ob_next = op->_ob_next; + op->_ob_next = op->_ob_prev = NULL; + _Py_INC_TPFREES(op); } void _Py_Dealloc(PyObject *op) { - destructor dealloc = Py_TYPE(op)->tp_dealloc; - _Py_ForgetReference(op); - (*dealloc)(op); + destructor dealloc = Py_TYPE(op)->tp_dealloc; + _Py_ForgetReference(op); + (*dealloc)(op); } /* Print all live objects. Because PyObject_Print is called, the @@ -1679,14 +1679,14 @@ void _Py_PrintReferences(FILE *fp) { - PyObject *op; - fprintf(fp, "Remaining objects:\n"); - for (op = refchain._ob_next; op != &refchain; op = op->_ob_next) { - fprintf(fp, "%p [%" PY_FORMAT_SIZE_T "d] ", op, op->ob_refcnt); - if (PyObject_Print(op, fp, 0) != 0) - PyErr_Clear(); - putc('\n', fp); - } + PyObject *op; + fprintf(fp, "Remaining objects:\n"); + for (op = refchain._ob_next; op != &refchain; op = op->_ob_next) { + fprintf(fp, "%p [%" PY_FORMAT_SIZE_T "d] ", op, op->ob_refcnt); + if (PyObject_Print(op, fp, 0) != 0) + PyErr_Clear(); + putc('\n', fp); + } } /* Print the addresses of all live objects. Unlike _Py_PrintReferences, this @@ -1695,40 +1695,40 @@ void _Py_PrintReferenceAddresses(FILE *fp) { - PyObject *op; - fprintf(fp, "Remaining object addresses:\n"); - for (op = refchain._ob_next; op != &refchain; op = op->_ob_next) - fprintf(fp, "%p [%" PY_FORMAT_SIZE_T "d] %s\n", op, - op->ob_refcnt, Py_TYPE(op)->tp_name); + PyObject *op; + fprintf(fp, "Remaining object addresses:\n"); + for (op = refchain._ob_next; op != &refchain; op = op->_ob_next) + fprintf(fp, "%p [%" PY_FORMAT_SIZE_T "d] %s\n", op, + op->ob_refcnt, Py_TYPE(op)->tp_name); } PyObject * _Py_GetObjects(PyObject *self, PyObject *args) { - int i, n; - PyObject *t = NULL; - PyObject *res, *op; - - if (!PyArg_ParseTuple(args, "i|O", &n, &t)) - return NULL; - op = refchain._ob_next; - res = PyList_New(0); - if (res == NULL) - return NULL; - for (i = 0; (n == 0 || i < n) && op != &refchain; i++) { - while (op == self || op == args || op == res || op == t || - (t != NULL && Py_TYPE(op) != (PyTypeObject *) t)) { - op = op->_ob_next; - if (op == &refchain) - return res; - } - if (PyList_Append(res, op) < 0) { - Py_DECREF(res); - return NULL; - } - op = op->_ob_next; - } - return res; + int i, n; + PyObject *t = NULL; + PyObject *res, *op; + + if (!PyArg_ParseTuple(args, "i|O", &n, &t)) + return NULL; + op = refchain._ob_next; + res = PyList_New(0); + if (res == NULL) + return NULL; + for (i = 0; (n == 0 || i < n) && op != &refchain; i++) { + while (op == self || op == args || op == res || op == t || + (t != NULL && Py_TYPE(op) != (PyTypeObject *) t)) { + op = op->_ob_next; + if (op == &refchain) + return res; + } + if (PyList_Append(res, op) < 0) { + Py_DECREF(res); + return NULL; + } + op = op->_ob_next; + } + return res; } #endif @@ -1747,19 +1747,19 @@ void * PyMem_Malloc(size_t nbytes) { - return PyMem_MALLOC(nbytes); + return PyMem_MALLOC(nbytes); } void * PyMem_Realloc(void *p, size_t nbytes) { - return PyMem_REALLOC(p, nbytes); + return PyMem_REALLOC(p, nbytes); } void PyMem_Free(void *p) { - PyMem_FREE(p); + PyMem_FREE(p); } @@ -1780,52 +1780,52 @@ int Py_ReprEnter(PyObject *obj) { - PyObject *dict; - PyObject *list; - Py_ssize_t i; - - dict = PyThreadState_GetDict(); - if (dict == NULL) - return 0; - list = PyDict_GetItemString(dict, KEY); - if (list == NULL) { - list = PyList_New(0); - if (list == NULL) - return -1; - if (PyDict_SetItemString(dict, KEY, list) < 0) - return -1; - Py_DECREF(list); - } - i = PyList_GET_SIZE(list); - while (--i >= 0) { - if (PyList_GET_ITEM(list, i) == obj) - return 1; - } - PyList_Append(list, obj); - return 0; + PyObject *dict; + PyObject *list; + Py_ssize_t i; + + dict = PyThreadState_GetDict(); + if (dict == NULL) + return 0; + list = PyDict_GetItemString(dict, KEY); + if (list == NULL) { + list = PyList_New(0); + if (list == NULL) + return -1; + if (PyDict_SetItemString(dict, KEY, list) < 0) + return -1; + Py_DECREF(list); + } + i = PyList_GET_SIZE(list); + while (--i >= 0) { + if (PyList_GET_ITEM(list, i) == obj) + return 1; + } + PyList_Append(list, obj); + return 0; } void Py_ReprLeave(PyObject *obj) { - PyObject *dict; - PyObject *list; - Py_ssize_t i; - - dict = PyThreadState_GetDict(); - if (dict == NULL) - return; - list = PyDict_GetItemString(dict, KEY); - if (list == NULL || !PyList_Check(list)) - return; - i = PyList_GET_SIZE(list); - /* Count backwards because we always expect obj to be list[-1] */ - while (--i >= 0) { - if (PyList_GET_ITEM(list, i) == obj) { - PyList_SetSlice(list, i, i + 1, NULL); - break; - } - } + PyObject *dict; + PyObject *list; + Py_ssize_t i; + + dict = PyThreadState_GetDict(); + if (dict == NULL) + return; + list = PyDict_GetItemString(dict, KEY); + if (list == NULL || !PyList_Check(list)) + return; + i = PyList_GET_SIZE(list); + /* Count backwards because we always expect obj to be list[-1] */ + while (--i >= 0) { + if (PyList_GET_ITEM(list, i) == obj) { + PyList_SetSlice(list, i, i + 1, NULL); + break; + } + } } /* Trashcan support. */ @@ -1845,11 +1845,11 @@ void _PyTrash_deposit_object(PyObject *op) { - assert(PyObject_IS_GC(op)); - assert(_Py_AS_GC(op)->gc.gc_refs == _PyGC_REFS_UNTRACKED); - assert(op->ob_refcnt == 0); - _Py_AS_GC(op)->gc.gc_prev = (PyGC_Head *)_PyTrash_delete_later; - _PyTrash_delete_later = op; + assert(PyObject_IS_GC(op)); + assert(_Py_AS_GC(op)->gc.gc_refs == _PyGC_REFS_UNTRACKED); + assert(op->ob_refcnt == 0); + _Py_AS_GC(op)->gc.gc_prev = (PyGC_Head *)_PyTrash_delete_later; + _PyTrash_delete_later = op; } /* Dealloccate all the objects in the _PyTrash_delete_later list. Called when @@ -1858,24 +1858,24 @@ void _PyTrash_destroy_chain(void) { - while (_PyTrash_delete_later) { - PyObject *op = _PyTrash_delete_later; - destructor dealloc = Py_TYPE(op)->tp_dealloc; - - _PyTrash_delete_later = - (PyObject*) _Py_AS_GC(op)->gc.gc_prev; - - /* Call the deallocator directly. This used to try to - * fool Py_DECREF into calling it indirectly, but - * Py_DECREF was already called on this object, and in - * assorted non-release builds calling Py_DECREF again ends - * up distorting allocation statistics. - */ - assert(op->ob_refcnt == 0); - ++_PyTrash_delete_nesting; - (*dealloc)(op); - --_PyTrash_delete_nesting; - } + while (_PyTrash_delete_later) { + PyObject *op = _PyTrash_delete_later; + destructor dealloc = Py_TYPE(op)->tp_dealloc; + + _PyTrash_delete_later = + (PyObject*) _Py_AS_GC(op)->gc.gc_prev; + + /* Call the deallocator directly. This used to try to + * fool Py_DECREF into calling it indirectly, but + * Py_DECREF was already called on this object, and in + * assorted non-release builds calling Py_DECREF again ends + * up distorting allocation statistics. + */ + assert(op->ob_refcnt == 0); + ++_PyTrash_delete_nesting; + (*dealloc)(op); + --_PyTrash_delete_nesting; + } } #ifdef __cplusplus Modified: python/branches/py3k-jit/Objects/obmalloc.c ============================================================================== --- python/branches/py3k-jit/Objects/obmalloc.c (original) +++ python/branches/py3k-jit/Objects/obmalloc.c Mon May 10 23:55:43 2010 @@ -27,7 +27,7 @@ the cyclic garbage collector operates selectively on container objects. - Object-specific allocators + Object-specific allocators _____ ______ ______ ________ [ int ] [ dict ] [ list ] ... [ string ] Python core | +3 | <----- Object-specific memory -----> | <-- Non-object memory --> | @@ -67,7 +67,7 @@ * in Proc. 1995 Int'l. Workshop on Memory Management, September 1995. */ -/* #undef WITH_MEMORY_LIMITS */ /* disable mem limit checks */ +/* #undef WITH_MEMORY_LIMITS */ /* disable mem limit checks */ /*==========================================================================*/ @@ -95,22 +95,22 @@ * * For small requests we have the following table: * - * Request in bytes Size of allocated block Size class idx + * Request in bytes Size of allocated block Size class idx * ---------------------------------------------------------------- * 1-8 8 0 - * 9-16 16 1 - * 17-24 24 2 - * 25-32 32 3 - * 33-40 40 4 - * 41-48 48 5 - * 49-56 56 6 - * 57-64 64 7 - * 65-72 72 8 - * ... ... ... - * 241-248 248 30 - * 249-256 256 31 + * 9-16 16 1 + * 17-24 24 2 + * 25-32 32 3 + * 33-40 40 4 + * 41-48 48 5 + * 49-56 56 6 + * 57-64 64 7 + * 65-72 72 8 + * ... ... ... + * 241-248 248 30 + * 249-256 256 31 * - * 0, 257 and up: routed to the underlying allocator. + * 0, 257 and up: routed to the underlying allocator. */ /*==========================================================================*/ @@ -127,9 +127,9 @@ * * You shouldn't change this unless you know what you are doing. */ -#define ALIGNMENT 8 /* must be 2^N */ -#define ALIGNMENT_SHIFT 3 -#define ALIGNMENT_MASK (ALIGNMENT - 1) +#define ALIGNMENT 8 /* must be 2^N */ +#define ALIGNMENT_SHIFT 3 +#define ALIGNMENT_MASK (ALIGNMENT - 1) /* Return the number of bytes in size class I, as a uint. */ #define INDEX2SIZE(I) (((uint)(I) + 1) << ALIGNMENT_SHIFT) @@ -140,14 +140,14 @@ * this value according to your application behaviour and memory needs. * * The following invariants must hold: - * 1) ALIGNMENT <= SMALL_REQUEST_THRESHOLD <= 256 - * 2) SMALL_REQUEST_THRESHOLD is evenly divisible by ALIGNMENT + * 1) ALIGNMENT <= SMALL_REQUEST_THRESHOLD <= 256 + * 2) SMALL_REQUEST_THRESHOLD is evenly divisible by ALIGNMENT * * Although not required, for better performance and space efficiency, * it is recommended that SMALL_REQUEST_THRESHOLD is set to a power of 2. */ -#define SMALL_REQUEST_THRESHOLD 256 -#define NB_SMALL_SIZE_CLASSES (SMALL_REQUEST_THRESHOLD / ALIGNMENT) +#define SMALL_REQUEST_THRESHOLD 256 +#define NB_SMALL_SIZE_CLASSES (SMALL_REQUEST_THRESHOLD / ALIGNMENT) /* * The system's VMM page size can be obtained on most unices with a @@ -159,15 +159,15 @@ * violation fault. 4K is apparently OK for all the platforms that python * currently targets. */ -#define SYSTEM_PAGE_SIZE (4 * 1024) -#define SYSTEM_PAGE_SIZE_MASK (SYSTEM_PAGE_SIZE - 1) +#define SYSTEM_PAGE_SIZE (4 * 1024) +#define SYSTEM_PAGE_SIZE_MASK (SYSTEM_PAGE_SIZE - 1) /* * Maximum amount of memory managed by the allocator for small requests. */ #ifdef WITH_MEMORY_LIMITS #ifndef SMALL_MEMORY_LIMIT -#define SMALL_MEMORY_LIMIT (64 * 1024 * 1024) /* 64 MB -- more? */ +#define SMALL_MEMORY_LIMIT (64 * 1024 * 1024) /* 64 MB -- more? */ #endif #endif @@ -184,18 +184,18 @@ * some address space wastage, but this is the most portable way to request * memory from the system across various platforms. */ -#define ARENA_SIZE (256 << 10) /* 256KB */ +#define ARENA_SIZE (256 << 10) /* 256KB */ #ifdef WITH_MEMORY_LIMITS -#define MAX_ARENAS (SMALL_MEMORY_LIMIT / ARENA_SIZE) +#define MAX_ARENAS (SMALL_MEMORY_LIMIT / ARENA_SIZE) #endif /* * Size of the pools used for small blocks. Should be a power of 2, * between 1K and SYSTEM_PAGE_SIZE, that is: 1k, 2k, 4k. */ -#define POOL_SIZE SYSTEM_PAGE_SIZE /* must be 2^N */ -#define POOL_SIZE_MASK SYSTEM_PAGE_SIZE_MASK +#define POOL_SIZE SYSTEM_PAGE_SIZE /* must be 2^N */ +#define POOL_SIZE_MASK SYSTEM_PAGE_SIZE_MASK /* * -- End of tunable settings section -- @@ -221,92 +221,92 @@ /* * Python's threads are serialized, so object malloc locking is disabled. */ -#define SIMPLELOCK_DECL(lock) /* simple lock declaration */ -#define SIMPLELOCK_INIT(lock) /* allocate (if needed) and initialize */ -#define SIMPLELOCK_FINI(lock) /* free/destroy an existing lock */ -#define SIMPLELOCK_LOCK(lock) /* acquire released lock */ -#define SIMPLELOCK_UNLOCK(lock) /* release acquired lock */ +#define SIMPLELOCK_DECL(lock) /* simple lock declaration */ +#define SIMPLELOCK_INIT(lock) /* allocate (if needed) and initialize */ +#define SIMPLELOCK_FINI(lock) /* free/destroy an existing lock */ +#define SIMPLELOCK_LOCK(lock) /* acquire released lock */ +#define SIMPLELOCK_UNLOCK(lock) /* release acquired lock */ /* * Basic types * I don't care if these are defined in or elsewhere. Axiom. */ #undef uchar -#define uchar unsigned char /* assuming == 8 bits */ +#define uchar unsigned char /* assuming == 8 bits */ #undef uint -#define uint unsigned int /* assuming >= 16 bits */ +#define uint unsigned int /* assuming >= 16 bits */ #undef ulong -#define ulong unsigned long /* assuming >= 32 bits */ +#define ulong unsigned long /* assuming >= 32 bits */ #undef uptr -#define uptr Py_uintptr_t +#define uptr Py_uintptr_t /* When you say memory, my mind reasons in terms of (pointers to) blocks */ typedef uchar block; /* Pool for small blocks. */ struct pool_header { - union { block *_padding; - uint count; } ref; /* number of allocated blocks */ - block *freeblock; /* pool's free list head */ - struct pool_header *nextpool; /* next pool of this size class */ - struct pool_header *prevpool; /* previous pool "" */ - uint arenaindex; /* index into arenas of base adr */ - uint szidx; /* block size class index */ - uint nextoffset; /* bytes to virgin block */ - uint maxnextoffset; /* largest valid nextoffset */ + union { block *_padding; + uint count; } ref; /* number of allocated blocks */ + block *freeblock; /* pool's free list head */ + struct pool_header *nextpool; /* next pool of this size class */ + struct pool_header *prevpool; /* previous pool "" */ + uint arenaindex; /* index into arenas of base adr */ + uint szidx; /* block size class index */ + uint nextoffset; /* bytes to virgin block */ + uint maxnextoffset; /* largest valid nextoffset */ }; typedef struct pool_header *poolp; /* Record keeping for arenas. */ struct arena_object { - /* The address of the arena, as returned by malloc. Note that 0 - * will never be returned by a successful malloc, and is used - * here to mark an arena_object that doesn't correspond to an - * allocated arena. - */ - uptr address; - - /* Pool-aligned pointer to the next pool to be carved off. */ - block* pool_address; - - /* The number of available pools in the arena: free pools + never- - * allocated pools. - */ - uint nfreepools; - - /* The total number of pools in the arena, whether or not available. */ - uint ntotalpools; - - /* Singly-linked list of available pools. */ - struct pool_header* freepools; - - /* Whenever this arena_object is not associated with an allocated - * arena, the nextarena member is used to link all unassociated - * arena_objects in the singly-linked `unused_arena_objects` list. - * The prevarena member is unused in this case. - * - * When this arena_object is associated with an allocated arena - * with at least one available pool, both members are used in the - * doubly-linked `usable_arenas` list, which is maintained in - * increasing order of `nfreepools` values. - * - * Else this arena_object is associated with an allocated arena - * all of whose pools are in use. `nextarena` and `prevarena` - * are both meaningless in this case. - */ - struct arena_object* nextarena; - struct arena_object* prevarena; + /* The address of the arena, as returned by malloc. Note that 0 + * will never be returned by a successful malloc, and is used + * here to mark an arena_object that doesn't correspond to an + * allocated arena. + */ + uptr address; + + /* Pool-aligned pointer to the next pool to be carved off. */ + block* pool_address; + + /* The number of available pools in the arena: free pools + never- + * allocated pools. + */ + uint nfreepools; + + /* The total number of pools in the arena, whether or not available. */ + uint ntotalpools; + + /* Singly-linked list of available pools. */ + struct pool_header* freepools; + + /* Whenever this arena_object is not associated with an allocated + * arena, the nextarena member is used to link all unassociated + * arena_objects in the singly-linked `unused_arena_objects` list. + * The prevarena member is unused in this case. + * + * When this arena_object is associated with an allocated arena + * with at least one available pool, both members are used in the + * doubly-linked `usable_arenas` list, which is maintained in + * increasing order of `nfreepools` values. + * + * Else this arena_object is associated with an allocated arena + * all of whose pools are in use. `nextarena` and `prevarena` + * are both meaningless in this case. + */ + struct arena_object* nextarena; + struct arena_object* prevarena; }; #undef ROUNDUP -#define ROUNDUP(x) (((x) + ALIGNMENT_MASK) & ~ALIGNMENT_MASK) -#define POOL_OVERHEAD ROUNDUP(sizeof(struct pool_header)) +#define ROUNDUP(x) (((x) + ALIGNMENT_MASK) & ~ALIGNMENT_MASK) +#define POOL_OVERHEAD ROUNDUP(sizeof(struct pool_header)) -#define DUMMY_SIZE_IDX 0xffff /* size class of newly cached pools */ +#define DUMMY_SIZE_IDX 0xffff /* size class of newly cached pools */ /* Round pointer P down to the closest pool-aligned address <= P, as a poolp */ #define POOL_ADDR(P) ((poolp)((uptr)(P) & ~(uptr)POOL_SIZE_MASK)) @@ -320,10 +320,10 @@ * This malloc lock */ SIMPLELOCK_DECL(_malloc_lock) -#define LOCK() SIMPLELOCK_LOCK(_malloc_lock) -#define UNLOCK() SIMPLELOCK_UNLOCK(_malloc_lock) -#define LOCK_INIT() SIMPLELOCK_INIT(_malloc_lock) -#define LOCK_FINI() SIMPLELOCK_FINI(_malloc_lock) +#define LOCK() SIMPLELOCK_LOCK(_malloc_lock) +#define UNLOCK() SIMPLELOCK_UNLOCK(_malloc_lock) +#define LOCK_INIT() SIMPLELOCK_INIT(_malloc_lock) +#define LOCK_FINI() SIMPLELOCK_FINI(_malloc_lock) /* * Pool table -- headed, circular, doubly-linked lists of partially used pools. @@ -403,9 +403,9 @@ compensating for that a pool_header's nextpool and prevpool members immediately follow a pool_header's first two members: - union { block *_padding; - uint count; } ref; - block *freeblock; + union { block *_padding; + uint count; } ref; + block *freeblock; each of which consume sizeof(block *) bytes. So what usedpools[i+i] really contains is a fudged-up pointer p such that *if* C believes it's a poolp @@ -421,25 +421,25 @@ the prevpool member. **************************************************************************** */ -#define PTA(x) ((poolp )((uchar *)&(usedpools[2*(x)]) - 2*sizeof(block *))) -#define PT(x) PTA(x), PTA(x) +#define PTA(x) ((poolp )((uchar *)&(usedpools[2*(x)]) - 2*sizeof(block *))) +#define PT(x) PTA(x), PTA(x) static poolp usedpools[2 * ((NB_SMALL_SIZE_CLASSES + 7) / 8) * 8] = { - PT(0), PT(1), PT(2), PT(3), PT(4), PT(5), PT(6), PT(7) + PT(0), PT(1), PT(2), PT(3), PT(4), PT(5), PT(6), PT(7) #if NB_SMALL_SIZE_CLASSES > 8 - , PT(8), PT(9), PT(10), PT(11), PT(12), PT(13), PT(14), PT(15) + , PT(8), PT(9), PT(10), PT(11), PT(12), PT(13), PT(14), PT(15) #if NB_SMALL_SIZE_CLASSES > 16 - , PT(16), PT(17), PT(18), PT(19), PT(20), PT(21), PT(22), PT(23) + , PT(16), PT(17), PT(18), PT(19), PT(20), PT(21), PT(22), PT(23) #if NB_SMALL_SIZE_CLASSES > 24 - , PT(24), PT(25), PT(26), PT(27), PT(28), PT(29), PT(30), PT(31) + , PT(24), PT(25), PT(26), PT(27), PT(28), PT(29), PT(30), PT(31) #if NB_SMALL_SIZE_CLASSES > 32 - , PT(32), PT(33), PT(34), PT(35), PT(36), PT(37), PT(38), PT(39) + , PT(32), PT(33), PT(34), PT(35), PT(36), PT(37), PT(38), PT(39) #if NB_SMALL_SIZE_CLASSES > 40 - , PT(40), PT(41), PT(42), PT(43), PT(44), PT(45), PT(46), PT(47) + , PT(40), PT(41), PT(42), PT(43), PT(44), PT(45), PT(46), PT(47) #if NB_SMALL_SIZE_CLASSES > 48 - , PT(48), PT(49), PT(50), PT(51), PT(52), PT(53), PT(54), PT(55) + , PT(48), PT(49), PT(50), PT(51), PT(52), PT(53), PT(54), PT(55) #if NB_SMALL_SIZE_CLASSES > 56 - , PT(56), PT(57), PT(58), PT(59), PT(60), PT(61), PT(62), PT(63) + , PT(56), PT(57), PT(58), PT(59), PT(60), PT(61), PT(62), PT(63) #endif /* NB_SMALL_SIZE_CLASSES > 56 */ #endif /* NB_SMALL_SIZE_CLASSES > 48 */ #endif /* NB_SMALL_SIZE_CLASSES > 40 */ @@ -523,90 +523,90 @@ static struct arena_object* new_arena(void) { - struct arena_object* arenaobj; - uint excess; /* number of bytes above pool alignment */ + struct arena_object* arenaobj; + uint excess; /* number of bytes above pool alignment */ #ifdef PYMALLOC_DEBUG - if (Py_GETENV("PYTHONMALLOCSTATS")) - _PyObject_DebugMallocStats(); + if (Py_GETENV("PYTHONMALLOCSTATS")) + _PyObject_DebugMallocStats(); #endif - if (unused_arena_objects == NULL) { - uint i; - uint numarenas; - size_t nbytes; - - /* Double the number of arena objects on each allocation. - * Note that it's possible for `numarenas` to overflow. - */ - numarenas = maxarenas ? maxarenas << 1 : INITIAL_ARENA_OBJECTS; - if (numarenas <= maxarenas) - return NULL; /* overflow */ + if (unused_arena_objects == NULL) { + uint i; + uint numarenas; + size_t nbytes; + + /* Double the number of arena objects on each allocation. + * Note that it's possible for `numarenas` to overflow. + */ + numarenas = maxarenas ? maxarenas << 1 : INITIAL_ARENA_OBJECTS; + if (numarenas <= maxarenas) + return NULL; /* overflow */ #if SIZEOF_SIZE_T <= SIZEOF_INT - if (numarenas > PY_SIZE_MAX / sizeof(*arenas)) - return NULL; /* overflow */ + if (numarenas > PY_SIZE_MAX / sizeof(*arenas)) + return NULL; /* overflow */ #endif - nbytes = numarenas * sizeof(*arenas); - arenaobj = (struct arena_object *)realloc(arenas, nbytes); - if (arenaobj == NULL) - return NULL; - arenas = arenaobj; - - /* We might need to fix pointers that were copied. However, - * new_arena only gets called when all the pages in the - * previous arenas are full. Thus, there are *no* pointers - * into the old array. Thus, we don't have to worry about - * invalid pointers. Just to be sure, some asserts: - */ - assert(usable_arenas == NULL); - assert(unused_arena_objects == NULL); - - /* Put the new arenas on the unused_arena_objects list. */ - for (i = maxarenas; i < numarenas; ++i) { - arenas[i].address = 0; /* mark as unassociated */ - arenas[i].nextarena = i < numarenas - 1 ? - &arenas[i+1] : NULL; - } - - /* Update globals. */ - unused_arena_objects = &arenas[maxarenas]; - maxarenas = numarenas; - } - - /* Take the next available arena object off the head of the list. */ - assert(unused_arena_objects != NULL); - arenaobj = unused_arena_objects; - unused_arena_objects = arenaobj->nextarena; - assert(arenaobj->address == 0); - arenaobj->address = (uptr)malloc(ARENA_SIZE); - if (arenaobj->address == 0) { - /* The allocation failed: return NULL after putting the - * arenaobj back. - */ - arenaobj->nextarena = unused_arena_objects; - unused_arena_objects = arenaobj; - return NULL; - } + nbytes = numarenas * sizeof(*arenas); + arenaobj = (struct arena_object *)realloc(arenas, nbytes); + if (arenaobj == NULL) + return NULL; + arenas = arenaobj; + + /* We might need to fix pointers that were copied. However, + * new_arena only gets called when all the pages in the + * previous arenas are full. Thus, there are *no* pointers + * into the old array. Thus, we don't have to worry about + * invalid pointers. Just to be sure, some asserts: + */ + assert(usable_arenas == NULL); + assert(unused_arena_objects == NULL); - ++narenas_currently_allocated; + /* Put the new arenas on the unused_arena_objects list. */ + for (i = maxarenas; i < numarenas; ++i) { + arenas[i].address = 0; /* mark as unassociated */ + arenas[i].nextarena = i < numarenas - 1 ? + &arenas[i+1] : NULL; + } + + /* Update globals. */ + unused_arena_objects = &arenas[maxarenas]; + maxarenas = numarenas; + } + + /* Take the next available arena object off the head of the list. */ + assert(unused_arena_objects != NULL); + arenaobj = unused_arena_objects; + unused_arena_objects = arenaobj->nextarena; + assert(arenaobj->address == 0); + arenaobj->address = (uptr)malloc(ARENA_SIZE); + if (arenaobj->address == 0) { + /* The allocation failed: return NULL after putting the + * arenaobj back. + */ + arenaobj->nextarena = unused_arena_objects; + unused_arena_objects = arenaobj; + return NULL; + } + + ++narenas_currently_allocated; #ifdef PYMALLOC_DEBUG - ++ntimes_arena_allocated; - if (narenas_currently_allocated > narenas_highwater) - narenas_highwater = narenas_currently_allocated; + ++ntimes_arena_allocated; + if (narenas_currently_allocated > narenas_highwater) + narenas_highwater = narenas_currently_allocated; #endif - arenaobj->freepools = NULL; - /* pool_address <- first pool-aligned address in the arena - nfreepools <- number of whole pools that fit after alignment */ - arenaobj->pool_address = (block*)arenaobj->address; - arenaobj->nfreepools = ARENA_SIZE / POOL_SIZE; - assert(POOL_SIZE * arenaobj->nfreepools == ARENA_SIZE); - excess = (uint)(arenaobj->address & POOL_SIZE_MASK); - if (excess != 0) { - --arenaobj->nfreepools; - arenaobj->pool_address += POOL_SIZE - excess; - } - arenaobj->ntotalpools = arenaobj->nfreepools; + arenaobj->freepools = NULL; + /* pool_address <- first pool-aligned address in the arena + nfreepools <- number of whole pools that fit after alignment */ + arenaobj->pool_address = (block*)arenaobj->address; + arenaobj->nfreepools = ARENA_SIZE / POOL_SIZE; + assert(POOL_SIZE * arenaobj->nfreepools == ARENA_SIZE); + excess = (uint)(arenaobj->address & POOL_SIZE_MASK); + if (excess != 0) { + --arenaobj->nfreepools; + arenaobj->pool_address += POOL_SIZE - excess; + } + arenaobj->ntotalpools = arenaobj->nfreepools; - return arenaobj; + return arenaobj; } /* @@ -622,11 +622,11 @@ Tricky: Let B be the arena base address associated with the pool, B = arenas[(POOL)->arenaindex].address. Then P belongs to the arena if and only if - B <= P < B + ARENA_SIZE + B <= P < B + ARENA_SIZE Subtracting B throughout, this is true iff - 0 <= P-B < ARENA_SIZE + 0 <= P-B < ARENA_SIZE By using unsigned arithmetic, the "0 <=" half of the test can be skipped. @@ -660,7 +660,7 @@ arena_object (one not currently associated with an allocated arena), AO.address is 0, and the second test in the macro reduces to: - P < ARENA_SIZE + P < ARENA_SIZE If P >= ARENA_SIZE (extremely likely), the macro again correctly concludes that P is not controlled by obmalloc. However, if P < ARENA_SIZE, this part @@ -683,10 +683,10 @@ obmalloc controls. Since this test is needed at every entry point, it's extremely desirable that it be this fast. */ -#define Py_ADDRESS_IN_RANGE(P, POOL) \ - ((POOL)->arenaindex < maxarenas && \ - (uptr)(P) - arenas[(POOL)->arenaindex].address < (uptr)ARENA_SIZE && \ - arenas[(POOL)->arenaindex].address != 0) +#define Py_ADDRESS_IN_RANGE(P, POOL) \ + ((POOL)->arenaindex < maxarenas && \ + (uptr)(P) - arenas[(POOL)->arenaindex].address < (uptr)ARENA_SIZE && \ + arenas[(POOL)->arenaindex].address != 0) /* This is only useful when running memory debuggers such as @@ -709,7 +709,7 @@ #undef Py_ADDRESS_IN_RANGE #if defined(__GNUC__) && ((__GNUC__ == 3) && (__GNUC_MINOR__ >= 1) || \ - (__GNUC__ >= 4)) + (__GNUC__ >= 4)) #define Py_NO_INLINE __attribute__((__noinline__)) #else #define Py_NO_INLINE @@ -738,201 +738,201 @@ void * PyObject_Malloc(size_t nbytes) { - block *bp; - poolp pool; - poolp next; - uint size; + block *bp; + poolp pool; + poolp next; + uint size; #ifdef WITH_VALGRIND - if (UNLIKELY(running_on_valgrind == -1)) - running_on_valgrind = RUNNING_ON_VALGRIND; - if (UNLIKELY(running_on_valgrind)) - goto redirect; + if (UNLIKELY(running_on_valgrind == -1)) + running_on_valgrind = RUNNING_ON_VALGRIND; + if (UNLIKELY(running_on_valgrind)) + goto redirect; #endif - /* - * Limit ourselves to PY_SSIZE_T_MAX bytes to prevent security holes. - * Most python internals blindly use a signed Py_ssize_t to track - * things without checking for overflows or negatives. - * As size_t is unsigned, checking for nbytes < 0 is not required. - */ - if (nbytes > PY_SSIZE_T_MAX) - return NULL; - - /* - * This implicitly redirects malloc(0). - */ - if ((nbytes - 1) < SMALL_REQUEST_THRESHOLD) { - LOCK(); - /* - * Most frequent paths first - */ - size = (uint)(nbytes - 1) >> ALIGNMENT_SHIFT; - pool = usedpools[size + size]; - if (pool != pool->nextpool) { - /* - * There is a used pool for this size class. - * Pick up the head block of its free list. - */ - ++pool->ref.count; - bp = pool->freeblock; - assert(bp != NULL); - if ((pool->freeblock = *(block **)bp) != NULL) { - UNLOCK(); - return (void *)bp; - } - /* - * Reached the end of the free list, try to extend it. - */ - if (pool->nextoffset <= pool->maxnextoffset) { - /* There is room for another block. */ - pool->freeblock = (block*)pool + - pool->nextoffset; - pool->nextoffset += INDEX2SIZE(size); - *(block **)(pool->freeblock) = NULL; - UNLOCK(); - return (void *)bp; - } - /* Pool is full, unlink from used pools. */ - next = pool->nextpool; - pool = pool->prevpool; - next->prevpool = pool; - pool->nextpool = next; - UNLOCK(); - return (void *)bp; - } - - /* There isn't a pool of the right size class immediately - * available: use a free pool. - */ - if (usable_arenas == NULL) { - /* No arena has a free pool: allocate a new arena. */ + /* + * Limit ourselves to PY_SSIZE_T_MAX bytes to prevent security holes. + * Most python internals blindly use a signed Py_ssize_t to track + * things without checking for overflows or negatives. + * As size_t is unsigned, checking for nbytes < 0 is not required. + */ + if (nbytes > PY_SSIZE_T_MAX) + return NULL; + + /* + * This implicitly redirects malloc(0). + */ + if ((nbytes - 1) < SMALL_REQUEST_THRESHOLD) { + LOCK(); + /* + * Most frequent paths first + */ + size = (uint)(nbytes - 1) >> ALIGNMENT_SHIFT; + pool = usedpools[size + size]; + if (pool != pool->nextpool) { + /* + * There is a used pool for this size class. + * Pick up the head block of its free list. + */ + ++pool->ref.count; + bp = pool->freeblock; + assert(bp != NULL); + if ((pool->freeblock = *(block **)bp) != NULL) { + UNLOCK(); + return (void *)bp; + } + /* + * Reached the end of the free list, try to extend it. + */ + if (pool->nextoffset <= pool->maxnextoffset) { + /* There is room for another block. */ + pool->freeblock = (block*)pool + + pool->nextoffset; + pool->nextoffset += INDEX2SIZE(size); + *(block **)(pool->freeblock) = NULL; + UNLOCK(); + return (void *)bp; + } + /* Pool is full, unlink from used pools. */ + next = pool->nextpool; + pool = pool->prevpool; + next->prevpool = pool; + pool->nextpool = next; + UNLOCK(); + return (void *)bp; + } + + /* There isn't a pool of the right size class immediately + * available: use a free pool. + */ + if (usable_arenas == NULL) { + /* No arena has a free pool: allocate a new arena. */ #ifdef WITH_MEMORY_LIMITS - if (narenas_currently_allocated >= MAX_ARENAS) { - UNLOCK(); - goto redirect; - } + if (narenas_currently_allocated >= MAX_ARENAS) { + UNLOCK(); + goto redirect; + } #endif - usable_arenas = new_arena(); - if (usable_arenas == NULL) { - UNLOCK(); - goto redirect; - } - usable_arenas->nextarena = - usable_arenas->prevarena = NULL; - } - assert(usable_arenas->address != 0); - - /* Try to get a cached free pool. */ - pool = usable_arenas->freepools; - if (pool != NULL) { - /* Unlink from cached pools. */ - usable_arenas->freepools = pool->nextpool; - - /* This arena already had the smallest nfreepools - * value, so decreasing nfreepools doesn't change - * that, and we don't need to rearrange the - * usable_arenas list. However, if the arena has - * become wholly allocated, we need to remove its - * arena_object from usable_arenas. - */ - --usable_arenas->nfreepools; - if (usable_arenas->nfreepools == 0) { - /* Wholly allocated: remove. */ - assert(usable_arenas->freepools == NULL); - assert(usable_arenas->nextarena == NULL || - usable_arenas->nextarena->prevarena == - usable_arenas); - - usable_arenas = usable_arenas->nextarena; - if (usable_arenas != NULL) { - usable_arenas->prevarena = NULL; - assert(usable_arenas->address != 0); - } - } - else { - /* nfreepools > 0: it must be that freepools - * isn't NULL, or that we haven't yet carved - * off all the arena's pools for the first - * time. - */ - assert(usable_arenas->freepools != NULL || - usable_arenas->pool_address <= - (block*)usable_arenas->address + - ARENA_SIZE - POOL_SIZE); - } - init_pool: - /* Frontlink to used pools. */ - next = usedpools[size + size]; /* == prev */ - pool->nextpool = next; - pool->prevpool = next; - next->nextpool = pool; - next->prevpool = pool; - pool->ref.count = 1; - if (pool->szidx == size) { - /* Luckily, this pool last contained blocks - * of the same size class, so its header - * and free list are already initialized. - */ - bp = pool->freeblock; - pool->freeblock = *(block **)bp; - UNLOCK(); - return (void *)bp; - } - /* - * Initialize the pool header, set up the free list to - * contain just the second block, and return the first - * block. - */ - pool->szidx = size; - size = INDEX2SIZE(size); - bp = (block *)pool + POOL_OVERHEAD; - pool->nextoffset = POOL_OVERHEAD + (size << 1); - pool->maxnextoffset = POOL_SIZE - size; - pool->freeblock = bp + size; - *(block **)(pool->freeblock) = NULL; - UNLOCK(); - return (void *)bp; - } - - /* Carve off a new pool. */ - assert(usable_arenas->nfreepools > 0); - assert(usable_arenas->freepools == NULL); - pool = (poolp)usable_arenas->pool_address; - assert((block*)pool <= (block*)usable_arenas->address + - ARENA_SIZE - POOL_SIZE); - pool->arenaindex = usable_arenas - arenas; - assert(&arenas[pool->arenaindex] == usable_arenas); - pool->szidx = DUMMY_SIZE_IDX; - usable_arenas->pool_address += POOL_SIZE; - --usable_arenas->nfreepools; - - if (usable_arenas->nfreepools == 0) { - assert(usable_arenas->nextarena == NULL || - usable_arenas->nextarena->prevarena == - usable_arenas); - /* Unlink the arena: it is completely allocated. */ - usable_arenas = usable_arenas->nextarena; - if (usable_arenas != NULL) { - usable_arenas->prevarena = NULL; - assert(usable_arenas->address != 0); - } - } + usable_arenas = new_arena(); + if (usable_arenas == NULL) { + UNLOCK(); + goto redirect; + } + usable_arenas->nextarena = + usable_arenas->prevarena = NULL; + } + assert(usable_arenas->address != 0); + + /* Try to get a cached free pool. */ + pool = usable_arenas->freepools; + if (pool != NULL) { + /* Unlink from cached pools. */ + usable_arenas->freepools = pool->nextpool; + + /* This arena already had the smallest nfreepools + * value, so decreasing nfreepools doesn't change + * that, and we don't need to rearrange the + * usable_arenas list. However, if the arena has + * become wholly allocated, we need to remove its + * arena_object from usable_arenas. + */ + --usable_arenas->nfreepools; + if (usable_arenas->nfreepools == 0) { + /* Wholly allocated: remove. */ + assert(usable_arenas->freepools == NULL); + assert(usable_arenas->nextarena == NULL || + usable_arenas->nextarena->prevarena == + usable_arenas); + + usable_arenas = usable_arenas->nextarena; + if (usable_arenas != NULL) { + usable_arenas->prevarena = NULL; + assert(usable_arenas->address != 0); + } + } + else { + /* nfreepools > 0: it must be that freepools + * isn't NULL, or that we haven't yet carved + * off all the arena's pools for the first + * time. + */ + assert(usable_arenas->freepools != NULL || + usable_arenas->pool_address <= + (block*)usable_arenas->address + + ARENA_SIZE - POOL_SIZE); + } + init_pool: + /* Frontlink to used pools. */ + next = usedpools[size + size]; /* == prev */ + pool->nextpool = next; + pool->prevpool = next; + next->nextpool = pool; + next->prevpool = pool; + pool->ref.count = 1; + if (pool->szidx == size) { + /* Luckily, this pool last contained blocks + * of the same size class, so its header + * and free list are already initialized. + */ + bp = pool->freeblock; + pool->freeblock = *(block **)bp; + UNLOCK(); + return (void *)bp; + } + /* + * Initialize the pool header, set up the free list to + * contain just the second block, and return the first + * block. + */ + pool->szidx = size; + size = INDEX2SIZE(size); + bp = (block *)pool + POOL_OVERHEAD; + pool->nextoffset = POOL_OVERHEAD + (size << 1); + pool->maxnextoffset = POOL_SIZE - size; + pool->freeblock = bp + size; + *(block **)(pool->freeblock) = NULL; + UNLOCK(); + return (void *)bp; + } + + /* Carve off a new pool. */ + assert(usable_arenas->nfreepools > 0); + assert(usable_arenas->freepools == NULL); + pool = (poolp)usable_arenas->pool_address; + assert((block*)pool <= (block*)usable_arenas->address + + ARENA_SIZE - POOL_SIZE); + pool->arenaindex = usable_arenas - arenas; + assert(&arenas[pool->arenaindex] == usable_arenas); + pool->szidx = DUMMY_SIZE_IDX; + usable_arenas->pool_address += POOL_SIZE; + --usable_arenas->nfreepools; + + if (usable_arenas->nfreepools == 0) { + assert(usable_arenas->nextarena == NULL || + usable_arenas->nextarena->prevarena == + usable_arenas); + /* Unlink the arena: it is completely allocated. */ + usable_arenas = usable_arenas->nextarena; + if (usable_arenas != NULL) { + usable_arenas->prevarena = NULL; + assert(usable_arenas->address != 0); + } + } - goto init_pool; - } + goto init_pool; + } - /* The small block allocator ends here. */ + /* The small block allocator ends here. */ redirect: - /* Redirect the original request to the underlying (libc) allocator. - * We jump here on bigger requests, on error in the code above (as a - * last chance to serve the request) or when the max memory limit - * has been reached. - */ - if (nbytes == 0) - nbytes = 1; - return (void *)malloc(nbytes); + /* Redirect the original request to the underlying (libc) allocator. + * We jump here on bigger requests, on error in the code above (as a + * last chance to serve the request) or when the max memory limit + * has been reached. + */ + if (nbytes == 0) + nbytes = 1; + return (void *)malloc(nbytes); } /* free */ @@ -941,218 +941,218 @@ void PyObject_Free(void *p) { - poolp pool; - block *lastfree; - poolp next, prev; - uint size; + poolp pool; + block *lastfree; + poolp next, prev; + uint size; - if (p == NULL) /* free(NULL) has no effect */ - return; + if (p == NULL) /* free(NULL) has no effect */ + return; #ifdef WITH_VALGRIND - if (UNLIKELY(running_on_valgrind > 0)) - goto redirect; + if (UNLIKELY(running_on_valgrind > 0)) + goto redirect; #endif - pool = POOL_ADDR(p); - if (Py_ADDRESS_IN_RANGE(p, pool)) { - /* We allocated this address. */ - LOCK(); - /* Link p to the start of the pool's freeblock list. Since - * the pool had at least the p block outstanding, the pool - * wasn't empty (so it's already in a usedpools[] list, or - * was full and is in no list -- it's not in the freeblocks - * list in any case). - */ - assert(pool->ref.count > 0); /* else it was empty */ - *(block **)p = lastfree = pool->freeblock; - pool->freeblock = (block *)p; - if (lastfree) { - struct arena_object* ao; - uint nf; /* ao->nfreepools */ - - /* freeblock wasn't NULL, so the pool wasn't full, - * and the pool is in a usedpools[] list. - */ - if (--pool->ref.count != 0) { - /* pool isn't empty: leave it in usedpools */ - UNLOCK(); - return; - } - /* Pool is now empty: unlink from usedpools, and - * link to the front of freepools. This ensures that - * previously freed pools will be allocated later - * (being not referenced, they are perhaps paged out). - */ - next = pool->nextpool; - prev = pool->prevpool; - next->prevpool = prev; - prev->nextpool = next; - - /* Link the pool to freepools. This is a singly-linked - * list, and pool->prevpool isn't used there. - */ - ao = &arenas[pool->arenaindex]; - pool->nextpool = ao->freepools; - ao->freepools = pool; - nf = ++ao->nfreepools; - - /* All the rest is arena management. We just freed - * a pool, and there are 4 cases for arena mgmt: - * 1. If all the pools are free, return the arena to - * the system free(). - * 2. If this is the only free pool in the arena, - * add the arena back to the `usable_arenas` list. - * 3. If the "next" arena has a smaller count of free - * pools, we have to "slide this arena right" to - * restore that usable_arenas is sorted in order of - * nfreepools. - * 4. Else there's nothing more to do. - */ - if (nf == ao->ntotalpools) { - /* Case 1. First unlink ao from usable_arenas. - */ - assert(ao->prevarena == NULL || - ao->prevarena->address != 0); - assert(ao ->nextarena == NULL || - ao->nextarena->address != 0); - - /* Fix the pointer in the prevarena, or the - * usable_arenas pointer. - */ - if (ao->prevarena == NULL) { - usable_arenas = ao->nextarena; - assert(usable_arenas == NULL || - usable_arenas->address != 0); - } - else { - assert(ao->prevarena->nextarena == ao); - ao->prevarena->nextarena = - ao->nextarena; - } - /* Fix the pointer in the nextarena. */ - if (ao->nextarena != NULL) { - assert(ao->nextarena->prevarena == ao); - ao->nextarena->prevarena = - ao->prevarena; - } - /* Record that this arena_object slot is - * available to be reused. - */ - ao->nextarena = unused_arena_objects; - unused_arena_objects = ao; - - /* Free the entire arena. */ - free((void *)ao->address); - ao->address = 0; /* mark unassociated */ - --narenas_currently_allocated; - - UNLOCK(); - return; - } - if (nf == 1) { - /* Case 2. Put ao at the head of - * usable_arenas. Note that because - * ao->nfreepools was 0 before, ao isn't - * currently on the usable_arenas list. - */ - ao->nextarena = usable_arenas; - ao->prevarena = NULL; - if (usable_arenas) - usable_arenas->prevarena = ao; - usable_arenas = ao; - assert(usable_arenas->address != 0); - - UNLOCK(); - return; - } - /* If this arena is now out of order, we need to keep - * the list sorted. The list is kept sorted so that - * the "most full" arenas are used first, which allows - * the nearly empty arenas to be completely freed. In - * a few un-scientific tests, it seems like this - * approach allowed a lot more memory to be freed. - */ - if (ao->nextarena == NULL || - nf <= ao->nextarena->nfreepools) { - /* Case 4. Nothing to do. */ - UNLOCK(); - return; - } - /* Case 3: We have to move the arena towards the end - * of the list, because it has more free pools than - * the arena to its right. - * First unlink ao from usable_arenas. - */ - if (ao->prevarena != NULL) { - /* ao isn't at the head of the list */ - assert(ao->prevarena->nextarena == ao); - ao->prevarena->nextarena = ao->nextarena; - } - else { - /* ao is at the head of the list */ - assert(usable_arenas == ao); - usable_arenas = ao->nextarena; - } - ao->nextarena->prevarena = ao->prevarena; - - /* Locate the new insertion point by iterating over - * the list, using our nextarena pointer. - */ - while (ao->nextarena != NULL && - nf > ao->nextarena->nfreepools) { - ao->prevarena = ao->nextarena; - ao->nextarena = ao->nextarena->nextarena; - } - - /* Insert ao at this point. */ - assert(ao->nextarena == NULL || - ao->prevarena == ao->nextarena->prevarena); - assert(ao->prevarena->nextarena == ao->nextarena); - - ao->prevarena->nextarena = ao; - if (ao->nextarena != NULL) - ao->nextarena->prevarena = ao; - - /* Verify that the swaps worked. */ - assert(ao->nextarena == NULL || - nf <= ao->nextarena->nfreepools); - assert(ao->prevarena == NULL || - nf > ao->prevarena->nfreepools); - assert(ao->nextarena == NULL || - ao->nextarena->prevarena == ao); - assert((usable_arenas == ao && - ao->prevarena == NULL) || - ao->prevarena->nextarena == ao); - - UNLOCK(); - return; - } - /* Pool was full, so doesn't currently live in any list: - * link it to the front of the appropriate usedpools[] list. - * This mimics LRU pool usage for new allocations and - * targets optimal filling when several pools contain - * blocks of the same size class. - */ - --pool->ref.count; - assert(pool->ref.count > 0); /* else the pool is empty */ - size = pool->szidx; - next = usedpools[size + size]; - prev = next->prevpool; - /* insert pool before next: prev <-> pool <-> next */ - pool->nextpool = next; - pool->prevpool = prev; - next->prevpool = pool; - prev->nextpool = pool; - UNLOCK(); - return; - } + pool = POOL_ADDR(p); + if (Py_ADDRESS_IN_RANGE(p, pool)) { + /* We allocated this address. */ + LOCK(); + /* Link p to the start of the pool's freeblock list. Since + * the pool had at least the p block outstanding, the pool + * wasn't empty (so it's already in a usedpools[] list, or + * was full and is in no list -- it's not in the freeblocks + * list in any case). + */ + assert(pool->ref.count > 0); /* else it was empty */ + *(block **)p = lastfree = pool->freeblock; + pool->freeblock = (block *)p; + if (lastfree) { + struct arena_object* ao; + uint nf; /* ao->nfreepools */ + + /* freeblock wasn't NULL, so the pool wasn't full, + * and the pool is in a usedpools[] list. + */ + if (--pool->ref.count != 0) { + /* pool isn't empty: leave it in usedpools */ + UNLOCK(); + return; + } + /* Pool is now empty: unlink from usedpools, and + * link to the front of freepools. This ensures that + * previously freed pools will be allocated later + * (being not referenced, they are perhaps paged out). + */ + next = pool->nextpool; + prev = pool->prevpool; + next->prevpool = prev; + prev->nextpool = next; + + /* Link the pool to freepools. This is a singly-linked + * list, and pool->prevpool isn't used there. + */ + ao = &arenas[pool->arenaindex]; + pool->nextpool = ao->freepools; + ao->freepools = pool; + nf = ++ao->nfreepools; + + /* All the rest is arena management. We just freed + * a pool, and there are 4 cases for arena mgmt: + * 1. If all the pools are free, return the arena to + * the system free(). + * 2. If this is the only free pool in the arena, + * add the arena back to the `usable_arenas` list. + * 3. If the "next" arena has a smaller count of free + * pools, we have to "slide this arena right" to + * restore that usable_arenas is sorted in order of + * nfreepools. + * 4. Else there's nothing more to do. + */ + if (nf == ao->ntotalpools) { + /* Case 1. First unlink ao from usable_arenas. + */ + assert(ao->prevarena == NULL || + ao->prevarena->address != 0); + assert(ao ->nextarena == NULL || + ao->nextarena->address != 0); + + /* Fix the pointer in the prevarena, or the + * usable_arenas pointer. + */ + if (ao->prevarena == NULL) { + usable_arenas = ao->nextarena; + assert(usable_arenas == NULL || + usable_arenas->address != 0); + } + else { + assert(ao->prevarena->nextarena == ao); + ao->prevarena->nextarena = + ao->nextarena; + } + /* Fix the pointer in the nextarena. */ + if (ao->nextarena != NULL) { + assert(ao->nextarena->prevarena == ao); + ao->nextarena->prevarena = + ao->prevarena; + } + /* Record that this arena_object slot is + * available to be reused. + */ + ao->nextarena = unused_arena_objects; + unused_arena_objects = ao; + + /* Free the entire arena. */ + free((void *)ao->address); + ao->address = 0; /* mark unassociated */ + --narenas_currently_allocated; + + UNLOCK(); + return; + } + if (nf == 1) { + /* Case 2. Put ao at the head of + * usable_arenas. Note that because + * ao->nfreepools was 0 before, ao isn't + * currently on the usable_arenas list. + */ + ao->nextarena = usable_arenas; + ao->prevarena = NULL; + if (usable_arenas) + usable_arenas->prevarena = ao; + usable_arenas = ao; + assert(usable_arenas->address != 0); + + UNLOCK(); + return; + } + /* If this arena is now out of order, we need to keep + * the list sorted. The list is kept sorted so that + * the "most full" arenas are used first, which allows + * the nearly empty arenas to be completely freed. In + * a few un-scientific tests, it seems like this + * approach allowed a lot more memory to be freed. + */ + if (ao->nextarena == NULL || + nf <= ao->nextarena->nfreepools) { + /* Case 4. Nothing to do. */ + UNLOCK(); + return; + } + /* Case 3: We have to move the arena towards the end + * of the list, because it has more free pools than + * the arena to its right. + * First unlink ao from usable_arenas. + */ + if (ao->prevarena != NULL) { + /* ao isn't at the head of the list */ + assert(ao->prevarena->nextarena == ao); + ao->prevarena->nextarena = ao->nextarena; + } + else { + /* ao is at the head of the list */ + assert(usable_arenas == ao); + usable_arenas = ao->nextarena; + } + ao->nextarena->prevarena = ao->prevarena; + + /* Locate the new insertion point by iterating over + * the list, using our nextarena pointer. + */ + while (ao->nextarena != NULL && + nf > ao->nextarena->nfreepools) { + ao->prevarena = ao->nextarena; + ao->nextarena = ao->nextarena->nextarena; + } + + /* Insert ao at this point. */ + assert(ao->nextarena == NULL || + ao->prevarena == ao->nextarena->prevarena); + assert(ao->prevarena->nextarena == ao->nextarena); + + ao->prevarena->nextarena = ao; + if (ao->nextarena != NULL) + ao->nextarena->prevarena = ao; + + /* Verify that the swaps worked. */ + assert(ao->nextarena == NULL || + nf <= ao->nextarena->nfreepools); + assert(ao->prevarena == NULL || + nf > ao->prevarena->nfreepools); + assert(ao->nextarena == NULL || + ao->nextarena->prevarena == ao); + assert((usable_arenas == ao && + ao->prevarena == NULL) || + ao->prevarena->nextarena == ao); + + UNLOCK(); + return; + } + /* Pool was full, so doesn't currently live in any list: + * link it to the front of the appropriate usedpools[] list. + * This mimics LRU pool usage for new allocations and + * targets optimal filling when several pools contain + * blocks of the same size class. + */ + --pool->ref.count; + assert(pool->ref.count > 0); /* else the pool is empty */ + size = pool->szidx; + next = usedpools[size + size]; + prev = next->prevpool; + /* insert pool before next: prev <-> pool <-> next */ + pool->nextpool = next; + pool->prevpool = prev; + next->prevpool = pool; + prev->nextpool = pool; + UNLOCK(); + return; + } #ifdef WITH_VALGRIND redirect: #endif - /* We didn't allocate this address. */ - free(p); + /* We didn't allocate this address. */ + free(p); } /* realloc. If p is NULL, this acts like malloc(nbytes). Else if nbytes==0, @@ -1164,81 +1164,81 @@ void * PyObject_Realloc(void *p, size_t nbytes) { - void *bp; - poolp pool; - size_t size; - - if (p == NULL) - return PyObject_Malloc(nbytes); - - /* - * Limit ourselves to PY_SSIZE_T_MAX bytes to prevent security holes. - * Most python internals blindly use a signed Py_ssize_t to track - * things without checking for overflows or negatives. - * As size_t is unsigned, checking for nbytes < 0 is not required. - */ - if (nbytes > PY_SSIZE_T_MAX) - return NULL; + void *bp; + poolp pool; + size_t size; + + if (p == NULL) + return PyObject_Malloc(nbytes); + + /* + * Limit ourselves to PY_SSIZE_T_MAX bytes to prevent security holes. + * Most python internals blindly use a signed Py_ssize_t to track + * things without checking for overflows or negatives. + * As size_t is unsigned, checking for nbytes < 0 is not required. + */ + if (nbytes > PY_SSIZE_T_MAX) + return NULL; #ifdef WITH_VALGRIND - /* Treat running_on_valgrind == -1 the same as 0 */ - if (UNLIKELY(running_on_valgrind > 0)) - goto redirect; + /* Treat running_on_valgrind == -1 the same as 0 */ + if (UNLIKELY(running_on_valgrind > 0)) + goto redirect; #endif - pool = POOL_ADDR(p); - if (Py_ADDRESS_IN_RANGE(p, pool)) { - /* We're in charge of this block */ - size = INDEX2SIZE(pool->szidx); - if (nbytes <= size) { - /* The block is staying the same or shrinking. If - * it's shrinking, there's a tradeoff: it costs - * cycles to copy the block to a smaller size class, - * but it wastes memory not to copy it. The - * compromise here is to copy on shrink only if at - * least 25% of size can be shaved off. - */ - if (4 * nbytes > 3 * size) { - /* It's the same, - * or shrinking and new/old > 3/4. - */ - return p; - } - size = nbytes; - } - bp = PyObject_Malloc(nbytes); - if (bp != NULL) { - memcpy(bp, p, size); - PyObject_Free(p); - } - return bp; - } + pool = POOL_ADDR(p); + if (Py_ADDRESS_IN_RANGE(p, pool)) { + /* We're in charge of this block */ + size = INDEX2SIZE(pool->szidx); + if (nbytes <= size) { + /* The block is staying the same or shrinking. If + * it's shrinking, there's a tradeoff: it costs + * cycles to copy the block to a smaller size class, + * but it wastes memory not to copy it. The + * compromise here is to copy on shrink only if at + * least 25% of size can be shaved off. + */ + if (4 * nbytes > 3 * size) { + /* It's the same, + * or shrinking and new/old > 3/4. + */ + return p; + } + size = nbytes; + } + bp = PyObject_Malloc(nbytes); + if (bp != NULL) { + memcpy(bp, p, size); + PyObject_Free(p); + } + return bp; + } #ifdef WITH_VALGRIND redirect: #endif - /* We're not managing this block. If nbytes <= - * SMALL_REQUEST_THRESHOLD, it's tempting to try to take over this - * block. However, if we do, we need to copy the valid data from - * the C-managed block to one of our blocks, and there's no portable - * way to know how much of the memory space starting at p is valid. - * As bug 1185883 pointed out the hard way, it's possible that the - * C-managed block is "at the end" of allocated VM space, so that - * a memory fault can occur if we try to copy nbytes bytes starting - * at p. Instead we punt: let C continue to manage this block. - */ - if (nbytes) - return realloc(p, nbytes); - /* C doesn't define the result of realloc(p, 0) (it may or may not - * return NULL then), but Python's docs promise that nbytes==0 never - * returns NULL. We don't pass 0 to realloc(), to avoid that endcase - * to begin with. Even then, we can't be sure that realloc() won't - * return NULL. - */ - bp = realloc(p, 1); - return bp ? bp : p; + /* We're not managing this block. If nbytes <= + * SMALL_REQUEST_THRESHOLD, it's tempting to try to take over this + * block. However, if we do, we need to copy the valid data from + * the C-managed block to one of our blocks, and there's no portable + * way to know how much of the memory space starting at p is valid. + * As bug 1185883 pointed out the hard way, it's possible that the + * C-managed block is "at the end" of allocated VM space, so that + * a memory fault can occur if we try to copy nbytes bytes starting + * at p. Instead we punt: let C continue to manage this block. + */ + if (nbytes) + return realloc(p, nbytes); + /* C doesn't define the result of realloc(p, 0) (it may or may not + * return NULL then), but Python's docs promise that nbytes==0 never + * returns NULL. We don't pass 0 to realloc(), to avoid that endcase + * to begin with. Even then, we can't be sure that realloc() won't + * return NULL. + */ + bp = realloc(p, 1); + return bp ? bp : p; } -#else /* ! WITH_PYMALLOC */ +#else /* ! WITH_PYMALLOC */ /*==========================================================================*/ /* pymalloc not enabled: Redirect the entry points to malloc. These will @@ -1247,19 +1247,19 @@ void * PyObject_Malloc(size_t n) { - return PyMem_MALLOC(n); + return PyMem_MALLOC(n); } void * PyObject_Realloc(void *p, size_t n) { - return PyMem_REALLOC(p, n); + return PyMem_REALLOC(p, n); } void PyObject_Free(void *p) { - PyMem_FREE(p); + PyMem_FREE(p); } #endif /* WITH_PYMALLOC */ @@ -1284,7 +1284,7 @@ #define _PYMALLOC_MEM_ID 'm' /* the PyMem_Malloc() API */ #define _PYMALLOC_OBJ_ID 'o' /* The PyObject_Malloc() API */ -static size_t serialno = 0; /* incremented on each debug {m,re}alloc */ +static size_t serialno = 0; /* incremented on each debug {m,re}alloc */ /* serialno is always incremented via calling this routine. The point is * to supply a single place to set a breakpoint. @@ -1292,7 +1292,7 @@ static void bumpserialno(void) { - ++serialno; + ++serialno; } #define SST SIZEOF_SIZE_T @@ -1301,13 +1301,13 @@ static size_t read_size_t(const void *p) { - const uchar *q = (const uchar *)p; - size_t result = *q++; - int i; - - for (i = SST; --i > 0; ++q) - result = (result << 8) | *q; - return result; + const uchar *q = (const uchar *)p; + size_t result = *q++; + int i; + + for (i = SST; --i > 0; ++q) + result = (result << 8) | *q; + return result; } /* Write n as a big-endian size_t, MSB at address p, LSB at @@ -1316,13 +1316,13 @@ static void write_size_t(void *p, size_t n) { - uchar *q = (uchar *)p + SST - 1; - int i; + uchar *q = (uchar *)p + SST - 1; + int i; - for (i = SST; --i >= 0; --q) { - *q = (uchar)(n & 0xff); - n >>= 8; - } + for (i = SST; --i >= 0; --q) { + *q = (uchar)(n & 0xff); + n >>= 8; + } } #ifdef Py_DEBUG @@ -1333,22 +1333,22 @@ static int pool_is_in_list(const poolp target, poolp list) { - poolp origlist = list; - assert(target != NULL); - if (list == NULL) - return 0; - do { - if (target == list) - return 1; - list = list->nextpool; - } while (list != NULL && list != origlist); - return 0; + poolp origlist = list; + assert(target != NULL); + if (list == NULL) + return 0; + do { + if (target == list) + return 1; + list = list->nextpool; + } while (list != NULL && list != origlist); + return 0; } #else #define pool_is_in_list(X, Y) 1 -#endif /* Py_DEBUG */ +#endif /* Py_DEBUG */ /* Let S = sizeof(size_t). The debug malloc asks for 4*S extra bytes and fills them with useful stuff, here calling the underlying malloc's result p: @@ -1378,39 +1378,39 @@ void * _PyMem_DebugMalloc(size_t nbytes) { - return _PyObject_DebugMallocApi(_PYMALLOC_MEM_ID, nbytes); + return _PyObject_DebugMallocApi(_PYMALLOC_MEM_ID, nbytes); } void * _PyMem_DebugRealloc(void *p, size_t nbytes) { - return _PyObject_DebugReallocApi(_PYMALLOC_MEM_ID, p, nbytes); + return _PyObject_DebugReallocApi(_PYMALLOC_MEM_ID, p, nbytes); } void _PyMem_DebugFree(void *p) { - _PyObject_DebugFreeApi(_PYMALLOC_MEM_ID, p); + _PyObject_DebugFreeApi(_PYMALLOC_MEM_ID, p); } /* debug replacements for the PyObject_* memory API */ void * _PyObject_DebugMalloc(size_t nbytes) { - return _PyObject_DebugMallocApi(_PYMALLOC_OBJ_ID, nbytes); + return _PyObject_DebugMallocApi(_PYMALLOC_OBJ_ID, nbytes); } void * _PyObject_DebugRealloc(void *p, size_t nbytes) { - return _PyObject_DebugReallocApi(_PYMALLOC_OBJ_ID, p, nbytes); + return _PyObject_DebugReallocApi(_PYMALLOC_OBJ_ID, p, nbytes); } void _PyObject_DebugFree(void *p) { - _PyObject_DebugFreeApi(_PYMALLOC_OBJ_ID, p); + _PyObject_DebugFreeApi(_PYMALLOC_OBJ_ID, p); } void _PyObject_DebugCheckAddress(const void *p) { - _PyObject_DebugCheckAddressApi(_PYMALLOC_OBJ_ID, p); + _PyObject_DebugCheckAddressApi(_PYMALLOC_OBJ_ID, p); } @@ -1418,34 +1418,34 @@ void * _PyObject_DebugMallocApi(char id, size_t nbytes) { - uchar *p; /* base address of malloc'ed block */ - uchar *tail; /* p + 2*SST + nbytes == pointer to tail pad bytes */ - size_t total; /* nbytes + 4*SST */ - - bumpserialno(); - total = nbytes + 4*SST; - if (total < nbytes) - /* overflow: can't represent total as a size_t */ - return NULL; - - p = (uchar *)PyObject_Malloc(total); - if (p == NULL) - return NULL; - - /* at p, write size (SST bytes), id (1 byte), pad (SST-1 bytes) */ - write_size_t(p, nbytes); - p[SST] = (uchar)id; - memset(p + SST + 1 , FORBIDDENBYTE, SST-1); - - if (nbytes > 0) - memset(p + 2*SST, CLEANBYTE, nbytes); - - /* at tail, write pad (SST bytes) and serialno (SST bytes) */ - tail = p + 2*SST + nbytes; - memset(tail, FORBIDDENBYTE, SST); - write_size_t(tail + SST, serialno); + uchar *p; /* base address of malloc'ed block */ + uchar *tail; /* p + 2*SST + nbytes == pointer to tail pad bytes */ + size_t total; /* nbytes + 4*SST */ + + bumpserialno(); + total = nbytes + 4*SST; + if (total < nbytes) + /* overflow: can't represent total as a size_t */ + return NULL; + + p = (uchar *)PyObject_Malloc(total); + if (p == NULL) + return NULL; + + /* at p, write size (SST bytes), id (1 byte), pad (SST-1 bytes) */ + write_size_t(p, nbytes); + p[SST] = (uchar)id; + memset(p + SST + 1 , FORBIDDENBYTE, SST-1); + + if (nbytes > 0) + memset(p + 2*SST, CLEANBYTE, nbytes); + + /* at tail, write pad (SST bytes) and serialno (SST bytes) */ + tail = p + 2*SST + nbytes; + memset(tail, FORBIDDENBYTE, SST); + write_size_t(tail + SST, serialno); - return p + 2*SST; + return p + 2*SST; } /* The debug free first checks the 2*SST bytes on each end for sanity (in @@ -1456,68 +1456,68 @@ void _PyObject_DebugFreeApi(char api, void *p) { - uchar *q = (uchar *)p - 2*SST; /* address returned from malloc */ - size_t nbytes; + uchar *q = (uchar *)p - 2*SST; /* address returned from malloc */ + size_t nbytes; - if (p == NULL) - return; - _PyObject_DebugCheckAddressApi(api, p); - nbytes = read_size_t(q); - nbytes += 4*SST; - if (nbytes > 0) - memset(q, DEADBYTE, nbytes); - PyObject_Free(q); + if (p == NULL) + return; + _PyObject_DebugCheckAddressApi(api, p); + nbytes = read_size_t(q); + nbytes += 4*SST; + if (nbytes > 0) + memset(q, DEADBYTE, nbytes); + PyObject_Free(q); } void * _PyObject_DebugReallocApi(char api, void *p, size_t nbytes) { - uchar *q = (uchar *)p; - uchar *tail; - size_t total; /* nbytes + 4*SST */ - size_t original_nbytes; - int i; - - if (p == NULL) - return _PyObject_DebugMallocApi(api, nbytes); - - _PyObject_DebugCheckAddressApi(api, p); - bumpserialno(); - original_nbytes = read_size_t(q - 2*SST); - total = nbytes + 4*SST; - if (total < nbytes) - /* overflow: can't represent total as a size_t */ - return NULL; - - if (nbytes < original_nbytes) { - /* shrinking: mark old extra memory dead */ - memset(q + nbytes, DEADBYTE, original_nbytes - nbytes + 2*SST); - } - - /* Resize and add decorations. We may get a new pointer here, in which - * case we didn't get the chance to mark the old memory with DEADBYTE, - * but we live with that. - */ - q = (uchar *)PyObject_Realloc(q - 2*SST, total); - if (q == NULL) - return NULL; - - write_size_t(q, nbytes); - assert(q[SST] == (uchar)api); - for (i = 1; i < SST; ++i) - assert(q[SST + i] == FORBIDDENBYTE); - q += 2*SST; - tail = q + nbytes; - memset(tail, FORBIDDENBYTE, SST); - write_size_t(tail + SST, serialno); - - if (nbytes > original_nbytes) { - /* growing: mark new extra memory clean */ - memset(q + original_nbytes, CLEANBYTE, - nbytes - original_nbytes); - } + uchar *q = (uchar *)p; + uchar *tail; + size_t total; /* nbytes + 4*SST */ + size_t original_nbytes; + int i; + + if (p == NULL) + return _PyObject_DebugMallocApi(api, nbytes); + + _PyObject_DebugCheckAddressApi(api, p); + bumpserialno(); + original_nbytes = read_size_t(q - 2*SST); + total = nbytes + 4*SST; + if (total < nbytes) + /* overflow: can't represent total as a size_t */ + return NULL; + + if (nbytes < original_nbytes) { + /* shrinking: mark old extra memory dead */ + memset(q + nbytes, DEADBYTE, original_nbytes - nbytes + 2*SST); + } + + /* Resize and add decorations. We may get a new pointer here, in which + * case we didn't get the chance to mark the old memory with DEADBYTE, + * but we live with that. + */ + q = (uchar *)PyObject_Realloc(q - 2*SST, total); + if (q == NULL) + return NULL; + + write_size_t(q, nbytes); + assert(q[SST] == (uchar)api); + for (i = 1; i < SST; ++i) + assert(q[SST + i] == FORBIDDENBYTE); + q += 2*SST; + tail = q + nbytes; + memset(tail, FORBIDDENBYTE, SST); + write_size_t(tail + SST, serialno); + + if (nbytes > original_nbytes) { + /* growing: mark new extra memory clean */ + memset(q + original_nbytes, CLEANBYTE, + nbytes - original_nbytes); + } - return q; + return q; } /* Check the forbidden bytes on both ends of the memory allocated for p. @@ -1528,192 +1528,192 @@ void _PyObject_DebugCheckAddressApi(char api, const void *p) { - const uchar *q = (const uchar *)p; - char msgbuf[64]; - char *msg; - size_t nbytes; - const uchar *tail; - int i; - char id; - - if (p == NULL) { - msg = "didn't expect a NULL pointer"; - goto error; - } - - /* Check the API id */ - id = (char)q[-SST]; - if (id != api) { - msg = msgbuf; - snprintf(msg, sizeof(msgbuf), "bad ID: Allocated using API '%c', verified using API '%c'", id, api); - msgbuf[sizeof(msgbuf)-1] = 0; - goto error; - } - - /* Check the stuff at the start of p first: if there's underwrite - * corruption, the number-of-bytes field may be nuts, and checking - * the tail could lead to a segfault then. - */ - for (i = SST-1; i >= 1; --i) { - if (*(q-i) != FORBIDDENBYTE) { - msg = "bad leading pad byte"; - goto error; - } - } - - nbytes = read_size_t(q - 2*SST); - tail = q + nbytes; - for (i = 0; i < SST; ++i) { - if (tail[i] != FORBIDDENBYTE) { - msg = "bad trailing pad byte"; - goto error; - } - } + const uchar *q = (const uchar *)p; + char msgbuf[64]; + char *msg; + size_t nbytes; + const uchar *tail; + int i; + char id; + + if (p == NULL) { + msg = "didn't expect a NULL pointer"; + goto error; + } + + /* Check the API id */ + id = (char)q[-SST]; + if (id != api) { + msg = msgbuf; + snprintf(msg, sizeof(msgbuf), "bad ID: Allocated using API '%c', verified using API '%c'", id, api); + msgbuf[sizeof(msgbuf)-1] = 0; + goto error; + } + + /* Check the stuff at the start of p first: if there's underwrite + * corruption, the number-of-bytes field may be nuts, and checking + * the tail could lead to a segfault then. + */ + for (i = SST-1; i >= 1; --i) { + if (*(q-i) != FORBIDDENBYTE) { + msg = "bad leading pad byte"; + goto error; + } + } + + nbytes = read_size_t(q - 2*SST); + tail = q + nbytes; + for (i = 0; i < SST; ++i) { + if (tail[i] != FORBIDDENBYTE) { + msg = "bad trailing pad byte"; + goto error; + } + } - return; + return; error: - _PyObject_DebugDumpAddress(p); - Py_FatalError(msg); + _PyObject_DebugDumpAddress(p); + Py_FatalError(msg); } /* Display info to stderr about the memory block at p. */ void _PyObject_DebugDumpAddress(const void *p) { - const uchar *q = (const uchar *)p; - const uchar *tail; - size_t nbytes, serial; - int i; - int ok; - char id; - - fprintf(stderr, "Debug memory block at address p=%p:", p); - if (p == NULL) { - fprintf(stderr, "\n"); - return; - } - id = (char)q[-SST]; - fprintf(stderr, " API '%c'\n", id); - - nbytes = read_size_t(q - 2*SST); - fprintf(stderr, " %" PY_FORMAT_SIZE_T "u bytes originally " - "requested\n", nbytes); - - /* In case this is nuts, check the leading pad bytes first. */ - fprintf(stderr, " The %d pad bytes at p-%d are ", SST-1, SST-1); - ok = 1; - for (i = 1; i <= SST-1; ++i) { - if (*(q-i) != FORBIDDENBYTE) { - ok = 0; - break; - } - } - if (ok) - fputs("FORBIDDENBYTE, as expected.\n", stderr); - else { - fprintf(stderr, "not all FORBIDDENBYTE (0x%02x):\n", - FORBIDDENBYTE); - for (i = SST-1; i >= 1; --i) { - const uchar byte = *(q-i); - fprintf(stderr, " at p-%d: 0x%02x", i, byte); - if (byte != FORBIDDENBYTE) - fputs(" *** OUCH", stderr); - fputc('\n', stderr); - } - - fputs(" Because memory is corrupted at the start, the " - "count of bytes requested\n" - " may be bogus, and checking the trailing pad " - "bytes may segfault.\n", stderr); - } - - tail = q + nbytes; - fprintf(stderr, " The %d pad bytes at tail=%p are ", SST, tail); - ok = 1; - for (i = 0; i < SST; ++i) { - if (tail[i] != FORBIDDENBYTE) { - ok = 0; - break; - } - } - if (ok) - fputs("FORBIDDENBYTE, as expected.\n", stderr); - else { - fprintf(stderr, "not all FORBIDDENBYTE (0x%02x):\n", - FORBIDDENBYTE); - for (i = 0; i < SST; ++i) { - const uchar byte = tail[i]; - fprintf(stderr, " at tail+%d: 0x%02x", - i, byte); - if (byte != FORBIDDENBYTE) - fputs(" *** OUCH", stderr); - fputc('\n', stderr); - } - } - - serial = read_size_t(tail + SST); - fprintf(stderr, " The block was made by call #%" PY_FORMAT_SIZE_T - "u to debug malloc/realloc.\n", serial); - - if (nbytes > 0) { - i = 0; - fputs(" Data at p:", stderr); - /* print up to 8 bytes at the start */ - while (q < tail && i < 8) { - fprintf(stderr, " %02x", *q); - ++i; - ++q; - } - /* and up to 8 at the end */ - if (q < tail) { - if (tail - q > 8) { - fputs(" ...", stderr); - q = tail - 8; - } - while (q < tail) { - fprintf(stderr, " %02x", *q); - ++q; - } - } - fputc('\n', stderr); - } + const uchar *q = (const uchar *)p; + const uchar *tail; + size_t nbytes, serial; + int i; + int ok; + char id; + + fprintf(stderr, "Debug memory block at address p=%p:", p); + if (p == NULL) { + fprintf(stderr, "\n"); + return; + } + id = (char)q[-SST]; + fprintf(stderr, " API '%c'\n", id); + + nbytes = read_size_t(q - 2*SST); + fprintf(stderr, " %" PY_FORMAT_SIZE_T "u bytes originally " + "requested\n", nbytes); + + /* In case this is nuts, check the leading pad bytes first. */ + fprintf(stderr, " The %d pad bytes at p-%d are ", SST-1, SST-1); + ok = 1; + for (i = 1; i <= SST-1; ++i) { + if (*(q-i) != FORBIDDENBYTE) { + ok = 0; + break; + } + } + if (ok) + fputs("FORBIDDENBYTE, as expected.\n", stderr); + else { + fprintf(stderr, "not all FORBIDDENBYTE (0x%02x):\n", + FORBIDDENBYTE); + for (i = SST-1; i >= 1; --i) { + const uchar byte = *(q-i); + fprintf(stderr, " at p-%d: 0x%02x", i, byte); + if (byte != FORBIDDENBYTE) + fputs(" *** OUCH", stderr); + fputc('\n', stderr); + } + + fputs(" Because memory is corrupted at the start, the " + "count of bytes requested\n" + " may be bogus, and checking the trailing pad " + "bytes may segfault.\n", stderr); + } + + tail = q + nbytes; + fprintf(stderr, " The %d pad bytes at tail=%p are ", SST, tail); + ok = 1; + for (i = 0; i < SST; ++i) { + if (tail[i] != FORBIDDENBYTE) { + ok = 0; + break; + } + } + if (ok) + fputs("FORBIDDENBYTE, as expected.\n", stderr); + else { + fprintf(stderr, "not all FORBIDDENBYTE (0x%02x):\n", + FORBIDDENBYTE); + for (i = 0; i < SST; ++i) { + const uchar byte = tail[i]; + fprintf(stderr, " at tail+%d: 0x%02x", + i, byte); + if (byte != FORBIDDENBYTE) + fputs(" *** OUCH", stderr); + fputc('\n', stderr); + } + } + + serial = read_size_t(tail + SST); + fprintf(stderr, " The block was made by call #%" PY_FORMAT_SIZE_T + "u to debug malloc/realloc.\n", serial); + + if (nbytes > 0) { + i = 0; + fputs(" Data at p:", stderr); + /* print up to 8 bytes at the start */ + while (q < tail && i < 8) { + fprintf(stderr, " %02x", *q); + ++i; + ++q; + } + /* and up to 8 at the end */ + if (q < tail) { + if (tail - q > 8) { + fputs(" ...", stderr); + q = tail - 8; + } + while (q < tail) { + fprintf(stderr, " %02x", *q); + ++q; + } + } + fputc('\n', stderr); + } } static size_t printone(const char* msg, size_t value) { - int i, k; - char buf[100]; - size_t origvalue = value; - - fputs(msg, stderr); - for (i = (int)strlen(msg); i < 35; ++i) - fputc(' ', stderr); - fputc('=', stderr); - - /* Write the value with commas. */ - i = 22; - buf[i--] = '\0'; - buf[i--] = '\n'; - k = 3; - do { - size_t nextvalue = value / 10; - uint digit = (uint)(value - nextvalue * 10); - value = nextvalue; - buf[i--] = (char)(digit + '0'); - --k; - if (k == 0 && value && i >= 0) { - k = 3; - buf[i--] = ','; - } - } while (value && i >= 0); - - while (i >= 0) - buf[i--] = ' '; - fputs(buf, stderr); + int i, k; + char buf[100]; + size_t origvalue = value; + + fputs(msg, stderr); + for (i = (int)strlen(msg); i < 35; ++i) + fputc(' ', stderr); + fputc('=', stderr); + + /* Write the value with commas. */ + i = 22; + buf[i--] = '\0'; + buf[i--] = '\n'; + k = 3; + do { + size_t nextvalue = value / 10; + uint digit = (uint)(value - nextvalue * 10); + value = nextvalue; + buf[i--] = (char)(digit + '0'); + --k; + if (k == 0 && value && i >= 0) { + k = 3; + buf[i--] = ','; + } + } while (value && i >= 0); + + while (i >= 0) + buf[i--] = ' '; + fputs(buf, stderr); - return origvalue; + return origvalue; } /* Print summary info to stderr about the state of pymalloc's structures. @@ -1723,142 +1723,142 @@ void _PyObject_DebugMallocStats(void) { - uint i; - const uint numclasses = SMALL_REQUEST_THRESHOLD >> ALIGNMENT_SHIFT; - /* # of pools, allocated blocks, and free blocks per class index */ - size_t numpools[SMALL_REQUEST_THRESHOLD >> ALIGNMENT_SHIFT]; - size_t numblocks[SMALL_REQUEST_THRESHOLD >> ALIGNMENT_SHIFT]; - size_t numfreeblocks[SMALL_REQUEST_THRESHOLD >> ALIGNMENT_SHIFT]; - /* total # of allocated bytes in used and full pools */ - size_t allocated_bytes = 0; - /* total # of available bytes in used pools */ - size_t available_bytes = 0; - /* # of free pools + pools not yet carved out of current arena */ - uint numfreepools = 0; - /* # of bytes for arena alignment padding */ - size_t arena_alignment = 0; - /* # of bytes in used and full pools used for pool_headers */ - size_t pool_header_bytes = 0; - /* # of bytes in used and full pools wasted due to quantization, - * i.e. the necessarily leftover space at the ends of used and - * full pools. - */ - size_t quantization = 0; - /* # of arenas actually allocated. */ - size_t narenas = 0; - /* running total -- should equal narenas * ARENA_SIZE */ - size_t total; - char buf[128]; - - fprintf(stderr, "Small block threshold = %d, in %u size classes.\n", - SMALL_REQUEST_THRESHOLD, numclasses); - - for (i = 0; i < numclasses; ++i) - numpools[i] = numblocks[i] = numfreeblocks[i] = 0; - - /* Because full pools aren't linked to from anything, it's easiest - * to march over all the arenas. If we're lucky, most of the memory - * will be living in full pools -- would be a shame to miss them. - */ - for (i = 0; i < maxarenas; ++i) { - uint poolsinarena; - uint j; - uptr base = arenas[i].address; - - /* Skip arenas which are not allocated. */ - if (arenas[i].address == (uptr)NULL) - continue; - narenas += 1; - - poolsinarena = arenas[i].ntotalpools; - numfreepools += arenas[i].nfreepools; - - /* round up to pool alignment */ - if (base & (uptr)POOL_SIZE_MASK) { - arena_alignment += POOL_SIZE; - base &= ~(uptr)POOL_SIZE_MASK; - base += POOL_SIZE; - } - - /* visit every pool in the arena */ - assert(base <= (uptr) arenas[i].pool_address); - for (j = 0; - base < (uptr) arenas[i].pool_address; - ++j, base += POOL_SIZE) { - poolp p = (poolp)base; - const uint sz = p->szidx; - uint freeblocks; - - if (p->ref.count == 0) { - /* currently unused */ - assert(pool_is_in_list(p, arenas[i].freepools)); - continue; - } - ++numpools[sz]; - numblocks[sz] += p->ref.count; - freeblocks = NUMBLOCKS(sz) - p->ref.count; - numfreeblocks[sz] += freeblocks; + uint i; + const uint numclasses = SMALL_REQUEST_THRESHOLD >> ALIGNMENT_SHIFT; + /* # of pools, allocated blocks, and free blocks per class index */ + size_t numpools[SMALL_REQUEST_THRESHOLD >> ALIGNMENT_SHIFT]; + size_t numblocks[SMALL_REQUEST_THRESHOLD >> ALIGNMENT_SHIFT]; + size_t numfreeblocks[SMALL_REQUEST_THRESHOLD >> ALIGNMENT_SHIFT]; + /* total # of allocated bytes in used and full pools */ + size_t allocated_bytes = 0; + /* total # of available bytes in used pools */ + size_t available_bytes = 0; + /* # of free pools + pools not yet carved out of current arena */ + uint numfreepools = 0; + /* # of bytes for arena alignment padding */ + size_t arena_alignment = 0; + /* # of bytes in used and full pools used for pool_headers */ + size_t pool_header_bytes = 0; + /* # of bytes in used and full pools wasted due to quantization, + * i.e. the necessarily leftover space at the ends of used and + * full pools. + */ + size_t quantization = 0; + /* # of arenas actually allocated. */ + size_t narenas = 0; + /* running total -- should equal narenas * ARENA_SIZE */ + size_t total; + char buf[128]; + + fprintf(stderr, "Small block threshold = %d, in %u size classes.\n", + SMALL_REQUEST_THRESHOLD, numclasses); + + for (i = 0; i < numclasses; ++i) + numpools[i] = numblocks[i] = numfreeblocks[i] = 0; + + /* Because full pools aren't linked to from anything, it's easiest + * to march over all the arenas. If we're lucky, most of the memory + * will be living in full pools -- would be a shame to miss them. + */ + for (i = 0; i < maxarenas; ++i) { + uint poolsinarena; + uint j; + uptr base = arenas[i].address; + + /* Skip arenas which are not allocated. */ + if (arenas[i].address == (uptr)NULL) + continue; + narenas += 1; + + poolsinarena = arenas[i].ntotalpools; + numfreepools += arenas[i].nfreepools; + + /* round up to pool alignment */ + if (base & (uptr)POOL_SIZE_MASK) { + arena_alignment += POOL_SIZE; + base &= ~(uptr)POOL_SIZE_MASK; + base += POOL_SIZE; + } + + /* visit every pool in the arena */ + assert(base <= (uptr) arenas[i].pool_address); + for (j = 0; + base < (uptr) arenas[i].pool_address; + ++j, base += POOL_SIZE) { + poolp p = (poolp)base; + const uint sz = p->szidx; + uint freeblocks; + + if (p->ref.count == 0) { + /* currently unused */ + assert(pool_is_in_list(p, arenas[i].freepools)); + continue; + } + ++numpools[sz]; + numblocks[sz] += p->ref.count; + freeblocks = NUMBLOCKS(sz) - p->ref.count; + numfreeblocks[sz] += freeblocks; #ifdef Py_DEBUG - if (freeblocks > 0) - assert(pool_is_in_list(p, usedpools[sz + sz])); + if (freeblocks > 0) + assert(pool_is_in_list(p, usedpools[sz + sz])); #endif - } - } - assert(narenas == narenas_currently_allocated); - - fputc('\n', stderr); - fputs("class size num pools blocks in use avail blocks\n" - "----- ---- --------- ------------- ------------\n", - stderr); - - for (i = 0; i < numclasses; ++i) { - size_t p = numpools[i]; - size_t b = numblocks[i]; - size_t f = numfreeblocks[i]; - uint size = INDEX2SIZE(i); - if (p == 0) { - assert(b == 0 && f == 0); - continue; - } - fprintf(stderr, "%5u %6u " - "%11" PY_FORMAT_SIZE_T "u " - "%15" PY_FORMAT_SIZE_T "u " - "%13" PY_FORMAT_SIZE_T "u\n", - i, size, p, b, f); - allocated_bytes += b * size; - available_bytes += f * size; - pool_header_bytes += p * POOL_OVERHEAD; - quantization += p * ((POOL_SIZE - POOL_OVERHEAD) % size); - } - fputc('\n', stderr); - (void)printone("# times object malloc called", serialno); - - (void)printone("# arenas allocated total", ntimes_arena_allocated); - (void)printone("# arenas reclaimed", ntimes_arena_allocated - narenas); - (void)printone("# arenas highwater mark", narenas_highwater); - (void)printone("# arenas allocated current", narenas); - - PyOS_snprintf(buf, sizeof(buf), - "%" PY_FORMAT_SIZE_T "u arenas * %d bytes/arena", - narenas, ARENA_SIZE); - (void)printone(buf, narenas * ARENA_SIZE); - - fputc('\n', stderr); - - total = printone("# bytes in allocated blocks", allocated_bytes); - total += printone("# bytes in available blocks", available_bytes); - - PyOS_snprintf(buf, sizeof(buf), - "%u unused pools * %d bytes", numfreepools, POOL_SIZE); - total += printone(buf, (size_t)numfreepools * POOL_SIZE); - - total += printone("# bytes lost to pool headers", pool_header_bytes); - total += printone("# bytes lost to quantization", quantization); - total += printone("# bytes lost to arena alignment", arena_alignment); - (void)printone("Total", total); + } + } + assert(narenas == narenas_currently_allocated); + + fputc('\n', stderr); + fputs("class size num pools blocks in use avail blocks\n" + "----- ---- --------- ------------- ------------\n", + stderr); + + for (i = 0; i < numclasses; ++i) { + size_t p = numpools[i]; + size_t b = numblocks[i]; + size_t f = numfreeblocks[i]; + uint size = INDEX2SIZE(i); + if (p == 0) { + assert(b == 0 && f == 0); + continue; + } + fprintf(stderr, "%5u %6u " + "%11" PY_FORMAT_SIZE_T "u " + "%15" PY_FORMAT_SIZE_T "u " + "%13" PY_FORMAT_SIZE_T "u\n", + i, size, p, b, f); + allocated_bytes += b * size; + available_bytes += f * size; + pool_header_bytes += p * POOL_OVERHEAD; + quantization += p * ((POOL_SIZE - POOL_OVERHEAD) % size); + } + fputc('\n', stderr); + (void)printone("# times object malloc called", serialno); + + (void)printone("# arenas allocated total", ntimes_arena_allocated); + (void)printone("# arenas reclaimed", ntimes_arena_allocated - narenas); + (void)printone("# arenas highwater mark", narenas_highwater); + (void)printone("# arenas allocated current", narenas); + + PyOS_snprintf(buf, sizeof(buf), + "%" PY_FORMAT_SIZE_T "u arenas * %d bytes/arena", + narenas, ARENA_SIZE); + (void)printone(buf, narenas * ARENA_SIZE); + + fputc('\n', stderr); + + total = printone("# bytes in allocated blocks", allocated_bytes); + total += printone("# bytes in available blocks", available_bytes); + + PyOS_snprintf(buf, sizeof(buf), + "%u unused pools * %d bytes", numfreepools, POOL_SIZE); + total += printone(buf, (size_t)numfreepools * POOL_SIZE); + + total += printone("# bytes lost to pool headers", pool_header_bytes); + total += printone("# bytes lost to quantization", quantization); + total += printone("# bytes lost to arena alignment", arena_alignment); + (void)printone("Total", total); } -#endif /* PYMALLOC_DEBUG */ +#endif /* PYMALLOC_DEBUG */ #ifdef Py_USING_MEMORY_DEBUGGER /* Make this function last so gcc won't inline it since the definition is @@ -1867,8 +1867,8 @@ int Py_ADDRESS_IN_RANGE(void *P, poolp pool) { - return pool->arenaindex < maxarenas && - (uptr)P - arenas[pool->arenaindex].address < (uptr)ARENA_SIZE && - arenas[pool->arenaindex].address != 0; + return pool->arenaindex < maxarenas && + (uptr)P - arenas[pool->arenaindex].address < (uptr)ARENA_SIZE && + arenas[pool->arenaindex].address != 0; } #endif Modified: python/branches/py3k-jit/Objects/rangeobject.c ============================================================================== --- python/branches/py3k-jit/Objects/rangeobject.c (original) +++ python/branches/py3k-jit/Objects/rangeobject.c Mon May 10 23:55:43 2010 @@ -17,7 +17,7 @@ } rangeobject; /* Helper function for validating step. Always returns a new reference or - NULL on error. + NULL on error. */ static PyObject * validate_step(PyObject *step) @@ -269,7 +269,7 @@ static PyObject * range_reduce(rangeobject *r, PyObject *args) { - return Py_BuildValue("(O(OOO))", Py_TYPE(r), + return Py_BuildValue("(O(OOO))", Py_TYPE(r), r->start, r->stop, r->step); } @@ -328,11 +328,11 @@ } static PySequenceMethods range_as_sequence = { - (lenfunc)range_length, /* sq_length */ - 0, /* sq_concat */ - 0, /* sq_repeat */ + (lenfunc)range_length, /* sq_length */ + 0, /* sq_concat */ + 0, /* sq_repeat */ (ssizeargfunc)range_item, /* sq_item */ - 0, /* sq_slice */ + 0, /* sq_slice */ 0, /* sq_ass_item */ 0, /* sq_ass_slice */ (objobjproc)range_contains, /* sq_contains */ @@ -345,51 +345,51 @@ "Returns a reverse iterator."); static PyMethodDef range_methods[] = { - {"__reversed__", (PyCFunction)range_reverse, METH_NOARGS, - reverse_doc}, - {"__reduce__", (PyCFunction)range_reduce, METH_VARARGS}, - {NULL, NULL} /* sentinel */ + {"__reversed__", (PyCFunction)range_reverse, METH_NOARGS, + reverse_doc}, + {"__reduce__", (PyCFunction)range_reduce, METH_VARARGS}, + {NULL, NULL} /* sentinel */ }; PyTypeObject PyRange_Type = { - PyVarObject_HEAD_INIT(&PyType_Type, 0) - "range", /* Name of this type */ - sizeof(rangeobject), /* Basic object size */ - 0, /* Item size for varobject */ - (destructor)range_dealloc, /* tp_dealloc */ - 0, /* tp_print */ - 0, /* tp_getattr */ - 0, /* tp_setattr */ - 0, /* tp_reserved */ - (reprfunc)range_repr, /* tp_repr */ - 0, /* tp_as_number */ - &range_as_sequence, /* tp_as_sequence */ - 0, /* tp_as_mapping */ - 0, /* tp_hash */ - 0, /* tp_call */ - 0, /* tp_str */ - PyObject_GenericGetAttr, /* tp_getattro */ - 0, /* tp_setattro */ - 0, /* tp_as_buffer */ - Py_TPFLAGS_DEFAULT, /* tp_flags */ - range_doc, /* tp_doc */ - 0, /* tp_traverse */ - 0, /* tp_clear */ - 0, /* tp_richcompare */ - 0, /* tp_weaklistoffset */ - range_iter, /* tp_iter */ - 0, /* tp_iternext */ - range_methods, /* tp_methods */ - 0, /* tp_members */ - 0, /* tp_getset */ - 0, /* tp_base */ - 0, /* tp_dict */ - 0, /* tp_descr_get */ - 0, /* tp_descr_set */ - 0, /* tp_dictoffset */ - 0, /* tp_init */ - 0, /* tp_alloc */ - range_new, /* tp_new */ + PyVarObject_HEAD_INIT(&PyType_Type, 0) + "range", /* Name of this type */ + sizeof(rangeobject), /* Basic object size */ + 0, /* Item size for varobject */ + (destructor)range_dealloc, /* tp_dealloc */ + 0, /* tp_print */ + 0, /* tp_getattr */ + 0, /* tp_setattr */ + 0, /* tp_reserved */ + (reprfunc)range_repr, /* tp_repr */ + 0, /* tp_as_number */ + &range_as_sequence, /* tp_as_sequence */ + 0, /* tp_as_mapping */ + 0, /* tp_hash */ + 0, /* tp_call */ + 0, /* tp_str */ + PyObject_GenericGetAttr, /* tp_getattro */ + 0, /* tp_setattro */ + 0, /* tp_as_buffer */ + Py_TPFLAGS_DEFAULT, /* tp_flags */ + range_doc, /* tp_doc */ + 0, /* tp_traverse */ + 0, /* tp_clear */ + 0, /* tp_richcompare */ + 0, /* tp_weaklistoffset */ + range_iter, /* tp_iter */ + 0, /* tp_iternext */ + range_methods, /* tp_methods */ + 0, /* tp_members */ + 0, /* tp_getset */ + 0, /* tp_base */ + 0, /* tp_dict */ + 0, /* tp_descr_get */ + 0, /* tp_descr_set */ + 0, /* tp_dictoffset */ + 0, /* tp_init */ + 0, /* tp_alloc */ + range_new, /* tp_new */ }; /*********************** range Iterator **************************/ @@ -400,18 +400,18 @@ */ typedef struct { - PyObject_HEAD - long index; - long start; - long step; - long len; + PyObject_HEAD + long index; + long start; + long step; + long len; } rangeiterobject; static PyObject * rangeiter_next(rangeiterobject *r) { if (r->index < r->len) - /* cast to unsigned to avoid possible signed overflow + /* cast to unsigned to avoid possible signed overflow in intermediate calculations. */ return PyLong_FromLong((long)(r->start + (unsigned long)(r->index++) * r->step)); @@ -445,50 +445,50 @@ static PyMethodDef rangeiter_methods[] = { {"__length_hint__", (PyCFunction)rangeiter_len, METH_NOARGS, - length_hint_doc}, - {NULL, NULL} /* sentinel */ + length_hint_doc}, + {NULL, NULL} /* sentinel */ }; PyTypeObject PyRangeIter_Type = { - PyVarObject_HEAD_INIT(&PyType_Type, 0) - "range_iterator", /* tp_name */ - sizeof(rangeiterobject), /* tp_basicsize */ - 0, /* tp_itemsize */ - /* methods */ - (destructor)PyObject_Del, /* 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, /* tp_flags */ - 0, /* tp_doc */ - 0, /* tp_traverse */ - 0, /* tp_clear */ - 0, /* tp_richcompare */ - 0, /* tp_weaklistoffset */ - PyObject_SelfIter, /* tp_iter */ - (iternextfunc)rangeiter_next, /* tp_iternext */ - rangeiter_methods, /* tp_methods */ - 0, /* tp_members */ - 0, /* tp_getset */ - 0, /* tp_base */ - 0, /* tp_dict */ - 0, /* tp_descr_get */ - 0, /* tp_descr_set */ - 0, /* tp_dictoffset */ - 0, /* tp_init */ - 0, /* tp_alloc */ - rangeiter_new, /* tp_new */ + PyVarObject_HEAD_INIT(&PyType_Type, 0) + "range_iterator", /* tp_name */ + sizeof(rangeiterobject), /* tp_basicsize */ + 0, /* tp_itemsize */ + /* methods */ + (destructor)PyObject_Del, /* 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, /* tp_flags */ + 0, /* tp_doc */ + 0, /* tp_traverse */ + 0, /* tp_clear */ + 0, /* tp_richcompare */ + 0, /* tp_weaklistoffset */ + PyObject_SelfIter, /* tp_iter */ + (iternextfunc)rangeiter_next, /* tp_iternext */ + rangeiter_methods, /* tp_methods */ + 0, /* tp_members */ + 0, /* tp_getset */ + 0, /* tp_base */ + 0, /* tp_dict */ + 0, /* tp_descr_get */ + 0, /* tp_descr_set */ + 0, /* tp_dictoffset */ + 0, /* tp_init */ + 0, /* tp_alloc */ + rangeiter_new, /* tp_new */ }; /* Return number of items in range (lo, hi, step). step != 0 @@ -560,8 +560,8 @@ static PyMethodDef longrangeiter_methods[] = { {"__length_hint__", (PyCFunction)longrangeiter_len, METH_NOARGS, - length_hint_doc}, - {NULL, NULL} /* sentinel */ + length_hint_doc}, + {NULL, NULL} /* sentinel */ }; static void @@ -610,36 +610,36 @@ } PyTypeObject PyLongRangeIter_Type = { - PyVarObject_HEAD_INIT(&PyType_Type, 0) - "longrange_iterator", /* tp_name */ - sizeof(longrangeiterobject), /* tp_basicsize */ - 0, /* tp_itemsize */ - /* methods */ - (destructor)longrangeiter_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, /* tp_flags */ - 0, /* tp_doc */ - 0, /* tp_traverse */ - 0, /* tp_clear */ - 0, /* tp_richcompare */ - 0, /* tp_weaklistoffset */ - PyObject_SelfIter, /* tp_iter */ - (iternextfunc)longrangeiter_next, /* tp_iternext */ - longrangeiter_methods, /* tp_methods */ - 0, + PyVarObject_HEAD_INIT(&PyType_Type, 0) + "longrange_iterator", /* tp_name */ + sizeof(longrangeiterobject), /* tp_basicsize */ + 0, /* tp_itemsize */ + /* methods */ + (destructor)longrangeiter_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, /* tp_flags */ + 0, /* tp_doc */ + 0, /* tp_traverse */ + 0, /* tp_clear */ + 0, /* tp_richcompare */ + 0, /* tp_weaklistoffset */ + PyObject_SelfIter, /* tp_iter */ + (iternextfunc)longrangeiter_next, /* tp_iternext */ + longrangeiter_methods, /* tp_methods */ + 0, }; static PyObject * Modified: python/branches/py3k-jit/Objects/setobject.c ============================================================================== --- python/branches/py3k-jit/Objects/setobject.c (original) +++ python/branches/py3k-jit/Objects/setobject.c Mon May 10 23:55:43 2010 @@ -1,5 +1,5 @@ -/* set object implementation +/* set object implementation Written and maintained by Raymond D. Hettinger Derived from Lib/sets.py and Objects/dictobject.c. @@ -17,12 +17,12 @@ static void set_key_error(PyObject *arg) { - PyObject *tup; - tup = PyTuple_Pack(1, arg); - if (!tup) - return; /* caller will expect error to be set anyway */ - PyErr_SetObject(PyExc_KeyError, tup); - Py_DECREF(tup); + PyObject *tup; + tup = PyTuple_Pack(1, arg); + if (!tup) + return; /* caller will expect error to be set anyway */ + PyErr_SetObject(PyExc_KeyError, tup); + Py_DECREF(tup); } /* This must be >= 1. */ @@ -35,20 +35,20 @@ PyObject * _PySet_Dummy(void) { - return dummy; + return dummy; } #endif -#define INIT_NONZERO_SET_SLOTS(so) do { \ - (so)->table = (so)->smalltable; \ - (so)->mask = PySet_MINSIZE - 1; \ - (so)->hash = -1; \ +#define INIT_NONZERO_SET_SLOTS(so) do { \ + (so)->table = (so)->smalltable; \ + (so)->mask = PySet_MINSIZE - 1; \ + (so)->hash = -1; \ } while(0) -#define EMPTY_TO_MINSIZE(so) do { \ - memset((so)->smalltable, 0, sizeof((so)->smalltable)); \ - (so)->used = (so)->fill = 0; \ - INIT_NONZERO_SET_SLOTS(so); \ +#define EMPTY_TO_MINSIZE(so) do { \ + memset((so)->smalltable, 0, sizeof((so)->smalltable)); \ + (so)->used = (so)->fill = 0; \ + INIT_NONZERO_SET_SLOTS(so); \ } while(0) /* Reuse scheme to save calls to malloc, free, and memset */ @@ -77,78 +77,78 @@ static setentry * set_lookkey(PySetObject *so, PyObject *key, register long hash) { - register Py_ssize_t i; - register size_t perturb; - register setentry *freeslot; - register size_t mask = so->mask; - setentry *table = so->table; - register setentry *entry; - register int cmp; - PyObject *startkey; - - i = hash & mask; - entry = &table[i]; - if (entry->key == NULL || entry->key == key) - return entry; - - if (entry->key == dummy) - freeslot = entry; - else { - if (entry->hash == hash) { - startkey = entry->key; - Py_INCREF(startkey); - cmp = PyObject_RichCompareBool(startkey, key, Py_EQ); - Py_DECREF(startkey); - if (cmp < 0) - return NULL; - if (table == so->table && entry->key == startkey) { - if (cmp > 0) - return entry; - } - else { - /* The compare did major nasty stuff to the - * set: start over. - */ - return set_lookkey(so, key, hash); - } - } - freeslot = NULL; - } - - /* In the loop, key == dummy is by far (factor of 100s) the - least likely outcome, so test for that last. */ - for (perturb = hash; ; perturb >>= PERTURB_SHIFT) { - i = (i << 2) + i + perturb + 1; - entry = &table[i & mask]; - if (entry->key == NULL) { - if (freeslot != NULL) - entry = freeslot; - break; - } - if (entry->key == key) - break; - if (entry->hash == hash && entry->key != dummy) { - startkey = entry->key; - Py_INCREF(startkey); - cmp = PyObject_RichCompareBool(startkey, key, Py_EQ); - Py_DECREF(startkey); - if (cmp < 0) - return NULL; - if (table == so->table && entry->key == startkey) { - if (cmp > 0) - break; - } - else { - /* The compare did major nasty stuff to the - * set: start over. - */ - return set_lookkey(so, key, hash); - } - } - else if (entry->key == dummy && freeslot == NULL) - freeslot = entry; - } - return entry; + register Py_ssize_t i; + register size_t perturb; + register setentry *freeslot; + register size_t mask = so->mask; + setentry *table = so->table; + register setentry *entry; + register int cmp; + PyObject *startkey; + + i = hash & mask; + entry = &table[i]; + if (entry->key == NULL || entry->key == key) + return entry; + + if (entry->key == dummy) + freeslot = entry; + else { + if (entry->hash == hash) { + startkey = entry->key; + Py_INCREF(startkey); + cmp = PyObject_RichCompareBool(startkey, key, Py_EQ); + Py_DECREF(startkey); + if (cmp < 0) + return NULL; + if (table == so->table && entry->key == startkey) { + if (cmp > 0) + return entry; + } + else { + /* The compare did major nasty stuff to the + * set: start over. + */ + return set_lookkey(so, key, hash); + } + } + freeslot = NULL; + } + + /* In the loop, key == dummy is by far (factor of 100s) the + least likely outcome, so test for that last. */ + for (perturb = hash; ; perturb >>= PERTURB_SHIFT) { + i = (i << 2) + i + perturb + 1; + entry = &table[i & mask]; + if (entry->key == NULL) { + if (freeslot != NULL) + entry = freeslot; + break; + } + if (entry->key == key) + break; + if (entry->hash == hash && entry->key != dummy) { + startkey = entry->key; + Py_INCREF(startkey); + cmp = PyObject_RichCompareBool(startkey, key, Py_EQ); + Py_DECREF(startkey); + if (cmp < 0) + return NULL; + if (table == so->table && entry->key == startkey) { + if (cmp > 0) + break; + } + else { + /* The compare did major nasty stuff to the + * set: start over. + */ + return set_lookkey(so, key, hash); + } + } + else if (entry->key == dummy && freeslot == NULL) + freeslot = entry; + } + return entry; } /* @@ -159,50 +159,50 @@ static setentry * set_lookkey_unicode(PySetObject *so, PyObject *key, register long hash) { - register Py_ssize_t i; - register size_t perturb; - register setentry *freeslot; - register size_t mask = so->mask; - setentry *table = so->table; - register setentry *entry; - - /* Make sure this function doesn't have to handle non-unicode keys, - including subclasses of str; e.g., one reason to subclass - strings is to override __eq__, and for speed we don't cater to - that here. */ - if (!PyUnicode_CheckExact(key)) { - so->lookup = set_lookkey; - return set_lookkey(so, key, hash); - } - i = hash & mask; - entry = &table[i]; - if (entry->key == NULL || entry->key == key) - return entry; - if (entry->key == dummy) - freeslot = entry; - else { - if (entry->hash == hash && unicode_eq(entry->key, key)) - return entry; - freeslot = NULL; - } - - /* In the loop, key == dummy is by far (factor of 100s) the - least likely outcome, so test for that last. */ - for (perturb = hash; ; perturb >>= PERTURB_SHIFT) { - i = (i << 2) + i + perturb + 1; - entry = &table[i & mask]; - if (entry->key == NULL) - return freeslot == NULL ? entry : freeslot; - if (entry->key == key - || (entry->hash == hash - && entry->key != dummy - && unicode_eq(entry->key, key))) - return entry; - if (entry->key == dummy && freeslot == NULL) - freeslot = entry; - } - assert(0); /* NOT REACHED */ - return 0; + register Py_ssize_t i; + register size_t perturb; + register setentry *freeslot; + register size_t mask = so->mask; + setentry *table = so->table; + register setentry *entry; + + /* Make sure this function doesn't have to handle non-unicode keys, + including subclasses of str; e.g., one reason to subclass + strings is to override __eq__, and for speed we don't cater to + that here. */ + if (!PyUnicode_CheckExact(key)) { + so->lookup = set_lookkey; + return set_lookkey(so, key, hash); + } + i = hash & mask; + entry = &table[i]; + if (entry->key == NULL || entry->key == key) + return entry; + if (entry->key == dummy) + freeslot = entry; + else { + if (entry->hash == hash && unicode_eq(entry->key, key)) + return entry; + freeslot = NULL; + } + + /* In the loop, key == dummy is by far (factor of 100s) the + least likely outcome, so test for that last. */ + for (perturb = hash; ; perturb >>= PERTURB_SHIFT) { + i = (i << 2) + i + perturb + 1; + entry = &table[i & mask]; + if (entry->key == NULL) + return freeslot == NULL ? entry : freeslot; + if (entry->key == key + || (entry->hash == hash + && entry->key != dummy + && unicode_eq(entry->key, key))) + return entry; + if (entry->key == dummy && freeslot == NULL) + freeslot = entry; + } + assert(0); /* NOT REACHED */ + return 0; } /* @@ -213,30 +213,30 @@ static int set_insert_key(register PySetObject *so, PyObject *key, long hash) { - register setentry *entry; - typedef setentry *(*lookupfunc)(PySetObject *, PyObject *, long); + register setentry *entry; + typedef setentry *(*lookupfunc)(PySetObject *, PyObject *, long); - assert(so->lookup != NULL); - entry = so->lookup(so, key, hash); - if (entry == NULL) - return -1; - if (entry->key == NULL) { - /* UNUSED */ - so->fill++; - entry->key = key; - entry->hash = hash; - so->used++; - } else if (entry->key == dummy) { - /* DUMMY */ - entry->key = key; - entry->hash = hash; - so->used++; - Py_DECREF(dummy); - } else { - /* ACTIVE */ - Py_DECREF(key); - } - return 0; + assert(so->lookup != NULL); + entry = so->lookup(so, key, hash); + if (entry == NULL) + return -1; + if (entry->key == NULL) { + /* UNUSED */ + so->fill++; + entry->key = key; + entry->hash = hash; + so->used++; + } else if (entry->key == dummy) { + /* DUMMY */ + entry->key = key; + entry->hash = hash; + so->used++; + Py_DECREF(dummy); + } else { + /* ACTIVE */ + Py_DECREF(key); + } + return 0; } /* @@ -250,22 +250,22 @@ static void set_insert_clean(register PySetObject *so, PyObject *key, long hash) { - register size_t i; - register size_t perturb; - register size_t mask = (size_t)so->mask; - setentry *table = so->table; - register setentry *entry; - - i = hash & mask; - entry = &table[i]; - for (perturb = hash; entry->key != NULL; perturb >>= PERTURB_SHIFT) { - i = (i << 2) + i + perturb + 1; - entry = &table[i & mask]; - } - so->fill++; - entry->key = key; - entry->hash = hash; - so->used++; + register size_t i; + register size_t perturb; + register size_t mask = (size_t)so->mask; + setentry *table = so->table; + register setentry *entry; + + i = hash & mask; + entry = &table[i]; + for (perturb = hash; entry->key != NULL; perturb >>= PERTURB_SHIFT) { + i = (i << 2) + i + perturb + 1; + entry = &table[i & mask]; + } + so->fill++; + entry->key = key; + entry->hash = hash; + so->used++; } /* @@ -276,86 +276,86 @@ static int set_table_resize(PySetObject *so, Py_ssize_t minused) { - Py_ssize_t newsize; - setentry *oldtable, *newtable, *entry; - Py_ssize_t i; - int is_oldtable_malloced; - setentry small_copy[PySet_MINSIZE]; - - assert(minused >= 0); - - /* Find the smallest table size > minused. */ - for (newsize = PySet_MINSIZE; - newsize <= minused && newsize > 0; - newsize <<= 1) - ; - if (newsize <= 0) { - PyErr_NoMemory(); - return -1; - } - - /* Get space for a new table. */ - oldtable = so->table; - assert(oldtable != NULL); - is_oldtable_malloced = oldtable != so->smalltable; - - if (newsize == PySet_MINSIZE) { - /* A large table is shrinking, or we can't get any smaller. */ - newtable = so->smalltable; - if (newtable == oldtable) { - if (so->fill == so->used) { - /* No dummies, so no point doing anything. */ - return 0; - } - /* We're not going to resize it, but rebuild the - table anyway to purge old dummy entries. - Subtle: This is *necessary* if fill==size, - as set_lookkey needs at least one virgin slot to - terminate failing searches. If fill < size, it's - merely desirable, as dummies slow searches. */ - assert(so->fill > so->used); - memcpy(small_copy, oldtable, sizeof(small_copy)); - oldtable = small_copy; - } - } - else { - newtable = PyMem_NEW(setentry, newsize); - if (newtable == NULL) { - PyErr_NoMemory(); - return -1; - } - } - - /* Make the set empty, using the new table. */ - assert(newtable != oldtable); - so->table = newtable; - so->mask = newsize - 1; - memset(newtable, 0, sizeof(setentry) * newsize); - so->used = 0; - i = so->fill; - so->fill = 0; - - /* Copy the data over; this is refcount-neutral for active entries; - dummy entries aren't copied over, of course */ - for (entry = oldtable; i > 0; entry++) { - if (entry->key == NULL) { - /* UNUSED */ - ; - } else if (entry->key == dummy) { - /* DUMMY */ - --i; - assert(entry->key == dummy); - Py_DECREF(entry->key); - } else { - /* ACTIVE */ - --i; - set_insert_clean(so, entry->key, entry->hash); - } - } - - if (is_oldtable_malloced) - PyMem_DEL(oldtable); - return 0; + Py_ssize_t newsize; + setentry *oldtable, *newtable, *entry; + Py_ssize_t i; + int is_oldtable_malloced; + setentry small_copy[PySet_MINSIZE]; + + assert(minused >= 0); + + /* Find the smallest table size > minused. */ + for (newsize = PySet_MINSIZE; + newsize <= minused && newsize > 0; + newsize <<= 1) + ; + if (newsize <= 0) { + PyErr_NoMemory(); + return -1; + } + + /* Get space for a new table. */ + oldtable = so->table; + assert(oldtable != NULL); + is_oldtable_malloced = oldtable != so->smalltable; + + if (newsize == PySet_MINSIZE) { + /* A large table is shrinking, or we can't get any smaller. */ + newtable = so->smalltable; + if (newtable == oldtable) { + if (so->fill == so->used) { + /* No dummies, so no point doing anything. */ + return 0; + } + /* We're not going to resize it, but rebuild the + table anyway to purge old dummy entries. + Subtle: This is *necessary* if fill==size, + as set_lookkey needs at least one virgin slot to + terminate failing searches. If fill < size, it's + merely desirable, as dummies slow searches. */ + assert(so->fill > so->used); + memcpy(small_copy, oldtable, sizeof(small_copy)); + oldtable = small_copy; + } + } + else { + newtable = PyMem_NEW(setentry, newsize); + if (newtable == NULL) { + PyErr_NoMemory(); + return -1; + } + } + + /* Make the set empty, using the new table. */ + assert(newtable != oldtable); + so->table = newtable; + so->mask = newsize - 1; + memset(newtable, 0, sizeof(setentry) * newsize); + so->used = 0; + i = so->fill; + so->fill = 0; + + /* Copy the data over; this is refcount-neutral for active entries; + dummy entries aren't copied over, of course */ + for (entry = oldtable; i > 0; entry++) { + if (entry->key == NULL) { + /* UNUSED */ + ; + } else if (entry->key == dummy) { + /* DUMMY */ + --i; + assert(entry->key == dummy); + Py_DECREF(entry->key); + } else { + /* ACTIVE */ + --i; + set_insert_clean(so, entry->key, entry->hash); + } + } + + if (is_oldtable_malloced) + PyMem_DEL(oldtable); + return 0; } /* CAUTION: set_add_key/entry() must guarantee it won't resize the table */ @@ -363,42 +363,42 @@ static int set_add_entry(register PySetObject *so, setentry *entry) { - register Py_ssize_t n_used; + register Py_ssize_t n_used; - assert(so->fill <= so->mask); /* at least one empty slot */ - n_used = so->used; - Py_INCREF(entry->key); - if (set_insert_key(so, entry->key, entry->hash) == -1) { - Py_DECREF(entry->key); - return -1; - } - if (!(so->used > n_used && so->fill*3 >= (so->mask+1)*2)) - return 0; - return set_table_resize(so, so->used>50000 ? so->used*2 : so->used*4); + assert(so->fill <= so->mask); /* at least one empty slot */ + n_used = so->used; + Py_INCREF(entry->key); + if (set_insert_key(so, entry->key, entry->hash) == -1) { + Py_DECREF(entry->key); + return -1; + } + if (!(so->used > n_used && so->fill*3 >= (so->mask+1)*2)) + return 0; + return set_table_resize(so, so->used>50000 ? so->used*2 : so->used*4); } static int set_add_key(register PySetObject *so, PyObject *key) { - register long hash; - register Py_ssize_t n_used; + register long hash; + register Py_ssize_t n_used; - if (!PyUnicode_CheckExact(key) || - (hash = ((PyUnicodeObject *) key)->hash) == -1) { - hash = PyObject_Hash(key); - if (hash == -1) - return -1; - } - assert(so->fill <= so->mask); /* at least one empty slot */ - n_used = so->used; - Py_INCREF(key); - if (set_insert_key(so, key, hash) == -1) { - Py_DECREF(key); - return -1; - } - if (!(so->used > n_used && so->fill*3 >= (so->mask+1)*2)) - return 0; - return set_table_resize(so, so->used>50000 ? so->used*2 : so->used*4); + if (!PyUnicode_CheckExact(key) || + (hash = ((PyUnicodeObject *) key)->hash) == -1) { + hash = PyObject_Hash(key); + if (hash == -1) + return -1; + } + assert(so->fill <= so->mask); /* at least one empty slot */ + n_used = so->used; + Py_INCREF(key); + if (set_insert_key(so, key, hash) == -1) { + Py_DECREF(key); + return -1; + } + if (!(so->used > n_used && so->fill*3 >= (so->mask+1)*2)) + return 0; + return set_table_resize(so, so->used>50000 ? so->used*2 : so->used*4); } #define DISCARD_NOTFOUND 0 @@ -406,112 +406,112 @@ static int set_discard_entry(PySetObject *so, setentry *oldentry) -{ register setentry *entry; - PyObject *old_key; +{ register setentry *entry; + PyObject *old_key; - entry = (so->lookup)(so, oldentry->key, oldentry->hash); - if (entry == NULL) - return -1; - if (entry->key == NULL || entry->key == dummy) - return DISCARD_NOTFOUND; - old_key = entry->key; - Py_INCREF(dummy); - entry->key = dummy; - so->used--; - Py_DECREF(old_key); - return DISCARD_FOUND; + entry = (so->lookup)(so, oldentry->key, oldentry->hash); + if (entry == NULL) + return -1; + if (entry->key == NULL || entry->key == dummy) + return DISCARD_NOTFOUND; + old_key = entry->key; + Py_INCREF(dummy); + entry->key = dummy; + so->used--; + Py_DECREF(old_key); + return DISCARD_FOUND; } static int set_discard_key(PySetObject *so, PyObject *key) { - register long hash; - register setentry *entry; - PyObject *old_key; - - assert (PyAnySet_Check(so)); - - if (!PyUnicode_CheckExact(key) || - (hash = ((PyUnicodeObject *) key)->hash) == -1) { - hash = PyObject_Hash(key); - if (hash == -1) - return -1; - } - entry = (so->lookup)(so, key, hash); - if (entry == NULL) - return -1; - if (entry->key == NULL || entry->key == dummy) - return DISCARD_NOTFOUND; - old_key = entry->key; - Py_INCREF(dummy); - entry->key = dummy; - so->used--; - Py_DECREF(old_key); - return DISCARD_FOUND; + register long hash; + register setentry *entry; + PyObject *old_key; + + assert (PyAnySet_Check(so)); + + if (!PyUnicode_CheckExact(key) || + (hash = ((PyUnicodeObject *) key)->hash) == -1) { + hash = PyObject_Hash(key); + if (hash == -1) + return -1; + } + entry = (so->lookup)(so, key, hash); + if (entry == NULL) + return -1; + if (entry->key == NULL || entry->key == dummy) + return DISCARD_NOTFOUND; + old_key = entry->key; + Py_INCREF(dummy); + entry->key = dummy; + so->used--; + Py_DECREF(old_key); + return DISCARD_FOUND; } static int set_clear_internal(PySetObject *so) { - setentry *entry, *table; - int table_is_malloced; - Py_ssize_t fill; - setentry small_copy[PySet_MINSIZE]; + setentry *entry, *table; + int table_is_malloced; + Py_ssize_t fill; + setentry small_copy[PySet_MINSIZE]; #ifdef Py_DEBUG - Py_ssize_t i, n; - assert (PyAnySet_Check(so)); + Py_ssize_t i, n; + assert (PyAnySet_Check(so)); - n = so->mask + 1; - i = 0; + n = so->mask + 1; + i = 0; #endif - table = so->table; - assert(table != NULL); - table_is_malloced = table != so->smalltable; - - /* This is delicate. During the process of clearing the set, - * decrefs can cause the set to mutate. To avoid fatal confusion - * (voice of experience), we have to make the set empty before - * clearing the slots, and never refer to anything via so->ref while - * clearing. - */ - fill = so->fill; - if (table_is_malloced) - EMPTY_TO_MINSIZE(so); - - else if (fill > 0) { - /* It's a small table with something that needs to be cleared. - * Afraid the only safe way is to copy the set entries into - * another small table first. - */ - memcpy(small_copy, table, sizeof(small_copy)); - table = small_copy; - EMPTY_TO_MINSIZE(so); - } - /* else it's a small table that's already empty */ - - /* Now we can finally clear things. If C had refcounts, we could - * assert that the refcount on table is 1 now, i.e. that this function - * has unique access to it, so decref side-effects can't alter it. - */ - for (entry = table; fill > 0; ++entry) { + table = so->table; + assert(table != NULL); + table_is_malloced = table != so->smalltable; + + /* This is delicate. During the process of clearing the set, + * decrefs can cause the set to mutate. To avoid fatal confusion + * (voice of experience), we have to make the set empty before + * clearing the slots, and never refer to anything via so->ref while + * clearing. + */ + fill = so->fill; + if (table_is_malloced) + EMPTY_TO_MINSIZE(so); + + else if (fill > 0) { + /* It's a small table with something that needs to be cleared. + * Afraid the only safe way is to copy the set entries into + * another small table first. + */ + memcpy(small_copy, table, sizeof(small_copy)); + table = small_copy; + EMPTY_TO_MINSIZE(so); + } + /* else it's a small table that's already empty */ + + /* Now we can finally clear things. If C had refcounts, we could + * assert that the refcount on table is 1 now, i.e. that this function + * has unique access to it, so decref side-effects can't alter it. + */ + for (entry = table; fill > 0; ++entry) { #ifdef Py_DEBUG - assert(i < n); - ++i; + assert(i < n); + ++i; #endif - if (entry->key) { - --fill; - Py_DECREF(entry->key); - } + if (entry->key) { + --fill; + Py_DECREF(entry->key); + } #ifdef Py_DEBUG - else - assert(entry->key == NULL); + else + assert(entry->key == NULL); #endif - } + } - if (table_is_malloced) - PyMem_DEL(table); - return 0; + if (table_is_malloced) + PyMem_DEL(table); + return 0; } /* @@ -525,223 +525,223 @@ * } * * CAUTION: In general, it isn't safe to use set_next in a loop that - * mutates the table. + * mutates the table. */ static int set_next(PySetObject *so, Py_ssize_t *pos_ptr, setentry **entry_ptr) { - Py_ssize_t i; - Py_ssize_t mask; - register setentry *table; - - assert (PyAnySet_Check(so)); - i = *pos_ptr; - assert(i >= 0); - table = so->table; - mask = so->mask; - while (i <= mask && (table[i].key == NULL || table[i].key == dummy)) - i++; - *pos_ptr = i+1; - if (i > mask) - return 0; - assert(table[i].key != NULL); - *entry_ptr = &table[i]; - return 1; + Py_ssize_t i; + Py_ssize_t mask; + register setentry *table; + + assert (PyAnySet_Check(so)); + i = *pos_ptr; + assert(i >= 0); + table = so->table; + mask = so->mask; + while (i <= mask && (table[i].key == NULL || table[i].key == dummy)) + i++; + *pos_ptr = i+1; + if (i > mask) + return 0; + assert(table[i].key != NULL); + *entry_ptr = &table[i]; + return 1; } static void set_dealloc(PySetObject *so) { - register setentry *entry; - Py_ssize_t fill = so->fill; - PyObject_GC_UnTrack(so); - Py_TRASHCAN_SAFE_BEGIN(so) - if (so->weakreflist != NULL) - PyObject_ClearWeakRefs((PyObject *) so); - - for (entry = so->table; fill > 0; entry++) { - if (entry->key) { - --fill; - Py_DECREF(entry->key); - } - } - if (so->table != so->smalltable) - PyMem_DEL(so->table); - if (numfree < PySet_MAXFREELIST && PyAnySet_CheckExact(so)) - free_list[numfree++] = so; - else - Py_TYPE(so)->tp_free(so); - Py_TRASHCAN_SAFE_END(so) + register setentry *entry; + Py_ssize_t fill = so->fill; + PyObject_GC_UnTrack(so); + Py_TRASHCAN_SAFE_BEGIN(so) + if (so->weakreflist != NULL) + PyObject_ClearWeakRefs((PyObject *) so); + + for (entry = so->table; fill > 0; entry++) { + if (entry->key) { + --fill; + Py_DECREF(entry->key); + } + } + if (so->table != so->smalltable) + PyMem_DEL(so->table); + if (numfree < PySet_MAXFREELIST && PyAnySet_CheckExact(so)) + free_list[numfree++] = so; + else + Py_TYPE(so)->tp_free(so); + Py_TRASHCAN_SAFE_END(so) } static PyObject * set_repr(PySetObject *so) { - PyObject *keys, *result=NULL; - Py_UNICODE *u; - int status = Py_ReprEnter((PyObject*)so); - PyObject *listrepr; - Py_ssize_t newsize; - - if (status != 0) { - if (status < 0) - return NULL; - return PyUnicode_FromFormat("%s(...)", Py_TYPE(so)->tp_name); - } - - /* shortcut for the empty set */ - if (!so->used) { - Py_ReprLeave((PyObject*)so); - return PyUnicode_FromFormat("%s()", Py_TYPE(so)->tp_name); - } - - keys = PySequence_List((PyObject *)so); - if (keys == NULL) - goto done; - - listrepr = PyObject_Repr(keys); - Py_DECREF(keys); - if (listrepr == NULL) - goto done; - newsize = PyUnicode_GET_SIZE(listrepr); - result = PyUnicode_FromUnicode(NULL, newsize); - if (result) { - u = PyUnicode_AS_UNICODE(result); - *u++ = '{'; - /* Omit the brackets from the listrepr */ - Py_UNICODE_COPY(u, PyUnicode_AS_UNICODE(listrepr)+1, - PyUnicode_GET_SIZE(listrepr)-2); - u += newsize-2; - *u++ = '}'; - } - Py_DECREF(listrepr); - if (Py_TYPE(so) != &PySet_Type) { - PyObject *tmp = PyUnicode_FromFormat("%s(%U)", - Py_TYPE(so)->tp_name, - result); - Py_DECREF(result); - result = tmp; - } + PyObject *keys, *result=NULL; + Py_UNICODE *u; + int status = Py_ReprEnter((PyObject*)so); + PyObject *listrepr; + Py_ssize_t newsize; + + if (status != 0) { + if (status < 0) + return NULL; + return PyUnicode_FromFormat("%s(...)", Py_TYPE(so)->tp_name); + } + + /* shortcut for the empty set */ + if (!so->used) { + Py_ReprLeave((PyObject*)so); + return PyUnicode_FromFormat("%s()", Py_TYPE(so)->tp_name); + } + + keys = PySequence_List((PyObject *)so); + if (keys == NULL) + goto done; + + listrepr = PyObject_Repr(keys); + Py_DECREF(keys); + if (listrepr == NULL) + goto done; + newsize = PyUnicode_GET_SIZE(listrepr); + result = PyUnicode_FromUnicode(NULL, newsize); + if (result) { + u = PyUnicode_AS_UNICODE(result); + *u++ = '{'; + /* Omit the brackets from the listrepr */ + Py_UNICODE_COPY(u, PyUnicode_AS_UNICODE(listrepr)+1, + PyUnicode_GET_SIZE(listrepr)-2); + u += newsize-2; + *u++ = '}'; + } + Py_DECREF(listrepr); + if (Py_TYPE(so) != &PySet_Type) { + PyObject *tmp = PyUnicode_FromFormat("%s(%U)", + Py_TYPE(so)->tp_name, + result); + Py_DECREF(result); + result = tmp; + } done: - Py_ReprLeave((PyObject*)so); - return result; + Py_ReprLeave((PyObject*)so); + return result; } static Py_ssize_t set_len(PyObject *so) { - return ((PySetObject *)so)->used; + return ((PySetObject *)so)->used; } static int set_merge(PySetObject *so, PyObject *otherset) { - PySetObject *other; - register Py_ssize_t i; - register setentry *entry; - - assert (PyAnySet_Check(so)); - assert (PyAnySet_Check(otherset)); - - other = (PySetObject*)otherset; - if (other == so || other->used == 0) - /* a.update(a) or a.update({}); nothing to do */ - return 0; - /* Do one big resize at the start, rather than - * incrementally resizing as we insert new keys. Expect - * that there will be no (or few) overlapping keys. - */ - if ((so->fill + other->used)*3 >= (so->mask+1)*2) { - if (set_table_resize(so, (so->used + other->used)*2) != 0) - return -1; - } - for (i = 0; i <= other->mask; i++) { - entry = &other->table[i]; - if (entry->key != NULL && - entry->key != dummy) { - Py_INCREF(entry->key); - if (set_insert_key(so, entry->key, entry->hash) == -1) { - Py_DECREF(entry->key); - return -1; - } - } - } - return 0; + PySetObject *other; + register Py_ssize_t i; + register setentry *entry; + + assert (PyAnySet_Check(so)); + assert (PyAnySet_Check(otherset)); + + other = (PySetObject*)otherset; + if (other == so || other->used == 0) + /* a.update(a) or a.update({}); nothing to do */ + return 0; + /* Do one big resize at the start, rather than + * incrementally resizing as we insert new keys. Expect + * that there will be no (or few) overlapping keys. + */ + if ((so->fill + other->used)*3 >= (so->mask+1)*2) { + if (set_table_resize(so, (so->used + other->used)*2) != 0) + return -1; + } + for (i = 0; i <= other->mask; i++) { + entry = &other->table[i]; + if (entry->key != NULL && + entry->key != dummy) { + Py_INCREF(entry->key); + if (set_insert_key(so, entry->key, entry->hash) == -1) { + Py_DECREF(entry->key); + return -1; + } + } + } + return 0; } static int set_contains_key(PySetObject *so, PyObject *key) { - long hash; - setentry *entry; + long hash; + setentry *entry; - if (!PyUnicode_CheckExact(key) || - (hash = ((PyUnicodeObject *) key)->hash) == -1) { - hash = PyObject_Hash(key); - if (hash == -1) - return -1; - } - entry = (so->lookup)(so, key, hash); - if (entry == NULL) - return -1; - key = entry->key; - return key != NULL && key != dummy; + if (!PyUnicode_CheckExact(key) || + (hash = ((PyUnicodeObject *) key)->hash) == -1) { + hash = PyObject_Hash(key); + if (hash == -1) + return -1; + } + entry = (so->lookup)(so, key, hash); + if (entry == NULL) + return -1; + key = entry->key; + return key != NULL && key != dummy; } static int set_contains_entry(PySetObject *so, setentry *entry) { - PyObject *key; - setentry *lu_entry; + PyObject *key; + setentry *lu_entry; - lu_entry = (so->lookup)(so, entry->key, entry->hash); - if (lu_entry == NULL) - return -1; - key = lu_entry->key; - return key != NULL && key != dummy; + lu_entry = (so->lookup)(so, entry->key, entry->hash); + if (lu_entry == NULL) + return -1; + key = lu_entry->key; + return key != NULL && key != dummy; } static PyObject * set_pop(PySetObject *so) { - register Py_ssize_t i = 0; - register setentry *entry; - PyObject *key; - - assert (PyAnySet_Check(so)); - if (so->used == 0) { - PyErr_SetString(PyExc_KeyError, "pop from an empty set"); - return NULL; - } - - /* Set entry to "the first" unused or dummy set entry. We abuse - * the hash field of slot 0 to hold a search finger: - * If slot 0 has a value, use slot 0. - * Else slot 0 is being used to hold a search finger, - * and we use its hash value as the first index to look. - */ - entry = &so->table[0]; - if (entry->key == NULL || entry->key == dummy) { - i = entry->hash; - /* The hash field may be a real hash value, or it may be a - * legit search finger, or it may be a once-legit search - * finger that's out of bounds now because it wrapped around - * or the table shrunk -- simply make sure it's in bounds now. - */ - if (i > so->mask || i < 1) - i = 1; /* skip slot 0 */ - while ((entry = &so->table[i])->key == NULL || entry->key==dummy) { - i++; - if (i > so->mask) - i = 1; - } - } - key = entry->key; - Py_INCREF(dummy); - entry->key = dummy; - so->used--; - so->table[0].hash = i + 1; /* next place to start */ - return key; + register Py_ssize_t i = 0; + register setentry *entry; + PyObject *key; + + assert (PyAnySet_Check(so)); + if (so->used == 0) { + PyErr_SetString(PyExc_KeyError, "pop from an empty set"); + return NULL; + } + + /* Set entry to "the first" unused or dummy set entry. We abuse + * the hash field of slot 0 to hold a search finger: + * If slot 0 has a value, use slot 0. + * Else slot 0 is being used to hold a search finger, + * and we use its hash value as the first index to look. + */ + entry = &so->table[0]; + if (entry->key == NULL || entry->key == dummy) { + i = entry->hash; + /* The hash field may be a real hash value, or it may be a + * legit search finger, or it may be a once-legit search + * finger that's out of bounds now because it wrapped around + * or the table shrunk -- simply make sure it's in bounds now. + */ + if (i > so->mask || i < 1) + i = 1; /* skip slot 0 */ + while ((entry = &so->table[i])->key == NULL || entry->key==dummy) { + i++; + if (i > so->mask) + i = 1; + } + } + key = entry->key; + Py_INCREF(dummy); + entry->key = dummy; + so->used--; + so->table[0].hash = i + 1; /* next place to start */ + return key; } PyDoc_STRVAR(pop_doc, "Remove and return an arbitrary set element.\n\ @@ -750,289 +750,289 @@ static int set_traverse(PySetObject *so, visitproc visit, void *arg) { - Py_ssize_t pos = 0; - setentry *entry; + Py_ssize_t pos = 0; + setentry *entry; - while (set_next(so, &pos, &entry)) - Py_VISIT(entry->key); - return 0; + while (set_next(so, &pos, &entry)) + Py_VISIT(entry->key); + return 0; } static long frozenset_hash(PyObject *self) { - PySetObject *so = (PySetObject *)self; - long h, hash = 1927868237L; - setentry *entry; - Py_ssize_t pos = 0; - - if (so->hash != -1) - return so->hash; - - hash *= PySet_GET_SIZE(self) + 1; - while (set_next(so, &pos, &entry)) { - /* Work to increase the bit dispersion for closely spaced hash - values. The is important because some use cases have many - combinations of a small number of elements with nearby - hashes so that many distinct combinations collapse to only - a handful of distinct hash values. */ - h = entry->hash; - hash ^= (h ^ (h << 16) ^ 89869747L) * 3644798167u; - } - hash = hash * 69069L + 907133923L; - if (hash == -1) - hash = 590923713L; - so->hash = hash; - return hash; + PySetObject *so = (PySetObject *)self; + long h, hash = 1927868237L; + setentry *entry; + Py_ssize_t pos = 0; + + if (so->hash != -1) + return so->hash; + + hash *= PySet_GET_SIZE(self) + 1; + while (set_next(so, &pos, &entry)) { + /* Work to increase the bit dispersion for closely spaced hash + values. The is important because some use cases have many + combinations of a small number of elements with nearby + hashes so that many distinct combinations collapse to only + a handful of distinct hash values. */ + h = entry->hash; + hash ^= (h ^ (h << 16) ^ 89869747L) * 3644798167u; + } + hash = hash * 69069L + 907133923L; + if (hash == -1) + hash = 590923713L; + so->hash = hash; + return hash; } /***** Set iterator type ***********************************************/ typedef struct { - PyObject_HEAD - PySetObject *si_set; /* Set to NULL when iterator is exhausted */ - Py_ssize_t si_used; - Py_ssize_t si_pos; - Py_ssize_t len; + PyObject_HEAD + PySetObject *si_set; /* Set to NULL when iterator is exhausted */ + Py_ssize_t si_used; + Py_ssize_t si_pos; + Py_ssize_t len; } setiterobject; static void setiter_dealloc(setiterobject *si) { - Py_XDECREF(si->si_set); - PyObject_GC_Del(si); + Py_XDECREF(si->si_set); + PyObject_GC_Del(si); } static int setiter_traverse(setiterobject *si, visitproc visit, void *arg) { - Py_VISIT(si->si_set); - return 0; + Py_VISIT(si->si_set); + return 0; } static PyObject * setiter_len(setiterobject *si) { - Py_ssize_t len = 0; - if (si->si_set != NULL && si->si_used == si->si_set->used) - len = si->len; - return PyLong_FromLong(len); + Py_ssize_t len = 0; + if (si->si_set != NULL && si->si_used == si->si_set->used) + len = si->len; + return PyLong_FromLong(len); } PyDoc_STRVAR(length_hint_doc, "Private method returning an estimate of len(list(it))."); static PyMethodDef setiter_methods[] = { - {"__length_hint__", (PyCFunction)setiter_len, METH_NOARGS, length_hint_doc}, - {NULL, NULL} /* sentinel */ + {"__length_hint__", (PyCFunction)setiter_len, METH_NOARGS, length_hint_doc}, + {NULL, NULL} /* sentinel */ }; static PyObject *setiter_iternext(setiterobject *si) { - PyObject *key; - register Py_ssize_t i, mask; - register setentry *entry; - PySetObject *so = si->si_set; - - if (so == NULL) - return NULL; - assert (PyAnySet_Check(so)); - - if (si->si_used != so->used) { - PyErr_SetString(PyExc_RuntimeError, - "Set changed size during iteration"); - si->si_used = -1; /* Make this state sticky */ - return NULL; - } - - i = si->si_pos; - assert(i>=0); - entry = so->table; - mask = so->mask; - while (i <= mask && (entry[i].key == NULL || entry[i].key == dummy)) - i++; - si->si_pos = i+1; - if (i > mask) - goto fail; - si->len--; - key = entry[i].key; - Py_INCREF(key); - return key; + PyObject *key; + register Py_ssize_t i, mask; + register setentry *entry; + PySetObject *so = si->si_set; + + if (so == NULL) + return NULL; + assert (PyAnySet_Check(so)); + + if (si->si_used != so->used) { + PyErr_SetString(PyExc_RuntimeError, + "Set changed size during iteration"); + si->si_used = -1; /* Make this state sticky */ + return NULL; + } + + i = si->si_pos; + assert(i>=0); + entry = so->table; + mask = so->mask; + while (i <= mask && (entry[i].key == NULL || entry[i].key == dummy)) + i++; + si->si_pos = i+1; + if (i > mask) + goto fail; + si->len--; + key = entry[i].key; + Py_INCREF(key); + return key; fail: - Py_DECREF(so); - si->si_set = NULL; - return NULL; + Py_DECREF(so); + si->si_set = NULL; + return NULL; } PyTypeObject PySetIter_Type = { - PyVarObject_HEAD_INIT(&PyType_Type, 0) - "set_iterator", /* tp_name */ - sizeof(setiterobject), /* tp_basicsize */ - 0, /* tp_itemsize */ - /* methods */ - (destructor)setiter_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)setiter_traverse, /* tp_traverse */ - 0, /* tp_clear */ - 0, /* tp_richcompare */ - 0, /* tp_weaklistoffset */ - PyObject_SelfIter, /* tp_iter */ - (iternextfunc)setiter_iternext, /* tp_iternext */ - setiter_methods, /* tp_methods */ - 0, + PyVarObject_HEAD_INIT(&PyType_Type, 0) + "set_iterator", /* tp_name */ + sizeof(setiterobject), /* tp_basicsize */ + 0, /* tp_itemsize */ + /* methods */ + (destructor)setiter_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)setiter_traverse, /* tp_traverse */ + 0, /* tp_clear */ + 0, /* tp_richcompare */ + 0, /* tp_weaklistoffset */ + PyObject_SelfIter, /* tp_iter */ + (iternextfunc)setiter_iternext, /* tp_iternext */ + setiter_methods, /* tp_methods */ + 0, }; static PyObject * set_iter(PySetObject *so) { - setiterobject *si = PyObject_GC_New(setiterobject, &PySetIter_Type); - if (si == NULL) - return NULL; - Py_INCREF(so); - si->si_set = so; - si->si_used = so->used; - si->si_pos = 0; - si->len = so->used; - _PyObject_GC_TRACK(si); - return (PyObject *)si; + setiterobject *si = PyObject_GC_New(setiterobject, &PySetIter_Type); + if (si == NULL) + return NULL; + Py_INCREF(so); + si->si_set = so; + si->si_used = so->used; + si->si_pos = 0; + si->len = so->used; + _PyObject_GC_TRACK(si); + return (PyObject *)si; } static int set_update_internal(PySetObject *so, PyObject *other) { - PyObject *key, *it; + PyObject *key, *it; - if (PyAnySet_Check(other)) - return set_merge(so, other); + if (PyAnySet_Check(other)) + return set_merge(so, other); - if (PyDict_CheckExact(other)) { - PyObject *value; - Py_ssize_t pos = 0; - long hash; - Py_ssize_t dictsize = PyDict_Size(other); - - /* Do one big resize at the start, rather than - * incrementally resizing as we insert new keys. Expect - * that there will be no (or few) overlapping keys. - */ - if (dictsize == -1) - return -1; - if ((so->fill + dictsize)*3 >= (so->mask+1)*2) { - if (set_table_resize(so, (so->used + dictsize)*2) != 0) - return -1; - } - while (_PyDict_Next(other, &pos, &key, &value, &hash)) { - setentry an_entry; - - an_entry.hash = hash; - an_entry.key = key; - if (set_add_entry(so, &an_entry) == -1) - return -1; - } - return 0; - } - - it = PyObject_GetIter(other); - if (it == NULL) - return -1; - - while ((key = PyIter_Next(it)) != NULL) { - if (set_add_key(so, key) == -1) { - Py_DECREF(it); - Py_DECREF(key); - return -1; - } - Py_DECREF(key); - } - Py_DECREF(it); - if (PyErr_Occurred()) - return -1; - return 0; + if (PyDict_CheckExact(other)) { + PyObject *value; + Py_ssize_t pos = 0; + long hash; + Py_ssize_t dictsize = PyDict_Size(other); + + /* Do one big resize at the start, rather than + * incrementally resizing as we insert new keys. Expect + * that there will be no (or few) overlapping keys. + */ + if (dictsize == -1) + return -1; + if ((so->fill + dictsize)*3 >= (so->mask+1)*2) { + if (set_table_resize(so, (so->used + dictsize)*2) != 0) + return -1; + } + while (_PyDict_Next(other, &pos, &key, &value, &hash)) { + setentry an_entry; + + an_entry.hash = hash; + an_entry.key = key; + if (set_add_entry(so, &an_entry) == -1) + return -1; + } + return 0; + } + + it = PyObject_GetIter(other); + if (it == NULL) + return -1; + + while ((key = PyIter_Next(it)) != NULL) { + if (set_add_key(so, key) == -1) { + Py_DECREF(it); + Py_DECREF(key); + return -1; + } + Py_DECREF(key); + } + Py_DECREF(it); + if (PyErr_Occurred()) + return -1; + return 0; } static PyObject * set_update(PySetObject *so, PyObject *args) { - Py_ssize_t i; + Py_ssize_t i; - for (i=0 ; i"); - if (dummy == NULL) - return NULL; - } - - /* create PySetObject structure */ - if (numfree && - (type == &PySet_Type || type == &PyFrozenSet_Type)) { - so = free_list[--numfree]; - assert (so != NULL && PyAnySet_CheckExact(so)); - Py_TYPE(so) = type; - _Py_NewReference((PyObject *)so); - EMPTY_TO_MINSIZE(so); - PyObject_GC_Track(so); - } else { - so = (PySetObject *)type->tp_alloc(type, 0); - if (so == NULL) - return NULL; - /* tp_alloc has already zeroed the structure */ - assert(so->table == NULL && so->fill == 0 && so->used == 0); - INIT_NONZERO_SET_SLOTS(so); - } - - so->lookup = set_lookkey_unicode; - so->weakreflist = NULL; - - if (iterable != NULL) { - if (set_update_internal(so, iterable) == -1) { - Py_DECREF(so); - return NULL; - } - } + if (dummy == NULL) { /* Auto-initialize dummy */ + dummy = PyUnicode_FromString(""); + if (dummy == NULL) + return NULL; + } + + /* create PySetObject structure */ + if (numfree && + (type == &PySet_Type || type == &PyFrozenSet_Type)) { + so = free_list[--numfree]; + assert (so != NULL && PyAnySet_CheckExact(so)); + Py_TYPE(so) = type; + _Py_NewReference((PyObject *)so); + EMPTY_TO_MINSIZE(so); + PyObject_GC_Track(so); + } else { + so = (PySetObject *)type->tp_alloc(type, 0); + if (so == NULL) + return NULL; + /* tp_alloc has already zeroed the structure */ + assert(so->table == NULL && so->fill == 0 && so->used == 0); + INIT_NONZERO_SET_SLOTS(so); + } + + so->lookup = set_lookkey_unicode; + so->weakreflist = NULL; + + if (iterable != NULL) { + if (set_update_internal(so, iterable) == -1) { + Py_DECREF(so); + return NULL; + } + } - return (PyObject *)so; + return (PyObject *)so; } static PyObject * make_new_set_basetype(PyTypeObject *type, PyObject *iterable) { - if (type != &PySet_Type && type != &PyFrozenSet_Type) { - if (PyType_IsSubtype(type, &PySet_Type)) - type = &PySet_Type; - else - type = &PyFrozenSet_Type; - } - return make_new_set(type, iterable); + if (type != &PySet_Type && type != &PyFrozenSet_Type) { + if (PyType_IsSubtype(type, &PySet_Type)) + type = &PySet_Type; + else + type = &PyFrozenSet_Type; + } + return make_new_set(type, iterable); } /* The empty frozenset is a singleton */ @@ -1041,56 +1041,56 @@ static PyObject * frozenset_new(PyTypeObject *type, PyObject *args, PyObject *kwds) { - PyObject *iterable = NULL, *result; + PyObject *iterable = NULL, *result; - if (type == &PyFrozenSet_Type && !_PyArg_NoKeywords("frozenset()", kwds)) - return NULL; + if (type == &PyFrozenSet_Type && !_PyArg_NoKeywords("frozenset()", kwds)) + return NULL; - if (!PyArg_UnpackTuple(args, type->tp_name, 0, 1, &iterable)) - return NULL; + if (!PyArg_UnpackTuple(args, type->tp_name, 0, 1, &iterable)) + return NULL; - if (type != &PyFrozenSet_Type) - return make_new_set(type, iterable); - - if (iterable != NULL) { - /* frozenset(f) is idempotent */ - if (PyFrozenSet_CheckExact(iterable)) { - Py_INCREF(iterable); - return iterable; - } - result = make_new_set(type, iterable); - if (result == NULL || PySet_GET_SIZE(result)) - return result; - Py_DECREF(result); - } - /* The empty frozenset is a singleton */ - if (emptyfrozenset == NULL) - emptyfrozenset = make_new_set(type, NULL); - Py_XINCREF(emptyfrozenset); - return emptyfrozenset; + if (type != &PyFrozenSet_Type) + return make_new_set(type, iterable); + + if (iterable != NULL) { + /* frozenset(f) is idempotent */ + if (PyFrozenSet_CheckExact(iterable)) { + Py_INCREF(iterable); + return iterable; + } + result = make_new_set(type, iterable); + if (result == NULL || PySet_GET_SIZE(result)) + return result; + Py_DECREF(result); + } + /* The empty frozenset is a singleton */ + if (emptyfrozenset == NULL) + emptyfrozenset = make_new_set(type, NULL); + Py_XINCREF(emptyfrozenset); + return emptyfrozenset; } void PySet_Fini(void) { - PySetObject *so; + PySetObject *so; - while (numfree) { - numfree--; - so = free_list[numfree]; - PyObject_GC_Del(so); - } - Py_CLEAR(dummy); - Py_CLEAR(emptyfrozenset); + while (numfree) { + numfree--; + so = free_list[numfree]; + PyObject_GC_Del(so); + } + Py_CLEAR(dummy); + Py_CLEAR(emptyfrozenset); } static PyObject * set_new(PyTypeObject *type, PyObject *args, PyObject *kwds) { - if (type == &PySet_Type && !_PyArg_NoKeywords("set()", kwds)) - return NULL; - - return make_new_set(type, NULL); + if (type == &PySet_Type && !_PyArg_NoKeywords("set()", kwds)) + return NULL; + + return make_new_set(type, NULL); } /* set_swap_bodies() switches the contents of any two sets by moving their @@ -1100,64 +1100,64 @@ t=set(a); a.clear(); a.update(b); b.clear(); b.update(t); del t The function always succeeds and it leaves both objects in a stable state. - Useful for creating temporary frozensets from sets for membership testing + Useful for creating temporary frozensets from sets for membership testing in __contains__(), discard(), and remove(). Also useful for operations - that update in-place (by allowing an intermediate result to be swapped + that update in-place (by allowing an intermediate result to be swapped into one of the original inputs). */ static void set_swap_bodies(PySetObject *a, PySetObject *b) { - Py_ssize_t t; - setentry *u; - setentry *(*f)(PySetObject *so, PyObject *key, long hash); - setentry tab[PySet_MINSIZE]; - long h; - - t = a->fill; a->fill = b->fill; b->fill = t; - t = a->used; a->used = b->used; b->used = t; - t = a->mask; a->mask = b->mask; b->mask = t; - - u = a->table; - if (a->table == a->smalltable) - u = b->smalltable; - a->table = b->table; - if (b->table == b->smalltable) - a->table = a->smalltable; - b->table = u; - - f = a->lookup; a->lookup = b->lookup; b->lookup = f; - - if (a->table == a->smalltable || b->table == b->smalltable) { - memcpy(tab, a->smalltable, sizeof(tab)); - memcpy(a->smalltable, b->smalltable, sizeof(tab)); - memcpy(b->smalltable, tab, sizeof(tab)); - } - - if (PyType_IsSubtype(Py_TYPE(a), &PyFrozenSet_Type) && - PyType_IsSubtype(Py_TYPE(b), &PyFrozenSet_Type)) { - h = a->hash; a->hash = b->hash; b->hash = h; - } else { - a->hash = -1; - b->hash = -1; - } + Py_ssize_t t; + setentry *u; + setentry *(*f)(PySetObject *so, PyObject *key, long hash); + setentry tab[PySet_MINSIZE]; + long h; + + t = a->fill; a->fill = b->fill; b->fill = t; + t = a->used; a->used = b->used; b->used = t; + t = a->mask; a->mask = b->mask; b->mask = t; + + u = a->table; + if (a->table == a->smalltable) + u = b->smalltable; + a->table = b->table; + if (b->table == b->smalltable) + a->table = a->smalltable; + b->table = u; + + f = a->lookup; a->lookup = b->lookup; b->lookup = f; + + if (a->table == a->smalltable || b->table == b->smalltable) { + memcpy(tab, a->smalltable, sizeof(tab)); + memcpy(a->smalltable, b->smalltable, sizeof(tab)); + memcpy(b->smalltable, tab, sizeof(tab)); + } + + if (PyType_IsSubtype(Py_TYPE(a), &PyFrozenSet_Type) && + PyType_IsSubtype(Py_TYPE(b), &PyFrozenSet_Type)) { + h = a->hash; a->hash = b->hash; b->hash = h; + } else { + a->hash = -1; + b->hash = -1; + } } static PyObject * set_copy(PySetObject *so) { - return make_new_set_basetype(Py_TYPE(so), (PyObject *)so); + return make_new_set_basetype(Py_TYPE(so), (PyObject *)so); } static PyObject * frozenset_copy(PySetObject *so) { - if (PyFrozenSet_CheckExact(so)) { - Py_INCREF(so); - return (PyObject *)so; - } - return set_copy(so); + if (PyFrozenSet_CheckExact(so)) { + Py_INCREF(so); + return (PyObject *)so; + } + return set_copy(so); } PyDoc_STRVAR(copy_doc, "Return a shallow copy of a set."); @@ -1165,8 +1165,8 @@ static PyObject * set_clear(PySetObject *so) { - set_clear_internal(so); - Py_RETURN_NONE; + set_clear_internal(so); + Py_RETURN_NONE; } PyDoc_STRVAR(clear_doc, "Remove all elements from this set."); @@ -1174,24 +1174,24 @@ static PyObject * set_union(PySetObject *so, PyObject *args) { - PySetObject *result; - PyObject *other; - Py_ssize_t i; - - result = (PySetObject *)set_copy(so); - if (result == NULL) - return NULL; - - for (i=0 ; i PySet_GET_SIZE(so)) { - tmp = (PyObject *)so; - so = (PySetObject *)other; - other = tmp; - } - - while (set_next((PySetObject *)other, &pos, &entry)) { - int rv = set_contains_entry(so, entry); - if (rv == -1) { - Py_DECREF(result); - return NULL; - } - if (rv) { - if (set_add_entry(result, entry) == -1) { - Py_DECREF(result); - return NULL; - } - } - } - return (PyObject *)result; - } - - it = PyObject_GetIter(other); - if (it == NULL) { - Py_DECREF(result); - return NULL; - } - - while ((key = PyIter_Next(it)) != NULL) { - int rv; - setentry entry; - long hash = PyObject_Hash(key); - - if (hash == -1) { - Py_DECREF(it); - Py_DECREF(result); - Py_DECREF(key); - return NULL; - } - entry.hash = hash; - entry.key = key; - rv = set_contains_entry(so, &entry); - if (rv == -1) { - Py_DECREF(it); - Py_DECREF(result); - Py_DECREF(key); - return NULL; - } - if (rv) { - if (set_add_entry(result, &entry) == -1) { - Py_DECREF(it); - Py_DECREF(result); - Py_DECREF(key); - return NULL; - } - } - Py_DECREF(key); - } - Py_DECREF(it); - if (PyErr_Occurred()) { - Py_DECREF(result); - return NULL; - } - return (PyObject *)result; + result = (PySetObject *)make_new_set_basetype(Py_TYPE(so), NULL); + if (result == NULL) + return NULL; + + if (PyAnySet_Check(other)) { + Py_ssize_t pos = 0; + setentry *entry; + + if (PySet_GET_SIZE(other) > PySet_GET_SIZE(so)) { + tmp = (PyObject *)so; + so = (PySetObject *)other; + other = tmp; + } + + while (set_next((PySetObject *)other, &pos, &entry)) { + int rv = set_contains_entry(so, entry); + if (rv == -1) { + Py_DECREF(result); + return NULL; + } + if (rv) { + if (set_add_entry(result, entry) == -1) { + Py_DECREF(result); + return NULL; + } + } + } + return (PyObject *)result; + } + + it = PyObject_GetIter(other); + if (it == NULL) { + Py_DECREF(result); + return NULL; + } + + while ((key = PyIter_Next(it)) != NULL) { + int rv; + setentry entry; + long hash = PyObject_Hash(key); + + if (hash == -1) { + Py_DECREF(it); + Py_DECREF(result); + Py_DECREF(key); + return NULL; + } + entry.hash = hash; + entry.key = key; + rv = set_contains_entry(so, &entry); + if (rv == -1) { + Py_DECREF(it); + Py_DECREF(result); + Py_DECREF(key); + return NULL; + } + if (rv) { + if (set_add_entry(result, &entry) == -1) { + Py_DECREF(it); + Py_DECREF(result); + Py_DECREF(key); + return NULL; + } + } + Py_DECREF(key); + } + Py_DECREF(it); + if (PyErr_Occurred()) { + Py_DECREF(result); + return NULL; + } + return (PyObject *)result; } static PyObject * set_intersection_multi(PySetObject *so, PyObject *args) { - Py_ssize_t i; - PyObject *result = (PyObject *)so; + Py_ssize_t i; + PyObject *result = (PyObject *)so; - if (PyTuple_GET_SIZE(args) == 0) - return set_copy(so); + if (PyTuple_GET_SIZE(args) == 0) + return set_copy(so); - Py_INCREF(so); - for (i=0 ; i PySet_GET_SIZE(so)) { - tmp = (PyObject *)so; - so = (PySetObject *)other; - other = tmp; - } - while (set_next((PySetObject *)other, &pos, &entry)) { - int rv = set_contains_entry(so, entry); - if (rv == -1) - return NULL; - if (rv) - Py_RETURN_FALSE; - } - Py_RETURN_TRUE; - } - - it = PyObject_GetIter(other); - if (it == NULL) - return NULL; - - while ((key = PyIter_Next(it)) != NULL) { - int rv; - setentry entry; - long hash = PyObject_Hash(key);; - - if (hash == -1) { - Py_DECREF(key); - Py_DECREF(it); - return NULL; - } - entry.hash = hash; - entry.key = key; - rv = set_contains_entry(so, &entry); - Py_DECREF(key); - if (rv == -1) { - Py_DECREF(it); - return NULL; - } - if (rv) { - Py_DECREF(it); - Py_RETURN_FALSE; - } - } - Py_DECREF(it); - if (PyErr_Occurred()) - return NULL; - Py_RETURN_TRUE; + if ((PyObject *)so == other) { + if (PySet_GET_SIZE(so) == 0) + Py_RETURN_TRUE; + else + Py_RETURN_FALSE; + } + + if (PyAnySet_CheckExact(other)) { + Py_ssize_t pos = 0; + setentry *entry; + + if (PySet_GET_SIZE(other) > PySet_GET_SIZE(so)) { + tmp = (PyObject *)so; + so = (PySetObject *)other; + other = tmp; + } + while (set_next((PySetObject *)other, &pos, &entry)) { + int rv = set_contains_entry(so, entry); + if (rv == -1) + return NULL; + if (rv) + Py_RETURN_FALSE; + } + Py_RETURN_TRUE; + } + + it = PyObject_GetIter(other); + if (it == NULL) + return NULL; + + while ((key = PyIter_Next(it)) != NULL) { + int rv; + setentry entry; + long hash = PyObject_Hash(key);; + + if (hash == -1) { + Py_DECREF(key); + Py_DECREF(it); + return NULL; + } + entry.hash = hash; + entry.key = key; + rv = set_contains_entry(so, &entry); + Py_DECREF(key); + if (rv == -1) { + Py_DECREF(it); + return NULL; + } + if (rv) { + Py_DECREF(it); + Py_RETURN_FALSE; + } + } + Py_DECREF(it); + if (PyErr_Occurred()) + return NULL; + Py_RETURN_TRUE; } PyDoc_STRVAR(isdisjoint_doc, @@ -1471,51 +1471,51 @@ static int set_difference_update_internal(PySetObject *so, PyObject *other) { - if ((PyObject *)so == other) - return set_clear_internal(so); - - if (PyAnySet_Check(other)) { - setentry *entry; - Py_ssize_t pos = 0; - - while (set_next((PySetObject *)other, &pos, &entry)) - if (set_discard_entry(so, entry) == -1) - return -1; - } else { - PyObject *key, *it; - it = PyObject_GetIter(other); - if (it == NULL) - return -1; - - while ((key = PyIter_Next(it)) != NULL) { - if (set_discard_key(so, key) == -1) { - Py_DECREF(it); - Py_DECREF(key); - return -1; - } - Py_DECREF(key); - } - Py_DECREF(it); - if (PyErr_Occurred()) - return -1; - } - /* If more than 1/5 are dummies, then resize them away. */ - if ((so->fill - so->used) * 5 < so->mask) - return 0; - return set_table_resize(so, so->used>50000 ? so->used*2 : so->used*4); + if ((PyObject *)so == other) + return set_clear_internal(so); + + if (PyAnySet_Check(other)) { + setentry *entry; + Py_ssize_t pos = 0; + + while (set_next((PySetObject *)other, &pos, &entry)) + if (set_discard_entry(so, entry) == -1) + return -1; + } else { + PyObject *key, *it; + it = PyObject_GetIter(other); + if (it == NULL) + return -1; + + while ((key = PyIter_Next(it)) != NULL) { + if (set_discard_key(so, key) == -1) { + Py_DECREF(it); + Py_DECREF(key); + return -1; + } + Py_DECREF(key); + } + Py_DECREF(it); + if (PyErr_Occurred()) + return -1; + } + /* If more than 1/5 are dummies, then resize them away. */ + if ((so->fill - so->used) * 5 < so->mask) + return 0; + return set_table_resize(so, so->used>50000 ? so->used*2 : so->used*4); } static PyObject * set_difference_update(PySetObject *so, PyObject *args) { - Py_ssize_t i; + Py_ssize_t i; - for (i=0 ; ihash; - entrycopy.key = entry->key; - if (!_PyDict_Contains(other, entry->key, entry->hash)) { - if (set_add_entry((PySetObject *)result, &entrycopy) == -1) { - Py_DECREF(result); - return NULL; - } - } - } - return result; - } - - while (set_next(so, &pos, &entry)) { - int rv = set_contains_entry((PySetObject *)other, entry); - if (rv == -1) { - Py_DECREF(result); - return NULL; - } - if (!rv) { - if (set_add_entry((PySetObject *)result, entry) == -1) { - Py_DECREF(result); - return NULL; - } - } - } - return result; + PyObject *result; + setentry *entry; + Py_ssize_t pos = 0; + + if (!PyAnySet_Check(other) && !PyDict_CheckExact(other)) { + result = set_copy(so); + if (result == NULL) + return NULL; + if (set_difference_update_internal((PySetObject *)result, other) != -1) + return result; + Py_DECREF(result); + return NULL; + } + + result = make_new_set_basetype(Py_TYPE(so), NULL); + if (result == NULL) + return NULL; + + if (PyDict_CheckExact(other)) { + while (set_next(so, &pos, &entry)) { + setentry entrycopy; + entrycopy.hash = entry->hash; + entrycopy.key = entry->key; + if (!_PyDict_Contains(other, entry->key, entry->hash)) { + if (set_add_entry((PySetObject *)result, &entrycopy) == -1) { + Py_DECREF(result); + return NULL; + } + } + } + return result; + } + + while (set_next(so, &pos, &entry)) { + int rv = set_contains_entry((PySetObject *)other, entry); + if (rv == -1) { + Py_DECREF(result); + return NULL; + } + if (!rv) { + if (set_add_entry((PySetObject *)result, entry) == -1) { + Py_DECREF(result); + return NULL; + } + } + } + return result; } static PyObject * set_difference_multi(PySetObject *so, PyObject *args) { - Py_ssize_t i; - PyObject *result, *other; + Py_ssize_t i; + PyObject *result, *other; - if (PyTuple_GET_SIZE(args) == 0) - return set_copy(so); + if (PyTuple_GET_SIZE(args) == 0) + return set_copy(so); - other = PyTuple_GET_ITEM(args, 0); - result = set_difference(so, other); - if (result == NULL) - return NULL; - - for (i=1 ; i PySet_GET_SIZE(other)) - Py_RETURN_FALSE; - - while (set_next(so, &pos, &entry)) { - int rv = set_contains_entry((PySetObject *)other, entry); - if (rv == -1) - return NULL; - if (!rv) - Py_RETURN_FALSE; - } - Py_RETURN_TRUE; + if (!PyAnySet_Check(other)) { + PyObject *tmp, *result; + tmp = make_new_set(&PySet_Type, other); + if (tmp == NULL) + return NULL; + result = set_issubset(so, tmp); + Py_DECREF(tmp); + return result; + } + if (PySet_GET_SIZE(so) > PySet_GET_SIZE(other)) + Py_RETURN_FALSE; + + while (set_next(so, &pos, &entry)) { + int rv = set_contains_entry((PySetObject *)other, entry); + if (rv == -1) + return NULL; + if (!rv) + Py_RETURN_FALSE; + } + Py_RETURN_TRUE; } PyDoc_STRVAR(issubset_doc, "Report whether another set contains this set."); @@ -1765,17 +1765,17 @@ static PyObject * set_issuperset(PySetObject *so, PyObject *other) { - PyObject *tmp, *result; + PyObject *tmp, *result; - if (!PyAnySet_Check(other)) { - tmp = make_new_set(&PySet_Type, other); - if (tmp == NULL) - return NULL; - result = set_issuperset(so, tmp); - Py_DECREF(tmp); - return result; - } - return set_issubset((PySetObject *)other, (PyObject *)so); + if (!PyAnySet_Check(other)) { + tmp = make_new_set(&PySet_Type, other); + if (tmp == NULL) + return NULL; + result = set_issuperset(so, tmp); + Py_DECREF(tmp); + return result; + } + return set_issubset((PySetObject *)other, (PyObject *)so); } PyDoc_STRVAR(issuperset_doc, "Report whether this set contains another set."); @@ -1783,54 +1783,54 @@ static PyObject * set_richcompare(PySetObject *v, PyObject *w, int op) { - PyObject *r1, *r2; + PyObject *r1, *r2; - if(!PyAnySet_Check(w)) { - Py_INCREF(Py_NotImplemented); - return Py_NotImplemented; - } - switch (op) { - case Py_EQ: - if (PySet_GET_SIZE(v) != PySet_GET_SIZE(w)) - Py_RETURN_FALSE; - if (v->hash != -1 && - ((PySetObject *)w)->hash != -1 && - v->hash != ((PySetObject *)w)->hash) - Py_RETURN_FALSE; - return set_issubset(v, w); - case Py_NE: - r1 = set_richcompare(v, w, Py_EQ); - if (r1 == NULL) - return NULL; - r2 = PyBool_FromLong(PyObject_Not(r1)); - Py_DECREF(r1); - return r2; - case Py_LE: - return set_issubset(v, w); - case Py_GE: - return set_issuperset(v, w); - case Py_LT: - if (PySet_GET_SIZE(v) >= PySet_GET_SIZE(w)) - Py_RETURN_FALSE; - return set_issubset(v, w); - case Py_GT: - if (PySet_GET_SIZE(v) <= PySet_GET_SIZE(w)) - Py_RETURN_FALSE; - return set_issuperset(v, w); - } - Py_INCREF(Py_NotImplemented); - return Py_NotImplemented; + if(!PyAnySet_Check(w)) { + Py_INCREF(Py_NotImplemented); + return Py_NotImplemented; + } + switch (op) { + case Py_EQ: + if (PySet_GET_SIZE(v) != PySet_GET_SIZE(w)) + Py_RETURN_FALSE; + if (v->hash != -1 && + ((PySetObject *)w)->hash != -1 && + v->hash != ((PySetObject *)w)->hash) + Py_RETURN_FALSE; + return set_issubset(v, w); + case Py_NE: + r1 = set_richcompare(v, w, Py_EQ); + if (r1 == NULL) + return NULL; + r2 = PyBool_FromLong(PyObject_Not(r1)); + Py_DECREF(r1); + return r2; + case Py_LE: + return set_issubset(v, w); + case Py_GE: + return set_issuperset(v, w); + case Py_LT: + if (PySet_GET_SIZE(v) >= PySet_GET_SIZE(w)) + Py_RETURN_FALSE; + return set_issubset(v, w); + case Py_GT: + if (PySet_GET_SIZE(v) <= PySet_GET_SIZE(w)) + Py_RETURN_FALSE; + return set_issuperset(v, w); + } + Py_INCREF(Py_NotImplemented); + return Py_NotImplemented; } static PyObject * set_add(PySetObject *so, PyObject *key) { - if (set_add_key(so, key) == -1) - return NULL; - Py_RETURN_NONE; + if (set_add_key(so, key) == -1) + return NULL; + Py_RETURN_NONE; } -PyDoc_STRVAR(add_doc, +PyDoc_STRVAR(add_doc, "Add an element to a set.\n\ \n\ This has no effect if the element is already present."); @@ -1838,34 +1838,34 @@ static int set_contains(PySetObject *so, PyObject *key) { - PyObject *tmpkey; - int rv; + PyObject *tmpkey; + int rv; - rv = set_contains_key(so, key); - if (rv == -1) { - if (!PySet_Check(key) || !PyErr_ExceptionMatches(PyExc_TypeError)) - return -1; - PyErr_Clear(); - tmpkey = make_new_set(&PyFrozenSet_Type, NULL); - if (tmpkey == NULL) - return -1; - set_swap_bodies((PySetObject *)tmpkey, (PySetObject *)key); - rv = set_contains(so, tmpkey); - set_swap_bodies((PySetObject *)tmpkey, (PySetObject *)key); - Py_DECREF(tmpkey); - } - return rv; + rv = set_contains_key(so, key); + if (rv == -1) { + if (!PySet_Check(key) || !PyErr_ExceptionMatches(PyExc_TypeError)) + return -1; + PyErr_Clear(); + tmpkey = make_new_set(&PyFrozenSet_Type, NULL); + if (tmpkey == NULL) + return -1; + set_swap_bodies((PySetObject *)tmpkey, (PySetObject *)key); + rv = set_contains(so, tmpkey); + set_swap_bodies((PySetObject *)tmpkey, (PySetObject *)key); + Py_DECREF(tmpkey); + } + return rv; } static PyObject * set_direct_contains(PySetObject *so, PyObject *key) { - long result; + long result; - result = set_contains(so, key); - if (result == -1) - return NULL; - return PyBool_FromLong(result); + result = set_contains(so, key); + if (result == -1) + return NULL; + return PyBool_FromLong(result); } PyDoc_STRVAR(contains_doc, "x.__contains__(y) <==> y in x."); @@ -1873,30 +1873,30 @@ static PyObject * set_remove(PySetObject *so, PyObject *key) { - PyObject *tmpkey; - int rv; + PyObject *tmpkey; + int rv; - rv = set_discard_key(so, key); - if (rv == -1) { - if (!PySet_Check(key) || !PyErr_ExceptionMatches(PyExc_TypeError)) - return NULL; - PyErr_Clear(); - tmpkey = make_new_set(&PyFrozenSet_Type, NULL); - if (tmpkey == NULL) - return NULL; - set_swap_bodies((PySetObject *)tmpkey, (PySetObject *)key); - rv = set_discard_key(so, tmpkey); - set_swap_bodies((PySetObject *)tmpkey, (PySetObject *)key); - Py_DECREF(tmpkey); - if (rv == -1) - return NULL; - } - - if (rv == DISCARD_NOTFOUND) { - set_key_error(key); - return NULL; - } - Py_RETURN_NONE; + rv = set_discard_key(so, key); + if (rv == -1) { + if (!PySet_Check(key) || !PyErr_ExceptionMatches(PyExc_TypeError)) + return NULL; + PyErr_Clear(); + tmpkey = make_new_set(&PyFrozenSet_Type, NULL); + if (tmpkey == NULL) + return NULL; + set_swap_bodies((PySetObject *)tmpkey, (PySetObject *)key); + rv = set_discard_key(so, tmpkey); + set_swap_bodies((PySetObject *)tmpkey, (PySetObject *)key); + Py_DECREF(tmpkey); + if (rv == -1) + return NULL; + } + + if (rv == DISCARD_NOTFOUND) { + set_key_error(key); + return NULL; + } + Py_RETURN_NONE; } PyDoc_STRVAR(remove_doc, @@ -1907,54 +1907,54 @@ static PyObject * set_discard(PySetObject *so, PyObject *key) { - PyObject *tmpkey, *result; - int rv; + PyObject *tmpkey, *result; + int rv; - rv = set_discard_key(so, key); - if (rv == -1) { - if (!PySet_Check(key) || !PyErr_ExceptionMatches(PyExc_TypeError)) - return NULL; - PyErr_Clear(); - tmpkey = make_new_set(&PyFrozenSet_Type, NULL); - if (tmpkey == NULL) - return NULL; - set_swap_bodies((PySetObject *)tmpkey, (PySetObject *)key); - result = set_discard(so, tmpkey); - set_swap_bodies((PySetObject *)tmpkey, (PySetObject *)key); - Py_DECREF(tmpkey); - return result; - } - Py_RETURN_NONE; + rv = set_discard_key(so, key); + if (rv == -1) { + if (!PySet_Check(key) || !PyErr_ExceptionMatches(PyExc_TypeError)) + return NULL; + PyErr_Clear(); + tmpkey = make_new_set(&PyFrozenSet_Type, NULL); + if (tmpkey == NULL) + return NULL; + set_swap_bodies((PySetObject *)tmpkey, (PySetObject *)key); + result = set_discard(so, tmpkey); + set_swap_bodies((PySetObject *)tmpkey, (PySetObject *)key); + Py_DECREF(tmpkey); + return result; + } + Py_RETURN_NONE; } PyDoc_STRVAR(discard_doc, "Remove an element from a set if it is a member.\n\ \n\ -If the element is not a member, do nothing."); +If the element is not a member, do nothing."); static PyObject * set_reduce(PySetObject *so) { - PyObject *keys=NULL, *args=NULL, *result=NULL, *dict=NULL; + PyObject *keys=NULL, *args=NULL, *result=NULL, *dict=NULL; - keys = PySequence_List((PyObject *)so); - if (keys == NULL) - goto done; - args = PyTuple_Pack(1, keys); - if (args == NULL) - goto done; - dict = PyObject_GetAttrString((PyObject *)so, "__dict__"); - if (dict == NULL) { - PyErr_Clear(); - dict = Py_None; - Py_INCREF(dict); - } - result = PyTuple_Pack(3, Py_TYPE(so), args, dict); + keys = PySequence_List((PyObject *)so); + if (keys == NULL) + goto done; + args = PyTuple_Pack(1, keys); + if (args == NULL) + goto done; + dict = PyObject_GetAttrString((PyObject *)so, "__dict__"); + if (dict == NULL) { + PyErr_Clear(); + dict = Py_None; + Py_INCREF(dict); + } + result = PyTuple_Pack(3, Py_TYPE(so), args, dict); done: - Py_XDECREF(args); - Py_XDECREF(keys); - Py_XDECREF(dict); - return result; + Py_XDECREF(args); + Py_XDECREF(keys); + Py_XDECREF(dict); + return result; } PyDoc_STRVAR(reduce_doc, "Return state information for pickling."); @@ -1962,42 +1962,42 @@ static PyObject * set_sizeof(PySetObject *so) { - Py_ssize_t res; + Py_ssize_t res; - res = sizeof(PySetObject); - if (so->table != so->smalltable) - res = res + (so->mask + 1) * sizeof(setentry); - return PyLong_FromSsize_t(res); + res = sizeof(PySetObject); + if (so->table != so->smalltable) + res = res + (so->mask + 1) * sizeof(setentry); + return PyLong_FromSsize_t(res); } PyDoc_STRVAR(sizeof_doc, "S.__sizeof__() -> size of S in memory, in bytes"); static int set_init(PySetObject *self, PyObject *args, PyObject *kwds) { - PyObject *iterable = NULL; + PyObject *iterable = NULL; - if (!PyAnySet_Check(self)) - return -1; - if (PySet_Check(self) && !_PyArg_NoKeywords("set()", kwds)) - return -1; - if (!PyArg_UnpackTuple(args, Py_TYPE(self)->tp_name, 0, 1, &iterable)) - return -1; - set_clear_internal(self); - self->hash = -1; - if (iterable == NULL) - return 0; - return set_update_internal(self, iterable); + if (!PyAnySet_Check(self)) + return -1; + if (PySet_Check(self) && !_PyArg_NoKeywords("set()", kwds)) + return -1; + if (!PyArg_UnpackTuple(args, Py_TYPE(self)->tp_name, 0, 1, &iterable)) + return -1; + set_clear_internal(self); + self->hash = -1; + if (iterable == NULL) + return 0; + return set_update_internal(self, iterable); } static PySequenceMethods set_as_sequence = { - set_len, /* sq_length */ - 0, /* sq_concat */ - 0, /* sq_repeat */ - 0, /* sq_item */ - 0, /* sq_slice */ - 0, /* sq_ass_item */ - 0, /* sq_ass_slice */ - (objobjproc)set_contains, /* sq_contains */ + set_len, /* sq_length */ + 0, /* sq_concat */ + 0, /* sq_repeat */ + 0, /* sq_item */ + 0, /* sq_slice */ + 0, /* sq_ass_item */ + 0, /* sq_ass_slice */ + (objobjproc)set_contains, /* sq_contains */ }; /* set object ********************************************************/ @@ -2010,83 +2010,83 @@ #endif static PyMethodDef set_methods[] = { - {"add", (PyCFunction)set_add, METH_O, - add_doc}, - {"clear", (PyCFunction)set_clear, METH_NOARGS, - clear_doc}, - {"__contains__",(PyCFunction)set_direct_contains, METH_O | METH_COEXIST, - contains_doc}, - {"copy", (PyCFunction)set_copy, METH_NOARGS, - copy_doc}, - {"discard", (PyCFunction)set_discard, METH_O, - discard_doc}, - {"difference", (PyCFunction)set_difference_multi, METH_VARARGS, - difference_doc}, - {"difference_update", (PyCFunction)set_difference_update, METH_VARARGS, - difference_update_doc}, - {"intersection",(PyCFunction)set_intersection_multi, METH_VARARGS, - intersection_doc}, - {"intersection_update",(PyCFunction)set_intersection_update_multi, METH_VARARGS, - intersection_update_doc}, - {"isdisjoint", (PyCFunction)set_isdisjoint, METH_O, - isdisjoint_doc}, - {"issubset", (PyCFunction)set_issubset, METH_O, - issubset_doc}, - {"issuperset", (PyCFunction)set_issuperset, METH_O, - issuperset_doc}, - {"pop", (PyCFunction)set_pop, METH_NOARGS, - pop_doc}, - {"__reduce__", (PyCFunction)set_reduce, METH_NOARGS, - reduce_doc}, - {"remove", (PyCFunction)set_remove, METH_O, - remove_doc}, - {"__sizeof__", (PyCFunction)set_sizeof, METH_NOARGS, - sizeof_doc}, - {"symmetric_difference",(PyCFunction)set_symmetric_difference, METH_O, - symmetric_difference_doc}, - {"symmetric_difference_update",(PyCFunction)set_symmetric_difference_update, METH_O, - symmetric_difference_update_doc}, + {"add", (PyCFunction)set_add, METH_O, + add_doc}, + {"clear", (PyCFunction)set_clear, METH_NOARGS, + clear_doc}, + {"__contains__",(PyCFunction)set_direct_contains, METH_O | METH_COEXIST, + contains_doc}, + {"copy", (PyCFunction)set_copy, METH_NOARGS, + copy_doc}, + {"discard", (PyCFunction)set_discard, METH_O, + discard_doc}, + {"difference", (PyCFunction)set_difference_multi, METH_VARARGS, + difference_doc}, + {"difference_update", (PyCFunction)set_difference_update, METH_VARARGS, + difference_update_doc}, + {"intersection",(PyCFunction)set_intersection_multi, METH_VARARGS, + intersection_doc}, + {"intersection_update",(PyCFunction)set_intersection_update_multi, METH_VARARGS, + intersection_update_doc}, + {"isdisjoint", (PyCFunction)set_isdisjoint, METH_O, + isdisjoint_doc}, + {"issubset", (PyCFunction)set_issubset, METH_O, + issubset_doc}, + {"issuperset", (PyCFunction)set_issuperset, METH_O, + issuperset_doc}, + {"pop", (PyCFunction)set_pop, METH_NOARGS, + pop_doc}, + {"__reduce__", (PyCFunction)set_reduce, METH_NOARGS, + reduce_doc}, + {"remove", (PyCFunction)set_remove, METH_O, + remove_doc}, + {"__sizeof__", (PyCFunction)set_sizeof, METH_NOARGS, + sizeof_doc}, + {"symmetric_difference",(PyCFunction)set_symmetric_difference, METH_O, + symmetric_difference_doc}, + {"symmetric_difference_update",(PyCFunction)set_symmetric_difference_update, METH_O, + symmetric_difference_update_doc}, #ifdef Py_DEBUG - {"test_c_api", (PyCFunction)test_c_api, METH_NOARGS, - test_c_api_doc}, + {"test_c_api", (PyCFunction)test_c_api, METH_NOARGS, + test_c_api_doc}, #endif - {"union", (PyCFunction)set_union, METH_VARARGS, - union_doc}, - {"update", (PyCFunction)set_update, METH_VARARGS, - update_doc}, - {NULL, NULL} /* sentinel */ + {"union", (PyCFunction)set_union, METH_VARARGS, + union_doc}, + {"update", (PyCFunction)set_update, METH_VARARGS, + update_doc}, + {NULL, NULL} /* sentinel */ }; static PyNumberMethods set_as_number = { - 0, /*nb_add*/ - (binaryfunc)set_sub, /*nb_subtract*/ - 0, /*nb_multiply*/ - 0, /*nb_remainder*/ - 0, /*nb_divmod*/ - 0, /*nb_power*/ - 0, /*nb_negative*/ - 0, /*nb_positive*/ - 0, /*nb_absolute*/ - 0, /*nb_bool*/ - 0, /*nb_invert*/ - 0, /*nb_lshift*/ - 0, /*nb_rshift*/ - (binaryfunc)set_and, /*nb_and*/ - (binaryfunc)set_xor, /*nb_xor*/ - (binaryfunc)set_or, /*nb_or*/ - 0, /*nb_int*/ - 0, /*nb_reserved*/ - 0, /*nb_float*/ - 0, /*nb_inplace_add*/ - (binaryfunc)set_isub, /*nb_inplace_subtract*/ - 0, /*nb_inplace_multiply*/ - 0, /*nb_inplace_remainder*/ - 0, /*nb_inplace_power*/ - 0, /*nb_inplace_lshift*/ - 0, /*nb_inplace_rshift*/ - (binaryfunc)set_iand, /*nb_inplace_and*/ - (binaryfunc)set_ixor, /*nb_inplace_xor*/ - (binaryfunc)set_ior, /*nb_inplace_or*/ + 0, /*nb_add*/ + (binaryfunc)set_sub, /*nb_subtract*/ + 0, /*nb_multiply*/ + 0, /*nb_remainder*/ + 0, /*nb_divmod*/ + 0, /*nb_power*/ + 0, /*nb_negative*/ + 0, /*nb_positive*/ + 0, /*nb_absolute*/ + 0, /*nb_bool*/ + 0, /*nb_invert*/ + 0, /*nb_lshift*/ + 0, /*nb_rshift*/ + (binaryfunc)set_and, /*nb_and*/ + (binaryfunc)set_xor, /*nb_xor*/ + (binaryfunc)set_or, /*nb_or*/ + 0, /*nb_int*/ + 0, /*nb_reserved*/ + 0, /*nb_float*/ + 0, /*nb_inplace_add*/ + (binaryfunc)set_isub, /*nb_inplace_subtract*/ + 0, /*nb_inplace_multiply*/ + 0, /*nb_inplace_remainder*/ + 0, /*nb_inplace_power*/ + 0, /*nb_inplace_lshift*/ + 0, /*nb_inplace_rshift*/ + (binaryfunc)set_iand, /*nb_inplace_and*/ + (binaryfunc)set_ixor, /*nb_inplace_xor*/ + (binaryfunc)set_ior, /*nb_inplace_or*/ }; PyDoc_STRVAR(set_doc, @@ -2096,95 +2096,95 @@ Build an unordered collection of unique elements."); PyTypeObject PySet_Type = { - PyVarObject_HEAD_INIT(&PyType_Type, 0) - "set", /* tp_name */ - sizeof(PySetObject), /* tp_basicsize */ - 0, /* tp_itemsize */ - /* methods */ - (destructor)set_dealloc, /* tp_dealloc */ - 0, /* tp_print */ - 0, /* tp_getattr */ - 0, /* tp_setattr */ - 0, /* tp_reserved */ - (reprfunc)set_repr, /* tp_repr */ - &set_as_number, /* tp_as_number */ - &set_as_sequence, /* tp_as_sequence */ - 0, /* tp_as_mapping */ - (hashfunc)PyObject_HashNotImplemented, /* 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 | - Py_TPFLAGS_BASETYPE, /* tp_flags */ - set_doc, /* tp_doc */ - (traverseproc)set_traverse, /* tp_traverse */ - (inquiry)set_clear_internal, /* tp_clear */ - (richcmpfunc)set_richcompare, /* tp_richcompare */ - offsetof(PySetObject, weakreflist), /* tp_weaklistoffset */ - (getiterfunc)set_iter, /* tp_iter */ - 0, /* tp_iternext */ - set_methods, /* tp_methods */ - 0, /* tp_members */ - 0, /* tp_getset */ - 0, /* tp_base */ - 0, /* tp_dict */ - 0, /* tp_descr_get */ - 0, /* tp_descr_set */ - 0, /* tp_dictoffset */ - (initproc)set_init, /* tp_init */ - PyType_GenericAlloc, /* tp_alloc */ - set_new, /* tp_new */ - PyObject_GC_Del, /* tp_free */ + PyVarObject_HEAD_INIT(&PyType_Type, 0) + "set", /* tp_name */ + sizeof(PySetObject), /* tp_basicsize */ + 0, /* tp_itemsize */ + /* methods */ + (destructor)set_dealloc, /* tp_dealloc */ + 0, /* tp_print */ + 0, /* tp_getattr */ + 0, /* tp_setattr */ + 0, /* tp_reserved */ + (reprfunc)set_repr, /* tp_repr */ + &set_as_number, /* tp_as_number */ + &set_as_sequence, /* tp_as_sequence */ + 0, /* tp_as_mapping */ + (hashfunc)PyObject_HashNotImplemented, /* 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 | + Py_TPFLAGS_BASETYPE, /* tp_flags */ + set_doc, /* tp_doc */ + (traverseproc)set_traverse, /* tp_traverse */ + (inquiry)set_clear_internal, /* tp_clear */ + (richcmpfunc)set_richcompare, /* tp_richcompare */ + offsetof(PySetObject, weakreflist), /* tp_weaklistoffset */ + (getiterfunc)set_iter, /* tp_iter */ + 0, /* tp_iternext */ + set_methods, /* tp_methods */ + 0, /* tp_members */ + 0, /* tp_getset */ + 0, /* tp_base */ + 0, /* tp_dict */ + 0, /* tp_descr_get */ + 0, /* tp_descr_set */ + 0, /* tp_dictoffset */ + (initproc)set_init, /* tp_init */ + PyType_GenericAlloc, /* tp_alloc */ + set_new, /* tp_new */ + PyObject_GC_Del, /* tp_free */ }; /* frozenset object ********************************************************/ static PyMethodDef frozenset_methods[] = { - {"__contains__",(PyCFunction)set_direct_contains, METH_O | METH_COEXIST, - contains_doc}, - {"copy", (PyCFunction)frozenset_copy, METH_NOARGS, - copy_doc}, - {"difference", (PyCFunction)set_difference_multi, METH_VARARGS, - difference_doc}, - {"intersection",(PyCFunction)set_intersection_multi, METH_VARARGS, - intersection_doc}, - {"isdisjoint", (PyCFunction)set_isdisjoint, METH_O, - isdisjoint_doc}, - {"issubset", (PyCFunction)set_issubset, METH_O, - issubset_doc}, - {"issuperset", (PyCFunction)set_issuperset, METH_O, - issuperset_doc}, - {"__reduce__", (PyCFunction)set_reduce, METH_NOARGS, - reduce_doc}, - {"__sizeof__", (PyCFunction)set_sizeof, METH_NOARGS, - sizeof_doc}, - {"symmetric_difference",(PyCFunction)set_symmetric_difference, METH_O, - symmetric_difference_doc}, - {"union", (PyCFunction)set_union, METH_VARARGS, - union_doc}, - {NULL, NULL} /* sentinel */ + {"__contains__",(PyCFunction)set_direct_contains, METH_O | METH_COEXIST, + contains_doc}, + {"copy", (PyCFunction)frozenset_copy, METH_NOARGS, + copy_doc}, + {"difference", (PyCFunction)set_difference_multi, METH_VARARGS, + difference_doc}, + {"intersection",(PyCFunction)set_intersection_multi, METH_VARARGS, + intersection_doc}, + {"isdisjoint", (PyCFunction)set_isdisjoint, METH_O, + isdisjoint_doc}, + {"issubset", (PyCFunction)set_issubset, METH_O, + issubset_doc}, + {"issuperset", (PyCFunction)set_issuperset, METH_O, + issuperset_doc}, + {"__reduce__", (PyCFunction)set_reduce, METH_NOARGS, + reduce_doc}, + {"__sizeof__", (PyCFunction)set_sizeof, METH_NOARGS, + sizeof_doc}, + {"symmetric_difference",(PyCFunction)set_symmetric_difference, METH_O, + symmetric_difference_doc}, + {"union", (PyCFunction)set_union, METH_VARARGS, + union_doc}, + {NULL, NULL} /* sentinel */ }; static PyNumberMethods frozenset_as_number = { - 0, /*nb_add*/ - (binaryfunc)set_sub, /*nb_subtract*/ - 0, /*nb_multiply*/ - 0, /*nb_remainder*/ - 0, /*nb_divmod*/ - 0, /*nb_power*/ - 0, /*nb_negative*/ - 0, /*nb_positive*/ - 0, /*nb_absolute*/ - 0, /*nb_bool*/ - 0, /*nb_invert*/ - 0, /*nb_lshift*/ - 0, /*nb_rshift*/ - (binaryfunc)set_and, /*nb_and*/ - (binaryfunc)set_xor, /*nb_xor*/ - (binaryfunc)set_or, /*nb_or*/ + 0, /*nb_add*/ + (binaryfunc)set_sub, /*nb_subtract*/ + 0, /*nb_multiply*/ + 0, /*nb_remainder*/ + 0, /*nb_divmod*/ + 0, /*nb_power*/ + 0, /*nb_negative*/ + 0, /*nb_positive*/ + 0, /*nb_absolute*/ + 0, /*nb_bool*/ + 0, /*nb_invert*/ + 0, /*nb_lshift*/ + 0, /*nb_rshift*/ + (binaryfunc)set_and, /*nb_and*/ + (binaryfunc)set_xor, /*nb_xor*/ + (binaryfunc)set_or, /*nb_or*/ }; PyDoc_STRVAR(frozenset_doc, @@ -2194,47 +2194,47 @@ Build an immutable unordered collection of unique elements."); PyTypeObject PyFrozenSet_Type = { - PyVarObject_HEAD_INIT(&PyType_Type, 0) - "frozenset", /* tp_name */ - sizeof(PySetObject), /* tp_basicsize */ - 0, /* tp_itemsize */ - /* methods */ - (destructor)set_dealloc, /* tp_dealloc */ - 0, /* tp_print */ - 0, /* tp_getattr */ - 0, /* tp_setattr */ - 0, /* tp_reserved */ - (reprfunc)set_repr, /* tp_repr */ - &frozenset_as_number, /* tp_as_number */ - &set_as_sequence, /* tp_as_sequence */ - 0, /* tp_as_mapping */ - frozenset_hash, /* 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 | - Py_TPFLAGS_BASETYPE, /* tp_flags */ - frozenset_doc, /* tp_doc */ - (traverseproc)set_traverse, /* tp_traverse */ - (inquiry)set_clear_internal, /* tp_clear */ - (richcmpfunc)set_richcompare, /* tp_richcompare */ - offsetof(PySetObject, weakreflist), /* tp_weaklistoffset */ - (getiterfunc)set_iter, /* tp_iter */ - 0, /* tp_iternext */ - frozenset_methods, /* tp_methods */ - 0, /* tp_members */ - 0, /* tp_getset */ - 0, /* tp_base */ - 0, /* tp_dict */ - 0, /* tp_descr_get */ - 0, /* tp_descr_set */ - 0, /* tp_dictoffset */ - 0, /* tp_init */ - PyType_GenericAlloc, /* tp_alloc */ - frozenset_new, /* tp_new */ - PyObject_GC_Del, /* tp_free */ + PyVarObject_HEAD_INIT(&PyType_Type, 0) + "frozenset", /* tp_name */ + sizeof(PySetObject), /* tp_basicsize */ + 0, /* tp_itemsize */ + /* methods */ + (destructor)set_dealloc, /* tp_dealloc */ + 0, /* tp_print */ + 0, /* tp_getattr */ + 0, /* tp_setattr */ + 0, /* tp_reserved */ + (reprfunc)set_repr, /* tp_repr */ + &frozenset_as_number, /* tp_as_number */ + &set_as_sequence, /* tp_as_sequence */ + 0, /* tp_as_mapping */ + frozenset_hash, /* 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 | + Py_TPFLAGS_BASETYPE, /* tp_flags */ + frozenset_doc, /* tp_doc */ + (traverseproc)set_traverse, /* tp_traverse */ + (inquiry)set_clear_internal, /* tp_clear */ + (richcmpfunc)set_richcompare, /* tp_richcompare */ + offsetof(PySetObject, weakreflist), /* tp_weaklistoffset */ + (getiterfunc)set_iter, /* tp_iter */ + 0, /* tp_iternext */ + frozenset_methods, /* tp_methods */ + 0, /* tp_members */ + 0, /* tp_getset */ + 0, /* tp_base */ + 0, /* tp_dict */ + 0, /* tp_descr_get */ + 0, /* tp_descr_set */ + 0, /* tp_dictoffset */ + 0, /* tp_init */ + PyType_GenericAlloc, /* tp_alloc */ + frozenset_new, /* tp_new */ + PyObject_GC_Del, /* tp_free */ }; @@ -2243,238 +2243,238 @@ PyObject * PySet_New(PyObject *iterable) { - return make_new_set(&PySet_Type, iterable); + return make_new_set(&PySet_Type, iterable); } PyObject * PyFrozenSet_New(PyObject *iterable) { - return make_new_set(&PyFrozenSet_Type, iterable); + return make_new_set(&PyFrozenSet_Type, iterable); } Py_ssize_t PySet_Size(PyObject *anyset) { - if (!PyAnySet_Check(anyset)) { - PyErr_BadInternalCall(); - return -1; - } - return PySet_GET_SIZE(anyset); + if (!PyAnySet_Check(anyset)) { + PyErr_BadInternalCall(); + return -1; + } + return PySet_GET_SIZE(anyset); } int PySet_Clear(PyObject *set) { - if (!PySet_Check(set)) { - PyErr_BadInternalCall(); - return -1; - } - return set_clear_internal((PySetObject *)set); + if (!PySet_Check(set)) { + PyErr_BadInternalCall(); + return -1; + } + return set_clear_internal((PySetObject *)set); } int PySet_Contains(PyObject *anyset, PyObject *key) { - if (!PyAnySet_Check(anyset)) { - PyErr_BadInternalCall(); - return -1; - } - return set_contains_key((PySetObject *)anyset, key); + if (!PyAnySet_Check(anyset)) { + PyErr_BadInternalCall(); + return -1; + } + return set_contains_key((PySetObject *)anyset, key); } int PySet_Discard(PyObject *set, PyObject *key) { - if (!PySet_Check(set)) { - PyErr_BadInternalCall(); - return -1; - } - return set_discard_key((PySetObject *)set, key); + if (!PySet_Check(set)) { + PyErr_BadInternalCall(); + return -1; + } + return set_discard_key((PySetObject *)set, key); } int PySet_Add(PyObject *anyset, PyObject *key) { - if (!PySet_Check(anyset) && - (!PyFrozenSet_Check(anyset) || Py_REFCNT(anyset) != 1)) { - PyErr_BadInternalCall(); - return -1; - } - return set_add_key((PySetObject *)anyset, key); + if (!PySet_Check(anyset) && + (!PyFrozenSet_Check(anyset) || Py_REFCNT(anyset) != 1)) { + PyErr_BadInternalCall(); + return -1; + } + return set_add_key((PySetObject *)anyset, key); } int _PySet_NextEntry(PyObject *set, Py_ssize_t *pos, PyObject **key, long *hash) { - setentry *entry; + setentry *entry; - if (!PyAnySet_Check(set)) { - PyErr_BadInternalCall(); - return -1; - } - if (set_next((PySetObject *)set, pos, &entry) == 0) - return 0; - *key = entry->key; - *hash = entry->hash; - return 1; + if (!PyAnySet_Check(set)) { + PyErr_BadInternalCall(); + return -1; + } + if (set_next((PySetObject *)set, pos, &entry) == 0) + return 0; + *key = entry->key; + *hash = entry->hash; + return 1; } PyObject * PySet_Pop(PyObject *set) { - if (!PySet_Check(set)) { - PyErr_BadInternalCall(); - return NULL; - } - return set_pop((PySetObject *)set); + if (!PySet_Check(set)) { + PyErr_BadInternalCall(); + return NULL; + } + return set_pop((PySetObject *)set); } int _PySet_Update(PyObject *set, PyObject *iterable) { - if (!PySet_Check(set)) { - PyErr_BadInternalCall(); - return -1; - } - return set_update_internal((PySetObject *)set, iterable); + if (!PySet_Check(set)) { + PyErr_BadInternalCall(); + return -1; + } + return set_update_internal((PySetObject *)set, iterable); } #ifdef Py_DEBUG -/* Test code to be called with any three element set. +/* Test code to be called with any three element set. Returns True and original set is restored. */ -#define assertRaises(call_return_value, exception) \ - do { \ - assert(call_return_value); \ - assert(PyErr_ExceptionMatches(exception)); \ - PyErr_Clear(); \ - } while(0) +#define assertRaises(call_return_value, exception) \ + do { \ + assert(call_return_value); \ + assert(PyErr_ExceptionMatches(exception)); \ + PyErr_Clear(); \ + } while(0) static PyObject * test_c_api(PySetObject *so) { - Py_ssize_t count; - char *s; - Py_ssize_t i; - PyObject *elem=NULL, *dup=NULL, *t, *f, *dup2, *x; - PyObject *ob = (PyObject *)so; - long hash; - PyObject *str; - - /* Verify preconditions */ - assert(PyAnySet_Check(ob)); - assert(PyAnySet_CheckExact(ob)); - assert(!PyFrozenSet_CheckExact(ob)); - - /* so.clear(); so |= set("abc"); */ - str = PyUnicode_FromString("abc"); - if (str == NULL) - return NULL; - set_clear_internal(so); - if (set_update_internal(so, str) == -1) { - Py_DECREF(str); - return NULL; - } - Py_DECREF(str); - - /* Exercise type/size checks */ - assert(PySet_Size(ob) == 3); - assert(PySet_GET_SIZE(ob) == 3); - - /* Raise TypeError for non-iterable constructor arguments */ - assertRaises(PySet_New(Py_None) == NULL, PyExc_TypeError); - assertRaises(PyFrozenSet_New(Py_None) == NULL, PyExc_TypeError); - - /* Raise TypeError for unhashable key */ - dup = PySet_New(ob); - assertRaises(PySet_Discard(ob, dup) == -1, PyExc_TypeError); - assertRaises(PySet_Contains(ob, dup) == -1, PyExc_TypeError); - assertRaises(PySet_Add(ob, dup) == -1, PyExc_TypeError); - - /* Exercise successful pop, contains, add, and discard */ - elem = PySet_Pop(ob); - assert(PySet_Contains(ob, elem) == 0); - assert(PySet_GET_SIZE(ob) == 2); - assert(PySet_Add(ob, elem) == 0); - assert(PySet_Contains(ob, elem) == 1); - assert(PySet_GET_SIZE(ob) == 3); - assert(PySet_Discard(ob, elem) == 1); - assert(PySet_GET_SIZE(ob) == 2); - assert(PySet_Discard(ob, elem) == 0); - assert(PySet_GET_SIZE(ob) == 2); - - /* Exercise clear */ - dup2 = PySet_New(dup); - assert(PySet_Clear(dup2) == 0); - assert(PySet_Size(dup2) == 0); - Py_DECREF(dup2); - - /* Raise SystemError on clear or update of frozen set */ - f = PyFrozenSet_New(dup); - assertRaises(PySet_Clear(f) == -1, PyExc_SystemError); - assertRaises(_PySet_Update(f, dup) == -1, PyExc_SystemError); - assert(PySet_Add(f, elem) == 0); - Py_INCREF(f); - assertRaises(PySet_Add(f, elem) == -1, PyExc_SystemError); - Py_DECREF(f); - Py_DECREF(f); - - /* Exercise direct iteration */ - i = 0, count = 0; - while (_PySet_NextEntry((PyObject *)dup, &i, &x, &hash)) { - s = _PyUnicode_AsString(x); - assert(s && (s[0] == 'a' || s[0] == 'b' || s[0] == 'c')); - count++; - } - assert(count == 3); - - /* Exercise updates */ - dup2 = PySet_New(NULL); - assert(_PySet_Update(dup2, dup) == 0); - assert(PySet_Size(dup2) == 3); - assert(_PySet_Update(dup2, dup) == 0); - assert(PySet_Size(dup2) == 3); - Py_DECREF(dup2); - - /* Raise SystemError when self argument is not a set or frozenset. */ - t = PyTuple_New(0); - assertRaises(PySet_Size(t) == -1, PyExc_SystemError); - assertRaises(PySet_Contains(t, elem) == -1, PyExc_SystemError); - Py_DECREF(t); - - /* Raise SystemError when self argument is not a set. */ - f = PyFrozenSet_New(dup); - assert(PySet_Size(f) == 3); - assert(PyFrozenSet_CheckExact(f)); - assertRaises(PySet_Discard(f, elem) == -1, PyExc_SystemError); - assertRaises(PySet_Pop(f) == NULL, PyExc_SystemError); - Py_DECREF(f); - - /* Raise KeyError when popping from an empty set */ - assert(PyNumber_InPlaceSubtract(ob, ob) == ob); - Py_DECREF(ob); - assert(PySet_GET_SIZE(ob) == 0); - assertRaises(PySet_Pop(ob) == NULL, PyExc_KeyError); - - /* Restore the set from the copy using the PyNumber API */ - assert(PyNumber_InPlaceOr(ob, dup) == ob); - Py_DECREF(ob); - - /* Verify constructors accept NULL arguments */ - f = PySet_New(NULL); - assert(f != NULL); - assert(PySet_GET_SIZE(f) == 0); - Py_DECREF(f); - f = PyFrozenSet_New(NULL); - assert(f != NULL); - assert(PyFrozenSet_CheckExact(f)); - assert(PySet_GET_SIZE(f) == 0); - Py_DECREF(f); - - Py_DECREF(elem); - Py_DECREF(dup); - Py_RETURN_TRUE; + Py_ssize_t count; + char *s; + Py_ssize_t i; + PyObject *elem=NULL, *dup=NULL, *t, *f, *dup2, *x; + PyObject *ob = (PyObject *)so; + long hash; + PyObject *str; + + /* Verify preconditions */ + assert(PyAnySet_Check(ob)); + assert(PyAnySet_CheckExact(ob)); + assert(!PyFrozenSet_CheckExact(ob)); + + /* so.clear(); so |= set("abc"); */ + str = PyUnicode_FromString("abc"); + if (str == NULL) + return NULL; + set_clear_internal(so); + if (set_update_internal(so, str) == -1) { + Py_DECREF(str); + return NULL; + } + Py_DECREF(str); + + /* Exercise type/size checks */ + assert(PySet_Size(ob) == 3); + assert(PySet_GET_SIZE(ob) == 3); + + /* Raise TypeError for non-iterable constructor arguments */ + assertRaises(PySet_New(Py_None) == NULL, PyExc_TypeError); + assertRaises(PyFrozenSet_New(Py_None) == NULL, PyExc_TypeError); + + /* Raise TypeError for unhashable key */ + dup = PySet_New(ob); + assertRaises(PySet_Discard(ob, dup) == -1, PyExc_TypeError); + assertRaises(PySet_Contains(ob, dup) == -1, PyExc_TypeError); + assertRaises(PySet_Add(ob, dup) == -1, PyExc_TypeError); + + /* Exercise successful pop, contains, add, and discard */ + elem = PySet_Pop(ob); + assert(PySet_Contains(ob, elem) == 0); + assert(PySet_GET_SIZE(ob) == 2); + assert(PySet_Add(ob, elem) == 0); + assert(PySet_Contains(ob, elem) == 1); + assert(PySet_GET_SIZE(ob) == 3); + assert(PySet_Discard(ob, elem) == 1); + assert(PySet_GET_SIZE(ob) == 2); + assert(PySet_Discard(ob, elem) == 0); + assert(PySet_GET_SIZE(ob) == 2); + + /* Exercise clear */ + dup2 = PySet_New(dup); + assert(PySet_Clear(dup2) == 0); + assert(PySet_Size(dup2) == 0); + Py_DECREF(dup2); + + /* Raise SystemError on clear or update of frozen set */ + f = PyFrozenSet_New(dup); + assertRaises(PySet_Clear(f) == -1, PyExc_SystemError); + assertRaises(_PySet_Update(f, dup) == -1, PyExc_SystemError); + assert(PySet_Add(f, elem) == 0); + Py_INCREF(f); + assertRaises(PySet_Add(f, elem) == -1, PyExc_SystemError); + Py_DECREF(f); + Py_DECREF(f); + + /* Exercise direct iteration */ + i = 0, count = 0; + while (_PySet_NextEntry((PyObject *)dup, &i, &x, &hash)) { + s = _PyUnicode_AsString(x); + assert(s && (s[0] == 'a' || s[0] == 'b' || s[0] == 'c')); + count++; + } + assert(count == 3); + + /* Exercise updates */ + dup2 = PySet_New(NULL); + assert(_PySet_Update(dup2, dup) == 0); + assert(PySet_Size(dup2) == 3); + assert(_PySet_Update(dup2, dup) == 0); + assert(PySet_Size(dup2) == 3); + Py_DECREF(dup2); + + /* Raise SystemError when self argument is not a set or frozenset. */ + t = PyTuple_New(0); + assertRaises(PySet_Size(t) == -1, PyExc_SystemError); + assertRaises(PySet_Contains(t, elem) == -1, PyExc_SystemError); + Py_DECREF(t); + + /* Raise SystemError when self argument is not a set. */ + f = PyFrozenSet_New(dup); + assert(PySet_Size(f) == 3); + assert(PyFrozenSet_CheckExact(f)); + assertRaises(PySet_Discard(f, elem) == -1, PyExc_SystemError); + assertRaises(PySet_Pop(f) == NULL, PyExc_SystemError); + Py_DECREF(f); + + /* Raise KeyError when popping from an empty set */ + assert(PyNumber_InPlaceSubtract(ob, ob) == ob); + Py_DECREF(ob); + assert(PySet_GET_SIZE(ob) == 0); + assertRaises(PySet_Pop(ob) == NULL, PyExc_KeyError); + + /* Restore the set from the copy using the PyNumber API */ + assert(PyNumber_InPlaceOr(ob, dup) == ob); + Py_DECREF(ob); + + /* Verify constructors accept NULL arguments */ + f = PySet_New(NULL); + assert(f != NULL); + assert(PySet_GET_SIZE(f) == 0); + Py_DECREF(f); + f = PyFrozenSet_New(NULL); + assert(f != NULL); + assert(PyFrozenSet_CheckExact(f)); + assert(PySet_GET_SIZE(f) == 0); + Py_DECREF(f); + + Py_DECREF(elem); + Py_DECREF(dup); + Py_RETURN_TRUE; } #undef assertRaises Modified: python/branches/py3k-jit/Objects/sliceobject.c ============================================================================== --- python/branches/py3k-jit/Objects/sliceobject.c (original) +++ python/branches/py3k-jit/Objects/sliceobject.c Mon May 10 23:55:43 2010 @@ -7,7 +7,7 @@ for this file. */ -/* +/* Py_Ellipsis encodes the '...' rubber index token. It is similar to the Py_NoneStruct in that there is no way to create other objects of this type and there is exactly one in existence. @@ -19,35 +19,35 @@ static PyObject * ellipsis_repr(PyObject *op) { - return PyUnicode_FromString("Ellipsis"); + return PyUnicode_FromString("Ellipsis"); } PyTypeObject PyEllipsis_Type = { - PyVarObject_HEAD_INIT(&PyType_Type, 0) - "ellipsis", /* tp_name */ - 0, /* tp_basicsize */ - 0, /* tp_itemsize */ - 0, /*never called*/ /* tp_dealloc */ - 0, /* tp_print */ - 0, /* tp_getattr */ - 0, /* tp_setattr */ - 0, /* tp_reserved */ - ellipsis_repr, /* tp_repr */ - 0, /* tp_as_number */ - 0, /* tp_as_sequence */ - 0, /* tp_as_mapping */ - 0, /* tp_hash */ - 0, /* tp_call */ - 0, /* tp_str */ - PyObject_GenericGetAttr, /* tp_getattro */ - 0, /* tp_setattro */ - 0, /* tp_as_buffer */ - Py_TPFLAGS_DEFAULT, /* tp_flags */ + PyVarObject_HEAD_INIT(&PyType_Type, 0) + "ellipsis", /* tp_name */ + 0, /* tp_basicsize */ + 0, /* tp_itemsize */ + 0, /*never called*/ /* tp_dealloc */ + 0, /* tp_print */ + 0, /* tp_getattr */ + 0, /* tp_setattr */ + 0, /* tp_reserved */ + ellipsis_repr, /* tp_repr */ + 0, /* tp_as_number */ + 0, /* tp_as_sequence */ + 0, /* tp_as_mapping */ + 0, /* tp_hash */ + 0, /* tp_call */ + 0, /* tp_str */ + PyObject_GenericGetAttr, /* tp_getattro */ + 0, /* tp_setattro */ + 0, /* tp_as_buffer */ + Py_TPFLAGS_DEFAULT, /* tp_flags */ }; PyObject _Py_EllipsisObject = { - _PyObject_EXTRA_INIT - 1, &PyEllipsis_Type + _PyObject_EXTRA_INIT + 1, &PyEllipsis_Type }; @@ -60,154 +60,154 @@ PyObject * PySlice_New(PyObject *start, PyObject *stop, PyObject *step) { - PySliceObject *obj = PyObject_New(PySliceObject, &PySlice_Type); + PySliceObject *obj = PyObject_New(PySliceObject, &PySlice_Type); - if (obj == NULL) - return NULL; + if (obj == NULL) + return NULL; - if (step == NULL) step = Py_None; - Py_INCREF(step); - if (start == NULL) start = Py_None; - Py_INCREF(start); - if (stop == NULL) stop = Py_None; - Py_INCREF(stop); - - obj->step = step; - obj->start = start; - obj->stop = stop; + if (step == NULL) step = Py_None; + Py_INCREF(step); + if (start == NULL) start = Py_None; + Py_INCREF(start); + if (stop == NULL) stop = Py_None; + Py_INCREF(stop); + + obj->step = step; + obj->start = start; + obj->stop = stop; - return (PyObject *) obj; + return (PyObject *) obj; } PyObject * _PySlice_FromIndices(Py_ssize_t istart, Py_ssize_t istop) { - PyObject *start, *end, *slice; - start = PyLong_FromSsize_t(istart); - if (!start) - return NULL; - end = PyLong_FromSsize_t(istop); - if (!end) { - Py_DECREF(start); - return NULL; - } - - slice = PySlice_New(start, end, NULL); - Py_DECREF(start); - Py_DECREF(end); - return slice; + PyObject *start, *end, *slice; + start = PyLong_FromSsize_t(istart); + if (!start) + return NULL; + end = PyLong_FromSsize_t(istop); + if (!end) { + Py_DECREF(start); + return NULL; + } + + slice = PySlice_New(start, end, NULL); + Py_DECREF(start); + Py_DECREF(end); + return slice; } int PySlice_GetIndices(PySliceObject *r, Py_ssize_t length, Py_ssize_t *start, Py_ssize_t *stop, Py_ssize_t *step) { - /* XXX support long ints */ - if (r->step == Py_None) { - *step = 1; - } else { - if (!PyLong_Check(r->step)) return -1; - *step = PyLong_AsSsize_t(r->step); - } - if (r->start == Py_None) { - *start = *step < 0 ? length-1 : 0; - } else { - if (!PyLong_Check(r->start)) return -1; - *start = PyLong_AsSsize_t(r->start); - if (*start < 0) *start += length; - } - if (r->stop == Py_None) { - *stop = *step < 0 ? -1 : length; - } else { - if (!PyLong_Check(r->stop)) return -1; - *stop = PyLong_AsSsize_t(r->stop); - if (*stop < 0) *stop += length; - } - if (*stop > length) return -1; - if (*start >= length) return -1; - if (*step == 0) return -1; - return 0; + /* XXX support long ints */ + if (r->step == Py_None) { + *step = 1; + } else { + if (!PyLong_Check(r->step)) return -1; + *step = PyLong_AsSsize_t(r->step); + } + if (r->start == Py_None) { + *start = *step < 0 ? length-1 : 0; + } else { + if (!PyLong_Check(r->start)) return -1; + *start = PyLong_AsSsize_t(r->start); + if (*start < 0) *start += length; + } + if (r->stop == Py_None) { + *stop = *step < 0 ? -1 : length; + } else { + if (!PyLong_Check(r->stop)) return -1; + *stop = PyLong_AsSsize_t(r->stop); + if (*stop < 0) *stop += length; + } + if (*stop > length) return -1; + if (*start >= length) return -1; + if (*step == 0) return -1; + return 0; } int PySlice_GetIndicesEx(PySliceObject *r, Py_ssize_t length, - Py_ssize_t *start, Py_ssize_t *stop, Py_ssize_t *step, Py_ssize_t *slicelength) + Py_ssize_t *start, Py_ssize_t *stop, Py_ssize_t *step, Py_ssize_t *slicelength) { - /* this is harder to get right than you might think */ + /* this is harder to get right than you might think */ - Py_ssize_t defstart, defstop; + Py_ssize_t defstart, defstop; - if (r->step == Py_None) { - *step = 1; - } - else { - if (!_PyEval_SliceIndex(r->step, step)) return -1; - if (*step == 0) { - PyErr_SetString(PyExc_ValueError, - "slice step cannot be zero"); - return -1; - } - } - - defstart = *step < 0 ? length-1 : 0; - defstop = *step < 0 ? -1 : length; - - if (r->start == Py_None) { - *start = defstart; - } - else { - if (!_PyEval_SliceIndex(r->start, start)) return -1; - if (*start < 0) *start += length; - if (*start < 0) *start = (*step < 0) ? -1 : 0; - if (*start >= length) - *start = (*step < 0) ? length - 1 : length; - } - - if (r->stop == Py_None) { - *stop = defstop; - } - else { - if (!_PyEval_SliceIndex(r->stop, stop)) return -1; - if (*stop < 0) *stop += length; - if (*stop < 0) *stop = (*step < 0) ? -1 : 0; - if (*stop >= length) - *stop = (*step < 0) ? length - 1 : length; - } - - if ((*step < 0 && *stop >= *start) - || (*step > 0 && *start >= *stop)) { - *slicelength = 0; - } - else if (*step < 0) { - *slicelength = (*stop-*start+1)/(*step)+1; - } - else { - *slicelength = (*stop-*start-1)/(*step)+1; - } + if (r->step == Py_None) { + *step = 1; + } + else { + if (!_PyEval_SliceIndex(r->step, step)) return -1; + if (*step == 0) { + PyErr_SetString(PyExc_ValueError, + "slice step cannot be zero"); + return -1; + } + } + + defstart = *step < 0 ? length-1 : 0; + defstop = *step < 0 ? -1 : length; + + if (r->start == Py_None) { + *start = defstart; + } + else { + if (!_PyEval_SliceIndex(r->start, start)) return -1; + if (*start < 0) *start += length; + if (*start < 0) *start = (*step < 0) ? -1 : 0; + if (*start >= length) + *start = (*step < 0) ? length - 1 : length; + } + + if (r->stop == Py_None) { + *stop = defstop; + } + else { + if (!_PyEval_SliceIndex(r->stop, stop)) return -1; + if (*stop < 0) *stop += length; + if (*stop < 0) *stop = (*step < 0) ? -1 : 0; + if (*stop >= length) + *stop = (*step < 0) ? length - 1 : length; + } + + if ((*step < 0 && *stop >= *start) + || (*step > 0 && *start >= *stop)) { + *slicelength = 0; + } + else if (*step < 0) { + *slicelength = (*stop-*start+1)/(*step)+1; + } + else { + *slicelength = (*stop-*start-1)/(*step)+1; + } - return 0; + return 0; } static PyObject * slice_new(PyTypeObject *type, PyObject *args, PyObject *kw) { - PyObject *start, *stop, *step; + PyObject *start, *stop, *step; - start = stop = step = NULL; + start = stop = step = NULL; - if (!_PyArg_NoKeywords("slice()", kw)) - return NULL; + if (!_PyArg_NoKeywords("slice()", kw)) + return NULL; - if (!PyArg_UnpackTuple(args, "slice", 1, 3, &start, &stop, &step)) - return NULL; - - /* This swapping of stop and start is to maintain similarity with - range(). */ - if (stop == NULL) { - stop = start; - start = NULL; - } - return PySlice_New(start, stop, step); + if (!PyArg_UnpackTuple(args, "slice", 1, 3, &start, &stop, &step)) + return NULL; + + /* This swapping of stop and start is to maintain similarity with + range(). */ + if (stop == NULL) { + stop = start; + start = NULL; + } + return PySlice_New(start, stop, step); } PyDoc_STRVAR(slice_doc, @@ -218,42 +218,42 @@ static void slice_dealloc(PySliceObject *r) { - Py_DECREF(r->step); - Py_DECREF(r->start); - Py_DECREF(r->stop); - PyObject_Del(r); + Py_DECREF(r->step); + Py_DECREF(r->start); + Py_DECREF(r->stop); + PyObject_Del(r); } static PyObject * slice_repr(PySliceObject *r) { - return PyUnicode_FromFormat("slice(%R, %R, %R)", r->start, r->stop, r->step); + return PyUnicode_FromFormat("slice(%R, %R, %R)", r->start, r->stop, r->step); } static PyMemberDef slice_members[] = { - {"start", T_OBJECT, offsetof(PySliceObject, start), READONLY}, - {"stop", T_OBJECT, offsetof(PySliceObject, stop), READONLY}, - {"step", T_OBJECT, offsetof(PySliceObject, step), READONLY}, - {0} + {"start", T_OBJECT, offsetof(PySliceObject, start), READONLY}, + {"stop", T_OBJECT, offsetof(PySliceObject, stop), READONLY}, + {"step", T_OBJECT, offsetof(PySliceObject, step), READONLY}, + {0} }; static PyObject* slice_indices(PySliceObject* self, PyObject* len) { - Py_ssize_t ilen, start, stop, step, slicelength; + Py_ssize_t ilen, start, stop, step, slicelength; - ilen = PyNumber_AsSsize_t(len, PyExc_OverflowError); + ilen = PyNumber_AsSsize_t(len, PyExc_OverflowError); - if (ilen == -1 && PyErr_Occurred()) { - return NULL; - } + if (ilen == -1 && PyErr_Occurred()) { + return NULL; + } - if (PySlice_GetIndicesEx(self, ilen, &start, &stop, - &step, &slicelength) < 0) { - return NULL; - } + if (PySlice_GetIndicesEx(self, ilen, &start, &stop, + &step, &slicelength) < 0) { + return NULL; + } - return Py_BuildValue("(nnn)", start, stop, step); + return Py_BuildValue("(nnn)", start, stop, step); } PyDoc_STRVAR(slice_indices_doc, @@ -267,119 +267,119 @@ static PyObject * slice_reduce(PySliceObject* self) { - return Py_BuildValue("O(OOO)", Py_TYPE(self), self->start, self->stop, self->step); + return Py_BuildValue("O(OOO)", Py_TYPE(self), self->start, self->stop, self->step); } PyDoc_STRVAR(reduce_doc, "Return state information for pickling."); static PyMethodDef slice_methods[] = { - {"indices", (PyCFunction)slice_indices, - METH_O, slice_indices_doc}, - {"__reduce__", (PyCFunction)slice_reduce, - METH_NOARGS, reduce_doc}, - {NULL, NULL} + {"indices", (PyCFunction)slice_indices, + METH_O, slice_indices_doc}, + {"__reduce__", (PyCFunction)slice_reduce, + METH_NOARGS, reduce_doc}, + {NULL, NULL} }; static PyObject * slice_richcompare(PyObject *v, PyObject *w, int op) { - PyObject *t1; - PyObject *t2; - PyObject *res; - - if (!PySlice_Check(v) || !PySlice_Check(w)) { - Py_INCREF(Py_NotImplemented); - return Py_NotImplemented; - } - - if (v == w) { - /* XXX Do we really need this shortcut? - There's a unit test for it, but is that fair? */ - switch (op) { - case Py_EQ: - case Py_LE: - case Py_GE: - res = Py_True; - break; - default: - res = Py_False; - break; - } - Py_INCREF(res); - return res; - } - - t1 = PyTuple_New(3); - t2 = PyTuple_New(3); - if (t1 == NULL || t2 == NULL) - return NULL; - - PyTuple_SET_ITEM(t1, 0, ((PySliceObject *)v)->start); - PyTuple_SET_ITEM(t1, 1, ((PySliceObject *)v)->stop); - PyTuple_SET_ITEM(t1, 2, ((PySliceObject *)v)->step); - PyTuple_SET_ITEM(t2, 0, ((PySliceObject *)w)->start); - PyTuple_SET_ITEM(t2, 1, ((PySliceObject *)w)->stop); - PyTuple_SET_ITEM(t2, 2, ((PySliceObject *)w)->step); - - res = PyObject_RichCompare(t1, t2, op); - - PyTuple_SET_ITEM(t1, 0, NULL); - PyTuple_SET_ITEM(t1, 1, NULL); - PyTuple_SET_ITEM(t1, 2, NULL); - PyTuple_SET_ITEM(t2, 0, NULL); - PyTuple_SET_ITEM(t2, 1, NULL); - PyTuple_SET_ITEM(t2, 2, NULL); + PyObject *t1; + PyObject *t2; + PyObject *res; + + if (!PySlice_Check(v) || !PySlice_Check(w)) { + Py_INCREF(Py_NotImplemented); + return Py_NotImplemented; + } + + if (v == w) { + /* XXX Do we really need this shortcut? + There's a unit test for it, but is that fair? */ + switch (op) { + case Py_EQ: + case Py_LE: + case Py_GE: + res = Py_True; + break; + default: + res = Py_False; + break; + } + Py_INCREF(res); + return res; + } + + t1 = PyTuple_New(3); + t2 = PyTuple_New(3); + if (t1 == NULL || t2 == NULL) + return NULL; + + PyTuple_SET_ITEM(t1, 0, ((PySliceObject *)v)->start); + PyTuple_SET_ITEM(t1, 1, ((PySliceObject *)v)->stop); + PyTuple_SET_ITEM(t1, 2, ((PySliceObject *)v)->step); + PyTuple_SET_ITEM(t2, 0, ((PySliceObject *)w)->start); + PyTuple_SET_ITEM(t2, 1, ((PySliceObject *)w)->stop); + PyTuple_SET_ITEM(t2, 2, ((PySliceObject *)w)->step); + + res = PyObject_RichCompare(t1, t2, op); + + PyTuple_SET_ITEM(t1, 0, NULL); + PyTuple_SET_ITEM(t1, 1, NULL); + PyTuple_SET_ITEM(t1, 2, NULL); + PyTuple_SET_ITEM(t2, 0, NULL); + PyTuple_SET_ITEM(t2, 1, NULL); + PyTuple_SET_ITEM(t2, 2, NULL); - Py_DECREF(t1); - Py_DECREF(t2); + Py_DECREF(t1); + Py_DECREF(t2); - return res; + return res; } static long slice_hash(PySliceObject *v) { - PyErr_SetString(PyExc_TypeError, "unhashable type"); - return -1L; + PyErr_SetString(PyExc_TypeError, "unhashable type"); + return -1L; } PyTypeObject PySlice_Type = { - PyVarObject_HEAD_INIT(&PyType_Type, 0) - "slice", /* Name of this type */ - sizeof(PySliceObject), /* Basic object size */ - 0, /* Item size for varobject */ - (destructor)slice_dealloc, /* tp_dealloc */ - 0, /* tp_print */ - 0, /* tp_getattr */ - 0, /* tp_setattr */ - 0, /* tp_reserved */ - (reprfunc)slice_repr, /* tp_repr */ - 0, /* tp_as_number */ - 0, /* tp_as_sequence */ - 0, /* tp_as_mapping */ - (hashfunc)slice_hash, /* tp_hash */ - 0, /* tp_call */ - 0, /* tp_str */ - PyObject_GenericGetAttr, /* tp_getattro */ - 0, /* tp_setattro */ - 0, /* tp_as_buffer */ - Py_TPFLAGS_DEFAULT, /* tp_flags */ - slice_doc, /* tp_doc */ - 0, /* tp_traverse */ - 0, /* tp_clear */ - slice_richcompare, /* tp_richcompare */ - 0, /* tp_weaklistoffset */ - 0, /* tp_iter */ - 0, /* tp_iternext */ - slice_methods, /* tp_methods */ - slice_members, /* tp_members */ - 0, /* tp_getset */ - 0, /* tp_base */ - 0, /* tp_dict */ - 0, /* tp_descr_get */ - 0, /* tp_descr_set */ - 0, /* tp_dictoffset */ - 0, /* tp_init */ - 0, /* tp_alloc */ - slice_new, /* tp_new */ + PyVarObject_HEAD_INIT(&PyType_Type, 0) + "slice", /* Name of this type */ + sizeof(PySliceObject), /* Basic object size */ + 0, /* Item size for varobject */ + (destructor)slice_dealloc, /* tp_dealloc */ + 0, /* tp_print */ + 0, /* tp_getattr */ + 0, /* tp_setattr */ + 0, /* tp_reserved */ + (reprfunc)slice_repr, /* tp_repr */ + 0, /* tp_as_number */ + 0, /* tp_as_sequence */ + 0, /* tp_as_mapping */ + (hashfunc)slice_hash, /* tp_hash */ + 0, /* tp_call */ + 0, /* tp_str */ + PyObject_GenericGetAttr, /* tp_getattro */ + 0, /* tp_setattro */ + 0, /* tp_as_buffer */ + Py_TPFLAGS_DEFAULT, /* tp_flags */ + slice_doc, /* tp_doc */ + 0, /* tp_traverse */ + 0, /* tp_clear */ + slice_richcompare, /* tp_richcompare */ + 0, /* tp_weaklistoffset */ + 0, /* tp_iter */ + 0, /* tp_iternext */ + slice_methods, /* tp_methods */ + slice_members, /* tp_members */ + 0, /* tp_getset */ + 0, /* tp_base */ + 0, /* tp_dict */ + 0, /* tp_descr_get */ + 0, /* tp_descr_set */ + 0, /* tp_dictoffset */ + 0, /* tp_init */ + 0, /* tp_alloc */ + slice_new, /* tp_new */ }; Modified: python/branches/py3k-jit/Objects/stringlib/eq.h ============================================================================== --- python/branches/py3k-jit/Objects/stringlib/eq.h (original) +++ python/branches/py3k-jit/Objects/stringlib/eq.h Mon May 10 23:55:43 2010 @@ -6,16 +6,16 @@ Py_LOCAL_INLINE(int) unicode_eq(PyObject *aa, PyObject *bb) { - register PyUnicodeObject *a = (PyUnicodeObject *)aa; - register PyUnicodeObject *b = (PyUnicodeObject *)bb; + register PyUnicodeObject *a = (PyUnicodeObject *)aa; + register PyUnicodeObject *b = (PyUnicodeObject *)bb; - if (a->length != b->length) - return 0; - if (a->length == 0) - return 1; - if (a->str[0] != b->str[0]) - return 0; - if (a->length == 1) - return 1; - return memcmp(a->str, b->str, a->length * sizeof(Py_UNICODE)) == 0; + if (a->length != b->length) + return 0; + if (a->length == 0) + return 1; + if (a->str[0] != b->str[0]) + return 0; + if (a->length == 1) + return 1; + return memcmp(a->str, b->str, a->length * sizeof(Py_UNICODE)) == 0; } Modified: python/branches/py3k-jit/Objects/stringlib/string_format.h ============================================================================== --- python/branches/py3k-jit/Objects/stringlib/string_format.h (original) +++ python/branches/py3k-jit/Objects/stringlib/string_format.h Mon May 10 23:55:43 2010 @@ -563,36 +563,36 @@ PyObject *format_spec_object = NULL; PyObject *(*formatter)(PyObject *, STRINGLIB_CHAR *, Py_ssize_t) = NULL; STRINGLIB_CHAR* format_spec_start = format_spec->ptr ? - format_spec->ptr : NULL; + format_spec->ptr : NULL; Py_ssize_t format_spec_len = format_spec->ptr ? - format_spec->end - format_spec->ptr : 0; + format_spec->end - format_spec->ptr : 0; /* If we know the type exactly, skip the lookup of __format__ and just call the formatter directly. */ if (PyUnicode_CheckExact(fieldobj)) - formatter = _PyUnicode_FormatAdvanced; + formatter = _PyUnicode_FormatAdvanced; else if (PyLong_CheckExact(fieldobj)) - formatter =_PyLong_FormatAdvanced; + formatter =_PyLong_FormatAdvanced; else if (PyFloat_CheckExact(fieldobj)) - formatter = _PyFloat_FormatAdvanced; + formatter = _PyFloat_FormatAdvanced; /* XXX: for 2.6, convert format_spec to the appropriate type (unicode, str) */ if (formatter) { - /* we know exactly which formatter will be called when __format__ is - looked up, so call it directly, instead. */ - result = formatter(fieldobj, format_spec_start, format_spec_len); + /* we know exactly which formatter will be called when __format__ is + looked up, so call it directly, instead. */ + result = formatter(fieldobj, format_spec_start, format_spec_len); } else { - /* We need to create an object out of the pointers we have, because - __format__ takes a string/unicode object for format_spec. */ - format_spec_object = STRINGLIB_NEW(format_spec_start, - format_spec_len); - if (format_spec_object == NULL) - goto done; + /* We need to create an object out of the pointers we have, because + __format__ takes a string/unicode object for format_spec. */ + format_spec_object = STRINGLIB_NEW(format_spec_start, + format_spec_len); + if (format_spec_object == NULL) + goto done; - result = PyObject_Format(fieldobj, format_spec_object); + result = PyObject_Format(fieldobj, format_spec_object); } if (result == NULL) goto done; @@ -605,11 +605,11 @@ /* Convert result to our type. We could be str, and result could be unicode */ { - PyObject *tmp = STRINGLIB_TOSTR(result); - if (tmp == NULL) - goto done; - Py_DECREF(result); - result = tmp; + PyObject *tmp = STRINGLIB_TOSTR(result); + if (tmp == NULL) + goto done; + Py_DECREF(result); + result = tmp; } #endif @@ -844,17 +844,17 @@ return STRINGLIB_TOASCII(obj); #endif default: - if (conversion > 32 && conversion < 127) { - /* It's the ASCII subrange; casting to char is safe - (assuming the execution character set is an ASCII - superset). */ - PyErr_Format(PyExc_ValueError, + if (conversion > 32 && conversion < 127) { + /* It's the ASCII subrange; casting to char is safe + (assuming the execution character set is an ASCII + superset). */ + PyErr_Format(PyExc_ValueError, "Unknown conversion specifier %c", (char)conversion); - } else - PyErr_Format(PyExc_ValueError, - "Unknown conversion specifier \\x%x", - (unsigned int)conversion); + } else + PyErr_Format(PyExc_ValueError, + "Unknown conversion specifier \\x%x", + (unsigned int)conversion); return NULL; } } @@ -1119,7 +1119,7 @@ Py_INCREF(conversion_str); } else - conversion_str = STRINGLIB_NEW(&conversion, 1); + conversion_str = STRINGLIB_NEW(&conversion, 1); if (conversion_str == NULL) goto done; @@ -1135,39 +1135,39 @@ } static PyMethodDef formatteriter_methods[] = { - {NULL, NULL} /* sentinel */ + {NULL, NULL} /* sentinel */ }; static PyTypeObject PyFormatterIter_Type = { PyVarObject_HEAD_INIT(&PyType_Type, 0) - "formatteriterator", /* tp_name */ - sizeof(formatteriterobject), /* tp_basicsize */ - 0, /* tp_itemsize */ + "formatteriterator", /* tp_name */ + sizeof(formatteriterobject), /* tp_basicsize */ + 0, /* tp_itemsize */ /* methods */ - (destructor)formatteriter_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, /* tp_flags */ - 0, /* tp_doc */ - 0, /* tp_traverse */ - 0, /* tp_clear */ - 0, /* tp_richcompare */ - 0, /* tp_weaklistoffset */ - PyObject_SelfIter, /* tp_iter */ - (iternextfunc)formatteriter_next, /* tp_iternext */ - formatteriter_methods, /* tp_methods */ + (destructor)formatteriter_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, /* tp_flags */ + 0, /* tp_doc */ + 0, /* tp_traverse */ + 0, /* tp_clear */ + 0, /* tp_richcompare */ + 0, /* tp_weaklistoffset */ + PyObject_SelfIter, /* tp_iter */ + (iternextfunc)formatteriter_next, /* tp_iternext */ + formatteriter_methods, /* tp_methods */ 0, }; @@ -1268,39 +1268,39 @@ } static PyMethodDef fieldnameiter_methods[] = { - {NULL, NULL} /* sentinel */ + {NULL, NULL} /* sentinel */ }; static PyTypeObject PyFieldNameIter_Type = { PyVarObject_HEAD_INIT(&PyType_Type, 0) - "fieldnameiterator", /* tp_name */ - sizeof(fieldnameiterobject), /* tp_basicsize */ - 0, /* tp_itemsize */ + "fieldnameiterator", /* tp_name */ + sizeof(fieldnameiterobject), /* tp_basicsize */ + 0, /* tp_itemsize */ /* methods */ - (destructor)fieldnameiter_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, /* tp_flags */ - 0, /* tp_doc */ - 0, /* tp_traverse */ - 0, /* tp_clear */ - 0, /* tp_richcompare */ - 0, /* tp_weaklistoffset */ - PyObject_SelfIter, /* tp_iter */ - (iternextfunc)fieldnameiter_next, /* tp_iternext */ - fieldnameiter_methods, /* tp_methods */ + (destructor)fieldnameiter_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, /* tp_flags */ + 0, /* tp_doc */ + 0, /* tp_traverse */ + 0, /* tp_clear */ + 0, /* tp_richcompare */ + 0, /* tp_weaklistoffset */ + PyObject_SelfIter, /* tp_iter */ + (iternextfunc)fieldnameiter_next, /* tp_iternext */ + fieldnameiter_methods, /* tp_methods */ 0}; /* unicode_formatter_field_name_split is used to implement Modified: python/branches/py3k-jit/Objects/structseq.c ============================================================================== --- python/branches/py3k-jit/Objects/structseq.c (original) +++ python/branches/py3k-jit/Objects/structseq.c Mon May 10 23:55:43 2010 @@ -9,7 +9,7 @@ static char real_length_key[] = "n_fields"; static char unnamed_fields_key[] = "n_unnamed_fields"; -/* Fields with this name have only a field index, not a field name. +/* Fields with this name have only a field index, not a field name. They are only allowed for indices < n_visible_fields. */ char *PyStructSequence_UnnamedField = "unnamed field"; @@ -29,511 +29,511 @@ PyObject * PyStructSequence_New(PyTypeObject *type) { - PyStructSequence *obj; + PyStructSequence *obj; - obj = PyObject_New(PyStructSequence, type); - if (obj == NULL) - return NULL; - Py_SIZE(obj) = VISIBLE_SIZE_TP(type); + obj = PyObject_New(PyStructSequence, type); + if (obj == NULL) + return NULL; + Py_SIZE(obj) = VISIBLE_SIZE_TP(type); - return (PyObject*) obj; + return (PyObject*) obj; } static void structseq_dealloc(PyStructSequence *obj) { - Py_ssize_t i, size; + Py_ssize_t i, size; - size = REAL_SIZE(obj); - for (i = 0; i < size; ++i) { - Py_XDECREF(obj->ob_item[i]); - } - PyObject_Del(obj); + size = REAL_SIZE(obj); + for (i = 0; i < size; ++i) { + Py_XDECREF(obj->ob_item[i]); + } + PyObject_Del(obj); } static Py_ssize_t structseq_length(PyStructSequence *obj) { - return VISIBLE_SIZE(obj); + return VISIBLE_SIZE(obj); } static PyObject* structseq_item(PyStructSequence *obj, Py_ssize_t i) { - if (i < 0 || i >= VISIBLE_SIZE(obj)) { - PyErr_SetString(PyExc_IndexError, "tuple index out of range"); - return NULL; - } - Py_INCREF(obj->ob_item[i]); - return obj->ob_item[i]; + if (i < 0 || i >= VISIBLE_SIZE(obj)) { + PyErr_SetString(PyExc_IndexError, "tuple index out of range"); + return NULL; + } + Py_INCREF(obj->ob_item[i]); + return obj->ob_item[i]; } static PyObject* structseq_slice(PyStructSequence *obj, Py_ssize_t low, Py_ssize_t high) { - PyTupleObject *np; - Py_ssize_t i; + PyTupleObject *np; + Py_ssize_t i; - if (low < 0) - low = 0; - if (high > VISIBLE_SIZE(obj)) - high = VISIBLE_SIZE(obj); - if (high < low) - high = low; - np = (PyTupleObject *)PyTuple_New(high-low); - if (np == NULL) - return NULL; - for(i = low; i < high; ++i) { - PyObject *v = obj->ob_item[i]; - Py_INCREF(v); - PyTuple_SET_ITEM(np, i-low, v); - } - return (PyObject *) np; + if (low < 0) + low = 0; + if (high > VISIBLE_SIZE(obj)) + high = VISIBLE_SIZE(obj); + if (high < low) + high = low; + np = (PyTupleObject *)PyTuple_New(high-low); + if (np == NULL) + return NULL; + for(i = low; i < high; ++i) { + PyObject *v = obj->ob_item[i]; + Py_INCREF(v); + PyTuple_SET_ITEM(np, i-low, v); + } + return (PyObject *) np; } static PyObject * structseq_subscript(PyStructSequence *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 += VISIBLE_SIZE(self); - - if (i < 0 || i >= VISIBLE_SIZE(self)) { - PyErr_SetString(PyExc_IndexError, - "tuple index out of range"); - return NULL; - } - Py_INCREF(self->ob_item[i]); - return self->ob_item[i]; - } - else if (PySlice_Check(item)) { - Py_ssize_t start, stop, step, slicelen, cur, i; - PyObject *result; - - if (PySlice_GetIndicesEx((PySliceObject *)item, - VISIBLE_SIZE(self), &start, &stop, - &step, &slicelen) < 0) { - return NULL; - } - if (slicelen <= 0) - return PyTuple_New(0); - result = PyTuple_New(slicelen); - if (result == NULL) - return NULL; - for (cur = start, i = 0; i < slicelen; - cur += step, i++) { - PyObject *v = self->ob_item[cur]; - Py_INCREF(v); - PyTuple_SET_ITEM(result, i, v); - } - return result; - } - else { - PyErr_SetString(PyExc_TypeError, - "structseq index must be integer"); - return NULL; - } + 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 += VISIBLE_SIZE(self); + + if (i < 0 || i >= VISIBLE_SIZE(self)) { + PyErr_SetString(PyExc_IndexError, + "tuple index out of range"); + return NULL; + } + Py_INCREF(self->ob_item[i]); + return self->ob_item[i]; + } + else if (PySlice_Check(item)) { + Py_ssize_t start, stop, step, slicelen, cur, i; + PyObject *result; + + if (PySlice_GetIndicesEx((PySliceObject *)item, + VISIBLE_SIZE(self), &start, &stop, + &step, &slicelen) < 0) { + return NULL; + } + if (slicelen <= 0) + return PyTuple_New(0); + result = PyTuple_New(slicelen); + if (result == NULL) + return NULL; + for (cur = start, i = 0; i < slicelen; + cur += step, i++) { + PyObject *v = self->ob_item[cur]; + Py_INCREF(v); + PyTuple_SET_ITEM(result, i, v); + } + return result; + } + else { + PyErr_SetString(PyExc_TypeError, + "structseq index must be integer"); + return NULL; + } } static PyObject * structseq_new(PyTypeObject *type, PyObject *args, PyObject *kwds) { - PyObject *arg = NULL; - PyObject *dict = NULL; - PyObject *ob; - PyStructSequence *res = NULL; - Py_ssize_t len, min_len, max_len, i, n_unnamed_fields; - static char *kwlist[] = {"sequence", "dict", 0}; - - if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|O:structseq", - kwlist, &arg, &dict)) - return NULL; - - arg = PySequence_Fast(arg, "constructor requires a sequence"); - - if (!arg) { - return NULL; - } - - if (dict && !PyDict_Check(dict)) { - PyErr_Format(PyExc_TypeError, - "%.500s() takes a dict as second arg, if any", - type->tp_name); - Py_DECREF(arg); - return NULL; - } - - len = PySequence_Fast_GET_SIZE(arg); - min_len = VISIBLE_SIZE_TP(type); - max_len = REAL_SIZE_TP(type); - n_unnamed_fields = UNNAMED_FIELDS_TP(type); - - if (min_len != max_len) { - if (len < min_len) { - PyErr_Format(PyExc_TypeError, - "%.500s() takes an at least %zd-sequence (%zd-sequence given)", - type->tp_name, min_len, len); - Py_DECREF(arg); - return NULL; - } - - if (len > max_len) { - PyErr_Format(PyExc_TypeError, - "%.500s() takes an at most %zd-sequence (%zd-sequence given)", - type->tp_name, max_len, len); - Py_DECREF(arg); - return NULL; - } - } - else { - if (len != min_len) { - PyErr_Format(PyExc_TypeError, - "%.500s() takes a %zd-sequence (%zd-sequence given)", - type->tp_name, min_len, len); - Py_DECREF(arg); - return NULL; - } - } - - res = (PyStructSequence*) PyStructSequence_New(type); - if (res == NULL) { - return NULL; - } - for (i = 0; i < len; ++i) { - PyObject *v = PySequence_Fast_GET_ITEM(arg, i); - Py_INCREF(v); - res->ob_item[i] = v; - } - for (; i < max_len; ++i) { - if (dict && (ob = PyDict_GetItemString( - dict, type->tp_members[i-n_unnamed_fields].name))) { - } - else { - ob = Py_None; - } - Py_INCREF(ob); - res->ob_item[i] = ob; - } - - Py_DECREF(arg); - return (PyObject*) res; + PyObject *arg = NULL; + PyObject *dict = NULL; + PyObject *ob; + PyStructSequence *res = NULL; + Py_ssize_t len, min_len, max_len, i, n_unnamed_fields; + static char *kwlist[] = {"sequence", "dict", 0}; + + if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|O:structseq", + kwlist, &arg, &dict)) + return NULL; + + arg = PySequence_Fast(arg, "constructor requires a sequence"); + + if (!arg) { + return NULL; + } + + if (dict && !PyDict_Check(dict)) { + PyErr_Format(PyExc_TypeError, + "%.500s() takes a dict as second arg, if any", + type->tp_name); + Py_DECREF(arg); + return NULL; + } + + len = PySequence_Fast_GET_SIZE(arg); + min_len = VISIBLE_SIZE_TP(type); + max_len = REAL_SIZE_TP(type); + n_unnamed_fields = UNNAMED_FIELDS_TP(type); + + if (min_len != max_len) { + if (len < min_len) { + PyErr_Format(PyExc_TypeError, + "%.500s() takes an at least %zd-sequence (%zd-sequence given)", + type->tp_name, min_len, len); + Py_DECREF(arg); + return NULL; + } + + if (len > max_len) { + PyErr_Format(PyExc_TypeError, + "%.500s() takes an at most %zd-sequence (%zd-sequence given)", + type->tp_name, max_len, len); + Py_DECREF(arg); + return NULL; + } + } + else { + if (len != min_len) { + PyErr_Format(PyExc_TypeError, + "%.500s() takes a %zd-sequence (%zd-sequence given)", + type->tp_name, min_len, len); + Py_DECREF(arg); + return NULL; + } + } + + res = (PyStructSequence*) PyStructSequence_New(type); + if (res == NULL) { + return NULL; + } + for (i = 0; i < len; ++i) { + PyObject *v = PySequence_Fast_GET_ITEM(arg, i); + Py_INCREF(v); + res->ob_item[i] = v; + } + for (; i < max_len; ++i) { + if (dict && (ob = PyDict_GetItemString( + dict, type->tp_members[i-n_unnamed_fields].name))) { + } + else { + ob = Py_None; + } + Py_INCREF(ob); + res->ob_item[i] = ob; + } + + Py_DECREF(arg); + return (PyObject*) res; } static PyObject * make_tuple(PyStructSequence *obj) { - return structseq_slice(obj, 0, VISIBLE_SIZE(obj)); + return structseq_slice(obj, 0, VISIBLE_SIZE(obj)); } static PyObject * structseq_repr(PyStructSequence *obj) { - /* buffer and type size were chosen well considered. */ + /* buffer and type size were chosen well considered. */ #define REPR_BUFFER_SIZE 512 #define TYPE_MAXSIZE 100 - PyObject *tup; - PyTypeObject *typ = Py_TYPE(obj); - int i, removelast = 0; - Py_ssize_t len; - char buf[REPR_BUFFER_SIZE]; - char *endofbuf, *pbuf = buf; - - /* pointer to end of writeable buffer; safes space for "...)\0" */ - endofbuf= &buf[REPR_BUFFER_SIZE-5]; - - if ((tup = make_tuple(obj)) == NULL) { - return NULL; - } - - /* "typename(", limited to TYPE_MAXSIZE */ - len = strlen(typ->tp_name) > TYPE_MAXSIZE ? TYPE_MAXSIZE : - strlen(typ->tp_name); - strncpy(pbuf, typ->tp_name, len); - pbuf += len; - *pbuf++ = '('; - - for (i=0; i < VISIBLE_SIZE(obj); i++) { - PyObject *val, *repr; - char *cname, *crepr; - - cname = typ->tp_members[i].name; - - val = PyTuple_GetItem(tup, i); - if (cname == NULL || val == NULL) { - return NULL; - } - repr = PyObject_Repr(val); - if (repr == NULL) { - Py_DECREF(tup); - return NULL; - } - crepr = _PyUnicode_AsString(repr); - if (crepr == NULL) { - Py_DECREF(tup); - Py_DECREF(repr); - return NULL; - } - - /* + 3: keep space for "=" and ", " */ - len = strlen(cname) + strlen(crepr) + 3; - if ((pbuf+len) <= endofbuf) { - strcpy(pbuf, cname); - pbuf += strlen(cname); - *pbuf++ = '='; - strcpy(pbuf, crepr); - pbuf += strlen(crepr); - *pbuf++ = ','; - *pbuf++ = ' '; - removelast = 1; - Py_DECREF(repr); - } - else { - strcpy(pbuf, "..."); - pbuf += 3; - removelast = 0; - Py_DECREF(repr); - break; - } - } - Py_DECREF(tup); - if (removelast) { - /* overwrite last ", " */ - pbuf-=2; - } - *pbuf++ = ')'; - *pbuf = '\0'; + PyObject *tup; + PyTypeObject *typ = Py_TYPE(obj); + int i, removelast = 0; + Py_ssize_t len; + char buf[REPR_BUFFER_SIZE]; + char *endofbuf, *pbuf = buf; + + /* pointer to end of writeable buffer; safes space for "...)\0" */ + endofbuf= &buf[REPR_BUFFER_SIZE-5]; + + if ((tup = make_tuple(obj)) == NULL) { + return NULL; + } + + /* "typename(", limited to TYPE_MAXSIZE */ + len = strlen(typ->tp_name) > TYPE_MAXSIZE ? TYPE_MAXSIZE : + strlen(typ->tp_name); + strncpy(pbuf, typ->tp_name, len); + pbuf += len; + *pbuf++ = '('; + + for (i=0; i < VISIBLE_SIZE(obj); i++) { + PyObject *val, *repr; + char *cname, *crepr; + + cname = typ->tp_members[i].name; + + val = PyTuple_GetItem(tup, i); + if (cname == NULL || val == NULL) { + return NULL; + } + repr = PyObject_Repr(val); + if (repr == NULL) { + Py_DECREF(tup); + return NULL; + } + crepr = _PyUnicode_AsString(repr); + if (crepr == NULL) { + Py_DECREF(tup); + Py_DECREF(repr); + return NULL; + } + + /* + 3: keep space for "=" and ", " */ + len = strlen(cname) + strlen(crepr) + 3; + if ((pbuf+len) <= endofbuf) { + strcpy(pbuf, cname); + pbuf += strlen(cname); + *pbuf++ = '='; + strcpy(pbuf, crepr); + pbuf += strlen(crepr); + *pbuf++ = ','; + *pbuf++ = ' '; + removelast = 1; + Py_DECREF(repr); + } + else { + strcpy(pbuf, "..."); + pbuf += 3; + removelast = 0; + Py_DECREF(repr); + break; + } + } + Py_DECREF(tup); + if (removelast) { + /* overwrite last ", " */ + pbuf-=2; + } + *pbuf++ = ')'; + *pbuf = '\0'; - return PyUnicode_FromString(buf); + return PyUnicode_FromString(buf); } static PyObject * structseq_concat(PyStructSequence *obj, PyObject *b) { - PyObject *tup, *result; - tup = make_tuple(obj); - result = PySequence_Concat(tup, b); - Py_DECREF(tup); - return result; + PyObject *tup, *result; + tup = make_tuple(obj); + result = PySequence_Concat(tup, b); + Py_DECREF(tup); + return result; } static PyObject * structseq_repeat(PyStructSequence *obj, Py_ssize_t n) { - PyObject *tup, *result; - tup = make_tuple(obj); - result = PySequence_Repeat(tup, n); - Py_DECREF(tup); - return result; + PyObject *tup, *result; + tup = make_tuple(obj); + result = PySequence_Repeat(tup, n); + Py_DECREF(tup); + return result; } static int structseq_contains(PyStructSequence *obj, PyObject *o) { - PyObject *tup; - int result; - tup = make_tuple(obj); - if (!tup) - return -1; - result = PySequence_Contains(tup, o); - Py_DECREF(tup); - return result; + PyObject *tup; + int result; + tup = make_tuple(obj); + if (!tup) + return -1; + result = PySequence_Contains(tup, o); + Py_DECREF(tup); + return result; } static long structseq_hash(PyObject *obj) { - PyObject *tup; - long result; - tup = make_tuple((PyStructSequence*) obj); - if (!tup) - return -1; - result = PyObject_Hash(tup); - Py_DECREF(tup); - return result; + PyObject *tup; + long result; + tup = make_tuple((PyStructSequence*) obj); + if (!tup) + return -1; + result = PyObject_Hash(tup); + Py_DECREF(tup); + return result; } static PyObject * structseq_richcompare(PyObject *obj, PyObject *o2, int op) { - PyObject *tup, *result; - tup = make_tuple((PyStructSequence*) obj); - result = PyObject_RichCompare(tup, o2, op); - Py_DECREF(tup); - return result; + PyObject *tup, *result; + tup = make_tuple((PyStructSequence*) obj); + result = PyObject_RichCompare(tup, o2, op); + Py_DECREF(tup); + return result; } static PyObject * structseq_reduce(PyStructSequence* self) { - PyObject* tup; - PyObject* dict; - PyObject* result; - Py_ssize_t n_fields, n_visible_fields, n_unnamed_fields; - int i; - - n_fields = REAL_SIZE(self); - n_visible_fields = VISIBLE_SIZE(self); - n_unnamed_fields = UNNAMED_FIELDS(self); - tup = PyTuple_New(n_visible_fields); - if (!tup) { - return NULL; - } - - dict = PyDict_New(); - if (!dict) { - Py_DECREF(tup); - return NULL; - } - - for (i = 0; i < n_visible_fields; i++) { - Py_INCREF(self->ob_item[i]); - PyTuple_SET_ITEM(tup, i, self->ob_item[i]); - } - - for (; i < n_fields; i++) { - char *n = Py_TYPE(self)->tp_members[i-n_unnamed_fields].name; - PyDict_SetItemString(dict, n, - self->ob_item[i]); - } + PyObject* tup; + PyObject* dict; + PyObject* result; + Py_ssize_t n_fields, n_visible_fields, n_unnamed_fields; + int i; + + n_fields = REAL_SIZE(self); + n_visible_fields = VISIBLE_SIZE(self); + n_unnamed_fields = UNNAMED_FIELDS(self); + tup = PyTuple_New(n_visible_fields); + if (!tup) { + return NULL; + } + + dict = PyDict_New(); + if (!dict) { + Py_DECREF(tup); + return NULL; + } + + for (i = 0; i < n_visible_fields; i++) { + Py_INCREF(self->ob_item[i]); + PyTuple_SET_ITEM(tup, i, self->ob_item[i]); + } + + for (; i < n_fields; i++) { + char *n = Py_TYPE(self)->tp_members[i-n_unnamed_fields].name; + PyDict_SetItemString(dict, n, + self->ob_item[i]); + } - result = Py_BuildValue("(O(OO))", Py_TYPE(self), tup, dict); + result = Py_BuildValue("(O(OO))", Py_TYPE(self), tup, dict); - Py_DECREF(tup); - Py_DECREF(dict); + Py_DECREF(tup); + Py_DECREF(dict); - return result; + return result; } static PySequenceMethods structseq_as_sequence = { - (lenfunc)structseq_length, - (binaryfunc)structseq_concat, /* sq_concat */ - (ssizeargfunc)structseq_repeat, /* sq_repeat */ - (ssizeargfunc)structseq_item, /* sq_item */ - 0, /* sq_slice */ - 0, /* sq_ass_item */ - 0, /* sq_ass_slice */ - (objobjproc)structseq_contains, /* sq_contains */ + (lenfunc)structseq_length, + (binaryfunc)structseq_concat, /* sq_concat */ + (ssizeargfunc)structseq_repeat, /* sq_repeat */ + (ssizeargfunc)structseq_item, /* sq_item */ + 0, /* sq_slice */ + 0, /* sq_ass_item */ + 0, /* sq_ass_slice */ + (objobjproc)structseq_contains, /* sq_contains */ }; static PyMappingMethods structseq_as_mapping = { - (lenfunc)structseq_length, - (binaryfunc)structseq_subscript, + (lenfunc)structseq_length, + (binaryfunc)structseq_subscript, }; static PyMethodDef structseq_methods[] = { - {"__reduce__", (PyCFunction)structseq_reduce, - METH_NOARGS, NULL}, - {NULL, NULL} + {"__reduce__", (PyCFunction)structseq_reduce, + METH_NOARGS, NULL}, + {NULL, NULL} }; static PyTypeObject _struct_sequence_template = { - PyVarObject_HEAD_INIT(&PyType_Type, 0) - NULL, /* tp_name */ - 0, /* tp_basicsize */ - 0, /* tp_itemsize */ - (destructor)structseq_dealloc, /* tp_dealloc */ - 0, /* tp_print */ - 0, /* tp_getattr */ - 0, /* tp_setattr */ - 0, /* tp_reserved */ - (reprfunc)structseq_repr, /* tp_repr */ - 0, /* tp_as_number */ - &structseq_as_sequence, /* tp_as_sequence */ - &structseq_as_mapping, /* tp_as_mapping */ - structseq_hash, /* tp_hash */ - 0, /* tp_call */ - 0, /* tp_str */ - 0, /* tp_getattro */ - 0, /* tp_setattro */ - 0, /* tp_as_buffer */ - Py_TPFLAGS_DEFAULT, /* tp_flags */ - NULL, /* tp_doc */ - 0, /* tp_traverse */ - 0, /* tp_clear */ - structseq_richcompare, /* tp_richcompare */ - 0, /* tp_weaklistoffset */ - 0, /* tp_iter */ - 0, /* tp_iternext */ - structseq_methods, /* tp_methods */ - NULL, /* tp_members */ - 0, /* tp_getset */ - 0, /* tp_base */ - 0, /* tp_dict */ - 0, /* tp_descr_get */ - 0, /* tp_descr_set */ - 0, /* tp_dictoffset */ - 0, /* tp_init */ - 0, /* tp_alloc */ - structseq_new, /* tp_new */ + PyVarObject_HEAD_INIT(&PyType_Type, 0) + NULL, /* tp_name */ + 0, /* tp_basicsize */ + 0, /* tp_itemsize */ + (destructor)structseq_dealloc, /* tp_dealloc */ + 0, /* tp_print */ + 0, /* tp_getattr */ + 0, /* tp_setattr */ + 0, /* tp_reserved */ + (reprfunc)structseq_repr, /* tp_repr */ + 0, /* tp_as_number */ + &structseq_as_sequence, /* tp_as_sequence */ + &structseq_as_mapping, /* tp_as_mapping */ + structseq_hash, /* tp_hash */ + 0, /* tp_call */ + 0, /* tp_str */ + 0, /* tp_getattro */ + 0, /* tp_setattro */ + 0, /* tp_as_buffer */ + Py_TPFLAGS_DEFAULT, /* tp_flags */ + NULL, /* tp_doc */ + 0, /* tp_traverse */ + 0, /* tp_clear */ + structseq_richcompare, /* tp_richcompare */ + 0, /* tp_weaklistoffset */ + 0, /* tp_iter */ + 0, /* tp_iternext */ + structseq_methods, /* tp_methods */ + NULL, /* tp_members */ + 0, /* tp_getset */ + 0, /* tp_base */ + 0, /* tp_dict */ + 0, /* tp_descr_get */ + 0, /* tp_descr_set */ + 0, /* tp_dictoffset */ + 0, /* tp_init */ + 0, /* tp_alloc */ + structseq_new, /* tp_new */ }; void PyStructSequence_InitType(PyTypeObject *type, PyStructSequence_Desc *desc) { - PyObject *dict; - PyMemberDef* members; - int n_members, n_unnamed_members, i, k; + PyObject *dict; + PyMemberDef* members; + int n_members, n_unnamed_members, i, k; #ifdef Py_TRACE_REFS - /* if the type object was chained, unchain it first - before overwriting its storage */ - if (type->ob_base.ob_base._ob_next) { - _Py_ForgetReference((PyObject*)type); - } + /* if the type object was chained, unchain it first + before overwriting its storage */ + if (type->ob_base.ob_base._ob_next) { + _Py_ForgetReference((PyObject*)type); + } #endif - n_unnamed_members = 0; - for (i = 0; desc->fields[i].name != NULL; ++i) - if (desc->fields[i].name == PyStructSequence_UnnamedField) - n_unnamed_members++; - n_members = i; - - memcpy(type, &_struct_sequence_template, sizeof(PyTypeObject)); - type->tp_name = desc->name; - type->tp_doc = desc->doc; - type->tp_basicsize = sizeof(PyStructSequence)+ - sizeof(PyObject*)*(n_members-1); - type->tp_itemsize = 0; - - members = PyMem_NEW(PyMemberDef, n_members-n_unnamed_members+1); - if (members == NULL) - return; - - for (i = k = 0; i < n_members; ++i) { - if (desc->fields[i].name == PyStructSequence_UnnamedField) - continue; - members[k].name = desc->fields[i].name; - members[k].type = T_OBJECT; - members[k].offset = offsetof(PyStructSequence, ob_item) - + i * sizeof(PyObject*); - members[k].flags = READONLY; - members[k].doc = desc->fields[i].doc; - k++; - } - members[k].name = NULL; - - type->tp_members = members; - - if (PyType_Ready(type) < 0) - return; - Py_INCREF(type); - - dict = type->tp_dict; -#define SET_DICT_FROM_INT(key, value) \ - do { \ - PyObject *v = PyLong_FromLong((long) value); \ - if (v != NULL) { \ - PyDict_SetItemString(dict, key, v); \ - Py_DECREF(v); \ - } \ - } while (0) - - SET_DICT_FROM_INT(visible_length_key, desc->n_in_sequence); - SET_DICT_FROM_INT(real_length_key, n_members); - SET_DICT_FROM_INT(unnamed_fields_key, n_unnamed_members); + n_unnamed_members = 0; + for (i = 0; desc->fields[i].name != NULL; ++i) + if (desc->fields[i].name == PyStructSequence_UnnamedField) + n_unnamed_members++; + n_members = i; + + memcpy(type, &_struct_sequence_template, sizeof(PyTypeObject)); + type->tp_name = desc->name; + type->tp_doc = desc->doc; + type->tp_basicsize = sizeof(PyStructSequence)+ + sizeof(PyObject*)*(n_members-1); + type->tp_itemsize = 0; + + members = PyMem_NEW(PyMemberDef, n_members-n_unnamed_members+1); + if (members == NULL) + return; + + for (i = k = 0; i < n_members; ++i) { + if (desc->fields[i].name == PyStructSequence_UnnamedField) + continue; + members[k].name = desc->fields[i].name; + members[k].type = T_OBJECT; + members[k].offset = offsetof(PyStructSequence, ob_item) + + i * sizeof(PyObject*); + members[k].flags = READONLY; + members[k].doc = desc->fields[i].doc; + k++; + } + members[k].name = NULL; + + type->tp_members = members; + + if (PyType_Ready(type) < 0) + return; + Py_INCREF(type); + + dict = type->tp_dict; +#define SET_DICT_FROM_INT(key, value) \ + do { \ + PyObject *v = PyLong_FromLong((long) value); \ + if (v != NULL) { \ + PyDict_SetItemString(dict, key, v); \ + Py_DECREF(v); \ + } \ + } while (0) + + SET_DICT_FROM_INT(visible_length_key, desc->n_in_sequence); + SET_DICT_FROM_INT(real_length_key, n_members); + SET_DICT_FROM_INT(unnamed_fields_key, n_unnamed_members); } Modified: python/branches/py3k-jit/Objects/tupleobject.c ============================================================================== --- python/branches/py3k-jit/Objects/tupleobject.c (original) +++ python/branches/py3k-jit/Objects/tupleobject.c Mon May 10 23:55:43 2010 @@ -5,9 +5,9 @@ /* Speed optimization to avoid frequent malloc/free of small tuples */ #ifndef PyTuple_MAXSAVESIZE -#define PyTuple_MAXSAVESIZE 20 /* Largest tuple to save on free list */ +#define PyTuple_MAXSAVESIZE 20 /* Largest tuple to save on free list */ #endif -#ifndef PyTuple_MAXFREELIST +#ifndef PyTuple_MAXFREELIST #define PyTuple_MAXFREELIST 2000 /* Maximum number of tuples of each size to save */ #endif @@ -35,12 +35,12 @@ static void show_track(void) { - fprintf(stderr, "Tuples created: %" PY_FORMAT_SIZE_T "d\n", - count_tracked + count_untracked); - fprintf(stderr, "Tuples tracked by the GC: %" PY_FORMAT_SIZE_T - "d\n", count_tracked); - fprintf(stderr, "%.2f%% tuple tracking rate\n\n", - (100.0*count_tracked/(count_untracked+count_tracked))); + fprintf(stderr, "Tuples created: %" PY_FORMAT_SIZE_T "d\n", + count_tracked + count_untracked); + fprintf(stderr, "Tuples tracked by the GC: %" PY_FORMAT_SIZE_T + "d\n", count_tracked); + fprintf(stderr, "%.2f%% tuple tracking rate\n\n", + (100.0*count_tracked/(count_untracked+count_tracked))); } #endif @@ -48,161 +48,161 @@ PyObject * PyTuple_New(register Py_ssize_t size) { - register PyTupleObject *op; - Py_ssize_t i; - if (size < 0) { - PyErr_BadInternalCall(); - return NULL; - } + register PyTupleObject *op; + Py_ssize_t i; + if (size < 0) { + PyErr_BadInternalCall(); + return NULL; + } #if PyTuple_MAXSAVESIZE > 0 - if (size == 0 && free_list[0]) { - op = free_list[0]; - Py_INCREF(op); + if (size == 0 && free_list[0]) { + op = free_list[0]; + Py_INCREF(op); #ifdef COUNT_ALLOCS - tuple_zero_allocs++; + tuple_zero_allocs++; #endif - return (PyObject *) op; - } - if (size < PyTuple_MAXSAVESIZE && (op = free_list[size]) != NULL) { - free_list[size] = (PyTupleObject *) op->ob_item[0]; - numfree[size]--; + return (PyObject *) op; + } + if (size < PyTuple_MAXSAVESIZE && (op = free_list[size]) != NULL) { + free_list[size] = (PyTupleObject *) op->ob_item[0]; + numfree[size]--; #ifdef COUNT_ALLOCS - fast_tuple_allocs++; + fast_tuple_allocs++; #endif - /* Inline PyObject_InitVar */ + /* Inline PyObject_InitVar */ #ifdef Py_TRACE_REFS - Py_SIZE(op) = size; - Py_TYPE(op) = &PyTuple_Type; + Py_SIZE(op) = size; + Py_TYPE(op) = &PyTuple_Type; #endif - _Py_NewReference((PyObject *)op); - } - else + _Py_NewReference((PyObject *)op); + } + else #endif - { - Py_ssize_t nbytes = size * sizeof(PyObject *); - /* Check for overflow */ - if (nbytes / sizeof(PyObject *) != (size_t)size || - (nbytes > PY_SSIZE_T_MAX - sizeof(PyTupleObject) - sizeof(PyObject *))) - { - return PyErr_NoMemory(); - } - nbytes += sizeof(PyTupleObject) - sizeof(PyObject *); - - op = PyObject_GC_NewVar(PyTupleObject, &PyTuple_Type, size); - if (op == NULL) - return NULL; - } - for (i=0; i < size; i++) - op->ob_item[i] = NULL; + { + Py_ssize_t nbytes = size * sizeof(PyObject *); + /* Check for overflow */ + if (nbytes / sizeof(PyObject *) != (size_t)size || + (nbytes > PY_SSIZE_T_MAX - sizeof(PyTupleObject) - sizeof(PyObject *))) + { + return PyErr_NoMemory(); + } + nbytes += sizeof(PyTupleObject) - sizeof(PyObject *); + + op = PyObject_GC_NewVar(PyTupleObject, &PyTuple_Type, size); + if (op == NULL) + return NULL; + } + for (i=0; i < size; i++) + op->ob_item[i] = NULL; #if PyTuple_MAXSAVESIZE > 0 - if (size == 0) { - free_list[0] = op; - ++numfree[0]; - Py_INCREF(op); /* extra INCREF so that this is never freed */ - } + if (size == 0) { + free_list[0] = op; + ++numfree[0]; + Py_INCREF(op); /* extra INCREF so that this is never freed */ + } #endif #ifdef SHOW_TRACK_COUNT - count_tracked++; + count_tracked++; #endif - _PyObject_GC_TRACK(op); - return (PyObject *) op; + _PyObject_GC_TRACK(op); + return (PyObject *) op; } Py_ssize_t PyTuple_Size(register PyObject *op) { - if (!PyTuple_Check(op)) { - PyErr_BadInternalCall(); - return -1; - } - else - return Py_SIZE(op); + if (!PyTuple_Check(op)) { + PyErr_BadInternalCall(); + return -1; + } + else + return Py_SIZE(op); } PyObject * PyTuple_GetItem(register PyObject *op, register Py_ssize_t i) { - if (!PyTuple_Check(op)) { - PyErr_BadInternalCall(); - return NULL; - } - if (i < 0 || i >= Py_SIZE(op)) { - PyErr_SetString(PyExc_IndexError, "tuple index out of range"); - return NULL; - } - return ((PyTupleObject *)op) -> ob_item[i]; + if (!PyTuple_Check(op)) { + PyErr_BadInternalCall(); + return NULL; + } + if (i < 0 || i >= Py_SIZE(op)) { + PyErr_SetString(PyExc_IndexError, "tuple index out of range"); + return NULL; + } + return ((PyTupleObject *)op) -> ob_item[i]; } int PyTuple_SetItem(register PyObject *op, register Py_ssize_t i, PyObject *newitem) { - register PyObject *olditem; - register PyObject **p; - if (!PyTuple_Check(op) || op->ob_refcnt != 1) { - Py_XDECREF(newitem); - PyErr_BadInternalCall(); - return -1; - } - if (i < 0 || i >= Py_SIZE(op)) { - Py_XDECREF(newitem); - PyErr_SetString(PyExc_IndexError, - "tuple assignment index out of range"); - return -1; - } - p = ((PyTupleObject *)op) -> ob_item + i; - olditem = *p; - *p = newitem; - Py_XDECREF(olditem); - return 0; + register PyObject *olditem; + register PyObject **p; + if (!PyTuple_Check(op) || op->ob_refcnt != 1) { + Py_XDECREF(newitem); + PyErr_BadInternalCall(); + return -1; + } + if (i < 0 || i >= Py_SIZE(op)) { + Py_XDECREF(newitem); + PyErr_SetString(PyExc_IndexError, + "tuple assignment index out of range"); + return -1; + } + p = ((PyTupleObject *)op) -> ob_item + i; + olditem = *p; + *p = newitem; + Py_XDECREF(olditem); + return 0; } void _PyTuple_MaybeUntrack(PyObject *op) { - PyTupleObject *t; - Py_ssize_t i, n; - - if (!PyTuple_CheckExact(op) || !_PyObject_GC_IS_TRACKED(op)) - return; - t = (PyTupleObject *) op; - n = Py_SIZE(t); - for (i = 0; i < n; i++) { - PyObject *elt = PyTuple_GET_ITEM(t, i); - /* Tuple with NULL elements aren't - fully constructed, don't untrack - them yet. */ - if (!elt || - _PyObject_GC_MAY_BE_TRACKED(elt)) - return; - } + PyTupleObject *t; + Py_ssize_t i, n; + + if (!PyTuple_CheckExact(op) || !_PyObject_GC_IS_TRACKED(op)) + return; + t = (PyTupleObject *) op; + n = Py_SIZE(t); + for (i = 0; i < n; i++) { + PyObject *elt = PyTuple_GET_ITEM(t, i); + /* Tuple with NULL elements aren't + fully constructed, don't untrack + them yet. */ + if (!elt || + _PyObject_GC_MAY_BE_TRACKED(elt)) + return; + } #ifdef SHOW_TRACK_COUNT - count_tracked--; - count_untracked++; + count_tracked--; + count_untracked++; #endif - _PyObject_GC_UNTRACK(op); + _PyObject_GC_UNTRACK(op); } PyObject * PyTuple_Pack(Py_ssize_t n, ...) { - Py_ssize_t i; - PyObject *o; - PyObject *result; - PyObject **items; - va_list vargs; - - va_start(vargs, n); - result = PyTuple_New(n); - if (result == NULL) - return NULL; - items = ((PyTupleObject *)result)->ob_item; - for (i = 0; i < n; i++) { - o = va_arg(vargs, PyObject *); - Py_INCREF(o); - items[i] = o; - } - va_end(vargs); - return result; + Py_ssize_t i; + PyObject *o; + PyObject *result; + PyObject **items; + va_list vargs; + + va_start(vargs, n); + result = PyTuple_New(n); + if (result == NULL) + return NULL; + items = ((PyTupleObject *)result)->ob_item; + for (i = 0; i < n; i++) { + o = va_arg(vargs, PyObject *); + Py_INCREF(o); + items[i] = o; + } + va_end(vargs); + return result; } @@ -211,405 +211,405 @@ static void tupledealloc(register PyTupleObject *op) { - register Py_ssize_t i; - register Py_ssize_t len = Py_SIZE(op); - PyObject_GC_UnTrack(op); - Py_TRASHCAN_SAFE_BEGIN(op) - if (len > 0) { - i = len; - while (--i >= 0) - Py_XDECREF(op->ob_item[i]); + register Py_ssize_t i; + register Py_ssize_t len = Py_SIZE(op); + PyObject_GC_UnTrack(op); + Py_TRASHCAN_SAFE_BEGIN(op) + if (len > 0) { + i = len; + while (--i >= 0) + Py_XDECREF(op->ob_item[i]); #if PyTuple_MAXSAVESIZE > 0 - if (len < PyTuple_MAXSAVESIZE && - numfree[len] < PyTuple_MAXFREELIST && - Py_TYPE(op) == &PyTuple_Type) - { - op->ob_item[0] = (PyObject *) free_list[len]; - numfree[len]++; - free_list[len] = op; - goto done; /* return */ - } + if (len < PyTuple_MAXSAVESIZE && + numfree[len] < PyTuple_MAXFREELIST && + Py_TYPE(op) == &PyTuple_Type) + { + op->ob_item[0] = (PyObject *) free_list[len]; + numfree[len]++; + free_list[len] = op; + goto done; /* return */ + } #endif - } - Py_TYPE(op)->tp_free((PyObject *)op); + } + Py_TYPE(op)->tp_free((PyObject *)op); done: - Py_TRASHCAN_SAFE_END(op) + Py_TRASHCAN_SAFE_END(op) } static PyObject * tuplerepr(PyTupleObject *v) { - Py_ssize_t i, n; - PyObject *s, *temp; - PyObject *pieces, *result = NULL; - - n = Py_SIZE(v); - if (n == 0) - return PyUnicode_FromString("()"); - - /* While not mutable, it is still possible to end up with a cycle in a - tuple through an object that stores itself within a tuple (and thus - infinitely asks for the repr of itself). This should only be - possible within a type. */ - i = Py_ReprEnter((PyObject *)v); - if (i != 0) { - return i > 0 ? PyUnicode_FromString("(...)") : NULL; - } - - pieces = PyTuple_New(n); - if (pieces == NULL) - return NULL; - - /* Do repr() on each element. */ - for (i = 0; i < n; ++i) { - if (Py_EnterRecursiveCall(" while getting the repr of a tuple")) - goto Done; - s = PyObject_Repr(v->ob_item[i]); - Py_LeaveRecursiveCall(); - if (s == NULL) - goto Done; - PyTuple_SET_ITEM(pieces, i, s); - } - - /* Add "()" decorations to the first and last items. */ - assert(n > 0); - s = PyUnicode_FromString("("); - if (s == NULL) - goto Done; - temp = PyTuple_GET_ITEM(pieces, 0); - PyUnicode_AppendAndDel(&s, temp); - PyTuple_SET_ITEM(pieces, 0, s); - if (s == NULL) - goto Done; - - s = PyUnicode_FromString(n == 1 ? ",)" : ")"); - if (s == NULL) - goto Done; - temp = PyTuple_GET_ITEM(pieces, n-1); - PyUnicode_AppendAndDel(&temp, s); - PyTuple_SET_ITEM(pieces, n-1, temp); - if (temp == NULL) - goto Done; - - /* Paste them all together with ", " between. */ - s = PyUnicode_FromString(", "); - if (s == NULL) - goto Done; - result = PyUnicode_Join(s, pieces); - Py_DECREF(s); + Py_ssize_t i, n; + PyObject *s, *temp; + PyObject *pieces, *result = NULL; + + n = Py_SIZE(v); + if (n == 0) + return PyUnicode_FromString("()"); + + /* While not mutable, it is still possible to end up with a cycle in a + tuple through an object that stores itself within a tuple (and thus + infinitely asks for the repr of itself). This should only be + possible within a type. */ + i = Py_ReprEnter((PyObject *)v); + if (i != 0) { + return i > 0 ? PyUnicode_FromString("(...)") : NULL; + } + + pieces = PyTuple_New(n); + if (pieces == NULL) + return NULL; + + /* Do repr() on each element. */ + for (i = 0; i < n; ++i) { + if (Py_EnterRecursiveCall(" while getting the repr of a tuple")) + goto Done; + s = PyObject_Repr(v->ob_item[i]); + Py_LeaveRecursiveCall(); + if (s == NULL) + goto Done; + PyTuple_SET_ITEM(pieces, i, s); + } + + /* Add "()" decorations to the first and last items. */ + assert(n > 0); + s = PyUnicode_FromString("("); + if (s == NULL) + goto Done; + temp = PyTuple_GET_ITEM(pieces, 0); + PyUnicode_AppendAndDel(&s, temp); + PyTuple_SET_ITEM(pieces, 0, s); + if (s == NULL) + goto Done; + + s = PyUnicode_FromString(n == 1 ? ",)" : ")"); + if (s == NULL) + goto Done; + temp = PyTuple_GET_ITEM(pieces, n-1); + PyUnicode_AppendAndDel(&temp, s); + PyTuple_SET_ITEM(pieces, n-1, temp); + if (temp == NULL) + goto Done; + + /* Paste them all together with ", " between. */ + s = PyUnicode_FromString(", "); + if (s == NULL) + goto Done; + result = PyUnicode_Join(s, pieces); + Py_DECREF(s); Done: - Py_DECREF(pieces); - Py_ReprLeave((PyObject *)v); - return result; + Py_DECREF(pieces); + Py_ReprLeave((PyObject *)v); + return result; } -/* The addend 82520, was selected from the range(0, 1000000) for - generating the greatest number of prime multipliers for tuples +/* The addend 82520, was selected from the range(0, 1000000) for + generating the greatest number of prime multipliers for tuples upto length eight: - 1082527, 1165049, 1082531, 1165057, 1247581, 1330103, 1082533, + 1082527, 1165049, 1082531, 1165057, 1247581, 1330103, 1082533, 1330111, 1412633, 1165069, 1247599, 1495177, 1577699 */ static long tuplehash(PyTupleObject *v) { - register long x, y; - register Py_ssize_t len = Py_SIZE(v); - register PyObject **p; - long mult = 1000003L; - x = 0x345678L; - p = v->ob_item; - while (--len >= 0) { - y = PyObject_Hash(*p++); - if (y == -1) - return -1; - x = (x ^ y) * mult; - /* the cast might truncate len; that doesn't change hash stability */ - mult += (long)(82520L + len + len); - } - x += 97531L; - if (x == -1) - x = -2; - return x; + register long x, y; + register Py_ssize_t len = Py_SIZE(v); + register PyObject **p; + long mult = 1000003L; + x = 0x345678L; + p = v->ob_item; + while (--len >= 0) { + y = PyObject_Hash(*p++); + if (y == -1) + return -1; + x = (x ^ y) * mult; + /* the cast might truncate len; that doesn't change hash stability */ + mult += (long)(82520L + len + len); + } + x += 97531L; + if (x == -1) + x = -2; + return x; } static Py_ssize_t tuplelength(PyTupleObject *a) { - return Py_SIZE(a); + return Py_SIZE(a); } static int tuplecontains(PyTupleObject *a, PyObject *el) { - Py_ssize_t i; - int cmp; + Py_ssize_t i; + int cmp; - for (i = 0, cmp = 0 ; cmp == 0 && i < Py_SIZE(a); ++i) - cmp = PyObject_RichCompareBool(el, PyTuple_GET_ITEM(a, i), - Py_EQ); - return cmp; + for (i = 0, cmp = 0 ; cmp == 0 && i < Py_SIZE(a); ++i) + cmp = PyObject_RichCompareBool(el, PyTuple_GET_ITEM(a, i), + Py_EQ); + return cmp; } static PyObject * tupleitem(register PyTupleObject *a, register Py_ssize_t i) { - if (i < 0 || i >= Py_SIZE(a)) { - PyErr_SetString(PyExc_IndexError, "tuple index out of range"); - return NULL; - } - Py_INCREF(a->ob_item[i]); - return a->ob_item[i]; + if (i < 0 || i >= Py_SIZE(a)) { + PyErr_SetString(PyExc_IndexError, "tuple index out of range"); + return NULL; + } + Py_INCREF(a->ob_item[i]); + return a->ob_item[i]; } static PyObject * -tupleslice(register PyTupleObject *a, register Py_ssize_t ilow, - register Py_ssize_t ihigh) +tupleslice(register PyTupleObject *a, register Py_ssize_t ilow, + register Py_ssize_t ihigh) { - register PyTupleObject *np; - PyObject **src, **dest; - register Py_ssize_t i; - Py_ssize_t len; - if (ilow < 0) - ilow = 0; - if (ihigh > Py_SIZE(a)) - ihigh = Py_SIZE(a); - if (ihigh < ilow) - ihigh = ilow; - if (ilow == 0 && ihigh == Py_SIZE(a) && PyTuple_CheckExact(a)) { - Py_INCREF(a); - return (PyObject *)a; - } - len = ihigh - ilow; - np = (PyTupleObject *)PyTuple_New(len); - if (np == NULL) - return NULL; - src = a->ob_item + ilow; - dest = np->ob_item; - for (i = 0; i < len; i++) { - PyObject *v = src[i]; - Py_INCREF(v); - dest[i] = v; - } - return (PyObject *)np; + register PyTupleObject *np; + PyObject **src, **dest; + register Py_ssize_t i; + Py_ssize_t len; + if (ilow < 0) + ilow = 0; + if (ihigh > Py_SIZE(a)) + ihigh = Py_SIZE(a); + if (ihigh < ilow) + ihigh = ilow; + if (ilow == 0 && ihigh == Py_SIZE(a) && PyTuple_CheckExact(a)) { + Py_INCREF(a); + return (PyObject *)a; + } + len = ihigh - ilow; + np = (PyTupleObject *)PyTuple_New(len); + if (np == NULL) + return NULL; + src = a->ob_item + ilow; + dest = np->ob_item; + for (i = 0; i < len; i++) { + PyObject *v = src[i]; + Py_INCREF(v); + dest[i] = v; + } + return (PyObject *)np; } PyObject * PyTuple_GetSlice(PyObject *op, Py_ssize_t i, Py_ssize_t j) { - if (op == NULL || !PyTuple_Check(op)) { - PyErr_BadInternalCall(); - return NULL; - } - return tupleslice((PyTupleObject *)op, i, j); + if (op == NULL || !PyTuple_Check(op)) { + PyErr_BadInternalCall(); + return NULL; + } + return tupleslice((PyTupleObject *)op, i, j); } static PyObject * tupleconcat(register PyTupleObject *a, register PyObject *bb) { - register Py_ssize_t size; - register Py_ssize_t i; - PyObject **src, **dest; - PyTupleObject *np; - if (!PyTuple_Check(bb)) { - PyErr_Format(PyExc_TypeError, - "can only concatenate tuple (not \"%.200s\") to tuple", - Py_TYPE(bb)->tp_name); - return NULL; - } + register Py_ssize_t size; + register Py_ssize_t i; + PyObject **src, **dest; + PyTupleObject *np; + if (!PyTuple_Check(bb)) { + PyErr_Format(PyExc_TypeError, + "can only concatenate tuple (not \"%.200s\") to tuple", + Py_TYPE(bb)->tp_name); + return NULL; + } #define b ((PyTupleObject *)bb) - size = Py_SIZE(a) + Py_SIZE(b); - if (size < 0) - return PyErr_NoMemory(); - np = (PyTupleObject *) PyTuple_New(size); - if (np == NULL) { - return NULL; - } - src = a->ob_item; - dest = np->ob_item; - for (i = 0; i < Py_SIZE(a); i++) { - PyObject *v = src[i]; - Py_INCREF(v); - dest[i] = v; - } - src = b->ob_item; - dest = np->ob_item + Py_SIZE(a); - for (i = 0; i < Py_SIZE(b); i++) { - PyObject *v = src[i]; - Py_INCREF(v); - dest[i] = v; - } - return (PyObject *)np; + size = Py_SIZE(a) + Py_SIZE(b); + if (size < 0) + return PyErr_NoMemory(); + np = (PyTupleObject *) PyTuple_New(size); + if (np == NULL) { + return NULL; + } + src = a->ob_item; + dest = np->ob_item; + for (i = 0; i < Py_SIZE(a); i++) { + PyObject *v = src[i]; + Py_INCREF(v); + dest[i] = v; + } + src = b->ob_item; + dest = np->ob_item + Py_SIZE(a); + for (i = 0; i < Py_SIZE(b); i++) { + PyObject *v = src[i]; + Py_INCREF(v); + dest[i] = v; + } + return (PyObject *)np; #undef b } static PyObject * tuplerepeat(PyTupleObject *a, Py_ssize_t n) { - Py_ssize_t i, j; - Py_ssize_t size; - PyTupleObject *np; - PyObject **p, **items; - if (n < 0) - n = 0; - if (Py_SIZE(a) == 0 || n == 1) { - if (PyTuple_CheckExact(a)) { - /* Since tuples are immutable, we can return a shared - copy in this case */ - Py_INCREF(a); - return (PyObject *)a; - } - if (Py_SIZE(a) == 0) - return PyTuple_New(0); - } - size = Py_SIZE(a) * n; - if (size/Py_SIZE(a) != n) - return PyErr_NoMemory(); - np = (PyTupleObject *) PyTuple_New(size); - if (np == NULL) - return NULL; - p = np->ob_item; - items = a->ob_item; - for (i = 0; i < n; i++) { - for (j = 0; j < Py_SIZE(a); j++) { - *p = items[j]; - Py_INCREF(*p); - p++; - } - } - return (PyObject *) np; + Py_ssize_t i, j; + Py_ssize_t size; + PyTupleObject *np; + PyObject **p, **items; + if (n < 0) + n = 0; + if (Py_SIZE(a) == 0 || n == 1) { + if (PyTuple_CheckExact(a)) { + /* Since tuples are immutable, we can return a shared + copy in this case */ + Py_INCREF(a); + return (PyObject *)a; + } + if (Py_SIZE(a) == 0) + return PyTuple_New(0); + } + size = Py_SIZE(a) * n; + if (size/Py_SIZE(a) != n) + return PyErr_NoMemory(); + np = (PyTupleObject *) PyTuple_New(size); + if (np == NULL) + return NULL; + p = np->ob_item; + items = a->ob_item; + for (i = 0; i < n; i++) { + for (j = 0; j < Py_SIZE(a); j++) { + *p = items[j]; + Py_INCREF(*p); + p++; + } + } + return (PyObject *) np; } static PyObject * tupleindex(PyTupleObject *self, PyObject *args) { - Py_ssize_t i, start=0, stop=Py_SIZE(self); - PyObject *v; + Py_ssize_t i, start=0, stop=Py_SIZE(self); + PyObject *v; - if (!PyArg_ParseTuple(args, "O|O&O&:index", &v, - _PyEval_SliceIndex, &start, - _PyEval_SliceIndex, &stop)) - return NULL; - if (start < 0) { - start += Py_SIZE(self); - if (start < 0) - start = 0; - } - if (stop < 0) { - stop += Py_SIZE(self); - if (stop < 0) - stop = 0; - } - for (i = start; i < stop && i < Py_SIZE(self); i++) { - int cmp = PyObject_RichCompareBool(self->ob_item[i], v, Py_EQ); - if (cmp > 0) - return PyLong_FromSsize_t(i); - else if (cmp < 0) - return NULL; - } - PyErr_SetString(PyExc_ValueError, "tuple.index(x): x not in tuple"); - return NULL; + if (!PyArg_ParseTuple(args, "O|O&O&:index", &v, + _PyEval_SliceIndex, &start, + _PyEval_SliceIndex, &stop)) + return NULL; + if (start < 0) { + start += Py_SIZE(self); + if (start < 0) + start = 0; + } + if (stop < 0) { + stop += Py_SIZE(self); + if (stop < 0) + stop = 0; + } + for (i = start; i < stop && i < Py_SIZE(self); i++) { + int cmp = PyObject_RichCompareBool(self->ob_item[i], v, Py_EQ); + if (cmp > 0) + return PyLong_FromSsize_t(i); + else if (cmp < 0) + return NULL; + } + PyErr_SetString(PyExc_ValueError, "tuple.index(x): x not in tuple"); + return NULL; } static PyObject * tuplecount(PyTupleObject *self, PyObject *v) { - Py_ssize_t count = 0; - Py_ssize_t i; + Py_ssize_t count = 0; + Py_ssize_t i; - for (i = 0; i < Py_SIZE(self); i++) { - int cmp = PyObject_RichCompareBool(self->ob_item[i], v, Py_EQ); - if (cmp > 0) - count++; - else if (cmp < 0) - return NULL; - } - return PyLong_FromSsize_t(count); + for (i = 0; i < Py_SIZE(self); i++) { + int cmp = PyObject_RichCompareBool(self->ob_item[i], v, Py_EQ); + if (cmp > 0) + count++; + else if (cmp < 0) + return NULL; + } + return PyLong_FromSsize_t(count); } static int tupletraverse(PyTupleObject *o, visitproc visit, void *arg) { - Py_ssize_t i; + Py_ssize_t i; - for (i = Py_SIZE(o); --i >= 0; ) - Py_VISIT(o->ob_item[i]); - return 0; + for (i = Py_SIZE(o); --i >= 0; ) + Py_VISIT(o->ob_item[i]); + return 0; } static PyObject * tuplerichcompare(PyObject *v, PyObject *w, int op) { - PyTupleObject *vt, *wt; - Py_ssize_t i; - Py_ssize_t vlen, wlen; - - if (!PyTuple_Check(v) || !PyTuple_Check(w)) { - Py_INCREF(Py_NotImplemented); - return Py_NotImplemented; - } - - vt = (PyTupleObject *)v; - wt = (PyTupleObject *)w; - - vlen = Py_SIZE(vt); - wlen = Py_SIZE(wt); - - /* Note: the corresponding code for lists has an "early out" test - * here when op is EQ or NE and the lengths differ. That pays there, - * but Tim was unable to find any real code where EQ/NE tuple - * compares don't have the same length, so testing for it here would - * have cost without benefit. - */ - - /* Search for the first index where items are different. - * Note that because tuples are immutable, it's safe to reuse - * vlen and wlen across the comparison calls. - */ - for (i = 0; i < vlen && i < wlen; i++) { - int k = PyObject_RichCompareBool(vt->ob_item[i], - wt->ob_item[i], Py_EQ); - if (k < 0) - return NULL; - if (!k) - break; - } - - if (i >= vlen || i >= wlen) { - /* No more items to compare -- compare sizes */ - int cmp; - PyObject *res; - switch (op) { - case Py_LT: cmp = vlen < wlen; break; - case Py_LE: cmp = vlen <= wlen; break; - case Py_EQ: cmp = vlen == wlen; break; - case Py_NE: cmp = vlen != wlen; break; - case Py_GT: cmp = vlen > wlen; break; - case Py_GE: cmp = vlen >= wlen; break; - default: return NULL; /* cannot happen */ - } - if (cmp) - res = Py_True; - else - res = Py_False; - Py_INCREF(res); - return res; - } - - /* We have an item that differs -- shortcuts for EQ/NE */ - if (op == Py_EQ) { - Py_INCREF(Py_False); - return Py_False; - } - if (op == Py_NE) { - Py_INCREF(Py_True); - return Py_True; - } + PyTupleObject *vt, *wt; + Py_ssize_t i; + Py_ssize_t vlen, wlen; + + if (!PyTuple_Check(v) || !PyTuple_Check(w)) { + Py_INCREF(Py_NotImplemented); + return Py_NotImplemented; + } + + vt = (PyTupleObject *)v; + wt = (PyTupleObject *)w; + + vlen = Py_SIZE(vt); + wlen = Py_SIZE(wt); + + /* Note: the corresponding code for lists has an "early out" test + * here when op is EQ or NE and the lengths differ. That pays there, + * but Tim was unable to find any real code where EQ/NE tuple + * compares don't have the same length, so testing for it here would + * have cost without benefit. + */ + + /* Search for the first index where items are different. + * Note that because tuples are immutable, it's safe to reuse + * vlen and wlen across the comparison calls. + */ + for (i = 0; i < vlen && i < wlen; i++) { + int k = PyObject_RichCompareBool(vt->ob_item[i], + wt->ob_item[i], Py_EQ); + if (k < 0) + return NULL; + if (!k) + break; + } + + if (i >= vlen || i >= wlen) { + /* No more items to compare -- compare sizes */ + int cmp; + PyObject *res; + switch (op) { + case Py_LT: cmp = vlen < wlen; break; + case Py_LE: cmp = vlen <= wlen; break; + case Py_EQ: cmp = vlen == wlen; break; + case Py_NE: cmp = vlen != wlen; break; + case Py_GT: cmp = vlen > wlen; break; + case Py_GE: cmp = vlen >= wlen; break; + default: return NULL; /* cannot happen */ + } + if (cmp) + res = Py_True; + else + res = Py_False; + Py_INCREF(res); + return res; + } + + /* We have an item that differs -- shortcuts for EQ/NE */ + if (op == Py_EQ) { + Py_INCREF(Py_False); + return Py_False; + } + if (op == Py_NE) { + Py_INCREF(Py_True); + return Py_True; + } - /* Compare the final item again using the proper operator */ - return PyObject_RichCompare(vt->ob_item[i], wt->ob_item[i], op); + /* Compare the final item again using the proper operator */ + return PyObject_RichCompare(vt->ob_item[i], wt->ob_item[i], op); } static PyObject * @@ -618,41 +618,41 @@ static PyObject * tuple_new(PyTypeObject *type, PyObject *args, PyObject *kwds) { - PyObject *arg = NULL; - static char *kwlist[] = {"sequence", 0}; + PyObject *arg = NULL; + static char *kwlist[] = {"sequence", 0}; - if (type != &PyTuple_Type) - return tuple_subtype_new(type, args, kwds); - if (!PyArg_ParseTupleAndKeywords(args, kwds, "|O:tuple", kwlist, &arg)) - return NULL; - - if (arg == NULL) - return PyTuple_New(0); - else - return PySequence_Tuple(arg); + if (type != &PyTuple_Type) + return tuple_subtype_new(type, args, kwds); + if (!PyArg_ParseTupleAndKeywords(args, kwds, "|O:tuple", kwlist, &arg)) + return NULL; + + if (arg == NULL) + return PyTuple_New(0); + else + return PySequence_Tuple(arg); } static PyObject * tuple_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds) { - PyObject *tmp, *newobj, *item; - Py_ssize_t i, n; + PyObject *tmp, *newobj, *item; + Py_ssize_t i, n; - assert(PyType_IsSubtype(type, &PyTuple_Type)); - tmp = tuple_new(&PyTuple_Type, args, kwds); - if (tmp == NULL) - return NULL; - assert(PyTuple_Check(tmp)); - newobj = type->tp_alloc(type, n = PyTuple_GET_SIZE(tmp)); - if (newobj == NULL) - return NULL; - for (i = 0; i < n; i++) { - item = PyTuple_GET_ITEM(tmp, i); - Py_INCREF(item); - PyTuple_SET_ITEM(newobj, i, item); - } - Py_DECREF(tmp); - return newobj; + assert(PyType_IsSubtype(type, &PyTuple_Type)); + tmp = tuple_new(&PyTuple_Type, args, kwds); + if (tmp == NULL) + return NULL; + assert(PyTuple_Check(tmp)); + newobj = type->tp_alloc(type, n = PyTuple_GET_SIZE(tmp)); + if (newobj == NULL) + return NULL; + for (i = 0; i < n; i++) { + item = PyTuple_GET_ITEM(tmp, i); + Py_INCREF(item); + PyTuple_SET_ITEM(newobj, i, item); + } + Py_DECREF(tmp); + return newobj; } PyDoc_STRVAR(tuple_doc, @@ -662,86 +662,86 @@ If the argument is a tuple, the return value is the same object."); static PySequenceMethods tuple_as_sequence = { - (lenfunc)tuplelength, /* sq_length */ - (binaryfunc)tupleconcat, /* sq_concat */ - (ssizeargfunc)tuplerepeat, /* sq_repeat */ - (ssizeargfunc)tupleitem, /* sq_item */ - 0, /* sq_slice */ - 0, /* sq_ass_item */ - 0, /* sq_ass_slice */ - (objobjproc)tuplecontains, /* sq_contains */ + (lenfunc)tuplelength, /* sq_length */ + (binaryfunc)tupleconcat, /* sq_concat */ + (ssizeargfunc)tuplerepeat, /* sq_repeat */ + (ssizeargfunc)tupleitem, /* sq_item */ + 0, /* sq_slice */ + 0, /* sq_ass_item */ + 0, /* sq_ass_slice */ + (objobjproc)tuplecontains, /* sq_contains */ }; static PyObject* tuplesubscript(PyTupleObject* 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 += PyTuple_GET_SIZE(self); - return tupleitem(self, i); - } - else if (PySlice_Check(item)) { - Py_ssize_t start, stop, step, slicelength, cur, i; - PyObject* result; - PyObject* it; - PyObject **src, **dest; - - if (PySlice_GetIndicesEx((PySliceObject*)item, - PyTuple_GET_SIZE(self), - &start, &stop, &step, &slicelength) < 0) { - return NULL; - } - - if (slicelength <= 0) { - return PyTuple_New(0); - } - else if (start == 0 && step == 1 && - slicelength == PyTuple_GET_SIZE(self) && - PyTuple_CheckExact(self)) { - Py_INCREF(self); - return (PyObject *)self; - } - else { - result = PyTuple_New(slicelength); - if (!result) return NULL; - - src = self->ob_item; - dest = ((PyTupleObject *)result)->ob_item; - for (cur = start, i = 0; i < slicelength; - cur += step, i++) { - it = src[cur]; - Py_INCREF(it); - dest[i] = it; - } - - return result; - } - } - else { - PyErr_Format(PyExc_TypeError, - "tuple indices must be integers, not %.200s", - Py_TYPE(item)->tp_name); - return NULL; - } + 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 += PyTuple_GET_SIZE(self); + return tupleitem(self, i); + } + else if (PySlice_Check(item)) { + Py_ssize_t start, stop, step, slicelength, cur, i; + PyObject* result; + PyObject* it; + PyObject **src, **dest; + + if (PySlice_GetIndicesEx((PySliceObject*)item, + PyTuple_GET_SIZE(self), + &start, &stop, &step, &slicelength) < 0) { + return NULL; + } + + if (slicelength <= 0) { + return PyTuple_New(0); + } + else if (start == 0 && step == 1 && + slicelength == PyTuple_GET_SIZE(self) && + PyTuple_CheckExact(self)) { + Py_INCREF(self); + return (PyObject *)self; + } + else { + result = PyTuple_New(slicelength); + if (!result) return NULL; + + src = self->ob_item; + dest = ((PyTupleObject *)result)->ob_item; + for (cur = start, i = 0; i < slicelength; + cur += step, i++) { + it = src[cur]; + Py_INCREF(it); + dest[i] = it; + } + + return result; + } + } + else { + PyErr_Format(PyExc_TypeError, + "tuple indices must be integers, not %.200s", + Py_TYPE(item)->tp_name); + return NULL; + } } static PyObject * tuple_getnewargs(PyTupleObject *v) { - return Py_BuildValue("(N)", tupleslice(v, 0, Py_SIZE(v))); - + return Py_BuildValue("(N)", tupleslice(v, 0, Py_SIZE(v))); + } static PyObject * tuple_sizeof(PyTupleObject *self) { - Py_ssize_t res; + Py_ssize_t res; - res = PyTuple_Type.tp_basicsize + Py_SIZE(self) * sizeof(PyObject *); - return PyLong_FromSsize_t(res); + res = PyTuple_Type.tp_basicsize + Py_SIZE(self) * sizeof(PyObject *); + return PyLong_FromSsize_t(res); } PyDoc_STRVAR(index_doc, @@ -754,62 +754,62 @@ "T.__sizeof__() -- size of T in memory, in bytes"); static PyMethodDef tuple_methods[] = { - {"__getnewargs__", (PyCFunction)tuple_getnewargs, METH_NOARGS}, - {"__sizeof__", (PyCFunction)tuple_sizeof, METH_NOARGS, sizeof_doc}, - {"index", (PyCFunction)tupleindex, METH_VARARGS, index_doc}, - {"count", (PyCFunction)tuplecount, METH_O, count_doc}, - {NULL, NULL} /* sentinel */ + {"__getnewargs__", (PyCFunction)tuple_getnewargs, METH_NOARGS}, + {"__sizeof__", (PyCFunction)tuple_sizeof, METH_NOARGS, sizeof_doc}, + {"index", (PyCFunction)tupleindex, METH_VARARGS, index_doc}, + {"count", (PyCFunction)tuplecount, METH_O, count_doc}, + {NULL, NULL} /* sentinel */ }; static PyMappingMethods tuple_as_mapping = { - (lenfunc)tuplelength, - (binaryfunc)tuplesubscript, - 0 + (lenfunc)tuplelength, + (binaryfunc)tuplesubscript, + 0 }; static PyObject *tuple_iter(PyObject *seq); PyTypeObject PyTuple_Type = { - PyVarObject_HEAD_INIT(&PyType_Type, 0) - "tuple", - sizeof(PyTupleObject) - sizeof(PyObject *), - sizeof(PyObject *), - (destructor)tupledealloc, /* tp_dealloc */ - 0, /* tp_print */ - 0, /* tp_getattr */ - 0, /* tp_setattr */ - 0, /* tp_reserved */ - (reprfunc)tuplerepr, /* tp_repr */ - 0, /* tp_as_number */ - &tuple_as_sequence, /* tp_as_sequence */ - &tuple_as_mapping, /* tp_as_mapping */ - (hashfunc)tuplehash, /* 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 | - Py_TPFLAGS_BASETYPE | Py_TPFLAGS_TUPLE_SUBCLASS, /* tp_flags */ - tuple_doc, /* tp_doc */ - (traverseproc)tupletraverse, /* tp_traverse */ - 0, /* tp_clear */ - tuplerichcompare, /* tp_richcompare */ - 0, /* tp_weaklistoffset */ - tuple_iter, /* tp_iter */ - 0, /* tp_iternext */ - tuple_methods, /* tp_methods */ - 0, /* tp_members */ - 0, /* tp_getset */ - 0, /* tp_base */ - 0, /* tp_dict */ - 0, /* tp_descr_get */ - 0, /* tp_descr_set */ - 0, /* tp_dictoffset */ - 0, /* tp_init */ - 0, /* tp_alloc */ - tuple_new, /* tp_new */ - PyObject_GC_Del, /* tp_free */ + PyVarObject_HEAD_INIT(&PyType_Type, 0) + "tuple", + sizeof(PyTupleObject) - sizeof(PyObject *), + sizeof(PyObject *), + (destructor)tupledealloc, /* tp_dealloc */ + 0, /* tp_print */ + 0, /* tp_getattr */ + 0, /* tp_setattr */ + 0, /* tp_reserved */ + (reprfunc)tuplerepr, /* tp_repr */ + 0, /* tp_as_number */ + &tuple_as_sequence, /* tp_as_sequence */ + &tuple_as_mapping, /* tp_as_mapping */ + (hashfunc)tuplehash, /* 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 | + Py_TPFLAGS_BASETYPE | Py_TPFLAGS_TUPLE_SUBCLASS, /* tp_flags */ + tuple_doc, /* tp_doc */ + (traverseproc)tupletraverse, /* tp_traverse */ + 0, /* tp_clear */ + tuplerichcompare, /* tp_richcompare */ + 0, /* tp_weaklistoffset */ + tuple_iter, /* tp_iter */ + 0, /* tp_iternext */ + tuple_methods, /* tp_methods */ + 0, /* tp_members */ + 0, /* tp_getset */ + 0, /* tp_base */ + 0, /* tp_dict */ + 0, /* tp_descr_get */ + 0, /* tp_descr_set */ + 0, /* tp_dictoffset */ + 0, /* tp_init */ + 0, /* tp_alloc */ + tuple_new, /* tp_new */ + PyObject_GC_Del, /* tp_free */ }; /* The following function breaks the notion that tuples are immutable: @@ -822,207 +822,207 @@ int _PyTuple_Resize(PyObject **pv, Py_ssize_t newsize) { - register PyTupleObject *v; - register PyTupleObject *sv; - Py_ssize_t i; - Py_ssize_t oldsize; - - v = (PyTupleObject *) *pv; - if (v == NULL || Py_TYPE(v) != &PyTuple_Type || - (Py_SIZE(v) != 0 && Py_REFCNT(v) != 1)) { - *pv = 0; - Py_XDECREF(v); - PyErr_BadInternalCall(); - return -1; - } - oldsize = Py_SIZE(v); - if (oldsize == newsize) - return 0; - - if (oldsize == 0) { - /* Empty tuples are often shared, so we should never - resize them in-place even if we do own the only - (current) reference */ - Py_DECREF(v); - *pv = PyTuple_New(newsize); - return *pv == NULL ? -1 : 0; - } - - /* XXX UNREF/NEWREF interface should be more symmetrical */ - _Py_DEC_REFTOTAL; - if (_PyObject_GC_IS_TRACKED(v)) - _PyObject_GC_UNTRACK(v); - _Py_ForgetReference((PyObject *) v); - /* DECREF items deleted by shrinkage */ - for (i = newsize; i < oldsize; i++) { - Py_XDECREF(v->ob_item[i]); - v->ob_item[i] = NULL; - } - sv = PyObject_GC_Resize(PyTupleObject, v, newsize); - if (sv == NULL) { - *pv = NULL; - PyObject_GC_Del(v); - return -1; - } - _Py_NewReference((PyObject *) sv); - /* Zero out items added by growing */ - if (newsize > oldsize) - memset(&sv->ob_item[oldsize], 0, - sizeof(*sv->ob_item) * (newsize - oldsize)); - *pv = (PyObject *) sv; - _PyObject_GC_TRACK(sv); - return 0; + register PyTupleObject *v; + register PyTupleObject *sv; + Py_ssize_t i; + Py_ssize_t oldsize; + + v = (PyTupleObject *) *pv; + if (v == NULL || Py_TYPE(v) != &PyTuple_Type || + (Py_SIZE(v) != 0 && Py_REFCNT(v) != 1)) { + *pv = 0; + Py_XDECREF(v); + PyErr_BadInternalCall(); + return -1; + } + oldsize = Py_SIZE(v); + if (oldsize == newsize) + return 0; + + if (oldsize == 0) { + /* Empty tuples are often shared, so we should never + resize them in-place even if we do own the only + (current) reference */ + Py_DECREF(v); + *pv = PyTuple_New(newsize); + return *pv == NULL ? -1 : 0; + } + + /* XXX UNREF/NEWREF interface should be more symmetrical */ + _Py_DEC_REFTOTAL; + if (_PyObject_GC_IS_TRACKED(v)) + _PyObject_GC_UNTRACK(v); + _Py_ForgetReference((PyObject *) v); + /* DECREF items deleted by shrinkage */ + for (i = newsize; i < oldsize; i++) { + Py_XDECREF(v->ob_item[i]); + v->ob_item[i] = NULL; + } + sv = PyObject_GC_Resize(PyTupleObject, v, newsize); + if (sv == NULL) { + *pv = NULL; + PyObject_GC_Del(v); + return -1; + } + _Py_NewReference((PyObject *) sv); + /* Zero out items added by growing */ + if (newsize > oldsize) + memset(&sv->ob_item[oldsize], 0, + sizeof(*sv->ob_item) * (newsize - oldsize)); + *pv = (PyObject *) sv; + _PyObject_GC_TRACK(sv); + return 0; } int PyTuple_ClearFreeList(void) { - int freelist_size = 0; + int freelist_size = 0; #if PyTuple_MAXSAVESIZE > 0 - int i; - for (i = 1; i < PyTuple_MAXSAVESIZE; i++) { - PyTupleObject *p, *q; - p = free_list[i]; - freelist_size += numfree[i]; - free_list[i] = NULL; - numfree[i] = 0; - while (p) { - q = p; - p = (PyTupleObject *)(p->ob_item[0]); - PyObject_GC_Del(q); - } - } + int i; + for (i = 1; i < PyTuple_MAXSAVESIZE; i++) { + PyTupleObject *p, *q; + p = free_list[i]; + freelist_size += numfree[i]; + free_list[i] = NULL; + numfree[i] = 0; + while (p) { + q = p; + p = (PyTupleObject *)(p->ob_item[0]); + PyObject_GC_Del(q); + } + } #endif - return freelist_size; + return freelist_size; } - + void PyTuple_Fini(void) { #if PyTuple_MAXSAVESIZE > 0 - /* empty tuples are used all over the place and applications may - * rely on the fact that an empty tuple is a singleton. */ - Py_XDECREF(free_list[0]); - free_list[0] = NULL; + /* empty tuples are used all over the place and applications may + * rely on the fact that an empty tuple is a singleton. */ + Py_XDECREF(free_list[0]); + free_list[0] = NULL; - (void)PyTuple_ClearFreeList(); + (void)PyTuple_ClearFreeList(); #endif #ifdef SHOW_TRACK_COUNT - show_track(); + show_track(); #endif } /*********************** Tuple Iterator **************************/ typedef struct { - PyObject_HEAD - long it_index; - PyTupleObject *it_seq; /* Set to NULL when iterator is exhausted */ + PyObject_HEAD + long it_index; + PyTupleObject *it_seq; /* Set to NULL when iterator is exhausted */ } tupleiterobject; static void tupleiter_dealloc(tupleiterobject *it) { - _PyObject_GC_UNTRACK(it); - Py_XDECREF(it->it_seq); - PyObject_GC_Del(it); + _PyObject_GC_UNTRACK(it); + Py_XDECREF(it->it_seq); + PyObject_GC_Del(it); } static int tupleiter_traverse(tupleiterobject *it, visitproc visit, void *arg) { - Py_VISIT(it->it_seq); - return 0; + Py_VISIT(it->it_seq); + return 0; } static PyObject * tupleiter_next(tupleiterobject *it) { - PyTupleObject *seq; - PyObject *item; + PyTupleObject *seq; + PyObject *item; - assert(it != NULL); - seq = it->it_seq; - if (seq == NULL) - return NULL; - assert(PyTuple_Check(seq)); - - if (it->it_index < PyTuple_GET_SIZE(seq)) { - item = PyTuple_GET_ITEM(seq, it->it_index); - ++it->it_index; - Py_INCREF(item); - return item; - } - - Py_DECREF(seq); - it->it_seq = NULL; - return NULL; + assert(it != NULL); + seq = it->it_seq; + if (seq == NULL) + return NULL; + assert(PyTuple_Check(seq)); + + if (it->it_index < PyTuple_GET_SIZE(seq)) { + item = PyTuple_GET_ITEM(seq, it->it_index); + ++it->it_index; + Py_INCREF(item); + return item; + } + + Py_DECREF(seq); + it->it_seq = NULL; + return NULL; } static PyObject * tupleiter_len(tupleiterobject *it) { - Py_ssize_t len = 0; - if (it->it_seq) - len = PyTuple_GET_SIZE(it->it_seq) - it->it_index; - return PyLong_FromSsize_t(len); + Py_ssize_t len = 0; + if (it->it_seq) + len = PyTuple_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 PyMethodDef tupleiter_methods[] = { - {"__length_hint__", (PyCFunction)tupleiter_len, METH_NOARGS, length_hint_doc}, - {NULL, NULL} /* sentinel */ + {"__length_hint__", (PyCFunction)tupleiter_len, METH_NOARGS, length_hint_doc}, + {NULL, NULL} /* sentinel */ }; PyTypeObject PyTupleIter_Type = { - PyVarObject_HEAD_INIT(&PyType_Type, 0) - "tuple_iterator", /* tp_name */ - sizeof(tupleiterobject), /* tp_basicsize */ - 0, /* tp_itemsize */ - /* methods */ - (destructor)tupleiter_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)tupleiter_traverse, /* tp_traverse */ - 0, /* tp_clear */ - 0, /* tp_richcompare */ - 0, /* tp_weaklistoffset */ - PyObject_SelfIter, /* tp_iter */ - (iternextfunc)tupleiter_next, /* tp_iternext */ - tupleiter_methods, /* tp_methods */ - 0, + PyVarObject_HEAD_INIT(&PyType_Type, 0) + "tuple_iterator", /* tp_name */ + sizeof(tupleiterobject), /* tp_basicsize */ + 0, /* tp_itemsize */ + /* methods */ + (destructor)tupleiter_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)tupleiter_traverse, /* tp_traverse */ + 0, /* tp_clear */ + 0, /* tp_richcompare */ + 0, /* tp_weaklistoffset */ + PyObject_SelfIter, /* tp_iter */ + (iternextfunc)tupleiter_next, /* tp_iternext */ + tupleiter_methods, /* tp_methods */ + 0, }; static PyObject * tuple_iter(PyObject *seq) { - tupleiterobject *it; + tupleiterobject *it; - if (!PyTuple_Check(seq)) { - PyErr_BadInternalCall(); - return NULL; - } - it = PyObject_GC_New(tupleiterobject, &PyTupleIter_Type); - if (it == NULL) - return NULL; - it->it_index = 0; - Py_INCREF(seq); - it->it_seq = (PyTupleObject *)seq; - _PyObject_GC_TRACK(it); - return (PyObject *)it; + if (!PyTuple_Check(seq)) { + PyErr_BadInternalCall(); + return NULL; + } + it = PyObject_GC_New(tupleiterobject, &PyTupleIter_Type); + if (it == NULL) + return NULL; + it->it_index = 0; + Py_INCREF(seq); + it->it_seq = (PyTupleObject *)seq; + _PyObject_GC_TRACK(it); + return (PyObject *)it; } Modified: python/branches/py3k-jit/Objects/typeobject.c ============================================================================== --- python/branches/py3k-jit/Objects/typeobject.c (original) +++ python/branches/py3k-jit/Objects/typeobject.c Mon May 10 23:55:43 2010 @@ -13,22 +13,22 @@ they normally would. This is why the maximum size is limited to MCACHE_MAX_ATTR_SIZE, since it might be a problem if very large strings are used as attribute names. */ -#define MCACHE_MAX_ATTR_SIZE 100 -#define MCACHE_SIZE_EXP 10 -#define MCACHE_HASH(version, name_hash) \ - (((unsigned int)(version) * (unsigned int)(name_hash)) \ - >> (8*sizeof(unsigned int) - MCACHE_SIZE_EXP)) +#define MCACHE_MAX_ATTR_SIZE 100 +#define MCACHE_SIZE_EXP 10 +#define MCACHE_HASH(version, name_hash) \ + (((unsigned int)(version) * (unsigned int)(name_hash)) \ + >> (8*sizeof(unsigned int) - MCACHE_SIZE_EXP)) #define MCACHE_HASH_METHOD(type, name) \ - MCACHE_HASH((type)->tp_version_tag, \ - ((PyUnicodeObject *)(name))->hash) + MCACHE_HASH((type)->tp_version_tag, \ + ((PyUnicodeObject *)(name))->hash) #define MCACHE_CACHEABLE_NAME(name) \ - PyUnicode_CheckExact(name) && \ - PyUnicode_GET_SIZE(name) <= MCACHE_MAX_ATTR_SIZE + PyUnicode_CheckExact(name) && \ + PyUnicode_GET_SIZE(name) <= MCACHE_MAX_ATTR_SIZE struct method_cache_entry { - unsigned int version; - PyObject *name; /* reference to exactly a str or None */ - PyObject *value; /* borrowed */ + unsigned int version; + PyObject *name; /* reference to exactly a str or None */ + PyObject *value; /* borrowed */ }; static struct method_cache_entry method_cache[1 << MCACHE_SIZE_EXP]; @@ -37,325 +37,325 @@ unsigned int PyType_ClearCache(void) { - Py_ssize_t i; - unsigned int cur_version_tag = next_version_tag - 1; - - for (i = 0; i < (1 << MCACHE_SIZE_EXP); i++) { - method_cache[i].version = 0; - Py_CLEAR(method_cache[i].name); - method_cache[i].value = NULL; - } - next_version_tag = 0; - /* mark all version tags as invalid */ - PyType_Modified(&PyBaseObject_Type); - return cur_version_tag; + Py_ssize_t i; + unsigned int cur_version_tag = next_version_tag - 1; + + for (i = 0; i < (1 << MCACHE_SIZE_EXP); i++) { + method_cache[i].version = 0; + Py_CLEAR(method_cache[i].name); + method_cache[i].value = NULL; + } + next_version_tag = 0; + /* mark all version tags as invalid */ + PyType_Modified(&PyBaseObject_Type); + return cur_version_tag; } void PyType_Modified(PyTypeObject *type) { - /* Invalidate any cached data for the specified type and all - subclasses. This function is called after the base - classes, mro, or attributes of the type are altered. - - Invariants: - - - Py_TPFLAGS_VALID_VERSION_TAG is never set if - Py_TPFLAGS_HAVE_VERSION_TAG is not set (e.g. on type - objects coming from non-recompiled extension modules) - - - before Py_TPFLAGS_VALID_VERSION_TAG can be set on a type, - it must first be set on all super types. - - This function clears the Py_TPFLAGS_VALID_VERSION_TAG of a - type (so it must first clear it on all subclasses). The - tp_version_tag value is meaningless unless this flag is set. - We don't assign new version tags eagerly, but only as - needed. - */ - PyObject *raw, *ref; - Py_ssize_t i, n; - - if (!PyType_HasFeature(type, Py_TPFLAGS_VALID_VERSION_TAG)) - return; - - raw = type->tp_subclasses; - if (raw != NULL) { - n = PyList_GET_SIZE(raw); - for (i = 0; i < n; i++) { - ref = PyList_GET_ITEM(raw, i); - ref = PyWeakref_GET_OBJECT(ref); - if (ref != Py_None) { - PyType_Modified((PyTypeObject *)ref); - } - } - } - type->tp_flags &= ~Py_TPFLAGS_VALID_VERSION_TAG; + /* Invalidate any cached data for the specified type and all + subclasses. This function is called after the base + classes, mro, or attributes of the type are altered. + + Invariants: + + - Py_TPFLAGS_VALID_VERSION_TAG is never set if + Py_TPFLAGS_HAVE_VERSION_TAG is not set (e.g. on type + objects coming from non-recompiled extension modules) + + - before Py_TPFLAGS_VALID_VERSION_TAG can be set on a type, + it must first be set on all super types. + + This function clears the Py_TPFLAGS_VALID_VERSION_TAG of a + type (so it must first clear it on all subclasses). The + tp_version_tag value is meaningless unless this flag is set. + We don't assign new version tags eagerly, but only as + needed. + */ + PyObject *raw, *ref; + Py_ssize_t i, n; + + if (!PyType_HasFeature(type, Py_TPFLAGS_VALID_VERSION_TAG)) + return; + + raw = type->tp_subclasses; + if (raw != NULL) { + n = PyList_GET_SIZE(raw); + for (i = 0; i < n; i++) { + ref = PyList_GET_ITEM(raw, i); + ref = PyWeakref_GET_OBJECT(ref); + if (ref != Py_None) { + PyType_Modified((PyTypeObject *)ref); + } + } + } + type->tp_flags &= ~Py_TPFLAGS_VALID_VERSION_TAG; } static void type_mro_modified(PyTypeObject *type, PyObject *bases) { - /* - Check that all base classes or elements of the mro of type are - able to be cached. This function is called after the base - classes or mro of the type are altered. - - Unset HAVE_VERSION_TAG and VALID_VERSION_TAG if the type - inherits from an old-style class, either directly or if it - appears in the MRO of a new-style class. No support either for - custom MROs that include types that are not officially super - types. - - Called from mro_internal, which will subsequently be called on - each subclass when their mro is recursively updated. - */ - Py_ssize_t i, n; - int clear = 0; - - if (!PyType_HasFeature(type, Py_TPFLAGS_HAVE_VERSION_TAG)) - return; - - n = PyTuple_GET_SIZE(bases); - for (i = 0; i < n; i++) { - PyObject *b = PyTuple_GET_ITEM(bases, i); - PyTypeObject *cls; - - if (!PyType_Check(b) ) { - clear = 1; - break; - } - - cls = (PyTypeObject *)b; - - if (!PyType_HasFeature(cls, Py_TPFLAGS_HAVE_VERSION_TAG) || - !PyType_IsSubtype(type, cls)) { - clear = 1; - break; - } - } - - if (clear) - type->tp_flags &= ~(Py_TPFLAGS_HAVE_VERSION_TAG| - Py_TPFLAGS_VALID_VERSION_TAG); + /* + Check that all base classes or elements of the mro of type are + able to be cached. This function is called after the base + classes or mro of the type are altered. + + Unset HAVE_VERSION_TAG and VALID_VERSION_TAG if the type + inherits from an old-style class, either directly or if it + appears in the MRO of a new-style class. No support either for + custom MROs that include types that are not officially super + types. + + Called from mro_internal, which will subsequently be called on + each subclass when their mro is recursively updated. + */ + Py_ssize_t i, n; + int clear = 0; + + if (!PyType_HasFeature(type, Py_TPFLAGS_HAVE_VERSION_TAG)) + return; + + n = PyTuple_GET_SIZE(bases); + for (i = 0; i < n; i++) { + PyObject *b = PyTuple_GET_ITEM(bases, i); + PyTypeObject *cls; + + if (!PyType_Check(b) ) { + clear = 1; + break; + } + + cls = (PyTypeObject *)b; + + if (!PyType_HasFeature(cls, Py_TPFLAGS_HAVE_VERSION_TAG) || + !PyType_IsSubtype(type, cls)) { + clear = 1; + break; + } + } + + if (clear) + type->tp_flags &= ~(Py_TPFLAGS_HAVE_VERSION_TAG| + Py_TPFLAGS_VALID_VERSION_TAG); } static int assign_version_tag(PyTypeObject *type) { - /* Ensure that the tp_version_tag is valid and set - Py_TPFLAGS_VALID_VERSION_TAG. To respect the invariant, this - must first be done on all super classes. Return 0 if this - cannot be done, 1 if Py_TPFLAGS_VALID_VERSION_TAG. - */ - Py_ssize_t i, n; - PyObject *bases; - - if (PyType_HasFeature(type, Py_TPFLAGS_VALID_VERSION_TAG)) - return 1; - if (!PyType_HasFeature(type, Py_TPFLAGS_HAVE_VERSION_TAG)) - return 0; - if (!PyType_HasFeature(type, Py_TPFLAGS_READY)) - return 0; - - type->tp_version_tag = next_version_tag++; - /* for stress-testing: next_version_tag &= 0xFF; */ - - if (type->tp_version_tag == 0) { - /* wrap-around or just starting Python - clear the whole - cache by filling names with references to Py_None. - Values are also set to NULL for added protection, as they - are borrowed reference */ - for (i = 0; i < (1 << MCACHE_SIZE_EXP); i++) { - method_cache[i].value = NULL; - Py_XDECREF(method_cache[i].name); - method_cache[i].name = Py_None; - Py_INCREF(Py_None); - } - /* mark all version tags as invalid */ - PyType_Modified(&PyBaseObject_Type); - return 1; - } - bases = type->tp_bases; - n = PyTuple_GET_SIZE(bases); - for (i = 0; i < n; i++) { - PyObject *b = PyTuple_GET_ITEM(bases, i); - assert(PyType_Check(b)); - if (!assign_version_tag((PyTypeObject *)b)) - return 0; - } - type->tp_flags |= Py_TPFLAGS_VALID_VERSION_TAG; - return 1; + /* Ensure that the tp_version_tag is valid and set + Py_TPFLAGS_VALID_VERSION_TAG. To respect the invariant, this + must first be done on all super classes. Return 0 if this + cannot be done, 1 if Py_TPFLAGS_VALID_VERSION_TAG. + */ + Py_ssize_t i, n; + PyObject *bases; + + if (PyType_HasFeature(type, Py_TPFLAGS_VALID_VERSION_TAG)) + return 1; + if (!PyType_HasFeature(type, Py_TPFLAGS_HAVE_VERSION_TAG)) + return 0; + if (!PyType_HasFeature(type, Py_TPFLAGS_READY)) + return 0; + + type->tp_version_tag = next_version_tag++; + /* for stress-testing: next_version_tag &= 0xFF; */ + + if (type->tp_version_tag == 0) { + /* wrap-around or just starting Python - clear the whole + cache by filling names with references to Py_None. + Values are also set to NULL for added protection, as they + are borrowed reference */ + for (i = 0; i < (1 << MCACHE_SIZE_EXP); i++) { + method_cache[i].value = NULL; + Py_XDECREF(method_cache[i].name); + method_cache[i].name = Py_None; + Py_INCREF(Py_None); + } + /* mark all version tags as invalid */ + PyType_Modified(&PyBaseObject_Type); + return 1; + } + bases = type->tp_bases; + n = PyTuple_GET_SIZE(bases); + for (i = 0; i < n; i++) { + PyObject *b = PyTuple_GET_ITEM(bases, i); + assert(PyType_Check(b)); + if (!assign_version_tag((PyTypeObject *)b)) + return 0; + } + type->tp_flags |= Py_TPFLAGS_VALID_VERSION_TAG; + return 1; } static PyMemberDef type_members[] = { - {"__basicsize__", T_INT, offsetof(PyTypeObject,tp_basicsize),READONLY}, - {"__itemsize__", T_INT, offsetof(PyTypeObject, tp_itemsize), READONLY}, - {"__flags__", T_LONG, offsetof(PyTypeObject, tp_flags), READONLY}, - {"__weakrefoffset__", T_LONG, - offsetof(PyTypeObject, tp_weaklistoffset), READONLY}, - {"__base__", T_OBJECT, offsetof(PyTypeObject, tp_base), READONLY}, - {"__dictoffset__", T_LONG, - offsetof(PyTypeObject, tp_dictoffset), READONLY}, - {"__mro__", T_OBJECT, offsetof(PyTypeObject, tp_mro), READONLY}, - {0} + {"__basicsize__", T_INT, offsetof(PyTypeObject,tp_basicsize),READONLY}, + {"__itemsize__", T_INT, offsetof(PyTypeObject, tp_itemsize), READONLY}, + {"__flags__", T_LONG, offsetof(PyTypeObject, tp_flags), READONLY}, + {"__weakrefoffset__", T_LONG, + offsetof(PyTypeObject, tp_weaklistoffset), READONLY}, + {"__base__", T_OBJECT, offsetof(PyTypeObject, tp_base), READONLY}, + {"__dictoffset__", T_LONG, + offsetof(PyTypeObject, tp_dictoffset), READONLY}, + {"__mro__", T_OBJECT, offsetof(PyTypeObject, tp_mro), READONLY}, + {0} }; static PyObject * type_name(PyTypeObject *type, void *context) { - const char *s; + const char *s; - if (type->tp_flags & Py_TPFLAGS_HEAPTYPE) { - PyHeapTypeObject* et = (PyHeapTypeObject*)type; + if (type->tp_flags & Py_TPFLAGS_HEAPTYPE) { + PyHeapTypeObject* et = (PyHeapTypeObject*)type; - Py_INCREF(et->ht_name); - return et->ht_name; - } - else { - s = strrchr(type->tp_name, '.'); - if (s == NULL) - s = type->tp_name; - else - s++; - return PyUnicode_FromString(s); - } + Py_INCREF(et->ht_name); + return et->ht_name; + } + else { + s = strrchr(type->tp_name, '.'); + if (s == NULL) + s = type->tp_name; + else + s++; + return PyUnicode_FromString(s); + } } static int type_set_name(PyTypeObject *type, PyObject *value, void *context) { - PyHeapTypeObject* et; - char *tp_name; - PyObject *tmp; - - if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE)) { - PyErr_Format(PyExc_TypeError, - "can't set %s.__name__", type->tp_name); - return -1; - } - if (!value) { - PyErr_Format(PyExc_TypeError, - "can't delete %s.__name__", type->tp_name); - return -1; - } - if (!PyUnicode_Check(value)) { - PyErr_Format(PyExc_TypeError, - "can only assign string to %s.__name__, not '%s'", - type->tp_name, Py_TYPE(value)->tp_name); - return -1; - } - - /* Check absence of null characters */ - tmp = PyUnicode_FromStringAndSize("\0", 1); - if (tmp == NULL) - return -1; - if (PyUnicode_Contains(value, tmp) != 0) { - Py_DECREF(tmp); - PyErr_Format(PyExc_ValueError, - "__name__ must not contain null bytes"); - return -1; - } - Py_DECREF(tmp); - - tp_name = _PyUnicode_AsString(value); - if (tp_name == NULL) - return -1; - - et = (PyHeapTypeObject*)type; + PyHeapTypeObject* et; + char *tp_name; + PyObject *tmp; + + if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE)) { + PyErr_Format(PyExc_TypeError, + "can't set %s.__name__", type->tp_name); + return -1; + } + if (!value) { + PyErr_Format(PyExc_TypeError, + "can't delete %s.__name__", type->tp_name); + return -1; + } + if (!PyUnicode_Check(value)) { + PyErr_Format(PyExc_TypeError, + "can only assign string to %s.__name__, not '%s'", + type->tp_name, Py_TYPE(value)->tp_name); + return -1; + } + + /* Check absence of null characters */ + tmp = PyUnicode_FromStringAndSize("\0", 1); + if (tmp == NULL) + return -1; + if (PyUnicode_Contains(value, tmp) != 0) { + Py_DECREF(tmp); + PyErr_Format(PyExc_ValueError, + "__name__ must not contain null bytes"); + return -1; + } + Py_DECREF(tmp); + + tp_name = _PyUnicode_AsString(value); + if (tp_name == NULL) + return -1; + + et = (PyHeapTypeObject*)type; - Py_INCREF(value); + Py_INCREF(value); - Py_DECREF(et->ht_name); - et->ht_name = value; + Py_DECREF(et->ht_name); + et->ht_name = value; - type->tp_name = tp_name; + type->tp_name = tp_name; - return 0; + return 0; } static PyObject * type_module(PyTypeObject *type, void *context) { - PyObject *mod; - char *s; + PyObject *mod; + char *s; - if (type->tp_flags & Py_TPFLAGS_HEAPTYPE) { - mod = PyDict_GetItemString(type->tp_dict, "__module__"); - if (!mod) { - PyErr_Format(PyExc_AttributeError, "__module__"); - return 0; - } - Py_XINCREF(mod); - return mod; - } - else { - s = strrchr(type->tp_name, '.'); - if (s != NULL) - return PyUnicode_FromStringAndSize( - type->tp_name, (Py_ssize_t)(s - type->tp_name)); - return PyUnicode_FromString("builtins"); - } + if (type->tp_flags & Py_TPFLAGS_HEAPTYPE) { + mod = PyDict_GetItemString(type->tp_dict, "__module__"); + if (!mod) { + PyErr_Format(PyExc_AttributeError, "__module__"); + return 0; + } + Py_XINCREF(mod); + return mod; + } + else { + s = strrchr(type->tp_name, '.'); + if (s != NULL) + return PyUnicode_FromStringAndSize( + type->tp_name, (Py_ssize_t)(s - type->tp_name)); + return PyUnicode_FromString("builtins"); + } } static int type_set_module(PyTypeObject *type, PyObject *value, void *context) { - if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE)) { - PyErr_Format(PyExc_TypeError, - "can't set %s.__module__", type->tp_name); - return -1; - } - if (!value) { - PyErr_Format(PyExc_TypeError, - "can't delete %s.__module__", type->tp_name); - return -1; - } + if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE)) { + PyErr_Format(PyExc_TypeError, + "can't set %s.__module__", type->tp_name); + return -1; + } + if (!value) { + PyErr_Format(PyExc_TypeError, + "can't delete %s.__module__", type->tp_name); + return -1; + } - PyType_Modified(type); + PyType_Modified(type); - return PyDict_SetItemString(type->tp_dict, "__module__", value); + return PyDict_SetItemString(type->tp_dict, "__module__", value); } static PyObject * type_abstractmethods(PyTypeObject *type, void *context) { - PyObject *mod = PyDict_GetItemString(type->tp_dict, - "__abstractmethods__"); - if (!mod) { - PyErr_Format(PyExc_AttributeError, "__abstractmethods__"); - return NULL; - } - Py_XINCREF(mod); - return mod; + PyObject *mod = PyDict_GetItemString(type->tp_dict, + "__abstractmethods__"); + if (!mod) { + PyErr_Format(PyExc_AttributeError, "__abstractmethods__"); + return NULL; + } + Py_XINCREF(mod); + return mod; } static int type_set_abstractmethods(PyTypeObject *type, PyObject *value, void *context) { - /* __abstractmethods__ should only be set once on a type, in - abc.ABCMeta.__new__, so this function doesn't do anything - special to update subclasses. - */ - int res = PyDict_SetItemString(type->tp_dict, - "__abstractmethods__", value); - if (res == 0) { - PyType_Modified(type); - if (value && PyObject_IsTrue(value)) { - type->tp_flags |= Py_TPFLAGS_IS_ABSTRACT; - } - else { - type->tp_flags &= ~Py_TPFLAGS_IS_ABSTRACT; - } - } - return res; + /* __abstractmethods__ should only be set once on a type, in + abc.ABCMeta.__new__, so this function doesn't do anything + special to update subclasses. + */ + int res = PyDict_SetItemString(type->tp_dict, + "__abstractmethods__", value); + if (res == 0) { + PyType_Modified(type); + if (value && PyObject_IsTrue(value)) { + type->tp_flags |= Py_TPFLAGS_IS_ABSTRACT; + } + else { + type->tp_flags &= ~Py_TPFLAGS_IS_ABSTRACT; + } + } + return res; } static PyObject * type_get_bases(PyTypeObject *type, void *context) { - Py_INCREF(type->tp_bases); - return type->tp_bases; + Py_INCREF(type->tp_bases); + return type->tp_bases; } static PyTypeObject *best_base(PyObject *); @@ -367,357 +367,357 @@ typedef int (*update_callback)(PyTypeObject *, void *); static int update_subclasses(PyTypeObject *type, PyObject *name, - update_callback callback, void *data); + update_callback callback, void *data); static int recurse_down_subclasses(PyTypeObject *type, PyObject *name, - update_callback callback, void *data); + update_callback callback, void *data); static int mro_subclasses(PyTypeObject *type, PyObject* temp) { - PyTypeObject *subclass; - PyObject *ref, *subclasses, *old_mro; - Py_ssize_t i, n; - - subclasses = type->tp_subclasses; - if (subclasses == NULL) - return 0; - assert(PyList_Check(subclasses)); - n = PyList_GET_SIZE(subclasses); - for (i = 0; i < n; i++) { - ref = PyList_GET_ITEM(subclasses, i); - assert(PyWeakref_CheckRef(ref)); - subclass = (PyTypeObject *)PyWeakref_GET_OBJECT(ref); - assert(subclass != NULL); - if ((PyObject *)subclass == Py_None) - continue; - assert(PyType_Check(subclass)); - old_mro = subclass->tp_mro; - if (mro_internal(subclass) < 0) { - subclass->tp_mro = old_mro; - return -1; - } - else { - PyObject* tuple; - tuple = PyTuple_Pack(2, subclass, old_mro); - Py_DECREF(old_mro); - if (!tuple) - return -1; - if (PyList_Append(temp, tuple) < 0) - return -1; - Py_DECREF(tuple); - } - if (mro_subclasses(subclass, temp) < 0) - return -1; - } - return 0; + PyTypeObject *subclass; + PyObject *ref, *subclasses, *old_mro; + Py_ssize_t i, n; + + subclasses = type->tp_subclasses; + if (subclasses == NULL) + return 0; + assert(PyList_Check(subclasses)); + n = PyList_GET_SIZE(subclasses); + for (i = 0; i < n; i++) { + ref = PyList_GET_ITEM(subclasses, i); + assert(PyWeakref_CheckRef(ref)); + subclass = (PyTypeObject *)PyWeakref_GET_OBJECT(ref); + assert(subclass != NULL); + if ((PyObject *)subclass == Py_None) + continue; + assert(PyType_Check(subclass)); + old_mro = subclass->tp_mro; + if (mro_internal(subclass) < 0) { + subclass->tp_mro = old_mro; + return -1; + } + else { + PyObject* tuple; + tuple = PyTuple_Pack(2, subclass, old_mro); + Py_DECREF(old_mro); + if (!tuple) + return -1; + if (PyList_Append(temp, tuple) < 0) + return -1; + Py_DECREF(tuple); + } + if (mro_subclasses(subclass, temp) < 0) + return -1; + } + return 0; } static int type_set_bases(PyTypeObject *type, PyObject *value, void *context) { - Py_ssize_t i; - int r = 0; - PyObject *ob, *temp; - PyTypeObject *new_base, *old_base; - PyObject *old_bases, *old_mro; - - if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE)) { - PyErr_Format(PyExc_TypeError, - "can't set %s.__bases__", type->tp_name); - return -1; - } - if (!value) { - PyErr_Format(PyExc_TypeError, - "can't delete %s.__bases__", type->tp_name); - return -1; - } - if (!PyTuple_Check(value)) { - PyErr_Format(PyExc_TypeError, - "can only assign tuple to %s.__bases__, not %s", - type->tp_name, Py_TYPE(value)->tp_name); - return -1; - } - if (PyTuple_GET_SIZE(value) == 0) { - PyErr_Format(PyExc_TypeError, - "can only assign non-empty tuple to %s.__bases__, not ()", - type->tp_name); - return -1; - } - for (i = 0; i < PyTuple_GET_SIZE(value); i++) { - ob = PyTuple_GET_ITEM(value, i); - if (!PyType_Check(ob)) { - PyErr_Format( - PyExc_TypeError, - "%s.__bases__ must be tuple of old- or new-style classes, not '%s'", - type->tp_name, Py_TYPE(ob)->tp_name); - return -1; - } - if (PyType_Check(ob)) { - if (PyType_IsSubtype((PyTypeObject*)ob, type)) { - PyErr_SetString(PyExc_TypeError, - "a __bases__ item causes an inheritance cycle"); - return -1; - } - } - } - - new_base = best_base(value); - - if (!new_base) { - return -1; - } - - if (!compatible_for_assignment(type->tp_base, new_base, "__bases__")) - return -1; - - Py_INCREF(new_base); - Py_INCREF(value); - - old_bases = type->tp_bases; - old_base = type->tp_base; - old_mro = type->tp_mro; - - type->tp_bases = value; - type->tp_base = new_base; - - if (mro_internal(type) < 0) { - goto bail; - } - - temp = PyList_New(0); - if (!temp) - goto bail; - - r = mro_subclasses(type, temp); - - if (r < 0) { - for (i = 0; i < PyList_Size(temp); i++) { - PyTypeObject* cls; - PyObject* mro; - PyArg_UnpackTuple(PyList_GET_ITEM(temp, i), - "", 2, 2, &cls, &mro); - Py_INCREF(mro); - ob = cls->tp_mro; - cls->tp_mro = mro; - Py_DECREF(ob); - } - Py_DECREF(temp); - goto bail; - } - - Py_DECREF(temp); - - /* any base that was in __bases__ but now isn't, we - need to remove |type| from its tp_subclasses. - conversely, any class now in __bases__ that wasn't - needs to have |type| added to its subclasses. */ - - /* for now, sod that: just remove from all old_bases, - add to all new_bases */ - - for (i = PyTuple_GET_SIZE(old_bases) - 1; i >= 0; i--) { - ob = PyTuple_GET_ITEM(old_bases, i); - if (PyType_Check(ob)) { - remove_subclass( - (PyTypeObject*)ob, type); - } - } - - for (i = PyTuple_GET_SIZE(value) - 1; i >= 0; i--) { - ob = PyTuple_GET_ITEM(value, i); - if (PyType_Check(ob)) { - if (add_subclass((PyTypeObject*)ob, type) < 0) - r = -1; - } - } - - update_all_slots(type); - - Py_DECREF(old_bases); - Py_DECREF(old_base); - Py_DECREF(old_mro); + Py_ssize_t i; + int r = 0; + PyObject *ob, *temp; + PyTypeObject *new_base, *old_base; + PyObject *old_bases, *old_mro; + + if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE)) { + PyErr_Format(PyExc_TypeError, + "can't set %s.__bases__", type->tp_name); + return -1; + } + if (!value) { + PyErr_Format(PyExc_TypeError, + "can't delete %s.__bases__", type->tp_name); + return -1; + } + if (!PyTuple_Check(value)) { + PyErr_Format(PyExc_TypeError, + "can only assign tuple to %s.__bases__, not %s", + type->tp_name, Py_TYPE(value)->tp_name); + return -1; + } + if (PyTuple_GET_SIZE(value) == 0) { + PyErr_Format(PyExc_TypeError, + "can only assign non-empty tuple to %s.__bases__, not ()", + type->tp_name); + return -1; + } + for (i = 0; i < PyTuple_GET_SIZE(value); i++) { + ob = PyTuple_GET_ITEM(value, i); + if (!PyType_Check(ob)) { + PyErr_Format( + PyExc_TypeError, + "%s.__bases__ must be tuple of old- or new-style classes, not '%s'", + type->tp_name, Py_TYPE(ob)->tp_name); + return -1; + } + if (PyType_Check(ob)) { + if (PyType_IsSubtype((PyTypeObject*)ob, type)) { + PyErr_SetString(PyExc_TypeError, + "a __bases__ item causes an inheritance cycle"); + return -1; + } + } + } + + new_base = best_base(value); + + if (!new_base) { + return -1; + } + + if (!compatible_for_assignment(type->tp_base, new_base, "__bases__")) + return -1; + + Py_INCREF(new_base); + Py_INCREF(value); + + old_bases = type->tp_bases; + old_base = type->tp_base; + old_mro = type->tp_mro; + + type->tp_bases = value; + type->tp_base = new_base; + + if (mro_internal(type) < 0) { + goto bail; + } + + temp = PyList_New(0); + if (!temp) + goto bail; + + r = mro_subclasses(type, temp); + + if (r < 0) { + for (i = 0; i < PyList_Size(temp); i++) { + PyTypeObject* cls; + PyObject* mro; + PyArg_UnpackTuple(PyList_GET_ITEM(temp, i), + "", 2, 2, &cls, &mro); + Py_INCREF(mro); + ob = cls->tp_mro; + cls->tp_mro = mro; + Py_DECREF(ob); + } + Py_DECREF(temp); + goto bail; + } + + Py_DECREF(temp); + + /* any base that was in __bases__ but now isn't, we + need to remove |type| from its tp_subclasses. + conversely, any class now in __bases__ that wasn't + needs to have |type| added to its subclasses. */ + + /* for now, sod that: just remove from all old_bases, + add to all new_bases */ + + for (i = PyTuple_GET_SIZE(old_bases) - 1; i >= 0; i--) { + ob = PyTuple_GET_ITEM(old_bases, i); + if (PyType_Check(ob)) { + remove_subclass( + (PyTypeObject*)ob, type); + } + } + + for (i = PyTuple_GET_SIZE(value) - 1; i >= 0; i--) { + ob = PyTuple_GET_ITEM(value, i); + if (PyType_Check(ob)) { + if (add_subclass((PyTypeObject*)ob, type) < 0) + r = -1; + } + } + + update_all_slots(type); + + Py_DECREF(old_bases); + Py_DECREF(old_base); + Py_DECREF(old_mro); - return r; + return r; bail: - Py_DECREF(type->tp_bases); - Py_DECREF(type->tp_base); - if (type->tp_mro != old_mro) { - Py_DECREF(type->tp_mro); - } - - type->tp_bases = old_bases; - type->tp_base = old_base; - type->tp_mro = old_mro; + Py_DECREF(type->tp_bases); + Py_DECREF(type->tp_base); + if (type->tp_mro != old_mro) { + Py_DECREF(type->tp_mro); + } + + type->tp_bases = old_bases; + type->tp_base = old_base; + type->tp_mro = old_mro; - return -1; + return -1; } static PyObject * type_dict(PyTypeObject *type, void *context) { - if (type->tp_dict == NULL) { - Py_INCREF(Py_None); - return Py_None; - } - return PyDictProxy_New(type->tp_dict); + if (type->tp_dict == NULL) { + Py_INCREF(Py_None); + return Py_None; + } + return PyDictProxy_New(type->tp_dict); } static PyObject * type_get_doc(PyTypeObject *type, void *context) { - PyObject *result; - if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE) && type->tp_doc != NULL) - return PyUnicode_FromString(type->tp_doc); - result = PyDict_GetItemString(type->tp_dict, "__doc__"); - if (result == NULL) { - result = Py_None; - Py_INCREF(result); - } - else if (Py_TYPE(result)->tp_descr_get) { - result = Py_TYPE(result)->tp_descr_get(result, NULL, - (PyObject *)type); - } - else { - Py_INCREF(result); - } - return result; + PyObject *result; + if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE) && type->tp_doc != NULL) + return PyUnicode_FromString(type->tp_doc); + result = PyDict_GetItemString(type->tp_dict, "__doc__"); + if (result == NULL) { + result = Py_None; + Py_INCREF(result); + } + else if (Py_TYPE(result)->tp_descr_get) { + result = Py_TYPE(result)->tp_descr_get(result, NULL, + (PyObject *)type); + } + else { + Py_INCREF(result); + } + return result; } static PyObject * type___instancecheck__(PyObject *type, PyObject *inst) { - switch (_PyObject_RealIsInstance(inst, type)) { - case -1: - return NULL; - case 0: - Py_RETURN_FALSE; - default: - Py_RETURN_TRUE; - } + switch (_PyObject_RealIsInstance(inst, type)) { + case -1: + return NULL; + case 0: + Py_RETURN_FALSE; + default: + Py_RETURN_TRUE; + } } static PyObject * type___subclasscheck__(PyObject *type, PyObject *inst) { - switch (_PyObject_RealIsSubclass(inst, type)) { - case -1: - return NULL; - case 0: - Py_RETURN_FALSE; - default: - Py_RETURN_TRUE; - } + switch (_PyObject_RealIsSubclass(inst, type)) { + case -1: + return NULL; + case 0: + Py_RETURN_FALSE; + default: + Py_RETURN_TRUE; + } } static PyGetSetDef type_getsets[] = { - {"__name__", (getter)type_name, (setter)type_set_name, NULL}, - {"__bases__", (getter)type_get_bases, (setter)type_set_bases, NULL}, - {"__module__", (getter)type_module, (setter)type_set_module, NULL}, - {"__abstractmethods__", (getter)type_abstractmethods, - (setter)type_set_abstractmethods, NULL}, - {"__dict__", (getter)type_dict, NULL, NULL}, - {"__doc__", (getter)type_get_doc, NULL, NULL}, - {0} + {"__name__", (getter)type_name, (setter)type_set_name, NULL}, + {"__bases__", (getter)type_get_bases, (setter)type_set_bases, NULL}, + {"__module__", (getter)type_module, (setter)type_set_module, NULL}, + {"__abstractmethods__", (getter)type_abstractmethods, + (setter)type_set_abstractmethods, NULL}, + {"__dict__", (getter)type_dict, NULL, NULL}, + {"__doc__", (getter)type_get_doc, NULL, NULL}, + {0} }; static PyObject * type_repr(PyTypeObject *type) { - PyObject *mod, *name, *rtn; + PyObject *mod, *name, *rtn; - mod = type_module(type, NULL); - if (mod == NULL) - PyErr_Clear(); - else if (!PyUnicode_Check(mod)) { - Py_DECREF(mod); - mod = NULL; - } - name = type_name(type, NULL); - if (name == NULL) - return NULL; - - if (mod != NULL && PyUnicode_CompareWithASCIIString(mod, "builtins")) - rtn = PyUnicode_FromFormat("", mod, name); - else - rtn = PyUnicode_FromFormat("", type->tp_name); - - Py_XDECREF(mod); - Py_DECREF(name); - return rtn; + mod = type_module(type, NULL); + if (mod == NULL) + PyErr_Clear(); + else if (!PyUnicode_Check(mod)) { + Py_DECREF(mod); + mod = NULL; + } + name = type_name(type, NULL); + if (name == NULL) + return NULL; + + if (mod != NULL && PyUnicode_CompareWithASCIIString(mod, "builtins")) + rtn = PyUnicode_FromFormat("", mod, name); + else + rtn = PyUnicode_FromFormat("", type->tp_name); + + Py_XDECREF(mod); + Py_DECREF(name); + return rtn; } static PyObject * type_call(PyTypeObject *type, PyObject *args, PyObject *kwds) { - PyObject *obj; + PyObject *obj; - if (type->tp_new == NULL) { - PyErr_Format(PyExc_TypeError, - "cannot create '%.100s' instances", - type->tp_name); - return NULL; - } - - obj = type->tp_new(type, args, kwds); - if (obj != NULL) { - /* Ugly exception: when the call was type(something), - don't call tp_init on the result. */ - if (type == &PyType_Type && - PyTuple_Check(args) && PyTuple_GET_SIZE(args) == 1 && - (kwds == NULL || - (PyDict_Check(kwds) && PyDict_Size(kwds) == 0))) - return obj; - /* If the returned object is not an instance of type, - it won't be initialized. */ - if (!PyType_IsSubtype(Py_TYPE(obj), type)) - return obj; - type = Py_TYPE(obj); - if (type->tp_init != NULL && - type->tp_init(obj, args, kwds) < 0) { - Py_DECREF(obj); - obj = NULL; - } - } - return obj; + if (type->tp_new == NULL) { + PyErr_Format(PyExc_TypeError, + "cannot create '%.100s' instances", + type->tp_name); + return NULL; + } + + obj = type->tp_new(type, args, kwds); + if (obj != NULL) { + /* Ugly exception: when the call was type(something), + don't call tp_init on the result. */ + if (type == &PyType_Type && + PyTuple_Check(args) && PyTuple_GET_SIZE(args) == 1 && + (kwds == NULL || + (PyDict_Check(kwds) && PyDict_Size(kwds) == 0))) + return obj; + /* If the returned object is not an instance of type, + it won't be initialized. */ + if (!PyType_IsSubtype(Py_TYPE(obj), type)) + return obj; + type = Py_TYPE(obj); + if (type->tp_init != NULL && + type->tp_init(obj, args, kwds) < 0) { + Py_DECREF(obj); + obj = NULL; + } + } + return obj; } PyObject * PyType_GenericAlloc(PyTypeObject *type, Py_ssize_t nitems) { - PyObject *obj; - const size_t size = _PyObject_VAR_SIZE(type, nitems+1); - /* note that we need to add one, for the sentinel */ - - if (PyType_IS_GC(type)) - obj = _PyObject_GC_Malloc(size); - else - obj = (PyObject *)PyObject_MALLOC(size); - - if (obj == NULL) - return PyErr_NoMemory(); - - memset(obj, '\0', size); - - if (type->tp_flags & Py_TPFLAGS_HEAPTYPE) - Py_INCREF(type); - - if (type->tp_itemsize == 0) - PyObject_INIT(obj, type); - else - (void) PyObject_INIT_VAR((PyVarObject *)obj, type, nitems); - - if (PyType_IS_GC(type)) - _PyObject_GC_TRACK(obj); - return obj; + PyObject *obj; + const size_t size = _PyObject_VAR_SIZE(type, nitems+1); + /* note that we need to add one, for the sentinel */ + + if (PyType_IS_GC(type)) + obj = _PyObject_GC_Malloc(size); + else + obj = (PyObject *)PyObject_MALLOC(size); + + if (obj == NULL) + return PyErr_NoMemory(); + + memset(obj, '\0', size); + + if (type->tp_flags & Py_TPFLAGS_HEAPTYPE) + Py_INCREF(type); + + if (type->tp_itemsize == 0) + PyObject_INIT(obj, type); + else + (void) PyObject_INIT_VAR((PyVarObject *)obj, type, nitems); + + if (PyType_IS_GC(type)) + _PyObject_GC_TRACK(obj); + return obj; } PyObject * PyType_GenericNew(PyTypeObject *type, PyObject *args, PyObject *kwds) { - return type->tp_alloc(type, 0); + return type->tp_alloc(type, 0); } /* Helpers for subtyping */ @@ -725,341 +725,341 @@ static int traverse_slots(PyTypeObject *type, PyObject *self, visitproc visit, void *arg) { - Py_ssize_t i, n; - PyMemberDef *mp; + Py_ssize_t i, n; + PyMemberDef *mp; - n = Py_SIZE(type); - mp = PyHeapType_GET_MEMBERS((PyHeapTypeObject *)type); - for (i = 0; i < n; i++, mp++) { - if (mp->type == T_OBJECT_EX) { - char *addr = (char *)self + mp->offset; - PyObject *obj = *(PyObject **)addr; - if (obj != NULL) { - int err = visit(obj, arg); - if (err) - return err; - } - } - } - return 0; + n = Py_SIZE(type); + mp = PyHeapType_GET_MEMBERS((PyHeapTypeObject *)type); + for (i = 0; i < n; i++, mp++) { + if (mp->type == T_OBJECT_EX) { + char *addr = (char *)self + mp->offset; + PyObject *obj = *(PyObject **)addr; + if (obj != NULL) { + int err = visit(obj, arg); + if (err) + return err; + } + } + } + return 0; } static int subtype_traverse(PyObject *self, visitproc visit, void *arg) { - PyTypeObject *type, *base; - traverseproc basetraverse; + PyTypeObject *type, *base; + traverseproc basetraverse; - /* Find the nearest base with a different tp_traverse, - and traverse slots while we're at it */ - type = Py_TYPE(self); - base = type; - while ((basetraverse = base->tp_traverse) == subtype_traverse) { - if (Py_SIZE(base)) { - int err = traverse_slots(base, self, visit, arg); - if (err) - return err; - } - base = base->tp_base; - assert(base); - } - - if (type->tp_dictoffset != base->tp_dictoffset) { - PyObject **dictptr = _PyObject_GetDictPtr(self); - if (dictptr && *dictptr) - Py_VISIT(*dictptr); - } - - if (type->tp_flags & Py_TPFLAGS_HEAPTYPE) - /* For a heaptype, the instances count as references - to the type. Traverse the type so the collector - can find cycles involving this link. */ - Py_VISIT(type); - - if (basetraverse) - return basetraverse(self, visit, arg); - return 0; + /* Find the nearest base with a different tp_traverse, + and traverse slots while we're at it */ + type = Py_TYPE(self); + base = type; + while ((basetraverse = base->tp_traverse) == subtype_traverse) { + if (Py_SIZE(base)) { + int err = traverse_slots(base, self, visit, arg); + if (err) + return err; + } + base = base->tp_base; + assert(base); + } + + if (type->tp_dictoffset != base->tp_dictoffset) { + PyObject **dictptr = _PyObject_GetDictPtr(self); + if (dictptr && *dictptr) + Py_VISIT(*dictptr); + } + + if (type->tp_flags & Py_TPFLAGS_HEAPTYPE) + /* For a heaptype, the instances count as references + to the type. Traverse the type so the collector + can find cycles involving this link. */ + Py_VISIT(type); + + if (basetraverse) + return basetraverse(self, visit, arg); + return 0; } static void clear_slots(PyTypeObject *type, PyObject *self) { - Py_ssize_t i, n; - PyMemberDef *mp; + Py_ssize_t i, n; + PyMemberDef *mp; - n = Py_SIZE(type); - mp = PyHeapType_GET_MEMBERS((PyHeapTypeObject *)type); - for (i = 0; i < n; i++, mp++) { - if (mp->type == T_OBJECT_EX && !(mp->flags & READONLY)) { - char *addr = (char *)self + mp->offset; - PyObject *obj = *(PyObject **)addr; - if (obj != NULL) { - *(PyObject **)addr = NULL; - Py_DECREF(obj); - } - } - } + n = Py_SIZE(type); + mp = PyHeapType_GET_MEMBERS((PyHeapTypeObject *)type); + for (i = 0; i < n; i++, mp++) { + if (mp->type == T_OBJECT_EX && !(mp->flags & READONLY)) { + char *addr = (char *)self + mp->offset; + PyObject *obj = *(PyObject **)addr; + if (obj != NULL) { + *(PyObject **)addr = NULL; + Py_DECREF(obj); + } + } + } } static int subtype_clear(PyObject *self) { - PyTypeObject *type, *base; - inquiry baseclear; + PyTypeObject *type, *base; + inquiry baseclear; - /* Find the nearest base with a different tp_clear - and clear slots while we're at it */ - type = Py_TYPE(self); - base = type; - while ((baseclear = base->tp_clear) == subtype_clear) { - if (Py_SIZE(base)) - clear_slots(base, self); - base = base->tp_base; - assert(base); - } - - /* There's no need to clear the instance dict (if any); - the collector will call its tp_clear handler. */ - - if (baseclear) - return baseclear(self); - return 0; + /* Find the nearest base with a different tp_clear + and clear slots while we're at it */ + type = Py_TYPE(self); + base = type; + while ((baseclear = base->tp_clear) == subtype_clear) { + if (Py_SIZE(base)) + clear_slots(base, self); + base = base->tp_base; + assert(base); + } + + /* There's no need to clear the instance dict (if any); + the collector will call its tp_clear handler. */ + + if (baseclear) + return baseclear(self); + return 0; } static void subtype_dealloc(PyObject *self) { - PyTypeObject *type, *base; - destructor basedealloc; + PyTypeObject *type, *base; + destructor basedealloc; + + /* Extract the type; we expect it to be a heap type */ + type = Py_TYPE(self); + assert(type->tp_flags & Py_TPFLAGS_HEAPTYPE); + + /* Test whether the type has GC exactly once */ + + if (!PyType_IS_GC(type)) { + /* It's really rare to find a dynamic type that doesn't have + GC; it can only happen when deriving from 'object' and not + adding any slots or instance variables. This allows + certain simplifications: there's no need to call + clear_slots(), or DECREF the dict, or clear weakrefs. */ + + /* Maybe call finalizer; exit early if resurrected */ + if (type->tp_del) { + type->tp_del(self); + if (self->ob_refcnt > 0) + return; + } + + /* Find the nearest base with a different tp_dealloc */ + base = type; + while ((basedealloc = base->tp_dealloc) == subtype_dealloc) { + assert(Py_SIZE(base) == 0); + base = base->tp_base; + assert(base); + } + + /* Extract the type again; tp_del may have changed it */ + type = Py_TYPE(self); + + /* Call the base tp_dealloc() */ + assert(basedealloc); + basedealloc(self); + + /* Can't reference self beyond this point */ + Py_DECREF(type); + + /* Done */ + return; + } + + /* We get here only if the type has GC */ + + /* UnTrack and re-Track around the trashcan macro, alas */ + /* See explanation at end of function for full disclosure */ + PyObject_GC_UnTrack(self); + ++_PyTrash_delete_nesting; + Py_TRASHCAN_SAFE_BEGIN(self); + --_PyTrash_delete_nesting; + /* DO NOT restore GC tracking at this point. weakref callbacks + * (if any, and whether directly here or indirectly in something we + * call) may trigger GC, and if self is tracked at that point, it + * will look like trash to GC and GC will try to delete self again. + */ + + /* Find the nearest base with a different tp_dealloc */ + base = type; + while ((basedealloc = base->tp_dealloc) == subtype_dealloc) { + base = base->tp_base; + assert(base); + } + + /* If we added a weaklist, we clear it. Do this *before* calling + the finalizer (__del__), clearing slots, or clearing the instance + dict. */ + + if (type->tp_weaklistoffset && !base->tp_weaklistoffset) + PyObject_ClearWeakRefs(self); + + /* Maybe call finalizer; exit early if resurrected */ + if (type->tp_del) { + _PyObject_GC_TRACK(self); + type->tp_del(self); + if (self->ob_refcnt > 0) + goto endlabel; /* resurrected */ + else + _PyObject_GC_UNTRACK(self); + /* New weakrefs could be created during the finalizer call. + If this occurs, clear them out without calling their + finalizers since they might rely on part of the object + being finalized that has already been destroyed. */ + if (type->tp_weaklistoffset && !base->tp_weaklistoffset) { + /* Modeled after GET_WEAKREFS_LISTPTR() */ + PyWeakReference **list = (PyWeakReference **) \ + PyObject_GET_WEAKREFS_LISTPTR(self); + while (*list) + _PyWeakref_ClearRef(*list); + } + } - /* Extract the type; we expect it to be a heap type */ - type = Py_TYPE(self); - assert(type->tp_flags & Py_TPFLAGS_HEAPTYPE); - - /* Test whether the type has GC exactly once */ - - if (!PyType_IS_GC(type)) { - /* It's really rare to find a dynamic type that doesn't have - GC; it can only happen when deriving from 'object' and not - adding any slots or instance variables. This allows - certain simplifications: there's no need to call - clear_slots(), or DECREF the dict, or clear weakrefs. */ - - /* Maybe call finalizer; exit early if resurrected */ - if (type->tp_del) { - type->tp_del(self); - if (self->ob_refcnt > 0) - return; - } - - /* Find the nearest base with a different tp_dealloc */ - base = type; - while ((basedealloc = base->tp_dealloc) == subtype_dealloc) { - assert(Py_SIZE(base) == 0); - base = base->tp_base; - assert(base); - } - - /* Extract the type again; tp_del may have changed it */ - type = Py_TYPE(self); - - /* Call the base tp_dealloc() */ - assert(basedealloc); - basedealloc(self); - - /* Can't reference self beyond this point */ - Py_DECREF(type); - - /* Done */ - return; - } - - /* We get here only if the type has GC */ - - /* UnTrack and re-Track around the trashcan macro, alas */ - /* See explanation at end of function for full disclosure */ - PyObject_GC_UnTrack(self); - ++_PyTrash_delete_nesting; - Py_TRASHCAN_SAFE_BEGIN(self); - --_PyTrash_delete_nesting; - /* DO NOT restore GC tracking at this point. weakref callbacks - * (if any, and whether directly here or indirectly in something we - * call) may trigger GC, and if self is tracked at that point, it - * will look like trash to GC and GC will try to delete self again. - */ - - /* Find the nearest base with a different tp_dealloc */ - base = type; - while ((basedealloc = base->tp_dealloc) == subtype_dealloc) { - base = base->tp_base; - assert(base); - } - - /* If we added a weaklist, we clear it. Do this *before* calling - the finalizer (__del__), clearing slots, or clearing the instance - dict. */ - - if (type->tp_weaklistoffset && !base->tp_weaklistoffset) - PyObject_ClearWeakRefs(self); - - /* Maybe call finalizer; exit early if resurrected */ - if (type->tp_del) { - _PyObject_GC_TRACK(self); - type->tp_del(self); - if (self->ob_refcnt > 0) - goto endlabel; /* resurrected */ - else - _PyObject_GC_UNTRACK(self); - /* New weakrefs could be created during the finalizer call. - If this occurs, clear them out without calling their - finalizers since they might rely on part of the object - being finalized that has already been destroyed. */ - if (type->tp_weaklistoffset && !base->tp_weaklistoffset) { - /* Modeled after GET_WEAKREFS_LISTPTR() */ - PyWeakReference **list = (PyWeakReference **) \ - PyObject_GET_WEAKREFS_LISTPTR(self); - while (*list) - _PyWeakref_ClearRef(*list); - } - } - - /* Clear slots up to the nearest base with a different tp_dealloc */ - base = type; - while ((basedealloc = base->tp_dealloc) == subtype_dealloc) { - if (Py_SIZE(base)) - clear_slots(base, self); - base = base->tp_base; - assert(base); - } - - /* If we added a dict, DECREF it */ - if (type->tp_dictoffset && !base->tp_dictoffset) { - PyObject **dictptr = _PyObject_GetDictPtr(self); - if (dictptr != NULL) { - PyObject *dict = *dictptr; - if (dict != NULL) { - Py_DECREF(dict); - *dictptr = NULL; - } - } - } - - /* Extract the type again; tp_del may have changed it */ - type = Py_TYPE(self); - - /* Call the base tp_dealloc(); first retrack self if - * basedealloc knows about gc. - */ - if (PyType_IS_GC(base)) - _PyObject_GC_TRACK(self); - assert(basedealloc); - basedealloc(self); + /* Clear slots up to the nearest base with a different tp_dealloc */ + base = type; + while ((basedealloc = base->tp_dealloc) == subtype_dealloc) { + if (Py_SIZE(base)) + clear_slots(base, self); + base = base->tp_base; + assert(base); + } + + /* If we added a dict, DECREF it */ + if (type->tp_dictoffset && !base->tp_dictoffset) { + PyObject **dictptr = _PyObject_GetDictPtr(self); + if (dictptr != NULL) { + PyObject *dict = *dictptr; + if (dict != NULL) { + Py_DECREF(dict); + *dictptr = NULL; + } + } + } + + /* Extract the type again; tp_del may have changed it */ + type = Py_TYPE(self); + + /* Call the base tp_dealloc(); first retrack self if + * basedealloc knows about gc. + */ + if (PyType_IS_GC(base)) + _PyObject_GC_TRACK(self); + assert(basedealloc); + basedealloc(self); - /* Can't reference self beyond this point */ - Py_DECREF(type); + /* Can't reference self beyond this point */ + Py_DECREF(type); endlabel: - ++_PyTrash_delete_nesting; - Py_TRASHCAN_SAFE_END(self); - --_PyTrash_delete_nesting; + ++_PyTrash_delete_nesting; + Py_TRASHCAN_SAFE_END(self); + --_PyTrash_delete_nesting; - /* Explanation of the weirdness around the trashcan macros: + /* Explanation of the weirdness around the trashcan macros: - Q. What do the trashcan macros do? + Q. What do the trashcan macros do? - A. Read the comment titled "Trashcan mechanism" in object.h. - For one, this explains why there must be a call to GC-untrack - before the trashcan begin macro. Without understanding the - trashcan code, the answers to the following questions don't make - sense. + A. Read the comment titled "Trashcan mechanism" in object.h. + For one, this explains why there must be a call to GC-untrack + before the trashcan begin macro. Without understanding the + trashcan code, the answers to the following questions don't make + sense. - Q. Why do we GC-untrack before the trashcan and then immediately - GC-track again afterward? + Q. Why do we GC-untrack before the trashcan and then immediately + GC-track again afterward? - A. In the case that the base class is GC-aware, the base class - probably GC-untracks the object. If it does that using the - UNTRACK macro, this will crash when the object is already - untracked. Because we don't know what the base class does, the - only safe thing is to make sure the object is tracked when we - call the base class dealloc. But... The trashcan begin macro - requires that the object is *untracked* before it is called. So - the dance becomes: + A. In the case that the base class is GC-aware, the base class + probably GC-untracks the object. If it does that using the + UNTRACK macro, this will crash when the object is already + untracked. Because we don't know what the base class does, the + only safe thing is to make sure the object is tracked when we + call the base class dealloc. But... The trashcan begin macro + requires that the object is *untracked* before it is called. So + the dance becomes: - GC untrack - trashcan begin - GC track + GC untrack + trashcan begin + GC track - Q. Why did the last question say "immediately GC-track again"? - It's nowhere near immediately. + Q. Why did the last question say "immediately GC-track again"? + It's nowhere near immediately. - A. Because the code *used* to re-track immediately. Bad Idea. - self has a refcount of 0, and if gc ever gets its hands on it - (which can happen if any weakref callback gets invoked), it - looks like trash to gc too, and gc also tries to delete self - then. But we're already deleting self. Double dealloction is - a subtle disaster. + A. Because the code *used* to re-track immediately. Bad Idea. + self has a refcount of 0, and if gc ever gets its hands on it + (which can happen if any weakref callback gets invoked), it + looks like trash to gc too, and gc also tries to delete self + then. But we're already deleting self. Double dealloction is + a subtle disaster. - Q. Why the bizarre (net-zero) manipulation of - _PyTrash_delete_nesting around the trashcan macros? + Q. Why the bizarre (net-zero) manipulation of + _PyTrash_delete_nesting around the trashcan macros? - A. Some base classes (e.g. list) also use the trashcan mechanism. - The following scenario used to be possible: + A. Some base classes (e.g. list) also use the trashcan mechanism. + The following scenario used to be possible: - - suppose the trashcan level is one below the trashcan limit + - suppose the trashcan level is one below the trashcan limit - - subtype_dealloc() is called + - subtype_dealloc() is called - - the trashcan limit is not yet reached, so the trashcan level - is incremented and the code between trashcan begin and end is - executed + - the trashcan limit is not yet reached, so the trashcan level + is incremented and the code between trashcan begin and end is + executed - - this destroys much of the object's contents, including its - slots and __dict__ + - this destroys much of the object's contents, including its + slots and __dict__ - - basedealloc() is called; this is really list_dealloc(), or - some other type which also uses the trashcan macros + - basedealloc() is called; this is really list_dealloc(), or + some other type which also uses the trashcan macros - - the trashcan limit is now reached, so the object is put on the - trashcan's to-be-deleted-later list + - the trashcan limit is now reached, so the object is put on the + trashcan's to-be-deleted-later list - - basedealloc() returns + - basedealloc() returns - - subtype_dealloc() decrefs the object's type + - subtype_dealloc() decrefs the object's type - - subtype_dealloc() returns + - subtype_dealloc() returns - - later, the trashcan code starts deleting the objects from its - to-be-deleted-later list + - later, the trashcan code starts deleting the objects from its + to-be-deleted-later list - - subtype_dealloc() is called *AGAIN* for the same object + - subtype_dealloc() is called *AGAIN* for the same object - - at the very least (if the destroyed slots and __dict__ don't - cause problems) the object's type gets decref'ed a second - time, which is *BAD*!!! + - at the very least (if the destroyed slots and __dict__ don't + cause problems) the object's type gets decref'ed a second + time, which is *BAD*!!! - The remedy is to make sure that if the code between trashcan - begin and end in subtype_dealloc() is called, the code between - trashcan begin and end in basedealloc() will also be called. - This is done by decrementing the level after passing into the - trashcan block, and incrementing it just before leaving the - block. + The remedy is to make sure that if the code between trashcan + begin and end in subtype_dealloc() is called, the code between + trashcan begin and end in basedealloc() will also be called. + This is done by decrementing the level after passing into the + trashcan block, and incrementing it just before leaving the + block. - But now it's possible that a chain of objects consisting solely - of objects whose deallocator is subtype_dealloc() will defeat - the trashcan mechanism completely: the decremented level means - that the effective level never reaches the limit. Therefore, we - *increment* the level *before* entering the trashcan block, and - matchingly decrement it after leaving. This means the trashcan - code will trigger a little early, but that's no big deal. + But now it's possible that a chain of objects consisting solely + of objects whose deallocator is subtype_dealloc() will defeat + the trashcan mechanism completely: the decremented level means + that the effective level never reaches the limit. Therefore, we + *increment* the level *before* entering the trashcan block, and + matchingly decrement it after leaving. This means the trashcan + code will trigger a little early, but that's no big deal. - Q. Are there any live examples of code in need of all this - complexity? + Q. Are there any live examples of code in need of all this + complexity? - A. Yes. See SF bug 668433 for code that crashed (when Python was - compiled in debug mode) before the trashcan level manipulations - were added. For more discussion, see SF patches 581742, 575073 - and bug 574207. - */ + A. Yes. See SF bug 668433 for code that crashed (when Python was + compiled in debug mode) before the trashcan level manipulations + were added. For more discussion, see SF patches 581742, 575073 + and bug 574207. + */ } static PyTypeObject *solid_base(PyTypeObject *type); @@ -1069,36 +1069,36 @@ int PyType_IsSubtype(PyTypeObject *a, PyTypeObject *b) { - PyObject *mro; + PyObject *mro; - mro = a->tp_mro; - if (mro != NULL) { - /* Deal with multiple inheritance without recursion - by walking the MRO tuple */ - Py_ssize_t i, n; - assert(PyTuple_Check(mro)); - n = PyTuple_GET_SIZE(mro); - for (i = 0; i < n; i++) { - if (PyTuple_GET_ITEM(mro, i) == (PyObject *)b) - return 1; - } - return 0; - } - else { - /* a is not completely initilized yet; follow tp_base */ - do { - if (a == b) - return 1; - a = a->tp_base; - } while (a != NULL); - return b == &PyBaseObject_Type; - } + mro = a->tp_mro; + if (mro != NULL) { + /* Deal with multiple inheritance without recursion + by walking the MRO tuple */ + Py_ssize_t i, n; + assert(PyTuple_Check(mro)); + n = PyTuple_GET_SIZE(mro); + for (i = 0; i < n; i++) { + if (PyTuple_GET_ITEM(mro, i) == (PyObject *)b) + return 1; + } + return 0; + } + else { + /* a is not completely initilized yet; follow tp_base */ + do { + if (a == b) + return 1; + a = a->tp_base; + } while (a != NULL); + return b == &PyBaseObject_Type; + } } /* Internal routines to do a method lookup in the type without looking in the instance dictionary (so we can't use PyObject_GetAttr) but still binding - it to the instance. The arguments are the object, + it to the instance. The arguments are the object, the method name as a C string, and the address of a static variable used to cache the interned Python string. @@ -1115,75 +1115,75 @@ static PyObject * lookup_maybe(PyObject *self, char *attrstr, PyObject **attrobj) { - PyObject *res; + PyObject *res; - if (*attrobj == NULL) { - *attrobj = PyUnicode_InternFromString(attrstr); - if (*attrobj == NULL) - return NULL; - } - res = _PyType_Lookup(Py_TYPE(self), *attrobj); - if (res != NULL) { - descrgetfunc f; - if ((f = Py_TYPE(res)->tp_descr_get) == NULL) - Py_INCREF(res); - else - res = f(res, self, (PyObject *)(Py_TYPE(self))); - } - return res; + if (*attrobj == NULL) { + *attrobj = PyUnicode_InternFromString(attrstr); + if (*attrobj == NULL) + return NULL; + } + res = _PyType_Lookup(Py_TYPE(self), *attrobj); + if (res != NULL) { + descrgetfunc f; + if ((f = Py_TYPE(res)->tp_descr_get) == NULL) + Py_INCREF(res); + else + res = f(res, self, (PyObject *)(Py_TYPE(self))); + } + return res; } static PyObject * lookup_method(PyObject *self, char *attrstr, PyObject **attrobj) { - PyObject *res = lookup_maybe(self, attrstr, attrobj); - if (res == NULL && !PyErr_Occurred()) - PyErr_SetObject(PyExc_AttributeError, *attrobj); - return res; + PyObject *res = lookup_maybe(self, attrstr, attrobj); + if (res == NULL && !PyErr_Occurred()) + PyErr_SetObject(PyExc_AttributeError, *attrobj); + return res; } PyObject * _PyObject_LookupSpecial(PyObject *self, char *attrstr, PyObject **attrobj) { - return lookup_maybe(self, attrstr, attrobj); + return lookup_maybe(self, attrstr, attrobj); } /* A variation of PyObject_CallMethod that uses lookup_method() - instead of PyObject_GetAttrString(). This uses the same convention + instead of PyObject_GetAttrString(). This uses the same convention as lookup_method to cache the interned name string object. */ static PyObject * call_method(PyObject *o, char *name, PyObject **nameobj, char *format, ...) { - va_list va; - PyObject *args, *func = 0, *retval; - va_start(va, format); - - func = lookup_maybe(o, name, nameobj); - if (func == NULL) { - va_end(va); - if (!PyErr_Occurred()) - PyErr_SetObject(PyExc_AttributeError, *nameobj); - return NULL; - } - - if (format && *format) - args = Py_VaBuildValue(format, va); - else - args = PyTuple_New(0); - - va_end(va); - - if (args == NULL) - return NULL; + va_list va; + PyObject *args, *func = 0, *retval; + va_start(va, format); + + func = lookup_maybe(o, name, nameobj); + if (func == NULL) { + va_end(va); + if (!PyErr_Occurred()) + PyErr_SetObject(PyExc_AttributeError, *nameobj); + return NULL; + } + + if (format && *format) + args = Py_VaBuildValue(format, va); + else + args = PyTuple_New(0); + + va_end(va); + + if (args == NULL) + return NULL; - assert(PyTuple_Check(args)); - retval = PyObject_Call(func, args, NULL); + assert(PyTuple_Check(args)); + retval = PyObject_Call(func, args, NULL); - Py_DECREF(args); - Py_DECREF(func); + Py_DECREF(args); + Py_DECREF(func); - return retval; + return retval; } /* Clone of call_method() that returns NotImplemented when the lookup fails. */ @@ -1191,37 +1191,37 @@ static PyObject * call_maybe(PyObject *o, char *name, PyObject **nameobj, char *format, ...) { - va_list va; - PyObject *args, *func = 0, *retval; - va_start(va, format); - - func = lookup_maybe(o, name, nameobj); - if (func == NULL) { - va_end(va); - if (!PyErr_Occurred()) { - Py_INCREF(Py_NotImplemented); - return Py_NotImplemented; - } - return NULL; - } - - if (format && *format) - args = Py_VaBuildValue(format, va); - else - args = PyTuple_New(0); - - va_end(va); - - if (args == NULL) - return NULL; + va_list va; + PyObject *args, *func = 0, *retval; + va_start(va, format); + + func = lookup_maybe(o, name, nameobj); + if (func == NULL) { + va_end(va); + if (!PyErr_Occurred()) { + Py_INCREF(Py_NotImplemented); + return Py_NotImplemented; + } + return NULL; + } + + if (format && *format) + args = Py_VaBuildValue(format, va); + else + args = PyTuple_New(0); - assert(PyTuple_Check(args)); - retval = PyObject_Call(func, args, NULL); + va_end(va); - Py_DECREF(args); - Py_DECREF(func); + if (args == NULL) + return NULL; - return retval; + assert(PyTuple_Check(args)); + retval = PyObject_Call(func, args, NULL); + + Py_DECREF(args); + Py_DECREF(func); + + return retval; } /* @@ -1254,68 +1254,68 @@ static int tail_contains(PyObject *list, int whence, PyObject *o) { - Py_ssize_t j, size; - size = PyList_GET_SIZE(list); + Py_ssize_t j, size; + size = PyList_GET_SIZE(list); - for (j = whence+1; j < size; j++) { - if (PyList_GET_ITEM(list, j) == o) - return 1; - } - return 0; + for (j = whence+1; j < size; j++) { + if (PyList_GET_ITEM(list, j) == o) + return 1; + } + return 0; } static PyObject * class_name(PyObject *cls) { - PyObject *name = PyObject_GetAttrString(cls, "__name__"); - if (name == NULL) { - PyErr_Clear(); - Py_XDECREF(name); - name = PyObject_Repr(cls); - } - if (name == NULL) - return NULL; - if (!PyUnicode_Check(name)) { - Py_DECREF(name); - return NULL; - } - return name; + PyObject *name = PyObject_GetAttrString(cls, "__name__"); + if (name == NULL) { + PyErr_Clear(); + Py_XDECREF(name); + name = PyObject_Repr(cls); + } + if (name == NULL) + return NULL; + if (!PyUnicode_Check(name)) { + Py_DECREF(name); + return NULL; + } + return name; } static int check_duplicates(PyObject *list) { - Py_ssize_t i, j, n; - /* Let's use a quadratic time algorithm, - assuming that the bases lists is short. - */ - n = PyList_GET_SIZE(list); - for (i = 0; i < n; i++) { - PyObject *o = PyList_GET_ITEM(list, i); - for (j = i + 1; j < n; j++) { - if (PyList_GET_ITEM(list, j) == o) { - o = class_name(o); - if (o != NULL) { - PyErr_Format(PyExc_TypeError, - "duplicate base class %U", - o); - Py_DECREF(o); - } else { - PyErr_SetString(PyExc_TypeError, - "duplicate base class"); - } - return -1; - } - } - } - return 0; + Py_ssize_t i, j, n; + /* Let's use a quadratic time algorithm, + assuming that the bases lists is short. + */ + n = PyList_GET_SIZE(list); + for (i = 0; i < n; i++) { + PyObject *o = PyList_GET_ITEM(list, i); + for (j = i + 1; j < n; j++) { + if (PyList_GET_ITEM(list, j) == o) { + o = class_name(o); + if (o != NULL) { + PyErr_Format(PyExc_TypeError, + "duplicate base class %U", + o); + Py_DECREF(o); + } else { + PyErr_SetString(PyExc_TypeError, + "duplicate base class"); + } + return -1; + } + } + } + return 0; } /* Raise a TypeError for an MRO order disagreement. It's hard to produce a good error message. In the absence of better insight into error reporting, report the classes that were candidates - to be put next into the MRO. There is some conflict between the + to be put next into the MRO. There is some conflict between the order in which they should be put in the MRO, but it's hard to diagnose what constraint can't be satisfied. */ @@ -1323,252 +1323,252 @@ static void set_mro_error(PyObject *to_merge, int *remain) { - Py_ssize_t i, n, off, to_merge_size; - char buf[1000]; - PyObject *k, *v; - PyObject *set = PyDict_New(); - if (!set) return; - - to_merge_size = PyList_GET_SIZE(to_merge); - for (i = 0; i < to_merge_size; i++) { - PyObject *L = PyList_GET_ITEM(to_merge, i); - if (remain[i] < PyList_GET_SIZE(L)) { - PyObject *c = PyList_GET_ITEM(L, remain[i]); - if (PyDict_SetItem(set, c, Py_None) < 0) { - Py_DECREF(set); - return; - } - } - } - n = PyDict_Size(set); + Py_ssize_t i, n, off, to_merge_size; + char buf[1000]; + PyObject *k, *v; + PyObject *set = PyDict_New(); + if (!set) return; + + to_merge_size = PyList_GET_SIZE(to_merge); + for (i = 0; i < to_merge_size; i++) { + PyObject *L = PyList_GET_ITEM(to_merge, i); + if (remain[i] < PyList_GET_SIZE(L)) { + PyObject *c = PyList_GET_ITEM(L, remain[i]); + if (PyDict_SetItem(set, c, Py_None) < 0) { + Py_DECREF(set); + return; + } + } + } + n = PyDict_Size(set); - off = PyOS_snprintf(buf, sizeof(buf), "Cannot create a \ + off = PyOS_snprintf(buf, sizeof(buf), "Cannot create a \ consistent method resolution\norder (MRO) for bases"); - i = 0; - while (PyDict_Next(set, &i, &k, &v) && (size_t)off < sizeof(buf)) { - PyObject *name = class_name(k); - off += PyOS_snprintf(buf + off, sizeof(buf) - off, " %s", - name ? _PyUnicode_AsString(name) : "?"); - Py_XDECREF(name); - if (--n && (size_t)(off+1) < sizeof(buf)) { - buf[off++] = ','; - buf[off] = '\0'; - } - } - PyErr_SetString(PyExc_TypeError, buf); - Py_DECREF(set); + i = 0; + while (PyDict_Next(set, &i, &k, &v) && (size_t)off < sizeof(buf)) { + PyObject *name = class_name(k); + off += PyOS_snprintf(buf + off, sizeof(buf) - off, " %s", + name ? _PyUnicode_AsString(name) : "?"); + Py_XDECREF(name); + if (--n && (size_t)(off+1) < sizeof(buf)) { + buf[off++] = ','; + buf[off] = '\0'; + } + } + PyErr_SetString(PyExc_TypeError, buf); + Py_DECREF(set); } static int pmerge(PyObject *acc, PyObject* to_merge) { - Py_ssize_t i, j, to_merge_size, empty_cnt; - int *remain; - int ok; - - to_merge_size = PyList_GET_SIZE(to_merge); - - /* remain stores an index into each sublist of to_merge. - remain[i] is the index of the next base in to_merge[i] - that is not included in acc. - */ - remain = (int *)PyMem_MALLOC(SIZEOF_INT*to_merge_size); - if (remain == NULL) - return -1; - for (i = 0; i < to_merge_size; i++) - remain[i] = 0; + Py_ssize_t i, j, to_merge_size, empty_cnt; + int *remain; + int ok; + + to_merge_size = PyList_GET_SIZE(to_merge); + + /* remain stores an index into each sublist of to_merge. + remain[i] is the index of the next base in to_merge[i] + that is not included in acc. + */ + remain = (int *)PyMem_MALLOC(SIZEOF_INT*to_merge_size); + if (remain == NULL) + return -1; + for (i = 0; i < to_merge_size; i++) + remain[i] = 0; again: - empty_cnt = 0; - for (i = 0; i < to_merge_size; i++) { - PyObject *candidate; - - PyObject *cur_list = PyList_GET_ITEM(to_merge, i); - - if (remain[i] >= PyList_GET_SIZE(cur_list)) { - empty_cnt++; - continue; - } - - /* Choose next candidate for MRO. - - The input sequences alone can determine the choice. - If not, choose the class which appears in the MRO - of the earliest direct superclass of the new class. - */ - - candidate = PyList_GET_ITEM(cur_list, remain[i]); - for (j = 0; j < to_merge_size; j++) { - PyObject *j_lst = PyList_GET_ITEM(to_merge, j); - if (tail_contains(j_lst, remain[j], candidate)) { - goto skip; /* continue outer loop */ - } - } - ok = PyList_Append(acc, candidate); - if (ok < 0) { - PyMem_Free(remain); - return -1; - } - for (j = 0; j < to_merge_size; j++) { - PyObject *j_lst = PyList_GET_ITEM(to_merge, j); - if (remain[j] < PyList_GET_SIZE(j_lst) && - PyList_GET_ITEM(j_lst, remain[j]) == candidate) { - remain[j]++; - } - } - goto again; - skip: ; - } - - if (empty_cnt == to_merge_size) { - PyMem_FREE(remain); - return 0; - } - set_mro_error(to_merge, remain); - PyMem_FREE(remain); - return -1; + empty_cnt = 0; + for (i = 0; i < to_merge_size; i++) { + PyObject *candidate; + + PyObject *cur_list = PyList_GET_ITEM(to_merge, i); + + if (remain[i] >= PyList_GET_SIZE(cur_list)) { + empty_cnt++; + continue; + } + + /* Choose next candidate for MRO. + + The input sequences alone can determine the choice. + If not, choose the class which appears in the MRO + of the earliest direct superclass of the new class. + */ + + candidate = PyList_GET_ITEM(cur_list, remain[i]); + for (j = 0; j < to_merge_size; j++) { + PyObject *j_lst = PyList_GET_ITEM(to_merge, j); + if (tail_contains(j_lst, remain[j], candidate)) { + goto skip; /* continue outer loop */ + } + } + ok = PyList_Append(acc, candidate); + if (ok < 0) { + PyMem_Free(remain); + return -1; + } + for (j = 0; j < to_merge_size; j++) { + PyObject *j_lst = PyList_GET_ITEM(to_merge, j); + if (remain[j] < PyList_GET_SIZE(j_lst) && + PyList_GET_ITEM(j_lst, remain[j]) == candidate) { + remain[j]++; + } + } + goto again; + skip: ; + } + + if (empty_cnt == to_merge_size) { + PyMem_FREE(remain); + return 0; + } + set_mro_error(to_merge, remain); + PyMem_FREE(remain); + return -1; } static PyObject * mro_implementation(PyTypeObject *type) { - Py_ssize_t i, n; - int ok; - PyObject *bases, *result; - PyObject *to_merge, *bases_aslist; - - if (type->tp_dict == NULL) { - if (PyType_Ready(type) < 0) - return NULL; - } - - /* Find a superclass linearization that honors the constraints - of the explicit lists of bases and the constraints implied by - each base class. - - to_merge is a list of lists, where each list is a superclass - linearization implied by a base class. The last element of - to_merge is the declared list of bases. - */ - - bases = type->tp_bases; - n = PyTuple_GET_SIZE(bases); - - to_merge = PyList_New(n+1); - if (to_merge == NULL) - return NULL; - - for (i = 0; i < n; i++) { - PyObject *base = PyTuple_GET_ITEM(bases, i); - PyObject *parentMRO; - parentMRO = PySequence_List(((PyTypeObject*)base)->tp_mro); - if (parentMRO == NULL) { - Py_DECREF(to_merge); - return NULL; - } - - PyList_SET_ITEM(to_merge, i, parentMRO); - } - - bases_aslist = PySequence_List(bases); - if (bases_aslist == NULL) { - Py_DECREF(to_merge); - return NULL; - } - /* This is just a basic sanity check. */ - if (check_duplicates(bases_aslist) < 0) { - Py_DECREF(to_merge); - Py_DECREF(bases_aslist); - return NULL; - } - PyList_SET_ITEM(to_merge, n, bases_aslist); - - result = Py_BuildValue("[O]", (PyObject *)type); - if (result == NULL) { - Py_DECREF(to_merge); - return NULL; - } - - ok = pmerge(result, to_merge); - Py_DECREF(to_merge); - if (ok < 0) { - Py_DECREF(result); - return NULL; - } + Py_ssize_t i, n; + int ok; + PyObject *bases, *result; + PyObject *to_merge, *bases_aslist; + + if (type->tp_dict == NULL) { + if (PyType_Ready(type) < 0) + return NULL; + } + + /* Find a superclass linearization that honors the constraints + of the explicit lists of bases and the constraints implied by + each base class. + + to_merge is a list of lists, where each list is a superclass + linearization implied by a base class. The last element of + to_merge is the declared list of bases. + */ + + bases = type->tp_bases; + n = PyTuple_GET_SIZE(bases); + + to_merge = PyList_New(n+1); + if (to_merge == NULL) + return NULL; + + for (i = 0; i < n; i++) { + PyObject *base = PyTuple_GET_ITEM(bases, i); + PyObject *parentMRO; + parentMRO = PySequence_List(((PyTypeObject*)base)->tp_mro); + if (parentMRO == NULL) { + Py_DECREF(to_merge); + return NULL; + } + + PyList_SET_ITEM(to_merge, i, parentMRO); + } - return result; + bases_aslist = PySequence_List(bases); + if (bases_aslist == NULL) { + Py_DECREF(to_merge); + return NULL; + } + /* This is just a basic sanity check. */ + if (check_duplicates(bases_aslist) < 0) { + Py_DECREF(to_merge); + Py_DECREF(bases_aslist); + return NULL; + } + PyList_SET_ITEM(to_merge, n, bases_aslist); + + result = Py_BuildValue("[O]", (PyObject *)type); + if (result == NULL) { + Py_DECREF(to_merge); + return NULL; + } + + ok = pmerge(result, to_merge); + Py_DECREF(to_merge); + if (ok < 0) { + Py_DECREF(result); + return NULL; + } + + return result; } static PyObject * mro_external(PyObject *self) { - PyTypeObject *type = (PyTypeObject *)self; + PyTypeObject *type = (PyTypeObject *)self; - return mro_implementation(type); + return mro_implementation(type); } static int mro_internal(PyTypeObject *type) { - PyObject *mro, *result, *tuple; - int checkit = 0; + PyObject *mro, *result, *tuple; + int checkit = 0; + + if (Py_TYPE(type) == &PyType_Type) { + result = mro_implementation(type); + } + else { + static PyObject *mro_str; + checkit = 1; + mro = lookup_method((PyObject *)type, "mro", &mro_str); + if (mro == NULL) + return -1; + result = PyObject_CallObject(mro, NULL); + Py_DECREF(mro); + } + if (result == NULL) + return -1; + tuple = PySequence_Tuple(result); + Py_DECREF(result); + if (tuple == NULL) + return -1; + if (checkit) { + Py_ssize_t i, len; + PyObject *cls; + PyTypeObject *solid; + + solid = solid_base(type); + + len = PyTuple_GET_SIZE(tuple); + + for (i = 0; i < len; i++) { + PyTypeObject *t; + cls = PyTuple_GET_ITEM(tuple, i); + if (!PyType_Check(cls)) { + PyErr_Format(PyExc_TypeError, + "mro() returned a non-class ('%.500s')", + Py_TYPE(cls)->tp_name); + Py_DECREF(tuple); + return -1; + } + t = (PyTypeObject*)cls; + if (!PyType_IsSubtype(solid, solid_base(t))) { + PyErr_Format(PyExc_TypeError, + "mro() returned base with unsuitable layout ('%.500s')", + t->tp_name); + Py_DECREF(tuple); + return -1; + } + } + } + type->tp_mro = tuple; - if (Py_TYPE(type) == &PyType_Type) { - result = mro_implementation(type); - } - else { - static PyObject *mro_str; - checkit = 1; - mro = lookup_method((PyObject *)type, "mro", &mro_str); - if (mro == NULL) - return -1; - result = PyObject_CallObject(mro, NULL); - Py_DECREF(mro); - } - if (result == NULL) - return -1; - tuple = PySequence_Tuple(result); - Py_DECREF(result); - if (tuple == NULL) - return -1; - if (checkit) { - Py_ssize_t i, len; - PyObject *cls; - PyTypeObject *solid; - - solid = solid_base(type); - - len = PyTuple_GET_SIZE(tuple); - - for (i = 0; i < len; i++) { - PyTypeObject *t; - cls = PyTuple_GET_ITEM(tuple, i); - if (!PyType_Check(cls)) { - PyErr_Format(PyExc_TypeError, - "mro() returned a non-class ('%.500s')", - Py_TYPE(cls)->tp_name); - Py_DECREF(tuple); - return -1; - } - t = (PyTypeObject*)cls; - if (!PyType_IsSubtype(solid, solid_base(t))) { - PyErr_Format(PyExc_TypeError, - "mro() returned base with unsuitable layout ('%.500s')", - t->tp_name); - Py_DECREF(tuple); - return -1; - } - } - } - type->tp_mro = tuple; - - type_mro_modified(type, type->tp_mro); - /* corner case: the old-style super class might have been hidden - from the custom MRO */ - type_mro_modified(type, type->tp_bases); + type_mro_modified(type, type->tp_mro); + /* corner case: the old-style super class might have been hidden + from the custom MRO */ + type_mro_modified(type, type->tp_bases); - PyType_Modified(type); + PyType_Modified(type); - return 0; + return 0; } @@ -1578,90 +1578,90 @@ static PyTypeObject * best_base(PyObject *bases) { - Py_ssize_t i, n; - PyTypeObject *base, *winner, *candidate, *base_i; - PyObject *base_proto; - - assert(PyTuple_Check(bases)); - n = PyTuple_GET_SIZE(bases); - assert(n > 0); - base = NULL; - winner = NULL; - for (i = 0; i < n; i++) { - base_proto = PyTuple_GET_ITEM(bases, i); - if (!PyType_Check(base_proto)) { - PyErr_SetString( - PyExc_TypeError, - "bases must be types"); - return NULL; - } - base_i = (PyTypeObject *)base_proto; - if (base_i->tp_dict == NULL) { - if (PyType_Ready(base_i) < 0) - return NULL; - } - candidate = solid_base(base_i); - if (winner == NULL) { - winner = candidate; - base = base_i; - } - else if (PyType_IsSubtype(winner, candidate)) - ; - else if (PyType_IsSubtype(candidate, winner)) { - winner = candidate; - base = base_i; - } - else { - PyErr_SetString( - PyExc_TypeError, - "multiple bases have " - "instance lay-out conflict"); - return NULL; - } - } - if (base == NULL) - PyErr_SetString(PyExc_TypeError, - "a new-style class can't have only classic bases"); - return base; + Py_ssize_t i, n; + PyTypeObject *base, *winner, *candidate, *base_i; + PyObject *base_proto; + + assert(PyTuple_Check(bases)); + n = PyTuple_GET_SIZE(bases); + assert(n > 0); + base = NULL; + winner = NULL; + for (i = 0; i < n; i++) { + base_proto = PyTuple_GET_ITEM(bases, i); + if (!PyType_Check(base_proto)) { + PyErr_SetString( + PyExc_TypeError, + "bases must be types"); + return NULL; + } + base_i = (PyTypeObject *)base_proto; + if (base_i->tp_dict == NULL) { + if (PyType_Ready(base_i) < 0) + return NULL; + } + candidate = solid_base(base_i); + if (winner == NULL) { + winner = candidate; + base = base_i; + } + else if (PyType_IsSubtype(winner, candidate)) + ; + else if (PyType_IsSubtype(candidate, winner)) { + winner = candidate; + base = base_i; + } + else { + PyErr_SetString( + PyExc_TypeError, + "multiple bases have " + "instance lay-out conflict"); + return NULL; + } + } + if (base == NULL) + PyErr_SetString(PyExc_TypeError, + "a new-style class can't have only classic bases"); + return base; } static int extra_ivars(PyTypeObject *type, PyTypeObject *base) { - size_t t_size = type->tp_basicsize; - size_t b_size = base->tp_basicsize; + size_t t_size = type->tp_basicsize; + size_t b_size = base->tp_basicsize; - assert(t_size >= b_size); /* Else type smaller than base! */ - if (type->tp_itemsize || base->tp_itemsize) { - /* If itemsize is involved, stricter rules */ - return t_size != b_size || - type->tp_itemsize != base->tp_itemsize; - } - if (type->tp_weaklistoffset && base->tp_weaklistoffset == 0 && - type->tp_weaklistoffset + sizeof(PyObject *) == t_size && - type->tp_flags & Py_TPFLAGS_HEAPTYPE) - t_size -= sizeof(PyObject *); - if (type->tp_dictoffset && base->tp_dictoffset == 0 && - type->tp_dictoffset + sizeof(PyObject *) == t_size && - type->tp_flags & Py_TPFLAGS_HEAPTYPE) - t_size -= sizeof(PyObject *); + assert(t_size >= b_size); /* Else type smaller than base! */ + if (type->tp_itemsize || base->tp_itemsize) { + /* If itemsize is involved, stricter rules */ + return t_size != b_size || + type->tp_itemsize != base->tp_itemsize; + } + if (type->tp_weaklistoffset && base->tp_weaklistoffset == 0 && + type->tp_weaklistoffset + sizeof(PyObject *) == t_size && + type->tp_flags & Py_TPFLAGS_HEAPTYPE) + t_size -= sizeof(PyObject *); + if (type->tp_dictoffset && base->tp_dictoffset == 0 && + type->tp_dictoffset + sizeof(PyObject *) == t_size && + type->tp_flags & Py_TPFLAGS_HEAPTYPE) + t_size -= sizeof(PyObject *); - return t_size != b_size; + return t_size != b_size; } static PyTypeObject * solid_base(PyTypeObject *type) { - PyTypeObject *base; + PyTypeObject *base; - if (type->tp_base) - base = solid_base(type->tp_base); - else - base = &PyBaseObject_Type; - if (extra_ivars(type, base)) - return type; - else - return base; + if (type->tp_base) + base = solid_base(type->tp_base); + else + base = &PyBaseObject_Type; + if (extra_ivars(type, base)) + return type; + else + return base; } static void object_dealloc(PyObject *); @@ -1677,180 +1677,180 @@ static PyTypeObject * get_builtin_base_with_dict(PyTypeObject *type) { - while (type->tp_base != NULL) { - if (type->tp_dictoffset != 0 && - !(type->tp_flags & Py_TPFLAGS_HEAPTYPE)) - return type; - type = type->tp_base; - } - return NULL; + while (type->tp_base != NULL) { + if (type->tp_dictoffset != 0 && + !(type->tp_flags & Py_TPFLAGS_HEAPTYPE)) + return type; + type = type->tp_base; + } + return NULL; } static PyObject * get_dict_descriptor(PyTypeObject *type) { - static PyObject *dict_str; - PyObject *descr; + static PyObject *dict_str; + PyObject *descr; - if (dict_str == NULL) { - dict_str = PyUnicode_InternFromString("__dict__"); - if (dict_str == NULL) - return NULL; - } - descr = _PyType_Lookup(type, dict_str); - if (descr == NULL || !PyDescr_IsData(descr)) - return NULL; + if (dict_str == NULL) { + dict_str = PyUnicode_InternFromString("__dict__"); + if (dict_str == NULL) + return NULL; + } + descr = _PyType_Lookup(type, dict_str); + if (descr == NULL || !PyDescr_IsData(descr)) + return NULL; - return descr; + return descr; } static void raise_dict_descr_error(PyObject *obj) { - PyErr_Format(PyExc_TypeError, - "this __dict__ descriptor does not support " - "'%.200s' objects", Py_TYPE(obj)->tp_name); + PyErr_Format(PyExc_TypeError, + "this __dict__ descriptor does not support " + "'%.200s' objects", Py_TYPE(obj)->tp_name); } static PyObject * subtype_dict(PyObject *obj, void *context) { - PyObject **dictptr; - PyObject *dict; - PyTypeObject *base; - - base = get_builtin_base_with_dict(Py_TYPE(obj)); - if (base != NULL) { - descrgetfunc func; - PyObject *descr = get_dict_descriptor(base); - if (descr == NULL) { - raise_dict_descr_error(obj); - return NULL; - } - func = Py_TYPE(descr)->tp_descr_get; - if (func == NULL) { - raise_dict_descr_error(obj); - return NULL; - } - return func(descr, obj, (PyObject *)(Py_TYPE(obj))); - } - - dictptr = _PyObject_GetDictPtr(obj); - if (dictptr == NULL) { - PyErr_SetString(PyExc_AttributeError, - "This object has no __dict__"); - return NULL; - } - dict = *dictptr; - if (dict == NULL) - *dictptr = dict = PyDict_New(); - Py_XINCREF(dict); - return dict; + PyObject **dictptr; + PyObject *dict; + PyTypeObject *base; + + base = get_builtin_base_with_dict(Py_TYPE(obj)); + if (base != NULL) { + descrgetfunc func; + PyObject *descr = get_dict_descriptor(base); + if (descr == NULL) { + raise_dict_descr_error(obj); + return NULL; + } + func = Py_TYPE(descr)->tp_descr_get; + if (func == NULL) { + raise_dict_descr_error(obj); + return NULL; + } + return func(descr, obj, (PyObject *)(Py_TYPE(obj))); + } + + dictptr = _PyObject_GetDictPtr(obj); + if (dictptr == NULL) { + PyErr_SetString(PyExc_AttributeError, + "This object has no __dict__"); + return NULL; + } + dict = *dictptr; + if (dict == NULL) + *dictptr = dict = PyDict_New(); + Py_XINCREF(dict); + return dict; } static int subtype_setdict(PyObject *obj, PyObject *value, void *context) { - PyObject **dictptr; - PyObject *dict; - PyTypeObject *base; - - base = get_builtin_base_with_dict(Py_TYPE(obj)); - if (base != NULL) { - descrsetfunc func; - PyObject *descr = get_dict_descriptor(base); - if (descr == NULL) { - raise_dict_descr_error(obj); - return -1; - } - func = Py_TYPE(descr)->tp_descr_set; - if (func == NULL) { - raise_dict_descr_error(obj); - return -1; - } - return func(descr, obj, value); - } - - dictptr = _PyObject_GetDictPtr(obj); - if (dictptr == NULL) { - PyErr_SetString(PyExc_AttributeError, - "This object has no __dict__"); - return -1; - } - if (value != NULL && !PyDict_Check(value)) { - PyErr_Format(PyExc_TypeError, - "__dict__ must be set to a dictionary, " - "not a '%.200s'", Py_TYPE(value)->tp_name); - return -1; - } - dict = *dictptr; - Py_XINCREF(value); - *dictptr = value; - Py_XDECREF(dict); - return 0; + PyObject **dictptr; + PyObject *dict; + PyTypeObject *base; + + base = get_builtin_base_with_dict(Py_TYPE(obj)); + if (base != NULL) { + descrsetfunc func; + PyObject *descr = get_dict_descriptor(base); + if (descr == NULL) { + raise_dict_descr_error(obj); + return -1; + } + func = Py_TYPE(descr)->tp_descr_set; + if (func == NULL) { + raise_dict_descr_error(obj); + return -1; + } + return func(descr, obj, value); + } + + dictptr = _PyObject_GetDictPtr(obj); + if (dictptr == NULL) { + PyErr_SetString(PyExc_AttributeError, + "This object has no __dict__"); + return -1; + } + if (value != NULL && !PyDict_Check(value)) { + PyErr_Format(PyExc_TypeError, + "__dict__ must be set to a dictionary, " + "not a '%.200s'", Py_TYPE(value)->tp_name); + return -1; + } + dict = *dictptr; + Py_XINCREF(value); + *dictptr = value; + Py_XDECREF(dict); + return 0; } static PyObject * subtype_getweakref(PyObject *obj, void *context) { - PyObject **weaklistptr; - PyObject *result; + PyObject **weaklistptr; + PyObject *result; - if (Py_TYPE(obj)->tp_weaklistoffset == 0) { - PyErr_SetString(PyExc_AttributeError, - "This object has no __weakref__"); - return NULL; - } - assert(Py_TYPE(obj)->tp_weaklistoffset > 0); - assert(Py_TYPE(obj)->tp_weaklistoffset + sizeof(PyObject *) <= - (size_t)(Py_TYPE(obj)->tp_basicsize)); - weaklistptr = (PyObject **) - ((char *)obj + Py_TYPE(obj)->tp_weaklistoffset); - if (*weaklistptr == NULL) - result = Py_None; - else - result = *weaklistptr; - Py_INCREF(result); - return result; + if (Py_TYPE(obj)->tp_weaklistoffset == 0) { + PyErr_SetString(PyExc_AttributeError, + "This object has no __weakref__"); + return NULL; + } + assert(Py_TYPE(obj)->tp_weaklistoffset > 0); + assert(Py_TYPE(obj)->tp_weaklistoffset + sizeof(PyObject *) <= + (size_t)(Py_TYPE(obj)->tp_basicsize)); + weaklistptr = (PyObject **) + ((char *)obj + Py_TYPE(obj)->tp_weaklistoffset); + if (*weaklistptr == NULL) + result = Py_None; + else + result = *weaklistptr; + Py_INCREF(result); + return result; } /* Three variants on the subtype_getsets list. */ static PyGetSetDef subtype_getsets_full[] = { - {"__dict__", subtype_dict, subtype_setdict, - PyDoc_STR("dictionary for instance variables (if defined)")}, - {"__weakref__", subtype_getweakref, NULL, - PyDoc_STR("list of weak references to the object (if defined)")}, - {0} + {"__dict__", subtype_dict, subtype_setdict, + PyDoc_STR("dictionary for instance variables (if defined)")}, + {"__weakref__", subtype_getweakref, NULL, + PyDoc_STR("list of weak references to the object (if defined)")}, + {0} }; static PyGetSetDef subtype_getsets_dict_only[] = { - {"__dict__", subtype_dict, subtype_setdict, - PyDoc_STR("dictionary for instance variables (if defined)")}, - {0} + {"__dict__", subtype_dict, subtype_setdict, + PyDoc_STR("dictionary for instance variables (if defined)")}, + {0} }; static PyGetSetDef subtype_getsets_weakref_only[] = { - {"__weakref__", subtype_getweakref, NULL, - PyDoc_STR("list of weak references to the object (if defined)")}, - {0} + {"__weakref__", subtype_getweakref, NULL, + PyDoc_STR("list of weak references to the object (if defined)")}, + {0} }; static int valid_identifier(PyObject *s) { - if (!PyUnicode_Check(s)) { - PyErr_Format(PyExc_TypeError, - "__slots__ items must be strings, not '%.200s'", - Py_TYPE(s)->tp_name); - return 0; - } - if (!PyUnicode_IsIdentifier(s)) { - PyErr_SetString(PyExc_TypeError, - "__slots__ must be identifiers"); - return 0; - } - return 1; + if (!PyUnicode_Check(s)) { + PyErr_Format(PyExc_TypeError, + "__slots__ items must be strings, not '%.200s'", + Py_TYPE(s)->tp_name); + return 0; + } + if (!PyUnicode_IsIdentifier(s)) { + PyErr_SetString(PyExc_TypeError, + "__slots__ must be identifiers"); + return 0; + } + return 1; } /* Forward */ @@ -1860,435 +1860,435 @@ static int type_init(PyObject *cls, PyObject *args, PyObject *kwds) { - int res; + int res; - assert(args != NULL && PyTuple_Check(args)); - assert(kwds == NULL || PyDict_Check(kwds)); + assert(args != NULL && PyTuple_Check(args)); + assert(kwds == NULL || PyDict_Check(kwds)); - if (kwds != NULL && PyDict_Check(kwds) && PyDict_Size(kwds) != 0) { - PyErr_SetString(PyExc_TypeError, - "type.__init__() takes no keyword arguments"); - return -1; - } - - if (args != NULL && PyTuple_Check(args) && - (PyTuple_GET_SIZE(args) != 1 && PyTuple_GET_SIZE(args) != 3)) { - PyErr_SetString(PyExc_TypeError, - "type.__init__() takes 1 or 3 arguments"); - return -1; - } - - /* Call object.__init__(self) now. */ - /* XXX Could call super(type, cls).__init__() but what's the point? */ - args = PyTuple_GetSlice(args, 0, 0); - res = object_init(cls, args, NULL); - Py_DECREF(args); - return res; + if (kwds != NULL && PyDict_Check(kwds) && PyDict_Size(kwds) != 0) { + PyErr_SetString(PyExc_TypeError, + "type.__init__() takes no keyword arguments"); + return -1; + } + + if (args != NULL && PyTuple_Check(args) && + (PyTuple_GET_SIZE(args) != 1 && PyTuple_GET_SIZE(args) != 3)) { + PyErr_SetString(PyExc_TypeError, + "type.__init__() takes 1 or 3 arguments"); + return -1; + } + + /* Call object.__init__(self) now. */ + /* XXX Could call super(type, cls).__init__() but what's the point? */ + args = PyTuple_GetSlice(args, 0, 0); + res = object_init(cls, args, NULL); + Py_DECREF(args); + return res; } static PyObject * type_new(PyTypeObject *metatype, PyObject *args, PyObject *kwds) { - PyObject *name, *bases, *dict; - static char *kwlist[] = {"name", "bases", "dict", 0}; - PyObject *slots, *tmp, *newslots; - PyTypeObject *type, *base, *tmptype, *winner; - PyHeapTypeObject *et; - PyMemberDef *mp; - Py_ssize_t i, nbases, nslots, slotoffset, add_dict, add_weak; - int j, may_add_dict, may_add_weak; - - assert(args != NULL && PyTuple_Check(args)); - assert(kwds == NULL || PyDict_Check(kwds)); - - /* Special case: type(x) should return x->ob_type */ - { - const Py_ssize_t nargs = PyTuple_GET_SIZE(args); - const Py_ssize_t nkwds = kwds == NULL ? 0 : PyDict_Size(kwds); - - if (PyType_CheckExact(metatype) && nargs == 1 && nkwds == 0) { - PyObject *x = PyTuple_GET_ITEM(args, 0); - Py_INCREF(Py_TYPE(x)); - return (PyObject *) Py_TYPE(x); - } - - /* SF bug 475327 -- if that didn't trigger, we need 3 - arguments. but PyArg_ParseTupleAndKeywords below may give - a msg saying type() needs exactly 3. */ - if (nargs + nkwds != 3) { - PyErr_SetString(PyExc_TypeError, - "type() takes 1 or 3 arguments"); - return NULL; - } - } - - /* Check arguments: (name, bases, dict) */ - if (!PyArg_ParseTupleAndKeywords(args, kwds, "UO!O!:type", kwlist, - &name, - &PyTuple_Type, &bases, - &PyDict_Type, &dict)) - return NULL; - - /* Determine the proper metatype to deal with this, - and check for metatype conflicts while we're at it. - Note that if some other metatype wins to contract, - it's possible that its instances are not types. */ - nbases = PyTuple_GET_SIZE(bases); - winner = metatype; - for (i = 0; i < nbases; i++) { - tmp = PyTuple_GET_ITEM(bases, i); - tmptype = Py_TYPE(tmp); - if (PyType_IsSubtype(winner, tmptype)) - continue; - if (PyType_IsSubtype(tmptype, winner)) { - winner = tmptype; - continue; - } - PyErr_SetString(PyExc_TypeError, - "metaclass conflict: " - "the metaclass of a derived class " - "must be a (non-strict) subclass " - "of the metaclasses of all its bases"); - return NULL; - } - if (winner != metatype) { - if (winner->tp_new != type_new) /* Pass it to the winner */ - return winner->tp_new(winner, args, kwds); - metatype = winner; - } - - /* Adjust for empty tuple bases */ - if (nbases == 0) { - bases = PyTuple_Pack(1, &PyBaseObject_Type); - if (bases == NULL) - return NULL; - nbases = 1; - } - else - Py_INCREF(bases); - - /* XXX From here until type is allocated, "return NULL" leaks bases! */ - - /* Calculate best base, and check that all bases are type objects */ - base = best_base(bases); - if (base == NULL) { - Py_DECREF(bases); - return NULL; - } - if (!PyType_HasFeature(base, Py_TPFLAGS_BASETYPE)) { - PyErr_Format(PyExc_TypeError, - "type '%.100s' is not an acceptable base type", - base->tp_name); - Py_DECREF(bases); - return NULL; - } - - /* Check for a __slots__ sequence variable in dict, and count it */ - slots = PyDict_GetItemString(dict, "__slots__"); - nslots = 0; - add_dict = 0; - add_weak = 0; - may_add_dict = base->tp_dictoffset == 0; - may_add_weak = base->tp_weaklistoffset == 0 && base->tp_itemsize == 0; - if (slots == NULL) { - if (may_add_dict) { - add_dict++; - } - if (may_add_weak) { - add_weak++; - } - } - else { - /* Have slots */ - - /* Make it into a tuple */ - if (PyUnicode_Check(slots)) - slots = PyTuple_Pack(1, slots); - else - slots = PySequence_Tuple(slots); - if (slots == NULL) { - Py_DECREF(bases); - return NULL; - } - assert(PyTuple_Check(slots)); - - /* Are slots allowed? */ - nslots = PyTuple_GET_SIZE(slots); - if (nslots > 0 && base->tp_itemsize != 0) { - PyErr_Format(PyExc_TypeError, - "nonempty __slots__ " - "not supported for subtype of '%s'", - base->tp_name); - bad_slots: - Py_DECREF(bases); - Py_DECREF(slots); - return NULL; - } - - /* Check for valid slot names and two special cases */ - for (i = 0; i < nslots; i++) { - PyObject *tmp = PyTuple_GET_ITEM(slots, i); - if (!valid_identifier(tmp)) - goto bad_slots; - assert(PyUnicode_Check(tmp)); - if (PyUnicode_CompareWithASCIIString(tmp, "__dict__") == 0) { - if (!may_add_dict || add_dict) { - PyErr_SetString(PyExc_TypeError, - "__dict__ slot disallowed: " - "we already got one"); - goto bad_slots; - } - add_dict++; - } - if (PyUnicode_CompareWithASCIIString(tmp, "__weakref__") == 0) { - if (!may_add_weak || add_weak) { - PyErr_SetString(PyExc_TypeError, - "__weakref__ slot disallowed: " - "either we already got one, " - "or __itemsize__ != 0"); - goto bad_slots; - } - add_weak++; - } - } - - /* Copy slots into a list, mangle names and sort them. - Sorted names are needed for __class__ assignment. - Convert them back to tuple at the end. - */ - newslots = PyList_New(nslots - add_dict - add_weak); - if (newslots == NULL) - goto bad_slots; - for (i = j = 0; i < nslots; i++) { - tmp = PyTuple_GET_ITEM(slots, i); - if ((add_dict && - PyUnicode_CompareWithASCIIString(tmp, "__dict__") == 0) || - (add_weak && - PyUnicode_CompareWithASCIIString(tmp, "__weakref__") == 0)) - continue; - tmp =_Py_Mangle(name, tmp); - if (!tmp) - goto bad_slots; - PyList_SET_ITEM(newslots, j, tmp); - j++; - } - assert(j == nslots - add_dict - add_weak); - nslots = j; - Py_DECREF(slots); - if (PyList_Sort(newslots) == -1) { - Py_DECREF(bases); - Py_DECREF(newslots); - return NULL; - } - slots = PyList_AsTuple(newslots); - Py_DECREF(newslots); - if (slots == NULL) { - Py_DECREF(bases); - return NULL; - } - - /* Secondary bases may provide weakrefs or dict */ - if (nbases > 1 && - ((may_add_dict && !add_dict) || - (may_add_weak && !add_weak))) { - for (i = 0; i < nbases; i++) { - tmp = PyTuple_GET_ITEM(bases, i); - if (tmp == (PyObject *)base) - continue; /* Skip primary base */ - assert(PyType_Check(tmp)); - tmptype = (PyTypeObject *)tmp; - if (may_add_dict && !add_dict && - tmptype->tp_dictoffset != 0) - add_dict++; - if (may_add_weak && !add_weak && - tmptype->tp_weaklistoffset != 0) - add_weak++; - if (may_add_dict && !add_dict) - continue; - if (may_add_weak && !add_weak) - continue; - /* Nothing more to check */ - break; - } - } - } - - /* XXX From here until type is safely allocated, - "return NULL" may leak slots! */ - - /* Allocate the type object */ - type = (PyTypeObject *)metatype->tp_alloc(metatype, nslots); - if (type == NULL) { - Py_XDECREF(slots); - Py_DECREF(bases); - return NULL; - } - - /* Keep name and slots alive in the extended type object */ - et = (PyHeapTypeObject *)type; - Py_INCREF(name); - et->ht_name = name; - et->ht_slots = slots; - - /* Initialize tp_flags */ - type->tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HEAPTYPE | - Py_TPFLAGS_BASETYPE; - if (base->tp_flags & Py_TPFLAGS_HAVE_GC) - type->tp_flags |= Py_TPFLAGS_HAVE_GC; - - /* Initialize essential fields */ - type->tp_as_number = &et->as_number; - type->tp_as_sequence = &et->as_sequence; - type->tp_as_mapping = &et->as_mapping; - type->tp_as_buffer = &et->as_buffer; - type->tp_name = _PyUnicode_AsString(name); - if (!type->tp_name) { - Py_DECREF(type); - return NULL; - } - - /* Set tp_base and tp_bases */ - type->tp_bases = bases; - Py_INCREF(base); - type->tp_base = base; - - /* Initialize tp_dict from passed-in dict */ - type->tp_dict = dict = PyDict_Copy(dict); - if (dict == NULL) { - Py_DECREF(type); - return NULL; - } - - /* Set __module__ in the dict */ - if (PyDict_GetItemString(dict, "__module__") == NULL) { - tmp = PyEval_GetGlobals(); - if (tmp != NULL) { - tmp = PyDict_GetItemString(tmp, "__name__"); - if (tmp != NULL) { - if (PyDict_SetItemString(dict, "__module__", - tmp) < 0) - return NULL; - } - } - } - - /* Set tp_doc to a copy of dict['__doc__'], if the latter is there - and is a string. The __doc__ accessor will first look for tp_doc; - if that fails, it will still look into __dict__. - */ - { - PyObject *doc = PyDict_GetItemString(dict, "__doc__"); - if (doc != NULL && PyUnicode_Check(doc)) { - Py_ssize_t len; - char *doc_str; - char *tp_doc; - - doc_str = _PyUnicode_AsString(doc); - if (doc_str == NULL) { - Py_DECREF(type); - return NULL; - } - /* Silently truncate the docstring if it contains null bytes. */ - len = strlen(doc_str); - tp_doc = (char *)PyObject_MALLOC(len + 1); - if (tp_doc == NULL) { - Py_DECREF(type); - return NULL; - } - memcpy(tp_doc, doc_str, len + 1); - type->tp_doc = tp_doc; - } - } - - /* Special-case __new__: if it's a plain function, - make it a static function */ - tmp = PyDict_GetItemString(dict, "__new__"); - if (tmp != NULL && PyFunction_Check(tmp)) { - tmp = PyStaticMethod_New(tmp); - if (tmp == NULL) { - Py_DECREF(type); - return NULL; - } - PyDict_SetItemString(dict, "__new__", tmp); - Py_DECREF(tmp); - } - - /* Add descriptors for custom slots from __slots__, or for __dict__ */ - mp = PyHeapType_GET_MEMBERS(et); - slotoffset = base->tp_basicsize; - if (slots != NULL) { - for (i = 0; i < nslots; i++, mp++) { - mp->name = _PyUnicode_AsString( - PyTuple_GET_ITEM(slots, i)); - mp->type = T_OBJECT_EX; - mp->offset = slotoffset; - - /* __dict__ and __weakref__ are already filtered out */ - assert(strcmp(mp->name, "__dict__") != 0); - assert(strcmp(mp->name, "__weakref__") != 0); - - slotoffset += sizeof(PyObject *); - } - } - if (add_dict) { - if (base->tp_itemsize) - type->tp_dictoffset = -(long)sizeof(PyObject *); - else - type->tp_dictoffset = slotoffset; - slotoffset += sizeof(PyObject *); - } - if (add_weak) { - assert(!base->tp_itemsize); - type->tp_weaklistoffset = slotoffset; - slotoffset += sizeof(PyObject *); - } - type->tp_basicsize = slotoffset; - type->tp_itemsize = base->tp_itemsize; - type->tp_members = PyHeapType_GET_MEMBERS(et); - - if (type->tp_weaklistoffset && type->tp_dictoffset) - type->tp_getset = subtype_getsets_full; - else if (type->tp_weaklistoffset && !type->tp_dictoffset) - type->tp_getset = subtype_getsets_weakref_only; - else if (!type->tp_weaklistoffset && type->tp_dictoffset) - type->tp_getset = subtype_getsets_dict_only; - else - type->tp_getset = NULL; - - /* Special case some slots */ - if (type->tp_dictoffset != 0 || nslots > 0) { - if (base->tp_getattr == NULL && base->tp_getattro == NULL) - type->tp_getattro = PyObject_GenericGetAttr; - if (base->tp_setattr == NULL && base->tp_setattro == NULL) - type->tp_setattro = PyObject_GenericSetAttr; - } - type->tp_dealloc = subtype_dealloc; - - /* Enable GC unless there are really no instance variables possible */ - if (!(type->tp_basicsize == sizeof(PyObject) && - type->tp_itemsize == 0)) - type->tp_flags |= Py_TPFLAGS_HAVE_GC; - - /* Always override allocation strategy to use regular heap */ - type->tp_alloc = PyType_GenericAlloc; - if (type->tp_flags & Py_TPFLAGS_HAVE_GC) { - type->tp_free = PyObject_GC_Del; - type->tp_traverse = subtype_traverse; - type->tp_clear = subtype_clear; - } - else - type->tp_free = PyObject_Del; - - /* Initialize the rest */ - if (PyType_Ready(type) < 0) { - Py_DECREF(type); - return NULL; - } + PyObject *name, *bases, *dict; + static char *kwlist[] = {"name", "bases", "dict", 0}; + PyObject *slots, *tmp, *newslots; + PyTypeObject *type, *base, *tmptype, *winner; + PyHeapTypeObject *et; + PyMemberDef *mp; + Py_ssize_t i, nbases, nslots, slotoffset, add_dict, add_weak; + int j, may_add_dict, may_add_weak; + + assert(args != NULL && PyTuple_Check(args)); + assert(kwds == NULL || PyDict_Check(kwds)); + + /* Special case: type(x) should return x->ob_type */ + { + const Py_ssize_t nargs = PyTuple_GET_SIZE(args); + const Py_ssize_t nkwds = kwds == NULL ? 0 : PyDict_Size(kwds); + + if (PyType_CheckExact(metatype) && nargs == 1 && nkwds == 0) { + PyObject *x = PyTuple_GET_ITEM(args, 0); + Py_INCREF(Py_TYPE(x)); + return (PyObject *) Py_TYPE(x); + } + + /* SF bug 475327 -- if that didn't trigger, we need 3 + arguments. but PyArg_ParseTupleAndKeywords below may give + a msg saying type() needs exactly 3. */ + if (nargs + nkwds != 3) { + PyErr_SetString(PyExc_TypeError, + "type() takes 1 or 3 arguments"); + return NULL; + } + } + + /* Check arguments: (name, bases, dict) */ + if (!PyArg_ParseTupleAndKeywords(args, kwds, "UO!O!:type", kwlist, + &name, + &PyTuple_Type, &bases, + &PyDict_Type, &dict)) + return NULL; + + /* Determine the proper metatype to deal with this, + and check for metatype conflicts while we're at it. + Note that if some other metatype wins to contract, + it's possible that its instances are not types. */ + nbases = PyTuple_GET_SIZE(bases); + winner = metatype; + for (i = 0; i < nbases; i++) { + tmp = PyTuple_GET_ITEM(bases, i); + tmptype = Py_TYPE(tmp); + if (PyType_IsSubtype(winner, tmptype)) + continue; + if (PyType_IsSubtype(tmptype, winner)) { + winner = tmptype; + continue; + } + PyErr_SetString(PyExc_TypeError, + "metaclass conflict: " + "the metaclass of a derived class " + "must be a (non-strict) subclass " + "of the metaclasses of all its bases"); + return NULL; + } + if (winner != metatype) { + if (winner->tp_new != type_new) /* Pass it to the winner */ + return winner->tp_new(winner, args, kwds); + metatype = winner; + } + + /* Adjust for empty tuple bases */ + if (nbases == 0) { + bases = PyTuple_Pack(1, &PyBaseObject_Type); + if (bases == NULL) + return NULL; + nbases = 1; + } + else + Py_INCREF(bases); + + /* XXX From here until type is allocated, "return NULL" leaks bases! */ + + /* Calculate best base, and check that all bases are type objects */ + base = best_base(bases); + if (base == NULL) { + Py_DECREF(bases); + return NULL; + } + if (!PyType_HasFeature(base, Py_TPFLAGS_BASETYPE)) { + PyErr_Format(PyExc_TypeError, + "type '%.100s' is not an acceptable base type", + base->tp_name); + Py_DECREF(bases); + return NULL; + } + + /* Check for a __slots__ sequence variable in dict, and count it */ + slots = PyDict_GetItemString(dict, "__slots__"); + nslots = 0; + add_dict = 0; + add_weak = 0; + may_add_dict = base->tp_dictoffset == 0; + may_add_weak = base->tp_weaklistoffset == 0 && base->tp_itemsize == 0; + if (slots == NULL) { + if (may_add_dict) { + add_dict++; + } + if (may_add_weak) { + add_weak++; + } + } + else { + /* Have slots */ + + /* Make it into a tuple */ + if (PyUnicode_Check(slots)) + slots = PyTuple_Pack(1, slots); + else + slots = PySequence_Tuple(slots); + if (slots == NULL) { + Py_DECREF(bases); + return NULL; + } + assert(PyTuple_Check(slots)); + + /* Are slots allowed? */ + nslots = PyTuple_GET_SIZE(slots); + if (nslots > 0 && base->tp_itemsize != 0) { + PyErr_Format(PyExc_TypeError, + "nonempty __slots__ " + "not supported for subtype of '%s'", + base->tp_name); + bad_slots: + Py_DECREF(bases); + Py_DECREF(slots); + return NULL; + } + + /* Check for valid slot names and two special cases */ + for (i = 0; i < nslots; i++) { + PyObject *tmp = PyTuple_GET_ITEM(slots, i); + if (!valid_identifier(tmp)) + goto bad_slots; + assert(PyUnicode_Check(tmp)); + if (PyUnicode_CompareWithASCIIString(tmp, "__dict__") == 0) { + if (!may_add_dict || add_dict) { + PyErr_SetString(PyExc_TypeError, + "__dict__ slot disallowed: " + "we already got one"); + goto bad_slots; + } + add_dict++; + } + if (PyUnicode_CompareWithASCIIString(tmp, "__weakref__") == 0) { + if (!may_add_weak || add_weak) { + PyErr_SetString(PyExc_TypeError, + "__weakref__ slot disallowed: " + "either we already got one, " + "or __itemsize__ != 0"); + goto bad_slots; + } + add_weak++; + } + } + + /* Copy slots into a list, mangle names and sort them. + Sorted names are needed for __class__ assignment. + Convert them back to tuple at the end. + */ + newslots = PyList_New(nslots - add_dict - add_weak); + if (newslots == NULL) + goto bad_slots; + for (i = j = 0; i < nslots; i++) { + tmp = PyTuple_GET_ITEM(slots, i); + if ((add_dict && + PyUnicode_CompareWithASCIIString(tmp, "__dict__") == 0) || + (add_weak && + PyUnicode_CompareWithASCIIString(tmp, "__weakref__") == 0)) + continue; + tmp =_Py_Mangle(name, tmp); + if (!tmp) + goto bad_slots; + PyList_SET_ITEM(newslots, j, tmp); + j++; + } + assert(j == nslots - add_dict - add_weak); + nslots = j; + Py_DECREF(slots); + if (PyList_Sort(newslots) == -1) { + Py_DECREF(bases); + Py_DECREF(newslots); + return NULL; + } + slots = PyList_AsTuple(newslots); + Py_DECREF(newslots); + if (slots == NULL) { + Py_DECREF(bases); + return NULL; + } + + /* Secondary bases may provide weakrefs or dict */ + if (nbases > 1 && + ((may_add_dict && !add_dict) || + (may_add_weak && !add_weak))) { + for (i = 0; i < nbases; i++) { + tmp = PyTuple_GET_ITEM(bases, i); + if (tmp == (PyObject *)base) + continue; /* Skip primary base */ + assert(PyType_Check(tmp)); + tmptype = (PyTypeObject *)tmp; + if (may_add_dict && !add_dict && + tmptype->tp_dictoffset != 0) + add_dict++; + if (may_add_weak && !add_weak && + tmptype->tp_weaklistoffset != 0) + add_weak++; + if (may_add_dict && !add_dict) + continue; + if (may_add_weak && !add_weak) + continue; + /* Nothing more to check */ + break; + } + } + } - /* Put the proper slots in place */ - fixup_slot_dispatchers(type); + /* XXX From here until type is safely allocated, + "return NULL" may leak slots! */ - return (PyObject *)type; + /* Allocate the type object */ + type = (PyTypeObject *)metatype->tp_alloc(metatype, nslots); + if (type == NULL) { + Py_XDECREF(slots); + Py_DECREF(bases); + return NULL; + } + + /* Keep name and slots alive in the extended type object */ + et = (PyHeapTypeObject *)type; + Py_INCREF(name); + et->ht_name = name; + et->ht_slots = slots; + + /* Initialize tp_flags */ + type->tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HEAPTYPE | + Py_TPFLAGS_BASETYPE; + if (base->tp_flags & Py_TPFLAGS_HAVE_GC) + type->tp_flags |= Py_TPFLAGS_HAVE_GC; + + /* Initialize essential fields */ + type->tp_as_number = &et->as_number; + type->tp_as_sequence = &et->as_sequence; + type->tp_as_mapping = &et->as_mapping; + type->tp_as_buffer = &et->as_buffer; + type->tp_name = _PyUnicode_AsString(name); + if (!type->tp_name) { + Py_DECREF(type); + return NULL; + } + + /* Set tp_base and tp_bases */ + type->tp_bases = bases; + Py_INCREF(base); + type->tp_base = base; + + /* Initialize tp_dict from passed-in dict */ + type->tp_dict = dict = PyDict_Copy(dict); + if (dict == NULL) { + Py_DECREF(type); + return NULL; + } + + /* Set __module__ in the dict */ + if (PyDict_GetItemString(dict, "__module__") == NULL) { + tmp = PyEval_GetGlobals(); + if (tmp != NULL) { + tmp = PyDict_GetItemString(tmp, "__name__"); + if (tmp != NULL) { + if (PyDict_SetItemString(dict, "__module__", + tmp) < 0) + return NULL; + } + } + } + + /* Set tp_doc to a copy of dict['__doc__'], if the latter is there + and is a string. The __doc__ accessor will first look for tp_doc; + if that fails, it will still look into __dict__. + */ + { + PyObject *doc = PyDict_GetItemString(dict, "__doc__"); + if (doc != NULL && PyUnicode_Check(doc)) { + Py_ssize_t len; + char *doc_str; + char *tp_doc; + + doc_str = _PyUnicode_AsString(doc); + if (doc_str == NULL) { + Py_DECREF(type); + return NULL; + } + /* Silently truncate the docstring if it contains null bytes. */ + len = strlen(doc_str); + tp_doc = (char *)PyObject_MALLOC(len + 1); + if (tp_doc == NULL) { + Py_DECREF(type); + return NULL; + } + memcpy(tp_doc, doc_str, len + 1); + type->tp_doc = tp_doc; + } + } + + /* Special-case __new__: if it's a plain function, + make it a static function */ + tmp = PyDict_GetItemString(dict, "__new__"); + if (tmp != NULL && PyFunction_Check(tmp)) { + tmp = PyStaticMethod_New(tmp); + if (tmp == NULL) { + Py_DECREF(type); + return NULL; + } + PyDict_SetItemString(dict, "__new__", tmp); + Py_DECREF(tmp); + } + + /* Add descriptors for custom slots from __slots__, or for __dict__ */ + mp = PyHeapType_GET_MEMBERS(et); + slotoffset = base->tp_basicsize; + if (slots != NULL) { + for (i = 0; i < nslots; i++, mp++) { + mp->name = _PyUnicode_AsString( + PyTuple_GET_ITEM(slots, i)); + mp->type = T_OBJECT_EX; + mp->offset = slotoffset; + + /* __dict__ and __weakref__ are already filtered out */ + assert(strcmp(mp->name, "__dict__") != 0); + assert(strcmp(mp->name, "__weakref__") != 0); + + slotoffset += sizeof(PyObject *); + } + } + if (add_dict) { + if (base->tp_itemsize) + type->tp_dictoffset = -(long)sizeof(PyObject *); + else + type->tp_dictoffset = slotoffset; + slotoffset += sizeof(PyObject *); + } + if (add_weak) { + assert(!base->tp_itemsize); + type->tp_weaklistoffset = slotoffset; + slotoffset += sizeof(PyObject *); + } + type->tp_basicsize = slotoffset; + type->tp_itemsize = base->tp_itemsize; + type->tp_members = PyHeapType_GET_MEMBERS(et); + + if (type->tp_weaklistoffset && type->tp_dictoffset) + type->tp_getset = subtype_getsets_full; + else if (type->tp_weaklistoffset && !type->tp_dictoffset) + type->tp_getset = subtype_getsets_weakref_only; + else if (!type->tp_weaklistoffset && type->tp_dictoffset) + type->tp_getset = subtype_getsets_dict_only; + else + type->tp_getset = NULL; + + /* Special case some slots */ + if (type->tp_dictoffset != 0 || nslots > 0) { + if (base->tp_getattr == NULL && base->tp_getattro == NULL) + type->tp_getattro = PyObject_GenericGetAttr; + if (base->tp_setattr == NULL && base->tp_setattro == NULL) + type->tp_setattro = PyObject_GenericSetAttr; + } + type->tp_dealloc = subtype_dealloc; + + /* Enable GC unless there are really no instance variables possible */ + if (!(type->tp_basicsize == sizeof(PyObject) && + type->tp_itemsize == 0)) + type->tp_flags |= Py_TPFLAGS_HAVE_GC; + + /* Always override allocation strategy to use regular heap */ + type->tp_alloc = PyType_GenericAlloc; + if (type->tp_flags & Py_TPFLAGS_HAVE_GC) { + type->tp_free = PyObject_GC_Del; + type->tp_traverse = subtype_traverse; + type->tp_clear = subtype_clear; + } + else + type->tp_free = PyObject_Del; + + /* Initialize the rest */ + if (PyType_Ready(type) < 0) { + Py_DECREF(type); + return NULL; + } + + /* Put the proper slots in place */ + fixup_slot_dispatchers(type); + + return (PyObject *)type; } /* Internal API to look for a name through the MRO. @@ -2296,50 +2296,50 @@ PyObject * _PyType_Lookup(PyTypeObject *type, PyObject *name) { - Py_ssize_t i, n; - PyObject *mro, *res, *base, *dict; - unsigned int h; - - if (MCACHE_CACHEABLE_NAME(name) && - PyType_HasFeature(type, Py_TPFLAGS_VALID_VERSION_TAG)) { - /* fast path */ - h = MCACHE_HASH_METHOD(type, name); - if (method_cache[h].version == type->tp_version_tag && - method_cache[h].name == name) - return method_cache[h].value; - } - - /* Look in tp_dict of types in MRO */ - mro = type->tp_mro; - - /* If mro is NULL, the type is either not yet initialized - by PyType_Ready(), or already cleared by type_clear(). - Either way the safest thing to do is to return NULL. */ - if (mro == NULL) - return NULL; - - res = NULL; - assert(PyTuple_Check(mro)); - n = PyTuple_GET_SIZE(mro); - for (i = 0; i < n; i++) { - base = PyTuple_GET_ITEM(mro, i); - assert(PyType_Check(base)); - dict = ((PyTypeObject *)base)->tp_dict; - assert(dict && PyDict_Check(dict)); - res = PyDict_GetItem(dict, name); - if (res != NULL) - break; - } - - if (MCACHE_CACHEABLE_NAME(name) && assign_version_tag(type)) { - h = MCACHE_HASH_METHOD(type, name); - method_cache[h].version = type->tp_version_tag; - method_cache[h].value = res; /* borrowed */ - Py_INCREF(name); - Py_DECREF(method_cache[h].name); - method_cache[h].name = name; - } - return res; + Py_ssize_t i, n; + PyObject *mro, *res, *base, *dict; + unsigned int h; + + if (MCACHE_CACHEABLE_NAME(name) && + PyType_HasFeature(type, Py_TPFLAGS_VALID_VERSION_TAG)) { + /* fast path */ + h = MCACHE_HASH_METHOD(type, name); + if (method_cache[h].version == type->tp_version_tag && + method_cache[h].name == name) + return method_cache[h].value; + } + + /* Look in tp_dict of types in MRO */ + mro = type->tp_mro; + + /* If mro is NULL, the type is either not yet initialized + by PyType_Ready(), or already cleared by type_clear(). + Either way the safest thing to do is to return NULL. */ + if (mro == NULL) + return NULL; + + res = NULL; + assert(PyTuple_Check(mro)); + n = PyTuple_GET_SIZE(mro); + for (i = 0; i < n; i++) { + base = PyTuple_GET_ITEM(mro, i); + assert(PyType_Check(base)); + dict = ((PyTypeObject *)base)->tp_dict; + assert(dict && PyDict_Check(dict)); + res = PyDict_GetItem(dict, name); + if (res != NULL) + break; + } + + if (MCACHE_CACHEABLE_NAME(name) && assign_version_tag(type)) { + h = MCACHE_HASH_METHOD(type, name); + method_cache[h].version = type->tp_version_tag; + method_cache[h].value = res; /* borrowed */ + Py_INCREF(name); + Py_DECREF(method_cache[h].name); + method_cache[h].name = name; + } + return res; } /* This is similar to PyObject_GenericGetAttr(), @@ -2347,166 +2347,166 @@ static PyObject * type_getattro(PyTypeObject *type, PyObject *name) { - PyTypeObject *metatype = Py_TYPE(type); - PyObject *meta_attribute, *attribute; - descrgetfunc meta_get; - - /* Initialize this type (we'll assume the metatype is initialized) */ - if (type->tp_dict == NULL) { - if (PyType_Ready(type) < 0) - return NULL; - } - - /* No readable descriptor found yet */ - meta_get = NULL; - - /* Look for the attribute in the metatype */ - meta_attribute = _PyType_Lookup(metatype, name); - - if (meta_attribute != NULL) { - meta_get = Py_TYPE(meta_attribute)->tp_descr_get; - - if (meta_get != NULL && PyDescr_IsData(meta_attribute)) { - /* Data descriptors implement tp_descr_set to intercept - * 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); - } - Py_INCREF(meta_attribute); - } - - /* No data descriptor found on metatype. Look in tp_dict of this - * type and its bases */ - attribute = _PyType_Lookup(type, name); - if (attribute != NULL) { - /* Implement descriptor functionality, if any */ - descrgetfunc 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); - } - - Py_INCREF(attribute); - return attribute; - } - - /* No attribute found in local __dict__ (or bases): use the - * descriptor from the metatype, if any */ - if (meta_get != NULL) { - PyObject *res; - res = meta_get(meta_attribute, (PyObject *)type, - (PyObject *)metatype); - Py_DECREF(meta_attribute); - return res; - } - - /* If an ordinary attribute was found on the metatype, return it now */ - if (meta_attribute != NULL) { - return meta_attribute; - } - - /* Give up */ - PyErr_Format(PyExc_AttributeError, - "type object '%.50s' has no attribute '%U'", - type->tp_name, name); - return NULL; + PyTypeObject *metatype = Py_TYPE(type); + PyObject *meta_attribute, *attribute; + descrgetfunc meta_get; + + /* Initialize this type (we'll assume the metatype is initialized) */ + if (type->tp_dict == NULL) { + if (PyType_Ready(type) < 0) + return NULL; + } + + /* No readable descriptor found yet */ + meta_get = NULL; + + /* Look for the attribute in the metatype */ + meta_attribute = _PyType_Lookup(metatype, name); + + if (meta_attribute != NULL) { + meta_get = Py_TYPE(meta_attribute)->tp_descr_get; + + if (meta_get != NULL && PyDescr_IsData(meta_attribute)) { + /* Data descriptors implement tp_descr_set to intercept + * 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); + } + Py_INCREF(meta_attribute); + } + + /* No data descriptor found on metatype. Look in tp_dict of this + * type and its bases */ + attribute = _PyType_Lookup(type, name); + if (attribute != NULL) { + /* Implement descriptor functionality, if any */ + descrgetfunc 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); + } + + Py_INCREF(attribute); + return attribute; + } + + /* No attribute found in local __dict__ (or bases): use the + * descriptor from the metatype, if any */ + if (meta_get != NULL) { + PyObject *res; + res = meta_get(meta_attribute, (PyObject *)type, + (PyObject *)metatype); + Py_DECREF(meta_attribute); + return res; + } + + /* If an ordinary attribute was found on the metatype, return it now */ + if (meta_attribute != NULL) { + return meta_attribute; + } + + /* Give up */ + PyErr_Format(PyExc_AttributeError, + "type object '%.50s' has no attribute '%U'", + type->tp_name, name); + return NULL; } static int type_setattro(PyTypeObject *type, PyObject *name, PyObject *value) { - if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE)) { - PyErr_Format( - PyExc_TypeError, - "can't set attributes of built-in/extension type '%s'", - type->tp_name); - return -1; - } - if (PyObject_GenericSetAttr((PyObject *)type, name, value) < 0) - return -1; - return update_slot(type, name); + if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE)) { + PyErr_Format( + PyExc_TypeError, + "can't set attributes of built-in/extension type '%s'", + type->tp_name); + return -1; + } + if (PyObject_GenericSetAttr((PyObject *)type, name, value) < 0) + return -1; + return update_slot(type, name); } static void type_dealloc(PyTypeObject *type) { - PyHeapTypeObject *et; + PyHeapTypeObject *et; - /* Assert this is a heap-allocated type object */ - assert(type->tp_flags & Py_TPFLAGS_HEAPTYPE); - _PyObject_GC_UNTRACK(type); - PyObject_ClearWeakRefs((PyObject *)type); - et = (PyHeapTypeObject *)type; - Py_XDECREF(type->tp_base); - Py_XDECREF(type->tp_dict); - Py_XDECREF(type->tp_bases); - Py_XDECREF(type->tp_mro); - Py_XDECREF(type->tp_cache); - Py_XDECREF(type->tp_subclasses); - /* A type's tp_doc is heap allocated, unlike the tp_doc slots - * of most other objects. It's okay to cast it to char *. - */ - PyObject_Free((char *)type->tp_doc); - Py_XDECREF(et->ht_name); - Py_XDECREF(et->ht_slots); - Py_TYPE(type)->tp_free((PyObject *)type); + /* Assert this is a heap-allocated type object */ + assert(type->tp_flags & Py_TPFLAGS_HEAPTYPE); + _PyObject_GC_UNTRACK(type); + PyObject_ClearWeakRefs((PyObject *)type); + et = (PyHeapTypeObject *)type; + Py_XDECREF(type->tp_base); + Py_XDECREF(type->tp_dict); + Py_XDECREF(type->tp_bases); + Py_XDECREF(type->tp_mro); + Py_XDECREF(type->tp_cache); + Py_XDECREF(type->tp_subclasses); + /* A type's tp_doc is heap allocated, unlike the tp_doc slots + * of most other objects. It's okay to cast it to char *. + */ + PyObject_Free((char *)type->tp_doc); + Py_XDECREF(et->ht_name); + Py_XDECREF(et->ht_slots); + Py_TYPE(type)->tp_free((PyObject *)type); } static PyObject * type_subclasses(PyTypeObject *type, PyObject *args_ignored) { - PyObject *list, *raw, *ref; - Py_ssize_t i, n; + PyObject *list, *raw, *ref; + Py_ssize_t i, n; - list = PyList_New(0); - if (list == NULL) - return NULL; - raw = type->tp_subclasses; - if (raw == NULL) - return list; - assert(PyList_Check(raw)); - n = PyList_GET_SIZE(raw); - for (i = 0; i < n; i++) { - ref = PyList_GET_ITEM(raw, i); - assert(PyWeakref_CheckRef(ref)); - ref = PyWeakref_GET_OBJECT(ref); - if (ref != Py_None) { - if (PyList_Append(list, ref) < 0) { - Py_DECREF(list); - return NULL; - } - } - } - return list; + list = PyList_New(0); + if (list == NULL) + return NULL; + raw = type->tp_subclasses; + if (raw == NULL) + return list; + assert(PyList_Check(raw)); + n = PyList_GET_SIZE(raw); + for (i = 0; i < n; i++) { + ref = PyList_GET_ITEM(raw, i); + assert(PyWeakref_CheckRef(ref)); + ref = PyWeakref_GET_OBJECT(ref); + if (ref != Py_None) { + if (PyList_Append(list, ref) < 0) { + Py_DECREF(list); + return NULL; + } + } + } + return list; } static PyObject * type_prepare(PyObject *self, PyObject *args, PyObject *kwds) { - return PyDict_New(); + return PyDict_New(); } static PyMethodDef type_methods[] = { - {"mro", (PyCFunction)mro_external, METH_NOARGS, - PyDoc_STR("mro() -> list\nreturn a type's method resolution order")}, - {"__subclasses__", (PyCFunction)type_subclasses, METH_NOARGS, - PyDoc_STR("__subclasses__() -> list of immediate subclasses")}, - {"__prepare__", (PyCFunction)type_prepare, - METH_VARARGS | METH_KEYWORDS | METH_CLASS, - PyDoc_STR("__prepare__() -> dict\n" - "used to create the namespace for the class statement")}, - {"__instancecheck__", type___instancecheck__, METH_O, - PyDoc_STR("__instancecheck__() -> check if an object is an instance")}, - {"__subclasscheck__", type___subclasscheck__, METH_O, - PyDoc_STR("__subclasschck__ -> check if an class is a subclass")}, - {0} + {"mro", (PyCFunction)mro_external, METH_NOARGS, + PyDoc_STR("mro() -> list\nreturn a type's method resolution order")}, + {"__subclasses__", (PyCFunction)type_subclasses, METH_NOARGS, + PyDoc_STR("__subclasses__() -> list of immediate subclasses")}, + {"__prepare__", (PyCFunction)type_prepare, + METH_VARARGS | METH_KEYWORDS | METH_CLASS, + PyDoc_STR("__prepare__() -> dict\n" + "used to create the namespace for the class statement")}, + {"__instancecheck__", type___instancecheck__, METH_O, + PyDoc_STR("__instancecheck__() -> check if an object is an instance")}, + {"__subclasscheck__", type___subclasscheck__, METH_O, + PyDoc_STR("__subclasschck__ -> check if an class is a subclass")}, + {0} }; PyDoc_STRVAR(type_doc, @@ -2516,109 +2516,109 @@ static int type_traverse(PyTypeObject *type, visitproc visit, void *arg) { - /* Because of type_is_gc(), the collector only calls this - for heaptypes. */ - assert(type->tp_flags & Py_TPFLAGS_HEAPTYPE); - - Py_VISIT(type->tp_dict); - Py_VISIT(type->tp_cache); - Py_VISIT(type->tp_mro); - Py_VISIT(type->tp_bases); - Py_VISIT(type->tp_base); - - /* There's no need to visit type->tp_subclasses or - ((PyHeapTypeObject *)type)->ht_slots, because they can't be involved - in cycles; tp_subclasses is a list of weak references, - and slots is a tuple of strings. */ + /* Because of type_is_gc(), the collector only calls this + for heaptypes. */ + assert(type->tp_flags & Py_TPFLAGS_HEAPTYPE); + + Py_VISIT(type->tp_dict); + Py_VISIT(type->tp_cache); + Py_VISIT(type->tp_mro); + Py_VISIT(type->tp_bases); + Py_VISIT(type->tp_base); + + /* There's no need to visit type->tp_subclasses or + ((PyHeapTypeObject *)type)->ht_slots, because they can't be involved + in cycles; tp_subclasses is a list of weak references, + and slots is a tuple of strings. */ - return 0; + return 0; } static int type_clear(PyTypeObject *type) { - /* Because of type_is_gc(), the collector only calls this - for heaptypes. */ - assert(type->tp_flags & Py_TPFLAGS_HEAPTYPE); - - /* The only field we need to clear is tp_mro, which is part of a - hard cycle (its first element is the class itself) that won't - be broken otherwise (it's a tuple and tuples don't have a - tp_clear handler). None of the other fields need to be - cleared, and here's why: - - tp_dict: - It is a dict, so the collector will call its tp_clear. - - tp_cache: - Not used; if it were, it would be a dict. - - tp_bases, tp_base: - If these are involved in a cycle, there must be at least - one other, mutable object in the cycle, e.g. a base - class's dict; the cycle will be broken that way. - - tp_subclasses: - A list of weak references can't be part of a cycle; and - lists have their own tp_clear. - - slots (in PyHeapTypeObject): - A tuple of strings can't be part of a cycle. - */ + /* Because of type_is_gc(), the collector only calls this + for heaptypes. */ + assert(type->tp_flags & Py_TPFLAGS_HEAPTYPE); + + /* The only field we need to clear is tp_mro, which is part of a + hard cycle (its first element is the class itself) that won't + be broken otherwise (it's a tuple and tuples don't have a + tp_clear handler). None of the other fields need to be + cleared, and here's why: + + tp_dict: + It is a dict, so the collector will call its tp_clear. + + tp_cache: + Not used; if it were, it would be a dict. + + tp_bases, tp_base: + If these are involved in a cycle, there must be at least + one other, mutable object in the cycle, e.g. a base + class's dict; the cycle will be broken that way. + + tp_subclasses: + A list of weak references can't be part of a cycle; and + lists have their own tp_clear. + + slots (in PyHeapTypeObject): + A tuple of strings can't be part of a cycle. + */ - Py_CLEAR(type->tp_mro); + Py_CLEAR(type->tp_mro); - return 0; + return 0; } static int type_is_gc(PyTypeObject *type) { - return type->tp_flags & Py_TPFLAGS_HEAPTYPE; + return type->tp_flags & Py_TPFLAGS_HEAPTYPE; } PyTypeObject PyType_Type = { - PyVarObject_HEAD_INIT(&PyType_Type, 0) - "type", /* tp_name */ - sizeof(PyHeapTypeObject), /* tp_basicsize */ - sizeof(PyMemberDef), /* tp_itemsize */ - (destructor)type_dealloc, /* tp_dealloc */ - 0, /* tp_print */ - 0, /* tp_getattr */ - 0, /* tp_setattr */ - 0, /* tp_reserved */ - (reprfunc)type_repr, /* tp_repr */ - 0, /* tp_as_number */ - 0, /* tp_as_sequence */ - 0, /* tp_as_mapping */ - 0, /* tp_hash */ - (ternaryfunc)type_call, /* tp_call */ - 0, /* tp_str */ - (getattrofunc)type_getattro, /* tp_getattro */ - (setattrofunc)type_setattro, /* tp_setattro */ - 0, /* tp_as_buffer */ - Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC | - Py_TPFLAGS_BASETYPE | Py_TPFLAGS_TYPE_SUBCLASS, /* tp_flags */ - type_doc, /* tp_doc */ - (traverseproc)type_traverse, /* tp_traverse */ - (inquiry)type_clear, /* tp_clear */ - 0, /* tp_richcompare */ - offsetof(PyTypeObject, tp_weaklist), /* tp_weaklistoffset */ - 0, /* tp_iter */ - 0, /* tp_iternext */ - type_methods, /* tp_methods */ - type_members, /* tp_members */ - type_getsets, /* tp_getset */ - 0, /* tp_base */ - 0, /* tp_dict */ - 0, /* tp_descr_get */ - 0, /* tp_descr_set */ - offsetof(PyTypeObject, tp_dict), /* tp_dictoffset */ - type_init, /* tp_init */ - 0, /* tp_alloc */ - type_new, /* tp_new */ - PyObject_GC_Del, /* tp_free */ - (inquiry)type_is_gc, /* tp_is_gc */ + PyVarObject_HEAD_INIT(&PyType_Type, 0) + "type", /* tp_name */ + sizeof(PyHeapTypeObject), /* tp_basicsize */ + sizeof(PyMemberDef), /* tp_itemsize */ + (destructor)type_dealloc, /* tp_dealloc */ + 0, /* tp_print */ + 0, /* tp_getattr */ + 0, /* tp_setattr */ + 0, /* tp_reserved */ + (reprfunc)type_repr, /* tp_repr */ + 0, /* tp_as_number */ + 0, /* tp_as_sequence */ + 0, /* tp_as_mapping */ + 0, /* tp_hash */ + (ternaryfunc)type_call, /* tp_call */ + 0, /* tp_str */ + (getattrofunc)type_getattro, /* tp_getattro */ + (setattrofunc)type_setattro, /* tp_setattro */ + 0, /* tp_as_buffer */ + Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC | + Py_TPFLAGS_BASETYPE | Py_TPFLAGS_TYPE_SUBCLASS, /* tp_flags */ + type_doc, /* tp_doc */ + (traverseproc)type_traverse, /* tp_traverse */ + (inquiry)type_clear, /* tp_clear */ + 0, /* tp_richcompare */ + offsetof(PyTypeObject, tp_weaklist), /* tp_weaklistoffset */ + 0, /* tp_iter */ + 0, /* tp_iternext */ + type_methods, /* tp_methods */ + type_members, /* tp_members */ + type_getsets, /* tp_getset */ + 0, /* tp_base */ + 0, /* tp_dict */ + 0, /* tp_descr_get */ + 0, /* tp_descr_set */ + offsetof(PyTypeObject, tp_dict), /* tp_dictoffset */ + type_init, /* tp_init */ + 0, /* tp_alloc */ + type_new, /* tp_new */ + PyObject_GC_Del, /* tp_free */ + (inquiry)type_is_gc, /* tp_is_gc */ }; @@ -2671,318 +2671,318 @@ static int excess_args(PyObject *args, PyObject *kwds) { - return PyTuple_GET_SIZE(args) || - (kwds && PyDict_Check(kwds) && PyDict_Size(kwds)); + return PyTuple_GET_SIZE(args) || + (kwds && PyDict_Check(kwds) && PyDict_Size(kwds)); } static int object_init(PyObject *self, PyObject *args, PyObject *kwds) { - int err = 0; - if (excess_args(args, kwds)) { - PyTypeObject *type = Py_TYPE(self); - if (type->tp_init != object_init && - type->tp_new != object_new) - { - err = PyErr_WarnEx(PyExc_DeprecationWarning, - "object.__init__() takes no parameters", - 1); - } - else if (type->tp_init != object_init || - type->tp_new == object_new) - { - PyErr_SetString(PyExc_TypeError, - "object.__init__() takes no parameters"); - err = -1; - } - } - return err; + int err = 0; + if (excess_args(args, kwds)) { + PyTypeObject *type = Py_TYPE(self); + if (type->tp_init != object_init && + type->tp_new != object_new) + { + err = PyErr_WarnEx(PyExc_DeprecationWarning, + "object.__init__() takes no parameters", + 1); + } + else if (type->tp_init != object_init || + type->tp_new == object_new) + { + PyErr_SetString(PyExc_TypeError, + "object.__init__() takes no parameters"); + err = -1; + } + } + return err; } static PyObject * object_new(PyTypeObject *type, PyObject *args, PyObject *kwds) { - int err = 0; - if (excess_args(args, kwds)) { - if (type->tp_new != object_new && - type->tp_init != object_init) - { - err = PyErr_WarnEx(PyExc_DeprecationWarning, - "object.__new__() takes no parameters", - 1); - } - else if (type->tp_new != object_new || - type->tp_init == object_init) - { - PyErr_SetString(PyExc_TypeError, - "object.__new__() takes no parameters"); - err = -1; - } - } - if (err < 0) - return NULL; - - if (type->tp_flags & Py_TPFLAGS_IS_ABSTRACT) { - static PyObject *comma = NULL; - PyObject *abstract_methods = NULL; - PyObject *builtins; - PyObject *sorted; - PyObject *sorted_methods = NULL; - PyObject *joined = NULL; - - /* Compute ", ".join(sorted(type.__abstractmethods__)) - into joined. */ - abstract_methods = type_abstractmethods(type, NULL); - if (abstract_methods == NULL) - goto error; - builtins = PyEval_GetBuiltins(); - if (builtins == NULL) - goto error; - sorted = PyDict_GetItemString(builtins, "sorted"); - if (sorted == NULL) - goto error; - sorted_methods = PyObject_CallFunctionObjArgs(sorted, - abstract_methods, - NULL); - if (sorted_methods == NULL) - goto error; - if (comma == NULL) { - comma = PyUnicode_InternFromString(", "); - if (comma == NULL) - goto error; - } - joined = PyObject_CallMethod(comma, "join", - "O", sorted_methods); - if (joined == NULL) - goto error; - - PyErr_Format(PyExc_TypeError, - "Can't instantiate abstract class %s " - "with abstract methods %U", - type->tp_name, - joined); - error: - Py_XDECREF(joined); - Py_XDECREF(sorted_methods); - Py_XDECREF(abstract_methods); - return NULL; - } - return type->tp_alloc(type, 0); + int err = 0; + if (excess_args(args, kwds)) { + if (type->tp_new != object_new && + type->tp_init != object_init) + { + err = PyErr_WarnEx(PyExc_DeprecationWarning, + "object.__new__() takes no parameters", + 1); + } + else if (type->tp_new != object_new || + type->tp_init == object_init) + { + PyErr_SetString(PyExc_TypeError, + "object.__new__() takes no parameters"); + err = -1; + } + } + if (err < 0) + return NULL; + + if (type->tp_flags & Py_TPFLAGS_IS_ABSTRACT) { + static PyObject *comma = NULL; + PyObject *abstract_methods = NULL; + PyObject *builtins; + PyObject *sorted; + PyObject *sorted_methods = NULL; + PyObject *joined = NULL; + + /* Compute ", ".join(sorted(type.__abstractmethods__)) + into joined. */ + abstract_methods = type_abstractmethods(type, NULL); + if (abstract_methods == NULL) + goto error; + builtins = PyEval_GetBuiltins(); + if (builtins == NULL) + goto error; + sorted = PyDict_GetItemString(builtins, "sorted"); + if (sorted == NULL) + goto error; + sorted_methods = PyObject_CallFunctionObjArgs(sorted, + abstract_methods, + NULL); + if (sorted_methods == NULL) + goto error; + if (comma == NULL) { + comma = PyUnicode_InternFromString(", "); + if (comma == NULL) + goto error; + } + joined = PyObject_CallMethod(comma, "join", + "O", sorted_methods); + if (joined == NULL) + goto error; + + PyErr_Format(PyExc_TypeError, + "Can't instantiate abstract class %s " + "with abstract methods %U", + type->tp_name, + joined); + error: + Py_XDECREF(joined); + Py_XDECREF(sorted_methods); + Py_XDECREF(abstract_methods); + return NULL; + } + return type->tp_alloc(type, 0); } static void object_dealloc(PyObject *self) { - Py_TYPE(self)->tp_free(self); + Py_TYPE(self)->tp_free(self); } static PyObject * object_repr(PyObject *self) { - PyTypeObject *type; - PyObject *mod, *name, *rtn; + PyTypeObject *type; + PyObject *mod, *name, *rtn; - type = Py_TYPE(self); - mod = type_module(type, NULL); - if (mod == NULL) - PyErr_Clear(); - else if (!PyUnicode_Check(mod)) { - Py_DECREF(mod); - mod = NULL; - } - name = type_name(type, NULL); - if (name == NULL) - return NULL; - if (mod != NULL && PyUnicode_CompareWithASCIIString(mod, "builtins")) - rtn = PyUnicode_FromFormat("<%U.%U object at %p>", mod, name, self); - else - rtn = PyUnicode_FromFormat("<%s object at %p>", - type->tp_name, self); - Py_XDECREF(mod); - Py_DECREF(name); - return rtn; + type = Py_TYPE(self); + mod = type_module(type, NULL); + if (mod == NULL) + PyErr_Clear(); + else if (!PyUnicode_Check(mod)) { + Py_DECREF(mod); + mod = NULL; + } + name = type_name(type, NULL); + if (name == NULL) + return NULL; + if (mod != NULL && PyUnicode_CompareWithASCIIString(mod, "builtins")) + rtn = PyUnicode_FromFormat("<%U.%U object at %p>", mod, name, self); + else + rtn = PyUnicode_FromFormat("<%s object at %p>", + type->tp_name, self); + Py_XDECREF(mod); + Py_DECREF(name); + return rtn; } static PyObject * object_str(PyObject *self) { - unaryfunc f; + unaryfunc f; - f = Py_TYPE(self)->tp_repr; - if (f == NULL) - f = object_repr; - return f(self); + f = Py_TYPE(self)->tp_repr; + if (f == NULL) + f = object_repr; + return f(self); } static PyObject * object_richcompare(PyObject *self, PyObject *other, int op) { - PyObject *res; + PyObject *res; - switch (op) { + switch (op) { - case Py_EQ: - /* Return NotImplemented instead of False, so if two - objects are compared, both get a chance at the - comparison. See issue #1393. */ - res = (self == other) ? Py_True : Py_NotImplemented; - Py_INCREF(res); - break; - - case Py_NE: - /* By default, != returns the opposite of ==, - unless the latter returns NotImplemented. */ - res = PyObject_RichCompare(self, other, Py_EQ); - if (res != NULL && res != Py_NotImplemented) { - int ok = PyObject_IsTrue(res); - Py_DECREF(res); - if (ok < 0) - res = NULL; - else { - if (ok) - res = Py_False; - else - res = Py_True; - Py_INCREF(res); - } - } - break; - - default: - res = Py_NotImplemented; - Py_INCREF(res); - break; - } + case Py_EQ: + /* Return NotImplemented instead of False, so if two + objects are compared, both get a chance at the + comparison. See issue #1393. */ + res = (self == other) ? Py_True : Py_NotImplemented; + Py_INCREF(res); + break; + + case Py_NE: + /* By default, != returns the opposite of ==, + unless the latter returns NotImplemented. */ + res = PyObject_RichCompare(self, other, Py_EQ); + if (res != NULL && res != Py_NotImplemented) { + int ok = PyObject_IsTrue(res); + Py_DECREF(res); + if (ok < 0) + res = NULL; + else { + if (ok) + res = Py_False; + else + res = Py_True; + Py_INCREF(res); + } + } + break; - return res; + default: + res = Py_NotImplemented; + Py_INCREF(res); + break; + } + + return res; } static PyObject * object_get_class(PyObject *self, void *closure) { - Py_INCREF(Py_TYPE(self)); - return (PyObject *)(Py_TYPE(self)); + Py_INCREF(Py_TYPE(self)); + return (PyObject *)(Py_TYPE(self)); } static int equiv_structs(PyTypeObject *a, PyTypeObject *b) { - return a == b || - (a != NULL && - b != NULL && - a->tp_basicsize == b->tp_basicsize && - a->tp_itemsize == b->tp_itemsize && - a->tp_dictoffset == b->tp_dictoffset && - a->tp_weaklistoffset == b->tp_weaklistoffset && - ((a->tp_flags & Py_TPFLAGS_HAVE_GC) == - (b->tp_flags & Py_TPFLAGS_HAVE_GC))); + return a == b || + (a != NULL && + b != NULL && + a->tp_basicsize == b->tp_basicsize && + a->tp_itemsize == b->tp_itemsize && + a->tp_dictoffset == b->tp_dictoffset && + a->tp_weaklistoffset == b->tp_weaklistoffset && + ((a->tp_flags & Py_TPFLAGS_HAVE_GC) == + (b->tp_flags & Py_TPFLAGS_HAVE_GC))); } static int same_slots_added(PyTypeObject *a, PyTypeObject *b) { - PyTypeObject *base = a->tp_base; - Py_ssize_t size; - PyObject *slots_a, *slots_b; - - if (base != b->tp_base) - return 0; - if (equiv_structs(a, base) && equiv_structs(b, base)) - return 1; - size = base->tp_basicsize; - if (a->tp_dictoffset == size && b->tp_dictoffset == size) - size += sizeof(PyObject *); - if (a->tp_weaklistoffset == size && b->tp_weaklistoffset == size) - size += sizeof(PyObject *); - - /* Check slots compliance */ - slots_a = ((PyHeapTypeObject *)a)->ht_slots; - slots_b = ((PyHeapTypeObject *)b)->ht_slots; - if (slots_a && slots_b) { - if (PyObject_RichCompareBool(slots_a, slots_b, Py_EQ) != 1) - return 0; - size += sizeof(PyObject *) * PyTuple_GET_SIZE(slots_a); - } - return size == a->tp_basicsize && size == b->tp_basicsize; + PyTypeObject *base = a->tp_base; + Py_ssize_t size; + PyObject *slots_a, *slots_b; + + if (base != b->tp_base) + return 0; + if (equiv_structs(a, base) && equiv_structs(b, base)) + return 1; + size = base->tp_basicsize; + if (a->tp_dictoffset == size && b->tp_dictoffset == size) + size += sizeof(PyObject *); + if (a->tp_weaklistoffset == size && b->tp_weaklistoffset == size) + size += sizeof(PyObject *); + + /* Check slots compliance */ + slots_a = ((PyHeapTypeObject *)a)->ht_slots; + slots_b = ((PyHeapTypeObject *)b)->ht_slots; + if (slots_a && slots_b) { + if (PyObject_RichCompareBool(slots_a, slots_b, Py_EQ) != 1) + return 0; + size += sizeof(PyObject *) * PyTuple_GET_SIZE(slots_a); + } + return size == a->tp_basicsize && size == b->tp_basicsize; } static int compatible_for_assignment(PyTypeObject* oldto, PyTypeObject* newto, char* attr) { - PyTypeObject *newbase, *oldbase; + PyTypeObject *newbase, *oldbase; - if (newto->tp_dealloc != oldto->tp_dealloc || - newto->tp_free != oldto->tp_free) - { - PyErr_Format(PyExc_TypeError, - "%s assignment: " - "'%s' deallocator differs from '%s'", - attr, - newto->tp_name, - oldto->tp_name); - return 0; - } - newbase = newto; - oldbase = oldto; - while (equiv_structs(newbase, newbase->tp_base)) - newbase = newbase->tp_base; - while (equiv_structs(oldbase, oldbase->tp_base)) - oldbase = oldbase->tp_base; - if (newbase != oldbase && - (newbase->tp_base != oldbase->tp_base || - !same_slots_added(newbase, oldbase))) { - PyErr_Format(PyExc_TypeError, - "%s assignment: " - "'%s' object layout differs from '%s'", - attr, - newto->tp_name, - oldto->tp_name); - return 0; - } + if (newto->tp_dealloc != oldto->tp_dealloc || + newto->tp_free != oldto->tp_free) + { + PyErr_Format(PyExc_TypeError, + "%s assignment: " + "'%s' deallocator differs from '%s'", + attr, + newto->tp_name, + oldto->tp_name); + return 0; + } + newbase = newto; + oldbase = oldto; + while (equiv_structs(newbase, newbase->tp_base)) + newbase = newbase->tp_base; + while (equiv_structs(oldbase, oldbase->tp_base)) + oldbase = oldbase->tp_base; + if (newbase != oldbase && + (newbase->tp_base != oldbase->tp_base || + !same_slots_added(newbase, oldbase))) { + PyErr_Format(PyExc_TypeError, + "%s assignment: " + "'%s' object layout differs from '%s'", + attr, + newto->tp_name, + oldto->tp_name); + return 0; + } - return 1; + return 1; } static int object_set_class(PyObject *self, PyObject *value, void *closure) { - PyTypeObject *oldto = Py_TYPE(self); - PyTypeObject *newto; + PyTypeObject *oldto = Py_TYPE(self); + PyTypeObject *newto; - if (value == NULL) { - PyErr_SetString(PyExc_TypeError, - "can't delete __class__ attribute"); - return -1; - } - if (!PyType_Check(value)) { - PyErr_Format(PyExc_TypeError, - "__class__ must be set to new-style class, not '%s' object", - Py_TYPE(value)->tp_name); - return -1; - } - newto = (PyTypeObject *)value; - if (!(newto->tp_flags & Py_TPFLAGS_HEAPTYPE) || - !(oldto->tp_flags & Py_TPFLAGS_HEAPTYPE)) - { - PyErr_Format(PyExc_TypeError, - "__class__ assignment: only for heap types"); - return -1; - } - if (compatible_for_assignment(newto, oldto, "__class__")) { - Py_INCREF(newto); - Py_TYPE(self) = newto; - Py_DECREF(oldto); - return 0; - } - else { - return -1; - } + if (value == NULL) { + PyErr_SetString(PyExc_TypeError, + "can't delete __class__ attribute"); + return -1; + } + if (!PyType_Check(value)) { + PyErr_Format(PyExc_TypeError, + "__class__ must be set to new-style class, not '%s' object", + Py_TYPE(value)->tp_name); + return -1; + } + newto = (PyTypeObject *)value; + if (!(newto->tp_flags & Py_TPFLAGS_HEAPTYPE) || + !(oldto->tp_flags & Py_TPFLAGS_HEAPTYPE)) + { + PyErr_Format(PyExc_TypeError, + "__class__ assignment: only for heap types"); + return -1; + } + if (compatible_for_assignment(newto, oldto, "__class__")) { + Py_INCREF(newto); + Py_TYPE(self) = newto; + Py_DECREF(oldto); + return 0; + } + else { + return -1; + } } static PyGetSetDef object_getsets[] = { - {"__class__", object_get_class, object_set_class, - PyDoc_STR("the object's class")}, - {0} + {"__class__", object_get_class, object_set_class, + PyDoc_STR("the object's class")}, + {0} }; @@ -2996,194 +2996,194 @@ static PyObject * import_copyreg(void) { - static PyObject *copyreg_str; + static PyObject *copyreg_str; - if (!copyreg_str) { - copyreg_str = PyUnicode_InternFromString("copyreg"); - if (copyreg_str == NULL) - return NULL; - } + if (!copyreg_str) { + copyreg_str = PyUnicode_InternFromString("copyreg"); + if (copyreg_str == NULL) + return NULL; + } - return PyImport_Import(copyreg_str); + return PyImport_Import(copyreg_str); } static PyObject * slotnames(PyObject *cls) { - PyObject *clsdict; - PyObject *copyreg; - PyObject *slotnames; - - if (!PyType_Check(cls)) { - Py_INCREF(Py_None); - return Py_None; - } - - clsdict = ((PyTypeObject *)cls)->tp_dict; - slotnames = PyDict_GetItemString(clsdict, "__slotnames__"); - if (slotnames != NULL && PyList_Check(slotnames)) { - Py_INCREF(slotnames); - return slotnames; - } - - copyreg = import_copyreg(); - if (copyreg == NULL) - return NULL; - - slotnames = PyObject_CallMethod(copyreg, "_slotnames", "O", cls); - Py_DECREF(copyreg); - if (slotnames != NULL && - slotnames != Py_None && - !PyList_Check(slotnames)) - { - PyErr_SetString(PyExc_TypeError, - "copyreg._slotnames didn't return a list or None"); - Py_DECREF(slotnames); - slotnames = NULL; - } + PyObject *clsdict; + PyObject *copyreg; + PyObject *slotnames; + + if (!PyType_Check(cls)) { + Py_INCREF(Py_None); + return Py_None; + } + + clsdict = ((PyTypeObject *)cls)->tp_dict; + slotnames = PyDict_GetItemString(clsdict, "__slotnames__"); + if (slotnames != NULL && PyList_Check(slotnames)) { + Py_INCREF(slotnames); + return slotnames; + } + + copyreg = import_copyreg(); + if (copyreg == NULL) + return NULL; + + slotnames = PyObject_CallMethod(copyreg, "_slotnames", "O", cls); + Py_DECREF(copyreg); + if (slotnames != NULL && + slotnames != Py_None && + !PyList_Check(slotnames)) + { + PyErr_SetString(PyExc_TypeError, + "copyreg._slotnames didn't return a list or None"); + Py_DECREF(slotnames); + slotnames = NULL; + } - return slotnames; + return slotnames; } static PyObject * reduce_2(PyObject *obj) { - PyObject *cls, *getnewargs; - PyObject *args = NULL, *args2 = NULL; - PyObject *getstate = NULL, *state = NULL, *names = NULL; - PyObject *slots = NULL, *listitems = NULL, *dictitems = NULL; - PyObject *copyreg = NULL, *newobj = NULL, *res = NULL; - Py_ssize_t i, n; - - cls = PyObject_GetAttrString(obj, "__class__"); - if (cls == NULL) - return NULL; - - getnewargs = PyObject_GetAttrString(obj, "__getnewargs__"); - if (getnewargs != NULL) { - args = PyObject_CallObject(getnewargs, NULL); - Py_DECREF(getnewargs); - if (args != NULL && !PyTuple_Check(args)) { - PyErr_Format(PyExc_TypeError, - "__getnewargs__ should return a tuple, " - "not '%.200s'", Py_TYPE(args)->tp_name); - goto end; - } - } - else { - PyErr_Clear(); - args = PyTuple_New(0); - } - if (args == NULL) - goto end; - - getstate = PyObject_GetAttrString(obj, "__getstate__"); - if (getstate != NULL) { - state = PyObject_CallObject(getstate, NULL); - Py_DECREF(getstate); - if (state == NULL) - goto end; - } - else { - PyErr_Clear(); - state = PyObject_GetAttrString(obj, "__dict__"); - if (state == NULL) { - PyErr_Clear(); - state = Py_None; - Py_INCREF(state); - } - names = slotnames(cls); - if (names == NULL) - goto end; - if (names != Py_None) { - assert(PyList_Check(names)); - slots = PyDict_New(); - if (slots == NULL) - goto end; - n = 0; - /* Can't pre-compute the list size; the list - is stored on the class so accessible to other - threads, which may be run by DECREF */ - for (i = 0; i < PyList_GET_SIZE(names); i++) { - PyObject *name, *value; - name = PyList_GET_ITEM(names, i); - value = PyObject_GetAttr(obj, name); - if (value == NULL) - PyErr_Clear(); - else { - int err = PyDict_SetItem(slots, name, - value); - Py_DECREF(value); - if (err) - goto end; - n++; - } - } - if (n) { - state = Py_BuildValue("(NO)", state, slots); - if (state == NULL) - goto end; - } - } - } - - if (!PyList_Check(obj)) { - listitems = Py_None; - Py_INCREF(listitems); - } - else { - listitems = PyObject_GetIter(obj); - if (listitems == NULL) - goto end; - } - - if (!PyDict_Check(obj)) { - dictitems = Py_None; - Py_INCREF(dictitems); - } - else { - PyObject *items = PyObject_CallMethod(obj, "items", ""); - if (items == NULL) - goto end; - dictitems = PyObject_GetIter(items); - Py_DECREF(items); - if (dictitems == NULL) - goto end; - } - - copyreg = import_copyreg(); - if (copyreg == NULL) - goto end; - newobj = PyObject_GetAttrString(copyreg, "__newobj__"); - if (newobj == NULL) - goto end; - - n = PyTuple_GET_SIZE(args); - args2 = PyTuple_New(n+1); - if (args2 == NULL) - goto end; - PyTuple_SET_ITEM(args2, 0, cls); - cls = NULL; - for (i = 0; i < n; i++) { - PyObject *v = PyTuple_GET_ITEM(args, i); - Py_INCREF(v); - PyTuple_SET_ITEM(args2, i+1, v); - } + PyObject *cls, *getnewargs; + PyObject *args = NULL, *args2 = NULL; + PyObject *getstate = NULL, *state = NULL, *names = NULL; + PyObject *slots = NULL, *listitems = NULL, *dictitems = NULL; + PyObject *copyreg = NULL, *newobj = NULL, *res = NULL; + Py_ssize_t i, n; + + cls = PyObject_GetAttrString(obj, "__class__"); + if (cls == NULL) + return NULL; + + getnewargs = PyObject_GetAttrString(obj, "__getnewargs__"); + if (getnewargs != NULL) { + args = PyObject_CallObject(getnewargs, NULL); + Py_DECREF(getnewargs); + if (args != NULL && !PyTuple_Check(args)) { + PyErr_Format(PyExc_TypeError, + "__getnewargs__ should return a tuple, " + "not '%.200s'", Py_TYPE(args)->tp_name); + goto end; + } + } + else { + PyErr_Clear(); + args = PyTuple_New(0); + } + if (args == NULL) + goto end; + + getstate = PyObject_GetAttrString(obj, "__getstate__"); + if (getstate != NULL) { + state = PyObject_CallObject(getstate, NULL); + Py_DECREF(getstate); + if (state == NULL) + goto end; + } + else { + PyErr_Clear(); + state = PyObject_GetAttrString(obj, "__dict__"); + if (state == NULL) { + PyErr_Clear(); + state = Py_None; + Py_INCREF(state); + } + names = slotnames(cls); + if (names == NULL) + goto end; + if (names != Py_None) { + assert(PyList_Check(names)); + slots = PyDict_New(); + if (slots == NULL) + goto end; + n = 0; + /* Can't pre-compute the list size; the list + is stored on the class so accessible to other + threads, which may be run by DECREF */ + for (i = 0; i < PyList_GET_SIZE(names); i++) { + PyObject *name, *value; + name = PyList_GET_ITEM(names, i); + value = PyObject_GetAttr(obj, name); + if (value == NULL) + PyErr_Clear(); + else { + int err = PyDict_SetItem(slots, name, + value); + Py_DECREF(value); + if (err) + goto end; + n++; + } + } + if (n) { + state = Py_BuildValue("(NO)", state, slots); + if (state == NULL) + goto end; + } + } + } + + if (!PyList_Check(obj)) { + listitems = Py_None; + Py_INCREF(listitems); + } + else { + listitems = PyObject_GetIter(obj); + if (listitems == NULL) + goto end; + } + + if (!PyDict_Check(obj)) { + dictitems = Py_None; + Py_INCREF(dictitems); + } + else { + PyObject *items = PyObject_CallMethod(obj, "items", ""); + if (items == NULL) + goto end; + dictitems = PyObject_GetIter(items); + Py_DECREF(items); + if (dictitems == NULL) + goto end; + } + + copyreg = import_copyreg(); + if (copyreg == NULL) + goto end; + newobj = PyObject_GetAttrString(copyreg, "__newobj__"); + if (newobj == NULL) + goto end; + + n = PyTuple_GET_SIZE(args); + args2 = PyTuple_New(n+1); + if (args2 == NULL) + goto end; + PyTuple_SET_ITEM(args2, 0, cls); + cls = NULL; + for (i = 0; i < n; i++) { + PyObject *v = PyTuple_GET_ITEM(args, i); + Py_INCREF(v); + PyTuple_SET_ITEM(args2, i+1, v); + } - res = PyTuple_Pack(5, newobj, args2, state, listitems, dictitems); + res = PyTuple_Pack(5, newobj, args2, state, listitems, dictitems); end: - Py_XDECREF(cls); - Py_XDECREF(args); - Py_XDECREF(args2); - Py_XDECREF(slots); - Py_XDECREF(state); - Py_XDECREF(names); - Py_XDECREF(listitems); - Py_XDECREF(dictitems); - Py_XDECREF(copyreg); - Py_XDECREF(newobj); - return res; + Py_XDECREF(cls); + Py_XDECREF(args); + Py_XDECREF(args2); + Py_XDECREF(slots); + Py_XDECREF(state); + Py_XDECREF(names); + Py_XDECREF(listitems); + Py_XDECREF(dictitems); + Py_XDECREF(copyreg); + Py_XDECREF(newobj); + return res; } /* @@ -3204,79 +3204,79 @@ static PyObject * _common_reduce(PyObject *self, int proto) { - PyObject *copyreg, *res; + PyObject *copyreg, *res; - if (proto >= 2) - return reduce_2(self); + if (proto >= 2) + return reduce_2(self); - copyreg = import_copyreg(); - if (!copyreg) - return NULL; + copyreg = import_copyreg(); + if (!copyreg) + return NULL; - res = PyEval_CallMethod(copyreg, "_reduce_ex", "(Oi)", self, proto); - Py_DECREF(copyreg); + res = PyEval_CallMethod(copyreg, "_reduce_ex", "(Oi)", self, proto); + Py_DECREF(copyreg); - return res; + return res; } static PyObject * object_reduce(PyObject *self, PyObject *args) { - int proto = 0; + int proto = 0; - if (!PyArg_ParseTuple(args, "|i:__reduce__", &proto)) - return NULL; + if (!PyArg_ParseTuple(args, "|i:__reduce__", &proto)) + return NULL; - return _common_reduce(self, proto); + return _common_reduce(self, proto); } static PyObject * object_reduce_ex(PyObject *self, PyObject *args) { - PyObject *reduce, *res; - int proto = 0; + PyObject *reduce, *res; + int proto = 0; - if (!PyArg_ParseTuple(args, "|i:__reduce_ex__", &proto)) - return NULL; + if (!PyArg_ParseTuple(args, "|i:__reduce_ex__", &proto)) + return NULL; - reduce = PyObject_GetAttrString(self, "__reduce__"); - if (reduce == NULL) - PyErr_Clear(); - else { - PyObject *cls, *clsreduce, *objreduce; - int override; - cls = PyObject_GetAttrString(self, "__class__"); - if (cls == NULL) { - Py_DECREF(reduce); - return NULL; - } - clsreduce = PyObject_GetAttrString(cls, "__reduce__"); - Py_DECREF(cls); - if (clsreduce == NULL) { - Py_DECREF(reduce); - return NULL; - } - objreduce = PyDict_GetItemString(PyBaseObject_Type.tp_dict, - "__reduce__"); - override = (clsreduce != objreduce); - Py_DECREF(clsreduce); - if (override) { - res = PyObject_CallObject(reduce, NULL); - Py_DECREF(reduce); - return res; - } - else - Py_DECREF(reduce); - } + reduce = PyObject_GetAttrString(self, "__reduce__"); + if (reduce == NULL) + PyErr_Clear(); + else { + PyObject *cls, *clsreduce, *objreduce; + int override; + cls = PyObject_GetAttrString(self, "__class__"); + if (cls == NULL) { + Py_DECREF(reduce); + return NULL; + } + clsreduce = PyObject_GetAttrString(cls, "__reduce__"); + Py_DECREF(cls); + if (clsreduce == NULL) { + Py_DECREF(reduce); + return NULL; + } + objreduce = PyDict_GetItemString(PyBaseObject_Type.tp_dict, + "__reduce__"); + override = (clsreduce != objreduce); + Py_DECREF(clsreduce); + if (override) { + res = PyObject_CallObject(reduce, NULL); + Py_DECREF(reduce); + return res; + } + else + Py_DECREF(reduce); + } - return _common_reduce(self, proto); + return _common_reduce(self, proto); } static PyObject * object_subclasshook(PyObject *cls, PyObject *args) { - Py_INCREF(Py_NotImplemented); - return Py_NotImplemented; + Py_INCREF(Py_NotImplemented); + return Py_NotImplemented; } PyDoc_STRVAR(object_subclasshook_doc, @@ -3292,104 +3292,104 @@ class object: def __format__(self, format_spec): - return format(str(self), format_spec) + return format(str(self), format_spec) */ static PyObject * object_format(PyObject *self, PyObject *args) { - PyObject *format_spec; - PyObject *self_as_str = NULL; - PyObject *result = NULL; - PyObject *format_meth = NULL; - - if (!PyArg_ParseTuple(args, "U:__format__", &format_spec)) - return NULL; - - self_as_str = PyObject_Str(self); - if (self_as_str != NULL) { - /* find the format function */ - format_meth = PyObject_GetAttrString(self_as_str, "__format__"); - if (format_meth != NULL) { - /* and call it */ - result = PyObject_CallFunctionObjArgs(format_meth, format_spec, NULL); - } + PyObject *format_spec; + PyObject *self_as_str = NULL; + PyObject *result = NULL; + PyObject *format_meth = NULL; + + if (!PyArg_ParseTuple(args, "U:__format__", &format_spec)) + return NULL; + + self_as_str = PyObject_Str(self); + if (self_as_str != NULL) { + /* find the format function */ + format_meth = PyObject_GetAttrString(self_as_str, "__format__"); + if (format_meth != NULL) { + /* and call it */ + result = PyObject_CallFunctionObjArgs(format_meth, format_spec, NULL); } + } - Py_XDECREF(self_as_str); - Py_XDECREF(format_meth); + Py_XDECREF(self_as_str); + Py_XDECREF(format_meth); - return result; + return result; } static PyObject * object_sizeof(PyObject *self, PyObject *args) { - Py_ssize_t res, isize; + Py_ssize_t res, isize; - res = 0; - isize = self->ob_type->tp_itemsize; - if (isize > 0) - res = Py_SIZE(self->ob_type) * isize; - res += self->ob_type->tp_basicsize; + res = 0; + isize = self->ob_type->tp_itemsize; + if (isize > 0) + res = Py_SIZE(self->ob_type) * isize; + res += self->ob_type->tp_basicsize; - return PyLong_FromSsize_t(res); + return PyLong_FromSsize_t(res); } static PyMethodDef object_methods[] = { - {"__reduce_ex__", object_reduce_ex, METH_VARARGS, - PyDoc_STR("helper for pickle")}, - {"__reduce__", object_reduce, METH_VARARGS, - PyDoc_STR("helper for pickle")}, - {"__subclasshook__", object_subclasshook, METH_CLASS | METH_VARARGS, - object_subclasshook_doc}, - {"__format__", object_format, METH_VARARGS, - PyDoc_STR("default object formatter")}, - {"__sizeof__", object_sizeof, METH_NOARGS, - PyDoc_STR("__sizeof__() -> size of object in memory, in bytes")}, - {0} + {"__reduce_ex__", object_reduce_ex, METH_VARARGS, + PyDoc_STR("helper for pickle")}, + {"__reduce__", object_reduce, METH_VARARGS, + PyDoc_STR("helper for pickle")}, + {"__subclasshook__", object_subclasshook, METH_CLASS | METH_VARARGS, + object_subclasshook_doc}, + {"__format__", object_format, METH_VARARGS, + PyDoc_STR("default object formatter")}, + {"__sizeof__", object_sizeof, METH_NOARGS, + PyDoc_STR("__sizeof__() -> size of object in memory, in bytes")}, + {0} }; PyTypeObject PyBaseObject_Type = { - PyVarObject_HEAD_INIT(&PyType_Type, 0) - "object", /* tp_name */ - sizeof(PyObject), /* tp_basicsize */ - 0, /* tp_itemsize */ - object_dealloc, /* tp_dealloc */ - 0, /* tp_print */ - 0, /* tp_getattr */ - 0, /* tp_setattr */ - 0, /* tp_reserved */ - object_repr, /* tp_repr */ - 0, /* tp_as_number */ - 0, /* tp_as_sequence */ - 0, /* tp_as_mapping */ - (hashfunc)_Py_HashPointer, /* tp_hash */ - 0, /* tp_call */ - object_str, /* tp_str */ - PyObject_GenericGetAttr, /* tp_getattro */ - PyObject_GenericSetAttr, /* tp_setattro */ - 0, /* tp_as_buffer */ - Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */ - PyDoc_STR("The most base type"), /* tp_doc */ - 0, /* tp_traverse */ - 0, /* tp_clear */ - object_richcompare, /* tp_richcompare */ - 0, /* tp_weaklistoffset */ - 0, /* tp_iter */ - 0, /* tp_iternext */ - object_methods, /* tp_methods */ - 0, /* tp_members */ - object_getsets, /* tp_getset */ - 0, /* tp_base */ - 0, /* tp_dict */ - 0, /* tp_descr_get */ - 0, /* tp_descr_set */ - 0, /* tp_dictoffset */ - object_init, /* tp_init */ - PyType_GenericAlloc, /* tp_alloc */ - object_new, /* tp_new */ - PyObject_Del, /* tp_free */ + PyVarObject_HEAD_INIT(&PyType_Type, 0) + "object", /* tp_name */ + sizeof(PyObject), /* tp_basicsize */ + 0, /* tp_itemsize */ + object_dealloc, /* tp_dealloc */ + 0, /* tp_print */ + 0, /* tp_getattr */ + 0, /* tp_setattr */ + 0, /* tp_reserved */ + object_repr, /* tp_repr */ + 0, /* tp_as_number */ + 0, /* tp_as_sequence */ + 0, /* tp_as_mapping */ + (hashfunc)_Py_HashPointer, /* tp_hash */ + 0, /* tp_call */ + object_str, /* tp_str */ + PyObject_GenericGetAttr, /* tp_getattro */ + PyObject_GenericSetAttr, /* tp_setattro */ + 0, /* tp_as_buffer */ + Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */ + PyDoc_STR("The most base type"), /* tp_doc */ + 0, /* tp_traverse */ + 0, /* tp_clear */ + object_richcompare, /* tp_richcompare */ + 0, /* tp_weaklistoffset */ + 0, /* tp_iter */ + 0, /* tp_iternext */ + object_methods, /* tp_methods */ + 0, /* tp_members */ + object_getsets, /* tp_getset */ + 0, /* tp_base */ + 0, /* tp_dict */ + 0, /* tp_descr_get */ + 0, /* tp_descr_set */ + 0, /* tp_dictoffset */ + object_init, /* tp_init */ + PyType_GenericAlloc, /* tp_alloc */ + object_new, /* tp_new */ + PyObject_Del, /* tp_free */ }; @@ -3398,168 +3398,168 @@ static int add_methods(PyTypeObject *type, PyMethodDef *meth) { - PyObject *dict = type->tp_dict; + PyObject *dict = type->tp_dict; - for (; meth->ml_name != NULL; meth++) { - PyObject *descr; - if (PyDict_GetItemString(dict, meth->ml_name) && - !(meth->ml_flags & METH_COEXIST)) - continue; - if (meth->ml_flags & METH_CLASS) { - if (meth->ml_flags & METH_STATIC) { - PyErr_SetString(PyExc_ValueError, - "method cannot be both class and static"); - return -1; - } - descr = PyDescr_NewClassMethod(type, meth); - } - else if (meth->ml_flags & METH_STATIC) { - PyObject *cfunc = PyCFunction_New(meth, NULL); - if (cfunc == NULL) - return -1; - descr = PyStaticMethod_New(cfunc); - Py_DECREF(cfunc); - } - else { - descr = PyDescr_NewMethod(type, meth); - } - if (descr == NULL) - return -1; - if (PyDict_SetItemString(dict, meth->ml_name, descr) < 0) - return -1; - Py_DECREF(descr); - } - return 0; + for (; meth->ml_name != NULL; meth++) { + PyObject *descr; + if (PyDict_GetItemString(dict, meth->ml_name) && + !(meth->ml_flags & METH_COEXIST)) + continue; + if (meth->ml_flags & METH_CLASS) { + if (meth->ml_flags & METH_STATIC) { + PyErr_SetString(PyExc_ValueError, + "method cannot be both class and static"); + return -1; + } + descr = PyDescr_NewClassMethod(type, meth); + } + else if (meth->ml_flags & METH_STATIC) { + PyObject *cfunc = PyCFunction_New(meth, NULL); + if (cfunc == NULL) + return -1; + descr = PyStaticMethod_New(cfunc); + Py_DECREF(cfunc); + } + else { + descr = PyDescr_NewMethod(type, meth); + } + if (descr == NULL) + return -1; + if (PyDict_SetItemString(dict, meth->ml_name, descr) < 0) + return -1; + Py_DECREF(descr); + } + return 0; } static int add_members(PyTypeObject *type, PyMemberDef *memb) { - PyObject *dict = type->tp_dict; + PyObject *dict = type->tp_dict; - for (; memb->name != NULL; memb++) { - PyObject *descr; - if (PyDict_GetItemString(dict, memb->name)) - continue; - descr = PyDescr_NewMember(type, memb); - if (descr == NULL) - return -1; - if (PyDict_SetItemString(dict, memb->name, descr) < 0) - return -1; - Py_DECREF(descr); - } - return 0; + for (; memb->name != NULL; memb++) { + PyObject *descr; + if (PyDict_GetItemString(dict, memb->name)) + continue; + descr = PyDescr_NewMember(type, memb); + if (descr == NULL) + return -1; + if (PyDict_SetItemString(dict, memb->name, descr) < 0) + return -1; + Py_DECREF(descr); + } + return 0; } static int add_getset(PyTypeObject *type, PyGetSetDef *gsp) { - PyObject *dict = type->tp_dict; + PyObject *dict = type->tp_dict; - for (; gsp->name != NULL; gsp++) { - PyObject *descr; - if (PyDict_GetItemString(dict, gsp->name)) - continue; - descr = PyDescr_NewGetSet(type, gsp); - - if (descr == NULL) - return -1; - if (PyDict_SetItemString(dict, gsp->name, descr) < 0) - return -1; - Py_DECREF(descr); - } - return 0; + for (; gsp->name != NULL; gsp++) { + PyObject *descr; + if (PyDict_GetItemString(dict, gsp->name)) + continue; + descr = PyDescr_NewGetSet(type, gsp); + + if (descr == NULL) + return -1; + if (PyDict_SetItemString(dict, gsp->name, descr) < 0) + return -1; + Py_DECREF(descr); + } + return 0; } static void inherit_special(PyTypeObject *type, PyTypeObject *base) { - Py_ssize_t oldsize, newsize; + Py_ssize_t oldsize, newsize; - /* Copying basicsize is connected to the GC flags */ - oldsize = base->tp_basicsize; - newsize = type->tp_basicsize ? type->tp_basicsize : oldsize; - if (!(type->tp_flags & Py_TPFLAGS_HAVE_GC) && - (base->tp_flags & Py_TPFLAGS_HAVE_GC) && - (!type->tp_traverse && !type->tp_clear)) { - type->tp_flags |= Py_TPFLAGS_HAVE_GC; - if (type->tp_traverse == NULL) - type->tp_traverse = base->tp_traverse; - if (type->tp_clear == NULL) - type->tp_clear = base->tp_clear; - } - { - /* The condition below could use some explanation. - It appears that tp_new is not inherited for static types - whose base class is 'object'; this seems to be a precaution - so that old extension types don't suddenly become - callable (object.__new__ wouldn't insure the invariants - that the extension type's own factory function ensures). - Heap types, of course, are under our control, so they do - inherit tp_new; static extension types that specify some - other built-in type as the default are considered - new-style-aware so they also inherit object.__new__. */ - if (base != &PyBaseObject_Type || - (type->tp_flags & Py_TPFLAGS_HEAPTYPE)) { - if (type->tp_new == NULL) - type->tp_new = base->tp_new; - } - } - type->tp_basicsize = newsize; + /* Copying basicsize is connected to the GC flags */ + oldsize = base->tp_basicsize; + newsize = type->tp_basicsize ? type->tp_basicsize : oldsize; + if (!(type->tp_flags & Py_TPFLAGS_HAVE_GC) && + (base->tp_flags & Py_TPFLAGS_HAVE_GC) && + (!type->tp_traverse && !type->tp_clear)) { + type->tp_flags |= Py_TPFLAGS_HAVE_GC; + if (type->tp_traverse == NULL) + type->tp_traverse = base->tp_traverse; + if (type->tp_clear == NULL) + type->tp_clear = base->tp_clear; + } + { + /* The condition below could use some explanation. + It appears that tp_new is not inherited for static types + whose base class is 'object'; this seems to be a precaution + so that old extension types don't suddenly become + callable (object.__new__ wouldn't insure the invariants + that the extension type's own factory function ensures). + Heap types, of course, are under our control, so they do + inherit tp_new; static extension types that specify some + other built-in type as the default are considered + new-style-aware so they also inherit object.__new__. */ + if (base != &PyBaseObject_Type || + (type->tp_flags & Py_TPFLAGS_HEAPTYPE)) { + if (type->tp_new == NULL) + type->tp_new = base->tp_new; + } + } + type->tp_basicsize = newsize; - /* Copy other non-function slots */ + /* Copy other non-function slots */ #undef COPYVAL #define COPYVAL(SLOT) \ - if (type->SLOT == 0) type->SLOT = base->SLOT + if (type->SLOT == 0) type->SLOT = base->SLOT - COPYVAL(tp_itemsize); - COPYVAL(tp_weaklistoffset); - COPYVAL(tp_dictoffset); - - /* Setup fast subclass flags */ - if (PyType_IsSubtype(base, (PyTypeObject*)PyExc_BaseException)) - type->tp_flags |= Py_TPFLAGS_BASE_EXC_SUBCLASS; - else if (PyType_IsSubtype(base, &PyType_Type)) - type->tp_flags |= Py_TPFLAGS_TYPE_SUBCLASS; - else if (PyType_IsSubtype(base, &PyLong_Type)) - type->tp_flags |= Py_TPFLAGS_LONG_SUBCLASS; - else if (PyType_IsSubtype(base, &PyBytes_Type)) - type->tp_flags |= Py_TPFLAGS_BYTES_SUBCLASS; - else if (PyType_IsSubtype(base, &PyUnicode_Type)) - type->tp_flags |= Py_TPFLAGS_UNICODE_SUBCLASS; - else if (PyType_IsSubtype(base, &PyTuple_Type)) - type->tp_flags |= Py_TPFLAGS_TUPLE_SUBCLASS; - else if (PyType_IsSubtype(base, &PyList_Type)) - type->tp_flags |= Py_TPFLAGS_LIST_SUBCLASS; - else if (PyType_IsSubtype(base, &PyDict_Type)) - type->tp_flags |= Py_TPFLAGS_DICT_SUBCLASS; + COPYVAL(tp_itemsize); + COPYVAL(tp_weaklistoffset); + COPYVAL(tp_dictoffset); + + /* Setup fast subclass flags */ + if (PyType_IsSubtype(base, (PyTypeObject*)PyExc_BaseException)) + type->tp_flags |= Py_TPFLAGS_BASE_EXC_SUBCLASS; + else if (PyType_IsSubtype(base, &PyType_Type)) + type->tp_flags |= Py_TPFLAGS_TYPE_SUBCLASS; + else if (PyType_IsSubtype(base, &PyLong_Type)) + type->tp_flags |= Py_TPFLAGS_LONG_SUBCLASS; + else if (PyType_IsSubtype(base, &PyBytes_Type)) + type->tp_flags |= Py_TPFLAGS_BYTES_SUBCLASS; + else if (PyType_IsSubtype(base, &PyUnicode_Type)) + type->tp_flags |= Py_TPFLAGS_UNICODE_SUBCLASS; + else if (PyType_IsSubtype(base, &PyTuple_Type)) + type->tp_flags |= Py_TPFLAGS_TUPLE_SUBCLASS; + else if (PyType_IsSubtype(base, &PyList_Type)) + type->tp_flags |= Py_TPFLAGS_LIST_SUBCLASS; + else if (PyType_IsSubtype(base, &PyDict_Type)) + type->tp_flags |= Py_TPFLAGS_DICT_SUBCLASS; } static char *hash_name_op[] = { - "__eq__", - "__hash__", - NULL + "__eq__", + "__hash__", + NULL }; static int overrides_hash(PyTypeObject *type) { - char **p; - PyObject *dict = type->tp_dict; + char **p; + PyObject *dict = type->tp_dict; - assert(dict != NULL); - for (p = hash_name_op; *p; p++) { - if (PyDict_GetItemString(dict, *p) != NULL) - return 1; - } - return 0; + assert(dict != NULL); + for (p = hash_name_op; *p; p++) { + if (PyDict_GetItemString(dict, *p) != NULL) + return 1; + } + return 0; } static void inherit_slots(PyTypeObject *type, PyTypeObject *base) { - PyTypeObject *basebase; + PyTypeObject *basebase; #undef SLOTDEFINED #undef COPYSLOT @@ -3569,147 +3569,147 @@ #undef COPYBUF #define SLOTDEFINED(SLOT) \ - (base->SLOT != 0 && \ - (basebase == NULL || base->SLOT != basebase->SLOT)) + (base->SLOT != 0 && \ + (basebase == NULL || base->SLOT != basebase->SLOT)) #define COPYSLOT(SLOT) \ - if (!type->SLOT && SLOTDEFINED(SLOT)) type->SLOT = base->SLOT + if (!type->SLOT && SLOTDEFINED(SLOT)) type->SLOT = base->SLOT #define COPYNUM(SLOT) COPYSLOT(tp_as_number->SLOT) #define COPYSEQ(SLOT) COPYSLOT(tp_as_sequence->SLOT) #define COPYMAP(SLOT) COPYSLOT(tp_as_mapping->SLOT) #define COPYBUF(SLOT) COPYSLOT(tp_as_buffer->SLOT) - /* This won't inherit indirect slots (from tp_as_number etc.) - if type doesn't provide the space. */ + /* This won't inherit indirect slots (from tp_as_number etc.) + if type doesn't provide the space. */ - if (type->tp_as_number != NULL && base->tp_as_number != NULL) { - basebase = base->tp_base; - if (basebase->tp_as_number == NULL) - basebase = NULL; - COPYNUM(nb_add); - COPYNUM(nb_subtract); - COPYNUM(nb_multiply); - COPYNUM(nb_remainder); - COPYNUM(nb_divmod); - COPYNUM(nb_power); - COPYNUM(nb_negative); - COPYNUM(nb_positive); - COPYNUM(nb_absolute); - COPYNUM(nb_bool); - COPYNUM(nb_invert); - COPYNUM(nb_lshift); - COPYNUM(nb_rshift); - COPYNUM(nb_and); - COPYNUM(nb_xor); - COPYNUM(nb_or); - COPYNUM(nb_int); - COPYNUM(nb_float); - COPYNUM(nb_inplace_add); - COPYNUM(nb_inplace_subtract); - COPYNUM(nb_inplace_multiply); - COPYNUM(nb_inplace_remainder); - COPYNUM(nb_inplace_power); - COPYNUM(nb_inplace_lshift); - COPYNUM(nb_inplace_rshift); - COPYNUM(nb_inplace_and); - COPYNUM(nb_inplace_xor); - COPYNUM(nb_inplace_or); - COPYNUM(nb_true_divide); - COPYNUM(nb_floor_divide); - COPYNUM(nb_inplace_true_divide); - COPYNUM(nb_inplace_floor_divide); - COPYNUM(nb_index); - } - - if (type->tp_as_sequence != NULL && base->tp_as_sequence != NULL) { - basebase = base->tp_base; - if (basebase->tp_as_sequence == NULL) - basebase = NULL; - COPYSEQ(sq_length); - COPYSEQ(sq_concat); - COPYSEQ(sq_repeat); - COPYSEQ(sq_item); - COPYSEQ(sq_ass_item); - COPYSEQ(sq_contains); - COPYSEQ(sq_inplace_concat); - COPYSEQ(sq_inplace_repeat); - } - - if (type->tp_as_mapping != NULL && base->tp_as_mapping != NULL) { - basebase = base->tp_base; - if (basebase->tp_as_mapping == NULL) - basebase = NULL; - COPYMAP(mp_length); - COPYMAP(mp_subscript); - COPYMAP(mp_ass_subscript); - } - - if (type->tp_as_buffer != NULL && base->tp_as_buffer != NULL) { - basebase = base->tp_base; - if (basebase->tp_as_buffer == NULL) - basebase = NULL; - COPYBUF(bf_getbuffer); - COPYBUF(bf_releasebuffer); - } - - basebase = base->tp_base; - - COPYSLOT(tp_dealloc); - if (type->tp_getattr == NULL && type->tp_getattro == NULL) { - type->tp_getattr = base->tp_getattr; - type->tp_getattro = base->tp_getattro; - } - if (type->tp_setattr == NULL && type->tp_setattro == NULL) { - type->tp_setattr = base->tp_setattr; - type->tp_setattro = base->tp_setattro; - } - /* tp_reserved is ignored */ - COPYSLOT(tp_repr); - /* tp_hash see tp_richcompare */ - COPYSLOT(tp_call); - COPYSLOT(tp_str); - { - /* Copy comparison-related slots only when - not overriding them anywhere */ - if (type->tp_richcompare == NULL && - type->tp_hash == NULL && - !overrides_hash(type)) - { - type->tp_richcompare = base->tp_richcompare; - type->tp_hash = base->tp_hash; - } - } - { - COPYSLOT(tp_iter); - COPYSLOT(tp_iternext); - } - { - COPYSLOT(tp_descr_get); - COPYSLOT(tp_descr_set); - COPYSLOT(tp_dictoffset); - COPYSLOT(tp_init); - COPYSLOT(tp_alloc); - COPYSLOT(tp_is_gc); - if ((type->tp_flags & Py_TPFLAGS_HAVE_GC) == - (base->tp_flags & Py_TPFLAGS_HAVE_GC)) { - /* They agree about gc. */ - COPYSLOT(tp_free); - } - else if ((type->tp_flags & Py_TPFLAGS_HAVE_GC) && - type->tp_free == NULL && - base->tp_free == PyObject_Free) { - /* A bit of magic to plug in the correct default - * tp_free function when a derived class adds gc, - * didn't define tp_free, and the base uses the - * default non-gc tp_free. - */ - type->tp_free = PyObject_GC_Del; - } - /* else they didn't agree about gc, and there isn't something - * obvious to be done -- the type is on its own. - */ - } + if (type->tp_as_number != NULL && base->tp_as_number != NULL) { + basebase = base->tp_base; + if (basebase->tp_as_number == NULL) + basebase = NULL; + COPYNUM(nb_add); + COPYNUM(nb_subtract); + COPYNUM(nb_multiply); + COPYNUM(nb_remainder); + COPYNUM(nb_divmod); + COPYNUM(nb_power); + COPYNUM(nb_negative); + COPYNUM(nb_positive); + COPYNUM(nb_absolute); + COPYNUM(nb_bool); + COPYNUM(nb_invert); + COPYNUM(nb_lshift); + COPYNUM(nb_rshift); + COPYNUM(nb_and); + COPYNUM(nb_xor); + COPYNUM(nb_or); + COPYNUM(nb_int); + COPYNUM(nb_float); + COPYNUM(nb_inplace_add); + COPYNUM(nb_inplace_subtract); + COPYNUM(nb_inplace_multiply); + COPYNUM(nb_inplace_remainder); + COPYNUM(nb_inplace_power); + COPYNUM(nb_inplace_lshift); + COPYNUM(nb_inplace_rshift); + COPYNUM(nb_inplace_and); + COPYNUM(nb_inplace_xor); + COPYNUM(nb_inplace_or); + COPYNUM(nb_true_divide); + COPYNUM(nb_floor_divide); + COPYNUM(nb_inplace_true_divide); + COPYNUM(nb_inplace_floor_divide); + COPYNUM(nb_index); + } + + if (type->tp_as_sequence != NULL && base->tp_as_sequence != NULL) { + basebase = base->tp_base; + if (basebase->tp_as_sequence == NULL) + basebase = NULL; + COPYSEQ(sq_length); + COPYSEQ(sq_concat); + COPYSEQ(sq_repeat); + COPYSEQ(sq_item); + COPYSEQ(sq_ass_item); + COPYSEQ(sq_contains); + COPYSEQ(sq_inplace_concat); + COPYSEQ(sq_inplace_repeat); + } + + if (type->tp_as_mapping != NULL && base->tp_as_mapping != NULL) { + basebase = base->tp_base; + if (basebase->tp_as_mapping == NULL) + basebase = NULL; + COPYMAP(mp_length); + COPYMAP(mp_subscript); + COPYMAP(mp_ass_subscript); + } + + if (type->tp_as_buffer != NULL && base->tp_as_buffer != NULL) { + basebase = base->tp_base; + if (basebase->tp_as_buffer == NULL) + basebase = NULL; + COPYBUF(bf_getbuffer); + COPYBUF(bf_releasebuffer); + } + + basebase = base->tp_base; + + COPYSLOT(tp_dealloc); + if (type->tp_getattr == NULL && type->tp_getattro == NULL) { + type->tp_getattr = base->tp_getattr; + type->tp_getattro = base->tp_getattro; + } + if (type->tp_setattr == NULL && type->tp_setattro == NULL) { + type->tp_setattr = base->tp_setattr; + type->tp_setattro = base->tp_setattro; + } + /* tp_reserved is ignored */ + COPYSLOT(tp_repr); + /* tp_hash see tp_richcompare */ + COPYSLOT(tp_call); + COPYSLOT(tp_str); + { + /* Copy comparison-related slots only when + not overriding them anywhere */ + if (type->tp_richcompare == NULL && + type->tp_hash == NULL && + !overrides_hash(type)) + { + type->tp_richcompare = base->tp_richcompare; + type->tp_hash = base->tp_hash; + } + } + { + COPYSLOT(tp_iter); + COPYSLOT(tp_iternext); + } + { + COPYSLOT(tp_descr_get); + COPYSLOT(tp_descr_set); + COPYSLOT(tp_dictoffset); + COPYSLOT(tp_init); + COPYSLOT(tp_alloc); + COPYSLOT(tp_is_gc); + if ((type->tp_flags & Py_TPFLAGS_HAVE_GC) == + (base->tp_flags & Py_TPFLAGS_HAVE_GC)) { + /* They agree about gc. */ + COPYSLOT(tp_free); + } + else if ((type->tp_flags & Py_TPFLAGS_HAVE_GC) && + type->tp_free == NULL && + base->tp_free == PyObject_Free) { + /* A bit of magic to plug in the correct default + * tp_free function when a derived class adds gc, + * didn't define tp_free, and the base uses the + * default non-gc tp_free. + */ + type->tp_free = PyObject_GC_Del; + } + /* else they didn't agree about gc, and there isn't something + * obvious to be done -- the type is on its own. + */ + } } static int add_operators(PyTypeObject *); @@ -3717,273 +3717,273 @@ int PyType_Ready(PyTypeObject *type) { - PyObject *dict, *bases; - PyTypeObject *base; - Py_ssize_t i, n; - - if (type->tp_flags & Py_TPFLAGS_READY) { - assert(type->tp_dict != NULL); - return 0; - } - assert((type->tp_flags & Py_TPFLAGS_READYING) == 0); + PyObject *dict, *bases; + PyTypeObject *base; + Py_ssize_t i, n; + + if (type->tp_flags & Py_TPFLAGS_READY) { + assert(type->tp_dict != NULL); + return 0; + } + assert((type->tp_flags & Py_TPFLAGS_READYING) == 0); - type->tp_flags |= Py_TPFLAGS_READYING; + type->tp_flags |= Py_TPFLAGS_READYING; #ifdef Py_TRACE_REFS - /* PyType_Ready is the closest thing we have to a choke point - * for type objects, so is the best place I can think of to try - * to get type objects into the doubly-linked list of all objects. - * Still, not all type objects go thru PyType_Ready. - */ - _Py_AddToAllObjects((PyObject *)type, 0); + /* PyType_Ready is the closest thing we have to a choke point + * for type objects, so is the best place I can think of to try + * to get type objects into the doubly-linked list of all objects. + * Still, not all type objects go thru PyType_Ready. + */ + _Py_AddToAllObjects((PyObject *)type, 0); #endif - /* Initialize tp_base (defaults to BaseObject unless that's us) */ - base = type->tp_base; - if (base == NULL && type != &PyBaseObject_Type) { - base = type->tp_base = &PyBaseObject_Type; - Py_INCREF(base); - } - - /* Now the only way base can still be NULL is if type is - * &PyBaseObject_Type. - */ - - /* Initialize the base class */ - if (base != NULL && base->tp_dict == NULL) { - if (PyType_Ready(base) < 0) - goto error; - } - - /* Initialize ob_type if NULL. This means extensions that want to be - compilable separately on Windows can call PyType_Ready() instead of - initializing the ob_type field of their type objects. */ - /* The test for base != NULL is really unnecessary, since base is only - NULL when type is &PyBaseObject_Type, and we know its ob_type is - not NULL (it's initialized to &PyType_Type). But coverity doesn't - know that. */ - if (Py_TYPE(type) == NULL && base != NULL) - Py_TYPE(type) = Py_TYPE(base); - - /* Initialize tp_bases */ - bases = type->tp_bases; - if (bases == NULL) { - if (base == NULL) - bases = PyTuple_New(0); - else - bases = PyTuple_Pack(1, base); - if (bases == NULL) - goto error; - type->tp_bases = bases; - } - - /* Initialize tp_dict */ - dict = type->tp_dict; - if (dict == NULL) { - dict = PyDict_New(); - if (dict == NULL) - goto error; - type->tp_dict = dict; - } - - /* Add type-specific descriptors to tp_dict */ - if (add_operators(type) < 0) - goto error; - if (type->tp_methods != NULL) { - if (add_methods(type, type->tp_methods) < 0) - goto error; - } - if (type->tp_members != NULL) { - if (add_members(type, type->tp_members) < 0) - goto error; - } - if (type->tp_getset != NULL) { - if (add_getset(type, type->tp_getset) < 0) - goto error; - } - - /* Calculate method resolution order */ - if (mro_internal(type) < 0) { - goto error; - } - - /* Inherit special flags from dominant base */ - if (type->tp_base != NULL) - inherit_special(type, type->tp_base); - - /* Initialize tp_dict properly */ - bases = type->tp_mro; - assert(bases != NULL); - assert(PyTuple_Check(bases)); - n = PyTuple_GET_SIZE(bases); - for (i = 1; i < n; i++) { - PyObject *b = PyTuple_GET_ITEM(bases, i); - if (PyType_Check(b)) - inherit_slots(type, (PyTypeObject *)b); - } - - /* Sanity check for tp_free. */ - if (PyType_IS_GC(type) && (type->tp_flags & Py_TPFLAGS_BASETYPE) && - (type->tp_free == NULL || type->tp_free == PyObject_Del)) { - /* This base class needs to call tp_free, but doesn't have - * one, or its tp_free is for non-gc'ed objects. - */ - PyErr_Format(PyExc_TypeError, "type '%.100s' participates in " - "gc and is a base type but has inappropriate " - "tp_free slot", - type->tp_name); - goto error; - } - - /* if the type dictionary doesn't contain a __doc__, set it from - the tp_doc slot. - */ - if (PyDict_GetItemString(type->tp_dict, "__doc__") == NULL) { - if (type->tp_doc != NULL) { - PyObject *doc = PyUnicode_FromString(type->tp_doc); - if (doc == NULL) - goto error; - PyDict_SetItemString(type->tp_dict, "__doc__", doc); - Py_DECREF(doc); - } else { - PyDict_SetItemString(type->tp_dict, - "__doc__", Py_None); - } - } - - /* Hack for tp_hash and __hash__. - If after all that, tp_hash is still NULL, and __hash__ is not in - tp_dict, set tp_hash to PyObject_HashNotImplemented and - tp_dict['__hash__'] equal to None. - This signals that __hash__ is not inherited. - */ - if (type->tp_hash == NULL) { - if (PyDict_GetItemString(type->tp_dict, "__hash__") == NULL) { - if (PyDict_SetItemString(type->tp_dict, "__hash__", Py_None) < 0) - goto error; - type->tp_hash = PyObject_HashNotImplemented; - } - } - - /* Some more special stuff */ - base = type->tp_base; - if (base != NULL) { - if (type->tp_as_number == NULL) - type->tp_as_number = base->tp_as_number; - if (type->tp_as_sequence == NULL) - type->tp_as_sequence = base->tp_as_sequence; - if (type->tp_as_mapping == NULL) - type->tp_as_mapping = base->tp_as_mapping; - if (type->tp_as_buffer == NULL) - type->tp_as_buffer = base->tp_as_buffer; - } - - /* Link into each base class's list of subclasses */ - bases = type->tp_bases; - n = PyTuple_GET_SIZE(bases); - for (i = 0; i < n; i++) { - PyObject *b = PyTuple_GET_ITEM(bases, i); - if (PyType_Check(b) && - add_subclass((PyTypeObject *)b, type) < 0) - goto error; - } - - /* Warn for a type that implements tp_compare (now known as - tp_reserved) but not tp_richcompare. */ - if (type->tp_reserved && !type->tp_richcompare) { - int error; - char msg[240]; - PyOS_snprintf(msg, sizeof(msg), - "Type %.100s defines tp_reserved (formerly " - "tp_compare) but not tp_richcompare. " - "Comparisons may not behave as intended.", - type->tp_name); - error = PyErr_WarnEx(PyExc_DeprecationWarning, msg, 1); - if (error == -1) - goto error; - } - - /* All done -- set the ready flag */ - assert(type->tp_dict != NULL); - type->tp_flags = - (type->tp_flags & ~Py_TPFLAGS_READYING) | Py_TPFLAGS_READY; - return 0; + /* Initialize tp_base (defaults to BaseObject unless that's us) */ + base = type->tp_base; + if (base == NULL && type != &PyBaseObject_Type) { + base = type->tp_base = &PyBaseObject_Type; + Py_INCREF(base); + } + + /* Now the only way base can still be NULL is if type is + * &PyBaseObject_Type. + */ + + /* Initialize the base class */ + if (base != NULL && base->tp_dict == NULL) { + if (PyType_Ready(base) < 0) + goto error; + } + + /* Initialize ob_type if NULL. This means extensions that want to be + compilable separately on Windows can call PyType_Ready() instead of + initializing the ob_type field of their type objects. */ + /* The test for base != NULL is really unnecessary, since base is only + NULL when type is &PyBaseObject_Type, and we know its ob_type is + not NULL (it's initialized to &PyType_Type). But coverity doesn't + know that. */ + if (Py_TYPE(type) == NULL && base != NULL) + Py_TYPE(type) = Py_TYPE(base); + + /* Initialize tp_bases */ + bases = type->tp_bases; + if (bases == NULL) { + if (base == NULL) + bases = PyTuple_New(0); + else + bases = PyTuple_Pack(1, base); + if (bases == NULL) + goto error; + type->tp_bases = bases; + } + + /* Initialize tp_dict */ + dict = type->tp_dict; + if (dict == NULL) { + dict = PyDict_New(); + if (dict == NULL) + goto error; + type->tp_dict = dict; + } + + /* Add type-specific descriptors to tp_dict */ + if (add_operators(type) < 0) + goto error; + if (type->tp_methods != NULL) { + if (add_methods(type, type->tp_methods) < 0) + goto error; + } + if (type->tp_members != NULL) { + if (add_members(type, type->tp_members) < 0) + goto error; + } + if (type->tp_getset != NULL) { + if (add_getset(type, type->tp_getset) < 0) + goto error; + } + + /* Calculate method resolution order */ + if (mro_internal(type) < 0) { + goto error; + } + + /* Inherit special flags from dominant base */ + if (type->tp_base != NULL) + inherit_special(type, type->tp_base); + + /* Initialize tp_dict properly */ + bases = type->tp_mro; + assert(bases != NULL); + assert(PyTuple_Check(bases)); + n = PyTuple_GET_SIZE(bases); + for (i = 1; i < n; i++) { + PyObject *b = PyTuple_GET_ITEM(bases, i); + if (PyType_Check(b)) + inherit_slots(type, (PyTypeObject *)b); + } + + /* Sanity check for tp_free. */ + if (PyType_IS_GC(type) && (type->tp_flags & Py_TPFLAGS_BASETYPE) && + (type->tp_free == NULL || type->tp_free == PyObject_Del)) { + /* This base class needs to call tp_free, but doesn't have + * one, or its tp_free is for non-gc'ed objects. + */ + PyErr_Format(PyExc_TypeError, "type '%.100s' participates in " + "gc and is a base type but has inappropriate " + "tp_free slot", + type->tp_name); + goto error; + } + + /* if the type dictionary doesn't contain a __doc__, set it from + the tp_doc slot. + */ + if (PyDict_GetItemString(type->tp_dict, "__doc__") == NULL) { + if (type->tp_doc != NULL) { + PyObject *doc = PyUnicode_FromString(type->tp_doc); + if (doc == NULL) + goto error; + PyDict_SetItemString(type->tp_dict, "__doc__", doc); + Py_DECREF(doc); + } else { + PyDict_SetItemString(type->tp_dict, + "__doc__", Py_None); + } + } + + /* Hack for tp_hash and __hash__. + If after all that, tp_hash is still NULL, and __hash__ is not in + tp_dict, set tp_hash to PyObject_HashNotImplemented and + tp_dict['__hash__'] equal to None. + This signals that __hash__ is not inherited. + */ + if (type->tp_hash == NULL) { + if (PyDict_GetItemString(type->tp_dict, "__hash__") == NULL) { + if (PyDict_SetItemString(type->tp_dict, "__hash__", Py_None) < 0) + goto error; + type->tp_hash = PyObject_HashNotImplemented; + } + } + + /* Some more special stuff */ + base = type->tp_base; + if (base != NULL) { + if (type->tp_as_number == NULL) + type->tp_as_number = base->tp_as_number; + if (type->tp_as_sequence == NULL) + type->tp_as_sequence = base->tp_as_sequence; + if (type->tp_as_mapping == NULL) + type->tp_as_mapping = base->tp_as_mapping; + if (type->tp_as_buffer == NULL) + type->tp_as_buffer = base->tp_as_buffer; + } + + /* Link into each base class's list of subclasses */ + bases = type->tp_bases; + n = PyTuple_GET_SIZE(bases); + for (i = 0; i < n; i++) { + PyObject *b = PyTuple_GET_ITEM(bases, i); + if (PyType_Check(b) && + add_subclass((PyTypeObject *)b, type) < 0) + goto error; + } + + /* Warn for a type that implements tp_compare (now known as + tp_reserved) but not tp_richcompare. */ + if (type->tp_reserved && !type->tp_richcompare) { + int error; + char msg[240]; + PyOS_snprintf(msg, sizeof(msg), + "Type %.100s defines tp_reserved (formerly " + "tp_compare) but not tp_richcompare. " + "Comparisons may not behave as intended.", + type->tp_name); + error = PyErr_WarnEx(PyExc_DeprecationWarning, msg, 1); + if (error == -1) + goto error; + } + + /* All done -- set the ready flag */ + assert(type->tp_dict != NULL); + type->tp_flags = + (type->tp_flags & ~Py_TPFLAGS_READYING) | Py_TPFLAGS_READY; + return 0; error: - type->tp_flags &= ~Py_TPFLAGS_READYING; - return -1; + type->tp_flags &= ~Py_TPFLAGS_READYING; + return -1; } static int add_subclass(PyTypeObject *base, PyTypeObject *type) { - Py_ssize_t i; - int result; - PyObject *list, *ref, *newobj; - - list = base->tp_subclasses; - if (list == NULL) { - base->tp_subclasses = list = PyList_New(0); - if (list == NULL) - return -1; - } - assert(PyList_Check(list)); - newobj = PyWeakref_NewRef((PyObject *)type, NULL); - i = PyList_GET_SIZE(list); - while (--i >= 0) { - ref = PyList_GET_ITEM(list, i); - assert(PyWeakref_CheckRef(ref)); - if (PyWeakref_GET_OBJECT(ref) == Py_None) - return PyList_SetItem(list, i, newobj); - } - result = PyList_Append(list, newobj); - Py_DECREF(newobj); - return result; + Py_ssize_t i; + int result; + PyObject *list, *ref, *newobj; + + list = base->tp_subclasses; + if (list == NULL) { + base->tp_subclasses = list = PyList_New(0); + if (list == NULL) + return -1; + } + assert(PyList_Check(list)); + newobj = PyWeakref_NewRef((PyObject *)type, NULL); + i = PyList_GET_SIZE(list); + while (--i >= 0) { + ref = PyList_GET_ITEM(list, i); + assert(PyWeakref_CheckRef(ref)); + if (PyWeakref_GET_OBJECT(ref) == Py_None) + return PyList_SetItem(list, i, newobj); + } + result = PyList_Append(list, newobj); + Py_DECREF(newobj); + return result; } static void remove_subclass(PyTypeObject *base, PyTypeObject *type) { - Py_ssize_t i; - PyObject *list, *ref; + Py_ssize_t i; + PyObject *list, *ref; - list = base->tp_subclasses; - if (list == NULL) { - return; - } - assert(PyList_Check(list)); - i = PyList_GET_SIZE(list); - while (--i >= 0) { - ref = PyList_GET_ITEM(list, i); - assert(PyWeakref_CheckRef(ref)); - if (PyWeakref_GET_OBJECT(ref) == (PyObject*)type) { - /* this can't fail, right? */ - PySequence_DelItem(list, i); - return; - } - } + list = base->tp_subclasses; + if (list == NULL) { + return; + } + assert(PyList_Check(list)); + i = PyList_GET_SIZE(list); + while (--i >= 0) { + ref = PyList_GET_ITEM(list, i); + assert(PyWeakref_CheckRef(ref)); + if (PyWeakref_GET_OBJECT(ref) == (PyObject*)type) { + /* this can't fail, right? */ + PySequence_DelItem(list, i); + return; + } + } } static int check_num_args(PyObject *ob, int n) { - if (!PyTuple_CheckExact(ob)) { - PyErr_SetString(PyExc_SystemError, - "PyArg_UnpackTuple() argument list is not a tuple"); - return 0; - } - if (n == PyTuple_GET_SIZE(ob)) - return 1; - PyErr_Format( - PyExc_TypeError, - "expected %d arguments, got %zd", n, PyTuple_GET_SIZE(ob)); - return 0; + if (!PyTuple_CheckExact(ob)) { + PyErr_SetString(PyExc_SystemError, + "PyArg_UnpackTuple() argument list is not a tuple"); + return 0; + } + if (n == PyTuple_GET_SIZE(ob)) + return 1; + PyErr_Format( + PyExc_TypeError, + "expected %d arguments, got %zd", n, PyTuple_GET_SIZE(ob)); + return 0; } /* Generic wrappers for overloadable 'operators' such as __getitem__ */ /* There's a wrapper *function* for each distinct function typedef used - for type object slots (e.g. binaryfunc, ternaryfunc, etc.). There's a + for type object slots (e.g. binaryfunc, ternaryfunc, etc.). There's a wrapper *table* for each distinct operation (e.g. __len__, __add__). Most tables have only one entry; the tables for binary operators have two entries, one regular and one with reversed arguments. */ @@ -3991,253 +3991,253 @@ static PyObject * wrap_lenfunc(PyObject *self, PyObject *args, void *wrapped) { - lenfunc func = (lenfunc)wrapped; - Py_ssize_t res; + lenfunc func = (lenfunc)wrapped; + Py_ssize_t res; - if (!check_num_args(args, 0)) - return NULL; - res = (*func)(self); - if (res == -1 && PyErr_Occurred()) - return NULL; - return PyLong_FromLong((long)res); + if (!check_num_args(args, 0)) + return NULL; + res = (*func)(self); + if (res == -1 && PyErr_Occurred()) + return NULL; + return PyLong_FromLong((long)res); } static PyObject * wrap_inquirypred(PyObject *self, PyObject *args, void *wrapped) { - inquiry func = (inquiry)wrapped; - int res; + inquiry func = (inquiry)wrapped; + int res; - if (!check_num_args(args, 0)) - return NULL; - res = (*func)(self); - if (res == -1 && PyErr_Occurred()) - return NULL; - return PyBool_FromLong((long)res); + if (!check_num_args(args, 0)) + return NULL; + res = (*func)(self); + if (res == -1 && PyErr_Occurred()) + return NULL; + return PyBool_FromLong((long)res); } static PyObject * wrap_binaryfunc(PyObject *self, PyObject *args, void *wrapped) { - binaryfunc func = (binaryfunc)wrapped; - PyObject *other; + binaryfunc func = (binaryfunc)wrapped; + PyObject *other; - if (!check_num_args(args, 1)) - return NULL; - other = PyTuple_GET_ITEM(args, 0); - return (*func)(self, other); + if (!check_num_args(args, 1)) + return NULL; + other = PyTuple_GET_ITEM(args, 0); + return (*func)(self, other); } static PyObject * wrap_binaryfunc_l(PyObject *self, PyObject *args, void *wrapped) { - binaryfunc func = (binaryfunc)wrapped; - PyObject *other; + binaryfunc func = (binaryfunc)wrapped; + PyObject *other; - if (!check_num_args(args, 1)) - return NULL; - other = PyTuple_GET_ITEM(args, 0); - return (*func)(self, other); + if (!check_num_args(args, 1)) + return NULL; + other = PyTuple_GET_ITEM(args, 0); + return (*func)(self, other); } static PyObject * wrap_binaryfunc_r(PyObject *self, PyObject *args, void *wrapped) { - binaryfunc func = (binaryfunc)wrapped; - PyObject *other; + binaryfunc func = (binaryfunc)wrapped; + PyObject *other; - if (!check_num_args(args, 1)) - return NULL; - other = PyTuple_GET_ITEM(args, 0); - if (!PyType_IsSubtype(Py_TYPE(other), Py_TYPE(self))) { - Py_INCREF(Py_NotImplemented); - return Py_NotImplemented; - } - return (*func)(other, self); + if (!check_num_args(args, 1)) + return NULL; + other = PyTuple_GET_ITEM(args, 0); + if (!PyType_IsSubtype(Py_TYPE(other), Py_TYPE(self))) { + Py_INCREF(Py_NotImplemented); + return Py_NotImplemented; + } + return (*func)(other, self); } static PyObject * wrap_ternaryfunc(PyObject *self, PyObject *args, void *wrapped) { - ternaryfunc func = (ternaryfunc)wrapped; - PyObject *other; - PyObject *third = Py_None; - - /* Note: This wrapper only works for __pow__() */ - - if (!PyArg_UnpackTuple(args, "", 1, 2, &other, &third)) - return NULL; - return (*func)(self, other, third); + ternaryfunc func = (ternaryfunc)wrapped; + PyObject *other; + PyObject *third = Py_None; + + /* Note: This wrapper only works for __pow__() */ + + if (!PyArg_UnpackTuple(args, "", 1, 2, &other, &third)) + return NULL; + return (*func)(self, other, third); } static PyObject * wrap_ternaryfunc_r(PyObject *self, PyObject *args, void *wrapped) { - ternaryfunc func = (ternaryfunc)wrapped; - PyObject *other; - PyObject *third = Py_None; - - /* Note: This wrapper only works for __pow__() */ - - if (!PyArg_UnpackTuple(args, "", 1, 2, &other, &third)) - return NULL; - return (*func)(other, self, third); + ternaryfunc func = (ternaryfunc)wrapped; + PyObject *other; + PyObject *third = Py_None; + + /* Note: This wrapper only works for __pow__() */ + + if (!PyArg_UnpackTuple(args, "", 1, 2, &other, &third)) + return NULL; + return (*func)(other, self, third); } static PyObject * wrap_unaryfunc(PyObject *self, PyObject *args, void *wrapped) { - unaryfunc func = (unaryfunc)wrapped; + unaryfunc func = (unaryfunc)wrapped; - if (!check_num_args(args, 0)) - return NULL; - return (*func)(self); + if (!check_num_args(args, 0)) + return NULL; + return (*func)(self); } static PyObject * wrap_indexargfunc(PyObject *self, PyObject *args, void *wrapped) { - ssizeargfunc func = (ssizeargfunc)wrapped; - PyObject* o; - Py_ssize_t i; - - if (!PyArg_UnpackTuple(args, "", 1, 1, &o)) - return NULL; - i = PyNumber_AsSsize_t(o, PyExc_OverflowError); - if (i == -1 && PyErr_Occurred()) - return NULL; - return (*func)(self, i); + ssizeargfunc func = (ssizeargfunc)wrapped; + PyObject* o; + Py_ssize_t i; + + if (!PyArg_UnpackTuple(args, "", 1, 1, &o)) + return NULL; + i = PyNumber_AsSsize_t(o, PyExc_OverflowError); + if (i == -1 && PyErr_Occurred()) + return NULL; + return (*func)(self, i); } static Py_ssize_t getindex(PyObject *self, PyObject *arg) { - Py_ssize_t i; + Py_ssize_t i; - i = PyNumber_AsSsize_t(arg, PyExc_OverflowError); - if (i == -1 && PyErr_Occurred()) - return -1; - if (i < 0) { - PySequenceMethods *sq = Py_TYPE(self)->tp_as_sequence; - if (sq && sq->sq_length) { - Py_ssize_t n = (*sq->sq_length)(self); - if (n < 0) - return -1; - i += n; - } - } - return i; + i = PyNumber_AsSsize_t(arg, PyExc_OverflowError); + if (i == -1 && PyErr_Occurred()) + return -1; + if (i < 0) { + PySequenceMethods *sq = Py_TYPE(self)->tp_as_sequence; + if (sq && sq->sq_length) { + Py_ssize_t n = (*sq->sq_length)(self); + if (n < 0) + return -1; + i += n; + } + } + return i; } static PyObject * wrap_sq_item(PyObject *self, PyObject *args, void *wrapped) { - ssizeargfunc func = (ssizeargfunc)wrapped; - PyObject *arg; - Py_ssize_t i; - - if (PyTuple_GET_SIZE(args) == 1) { - arg = PyTuple_GET_ITEM(args, 0); - i = getindex(self, arg); - if (i == -1 && PyErr_Occurred()) - return NULL; - return (*func)(self, i); - } - check_num_args(args, 1); - assert(PyErr_Occurred()); - return NULL; + ssizeargfunc func = (ssizeargfunc)wrapped; + PyObject *arg; + Py_ssize_t i; + + if (PyTuple_GET_SIZE(args) == 1) { + arg = PyTuple_GET_ITEM(args, 0); + i = getindex(self, arg); + if (i == -1 && PyErr_Occurred()) + return NULL; + return (*func)(self, i); + } + check_num_args(args, 1); + assert(PyErr_Occurred()); + return NULL; } static PyObject * wrap_sq_setitem(PyObject *self, PyObject *args, void *wrapped) { - ssizeobjargproc func = (ssizeobjargproc)wrapped; - Py_ssize_t i; - int res; - PyObject *arg, *value; - - if (!PyArg_UnpackTuple(args, "", 2, 2, &arg, &value)) - return NULL; - i = getindex(self, arg); - if (i == -1 && PyErr_Occurred()) - return NULL; - res = (*func)(self, i, value); - if (res == -1 && PyErr_Occurred()) - return NULL; - Py_INCREF(Py_None); - return Py_None; + ssizeobjargproc func = (ssizeobjargproc)wrapped; + Py_ssize_t i; + int res; + PyObject *arg, *value; + + if (!PyArg_UnpackTuple(args, "", 2, 2, &arg, &value)) + return NULL; + i = getindex(self, arg); + if (i == -1 && PyErr_Occurred()) + return NULL; + res = (*func)(self, i, value); + if (res == -1 && PyErr_Occurred()) + return NULL; + Py_INCREF(Py_None); + return Py_None; } static PyObject * wrap_sq_delitem(PyObject *self, PyObject *args, void *wrapped) { - ssizeobjargproc func = (ssizeobjargproc)wrapped; - Py_ssize_t i; - int res; - PyObject *arg; - - if (!check_num_args(args, 1)) - return NULL; - arg = PyTuple_GET_ITEM(args, 0); - i = getindex(self, arg); - if (i == -1 && PyErr_Occurred()) - return NULL; - res = (*func)(self, i, NULL); - if (res == -1 && PyErr_Occurred()) - return NULL; - Py_INCREF(Py_None); - return Py_None; + ssizeobjargproc func = (ssizeobjargproc)wrapped; + Py_ssize_t i; + int res; + PyObject *arg; + + if (!check_num_args(args, 1)) + return NULL; + arg = PyTuple_GET_ITEM(args, 0); + i = getindex(self, arg); + if (i == -1 && PyErr_Occurred()) + return NULL; + res = (*func)(self, i, NULL); + if (res == -1 && PyErr_Occurred()) + return NULL; + Py_INCREF(Py_None); + return Py_None; } /* XXX objobjproc is a misnomer; should be objargpred */ static PyObject * wrap_objobjproc(PyObject *self, PyObject *args, void *wrapped) { - objobjproc func = (objobjproc)wrapped; - int res; - PyObject *value; - - if (!check_num_args(args, 1)) - return NULL; - value = PyTuple_GET_ITEM(args, 0); - res = (*func)(self, value); - if (res == -1 && PyErr_Occurred()) - return NULL; - else - return PyBool_FromLong(res); + objobjproc func = (objobjproc)wrapped; + int res; + PyObject *value; + + if (!check_num_args(args, 1)) + return NULL; + value = PyTuple_GET_ITEM(args, 0); + res = (*func)(self, value); + if (res == -1 && PyErr_Occurred()) + return NULL; + else + return PyBool_FromLong(res); } static PyObject * wrap_objobjargproc(PyObject *self, PyObject *args, void *wrapped) { - objobjargproc func = (objobjargproc)wrapped; - int res; - PyObject *key, *value; - - if (!PyArg_UnpackTuple(args, "", 2, 2, &key, &value)) - return NULL; - res = (*func)(self, key, value); - if (res == -1 && PyErr_Occurred()) - return NULL; - Py_INCREF(Py_None); - return Py_None; + objobjargproc func = (objobjargproc)wrapped; + int res; + PyObject *key, *value; + + if (!PyArg_UnpackTuple(args, "", 2, 2, &key, &value)) + return NULL; + res = (*func)(self, key, value); + if (res == -1 && PyErr_Occurred()) + return NULL; + Py_INCREF(Py_None); + return Py_None; } static PyObject * wrap_delitem(PyObject *self, PyObject *args, void *wrapped) { - objobjargproc func = (objobjargproc)wrapped; - int res; - PyObject *key; - - if (!check_num_args(args, 1)) - return NULL; - key = PyTuple_GET_ITEM(args, 0); - res = (*func)(self, key, NULL); - if (res == -1 && PyErr_Occurred()) - return NULL; - Py_INCREF(Py_None); - return Py_None; + objobjargproc func = (objobjargproc)wrapped; + int res; + PyObject *key; + + if (!check_num_args(args, 1)) + return NULL; + key = PyTuple_GET_ITEM(args, 0); + res = (*func)(self, key, NULL); + if (res == -1 && PyErr_Occurred()) + return NULL; + Py_INCREF(Py_None); + return Py_None; } /* Helper to check for object.__setattr__ or __delattr__ applied to a type. @@ -4245,90 +4245,90 @@ static int hackcheck(PyObject *self, setattrofunc func, char *what) { - PyTypeObject *type = Py_TYPE(self); - while (type && type->tp_flags & Py_TPFLAGS_HEAPTYPE) - type = type->tp_base; - /* If type is NULL now, this is a really weird type. - In the spirit of backwards compatibility (?), just shut up. */ - if (type && type->tp_setattro != func) { - PyErr_Format(PyExc_TypeError, - "can't apply this %s to %s object", - what, - type->tp_name); - return 0; - } - return 1; + PyTypeObject *type = Py_TYPE(self); + while (type && type->tp_flags & Py_TPFLAGS_HEAPTYPE) + type = type->tp_base; + /* If type is NULL now, this is a really weird type. + In the spirit of backwards compatibility (?), just shut up. */ + if (type && type->tp_setattro != func) { + PyErr_Format(PyExc_TypeError, + "can't apply this %s to %s object", + what, + type->tp_name); + return 0; + } + return 1; } static PyObject * wrap_setattr(PyObject *self, PyObject *args, void *wrapped) { - setattrofunc func = (setattrofunc)wrapped; - int res; - PyObject *name, *value; - - if (!PyArg_UnpackTuple(args, "", 2, 2, &name, &value)) - return NULL; - if (!hackcheck(self, func, "__setattr__")) - return NULL; - res = (*func)(self, name, value); - if (res < 0) - return NULL; - Py_INCREF(Py_None); - return Py_None; + setattrofunc func = (setattrofunc)wrapped; + int res; + PyObject *name, *value; + + if (!PyArg_UnpackTuple(args, "", 2, 2, &name, &value)) + return NULL; + if (!hackcheck(self, func, "__setattr__")) + return NULL; + res = (*func)(self, name, value); + if (res < 0) + return NULL; + Py_INCREF(Py_None); + return Py_None; } static PyObject * wrap_delattr(PyObject *self, PyObject *args, void *wrapped) { - setattrofunc func = (setattrofunc)wrapped; - int res; - PyObject *name; - - if (!check_num_args(args, 1)) - return NULL; - name = PyTuple_GET_ITEM(args, 0); - if (!hackcheck(self, func, "__delattr__")) - return NULL; - res = (*func)(self, name, NULL); - if (res < 0) - return NULL; - Py_INCREF(Py_None); - return Py_None; + setattrofunc func = (setattrofunc)wrapped; + int res; + PyObject *name; + + if (!check_num_args(args, 1)) + return NULL; + name = PyTuple_GET_ITEM(args, 0); + if (!hackcheck(self, func, "__delattr__")) + return NULL; + res = (*func)(self, name, NULL); + if (res < 0) + return NULL; + Py_INCREF(Py_None); + return Py_None; } static PyObject * wrap_hashfunc(PyObject *self, PyObject *args, void *wrapped) { - hashfunc func = (hashfunc)wrapped; - long res; + hashfunc func = (hashfunc)wrapped; + long res; - if (!check_num_args(args, 0)) - return NULL; - res = (*func)(self); - if (res == -1 && PyErr_Occurred()) - return NULL; - return PyLong_FromLong(res); + if (!check_num_args(args, 0)) + return NULL; + res = (*func)(self); + if (res == -1 && PyErr_Occurred()) + return NULL; + return PyLong_FromLong(res); } static PyObject * wrap_call(PyObject *self, PyObject *args, void *wrapped, PyObject *kwds) { - ternaryfunc func = (ternaryfunc)wrapped; + ternaryfunc func = (ternaryfunc)wrapped; - return (*func)(self, args, kwds); + return (*func)(self, args, kwds); } static PyObject * wrap_richcmpfunc(PyObject *self, PyObject *args, void *wrapped, int op) { - richcmpfunc func = (richcmpfunc)wrapped; - PyObject *other; + richcmpfunc func = (richcmpfunc)wrapped; + PyObject *other; - if (!check_num_args(args, 1)) - return NULL; - other = PyTuple_GET_ITEM(args, 0); - return (*func)(self, other, op); + if (!check_num_args(args, 1)) + return NULL; + other = PyTuple_GET_ITEM(args, 0); + return (*func)(self, other, op); } #undef RICHCMP_WRAPPER @@ -4336,7 +4336,7 @@ static PyObject * \ richcmp_##NAME(PyObject *self, PyObject *args, void *wrapped) \ { \ - return wrap_richcmpfunc(self, args, wrapped, OP); \ + return wrap_richcmpfunc(self, args, wrapped, OP); \ } RICHCMP_WRAPPER(lt, Py_LT) @@ -4349,164 +4349,164 @@ static PyObject * wrap_next(PyObject *self, PyObject *args, void *wrapped) { - unaryfunc func = (unaryfunc)wrapped; - PyObject *res; + unaryfunc func = (unaryfunc)wrapped; + PyObject *res; - if (!check_num_args(args, 0)) - return NULL; - res = (*func)(self); - if (res == NULL && !PyErr_Occurred()) - PyErr_SetNone(PyExc_StopIteration); - return res; + if (!check_num_args(args, 0)) + return NULL; + res = (*func)(self); + if (res == NULL && !PyErr_Occurred()) + PyErr_SetNone(PyExc_StopIteration); + return res; } static PyObject * wrap_descr_get(PyObject *self, PyObject *args, void *wrapped) { - descrgetfunc func = (descrgetfunc)wrapped; - PyObject *obj; - PyObject *type = NULL; - - if (!PyArg_UnpackTuple(args, "", 1, 2, &obj, &type)) - return NULL; - if (obj == Py_None) - obj = NULL; - if (type == Py_None) - type = NULL; - if (type == NULL &&obj == NULL) { - PyErr_SetString(PyExc_TypeError, - "__get__(None, None) is invalid"); - return NULL; - } - return (*func)(self, obj, type); + descrgetfunc func = (descrgetfunc)wrapped; + PyObject *obj; + PyObject *type = NULL; + + if (!PyArg_UnpackTuple(args, "", 1, 2, &obj, &type)) + return NULL; + if (obj == Py_None) + obj = NULL; + if (type == Py_None) + type = NULL; + if (type == NULL &&obj == NULL) { + PyErr_SetString(PyExc_TypeError, + "__get__(None, None) is invalid"); + return NULL; + } + return (*func)(self, obj, type); } static PyObject * wrap_descr_set(PyObject *self, PyObject *args, void *wrapped) { - descrsetfunc func = (descrsetfunc)wrapped; - PyObject *obj, *value; - int ret; - - if (!PyArg_UnpackTuple(args, "", 2, 2, &obj, &value)) - return NULL; - ret = (*func)(self, obj, value); - if (ret < 0) - return NULL; - Py_INCREF(Py_None); - return Py_None; + descrsetfunc func = (descrsetfunc)wrapped; + PyObject *obj, *value; + int ret; + + if (!PyArg_UnpackTuple(args, "", 2, 2, &obj, &value)) + return NULL; + ret = (*func)(self, obj, value); + if (ret < 0) + return NULL; + Py_INCREF(Py_None); + return Py_None; } static PyObject * wrap_descr_delete(PyObject *self, PyObject *args, void *wrapped) { - descrsetfunc func = (descrsetfunc)wrapped; - PyObject *obj; - int ret; - - if (!check_num_args(args, 1)) - return NULL; - obj = PyTuple_GET_ITEM(args, 0); - ret = (*func)(self, obj, NULL); - if (ret < 0) - return NULL; - Py_INCREF(Py_None); - return Py_None; + descrsetfunc func = (descrsetfunc)wrapped; + PyObject *obj; + int ret; + + if (!check_num_args(args, 1)) + return NULL; + obj = PyTuple_GET_ITEM(args, 0); + ret = (*func)(self, obj, NULL); + if (ret < 0) + return NULL; + Py_INCREF(Py_None); + return Py_None; } static PyObject * wrap_init(PyObject *self, PyObject *args, void *wrapped, PyObject *kwds) { - initproc func = (initproc)wrapped; + initproc func = (initproc)wrapped; - if (func(self, args, kwds) < 0) - return NULL; - Py_INCREF(Py_None); - return Py_None; + if (func(self, args, kwds) < 0) + return NULL; + Py_INCREF(Py_None); + return Py_None; } static PyObject * tp_new_wrapper(PyObject *self, PyObject *args, PyObject *kwds) { - PyTypeObject *type, *subtype, *staticbase; - PyObject *arg0, *res; + PyTypeObject *type, *subtype, *staticbase; + PyObject *arg0, *res; - if (self == NULL || !PyType_Check(self)) - Py_FatalError("__new__() called with non-type 'self'"); - type = (PyTypeObject *)self; - if (!PyTuple_Check(args) || PyTuple_GET_SIZE(args) < 1) { - PyErr_Format(PyExc_TypeError, - "%s.__new__(): not enough arguments", - type->tp_name); - return NULL; - } - arg0 = PyTuple_GET_ITEM(args, 0); - if (!PyType_Check(arg0)) { - PyErr_Format(PyExc_TypeError, - "%s.__new__(X): X is not a type object (%s)", - type->tp_name, - Py_TYPE(arg0)->tp_name); - return NULL; - } - subtype = (PyTypeObject *)arg0; - if (!PyType_IsSubtype(subtype, type)) { - PyErr_Format(PyExc_TypeError, - "%s.__new__(%s): %s is not a subtype of %s", - type->tp_name, - subtype->tp_name, - subtype->tp_name, - type->tp_name); - return NULL; - } - - /* Check that the use doesn't do something silly and unsafe like - object.__new__(dict). To do this, we check that the - most derived base that's not a heap type is this type. */ - staticbase = subtype; - while (staticbase && (staticbase->tp_flags & Py_TPFLAGS_HEAPTYPE)) - staticbase = staticbase->tp_base; - /* If staticbase is NULL now, it is a really weird type. - In the spirit of backwards compatibility (?), just shut up. */ - if (staticbase && staticbase->tp_new != type->tp_new) { - PyErr_Format(PyExc_TypeError, - "%s.__new__(%s) is not safe, use %s.__new__()", - type->tp_name, - subtype->tp_name, - staticbase == NULL ? "?" : staticbase->tp_name); - return NULL; - } - - args = PyTuple_GetSlice(args, 1, PyTuple_GET_SIZE(args)); - if (args == NULL) - return NULL; - res = type->tp_new(subtype, args, kwds); - Py_DECREF(args); - return res; + if (self == NULL || !PyType_Check(self)) + Py_FatalError("__new__() called with non-type 'self'"); + type = (PyTypeObject *)self; + if (!PyTuple_Check(args) || PyTuple_GET_SIZE(args) < 1) { + PyErr_Format(PyExc_TypeError, + "%s.__new__(): not enough arguments", + type->tp_name); + return NULL; + } + arg0 = PyTuple_GET_ITEM(args, 0); + if (!PyType_Check(arg0)) { + PyErr_Format(PyExc_TypeError, + "%s.__new__(X): X is not a type object (%s)", + type->tp_name, + Py_TYPE(arg0)->tp_name); + return NULL; + } + subtype = (PyTypeObject *)arg0; + if (!PyType_IsSubtype(subtype, type)) { + PyErr_Format(PyExc_TypeError, + "%s.__new__(%s): %s is not a subtype of %s", + type->tp_name, + subtype->tp_name, + subtype->tp_name, + type->tp_name); + return NULL; + } + + /* Check that the use doesn't do something silly and unsafe like + object.__new__(dict). To do this, we check that the + most derived base that's not a heap type is this type. */ + staticbase = subtype; + while (staticbase && (staticbase->tp_flags & Py_TPFLAGS_HEAPTYPE)) + staticbase = staticbase->tp_base; + /* If staticbase is NULL now, it is a really weird type. + In the spirit of backwards compatibility (?), just shut up. */ + if (staticbase && staticbase->tp_new != type->tp_new) { + PyErr_Format(PyExc_TypeError, + "%s.__new__(%s) is not safe, use %s.__new__()", + type->tp_name, + subtype->tp_name, + staticbase == NULL ? "?" : staticbase->tp_name); + return NULL; + } + + args = PyTuple_GetSlice(args, 1, PyTuple_GET_SIZE(args)); + if (args == NULL) + return NULL; + res = type->tp_new(subtype, args, kwds); + Py_DECREF(args); + return res; } static struct PyMethodDef tp_new_methoddef[] = { - {"__new__", (PyCFunction)tp_new_wrapper, METH_VARARGS|METH_KEYWORDS, - PyDoc_STR("T.__new__(S, ...) -> " - "a new object with type S, a subtype of T")}, - {0} + {"__new__", (PyCFunction)tp_new_wrapper, METH_VARARGS|METH_KEYWORDS, + PyDoc_STR("T.__new__(S, ...) -> " + "a new object with type S, a subtype of T")}, + {0} }; static int add_tp_new_wrapper(PyTypeObject *type) { - PyObject *func; + PyObject *func; - if (PyDict_GetItemString(type->tp_dict, "__new__") != NULL) - return 0; - func = PyCFunction_New(tp_new_methoddef, (PyObject *)type); - if (func == NULL) - return -1; - if (PyDict_SetItemString(type->tp_dict, "__new__", func)) { - Py_DECREF(func); - return -1; - } - Py_DECREF(func); - return 0; + if (PyDict_GetItemString(type->tp_dict, "__new__") != NULL) + return 0; + func = PyCFunction_New(tp_new_methoddef, (PyObject *)type); + if (func == NULL) + return -1; + if (PyDict_SetItemString(type->tp_dict, "__new__", func)) { + Py_DECREF(func); + return -1; + } + Py_DECREF(func); + return 0; } /* Slot wrappers that call the corresponding __foo__ slot. See comments @@ -4516,16 +4516,16 @@ static PyObject * \ FUNCNAME(PyObject *self) \ { \ - static PyObject *cache_str; \ - return call_method(self, OPSTR, &cache_str, "()"); \ + static PyObject *cache_str; \ + return call_method(self, OPSTR, &cache_str, "()"); \ } #define SLOT1(FUNCNAME, OPSTR, ARG1TYPE, ARGCODES) \ static PyObject * \ FUNCNAME(PyObject *self, ARG1TYPE arg1) \ { \ - static PyObject *cache_str; \ - return call_method(self, OPSTR, &cache_str, "(" ARGCODES ")", arg1); \ + static PyObject *cache_str; \ + return call_method(self, OPSTR, &cache_str, "(" ARGCODES ")", arg1); \ } /* Boolean helper for SLOT1BINFULL(). @@ -4533,33 +4533,33 @@ static int method_is_overloaded(PyObject *left, PyObject *right, char *name) { - PyObject *a, *b; - int ok; + PyObject *a, *b; + int ok; - b = PyObject_GetAttrString((PyObject *)(Py_TYPE(right)), name); - if (b == NULL) { - PyErr_Clear(); - /* If right doesn't have it, it's not overloaded */ - return 0; - } - - a = PyObject_GetAttrString((PyObject *)(Py_TYPE(left)), name); - if (a == NULL) { - PyErr_Clear(); - Py_DECREF(b); - /* If right has it but left doesn't, it's overloaded */ - return 1; - } - - ok = PyObject_RichCompareBool(a, b, Py_NE); - Py_DECREF(a); - Py_DECREF(b); - if (ok < 0) { - PyErr_Clear(); - return 0; - } + b = PyObject_GetAttrString((PyObject *)(Py_TYPE(right)), name); + if (b == NULL) { + PyErr_Clear(); + /* If right doesn't have it, it's not overloaded */ + return 0; + } + + a = PyObject_GetAttrString((PyObject *)(Py_TYPE(left)), name); + if (a == NULL) { + PyErr_Clear(); + Py_DECREF(b); + /* If right has it but left doesn't, it's overloaded */ + return 1; + } + + ok = PyObject_RichCompareBool(a, b, Py_NE); + Py_DECREF(a); + Py_DECREF(b); + if (ok < 0) { + PyErr_Clear(); + return 0; + } - return ok; + return ok; } @@ -4567,68 +4567,68 @@ static PyObject * \ FUNCNAME(PyObject *self, PyObject *other) \ { \ - static PyObject *cache_str, *rcache_str; \ - int do_other = Py_TYPE(self) != Py_TYPE(other) && \ - Py_TYPE(other)->tp_as_number != NULL && \ - Py_TYPE(other)->tp_as_number->SLOTNAME == TESTFUNC; \ - if (Py_TYPE(self)->tp_as_number != NULL && \ - Py_TYPE(self)->tp_as_number->SLOTNAME == TESTFUNC) { \ - PyObject *r; \ - if (do_other && \ - PyType_IsSubtype(Py_TYPE(other), Py_TYPE(self)) && \ - method_is_overloaded(self, other, ROPSTR)) { \ - r = call_maybe( \ - other, ROPSTR, &rcache_str, "(O)", self); \ - if (r != Py_NotImplemented) \ - return r; \ - Py_DECREF(r); \ - do_other = 0; \ - } \ - r = call_maybe( \ - self, OPSTR, &cache_str, "(O)", other); \ - if (r != Py_NotImplemented || \ - Py_TYPE(other) == Py_TYPE(self)) \ - return r; \ - Py_DECREF(r); \ - } \ - if (do_other) { \ - return call_maybe( \ - other, ROPSTR, &rcache_str, "(O)", self); \ - } \ - Py_INCREF(Py_NotImplemented); \ - return Py_NotImplemented; \ + static PyObject *cache_str, *rcache_str; \ + int do_other = Py_TYPE(self) != Py_TYPE(other) && \ + Py_TYPE(other)->tp_as_number != NULL && \ + Py_TYPE(other)->tp_as_number->SLOTNAME == TESTFUNC; \ + if (Py_TYPE(self)->tp_as_number != NULL && \ + Py_TYPE(self)->tp_as_number->SLOTNAME == TESTFUNC) { \ + PyObject *r; \ + if (do_other && \ + PyType_IsSubtype(Py_TYPE(other), Py_TYPE(self)) && \ + method_is_overloaded(self, other, ROPSTR)) { \ + r = call_maybe( \ + other, ROPSTR, &rcache_str, "(O)", self); \ + if (r != Py_NotImplemented) \ + return r; \ + Py_DECREF(r); \ + do_other = 0; \ + } \ + r = call_maybe( \ + self, OPSTR, &cache_str, "(O)", other); \ + if (r != Py_NotImplemented || \ + Py_TYPE(other) == Py_TYPE(self)) \ + return r; \ + Py_DECREF(r); \ + } \ + if (do_other) { \ + return call_maybe( \ + other, ROPSTR, &rcache_str, "(O)", self); \ + } \ + Py_INCREF(Py_NotImplemented); \ + return Py_NotImplemented; \ } #define SLOT1BIN(FUNCNAME, SLOTNAME, OPSTR, ROPSTR) \ - SLOT1BINFULL(FUNCNAME, FUNCNAME, SLOTNAME, OPSTR, ROPSTR) + SLOT1BINFULL(FUNCNAME, FUNCNAME, SLOTNAME, OPSTR, ROPSTR) #define SLOT2(FUNCNAME, OPSTR, ARG1TYPE, ARG2TYPE, ARGCODES) \ static PyObject * \ FUNCNAME(PyObject *self, ARG1TYPE arg1, ARG2TYPE arg2) \ { \ - static PyObject *cache_str; \ - return call_method(self, OPSTR, &cache_str, \ - "(" ARGCODES ")", arg1, arg2); \ + static PyObject *cache_str; \ + return call_method(self, OPSTR, &cache_str, \ + "(" ARGCODES ")", arg1, arg2); \ } static Py_ssize_t slot_sq_length(PyObject *self) { - static PyObject *len_str; - PyObject *res = call_method(self, "__len__", &len_str, "()"); - Py_ssize_t len; - - if (res == NULL) - return -1; - len = PyNumber_AsSsize_t(res, PyExc_OverflowError); - Py_DECREF(res); - if (len < 0) { - if (!PyErr_Occurred()) - PyErr_SetString(PyExc_ValueError, - "__len__() should return >= 0"); - return -1; - } - return len; + static PyObject *len_str; + PyObject *res = call_method(self, "__len__", &len_str, "()"); + Py_ssize_t len; + + if (res == NULL) + return -1; + len = PyNumber_AsSsize_t(res, PyExc_OverflowError); + Py_DECREF(res); + if (len < 0) { + if (!PyErr_Occurred()) + PyErr_SetString(PyExc_ValueError, + "__len__() should return >= 0"); + return -1; + } + return len; } /* Super-optimized version of slot_sq_item. @@ -4636,93 +4636,93 @@ static PyObject * slot_sq_item(PyObject *self, Py_ssize_t i) { - static PyObject *getitem_str; - PyObject *func, *args = NULL, *ival = NULL, *retval = NULL; - descrgetfunc f; - - if (getitem_str == NULL) { - getitem_str = PyUnicode_InternFromString("__getitem__"); - if (getitem_str == NULL) - return NULL; - } - func = _PyType_Lookup(Py_TYPE(self), getitem_str); - if (func != NULL) { - if ((f = Py_TYPE(func)->tp_descr_get) == NULL) - Py_INCREF(func); - else { - func = f(func, self, (PyObject *)(Py_TYPE(self))); - if (func == NULL) { - return NULL; - } - } - ival = PyLong_FromSsize_t(i); - if (ival != NULL) { - args = PyTuple_New(1); - if (args != NULL) { - PyTuple_SET_ITEM(args, 0, ival); - retval = PyObject_Call(func, args, NULL); - Py_XDECREF(args); - Py_XDECREF(func); - return retval; - } - } - } - else { - PyErr_SetObject(PyExc_AttributeError, getitem_str); - } - Py_XDECREF(args); - Py_XDECREF(ival); - Py_XDECREF(func); - return NULL; + static PyObject *getitem_str; + PyObject *func, *args = NULL, *ival = NULL, *retval = NULL; + descrgetfunc f; + + if (getitem_str == NULL) { + getitem_str = PyUnicode_InternFromString("__getitem__"); + if (getitem_str == NULL) + return NULL; + } + func = _PyType_Lookup(Py_TYPE(self), getitem_str); + if (func != NULL) { + if ((f = Py_TYPE(func)->tp_descr_get) == NULL) + Py_INCREF(func); + else { + func = f(func, self, (PyObject *)(Py_TYPE(self))); + if (func == NULL) { + return NULL; + } + } + ival = PyLong_FromSsize_t(i); + if (ival != NULL) { + args = PyTuple_New(1); + if (args != NULL) { + PyTuple_SET_ITEM(args, 0, ival); + retval = PyObject_Call(func, args, NULL); + Py_XDECREF(args); + Py_XDECREF(func); + return retval; + } + } + } + else { + PyErr_SetObject(PyExc_AttributeError, getitem_str); + } + Py_XDECREF(args); + Py_XDECREF(ival); + Py_XDECREF(func); + return NULL; } static int slot_sq_ass_item(PyObject *self, Py_ssize_t index, PyObject *value) { - PyObject *res; - static PyObject *delitem_str, *setitem_str; + PyObject *res; + static PyObject *delitem_str, *setitem_str; - if (value == NULL) - res = call_method(self, "__delitem__", &delitem_str, - "(n)", index); - else - res = call_method(self, "__setitem__", &setitem_str, - "(nO)", index, value); - if (res == NULL) - return -1; - Py_DECREF(res); - return 0; + if (value == NULL) + res = call_method(self, "__delitem__", &delitem_str, + "(n)", index); + else + res = call_method(self, "__setitem__", &setitem_str, + "(nO)", index, value); + if (res == NULL) + return -1; + Py_DECREF(res); + return 0; } static int slot_sq_contains(PyObject *self, PyObject *value) { - PyObject *func, *res, *args; - int result = -1; + PyObject *func, *res, *args; + int result = -1; - static PyObject *contains_str; + static PyObject *contains_str; - func = lookup_maybe(self, "__contains__", &contains_str); - if (func != NULL) { - args = PyTuple_Pack(1, value); - if (args == NULL) - res = NULL; - else { - res = PyObject_Call(func, args, NULL); - Py_DECREF(args); - } - Py_DECREF(func); - if (res != NULL) { - result = PyObject_IsTrue(res); - Py_DECREF(res); - } - } - else if (! PyErr_Occurred()) { - /* Possible results: -1 and 1 */ - result = (int)_PySequence_IterSearch(self, value, - PY_ITERSEARCH_CONTAINS); - } - return result; + func = lookup_maybe(self, "__contains__", &contains_str); + if (func != NULL) { + args = PyTuple_Pack(1, value); + if (args == NULL) + res = NULL; + else { + res = PyObject_Call(func, args, NULL); + Py_DECREF(args); + } + Py_DECREF(func); + if (res != NULL) { + result = PyObject_IsTrue(res); + Py_DECREF(res); + } + } + else if (! PyErr_Occurred()) { + /* Possible results: -1 and 1 */ + result = (int)_PySequence_IterSearch(self, value, + PY_ITERSEARCH_CONTAINS); + } + return result; } #define slot_mp_length slot_sq_length @@ -4732,19 +4732,19 @@ static int slot_mp_ass_subscript(PyObject *self, PyObject *key, PyObject *value) { - PyObject *res; - static PyObject *delitem_str, *setitem_str; + PyObject *res; + static PyObject *delitem_str, *setitem_str; - if (value == NULL) - res = call_method(self, "__delitem__", &delitem_str, - "(O)", key); - else - res = call_method(self, "__setitem__", &setitem_str, - "(OO)", key, value); - if (res == NULL) - return -1; - Py_DECREF(res); - return 0; + if (value == NULL) + res = call_method(self, "__delitem__", &delitem_str, + "(O)", key); + else + res = call_method(self, "__setitem__", &setitem_str, + "(OO)", key, value); + if (res == NULL) + return -1; + Py_DECREF(res); + return 0; } SLOT1BIN(slot_nb_add, nb_add, "__add__", "__radd__") @@ -4756,25 +4756,25 @@ static PyObject *slot_nb_power(PyObject *, PyObject *, PyObject *); SLOT1BINFULL(slot_nb_power_binary, slot_nb_power, - nb_power, "__pow__", "__rpow__") + nb_power, "__pow__", "__rpow__") static PyObject * slot_nb_power(PyObject *self, PyObject *other, PyObject *modulus) { - static PyObject *pow_str; + static PyObject *pow_str; - if (modulus == Py_None) - return slot_nb_power_binary(self, other); - /* Three-arg power doesn't use __rpow__. But ternary_op - can call this when the second argument's type uses - slot_nb_power, so check before calling self.__pow__. */ - if (Py_TYPE(self)->tp_as_number != NULL && - Py_TYPE(self)->tp_as_number->nb_power == slot_nb_power) { - return call_method(self, "__pow__", &pow_str, - "(OO)", other, modulus); - } - Py_INCREF(Py_NotImplemented); - return Py_NotImplemented; + if (modulus == Py_None) + return slot_nb_power_binary(self, other); + /* Three-arg power doesn't use __rpow__. But ternary_op + can call this when the second argument's type uses + slot_nb_power, so check before calling self.__pow__. */ + if (Py_TYPE(self)->tp_as_number != NULL && + Py_TYPE(self)->tp_as_number->nb_power == slot_nb_power) { + return call_method(self, "__pow__", &pow_str, + "(OO)", other, modulus); + } + Py_INCREF(Py_NotImplemented); + return Py_NotImplemented; } SLOT0(slot_nb_negative, "__neg__") @@ -4784,52 +4784,52 @@ static int slot_nb_bool(PyObject *self) { - PyObject *func, *args; - static PyObject *bool_str, *len_str; - int result = -1; - int using_len = 0; - - func = lookup_maybe(self, "__bool__", &bool_str); - if (func == NULL) { - if (PyErr_Occurred()) - return -1; - func = lookup_maybe(self, "__len__", &len_str); - if (func == NULL) - return PyErr_Occurred() ? -1 : 1; - using_len = 1; - } - args = PyTuple_New(0); - if (args != NULL) { - PyObject *temp = PyObject_Call(func, args, NULL); - Py_DECREF(args); - if (temp != NULL) { - if (using_len) { - /* enforced by slot_nb_len */ - result = PyObject_IsTrue(temp); - } - else if (PyBool_Check(temp)) { - result = PyObject_IsTrue(temp); - } - else { - PyErr_Format(PyExc_TypeError, - "__bool__ should return " - "bool, returned %s", - Py_TYPE(temp)->tp_name); - result = -1; - } - Py_DECREF(temp); - } - } - Py_DECREF(func); - return result; + PyObject *func, *args; + static PyObject *bool_str, *len_str; + int result = -1; + int using_len = 0; + + func = lookup_maybe(self, "__bool__", &bool_str); + if (func == NULL) { + if (PyErr_Occurred()) + return -1; + func = lookup_maybe(self, "__len__", &len_str); + if (func == NULL) + return PyErr_Occurred() ? -1 : 1; + using_len = 1; + } + args = PyTuple_New(0); + if (args != NULL) { + PyObject *temp = PyObject_Call(func, args, NULL); + Py_DECREF(args); + if (temp != NULL) { + if (using_len) { + /* enforced by slot_nb_len */ + result = PyObject_IsTrue(temp); + } + else if (PyBool_Check(temp)) { + result = PyObject_IsTrue(temp); + } + else { + PyErr_Format(PyExc_TypeError, + "__bool__ should return " + "bool, returned %s", + Py_TYPE(temp)->tp_name); + result = -1; + } + Py_DECREF(temp); + } + } + Py_DECREF(func); + return result; } static PyObject * slot_nb_index(PyObject *self) { - static PyObject *index_str; - return call_method(self, "__index__", &index_str, "()"); + static PyObject *index_str; + return call_method(self, "__index__", &index_str, "()"); } @@ -4847,11 +4847,11 @@ SLOT1(slot_nb_inplace_multiply, "__imul__", PyObject *, "O") SLOT1(slot_nb_inplace_remainder, "__imod__", PyObject *, "O") /* Can't use SLOT1 here, because nb_inplace_power is ternary */ -static PyObject * -slot_nb_inplace_power(PyObject *self, PyObject * arg1, PyObject *arg2) -{ - static PyObject *cache_str; - return call_method(self, "__ipow__", &cache_str, "(" "O" ")", arg1); +static PyObject * +slot_nb_inplace_power(PyObject *self, PyObject * arg1, PyObject *arg2) +{ + static PyObject *cache_str; + return call_method(self, "__ipow__", &cache_str, "(" "O" ")", arg1); } SLOT1(slot_nb_inplace_lshift, "__ilshift__", PyObject *, "O") SLOT1(slot_nb_inplace_rshift, "__irshift__", PyObject *, "O") @@ -4859,7 +4859,7 @@ SLOT1(slot_nb_inplace_xor, "__ixor__", PyObject *, "O") SLOT1(slot_nb_inplace_or, "__ior__", PyObject *, "O") SLOT1BIN(slot_nb_floor_divide, nb_floor_divide, - "__floordiv__", "__rfloordiv__") + "__floordiv__", "__rfloordiv__") SLOT1BIN(slot_nb_true_divide, nb_true_divide, "__truediv__", "__rtruediv__") SLOT1(slot_nb_inplace_floor_divide, "__ifloordiv__", PyObject *, "O") SLOT1(slot_nb_inplace_true_divide, "__itruediv__", PyObject *, "O") @@ -4867,90 +4867,90 @@ static PyObject * slot_tp_repr(PyObject *self) { - PyObject *func, *res; - static PyObject *repr_str; + PyObject *func, *res; + static PyObject *repr_str; - func = lookup_method(self, "__repr__", &repr_str); - if (func != NULL) { - res = PyEval_CallObject(func, NULL); - Py_DECREF(func); - return res; - } - PyErr_Clear(); - return PyUnicode_FromFormat("<%s object at %p>", - Py_TYPE(self)->tp_name, self); + func = lookup_method(self, "__repr__", &repr_str); + if (func != NULL) { + res = PyEval_CallObject(func, NULL); + Py_DECREF(func); + return res; + } + PyErr_Clear(); + return PyUnicode_FromFormat("<%s object at %p>", + Py_TYPE(self)->tp_name, self); } static PyObject * slot_tp_str(PyObject *self) { - PyObject *func, *res; - static PyObject *str_str; + PyObject *func, *res; + static PyObject *str_str; - func = lookup_method(self, "__str__", &str_str); - if (func != NULL) { - res = PyEval_CallObject(func, NULL); - Py_DECREF(func); - return res; - } - else { - PyObject *ress; - PyErr_Clear(); - res = slot_tp_repr(self); - if (!res) - return NULL; - ress = _PyUnicode_AsDefaultEncodedString(res, NULL); - Py_DECREF(res); - return ress; - } + func = lookup_method(self, "__str__", &str_str); + if (func != NULL) { + res = PyEval_CallObject(func, NULL); + Py_DECREF(func); + return res; + } + else { + PyObject *ress; + PyErr_Clear(); + res = slot_tp_repr(self); + if (!res) + return NULL; + ress = _PyUnicode_AsDefaultEncodedString(res, NULL); + Py_DECREF(res); + return ress; + } } static long slot_tp_hash(PyObject *self) { - PyObject *func, *res; - static PyObject *hash_str; - long h; - - func = lookup_method(self, "__hash__", &hash_str); - - if (func == Py_None) { - Py_DECREF(func); - func = NULL; - } - - if (func == NULL) { - return PyObject_HashNotImplemented(self); - } - - res = PyEval_CallObject(func, NULL); - Py_DECREF(func); - if (res == NULL) - return -1; - if (PyLong_Check(res)) - h = PyLong_Type.tp_hash(res); - else - h = PyLong_AsLong(res); - Py_DECREF(res); - if (h == -1 && !PyErr_Occurred()) - h = -2; - return h; + PyObject *func, *res; + static PyObject *hash_str; + long h; + + func = lookup_method(self, "__hash__", &hash_str); + + if (func == Py_None) { + Py_DECREF(func); + func = NULL; + } + + if (func == NULL) { + return PyObject_HashNotImplemented(self); + } + + res = PyEval_CallObject(func, NULL); + Py_DECREF(func); + if (res == NULL) + return -1; + if (PyLong_Check(res)) + h = PyLong_Type.tp_hash(res); + else + h = PyLong_AsLong(res); + Py_DECREF(res); + if (h == -1 && !PyErr_Occurred()) + h = -2; + return h; } static PyObject * slot_tp_call(PyObject *self, PyObject *args, PyObject *kwds) { - static PyObject *call_str; - PyObject *meth = lookup_method(self, "__call__", &call_str); - PyObject *res; + static PyObject *call_str; + PyObject *meth = lookup_method(self, "__call__", &call_str); + PyObject *res; - if (meth == NULL) - return NULL; + if (meth == NULL) + return NULL; - res = PyObject_Call(meth, args, kwds); + res = PyObject_Call(meth, args, kwds); - Py_DECREF(meth); - return res; + Py_DECREF(meth); + return res; } /* There are two slot dispatch functions for tp_getattro. @@ -4967,100 +4967,100 @@ static PyObject * slot_tp_getattro(PyObject *self, PyObject *name) { - static PyObject *getattribute_str = NULL; - return call_method(self, "__getattribute__", &getattribute_str, - "(O)", name); + static PyObject *getattribute_str = NULL; + return call_method(self, "__getattribute__", &getattribute_str, + "(O)", name); } static PyObject * call_attribute(PyObject *self, PyObject *attr, PyObject *name) { - PyObject *res, *descr = NULL; - descrgetfunc f = Py_TYPE(attr)->tp_descr_get; + PyObject *res, *descr = NULL; + descrgetfunc f = Py_TYPE(attr)->tp_descr_get; - if (f != NULL) { - descr = f(attr, self, (PyObject *)(Py_TYPE(self))); - if (descr == NULL) - return NULL; - else - attr = descr; - } - res = PyObject_CallFunctionObjArgs(attr, name, NULL); - Py_XDECREF(descr); - return res; + if (f != NULL) { + descr = f(attr, self, (PyObject *)(Py_TYPE(self))); + if (descr == NULL) + return NULL; + else + attr = descr; + } + res = PyObject_CallFunctionObjArgs(attr, name, NULL); + Py_XDECREF(descr); + return res; } static PyObject * slot_tp_getattr_hook(PyObject *self, PyObject *name) { - PyTypeObject *tp = Py_TYPE(self); - PyObject *getattr, *getattribute, *res; - static PyObject *getattribute_str = NULL; - static PyObject *getattr_str = NULL; - - if (getattr_str == NULL) { - getattr_str = PyUnicode_InternFromString("__getattr__"); - if (getattr_str == NULL) - return NULL; - } - if (getattribute_str == NULL) { - getattribute_str = - PyUnicode_InternFromString("__getattribute__"); - if (getattribute_str == NULL) - return NULL; - } - /* speed hack: we could use lookup_maybe, but that would resolve the - method fully for each attribute lookup for classes with - __getattr__, even when the attribute is present. So we use - _PyType_Lookup and create the method only when needed, with - call_attribute. */ - getattr = _PyType_Lookup(tp, getattr_str); - if (getattr == NULL) { - /* No __getattr__ hook: use a simpler dispatcher */ - tp->tp_getattro = slot_tp_getattro; - return slot_tp_getattro(self, name); - } - Py_INCREF(getattr); - /* speed hack: we could use lookup_maybe, but that would resolve the - method fully for each attribute lookup for classes with - __getattr__, even when self has the default __getattribute__ - method. So we use _PyType_Lookup and create the method only when - needed, with call_attribute. */ - getattribute = _PyType_Lookup(tp, getattribute_str); - if (getattribute == NULL || - (Py_TYPE(getattribute) == &PyWrapperDescr_Type && - ((PyWrapperDescrObject *)getattribute)->d_wrapped == - (void *)PyObject_GenericGetAttr)) - res = PyObject_GenericGetAttr(self, name); - else { - Py_INCREF(getattribute); - res = call_attribute(self, getattribute, name); - Py_DECREF(getattribute); - } - if (res == NULL && PyErr_ExceptionMatches(PyExc_AttributeError)) { - PyErr_Clear(); - res = call_attribute(self, getattr, name); - } - Py_DECREF(getattr); - return res; + PyTypeObject *tp = Py_TYPE(self); + PyObject *getattr, *getattribute, *res; + static PyObject *getattribute_str = NULL; + static PyObject *getattr_str = NULL; + + if (getattr_str == NULL) { + getattr_str = PyUnicode_InternFromString("__getattr__"); + if (getattr_str == NULL) + return NULL; + } + if (getattribute_str == NULL) { + getattribute_str = + PyUnicode_InternFromString("__getattribute__"); + if (getattribute_str == NULL) + return NULL; + } + /* speed hack: we could use lookup_maybe, but that would resolve the + method fully for each attribute lookup for classes with + __getattr__, even when the attribute is present. So we use + _PyType_Lookup and create the method only when needed, with + call_attribute. */ + getattr = _PyType_Lookup(tp, getattr_str); + if (getattr == NULL) { + /* No __getattr__ hook: use a simpler dispatcher */ + tp->tp_getattro = slot_tp_getattro; + return slot_tp_getattro(self, name); + } + Py_INCREF(getattr); + /* speed hack: we could use lookup_maybe, but that would resolve the + method fully for each attribute lookup for classes with + __getattr__, even when self has the default __getattribute__ + method. So we use _PyType_Lookup and create the method only when + needed, with call_attribute. */ + getattribute = _PyType_Lookup(tp, getattribute_str); + if (getattribute == NULL || + (Py_TYPE(getattribute) == &PyWrapperDescr_Type && + ((PyWrapperDescrObject *)getattribute)->d_wrapped == + (void *)PyObject_GenericGetAttr)) + res = PyObject_GenericGetAttr(self, name); + else { + Py_INCREF(getattribute); + res = call_attribute(self, getattribute, name); + Py_DECREF(getattribute); + } + if (res == NULL && PyErr_ExceptionMatches(PyExc_AttributeError)) { + PyErr_Clear(); + res = call_attribute(self, getattr, name); + } + Py_DECREF(getattr); + return res; } static int slot_tp_setattro(PyObject *self, PyObject *name, PyObject *value) { - PyObject *res; - static PyObject *delattr_str, *setattr_str; + PyObject *res; + static PyObject *delattr_str, *setattr_str; - if (value == NULL) - res = call_method(self, "__delattr__", &delattr_str, - "(O)", name); - else - res = call_method(self, "__setattr__", &setattr_str, - "(OO)", name, value); - if (res == NULL) - return -1; - Py_DECREF(res); - return 0; + if (value == NULL) + res = call_method(self, "__delattr__", &delattr_str, + "(O)", name); + else + res = call_method(self, "__setattr__", &setattr_str, + "(OO)", name, value); + if (res == NULL) + return -1; + Py_DECREF(res); + return 0; } static char *name_op[] = { @@ -5075,222 +5075,222 @@ static PyObject * slot_tp_richcompare(PyObject *self, PyObject *other, int op) { - PyObject *func, *args, *res; - static PyObject *op_str[6]; + PyObject *func, *args, *res; + static PyObject *op_str[6]; - func = lookup_method(self, name_op[op], &op_str[op]); - if (func == NULL) { - PyErr_Clear(); - Py_INCREF(Py_NotImplemented); - return Py_NotImplemented; - } - args = PyTuple_Pack(1, other); - if (args == NULL) - res = NULL; - else { - res = PyObject_Call(func, args, NULL); - Py_DECREF(args); - } - Py_DECREF(func); - return res; + func = lookup_method(self, name_op[op], &op_str[op]); + if (func == NULL) { + PyErr_Clear(); + Py_INCREF(Py_NotImplemented); + return Py_NotImplemented; + } + args = PyTuple_Pack(1, other); + if (args == NULL) + res = NULL; + else { + res = PyObject_Call(func, args, NULL); + Py_DECREF(args); + } + Py_DECREF(func); + return res; } static PyObject * slot_tp_iter(PyObject *self) { - PyObject *func, *res; - static PyObject *iter_str, *getitem_str; + PyObject *func, *res; + static PyObject *iter_str, *getitem_str; - func = lookup_method(self, "__iter__", &iter_str); - if (func != NULL) { - PyObject *args; - args = res = PyTuple_New(0); - if (args != NULL) { - res = PyObject_Call(func, args, NULL); - Py_DECREF(args); - } - Py_DECREF(func); - return res; - } - PyErr_Clear(); - func = lookup_method(self, "__getitem__", &getitem_str); - if (func == NULL) { - PyErr_Format(PyExc_TypeError, - "'%.200s' object is not iterable", - Py_TYPE(self)->tp_name); - return NULL; - } - Py_DECREF(func); - return PySeqIter_New(self); + func = lookup_method(self, "__iter__", &iter_str); + if (func != NULL) { + PyObject *args; + args = res = PyTuple_New(0); + if (args != NULL) { + res = PyObject_Call(func, args, NULL); + Py_DECREF(args); + } + Py_DECREF(func); + return res; + } + PyErr_Clear(); + func = lookup_method(self, "__getitem__", &getitem_str); + if (func == NULL) { + PyErr_Format(PyExc_TypeError, + "'%.200s' object is not iterable", + Py_TYPE(self)->tp_name); + return NULL; + } + Py_DECREF(func); + return PySeqIter_New(self); } static PyObject * slot_tp_iternext(PyObject *self) { - static PyObject *next_str; - return call_method(self, "__next__", &next_str, "()"); + static PyObject *next_str; + return call_method(self, "__next__", &next_str, "()"); } static PyObject * slot_tp_descr_get(PyObject *self, PyObject *obj, PyObject *type) { - PyTypeObject *tp = Py_TYPE(self); - PyObject *get; - static PyObject *get_str = NULL; - - if (get_str == NULL) { - get_str = PyUnicode_InternFromString("__get__"); - if (get_str == NULL) - return NULL; - } - get = _PyType_Lookup(tp, get_str); - if (get == NULL) { - /* Avoid further slowdowns */ - if (tp->tp_descr_get == slot_tp_descr_get) - tp->tp_descr_get = NULL; - Py_INCREF(self); - return self; - } - if (obj == NULL) - obj = Py_None; - if (type == NULL) - type = Py_None; - return PyObject_CallFunctionObjArgs(get, self, obj, type, NULL); + PyTypeObject *tp = Py_TYPE(self); + PyObject *get; + static PyObject *get_str = NULL; + + if (get_str == NULL) { + get_str = PyUnicode_InternFromString("__get__"); + if (get_str == NULL) + return NULL; + } + get = _PyType_Lookup(tp, get_str); + if (get == NULL) { + /* Avoid further slowdowns */ + if (tp->tp_descr_get == slot_tp_descr_get) + tp->tp_descr_get = NULL; + Py_INCREF(self); + return self; + } + if (obj == NULL) + obj = Py_None; + if (type == NULL) + type = Py_None; + return PyObject_CallFunctionObjArgs(get, self, obj, type, NULL); } static int slot_tp_descr_set(PyObject *self, PyObject *target, PyObject *value) { - PyObject *res; - static PyObject *del_str, *set_str; + PyObject *res; + static PyObject *del_str, *set_str; - if (value == NULL) - res = call_method(self, "__delete__", &del_str, - "(O)", target); - else - res = call_method(self, "__set__", &set_str, - "(OO)", target, value); - if (res == NULL) - return -1; - Py_DECREF(res); - return 0; + if (value == NULL) + res = call_method(self, "__delete__", &del_str, + "(O)", target); + else + res = call_method(self, "__set__", &set_str, + "(OO)", target, value); + if (res == NULL) + return -1; + Py_DECREF(res); + return 0; } static int slot_tp_init(PyObject *self, PyObject *args, PyObject *kwds) { - static PyObject *init_str; - PyObject *meth = lookup_method(self, "__init__", &init_str); - PyObject *res; - - if (meth == NULL) - return -1; - res = PyObject_Call(meth, args, kwds); - Py_DECREF(meth); - if (res == NULL) - return -1; - if (res != Py_None) { - PyErr_Format(PyExc_TypeError, - "__init__() should return None, not '%.200s'", - Py_TYPE(res)->tp_name); - Py_DECREF(res); - return -1; - } - Py_DECREF(res); - return 0; + static PyObject *init_str; + PyObject *meth = lookup_method(self, "__init__", &init_str); + PyObject *res; + + if (meth == NULL) + return -1; + res = PyObject_Call(meth, args, kwds); + Py_DECREF(meth); + if (res == NULL) + return -1; + if (res != Py_None) { + PyErr_Format(PyExc_TypeError, + "__init__() should return None, not '%.200s'", + Py_TYPE(res)->tp_name); + Py_DECREF(res); + return -1; + } + Py_DECREF(res); + return 0; } static PyObject * slot_tp_new(PyTypeObject *type, PyObject *args, PyObject *kwds) { - static PyObject *new_str; - PyObject *func; - PyObject *newargs, *x; - Py_ssize_t i, n; - - if (new_str == NULL) { - new_str = PyUnicode_InternFromString("__new__"); - if (new_str == NULL) - return NULL; - } - func = PyObject_GetAttr((PyObject *)type, new_str); - if (func == NULL) - return NULL; - assert(PyTuple_Check(args)); - n = PyTuple_GET_SIZE(args); - newargs = PyTuple_New(n+1); - if (newargs == NULL) - return NULL; - Py_INCREF(type); - PyTuple_SET_ITEM(newargs, 0, (PyObject *)type); - for (i = 0; i < n; i++) { - x = PyTuple_GET_ITEM(args, i); - Py_INCREF(x); - PyTuple_SET_ITEM(newargs, i+1, x); - } - x = PyObject_Call(func, newargs, kwds); - Py_DECREF(newargs); - Py_DECREF(func); - return x; + static PyObject *new_str; + PyObject *func; + PyObject *newargs, *x; + Py_ssize_t i, n; + + if (new_str == NULL) { + new_str = PyUnicode_InternFromString("__new__"); + if (new_str == NULL) + return NULL; + } + func = PyObject_GetAttr((PyObject *)type, new_str); + if (func == NULL) + return NULL; + assert(PyTuple_Check(args)); + n = PyTuple_GET_SIZE(args); + newargs = PyTuple_New(n+1); + if (newargs == NULL) + return NULL; + Py_INCREF(type); + PyTuple_SET_ITEM(newargs, 0, (PyObject *)type); + for (i = 0; i < n; i++) { + x = PyTuple_GET_ITEM(args, i); + Py_INCREF(x); + PyTuple_SET_ITEM(newargs, i+1, x); + } + x = PyObject_Call(func, newargs, kwds); + Py_DECREF(newargs); + Py_DECREF(func); + return x; } static void slot_tp_del(PyObject *self) { - static PyObject *del_str = NULL; - PyObject *del, *res; - PyObject *error_type, *error_value, *error_traceback; - - /* Temporarily resurrect the object. */ - assert(self->ob_refcnt == 0); - self->ob_refcnt = 1; - - /* Save the current exception, if any. */ - PyErr_Fetch(&error_type, &error_value, &error_traceback); - - /* Execute __del__ method, if any. */ - del = lookup_maybe(self, "__del__", &del_str); - if (del != NULL) { - res = PyEval_CallObject(del, NULL); - if (res == NULL) - PyErr_WriteUnraisable(del); - else - Py_DECREF(res); - Py_DECREF(del); - } - - /* Restore the saved exception. */ - PyErr_Restore(error_type, error_value, error_traceback); - - /* Undo the temporary resurrection; can't use DECREF here, it would - * cause a recursive call. - */ - assert(self->ob_refcnt > 0); - if (--self->ob_refcnt == 0) - return; /* this is the normal path out */ - - /* __del__ resurrected it! Make it look like the original Py_DECREF - * never happened. - */ - { - Py_ssize_t refcnt = self->ob_refcnt; - _Py_NewReference(self); - self->ob_refcnt = refcnt; - } - assert(!PyType_IS_GC(Py_TYPE(self)) || - _Py_AS_GC(self)->gc.gc_refs != _PyGC_REFS_UNTRACKED); - /* If Py_REF_DEBUG, _Py_NewReference bumped _Py_RefTotal, so - * we need to undo that. */ - _Py_DEC_REFTOTAL; - /* If Py_TRACE_REFS, _Py_NewReference re-added self to the object - * chain, so no more to do there. - * If COUNT_ALLOCS, the original decref bumped tp_frees, and - * _Py_NewReference bumped tp_allocs: both of those need to be - * undone. - */ + static PyObject *del_str = NULL; + PyObject *del, *res; + PyObject *error_type, *error_value, *error_traceback; + + /* Temporarily resurrect the object. */ + assert(self->ob_refcnt == 0); + self->ob_refcnt = 1; + + /* Save the current exception, if any. */ + PyErr_Fetch(&error_type, &error_value, &error_traceback); + + /* Execute __del__ method, if any. */ + del = lookup_maybe(self, "__del__", &del_str); + if (del != NULL) { + res = PyEval_CallObject(del, NULL); + if (res == NULL) + PyErr_WriteUnraisable(del); + else + Py_DECREF(res); + Py_DECREF(del); + } + + /* Restore the saved exception. */ + PyErr_Restore(error_type, error_value, error_traceback); + + /* Undo the temporary resurrection; can't use DECREF here, it would + * cause a recursive call. + */ + assert(self->ob_refcnt > 0); + if (--self->ob_refcnt == 0) + return; /* this is the normal path out */ + + /* __del__ resurrected it! Make it look like the original Py_DECREF + * never happened. + */ + { + Py_ssize_t refcnt = self->ob_refcnt; + _Py_NewReference(self); + self->ob_refcnt = refcnt; + } + assert(!PyType_IS_GC(Py_TYPE(self)) || + _Py_AS_GC(self)->gc.gc_refs != _PyGC_REFS_UNTRACKED); + /* If Py_REF_DEBUG, _Py_NewReference bumped _Py_RefTotal, so + * we need to undo that. */ + _Py_DEC_REFTOTAL; + /* If Py_TRACE_REFS, _Py_NewReference re-added self to the object + * chain, so no more to do there. + * If COUNT_ALLOCS, the original decref bumped tp_frees, and + * _Py_NewReference bumped tp_allocs: both of those need to be + * undone. + */ #ifdef COUNT_ALLOCS - --Py_TYPE(self)->tp_frees; - --Py_TYPE(self)->tp_allocs; + --Py_TYPE(self)->tp_frees; + --Py_TYPE(self)->tp_allocs; #endif } @@ -5319,236 +5319,236 @@ #undef RBINSLOT #define TPSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \ - {NAME, offsetof(PyTypeObject, SLOT), (void *)(FUNCTION), WRAPPER, \ - PyDoc_STR(DOC)} + {NAME, offsetof(PyTypeObject, SLOT), (void *)(FUNCTION), WRAPPER, \ + PyDoc_STR(DOC)} #define FLSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC, FLAGS) \ - {NAME, offsetof(PyTypeObject, SLOT), (void *)(FUNCTION), WRAPPER, \ - PyDoc_STR(DOC), FLAGS} + {NAME, offsetof(PyTypeObject, SLOT), (void *)(FUNCTION), WRAPPER, \ + PyDoc_STR(DOC), FLAGS} #define ETSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \ - {NAME, offsetof(PyHeapTypeObject, SLOT), (void *)(FUNCTION), WRAPPER, \ - PyDoc_STR(DOC)} + {NAME, offsetof(PyHeapTypeObject, SLOT), (void *)(FUNCTION), WRAPPER, \ + PyDoc_STR(DOC)} #define SQSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \ - ETSLOT(NAME, as_sequence.SLOT, FUNCTION, WRAPPER, DOC) + ETSLOT(NAME, as_sequence.SLOT, FUNCTION, WRAPPER, DOC) #define MPSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \ - ETSLOT(NAME, as_mapping.SLOT, FUNCTION, WRAPPER, DOC) + ETSLOT(NAME, as_mapping.SLOT, FUNCTION, WRAPPER, DOC) #define NBSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \ - ETSLOT(NAME, as_number.SLOT, FUNCTION, WRAPPER, DOC) + ETSLOT(NAME, as_number.SLOT, FUNCTION, WRAPPER, DOC) #define UNSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \ - ETSLOT(NAME, as_number.SLOT, FUNCTION, WRAPPER, \ - "x." NAME "() <==> " DOC) + ETSLOT(NAME, as_number.SLOT, FUNCTION, WRAPPER, \ + "x." NAME "() <==> " DOC) #define IBSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \ - ETSLOT(NAME, as_number.SLOT, FUNCTION, WRAPPER, \ - "x." NAME "(y) <==> x" DOC "y") + ETSLOT(NAME, as_number.SLOT, FUNCTION, WRAPPER, \ + "x." NAME "(y) <==> x" DOC "y") #define BINSLOT(NAME, SLOT, FUNCTION, DOC) \ - ETSLOT(NAME, as_number.SLOT, FUNCTION, wrap_binaryfunc_l, \ - "x." NAME "(y) <==> x" DOC "y") + ETSLOT(NAME, as_number.SLOT, FUNCTION, wrap_binaryfunc_l, \ + "x." NAME "(y) <==> x" DOC "y") #define RBINSLOT(NAME, SLOT, FUNCTION, DOC) \ - ETSLOT(NAME, as_number.SLOT, FUNCTION, wrap_binaryfunc_r, \ - "x." NAME "(y) <==> y" DOC "x") + ETSLOT(NAME, as_number.SLOT, FUNCTION, wrap_binaryfunc_r, \ + "x." NAME "(y) <==> y" DOC "x") #define BINSLOTNOTINFIX(NAME, SLOT, FUNCTION, DOC) \ - ETSLOT(NAME, as_number.SLOT, FUNCTION, wrap_binaryfunc_l, \ - "x." NAME "(y) <==> " DOC) + ETSLOT(NAME, as_number.SLOT, FUNCTION, wrap_binaryfunc_l, \ + "x." NAME "(y) <==> " DOC) #define RBINSLOTNOTINFIX(NAME, SLOT, FUNCTION, DOC) \ - ETSLOT(NAME, as_number.SLOT, FUNCTION, wrap_binaryfunc_r, \ - "x." NAME "(y) <==> " DOC) + ETSLOT(NAME, as_number.SLOT, FUNCTION, wrap_binaryfunc_r, \ + "x." NAME "(y) <==> " DOC) static slotdef slotdefs[] = { - SQSLOT("__len__", sq_length, slot_sq_length, wrap_lenfunc, - "x.__len__() <==> len(x)"), - /* Heap types defining __add__/__mul__ have sq_concat/sq_repeat == NULL. - The logic in abstract.c always falls back to nb_add/nb_multiply in - this case. Defining both the nb_* and the sq_* slots to call the - user-defined methods has unexpected side-effects, as shown by - test_descr.notimplemented() */ - SQSLOT("__add__", sq_concat, NULL, wrap_binaryfunc, - "x.__add__(y) <==> x+y"), - SQSLOT("__mul__", sq_repeat, NULL, wrap_indexargfunc, - "x.__mul__(n) <==> x*n"), - SQSLOT("__rmul__", sq_repeat, NULL, wrap_indexargfunc, - "x.__rmul__(n) <==> n*x"), - SQSLOT("__getitem__", sq_item, slot_sq_item, wrap_sq_item, - "x.__getitem__(y) <==> x[y]"), - SQSLOT("__setitem__", sq_ass_item, slot_sq_ass_item, wrap_sq_setitem, - "x.__setitem__(i, y) <==> x[i]=y"), - SQSLOT("__delitem__", sq_ass_item, slot_sq_ass_item, wrap_sq_delitem, - "x.__delitem__(y) <==> del x[y]"), - SQSLOT("__contains__", sq_contains, slot_sq_contains, wrap_objobjproc, - "x.__contains__(y) <==> y in x"), - SQSLOT("__iadd__", sq_inplace_concat, NULL, - wrap_binaryfunc, "x.__iadd__(y) <==> x+=y"), - SQSLOT("__imul__", sq_inplace_repeat, NULL, - wrap_indexargfunc, "x.__imul__(y) <==> x*=y"), - - MPSLOT("__len__", mp_length, slot_mp_length, wrap_lenfunc, - "x.__len__() <==> len(x)"), - MPSLOT("__getitem__", mp_subscript, slot_mp_subscript, - wrap_binaryfunc, - "x.__getitem__(y) <==> x[y]"), - MPSLOT("__setitem__", mp_ass_subscript, slot_mp_ass_subscript, - wrap_objobjargproc, - "x.__setitem__(i, y) <==> x[i]=y"), - MPSLOT("__delitem__", mp_ass_subscript, slot_mp_ass_subscript, - wrap_delitem, - "x.__delitem__(y) <==> del x[y]"), - - BINSLOT("__add__", nb_add, slot_nb_add, - "+"), - RBINSLOT("__radd__", nb_add, slot_nb_add, - "+"), - BINSLOT("__sub__", nb_subtract, slot_nb_subtract, - "-"), - RBINSLOT("__rsub__", nb_subtract, slot_nb_subtract, - "-"), - BINSLOT("__mul__", nb_multiply, slot_nb_multiply, - "*"), - RBINSLOT("__rmul__", nb_multiply, slot_nb_multiply, - "*"), - BINSLOT("__mod__", nb_remainder, slot_nb_remainder, - "%"), - RBINSLOT("__rmod__", nb_remainder, slot_nb_remainder, - "%"), - BINSLOTNOTINFIX("__divmod__", nb_divmod, slot_nb_divmod, - "divmod(x, y)"), - RBINSLOTNOTINFIX("__rdivmod__", nb_divmod, slot_nb_divmod, - "divmod(y, x)"), - NBSLOT("__pow__", nb_power, slot_nb_power, wrap_ternaryfunc, - "x.__pow__(y[, z]) <==> pow(x, y[, z])"), - NBSLOT("__rpow__", nb_power, slot_nb_power, wrap_ternaryfunc_r, - "y.__rpow__(x[, z]) <==> pow(x, y[, z])"), - UNSLOT("__neg__", nb_negative, slot_nb_negative, wrap_unaryfunc, "-x"), - UNSLOT("__pos__", nb_positive, slot_nb_positive, wrap_unaryfunc, "+x"), - UNSLOT("__abs__", nb_absolute, slot_nb_absolute, wrap_unaryfunc, - "abs(x)"), - UNSLOT("__bool__", nb_bool, slot_nb_bool, wrap_inquirypred, - "x != 0"), - UNSLOT("__invert__", nb_invert, slot_nb_invert, wrap_unaryfunc, "~x"), - BINSLOT("__lshift__", nb_lshift, slot_nb_lshift, "<<"), - RBINSLOT("__rlshift__", nb_lshift, slot_nb_lshift, "<<"), - BINSLOT("__rshift__", nb_rshift, slot_nb_rshift, ">>"), - RBINSLOT("__rrshift__", nb_rshift, slot_nb_rshift, ">>"), - BINSLOT("__and__", nb_and, slot_nb_and, "&"), - RBINSLOT("__rand__", nb_and, slot_nb_and, "&"), - BINSLOT("__xor__", nb_xor, slot_nb_xor, "^"), - RBINSLOT("__rxor__", nb_xor, slot_nb_xor, "^"), - BINSLOT("__or__", nb_or, slot_nb_or, "|"), - RBINSLOT("__ror__", nb_or, slot_nb_or, "|"), - UNSLOT("__int__", nb_int, slot_nb_int, wrap_unaryfunc, - "int(x)"), - UNSLOT("__float__", nb_float, slot_nb_float, wrap_unaryfunc, - "float(x)"), - NBSLOT("__index__", nb_index, slot_nb_index, wrap_unaryfunc, - "x[y:z] <==> x[y.__index__():z.__index__()]"), - IBSLOT("__iadd__", nb_inplace_add, slot_nb_inplace_add, - wrap_binaryfunc, "+"), - IBSLOT("__isub__", nb_inplace_subtract, slot_nb_inplace_subtract, - wrap_binaryfunc, "-"), - IBSLOT("__imul__", nb_inplace_multiply, slot_nb_inplace_multiply, - wrap_binaryfunc, "*"), - IBSLOT("__imod__", nb_inplace_remainder, slot_nb_inplace_remainder, - wrap_binaryfunc, "%"), - IBSLOT("__ipow__", nb_inplace_power, slot_nb_inplace_power, - wrap_binaryfunc, "**"), - IBSLOT("__ilshift__", nb_inplace_lshift, slot_nb_inplace_lshift, - wrap_binaryfunc, "<<"), - IBSLOT("__irshift__", nb_inplace_rshift, slot_nb_inplace_rshift, - wrap_binaryfunc, ">>"), - IBSLOT("__iand__", nb_inplace_and, slot_nb_inplace_and, - wrap_binaryfunc, "&"), - IBSLOT("__ixor__", nb_inplace_xor, slot_nb_inplace_xor, - wrap_binaryfunc, "^"), - IBSLOT("__ior__", nb_inplace_or, slot_nb_inplace_or, - wrap_binaryfunc, "|"), - BINSLOT("__floordiv__", nb_floor_divide, slot_nb_floor_divide, "//"), - RBINSLOT("__rfloordiv__", nb_floor_divide, slot_nb_floor_divide, "//"), - BINSLOT("__truediv__", nb_true_divide, slot_nb_true_divide, "/"), - RBINSLOT("__rtruediv__", nb_true_divide, slot_nb_true_divide, "/"), - IBSLOT("__ifloordiv__", nb_inplace_floor_divide, - slot_nb_inplace_floor_divide, wrap_binaryfunc, "//"), - IBSLOT("__itruediv__", nb_inplace_true_divide, - slot_nb_inplace_true_divide, wrap_binaryfunc, "/"), - - TPSLOT("__str__", tp_str, slot_tp_str, wrap_unaryfunc, - "x.__str__() <==> str(x)"), - TPSLOT("__repr__", tp_repr, slot_tp_repr, wrap_unaryfunc, - "x.__repr__() <==> repr(x)"), - TPSLOT("__hash__", tp_hash, slot_tp_hash, wrap_hashfunc, - "x.__hash__() <==> hash(x)"), - FLSLOT("__call__", tp_call, slot_tp_call, (wrapperfunc)wrap_call, - "x.__call__(...) <==> x(...)", PyWrapperFlag_KEYWORDS), - TPSLOT("__getattribute__", tp_getattro, slot_tp_getattr_hook, - wrap_binaryfunc, "x.__getattribute__('name') <==> x.name"), - TPSLOT("__getattribute__", tp_getattr, NULL, NULL, ""), - TPSLOT("__getattr__", tp_getattro, slot_tp_getattr_hook, NULL, ""), - TPSLOT("__getattr__", tp_getattr, NULL, NULL, ""), - TPSLOT("__setattr__", tp_setattro, slot_tp_setattro, wrap_setattr, - "x.__setattr__('name', value) <==> x.name = value"), - TPSLOT("__setattr__", tp_setattr, NULL, NULL, ""), - TPSLOT("__delattr__", tp_setattro, slot_tp_setattro, wrap_delattr, - "x.__delattr__('name') <==> del x.name"), - TPSLOT("__delattr__", tp_setattr, NULL, NULL, ""), - TPSLOT("__lt__", tp_richcompare, slot_tp_richcompare, richcmp_lt, - "x.__lt__(y) <==> x x<=y"), - TPSLOT("__eq__", tp_richcompare, slot_tp_richcompare, richcmp_eq, - "x.__eq__(y) <==> x==y"), - TPSLOT("__ne__", tp_richcompare, slot_tp_richcompare, richcmp_ne, - "x.__ne__(y) <==> x!=y"), - TPSLOT("__gt__", tp_richcompare, slot_tp_richcompare, richcmp_gt, - "x.__gt__(y) <==> x>y"), - TPSLOT("__ge__", tp_richcompare, slot_tp_richcompare, richcmp_ge, - "x.__ge__(y) <==> x>=y"), - TPSLOT("__iter__", tp_iter, slot_tp_iter, wrap_unaryfunc, - "x.__iter__() <==> iter(x)"), - TPSLOT("__next__", tp_iternext, slot_tp_iternext, wrap_next, - "x.__next__() <==> next(x)"), - TPSLOT("__get__", tp_descr_get, slot_tp_descr_get, wrap_descr_get, - "descr.__get__(obj[, type]) -> value"), - TPSLOT("__set__", tp_descr_set, slot_tp_descr_set, wrap_descr_set, - "descr.__set__(obj, value)"), - TPSLOT("__delete__", tp_descr_set, slot_tp_descr_set, - wrap_descr_delete, "descr.__delete__(obj)"), - FLSLOT("__init__", tp_init, slot_tp_init, (wrapperfunc)wrap_init, - "x.__init__(...) initializes x; " - "see x.__class__.__doc__ for signature", - PyWrapperFlag_KEYWORDS), - TPSLOT("__new__", tp_new, slot_tp_new, NULL, ""), - TPSLOT("__del__", tp_del, slot_tp_del, NULL, ""), - {NULL} + SQSLOT("__len__", sq_length, slot_sq_length, wrap_lenfunc, + "x.__len__() <==> len(x)"), + /* Heap types defining __add__/__mul__ have sq_concat/sq_repeat == NULL. + The logic in abstract.c always falls back to nb_add/nb_multiply in + this case. Defining both the nb_* and the sq_* slots to call the + user-defined methods has unexpected side-effects, as shown by + test_descr.notimplemented() */ + SQSLOT("__add__", sq_concat, NULL, wrap_binaryfunc, + "x.__add__(y) <==> x+y"), + SQSLOT("__mul__", sq_repeat, NULL, wrap_indexargfunc, + "x.__mul__(n) <==> x*n"), + SQSLOT("__rmul__", sq_repeat, NULL, wrap_indexargfunc, + "x.__rmul__(n) <==> n*x"), + SQSLOT("__getitem__", sq_item, slot_sq_item, wrap_sq_item, + "x.__getitem__(y) <==> x[y]"), + SQSLOT("__setitem__", sq_ass_item, slot_sq_ass_item, wrap_sq_setitem, + "x.__setitem__(i, y) <==> x[i]=y"), + SQSLOT("__delitem__", sq_ass_item, slot_sq_ass_item, wrap_sq_delitem, + "x.__delitem__(y) <==> del x[y]"), + SQSLOT("__contains__", sq_contains, slot_sq_contains, wrap_objobjproc, + "x.__contains__(y) <==> y in x"), + SQSLOT("__iadd__", sq_inplace_concat, NULL, + wrap_binaryfunc, "x.__iadd__(y) <==> x+=y"), + SQSLOT("__imul__", sq_inplace_repeat, NULL, + wrap_indexargfunc, "x.__imul__(y) <==> x*=y"), + + MPSLOT("__len__", mp_length, slot_mp_length, wrap_lenfunc, + "x.__len__() <==> len(x)"), + MPSLOT("__getitem__", mp_subscript, slot_mp_subscript, + wrap_binaryfunc, + "x.__getitem__(y) <==> x[y]"), + MPSLOT("__setitem__", mp_ass_subscript, slot_mp_ass_subscript, + wrap_objobjargproc, + "x.__setitem__(i, y) <==> x[i]=y"), + MPSLOT("__delitem__", mp_ass_subscript, slot_mp_ass_subscript, + wrap_delitem, + "x.__delitem__(y) <==> del x[y]"), + + BINSLOT("__add__", nb_add, slot_nb_add, + "+"), + RBINSLOT("__radd__", nb_add, slot_nb_add, + "+"), + BINSLOT("__sub__", nb_subtract, slot_nb_subtract, + "-"), + RBINSLOT("__rsub__", nb_subtract, slot_nb_subtract, + "-"), + BINSLOT("__mul__", nb_multiply, slot_nb_multiply, + "*"), + RBINSLOT("__rmul__", nb_multiply, slot_nb_multiply, + "*"), + BINSLOT("__mod__", nb_remainder, slot_nb_remainder, + "%"), + RBINSLOT("__rmod__", nb_remainder, slot_nb_remainder, + "%"), + BINSLOTNOTINFIX("__divmod__", nb_divmod, slot_nb_divmod, + "divmod(x, y)"), + RBINSLOTNOTINFIX("__rdivmod__", nb_divmod, slot_nb_divmod, + "divmod(y, x)"), + NBSLOT("__pow__", nb_power, slot_nb_power, wrap_ternaryfunc, + "x.__pow__(y[, z]) <==> pow(x, y[, z])"), + NBSLOT("__rpow__", nb_power, slot_nb_power, wrap_ternaryfunc_r, + "y.__rpow__(x[, z]) <==> pow(x, y[, z])"), + UNSLOT("__neg__", nb_negative, slot_nb_negative, wrap_unaryfunc, "-x"), + UNSLOT("__pos__", nb_positive, slot_nb_positive, wrap_unaryfunc, "+x"), + UNSLOT("__abs__", nb_absolute, slot_nb_absolute, wrap_unaryfunc, + "abs(x)"), + UNSLOT("__bool__", nb_bool, slot_nb_bool, wrap_inquirypred, + "x != 0"), + UNSLOT("__invert__", nb_invert, slot_nb_invert, wrap_unaryfunc, "~x"), + BINSLOT("__lshift__", nb_lshift, slot_nb_lshift, "<<"), + RBINSLOT("__rlshift__", nb_lshift, slot_nb_lshift, "<<"), + BINSLOT("__rshift__", nb_rshift, slot_nb_rshift, ">>"), + RBINSLOT("__rrshift__", nb_rshift, slot_nb_rshift, ">>"), + BINSLOT("__and__", nb_and, slot_nb_and, "&"), + RBINSLOT("__rand__", nb_and, slot_nb_and, "&"), + BINSLOT("__xor__", nb_xor, slot_nb_xor, "^"), + RBINSLOT("__rxor__", nb_xor, slot_nb_xor, "^"), + BINSLOT("__or__", nb_or, slot_nb_or, "|"), + RBINSLOT("__ror__", nb_or, slot_nb_or, "|"), + UNSLOT("__int__", nb_int, slot_nb_int, wrap_unaryfunc, + "int(x)"), + UNSLOT("__float__", nb_float, slot_nb_float, wrap_unaryfunc, + "float(x)"), + NBSLOT("__index__", nb_index, slot_nb_index, wrap_unaryfunc, + "x[y:z] <==> x[y.__index__():z.__index__()]"), + IBSLOT("__iadd__", nb_inplace_add, slot_nb_inplace_add, + wrap_binaryfunc, "+"), + IBSLOT("__isub__", nb_inplace_subtract, slot_nb_inplace_subtract, + wrap_binaryfunc, "-"), + IBSLOT("__imul__", nb_inplace_multiply, slot_nb_inplace_multiply, + wrap_binaryfunc, "*"), + IBSLOT("__imod__", nb_inplace_remainder, slot_nb_inplace_remainder, + wrap_binaryfunc, "%"), + IBSLOT("__ipow__", nb_inplace_power, slot_nb_inplace_power, + wrap_binaryfunc, "**"), + IBSLOT("__ilshift__", nb_inplace_lshift, slot_nb_inplace_lshift, + wrap_binaryfunc, "<<"), + IBSLOT("__irshift__", nb_inplace_rshift, slot_nb_inplace_rshift, + wrap_binaryfunc, ">>"), + IBSLOT("__iand__", nb_inplace_and, slot_nb_inplace_and, + wrap_binaryfunc, "&"), + IBSLOT("__ixor__", nb_inplace_xor, slot_nb_inplace_xor, + wrap_binaryfunc, "^"), + IBSLOT("__ior__", nb_inplace_or, slot_nb_inplace_or, + wrap_binaryfunc, "|"), + BINSLOT("__floordiv__", nb_floor_divide, slot_nb_floor_divide, "//"), + RBINSLOT("__rfloordiv__", nb_floor_divide, slot_nb_floor_divide, "//"), + BINSLOT("__truediv__", nb_true_divide, slot_nb_true_divide, "/"), + RBINSLOT("__rtruediv__", nb_true_divide, slot_nb_true_divide, "/"), + IBSLOT("__ifloordiv__", nb_inplace_floor_divide, + slot_nb_inplace_floor_divide, wrap_binaryfunc, "//"), + IBSLOT("__itruediv__", nb_inplace_true_divide, + slot_nb_inplace_true_divide, wrap_binaryfunc, "/"), + + TPSLOT("__str__", tp_str, slot_tp_str, wrap_unaryfunc, + "x.__str__() <==> str(x)"), + TPSLOT("__repr__", tp_repr, slot_tp_repr, wrap_unaryfunc, + "x.__repr__() <==> repr(x)"), + TPSLOT("__hash__", tp_hash, slot_tp_hash, wrap_hashfunc, + "x.__hash__() <==> hash(x)"), + FLSLOT("__call__", tp_call, slot_tp_call, (wrapperfunc)wrap_call, + "x.__call__(...) <==> x(...)", PyWrapperFlag_KEYWORDS), + TPSLOT("__getattribute__", tp_getattro, slot_tp_getattr_hook, + wrap_binaryfunc, "x.__getattribute__('name') <==> x.name"), + TPSLOT("__getattribute__", tp_getattr, NULL, NULL, ""), + TPSLOT("__getattr__", tp_getattro, slot_tp_getattr_hook, NULL, ""), + TPSLOT("__getattr__", tp_getattr, NULL, NULL, ""), + TPSLOT("__setattr__", tp_setattro, slot_tp_setattro, wrap_setattr, + "x.__setattr__('name', value) <==> x.name = value"), + TPSLOT("__setattr__", tp_setattr, NULL, NULL, ""), + TPSLOT("__delattr__", tp_setattro, slot_tp_setattro, wrap_delattr, + "x.__delattr__('name') <==> del x.name"), + TPSLOT("__delattr__", tp_setattr, NULL, NULL, ""), + TPSLOT("__lt__", tp_richcompare, slot_tp_richcompare, richcmp_lt, + "x.__lt__(y) <==> x x<=y"), + TPSLOT("__eq__", tp_richcompare, slot_tp_richcompare, richcmp_eq, + "x.__eq__(y) <==> x==y"), + TPSLOT("__ne__", tp_richcompare, slot_tp_richcompare, richcmp_ne, + "x.__ne__(y) <==> x!=y"), + TPSLOT("__gt__", tp_richcompare, slot_tp_richcompare, richcmp_gt, + "x.__gt__(y) <==> x>y"), + TPSLOT("__ge__", tp_richcompare, slot_tp_richcompare, richcmp_ge, + "x.__ge__(y) <==> x>=y"), + TPSLOT("__iter__", tp_iter, slot_tp_iter, wrap_unaryfunc, + "x.__iter__() <==> iter(x)"), + TPSLOT("__next__", tp_iternext, slot_tp_iternext, wrap_next, + "x.__next__() <==> next(x)"), + TPSLOT("__get__", tp_descr_get, slot_tp_descr_get, wrap_descr_get, + "descr.__get__(obj[, type]) -> value"), + TPSLOT("__set__", tp_descr_set, slot_tp_descr_set, wrap_descr_set, + "descr.__set__(obj, value)"), + TPSLOT("__delete__", tp_descr_set, slot_tp_descr_set, + wrap_descr_delete, "descr.__delete__(obj)"), + FLSLOT("__init__", tp_init, slot_tp_init, (wrapperfunc)wrap_init, + "x.__init__(...) initializes x; " + "see x.__class__.__doc__ for signature", + PyWrapperFlag_KEYWORDS), + TPSLOT("__new__", tp_new, slot_tp_new, NULL, ""), + TPSLOT("__del__", tp_del, slot_tp_del, NULL, ""), + {NULL} }; /* Given a type pointer and an offset gotten from a slotdef entry, return a - pointer to the actual slot. This is not quite the same as simply adding + pointer to the actual slot. This is not quite the same as simply adding the offset to the type pointer, since it takes care to indirect through the proper indirection pointer (as_buffer, etc.); it returns NULL if the indirection pointer is NULL. */ static void ** slotptr(PyTypeObject *type, int ioffset) { - char *ptr; - long offset = ioffset; + char *ptr; + long offset = ioffset; - /* Note: this depends on the order of the members of PyHeapTypeObject! */ - assert(offset >= 0); - assert((size_t)offset < offsetof(PyHeapTypeObject, as_buffer)); - if ((size_t)offset >= offsetof(PyHeapTypeObject, as_sequence)) { - ptr = (char *)type->tp_as_sequence; - offset -= offsetof(PyHeapTypeObject, as_sequence); - } - else if ((size_t)offset >= offsetof(PyHeapTypeObject, as_mapping)) { - ptr = (char *)type->tp_as_mapping; - offset -= offsetof(PyHeapTypeObject, as_mapping); - } - else if ((size_t)offset >= offsetof(PyHeapTypeObject, as_number)) { - ptr = (char *)type->tp_as_number; - offset -= offsetof(PyHeapTypeObject, as_number); - } - else { - ptr = (char *)type; - } - if (ptr != NULL) - ptr += offset; - return (void **)ptr; + /* Note: this depends on the order of the members of PyHeapTypeObject! */ + assert(offset >= 0); + assert((size_t)offset < offsetof(PyHeapTypeObject, as_buffer)); + if ((size_t)offset >= offsetof(PyHeapTypeObject, as_sequence)) { + ptr = (char *)type->tp_as_sequence; + offset -= offsetof(PyHeapTypeObject, as_sequence); + } + else if ((size_t)offset >= offsetof(PyHeapTypeObject, as_mapping)) { + ptr = (char *)type->tp_as_mapping; + offset -= offsetof(PyHeapTypeObject, as_mapping); + } + else if ((size_t)offset >= offsetof(PyHeapTypeObject, as_number)) { + ptr = (char *)type->tp_as_number; + offset -= offsetof(PyHeapTypeObject, as_number); + } + else { + ptr = (char *)type; + } + if (ptr != NULL) + ptr += offset; + return (void **)ptr; } /* Length of array of slotdef pointers used to store slots with the @@ -5562,37 +5562,37 @@ static void ** resolve_slotdups(PyTypeObject *type, PyObject *name) { - /* XXX Maybe this could be optimized more -- but is it worth it? */ + /* XXX Maybe this could be optimized more -- but is it worth it? */ - /* pname and ptrs act as a little cache */ - static PyObject *pname; - static slotdef *ptrs[MAX_EQUIV]; - slotdef *p, **pp; - void **res, **ptr; - - if (pname != name) { - /* Collect all slotdefs that match name into ptrs. */ - pname = name; - pp = ptrs; - for (p = slotdefs; p->name_strobj; p++) { - if (p->name_strobj == name) - *pp++ = p; - } - *pp = NULL; - } - - /* Look in all matching slots of the type; if exactly one of these has - a filled-in slot, return its value. Otherwise return NULL. */ - res = NULL; - for (pp = ptrs; *pp; pp++) { - ptr = slotptr(type, (*pp)->offset); - if (ptr == NULL || *ptr == NULL) - continue; - if (res != NULL) - return NULL; - res = ptr; - } - return res; + /* pname and ptrs act as a little cache */ + static PyObject *pname; + static slotdef *ptrs[MAX_EQUIV]; + slotdef *p, **pp; + void **res, **ptr; + + if (pname != name) { + /* Collect all slotdefs that match name into ptrs. */ + pname = name; + pp = ptrs; + for (p = slotdefs; p->name_strobj; p++) { + if (p->name_strobj == name) + *pp++ = p; + } + *pp = NULL; + } + + /* Look in all matching slots of the type; if exactly one of these has + a filled-in slot, return its value. Otherwise return NULL. */ + res = NULL; + for (pp = ptrs; *pp; pp++) { + ptr = slotptr(type, (*pp)->offset); + if (ptr == NULL || *ptr == NULL) + continue; + if (res != NULL) + return NULL; + res = ptr; + } + return res; } /* Common code for update_slots_callback() and fixup_slot_dispatchers(). This @@ -5604,81 +5604,81 @@ static slotdef * update_one_slot(PyTypeObject *type, slotdef *p) { - PyObject *descr; - PyWrapperDescrObject *d; - void *generic = NULL, *specific = NULL; - int use_generic = 0; - int offset = p->offset; - void **ptr = slotptr(type, offset); - - if (ptr == NULL) { - do { - ++p; - } while (p->offset == offset); - return p; - } - do { - descr = _PyType_Lookup(type, p->name_strobj); - if (descr == NULL) { - if (ptr == (void**)&type->tp_iternext) { - specific = _PyObject_NextNotImplemented; - } - continue; - } - if (Py_TYPE(descr) == &PyWrapperDescr_Type) { - void **tptr = resolve_slotdups(type, p->name_strobj); - if (tptr == NULL || tptr == ptr) - generic = p->function; - d = (PyWrapperDescrObject *)descr; - if (d->d_base->wrapper == p->wrapper && - PyType_IsSubtype(type, PyDescr_TYPE(d))) - { - if (specific == NULL || - specific == d->d_wrapped) - specific = d->d_wrapped; - else - use_generic = 1; - } - } - else if (Py_TYPE(descr) == &PyCFunction_Type && - PyCFunction_GET_FUNCTION(descr) == - (PyCFunction)tp_new_wrapper && - ptr == (void**)&type->tp_new) - { - /* The __new__ wrapper is not a wrapper descriptor, - so must be special-cased differently. - If we don't do this, creating an instance will - always use slot_tp_new which will look up - __new__ in the MRO which will call tp_new_wrapper - which will look through the base classes looking - for a static base and call its tp_new (usually - PyType_GenericNew), after performing various - sanity checks and constructing a new argument - list. Cut all that nonsense short -- this speeds - up instance creation tremendously. */ - specific = (void *)type->tp_new; - /* XXX I'm not 100% sure that there isn't a hole - in this reasoning that requires additional - sanity checks. I'll buy the first person to - point out a bug in this reasoning a beer. */ - } - else if (descr == Py_None && - ptr == (void**)&type->tp_hash) { - /* We specifically allow __hash__ to be set to None - to prevent inheritance of the default - implementation from object.__hash__ */ - specific = PyObject_HashNotImplemented; - } - else { - use_generic = 1; - generic = p->function; - } - } while ((++p)->offset == offset); - if (specific && !use_generic) - *ptr = specific; - else - *ptr = generic; - return p; + PyObject *descr; + PyWrapperDescrObject *d; + void *generic = NULL, *specific = NULL; + int use_generic = 0; + int offset = p->offset; + void **ptr = slotptr(type, offset); + + if (ptr == NULL) { + do { + ++p; + } while (p->offset == offset); + return p; + } + do { + descr = _PyType_Lookup(type, p->name_strobj); + if (descr == NULL) { + if (ptr == (void**)&type->tp_iternext) { + specific = _PyObject_NextNotImplemented; + } + continue; + } + if (Py_TYPE(descr) == &PyWrapperDescr_Type) { + void **tptr = resolve_slotdups(type, p->name_strobj); + if (tptr == NULL || tptr == ptr) + generic = p->function; + d = (PyWrapperDescrObject *)descr; + if (d->d_base->wrapper == p->wrapper && + PyType_IsSubtype(type, PyDescr_TYPE(d))) + { + if (specific == NULL || + specific == d->d_wrapped) + specific = d->d_wrapped; + else + use_generic = 1; + } + } + else if (Py_TYPE(descr) == &PyCFunction_Type && + PyCFunction_GET_FUNCTION(descr) == + (PyCFunction)tp_new_wrapper && + ptr == (void**)&type->tp_new) + { + /* The __new__ wrapper is not a wrapper descriptor, + so must be special-cased differently. + If we don't do this, creating an instance will + always use slot_tp_new which will look up + __new__ in the MRO which will call tp_new_wrapper + which will look through the base classes looking + for a static base and call its tp_new (usually + PyType_GenericNew), after performing various + sanity checks and constructing a new argument + list. Cut all that nonsense short -- this speeds + up instance creation tremendously. */ + specific = (void *)type->tp_new; + /* XXX I'm not 100% sure that there isn't a hole + in this reasoning that requires additional + sanity checks. I'll buy the first person to + point out a bug in this reasoning a beer. */ + } + else if (descr == Py_None && + ptr == (void**)&type->tp_hash) { + /* We specifically allow __hash__ to be set to None + to prevent inheritance of the default + implementation from object.__hash__ */ + specific = PyObject_HashNotImplemented; + } + else { + use_generic = 1; + generic = p->function; + } + } while ((++p)->offset == offset); + if (specific && !use_generic) + *ptr = specific; + else + *ptr = generic; + return p; } /* In the type, update the slots whose slotdefs are gathered in the pp array. @@ -5686,11 +5686,11 @@ static int update_slots_callback(PyTypeObject *type, void *data) { - slotdef **pp = (slotdef **)data; + slotdef **pp = (slotdef **)data; - for (; *pp; pp++) - update_one_slot(type, *pp); - return 0; + for (; *pp; pp++) + update_one_slot(type, *pp); + return 0; } /* Comparison function for qsort() to compare slotdefs by their offset, and @@ -5698,14 +5698,14 @@ static int slotdef_cmp(const void *aa, const void *bb) { - const slotdef *a = (const slotdef *)aa, *b = (const slotdef *)bb; - int c = a->offset - b->offset; - if (c != 0) - return c; - else - /* Cannot use a-b, as this gives off_t, - which may lose precision when converted to int. */ - return (a > b) ? 1 : (a < b) ? -1 : 0; + const slotdef *a = (const slotdef *)aa, *b = (const slotdef *)bb; + int c = a->offset - b->offset; + if (c != 0) + return c; + else + /* Cannot use a-b, as this gives off_t, + which may lose precision when converted to int. */ + return (a > b) ? 1 : (a < b) ? -1 : 0; } /* Initialize the slotdefs table by adding interned string objects for the @@ -5713,56 +5713,56 @@ static void init_slotdefs(void) { - slotdef *p; - static int initialized = 0; + slotdef *p; + static int initialized = 0; - if (initialized) - return; - for (p = slotdefs; p->name; p++) { - p->name_strobj = PyUnicode_InternFromString(p->name); - if (!p->name_strobj) - Py_FatalError("Out of memory interning slotdef names"); - } - qsort((void *)slotdefs, (size_t)(p-slotdefs), sizeof(slotdef), - slotdef_cmp); - initialized = 1; + if (initialized) + return; + for (p = slotdefs; p->name; p++) { + p->name_strobj = PyUnicode_InternFromString(p->name); + if (!p->name_strobj) + Py_FatalError("Out of memory interning slotdef names"); + } + qsort((void *)slotdefs, (size_t)(p-slotdefs), sizeof(slotdef), + slotdef_cmp); + initialized = 1; } /* Update the slots after assignment to a class (type) attribute. */ static int update_slot(PyTypeObject *type, PyObject *name) { - slotdef *ptrs[MAX_EQUIV]; - slotdef *p; - slotdef **pp; - int offset; - - /* Clear the VALID_VERSION flag of 'type' and all its - subclasses. This could possibly be unified with the - update_subclasses() recursion below, but carefully: - they each have their own conditions on which to stop - recursing into subclasses. */ - PyType_Modified(type); - - init_slotdefs(); - pp = ptrs; - for (p = slotdefs; p->name; p++) { - /* XXX assume name is interned! */ - if (p->name_strobj == name) - *pp++ = p; - } - *pp = NULL; - for (pp = ptrs; *pp; pp++) { - p = *pp; - offset = p->offset; - while (p > slotdefs && (p-1)->offset == offset) - --p; - *pp = p; - } - if (ptrs[0] == NULL) - return 0; /* Not an attribute that affects any slots */ - return update_subclasses(type, name, - update_slots_callback, (void *)ptrs); + slotdef *ptrs[MAX_EQUIV]; + slotdef *p; + slotdef **pp; + int offset; + + /* Clear the VALID_VERSION flag of 'type' and all its + subclasses. This could possibly be unified with the + update_subclasses() recursion below, but carefully: + they each have their own conditions on which to stop + recursing into subclasses. */ + PyType_Modified(type); + + init_slotdefs(); + pp = ptrs; + for (p = slotdefs; p->name; p++) { + /* XXX assume name is interned! */ + if (p->name_strobj == name) + *pp++ = p; + } + *pp = NULL; + for (pp = ptrs; *pp; pp++) { + p = *pp; + offset = p->offset; + while (p > slotdefs && (p-1)->offset == offset) + --p; + *pp = p; + } + if (ptrs[0] == NULL) + return 0; /* Not an attribute that affects any slots */ + return update_subclasses(type, name, + update_slots_callback, (void *)ptrs); } /* Store the proper functions in the slot dispatches at class (type) @@ -5771,23 +5771,23 @@ static void fixup_slot_dispatchers(PyTypeObject *type) { - slotdef *p; + slotdef *p; - init_slotdefs(); - for (p = slotdefs; p->name; ) - p = update_one_slot(type, p); + init_slotdefs(); + for (p = slotdefs; p->name; ) + p = update_one_slot(type, p); } static void update_all_slots(PyTypeObject* type) { - slotdef *p; + slotdef *p; - init_slotdefs(); - for (p = slotdefs; p->name; p++) { - /* update_slot returns int but can't actually fail */ - update_slot(type, p->name_strobj); - } + init_slotdefs(); + for (p = slotdefs; p->name; p++) { + /* update_slot returns int but can't actually fail */ + update_slot(type, p->name_strobj); + } } /* recurse_down_subclasses() and update_subclasses() are mutually @@ -5796,56 +5796,56 @@ static int update_subclasses(PyTypeObject *type, PyObject *name, - update_callback callback, void *data) + update_callback callback, void *data) { - if (callback(type, data) < 0) - return -1; - return recurse_down_subclasses(type, name, callback, data); + if (callback(type, data) < 0) + return -1; + return recurse_down_subclasses(type, name, callback, data); } static int recurse_down_subclasses(PyTypeObject *type, PyObject *name, - update_callback callback, void *data) + update_callback callback, void *data) { - PyTypeObject *subclass; - PyObject *ref, *subclasses, *dict; - Py_ssize_t i, n; - - subclasses = type->tp_subclasses; - if (subclasses == NULL) - return 0; - assert(PyList_Check(subclasses)); - n = PyList_GET_SIZE(subclasses); - for (i = 0; i < n; i++) { - ref = PyList_GET_ITEM(subclasses, i); - assert(PyWeakref_CheckRef(ref)); - subclass = (PyTypeObject *)PyWeakref_GET_OBJECT(ref); - assert(subclass != NULL); - if ((PyObject *)subclass == Py_None) - continue; - assert(PyType_Check(subclass)); - /* Avoid recursing down into unaffected classes */ - dict = subclass->tp_dict; - if (dict != NULL && PyDict_Check(dict) && - PyDict_GetItem(dict, name) != NULL) - continue; - if (update_subclasses(subclass, name, callback, data) < 0) - return -1; - } - return 0; + PyTypeObject *subclass; + PyObject *ref, *subclasses, *dict; + Py_ssize_t i, n; + + subclasses = type->tp_subclasses; + if (subclasses == NULL) + return 0; + assert(PyList_Check(subclasses)); + n = PyList_GET_SIZE(subclasses); + for (i = 0; i < n; i++) { + ref = PyList_GET_ITEM(subclasses, i); + assert(PyWeakref_CheckRef(ref)); + subclass = (PyTypeObject *)PyWeakref_GET_OBJECT(ref); + assert(subclass != NULL); + if ((PyObject *)subclass == Py_None) + continue; + assert(PyType_Check(subclass)); + /* Avoid recursing down into unaffected classes */ + dict = subclass->tp_dict; + if (dict != NULL && PyDict_Check(dict) && + PyDict_GetItem(dict, name) != NULL) + continue; + if (update_subclasses(subclass, name, callback, data) < 0) + return -1; + } + return 0; } /* This function is called by PyType_Ready() to populate the type's dictionary with method descriptors for function slots. For each function slot (like tp_repr) that's defined in the type, one or more corresponding descriptors are added in the type's tp_dict dictionary - under the appropriate name (like __repr__). Some function slots + under the appropriate name (like __repr__). Some function slots cause more than one descriptor to be added (for example, the nb_add slot adds both __add__ and __radd__ descriptors) and some function slots compete for the same descriptor (for example both sq_item and mp_subscript generate a __getitem__ descriptor). - In the latter case, the first slotdef entry encoutered wins. Since + In the latter case, the first slotdef entry encoutered wins. Since slotdef entries are sorted by the offset of the slot in the PyHeapTypeObject, this gives us some control over disambiguating between competing slots: the members of PyHeapTypeObject are listed @@ -5868,344 +5868,344 @@ static int add_operators(PyTypeObject *type) { - PyObject *dict = type->tp_dict; - slotdef *p; - PyObject *descr; - void **ptr; - - init_slotdefs(); - for (p = slotdefs; p->name; p++) { - if (p->wrapper == NULL) - continue; - ptr = slotptr(type, p->offset); - if (!ptr || !*ptr) - continue; - if (PyDict_GetItem(dict, p->name_strobj)) - continue; - if (*ptr == PyObject_HashNotImplemented) { - /* Classes may prevent the inheritance of the tp_hash - slot by storing PyObject_HashNotImplemented in it. Make it - visible as a None value for the __hash__ attribute. */ - if (PyDict_SetItem(dict, p->name_strobj, Py_None) < 0) - return -1; - } - else { - descr = PyDescr_NewWrapper(type, p, *ptr); - if (descr == NULL) - return -1; - if (PyDict_SetItem(dict, p->name_strobj, descr) < 0) - return -1; - Py_DECREF(descr); - } - } - if (type->tp_new != NULL) { - if (add_tp_new_wrapper(type) < 0) - return -1; - } - return 0; + PyObject *dict = type->tp_dict; + slotdef *p; + PyObject *descr; + void **ptr; + + init_slotdefs(); + for (p = slotdefs; p->name; p++) { + if (p->wrapper == NULL) + continue; + ptr = slotptr(type, p->offset); + if (!ptr || !*ptr) + continue; + if (PyDict_GetItem(dict, p->name_strobj)) + continue; + if (*ptr == PyObject_HashNotImplemented) { + /* Classes may prevent the inheritance of the tp_hash + slot by storing PyObject_HashNotImplemented in it. Make it + visible as a None value for the __hash__ attribute. */ + if (PyDict_SetItem(dict, p->name_strobj, Py_None) < 0) + return -1; + } + else { + descr = PyDescr_NewWrapper(type, p, *ptr); + if (descr == NULL) + return -1; + if (PyDict_SetItem(dict, p->name_strobj, descr) < 0) + return -1; + Py_DECREF(descr); + } + } + if (type->tp_new != NULL) { + if (add_tp_new_wrapper(type) < 0) + return -1; + } + return 0; } /* Cooperative 'super' */ typedef struct { - PyObject_HEAD - PyTypeObject *type; - PyObject *obj; - PyTypeObject *obj_type; + PyObject_HEAD + PyTypeObject *type; + PyObject *obj; + PyTypeObject *obj_type; } superobject; static PyMemberDef super_members[] = { - {"__thisclass__", T_OBJECT, offsetof(superobject, type), READONLY, - "the class invoking super()"}, - {"__self__", T_OBJECT, offsetof(superobject, obj), READONLY, - "the instance invoking super(); may be None"}, - {"__self_class__", T_OBJECT, offsetof(superobject, obj_type), READONLY, - "the type of the instance invoking super(); may be None"}, - {0} + {"__thisclass__", T_OBJECT, offsetof(superobject, type), READONLY, + "the class invoking super()"}, + {"__self__", T_OBJECT, offsetof(superobject, obj), READONLY, + "the instance invoking super(); may be None"}, + {"__self_class__", T_OBJECT, offsetof(superobject, obj_type), READONLY, + "the type of the instance invoking super(); may be None"}, + {0} }; static void super_dealloc(PyObject *self) { - superobject *su = (superobject *)self; + superobject *su = (superobject *)self; - _PyObject_GC_UNTRACK(self); - Py_XDECREF(su->obj); - Py_XDECREF(su->type); - Py_XDECREF(su->obj_type); - Py_TYPE(self)->tp_free(self); + _PyObject_GC_UNTRACK(self); + Py_XDECREF(su->obj); + Py_XDECREF(su->type); + Py_XDECREF(su->obj_type); + Py_TYPE(self)->tp_free(self); } static PyObject * super_repr(PyObject *self) { - superobject *su = (superobject *)self; + superobject *su = (superobject *)self; - if (su->obj_type) - return PyUnicode_FromFormat( - ", <%s object>>", - su->type ? su->type->tp_name : "NULL", - su->obj_type->tp_name); - else - return PyUnicode_FromFormat( - ", NULL>", - su->type ? su->type->tp_name : "NULL"); + if (su->obj_type) + return PyUnicode_FromFormat( + ", <%s object>>", + su->type ? su->type->tp_name : "NULL", + su->obj_type->tp_name); + else + return PyUnicode_FromFormat( + ", NULL>", + su->type ? su->type->tp_name : "NULL"); } static PyObject * super_getattro(PyObject *self, PyObject *name) { - superobject *su = (superobject *)self; - int skip = su->obj_type == NULL; + superobject *su = (superobject *)self; + int skip = su->obj_type == NULL; - if (!skip) { - /* We want __class__ to return the class of the super object - (i.e. super, or a subclass), not the class of su->obj. */ - skip = (PyUnicode_Check(name) && - PyUnicode_GET_SIZE(name) == 9 && - PyUnicode_CompareWithASCIIString(name, "__class__") == 0); - } - - if (!skip) { - PyObject *mro, *res, *tmp, *dict; - PyTypeObject *starttype; - descrgetfunc f; - Py_ssize_t i, n; - - starttype = su->obj_type; - mro = starttype->tp_mro; - - if (mro == NULL) - n = 0; - else { - assert(PyTuple_Check(mro)); - n = PyTuple_GET_SIZE(mro); - } - for (i = 0; i < n; i++) { - if ((PyObject *)(su->type) == PyTuple_GET_ITEM(mro, i)) - break; - } - i++; - res = NULL; - for (; i < n; i++) { - tmp = PyTuple_GET_ITEM(mro, i); - if (PyType_Check(tmp)) - dict = ((PyTypeObject *)tmp)->tp_dict; - else - continue; - res = PyDict_GetItem(dict, name); - if (res != NULL) { - Py_INCREF(res); - f = Py_TYPE(res)->tp_descr_get; - if (f != NULL) { - tmp = f(res, - /* Only pass 'obj' param if - this is instance-mode super - (See SF ID #743627) - */ - (su->obj == (PyObject *) - su->obj_type - ? (PyObject *)NULL - : su->obj), - (PyObject *)starttype); - Py_DECREF(res); - res = tmp; - } - return res; - } - } - } - return PyObject_GenericGetAttr(self, name); + if (!skip) { + /* We want __class__ to return the class of the super object + (i.e. super, or a subclass), not the class of su->obj. */ + skip = (PyUnicode_Check(name) && + PyUnicode_GET_SIZE(name) == 9 && + PyUnicode_CompareWithASCIIString(name, "__class__") == 0); + } + + if (!skip) { + PyObject *mro, *res, *tmp, *dict; + PyTypeObject *starttype; + descrgetfunc f; + Py_ssize_t i, n; + + starttype = su->obj_type; + mro = starttype->tp_mro; + + if (mro == NULL) + n = 0; + else { + assert(PyTuple_Check(mro)); + n = PyTuple_GET_SIZE(mro); + } + for (i = 0; i < n; i++) { + if ((PyObject *)(su->type) == PyTuple_GET_ITEM(mro, i)) + break; + } + i++; + res = NULL; + for (; i < n; i++) { + tmp = PyTuple_GET_ITEM(mro, i); + if (PyType_Check(tmp)) + dict = ((PyTypeObject *)tmp)->tp_dict; + else + continue; + res = PyDict_GetItem(dict, name); + if (res != NULL) { + Py_INCREF(res); + f = Py_TYPE(res)->tp_descr_get; + if (f != NULL) { + tmp = f(res, + /* Only pass 'obj' param if + this is instance-mode super + (See SF ID #743627) + */ + (su->obj == (PyObject *) + su->obj_type + ? (PyObject *)NULL + : su->obj), + (PyObject *)starttype); + Py_DECREF(res); + res = tmp; + } + return res; + } + } + } + return PyObject_GenericGetAttr(self, name); } static PyTypeObject * supercheck(PyTypeObject *type, PyObject *obj) { - /* Check that a super() call makes sense. Return a type object. + /* Check that a super() call makes sense. Return a type object. + + obj can be a new-style class, or an instance of one: - obj can be a new-style class, or an instance of one: + - If it is a class, it must be a subclass of 'type'. This case is + used for class methods; the return value is obj. - - If it is a class, it must be a subclass of 'type'. This case is - used for class methods; the return value is obj. + - If it is an instance, it must be an instance of 'type'. This is + the normal case; the return value is obj.__class__. + + But... when obj is an instance, we want to allow for the case where + Py_TYPE(obj) is not a subclass of type, but obj.__class__ is! + This will allow using super() with a proxy for obj. + */ + + /* Check for first bullet above (special case) */ + if (PyType_Check(obj) && PyType_IsSubtype((PyTypeObject *)obj, type)) { + Py_INCREF(obj); + return (PyTypeObject *)obj; + } + + /* Normal case */ + if (PyType_IsSubtype(Py_TYPE(obj), type)) { + Py_INCREF(Py_TYPE(obj)); + return Py_TYPE(obj); + } + else { + /* Try the slow way */ + static PyObject *class_str = NULL; + PyObject *class_attr; + + if (class_str == NULL) { + class_str = PyUnicode_FromString("__class__"); + if (class_str == NULL) + return NULL; + } + + class_attr = PyObject_GetAttr(obj, class_str); + + if (class_attr != NULL && + PyType_Check(class_attr) && + (PyTypeObject *)class_attr != Py_TYPE(obj)) + { + int ok = PyType_IsSubtype( + (PyTypeObject *)class_attr, type); + if (ok) + return (PyTypeObject *)class_attr; + } - - If it is an instance, it must be an instance of 'type'. This is - the normal case; the return value is obj.__class__. - - But... when obj is an instance, we want to allow for the case where - Py_TYPE(obj) is not a subclass of type, but obj.__class__ is! - This will allow using super() with a proxy for obj. - */ - - /* Check for first bullet above (special case) */ - if (PyType_Check(obj) && PyType_IsSubtype((PyTypeObject *)obj, type)) { - Py_INCREF(obj); - return (PyTypeObject *)obj; - } - - /* Normal case */ - if (PyType_IsSubtype(Py_TYPE(obj), type)) { - Py_INCREF(Py_TYPE(obj)); - return Py_TYPE(obj); - } - else { - /* Try the slow way */ - static PyObject *class_str = NULL; - PyObject *class_attr; - - if (class_str == NULL) { - class_str = PyUnicode_FromString("__class__"); - if (class_str == NULL) - return NULL; - } - - class_attr = PyObject_GetAttr(obj, class_str); - - if (class_attr != NULL && - PyType_Check(class_attr) && - (PyTypeObject *)class_attr != Py_TYPE(obj)) - { - int ok = PyType_IsSubtype( - (PyTypeObject *)class_attr, type); - if (ok) - return (PyTypeObject *)class_attr; - } - - if (class_attr == NULL) - PyErr_Clear(); - else - Py_DECREF(class_attr); - } - - PyErr_SetString(PyExc_TypeError, - "super(type, obj): " - "obj must be an instance or subtype of type"); - return NULL; + if (class_attr == NULL) + PyErr_Clear(); + else + Py_DECREF(class_attr); + } + + PyErr_SetString(PyExc_TypeError, + "super(type, obj): " + "obj must be an instance or subtype of type"); + return NULL; } static PyObject * super_descr_get(PyObject *self, PyObject *obj, PyObject *type) { - superobject *su = (superobject *)self; - superobject *newobj; + superobject *su = (superobject *)self; + superobject *newobj; - if (obj == NULL || obj == Py_None || su->obj != NULL) { - /* Not binding to an object, or already bound */ - Py_INCREF(self); - return self; - } - if (Py_TYPE(su) != &PySuper_Type) - /* If su is an instance of a (strict) subclass of super, - call its type */ - return PyObject_CallFunctionObjArgs((PyObject *)Py_TYPE(su), - su->type, obj, NULL); - else { - /* Inline the common case */ - PyTypeObject *obj_type = supercheck(su->type, obj); - if (obj_type == NULL) - return NULL; - newobj = (superobject *)PySuper_Type.tp_new(&PySuper_Type, - NULL, NULL); - if (newobj == NULL) - return NULL; - Py_INCREF(su->type); - Py_INCREF(obj); - newobj->type = su->type; - newobj->obj = obj; - newobj->obj_type = obj_type; - return (PyObject *)newobj; - } + if (obj == NULL || obj == Py_None || su->obj != NULL) { + /* Not binding to an object, or already bound */ + Py_INCREF(self); + return self; + } + if (Py_TYPE(su) != &PySuper_Type) + /* If su is an instance of a (strict) subclass of super, + call its type */ + return PyObject_CallFunctionObjArgs((PyObject *)Py_TYPE(su), + su->type, obj, NULL); + else { + /* Inline the common case */ + PyTypeObject *obj_type = supercheck(su->type, obj); + if (obj_type == NULL) + return NULL; + newobj = (superobject *)PySuper_Type.tp_new(&PySuper_Type, + NULL, NULL); + if (newobj == NULL) + return NULL; + Py_INCREF(su->type); + Py_INCREF(obj); + newobj->type = su->type; + newobj->obj = obj; + newobj->obj_type = obj_type; + return (PyObject *)newobj; + } } static int super_init(PyObject *self, PyObject *args, PyObject *kwds) { - superobject *su = (superobject *)self; - PyTypeObject *type = NULL; - PyObject *obj = NULL; - PyTypeObject *obj_type = NULL; - - if (!_PyArg_NoKeywords("super", kwds)) - return -1; - if (!PyArg_ParseTuple(args, "|O!O:super", &PyType_Type, &type, &obj)) - return -1; - + superobject *su = (superobject *)self; + PyTypeObject *type = NULL; + PyObject *obj = NULL; + PyTypeObject *obj_type = NULL; + + if (!_PyArg_NoKeywords("super", kwds)) + return -1; + if (!PyArg_ParseTuple(args, "|O!O:super", &PyType_Type, &type, &obj)) + return -1; + + if (type == NULL) { + /* Call super(), without args -- fill in from __class__ + and first local variable on the stack. */ + PyFrameObject *f = PyThreadState_GET()->frame; + PyCodeObject *co = f->f_code; + int i, n; + if (co == NULL) { + PyErr_SetString(PyExc_SystemError, + "super(): no code object"); + return -1; + } + if (co->co_argcount == 0) { + PyErr_SetString(PyExc_SystemError, + "super(): no arguments"); + return -1; + } + obj = f->f_localsplus[0]; + if (obj == NULL) { + PyErr_SetString(PyExc_SystemError, + "super(): arg[0] deleted"); + return -1; + } + if (co->co_freevars == NULL) + n = 0; + else { + assert(PyTuple_Check(co->co_freevars)); + n = PyTuple_GET_SIZE(co->co_freevars); + } + for (i = 0; i < n; i++) { + PyObject *name = PyTuple_GET_ITEM(co->co_freevars, i); + assert(PyUnicode_Check(name)); + if (!PyUnicode_CompareWithASCIIString(name, + "__class__")) { + Py_ssize_t index = co->co_nlocals + + PyTuple_GET_SIZE(co->co_cellvars) + i; + PyObject *cell = f->f_localsplus[index]; + if (cell == NULL || !PyCell_Check(cell)) { + PyErr_SetString(PyExc_SystemError, + "super(): bad __class__ cell"); + return -1; + } + type = (PyTypeObject *) PyCell_GET(cell); + if (type == NULL) { + PyErr_SetString(PyExc_SystemError, + "super(): empty __class__ cell"); + return -1; + } + if (!PyType_Check(type)) { + PyErr_Format(PyExc_SystemError, + "super(): __class__ is not a type (%s)", + Py_TYPE(type)->tp_name); + return -1; + } + break; + } + } if (type == NULL) { - /* Call super(), without args -- fill in from __class__ - and first local variable on the stack. */ - PyFrameObject *f = PyThreadState_GET()->frame; - PyCodeObject *co = f->f_code; - int i, n; - if (co == NULL) { - PyErr_SetString(PyExc_SystemError, - "super(): no code object"); - return -1; - } - if (co->co_argcount == 0) { - PyErr_SetString(PyExc_SystemError, - "super(): no arguments"); - return -1; - } - obj = f->f_localsplus[0]; - if (obj == NULL) { - PyErr_SetString(PyExc_SystemError, - "super(): arg[0] deleted"); - return -1; - } - if (co->co_freevars == NULL) - n = 0; - else { - assert(PyTuple_Check(co->co_freevars)); - n = PyTuple_GET_SIZE(co->co_freevars); - } - for (i = 0; i < n; i++) { - PyObject *name = PyTuple_GET_ITEM(co->co_freevars, i); - assert(PyUnicode_Check(name)); - if (!PyUnicode_CompareWithASCIIString(name, - "__class__")) { - Py_ssize_t index = co->co_nlocals + - PyTuple_GET_SIZE(co->co_cellvars) + i; - PyObject *cell = f->f_localsplus[index]; - if (cell == NULL || !PyCell_Check(cell)) { - PyErr_SetString(PyExc_SystemError, - "super(): bad __class__ cell"); - return -1; - } - type = (PyTypeObject *) PyCell_GET(cell); - if (type == NULL) { - PyErr_SetString(PyExc_SystemError, - "super(): empty __class__ cell"); - return -1; - } - if (!PyType_Check(type)) { - PyErr_Format(PyExc_SystemError, - "super(): __class__ is not a type (%s)", - Py_TYPE(type)->tp_name); - return -1; - } - break; - } - } - if (type == NULL) { - PyErr_SetString(PyExc_SystemError, - "super(): __class__ cell not found"); - return -1; - } - } - - if (obj == Py_None) - obj = NULL; - if (obj != NULL) { - obj_type = supercheck(type, obj); - if (obj_type == NULL) - return -1; - Py_INCREF(obj); - } - Py_INCREF(type); - su->type = type; - su->obj = obj; - su->obj_type = obj_type; - return 0; + PyErr_SetString(PyExc_SystemError, + "super(): __class__ cell not found"); + return -1; + } + } + + if (obj == Py_None) + obj = NULL; + if (obj != NULL) { + obj_type = supercheck(type, obj); + if (obj_type == NULL) + return -1; + Py_INCREF(obj); + } + Py_INCREF(type); + su->type = type; + su->obj = obj; + su->obj_type = obj_type; + return 0; } PyDoc_STRVAR(super_doc, @@ -6216,65 +6216,65 @@ "Typical use to call a cooperative superclass method:\n" "class C(B):\n" " def meth(self, arg):\n" -" super().meth(arg)\n" +" super().meth(arg)\n" "This works for class methods too:\n" "class C(B):\n" " @classmethod\n" " def cmeth(cls, arg):\n" -" super().cmeth(arg)\n"); +" super().cmeth(arg)\n"); static int super_traverse(PyObject *self, visitproc visit, void *arg) { - superobject *su = (superobject *)self; + superobject *su = (superobject *)self; - Py_VISIT(su->obj); - Py_VISIT(su->type); - Py_VISIT(su->obj_type); + Py_VISIT(su->obj); + Py_VISIT(su->type); + Py_VISIT(su->obj_type); - return 0; + return 0; } PyTypeObject PySuper_Type = { - PyVarObject_HEAD_INIT(&PyType_Type, 0) - "super", /* tp_name */ - sizeof(superobject), /* tp_basicsize */ - 0, /* tp_itemsize */ - /* methods */ - super_dealloc, /* tp_dealloc */ - 0, /* tp_print */ - 0, /* tp_getattr */ - 0, /* tp_setattr */ - 0, /* tp_reserved */ - super_repr, /* tp_repr */ - 0, /* tp_as_number */ - 0, /* tp_as_sequence */ - 0, /* tp_as_mapping */ - 0, /* tp_hash */ - 0, /* tp_call */ - 0, /* tp_str */ - super_getattro, /* tp_getattro */ - 0, /* tp_setattro */ - 0, /* tp_as_buffer */ - Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC | - Py_TPFLAGS_BASETYPE, /* tp_flags */ - super_doc, /* tp_doc */ - super_traverse, /* tp_traverse */ - 0, /* tp_clear */ - 0, /* tp_richcompare */ - 0, /* tp_weaklistoffset */ - 0, /* tp_iter */ - 0, /* tp_iternext */ - 0, /* tp_methods */ - super_members, /* tp_members */ - 0, /* tp_getset */ - 0, /* tp_base */ - 0, /* tp_dict */ - super_descr_get, /* tp_descr_get */ - 0, /* tp_descr_set */ - 0, /* tp_dictoffset */ - super_init, /* tp_init */ - PyType_GenericAlloc, /* tp_alloc */ - PyType_GenericNew, /* tp_new */ - PyObject_GC_Del, /* tp_free */ + PyVarObject_HEAD_INIT(&PyType_Type, 0) + "super", /* tp_name */ + sizeof(superobject), /* tp_basicsize */ + 0, /* tp_itemsize */ + /* methods */ + super_dealloc, /* tp_dealloc */ + 0, /* tp_print */ + 0, /* tp_getattr */ + 0, /* tp_setattr */ + 0, /* tp_reserved */ + super_repr, /* tp_repr */ + 0, /* tp_as_number */ + 0, /* tp_as_sequence */ + 0, /* tp_as_mapping */ + 0, /* tp_hash */ + 0, /* tp_call */ + 0, /* tp_str */ + super_getattro, /* tp_getattro */ + 0, /* tp_setattro */ + 0, /* tp_as_buffer */ + Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC | + Py_TPFLAGS_BASETYPE, /* tp_flags */ + super_doc, /* tp_doc */ + super_traverse, /* tp_traverse */ + 0, /* tp_clear */ + 0, /* tp_richcompare */ + 0, /* tp_weaklistoffset */ + 0, /* tp_iter */ + 0, /* tp_iternext */ + 0, /* tp_methods */ + super_members, /* tp_members */ + 0, /* tp_getset */ + 0, /* tp_base */ + 0, /* tp_dict */ + super_descr_get, /* tp_descr_get */ + 0, /* tp_descr_set */ + 0, /* tp_dictoffset */ + super_init, /* tp_init */ + PyType_GenericAlloc, /* tp_alloc */ + PyType_GenericNew, /* tp_new */ + PyObject_GC_Del, /* tp_free */ }; Modified: python/branches/py3k-jit/Objects/weakrefobject.c ============================================================================== --- python/branches/py3k-jit/Objects/weakrefobject.c (original) +++ python/branches/py3k-jit/Objects/weakrefobject.c Mon May 10 23:55:43 2010 @@ -57,9 +57,9 @@ PyWeakref_GET_OBJECT(self)); if (*list == self) - /* If 'self' is the end of the list (and thus self->wr_next == NULL) - then the weakref list itself (and thus the value of *list) will - end up being set to NULL. */ + /* If 'self' is the end of the list (and thus self->wr_next == NULL) + then the weakref list itself (and thus the value of *list) will + end up being set to NULL. */ *list = self->wr_next; self->wr_object = Py_None; if (self->wr_prev != NULL) @@ -161,21 +161,21 @@ PyOS_snprintf(buffer, sizeof(buffer), "", self); } else { - char *name = NULL; - PyObject *nameobj = PyObject_GetAttrString(PyWeakref_GET_OBJECT(self), - "__name__"); - if (nameobj == NULL) - PyErr_Clear(); - else if (PyUnicode_Check(nameobj)) - name = _PyUnicode_AsString(nameobj); + char *name = NULL; + PyObject *nameobj = PyObject_GetAttrString(PyWeakref_GET_OBJECT(self), + "__name__"); + if (nameobj == NULL) + PyErr_Clear(); + else if (PyUnicode_Check(nameobj)) + name = _PyUnicode_AsString(nameobj); PyOS_snprintf(buffer, sizeof(buffer), - name ? "" - : "", - self, - Py_TYPE(PyWeakref_GET_OBJECT(self))->tp_name, - PyWeakref_GET_OBJECT(self), - name); - Py_XDECREF(nameobj); + name ? "" + : "", + self, + Py_TYPE(PyWeakref_GET_OBJECT(self))->tp_name, + PyWeakref_GET_OBJECT(self), + name); + Py_XDECREF(nameobj); } return PyUnicode_FromString(buffer); } @@ -188,8 +188,8 @@ weakref_richcompare(PyWeakReference* self, PyWeakReference* other, int op) { if ((op != Py_EQ && op != Py_NE) || - !PyWeakref_Check(self) || - !PyWeakref_Check(other)) { + !PyWeakref_Check(self) || + !PyWeakref_Check(other)) { Py_INCREF(Py_NotImplemented); return Py_NotImplemented; } @@ -339,10 +339,10 @@ sizeof(PyWeakReference), 0, weakref_dealloc, /*tp_dealloc*/ - 0, /*tp_print*/ + 0, /*tp_print*/ 0, /*tp_getattr*/ 0, /*tp_setattr*/ - 0, /*tp_reserved*/ + 0, /*tp_reserved*/ (reprfunc)weakref_repr, /*tp_repr*/ 0, /*tp_as_number*/ 0, /*tp_as_sequence*/ @@ -358,7 +358,7 @@ 0, /*tp_doc*/ (traverseproc)gc_traverse, /*tp_traverse*/ (inquiry)gc_clear, /*tp_clear*/ - (richcmpfunc)weakref_richcompare, /*tp_richcompare*/ + (richcmpfunc)weakref_richcompare, /*tp_richcompare*/ 0, /*tp_weaklistoffset*/ 0, /*tp_iter*/ 0, /*tp_iternext*/ @@ -438,9 +438,9 @@ #define WRAP_METHOD(method, special) \ static PyObject * \ method(PyObject *proxy) { \ - UNWRAP(proxy); \ - return PyObject_CallMethod(proxy, special, ""); \ - } + UNWRAP(proxy); \ + return PyObject_CallMethod(proxy, special, ""); \ + } /* direct slots */ @@ -454,9 +454,9 @@ { char buf[160]; PyOS_snprintf(buf, sizeof(buf), - "", proxy, - Py_TYPE(PyWeakref_GET_OBJECT(proxy))->tp_name, - PyWeakref_GET_OBJECT(proxy)); + "", proxy, + Py_TYPE(PyWeakref_GET_OBJECT(proxy))->tp_name, + PyWeakref_GET_OBJECT(proxy)); return PyUnicode_FromString(buf); } @@ -587,8 +587,8 @@ static PyMethodDef proxy_methods[] = { - {"__bytes__", (PyCFunction)proxy_bytes, METH_NOARGS}, - {NULL, NULL} + {"__bytes__", (PyCFunction)proxy_bytes, METH_NOARGS}, + {NULL, NULL} }; @@ -636,7 +636,7 @@ 0, /*sq_item*/ 0, /*sq_slice*/ 0, /*sq_ass_item*/ - 0, /*sq_ass_slice*/ + 0, /*sq_ass_slice*/ (objobjproc)proxy_contains, /* sq_contains */ }; @@ -655,20 +655,20 @@ 0, /* methods */ (destructor)proxy_dealloc, /* tp_dealloc */ - 0, /* tp_print */ - 0, /* tp_getattr */ - 0, /* tp_setattr */ - 0, /* tp_reserved */ - (reprfunc)proxy_repr, /* tp_repr */ - &proxy_as_number, /* tp_as_number */ - &proxy_as_sequence, /* tp_as_sequence */ - &proxy_as_mapping, /* tp_as_mapping */ - 0, /* tp_hash */ - 0, /* tp_call */ + 0, /* tp_print */ + 0, /* tp_getattr */ + 0, /* tp_setattr */ + 0, /* tp_reserved */ + (reprfunc)proxy_repr, /* tp_repr */ + &proxy_as_number, /* tp_as_number */ + &proxy_as_sequence, /* tp_as_sequence */ + &proxy_as_mapping, /* tp_as_mapping */ + 0, /* tp_hash */ + 0, /* tp_call */ proxy_str, /* tp_str */ proxy_getattr, /* tp_getattro */ (setattrofunc)proxy_setattr, /* tp_setattro */ - 0, /* tp_as_buffer */ + 0, /* tp_as_buffer */ Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC, /* tp_flags */ 0, /* tp_doc */ (traverseproc)gc_traverse, /* tp_traverse */ @@ -677,7 +677,7 @@ 0, /* tp_weaklistoffset */ (getiterfunc)proxy_iter, /* tp_iter */ (iternextfunc)proxy_iternext, /* tp_iternext */ - proxy_methods, /* tp_methods */ + proxy_methods, /* tp_methods */ }; @@ -689,20 +689,20 @@ 0, /* methods */ (destructor)proxy_dealloc, /* tp_dealloc */ - 0, /* tp_print */ - 0, /* tp_getattr */ - 0, /* tp_setattr */ - 0, /* tp_reserved */ - (unaryfunc)proxy_repr, /* tp_repr */ - &proxy_as_number, /* tp_as_number */ - &proxy_as_sequence, /* tp_as_sequence */ - &proxy_as_mapping, /* tp_as_mapping */ - 0, /* tp_hash */ - proxy_call, /* tp_call */ - proxy_str, /* tp_str */ + 0, /* tp_print */ + 0, /* tp_getattr */ + 0, /* tp_setattr */ + 0, /* tp_reserved */ + (unaryfunc)proxy_repr, /* tp_repr */ + &proxy_as_number, /* tp_as_number */ + &proxy_as_sequence, /* tp_as_sequence */ + &proxy_as_mapping, /* tp_as_mapping */ + 0, /* tp_hash */ + proxy_call, /* tp_call */ + proxy_str, /* tp_str */ proxy_getattr, /* tp_getattro */ (setattrofunc)proxy_setattr, /* tp_setattro */ - 0, /* tp_as_buffer */ + 0, /* tp_as_buffer */ Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC, /* tp_flags */ 0, /* tp_doc */ (traverseproc)gc_traverse, /* tp_traverse */ @@ -724,7 +724,7 @@ if (!PyType_SUPPORTS_WEAKREFS(Py_TYPE(ob))) { PyErr_Format(PyExc_TypeError, - "cannot create weak reference to '%s' object", + "cannot create weak reference to '%s' object", Py_TYPE(ob)->tp_name); return NULL; } @@ -783,7 +783,7 @@ if (!PyType_SUPPORTS_WEAKREFS(Py_TYPE(ob))) { PyErr_Format(PyExc_TypeError, - "cannot create weak reference to '%s' object", + "cannot create weak reference to '%s' object", Py_TYPE(ob)->tp_name); return NULL; } @@ -908,7 +908,7 @@ else { PyObject *tuple; Py_ssize_t i = 0; - + tuple = PyTuple_New(count * 2); if (tuple == NULL) { if (restore_error) Modified: python/branches/py3k-jit/PC/VS7.1/make_buildinfo.c ============================================================================== --- python/branches/py3k-jit/PC/VS7.1/make_buildinfo.c (original) +++ python/branches/py3k-jit/PC/VS7.1/make_buildinfo.c Mon May 10 23:55:43 2010 @@ -21,72 +21,72 @@ int make_buildinfo2() { - struct _stat st; - HKEY hTortoise; - char command[500]; - DWORD type, size; - if (_stat(".svn", &st) < 0) - return 0; - /* Allow suppression of subwcrev.exe invocation if a no_subwcrev file is present. */ - if (_stat("no_subwcrev", &st) == 0) - return 0; - if (RegOpenKey(HKEY_LOCAL_MACHINE, "Software\\TortoiseSVN", &hTortoise) != ERROR_SUCCESS && - RegOpenKey(HKEY_CURRENT_USER, "Software\\TortoiseSVN", &hTortoise) != ERROR_SUCCESS) - /* Tortoise not installed */ - return 0; - command[0] = '"'; /* quote the path to the executable */ - size = sizeof(command) - 1; - if (RegQueryValueEx(hTortoise, "Directory", 0, &type, command+1, &size) != ERROR_SUCCESS || - type != REG_SZ) - /* Registry corrupted */ - return 0; - strcat(command, "bin\\subwcrev.exe"); - if (_stat(command+1, &st) < 0) - /* subwcrev.exe not part of the release */ - return 0; - strcat(command, "\" ..\\.. ..\\..\\Modules\\getbuildinfo.c getbuildinfo2.c"); - puts(command); fflush(stdout); - if (system(command) < 0) - return 0; - return 1; + struct _stat st; + HKEY hTortoise; + char command[500]; + DWORD type, size; + if (_stat(".svn", &st) < 0) + return 0; + /* Allow suppression of subwcrev.exe invocation if a no_subwcrev file is present. */ + if (_stat("no_subwcrev", &st) == 0) + return 0; + if (RegOpenKey(HKEY_LOCAL_MACHINE, "Software\\TortoiseSVN", &hTortoise) != ERROR_SUCCESS && + RegOpenKey(HKEY_CURRENT_USER, "Software\\TortoiseSVN", &hTortoise) != ERROR_SUCCESS) + /* Tortoise not installed */ + return 0; + command[0] = '"'; /* quote the path to the executable */ + size = sizeof(command) - 1; + if (RegQueryValueEx(hTortoise, "Directory", 0, &type, command+1, &size) != ERROR_SUCCESS || + type != REG_SZ) + /* Registry corrupted */ + return 0; + strcat(command, "bin\\subwcrev.exe"); + if (_stat(command+1, &st) < 0) + /* subwcrev.exe not part of the release */ + return 0; + strcat(command, "\" ..\\.. ..\\..\\Modules\\getbuildinfo.c getbuildinfo2.c"); + puts(command); fflush(stdout); + if (system(command) < 0) + return 0; + return 1; } int main(int argc, char*argv[]) { - char command[500] = "cl.exe -c -D_WIN32 -DUSE_DL_EXPORT -D_WINDOWS -DWIN32 -D_WINDLL "; - int do_unlink, result; - if (argc != 2) { - fprintf(stderr, "make_buildinfo $(ConfigurationName)\n"); - return EXIT_FAILURE; - } - if (strcmp(argv[1], "Release") == 0) { - strcat(command, "-MD "); - } - else if (strcmp(argv[1], "Debug") == 0) { - strcat(command, "-D_DEBUG -MDd "); - } - else if (strcmp(argv[1], "ReleaseItanium") == 0) { - strcat(command, "-MD /USECL:MS_ITANIUM "); - } - else if (strcmp(argv[1], "ReleaseAMD64") == 0) { - strcat(command, "-MD "); - strcat(command, "-MD /USECL:MS_OPTERON "); - } - else { - fprintf(stderr, "unsupported configuration %s\n", argv[1]); - return EXIT_FAILURE; - } + char command[500] = "cl.exe -c -D_WIN32 -DUSE_DL_EXPORT -D_WINDOWS -DWIN32 -D_WINDLL "; + int do_unlink, result; + if (argc != 2) { + fprintf(stderr, "make_buildinfo $(ConfigurationName)\n"); + return EXIT_FAILURE; + } + if (strcmp(argv[1], "Release") == 0) { + strcat(command, "-MD "); + } + else if (strcmp(argv[1], "Debug") == 0) { + strcat(command, "-D_DEBUG -MDd "); + } + else if (strcmp(argv[1], "ReleaseItanium") == 0) { + strcat(command, "-MD /USECL:MS_ITANIUM "); + } + else if (strcmp(argv[1], "ReleaseAMD64") == 0) { + strcat(command, "-MD "); + strcat(command, "-MD /USECL:MS_OPTERON "); + } + else { + fprintf(stderr, "unsupported configuration %s\n", argv[1]); + return EXIT_FAILURE; + } - if ((do_unlink = make_buildinfo2())) - strcat(command, "getbuildinfo2.c -DSUBWCREV "); - else - strcat(command, "..\\..\\Modules\\getbuildinfo.c"); - strcat(command, " -Fogetbuildinfo.o -I..\\..\\Include -I..\\..\\PC"); - puts(command); fflush(stdout); - result = system(command); - if (do_unlink) - unlink("getbuildinfo2.c"); - if (result < 0) - return EXIT_FAILURE; - return 0; + if ((do_unlink = make_buildinfo2())) + strcat(command, "getbuildinfo2.c -DSUBWCREV "); + else + strcat(command, "..\\..\\Modules\\getbuildinfo.c"); + strcat(command, " -Fogetbuildinfo.o -I..\\..\\Include -I..\\..\\PC"); + puts(command); fflush(stdout); + result = system(command); + if (do_unlink) + unlink("getbuildinfo2.c"); + if (result < 0) + return EXIT_FAILURE; + return 0; } Modified: python/branches/py3k-jit/PC/VS8.0/make_buildinfo.c ============================================================================== --- python/branches/py3k-jit/PC/VS8.0/make_buildinfo.c (original) +++ python/branches/py3k-jit/PC/VS8.0/make_buildinfo.c Mon May 10 23:55:43 2010 @@ -23,72 +23,72 @@ int make_buildinfo2() { - struct _stat st; - HKEY hTortoise; - char command[CMD_SIZE+1]; - DWORD type, size; - if (_stat(".svn", &st) < 0) - return 0; - /* Allow suppression of subwcrev.exe invocation if a no_subwcrev file is present. */ - if (_stat("no_subwcrev", &st) == 0) - return 0; - if (RegOpenKey(HKEY_LOCAL_MACHINE, "Software\\TortoiseSVN", &hTortoise) != ERROR_SUCCESS && - RegOpenKey(HKEY_CURRENT_USER, "Software\\TortoiseSVN", &hTortoise) != ERROR_SUCCESS) - /* Tortoise not installed */ - return 0; - command[0] = '"'; /* quote the path to the executable */ - size = sizeof(command) - 1; - if (RegQueryValueEx(hTortoise, "Directory", 0, &type, command+1, &size) != ERROR_SUCCESS || - type != REG_SZ) - /* Registry corrupted */ - return 0; - strcat_s(command, CMD_SIZE, "bin\\subwcrev.exe"); - if (_stat(command+1, &st) < 0) - /* subwcrev.exe not part of the release */ - return 0; - strcat_s(command, CMD_SIZE, "\" ..\\.. ..\\..\\Modules\\getbuildinfo.c getbuildinfo2.c"); - puts(command); fflush(stdout); - if (system(command) < 0) - return 0; - return 1; + struct _stat st; + HKEY hTortoise; + char command[CMD_SIZE+1]; + DWORD type, size; + if (_stat(".svn", &st) < 0) + return 0; + /* Allow suppression of subwcrev.exe invocation if a no_subwcrev file is present. */ + if (_stat("no_subwcrev", &st) == 0) + return 0; + if (RegOpenKey(HKEY_LOCAL_MACHINE, "Software\\TortoiseSVN", &hTortoise) != ERROR_SUCCESS && + RegOpenKey(HKEY_CURRENT_USER, "Software\\TortoiseSVN", &hTortoise) != ERROR_SUCCESS) + /* Tortoise not installed */ + return 0; + command[0] = '"'; /* quote the path to the executable */ + size = sizeof(command) - 1; + if (RegQueryValueEx(hTortoise, "Directory", 0, &type, command+1, &size) != ERROR_SUCCESS || + type != REG_SZ) + /* Registry corrupted */ + return 0; + strcat_s(command, CMD_SIZE, "bin\\subwcrev.exe"); + if (_stat(command+1, &st) < 0) + /* subwcrev.exe not part of the release */ + return 0; + strcat_s(command, CMD_SIZE, "\" ..\\.. ..\\..\\Modules\\getbuildinfo.c getbuildinfo2.c"); + puts(command); fflush(stdout); + if (system(command) < 0) + return 0; + return 1; } int main(int argc, char*argv[]) { - char command[500] = "cl.exe -c -D_WIN32 -DUSE_DL_EXPORT -D_WINDOWS -DWIN32 -D_WINDLL "; - int do_unlink, result; - if (argc != 2) { - fprintf(stderr, "make_buildinfo $(ConfigurationName)\n"); - return EXIT_FAILURE; - } - if (strcmp(argv[1], "Release") == 0) { - strcat_s(command, CMD_SIZE, "-MD "); - } - else if (strcmp(argv[1], "Debug") == 0) { - strcat_s(command, CMD_SIZE, "-D_DEBUG -MDd "); - } - else if (strcmp(argv[1], "ReleaseItanium") == 0) { - strcat_s(command, CMD_SIZE, "-MD /USECL:MS_ITANIUM "); - } - else if (strcmp(argv[1], "ReleaseAMD64") == 0) { - strcat_s(command, CMD_SIZE, "-MD "); - strcat_s(command, CMD_SIZE, "-MD /USECL:MS_OPTERON "); - } - else { - fprintf(stderr, "unsupported configuration %s\n", argv[1]); - return EXIT_FAILURE; - } + char command[500] = "cl.exe -c -D_WIN32 -DUSE_DL_EXPORT -D_WINDOWS -DWIN32 -D_WINDLL "; + int do_unlink, result; + if (argc != 2) { + fprintf(stderr, "make_buildinfo $(ConfigurationName)\n"); + return EXIT_FAILURE; + } + if (strcmp(argv[1], "Release") == 0) { + strcat_s(command, CMD_SIZE, "-MD "); + } + else if (strcmp(argv[1], "Debug") == 0) { + strcat_s(command, CMD_SIZE, "-D_DEBUG -MDd "); + } + else if (strcmp(argv[1], "ReleaseItanium") == 0) { + strcat_s(command, CMD_SIZE, "-MD /USECL:MS_ITANIUM "); + } + else if (strcmp(argv[1], "ReleaseAMD64") == 0) { + strcat_s(command, CMD_SIZE, "-MD "); + strcat_s(command, CMD_SIZE, "-MD /USECL:MS_OPTERON "); + } + else { + fprintf(stderr, "unsupported configuration %s\n", argv[1]); + return EXIT_FAILURE; + } - if ((do_unlink = make_buildinfo2())) - strcat_s(command, CMD_SIZE, "getbuildinfo2.c -DSUBWCREV "); - else - strcat_s(command, CMD_SIZE, "..\\..\\Modules\\getbuildinfo.c"); - strcat_s(command, CMD_SIZE, " -Fogetbuildinfo.o -I..\\..\\Include -I..\\..\\PC"); - puts(command); fflush(stdout); - result = system(command); - if (do_unlink) - _unlink("getbuildinfo2.c"); - if (result < 0) - return EXIT_FAILURE; - return 0; -} \ No newline at end of file + if ((do_unlink = make_buildinfo2())) + strcat_s(command, CMD_SIZE, "getbuildinfo2.c -DSUBWCREV "); + else + strcat_s(command, CMD_SIZE, "..\\..\\Modules\\getbuildinfo.c"); + strcat_s(command, CMD_SIZE, " -Fogetbuildinfo.o -I..\\..\\Include -I..\\..\\PC"); + puts(command); fflush(stdout); + result = system(command); + if (do_unlink) + _unlink("getbuildinfo2.c"); + if (result < 0) + return EXIT_FAILURE; + return 0; +} Modified: python/branches/py3k-jit/PC/_msi.c ============================================================================== --- python/branches/py3k-jit/PC/_msi.c (original) +++ python/branches/py3k-jit/PC/_msi.c Mon May 10 23:55:43 2010 @@ -20,19 +20,19 @@ UUID result; unsigned short *cresult; PyObject *oresult; - + /* May return ok, local only, and no address. For local only, the documentation says we still get a uuid. For RPC_S_UUID_NO_ADDRESS, it's not clear whether we can use the result. */ if (UuidCreate(&result) == RPC_S_UUID_NO_ADDRESS) { - PyErr_SetString(PyExc_NotImplementedError, "processing 'no address' result"); - return NULL; + PyErr_SetString(PyExc_NotImplementedError, "processing 'no address' result"); + return NULL; } if (UuidToStringW(&result, &cresult) == RPC_S_OUT_OF_MEMORY) { - PyErr_SetString(PyExc_MemoryError, "out of memory in uuidgen"); - return NULL; + PyErr_SetString(PyExc_MemoryError, "out of memory in uuidgen"); + return NULL; } oresult = PyUnicode_FromUnicode(cresult, wcslen(cresult)); @@ -57,7 +57,7 @@ { int result = _open(pszFile, oflag, pmode); if (result == -1) - *err = errno; + *err = errno; return result; } @@ -65,7 +65,7 @@ { UINT result = (UINT)_read(hf, memory, cb); if (result != cb) - *err = errno; + *err = errno; return result; } @@ -73,7 +73,7 @@ { UINT result = (UINT)_write(hf, memory, cb); if (result != cb) - *err = errno; + *err = errno; return result; } @@ -81,7 +81,7 @@ { int result = _close(hf); if (result != 0) - *err = errno; + *err = errno; return result; } @@ -89,7 +89,7 @@ { long result = (long)_lseek(hf, dist, seektype); if (result == -1) - *err = errno; + *err = errno; return result; } @@ -97,7 +97,7 @@ { int result = remove(pszFile); if (result != 0) - *err = errno; + *err = errno; return result; } @@ -110,9 +110,9 @@ { char *name = _tempnam("", "tmp"); if ((name != NULL) && ((int)strlen(name) < cbTempName)) { - strcpy(pszTempName, name); - free(name); - return TRUE; + strcpy(pszTempName, name); + free(name); + return TRUE; } if (name) free(name); @@ -122,10 +122,10 @@ static FNFCISTATUS(cb_status) { if (pv) { - PyObject *result = PyObject_CallMethod(pv, "status", "iii", typeStatus, cb1, cb2); - if (result == NULL) - return -1; - Py_DECREF(result); + PyObject *result = PyObject_CallMethod(pv, "status", "iii", typeStatus, cb1, cb2); + if (result == NULL) + return -1; + Py_DECREF(result); } return 0; } @@ -133,18 +133,18 @@ static FNFCIGETNEXTCABINET(cb_getnextcabinet) { if (pv) { - PyObject *result = PyObject_CallMethod(pv, "getnextcabinet", "i", pccab->iCab); - if (result == NULL) - return -1; - if (!PyBytes_Check(result)) { - PyErr_Format(PyExc_TypeError, - "Incorrect return type %s from getnextcabinet", - result->ob_type->tp_name); - Py_DECREF(result); - return FALSE; - } - strncpy(pccab->szCab, PyBytes_AsString(result), sizeof(pccab->szCab)); - return TRUE; + PyObject *result = PyObject_CallMethod(pv, "getnextcabinet", "i", pccab->iCab); + if (result == NULL) + return -1; + if (!PyBytes_Check(result)) { + PyErr_Format(PyExc_TypeError, + "Incorrect return type %s from getnextcabinet", + result->ob_type->tp_name); + Py_DECREF(result); + return FALSE; + } + strncpy(pccab->szCab, PyBytes_AsString(result), sizeof(pccab->szCab)); + return TRUE; } return FALSE; } @@ -157,21 +157,21 @@ /* Need Win32 handle to get time stamps */ handle = CreateFile(pszName, GENERIC_READ, FILE_SHARE_READ, NULL, - OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL); + OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL); if (handle == INVALID_HANDLE_VALUE) - return -1; + return -1; if (GetFileInformationByHandle(handle, &bhfi) == FALSE) { - CloseHandle(handle); - return -1; + CloseHandle(handle); + return -1; } FileTimeToLocalFileTime(&bhfi.ftLastWriteTime, &filetime); FileTimeToDosDateTime(&filetime, pdate, ptime); - *pattribs = (int)(bhfi.dwFileAttributes & - (_A_RDONLY | _A_SYSTEM | _A_HIDDEN | _A_ARCH)); + *pattribs = (int)(bhfi.dwFileAttributes & + (_A_RDONLY | _A_SYSTEM | _A_HIDDEN | _A_ARCH)); CloseHandle(handle); @@ -189,11 +189,11 @@ if (!PyArg_ParseTuple(args, "sO:FCICreate", &cabname, &files)) - return NULL; + return NULL; if (!PyList_Check(files)) { - PyErr_SetString(PyExc_TypeError, "FCICreate expects a list"); - return NULL; + PyErr_SetString(PyExc_TypeError, "FCICreate expects a list"); + return NULL; } ccab.cb = INT_MAX; /* no need to split CAB into multiple media */ @@ -209,49 +209,49 @@ ccab.szDisk[0] = '\0'; for (i = 0, p = cabname; *p; p = CharNext(p)) - if (*p == '\\' || *p == '/') - i = p - cabname + 1; + if (*p == '\\' || *p == '/') + i = p - cabname + 1; if (i >= sizeof(ccab.szCabPath) || - strlen(cabname+i) >= sizeof(ccab.szCab)) { - PyErr_SetString(PyExc_ValueError, "path name too long"); - return 0; + strlen(cabname+i) >= sizeof(ccab.szCab)) { + PyErr_SetString(PyExc_ValueError, "path name too long"); + return 0; } if (i > 0) { - memcpy(ccab.szCabPath, cabname, i); - ccab.szCabPath[i] = '\0'; - strcpy(ccab.szCab, cabname+i); + memcpy(ccab.szCabPath, cabname, i); + ccab.szCabPath[i] = '\0'; + strcpy(ccab.szCab, cabname+i); } else { - strcpy(ccab.szCabPath, ".\\"); - strcpy(ccab.szCab, cabname); + strcpy(ccab.szCabPath, ".\\"); + strcpy(ccab.szCab, cabname); } hfci = FCICreate(&erf, cb_fileplaced, cb_alloc, cb_free, - cb_open, cb_read, cb_write, cb_close, cb_seek, cb_delete, - cb_gettempfile, &ccab, NULL); + cb_open, cb_read, cb_write, cb_close, cb_seek, cb_delete, + cb_gettempfile, &ccab, NULL); if (hfci == NULL) { - PyErr_Format(PyExc_ValueError, "FCI error %d", erf.erfOper); - return NULL; + PyErr_Format(PyExc_ValueError, "FCI error %d", erf.erfOper); + return NULL; } for (i=0; i < PyList_GET_SIZE(files); i++) { - PyObject *item = PyList_GET_ITEM(files, i); - char *filename, *cabname; - if (!PyArg_ParseTuple(item, "ss", &filename, &cabname)) - goto err; - if (!FCIAddFile(hfci, filename, cabname, FALSE, - cb_getnextcabinet, cb_status, cb_getopeninfo, - tcompTYPE_MSZIP)) - goto err; + PyObject *item = PyList_GET_ITEM(files, i); + char *filename, *cabname; + if (!PyArg_ParseTuple(item, "ss", &filename, &cabname)) + goto err; + if (!FCIAddFile(hfci, filename, cabname, FALSE, + cb_getnextcabinet, cb_status, cb_getopeninfo, + tcompTYPE_MSZIP)) + goto err; } if (!FCIFlushCabinet(hfci, FALSE, cb_getnextcabinet, cb_status)) - goto err; + goto err; if (!FCIDestroy(hfci)) - goto err; + goto err; Py_INCREF(Py_None); return Py_None; @@ -266,7 +266,7 @@ MSIHANDLE h; }msiobj; -static void +static void msiobj_dealloc(msiobj* msidb) { MsiCloseHandle(msidb->h); @@ -292,41 +292,41 @@ MSIHANDLE err = MsiGetLastErrorRecord(); if (err == 0) { - switch(status) { - case ERROR_ACCESS_DENIED: - PyErr_SetString(MSIError, "access denied"); - return NULL; - case ERROR_FUNCTION_FAILED: - PyErr_SetString(MSIError, "function failed"); - return NULL; - case ERROR_INVALID_DATA: - PyErr_SetString(MSIError, "invalid data"); - return NULL; - case ERROR_INVALID_HANDLE: - PyErr_SetString(MSIError, "invalid handle"); - return NULL; - case ERROR_INVALID_STATE: - PyErr_SetString(MSIError, "invalid state"); - return NULL; - case ERROR_INVALID_PARAMETER: - PyErr_SetString(MSIError, "invalid parameter"); - return NULL; - default: - PyErr_Format(MSIError, "unknown error %x", status); - return NULL; - } + switch(status) { + case ERROR_ACCESS_DENIED: + PyErr_SetString(MSIError, "access denied"); + return NULL; + case ERROR_FUNCTION_FAILED: + PyErr_SetString(MSIError, "function failed"); + return NULL; + case ERROR_INVALID_DATA: + PyErr_SetString(MSIError, "invalid data"); + return NULL; + case ERROR_INVALID_HANDLE: + PyErr_SetString(MSIError, "invalid handle"); + return NULL; + case ERROR_INVALID_STATE: + PyErr_SetString(MSIError, "invalid state"); + return NULL; + case ERROR_INVALID_PARAMETER: + PyErr_SetString(MSIError, "invalid parameter"); + return NULL; + default: + PyErr_Format(MSIError, "unknown error %x", status); + return NULL; + } } code = MsiRecordGetInteger(err, 1); /* XXX code */ if (MsiFormatRecord(0, err, res, &size) == ERROR_MORE_DATA) { - res = malloc(size+1); - MsiFormatRecord(0, err, res, &size); - res[size]='\0'; + res = malloc(size+1); + MsiFormatRecord(0, err, res, &size); + res[size]='\0'; } MsiCloseHandle(err); PyErr_SetString(MSIError, res); if (res != buf) - free(res); + free(res); return NULL; } @@ -343,7 +343,7 @@ { unsigned int field; int status; - + if (!PyArg_ParseTuple(args, "I:GetInteger", &field)) return NULL; status = MsiRecordGetInteger(record->h, field); @@ -363,7 +363,7 @@ WCHAR *res = buf; DWORD size = sizeof(buf); PyObject* string; - + if (!PyArg_ParseTuple(args, "I:GetString", &field)) return NULL; status = MsiRecordGetStringW(record->h, field, res, &size); @@ -386,7 +386,7 @@ { int status = MsiRecordClearData(record->h); if (status != ERROR_SUCCESS) - return msierror(status); + return msierror(status); Py_INCREF(Py_None); return Py_None; @@ -400,10 +400,10 @@ Py_UNICODE *data; if (!PyArg_ParseTuple(args, "iu:SetString", &field, &data)) - return NULL; + return NULL; if ((status = MsiRecordSetStringW(record->h, field, data)) != ERROR_SUCCESS) - return msierror(status); + return msierror(status); Py_INCREF(Py_None); return Py_None; @@ -417,10 +417,10 @@ Py_UNICODE *data; if (!PyArg_ParseTuple(args, "iu:SetStream", &field, &data)) - return NULL; + return NULL; if ((status = MsiRecordSetStreamW(record->h, field, data)) != ERROR_SUCCESS) - return msierror(status); + return msierror(status); Py_INCREF(Py_None); return Py_None; @@ -434,10 +434,10 @@ int data; if (!PyArg_ParseTuple(args, "ii:SetInteger", &field, &data)) - return NULL; + return NULL; if ((status = MsiRecordSetInteger(record->h, field, data)) != ERROR_SUCCESS) - return msierror(status); + return msierror(status); Py_INCREF(Py_None); return Py_None; @@ -446,39 +446,39 @@ static PyMethodDef record_methods[] = { - { "GetFieldCount", (PyCFunction)record_getfieldcount, METH_NOARGS, - PyDoc_STR("GetFieldCount() -> int\nWraps MsiRecordGetFieldCount")}, + { "GetFieldCount", (PyCFunction)record_getfieldcount, METH_NOARGS, + PyDoc_STR("GetFieldCount() -> int\nWraps MsiRecordGetFieldCount")}, { "GetInteger", (PyCFunction)record_getinteger, METH_VARARGS, PyDoc_STR("GetInteger(field) -> int\nWraps MsiRecordGetInteger")}, { "GetString", (PyCFunction)record_getstring, METH_VARARGS, PyDoc_STR("GetString(field) -> string\nWraps MsiRecordGetString")}, - { "SetString", (PyCFunction)record_setstring, METH_VARARGS, - PyDoc_STR("SetString(field,str) -> None\nWraps MsiRecordSetString")}, - { "SetStream", (PyCFunction)record_setstream, METH_VARARGS, - PyDoc_STR("SetStream(field,filename) -> None\nWraps MsiRecordSetInteger")}, - { "SetInteger", (PyCFunction)record_setinteger, METH_VARARGS, - PyDoc_STR("SetInteger(field,int) -> None\nWraps MsiRecordSetInteger")}, - { "ClearData", (PyCFunction)record_cleardata, METH_NOARGS, - PyDoc_STR("ClearData() -> int\nWraps MsiRecordGClearData")}, + { "SetString", (PyCFunction)record_setstring, METH_VARARGS, + PyDoc_STR("SetString(field,str) -> None\nWraps MsiRecordSetString")}, + { "SetStream", (PyCFunction)record_setstream, METH_VARARGS, + PyDoc_STR("SetStream(field,filename) -> None\nWraps MsiRecordSetInteger")}, + { "SetInteger", (PyCFunction)record_setinteger, METH_VARARGS, + PyDoc_STR("SetInteger(field,int) -> None\nWraps MsiRecordSetInteger")}, + { "ClearData", (PyCFunction)record_cleardata, METH_NOARGS, + PyDoc_STR("ClearData() -> int\nWraps MsiRecordGClearData")}, { NULL, NULL } }; static PyTypeObject record_Type = { - PyVarObject_HEAD_INIT(NULL, 0) - "_msi.Record", /*tp_name*/ - sizeof(msiobj), /*tp_basicsize*/ - 0, /*tp_itemsize*/ - /* methods */ - (destructor)msiobj_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*/ + PyVarObject_HEAD_INIT(NULL, 0) + "_msi.Record", /*tp_name*/ + sizeof(msiobj), /*tp_basicsize*/ + 0, /*tp_itemsize*/ + /* methods */ + (destructor)msiobj_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*/ @@ -513,8 +513,8 @@ msiobj *result = PyObject_NEW(struct msiobj, &record_Type); if (!result) { - MsiCloseHandle(h); - return NULL; + MsiCloseHandle(h); + return NULL; } result->h = h; @@ -537,27 +537,27 @@ DWORD ssize = sizeof(sval); if (!PyArg_ParseTuple(args, "i:GetProperty", &field)) - return NULL; + return NULL; - status = MsiSummaryInfoGetProperty(si->h, field, &type, &ival, - &fval, sval, &ssize); + status = MsiSummaryInfoGetProperty(si->h, field, &type, &ival, + &fval, sval, &ssize); if (status == ERROR_MORE_DATA) { - sval = malloc(ssize); - status = MsiSummaryInfoGetProperty(si->h, field, &type, &ival, - &fval, sval, &ssize); + sval = malloc(ssize); + status = MsiSummaryInfoGetProperty(si->h, field, &type, &ival, + &fval, sval, &ssize); } switch(type) { - case VT_I2: case VT_I4: - return PyLong_FromLong(ival); - case VT_FILETIME: - PyErr_SetString(PyExc_NotImplementedError, "FILETIME result"); - return NULL; - case VT_LPSTR: - result = PyBytes_FromStringAndSize(sval, ssize); - if (sval != sbuf) - free(sval); - return result; + case VT_I2: case VT_I4: + return PyLong_FromLong(ival); + case VT_FILETIME: + PyErr_SetString(PyExc_NotImplementedError, "FILETIME result"); + return NULL; + case VT_LPSTR: + result = PyBytes_FromStringAndSize(sval, ssize); + if (sval != sbuf) + free(sval); + return result; } PyErr_Format(PyExc_NotImplementedError, "result of type %d", type); return NULL; @@ -571,7 +571,7 @@ status = MsiSummaryInfoGetPropertyCount(si->h, &result); if (status != ERROR_SUCCESS) - return msierror(status); + return msierror(status); return PyLong_FromLong(result); } @@ -584,25 +584,25 @@ PyObject* data; if (!PyArg_ParseTuple(args, "iO:SetProperty", &field, &data)) - return NULL; + return NULL; if (PyUnicode_Check(data)) { - status = MsiSummaryInfoSetPropertyW(si->h, field, VT_LPSTR, - 0, NULL, PyUnicode_AsUnicode(data)); + status = MsiSummaryInfoSetPropertyW(si->h, field, VT_LPSTR, + 0, NULL, PyUnicode_AsUnicode(data)); } else if (PyLong_CheckExact(data)) { - long value = PyLong_AsLong(data); - if (value == -1 && PyErr_Occurred()) { - return NULL; - } - status = MsiSummaryInfoSetProperty(si->h, field, VT_I4, - value, NULL, NULL); + long value = PyLong_AsLong(data); + if (value == -1 && PyErr_Occurred()) { + return NULL; + } + status = MsiSummaryInfoSetProperty(si->h, field, VT_I4, + value, NULL, NULL); } else { - PyErr_SetString(PyExc_TypeError, "unsupported type"); - return NULL; + PyErr_SetString(PyExc_TypeError, "unsupported type"); + return NULL; } - + if (status != ERROR_SUCCESS) - return msierror(status); + return msierror(status); Py_INCREF(Py_None); return Py_None; @@ -616,39 +616,39 @@ status = MsiSummaryInfoPersist(si->h); if (status != ERROR_SUCCESS) - return msierror(status); + return msierror(status); Py_INCREF(Py_None); return Py_None; } static PyMethodDef summary_methods[] = { - { "GetProperty", (PyCFunction)summary_getproperty, METH_VARARGS, - PyDoc_STR("GetProperty(propid) -> value\nWraps MsiSummaryInfoGetProperty")}, - { "GetPropertyCount", (PyCFunction)summary_getpropertycount, METH_NOARGS, - PyDoc_STR("GetProperty() -> int\nWraps MsiSummaryInfoGetPropertyCount")}, - { "SetProperty", (PyCFunction)summary_setproperty, METH_VARARGS, - PyDoc_STR("SetProperty(value) -> None\nWraps MsiSummaryInfoProperty")}, - { "Persist", (PyCFunction)summary_persist, METH_NOARGS, - PyDoc_STR("Persist() -> None\nWraps MsiSummaryInfoPersist")}, + { "GetProperty", (PyCFunction)summary_getproperty, METH_VARARGS, + PyDoc_STR("GetProperty(propid) -> value\nWraps MsiSummaryInfoGetProperty")}, + { "GetPropertyCount", (PyCFunction)summary_getpropertycount, METH_NOARGS, + PyDoc_STR("GetProperty() -> int\nWraps MsiSummaryInfoGetPropertyCount")}, + { "SetProperty", (PyCFunction)summary_setproperty, METH_VARARGS, + PyDoc_STR("SetProperty(value) -> None\nWraps MsiSummaryInfoProperty")}, + { "Persist", (PyCFunction)summary_persist, METH_NOARGS, + PyDoc_STR("Persist() -> None\nWraps MsiSummaryInfoPersist")}, { NULL, NULL } }; static PyTypeObject summary_Type = { - PyVarObject_HEAD_INIT(NULL, 0) - "_msi.SummaryInformation", /*tp_name*/ - sizeof(msiobj), /*tp_basicsize*/ - 0, /*tp_itemsize*/ - /* methods */ - (destructor)msiobj_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*/ + PyVarObject_HEAD_INIT(NULL, 0) + "_msi.SummaryInformation", /*tp_name*/ + sizeof(msiobj), /*tp_basicsize*/ + 0, /*tp_itemsize*/ + /* methods */ + (destructor)msiobj_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*/ @@ -687,7 +687,7 @@ PyObject *oparams = Py_None; if (!PyArg_ParseTuple(args, "O:Execute", &oparams)) - return NULL; + return NULL; if (oparams != Py_None) { if (oparams->ob_type != &record_Type) { @@ -699,7 +699,7 @@ status = MsiViewExecute(view->h, params); if (status != ERROR_SUCCESS) - return msierror(status); + return msierror(status); Py_INCREF(Py_None); return Py_None; @@ -712,7 +712,7 @@ MSIHANDLE result; if ((status = MsiViewFetch(view->h, &result)) != ERROR_SUCCESS) - return msierror(status); + return msierror(status); return record_new(result); } @@ -725,10 +725,10 @@ MSIHANDLE result; if (!PyArg_ParseTuple(args, "i:GetColumnInfo", &kind)) - return NULL; + return NULL; if ((status = MsiViewGetColumnInfo(view->h, kind, &result)) != ERROR_SUCCESS) - return msierror(status); + return msierror(status); return record_new(result); } @@ -741,15 +741,15 @@ int status; if (!PyArg_ParseTuple(args, "iO:Modify", &kind, &data)) - return NULL; + return NULL; if (data->ob_type != &record_Type) { - PyErr_SetString(PyExc_TypeError, "Modify expects a record object"); - return NULL; + PyErr_SetString(PyExc_TypeError, "Modify expects a record object"); + return NULL; } if ((status = MsiViewModify(view->h, kind, ((msiobj*)data)->h)) != ERROR_SUCCESS) - return msierror(status); + return msierror(status); Py_INCREF(Py_None); return Py_None; @@ -761,42 +761,42 @@ int status; if ((status = MsiViewClose(view->h)) != ERROR_SUCCESS) - return msierror(status); + return msierror(status); Py_INCREF(Py_None); return Py_None; } static PyMethodDef view_methods[] = { - { "Execute", (PyCFunction)view_execute, METH_VARARGS, - PyDoc_STR("Execute(params=None) -> None\nWraps MsiViewExecute")}, + { "Execute", (PyCFunction)view_execute, METH_VARARGS, + PyDoc_STR("Execute(params=None) -> None\nWraps MsiViewExecute")}, { "GetColumnInfo", (PyCFunction)view_getcolumninfo, METH_VARARGS, - PyDoc_STR("GetColumnInfo() -> result\nWraps MsiGetColumnInfo")}, + PyDoc_STR("GetColumnInfo() -> result\nWraps MsiGetColumnInfo")}, { "Fetch", (PyCFunction)view_fetch, METH_NOARGS, - PyDoc_STR("Fetch() -> result\nWraps MsiViewFetch")}, + PyDoc_STR("Fetch() -> result\nWraps MsiViewFetch")}, { "Modify", (PyCFunction)view_modify, METH_VARARGS, - PyDoc_STR("Modify(mode,record) -> None\nWraps MsiViewModify")}, + PyDoc_STR("Modify(mode,record) -> None\nWraps MsiViewModify")}, { "Close", (PyCFunction)view_close, METH_NOARGS, - PyDoc_STR("Close() -> result\nWraps MsiViewClose")}, + PyDoc_STR("Close() -> result\nWraps MsiViewClose")}, { NULL, NULL } }; static PyTypeObject msiview_Type = { - PyVarObject_HEAD_INIT(NULL, 0) - "_msi.View", /*tp_name*/ - sizeof(msiobj), /*tp_basicsize*/ - 0, /*tp_itemsize*/ - /* methods */ - (destructor)msiobj_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*/ + PyVarObject_HEAD_INIT(NULL, 0) + "_msi.View", /*tp_name*/ + sizeof(msiobj), /*tp_basicsize*/ + 0, /*tp_itemsize*/ + /* methods */ + (destructor)msiobj_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*/ @@ -836,15 +836,15 @@ msiobj *result; if (!PyArg_ParseTuple(args, "s:OpenView", &sql)) - return NULL; + return NULL; if ((status = MsiDatabaseOpenView(msidb->h, sql, &hView)) != ERROR_SUCCESS) - return msierror(status); + return msierror(status); result = PyObject_NEW(struct msiobj, &msiview_Type); if (!result) { - MsiCloseHandle(hView); - return NULL; + MsiCloseHandle(hView); + return NULL; } result->h = hView; @@ -857,7 +857,7 @@ int status; if ((status = MsiDatabaseCommit(msidb->h)) != ERROR_SUCCESS) - return msierror(status); + return msierror(status); Py_INCREF(Py_None); return Py_None; @@ -872,16 +872,16 @@ msiobj *oresult; if (!PyArg_ParseTuple(args, "i:GetSummaryInformation", &count)) - return NULL; + return NULL; status = MsiGetSummaryInformation(db->h, NULL, count, &result); if (status != ERROR_SUCCESS) - return msierror(status); + return msierror(status); oresult = PyObject_NEW(struct msiobj, &summary_Type); if (!result) { - MsiCloseHandle(result); - return NULL; + MsiCloseHandle(result); + return NULL; } oresult->h = result; @@ -889,31 +889,31 @@ } static PyMethodDef db_methods[] = { - { "OpenView", (PyCFunction)msidb_openview, METH_VARARGS, - PyDoc_STR("OpenView(sql) -> viewobj\nWraps MsiDatabaseOpenView")}, + { "OpenView", (PyCFunction)msidb_openview, METH_VARARGS, + PyDoc_STR("OpenView(sql) -> viewobj\nWraps MsiDatabaseOpenView")}, { "Commit", (PyCFunction)msidb_commit, METH_NOARGS, - PyDoc_STR("Commit() -> None\nWraps MsiDatabaseCommit")}, - { "GetSummaryInformation", (PyCFunction)msidb_getsummaryinformation, METH_VARARGS, - PyDoc_STR("GetSummaryInformation(updateCount) -> viewobj\nWraps MsiGetSummaryInformation")}, + PyDoc_STR("Commit() -> None\nWraps MsiDatabaseCommit")}, + { "GetSummaryInformation", (PyCFunction)msidb_getsummaryinformation, METH_VARARGS, + PyDoc_STR("GetSummaryInformation(updateCount) -> viewobj\nWraps MsiGetSummaryInformation")}, { NULL, NULL } }; static PyTypeObject msidb_Type = { - PyVarObject_HEAD_INIT(NULL, 0) - "_msi.Database", /*tp_name*/ - sizeof(msiobj), /*tp_basicsize*/ - 0, /*tp_itemsize*/ - /* methods */ - (destructor)msiobj_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*/ + PyVarObject_HEAD_INIT(NULL, 0) + "_msi.Database", /*tp_name*/ + sizeof(msiobj), /*tp_basicsize*/ + 0, /*tp_itemsize*/ + /* methods */ + (destructor)msiobj_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*/ @@ -949,18 +949,18 @@ int persist; MSIHANDLE h; msiobj *result; - + if (!PyArg_ParseTuple(args, "si:MSIOpenDatabase", &path, &persist)) - return NULL; + return NULL; - status = MsiOpenDatabase(path, (LPCSTR)persist, &h); + status = MsiOpenDatabase(path, (LPCSTR)persist, &h); if (status != ERROR_SUCCESS) - return msierror(status); + return msierror(status); result = PyObject_NEW(struct msiobj, &msidb_Type); if (!result) { - MsiCloseHandle(h); - return NULL; + MsiCloseHandle(h); + return NULL; } result->h = h; return (PyObject*)result; @@ -973,11 +973,11 @@ MSIHANDLE h; if (!PyArg_ParseTuple(args, "i:CreateRecord", &count)) - return NULL; - + return NULL; + h = MsiCreateRecord(count); if (h == 0) - return msierror(0); + return msierror(0); return record_new(h); } @@ -985,29 +985,29 @@ static PyMethodDef msi_methods[] = { {"UuidCreate", (PyCFunction)uuidcreate, METH_NOARGS, - PyDoc_STR("UuidCreate() -> string")}, - {"FCICreate", (PyCFunction)fcicreate, METH_VARARGS, - PyDoc_STR("fcicreate(cabname,files) -> None")}, - {"OpenDatabase", (PyCFunction)msiopendb, METH_VARARGS, - PyDoc_STR("OpenDatabase(name, flags) -> dbobj\nWraps MsiOpenDatabase")}, - {"CreateRecord", (PyCFunction)createrecord, METH_VARARGS, - PyDoc_STR("OpenDatabase(name, flags) -> dbobj\nWraps MsiCreateRecord")}, - {NULL, NULL} /* sentinel */ + PyDoc_STR("UuidCreate() -> string")}, + {"FCICreate", (PyCFunction)fcicreate, METH_VARARGS, + PyDoc_STR("fcicreate(cabname,files) -> None")}, + {"OpenDatabase", (PyCFunction)msiopendb, METH_VARARGS, + PyDoc_STR("OpenDatabase(name, flags) -> dbobj\nWraps MsiOpenDatabase")}, + {"CreateRecord", (PyCFunction)createrecord, METH_VARARGS, + PyDoc_STR("OpenDatabase(name, flags) -> dbobj\nWraps MsiCreateRecord")}, + {NULL, NULL} /* sentinel */ }; static char msi_doc[] = "Documentation"; static struct PyModuleDef _msimodule = { - PyModuleDef_HEAD_INIT, - "_msi", - msi_doc, - -1, - msi_methods, - NULL, - NULL, - NULL, - NULL + PyModuleDef_HEAD_INIT, + "_msi", + msi_doc, + -1, + msi_methods, + NULL, + NULL, + NULL, + NULL }; PyMODINIT_FUNC @@ -1017,7 +1017,7 @@ m = PyModule_Create(&_msimodule); if (m == NULL) - return NULL; + return NULL; PyModule_AddIntConstant(m, "MSIDBOPEN_CREATEDIRECT", (int)MSIDBOPEN_CREATEDIRECT); PyModule_AddIntConstant(m, "MSIDBOPEN_CREATE", (int)MSIDBOPEN_CREATE); @@ -1063,7 +1063,7 @@ MSIError = PyErr_NewException ("_msi.MSIError", NULL, NULL); if (!MSIError) - return NULL; + return NULL; PyModule_AddObject(m, "MSIError", MSIError); return m; } Modified: python/branches/py3k-jit/PC/_subprocess.c ============================================================================== --- python/branches/py3k-jit/PC/_subprocess.c (original) +++ python/branches/py3k-jit/PC/_subprocess.c Mon May 10 23:55:43 2010 @@ -46,8 +46,8 @@ the wrapper is used to provide Detach and Close methods */ typedef struct { - PyObject_HEAD - HANDLE handle; + PyObject_HEAD + HANDLE handle; } sp_handle_object; static PyTypeObject sp_handle_type; @@ -55,104 +55,104 @@ static PyObject* sp_handle_new(HANDLE handle) { - sp_handle_object* self; + sp_handle_object* self; - self = PyObject_NEW(sp_handle_object, &sp_handle_type); - if (self == NULL) - return NULL; + self = PyObject_NEW(sp_handle_object, &sp_handle_type); + if (self == NULL) + return NULL; - self->handle = handle; + self->handle = handle; - return (PyObject*) self; + return (PyObject*) self; } #if defined(MS_WIN32) && !defined(MS_WIN64) -#define HANDLE_TO_PYNUM(handle) PyLong_FromLong((long) handle) -#define PY_HANDLE_PARAM "l" +#define HANDLE_TO_PYNUM(handle) PyLong_FromLong((long) handle) +#define PY_HANDLE_PARAM "l" #else -#define HANDLE_TO_PYNUM(handle) PyLong_FromLongLong((long long) handle) -#define PY_HANDLE_PARAM "L" +#define HANDLE_TO_PYNUM(handle) PyLong_FromLongLong((long long) handle) +#define PY_HANDLE_PARAM "L" #endif static PyObject* sp_handle_detach(sp_handle_object* self, PyObject* args) { - HANDLE handle; + HANDLE handle; - if (! PyArg_ParseTuple(args, ":Detach")) - return NULL; + if (! PyArg_ParseTuple(args, ":Detach")) + return NULL; - handle = self->handle; + handle = self->handle; - self->handle = INVALID_HANDLE_VALUE; + self->handle = INVALID_HANDLE_VALUE; - /* note: return the current handle, as an integer */ - return HANDLE_TO_PYNUM(handle); + /* note: return the current handle, as an integer */ + return HANDLE_TO_PYNUM(handle); } static PyObject* sp_handle_close(sp_handle_object* self, PyObject* args) { - if (! PyArg_ParseTuple(args, ":Close")) - return NULL; + if (! PyArg_ParseTuple(args, ":Close")) + return NULL; - if (self->handle != INVALID_HANDLE_VALUE) { - CloseHandle(self->handle); - self->handle = INVALID_HANDLE_VALUE; - } - Py_INCREF(Py_None); - return Py_None; + if (self->handle != INVALID_HANDLE_VALUE) { + CloseHandle(self->handle); + self->handle = INVALID_HANDLE_VALUE; + } + Py_INCREF(Py_None); + return Py_None; } static void sp_handle_dealloc(sp_handle_object* self) { - if (self->handle != INVALID_HANDLE_VALUE) - CloseHandle(self->handle); - PyObject_FREE(self); + if (self->handle != INVALID_HANDLE_VALUE) + CloseHandle(self->handle); + PyObject_FREE(self); } static PyMethodDef sp_handle_methods[] = { - {"Detach", (PyCFunction) sp_handle_detach, METH_VARARGS}, - {"Close", (PyCFunction) sp_handle_close, METH_VARARGS}, - {NULL, NULL} + {"Detach", (PyCFunction) sp_handle_detach, METH_VARARGS}, + {"Close", (PyCFunction) sp_handle_close, METH_VARARGS}, + {NULL, NULL} }; static PyObject* sp_handle_as_int(sp_handle_object* self) { - return HANDLE_TO_PYNUM(self->handle); + return HANDLE_TO_PYNUM(self->handle); } static PyNumberMethods sp_handle_as_number; static PyTypeObject sp_handle_type = { - PyVarObject_HEAD_INIT(NULL, 0) - "_subprocess_handle", sizeof(sp_handle_object), 0, - (destructor) sp_handle_dealloc, /*tp_dealloc*/ - 0, /*tp_print*/ - 0, /*tp_getattr*/ - 0, /*tp_setattr*/ - 0, /*tp_reserved*/ - 0, /*tp_repr*/ - &sp_handle_as_number, /*tp_as_number */ - 0, /*tp_as_sequence */ - 0, /*tp_as_mapping */ - 0, /*tp_hash*/ - 0, /*tp_call*/ - 0, /*tp_str*/ - 0, /*tp_getattro*/ - 0, /*tp_setattro*/ - 0, /*tp_as_buffer*/ - Py_TPFLAGS_DEFAULT, /*tp_flags*/ - 0, /*tp_doc*/ - 0, /*tp_traverse*/ - 0, /*tp_clear*/ - 0, /*tp_richcompare*/ - 0, /*tp_weaklistoffset*/ - 0, /*tp_iter*/ - 0, /*tp_iternext*/ - sp_handle_methods, /*tp_methods*/ + PyVarObject_HEAD_INIT(NULL, 0) + "_subprocess_handle", sizeof(sp_handle_object), 0, + (destructor) sp_handle_dealloc, /*tp_dealloc*/ + 0, /*tp_print*/ + 0, /*tp_getattr*/ + 0, /*tp_setattr*/ + 0, /*tp_reserved*/ + 0, /*tp_repr*/ + &sp_handle_as_number, /*tp_as_number */ + 0, /*tp_as_sequence */ + 0, /*tp_as_mapping */ + 0, /*tp_hash*/ + 0, /*tp_call*/ + 0, /*tp_str*/ + 0, /*tp_getattro*/ + 0, /*tp_setattro*/ + 0, /*tp_as_buffer*/ + Py_TPFLAGS_DEFAULT, /*tp_flags*/ + 0, /*tp_doc*/ + 0, /*tp_traverse*/ + 0, /*tp_clear*/ + 0, /*tp_richcompare*/ + 0, /*tp_weaklistoffset*/ + 0, /*tp_iter*/ + 0, /*tp_iternext*/ + sp_handle_methods, /*tp_methods*/ }; /* -------------------------------------------------------------------- */ @@ -168,26 +168,26 @@ static PyObject * sp_GetStdHandle(PyObject* self, PyObject* args) { - HANDLE handle; - int std_handle; + HANDLE handle; + int std_handle; - if (! PyArg_ParseTuple(args, "i:GetStdHandle", &std_handle)) - return NULL; + if (! PyArg_ParseTuple(args, "i:GetStdHandle", &std_handle)) + return NULL; - Py_BEGIN_ALLOW_THREADS - handle = GetStdHandle((DWORD) std_handle); - Py_END_ALLOW_THREADS - - if (handle == INVALID_HANDLE_VALUE) - return PyErr_SetFromWindowsErr(GetLastError()); - - if (! handle) { - Py_INCREF(Py_None); - return Py_None; - } + Py_BEGIN_ALLOW_THREADS + handle = GetStdHandle((DWORD) std_handle); + Py_END_ALLOW_THREADS + + if (handle == INVALID_HANDLE_VALUE) + return PyErr_SetFromWindowsErr(GetLastError()); + + if (! handle) { + Py_INCREF(Py_None); + return Py_None; + } - /* note: returns integer, not handle object */ - return HANDLE_TO_PYNUM(handle); + /* note: returns integer, not handle object */ + return HANDLE_TO_PYNUM(handle); } PyDoc_STRVAR(GetCurrentProcess_doc, @@ -198,10 +198,10 @@ static PyObject * sp_GetCurrentProcess(PyObject* self, PyObject* args) { - if (! PyArg_ParseTuple(args, ":GetCurrentProcess")) - return NULL; + if (! PyArg_ParseTuple(args, ":GetCurrentProcess")) + return NULL; - return sp_handle_new(GetCurrentProcess()); + return sp_handle_new(GetCurrentProcess()); } PyDoc_STRVAR(DuplicateHandle_doc, @@ -218,43 +218,43 @@ static PyObject * sp_DuplicateHandle(PyObject* self, PyObject* args) { - HANDLE target_handle; - BOOL result; + HANDLE target_handle; + BOOL result; - HANDLE source_process_handle; - HANDLE source_handle; - HANDLE target_process_handle; - int desired_access; - int inherit_handle; - int options = 0; - - if (! PyArg_ParseTuple(args, - PY_HANDLE_PARAM PY_HANDLE_PARAM PY_HANDLE_PARAM - "ii|i:DuplicateHandle", - &source_process_handle, - &source_handle, - &target_process_handle, - &desired_access, - &inherit_handle, - &options)) - return NULL; - - Py_BEGIN_ALLOW_THREADS - result = DuplicateHandle( - source_process_handle, - source_handle, - target_process_handle, - &target_handle, - desired_access, - inherit_handle, - options - ); - Py_END_ALLOW_THREADS + HANDLE source_process_handle; + HANDLE source_handle; + HANDLE target_process_handle; + int desired_access; + int inherit_handle; + int options = 0; + + if (! PyArg_ParseTuple(args, + PY_HANDLE_PARAM PY_HANDLE_PARAM PY_HANDLE_PARAM + "ii|i:DuplicateHandle", + &source_process_handle, + &source_handle, + &target_process_handle, + &desired_access, + &inherit_handle, + &options)) + return NULL; + + Py_BEGIN_ALLOW_THREADS + result = DuplicateHandle( + source_process_handle, + source_handle, + target_process_handle, + &target_handle, + desired_access, + inherit_handle, + options + ); + Py_END_ALLOW_THREADS - if (! result) - return PyErr_SetFromWindowsErr(GetLastError()); + if (! result) + return PyErr_SetFromWindowsErr(GetLastError()); - return sp_handle_new(target_handle); + return sp_handle_new(target_handle); } PyDoc_STRVAR(CreatePipe_doc, @@ -268,25 +268,25 @@ static PyObject * sp_CreatePipe(PyObject* self, PyObject* args) { - HANDLE read_pipe; - HANDLE write_pipe; - BOOL result; + HANDLE read_pipe; + HANDLE write_pipe; + BOOL result; - PyObject* pipe_attributes; /* ignored */ - int size; + PyObject* pipe_attributes; /* ignored */ + int size; - if (! PyArg_ParseTuple(args, "Oi:CreatePipe", &pipe_attributes, &size)) - return NULL; + if (! PyArg_ParseTuple(args, "Oi:CreatePipe", &pipe_attributes, &size)) + return NULL; - Py_BEGIN_ALLOW_THREADS - result = CreatePipe(&read_pipe, &write_pipe, NULL, size); - Py_END_ALLOW_THREADS + Py_BEGIN_ALLOW_THREADS + result = CreatePipe(&read_pipe, &write_pipe, NULL, size); + Py_END_ALLOW_THREADS - if (! result) - return PyErr_SetFromWindowsErr(GetLastError()); + if (! result) + return PyErr_SetFromWindowsErr(GetLastError()); - return Py_BuildValue( - "NN", sp_handle_new(read_pipe), sp_handle_new(write_pipe)); + return Py_BuildValue( + "NN", sp_handle_new(read_pipe), sp_handle_new(write_pipe)); } /* helpers for createprocess */ @@ -294,110 +294,110 @@ static int getint(PyObject* obj, char* name) { - PyObject* value; - int ret; + PyObject* value; + int ret; - value = PyObject_GetAttrString(obj, name); - if (! value) { - PyErr_Clear(); /* FIXME: propagate error? */ - return 0; - } - ret = (int) PyLong_AsLong(value); - Py_DECREF(value); - return ret; + value = PyObject_GetAttrString(obj, name); + if (! value) { + PyErr_Clear(); /* FIXME: propagate error? */ + return 0; + } + ret = (int) PyLong_AsLong(value); + Py_DECREF(value); + return ret; } static HANDLE gethandle(PyObject* obj, char* name) { - sp_handle_object* value; - HANDLE ret; + sp_handle_object* value; + HANDLE ret; - value = (sp_handle_object*) PyObject_GetAttrString(obj, name); - if (! value) { - PyErr_Clear(); /* FIXME: propagate error? */ - return NULL; - } - if (Py_TYPE(value) != &sp_handle_type) - ret = NULL; - else - ret = value->handle; - Py_DECREF(value); - return ret; + value = (sp_handle_object*) PyObject_GetAttrString(obj, name); + if (! value) { + PyErr_Clear(); /* FIXME: propagate error? */ + return NULL; + } + if (Py_TYPE(value) != &sp_handle_type) + ret = NULL; + else + ret = value->handle; + Py_DECREF(value); + return ret; } static PyObject* getenvironment(PyObject* environment) { - int i, envsize; - PyObject* out = NULL; - PyObject* keys; - PyObject* values; - Py_UNICODE* p; - - /* convert environment dictionary to windows enviroment string */ - if (! PyMapping_Check(environment)) { - PyErr_SetString( - PyExc_TypeError, "environment must be dictionary or None"); - return NULL; - } - - envsize = PyMapping_Length(environment); - - keys = PyMapping_Keys(environment); - values = PyMapping_Values(environment); - if (!keys || !values) - goto error; - - out = PyUnicode_FromUnicode(NULL, 2048); - if (! out) - goto error; - - p = PyUnicode_AS_UNICODE(out); - - for (i = 0; i < envsize; i++) { - int ksize, vsize, totalsize; - PyObject* key = PyList_GET_ITEM(keys, i); - PyObject* value = PyList_GET_ITEM(values, i); - - if (! PyUnicode_Check(key) || ! PyUnicode_Check(value)) { - PyErr_SetString(PyExc_TypeError, - "environment can only contain strings"); - goto error; - } - ksize = PyUnicode_GET_SIZE(key); - vsize = PyUnicode_GET_SIZE(value); - totalsize = (p - PyUnicode_AS_UNICODE(out)) + ksize + 1 + - vsize + 1 + 1; - if (totalsize > PyUnicode_GET_SIZE(out)) { - int offset = p - PyUnicode_AS_UNICODE(out); - PyUnicode_Resize(&out, totalsize + 1024); - p = PyUnicode_AS_UNICODE(out) + offset; - } - Py_UNICODE_COPY(p, PyUnicode_AS_UNICODE(key), ksize); - p += ksize; - *p++ = '='; - Py_UNICODE_COPY(p, PyUnicode_AS_UNICODE(value), vsize); - p += vsize; - *p++ = '\0'; - } - - /* add trailing null byte */ - *p++ = '\0'; - PyUnicode_Resize(&out, p - PyUnicode_AS_UNICODE(out)); + int i, envsize; + PyObject* out = NULL; + PyObject* keys; + PyObject* values; + Py_UNICODE* p; + + /* convert environment dictionary to windows enviroment string */ + if (! PyMapping_Check(environment)) { + PyErr_SetString( + PyExc_TypeError, "environment must be dictionary or None"); + return NULL; + } + + envsize = PyMapping_Length(environment); + + keys = PyMapping_Keys(environment); + values = PyMapping_Values(environment); + if (!keys || !values) + goto error; + + out = PyUnicode_FromUnicode(NULL, 2048); + if (! out) + goto error; + + p = PyUnicode_AS_UNICODE(out); + + for (i = 0; i < envsize; i++) { + int ksize, vsize, totalsize; + PyObject* key = PyList_GET_ITEM(keys, i); + PyObject* value = PyList_GET_ITEM(values, i); + + if (! PyUnicode_Check(key) || ! PyUnicode_Check(value)) { + PyErr_SetString(PyExc_TypeError, + "environment can only contain strings"); + goto error; + } + ksize = PyUnicode_GET_SIZE(key); + vsize = PyUnicode_GET_SIZE(value); + totalsize = (p - PyUnicode_AS_UNICODE(out)) + ksize + 1 + + vsize + 1 + 1; + if (totalsize > PyUnicode_GET_SIZE(out)) { + int offset = p - PyUnicode_AS_UNICODE(out); + PyUnicode_Resize(&out, totalsize + 1024); + p = PyUnicode_AS_UNICODE(out) + offset; + } + Py_UNICODE_COPY(p, PyUnicode_AS_UNICODE(key), ksize); + p += ksize; + *p++ = '='; + Py_UNICODE_COPY(p, PyUnicode_AS_UNICODE(value), vsize); + p += vsize; + *p++ = '\0'; + } + + /* add trailing null byte */ + *p++ = '\0'; + PyUnicode_Resize(&out, p - PyUnicode_AS_UNICODE(out)); - /* PyObject_Print(out, stdout, 0); */ + /* PyObject_Print(out, stdout, 0); */ - Py_XDECREF(keys); - Py_XDECREF(values); + Py_XDECREF(keys); + Py_XDECREF(values); - return out; + return out; error: - Py_XDECREF(out); - Py_XDECREF(keys); - Py_XDECREF(values); - return NULL; + Py_XDECREF(out); + Py_XDECREF(keys); + Py_XDECREF(values); + return NULL; } PyDoc_STRVAR(CreateProcess_doc, @@ -415,77 +415,77 @@ static PyObject * sp_CreateProcess(PyObject* self, PyObject* args) { - BOOL result; - PROCESS_INFORMATION pi; - STARTUPINFOW si; - PyObject* environment; - - Py_UNICODE* application_name; - Py_UNICODE* command_line; - PyObject* process_attributes; /* ignored */ - PyObject* thread_attributes; /* ignored */ - int inherit_handles; - int creation_flags; - PyObject* env_mapping; - Py_UNICODE* current_directory; - PyObject* startup_info; - - if (! PyArg_ParseTuple(args, "ZZOOiiOZO:CreateProcess", - &application_name, - &command_line, - &process_attributes, - &thread_attributes, - &inherit_handles, - &creation_flags, - &env_mapping, - ¤t_directory, - &startup_info)) - return NULL; - - ZeroMemory(&si, sizeof(si)); - si.cb = sizeof(si); - - /* note: we only support a small subset of all SI attributes */ - si.dwFlags = getint(startup_info, "dwFlags"); - si.wShowWindow = getint(startup_info, "wShowWindow"); - si.hStdInput = gethandle(startup_info, "hStdInput"); - si.hStdOutput = gethandle(startup_info, "hStdOutput"); - si.hStdError = gethandle(startup_info, "hStdError"); - - if (PyErr_Occurred()) - return NULL; - - if (env_mapping == Py_None) - environment = NULL; - else { - environment = getenvironment(env_mapping); - if (! environment) - return NULL; - } - - Py_BEGIN_ALLOW_THREADS - result = CreateProcessW(application_name, - command_line, - NULL, - NULL, - inherit_handles, - creation_flags | CREATE_UNICODE_ENVIRONMENT, - environment ? PyUnicode_AS_UNICODE(environment) : NULL, - current_directory, - &si, - &pi); - Py_END_ALLOW_THREADS - - Py_XDECREF(environment); - - if (! result) - return PyErr_SetFromWindowsErr(GetLastError()); - - return Py_BuildValue("NNii", - sp_handle_new(pi.hProcess), - sp_handle_new(pi.hThread), - pi.dwProcessId, - pi.dwThreadId); + BOOL result; + PROCESS_INFORMATION pi; + STARTUPINFOW si; + PyObject* environment; + + Py_UNICODE* application_name; + Py_UNICODE* command_line; + PyObject* process_attributes; /* ignored */ + PyObject* thread_attributes; /* ignored */ + int inherit_handles; + int creation_flags; + PyObject* env_mapping; + Py_UNICODE* current_directory; + PyObject* startup_info; + + if (! PyArg_ParseTuple(args, "ZZOOiiOZO:CreateProcess", + &application_name, + &command_line, + &process_attributes, + &thread_attributes, + &inherit_handles, + &creation_flags, + &env_mapping, + ¤t_directory, + &startup_info)) + return NULL; + + ZeroMemory(&si, sizeof(si)); + si.cb = sizeof(si); + + /* note: we only support a small subset of all SI attributes */ + si.dwFlags = getint(startup_info, "dwFlags"); + si.wShowWindow = getint(startup_info, "wShowWindow"); + si.hStdInput = gethandle(startup_info, "hStdInput"); + si.hStdOutput = gethandle(startup_info, "hStdOutput"); + si.hStdError = gethandle(startup_info, "hStdError"); + + if (PyErr_Occurred()) + return NULL; + + if (env_mapping == Py_None) + environment = NULL; + else { + environment = getenvironment(env_mapping); + if (! environment) + return NULL; + } + + Py_BEGIN_ALLOW_THREADS + result = CreateProcessW(application_name, + command_line, + NULL, + NULL, + inherit_handles, + creation_flags | CREATE_UNICODE_ENVIRONMENT, + environment ? PyUnicode_AS_UNICODE(environment) : NULL, + current_directory, + &si, + &pi); + Py_END_ALLOW_THREADS + + Py_XDECREF(environment); + + if (! result) + return PyErr_SetFromWindowsErr(GetLastError()); + + return Py_BuildValue("NNii", + sp_handle_new(pi.hProcess), + sp_handle_new(pi.hThread), + pi.dwProcessId, + pi.dwThreadId); } PyDoc_STRVAR(TerminateProcess_doc, @@ -496,21 +496,21 @@ static PyObject * sp_TerminateProcess(PyObject* self, PyObject* args) { - BOOL result; + BOOL result; - HANDLE process; - int exit_code; - if (! PyArg_ParseTuple(args, PY_HANDLE_PARAM "i:TerminateProcess", - &process, &exit_code)) - return NULL; + HANDLE process; + int exit_code; + if (! PyArg_ParseTuple(args, PY_HANDLE_PARAM "i:TerminateProcess", + &process, &exit_code)) + return NULL; - result = TerminateProcess(process, exit_code); + result = TerminateProcess(process, exit_code); - if (! result) - return PyErr_SetFromWindowsErr(GetLastError()); + if (! result) + return PyErr_SetFromWindowsErr(GetLastError()); - Py_INCREF(Py_None); - return Py_None; + Py_INCREF(Py_None); + return Py_None; } PyDoc_STRVAR(GetExitCodeProcess_doc, @@ -521,19 +521,19 @@ static PyObject * sp_GetExitCodeProcess(PyObject* self, PyObject* args) { - DWORD exit_code; - BOOL result; + DWORD exit_code; + BOOL result; - HANDLE process; - if (! PyArg_ParseTuple(args, PY_HANDLE_PARAM ":GetExitCodeProcess", &process)) - return NULL; + HANDLE process; + if (! PyArg_ParseTuple(args, PY_HANDLE_PARAM ":GetExitCodeProcess", &process)) + return NULL; - result = GetExitCodeProcess(process, &exit_code); + result = GetExitCodeProcess(process, &exit_code); - if (! result) - return PyErr_SetFromWindowsErr(GetLastError()); + if (! result) + return PyErr_SetFromWindowsErr(GetLastError()); - return PyLong_FromLong(exit_code); + return PyLong_FromLong(exit_code); } PyDoc_STRVAR(WaitForSingleObject_doc, @@ -546,23 +546,23 @@ static PyObject * sp_WaitForSingleObject(PyObject* self, PyObject* args) { - DWORD result; + DWORD result; - HANDLE handle; - int milliseconds; - if (! PyArg_ParseTuple(args, PY_HANDLE_PARAM "i:WaitForSingleObject", - &handle, - &milliseconds)) - return NULL; - - Py_BEGIN_ALLOW_THREADS - result = WaitForSingleObject(handle, (DWORD) milliseconds); - Py_END_ALLOW_THREADS + HANDLE handle; + int milliseconds; + if (! PyArg_ParseTuple(args, PY_HANDLE_PARAM "i:WaitForSingleObject", + &handle, + &milliseconds)) + return NULL; + + Py_BEGIN_ALLOW_THREADS + result = WaitForSingleObject(handle, (DWORD) milliseconds); + Py_END_ALLOW_THREADS - if (result == WAIT_FAILED) - return PyErr_SetFromWindowsErr(GetLastError()); + if (result == WAIT_FAILED) + return PyErr_SetFromWindowsErr(GetLastError()); - return PyLong_FromLong((int) result); + return PyLong_FromLong((int) result); } PyDoc_STRVAR(GetVersion_doc, @@ -573,10 +573,10 @@ static PyObject * sp_GetVersion(PyObject* self, PyObject* args) { - if (! PyArg_ParseTuple(args, ":GetVersion")) - return NULL; + if (! PyArg_ParseTuple(args, ":GetVersion")) + return NULL; - return PyLong_FromLong((int) GetVersion()); + return PyLong_FromLong((int) GetVersion()); } PyDoc_STRVAR(GetModuleFileName_doc, @@ -594,41 +594,41 @@ static PyObject * sp_GetModuleFileName(PyObject* self, PyObject* args) { - BOOL result; - HMODULE module; - WCHAR filename[MAX_PATH]; + BOOL result; + HMODULE module; + WCHAR filename[MAX_PATH]; - if (! PyArg_ParseTuple(args, PY_HANDLE_PARAM ":GetModuleFileName", - &module)) - return NULL; + if (! PyArg_ParseTuple(args, PY_HANDLE_PARAM ":GetModuleFileName", + &module)) + return NULL; - result = GetModuleFileNameW(module, filename, MAX_PATH); - filename[MAX_PATH-1] = '\0'; + result = GetModuleFileNameW(module, filename, MAX_PATH); + filename[MAX_PATH-1] = '\0'; - if (! result) - return PyErr_SetFromWindowsErr(GetLastError()); + if (! result) + return PyErr_SetFromWindowsErr(GetLastError()); - return PyUnicode_FromUnicode(filename, Py_UNICODE_strlen(filename)); + return PyUnicode_FromUnicode(filename, Py_UNICODE_strlen(filename)); } static PyMethodDef sp_functions[] = { - {"GetStdHandle", sp_GetStdHandle, METH_VARARGS, GetStdHandle_doc}, - {"GetCurrentProcess", sp_GetCurrentProcess, METH_VARARGS, - GetCurrentProcess_doc}, - {"DuplicateHandle", sp_DuplicateHandle, METH_VARARGS, - DuplicateHandle_doc}, - {"CreatePipe", sp_CreatePipe, METH_VARARGS, CreatePipe_doc}, - {"CreateProcess", sp_CreateProcess, METH_VARARGS, CreateProcess_doc}, - {"TerminateProcess", sp_TerminateProcess, METH_VARARGS, - TerminateProcess_doc}, - {"GetExitCodeProcess", sp_GetExitCodeProcess, METH_VARARGS, - GetExitCodeProcess_doc}, - {"WaitForSingleObject", sp_WaitForSingleObject, METH_VARARGS, - WaitForSingleObject_doc}, - {"GetVersion", sp_GetVersion, METH_VARARGS, GetVersion_doc}, - {"GetModuleFileName", sp_GetModuleFileName, METH_VARARGS, - GetModuleFileName_doc}, - {NULL, NULL} + {"GetStdHandle", sp_GetStdHandle, METH_VARARGS, GetStdHandle_doc}, + {"GetCurrentProcess", sp_GetCurrentProcess, METH_VARARGS, + GetCurrentProcess_doc}, + {"DuplicateHandle", sp_DuplicateHandle, METH_VARARGS, + DuplicateHandle_doc}, + {"CreatePipe", sp_CreatePipe, METH_VARARGS, CreatePipe_doc}, + {"CreateProcess", sp_CreateProcess, METH_VARARGS, CreateProcess_doc}, + {"TerminateProcess", sp_TerminateProcess, METH_VARARGS, + TerminateProcess_doc}, + {"GetExitCodeProcess", sp_GetExitCodeProcess, METH_VARARGS, + GetExitCodeProcess_doc}, + {"WaitForSingleObject", sp_WaitForSingleObject, METH_VARARGS, + WaitForSingleObject_doc}, + {"GetVersion", sp_GetVersion, METH_VARARGS, GetVersion_doc}, + {"GetModuleFileName", sp_GetModuleFileName, METH_VARARGS, + GetModuleFileName_doc}, + {NULL, NULL} }; /* -------------------------------------------------------------------- */ @@ -636,53 +636,53 @@ static void defint(PyObject* d, const char* name, int value) { - PyObject* v = PyLong_FromLong((long) value); - if (v) { - PyDict_SetItemString(d, (char*) name, v); - Py_DECREF(v); - } + PyObject* v = PyLong_FromLong((long) value); + if (v) { + PyDict_SetItemString(d, (char*) name, v); + Py_DECREF(v); + } } static struct PyModuleDef _subprocessmodule = { - PyModuleDef_HEAD_INIT, - "_subprocess", - NULL, - -1, - sp_functions, - NULL, - NULL, - NULL, - NULL + PyModuleDef_HEAD_INIT, + "_subprocess", + NULL, + -1, + sp_functions, + NULL, + NULL, + NULL, + NULL }; PyMODINIT_FUNC PyInit__subprocess() { - PyObject *d; - PyObject *m; + PyObject *d; + PyObject *m; - /* patch up object descriptors */ - sp_handle_as_number.nb_int = (unaryfunc) sp_handle_as_int; - if (PyType_Ready(&sp_handle_type) < 0) - return NULL; - - m = PyModule_Create(&_subprocessmodule); - if (m == NULL) - return NULL; - d = PyModule_GetDict(m); - - /* constants */ - defint(d, "STD_INPUT_HANDLE", STD_INPUT_HANDLE); - defint(d, "STD_OUTPUT_HANDLE", STD_OUTPUT_HANDLE); - defint(d, "STD_ERROR_HANDLE", STD_ERROR_HANDLE); - defint(d, "DUPLICATE_SAME_ACCESS", DUPLICATE_SAME_ACCESS); - defint(d, "STARTF_USESTDHANDLES", STARTF_USESTDHANDLES); - defint(d, "STARTF_USESHOWWINDOW", STARTF_USESHOWWINDOW); - defint(d, "SW_HIDE", SW_HIDE); - defint(d, "INFINITE", INFINITE); - defint(d, "WAIT_OBJECT_0", WAIT_OBJECT_0); - defint(d, "CREATE_NEW_CONSOLE", CREATE_NEW_CONSOLE); - defint(d, "CREATE_NEW_PROCESS_GROUP", CREATE_NEW_PROCESS_GROUP); + /* patch up object descriptors */ + sp_handle_as_number.nb_int = (unaryfunc) sp_handle_as_int; + if (PyType_Ready(&sp_handle_type) < 0) + return NULL; + + m = PyModule_Create(&_subprocessmodule); + if (m == NULL) + return NULL; + d = PyModule_GetDict(m); + + /* constants */ + defint(d, "STD_INPUT_HANDLE", STD_INPUT_HANDLE); + defint(d, "STD_OUTPUT_HANDLE", STD_OUTPUT_HANDLE); + defint(d, "STD_ERROR_HANDLE", STD_ERROR_HANDLE); + defint(d, "DUPLICATE_SAME_ACCESS", DUPLICATE_SAME_ACCESS); + defint(d, "STARTF_USESTDHANDLES", STARTF_USESTDHANDLES); + defint(d, "STARTF_USESHOWWINDOW", STARTF_USESHOWWINDOW); + defint(d, "SW_HIDE", SW_HIDE); + defint(d, "INFINITE", INFINITE); + defint(d, "WAIT_OBJECT_0", WAIT_OBJECT_0); + defint(d, "CREATE_NEW_CONSOLE", CREATE_NEW_CONSOLE); + defint(d, "CREATE_NEW_PROCESS_GROUP", CREATE_NEW_PROCESS_GROUP); - return m; + return m; } Modified: python/branches/py3k-jit/PC/bdist_wininst/archive.h ============================================================================== --- python/branches/py3k-jit/PC/bdist_wininst/archive.h (original) +++ python/branches/py3k-jit/PC/bdist_wininst/archive.h Mon May 10 23:55:43 2010 @@ -14,55 +14,55 @@ */ struct eof_cdir { - long tag; /* must be 0x06054b50 */ - short disknum; - short firstdisk; - short nTotalCDirThis; - short nTotalCDir; - long nBytesCDir; - long ofsCDir; - short commentlen; + long tag; /* must be 0x06054b50 */ + short disknum; + short firstdisk; + short nTotalCDirThis; + short nTotalCDir; + long nBytesCDir; + long ofsCDir; + short commentlen; }; struct cdir { - long tag; /* must be 0x02014b50 */ - short version_made; - short version_extract; - short gp_bitflag; - short comp_method; - short last_mod_file_time; - short last_mod_file_date; - long crc32; - long comp_size; - long uncomp_size; - short fname_length; - short extra_length; - short comment_length; - short disknum_start; - short int_file_attr; - long ext_file_attr; - long ofs_local_header; + long tag; /* must be 0x02014b50 */ + short version_made; + short version_extract; + short gp_bitflag; + short comp_method; + short last_mod_file_time; + short last_mod_file_date; + long crc32; + long comp_size; + long uncomp_size; + short fname_length; + short extra_length; + short comment_length; + short disknum_start; + short int_file_attr; + long ext_file_attr; + long ofs_local_header; }; struct fhdr { - long tag; /* must be 0x04034b50 */ - short version_needed; - short flags; - short method; - short last_mod_file_time; - short last_mod_file_date; - long crc32; - long comp_size; - long uncomp_size; - short fname_length; - short extra_length; + long tag; /* must be 0x04034b50 */ + short version_needed; + short flags; + short method; + short last_mod_file_time; + short last_mod_file_date; + long crc32; + long comp_size; + long uncomp_size; + short fname_length; + short extra_length; }; struct meta_data_hdr { - int tag; - int uncomp_size; - int bitmap_size; + int tag; + int uncomp_size; + int bitmap_size; }; #pragma pack() @@ -70,29 +70,29 @@ /* installation scheme */ typedef struct tagSCHEME { - char *name; - char *prefix; + char *name; + char *prefix; } SCHEME; typedef int (*NOTIFYPROC)(int code, LPSTR text, ...); extern BOOL extract_file(char *dst, char *src, int method, int comp_size, - int uncomp_size, NOTIFYPROC notify); + int uncomp_size, NOTIFYPROC notify); extern BOOL unzip_archive(SCHEME *scheme, char *dirname, char *data, - DWORD size, NOTIFYPROC notify); + DWORD size, NOTIFYPROC notify); extern char * map_new_file(DWORD flags, char *filename, char - *pathname_part, int size, - WORD wFatDate, WORD wFatTime, - NOTIFYPROC callback); + *pathname_part, int size, + WORD wFatDate, WORD wFatTime, + NOTIFYPROC callback); extern BOOL ensure_directory (char *pathname, char *new_part, - NOTIFYPROC callback); + NOTIFYPROC callback); /* codes for NOITIFYPROC */ #define DIR_CREATED 1 Modified: python/branches/py3k-jit/PC/bdist_wininst/extract.c ============================================================================== --- python/branches/py3k-jit/PC/bdist_wininst/extract.c (original) +++ python/branches/py3k-jit/PC/bdist_wininst/extract.c Mon May 10 23:55:43 2010 @@ -19,181 +19,181 @@ /* Convert unix-path to dos-path */ static void normpath(char *path) { - while (path && *path) { - if (*path == '/') - *path = '\\'; - ++path; - } + while (path && *path) { + if (*path == '/') + *path = '\\'; + ++path; + } } BOOL ensure_directory(char *pathname, char *new_part, NOTIFYPROC notify) { - while (new_part && *new_part && (new_part = strchr(new_part, '\\'))) { - DWORD attr; - *new_part = '\0'; - attr = GetFileAttributes(pathname); - if (attr == -1) { - /* nothing found */ - if (!CreateDirectory(pathname, NULL) && notify) - notify(SYSTEM_ERROR, - "CreateDirectory (%s)", pathname); - else - notify(DIR_CREATED, pathname); - } - if (attr & FILE_ATTRIBUTE_DIRECTORY) { - ; - } else { - SetLastError(183); - if (notify) - notify(SYSTEM_ERROR, - "CreateDirectory (%s)", pathname); - } - *new_part = '\\'; - ++new_part; - } - return TRUE; + while (new_part && *new_part && (new_part = strchr(new_part, '\\'))) { + DWORD attr; + *new_part = '\0'; + attr = GetFileAttributes(pathname); + if (attr == -1) { + /* nothing found */ + if (!CreateDirectory(pathname, NULL) && notify) + notify(SYSTEM_ERROR, + "CreateDirectory (%s)", pathname); + else + notify(DIR_CREATED, pathname); + } + if (attr & FILE_ATTRIBUTE_DIRECTORY) { + ; + } else { + SetLastError(183); + if (notify) + notify(SYSTEM_ERROR, + "CreateDirectory (%s)", pathname); + } + *new_part = '\\'; + ++new_part; + } + return TRUE; } /* XXX Should better explicitely specify * uncomp_size and file_times instead of pfhdr! */ char *map_new_file(DWORD flags, char *filename, - char *pathname_part, int size, - WORD wFatDate, WORD wFatTime, - NOTIFYPROC notify) + char *pathname_part, int size, + WORD wFatDate, WORD wFatTime, + NOTIFYPROC notify) { - HANDLE hFile, hFileMapping; - char *dst; - FILETIME ft; + HANDLE hFile, hFileMapping; + char *dst; + FILETIME ft; try_again: - if (!flags) - flags = CREATE_NEW; - hFile = CreateFile(filename, - GENERIC_WRITE | GENERIC_READ, - 0, NULL, - flags, - FILE_ATTRIBUTE_NORMAL, NULL); - if (hFile == INVALID_HANDLE_VALUE) { - DWORD x = GetLastError(); - switch (x) { - case ERROR_FILE_EXISTS: - if (notify && notify(CAN_OVERWRITE, filename)) - hFile = CreateFile(filename, - GENERIC_WRITE|GENERIC_READ, - 0, NULL, - CREATE_ALWAYS, - FILE_ATTRIBUTE_NORMAL, - NULL); - else { - if (notify) - notify(FILE_OVERWRITTEN, filename); - return NULL; - } - break; - case ERROR_PATH_NOT_FOUND: - if (ensure_directory(filename, pathname_part, notify)) - goto try_again; - else - return FALSE; - break; - default: - SetLastError(x); - break; - } - } - if (hFile == INVALID_HANDLE_VALUE) { - if (notify) - notify (SYSTEM_ERROR, "CreateFile (%s)", filename); - return NULL; - } - - if (notify) - notify(FILE_CREATED, filename); - - DosDateTimeToFileTime(wFatDate, wFatTime, &ft); - SetFileTime(hFile, &ft, &ft, &ft); - - - if (size == 0) { - /* We cannot map a zero-length file (Also it makes - no sense */ - CloseHandle(hFile); - return NULL; - } - - hFileMapping = CreateFileMapping(hFile, - NULL, PAGE_READWRITE, 0, size, NULL); - - CloseHandle(hFile); - - if (hFileMapping == INVALID_HANDLE_VALUE) { - if (notify) - notify(SYSTEM_ERROR, - "CreateFileMapping (%s)", filename); - return NULL; - } - - dst = MapViewOfFile(hFileMapping, - FILE_MAP_WRITE, 0, 0, 0); - - CloseHandle(hFileMapping); - - if (!dst) { - if (notify) - notify(SYSTEM_ERROR, "MapViewOfFile (%s)", filename); - return NULL; - } - return dst; + if (!flags) + flags = CREATE_NEW; + hFile = CreateFile(filename, + GENERIC_WRITE | GENERIC_READ, + 0, NULL, + flags, + FILE_ATTRIBUTE_NORMAL, NULL); + if (hFile == INVALID_HANDLE_VALUE) { + DWORD x = GetLastError(); + switch (x) { + case ERROR_FILE_EXISTS: + if (notify && notify(CAN_OVERWRITE, filename)) + hFile = CreateFile(filename, + GENERIC_WRITE|GENERIC_READ, + 0, NULL, + CREATE_ALWAYS, + FILE_ATTRIBUTE_NORMAL, + NULL); + else { + if (notify) + notify(FILE_OVERWRITTEN, filename); + return NULL; + } + break; + case ERROR_PATH_NOT_FOUND: + if (ensure_directory(filename, pathname_part, notify)) + goto try_again; + else + return FALSE; + break; + default: + SetLastError(x); + break; + } + } + if (hFile == INVALID_HANDLE_VALUE) { + if (notify) + notify (SYSTEM_ERROR, "CreateFile (%s)", filename); + return NULL; + } + + if (notify) + notify(FILE_CREATED, filename); + + DosDateTimeToFileTime(wFatDate, wFatTime, &ft); + SetFileTime(hFile, &ft, &ft, &ft); + + + if (size == 0) { + /* We cannot map a zero-length file (Also it makes + no sense */ + CloseHandle(hFile); + return NULL; + } + + hFileMapping = CreateFileMapping(hFile, + NULL, PAGE_READWRITE, 0, size, NULL); + + CloseHandle(hFile); + + if (hFileMapping == INVALID_HANDLE_VALUE) { + if (notify) + notify(SYSTEM_ERROR, + "CreateFileMapping (%s)", filename); + return NULL; + } + + dst = MapViewOfFile(hFileMapping, + FILE_MAP_WRITE, 0, 0, 0); + + CloseHandle(hFileMapping); + + if (!dst) { + if (notify) + notify(SYSTEM_ERROR, "MapViewOfFile (%s)", filename); + return NULL; + } + return dst; } BOOL extract_file(char *dst, char *src, int method, int comp_size, - int uncomp_size, NOTIFYPROC notify) + int uncomp_size, NOTIFYPROC notify) { - z_stream zstream; - int result; + z_stream zstream; + int result; - if (method == Z_DEFLATED) { - int x; - memset(&zstream, 0, sizeof(zstream)); - zstream.next_in = src; - zstream.avail_in = comp_size+1; - zstream.next_out = dst; - zstream.avail_out = uncomp_size; + if (method == Z_DEFLATED) { + int x; + memset(&zstream, 0, sizeof(zstream)); + zstream.next_in = src; + zstream.avail_in = comp_size+1; + zstream.next_out = dst; + zstream.avail_out = uncomp_size; /* Apparently an undocumented feature of zlib: Set windowsize to negative values to supress the gzip header and be compatible with zip! */ - result = TRUE; - if (Z_OK != (x = inflateInit2(&zstream, -15))) { - if (notify) - notify(ZLIB_ERROR, - "inflateInit2 returns %d", x); - result = FALSE; - goto cleanup; - } - if (Z_STREAM_END != (x = inflate(&zstream, Z_FINISH))) { - if (notify) - notify(ZLIB_ERROR, - "inflate returns %d", x); - result = FALSE; - } - cleanup: - if (Z_OK != (x = inflateEnd(&zstream))) { - if (notify) - notify (ZLIB_ERROR, - "inflateEnd returns %d", x); - result = FALSE; - } - } else if (method == 0) { - memcpy(dst, src, uncomp_size); - result = TRUE; - } else - result = FALSE; - UnmapViewOfFile(dst); - return result; + result = TRUE; + if (Z_OK != (x = inflateInit2(&zstream, -15))) { + if (notify) + notify(ZLIB_ERROR, + "inflateInit2 returns %d", x); + result = FALSE; + goto cleanup; + } + if (Z_STREAM_END != (x = inflate(&zstream, Z_FINISH))) { + if (notify) + notify(ZLIB_ERROR, + "inflate returns %d", x); + result = FALSE; + } + cleanup: + if (Z_OK != (x = inflateEnd(&zstream))) { + if (notify) + notify (ZLIB_ERROR, + "inflateEnd returns %d", x); + result = FALSE; + } + } else if (method == 0) { + memcpy(dst, src, uncomp_size); + result = TRUE; + } else + result = FALSE; + UnmapViewOfFile(dst); + return result; } /* Open a zip-compatible archive and extract all files @@ -201,121 +201,121 @@ */ BOOL unzip_archive(SCHEME *scheme, char *dirname, char *data, DWORD size, - NOTIFYPROC notify) + NOTIFYPROC notify) { - int n; - char pathname[MAX_PATH]; - char *new_part; - - /* read the end of central directory record */ - struct eof_cdir *pe = (struct eof_cdir *)&data[size - sizeof - (struct eof_cdir)]; - - int arc_start = size - sizeof (struct eof_cdir) - pe->nBytesCDir - - pe->ofsCDir; - - /* set position to start of central directory */ - int pos = arc_start + pe->ofsCDir; - - /* make sure this is a zip file */ - if (pe->tag != 0x06054b50) - return FALSE; - - /* Loop through the central directory, reading all entries */ - for (n = 0; n < pe->nTotalCDir; ++n) { - int i; - char *fname; - char *pcomp; - char *dst; - struct cdir *pcdir; - struct fhdr *pfhdr; - - pcdir = (struct cdir *)&data[pos]; - pfhdr = (struct fhdr *)&data[pcdir->ofs_local_header + - arc_start]; - - if (pcdir->tag != 0x02014b50) - return FALSE; - if (pfhdr->tag != 0x04034b50) - return FALSE; - pos += sizeof(struct cdir); - fname = (char *)&data[pos]; /* This is not null terminated! */ - pos += pcdir->fname_length + pcdir->extra_length + - pcdir->comment_length; - - pcomp = &data[pcdir->ofs_local_header - + sizeof(struct fhdr) - + arc_start - + pfhdr->fname_length - + pfhdr->extra_length]; - - /* dirname is the Python home directory (prefix) */ - strcpy(pathname, dirname); - if (pathname[strlen(pathname)-1] != '\\') - strcat(pathname, "\\"); - new_part = &pathname[lstrlen(pathname)]; - /* we must now match the first part of the pathname - * in the archive to a component in the installation - * scheme (PURELIB, PLATLIB, HEADERS, SCRIPTS, or DATA) - * and replace this part by the one in the scheme to use - */ - for (i = 0; scheme[i].name; ++i) { - if (0 == strnicmp(scheme[i].name, fname, - strlen(scheme[i].name))) { - char *rest; - int len; - - /* length of the replaced part */ - int namelen = strlen(scheme[i].name); - - strcat(pathname, scheme[i].prefix); - - rest = fname + namelen; - len = pfhdr->fname_length - namelen; - - if ((pathname[strlen(pathname)-1] != '\\') - && (pathname[strlen(pathname)-1] != '/')) - strcat(pathname, "\\"); - /* Now that pathname ends with a separator, - * we must make sure rest does not start with - * an additional one. - */ - if ((rest[0] == '\\') || (rest[0] == '/')) { - ++rest; - --len; - } - - strncat(pathname, rest, len); - goto Done; - } - } - /* no prefix to replace found, go unchanged */ - strncat(pathname, fname, pfhdr->fname_length); - Done: - normpath(pathname); - if (pathname[strlen(pathname)-1] != '\\') { - /* - * The local file header (pfhdr) does not always - * contain the compressed and uncompressed sizes of - * the data depending on bit 3 of the flags field. So - * it seems better to use the data from the central - * directory (pcdir). - */ - dst = map_new_file(0, pathname, new_part, - pcdir->uncomp_size, - pcdir->last_mod_file_date, - pcdir->last_mod_file_time, notify); - if (dst) { - if (!extract_file(dst, pcomp, pfhdr->method, - pcdir->comp_size, - pcdir->uncomp_size, - notify)) - return FALSE; - } /* else ??? */ - } - if (notify) - notify(NUM_FILES, new_part, (int)pe->nTotalCDir, - (int)n+1); - } - return TRUE; + int n; + char pathname[MAX_PATH]; + char *new_part; + + /* read the end of central directory record */ + struct eof_cdir *pe = (struct eof_cdir *)&data[size - sizeof + (struct eof_cdir)]; + + int arc_start = size - sizeof (struct eof_cdir) - pe->nBytesCDir - + pe->ofsCDir; + + /* set position to start of central directory */ + int pos = arc_start + pe->ofsCDir; + + /* make sure this is a zip file */ + if (pe->tag != 0x06054b50) + return FALSE; + + /* Loop through the central directory, reading all entries */ + for (n = 0; n < pe->nTotalCDir; ++n) { + int i; + char *fname; + char *pcomp; + char *dst; + struct cdir *pcdir; + struct fhdr *pfhdr; + + pcdir = (struct cdir *)&data[pos]; + pfhdr = (struct fhdr *)&data[pcdir->ofs_local_header + + arc_start]; + + if (pcdir->tag != 0x02014b50) + return FALSE; + if (pfhdr->tag != 0x04034b50) + return FALSE; + pos += sizeof(struct cdir); + fname = (char *)&data[pos]; /* This is not null terminated! */ + pos += pcdir->fname_length + pcdir->extra_length + + pcdir->comment_length; + + pcomp = &data[pcdir->ofs_local_header + + sizeof(struct fhdr) + + arc_start + + pfhdr->fname_length + + pfhdr->extra_length]; + + /* dirname is the Python home directory (prefix) */ + strcpy(pathname, dirname); + if (pathname[strlen(pathname)-1] != '\\') + strcat(pathname, "\\"); + new_part = &pathname[lstrlen(pathname)]; + /* we must now match the first part of the pathname + * in the archive to a component in the installation + * scheme (PURELIB, PLATLIB, HEADERS, SCRIPTS, or DATA) + * and replace this part by the one in the scheme to use + */ + for (i = 0; scheme[i].name; ++i) { + if (0 == strnicmp(scheme[i].name, fname, + strlen(scheme[i].name))) { + char *rest; + int len; + + /* length of the replaced part */ + int namelen = strlen(scheme[i].name); + + strcat(pathname, scheme[i].prefix); + + rest = fname + namelen; + len = pfhdr->fname_length - namelen; + + if ((pathname[strlen(pathname)-1] != '\\') + && (pathname[strlen(pathname)-1] != '/')) + strcat(pathname, "\\"); + /* Now that pathname ends with a separator, + * we must make sure rest does not start with + * an additional one. + */ + if ((rest[0] == '\\') || (rest[0] == '/')) { + ++rest; + --len; + } + + strncat(pathname, rest, len); + goto Done; + } + } + /* no prefix to replace found, go unchanged */ + strncat(pathname, fname, pfhdr->fname_length); + Done: + normpath(pathname); + if (pathname[strlen(pathname)-1] != '\\') { + /* + * The local file header (pfhdr) does not always + * contain the compressed and uncompressed sizes of + * the data depending on bit 3 of the flags field. So + * it seems better to use the data from the central + * directory (pcdir). + */ + dst = map_new_file(0, pathname, new_part, + pcdir->uncomp_size, + pcdir->last_mod_file_date, + pcdir->last_mod_file_time, notify); + if (dst) { + if (!extract_file(dst, pcomp, pfhdr->method, + pcdir->comp_size, + pcdir->uncomp_size, + notify)) + return FALSE; + } /* else ??? */ + } + if (notify) + notify(NUM_FILES, new_part, (int)pe->nTotalCDir, + (int)n+1); + } + return TRUE; } Modified: python/branches/py3k-jit/PC/bdist_wininst/install.c ============================================================================== --- python/branches/py3k-jit/PC/bdist_wininst/install.c (original) +++ python/branches/py3k-jit/PC/bdist_wininst/install.c Mon May 10 23:55:43 2010 @@ -20,21 +20,21 @@ * * At runtime, the exefile has appended: * - compressed setup-data in ini-format, containing the following sections: - * [metadata] - * author=Greg Ward - * author_email=gward at python.net - * description=Python Distribution Utilities - * licence=Python - * name=Distutils - * url=http://www.python.org/sigs/distutils-sig/ - * version=0.9pre + * [metadata] + * author=Greg Ward + * author_email=gward at python.net + * description=Python Distribution Utilities + * licence=Python + * name=Distutils + * url=http://www.python.org/sigs/distutils-sig/ + * version=0.9pre * - * [Setup] - * info= text to be displayed in the edit-box - * title= to be displayed by this program - * target_version = if present, python version required - * pyc_compile = if 0, do not compile py to pyc - * pyo_compile = if 0, do not compile py to pyo + * [Setup] + * info= text to be displayed in the edit-box + * title= to be displayed by this program + * target_version = if present, python version required + * pyc_compile = if 0, do not compile py to pyc + * pyo_compile = if 0, do not compile py to pyo * * - a struct meta_data_hdr, describing the above * - a zip-file, containing the modules to be installed. @@ -119,28 +119,28 @@ HWND hwndMain; HWND hDialog; -char *ini_file; /* Full pathname of ini-file */ +char *ini_file; /* Full pathname of ini-file */ /* From ini-file */ -char info[4096]; /* [Setup] info= */ -char title[80]; /* [Setup] title=, contains package name - including version: "Distutils-1.0.1" */ -char target_version[10]; /* [Setup] target_version=, required python - version or empty string */ -char build_info[80]; /* [Setup] build_info=, distutils version - and build date */ +char info[4096]; /* [Setup] info= */ +char title[80]; /* [Setup] title=, contains package name + including version: "Distutils-1.0.1" */ +char target_version[10]; /* [Setup] target_version=, required python + version or empty string */ +char build_info[80]; /* [Setup] build_info=, distutils version + and build date */ -char meta_name[80]; /* package name without version like - 'Distutils' */ +char meta_name[80]; /* package name without version like + 'Distutils' */ char install_script[MAX_PATH]; char *pre_install_script; /* run before we install a single file */ char user_access_control[10]; // one of 'auto', 'force', otherwise none. -int py_major, py_minor; /* Python version selected for installation */ +int py_major, py_minor; /* Python version selected for installation */ -char *arc_data; /* memory mapped archive */ -DWORD arc_size; /* number of bytes in archive */ -int exe_size; /* number of bytes for exe-file portion */ +char *arc_data; /* memory mapped archive */ +DWORD arc_size; /* number of bytes in archive */ +int exe_size; /* number of bytes for exe-file portion */ char python_dir[MAX_PATH]; char pythondll[MAX_PATH]; BOOL pyc_compile, pyo_compile; @@ -148,7 +148,7 @@ the permissions of the current user. */ HKEY hkey_root = (HKEY)-1; -BOOL success; /* Installation successfull? */ +BOOL success; /* Installation successfull? */ char *failure_reason = NULL; HANDLE hBitmap; @@ -166,128 +166,128 @@ /* Note: If scheme.prefix is nonempty, it must end with a '\'! */ /* Note: purelib must be the FIRST entry! */ SCHEME old_scheme[] = { - { "PURELIB", "" }, - { "PLATLIB", "" }, - { "HEADERS", "" }, /* 'Include/dist_name' part already in archive */ - { "SCRIPTS", "Scripts\\" }, - { "DATA", "" }, - { NULL, NULL }, + { "PURELIB", "" }, + { "PLATLIB", "" }, + { "HEADERS", "" }, /* 'Include/dist_name' part already in archive */ + { "SCRIPTS", "Scripts\\" }, + { "DATA", "" }, + { NULL, NULL }, }; SCHEME new_scheme[] = { - { "PURELIB", "Lib\\site-packages\\" }, - { "PLATLIB", "Lib\\site-packages\\" }, - { "HEADERS", "" }, /* 'Include/dist_name' part already in archive */ - { "SCRIPTS", "Scripts\\" }, - { "DATA", "" }, - { NULL, NULL }, + { "PURELIB", "Lib\\site-packages\\" }, + { "PLATLIB", "Lib\\site-packages\\" }, + { "HEADERS", "" }, /* 'Include/dist_name' part already in archive */ + { "SCRIPTS", "Scripts\\" }, + { "DATA", "" }, + { NULL, NULL }, }; static void unescape(char *dst, char *src, unsigned size) { - char *eon; - char ch; + char *eon; + char ch; - while (src && *src && (size > 2)) { - if (*src == '\\') { - switch (*++src) { - case 'n': - ++src; - *dst++ = '\r'; - *dst++ = '\n'; - size -= 2; - break; - case 'r': - ++src; - *dst++ = '\r'; - --size; - break; - case '0': case '1': case '2': case '3': - ch = (char)strtol(src, &eon, 8); - if (ch == '\n') { - *dst++ = '\r'; - --size; - } - *dst++ = ch; - --size; - src = eon; - } - } else { - *dst++ = *src++; - --size; - } - } - *dst = '\0'; + while (src && *src && (size > 2)) { + if (*src == '\\') { + switch (*++src) { + case 'n': + ++src; + *dst++ = '\r'; + *dst++ = '\n'; + size -= 2; + break; + case 'r': + ++src; + *dst++ = '\r'; + --size; + break; + case '0': case '1': case '2': case '3': + ch = (char)strtol(src, &eon, 8); + if (ch == '\n') { + *dst++ = '\r'; + --size; + } + *dst++ = ch; + --size; + src = eon; + } + } else { + *dst++ = *src++; + --size; + } + } + *dst = '\0'; } static struct tagFile { - char *path; - struct tagFile *next; + char *path; + struct tagFile *next; } *file_list = NULL; static void set_failure_reason(char *reason) { if (failure_reason) - free(failure_reason); + free(failure_reason); failure_reason = strdup(reason); success = FALSE; } static char *get_failure_reason() { if (!failure_reason) - return "Installation failed."; + return "Installation failed."; return failure_reason; } static void add_to_filelist(char *path) { - struct tagFile *p; - p = (struct tagFile *)malloc(sizeof(struct tagFile)); - p->path = strdup(path); - p->next = file_list; - file_list = p; + struct tagFile *p; + p = (struct tagFile *)malloc(sizeof(struct tagFile)); + p->path = strdup(path); + p->next = file_list; + file_list = p; } static int do_compile_files(int (__cdecl * PyRun_SimpleString)(char *), - int optimize) + int optimize) { - struct tagFile *p; - int total, n; - char Buffer[MAX_PATH + 64]; - int errors = 0; - - total = 0; - p = file_list; - while (p) { - ++total; - p = p->next; - } - SendDlgItemMessage(hDialog, IDC_PROGRESS, PBM_SETRANGE, 0, - MAKELPARAM(0, total)); - SendDlgItemMessage(hDialog, IDC_PROGRESS, PBM_SETPOS, 0, 0); - - n = 0; - p = file_list; - while (p) { - ++n; - wsprintf(Buffer, - "import py_compile; py_compile.compile (r'%s')", - p->path); - if (PyRun_SimpleString(Buffer)) { - ++errors; - } - /* We send the notification even if the files could not - * be created so that the uninstaller will remove them - * in case they are created later. - */ - wsprintf(Buffer, "%s%c", p->path, optimize ? 'o' : 'c'); - notify(FILE_CREATED, Buffer); - - SendDlgItemMessage(hDialog, IDC_PROGRESS, PBM_SETPOS, n, 0); - SetDlgItemText(hDialog, IDC_INFO, p->path); - p = p->next; - } - return errors; + struct tagFile *p; + int total, n; + char Buffer[MAX_PATH + 64]; + int errors = 0; + + total = 0; + p = file_list; + while (p) { + ++total; + p = p->next; + } + SendDlgItemMessage(hDialog, IDC_PROGRESS, PBM_SETRANGE, 0, + MAKELPARAM(0, total)); + SendDlgItemMessage(hDialog, IDC_PROGRESS, PBM_SETPOS, 0, 0); + + n = 0; + p = file_list; + while (p) { + ++n; + wsprintf(Buffer, + "import py_compile; py_compile.compile (r'%s')", + p->path); + if (PyRun_SimpleString(Buffer)) { + ++errors; + } + /* We send the notification even if the files could not + * be created so that the uninstaller will remove them + * in case they are created later. + */ + wsprintf(Buffer, "%s%c", p->path, optimize ? 'o' : 'c'); + notify(FILE_CREATED, Buffer); + + SendDlgItemMessage(hDialog, IDC_PROGRESS, PBM_SETPOS, n, 0); + SetDlgItemText(hDialog, IDC_INFO, p->path); + p = p->next; + } + return errors; } #define DECLPROC(dll, result, name, args)\ @@ -304,22 +304,22 @@ // Result string must be free'd wchar_t *widen_string(char *src) { - wchar_t *result; - DWORD dest_cch; - int src_len = strlen(src) + 1; // include NULL term in all ops - /* use MultiByteToWideChar() to see how much we need. */ - /* NOTE: this will include the null-term in the length */ - dest_cch = MultiByteToWideChar(CP_ACP, 0, src, src_len, NULL, 0); - // alloc the buffer - result = (wchar_t *)malloc(dest_cch * sizeof(wchar_t)); - if (result==NULL) - return NULL; - /* do the conversion */ - if (0==MultiByteToWideChar(CP_ACP, 0, src, src_len, result, dest_cch)) { - free(result); - return NULL; - } - return result; + wchar_t *result; + DWORD dest_cch; + int src_len = strlen(src) + 1; // include NULL term in all ops + /* use MultiByteToWideChar() to see how much we need. */ + /* NOTE: this will include the null-term in the length */ + dest_cch = MultiByteToWideChar(CP_ACP, 0, src, src_len, NULL, 0); + // alloc the buffer + result = (wchar_t *)malloc(dest_cch * sizeof(wchar_t)); + if (result==NULL) + return NULL; + /* do the conversion */ + if (0==MultiByteToWideChar(CP_ACP, 0, src, src_len, result, dest_cch)) { + free(result); + return NULL; + } + return result; } /* @@ -328,47 +328,47 @@ */ static int compile_filelist(HINSTANCE hPython, BOOL optimize_flag) { - DECLPROC(hPython, void, Py_Initialize, (void)); - DECLPROC(hPython, void, Py_SetProgramName, (wchar_t *)); - DECLPROC(hPython, void, Py_Finalize, (void)); - DECLPROC(hPython, int, PyRun_SimpleString, (char *)); - DECLPROC(hPython, PyObject *, PySys_GetObject, (char *)); - DECLVAR(hPython, int, Py_OptimizeFlag); + DECLPROC(hPython, void, Py_Initialize, (void)); + DECLPROC(hPython, void, Py_SetProgramName, (wchar_t *)); + DECLPROC(hPython, void, Py_Finalize, (void)); + DECLPROC(hPython, int, PyRun_SimpleString, (char *)); + DECLPROC(hPython, PyObject *, PySys_GetObject, (char *)); + DECLVAR(hPython, int, Py_OptimizeFlag); - int errors = 0; - struct tagFile *p = file_list; + int errors = 0; + struct tagFile *p = file_list; - if (!p) - return 0; + if (!p) + return 0; - if (!Py_Initialize || !Py_SetProgramName || !Py_Finalize) - return -1; + if (!Py_Initialize || !Py_SetProgramName || !Py_Finalize) + return -1; - if (!PyRun_SimpleString || !PySys_GetObject || !Py_OptimizeFlag) - return -1; + if (!PyRun_SimpleString || !PySys_GetObject || !Py_OptimizeFlag) + return -1; - *Py_OptimizeFlag = optimize_flag ? 1 : 0; - Py_SetProgramName(wmodulename); - Py_Initialize(); + *Py_OptimizeFlag = optimize_flag ? 1 : 0; + Py_SetProgramName(wmodulename); + Py_Initialize(); - errors += do_compile_files(PyRun_SimpleString, optimize_flag); - Py_Finalize(); + errors += do_compile_files(PyRun_SimpleString, optimize_flag); + Py_Finalize(); - return errors; + return errors; } typedef PyObject *(*PyCFunction)(PyObject *, PyObject *); struct PyMethodDef { - char *ml_name; - PyCFunction ml_meth; - int ml_flags; - char *ml_doc; + char *ml_name; + PyCFunction ml_meth; + int ml_flags; + char *ml_doc; }; typedef struct PyMethodDef PyMethodDef; // XXX - all of these are potentially fragile! We load and unload -// the Python DLL multiple times - so storing functions pointers +// the Python DLL multiple times - so storing functions pointers // is dangerous (although things *look* OK at present) // Better might be to roll prepare_script_environment() into // LoadPythonDll(), and create a new UnloadPythonDLL() which also @@ -385,249 +385,249 @@ #define DEF_CSIDL(name) { name, #name } struct { - int nFolder; - char *name; + int nFolder; + char *name; } csidl_names[] = { - /* Startup menu for all users. - NT only */ - DEF_CSIDL(CSIDL_COMMON_STARTMENU), - /* Startup menu. */ - DEF_CSIDL(CSIDL_STARTMENU), + /* Startup menu for all users. + NT only */ + DEF_CSIDL(CSIDL_COMMON_STARTMENU), + /* Startup menu. */ + DEF_CSIDL(CSIDL_STARTMENU), /* DEF_CSIDL(CSIDL_COMMON_APPDATA), */ /* DEF_CSIDL(CSIDL_LOCAL_APPDATA), */ - /* Repository for application-specific data. - Needs Internet Explorer 4.0 */ - DEF_CSIDL(CSIDL_APPDATA), - - /* The desktop for all users. - NT only */ - DEF_CSIDL(CSIDL_COMMON_DESKTOPDIRECTORY), - /* The desktop. */ - DEF_CSIDL(CSIDL_DESKTOPDIRECTORY), - - /* Startup folder for all users. - NT only */ - DEF_CSIDL(CSIDL_COMMON_STARTUP), - /* Startup folder. */ - DEF_CSIDL(CSIDL_STARTUP), - - /* Programs item in the start menu for all users. - NT only */ - DEF_CSIDL(CSIDL_COMMON_PROGRAMS), - /* Program item in the user's start menu. */ - DEF_CSIDL(CSIDL_PROGRAMS), + /* Repository for application-specific data. + Needs Internet Explorer 4.0 */ + DEF_CSIDL(CSIDL_APPDATA), + + /* The desktop for all users. + NT only */ + DEF_CSIDL(CSIDL_COMMON_DESKTOPDIRECTORY), + /* The desktop. */ + DEF_CSIDL(CSIDL_DESKTOPDIRECTORY), + + /* Startup folder for all users. + NT only */ + DEF_CSIDL(CSIDL_COMMON_STARTUP), + /* Startup folder. */ + DEF_CSIDL(CSIDL_STARTUP), + + /* Programs item in the start menu for all users. + NT only */ + DEF_CSIDL(CSIDL_COMMON_PROGRAMS), + /* Program item in the user's start menu. */ + DEF_CSIDL(CSIDL_PROGRAMS), /* DEF_CSIDL(CSIDL_PROGRAM_FILES_COMMON), */ /* DEF_CSIDL(CSIDL_PROGRAM_FILES), */ - /* Virtual folder containing fonts. */ - DEF_CSIDL(CSIDL_FONTS), + /* Virtual folder containing fonts. */ + DEF_CSIDL(CSIDL_FONTS), }; #define DIM(a) (sizeof(a) / sizeof((a)[0])) static PyObject *FileCreated(PyObject *self, PyObject *args) { - char *path; - if (!g_PyArg_ParseTuple(args, "s", &path)) - return NULL; - notify(FILE_CREATED, path); - return g_Py_BuildValue(""); + char *path; + if (!g_PyArg_ParseTuple(args, "s", &path)) + return NULL; + notify(FILE_CREATED, path); + return g_Py_BuildValue(""); } static PyObject *DirectoryCreated(PyObject *self, PyObject *args) { - char *path; - if (!g_PyArg_ParseTuple(args, "s", &path)) - return NULL; - notify(DIR_CREATED, path); - return g_Py_BuildValue(""); + char *path; + if (!g_PyArg_ParseTuple(args, "s", &path)) + return NULL; + notify(DIR_CREATED, path); + return g_Py_BuildValue(""); } static PyObject *GetSpecialFolderPath(PyObject *self, PyObject *args) { - char *name; - char lpszPath[MAX_PATH]; - int i; - static HRESULT (WINAPI *My_SHGetSpecialFolderPath)(HWND hwnd, - LPTSTR lpszPath, - int nFolder, - BOOL fCreate); - - if (!My_SHGetSpecialFolderPath) { - HINSTANCE hLib = LoadLibrary("shell32.dll"); - if (!hLib) { - g_PyErr_Format(g_PyExc_OSError, - "function not available"); - return NULL; - } - My_SHGetSpecialFolderPath = (BOOL (WINAPI *)(HWND, LPTSTR, - int, BOOL)) - GetProcAddress(hLib, - "SHGetSpecialFolderPathA"); - } - - if (!g_PyArg_ParseTuple(args, "s", &name)) - return NULL; - - if (!My_SHGetSpecialFolderPath) { - g_PyErr_Format(g_PyExc_OSError, "function not available"); - return NULL; - } - - for (i = 0; i < DIM(csidl_names); ++i) { - if (0 == strcmpi(csidl_names[i].name, name)) { - int nFolder; - nFolder = csidl_names[i].nFolder; - if (My_SHGetSpecialFolderPath(NULL, lpszPath, - nFolder, 0)) - return g_Py_BuildValue("s", lpszPath); - else { - g_PyErr_Format(g_PyExc_OSError, - "no such folder (%s)", name); - return NULL; - } - - } - }; - g_PyErr_Format(g_PyExc_ValueError, "unknown CSIDL (%s)", name); - return NULL; + char *name; + char lpszPath[MAX_PATH]; + int i; + static HRESULT (WINAPI *My_SHGetSpecialFolderPath)(HWND hwnd, + LPTSTR lpszPath, + int nFolder, + BOOL fCreate); + + if (!My_SHGetSpecialFolderPath) { + HINSTANCE hLib = LoadLibrary("shell32.dll"); + if (!hLib) { + g_PyErr_Format(g_PyExc_OSError, + "function not available"); + return NULL; + } + My_SHGetSpecialFolderPath = (BOOL (WINAPI *)(HWND, LPTSTR, + int, BOOL)) + GetProcAddress(hLib, + "SHGetSpecialFolderPathA"); + } + + if (!g_PyArg_ParseTuple(args, "s", &name)) + return NULL; + + if (!My_SHGetSpecialFolderPath) { + g_PyErr_Format(g_PyExc_OSError, "function not available"); + return NULL; + } + + for (i = 0; i < DIM(csidl_names); ++i) { + if (0 == strcmpi(csidl_names[i].name, name)) { + int nFolder; + nFolder = csidl_names[i].nFolder; + if (My_SHGetSpecialFolderPath(NULL, lpszPath, + nFolder, 0)) + return g_Py_BuildValue("s", lpszPath); + else { + g_PyErr_Format(g_PyExc_OSError, + "no such folder (%s)", name); + return NULL; + } + + } + }; + g_PyErr_Format(g_PyExc_ValueError, "unknown CSIDL (%s)", name); + return NULL; } static PyObject *CreateShortcut(PyObject *self, PyObject *args) { - char *path; /* path and filename */ - char *description; - char *filename; - - char *arguments = NULL; - char *iconpath = NULL; - int iconindex = 0; - char *workdir = NULL; - - WCHAR wszFilename[MAX_PATH]; - - IShellLink *ps1 = NULL; - IPersistFile *pPf = NULL; - - HRESULT hr; - - hr = CoInitialize(NULL); - if (FAILED(hr)) { - g_PyErr_Format(g_PyExc_OSError, - "CoInitialize failed, error 0x%x", hr); - goto error; - } - - if (!g_PyArg_ParseTuple(args, "sss|sssi", - &path, &description, &filename, - &arguments, &workdir, &iconpath, &iconindex)) - return NULL; - - hr = CoCreateInstance(&CLSID_ShellLink, - NULL, - CLSCTX_INPROC_SERVER, - &IID_IShellLink, - &ps1); - if (FAILED(hr)) { - g_PyErr_Format(g_PyExc_OSError, - "CoCreateInstance failed, error 0x%x", hr); - goto error; - } - - hr = ps1->lpVtbl->QueryInterface(ps1, &IID_IPersistFile, - (void **)&pPf); - if (FAILED(hr)) { - g_PyErr_Format(g_PyExc_OSError, - "QueryInterface(IPersistFile) error 0x%x", hr); - goto error; - } - - - hr = ps1->lpVtbl->SetPath(ps1, path); - if (FAILED(hr)) { - g_PyErr_Format(g_PyExc_OSError, - "SetPath() failed, error 0x%x", hr); - goto error; - } - - hr = ps1->lpVtbl->SetDescription(ps1, description); - if (FAILED(hr)) { - g_PyErr_Format(g_PyExc_OSError, - "SetDescription() failed, error 0x%x", hr); - goto error; - } - - if (arguments) { - hr = ps1->lpVtbl->SetArguments(ps1, arguments); - if (FAILED(hr)) { - g_PyErr_Format(g_PyExc_OSError, - "SetArguments() error 0x%x", hr); - goto error; - } - } - - if (iconpath) { - hr = ps1->lpVtbl->SetIconLocation(ps1, iconpath, iconindex); - if (FAILED(hr)) { - g_PyErr_Format(g_PyExc_OSError, - "SetIconLocation() error 0x%x", hr); - goto error; - } - } - - if (workdir) { - hr = ps1->lpVtbl->SetWorkingDirectory(ps1, workdir); - if (FAILED(hr)) { - g_PyErr_Format(g_PyExc_OSError, - "SetWorkingDirectory() error 0x%x", hr); - goto error; - } - } - - MultiByteToWideChar(CP_ACP, 0, - filename, -1, - wszFilename, MAX_PATH); - - hr = pPf->lpVtbl->Save(pPf, wszFilename, TRUE); - if (FAILED(hr)) { - g_PyErr_Format(g_PyExc_OSError, - "Failed to create shortcut '%s' - error 0x%x", filename, hr); - goto error; - } - - pPf->lpVtbl->Release(pPf); - ps1->lpVtbl->Release(ps1); - CoUninitialize(); - return g_Py_BuildValue(""); - + char *path; /* path and filename */ + char *description; + char *filename; + + char *arguments = NULL; + char *iconpath = NULL; + int iconindex = 0; + char *workdir = NULL; + + WCHAR wszFilename[MAX_PATH]; + + IShellLink *ps1 = NULL; + IPersistFile *pPf = NULL; + + HRESULT hr; + + hr = CoInitialize(NULL); + if (FAILED(hr)) { + g_PyErr_Format(g_PyExc_OSError, + "CoInitialize failed, error 0x%x", hr); + goto error; + } + + if (!g_PyArg_ParseTuple(args, "sss|sssi", + &path, &description, &filename, + &arguments, &workdir, &iconpath, &iconindex)) + return NULL; + + hr = CoCreateInstance(&CLSID_ShellLink, + NULL, + CLSCTX_INPROC_SERVER, + &IID_IShellLink, + &ps1); + if (FAILED(hr)) { + g_PyErr_Format(g_PyExc_OSError, + "CoCreateInstance failed, error 0x%x", hr); + goto error; + } + + hr = ps1->lpVtbl->QueryInterface(ps1, &IID_IPersistFile, + (void **)&pPf); + if (FAILED(hr)) { + g_PyErr_Format(g_PyExc_OSError, + "QueryInterface(IPersistFile) error 0x%x", hr); + goto error; + } + + + hr = ps1->lpVtbl->SetPath(ps1, path); + if (FAILED(hr)) { + g_PyErr_Format(g_PyExc_OSError, + "SetPath() failed, error 0x%x", hr); + goto error; + } + + hr = ps1->lpVtbl->SetDescription(ps1, description); + if (FAILED(hr)) { + g_PyErr_Format(g_PyExc_OSError, + "SetDescription() failed, error 0x%x", hr); + goto error; + } + + if (arguments) { + hr = ps1->lpVtbl->SetArguments(ps1, arguments); + if (FAILED(hr)) { + g_PyErr_Format(g_PyExc_OSError, + "SetArguments() error 0x%x", hr); + goto error; + } + } + + if (iconpath) { + hr = ps1->lpVtbl->SetIconLocation(ps1, iconpath, iconindex); + if (FAILED(hr)) { + g_PyErr_Format(g_PyExc_OSError, + "SetIconLocation() error 0x%x", hr); + goto error; + } + } + + if (workdir) { + hr = ps1->lpVtbl->SetWorkingDirectory(ps1, workdir); + if (FAILED(hr)) { + g_PyErr_Format(g_PyExc_OSError, + "SetWorkingDirectory() error 0x%x", hr); + goto error; + } + } + + MultiByteToWideChar(CP_ACP, 0, + filename, -1, + wszFilename, MAX_PATH); + + hr = pPf->lpVtbl->Save(pPf, wszFilename, TRUE); + if (FAILED(hr)) { + g_PyErr_Format(g_PyExc_OSError, + "Failed to create shortcut '%s' - error 0x%x", filename, hr); + goto error; + } + + pPf->lpVtbl->Release(pPf); + ps1->lpVtbl->Release(ps1); + CoUninitialize(); + return g_Py_BuildValue(""); + error: - if (pPf) - pPf->lpVtbl->Release(pPf); + if (pPf) + pPf->lpVtbl->Release(pPf); - if (ps1) - ps1->lpVtbl->Release(ps1); + if (ps1) + ps1->lpVtbl->Release(ps1); - CoUninitialize(); + CoUninitialize(); - return NULL; + return NULL; } static PyObject *PyMessageBox(PyObject *self, PyObject *args) { - int rc; - char *text, *caption; - int flags; - if (!g_PyArg_ParseTuple(args, "ssi", &text, &caption, &flags)) - return NULL; - rc = MessageBox(GetFocus(), text, caption, flags); - return g_Py_BuildValue("i", rc); + int rc; + char *text, *caption; + int flags; + if (!g_PyArg_ParseTuple(args, "ssi", &text, &caption, &flags)) + return NULL; + rc = MessageBox(GetFocus(), text, caption, flags); + return g_Py_BuildValue("i", rc); } static PyObject *GetRootHKey(PyObject *self) { - return g_PyLong_FromVoidPtr(hkey_root); + return g_PyLong_FromVoidPtr(hkey_root); } #define METH_VARARGS 0x0001 @@ -635,74 +635,74 @@ typedef PyObject *(*PyCFunction)(PyObject *, PyObject *); PyMethodDef meth[] = { - {"create_shortcut", CreateShortcut, METH_VARARGS, NULL}, - {"get_special_folder_path", GetSpecialFolderPath, METH_VARARGS, NULL}, - {"get_root_hkey", (PyCFunction)GetRootHKey, METH_NOARGS, NULL}, - {"file_created", FileCreated, METH_VARARGS, NULL}, - {"directory_created", DirectoryCreated, METH_VARARGS, NULL}, - {"message_box", PyMessageBox, METH_VARARGS, NULL}, + {"create_shortcut", CreateShortcut, METH_VARARGS, NULL}, + {"get_special_folder_path", GetSpecialFolderPath, METH_VARARGS, NULL}, + {"get_root_hkey", (PyCFunction)GetRootHKey, METH_NOARGS, NULL}, + {"file_created", FileCreated, METH_VARARGS, NULL}, + {"directory_created", DirectoryCreated, METH_VARARGS, NULL}, + {"message_box", PyMessageBox, METH_VARARGS, NULL}, }; static HINSTANCE LoadPythonDll(char *fname) { - char fullpath[_MAX_PATH]; - LONG size = sizeof(fullpath); - char subkey_name[80]; - char buffer[260 + 12]; - HINSTANCE h; - - /* make sure PYTHONHOME is set, to that sys.path is initialized correctly */ - wsprintf(buffer, "PYTHONHOME=%s", python_dir); - _putenv(buffer); - h = LoadLibrary(fname); - if (h) - return h; - wsprintf(subkey_name, - "SOFTWARE\\Python\\PythonCore\\%d.%d\\InstallPath", - py_major, py_minor); - if (ERROR_SUCCESS != RegQueryValue(HKEY_CURRENT_USER, subkey_name, - fullpath, &size) && - ERROR_SUCCESS != RegQueryValue(HKEY_LOCAL_MACHINE, subkey_name, - fullpath, &size)) - return NULL; - strcat(fullpath, "\\"); - strcat(fullpath, fname); - return LoadLibrary(fullpath); + char fullpath[_MAX_PATH]; + LONG size = sizeof(fullpath); + char subkey_name[80]; + char buffer[260 + 12]; + HINSTANCE h; + + /* make sure PYTHONHOME is set, to that sys.path is initialized correctly */ + wsprintf(buffer, "PYTHONHOME=%s", python_dir); + _putenv(buffer); + h = LoadLibrary(fname); + if (h) + return h; + wsprintf(subkey_name, + "SOFTWARE\\Python\\PythonCore\\%d.%d\\InstallPath", + py_major, py_minor); + if (ERROR_SUCCESS != RegQueryValue(HKEY_CURRENT_USER, subkey_name, + fullpath, &size) && + ERROR_SUCCESS != RegQueryValue(HKEY_LOCAL_MACHINE, subkey_name, + fullpath, &size)) + return NULL; + strcat(fullpath, "\\"); + strcat(fullpath, fname); + return LoadLibrary(fullpath); } static int prepare_script_environment(HINSTANCE hPython) { - PyObject *mod; - DECLPROC(hPython, PyObject *, PyImport_ImportModule, (char *)); - DECLPROC(hPython, int, PyObject_SetAttrString, (PyObject *, char *, PyObject *)); - DECLPROC(hPython, PyObject *, PyObject_GetAttrString, (PyObject *, char *)); - DECLPROC(hPython, PyObject *, PyCFunction_New, (PyMethodDef *, PyObject *)); - DECLPROC(hPython, PyObject *, Py_BuildValue, (char *, ...)); - DECLPROC(hPython, int, PyArg_ParseTuple, (PyObject *, char *, ...)); - DECLPROC(hPython, PyObject *, PyErr_Format, (PyObject *, char *)); - DECLPROC(hPython, PyObject *, PyLong_FromVoidPtr, (void *)); - if (!PyImport_ImportModule || !PyObject_GetAttrString || - !PyObject_SetAttrString || !PyCFunction_New) - return 1; - if (!Py_BuildValue || !PyArg_ParseTuple || !PyErr_Format) - return 1; - - mod = PyImport_ImportModule("builtins"); - if (mod) { - int i; - g_PyExc_ValueError = PyObject_GetAttrString(mod, "ValueError"); - g_PyExc_OSError = PyObject_GetAttrString(mod, "OSError"); - for (i = 0; i < DIM(meth); ++i) { - PyObject_SetAttrString(mod, meth[i].ml_name, - PyCFunction_New(&meth[i], NULL)); - } - } - g_Py_BuildValue = Py_BuildValue; - g_PyArg_ParseTuple = PyArg_ParseTuple; - g_PyErr_Format = PyErr_Format; - g_PyLong_FromVoidPtr = PyLong_FromVoidPtr; + PyObject *mod; + DECLPROC(hPython, PyObject *, PyImport_ImportModule, (char *)); + DECLPROC(hPython, int, PyObject_SetAttrString, (PyObject *, char *, PyObject *)); + DECLPROC(hPython, PyObject *, PyObject_GetAttrString, (PyObject *, char *)); + DECLPROC(hPython, PyObject *, PyCFunction_New, (PyMethodDef *, PyObject *)); + DECLPROC(hPython, PyObject *, Py_BuildValue, (char *, ...)); + DECLPROC(hPython, int, PyArg_ParseTuple, (PyObject *, char *, ...)); + DECLPROC(hPython, PyObject *, PyErr_Format, (PyObject *, char *)); + DECLPROC(hPython, PyObject *, PyLong_FromVoidPtr, (void *)); + if (!PyImport_ImportModule || !PyObject_GetAttrString || + !PyObject_SetAttrString || !PyCFunction_New) + return 1; + if (!Py_BuildValue || !PyArg_ParseTuple || !PyErr_Format) + return 1; + + mod = PyImport_ImportModule("builtins"); + if (mod) { + int i; + g_PyExc_ValueError = PyObject_GetAttrString(mod, "ValueError"); + g_PyExc_OSError = PyObject_GetAttrString(mod, "OSError"); + for (i = 0; i < DIM(meth); ++i) { + PyObject_SetAttrString(mod, meth[i].ml_name, + PyCFunction_New(&meth[i], NULL)); + } + } + g_Py_BuildValue = Py_BuildValue; + g_PyArg_ParseTuple = PyArg_ParseTuple; + g_PyErr_Format = PyErr_Format; + g_PyLong_FromVoidPtr = PyLong_FromVoidPtr; - return 0; + return 0; } /* @@ -718,483 +718,483 @@ static int do_run_installscript(HINSTANCE hPython, char *pathname, int argc, char **argv) { - int fh, result, i; - static wchar_t *wargv[256]; - DECLPROC(hPython, void, Py_Initialize, (void)); - DECLPROC(hPython, int, PySys_SetArgv, (int, wchar_t **)); - DECLPROC(hPython, int, PyRun_SimpleString, (char *)); - DECLPROC(hPython, void, Py_Finalize, (void)); - DECLPROC(hPython, PyObject *, Py_BuildValue, (char *, ...)); - DECLPROC(hPython, PyObject *, PyCFunction_New, - (PyMethodDef *, PyObject *)); - DECLPROC(hPython, int, PyArg_ParseTuple, (PyObject *, char *, ...)); - DECLPROC(hPython, PyObject *, PyErr_Format, (PyObject *, char *)); - - if (!Py_Initialize || !PySys_SetArgv - || !PyRun_SimpleString || !Py_Finalize) - return 1; - - if (!Py_BuildValue || !PyArg_ParseTuple || !PyErr_Format) - return 1; - - if (!PyCFunction_New || !PyArg_ParseTuple || !PyErr_Format) - return 1; - - if (pathname == NULL || pathname[0] == '\0') - return 2; - - fh = open(pathname, _O_RDONLY); - if (-1 == fh) { - fprintf(stderr, "Could not open postinstall-script %s\n", - pathname); - return 3; - } - - SetDlgItemText(hDialog, IDC_INFO, "Running Script..."); - - Py_Initialize(); - - prepare_script_environment(hPython); - // widen the argv array for py3k. - memset(wargv, 0, sizeof(wargv)); - for (i=0;i 0) { - script[n] = '\n'; - script[n+1] = 0; - result = PyRun_SimpleString(script); - } - } - } - Py_Finalize(); + int fh, result, i; + static wchar_t *wargv[256]; + DECLPROC(hPython, void, Py_Initialize, (void)); + DECLPROC(hPython, int, PySys_SetArgv, (int, wchar_t **)); + DECLPROC(hPython, int, PyRun_SimpleString, (char *)); + DECLPROC(hPython, void, Py_Finalize, (void)); + DECLPROC(hPython, PyObject *, Py_BuildValue, (char *, ...)); + DECLPROC(hPython, PyObject *, PyCFunction_New, + (PyMethodDef *, PyObject *)); + DECLPROC(hPython, int, PyArg_ParseTuple, (PyObject *, char *, ...)); + DECLPROC(hPython, PyObject *, PyErr_Format, (PyObject *, char *)); + + if (!Py_Initialize || !PySys_SetArgv + || !PyRun_SimpleString || !Py_Finalize) + return 1; + + if (!Py_BuildValue || !PyArg_ParseTuple || !PyErr_Format) + return 1; + + if (!PyCFunction_New || !PyArg_ParseTuple || !PyErr_Format) + return 1; + + if (pathname == NULL || pathname[0] == '\0') + return 2; + + fh = open(pathname, _O_RDONLY); + if (-1 == fh) { + fprintf(stderr, "Could not open postinstall-script %s\n", + pathname); + return 3; + } + + SetDlgItemText(hDialog, IDC_INFO, "Running Script..."); + + Py_Initialize(); + + prepare_script_environment(hPython); + // widen the argv array for py3k. + memset(wargv, 0, sizeof(wargv)); + for (i=0;i 0) { + script[n] = '\n'; + script[n+1] = 0; + result = PyRun_SimpleString(script); + } + } + } + Py_Finalize(); - close(fh); - return result; + close(fh); + return result; } static int run_installscript(char *pathname, int argc, char **argv, char **pOutput) { - HINSTANCE hPython; - int result = 1; - int out_buf_size; - HANDLE redirected, old_stderr, old_stdout; - char *tempname; - - *pOutput = NULL; - - tempname = tempnam(NULL, NULL); - // We use a static CRT while the Python version we load uses - // the CRT from one of various possibile DLLs. As a result we - // need to redirect the standard handles using the API rather - // than the CRT. - redirected = CreateFile( - tempname, - GENERIC_WRITE | GENERIC_READ, - FILE_SHARE_READ, - NULL, - CREATE_ALWAYS, - FILE_ATTRIBUTE_NORMAL | FILE_FLAG_WRITE_THROUGH, - NULL); - old_stdout = GetStdHandle(STD_OUTPUT_HANDLE); - old_stderr = GetStdHandle(STD_ERROR_HANDLE); - SetStdHandle(STD_OUTPUT_HANDLE, redirected); - SetStdHandle(STD_ERROR_HANDLE, redirected); - - hPython = LoadPythonDll(pythondll); - if (hPython) { - result = do_run_installscript(hPython, pathname, argc, argv); - FreeLibrary(hPython); - } else { - fprintf(stderr, "*** Could not load Python ***"); - } - SetStdHandle(STD_OUTPUT_HANDLE, old_stdout); - SetStdHandle(STD_ERROR_HANDLE, old_stderr); - out_buf_size = min(GetFileSize(redirected, NULL), 4096); - *pOutput = malloc(out_buf_size+1); - if (*pOutput) { - DWORD nread = 0; - SetFilePointer(redirected, 0, 0, FILE_BEGIN); - ReadFile(redirected, *pOutput, out_buf_size, &nread, NULL); - (*pOutput)[nread] = '\0'; - } - CloseHandle(redirected); - DeleteFile(tempname); - return result; + HINSTANCE hPython; + int result = 1; + int out_buf_size; + HANDLE redirected, old_stderr, old_stdout; + char *tempname; + + *pOutput = NULL; + + tempname = tempnam(NULL, NULL); + // We use a static CRT while the Python version we load uses + // the CRT from one of various possibile DLLs. As a result we + // need to redirect the standard handles using the API rather + // than the CRT. + redirected = CreateFile( + tempname, + GENERIC_WRITE | GENERIC_READ, + FILE_SHARE_READ, + NULL, + CREATE_ALWAYS, + FILE_ATTRIBUTE_NORMAL | FILE_FLAG_WRITE_THROUGH, + NULL); + old_stdout = GetStdHandle(STD_OUTPUT_HANDLE); + old_stderr = GetStdHandle(STD_ERROR_HANDLE); + SetStdHandle(STD_OUTPUT_HANDLE, redirected); + SetStdHandle(STD_ERROR_HANDLE, redirected); + + hPython = LoadPythonDll(pythondll); + if (hPython) { + result = do_run_installscript(hPython, pathname, argc, argv); + FreeLibrary(hPython); + } else { + fprintf(stderr, "*** Could not load Python ***"); + } + SetStdHandle(STD_OUTPUT_HANDLE, old_stdout); + SetStdHandle(STD_ERROR_HANDLE, old_stderr); + out_buf_size = min(GetFileSize(redirected, NULL), 4096); + *pOutput = malloc(out_buf_size+1); + if (*pOutput) { + DWORD nread = 0; + SetFilePointer(redirected, 0, 0, FILE_BEGIN); + ReadFile(redirected, *pOutput, out_buf_size, &nread, NULL); + (*pOutput)[nread] = '\0'; + } + CloseHandle(redirected); + DeleteFile(tempname); + return result; } static int do_run_simple_script(HINSTANCE hPython, char *script) { - int rc; - DECLPROC(hPython, void, Py_Initialize, (void)); - DECLPROC(hPython, void, Py_SetProgramName, (wchar_t *)); - DECLPROC(hPython, void, Py_Finalize, (void)); - DECLPROC(hPython, int, PyRun_SimpleString, (char *)); - DECLPROC(hPython, void, PyErr_Print, (void)); - - if (!Py_Initialize || !Py_SetProgramName || !Py_Finalize || - !PyRun_SimpleString || !PyErr_Print) - return -1; - - Py_SetProgramName(wmodulename); - Py_Initialize(); - prepare_script_environment(hPython); - rc = PyRun_SimpleString(script); - if (rc) - PyErr_Print(); - Py_Finalize(); - return rc; + int rc; + DECLPROC(hPython, void, Py_Initialize, (void)); + DECLPROC(hPython, void, Py_SetProgramName, (wchar_t *)); + DECLPROC(hPython, void, Py_Finalize, (void)); + DECLPROC(hPython, int, PyRun_SimpleString, (char *)); + DECLPROC(hPython, void, PyErr_Print, (void)); + + if (!Py_Initialize || !Py_SetProgramName || !Py_Finalize || + !PyRun_SimpleString || !PyErr_Print) + return -1; + + Py_SetProgramName(wmodulename); + Py_Initialize(); + prepare_script_environment(hPython); + rc = PyRun_SimpleString(script); + if (rc) + PyErr_Print(); + Py_Finalize(); + return rc; } static int run_simple_script(char *script) { - int rc; - HINSTANCE hPython; - char *tempname = tempnam(NULL, NULL); - // Redirect output using win32 API - see comments above... - HANDLE redirected = CreateFile( - tempname, - GENERIC_WRITE | GENERIC_READ, - FILE_SHARE_READ, - NULL, - CREATE_ALWAYS, - FILE_ATTRIBUTE_NORMAL | FILE_FLAG_WRITE_THROUGH, - NULL); - HANDLE old_stdout = GetStdHandle(STD_OUTPUT_HANDLE); - HANDLE old_stderr = GetStdHandle(STD_ERROR_HANDLE); - SetStdHandle(STD_OUTPUT_HANDLE, redirected); - SetStdHandle(STD_ERROR_HANDLE, redirected); - - hPython = LoadPythonDll(pythondll); - if (!hPython) { - char reason[128]; - wsprintf(reason, "Can't load Python for pre-install script (%d)", GetLastError()); - set_failure_reason(reason); - return -1; - } - rc = do_run_simple_script(hPython, script); - FreeLibrary(hPython); - SetStdHandle(STD_OUTPUT_HANDLE, old_stdout); - SetStdHandle(STD_ERROR_HANDLE, old_stderr); - /* We only care about the output when we fail. If the script works - OK, then we discard it - */ - if (rc) { - int err_buf_size; - char *err_buf; - const char *prefix = "Running the pre-installation script failed\r\n"; - int prefix_len = strlen(prefix); - err_buf_size = GetFileSize(redirected, NULL); - if (err_buf_size==INVALID_FILE_SIZE) // an error - let's try anyway... - err_buf_size = 4096; - err_buf = malloc(prefix_len + err_buf_size + 1); - if (err_buf) { - DWORD n = 0; - strcpy(err_buf, prefix); - SetFilePointer(redirected, 0, 0, FILE_BEGIN); - ReadFile(redirected, err_buf+prefix_len, err_buf_size, &n, NULL); - err_buf[prefix_len+n] = '\0'; - set_failure_reason(err_buf); - free(err_buf); - } else { - set_failure_reason("Out of memory!"); - } - } - CloseHandle(redirected); - DeleteFile(tempname); - return rc; + int rc; + HINSTANCE hPython; + char *tempname = tempnam(NULL, NULL); + // Redirect output using win32 API - see comments above... + HANDLE redirected = CreateFile( + tempname, + GENERIC_WRITE | GENERIC_READ, + FILE_SHARE_READ, + NULL, + CREATE_ALWAYS, + FILE_ATTRIBUTE_NORMAL | FILE_FLAG_WRITE_THROUGH, + NULL); + HANDLE old_stdout = GetStdHandle(STD_OUTPUT_HANDLE); + HANDLE old_stderr = GetStdHandle(STD_ERROR_HANDLE); + SetStdHandle(STD_OUTPUT_HANDLE, redirected); + SetStdHandle(STD_ERROR_HANDLE, redirected); + + hPython = LoadPythonDll(pythondll); + if (!hPython) { + char reason[128]; + wsprintf(reason, "Can't load Python for pre-install script (%d)", GetLastError()); + set_failure_reason(reason); + return -1; + } + rc = do_run_simple_script(hPython, script); + FreeLibrary(hPython); + SetStdHandle(STD_OUTPUT_HANDLE, old_stdout); + SetStdHandle(STD_ERROR_HANDLE, old_stderr); + /* We only care about the output when we fail. If the script works + OK, then we discard it + */ + if (rc) { + int err_buf_size; + char *err_buf; + const char *prefix = "Running the pre-installation script failed\r\n"; + int prefix_len = strlen(prefix); + err_buf_size = GetFileSize(redirected, NULL); + if (err_buf_size==INVALID_FILE_SIZE) // an error - let's try anyway... + err_buf_size = 4096; + err_buf = malloc(prefix_len + err_buf_size + 1); + if (err_buf) { + DWORD n = 0; + strcpy(err_buf, prefix); + SetFilePointer(redirected, 0, 0, FILE_BEGIN); + ReadFile(redirected, err_buf+prefix_len, err_buf_size, &n, NULL); + err_buf[prefix_len+n] = '\0'; + set_failure_reason(err_buf); + free(err_buf); + } else { + set_failure_reason("Out of memory!"); + } + } + CloseHandle(redirected); + DeleteFile(tempname); + return rc; } static BOOL SystemError(int error, char *msg) { - char Buffer[1024]; - int n; + char Buffer[1024]; + int n; - if (error) { - LPVOID lpMsgBuf; - FormatMessage( - FORMAT_MESSAGE_ALLOCATE_BUFFER | - FORMAT_MESSAGE_FROM_SYSTEM, - NULL, - error, - MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), - (LPSTR)&lpMsgBuf, - 0, - NULL - ); - strncpy(Buffer, lpMsgBuf, sizeof(Buffer)); - LocalFree(lpMsgBuf); - } else - Buffer[0] = '\0'; - n = lstrlen(Buffer); - _snprintf(Buffer+n, sizeof(Buffer)-n, msg); - MessageBox(hwndMain, Buffer, "Runtime Error", MB_OK | MB_ICONSTOP); - return FALSE; + if (error) { + LPVOID lpMsgBuf; + FormatMessage( + FORMAT_MESSAGE_ALLOCATE_BUFFER | + FORMAT_MESSAGE_FROM_SYSTEM, + NULL, + error, + MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), + (LPSTR)&lpMsgBuf, + 0, + NULL + ); + strncpy(Buffer, lpMsgBuf, sizeof(Buffer)); + LocalFree(lpMsgBuf); + } else + Buffer[0] = '\0'; + n = lstrlen(Buffer); + _snprintf(Buffer+n, sizeof(Buffer)-n, msg); + MessageBox(hwndMain, Buffer, "Runtime Error", MB_OK | MB_ICONSTOP); + return FALSE; } static BOOL notify (int code, char *fmt, ...) { - char Buffer[1024]; - va_list marker; - BOOL result = TRUE; - int a, b; - char *cp; + char Buffer[1024]; + va_list marker; + BOOL result = TRUE; + int a, b; + char *cp; - va_start(marker, fmt); - _vsnprintf(Buffer, sizeof(Buffer), fmt, marker); + va_start(marker, fmt); + _vsnprintf(Buffer, sizeof(Buffer), fmt, marker); - switch (code) { + switch (code) { /* Questions */ - case CAN_OVERWRITE: - break; + case CAN_OVERWRITE: + break; /* Information notification */ - case DIR_CREATED: - if (logfile) - fprintf(logfile, "100 Made Dir: %s\n", fmt); - break; - - case FILE_CREATED: - if (logfile) - fprintf(logfile, "200 File Copy: %s\n", fmt); - goto add_to_filelist_label; - break; - - case FILE_OVERWRITTEN: - if (logfile) - fprintf(logfile, "200 File Overwrite: %s\n", fmt); - add_to_filelist_label: - if ((cp = strrchr(fmt, '.')) && (0 == strcmp (cp, ".py"))) - add_to_filelist(fmt); - break; + case DIR_CREATED: + if (logfile) + fprintf(logfile, "100 Made Dir: %s\n", fmt); + break; + + case FILE_CREATED: + if (logfile) + fprintf(logfile, "200 File Copy: %s\n", fmt); + goto add_to_filelist_label; + break; + + case FILE_OVERWRITTEN: + if (logfile) + fprintf(logfile, "200 File Overwrite: %s\n", fmt); + add_to_filelist_label: + if ((cp = strrchr(fmt, '.')) && (0 == strcmp (cp, ".py"))) + add_to_filelist(fmt); + break; /* Error Messages */ - case ZLIB_ERROR: - MessageBox(GetFocus(), Buffer, "Error", - MB_OK | MB_ICONWARNING); - break; - - case SYSTEM_ERROR: - SystemError(GetLastError(), Buffer); - break; - - case NUM_FILES: - a = va_arg(marker, int); - b = va_arg(marker, int); - SendMessage(hDialog, WM_NUMFILES, 0, MAKELPARAM(0, a)); - SendMessage(hDialog, WM_NEXTFILE, b,(LPARAM)fmt); - } - va_end(marker); - - return result; + case ZLIB_ERROR: + MessageBox(GetFocus(), Buffer, "Error", + MB_OK | MB_ICONWARNING); + break; + + case SYSTEM_ERROR: + SystemError(GetLastError(), Buffer); + break; + + case NUM_FILES: + a = va_arg(marker, int); + b = va_arg(marker, int); + SendMessage(hDialog, WM_NUMFILES, 0, MAKELPARAM(0, a)); + SendMessage(hDialog, WM_NEXTFILE, b,(LPARAM)fmt); + } + va_end(marker); + + return result; } static char *MapExistingFile(char *pathname, DWORD *psize) { - HANDLE hFile, hFileMapping; - DWORD nSizeLow, nSizeHigh; - char *data; - - hFile = CreateFile(pathname, - GENERIC_READ, FILE_SHARE_READ, NULL, - OPEN_EXISTING, - FILE_ATTRIBUTE_NORMAL, NULL); - if (hFile == INVALID_HANDLE_VALUE) - return NULL; - nSizeLow = GetFileSize(hFile, &nSizeHigh); - hFileMapping = CreateFileMapping(hFile, - NULL, PAGE_READONLY, 0, 0, NULL); - CloseHandle(hFile); - - if (hFileMapping == INVALID_HANDLE_VALUE) - return NULL; - - data = MapViewOfFile(hFileMapping, - FILE_MAP_READ, 0, 0, 0); - - CloseHandle(hFileMapping); - *psize = nSizeLow; - return data; + HANDLE hFile, hFileMapping; + DWORD nSizeLow, nSizeHigh; + char *data; + + hFile = CreateFile(pathname, + GENERIC_READ, FILE_SHARE_READ, NULL, + OPEN_EXISTING, + FILE_ATTRIBUTE_NORMAL, NULL); + if (hFile == INVALID_HANDLE_VALUE) + return NULL; + nSizeLow = GetFileSize(hFile, &nSizeHigh); + hFileMapping = CreateFileMapping(hFile, + NULL, PAGE_READONLY, 0, 0, NULL); + CloseHandle(hFile); + + if (hFileMapping == INVALID_HANDLE_VALUE) + return NULL; + + data = MapViewOfFile(hFileMapping, + FILE_MAP_READ, 0, 0, 0); + + CloseHandle(hFileMapping); + *psize = nSizeLow; + return data; } static void create_bitmap(HWND hwnd) { - BITMAPFILEHEADER *bfh; - BITMAPINFO *bi; - HDC hdc; - - if (!bitmap_bytes) - return; - - if (hBitmap) - return; - - hdc = GetDC(hwnd); - - bfh = (BITMAPFILEHEADER *)bitmap_bytes; - bi = (BITMAPINFO *)(bitmap_bytes + sizeof(BITMAPFILEHEADER)); - - hBitmap = CreateDIBitmap(hdc, - &bi->bmiHeader, - CBM_INIT, - bitmap_bytes + bfh->bfOffBits, - bi, - DIB_RGB_COLORS); - ReleaseDC(hwnd, hdc); + BITMAPFILEHEADER *bfh; + BITMAPINFO *bi; + HDC hdc; + + if (!bitmap_bytes) + return; + + if (hBitmap) + return; + + hdc = GetDC(hwnd); + + bfh = (BITMAPFILEHEADER *)bitmap_bytes; + bi = (BITMAPINFO *)(bitmap_bytes + sizeof(BITMAPFILEHEADER)); + + hBitmap = CreateDIBitmap(hdc, + &bi->bmiHeader, + CBM_INIT, + bitmap_bytes + bfh->bfOffBits, + bi, + DIB_RGB_COLORS); + ReleaseDC(hwnd, hdc); } /* Extract everything we need to begin the installation. Currently this is the INI filename with install data, and the raw pre-install script */ static BOOL ExtractInstallData(char *data, DWORD size, int *pexe_size, - char **out_ini_file, char **out_preinstall_script) + char **out_ini_file, char **out_preinstall_script) { - /* read the end of central directory record */ - struct eof_cdir *pe = (struct eof_cdir *)&data[size - sizeof - (struct eof_cdir)]; - - int arc_start = size - sizeof (struct eof_cdir) - pe->nBytesCDir - - pe->ofsCDir; - - int ofs = arc_start - sizeof (struct meta_data_hdr); - - /* read meta_data info */ - struct meta_data_hdr *pmd = (struct meta_data_hdr *)&data[ofs]; - char *src, *dst; - char *ini_file; - char tempdir[MAX_PATH]; - - /* ensure that if we fail, we don't have garbage out pointers */ - *out_ini_file = *out_preinstall_script = NULL; - - if (pe->tag != 0x06054b50) { - return FALSE; - } - - if (pmd->tag != 0x1234567B) { - return SystemError(0, - "Invalid cfgdata magic number (see bdist_wininst.py)"); - } - if (ofs < 0) { - return FALSE; - } - - if (pmd->bitmap_size) { - /* Store pointer to bitmap bytes */ - bitmap_bytes = (char *)pmd - pmd->uncomp_size - pmd->bitmap_size; - } - - *pexe_size = ofs - pmd->uncomp_size - pmd->bitmap_size; - - src = ((char *)pmd) - pmd->uncomp_size; - ini_file = malloc(MAX_PATH); /* will be returned, so do not free it */ - if (!ini_file) - return FALSE; - if (!GetTempPath(sizeof(tempdir), tempdir) - || !GetTempFileName(tempdir, "~du", 0, ini_file)) { - SystemError(GetLastError(), - "Could not create temporary file"); - return FALSE; - } - - dst = map_new_file(CREATE_ALWAYS, ini_file, NULL, pmd->uncomp_size, - 0, 0, NULL/*notify*/); - if (!dst) - return FALSE; - /* Up to the first \0 is the INI file data. */ - strncpy(dst, src, pmd->uncomp_size); - src += strlen(dst) + 1; - /* Up to next \0 is the pre-install script */ - *out_preinstall_script = strdup(src); - *out_ini_file = ini_file; - UnmapViewOfFile(dst); - return TRUE; + /* read the end of central directory record */ + struct eof_cdir *pe = (struct eof_cdir *)&data[size - sizeof + (struct eof_cdir)]; + + int arc_start = size - sizeof (struct eof_cdir) - pe->nBytesCDir - + pe->ofsCDir; + + int ofs = arc_start - sizeof (struct meta_data_hdr); + + /* read meta_data info */ + struct meta_data_hdr *pmd = (struct meta_data_hdr *)&data[ofs]; + char *src, *dst; + char *ini_file; + char tempdir[MAX_PATH]; + + /* ensure that if we fail, we don't have garbage out pointers */ + *out_ini_file = *out_preinstall_script = NULL; + + if (pe->tag != 0x06054b50) { + return FALSE; + } + + if (pmd->tag != 0x1234567B) { + return SystemError(0, + "Invalid cfgdata magic number (see bdist_wininst.py)"); + } + if (ofs < 0) { + return FALSE; + } + + if (pmd->bitmap_size) { + /* Store pointer to bitmap bytes */ + bitmap_bytes = (char *)pmd - pmd->uncomp_size - pmd->bitmap_size; + } + + *pexe_size = ofs - pmd->uncomp_size - pmd->bitmap_size; + + src = ((char *)pmd) - pmd->uncomp_size; + ini_file = malloc(MAX_PATH); /* will be returned, so do not free it */ + if (!ini_file) + return FALSE; + if (!GetTempPath(sizeof(tempdir), tempdir) + || !GetTempFileName(tempdir, "~du", 0, ini_file)) { + SystemError(GetLastError(), + "Could not create temporary file"); + return FALSE; + } + + dst = map_new_file(CREATE_ALWAYS, ini_file, NULL, pmd->uncomp_size, + 0, 0, NULL/*notify*/); + if (!dst) + return FALSE; + /* Up to the first \0 is the INI file data. */ + strncpy(dst, src, pmd->uncomp_size); + src += strlen(dst) + 1; + /* Up to next \0 is the pre-install script */ + *out_preinstall_script = strdup(src); + *out_ini_file = ini_file; + UnmapViewOfFile(dst); + return TRUE; } static void PumpMessages(void) { - MSG msg; - while (PeekMessage(&msg, NULL, 0, 0, PM_REMOVE)) { - TranslateMessage(&msg); - DispatchMessage(&msg); - } + MSG msg; + while (PeekMessage(&msg, NULL, 0, 0, PM_REMOVE)) { + TranslateMessage(&msg); + DispatchMessage(&msg); + } } LRESULT CALLBACK WindowProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam) { - HDC hdc; - HFONT hFont; - int h; - PAINTSTRUCT ps; - switch (msg) { - case WM_PAINT: - hdc = BeginPaint(hwnd, &ps); - h = GetSystemMetrics(SM_CYSCREEN) / 10; - hFont = CreateFont(h, 0, 0, 0, 700, TRUE, - 0, 0, 0, 0, 0, 0, 0, "Times Roman"); - hFont = SelectObject(hdc, hFont); - SetBkMode(hdc, TRANSPARENT); - TextOut(hdc, 15, 15, title, strlen(title)); - SetTextColor(hdc, RGB(255, 255, 255)); - TextOut(hdc, 10, 10, title, strlen(title)); - DeleteObject(SelectObject(hdc, hFont)); - EndPaint(hwnd, &ps); - return 0; - } - return DefWindowProc(hwnd, msg, wParam, lParam); + HDC hdc; + HFONT hFont; + int h; + PAINTSTRUCT ps; + switch (msg) { + case WM_PAINT: + hdc = BeginPaint(hwnd, &ps); + h = GetSystemMetrics(SM_CYSCREEN) / 10; + hFont = CreateFont(h, 0, 0, 0, 700, TRUE, + 0, 0, 0, 0, 0, 0, 0, "Times Roman"); + hFont = SelectObject(hdc, hFont); + SetBkMode(hdc, TRANSPARENT); + TextOut(hdc, 15, 15, title, strlen(title)); + SetTextColor(hdc, RGB(255, 255, 255)); + TextOut(hdc, 10, 10, title, strlen(title)); + DeleteObject(SelectObject(hdc, hFont)); + EndPaint(hwnd, &ps); + return 0; + } + return DefWindowProc(hwnd, msg, wParam, lParam); } static HWND CreateBackground(char *title) { - WNDCLASS wc; - HWND hwnd; - char buffer[4096]; - - wc.style = CS_VREDRAW | CS_HREDRAW; - wc.lpfnWndProc = WindowProc; - wc.cbWndExtra = 0; - wc.cbClsExtra = 0; - wc.hInstance = GetModuleHandle(NULL); - wc.hIcon = NULL; - wc.hCursor = LoadCursor(NULL, IDC_ARROW); - wc.hbrBackground = CreateSolidBrush(RGB(0, 0, 128)); - wc.lpszMenuName = NULL; - wc.lpszClassName = "SetupWindowClass"; - - if (!RegisterClass(&wc)) - MessageBox(hwndMain, - "Could not register window class", - "Setup.exe", MB_OK); - - wsprintf(buffer, "Setup %s", title); - hwnd = CreateWindow("SetupWindowClass", - buffer, - 0, - 0, 0, - GetSystemMetrics(SM_CXFULLSCREEN), - GetSystemMetrics(SM_CYFULLSCREEN), - NULL, - NULL, - GetModuleHandle(NULL), - NULL); - ShowWindow(hwnd, SW_SHOWMAXIMIZED); - UpdateWindow(hwnd); - return hwnd; + WNDCLASS wc; + HWND hwnd; + char buffer[4096]; + + wc.style = CS_VREDRAW | CS_HREDRAW; + wc.lpfnWndProc = WindowProc; + wc.cbWndExtra = 0; + wc.cbClsExtra = 0; + wc.hInstance = GetModuleHandle(NULL); + wc.hIcon = NULL; + wc.hCursor = LoadCursor(NULL, IDC_ARROW); + wc.hbrBackground = CreateSolidBrush(RGB(0, 0, 128)); + wc.lpszMenuName = NULL; + wc.lpszClassName = "SetupWindowClass"; + + if (!RegisterClass(&wc)) + MessageBox(hwndMain, + "Could not register window class", + "Setup.exe", MB_OK); + + wsprintf(buffer, "Setup %s", title); + hwnd = CreateWindow("SetupWindowClass", + buffer, + 0, + 0, 0, + GetSystemMetrics(SM_CXFULLSCREEN), + GetSystemMetrics(SM_CYFULLSCREEN), + NULL, + NULL, + GetModuleHandle(NULL), + NULL); + ShowWindow(hwnd, SW_SHOWMAXIMIZED); + UpdateWindow(hwnd); + return hwnd; } /* @@ -1202,16 +1202,16 @@ */ static void CenterWindow(HWND hwnd) { - RECT rc; - int w, h; + RECT rc; + int w, h; - GetWindowRect(hwnd, &rc); - w = GetSystemMetrics(SM_CXSCREEN); - h = GetSystemMetrics(SM_CYSCREEN); - MoveWindow(hwnd, - (w - (rc.right-rc.left))/2, - (h - (rc.bottom-rc.top))/2, - rc.right-rc.left, rc.bottom-rc.top, FALSE); + GetWindowRect(hwnd, &rc); + w = GetSystemMetrics(SM_CXSCREEN); + h = GetSystemMetrics(SM_CYSCREEN); + MoveWindow(hwnd, + (w - (rc.right-rc.left))/2, + (h - (rc.bottom-rc.top))/2, + rc.right-rc.left, rc.bottom-rc.top, FALSE); } #include @@ -1219,45 +1219,45 @@ BOOL CALLBACK IntroDlgProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam) { - LPNMHDR lpnm; - char Buffer[4096]; + LPNMHDR lpnm; + char Buffer[4096]; - switch (msg) { - case WM_INITDIALOG: - create_bitmap(hwnd); - if(hBitmap) - SendDlgItemMessage(hwnd, IDC_BITMAP, STM_SETIMAGE, - IMAGE_BITMAP, (LPARAM)hBitmap); - CenterWindow(GetParent(hwnd)); - wsprintf(Buffer, - "This Wizard will install %s on your computer. " - "Click Next to continue " - "or Cancel to exit the Setup Wizard.", - meta_name); - SetDlgItemText(hwnd, IDC_TITLE, Buffer); - SetDlgItemText(hwnd, IDC_INTRO_TEXT, info); - SetDlgItemText(hwnd, IDC_BUILD_INFO, build_info); - return FALSE; - - case WM_NOTIFY: - lpnm = (LPNMHDR) lParam; - - switch (lpnm->code) { - case PSN_SETACTIVE: - PropSheet_SetWizButtons(GetParent(hwnd), PSWIZB_NEXT); - break; - - case PSN_WIZNEXT: - break; - - case PSN_RESET: - break; - - default: - break; - } - } - return FALSE; + switch (msg) { + case WM_INITDIALOG: + create_bitmap(hwnd); + if(hBitmap) + SendDlgItemMessage(hwnd, IDC_BITMAP, STM_SETIMAGE, + IMAGE_BITMAP, (LPARAM)hBitmap); + CenterWindow(GetParent(hwnd)); + wsprintf(Buffer, + "This Wizard will install %s on your computer. " + "Click Next to continue " + "or Cancel to exit the Setup Wizard.", + meta_name); + SetDlgItemText(hwnd, IDC_TITLE, Buffer); + SetDlgItemText(hwnd, IDC_INTRO_TEXT, info); + SetDlgItemText(hwnd, IDC_BUILD_INFO, build_info); + return FALSE; + + case WM_NOTIFY: + lpnm = (LPNMHDR) lParam; + + switch (lpnm->code) { + case PSN_SETACTIVE: + PropSheet_SetWizButtons(GetParent(hwnd), PSWIZB_NEXT); + break; + + case PSN_WIZNEXT: + break; + + case PSN_RESET: + break; + + default: + break; + } + } + return FALSE; } #ifdef USE_OTHER_PYTHON_VERSIONS @@ -1269,133 +1269,133 @@ int bound_image_minor; static BOOL __stdcall StatusRoutine(IMAGEHLP_STATUS_REASON reason, - PSTR ImageName, - PSTR DllName, - ULONG Va, - ULONG Parameter) -{ - char fname[_MAX_PATH]; - int int_version; - - switch(reason) { - case BindOutOfMemory: - case BindRvaToVaFailed: - case BindNoRoomInImage: - case BindImportProcedureFailed: - break; - - case BindImportProcedure: - case BindForwarder: - case BindForwarderNOT: - case BindImageModified: - case BindExpandFileHeaders: - case BindImageComplete: - case BindSymbolsNotUpdated: - case BindMismatchedSymbols: - case BindImportModuleFailed: - break; - - case BindImportModule: - if (1 == sscanf(DllName, "python%d", &int_version)) { - SearchPath(NULL, DllName, NULL, sizeof(fname), - fname, NULL); - strcpy(bound_image_dll, fname); - bound_image_major = int_version / 10; - bound_image_minor = int_version % 10; - OutputDebugString("BOUND "); - OutputDebugString(fname); - OutputDebugString("\n"); - } - break; - } - return TRUE; + PSTR ImageName, + PSTR DllName, + ULONG Va, + ULONG Parameter) +{ + char fname[_MAX_PATH]; + int int_version; + + switch(reason) { + case BindOutOfMemory: + case BindRvaToVaFailed: + case BindNoRoomInImage: + case BindImportProcedureFailed: + break; + + case BindImportProcedure: + case BindForwarder: + case BindForwarderNOT: + case BindImageModified: + case BindExpandFileHeaders: + case BindImageComplete: + case BindSymbolsNotUpdated: + case BindMismatchedSymbols: + case BindImportModuleFailed: + break; + + case BindImportModule: + if (1 == sscanf(DllName, "python%d", &int_version)) { + SearchPath(NULL, DllName, NULL, sizeof(fname), + fname, NULL); + strcpy(bound_image_dll, fname); + bound_image_major = int_version / 10; + bound_image_minor = int_version % 10; + OutputDebugString("BOUND "); + OutputDebugString(fname); + OutputDebugString("\n"); + } + break; + } + return TRUE; } /* */ static LPSTR get_sys_prefix(LPSTR exe, LPSTR dll) { - void (__cdecl * Py_Initialize)(void); - void (__cdecl * Py_SetProgramName)(char *); - void (__cdecl * Py_Finalize)(void); - void* (__cdecl * PySys_GetObject)(char *); - void (__cdecl * PySys_SetArgv)(int, char **); - char* (__cdecl * Py_GetPrefix)(void); - char* (__cdecl * Py_GetPath)(void); - HINSTANCE hPython; - LPSTR prefix = NULL; - int (__cdecl * PyRun_SimpleString)(char *); - - { - char Buffer[256]; - wsprintf(Buffer, "PYTHONHOME=%s", exe); - *strrchr(Buffer, '\\') = '\0'; -// MessageBox(GetFocus(), Buffer, "PYTHONHOME", MB_OK); - _putenv(Buffer); - _putenv("PYTHONPATH="); - } - - hPython = LoadLibrary(dll); - if (!hPython) - return NULL; - Py_Initialize = (void (*)(void))GetProcAddress - (hPython,"Py_Initialize"); - - PySys_SetArgv = (void (*)(int, char **))GetProcAddress - (hPython,"PySys_SetArgv"); - - PyRun_SimpleString = (int (*)(char *))GetProcAddress - (hPython,"PyRun_SimpleString"); - - Py_SetProgramName = (void (*)(char *))GetProcAddress - (hPython,"Py_SetProgramName"); - - PySys_GetObject = (void* (*)(char *))GetProcAddress - (hPython,"PySys_GetObject"); - - Py_GetPrefix = (char * (*)(void))GetProcAddress - (hPython,"Py_GetPrefix"); - - Py_GetPath = (char * (*)(void))GetProcAddress - (hPython,"Py_GetPath"); - - Py_Finalize = (void (*)(void))GetProcAddress(hPython, - "Py_Finalize"); - Py_SetProgramName(exe); - Py_Initialize(); - PySys_SetArgv(1, &exe); + void (__cdecl * Py_Initialize)(void); + void (__cdecl * Py_SetProgramName)(char *); + void (__cdecl * Py_Finalize)(void); + void* (__cdecl * PySys_GetObject)(char *); + void (__cdecl * PySys_SetArgv)(int, char **); + char* (__cdecl * Py_GetPrefix)(void); + char* (__cdecl * Py_GetPath)(void); + HINSTANCE hPython; + LPSTR prefix = NULL; + int (__cdecl * PyRun_SimpleString)(char *); + + { + char Buffer[256]; + wsprintf(Buffer, "PYTHONHOME=%s", exe); + *strrchr(Buffer, '\\') = '\0'; +// MessageBox(GetFocus(), Buffer, "PYTHONHOME", MB_OK); + _putenv(Buffer); + _putenv("PYTHONPATH="); + } + + hPython = LoadLibrary(dll); + if (!hPython) + return NULL; + Py_Initialize = (void (*)(void))GetProcAddress + (hPython,"Py_Initialize"); + + PySys_SetArgv = (void (*)(int, char **))GetProcAddress + (hPython,"PySys_SetArgv"); + + PyRun_SimpleString = (int (*)(char *))GetProcAddress + (hPython,"PyRun_SimpleString"); + + Py_SetProgramName = (void (*)(char *))GetProcAddress + (hPython,"Py_SetProgramName"); + + PySys_GetObject = (void* (*)(char *))GetProcAddress + (hPython,"PySys_GetObject"); + + Py_GetPrefix = (char * (*)(void))GetProcAddress + (hPython,"Py_GetPrefix"); + + Py_GetPath = (char * (*)(void))GetProcAddress + (hPython,"Py_GetPath"); + + Py_Finalize = (void (*)(void))GetProcAddress(hPython, + "Py_Finalize"); + Py_SetProgramName(exe); + Py_Initialize(); + PySys_SetArgv(1, &exe); - MessageBox(GetFocus(), Py_GetPrefix(), "PREFIX", MB_OK); - MessageBox(GetFocus(), Py_GetPath(), "PATH", MB_OK); + MessageBox(GetFocus(), Py_GetPrefix(), "PREFIX", MB_OK); + MessageBox(GetFocus(), Py_GetPath(), "PATH", MB_OK); - Py_Finalize(); - FreeLibrary(hPython); + Py_Finalize(); + FreeLibrary(hPython); - return prefix; + return prefix; } static BOOL CheckPythonExe(LPSTR pathname, LPSTR version, int *pmajor, int *pminor) { - bound_image_dll[0] = '\0'; - if (!BindImageEx(BIND_NO_BOUND_IMPORTS | BIND_NO_UPDATE | BIND_ALL_IMAGES, - pathname, - NULL, - NULL, - StatusRoutine)) - return SystemError(0, "Could not bind image"); - if (bound_image_dll[0] == '\0') - return SystemError(0, "Does not seem to be a python executable"); - *pmajor = bound_image_major; - *pminor = bound_image_minor; - if (version && *version) { - char core_version[12]; - wsprintf(core_version, "%d.%d", bound_image_major, bound_image_minor); - if (strcmp(version, core_version)) - return SystemError(0, "Wrong Python version"); - } - get_sys_prefix(pathname, bound_image_dll); - return TRUE; + bound_image_dll[0] = '\0'; + if (!BindImageEx(BIND_NO_BOUND_IMPORTS | BIND_NO_UPDATE | BIND_ALL_IMAGES, + pathname, + NULL, + NULL, + StatusRoutine)) + return SystemError(0, "Could not bind image"); + if (bound_image_dll[0] == '\0') + return SystemError(0, "Does not seem to be a python executable"); + *pmajor = bound_image_major; + *pminor = bound_image_minor; + if (version && *version) { + char core_version[12]; + wsprintf(core_version, "%d.%d", bound_image_major, bound_image_minor); + if (strcmp(version, core_version)) + return SystemError(0, "Wrong Python version"); + } + get_sys_prefix(pathname, bound_image_dll); + return TRUE; } /* @@ -1404,48 +1404,48 @@ */ static BOOL GetOtherPythonVersion(HWND hwnd, LPSTR version) { - char vers_name[_MAX_PATH + 80]; - DWORD itemindex; - OPENFILENAME of; - char pathname[_MAX_PATH]; - DWORD result; - - strcpy(pathname, "python.exe"); - - memset(&of, 0, sizeof(of)); - of.lStructSize = sizeof(OPENFILENAME); - of.hwndOwner = GetParent(hwnd); - of.hInstance = NULL; - of.lpstrFilter = "python.exe\0python.exe\0"; - of.lpstrCustomFilter = NULL; - of.nMaxCustFilter = 0; - of.nFilterIndex = 1; - of.lpstrFile = pathname; - of.nMaxFile = sizeof(pathname); - of.lpstrFileTitle = NULL; - of.nMaxFileTitle = 0; - of.lpstrInitialDir = NULL; - of.lpstrTitle = "Python executable"; - of.Flags = OFN_FILEMUSTEXIST | OFN_PATHMUSTEXIST; - of.lpstrDefExt = "exe"; - - result = GetOpenFileName(&of); - if (result) { - int major, minor; - if (!CheckPythonExe(pathname, version, &major, &minor)) { - return FALSE; - } - *strrchr(pathname, '\\') = '\0'; - wsprintf(vers_name, "Python Version %d.%d in %s", - major, minor, pathname); - itemindex = SendMessage(hwnd, LB_INSERTSTRING, -1, - (LPARAM)(LPSTR)vers_name); - SendMessage(hwnd, LB_SETCURSEL, itemindex, 0); - SendMessage(hwnd, LB_SETITEMDATA, itemindex, - (LPARAM)(LPSTR)strdup(pathname)); - return TRUE; - } - return FALSE; + char vers_name[_MAX_PATH + 80]; + DWORD itemindex; + OPENFILENAME of; + char pathname[_MAX_PATH]; + DWORD result; + + strcpy(pathname, "python.exe"); + + memset(&of, 0, sizeof(of)); + of.lStructSize = sizeof(OPENFILENAME); + of.hwndOwner = GetParent(hwnd); + of.hInstance = NULL; + of.lpstrFilter = "python.exe\0python.exe\0"; + of.lpstrCustomFilter = NULL; + of.nMaxCustFilter = 0; + of.nFilterIndex = 1; + of.lpstrFile = pathname; + of.nMaxFile = sizeof(pathname); + of.lpstrFileTitle = NULL; + of.nMaxFileTitle = 0; + of.lpstrInitialDir = NULL; + of.lpstrTitle = "Python executable"; + of.Flags = OFN_FILEMUSTEXIST | OFN_PATHMUSTEXIST; + of.lpstrDefExt = "exe"; + + result = GetOpenFileName(&of); + if (result) { + int major, minor; + if (!CheckPythonExe(pathname, version, &major, &minor)) { + return FALSE; + } + *strrchr(pathname, '\\') = '\0'; + wsprintf(vers_name, "Python Version %d.%d in %s", + major, minor, pathname); + itemindex = SendMessage(hwnd, LB_INSERTSTRING, -1, + (LPARAM)(LPSTR)vers_name); + SendMessage(hwnd, LB_SETCURSEL, itemindex, 0); + SendMessage(hwnd, LB_SETITEMDATA, itemindex, + (LPARAM)(LPSTR)strdup(pathname)); + return TRUE; + } + return FALSE; } #endif /* USE_OTHER_PYTHON_VERSIONS */ @@ -1462,71 +1462,71 @@ */ static BOOL GetPythonVersions(HWND hwnd, HKEY hkRoot, LPSTR version) { - DWORD index = 0; - char core_version[80]; - HKEY hKey; - BOOL result = TRUE; - DWORD bufsize; - - if (ERROR_SUCCESS != RegOpenKeyEx(hkRoot, - "Software\\Python\\PythonCore", - 0, KEY_READ, &hKey)) - return FALSE; - bufsize = sizeof(core_version); - while (ERROR_SUCCESS == RegEnumKeyEx(hKey, index, - core_version, &bufsize, NULL, - NULL, NULL, NULL)) { - char subkey_name[80], vers_name[80]; - int itemindex; - DWORD value_size; - HKEY hk; - - bufsize = sizeof(core_version); - ++index; - if (version && *version && strcmp(version, core_version)) - continue; - - wsprintf(vers_name, "Python Version %s (found in registry)", - core_version); - wsprintf(subkey_name, - "Software\\Python\\PythonCore\\%s\\InstallPath", - core_version); - if (ERROR_SUCCESS == RegOpenKeyEx(hkRoot, subkey_name, 0, KEY_READ, &hk)) { - InstalledVersionInfo *ivi = - (InstalledVersionInfo *)malloc(sizeof(InstalledVersionInfo)); - value_size = sizeof(ivi->prefix); - if (ivi && - ERROR_SUCCESS == RegQueryValueEx(hk, NULL, NULL, NULL, - ivi->prefix, &value_size)) { - itemindex = SendMessage(hwnd, LB_ADDSTRING, 0, - (LPARAM)(LPSTR)vers_name); - ivi->hkey = hkRoot; - SendMessage(hwnd, LB_SETITEMDATA, itemindex, - (LPARAM)(LPSTR)ivi); - } - RegCloseKey(hk); - } - } - RegCloseKey(hKey); - return result; + DWORD index = 0; + char core_version[80]; + HKEY hKey; + BOOL result = TRUE; + DWORD bufsize; + + if (ERROR_SUCCESS != RegOpenKeyEx(hkRoot, + "Software\\Python\\PythonCore", + 0, KEY_READ, &hKey)) + return FALSE; + bufsize = sizeof(core_version); + while (ERROR_SUCCESS == RegEnumKeyEx(hKey, index, + core_version, &bufsize, NULL, + NULL, NULL, NULL)) { + char subkey_name[80], vers_name[80]; + int itemindex; + DWORD value_size; + HKEY hk; + + bufsize = sizeof(core_version); + ++index; + if (version && *version && strcmp(version, core_version)) + continue; + + wsprintf(vers_name, "Python Version %s (found in registry)", + core_version); + wsprintf(subkey_name, + "Software\\Python\\PythonCore\\%s\\InstallPath", + core_version); + if (ERROR_SUCCESS == RegOpenKeyEx(hkRoot, subkey_name, 0, KEY_READ, &hk)) { + InstalledVersionInfo *ivi = + (InstalledVersionInfo *)malloc(sizeof(InstalledVersionInfo)); + value_size = sizeof(ivi->prefix); + if (ivi && + ERROR_SUCCESS == RegQueryValueEx(hk, NULL, NULL, NULL, + ivi->prefix, &value_size)) { + itemindex = SendMessage(hwnd, LB_ADDSTRING, 0, + (LPARAM)(LPSTR)vers_name); + ivi->hkey = hkRoot; + SendMessage(hwnd, LB_SETITEMDATA, itemindex, + (LPARAM)(LPSTR)ivi); + } + RegCloseKey(hk); + } + } + RegCloseKey(hKey); + return result; } /* Determine if the current user can write to HKEY_LOCAL_MACHINE */ BOOL HasLocalMachinePrivs() { - HKEY hKey; - DWORD result; - static char KeyName[] = - "Software\\Microsoft\\Windows\\CurrentVersion\\Uninstall"; - - result = RegOpenKeyEx(HKEY_LOCAL_MACHINE, - KeyName, - 0, - KEY_CREATE_SUB_KEY, - &hKey); - if (result==0) - RegCloseKey(hKey); - return result==0; + HKEY hKey; + DWORD result; + static char KeyName[] = + "Software\\Microsoft\\Windows\\CurrentVersion\\Uninstall"; + + result = RegOpenKeyEx(HKEY_LOCAL_MACHINE, + KeyName, + 0, + KEY_CREATE_SUB_KEY, + &hKey); + if (result==0) + RegCloseKey(hKey); + return result==0; } // Check the root registry key to use - either HKLM or HKCU. @@ -1539,86 +1539,86 @@ // We assume hkey_root is already set to where Python itself is installed. void CheckRootKey(HWND hwnd) { - if (hkey_root==HKEY_CURRENT_USER) { - ; // as above, always install ourself in HKCU too. - } else if (hkey_root==HKEY_LOCAL_MACHINE) { - // Python in HKLM, but we may or may not have permissions there. - // Open the uninstall key with 'create' permissions - if this fails, - // we don't have permission. - if (!HasLocalMachinePrivs()) - hkey_root = HKEY_CURRENT_USER; - } else { - MessageBox(hwnd, "Don't know Python's installation type", - "Strange", MB_OK | MB_ICONSTOP); - /* Default to wherever they can, but preferring HKLM */ - hkey_root = HasLocalMachinePrivs() ? HKEY_LOCAL_MACHINE : HKEY_CURRENT_USER; - } + if (hkey_root==HKEY_CURRENT_USER) { + ; // as above, always install ourself in HKCU too. + } else if (hkey_root==HKEY_LOCAL_MACHINE) { + // Python in HKLM, but we may or may not have permissions there. + // Open the uninstall key with 'create' permissions - if this fails, + // we don't have permission. + if (!HasLocalMachinePrivs()) + hkey_root = HKEY_CURRENT_USER; + } else { + MessageBox(hwnd, "Don't know Python's installation type", + "Strange", MB_OK | MB_ICONSTOP); + /* Default to wherever they can, but preferring HKLM */ + hkey_root = HasLocalMachinePrivs() ? HKEY_LOCAL_MACHINE : HKEY_CURRENT_USER; + } } /* Return the installation scheme depending on Python version number */ SCHEME *GetScheme(int major, int minor) { - if (major > 2) - return new_scheme; - else if((major == 2) && (minor >= 2)) - return new_scheme; - return old_scheme; + if (major > 2) + return new_scheme; + else if((major == 2) && (minor >= 2)) + return new_scheme; + return old_scheme; } BOOL CALLBACK SelectPythonDlgProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam) { - LPNMHDR lpnm; + LPNMHDR lpnm; - switch (msg) { - case WM_INITDIALOG: - if (hBitmap) - SendDlgItemMessage(hwnd, IDC_BITMAP, STM_SETIMAGE, - IMAGE_BITMAP, (LPARAM)hBitmap); - GetPythonVersions(GetDlgItem(hwnd, IDC_VERSIONS_LIST), - HKEY_LOCAL_MACHINE, target_version); - GetPythonVersions(GetDlgItem(hwnd, IDC_VERSIONS_LIST), - HKEY_CURRENT_USER, target_version); - { /* select the last entry which is the highest python - version found */ - int count; - count = SendDlgItemMessage(hwnd, IDC_VERSIONS_LIST, - LB_GETCOUNT, 0, 0); - if (count && count != LB_ERR) - SendDlgItemMessage(hwnd, IDC_VERSIONS_LIST, LB_SETCURSEL, - count-1, 0); - - /* If a specific Python version is required, - * display a prominent notice showing this fact. - */ - if (target_version && target_version[0]) { - char buffer[4096]; - wsprintf(buffer, - "Python %s is required for this package. " - "Select installation to use:", - target_version); - SetDlgItemText(hwnd, IDC_TITLE, buffer); - } - - if (count == 0) { - char Buffer[4096]; - char *msg; - if (target_version && target_version[0]) { - wsprintf(Buffer, - "Python version %s required, which was not found" - " in the registry.", target_version); - msg = Buffer; - } else - msg = "No Python installation found in the registry."; - MessageBox(hwnd, msg, "Cannot install", - MB_OK | MB_ICONSTOP); - } - } - goto UpdateInstallDir; - break; + switch (msg) { + case WM_INITDIALOG: + if (hBitmap) + SendDlgItemMessage(hwnd, IDC_BITMAP, STM_SETIMAGE, + IMAGE_BITMAP, (LPARAM)hBitmap); + GetPythonVersions(GetDlgItem(hwnd, IDC_VERSIONS_LIST), + HKEY_LOCAL_MACHINE, target_version); + GetPythonVersions(GetDlgItem(hwnd, IDC_VERSIONS_LIST), + HKEY_CURRENT_USER, target_version); + { /* select the last entry which is the highest python + version found */ + int count; + count = SendDlgItemMessage(hwnd, IDC_VERSIONS_LIST, + LB_GETCOUNT, 0, 0); + if (count && count != LB_ERR) + SendDlgItemMessage(hwnd, IDC_VERSIONS_LIST, LB_SETCURSEL, + count-1, 0); + + /* If a specific Python version is required, + * display a prominent notice showing this fact. + */ + if (target_version && target_version[0]) { + char buffer[4096]; + wsprintf(buffer, + "Python %s is required for this package. " + "Select installation to use:", + target_version); + SetDlgItemText(hwnd, IDC_TITLE, buffer); + } + + if (count == 0) { + char Buffer[4096]; + char *msg; + if (target_version && target_version[0]) { + wsprintf(Buffer, + "Python version %s required, which was not found" + " in the registry.", target_version); + msg = Buffer; + } else + msg = "No Python installation found in the registry."; + MessageBox(hwnd, msg, "Cannot install", + MB_OK | MB_ICONSTOP); + } + } + goto UpdateInstallDir; + break; - case WM_COMMAND: - switch (LOWORD(wParam)) { + case WM_COMMAND: + switch (LOWORD(wParam)) { /* case IDC_OTHERPYTHON: if (GetOtherPythonVersion(GetDlgItem(hwnd, IDC_VERSIONS_LIST), @@ -1626,307 +1626,307 @@ goto UpdateInstallDir; break; */ - case IDC_VERSIONS_LIST: - switch (HIWORD(wParam)) { - int id; - case LBN_SELCHANGE: - UpdateInstallDir: - PropSheet_SetWizButtons(GetParent(hwnd), - PSWIZB_BACK | PSWIZB_NEXT); - id = SendDlgItemMessage(hwnd, IDC_VERSIONS_LIST, - LB_GETCURSEL, 0, 0); - if (id == LB_ERR) { - PropSheet_SetWizButtons(GetParent(hwnd), - PSWIZB_BACK); - SetDlgItemText(hwnd, IDC_PATH, ""); - SetDlgItemText(hwnd, IDC_INSTALL_PATH, ""); - strcpy(python_dir, ""); - strcpy(pythondll, ""); - } else { - char *pbuf; - int result; - InstalledVersionInfo *ivi; - PropSheet_SetWizButtons(GetParent(hwnd), - PSWIZB_BACK | PSWIZB_NEXT); - /* Get the python directory */ - ivi = (InstalledVersionInfo *) - SendDlgItemMessage(hwnd, - IDC_VERSIONS_LIST, - LB_GETITEMDATA, - id, - 0); - hkey_root = ivi->hkey; - strcpy(python_dir, ivi->prefix); - SetDlgItemText(hwnd, IDC_PATH, python_dir); - /* retrieve the python version and pythondll to use */ - result = SendDlgItemMessage(hwnd, IDC_VERSIONS_LIST, - LB_GETTEXTLEN, (WPARAM)id, 0); - pbuf = (char *)malloc(result + 1); - if (pbuf) { - /* guess the name of the python-dll */ - SendDlgItemMessage(hwnd, IDC_VERSIONS_LIST, - LB_GETTEXT, (WPARAM)id, - (LPARAM)pbuf); - result = sscanf(pbuf, "Python Version %d.%d", - &py_major, &py_minor); - if (result == 2) { + case IDC_VERSIONS_LIST: + switch (HIWORD(wParam)) { + int id; + case LBN_SELCHANGE: + UpdateInstallDir: + PropSheet_SetWizButtons(GetParent(hwnd), + PSWIZB_BACK | PSWIZB_NEXT); + id = SendDlgItemMessage(hwnd, IDC_VERSIONS_LIST, + LB_GETCURSEL, 0, 0); + if (id == LB_ERR) { + PropSheet_SetWizButtons(GetParent(hwnd), + PSWIZB_BACK); + SetDlgItemText(hwnd, IDC_PATH, ""); + SetDlgItemText(hwnd, IDC_INSTALL_PATH, ""); + strcpy(python_dir, ""); + strcpy(pythondll, ""); + } else { + char *pbuf; + int result; + InstalledVersionInfo *ivi; + PropSheet_SetWizButtons(GetParent(hwnd), + PSWIZB_BACK | PSWIZB_NEXT); + /* Get the python directory */ + ivi = (InstalledVersionInfo *) + SendDlgItemMessage(hwnd, + IDC_VERSIONS_LIST, + LB_GETITEMDATA, + id, + 0); + hkey_root = ivi->hkey; + strcpy(python_dir, ivi->prefix); + SetDlgItemText(hwnd, IDC_PATH, python_dir); + /* retrieve the python version and pythondll to use */ + result = SendDlgItemMessage(hwnd, IDC_VERSIONS_LIST, + LB_GETTEXTLEN, (WPARAM)id, 0); + pbuf = (char *)malloc(result + 1); + if (pbuf) { + /* guess the name of the python-dll */ + SendDlgItemMessage(hwnd, IDC_VERSIONS_LIST, + LB_GETTEXT, (WPARAM)id, + (LPARAM)pbuf); + result = sscanf(pbuf, "Python Version %d.%d", + &py_major, &py_minor); + if (result == 2) { #ifdef _DEBUG - wsprintf(pythondll, "python%d%d_d.dll", - py_major, py_minor); + wsprintf(pythondll, "python%d%d_d.dll", + py_major, py_minor); #else - wsprintf(pythondll, "python%d%d.dll", - py_major, py_minor); + wsprintf(pythondll, "python%d%d.dll", + py_major, py_minor); #endif - } - free(pbuf); - } else - strcpy(pythondll, ""); - /* retrieve the scheme for this version */ - { - char install_path[_MAX_PATH]; - SCHEME *scheme = GetScheme(py_major, py_minor); - strcpy(install_path, python_dir); - if (install_path[strlen(install_path)-1] != '\\') - strcat(install_path, "\\"); - strcat(install_path, scheme[0].prefix); - SetDlgItemText(hwnd, IDC_INSTALL_PATH, install_path); - } - } - } - break; - } - return 0; - - case WM_NOTIFY: - lpnm = (LPNMHDR) lParam; - - switch (lpnm->code) { - int id; - case PSN_SETACTIVE: - id = SendDlgItemMessage(hwnd, IDC_VERSIONS_LIST, - LB_GETCURSEL, 0, 0); - if (id == LB_ERR) - PropSheet_SetWizButtons(GetParent(hwnd), - PSWIZB_BACK); - else - PropSheet_SetWizButtons(GetParent(hwnd), - PSWIZB_BACK | PSWIZB_NEXT); - break; - - case PSN_WIZNEXT: - break; - - case PSN_WIZFINISH: - break; - - case PSN_RESET: - break; - - default: - break; - } - } - return 0; + } + free(pbuf); + } else + strcpy(pythondll, ""); + /* retrieve the scheme for this version */ + { + char install_path[_MAX_PATH]; + SCHEME *scheme = GetScheme(py_major, py_minor); + strcpy(install_path, python_dir); + if (install_path[strlen(install_path)-1] != '\\') + strcat(install_path, "\\"); + strcat(install_path, scheme[0].prefix); + SetDlgItemText(hwnd, IDC_INSTALL_PATH, install_path); + } + } + } + break; + } + return 0; + + case WM_NOTIFY: + lpnm = (LPNMHDR) lParam; + + switch (lpnm->code) { + int id; + case PSN_SETACTIVE: + id = SendDlgItemMessage(hwnd, IDC_VERSIONS_LIST, + LB_GETCURSEL, 0, 0); + if (id == LB_ERR) + PropSheet_SetWizButtons(GetParent(hwnd), + PSWIZB_BACK); + else + PropSheet_SetWizButtons(GetParent(hwnd), + PSWIZB_BACK | PSWIZB_NEXT); + break; + + case PSN_WIZNEXT: + break; + + case PSN_WIZFINISH: + break; + + case PSN_RESET: + break; + + default: + break; + } + } + return 0; } static BOOL OpenLogfile(char *dir) { - char buffer[_MAX_PATH+1]; - time_t ltime; - struct tm *now; - long result; - HKEY hKey, hSubkey; - char subkey_name[256]; - static char KeyName[] = - "Software\\Microsoft\\Windows\\CurrentVersion\\Uninstall"; - const char *root_name = (hkey_root==HKEY_LOCAL_MACHINE ? - "HKEY_LOCAL_MACHINE" : "HKEY_CURRENT_USER"); - DWORD disposition; - - /* Use Create, as the Uninstall subkey may not exist under HKCU. - Use CreateKeyEx, so we can specify a SAM specifying write access - */ - result = RegCreateKeyEx(hkey_root, - KeyName, - 0, /* reserved */ - NULL, /* class */ - 0, /* options */ - KEY_CREATE_SUB_KEY, /* sam */ - NULL, /* security */ - &hKey, /* result key */ - NULL); /* disposition */ - if (result != ERROR_SUCCESS) { - if (result == ERROR_ACCESS_DENIED) { - /* This should no longer be able to happen - we have already - checked if they have permissions in HKLM, and all users - should have write access to HKCU. - */ - MessageBox(GetFocus(), - "You do not seem to have sufficient access rights\n" - "on this machine to install this software", - NULL, - MB_OK | MB_ICONSTOP); - return FALSE; - } else { - MessageBox(GetFocus(), KeyName, "Could not open key", MB_OK); - } - } - - sprintf(buffer, "%s\\%s-wininst.log", dir, meta_name); - logfile = fopen(buffer, "a"); - time(<ime); - now = localtime(<ime); - strftime(buffer, sizeof(buffer), - "*** Installation started %Y/%m/%d %H:%M ***\n", - localtime(<ime)); - fprintf(logfile, buffer); - fprintf(logfile, "Source: %s\n", modulename); - - /* Root key must be first entry processed by uninstaller. */ - fprintf(logfile, "999 Root Key: %s\n", root_name); - - sprintf(subkey_name, "%s-py%d.%d", meta_name, py_major, py_minor); - - result = RegCreateKeyEx(hKey, subkey_name, - 0, NULL, 0, - KEY_WRITE, - NULL, - &hSubkey, - &disposition); - - if (result != ERROR_SUCCESS) - MessageBox(GetFocus(), subkey_name, "Could not create key", MB_OK); - - RegCloseKey(hKey); - - if (disposition == REG_CREATED_NEW_KEY) - fprintf(logfile, "020 Reg DB Key: [%s]%s\n", KeyName, subkey_name); - - sprintf(buffer, "Python %d.%d %s", py_major, py_minor, title); - - result = RegSetValueEx(hSubkey, "DisplayName", - 0, - REG_SZ, - buffer, - strlen(buffer)+1); - - if (result != ERROR_SUCCESS) - MessageBox(GetFocus(), buffer, "Could not set key value", MB_OK); - - fprintf(logfile, "040 Reg DB Value: [%s\\%s]%s=%s\n", - KeyName, subkey_name, "DisplayName", buffer); - - { - FILE *fp; - sprintf(buffer, "%s\\Remove%s.exe", dir, meta_name); - fp = fopen(buffer, "wb"); - fwrite(arc_data, exe_size, 1, fp); - fclose(fp); - - sprintf(buffer, "\"%s\\Remove%s.exe\" -u \"%s\\%s-wininst.log\"", - dir, meta_name, dir, meta_name); - - result = RegSetValueEx(hSubkey, "UninstallString", - 0, - REG_SZ, - buffer, - strlen(buffer)+1); - - if (result != ERROR_SUCCESS) - MessageBox(GetFocus(), buffer, "Could not set key value", MB_OK); - - fprintf(logfile, "040 Reg DB Value: [%s\\%s]%s=%s\n", - KeyName, subkey_name, "UninstallString", buffer); - } - return TRUE; + char buffer[_MAX_PATH+1]; + time_t ltime; + struct tm *now; + long result; + HKEY hKey, hSubkey; + char subkey_name[256]; + static char KeyName[] = + "Software\\Microsoft\\Windows\\CurrentVersion\\Uninstall"; + const char *root_name = (hkey_root==HKEY_LOCAL_MACHINE ? + "HKEY_LOCAL_MACHINE" : "HKEY_CURRENT_USER"); + DWORD disposition; + + /* Use Create, as the Uninstall subkey may not exist under HKCU. + Use CreateKeyEx, so we can specify a SAM specifying write access + */ + result = RegCreateKeyEx(hkey_root, + KeyName, + 0, /* reserved */ + NULL, /* class */ + 0, /* options */ + KEY_CREATE_SUB_KEY, /* sam */ + NULL, /* security */ + &hKey, /* result key */ + NULL); /* disposition */ + if (result != ERROR_SUCCESS) { + if (result == ERROR_ACCESS_DENIED) { + /* This should no longer be able to happen - we have already + checked if they have permissions in HKLM, and all users + should have write access to HKCU. + */ + MessageBox(GetFocus(), + "You do not seem to have sufficient access rights\n" + "on this machine to install this software", + NULL, + MB_OK | MB_ICONSTOP); + return FALSE; + } else { + MessageBox(GetFocus(), KeyName, "Could not open key", MB_OK); + } + } + + sprintf(buffer, "%s\\%s-wininst.log", dir, meta_name); + logfile = fopen(buffer, "a"); + time(<ime); + now = localtime(<ime); + strftime(buffer, sizeof(buffer), + "*** Installation started %Y/%m/%d %H:%M ***\n", + localtime(<ime)); + fprintf(logfile, buffer); + fprintf(logfile, "Source: %s\n", modulename); + + /* Root key must be first entry processed by uninstaller. */ + fprintf(logfile, "999 Root Key: %s\n", root_name); + + sprintf(subkey_name, "%s-py%d.%d", meta_name, py_major, py_minor); + + result = RegCreateKeyEx(hKey, subkey_name, + 0, NULL, 0, + KEY_WRITE, + NULL, + &hSubkey, + &disposition); + + if (result != ERROR_SUCCESS) + MessageBox(GetFocus(), subkey_name, "Could not create key", MB_OK); + + RegCloseKey(hKey); + + if (disposition == REG_CREATED_NEW_KEY) + fprintf(logfile, "020 Reg DB Key: [%s]%s\n", KeyName, subkey_name); + + sprintf(buffer, "Python %d.%d %s", py_major, py_minor, title); + + result = RegSetValueEx(hSubkey, "DisplayName", + 0, + REG_SZ, + buffer, + strlen(buffer)+1); + + if (result != ERROR_SUCCESS) + MessageBox(GetFocus(), buffer, "Could not set key value", MB_OK); + + fprintf(logfile, "040 Reg DB Value: [%s\\%s]%s=%s\n", + KeyName, subkey_name, "DisplayName", buffer); + + { + FILE *fp; + sprintf(buffer, "%s\\Remove%s.exe", dir, meta_name); + fp = fopen(buffer, "wb"); + fwrite(arc_data, exe_size, 1, fp); + fclose(fp); + + sprintf(buffer, "\"%s\\Remove%s.exe\" -u \"%s\\%s-wininst.log\"", + dir, meta_name, dir, meta_name); + + result = RegSetValueEx(hSubkey, "UninstallString", + 0, + REG_SZ, + buffer, + strlen(buffer)+1); + + if (result != ERROR_SUCCESS) + MessageBox(GetFocus(), buffer, "Could not set key value", MB_OK); + + fprintf(logfile, "040 Reg DB Value: [%s\\%s]%s=%s\n", + KeyName, subkey_name, "UninstallString", buffer); + } + return TRUE; } static void CloseLogfile(void) { - char buffer[_MAX_PATH+1]; - time_t ltime; - struct tm *now; - - time(<ime); - now = localtime(<ime); - strftime(buffer, sizeof(buffer), - "*** Installation finished %Y/%m/%d %H:%M ***\n", - localtime(<ime)); - fprintf(logfile, buffer); - if (logfile) - fclose(logfile); + char buffer[_MAX_PATH+1]; + time_t ltime; + struct tm *now; + + time(<ime); + now = localtime(<ime); + strftime(buffer, sizeof(buffer), + "*** Installation finished %Y/%m/%d %H:%M ***\n", + localtime(<ime)); + fprintf(logfile, buffer); + if (logfile) + fclose(logfile); } BOOL CALLBACK InstallFilesDlgProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam) { - LPNMHDR lpnm; - char Buffer[4096]; - SCHEME *scheme; - - switch (msg) { - case WM_INITDIALOG: - if (hBitmap) - SendDlgItemMessage(hwnd, IDC_BITMAP, STM_SETIMAGE, - IMAGE_BITMAP, (LPARAM)hBitmap); - wsprintf(Buffer, - "Click Next to begin the installation of %s. " - "If you want to review or change any of your " - " installation settings, click Back. " - "Click Cancel to exit the wizard.", - meta_name); - SetDlgItemText(hwnd, IDC_TITLE, Buffer); - SetDlgItemText(hwnd, IDC_INFO, "Ready to install"); - break; - - case WM_NUMFILES: - SendDlgItemMessage(hwnd, IDC_PROGRESS, PBM_SETRANGE, 0, lParam); - PumpMessages(); - return TRUE; - - case WM_NEXTFILE: - SendDlgItemMessage(hwnd, IDC_PROGRESS, PBM_SETPOS, wParam, - 0); - SetDlgItemText(hwnd, IDC_INFO, (LPSTR)lParam); - PumpMessages(); - return TRUE; - - case WM_NOTIFY: - lpnm = (LPNMHDR) lParam; - - switch (lpnm->code) { - case PSN_SETACTIVE: - PropSheet_SetWizButtons(GetParent(hwnd), - PSWIZB_BACK | PSWIZB_NEXT); - break; - - case PSN_WIZFINISH: - break; - - case PSN_WIZNEXT: - /* Handle a Next button click here */ - hDialog = hwnd; - success = TRUE; - - /* Disable the buttons while we work. Sending CANCELTOCLOSE has - the effect of disabling the cancel button, which is a) as we - do everything synchronously we can't cancel, and b) the next - step is 'finished', when it is too late to cancel anyway. - The next step being 'Finished' means we also don't need to - restore the button state back */ - PropSheet_SetWizButtons(GetParent(hwnd), 0); - SendMessage(GetParent(hwnd), PSM_CANCELTOCLOSE, 0, 0); - /* Make sure the installation directory name ends in a */ - /* backslash */ - if (python_dir[strlen(python_dir)-1] != '\\') - strcat(python_dir, "\\"); - /* Strip the trailing backslash again */ - python_dir[strlen(python_dir)-1] = '\0'; - - CheckRootKey(hwnd); - - if (!OpenLogfile(python_dir)) - break; + LPNMHDR lpnm; + char Buffer[4096]; + SCHEME *scheme; + + switch (msg) { + case WM_INITDIALOG: + if (hBitmap) + SendDlgItemMessage(hwnd, IDC_BITMAP, STM_SETIMAGE, + IMAGE_BITMAP, (LPARAM)hBitmap); + wsprintf(Buffer, + "Click Next to begin the installation of %s. " + "If you want to review or change any of your " + " installation settings, click Back. " + "Click Cancel to exit the wizard.", + meta_name); + SetDlgItemText(hwnd, IDC_TITLE, Buffer); + SetDlgItemText(hwnd, IDC_INFO, "Ready to install"); + break; + + case WM_NUMFILES: + SendDlgItemMessage(hwnd, IDC_PROGRESS, PBM_SETRANGE, 0, lParam); + PumpMessages(); + return TRUE; + + case WM_NEXTFILE: + SendDlgItemMessage(hwnd, IDC_PROGRESS, PBM_SETPOS, wParam, + 0); + SetDlgItemText(hwnd, IDC_INFO, (LPSTR)lParam); + PumpMessages(); + return TRUE; + + case WM_NOTIFY: + lpnm = (LPNMHDR) lParam; + + switch (lpnm->code) { + case PSN_SETACTIVE: + PropSheet_SetWizButtons(GetParent(hwnd), + PSWIZB_BACK | PSWIZB_NEXT); + break; + + case PSN_WIZFINISH: + break; + + case PSN_WIZNEXT: + /* Handle a Next button click here */ + hDialog = hwnd; + success = TRUE; + + /* Disable the buttons while we work. Sending CANCELTOCLOSE has + the effect of disabling the cancel button, which is a) as we + do everything synchronously we can't cancel, and b) the next + step is 'finished', when it is too late to cancel anyway. + The next step being 'Finished' means we also don't need to + restore the button state back */ + PropSheet_SetWizButtons(GetParent(hwnd), 0); + SendMessage(GetParent(hwnd), PSM_CANCELTOCLOSE, 0, 0); + /* Make sure the installation directory name ends in a */ + /* backslash */ + if (python_dir[strlen(python_dir)-1] != '\\') + strcat(python_dir, "\\"); + /* Strip the trailing backslash again */ + python_dir[strlen(python_dir)-1] = '\0'; + + CheckRootKey(hwnd); + + if (!OpenLogfile(python_dir)) + break; /* * The scheme we have to use depends on the Python version... @@ -1947,202 +1947,202 @@ 'data' : '$base', } */ - scheme = GetScheme(py_major, py_minor); - /* Run the pre-install script. */ - if (pre_install_script && *pre_install_script) { - SetDlgItemText (hwnd, IDC_TITLE, - "Running pre-installation script"); - run_simple_script(pre_install_script); - } - if (!success) { - break; - } - /* Extract all files from the archive */ - SetDlgItemText(hwnd, IDC_TITLE, "Installing files..."); - if (!unzip_archive (scheme, - python_dir, arc_data, - arc_size, notify)) - set_failure_reason("Failed to unzip installation files"); - /* Compile the py-files */ - if (success && pyc_compile) { - int errors; - HINSTANCE hPython; - SetDlgItemText(hwnd, IDC_TITLE, - "Compiling files to .pyc..."); - - SetDlgItemText(hDialog, IDC_INFO, "Loading python..."); - hPython = LoadPythonDll(pythondll); - if (hPython) { - errors = compile_filelist(hPython, FALSE); - FreeLibrary(hPython); - } - /* Compilation errors are intentionally ignored: - * Python2.0 contains a bug which will result - * in sys.path containing garbage under certain - * circumstances, and an error message will only - * confuse the user. - */ - } - if (success && pyo_compile) { - int errors; - HINSTANCE hPython; - SetDlgItemText(hwnd, IDC_TITLE, - "Compiling files to .pyo..."); - - SetDlgItemText(hDialog, IDC_INFO, "Loading python..."); - hPython = LoadPythonDll(pythondll); - if (hPython) { - errors = compile_filelist(hPython, TRUE); - FreeLibrary(hPython); - } - /* Errors ignored: see above */ - } - - - break; - - case PSN_RESET: - break; - - default: - break; - } - } - return 0; + scheme = GetScheme(py_major, py_minor); + /* Run the pre-install script. */ + if (pre_install_script && *pre_install_script) { + SetDlgItemText (hwnd, IDC_TITLE, + "Running pre-installation script"); + run_simple_script(pre_install_script); + } + if (!success) { + break; + } + /* Extract all files from the archive */ + SetDlgItemText(hwnd, IDC_TITLE, "Installing files..."); + if (!unzip_archive (scheme, + python_dir, arc_data, + arc_size, notify)) + set_failure_reason("Failed to unzip installation files"); + /* Compile the py-files */ + if (success && pyc_compile) { + int errors; + HINSTANCE hPython; + SetDlgItemText(hwnd, IDC_TITLE, + "Compiling files to .pyc..."); + + SetDlgItemText(hDialog, IDC_INFO, "Loading python..."); + hPython = LoadPythonDll(pythondll); + if (hPython) { + errors = compile_filelist(hPython, FALSE); + FreeLibrary(hPython); + } + /* Compilation errors are intentionally ignored: + * Python2.0 contains a bug which will result + * in sys.path containing garbage under certain + * circumstances, and an error message will only + * confuse the user. + */ + } + if (success && pyo_compile) { + int errors; + HINSTANCE hPython; + SetDlgItemText(hwnd, IDC_TITLE, + "Compiling files to .pyo..."); + + SetDlgItemText(hDialog, IDC_INFO, "Loading python..."); + hPython = LoadPythonDll(pythondll); + if (hPython) { + errors = compile_filelist(hPython, TRUE); + FreeLibrary(hPython); + } + /* Errors ignored: see above */ + } + + + break; + + case PSN_RESET: + break; + + default: + break; + } + } + return 0; } BOOL CALLBACK FinishedDlgProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam) { - LPNMHDR lpnm; + LPNMHDR lpnm; - switch (msg) { - case WM_INITDIALOG: - if (hBitmap) - SendDlgItemMessage(hwnd, IDC_BITMAP, STM_SETIMAGE, - IMAGE_BITMAP, (LPARAM)hBitmap); - if (!success) - SetDlgItemText(hwnd, IDC_INFO, get_failure_reason()); - - /* async delay: will show the dialog box completely before - the install_script is started */ - PostMessage(hwnd, WM_USER, 0, 0L); - return TRUE; - - case WM_USER: - - if (success && install_script && install_script[0]) { - char fname[MAX_PATH]; - char *buffer; - HCURSOR hCursor; - int result; - - char *argv[3] = {NULL, "-install", NULL}; - - SetDlgItemText(hwnd, IDC_TITLE, - "Please wait while running postinstall script..."); - strcpy(fname, python_dir); - strcat(fname, "\\Scripts\\"); - strcat(fname, install_script); - - if (logfile) - fprintf(logfile, "300 Run Script: [%s]%s\n", pythondll, fname); - - hCursor = SetCursor(LoadCursor(NULL, IDC_WAIT)); - - argv[0] = fname; - - result = run_installscript(fname, 2, argv, &buffer); - if (0 != result) { - fprintf(stderr, "*** run_installscript: internal error 0x%X ***\n", result); - } - if (buffer) - SetDlgItemText(hwnd, IDC_INFO, buffer); - SetDlgItemText(hwnd, IDC_TITLE, - "Postinstall script finished.\n" - "Click the Finish button to exit the Setup wizard."); - - free(buffer); - SetCursor(hCursor); - CloseLogfile(); - } - - return TRUE; - - case WM_NOTIFY: - lpnm = (LPNMHDR) lParam; - - switch (lpnm->code) { - case PSN_SETACTIVE: /* Enable the Finish button */ - PropSheet_SetWizButtons(GetParent(hwnd), PSWIZB_FINISH); - break; - - case PSN_WIZNEXT: - break; - - case PSN_WIZFINISH: - break; - - case PSN_RESET: - break; - - default: - break; - } - } - return 0; + switch (msg) { + case WM_INITDIALOG: + if (hBitmap) + SendDlgItemMessage(hwnd, IDC_BITMAP, STM_SETIMAGE, + IMAGE_BITMAP, (LPARAM)hBitmap); + if (!success) + SetDlgItemText(hwnd, IDC_INFO, get_failure_reason()); + + /* async delay: will show the dialog box completely before + the install_script is started */ + PostMessage(hwnd, WM_USER, 0, 0L); + return TRUE; + + case WM_USER: + + if (success && install_script && install_script[0]) { + char fname[MAX_PATH]; + char *buffer; + HCURSOR hCursor; + int result; + + char *argv[3] = {NULL, "-install", NULL}; + + SetDlgItemText(hwnd, IDC_TITLE, + "Please wait while running postinstall script..."); + strcpy(fname, python_dir); + strcat(fname, "\\Scripts\\"); + strcat(fname, install_script); + + if (logfile) + fprintf(logfile, "300 Run Script: [%s]%s\n", pythondll, fname); + + hCursor = SetCursor(LoadCursor(NULL, IDC_WAIT)); + + argv[0] = fname; + + result = run_installscript(fname, 2, argv, &buffer); + if (0 != result) { + fprintf(stderr, "*** run_installscript: internal error 0x%X ***\n", result); + } + if (buffer) + SetDlgItemText(hwnd, IDC_INFO, buffer); + SetDlgItemText(hwnd, IDC_TITLE, + "Postinstall script finished.\n" + "Click the Finish button to exit the Setup wizard."); + + free(buffer); + SetCursor(hCursor); + CloseLogfile(); + } + + return TRUE; + + case WM_NOTIFY: + lpnm = (LPNMHDR) lParam; + + switch (lpnm->code) { + case PSN_SETACTIVE: /* Enable the Finish button */ + PropSheet_SetWizButtons(GetParent(hwnd), PSWIZB_FINISH); + break; + + case PSN_WIZNEXT: + break; + + case PSN_WIZFINISH: + break; + + case PSN_RESET: + break; + + default: + break; + } + } + return 0; } void RunWizard(HWND hwnd) { - PROPSHEETPAGE psp = {0}; - HPROPSHEETPAGE ahpsp[4] = {0}; - PROPSHEETHEADER psh = {0}; - - /* Display module information */ - psp.dwSize = sizeof(psp); - psp.dwFlags = PSP_DEFAULT|PSP_HIDEHEADER; - psp.hInstance = GetModuleHandle (NULL); - psp.lParam = 0; - psp.pfnDlgProc = IntroDlgProc; - psp.pszTemplate = MAKEINTRESOURCE(IDD_INTRO); - - ahpsp[0] = CreatePropertySheetPage(&psp); - - /* Select python version to use */ - psp.dwFlags = PSP_DEFAULT|PSP_HIDEHEADER; - psp.pszTemplate = MAKEINTRESOURCE(IDD_SELECTPYTHON); - psp.pfnDlgProc = SelectPythonDlgProc; - - ahpsp[1] = CreatePropertySheetPage(&psp); - - /* Install the files */ - psp.dwFlags = PSP_DEFAULT|PSP_HIDEHEADER; - psp.pszTemplate = MAKEINTRESOURCE(IDD_INSTALLFILES); - psp.pfnDlgProc = InstallFilesDlgProc; - - ahpsp[2] = CreatePropertySheetPage(&psp); - - /* Show success or failure */ - psp.dwFlags = PSP_DEFAULT|PSP_HIDEHEADER; - psp.pszTemplate = MAKEINTRESOURCE(IDD_FINISHED); - psp.pfnDlgProc = FinishedDlgProc; - - ahpsp[3] = CreatePropertySheetPage(&psp); - - /* Create the property sheet */ - psh.dwSize = sizeof(psh); - psh.hInstance = GetModuleHandle(NULL); - psh.hwndParent = hwnd; - psh.phpage = ahpsp; - psh.dwFlags = PSH_WIZARD/*97*//*|PSH_WATERMARK|PSH_HEADER*/; - psh.pszbmWatermark = NULL; - psh.pszbmHeader = NULL; - psh.nStartPage = 0; - psh.nPages = 4; + PROPSHEETPAGE psp = {0}; + HPROPSHEETPAGE ahpsp[4] = {0}; + PROPSHEETHEADER psh = {0}; + + /* Display module information */ + psp.dwSize = sizeof(psp); + psp.dwFlags = PSP_DEFAULT|PSP_HIDEHEADER; + psp.hInstance = GetModuleHandle (NULL); + psp.lParam = 0; + psp.pfnDlgProc = IntroDlgProc; + psp.pszTemplate = MAKEINTRESOURCE(IDD_INTRO); + + ahpsp[0] = CreatePropertySheetPage(&psp); + + /* Select python version to use */ + psp.dwFlags = PSP_DEFAULT|PSP_HIDEHEADER; + psp.pszTemplate = MAKEINTRESOURCE(IDD_SELECTPYTHON); + psp.pfnDlgProc = SelectPythonDlgProc; + + ahpsp[1] = CreatePropertySheetPage(&psp); + + /* Install the files */ + psp.dwFlags = PSP_DEFAULT|PSP_HIDEHEADER; + psp.pszTemplate = MAKEINTRESOURCE(IDD_INSTALLFILES); + psp.pfnDlgProc = InstallFilesDlgProc; + + ahpsp[2] = CreatePropertySheetPage(&psp); + + /* Show success or failure */ + psp.dwFlags = PSP_DEFAULT|PSP_HIDEHEADER; + psp.pszTemplate = MAKEINTRESOURCE(IDD_FINISHED); + psp.pfnDlgProc = FinishedDlgProc; + + ahpsp[3] = CreatePropertySheetPage(&psp); + + /* Create the property sheet */ + psh.dwSize = sizeof(psh); + psh.hInstance = GetModuleHandle(NULL); + psh.hwndParent = hwnd; + psh.phpage = ahpsp; + psh.dwFlags = PSH_WIZARD/*97*//*|PSH_WATERMARK|PSH_HEADER*/; + psh.pszbmWatermark = NULL; + psh.pszbmHeader = NULL; + psh.nStartPage = 0; + psh.nPages = 4; - PropertySheet(&psh); + PropertySheet(&psh); } // subtly different from HasLocalMachinePrivs(), in that after executing @@ -2150,16 +2150,16 @@ // such implication for HasLocalMachinePrivs BOOL MyIsUserAnAdmin() { - typedef BOOL (WINAPI *PFNIsUserAnAdmin)(); - static PFNIsUserAnAdmin pfnIsUserAnAdmin = NULL; - HMODULE shell32; - // This function isn't guaranteed to be available (and it can't hurt - // to leave the library loaded) - if (0 == (shell32=LoadLibrary("shell32.dll"))) - return FALSE; - if (0 == (pfnIsUserAnAdmin=(PFNIsUserAnAdmin)GetProcAddress(shell32, "IsUserAnAdmin"))) - return FALSE; - return (*pfnIsUserAnAdmin)(); + typedef BOOL (WINAPI *PFNIsUserAnAdmin)(); + static PFNIsUserAnAdmin pfnIsUserAnAdmin = NULL; + HMODULE shell32; + // This function isn't guaranteed to be available (and it can't hurt + // to leave the library loaded) + if (0 == (shell32=LoadLibrary("shell32.dll"))) + return FALSE; + if (0 == (pfnIsUserAnAdmin=(PFNIsUserAnAdmin)GetProcAddress(shell32, "IsUserAnAdmin"))) + return FALSE; + return (*pfnIsUserAnAdmin)(); } // Some magic for Vista's UAC. If there is a target_version, and @@ -2171,38 +2171,38 @@ // Returns TRUE if we should spawn an elevated child BOOL NeedAutoUAC() { - HKEY hk; - char key_name[80]; - // no Python version info == we can't know yet. - if (target_version[0] == '\0') - return FALSE; - // see how python is current installed - wsprintf(key_name, - "Software\\Python\\PythonCore\\%s\\InstallPath", - target_version); - if (ERROR_SUCCESS != RegOpenKeyEx(HKEY_LOCAL_MACHINE, - key_name, 0, KEY_READ, &hk)) - return FALSE; - RegCloseKey(hk); - // Python is installed in HKLM - we must elevate. - return TRUE; + HKEY hk; + char key_name[80]; + // no Python version info == we can't know yet. + if (target_version[0] == '\0') + return FALSE; + // see how python is current installed + wsprintf(key_name, + "Software\\Python\\PythonCore\\%s\\InstallPath", + target_version); + if (ERROR_SUCCESS != RegOpenKeyEx(HKEY_LOCAL_MACHINE, + key_name, 0, KEY_READ, &hk)) + return FALSE; + RegCloseKey(hk); + // Python is installed in HKLM - we must elevate. + return TRUE; } // Returns TRUE if the platform supports UAC. BOOL PlatformSupportsUAC() { - // Note that win2k does seem to support ShellExecute with 'runas', - // but does *not* support IsUserAnAdmin - so we just pretend things - // only work on XP and later. - BOOL bIsWindowsXPorLater; - OSVERSIONINFO winverinfo; - winverinfo.dwOSVersionInfoSize = sizeof(winverinfo); - if (!GetVersionEx(&winverinfo)) - return FALSE; // something bad has gone wrong - bIsWindowsXPorLater = + // Note that win2k does seem to support ShellExecute with 'runas', + // but does *not* support IsUserAnAdmin - so we just pretend things + // only work on XP and later. + BOOL bIsWindowsXPorLater; + OSVERSIONINFO winverinfo; + winverinfo.dwOSVersionInfoSize = sizeof(winverinfo); + if (!GetVersionEx(&winverinfo)) + return FALSE; // something bad has gone wrong + bIsWindowsXPorLater = ( (winverinfo.dwMajorVersion > 5) || ( (winverinfo.dwMajorVersion == 5) && (winverinfo.dwMinorVersion >= 1) )); - return bIsWindowsXPorLater; + return bIsWindowsXPorLater; } // Spawn ourself as an elevated application. On failure, a message is @@ -2210,97 +2210,97 @@ // on error. void SpawnUAC() { - // interesting failure scenario that has been seen: initial executable - // runs from a network drive - but once elevated, that network share - // isn't seen, and ShellExecute fails with SE_ERR_ACCESSDENIED. - int ret = (int)ShellExecute(0, "runas", modulename, "", NULL, - SW_SHOWNORMAL); - if (ret <= 32) { - char msg[128]; - wsprintf(msg, "Failed to start elevated process (ShellExecute returned %d)", ret); - MessageBox(0, msg, "Setup", MB_OK | MB_ICONERROR); - } + // interesting failure scenario that has been seen: initial executable + // runs from a network drive - but once elevated, that network share + // isn't seen, and ShellExecute fails with SE_ERR_ACCESSDENIED. + int ret = (int)ShellExecute(0, "runas", modulename, "", NULL, + SW_SHOWNORMAL); + if (ret <= 32) { + char msg[128]; + wsprintf(msg, "Failed to start elevated process (ShellExecute returned %d)", ret); + MessageBox(0, msg, "Setup", MB_OK | MB_ICONERROR); + } } int DoInstall(void) { - char ini_buffer[4096]; + char ini_buffer[4096]; - /* Read installation information */ - GetPrivateProfileString("Setup", "title", "", ini_buffer, - sizeof(ini_buffer), ini_file); - unescape(title, ini_buffer, sizeof(title)); - - GetPrivateProfileString("Setup", "info", "", ini_buffer, - sizeof(ini_buffer), ini_file); - unescape(info, ini_buffer, sizeof(info)); - - GetPrivateProfileString("Setup", "build_info", "", build_info, - sizeof(build_info), ini_file); - - pyc_compile = GetPrivateProfileInt("Setup", "target_compile", 1, - ini_file); - pyo_compile = GetPrivateProfileInt("Setup", "target_optimize", 1, - ini_file); - - GetPrivateProfileString("Setup", "target_version", "", - target_version, sizeof(target_version), - ini_file); - - GetPrivateProfileString("metadata", "name", "", - meta_name, sizeof(meta_name), - ini_file); - - GetPrivateProfileString("Setup", "install_script", "", - install_script, sizeof(install_script), - ini_file); - - GetPrivateProfileString("Setup", "user_access_control", "", - user_access_control, sizeof(user_access_control), ini_file); - - // See if we need to do the Vista UAC magic. - if (strcmp(user_access_control, "force")==0) { - if (PlatformSupportsUAC() && !MyIsUserAnAdmin()) { - SpawnUAC(); - return 0; - } - // already admin - keep going - } else if (strcmp(user_access_control, "auto")==0) { - // Check if it looks like we need UAC control, based - // on how Python itself was installed. - if (PlatformSupportsUAC() && !MyIsUserAnAdmin() && NeedAutoUAC()) { - SpawnUAC(); - return 0; - } - } else { - // display a warning about unknown values - only the developer - // of the extension will see it (until they fix it!) - if (user_access_control[0] && strcmp(user_access_control, "none") != 0) { - MessageBox(GetFocus(), "Bad user_access_control value", "oops", MB_OK); - // nothing to do. - } - } - - hwndMain = CreateBackground(title); - - RunWizard(hwndMain); - - /* Clean up */ - UnmapViewOfFile(arc_data); - if (ini_file) - DeleteFile(ini_file); + /* Read installation information */ + GetPrivateProfileString("Setup", "title", "", ini_buffer, + sizeof(ini_buffer), ini_file); + unescape(title, ini_buffer, sizeof(title)); + + GetPrivateProfileString("Setup", "info", "", ini_buffer, + sizeof(ini_buffer), ini_file); + unescape(info, ini_buffer, sizeof(info)); + + GetPrivateProfileString("Setup", "build_info", "", build_info, + sizeof(build_info), ini_file); + + pyc_compile = GetPrivateProfileInt("Setup", "target_compile", 1, + ini_file); + pyo_compile = GetPrivateProfileInt("Setup", "target_optimize", 1, + ini_file); + + GetPrivateProfileString("Setup", "target_version", "", + target_version, sizeof(target_version), + ini_file); + + GetPrivateProfileString("metadata", "name", "", + meta_name, sizeof(meta_name), + ini_file); + + GetPrivateProfileString("Setup", "install_script", "", + install_script, sizeof(install_script), + ini_file); + + GetPrivateProfileString("Setup", "user_access_control", "", + user_access_control, sizeof(user_access_control), ini_file); + + // See if we need to do the Vista UAC magic. + if (strcmp(user_access_control, "force")==0) { + if (PlatformSupportsUAC() && !MyIsUserAnAdmin()) { + SpawnUAC(); + return 0; + } + // already admin - keep going + } else if (strcmp(user_access_control, "auto")==0) { + // Check if it looks like we need UAC control, based + // on how Python itself was installed. + if (PlatformSupportsUAC() && !MyIsUserAnAdmin() && NeedAutoUAC()) { + SpawnUAC(); + return 0; + } + } else { + // display a warning about unknown values - only the developer + // of the extension will see it (until they fix it!) + if (user_access_control[0] && strcmp(user_access_control, "none") != 0) { + MessageBox(GetFocus(), "Bad user_access_control value", "oops", MB_OK); + // nothing to do. + } + } + + hwndMain = CreateBackground(title); + + RunWizard(hwndMain); + + /* Clean up */ + UnmapViewOfFile(arc_data); + if (ini_file) + DeleteFile(ini_file); - if (hBitmap) - DeleteObject(hBitmap); + if (hBitmap) + DeleteObject(hBitmap); - return 0; + return 0; } /*********************** uninstall section ******************************/ static int compare(const void *p1, const void *p2) { - return strcmp(*(char **)p2, *(char **)p1); + return strcmp(*(char **)p2, *(char **)p1); } /* @@ -2314,380 +2314,380 @@ */ void remove_exe(void) { - char exename[_MAX_PATH]; - char batname[_MAX_PATH]; - FILE *fp; - STARTUPINFO si; - PROCESS_INFORMATION pi; - - GetModuleFileName(NULL, exename, sizeof(exename)); - sprintf(batname, "%s.bat", exename); - fp = fopen(batname, "w"); - fprintf(fp, ":Repeat\n"); - fprintf(fp, "del \"%s\"\n", exename); - fprintf(fp, "if exist \"%s\" goto Repeat\n", exename); - fprintf(fp, "del \"%s\"\n", batname); - fclose(fp); - - ZeroMemory(&si, sizeof(si)); - si.cb = sizeof(si); - si.dwFlags = STARTF_USESHOWWINDOW; - si.wShowWindow = SW_HIDE; - if (CreateProcess(NULL, - batname, - NULL, - NULL, - FALSE, - CREATE_SUSPENDED | IDLE_PRIORITY_CLASS, - NULL, - "\\", - &si, - &pi)) { - SetThreadPriority(pi.hThread, THREAD_PRIORITY_IDLE); - SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_TIME_CRITICAL); - SetPriorityClass(GetCurrentProcess(), HIGH_PRIORITY_CLASS); - CloseHandle(pi.hProcess); - ResumeThread(pi.hThread); - CloseHandle(pi.hThread); - } + char exename[_MAX_PATH]; + char batname[_MAX_PATH]; + FILE *fp; + STARTUPINFO si; + PROCESS_INFORMATION pi; + + GetModuleFileName(NULL, exename, sizeof(exename)); + sprintf(batname, "%s.bat", exename); + fp = fopen(batname, "w"); + fprintf(fp, ":Repeat\n"); + fprintf(fp, "del \"%s\"\n", exename); + fprintf(fp, "if exist \"%s\" goto Repeat\n", exename); + fprintf(fp, "del \"%s\"\n", batname); + fclose(fp); + + ZeroMemory(&si, sizeof(si)); + si.cb = sizeof(si); + si.dwFlags = STARTF_USESHOWWINDOW; + si.wShowWindow = SW_HIDE; + if (CreateProcess(NULL, + batname, + NULL, + NULL, + FALSE, + CREATE_SUSPENDED | IDLE_PRIORITY_CLASS, + NULL, + "\\", + &si, + &pi)) { + SetThreadPriority(pi.hThread, THREAD_PRIORITY_IDLE); + SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_TIME_CRITICAL); + SetPriorityClass(GetCurrentProcess(), HIGH_PRIORITY_CLASS); + CloseHandle(pi.hProcess); + ResumeThread(pi.hThread); + CloseHandle(pi.hThread); + } } void DeleteRegistryKey(char *string) { - char *keyname; - char *subkeyname; - char *delim; - HKEY hKey; - long result; - char *line; - - line = strdup(string); /* so we can change it */ - - keyname = strchr(line, '['); - if (!keyname) - return; - ++keyname; - - subkeyname = strchr(keyname, ']'); - if (!subkeyname) - return; - *subkeyname++='\0'; - delim = strchr(subkeyname, '\n'); - if (delim) - *delim = '\0'; - - result = RegOpenKeyEx(hkey_root, - keyname, - 0, - KEY_WRITE, - &hKey); - - if (result != ERROR_SUCCESS) - MessageBox(GetFocus(), string, "Could not open key", MB_OK); - else { - result = RegDeleteKey(hKey, subkeyname); - if (result != ERROR_SUCCESS && result != ERROR_FILE_NOT_FOUND) - MessageBox(GetFocus(), string, "Could not delete key", MB_OK); - RegCloseKey(hKey); - } - free(line); + char *keyname; + char *subkeyname; + char *delim; + HKEY hKey; + long result; + char *line; + + line = strdup(string); /* so we can change it */ + + keyname = strchr(line, '['); + if (!keyname) + return; + ++keyname; + + subkeyname = strchr(keyname, ']'); + if (!subkeyname) + return; + *subkeyname++='\0'; + delim = strchr(subkeyname, '\n'); + if (delim) + *delim = '\0'; + + result = RegOpenKeyEx(hkey_root, + keyname, + 0, + KEY_WRITE, + &hKey); + + if (result != ERROR_SUCCESS) + MessageBox(GetFocus(), string, "Could not open key", MB_OK); + else { + result = RegDeleteKey(hKey, subkeyname); + if (result != ERROR_SUCCESS && result != ERROR_FILE_NOT_FOUND) + MessageBox(GetFocus(), string, "Could not delete key", MB_OK); + RegCloseKey(hKey); + } + free(line); } void DeleteRegistryValue(char *string) { - char *keyname; - char *valuename; - char *value; - HKEY hKey; - long result; - char *line; + char *keyname; + char *valuename; + char *value; + HKEY hKey; + long result; + char *line; - line = strdup(string); /* so we can change it */ + line = strdup(string); /* so we can change it */ /* Format is 'Reg DB Value: [key]name=value' */ - keyname = strchr(line, '['); - if (!keyname) - return; - ++keyname; - valuename = strchr(keyname, ']'); - if (!valuename) - return; - *valuename++ = '\0'; - value = strchr(valuename, '='); - if (!value) - return; - - *value++ = '\0'; - - result = RegOpenKeyEx(hkey_root, - keyname, - 0, - KEY_WRITE, - &hKey); - if (result != ERROR_SUCCESS) - MessageBox(GetFocus(), string, "Could not open key", MB_OK); - else { - result = RegDeleteValue(hKey, valuename); - if (result != ERROR_SUCCESS && result != ERROR_FILE_NOT_FOUND) - MessageBox(GetFocus(), string, "Could not delete value", MB_OK); - RegCloseKey(hKey); - } - free(line); + keyname = strchr(line, '['); + if (!keyname) + return; + ++keyname; + valuename = strchr(keyname, ']'); + if (!valuename) + return; + *valuename++ = '\0'; + value = strchr(valuename, '='); + if (!value) + return; + + *value++ = '\0'; + + result = RegOpenKeyEx(hkey_root, + keyname, + 0, + KEY_WRITE, + &hKey); + if (result != ERROR_SUCCESS) + MessageBox(GetFocus(), string, "Could not open key", MB_OK); + else { + result = RegDeleteValue(hKey, valuename); + if (result != ERROR_SUCCESS && result != ERROR_FILE_NOT_FOUND) + MessageBox(GetFocus(), string, "Could not delete value", MB_OK); + RegCloseKey(hKey); + } + free(line); } BOOL MyDeleteFile(char *line) { - char *pathname = strchr(line, ':'); - if (!pathname) - return FALSE; - ++pathname; - while (isspace(*pathname)) - ++pathname; - return DeleteFile(pathname); + char *pathname = strchr(line, ':'); + if (!pathname) + return FALSE; + ++pathname; + while (isspace(*pathname)) + ++pathname; + return DeleteFile(pathname); } BOOL MyRemoveDirectory(char *line) { - char *pathname = strchr(line, ':'); - if (!pathname) - return FALSE; - ++pathname; - while (isspace(*pathname)) - ++pathname; - return RemoveDirectory(pathname); + char *pathname = strchr(line, ':'); + if (!pathname) + return FALSE; + ++pathname; + while (isspace(*pathname)) + ++pathname; + return RemoveDirectory(pathname); } BOOL Run_RemoveScript(char *line) { - char *dllname; - char *scriptname; - static char lastscript[MAX_PATH]; + char *dllname; + char *scriptname; + static char lastscript[MAX_PATH]; /* Format is 'Run Scripts: [pythondll]scriptname' */ /* XXX Currently, pythondll carries no path!!! */ - dllname = strchr(line, '['); - if (!dllname) - return FALSE; - ++dllname; - scriptname = strchr(dllname, ']'); - if (!scriptname) - return FALSE; - *scriptname++ = '\0'; - /* this function may be called more than one time with the same - script, only run it one time */ - if (strcmp(lastscript, scriptname)) { - char *argv[3] = {NULL, "-remove", NULL}; - char *buffer = NULL; - - argv[0] = scriptname; - - if (0 != run_installscript(scriptname, 2, argv, &buffer)) - fprintf(stderr, "*** Could not run installation script ***"); - - if (buffer && buffer[0]) - MessageBox(GetFocus(), buffer, "uninstall-script", MB_OK); - free(buffer); - - strcpy(lastscript, scriptname); - } - return TRUE; + dllname = strchr(line, '['); + if (!dllname) + return FALSE; + ++dllname; + scriptname = strchr(dllname, ']'); + if (!scriptname) + return FALSE; + *scriptname++ = '\0'; + /* this function may be called more than one time with the same + script, only run it one time */ + if (strcmp(lastscript, scriptname)) { + char *argv[3] = {NULL, "-remove", NULL}; + char *buffer = NULL; + + argv[0] = scriptname; + + if (0 != run_installscript(scriptname, 2, argv, &buffer)) + fprintf(stderr, "*** Could not run installation script ***"); + + if (buffer && buffer[0]) + MessageBox(GetFocus(), buffer, "uninstall-script", MB_OK); + free(buffer); + + strcpy(lastscript, scriptname); + } + return TRUE; } int DoUninstall(int argc, char **argv) { - FILE *logfile; - char buffer[4096]; - int nLines = 0; - int i; - char *cp; - int nFiles = 0; - int nDirs = 0; - int nErrors = 0; - char **lines; - int lines_buffer_size = 10; - - if (argc != 3) { - MessageBox(NULL, - "Wrong number of args", - NULL, - MB_OK); - return 1; /* Error */ - } - if (strcmp(argv[1], "-u")) { - MessageBox(NULL, - "2. arg is not -u", - NULL, - MB_OK); - return 1; /* Error */ - } - - logfile = fopen(argv[2], "r"); - if (!logfile) { - MessageBox(NULL, - "could not open logfile", - NULL, - MB_OK); - return 1; /* Error */ - } - - lines = (char **)malloc(sizeof(char *) * lines_buffer_size); - if (!lines) - return SystemError(0, "Out of memory"); - - /* Read the whole logfile, realloacting the buffer */ - while (fgets(buffer, sizeof(buffer), logfile)) { - int len = strlen(buffer); - /* remove trailing white space */ - while (isspace(buffer[len-1])) - len -= 1; - buffer[len] = '\0'; - lines[nLines++] = strdup(buffer); - if (nLines >= lines_buffer_size) { - lines_buffer_size += 10; - lines = (char **)realloc(lines, - sizeof(char *) * lines_buffer_size); - if (!lines) - return SystemError(0, "Out of memory"); - } - } - fclose(logfile); - - /* Sort all the lines, so that highest 3-digit codes are first */ - qsort(&lines[0], nLines, sizeof(char *), - compare); - - if (IDYES != MessageBox(NULL, - "Are you sure you want to remove\n" - "this package from your computer?", - "Please confirm", - MB_YESNO | MB_ICONQUESTION)) - return 0; - - hkey_root = HKEY_LOCAL_MACHINE; - cp = ""; - for (i = 0; i < nLines; ++i) { - /* Ignore duplicate lines */ - if (strcmp(cp, lines[i])) { - int ign; - cp = lines[i]; - /* Parse the lines */ - if (2 == sscanf(cp, "%d Root Key: %s", &ign, &buffer)) { - if (strcmp(buffer, "HKEY_CURRENT_USER")==0) - hkey_root = HKEY_CURRENT_USER; - else { - // HKLM - check they have permissions. - if (!HasLocalMachinePrivs()) { - MessageBox(GetFocus(), - "You do not seem to have sufficient access rights\n" - "on this machine to uninstall this software", - NULL, - MB_OK | MB_ICONSTOP); - return 1; /* Error */ - } - } - } else if (2 == sscanf(cp, "%d Made Dir: %s", &ign, &buffer)) { - if (MyRemoveDirectory(cp)) - ++nDirs; - else { - int code = GetLastError(); - if (code != 2 && code != 3) { /* file or path not found */ - ++nErrors; - } - } - } else if (2 == sscanf(cp, "%d File Copy: %s", &ign, &buffer)) { - if (MyDeleteFile(cp)) - ++nFiles; - else { - int code = GetLastError(); - if (code != 2 && code != 3) { /* file or path not found */ - ++nErrors; - } - } - } else if (2 == sscanf(cp, "%d File Overwrite: %s", &ign, &buffer)) { - if (MyDeleteFile(cp)) - ++nFiles; - else { - int code = GetLastError(); - if (code != 2 && code != 3) { /* file or path not found */ - ++nErrors; - } - } - } else if (2 == sscanf(cp, "%d Reg DB Key: %s", &ign, &buffer)) { - DeleteRegistryKey(cp); - } else if (2 == sscanf(cp, "%d Reg DB Value: %s", &ign, &buffer)) { - DeleteRegistryValue(cp); - } else if (2 == sscanf(cp, "%d Run Script: %s", &ign, &buffer)) { - Run_RemoveScript(cp); - } - } - } - - if (DeleteFile(argv[2])) { - ++nFiles; - } else { - ++nErrors; - SystemError(GetLastError(), argv[2]); - } - if (nErrors) - wsprintf(buffer, - "%d files and %d directories removed\n" - "%d files or directories could not be removed", - nFiles, nDirs, nErrors); - else - wsprintf(buffer, "%d files and %d directories removed", - nFiles, nDirs); - MessageBox(NULL, buffer, "Uninstall Finished!", - MB_OK | MB_ICONINFORMATION); - remove_exe(); - return 0; + FILE *logfile; + char buffer[4096]; + int nLines = 0; + int i; + char *cp; + int nFiles = 0; + int nDirs = 0; + int nErrors = 0; + char **lines; + int lines_buffer_size = 10; + + if (argc != 3) { + MessageBox(NULL, + "Wrong number of args", + NULL, + MB_OK); + return 1; /* Error */ + } + if (strcmp(argv[1], "-u")) { + MessageBox(NULL, + "2. arg is not -u", + NULL, + MB_OK); + return 1; /* Error */ + } + + logfile = fopen(argv[2], "r"); + if (!logfile) { + MessageBox(NULL, + "could not open logfile", + NULL, + MB_OK); + return 1; /* Error */ + } + + lines = (char **)malloc(sizeof(char *) * lines_buffer_size); + if (!lines) + return SystemError(0, "Out of memory"); + + /* Read the whole logfile, realloacting the buffer */ + while (fgets(buffer, sizeof(buffer), logfile)) { + int len = strlen(buffer); + /* remove trailing white space */ + while (isspace(buffer[len-1])) + len -= 1; + buffer[len] = '\0'; + lines[nLines++] = strdup(buffer); + if (nLines >= lines_buffer_size) { + lines_buffer_size += 10; + lines = (char **)realloc(lines, + sizeof(char *) * lines_buffer_size); + if (!lines) + return SystemError(0, "Out of memory"); + } + } + fclose(logfile); + + /* Sort all the lines, so that highest 3-digit codes are first */ + qsort(&lines[0], nLines, sizeof(char *), + compare); + + if (IDYES != MessageBox(NULL, + "Are you sure you want to remove\n" + "this package from your computer?", + "Please confirm", + MB_YESNO | MB_ICONQUESTION)) + return 0; + + hkey_root = HKEY_LOCAL_MACHINE; + cp = ""; + for (i = 0; i < nLines; ++i) { + /* Ignore duplicate lines */ + if (strcmp(cp, lines[i])) { + int ign; + cp = lines[i]; + /* Parse the lines */ + if (2 == sscanf(cp, "%d Root Key: %s", &ign, &buffer)) { + if (strcmp(buffer, "HKEY_CURRENT_USER")==0) + hkey_root = HKEY_CURRENT_USER; + else { + // HKLM - check they have permissions. + if (!HasLocalMachinePrivs()) { + MessageBox(GetFocus(), + "You do not seem to have sufficient access rights\n" + "on this machine to uninstall this software", + NULL, + MB_OK | MB_ICONSTOP); + return 1; /* Error */ + } + } + } else if (2 == sscanf(cp, "%d Made Dir: %s", &ign, &buffer)) { + if (MyRemoveDirectory(cp)) + ++nDirs; + else { + int code = GetLastError(); + if (code != 2 && code != 3) { /* file or path not found */ + ++nErrors; + } + } + } else if (2 == sscanf(cp, "%d File Copy: %s", &ign, &buffer)) { + if (MyDeleteFile(cp)) + ++nFiles; + else { + int code = GetLastError(); + if (code != 2 && code != 3) { /* file or path not found */ + ++nErrors; + } + } + } else if (2 == sscanf(cp, "%d File Overwrite: %s", &ign, &buffer)) { + if (MyDeleteFile(cp)) + ++nFiles; + else { + int code = GetLastError(); + if (code != 2 && code != 3) { /* file or path not found */ + ++nErrors; + } + } + } else if (2 == sscanf(cp, "%d Reg DB Key: %s", &ign, &buffer)) { + DeleteRegistryKey(cp); + } else if (2 == sscanf(cp, "%d Reg DB Value: %s", &ign, &buffer)) { + DeleteRegistryValue(cp); + } else if (2 == sscanf(cp, "%d Run Script: %s", &ign, &buffer)) { + Run_RemoveScript(cp); + } + } + } + + if (DeleteFile(argv[2])) { + ++nFiles; + } else { + ++nErrors; + SystemError(GetLastError(), argv[2]); + } + if (nErrors) + wsprintf(buffer, + "%d files and %d directories removed\n" + "%d files or directories could not be removed", + nFiles, nDirs, nErrors); + else + wsprintf(buffer, "%d files and %d directories removed", + nFiles, nDirs); + MessageBox(NULL, buffer, "Uninstall Finished!", + MB_OK | MB_ICONINFORMATION); + remove_exe(); + return 0; } int WINAPI WinMain(HINSTANCE hInst, HINSTANCE hPrevInst, - LPSTR lpszCmdLine, INT nCmdShow) + LPSTR lpszCmdLine, INT nCmdShow) { - extern int __argc; - extern char **__argv; - char *basename; - - GetModuleFileName(NULL, modulename, sizeof(modulename)); - GetModuleFileNameW(NULL, wmodulename, sizeof(wmodulename)/sizeof(wmodulename[0])); - - /* Map the executable file to memory */ - arc_data = MapExistingFile(modulename, &arc_size); - if (!arc_data) { - SystemError(GetLastError(), "Could not open archive"); - return 1; - } - - /* OK. So this program can act as installer (self-extracting - * zip-file, or as uninstaller when started with '-u logfile' - * command line flags. - * - * The installer is usually started without command line flags, - * and the uninstaller is usually started with the '-u logfile' - * flag. What to do if some innocent user double-clicks the - * exe-file? - * The following implements a defensive strategy... - */ - - /* Try to extract the configuration data into a temporary file */ - if (ExtractInstallData(arc_data, arc_size, &exe_size, - &ini_file, &pre_install_script)) - return DoInstall(); - - if (!ini_file && __argc > 1) { - return DoUninstall(__argc, __argv); - } - - - basename = strrchr(modulename, '\\'); - if (basename) - ++basename; - - /* Last guess about the purpose of this program */ - if (basename && (0 == strncmp(basename, "Remove", 6))) - SystemError(0, "This program is normally started by windows"); - else - SystemError(0, "Setup program invalid or damaged"); - return 1; + extern int __argc; + extern char **__argv; + char *basename; + + GetModuleFileName(NULL, modulename, sizeof(modulename)); + GetModuleFileNameW(NULL, wmodulename, sizeof(wmodulename)/sizeof(wmodulename[0])); + + /* Map the executable file to memory */ + arc_data = MapExistingFile(modulename, &arc_size); + if (!arc_data) { + SystemError(GetLastError(), "Could not open archive"); + return 1; + } + + /* OK. So this program can act as installer (self-extracting + * zip-file, or as uninstaller when started with '-u logfile' + * command line flags. + * + * The installer is usually started without command line flags, + * and the uninstaller is usually started with the '-u logfile' + * flag. What to do if some innocent user double-clicks the + * exe-file? + * The following implements a defensive strategy... + */ + + /* Try to extract the configuration data into a temporary file */ + if (ExtractInstallData(arc_data, arc_size, &exe_size, + &ini_file, &pre_install_script)) + return DoInstall(); + + if (!ini_file && __argc > 1) { + return DoUninstall(__argc, __argv); + } + + + basename = strrchr(modulename, '\\'); + if (basename) + ++basename; + + /* Last guess about the purpose of this program */ + if (basename && (0 == strncmp(basename, "Remove", 6))) + SystemError(0, "This program is normally started by windows"); + else + SystemError(0, "Setup program invalid or damaged"); + return 1; } Modified: python/branches/py3k-jit/PC/config.c ============================================================================== --- python/branches/py3k-jit/PC/config.c (original) +++ python/branches/py3k-jit/PC/config.c Mon May 10 23:55:43 2010 @@ -71,87 +71,87 @@ struct _inittab _PyImport_Inittab[] = { - {"array", PyInit_array}, - {"_ast", PyInit__ast}, + {"array", PyInit_array}, + {"_ast", PyInit__ast}, #ifdef MS_WINDOWS #ifndef MS_WINI64 - {"audioop", PyInit_audioop}, + {"audioop", PyInit_audioop}, #endif #endif - {"binascii", PyInit_binascii}, - {"cmath", PyInit_cmath}, - {"errno", PyInit_errno}, - {"gc", PyInit_gc}, - {"math", PyInit_math}, - {"nt", PyInit_nt}, /* Use the NT os functions, not posix */ - {"operator", PyInit_operator}, - {"signal", PyInit_signal}, - {"_md5", PyInit__md5}, - {"_sha1", PyInit__sha1}, - {"_sha256", PyInit__sha256}, - {"_sha512", PyInit__sha512}, - {"time", PyInit_time}, + {"binascii", PyInit_binascii}, + {"cmath", PyInit_cmath}, + {"errno", PyInit_errno}, + {"gc", PyInit_gc}, + {"math", PyInit_math}, + {"nt", PyInit_nt}, /* Use the NT os functions, not posix */ + {"operator", PyInit_operator}, + {"signal", PyInit_signal}, + {"_md5", PyInit__md5}, + {"_sha1", PyInit__sha1}, + {"_sha256", PyInit__sha256}, + {"_sha512", PyInit__sha512}, + {"time", PyInit_time}, #ifdef WITH_THREAD - {"_thread", PyInit__thread}, + {"_thread", PyInit__thread}, #endif #ifdef WIN32 - {"msvcrt", PyInit_msvcrt}, - {"_locale", PyInit__locale}, + {"msvcrt", PyInit_msvcrt}, + {"_locale", PyInit__locale}, #endif - /* XXX Should _subprocess go in a WIN32 block? not WIN64? */ - {"_subprocess", PyInit__subprocess}, + /* XXX Should _subprocess go in a WIN32 block? not WIN64? */ + {"_subprocess", PyInit__subprocess}, - {"_codecs", PyInit__codecs}, - {"_weakref", PyInit__weakref}, - {"_random", PyInit__random}, - {"_bisect", PyInit__bisect}, - {"_heapq", PyInit__heapq}, - {"_lsprof", PyInit__lsprof}, - {"itertools", PyInit_itertools}, - {"_collections", PyInit__collections}, - {"_symtable", PyInit__symtable}, - {"mmap", PyInit_mmap}, - {"_csv", PyInit__csv}, - {"_sre", PyInit__sre}, - {"parser", PyInit_parser}, - {"winreg", PyInit_winreg}, - {"_struct", PyInit__struct}, - {"datetime", PyInit_datetime}, - {"_functools", PyInit__functools}, - {"_json", PyInit__json}, - - {"xxsubtype", PyInit_xxsubtype}, - {"zipimport", PyInit_zipimport}, - {"zlib", PyInit_zlib}, - - /* CJK codecs */ - {"_multibytecodec", PyInit__multibytecodec}, - {"_codecs_cn", PyInit__codecs_cn}, - {"_codecs_hk", PyInit__codecs_hk}, - {"_codecs_iso2022", PyInit__codecs_iso2022}, - {"_codecs_jp", PyInit__codecs_jp}, - {"_codecs_kr", PyInit__codecs_kr}, - {"_codecs_tw", PyInit__codecs_tw}, + {"_codecs", PyInit__codecs}, + {"_weakref", PyInit__weakref}, + {"_random", PyInit__random}, + {"_bisect", PyInit__bisect}, + {"_heapq", PyInit__heapq}, + {"_lsprof", PyInit__lsprof}, + {"itertools", PyInit_itertools}, + {"_collections", PyInit__collections}, + {"_symtable", PyInit__symtable}, + {"mmap", PyInit_mmap}, + {"_csv", PyInit__csv}, + {"_sre", PyInit__sre}, + {"parser", PyInit_parser}, + {"winreg", PyInit_winreg}, + {"_struct", PyInit__struct}, + {"datetime", PyInit_datetime}, + {"_functools", PyInit__functools}, + {"_json", PyInit__json}, + + {"xxsubtype", PyInit_xxsubtype}, + {"zipimport", PyInit_zipimport}, + {"zlib", PyInit_zlib}, + + /* CJK codecs */ + {"_multibytecodec", PyInit__multibytecodec}, + {"_codecs_cn", PyInit__codecs_cn}, + {"_codecs_hk", PyInit__codecs_hk}, + {"_codecs_iso2022", PyInit__codecs_iso2022}, + {"_codecs_jp", PyInit__codecs_jp}, + {"_codecs_kr", PyInit__codecs_kr}, + {"_codecs_tw", PyInit__codecs_tw}, /* tools/freeze/makeconfig.py marker for additional "_inittab" entries */ /* -- ADDMODULE MARKER 2 -- */ - /* This module "lives in" with marshal.c */ - {"marshal", PyMarshal_Init}, + /* This module "lives in" with marshal.c */ + {"marshal", PyMarshal_Init}, - /* This lives it with import.c */ - {"imp", PyInit_imp}, + /* This lives it with import.c */ + {"imp", PyInit_imp}, - /* These entries are here for sys.builtin_module_names */ - {"__main__", NULL}, - {"builtins", NULL}, - {"sys", NULL}, - {"_warnings", _PyWarnings_Init}, - - {"_io", PyInit__io}, - {"_pickle", PyInit__pickle}, - {"atexit", PyInit_atexit}, + /* These entries are here for sys.builtin_module_names */ + {"__main__", NULL}, + {"builtins", NULL}, + {"sys", NULL}, + {"_warnings", _PyWarnings_Init}, + + {"_io", PyInit__io}, + {"_pickle", PyInit__pickle}, + {"atexit", PyInit_atexit}, - /* Sentinel */ - {0, 0} + /* Sentinel */ + {0, 0} }; Modified: python/branches/py3k-jit/PC/dl_nt.c ============================================================================== --- python/branches/py3k-jit/PC/dl_nt.c (original) +++ python/branches/py3k-jit/PC/dl_nt.c Mon May 10 23:55:43 2010 @@ -3,7 +3,7 @@ Entry point for the Windows NT DLL. About the only reason for having this, is so initall() can automatically -be called, removing that burden (and possible source of frustration if +be called, removing that burden (and possible source of frustration if forgotten) from the programmer. */ @@ -46,61 +46,61 @@ void _LoadActCtxPointers() { - HINSTANCE hKernel32 = GetModuleHandleW(L"kernel32.dll"); - if (hKernel32) - pfnGetCurrentActCtx = (PFN_GETCURRENTACTCTX) GetProcAddress(hKernel32, "GetCurrentActCtx"); - // If we can't load GetCurrentActCtx (ie, pre XP) , don't bother with the rest. - if (pfnGetCurrentActCtx) { - pfnActivateActCtx = (PFN_ACTIVATEACTCTX) GetProcAddress(hKernel32, "ActivateActCtx"); - pfnDeactivateActCtx = (PFN_DEACTIVATEACTCTX) GetProcAddress(hKernel32, "DeactivateActCtx"); - pfnAddRefActCtx = (PFN_ADDREFACTCTX) GetProcAddress(hKernel32, "AddRefActCtx"); - pfnReleaseActCtx = (PFN_RELEASEACTCTX) GetProcAddress(hKernel32, "ReleaseActCtx"); - } + HINSTANCE hKernel32 = GetModuleHandleW(L"kernel32.dll"); + if (hKernel32) + pfnGetCurrentActCtx = (PFN_GETCURRENTACTCTX) GetProcAddress(hKernel32, "GetCurrentActCtx"); + // If we can't load GetCurrentActCtx (ie, pre XP) , don't bother with the rest. + if (pfnGetCurrentActCtx) { + pfnActivateActCtx = (PFN_ACTIVATEACTCTX) GetProcAddress(hKernel32, "ActivateActCtx"); + pfnDeactivateActCtx = (PFN_DEACTIVATEACTCTX) GetProcAddress(hKernel32, "DeactivateActCtx"); + pfnAddRefActCtx = (PFN_ADDREFACTCTX) GetProcAddress(hKernel32, "AddRefActCtx"); + pfnReleaseActCtx = (PFN_RELEASEACTCTX) GetProcAddress(hKernel32, "ReleaseActCtx"); + } } ULONG_PTR _Py_ActivateActCtx() { - ULONG_PTR ret = 0; - if (PyWin_DLLhActivationContext && pfnActivateActCtx) - if (!(*pfnActivateActCtx)(PyWin_DLLhActivationContext, &ret)) { - OutputDebugString("Python failed to activate the activation context before loading a DLL\n"); - ret = 0; // no promise the failing function didn't change it! - } - return ret; + ULONG_PTR ret = 0; + if (PyWin_DLLhActivationContext && pfnActivateActCtx) + if (!(*pfnActivateActCtx)(PyWin_DLLhActivationContext, &ret)) { + OutputDebugString("Python failed to activate the activation context before loading a DLL\n"); + ret = 0; // no promise the failing function didn't change it! + } + return ret; } void _Py_DeactivateActCtx(ULONG_PTR cookie) { - if (cookie && pfnDeactivateActCtx) - if (!(*pfnDeactivateActCtx)(0, cookie)) - OutputDebugString("Python failed to de-activate the activation context\n"); + if (cookie && pfnDeactivateActCtx) + if (!(*pfnDeactivateActCtx)(0, cookie)) + OutputDebugString("Python failed to de-activate the activation context\n"); } -BOOL WINAPI DllMain (HANDLE hInst, - ULONG ul_reason_for_call, - LPVOID lpReserved) +BOOL WINAPI DllMain (HANDLE hInst, + ULONG ul_reason_for_call, + LPVOID lpReserved) { - switch (ul_reason_for_call) - { - case DLL_PROCESS_ATTACH: - PyWin_DLLhModule = hInst; - // 1000 is a magic number I picked out of the air. Could do with a #define, I spose... - LoadString(hInst, 1000, dllVersionBuffer, sizeof(dllVersionBuffer)); - - // and capture our activation context for use when loading extensions. - _LoadActCtxPointers(); - if (pfnGetCurrentActCtx && pfnAddRefActCtx) - if ((*pfnGetCurrentActCtx)(&PyWin_DLLhActivationContext)) - if (!(*pfnAddRefActCtx)(PyWin_DLLhActivationContext)) - OutputDebugString("Python failed to load the default activation context\n"); - break; - - case DLL_PROCESS_DETACH: - if (pfnReleaseActCtx) - (*pfnReleaseActCtx)(PyWin_DLLhActivationContext); - break; - } - return TRUE; + switch (ul_reason_for_call) + { + case DLL_PROCESS_ATTACH: + PyWin_DLLhModule = hInst; + // 1000 is a magic number I picked out of the air. Could do with a #define, I spose... + LoadString(hInst, 1000, dllVersionBuffer, sizeof(dllVersionBuffer)); + + // and capture our activation context for use when loading extensions. + _LoadActCtxPointers(); + if (pfnGetCurrentActCtx && pfnAddRefActCtx) + if ((*pfnGetCurrentActCtx)(&PyWin_DLLhActivationContext)) + if (!(*pfnAddRefActCtx)(PyWin_DLLhActivationContext)) + OutputDebugString("Python failed to load the default activation context\n"); + break; + + case DLL_PROCESS_DETACH: + if (pfnReleaseActCtx) + (*pfnReleaseActCtx)(PyWin_DLLhActivationContext); + break; + } + return TRUE; } #endif /* Py_ENABLE_SHARED */ Modified: python/branches/py3k-jit/PC/errmap.h ============================================================================== --- python/branches/py3k-jit/PC/errmap.h (original) +++ python/branches/py3k-jit/PC/errmap.h Mon May 10 23:55:43 2010 @@ -1,78 +1,78 @@ /* Generated file. Do not edit. */ int winerror_to_errno(int winerror) { - switch(winerror) { - case 2: return 2; - case 3: return 2; - case 4: return 24; - case 5: return 13; - case 6: return 9; - case 7: return 12; - case 8: return 12; - case 9: return 12; - case 10: return 7; - case 11: return 8; - case 15: return 2; - case 16: return 13; - case 17: return 18; - case 18: return 2; - case 19: return 13; - case 20: return 13; - case 21: return 13; - case 22: return 13; - case 23: return 13; - case 24: return 13; - case 25: return 13; - case 26: return 13; - case 27: return 13; - case 28: return 13; - case 29: return 13; - case 30: return 13; - case 31: return 13; - case 32: return 13; - case 33: return 13; - case 34: return 13; - case 35: return 13; - case 36: return 13; - case 53: return 2; - case 65: return 13; - case 67: return 2; - case 80: return 17; - case 82: return 13; - case 83: return 13; - case 89: return 11; - case 108: return 13; - case 109: return 32; - case 112: return 28; - case 114: return 9; - case 128: return 10; - case 129: return 10; - case 130: return 9; - case 132: return 13; - case 145: return 41; - case 158: return 13; - case 161: return 2; - case 164: return 11; - case 167: return 13; - case 183: return 17; - case 188: return 8; - case 189: return 8; - case 190: return 8; - case 191: return 8; - case 192: return 8; - case 193: return 8; - case 194: return 8; - case 195: return 8; - case 196: return 8; - case 197: return 8; - case 198: return 8; - case 199: return 8; - case 200: return 8; - case 201: return 8; - case 202: return 8; - case 206: return 2; - case 215: return 11; - case 1816: return 12; - default: return EINVAL; - } + switch(winerror) { + case 2: return 2; + case 3: return 2; + case 4: return 24; + case 5: return 13; + case 6: return 9; + case 7: return 12; + case 8: return 12; + case 9: return 12; + case 10: return 7; + case 11: return 8; + case 15: return 2; + case 16: return 13; + case 17: return 18; + case 18: return 2; + case 19: return 13; + case 20: return 13; + case 21: return 13; + case 22: return 13; + case 23: return 13; + case 24: return 13; + case 25: return 13; + case 26: return 13; + case 27: return 13; + case 28: return 13; + case 29: return 13; + case 30: return 13; + case 31: return 13; + case 32: return 13; + case 33: return 13; + case 34: return 13; + case 35: return 13; + case 36: return 13; + case 53: return 2; + case 65: return 13; + case 67: return 2; + case 80: return 17; + case 82: return 13; + case 83: return 13; + case 89: return 11; + case 108: return 13; + case 109: return 32; + case 112: return 28; + case 114: return 9; + case 128: return 10; + case 129: return 10; + case 130: return 9; + case 132: return 13; + case 145: return 41; + case 158: return 13; + case 161: return 2; + case 164: return 11; + case 167: return 13; + case 183: return 17; + case 188: return 8; + case 189: return 8; + case 190: return 8; + case 191: return 8; + case 192: return 8; + case 193: return 8; + case 194: return 8; + case 195: return 8; + case 196: return 8; + case 197: return 8; + case 198: return 8; + case 199: return 8; + case 200: return 8; + case 201: return 8; + case 202: return 8; + case 206: return 2; + case 215: return 11; + case 1816: return 12; + default: return EINVAL; + } } Modified: python/branches/py3k-jit/PC/example_nt/example.c ============================================================================== --- python/branches/py3k-jit/PC/example_nt/example.c (original) +++ python/branches/py3k-jit/PC/example_nt/example.c Mon May 10 23:55:43 2010 @@ -3,30 +3,30 @@ static PyObject * ex_foo(PyObject *self, PyObject *args) { - printf("Hello, world\n"); - Py_INCREF(Py_None); - return Py_None; + printf("Hello, world\n"); + Py_INCREF(Py_None); + return Py_None; } static PyMethodDef example_methods[] = { - {"foo", ex_foo, METH_VARARGS, "foo() doc string"}, - {NULL, NULL} + {"foo", ex_foo, METH_VARARGS, "foo() doc string"}, + {NULL, NULL} }; static struct PyModuleDef examplemodule = { - PyModuleDef_HEAD_INIT, - "example", - "example module doc string", - -1, - example_methods, - NULL, - NULL, - NULL, - NULL + PyModuleDef_HEAD_INIT, + "example", + "example module doc string", + -1, + example_methods, + NULL, + NULL, + NULL, + NULL }; PyMODINIT_FUNC PyInit_example(void) { - return PyModule_Create(&examplemodule); + return PyModule_Create(&examplemodule); } Modified: python/branches/py3k-jit/PC/frozen_dllmain.c ============================================================================== --- python/branches/py3k-jit/PC/frozen_dllmain.c (original) +++ python/branches/py3k-jit/PC/frozen_dllmain.c Mon May 10 23:55:43 2010 @@ -9,7 +9,7 @@ The solution is: * Each module checks for a frozen build, and if so, defines its DLLMain - function as "__declspec(dllexport) DllMain%module%" + function as "__declspec(dllexport) DllMain%module%" (eg, DllMainpythoncom, or DllMainpywintypes) * The frozen .EXE/.DLL links against this module, which provides @@ -47,10 +47,10 @@ #include "windows.h" static char *possibleModules[] = { - "pywintypes", - "pythoncom", - "win32ui", - NULL, + "pywintypes", + "pythoncom", + "win32ui", + NULL, }; BOOL CallModuleDllMain(char *modName, DWORD dwReason); @@ -62,73 +62,73 @@ */ void PyWinFreeze_ExeInit(void) { - char **modName; - for (modName = possibleModules;*modName;*modName++) { -/* printf("Initialising '%s'\n", *modName); */ - CallModuleDllMain(*modName, DLL_PROCESS_ATTACH); - } + char **modName; + for (modName = possibleModules;*modName;*modName++) { +/* printf("Initialising '%s'\n", *modName); */ + CallModuleDllMain(*modName, DLL_PROCESS_ATTACH); + } } /* Called by a frozen .EXE only, so that built-in extension - modules are cleaned up + modules are cleaned up */ void PyWinFreeze_ExeTerm(void) { - // Must go backwards - char **modName; - for (modName = possibleModules+(sizeof(possibleModules) / sizeof(char *))-2; - modName >= possibleModules; - *modName--) { -/* printf("Terminating '%s'\n", *modName);*/ - CallModuleDllMain(*modName, DLL_PROCESS_DETACH); - } + // Must go backwards + char **modName; + for (modName = possibleModules+(sizeof(possibleModules) / sizeof(char *))-2; + modName >= possibleModules; + *modName--) { +/* printf("Terminating '%s'\n", *modName);*/ + CallModuleDllMain(*modName, DLL_PROCESS_DETACH); + } } BOOL WINAPI DllMain(HINSTANCE hInstance, DWORD dwReason, LPVOID lpReserved) { - BOOL ret = TRUE; - switch (dwReason) { - case DLL_PROCESS_ATTACH: - { - char **modName; - for (modName = possibleModules;*modName;*modName++) { - BOOL ok = CallModuleDllMain(*modName, dwReason); - if (!ok) - ret = FALSE; - } - break; - } - case DLL_PROCESS_DETACH: - { - // Must go backwards - char **modName; - for (modName = possibleModules+(sizeof(possibleModules) / sizeof(char *))-2; - modName >= possibleModules; - *modName--) - CallModuleDllMain(*modName, DLL_PROCESS_DETACH); - break; - } - } - return ret; + BOOL ret = TRUE; + switch (dwReason) { + case DLL_PROCESS_ATTACH: + { + char **modName; + for (modName = possibleModules;*modName;*modName++) { + BOOL ok = CallModuleDllMain(*modName, dwReason); + if (!ok) + ret = FALSE; + } + break; + } + case DLL_PROCESS_DETACH: + { + // Must go backwards + char **modName; + for (modName = possibleModules+(sizeof(possibleModules) / sizeof(char *))-2; + modName >= possibleModules; + *modName--) + CallModuleDllMain(*modName, DLL_PROCESS_DETACH); + break; + } + } + return ret; } BOOL CallModuleDllMain(char *modName, DWORD dwReason) { - BOOL (WINAPI * pfndllmain)(HINSTANCE, DWORD, LPVOID); + BOOL (WINAPI * pfndllmain)(HINSTANCE, DWORD, LPVOID); - char funcName[255]; - HMODULE hmod = GetModuleHandle(NULL); - strcpy(funcName, "_DllMain"); - strcat(funcName, modName); - strcat(funcName, "@12"); // stdcall convention. - pfndllmain = (BOOL (WINAPI *)(HINSTANCE, DWORD, LPVOID))GetProcAddress(hmod, funcName); - if (pfndllmain==NULL) { - /* No function by that name exported - then that module does - not appear in our frozen program - return OK - */ - return TRUE; - } - return (*pfndllmain)(hmod, dwReason, NULL); + char funcName[255]; + HMODULE hmod = GetModuleHandle(NULL); + strcpy(funcName, "_DllMain"); + strcat(funcName, modName); + strcat(funcName, "@12"); // stdcall convention. + pfndllmain = (BOOL (WINAPI *)(HINSTANCE, DWORD, LPVOID))GetProcAddress(hmod, funcName); + if (pfndllmain==NULL) { + /* No function by that name exported - then that module does + not appear in our frozen program - return OK + */ + return TRUE; + } + return (*pfndllmain)(hmod, dwReason, NULL); } Modified: python/branches/py3k-jit/PC/generrmap.c ============================================================================== --- python/branches/py3k-jit/PC/generrmap.c (original) +++ python/branches/py3k-jit/PC/generrmap.c Mon May 10 23:55:43 2010 @@ -5,16 +5,16 @@ int main() { - int i; - printf("/* Generated file. Do not edit. */\n"); - printf("int winerror_to_errno(int winerror)\n"); - printf("{\n\tswitch(winerror) {\n"); - for(i=1; i < 65000; i++) { - _dosmaperr(i); - if (errno == EINVAL) - continue; - printf("\t\tcase %d: return %d;\n", i, errno); - } - printf("\t\tdefault: return EINVAL;\n"); - printf("\t}\n}\n"); + int i; + printf("/* Generated file. Do not edit. */\n"); + printf("int winerror_to_errno(int winerror)\n"); + printf("{\n\tswitch(winerror) {\n"); + for(i=1; i < 65000; i++) { + _dosmaperr(i); + if (errno == EINVAL) + continue; + printf("\t\tcase %d: return %d;\n", i, errno); + } + printf("\t\tdefault: return EINVAL;\n"); + printf("\t}\n}\n"); } Modified: python/branches/py3k-jit/PC/getpathp.c ============================================================================== --- python/branches/py3k-jit/PC/getpathp.c (original) +++ python/branches/py3k-jit/PC/getpathp.c Mon May 10 23:55:43 2010 @@ -4,8 +4,8 @@ /* ---------------------------------------------------------------- PATH RULES FOR WINDOWS: - This describes how sys.path is formed on Windows. It describes the - functionality, not the implementation (ie, the order in which these + This describes how sys.path is formed on Windows. It describes the + functionality, not the implementation (ie, the order in which these are actually fetched is different) * Python always adds an empty entry at the start, which corresponds @@ -24,15 +24,15 @@ * We attempt to locate the "Python Home" - if the PYTHONHOME env var is set, we believe it. Otherwise, we use the path of our host .EXE's to try and locate our "landmark" (lib\\os.py) and deduce our home. - - If we DO have a Python Home: The relevant sub-directories (Lib, + - If we DO have a Python Home: The relevant sub-directories (Lib, plat-win, etc) are based on the Python Home - If we DO NOT have a Python Home, the core Python Path is - loaded from the registry. This is the main PythonPath key, + loaded from the registry. This is the main PythonPath key, and both HKLM and HKCU are combined to form the path) * Iff - we can not locate the Python Home, have not had a PYTHONPATH specified, and can't locate any Registry entries (ie, we have _nothing_ - we can assume is a good path), a default path with relative entries is + we can assume is a good path), a default path with relative entries is used (eg. .\Lib;.\plat-win, etc) @@ -42,9 +42,9 @@ the core path is deduced, and the core paths in the registry are ignored. Other "application paths" in the registry are always read. - * When Python is hosted in another exe (different directory, embedded via + * When Python is hosted in another exe (different directory, embedded via COM, etc), the Python Home will not be deduced, so the core path from - the registry is used. Other "application paths" in the registry are + the registry is used. Other "application paths" in the registry are always read. * If Python can't find its home and there is no registry (eg, frozen @@ -92,12 +92,12 @@ static int -is_sep(wchar_t ch) /* determine if "ch" is a separator character */ +is_sep(wchar_t ch) /* determine if "ch" is a separator character */ { #ifdef ALTSEP - return ch == SEP || ch == ALTSEP; + return ch == SEP || ch == ALTSEP; #else - return ch == SEP; + return ch == SEP; #endif } @@ -107,35 +107,35 @@ static void reduce(wchar_t *dir) { - size_t i = wcslen(dir); - while (i > 0 && !is_sep(dir[i])) - --i; - dir[i] = '\0'; + size_t i = wcslen(dir); + while (i > 0 && !is_sep(dir[i])) + --i; + dir[i] = '\0'; } - + static int exists(wchar_t *filename) { - return GetFileAttributesW(filename) != 0xFFFFFFFF; + return GetFileAttributesW(filename) != 0xFFFFFFFF; } -/* Assumes 'filename' MAXPATHLEN+1 bytes long - +/* Assumes 'filename' MAXPATHLEN+1 bytes long - may extend 'filename' by one character. */ static int -ismodule(wchar_t *filename) /* Is module -- check for .pyc/.pyo too */ +ismodule(wchar_t *filename) /* Is module -- check for .pyc/.pyo too */ { - if (exists(filename)) - return 1; + if (exists(filename)) + return 1; - /* Check for the compiled version of prefix. */ - if (wcslen(filename) < MAXPATHLEN) { - wcscat(filename, Py_OptimizeFlag ? L"o" : L"c"); - if (exists(filename)) - return 1; - } - return 0; + /* Check for the compiled version of prefix. */ + if (wcslen(filename) < MAXPATHLEN) { + wcscat(filename, Py_OptimizeFlag ? L"o" : L"c"); + if (exists(filename)) + return 1; + } + return 0; } /* Add a path component, by appending stuff to buffer. @@ -150,21 +150,21 @@ static void join(wchar_t *buffer, wchar_t *stuff) { - size_t n, k; - if (is_sep(stuff[0])) - n = 0; - else { - n = wcslen(buffer); - if (n > 0 && !is_sep(buffer[n-1]) && n < MAXPATHLEN) - buffer[n++] = SEP; - } - if (n > MAXPATHLEN) - Py_FatalError("buffer overflow in getpathp.c's joinpath()"); - k = wcslen(stuff); - if (n + k > MAXPATHLEN) - k = MAXPATHLEN - n; - wcsncpy(buffer+n, stuff, k); - buffer[n+k] = '\0'; + size_t n, k; + if (is_sep(stuff[0])) + n = 0; + else { + n = wcslen(buffer); + if (n > 0 && !is_sep(buffer[n-1]) && n < MAXPATHLEN) + buffer[n++] = SEP; + } + if (n > MAXPATHLEN) + Py_FatalError("buffer overflow in getpathp.c's joinpath()"); + k = wcslen(stuff); + if (n + k > MAXPATHLEN) + k = MAXPATHLEN - n; + wcsncpy(buffer+n, stuff, k); + buffer[n+k] = '\0'; } /* gotlandmark only called by search_for_prefix, which ensures @@ -174,29 +174,29 @@ static int gotlandmark(wchar_t *landmark) { - int ok; - Py_ssize_t n; + int ok; + Py_ssize_t n; - n = wcslen(prefix); - join(prefix, landmark); - ok = ismodule(prefix); - prefix[n] = '\0'; - return ok; + n = wcslen(prefix); + join(prefix, landmark); + ok = ismodule(prefix); + prefix[n] = '\0'; + return ok; } -/* assumes argv0_path is MAXPATHLEN+1 bytes long, already \0 term'd. +/* assumes argv0_path is MAXPATHLEN+1 bytes long, already \0 term'd. assumption provided by only caller, calculate_path() */ static int search_for_prefix(wchar_t *argv0_path, wchar_t *landmark) { - /* Search from argv0_path, until landmark is found */ - wcscpy(prefix, argv0_path); - do { - if (gotlandmark(landmark)) - return 1; - reduce(prefix); - } while (prefix[0]); - return 0; + /* Search from argv0_path, until landmark is found */ + wcscpy(prefix, argv0_path); + do { + if (gotlandmark(landmark)) + return 1; + reduce(prefix); + } while (prefix[0]); + return 0; } #ifdef MS_WINDOWS @@ -222,133 +222,133 @@ static wchar_t * getpythonregpath(HKEY keyBase, int skipcore) { - HKEY newKey = 0; - DWORD dataSize = 0; - DWORD numKeys = 0; - LONG rc; - wchar_t *retval = NULL; - WCHAR *dataBuf = NULL; - static const WCHAR keyPrefix[] = L"Software\\Python\\PythonCore\\"; - static const WCHAR keySuffix[] = L"\\PythonPath"; - size_t versionLen; - DWORD index; - WCHAR *keyBuf = NULL; - WCHAR *keyBufPtr; - WCHAR **ppPaths = NULL; - - /* Tried to use sysget("winver") but here is too early :-( */ - versionLen = strlen(PyWin_DLLVersionString); - /* Space for all the chars, plus one \0 */ - keyBuf = keyBufPtr = malloc(sizeof(keyPrefix) + - sizeof(WCHAR)*(versionLen-1) + - sizeof(keySuffix)); - if (keyBuf==NULL) goto done; - - memcpy(keyBufPtr, keyPrefix, sizeof(keyPrefix)-sizeof(WCHAR)); - keyBufPtr += sizeof(keyPrefix)/sizeof(WCHAR) - 1; - mbstowcs(keyBufPtr, PyWin_DLLVersionString, versionLen); - keyBufPtr += versionLen; - /* NULL comes with this one! */ - memcpy(keyBufPtr, keySuffix, sizeof(keySuffix)); - /* Open the root Python key */ - rc=RegOpenKeyExW(keyBase, - keyBuf, /* subkey */ - 0, /* reserved */ - KEY_READ, - &newKey); - if (rc!=ERROR_SUCCESS) goto done; - /* Find out how big our core buffer is, and how many subkeys we have */ - rc = RegQueryInfoKey(newKey, NULL, NULL, NULL, &numKeys, NULL, NULL, - NULL, NULL, &dataSize, NULL, NULL); - if (rc!=ERROR_SUCCESS) goto done; - if (skipcore) dataSize = 0; /* Only count core ones if we want them! */ - /* Allocate a temp array of char buffers, so we only need to loop - reading the registry once - */ - ppPaths = malloc( sizeof(WCHAR *) * numKeys ); - if (ppPaths==NULL) goto done; - memset(ppPaths, 0, sizeof(WCHAR *) * numKeys); - /* Loop over all subkeys, allocating a temp sub-buffer. */ - for(index=0;index 0) { - *(szCur++) = L';'; - dataSize--; - } - if (ppPaths[index]) { - Py_ssize_t len = wcslen(ppPaths[index]); - wcsncpy(szCur, ppPaths[index], len); - szCur += len; - assert(dataSize > (DWORD)len); - dataSize -= (DWORD)len; - } - } - if (skipcore) - *szCur = '\0'; - else { - /* If we have no values, we dont need a ';' */ - if (numKeys) { - *(szCur++) = L';'; - dataSize--; - } - /* Now append the core path entries - - this will include the NULL - */ - rc = RegQueryValueExW(newKey, NULL, 0, NULL, - (LPBYTE)szCur, &dataSize); - } - /* And set the result - caller must free */ - retval = dataBuf; - } + HKEY newKey = 0; + DWORD dataSize = 0; + DWORD numKeys = 0; + LONG rc; + wchar_t *retval = NULL; + WCHAR *dataBuf = NULL; + static const WCHAR keyPrefix[] = L"Software\\Python\\PythonCore\\"; + static const WCHAR keySuffix[] = L"\\PythonPath"; + size_t versionLen; + DWORD index; + WCHAR *keyBuf = NULL; + WCHAR *keyBufPtr; + WCHAR **ppPaths = NULL; + + /* Tried to use sysget("winver") but here is too early :-( */ + versionLen = strlen(PyWin_DLLVersionString); + /* Space for all the chars, plus one \0 */ + keyBuf = keyBufPtr = malloc(sizeof(keyPrefix) + + sizeof(WCHAR)*(versionLen-1) + + sizeof(keySuffix)); + if (keyBuf==NULL) goto done; + + memcpy(keyBufPtr, keyPrefix, sizeof(keyPrefix)-sizeof(WCHAR)); + keyBufPtr += sizeof(keyPrefix)/sizeof(WCHAR) - 1; + mbstowcs(keyBufPtr, PyWin_DLLVersionString, versionLen); + keyBufPtr += versionLen; + /* NULL comes with this one! */ + memcpy(keyBufPtr, keySuffix, sizeof(keySuffix)); + /* Open the root Python key */ + rc=RegOpenKeyExW(keyBase, + keyBuf, /* subkey */ + 0, /* reserved */ + KEY_READ, + &newKey); + if (rc!=ERROR_SUCCESS) goto done; + /* Find out how big our core buffer is, and how many subkeys we have */ + rc = RegQueryInfoKey(newKey, NULL, NULL, NULL, &numKeys, NULL, NULL, + NULL, NULL, &dataSize, NULL, NULL); + if (rc!=ERROR_SUCCESS) goto done; + if (skipcore) dataSize = 0; /* Only count core ones if we want them! */ + /* Allocate a temp array of char buffers, so we only need to loop + reading the registry once + */ + ppPaths = malloc( sizeof(WCHAR *) * numKeys ); + if (ppPaths==NULL) goto done; + memset(ppPaths, 0, sizeof(WCHAR *) * numKeys); + /* Loop over all subkeys, allocating a temp sub-buffer. */ + for(index=0;index 0) { + *(szCur++) = L';'; + dataSize--; + } + if (ppPaths[index]) { + Py_ssize_t len = wcslen(ppPaths[index]); + wcsncpy(szCur, ppPaths[index], len); + szCur += len; + assert(dataSize > (DWORD)len); + dataSize -= (DWORD)len; + } + } + if (skipcore) + *szCur = '\0'; + else { + /* If we have no values, we dont need a ';' */ + if (numKeys) { + *(szCur++) = L';'; + dataSize--; + } + /* Now append the core path entries - + this will include the NULL + */ + rc = RegQueryValueExW(newKey, NULL, 0, NULL, + (LPBYTE)szCur, &dataSize); + } + /* And set the result - caller must free */ + retval = dataBuf; + } done: - /* Loop freeing my temp buffers */ - if (ppPaths) { - for(index=0;index= MAXPATHLEN) - envpath = NULL; - } + char *_envpath = Py_GETENV("PYTHONPATH"); + wchar_t wenvpath[MAXPATHLEN+1]; + if (_envpath) { + size_t r = mbstowcs(wenvpath, _envpath, MAXPATHLEN+1); + envpath = wenvpath; + if (r == (size_t)-1 || r >= MAXPATHLEN) + envpath = NULL; + } #endif - get_progpath(); - /* progpath guaranteed \0 terminated in MAXPATH+1 bytes. */ - wcscpy(argv0_path, progpath); - reduce(argv0_path); - if (pythonhome == NULL || *pythonhome == '\0') { - if (search_for_prefix(argv0_path, LANDMARK)) - pythonhome = prefix; - else - pythonhome = NULL; - } - else - wcsncpy(prefix, pythonhome, MAXPATHLEN); + get_progpath(); + /* progpath guaranteed \0 terminated in MAXPATH+1 bytes. */ + wcscpy(argv0_path, progpath); + reduce(argv0_path); + if (pythonhome == NULL || *pythonhome == '\0') { + if (search_for_prefix(argv0_path, LANDMARK)) + pythonhome = prefix; + else + pythonhome = NULL; + } + else + wcsncpy(prefix, pythonhome, MAXPATHLEN); - if (envpath && *envpath == '\0') - envpath = NULL; + if (envpath && *envpath == '\0') + envpath = NULL; #ifdef MS_WINDOWS - /* Calculate zip archive path */ - if (dllpath[0]) /* use name of python DLL */ - wcsncpy(zip_path, dllpath, MAXPATHLEN); - else /* use name of executable program */ - wcsncpy(zip_path, progpath, MAXPATHLEN); - zip_path[MAXPATHLEN] = '\0'; - len = wcslen(zip_path); - if (len > 4) { - zip_path[len-3] = 'z'; /* change ending to "zip" */ - zip_path[len-2] = 'i'; - zip_path[len-1] = 'p'; - } - else { - zip_path[0] = 0; - } - - skiphome = pythonhome==NULL ? 0 : 1; + /* Calculate zip archive path */ + if (dllpath[0]) /* use name of python DLL */ + wcsncpy(zip_path, dllpath, MAXPATHLEN); + else /* use name of executable program */ + wcsncpy(zip_path, progpath, MAXPATHLEN); + zip_path[MAXPATHLEN] = '\0'; + len = wcslen(zip_path); + if (len > 4) { + zip_path[len-3] = 'z'; /* change ending to "zip" */ + zip_path[len-2] = 'i'; + zip_path[len-1] = 'p'; + } + else { + zip_path[0] = 0; + } + + skiphome = pythonhome==NULL ? 0 : 1; #ifdef Py_ENABLE_SHARED - machinepath = getpythonregpath(HKEY_LOCAL_MACHINE, skiphome); - userpath = getpythonregpath(HKEY_CURRENT_USER, skiphome); + machinepath = getpythonregpath(HKEY_LOCAL_MACHINE, skiphome); + userpath = getpythonregpath(HKEY_CURRENT_USER, skiphome); #endif - /* We only use the default relative PYTHONPATH if we havent - anything better to use! */ - skipdefault = envpath!=NULL || pythonhome!=NULL || \ - machinepath!=NULL || userpath!=NULL; + /* We only use the default relative PYTHONPATH if we havent + anything better to use! */ + skipdefault = envpath!=NULL || pythonhome!=NULL || \ + machinepath!=NULL || userpath!=NULL; #endif - /* We need to construct a path from the following parts. - (1) the PYTHONPATH environment variable, if set; - (2) for Win32, the zip archive file path; - (3) for Win32, the machinepath and userpath, if set; - (4) the PYTHONPATH config macro, with the leading "." - of each component replaced with pythonhome, if set; - (5) the directory containing the executable (argv0_path). - The length calculation calculates #4 first. - Extra rules: - - If PYTHONHOME is set (in any way) item (3) is ignored. - - If registry values are used, (4) and (5) are ignored. - */ - - /* Calculate size of return buffer */ - if (pythonhome != NULL) { - wchar_t *p; - bufsz = 1; - for (p = PYTHONPATH; *p; p++) { - if (*p == DELIM) - bufsz++; /* number of DELIM plus one */ - } - bufsz *= wcslen(pythonhome); - } - else - bufsz = 0; - bufsz += wcslen(PYTHONPATH) + 1; - bufsz += wcslen(argv0_path) + 1; + /* We need to construct a path from the following parts. + (1) the PYTHONPATH environment variable, if set; + (2) for Win32, the zip archive file path; + (3) for Win32, the machinepath and userpath, if set; + (4) the PYTHONPATH config macro, with the leading "." + of each component replaced with pythonhome, if set; + (5) the directory containing the executable (argv0_path). + The length calculation calculates #4 first. + Extra rules: + - If PYTHONHOME is set (in any way) item (3) is ignored. + - If registry values are used, (4) and (5) are ignored. + */ + + /* Calculate size of return buffer */ + if (pythonhome != NULL) { + wchar_t *p; + bufsz = 1; + for (p = PYTHONPATH; *p; p++) { + if (*p == DELIM) + bufsz++; /* number of DELIM plus one */ + } + bufsz *= wcslen(pythonhome); + } + else + bufsz = 0; + bufsz += wcslen(PYTHONPATH) + 1; + bufsz += wcslen(argv0_path) + 1; #ifdef MS_WINDOWS - if (userpath) - bufsz += wcslen(userpath) + 1; - if (machinepath) - bufsz += wcslen(machinepath) + 1; - bufsz += wcslen(zip_path) + 1; + if (userpath) + bufsz += wcslen(userpath) + 1; + if (machinepath) + bufsz += wcslen(machinepath) + 1; + bufsz += wcslen(zip_path) + 1; #endif - if (envpath != NULL) - bufsz += wcslen(envpath) + 1; + if (envpath != NULL) + bufsz += wcslen(envpath) + 1; - module_search_path = buf = malloc(bufsz*sizeof(wchar_t)); - if (buf == NULL) { - /* We can't exit, so print a warning and limp along */ - fprintf(stderr, "Can't malloc dynamic PYTHONPATH.\n"); - if (envpath) { - fprintf(stderr, "Using environment $PYTHONPATH.\n"); - module_search_path = envpath; - } - else { - fprintf(stderr, "Using default static path.\n"); - module_search_path = PYTHONPATH; - } + module_search_path = buf = malloc(bufsz*sizeof(wchar_t)); + if (buf == NULL) { + /* We can't exit, so print a warning and limp along */ + fprintf(stderr, "Can't malloc dynamic PYTHONPATH.\n"); + if (envpath) { + fprintf(stderr, "Using environment $PYTHONPATH.\n"); + module_search_path = envpath; + } + else { + fprintf(stderr, "Using default static path.\n"); + module_search_path = PYTHONPATH; + } #ifdef MS_WINDOWS - if (machinepath) - free(machinepath); - if (userpath) - free(userpath); + if (machinepath) + free(machinepath); + if (userpath) + free(userpath); #endif /* MS_WINDOWS */ - return; - } + return; + } - if (envpath) { - wcscpy(buf, envpath); - buf = wcschr(buf, L'\0'); - *buf++ = DELIM; - } + if (envpath) { + wcscpy(buf, envpath); + buf = wcschr(buf, L'\0'); + *buf++ = DELIM; + } #ifdef MS_WINDOWS - if (zip_path[0]) { - wcscpy(buf, zip_path); - buf = wcschr(buf, L'\0'); - *buf++ = DELIM; - } - if (userpath) { - wcscpy(buf, userpath); - buf = wcschr(buf, L'\0'); - *buf++ = DELIM; - free(userpath); - } - if (machinepath) { - wcscpy(buf, machinepath); - buf = wcschr(buf, L'\0'); - *buf++ = DELIM; - free(machinepath); - } - if (pythonhome == NULL) { - if (!skipdefault) { - wcscpy(buf, PYTHONPATH); - buf = wcschr(buf, L'\0'); - } - } + if (zip_path[0]) { + wcscpy(buf, zip_path); + buf = wcschr(buf, L'\0'); + *buf++ = DELIM; + } + if (userpath) { + wcscpy(buf, userpath); + buf = wcschr(buf, L'\0'); + *buf++ = DELIM; + free(userpath); + } + if (machinepath) { + wcscpy(buf, machinepath); + buf = wcschr(buf, L'\0'); + *buf++ = DELIM; + free(machinepath); + } + if (pythonhome == NULL) { + if (!skipdefault) { + wcscpy(buf, PYTHONPATH); + buf = wcschr(buf, L'\0'); + } + } #else - if (pythonhome == NULL) { - wcscpy(buf, PYTHONPATH); - buf = wcschr(buf, L'\0'); - } + if (pythonhome == NULL) { + wcscpy(buf, PYTHONPATH); + buf = wcschr(buf, L'\0'); + } #endif /* MS_WINDOWS */ - else { - wchar_t *p = PYTHONPATH; - wchar_t *q; - size_t n; - for (;;) { - q = wcschr(p, DELIM); - if (q == NULL) - n = wcslen(p); - else - n = q-p; - if (p[0] == '.' && is_sep(p[1])) { - wcscpy(buf, pythonhome); - buf = wcschr(buf, L'\0'); - p++; - n--; - } - wcsncpy(buf, p, n); - buf += n; - if (q == NULL) - break; - *buf++ = DELIM; - p = q+1; - } - } - if (argv0_path) { - *buf++ = DELIM; - wcscpy(buf, argv0_path); - buf = wcschr(buf, L'\0'); - } - *buf = L'\0'; - /* Now to pull one last hack/trick. If sys.prefix is - empty, then try and find it somewhere on the paths - we calculated. We scan backwards, as our general policy - is that Python core directories are at the *end* of - sys.path. We assume that our "lib" directory is - on the path, and that our 'prefix' directory is - the parent of that. - */ - if (*prefix==L'\0') { - wchar_t lookBuf[MAXPATHLEN+1]; - wchar_t *look = buf - 1; /* 'buf' is at the end of the buffer */ - while (1) { - Py_ssize_t nchars; - wchar_t *lookEnd = look; - /* 'look' will end up one character before the - start of the path in question - even if this - is one character before the start of the buffer - */ - while (look >= module_search_path && *look != DELIM) - look--; - nchars = lookEnd-look; - wcsncpy(lookBuf, look+1, nchars); - lookBuf[nchars] = L'\0'; - /* Up one level to the parent */ - reduce(lookBuf); - if (search_for_prefix(lookBuf, LANDMARK)) { - break; - } - /* If we are out of paths to search - give up */ - if (look < module_search_path) - break; - look--; - } - } + else { + wchar_t *p = PYTHONPATH; + wchar_t *q; + size_t n; + for (;;) { + q = wcschr(p, DELIM); + if (q == NULL) + n = wcslen(p); + else + n = q-p; + if (p[0] == '.' && is_sep(p[1])) { + wcscpy(buf, pythonhome); + buf = wcschr(buf, L'\0'); + p++; + n--; + } + wcsncpy(buf, p, n); + buf += n; + if (q == NULL) + break; + *buf++ = DELIM; + p = q+1; + } + } + if (argv0_path) { + *buf++ = DELIM; + wcscpy(buf, argv0_path); + buf = wcschr(buf, L'\0'); + } + *buf = L'\0'; + /* Now to pull one last hack/trick. If sys.prefix is + empty, then try and find it somewhere on the paths + we calculated. We scan backwards, as our general policy + is that Python core directories are at the *end* of + sys.path. We assume that our "lib" directory is + on the path, and that our 'prefix' directory is + the parent of that. + */ + if (*prefix==L'\0') { + wchar_t lookBuf[MAXPATHLEN+1]; + wchar_t *look = buf - 1; /* 'buf' is at the end of the buffer */ + while (1) { + Py_ssize_t nchars; + wchar_t *lookEnd = look; + /* 'look' will end up one character before the + start of the path in question - even if this + is one character before the start of the buffer + */ + while (look >= module_search_path && *look != DELIM) + look--; + nchars = lookEnd-look; + wcsncpy(lookBuf, look+1, nchars); + lookBuf[nchars] = L'\0'; + /* Up one level to the parent */ + reduce(lookBuf); + if (search_for_prefix(lookBuf, LANDMARK)) { + break; + } + /* If we are out of paths to search - give up */ + if (look < module_search_path) + break; + look--; + } + } } @@ -657,29 +657,29 @@ wchar_t * Py_GetPath(void) { - if (!module_search_path) - calculate_path(); - return module_search_path; + if (!module_search_path) + calculate_path(); + return module_search_path; } wchar_t * Py_GetPrefix(void) { - if (!module_search_path) - calculate_path(); - return prefix; + if (!module_search_path) + calculate_path(); + return prefix; } wchar_t * Py_GetExecPrefix(void) { - return Py_GetPrefix(); + return Py_GetPrefix(); } wchar_t * Py_GetProgramFullPath(void) { - if (!module_search_path) - calculate_path(); - return progpath; + if (!module_search_path) + calculate_path(); + return progpath; } Modified: python/branches/py3k-jit/PC/import_nt.c ============================================================================== --- python/branches/py3k-jit/PC/import_nt.c (original) +++ python/branches/py3k-jit/PC/import_nt.c Mon May 10 23:55:43 2010 @@ -1,6 +1,6 @@ /******************************************************************** - import_nt.c + import_nt.c Win32 specific import code. @@ -16,71 +16,71 @@ extern const char *PyWin_DLLVersionString; FILE *PyWin_FindRegisteredModule(const char *moduleName, - struct filedescr **ppFileDesc, - char *pathBuf, - Py_ssize_t pathLen) + struct filedescr **ppFileDesc, + char *pathBuf, + Py_ssize_t pathLen) { - char *moduleKey; - const char keyPrefix[] = "Software\\Python\\PythonCore\\"; - const char keySuffix[] = "\\Modules\\"; + char *moduleKey; + const char keyPrefix[] = "Software\\Python\\PythonCore\\"; + const char keySuffix[] = "\\Modules\\"; #ifdef _DEBUG - /* In debugging builds, we _must_ have the debug version - * registered. - */ - const char debugString[] = "\\Debug"; + /* In debugging builds, we _must_ have the debug version + * registered. + */ + const char debugString[] = "\\Debug"; #else - const char debugString[] = ""; + const char debugString[] = ""; #endif - struct filedescr *fdp = NULL; - FILE *fp; - HKEY keyBase = HKEY_CURRENT_USER; - int modNameSize; - long regStat; - - /* Calculate the size for the sprintf buffer. - * Get the size of the chars only, plus 1 NULL. - */ - size_t bufSize = sizeof(keyPrefix)-1 + - strlen(PyWin_DLLVersionString) + - sizeof(keySuffix) + - strlen(moduleName) + - sizeof(debugString) - 1; - /* alloca == no free required, but memory only local to fn, - * also no heap fragmentation! - */ - moduleKey = alloca(bufSize); - PyOS_snprintf(moduleKey, bufSize, - "Software\\Python\\PythonCore\\%s\\Modules\\%s%s", - PyWin_DLLVersionString, moduleName, debugString); - - assert(pathLen < INT_MAX); - modNameSize = (int)pathLen; - regStat = RegQueryValue(keyBase, moduleKey, pathBuf, &modNameSize); - if (regStat != ERROR_SUCCESS) { - /* No user setting - lookup in machine settings */ - keyBase = HKEY_LOCAL_MACHINE; - /* be anal - failure may have reset size param */ - modNameSize = (int)pathLen; - regStat = RegQueryValue(keyBase, moduleKey, - pathBuf, &modNameSize); - - if (regStat != ERROR_SUCCESS) - return NULL; - } - /* use the file extension to locate the type entry. */ - for (fdp = _PyImport_Filetab; fdp->suffix != NULL; fdp++) { - size_t extLen = strlen(fdp->suffix); - assert(modNameSize >= 0); /* else cast to size_t is wrong */ - if ((size_t)modNameSize > extLen && - strnicmp(pathBuf + ((size_t)modNameSize-extLen-1), - fdp->suffix, - extLen) == 0) - break; - } - if (fdp->suffix == NULL) - return NULL; - fp = fopen(pathBuf, fdp->mode); - if (fp != NULL) - *ppFileDesc = fdp; - return fp; + struct filedescr *fdp = NULL; + FILE *fp; + HKEY keyBase = HKEY_CURRENT_USER; + int modNameSize; + long regStat; + + /* Calculate the size for the sprintf buffer. + * Get the size of the chars only, plus 1 NULL. + */ + size_t bufSize = sizeof(keyPrefix)-1 + + strlen(PyWin_DLLVersionString) + + sizeof(keySuffix) + + strlen(moduleName) + + sizeof(debugString) - 1; + /* alloca == no free required, but memory only local to fn, + * also no heap fragmentation! + */ + moduleKey = alloca(bufSize); + PyOS_snprintf(moduleKey, bufSize, + "Software\\Python\\PythonCore\\%s\\Modules\\%s%s", + PyWin_DLLVersionString, moduleName, debugString); + + assert(pathLen < INT_MAX); + modNameSize = (int)pathLen; + regStat = RegQueryValue(keyBase, moduleKey, pathBuf, &modNameSize); + if (regStat != ERROR_SUCCESS) { + /* No user setting - lookup in machine settings */ + keyBase = HKEY_LOCAL_MACHINE; + /* be anal - failure may have reset size param */ + modNameSize = (int)pathLen; + regStat = RegQueryValue(keyBase, moduleKey, + pathBuf, &modNameSize); + + if (regStat != ERROR_SUCCESS) + return NULL; + } + /* use the file extension to locate the type entry. */ + for (fdp = _PyImport_Filetab; fdp->suffix != NULL; fdp++) { + size_t extLen = strlen(fdp->suffix); + assert(modNameSize >= 0); /* else cast to size_t is wrong */ + if ((size_t)modNameSize > extLen && + strnicmp(pathBuf + ((size_t)modNameSize-extLen-1), + fdp->suffix, + extLen) == 0) + break; + } + if (fdp->suffix == NULL) + return NULL; + fp = fopen(pathBuf, fdp->mode); + if (fp != NULL) + *ppFileDesc = fdp; + return fp; } Modified: python/branches/py3k-jit/PC/make_versioninfo.c ============================================================================== --- python/branches/py3k-jit/PC/make_versioninfo.c (original) +++ python/branches/py3k-jit/PC/make_versioninfo.c Mon May 10 23:55:43 2010 @@ -22,17 +22,17 @@ */ int main(int argc, char **argv) { - printf("/* This file created by make_versioninfo.exe */\n"); - printf("#define FIELD3 %d\n", - PY_MICRO_VERSION*1000 + PY_RELEASE_LEVEL*10 + PY_RELEASE_SERIAL); - printf("#define MS_DLL_ID \"%d.%d\"\n", - PY_MAJOR_VERSION, PY_MINOR_VERSION); - printf("#ifndef _DEBUG\n"); - printf("#define PYTHON_DLL_NAME \"python%d%d.dll\"\n", - PY_MAJOR_VERSION, PY_MINOR_VERSION); - printf("#else\n"); - printf("#define PYTHON_DLL_NAME \"python%d%d_d.dll\"\n", - PY_MAJOR_VERSION, PY_MINOR_VERSION); - printf("#endif\n"); - return 0; + printf("/* This file created by make_versioninfo.exe */\n"); + printf("#define FIELD3 %d\n", + PY_MICRO_VERSION*1000 + PY_RELEASE_LEVEL*10 + PY_RELEASE_SERIAL); + printf("#define MS_DLL_ID \"%d.%d\"\n", + PY_MAJOR_VERSION, PY_MINOR_VERSION); + printf("#ifndef _DEBUG\n"); + printf("#define PYTHON_DLL_NAME \"python%d%d.dll\"\n", + PY_MAJOR_VERSION, PY_MINOR_VERSION); + printf("#else\n"); + printf("#define PYTHON_DLL_NAME \"python%d%d_d.dll\"\n", + PY_MAJOR_VERSION, PY_MINOR_VERSION); + printf("#endif\n"); + return 0; } Modified: python/branches/py3k-jit/PC/msvcrtmodule.c ============================================================================== --- python/branches/py3k-jit/PC/msvcrtmodule.c (original) +++ python/branches/py3k-jit/PC/msvcrtmodule.c Mon May 10 23:55:43 2010 @@ -1,18 +1,18 @@ /********************************************************* - msvcrtmodule.c + msvcrtmodule.c - A Python interface to the Microsoft Visual C Runtime - Library, providing access to those non-portable, but - still useful routines. + A Python interface to the Microsoft Visual C Runtime + Library, providing access to those non-portable, but + still useful routines. - Only ever compiled with an MS compiler, so no attempt - has been made to avoid MS language extensions, etc... + Only ever compiled with an MS compiler, so no attempt + has been made to avoid MS language extensions, etc... - This may only work on NT or 95... + This may only work on NT or 95... - Author: Mark Hammond and Guido van Rossum. - Maintenance: Guido van Rossum. + Author: Mark Hammond and Guido van Rossum. + Maintenance: Guido van Rossum. ***********************************************************/ @@ -35,14 +35,14 @@ static PyObject * msvcrt_heapmin(PyObject *self, PyObject *args) { - if (!PyArg_ParseTuple(args, ":heapmin")) - return NULL; + if (!PyArg_ParseTuple(args, ":heapmin")) + return NULL; - if (_heapmin() != 0) - return PyErr_SetFromErrno(PyExc_IOError); + if (_heapmin() != 0) + return PyErr_SetFromErrno(PyExc_IOError); - Py_INCREF(Py_None); - return Py_None; + Py_INCREF(Py_None); + return Py_None; } PyDoc_STRVAR(heapmin_doc, @@ -55,22 +55,22 @@ static PyObject * msvcrt_locking(PyObject *self, PyObject *args) { - int fd; - int mode; - long nbytes; - int err; - - if (!PyArg_ParseTuple(args, "iil:locking", &fd, &mode, &nbytes)) - return NULL; - - Py_BEGIN_ALLOW_THREADS - err = _locking(fd, mode, nbytes); - Py_END_ALLOW_THREADS - if (err != 0) - return PyErr_SetFromErrno(PyExc_IOError); + int fd; + int mode; + long nbytes; + int err; + + if (!PyArg_ParseTuple(args, "iil:locking", &fd, &mode, &nbytes)) + return NULL; + + Py_BEGIN_ALLOW_THREADS + err = _locking(fd, mode, nbytes); + Py_END_ALLOW_THREADS + if (err != 0) + return PyErr_SetFromErrno(PyExc_IOError); - Py_INCREF(Py_None); - return Py_None; + Py_INCREF(Py_None); + return Py_None; } PyDoc_STRVAR(locking_doc, @@ -88,16 +88,16 @@ static PyObject * msvcrt_setmode(PyObject *self, PyObject *args) { - int fd; - int flags; - if (!PyArg_ParseTuple(args,"ii:setmode", &fd, &flags)) - return NULL; - - flags = _setmode(fd, flags); - if (flags == -1) - return PyErr_SetFromErrno(PyExc_IOError); + int fd; + int flags; + if (!PyArg_ParseTuple(args,"ii:setmode", &fd, &flags)) + return NULL; + + flags = _setmode(fd, flags); + if (flags == -1) + return PyErr_SetFromErrno(PyExc_IOError); - return PyLong_FromLong(flags); + return PyLong_FromLong(flags); } PyDoc_STRVAR(setmode_doc, @@ -111,18 +111,18 @@ static PyObject * msvcrt_open_osfhandle(PyObject *self, PyObject *args) { - long handle; - int flags; - int fd; - - if (!PyArg_ParseTuple(args, "li:open_osfhandle", &handle, &flags)) - return NULL; - - fd = _open_osfhandle(handle, flags); - if (fd == -1) - return PyErr_SetFromErrno(PyExc_IOError); + long handle; + int flags; + int fd; + + if (!PyArg_ParseTuple(args, "li:open_osfhandle", &handle, &flags)) + return NULL; + + fd = _open_osfhandle(handle, flags); + if (fd == -1) + return PyErr_SetFromErrno(PyExc_IOError); - return PyLong_FromLong(fd); + return PyLong_FromLong(fd); } PyDoc_STRVAR(open_osfhandle_doc, @@ -137,20 +137,20 @@ static PyObject * msvcrt_get_osfhandle(PyObject *self, PyObject *args) { - int fd; - Py_intptr_t handle; + int fd; + Py_intptr_t handle; - if (!PyArg_ParseTuple(args,"i:get_osfhandle", &fd)) - return NULL; + if (!PyArg_ParseTuple(args,"i:get_osfhandle", &fd)) + return NULL; - handle = _get_osfhandle(fd); - if (handle == -1) - return PyErr_SetFromErrno(PyExc_IOError); - - /* technically 'handle' is not a pointer, but a integer as - large as a pointer, Python's *VoidPtr interface is the - most appropriate here */ - return PyLong_FromVoidPtr((void*)handle); + handle = _get_osfhandle(fd); + if (handle == -1) + return PyErr_SetFromErrno(PyExc_IOError); + + /* technically 'handle' is not a pointer, but a integer as + large as a pointer, Python's *VoidPtr interface is the + most appropriate here */ + return PyLong_FromVoidPtr((void*)handle); } PyDoc_STRVAR(get_osfhandle_doc, @@ -164,13 +164,13 @@ static PyObject * msvcrt_kbhit(PyObject *self, PyObject *args) { - int ok; + int ok; - if (!PyArg_ParseTuple(args, ":kbhit")) - return NULL; + if (!PyArg_ParseTuple(args, ":kbhit")) + return NULL; - ok = _kbhit(); - return PyLong_FromLong(ok); + ok = _kbhit(); + return PyLong_FromLong(ok); } PyDoc_STRVAR(kbhit_doc, @@ -181,17 +181,17 @@ static PyObject * msvcrt_getch(PyObject *self, PyObject *args) { - int ch; - char s[1]; + int ch; + char s[1]; - if (!PyArg_ParseTuple(args, ":getch")) - return NULL; + if (!PyArg_ParseTuple(args, ":getch")) + return NULL; - Py_BEGIN_ALLOW_THREADS - ch = _getch(); - Py_END_ALLOW_THREADS - s[0] = ch; - return PyBytes_FromStringAndSize(s, 1); + Py_BEGIN_ALLOW_THREADS + ch = _getch(); + Py_END_ALLOW_THREADS + s[0] = ch; + return PyBytes_FromStringAndSize(s, 1); } PyDoc_STRVAR(getch_doc, @@ -208,17 +208,17 @@ static PyObject * msvcrt_getwch(PyObject *self, PyObject *args) { - Py_UNICODE ch; - Py_UNICODE u[1]; + Py_UNICODE ch; + Py_UNICODE u[1]; - if (!PyArg_ParseTuple(args, ":getwch")) - return NULL; + if (!PyArg_ParseTuple(args, ":getwch")) + return NULL; - Py_BEGIN_ALLOW_THREADS - ch = _getwch(); - Py_END_ALLOW_THREADS - u[0] = ch; - return PyUnicode_FromUnicode(u, 1); + Py_BEGIN_ALLOW_THREADS + ch = _getwch(); + Py_END_ALLOW_THREADS + u[0] = ch; + return PyUnicode_FromUnicode(u, 1); } PyDoc_STRVAR(getwch_doc, @@ -230,17 +230,17 @@ static PyObject * msvcrt_getche(PyObject *self, PyObject *args) { - int ch; - char s[1]; + int ch; + char s[1]; - if (!PyArg_ParseTuple(args, ":getche")) - return NULL; + if (!PyArg_ParseTuple(args, ":getche")) + return NULL; - Py_BEGIN_ALLOW_THREADS - ch = _getche(); - Py_END_ALLOW_THREADS - s[0] = ch; - return PyBytes_FromStringAndSize(s, 1); + Py_BEGIN_ALLOW_THREADS + ch = _getche(); + Py_END_ALLOW_THREADS + s[0] = ch; + return PyBytes_FromStringAndSize(s, 1); } PyDoc_STRVAR(getche_doc, @@ -253,17 +253,17 @@ static PyObject * msvcrt_getwche(PyObject *self, PyObject *args) { - Py_UNICODE ch; - Py_UNICODE s[1]; + Py_UNICODE ch; + Py_UNICODE s[1]; - if (!PyArg_ParseTuple(args, ":getwche")) - return NULL; + if (!PyArg_ParseTuple(args, ":getwche")) + return NULL; - Py_BEGIN_ALLOW_THREADS - ch = _getwche(); - Py_END_ALLOW_THREADS - s[0] = ch; - return PyUnicode_FromUnicode(s, 1); + Py_BEGIN_ALLOW_THREADS + ch = _getwche(); + Py_END_ALLOW_THREADS + s[0] = ch; + return PyUnicode_FromUnicode(s, 1); } PyDoc_STRVAR(getwche_doc, @@ -275,14 +275,14 @@ static PyObject * msvcrt_putch(PyObject *self, PyObject *args) { - char ch; + char ch; - if (!PyArg_ParseTuple(args, "c:putch", &ch)) - return NULL; + if (!PyArg_ParseTuple(args, "c:putch", &ch)) + return NULL; - _putch(ch); - Py_INCREF(Py_None); - return Py_None; + _putch(ch); + Py_INCREF(Py_None); + return Py_None; } PyDoc_STRVAR(putch_doc, @@ -294,13 +294,13 @@ static PyObject * msvcrt_putwch(PyObject *self, PyObject *args) { - int ch; + int ch; - if (!PyArg_ParseTuple(args, "C:putwch", &ch)) - return NULL; + if (!PyArg_ParseTuple(args, "C:putwch", &ch)) + return NULL; - _putwch(ch); - Py_RETURN_NONE; + _putwch(ch); + Py_RETURN_NONE; } @@ -313,15 +313,15 @@ static PyObject * msvcrt_ungetch(PyObject *self, PyObject *args) { - char ch; + char ch; - if (!PyArg_ParseTuple(args, "c:ungetch", &ch)) - return NULL; + if (!PyArg_ParseTuple(args, "c:ungetch", &ch)) + return NULL; - if (_ungetch(ch) == EOF) - return PyErr_SetFromErrno(PyExc_IOError); - Py_INCREF(Py_None); - return Py_None; + if (_ungetch(ch) == EOF) + return PyErr_SetFromErrno(PyExc_IOError); + Py_INCREF(Py_None); + return Py_None; } PyDoc_STRVAR(ungetch_doc, @@ -334,15 +334,15 @@ static PyObject * msvcrt_ungetwch(PyObject *self, PyObject *args) { - int ch; + int ch; - if (!PyArg_ParseTuple(args, "C:ungetwch", &ch)) - return NULL; + if (!PyArg_ParseTuple(args, "C:ungetwch", &ch)) + return NULL; - if (_ungetwch(ch) == WEOF) - return PyErr_SetFromErrno(PyExc_IOError); - Py_INCREF(Py_None); - return Py_None; + if (_ungetwch(ch) == WEOF) + return PyErr_SetFromErrno(PyExc_IOError); + Py_INCREF(Py_None); + return Py_None; } PyDoc_STRVAR(ungetwch_doc, @@ -354,15 +354,15 @@ static void insertint(PyObject *d, char *name, int value) { - PyObject *v = PyLong_FromLong((long) value); - if (v == NULL) { - /* Don't bother reporting this error */ - PyErr_Clear(); - } - else { - PyDict_SetItemString(d, name, v); - Py_DECREF(v); - } + PyObject *v = PyLong_FromLong((long) value); + if (v == NULL) { + /* Don't bother reporting this error */ + PyErr_Clear(); + } + else { + PyDict_SetItemString(d, name, v); + Py_DECREF(v); + } } #ifdef _DEBUG @@ -370,40 +370,40 @@ static PyObject* msvcrt_setreportfile(PyObject *self, PyObject *args) { - int type, file; - _HFILE res; + int type, file; + _HFILE res; - if (!PyArg_ParseTuple(args, "ii", &type, &file)) - return NULL; - res = _CrtSetReportFile(type, (_HFILE)file); - return PyLong_FromLong((long)res); - Py_INCREF(Py_None); - return Py_None; + if (!PyArg_ParseTuple(args, "ii", &type, &file)) + return NULL; + res = _CrtSetReportFile(type, (_HFILE)file); + return PyLong_FromLong((long)res); + Py_INCREF(Py_None); + return Py_None; } static PyObject* msvcrt_setreportmode(PyObject *self, PyObject *args) { - int type, mode; - int res; + int type, mode; + int res; - if (!PyArg_ParseTuple(args, "ii", &type, &mode)) - return NULL; - res = _CrtSetReportMode(type, mode); - if (res == -1) - return PyErr_SetFromErrno(PyExc_IOError); - return PyLong_FromLong(res); + if (!PyArg_ParseTuple(args, "ii", &type, &mode)) + return NULL; + res = _CrtSetReportMode(type, mode); + if (res == -1) + return PyErr_SetFromErrno(PyExc_IOError); + return PyLong_FromLong(res); } static PyObject* msvcrt_seterrormode(PyObject *self, PyObject *args) { - int mode, res; + int mode, res; - if (!PyArg_ParseTuple(args, "i", &mode)) - return NULL; - res = _set_error_mode(mode); - return PyLong_FromLong(res); + if (!PyArg_ParseTuple(args, "i", &mode)) + return NULL; + res = _set_error_mode(mode); + return PyLong_FromLong(res); } #endif @@ -411,104 +411,104 @@ static PyObject* seterrormode(PyObject *self, PyObject *args) { - unsigned int mode, res; + unsigned int mode, res; - if (!PyArg_ParseTuple(args, "I", &mode)) - return NULL; - res = SetErrorMode(mode); - return PyLong_FromUnsignedLong(res); + if (!PyArg_ParseTuple(args, "I", &mode)) + return NULL; + res = SetErrorMode(mode); + return PyLong_FromUnsignedLong(res); } /* List of functions exported by this module */ static struct PyMethodDef msvcrt_functions[] = { - {"heapmin", msvcrt_heapmin, METH_VARARGS, heapmin_doc}, - {"locking", msvcrt_locking, METH_VARARGS, locking_doc}, - {"setmode", msvcrt_setmode, METH_VARARGS, setmode_doc}, - {"open_osfhandle", msvcrt_open_osfhandle, METH_VARARGS, open_osfhandle_doc}, - {"get_osfhandle", msvcrt_get_osfhandle, METH_VARARGS, get_osfhandle_doc}, - {"kbhit", msvcrt_kbhit, METH_VARARGS, kbhit_doc}, - {"getch", msvcrt_getch, METH_VARARGS, getch_doc}, - {"getche", msvcrt_getche, METH_VARARGS, getche_doc}, - {"putch", msvcrt_putch, METH_VARARGS, putch_doc}, - {"ungetch", msvcrt_ungetch, METH_VARARGS, ungetch_doc}, - {"SetErrorMode", seterrormode, METH_VARARGS}, + {"heapmin", msvcrt_heapmin, METH_VARARGS, heapmin_doc}, + {"locking", msvcrt_locking, METH_VARARGS, locking_doc}, + {"setmode", msvcrt_setmode, METH_VARARGS, setmode_doc}, + {"open_osfhandle", msvcrt_open_osfhandle, METH_VARARGS, open_osfhandle_doc}, + {"get_osfhandle", msvcrt_get_osfhandle, METH_VARARGS, get_osfhandle_doc}, + {"kbhit", msvcrt_kbhit, METH_VARARGS, kbhit_doc}, + {"getch", msvcrt_getch, METH_VARARGS, getch_doc}, + {"getche", msvcrt_getche, METH_VARARGS, getche_doc}, + {"putch", msvcrt_putch, METH_VARARGS, putch_doc}, + {"ungetch", msvcrt_ungetch, METH_VARARGS, ungetch_doc}, + {"SetErrorMode", seterrormode, METH_VARARGS}, #ifdef _DEBUG - {"CrtSetReportFile", msvcrt_setreportfile, METH_VARARGS}, - {"CrtSetReportMode", msvcrt_setreportmode, METH_VARARGS}, - {"set_error_mode", msvcrt_seterrormode, METH_VARARGS}, + {"CrtSetReportFile", msvcrt_setreportfile, METH_VARARGS}, + {"CrtSetReportMode", msvcrt_setreportmode, METH_VARARGS}, + {"set_error_mode", msvcrt_seterrormode, METH_VARARGS}, #endif #ifdef _WCONIO_DEFINED - {"getwch", msvcrt_getwch, METH_VARARGS, getwch_doc}, - {"getwche", msvcrt_getwche, METH_VARARGS, getwche_doc}, - {"putwch", msvcrt_putwch, METH_VARARGS, putwch_doc}, - {"ungetwch", msvcrt_ungetwch, METH_VARARGS, ungetwch_doc}, + {"getwch", msvcrt_getwch, METH_VARARGS, getwch_doc}, + {"getwche", msvcrt_getwche, METH_VARARGS, getwche_doc}, + {"putwch", msvcrt_putwch, METH_VARARGS, putwch_doc}, + {"ungetwch", msvcrt_ungetwch, METH_VARARGS, ungetwch_doc}, #endif - {NULL, NULL} + {NULL, NULL} }; static struct PyModuleDef msvcrtmodule = { - PyModuleDef_HEAD_INIT, - "msvcrt", - NULL, - -1, - msvcrt_functions, - NULL, - NULL, - NULL, - NULL + PyModuleDef_HEAD_INIT, + "msvcrt", + NULL, + -1, + msvcrt_functions, + NULL, + NULL, + NULL, + NULL }; PyMODINIT_FUNC PyInit_msvcrt(void) { - int st; - PyObject *d; - PyObject *m = PyModule_Create(&msvcrtmodule); - if (m == NULL) - return NULL; - d = PyModule_GetDict(m); - - /* constants for the locking() function's mode argument */ - insertint(d, "LK_LOCK", _LK_LOCK); - insertint(d, "LK_NBLCK", _LK_NBLCK); - insertint(d, "LK_NBRLCK", _LK_NBRLCK); - insertint(d, "LK_RLCK", _LK_RLCK); - insertint(d, "LK_UNLCK", _LK_UNLCK); - insertint(d, "SEM_FAILCRITICALERRORS", SEM_FAILCRITICALERRORS); - insertint(d, "SEM_NOALIGNMENTFAULTEXCEPT", SEM_NOALIGNMENTFAULTEXCEPT); - insertint(d, "SEM_NOGPFAULTERRORBOX", SEM_NOGPFAULTERRORBOX); - insertint(d, "SEM_NOOPENFILEERRORBOX", SEM_NOOPENFILEERRORBOX); + int st; + PyObject *d; + PyObject *m = PyModule_Create(&msvcrtmodule); + if (m == NULL) + return NULL; + d = PyModule_GetDict(m); + + /* constants for the locking() function's mode argument */ + insertint(d, "LK_LOCK", _LK_LOCK); + insertint(d, "LK_NBLCK", _LK_NBLCK); + insertint(d, "LK_NBRLCK", _LK_NBRLCK); + insertint(d, "LK_RLCK", _LK_RLCK); + insertint(d, "LK_UNLCK", _LK_UNLCK); + insertint(d, "SEM_FAILCRITICALERRORS", SEM_FAILCRITICALERRORS); + insertint(d, "SEM_NOALIGNMENTFAULTEXCEPT", SEM_NOALIGNMENTFAULTEXCEPT); + insertint(d, "SEM_NOGPFAULTERRORBOX", SEM_NOGPFAULTERRORBOX); + insertint(d, "SEM_NOOPENFILEERRORBOX", SEM_NOOPENFILEERRORBOX); #ifdef _DEBUG - insertint(d, "CRT_WARN", _CRT_WARN); - insertint(d, "CRT_ERROR", _CRT_ERROR); - insertint(d, "CRT_ASSERT", _CRT_ASSERT); - insertint(d, "CRTDBG_MODE_DEBUG", _CRTDBG_MODE_DEBUG); - insertint(d, "CRTDBG_MODE_FILE", _CRTDBG_MODE_FILE); - insertint(d, "CRTDBG_MODE_WNDW", _CRTDBG_MODE_WNDW); - insertint(d, "CRTDBG_REPORT_MODE", _CRTDBG_REPORT_MODE); - insertint(d, "CRTDBG_FILE_STDERR", (int)_CRTDBG_FILE_STDERR); - insertint(d, "CRTDBG_FILE_STDOUT", (int)_CRTDBG_FILE_STDOUT); - insertint(d, "CRTDBG_REPORT_FILE", (int)_CRTDBG_REPORT_FILE); + insertint(d, "CRT_WARN", _CRT_WARN); + insertint(d, "CRT_ERROR", _CRT_ERROR); + insertint(d, "CRT_ASSERT", _CRT_ASSERT); + insertint(d, "CRTDBG_MODE_DEBUG", _CRTDBG_MODE_DEBUG); + insertint(d, "CRTDBG_MODE_FILE", _CRTDBG_MODE_FILE); + insertint(d, "CRTDBG_MODE_WNDW", _CRTDBG_MODE_WNDW); + insertint(d, "CRTDBG_REPORT_MODE", _CRTDBG_REPORT_MODE); + insertint(d, "CRTDBG_FILE_STDERR", (int)_CRTDBG_FILE_STDERR); + insertint(d, "CRTDBG_FILE_STDOUT", (int)_CRTDBG_FILE_STDOUT); + insertint(d, "CRTDBG_REPORT_FILE", (int)_CRTDBG_REPORT_FILE); #endif - /* constants for the crt versions */ + /* constants for the crt versions */ #ifdef _VC_ASSEMBLY_PUBLICKEYTOKEN - st = PyModule_AddStringConstant(m, "VC_ASSEMBLY_PUBLICKEYTOKEN", - _VC_ASSEMBLY_PUBLICKEYTOKEN); - if (st < 0) return NULL; + st = PyModule_AddStringConstant(m, "VC_ASSEMBLY_PUBLICKEYTOKEN", + _VC_ASSEMBLY_PUBLICKEYTOKEN); + if (st < 0) return NULL; #endif #ifdef _CRT_ASSEMBLY_VERSION - st = PyModule_AddStringConstant(m, "CRT_ASSEMBLY_VERSION", - _CRT_ASSEMBLY_VERSION); - if (st < 0) return NULL; + st = PyModule_AddStringConstant(m, "CRT_ASSEMBLY_VERSION", + _CRT_ASSEMBLY_VERSION); + if (st < 0) return NULL; #endif #ifdef __LIBRARIES_ASSEMBLY_NAME_PREFIX - st = PyModule_AddStringConstant(m, "LIBRARIES_ASSEMBLY_NAME_PREFIX", - __LIBRARIES_ASSEMBLY_NAME_PREFIX); - if (st < 0) return NULL; + st = PyModule_AddStringConstant(m, "LIBRARIES_ASSEMBLY_NAME_PREFIX", + __LIBRARIES_ASSEMBLY_NAME_PREFIX); + if (st < 0) return NULL; #endif - return m; + return m; } Modified: python/branches/py3k-jit/PC/os2emx/config.c ============================================================================== --- python/branches/py3k-jit/PC/os2emx/config.c (original) +++ python/branches/py3k-jit/PC/os2emx/config.c Mon May 10 23:55:43 2010 @@ -95,71 +95,71 @@ struct _inittab _PyImport_Inittab[] = { - {"os2", initos2}, - {"signal", initsignal}, + {"os2", initos2}, + {"signal", initsignal}, #ifdef WITH_THREAD - {"_thread", init_thread}, + {"_thread", init_thread}, #endif - {"_codecs", init_codecs}, - {"_csv", init_csv}, - {"_locale", init_locale}, - {"_random", init_random}, - {"_sre", init_sre}, - {"_symtable", init_symtable}, - {"_weakref", init_weakref}, - {"array", initarray}, - {"binascii", initbinascii}, - {"collections", initcollections}, - {"cmath", initcmath}, - {"datetime", initdatetime}, - {"dl", initdl}, - {"errno", initerrno}, - {"fcntl", initfcntl}, - {"_functools", init_functools}, - {"_heapq", init_heapq}, - {"imageop", initimageop}, - {"itertools", inititertools}, - {"math", initmath}, - {"operator", initoperator}, - {"_sha256", init_sha256}, - {"_sha512", init_sha512}, - {"_struct", init_struct}, - {"termios", inittermios}, - {"time", inittime}, - {"xxsubtype", initxxsubtype}, - {"zipimport", initzipimport}, + {"_codecs", init_codecs}, + {"_csv", init_csv}, + {"_locale", init_locale}, + {"_random", init_random}, + {"_sre", init_sre}, + {"_symtable", init_symtable}, + {"_weakref", init_weakref}, + {"array", initarray}, + {"binascii", initbinascii}, + {"collections", initcollections}, + {"cmath", initcmath}, + {"datetime", initdatetime}, + {"dl", initdl}, + {"errno", initerrno}, + {"fcntl", initfcntl}, + {"_functools", init_functools}, + {"_heapq", init_heapq}, + {"imageop", initimageop}, + {"itertools", inititertools}, + {"math", initmath}, + {"operator", initoperator}, + {"_sha256", init_sha256}, + {"_sha512", init_sha512}, + {"_struct", init_struct}, + {"termios", inittermios}, + {"time", inittime}, + {"xxsubtype", initxxsubtype}, + {"zipimport", initzipimport}, #if !HAVE_DYNAMIC_LOADING - {"_curses", init_curses}, - {"_curses_panel", init_curses_panel}, - {"_testcapi", init_testcapi}, - {"bz2", initbz2}, - {"fpectl", initfpectl}, - {"fpetest", initfpetest}, - {"parser", initparser}, - {"pwd", initpwd}, - {"unicodedata", initunicodedata}, - {"zlib", initzlib}, + {"_curses", init_curses}, + {"_curses_panel", init_curses_panel}, + {"_testcapi", init_testcapi}, + {"bz2", initbz2}, + {"fpectl", initfpectl}, + {"fpetest", initfpetest}, + {"parser", initparser}, + {"pwd", initpwd}, + {"unicodedata", initunicodedata}, + {"zlib", initzlib}, #ifdef USE_SOCKET - {"_socket", init_socket}, - {"select", initselect}, + {"_socket", init_socket}, + {"select", initselect}, #endif #endif /* -- ADDMODULE MARKER 2 -- */ - /* This module "lives in" with marshal.c */ - {"marshal", PyMarshal_Init}, + /* This module "lives in" with marshal.c */ + {"marshal", PyMarshal_Init}, - /* This lives it with import.c */ - {"imp", initimp}, + /* This lives it with import.c */ + {"imp", initimp}, - /* These entries are here for sys.builtin_module_names */ - {"__main__", NULL}, - {"builtins", NULL}, - {"sys", NULL}, + /* These entries are here for sys.builtin_module_names */ + {"__main__", NULL}, + {"builtins", NULL}, + {"sys", NULL}, - /* This lives in gcmodule.c */ - {"gc", initgc}, + /* This lives in gcmodule.c */ + {"gc", initgc}, - /* Sentinel */ - {0, 0} + /* Sentinel */ + {0, 0} }; Modified: python/branches/py3k-jit/PC/os2emx/dlfcn.c ============================================================================== --- python/branches/py3k-jit/PC/os2emx/dlfcn.c (original) +++ python/branches/py3k-jit/PC/os2emx/dlfcn.c Mon May 10 23:55:43 2010 @@ -46,178 +46,178 @@ #include typedef struct _track_rec { - char *name; - HMODULE handle; - void *id; - struct _track_rec *next; + char *name; + HMODULE handle; + void *id; + struct _track_rec *next; } tDLLchain, *DLLchain; -static DLLchain dlload = NULL; /* A simple chained list of DLL names */ -static char dlerr [256]; /* last error text string */ +static DLLchain dlload = NULL; /* A simple chained list of DLL names */ +static char dlerr [256]; /* last error text string */ static void *last_id; static DLLchain find_id(void *id) { - DLLchain tmp; + DLLchain tmp; - for (tmp = dlload; tmp; tmp = tmp->next) - if (id == tmp->id) - return tmp; + for (tmp = dlload; tmp; tmp = tmp->next) + if (id == tmp->id) + return tmp; - return NULL; + return NULL; } /* load a dynamic-link library and return handle */ void *dlopen(char *filename, int flags) { - HMODULE hm; - DLLchain tmp; - char err[256]; - char *errtxt; - int rc = 0, set_chain = 0; - - for (tmp = dlload; tmp; tmp = tmp->next) - if (strnicmp(tmp->name, filename, 999) == 0) - break; - - if (!tmp) - { - tmp = (DLLchain) malloc(sizeof(tDLLchain)); - if (!tmp) - goto nomem; - tmp->name = strdup(filename); - tmp->next = dlload; - set_chain = 1; - } - - switch (rc = DosLoadModule((PSZ)&err, sizeof(err), filename, &hm)) - { - case NO_ERROR: - tmp->handle = hm; - if (set_chain) - { - do - last_id++; - while ((last_id == 0) || (find_id(last_id))); - tmp->id = last_id; - dlload = tmp; - } - return tmp->id; - case ERROR_FILE_NOT_FOUND: - case ERROR_PATH_NOT_FOUND: - errtxt = "module `%s' not found"; - break; - case ERROR_TOO_MANY_OPEN_FILES: - case ERROR_NOT_ENOUGH_MEMORY: - case ERROR_SHARING_BUFFER_EXCEEDED: + HMODULE hm; + DLLchain tmp; + char err[256]; + char *errtxt; + int rc = 0, set_chain = 0; + + for (tmp = dlload; tmp; tmp = tmp->next) + if (strnicmp(tmp->name, filename, 999) == 0) + break; + + if (!tmp) + { + tmp = (DLLchain) malloc(sizeof(tDLLchain)); + if (!tmp) + goto nomem; + tmp->name = strdup(filename); + tmp->next = dlload; + set_chain = 1; + } + + switch (rc = DosLoadModule((PSZ)&err, sizeof(err), filename, &hm)) + { + case NO_ERROR: + tmp->handle = hm; + if (set_chain) + { + do + last_id++; + while ((last_id == 0) || (find_id(last_id))); + tmp->id = last_id; + dlload = tmp; + } + return tmp->id; + case ERROR_FILE_NOT_FOUND: + case ERROR_PATH_NOT_FOUND: + errtxt = "module `%s' not found"; + break; + case ERROR_TOO_MANY_OPEN_FILES: + case ERROR_NOT_ENOUGH_MEMORY: + case ERROR_SHARING_BUFFER_EXCEEDED: nomem: - errtxt = "out of system resources"; - break; - case ERROR_ACCESS_DENIED: - errtxt = "access denied"; - break; - case ERROR_BAD_FORMAT: - case ERROR_INVALID_SEGMENT_NUMBER: - case ERROR_INVALID_ORDINAL: - case ERROR_INVALID_MODULETYPE: - case ERROR_INVALID_EXE_SIGNATURE: - case ERROR_EXE_MARKED_INVALID: - case ERROR_ITERATED_DATA_EXCEEDS_64K: - case ERROR_INVALID_MINALLOCSIZE: - case ERROR_INVALID_SEGDPL: - case ERROR_AUTODATASEG_EXCEEDS_64K: - case ERROR_RELOCSRC_CHAIN_EXCEEDS_SEGLIMIT: - errtxt = "invalid module format"; - break; - case ERROR_INVALID_NAME: - errtxt = "filename doesn't match module name"; - break; - case ERROR_SHARING_VIOLATION: - case ERROR_LOCK_VIOLATION: - errtxt = "sharing violation"; - break; - case ERROR_INIT_ROUTINE_FAILED: - errtxt = "module initialization failed"; - break; - default: - errtxt = "cause `%s', error code = %d"; - break; - } - snprintf(dlerr, sizeof(dlerr), errtxt, &err, rc); - if (tmp) - { - if (tmp->name) - free(tmp->name); - free(tmp); - } - return 0; + errtxt = "out of system resources"; + break; + case ERROR_ACCESS_DENIED: + errtxt = "access denied"; + break; + case ERROR_BAD_FORMAT: + case ERROR_INVALID_SEGMENT_NUMBER: + case ERROR_INVALID_ORDINAL: + case ERROR_INVALID_MODULETYPE: + case ERROR_INVALID_EXE_SIGNATURE: + case ERROR_EXE_MARKED_INVALID: + case ERROR_ITERATED_DATA_EXCEEDS_64K: + case ERROR_INVALID_MINALLOCSIZE: + case ERROR_INVALID_SEGDPL: + case ERROR_AUTODATASEG_EXCEEDS_64K: + case ERROR_RELOCSRC_CHAIN_EXCEEDS_SEGLIMIT: + errtxt = "invalid module format"; + break; + case ERROR_INVALID_NAME: + errtxt = "filename doesn't match module name"; + break; + case ERROR_SHARING_VIOLATION: + case ERROR_LOCK_VIOLATION: + errtxt = "sharing violation"; + break; + case ERROR_INIT_ROUTINE_FAILED: + errtxt = "module initialization failed"; + break; + default: + errtxt = "cause `%s', error code = %d"; + break; + } + snprintf(dlerr, sizeof(dlerr), errtxt, &err, rc); + if (tmp) + { + if (tmp->name) + free(tmp->name); + free(tmp); + } + return 0; } /* return a pointer to the `symbol' in DLL */ void *dlsym(void *handle, char *symbol) { - int rc = 0; - PFN addr; - char *errtxt; - int symord = 0; - DLLchain tmp = find_id(handle); - - if (!tmp) - goto inv_handle; - - if (*symbol == '#') - symord = atoi(symbol + 1); - - switch (rc = DosQueryProcAddr(tmp->handle, symord, symbol, &addr)) - { - case NO_ERROR: - return (void *)addr; - case ERROR_INVALID_HANDLE: + int rc = 0; + PFN addr; + char *errtxt; + int symord = 0; + DLLchain tmp = find_id(handle); + + if (!tmp) + goto inv_handle; + + if (*symbol == '#') + symord = atoi(symbol + 1); + + switch (rc = DosQueryProcAddr(tmp->handle, symord, symbol, &addr)) + { + case NO_ERROR: + return (void *)addr; + case ERROR_INVALID_HANDLE: inv_handle: - errtxt = "invalid module handle"; - break; - case ERROR_PROC_NOT_FOUND: - case ERROR_INVALID_NAME: - errtxt = "no symbol `%s' in module"; - break; - default: - errtxt = "symbol `%s', error code = %d"; - break; - } - snprintf(dlerr, sizeof(dlerr), errtxt, symbol, rc); - return NULL; + errtxt = "invalid module handle"; + break; + case ERROR_PROC_NOT_FOUND: + case ERROR_INVALID_NAME: + errtxt = "no symbol `%s' in module"; + break; + default: + errtxt = "symbol `%s', error code = %d"; + break; + } + snprintf(dlerr, sizeof(dlerr), errtxt, symbol, rc); + return NULL; } /* free dynamicaly-linked library */ int dlclose(void *handle) { - int rc; - DLLchain tmp = find_id(handle); + int rc; + DLLchain tmp = find_id(handle); - if (!tmp) - goto inv_handle; + if (!tmp) + goto inv_handle; - switch (rc = DosFreeModule(tmp->handle)) - { - case NO_ERROR: - free(tmp->name); - dlload = tmp->next; - free(tmp); - return 0; - case ERROR_INVALID_HANDLE: + switch (rc = DosFreeModule(tmp->handle)) + { + case NO_ERROR: + free(tmp->name); + dlload = tmp->next; + free(tmp); + return 0; + case ERROR_INVALID_HANDLE: inv_handle: - strcpy(dlerr, "invalid module handle"); - return -1; - case ERROR_INVALID_ACCESS: - strcpy(dlerr, "access denied"); - return -1; - default: - return -1; - } + strcpy(dlerr, "invalid module handle"); + return -1; + case ERROR_INVALID_ACCESS: + strcpy(dlerr, "access denied"); + return -1; + default: + return -1; + } } /* return a string describing last occurred dl error */ char *dlerror() { - return dlerr; + return dlerr; } Modified: python/branches/py3k-jit/PC/os2emx/dllentry.c ============================================================================== --- python/branches/py3k-jit/PC/os2emx/dllentry.c (original) +++ python/branches/py3k-jit/PC/os2emx/dllentry.c Mon May 10 23:55:43 2010 @@ -4,7 +4,7 @@ #define NULL 0 -#define REF(s) extern void s(); void *____ref_##s = &s; +#define REF(s) extern void s(); void *____ref_##s = &s; /* Make references to imported symbols to pull them from static library */ REF(Py_Main); @@ -18,25 +18,25 @@ unsigned long _DLL_InitTerm(unsigned long mod_handle, unsigned long flag) { - switch (flag) - { - case 0: - if (_CRT_init()) - return 0; - __ctordtorInit(); - - /* Ignore fatal signals */ - signal(SIGSEGV, SIG_IGN); - signal(SIGFPE, SIG_IGN); - - return 1; - - case 1: - __ctordtorTerm(); - _CRT_term(); - return 1; - - default: - return 0; - } + switch (flag) + { + case 0: + if (_CRT_init()) + return 0; + __ctordtorInit(); + + /* Ignore fatal signals */ + signal(SIGSEGV, SIG_IGN); + signal(SIGFPE, SIG_IGN); + + return 1; + + case 1: + __ctordtorTerm(); + _CRT_term(); + return 1; + + default: + return 0; + } } Modified: python/branches/py3k-jit/PC/os2emx/getpathp.c ============================================================================== --- python/branches/py3k-jit/PC/os2emx/getpathp.c (original) +++ python/branches/py3k-jit/PC/os2emx/getpathp.c Mon May 10 23:55:43 2010 @@ -4,8 +4,8 @@ /* ---------------------------------------------------------------- PATH RULES FOR OS/2+EMX: - This describes how sys.path is formed on OS/2+EMX. It describes the - functionality, not the implementation (ie, the order in which these + This describes how sys.path is formed on OS/2+EMX. It describes the + functionality, not the implementation (ie, the order in which these are actually fetched is different) * Python always adds an empty entry at the start, which corresponds @@ -16,10 +16,10 @@ * We attempt to locate the "Python Home" - if the PYTHONHOME env var is set, we believe it. Otherwise, we use the path of our host .EXE's to try and locate our "landmark" (lib\\os.py) and deduce our home. - - If we DO have a Python Home: The relevant sub-directories (Lib, + - If we DO have a Python Home: The relevant sub-directories (Lib, plat-win, etc) are based on the Python Home - If we DO NOT have a Python Home, the core Python Path is - loaded from the registry. This is the main PythonPath key, + loaded from the registry. This is the main PythonPath key, and both HKLM and HKCU are combined to form the path) * Iff - we can not locate the Python Home, and have not had a PYTHONPATH @@ -32,9 +32,9 @@ (either an installed version, or directly from the PCbuild directory), the core path is deduced. - * When Python is hosted in another exe (different directory, embedded via + * When Python is hosted in another exe (different directory, embedded via COM, etc), the Python Home will not be deduced, so the core path from - the registry is used. Other "application paths "in the registry are + the registry is used. Other "application paths "in the registry are always read. * If Python can't find its home and there is no registry (eg, frozen @@ -85,12 +85,12 @@ static int -is_sep(char ch) /* determine if "ch" is a separator character */ +is_sep(char ch) /* determine if "ch" is a separator character */ { #ifdef ALTSEP - return ch == SEP || ch == ALTSEP; + return ch == SEP || ch == ALTSEP; #else - return ch == SEP; + return ch == SEP; #endif } @@ -100,36 +100,36 @@ static void reduce(char *dir) { - size_t i = strlen(dir); - while (i > 0 && !is_sep(dir[i])) - --i; - dir[i] = '\0'; + size_t i = strlen(dir); + while (i > 0 && !is_sep(dir[i])) + --i; + dir[i] = '\0'; } - + static int exists(char *filename) { - struct stat buf; - return stat(filename, &buf) == 0; + struct stat buf; + return stat(filename, &buf) == 0; } /* Is module (check for .pyc/.pyo too) - * Assumes 'filename' MAXPATHLEN+1 bytes long - + * Assumes 'filename' MAXPATHLEN+1 bytes long - * may extend 'filename' by one character. */ static int ismodule(char *filename) { - if (exists(filename)) - return 1; + if (exists(filename)) + return 1; - /* Check for the compiled version of prefix. */ - if (strlen(filename) < MAXPATHLEN) { - strcat(filename, Py_OptimizeFlag ? "o" : "c"); - if (exists(filename)) - return 1; - } - return 0; + /* Check for the compiled version of prefix. */ + if (strlen(filename) < MAXPATHLEN) { + strcat(filename, Py_OptimizeFlag ? "o" : "c"); + if (exists(filename)) + return 1; + } + return 0; } /* Add a path component, by appending stuff to buffer. @@ -145,21 +145,21 @@ static void join(char *buffer, char *stuff) { - size_t n, k; - if (is_sep(stuff[0])) - n = 0; - else { - n = strlen(buffer); - if (n > 0 && !is_sep(buffer[n-1]) && n < MAXPATHLEN) - buffer[n++] = SEP; - } - if (n > MAXPATHLEN) - Py_FatalError("buffer overflow in getpathp.c's joinpath()"); - k = strlen(stuff); - if (n + k > MAXPATHLEN) - k = MAXPATHLEN - n; - strncpy(buffer+n, stuff, k); - buffer[n+k] = '\0'; + size_t n, k; + if (is_sep(stuff[0])) + n = 0; + else { + n = strlen(buffer); + if (n > 0 && !is_sep(buffer[n-1]) && n < MAXPATHLEN) + buffer[n++] = SEP; + } + if (n > MAXPATHLEN) + Py_FatalError("buffer overflow in getpathp.c's joinpath()"); + k = strlen(stuff); + if (n + k > MAXPATHLEN) + k = MAXPATHLEN - n; + strncpy(buffer+n, stuff, k); + buffer[n+k] = '\0'; } /* gotlandmark only called by search_for_prefix, which ensures @@ -169,219 +169,219 @@ static int gotlandmark(char *landmark) { - int n, ok; + int n, ok; - n = strlen(prefix); - join(prefix, landmark); - ok = ismodule(prefix); - prefix[n] = '\0'; - return ok; + n = strlen(prefix); + join(prefix, landmark); + ok = ismodule(prefix); + prefix[n] = '\0'; + return ok; } -/* assumes argv0_path is MAXPATHLEN+1 bytes long, already \0 term'd. +/* assumes argv0_path is MAXPATHLEN+1 bytes long, already \0 term'd. * assumption provided by only caller, calculate_path() */ static int search_for_prefix(char *argv0_path, char *landmark) { - /* Search from argv0_path, until landmark is found */ - strcpy(prefix, argv0_path); - do { - if (gotlandmark(landmark)) - return 1; - reduce(prefix); - } while (prefix[0]); - return 0; + /* Search from argv0_path, until landmark is found */ + strcpy(prefix, argv0_path); + do { + if (gotlandmark(landmark)) + return 1; + reduce(prefix); + } while (prefix[0]); + return 0; } static void get_progpath(void) { - extern char *Py_GetProgramName(void); - char *path = getenv("PATH"); - char *prog = Py_GetProgramName(); - - PPIB pib; - if ((DosGetInfoBlocks(NULL, &pib) == 0) && - (DosQueryModuleName(pib->pib_hmte, sizeof(progpath), progpath) == 0)) - return; - - if (prog == NULL || *prog == '\0') - prog = "python"; - - /* If there is no slash in the argv0 path, then we have to - * assume python is on the user's $PATH, since there's no - * other way to find a directory to start the search from. If - * $PATH isn't exported, you lose. - */ + extern char *Py_GetProgramName(void); + char *path = getenv("PATH"); + char *prog = Py_GetProgramName(); + + PPIB pib; + if ((DosGetInfoBlocks(NULL, &pib) == 0) && + (DosQueryModuleName(pib->pib_hmte, sizeof(progpath), progpath) == 0)) + return; + + if (prog == NULL || *prog == '\0') + prog = "python"; + + /* If there is no slash in the argv0 path, then we have to + * assume python is on the user's $PATH, since there's no + * other way to find a directory to start the search from. If + * $PATH isn't exported, you lose. + */ #ifdef ALTSEP - if (strchr(prog, SEP) || strchr(prog, ALTSEP)) + if (strchr(prog, SEP) || strchr(prog, ALTSEP)) #else - if (strchr(prog, SEP)) + if (strchr(prog, SEP)) #endif - strncpy(progpath, prog, MAXPATHLEN); - else if (path) { - while (1) { - char *delim = strchr(path, DELIM); - - if (delim) { - size_t len = delim - path; - /* ensure we can't overwrite buffer */ + strncpy(progpath, prog, MAXPATHLEN); + else if (path) { + while (1) { + char *delim = strchr(path, DELIM); + + if (delim) { + size_t len = delim - path; + /* ensure we can't overwrite buffer */ #if !defined(PYCC_GCC) - len = min(MAXPATHLEN,len); + len = min(MAXPATHLEN,len); #else - len = MAXPATHLEN < len ? MAXPATHLEN : len; + len = MAXPATHLEN < len ? MAXPATHLEN : len; #endif - strncpy(progpath, path, len); - *(progpath + len) = '\0'; - } - else - strncpy(progpath, path, MAXPATHLEN); - - /* join() is safe for MAXPATHLEN+1 size buffer */ - join(progpath, prog); - if (exists(progpath)) - break; - - if (!delim) { - progpath[0] = '\0'; - break; - } - path = delim + 1; - } - } - else - progpath[0] = '\0'; + strncpy(progpath, path, len); + *(progpath + len) = '\0'; + } + else + strncpy(progpath, path, MAXPATHLEN); + + /* join() is safe for MAXPATHLEN+1 size buffer */ + join(progpath, prog); + if (exists(progpath)) + break; + + if (!delim) { + progpath[0] = '\0'; + break; + } + path = delim + 1; + } + } + else + progpath[0] = '\0'; } static void calculate_path(void) { - char argv0_path[MAXPATHLEN+1]; - char *buf; - size_t bufsz; - char *pythonhome = Py_GetPythonHome(); - char *envpath = getenv("PYTHONPATH"); - char zip_path[MAXPATHLEN+1]; - size_t len; - - get_progpath(); - /* progpath guaranteed \0 terminated in MAXPATH+1 bytes. */ - strcpy(argv0_path, progpath); - reduce(argv0_path); - if (pythonhome == NULL || *pythonhome == '\0') { - if (search_for_prefix(argv0_path, LANDMARK)) - pythonhome = prefix; - else - pythonhome = NULL; - } - else - strncpy(prefix, pythonhome, MAXPATHLEN); - - if (envpath && *envpath == '\0') - envpath = NULL; - - /* Calculate zip archive path */ - strncpy(zip_path, progpath, MAXPATHLEN); - zip_path[MAXPATHLEN] = '\0'; - len = strlen(zip_path); - if (len > 4) { - zip_path[len-3] = 'z'; /* change ending to "zip" */ - zip_path[len-2] = 'i'; - zip_path[len-1] = 'p'; - } - else { - zip_path[0] = 0; - } - - /* We need to construct a path from the following parts. - * (1) the PYTHONPATH environment variable, if set; - * (2) the zip archive file path; - * (3) the PYTHONPATH config macro, with the leading "." - * of each component replaced with pythonhome, if set; - * (4) the directory containing the executable (argv0_path). - * The length calculation calculates #3 first. - */ - - /* Calculate size of return buffer */ - if (pythonhome != NULL) { - char *p; - bufsz = 1; - for (p = PYTHONPATH; *p; p++) { - if (*p == DELIM) - bufsz++; /* number of DELIM plus one */ - } - bufsz *= strlen(pythonhome); - } - else - bufsz = 0; - bufsz += strlen(PYTHONPATH) + 1; - bufsz += strlen(argv0_path) + 1; - bufsz += strlen(zip_path) + 1; - if (envpath != NULL) - bufsz += strlen(envpath) + 1; - - module_search_path = buf = malloc(bufsz); - if (buf == NULL) { - /* We can't exit, so print a warning and limp along */ - fprintf(stderr, "Can't malloc dynamic PYTHONPATH.\n"); - if (envpath) { - fprintf(stderr, "Using environment $PYTHONPATH.\n"); - module_search_path = envpath; - } - else { - fprintf(stderr, "Using default static path.\n"); - module_search_path = PYTHONPATH; - } - return; - } - - if (envpath) { - strcpy(buf, envpath); - buf = strchr(buf, '\0'); - *buf++ = DELIM; - } - if (zip_path[0]) { - strcpy(buf, zip_path); - buf = strchr(buf, '\0'); - *buf++ = DELIM; - } - - if (pythonhome == NULL) { - strcpy(buf, PYTHONPATH); - buf = strchr(buf, '\0'); - } - else { - char *p = PYTHONPATH; - char *q; - size_t n; - for (;;) { - q = strchr(p, DELIM); - if (q == NULL) - n = strlen(p); - else - n = q-p; - if (p[0] == '.' && is_sep(p[1])) { - strcpy(buf, pythonhome); - buf = strchr(buf, '\0'); - p++; - n--; - } - strncpy(buf, p, n); - buf += n; - if (q == NULL) - break; - *buf++ = DELIM; - p = q+1; - } - } - if (argv0_path) { - *buf++ = DELIM; - strcpy(buf, argv0_path); - buf = strchr(buf, '\0'); - } - *buf = '\0'; + char argv0_path[MAXPATHLEN+1]; + char *buf; + size_t bufsz; + char *pythonhome = Py_GetPythonHome(); + char *envpath = getenv("PYTHONPATH"); + char zip_path[MAXPATHLEN+1]; + size_t len; + + get_progpath(); + /* progpath guaranteed \0 terminated in MAXPATH+1 bytes. */ + strcpy(argv0_path, progpath); + reduce(argv0_path); + if (pythonhome == NULL || *pythonhome == '\0') { + if (search_for_prefix(argv0_path, LANDMARK)) + pythonhome = prefix; + else + pythonhome = NULL; + } + else + strncpy(prefix, pythonhome, MAXPATHLEN); + + if (envpath && *envpath == '\0') + envpath = NULL; + + /* Calculate zip archive path */ + strncpy(zip_path, progpath, MAXPATHLEN); + zip_path[MAXPATHLEN] = '\0'; + len = strlen(zip_path); + if (len > 4) { + zip_path[len-3] = 'z'; /* change ending to "zip" */ + zip_path[len-2] = 'i'; + zip_path[len-1] = 'p'; + } + else { + zip_path[0] = 0; + } + + /* We need to construct a path from the following parts. + * (1) the PYTHONPATH environment variable, if set; + * (2) the zip archive file path; + * (3) the PYTHONPATH config macro, with the leading "." + * of each component replaced with pythonhome, if set; + * (4) the directory containing the executable (argv0_path). + * The length calculation calculates #3 first. + */ + + /* Calculate size of return buffer */ + if (pythonhome != NULL) { + char *p; + bufsz = 1; + for (p = PYTHONPATH; *p; p++) { + if (*p == DELIM) + bufsz++; /* number of DELIM plus one */ + } + bufsz *= strlen(pythonhome); + } + else + bufsz = 0; + bufsz += strlen(PYTHONPATH) + 1; + bufsz += strlen(argv0_path) + 1; + bufsz += strlen(zip_path) + 1; + if (envpath != NULL) + bufsz += strlen(envpath) + 1; + + module_search_path = buf = malloc(bufsz); + if (buf == NULL) { + /* We can't exit, so print a warning and limp along */ + fprintf(stderr, "Can't malloc dynamic PYTHONPATH.\n"); + if (envpath) { + fprintf(stderr, "Using environment $PYTHONPATH.\n"); + module_search_path = envpath; + } + else { + fprintf(stderr, "Using default static path.\n"); + module_search_path = PYTHONPATH; + } + return; + } + + if (envpath) { + strcpy(buf, envpath); + buf = strchr(buf, '\0'); + *buf++ = DELIM; + } + if (zip_path[0]) { + strcpy(buf, zip_path); + buf = strchr(buf, '\0'); + *buf++ = DELIM; + } + + if (pythonhome == NULL) { + strcpy(buf, PYTHONPATH); + buf = strchr(buf, '\0'); + } + else { + char *p = PYTHONPATH; + char *q; + size_t n; + for (;;) { + q = strchr(p, DELIM); + if (q == NULL) + n = strlen(p); + else + n = q-p; + if (p[0] == '.' && is_sep(p[1])) { + strcpy(buf, pythonhome); + buf = strchr(buf, '\0'); + p++; + n--; + } + strncpy(buf, p, n); + buf += n; + if (q == NULL) + break; + *buf++ = DELIM; + p = q+1; + } + } + if (argv0_path) { + *buf++ = DELIM; + strcpy(buf, argv0_path); + buf = strchr(buf, '\0'); + } + *buf = '\0'; } @@ -390,29 +390,29 @@ char * Py_GetPath(void) { - if (!module_search_path) - calculate_path(); - return module_search_path; + if (!module_search_path) + calculate_path(); + return module_search_path; } char * Py_GetPrefix(void) { - if (!module_search_path) - calculate_path(); - return prefix; + if (!module_search_path) + calculate_path(); + return prefix; } char * Py_GetExecPrefix(void) { - return Py_GetPrefix(); + return Py_GetPrefix(); } char * Py_GetProgramFullPath(void) { - if (!module_search_path) - calculate_path(); - return progpath; + if (!module_search_path) + calculate_path(); + return progpath; } Modified: python/branches/py3k-jit/PC/os2emx/pythonpm.c ============================================================================== --- python/branches/py3k-jit/PC/os2emx/pythonpm.c (original) +++ python/branches/py3k-jit/PC/os2emx/pythonpm.c Mon May 10 23:55:43 2010 @@ -27,10 +27,10 @@ /* use structure to pass command line to Python thread */ typedef struct { - int argc; - char **argv; - HWND Frame; - int running; + int argc; + char **argv; + HWND Frame; + int running; } arglist; /* make this a global to simplify access. @@ -45,80 +45,80 @@ int main(int argc, char **argv) { - ULONG FrameFlags = FCF_TITLEBAR | - FCF_SYSMENU | - FCF_SIZEBORDER | - FCF_HIDEBUTTON | - FCF_SHELLPOSITION | - FCF_TASKLIST; - HAB hab; - HMQ hmq; - HWND Client; - QMSG qmsg; - arglist args; - int python_tid; - - /* init PM and create message queue */ - hab = WinInitialize(0); - hmq = WinCreateMsgQueue(hab, 0); - - /* create a (hidden) Window to house the window procedure */ - args.Frame = WinCreateStdWindow(HWND_DESKTOP, - 0, - &FrameFlags, - NULL, - "PythonPM", - 0L, - 0, - 0, - &Client); - - /* run Python interpreter in a thread */ - args.argc = argc; - args.argv = argv; - args.running = 0; - if (-1 == (python_tid = _beginthread(PythonThread, NULL, 1024 * 1024, &args))) - { - /* couldn't start thread */ - WinAlarm(HWND_DESKTOP, WA_ERROR); - PythonRC = 1; - } - else - { - /* process PM messages, until Python exits */ - while (WinGetMsg(hab, &qmsg, NULLHANDLE, 0, 0)) - WinDispatchMsg(hab, &qmsg); - if (args.running > 0) - DosKillThread(python_tid); - } - - /* destroy window, shutdown message queue and PM */ - WinDestroyWindow(args.Frame); - WinDestroyMsgQueue(hmq); - WinTerminate(hab); + ULONG FrameFlags = FCF_TITLEBAR | + FCF_SYSMENU | + FCF_SIZEBORDER | + FCF_HIDEBUTTON | + FCF_SHELLPOSITION | + FCF_TASKLIST; + HAB hab; + HMQ hmq; + HWND Client; + QMSG qmsg; + arglist args; + int python_tid; + + /* init PM and create message queue */ + hab = WinInitialize(0); + hmq = WinCreateMsgQueue(hab, 0); + + /* create a (hidden) Window to house the window procedure */ + args.Frame = WinCreateStdWindow(HWND_DESKTOP, + 0, + &FrameFlags, + NULL, + "PythonPM", + 0L, + 0, + 0, + &Client); + + /* run Python interpreter in a thread */ + args.argc = argc; + args.argv = argv; + args.running = 0; + if (-1 == (python_tid = _beginthread(PythonThread, NULL, 1024 * 1024, &args))) + { + /* couldn't start thread */ + WinAlarm(HWND_DESKTOP, WA_ERROR); + PythonRC = 1; + } + else + { + /* process PM messages, until Python exits */ + while (WinGetMsg(hab, &qmsg, NULLHANDLE, 0, 0)) + WinDispatchMsg(hab, &qmsg); + if (args.running > 0) + DosKillThread(python_tid); + } + + /* destroy window, shutdown message queue and PM */ + WinDestroyWindow(args.Frame); + WinDestroyMsgQueue(hmq); + WinTerminate(hab); - return PythonRC; + return PythonRC; } void PythonThread(void *argl) { - HAB hab; - arglist *args; + HAB hab; + arglist *args; - /* PM initialisation */ - hab = WinInitialize(0); + /* PM initialisation */ + hab = WinInitialize(0); - /* start Python */ - args = (arglist *)argl; - args->running = 1; - PythonRC = Py_Main(args->argc, args->argv); - - /* enter a critical section and send the termination message */ - DosEnterCritSec(); - args->running = 0; - WinPostMsg(args->Frame, WM_QUIT, NULL, NULL); - - /* shutdown PM and terminate thread */ - WinTerminate(hab); - _endthread(); + /* start Python */ + args = (arglist *)argl; + args->running = 1; + PythonRC = Py_Main(args->argc, args->argv); + + /* enter a critical section and send the termination message */ + DosEnterCritSec(); + args->running = 0; + WinPostMsg(args->Frame, WM_QUIT, NULL, NULL); + + /* shutdown PM and terminate thread */ + WinTerminate(hab); + _endthread(); } Modified: python/branches/py3k-jit/PC/os2vacpp/getpathp.c ============================================================================== --- python/branches/py3k-jit/PC/os2vacpp/getpathp.c (original) +++ python/branches/py3k-jit/PC/os2vacpp/getpathp.c Mon May 10 23:55:43 2010 @@ -55,12 +55,12 @@ static int -is_sep(char ch) /* determine if "ch" is a separator character */ +is_sep(char ch) /* determine if "ch" is a separator character */ { #ifdef ALTSEP - return ch == SEP || ch == ALTSEP; + return ch == SEP || ch == ALTSEP; #else - return ch == SEP; + return ch == SEP; #endif } @@ -68,18 +68,18 @@ static void reduce(char *dir) { - int i = strlen(dir); - while (i > 0 && !is_sep(dir[i])) - --i; - dir[i] = '\0'; + int i = strlen(dir); + while (i > 0 && !is_sep(dir[i])) + --i; + dir[i] = '\0'; } - + static int exists(char *filename) { - struct stat buf; - return stat(filename, &buf) == 0; + struct stat buf; + return stat(filename, &buf) == 0; } @@ -95,42 +95,42 @@ static void join(char *buffer, char *stuff) { - int n, k; - if (is_sep(stuff[0])) - n = 0; - else { - n = strlen(buffer); - if (n > 0 && !is_sep(buffer[n-1]) && n < MAXPATHLEN) - buffer[n++] = SEP; - } - if (n > MAXPATHLEN) - Py_FatalError("buffer overflow in getpathp.c's joinpath()"); - k = strlen(stuff); - if (n + k > MAXPATHLEN) - k = MAXPATHLEN - n; - strncpy(buffer+n, stuff, k); - buffer[n+k] = '\0'; + int n, k; + if (is_sep(stuff[0])) + n = 0; + else { + n = strlen(buffer); + if (n > 0 && !is_sep(buffer[n-1]) && n < MAXPATHLEN) + buffer[n++] = SEP; + } + if (n > MAXPATHLEN) + Py_FatalError("buffer overflow in getpathp.c's joinpath()"); + k = strlen(stuff); + if (n + k > MAXPATHLEN) + k = MAXPATHLEN - n; + strncpy(buffer+n, stuff, k); + buffer[n+k] = '\0'; } static int search_for_prefix(char *argv0_path, char *landmark) { - int n; + int n; - /* Search from argv0_path, until root is found */ - strcpy(prefix, argv0_path); - do { - n = strlen(prefix); - join(prefix, landmark); - if (exists(prefix)) { - prefix[n] = '\0'; - return 1; - } - prefix[n] = '\0'; - reduce(prefix); - } while (prefix[0]); - return 0; + /* Search from argv0_path, until root is found */ + strcpy(prefix, argv0_path); + do { + n = strlen(prefix); + join(prefix, landmark); + if (exists(prefix)) { + prefix[n] = '\0'; + return 1; + } + prefix[n] = '\0'; + reduce(prefix); + } while (prefix[0]); + return 0; } #ifdef MS_WIN32 @@ -147,299 +147,299 @@ static char * getpythonregpath(HKEY keyBase, BOOL bWin32s) { - HKEY newKey = 0; - DWORD nameSize = 0; - DWORD dataSize = 0; - DWORD numEntries = 0; - LONG rc; - char *retval = NULL; - char *dataBuf; - const char keyPrefix[] = "Software\\Python\\PythonCore\\"; - const char keySuffix[] = "\\PythonPath"; - int versionLen; - char *keyBuf; - - // Tried to use sysget("winver") but here is too early :-( - versionLen = strlen(PyWin_DLLVersionString); - // alloca == no free required, but memory only local to fn. - // also no heap fragmentation! Am I being silly? - keyBuf = alloca(sizeof(keyPrefix)-1 + versionLen + sizeof(keySuffix)); // chars only, plus 1 NULL. - // lots of constants here for the compiler to optimize away :-) - memcpy(keyBuf, keyPrefix, sizeof(keyPrefix)-1); - memcpy(keyBuf+sizeof(keyPrefix)-1, PyWin_DLLVersionString, versionLen); - memcpy(keyBuf+sizeof(keyPrefix)-1+versionLen, keySuffix, sizeof(keySuffix)); // NULL comes with this one! - - rc=RegOpenKey(keyBase, - keyBuf, - &newKey); - if (rc==ERROR_SUCCESS) { - RegQueryInfoKey(newKey, NULL, NULL, NULL, NULL, NULL, NULL, - &numEntries, &nameSize, &dataSize, NULL, NULL); - } - if (bWin32s && numEntries==0 && dataSize==0) { - /* must hardcode for Win32s */ - numEntries = 1; - dataSize = 511; - } - if (numEntries) { - /* Loop over all subkeys. */ - /* Win32s doesnt know how many subkeys, so we do - it twice */ - char keyBuf[MAX_PATH+1]; - int index = 0; - int off = 0; - for(index=0;;index++) { - long reqdSize = 0; - DWORD rc = RegEnumKey(newKey, - index, keyBuf, MAX_PATH+1); - if (rc) break; - rc = RegQueryValue(newKey, keyBuf, NULL, &reqdSize); - if (rc) break; - if (bWin32s && reqdSize==0) reqdSize = 512; - dataSize += reqdSize + 1; /* 1 for the ";" */ - } - dataBuf = malloc(dataSize+1); - if (dataBuf==NULL) - return NULL; /* pretty serious? Raise error? */ - /* Now loop over, grabbing the paths. - Subkeys before main library */ - for(index=0;;index++) { - int adjust; - long reqdSize = dataSize; - DWORD rc = RegEnumKey(newKey, - index, keyBuf,MAX_PATH+1); - if (rc) break; - rc = RegQueryValue(newKey, - keyBuf, dataBuf+off, &reqdSize); - if (rc) break; - if (reqdSize>1) { - /* If Nothing, or only '\0' copied. */ - adjust = strlen(dataBuf+off); - dataSize -= adjust; - off += adjust; - dataBuf[off++] = ';'; - dataBuf[off] = '\0'; - dataSize--; - } - } - /* Additionally, win32s doesnt work as expected, so - the specific strlen() is required for 3.1. */ - rc = RegQueryValue(newKey, "", dataBuf+off, &dataSize); - if (rc==ERROR_SUCCESS) { - if (strlen(dataBuf)==0) - free(dataBuf); - else - retval = dataBuf; /* caller will free */ - } - else - free(dataBuf); - } - - if (newKey) - RegCloseKey(newKey); - return retval; + HKEY newKey = 0; + DWORD nameSize = 0; + DWORD dataSize = 0; + DWORD numEntries = 0; + LONG rc; + char *retval = NULL; + char *dataBuf; + const char keyPrefix[] = "Software\\Python\\PythonCore\\"; + const char keySuffix[] = "\\PythonPath"; + int versionLen; + char *keyBuf; + + // Tried to use sysget("winver") but here is too early :-( + versionLen = strlen(PyWin_DLLVersionString); + // alloca == no free required, but memory only local to fn. + // also no heap fragmentation! Am I being silly? + keyBuf = alloca(sizeof(keyPrefix)-1 + versionLen + sizeof(keySuffix)); // chars only, plus 1 NULL. + // lots of constants here for the compiler to optimize away :-) + memcpy(keyBuf, keyPrefix, sizeof(keyPrefix)-1); + memcpy(keyBuf+sizeof(keyPrefix)-1, PyWin_DLLVersionString, versionLen); + memcpy(keyBuf+sizeof(keyPrefix)-1+versionLen, keySuffix, sizeof(keySuffix)); // NULL comes with this one! + + rc=RegOpenKey(keyBase, + keyBuf, + &newKey); + if (rc==ERROR_SUCCESS) { + RegQueryInfoKey(newKey, NULL, NULL, NULL, NULL, NULL, NULL, + &numEntries, &nameSize, &dataSize, NULL, NULL); + } + if (bWin32s && numEntries==0 && dataSize==0) { + /* must hardcode for Win32s */ + numEntries = 1; + dataSize = 511; + } + if (numEntries) { + /* Loop over all subkeys. */ + /* Win32s doesnt know how many subkeys, so we do + it twice */ + char keyBuf[MAX_PATH+1]; + int index = 0; + int off = 0; + for(index=0;;index++) { + long reqdSize = 0; + DWORD rc = RegEnumKey(newKey, + index, keyBuf, MAX_PATH+1); + if (rc) break; + rc = RegQueryValue(newKey, keyBuf, NULL, &reqdSize); + if (rc) break; + if (bWin32s && reqdSize==0) reqdSize = 512; + dataSize += reqdSize + 1; /* 1 for the ";" */ + } + dataBuf = malloc(dataSize+1); + if (dataBuf==NULL) + return NULL; /* pretty serious? Raise error? */ + /* Now loop over, grabbing the paths. + Subkeys before main library */ + for(index=0;;index++) { + int adjust; + long reqdSize = dataSize; + DWORD rc = RegEnumKey(newKey, + index, keyBuf,MAX_PATH+1); + if (rc) break; + rc = RegQueryValue(newKey, + keyBuf, dataBuf+off, &reqdSize); + if (rc) break; + if (reqdSize>1) { + /* If Nothing, or only '\0' copied. */ + adjust = strlen(dataBuf+off); + dataSize -= adjust; + off += adjust; + dataBuf[off++] = ';'; + dataBuf[off] = '\0'; + dataSize--; + } + } + /* Additionally, win32s doesnt work as expected, so + the specific strlen() is required for 3.1. */ + rc = RegQueryValue(newKey, "", dataBuf+off, &dataSize); + if (rc==ERROR_SUCCESS) { + if (strlen(dataBuf)==0) + free(dataBuf); + else + retval = dataBuf; /* caller will free */ + } + else + free(dataBuf); + } + + if (newKey) + RegCloseKey(newKey); + return retval; } #endif /* MS_WIN32 */ static void get_progpath(void) { - extern char *Py_GetProgramName(void); - char *path = getenv("PATH"); - char *prog = Py_GetProgramName(); + extern char *Py_GetProgramName(void); + char *path = getenv("PATH"); + char *prog = Py_GetProgramName(); #ifdef MS_WIN32 - if (GetModuleFileName(NULL, progpath, MAXPATHLEN)) - return; + if (GetModuleFileName(NULL, progpath, MAXPATHLEN)) + return; #endif - if (prog == NULL || *prog == '\0') - prog = "python"; + if (prog == NULL || *prog == '\0') + prog = "python"; - /* If there is no slash in the argv0 path, then we have to - * assume python is on the user's $PATH, since there's no - * other way to find a directory to start the search from. If - * $PATH isn't exported, you lose. - */ + /* If there is no slash in the argv0 path, then we have to + * assume python is on the user's $PATH, since there's no + * other way to find a directory to start the search from. If + * $PATH isn't exported, you lose. + */ #ifdef ALTSEP - if (strchr(prog, SEP) || strchr(prog, ALTSEP)) + if (strchr(prog, SEP) || strchr(prog, ALTSEP)) #else - if (strchr(prog, SEP)) + if (strchr(prog, SEP)) #endif - strcpy(progpath, prog); - else if (path) { - while (1) { - char *delim = strchr(path, DELIM); - - if (delim) { - int len = delim - path; - strncpy(progpath, path, len); - *(progpath + len) = '\0'; - } - else - strcpy(progpath, path); - - join(progpath, prog); - if (exists(progpath)) - break; - - if (!delim) { - progpath[0] = '\0'; - break; - } - path = delim + 1; - } - } - else - progpath[0] = '\0'; + strcpy(progpath, prog); + else if (path) { + while (1) { + char *delim = strchr(path, DELIM); + + if (delim) { + int len = delim - path; + strncpy(progpath, path, len); + *(progpath + len) = '\0'; + } + else + strcpy(progpath, path); + + join(progpath, prog); + if (exists(progpath)) + break; + + if (!delim) { + progpath[0] = '\0'; + break; + } + path = delim + 1; + } + } + else + progpath[0] = '\0'; } static void calculate_path(void) { - char argv0_path[MAXPATHLEN+1]; - char *buf; - int bufsz; - char *pythonhome = Py_GetPythonHome(); - char *envpath = Py_GETENV("PYTHONPATH"); + char argv0_path[MAXPATHLEN+1]; + char *buf; + int bufsz; + char *pythonhome = Py_GetPythonHome(); + char *envpath = Py_GETENV("PYTHONPATH"); #ifdef MS_WIN32 - char *machinepath, *userpath; + char *machinepath, *userpath; - /* Are we running under Windows 3.1(1) Win32s? */ - if (PyWin_IsWin32s()) { - /* Only CLASSES_ROOT is supported */ - machinepath = getpythonregpath(HKEY_CLASSES_ROOT, TRUE); - userpath = NULL; - } else { - machinepath = getpythonregpath(HKEY_LOCAL_MACHINE, FALSE); - userpath = getpythonregpath(HKEY_CURRENT_USER, FALSE); - } + /* Are we running under Windows 3.1(1) Win32s? */ + if (PyWin_IsWin32s()) { + /* Only CLASSES_ROOT is supported */ + machinepath = getpythonregpath(HKEY_CLASSES_ROOT, TRUE); + userpath = NULL; + } else { + machinepath = getpythonregpath(HKEY_LOCAL_MACHINE, FALSE); + userpath = getpythonregpath(HKEY_CURRENT_USER, FALSE); + } #endif - get_progpath(); - strcpy(argv0_path, progpath); - reduce(argv0_path); - if (pythonhome == NULL || *pythonhome == '\0') { - if (search_for_prefix(argv0_path, LANDMARK)) - pythonhome = prefix; - else - pythonhome = NULL; - } - else { - char *delim; - - strcpy(prefix, pythonhome); - - /* Extract Any Optional Trailing EXEC_PREFIX */ - /* e.g. PYTHONHOME=: */ - delim = strchr(prefix, DELIM); - if (delim) { - *delim = '\0'; - strcpy(exec_prefix, delim+1); - } else - strcpy(exec_prefix, EXEC_PREFIX); - } - - if (envpath && *envpath == '\0') - envpath = NULL; - - /* We need to construct a path from the following parts: - (1) the PYTHONPATH environment variable, if set; - (2) for Win32, the machinepath and userpath, if set; - (3) the PYTHONPATH config macro, with the leading "." - of each component replaced with pythonhome, if set; - (4) the directory containing the executable (argv0_path). - The length calculation calculates #3 first. - */ - - /* Calculate size of return buffer */ - if (pythonhome != NULL) { - char *p; - bufsz = 1; - for (p = PYTHONPATH; *p; p++) { - if (*p == DELIM) - bufsz++; /* number of DELIM plus one */ - } - bufsz *= strlen(pythonhome); - } - else - bufsz = 0; - bufsz += strlen(PYTHONPATH) + 1; - if (envpath != NULL) - bufsz += strlen(envpath) + 1; - bufsz += strlen(argv0_path) + 1; + get_progpath(); + strcpy(argv0_path, progpath); + reduce(argv0_path); + if (pythonhome == NULL || *pythonhome == '\0') { + if (search_for_prefix(argv0_path, LANDMARK)) + pythonhome = prefix; + else + pythonhome = NULL; + } + else { + char *delim; + + strcpy(prefix, pythonhome); + + /* Extract Any Optional Trailing EXEC_PREFIX */ + /* e.g. PYTHONHOME=: */ + delim = strchr(prefix, DELIM); + if (delim) { + *delim = '\0'; + strcpy(exec_prefix, delim+1); + } else + strcpy(exec_prefix, EXEC_PREFIX); + } + + if (envpath && *envpath == '\0') + envpath = NULL; + + /* We need to construct a path from the following parts: + (1) the PYTHONPATH environment variable, if set; + (2) for Win32, the machinepath and userpath, if set; + (3) the PYTHONPATH config macro, with the leading "." + of each component replaced with pythonhome, if set; + (4) the directory containing the executable (argv0_path). + The length calculation calculates #3 first. + */ + + /* Calculate size of return buffer */ + if (pythonhome != NULL) { + char *p; + bufsz = 1; + for (p = PYTHONPATH; *p; p++) { + if (*p == DELIM) + bufsz++; /* number of DELIM plus one */ + } + bufsz *= strlen(pythonhome); + } + else + bufsz = 0; + bufsz += strlen(PYTHONPATH) + 1; + if (envpath != NULL) + bufsz += strlen(envpath) + 1; + bufsz += strlen(argv0_path) + 1; #ifdef MS_WIN32 - if (machinepath) - bufsz += strlen(machinepath) + 1; - if (userpath) - bufsz += strlen(userpath) + 1; + if (machinepath) + bufsz += strlen(machinepath) + 1; + if (userpath) + bufsz += strlen(userpath) + 1; #endif - module_search_path = buf = malloc(bufsz); - if (buf == NULL) { - /* We can't exit, so print a warning and limp along */ - fprintf(stderr, "Can't malloc dynamic PYTHONPATH.\n"); - if (envpath) { - fprintf(stderr, "Using default static $PYTHONPATH.\n"); - module_search_path = envpath; - } - else { - fprintf(stderr, "Using environment $PYTHONPATH.\n"); - module_search_path = PYTHONPATH; - } - return; - } - - if (envpath) { - strcpy(buf, envpath); - buf = strchr(buf, '\0'); - *buf++ = DELIM; - } + module_search_path = buf = malloc(bufsz); + if (buf == NULL) { + /* We can't exit, so print a warning and limp along */ + fprintf(stderr, "Can't malloc dynamic PYTHONPATH.\n"); + if (envpath) { + fprintf(stderr, "Using default static $PYTHONPATH.\n"); + module_search_path = envpath; + } + else { + fprintf(stderr, "Using environment $PYTHONPATH.\n"); + module_search_path = PYTHONPATH; + } + return; + } + + if (envpath) { + strcpy(buf, envpath); + buf = strchr(buf, '\0'); + *buf++ = DELIM; + } #ifdef MS_WIN32 - if (machinepath) { - strcpy(buf, machinepath); - buf = strchr(buf, '\0'); - *buf++ = DELIM; - } - if (userpath) { - strcpy(buf, userpath); - buf = strchr(buf, '\0'); - *buf++ = DELIM; - } + if (machinepath) { + strcpy(buf, machinepath); + buf = strchr(buf, '\0'); + *buf++ = DELIM; + } + if (userpath) { + strcpy(buf, userpath); + buf = strchr(buf, '\0'); + *buf++ = DELIM; + } #endif - if (pythonhome == NULL) { - strcpy(buf, PYTHONPATH); - buf = strchr(buf, '\0'); - } - else { - char *p = PYTHONPATH; - char *q; - int n; - for (;;) { - q = strchr(p, DELIM); - if (q == NULL) - n = strlen(p); - else - n = q-p; - if (p[0] == '.' && is_sep(p[1])) { - strcpy(buf, pythonhome); - buf = strchr(buf, '\0'); - p++; - n--; - } - strncpy(buf, p, n); - buf += n; - if (q == NULL) - break; - *buf++ = DELIM; - p = q+1; - } - } - if (argv0_path) { - *buf++ = DELIM; - strcpy(buf, argv0_path); - buf = strchr(buf, '\0'); - } - *buf = '\0'; + if (pythonhome == NULL) { + strcpy(buf, PYTHONPATH); + buf = strchr(buf, '\0'); + } + else { + char *p = PYTHONPATH; + char *q; + int n; + for (;;) { + q = strchr(p, DELIM); + if (q == NULL) + n = strlen(p); + else + n = q-p; + if (p[0] == '.' && is_sep(p[1])) { + strcpy(buf, pythonhome); + buf = strchr(buf, '\0'); + p++; + n--; + } + strncpy(buf, p, n); + buf += n; + if (q == NULL) + break; + *buf++ = DELIM; + p = q+1; + } + } + if (argv0_path) { + *buf++ = DELIM; + strcpy(buf, argv0_path); + buf = strchr(buf, '\0'); + } + *buf = '\0'; } @@ -448,35 +448,35 @@ char * Py_GetPath(void) { - if (!module_search_path) - calculate_path(); + if (!module_search_path) + calculate_path(); - return module_search_path; + return module_search_path; } char * Py_GetPrefix(void) { - if (!module_search_path) - calculate_path(); + if (!module_search_path) + calculate_path(); - return prefix; + return prefix; } char * Py_GetExecPrefix(void) { - if (!module_search_path) - calculate_path(); + if (!module_search_path) + calculate_path(); - return exec_prefix; + return exec_prefix; } char * Py_GetProgramFullPath(void) { - if (!module_search_path) - calculate_path(); + if (!module_search_path) + calculate_path(); - return progpath; + return progpath; } Modified: python/branches/py3k-jit/PC/winreg.c ============================================================================== --- python/branches/py3k-jit/PC/winreg.c (original) +++ python/branches/py3k-jit/PC/winreg.c Mon May 10 23:55:43 2010 @@ -4,7 +4,7 @@ Windows Registry access module for Python. * Simple registry access written by Mark Hammond in win32api - module circa 1995. + module circa 1995. * Bill Tutt expanded the support significantly not long after. * Numerous other people have submitted patches since then. * Ripped from win32api module 03-Feb-2000 by Mark Hammond, and @@ -28,7 +28,7 @@ want to lose this info... */ #define PyErr_SetFromWindowsErrWithFunction(rc, fnname) \ - PyErr_SetFromWindowsErr(rc) + PyErr_SetFromWindowsErr(rc) /* Forward declares */ @@ -383,8 +383,8 @@ ************************************************************************/ typedef struct { - PyObject_VAR_HEAD - HKEY hkey; + PyObject_VAR_HEAD + HKEY hkey; } PyHKEYObject; #define PyHKEY_Check(op) ((op)->ob_type == &PyHKEY_Type) @@ -394,95 +394,95 @@ static PyObject * PyHKEY_unaryFailureFunc(PyObject *ob) { - PyErr_SetString(PyExc_TypeError, failMsg); - return NULL; + PyErr_SetString(PyExc_TypeError, failMsg); + return NULL; } static PyObject * PyHKEY_binaryFailureFunc(PyObject *ob1, PyObject *ob2) { - PyErr_SetString(PyExc_TypeError, failMsg); - return NULL; + PyErr_SetString(PyExc_TypeError, failMsg); + return NULL; } static PyObject * PyHKEY_ternaryFailureFunc(PyObject *ob1, PyObject *ob2, PyObject *ob3) { - PyErr_SetString(PyExc_TypeError, failMsg); - return NULL; + PyErr_SetString(PyExc_TypeError, failMsg); + return NULL; } static void PyHKEY_deallocFunc(PyObject *ob) { - /* Can not call PyHKEY_Close, as the ob->tp_type - has already been cleared, thus causing the type - check to fail! - */ - PyHKEYObject *obkey = (PyHKEYObject *)ob; - if (obkey->hkey) - RegCloseKey((HKEY)obkey->hkey); - PyObject_DEL(ob); + /* Can not call PyHKEY_Close, as the ob->tp_type + has already been cleared, thus causing the type + check to fail! + */ + PyHKEYObject *obkey = (PyHKEYObject *)ob; + if (obkey->hkey) + RegCloseKey((HKEY)obkey->hkey); + PyObject_DEL(ob); } static int PyHKEY_boolFunc(PyObject *ob) { - return ((PyHKEYObject *)ob)->hkey != 0; + return ((PyHKEYObject *)ob)->hkey != 0; } static PyObject * PyHKEY_intFunc(PyObject *ob) { - PyHKEYObject *pyhkey = (PyHKEYObject *)ob; - return PyLong_FromVoidPtr(pyhkey->hkey); + PyHKEYObject *pyhkey = (PyHKEYObject *)ob; + return PyLong_FromVoidPtr(pyhkey->hkey); } static PyObject * PyHKEY_strFunc(PyObject *ob) { - PyHKEYObject *pyhkey = (PyHKEYObject *)ob; - return PyUnicode_FromFormat("", pyhkey->hkey); + PyHKEYObject *pyhkey = (PyHKEYObject *)ob; + return PyUnicode_FromFormat("", pyhkey->hkey); } static int PyHKEY_compareFunc(PyObject *ob1, PyObject *ob2) { - PyHKEYObject *pyhkey1 = (PyHKEYObject *)ob1; - PyHKEYObject *pyhkey2 = (PyHKEYObject *)ob2; - return pyhkey1 == pyhkey2 ? 0 : - (pyhkey1 < pyhkey2 ? -1 : 1); + PyHKEYObject *pyhkey1 = (PyHKEYObject *)ob1; + PyHKEYObject *pyhkey2 = (PyHKEYObject *)ob2; + return pyhkey1 == pyhkey2 ? 0 : + (pyhkey1 < pyhkey2 ? -1 : 1); } static long PyHKEY_hashFunc(PyObject *ob) { - /* Just use the address. - XXX - should we use the handle value? - */ - return _Py_HashPointer(ob); + /* Just use the address. + XXX - should we use the handle value? + */ + return _Py_HashPointer(ob); } static PyNumberMethods PyHKEY_NumberMethods = { - PyHKEY_binaryFailureFunc, /* nb_add */ - PyHKEY_binaryFailureFunc, /* nb_subtract */ - PyHKEY_binaryFailureFunc, /* nb_multiply */ - PyHKEY_binaryFailureFunc, /* nb_remainder */ - PyHKEY_binaryFailureFunc, /* nb_divmod */ - PyHKEY_ternaryFailureFunc, /* nb_power */ - PyHKEY_unaryFailureFunc, /* nb_negative */ - PyHKEY_unaryFailureFunc, /* nb_positive */ - PyHKEY_unaryFailureFunc, /* nb_absolute */ - PyHKEY_boolFunc, /* nb_bool */ - PyHKEY_unaryFailureFunc, /* nb_invert */ - PyHKEY_binaryFailureFunc, /* nb_lshift */ - PyHKEY_binaryFailureFunc, /* nb_rshift */ - PyHKEY_binaryFailureFunc, /* nb_and */ - PyHKEY_binaryFailureFunc, /* nb_xor */ - PyHKEY_binaryFailureFunc, /* nb_or */ - PyHKEY_intFunc, /* nb_int */ - 0, /* nb_reserved */ - PyHKEY_unaryFailureFunc, /* nb_float */ + PyHKEY_binaryFailureFunc, /* nb_add */ + PyHKEY_binaryFailureFunc, /* nb_subtract */ + PyHKEY_binaryFailureFunc, /* nb_multiply */ + PyHKEY_binaryFailureFunc, /* nb_remainder */ + PyHKEY_binaryFailureFunc, /* nb_divmod */ + PyHKEY_ternaryFailureFunc, /* nb_power */ + PyHKEY_unaryFailureFunc, /* nb_negative */ + PyHKEY_unaryFailureFunc, /* nb_positive */ + PyHKEY_unaryFailureFunc, /* nb_absolute */ + PyHKEY_boolFunc, /* nb_bool */ + PyHKEY_unaryFailureFunc, /* nb_invert */ + PyHKEY_binaryFailureFunc, /* nb_lshift */ + PyHKEY_binaryFailureFunc, /* nb_rshift */ + PyHKEY_binaryFailureFunc, /* nb_and */ + PyHKEY_binaryFailureFunc, /* nb_xor */ + PyHKEY_binaryFailureFunc, /* nb_or */ + PyHKEY_intFunc, /* nb_int */ + 0, /* nb_reserved */ + PyHKEY_unaryFailureFunc, /* nb_float */ }; static PyObject *PyHKEY_CloseMethod(PyObject *self, PyObject *args); @@ -491,51 +491,51 @@ static PyObject *PyHKEY_Exit(PyObject *self, PyObject *args); static struct PyMethodDef PyHKEY_methods[] = { - {"Close", PyHKEY_CloseMethod, METH_VARARGS, PyHKEY_Close_doc}, - {"Detach", PyHKEY_DetachMethod, METH_VARARGS, PyHKEY_Detach_doc}, - {"__enter__", (PyCFunction)PyHKEY_Enter, METH_NOARGS, NULL}, - {"__exit__", PyHKEY_Exit, METH_VARARGS, NULL}, - {NULL} + {"Close", PyHKEY_CloseMethod, METH_VARARGS, PyHKEY_Close_doc}, + {"Detach", PyHKEY_DetachMethod, METH_VARARGS, PyHKEY_Detach_doc}, + {"__enter__", (PyCFunction)PyHKEY_Enter, METH_NOARGS, NULL}, + {"__exit__", PyHKEY_Exit, METH_VARARGS, NULL}, + {NULL} }; #define OFF(e) offsetof(PyHKEYObject, e) static PyMemberDef PyHKEY_memberlist[] = { - {"handle", T_INT, OFF(hkey), READONLY}, - {NULL} /* Sentinel */ + {"handle", T_INT, OFF(hkey), READONLY}, + {NULL} /* Sentinel */ }; /* The type itself */ PyTypeObject PyHKEY_Type = { - PyVarObject_HEAD_INIT(0, 0) /* fill in type at module init */ - "PyHKEY", - sizeof(PyHKEYObject), - 0, - PyHKEY_deallocFunc, /* tp_dealloc */ - 0, /* tp_print */ - 0, /* tp_getattr */ - 0, /* tp_setattr */ - 0, /* tp_reserved */ - 0, /* tp_repr */ - &PyHKEY_NumberMethods, /* tp_as_number */ - 0, /* tp_as_sequence */ - 0, /* tp_as_mapping */ - PyHKEY_hashFunc, /* tp_hash */ - 0, /* tp_call */ - PyHKEY_strFunc, /* tp_str */ - 0, /* tp_getattro */ - 0, /* tp_setattro */ - 0, /* tp_as_buffer */ - 0, /* tp_flags */ - PyHKEY_doc, /* tp_doc */ - 0, /*tp_traverse*/ - 0, /*tp_clear*/ - 0, /*tp_richcompare*/ - 0, /*tp_weaklistoffset*/ - 0, /*tp_iter*/ - 0, /*tp_iternext*/ - PyHKEY_methods, /*tp_methods*/ - PyHKEY_memberlist, /*tp_members*/ + PyVarObject_HEAD_INIT(0, 0) /* fill in type at module init */ + "PyHKEY", + sizeof(PyHKEYObject), + 0, + PyHKEY_deallocFunc, /* tp_dealloc */ + 0, /* tp_print */ + 0, /* tp_getattr */ + 0, /* tp_setattr */ + 0, /* tp_reserved */ + 0, /* tp_repr */ + &PyHKEY_NumberMethods, /* tp_as_number */ + 0, /* tp_as_sequence */ + 0, /* tp_as_mapping */ + PyHKEY_hashFunc, /* tp_hash */ + 0, /* tp_call */ + PyHKEY_strFunc, /* tp_str */ + 0, /* tp_getattro */ + 0, /* tp_setattro */ + 0, /* tp_as_buffer */ + 0, /* tp_flags */ + PyHKEY_doc, /* tp_doc */ + 0, /*tp_traverse*/ + 0, /*tp_clear*/ + 0, /*tp_richcompare*/ + 0, /*tp_weaklistoffset*/ + 0, /*tp_iter*/ + 0, /*tp_iternext*/ + PyHKEY_methods, /*tp_methods*/ + PyHKEY_memberlist, /*tp_members*/ }; /************************************************************************ @@ -546,39 +546,39 @@ static PyObject * PyHKEY_CloseMethod(PyObject *self, PyObject *args) { - if (!PyArg_ParseTuple(args, ":Close")) - return NULL; - if (!PyHKEY_Close(self)) - return NULL; - Py_INCREF(Py_None); - return Py_None; + if (!PyArg_ParseTuple(args, ":Close")) + return NULL; + if (!PyHKEY_Close(self)) + return NULL; + Py_INCREF(Py_None); + return Py_None; } static PyObject * PyHKEY_DetachMethod(PyObject *self, PyObject *args) { - void* ret; - PyHKEYObject *pThis = (PyHKEYObject *)self; - if (!PyArg_ParseTuple(args, ":Detach")) - return NULL; - ret = (void*)pThis->hkey; - pThis->hkey = 0; - return PyLong_FromVoidPtr(ret); + void* ret; + PyHKEYObject *pThis = (PyHKEYObject *)self; + if (!PyArg_ParseTuple(args, ":Detach")) + return NULL; + ret = (void*)pThis->hkey; + pThis->hkey = 0; + return PyLong_FromVoidPtr(ret); } static PyObject * PyHKEY_Enter(PyObject *self) { - Py_XINCREF(self); - return self; + Py_XINCREF(self); + return self; } static PyObject * PyHKEY_Exit(PyObject *self, PyObject *args) { - if (!PyHKEY_Close(self)) - return NULL; - Py_RETURN_NONE; + if (!PyHKEY_Close(self)) + return NULL; + Py_RETURN_NONE; } @@ -588,74 +588,74 @@ PyObject * PyHKEY_New(HKEY hInit) { - PyHKEYObject *key = PyObject_NEW(PyHKEYObject, &PyHKEY_Type); - if (key) - key->hkey = hInit; - return (PyObject *)key; + PyHKEYObject *key = PyObject_NEW(PyHKEYObject, &PyHKEY_Type); + if (key) + key->hkey = hInit; + return (PyObject *)key; } BOOL PyHKEY_Close(PyObject *ob_handle) { - LONG rc; - PyHKEYObject *key; + LONG rc; + PyHKEYObject *key; - if (!PyHKEY_Check(ob_handle)) { - PyErr_SetString(PyExc_TypeError, "bad operand type"); - return FALSE; - } - key = (PyHKEYObject *)ob_handle; - rc = key->hkey ? RegCloseKey((HKEY)key->hkey) : ERROR_SUCCESS; - key->hkey = 0; - if (rc != ERROR_SUCCESS) - PyErr_SetFromWindowsErrWithFunction(rc, "RegCloseKey"); - return rc == ERROR_SUCCESS; + if (!PyHKEY_Check(ob_handle)) { + PyErr_SetString(PyExc_TypeError, "bad operand type"); + return FALSE; + } + key = (PyHKEYObject *)ob_handle; + rc = key->hkey ? RegCloseKey((HKEY)key->hkey) : ERROR_SUCCESS; + key->hkey = 0; + if (rc != ERROR_SUCCESS) + PyErr_SetFromWindowsErrWithFunction(rc, "RegCloseKey"); + return rc == ERROR_SUCCESS; } BOOL PyHKEY_AsHKEY(PyObject *ob, HKEY *pHANDLE, BOOL bNoneOK) { - if (ob == Py_None) { - if (!bNoneOK) { - PyErr_SetString( - PyExc_TypeError, - "None is not a valid HKEY in this context"); - return FALSE; - } - *pHANDLE = (HKEY)0; - } - else if (PyHKEY_Check(ob)) { - PyHKEYObject *pH = (PyHKEYObject *)ob; - *pHANDLE = pH->hkey; - } - else if (PyLong_Check(ob)) { - /* We also support integers */ - PyErr_Clear(); - *pHANDLE = (HKEY)PyLong_AsVoidPtr(ob); - if (PyErr_Occurred()) - return FALSE; - } - else { - PyErr_SetString( - PyExc_TypeError, - "The object is not a PyHKEY object"); - return FALSE; - } - return TRUE; + if (ob == Py_None) { + if (!bNoneOK) { + PyErr_SetString( + PyExc_TypeError, + "None is not a valid HKEY in this context"); + return FALSE; + } + *pHANDLE = (HKEY)0; + } + else if (PyHKEY_Check(ob)) { + PyHKEYObject *pH = (PyHKEYObject *)ob; + *pHANDLE = pH->hkey; + } + else if (PyLong_Check(ob)) { + /* We also support integers */ + PyErr_Clear(); + *pHANDLE = (HKEY)PyLong_AsVoidPtr(ob); + if (PyErr_Occurred()) + return FALSE; + } + else { + PyErr_SetString( + PyExc_TypeError, + "The object is not a PyHKEY object"); + return FALSE; + } + return TRUE; } PyObject * PyHKEY_FromHKEY(HKEY h) { - PyHKEYObject *op; + PyHKEYObject *op; - /* Inline PyObject_New */ - op = (PyHKEYObject *) PyObject_MALLOC(sizeof(PyHKEYObject)); - if (op == NULL) - return PyErr_NoMemory(); - PyObject_INIT(op, &PyHKEY_Type); - op->hkey = h; - return (PyObject *)op; + /* Inline PyObject_New */ + op = (PyHKEYObject *) PyObject_MALLOC(sizeof(PyHKEYObject)); + if (op == NULL) + return PyErr_NoMemory(); + PyObject_INIT(op, &PyHKEY_Type); + op->hkey = h; + return (PyObject *)op; } @@ -665,32 +665,32 @@ BOOL PyWinObject_CloseHKEY(PyObject *obHandle) { - BOOL ok; - if (PyHKEY_Check(obHandle)) { - ok = PyHKEY_Close(obHandle); - } + BOOL ok; + if (PyHKEY_Check(obHandle)) { + ok = PyHKEY_Close(obHandle); + } #if SIZEOF_LONG >= SIZEOF_HKEY - else if (PyLong_Check(obHandle)) { - long rc = RegCloseKey((HKEY)PyLong_AsLong(obHandle)); - ok = (rc == ERROR_SUCCESS); - if (!ok) - PyErr_SetFromWindowsErrWithFunction(rc, "RegCloseKey"); - } + else if (PyLong_Check(obHandle)) { + long rc = RegCloseKey((HKEY)PyLong_AsLong(obHandle)); + ok = (rc == ERROR_SUCCESS); + if (!ok) + PyErr_SetFromWindowsErrWithFunction(rc, "RegCloseKey"); + } #else - else if (PyLong_Check(obHandle)) { - long rc = RegCloseKey((HKEY)PyLong_AsVoidPtr(obHandle)); - ok = (rc == ERROR_SUCCESS); - if (!ok) - PyErr_SetFromWindowsErrWithFunction(rc, "RegCloseKey"); - } + else if (PyLong_Check(obHandle)) { + long rc = RegCloseKey((HKEY)PyLong_AsVoidPtr(obHandle)); + ok = (rc == ERROR_SUCCESS); + if (!ok) + PyErr_SetFromWindowsErrWithFunction(rc, "RegCloseKey"); + } #endif - else { - PyErr_SetString( - PyExc_TypeError, - "A handle must be a HKEY object or an integer"); - return FALSE; - } - return ok; + else { + PyErr_SetString( + PyExc_TypeError, + "A handle must be a HKEY object or an integer"); + return FALSE; + } + return ok; } @@ -707,29 +707,29 @@ static void fixupMultiSZ(wchar_t **str, wchar_t *data, int len) { - wchar_t *P; - int i; - wchar_t *Q; - - Q = data + len; - for (P = data, i = 0; P < Q && *P != '\0'; P++, i++) { - str[i] = P; - for(; *P != '\0'; P++) - ; - } + wchar_t *P; + int i; + wchar_t *Q; + + Q = data + len; + for (P = data, i = 0; P < Q && *P != '\0'; P++, i++) { + str[i] = P; + for(; *P != '\0'; P++) + ; + } } static int countStrings(wchar_t *data, int len) { - int strings; - wchar_t *P; - wchar_t *Q = data + len; - - for (P = data, strings = 0; P < Q && *P != '\0'; P++, strings++) - for (; P < Q && *P != '\0'; P++) - ; - return strings; + int strings; + wchar_t *P; + wchar_t *Q = data + len; + + for (P = data, strings = 0; P < Q && *P != '\0'; P++, strings++) + for (; P < Q && *P != '\0'; P++) + ; + return strings; } /* Convert PyObject into Registry data. @@ -737,200 +737,200 @@ static BOOL Py2Reg(PyObject *value, DWORD typ, BYTE **retDataBuf, DWORD *retDataSize) { - Py_ssize_t i,j; - switch (typ) { - case REG_DWORD: - if (value != Py_None && !PyLong_Check(value)) - return FALSE; - *retDataBuf = (BYTE *)PyMem_NEW(DWORD, 1); - if (*retDataBuf==NULL){ - PyErr_NoMemory(); - return FALSE; - } - *retDataSize = sizeof(DWORD); - if (value == Py_None) { - DWORD zero = 0; - memcpy(*retDataBuf, &zero, sizeof(DWORD)); - } - else { - DWORD d = PyLong_AsLong(value); - memcpy(*retDataBuf, &d, sizeof(DWORD)); - } - break; - case REG_SZ: - case REG_EXPAND_SZ: - { - if (value == Py_None) - *retDataSize = 1; - else { - if (!PyUnicode_Check(value)) - return FALSE; - - *retDataSize = 2 + PyUnicode_GET_DATA_SIZE(value); - } - *retDataBuf = (BYTE *)PyMem_NEW(DWORD, *retDataSize); - if (*retDataBuf==NULL){ - PyErr_NoMemory(); - return FALSE; - } - if (value == Py_None) - wcscpy((wchar_t *)*retDataBuf, L""); - else - wcscpy((wchar_t *)*retDataBuf, - PyUnicode_AS_UNICODE(value)); - break; - } - case REG_MULTI_SZ: - { - DWORD size = 0; - wchar_t *P; - - if (value == Py_None) - i = 0; - else { - if (!PyList_Check(value)) - return FALSE; - i = PyList_Size(value); - } - for (j = 0; j < i; j++) - { - PyObject *t; - t = PyList_GET_ITEM(value, j); - if (!PyUnicode_Check(t)) - return FALSE; - size += 2 + PyUnicode_GET_DATA_SIZE(t); - } - - *retDataSize = size + 2; - *retDataBuf = (BYTE *)PyMem_NEW(char, - *retDataSize); - if (*retDataBuf==NULL){ - PyErr_NoMemory(); - return FALSE; - } - P = (wchar_t *)*retDataBuf; - - for (j = 0; j < i; j++) - { - PyObject *t; - t = PyList_GET_ITEM(value, j); - wcscpy(P, PyUnicode_AS_UNICODE(t)); - P += 1 + wcslen( - PyUnicode_AS_UNICODE(t)); - } - /* And doubly-terminate the list... */ - *P = '\0'; - break; - } - case REG_BINARY: - /* ALSO handle ALL unknown data types here. Even if we can't - support it natively, we should handle the bits. */ - default: - if (value == Py_None) - *retDataSize = 0; - else { - Py_buffer view; - - if (!PyObject_CheckBuffer(value)) { - PyErr_Format(PyExc_TypeError, - "Objects of type '%s' can not " - "be used as binary registry values", - value->ob_type->tp_name); - return FALSE; - } - - if (PyObject_GetBuffer(value, &view, PyBUF_SIMPLE) < 0) - return FALSE; - - *retDataBuf = (BYTE *)PyMem_NEW(char, view.len); - if (*retDataBuf==NULL){ - PyBuffer_Release(&view); - PyErr_NoMemory(); - return FALSE; - } - *retDataSize = view.len; - memcpy(*retDataBuf, view.buf, view.len); - PyBuffer_Release(&view); - } - break; - } - return TRUE; + Py_ssize_t i,j; + switch (typ) { + case REG_DWORD: + if (value != Py_None && !PyLong_Check(value)) + return FALSE; + *retDataBuf = (BYTE *)PyMem_NEW(DWORD, 1); + if (*retDataBuf==NULL){ + PyErr_NoMemory(); + return FALSE; + } + *retDataSize = sizeof(DWORD); + if (value == Py_None) { + DWORD zero = 0; + memcpy(*retDataBuf, &zero, sizeof(DWORD)); + } + else { + DWORD d = PyLong_AsLong(value); + memcpy(*retDataBuf, &d, sizeof(DWORD)); + } + break; + case REG_SZ: + case REG_EXPAND_SZ: + { + if (value == Py_None) + *retDataSize = 1; + else { + if (!PyUnicode_Check(value)) + return FALSE; + + *retDataSize = 2 + PyUnicode_GET_DATA_SIZE(value); + } + *retDataBuf = (BYTE *)PyMem_NEW(DWORD, *retDataSize); + if (*retDataBuf==NULL){ + PyErr_NoMemory(); + return FALSE; + } + if (value == Py_None) + wcscpy((wchar_t *)*retDataBuf, L""); + else + wcscpy((wchar_t *)*retDataBuf, + PyUnicode_AS_UNICODE(value)); + break; + } + case REG_MULTI_SZ: + { + DWORD size = 0; + wchar_t *P; + + if (value == Py_None) + i = 0; + else { + if (!PyList_Check(value)) + return FALSE; + i = PyList_Size(value); + } + for (j = 0; j < i; j++) + { + PyObject *t; + t = PyList_GET_ITEM(value, j); + if (!PyUnicode_Check(t)) + return FALSE; + size += 2 + PyUnicode_GET_DATA_SIZE(t); + } + + *retDataSize = size + 2; + *retDataBuf = (BYTE *)PyMem_NEW(char, + *retDataSize); + if (*retDataBuf==NULL){ + PyErr_NoMemory(); + return FALSE; + } + P = (wchar_t *)*retDataBuf; + + for (j = 0; j < i; j++) + { + PyObject *t; + t = PyList_GET_ITEM(value, j); + wcscpy(P, PyUnicode_AS_UNICODE(t)); + P += 1 + wcslen( + PyUnicode_AS_UNICODE(t)); + } + /* And doubly-terminate the list... */ + *P = '\0'; + break; + } + case REG_BINARY: + /* ALSO handle ALL unknown data types here. Even if we can't + support it natively, we should handle the bits. */ + default: + if (value == Py_None) + *retDataSize = 0; + else { + Py_buffer view; + + if (!PyObject_CheckBuffer(value)) { + PyErr_Format(PyExc_TypeError, + "Objects of type '%s' can not " + "be used as binary registry values", + value->ob_type->tp_name); + return FALSE; + } + + if (PyObject_GetBuffer(value, &view, PyBUF_SIMPLE) < 0) + return FALSE; + + *retDataBuf = (BYTE *)PyMem_NEW(char, view.len); + if (*retDataBuf==NULL){ + PyBuffer_Release(&view); + PyErr_NoMemory(); + return FALSE; + } + *retDataSize = view.len; + memcpy(*retDataBuf, view.buf, view.len); + PyBuffer_Release(&view); + } + break; + } + return TRUE; } /* Convert Registry data into PyObject*/ static PyObject * Reg2Py(BYTE *retDataBuf, DWORD retDataSize, DWORD typ) { - PyObject *obData; + PyObject *obData; - switch (typ) { - case REG_DWORD: - if (retDataSize == 0) - obData = PyLong_FromLong(0); - else - obData = PyLong_FromLong(*(int *)retDataBuf); - break; - case REG_SZ: - case REG_EXPAND_SZ: - { - /* the buffer may or may not have a trailing NULL */ - wchar_t *data = (wchar_t *)retDataBuf; - int len = retDataSize / 2; - if (retDataSize && data[len-1] == '\0') - retDataSize -= 2; - if (retDataSize <= 0) - data = L""; - obData = PyUnicode_FromUnicode(data, retDataSize/2); - break; - } - case REG_MULTI_SZ: - if (retDataSize == 0) - obData = PyList_New(0); - else - { - int index = 0; - wchar_t *data = (wchar_t *)retDataBuf; - int len = retDataSize / 2; - int s = countStrings(data, len); - wchar_t **str = (wchar_t **)malloc(sizeof(wchar_t *)*s); - if (str == NULL) - return PyErr_NoMemory(); - - fixupMultiSZ(str, data, len); - obData = PyList_New(s); - if (obData == NULL) - return NULL; - for (index = 0; index < s; index++) - { - size_t len = wcslen(str[index]); - if (len > INT_MAX) { - PyErr_SetString(PyExc_OverflowError, - "registry string is too long for a Python string"); - Py_DECREF(obData); - return NULL; - } - PyList_SetItem(obData, - index, - PyUnicode_FromUnicode(str[index], len)); - } - free(str); - - break; - } - case REG_BINARY: - /* ALSO handle ALL unknown data types here. Even if we can't - support it natively, we should handle the bits. */ - default: - if (retDataSize == 0) { - Py_INCREF(Py_None); - obData = Py_None; - } - else - obData = PyBytes_FromStringAndSize( - (char *)retDataBuf, retDataSize); - break; - } - return obData; + switch (typ) { + case REG_DWORD: + if (retDataSize == 0) + obData = PyLong_FromLong(0); + else + obData = PyLong_FromLong(*(int *)retDataBuf); + break; + case REG_SZ: + case REG_EXPAND_SZ: + { + /* the buffer may or may not have a trailing NULL */ + wchar_t *data = (wchar_t *)retDataBuf; + int len = retDataSize / 2; + if (retDataSize && data[len-1] == '\0') + retDataSize -= 2; + if (retDataSize <= 0) + data = L""; + obData = PyUnicode_FromUnicode(data, retDataSize/2); + break; + } + case REG_MULTI_SZ: + if (retDataSize == 0) + obData = PyList_New(0); + else + { + int index = 0; + wchar_t *data = (wchar_t *)retDataBuf; + int len = retDataSize / 2; + int s = countStrings(data, len); + wchar_t **str = (wchar_t **)malloc(sizeof(wchar_t *)*s); + if (str == NULL) + return PyErr_NoMemory(); + + fixupMultiSZ(str, data, len); + obData = PyList_New(s); + if (obData == NULL) + return NULL; + for (index = 0; index < s; index++) + { + size_t len = wcslen(str[index]); + if (len > INT_MAX) { + PyErr_SetString(PyExc_OverflowError, + "registry string is too long for a Python string"); + Py_DECREF(obData); + return NULL; + } + PyList_SetItem(obData, + index, + PyUnicode_FromUnicode(str[index], len)); + } + free(str); + + break; + } + case REG_BINARY: + /* ALSO handle ALL unknown data types here. Even if we can't + support it natively, we should handle the bits. */ + default: + if (retDataSize == 0) { + Py_INCREF(Py_None); + obData = Py_None; + } + else + obData = PyBytes_FromStringAndSize( + (char *)retDataBuf, retDataSize); + break; + } + return obData; } /* The Python methods */ @@ -938,344 +938,344 @@ static PyObject * PyCloseKey(PyObject *self, PyObject *args) { - PyObject *obKey; - if (!PyArg_ParseTuple(args, "O:CloseKey", &obKey)) - return NULL; - if (!PyHKEY_Close(obKey)) - return NULL; - Py_INCREF(Py_None); - return Py_None; + PyObject *obKey; + if (!PyArg_ParseTuple(args, "O:CloseKey", &obKey)) + return NULL; + if (!PyHKEY_Close(obKey)) + return NULL; + Py_INCREF(Py_None); + return Py_None; } static PyObject * PyConnectRegistry(PyObject *self, PyObject *args) { - HKEY hKey; - PyObject *obKey; - wchar_t *szCompName = NULL; - HKEY retKey; - long rc; - if (!PyArg_ParseTuple(args, "ZO:ConnectRegistry", &szCompName, &obKey)) - return NULL; - if (!PyHKEY_AsHKEY(obKey, &hKey, FALSE)) - return NULL; - Py_BEGIN_ALLOW_THREADS - rc = RegConnectRegistryW(szCompName, hKey, &retKey); - Py_END_ALLOW_THREADS - if (rc != ERROR_SUCCESS) - return PyErr_SetFromWindowsErrWithFunction(rc, - "ConnectRegistry"); - return PyHKEY_FromHKEY(retKey); + HKEY hKey; + PyObject *obKey; + wchar_t *szCompName = NULL; + HKEY retKey; + long rc; + if (!PyArg_ParseTuple(args, "ZO:ConnectRegistry", &szCompName, &obKey)) + return NULL; + if (!PyHKEY_AsHKEY(obKey, &hKey, FALSE)) + return NULL; + Py_BEGIN_ALLOW_THREADS + rc = RegConnectRegistryW(szCompName, hKey, &retKey); + Py_END_ALLOW_THREADS + if (rc != ERROR_SUCCESS) + return PyErr_SetFromWindowsErrWithFunction(rc, + "ConnectRegistry"); + return PyHKEY_FromHKEY(retKey); } static PyObject * PyCreateKey(PyObject *self, PyObject *args) { - HKEY hKey; - PyObject *obKey; - wchar_t *subKey; - HKEY retKey; - long rc; - if (!PyArg_ParseTuple(args, "OZ:CreateKey", &obKey, &subKey)) - return NULL; - if (!PyHKEY_AsHKEY(obKey, &hKey, FALSE)) - return NULL; - rc = RegCreateKeyW(hKey, subKey, &retKey); - if (rc != ERROR_SUCCESS) - return PyErr_SetFromWindowsErrWithFunction(rc, "CreateKey"); - return PyHKEY_FromHKEY(retKey); + HKEY hKey; + PyObject *obKey; + wchar_t *subKey; + HKEY retKey; + long rc; + if (!PyArg_ParseTuple(args, "OZ:CreateKey", &obKey, &subKey)) + return NULL; + if (!PyHKEY_AsHKEY(obKey, &hKey, FALSE)) + return NULL; + rc = RegCreateKeyW(hKey, subKey, &retKey); + if (rc != ERROR_SUCCESS) + return PyErr_SetFromWindowsErrWithFunction(rc, "CreateKey"); + return PyHKEY_FromHKEY(retKey); } static PyObject * PyCreateKeyEx(PyObject *self, PyObject *args) { - HKEY hKey; - PyObject *obKey; - wchar_t *subKey; - HKEY retKey; - int res = 0; - REGSAM sam = KEY_WRITE; - long rc; - if (!PyArg_ParseTuple(args, "OZ|ii:CreateKeyEx", &obKey, &subKey, - &res, &sam)) - return NULL; - if (!PyHKEY_AsHKEY(obKey, &hKey, FALSE)) - return NULL; - - rc = RegCreateKeyExW(hKey, subKey, res, NULL, (DWORD)NULL, - sam, NULL, &retKey, NULL); - if (rc != ERROR_SUCCESS) - return PyErr_SetFromWindowsErrWithFunction(rc, "CreateKeyEx"); - return PyHKEY_FromHKEY(retKey); + HKEY hKey; + PyObject *obKey; + wchar_t *subKey; + HKEY retKey; + int res = 0; + REGSAM sam = KEY_WRITE; + long rc; + if (!PyArg_ParseTuple(args, "OZ|ii:CreateKeyEx", &obKey, &subKey, + &res, &sam)) + return NULL; + if (!PyHKEY_AsHKEY(obKey, &hKey, FALSE)) + return NULL; + + rc = RegCreateKeyExW(hKey, subKey, res, NULL, (DWORD)NULL, + sam, NULL, &retKey, NULL); + if (rc != ERROR_SUCCESS) + return PyErr_SetFromWindowsErrWithFunction(rc, "CreateKeyEx"); + return PyHKEY_FromHKEY(retKey); } static PyObject * PyDeleteKey(PyObject *self, PyObject *args) { - HKEY hKey; - PyObject *obKey; - wchar_t *subKey; - long rc; - if (!PyArg_ParseTuple(args, "Ou:DeleteKey", &obKey, &subKey)) - return NULL; - if (!PyHKEY_AsHKEY(obKey, &hKey, FALSE)) - return NULL; - rc = RegDeleteKeyW(hKey, subKey ); - if (rc != ERROR_SUCCESS) - return PyErr_SetFromWindowsErrWithFunction(rc, "RegDeleteKey"); - Py_INCREF(Py_None); - return Py_None; + HKEY hKey; + PyObject *obKey; + wchar_t *subKey; + long rc; + if (!PyArg_ParseTuple(args, "Ou:DeleteKey", &obKey, &subKey)) + return NULL; + if (!PyHKEY_AsHKEY(obKey, &hKey, FALSE)) + return NULL; + rc = RegDeleteKeyW(hKey, subKey ); + if (rc != ERROR_SUCCESS) + return PyErr_SetFromWindowsErrWithFunction(rc, "RegDeleteKey"); + Py_INCREF(Py_None); + return Py_None; } static PyObject * PyDeleteKeyEx(PyObject *self, PyObject *args) { - HKEY hKey; - PyObject *obKey; - HMODULE hMod; - typedef LONG (WINAPI *RDKEFunc)(HKEY, const wchar_t*, REGSAM, int); - RDKEFunc pfn = NULL; - wchar_t *subKey; - long rc; - int res = 0; - REGSAM sam = KEY_WOW64_64KEY; - - if (!PyArg_ParseTuple(args, "Ou|ii:DeleteKeyEx", - &obKey, &subKey, &sam, &res)) - return NULL; - if (!PyHKEY_AsHKEY(obKey, &hKey, FALSE)) - return NULL; - - /* Only available on 64bit platforms, so we must load it - dynamically. */ - hMod = GetModuleHandle("advapi32.dll"); - if (hMod) - pfn = (RDKEFunc)GetProcAddress(hMod, - "RegDeleteKeyExW"); - if (!pfn) { - PyErr_SetString(PyExc_NotImplementedError, - "not implemented on this platform"); - return NULL; - } - Py_BEGIN_ALLOW_THREADS - rc = (*pfn)(hKey, subKey, sam, res); - Py_END_ALLOW_THREADS - - if (rc != ERROR_SUCCESS) - return PyErr_SetFromWindowsErrWithFunction(rc, "RegDeleteKeyEx"); - Py_INCREF(Py_None); - return Py_None; + HKEY hKey; + PyObject *obKey; + HMODULE hMod; + typedef LONG (WINAPI *RDKEFunc)(HKEY, const wchar_t*, REGSAM, int); + RDKEFunc pfn = NULL; + wchar_t *subKey; + long rc; + int res = 0; + REGSAM sam = KEY_WOW64_64KEY; + + if (!PyArg_ParseTuple(args, "Ou|ii:DeleteKeyEx", + &obKey, &subKey, &sam, &res)) + return NULL; + if (!PyHKEY_AsHKEY(obKey, &hKey, FALSE)) + return NULL; + + /* Only available on 64bit platforms, so we must load it + dynamically. */ + hMod = GetModuleHandle("advapi32.dll"); + if (hMod) + pfn = (RDKEFunc)GetProcAddress(hMod, + "RegDeleteKeyExW"); + if (!pfn) { + PyErr_SetString(PyExc_NotImplementedError, + "not implemented on this platform"); + return NULL; + } + Py_BEGIN_ALLOW_THREADS + rc = (*pfn)(hKey, subKey, sam, res); + Py_END_ALLOW_THREADS + + if (rc != ERROR_SUCCESS) + return PyErr_SetFromWindowsErrWithFunction(rc, "RegDeleteKeyEx"); + Py_INCREF(Py_None); + return Py_None; } static PyObject * PyDeleteValue(PyObject *self, PyObject *args) { - HKEY hKey; - PyObject *obKey; - wchar_t *subKey; - long rc; - if (!PyArg_ParseTuple(args, "OZ:DeleteValue", &obKey, &subKey)) - return NULL; - if (!PyHKEY_AsHKEY(obKey, &hKey, FALSE)) - return NULL; - Py_BEGIN_ALLOW_THREADS - rc = RegDeleteValueW(hKey, subKey); - Py_END_ALLOW_THREADS - if (rc !=ERROR_SUCCESS) - return PyErr_SetFromWindowsErrWithFunction(rc, - "RegDeleteValue"); - Py_INCREF(Py_None); - return Py_None; + HKEY hKey; + PyObject *obKey; + wchar_t *subKey; + long rc; + if (!PyArg_ParseTuple(args, "OZ:DeleteValue", &obKey, &subKey)) + return NULL; + if (!PyHKEY_AsHKEY(obKey, &hKey, FALSE)) + return NULL; + Py_BEGIN_ALLOW_THREADS + rc = RegDeleteValueW(hKey, subKey); + Py_END_ALLOW_THREADS + if (rc !=ERROR_SUCCESS) + return PyErr_SetFromWindowsErrWithFunction(rc, + "RegDeleteValue"); + Py_INCREF(Py_None); + return Py_None; } static PyObject * PyEnumKey(PyObject *self, PyObject *args) { - HKEY hKey; - PyObject *obKey; - int index; - long rc; - PyObject *retStr; - wchar_t tmpbuf[256]; /* max key name length is 255 */ - DWORD len = sizeof(tmpbuf); /* includes NULL terminator */ - - if (!PyArg_ParseTuple(args, "Oi:EnumKey", &obKey, &index)) - return NULL; - if (!PyHKEY_AsHKEY(obKey, &hKey, FALSE)) - return NULL; - - Py_BEGIN_ALLOW_THREADS - rc = RegEnumKeyExW(hKey, index, tmpbuf, &len, NULL, NULL, NULL, NULL); - Py_END_ALLOW_THREADS - if (rc != ERROR_SUCCESS) - return PyErr_SetFromWindowsErrWithFunction(rc, "RegEnumKeyEx"); + HKEY hKey; + PyObject *obKey; + int index; + long rc; + PyObject *retStr; + wchar_t tmpbuf[256]; /* max key name length is 255 */ + DWORD len = sizeof(tmpbuf); /* includes NULL terminator */ + + if (!PyArg_ParseTuple(args, "Oi:EnumKey", &obKey, &index)) + return NULL; + if (!PyHKEY_AsHKEY(obKey, &hKey, FALSE)) + return NULL; + + Py_BEGIN_ALLOW_THREADS + rc = RegEnumKeyExW(hKey, index, tmpbuf, &len, NULL, NULL, NULL, NULL); + Py_END_ALLOW_THREADS + if (rc != ERROR_SUCCESS) + return PyErr_SetFromWindowsErrWithFunction(rc, "RegEnumKeyEx"); - retStr = PyUnicode_FromUnicode(tmpbuf, len); - return retStr; /* can be NULL */ + retStr = PyUnicode_FromUnicode(tmpbuf, len); + return retStr; /* can be NULL */ } static PyObject * PyEnumValue(PyObject *self, PyObject *args) { - HKEY hKey; - PyObject *obKey; - int index; - long rc; - wchar_t *retValueBuf; - BYTE *retDataBuf; - DWORD retValueSize; - DWORD retDataSize; - DWORD typ; - PyObject *obData; - PyObject *retVal; - - if (!PyArg_ParseTuple(args, "Oi:EnumValue", &obKey, &index)) - return NULL; - if (!PyHKEY_AsHKEY(obKey, &hKey, FALSE)) - return NULL; - - if ((rc = RegQueryInfoKeyW(hKey, NULL, NULL, NULL, NULL, NULL, NULL, - NULL, - &retValueSize, &retDataSize, NULL, NULL)) - != ERROR_SUCCESS) - return PyErr_SetFromWindowsErrWithFunction(rc, - "RegQueryInfoKey"); - ++retValueSize; /* include null terminators */ - ++retDataSize; - retValueBuf = (wchar_t *)PyMem_Malloc(sizeof(wchar_t) * retValueSize); - if (retValueBuf == NULL) - return PyErr_NoMemory(); - retDataBuf = (BYTE *)PyMem_Malloc(retDataSize); - if (retDataBuf == NULL) { - PyMem_Free(retValueBuf); - return PyErr_NoMemory(); - } - - Py_BEGIN_ALLOW_THREADS - rc = RegEnumValueW(hKey, - index, - retValueBuf, - &retValueSize, - NULL, - &typ, - retDataBuf, - &retDataSize); - Py_END_ALLOW_THREADS - - if (rc != ERROR_SUCCESS) { - retVal = PyErr_SetFromWindowsErrWithFunction(rc, - "PyRegEnumValue"); - goto fail; - } - obData = Reg2Py(retDataBuf, retDataSize, typ); - if (obData == NULL) { - retVal = NULL; - goto fail; - } - retVal = Py_BuildValue("uOi", retValueBuf, obData, typ); - Py_DECREF(obData); + HKEY hKey; + PyObject *obKey; + int index; + long rc; + wchar_t *retValueBuf; + BYTE *retDataBuf; + DWORD retValueSize; + DWORD retDataSize; + DWORD typ; + PyObject *obData; + PyObject *retVal; + + if (!PyArg_ParseTuple(args, "Oi:EnumValue", &obKey, &index)) + return NULL; + if (!PyHKEY_AsHKEY(obKey, &hKey, FALSE)) + return NULL; + + if ((rc = RegQueryInfoKeyW(hKey, NULL, NULL, NULL, NULL, NULL, NULL, + NULL, + &retValueSize, &retDataSize, NULL, NULL)) + != ERROR_SUCCESS) + return PyErr_SetFromWindowsErrWithFunction(rc, + "RegQueryInfoKey"); + ++retValueSize; /* include null terminators */ + ++retDataSize; + retValueBuf = (wchar_t *)PyMem_Malloc(sizeof(wchar_t) * retValueSize); + if (retValueBuf == NULL) + return PyErr_NoMemory(); + retDataBuf = (BYTE *)PyMem_Malloc(retDataSize); + if (retDataBuf == NULL) { + PyMem_Free(retValueBuf); + return PyErr_NoMemory(); + } + + Py_BEGIN_ALLOW_THREADS + rc = RegEnumValueW(hKey, + index, + retValueBuf, + &retValueSize, + NULL, + &typ, + retDataBuf, + &retDataSize); + Py_END_ALLOW_THREADS + + if (rc != ERROR_SUCCESS) { + retVal = PyErr_SetFromWindowsErrWithFunction(rc, + "PyRegEnumValue"); + goto fail; + } + obData = Reg2Py(retDataBuf, retDataSize, typ); + if (obData == NULL) { + retVal = NULL; + goto fail; + } + retVal = Py_BuildValue("uOi", retValueBuf, obData, typ); + Py_DECREF(obData); fail: - PyMem_Free(retValueBuf); - PyMem_Free(retDataBuf); - return retVal; + PyMem_Free(retValueBuf); + PyMem_Free(retDataBuf); + return retVal; } static PyObject * PyExpandEnvironmentStrings(PyObject *self, PyObject *args) { - Py_UNICODE *retValue = NULL; - Py_UNICODE *src; - DWORD retValueSize; - DWORD rc; - PyObject *o; - - if (!PyArg_ParseTuple(args, "u:ExpandEnvironmentStrings", &src)) - return NULL; - - retValueSize = ExpandEnvironmentStringsW(src, retValue, 0); - if (retValueSize == 0) { - return PyErr_SetFromWindowsErrWithFunction(retValueSize, - "ExpandEnvironmentStrings"); - } - retValue = (Py_UNICODE *)PyMem_Malloc(retValueSize * sizeof(Py_UNICODE)); - if (retValue == NULL) { - return PyErr_NoMemory(); - } - - rc = ExpandEnvironmentStringsW(src, retValue, retValueSize); - if (rc == 0) { - PyMem_Free(retValue); - return PyErr_SetFromWindowsErrWithFunction(retValueSize, - "ExpandEnvironmentStrings"); - } - o = PyUnicode_FromUnicode(retValue, wcslen(retValue)); - PyMem_Free(retValue); - return o; + Py_UNICODE *retValue = NULL; + Py_UNICODE *src; + DWORD retValueSize; + DWORD rc; + PyObject *o; + + if (!PyArg_ParseTuple(args, "u:ExpandEnvironmentStrings", &src)) + return NULL; + + retValueSize = ExpandEnvironmentStringsW(src, retValue, 0); + if (retValueSize == 0) { + return PyErr_SetFromWindowsErrWithFunction(retValueSize, + "ExpandEnvironmentStrings"); + } + retValue = (Py_UNICODE *)PyMem_Malloc(retValueSize * sizeof(Py_UNICODE)); + if (retValue == NULL) { + return PyErr_NoMemory(); + } + + rc = ExpandEnvironmentStringsW(src, retValue, retValueSize); + if (rc == 0) { + PyMem_Free(retValue); + return PyErr_SetFromWindowsErrWithFunction(retValueSize, + "ExpandEnvironmentStrings"); + } + o = PyUnicode_FromUnicode(retValue, wcslen(retValue)); + PyMem_Free(retValue); + return o; } static PyObject * PyFlushKey(PyObject *self, PyObject *args) { - HKEY hKey; - PyObject *obKey; - long rc; - if (!PyArg_ParseTuple(args, "O:FlushKey", &obKey)) - return NULL; - if (!PyHKEY_AsHKEY(obKey, &hKey, FALSE)) - return NULL; - Py_BEGIN_ALLOW_THREADS - rc = RegFlushKey(hKey); - Py_END_ALLOW_THREADS - if (rc != ERROR_SUCCESS) - return PyErr_SetFromWindowsErrWithFunction(rc, "RegFlushKey"); - Py_INCREF(Py_None); - return Py_None; + HKEY hKey; + PyObject *obKey; + long rc; + if (!PyArg_ParseTuple(args, "O:FlushKey", &obKey)) + return NULL; + if (!PyHKEY_AsHKEY(obKey, &hKey, FALSE)) + return NULL; + Py_BEGIN_ALLOW_THREADS + rc = RegFlushKey(hKey); + Py_END_ALLOW_THREADS + if (rc != ERROR_SUCCESS) + return PyErr_SetFromWindowsErrWithFunction(rc, "RegFlushKey"); + Py_INCREF(Py_None); + return Py_None; } static PyObject * PyLoadKey(PyObject *self, PyObject *args) { - HKEY hKey; - PyObject *obKey; - wchar_t *subKey; - wchar_t *fileName; - - long rc; - if (!PyArg_ParseTuple(args, "Ouu:LoadKey", &obKey, &subKey, &fileName)) - return NULL; - if (!PyHKEY_AsHKEY(obKey, &hKey, FALSE)) - return NULL; - Py_BEGIN_ALLOW_THREADS - rc = RegLoadKeyW(hKey, subKey, fileName ); - Py_END_ALLOW_THREADS - if (rc != ERROR_SUCCESS) - return PyErr_SetFromWindowsErrWithFunction(rc, "RegLoadKey"); - Py_INCREF(Py_None); - return Py_None; + HKEY hKey; + PyObject *obKey; + wchar_t *subKey; + wchar_t *fileName; + + long rc; + if (!PyArg_ParseTuple(args, "Ouu:LoadKey", &obKey, &subKey, &fileName)) + return NULL; + if (!PyHKEY_AsHKEY(obKey, &hKey, FALSE)) + return NULL; + Py_BEGIN_ALLOW_THREADS + rc = RegLoadKeyW(hKey, subKey, fileName ); + Py_END_ALLOW_THREADS + if (rc != ERROR_SUCCESS) + return PyErr_SetFromWindowsErrWithFunction(rc, "RegLoadKey"); + Py_INCREF(Py_None); + return Py_None; } static PyObject * PyOpenKey(PyObject *self, PyObject *args) { - HKEY hKey; - PyObject *obKey; + HKEY hKey; + PyObject *obKey; - wchar_t *subKey; - int res = 0; - HKEY retKey; - long rc; - REGSAM sam = KEY_READ; - if (!PyArg_ParseTuple(args, "OZ|ii:OpenKey", &obKey, &subKey, - &res, &sam)) - return NULL; - if (!PyHKEY_AsHKEY(obKey, &hKey, FALSE)) - return NULL; - - Py_BEGIN_ALLOW_THREADS - rc = RegOpenKeyExW(hKey, subKey, res, sam, &retKey); - Py_END_ALLOW_THREADS - if (rc != ERROR_SUCCESS) - return PyErr_SetFromWindowsErrWithFunction(rc, "RegOpenKeyEx"); - return PyHKEY_FromHKEY(retKey); + wchar_t *subKey; + int res = 0; + HKEY retKey; + long rc; + REGSAM sam = KEY_READ; + if (!PyArg_ParseTuple(args, "OZ|ii:OpenKey", &obKey, &subKey, + &res, &sam)) + return NULL; + if (!PyHKEY_AsHKEY(obKey, &hKey, FALSE)) + return NULL; + + Py_BEGIN_ALLOW_THREADS + rc = RegOpenKeyExW(hKey, subKey, res, sam, &retKey); + Py_END_ALLOW_THREADS + if (rc != ERROR_SUCCESS) + return PyErr_SetFromWindowsErrWithFunction(rc, "RegOpenKeyEx"); + return PyHKEY_FromHKEY(retKey); } @@ -1291,18 +1291,18 @@ PyObject *l; PyObject *ret; if (!PyArg_ParseTuple(args, "O:QueryInfoKey", &obKey)) - return NULL; + return NULL; if (!PyHKEY_AsHKEY(obKey, &hKey, FALSE)) - return NULL; + return NULL; if ((rc = RegQueryInfoKey(hKey, NULL, NULL, 0, &nSubKeys, NULL, NULL, - &nValues, NULL, NULL, NULL, &ft)) + &nValues, NULL, NULL, NULL, &ft)) != ERROR_SUCCESS) - return PyErr_SetFromWindowsErrWithFunction(rc, "RegQueryInfoKey"); + return PyErr_SetFromWindowsErrWithFunction(rc, "RegQueryInfoKey"); li.LowPart = ft.dwLowDateTime; li.HighPart = ft.dwHighDateTime; l = PyLong_FromLongLong(li.QuadPart); if (l == NULL) - return NULL; + return NULL; ret = Py_BuildValue("iiO", nSubKeys, nValues, l); Py_DECREF(l); return ret; @@ -1311,328 +1311,328 @@ static PyObject * PyQueryValue(PyObject *self, PyObject *args) { - HKEY hKey; - PyObject *obKey; - wchar_t *subKey; - long rc; - PyObject *retStr; - wchar_t *retBuf; - long bufSize = 0; - - if (!PyArg_ParseTuple(args, "OZ:QueryValue", &obKey, &subKey)) - return NULL; - - if (!PyHKEY_AsHKEY(obKey, &hKey, FALSE)) - return NULL; - if ((rc = RegQueryValueW(hKey, subKey, NULL, &bufSize)) - != ERROR_SUCCESS) - return PyErr_SetFromWindowsErrWithFunction(rc, - "RegQueryValue"); - retBuf = (wchar_t *)PyMem_Malloc(bufSize); - if (retBuf == NULL) - return PyErr_NoMemory(); - - if ((rc = RegQueryValueW(hKey, subKey, retBuf, &bufSize)) - != ERROR_SUCCESS) { - PyMem_Free(retBuf); - return PyErr_SetFromWindowsErrWithFunction(rc, - "RegQueryValue"); - } - - retStr = PyUnicode_FromUnicode(retBuf, wcslen(retBuf)); - PyMem_Free(retBuf); - return retStr; + HKEY hKey; + PyObject *obKey; + wchar_t *subKey; + long rc; + PyObject *retStr; + wchar_t *retBuf; + long bufSize = 0; + + if (!PyArg_ParseTuple(args, "OZ:QueryValue", &obKey, &subKey)) + return NULL; + + if (!PyHKEY_AsHKEY(obKey, &hKey, FALSE)) + return NULL; + if ((rc = RegQueryValueW(hKey, subKey, NULL, &bufSize)) + != ERROR_SUCCESS) + return PyErr_SetFromWindowsErrWithFunction(rc, + "RegQueryValue"); + retBuf = (wchar_t *)PyMem_Malloc(bufSize); + if (retBuf == NULL) + return PyErr_NoMemory(); + + if ((rc = RegQueryValueW(hKey, subKey, retBuf, &bufSize)) + != ERROR_SUCCESS) { + PyMem_Free(retBuf); + return PyErr_SetFromWindowsErrWithFunction(rc, + "RegQueryValue"); + } + + retStr = PyUnicode_FromUnicode(retBuf, wcslen(retBuf)); + PyMem_Free(retBuf); + return retStr; } static PyObject * PyQueryValueEx(PyObject *self, PyObject *args) { - HKEY hKey; - PyObject *obKey; - wchar_t *valueName; - - long rc; - BYTE *retBuf; - DWORD bufSize = 0; - DWORD typ; - PyObject *obData; - PyObject *result; - - if (!PyArg_ParseTuple(args, "OZ:QueryValueEx", &obKey, &valueName)) - return NULL; - - if (!PyHKEY_AsHKEY(obKey, &hKey, FALSE)) - return NULL; - if ((rc = RegQueryValueExW(hKey, valueName, - NULL, NULL, NULL, - &bufSize)) - != ERROR_SUCCESS) - return PyErr_SetFromWindowsErrWithFunction(rc, - "RegQueryValueEx"); - retBuf = (BYTE *)PyMem_Malloc(bufSize); - if (retBuf == NULL) - return PyErr_NoMemory(); - if ((rc = RegQueryValueExW(hKey, valueName, NULL, - &typ, retBuf, &bufSize)) - != ERROR_SUCCESS) { - PyMem_Free(retBuf); - return PyErr_SetFromWindowsErrWithFunction(rc, - "RegQueryValueEx"); - } - obData = Reg2Py(retBuf, bufSize, typ); - PyMem_Free(retBuf); - if (obData == NULL) - return NULL; - result = Py_BuildValue("Oi", obData, typ); - Py_DECREF(obData); - return result; + HKEY hKey; + PyObject *obKey; + wchar_t *valueName; + + long rc; + BYTE *retBuf; + DWORD bufSize = 0; + DWORD typ; + PyObject *obData; + PyObject *result; + + if (!PyArg_ParseTuple(args, "OZ:QueryValueEx", &obKey, &valueName)) + return NULL; + + if (!PyHKEY_AsHKEY(obKey, &hKey, FALSE)) + return NULL; + if ((rc = RegQueryValueExW(hKey, valueName, + NULL, NULL, NULL, + &bufSize)) + != ERROR_SUCCESS) + return PyErr_SetFromWindowsErrWithFunction(rc, + "RegQueryValueEx"); + retBuf = (BYTE *)PyMem_Malloc(bufSize); + if (retBuf == NULL) + return PyErr_NoMemory(); + if ((rc = RegQueryValueExW(hKey, valueName, NULL, + &typ, retBuf, &bufSize)) + != ERROR_SUCCESS) { + PyMem_Free(retBuf); + return PyErr_SetFromWindowsErrWithFunction(rc, + "RegQueryValueEx"); + } + obData = Reg2Py(retBuf, bufSize, typ); + PyMem_Free(retBuf); + if (obData == NULL) + return NULL; + result = Py_BuildValue("Oi", obData, typ); + Py_DECREF(obData); + return result; } static PyObject * PySaveKey(PyObject *self, PyObject *args) { - HKEY hKey; - PyObject *obKey; - wchar_t *fileName; - LPSECURITY_ATTRIBUTES pSA = NULL; - - long rc; - if (!PyArg_ParseTuple(args, "Ou:SaveKey", &obKey, &fileName)) - return NULL; - if (!PyHKEY_AsHKEY(obKey, &hKey, FALSE)) - return NULL; + HKEY hKey; + PyObject *obKey; + wchar_t *fileName; + LPSECURITY_ATTRIBUTES pSA = NULL; + + long rc; + if (!PyArg_ParseTuple(args, "Ou:SaveKey", &obKey, &fileName)) + return NULL; + if (!PyHKEY_AsHKEY(obKey, &hKey, FALSE)) + return NULL; /* One day we may get security into the core? - if (!PyWinObject_AsSECURITY_ATTRIBUTES(obSA, &pSA, TRUE)) - return NULL; + if (!PyWinObject_AsSECURITY_ATTRIBUTES(obSA, &pSA, TRUE)) + return NULL; */ - Py_BEGIN_ALLOW_THREADS - rc = RegSaveKeyW(hKey, fileName, pSA ); - Py_END_ALLOW_THREADS - if (rc != ERROR_SUCCESS) - return PyErr_SetFromWindowsErrWithFunction(rc, "RegSaveKey"); - Py_INCREF(Py_None); - return Py_None; + Py_BEGIN_ALLOW_THREADS + rc = RegSaveKeyW(hKey, fileName, pSA ); + Py_END_ALLOW_THREADS + if (rc != ERROR_SUCCESS) + return PyErr_SetFromWindowsErrWithFunction(rc, "RegSaveKey"); + Py_INCREF(Py_None); + return Py_None; } static PyObject * PySetValue(PyObject *self, PyObject *args) { - HKEY hKey; - PyObject *obKey; - wchar_t *subKey; - wchar_t *str; - DWORD typ; - DWORD len; - long rc; - if (!PyArg_ParseTuple(args, "OZiu#:SetValue", - &obKey, - &subKey, - &typ, - &str, - &len)) - return NULL; - if (!PyHKEY_AsHKEY(obKey, &hKey, FALSE)) - return NULL; - if (typ != REG_SZ) { - PyErr_SetString(PyExc_TypeError, - "Type must be winreg.REG_SZ"); - return NULL; - } - - Py_BEGIN_ALLOW_THREADS - rc = RegSetValueW(hKey, subKey, REG_SZ, str, len+1); - Py_END_ALLOW_THREADS - if (rc != ERROR_SUCCESS) - return PyErr_SetFromWindowsErrWithFunction(rc, "RegSetValue"); - Py_INCREF(Py_None); - return Py_None; + HKEY hKey; + PyObject *obKey; + wchar_t *subKey; + wchar_t *str; + DWORD typ; + DWORD len; + long rc; + if (!PyArg_ParseTuple(args, "OZiu#:SetValue", + &obKey, + &subKey, + &typ, + &str, + &len)) + return NULL; + if (!PyHKEY_AsHKEY(obKey, &hKey, FALSE)) + return NULL; + if (typ != REG_SZ) { + PyErr_SetString(PyExc_TypeError, + "Type must be winreg.REG_SZ"); + return NULL; + } + + Py_BEGIN_ALLOW_THREADS + rc = RegSetValueW(hKey, subKey, REG_SZ, str, len+1); + Py_END_ALLOW_THREADS + if (rc != ERROR_SUCCESS) + return PyErr_SetFromWindowsErrWithFunction(rc, "RegSetValue"); + Py_INCREF(Py_None); + return Py_None; } static PyObject * PySetValueEx(PyObject *self, PyObject *args) { - HKEY hKey; - PyObject *obKey; - Py_UNICODE *valueName; - PyObject *obRes; - PyObject *value; - BYTE *data; - DWORD len; - DWORD typ; - - LONG rc; - - if (!PyArg_ParseTuple(args, "OZOiO:SetValueEx", - &obKey, - &valueName, - &obRes, - &typ, - &value)) - return NULL; - if (!PyHKEY_AsHKEY(obKey, &hKey, FALSE)) - return NULL; - if (!Py2Reg(value, typ, &data, &len)) - { - if (!PyErr_Occurred()) - PyErr_SetString(PyExc_ValueError, - "Could not convert the data to the specified type."); - return NULL; - } - Py_BEGIN_ALLOW_THREADS - rc = RegSetValueExW(hKey, valueName, 0, typ, data, len); - Py_END_ALLOW_THREADS - PyMem_DEL(data); - if (rc != ERROR_SUCCESS) - return PyErr_SetFromWindowsErrWithFunction(rc, - "RegSetValueEx"); - Py_INCREF(Py_None); - return Py_None; + HKEY hKey; + PyObject *obKey; + Py_UNICODE *valueName; + PyObject *obRes; + PyObject *value; + BYTE *data; + DWORD len; + DWORD typ; + + LONG rc; + + if (!PyArg_ParseTuple(args, "OZOiO:SetValueEx", + &obKey, + &valueName, + &obRes, + &typ, + &value)) + return NULL; + if (!PyHKEY_AsHKEY(obKey, &hKey, FALSE)) + return NULL; + if (!Py2Reg(value, typ, &data, &len)) + { + if (!PyErr_Occurred()) + PyErr_SetString(PyExc_ValueError, + "Could not convert the data to the specified type."); + return NULL; + } + Py_BEGIN_ALLOW_THREADS + rc = RegSetValueExW(hKey, valueName, 0, typ, data, len); + Py_END_ALLOW_THREADS + PyMem_DEL(data); + if (rc != ERROR_SUCCESS) + return PyErr_SetFromWindowsErrWithFunction(rc, + "RegSetValueEx"); + Py_INCREF(Py_None); + return Py_None; } static PyObject * PyDisableReflectionKey(PyObject *self, PyObject *args) { - HKEY hKey; - PyObject *obKey; - HMODULE hMod; - typedef LONG (WINAPI *RDRKFunc)(HKEY); - RDRKFunc pfn = NULL; - LONG rc; - - if (!PyArg_ParseTuple(args, "O:DisableReflectionKey", &obKey)) - return NULL; - if (!PyHKEY_AsHKEY(obKey, &hKey, FALSE)) - return NULL; - - /* Only available on 64bit platforms, so we must load it - dynamically.*/ - hMod = GetModuleHandle("advapi32.dll"); - if (hMod) - pfn = (RDRKFunc)GetProcAddress(hMod, - "RegDisableReflectionKey"); - if (!pfn) { - PyErr_SetString(PyExc_NotImplementedError, - "not implemented on this platform"); - return NULL; - } - Py_BEGIN_ALLOW_THREADS - rc = (*pfn)(hKey); - Py_END_ALLOW_THREADS - if (rc != ERROR_SUCCESS) - return PyErr_SetFromWindowsErrWithFunction(rc, - "RegDisableReflectionKey"); - Py_INCREF(Py_None); - return Py_None; + HKEY hKey; + PyObject *obKey; + HMODULE hMod; + typedef LONG (WINAPI *RDRKFunc)(HKEY); + RDRKFunc pfn = NULL; + LONG rc; + + if (!PyArg_ParseTuple(args, "O:DisableReflectionKey", &obKey)) + return NULL; + if (!PyHKEY_AsHKEY(obKey, &hKey, FALSE)) + return NULL; + + /* Only available on 64bit platforms, so we must load it + dynamically.*/ + hMod = GetModuleHandle("advapi32.dll"); + if (hMod) + pfn = (RDRKFunc)GetProcAddress(hMod, + "RegDisableReflectionKey"); + if (!pfn) { + PyErr_SetString(PyExc_NotImplementedError, + "not implemented on this platform"); + return NULL; + } + Py_BEGIN_ALLOW_THREADS + rc = (*pfn)(hKey); + Py_END_ALLOW_THREADS + if (rc != ERROR_SUCCESS) + return PyErr_SetFromWindowsErrWithFunction(rc, + "RegDisableReflectionKey"); + Py_INCREF(Py_None); + return Py_None; } static PyObject * PyEnableReflectionKey(PyObject *self, PyObject *args) { - HKEY hKey; - PyObject *obKey; - HMODULE hMod; - typedef LONG (WINAPI *RERKFunc)(HKEY); - RERKFunc pfn = NULL; - LONG rc; - - if (!PyArg_ParseTuple(args, "O:EnableReflectionKey", &obKey)) - return NULL; - if (!PyHKEY_AsHKEY(obKey, &hKey, FALSE)) - return NULL; - - /* Only available on 64bit platforms, so we must load it - dynamically.*/ - hMod = GetModuleHandle("advapi32.dll"); - if (hMod) - pfn = (RERKFunc)GetProcAddress(hMod, - "RegEnableReflectionKey"); - if (!pfn) { - PyErr_SetString(PyExc_NotImplementedError, - "not implemented on this platform"); - return NULL; - } - Py_BEGIN_ALLOW_THREADS - rc = (*pfn)(hKey); - Py_END_ALLOW_THREADS - if (rc != ERROR_SUCCESS) - return PyErr_SetFromWindowsErrWithFunction(rc, - "RegEnableReflectionKey"); - Py_INCREF(Py_None); - return Py_None; + HKEY hKey; + PyObject *obKey; + HMODULE hMod; + typedef LONG (WINAPI *RERKFunc)(HKEY); + RERKFunc pfn = NULL; + LONG rc; + + if (!PyArg_ParseTuple(args, "O:EnableReflectionKey", &obKey)) + return NULL; + if (!PyHKEY_AsHKEY(obKey, &hKey, FALSE)) + return NULL; + + /* Only available on 64bit platforms, so we must load it + dynamically.*/ + hMod = GetModuleHandle("advapi32.dll"); + if (hMod) + pfn = (RERKFunc)GetProcAddress(hMod, + "RegEnableReflectionKey"); + if (!pfn) { + PyErr_SetString(PyExc_NotImplementedError, + "not implemented on this platform"); + return NULL; + } + Py_BEGIN_ALLOW_THREADS + rc = (*pfn)(hKey); + Py_END_ALLOW_THREADS + if (rc != ERROR_SUCCESS) + return PyErr_SetFromWindowsErrWithFunction(rc, + "RegEnableReflectionKey"); + Py_INCREF(Py_None); + return Py_None; } static PyObject * PyQueryReflectionKey(PyObject *self, PyObject *args) { - HKEY hKey; - PyObject *obKey; - HMODULE hMod; - typedef LONG (WINAPI *RQRKFunc)(HKEY, BOOL *); - RQRKFunc pfn = NULL; - BOOL result; - LONG rc; - - if (!PyArg_ParseTuple(args, "O:QueryReflectionKey", &obKey)) - return NULL; - if (!PyHKEY_AsHKEY(obKey, &hKey, FALSE)) - return NULL; - - /* Only available on 64bit platforms, so we must load it - dynamically.*/ - hMod = GetModuleHandle("advapi32.dll"); - if (hMod) - pfn = (RQRKFunc)GetProcAddress(hMod, - "RegQueryReflectionKey"); - if (!pfn) { - PyErr_SetString(PyExc_NotImplementedError, - "not implemented on this platform"); - return NULL; - } - Py_BEGIN_ALLOW_THREADS - rc = (*pfn)(hKey, &result); - Py_END_ALLOW_THREADS - if (rc != ERROR_SUCCESS) - return PyErr_SetFromWindowsErrWithFunction(rc, - "RegQueryReflectionKey"); - return PyBool_FromLong(result); + HKEY hKey; + PyObject *obKey; + HMODULE hMod; + typedef LONG (WINAPI *RQRKFunc)(HKEY, BOOL *); + RQRKFunc pfn = NULL; + BOOL result; + LONG rc; + + if (!PyArg_ParseTuple(args, "O:QueryReflectionKey", &obKey)) + return NULL; + if (!PyHKEY_AsHKEY(obKey, &hKey, FALSE)) + return NULL; + + /* Only available on 64bit platforms, so we must load it + dynamically.*/ + hMod = GetModuleHandle("advapi32.dll"); + if (hMod) + pfn = (RQRKFunc)GetProcAddress(hMod, + "RegQueryReflectionKey"); + if (!pfn) { + PyErr_SetString(PyExc_NotImplementedError, + "not implemented on this platform"); + return NULL; + } + Py_BEGIN_ALLOW_THREADS + rc = (*pfn)(hKey, &result); + Py_END_ALLOW_THREADS + if (rc != ERROR_SUCCESS) + return PyErr_SetFromWindowsErrWithFunction(rc, + "RegQueryReflectionKey"); + return PyBool_FromLong(result); } static struct PyMethodDef winreg_methods[] = { - {"CloseKey", PyCloseKey, METH_VARARGS, CloseKey_doc}, - {"ConnectRegistry", PyConnectRegistry, METH_VARARGS, ConnectRegistry_doc}, - {"CreateKey", PyCreateKey, METH_VARARGS, CreateKey_doc}, - {"CreateKeyEx", PyCreateKeyEx, METH_VARARGS, CreateKeyEx_doc}, - {"DeleteKey", PyDeleteKey, METH_VARARGS, DeleteKey_doc}, - {"DeleteKeyEx", PyDeleteKeyEx, METH_VARARGS, DeleteKeyEx_doc}, - {"DeleteValue", PyDeleteValue, METH_VARARGS, DeleteValue_doc}, - {"DisableReflectionKey", PyDisableReflectionKey, METH_VARARGS, DisableReflectionKey_doc}, - {"EnableReflectionKey", PyEnableReflectionKey, METH_VARARGS, EnableReflectionKey_doc}, - {"EnumKey", PyEnumKey, METH_VARARGS, EnumKey_doc}, - {"EnumValue", PyEnumValue, METH_VARARGS, EnumValue_doc}, - {"ExpandEnvironmentStrings", PyExpandEnvironmentStrings, METH_VARARGS, - ExpandEnvironmentStrings_doc }, - {"FlushKey", PyFlushKey, METH_VARARGS, FlushKey_doc}, - {"LoadKey", PyLoadKey, METH_VARARGS, LoadKey_doc}, - {"OpenKey", PyOpenKey, METH_VARARGS, OpenKey_doc}, - {"OpenKeyEx", PyOpenKey, METH_VARARGS, OpenKeyEx_doc}, - {"QueryValue", PyQueryValue, METH_VARARGS, QueryValue_doc}, - {"QueryValueEx", PyQueryValueEx, METH_VARARGS, QueryValueEx_doc}, - {"QueryInfoKey", PyQueryInfoKey, METH_VARARGS, QueryInfoKey_doc}, - {"QueryReflectionKey",PyQueryReflectionKey,METH_VARARGS, QueryReflectionKey_doc}, - {"SaveKey", PySaveKey, METH_VARARGS, SaveKey_doc}, - {"SetValue", PySetValue, METH_VARARGS, SetValue_doc}, - {"SetValueEx", PySetValueEx, METH_VARARGS, SetValueEx_doc}, - NULL, + {"CloseKey", PyCloseKey, METH_VARARGS, CloseKey_doc}, + {"ConnectRegistry", PyConnectRegistry, METH_VARARGS, ConnectRegistry_doc}, + {"CreateKey", PyCreateKey, METH_VARARGS, CreateKey_doc}, + {"CreateKeyEx", PyCreateKeyEx, METH_VARARGS, CreateKeyEx_doc}, + {"DeleteKey", PyDeleteKey, METH_VARARGS, DeleteKey_doc}, + {"DeleteKeyEx", PyDeleteKeyEx, METH_VARARGS, DeleteKeyEx_doc}, + {"DeleteValue", PyDeleteValue, METH_VARARGS, DeleteValue_doc}, + {"DisableReflectionKey", PyDisableReflectionKey, METH_VARARGS, DisableReflectionKey_doc}, + {"EnableReflectionKey", PyEnableReflectionKey, METH_VARARGS, EnableReflectionKey_doc}, + {"EnumKey", PyEnumKey, METH_VARARGS, EnumKey_doc}, + {"EnumValue", PyEnumValue, METH_VARARGS, EnumValue_doc}, + {"ExpandEnvironmentStrings", PyExpandEnvironmentStrings, METH_VARARGS, + ExpandEnvironmentStrings_doc }, + {"FlushKey", PyFlushKey, METH_VARARGS, FlushKey_doc}, + {"LoadKey", PyLoadKey, METH_VARARGS, LoadKey_doc}, + {"OpenKey", PyOpenKey, METH_VARARGS, OpenKey_doc}, + {"OpenKeyEx", PyOpenKey, METH_VARARGS, OpenKeyEx_doc}, + {"QueryValue", PyQueryValue, METH_VARARGS, QueryValue_doc}, + {"QueryValueEx", PyQueryValueEx, METH_VARARGS, QueryValueEx_doc}, + {"QueryInfoKey", PyQueryInfoKey, METH_VARARGS, QueryInfoKey_doc}, + {"QueryReflectionKey",PyQueryReflectionKey,METH_VARARGS, QueryReflectionKey_doc}, + {"SaveKey", PySaveKey, METH_VARARGS, SaveKey_doc}, + {"SetValue", PySetValue, METH_VARARGS, SetValue_doc}, + {"SetValueEx", PySetValueEx, METH_VARARGS, SetValueEx_doc}, + NULL, }; static void insint(PyObject * d, char * name, long value) { - PyObject *v = PyLong_FromLong(value); - if (!v || PyDict_SetItemString(d, name, v)) - PyErr_Clear(); - Py_XDECREF(v); + PyObject *v = PyLong_FromLong(value); + if (!v || PyDict_SetItemString(d, name, v)) + PyErr_Clear(); + Py_XDECREF(v); } #define ADD_INT(val) insint(d, #val, val) @@ -1640,104 +1640,104 @@ static void inskey(PyObject * d, char * name, HKEY key) { - PyObject *v = PyLong_FromVoidPtr(key); - if (!v || PyDict_SetItemString(d, name, v)) - PyErr_Clear(); - Py_XDECREF(v); + PyObject *v = PyLong_FromVoidPtr(key); + if (!v || PyDict_SetItemString(d, name, v)) + PyErr_Clear(); + Py_XDECREF(v); } #define ADD_KEY(val) inskey(d, #val, val) static struct PyModuleDef winregmodule = { - PyModuleDef_HEAD_INIT, - "winreg", - module_doc, - -1, - winreg_methods, - NULL, - NULL, - NULL, - NULL + PyModuleDef_HEAD_INIT, + "winreg", + module_doc, + -1, + winreg_methods, + NULL, + NULL, + NULL, + NULL }; PyMODINIT_FUNC PyInit_winreg(void) { - PyObject *m, *d; - m = PyModule_Create(&winregmodule); - if (m == NULL) - return NULL; - d = PyModule_GetDict(m); - PyHKEY_Type.tp_doc = PyHKEY_doc; - if (PyType_Ready(&PyHKEY_Type) < 0) - return NULL; - Py_INCREF(&PyHKEY_Type); - if (PyDict_SetItemString(d, "HKEYType", - (PyObject *)&PyHKEY_Type) != 0) - return NULL; - Py_INCREF(PyExc_WindowsError); - if (PyDict_SetItemString(d, "error", - PyExc_WindowsError) != 0) - return NULL; - - /* Add the relevant constants */ - ADD_KEY(HKEY_CLASSES_ROOT); - ADD_KEY(HKEY_CURRENT_USER); - ADD_KEY(HKEY_LOCAL_MACHINE); - ADD_KEY(HKEY_USERS); - ADD_KEY(HKEY_PERFORMANCE_DATA); + PyObject *m, *d; + m = PyModule_Create(&winregmodule); + if (m == NULL) + return NULL; + d = PyModule_GetDict(m); + PyHKEY_Type.tp_doc = PyHKEY_doc; + if (PyType_Ready(&PyHKEY_Type) < 0) + return NULL; + Py_INCREF(&PyHKEY_Type); + if (PyDict_SetItemString(d, "HKEYType", + (PyObject *)&PyHKEY_Type) != 0) + return NULL; + Py_INCREF(PyExc_WindowsError); + if (PyDict_SetItemString(d, "error", + PyExc_WindowsError) != 0) + return NULL; + + /* Add the relevant constants */ + ADD_KEY(HKEY_CLASSES_ROOT); + ADD_KEY(HKEY_CURRENT_USER); + ADD_KEY(HKEY_LOCAL_MACHINE); + ADD_KEY(HKEY_USERS); + ADD_KEY(HKEY_PERFORMANCE_DATA); #ifdef HKEY_CURRENT_CONFIG - ADD_KEY(HKEY_CURRENT_CONFIG); + ADD_KEY(HKEY_CURRENT_CONFIG); #endif #ifdef HKEY_DYN_DATA - ADD_KEY(HKEY_DYN_DATA); + ADD_KEY(HKEY_DYN_DATA); #endif - ADD_INT(KEY_QUERY_VALUE); - ADD_INT(KEY_SET_VALUE); - ADD_INT(KEY_CREATE_SUB_KEY); - ADD_INT(KEY_ENUMERATE_SUB_KEYS); - ADD_INT(KEY_NOTIFY); - ADD_INT(KEY_CREATE_LINK); - ADD_INT(KEY_READ); - ADD_INT(KEY_WRITE); - ADD_INT(KEY_EXECUTE); - ADD_INT(KEY_ALL_ACCESS); + ADD_INT(KEY_QUERY_VALUE); + ADD_INT(KEY_SET_VALUE); + ADD_INT(KEY_CREATE_SUB_KEY); + ADD_INT(KEY_ENUMERATE_SUB_KEYS); + ADD_INT(KEY_NOTIFY); + ADD_INT(KEY_CREATE_LINK); + ADD_INT(KEY_READ); + ADD_INT(KEY_WRITE); + ADD_INT(KEY_EXECUTE); + ADD_INT(KEY_ALL_ACCESS); #ifdef KEY_WOW64_64KEY - ADD_INT(KEY_WOW64_64KEY); + ADD_INT(KEY_WOW64_64KEY); #endif #ifdef KEY_WOW64_32KEY - ADD_INT(KEY_WOW64_32KEY); + ADD_INT(KEY_WOW64_32KEY); #endif - ADD_INT(REG_OPTION_RESERVED); - ADD_INT(REG_OPTION_NON_VOLATILE); - ADD_INT(REG_OPTION_VOLATILE); - ADD_INT(REG_OPTION_CREATE_LINK); - ADD_INT(REG_OPTION_BACKUP_RESTORE); - ADD_INT(REG_OPTION_OPEN_LINK); - ADD_INT(REG_LEGAL_OPTION); - ADD_INT(REG_CREATED_NEW_KEY); - ADD_INT(REG_OPENED_EXISTING_KEY); - ADD_INT(REG_WHOLE_HIVE_VOLATILE); - ADD_INT(REG_REFRESH_HIVE); - ADD_INT(REG_NO_LAZY_FLUSH); - ADD_INT(REG_NOTIFY_CHANGE_NAME); - ADD_INT(REG_NOTIFY_CHANGE_ATTRIBUTES); - ADD_INT(REG_NOTIFY_CHANGE_LAST_SET); - ADD_INT(REG_NOTIFY_CHANGE_SECURITY); - ADD_INT(REG_LEGAL_CHANGE_FILTER); - ADD_INT(REG_NONE); - ADD_INT(REG_SZ); - ADD_INT(REG_EXPAND_SZ); - ADD_INT(REG_BINARY); - ADD_INT(REG_DWORD); - ADD_INT(REG_DWORD_LITTLE_ENDIAN); - ADD_INT(REG_DWORD_BIG_ENDIAN); - ADD_INT(REG_LINK); - ADD_INT(REG_MULTI_SZ); - ADD_INT(REG_RESOURCE_LIST); - ADD_INT(REG_FULL_RESOURCE_DESCRIPTOR); - ADD_INT(REG_RESOURCE_REQUIREMENTS_LIST); - return m; + ADD_INT(REG_OPTION_RESERVED); + ADD_INT(REG_OPTION_NON_VOLATILE); + ADD_INT(REG_OPTION_VOLATILE); + ADD_INT(REG_OPTION_CREATE_LINK); + ADD_INT(REG_OPTION_BACKUP_RESTORE); + ADD_INT(REG_OPTION_OPEN_LINK); + ADD_INT(REG_LEGAL_OPTION); + ADD_INT(REG_CREATED_NEW_KEY); + ADD_INT(REG_OPENED_EXISTING_KEY); + ADD_INT(REG_WHOLE_HIVE_VOLATILE); + ADD_INT(REG_REFRESH_HIVE); + ADD_INT(REG_NO_LAZY_FLUSH); + ADD_INT(REG_NOTIFY_CHANGE_NAME); + ADD_INT(REG_NOTIFY_CHANGE_ATTRIBUTES); + ADD_INT(REG_NOTIFY_CHANGE_LAST_SET); + ADD_INT(REG_NOTIFY_CHANGE_SECURITY); + ADD_INT(REG_LEGAL_CHANGE_FILTER); + ADD_INT(REG_NONE); + ADD_INT(REG_SZ); + ADD_INT(REG_EXPAND_SZ); + ADD_INT(REG_BINARY); + ADD_INT(REG_DWORD); + ADD_INT(REG_DWORD_LITTLE_ENDIAN); + ADD_INT(REG_DWORD_BIG_ENDIAN); + ADD_INT(REG_LINK); + ADD_INT(REG_MULTI_SZ); + ADD_INT(REG_RESOURCE_LIST); + ADD_INT(REG_FULL_RESOURCE_DESCRIPTOR); + ADD_INT(REG_RESOURCE_REQUIREMENTS_LIST); + return m; } Modified: python/branches/py3k-jit/PC/winsound.c ============================================================================== --- python/branches/py3k-jit/PC/winsound.c (original) +++ python/branches/py3k-jit/PC/winsound.c Mon May 10 23:55:43 2010 @@ -78,14 +78,14 @@ int ok; if(!PyArg_ParseTuple(args,"z#i:PlaySound",&sound,&length,&flags)) { - return NULL; + return NULL; } if(flags&SND_ASYNC && flags &SND_MEMORY) { - /* Sidestep reference counting headache; unfortunately this also - prevent SND_LOOP from memory. */ - PyErr_SetString(PyExc_RuntimeError,"Cannot play asynchronously from memory"); - return NULL; + /* Sidestep reference counting headache; unfortunately this also + prevent SND_LOOP from memory. */ + PyErr_SetString(PyExc_RuntimeError,"Cannot play asynchronously from memory"); + return NULL; } Py_BEGIN_ALLOW_THREADS @@ -93,8 +93,8 @@ Py_END_ALLOW_THREADS if(!ok) { - PyErr_SetString(PyExc_RuntimeError,"Failed to play sound"); - return NULL; + PyErr_SetString(PyExc_RuntimeError,"Failed to play sound"); + return NULL; } Py_INCREF(Py_None); @@ -104,40 +104,40 @@ static PyObject * sound_beep(PyObject *self, PyObject *args) { - int freq; - int dur; - BOOL ok; - - if (!PyArg_ParseTuple(args, "ii:Beep", &freq, &dur)) - return NULL; - - if (freq < 37 || freq > 32767) { - PyErr_SetString(PyExc_ValueError, - "frequency must be in 37 thru 32767"); - return NULL; - } - - Py_BEGIN_ALLOW_THREADS - ok = Beep(freq, dur); - Py_END_ALLOW_THREADS - if (!ok) { - PyErr_SetString(PyExc_RuntimeError,"Failed to beep"); - return NULL; - } + int freq; + int dur; + BOOL ok; + + if (!PyArg_ParseTuple(args, "ii:Beep", &freq, &dur)) + return NULL; + + if (freq < 37 || freq > 32767) { + PyErr_SetString(PyExc_ValueError, + "frequency must be in 37 thru 32767"); + return NULL; + } + + Py_BEGIN_ALLOW_THREADS + ok = Beep(freq, dur); + Py_END_ALLOW_THREADS + if (!ok) { + PyErr_SetString(PyExc_RuntimeError,"Failed to beep"); + return NULL; + } - Py_INCREF(Py_None); - return Py_None; + Py_INCREF(Py_None); + return Py_None; } static PyObject * sound_msgbeep(PyObject *self, PyObject *args) { - int x = MB_OK; - if (!PyArg_ParseTuple(args, "|i:MessageBeep", &x)) - return NULL; - MessageBeep(x); - Py_INCREF(Py_None); - return Py_None; + int x = MB_OK; + if (!PyArg_ParseTuple(args, "|i:MessageBeep", &x)) + return NULL; + MessageBeep(x); + Py_INCREF(Py_None); + return Py_None; } static struct PyMethodDef sound_methods[] = @@ -155,7 +155,7 @@ PyObject *v=PyLong_FromLong(value); if(v&&k) { - PyDict_SetItem(dict,k,v); + PyDict_SetItem(dict,k,v); } Py_XDECREF(k); Py_XDECREF(v); @@ -165,41 +165,41 @@ static struct PyModuleDef winsoundmodule = { - PyModuleDef_HEAD_INIT, - "winsound", - sound_module_doc, - -1, - sound_methods, - NULL, - NULL, - NULL, - NULL + PyModuleDef_HEAD_INIT, + "winsound", + sound_module_doc, + -1, + sound_methods, + NULL, + NULL, + NULL, + NULL }; PyMODINIT_FUNC PyInit_winsound(void) { - PyObject *dict; - PyObject *module = PyModule_Create(&winsoundmodule); - if (module == NULL) - return NULL; - dict = PyModule_GetDict(module); - - ADD_DEFINE(SND_ASYNC); - ADD_DEFINE(SND_NODEFAULT); - ADD_DEFINE(SND_NOSTOP); - ADD_DEFINE(SND_NOWAIT); - ADD_DEFINE(SND_ALIAS); - ADD_DEFINE(SND_FILENAME); - ADD_DEFINE(SND_MEMORY); - ADD_DEFINE(SND_PURGE); - ADD_DEFINE(SND_LOOP); - ADD_DEFINE(SND_APPLICATION); - - ADD_DEFINE(MB_OK); - ADD_DEFINE(MB_ICONASTERISK); - ADD_DEFINE(MB_ICONEXCLAMATION); - ADD_DEFINE(MB_ICONHAND); - ADD_DEFINE(MB_ICONQUESTION); - return module; + PyObject *dict; + PyObject *module = PyModule_Create(&winsoundmodule); + if (module == NULL) + return NULL; + dict = PyModule_GetDict(module); + + ADD_DEFINE(SND_ASYNC); + ADD_DEFINE(SND_NODEFAULT); + ADD_DEFINE(SND_NOSTOP); + ADD_DEFINE(SND_NOWAIT); + ADD_DEFINE(SND_ALIAS); + ADD_DEFINE(SND_FILENAME); + ADD_DEFINE(SND_MEMORY); + ADD_DEFINE(SND_PURGE); + ADD_DEFINE(SND_LOOP); + ADD_DEFINE(SND_APPLICATION); + + ADD_DEFINE(MB_OK); + ADD_DEFINE(MB_ICONASTERISK); + ADD_DEFINE(MB_ICONEXCLAMATION); + ADD_DEFINE(MB_ICONHAND); + ADD_DEFINE(MB_ICONQUESTION); + return module; } Modified: python/branches/py3k-jit/PCbuild/make_buildinfo.c ============================================================================== --- python/branches/py3k-jit/PCbuild/make_buildinfo.c (original) +++ python/branches/py3k-jit/PCbuild/make_buildinfo.c Mon May 10 23:55:43 2010 @@ -23,72 +23,72 @@ int make_buildinfo2() { - struct _stat st; - HKEY hTortoise; - char command[CMD_SIZE+1]; - DWORD type, size; - if (_stat(".svn", &st) < 0) - return 0; - /* Allow suppression of subwcrev.exe invocation if a no_subwcrev file is present. */ - if (_stat("no_subwcrev", &st) == 0) - return 0; - if (RegOpenKey(HKEY_LOCAL_MACHINE, "Software\\TortoiseSVN", &hTortoise) != ERROR_SUCCESS && - RegOpenKey(HKEY_CURRENT_USER, "Software\\TortoiseSVN", &hTortoise) != ERROR_SUCCESS) - /* Tortoise not installed */ - return 0; - command[0] = '"'; /* quote the path to the executable */ - size = sizeof(command) - 1; - if (RegQueryValueEx(hTortoise, "Directory", 0, &type, command+1, &size) != ERROR_SUCCESS || - type != REG_SZ) - /* Registry corrupted */ - return 0; - strcat_s(command, CMD_SIZE, "bin\\subwcrev.exe"); - if (_stat(command+1, &st) < 0) - /* subwcrev.exe not part of the release */ - return 0; - strcat_s(command, CMD_SIZE, "\" .. ..\\Modules\\getbuildinfo.c getbuildinfo2.c"); - puts(command); fflush(stdout); - if (system(command) < 0) - return 0; - return 1; + struct _stat st; + HKEY hTortoise; + char command[CMD_SIZE+1]; + DWORD type, size; + if (_stat(".svn", &st) < 0) + return 0; + /* Allow suppression of subwcrev.exe invocation if a no_subwcrev file is present. */ + if (_stat("no_subwcrev", &st) == 0) + return 0; + if (RegOpenKey(HKEY_LOCAL_MACHINE, "Software\\TortoiseSVN", &hTortoise) != ERROR_SUCCESS && + RegOpenKey(HKEY_CURRENT_USER, "Software\\TortoiseSVN", &hTortoise) != ERROR_SUCCESS) + /* Tortoise not installed */ + return 0; + command[0] = '"'; /* quote the path to the executable */ + size = sizeof(command) - 1; + if (RegQueryValueEx(hTortoise, "Directory", 0, &type, command+1, &size) != ERROR_SUCCESS || + type != REG_SZ) + /* Registry corrupted */ + return 0; + strcat_s(command, CMD_SIZE, "bin\\subwcrev.exe"); + if (_stat(command+1, &st) < 0) + /* subwcrev.exe not part of the release */ + return 0; + strcat_s(command, CMD_SIZE, "\" .. ..\\Modules\\getbuildinfo.c getbuildinfo2.c"); + puts(command); fflush(stdout); + if (system(command) < 0) + return 0; + return 1; } int main(int argc, char*argv[]) { - char command[500] = "cl.exe -c -D_WIN32 -DUSE_DL_EXPORT -D_WINDOWS -DWIN32 -D_WINDLL "; - int do_unlink, result; - if (argc != 2) { - fprintf(stderr, "make_buildinfo $(ConfigurationName)\n"); - return EXIT_FAILURE; - } - if (strcmp(argv[1], "Release") == 0) { - strcat_s(command, CMD_SIZE, "-MD "); - } - else if (strcmp(argv[1], "Debug") == 0) { - strcat_s(command, CMD_SIZE, "-D_DEBUG -MDd "); - } - else if (strcmp(argv[1], "ReleaseItanium") == 0) { - strcat_s(command, CMD_SIZE, "-MD /USECL:MS_ITANIUM "); - } - else if (strcmp(argv[1], "ReleaseAMD64") == 0) { - strcat_s(command, CMD_SIZE, "-MD "); - strcat_s(command, CMD_SIZE, "-MD /USECL:MS_OPTERON "); - } - else { - fprintf(stderr, "unsupported configuration %s\n", argv[1]); - return EXIT_FAILURE; - } + char command[500] = "cl.exe -c -D_WIN32 -DUSE_DL_EXPORT -D_WINDOWS -DWIN32 -D_WINDLL "; + int do_unlink, result; + if (argc != 2) { + fprintf(stderr, "make_buildinfo $(ConfigurationName)\n"); + return EXIT_FAILURE; + } + if (strcmp(argv[1], "Release") == 0) { + strcat_s(command, CMD_SIZE, "-MD "); + } + else if (strcmp(argv[1], "Debug") == 0) { + strcat_s(command, CMD_SIZE, "-D_DEBUG -MDd "); + } + else if (strcmp(argv[1], "ReleaseItanium") == 0) { + strcat_s(command, CMD_SIZE, "-MD /USECL:MS_ITANIUM "); + } + else if (strcmp(argv[1], "ReleaseAMD64") == 0) { + strcat_s(command, CMD_SIZE, "-MD "); + strcat_s(command, CMD_SIZE, "-MD /USECL:MS_OPTERON "); + } + else { + fprintf(stderr, "unsupported configuration %s\n", argv[1]); + return EXIT_FAILURE; + } - if ((do_unlink = make_buildinfo2())) - strcat_s(command, CMD_SIZE, "getbuildinfo2.c -DSUBWCREV "); - else - strcat_s(command, CMD_SIZE, "..\\Modules\\getbuildinfo.c"); - strcat_s(command, CMD_SIZE, " -Fogetbuildinfo.o -I..\\Include -I..\\PC"); - puts(command); fflush(stdout); - result = system(command); - if (do_unlink) - _unlink("getbuildinfo2.c"); - if (result < 0) - return EXIT_FAILURE; - return 0; -} \ No newline at end of file + if ((do_unlink = make_buildinfo2())) + strcat_s(command, CMD_SIZE, "getbuildinfo2.c -DSUBWCREV "); + else + strcat_s(command, CMD_SIZE, "..\\Modules\\getbuildinfo.c"); + strcat_s(command, CMD_SIZE, " -Fogetbuildinfo.o -I..\\Include -I..\\PC"); + puts(command); fflush(stdout); + result = system(command); + if (do_unlink) + _unlink("getbuildinfo2.c"); + if (result < 0) + return EXIT_FAILURE; + return 0; +} Modified: python/branches/py3k-jit/Parser/acceler.c ============================================================================== --- python/branches/py3k-jit/Parser/acceler.c (original) +++ python/branches/py3k-jit/Parser/acceler.c Mon May 10 23:55:43 2010 @@ -23,103 +23,103 @@ void PyGrammar_AddAccelerators(grammar *g) { - dfa *d; - int i; - d = g->g_dfa; - for (i = g->g_ndfas; --i >= 0; d++) - fixdfa(g, d); - g->g_accel = 1; + dfa *d; + int i; + d = g->g_dfa; + for (i = g->g_ndfas; --i >= 0; d++) + fixdfa(g, d); + g->g_accel = 1; } void PyGrammar_RemoveAccelerators(grammar *g) { - dfa *d; - int i; - g->g_accel = 0; - d = g->g_dfa; - for (i = g->g_ndfas; --i >= 0; d++) { - state *s; - int j; - s = d->d_state; - for (j = 0; j < d->d_nstates; j++, s++) { - if (s->s_accel) - PyObject_FREE(s->s_accel); - s->s_accel = NULL; - } - } + dfa *d; + int i; + g->g_accel = 0; + d = g->g_dfa; + for (i = g->g_ndfas; --i >= 0; d++) { + state *s; + int j; + s = d->d_state; + for (j = 0; j < d->d_nstates; j++, s++) { + if (s->s_accel) + PyObject_FREE(s->s_accel); + s->s_accel = NULL; + } + } } static void fixdfa(grammar *g, dfa *d) { - state *s; - int j; - s = d->d_state; - for (j = 0; j < d->d_nstates; j++, s++) - fixstate(g, s); + state *s; + int j; + s = d->d_state; + for (j = 0; j < d->d_nstates; j++, s++) + fixstate(g, s); } static void fixstate(grammar *g, state *s) { - arc *a; - int k; - int *accel; - int nl = g->g_ll.ll_nlabels; - s->s_accept = 0; - accel = (int *) PyObject_MALLOC(nl * sizeof(int)); - if (accel == NULL) { - fprintf(stderr, "no mem to build parser accelerators\n"); - exit(1); - } - for (k = 0; k < nl; k++) - accel[k] = -1; - a = s->s_arc; - for (k = s->s_narcs; --k >= 0; a++) { - int lbl = a->a_lbl; - label *l = &g->g_ll.ll_label[lbl]; - int type = l->lb_type; - if (a->a_arrow >= (1 << 7)) { - printf("XXX too many states!\n"); - continue; - } - if (ISNONTERMINAL(type)) { - dfa *d1 = PyGrammar_FindDFA(g, type); - int ibit; - if (type - NT_OFFSET >= (1 << 7)) { - printf("XXX too high nonterminal number!\n"); - continue; - } - for (ibit = 0; ibit < g->g_ll.ll_nlabels; ibit++) { - if (testbit(d1->d_first, ibit)) { - if (accel[ibit] != -1) - printf("XXX ambiguity!\n"); - accel[ibit] = a->a_arrow | (1 << 7) | - ((type - NT_OFFSET) << 8); - } - } - } - else if (lbl == EMPTY) - s->s_accept = 1; - else if (lbl >= 0 && lbl < nl) - accel[lbl] = a->a_arrow; - } - while (nl > 0 && accel[nl-1] == -1) - nl--; - for (k = 0; k < nl && accel[k] == -1;) - k++; - if (k < nl) { - int i; - s->s_accel = (int *) PyObject_MALLOC((nl-k) * sizeof(int)); - if (s->s_accel == NULL) { - fprintf(stderr, "no mem to add parser accelerators\n"); - exit(1); - } - s->s_lower = k; - s->s_upper = nl; - for (i = 0; k < nl; i++, k++) - s->s_accel[i] = accel[k]; - } - PyObject_FREE(accel); + arc *a; + int k; + int *accel; + int nl = g->g_ll.ll_nlabels; + s->s_accept = 0; + accel = (int *) PyObject_MALLOC(nl * sizeof(int)); + if (accel == NULL) { + fprintf(stderr, "no mem to build parser accelerators\n"); + exit(1); + } + for (k = 0; k < nl; k++) + accel[k] = -1; + a = s->s_arc; + for (k = s->s_narcs; --k >= 0; a++) { + int lbl = a->a_lbl; + label *l = &g->g_ll.ll_label[lbl]; + int type = l->lb_type; + if (a->a_arrow >= (1 << 7)) { + printf("XXX too many states!\n"); + continue; + } + if (ISNONTERMINAL(type)) { + dfa *d1 = PyGrammar_FindDFA(g, type); + int ibit; + if (type - NT_OFFSET >= (1 << 7)) { + printf("XXX too high nonterminal number!\n"); + continue; + } + for (ibit = 0; ibit < g->g_ll.ll_nlabels; ibit++) { + if (testbit(d1->d_first, ibit)) { + if (accel[ibit] != -1) + printf("XXX ambiguity!\n"); + accel[ibit] = a->a_arrow | (1 << 7) | + ((type - NT_OFFSET) << 8); + } + } + } + else if (lbl == EMPTY) + s->s_accept = 1; + else if (lbl >= 0 && lbl < nl) + accel[lbl] = a->a_arrow; + } + while (nl > 0 && accel[nl-1] == -1) + nl--; + for (k = 0; k < nl && accel[k] == -1;) + k++; + if (k < nl) { + int i; + s->s_accel = (int *) PyObject_MALLOC((nl-k) * sizeof(int)); + if (s->s_accel == NULL) { + fprintf(stderr, "no mem to add parser accelerators\n"); + exit(1); + } + s->s_lower = k; + s->s_upper = nl; + for (i = 0; k < nl; i++, k++) + s->s_accel[i] = accel[k]; + } + PyObject_FREE(accel); } Modified: python/branches/py3k-jit/Parser/bitset.c ============================================================================== --- python/branches/py3k-jit/Parser/bitset.c (original) +++ python/branches/py3k-jit/Parser/bitset.c Mon May 10 23:55:43 2010 @@ -7,60 +7,60 @@ bitset newbitset(int nbits) { - int nbytes = NBYTES(nbits); - bitset ss = (char *)PyObject_MALLOC(sizeof(BYTE) * nbytes); - - if (ss == NULL) - Py_FatalError("no mem for bitset"); - - ss += nbytes; - while (--nbytes >= 0) - *--ss = 0; - return ss; + int nbytes = NBYTES(nbits); + bitset ss = (char *)PyObject_MALLOC(sizeof(BYTE) * nbytes); + + if (ss == NULL) + Py_FatalError("no mem for bitset"); + + ss += nbytes; + while (--nbytes >= 0) + *--ss = 0; + return ss; } void delbitset(bitset ss) { - PyObject_FREE(ss); + PyObject_FREE(ss); } int addbit(bitset ss, int ibit) { - int ibyte = BIT2BYTE(ibit); - BYTE mask = BIT2MASK(ibit); - - if (ss[ibyte] & mask) - return 0; /* Bit already set */ - ss[ibyte] |= mask; - return 1; + int ibyte = BIT2BYTE(ibit); + BYTE mask = BIT2MASK(ibit); + + if (ss[ibyte] & mask) + return 0; /* Bit already set */ + ss[ibyte] |= mask; + return 1; } #if 0 /* Now a macro */ int testbit(bitset ss, int ibit) { - return (ss[BIT2BYTE(ibit)] & BIT2MASK(ibit)) != 0; + return (ss[BIT2BYTE(ibit)] & BIT2MASK(ibit)) != 0; } #endif int samebitset(bitset ss1, bitset ss2, int nbits) { - int i; - - for (i = NBYTES(nbits); --i >= 0; ) - if (*ss1++ != *ss2++) - return 0; - return 1; + int i; + + for (i = NBYTES(nbits); --i >= 0; ) + if (*ss1++ != *ss2++) + return 0; + return 1; } void mergebitset(bitset ss1, bitset ss2, int nbits) { - int i; - - for (i = NBYTES(nbits); --i >= 0; ) - *ss1++ |= *ss2++; + int i; + + for (i = NBYTES(nbits); --i >= 0; ) + *ss1++ |= *ss2++; } Modified: python/branches/py3k-jit/Parser/firstsets.c ============================================================================== --- python/branches/py3k-jit/Parser/firstsets.c (original) +++ python/branches/py3k-jit/Parser/firstsets.c Mon May 10 23:55:43 2010 @@ -13,101 +13,101 @@ void addfirstsets(grammar *g) { - int i; - dfa *d; + int i; + dfa *d; - if (Py_DebugFlag) - printf("Adding FIRST sets ...\n"); - for (i = 0; i < g->g_ndfas; i++) { - d = &g->g_dfa[i]; - if (d->d_first == NULL) - calcfirstset(g, d); - } + if (Py_DebugFlag) + printf("Adding FIRST sets ...\n"); + for (i = 0; i < g->g_ndfas; i++) { + d = &g->g_dfa[i]; + if (d->d_first == NULL) + calcfirstset(g, d); + } } static void calcfirstset(grammar *g, dfa *d) { - int i, j; - state *s; - arc *a; - int nsyms; - int *sym; - int nbits; - static bitset dummy; - bitset result; - int type; - dfa *d1; - label *l0; - - if (Py_DebugFlag) - printf("Calculate FIRST set for '%s'\n", d->d_name); - - if (dummy == NULL) - dummy = newbitset(1); - if (d->d_first == dummy) { - fprintf(stderr, "Left-recursion for '%s'\n", d->d_name); - return; - } - if (d->d_first != NULL) { - fprintf(stderr, "Re-calculating FIRST set for '%s' ???\n", - d->d_name); - } - d->d_first = dummy; - - l0 = g->g_ll.ll_label; - nbits = g->g_ll.ll_nlabels; - result = newbitset(nbits); - - sym = (int *)PyObject_MALLOC(sizeof(int)); - if (sym == NULL) - Py_FatalError("no mem for new sym in calcfirstset"); - nsyms = 1; - sym[0] = findlabel(&g->g_ll, d->d_type, (char *)NULL); - - s = &d->d_state[d->d_initial]; - for (i = 0; i < s->s_narcs; i++) { - a = &s->s_arc[i]; - for (j = 0; j < nsyms; j++) { - if (sym[j] == a->a_lbl) - break; - } - if (j >= nsyms) { /* New label */ - sym = (int *)PyObject_REALLOC(sym, - sizeof(int) * (nsyms + 1)); - if (sym == NULL) - Py_FatalError( - "no mem to resize sym in calcfirstset"); - sym[nsyms++] = a->a_lbl; - type = l0[a->a_lbl].lb_type; - if (ISNONTERMINAL(type)) { - d1 = PyGrammar_FindDFA(g, type); - if (d1->d_first == dummy) { - fprintf(stderr, - "Left-recursion below '%s'\n", - d->d_name); - } - else { - if (d1->d_first == NULL) - calcfirstset(g, d1); - mergebitset(result, - d1->d_first, nbits); - } - } - else if (ISTERMINAL(type)) { - addbit(result, a->a_lbl); - } - } - } - d->d_first = result; - if (Py_DebugFlag) { - printf("FIRST set for '%s': {", d->d_name); - for (i = 0; i < nbits; i++) { - if (testbit(result, i)) - printf(" %s", PyGrammar_LabelRepr(&l0[i])); - } - printf(" }\n"); - } + int i, j; + state *s; + arc *a; + int nsyms; + int *sym; + int nbits; + static bitset dummy; + bitset result; + int type; + dfa *d1; + label *l0; - PyObject_FREE(sym); + if (Py_DebugFlag) + printf("Calculate FIRST set for '%s'\n", d->d_name); + + if (dummy == NULL) + dummy = newbitset(1); + if (d->d_first == dummy) { + fprintf(stderr, "Left-recursion for '%s'\n", d->d_name); + return; + } + if (d->d_first != NULL) { + fprintf(stderr, "Re-calculating FIRST set for '%s' ???\n", + d->d_name); + } + d->d_first = dummy; + + l0 = g->g_ll.ll_label; + nbits = g->g_ll.ll_nlabels; + result = newbitset(nbits); + + sym = (int *)PyObject_MALLOC(sizeof(int)); + if (sym == NULL) + Py_FatalError("no mem for new sym in calcfirstset"); + nsyms = 1; + sym[0] = findlabel(&g->g_ll, d->d_type, (char *)NULL); + + s = &d->d_state[d->d_initial]; + for (i = 0; i < s->s_narcs; i++) { + a = &s->s_arc[i]; + for (j = 0; j < nsyms; j++) { + if (sym[j] == a->a_lbl) + break; + } + if (j >= nsyms) { /* New label */ + sym = (int *)PyObject_REALLOC(sym, + sizeof(int) * (nsyms + 1)); + if (sym == NULL) + Py_FatalError( + "no mem to resize sym in calcfirstset"); + sym[nsyms++] = a->a_lbl; + type = l0[a->a_lbl].lb_type; + if (ISNONTERMINAL(type)) { + d1 = PyGrammar_FindDFA(g, type); + if (d1->d_first == dummy) { + fprintf(stderr, + "Left-recursion below '%s'\n", + d->d_name); + } + else { + if (d1->d_first == NULL) + calcfirstset(g, d1); + mergebitset(result, + d1->d_first, nbits); + } + } + else if (ISTERMINAL(type)) { + addbit(result, a->a_lbl); + } + } + } + d->d_first = result; + if (Py_DebugFlag) { + printf("FIRST set for '%s': {", d->d_name); + for (i = 0; i < nbits; i++) { + if (testbit(result, i)) + printf(" %s", PyGrammar_LabelRepr(&l0[i])); + } + printf(" }\n"); + } + + PyObject_FREE(sym); } Modified: python/branches/py3k-jit/Parser/grammar.c ============================================================================== --- python/branches/py3k-jit/Parser/grammar.c (original) +++ python/branches/py3k-jit/Parser/grammar.c Mon May 10 23:55:43 2010 @@ -14,98 +14,98 @@ grammar * newgrammar(int start) { - grammar *g; - - g = (grammar *)PyObject_MALLOC(sizeof(grammar)); - if (g == NULL) - Py_FatalError("no mem for new grammar"); - g->g_ndfas = 0; - g->g_dfa = NULL; - g->g_start = start; - g->g_ll.ll_nlabels = 0; - g->g_ll.ll_label = NULL; - g->g_accel = 0; - return g; + grammar *g; + + g = (grammar *)PyObject_MALLOC(sizeof(grammar)); + if (g == NULL) + Py_FatalError("no mem for new grammar"); + g->g_ndfas = 0; + g->g_dfa = NULL; + g->g_start = start; + g->g_ll.ll_nlabels = 0; + g->g_ll.ll_label = NULL; + g->g_accel = 0; + return g; } dfa * adddfa(grammar *g, int type, char *name) { - dfa *d; - - g->g_dfa = (dfa *)PyObject_REALLOC(g->g_dfa, - sizeof(dfa) * (g->g_ndfas + 1)); - if (g->g_dfa == NULL) - Py_FatalError("no mem to resize dfa in adddfa"); - d = &g->g_dfa[g->g_ndfas++]; - d->d_type = type; - d->d_name = strdup(name); - d->d_nstates = 0; - d->d_state = NULL; - d->d_initial = -1; - d->d_first = NULL; - return d; /* Only use while fresh! */ + dfa *d; + + g->g_dfa = (dfa *)PyObject_REALLOC(g->g_dfa, + sizeof(dfa) * (g->g_ndfas + 1)); + if (g->g_dfa == NULL) + Py_FatalError("no mem to resize dfa in adddfa"); + d = &g->g_dfa[g->g_ndfas++]; + d->d_type = type; + d->d_name = strdup(name); + d->d_nstates = 0; + d->d_state = NULL; + d->d_initial = -1; + d->d_first = NULL; + return d; /* Only use while fresh! */ } int addstate(dfa *d) { - state *s; - - d->d_state = (state *)PyObject_REALLOC(d->d_state, - sizeof(state) * (d->d_nstates + 1)); - if (d->d_state == NULL) - Py_FatalError("no mem to resize state in addstate"); - s = &d->d_state[d->d_nstates++]; - s->s_narcs = 0; - s->s_arc = NULL; - s->s_lower = 0; - s->s_upper = 0; - s->s_accel = NULL; - s->s_accept = 0; - return s - d->d_state; + state *s; + + d->d_state = (state *)PyObject_REALLOC(d->d_state, + sizeof(state) * (d->d_nstates + 1)); + if (d->d_state == NULL) + Py_FatalError("no mem to resize state in addstate"); + s = &d->d_state[d->d_nstates++]; + s->s_narcs = 0; + s->s_arc = NULL; + s->s_lower = 0; + s->s_upper = 0; + s->s_accel = NULL; + s->s_accept = 0; + return s - d->d_state; } void addarc(dfa *d, int from, int to, int lbl) { - state *s; - arc *a; - - assert(0 <= from && from < d->d_nstates); - assert(0 <= to && to < d->d_nstates); - - s = &d->d_state[from]; - s->s_arc = (arc *)PyObject_REALLOC(s->s_arc, sizeof(arc) * (s->s_narcs + 1)); - if (s->s_arc == NULL) - Py_FatalError("no mem to resize arc list in addarc"); - a = &s->s_arc[s->s_narcs++]; - a->a_lbl = lbl; - a->a_arrow = to; + state *s; + arc *a; + + assert(0 <= from && from < d->d_nstates); + assert(0 <= to && to < d->d_nstates); + + s = &d->d_state[from]; + s->s_arc = (arc *)PyObject_REALLOC(s->s_arc, sizeof(arc) * (s->s_narcs + 1)); + if (s->s_arc == NULL) + Py_FatalError("no mem to resize arc list in addarc"); + a = &s->s_arc[s->s_narcs++]; + a->a_lbl = lbl; + a->a_arrow = to; } int addlabel(labellist *ll, int type, char *str) { - int i; - label *lb; - - for (i = 0; i < ll->ll_nlabels; i++) { - if (ll->ll_label[i].lb_type == type && - strcmp(ll->ll_label[i].lb_str, str) == 0) - return i; - } - ll->ll_label = (label *)PyObject_REALLOC(ll->ll_label, - sizeof(label) * (ll->ll_nlabels + 1)); - if (ll->ll_label == NULL) - Py_FatalError("no mem to resize labellist in addlabel"); - lb = &ll->ll_label[ll->ll_nlabels++]; - lb->lb_type = type; - lb->lb_str = strdup(str); - if (Py_DebugFlag) - printf("Label @ %8p, %d: %s\n", ll, ll->ll_nlabels, - PyGrammar_LabelRepr(lb)); - return lb - ll->ll_label; + int i; + label *lb; + + for (i = 0; i < ll->ll_nlabels; i++) { + if (ll->ll_label[i].lb_type == type && + strcmp(ll->ll_label[i].lb_str, str) == 0) + return i; + } + ll->ll_label = (label *)PyObject_REALLOC(ll->ll_label, + sizeof(label) * (ll->ll_nlabels + 1)); + if (ll->ll_label == NULL) + Py_FatalError("no mem to resize labellist in addlabel"); + lb = &ll->ll_label[ll->ll_nlabels++]; + lb->lb_type = type; + lb->lb_str = strdup(str); + if (Py_DebugFlag) + printf("Label @ %8p, %d: %s\n", ll, ll->ll_nlabels, + PyGrammar_LabelRepr(lb)); + return lb - ll->ll_label; } /* Same, but rather dies than adds */ @@ -113,16 +113,16 @@ int findlabel(labellist *ll, int type, char *str) { - int i; - - for (i = 0; i < ll->ll_nlabels; i++) { - if (ll->ll_label[i].lb_type == type /*&& - strcmp(ll->ll_label[i].lb_str, str) == 0*/) - return i; - } - fprintf(stderr, "Label %d/'%s' not found\n", type, str); - Py_FatalError("grammar.c:findlabel()"); - return 0; /* Make gcc -Wall happy */ + int i; + + for (i = 0; i < ll->ll_nlabels; i++) { + if (ll->ll_label[i].lb_type == type /*&& + strcmp(ll->ll_label[i].lb_str, str) == 0*/) + return i; + } + fprintf(stderr, "Label %d/'%s' not found\n", type, str); + Py_FatalError("grammar.c:findlabel()"); + return 0; /* Make gcc -Wall happy */ } /* Forward */ @@ -131,120 +131,120 @@ void translatelabels(grammar *g) { - int i; + int i; #ifdef Py_DEBUG - printf("Translating labels ...\n"); + printf("Translating labels ...\n"); #endif - /* Don't translate EMPTY */ - for (i = EMPTY+1; i < g->g_ll.ll_nlabels; i++) - translabel(g, &g->g_ll.ll_label[i]); + /* Don't translate EMPTY */ + for (i = EMPTY+1; i < g->g_ll.ll_nlabels; i++) + translabel(g, &g->g_ll.ll_label[i]); } static void translabel(grammar *g, label *lb) { - int i; - - if (Py_DebugFlag) - printf("Translating label %s ...\n", PyGrammar_LabelRepr(lb)); - - if (lb->lb_type == NAME) { - for (i = 0; i < g->g_ndfas; i++) { - if (strcmp(lb->lb_str, g->g_dfa[i].d_name) == 0) { - if (Py_DebugFlag) - printf( - "Label %s is non-terminal %d.\n", - lb->lb_str, - g->g_dfa[i].d_type); - lb->lb_type = g->g_dfa[i].d_type; - free(lb->lb_str); - lb->lb_str = NULL; - return; - } - } - for (i = 0; i < (int)N_TOKENS; i++) { - if (strcmp(lb->lb_str, _PyParser_TokenNames[i]) == 0) { - if (Py_DebugFlag) - printf("Label %s is terminal %d.\n", - lb->lb_str, i); - lb->lb_type = i; - free(lb->lb_str); - lb->lb_str = NULL; - return; - } - } - printf("Can't translate NAME label '%s'\n", lb->lb_str); - return; - } - - if (lb->lb_type == STRING) { - if (isalpha(Py_CHARMASK(lb->lb_str[1])) || - lb->lb_str[1] == '_') { - char *p; - char *src; - char *dest; - size_t name_len; - if (Py_DebugFlag) - printf("Label %s is a keyword\n", lb->lb_str); - lb->lb_type = NAME; - src = lb->lb_str + 1; - p = strchr(src, '\''); - if (p) - name_len = p - src; - else - name_len = strlen(src); - dest = (char *)malloc(name_len + 1); - if (!dest) { - printf("Can't alloc dest '%s'\n", src); - return; - } - strncpy(dest, src, name_len); - dest[name_len] = '\0'; - free(lb->lb_str); - lb->lb_str = dest; - } - else if (lb->lb_str[2] == lb->lb_str[0]) { - int type = (int) PyToken_OneChar(lb->lb_str[1]); - if (type != OP) { - lb->lb_type = type; - free(lb->lb_str); - lb->lb_str = NULL; - } - else - printf("Unknown OP label %s\n", - lb->lb_str); - } - else if (lb->lb_str[2] && lb->lb_str[3] == lb->lb_str[0]) { - int type = (int) PyToken_TwoChars(lb->lb_str[1], - lb->lb_str[2]); - if (type != OP) { - lb->lb_type = type; - free(lb->lb_str); - lb->lb_str = NULL; - } - else - printf("Unknown OP label %s\n", - lb->lb_str); - } - else if (lb->lb_str[2] && lb->lb_str[3] && lb->lb_str[4] == lb->lb_str[0]) { - int type = (int) PyToken_ThreeChars(lb->lb_str[1], - lb->lb_str[2], - lb->lb_str[3]); - if (type != OP) { - lb->lb_type = type; - free(lb->lb_str); - lb->lb_str = NULL; - } - else - printf("Unknown OP label %s\n", - lb->lb_str); - } - else - printf("Can't translate STRING label %s\n", - lb->lb_str); - } - else - printf("Can't translate label '%s'\n", - PyGrammar_LabelRepr(lb)); + int i; + + if (Py_DebugFlag) + printf("Translating label %s ...\n", PyGrammar_LabelRepr(lb)); + + if (lb->lb_type == NAME) { + for (i = 0; i < g->g_ndfas; i++) { + if (strcmp(lb->lb_str, g->g_dfa[i].d_name) == 0) { + if (Py_DebugFlag) + printf( + "Label %s is non-terminal %d.\n", + lb->lb_str, + g->g_dfa[i].d_type); + lb->lb_type = g->g_dfa[i].d_type; + free(lb->lb_str); + lb->lb_str = NULL; + return; + } + } + for (i = 0; i < (int)N_TOKENS; i++) { + if (strcmp(lb->lb_str, _PyParser_TokenNames[i]) == 0) { + if (Py_DebugFlag) + printf("Label %s is terminal %d.\n", + lb->lb_str, i); + lb->lb_type = i; + free(lb->lb_str); + lb->lb_str = NULL; + return; + } + } + printf("Can't translate NAME label '%s'\n", lb->lb_str); + return; + } + + if (lb->lb_type == STRING) { + if (isalpha(Py_CHARMASK(lb->lb_str[1])) || + lb->lb_str[1] == '_') { + char *p; + char *src; + char *dest; + size_t name_len; + if (Py_DebugFlag) + printf("Label %s is a keyword\n", lb->lb_str); + lb->lb_type = NAME; + src = lb->lb_str + 1; + p = strchr(src, '\''); + if (p) + name_len = p - src; + else + name_len = strlen(src); + dest = (char *)malloc(name_len + 1); + if (!dest) { + printf("Can't alloc dest '%s'\n", src); + return; + } + strncpy(dest, src, name_len); + dest[name_len] = '\0'; + free(lb->lb_str); + lb->lb_str = dest; + } + else if (lb->lb_str[2] == lb->lb_str[0]) { + int type = (int) PyToken_OneChar(lb->lb_str[1]); + if (type != OP) { + lb->lb_type = type; + free(lb->lb_str); + lb->lb_str = NULL; + } + else + printf("Unknown OP label %s\n", + lb->lb_str); + } + else if (lb->lb_str[2] && lb->lb_str[3] == lb->lb_str[0]) { + int type = (int) PyToken_TwoChars(lb->lb_str[1], + lb->lb_str[2]); + if (type != OP) { + lb->lb_type = type; + free(lb->lb_str); + lb->lb_str = NULL; + } + else + printf("Unknown OP label %s\n", + lb->lb_str); + } + else if (lb->lb_str[2] && lb->lb_str[3] && lb->lb_str[4] == lb->lb_str[0]) { + int type = (int) PyToken_ThreeChars(lb->lb_str[1], + lb->lb_str[2], + lb->lb_str[3]); + if (type != OP) { + lb->lb_type = type; + free(lb->lb_str); + lb->lb_str = NULL; + } + else + printf("Unknown OP label %s\n", + lb->lb_str); + } + else + printf("Can't translate STRING label %s\n", + lb->lb_str); + } + else + printf("Can't translate label '%s'\n", + PyGrammar_LabelRepr(lb)); } Modified: python/branches/py3k-jit/Parser/grammar1.c ============================================================================== --- python/branches/py3k-jit/Parser/grammar1.c (original) +++ python/branches/py3k-jit/Parser/grammar1.c Mon May 10 23:55:43 2010 @@ -11,47 +11,47 @@ dfa * PyGrammar_FindDFA(grammar *g, register int type) { - register dfa *d; + register dfa *d; #if 1 - /* Massive speed-up */ - d = &g->g_dfa[type - NT_OFFSET]; - assert(d->d_type == type); - return d; + /* Massive speed-up */ + d = &g->g_dfa[type - NT_OFFSET]; + assert(d->d_type == type); + return d; #else - /* Old, slow version */ - register int i; - - for (i = g->g_ndfas, d = g->g_dfa; --i >= 0; d++) { - if (d->d_type == type) - return d; - } - assert(0); - /* NOTREACHED */ + /* Old, slow version */ + register int i; + + for (i = g->g_ndfas, d = g->g_dfa; --i >= 0; d++) { + if (d->d_type == type) + return d; + } + assert(0); + /* NOTREACHED */ #endif } char * PyGrammar_LabelRepr(label *lb) { - static char buf[100]; - - if (lb->lb_type == ENDMARKER) - return "EMPTY"; - else if (ISNONTERMINAL(lb->lb_type)) { - if (lb->lb_str == NULL) { - PyOS_snprintf(buf, sizeof(buf), "NT%d", lb->lb_type); - return buf; - } - else - return lb->lb_str; - } - else { - if (lb->lb_str == NULL) - return _PyParser_TokenNames[lb->lb_type]; - else { - PyOS_snprintf(buf, sizeof(buf), "%.32s(%.32s)", - _PyParser_TokenNames[lb->lb_type], lb->lb_str); - return buf; - } - } + static char buf[100]; + + if (lb->lb_type == ENDMARKER) + return "EMPTY"; + else if (ISNONTERMINAL(lb->lb_type)) { + if (lb->lb_str == NULL) { + PyOS_snprintf(buf, sizeof(buf), "NT%d", lb->lb_type); + return buf; + } + else + return lb->lb_str; + } + else { + if (lb->lb_str == NULL) + return _PyParser_TokenNames[lb->lb_type]; + else { + PyOS_snprintf(buf, sizeof(buf), "%.32s(%.32s)", + _PyParser_TokenNames[lb->lb_type], lb->lb_str); + return buf; + } + } } Modified: python/branches/py3k-jit/Parser/intrcheck.c ============================================================================== --- python/branches/py3k-jit/Parser/intrcheck.c (original) +++ python/branches/py3k-jit/Parser/intrcheck.c Mon May 10 23:55:43 2010 @@ -21,7 +21,7 @@ int PyOS_InterruptOccurred(void) { - _wyield(); + _wyield(); } #define OK @@ -47,7 +47,7 @@ void PyOS_InitInterrupts(void) { - _go32_want_ctrl_break(1 /* TRUE */); + _go32_want_ctrl_break(1 /* TRUE */); } void @@ -58,7 +58,7 @@ int PyOS_InterruptOccurred(void) { - return _go32_was_ctrl_break_hit(); + return _go32_was_ctrl_break_hit(); } #else /* !__GNUC__ */ @@ -78,12 +78,12 @@ int PyOS_InterruptOccurred(void) { - int interrupted = 0; - while (kbhit()) { - if (getch() == '\003') - interrupted = 1; - } - return interrupted; + int interrupted = 0; + while (kbhit()) { + if (getch() == '\003') + interrupted = 1; + } + return interrupted; } #endif /* __GNUC__ */ @@ -106,7 +106,7 @@ void PyErr_SetInterrupt(void) { - interrupted = 1; + interrupted = 1; } extern int PyErr_CheckSignals(void); @@ -114,28 +114,28 @@ static int checksignals_witharg(void * arg) { - return PyErr_CheckSignals(); + return PyErr_CheckSignals(); } static void intcatcher(int sig) { - extern void Py_Exit(int); - static char message[] = + extern void Py_Exit(int); + static char message[] = "python: to interrupt a truly hanging Python program, interrupt once more.\n"; - switch (interrupted++) { - case 0: - break; - case 1: - write(2, message, strlen(message)); - break; - case 2: - interrupted = 0; - Py_Exit(1); - break; - } - PyOS_setsig(SIGINT, intcatcher); - Py_AddPendingCall(checksignals_witharg, NULL); + switch (interrupted++) { + case 0: + break; + case 1: + write(2, message, strlen(message)); + break; + case 2: + interrupted = 0; + Py_Exit(1); + break; + } + PyOS_setsig(SIGINT, intcatcher); + Py_AddPendingCall(checksignals_witharg, NULL); } static void (*old_siginthandler)(int) = SIG_DFL; @@ -143,23 +143,23 @@ void PyOS_InitInterrupts(void) { - if ((old_siginthandler = PyOS_setsig(SIGINT, SIG_IGN)) != SIG_IGN) - PyOS_setsig(SIGINT, intcatcher); + if ((old_siginthandler = PyOS_setsig(SIGINT, SIG_IGN)) != SIG_IGN) + PyOS_setsig(SIGINT, intcatcher); } void PyOS_FiniInterrupts(void) { - PyOS_setsig(SIGINT, old_siginthandler); + PyOS_setsig(SIGINT, old_siginthandler); } int PyOS_InterruptOccurred(void) { - if (!interrupted) - return 0; - interrupted = 0; - return 1; + if (!interrupted) + return 0; + interrupted = 0; + return 1; } #endif /* !OK */ @@ -168,7 +168,7 @@ PyOS_AfterFork(void) { #ifdef WITH_THREAD - PyEval_ReInitThreads(); - PyThread_ReInitTLS(); + PyEval_ReInitThreads(); + PyThread_ReInitTLS(); #endif } Modified: python/branches/py3k-jit/Parser/listnode.c ============================================================================== --- python/branches/py3k-jit/Parser/listnode.c (original) +++ python/branches/py3k-jit/Parser/listnode.c Mon May 10 23:55:43 2010 @@ -12,7 +12,7 @@ void PyNode_ListTree(node *n) { - listnode(stdout, n); + listnode(stdout, n); } static int level, atbol; @@ -20,47 +20,47 @@ static void listnode(FILE *fp, node *n) { - level = 0; - atbol = 1; - list1node(fp, n); + level = 0; + atbol = 1; + list1node(fp, n); } static void list1node(FILE *fp, node *n) { - if (n == 0) - return; - if (ISNONTERMINAL(TYPE(n))) { - int i; - for (i = 0; i < NCH(n); i++) - list1node(fp, CHILD(n, i)); - } - else if (ISTERMINAL(TYPE(n))) { - switch (TYPE(n)) { - case INDENT: - ++level; - break; - case DEDENT: - --level; - break; - default: - if (atbol) { - int i; - for (i = 0; i < level; ++i) - fprintf(fp, "\t"); - atbol = 0; - } - if (TYPE(n) == NEWLINE) { - if (STR(n) != NULL) - fprintf(fp, "%s", STR(n)); - fprintf(fp, "\n"); - atbol = 1; - } - else - fprintf(fp, "%s ", STR(n)); - break; - } - } - else - fprintf(fp, "? "); + if (n == 0) + return; + if (ISNONTERMINAL(TYPE(n))) { + int i; + for (i = 0; i < NCH(n); i++) + list1node(fp, CHILD(n, i)); + } + else if (ISTERMINAL(TYPE(n))) { + switch (TYPE(n)) { + case INDENT: + ++level; + break; + case DEDENT: + --level; + break; + default: + if (atbol) { + int i; + for (i = 0; i < level; ++i) + fprintf(fp, "\t"); + atbol = 0; + } + if (TYPE(n) == NEWLINE) { + if (STR(n) != NULL) + fprintf(fp, "%s", STR(n)); + fprintf(fp, "\n"); + atbol = 1; + } + else + fprintf(fp, "%s ", STR(n)); + break; + } + } + else + fprintf(fp, "? "); } Modified: python/branches/py3k-jit/Parser/metagrammar.c ============================================================================== --- python/branches/py3k-jit/Parser/metagrammar.c (original) +++ python/branches/py3k-jit/Parser/metagrammar.c Mon May 10 23:55:43 2010 @@ -4,152 +4,152 @@ #include "grammar.h" #include "pgen.h" static arc arcs_0_0[3] = { - {2, 0}, - {3, 0}, - {4, 1}, + {2, 0}, + {3, 0}, + {4, 1}, }; static arc arcs_0_1[1] = { - {0, 1}, + {0, 1}, }; static state states_0[2] = { - {3, arcs_0_0}, - {1, arcs_0_1}, + {3, arcs_0_0}, + {1, arcs_0_1}, }; static arc arcs_1_0[1] = { - {5, 1}, + {5, 1}, }; static arc arcs_1_1[1] = { - {6, 2}, + {6, 2}, }; static arc arcs_1_2[1] = { - {7, 3}, + {7, 3}, }; static arc arcs_1_3[1] = { - {3, 4}, + {3, 4}, }; static arc arcs_1_4[1] = { - {0, 4}, + {0, 4}, }; static state states_1[5] = { - {1, arcs_1_0}, - {1, arcs_1_1}, - {1, arcs_1_2}, - {1, arcs_1_3}, - {1, arcs_1_4}, + {1, arcs_1_0}, + {1, arcs_1_1}, + {1, arcs_1_2}, + {1, arcs_1_3}, + {1, arcs_1_4}, }; static arc arcs_2_0[1] = { - {8, 1}, + {8, 1}, }; static arc arcs_2_1[2] = { - {9, 0}, - {0, 1}, + {9, 0}, + {0, 1}, }; static state states_2[2] = { - {1, arcs_2_0}, - {2, arcs_2_1}, + {1, arcs_2_0}, + {2, arcs_2_1}, }; static arc arcs_3_0[1] = { - {10, 1}, + {10, 1}, }; static arc arcs_3_1[2] = { - {10, 1}, - {0, 1}, + {10, 1}, + {0, 1}, }; static state states_3[2] = { - {1, arcs_3_0}, - {2, arcs_3_1}, + {1, arcs_3_0}, + {2, arcs_3_1}, }; static arc arcs_4_0[2] = { - {11, 1}, - {13, 2}, + {11, 1}, + {13, 2}, }; static arc arcs_4_1[1] = { - {7, 3}, + {7, 3}, }; static arc arcs_4_2[3] = { - {14, 4}, - {15, 4}, - {0, 2}, + {14, 4}, + {15, 4}, + {0, 2}, }; static arc arcs_4_3[1] = { - {12, 4}, + {12, 4}, }; static arc arcs_4_4[1] = { - {0, 4}, + {0, 4}, }; static state states_4[5] = { - {2, arcs_4_0}, - {1, arcs_4_1}, - {3, arcs_4_2}, - {1, arcs_4_3}, - {1, arcs_4_4}, + {2, arcs_4_0}, + {1, arcs_4_1}, + {3, arcs_4_2}, + {1, arcs_4_3}, + {1, arcs_4_4}, }; static arc arcs_5_0[3] = { - {5, 1}, - {16, 1}, - {17, 2}, + {5, 1}, + {16, 1}, + {17, 2}, }; static arc arcs_5_1[1] = { - {0, 1}, + {0, 1}, }; static arc arcs_5_2[1] = { - {7, 3}, + {7, 3}, }; static arc arcs_5_3[1] = { - {18, 1}, + {18, 1}, }; static state states_5[4] = { - {3, arcs_5_0}, - {1, arcs_5_1}, - {1, arcs_5_2}, - {1, arcs_5_3}, + {3, arcs_5_0}, + {1, arcs_5_1}, + {1, arcs_5_2}, + {1, arcs_5_3}, }; static dfa dfas[6] = { - {256, "MSTART", 0, 2, states_0, - "\070\000\000"}, - {257, "RULE", 0, 5, states_1, - "\040\000\000"}, - {258, "RHS", 0, 2, states_2, - "\040\010\003"}, - {259, "ALT", 0, 2, states_3, - "\040\010\003"}, - {260, "ITEM", 0, 5, states_4, - "\040\010\003"}, - {261, "ATOM", 0, 4, states_5, - "\040\000\003"}, + {256, "MSTART", 0, 2, states_0, + "\070\000\000"}, + {257, "RULE", 0, 5, states_1, + "\040\000\000"}, + {258, "RHS", 0, 2, states_2, + "\040\010\003"}, + {259, "ALT", 0, 2, states_3, + "\040\010\003"}, + {260, "ITEM", 0, 5, states_4, + "\040\010\003"}, + {261, "ATOM", 0, 4, states_5, + "\040\000\003"}, }; static label labels[19] = { - {0, "EMPTY"}, - {256, 0}, - {257, 0}, - {4, 0}, - {0, 0}, - {1, 0}, - {11, 0}, - {258, 0}, - {259, 0}, - {18, 0}, - {260, 0}, - {9, 0}, - {10, 0}, - {261, 0}, - {16, 0}, - {14, 0}, - {3, 0}, - {7, 0}, - {8, 0}, + {0, "EMPTY"}, + {256, 0}, + {257, 0}, + {4, 0}, + {0, 0}, + {1, 0}, + {11, 0}, + {258, 0}, + {259, 0}, + {18, 0}, + {260, 0}, + {9, 0}, + {10, 0}, + {261, 0}, + {16, 0}, + {14, 0}, + {3, 0}, + {7, 0}, + {8, 0}, }; static grammar _PyParser_Grammar = { - 6, - dfas, - {19, labels}, - 256 + 6, + dfas, + {19, labels}, + 256 }; grammar * meta_grammar(void) { - return &_PyParser_Grammar; + return &_PyParser_Grammar; } grammar * Modified: python/branches/py3k-jit/Parser/myreadline.c ============================================================================== --- python/branches/py3k-jit/Parser/myreadline.c (original) +++ python/branches/py3k-jit/Parser/myreadline.c Mon May 10 23:55:43 2010 @@ -35,64 +35,64 @@ static int my_fgets(char *buf, int len, FILE *fp) { - char *p; - if (PyOS_InputHook != NULL) - (void)(PyOS_InputHook)(); - errno = 0; - p = fgets(buf, len, fp); - if (p != NULL) - return 0; /* No error */ + char *p; + if (PyOS_InputHook != NULL) + (void)(PyOS_InputHook)(); + errno = 0; + p = fgets(buf, len, fp); + if (p != NULL) + return 0; /* No error */ #ifdef MS_WINDOWS - /* In the case of a Ctrl+C or some other external event - interrupting the operation: - Win2k/NT: ERROR_OPERATION_ABORTED is the most recent Win32 - error code (and feof() returns TRUE). - Win9x: Ctrl+C seems to have no effect on fgets() returning - early - the signal handler is called, but the fgets() - only returns "normally" (ie, when Enter hit or feof()) - */ - if (GetLastError()==ERROR_OPERATION_ABORTED) { - /* Signals come asynchronously, so we sleep a brief - moment before checking if the handler has been - triggered (we cant just return 1 before the - signal handler has been called, as the later - signal may be treated as a separate interrupt). - */ - Sleep(1); - if (PyOS_InterruptOccurred()) { - return 1; /* Interrupt */ - } - /* Either the sleep wasn't long enough (need a - short loop retrying?) or not interrupted at all - (in which case we should revisit the whole thing!) - Logging some warning would be nice. assert is not - viable as under the debugger, the various dialogs - mean the condition is not true. - */ - } + /* In the case of a Ctrl+C or some other external event + interrupting the operation: + Win2k/NT: ERROR_OPERATION_ABORTED is the most recent Win32 + error code (and feof() returns TRUE). + Win9x: Ctrl+C seems to have no effect on fgets() returning + early - the signal handler is called, but the fgets() + only returns "normally" (ie, when Enter hit or feof()) + */ + if (GetLastError()==ERROR_OPERATION_ABORTED) { + /* Signals come asynchronously, so we sleep a brief + moment before checking if the handler has been + triggered (we cant just return 1 before the + signal handler has been called, as the later + signal may be treated as a separate interrupt). + */ + Sleep(1); + if (PyOS_InterruptOccurred()) { + return 1; /* Interrupt */ + } + /* Either the sleep wasn't long enough (need a + short loop retrying?) or not interrupted at all + (in which case we should revisit the whole thing!) + Logging some warning would be nice. assert is not + viable as under the debugger, the various dialogs + mean the condition is not true. + */ + } #endif /* MS_WINDOWS */ - if (feof(fp)) { - return -1; /* EOF */ - } + if (feof(fp)) { + return -1; /* EOF */ + } #ifdef EINTR - if (errno == EINTR) { - int s; + if (errno == EINTR) { + int s; #ifdef WITH_THREAD - PyEval_RestoreThread(_PyOS_ReadlineTState); + PyEval_RestoreThread(_PyOS_ReadlineTState); #endif - s = PyErr_CheckSignals(); + s = PyErr_CheckSignals(); #ifdef WITH_THREAD - PyEval_SaveThread(); + PyEval_SaveThread(); #endif - if (s < 0) { - return 1; - } - } -#endif - if (PyOS_InterruptOccurred()) { - return 1; /* Interrupt */ - } - return -2; /* Error */ + if (s < 0) { + return 1; + } + } +#endif + if (PyOS_InterruptOccurred()) { + return 1; /* Interrupt */ + } + return -2; /* Error */ } @@ -101,41 +101,41 @@ char * PyOS_StdioReadline(FILE *sys_stdin, FILE *sys_stdout, char *prompt) { - size_t n; - char *p; - n = 100; - if ((p = (char *)PyMem_MALLOC(n)) == NULL) - return NULL; - fflush(sys_stdout); - if (prompt) - fprintf(stderr, "%s", prompt); - fflush(stderr); - switch (my_fgets(p, (int)n, sys_stdin)) { - case 0: /* Normal case */ - break; - case 1: /* Interrupt */ - PyMem_FREE(p); - return NULL; - case -1: /* EOF */ - case -2: /* Error */ - default: /* Shouldn't happen */ - *p = '\0'; - break; - } - n = strlen(p); - while (n > 0 && p[n-1] != '\n') { - size_t incr = n+2; - p = (char *)PyMem_REALLOC(p, n + incr); - if (p == NULL) - return NULL; - if (incr > INT_MAX) { - PyErr_SetString(PyExc_OverflowError, "input line too long"); - } - if (my_fgets(p+n, (int)incr, sys_stdin) != 0) - break; - n += strlen(p+n); - } - return (char *)PyMem_REALLOC(p, n+1); + size_t n; + char *p; + n = 100; + if ((p = (char *)PyMem_MALLOC(n)) == NULL) + return NULL; + fflush(sys_stdout); + if (prompt) + fprintf(stderr, "%s", prompt); + fflush(stderr); + switch (my_fgets(p, (int)n, sys_stdin)) { + case 0: /* Normal case */ + break; + case 1: /* Interrupt */ + PyMem_FREE(p); + return NULL; + case -1: /* EOF */ + case -2: /* Error */ + default: /* Shouldn't happen */ + *p = '\0'; + break; + } + n = strlen(p); + while (n > 0 && p[n-1] != '\n') { + size_t incr = n+2; + p = (char *)PyMem_REALLOC(p, n + incr); + if (p == NULL) + return NULL; + if (incr > INT_MAX) { + PyErr_SetString(PyExc_OverflowError, "input line too long"); + } + if (my_fgets(p+n, (int)incr, sys_stdin) != 0) + break; + n += strlen(p+n); + } + return (char *)PyMem_REALLOC(p, n+1); } @@ -152,52 +152,52 @@ char * PyOS_Readline(FILE *sys_stdin, FILE *sys_stdout, char *prompt) { - char *rv; + char *rv; - if (_PyOS_ReadlineTState == PyThreadState_GET()) { - PyErr_SetString(PyExc_RuntimeError, - "can't re-enter readline"); - return NULL; - } - + if (_PyOS_ReadlineTState == PyThreadState_GET()) { + PyErr_SetString(PyExc_RuntimeError, + "can't re-enter readline"); + return NULL; + } - if (PyOS_ReadlineFunctionPointer == NULL) { + + if (PyOS_ReadlineFunctionPointer == NULL) { #ifdef __VMS - PyOS_ReadlineFunctionPointer = vms__StdioReadline; + PyOS_ReadlineFunctionPointer = vms__StdioReadline; #else - PyOS_ReadlineFunctionPointer = PyOS_StdioReadline; + PyOS_ReadlineFunctionPointer = PyOS_StdioReadline; #endif - } - + } + #ifdef WITH_THREAD - if (_PyOS_ReadlineLock == NULL) { - _PyOS_ReadlineLock = PyThread_allocate_lock(); - } + if (_PyOS_ReadlineLock == NULL) { + _PyOS_ReadlineLock = PyThread_allocate_lock(); + } #endif - _PyOS_ReadlineTState = PyThreadState_GET(); - Py_BEGIN_ALLOW_THREADS + _PyOS_ReadlineTState = PyThreadState_GET(); + Py_BEGIN_ALLOW_THREADS #ifdef WITH_THREAD - PyThread_acquire_lock(_PyOS_ReadlineLock, 1); + PyThread_acquire_lock(_PyOS_ReadlineLock, 1); #endif - /* This is needed to handle the unlikely case that the - * interpreter is in interactive mode *and* stdin/out are not - * a tty. This can happen, for example if python is run like - * this: python -i < test1.py - */ - if (!isatty (fileno (sys_stdin)) || !isatty (fileno (sys_stdout))) - rv = PyOS_StdioReadline (sys_stdin, sys_stdout, prompt); - else - rv = (*PyOS_ReadlineFunctionPointer)(sys_stdin, sys_stdout, - prompt); - Py_END_ALLOW_THREADS + /* This is needed to handle the unlikely case that the + * interpreter is in interactive mode *and* stdin/out are not + * a tty. This can happen, for example if python is run like + * this: python -i < test1.py + */ + if (!isatty (fileno (sys_stdin)) || !isatty (fileno (sys_stdout))) + rv = PyOS_StdioReadline (sys_stdin, sys_stdout, prompt); + else + rv = (*PyOS_ReadlineFunctionPointer)(sys_stdin, sys_stdout, + prompt); + Py_END_ALLOW_THREADS #ifdef WITH_THREAD - PyThread_release_lock(_PyOS_ReadlineLock); + PyThread_release_lock(_PyOS_ReadlineLock); #endif - _PyOS_ReadlineTState = NULL; + _PyOS_ReadlineTState = NULL; - return rv; + return rv; } Modified: python/branches/py3k-jit/Parser/node.c ============================================================================== --- python/branches/py3k-jit/Parser/node.c (original) +++ python/branches/py3k-jit/Parser/node.c Mon May 10 23:55:43 2010 @@ -7,30 +7,30 @@ node * PyNode_New(int type) { - node *n = (node *) PyObject_MALLOC(1 * sizeof(node)); - if (n == NULL) - return NULL; - n->n_type = type; - n->n_str = NULL; - n->n_lineno = 0; - n->n_nchildren = 0; - n->n_child = NULL; - return n; + node *n = (node *) PyObject_MALLOC(1 * sizeof(node)); + if (n == NULL) + return NULL; + n->n_type = type; + n->n_str = NULL; + n->n_lineno = 0; + n->n_nchildren = 0; + n->n_child = NULL; + return n; } /* See comments at XXXROUNDUP below. Returns -1 on overflow. */ static int fancy_roundup(int n) { - /* Round up to the closest power of 2 >= n. */ - int result = 256; - assert(n > 128); - while (result < n) { - result <<= 1; - if (result <= 0) - return -1; - } - return result; + /* Round up to the closest power of 2 >= n. */ + int result = 256; + assert(n > 128); + while (result < n) { + result <<= 1; + if (result <= 0) + return -1; + } + return result; } /* A gimmick to make massive numbers of reallocs quicker. The result is @@ -70,46 +70,46 @@ * Note that this would be straightforward if a node stored its current * capacity. The code is tricky to avoid that. */ -#define XXXROUNDUP(n) ((n) <= 1 ? (n) : \ - (n) <= 128 ? (((n) + 3) & ~3) : \ - fancy_roundup(n)) +#define XXXROUNDUP(n) ((n) <= 1 ? (n) : \ + (n) <= 128 ? (((n) + 3) & ~3) : \ + fancy_roundup(n)) int PyNode_AddChild(register node *n1, int type, char *str, int lineno, int col_offset) { - const int nch = n1->n_nchildren; - int current_capacity; - int required_capacity; - node *n; - - if (nch == INT_MAX || nch < 0) - return E_OVERFLOW; - - current_capacity = XXXROUNDUP(nch); - required_capacity = XXXROUNDUP(nch + 1); - if (current_capacity < 0 || required_capacity < 0) - return E_OVERFLOW; - if (current_capacity < required_capacity) { - if (required_capacity > PY_SIZE_MAX / sizeof(node)) { - return E_NOMEM; - } - n = n1->n_child; - n = (node *) PyObject_REALLOC(n, - required_capacity * sizeof(node)); - if (n == NULL) - return E_NOMEM; - n1->n_child = n; - } - - n = &n1->n_child[n1->n_nchildren++]; - n->n_type = type; - n->n_str = str; - n->n_lineno = lineno; - n->n_col_offset = col_offset; - n->n_nchildren = 0; - n->n_child = NULL; - return 0; + const int nch = n1->n_nchildren; + int current_capacity; + int required_capacity; + node *n; + + if (nch == INT_MAX || nch < 0) + return E_OVERFLOW; + + current_capacity = XXXROUNDUP(nch); + required_capacity = XXXROUNDUP(nch + 1); + if (current_capacity < 0 || required_capacity < 0) + return E_OVERFLOW; + if (current_capacity < required_capacity) { + if (required_capacity > PY_SIZE_MAX / sizeof(node)) { + return E_NOMEM; + } + n = n1->n_child; + n = (node *) PyObject_REALLOC(n, + required_capacity * sizeof(node)); + if (n == NULL) + return E_NOMEM; + n1->n_child = n; + } + + n = &n1->n_child[n1->n_nchildren++]; + n->n_type = type; + n->n_str = str; + n->n_lineno = lineno; + n->n_col_offset = col_offset; + n->n_nchildren = 0; + n->n_child = NULL; + return 0; } /* Forward */ @@ -119,20 +119,20 @@ void PyNode_Free(node *n) { - if (n != NULL) { - freechildren(n); - PyObject_FREE(n); - } + if (n != NULL) { + freechildren(n); + PyObject_FREE(n); + } } static void freechildren(node *n) { - int i; - for (i = NCH(n); --i >= 0; ) - freechildren(CHILD(n, i)); - if (n->n_child != NULL) - PyObject_FREE(n->n_child); - if (STR(n) != NULL) - PyObject_FREE(STR(n)); + int i; + for (i = NCH(n); --i >= 0; ) + freechildren(CHILD(n, i)); + if (n->n_child != NULL) + PyObject_FREE(n->n_child); + if (STR(n) != NULL) + PyObject_FREE(STR(n)); } Modified: python/branches/py3k-jit/Parser/parser.c ============================================================================== --- python/branches/py3k-jit/Parser/parser.c (original) +++ python/branches/py3k-jit/Parser/parser.c Mon May 10 23:55:43 2010 @@ -29,7 +29,7 @@ static void s_reset(stack *s) { - s->s_top = &s->s_base[MAXSTACK]; + s->s_top = &s->s_base[MAXSTACK]; } #define s_empty(s) ((s)->s_top == &(s)->s_base[MAXSTACK]) @@ -37,16 +37,16 @@ static int s_push(register stack *s, dfa *d, node *parent) { - register stackentry *top; - if (s->s_top == s->s_base) { - fprintf(stderr, "s_push: parser stack overflow\n"); - return E_NOMEM; - } - top = --s->s_top; - top->s_dfa = d; - top->s_parent = parent; - top->s_state = 0; - return 0; + register stackentry *top; + if (s->s_top == s->s_base) { + fprintf(stderr, "s_push: parser stack overflow\n"); + return E_NOMEM; + } + top = --s->s_top; + top->s_dfa = d; + top->s_parent = parent; + top->s_state = 0; + return 0; } #ifdef Py_DEBUG @@ -54,9 +54,9 @@ static void s_pop(register stack *s) { - if (s_empty(s)) - Py_FatalError("s_pop: parser stack underflow -- FATAL"); - s->s_top++; + if (s_empty(s)) + Py_FatalError("s_pop: parser stack underflow -- FATAL"); + s->s_top++; } #else /* !Py_DEBUG */ @@ -71,34 +71,34 @@ parser_state * PyParser_New(grammar *g, int start) { - parser_state *ps; - - if (!g->g_accel) - PyGrammar_AddAccelerators(g); - ps = (parser_state *)PyMem_MALLOC(sizeof(parser_state)); - if (ps == NULL) - return NULL; - ps->p_grammar = g; + parser_state *ps; + + if (!g->g_accel) + PyGrammar_AddAccelerators(g); + ps = (parser_state *)PyMem_MALLOC(sizeof(parser_state)); + if (ps == NULL) + return NULL; + ps->p_grammar = g; #ifdef PY_PARSER_REQUIRES_FUTURE_KEYWORD - ps->p_flags = 0; + ps->p_flags = 0; #endif - ps->p_tree = PyNode_New(start); - if (ps->p_tree == NULL) { - PyMem_FREE(ps); - return NULL; - } - s_reset(&ps->p_stack); - (void) s_push(&ps->p_stack, PyGrammar_FindDFA(g, start), ps->p_tree); - return ps; + ps->p_tree = PyNode_New(start); + if (ps->p_tree == NULL) { + PyMem_FREE(ps); + return NULL; + } + s_reset(&ps->p_stack); + (void) s_push(&ps->p_stack, PyGrammar_FindDFA(g, start), ps->p_tree); + return ps; } void PyParser_Delete(parser_state *ps) { - /* NB If you want to save the parse tree, - you must set p_tree to NULL before calling delparser! */ - PyNode_Free(ps->p_tree); - PyMem_FREE(ps); + /* NB If you want to save the parse tree, + you must set p_tree to NULL before calling delparser! */ + PyNode_Free(ps->p_tree); + PyMem_FREE(ps); } @@ -107,27 +107,27 @@ static int shift(register stack *s, int type, char *str, int newstate, int lineno, int col_offset) { - int err; - assert(!s_empty(s)); - err = PyNode_AddChild(s->s_top->s_parent, type, str, lineno, col_offset); - if (err) - return err; - s->s_top->s_state = newstate; - return 0; + int err; + assert(!s_empty(s)); + err = PyNode_AddChild(s->s_top->s_parent, type, str, lineno, col_offset); + if (err) + return err; + s->s_top->s_state = newstate; + return 0; } static int push(register stack *s, int type, dfa *d, int newstate, int lineno, int col_offset) { - int err; - register node *n; - n = s->s_top->s_parent; - assert(!s_empty(s)); - err = PyNode_AddChild(n, type, (char *)NULL, lineno, col_offset); - if (err) - return err; - s->s_top->s_state = newstate; - return s_push(s, d, CHILD(n, NCH(n)-1)); + int err; + register node *n; + n = s->s_top->s_parent; + assert(!s_empty(s)); + err = PyNode_AddChild(n, type, (char *)NULL, lineno, col_offset); + if (err) + return err; + s->s_top->s_state = newstate; + return s_push(s, d, CHILD(n, NCH(n)-1)); } @@ -136,47 +136,47 @@ static int classify(parser_state *ps, int type, char *str) { - grammar *g = ps->p_grammar; - register int n = g->g_ll.ll_nlabels; - - if (type == NAME) { - register char *s = str; - register label *l = g->g_ll.ll_label; - register int i; - for (i = n; i > 0; i--, l++) { - if (l->lb_type != NAME || l->lb_str == NULL || - l->lb_str[0] != s[0] || - strcmp(l->lb_str, s) != 0) - continue; + grammar *g = ps->p_grammar; + register int n = g->g_ll.ll_nlabels; + + if (type == NAME) { + register char *s = str; + register label *l = g->g_ll.ll_label; + register int i; + for (i = n; i > 0; i--, l++) { + if (l->lb_type != NAME || l->lb_str == NULL || + l->lb_str[0] != s[0] || + strcmp(l->lb_str, s) != 0) + continue; #ifdef PY_PARSER_REQUIRES_FUTURE_KEYWORD #if 0 - /* Leaving this in as an example */ - if (!(ps->p_flags & CO_FUTURE_WITH_STATEMENT)) { - if (s[0] == 'w' && strcmp(s, "with") == 0) - break; /* not a keyword yet */ - else if (s[0] == 'a' && strcmp(s, "as") == 0) - break; /* not a keyword yet */ - } + /* Leaving this in as an example */ + if (!(ps->p_flags & CO_FUTURE_WITH_STATEMENT)) { + if (s[0] == 'w' && strcmp(s, "with") == 0) + break; /* not a keyword yet */ + else if (s[0] == 'a' && strcmp(s, "as") == 0) + break; /* not a keyword yet */ + } #endif #endif - D(printf("It's a keyword\n")); - return n - i; - } - } - - { - register label *l = g->g_ll.ll_label; - register int i; - for (i = n; i > 0; i--, l++) { - if (l->lb_type == type && l->lb_str == NULL) { - D(printf("It's a token we know\n")); - return n - i; - } - } - } - - D(printf("Illegal token\n")); - return -1; + D(printf("It's a keyword\n")); + return n - i; + } + } + + { + register label *l = g->g_ll.ll_label; + register int i; + for (i = n; i > 0; i--, l++) { + if (l->lb_type == type && l->lb_str == NULL) { + D(printf("It's a token we know\n")); + return n - i; + } + } + } + + D(printf("Illegal token\n")); + return -1; } #ifdef PY_PARSER_REQUIRES_FUTURE_KEYWORD @@ -185,152 +185,152 @@ static void future_hack(parser_state *ps) { - node *n = ps->p_stack.s_top->s_parent; - node *ch, *cch; - int i; - - /* from __future__ import ..., must have at least 4 children */ - n = CHILD(n, 0); - if (NCH(n) < 4) - return; - ch = CHILD(n, 0); - if (STR(ch) == NULL || strcmp(STR(ch), "from") != 0) - return; - ch = CHILD(n, 1); - if (NCH(ch) == 1 && STR(CHILD(ch, 0)) && - strcmp(STR(CHILD(ch, 0)), "__future__") != 0) - return; - ch = CHILD(n, 3); - /* ch can be a star, a parenthesis or import_as_names */ - if (TYPE(ch) == STAR) - return; - if (TYPE(ch) == LPAR) - ch = CHILD(n, 4); - - for (i = 0; i < NCH(ch); i += 2) { - cch = CHILD(ch, i); - if (NCH(cch) >= 1 && TYPE(CHILD(cch, 0)) == NAME) { - char *str_ch = STR(CHILD(cch, 0)); - if (strcmp(str_ch, FUTURE_WITH_STATEMENT) == 0) { - ps->p_flags |= CO_FUTURE_WITH_STATEMENT; - } else if (strcmp(str_ch, FUTURE_PRINT_FUNCTION) == 0) { - ps->p_flags |= CO_FUTURE_PRINT_FUNCTION; - } else if (strcmp(str_ch, FUTURE_UNICODE_LITERALS) == 0) { - ps->p_flags |= CO_FUTURE_UNICODE_LITERALS; - } - } - } + node *n = ps->p_stack.s_top->s_parent; + node *ch, *cch; + int i; + + /* from __future__ import ..., must have at least 4 children */ + n = CHILD(n, 0); + if (NCH(n) < 4) + return; + ch = CHILD(n, 0); + if (STR(ch) == NULL || strcmp(STR(ch), "from") != 0) + return; + ch = CHILD(n, 1); + if (NCH(ch) == 1 && STR(CHILD(ch, 0)) && + strcmp(STR(CHILD(ch, 0)), "__future__") != 0) + return; + ch = CHILD(n, 3); + /* ch can be a star, a parenthesis or import_as_names */ + if (TYPE(ch) == STAR) + return; + if (TYPE(ch) == LPAR) + ch = CHILD(n, 4); + + for (i = 0; i < NCH(ch); i += 2) { + cch = CHILD(ch, i); + if (NCH(cch) >= 1 && TYPE(CHILD(cch, 0)) == NAME) { + char *str_ch = STR(CHILD(cch, 0)); + if (strcmp(str_ch, FUTURE_WITH_STATEMENT) == 0) { + ps->p_flags |= CO_FUTURE_WITH_STATEMENT; + } else if (strcmp(str_ch, FUTURE_PRINT_FUNCTION) == 0) { + ps->p_flags |= CO_FUTURE_PRINT_FUNCTION; + } else if (strcmp(str_ch, FUTURE_UNICODE_LITERALS) == 0) { + ps->p_flags |= CO_FUTURE_UNICODE_LITERALS; + } + } + } } #endif #endif /* future keyword */ int PyParser_AddToken(register parser_state *ps, register int type, char *str, - int lineno, int col_offset, int *expected_ret) + int lineno, int col_offset, int *expected_ret) { - register int ilabel; - int err; - - D(printf("Token %s/'%s' ... ", _PyParser_TokenNames[type], str)); - - /* Find out which label this token is */ - ilabel = classify(ps, type, str); - if (ilabel < 0) - return E_SYNTAX; - - /* Loop until the token is shifted or an error occurred */ - for (;;) { - /* Fetch the current dfa and state */ - register dfa *d = ps->p_stack.s_top->s_dfa; - register state *s = &d->d_state[ps->p_stack.s_top->s_state]; - - D(printf(" DFA '%s', state %d:", - d->d_name, ps->p_stack.s_top->s_state)); - - /* Check accelerator */ - if (s->s_lower <= ilabel && ilabel < s->s_upper) { - register int x = s->s_accel[ilabel - s->s_lower]; - if (x != -1) { - if (x & (1<<7)) { - /* Push non-terminal */ - int nt = (x >> 8) + NT_OFFSET; - int arrow = x & ((1<<7)-1); - dfa *d1 = PyGrammar_FindDFA( - ps->p_grammar, nt); - if ((err = push(&ps->p_stack, nt, d1, - arrow, lineno, col_offset)) > 0) { - D(printf(" MemError: push\n")); - return err; - } - D(printf(" Push ...\n")); - continue; - } - - /* Shift the token */ - if ((err = shift(&ps->p_stack, type, str, - x, lineno, col_offset)) > 0) { - D(printf(" MemError: shift.\n")); - return err; - } - D(printf(" Shift.\n")); - /* Pop while we are in an accept-only state */ - while (s = &d->d_state - [ps->p_stack.s_top->s_state], - s->s_accept && s->s_narcs == 1) { - D(printf(" DFA '%s', state %d: " - "Direct pop.\n", - d->d_name, - ps->p_stack.s_top->s_state)); + register int ilabel; + int err; + + D(printf("Token %s/'%s' ... ", _PyParser_TokenNames[type], str)); + + /* Find out which label this token is */ + ilabel = classify(ps, type, str); + if (ilabel < 0) + return E_SYNTAX; + + /* Loop until the token is shifted or an error occurred */ + for (;;) { + /* Fetch the current dfa and state */ + register dfa *d = ps->p_stack.s_top->s_dfa; + register state *s = &d->d_state[ps->p_stack.s_top->s_state]; + + D(printf(" DFA '%s', state %d:", + d->d_name, ps->p_stack.s_top->s_state)); + + /* Check accelerator */ + if (s->s_lower <= ilabel && ilabel < s->s_upper) { + register int x = s->s_accel[ilabel - s->s_lower]; + if (x != -1) { + if (x & (1<<7)) { + /* Push non-terminal */ + int nt = (x >> 8) + NT_OFFSET; + int arrow = x & ((1<<7)-1); + dfa *d1 = PyGrammar_FindDFA( + ps->p_grammar, nt); + if ((err = push(&ps->p_stack, nt, d1, + arrow, lineno, col_offset)) > 0) { + D(printf(" MemError: push\n")); + return err; + } + D(printf(" Push ...\n")); + continue; + } + + /* Shift the token */ + if ((err = shift(&ps->p_stack, type, str, + x, lineno, col_offset)) > 0) { + D(printf(" MemError: shift.\n")); + return err; + } + D(printf(" Shift.\n")); + /* Pop while we are in an accept-only state */ + while (s = &d->d_state + [ps->p_stack.s_top->s_state], + s->s_accept && s->s_narcs == 1) { + D(printf(" DFA '%s', state %d: " + "Direct pop.\n", + d->d_name, + ps->p_stack.s_top->s_state)); #ifdef PY_PARSER_REQUIRES_FUTURE_KEYWORD #if 0 - if (d->d_name[0] == 'i' && - strcmp(d->d_name, - "import_stmt") == 0) - future_hack(ps); + if (d->d_name[0] == 'i' && + strcmp(d->d_name, + "import_stmt") == 0) + future_hack(ps); #endif #endif - s_pop(&ps->p_stack); - if (s_empty(&ps->p_stack)) { - D(printf(" ACCEPT.\n")); - return E_DONE; - } - d = ps->p_stack.s_top->s_dfa; - } - return E_OK; - } - } - - if (s->s_accept) { + s_pop(&ps->p_stack); + if (s_empty(&ps->p_stack)) { + D(printf(" ACCEPT.\n")); + return E_DONE; + } + d = ps->p_stack.s_top->s_dfa; + } + return E_OK; + } + } + + if (s->s_accept) { #ifdef PY_PARSER_REQUIRES_FUTURE_KEYWORD #if 0 - if (d->d_name[0] == 'i' && - strcmp(d->d_name, "import_stmt") == 0) - future_hack(ps); + if (d->d_name[0] == 'i' && + strcmp(d->d_name, "import_stmt") == 0) + future_hack(ps); #endif #endif - /* Pop this dfa and try again */ - s_pop(&ps->p_stack); - D(printf(" Pop ...\n")); - if (s_empty(&ps->p_stack)) { - D(printf(" Error: bottom of stack.\n")); - return E_SYNTAX; - } - continue; - } - - /* Stuck, report syntax error */ - D(printf(" Error.\n")); - if (expected_ret) { - if (s->s_lower == s->s_upper - 1) { - /* Only one possible expected token */ - *expected_ret = ps->p_grammar-> - g_ll.ll_label[s->s_lower].lb_type; - } - else - *expected_ret = -1; - } - return E_SYNTAX; - } + /* Pop this dfa and try again */ + s_pop(&ps->p_stack); + D(printf(" Pop ...\n")); + if (s_empty(&ps->p_stack)) { + D(printf(" Error: bottom of stack.\n")); + return E_SYNTAX; + } + continue; + } + + /* Stuck, report syntax error */ + D(printf(" Error.\n")); + if (expected_ret) { + if (s->s_lower == s->s_upper - 1) { + /* Only one possible expected token */ + *expected_ret = ps->p_grammar-> + g_ll.ll_label[s->s_lower].lb_type; + } + else + *expected_ret = -1; + } + return E_SYNTAX; + } } @@ -341,62 +341,62 @@ void dumptree(grammar *g, node *n) { - int i; - - if (n == NULL) - printf("NIL"); - else { - label l; - l.lb_type = TYPE(n); - l.lb_str = STR(n); - printf("%s", PyGrammar_LabelRepr(&l)); - if (ISNONTERMINAL(TYPE(n))) { - printf("("); - for (i = 0; i < NCH(n); i++) { - if (i > 0) - printf(","); - dumptree(g, CHILD(n, i)); - } - printf(")"); - } - } + int i; + + if (n == NULL) + printf("NIL"); + else { + label l; + l.lb_type = TYPE(n); + l.lb_str = STR(n); + printf("%s", PyGrammar_LabelRepr(&l)); + if (ISNONTERMINAL(TYPE(n))) { + printf("("); + for (i = 0; i < NCH(n); i++) { + if (i > 0) + printf(","); + dumptree(g, CHILD(n, i)); + } + printf(")"); + } + } } void showtree(grammar *g, node *n) { - int i; - - if (n == NULL) - return; - if (ISNONTERMINAL(TYPE(n))) { - for (i = 0; i < NCH(n); i++) - showtree(g, CHILD(n, i)); - } - else if (ISTERMINAL(TYPE(n))) { - printf("%s", _PyParser_TokenNames[TYPE(n)]); - if (TYPE(n) == NUMBER || TYPE(n) == NAME) - printf("(%s)", STR(n)); - printf(" "); - } - else - printf("? "); + int i; + + if (n == NULL) + return; + if (ISNONTERMINAL(TYPE(n))) { + for (i = 0; i < NCH(n); i++) + showtree(g, CHILD(n, i)); + } + else if (ISTERMINAL(TYPE(n))) { + printf("%s", _PyParser_TokenNames[TYPE(n)]); + if (TYPE(n) == NUMBER || TYPE(n) == NAME) + printf("(%s)", STR(n)); + printf(" "); + } + else + printf("? "); } void printtree(parser_state *ps) { - if (Py_DebugFlag) { - printf("Parse tree:\n"); - dumptree(ps->p_grammar, ps->p_tree); - printf("\n"); - printf("Tokens:\n"); - showtree(ps->p_grammar, ps->p_tree); - printf("\n"); - } - printf("Listing:\n"); - PyNode_ListTree(ps->p_tree); - printf("\n"); + if (Py_DebugFlag) { + printf("Parse tree:\n"); + dumptree(ps->p_grammar, ps->p_tree); + printf("\n"); + printf("Tokens:\n"); + showtree(ps->p_grammar, ps->p_tree); + printf("\n"); + } + printf("Listing:\n"); + PyNode_ListTree(ps->p_tree); + printf("\n"); } #endif /* Py_DEBUG */ @@ -431,15 +431,15 @@ As an example, consider this grammar: -expr: term (OP term)* -term: CONSTANT | '(' expr ')' +expr: term (OP term)* +term: CONSTANT | '(' expr ')' The DFA corresponding to the rule for expr is: ------->.---term-->.-------> - ^ | - | | - \----OP----/ + ^ | + | | + \----OP----/ The parse tree generated for the input a+b is: Modified: python/branches/py3k-jit/Parser/parsetok.c ============================================================================== --- python/branches/py3k-jit/Parser/parsetok.c (original) +++ python/branches/py3k-jit/Parser/parsetok.c Mon May 10 23:55:43 2010 @@ -19,85 +19,85 @@ node * PyParser_ParseString(const char *s, grammar *g, int start, perrdetail *err_ret) { - return PyParser_ParseStringFlagsFilename(s, NULL, g, start, err_ret, 0); + return PyParser_ParseStringFlagsFilename(s, NULL, g, start, err_ret, 0); } node * PyParser_ParseStringFlags(const char *s, grammar *g, int start, - perrdetail *err_ret, int flags) + perrdetail *err_ret, int flags) { - return PyParser_ParseStringFlagsFilename(s, NULL, - g, start, err_ret, flags); + return PyParser_ParseStringFlagsFilename(s, NULL, + g, start, err_ret, flags); } node * PyParser_ParseStringFlagsFilename(const char *s, const char *filename, - grammar *g, int start, - perrdetail *err_ret, int flags) + grammar *g, int start, + perrdetail *err_ret, int flags) { - int iflags = flags; - return PyParser_ParseStringFlagsFilenameEx(s, filename, g, start, - err_ret, &iflags); + int iflags = flags; + return PyParser_ParseStringFlagsFilenameEx(s, filename, g, start, + err_ret, &iflags); } node * PyParser_ParseStringFlagsFilenameEx(const char *s, const char *filename, - grammar *g, int start, - perrdetail *err_ret, int *flags) + grammar *g, int start, + perrdetail *err_ret, int *flags) { - struct tok_state *tok; - int exec_input = start == file_input; + struct tok_state *tok; + int exec_input = start == file_input; - initerr(err_ret, filename); + initerr(err_ret, filename); - if (*flags & PyPARSE_IGNORE_COOKIE) - tok = PyTokenizer_FromUTF8(s, exec_input); - else - tok = PyTokenizer_FromString(s, exec_input); - if (tok == NULL) { - err_ret->error = PyErr_Occurred() ? E_DECODE : E_NOMEM; - return NULL; - } + if (*flags & PyPARSE_IGNORE_COOKIE) + tok = PyTokenizer_FromUTF8(s, exec_input); + else + tok = PyTokenizer_FromString(s, exec_input); + if (tok == NULL) { + err_ret->error = PyErr_Occurred() ? E_DECODE : E_NOMEM; + return NULL; + } - tok->filename = filename ? filename : ""; - return parsetok(tok, g, start, err_ret, flags); + tok->filename = filename ? filename : ""; + return parsetok(tok, g, start, err_ret, flags); } /* Parse input coming from a file. Return error code, print some errors. */ node * PyParser_ParseFile(FILE *fp, const char *filename, grammar *g, int start, - char *ps1, char *ps2, perrdetail *err_ret) + char *ps1, char *ps2, perrdetail *err_ret) { - return PyParser_ParseFileFlags(fp, filename, NULL, - g, start, ps1, ps2, err_ret, 0); + return PyParser_ParseFileFlags(fp, filename, NULL, + g, start, ps1, ps2, err_ret, 0); } node * PyParser_ParseFileFlags(FILE *fp, const char *filename, const char *enc, - grammar *g, int start, - char *ps1, char *ps2, perrdetail *err_ret, int flags) + grammar *g, int start, + char *ps1, char *ps2, perrdetail *err_ret, int flags) { - int iflags = flags; - return PyParser_ParseFileFlagsEx(fp, filename, enc, g, start, ps1, - ps2, err_ret, &iflags); + int iflags = flags; + return PyParser_ParseFileFlagsEx(fp, filename, enc, g, start, ps1, + ps2, err_ret, &iflags); } node * -PyParser_ParseFileFlagsEx(FILE *fp, const char *filename, - const char *enc, grammar *g, int start, - char *ps1, char *ps2, perrdetail *err_ret, int *flags) +PyParser_ParseFileFlagsEx(FILE *fp, const char *filename, + const char *enc, grammar *g, int start, + char *ps1, char *ps2, perrdetail *err_ret, int *flags) { - struct tok_state *tok; + struct tok_state *tok; - initerr(err_ret, filename); + initerr(err_ret, filename); - if ((tok = PyTokenizer_FromFile(fp, (char *)enc, ps1, ps2)) == NULL) { - err_ret->error = E_NOMEM; - return NULL; - } - tok->filename = filename; - return parsetok(tok, g, start, err_ret, flags); + if ((tok = PyTokenizer_FromFile(fp, (char *)enc, ps1, ps2)) == NULL) { + err_ret->error = E_NOMEM; + return NULL; + } + tok->filename = filename; + return parsetok(tok, g, start, err_ret, flags); } #ifdef PY_PARSER_REQUIRES_FUTURE_KEYWORD @@ -111,9 +111,9 @@ static void warn(const char *msg, const char *filename, int lineno) { - if (filename == NULL) - filename = ""; - PySys_WriteStderr(msg, filename, lineno); + if (filename == NULL) + filename = ""; + PySys_WriteStderr(msg, filename, lineno); } #endif #endif @@ -123,159 +123,159 @@ static node * parsetok(struct tok_state *tok, grammar *g, int start, perrdetail *err_ret, - int *flags) + int *flags) { - parser_state *ps; - node *n; - int started = 0, handling_import = 0, handling_with = 0; - - if ((ps = PyParser_New(g, start)) == NULL) { - fprintf(stderr, "no mem for new parser\n"); - err_ret->error = E_NOMEM; - PyTokenizer_Free(tok); - return NULL; - } + parser_state *ps; + node *n; + int started = 0, handling_import = 0, handling_with = 0; + + if ((ps = PyParser_New(g, start)) == NULL) { + fprintf(stderr, "no mem for new parser\n"); + err_ret->error = E_NOMEM; + PyTokenizer_Free(tok); + return NULL; + } #ifdef PY_PARSER_REQUIRES_FUTURE_KEYWORD - if (*flags & PyPARSE_BARRY_AS_BDFL) - ps->p_flags |= CO_FUTURE_BARRY_AS_BDFL; + if (*flags & PyPARSE_BARRY_AS_BDFL) + ps->p_flags |= CO_FUTURE_BARRY_AS_BDFL; #endif - for (;;) { - char *a, *b; - int type; - size_t len; - char *str; - int col_offset; - - type = PyTokenizer_Get(tok, &a, &b); - if (type == ERRORTOKEN) { - err_ret->error = tok->done; - break; - } - if (type == ENDMARKER && started) { - type = NEWLINE; /* Add an extra newline */ - handling_with = handling_import = 0; - started = 0; - /* Add the right number of dedent tokens, - except if a certain flag is given -- - codeop.py uses this. */ - if (tok->indent && - !(*flags & PyPARSE_DONT_IMPLY_DEDENT)) - { - tok->pendin = -tok->indent; - tok->indent = 0; - } - } - else - started = 1; - len = b - a; /* XXX this may compute NULL - NULL */ - str = (char *) PyObject_MALLOC(len + 1); - if (str == NULL) { - fprintf(stderr, "no mem for next token\n"); - err_ret->error = E_NOMEM; - break; - } - if (len > 0) - strncpy(str, a, len); - str[len] = '\0'; + for (;;) { + char *a, *b; + int type; + size_t len; + char *str; + int col_offset; + + type = PyTokenizer_Get(tok, &a, &b); + if (type == ERRORTOKEN) { + err_ret->error = tok->done; + break; + } + if (type == ENDMARKER && started) { + type = NEWLINE; /* Add an extra newline */ + handling_with = handling_import = 0; + started = 0; + /* Add the right number of dedent tokens, + except if a certain flag is given -- + codeop.py uses this. */ + if (tok->indent && + !(*flags & PyPARSE_DONT_IMPLY_DEDENT)) + { + tok->pendin = -tok->indent; + tok->indent = 0; + } + } + else + started = 1; + len = b - a; /* XXX this may compute NULL - NULL */ + str = (char *) PyObject_MALLOC(len + 1); + if (str == NULL) { + fprintf(stderr, "no mem for next token\n"); + err_ret->error = E_NOMEM; + break; + } + if (len > 0) + strncpy(str, a, len); + str[len] = '\0'; #ifdef PY_PARSER_REQUIRES_FUTURE_KEYWORD - if (type == NOTEQUAL) { - if (!(ps->p_flags & CO_FUTURE_BARRY_AS_BDFL) && - strcmp(str, "!=")) { - err_ret->error = E_SYNTAX; - break; - } - else if ((ps->p_flags & CO_FUTURE_BARRY_AS_BDFL) && - strcmp(str, "<>")) { - err_ret->text = "with Barry as BDFL, use '<>' " - "instead of '!='"; - err_ret->error = E_SYNTAX; - break; - } - } + if (type == NOTEQUAL) { + if (!(ps->p_flags & CO_FUTURE_BARRY_AS_BDFL) && + strcmp(str, "!=")) { + err_ret->error = E_SYNTAX; + break; + } + else if ((ps->p_flags & CO_FUTURE_BARRY_AS_BDFL) && + strcmp(str, "<>")) { + err_ret->text = "with Barry as BDFL, use '<>' " + "instead of '!='"; + err_ret->error = E_SYNTAX; + break; + } + } #endif - if (a >= tok->line_start) - col_offset = a - tok->line_start; - else - col_offset = -1; - - if ((err_ret->error = - PyParser_AddToken(ps, (int)type, str, - tok->lineno, col_offset, - &(err_ret->expected))) != E_OK) { - if (err_ret->error != E_DONE) { - PyObject_FREE(str); - err_ret->token = type; - } - break; - } - } - - if (err_ret->error == E_DONE) { - n = ps->p_tree; - ps->p_tree = NULL; - } - else - n = NULL; + if (a >= tok->line_start) + col_offset = a - tok->line_start; + else + col_offset = -1; + + if ((err_ret->error = + PyParser_AddToken(ps, (int)type, str, + tok->lineno, col_offset, + &(err_ret->expected))) != E_OK) { + if (err_ret->error != E_DONE) { + PyObject_FREE(str); + err_ret->token = type; + } + break; + } + } + + if (err_ret->error == E_DONE) { + n = ps->p_tree; + ps->p_tree = NULL; + } + else + n = NULL; #ifdef PY_PARSER_REQUIRES_FUTURE_KEYWORD - *flags = ps->p_flags; + *flags = ps->p_flags; #endif - PyParser_Delete(ps); + PyParser_Delete(ps); - if (n == NULL) { - if (tok->lineno <= 1 && tok->done == E_EOF) - err_ret->error = E_EOF; - err_ret->lineno = tok->lineno; - if (tok->buf != NULL) { - size_t len; - assert(tok->cur - tok->buf < INT_MAX); - err_ret->offset = (int)(tok->cur - tok->buf); - len = tok->inp - tok->buf; - err_ret->text = (char *) PyObject_MALLOC(len + 1); - if (err_ret->text != NULL) { - if (len > 0) - strncpy(err_ret->text, tok->buf, len); - err_ret->text[len] = '\0'; - } - } - } else if (tok->encoding != NULL) { - /* 'nodes->n_str' uses PyObject_*, while 'tok->encoding' was - * allocated using PyMem_ - */ - node* r = PyNode_New(encoding_decl); - if (r) - r->n_str = PyObject_MALLOC(strlen(tok->encoding)+1); - if (!r || !r->n_str) { - err_ret->error = E_NOMEM; - if (r) - PyObject_FREE(r); - n = NULL; - goto done; - } - strcpy(r->n_str, tok->encoding); - PyMem_FREE(tok->encoding); - tok->encoding = NULL; - r->n_nchildren = 1; - r->n_child = n; - n = r; - } + if (n == NULL) { + if (tok->lineno <= 1 && tok->done == E_EOF) + err_ret->error = E_EOF; + err_ret->lineno = tok->lineno; + if (tok->buf != NULL) { + size_t len; + assert(tok->cur - tok->buf < INT_MAX); + err_ret->offset = (int)(tok->cur - tok->buf); + len = tok->inp - tok->buf; + err_ret->text = (char *) PyObject_MALLOC(len + 1); + if (err_ret->text != NULL) { + if (len > 0) + strncpy(err_ret->text, tok->buf, len); + err_ret->text[len] = '\0'; + } + } + } else if (tok->encoding != NULL) { + /* 'nodes->n_str' uses PyObject_*, while 'tok->encoding' was + * allocated using PyMem_ + */ + node* r = PyNode_New(encoding_decl); + if (r) + r->n_str = PyObject_MALLOC(strlen(tok->encoding)+1); + if (!r || !r->n_str) { + err_ret->error = E_NOMEM; + if (r) + PyObject_FREE(r); + n = NULL; + goto done; + } + strcpy(r->n_str, tok->encoding); + PyMem_FREE(tok->encoding); + tok->encoding = NULL; + r->n_nchildren = 1; + r->n_child = n; + n = r; + } done: - PyTokenizer_Free(tok); + PyTokenizer_Free(tok); - return n; + return n; } static void initerr(perrdetail *err_ret, const char *filename) { - err_ret->error = E_OK; - err_ret->filename = filename; - err_ret->lineno = 0; - err_ret->offset = 0; - err_ret->text = NULL; - err_ret->token = -1; - err_ret->expected = -1; + err_ret->error = E_OK; + err_ret->filename = filename; + err_ret->lineno = 0; + err_ret->offset = 0; + err_ret->text = NULL; + err_ret->token = -1; + err_ret->expected = -1; } Modified: python/branches/py3k-jit/Parser/pgen.c ============================================================================== --- python/branches/py3k-jit/Parser/pgen.c (original) +++ python/branches/py3k-jit/Parser/pgen.c Mon May 10 23:55:43 2010 @@ -17,85 +17,85 @@ /* PART ONE -- CONSTRUCT NFA -- Cf. Algorithm 3.2 from [Aho&Ullman 77] */ typedef struct _nfaarc { - int ar_label; - int ar_arrow; + int ar_label; + int ar_arrow; } nfaarc; typedef struct _nfastate { - int st_narcs; - nfaarc *st_arc; + int st_narcs; + nfaarc *st_arc; } nfastate; typedef struct _nfa { - int nf_type; - char *nf_name; - int nf_nstates; - nfastate *nf_state; - int nf_start, nf_finish; + int nf_type; + char *nf_name; + int nf_nstates; + nfastate *nf_state; + int nf_start, nf_finish; } nfa; /* Forward */ static void compile_rhs(labellist *ll, - nfa *nf, node *n, int *pa, int *pb); + nfa *nf, node *n, int *pa, int *pb); static void compile_alt(labellist *ll, - nfa *nf, node *n, int *pa, int *pb); + nfa *nf, node *n, int *pa, int *pb); static void compile_item(labellist *ll, - nfa *nf, node *n, int *pa, int *pb); + nfa *nf, node *n, int *pa, int *pb); static void compile_atom(labellist *ll, - nfa *nf, node *n, int *pa, int *pb); + nfa *nf, node *n, int *pa, int *pb); static int addnfastate(nfa *nf) { - nfastate *st; - - nf->nf_state = (nfastate *)PyObject_REALLOC(nf->nf_state, - sizeof(nfastate) * (nf->nf_nstates + 1)); - if (nf->nf_state == NULL) - Py_FatalError("out of mem"); - st = &nf->nf_state[nf->nf_nstates++]; - st->st_narcs = 0; - st->st_arc = NULL; - return st - nf->nf_state; + nfastate *st; + + nf->nf_state = (nfastate *)PyObject_REALLOC(nf->nf_state, + sizeof(nfastate) * (nf->nf_nstates + 1)); + if (nf->nf_state == NULL) + Py_FatalError("out of mem"); + st = &nf->nf_state[nf->nf_nstates++]; + st->st_narcs = 0; + st->st_arc = NULL; + return st - nf->nf_state; } static void addnfaarc(nfa *nf, int from, int to, int lbl) { - nfastate *st; - nfaarc *ar; - - st = &nf->nf_state[from]; - st->st_arc = (nfaarc *)PyObject_REALLOC(st->st_arc, - sizeof(nfaarc) * (st->st_narcs + 1)); - if (st->st_arc == NULL) - Py_FatalError("out of mem"); - ar = &st->st_arc[st->st_narcs++]; - ar->ar_label = lbl; - ar->ar_arrow = to; + nfastate *st; + nfaarc *ar; + + st = &nf->nf_state[from]; + st->st_arc = (nfaarc *)PyObject_REALLOC(st->st_arc, + sizeof(nfaarc) * (st->st_narcs + 1)); + if (st->st_arc == NULL) + Py_FatalError("out of mem"); + ar = &st->st_arc[st->st_narcs++]; + ar->ar_label = lbl; + ar->ar_arrow = to; } static nfa * newnfa(char *name) { - nfa *nf; - static int type = NT_OFFSET; /* All types will be disjunct */ - - nf = (nfa *)PyObject_MALLOC(sizeof(nfa)); - if (nf == NULL) - Py_FatalError("no mem for new nfa"); - nf->nf_type = type++; - nf->nf_name = name; /* XXX strdup(name) ??? */ - nf->nf_nstates = 0; - nf->nf_state = NULL; - nf->nf_start = nf->nf_finish = -1; - return nf; + nfa *nf; + static int type = NT_OFFSET; /* All types will be disjunct */ + + nf = (nfa *)PyObject_MALLOC(sizeof(nfa)); + if (nf == NULL) + Py_FatalError("no mem for new nfa"); + nf->nf_type = type++; + nf->nf_name = name; /* XXX strdup(name) ??? */ + nf->nf_nstates = 0; + nf->nf_state = NULL; + nf->nf_start = nf->nf_finish = -1; + return nf; } typedef struct _nfagrammar { - int gr_nnfas; - nfa **gr_nfa; - labellist gr_ll; + int gr_nnfas; + nfa **gr_nfa; + labellist gr_ll; } nfagrammar; /* Forward */ @@ -104,32 +104,32 @@ static nfagrammar * newnfagrammar(void) { - nfagrammar *gr; - - gr = (nfagrammar *)PyObject_MALLOC(sizeof(nfagrammar)); - if (gr == NULL) - Py_FatalError("no mem for new nfa grammar"); - gr->gr_nnfas = 0; - gr->gr_nfa = NULL; - gr->gr_ll.ll_nlabels = 0; - gr->gr_ll.ll_label = NULL; - addlabel(&gr->gr_ll, ENDMARKER, "EMPTY"); - return gr; + nfagrammar *gr; + + gr = (nfagrammar *)PyObject_MALLOC(sizeof(nfagrammar)); + if (gr == NULL) + Py_FatalError("no mem for new nfa grammar"); + gr->gr_nnfas = 0; + gr->gr_nfa = NULL; + gr->gr_ll.ll_nlabels = 0; + gr->gr_ll.ll_label = NULL; + addlabel(&gr->gr_ll, ENDMARKER, "EMPTY"); + return gr; } static nfa * addnfa(nfagrammar *gr, char *name) { - nfa *nf; - - nf = newnfa(name); - gr->gr_nfa = (nfa **)PyObject_REALLOC(gr->gr_nfa, - sizeof(nfa*) * (gr->gr_nnfas + 1)); - if (gr->gr_nfa == NULL) - Py_FatalError("out of mem"); - gr->gr_nfa[gr->gr_nnfas++] = nf; - addlabel(&gr->gr_ll, NAME, nf->nf_name); - return nf; + nfa *nf; + + nf = newnfa(name); + gr->gr_nfa = (nfa **)PyObject_REALLOC(gr->gr_nfa, + sizeof(nfa*) * (gr->gr_nnfas + 1)); + if (gr->gr_nfa == NULL) + Py_FatalError("out of mem"); + gr->gr_nfa[gr->gr_nnfas++] = nf; + addlabel(&gr->gr_ll, NAME, nf->nf_name); + return nf; } #ifdef Py_DEBUG @@ -137,203 +137,203 @@ static char REQNFMT[] = "metacompile: less than %d children\n"; #define REQN(i, count) \ - if (i < count) { \ - fprintf(stderr, REQNFMT, count); \ - Py_FatalError("REQN"); \ - } else + if (i < count) { \ + fprintf(stderr, REQNFMT, count); \ + Py_FatalError("REQN"); \ + } else #else -#define REQN(i, count) /* empty */ +#define REQN(i, count) /* empty */ #endif static nfagrammar * metacompile(node *n) { - nfagrammar *gr; - int i; + nfagrammar *gr; + int i; - if (Py_DebugFlag) - printf("Compiling (meta-) parse tree into NFA grammar\n"); - gr = newnfagrammar(); - REQ(n, MSTART); - i = n->n_nchildren - 1; /* Last child is ENDMARKER */ - n = n->n_child; - for (; --i >= 0; n++) { - if (n->n_type != NEWLINE) - compile_rule(gr, n); - } - return gr; + if (Py_DebugFlag) + printf("Compiling (meta-) parse tree into NFA grammar\n"); + gr = newnfagrammar(); + REQ(n, MSTART); + i = n->n_nchildren - 1; /* Last child is ENDMARKER */ + n = n->n_child; + for (; --i >= 0; n++) { + if (n->n_type != NEWLINE) + compile_rule(gr, n); + } + return gr; } static void compile_rule(nfagrammar *gr, node *n) { - nfa *nf; - - REQ(n, RULE); - REQN(n->n_nchildren, 4); - n = n->n_child; - REQ(n, NAME); - nf = addnfa(gr, n->n_str); - n++; - REQ(n, COLON); - n++; - REQ(n, RHS); - compile_rhs(&gr->gr_ll, nf, n, &nf->nf_start, &nf->nf_finish); - n++; - REQ(n, NEWLINE); + nfa *nf; + + REQ(n, RULE); + REQN(n->n_nchildren, 4); + n = n->n_child; + REQ(n, NAME); + nf = addnfa(gr, n->n_str); + n++; + REQ(n, COLON); + n++; + REQ(n, RHS); + compile_rhs(&gr->gr_ll, nf, n, &nf->nf_start, &nf->nf_finish); + n++; + REQ(n, NEWLINE); } static void compile_rhs(labellist *ll, nfa *nf, node *n, int *pa, int *pb) { - int i; - int a, b; - - REQ(n, RHS); - i = n->n_nchildren; - REQN(i, 1); - n = n->n_child; - REQ(n, ALT); - compile_alt(ll, nf, n, pa, pb); - if (--i <= 0) - return; - n++; - a = *pa; - b = *pb; - *pa = addnfastate(nf); - *pb = addnfastate(nf); - addnfaarc(nf, *pa, a, EMPTY); - addnfaarc(nf, b, *pb, EMPTY); - for (; --i >= 0; n++) { - REQ(n, VBAR); - REQN(i, 1); - --i; - n++; - REQ(n, ALT); - compile_alt(ll, nf, n, &a, &b); - addnfaarc(nf, *pa, a, EMPTY); - addnfaarc(nf, b, *pb, EMPTY); - } + int i; + int a, b; + + REQ(n, RHS); + i = n->n_nchildren; + REQN(i, 1); + n = n->n_child; + REQ(n, ALT); + compile_alt(ll, nf, n, pa, pb); + if (--i <= 0) + return; + n++; + a = *pa; + b = *pb; + *pa = addnfastate(nf); + *pb = addnfastate(nf); + addnfaarc(nf, *pa, a, EMPTY); + addnfaarc(nf, b, *pb, EMPTY); + for (; --i >= 0; n++) { + REQ(n, VBAR); + REQN(i, 1); + --i; + n++; + REQ(n, ALT); + compile_alt(ll, nf, n, &a, &b); + addnfaarc(nf, *pa, a, EMPTY); + addnfaarc(nf, b, *pb, EMPTY); + } } static void compile_alt(labellist *ll, nfa *nf, node *n, int *pa, int *pb) { - int i; - int a, b; - - REQ(n, ALT); - i = n->n_nchildren; - REQN(i, 1); - n = n->n_child; - REQ(n, ITEM); - compile_item(ll, nf, n, pa, pb); - --i; - n++; - for (; --i >= 0; n++) { - REQ(n, ITEM); - compile_item(ll, nf, n, &a, &b); - addnfaarc(nf, *pb, a, EMPTY); - *pb = b; - } + int i; + int a, b; + + REQ(n, ALT); + i = n->n_nchildren; + REQN(i, 1); + n = n->n_child; + REQ(n, ITEM); + compile_item(ll, nf, n, pa, pb); + --i; + n++; + for (; --i >= 0; n++) { + REQ(n, ITEM); + compile_item(ll, nf, n, &a, &b); + addnfaarc(nf, *pb, a, EMPTY); + *pb = b; + } } static void compile_item(labellist *ll, nfa *nf, node *n, int *pa, int *pb) { - int i; - int a, b; - - REQ(n, ITEM); - i = n->n_nchildren; - REQN(i, 1); - n = n->n_child; - if (n->n_type == LSQB) { - REQN(i, 3); - n++; - REQ(n, RHS); - *pa = addnfastate(nf); - *pb = addnfastate(nf); - addnfaarc(nf, *pa, *pb, EMPTY); - compile_rhs(ll, nf, n, &a, &b); - addnfaarc(nf, *pa, a, EMPTY); - addnfaarc(nf, b, *pb, EMPTY); - REQN(i, 1); - n++; - REQ(n, RSQB); - } - else { - compile_atom(ll, nf, n, pa, pb); - if (--i <= 0) - return; - n++; - addnfaarc(nf, *pb, *pa, EMPTY); - if (n->n_type == STAR) - *pb = *pa; - else - REQ(n, PLUS); - } + int i; + int a, b; + + REQ(n, ITEM); + i = n->n_nchildren; + REQN(i, 1); + n = n->n_child; + if (n->n_type == LSQB) { + REQN(i, 3); + n++; + REQ(n, RHS); + *pa = addnfastate(nf); + *pb = addnfastate(nf); + addnfaarc(nf, *pa, *pb, EMPTY); + compile_rhs(ll, nf, n, &a, &b); + addnfaarc(nf, *pa, a, EMPTY); + addnfaarc(nf, b, *pb, EMPTY); + REQN(i, 1); + n++; + REQ(n, RSQB); + } + else { + compile_atom(ll, nf, n, pa, pb); + if (--i <= 0) + return; + n++; + addnfaarc(nf, *pb, *pa, EMPTY); + if (n->n_type == STAR) + *pb = *pa; + else + REQ(n, PLUS); + } } static void compile_atom(labellist *ll, nfa *nf, node *n, int *pa, int *pb) { - int i; - - REQ(n, ATOM); - i = n->n_nchildren; - REQN(i, 1); - n = n->n_child; - if (n->n_type == LPAR) { - REQN(i, 3); - n++; - REQ(n, RHS); - compile_rhs(ll, nf, n, pa, pb); - n++; - REQ(n, RPAR); - } - else if (n->n_type == NAME || n->n_type == STRING) { - *pa = addnfastate(nf); - *pb = addnfastate(nf); - addnfaarc(nf, *pa, *pb, addlabel(ll, n->n_type, n->n_str)); - } - else - REQ(n, NAME); + int i; + + REQ(n, ATOM); + i = n->n_nchildren; + REQN(i, 1); + n = n->n_child; + if (n->n_type == LPAR) { + REQN(i, 3); + n++; + REQ(n, RHS); + compile_rhs(ll, nf, n, pa, pb); + n++; + REQ(n, RPAR); + } + else if (n->n_type == NAME || n->n_type == STRING) { + *pa = addnfastate(nf); + *pb = addnfastate(nf); + addnfaarc(nf, *pa, *pb, addlabel(ll, n->n_type, n->n_str)); + } + else + REQ(n, NAME); } static void dumpstate(labellist *ll, nfa *nf, int istate) { - nfastate *st; - int i; - nfaarc *ar; - - printf("%c%2d%c", - istate == nf->nf_start ? '*' : ' ', - istate, - istate == nf->nf_finish ? '.' : ' '); - st = &nf->nf_state[istate]; - ar = st->st_arc; - for (i = 0; i < st->st_narcs; i++) { - if (i > 0) - printf("\n "); - printf("-> %2d %s", ar->ar_arrow, - PyGrammar_LabelRepr(&ll->ll_label[ar->ar_label])); - ar++; - } - printf("\n"); + nfastate *st; + int i; + nfaarc *ar; + + printf("%c%2d%c", + istate == nf->nf_start ? '*' : ' ', + istate, + istate == nf->nf_finish ? '.' : ' '); + st = &nf->nf_state[istate]; + ar = st->st_arc; + for (i = 0; i < st->st_narcs; i++) { + if (i > 0) + printf("\n "); + printf("-> %2d %s", ar->ar_arrow, + PyGrammar_LabelRepr(&ll->ll_label[ar->ar_label])); + ar++; + } + printf("\n"); } static void dumpnfa(labellist *ll, nfa *nf) { - int i; - - printf("NFA '%s' has %d states; start %d, finish %d\n", - nf->nf_name, nf->nf_nstates, nf->nf_start, nf->nf_finish); - for (i = 0; i < nf->nf_nstates; i++) - dumpstate(ll, nf, i); + int i; + + printf("NFA '%s' has %d states; start %d, finish %d\n", + nf->nf_name, nf->nf_nstates, nf->nf_start, nf->nf_finish); + for (i = 0; i < nf->nf_nstates; i++) + dumpstate(ll, nf, i); } @@ -342,184 +342,184 @@ static void addclosure(bitset ss, nfa *nf, int istate) { - if (addbit(ss, istate)) { - nfastate *st = &nf->nf_state[istate]; - nfaarc *ar = st->st_arc; - int i; - - for (i = st->st_narcs; --i >= 0; ) { - if (ar->ar_label == EMPTY) - addclosure(ss, nf, ar->ar_arrow); - ar++; - } - } + if (addbit(ss, istate)) { + nfastate *st = &nf->nf_state[istate]; + nfaarc *ar = st->st_arc; + int i; + + for (i = st->st_narcs; --i >= 0; ) { + if (ar->ar_label == EMPTY) + addclosure(ss, nf, ar->ar_arrow); + ar++; + } + } } typedef struct _ss_arc { - bitset sa_bitset; - int sa_arrow; - int sa_label; + bitset sa_bitset; + int sa_arrow; + int sa_label; } ss_arc; typedef struct _ss_state { - bitset ss_ss; - int ss_narcs; - struct _ss_arc *ss_arc; - int ss_deleted; - int ss_finish; - int ss_rename; + bitset ss_ss; + int ss_narcs; + struct _ss_arc *ss_arc; + int ss_deleted; + int ss_finish; + int ss_rename; } ss_state; typedef struct _ss_dfa { - int sd_nstates; - ss_state *sd_state; + int sd_nstates; + ss_state *sd_state; } ss_dfa; /* Forward */ static void printssdfa(int xx_nstates, ss_state *xx_state, int nbits, - labellist *ll, char *msg); + labellist *ll, char *msg); static void simplify(int xx_nstates, ss_state *xx_state); static void convert(dfa *d, int xx_nstates, ss_state *xx_state); static void makedfa(nfagrammar *gr, nfa *nf, dfa *d) { - int nbits = nf->nf_nstates; - bitset ss; - int xx_nstates; - ss_state *xx_state, *yy; - ss_arc *zz; - int istate, jstate, iarc, jarc, ibit; - nfastate *st; - nfaarc *ar; - - ss = newbitset(nbits); - addclosure(ss, nf, nf->nf_start); - xx_state = (ss_state *)PyObject_MALLOC(sizeof(ss_state)); - if (xx_state == NULL) - Py_FatalError("no mem for xx_state in makedfa"); - xx_nstates = 1; - yy = &xx_state[0]; - yy->ss_ss = ss; - yy->ss_narcs = 0; - yy->ss_arc = NULL; - yy->ss_deleted = 0; - yy->ss_finish = testbit(ss, nf->nf_finish); - if (yy->ss_finish) - printf("Error: nonterminal '%s' may produce empty.\n", - nf->nf_name); - - /* This algorithm is from a book written before - the invention of structured programming... */ - - /* For each unmarked state... */ - for (istate = 0; istate < xx_nstates; ++istate) { - size_t size; - yy = &xx_state[istate]; - ss = yy->ss_ss; - /* For all its states... */ - for (ibit = 0; ibit < nf->nf_nstates; ++ibit) { - if (!testbit(ss, ibit)) - continue; - st = &nf->nf_state[ibit]; - /* For all non-empty arcs from this state... */ - for (iarc = 0; iarc < st->st_narcs; iarc++) { - ar = &st->st_arc[iarc]; - if (ar->ar_label == EMPTY) - continue; - /* Look up in list of arcs from this state */ - for (jarc = 0; jarc < yy->ss_narcs; ++jarc) { - zz = &yy->ss_arc[jarc]; - if (ar->ar_label == zz->sa_label) - goto found; - } - /* Add new arc for this state */ - size = sizeof(ss_arc) * (yy->ss_narcs + 1); - yy->ss_arc = (ss_arc *)PyObject_REALLOC( - yy->ss_arc, size); - if (yy->ss_arc == NULL) - Py_FatalError("out of mem"); - zz = &yy->ss_arc[yy->ss_narcs++]; - zz->sa_label = ar->ar_label; - zz->sa_bitset = newbitset(nbits); - zz->sa_arrow = -1; - found: ; - /* Add destination */ - addclosure(zz->sa_bitset, nf, ar->ar_arrow); - } - } - /* Now look up all the arrow states */ - for (jarc = 0; jarc < xx_state[istate].ss_narcs; jarc++) { - zz = &xx_state[istate].ss_arc[jarc]; - for (jstate = 0; jstate < xx_nstates; jstate++) { - if (samebitset(zz->sa_bitset, - xx_state[jstate].ss_ss, nbits)) { - zz->sa_arrow = jstate; - goto done; - } - } - size = sizeof(ss_state) * (xx_nstates + 1); - xx_state = (ss_state *)PyObject_REALLOC(xx_state, - size); - if (xx_state == NULL) - Py_FatalError("out of mem"); - zz->sa_arrow = xx_nstates; - yy = &xx_state[xx_nstates++]; - yy->ss_ss = zz->sa_bitset; - yy->ss_narcs = 0; - yy->ss_arc = NULL; - yy->ss_deleted = 0; - yy->ss_finish = testbit(yy->ss_ss, nf->nf_finish); - done: ; - } - } - - if (Py_DebugFlag) - printssdfa(xx_nstates, xx_state, nbits, &gr->gr_ll, - "before minimizing"); - - simplify(xx_nstates, xx_state); - - if (Py_DebugFlag) - printssdfa(xx_nstates, xx_state, nbits, &gr->gr_ll, - "after minimizing"); - - convert(d, xx_nstates, xx_state); - - /* XXX cleanup */ - PyObject_FREE(xx_state); + int nbits = nf->nf_nstates; + bitset ss; + int xx_nstates; + ss_state *xx_state, *yy; + ss_arc *zz; + int istate, jstate, iarc, jarc, ibit; + nfastate *st; + nfaarc *ar; + + ss = newbitset(nbits); + addclosure(ss, nf, nf->nf_start); + xx_state = (ss_state *)PyObject_MALLOC(sizeof(ss_state)); + if (xx_state == NULL) + Py_FatalError("no mem for xx_state in makedfa"); + xx_nstates = 1; + yy = &xx_state[0]; + yy->ss_ss = ss; + yy->ss_narcs = 0; + yy->ss_arc = NULL; + yy->ss_deleted = 0; + yy->ss_finish = testbit(ss, nf->nf_finish); + if (yy->ss_finish) + printf("Error: nonterminal '%s' may produce empty.\n", + nf->nf_name); + + /* This algorithm is from a book written before + the invention of structured programming... */ + + /* For each unmarked state... */ + for (istate = 0; istate < xx_nstates; ++istate) { + size_t size; + yy = &xx_state[istate]; + ss = yy->ss_ss; + /* For all its states... */ + for (ibit = 0; ibit < nf->nf_nstates; ++ibit) { + if (!testbit(ss, ibit)) + continue; + st = &nf->nf_state[ibit]; + /* For all non-empty arcs from this state... */ + for (iarc = 0; iarc < st->st_narcs; iarc++) { + ar = &st->st_arc[iarc]; + if (ar->ar_label == EMPTY) + continue; + /* Look up in list of arcs from this state */ + for (jarc = 0; jarc < yy->ss_narcs; ++jarc) { + zz = &yy->ss_arc[jarc]; + if (ar->ar_label == zz->sa_label) + goto found; + } + /* Add new arc for this state */ + size = sizeof(ss_arc) * (yy->ss_narcs + 1); + yy->ss_arc = (ss_arc *)PyObject_REALLOC( + yy->ss_arc, size); + if (yy->ss_arc == NULL) + Py_FatalError("out of mem"); + zz = &yy->ss_arc[yy->ss_narcs++]; + zz->sa_label = ar->ar_label; + zz->sa_bitset = newbitset(nbits); + zz->sa_arrow = -1; + found: ; + /* Add destination */ + addclosure(zz->sa_bitset, nf, ar->ar_arrow); + } + } + /* Now look up all the arrow states */ + for (jarc = 0; jarc < xx_state[istate].ss_narcs; jarc++) { + zz = &xx_state[istate].ss_arc[jarc]; + for (jstate = 0; jstate < xx_nstates; jstate++) { + if (samebitset(zz->sa_bitset, + xx_state[jstate].ss_ss, nbits)) { + zz->sa_arrow = jstate; + goto done; + } + } + size = sizeof(ss_state) * (xx_nstates + 1); + xx_state = (ss_state *)PyObject_REALLOC(xx_state, + size); + if (xx_state == NULL) + Py_FatalError("out of mem"); + zz->sa_arrow = xx_nstates; + yy = &xx_state[xx_nstates++]; + yy->ss_ss = zz->sa_bitset; + yy->ss_narcs = 0; + yy->ss_arc = NULL; + yy->ss_deleted = 0; + yy->ss_finish = testbit(yy->ss_ss, nf->nf_finish); + done: ; + } + } + + if (Py_DebugFlag) + printssdfa(xx_nstates, xx_state, nbits, &gr->gr_ll, + "before minimizing"); + + simplify(xx_nstates, xx_state); + + if (Py_DebugFlag) + printssdfa(xx_nstates, xx_state, nbits, &gr->gr_ll, + "after minimizing"); + + convert(d, xx_nstates, xx_state); + + /* XXX cleanup */ + PyObject_FREE(xx_state); } static void printssdfa(int xx_nstates, ss_state *xx_state, int nbits, - labellist *ll, char *msg) + labellist *ll, char *msg) { - int i, ibit, iarc; - ss_state *yy; - ss_arc *zz; - - printf("Subset DFA %s\n", msg); - for (i = 0; i < xx_nstates; i++) { - yy = &xx_state[i]; - if (yy->ss_deleted) - continue; - printf(" Subset %d", i); - if (yy->ss_finish) - printf(" (finish)"); - printf(" { "); - for (ibit = 0; ibit < nbits; ibit++) { - if (testbit(yy->ss_ss, ibit)) - printf("%d ", ibit); - } - printf("}\n"); - for (iarc = 0; iarc < yy->ss_narcs; iarc++) { - zz = &yy->ss_arc[iarc]; - printf(" Arc to state %d, label %s\n", - zz->sa_arrow, - PyGrammar_LabelRepr( - &ll->ll_label[zz->sa_label])); - } - } + int i, ibit, iarc; + ss_state *yy; + ss_arc *zz; + + printf("Subset DFA %s\n", msg); + for (i = 0; i < xx_nstates; i++) { + yy = &xx_state[i]; + if (yy->ss_deleted) + continue; + printf(" Subset %d", i); + if (yy->ss_finish) + printf(" (finish)"); + printf(" { "); + for (ibit = 0; ibit < nbits; ibit++) { + if (testbit(yy->ss_ss, ibit)) + printf("%d ", ibit); + } + printf("}\n"); + for (iarc = 0; iarc < yy->ss_narcs; iarc++) { + zz = &yy->ss_arc[iarc]; + printf(" Arc to state %d, label %s\n", + zz->sa_arrow, + PyGrammar_LabelRepr( + &ll->ll_label[zz->sa_label])); + } + } } @@ -535,59 +535,59 @@ static int samestate(ss_state *s1, ss_state *s2) { - int i; - - if (s1->ss_narcs != s2->ss_narcs || s1->ss_finish != s2->ss_finish) - return 0; - for (i = 0; i < s1->ss_narcs; i++) { - if (s1->ss_arc[i].sa_arrow != s2->ss_arc[i].sa_arrow || - s1->ss_arc[i].sa_label != s2->ss_arc[i].sa_label) - return 0; - } - return 1; + int i; + + if (s1->ss_narcs != s2->ss_narcs || s1->ss_finish != s2->ss_finish) + return 0; + for (i = 0; i < s1->ss_narcs; i++) { + if (s1->ss_arc[i].sa_arrow != s2->ss_arc[i].sa_arrow || + s1->ss_arc[i].sa_label != s2->ss_arc[i].sa_label) + return 0; + } + return 1; } static void renamestates(int xx_nstates, ss_state *xx_state, int from, int to) { - int i, j; - - if (Py_DebugFlag) - printf("Rename state %d to %d.\n", from, to); - for (i = 0; i < xx_nstates; i++) { - if (xx_state[i].ss_deleted) - continue; - for (j = 0; j < xx_state[i].ss_narcs; j++) { - if (xx_state[i].ss_arc[j].sa_arrow == from) - xx_state[i].ss_arc[j].sa_arrow = to; - } - } + int i, j; + + if (Py_DebugFlag) + printf("Rename state %d to %d.\n", from, to); + for (i = 0; i < xx_nstates; i++) { + if (xx_state[i].ss_deleted) + continue; + for (j = 0; j < xx_state[i].ss_narcs; j++) { + if (xx_state[i].ss_arc[j].sa_arrow == from) + xx_state[i].ss_arc[j].sa_arrow = to; + } + } } static void simplify(int xx_nstates, ss_state *xx_state) { - int changes; - int i, j; - - do { - changes = 0; - for (i = 1; i < xx_nstates; i++) { - if (xx_state[i].ss_deleted) - continue; - for (j = 0; j < i; j++) { - if (xx_state[j].ss_deleted) - continue; - if (samestate(&xx_state[i], &xx_state[j])) { - xx_state[i].ss_deleted++; - renamestates(xx_nstates, xx_state, - i, j); - changes++; - break; - } - } - } - } while (changes); + int changes; + int i, j; + + do { + changes = 0; + for (i = 1; i < xx_nstates; i++) { + if (xx_state[i].ss_deleted) + continue; + for (j = 0; j < i; j++) { + if (xx_state[j].ss_deleted) + continue; + if (samestate(&xx_state[i], &xx_state[j])) { + xx_state[i].ss_deleted++; + renamestates(xx_nstates, xx_state, + i, j); + changes++; + break; + } + } + } + } while (changes); } @@ -598,32 +598,32 @@ static void convert(dfa *d, int xx_nstates, ss_state *xx_state) { - int i, j; - ss_state *yy; - ss_arc *zz; - - for (i = 0; i < xx_nstates; i++) { - yy = &xx_state[i]; - if (yy->ss_deleted) - continue; - yy->ss_rename = addstate(d); - } - - for (i = 0; i < xx_nstates; i++) { - yy = &xx_state[i]; - if (yy->ss_deleted) - continue; - for (j = 0; j < yy->ss_narcs; j++) { - zz = &yy->ss_arc[j]; - addarc(d, yy->ss_rename, - xx_state[zz->sa_arrow].ss_rename, - zz->sa_label); - } - if (yy->ss_finish) - addarc(d, yy->ss_rename, yy->ss_rename, 0); - } - - d->d_initial = 0; + int i, j; + ss_state *yy; + ss_arc *zz; + + for (i = 0; i < xx_nstates; i++) { + yy = &xx_state[i]; + if (yy->ss_deleted) + continue; + yy->ss_rename = addstate(d); + } + + for (i = 0; i < xx_nstates; i++) { + yy = &xx_state[i]; + if (yy->ss_deleted) + continue; + for (j = 0; j < yy->ss_narcs; j++) { + zz = &yy->ss_arc[j]; + addarc(d, yy->ss_rename, + xx_state[zz->sa_arrow].ss_rename, + zz->sa_label); + } + if (yy->ss_finish) + addarc(d, yy->ss_rename, yy->ss_rename, 0); + } + + d->d_initial = 0; } @@ -632,43 +632,43 @@ static grammar * maketables(nfagrammar *gr) { - int i; - nfa *nf; - dfa *d; - grammar *g; - - if (gr->gr_nnfas == 0) - return NULL; - g = newgrammar(gr->gr_nfa[0]->nf_type); - /* XXX first rule must be start rule */ - g->g_ll = gr->gr_ll; - - for (i = 0; i < gr->gr_nnfas; i++) { - nf = gr->gr_nfa[i]; - if (Py_DebugFlag) { - printf("Dump of NFA for '%s' ...\n", nf->nf_name); - dumpnfa(&gr->gr_ll, nf); - printf("Making DFA for '%s' ...\n", nf->nf_name); - } - d = adddfa(g, nf->nf_type, nf->nf_name); - makedfa(gr, gr->gr_nfa[i], d); - } - - return g; + int i; + nfa *nf; + dfa *d; + grammar *g; + + if (gr->gr_nnfas == 0) + return NULL; + g = newgrammar(gr->gr_nfa[0]->nf_type); + /* XXX first rule must be start rule */ + g->g_ll = gr->gr_ll; + + for (i = 0; i < gr->gr_nnfas; i++) { + nf = gr->gr_nfa[i]; + if (Py_DebugFlag) { + printf("Dump of NFA for '%s' ...\n", nf->nf_name); + dumpnfa(&gr->gr_ll, nf); + printf("Making DFA for '%s' ...\n", nf->nf_name); + } + d = adddfa(g, nf->nf_type, nf->nf_name); + makedfa(gr, gr->gr_nfa[i], d); + } + + return g; } grammar * pgen(node *n) { - nfagrammar *gr; - grammar *g; - - gr = metacompile(n); - g = maketables(gr); - translatelabels(g); - addfirstsets(g); - PyObject_FREE(gr); - return g; + nfagrammar *gr; + grammar *g; + + gr = metacompile(n); + g = maketables(gr); + translatelabels(g); + addfirstsets(g); + PyObject_FREE(gr); + return g; } grammar * @@ -702,7 +702,7 @@ --------- [Aho&Ullman 77] - Aho&Ullman, Principles of Compiler Design, Addison-Wesley 1977 - (first edition) + Aho&Ullman, Principles of Compiler Design, Addison-Wesley 1977 + (first edition) */ Modified: python/branches/py3k-jit/Parser/pgenmain.c ============================================================================== --- python/branches/py3k-jit/Parser/pgenmain.c (original) +++ python/branches/py3k-jit/Parser/pgenmain.c Mon May 10 23:55:43 2010 @@ -30,104 +30,104 @@ void Py_Exit(int sts) { - exit(sts); + exit(sts); } int main(int argc, char **argv) { - grammar *g; - FILE *fp; - char *filename, *graminit_h, *graminit_c; - - if (argc != 4) { - fprintf(stderr, - "usage: %s grammar graminit.h graminit.c\n", argv[0]); - Py_Exit(2); - } - filename = argv[1]; - graminit_h = argv[2]; - graminit_c = argv[3]; - g = getgrammar(filename); - fp = fopen(graminit_c, "w"); - if (fp == NULL) { - perror(graminit_c); - Py_Exit(1); - } - if (Py_DebugFlag) - printf("Writing %s ...\n", graminit_c); - printgrammar(g, fp); - fclose(fp); - fp = fopen(graminit_h, "w"); - if (fp == NULL) { - perror(graminit_h); - Py_Exit(1); - } - if (Py_DebugFlag) - printf("Writing %s ...\n", graminit_h); - printnonterminals(g, fp); - fclose(fp); - Py_Exit(0); - return 0; /* Make gcc -Wall happy */ + grammar *g; + FILE *fp; + char *filename, *graminit_h, *graminit_c; + + if (argc != 4) { + fprintf(stderr, + "usage: %s grammar graminit.h graminit.c\n", argv[0]); + Py_Exit(2); + } + filename = argv[1]; + graminit_h = argv[2]; + graminit_c = argv[3]; + g = getgrammar(filename); + fp = fopen(graminit_c, "w"); + if (fp == NULL) { + perror(graminit_c); + Py_Exit(1); + } + if (Py_DebugFlag) + printf("Writing %s ...\n", graminit_c); + printgrammar(g, fp); + fclose(fp); + fp = fopen(graminit_h, "w"); + if (fp == NULL) { + perror(graminit_h); + Py_Exit(1); + } + if (Py_DebugFlag) + printf("Writing %s ...\n", graminit_h); + printnonterminals(g, fp); + fclose(fp); + Py_Exit(0); + return 0; /* Make gcc -Wall happy */ } grammar * getgrammar(char *filename) { - FILE *fp; - node *n; - grammar *g0, *g; - perrdetail err; - - fp = fopen(filename, "r"); - if (fp == NULL) { - perror(filename); - Py_Exit(1); - } - g0 = meta_grammar(); - n = PyParser_ParseFile(fp, filename, g0, g0->g_start, - (char *)NULL, (char *)NULL, &err); - fclose(fp); - if (n == NULL) { - fprintf(stderr, "Parsing error %d, line %d.\n", - err.error, err.lineno); - if (err.text != NULL) { - size_t i; - fprintf(stderr, "%s", err.text); - i = strlen(err.text); - if (i == 0 || err.text[i-1] != '\n') - fprintf(stderr, "\n"); - for (i = 0; i < err.offset; i++) { - if (err.text[i] == '\t') - putc('\t', stderr); - else - putc(' ', stderr); - } - fprintf(stderr, "^\n"); - PyObject_FREE(err.text); - } - Py_Exit(1); - } - g = pgen(n); - if (g == NULL) { - printf("Bad grammar.\n"); - Py_Exit(1); - } - return g; + FILE *fp; + node *n; + grammar *g0, *g; + perrdetail err; + + fp = fopen(filename, "r"); + if (fp == NULL) { + perror(filename); + Py_Exit(1); + } + g0 = meta_grammar(); + n = PyParser_ParseFile(fp, filename, g0, g0->g_start, + (char *)NULL, (char *)NULL, &err); + fclose(fp); + if (n == NULL) { + fprintf(stderr, "Parsing error %d, line %d.\n", + err.error, err.lineno); + if (err.text != NULL) { + size_t i; + fprintf(stderr, "%s", err.text); + i = strlen(err.text); + if (i == 0 || err.text[i-1] != '\n') + fprintf(stderr, "\n"); + for (i = 0; i < err.offset; i++) { + if (err.text[i] == '\t') + putc('\t', stderr); + else + putc(' ', stderr); + } + fprintf(stderr, "^\n"); + PyObject_FREE(err.text); + } + Py_Exit(1); + } + g = pgen(n); + if (g == NULL) { + printf("Bad grammar.\n"); + Py_Exit(1); + } + return g; } /* Can't happen in pgen */ PyObject* PyErr_Occurred() { - return 0; + return 0; } void Py_FatalError(const char *msg) { - fprintf(stderr, "pgen: FATAL ERROR: %s\n", msg); - Py_Exit(1); + fprintf(stderr, "pgen: FATAL ERROR: %s\n", msg); + Py_Exit(1); } /* No-nonsense my_readline() for tokenizer.c */ @@ -135,28 +135,28 @@ char * PyOS_Readline(FILE *sys_stdin, FILE *sys_stdout, char *prompt) { - size_t n = 1000; - char *p = (char *)PyMem_MALLOC(n); - char *q; - if (p == NULL) - return NULL; - fprintf(stderr, "%s", prompt); - q = fgets(p, n, sys_stdin); - if (q == NULL) { - *p = '\0'; - return p; - } - n = strlen(p); - if (n > 0 && p[n-1] != '\n') - p[n-1] = '\n'; - return (char *)PyMem_REALLOC(p, n+1); + size_t n = 1000; + char *p = (char *)PyMem_MALLOC(n); + char *q; + if (p == NULL) + return NULL; + fprintf(stderr, "%s", prompt); + q = fgets(p, n, sys_stdin); + if (q == NULL) { + *p = '\0'; + return p; + } + n = strlen(p); + if (n > 0 && p[n-1] != '\n') + p[n-1] = '\n'; + return (char *)PyMem_REALLOC(p, n+1); } /* No-nonsense fgets */ char * Py_UniversalNewlineFgets(char *buf, int n, FILE *stream, PyObject *fobj) { - return fgets(buf, n, stream); + return fgets(buf, n, stream); } @@ -165,9 +165,9 @@ void PySys_WriteStderr(const char *format, ...) { - va_list va; + va_list va; - va_start(va, format); - vfprintf(stderr, format, va); - va_end(va); + va_start(va, format); + vfprintf(stderr, format, va); + va_end(va); } Modified: python/branches/py3k-jit/Parser/printgrammar.c ============================================================================== --- python/branches/py3k-jit/Parser/printgrammar.c (original) +++ python/branches/py3k-jit/Parser/printgrammar.c Mon May 10 23:55:43 2010 @@ -13,105 +13,105 @@ void printgrammar(grammar *g, FILE *fp) { - fprintf(fp, "/* Generated by Parser/pgen */\n\n"); - fprintf(fp, "#include \"pgenheaders.h\"\n"); - fprintf(fp, "#include \"grammar.h\"\n"); - fprintf(fp, "PyAPI_DATA(grammar) _PyParser_Grammar;\n"); - printdfas(g, fp); - printlabels(g, fp); - fprintf(fp, "grammar _PyParser_Grammar = {\n"); - fprintf(fp, "\t%d,\n", g->g_ndfas); - fprintf(fp, "\tdfas,\n"); - fprintf(fp, "\t{%d, labels},\n", g->g_ll.ll_nlabels); - fprintf(fp, "\t%d\n", g->g_start); - fprintf(fp, "};\n"); + fprintf(fp, "/* Generated by Parser/pgen */\n\n"); + fprintf(fp, "#include \"pgenheaders.h\"\n"); + fprintf(fp, "#include \"grammar.h\"\n"); + fprintf(fp, "PyAPI_DATA(grammar) _PyParser_Grammar;\n"); + printdfas(g, fp); + printlabels(g, fp); + fprintf(fp, "grammar _PyParser_Grammar = {\n"); + fprintf(fp, "\t%d,\n", g->g_ndfas); + fprintf(fp, "\tdfas,\n"); + fprintf(fp, "\t{%d, labels},\n", g->g_ll.ll_nlabels); + fprintf(fp, "\t%d\n", g->g_start); + fprintf(fp, "};\n"); } void printnonterminals(grammar *g, FILE *fp) { - dfa *d; - int i; - - fprintf(fp, "/* Generated by Parser/pgen */\n\n"); - - d = g->g_dfa; - for (i = g->g_ndfas; --i >= 0; d++) - fprintf(fp, "#define %s %d\n", d->d_name, d->d_type); + dfa *d; + int i; + + fprintf(fp, "/* Generated by Parser/pgen */\n\n"); + + d = g->g_dfa; + for (i = g->g_ndfas; --i >= 0; d++) + fprintf(fp, "#define %s %d\n", d->d_name, d->d_type); } static void printarcs(int i, dfa *d, FILE *fp) { - arc *a; - state *s; - int j, k; - - s = d->d_state; - for (j = 0; j < d->d_nstates; j++, s++) { - fprintf(fp, "static arc arcs_%d_%d[%d] = {\n", - i, j, s->s_narcs); - a = s->s_arc; - for (k = 0; k < s->s_narcs; k++, a++) - fprintf(fp, "\t{%d, %d},\n", a->a_lbl, a->a_arrow); - fprintf(fp, "};\n"); - } + arc *a; + state *s; + int j, k; + + s = d->d_state; + for (j = 0; j < d->d_nstates; j++, s++) { + fprintf(fp, "static arc arcs_%d_%d[%d] = {\n", + i, j, s->s_narcs); + a = s->s_arc; + for (k = 0; k < s->s_narcs; k++, a++) + fprintf(fp, "\t{%d, %d},\n", a->a_lbl, a->a_arrow); + fprintf(fp, "};\n"); + } } static void printstates(grammar *g, FILE *fp) { - state *s; - dfa *d; - int i, j; - - d = g->g_dfa; - for (i = 0; i < g->g_ndfas; i++, d++) { - printarcs(i, d, fp); - fprintf(fp, "static state states_%d[%d] = {\n", - i, d->d_nstates); - s = d->d_state; - for (j = 0; j < d->d_nstates; j++, s++) - fprintf(fp, "\t{%d, arcs_%d_%d},\n", - s->s_narcs, i, j); - fprintf(fp, "};\n"); - } + state *s; + dfa *d; + int i, j; + + d = g->g_dfa; + for (i = 0; i < g->g_ndfas; i++, d++) { + printarcs(i, d, fp); + fprintf(fp, "static state states_%d[%d] = {\n", + i, d->d_nstates); + s = d->d_state; + for (j = 0; j < d->d_nstates; j++, s++) + fprintf(fp, "\t{%d, arcs_%d_%d},\n", + s->s_narcs, i, j); + fprintf(fp, "};\n"); + } } static void printdfas(grammar *g, FILE *fp) { - dfa *d; - int i, j; - - printstates(g, fp); - fprintf(fp, "static dfa dfas[%d] = {\n", g->g_ndfas); - d = g->g_dfa; - for (i = 0; i < g->g_ndfas; i++, d++) { - fprintf(fp, "\t{%d, \"%s\", %d, %d, states_%d,\n", - d->d_type, d->d_name, d->d_initial, d->d_nstates, i); - fprintf(fp, "\t \""); - for (j = 0; j < NBYTES(g->g_ll.ll_nlabels); j++) - fprintf(fp, "\\%03o", d->d_first[j] & 0xff); - fprintf(fp, "\"},\n"); - } - fprintf(fp, "};\n"); + dfa *d; + int i, j; + + printstates(g, fp); + fprintf(fp, "static dfa dfas[%d] = {\n", g->g_ndfas); + d = g->g_dfa; + for (i = 0; i < g->g_ndfas; i++, d++) { + fprintf(fp, "\t{%d, \"%s\", %d, %d, states_%d,\n", + d->d_type, d->d_name, d->d_initial, d->d_nstates, i); + fprintf(fp, "\t \""); + for (j = 0; j < NBYTES(g->g_ll.ll_nlabels); j++) + fprintf(fp, "\\%03o", d->d_first[j] & 0xff); + fprintf(fp, "\"},\n"); + } + fprintf(fp, "};\n"); } static void printlabels(grammar *g, FILE *fp) { - label *l; - int i; - - fprintf(fp, "static label labels[%d] = {\n", g->g_ll.ll_nlabels); - l = g->g_ll.ll_label; - for (i = g->g_ll.ll_nlabels; --i >= 0; l++) { - if (l->lb_str == NULL) - fprintf(fp, "\t{%d, 0},\n", l->lb_type); - else - fprintf(fp, "\t{%d, \"%s\"},\n", - l->lb_type, l->lb_str); - } - fprintf(fp, "};\n"); + label *l; + int i; + + fprintf(fp, "static label labels[%d] = {\n", g->g_ll.ll_nlabels); + l = g->g_ll.ll_label; + for (i = g->g_ll.ll_nlabels; --i >= 0; l++) { + if (l->lb_str == NULL) + fprintf(fp, "\t{%d, 0},\n", l->lb_type); + else + fprintf(fp, "\t{%d, \"%s\"},\n", + l->lb_type, l->lb_str); + } + fprintf(fp, "};\n"); } Modified: python/branches/py3k-jit/Parser/tokenizer.c ============================================================================== --- python/branches/py3k-jit/Parser/tokenizer.c (original) +++ python/branches/py3k-jit/Parser/tokenizer.c Mon May 10 23:55:43 2010 @@ -19,17 +19,17 @@ #endif /* PGEN */ #define is_potential_identifier_start(c) (\ - (c >= 'a' && c <= 'z')\ - || (c >= 'A' && c <= 'Z')\ - || c == '_'\ - || (c >= 128)) + (c >= 'a' && c <= 'z')\ + || (c >= 'A' && c <= 'Z')\ + || c == '_'\ + || (c >= 128)) #define is_potential_identifier_char(c) (\ - (c >= 'a' && c <= 'z')\ - || (c >= 'A' && c <= 'Z')\ - || (c >= '0' && c <= '9')\ - || c == '_'\ - || (c >= 128)) + (c >= 'a' && c <= 'z')\ + || (c >= 'A' && c <= 'Z')\ + || (c >= '0' && c <= '9')\ + || c == '_'\ + || (c >= 128)) extern char *PyOS_Readline(FILE *, FILE *, char *); /* Return malloc'ed string including trailing \n; @@ -48,62 +48,62 @@ /* Token names */ char *_PyParser_TokenNames[] = { - "ENDMARKER", - "NAME", - "NUMBER", - "STRING", - "NEWLINE", - "INDENT", - "DEDENT", - "LPAR", - "RPAR", - "LSQB", - "RSQB", - "COLON", - "COMMA", - "SEMI", - "PLUS", - "MINUS", - "STAR", - "SLASH", - "VBAR", - "AMPER", - "LESS", - "GREATER", - "EQUAL", - "DOT", - "PERCENT", - "LBRACE", - "RBRACE", - "EQEQUAL", - "NOTEQUAL", - "LESSEQUAL", - "GREATEREQUAL", - "TILDE", - "CIRCUMFLEX", - "LEFTSHIFT", - "RIGHTSHIFT", - "DOUBLESTAR", - "PLUSEQUAL", - "MINEQUAL", - "STAREQUAL", - "SLASHEQUAL", - "PERCENTEQUAL", - "AMPEREQUAL", - "VBAREQUAL", - "CIRCUMFLEXEQUAL", - "LEFTSHIFTEQUAL", - "RIGHTSHIFTEQUAL", - "DOUBLESTAREQUAL", - "DOUBLESLASH", - "DOUBLESLASHEQUAL", - "AT", - "RARROW", - "ELLIPSIS", - /* This table must match the #defines in token.h! */ - "OP", - "", - "" + "ENDMARKER", + "NAME", + "NUMBER", + "STRING", + "NEWLINE", + "INDENT", + "DEDENT", + "LPAR", + "RPAR", + "LSQB", + "RSQB", + "COLON", + "COMMA", + "SEMI", + "PLUS", + "MINUS", + "STAR", + "SLASH", + "VBAR", + "AMPER", + "LESS", + "GREATER", + "EQUAL", + "DOT", + "PERCENT", + "LBRACE", + "RBRACE", + "EQEQUAL", + "NOTEQUAL", + "LESSEQUAL", + "GREATEREQUAL", + "TILDE", + "CIRCUMFLEX", + "LEFTSHIFT", + "RIGHTSHIFT", + "DOUBLESTAR", + "PLUSEQUAL", + "MINEQUAL", + "STAREQUAL", + "SLASHEQUAL", + "PERCENTEQUAL", + "AMPEREQUAL", + "VBAREQUAL", + "CIRCUMFLEXEQUAL", + "LEFTSHIFTEQUAL", + "RIGHTSHIFTEQUAL", + "DOUBLESTAREQUAL", + "DOUBLESLASH", + "DOUBLESLASHEQUAL", + "AT", + "RARROW", + "ELLIPSIS", + /* This table must match the #defines in token.h! */ + "OP", + "", + "" }; @@ -112,49 +112,49 @@ static struct tok_state * tok_new(void) { - struct tok_state *tok = (struct tok_state *)PyMem_MALLOC( - sizeof(struct tok_state)); - if (tok == NULL) - return NULL; - tok->buf = tok->cur = tok->end = tok->inp = tok->start = NULL; - tok->done = E_OK; - tok->fp = NULL; - tok->input = NULL; - tok->tabsize = TABSIZE; - tok->indent = 0; - tok->indstack[0] = 0; - tok->atbol = 1; - tok->pendin = 0; - tok->prompt = tok->nextprompt = NULL; - tok->lineno = 0; - tok->level = 0; - tok->filename = NULL; - tok->altwarning = 1; - tok->alterror = 1; - tok->alttabsize = 1; - tok->altindstack[0] = 0; - tok->decoding_state = STATE_INIT; - tok->decoding_erred = 0; - tok->read_coding_spec = 0; - tok->enc = NULL; - tok->encoding = NULL; - tok->cont_line = 0; + struct tok_state *tok = (struct tok_state *)PyMem_MALLOC( + sizeof(struct tok_state)); + if (tok == NULL) + return NULL; + tok->buf = tok->cur = tok->end = tok->inp = tok->start = NULL; + tok->done = E_OK; + tok->fp = NULL; + tok->input = NULL; + tok->tabsize = TABSIZE; + tok->indent = 0; + tok->indstack[0] = 0; + tok->atbol = 1; + tok->pendin = 0; + tok->prompt = tok->nextprompt = NULL; + tok->lineno = 0; + tok->level = 0; + tok->filename = NULL; + tok->altwarning = 1; + tok->alterror = 1; + tok->alttabsize = 1; + tok->altindstack[0] = 0; + tok->decoding_state = STATE_INIT; + tok->decoding_erred = 0; + tok->read_coding_spec = 0; + tok->enc = NULL; + tok->encoding = NULL; + tok->cont_line = 0; #ifndef PGEN - tok->decoding_readline = NULL; - tok->decoding_buffer = NULL; + tok->decoding_readline = NULL; + tok->decoding_buffer = NULL; #endif - return tok; + return tok; } static char * new_string(const char *s, Py_ssize_t len) { - char* result = (char *)PyMem_MALLOC(len + 1); - if (result != NULL) { - memcpy(result, s, len); - result[len] = '\0'; - } - return result; + char* result = (char *)PyMem_MALLOC(len + 1); + if (result != NULL) { + memcpy(result, s, len); + result[len] = '\0'; + } + return result; } #ifdef PGEN @@ -162,19 +162,19 @@ static char * decoding_fgets(char *s, int size, struct tok_state *tok) { - return fgets(s, size, tok->fp); + return fgets(s, size, tok->fp); } static int decoding_feof(struct tok_state *tok) { - return feof(tok->fp); + return feof(tok->fp); } static char * decode_str(const char *str, int exec_input, struct tok_state *tok) { - return new_string(str, strlen(str)); + return new_string(str, strlen(str)); } #else /* PGEN */ @@ -182,41 +182,41 @@ static char * error_ret(struct tok_state *tok) /* XXX */ { - tok->decoding_erred = 1; - if (tok->fp != NULL && tok->buf != NULL) /* see PyTokenizer_Free */ - PyMem_FREE(tok->buf); - tok->buf = NULL; - return NULL; /* as if it were EOF */ + tok->decoding_erred = 1; + if (tok->fp != NULL && tok->buf != NULL) /* see PyTokenizer_Free */ + PyMem_FREE(tok->buf); + tok->buf = NULL; + return NULL; /* as if it were EOF */ } static char * -get_normal_name(char *s) /* for utf-8 and latin-1 */ +get_normal_name(char *s) /* for utf-8 and latin-1 */ { - char buf[13]; - int i; - for (i = 0; i < 12; i++) { - int c = s[i]; - if (c == '\0') - break; - else if (c == '_') - buf[i] = '-'; - else - buf[i] = tolower(c); - } - buf[i] = '\0'; - if (strcmp(buf, "utf-8") == 0 || - strncmp(buf, "utf-8-", 6) == 0) - return "utf-8"; - else if (strcmp(buf, "latin-1") == 0 || - strcmp(buf, "iso-8859-1") == 0 || - strcmp(buf, "iso-latin-1") == 0 || - strncmp(buf, "latin-1-", 8) == 0 || - strncmp(buf, "iso-8859-1-", 11) == 0 || - strncmp(buf, "iso-latin-1-", 12) == 0) - return "iso-8859-1"; - else - return s; + char buf[13]; + int i; + for (i = 0; i < 12; i++) { + int c = s[i]; + if (c == '\0') + break; + else if (c == '_') + buf[i] = '-'; + else + buf[i] = tolower(c); + } + buf[i] = '\0'; + if (strcmp(buf, "utf-8") == 0 || + strncmp(buf, "utf-8-", 6) == 0) + return "utf-8"; + else if (strcmp(buf, "latin-1") == 0 || + strcmp(buf, "iso-8859-1") == 0 || + strcmp(buf, "iso-latin-1") == 0 || + strncmp(buf, "latin-1-", 8) == 0 || + strncmp(buf, "iso-8859-1-", 11) == 0 || + strncmp(buf, "iso-latin-1-", 12) == 0) + return "iso-8859-1"; + else + return s; } /* Return the coding spec in S, or NULL if none is found. */ @@ -224,43 +224,43 @@ static char * get_coding_spec(const char *s, Py_ssize_t size) { - Py_ssize_t i; - /* Coding spec must be in a comment, and that comment must be - * the only statement on the source code line. */ - for (i = 0; i < size - 6; i++) { - if (s[i] == '#') - break; - if (s[i] != ' ' && s[i] != '\t' && s[i] != '\014') - return NULL; - } - for (; i < size - 6; i++) { /* XXX inefficient search */ - const char* t = s + i; - if (strncmp(t, "coding", 6) == 0) { - const char* begin = NULL; - t += 6; - if (t[0] != ':' && t[0] != '=') - continue; - do { - t++; - } while (t[0] == '\x20' || t[0] == '\t'); - - begin = t; - while (Py_ISALNUM(t[0]) || - t[0] == '-' || t[0] == '_' || t[0] == '.') - t++; - - if (begin < t) { - char* r = new_string(begin, t - begin); - char* q = get_normal_name(r); - if (r != q) { - PyMem_FREE(r); - r = new_string(q, strlen(q)); - } - return r; - } - } - } - return NULL; + Py_ssize_t i; + /* Coding spec must be in a comment, and that comment must be + * the only statement on the source code line. */ + for (i = 0; i < size - 6; i++) { + if (s[i] == '#') + break; + if (s[i] != ' ' && s[i] != '\t' && s[i] != '\014') + return NULL; + } + for (; i < size - 6; i++) { /* XXX inefficient search */ + const char* t = s + i; + if (strncmp(t, "coding", 6) == 0) { + const char* begin = NULL; + t += 6; + if (t[0] != ':' && t[0] != '=') + continue; + do { + t++; + } while (t[0] == '\x20' || t[0] == '\t'); + + begin = t; + while (Py_ISALNUM(t[0]) || + t[0] == '-' || t[0] == '_' || t[0] == '.') + t++; + + if (begin < t) { + char* r = new_string(begin, t - begin); + char* q = get_normal_name(r); + if (r != q) { + PyMem_FREE(r); + r = new_string(q, strlen(q)); + } + return r; + } + } + } + return NULL; } /* Check whether the line contains a coding spec. If it does, @@ -270,42 +270,42 @@ static int check_coding_spec(const char* line, Py_ssize_t size, struct tok_state *tok, - int set_readline(struct tok_state *, const char *)) + int set_readline(struct tok_state *, const char *)) { - char * cs; - int r = 1; + char * cs; + int r = 1; - if (tok->cont_line) - /* It's a continuation line, so it can't be a coding spec. */ - return 1; - cs = get_coding_spec(line, size); - if (cs != NULL) { - tok->read_coding_spec = 1; - if (tok->encoding == NULL) { - assert(tok->decoding_state == STATE_RAW); - if (strcmp(cs, "utf-8") == 0) { - tok->encoding = cs; - } else { - r = set_readline(tok, cs); - if (r) { - tok->encoding = cs; - tok->decoding_state = STATE_NORMAL; - } - else - PyMem_FREE(cs); - } - } else { /* then, compare cs with BOM */ - r = (strcmp(tok->encoding, cs) == 0); - PyMem_FREE(cs); - } - } - if (!r) { - cs = tok->encoding; - if (!cs) - cs = "with BOM"; - PyErr_Format(PyExc_SyntaxError, "encoding problem: %s", cs); - } - return r; + if (tok->cont_line) + /* It's a continuation line, so it can't be a coding spec. */ + return 1; + cs = get_coding_spec(line, size); + if (cs != NULL) { + tok->read_coding_spec = 1; + if (tok->encoding == NULL) { + assert(tok->decoding_state == STATE_RAW); + if (strcmp(cs, "utf-8") == 0) { + tok->encoding = cs; + } else { + r = set_readline(tok, cs); + if (r) { + tok->encoding = cs; + tok->decoding_state = STATE_NORMAL; + } + else + PyMem_FREE(cs); + } + } else { /* then, compare cs with BOM */ + r = (strcmp(tok->encoding, cs) == 0); + PyMem_FREE(cs); + } + } + if (!r) { + cs = tok->encoding; + if (!cs) + cs = "with BOM"; + PyErr_Format(PyExc_SyntaxError, "encoding problem: %s", cs); + } + return r; } /* See whether the file starts with a BOM. If it does, @@ -314,62 +314,62 @@ static int check_bom(int get_char(struct tok_state *), - void unget_char(int, struct tok_state *), - int set_readline(struct tok_state *, const char *), - struct tok_state *tok) -{ - int ch1, ch2, ch3; - ch1 = get_char(tok); - tok->decoding_state = STATE_RAW; - if (ch1 == EOF) { - return 1; - } else if (ch1 == 0xEF) { - ch2 = get_char(tok); - if (ch2 != 0xBB) { - unget_char(ch2, tok); - unget_char(ch1, tok); - return 1; - } - ch3 = get_char(tok); - if (ch3 != 0xBF) { - unget_char(ch3, tok); - unget_char(ch2, tok); - unget_char(ch1, tok); - return 1; - } + void unget_char(int, struct tok_state *), + int set_readline(struct tok_state *, const char *), + struct tok_state *tok) +{ + int ch1, ch2, ch3; + ch1 = get_char(tok); + tok->decoding_state = STATE_RAW; + if (ch1 == EOF) { + return 1; + } else if (ch1 == 0xEF) { + ch2 = get_char(tok); + if (ch2 != 0xBB) { + unget_char(ch2, tok); + unget_char(ch1, tok); + return 1; + } + ch3 = get_char(tok); + if (ch3 != 0xBF) { + unget_char(ch3, tok); + unget_char(ch2, tok); + unget_char(ch1, tok); + return 1; + } #if 0 - /* Disable support for UTF-16 BOMs until a decision - is made whether this needs to be supported. */ - } else if (ch1 == 0xFE) { - ch2 = get_char(tok); - if (ch2 != 0xFF) { - unget_char(ch2, tok); - unget_char(ch1, tok); - return 1; - } - if (!set_readline(tok, "utf-16-be")) - return 0; - tok->decoding_state = STATE_NORMAL; - } else if (ch1 == 0xFF) { - ch2 = get_char(tok); - if (ch2 != 0xFE) { - unget_char(ch2, tok); - unget_char(ch1, tok); - return 1; - } - if (!set_readline(tok, "utf-16-le")) - return 0; - tok->decoding_state = STATE_NORMAL; + /* Disable support for UTF-16 BOMs until a decision + is made whether this needs to be supported. */ + } else if (ch1 == 0xFE) { + ch2 = get_char(tok); + if (ch2 != 0xFF) { + unget_char(ch2, tok); + unget_char(ch1, tok); + return 1; + } + if (!set_readline(tok, "utf-16-be")) + return 0; + tok->decoding_state = STATE_NORMAL; + } else if (ch1 == 0xFF) { + ch2 = get_char(tok); + if (ch2 != 0xFE) { + unget_char(ch2, tok); + unget_char(ch1, tok); + return 1; + } + if (!set_readline(tok, "utf-16-le")) + return 0; + tok->decoding_state = STATE_NORMAL; #endif - } else { - unget_char(ch1, tok); - return 1; - } - if (tok->encoding != NULL) - PyMem_FREE(tok->encoding); - tok->encoding = new_string("utf-8", 5); /* resulting is in utf-8 */ - /* No need to set_readline: input is already utf-8 */ - return 1; + } else { + unget_char(ch1, tok); + return 1; + } + if (tok->encoding != NULL) + PyMem_FREE(tok->encoding); + tok->encoding = new_string("utf-8", 5); /* resulting is in utf-8 */ + /* No need to set_readline: input is already utf-8 */ + return 1; } /* Read a line of text from TOK into S, using the stream in TOK. @@ -378,74 +378,74 @@ On entry, tok->decoding_buffer will be one of: 1) NULL: need to call tok->decoding_readline to get a new line 2) PyUnicodeObject *: decoding_feof has called tok->decoding_readline and - stored the result in tok->decoding_buffer + stored the result in tok->decoding_buffer 3) PyByteArrayObject *: previous call to fp_readl did not have enough room - (in the s buffer) to copy entire contents of the line read - by tok->decoding_readline. tok->decoding_buffer has the overflow. - In this case, fp_readl is called in a loop (with an expanded buffer) - until the buffer ends with a '\n' (or until the end of the file is - reached): see tok_nextc and its calls to decoding_fgets. + (in the s buffer) to copy entire contents of the line read + by tok->decoding_readline. tok->decoding_buffer has the overflow. + In this case, fp_readl is called in a loop (with an expanded buffer) + until the buffer ends with a '\n' (or until the end of the file is + reached): see tok_nextc and its calls to decoding_fgets. */ static char * fp_readl(char *s, int size, struct tok_state *tok) { - PyObject* bufobj; - const char *buf; - Py_ssize_t buflen; - - /* Ask for one less byte so we can terminate it */ - assert(size > 0); - size--; - - if (tok->decoding_buffer) { - bufobj = tok->decoding_buffer; - Py_INCREF(bufobj); - } - else - { - bufobj = PyObject_CallObject(tok->decoding_readline, NULL); - if (bufobj == NULL) - goto error; - } - if (PyUnicode_CheckExact(bufobj)) - { - buf = _PyUnicode_AsStringAndSize(bufobj, &buflen); - if (buf == NULL) { - goto error; - } - } - else - { - buf = PyByteArray_AsString(bufobj); - if (buf == NULL) { - goto error; - } - buflen = PyByteArray_GET_SIZE(bufobj); - } - - Py_XDECREF(tok->decoding_buffer); - if (buflen > size) { - /* Too many chars, the rest goes into tok->decoding_buffer */ - tok->decoding_buffer = PyByteArray_FromStringAndSize(buf+size, - buflen-size); - if (tok->decoding_buffer == NULL) - goto error; - buflen = size; - } - else - tok->decoding_buffer = NULL; - - memcpy(s, buf, buflen); - s[buflen] = '\0'; - if (buflen == 0) /* EOF */ - s = NULL; - Py_DECREF(bufobj); - return s; + PyObject* bufobj; + const char *buf; + Py_ssize_t buflen; + + /* Ask for one less byte so we can terminate it */ + assert(size > 0); + size--; + + if (tok->decoding_buffer) { + bufobj = tok->decoding_buffer; + Py_INCREF(bufobj); + } + else + { + bufobj = PyObject_CallObject(tok->decoding_readline, NULL); + if (bufobj == NULL) + goto error; + } + if (PyUnicode_CheckExact(bufobj)) + { + buf = _PyUnicode_AsStringAndSize(bufobj, &buflen); + if (buf == NULL) { + goto error; + } + } + else + { + buf = PyByteArray_AsString(bufobj); + if (buf == NULL) { + goto error; + } + buflen = PyByteArray_GET_SIZE(bufobj); + } + + Py_XDECREF(tok->decoding_buffer); + if (buflen > size) { + /* Too many chars, the rest goes into tok->decoding_buffer */ + tok->decoding_buffer = PyByteArray_FromStringAndSize(buf+size, + buflen-size); + if (tok->decoding_buffer == NULL) + goto error; + buflen = size; + } + else + tok->decoding_buffer = NULL; + + memcpy(s, buf, buflen); + s[buflen] = '\0'; + if (buflen == 0) /* EOF */ + s = NULL; + Py_DECREF(bufobj); + return s; error: - Py_XDECREF(bufobj); - return error_ret(tok); + Py_XDECREF(bufobj); + return error_ret(tok); } /* Set the readline function for TOK to a StreamReader's @@ -461,49 +461,49 @@ static int fp_setreadl(struct tok_state *tok, const char* enc) { - PyObject *readline = NULL, *stream = NULL, *io = NULL; + PyObject *readline = NULL, *stream = NULL, *io = NULL; - io = PyImport_ImportModuleNoBlock("io"); - if (io == NULL) - goto cleanup; - - if (tok->filename) - stream = PyObject_CallMethod(io, "open", "ssis", - tok->filename, "r", -1, enc); - else - stream = PyObject_CallMethod(io, "open", "isisOOO", - fileno(tok->fp), "r", -1, enc, Py_None, Py_None, Py_False); - if (stream == NULL) - goto cleanup; - - Py_XDECREF(tok->decoding_readline); - readline = PyObject_GetAttrString(stream, "readline"); - tok->decoding_readline = readline; - - /* The file has been reopened; parsing will restart from - * the beginning of the file, we have to reset the line number. - * But this function has been called from inside tok_nextc() which - * will increment lineno before it returns. So we set it -1 so that - * the next call to tok_nextc() will start with tok->lineno == 0. - */ - tok->lineno = -1; + io = PyImport_ImportModuleNoBlock("io"); + if (io == NULL) + goto cleanup; + + if (tok->filename) + stream = PyObject_CallMethod(io, "open", "ssis", + tok->filename, "r", -1, enc); + else + stream = PyObject_CallMethod(io, "open", "isisOOO", + fileno(tok->fp), "r", -1, enc, Py_None, Py_None, Py_False); + if (stream == NULL) + goto cleanup; + + Py_XDECREF(tok->decoding_readline); + readline = PyObject_GetAttrString(stream, "readline"); + tok->decoding_readline = readline; + + /* The file has been reopened; parsing will restart from + * the beginning of the file, we have to reset the line number. + * But this function has been called from inside tok_nextc() which + * will increment lineno before it returns. So we set it -1 so that + * the next call to tok_nextc() will start with tok->lineno == 0. + */ + tok->lineno = -1; cleanup: - Py_XDECREF(stream); - Py_XDECREF(io); - return readline != NULL; + Py_XDECREF(stream); + Py_XDECREF(io); + return readline != NULL; } /* Fetch the next byte from TOK. */ static int fp_getc(struct tok_state *tok) { - return getc(tok->fp); + return getc(tok->fp); } /* Unfetch the last byte back into TOK. */ static void fp_ungetc(int c, struct tok_state *tok) { - ungetc(c, tok->fp); + ungetc(c, tok->fp); } /* Check whether the characters at s start a valid @@ -511,27 +511,27 @@ the sequence if yes, 0 if not. */ static int valid_utf8(const unsigned char* s) { - int expected = 0; - int length; - if (*s < 0x80) - /* single-byte code */ - return 1; - if (*s < 0xc0) - /* following byte */ - return 0; - if (*s < 0xE0) - expected = 1; - else if (*s < 0xF0) - expected = 2; - else if (*s < 0xF8) - expected = 3; - else - return 0; - length = expected + 1; - for (; expected; expected--) - if (s[expected] < 0x80 || s[expected] >= 0xC0) - return 0; - return length; + int expected = 0; + int length; + if (*s < 0x80) + /* single-byte code */ + return 1; + if (*s < 0xc0) + /* following byte */ + return 0; + if (*s < 0xE0) + expected = 1; + else if (*s < 0xF0) + expected = 2; + else if (*s < 0xF8) + expected = 3; + else + return 0; + length = expected + 1; + for (; expected; expected--) + if (s[expected] < 0x80 || s[expected] >= 0xC0) + return 0; + return length; } /* Read a line of input from TOK. Determine encoding @@ -540,93 +540,93 @@ static char * decoding_fgets(char *s, int size, struct tok_state *tok) { - char *line = NULL; - int badchar = 0; - for (;;) { - if (tok->decoding_state == STATE_NORMAL) { - /* We already have a codec associated with - this input. */ - line = fp_readl(s, size, tok); - break; - } else if (tok->decoding_state == STATE_RAW) { - /* We want a 'raw' read. */ - line = Py_UniversalNewlineFgets(s, size, - tok->fp, NULL); - break; - } else { - /* We have not yet determined the encoding. - If an encoding is found, use the file-pointer - reader functions from now on. */ - if (!check_bom(fp_getc, fp_ungetc, fp_setreadl, tok)) - return error_ret(tok); - assert(tok->decoding_state != STATE_INIT); - } - } - if (line != NULL && tok->lineno < 2 && !tok->read_coding_spec) { - if (!check_coding_spec(line, strlen(line), tok, fp_setreadl)) { - return error_ret(tok); - } - } + char *line = NULL; + int badchar = 0; + for (;;) { + if (tok->decoding_state == STATE_NORMAL) { + /* We already have a codec associated with + this input. */ + line = fp_readl(s, size, tok); + break; + } else if (tok->decoding_state == STATE_RAW) { + /* We want a 'raw' read. */ + line = Py_UniversalNewlineFgets(s, size, + tok->fp, NULL); + break; + } else { + /* We have not yet determined the encoding. + If an encoding is found, use the file-pointer + reader functions from now on. */ + if (!check_bom(fp_getc, fp_ungetc, fp_setreadl, tok)) + return error_ret(tok); + assert(tok->decoding_state != STATE_INIT); + } + } + if (line != NULL && tok->lineno < 2 && !tok->read_coding_spec) { + if (!check_coding_spec(line, strlen(line), tok, fp_setreadl)) { + return error_ret(tok); + } + } #ifndef PGEN - /* The default encoding is UTF-8, so make sure we don't have any - non-UTF-8 sequences in it. */ - if (line && !tok->encoding) { - unsigned char *c; - int length; - for (c = (unsigned char *)line; *c; c += length) - if (!(length = valid_utf8(c))) { - badchar = *c; - break; - } - } - if (badchar) { - /* Need to add 1 to the line number, since this line - has not been counted, yet. */ - PyErr_Format(PyExc_SyntaxError, - "Non-UTF-8 code starting with '\\x%.2x' " - "in file %.200s on line %i, " - "but no encoding declared; " - "see http://python.org/dev/peps/pep-0263/ for details", - badchar, tok->filename, tok->lineno + 1); - return error_ret(tok); - } + /* The default encoding is UTF-8, so make sure we don't have any + non-UTF-8 sequences in it. */ + if (line && !tok->encoding) { + unsigned char *c; + int length; + for (c = (unsigned char *)line; *c; c += length) + if (!(length = valid_utf8(c))) { + badchar = *c; + break; + } + } + if (badchar) { + /* Need to add 1 to the line number, since this line + has not been counted, yet. */ + PyErr_Format(PyExc_SyntaxError, + "Non-UTF-8 code starting with '\\x%.2x' " + "in file %.200s on line %i, " + "but no encoding declared; " + "see http://python.org/dev/peps/pep-0263/ for details", + badchar, tok->filename, tok->lineno + 1); + return error_ret(tok); + } #endif - return line; + return line; } static int decoding_feof(struct tok_state *tok) { - if (tok->decoding_state != STATE_NORMAL) { - return feof(tok->fp); - } else { - PyObject* buf = tok->decoding_buffer; - if (buf == NULL) { - buf = PyObject_CallObject(tok->decoding_readline, NULL); - if (buf == NULL) { - error_ret(tok); - return 1; - } else { - tok->decoding_buffer = buf; - } - } - return PyObject_Length(buf) == 0; - } + if (tok->decoding_state != STATE_NORMAL) { + return feof(tok->fp); + } else { + PyObject* buf = tok->decoding_buffer; + if (buf == NULL) { + buf = PyObject_CallObject(tok->decoding_readline, NULL); + if (buf == NULL) { + error_ret(tok); + return 1; + } else { + tok->decoding_buffer = buf; + } + } + return PyObject_Length(buf) == 0; + } } /* Fetch a byte from TOK, using the string buffer. */ static int buf_getc(struct tok_state *tok) { - return Py_CHARMASK(*tok->str++); + return Py_CHARMASK(*tok->str++); } /* Unfetch a byte from TOK, using the string buffer. */ static void buf_ungetc(int c, struct tok_state *tok) { - tok->str--; - assert(Py_CHARMASK(*tok->str) == c); /* tok->cur may point to read-only segment */ + tok->str--; + assert(Py_CHARMASK(*tok->str) == c); /* tok->cur may point to read-only segment */ } /* Set the readline function for TOK to ENC. For the string-based @@ -634,8 +634,8 @@ static int buf_setreadl(struct tok_state *tok, const char* enc) { - tok->enc = enc; - return 1; + tok->enc = enc; + return 1; } /* Return a UTF-8 encoding Python string object from the @@ -643,54 +643,54 @@ static PyObject * translate_into_utf8(const char* str, const char* enc) { - PyObject *utf8; - PyObject* buf = PyUnicode_Decode(str, strlen(str), enc, NULL); - if (buf == NULL) - return NULL; - utf8 = PyUnicode_AsUTF8String(buf); - Py_DECREF(buf); - return utf8; + PyObject *utf8; + PyObject* buf = PyUnicode_Decode(str, strlen(str), enc, NULL); + if (buf == NULL) + return NULL; + utf8 = PyUnicode_AsUTF8String(buf); + Py_DECREF(buf); + return utf8; } static char * translate_newlines(const char *s, int exec_input, struct tok_state *tok) { - int skip_next_lf = 0, needed_length = strlen(s) + 2, final_length; - char *buf, *current; - char c = '\0'; - buf = PyMem_MALLOC(needed_length); - if (buf == NULL) { - tok->done = E_NOMEM; - return NULL; - } - for (current = buf; *s; s++, current++) { - c = *s; - if (skip_next_lf) { - skip_next_lf = 0; - if (c == '\n') { - c = *++s; - if (!c) - break; - } - } - if (c == '\r') { - skip_next_lf = 1; - c = '\n'; - } - *current = c; - } - /* If this is exec input, add a newline to the end of the string if - there isn't one already. */ - if (exec_input && c != '\n') { - *current = '\n'; - current++; - } - *current = '\0'; - final_length = current - buf + 1; - if (final_length < needed_length && final_length) - /* should never fail */ - buf = PyMem_REALLOC(buf, final_length); - return buf; + int skip_next_lf = 0, needed_length = strlen(s) + 2, final_length; + char *buf, *current; + char c = '\0'; + buf = PyMem_MALLOC(needed_length); + if (buf == NULL) { + tok->done = E_NOMEM; + return NULL; + } + for (current = buf; *s; s++, current++) { + c = *s; + if (skip_next_lf) { + skip_next_lf = 0; + if (c == '\n') { + c = *++s; + if (!c) + break; + } + } + if (c == '\r') { + skip_next_lf = 1; + c = '\n'; + } + *current = c; + } + /* If this is exec input, add a newline to the end of the string if + there isn't one already. */ + if (exec_input && c != '\n') { + *current = '\n'; + current++; + } + *current = '\0'; + final_length = current - buf + 1; + if (final_length < needed_length && final_length) + /* should never fail */ + buf = PyMem_REALLOC(buf, final_length); + return buf; } /* Decode a byte string STR for use as the buffer of TOK. @@ -700,57 +700,57 @@ static const char * decode_str(const char *input, int single, struct tok_state *tok) { - PyObject* utf8 = NULL; - const char *str; - const char *s; - const char *newl[2] = {NULL, NULL}; - int lineno = 0; - tok->input = str = translate_newlines(input, single, tok); - if (str == NULL) - return NULL; - tok->enc = NULL; - tok->str = str; - if (!check_bom(buf_getc, buf_ungetc, buf_setreadl, tok)) - return error_ret(tok); - str = tok->str; /* string after BOM if any */ - assert(str); - if (tok->enc != NULL) { - utf8 = translate_into_utf8(str, tok->enc); - if (utf8 == NULL) - return error_ret(tok); - str = PyBytes_AsString(utf8); - } - for (s = str;; s++) { - if (*s == '\0') break; - else if (*s == '\n') { - assert(lineno < 2); - newl[lineno] = s; - lineno++; - if (lineno == 2) break; - } - } - tok->enc = NULL; - /* need to check line 1 and 2 separately since check_coding_spec - assumes a single line as input */ - if (newl[0]) { - if (!check_coding_spec(str, newl[0] - str, tok, buf_setreadl)) - return error_ret(tok); - if (tok->enc == NULL && newl[1]) { - if (!check_coding_spec(newl[0]+1, newl[1] - newl[0], - tok, buf_setreadl)) - return error_ret(tok); - } - } - if (tok->enc != NULL) { - assert(utf8 == NULL); - utf8 = translate_into_utf8(str, tok->enc); - if (utf8 == NULL) - return error_ret(tok); - str = PyBytes_AS_STRING(utf8); - } - assert(tok->decoding_buffer == NULL); - tok->decoding_buffer = utf8; /* CAUTION */ - return str; + PyObject* utf8 = NULL; + const char *str; + const char *s; + const char *newl[2] = {NULL, NULL}; + int lineno = 0; + tok->input = str = translate_newlines(input, single, tok); + if (str == NULL) + return NULL; + tok->enc = NULL; + tok->str = str; + if (!check_bom(buf_getc, buf_ungetc, buf_setreadl, tok)) + return error_ret(tok); + str = tok->str; /* string after BOM if any */ + assert(str); + if (tok->enc != NULL) { + utf8 = translate_into_utf8(str, tok->enc); + if (utf8 == NULL) + return error_ret(tok); + str = PyBytes_AsString(utf8); + } + for (s = str;; s++) { + if (*s == '\0') break; + else if (*s == '\n') { + assert(lineno < 2); + newl[lineno] = s; + lineno++; + if (lineno == 2) break; + } + } + tok->enc = NULL; + /* need to check line 1 and 2 separately since check_coding_spec + assumes a single line as input */ + if (newl[0]) { + if (!check_coding_spec(str, newl[0] - str, tok, buf_setreadl)) + return error_ret(tok); + if (tok->enc == NULL && newl[1]) { + if (!check_coding_spec(newl[0]+1, newl[1] - newl[0], + tok, buf_setreadl)) + return error_ret(tok); + } + } + if (tok->enc != NULL) { + assert(utf8 == NULL); + utf8 = translate_into_utf8(str, tok->enc); + if (utf8 == NULL) + return error_ret(tok); + str = PyBytes_AS_STRING(utf8); + } + assert(tok->decoding_buffer == NULL); + tok->decoding_buffer = utf8; /* CAUTION */ + return str; } #endif /* PGEN */ @@ -760,47 +760,47 @@ struct tok_state * PyTokenizer_FromString(const char *str, int exec_input) { - struct tok_state *tok = tok_new(); - if (tok == NULL) - return NULL; - str = (char *)decode_str(str, exec_input, tok); - if (str == NULL) { - PyTokenizer_Free(tok); - return NULL; - } - - /* XXX: constify members. */ - tok->buf = tok->cur = tok->end = tok->inp = (char*)str; - return tok; + struct tok_state *tok = tok_new(); + if (tok == NULL) + return NULL; + str = (char *)decode_str(str, exec_input, tok); + if (str == NULL) { + PyTokenizer_Free(tok); + return NULL; + } + + /* XXX: constify members. */ + tok->buf = tok->cur = tok->end = tok->inp = (char*)str; + return tok; } struct tok_state * PyTokenizer_FromUTF8(const char *str, int exec_input) { - struct tok_state *tok = tok_new(); - if (tok == NULL) - return NULL; + struct tok_state *tok = tok_new(); + if (tok == NULL) + return NULL; #ifndef PGEN - tok->input = str = translate_newlines(str, exec_input, tok); + tok->input = str = translate_newlines(str, exec_input, tok); #endif - if (str == NULL) { - PyTokenizer_Free(tok); - return NULL; - } - tok->decoding_state = STATE_RAW; - tok->read_coding_spec = 1; - tok->enc = NULL; - tok->str = str; - tok->encoding = (char *)PyMem_MALLOC(6); - if (!tok->encoding) { - PyTokenizer_Free(tok); - return NULL; - } - strcpy(tok->encoding, "utf-8"); - - /* XXX: constify members. */ - tok->buf = tok->cur = tok->end = tok->inp = (char*)str; - return tok; + if (str == NULL) { + PyTokenizer_Free(tok); + return NULL; + } + tok->decoding_state = STATE_RAW; + tok->read_coding_spec = 1; + tok->enc = NULL; + tok->str = str; + tok->encoding = (char *)PyMem_MALLOC(6); + if (!tok->encoding) { + PyTokenizer_Free(tok); + return NULL; + } + strcpy(tok->encoding, "utf-8"); + + /* XXX: constify members. */ + tok->buf = tok->cur = tok->end = tok->inp = (char*)str; + return tok; } /* Set up tokenizer for file */ @@ -808,30 +808,30 @@ struct tok_state * PyTokenizer_FromFile(FILE *fp, char* enc, char *ps1, char *ps2) { - struct tok_state *tok = tok_new(); - if (tok == NULL) - return NULL; - if ((tok->buf = (char *)PyMem_MALLOC(BUFSIZ)) == NULL) { - PyTokenizer_Free(tok); - return NULL; - } - tok->cur = tok->inp = tok->buf; - tok->end = tok->buf + BUFSIZ; - tok->fp = fp; - tok->prompt = ps1; - tok->nextprompt = ps2; - if (enc != NULL) { - /* Must copy encoding declaration since it - gets copied into the parse tree. */ - tok->encoding = PyMem_MALLOC(strlen(enc)+1); - if (!tok->encoding) { - PyTokenizer_Free(tok); - return NULL; - } - strcpy(tok->encoding, enc); - tok->decoding_state = STATE_NORMAL; - } - return tok; + struct tok_state *tok = tok_new(); + if (tok == NULL) + return NULL; + if ((tok->buf = (char *)PyMem_MALLOC(BUFSIZ)) == NULL) { + PyTokenizer_Free(tok); + return NULL; + } + tok->cur = tok->inp = tok->buf; + tok->end = tok->buf + BUFSIZ; + tok->fp = fp; + tok->prompt = ps1; + tok->nextprompt = ps2; + if (enc != NULL) { + /* Must copy encoding declaration since it + gets copied into the parse tree. */ + tok->encoding = PyMem_MALLOC(strlen(enc)+1); + if (!tok->encoding) { + PyTokenizer_Free(tok); + return NULL; + } + strcpy(tok->encoding, enc); + tok->decoding_state = STATE_NORMAL; + } + return tok; } @@ -840,17 +840,17 @@ void PyTokenizer_Free(struct tok_state *tok) { - if (tok->encoding != NULL) - PyMem_FREE(tok->encoding); + if (tok->encoding != NULL) + PyMem_FREE(tok->encoding); #ifndef PGEN - Py_XDECREF(tok->decoding_readline); - Py_XDECREF(tok->decoding_buffer); + Py_XDECREF(tok->decoding_readline); + Py_XDECREF(tok->decoding_buffer); #endif - if (tok->fp != NULL && tok->buf != NULL) - PyMem_FREE(tok->buf); - if (tok->input) - PyMem_FREE((char *)tok->input); - PyMem_FREE(tok); + if (tok->fp != NULL && tok->buf != NULL) + PyMem_FREE(tok->buf); + if (tok->input) + PyMem_FREE((char *)tok->input); + PyMem_FREE(tok); } /* Get next char, updating state; error code goes into tok->done */ @@ -858,188 +858,188 @@ static int tok_nextc(register struct tok_state *tok) { - for (;;) { - if (tok->cur != tok->inp) { - return Py_CHARMASK(*tok->cur++); /* Fast path */ - } - if (tok->done != E_OK) - return EOF; - if (tok->fp == NULL) { - char *end = strchr(tok->inp, '\n'); - if (end != NULL) - end++; - else { - end = strchr(tok->inp, '\0'); - if (end == tok->inp) { - tok->done = E_EOF; - return EOF; - } - } - if (tok->start == NULL) - tok->buf = tok->cur; - tok->line_start = tok->cur; - tok->lineno++; - tok->inp = end; - return Py_CHARMASK(*tok->cur++); - } - if (tok->prompt != NULL) { - char *newtok = PyOS_Readline(stdin, stdout, tok->prompt); + for (;;) { + if (tok->cur != tok->inp) { + return Py_CHARMASK(*tok->cur++); /* Fast path */ + } + if (tok->done != E_OK) + return EOF; + if (tok->fp == NULL) { + char *end = strchr(tok->inp, '\n'); + if (end != NULL) + end++; + else { + end = strchr(tok->inp, '\0'); + if (end == tok->inp) { + tok->done = E_EOF; + return EOF; + } + } + if (tok->start == NULL) + tok->buf = tok->cur; + tok->line_start = tok->cur; + tok->lineno++; + tok->inp = end; + return Py_CHARMASK(*tok->cur++); + } + if (tok->prompt != NULL) { + char *newtok = PyOS_Readline(stdin, stdout, tok->prompt); #ifndef PGEN - if (tok->encoding && newtok && *newtok) { - /* Recode to UTF-8 */ - Py_ssize_t buflen; - const char* buf; - PyObject *u = translate_into_utf8(newtok, tok->encoding); - PyMem_FREE(newtok); - if (!u) { - tok->done = E_DECODE; - return EOF; - } - buflen = PyBytes_GET_SIZE(u); - buf = PyBytes_AS_STRING(u); - if (!buf) { - Py_DECREF(u); - tok->done = E_DECODE; - return EOF; - } - newtok = PyMem_MALLOC(buflen+1); - strcpy(newtok, buf); - Py_DECREF(u); - } + if (tok->encoding && newtok && *newtok) { + /* Recode to UTF-8 */ + Py_ssize_t buflen; + const char* buf; + PyObject *u = translate_into_utf8(newtok, tok->encoding); + PyMem_FREE(newtok); + if (!u) { + tok->done = E_DECODE; + return EOF; + } + buflen = PyBytes_GET_SIZE(u); + buf = PyBytes_AS_STRING(u); + if (!buf) { + Py_DECREF(u); + tok->done = E_DECODE; + return EOF; + } + newtok = PyMem_MALLOC(buflen+1); + strcpy(newtok, buf); + Py_DECREF(u); + } #endif - if (tok->nextprompt != NULL) - tok->prompt = tok->nextprompt; - if (newtok == NULL) - tok->done = E_INTR; - else if (*newtok == '\0') { - PyMem_FREE(newtok); - tok->done = E_EOF; - } - else if (tok->start != NULL) { - size_t start = tok->start - tok->buf; - size_t oldlen = tok->cur - tok->buf; - size_t newlen = oldlen + strlen(newtok); - char *buf = tok->buf; - buf = (char *)PyMem_REALLOC(buf, newlen+1); - tok->lineno++; - if (buf == NULL) { - PyMem_FREE(tok->buf); - tok->buf = NULL; - PyMem_FREE(newtok); - tok->done = E_NOMEM; - return EOF; - } - tok->buf = buf; - tok->cur = tok->buf + oldlen; - tok->line_start = tok->cur; - strcpy(tok->buf + oldlen, newtok); - PyMem_FREE(newtok); - tok->inp = tok->buf + newlen; - tok->end = tok->inp + 1; - tok->start = tok->buf + start; - } - else { - tok->lineno++; - if (tok->buf != NULL) - PyMem_FREE(tok->buf); - tok->buf = newtok; - tok->line_start = tok->buf; - tok->cur = tok->buf; - tok->line_start = tok->buf; - tok->inp = strchr(tok->buf, '\0'); - tok->end = tok->inp + 1; - } - } - else { - int done = 0; - Py_ssize_t cur = 0; - char *pt; - if (tok->start == NULL) { - if (tok->buf == NULL) { - tok->buf = (char *) - PyMem_MALLOC(BUFSIZ); - if (tok->buf == NULL) { - tok->done = E_NOMEM; - return EOF; - } - tok->end = tok->buf + BUFSIZ; - } - if (decoding_fgets(tok->buf, (int)(tok->end - tok->buf), - tok) == NULL) { - tok->done = E_EOF; - done = 1; - } - else { - tok->done = E_OK; - tok->inp = strchr(tok->buf, '\0'); - done = tok->inp[-1] == '\n'; - } - } - else { - cur = tok->cur - tok->buf; - if (decoding_feof(tok)) { - tok->done = E_EOF; - done = 1; - } - else - tok->done = E_OK; - } - tok->lineno++; - /* Read until '\n' or EOF */ - while (!done) { - Py_ssize_t curstart = tok->start == NULL ? -1 : - tok->start - tok->buf; - Py_ssize_t curvalid = tok->inp - tok->buf; - Py_ssize_t newsize = curvalid + BUFSIZ; - char *newbuf = tok->buf; - newbuf = (char *)PyMem_REALLOC(newbuf, - newsize); - if (newbuf == NULL) { - tok->done = E_NOMEM; - tok->cur = tok->inp; - return EOF; - } - tok->buf = newbuf; - tok->inp = tok->buf + curvalid; - tok->end = tok->buf + newsize; - tok->start = curstart < 0 ? NULL : - tok->buf + curstart; - if (decoding_fgets(tok->inp, - (int)(tok->end - tok->inp), - tok) == NULL) { - /* Break out early on decoding - errors, as tok->buf will be NULL - */ - if (tok->decoding_erred) - return EOF; - /* Last line does not end in \n, - fake one */ - strcpy(tok->inp, "\n"); - } - tok->inp = strchr(tok->inp, '\0'); - done = tok->inp[-1] == '\n'; - } - if (tok->buf != NULL) { - tok->cur = tok->buf + cur; - tok->line_start = tok->cur; - /* replace "\r\n" with "\n" */ - /* For Mac leave the \r, giving a syntax error */ - pt = tok->inp - 2; - if (pt >= tok->buf && *pt == '\r') { - *pt++ = '\n'; - *pt = '\0'; - tok->inp = pt; - } - } - } - if (tok->done != E_OK) { - if (tok->prompt != NULL) - PySys_WriteStderr("\n"); - tok->cur = tok->inp; - return EOF; - } - } - /*NOTREACHED*/ + if (tok->nextprompt != NULL) + tok->prompt = tok->nextprompt; + if (newtok == NULL) + tok->done = E_INTR; + else if (*newtok == '\0') { + PyMem_FREE(newtok); + tok->done = E_EOF; + } + else if (tok->start != NULL) { + size_t start = tok->start - tok->buf; + size_t oldlen = tok->cur - tok->buf; + size_t newlen = oldlen + strlen(newtok); + char *buf = tok->buf; + buf = (char *)PyMem_REALLOC(buf, newlen+1); + tok->lineno++; + if (buf == NULL) { + PyMem_FREE(tok->buf); + tok->buf = NULL; + PyMem_FREE(newtok); + tok->done = E_NOMEM; + return EOF; + } + tok->buf = buf; + tok->cur = tok->buf + oldlen; + tok->line_start = tok->cur; + strcpy(tok->buf + oldlen, newtok); + PyMem_FREE(newtok); + tok->inp = tok->buf + newlen; + tok->end = tok->inp + 1; + tok->start = tok->buf + start; + } + else { + tok->lineno++; + if (tok->buf != NULL) + PyMem_FREE(tok->buf); + tok->buf = newtok; + tok->line_start = tok->buf; + tok->cur = tok->buf; + tok->line_start = tok->buf; + tok->inp = strchr(tok->buf, '\0'); + tok->end = tok->inp + 1; + } + } + else { + int done = 0; + Py_ssize_t cur = 0; + char *pt; + if (tok->start == NULL) { + if (tok->buf == NULL) { + tok->buf = (char *) + PyMem_MALLOC(BUFSIZ); + if (tok->buf == NULL) { + tok->done = E_NOMEM; + return EOF; + } + tok->end = tok->buf + BUFSIZ; + } + if (decoding_fgets(tok->buf, (int)(tok->end - tok->buf), + tok) == NULL) { + tok->done = E_EOF; + done = 1; + } + else { + tok->done = E_OK; + tok->inp = strchr(tok->buf, '\0'); + done = tok->inp[-1] == '\n'; + } + } + else { + cur = tok->cur - tok->buf; + if (decoding_feof(tok)) { + tok->done = E_EOF; + done = 1; + } + else + tok->done = E_OK; + } + tok->lineno++; + /* Read until '\n' or EOF */ + while (!done) { + Py_ssize_t curstart = tok->start == NULL ? -1 : + tok->start - tok->buf; + Py_ssize_t curvalid = tok->inp - tok->buf; + Py_ssize_t newsize = curvalid + BUFSIZ; + char *newbuf = tok->buf; + newbuf = (char *)PyMem_REALLOC(newbuf, + newsize); + if (newbuf == NULL) { + tok->done = E_NOMEM; + tok->cur = tok->inp; + return EOF; + } + tok->buf = newbuf; + tok->inp = tok->buf + curvalid; + tok->end = tok->buf + newsize; + tok->start = curstart < 0 ? NULL : + tok->buf + curstart; + if (decoding_fgets(tok->inp, + (int)(tok->end - tok->inp), + tok) == NULL) { + /* Break out early on decoding + errors, as tok->buf will be NULL + */ + if (tok->decoding_erred) + return EOF; + /* Last line does not end in \n, + fake one */ + strcpy(tok->inp, "\n"); + } + tok->inp = strchr(tok->inp, '\0'); + done = tok->inp[-1] == '\n'; + } + if (tok->buf != NULL) { + tok->cur = tok->buf + cur; + tok->line_start = tok->cur; + /* replace "\r\n" with "\n" */ + /* For Mac leave the \r, giving a syntax error */ + pt = tok->inp - 2; + if (pt >= tok->buf && *pt == '\r') { + *pt++ = '\n'; + *pt = '\0'; + tok->inp = pt; + } + } + } + if (tok->done != E_OK) { + if (tok->prompt != NULL) + PySys_WriteStderr("\n"); + tok->cur = tok->inp; + return EOF; + } + } + /*NOTREACHED*/ } @@ -1048,12 +1048,12 @@ static void tok_backup(register struct tok_state *tok, register int c) { - if (c != EOF) { - if (--tok->cur < tok->buf) - Py_FatalError("tok_backup: beginning of buffer"); - if (*tok->cur != c) - *tok->cur = c; - } + if (c != EOF) { + if (--tok->cur < tok->buf) + Py_FatalError("tok_backup: beginning of buffer"); + if (*tok->cur != c) + *tok->cur = c; + } } @@ -1062,181 +1062,181 @@ int PyToken_OneChar(int c) { - switch (c) { - case '(': return LPAR; - case ')': return RPAR; - case '[': return LSQB; - case ']': return RSQB; - case ':': return COLON; - case ',': return COMMA; - case ';': return SEMI; - case '+': return PLUS; - case '-': return MINUS; - case '*': return STAR; - case '/': return SLASH; - case '|': return VBAR; - case '&': return AMPER; - case '<': return LESS; - case '>': return GREATER; - case '=': return EQUAL; - case '.': return DOT; - case '%': return PERCENT; - case '{': return LBRACE; - case '}': return RBRACE; - case '^': return CIRCUMFLEX; - case '~': return TILDE; - case '@': return AT; - default: return OP; - } + switch (c) { + case '(': return LPAR; + case ')': return RPAR; + case '[': return LSQB; + case ']': return RSQB; + case ':': return COLON; + case ',': return COMMA; + case ';': return SEMI; + case '+': return PLUS; + case '-': return MINUS; + case '*': return STAR; + case '/': return SLASH; + case '|': return VBAR; + case '&': return AMPER; + case '<': return LESS; + case '>': return GREATER; + case '=': return EQUAL; + case '.': return DOT; + case '%': return PERCENT; + case '{': return LBRACE; + case '}': return RBRACE; + case '^': return CIRCUMFLEX; + case '~': return TILDE; + case '@': return AT; + default: return OP; + } } int PyToken_TwoChars(int c1, int c2) { - switch (c1) { - case '=': - switch (c2) { - case '=': return EQEQUAL; - } - break; - case '!': - switch (c2) { - case '=': return NOTEQUAL; - } - break; - case '<': - switch (c2) { - case '>': return NOTEQUAL; - case '=': return LESSEQUAL; - case '<': return LEFTSHIFT; - } - break; - case '>': - switch (c2) { - case '=': return GREATEREQUAL; - case '>': return RIGHTSHIFT; - } - break; - case '+': - switch (c2) { - case '=': return PLUSEQUAL; - } - break; - case '-': - switch (c2) { - case '=': return MINEQUAL; - case '>': return RARROW; - } - break; - case '*': - switch (c2) { - case '*': return DOUBLESTAR; - case '=': return STAREQUAL; - } - break; - case '/': - switch (c2) { - case '/': return DOUBLESLASH; - case '=': return SLASHEQUAL; - } - break; - case '|': - switch (c2) { - case '=': return VBAREQUAL; - } - break; - case '%': - switch (c2) { - case '=': return PERCENTEQUAL; - } - break; - case '&': - switch (c2) { - case '=': return AMPEREQUAL; - } - break; - case '^': - switch (c2) { - case '=': return CIRCUMFLEXEQUAL; - } - break; - } - return OP; + switch (c1) { + case '=': + switch (c2) { + case '=': return EQEQUAL; + } + break; + case '!': + switch (c2) { + case '=': return NOTEQUAL; + } + break; + case '<': + switch (c2) { + case '>': return NOTEQUAL; + case '=': return LESSEQUAL; + case '<': return LEFTSHIFT; + } + break; + case '>': + switch (c2) { + case '=': return GREATEREQUAL; + case '>': return RIGHTSHIFT; + } + break; + case '+': + switch (c2) { + case '=': return PLUSEQUAL; + } + break; + case '-': + switch (c2) { + case '=': return MINEQUAL; + case '>': return RARROW; + } + break; + case '*': + switch (c2) { + case '*': return DOUBLESTAR; + case '=': return STAREQUAL; + } + break; + case '/': + switch (c2) { + case '/': return DOUBLESLASH; + case '=': return SLASHEQUAL; + } + break; + case '|': + switch (c2) { + case '=': return VBAREQUAL; + } + break; + case '%': + switch (c2) { + case '=': return PERCENTEQUAL; + } + break; + case '&': + switch (c2) { + case '=': return AMPEREQUAL; + } + break; + case '^': + switch (c2) { + case '=': return CIRCUMFLEXEQUAL; + } + break; + } + return OP; } int PyToken_ThreeChars(int c1, int c2, int c3) { - switch (c1) { - case '<': - switch (c2) { - case '<': - switch (c3) { - case '=': - return LEFTSHIFTEQUAL; - } - break; - } - break; - case '>': - switch (c2) { - case '>': - switch (c3) { - case '=': - return RIGHTSHIFTEQUAL; - } - break; - } - break; - case '*': - switch (c2) { - case '*': - switch (c3) { - case '=': - return DOUBLESTAREQUAL; - } - break; - } - break; - case '/': - switch (c2) { - case '/': - switch (c3) { - case '=': - return DOUBLESLASHEQUAL; - } - break; - } - break; + switch (c1) { + case '<': + switch (c2) { + case '<': + switch (c3) { + case '=': + return LEFTSHIFTEQUAL; + } + break; + } + break; + case '>': + switch (c2) { + case '>': + switch (c3) { + case '=': + return RIGHTSHIFTEQUAL; + } + break; + } + break; + case '*': + switch (c2) { + case '*': + switch (c3) { + case '=': + return DOUBLESTAREQUAL; + } + break; + } + break; + case '/': + switch (c2) { + case '/': + switch (c3) { + case '=': + return DOUBLESLASHEQUAL; + } + break; + } + break; + case '.': + switch (c2) { case '.': - switch (c2) { - case '.': - switch (c3) { - case '.': - return ELLIPSIS; - } - break; - } - break; - } - return OP; + switch (c3) { + case '.': + return ELLIPSIS; + } + break; + } + break; + } + return OP; } static int indenterror(struct tok_state *tok) { - if (tok->alterror) { - tok->done = E_TABSPACE; - tok->cur = tok->inp; - return 1; - } - if (tok->altwarning) { - PySys_WriteStderr("%s: inconsistent use of tabs and spaces " - "in indentation\n", tok->filename); - tok->altwarning = 0; - } - return 0; + if (tok->alterror) { + tok->done = E_TABSPACE; + tok->cur = tok->inp; + return 1; + } + if (tok->altwarning) { + PySys_WriteStderr("%s: inconsistent use of tabs and spaces " + "in indentation\n", tok->filename); + tok->altwarning = 0; + } + return 0; } #ifdef PGEN @@ -1246,23 +1246,23 @@ static int verify_identifier(struct tok_state *tok) { - PyObject *s; - int result; - s = PyUnicode_DecodeUTF8(tok->start, tok->cur - tok->start, NULL); - if (s == NULL) { - if (PyErr_ExceptionMatches(PyExc_UnicodeDecodeError)) { - PyErr_Clear(); - tok->done = E_IDENTIFIER; - } else { - tok->done = E_ERROR; - } - return 0; - } - result = PyUnicode_IsIdentifier(s); - Py_DECREF(s); - if (result == 0) - tok->done = E_IDENTIFIER; - return result; + PyObject *s; + int result; + s = PyUnicode_DecodeUTF8(tok->start, tok->cur - tok->start, NULL); + if (s == NULL) { + if (PyErr_ExceptionMatches(PyExc_UnicodeDecodeError)) { + PyErr_Clear(); + tok->done = E_IDENTIFIER; + } else { + tok->done = E_ERROR; + } + return 0; + } + result = PyUnicode_IsIdentifier(s); + Py_DECREF(s); + if (result == 0) + tok->done = E_IDENTIFIER; + return result; } #endif @@ -1271,407 +1271,407 @@ static int tok_get(register struct tok_state *tok, char **p_start, char **p_end) { - register int c; - int blankline, nonascii; + register int c; + int blankline, nonascii; - *p_start = *p_end = NULL; + *p_start = *p_end = NULL; nextline: - tok->start = NULL; - blankline = 0; + tok->start = NULL; + blankline = 0; - /* Get indentation level */ - if (tok->atbol) { - register int col = 0; - register int altcol = 0; - tok->atbol = 0; - for (;;) { - c = tok_nextc(tok); - if (c == ' ') - col++, altcol++; - else if (c == '\t') { - col = (col/tok->tabsize + 1) * tok->tabsize; - altcol = (altcol/tok->alttabsize + 1) - * tok->alttabsize; - } - else if (c == '\014') /* Control-L (formfeed) */ - col = altcol = 0; /* For Emacs users */ - else - break; - } - tok_backup(tok, c); - if (c == '#' || c == '\n') { - /* Lines with only whitespace and/or comments - shouldn't affect the indentation and are - not passed to the parser as NEWLINE tokens, - except *totally* empty lines in interactive - mode, which signal the end of a command group. */ - if (col == 0 && c == '\n' && tok->prompt != NULL) - blankline = 0; /* Let it through */ - else - blankline = 1; /* Ignore completely */ - /* We can't jump back right here since we still - may need to skip to the end of a comment */ - } - if (!blankline && tok->level == 0) { - if (col == tok->indstack[tok->indent]) { - /* No change */ - if (altcol != tok->altindstack[tok->indent]) { - if (indenterror(tok)) - return ERRORTOKEN; - } - } - else if (col > tok->indstack[tok->indent]) { - /* Indent -- always one */ - if (tok->indent+1 >= MAXINDENT) { - tok->done = E_TOODEEP; - tok->cur = tok->inp; - return ERRORTOKEN; - } - if (altcol <= tok->altindstack[tok->indent]) { - if (indenterror(tok)) - return ERRORTOKEN; - } - tok->pendin++; - tok->indstack[++tok->indent] = col; - tok->altindstack[tok->indent] = altcol; - } - else /* col < tok->indstack[tok->indent] */ { - /* Dedent -- any number, must be consistent */ - while (tok->indent > 0 && - col < tok->indstack[tok->indent]) { - tok->pendin--; - tok->indent--; - } - if (col != tok->indstack[tok->indent]) { - tok->done = E_DEDENT; - tok->cur = tok->inp; - return ERRORTOKEN; - } - if (altcol != tok->altindstack[tok->indent]) { - if (indenterror(tok)) - return ERRORTOKEN; - } - } - } - } - - tok->start = tok->cur; - - /* Return pending indents/dedents */ - if (tok->pendin != 0) { - if (tok->pendin < 0) { - tok->pendin++; - return DEDENT; - } - else { - tok->pendin--; - return INDENT; - } - } + /* Get indentation level */ + if (tok->atbol) { + register int col = 0; + register int altcol = 0; + tok->atbol = 0; + for (;;) { + c = tok_nextc(tok); + if (c == ' ') + col++, altcol++; + else if (c == '\t') { + col = (col/tok->tabsize + 1) * tok->tabsize; + altcol = (altcol/tok->alttabsize + 1) + * tok->alttabsize; + } + else if (c == '\014') /* Control-L (formfeed) */ + col = altcol = 0; /* For Emacs users */ + else + break; + } + tok_backup(tok, c); + if (c == '#' || c == '\n') { + /* Lines with only whitespace and/or comments + shouldn't affect the indentation and are + not passed to the parser as NEWLINE tokens, + except *totally* empty lines in interactive + mode, which signal the end of a command group. */ + if (col == 0 && c == '\n' && tok->prompt != NULL) + blankline = 0; /* Let it through */ + else + blankline = 1; /* Ignore completely */ + /* We can't jump back right here since we still + may need to skip to the end of a comment */ + } + if (!blankline && tok->level == 0) { + if (col == tok->indstack[tok->indent]) { + /* No change */ + if (altcol != tok->altindstack[tok->indent]) { + if (indenterror(tok)) + return ERRORTOKEN; + } + } + else if (col > tok->indstack[tok->indent]) { + /* Indent -- always one */ + if (tok->indent+1 >= MAXINDENT) { + tok->done = E_TOODEEP; + tok->cur = tok->inp; + return ERRORTOKEN; + } + if (altcol <= tok->altindstack[tok->indent]) { + if (indenterror(tok)) + return ERRORTOKEN; + } + tok->pendin++; + tok->indstack[++tok->indent] = col; + tok->altindstack[tok->indent] = altcol; + } + else /* col < tok->indstack[tok->indent] */ { + /* Dedent -- any number, must be consistent */ + while (tok->indent > 0 && + col < tok->indstack[tok->indent]) { + tok->pendin--; + tok->indent--; + } + if (col != tok->indstack[tok->indent]) { + tok->done = E_DEDENT; + tok->cur = tok->inp; + return ERRORTOKEN; + } + if (altcol != tok->altindstack[tok->indent]) { + if (indenterror(tok)) + return ERRORTOKEN; + } + } + } + } + + tok->start = tok->cur; + + /* Return pending indents/dedents */ + if (tok->pendin != 0) { + if (tok->pendin < 0) { + tok->pendin++; + return DEDENT; + } + else { + tok->pendin--; + return INDENT; + } + } again: - tok->start = NULL; - /* Skip spaces */ - do { - c = tok_nextc(tok); - } while (c == ' ' || c == '\t' || c == '\014'); - - /* Set start of current token */ - tok->start = tok->cur - 1; - - /* Skip comment */ - if (c == '#') - while (c != EOF && c != '\n') - c = tok_nextc(tok); - - /* Check for EOF and errors now */ - if (c == EOF) { - return tok->done == E_EOF ? ENDMARKER : ERRORTOKEN; - } - - /* Identifier (most frequent token!) */ - nonascii = 0; - if (is_potential_identifier_start(c)) { - /* Process b"", r"" and br"" */ - if (c == 'b' || c == 'B') { - c = tok_nextc(tok); - if (c == '"' || c == '\'') - goto letter_quote; - } - if (c == 'r' || c == 'R') { - c = tok_nextc(tok); - if (c == '"' || c == '\'') - goto letter_quote; - } - while (is_potential_identifier_char(c)) { - if (c >= 128) - nonascii = 1; - c = tok_nextc(tok); - } - tok_backup(tok, c); - if (nonascii && - !verify_identifier(tok)) { - tok->done = E_IDENTIFIER; - return ERRORTOKEN; - } - *p_start = tok->start; - *p_end = tok->cur; - return NAME; - } - - /* Newline */ - if (c == '\n') { - tok->atbol = 1; - if (blankline || tok->level > 0) - goto nextline; - *p_start = tok->start; - *p_end = tok->cur - 1; /* Leave '\n' out of the string */ - tok->cont_line = 0; - return NEWLINE; - } - - /* Period or number starting with period? */ - if (c == '.') { - c = tok_nextc(tok); - if (isdigit(c)) { - goto fraction; - } else if (c == '.') { - c = tok_nextc(tok); - if (c == '.') { - *p_start = tok->start; - *p_end = tok->cur; - return ELLIPSIS; - } else { - tok_backup(tok, c); - } - tok_backup(tok, '.'); - } else { - tok_backup(tok, c); - } - *p_start = tok->start; - *p_end = tok->cur; - return DOT; - } - - /* Number */ - if (isdigit(c)) { - if (c == '0') { - /* Hex, octal or binary -- maybe. */ - c = tok_nextc(tok); - if (c == '.') - goto fraction; - if (c == 'j' || c == 'J') - goto imaginary; - if (c == 'x' || c == 'X') { - - /* Hex */ - c = tok_nextc(tok); - if (!isxdigit(c)) { - tok->done = E_TOKEN; - tok_backup(tok, c); - return ERRORTOKEN; - } - do { - c = tok_nextc(tok); - } while (isxdigit(c)); - } - else if (c == 'o' || c == 'O') { - /* Octal */ - c = tok_nextc(tok); - if (c < '0' || c >= '8') { - tok->done = E_TOKEN; - tok_backup(tok, c); - return ERRORTOKEN; - } - do { - c = tok_nextc(tok); - } while ('0' <= c && c < '8'); - } - else if (c == 'b' || c == 'B') { - /* Binary */ - c = tok_nextc(tok); - if (c != '0' && c != '1') { - tok->done = E_TOKEN; - tok_backup(tok, c); - return ERRORTOKEN; - } - do { - c = tok_nextc(tok); - } while (c == '0' || c == '1'); - } - else { - int nonzero = 0; - /* maybe old-style octal; c is first char of it */ - /* in any case, allow '0' as a literal */ - while (c == '0') - c = tok_nextc(tok); - while (isdigit(c)) { - nonzero = 1; - c = tok_nextc(tok); - } - if (c == '.') - goto fraction; - else if (c == 'e' || c == 'E') - goto exponent; - else if (c == 'j' || c == 'J') - goto imaginary; - else if (nonzero) { - tok->done = E_TOKEN; - tok_backup(tok, c); - return ERRORTOKEN; - } - } - } - else { - /* Decimal */ - do { - c = tok_nextc(tok); - } while (isdigit(c)); - { - /* Accept floating point numbers. */ - if (c == '.') { - fraction: - /* Fraction */ - do { - c = tok_nextc(tok); - } while (isdigit(c)); - } - if (c == 'e' || c == 'E') { - exponent: - /* Exponent part */ - c = tok_nextc(tok); - if (c == '+' || c == '-') - c = tok_nextc(tok); - if (!isdigit(c)) { - tok->done = E_TOKEN; - tok_backup(tok, c); - return ERRORTOKEN; - } - do { - c = tok_nextc(tok); - } while (isdigit(c)); - } - if (c == 'j' || c == 'J') - /* Imaginary part */ - imaginary: - c = tok_nextc(tok); - } - } - tok_backup(tok, c); - *p_start = tok->start; - *p_end = tok->cur; - return NUMBER; - } + tok->start = NULL; + /* Skip spaces */ + do { + c = tok_nextc(tok); + } while (c == ' ' || c == '\t' || c == '\014'); + + /* Set start of current token */ + tok->start = tok->cur - 1; + + /* Skip comment */ + if (c == '#') + while (c != EOF && c != '\n') + c = tok_nextc(tok); + + /* Check for EOF and errors now */ + if (c == EOF) { + return tok->done == E_EOF ? ENDMARKER : ERRORTOKEN; + } + + /* Identifier (most frequent token!) */ + nonascii = 0; + if (is_potential_identifier_start(c)) { + /* Process b"", r"" and br"" */ + if (c == 'b' || c == 'B') { + c = tok_nextc(tok); + if (c == '"' || c == '\'') + goto letter_quote; + } + if (c == 'r' || c == 'R') { + c = tok_nextc(tok); + if (c == '"' || c == '\'') + goto letter_quote; + } + while (is_potential_identifier_char(c)) { + if (c >= 128) + nonascii = 1; + c = tok_nextc(tok); + } + tok_backup(tok, c); + if (nonascii && + !verify_identifier(tok)) { + tok->done = E_IDENTIFIER; + return ERRORTOKEN; + } + *p_start = tok->start; + *p_end = tok->cur; + return NAME; + } + + /* Newline */ + if (c == '\n') { + tok->atbol = 1; + if (blankline || tok->level > 0) + goto nextline; + *p_start = tok->start; + *p_end = tok->cur - 1; /* Leave '\n' out of the string */ + tok->cont_line = 0; + return NEWLINE; + } + + /* Period or number starting with period? */ + if (c == '.') { + c = tok_nextc(tok); + if (isdigit(c)) { + goto fraction; + } else if (c == '.') { + c = tok_nextc(tok); + if (c == '.') { + *p_start = tok->start; + *p_end = tok->cur; + return ELLIPSIS; + } else { + tok_backup(tok, c); + } + tok_backup(tok, '.'); + } else { + tok_backup(tok, c); + } + *p_start = tok->start; + *p_end = tok->cur; + return DOT; + } + + /* Number */ + if (isdigit(c)) { + if (c == '0') { + /* Hex, octal or binary -- maybe. */ + c = tok_nextc(tok); + if (c == '.') + goto fraction; + if (c == 'j' || c == 'J') + goto imaginary; + if (c == 'x' || c == 'X') { + + /* Hex */ + c = tok_nextc(tok); + if (!isxdigit(c)) { + tok->done = E_TOKEN; + tok_backup(tok, c); + return ERRORTOKEN; + } + do { + c = tok_nextc(tok); + } while (isxdigit(c)); + } + else if (c == 'o' || c == 'O') { + /* Octal */ + c = tok_nextc(tok); + if (c < '0' || c >= '8') { + tok->done = E_TOKEN; + tok_backup(tok, c); + return ERRORTOKEN; + } + do { + c = tok_nextc(tok); + } while ('0' <= c && c < '8'); + } + else if (c == 'b' || c == 'B') { + /* Binary */ + c = tok_nextc(tok); + if (c != '0' && c != '1') { + tok->done = E_TOKEN; + tok_backup(tok, c); + return ERRORTOKEN; + } + do { + c = tok_nextc(tok); + } while (c == '0' || c == '1'); + } + else { + int nonzero = 0; + /* maybe old-style octal; c is first char of it */ + /* in any case, allow '0' as a literal */ + while (c == '0') + c = tok_nextc(tok); + while (isdigit(c)) { + nonzero = 1; + c = tok_nextc(tok); + } + if (c == '.') + goto fraction; + else if (c == 'e' || c == 'E') + goto exponent; + else if (c == 'j' || c == 'J') + goto imaginary; + else if (nonzero) { + tok->done = E_TOKEN; + tok_backup(tok, c); + return ERRORTOKEN; + } + } + } + else { + /* Decimal */ + do { + c = tok_nextc(tok); + } while (isdigit(c)); + { + /* Accept floating point numbers. */ + if (c == '.') { + fraction: + /* Fraction */ + do { + c = tok_nextc(tok); + } while (isdigit(c)); + } + if (c == 'e' || c == 'E') { + exponent: + /* Exponent part */ + c = tok_nextc(tok); + if (c == '+' || c == '-') + c = tok_nextc(tok); + if (!isdigit(c)) { + tok->done = E_TOKEN; + tok_backup(tok, c); + return ERRORTOKEN; + } + do { + c = tok_nextc(tok); + } while (isdigit(c)); + } + if (c == 'j' || c == 'J') + /* Imaginary part */ + imaginary: + c = tok_nextc(tok); + } + } + tok_backup(tok, c); + *p_start = tok->start; + *p_end = tok->cur; + return NUMBER; + } letter_quote: - /* String */ - if (c == '\'' || c == '"') { - int quote = c; - int quote_size = 1; /* 1 or 3 */ - int end_quote_size = 0; - - /* Find the quote size and start of string */ - c = tok_nextc(tok); - if (c == quote) { - c = tok_nextc(tok); - if (c == quote) - quote_size = 3; - else - end_quote_size = 1; /* empty string found */ - } - if (c != quote) - tok_backup(tok, c); - - /* Get rest of string */ - while (end_quote_size != quote_size) { - c = tok_nextc(tok); - if (c == EOF) { - if (quote_size == 3) - tok->done = E_EOFS; - else - tok->done = E_EOLS; - tok->cur = tok->inp; - return ERRORTOKEN; - } - if (quote_size == 1 && c == '\n') { - tok->done = E_EOLS; - tok->cur = tok->inp; - return ERRORTOKEN; - } - if (c == quote) - end_quote_size += 1; - else { - end_quote_size = 0; - if (c == '\\') - c = tok_nextc(tok); /* skip escaped char */ - } - } - - *p_start = tok->start; - *p_end = tok->cur; - return STRING; - } - - /* Line continuation */ - if (c == '\\') { - c = tok_nextc(tok); - if (c != '\n') { - tok->done = E_LINECONT; - tok->cur = tok->inp; - return ERRORTOKEN; - } - tok->cont_line = 1; - goto again; /* Read next line */ - } - - /* Check for two-character token */ - { - int c2 = tok_nextc(tok); - int token = PyToken_TwoChars(c, c2); - if (token != OP) { - int c3 = tok_nextc(tok); - int token3 = PyToken_ThreeChars(c, c2, c3); - if (token3 != OP) { - token = token3; - } else { - tok_backup(tok, c3); - } - *p_start = tok->start; - *p_end = tok->cur; - return token; - } - tok_backup(tok, c2); - } - - /* Keep track of parentheses nesting level */ - switch (c) { - case '(': - case '[': - case '{': - tok->level++; - break; - case ')': - case ']': - case '}': - tok->level--; - break; - } - - /* Punctuation character */ - *p_start = tok->start; - *p_end = tok->cur; - return PyToken_OneChar(c); + /* String */ + if (c == '\'' || c == '"') { + int quote = c; + int quote_size = 1; /* 1 or 3 */ + int end_quote_size = 0; + + /* Find the quote size and start of string */ + c = tok_nextc(tok); + if (c == quote) { + c = tok_nextc(tok); + if (c == quote) + quote_size = 3; + else + end_quote_size = 1; /* empty string found */ + } + if (c != quote) + tok_backup(tok, c); + + /* Get rest of string */ + while (end_quote_size != quote_size) { + c = tok_nextc(tok); + if (c == EOF) { + if (quote_size == 3) + tok->done = E_EOFS; + else + tok->done = E_EOLS; + tok->cur = tok->inp; + return ERRORTOKEN; + } + if (quote_size == 1 && c == '\n') { + tok->done = E_EOLS; + tok->cur = tok->inp; + return ERRORTOKEN; + } + if (c == quote) + end_quote_size += 1; + else { + end_quote_size = 0; + if (c == '\\') + c = tok_nextc(tok); /* skip escaped char */ + } + } + + *p_start = tok->start; + *p_end = tok->cur; + return STRING; + } + + /* Line continuation */ + if (c == '\\') { + c = tok_nextc(tok); + if (c != '\n') { + tok->done = E_LINECONT; + tok->cur = tok->inp; + return ERRORTOKEN; + } + tok->cont_line = 1; + goto again; /* Read next line */ + } + + /* Check for two-character token */ + { + int c2 = tok_nextc(tok); + int token = PyToken_TwoChars(c, c2); + if (token != OP) { + int c3 = tok_nextc(tok); + int token3 = PyToken_ThreeChars(c, c2, c3); + if (token3 != OP) { + token = token3; + } else { + tok_backup(tok, c3); + } + *p_start = tok->start; + *p_end = tok->cur; + return token; + } + tok_backup(tok, c2); + } + + /* Keep track of parentheses nesting level */ + switch (c) { + case '(': + case '[': + case '{': + tok->level++; + break; + case ')': + case ']': + case '}': + tok->level--; + break; + } + + /* Punctuation character */ + *p_start = tok->start; + *p_end = tok->cur; + return PyToken_OneChar(c); } int PyTokenizer_Get(struct tok_state *tok, char **p_start, char **p_end) { - int result = tok_get(tok, p_start, p_end); - if (tok->decoding_erred) { - result = ERRORTOKEN; - tok->done = E_DECODE; - } - return result; + int result = tok_get(tok, p_start, p_end); + if (tok->decoding_erred) { + result = ERRORTOKEN; + tok->done = E_DECODE; + } + return result; } /* Get -*- encoding -*- from a Python file. @@ -1686,34 +1686,34 @@ char * PyTokenizer_FindEncoding(int fd) { - struct tok_state *tok; - FILE *fp; - char *p_start =NULL , *p_end =NULL , *encoding = NULL; - - fd = dup(fd); - if (fd < 0) { - return NULL; - } - fp = fdopen(fd, "r"); - if (fp == NULL) { - return NULL; - } - tok = PyTokenizer_FromFile(fp, NULL, NULL, NULL); - if (tok == NULL) { - fclose(fp); - return NULL; - } - while (tok->lineno < 2 && tok->done == E_OK) { - PyTokenizer_Get(tok, &p_start, &p_end); - } - fclose(fp); - if (tok->encoding) { - encoding = (char *)PyMem_MALLOC(strlen(tok->encoding) + 1); - if (encoding) - strcpy(encoding, tok->encoding); - } - PyTokenizer_Free(tok); - return encoding; + struct tok_state *tok; + FILE *fp; + char *p_start =NULL , *p_end =NULL , *encoding = NULL; + + fd = dup(fd); + if (fd < 0) { + return NULL; + } + fp = fdopen(fd, "r"); + if (fp == NULL) { + return NULL; + } + tok = PyTokenizer_FromFile(fp, NULL, NULL, NULL); + if (tok == NULL) { + fclose(fp); + return NULL; + } + while (tok->lineno < 2 && tok->done == E_OK) { + PyTokenizer_Get(tok, &p_start, &p_end); + } + fclose(fp); + if (tok->encoding) { + encoding = (char *)PyMem_MALLOC(strlen(tok->encoding) + 1); + if (encoding) + strcpy(encoding, tok->encoding); + } + PyTokenizer_Free(tok); + return encoding; } #ifdef Py_DEBUG @@ -1721,9 +1721,9 @@ void tok_dump(int type, char *start, char *end) { - printf("%s", _PyParser_TokenNames[type]); - if (type == NAME || type == NUMBER || type == STRING || type == OP) - printf("(%.*s)", (int)(end - start), start); + printf("%s", _PyParser_TokenNames[type]); + if (type == NAME || type == NUMBER || type == STRING || type == OP) + printf("(%.*s)", (int)(end - start), start); } #endif Modified: python/branches/py3k-jit/Parser/tokenizer.h ============================================================================== --- python/branches/py3k-jit/Parser/tokenizer.h (original) +++ python/branches/py3k-jit/Parser/tokenizer.h Mon May 10 23:55:43 2010 @@ -8,67 +8,67 @@ /* Tokenizer interface */ -#include "token.h" /* For token types */ +#include "token.h" /* For token types */ -#define MAXINDENT 100 /* Max indentation level */ +#define MAXINDENT 100 /* Max indentation level */ enum decoding_state { - STATE_INIT, - STATE_RAW, - STATE_NORMAL, /* have a codec associated with input */ + STATE_INIT, + STATE_RAW, + STATE_NORMAL, /* have a codec associated with input */ }; /* Tokenizer state */ struct tok_state { - /* Input state; buf <= cur <= inp <= end */ - /* NB an entire line is held in the buffer */ - char *buf; /* Input buffer, or NULL; malloc'ed if fp != NULL */ - char *cur; /* Next character in buffer */ - char *inp; /* End of data in buffer */ - char *end; /* End of input buffer if buf != NULL */ - char *start; /* Start of current token if not NULL */ - int done; /* E_OK normally, E_EOF at EOF, otherwise error code */ - /* NB If done != E_OK, cur must be == inp!!! */ - FILE *fp; /* Rest of input; NULL if tokenizing a string */ - int tabsize; /* Tab spacing */ - int indent; /* Current indentation index */ - int indstack[MAXINDENT]; /* Stack of indents */ - int atbol; /* Nonzero if at begin of new line */ - int pendin; /* Pending indents (if > 0) or dedents (if < 0) */ - char *prompt, *nextprompt; /* For interactive prompting */ - int lineno; /* Current line number */ - int level; /* () [] {} Parentheses nesting level */ - /* Used to allow free continuations inside them */ - /* Stuff for checking on different tab sizes */ - const char *filename; /* For error messages */ - int altwarning; /* Issue warning if alternate tabs don't match */ - int alterror; /* Issue error if alternate tabs don't match */ - int alttabsize; /* Alternate tab spacing */ - int altindstack[MAXINDENT]; /* Stack of alternate indents */ - /* Stuff for PEP 0263 */ - enum decoding_state decoding_state; - int decoding_erred; /* whether erred in decoding */ - int read_coding_spec; /* whether 'coding:...' has been read */ - char *encoding; /* Source encoding. */ - int cont_line; /* whether we are in a continuation line. */ - const char* line_start; /* pointer to start of current line */ + /* Input state; buf <= cur <= inp <= end */ + /* NB an entire line is held in the buffer */ + char *buf; /* Input buffer, or NULL; malloc'ed if fp != NULL */ + char *cur; /* Next character in buffer */ + char *inp; /* End of data in buffer */ + char *end; /* End of input buffer if buf != NULL */ + char *start; /* Start of current token if not NULL */ + int done; /* E_OK normally, E_EOF at EOF, otherwise error code */ + /* NB If done != E_OK, cur must be == inp!!! */ + FILE *fp; /* Rest of input; NULL if tokenizing a string */ + int tabsize; /* Tab spacing */ + int indent; /* Current indentation index */ + int indstack[MAXINDENT]; /* Stack of indents */ + int atbol; /* Nonzero if at begin of new line */ + int pendin; /* Pending indents (if > 0) or dedents (if < 0) */ + char *prompt, *nextprompt; /* For interactive prompting */ + int lineno; /* Current line number */ + int level; /* () [] {} Parentheses nesting level */ + /* Used to allow free continuations inside them */ + /* Stuff for checking on different tab sizes */ + const char *filename; /* For error messages */ + int altwarning; /* Issue warning if alternate tabs don't match */ + int alterror; /* Issue error if alternate tabs don't match */ + int alttabsize; /* Alternate tab spacing */ + int altindstack[MAXINDENT]; /* Stack of alternate indents */ + /* Stuff for PEP 0263 */ + enum decoding_state decoding_state; + int decoding_erred; /* whether erred in decoding */ + int read_coding_spec; /* whether 'coding:...' has been read */ + char *encoding; /* Source encoding. */ + int cont_line; /* whether we are in a continuation line. */ + const char* line_start; /* pointer to start of current line */ #ifndef PGEN - PyObject *decoding_readline; /* codecs.open(...).readline */ - PyObject *decoding_buffer; + PyObject *decoding_readline; /* codecs.open(...).readline */ + PyObject *decoding_buffer; #endif - const char* enc; /* Encoding for the current str. */ - const char* str; - const char* input; /* Tokenizer's newline translated copy of the string. */ + const char* enc; /* Encoding for the current str. */ + const char* str; + const char* input; /* Tokenizer's newline translated copy of the string. */ }; extern struct tok_state *PyTokenizer_FromString(const char *, int); extern struct tok_state *PyTokenizer_FromUTF8(const char *, int); extern struct tok_state *PyTokenizer_FromFile(FILE *, char*, - char *, char *); + char *, char *); extern void PyTokenizer_Free(struct tok_state *); extern int PyTokenizer_Get(struct tok_state *, char **, char **); -extern char * PyTokenizer_RestoreEncoding(struct tok_state* tok, - int len, int *offset); +extern char * PyTokenizer_RestoreEncoding(struct tok_state* tok, + int len, int *offset); extern char * PyTokenizer_FindEncoding(int); #ifdef __cplusplus Modified: python/branches/py3k-jit/Python/_warnings.c ============================================================================== --- python/branches/py3k-jit/Python/_warnings.c (original) +++ python/branches/py3k-jit/Python/_warnings.c Mon May 10 23:55:43 2010 @@ -85,10 +85,10 @@ default_action = get_warnings_attr("defaultaction"); if (default_action == NULL) { - if (PyErr_Occurred()) { - return NULL; - } - return _default_action; + if (PyErr_Occurred()) { + return NULL; + } + return _default_action; } Py_DECREF(_default_action); @@ -202,12 +202,12 @@ mod_str = _PyUnicode_AsString(filename); if (mod_str == NULL) - return NULL; + return NULL; len = PyUnicode_GetSize(filename); if (len < 0) return NULL; if (len >= 3 && - strncmp(mod_str + (len - 3), ".py", 3) == 0) { + strncmp(mod_str + (len - 3), ".py", 3) == 0) { module = PyUnicode_FromStringAndSize(mod_str, len-3); } else { @@ -243,15 +243,15 @@ show_warning(PyObject *filename, int lineno, PyObject *text, PyObject *category, PyObject *sourceline) { - PyObject *f_stderr; - PyObject *name; + PyObject *f_stderr; + PyObject *name; char lineno_str[128]; PyOS_snprintf(lineno_str, sizeof(lineno_str), ":%d: ", lineno); name = PyObject_GetAttrString(category, "__name__"); if (name == NULL) /* XXX Can an object lack a '__name__' attribute? */ - return; + return; f_stderr = PySys_GetObject("stderr"); if (f_stderr == NULL) { @@ -272,8 +272,8 @@ /* Print " source_line\n" */ if (sourceline) { char *source_line_str = _PyUnicode_AsString(sourceline); - if (source_line_str == NULL) - return; + if (source_line_str == NULL) + return; while (*source_line_str == ' ' || *source_line_str == '\t' || *source_line_str == '\014') source_line_str++; @@ -284,12 +284,12 @@ else if (_Py_DisplaySourceLine(f_stderr, _PyUnicode_AsString(filename), lineno, 2) < 0) - return; + return; PyErr_Clear(); } static PyObject * -warn_explicit(PyObject *category, PyObject *message, +warn_explicit(PyObject *category, PyObject *message, PyObject *filename, int lineno, PyObject *module, PyObject *registry, PyObject *sourceline) { @@ -297,7 +297,7 @@ PyObject *item = Py_None; const char *action; int rc; - + if (registry && !PyDict_Check(registry) && (registry != Py_None)) { PyErr_SetString(PyExc_TypeError, "'registry' must be a dict"); return NULL; @@ -344,7 +344,7 @@ rc = already_warned(registry, key, 0); if (rc == -1) goto cleanup; - else if (rc == 1) + else if (rc == 1) goto return_none; /* Else this warning hasn't been generated before. */ } @@ -374,12 +374,12 @@ goto cleanup; } /* _once_registry[(text, category)] = 1 */ - rc = update_registry(registry, text, category, 0); + rc = update_registry(registry, text, category, 0); } else if (strcmp(action, "module") == 0) { /* registry[(text, category, 0)] = 1 */ if (registry != NULL && registry != Py_None) - rc = update_registry(registry, text, category, 0); + rc = update_registry(registry, text, category, 0); } else if (strcmp(action, "default") != 0) { PyObject *to_str = PyObject_Str(item); @@ -387,9 +387,9 @@ if (to_str != NULL) { err_str = _PyUnicode_AsString(to_str); - if (err_str == NULL) - goto cleanup; - } + if (err_str == NULL) + goto cleanup; + } PyErr_Format(PyExc_RuntimeError, "Unrecognized action (%s) in warnings.filters:\n %s", action, err_str); @@ -500,7 +500,7 @@ if (*filename != NULL) { Py_ssize_t len = PyUnicode_GetSize(*filename); const char *file_str = _PyUnicode_AsString(*filename); - if (file_str == NULL || (len < 0 && PyErr_Occurred())) + if (file_str == NULL || (len < 0 && PyErr_Occurred())) goto handle_error; /* if filename.lower().endswith((".pyc", ".pyo")): */ @@ -512,16 +512,16 @@ tolower(file_str[len-1]) == 'o')) { *filename = PyUnicode_FromStringAndSize(file_str, len-1); - if (*filename == NULL) - goto handle_error; - } - else + if (*filename == NULL) + goto handle_error; + } + else Py_INCREF(*filename); } else { const char *module_str = _PyUnicode_AsString(*module); - if (module_str == NULL) - goto handle_error; + if (module_str == NULL) + goto handle_error; if (strcmp(module_str, "__main__") == 0) { PyObject *argv = PySys_GetObject("argv"); if (argv != NULL && PyList_Size(argv) > 0) { @@ -544,8 +544,8 @@ else { /* embedded interpreters don't have sys.argv, see bug #839151 */ *filename = PyUnicode_FromString("__main__"); - if (*filename == NULL) - goto handle_error; + if (*filename == NULL) + goto handle_error; } } if (*filename == NULL) { @@ -616,7 +616,7 @@ PyObject *message, *category = NULL; Py_ssize_t stack_level = 1; - if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|On:warn", kw_list, + if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|On:warn", kw_list, &message, &category, &stack_level)) return NULL; @@ -794,7 +794,7 @@ METH_VARARGS | METH_KEYWORDS, warn_explicit_doc}, /* XXX(brett.cannon): add showwarning? */ /* XXX(brett.cannon): Reasonable to add formatwarning? */ - {NULL, NULL} /* sentinel */ + {NULL, NULL} /* sentinel */ }; @@ -875,15 +875,15 @@ } static struct PyModuleDef warningsmodule = { - PyModuleDef_HEAD_INIT, - MODULE_NAME, - warnings__doc__, - 0, - warnings_functions, - NULL, - NULL, - NULL, - NULL + PyModuleDef_HEAD_INIT, + MODULE_NAME, + warnings__doc__, + 0, + warnings_functions, + NULL, + NULL, + NULL, + NULL }; Modified: python/branches/py3k-jit/Python/asdl.c ============================================================================== --- python/branches/py3k-jit/Python/asdl.c (original) +++ python/branches/py3k-jit/Python/asdl.c Mon May 10 23:55:43 2010 @@ -4,61 +4,61 @@ asdl_seq * asdl_seq_new(int size, PyArena *arena) { - asdl_seq *seq = NULL; - size_t n = (size ? (sizeof(void *) * (size - 1)) : 0); + asdl_seq *seq = NULL; + size_t n = (size ? (sizeof(void *) * (size - 1)) : 0); - /* check size is sane */ - if (size < 0 || size == INT_MIN || - (size && ((size - 1) > (PY_SIZE_MAX / sizeof(void *))))) { - PyErr_NoMemory(); - return NULL; - } - - /* check if size can be added safely */ - if (n > PY_SIZE_MAX - sizeof(asdl_seq)) { - PyErr_NoMemory(); - return NULL; - } - - n += sizeof(asdl_seq); - - seq = (asdl_seq *)PyArena_Malloc(arena, n); - if (!seq) { - PyErr_NoMemory(); - return NULL; - } - memset(seq, 0, n); - seq->size = size; - return seq; + /* check size is sane */ + if (size < 0 || size == INT_MIN || + (size && ((size - 1) > (PY_SIZE_MAX / sizeof(void *))))) { + PyErr_NoMemory(); + return NULL; + } + + /* check if size can be added safely */ + if (n > PY_SIZE_MAX - sizeof(asdl_seq)) { + PyErr_NoMemory(); + return NULL; + } + + n += sizeof(asdl_seq); + + seq = (asdl_seq *)PyArena_Malloc(arena, n); + if (!seq) { + PyErr_NoMemory(); + return NULL; + } + memset(seq, 0, n); + seq->size = size; + return seq; } asdl_int_seq * asdl_int_seq_new(int size, PyArena *arena) { - asdl_int_seq *seq = NULL; - size_t n = (size ? (sizeof(void *) * (size - 1)) : 0); + asdl_int_seq *seq = NULL; + size_t n = (size ? (sizeof(void *) * (size - 1)) : 0); - /* check size is sane */ - if (size < 0 || size == INT_MIN || - (size && ((size - 1) > (PY_SIZE_MAX / sizeof(void *))))) { - PyErr_NoMemory(); - return NULL; - } - - /* check if size can be added safely */ - if (n > PY_SIZE_MAX - sizeof(asdl_seq)) { - PyErr_NoMemory(); - return NULL; - } - - n += sizeof(asdl_seq); - - seq = (asdl_int_seq *)PyArena_Malloc(arena, n); - if (!seq) { - PyErr_NoMemory(); - return NULL; - } - memset(seq, 0, n); - seq->size = size; - return seq; + /* check size is sane */ + if (size < 0 || size == INT_MIN || + (size && ((size - 1) > (PY_SIZE_MAX / sizeof(void *))))) { + PyErr_NoMemory(); + return NULL; + } + + /* check if size can be added safely */ + if (n > PY_SIZE_MAX - sizeof(asdl_seq)) { + PyErr_NoMemory(); + return NULL; + } + + n += sizeof(asdl_seq); + + seq = (asdl_int_seq *)PyArena_Malloc(arena, n); + if (!seq) { + PyErr_NoMemory(); + return NULL; + } + memset(seq, 0, n); + seq->size = size; + return seq; } Modified: python/branches/py3k-jit/Python/ast.c ============================================================================== --- python/branches/py3k-jit/Python/ast.c (original) +++ python/branches/py3k-jit/Python/ast.c Mon May 10 23:55:43 2010 @@ -58,19 +58,19 @@ /* Check whether there are non-ASCII characters in the identifier; if so, normalize to NFKC. */ for (; *u; u++) { - if (*u >= 128) { - PyObject *m = PyImport_ImportModuleNoBlock("unicodedata"); - PyObject *id2; - if (!m) - return NULL; - id2 = PyObject_CallMethod(m, "normalize", "sO", "NFKC", id); - Py_DECREF(m); - if (!id2) - return NULL; - Py_DECREF(id); - id = id2; - break; - } + if (*u >= 128) { + PyObject *m = PyImport_ImportModuleNoBlock("unicodedata"); + PyObject *id2; + if (!m) + return NULL; + id2 = PyObject_CallMethod(m, "normalize", "sO", "NFKC", id); + Py_DECREF(m); + if (!id2) + return NULL; + Py_DECREF(id); + id = id2; + break; + } } PyUnicode_InternInPlace(&id); PyArena_AddPyObject(arena, id); @@ -226,7 +226,7 @@ c.c_encoding = STR(n); n = CHILD(n, 0); } else { - /* PEP 3120 */ + /* PEP 3120 */ c.c_encoding = "utf-8"; } c.c_arena = arena; @@ -481,8 +481,8 @@ expr_name = "conditional expression"; break; default: - PyErr_Format(PyExc_SystemError, - "unexpected expression in assignment %d (line %d)", + PyErr_Format(PyExc_SystemError, + "unexpected expression in assignment %d (line %d)", e->kind, e->lineno); return 0; } @@ -497,7 +497,7 @@ } /* If the LHS is a list or tuple, we need to set the assignment - context for all the contained elements. + context for all the contained elements. */ if (s) { int i; @@ -603,7 +603,7 @@ static asdl_seq * seq_for_testlist(struct compiling *c, const node *n) { - /* testlist: test (',' test)* [','] + /* testlist: test (',' test)* [','] testlist_star_expr: test|star_expr (',' test|star_expr)* [','] */ asdl_seq *seq; @@ -616,7 +616,7 @@ return NULL; for (i = 0; i < NCH(n); i += 2) { - const node *ch = CHILD(n, i); + const node *ch = CHILD(n, i); assert(TYPE(ch) == test || TYPE(ch) == test_nocond || TYPE(ch) == star_expr); expression = ast_for_expr(c, ch); @@ -726,7 +726,7 @@ } return i; error: - return -1; + return -1; } /* Create AST for argument list. */ @@ -739,12 +739,12 @@ parameters: '(' [typedargslist] ')' typedargslist: ((tfpdef ['=' test] ',')* - ('*' [tfpdef] (',' tfpdef ['=' test])* [',' '**' tfpdef] + ('*' [tfpdef] (',' tfpdef ['=' test])* [',' '**' tfpdef] | '**' tfpdef) | tfpdef ['=' test] (',' tfpdef ['=' test])* [',']) tfpdef: NAME [':' test] varargslist: ((vfpdef ['=' test] ',')* - ('*' [vfpdef] (',' vfpdef ['=' test])* [',' '**' vfpdef] + ('*' [vfpdef] (',' vfpdef ['=' test])* [',' '**' vfpdef] | '**' vfpdef) | vfpdef ['=' test] (',' vfpdef ['=' test])* [',']) vfpdef: NAME @@ -785,7 +785,7 @@ if (TYPE(ch) == vfpdef || TYPE(ch) == tfpdef) nposargs++; if (TYPE(ch) == EQUAL) nposdefaults++; } - /* count the number of keyword only args & + /* count the number of keyword only args & defaults for keyword only args */ for ( ; i < NCH(n); ++i) { ch = CHILD(n, i); @@ -799,11 +799,11 @@ asdl_seq_new(nkwonlyargs, c->c_arena) : NULL); if (!kwonlyargs && nkwonlyargs) goto error; - posdefaults = (nposdefaults ? + posdefaults = (nposdefaults ? asdl_seq_new(nposdefaults, c->c_arena) : NULL); if (!posdefaults && nposdefaults) goto error; - /* The length of kwonlyargs and kwdefaults are same + /* The length of kwonlyargs and kwdefaults are same since we set NULL as default for keyword only argument w/o default - we have sequence data structure, but no dictionary */ kwdefaults = (nkwonlyargs ? @@ -840,7 +840,7 @@ found_default = 1; } else if (found_default) { - ast_error(n, + ast_error(n, "non-default argument follows default argument"); goto error; } @@ -852,7 +852,7 @@ break; case STAR: if (i+1 >= NCH(n)) { - ast_error(CHILD(n, i), + ast_error(CHILD(n, i), "named arguments must follow bare *"); goto error; } @@ -953,15 +953,15 @@ /* decorator: '@' dotted_name [ '(' [arglist] ')' ] NEWLINE */ expr_ty d = NULL; expr_ty name_expr; - + REQ(n, decorator); REQ(CHILD(n, 0), AT); REQ(RCHILD(n, -1), NEWLINE); - + name_expr = ast_for_dotted_name(c, CHILD(n, 1)); if (!name_expr) return NULL; - + if (NCH(n) == 3) { /* No arguments */ d = name_expr; name_expr = NULL; @@ -989,12 +989,12 @@ asdl_seq* decorator_seq; expr_ty d; int i; - + REQ(n, decorators); decorator_seq = asdl_seq_new(NCH(n), c->c_arena); if (!decorator_seq) return NULL; - + for (i = 0; i < NCH(n); i++) { d = ast_for_decorator(c, CHILD(n, i)); if (!d) @@ -1052,7 +1052,7 @@ return NULL; assert(TYPE(CHILD(n, 1)) == funcdef || - TYPE(CHILD(n, 1)) == classdef); + TYPE(CHILD(n, 1)) == classdef); if (TYPE(CHILD(n, 1)) == funcdef) { thing = ast_for_funcdef(c, CHILD(n, 1), decorator_seq); @@ -1100,7 +1100,7 @@ static expr_ty ast_for_ifexpr(struct compiling *c, const node *n) { - /* test: or_test 'if' or_test 'else' test */ + /* test: or_test 'if' or_test 'else' test */ expr_ty expression, body, orelse; assert(NCH(n) == 5); @@ -1197,9 +1197,9 @@ asdl_seq *t; expr_ty expression, first; node *for_ch; - + REQ(n, comp_for); - + for_ch = CHILD(n, 1); t = ast_for_exprlist(c, for_ch, Store); if (!t) @@ -1223,7 +1223,7 @@ if (NCH(n) == 5) { int j, n_ifs; asdl_seq *ifs; - + n = CHILD(n, 4); n_ifs = count_comp_ifs(c, n); if (n_ifs == -1) @@ -1237,7 +1237,7 @@ REQ(n, comp_iter); n = CHILD(n, 0); REQ(n, comp_if); - + expression = ast_for_expr(c, CHILD(n, 1)); if (!expression) return NULL; @@ -1262,13 +1262,13 @@ argument: [test '='] test [comp_for] # Really [keyword '='] test */ expr_ty elt; asdl_seq *comps; - + assert(NCH(n) > 1); - + elt = ast_for_expr(c, CHILD(n, 0)); if (!elt) return NULL; - + comps = ast_for_comprehension(c, CHILD(n, 1)); if (!comps) return NULL; @@ -1289,21 +1289,21 @@ { expr_ty key, value; asdl_seq *comps; - + assert(NCH(n) > 3); REQ(CHILD(n, 1), COLON); - + key = ast_for_expr(c, CHILD(n, 0)); if (!key) return NULL; value = ast_for_expr(c, CHILD(n, 2)); if (!value) return NULL; - + comps = ast_for_comprehension(c, CHILD(n, 3)); if (!comps) return NULL; - + return DictComp(key, value, comps, LINENO(n), n->n_col_offset, c->c_arena); } @@ -1338,7 +1338,7 @@ */ node *ch = CHILD(n, 0); int bytesmode = 0; - + switch (TYPE(ch)) { case NAME: { /* All names start in Load context, but may later be @@ -1389,24 +1389,24 @@ return Ellipsis(LINENO(n), n->n_col_offset, c->c_arena); case LPAR: /* some parenthesized expressions */ ch = CHILD(n, 1); - + if (TYPE(ch) == RPAR) return Tuple(NULL, Load, LINENO(n), n->n_col_offset, c->c_arena); - + if (TYPE(ch) == yield_expr) return ast_for_expr(c, ch); - /* testlist_comp: test ( comp_for | (',' test)* [','] ) */ + /* testlist_comp: test ( comp_for | (',' test)* [','] ) */ if ((NCH(ch) > 1) && (TYPE(CHILD(ch, 1)) == comp_for)) return ast_for_genexp(c, ch); return ast_for_testlist(c, ch); case LSQB: /* list (or list comprehension) */ ch = CHILD(n, 1); - + if (TYPE(ch) == RSQB) return List(NULL, Load, LINENO(n), n->n_col_offset, c->c_arena); - + REQ(ch, testlist_comp); if (NCH(ch) == 1 || TYPE(CHILD(ch, 1)) == COMMA) { asdl_seq *elts = seq_for_testlist(c, ch); @@ -1453,14 +1453,14 @@ keys = asdl_seq_new(size, c->c_arena); if (!keys) return NULL; - + values = asdl_seq_new(size, c->c_arena); if (!values) return NULL; - + for (i = 0; i < NCH(ch); i += 4) { expr_ty expression; - + expression = ast_for_expr(c, CHILD(ch, i)); if (!expression) return NULL; @@ -1498,10 +1498,10 @@ if (NCH(n) == 1 && TYPE(ch) == test) { /* 'step' variable hold no significance in terms of being used over other vars */ - step = ast_for_expr(c, ch); + step = ast_for_expr(c, ch); if (!step) return NULL; - + return Index(step, c->c_arena); } @@ -1551,7 +1551,7 @@ ast_for_binop(struct compiling *c, const node *n) { /* Must account for a sequence of expressions. - How should A op B op C by represented? + How should A op B op C by represented? BinOp(BinOp(A, op, B), op, C). */ @@ -1589,10 +1589,10 @@ if (!tmp) return NULL; - tmp_result = BinOp(result, newoperator, tmp, + tmp_result = BinOp(result, newoperator, tmp, LINENO(next_oper), next_oper->n_col_offset, c->c_arena); - if (!tmp_result) + if (!tmp_result) return NULL; result = tmp_result; } @@ -1602,7 +1602,7 @@ static expr_ty ast_for_trailer(struct compiling *c, const node *n, expr_ty left_expr) { - /* trailer: '(' [arglist] ')' | '[' subscriptlist ']' | '.' NAME + /* trailer: '(' [arglist] ')' | '[' subscriptlist ']' | '.' NAME subscriptlist: subscript (',' subscript)* [','] subscript: '.' '.' '.' | test | [test] ':' [test] [sliceop] */ @@ -1633,7 +1633,7 @@ c->c_arena); } else { - /* The grammar is ambiguous here. The ambiguity is resolved + /* The grammar is ambiguous here. The ambiguity is resolved by treating the sequence as a tuple literal if there are no slice features. */ @@ -1786,7 +1786,7 @@ /* handle the full range of simple expressions test: or_test ['if' or_test 'else' test] | lambdef test_nocond: or_test | lambdef_nocond - or_test: and_test ('or' and_test)* + or_test: and_test ('or' and_test)* and_test: not_test ('and' not_test)* not_test: 'not' not_test | comparison comparison: expr (comp_op expr)* @@ -1874,7 +1874,7 @@ if (!expression) { return NULL; } - + asdl_seq_SET(ops, i / 2, newoperator); asdl_seq_SET(cmps, i / 2, expression); } @@ -1882,14 +1882,14 @@ if (!expression) { return NULL; } - + return Compare(expression, ops, cmps, LINENO(n), n->n_col_offset, c->c_arena); } break; case star_expr: - return ast_for_starred(c, n); + return ast_for_starred(c, n); /* The next five cases all handle BinOps. The main body of code is the same in each case, but the switch turned inside out to reuse the code for each type of operator. @@ -1998,7 +1998,7 @@ if (!e) return NULL; asdl_seq_SET(args, nargs++, e); - } + } else if (TYPE(CHILD(ch, 1)) == comp_for) { e = ast_for_genexp(c, ch); if (!e) @@ -2010,7 +2010,7 @@ identifier key, tmp; int k; - /* CHILD(ch, 0) is test, but must be an identifier? */ + /* CHILD(ch, 0) is test, but must be an identifier? */ e = ast_for_expr(c, CHILD(ch, 0)); if (!e) return NULL; @@ -2026,8 +2026,8 @@ ast_error(CHILD(ch, 0), "keyword can't be an expression"); return NULL; } else if (forbidden_name(e->v.Name.id, ch, 1)) { - return NULL; - } + return NULL; + } key = e->v.Name.id; for (k = 0; k < nkeywords; k++) { tmp = ((keyword_ty)asdl_seq_GET(keywords, k))->arg; @@ -2090,7 +2090,7 @@ ast_for_expr_stmt(struct compiling *c, const node *n) { REQ(n, expr_stmt); - /* expr_stmt: testlist_star_expr (augassign (yield_expr|testlist) + /* expr_stmt: testlist_star_expr (augassign (yield_expr|testlist) | ('=' (yield_expr|testlist))*) testlist_star_expr: (test|star_expr) (',' test|star_expr)* [','] augassign: '+=' | '-=' | '*=' | '/=' | '%=' | '&=' | '|=' | '^=' @@ -2164,7 +2164,7 @@ e = ast_for_testlist(c, ch); /* set context to assign */ - if (!e) + if (!e) return NULL; if (!set_context(c, e, Store, CHILD(n, i))) @@ -2211,7 +2211,7 @@ ast_for_del_stmt(struct compiling *c, const node *n) { asdl_seq *expr_list; - + /* del_stmt: 'del' exprlist */ REQ(n, del_stmt); @@ -2349,7 +2349,7 @@ int i; size_t len; char *s; - PyObject *uni; + PyObject *uni; len = 0; for (i = 0; i < NCH(n); i += 2) @@ -2370,13 +2370,13 @@ } --s; *s = '\0'; - uni = PyUnicode_DecodeUTF8(PyBytes_AS_STRING(str), - PyBytes_GET_SIZE(str), - NULL); - Py_DECREF(str); - if (!uni) - return NULL; - str = uni; + uni = PyUnicode_DecodeUTF8(PyBytes_AS_STRING(str), + PyBytes_GET_SIZE(str), + NULL); + Py_DECREF(str); + if (!uni) + return NULL; + str = uni; PyUnicode_InternInPlace(&str); PyArena_AddPyObject(c->c_arena, str); return alias(str, NULL, c->c_arena); @@ -2433,7 +2433,7 @@ int idx, ndots = 0; alias_ty mod = NULL; identifier modname = NULL; - + /* Count the number of dots (for relative imports) and check for the optional module name */ for (idx = 1; idx < NCH(n); idx++) { @@ -2444,7 +2444,7 @@ idx++; break; } else if (TYPE(CHILD(n, idx)) == ELLIPSIS) { - /* three consecutive dots are tokenized as one ELLIPSIS */ + /* three consecutive dots are tokenized as one ELLIPSIS */ ndots += 3; continue; } else if (TYPE(CHILD(n, idx)) != DOT) { @@ -2571,7 +2571,7 @@ expr2 = ast_for_expr(c, CHILD(n, 3)); if (!expr2) return NULL; - + return Assert(expr1, expr2, LINENO(n), n->n_col_offset, c->c_arena); } PyErr_Format(PyExc_SystemError, @@ -2598,7 +2598,7 @@ if (TYPE(CHILD(n, 0)) == simple_stmt) { n = CHILD(n, 0); /* simple_stmt always ends with a NEWLINE, - and may have a trailing SEMI + and may have a trailing SEMI */ end = NCH(n) - 1; if (TYPE(CHILD(n, end - 1)) == SEMI) @@ -2663,10 +2663,10 @@ expression = ast_for_expr(c, CHILD(n, 1)); if (!expression) return NULL; - suite_seq = ast_for_suite(c, CHILD(n, 3)); + suite_seq = ast_for_suite(c, CHILD(n, 3)); if (!suite_seq) return NULL; - + return If(expression, suite_seq, NULL, LINENO(n), n->n_col_offset, c->c_arena); } @@ -2724,8 +2724,8 @@ if (!suite_seq2) return NULL; - asdl_seq_SET(orelse, 0, - If(expression, suite_seq, suite_seq2, + asdl_seq_SET(orelse, 0, + If(expression, suite_seq, suite_seq2, LINENO(CHILD(n, NCH(n) - 6)), CHILD(n, NCH(n) - 6)->n_col_offset, c->c_arena)); @@ -2746,7 +2746,7 @@ return NULL; asdl_seq_SET(newobj, 0, - If(expression, suite_seq, orelse, + If(expression, suite_seq, orelse, LINENO(CHILD(n, off)), CHILD(n, off)->n_col_offset, c->c_arena)); orelse = newobj; @@ -2943,7 +2943,7 @@ ast_error(n, "malformed 'try' statement"); return NULL; } - + if (n_except > 0) { int i; stmt_ty except_st; @@ -3160,8 +3160,8 @@ return ast_for_funcdef(c, ch, NULL); case classdef: return ast_for_classdef(c, ch, NULL); - case decorated: - return ast_for_decorated(c, ch); + case decorated: + return ast_for_decorated(c, ch); default: PyErr_Format(PyExc_SystemError, "unhandled small_stmt: TYPE=%d NCH=%d\n", @@ -3317,7 +3317,7 @@ if (quote == 'b' || quote == 'B') { quote = *++s; *bytesmode = 1; - } + } if (quote == 'r' || quote == 'R') { quote = *++s; rawmode = 1; @@ -3330,7 +3330,7 @@ s++; len = strlen(s); if (len > INT_MAX) { - PyErr_SetString(PyExc_OverflowError, + PyErr_SetString(PyExc_OverflowError, "string to parse is too long"); return NULL; } @@ -3374,7 +3374,7 @@ return PyBytes_FromStringAndSize(s, len); } else if (strcmp(c->c_encoding, "utf-8") == 0) { return PyUnicode_FromStringAndSize(s, len); - } else { + } else { return PyUnicode_DecodeLatin1(s, len, NULL); } } Modified: python/branches/py3k-jit/Python/bltinmodule.c ============================================================================== --- python/branches/py3k-jit/Python/bltinmodule.c (original) +++ python/branches/py3k-jit/Python/bltinmodule.c Mon May 10 23:55:43 2010 @@ -29,138 +29,138 @@ int _Py_SetFileSystemEncoding(PyObject *s) { - PyObject *defenc, *codec; - if (!PyUnicode_Check(s)) { - PyErr_BadInternalCall(); - return -1; - } - defenc = _PyUnicode_AsDefaultEncodedString(s, NULL); - if (!defenc) - return -1; - codec = _PyCodec_Lookup(PyBytes_AsString(defenc)); - if (codec == NULL) - return -1; - Py_DECREF(codec); - if (!Py_HasFileSystemDefaultEncoding && Py_FileSystemDefaultEncoding) - /* A file system encoding was set at run-time */ - free((char*)Py_FileSystemDefaultEncoding); - Py_FileSystemDefaultEncoding = strdup(PyBytes_AsString(defenc)); - Py_HasFileSystemDefaultEncoding = 0; - return 0; + PyObject *defenc, *codec; + if (!PyUnicode_Check(s)) { + PyErr_BadInternalCall(); + return -1; + } + defenc = _PyUnicode_AsDefaultEncodedString(s, NULL); + if (!defenc) + return -1; + codec = _PyCodec_Lookup(PyBytes_AsString(defenc)); + if (codec == NULL) + return -1; + Py_DECREF(codec); + if (!Py_HasFileSystemDefaultEncoding && Py_FileSystemDefaultEncoding) + /* A file system encoding was set at run-time */ + free((char*)Py_FileSystemDefaultEncoding); + Py_FileSystemDefaultEncoding = strdup(PyBytes_AsString(defenc)); + Py_HasFileSystemDefaultEncoding = 0; + return 0; } static PyObject * builtin___build_class__(PyObject *self, PyObject *args, PyObject *kwds) { - PyObject *func, *name, *bases, *mkw, *meta, *prep, *ns, *cell; - PyObject *cls = NULL; - Py_ssize_t nargs, nbases; - - assert(args != NULL); - if (!PyTuple_Check(args)) { - PyErr_SetString(PyExc_TypeError, - "__build_class__: args is not a tuple"); - return NULL; - } - nargs = PyTuple_GET_SIZE(args); - if (nargs < 2) { - PyErr_SetString(PyExc_TypeError, - "__build_class__: not enough arguments"); - return NULL; - } - func = PyTuple_GET_ITEM(args, 0); /* Better be callable */ - name = PyTuple_GET_ITEM(args, 1); - if (!PyUnicode_Check(name)) { - PyErr_SetString(PyExc_TypeError, - "__build_class__: name is not a string"); - return NULL; - } - bases = PyTuple_GetSlice(args, 2, nargs); - if (bases == NULL) - return NULL; - nbases = nargs - 2; - - if (kwds == NULL) { - meta = NULL; - mkw = NULL; - } - else { - mkw = PyDict_Copy(kwds); /* Don't modify kwds passed in! */ - if (mkw == NULL) { - Py_DECREF(bases); - return NULL; - } - meta = PyDict_GetItemString(mkw, "metaclass"); - if (meta != NULL) { - Py_INCREF(meta); - if (PyDict_DelItemString(mkw, "metaclass") < 0) { - Py_DECREF(meta); - Py_DECREF(mkw); - Py_DECREF(bases); - return NULL; - } - } - } - if (meta == NULL) { - if (PyTuple_GET_SIZE(bases) == 0) - meta = (PyObject *) (&PyType_Type); - else { - PyObject *base0 = PyTuple_GET_ITEM(bases, 0); - meta = (PyObject *) (base0->ob_type); - } - Py_INCREF(meta); - } - prep = PyObject_GetAttrString(meta, "__prepare__"); - if (prep == NULL) { - if (PyErr_ExceptionMatches(PyExc_AttributeError)) { - PyErr_Clear(); - ns = PyDict_New(); - } - else { - Py_DECREF(meta); - Py_XDECREF(mkw); - Py_DECREF(bases); - return NULL; - } - } - else { - PyObject *pargs = PyTuple_Pack(2, name, bases); - if (pargs == NULL) { - Py_DECREF(prep); - Py_DECREF(meta); - Py_XDECREF(mkw); - Py_DECREF(bases); - return NULL; - } - ns = PyEval_CallObjectWithKeywords(prep, pargs, mkw); - Py_DECREF(pargs); - Py_DECREF(prep); - } - if (ns == NULL) { - Py_DECREF(meta); - Py_XDECREF(mkw); - Py_DECREF(bases); - return NULL; - } - cell = PyObject_CallFunctionObjArgs(func, ns, NULL); - if (cell != NULL) { - PyObject *margs; - margs = PyTuple_Pack(3, name, bases, ns); - if (margs != NULL) { - cls = PyEval_CallObjectWithKeywords(meta, margs, mkw); - Py_DECREF(margs); - } - if (cls != NULL && PyCell_Check(cell)) { - Py_INCREF(cls); - PyCell_SET(cell, cls); - } - Py_DECREF(cell); - } - Py_DECREF(ns); - Py_DECREF(meta); - Py_XDECREF(mkw); - Py_DECREF(bases); - return cls; + PyObject *func, *name, *bases, *mkw, *meta, *prep, *ns, *cell; + PyObject *cls = NULL; + Py_ssize_t nargs, nbases; + + assert(args != NULL); + if (!PyTuple_Check(args)) { + PyErr_SetString(PyExc_TypeError, + "__build_class__: args is not a tuple"); + return NULL; + } + nargs = PyTuple_GET_SIZE(args); + if (nargs < 2) { + PyErr_SetString(PyExc_TypeError, + "__build_class__: not enough arguments"); + return NULL; + } + func = PyTuple_GET_ITEM(args, 0); /* Better be callable */ + name = PyTuple_GET_ITEM(args, 1); + if (!PyUnicode_Check(name)) { + PyErr_SetString(PyExc_TypeError, + "__build_class__: name is not a string"); + return NULL; + } + bases = PyTuple_GetSlice(args, 2, nargs); + if (bases == NULL) + return NULL; + nbases = nargs - 2; + + if (kwds == NULL) { + meta = NULL; + mkw = NULL; + } + else { + mkw = PyDict_Copy(kwds); /* Don't modify kwds passed in! */ + if (mkw == NULL) { + Py_DECREF(bases); + return NULL; + } + meta = PyDict_GetItemString(mkw, "metaclass"); + if (meta != NULL) { + Py_INCREF(meta); + if (PyDict_DelItemString(mkw, "metaclass") < 0) { + Py_DECREF(meta); + Py_DECREF(mkw); + Py_DECREF(bases); + return NULL; + } + } + } + if (meta == NULL) { + if (PyTuple_GET_SIZE(bases) == 0) + meta = (PyObject *) (&PyType_Type); + else { + PyObject *base0 = PyTuple_GET_ITEM(bases, 0); + meta = (PyObject *) (base0->ob_type); + } + Py_INCREF(meta); + } + prep = PyObject_GetAttrString(meta, "__prepare__"); + if (prep == NULL) { + if (PyErr_ExceptionMatches(PyExc_AttributeError)) { + PyErr_Clear(); + ns = PyDict_New(); + } + else { + Py_DECREF(meta); + Py_XDECREF(mkw); + Py_DECREF(bases); + return NULL; + } + } + else { + PyObject *pargs = PyTuple_Pack(2, name, bases); + if (pargs == NULL) { + Py_DECREF(prep); + Py_DECREF(meta); + Py_XDECREF(mkw); + Py_DECREF(bases); + return NULL; + } + ns = PyEval_CallObjectWithKeywords(prep, pargs, mkw); + Py_DECREF(pargs); + Py_DECREF(prep); + } + if (ns == NULL) { + Py_DECREF(meta); + Py_XDECREF(mkw); + Py_DECREF(bases); + return NULL; + } + cell = PyObject_CallFunctionObjArgs(func, ns, NULL); + if (cell != NULL) { + PyObject *margs; + margs = PyTuple_Pack(3, name, bases, ns); + if (margs != NULL) { + cls = PyEval_CallObjectWithKeywords(meta, margs, mkw); + Py_DECREF(margs); + } + if (cls != NULL && PyCell_Check(cell)) { + Py_INCREF(cls); + PyCell_SET(cell, cls); + } + Py_DECREF(cell); + } + Py_DECREF(ns); + Py_DECREF(meta); + Py_XDECREF(mkw); + Py_DECREF(bases); + return cls; } PyDoc_STRVAR(build_class_doc, @@ -171,19 +171,19 @@ static PyObject * builtin___import__(PyObject *self, PyObject *args, PyObject *kwds) { - static char *kwlist[] = {"name", "globals", "locals", "fromlist", - "level", 0}; - char *name; - PyObject *globals = NULL; - PyObject *locals = NULL; - PyObject *fromlist = NULL; - int level = -1; - - if (!PyArg_ParseTupleAndKeywords(args, kwds, "s|OOOi:__import__", - kwlist, &name, &globals, &locals, &fromlist, &level)) - return NULL; - return PyImport_ImportModuleLevel(name, globals, locals, - fromlist, level); + static char *kwlist[] = {"name", "globals", "locals", "fromlist", + "level", 0}; + char *name; + PyObject *globals = NULL; + PyObject *locals = NULL; + PyObject *fromlist = NULL; + int level = -1; + + if (!PyArg_ParseTupleAndKeywords(args, kwds, "s|OOOi:__import__", + kwlist, &name, &globals, &locals, &fromlist, &level)) + return NULL; + return PyImport_ImportModuleLevel(name, globals, locals, + fromlist, level); } PyDoc_STRVAR(import_doc, @@ -204,7 +204,7 @@ static PyObject * builtin_abs(PyObject *self, PyObject *v) { - return PyNumber_Absolute(v); + return PyNumber_Absolute(v); } PyDoc_STRVAR(abs_doc, @@ -215,38 +215,38 @@ static PyObject * builtin_all(PyObject *self, PyObject *v) { - PyObject *it, *item; - PyObject *(*iternext)(PyObject *); - int cmp; - - it = PyObject_GetIter(v); - if (it == NULL) - return NULL; - iternext = *Py_TYPE(it)->tp_iternext; - - for (;;) { - item = iternext(it); - if (item == NULL) - break; - cmp = PyObject_IsTrue(item); - Py_DECREF(item); - if (cmp < 0) { - Py_DECREF(it); - return NULL; - } - if (cmp == 0) { - Py_DECREF(it); - Py_RETURN_FALSE; - } - } - Py_DECREF(it); - if (PyErr_Occurred()) { - if (PyErr_ExceptionMatches(PyExc_StopIteration)) - PyErr_Clear(); - else - return NULL; - } - Py_RETURN_TRUE; + PyObject *it, *item; + PyObject *(*iternext)(PyObject *); + int cmp; + + it = PyObject_GetIter(v); + if (it == NULL) + return NULL; + iternext = *Py_TYPE(it)->tp_iternext; + + for (;;) { + item = iternext(it); + if (item == NULL) + break; + cmp = PyObject_IsTrue(item); + Py_DECREF(item); + if (cmp < 0) { + Py_DECREF(it); + return NULL; + } + if (cmp == 0) { + Py_DECREF(it); + Py_RETURN_FALSE; + } + } + Py_DECREF(it); + if (PyErr_Occurred()) { + if (PyErr_ExceptionMatches(PyExc_StopIteration)) + PyErr_Clear(); + else + return NULL; + } + Py_RETURN_TRUE; } PyDoc_STRVAR(all_doc, @@ -257,38 +257,38 @@ static PyObject * builtin_any(PyObject *self, PyObject *v) { - PyObject *it, *item; - PyObject *(*iternext)(PyObject *); - int cmp; - - it = PyObject_GetIter(v); - if (it == NULL) - return NULL; - iternext = *Py_TYPE(it)->tp_iternext; - - for (;;) { - item = iternext(it); - if (item == NULL) - break; - cmp = PyObject_IsTrue(item); - Py_DECREF(item); - if (cmp < 0) { - Py_DECREF(it); - return NULL; - } - if (cmp == 1) { - Py_DECREF(it); - Py_RETURN_TRUE; - } - } - Py_DECREF(it); - if (PyErr_Occurred()) { - if (PyErr_ExceptionMatches(PyExc_StopIteration)) - PyErr_Clear(); - else - return NULL; - } - Py_RETURN_FALSE; + PyObject *it, *item; + PyObject *(*iternext)(PyObject *); + int cmp; + + it = PyObject_GetIter(v); + if (it == NULL) + return NULL; + iternext = *Py_TYPE(it)->tp_iternext; + + for (;;) { + item = iternext(it); + if (item == NULL) + break; + cmp = PyObject_IsTrue(item); + Py_DECREF(item); + if (cmp < 0) { + Py_DECREF(it); + return NULL; + } + if (cmp == 1) { + Py_DECREF(it); + Py_RETURN_TRUE; + } + } + Py_DECREF(it); + if (PyErr_Occurred()) { + if (PyErr_ExceptionMatches(PyExc_StopIteration)) + PyErr_Clear(); + else + return NULL; + } + Py_RETURN_FALSE; } PyDoc_STRVAR(any_doc, @@ -299,7 +299,7 @@ static PyObject * builtin_ascii(PyObject *self, PyObject *v) { - return PyObject_ASCII(v); + return PyObject_ASCII(v); } PyDoc_STRVAR(ascii_doc, @@ -314,7 +314,7 @@ static PyObject * builtin_bin(PyObject *self, PyObject *v) { - return PyNumber_ToBase(v, 2); + return PyNumber_ToBase(v, 2); } PyDoc_STRVAR(bin_doc, @@ -324,90 +324,90 @@ typedef struct { - PyObject_HEAD - PyObject *func; - PyObject *it; + PyObject_HEAD + PyObject *func; + PyObject *it; } filterobject; static PyObject * filter_new(PyTypeObject *type, PyObject *args, PyObject *kwds) { - PyObject *func, *seq; - PyObject *it; - filterobject *lz; - - if (type == &PyFilter_Type && !_PyArg_NoKeywords("filter()", kwds)) - return NULL; - - if (!PyArg_UnpackTuple(args, "filter", 2, 2, &func, &seq)) - return NULL; - - /* Get iterator. */ - it = PyObject_GetIter(seq); - if (it == NULL) - return NULL; - - /* create filterobject structure */ - lz = (filterobject *)type->tp_alloc(type, 0); - if (lz == NULL) { - Py_DECREF(it); - return NULL; - } - Py_INCREF(func); - lz->func = func; - lz->it = it; + PyObject *func, *seq; + PyObject *it; + filterobject *lz; + + if (type == &PyFilter_Type && !_PyArg_NoKeywords("filter()", kwds)) + return NULL; + + if (!PyArg_UnpackTuple(args, "filter", 2, 2, &func, &seq)) + return NULL; + + /* Get iterator. */ + it = PyObject_GetIter(seq); + if (it == NULL) + return NULL; - return (PyObject *)lz; + /* create filterobject structure */ + lz = (filterobject *)type->tp_alloc(type, 0); + if (lz == NULL) { + Py_DECREF(it); + return NULL; + } + Py_INCREF(func); + lz->func = func; + lz->it = it; + + return (PyObject *)lz; } static void filter_dealloc(filterobject *lz) { - PyObject_GC_UnTrack(lz); - Py_XDECREF(lz->func); - Py_XDECREF(lz->it); - Py_TYPE(lz)->tp_free(lz); + PyObject_GC_UnTrack(lz); + Py_XDECREF(lz->func); + Py_XDECREF(lz->it); + Py_TYPE(lz)->tp_free(lz); } static int filter_traverse(filterobject *lz, visitproc visit, void *arg) { - Py_VISIT(lz->it); - Py_VISIT(lz->func); - return 0; + Py_VISIT(lz->it); + Py_VISIT(lz->func); + return 0; } static PyObject * filter_next(filterobject *lz) { - PyObject *item; - PyObject *it = lz->it; - long ok; - PyObject *(*iternext)(PyObject *); - - iternext = *Py_TYPE(it)->tp_iternext; - for (;;) { - item = iternext(it); - if (item == NULL) - return NULL; - - if (lz->func == Py_None || lz->func == (PyObject *)&PyBool_Type) { - ok = PyObject_IsTrue(item); - } else { - PyObject *good; - good = PyObject_CallFunctionObjArgs(lz->func, - item, NULL); - if (good == NULL) { - Py_DECREF(item); - return NULL; - } - ok = PyObject_IsTrue(good); - Py_DECREF(good); - } - if (ok) - return item; - Py_DECREF(item); - } + PyObject *item; + PyObject *it = lz->it; + long ok; + PyObject *(*iternext)(PyObject *); + + iternext = *Py_TYPE(it)->tp_iternext; + for (;;) { + item = iternext(it); + if (item == NULL) + return NULL; + + if (lz->func == Py_None || lz->func == (PyObject *)&PyBool_Type) { + ok = PyObject_IsTrue(item); + } else { + PyObject *good; + good = PyObject_CallFunctionObjArgs(lz->func, + item, NULL); + if (good == NULL) { + Py_DECREF(item); + return NULL; + } + ok = PyObject_IsTrue(good); + Py_DECREF(good); + } + if (ok) + return item; + Py_DECREF(item); + } } PyDoc_STRVAR(filter_doc, @@ -417,47 +417,47 @@ is true. If function is None, return the items that are true."); PyTypeObject PyFilter_Type = { - PyVarObject_HEAD_INIT(&PyType_Type, 0) - "filter", /* tp_name */ - sizeof(filterobject), /* tp_basicsize */ - 0, /* tp_itemsize */ - /* methods */ - (destructor)filter_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 | - Py_TPFLAGS_BASETYPE, /* tp_flags */ - filter_doc, /* tp_doc */ - (traverseproc)filter_traverse, /* tp_traverse */ - 0, /* tp_clear */ - 0, /* tp_richcompare */ - 0, /* tp_weaklistoffset */ - PyObject_SelfIter, /* tp_iter */ - (iternextfunc)filter_next, /* tp_iternext */ - 0, /* tp_methods */ - 0, /* tp_members */ - 0, /* tp_getset */ - 0, /* tp_base */ - 0, /* tp_dict */ - 0, /* tp_descr_get */ - 0, /* tp_descr_set */ - 0, /* tp_dictoffset */ - 0, /* tp_init */ - PyType_GenericAlloc, /* tp_alloc */ - filter_new, /* tp_new */ - PyObject_GC_Del, /* tp_free */ + PyVarObject_HEAD_INIT(&PyType_Type, 0) + "filter", /* tp_name */ + sizeof(filterobject), /* tp_basicsize */ + 0, /* tp_itemsize */ + /* methods */ + (destructor)filter_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 | + Py_TPFLAGS_BASETYPE, /* tp_flags */ + filter_doc, /* tp_doc */ + (traverseproc)filter_traverse, /* tp_traverse */ + 0, /* tp_clear */ + 0, /* tp_richcompare */ + 0, /* tp_weaklistoffset */ + PyObject_SelfIter, /* tp_iter */ + (iternextfunc)filter_next, /* tp_iternext */ + 0, /* tp_methods */ + 0, /* tp_members */ + 0, /* tp_getset */ + 0, /* tp_base */ + 0, /* tp_dict */ + 0, /* tp_descr_get */ + 0, /* tp_descr_set */ + 0, /* tp_dictoffset */ + 0, /* tp_init */ + PyType_GenericAlloc, /* tp_alloc */ + filter_new, /* tp_new */ + PyObject_GC_Del, /* tp_free */ }; @@ -468,7 +468,7 @@ PyObject *format_spec = NULL; if (!PyArg_ParseTuple(args, "O|U:format", &value, &format_spec)) - return NULL; + return NULL; return PyObject_Format(value, format_spec); } @@ -482,12 +482,12 @@ static PyObject * builtin_chr(PyObject *self, PyObject *args) { - int x; + int x; - if (!PyArg_ParseTuple(args, "i:chr", &x)) - return NULL; + if (!PyArg_ParseTuple(args, "i:chr", &x)) + return NULL; - return PyUnicode_FromOrdinal(x); + return PyUnicode_FromOrdinal(x); } PyDoc_VAR(chr_doc) = PyDoc_STR( @@ -506,111 +506,111 @@ static char * source_as_string(PyObject *cmd, char *funcname, char *what, PyCompilerFlags *cf) { - char *str; - Py_ssize_t size; + char *str; + Py_ssize_t size; - if (PyUnicode_Check(cmd)) { - cf->cf_flags |= PyCF_IGNORE_COOKIE; - cmd = _PyUnicode_AsDefaultEncodedString(cmd, NULL); - if (cmd == NULL) - return NULL; - } - else if (!PyObject_CheckReadBuffer(cmd)) { - PyErr_Format(PyExc_TypeError, - "%s() arg 1 must be a %s object", - funcname, what); - return NULL; - } - if (PyObject_AsReadBuffer(cmd, (const void **)&str, &size) < 0) { - return NULL; - } - if (strlen(str) != size) { - PyErr_SetString(PyExc_TypeError, - "source code string cannot contain null bytes"); - return NULL; - } - return str; + if (PyUnicode_Check(cmd)) { + cf->cf_flags |= PyCF_IGNORE_COOKIE; + cmd = _PyUnicode_AsDefaultEncodedString(cmd, NULL); + if (cmd == NULL) + return NULL; + } + else if (!PyObject_CheckReadBuffer(cmd)) { + PyErr_Format(PyExc_TypeError, + "%s() arg 1 must be a %s object", + funcname, what); + return NULL; + } + if (PyObject_AsReadBuffer(cmd, (const void **)&str, &size) < 0) { + return NULL; + } + if (strlen(str) != size) { + PyErr_SetString(PyExc_TypeError, + "source code string cannot contain null bytes"); + return NULL; + } + return str; } static PyObject * builtin_compile(PyObject *self, PyObject *args, PyObject *kwds) { - char *str; - char *filename; - char *startstr; - int mode = -1; - int dont_inherit = 0; - int supplied_flags = 0; - int is_ast; - PyCompilerFlags cf; - PyObject *cmd; - static char *kwlist[] = {"source", "filename", "mode", "flags", - "dont_inherit", NULL}; - int start[] = {Py_file_input, Py_eval_input, Py_single_input}; - - if (!PyArg_ParseTupleAndKeywords(args, kwds, "Oss|ii:compile", - kwlist, &cmd, &filename, &startstr, - &supplied_flags, &dont_inherit)) - return NULL; - - cf.cf_flags = supplied_flags | PyCF_SOURCE_IS_UTF8; - - if (supplied_flags & - ~(PyCF_MASK | PyCF_MASK_OBSOLETE | PyCF_DONT_IMPLY_DEDENT | PyCF_ONLY_AST)) - { - PyErr_SetString(PyExc_ValueError, - "compile(): unrecognised flags"); - return NULL; - } - /* XXX Warn if (supplied_flags & PyCF_MASK_OBSOLETE) != 0? */ - - if (!dont_inherit) { - PyEval_MergeCompilerFlags(&cf); - } - - if (strcmp(startstr, "exec") == 0) - mode = 0; - else if (strcmp(startstr, "eval") == 0) - mode = 1; - else if (strcmp(startstr, "single") == 0) - mode = 2; - else { - PyErr_SetString(PyExc_ValueError, - "compile() arg 3 must be 'exec', 'eval' or 'single'"); - return NULL; - } - - is_ast = PyAST_Check(cmd); - if (is_ast == -1) - return NULL; - if (is_ast) { - PyObject *result; - if (supplied_flags & PyCF_ONLY_AST) { - Py_INCREF(cmd); - result = cmd; - } - else { - PyArena *arena; - mod_ty mod; - - arena = PyArena_New(); - mod = PyAST_obj2mod(cmd, arena, mode); - if (mod == NULL) { - PyArena_Free(arena); - return NULL; - } - result = (PyObject*)PyAST_Compile(mod, filename, - &cf, arena); - PyArena_Free(arena); - } - return result; - } - - str = source_as_string(cmd, "compile", "string, bytes, AST or code", &cf); - if (str == NULL) - return NULL; + char *str; + char *filename; + char *startstr; + int mode = -1; + int dont_inherit = 0; + int supplied_flags = 0; + int is_ast; + PyCompilerFlags cf; + PyObject *cmd; + static char *kwlist[] = {"source", "filename", "mode", "flags", + "dont_inherit", NULL}; + int start[] = {Py_file_input, Py_eval_input, Py_single_input}; + + if (!PyArg_ParseTupleAndKeywords(args, kwds, "Oss|ii:compile", + kwlist, &cmd, &filename, &startstr, + &supplied_flags, &dont_inherit)) + return NULL; + + cf.cf_flags = supplied_flags | PyCF_SOURCE_IS_UTF8; + + if (supplied_flags & + ~(PyCF_MASK | PyCF_MASK_OBSOLETE | PyCF_DONT_IMPLY_DEDENT | PyCF_ONLY_AST)) + { + PyErr_SetString(PyExc_ValueError, + "compile(): unrecognised flags"); + return NULL; + } + /* XXX Warn if (supplied_flags & PyCF_MASK_OBSOLETE) != 0? */ + + if (!dont_inherit) { + PyEval_MergeCompilerFlags(&cf); + } + + if (strcmp(startstr, "exec") == 0) + mode = 0; + else if (strcmp(startstr, "eval") == 0) + mode = 1; + else if (strcmp(startstr, "single") == 0) + mode = 2; + else { + PyErr_SetString(PyExc_ValueError, + "compile() arg 3 must be 'exec', 'eval' or 'single'"); + return NULL; + } + + is_ast = PyAST_Check(cmd); + if (is_ast == -1) + return NULL; + if (is_ast) { + PyObject *result; + if (supplied_flags & PyCF_ONLY_AST) { + Py_INCREF(cmd); + result = cmd; + } + else { + PyArena *arena; + mod_ty mod; + + arena = PyArena_New(); + mod = PyAST_obj2mod(cmd, arena, mode); + if (mod == NULL) { + PyArena_Free(arena); + return NULL; + } + result = (PyObject*)PyAST_Compile(mod, filename, + &cf, arena); + PyArena_Free(arena); + } + return result; + } - return Py_CompileStringFlags(str, filename, start[mode], &cf); + str = source_as_string(cmd, "compile", "string, bytes, AST or code", &cf); + if (str == NULL) + return NULL; + + return Py_CompileStringFlags(str, filename, start[mode], &cf); } PyDoc_STRVAR(compile_doc, @@ -631,11 +631,11 @@ static PyObject * builtin_dir(PyObject *self, PyObject *args) { - PyObject *arg = NULL; + PyObject *arg = NULL; - if (!PyArg_UnpackTuple(args, "dir", 0, 1, &arg)) - return NULL; - return PyObject_Dir(arg); + if (!PyArg_UnpackTuple(args, "dir", 0, 1, &arg)) + return NULL; + return PyObject_Dir(arg); } PyDoc_STRVAR(dir_doc, @@ -655,11 +655,11 @@ static PyObject * builtin_divmod(PyObject *self, PyObject *args) { - PyObject *v, *w; + PyObject *v, *w; - if (!PyArg_UnpackTuple(args, "divmod", 2, 2, &v, &w)) - return NULL; - return PyNumber_Divmod(v, w); + if (!PyArg_UnpackTuple(args, "divmod", 2, 2, &v, &w)) + return NULL; + return PyNumber_Divmod(v, w); } PyDoc_STRVAR(divmod_doc, @@ -671,65 +671,65 @@ static PyObject * builtin_eval(PyObject *self, PyObject *args) { - PyObject *cmd, *result, *tmp = NULL; - PyObject *globals = Py_None, *locals = Py_None; - char *str; - PyCompilerFlags cf; - - if (!PyArg_UnpackTuple(args, "eval", 1, 3, &cmd, &globals, &locals)) - return NULL; - if (locals != Py_None && !PyMapping_Check(locals)) { - PyErr_SetString(PyExc_TypeError, "locals must be a mapping"); - return NULL; - } - if (globals != Py_None && !PyDict_Check(globals)) { - PyErr_SetString(PyExc_TypeError, PyMapping_Check(globals) ? - "globals must be a real dict; try eval(expr, {}, mapping)" - : "globals must be a dict"); - return NULL; - } - if (globals == Py_None) { - globals = PyEval_GetGlobals(); - if (locals == Py_None) - locals = PyEval_GetLocals(); - } - else if (locals == Py_None) - locals = globals; - - if (globals == NULL || locals == NULL) { - PyErr_SetString(PyExc_TypeError, - "eval must be given globals and locals " - "when called without a frame"); - return NULL; - } - - if (PyDict_GetItemString(globals, "__builtins__") == NULL) { - if (PyDict_SetItemString(globals, "__builtins__", - PyEval_GetBuiltins()) != 0) - return NULL; - } - - if (PyCode_Check(cmd)) { - if (PyCode_GetNumFree((PyCodeObject *)cmd) > 0) { - PyErr_SetString(PyExc_TypeError, - "code object passed to eval() may not contain free variables"); - return NULL; - } - return PyEval_EvalCode((PyCodeObject *) cmd, globals, locals); - } - - cf.cf_flags = PyCF_SOURCE_IS_UTF8; - str = source_as_string(cmd, "eval", "string, bytes or code", &cf); - if (str == NULL) - return NULL; - - while (*str == ' ' || *str == '\t') - str++; - - (void)PyEval_MergeCompilerFlags(&cf); - result = PyRun_StringFlags(str, Py_eval_input, globals, locals, &cf); - Py_XDECREF(tmp); - return result; + PyObject *cmd, *result, *tmp = NULL; + PyObject *globals = Py_None, *locals = Py_None; + char *str; + PyCompilerFlags cf; + + if (!PyArg_UnpackTuple(args, "eval", 1, 3, &cmd, &globals, &locals)) + return NULL; + if (locals != Py_None && !PyMapping_Check(locals)) { + PyErr_SetString(PyExc_TypeError, "locals must be a mapping"); + return NULL; + } + if (globals != Py_None && !PyDict_Check(globals)) { + PyErr_SetString(PyExc_TypeError, PyMapping_Check(globals) ? + "globals must be a real dict; try eval(expr, {}, mapping)" + : "globals must be a dict"); + return NULL; + } + if (globals == Py_None) { + globals = PyEval_GetGlobals(); + if (locals == Py_None) + locals = PyEval_GetLocals(); + } + else if (locals == Py_None) + locals = globals; + + if (globals == NULL || locals == NULL) { + PyErr_SetString(PyExc_TypeError, + "eval must be given globals and locals " + "when called without a frame"); + return NULL; + } + + if (PyDict_GetItemString(globals, "__builtins__") == NULL) { + if (PyDict_SetItemString(globals, "__builtins__", + PyEval_GetBuiltins()) != 0) + return NULL; + } + + if (PyCode_Check(cmd)) { + if (PyCode_GetNumFree((PyCodeObject *)cmd) > 0) { + PyErr_SetString(PyExc_TypeError, + "code object passed to eval() may not contain free variables"); + return NULL; + } + return PyEval_EvalCode((PyCodeObject *) cmd, globals, locals); + } + + cf.cf_flags = PyCF_SOURCE_IS_UTF8; + str = source_as_string(cmd, "eval", "string, bytes or code", &cf); + if (str == NULL) + return NULL; + + while (*str == ' ' || *str == '\t') + str++; + + (void)PyEval_MergeCompilerFlags(&cf); + result = PyRun_StringFlags(str, Py_eval_input, globals, locals, &cf); + Py_XDECREF(tmp); + return result; } PyDoc_STRVAR(eval_doc, @@ -745,72 +745,72 @@ static PyObject * builtin_exec(PyObject *self, PyObject *args) { - PyObject *v; - PyObject *prog, *globals = Py_None, *locals = Py_None; - int plain = 0; - - if (!PyArg_UnpackTuple(args, "exec", 1, 3, &prog, &globals, &locals)) - return NULL; - - if (globals == Py_None) { - globals = PyEval_GetGlobals(); - if (locals == Py_None) { - locals = PyEval_GetLocals(); - plain = 1; - } - if (!globals || !locals) { - PyErr_SetString(PyExc_SystemError, - "globals and locals cannot be NULL"); - return NULL; - } - } - else if (locals == Py_None) - locals = globals; - - if (!PyDict_Check(globals)) { - PyErr_Format(PyExc_TypeError, "exec() arg 2 must be a dict, not %.100s", - globals->ob_type->tp_name); - return NULL; - } - if (!PyMapping_Check(locals)) { - PyErr_Format(PyExc_TypeError, - "arg 3 must be a mapping or None, not %.100s", - locals->ob_type->tp_name); - return NULL; - } - if (PyDict_GetItemString(globals, "__builtins__") == NULL) { - if (PyDict_SetItemString(globals, "__builtins__", - PyEval_GetBuiltins()) != 0) - return NULL; - } - - if (PyCode_Check(prog)) { - if (PyCode_GetNumFree((PyCodeObject *)prog) > 0) { - PyErr_SetString(PyExc_TypeError, - "code object passed to exec() may not " - "contain free variables"); - return NULL; - } - v = PyEval_EvalCode((PyCodeObject *) prog, globals, locals); - } - else { - char *str; - PyCompilerFlags cf; - cf.cf_flags = PyCF_SOURCE_IS_UTF8; - str = source_as_string(prog, "exec", - "string, bytes or code", &cf); - if (str == NULL) - return NULL; - if (PyEval_MergeCompilerFlags(&cf)) - v = PyRun_StringFlags(str, Py_file_input, globals, - locals, &cf); - else - v = PyRun_String(str, Py_file_input, globals, locals); - } - if (v == NULL) - return NULL; - Py_DECREF(v); - Py_RETURN_NONE; + PyObject *v; + PyObject *prog, *globals = Py_None, *locals = Py_None; + int plain = 0; + + if (!PyArg_UnpackTuple(args, "exec", 1, 3, &prog, &globals, &locals)) + return NULL; + + if (globals == Py_None) { + globals = PyEval_GetGlobals(); + if (locals == Py_None) { + locals = PyEval_GetLocals(); + plain = 1; + } + if (!globals || !locals) { + PyErr_SetString(PyExc_SystemError, + "globals and locals cannot be NULL"); + return NULL; + } + } + else if (locals == Py_None) + locals = globals; + + if (!PyDict_Check(globals)) { + PyErr_Format(PyExc_TypeError, "exec() arg 2 must be a dict, not %.100s", + globals->ob_type->tp_name); + return NULL; + } + if (!PyMapping_Check(locals)) { + PyErr_Format(PyExc_TypeError, + "arg 3 must be a mapping or None, not %.100s", + locals->ob_type->tp_name); + return NULL; + } + if (PyDict_GetItemString(globals, "__builtins__") == NULL) { + if (PyDict_SetItemString(globals, "__builtins__", + PyEval_GetBuiltins()) != 0) + return NULL; + } + + if (PyCode_Check(prog)) { + if (PyCode_GetNumFree((PyCodeObject *)prog) > 0) { + PyErr_SetString(PyExc_TypeError, + "code object passed to exec() may not " + "contain free variables"); + return NULL; + } + v = PyEval_EvalCode((PyCodeObject *) prog, globals, locals); + } + else { + char *str; + PyCompilerFlags cf; + cf.cf_flags = PyCF_SOURCE_IS_UTF8; + str = source_as_string(prog, "exec", + "string, bytes or code", &cf); + if (str == NULL) + return NULL; + if (PyEval_MergeCompilerFlags(&cf)) + v = PyRun_StringFlags(str, Py_file_input, globals, + locals, &cf); + else + v = PyRun_String(str, Py_file_input, globals, locals); + } + if (v == NULL) + return NULL; + Py_DECREF(v); + Py_RETURN_NONE; } PyDoc_STRVAR(exec_doc, @@ -825,26 +825,26 @@ static PyObject * builtin_getattr(PyObject *self, PyObject *args) { - PyObject *v, *result, *dflt = NULL; - PyObject *name; + PyObject *v, *result, *dflt = NULL; + PyObject *name; - if (!PyArg_UnpackTuple(args, "getattr", 2, 3, &v, &name, &dflt)) - return NULL; + if (!PyArg_UnpackTuple(args, "getattr", 2, 3, &v, &name, &dflt)) + return NULL; - if (!PyUnicode_Check(name)) { - PyErr_SetString(PyExc_TypeError, - "getattr(): attribute name must be string"); - return NULL; - } - result = PyObject_GetAttr(v, name); - if (result == NULL && dflt != NULL && - PyErr_ExceptionMatches(PyExc_AttributeError)) - { - PyErr_Clear(); - Py_INCREF(dflt); - result = dflt; - } - return result; + if (!PyUnicode_Check(name)) { + PyErr_SetString(PyExc_TypeError, + "getattr(): attribute name must be string"); + return NULL; + } + result = PyObject_GetAttr(v, name); + if (result == NULL && dflt != NULL && + PyErr_ExceptionMatches(PyExc_AttributeError)) + { + PyErr_Clear(); + Py_INCREF(dflt); + result = dflt; + } + return result; } PyDoc_STRVAR(getattr_doc, @@ -858,11 +858,11 @@ static PyObject * builtin_globals(PyObject *self) { - PyObject *d; + PyObject *d; - d = PyEval_GetGlobals(); - Py_XINCREF(d); - return d; + d = PyEval_GetGlobals(); + Py_XINCREF(d); + return d; } PyDoc_STRVAR(globals_doc, @@ -874,29 +874,29 @@ static PyObject * builtin_hasattr(PyObject *self, PyObject *args) { - PyObject *v; - PyObject *name; + PyObject *v; + PyObject *name; - if (!PyArg_UnpackTuple(args, "hasattr", 2, 2, &v, &name)) - return NULL; - if (!PyUnicode_Check(name)) { - PyErr_SetString(PyExc_TypeError, - "hasattr(): attribute name must be string"); - return NULL; - } - v = PyObject_GetAttr(v, name); - if (v == NULL) { - if (!PyErr_ExceptionMatches(PyExc_Exception)) - return NULL; - else { - PyErr_Clear(); - Py_INCREF(Py_False); - return Py_False; - } - } - Py_DECREF(v); - Py_INCREF(Py_True); - return Py_True; + if (!PyArg_UnpackTuple(args, "hasattr", 2, 2, &v, &name)) + return NULL; + if (!PyUnicode_Check(name)) { + PyErr_SetString(PyExc_TypeError, + "hasattr(): attribute name must be string"); + return NULL; + } + v = PyObject_GetAttr(v, name); + if (v == NULL) { + if (!PyErr_ExceptionMatches(PyExc_Exception)) + return NULL; + else { + PyErr_Clear(); + Py_INCREF(Py_False); + return Py_False; + } + } + Py_DECREF(v); + Py_INCREF(Py_True); + return Py_True; } PyDoc_STRVAR(hasattr_doc, @@ -909,7 +909,7 @@ static PyObject * builtin_id(PyObject *self, PyObject *v) { - return PyLong_FromVoidPtr(v); + return PyLong_FromVoidPtr(v); } PyDoc_STRVAR(id_doc, @@ -922,181 +922,181 @@ /* map object ************************************************************/ typedef struct { - PyObject_HEAD - PyObject *iters; - PyObject *func; + PyObject_HEAD + PyObject *iters; + PyObject *func; } mapobject; static PyObject * map_new(PyTypeObject *type, PyObject *args, PyObject *kwds) { - PyObject *it, *iters, *func; - mapobject *lz; - Py_ssize_t numargs, i; - - if (type == &PyMap_Type && !_PyArg_NoKeywords("map()", kwds)) - return NULL; - - numargs = PyTuple_Size(args); - if (numargs < 2) { - PyErr_SetString(PyExc_TypeError, - "map() must have at least two arguments."); - return NULL; - } - - iters = PyTuple_New(numargs-1); - if (iters == NULL) - return NULL; - - for (i=1 ; itp_alloc(type, 0); - if (lz == NULL) { - Py_DECREF(iters); - return NULL; - } - lz->iters = iters; - func = PyTuple_GET_ITEM(args, 0); - Py_INCREF(func); - lz->func = func; + PyObject *it, *iters, *func; + mapobject *lz; + Py_ssize_t numargs, i; - return (PyObject *)lz; + if (type == &PyMap_Type && !_PyArg_NoKeywords("map()", kwds)) + return NULL; + + numargs = PyTuple_Size(args); + if (numargs < 2) { + PyErr_SetString(PyExc_TypeError, + "map() must have at least two arguments."); + return NULL; + } + + iters = PyTuple_New(numargs-1); + if (iters == NULL) + return NULL; + + for (i=1 ; itp_alloc(type, 0); + if (lz == NULL) { + Py_DECREF(iters); + return NULL; + } + lz->iters = iters; + func = PyTuple_GET_ITEM(args, 0); + Py_INCREF(func); + lz->func = func; + + return (PyObject *)lz; } static void map_dealloc(mapobject *lz) { - PyObject_GC_UnTrack(lz); - Py_XDECREF(lz->iters); - Py_XDECREF(lz->func); - Py_TYPE(lz)->tp_free(lz); + PyObject_GC_UnTrack(lz); + Py_XDECREF(lz->iters); + Py_XDECREF(lz->func); + Py_TYPE(lz)->tp_free(lz); } static int map_traverse(mapobject *lz, visitproc visit, void *arg) { - Py_VISIT(lz->iters); - Py_VISIT(lz->func); - return 0; + Py_VISIT(lz->iters); + Py_VISIT(lz->func); + return 0; } static PyObject * map_next(mapobject *lz) { - PyObject *val; - PyObject *argtuple; - PyObject *result; - Py_ssize_t numargs, i; - - numargs = PyTuple_Size(lz->iters); - argtuple = PyTuple_New(numargs); - if (argtuple == NULL) - return NULL; - - for (i=0 ; iiters, i)); - if (val == NULL) { - Py_DECREF(argtuple); - return NULL; - } - PyTuple_SET_ITEM(argtuple, i, val); - } - result = PyObject_Call(lz->func, argtuple, NULL); - Py_DECREF(argtuple); - return result; + PyObject *val; + PyObject *argtuple; + PyObject *result; + Py_ssize_t numargs, i; + + numargs = PyTuple_Size(lz->iters); + argtuple = PyTuple_New(numargs); + if (argtuple == NULL) + return NULL; + + for (i=0 ; iiters, i)); + if (val == NULL) { + Py_DECREF(argtuple); + return NULL; + } + PyTuple_SET_ITEM(argtuple, i, val); + } + result = PyObject_Call(lz->func, argtuple, NULL); + Py_DECREF(argtuple); + return result; } PyDoc_STRVAR(map_doc, "map(func, *iterables) --> map object\n\ \n\ Make an iterator that computes the function using arguments from\n\ -each of the iterables. Stops when the shortest iterable is exhausted."); +each of the iterables. Stops when the shortest iterable is exhausted."); PyTypeObject PyMap_Type = { - PyVarObject_HEAD_INIT(&PyType_Type, 0) - "map", /* tp_name */ - sizeof(mapobject), /* tp_basicsize */ - 0, /* tp_itemsize */ - /* methods */ - (destructor)map_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 | - Py_TPFLAGS_BASETYPE, /* tp_flags */ - map_doc, /* tp_doc */ - (traverseproc)map_traverse, /* tp_traverse */ - 0, /* tp_clear */ - 0, /* tp_richcompare */ - 0, /* tp_weaklistoffset */ - PyObject_SelfIter, /* tp_iter */ - (iternextfunc)map_next, /* tp_iternext */ - 0, /* tp_methods */ - 0, /* tp_members */ - 0, /* tp_getset */ - 0, /* tp_base */ - 0, /* tp_dict */ - 0, /* tp_descr_get */ - 0, /* tp_descr_set */ - 0, /* tp_dictoffset */ - 0, /* tp_init */ - PyType_GenericAlloc, /* tp_alloc */ - map_new, /* tp_new */ - PyObject_GC_Del, /* tp_free */ + PyVarObject_HEAD_INIT(&PyType_Type, 0) + "map", /* tp_name */ + sizeof(mapobject), /* tp_basicsize */ + 0, /* tp_itemsize */ + /* methods */ + (destructor)map_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 | + Py_TPFLAGS_BASETYPE, /* tp_flags */ + map_doc, /* tp_doc */ + (traverseproc)map_traverse, /* tp_traverse */ + 0, /* tp_clear */ + 0, /* tp_richcompare */ + 0, /* tp_weaklistoffset */ + PyObject_SelfIter, /* tp_iter */ + (iternextfunc)map_next, /* tp_iternext */ + 0, /* tp_methods */ + 0, /* tp_members */ + 0, /* tp_getset */ + 0, /* tp_base */ + 0, /* tp_dict */ + 0, /* tp_descr_get */ + 0, /* tp_descr_set */ + 0, /* tp_dictoffset */ + 0, /* tp_init */ + PyType_GenericAlloc, /* tp_alloc */ + map_new, /* tp_new */ + PyObject_GC_Del, /* tp_free */ }; static PyObject * builtin_next(PyObject *self, PyObject *args) { - PyObject *it, *res; - PyObject *def = NULL; + PyObject *it, *res; + PyObject *def = NULL; + + if (!PyArg_UnpackTuple(args, "next", 1, 2, &it, &def)) + return NULL; + if (!PyIter_Check(it)) { + PyErr_Format(PyExc_TypeError, + "%.200s object is not an iterator", + it->ob_type->tp_name); + return NULL; + } - if (!PyArg_UnpackTuple(args, "next", 1, 2, &it, &def)) - return NULL; - if (!PyIter_Check(it)) { - PyErr_Format(PyExc_TypeError, - "%.200s object is not an iterator", - it->ob_type->tp_name); - return NULL; - } - - res = (*it->ob_type->tp_iternext)(it); - if (res != NULL) { - return res; - } else if (def != NULL) { - if (PyErr_Occurred()) { - if(!PyErr_ExceptionMatches(PyExc_StopIteration)) - return NULL; - PyErr_Clear(); - } - Py_INCREF(def); - return def; - } else if (PyErr_Occurred()) { - return NULL; - } else { - PyErr_SetNone(PyExc_StopIteration); - return NULL; - } + res = (*it->ob_type->tp_iternext)(it); + if (res != NULL) { + return res; + } else if (def != NULL) { + if (PyErr_Occurred()) { + if(!PyErr_ExceptionMatches(PyExc_StopIteration)) + return NULL; + PyErr_Clear(); + } + Py_INCREF(def); + return def; + } else if (PyErr_Occurred()) { + return NULL; + } else { + PyErr_SetNone(PyExc_StopIteration); + return NULL; + } } PyDoc_STRVAR(next_doc, @@ -1109,16 +1109,16 @@ static PyObject * builtin_setattr(PyObject *self, PyObject *args) { - PyObject *v; - PyObject *name; - PyObject *value; - - if (!PyArg_UnpackTuple(args, "setattr", 3, 3, &v, &name, &value)) - return NULL; - if (PyObject_SetAttr(v, name, value) != 0) - return NULL; - Py_INCREF(Py_None); - return Py_None; + PyObject *v; + PyObject *name; + PyObject *value; + + if (!PyArg_UnpackTuple(args, "setattr", 3, 3, &v, &name, &value)) + return NULL; + if (PyObject_SetAttr(v, name, value) != 0) + return NULL; + Py_INCREF(Py_None); + return Py_None; } PyDoc_STRVAR(setattr_doc, @@ -1131,15 +1131,15 @@ static PyObject * builtin_delattr(PyObject *self, PyObject *args) { - PyObject *v; - PyObject *name; + PyObject *v; + PyObject *name; - if (!PyArg_UnpackTuple(args, "delattr", 2, 2, &v, &name)) - return NULL; - if (PyObject_SetAttr(v, name, (PyObject *)NULL) != 0) - return NULL; - Py_INCREF(Py_None); - return Py_None; + if (!PyArg_UnpackTuple(args, "delattr", 2, 2, &v, &name)) + return NULL; + if (PyObject_SetAttr(v, name, (PyObject *)NULL) != 0) + return NULL; + Py_INCREF(Py_None); + return Py_None; } PyDoc_STRVAR(delattr_doc, @@ -1152,12 +1152,12 @@ static PyObject * builtin_hash(PyObject *self, PyObject *v) { - long x; + long x; - x = PyObject_Hash(v); - if (x == -1) - return NULL; - return PyLong_FromLong(x); + x = PyObject_Hash(v); + if (x == -1) + return NULL; + return PyLong_FromLong(x); } PyDoc_STRVAR(hash_doc, @@ -1170,7 +1170,7 @@ static PyObject * builtin_hex(PyObject *self, PyObject *v) { - return PyNumber_ToBase(v, 16); + return PyNumber_ToBase(v, 16); } PyDoc_STRVAR(hex_doc, @@ -1182,18 +1182,18 @@ static PyObject * builtin_iter(PyObject *self, PyObject *args) { - PyObject *v, *w = NULL; + PyObject *v, *w = NULL; - if (!PyArg_UnpackTuple(args, "iter", 1, 2, &v, &w)) - return NULL; - if (w == NULL) - return PyObject_GetIter(v); - if (!PyCallable_Check(v)) { - PyErr_SetString(PyExc_TypeError, - "iter(v, w): v must be callable"); - return NULL; - } - return PyCallIter_New(v, w); + if (!PyArg_UnpackTuple(args, "iter", 1, 2, &v, &w)) + return NULL; + if (w == NULL) + return PyObject_GetIter(v); + if (!PyCallable_Check(v)) { + PyErr_SetString(PyExc_TypeError, + "iter(v, w): v must be callable"); + return NULL; + } + return PyCallIter_New(v, w); } PyDoc_STRVAR(iter_doc, @@ -1208,12 +1208,12 @@ static PyObject * builtin_len(PyObject *self, PyObject *v) { - Py_ssize_t res; + Py_ssize_t res; - res = PyObject_Size(v); - if (res < 0 && PyErr_Occurred()) - return NULL; - return PyLong_FromSsize_t(res); + res = PyObject_Size(v); + if (res < 0 && PyErr_Occurred()) + return NULL; + return PyLong_FromSsize_t(res); } PyDoc_STRVAR(len_doc, @@ -1225,11 +1225,11 @@ static PyObject * builtin_locals(PyObject *self) { - PyObject *d; + PyObject *d; - d = PyEval_GetLocals(); - Py_XINCREF(d); - return d; + d = PyEval_GetLocals(); + Py_XINCREF(d); + return d; } PyDoc_STRVAR(locals_doc, @@ -1241,96 +1241,96 @@ static PyObject * min_max(PyObject *args, PyObject *kwds, int op) { - PyObject *v, *it, *item, *val, *maxitem, *maxval, *keyfunc=NULL; - const char *name = op == Py_LT ? "min" : "max"; + PyObject *v, *it, *item, *val, *maxitem, *maxval, *keyfunc=NULL; + const char *name = op == Py_LT ? "min" : "max"; + + if (PyTuple_Size(args) > 1) + v = args; + else if (!PyArg_UnpackTuple(args, (char *)name, 1, 1, &v)) + return NULL; - if (PyTuple_Size(args) > 1) - v = args; - else if (!PyArg_UnpackTuple(args, (char *)name, 1, 1, &v)) - return NULL; - - if (kwds != NULL && PyDict_Check(kwds) && PyDict_Size(kwds)) { - keyfunc = PyDict_GetItemString(kwds, "key"); - if (PyDict_Size(kwds)!=1 || keyfunc == NULL) { - PyErr_Format(PyExc_TypeError, - "%s() got an unexpected keyword argument", name); - return NULL; - } - Py_INCREF(keyfunc); - } - - it = PyObject_GetIter(v); - if (it == NULL) { - Py_XDECREF(keyfunc); - return NULL; - } - - maxitem = NULL; /* the result */ - maxval = NULL; /* the value associated with the result */ - while (( item = PyIter_Next(it) )) { - /* get the value from the key function */ - if (keyfunc != NULL) { - val = PyObject_CallFunctionObjArgs(keyfunc, item, NULL); - if (val == NULL) - goto Fail_it_item; - } - /* no key function; the value is the item */ - else { - val = item; - Py_INCREF(val); - } - - /* maximum value and item are unset; set them */ - if (maxval == NULL) { - maxitem = item; - maxval = val; - } - /* maximum value and item are set; update them as necessary */ - else { - int cmp = PyObject_RichCompareBool(val, maxval, op); - if (cmp < 0) - goto Fail_it_item_and_val; - else if (cmp > 0) { - Py_DECREF(maxval); - Py_DECREF(maxitem); - maxval = val; - maxitem = item; - } - else { - Py_DECREF(item); - Py_DECREF(val); - } - } - } - if (PyErr_Occurred()) - goto Fail_it; - if (maxval == NULL) { - PyErr_Format(PyExc_ValueError, - "%s() arg is an empty sequence", name); - assert(maxitem == NULL); - } - else - Py_DECREF(maxval); - Py_DECREF(it); - Py_XDECREF(keyfunc); - return maxitem; + if (kwds != NULL && PyDict_Check(kwds) && PyDict_Size(kwds)) { + keyfunc = PyDict_GetItemString(kwds, "key"); + if (PyDict_Size(kwds)!=1 || keyfunc == NULL) { + PyErr_Format(PyExc_TypeError, + "%s() got an unexpected keyword argument", name); + return NULL; + } + Py_INCREF(keyfunc); + } + + it = PyObject_GetIter(v); + if (it == NULL) { + Py_XDECREF(keyfunc); + return NULL; + } + + maxitem = NULL; /* the result */ + maxval = NULL; /* the value associated with the result */ + while (( item = PyIter_Next(it) )) { + /* get the value from the key function */ + if (keyfunc != NULL) { + val = PyObject_CallFunctionObjArgs(keyfunc, item, NULL); + if (val == NULL) + goto Fail_it_item; + } + /* no key function; the value is the item */ + else { + val = item; + Py_INCREF(val); + } + + /* maximum value and item are unset; set them */ + if (maxval == NULL) { + maxitem = item; + maxval = val; + } + /* maximum value and item are set; update them as necessary */ + else { + int cmp = PyObject_RichCompareBool(val, maxval, op); + if (cmp < 0) + goto Fail_it_item_and_val; + else if (cmp > 0) { + Py_DECREF(maxval); + Py_DECREF(maxitem); + maxval = val; + maxitem = item; + } + else { + Py_DECREF(item); + Py_DECREF(val); + } + } + } + if (PyErr_Occurred()) + goto Fail_it; + if (maxval == NULL) { + PyErr_Format(PyExc_ValueError, + "%s() arg is an empty sequence", name); + assert(maxitem == NULL); + } + else + Py_DECREF(maxval); + Py_DECREF(it); + Py_XDECREF(keyfunc); + return maxitem; Fail_it_item_and_val: - Py_DECREF(val); + Py_DECREF(val); Fail_it_item: - Py_DECREF(item); + Py_DECREF(item); Fail_it: - Py_XDECREF(maxval); - Py_XDECREF(maxitem); - Py_DECREF(it); - Py_XDECREF(keyfunc); - return NULL; + Py_XDECREF(maxval); + Py_XDECREF(maxitem); + Py_DECREF(it); + Py_XDECREF(keyfunc); + return NULL; } static PyObject * builtin_min(PyObject *self, PyObject *args, PyObject *kwds) { - return min_max(args, kwds, Py_LT); + return min_max(args, kwds, Py_LT); } PyDoc_STRVAR(min_doc, @@ -1344,7 +1344,7 @@ static PyObject * builtin_max(PyObject *self, PyObject *args, PyObject *kwds) { - return min_max(args, kwds, Py_GT); + return min_max(args, kwds, Py_GT); } PyDoc_STRVAR(max_doc, @@ -1358,7 +1358,7 @@ static PyObject * builtin_oct(PyObject *self, PyObject *v) { - return PyNumber_ToBase(v, 8); + return PyNumber_ToBase(v, 8); } PyDoc_STRVAR(oct_doc, @@ -1370,56 +1370,56 @@ static PyObject * builtin_ord(PyObject *self, PyObject* obj) { - long ord; - Py_ssize_t size; + long ord; + Py_ssize_t size; - if (PyBytes_Check(obj)) { - size = PyBytes_GET_SIZE(obj); - if (size == 1) { - ord = (long)((unsigned char)*PyBytes_AS_STRING(obj)); - return PyLong_FromLong(ord); - } - } - else if (PyUnicode_Check(obj)) { - size = PyUnicode_GET_SIZE(obj); - if (size == 1) { - ord = (long)*PyUnicode_AS_UNICODE(obj); - return PyLong_FromLong(ord); - } + if (PyBytes_Check(obj)) { + size = PyBytes_GET_SIZE(obj); + if (size == 1) { + ord = (long)((unsigned char)*PyBytes_AS_STRING(obj)); + return PyLong_FromLong(ord); + } + } + else if (PyUnicode_Check(obj)) { + size = PyUnicode_GET_SIZE(obj); + if (size == 1) { + ord = (long)*PyUnicode_AS_UNICODE(obj); + return PyLong_FromLong(ord); + } #ifndef Py_UNICODE_WIDE - if (size == 2) { - /* Decode a valid surrogate pair */ - int c0 = PyUnicode_AS_UNICODE(obj)[0]; - int c1 = PyUnicode_AS_UNICODE(obj)[1]; - if (0xD800 <= c0 && c0 <= 0xDBFF && - 0xDC00 <= c1 && c1 <= 0xDFFF) { - ord = ((((c0 & 0x03FF) << 10) | (c1 & 0x03FF)) + - 0x00010000); - return PyLong_FromLong(ord); - } - } + if (size == 2) { + /* Decode a valid surrogate pair */ + int c0 = PyUnicode_AS_UNICODE(obj)[0]; + int c1 = PyUnicode_AS_UNICODE(obj)[1]; + if (0xD800 <= c0 && c0 <= 0xDBFF && + 0xDC00 <= c1 && c1 <= 0xDFFF) { + ord = ((((c0 & 0x03FF) << 10) | (c1 & 0x03FF)) + + 0x00010000); + return PyLong_FromLong(ord); + } + } #endif - } - else if (PyByteArray_Check(obj)) { - /* XXX Hopefully this is temporary */ - size = PyByteArray_GET_SIZE(obj); - if (size == 1) { - ord = (long)((unsigned char)*PyByteArray_AS_STRING(obj)); - return PyLong_FromLong(ord); - } - } - else { - PyErr_Format(PyExc_TypeError, - "ord() expected string of length 1, but " \ - "%.200s found", obj->ob_type->tp_name); - return NULL; - } - - PyErr_Format(PyExc_TypeError, - "ord() expected a character, " - "but string of length %zd found", - size); - return NULL; + } + else if (PyByteArray_Check(obj)) { + /* XXX Hopefully this is temporary */ + size = PyByteArray_GET_SIZE(obj); + if (size == 1) { + ord = (long)((unsigned char)*PyByteArray_AS_STRING(obj)); + return PyLong_FromLong(ord); + } + } + else { + PyErr_Format(PyExc_TypeError, + "ord() expected string of length 1, but " \ + "%.200s found", obj->ob_type->tp_name); + return NULL; + } + + PyErr_Format(PyExc_TypeError, + "ord() expected a character, " + "but string of length %zd found", + size); + return NULL; } PyDoc_VAR(ord_doc) = PyDoc_STR( @@ -1438,11 +1438,11 @@ static PyObject * builtin_pow(PyObject *self, PyObject *args) { - PyObject *v, *w, *z = Py_None; + PyObject *v, *w, *z = Py_None; - if (!PyArg_UnpackTuple(args, "pow", 2, 3, &v, &w, &z)) - return NULL; - return PyNumber_Power(v, w, z); + if (!PyArg_UnpackTuple(args, "pow", 2, 3, &v, &w, &z)) + return NULL; + return PyNumber_Power(v, w, z); } PyDoc_STRVAR(pow_doc, @@ -1456,68 +1456,68 @@ static PyObject * builtin_print(PyObject *self, PyObject *args, PyObject *kwds) { - static char *kwlist[] = {"sep", "end", "file", 0}; - static PyObject *dummy_args; - PyObject *sep = NULL, *end = NULL, *file = NULL; - int i, err; - - if (dummy_args == NULL) { - if (!(dummy_args = PyTuple_New(0))) - return NULL; - } - if (!PyArg_ParseTupleAndKeywords(dummy_args, kwds, "|OOO:print", - kwlist, &sep, &end, &file)) - return NULL; - if (file == NULL || file == Py_None) { - file = PySys_GetObject("stdout"); - /* sys.stdout may be None when FILE* stdout isn't connected */ - if (file == Py_None) - Py_RETURN_NONE; - } - - if (sep == Py_None) { - sep = NULL; - } - else if (sep && !PyUnicode_Check(sep)) { - PyErr_Format(PyExc_TypeError, - "sep must be None or a string, not %.200s", - sep->ob_type->tp_name); - return NULL; - } - if (end == Py_None) { - end = NULL; - } - else if (end && !PyUnicode_Check(end)) { - PyErr_Format(PyExc_TypeError, - "end must be None or a string, not %.200s", - end->ob_type->tp_name); - return NULL; - } - - for (i = 0; i < PyTuple_Size(args); i++) { - if (i > 0) { - if (sep == NULL) - err = PyFile_WriteString(" ", file); - else - err = PyFile_WriteObject(sep, file, - Py_PRINT_RAW); - if (err) - return NULL; - } - err = PyFile_WriteObject(PyTuple_GetItem(args, i), file, - Py_PRINT_RAW); - if (err) - return NULL; - } - - if (end == NULL) - err = PyFile_WriteString("\n", file); - else - err = PyFile_WriteObject(end, file, Py_PRINT_RAW); - if (err) - return NULL; + static char *kwlist[] = {"sep", "end", "file", 0}; + static PyObject *dummy_args; + PyObject *sep = NULL, *end = NULL, *file = NULL; + int i, err; + + if (dummy_args == NULL) { + if (!(dummy_args = PyTuple_New(0))) + return NULL; + } + if (!PyArg_ParseTupleAndKeywords(dummy_args, kwds, "|OOO:print", + kwlist, &sep, &end, &file)) + return NULL; + if (file == NULL || file == Py_None) { + file = PySys_GetObject("stdout"); + /* sys.stdout may be None when FILE* stdout isn't connected */ + if (file == Py_None) + Py_RETURN_NONE; + } + + if (sep == Py_None) { + sep = NULL; + } + else if (sep && !PyUnicode_Check(sep)) { + PyErr_Format(PyExc_TypeError, + "sep must be None or a string, not %.200s", + sep->ob_type->tp_name); + return NULL; + } + if (end == Py_None) { + end = NULL; + } + else if (end && !PyUnicode_Check(end)) { + PyErr_Format(PyExc_TypeError, + "end must be None or a string, not %.200s", + end->ob_type->tp_name); + return NULL; + } + + for (i = 0; i < PyTuple_Size(args); i++) { + if (i > 0) { + if (sep == NULL) + err = PyFile_WriteString(" ", file); + else + err = PyFile_WriteObject(sep, file, + Py_PRINT_RAW); + if (err) + return NULL; + } + err = PyFile_WriteObject(PyTuple_GetItem(args, i), file, + Py_PRINT_RAW); + if (err) + return NULL; + } + + if (end == NULL) + err = PyFile_WriteString("\n", file); + else + err = PyFile_WriteObject(end, file, Py_PRINT_RAW); + if (err) + return NULL; - Py_RETURN_NONE; + Py_RETURN_NONE; } PyDoc_STRVAR(print_doc, @@ -1533,164 +1533,164 @@ static PyObject * builtin_input(PyObject *self, PyObject *args) { - PyObject *promptarg = NULL; - PyObject *fin = PySys_GetObject("stdin"); - PyObject *fout = PySys_GetObject("stdout"); - PyObject *ferr = PySys_GetObject("stderr"); - PyObject *tmp; - long fd; - int tty; - - /* Parse arguments */ - if (!PyArg_UnpackTuple(args, "input", 0, 1, &promptarg)) - return NULL; - - /* Check that stdin/out/err are intact */ - if (fin == NULL || fin == Py_None) { - PyErr_SetString(PyExc_RuntimeError, - "input(): lost sys.stdin"); - return NULL; - } - if (fout == NULL || fout == Py_None) { - PyErr_SetString(PyExc_RuntimeError, - "input(): lost sys.stdout"); - return NULL; - } - if (ferr == NULL || ferr == Py_None) { - PyErr_SetString(PyExc_RuntimeError, - "input(): lost sys.stderr"); - return NULL; - } - - /* First of all, flush stderr */ - tmp = PyObject_CallMethod(ferr, "flush", ""); - if (tmp == NULL) - PyErr_Clear(); - else - Py_DECREF(tmp); - - /* We should only use (GNU) readline if Python's sys.stdin and - sys.stdout are the same as C's stdin and stdout, because we - need to pass it those. */ - tmp = PyObject_CallMethod(fin, "fileno", ""); - if (tmp == NULL) { - PyErr_Clear(); - tty = 0; - } - else { - fd = PyLong_AsLong(tmp); - Py_DECREF(tmp); - if (fd < 0 && PyErr_Occurred()) - return NULL; - tty = fd == fileno(stdin) && isatty(fd); - } - if (tty) { - tmp = PyObject_CallMethod(fout, "fileno", ""); - if (tmp == NULL) - PyErr_Clear(); - else { - fd = PyLong_AsLong(tmp); - Py_DECREF(tmp); - if (fd < 0 && PyErr_Occurred()) - return NULL; - tty = fd == fileno(stdout) && isatty(fd); - } - } - - /* If we're interactive, use (GNU) readline */ - if (tty) { - PyObject *po; - char *prompt; - char *s; - PyObject *stdin_encoding; - PyObject *result; - - stdin_encoding = PyObject_GetAttrString(fin, "encoding"); - if (!stdin_encoding) - /* stdin is a text stream, so it must have an - encoding. */ - return NULL; - tmp = PyObject_CallMethod(fout, "flush", ""); - if (tmp == NULL) - PyErr_Clear(); - else - Py_DECREF(tmp); - if (promptarg != NULL) { - PyObject *stringpo; - PyObject *stdout_encoding; - stdout_encoding = PyObject_GetAttrString(fout, - "encoding"); - if (stdout_encoding == NULL) { - Py_DECREF(stdin_encoding); - return NULL; - } - stringpo = PyObject_Str(promptarg); - if (stringpo == NULL) { - Py_DECREF(stdin_encoding); - Py_DECREF(stdout_encoding); - return NULL; - } - po = PyUnicode_AsEncodedString(stringpo, - _PyUnicode_AsString(stdout_encoding), NULL); - Py_DECREF(stdout_encoding); - Py_DECREF(stringpo); - if (po == NULL) { - Py_DECREF(stdin_encoding); - return NULL; - } - prompt = PyBytes_AsString(po); - if (prompt == NULL) { - Py_DECREF(stdin_encoding); - Py_DECREF(po); - return NULL; - } - } - else { - po = NULL; - prompt = ""; - } - s = PyOS_Readline(stdin, stdout, prompt); - Py_XDECREF(po); - if (s == NULL) { - if (!PyErr_Occurred()) - PyErr_SetNone(PyExc_KeyboardInterrupt); - Py_DECREF(stdin_encoding); - return NULL; - } - if (*s == '\0') { - PyErr_SetNone(PyExc_EOFError); - result = NULL; - } - else { /* strip trailing '\n' */ - size_t len = strlen(s); - if (len > PY_SSIZE_T_MAX) { - PyErr_SetString(PyExc_OverflowError, - "input: input too long"); - result = NULL; - } - else { - result = PyUnicode_Decode - (s, len-1, - _PyUnicode_AsString(stdin_encoding), - NULL); - } - } - Py_DECREF(stdin_encoding); - PyMem_FREE(s); - return result; - } - - /* Fallback if we're not interactive */ - if (promptarg != NULL) { - if (PyFile_WriteObject(promptarg, fout, Py_PRINT_RAW) != 0) - return NULL; - } - tmp = PyObject_CallMethod(fout, "flush", ""); - if (tmp == NULL) - PyErr_Clear(); - else - Py_DECREF(tmp); - return PyFile_GetLine(fin, -1); + PyObject *promptarg = NULL; + PyObject *fin = PySys_GetObject("stdin"); + PyObject *fout = PySys_GetObject("stdout"); + PyObject *ferr = PySys_GetObject("stderr"); + PyObject *tmp; + long fd; + int tty; + + /* Parse arguments */ + if (!PyArg_UnpackTuple(args, "input", 0, 1, &promptarg)) + return NULL; + + /* Check that stdin/out/err are intact */ + if (fin == NULL || fin == Py_None) { + PyErr_SetString(PyExc_RuntimeError, + "input(): lost sys.stdin"); + return NULL; + } + if (fout == NULL || fout == Py_None) { + PyErr_SetString(PyExc_RuntimeError, + "input(): lost sys.stdout"); + return NULL; + } + if (ferr == NULL || ferr == Py_None) { + PyErr_SetString(PyExc_RuntimeError, + "input(): lost sys.stderr"); + return NULL; + } + + /* First of all, flush stderr */ + tmp = PyObject_CallMethod(ferr, "flush", ""); + if (tmp == NULL) + PyErr_Clear(); + else + Py_DECREF(tmp); + + /* We should only use (GNU) readline if Python's sys.stdin and + sys.stdout are the same as C's stdin and stdout, because we + need to pass it those. */ + tmp = PyObject_CallMethod(fin, "fileno", ""); + if (tmp == NULL) { + PyErr_Clear(); + tty = 0; + } + else { + fd = PyLong_AsLong(tmp); + Py_DECREF(tmp); + if (fd < 0 && PyErr_Occurred()) + return NULL; + tty = fd == fileno(stdin) && isatty(fd); + } + if (tty) { + tmp = PyObject_CallMethod(fout, "fileno", ""); + if (tmp == NULL) + PyErr_Clear(); + else { + fd = PyLong_AsLong(tmp); + Py_DECREF(tmp); + if (fd < 0 && PyErr_Occurred()) + return NULL; + tty = fd == fileno(stdout) && isatty(fd); + } + } + + /* If we're interactive, use (GNU) readline */ + if (tty) { + PyObject *po; + char *prompt; + char *s; + PyObject *stdin_encoding; + PyObject *result; + + stdin_encoding = PyObject_GetAttrString(fin, "encoding"); + if (!stdin_encoding) + /* stdin is a text stream, so it must have an + encoding. */ + return NULL; + tmp = PyObject_CallMethod(fout, "flush", ""); + if (tmp == NULL) + PyErr_Clear(); + else + Py_DECREF(tmp); + if (promptarg != NULL) { + PyObject *stringpo; + PyObject *stdout_encoding; + stdout_encoding = PyObject_GetAttrString(fout, + "encoding"); + if (stdout_encoding == NULL) { + Py_DECREF(stdin_encoding); + return NULL; + } + stringpo = PyObject_Str(promptarg); + if (stringpo == NULL) { + Py_DECREF(stdin_encoding); + Py_DECREF(stdout_encoding); + return NULL; + } + po = PyUnicode_AsEncodedString(stringpo, + _PyUnicode_AsString(stdout_encoding), NULL); + Py_DECREF(stdout_encoding); + Py_DECREF(stringpo); + if (po == NULL) { + Py_DECREF(stdin_encoding); + return NULL; + } + prompt = PyBytes_AsString(po); + if (prompt == NULL) { + Py_DECREF(stdin_encoding); + Py_DECREF(po); + return NULL; + } + } + else { + po = NULL; + prompt = ""; + } + s = PyOS_Readline(stdin, stdout, prompt); + Py_XDECREF(po); + if (s == NULL) { + if (!PyErr_Occurred()) + PyErr_SetNone(PyExc_KeyboardInterrupt); + Py_DECREF(stdin_encoding); + return NULL; + } + if (*s == '\0') { + PyErr_SetNone(PyExc_EOFError); + result = NULL; + } + else { /* strip trailing '\n' */ + size_t len = strlen(s); + if (len > PY_SSIZE_T_MAX) { + PyErr_SetString(PyExc_OverflowError, + "input: input too long"); + result = NULL; + } + else { + result = PyUnicode_Decode + (s, len-1, + _PyUnicode_AsString(stdin_encoding), + NULL); + } + } + Py_DECREF(stdin_encoding); + PyMem_FREE(s); + return result; + } + + /* Fallback if we're not interactive */ + if (promptarg != NULL) { + if (PyFile_WriteObject(promptarg, fout, Py_PRINT_RAW) != 0) + return NULL; + } + tmp = PyObject_CallMethod(fout, "flush", ""); + if (tmp == NULL) + PyErr_Clear(); + else + Py_DECREF(tmp); + return PyFile_GetLine(fin, -1); } PyDoc_STRVAR(input_doc, @@ -1705,7 +1705,7 @@ static PyObject * builtin_repr(PyObject *self, PyObject *v) { - return PyObject_Repr(v); + return PyObject_Repr(v); } PyDoc_STRVAR(repr_doc, @@ -1718,38 +1718,38 @@ static PyObject * builtin_round(PyObject *self, PyObject *args, PyObject *kwds) { - static PyObject *round_str = NULL; - PyObject *ndigits = NULL; - static char *kwlist[] = {"number", "ndigits", 0}; - PyObject *number, *round; - - if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|O:round", - kwlist, &number, &ndigits)) - return NULL; - - if (Py_TYPE(number)->tp_dict == NULL) { - if (PyType_Ready(Py_TYPE(number)) < 0) - return NULL; - } - - if (round_str == NULL) { - round_str = PyUnicode_InternFromString("__round__"); - if (round_str == NULL) - return NULL; - } - - round = _PyType_Lookup(Py_TYPE(number), round_str); - if (round == NULL) { - PyErr_Format(PyExc_TypeError, - "type %.100s doesn't define __round__ method", - Py_TYPE(number)->tp_name); - return NULL; - } - - if (ndigits == NULL) - return PyObject_CallFunction(round, "O", number); - else - return PyObject_CallFunction(round, "OO", number, ndigits); + static PyObject *round_str = NULL; + PyObject *ndigits = NULL; + static char *kwlist[] = {"number", "ndigits", 0}; + PyObject *number, *round; + + if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|O:round", + kwlist, &number, &ndigits)) + return NULL; + + if (Py_TYPE(number)->tp_dict == NULL) { + if (PyType_Ready(Py_TYPE(number)) < 0) + return NULL; + } + + if (round_str == NULL) { + round_str = PyUnicode_InternFromString("__round__"); + if (round_str == NULL) + return NULL; + } + + round = _PyType_Lookup(Py_TYPE(number), round_str); + if (round == NULL) { + PyErr_Format(PyExc_TypeError, + "type %.100s doesn't define __round__ method", + Py_TYPE(number)->tp_name); + return NULL; + } + + if (ndigits == NULL) + return PyObject_CallFunction(round, "O", number); + else + return PyObject_CallFunction(round, "OO", number, ndigits); } PyDoc_STRVAR(round_doc, @@ -1763,42 +1763,42 @@ static PyObject * builtin_sorted(PyObject *self, PyObject *args, PyObject *kwds) { - PyObject *newlist, *v, *seq, *keyfunc=NULL, *newargs; - PyObject *callable; - static char *kwlist[] = {"iterable", "key", "reverse", 0}; - int reverse; - - /* args 1-3 should match listsort in Objects/listobject.c */ - if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|Oi:sorted", - kwlist, &seq, &keyfunc, &reverse)) - return NULL; - - newlist = PySequence_List(seq); - if (newlist == NULL) - return NULL; - - callable = PyObject_GetAttrString(newlist, "sort"); - if (callable == NULL) { - Py_DECREF(newlist); - return NULL; - } - - newargs = PyTuple_GetSlice(args, 1, 4); - if (newargs == NULL) { - Py_DECREF(newlist); - Py_DECREF(callable); - return NULL; - } - - v = PyObject_Call(callable, newargs, kwds); - Py_DECREF(newargs); - Py_DECREF(callable); - if (v == NULL) { - Py_DECREF(newlist); - return NULL; - } - Py_DECREF(v); - return newlist; + PyObject *newlist, *v, *seq, *keyfunc=NULL, *newargs; + PyObject *callable; + static char *kwlist[] = {"iterable", "key", "reverse", 0}; + int reverse; + + /* args 1-3 should match listsort in Objects/listobject.c */ + if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|Oi:sorted", + kwlist, &seq, &keyfunc, &reverse)) + return NULL; + + newlist = PySequence_List(seq); + if (newlist == NULL) + return NULL; + + callable = PyObject_GetAttrString(newlist, "sort"); + if (callable == NULL) { + Py_DECREF(newlist); + return NULL; + } + + newargs = PyTuple_GetSlice(args, 1, 4); + if (newargs == NULL) { + Py_DECREF(newlist); + Py_DECREF(callable); + return NULL; + } + + v = PyObject_Call(callable, newargs, kwds); + Py_DECREF(newargs); + Py_DECREF(callable); + if (v == NULL) { + Py_DECREF(newlist); + return NULL; + } + Py_DECREF(v); + return newlist; } PyDoc_STRVAR(sorted_doc, @@ -1807,30 +1807,30 @@ static PyObject * builtin_vars(PyObject *self, PyObject *args) { - PyObject *v = NULL; - PyObject *d; + PyObject *v = NULL; + PyObject *d; - if (!PyArg_UnpackTuple(args, "vars", 0, 1, &v)) - return NULL; - if (v == NULL) { - d = PyEval_GetLocals(); - if (d == NULL) { - if (!PyErr_Occurred()) - PyErr_SetString(PyExc_SystemError, - "vars(): no locals!?"); - } - else - Py_INCREF(d); - } - else { - d = PyObject_GetAttrString(v, "__dict__"); - if (d == NULL) { - PyErr_SetString(PyExc_TypeError, - "vars() argument must have __dict__ attribute"); - return NULL; - } - } - return d; + if (!PyArg_UnpackTuple(args, "vars", 0, 1, &v)) + return NULL; + if (v == NULL) { + d = PyEval_GetLocals(); + if (d == NULL) { + if (!PyErr_Occurred()) + PyErr_SetString(PyExc_SystemError, + "vars(): no locals!?"); + } + else + Py_INCREF(d); + } + else { + d = PyObject_GetAttrString(v, "__dict__"); + if (d == NULL) { + PyErr_SetString(PyExc_TypeError, + "vars() argument must have __dict__ attribute"); + return NULL; + } + } + return d; } PyDoc_STRVAR(vars_doc, @@ -1842,156 +1842,156 @@ static PyObject* builtin_sum(PyObject *self, PyObject *args) { - PyObject *seq; - PyObject *result = NULL; - PyObject *temp, *item, *iter; - - if (!PyArg_UnpackTuple(args, "sum", 1, 2, &seq, &result)) - return NULL; - - iter = PyObject_GetIter(seq); - if (iter == NULL) - return NULL; - - if (result == NULL) { - result = PyLong_FromLong(0); - if (result == NULL) { - Py_DECREF(iter); - return NULL; - } - } else { - /* reject string values for 'start' parameter */ - if (PyUnicode_Check(result)) { - PyErr_SetString(PyExc_TypeError, - "sum() can't sum strings [use ''.join(seq) instead]"); - Py_DECREF(iter); - return NULL; - } - if (PyByteArray_Check(result)) { - PyErr_SetString(PyExc_TypeError, - "sum() can't sum bytes [use b''.join(seq) instead]"); - Py_DECREF(iter); - return NULL; - } + PyObject *seq; + PyObject *result = NULL; + PyObject *temp, *item, *iter; - Py_INCREF(result); - } + if (!PyArg_UnpackTuple(args, "sum", 1, 2, &seq, &result)) + return NULL; + + iter = PyObject_GetIter(seq); + if (iter == NULL) + return NULL; + + if (result == NULL) { + result = PyLong_FromLong(0); + if (result == NULL) { + Py_DECREF(iter); + return NULL; + } + } else { + /* reject string values for 'start' parameter */ + if (PyUnicode_Check(result)) { + PyErr_SetString(PyExc_TypeError, + "sum() can't sum strings [use ''.join(seq) instead]"); + Py_DECREF(iter); + return NULL; + } + if (PyByteArray_Check(result)) { + PyErr_SetString(PyExc_TypeError, + "sum() can't sum bytes [use b''.join(seq) instead]"); + Py_DECREF(iter); + return NULL; + } + + Py_INCREF(result); + } #ifndef SLOW_SUM - /* Fast addition by keeping temporary sums in C instead of new Python objects. - Assumes all inputs are the same type. If the assumption fails, default - to the more general routine. - */ - if (PyLong_CheckExact(result)) { - int overflow; - long i_result = PyLong_AsLongAndOverflow(result, &overflow); - /* If this already overflowed, don't even enter the loop. */ - if (overflow == 0) { - Py_DECREF(result); - result = NULL; - } - while(result == NULL) { - item = PyIter_Next(iter); - if (item == NULL) { - Py_DECREF(iter); - if (PyErr_Occurred()) - return NULL; - return PyLong_FromLong(i_result); - } - if (PyLong_CheckExact(item)) { - long b = PyLong_AsLongAndOverflow(item, &overflow); - long x = i_result + b; - if (overflow == 0 && ((x^i_result) >= 0 || (x^b) >= 0)) { - i_result = x; - Py_DECREF(item); - continue; - } - } - /* Either overflowed or is not an int. Restore real objects and process normally */ - result = PyLong_FromLong(i_result); - temp = PyNumber_Add(result, item); - Py_DECREF(result); - Py_DECREF(item); - result = temp; - if (result == NULL) { - Py_DECREF(iter); - return NULL; - } - } - } - - if (PyFloat_CheckExact(result)) { - double f_result = PyFloat_AS_DOUBLE(result); - Py_DECREF(result); - result = NULL; - while(result == NULL) { - item = PyIter_Next(iter); - if (item == NULL) { - Py_DECREF(iter); - if (PyErr_Occurred()) - return NULL; - return PyFloat_FromDouble(f_result); - } - if (PyFloat_CheckExact(item)) { - PyFPE_START_PROTECT("add", Py_DECREF(item); Py_DECREF(iter); return 0) - f_result += PyFloat_AS_DOUBLE(item); - PyFPE_END_PROTECT(f_result) - Py_DECREF(item); - continue; - } - if (PyLong_CheckExact(item)) { - long value; - int overflow; - value = PyLong_AsLongAndOverflow(item, &overflow); - if (!overflow) { - PyFPE_START_PROTECT("add", Py_DECREF(item); Py_DECREF(iter); return 0) - f_result += (double)value; - PyFPE_END_PROTECT(f_result) - Py_DECREF(item); - continue; - } - } - result = PyFloat_FromDouble(f_result); - temp = PyNumber_Add(result, item); - Py_DECREF(result); - Py_DECREF(item); - result = temp; - if (result == NULL) { - Py_DECREF(iter); - return NULL; - } - } - } + /* Fast addition by keeping temporary sums in C instead of new Python objects. + Assumes all inputs are the same type. If the assumption fails, default + to the more general routine. + */ + if (PyLong_CheckExact(result)) { + int overflow; + long i_result = PyLong_AsLongAndOverflow(result, &overflow); + /* If this already overflowed, don't even enter the loop. */ + if (overflow == 0) { + Py_DECREF(result); + result = NULL; + } + while(result == NULL) { + item = PyIter_Next(iter); + if (item == NULL) { + Py_DECREF(iter); + if (PyErr_Occurred()) + return NULL; + return PyLong_FromLong(i_result); + } + if (PyLong_CheckExact(item)) { + long b = PyLong_AsLongAndOverflow(item, &overflow); + long x = i_result + b; + if (overflow == 0 && ((x^i_result) >= 0 || (x^b) >= 0)) { + i_result = x; + Py_DECREF(item); + continue; + } + } + /* Either overflowed or is not an int. Restore real objects and process normally */ + result = PyLong_FromLong(i_result); + temp = PyNumber_Add(result, item); + Py_DECREF(result); + Py_DECREF(item); + result = temp; + if (result == NULL) { + Py_DECREF(iter); + return NULL; + } + } + } + + if (PyFloat_CheckExact(result)) { + double f_result = PyFloat_AS_DOUBLE(result); + Py_DECREF(result); + result = NULL; + while(result == NULL) { + item = PyIter_Next(iter); + if (item == NULL) { + Py_DECREF(iter); + if (PyErr_Occurred()) + return NULL; + return PyFloat_FromDouble(f_result); + } + if (PyFloat_CheckExact(item)) { + PyFPE_START_PROTECT("add", Py_DECREF(item); Py_DECREF(iter); return 0) + f_result += PyFloat_AS_DOUBLE(item); + PyFPE_END_PROTECT(f_result) + Py_DECREF(item); + continue; + } + if (PyLong_CheckExact(item)) { + long value; + int overflow; + value = PyLong_AsLongAndOverflow(item, &overflow); + if (!overflow) { + PyFPE_START_PROTECT("add", Py_DECREF(item); Py_DECREF(iter); return 0) + f_result += (double)value; + PyFPE_END_PROTECT(f_result) + Py_DECREF(item); + continue; + } + } + result = PyFloat_FromDouble(f_result); + temp = PyNumber_Add(result, item); + Py_DECREF(result); + Py_DECREF(item); + result = temp; + if (result == NULL) { + Py_DECREF(iter); + return NULL; + } + } + } #endif - for(;;) { - item = PyIter_Next(iter); - if (item == NULL) { - /* error, or end-of-sequence */ - if (PyErr_Occurred()) { - Py_DECREF(result); - result = NULL; - } - break; - } - /* It's tempting to use PyNumber_InPlaceAdd instead of - PyNumber_Add here, to avoid quadratic running time - when doing 'sum(list_of_lists, [])'. However, this - would produce a change in behaviour: a snippet like - - empty = [] - sum([[x] for x in range(10)], empty) - - would change the value of empty. */ - temp = PyNumber_Add(result, item); - Py_DECREF(result); - Py_DECREF(item); - result = temp; - if (result == NULL) - break; - } - Py_DECREF(iter); - return result; + for(;;) { + item = PyIter_Next(iter); + if (item == NULL) { + /* error, or end-of-sequence */ + if (PyErr_Occurred()) { + Py_DECREF(result); + result = NULL; + } + break; + } + /* It's tempting to use PyNumber_InPlaceAdd instead of + PyNumber_Add here, to avoid quadratic running time + when doing 'sum(list_of_lists, [])'. However, this + would produce a change in behaviour: a snippet like + + empty = [] + sum([[x] for x in range(10)], empty) + + would change the value of empty. */ + temp = PyNumber_Add(result, item); + Py_DECREF(result); + Py_DECREF(item); + result = temp; + if (result == NULL) + break; + } + Py_DECREF(iter); + return result; } PyDoc_STRVAR(sum_doc, @@ -2005,17 +2005,17 @@ static PyObject * builtin_isinstance(PyObject *self, PyObject *args) { - PyObject *inst; - PyObject *cls; - int retval; - - if (!PyArg_UnpackTuple(args, "isinstance", 2, 2, &inst, &cls)) - return NULL; - - retval = PyObject_IsInstance(inst, cls); - if (retval < 0) - return NULL; - return PyBool_FromLong(retval); + PyObject *inst; + PyObject *cls; + int retval; + + if (!PyArg_UnpackTuple(args, "isinstance", 2, 2, &inst, &cls)) + return NULL; + + retval = PyObject_IsInstance(inst, cls); + if (retval < 0) + return NULL; + return PyBool_FromLong(retval); } PyDoc_STRVAR(isinstance_doc, @@ -2030,17 +2030,17 @@ static PyObject * builtin_issubclass(PyObject *self, PyObject *args) { - PyObject *derived; - PyObject *cls; - int retval; - - if (!PyArg_UnpackTuple(args, "issubclass", 2, 2, &derived, &cls)) - return NULL; - - retval = PyObject_IsSubclass(derived, cls); - if (retval < 0) - return NULL; - return PyBool_FromLong(retval); + PyObject *derived; + PyObject *cls; + int retval; + + if (!PyArg_UnpackTuple(args, "issubclass", 2, 2, &derived, &cls)) + return NULL; + + retval = PyObject_IsSubclass(derived, cls); + if (retval < 0) + return NULL; + return PyBool_FromLong(retval); } PyDoc_STRVAR(issubclass_doc, @@ -2052,127 +2052,127 @@ typedef struct { - PyObject_HEAD - Py_ssize_t tuplesize; - PyObject *ittuple; /* tuple of iterators */ - PyObject *result; + PyObject_HEAD + Py_ssize_t tuplesize; + PyObject *ittuple; /* tuple of iterators */ + PyObject *result; } zipobject; static PyObject * zip_new(PyTypeObject *type, PyObject *args, PyObject *kwds) { - zipobject *lz; - Py_ssize_t i; - PyObject *ittuple; /* tuple of iterators */ - PyObject *result; - Py_ssize_t tuplesize = PySequence_Length(args); - - if (type == &PyZip_Type && !_PyArg_NoKeywords("zip()", kwds)) - return NULL; - - /* args must be a tuple */ - assert(PyTuple_Check(args)); - - /* obtain iterators */ - ittuple = PyTuple_New(tuplesize); - if (ittuple == NULL) - return NULL; - for (i=0; i < tuplesize; ++i) { - PyObject *item = PyTuple_GET_ITEM(args, i); - PyObject *it = PyObject_GetIter(item); - if (it == NULL) { - if (PyErr_ExceptionMatches(PyExc_TypeError)) - PyErr_Format(PyExc_TypeError, - "zip argument #%zd must support iteration", - i+1); - Py_DECREF(ittuple); - return NULL; - } - PyTuple_SET_ITEM(ittuple, i, it); - } - - /* create a result holder */ - result = PyTuple_New(tuplesize); - if (result == NULL) { - Py_DECREF(ittuple); - return NULL; - } - for (i=0 ; i < tuplesize ; i++) { - Py_INCREF(Py_None); - PyTuple_SET_ITEM(result, i, Py_None); - } - - /* create zipobject structure */ - lz = (zipobject *)type->tp_alloc(type, 0); - if (lz == NULL) { - Py_DECREF(ittuple); - Py_DECREF(result); - return NULL; - } - lz->ittuple = ittuple; - lz->tuplesize = tuplesize; - lz->result = result; + zipobject *lz; + Py_ssize_t i; + PyObject *ittuple; /* tuple of iterators */ + PyObject *result; + Py_ssize_t tuplesize = PySequence_Length(args); + + if (type == &PyZip_Type && !_PyArg_NoKeywords("zip()", kwds)) + return NULL; + + /* args must be a tuple */ + assert(PyTuple_Check(args)); - return (PyObject *)lz; + /* obtain iterators */ + ittuple = PyTuple_New(tuplesize); + if (ittuple == NULL) + return NULL; + for (i=0; i < tuplesize; ++i) { + PyObject *item = PyTuple_GET_ITEM(args, i); + PyObject *it = PyObject_GetIter(item); + if (it == NULL) { + if (PyErr_ExceptionMatches(PyExc_TypeError)) + PyErr_Format(PyExc_TypeError, + "zip argument #%zd must support iteration", + i+1); + Py_DECREF(ittuple); + return NULL; + } + PyTuple_SET_ITEM(ittuple, i, it); + } + + /* create a result holder */ + result = PyTuple_New(tuplesize); + if (result == NULL) { + Py_DECREF(ittuple); + return NULL; + } + for (i=0 ; i < tuplesize ; i++) { + Py_INCREF(Py_None); + PyTuple_SET_ITEM(result, i, Py_None); + } + + /* create zipobject structure */ + lz = (zipobject *)type->tp_alloc(type, 0); + if (lz == NULL) { + Py_DECREF(ittuple); + Py_DECREF(result); + return NULL; + } + lz->ittuple = ittuple; + lz->tuplesize = tuplesize; + lz->result = result; + + return (PyObject *)lz; } static void zip_dealloc(zipobject *lz) { - PyObject_GC_UnTrack(lz); - Py_XDECREF(lz->ittuple); - Py_XDECREF(lz->result); - Py_TYPE(lz)->tp_free(lz); + PyObject_GC_UnTrack(lz); + Py_XDECREF(lz->ittuple); + Py_XDECREF(lz->result); + Py_TYPE(lz)->tp_free(lz); } static int zip_traverse(zipobject *lz, visitproc visit, void *arg) { - Py_VISIT(lz->ittuple); - Py_VISIT(lz->result); - return 0; + Py_VISIT(lz->ittuple); + Py_VISIT(lz->result); + return 0; } static PyObject * zip_next(zipobject *lz) { - Py_ssize_t i; - Py_ssize_t tuplesize = lz->tuplesize; - PyObject *result = lz->result; - PyObject *it; - PyObject *item; - PyObject *olditem; - - if (tuplesize == 0) - return NULL; - if (Py_REFCNT(result) == 1) { - Py_INCREF(result); - for (i=0 ; i < tuplesize ; i++) { - it = PyTuple_GET_ITEM(lz->ittuple, i); - item = (*Py_TYPE(it)->tp_iternext)(it); - if (item == NULL) { - Py_DECREF(result); - return NULL; - } - olditem = PyTuple_GET_ITEM(result, i); - PyTuple_SET_ITEM(result, i, item); - Py_DECREF(olditem); - } - } else { - result = PyTuple_New(tuplesize); - if (result == NULL) - return NULL; - for (i=0 ; i < tuplesize ; i++) { - it = PyTuple_GET_ITEM(lz->ittuple, i); - item = (*Py_TYPE(it)->tp_iternext)(it); - if (item == NULL) { - Py_DECREF(result); - return NULL; - } - PyTuple_SET_ITEM(result, i, item); - } - } - return result; + Py_ssize_t i; + Py_ssize_t tuplesize = lz->tuplesize; + PyObject *result = lz->result; + PyObject *it; + PyObject *item; + PyObject *olditem; + + if (tuplesize == 0) + return NULL; + if (Py_REFCNT(result) == 1) { + Py_INCREF(result); + for (i=0 ; i < tuplesize ; i++) { + it = PyTuple_GET_ITEM(lz->ittuple, i); + item = (*Py_TYPE(it)->tp_iternext)(it); + if (item == NULL) { + Py_DECREF(result); + return NULL; + } + olditem = PyTuple_GET_ITEM(result, i); + PyTuple_SET_ITEM(result, i, item); + Py_DECREF(olditem); + } + } else { + result = PyTuple_New(tuplesize); + if (result == NULL) + return NULL; + for (i=0 ; i < tuplesize ; i++) { + it = PyTuple_GET_ITEM(lz->ittuple, i); + item = (*Py_TYPE(it)->tp_iternext)(it); + if (item == NULL) { + Py_DECREF(result); + return NULL; + } + PyTuple_SET_ITEM(result, i, item); + } + } + return result; } PyDoc_STRVAR(zip_doc, @@ -2184,93 +2184,93 @@ is exhausted and then it raises StopIteration."); PyTypeObject PyZip_Type = { - PyVarObject_HEAD_INIT(&PyType_Type, 0) - "zip", /* tp_name */ - sizeof(zipobject), /* tp_basicsize */ - 0, /* tp_itemsize */ - /* methods */ - (destructor)zip_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 | - Py_TPFLAGS_BASETYPE, /* tp_flags */ - zip_doc, /* tp_doc */ - (traverseproc)zip_traverse, /* tp_traverse */ - 0, /* tp_clear */ - 0, /* tp_richcompare */ - 0, /* tp_weaklistoffset */ - PyObject_SelfIter, /* tp_iter */ - (iternextfunc)zip_next, /* tp_iternext */ - 0, /* tp_methods */ - 0, /* tp_members */ - 0, /* tp_getset */ - 0, /* tp_base */ - 0, /* tp_dict */ - 0, /* tp_descr_get */ - 0, /* tp_descr_set */ - 0, /* tp_dictoffset */ - 0, /* tp_init */ - PyType_GenericAlloc, /* tp_alloc */ - zip_new, /* tp_new */ - PyObject_GC_Del, /* tp_free */ + PyVarObject_HEAD_INIT(&PyType_Type, 0) + "zip", /* tp_name */ + sizeof(zipobject), /* tp_basicsize */ + 0, /* tp_itemsize */ + /* methods */ + (destructor)zip_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 | + Py_TPFLAGS_BASETYPE, /* tp_flags */ + zip_doc, /* tp_doc */ + (traverseproc)zip_traverse, /* tp_traverse */ + 0, /* tp_clear */ + 0, /* tp_richcompare */ + 0, /* tp_weaklistoffset */ + PyObject_SelfIter, /* tp_iter */ + (iternextfunc)zip_next, /* tp_iternext */ + 0, /* tp_methods */ + 0, /* tp_members */ + 0, /* tp_getset */ + 0, /* tp_base */ + 0, /* tp_dict */ + 0, /* tp_descr_get */ + 0, /* tp_descr_set */ + 0, /* tp_dictoffset */ + 0, /* tp_init */ + PyType_GenericAlloc, /* tp_alloc */ + zip_new, /* tp_new */ + PyObject_GC_Del, /* tp_free */ }; static PyMethodDef builtin_methods[] = { - {"__build_class__", (PyCFunction)builtin___build_class__, - METH_VARARGS | METH_KEYWORDS, build_class_doc}, - {"__import__", (PyCFunction)builtin___import__, METH_VARARGS | METH_KEYWORDS, import_doc}, - {"abs", builtin_abs, METH_O, abs_doc}, - {"all", builtin_all, METH_O, all_doc}, - {"any", builtin_any, METH_O, any_doc}, - {"ascii", builtin_ascii, METH_O, ascii_doc}, - {"bin", builtin_bin, METH_O, bin_doc}, - {"chr", builtin_chr, METH_VARARGS, chr_doc}, - {"compile", (PyCFunction)builtin_compile, METH_VARARGS | METH_KEYWORDS, compile_doc}, - {"delattr", builtin_delattr, METH_VARARGS, delattr_doc}, - {"dir", builtin_dir, METH_VARARGS, dir_doc}, - {"divmod", builtin_divmod, METH_VARARGS, divmod_doc}, - {"eval", builtin_eval, METH_VARARGS, eval_doc}, - {"exec", builtin_exec, METH_VARARGS, exec_doc}, - {"format", builtin_format, METH_VARARGS, format_doc}, - {"getattr", builtin_getattr, METH_VARARGS, getattr_doc}, - {"globals", (PyCFunction)builtin_globals, METH_NOARGS, globals_doc}, - {"hasattr", builtin_hasattr, METH_VARARGS, hasattr_doc}, - {"hash", builtin_hash, METH_O, hash_doc}, - {"hex", builtin_hex, METH_O, hex_doc}, - {"id", builtin_id, METH_O, id_doc}, - {"input", builtin_input, METH_VARARGS, input_doc}, - {"isinstance", builtin_isinstance, METH_VARARGS, isinstance_doc}, - {"issubclass", builtin_issubclass, METH_VARARGS, issubclass_doc}, - {"iter", builtin_iter, METH_VARARGS, iter_doc}, - {"len", builtin_len, METH_O, len_doc}, - {"locals", (PyCFunction)builtin_locals, METH_NOARGS, locals_doc}, - {"max", (PyCFunction)builtin_max, METH_VARARGS | METH_KEYWORDS, max_doc}, - {"min", (PyCFunction)builtin_min, METH_VARARGS | METH_KEYWORDS, min_doc}, - {"next", (PyCFunction)builtin_next, METH_VARARGS, next_doc}, - {"oct", builtin_oct, METH_O, oct_doc}, - {"ord", builtin_ord, METH_O, ord_doc}, - {"pow", builtin_pow, METH_VARARGS, pow_doc}, - {"print", (PyCFunction)builtin_print, METH_VARARGS | METH_KEYWORDS, print_doc}, - {"repr", builtin_repr, METH_O, repr_doc}, - {"round", (PyCFunction)builtin_round, METH_VARARGS | METH_KEYWORDS, round_doc}, - {"setattr", builtin_setattr, METH_VARARGS, setattr_doc}, - {"sorted", (PyCFunction)builtin_sorted, METH_VARARGS | METH_KEYWORDS, sorted_doc}, - {"sum", builtin_sum, METH_VARARGS, sum_doc}, - {"vars", builtin_vars, METH_VARARGS, vars_doc}, - {NULL, NULL}, + {"__build_class__", (PyCFunction)builtin___build_class__, + METH_VARARGS | METH_KEYWORDS, build_class_doc}, + {"__import__", (PyCFunction)builtin___import__, METH_VARARGS | METH_KEYWORDS, import_doc}, + {"abs", builtin_abs, METH_O, abs_doc}, + {"all", builtin_all, METH_O, all_doc}, + {"any", builtin_any, METH_O, any_doc}, + {"ascii", builtin_ascii, METH_O, ascii_doc}, + {"bin", builtin_bin, METH_O, bin_doc}, + {"chr", builtin_chr, METH_VARARGS, chr_doc}, + {"compile", (PyCFunction)builtin_compile, METH_VARARGS | METH_KEYWORDS, compile_doc}, + {"delattr", builtin_delattr, METH_VARARGS, delattr_doc}, + {"dir", builtin_dir, METH_VARARGS, dir_doc}, + {"divmod", builtin_divmod, METH_VARARGS, divmod_doc}, + {"eval", builtin_eval, METH_VARARGS, eval_doc}, + {"exec", builtin_exec, METH_VARARGS, exec_doc}, + {"format", builtin_format, METH_VARARGS, format_doc}, + {"getattr", builtin_getattr, METH_VARARGS, getattr_doc}, + {"globals", (PyCFunction)builtin_globals, METH_NOARGS, globals_doc}, + {"hasattr", builtin_hasattr, METH_VARARGS, hasattr_doc}, + {"hash", builtin_hash, METH_O, hash_doc}, + {"hex", builtin_hex, METH_O, hex_doc}, + {"id", builtin_id, METH_O, id_doc}, + {"input", builtin_input, METH_VARARGS, input_doc}, + {"isinstance", builtin_isinstance, METH_VARARGS, isinstance_doc}, + {"issubclass", builtin_issubclass, METH_VARARGS, issubclass_doc}, + {"iter", builtin_iter, METH_VARARGS, iter_doc}, + {"len", builtin_len, METH_O, len_doc}, + {"locals", (PyCFunction)builtin_locals, METH_NOARGS, locals_doc}, + {"max", (PyCFunction)builtin_max, METH_VARARGS | METH_KEYWORDS, max_doc}, + {"min", (PyCFunction)builtin_min, METH_VARARGS | METH_KEYWORDS, min_doc}, + {"next", (PyCFunction)builtin_next, METH_VARARGS, next_doc}, + {"oct", builtin_oct, METH_O, oct_doc}, + {"ord", builtin_ord, METH_O, ord_doc}, + {"pow", builtin_pow, METH_VARARGS, pow_doc}, + {"print", (PyCFunction)builtin_print, METH_VARARGS | METH_KEYWORDS, print_doc}, + {"repr", builtin_repr, METH_O, repr_doc}, + {"round", (PyCFunction)builtin_round, METH_VARARGS | METH_KEYWORDS, round_doc}, + {"setattr", builtin_setattr, METH_VARARGS, setattr_doc}, + {"sorted", (PyCFunction)builtin_sorted, METH_VARARGS | METH_KEYWORDS, sorted_doc}, + {"sum", builtin_sum, METH_VARARGS, sum_doc}, + {"vars", builtin_vars, METH_VARARGS, vars_doc}, + {NULL, NULL}, }; PyDoc_STRVAR(builtin_doc, @@ -2279,83 +2279,83 @@ Noteworthy: None is the `nil' object; Ellipsis represents `...' in slices."); static struct PyModuleDef builtinsmodule = { - PyModuleDef_HEAD_INIT, - "builtins", - builtin_doc, - -1, /* multiple "initialization" just copies the module dict. */ - builtin_methods, - NULL, - NULL, - NULL, - NULL + PyModuleDef_HEAD_INIT, + "builtins", + builtin_doc, + -1, /* multiple "initialization" just copies the module dict. */ + builtin_methods, + NULL, + NULL, + NULL, + NULL }; PyObject * _PyBuiltin_Init(void) { - PyObject *mod, *dict, *debug; - mod = PyModule_Create(&builtinsmodule); - if (mod == NULL) - return NULL; - dict = PyModule_GetDict(mod); + PyObject *mod, *dict, *debug; + mod = PyModule_Create(&builtinsmodule); + if (mod == NULL) + return NULL; + dict = PyModule_GetDict(mod); #ifdef Py_TRACE_REFS - /* "builtins" exposes a number of statically allocated objects - * that, before this code was added in 2.3, never showed up in - * the list of "all objects" maintained by Py_TRACE_REFS. As a - * result, programs leaking references to None and False (etc) - * couldn't be diagnosed by examining sys.getobjects(0). - */ + /* "builtins" exposes a number of statically allocated objects + * that, before this code was added in 2.3, never showed up in + * the list of "all objects" maintained by Py_TRACE_REFS. As a + * result, programs leaking references to None and False (etc) + * couldn't be diagnosed by examining sys.getobjects(0). + */ #define ADD_TO_ALL(OBJECT) _Py_AddToAllObjects((PyObject *)(OBJECT), 0) #else #define ADD_TO_ALL(OBJECT) (void)0 #endif #define SETBUILTIN(NAME, OBJECT) \ - if (PyDict_SetItemString(dict, NAME, (PyObject *)OBJECT) < 0) \ - return NULL; \ - ADD_TO_ALL(OBJECT) - - SETBUILTIN("None", Py_None); - SETBUILTIN("Ellipsis", Py_Ellipsis); - SETBUILTIN("NotImplemented", Py_NotImplemented); - SETBUILTIN("False", Py_False); - SETBUILTIN("True", Py_True); - SETBUILTIN("bool", &PyBool_Type); - SETBUILTIN("memoryview", &PyMemoryView_Type); - SETBUILTIN("bytearray", &PyByteArray_Type); - SETBUILTIN("bytes", &PyBytes_Type); - SETBUILTIN("classmethod", &PyClassMethod_Type); - SETBUILTIN("complex", &PyComplex_Type); - SETBUILTIN("dict", &PyDict_Type); - SETBUILTIN("enumerate", &PyEnum_Type); - SETBUILTIN("filter", &PyFilter_Type); - SETBUILTIN("float", &PyFloat_Type); - SETBUILTIN("frozenset", &PyFrozenSet_Type); - SETBUILTIN("property", &PyProperty_Type); - SETBUILTIN("int", &PyLong_Type); - SETBUILTIN("list", &PyList_Type); - SETBUILTIN("map", &PyMap_Type); - SETBUILTIN("object", &PyBaseObject_Type); - SETBUILTIN("range", &PyRange_Type); - SETBUILTIN("reversed", &PyReversed_Type); - SETBUILTIN("set", &PySet_Type); - SETBUILTIN("slice", &PySlice_Type); - SETBUILTIN("staticmethod", &PyStaticMethod_Type); - SETBUILTIN("str", &PyUnicode_Type); - SETBUILTIN("super", &PySuper_Type); - SETBUILTIN("tuple", &PyTuple_Type); - SETBUILTIN("type", &PyType_Type); - SETBUILTIN("zip", &PyZip_Type); - debug = PyBool_FromLong(Py_OptimizeFlag == 0); - if (PyDict_SetItemString(dict, "__debug__", debug) < 0) { - Py_XDECREF(debug); - return NULL; - } - Py_XDECREF(debug); + if (PyDict_SetItemString(dict, NAME, (PyObject *)OBJECT) < 0) \ + return NULL; \ + ADD_TO_ALL(OBJECT) + + SETBUILTIN("None", Py_None); + SETBUILTIN("Ellipsis", Py_Ellipsis); + SETBUILTIN("NotImplemented", Py_NotImplemented); + SETBUILTIN("False", Py_False); + SETBUILTIN("True", Py_True); + SETBUILTIN("bool", &PyBool_Type); + SETBUILTIN("memoryview", &PyMemoryView_Type); + SETBUILTIN("bytearray", &PyByteArray_Type); + SETBUILTIN("bytes", &PyBytes_Type); + SETBUILTIN("classmethod", &PyClassMethod_Type); + SETBUILTIN("complex", &PyComplex_Type); + SETBUILTIN("dict", &PyDict_Type); + SETBUILTIN("enumerate", &PyEnum_Type); + SETBUILTIN("filter", &PyFilter_Type); + SETBUILTIN("float", &PyFloat_Type); + SETBUILTIN("frozenset", &PyFrozenSet_Type); + SETBUILTIN("property", &PyProperty_Type); + SETBUILTIN("int", &PyLong_Type); + SETBUILTIN("list", &PyList_Type); + SETBUILTIN("map", &PyMap_Type); + SETBUILTIN("object", &PyBaseObject_Type); + SETBUILTIN("range", &PyRange_Type); + SETBUILTIN("reversed", &PyReversed_Type); + SETBUILTIN("set", &PySet_Type); + SETBUILTIN("slice", &PySlice_Type); + SETBUILTIN("staticmethod", &PyStaticMethod_Type); + SETBUILTIN("str", &PyUnicode_Type); + SETBUILTIN("super", &PySuper_Type); + SETBUILTIN("tuple", &PyTuple_Type); + SETBUILTIN("type", &PyType_Type); + SETBUILTIN("zip", &PyZip_Type); + debug = PyBool_FromLong(Py_OptimizeFlag == 0); + if (PyDict_SetItemString(dict, "__debug__", debug) < 0) { + Py_XDECREF(debug); + return NULL; + } + Py_XDECREF(debug); - return mod; + return mod; #undef ADD_TO_ALL #undef SETBUILTIN } Modified: python/branches/py3k-jit/Python/ceval.c ============================================================================== --- python/branches/py3k-jit/Python/ceval.c (original) +++ python/branches/py3k-jit/Python/ceval.c Mon May 10 23:55:43 2010 @@ -28,27 +28,27 @@ typedef unsigned long long uint64; #if defined(__ppc__) /* <- Don't know if this is the correct symbol; this - section should work for GCC on any PowerPC - platform, irrespective of OS. - POWER? Who knows :-) */ + section should work for GCC on any PowerPC + platform, irrespective of OS. + POWER? Who knows :-) */ #define READ_TIMESTAMP(var) ppc_getcounter(&var) static void ppc_getcounter(uint64 *v) { - register unsigned long tbu, tb, tbu2; + register unsigned long tbu, tb, tbu2; loop: - asm volatile ("mftbu %0" : "=r" (tbu) ); - asm volatile ("mftb %0" : "=r" (tb) ); - asm volatile ("mftbu %0" : "=r" (tbu2)); - if (__builtin_expect(tbu != tbu2, 0)) goto loop; - - /* The slightly peculiar way of writing the next lines is - compiled better by GCC than any other way I tried. */ - ((long*)(v))[0] = tbu; - ((long*)(v))[1] = tb; + asm volatile ("mftbu %0" : "=r" (tbu) ); + asm volatile ("mftb %0" : "=r" (tb) ); + asm volatile ("mftbu %0" : "=r" (tbu2)); + if (__builtin_expect(tbu != tbu2, 0)) goto loop; + + /* The slightly peculiar way of writing the next lines is + compiled better by GCC than any other way I tried. */ + ((long*)(v))[0] = tbu; + ((long*)(v))[1] = tb; } #elif defined(__i386__) @@ -77,17 +77,17 @@ #endif void dump_tsc(int opcode, int ticked, uint64 inst0, uint64 inst1, - uint64 loop0, uint64 loop1, uint64 intr0, uint64 intr1) + uint64 loop0, uint64 loop1, uint64 intr0, uint64 intr1) { - uint64 intr, inst, loop; - PyThreadState *tstate = PyThreadState_Get(); - if (!tstate->interp->tscdump) - return; - intr = intr1 - intr0; - inst = inst1 - inst0 - intr; - loop = loop1 - loop0 - intr; - fprintf(stderr, "opcode=%03d t=%d inst=%06lld loop=%06lld\n", - opcode, ticked, inst, loop); + uint64 intr, inst, loop; + PyThreadState *tstate = PyThreadState_Get(); + if (!tstate->interp->tscdump) + return; + intr = intr1 - intr0; + inst = inst1 - inst0 - intr; + loop = loop1 - loop0 - intr; + fprintf(stderr, "opcode=%03d t=%d inst=%06lld loop=%06lld\n", + opcode, ticked, inst, loop); } #endif @@ -97,8 +97,8 @@ #ifdef Py_DEBUG /* For debugging the interpreter: */ -#define LLTRACE 1 /* Low-level trace feature */ -#define CHECKEXC 1 /* Double-check exception checking */ +#define LLTRACE 1 /* Low-level trace feature */ +#define CHECKEXC 1 /* Double-check exception checking */ #endif typedef PyObject *(*callproc)(PyObject *, PyObject *, PyObject *); @@ -113,7 +113,7 @@ static PyObject * do_call(PyObject *, PyObject ***, int, int); static PyObject * ext_do_call(PyObject *, PyObject ***, int, int, int); static PyObject * update_keyword_args(PyObject *, int, PyObject ***, - PyObject *); + PyObject *); static PyObject * update_star_args(int, int, PyObject *, PyObject ***); static PyObject * load_args(PyObject ***, int); #define CALL_FLAG_VAR 1 @@ -124,12 +124,12 @@ static int prtrace(PyObject *, char *); #endif static int call_trace(Py_tracefunc, PyObject *, PyFrameObject *, - int, PyObject *); + int, PyObject *); static int call_trace_protected(Py_tracefunc, PyObject *, - PyFrameObject *, int, PyObject *); + PyFrameObject *, int, PyObject *); static void call_exc_trace(Py_tracefunc, PyObject *, PyFrameObject *); static int maybe_call_line_trace(Py_tracefunc, PyObject *, - PyFrameObject *, int *, int *, int *); + PyFrameObject *, int *, int *, int *); static PyObject * cmp_outcome(int, PyObject *, PyObject *); static PyObject * import_from(PyObject *, PyObject *); @@ -140,14 +140,14 @@ static PyObject * special_lookup(PyObject *, char *, PyObject **); #define NAME_ERROR_MSG \ - "name '%.200s' is not defined" + "name '%.200s' is not defined" #define GLOBAL_NAME_ERROR_MSG \ - "global name '%.200s' is not defined" + "global name '%.200s' is not defined" #define UNBOUNDLOCAL_ERROR_MSG \ - "local variable '%.200s' referenced before assignment" + "local variable '%.200s' referenced before assignment" #define UNBOUNDFREE_ERROR_MSG \ - "free variable '%.200s' referenced before assignment" \ - " in enclosing scope" + "free variable '%.200s' referenced before assignment" \ + " in enclosing scope" /* Dynamic execution profile */ #ifdef DYNAMIC_EXECUTION_PROFILE @@ -199,10 +199,10 @@ PyObject * PyEval_GetCallStats(PyObject *self) { - return Py_BuildValue("iiiiiiiiiii", - pcall[0], pcall[1], pcall[2], pcall[3], - pcall[4], pcall[5], pcall[6], pcall[7], - pcall[8], pcall[9], pcall[10]); + return Py_BuildValue("iiiiiiiiiii", + pcall[0], pcall[1], pcall[2], pcall[3], + pcall[4], pcall[5], pcall[6], pcall[7], + pcall[8], pcall[9], pcall[10]); } #else #define PCALL(O) @@ -210,8 +210,8 @@ PyObject * PyEval_GetCallStats(PyObject *self) { - Py_INCREF(Py_None); - return Py_None; + Py_INCREF(Py_None); + return Py_None; } #endif @@ -220,45 +220,45 @@ 1. We believe this is all right because the eval loop will release the GIL eventually anyway. */ #define COMPUTE_EVAL_BREAKER() \ - _Py_atomic_store_relaxed( \ - &eval_breaker, \ - _Py_atomic_load_relaxed(&gil_drop_request) | \ - _Py_atomic_load_relaxed(&pendingcalls_to_do) | \ - pending_async_exc) + _Py_atomic_store_relaxed( \ + &eval_breaker, \ + _Py_atomic_load_relaxed(&gil_drop_request) | \ + _Py_atomic_load_relaxed(&pendingcalls_to_do) | \ + pending_async_exc) #define SET_GIL_DROP_REQUEST() \ - do { \ - _Py_atomic_store_relaxed(&gil_drop_request, 1); \ - _Py_atomic_store_relaxed(&eval_breaker, 1); \ - } while (0) + do { \ + _Py_atomic_store_relaxed(&gil_drop_request, 1); \ + _Py_atomic_store_relaxed(&eval_breaker, 1); \ + } while (0) #define RESET_GIL_DROP_REQUEST() \ - do { \ - _Py_atomic_store_relaxed(&gil_drop_request, 0); \ - COMPUTE_EVAL_BREAKER(); \ - } while (0) + do { \ + _Py_atomic_store_relaxed(&gil_drop_request, 0); \ + COMPUTE_EVAL_BREAKER(); \ + } while (0) /* Pending calls are only modified under pending_lock */ #define SIGNAL_PENDING_CALLS() \ - do { \ - _Py_atomic_store_relaxed(&pendingcalls_to_do, 1); \ - _Py_atomic_store_relaxed(&eval_breaker, 1); \ - } while (0) + do { \ + _Py_atomic_store_relaxed(&pendingcalls_to_do, 1); \ + _Py_atomic_store_relaxed(&eval_breaker, 1); \ + } while (0) #define UNSIGNAL_PENDING_CALLS() \ - do { \ - _Py_atomic_store_relaxed(&pendingcalls_to_do, 0); \ - COMPUTE_EVAL_BREAKER(); \ - } while (0) + do { \ + _Py_atomic_store_relaxed(&pendingcalls_to_do, 0); \ + COMPUTE_EVAL_BREAKER(); \ + } while (0) #define SIGNAL_ASYNC_EXC() \ - do { \ - pending_async_exc = 1; \ - _Py_atomic_store_relaxed(&eval_breaker, 1); \ - } while (0) + do { \ + pending_async_exc = 1; \ + _Py_atomic_store_relaxed(&eval_breaker, 1); \ + } while (0) #define UNSIGNAL_ASYNC_EXC() \ - do { pending_async_exc = 0; COMPUTE_EVAL_BREAKER(); } while (0) + do { pending_async_exc = 0; COMPUTE_EVAL_BREAKER(); } while (0) #ifdef WITH_THREAD @@ -286,62 +286,62 @@ int PyEval_ThreadsInitialized(void) { - return gil_created(); + return gil_created(); } void PyEval_InitThreads(void) { - if (gil_created()) - return; - create_gil(); - take_gil(PyThreadState_GET()); - main_thread = PyThread_get_thread_ident(); - if (!pending_lock) - pending_lock = PyThread_allocate_lock(); + if (gil_created()) + return; + create_gil(); + take_gil(PyThreadState_GET()); + main_thread = PyThread_get_thread_ident(); + if (!pending_lock) + pending_lock = PyThread_allocate_lock(); } void PyEval_AcquireLock(void) { - PyThreadState *tstate = PyThreadState_GET(); - if (tstate == NULL) - Py_FatalError("PyEval_AcquireLock: current thread state is NULL"); - take_gil(tstate); + PyThreadState *tstate = PyThreadState_GET(); + if (tstate == NULL) + Py_FatalError("PyEval_AcquireLock: current thread state is NULL"); + take_gil(tstate); } void PyEval_ReleaseLock(void) { - /* This function must succeed when the current thread state is NULL. - We therefore avoid PyThreadState_GET() which dumps a fatal error - in debug mode. - */ - drop_gil((PyThreadState*)_Py_atomic_load_relaxed( - &_PyThreadState_Current)); + /* This function must succeed when the current thread state is NULL. + We therefore avoid PyThreadState_GET() which dumps a fatal error + in debug mode. + */ + drop_gil((PyThreadState*)_Py_atomic_load_relaxed( + &_PyThreadState_Current)); } void PyEval_AcquireThread(PyThreadState *tstate) { - if (tstate == NULL) - Py_FatalError("PyEval_AcquireThread: NULL new thread state"); - /* Check someone has called PyEval_InitThreads() to create the lock */ - assert(gil_created()); - take_gil(tstate); - if (PyThreadState_Swap(tstate) != NULL) - Py_FatalError( - "PyEval_AcquireThread: non-NULL old thread state"); + if (tstate == NULL) + Py_FatalError("PyEval_AcquireThread: NULL new thread state"); + /* Check someone has called PyEval_InitThreads() to create the lock */ + assert(gil_created()); + take_gil(tstate); + if (PyThreadState_Swap(tstate) != NULL) + Py_FatalError( + "PyEval_AcquireThread: non-NULL old thread state"); } void PyEval_ReleaseThread(PyThreadState *tstate) { - if (tstate == NULL) - Py_FatalError("PyEval_ReleaseThread: NULL thread state"); - if (PyThreadState_Swap(NULL) != tstate) - Py_FatalError("PyEval_ReleaseThread: wrong thread state"); - drop_gil(tstate); + if (tstate == NULL) + Py_FatalError("PyEval_ReleaseThread: NULL thread state"); + if (PyThreadState_Swap(NULL) != tstate) + Py_FatalError("PyEval_ReleaseThread: wrong thread state"); + drop_gil(tstate); } /* This function is called from PyOS_AfterFork to ensure that newly @@ -352,36 +352,36 @@ void PyEval_ReInitThreads(void) { - PyObject *threading, *result; - PyThreadState *tstate = PyThreadState_GET(); + PyObject *threading, *result; + PyThreadState *tstate = PyThreadState_GET(); - if (!gil_created()) - return; - /*XXX Can't use PyThread_free_lock here because it does too - much error-checking. Doing this cleanly would require - adding a new function to each thread_*.h. Instead, just - create a new lock and waste a little bit of memory */ - recreate_gil(); - pending_lock = PyThread_allocate_lock(); - take_gil(tstate); - main_thread = PyThread_get_thread_ident(); - - /* Update the threading module with the new state. - */ - tstate = PyThreadState_GET(); - threading = PyMapping_GetItemString(tstate->interp->modules, - "threading"); - if (threading == NULL) { - /* threading not imported */ - PyErr_Clear(); - return; - } - result = PyObject_CallMethod(threading, "_after_fork", NULL); - if (result == NULL) - PyErr_WriteUnraisable(threading); - else - Py_DECREF(result); - Py_DECREF(threading); + if (!gil_created()) + return; + /*XXX Can't use PyThread_free_lock here because it does too + much error-checking. Doing this cleanly would require + adding a new function to each thread_*.h. Instead, just + create a new lock and waste a little bit of memory */ + recreate_gil(); + pending_lock = PyThread_allocate_lock(); + take_gil(tstate); + main_thread = PyThread_get_thread_ident(); + + /* Update the threading module with the new state. + */ + tstate = PyThreadState_GET(); + threading = PyMapping_GetItemString(tstate->interp->modules, + "threading"); + if (threading == NULL) { + /* threading not imported */ + PyErr_Clear(); + return; + } + result = PyObject_CallMethod(threading, "_after_fork", NULL); + if (result == NULL) + PyErr_WriteUnraisable(threading); + else + Py_DECREF(result); + Py_DECREF(threading); } #else @@ -396,7 +396,7 @@ void _PyEval_SignalAsyncExc(void) { - SIGNAL_ASYNC_EXC(); + SIGNAL_ASYNC_EXC(); } /* Functions save_thread and restore_thread are always defined so @@ -406,29 +406,29 @@ PyThreadState * PyEval_SaveThread(void) { - PyThreadState *tstate = PyThreadState_Swap(NULL); - if (tstate == NULL) - Py_FatalError("PyEval_SaveThread: NULL tstate"); + PyThreadState *tstate = PyThreadState_Swap(NULL); + if (tstate == NULL) + Py_FatalError("PyEval_SaveThread: NULL tstate"); #ifdef WITH_THREAD - if (gil_created()) - drop_gil(tstate); + if (gil_created()) + drop_gil(tstate); #endif - return tstate; + return tstate; } void PyEval_RestoreThread(PyThreadState *tstate) { - if (tstate == NULL) - Py_FatalError("PyEval_RestoreThread: NULL tstate"); + if (tstate == NULL) + Py_FatalError("PyEval_RestoreThread: NULL tstate"); #ifdef WITH_THREAD - if (gil_created()) { - int err = errno; - take_gil(tstate); - errno = err; - } + if (gil_created()) { + int err = errno; + take_gil(tstate); + errno = err; + } #endif - PyThreadState_Swap(tstate); + PyThreadState_Swap(tstate); } @@ -465,8 +465,8 @@ #define NPENDINGCALLS 32 static struct { - int (*func)(void *); - void *arg; + int (*func)(void *); + void *arg; } pendingcalls[NPENDINGCALLS]; static int pendingfirst = 0; static int pendinglast = 0; @@ -475,95 +475,95 @@ int Py_AddPendingCall(int (*func)(void *), void *arg) { - int i, j, result=0; - PyThread_type_lock lock = pending_lock; - - /* try a few times for the lock. Since this mechanism is used - * for signal handling (on the main thread), there is a (slim) - * chance that a signal is delivered on the same thread while we - * hold the lock during the Py_MakePendingCalls() function. - * This avoids a deadlock in that case. - * Note that signals can be delivered on any thread. In particular, - * on Windows, a SIGINT is delivered on a system-created worker - * thread. - * We also check for lock being NULL, in the unlikely case that - * this function is called before any bytecode evaluation takes place. - */ - if (lock != NULL) { - for (i = 0; i<100; i++) { - if (PyThread_acquire_lock(lock, NOWAIT_LOCK)) - break; - } - if (i == 100) - return -1; - } - - i = pendinglast; - j = (i + 1) % NPENDINGCALLS; - if (j == pendingfirst) { - result = -1; /* Queue full */ - } else { - pendingcalls[i].func = func; - pendingcalls[i].arg = arg; - pendinglast = j; - } - /* signal main loop */ - SIGNAL_PENDING_CALLS(); - if (lock != NULL) - PyThread_release_lock(lock); - return result; + int i, j, result=0; + PyThread_type_lock lock = pending_lock; + + /* try a few times for the lock. Since this mechanism is used + * for signal handling (on the main thread), there is a (slim) + * chance that a signal is delivered on the same thread while we + * hold the lock during the Py_MakePendingCalls() function. + * This avoids a deadlock in that case. + * Note that signals can be delivered on any thread. In particular, + * on Windows, a SIGINT is delivered on a system-created worker + * thread. + * We also check for lock being NULL, in the unlikely case that + * this function is called before any bytecode evaluation takes place. + */ + if (lock != NULL) { + for (i = 0; i<100; i++) { + if (PyThread_acquire_lock(lock, NOWAIT_LOCK)) + break; + } + if (i == 100) + return -1; + } + + i = pendinglast; + j = (i + 1) % NPENDINGCALLS; + if (j == pendingfirst) { + result = -1; /* Queue full */ + } else { + pendingcalls[i].func = func; + pendingcalls[i].arg = arg; + pendinglast = j; + } + /* signal main loop */ + SIGNAL_PENDING_CALLS(); + if (lock != NULL) + PyThread_release_lock(lock); + return result; } int Py_MakePendingCalls(void) { - int i; - int r = 0; + int i; + int r = 0; - if (!pending_lock) { - /* initial allocation of the lock */ - pending_lock = PyThread_allocate_lock(); - if (pending_lock == NULL) - return -1; - } - - /* only service pending calls on main thread */ - if (main_thread && PyThread_get_thread_ident() != main_thread) - return 0; - /* don't perform recursive pending calls */ - if (pendingbusy) - return 0; - pendingbusy = 1; - /* perform a bounded number of calls, in case of recursion */ - for (i=0; irecursion_depth; - PyErr_SetString(PyExc_MemoryError, "Stack overflow"); - return -1; - } -#endif - _Py_CheckRecursionLimit = recursion_limit; - if (tstate->recursion_critical) - /* Somebody asked that we don't check for recursion. */ - return 0; - if (tstate->overflowed) { - if (tstate->recursion_depth > recursion_limit + 50) { - /* Overflowing while handling an overflow. Give up. */ - Py_FatalError("Cannot recover from stack overflow."); - } - return 0; - } - if (tstate->recursion_depth > recursion_limit) { - --tstate->recursion_depth; - tstate->overflowed = 1; - PyErr_Format(PyExc_RuntimeError, - "maximum recursion depth exceeded%s", - where); - return -1; - } - return 0; + if (PyOS_CheckStack()) { + --tstate->recursion_depth; + PyErr_SetString(PyExc_MemoryError, "Stack overflow"); + return -1; + } +#endif + _Py_CheckRecursionLimit = recursion_limit; + if (tstate->recursion_critical) + /* Somebody asked that we don't check for recursion. */ + return 0; + if (tstate->overflowed) { + if (tstate->recursion_depth > recursion_limit + 50) { + /* Overflowing while handling an overflow. Give up. */ + Py_FatalError("Cannot recover from stack overflow."); + } + return 0; + } + if (tstate->recursion_depth > recursion_limit) { + --tstate->recursion_depth; + tstate->overflowed = 1; + PyErr_Format(PyExc_RuntimeError, + "maximum recursion depth exceeded%s", + where); + return -1; + } + return 0; } /* Status code for main loop (reason for stack unwind) */ enum why_code { - WHY_NOT = 0x0001, /* No error */ - WHY_EXCEPTION = 0x0002, /* Exception occurred */ - WHY_RERAISE = 0x0004, /* Exception re-raised by 'finally' */ - WHY_RETURN = 0x0008, /* 'return' statement */ - WHY_BREAK = 0x0010, /* 'break' statement */ - WHY_CONTINUE = 0x0020, /* 'continue' statement */ - WHY_YIELD = 0x0040, /* 'yield' operator */ - WHY_SILENCED = 0x0080 /* Exception silenced by 'with' */ + WHY_NOT = 0x0001, /* No error */ + WHY_EXCEPTION = 0x0002, /* Exception occurred */ + WHY_RERAISE = 0x0004, /* Exception re-raised by 'finally' */ + WHY_RETURN = 0x0008, /* 'return' statement */ + WHY_BREAK = 0x0010, /* 'break' statement */ + WHY_CONTINUE = 0x0020, /* 'continue' statement */ + WHY_YIELD = 0x0040, /* 'yield' operator */ + WHY_SILENCED = 0x0080 /* Exception silenced by 'with' */ }; static enum why_code do_raise(PyObject *, PyObject *); @@ -743,12 +743,12 @@ PyObject * PyEval_EvalCode(PyCodeObject *co, PyObject *globals, PyObject *locals) { - return PyEval_EvalCodeEx(co, - globals, locals, - (PyObject **)NULL, 0, - (PyObject **)NULL, 0, - (PyObject **)NULL, 0, - NULL, NULL); + return PyEval_EvalCodeEx(co, + globals, locals, + (PyObject **)NULL, 0, + (PyObject **)NULL, 0, + (PyObject **)NULL, 0, + NULL, NULL); } @@ -756,49 +756,49 @@ PyObject * PyEval_EvalFrame(PyFrameObject *f) { - /* This is for backward compatibility with extension modules that - used this API; core interpreter code should call - PyEval_EvalFrameEx() */ - return PyEval_EvalFrameEx(f, 0); + /* This is for backward compatibility with extension modules that + used this API; core interpreter code should call + PyEval_EvalFrameEx() */ + return PyEval_EvalFrameEx(f, 0); } PyObject * PyEval_EvalFrameEx(PyFrameObject *f, int throwflag) { #ifdef DXPAIRS - int lastopcode = 0; + int lastopcode = 0; #endif - register PyObject **stack_pointer; /* Next free slot in value stack */ - register unsigned char *next_instr; - register int opcode; /* Current opcode */ - register int oparg; /* Current opcode argument, if any */ - register enum why_code why; /* Reason for block stack unwind */ - register int err; /* Error status -- nonzero if error */ - register PyObject *x; /* Result object -- NULL if error */ - register PyObject *v; /* Temporary objects popped off stack */ - register PyObject *w; - register PyObject *u; - register PyObject *t; - register PyObject **fastlocals, **freevars; - PyObject *retval = NULL; /* Return value */ - PyThreadState *tstate = PyThreadState_GET(); - PyCodeObject *co; - - /* when tracing we set things up so that - - not (instr_lb <= current_bytecode_offset < instr_ub) - - is true when the line being executed has changed. The - initial values are such as to make this false the first - time it is tested. */ - int instr_ub = -1, instr_lb = 0, instr_prev = -1; - - unsigned char *first_instr; - PyObject *names; - PyObject *consts; + register PyObject **stack_pointer; /* Next free slot in value stack */ + register unsigned char *next_instr; + register int opcode; /* Current opcode */ + register int oparg; /* Current opcode argument, if any */ + register enum why_code why; /* Reason for block stack unwind */ + register int err; /* Error status -- nonzero if error */ + register PyObject *x; /* Result object -- NULL if error */ + register PyObject *v; /* Temporary objects popped off stack */ + register PyObject *w; + register PyObject *u; + register PyObject *t; + register PyObject **fastlocals, **freevars; + PyObject *retval = NULL; /* Return value */ + PyThreadState *tstate = PyThreadState_GET(); + PyCodeObject *co; + + /* when tracing we set things up so that + + not (instr_lb <= current_bytecode_offset < instr_ub) + + is true when the line being executed has changed. The + initial values are such as to make this false the first + time it is tested. */ + int instr_ub = -1, instr_lb = 0, instr_prev = -1; + + unsigned char *first_instr; + PyObject *names; + PyObject *consts; #if defined(Py_DEBUG) || defined(LLTRACE) - /* Make it easier to find out where we are with a debugger */ - char *filename; + /* Make it easier to find out where we are with a debugger */ + char *filename; #endif /* Computed GOTOs, or @@ -807,7 +807,7 @@ (http://gcc.gnu.org/onlinedocs/gcc/Labels-as-Values.html). The traditional bytecode evaluation loop uses a "switch" statement, which - decent compilers will optimize as a single indirect branch instruction + decent compilers will optimize as a single indirect branch instruction combined with a lookup table of jump addresses. However, since the indirect jump instruction is shared by all opcodes, the CPU will have a hard time making the right prediction for where to jump next (actually, @@ -822,7 +822,7 @@ a much better chance to turn out valid, especially in small bytecode loops. A mispredicted branch on a modern CPU flushes the whole pipeline and - can cost several CPU cycles (depending on the pipeline depth), + can cost several CPU cycles (depending on the pipeline depth), and potentially many more instructions (depending on the pipeline width). A correctly predicted branch, however, is nearly free. @@ -851,56 +851,56 @@ /* This macro is used when several opcodes defer to the same implementation (e.g. SETUP_LOOP, SETUP_FINALLY) */ #define TARGET_WITH_IMPL(op, impl) \ - TARGET_##op: \ - opcode = op; \ - if (HAS_ARG(op)) \ - oparg = NEXTARG(); \ - case op: \ - goto impl; \ + TARGET_##op: \ + opcode = op; \ + if (HAS_ARG(op)) \ + oparg = NEXTARG(); \ + case op: \ + goto impl; \ #define TARGET(op) \ - TARGET_##op: \ - opcode = op; \ - if (HAS_ARG(op)) \ - oparg = NEXTARG(); \ - case op: + TARGET_##op: \ + opcode = op; \ + if (HAS_ARG(op)) \ + oparg = NEXTARG(); \ + case op: #define DISPATCH() \ - { \ - if (!_Py_atomic_load_relaxed(&eval_breaker)) { \ - FAST_DISPATCH(); \ - } \ - continue; \ - } + { \ + if (!_Py_atomic_load_relaxed(&eval_breaker)) { \ + FAST_DISPATCH(); \ + } \ + continue; \ + } #ifdef LLTRACE #define FAST_DISPATCH() \ - { \ - if (!lltrace && !_Py_TracingPossible) { \ - f->f_lasti = INSTR_OFFSET(); \ - goto *opcode_targets[*next_instr++]; \ - } \ - goto fast_next_opcode; \ - } + { \ + if (!lltrace && !_Py_TracingPossible) { \ + f->f_lasti = INSTR_OFFSET(); \ + goto *opcode_targets[*next_instr++]; \ + } \ + goto fast_next_opcode; \ + } #else #define FAST_DISPATCH() \ - { \ - if (!_Py_TracingPossible) { \ - f->f_lasti = INSTR_OFFSET(); \ - goto *opcode_targets[*next_instr++]; \ - } \ - goto fast_next_opcode; \ - } + { \ + if (!_Py_TracingPossible) { \ + f->f_lasti = INSTR_OFFSET(); \ + goto *opcode_targets[*next_instr++]; \ + } \ + goto fast_next_opcode; \ + } #endif #else #define TARGET(op) \ - case op: + case op: #define TARGET_WITH_IMPL(op, impl) \ - /* silence compiler warnings about `impl` unused */ \ - if (0) goto impl; \ - case op: + /* silence compiler warnings about `impl` unused */ \ + if (0) goto impl; \ + case op: #define DISPATCH() continue #define FAST_DISPATCH() goto fast_next_opcode #endif @@ -942,62 +942,62 @@ CALL_FUNCTION (and friends) */ - uint64 inst0, inst1, loop0, loop1, intr0 = 0, intr1 = 0; - int ticked = 0; + uint64 inst0, inst1, loop0, loop1, intr0 = 0, intr1 = 0; + int ticked = 0; - READ_TIMESTAMP(inst0); - READ_TIMESTAMP(inst1); - READ_TIMESTAMP(loop0); - READ_TIMESTAMP(loop1); + READ_TIMESTAMP(inst0); + READ_TIMESTAMP(inst1); + READ_TIMESTAMP(loop0); + READ_TIMESTAMP(loop1); - /* shut up the compiler */ - opcode = 0; + /* shut up the compiler */ + opcode = 0; #endif /* Code access macros */ -#define INSTR_OFFSET() ((int)(next_instr - first_instr)) -#define NEXTOP() (*next_instr++) -#define NEXTARG() (next_instr += 2, (next_instr[-1]<<8) + next_instr[-2]) -#define PEEKARG() ((next_instr[2]<<8) + next_instr[1]) -#define JUMPTO(x) (next_instr = first_instr + (x)) -#define JUMPBY(x) (next_instr += (x)) +#define INSTR_OFFSET() ((int)(next_instr - first_instr)) +#define NEXTOP() (*next_instr++) +#define NEXTARG() (next_instr += 2, (next_instr[-1]<<8) + next_instr[-2]) +#define PEEKARG() ((next_instr[2]<<8) + next_instr[1]) +#define JUMPTO(x) (next_instr = first_instr + (x)) +#define JUMPBY(x) (next_instr += (x)) /* OpCode prediction macros - Some opcodes tend to come in pairs thus making it possible to - predict the second code when the first is run. For example, - COMPARE_OP is often followed by JUMP_IF_FALSE or JUMP_IF_TRUE. And, - those opcodes are often followed by a POP_TOP. - - Verifying the prediction costs a single high-speed test of a register - variable against a constant. If the pairing was good, then the - processor's own internal branch predication has a high likelihood of - success, resulting in a nearly zero-overhead transition to the - next opcode. A successful prediction saves a trip through the eval-loop - including its two unpredictable branches, the HAS_ARG test and the - switch-case. Combined with the processor's internal branch prediction, - a successful PREDICT has the effect of making the two opcodes run as if - they were a single new opcode with the bodies combined. + Some opcodes tend to come in pairs thus making it possible to + predict the second code when the first is run. For example, + COMPARE_OP is often followed by JUMP_IF_FALSE or JUMP_IF_TRUE. And, + those opcodes are often followed by a POP_TOP. + + Verifying the prediction costs a single high-speed test of a register + variable against a constant. If the pairing was good, then the + processor's own internal branch predication has a high likelihood of + success, resulting in a nearly zero-overhead transition to the + next opcode. A successful prediction saves a trip through the eval-loop + including its two unpredictable branches, the HAS_ARG test and the + switch-case. Combined with the processor's internal branch prediction, + a successful PREDICT has the effect of making the two opcodes run as if + they were a single new opcode with the bodies combined. If collecting opcode statistics, your choices are to either keep the - predictions turned-on and interpret the results as if some opcodes - had been combined or turn-off predictions so that the opcode frequency - counter updates for both opcodes. + predictions turned-on and interpret the results as if some opcodes + had been combined or turn-off predictions so that the opcode frequency + counter updates for both opcodes. Opcode prediction is disabled with threaded code, since the latter allows - the CPU to record separate branch prediction information for each - opcode. + the CPU to record separate branch prediction information for each + opcode. */ #if defined(DYNAMIC_EXECUTION_PROFILE) || defined(USE_COMPUTED_GOTOS) -#define PREDICT(op) if (0) goto PRED_##op -#define PREDICTED(op) PRED_##op: -#define PREDICTED_WITH_ARG(op) PRED_##op: +#define PREDICT(op) if (0) goto PRED_##op +#define PREDICTED(op) PRED_##op: +#define PREDICTED_WITH_ARG(op) PRED_##op: #else -#define PREDICT(op) if (*next_instr == op) goto PRED_##op -#define PREDICTED(op) PRED_##op: next_instr++ -#define PREDICTED_WITH_ARG(op) PRED_##op: oparg = PEEKARG(); next_instr += 3 +#define PREDICT(op) if (*next_instr == op) goto PRED_##op +#define PREDICTED(op) PRED_##op: next_instr++ +#define PREDICTED_WITH_ARG(op) PRED_##op: oparg = PEEKARG(); next_instr += 3 #endif @@ -1005,44 +1005,44 @@ /* The stack can grow at most MAXINT deep, as co_nlocals and co_stacksize are ints. */ -#define STACK_LEVEL() ((int)(stack_pointer - f->f_valuestack)) -#define EMPTY() (STACK_LEVEL() == 0) -#define TOP() (stack_pointer[-1]) -#define SECOND() (stack_pointer[-2]) -#define THIRD() (stack_pointer[-3]) -#define FOURTH() (stack_pointer[-4]) +#define STACK_LEVEL() ((int)(stack_pointer - f->f_valuestack)) +#define EMPTY() (STACK_LEVEL() == 0) +#define TOP() (stack_pointer[-1]) +#define SECOND() (stack_pointer[-2]) +#define THIRD() (stack_pointer[-3]) +#define FOURTH() (stack_pointer[-4]) #define PEEK(n) (stack_pointer[-(n)]) -#define SET_TOP(v) (stack_pointer[-1] = (v)) -#define SET_SECOND(v) (stack_pointer[-2] = (v)) -#define SET_THIRD(v) (stack_pointer[-3] = (v)) -#define SET_FOURTH(v) (stack_pointer[-4] = (v)) +#define SET_TOP(v) (stack_pointer[-1] = (v)) +#define SET_SECOND(v) (stack_pointer[-2] = (v)) +#define SET_THIRD(v) (stack_pointer[-3] = (v)) +#define SET_FOURTH(v) (stack_pointer[-4] = (v)) #define SET_VALUE(n, v) (stack_pointer[-(n)] = (v)) -#define BASIC_STACKADJ(n) (stack_pointer += n) -#define BASIC_PUSH(v) (*stack_pointer++ = (v)) -#define BASIC_POP() (*--stack_pointer) +#define BASIC_STACKADJ(n) (stack_pointer += n) +#define BASIC_PUSH(v) (*stack_pointer++ = (v)) +#define BASIC_POP() (*--stack_pointer) #ifdef LLTRACE -#define PUSH(v) { (void)(BASIC_PUSH(v), \ - lltrace && prtrace(TOP(), "push")); \ - assert(STACK_LEVEL() <= co->co_stacksize); } -#define POP() ((void)(lltrace && prtrace(TOP(), "pop")), \ - BASIC_POP()) -#define STACKADJ(n) { (void)(BASIC_STACKADJ(n), \ - lltrace && prtrace(TOP(), "stackadj")); \ - assert(STACK_LEVEL() <= co->co_stacksize); } +#define PUSH(v) { (void)(BASIC_PUSH(v), \ + lltrace && prtrace(TOP(), "push")); \ + assert(STACK_LEVEL() <= co->co_stacksize); } +#define POP() ((void)(lltrace && prtrace(TOP(), "pop")), \ + BASIC_POP()) +#define STACKADJ(n) { (void)(BASIC_STACKADJ(n), \ + lltrace && prtrace(TOP(), "stackadj")); \ + assert(STACK_LEVEL() <= co->co_stacksize); } #define EXT_POP(STACK_POINTER) ((void)(lltrace && \ - prtrace((STACK_POINTER)[-1], "ext_pop")), \ - *--(STACK_POINTER)) + prtrace((STACK_POINTER)[-1], "ext_pop")), \ + *--(STACK_POINTER)) #else -#define PUSH(v) BASIC_PUSH(v) -#define POP() BASIC_POP() -#define STACKADJ(n) BASIC_STACKADJ(n) +#define PUSH(v) BASIC_PUSH(v) +#define POP() BASIC_POP() +#define STACKADJ(n) BASIC_STACKADJ(n) #define EXT_POP(STACK_POINTER) (*--(STACK_POINTER)) #endif /* Local variable macros */ -#define GETLOCAL(i) (fastlocals[i]) +#define GETLOCAL(i) (fastlocals[i]) /* The SETLOCAL() macro must not DECREF the local variable in-place and then store the new value; it must copy the old value to a temporary @@ -1050,2006 +1050,2006 @@ This is because it is possible that during the DECREF the frame is accessed by other code (e.g. a __del__ method or gc.collect()) and the variable would be pointing to already-freed memory. */ -#define SETLOCAL(i, value) do { PyObject *tmp = GETLOCAL(i); \ - GETLOCAL(i) = value; \ - Py_XDECREF(tmp); } while (0) +#define SETLOCAL(i, value) do { PyObject *tmp = GETLOCAL(i); \ + GETLOCAL(i) = value; \ + Py_XDECREF(tmp); } while (0) #define UNWIND_BLOCK(b) \ - while (STACK_LEVEL() > (b)->b_level) { \ - PyObject *v = POP(); \ - Py_XDECREF(v); \ - } + while (STACK_LEVEL() > (b)->b_level) { \ + PyObject *v = POP(); \ + Py_XDECREF(v); \ + } #define UNWIND_EXCEPT_HANDLER(b) \ - { \ - PyObject *type, *value, *traceback; \ - assert(STACK_LEVEL() >= (b)->b_level + 3); \ - while (STACK_LEVEL() > (b)->b_level + 3) { \ - value = POP(); \ - Py_XDECREF(value); \ - } \ - type = tstate->exc_type; \ - value = tstate->exc_value; \ - traceback = tstate->exc_traceback; \ - tstate->exc_type = POP(); \ - tstate->exc_value = POP(); \ - tstate->exc_traceback = POP(); \ - Py_XDECREF(type); \ - Py_XDECREF(value); \ - Py_XDECREF(traceback); \ - } + { \ + PyObject *type, *value, *traceback; \ + assert(STACK_LEVEL() >= (b)->b_level + 3); \ + while (STACK_LEVEL() > (b)->b_level + 3) { \ + value = POP(); \ + Py_XDECREF(value); \ + } \ + type = tstate->exc_type; \ + value = tstate->exc_value; \ + traceback = tstate->exc_traceback; \ + tstate->exc_type = POP(); \ + tstate->exc_value = POP(); \ + tstate->exc_traceback = POP(); \ + Py_XDECREF(type); \ + Py_XDECREF(value); \ + Py_XDECREF(traceback); \ + } #define SAVE_EXC_STATE() \ - { \ - PyObject *type, *value, *traceback; \ - Py_XINCREF(tstate->exc_type); \ - Py_XINCREF(tstate->exc_value); \ - Py_XINCREF(tstate->exc_traceback); \ - type = f->f_exc_type; \ - value = f->f_exc_value; \ - traceback = f->f_exc_traceback; \ - f->f_exc_type = tstate->exc_type; \ - f->f_exc_value = tstate->exc_value; \ - f->f_exc_traceback = tstate->exc_traceback; \ - Py_XDECREF(type); \ - Py_XDECREF(value); \ - Py_XDECREF(traceback); \ - } + { \ + PyObject *type, *value, *traceback; \ + Py_XINCREF(tstate->exc_type); \ + Py_XINCREF(tstate->exc_value); \ + Py_XINCREF(tstate->exc_traceback); \ + type = f->f_exc_type; \ + value = f->f_exc_value; \ + traceback = f->f_exc_traceback; \ + f->f_exc_type = tstate->exc_type; \ + f->f_exc_value = tstate->exc_value; \ + f->f_exc_traceback = tstate->exc_traceback; \ + Py_XDECREF(type); \ + Py_XDECREF(value); \ + Py_XDECREF(traceback); \ + } #define SWAP_EXC_STATE() \ - { \ - PyObject *tmp; \ - tmp = tstate->exc_type; \ - tstate->exc_type = f->f_exc_type; \ - f->f_exc_type = tmp; \ - tmp = tstate->exc_value; \ - tstate->exc_value = f->f_exc_value; \ - f->f_exc_value = tmp; \ - tmp = tstate->exc_traceback; \ - tstate->exc_traceback = f->f_exc_traceback; \ - f->f_exc_traceback = tmp; \ - } + { \ + PyObject *tmp; \ + tmp = tstate->exc_type; \ + tstate->exc_type = f->f_exc_type; \ + f->f_exc_type = tmp; \ + tmp = tstate->exc_value; \ + tstate->exc_value = f->f_exc_value; \ + f->f_exc_value = tmp; \ + tmp = tstate->exc_traceback; \ + tstate->exc_traceback = f->f_exc_traceback; \ + f->f_exc_traceback = tmp; \ + } /* Start of code */ - if (f == NULL) - return NULL; + if (f == NULL) + return NULL; - /* push frame */ - if (Py_EnterRecursiveCall("")) - return NULL; - - tstate->frame = f; - - if (tstate->use_tracing) { - if (tstate->c_tracefunc != NULL) { - /* tstate->c_tracefunc, if defined, is a - function that will be called on *every* entry - to a code block. Its return value, if not - None, is a function that will be called at - the start of each executed line of code. - (Actually, the function must return itself - in order to continue tracing.) The trace - functions are called with three arguments: - a pointer to the current frame, a string - indicating why the function is called, and - an argument which depends on the situation. - The global trace function is also called - whenever an exception is detected. */ - if (call_trace_protected(tstate->c_tracefunc, - tstate->c_traceobj, - f, PyTrace_CALL, Py_None)) { - /* Trace function raised an error */ - goto exit_eval_frame; - } - } - if (tstate->c_profilefunc != NULL) { - /* Similar for c_profilefunc, except it needn't - return itself and isn't called for "line" events */ - if (call_trace_protected(tstate->c_profilefunc, - tstate->c_profileobj, - f, PyTrace_CALL, Py_None)) { - /* Profile function raised an error */ - goto exit_eval_frame; - } - } - } - - co = f->f_code; - names = co->co_names; - consts = co->co_consts; - fastlocals = f->f_localsplus; - freevars = f->f_localsplus + co->co_nlocals; - first_instr = (unsigned char*) PyBytes_AS_STRING(co->co_code); - /* An explanation is in order for the next line. - - f->f_lasti now refers to the index of the last instruction - executed. You might think this was obvious from the name, but - this wasn't always true before 2.3! PyFrame_New now sets - f->f_lasti to -1 (i.e. the index *before* the first instruction) - and YIELD_VALUE doesn't fiddle with f_lasti any more. So this - does work. Promise. - - When the PREDICT() macros are enabled, some opcode pairs follow in - direct succession without updating f->f_lasti. A successful - prediction effectively links the two codes together as if they - were a single new opcode; accordingly,f->f_lasti will point to - the first code in the pair (for instance, GET_ITER followed by - FOR_ITER is effectively a single opcode and f->f_lasti will point - at to the beginning of the combined pair.) - */ - next_instr = first_instr + f->f_lasti + 1; - stack_pointer = f->f_stacktop; - assert(stack_pointer != NULL); - f->f_stacktop = NULL; /* remains NULL unless yield suspends frame */ - - if (co->co_flags & CO_GENERATOR && !throwflag) { - if (f->f_exc_type != NULL && f->f_exc_type != Py_None) { - /* We were in an except handler when we left, - restore the exception state which was put aside - (see YIELD_VALUE). */ - SWAP_EXC_STATE(); - } - else { - SAVE_EXC_STATE(); - } - } + /* push frame */ + if (Py_EnterRecursiveCall("")) + return NULL; + + tstate->frame = f; + + if (tstate->use_tracing) { + if (tstate->c_tracefunc != NULL) { + /* tstate->c_tracefunc, if defined, is a + function that will be called on *every* entry + to a code block. Its return value, if not + None, is a function that will be called at + the start of each executed line of code. + (Actually, the function must return itself + in order to continue tracing.) The trace + functions are called with three arguments: + a pointer to the current frame, a string + indicating why the function is called, and + an argument which depends on the situation. + The global trace function is also called + whenever an exception is detected. */ + if (call_trace_protected(tstate->c_tracefunc, + tstate->c_traceobj, + f, PyTrace_CALL, Py_None)) { + /* Trace function raised an error */ + goto exit_eval_frame; + } + } + if (tstate->c_profilefunc != NULL) { + /* Similar for c_profilefunc, except it needn't + return itself and isn't called for "line" events */ + if (call_trace_protected(tstate->c_profilefunc, + tstate->c_profileobj, + f, PyTrace_CALL, Py_None)) { + /* Profile function raised an error */ + goto exit_eval_frame; + } + } + } + + co = f->f_code; + names = co->co_names; + consts = co->co_consts; + fastlocals = f->f_localsplus; + freevars = f->f_localsplus + co->co_nlocals; + first_instr = (unsigned char*) PyBytes_AS_STRING(co->co_code); + /* An explanation is in order for the next line. + + f->f_lasti now refers to the index of the last instruction + executed. You might think this was obvious from the name, but + this wasn't always true before 2.3! PyFrame_New now sets + f->f_lasti to -1 (i.e. the index *before* the first instruction) + and YIELD_VALUE doesn't fiddle with f_lasti any more. So this + does work. Promise. + + When the PREDICT() macros are enabled, some opcode pairs follow in + direct succession without updating f->f_lasti. A successful + prediction effectively links the two codes together as if they + were a single new opcode; accordingly,f->f_lasti will point to + the first code in the pair (for instance, GET_ITER followed by + FOR_ITER is effectively a single opcode and f->f_lasti will point + at to the beginning of the combined pair.) + */ + next_instr = first_instr + f->f_lasti + 1; + stack_pointer = f->f_stacktop; + assert(stack_pointer != NULL); + f->f_stacktop = NULL; /* remains NULL unless yield suspends frame */ + + if (co->co_flags & CO_GENERATOR && !throwflag) { + if (f->f_exc_type != NULL && f->f_exc_type != Py_None) { + /* We were in an except handler when we left, + restore the exception state which was put aside + (see YIELD_VALUE). */ + SWAP_EXC_STATE(); + } + else { + SAVE_EXC_STATE(); + } + } #ifdef LLTRACE - lltrace = PyDict_GetItemString(f->f_globals, "__lltrace__") != NULL; + lltrace = PyDict_GetItemString(f->f_globals, "__lltrace__") != NULL; #endif #if defined(Py_DEBUG) || defined(LLTRACE) - filename = _PyUnicode_AsString(co->co_filename); + filename = _PyUnicode_AsString(co->co_filename); #endif - why = WHY_NOT; - err = 0; - x = Py_None; /* Not a reference, just anything non-NULL */ - w = NULL; + why = WHY_NOT; + err = 0; + x = Py_None; /* Not a reference, just anything non-NULL */ + w = NULL; - if (throwflag) { /* support for generator.throw() */ - why = WHY_EXCEPTION; - goto on_error; - } + if (throwflag) { /* support for generator.throw() */ + why = WHY_EXCEPTION; + goto on_error; + } - for (;;) { + for (;;) { #ifdef WITH_TSC - if (inst1 == 0) { - /* Almost surely, the opcode executed a break - or a continue, preventing inst1 from being set - on the way out of the loop. - */ - READ_TIMESTAMP(inst1); - loop1 = inst1; - } - dump_tsc(opcode, ticked, inst0, inst1, loop0, loop1, - intr0, intr1); - ticked = 0; - inst1 = 0; - intr0 = 0; - intr1 = 0; - READ_TIMESTAMP(loop0); -#endif - assert(stack_pointer >= f->f_valuestack); /* else underflow */ - assert(STACK_LEVEL() <= co->co_stacksize); /* else overflow */ - - /* Do periodic things. Doing this every time through - the loop would add too much overhead, so we do it - only every Nth instruction. We also do it if - ``pendingcalls_to_do'' is set, i.e. when an asynchronous - event needs attention (e.g. a signal handler or - async I/O handler); see Py_AddPendingCall() and - Py_MakePendingCalls() above. */ - - if (_Py_atomic_load_relaxed(&eval_breaker)) { - if (*next_instr == SETUP_FINALLY) { - /* Make the last opcode before - a try: finally: block uninterruptable. */ - goto fast_next_opcode; - } - tstate->tick_counter++; + if (inst1 == 0) { + /* Almost surely, the opcode executed a break + or a continue, preventing inst1 from being set + on the way out of the loop. + */ + READ_TIMESTAMP(inst1); + loop1 = inst1; + } + dump_tsc(opcode, ticked, inst0, inst1, loop0, loop1, + intr0, intr1); + ticked = 0; + inst1 = 0; + intr0 = 0; + intr1 = 0; + READ_TIMESTAMP(loop0); +#endif + assert(stack_pointer >= f->f_valuestack); /* else underflow */ + assert(STACK_LEVEL() <= co->co_stacksize); /* else overflow */ + + /* Do periodic things. Doing this every time through + the loop would add too much overhead, so we do it + only every Nth instruction. We also do it if + ``pendingcalls_to_do'' is set, i.e. when an asynchronous + event needs attention (e.g. a signal handler or + async I/O handler); see Py_AddPendingCall() and + Py_MakePendingCalls() above. */ + + if (_Py_atomic_load_relaxed(&eval_breaker)) { + if (*next_instr == SETUP_FINALLY) { + /* Make the last opcode before + a try: finally: block uninterruptable. */ + goto fast_next_opcode; + } + tstate->tick_counter++; #ifdef WITH_TSC - ticked = 1; + ticked = 1; #endif - if (_Py_atomic_load_relaxed(&pendingcalls_to_do)) { - if (Py_MakePendingCalls() < 0) { - why = WHY_EXCEPTION; - goto on_error; - } - } - if (_Py_atomic_load_relaxed(&gil_drop_request)) { + if (_Py_atomic_load_relaxed(&pendingcalls_to_do)) { + if (Py_MakePendingCalls() < 0) { + why = WHY_EXCEPTION; + goto on_error; + } + } + if (_Py_atomic_load_relaxed(&gil_drop_request)) { #ifdef WITH_THREAD - /* Give another thread a chance */ - if (PyThreadState_Swap(NULL) != tstate) - Py_FatalError("ceval: tstate mix-up"); - drop_gil(tstate); - - /* Other threads may run now */ - - take_gil(tstate); - if (PyThreadState_Swap(tstate) != NULL) - Py_FatalError("ceval: orphan tstate"); -#endif - } - /* Check for asynchronous exceptions. */ - if (tstate->async_exc != NULL) { - x = tstate->async_exc; - tstate->async_exc = NULL; - UNSIGNAL_ASYNC_EXC(); - PyErr_SetNone(x); - Py_DECREF(x); - why = WHY_EXCEPTION; - goto on_error; - } - } - - fast_next_opcode: - f->f_lasti = INSTR_OFFSET(); - - /* line-by-line tracing support */ - - if (_Py_TracingPossible && - tstate->c_tracefunc != NULL && !tstate->tracing) { - /* see maybe_call_line_trace - for expository comments */ - f->f_stacktop = stack_pointer; - - err = maybe_call_line_trace(tstate->c_tracefunc, - tstate->c_traceobj, - f, &instr_lb, &instr_ub, - &instr_prev); - /* Reload possibly changed frame fields */ - JUMPTO(f->f_lasti); - if (f->f_stacktop != NULL) { - stack_pointer = f->f_stacktop; - f->f_stacktop = NULL; - } - if (err) { - /* trace function raised an exception */ - goto on_error; - } - } - - /* Extract opcode and argument */ - - opcode = NEXTOP(); - oparg = 0; /* allows oparg to be stored in a register because - it doesn't have to be remembered across a full loop */ - if (HAS_ARG(opcode)) - oparg = NEXTARG(); - dispatch_opcode: + /* Give another thread a chance */ + if (PyThreadState_Swap(NULL) != tstate) + Py_FatalError("ceval: tstate mix-up"); + drop_gil(tstate); + + /* Other threads may run now */ + + take_gil(tstate); + if (PyThreadState_Swap(tstate) != NULL) + Py_FatalError("ceval: orphan tstate"); +#endif + } + /* Check for asynchronous exceptions. */ + if (tstate->async_exc != NULL) { + x = tstate->async_exc; + tstate->async_exc = NULL; + UNSIGNAL_ASYNC_EXC(); + PyErr_SetNone(x); + Py_DECREF(x); + why = WHY_EXCEPTION; + goto on_error; + } + } + + fast_next_opcode: + f->f_lasti = INSTR_OFFSET(); + + /* line-by-line tracing support */ + + if (_Py_TracingPossible && + tstate->c_tracefunc != NULL && !tstate->tracing) { + /* see maybe_call_line_trace + for expository comments */ + f->f_stacktop = stack_pointer; + + err = maybe_call_line_trace(tstate->c_tracefunc, + tstate->c_traceobj, + f, &instr_lb, &instr_ub, + &instr_prev); + /* Reload possibly changed frame fields */ + JUMPTO(f->f_lasti); + if (f->f_stacktop != NULL) { + stack_pointer = f->f_stacktop; + f->f_stacktop = NULL; + } + if (err) { + /* trace function raised an exception */ + goto on_error; + } + } + + /* Extract opcode and argument */ + + opcode = NEXTOP(); + oparg = 0; /* allows oparg to be stored in a register because + it doesn't have to be remembered across a full loop */ + if (HAS_ARG(opcode)) + oparg = NEXTARG(); + dispatch_opcode: #ifdef DYNAMIC_EXECUTION_PROFILE #ifdef DXPAIRS - dxpairs[lastopcode][opcode]++; - lastopcode = opcode; + dxpairs[lastopcode][opcode]++; + lastopcode = opcode; #endif - dxp[opcode]++; + dxp[opcode]++; #endif #ifdef LLTRACE - /* Instruction tracing */ + /* Instruction tracing */ - if (lltrace) { - if (HAS_ARG(opcode)) { - printf("%d: %d, %d\n", - f->f_lasti, opcode, oparg); - } - else { - printf("%d: %d\n", - f->f_lasti, opcode); - } - } -#endif - - /* Main switch on opcode */ - READ_TIMESTAMP(inst0); - - switch (opcode) { - - /* BEWARE! - It is essential that any operation that fails sets either - x to NULL, err to nonzero, or why to anything but WHY_NOT, - and that no operation that succeeds does this! */ - - /* case STOP_CODE: this is an error! */ - - TARGET(NOP) - FAST_DISPATCH(); - - TARGET(LOAD_FAST) - x = GETLOCAL(oparg); - if (x != NULL) { - Py_INCREF(x); - PUSH(x); - FAST_DISPATCH(); - } - format_exc_check_arg(PyExc_UnboundLocalError, - UNBOUNDLOCAL_ERROR_MSG, - PyTuple_GetItem(co->co_varnames, oparg)); - break; - - TARGET(LOAD_CONST) - x = GETITEM(consts, oparg); - Py_INCREF(x); - PUSH(x); - FAST_DISPATCH(); - - PREDICTED_WITH_ARG(STORE_FAST); - TARGET(STORE_FAST) - v = POP(); - SETLOCAL(oparg, v); - FAST_DISPATCH(); - - TARGET(POP_TOP) - v = POP(); - Py_DECREF(v); - FAST_DISPATCH(); - - TARGET(ROT_TWO) - v = TOP(); - w = SECOND(); - SET_TOP(w); - SET_SECOND(v); - FAST_DISPATCH(); - - TARGET(ROT_THREE) - v = TOP(); - w = SECOND(); - x = THIRD(); - SET_TOP(w); - SET_SECOND(x); - SET_THIRD(v); - FAST_DISPATCH(); - - TARGET(ROT_FOUR) - u = TOP(); - v = SECOND(); - w = THIRD(); - x = FOURTH(); - SET_TOP(v); - SET_SECOND(w); - SET_THIRD(x); - SET_FOURTH(u); - FAST_DISPATCH(); - - TARGET(DUP_TOP) - v = TOP(); - Py_INCREF(v); - PUSH(v); - FAST_DISPATCH(); - - TARGET(DUP_TOPX) - if (oparg == 2) { - x = TOP(); - Py_INCREF(x); - w = SECOND(); - Py_INCREF(w); - STACKADJ(2); - SET_TOP(x); - SET_SECOND(w); - FAST_DISPATCH(); - } else if (oparg == 3) { - x = TOP(); - Py_INCREF(x); - w = SECOND(); - Py_INCREF(w); - v = THIRD(); - Py_INCREF(v); - STACKADJ(3); - SET_TOP(x); - SET_SECOND(w); - SET_THIRD(v); - FAST_DISPATCH(); - } - Py_FatalError("invalid argument to DUP_TOPX" - " (bytecode corruption?)"); - /* Never returns, so don't bother to set why. */ - break; - - TARGET(UNARY_POSITIVE) - v = TOP(); - x = PyNumber_Positive(v); - Py_DECREF(v); - SET_TOP(x); - if (x != NULL) DISPATCH(); - break; - - TARGET(UNARY_NEGATIVE) - v = TOP(); - x = PyNumber_Negative(v); - Py_DECREF(v); - SET_TOP(x); - if (x != NULL) DISPATCH(); - break; - - TARGET(UNARY_NOT) - v = TOP(); - err = PyObject_IsTrue(v); - Py_DECREF(v); - if (err == 0) { - Py_INCREF(Py_True); - SET_TOP(Py_True); - DISPATCH(); - } - else if (err > 0) { - Py_INCREF(Py_False); - SET_TOP(Py_False); - err = 0; - DISPATCH(); - } - STACKADJ(-1); - break; - - TARGET(UNARY_INVERT) - v = TOP(); - x = PyNumber_Invert(v); - Py_DECREF(v); - SET_TOP(x); - if (x != NULL) DISPATCH(); - break; - - TARGET(BINARY_POWER) - w = POP(); - v = TOP(); - x = PyNumber_Power(v, w, Py_None); - Py_DECREF(v); - Py_DECREF(w); - SET_TOP(x); - if (x != NULL) DISPATCH(); - break; - - TARGET(BINARY_MULTIPLY) - w = POP(); - v = TOP(); - x = PyNumber_Multiply(v, w); - Py_DECREF(v); - Py_DECREF(w); - SET_TOP(x); - if (x != NULL) DISPATCH(); - break; - - TARGET(BINARY_TRUE_DIVIDE) - w = POP(); - v = TOP(); - x = PyNumber_TrueDivide(v, w); - Py_DECREF(v); - Py_DECREF(w); - SET_TOP(x); - if (x != NULL) DISPATCH(); - break; - - TARGET(BINARY_FLOOR_DIVIDE) - w = POP(); - v = TOP(); - x = PyNumber_FloorDivide(v, w); - Py_DECREF(v); - Py_DECREF(w); - SET_TOP(x); - if (x != NULL) DISPATCH(); - break; - - TARGET(BINARY_MODULO) - w = POP(); - v = TOP(); - if (PyUnicode_CheckExact(v)) - x = PyUnicode_Format(v, w); - else - x = PyNumber_Remainder(v, w); - Py_DECREF(v); - Py_DECREF(w); - SET_TOP(x); - if (x != NULL) DISPATCH(); - break; - - TARGET(BINARY_ADD) - w = POP(); - v = TOP(); - if (PyUnicode_CheckExact(v) && - PyUnicode_CheckExact(w)) { - x = unicode_concatenate(v, w, f, next_instr); - /* unicode_concatenate consumed the ref to v */ - goto skip_decref_vx; - } - else { - x = PyNumber_Add(v, w); - } - Py_DECREF(v); - skip_decref_vx: - Py_DECREF(w); - SET_TOP(x); - if (x != NULL) DISPATCH(); - break; - - TARGET(BINARY_SUBTRACT) - w = POP(); - v = TOP(); - x = PyNumber_Subtract(v, w); - Py_DECREF(v); - Py_DECREF(w); - SET_TOP(x); - if (x != NULL) DISPATCH(); - break; - - TARGET(BINARY_SUBSCR) - w = POP(); - v = TOP(); - x = PyObject_GetItem(v, w); - Py_DECREF(v); - Py_DECREF(w); - SET_TOP(x); - if (x != NULL) DISPATCH(); - break; - - TARGET(BINARY_LSHIFT) - w = POP(); - v = TOP(); - x = PyNumber_Lshift(v, w); - Py_DECREF(v); - Py_DECREF(w); - SET_TOP(x); - if (x != NULL) DISPATCH(); - break; - - TARGET(BINARY_RSHIFT) - w = POP(); - v = TOP(); - x = PyNumber_Rshift(v, w); - Py_DECREF(v); - Py_DECREF(w); - SET_TOP(x); - if (x != NULL) DISPATCH(); - break; - - TARGET(BINARY_AND) - w = POP(); - v = TOP(); - x = PyNumber_And(v, w); - Py_DECREF(v); - Py_DECREF(w); - SET_TOP(x); - if (x != NULL) DISPATCH(); - break; - - TARGET(BINARY_XOR) - w = POP(); - v = TOP(); - x = PyNumber_Xor(v, w); - Py_DECREF(v); - Py_DECREF(w); - SET_TOP(x); - if (x != NULL) DISPATCH(); - break; - - TARGET(BINARY_OR) - w = POP(); - v = TOP(); - x = PyNumber_Or(v, w); - Py_DECREF(v); - Py_DECREF(w); - SET_TOP(x); - if (x != NULL) DISPATCH(); - break; - - TARGET(LIST_APPEND) - w = POP(); - v = PEEK(oparg); - err = PyList_Append(v, w); - Py_DECREF(w); - if (err == 0) { - PREDICT(JUMP_ABSOLUTE); - DISPATCH(); - } - break; - - TARGET(SET_ADD) - w = POP(); - v = stack_pointer[-oparg]; - err = PySet_Add(v, w); - Py_DECREF(w); - if (err == 0) { - PREDICT(JUMP_ABSOLUTE); - DISPATCH(); - } - break; - - TARGET(INPLACE_POWER) - w = POP(); - v = TOP(); - x = PyNumber_InPlacePower(v, w, Py_None); - Py_DECREF(v); - Py_DECREF(w); - SET_TOP(x); - if (x != NULL) DISPATCH(); - break; - - TARGET(INPLACE_MULTIPLY) - w = POP(); - v = TOP(); - x = PyNumber_InPlaceMultiply(v, w); - Py_DECREF(v); - Py_DECREF(w); - SET_TOP(x); - if (x != NULL) DISPATCH(); - break; - - TARGET(INPLACE_TRUE_DIVIDE) - w = POP(); - v = TOP(); - x = PyNumber_InPlaceTrueDivide(v, w); - Py_DECREF(v); - Py_DECREF(w); - SET_TOP(x); - if (x != NULL) DISPATCH(); - break; - - TARGET(INPLACE_FLOOR_DIVIDE) - w = POP(); - v = TOP(); - x = PyNumber_InPlaceFloorDivide(v, w); - Py_DECREF(v); - Py_DECREF(w); - SET_TOP(x); - if (x != NULL) DISPATCH(); - break; - - TARGET(INPLACE_MODULO) - w = POP(); - v = TOP(); - x = PyNumber_InPlaceRemainder(v, w); - Py_DECREF(v); - Py_DECREF(w); - SET_TOP(x); - if (x != NULL) DISPATCH(); - break; - - TARGET(INPLACE_ADD) - w = POP(); - v = TOP(); - if (PyUnicode_CheckExact(v) && - PyUnicode_CheckExact(w)) { - x = unicode_concatenate(v, w, f, next_instr); - /* unicode_concatenate consumed the ref to v */ - goto skip_decref_v; - } - else { - x = PyNumber_InPlaceAdd(v, w); - } - Py_DECREF(v); - skip_decref_v: - Py_DECREF(w); - SET_TOP(x); - if (x != NULL) DISPATCH(); - break; - - TARGET(INPLACE_SUBTRACT) - w = POP(); - v = TOP(); - x = PyNumber_InPlaceSubtract(v, w); - Py_DECREF(v); - Py_DECREF(w); - SET_TOP(x); - if (x != NULL) DISPATCH(); - break; - - TARGET(INPLACE_LSHIFT) - w = POP(); - v = TOP(); - x = PyNumber_InPlaceLshift(v, w); - Py_DECREF(v); - Py_DECREF(w); - SET_TOP(x); - if (x != NULL) DISPATCH(); - break; - - TARGET(INPLACE_RSHIFT) - w = POP(); - v = TOP(); - x = PyNumber_InPlaceRshift(v, w); - Py_DECREF(v); - Py_DECREF(w); - SET_TOP(x); - if (x != NULL) DISPATCH(); - break; - - TARGET(INPLACE_AND) - w = POP(); - v = TOP(); - x = PyNumber_InPlaceAnd(v, w); - Py_DECREF(v); - Py_DECREF(w); - SET_TOP(x); - if (x != NULL) DISPATCH(); - break; - - TARGET(INPLACE_XOR) - w = POP(); - v = TOP(); - x = PyNumber_InPlaceXor(v, w); - Py_DECREF(v); - Py_DECREF(w); - SET_TOP(x); - if (x != NULL) DISPATCH(); - break; - - TARGET(INPLACE_OR) - w = POP(); - v = TOP(); - x = PyNumber_InPlaceOr(v, w); - Py_DECREF(v); - Py_DECREF(w); - SET_TOP(x); - if (x != NULL) DISPATCH(); - break; - - TARGET(STORE_SUBSCR) - w = TOP(); - v = SECOND(); - u = THIRD(); - STACKADJ(-3); - /* v[w] = u */ - err = PyObject_SetItem(v, w, u); - Py_DECREF(u); - Py_DECREF(v); - Py_DECREF(w); - if (err == 0) DISPATCH(); - break; - - TARGET(DELETE_SUBSCR) - w = TOP(); - v = SECOND(); - STACKADJ(-2); - /* del v[w] */ - err = PyObject_DelItem(v, w); - Py_DECREF(v); - Py_DECREF(w); - if (err == 0) DISPATCH(); - break; - - TARGET(PRINT_EXPR) - v = POP(); - w = PySys_GetObject("displayhook"); - if (w == NULL) { - PyErr_SetString(PyExc_RuntimeError, - "lost sys.displayhook"); - err = -1; - x = NULL; - } - if (err == 0) { - x = PyTuple_Pack(1, v); - if (x == NULL) - err = -1; - } - if (err == 0) { - w = PyEval_CallObject(w, x); - Py_XDECREF(w); - if (w == NULL) - err = -1; - } - Py_DECREF(v); - Py_XDECREF(x); - break; + if (lltrace) { + if (HAS_ARG(opcode)) { + printf("%d: %d, %d\n", + f->f_lasti, opcode, oparg); + } + else { + printf("%d: %d\n", + f->f_lasti, opcode); + } + } +#endif + + /* Main switch on opcode */ + READ_TIMESTAMP(inst0); + + switch (opcode) { + + /* BEWARE! + It is essential that any operation that fails sets either + x to NULL, err to nonzero, or why to anything but WHY_NOT, + and that no operation that succeeds does this! */ + + /* case STOP_CODE: this is an error! */ + + TARGET(NOP) + FAST_DISPATCH(); + + TARGET(LOAD_FAST) + x = GETLOCAL(oparg); + if (x != NULL) { + Py_INCREF(x); + PUSH(x); + FAST_DISPATCH(); + } + format_exc_check_arg(PyExc_UnboundLocalError, + UNBOUNDLOCAL_ERROR_MSG, + PyTuple_GetItem(co->co_varnames, oparg)); + break; + + TARGET(LOAD_CONST) + x = GETITEM(consts, oparg); + Py_INCREF(x); + PUSH(x); + FAST_DISPATCH(); + + PREDICTED_WITH_ARG(STORE_FAST); + TARGET(STORE_FAST) + v = POP(); + SETLOCAL(oparg, v); + FAST_DISPATCH(); + + TARGET(POP_TOP) + v = POP(); + Py_DECREF(v); + FAST_DISPATCH(); + + TARGET(ROT_TWO) + v = TOP(); + w = SECOND(); + SET_TOP(w); + SET_SECOND(v); + FAST_DISPATCH(); + + TARGET(ROT_THREE) + v = TOP(); + w = SECOND(); + x = THIRD(); + SET_TOP(w); + SET_SECOND(x); + SET_THIRD(v); + FAST_DISPATCH(); + + TARGET(ROT_FOUR) + u = TOP(); + v = SECOND(); + w = THIRD(); + x = FOURTH(); + SET_TOP(v); + SET_SECOND(w); + SET_THIRD(x); + SET_FOURTH(u); + FAST_DISPATCH(); + + TARGET(DUP_TOP) + v = TOP(); + Py_INCREF(v); + PUSH(v); + FAST_DISPATCH(); + + TARGET(DUP_TOPX) + if (oparg == 2) { + x = TOP(); + Py_INCREF(x); + w = SECOND(); + Py_INCREF(w); + STACKADJ(2); + SET_TOP(x); + SET_SECOND(w); + FAST_DISPATCH(); + } else if (oparg == 3) { + x = TOP(); + Py_INCREF(x); + w = SECOND(); + Py_INCREF(w); + v = THIRD(); + Py_INCREF(v); + STACKADJ(3); + SET_TOP(x); + SET_SECOND(w); + SET_THIRD(v); + FAST_DISPATCH(); + } + Py_FatalError("invalid argument to DUP_TOPX" + " (bytecode corruption?)"); + /* Never returns, so don't bother to set why. */ + break; + + TARGET(UNARY_POSITIVE) + v = TOP(); + x = PyNumber_Positive(v); + Py_DECREF(v); + SET_TOP(x); + if (x != NULL) DISPATCH(); + break; + + TARGET(UNARY_NEGATIVE) + v = TOP(); + x = PyNumber_Negative(v); + Py_DECREF(v); + SET_TOP(x); + if (x != NULL) DISPATCH(); + break; + + TARGET(UNARY_NOT) + v = TOP(); + err = PyObject_IsTrue(v); + Py_DECREF(v); + if (err == 0) { + Py_INCREF(Py_True); + SET_TOP(Py_True); + DISPATCH(); + } + else if (err > 0) { + Py_INCREF(Py_False); + SET_TOP(Py_False); + err = 0; + DISPATCH(); + } + STACKADJ(-1); + break; + + TARGET(UNARY_INVERT) + v = TOP(); + x = PyNumber_Invert(v); + Py_DECREF(v); + SET_TOP(x); + if (x != NULL) DISPATCH(); + break; + + TARGET(BINARY_POWER) + w = POP(); + v = TOP(); + x = PyNumber_Power(v, w, Py_None); + Py_DECREF(v); + Py_DECREF(w); + SET_TOP(x); + if (x != NULL) DISPATCH(); + break; + + TARGET(BINARY_MULTIPLY) + w = POP(); + v = TOP(); + x = PyNumber_Multiply(v, w); + Py_DECREF(v); + Py_DECREF(w); + SET_TOP(x); + if (x != NULL) DISPATCH(); + break; + + TARGET(BINARY_TRUE_DIVIDE) + w = POP(); + v = TOP(); + x = PyNumber_TrueDivide(v, w); + Py_DECREF(v); + Py_DECREF(w); + SET_TOP(x); + if (x != NULL) DISPATCH(); + break; + + TARGET(BINARY_FLOOR_DIVIDE) + w = POP(); + v = TOP(); + x = PyNumber_FloorDivide(v, w); + Py_DECREF(v); + Py_DECREF(w); + SET_TOP(x); + if (x != NULL) DISPATCH(); + break; + + TARGET(BINARY_MODULO) + w = POP(); + v = TOP(); + if (PyUnicode_CheckExact(v)) + x = PyUnicode_Format(v, w); + else + x = PyNumber_Remainder(v, w); + Py_DECREF(v); + Py_DECREF(w); + SET_TOP(x); + if (x != NULL) DISPATCH(); + break; + + TARGET(BINARY_ADD) + w = POP(); + v = TOP(); + if (PyUnicode_CheckExact(v) && + PyUnicode_CheckExact(w)) { + x = unicode_concatenate(v, w, f, next_instr); + /* unicode_concatenate consumed the ref to v */ + goto skip_decref_vx; + } + else { + x = PyNumber_Add(v, w); + } + Py_DECREF(v); + skip_decref_vx: + Py_DECREF(w); + SET_TOP(x); + if (x != NULL) DISPATCH(); + break; + + TARGET(BINARY_SUBTRACT) + w = POP(); + v = TOP(); + x = PyNumber_Subtract(v, w); + Py_DECREF(v); + Py_DECREF(w); + SET_TOP(x); + if (x != NULL) DISPATCH(); + break; + + TARGET(BINARY_SUBSCR) + w = POP(); + v = TOP(); + x = PyObject_GetItem(v, w); + Py_DECREF(v); + Py_DECREF(w); + SET_TOP(x); + if (x != NULL) DISPATCH(); + break; + + TARGET(BINARY_LSHIFT) + w = POP(); + v = TOP(); + x = PyNumber_Lshift(v, w); + Py_DECREF(v); + Py_DECREF(w); + SET_TOP(x); + if (x != NULL) DISPATCH(); + break; + + TARGET(BINARY_RSHIFT) + w = POP(); + v = TOP(); + x = PyNumber_Rshift(v, w); + Py_DECREF(v); + Py_DECREF(w); + SET_TOP(x); + if (x != NULL) DISPATCH(); + break; + + TARGET(BINARY_AND) + w = POP(); + v = TOP(); + x = PyNumber_And(v, w); + Py_DECREF(v); + Py_DECREF(w); + SET_TOP(x); + if (x != NULL) DISPATCH(); + break; + + TARGET(BINARY_XOR) + w = POP(); + v = TOP(); + x = PyNumber_Xor(v, w); + Py_DECREF(v); + Py_DECREF(w); + SET_TOP(x); + if (x != NULL) DISPATCH(); + break; + + TARGET(BINARY_OR) + w = POP(); + v = TOP(); + x = PyNumber_Or(v, w); + Py_DECREF(v); + Py_DECREF(w); + SET_TOP(x); + if (x != NULL) DISPATCH(); + break; + + TARGET(LIST_APPEND) + w = POP(); + v = PEEK(oparg); + err = PyList_Append(v, w); + Py_DECREF(w); + if (err == 0) { + PREDICT(JUMP_ABSOLUTE); + DISPATCH(); + } + break; + + TARGET(SET_ADD) + w = POP(); + v = stack_pointer[-oparg]; + err = PySet_Add(v, w); + Py_DECREF(w); + if (err == 0) { + PREDICT(JUMP_ABSOLUTE); + DISPATCH(); + } + break; + + TARGET(INPLACE_POWER) + w = POP(); + v = TOP(); + x = PyNumber_InPlacePower(v, w, Py_None); + Py_DECREF(v); + Py_DECREF(w); + SET_TOP(x); + if (x != NULL) DISPATCH(); + break; + + TARGET(INPLACE_MULTIPLY) + w = POP(); + v = TOP(); + x = PyNumber_InPlaceMultiply(v, w); + Py_DECREF(v); + Py_DECREF(w); + SET_TOP(x); + if (x != NULL) DISPATCH(); + break; + + TARGET(INPLACE_TRUE_DIVIDE) + w = POP(); + v = TOP(); + x = PyNumber_InPlaceTrueDivide(v, w); + Py_DECREF(v); + Py_DECREF(w); + SET_TOP(x); + if (x != NULL) DISPATCH(); + break; + + TARGET(INPLACE_FLOOR_DIVIDE) + w = POP(); + v = TOP(); + x = PyNumber_InPlaceFloorDivide(v, w); + Py_DECREF(v); + Py_DECREF(w); + SET_TOP(x); + if (x != NULL) DISPATCH(); + break; + + TARGET(INPLACE_MODULO) + w = POP(); + v = TOP(); + x = PyNumber_InPlaceRemainder(v, w); + Py_DECREF(v); + Py_DECREF(w); + SET_TOP(x); + if (x != NULL) DISPATCH(); + break; + + TARGET(INPLACE_ADD) + w = POP(); + v = TOP(); + if (PyUnicode_CheckExact(v) && + PyUnicode_CheckExact(w)) { + x = unicode_concatenate(v, w, f, next_instr); + /* unicode_concatenate consumed the ref to v */ + goto skip_decref_v; + } + else { + x = PyNumber_InPlaceAdd(v, w); + } + Py_DECREF(v); + skip_decref_v: + Py_DECREF(w); + SET_TOP(x); + if (x != NULL) DISPATCH(); + break; + + TARGET(INPLACE_SUBTRACT) + w = POP(); + v = TOP(); + x = PyNumber_InPlaceSubtract(v, w); + Py_DECREF(v); + Py_DECREF(w); + SET_TOP(x); + if (x != NULL) DISPATCH(); + break; + + TARGET(INPLACE_LSHIFT) + w = POP(); + v = TOP(); + x = PyNumber_InPlaceLshift(v, w); + Py_DECREF(v); + Py_DECREF(w); + SET_TOP(x); + if (x != NULL) DISPATCH(); + break; + + TARGET(INPLACE_RSHIFT) + w = POP(); + v = TOP(); + x = PyNumber_InPlaceRshift(v, w); + Py_DECREF(v); + Py_DECREF(w); + SET_TOP(x); + if (x != NULL) DISPATCH(); + break; + + TARGET(INPLACE_AND) + w = POP(); + v = TOP(); + x = PyNumber_InPlaceAnd(v, w); + Py_DECREF(v); + Py_DECREF(w); + SET_TOP(x); + if (x != NULL) DISPATCH(); + break; + + TARGET(INPLACE_XOR) + w = POP(); + v = TOP(); + x = PyNumber_InPlaceXor(v, w); + Py_DECREF(v); + Py_DECREF(w); + SET_TOP(x); + if (x != NULL) DISPATCH(); + break; + + TARGET(INPLACE_OR) + w = POP(); + v = TOP(); + x = PyNumber_InPlaceOr(v, w); + Py_DECREF(v); + Py_DECREF(w); + SET_TOP(x); + if (x != NULL) DISPATCH(); + break; + + TARGET(STORE_SUBSCR) + w = TOP(); + v = SECOND(); + u = THIRD(); + STACKADJ(-3); + /* v[w] = u */ + err = PyObject_SetItem(v, w, u); + Py_DECREF(u); + Py_DECREF(v); + Py_DECREF(w); + if (err == 0) DISPATCH(); + break; + + TARGET(DELETE_SUBSCR) + w = TOP(); + v = SECOND(); + STACKADJ(-2); + /* del v[w] */ + err = PyObject_DelItem(v, w); + Py_DECREF(v); + Py_DECREF(w); + if (err == 0) DISPATCH(); + break; + + TARGET(PRINT_EXPR) + v = POP(); + w = PySys_GetObject("displayhook"); + if (w == NULL) { + PyErr_SetString(PyExc_RuntimeError, + "lost sys.displayhook"); + err = -1; + x = NULL; + } + if (err == 0) { + x = PyTuple_Pack(1, v); + if (x == NULL) + err = -1; + } + if (err == 0) { + w = PyEval_CallObject(w, x); + Py_XDECREF(w); + if (w == NULL) + err = -1; + } + Py_DECREF(v); + Py_XDECREF(x); + break; #ifdef CASE_TOO_BIG - default: switch (opcode) { + default: switch (opcode) { #endif - TARGET(RAISE_VARARGS) - v = w = NULL; - switch (oparg) { - case 2: - v = POP(); /* cause */ - case 1: - w = POP(); /* exc */ - case 0: /* Fallthrough */ - why = do_raise(w, v); - break; - default: - PyErr_SetString(PyExc_SystemError, - "bad RAISE_VARARGS oparg"); - why = WHY_EXCEPTION; - break; - } - break; - - TARGET(STORE_LOCALS) - x = POP(); - v = f->f_locals; - Py_XDECREF(v); - f->f_locals = x; - DISPATCH(); - - TARGET(RETURN_VALUE) - retval = POP(); - why = WHY_RETURN; - goto fast_block_end; - - TARGET(YIELD_VALUE) - retval = POP(); - f->f_stacktop = stack_pointer; - why = WHY_YIELD; - /* Put aside the current exception state and restore - that of the calling frame. This only serves when - "yield" is used inside an except handler. */ - SWAP_EXC_STATE(); - goto fast_yield; - - TARGET(POP_EXCEPT) - { - PyTryBlock *b = PyFrame_BlockPop(f); - if (b->b_type != EXCEPT_HANDLER) { - PyErr_SetString(PyExc_SystemError, - "popped block is not an except handler"); - why = WHY_EXCEPTION; - break; - } - UNWIND_EXCEPT_HANDLER(b); - } - DISPATCH(); - - TARGET(POP_BLOCK) - { - PyTryBlock *b = PyFrame_BlockPop(f); - UNWIND_BLOCK(b); - } - DISPATCH(); - - PREDICTED(END_FINALLY); - TARGET(END_FINALLY) - v = POP(); - if (PyLong_Check(v)) { - why = (enum why_code) PyLong_AS_LONG(v); - assert(why != WHY_YIELD); - if (why == WHY_RETURN || - why == WHY_CONTINUE) - retval = POP(); - if (why == WHY_SILENCED) { - /* An exception was silenced by 'with', we must - manually unwind the EXCEPT_HANDLER block which was - created when the exception was caught, otherwise - the stack will be in an inconsistent state. */ - PyTryBlock *b = PyFrame_BlockPop(f); - assert(b->b_type == EXCEPT_HANDLER); - UNWIND_EXCEPT_HANDLER(b); - why = WHY_NOT; - } - } - else if (PyExceptionClass_Check(v)) { - w = POP(); - u = POP(); - PyErr_Restore(v, w, u); - why = WHY_RERAISE; - break; - } - else if (v != Py_None) { - PyErr_SetString(PyExc_SystemError, - "'finally' pops bad exception"); - why = WHY_EXCEPTION; - } - Py_DECREF(v); - break; - - TARGET(LOAD_BUILD_CLASS) - x = PyDict_GetItemString(f->f_builtins, - "__build_class__"); - if (x == NULL) { - PyErr_SetString(PyExc_ImportError, - "__build_class__ not found"); - break; - } - Py_INCREF(x); - PUSH(x); - break; - - TARGET(STORE_NAME) - w = GETITEM(names, oparg); - v = POP(); - if ((x = f->f_locals) != NULL) { - if (PyDict_CheckExact(x)) - err = PyDict_SetItem(x, w, v); - else - err = PyObject_SetItem(x, w, v); - Py_DECREF(v); - if (err == 0) DISPATCH(); - break; - } - PyErr_Format(PyExc_SystemError, - "no locals found when storing %R", w); - break; - - TARGET(DELETE_NAME) - w = GETITEM(names, oparg); - if ((x = f->f_locals) != NULL) { - if ((err = PyObject_DelItem(x, w)) != 0) - format_exc_check_arg(PyExc_NameError, - NAME_ERROR_MSG, - w); - break; - } - PyErr_Format(PyExc_SystemError, - "no locals when deleting %R", w); - break; - - PREDICTED_WITH_ARG(UNPACK_SEQUENCE); - TARGET(UNPACK_SEQUENCE) - v = POP(); - if (PyTuple_CheckExact(v) && - PyTuple_GET_SIZE(v) == oparg) { - PyObject **items = \ - ((PyTupleObject *)v)->ob_item; - while (oparg--) { - w = items[oparg]; - Py_INCREF(w); - PUSH(w); - } - Py_DECREF(v); - DISPATCH(); - } else if (PyList_CheckExact(v) && - PyList_GET_SIZE(v) == oparg) { - PyObject **items = \ - ((PyListObject *)v)->ob_item; - while (oparg--) { - w = items[oparg]; - Py_INCREF(w); - PUSH(w); - } - } else if (unpack_iterable(v, oparg, -1, - stack_pointer + oparg)) { - STACKADJ(oparg); - } else { - /* unpack_iterable() raised an exception */ - why = WHY_EXCEPTION; - } - Py_DECREF(v); - break; - - TARGET(UNPACK_EX) - { - int totalargs = 1 + (oparg & 0xFF) + (oparg >> 8); - v = POP(); - - if (unpack_iterable(v, oparg & 0xFF, oparg >> 8, - stack_pointer + totalargs)) { - stack_pointer += totalargs; - } else { - why = WHY_EXCEPTION; - } - Py_DECREF(v); - break; - } - - TARGET(STORE_ATTR) - w = GETITEM(names, oparg); - v = TOP(); - u = SECOND(); - STACKADJ(-2); - err = PyObject_SetAttr(v, w, u); /* v.w = u */ - Py_DECREF(v); - Py_DECREF(u); - if (err == 0) DISPATCH(); - break; - - TARGET(DELETE_ATTR) - w = GETITEM(names, oparg); - v = POP(); - err = PyObject_SetAttr(v, w, (PyObject *)NULL); - /* del v.w */ - Py_DECREF(v); - break; - - TARGET(STORE_GLOBAL) - w = GETITEM(names, oparg); - v = POP(); - err = PyDict_SetItem(f->f_globals, w, v); - Py_DECREF(v); - if (err == 0) DISPATCH(); - break; - - TARGET(DELETE_GLOBAL) - w = GETITEM(names, oparg); - if ((err = PyDict_DelItem(f->f_globals, w)) != 0) - format_exc_check_arg( - PyExc_NameError, GLOBAL_NAME_ERROR_MSG, w); - break; - - TARGET(LOAD_NAME) - w = GETITEM(names, oparg); - if ((v = f->f_locals) == NULL) { - PyErr_Format(PyExc_SystemError, - "no locals when loading %R", w); - why = WHY_EXCEPTION; - break; - } - if (PyDict_CheckExact(v)) { - x = PyDict_GetItem(v, w); - Py_XINCREF(x); - } - else { - x = PyObject_GetItem(v, w); - if (x == NULL && PyErr_Occurred()) { - if (!PyErr_ExceptionMatches( - PyExc_KeyError)) - break; - PyErr_Clear(); - } - } - if (x == NULL) { - x = PyDict_GetItem(f->f_globals, w); - if (x == NULL) { - x = PyDict_GetItem(f->f_builtins, w); - if (x == NULL) { - format_exc_check_arg( - PyExc_NameError, - NAME_ERROR_MSG, w); - break; - } - } - Py_INCREF(x); - } - PUSH(x); - DISPATCH(); - - TARGET(LOAD_GLOBAL) - w = GETITEM(names, oparg); - if (PyUnicode_CheckExact(w)) { - /* Inline the PyDict_GetItem() calls. - WARNING: this is an extreme speed hack. - Do not try this at home. */ - long hash = ((PyUnicodeObject *)w)->hash; - if (hash != -1) { - PyDictObject *d; - PyDictEntry *e; - d = (PyDictObject *)(f->f_globals); - e = d->ma_lookup(d, w, hash); - if (e == NULL) { - x = NULL; - break; - } - x = e->me_value; - if (x != NULL) { - Py_INCREF(x); - PUSH(x); - DISPATCH(); - } - d = (PyDictObject *)(f->f_builtins); - e = d->ma_lookup(d, w, hash); - if (e == NULL) { - x = NULL; - break; - } - x = e->me_value; - if (x != NULL) { - Py_INCREF(x); - PUSH(x); - DISPATCH(); - } - goto load_global_error; - } - } - /* This is the un-inlined version of the code above */ - x = PyDict_GetItem(f->f_globals, w); - if (x == NULL) { - x = PyDict_GetItem(f->f_builtins, w); - if (x == NULL) { - load_global_error: - format_exc_check_arg( - PyExc_NameError, - GLOBAL_NAME_ERROR_MSG, w); - break; - } - } - Py_INCREF(x); - PUSH(x); - DISPATCH(); - - TARGET(DELETE_FAST) - x = GETLOCAL(oparg); - if (x != NULL) { - SETLOCAL(oparg, NULL); - DISPATCH(); - } - format_exc_check_arg( - PyExc_UnboundLocalError, - UNBOUNDLOCAL_ERROR_MSG, - PyTuple_GetItem(co->co_varnames, oparg) - ); - break; - - TARGET(LOAD_CLOSURE) - x = freevars[oparg]; - Py_INCREF(x); - PUSH(x); - if (x != NULL) DISPATCH(); - break; - - TARGET(LOAD_DEREF) - x = freevars[oparg]; - w = PyCell_Get(x); - if (w != NULL) { - PUSH(w); - DISPATCH(); - } - err = -1; - /* Don't stomp existing exception */ - if (PyErr_Occurred()) - break; - if (oparg < PyTuple_GET_SIZE(co->co_cellvars)) { - v = PyTuple_GET_ITEM(co->co_cellvars, - oparg); - format_exc_check_arg( - PyExc_UnboundLocalError, - UNBOUNDLOCAL_ERROR_MSG, - v); - } else { - v = PyTuple_GET_ITEM(co->co_freevars, oparg - - PyTuple_GET_SIZE(co->co_cellvars)); - format_exc_check_arg(PyExc_NameError, - UNBOUNDFREE_ERROR_MSG, v); - } - break; - - TARGET(STORE_DEREF) - w = POP(); - x = freevars[oparg]; - PyCell_Set(x, w); - Py_DECREF(w); - DISPATCH(); - - TARGET(BUILD_TUPLE) - x = PyTuple_New(oparg); - if (x != NULL) { - for (; --oparg >= 0;) { - w = POP(); - PyTuple_SET_ITEM(x, oparg, w); - } - PUSH(x); - DISPATCH(); - } - break; - - TARGET(BUILD_LIST) - x = PyList_New(oparg); - if (x != NULL) { - for (; --oparg >= 0;) { - w = POP(); - PyList_SET_ITEM(x, oparg, w); - } - PUSH(x); - DISPATCH(); - } - break; - - TARGET(BUILD_SET) - x = PySet_New(NULL); - if (x != NULL) { - for (; --oparg >= 0;) { - w = POP(); - if (err == 0) - err = PySet_Add(x, w); - Py_DECREF(w); - } - if (err != 0) { - Py_DECREF(x); - break; - } - PUSH(x); - DISPATCH(); - } - break; - - TARGET(BUILD_MAP) - x = _PyDict_NewPresized((Py_ssize_t)oparg); - PUSH(x); - if (x != NULL) DISPATCH(); - break; - - TARGET(STORE_MAP) - w = TOP(); /* key */ - u = SECOND(); /* value */ - v = THIRD(); /* dict */ - STACKADJ(-2); - assert (PyDict_CheckExact(v)); - err = PyDict_SetItem(v, w, u); /* v[w] = u */ - Py_DECREF(u); - Py_DECREF(w); - if (err == 0) DISPATCH(); - break; - - TARGET(MAP_ADD) - w = TOP(); /* key */ - u = SECOND(); /* value */ - STACKADJ(-2); - v = stack_pointer[-oparg]; /* dict */ - assert (PyDict_CheckExact(v)); - err = PyDict_SetItem(v, w, u); /* v[w] = u */ - Py_DECREF(u); - Py_DECREF(w); - if (err == 0) { - PREDICT(JUMP_ABSOLUTE); - DISPATCH(); - } - break; - - TARGET(LOAD_ATTR) - w = GETITEM(names, oparg); - v = TOP(); - x = PyObject_GetAttr(v, w); - Py_DECREF(v); - SET_TOP(x); - if (x != NULL) DISPATCH(); - break; - - TARGET(COMPARE_OP) - w = POP(); - v = TOP(); - x = cmp_outcome(oparg, v, w); - Py_DECREF(v); - Py_DECREF(w); - SET_TOP(x); - if (x == NULL) break; - PREDICT(POP_JUMP_IF_FALSE); - PREDICT(POP_JUMP_IF_TRUE); - DISPATCH(); - - TARGET(IMPORT_NAME) - w = GETITEM(names, oparg); - x = PyDict_GetItemString(f->f_builtins, "__import__"); - if (x == NULL) { - PyErr_SetString(PyExc_ImportError, - "__import__ not found"); - break; - } - Py_INCREF(x); - v = POP(); - u = TOP(); - if (PyLong_AsLong(u) != -1 || PyErr_Occurred()) - w = PyTuple_Pack(5, - w, - f->f_globals, - f->f_locals == NULL ? - Py_None : f->f_locals, - v, - u); - else - w = PyTuple_Pack(4, - w, - f->f_globals, - f->f_locals == NULL ? - Py_None : f->f_locals, - v); - Py_DECREF(v); - Py_DECREF(u); - if (w == NULL) { - u = POP(); - Py_DECREF(x); - x = NULL; - break; - } - READ_TIMESTAMP(intr0); - v = x; - x = PyEval_CallObject(v, w); - Py_DECREF(v); - READ_TIMESTAMP(intr1); - Py_DECREF(w); - SET_TOP(x); - if (x != NULL) DISPATCH(); - break; - - TARGET(IMPORT_STAR) - v = POP(); - PyFrame_FastToLocals(f); - if ((x = f->f_locals) == NULL) { - PyErr_SetString(PyExc_SystemError, - "no locals found during 'import *'"); - break; - } - READ_TIMESTAMP(intr0); - err = import_all_from(x, v); - READ_TIMESTAMP(intr1); - PyFrame_LocalsToFast(f, 0); - Py_DECREF(v); - if (err == 0) DISPATCH(); - break; - - TARGET(IMPORT_FROM) - w = GETITEM(names, oparg); - v = TOP(); - READ_TIMESTAMP(intr0); - x = import_from(v, w); - READ_TIMESTAMP(intr1); - PUSH(x); - if (x != NULL) DISPATCH(); - break; - - TARGET(JUMP_FORWARD) - JUMPBY(oparg); - FAST_DISPATCH(); - - PREDICTED_WITH_ARG(POP_JUMP_IF_FALSE); - TARGET(POP_JUMP_IF_FALSE) - w = POP(); - if (w == Py_True) { - Py_DECREF(w); - FAST_DISPATCH(); - } - if (w == Py_False) { - Py_DECREF(w); - JUMPTO(oparg); - FAST_DISPATCH(); - } - err = PyObject_IsTrue(w); - Py_DECREF(w); - if (err > 0) - err = 0; - else if (err == 0) - JUMPTO(oparg); - else - break; - DISPATCH(); - - PREDICTED_WITH_ARG(POP_JUMP_IF_TRUE); - TARGET(POP_JUMP_IF_TRUE) - w = POP(); - if (w == Py_False) { - Py_DECREF(w); - FAST_DISPATCH(); - } - if (w == Py_True) { - Py_DECREF(w); - JUMPTO(oparg); - FAST_DISPATCH(); - } - err = PyObject_IsTrue(w); - Py_DECREF(w); - if (err > 0) { - err = 0; - JUMPTO(oparg); - } - else if (err == 0) - ; - else - break; - DISPATCH(); - - TARGET(JUMP_IF_FALSE_OR_POP) - w = TOP(); - if (w == Py_True) { - STACKADJ(-1); - Py_DECREF(w); - FAST_DISPATCH(); - } - if (w == Py_False) { - JUMPTO(oparg); - FAST_DISPATCH(); - } - err = PyObject_IsTrue(w); - if (err > 0) { - STACKADJ(-1); - Py_DECREF(w); - err = 0; - } - else if (err == 0) - JUMPTO(oparg); - else - break; - DISPATCH(); - - TARGET(JUMP_IF_TRUE_OR_POP) - w = TOP(); - if (w == Py_False) { - STACKADJ(-1); - Py_DECREF(w); - FAST_DISPATCH(); - } - if (w == Py_True) { - JUMPTO(oparg); - FAST_DISPATCH(); - } - err = PyObject_IsTrue(w); - if (err > 0) { - err = 0; - JUMPTO(oparg); - } - else if (err == 0) { - STACKADJ(-1); - Py_DECREF(w); - } - else - break; - DISPATCH(); - - PREDICTED_WITH_ARG(JUMP_ABSOLUTE); - TARGET(JUMP_ABSOLUTE) - JUMPTO(oparg); + TARGET(RAISE_VARARGS) + v = w = NULL; + switch (oparg) { + case 2: + v = POP(); /* cause */ + case 1: + w = POP(); /* exc */ + case 0: /* Fallthrough */ + why = do_raise(w, v); + break; + default: + PyErr_SetString(PyExc_SystemError, + "bad RAISE_VARARGS oparg"); + why = WHY_EXCEPTION; + break; + } + break; + + TARGET(STORE_LOCALS) + x = POP(); + v = f->f_locals; + Py_XDECREF(v); + f->f_locals = x; + DISPATCH(); + + TARGET(RETURN_VALUE) + retval = POP(); + why = WHY_RETURN; + goto fast_block_end; + + TARGET(YIELD_VALUE) + retval = POP(); + f->f_stacktop = stack_pointer; + why = WHY_YIELD; + /* Put aside the current exception state and restore + that of the calling frame. This only serves when + "yield" is used inside an except handler. */ + SWAP_EXC_STATE(); + goto fast_yield; + + TARGET(POP_EXCEPT) + { + PyTryBlock *b = PyFrame_BlockPop(f); + if (b->b_type != EXCEPT_HANDLER) { + PyErr_SetString(PyExc_SystemError, + "popped block is not an except handler"); + why = WHY_EXCEPTION; + break; + } + UNWIND_EXCEPT_HANDLER(b); + } + DISPATCH(); + + TARGET(POP_BLOCK) + { + PyTryBlock *b = PyFrame_BlockPop(f); + UNWIND_BLOCK(b); + } + DISPATCH(); + + PREDICTED(END_FINALLY); + TARGET(END_FINALLY) + v = POP(); + if (PyLong_Check(v)) { + why = (enum why_code) PyLong_AS_LONG(v); + assert(why != WHY_YIELD); + if (why == WHY_RETURN || + why == WHY_CONTINUE) + retval = POP(); + if (why == WHY_SILENCED) { + /* An exception was silenced by 'with', we must + manually unwind the EXCEPT_HANDLER block which was + created when the exception was caught, otherwise + the stack will be in an inconsistent state. */ + PyTryBlock *b = PyFrame_BlockPop(f); + assert(b->b_type == EXCEPT_HANDLER); + UNWIND_EXCEPT_HANDLER(b); + why = WHY_NOT; + } + } + else if (PyExceptionClass_Check(v)) { + w = POP(); + u = POP(); + PyErr_Restore(v, w, u); + why = WHY_RERAISE; + break; + } + else if (v != Py_None) { + PyErr_SetString(PyExc_SystemError, + "'finally' pops bad exception"); + why = WHY_EXCEPTION; + } + Py_DECREF(v); + break; + + TARGET(LOAD_BUILD_CLASS) + x = PyDict_GetItemString(f->f_builtins, + "__build_class__"); + if (x == NULL) { + PyErr_SetString(PyExc_ImportError, + "__build_class__ not found"); + break; + } + Py_INCREF(x); + PUSH(x); + break; + + TARGET(STORE_NAME) + w = GETITEM(names, oparg); + v = POP(); + if ((x = f->f_locals) != NULL) { + if (PyDict_CheckExact(x)) + err = PyDict_SetItem(x, w, v); + else + err = PyObject_SetItem(x, w, v); + Py_DECREF(v); + if (err == 0) DISPATCH(); + break; + } + PyErr_Format(PyExc_SystemError, + "no locals found when storing %R", w); + break; + + TARGET(DELETE_NAME) + w = GETITEM(names, oparg); + if ((x = f->f_locals) != NULL) { + if ((err = PyObject_DelItem(x, w)) != 0) + format_exc_check_arg(PyExc_NameError, + NAME_ERROR_MSG, + w); + break; + } + PyErr_Format(PyExc_SystemError, + "no locals when deleting %R", w); + break; + + PREDICTED_WITH_ARG(UNPACK_SEQUENCE); + TARGET(UNPACK_SEQUENCE) + v = POP(); + if (PyTuple_CheckExact(v) && + PyTuple_GET_SIZE(v) == oparg) { + PyObject **items = \ + ((PyTupleObject *)v)->ob_item; + while (oparg--) { + w = items[oparg]; + Py_INCREF(w); + PUSH(w); + } + Py_DECREF(v); + DISPATCH(); + } else if (PyList_CheckExact(v) && + PyList_GET_SIZE(v) == oparg) { + PyObject **items = \ + ((PyListObject *)v)->ob_item; + while (oparg--) { + w = items[oparg]; + Py_INCREF(w); + PUSH(w); + } + } else if (unpack_iterable(v, oparg, -1, + stack_pointer + oparg)) { + STACKADJ(oparg); + } else { + /* unpack_iterable() raised an exception */ + why = WHY_EXCEPTION; + } + Py_DECREF(v); + break; + + TARGET(UNPACK_EX) + { + int totalargs = 1 + (oparg & 0xFF) + (oparg >> 8); + v = POP(); + + if (unpack_iterable(v, oparg & 0xFF, oparg >> 8, + stack_pointer + totalargs)) { + stack_pointer += totalargs; + } else { + why = WHY_EXCEPTION; + } + Py_DECREF(v); + break; + } + + TARGET(STORE_ATTR) + w = GETITEM(names, oparg); + v = TOP(); + u = SECOND(); + STACKADJ(-2); + err = PyObject_SetAttr(v, w, u); /* v.w = u */ + Py_DECREF(v); + Py_DECREF(u); + if (err == 0) DISPATCH(); + break; + + TARGET(DELETE_ATTR) + w = GETITEM(names, oparg); + v = POP(); + err = PyObject_SetAttr(v, w, (PyObject *)NULL); + /* del v.w */ + Py_DECREF(v); + break; + + TARGET(STORE_GLOBAL) + w = GETITEM(names, oparg); + v = POP(); + err = PyDict_SetItem(f->f_globals, w, v); + Py_DECREF(v); + if (err == 0) DISPATCH(); + break; + + TARGET(DELETE_GLOBAL) + w = GETITEM(names, oparg); + if ((err = PyDict_DelItem(f->f_globals, w)) != 0) + format_exc_check_arg( + PyExc_NameError, GLOBAL_NAME_ERROR_MSG, w); + break; + + TARGET(LOAD_NAME) + w = GETITEM(names, oparg); + if ((v = f->f_locals) == NULL) { + PyErr_Format(PyExc_SystemError, + "no locals when loading %R", w); + why = WHY_EXCEPTION; + break; + } + if (PyDict_CheckExact(v)) { + x = PyDict_GetItem(v, w); + Py_XINCREF(x); + } + else { + x = PyObject_GetItem(v, w); + if (x == NULL && PyErr_Occurred()) { + if (!PyErr_ExceptionMatches( + PyExc_KeyError)) + break; + PyErr_Clear(); + } + } + if (x == NULL) { + x = PyDict_GetItem(f->f_globals, w); + if (x == NULL) { + x = PyDict_GetItem(f->f_builtins, w); + if (x == NULL) { + format_exc_check_arg( + PyExc_NameError, + NAME_ERROR_MSG, w); + break; + } + } + Py_INCREF(x); + } + PUSH(x); + DISPATCH(); + + TARGET(LOAD_GLOBAL) + w = GETITEM(names, oparg); + if (PyUnicode_CheckExact(w)) { + /* Inline the PyDict_GetItem() calls. + WARNING: this is an extreme speed hack. + Do not try this at home. */ + long hash = ((PyUnicodeObject *)w)->hash; + if (hash != -1) { + PyDictObject *d; + PyDictEntry *e; + d = (PyDictObject *)(f->f_globals); + e = d->ma_lookup(d, w, hash); + if (e == NULL) { + x = NULL; + break; + } + x = e->me_value; + if (x != NULL) { + Py_INCREF(x); + PUSH(x); + DISPATCH(); + } + d = (PyDictObject *)(f->f_builtins); + e = d->ma_lookup(d, w, hash); + if (e == NULL) { + x = NULL; + break; + } + x = e->me_value; + if (x != NULL) { + Py_INCREF(x); + PUSH(x); + DISPATCH(); + } + goto load_global_error; + } + } + /* This is the un-inlined version of the code above */ + x = PyDict_GetItem(f->f_globals, w); + if (x == NULL) { + x = PyDict_GetItem(f->f_builtins, w); + if (x == NULL) { + load_global_error: + format_exc_check_arg( + PyExc_NameError, + GLOBAL_NAME_ERROR_MSG, w); + break; + } + } + Py_INCREF(x); + PUSH(x); + DISPATCH(); + + TARGET(DELETE_FAST) + x = GETLOCAL(oparg); + if (x != NULL) { + SETLOCAL(oparg, NULL); + DISPATCH(); + } + format_exc_check_arg( + PyExc_UnboundLocalError, + UNBOUNDLOCAL_ERROR_MSG, + PyTuple_GetItem(co->co_varnames, oparg) + ); + break; + + TARGET(LOAD_CLOSURE) + x = freevars[oparg]; + Py_INCREF(x); + PUSH(x); + if (x != NULL) DISPATCH(); + break; + + TARGET(LOAD_DEREF) + x = freevars[oparg]; + w = PyCell_Get(x); + if (w != NULL) { + PUSH(w); + DISPATCH(); + } + err = -1; + /* Don't stomp existing exception */ + if (PyErr_Occurred()) + break; + if (oparg < PyTuple_GET_SIZE(co->co_cellvars)) { + v = PyTuple_GET_ITEM(co->co_cellvars, + oparg); + format_exc_check_arg( + PyExc_UnboundLocalError, + UNBOUNDLOCAL_ERROR_MSG, + v); + } else { + v = PyTuple_GET_ITEM(co->co_freevars, oparg - + PyTuple_GET_SIZE(co->co_cellvars)); + format_exc_check_arg(PyExc_NameError, + UNBOUNDFREE_ERROR_MSG, v); + } + break; + + TARGET(STORE_DEREF) + w = POP(); + x = freevars[oparg]; + PyCell_Set(x, w); + Py_DECREF(w); + DISPATCH(); + + TARGET(BUILD_TUPLE) + x = PyTuple_New(oparg); + if (x != NULL) { + for (; --oparg >= 0;) { + w = POP(); + PyTuple_SET_ITEM(x, oparg, w); + } + PUSH(x); + DISPATCH(); + } + break; + + TARGET(BUILD_LIST) + x = PyList_New(oparg); + if (x != NULL) { + for (; --oparg >= 0;) { + w = POP(); + PyList_SET_ITEM(x, oparg, w); + } + PUSH(x); + DISPATCH(); + } + break; + + TARGET(BUILD_SET) + x = PySet_New(NULL); + if (x != NULL) { + for (; --oparg >= 0;) { + w = POP(); + if (err == 0) + err = PySet_Add(x, w); + Py_DECREF(w); + } + if (err != 0) { + Py_DECREF(x); + break; + } + PUSH(x); + DISPATCH(); + } + break; + + TARGET(BUILD_MAP) + x = _PyDict_NewPresized((Py_ssize_t)oparg); + PUSH(x); + if (x != NULL) DISPATCH(); + break; + + TARGET(STORE_MAP) + w = TOP(); /* key */ + u = SECOND(); /* value */ + v = THIRD(); /* dict */ + STACKADJ(-2); + assert (PyDict_CheckExact(v)); + err = PyDict_SetItem(v, w, u); /* v[w] = u */ + Py_DECREF(u); + Py_DECREF(w); + if (err == 0) DISPATCH(); + break; + + TARGET(MAP_ADD) + w = TOP(); /* key */ + u = SECOND(); /* value */ + STACKADJ(-2); + v = stack_pointer[-oparg]; /* dict */ + assert (PyDict_CheckExact(v)); + err = PyDict_SetItem(v, w, u); /* v[w] = u */ + Py_DECREF(u); + Py_DECREF(w); + if (err == 0) { + PREDICT(JUMP_ABSOLUTE); + DISPATCH(); + } + break; + + TARGET(LOAD_ATTR) + w = GETITEM(names, oparg); + v = TOP(); + x = PyObject_GetAttr(v, w); + Py_DECREF(v); + SET_TOP(x); + if (x != NULL) DISPATCH(); + break; + + TARGET(COMPARE_OP) + w = POP(); + v = TOP(); + x = cmp_outcome(oparg, v, w); + Py_DECREF(v); + Py_DECREF(w); + SET_TOP(x); + if (x == NULL) break; + PREDICT(POP_JUMP_IF_FALSE); + PREDICT(POP_JUMP_IF_TRUE); + DISPATCH(); + + TARGET(IMPORT_NAME) + w = GETITEM(names, oparg); + x = PyDict_GetItemString(f->f_builtins, "__import__"); + if (x == NULL) { + PyErr_SetString(PyExc_ImportError, + "__import__ not found"); + break; + } + Py_INCREF(x); + v = POP(); + u = TOP(); + if (PyLong_AsLong(u) != -1 || PyErr_Occurred()) + w = PyTuple_Pack(5, + w, + f->f_globals, + f->f_locals == NULL ? + Py_None : f->f_locals, + v, + u); + else + w = PyTuple_Pack(4, + w, + f->f_globals, + f->f_locals == NULL ? + Py_None : f->f_locals, + v); + Py_DECREF(v); + Py_DECREF(u); + if (w == NULL) { + u = POP(); + Py_DECREF(x); + x = NULL; + break; + } + READ_TIMESTAMP(intr0); + v = x; + x = PyEval_CallObject(v, w); + Py_DECREF(v); + READ_TIMESTAMP(intr1); + Py_DECREF(w); + SET_TOP(x); + if (x != NULL) DISPATCH(); + break; + + TARGET(IMPORT_STAR) + v = POP(); + PyFrame_FastToLocals(f); + if ((x = f->f_locals) == NULL) { + PyErr_SetString(PyExc_SystemError, + "no locals found during 'import *'"); + break; + } + READ_TIMESTAMP(intr0); + err = import_all_from(x, v); + READ_TIMESTAMP(intr1); + PyFrame_LocalsToFast(f, 0); + Py_DECREF(v); + if (err == 0) DISPATCH(); + break; + + TARGET(IMPORT_FROM) + w = GETITEM(names, oparg); + v = TOP(); + READ_TIMESTAMP(intr0); + x = import_from(v, w); + READ_TIMESTAMP(intr1); + PUSH(x); + if (x != NULL) DISPATCH(); + break; + + TARGET(JUMP_FORWARD) + JUMPBY(oparg); + FAST_DISPATCH(); + + PREDICTED_WITH_ARG(POP_JUMP_IF_FALSE); + TARGET(POP_JUMP_IF_FALSE) + w = POP(); + if (w == Py_True) { + Py_DECREF(w); + FAST_DISPATCH(); + } + if (w == Py_False) { + Py_DECREF(w); + JUMPTO(oparg); + FAST_DISPATCH(); + } + err = PyObject_IsTrue(w); + Py_DECREF(w); + if (err > 0) + err = 0; + else if (err == 0) + JUMPTO(oparg); + else + break; + DISPATCH(); + + PREDICTED_WITH_ARG(POP_JUMP_IF_TRUE); + TARGET(POP_JUMP_IF_TRUE) + w = POP(); + if (w == Py_False) { + Py_DECREF(w); + FAST_DISPATCH(); + } + if (w == Py_True) { + Py_DECREF(w); + JUMPTO(oparg); + FAST_DISPATCH(); + } + err = PyObject_IsTrue(w); + Py_DECREF(w); + if (err > 0) { + err = 0; + JUMPTO(oparg); + } + else if (err == 0) + ; + else + break; + DISPATCH(); + + TARGET(JUMP_IF_FALSE_OR_POP) + w = TOP(); + if (w == Py_True) { + STACKADJ(-1); + Py_DECREF(w); + FAST_DISPATCH(); + } + if (w == Py_False) { + JUMPTO(oparg); + FAST_DISPATCH(); + } + err = PyObject_IsTrue(w); + if (err > 0) { + STACKADJ(-1); + Py_DECREF(w); + err = 0; + } + else if (err == 0) + JUMPTO(oparg); + else + break; + DISPATCH(); + + TARGET(JUMP_IF_TRUE_OR_POP) + w = TOP(); + if (w == Py_False) { + STACKADJ(-1); + Py_DECREF(w); + FAST_DISPATCH(); + } + if (w == Py_True) { + JUMPTO(oparg); + FAST_DISPATCH(); + } + err = PyObject_IsTrue(w); + if (err > 0) { + err = 0; + JUMPTO(oparg); + } + else if (err == 0) { + STACKADJ(-1); + Py_DECREF(w); + } + else + break; + DISPATCH(); + + PREDICTED_WITH_ARG(JUMP_ABSOLUTE); + TARGET(JUMP_ABSOLUTE) + JUMPTO(oparg); #if FAST_LOOPS - /* Enabling this path speeds-up all while and for-loops by bypassing - the per-loop checks for signals. By default, this should be turned-off - because it prevents detection of a control-break in tight loops like - "while 1: pass". Compile with this option turned-on when you need - the speed-up and do not need break checking inside tight loops (ones - that contain only instructions ending with FAST_DISPATCH). - */ - FAST_DISPATCH(); + /* Enabling this path speeds-up all while and for-loops by bypassing + the per-loop checks for signals. By default, this should be turned-off + because it prevents detection of a control-break in tight loops like + "while 1: pass". Compile with this option turned-on when you need + the speed-up and do not need break checking inside tight loops (ones + that contain only instructions ending with FAST_DISPATCH). + */ + FAST_DISPATCH(); #else - DISPATCH(); + DISPATCH(); #endif - TARGET(GET_ITER) - /* before: [obj]; after [getiter(obj)] */ - v = TOP(); - x = PyObject_GetIter(v); - Py_DECREF(v); - if (x != NULL) { - SET_TOP(x); - PREDICT(FOR_ITER); - DISPATCH(); - } - STACKADJ(-1); - break; - - PREDICTED_WITH_ARG(FOR_ITER); - TARGET(FOR_ITER) - /* before: [iter]; after: [iter, iter()] *or* [] */ - v = TOP(); - x = (*v->ob_type->tp_iternext)(v); - if (x != NULL) { - PUSH(x); - PREDICT(STORE_FAST); - PREDICT(UNPACK_SEQUENCE); - DISPATCH(); - } - if (PyErr_Occurred()) { - if (!PyErr_ExceptionMatches( - PyExc_StopIteration)) - break; - PyErr_Clear(); - } - /* iterator ended normally */ - x = v = POP(); - Py_DECREF(v); - JUMPBY(oparg); - DISPATCH(); - - TARGET(BREAK_LOOP) - why = WHY_BREAK; - goto fast_block_end; - - TARGET(CONTINUE_LOOP) - retval = PyLong_FromLong(oparg); - if (!retval) { - x = NULL; - break; - } - why = WHY_CONTINUE; - goto fast_block_end; - - TARGET_WITH_IMPL(SETUP_LOOP, _setup_finally) - TARGET_WITH_IMPL(SETUP_EXCEPT, _setup_finally) - TARGET(SETUP_FINALLY) - _setup_finally: - /* NOTE: If you add any new block-setup opcodes that - are not try/except/finally handlers, you may need - to update the PyGen_NeedsFinalizing() function. - */ - - PyFrame_BlockSetup(f, opcode, INSTR_OFFSET() + oparg, - STACK_LEVEL()); - DISPATCH(); - - TARGET(SETUP_WITH) - { - static PyObject *exit, *enter; - w = TOP(); - x = special_lookup(w, "__exit__", &exit); - if (!x) - break; - SET_TOP(x); - u = special_lookup(w, "__enter__", &enter); - Py_DECREF(w); - if (!u) { - x = NULL; - break; - } - x = PyObject_CallFunctionObjArgs(u, NULL); - Py_DECREF(u); - if (!x) - break; - /* Setup the finally block before pushing the result - of __enter__ on the stack. */ - PyFrame_BlockSetup(f, SETUP_FINALLY, INSTR_OFFSET() + oparg, - STACK_LEVEL()); - - PUSH(x); - DISPATCH(); - } - - TARGET(WITH_CLEANUP) - { - /* At the top of the stack are 1-3 values indicating - how/why we entered the finally clause: - - TOP = None - - (TOP, SECOND) = (WHY_{RETURN,CONTINUE}), retval - - TOP = WHY_*; no retval below it - - (TOP, SECOND, THIRD) = exc_info() - (FOURTH, FITH, SIXTH) = previous exception for EXCEPT_HANDLER - Below them is EXIT, the context.__exit__ bound method. - In the last case, we must call - EXIT(TOP, SECOND, THIRD) - otherwise we must call - EXIT(None, None, None) - - In the first two cases, we remove EXIT from the - stack, leaving the rest in the same order. In the - third case, we shift the bottom 3 values of the - stack down, and replace the empty spot with NULL. - - In addition, if the stack represents an exception, - *and* the function call returns a 'true' value, we - push WHY_SILENCED onto the stack. END_FINALLY will - then not re-raise the exception. (But non-local - gotos should still be resumed.) - */ - - PyObject *exit_func; - u = TOP(); - if (u == Py_None) { - (void)POP(); - exit_func = TOP(); - SET_TOP(u); - v = w = Py_None; - } - else if (PyLong_Check(u)) { - (void)POP(); - switch(PyLong_AsLong(u)) { - case WHY_RETURN: - case WHY_CONTINUE: - /* Retval in TOP. */ - exit_func = SECOND(); - SET_SECOND(TOP()); - SET_TOP(u); - break; - default: - exit_func = TOP(); - SET_TOP(u); - break; - } - u = v = w = Py_None; - } - else { - PyObject *tp, *exc, *tb; - PyTryBlock *block; - v = SECOND(); - w = THIRD(); - tp = FOURTH(); - exc = PEEK(5); - tb = PEEK(6); - exit_func = PEEK(7); - SET_VALUE(7, tb); - SET_VALUE(6, exc); - SET_VALUE(5, tp); - /* UNWIND_EXCEPT_HANDLER will pop this off. */ - SET_FOURTH(NULL); - /* We just shifted the stack down, so we have - to tell the except handler block that the - values are lower than it expects. */ - block = &f->f_blockstack[f->f_iblock - 1]; - assert(block->b_type == EXCEPT_HANDLER); - block->b_level--; - } - /* XXX Not the fastest way to call it... */ - x = PyObject_CallFunctionObjArgs(exit_func, u, v, w, - NULL); - Py_DECREF(exit_func); - if (x == NULL) - break; /* Go to error exit */ - - if (u != Py_None) - err = PyObject_IsTrue(x); - else - err = 0; - Py_DECREF(x); - - if (err < 0) - break; /* Go to error exit */ - else if (err > 0) { - err = 0; - /* There was an exception and a True return */ - PUSH(PyLong_FromLong((long) WHY_SILENCED)); - } - PREDICT(END_FINALLY); - break; - } - - TARGET(CALL_FUNCTION) - { - PyObject **sp; - PCALL(PCALL_ALL); - sp = stack_pointer; + TARGET(GET_ITER) + /* before: [obj]; after [getiter(obj)] */ + v = TOP(); + x = PyObject_GetIter(v); + Py_DECREF(v); + if (x != NULL) { + SET_TOP(x); + PREDICT(FOR_ITER); + DISPATCH(); + } + STACKADJ(-1); + break; + + PREDICTED_WITH_ARG(FOR_ITER); + TARGET(FOR_ITER) + /* before: [iter]; after: [iter, iter()] *or* [] */ + v = TOP(); + x = (*v->ob_type->tp_iternext)(v); + if (x != NULL) { + PUSH(x); + PREDICT(STORE_FAST); + PREDICT(UNPACK_SEQUENCE); + DISPATCH(); + } + if (PyErr_Occurred()) { + if (!PyErr_ExceptionMatches( + PyExc_StopIteration)) + break; + PyErr_Clear(); + } + /* iterator ended normally */ + x = v = POP(); + Py_DECREF(v); + JUMPBY(oparg); + DISPATCH(); + + TARGET(BREAK_LOOP) + why = WHY_BREAK; + goto fast_block_end; + + TARGET(CONTINUE_LOOP) + retval = PyLong_FromLong(oparg); + if (!retval) { + x = NULL; + break; + } + why = WHY_CONTINUE; + goto fast_block_end; + + TARGET_WITH_IMPL(SETUP_LOOP, _setup_finally) + TARGET_WITH_IMPL(SETUP_EXCEPT, _setup_finally) + TARGET(SETUP_FINALLY) + _setup_finally: + /* NOTE: If you add any new block-setup opcodes that + are not try/except/finally handlers, you may need + to update the PyGen_NeedsFinalizing() function. + */ + + PyFrame_BlockSetup(f, opcode, INSTR_OFFSET() + oparg, + STACK_LEVEL()); + DISPATCH(); + + TARGET(SETUP_WITH) + { + static PyObject *exit, *enter; + w = TOP(); + x = special_lookup(w, "__exit__", &exit); + if (!x) + break; + SET_TOP(x); + u = special_lookup(w, "__enter__", &enter); + Py_DECREF(w); + if (!u) { + x = NULL; + break; + } + x = PyObject_CallFunctionObjArgs(u, NULL); + Py_DECREF(u); + if (!x) + break; + /* Setup the finally block before pushing the result + of __enter__ on the stack. */ + PyFrame_BlockSetup(f, SETUP_FINALLY, INSTR_OFFSET() + oparg, + STACK_LEVEL()); + + PUSH(x); + DISPATCH(); + } + + TARGET(WITH_CLEANUP) + { + /* At the top of the stack are 1-3 values indicating + how/why we entered the finally clause: + - TOP = None + - (TOP, SECOND) = (WHY_{RETURN,CONTINUE}), retval + - TOP = WHY_*; no retval below it + - (TOP, SECOND, THIRD) = exc_info() + (FOURTH, FITH, SIXTH) = previous exception for EXCEPT_HANDLER + Below them is EXIT, the context.__exit__ bound method. + In the last case, we must call + EXIT(TOP, SECOND, THIRD) + otherwise we must call + EXIT(None, None, None) + + In the first two cases, we remove EXIT from the + stack, leaving the rest in the same order. In the + third case, we shift the bottom 3 values of the + stack down, and replace the empty spot with NULL. + + In addition, if the stack represents an exception, + *and* the function call returns a 'true' value, we + push WHY_SILENCED onto the stack. END_FINALLY will + then not re-raise the exception. (But non-local + gotos should still be resumed.) + */ + + PyObject *exit_func; + u = TOP(); + if (u == Py_None) { + (void)POP(); + exit_func = TOP(); + SET_TOP(u); + v = w = Py_None; + } + else if (PyLong_Check(u)) { + (void)POP(); + switch(PyLong_AsLong(u)) { + case WHY_RETURN: + case WHY_CONTINUE: + /* Retval in TOP. */ + exit_func = SECOND(); + SET_SECOND(TOP()); + SET_TOP(u); + break; + default: + exit_func = TOP(); + SET_TOP(u); + break; + } + u = v = w = Py_None; + } + else { + PyObject *tp, *exc, *tb; + PyTryBlock *block; + v = SECOND(); + w = THIRD(); + tp = FOURTH(); + exc = PEEK(5); + tb = PEEK(6); + exit_func = PEEK(7); + SET_VALUE(7, tb); + SET_VALUE(6, exc); + SET_VALUE(5, tp); + /* UNWIND_EXCEPT_HANDLER will pop this off. */ + SET_FOURTH(NULL); + /* We just shifted the stack down, so we have + to tell the except handler block that the + values are lower than it expects. */ + block = &f->f_blockstack[f->f_iblock - 1]; + assert(block->b_type == EXCEPT_HANDLER); + block->b_level--; + } + /* XXX Not the fastest way to call it... */ + x = PyObject_CallFunctionObjArgs(exit_func, u, v, w, + NULL); + Py_DECREF(exit_func); + if (x == NULL) + break; /* Go to error exit */ + + if (u != Py_None) + err = PyObject_IsTrue(x); + else + err = 0; + Py_DECREF(x); + + if (err < 0) + break; /* Go to error exit */ + else if (err > 0) { + err = 0; + /* There was an exception and a True return */ + PUSH(PyLong_FromLong((long) WHY_SILENCED)); + } + PREDICT(END_FINALLY); + break; + } + + TARGET(CALL_FUNCTION) + { + PyObject **sp; + PCALL(PCALL_ALL); + sp = stack_pointer; #ifdef WITH_TSC - x = call_function(&sp, oparg, &intr0, &intr1); + x = call_function(&sp, oparg, &intr0, &intr1); #else - x = call_function(&sp, oparg); + x = call_function(&sp, oparg); #endif - stack_pointer = sp; - PUSH(x); - if (x != NULL) - DISPATCH(); - break; - } - - TARGET_WITH_IMPL(CALL_FUNCTION_VAR, _call_function_var_kw) - TARGET_WITH_IMPL(CALL_FUNCTION_KW, _call_function_var_kw) - TARGET(CALL_FUNCTION_VAR_KW) - _call_function_var_kw: - { - int na = oparg & 0xff; - int nk = (oparg>>8) & 0xff; - int flags = (opcode - CALL_FUNCTION) & 3; - int n = na + 2 * nk; - PyObject **pfunc, *func, **sp; - PCALL(PCALL_ALL); - if (flags & CALL_FLAG_VAR) - n++; - if (flags & CALL_FLAG_KW) - n++; - pfunc = stack_pointer - n - 1; - func = *pfunc; - - if (PyMethod_Check(func) - && PyMethod_GET_SELF(func) != NULL) { - PyObject *self = PyMethod_GET_SELF(func); - Py_INCREF(self); - func = PyMethod_GET_FUNCTION(func); - Py_INCREF(func); - Py_DECREF(*pfunc); - *pfunc = self; - na++; - n++; - } else - Py_INCREF(func); - sp = stack_pointer; - READ_TIMESTAMP(intr0); - x = ext_do_call(func, &sp, flags, na, nk); - READ_TIMESTAMP(intr1); - stack_pointer = sp; - Py_DECREF(func); - - while (stack_pointer > pfunc) { - w = POP(); - Py_DECREF(w); - } - PUSH(x); - if (x != NULL) - DISPATCH(); - break; - } - - TARGET_WITH_IMPL(MAKE_CLOSURE, _make_function) - TARGET(MAKE_FUNCTION) - _make_function: - { - int posdefaults = oparg & 0xff; - int kwdefaults = (oparg>>8) & 0xff; - int num_annotations = (oparg >> 16) & 0x7fff; - - v = POP(); /* code object */ - x = PyFunction_New(v, f->f_globals); - Py_DECREF(v); - - if (x != NULL && opcode == MAKE_CLOSURE) { - v = POP(); - if (PyFunction_SetClosure(x, v) != 0) { - /* Can't happen unless bytecode is corrupt. */ - why = WHY_EXCEPTION; - } - Py_DECREF(v); - } - - if (x != NULL && num_annotations > 0) { - Py_ssize_t name_ix; - u = POP(); /* names of args with annotations */ - v = PyDict_New(); - if (v == NULL) { - Py_DECREF(x); - x = NULL; - break; - } - name_ix = PyTuple_Size(u); - assert(num_annotations == name_ix+1); - while (name_ix > 0) { - --name_ix; - t = PyTuple_GET_ITEM(u, name_ix); - w = POP(); - /* XXX(nnorwitz): check for errors */ - PyDict_SetItem(v, t, w); - Py_DECREF(w); - } - - if (PyFunction_SetAnnotations(x, v) != 0) { - /* Can't happen unless - PyFunction_SetAnnotations changes. */ - why = WHY_EXCEPTION; - } - Py_DECREF(v); - Py_DECREF(u); - } - - /* XXX Maybe this should be a separate opcode? */ - if (x != NULL && posdefaults > 0) { - v = PyTuple_New(posdefaults); - if (v == NULL) { - Py_DECREF(x); - x = NULL; - break; - } - while (--posdefaults >= 0) { - w = POP(); - PyTuple_SET_ITEM(v, posdefaults, w); - } - if (PyFunction_SetDefaults(x, v) != 0) { - /* Can't happen unless - PyFunction_SetDefaults changes. */ - why = WHY_EXCEPTION; - } - Py_DECREF(v); - } - if (x != NULL && kwdefaults > 0) { - v = PyDict_New(); - if (v == NULL) { - Py_DECREF(x); - x = NULL; - break; - } - while (--kwdefaults >= 0) { - w = POP(); /* default value */ - u = POP(); /* kw only arg name */ - /* XXX(nnorwitz): check for errors */ - PyDict_SetItem(v, u, w); - Py_DECREF(w); - Py_DECREF(u); - } - if (PyFunction_SetKwDefaults(x, v) != 0) { - /* Can't happen unless - PyFunction_SetKwDefaults changes. */ - why = WHY_EXCEPTION; - } - Py_DECREF(v); - } - PUSH(x); - break; - } - - TARGET(BUILD_SLICE) - if (oparg == 3) - w = POP(); - else - w = NULL; - v = POP(); - u = TOP(); - x = PySlice_New(u, v, w); - Py_DECREF(u); - Py_DECREF(v); - Py_XDECREF(w); - SET_TOP(x); - if (x != NULL) DISPATCH(); - break; - - TARGET(EXTENDED_ARG) - opcode = NEXTOP(); - oparg = oparg<<16 | NEXTARG(); - goto dispatch_opcode; + stack_pointer = sp; + PUSH(x); + if (x != NULL) + DISPATCH(); + break; + } + + TARGET_WITH_IMPL(CALL_FUNCTION_VAR, _call_function_var_kw) + TARGET_WITH_IMPL(CALL_FUNCTION_KW, _call_function_var_kw) + TARGET(CALL_FUNCTION_VAR_KW) + _call_function_var_kw: + { + int na = oparg & 0xff; + int nk = (oparg>>8) & 0xff; + int flags = (opcode - CALL_FUNCTION) & 3; + int n = na + 2 * nk; + PyObject **pfunc, *func, **sp; + PCALL(PCALL_ALL); + if (flags & CALL_FLAG_VAR) + n++; + if (flags & CALL_FLAG_KW) + n++; + pfunc = stack_pointer - n - 1; + func = *pfunc; + + if (PyMethod_Check(func) + && PyMethod_GET_SELF(func) != NULL) { + PyObject *self = PyMethod_GET_SELF(func); + Py_INCREF(self); + func = PyMethod_GET_FUNCTION(func); + Py_INCREF(func); + Py_DECREF(*pfunc); + *pfunc = self; + na++; + n++; + } else + Py_INCREF(func); + sp = stack_pointer; + READ_TIMESTAMP(intr0); + x = ext_do_call(func, &sp, flags, na, nk); + READ_TIMESTAMP(intr1); + stack_pointer = sp; + Py_DECREF(func); + + while (stack_pointer > pfunc) { + w = POP(); + Py_DECREF(w); + } + PUSH(x); + if (x != NULL) + DISPATCH(); + break; + } + + TARGET_WITH_IMPL(MAKE_CLOSURE, _make_function) + TARGET(MAKE_FUNCTION) + _make_function: + { + int posdefaults = oparg & 0xff; + int kwdefaults = (oparg>>8) & 0xff; + int num_annotations = (oparg >> 16) & 0x7fff; + + v = POP(); /* code object */ + x = PyFunction_New(v, f->f_globals); + Py_DECREF(v); + + if (x != NULL && opcode == MAKE_CLOSURE) { + v = POP(); + if (PyFunction_SetClosure(x, v) != 0) { + /* Can't happen unless bytecode is corrupt. */ + why = WHY_EXCEPTION; + } + Py_DECREF(v); + } + + if (x != NULL && num_annotations > 0) { + Py_ssize_t name_ix; + u = POP(); /* names of args with annotations */ + v = PyDict_New(); + if (v == NULL) { + Py_DECREF(x); + x = NULL; + break; + } + name_ix = PyTuple_Size(u); + assert(num_annotations == name_ix+1); + while (name_ix > 0) { + --name_ix; + t = PyTuple_GET_ITEM(u, name_ix); + w = POP(); + /* XXX(nnorwitz): check for errors */ + PyDict_SetItem(v, t, w); + Py_DECREF(w); + } + + if (PyFunction_SetAnnotations(x, v) != 0) { + /* Can't happen unless + PyFunction_SetAnnotations changes. */ + why = WHY_EXCEPTION; + } + Py_DECREF(v); + Py_DECREF(u); + } + + /* XXX Maybe this should be a separate opcode? */ + if (x != NULL && posdefaults > 0) { + v = PyTuple_New(posdefaults); + if (v == NULL) { + Py_DECREF(x); + x = NULL; + break; + } + while (--posdefaults >= 0) { + w = POP(); + PyTuple_SET_ITEM(v, posdefaults, w); + } + if (PyFunction_SetDefaults(x, v) != 0) { + /* Can't happen unless + PyFunction_SetDefaults changes. */ + why = WHY_EXCEPTION; + } + Py_DECREF(v); + } + if (x != NULL && kwdefaults > 0) { + v = PyDict_New(); + if (v == NULL) { + Py_DECREF(x); + x = NULL; + break; + } + while (--kwdefaults >= 0) { + w = POP(); /* default value */ + u = POP(); /* kw only arg name */ + /* XXX(nnorwitz): check for errors */ + PyDict_SetItem(v, u, w); + Py_DECREF(w); + Py_DECREF(u); + } + if (PyFunction_SetKwDefaults(x, v) != 0) { + /* Can't happen unless + PyFunction_SetKwDefaults changes. */ + why = WHY_EXCEPTION; + } + Py_DECREF(v); + } + PUSH(x); + break; + } + + TARGET(BUILD_SLICE) + if (oparg == 3) + w = POP(); + else + w = NULL; + v = POP(); + u = TOP(); + x = PySlice_New(u, v, w); + Py_DECREF(u); + Py_DECREF(v); + Py_XDECREF(w); + SET_TOP(x); + if (x != NULL) DISPATCH(); + break; + + TARGET(EXTENDED_ARG) + opcode = NEXTOP(); + oparg = oparg<<16 | NEXTARG(); + goto dispatch_opcode; #ifdef USE_COMPUTED_GOTOS - _unknown_opcode: + _unknown_opcode: #endif - default: - fprintf(stderr, - "XXX lineno: %d, opcode: %d\n", - PyFrame_GetLineNumber(f), - opcode); - PyErr_SetString(PyExc_SystemError, "unknown opcode"); - why = WHY_EXCEPTION; - break; + default: + fprintf(stderr, + "XXX lineno: %d, opcode: %d\n", + PyFrame_GetLineNumber(f), + opcode); + PyErr_SetString(PyExc_SystemError, "unknown opcode"); + why = WHY_EXCEPTION; + break; #ifdef CASE_TOO_BIG - } + } #endif - } /* switch */ + } /* switch */ - on_error: + on_error: - READ_TIMESTAMP(inst1); + READ_TIMESTAMP(inst1); - /* Quickly continue if no error occurred */ + /* Quickly continue if no error occurred */ - if (why == WHY_NOT) { - if (err == 0 && x != NULL) { + if (why == WHY_NOT) { + if (err == 0 && x != NULL) { #ifdef CHECKEXC - /* This check is expensive! */ - if (PyErr_Occurred()) - fprintf(stderr, - "XXX undetected error\n"); - else { + /* This check is expensive! */ + if (PyErr_Occurred()) + fprintf(stderr, + "XXX undetected error\n"); + else { #endif - READ_TIMESTAMP(loop1); - continue; /* Normal, fast path */ + READ_TIMESTAMP(loop1); + continue; /* Normal, fast path */ #ifdef CHECKEXC - } + } #endif - } - why = WHY_EXCEPTION; - x = Py_None; - err = 0; - } - - /* Double-check exception status */ - - if (why == WHY_EXCEPTION || why == WHY_RERAISE) { - if (!PyErr_Occurred()) { - PyErr_SetString(PyExc_SystemError, - "error return without exception set"); - why = WHY_EXCEPTION; - } - } + } + why = WHY_EXCEPTION; + x = Py_None; + err = 0; + } + + /* Double-check exception status */ + + if (why == WHY_EXCEPTION || why == WHY_RERAISE) { + if (!PyErr_Occurred()) { + PyErr_SetString(PyExc_SystemError, + "error return without exception set"); + why = WHY_EXCEPTION; + } + } #ifdef CHECKEXC - else { - /* This check is expensive! */ - if (PyErr_Occurred()) { - char buf[128]; - sprintf(buf, "Stack unwind with exception " - "set and why=%d", why); - Py_FatalError(buf); - } - } + else { + /* This check is expensive! */ + if (PyErr_Occurred()) { + char buf[128]; + sprintf(buf, "Stack unwind with exception " + "set and why=%d", why); + Py_FatalError(buf); + } + } #endif - /* Log traceback info if this is a real exception */ + /* Log traceback info if this is a real exception */ - if (why == WHY_EXCEPTION) { - PyTraceBack_Here(f); + if (why == WHY_EXCEPTION) { + PyTraceBack_Here(f); - if (tstate->c_tracefunc != NULL) - call_exc_trace(tstate->c_tracefunc, - tstate->c_traceobj, f); - } + if (tstate->c_tracefunc != NULL) + call_exc_trace(tstate->c_tracefunc, + tstate->c_traceobj, f); + } - /* For the rest, treat WHY_RERAISE as WHY_EXCEPTION */ + /* For the rest, treat WHY_RERAISE as WHY_EXCEPTION */ - if (why == WHY_RERAISE) - why = WHY_EXCEPTION; + if (why == WHY_RERAISE) + why = WHY_EXCEPTION; - /* Unwind stacks if a (pseudo) exception occurred */ + /* Unwind stacks if a (pseudo) exception occurred */ fast_block_end: - while (why != WHY_NOT && f->f_iblock > 0) { - /* Peek at the current block. */ - PyTryBlock *b = &f->f_blockstack[f->f_iblock - 1]; - - assert(why != WHY_YIELD); - if (b->b_type == SETUP_LOOP && why == WHY_CONTINUE) { - why = WHY_NOT; - JUMPTO(PyLong_AS_LONG(retval)); - Py_DECREF(retval); - break; - } - /* Now we have to pop the block. */ - f->f_iblock--; - - if (b->b_type == EXCEPT_HANDLER) { - UNWIND_EXCEPT_HANDLER(b); - continue; - } - UNWIND_BLOCK(b); - if (b->b_type == SETUP_LOOP && why == WHY_BREAK) { - why = WHY_NOT; - JUMPTO(b->b_handler); - break; - } - if (why == WHY_EXCEPTION && (b->b_type == SETUP_EXCEPT - || b->b_type == SETUP_FINALLY)) { - PyObject *exc, *val, *tb; - int handler = b->b_handler; - /* Beware, this invalidates all b->b_* fields */ - PyFrame_BlockSetup(f, EXCEPT_HANDLER, -1, STACK_LEVEL()); - PUSH(tstate->exc_traceback); - PUSH(tstate->exc_value); - if (tstate->exc_type != NULL) { - PUSH(tstate->exc_type); - } - else { - Py_INCREF(Py_None); - PUSH(Py_None); - } - PyErr_Fetch(&exc, &val, &tb); - /* Make the raw exception data - available to the handler, - so a program can emulate the - Python main loop. */ - PyErr_NormalizeException( - &exc, &val, &tb); - PyException_SetTraceback(val, tb); - Py_INCREF(exc); - tstate->exc_type = exc; - Py_INCREF(val); - tstate->exc_value = val; - tstate->exc_traceback = tb; - if (tb == NULL) - tb = Py_None; - Py_INCREF(tb); - PUSH(tb); - PUSH(val); - PUSH(exc); - why = WHY_NOT; - JUMPTO(handler); - break; - } - if (b->b_type == SETUP_FINALLY) { - if (why & (WHY_RETURN | WHY_CONTINUE)) - PUSH(retval); - PUSH(PyLong_FromLong((long)why)); - why = WHY_NOT; - JUMPTO(b->b_handler); - break; - } - } /* unwind stack */ - - /* End the loop if we still have an error (or return) */ - - if (why != WHY_NOT) - break; - READ_TIMESTAMP(loop1); - - } /* main loop */ - - assert(why != WHY_YIELD); - /* Pop remaining stack entries. */ - while (!EMPTY()) { - v = POP(); - Py_XDECREF(v); - } + while (why != WHY_NOT && f->f_iblock > 0) { + /* Peek at the current block. */ + PyTryBlock *b = &f->f_blockstack[f->f_iblock - 1]; + + assert(why != WHY_YIELD); + if (b->b_type == SETUP_LOOP && why == WHY_CONTINUE) { + why = WHY_NOT; + JUMPTO(PyLong_AS_LONG(retval)); + Py_DECREF(retval); + break; + } + /* Now we have to pop the block. */ + f->f_iblock--; + + if (b->b_type == EXCEPT_HANDLER) { + UNWIND_EXCEPT_HANDLER(b); + continue; + } + UNWIND_BLOCK(b); + if (b->b_type == SETUP_LOOP && why == WHY_BREAK) { + why = WHY_NOT; + JUMPTO(b->b_handler); + break; + } + if (why == WHY_EXCEPTION && (b->b_type == SETUP_EXCEPT + || b->b_type == SETUP_FINALLY)) { + PyObject *exc, *val, *tb; + int handler = b->b_handler; + /* Beware, this invalidates all b->b_* fields */ + PyFrame_BlockSetup(f, EXCEPT_HANDLER, -1, STACK_LEVEL()); + PUSH(tstate->exc_traceback); + PUSH(tstate->exc_value); + if (tstate->exc_type != NULL) { + PUSH(tstate->exc_type); + } + else { + Py_INCREF(Py_None); + PUSH(Py_None); + } + PyErr_Fetch(&exc, &val, &tb); + /* Make the raw exception data + available to the handler, + so a program can emulate the + Python main loop. */ + PyErr_NormalizeException( + &exc, &val, &tb); + PyException_SetTraceback(val, tb); + Py_INCREF(exc); + tstate->exc_type = exc; + Py_INCREF(val); + tstate->exc_value = val; + tstate->exc_traceback = tb; + if (tb == NULL) + tb = Py_None; + Py_INCREF(tb); + PUSH(tb); + PUSH(val); + PUSH(exc); + why = WHY_NOT; + JUMPTO(handler); + break; + } + if (b->b_type == SETUP_FINALLY) { + if (why & (WHY_RETURN | WHY_CONTINUE)) + PUSH(retval); + PUSH(PyLong_FromLong((long)why)); + why = WHY_NOT; + JUMPTO(b->b_handler); + break; + } + } /* unwind stack */ + + /* End the loop if we still have an error (or return) */ + + if (why != WHY_NOT) + break; + READ_TIMESTAMP(loop1); + + } /* main loop */ + + assert(why != WHY_YIELD); + /* Pop remaining stack entries. */ + while (!EMPTY()) { + v = POP(); + Py_XDECREF(v); + } - if (why != WHY_RETURN) - retval = NULL; + if (why != WHY_RETURN) + retval = NULL; fast_yield: - if (tstate->use_tracing) { - if (tstate->c_tracefunc) { - if (why == WHY_RETURN || why == WHY_YIELD) { - if (call_trace(tstate->c_tracefunc, - tstate->c_traceobj, f, - PyTrace_RETURN, retval)) { - Py_XDECREF(retval); - retval = NULL; - why = WHY_EXCEPTION; - } - } - else if (why == WHY_EXCEPTION) { - call_trace_protected(tstate->c_tracefunc, - tstate->c_traceobj, f, - PyTrace_RETURN, NULL); - } - } - if (tstate->c_profilefunc) { - if (why == WHY_EXCEPTION) - call_trace_protected(tstate->c_profilefunc, - tstate->c_profileobj, f, - PyTrace_RETURN, NULL); - else if (call_trace(tstate->c_profilefunc, - tstate->c_profileobj, f, - PyTrace_RETURN, retval)) { - Py_XDECREF(retval); - retval = NULL; - why = WHY_EXCEPTION; - } - } - } + if (tstate->use_tracing) { + if (tstate->c_tracefunc) { + if (why == WHY_RETURN || why == WHY_YIELD) { + if (call_trace(tstate->c_tracefunc, + tstate->c_traceobj, f, + PyTrace_RETURN, retval)) { + Py_XDECREF(retval); + retval = NULL; + why = WHY_EXCEPTION; + } + } + else if (why == WHY_EXCEPTION) { + call_trace_protected(tstate->c_tracefunc, + tstate->c_traceobj, f, + PyTrace_RETURN, NULL); + } + } + if (tstate->c_profilefunc) { + if (why == WHY_EXCEPTION) + call_trace_protected(tstate->c_profilefunc, + tstate->c_profileobj, f, + PyTrace_RETURN, NULL); + else if (call_trace(tstate->c_profilefunc, + tstate->c_profileobj, f, + PyTrace_RETURN, retval)) { + Py_XDECREF(retval); + retval = NULL; + why = WHY_EXCEPTION; + } + } + } - /* pop frame */ + /* pop frame */ exit_eval_frame: - Py_LeaveRecursiveCall(); - tstate->frame = f->f_back; + Py_LeaveRecursiveCall(); + tstate->frame = f->f_back; - return retval; + return retval; } /* This is gonna seem *real weird*, but if you put some other code between @@ -3058,279 +3058,279 @@ PyObject * PyEval_EvalCodeEx(PyCodeObject *co, PyObject *globals, PyObject *locals, - PyObject **args, int argcount, PyObject **kws, int kwcount, - PyObject **defs, int defcount, PyObject *kwdefs, PyObject *closure) + PyObject **args, int argcount, PyObject **kws, int kwcount, + PyObject **defs, int defcount, PyObject *kwdefs, PyObject *closure) { - register PyFrameObject *f; - register PyObject *retval = NULL; - register PyObject **fastlocals, **freevars; - PyThreadState *tstate = PyThreadState_GET(); - PyObject *x, *u; - int total_args = co->co_argcount + co->co_kwonlyargcount; - - if (globals == NULL) { - PyErr_SetString(PyExc_SystemError, - "PyEval_EvalCodeEx: NULL globals"); - return NULL; - } - - assert(tstate != NULL); - assert(globals != NULL); - f = PyFrame_New(tstate, co, globals, locals); - if (f == NULL) - return NULL; - - fastlocals = f->f_localsplus; - freevars = f->f_localsplus + co->co_nlocals; - - if (total_args || co->co_flags & (CO_VARARGS | CO_VARKEYWORDS)) { - int i; - int n = argcount; - PyObject *kwdict = NULL; - if (co->co_flags & CO_VARKEYWORDS) { - kwdict = PyDict_New(); - if (kwdict == NULL) - goto fail; - i = total_args; - if (co->co_flags & CO_VARARGS) - i++; - SETLOCAL(i, kwdict); - } - if (argcount > co->co_argcount) { - if (!(co->co_flags & CO_VARARGS)) { - PyErr_Format(PyExc_TypeError, - "%U() takes %s %d " - "argument%s (%d given)", - co->co_name, - defcount ? "at most" : "exactly", - total_args, - total_args == 1 ? "" : "s", - argcount + kwcount); - goto fail; - } - n = co->co_argcount; - } - for (i = 0; i < n; i++) { - x = args[i]; - Py_INCREF(x); - SETLOCAL(i, x); - } - if (co->co_flags & CO_VARARGS) { - u = PyTuple_New(argcount - n); - if (u == NULL) - goto fail; - SETLOCAL(total_args, u); - for (i = n; i < argcount; i++) { - x = args[i]; - Py_INCREF(x); - PyTuple_SET_ITEM(u, i-n, x); - } - } - for (i = 0; i < kwcount; i++) { - PyObject **co_varnames; - PyObject *keyword = kws[2*i]; - PyObject *value = kws[2*i + 1]; - int j; - if (keyword == NULL || !PyUnicode_Check(keyword)) { - PyErr_Format(PyExc_TypeError, - "%U() keywords must be strings", - co->co_name); - goto fail; - } - /* Speed hack: do raw pointer compares. As names are - normally interned this should almost always hit. */ - co_varnames = ((PyTupleObject *)(co->co_varnames))->ob_item; - for (j = 0; j < total_args; j++) { - PyObject *nm = co_varnames[j]; - if (nm == keyword) - goto kw_found; - } - /* Slow fallback, just in case */ - for (j = 0; j < total_args; j++) { - PyObject *nm = co_varnames[j]; - int cmp = PyObject_RichCompareBool( - keyword, nm, Py_EQ); - if (cmp > 0) - goto kw_found; - else if (cmp < 0) - goto fail; - } - if (j >= total_args && kwdict == NULL) { - PyErr_Format(PyExc_TypeError, - "%U() got an unexpected " - "keyword argument '%S'", - co->co_name, - keyword); - goto fail; - } - PyDict_SetItem(kwdict, keyword, value); - continue; - kw_found: - if (GETLOCAL(j) != NULL) { - PyErr_Format(PyExc_TypeError, - "%U() got multiple " - "values for keyword " - "argument '%S'", - co->co_name, - keyword); - goto fail; - } - Py_INCREF(value); - SETLOCAL(j, value); - } - if (co->co_kwonlyargcount > 0) { - for (i = co->co_argcount; i < total_args; i++) { - PyObject *name; - if (GETLOCAL(i) != NULL) - continue; - name = PyTuple_GET_ITEM(co->co_varnames, i); - if (kwdefs != NULL) { - PyObject *def = PyDict_GetItem(kwdefs, name); - if (def) { - Py_INCREF(def); - SETLOCAL(i, def); - continue; - } - } - PyErr_Format(PyExc_TypeError, - "%U() needs keyword-only argument %S", - co->co_name, name); - goto fail; - } - } - if (argcount < co->co_argcount) { - int m = co->co_argcount - defcount; - for (i = argcount; i < m; i++) { - if (GETLOCAL(i) == NULL) { - int j, given = 0; - for (j = 0; j < co->co_argcount; j++) - if (GETLOCAL(j)) - given++; - PyErr_Format(PyExc_TypeError, - "%U() takes %s %d " - "argument%s " - "(%d given)", - co->co_name, - ((co->co_flags & CO_VARARGS) || - defcount) ? "at least" - : "exactly", - m, m == 1 ? "" : "s", given); - goto fail; - } - } - if (n > m) - i = n - m; - else - i = 0; - for (; i < defcount; i++) { - if (GETLOCAL(m+i) == NULL) { - PyObject *def = defs[i]; - Py_INCREF(def); - SETLOCAL(m+i, def); - } - } - } - } - else if (argcount > 0 || kwcount > 0) { - PyErr_Format(PyExc_TypeError, - "%U() takes no arguments (%d given)", - co->co_name, - argcount + kwcount); - goto fail; - } - /* Allocate and initialize storage for cell vars, and copy free - vars into frame. This isn't too efficient right now. */ - if (PyTuple_GET_SIZE(co->co_cellvars)) { - int i, j, nargs, found; - Py_UNICODE *cellname, *argname; - PyObject *c; - - nargs = total_args; - if (co->co_flags & CO_VARARGS) - nargs++; - if (co->co_flags & CO_VARKEYWORDS) - nargs++; - - /* Initialize each cell var, taking into account - cell vars that are initialized from arguments. - - Should arrange for the compiler to put cellvars - that are arguments at the beginning of the cellvars - list so that we can march over it more efficiently? - */ - for (i = 0; i < PyTuple_GET_SIZE(co->co_cellvars); ++i) { - cellname = PyUnicode_AS_UNICODE( - PyTuple_GET_ITEM(co->co_cellvars, i)); - found = 0; - for (j = 0; j < nargs; j++) { - argname = PyUnicode_AS_UNICODE( - PyTuple_GET_ITEM(co->co_varnames, j)); - if (Py_UNICODE_strcmp(cellname, argname) == 0) { - c = PyCell_New(GETLOCAL(j)); - if (c == NULL) - goto fail; - GETLOCAL(co->co_nlocals + i) = c; - found = 1; - break; - } - } - if (found == 0) { - c = PyCell_New(NULL); - if (c == NULL) - goto fail; - SETLOCAL(co->co_nlocals + i, c); - } - } - } - if (PyTuple_GET_SIZE(co->co_freevars)) { - int i; - for (i = 0; i < PyTuple_GET_SIZE(co->co_freevars); ++i) { - PyObject *o = PyTuple_GET_ITEM(closure, i); - Py_INCREF(o); - freevars[PyTuple_GET_SIZE(co->co_cellvars) + i] = o; - } - } - - if (co->co_flags & CO_GENERATOR) { - /* Don't need to keep the reference to f_back, it will be set - * when the generator is resumed. */ - Py_XDECREF(f->f_back); - f->f_back = NULL; - - PCALL(PCALL_GENERATOR); - - /* Create a new generator that owns the ready to run frame - * and return that as the value. */ - return PyGen_New(f); - } + register PyFrameObject *f; + register PyObject *retval = NULL; + register PyObject **fastlocals, **freevars; + PyThreadState *tstate = PyThreadState_GET(); + PyObject *x, *u; + int total_args = co->co_argcount + co->co_kwonlyargcount; + + if (globals == NULL) { + PyErr_SetString(PyExc_SystemError, + "PyEval_EvalCodeEx: NULL globals"); + return NULL; + } + + assert(tstate != NULL); + assert(globals != NULL); + f = PyFrame_New(tstate, co, globals, locals); + if (f == NULL) + return NULL; + + fastlocals = f->f_localsplus; + freevars = f->f_localsplus + co->co_nlocals; + + if (total_args || co->co_flags & (CO_VARARGS | CO_VARKEYWORDS)) { + int i; + int n = argcount; + PyObject *kwdict = NULL; + if (co->co_flags & CO_VARKEYWORDS) { + kwdict = PyDict_New(); + if (kwdict == NULL) + goto fail; + i = total_args; + if (co->co_flags & CO_VARARGS) + i++; + SETLOCAL(i, kwdict); + } + if (argcount > co->co_argcount) { + if (!(co->co_flags & CO_VARARGS)) { + PyErr_Format(PyExc_TypeError, + "%U() takes %s %d " + "argument%s (%d given)", + co->co_name, + defcount ? "at most" : "exactly", + total_args, + total_args == 1 ? "" : "s", + argcount + kwcount); + goto fail; + } + n = co->co_argcount; + } + for (i = 0; i < n; i++) { + x = args[i]; + Py_INCREF(x); + SETLOCAL(i, x); + } + if (co->co_flags & CO_VARARGS) { + u = PyTuple_New(argcount - n); + if (u == NULL) + goto fail; + SETLOCAL(total_args, u); + for (i = n; i < argcount; i++) { + x = args[i]; + Py_INCREF(x); + PyTuple_SET_ITEM(u, i-n, x); + } + } + for (i = 0; i < kwcount; i++) { + PyObject **co_varnames; + PyObject *keyword = kws[2*i]; + PyObject *value = kws[2*i + 1]; + int j; + if (keyword == NULL || !PyUnicode_Check(keyword)) { + PyErr_Format(PyExc_TypeError, + "%U() keywords must be strings", + co->co_name); + goto fail; + } + /* Speed hack: do raw pointer compares. As names are + normally interned this should almost always hit. */ + co_varnames = ((PyTupleObject *)(co->co_varnames))->ob_item; + for (j = 0; j < total_args; j++) { + PyObject *nm = co_varnames[j]; + if (nm == keyword) + goto kw_found; + } + /* Slow fallback, just in case */ + for (j = 0; j < total_args; j++) { + PyObject *nm = co_varnames[j]; + int cmp = PyObject_RichCompareBool( + keyword, nm, Py_EQ); + if (cmp > 0) + goto kw_found; + else if (cmp < 0) + goto fail; + } + if (j >= total_args && kwdict == NULL) { + PyErr_Format(PyExc_TypeError, + "%U() got an unexpected " + "keyword argument '%S'", + co->co_name, + keyword); + goto fail; + } + PyDict_SetItem(kwdict, keyword, value); + continue; + kw_found: + if (GETLOCAL(j) != NULL) { + PyErr_Format(PyExc_TypeError, + "%U() got multiple " + "values for keyword " + "argument '%S'", + co->co_name, + keyword); + goto fail; + } + Py_INCREF(value); + SETLOCAL(j, value); + } + if (co->co_kwonlyargcount > 0) { + for (i = co->co_argcount; i < total_args; i++) { + PyObject *name; + if (GETLOCAL(i) != NULL) + continue; + name = PyTuple_GET_ITEM(co->co_varnames, i); + if (kwdefs != NULL) { + PyObject *def = PyDict_GetItem(kwdefs, name); + if (def) { + Py_INCREF(def); + SETLOCAL(i, def); + continue; + } + } + PyErr_Format(PyExc_TypeError, + "%U() needs keyword-only argument %S", + co->co_name, name); + goto fail; + } + } + if (argcount < co->co_argcount) { + int m = co->co_argcount - defcount; + for (i = argcount; i < m; i++) { + if (GETLOCAL(i) == NULL) { + int j, given = 0; + for (j = 0; j < co->co_argcount; j++) + if (GETLOCAL(j)) + given++; + PyErr_Format(PyExc_TypeError, + "%U() takes %s %d " + "argument%s " + "(%d given)", + co->co_name, + ((co->co_flags & CO_VARARGS) || + defcount) ? "at least" + : "exactly", + m, m == 1 ? "" : "s", given); + goto fail; + } + } + if (n > m) + i = n - m; + else + i = 0; + for (; i < defcount; i++) { + if (GETLOCAL(m+i) == NULL) { + PyObject *def = defs[i]; + Py_INCREF(def); + SETLOCAL(m+i, def); + } + } + } + } + else if (argcount > 0 || kwcount > 0) { + PyErr_Format(PyExc_TypeError, + "%U() takes no arguments (%d given)", + co->co_name, + argcount + kwcount); + goto fail; + } + /* Allocate and initialize storage for cell vars, and copy free + vars into frame. This isn't too efficient right now. */ + if (PyTuple_GET_SIZE(co->co_cellvars)) { + int i, j, nargs, found; + Py_UNICODE *cellname, *argname; + PyObject *c; + + nargs = total_args; + if (co->co_flags & CO_VARARGS) + nargs++; + if (co->co_flags & CO_VARKEYWORDS) + nargs++; + + /* Initialize each cell var, taking into account + cell vars that are initialized from arguments. + + Should arrange for the compiler to put cellvars + that are arguments at the beginning of the cellvars + list so that we can march over it more efficiently? + */ + for (i = 0; i < PyTuple_GET_SIZE(co->co_cellvars); ++i) { + cellname = PyUnicode_AS_UNICODE( + PyTuple_GET_ITEM(co->co_cellvars, i)); + found = 0; + for (j = 0; j < nargs; j++) { + argname = PyUnicode_AS_UNICODE( + PyTuple_GET_ITEM(co->co_varnames, j)); + if (Py_UNICODE_strcmp(cellname, argname) == 0) { + c = PyCell_New(GETLOCAL(j)); + if (c == NULL) + goto fail; + GETLOCAL(co->co_nlocals + i) = c; + found = 1; + break; + } + } + if (found == 0) { + c = PyCell_New(NULL); + if (c == NULL) + goto fail; + SETLOCAL(co->co_nlocals + i, c); + } + } + } + if (PyTuple_GET_SIZE(co->co_freevars)) { + int i; + for (i = 0; i < PyTuple_GET_SIZE(co->co_freevars); ++i) { + PyObject *o = PyTuple_GET_ITEM(closure, i); + Py_INCREF(o); + freevars[PyTuple_GET_SIZE(co->co_cellvars) + i] = o; + } + } + + if (co->co_flags & CO_GENERATOR) { + /* Don't need to keep the reference to f_back, it will be set + * when the generator is resumed. */ + Py_XDECREF(f->f_back); + f->f_back = NULL; + + PCALL(PCALL_GENERATOR); + + /* Create a new generator that owns the ready to run frame + * and return that as the value. */ + return PyGen_New(f); + } - retval = PyEval_EvalFrameEx(f,0); + retval = PyEval_EvalFrameEx(f,0); fail: /* Jump here from prelude on failure */ - /* decref'ing the frame can cause __del__ methods to get invoked, - which can call back into Python. While we're done with the - current Python frame (f), the associated C stack is still in use, - so recursion_depth must be boosted for the duration. - */ - assert(tstate != NULL); - ++tstate->recursion_depth; - Py_DECREF(f); - --tstate->recursion_depth; - return retval; + /* decref'ing the frame can cause __del__ methods to get invoked, + which can call back into Python. While we're done with the + current Python frame (f), the associated C stack is still in use, + so recursion_depth must be boosted for the duration. + */ + assert(tstate != NULL); + ++tstate->recursion_depth; + Py_DECREF(f); + --tstate->recursion_depth; + return retval; } static PyObject * special_lookup(PyObject *o, char *meth, PyObject **cache) { - PyObject *res; - res = _PyObject_LookupSpecial(o, meth, cache); - if (res == NULL && !PyErr_Occurred()) { - PyErr_SetObject(PyExc_AttributeError, *cache); - return NULL; - } - return res; + PyObject *res; + res = _PyObject_LookupSpecial(o, meth, cache); + if (res == NULL && !PyErr_Occurred()) { + PyErr_SetObject(PyExc_AttributeError, *cache); + return NULL; + } + return res; } @@ -3339,83 +3339,83 @@ static enum why_code do_raise(PyObject *exc, PyObject *cause) { - PyObject *type = NULL, *value = NULL; + PyObject *type = NULL, *value = NULL; - if (exc == NULL) { - /* Reraise */ - PyThreadState *tstate = PyThreadState_GET(); - PyObject *tb; - type = tstate->exc_type; - value = tstate->exc_value; - tb = tstate->exc_traceback; - if (type == Py_None) { - PyErr_SetString(PyExc_RuntimeError, - "No active exception to reraise"); - return WHY_EXCEPTION; - } - Py_XINCREF(type); - Py_XINCREF(value); - Py_XINCREF(tb); - PyErr_Restore(type, value, tb); - return WHY_RERAISE; - } + if (exc == NULL) { + /* Reraise */ + PyThreadState *tstate = PyThreadState_GET(); + PyObject *tb; + type = tstate->exc_type; + value = tstate->exc_value; + tb = tstate->exc_traceback; + if (type == Py_None) { + PyErr_SetString(PyExc_RuntimeError, + "No active exception to reraise"); + return WHY_EXCEPTION; + } + Py_XINCREF(type); + Py_XINCREF(value); + Py_XINCREF(tb); + PyErr_Restore(type, value, tb); + return WHY_RERAISE; + } - /* We support the following forms of raise: - raise + /* We support the following forms of raise: + raise raise raise */ - if (PyExceptionClass_Check(exc)) { - type = exc; - value = PyObject_CallObject(exc, NULL); - if (value == NULL) - goto raise_error; - } - else if (PyExceptionInstance_Check(exc)) { - value = exc; - type = PyExceptionInstance_Class(exc); - Py_INCREF(type); - } - else { - /* Not something you can raise. You get an exception - anyway, just not what you specified :-) */ - Py_DECREF(exc); - PyErr_SetString(PyExc_TypeError, - "exceptions must derive from BaseException"); - goto raise_error; - } - - if (cause) { - PyObject *fixed_cause; - if (PyExceptionClass_Check(cause)) { - fixed_cause = PyObject_CallObject(cause, NULL); - if (fixed_cause == NULL) - goto raise_error; - Py_DECREF(cause); - } - else if (PyExceptionInstance_Check(cause)) { - fixed_cause = cause; - } - else { - PyErr_SetString(PyExc_TypeError, - "exception causes must derive from " - "BaseException"); - goto raise_error; - } - PyException_SetCause(value, fixed_cause); - } - - PyErr_SetObject(type, value); - /* PyErr_SetObject incref's its arguments */ - Py_XDECREF(value); - Py_XDECREF(type); - return WHY_EXCEPTION; + if (PyExceptionClass_Check(exc)) { + type = exc; + value = PyObject_CallObject(exc, NULL); + if (value == NULL) + goto raise_error; + } + else if (PyExceptionInstance_Check(exc)) { + value = exc; + type = PyExceptionInstance_Class(exc); + Py_INCREF(type); + } + else { + /* Not something you can raise. You get an exception + anyway, just not what you specified :-) */ + Py_DECREF(exc); + PyErr_SetString(PyExc_TypeError, + "exceptions must derive from BaseException"); + goto raise_error; + } + + if (cause) { + PyObject *fixed_cause; + if (PyExceptionClass_Check(cause)) { + fixed_cause = PyObject_CallObject(cause, NULL); + if (fixed_cause == NULL) + goto raise_error; + Py_DECREF(cause); + } + else if (PyExceptionInstance_Check(cause)) { + fixed_cause = cause; + } + else { + PyErr_SetString(PyExc_TypeError, + "exception causes must derive from " + "BaseException"); + goto raise_error; + } + PyException_SetCause(value, fixed_cause); + } + + PyErr_SetObject(type, value); + /* PyErr_SetObject incref's its arguments */ + Py_XDECREF(value); + Py_XDECREF(type); + return WHY_EXCEPTION; raise_error: - Py_XDECREF(value); - Py_XDECREF(type); - Py_XDECREF(cause); - return WHY_EXCEPTION; + Py_XDECREF(value); + Py_XDECREF(type); + Py_XDECREF(cause); + return WHY_EXCEPTION; } /* Iterate v argcnt times and store the results on the stack (via decreasing @@ -3428,73 +3428,73 @@ static int unpack_iterable(PyObject *v, int argcnt, int argcntafter, PyObject **sp) { - int i = 0, j = 0; - Py_ssize_t ll = 0; - PyObject *it; /* iter(v) */ - PyObject *w; - PyObject *l = NULL; /* variable list */ - - assert(v != NULL); - - it = PyObject_GetIter(v); - if (it == NULL) - goto Error; - - for (; i < argcnt; i++) { - w = PyIter_Next(it); - if (w == NULL) { - /* Iterator done, via error or exhaustion. */ - if (!PyErr_Occurred()) { - PyErr_Format(PyExc_ValueError, - "need more than %d value%s to unpack", - i, i == 1 ? "" : "s"); - } - goto Error; - } - *--sp = w; - } - - if (argcntafter == -1) { - /* We better have exhausted the iterator now. */ - w = PyIter_Next(it); - if (w == NULL) { - if (PyErr_Occurred()) - goto Error; - Py_DECREF(it); - return 1; - } - Py_DECREF(w); - PyErr_SetString(PyExc_ValueError, "too many values to unpack"); - goto Error; - } - - l = PySequence_List(it); - if (l == NULL) - goto Error; - *--sp = l; - i++; - - ll = PyList_GET_SIZE(l); - if (ll < argcntafter) { - PyErr_Format(PyExc_ValueError, "need more than %zd values to unpack", - argcnt + ll); - goto Error; - } - - /* Pop the "after-variable" args off the list. */ - for (j = argcntafter; j > 0; j--, i++) { - *--sp = PyList_GET_ITEM(l, ll - j); - } - /* Resize the list. */ - Py_SIZE(l) = ll - argcntafter; - Py_DECREF(it); - return 1; + int i = 0, j = 0; + Py_ssize_t ll = 0; + PyObject *it; /* iter(v) */ + PyObject *w; + PyObject *l = NULL; /* variable list */ + + assert(v != NULL); + + it = PyObject_GetIter(v); + if (it == NULL) + goto Error; + + for (; i < argcnt; i++) { + w = PyIter_Next(it); + if (w == NULL) { + /* Iterator done, via error or exhaustion. */ + if (!PyErr_Occurred()) { + PyErr_Format(PyExc_ValueError, + "need more than %d value%s to unpack", + i, i == 1 ? "" : "s"); + } + goto Error; + } + *--sp = w; + } + + if (argcntafter == -1) { + /* We better have exhausted the iterator now. */ + w = PyIter_Next(it); + if (w == NULL) { + if (PyErr_Occurred()) + goto Error; + Py_DECREF(it); + return 1; + } + Py_DECREF(w); + PyErr_SetString(PyExc_ValueError, "too many values to unpack"); + goto Error; + } + + l = PySequence_List(it); + if (l == NULL) + goto Error; + *--sp = l; + i++; + + ll = PyList_GET_SIZE(l); + if (ll < argcntafter) { + PyErr_Format(PyExc_ValueError, "need more than %zd values to unpack", + argcnt + ll); + goto Error; + } + + /* Pop the "after-variable" args off the list. */ + for (j = argcntafter; j > 0; j--, i++) { + *--sp = PyList_GET_ITEM(l, ll - j); + } + /* Resize the list. */ + Py_SIZE(l) = ll - argcntafter; + Py_DECREF(it); + return 1; Error: - for (; i > 0; i--, sp++) - Py_DECREF(*sp); - Py_XDECREF(it); - return 0; + for (; i > 0; i--, sp++) + Py_DECREF(*sp); + Py_XDECREF(it); + return 0; } @@ -3502,220 +3502,220 @@ static int prtrace(PyObject *v, char *str) { - printf("%s ", str); - if (PyObject_Print(v, stdout, 0) != 0) - PyErr_Clear(); /* Don't know what else to do */ - printf("\n"); - return 1; + printf("%s ", str); + if (PyObject_Print(v, stdout, 0) != 0) + PyErr_Clear(); /* Don't know what else to do */ + printf("\n"); + return 1; } #endif static void call_exc_trace(Py_tracefunc func, PyObject *self, PyFrameObject *f) { - PyObject *type, *value, *traceback, *arg; - int err; - PyErr_Fetch(&type, &value, &traceback); - if (value == NULL) { - value = Py_None; - Py_INCREF(value); - } - arg = PyTuple_Pack(3, type, value, traceback); - if (arg == NULL) { - PyErr_Restore(type, value, traceback); - return; - } - err = call_trace(func, self, f, PyTrace_EXCEPTION, arg); - Py_DECREF(arg); - if (err == 0) - PyErr_Restore(type, value, traceback); - else { - Py_XDECREF(type); - Py_XDECREF(value); - Py_XDECREF(traceback); - } + PyObject *type, *value, *traceback, *arg; + int err; + PyErr_Fetch(&type, &value, &traceback); + if (value == NULL) { + value = Py_None; + Py_INCREF(value); + } + arg = PyTuple_Pack(3, type, value, traceback); + if (arg == NULL) { + PyErr_Restore(type, value, traceback); + return; + } + err = call_trace(func, self, f, PyTrace_EXCEPTION, arg); + Py_DECREF(arg); + if (err == 0) + PyErr_Restore(type, value, traceback); + else { + Py_XDECREF(type); + Py_XDECREF(value); + Py_XDECREF(traceback); + } } static int call_trace_protected(Py_tracefunc func, PyObject *obj, PyFrameObject *frame, - int what, PyObject *arg) + int what, PyObject *arg) { - PyObject *type, *value, *traceback; - int err; - PyErr_Fetch(&type, &value, &traceback); - err = call_trace(func, obj, frame, what, arg); - if (err == 0) - { - PyErr_Restore(type, value, traceback); - return 0; - } - else { - Py_XDECREF(type); - Py_XDECREF(value); - Py_XDECREF(traceback); - return -1; - } + PyObject *type, *value, *traceback; + int err; + PyErr_Fetch(&type, &value, &traceback); + err = call_trace(func, obj, frame, what, arg); + if (err == 0) + { + PyErr_Restore(type, value, traceback); + return 0; + } + else { + Py_XDECREF(type); + Py_XDECREF(value); + Py_XDECREF(traceback); + return -1; + } } static int call_trace(Py_tracefunc func, PyObject *obj, PyFrameObject *frame, - int what, PyObject *arg) + int what, PyObject *arg) { - register PyThreadState *tstate = frame->f_tstate; - int result; - if (tstate->tracing) - return 0; - tstate->tracing++; - tstate->use_tracing = 0; - result = func(obj, frame, what, arg); - tstate->use_tracing = ((tstate->c_tracefunc != NULL) - || (tstate->c_profilefunc != NULL)); - tstate->tracing--; - return result; + register PyThreadState *tstate = frame->f_tstate; + int result; + if (tstate->tracing) + return 0; + tstate->tracing++; + tstate->use_tracing = 0; + result = func(obj, frame, what, arg); + tstate->use_tracing = ((tstate->c_tracefunc != NULL) + || (tstate->c_profilefunc != NULL)); + tstate->tracing--; + return result; } PyObject * _PyEval_CallTracing(PyObject *func, PyObject *args) { - PyFrameObject *frame = PyEval_GetFrame(); - PyThreadState *tstate = frame->f_tstate; - int save_tracing = tstate->tracing; - int save_use_tracing = tstate->use_tracing; - PyObject *result; - - tstate->tracing = 0; - tstate->use_tracing = ((tstate->c_tracefunc != NULL) - || (tstate->c_profilefunc != NULL)); - result = PyObject_Call(func, args, NULL); - tstate->tracing = save_tracing; - tstate->use_tracing = save_use_tracing; - return result; + PyFrameObject *frame = PyEval_GetFrame(); + PyThreadState *tstate = frame->f_tstate; + int save_tracing = tstate->tracing; + int save_use_tracing = tstate->use_tracing; + PyObject *result; + + tstate->tracing = 0; + tstate->use_tracing = ((tstate->c_tracefunc != NULL) + || (tstate->c_profilefunc != NULL)); + result = PyObject_Call(func, args, NULL); + tstate->tracing = save_tracing; + tstate->use_tracing = save_use_tracing; + return result; } /* See Objects/lnotab_notes.txt for a description of how tracing works. */ static int maybe_call_line_trace(Py_tracefunc func, PyObject *obj, - PyFrameObject *frame, int *instr_lb, int *instr_ub, - int *instr_prev) + PyFrameObject *frame, int *instr_lb, int *instr_ub, + int *instr_prev) { - int result = 0; - int line = frame->f_lineno; + int result = 0; + int line = frame->f_lineno; - /* If the last instruction executed isn't in the current - instruction window, reset the window. - */ - if (frame->f_lasti < *instr_lb || frame->f_lasti >= *instr_ub) { - PyAddrPair bounds; - line = _PyCode_CheckLineNumber(frame->f_code, frame->f_lasti, - &bounds); - *instr_lb = bounds.ap_lower; - *instr_ub = bounds.ap_upper; - } - /* If the last instruction falls at the start of a line or if - it represents a jump backwards, update the frame's line - number and call the trace function. */ - if (frame->f_lasti == *instr_lb || frame->f_lasti < *instr_prev) { - frame->f_lineno = line; - result = call_trace(func, obj, frame, PyTrace_LINE, Py_None); - } - *instr_prev = frame->f_lasti; - return result; + /* If the last instruction executed isn't in the current + instruction window, reset the window. + */ + if (frame->f_lasti < *instr_lb || frame->f_lasti >= *instr_ub) { + PyAddrPair bounds; + line = _PyCode_CheckLineNumber(frame->f_code, frame->f_lasti, + &bounds); + *instr_lb = bounds.ap_lower; + *instr_ub = bounds.ap_upper; + } + /* If the last instruction falls at the start of a line or if + it represents a jump backwards, update the frame's line + number and call the trace function. */ + if (frame->f_lasti == *instr_lb || frame->f_lasti < *instr_prev) { + frame->f_lineno = line; + result = call_trace(func, obj, frame, PyTrace_LINE, Py_None); + } + *instr_prev = frame->f_lasti; + return result; } void PyEval_SetProfile(Py_tracefunc func, PyObject *arg) { - PyThreadState *tstate = PyThreadState_GET(); - PyObject *temp = tstate->c_profileobj; - Py_XINCREF(arg); - tstate->c_profilefunc = NULL; - tstate->c_profileobj = NULL; - /* Must make sure that tracing is not ignored if 'temp' is freed */ - tstate->use_tracing = tstate->c_tracefunc != NULL; - Py_XDECREF(temp); - tstate->c_profilefunc = func; - tstate->c_profileobj = arg; - /* Flag that tracing or profiling is turned on */ - tstate->use_tracing = (func != NULL) || (tstate->c_tracefunc != NULL); + PyThreadState *tstate = PyThreadState_GET(); + PyObject *temp = tstate->c_profileobj; + Py_XINCREF(arg); + tstate->c_profilefunc = NULL; + tstate->c_profileobj = NULL; + /* Must make sure that tracing is not ignored if 'temp' is freed */ + tstate->use_tracing = tstate->c_tracefunc != NULL; + Py_XDECREF(temp); + tstate->c_profilefunc = func; + tstate->c_profileobj = arg; + /* Flag that tracing or profiling is turned on */ + tstate->use_tracing = (func != NULL) || (tstate->c_tracefunc != NULL); } void PyEval_SetTrace(Py_tracefunc func, PyObject *arg) { - PyThreadState *tstate = PyThreadState_GET(); - PyObject *temp = tstate->c_traceobj; - _Py_TracingPossible += (func != NULL) - (tstate->c_tracefunc != NULL); - Py_XINCREF(arg); - tstate->c_tracefunc = NULL; - tstate->c_traceobj = NULL; - /* Must make sure that profiling is not ignored if 'temp' is freed */ - tstate->use_tracing = tstate->c_profilefunc != NULL; - Py_XDECREF(temp); - tstate->c_tracefunc = func; - tstate->c_traceobj = arg; - /* Flag that tracing or profiling is turned on */ - tstate->use_tracing = ((func != NULL) - || (tstate->c_profilefunc != NULL)); + PyThreadState *tstate = PyThreadState_GET(); + PyObject *temp = tstate->c_traceobj; + _Py_TracingPossible += (func != NULL) - (tstate->c_tracefunc != NULL); + Py_XINCREF(arg); + tstate->c_tracefunc = NULL; + tstate->c_traceobj = NULL; + /* Must make sure that profiling is not ignored if 'temp' is freed */ + tstate->use_tracing = tstate->c_profilefunc != NULL; + Py_XDECREF(temp); + tstate->c_tracefunc = func; + tstate->c_traceobj = arg; + /* Flag that tracing or profiling is turned on */ + tstate->use_tracing = ((func != NULL) + || (tstate->c_profilefunc != NULL)); } PyObject * PyEval_GetBuiltins(void) { - PyFrameObject *current_frame = PyEval_GetFrame(); - if (current_frame == NULL) - return PyThreadState_GET()->interp->builtins; - else - return current_frame->f_builtins; + PyFrameObject *current_frame = PyEval_GetFrame(); + if (current_frame == NULL) + return PyThreadState_GET()->interp->builtins; + else + return current_frame->f_builtins; } PyObject * PyEval_GetLocals(void) { - PyFrameObject *current_frame = PyEval_GetFrame(); - if (current_frame == NULL) - return NULL; - PyFrame_FastToLocals(current_frame); - return current_frame->f_locals; + PyFrameObject *current_frame = PyEval_GetFrame(); + if (current_frame == NULL) + return NULL; + PyFrame_FastToLocals(current_frame); + return current_frame->f_locals; } PyObject * PyEval_GetGlobals(void) { - PyFrameObject *current_frame = PyEval_GetFrame(); - if (current_frame == NULL) - return NULL; - else - return current_frame->f_globals; + PyFrameObject *current_frame = PyEval_GetFrame(); + if (current_frame == NULL) + return NULL; + else + return current_frame->f_globals; } PyFrameObject * PyEval_GetFrame(void) { - PyThreadState *tstate = PyThreadState_GET(); - return _PyThreadState_GetFrame(tstate); + PyThreadState *tstate = PyThreadState_GET(); + return _PyThreadState_GetFrame(tstate); } int PyEval_MergeCompilerFlags(PyCompilerFlags *cf) { - PyFrameObject *current_frame = PyEval_GetFrame(); - int result = cf->cf_flags != 0; + PyFrameObject *current_frame = PyEval_GetFrame(); + int result = cf->cf_flags != 0; - if (current_frame != NULL) { - const int codeflags = current_frame->f_code->co_flags; - const int compilerflags = codeflags & PyCF_MASK; - if (compilerflags) { - result = 1; - cf->cf_flags |= compilerflags; - } + if (current_frame != NULL) { + const int codeflags = current_frame->f_code->co_flags; + const int compilerflags = codeflags & PyCF_MASK; + if (compilerflags) { + result = 1; + cf->cf_flags |= compilerflags; + } #if 0 /* future keyword */ - if (codeflags & CO_GENERATOR_ALLOWED) { - result = 1; - cf->cf_flags |= CO_GENERATOR_ALLOWED; - } + if (codeflags & CO_GENERATOR_ALLOWED) { + result = 1; + cf->cf_flags |= CO_GENERATOR_ALLOWED; + } #endif - } - return result; + } + return result; } @@ -3725,186 +3725,186 @@ PyObject * PyEval_CallObjectWithKeywords(PyObject *func, PyObject *arg, PyObject *kw) { - PyObject *result; + PyObject *result; - if (arg == NULL) { - arg = PyTuple_New(0); - if (arg == NULL) - return NULL; - } - else if (!PyTuple_Check(arg)) { - PyErr_SetString(PyExc_TypeError, - "argument list must be a tuple"); - return NULL; - } - else - Py_INCREF(arg); - - if (kw != NULL && !PyDict_Check(kw)) { - PyErr_SetString(PyExc_TypeError, - "keyword list must be a dictionary"); - Py_DECREF(arg); - return NULL; - } - - result = PyObject_Call(func, arg, kw); - Py_DECREF(arg); - return result; + if (arg == NULL) { + arg = PyTuple_New(0); + if (arg == NULL) + return NULL; + } + else if (!PyTuple_Check(arg)) { + PyErr_SetString(PyExc_TypeError, + "argument list must be a tuple"); + return NULL; + } + else + Py_INCREF(arg); + + if (kw != NULL && !PyDict_Check(kw)) { + PyErr_SetString(PyExc_TypeError, + "keyword list must be a dictionary"); + Py_DECREF(arg); + return NULL; + } + + result = PyObject_Call(func, arg, kw); + Py_DECREF(arg); + return result; } const char * PyEval_GetFuncName(PyObject *func) { - if (PyMethod_Check(func)) - return PyEval_GetFuncName(PyMethod_GET_FUNCTION(func)); - else if (PyFunction_Check(func)) - return _PyUnicode_AsString(((PyFunctionObject*)func)->func_name); - else if (PyCFunction_Check(func)) - return ((PyCFunctionObject*)func)->m_ml->ml_name; - else - return func->ob_type->tp_name; + if (PyMethod_Check(func)) + return PyEval_GetFuncName(PyMethod_GET_FUNCTION(func)); + else if (PyFunction_Check(func)) + return _PyUnicode_AsString(((PyFunctionObject*)func)->func_name); + else if (PyCFunction_Check(func)) + return ((PyCFunctionObject*)func)->m_ml->ml_name; + else + return func->ob_type->tp_name; } const char * PyEval_GetFuncDesc(PyObject *func) { - if (PyMethod_Check(func)) - return "()"; - else if (PyFunction_Check(func)) - return "()"; - else if (PyCFunction_Check(func)) - return "()"; - else - return " object"; + if (PyMethod_Check(func)) + return "()"; + else if (PyFunction_Check(func)) + return "()"; + else if (PyCFunction_Check(func)) + return "()"; + else + return " object"; } static void err_args(PyObject *func, int flags, int nargs) { - if (flags & METH_NOARGS) - PyErr_Format(PyExc_TypeError, - "%.200s() takes no arguments (%d given)", - ((PyCFunctionObject *)func)->m_ml->ml_name, - nargs); - else - PyErr_Format(PyExc_TypeError, - "%.200s() takes exactly one argument (%d given)", - ((PyCFunctionObject *)func)->m_ml->ml_name, - nargs); + if (flags & METH_NOARGS) + PyErr_Format(PyExc_TypeError, + "%.200s() takes no arguments (%d given)", + ((PyCFunctionObject *)func)->m_ml->ml_name, + nargs); + else + PyErr_Format(PyExc_TypeError, + "%.200s() takes exactly one argument (%d given)", + ((PyCFunctionObject *)func)->m_ml->ml_name, + nargs); } #define C_TRACE(x, call) \ if (tstate->use_tracing && tstate->c_profilefunc) { \ - if (call_trace(tstate->c_profilefunc, \ - tstate->c_profileobj, \ - tstate->frame, PyTrace_C_CALL, \ - func)) { \ - x = NULL; \ - } \ - else { \ - x = call; \ - if (tstate->c_profilefunc != NULL) { \ - if (x == NULL) { \ - call_trace_protected(tstate->c_profilefunc, \ - tstate->c_profileobj, \ - tstate->frame, PyTrace_C_EXCEPTION, \ - func); \ - /* XXX should pass (type, value, tb) */ \ - } else { \ - if (call_trace(tstate->c_profilefunc, \ - tstate->c_profileobj, \ - tstate->frame, PyTrace_C_RETURN, \ - func)) { \ - Py_DECREF(x); \ - x = NULL; \ - } \ - } \ - } \ - } \ + if (call_trace(tstate->c_profilefunc, \ + tstate->c_profileobj, \ + tstate->frame, PyTrace_C_CALL, \ + func)) { \ + x = NULL; \ + } \ + else { \ + x = call; \ + if (tstate->c_profilefunc != NULL) { \ + if (x == NULL) { \ + call_trace_protected(tstate->c_profilefunc, \ + tstate->c_profileobj, \ + tstate->frame, PyTrace_C_EXCEPTION, \ + func); \ + /* XXX should pass (type, value, tb) */ \ + } else { \ + if (call_trace(tstate->c_profilefunc, \ + tstate->c_profileobj, \ + tstate->frame, PyTrace_C_RETURN, \ + func)) { \ + Py_DECREF(x); \ + x = NULL; \ + } \ + } \ + } \ + } \ } else { \ - x = call; \ - } + x = call; \ + } static PyObject * call_function(PyObject ***pp_stack, int oparg #ifdef WITH_TSC - , uint64* pintr0, uint64* pintr1 + , uint64* pintr0, uint64* pintr1 #endif - ) + ) { - int na = oparg & 0xff; - int nk = (oparg>>8) & 0xff; - int n = na + 2 * nk; - PyObject **pfunc = (*pp_stack) - n - 1; - PyObject *func = *pfunc; - PyObject *x, *w; - - /* Always dispatch PyCFunction first, because these are - presumed to be the most frequent callable object. - */ - if (PyCFunction_Check(func) && nk == 0) { - int flags = PyCFunction_GET_FLAGS(func); - PyThreadState *tstate = PyThreadState_GET(); - - PCALL(PCALL_CFUNCTION); - if (flags & (METH_NOARGS | METH_O)) { - PyCFunction meth = PyCFunction_GET_FUNCTION(func); - PyObject *self = PyCFunction_GET_SELF(func); - if (flags & METH_NOARGS && na == 0) { - C_TRACE(x, (*meth)(self,NULL)); - } - else if (flags & METH_O && na == 1) { - PyObject *arg = EXT_POP(*pp_stack); - C_TRACE(x, (*meth)(self,arg)); - Py_DECREF(arg); - } - else { - err_args(func, flags, na); - x = NULL; - } - } - else { - PyObject *callargs; - callargs = load_args(pp_stack, na); - READ_TIMESTAMP(*pintr0); - C_TRACE(x, PyCFunction_Call(func,callargs,NULL)); - READ_TIMESTAMP(*pintr1); - Py_XDECREF(callargs); - } - } else { - if (PyMethod_Check(func) && PyMethod_GET_SELF(func) != NULL) { - /* optimize access to bound methods */ - PyObject *self = PyMethod_GET_SELF(func); - PCALL(PCALL_METHOD); - PCALL(PCALL_BOUND_METHOD); - Py_INCREF(self); - func = PyMethod_GET_FUNCTION(func); - Py_INCREF(func); - Py_DECREF(*pfunc); - *pfunc = self; - na++; - n++; - } else - Py_INCREF(func); - READ_TIMESTAMP(*pintr0); - if (PyFunction_Check(func)) - x = fast_function(func, pp_stack, n, na, nk); - else - x = do_call(func, pp_stack, na, nk); - READ_TIMESTAMP(*pintr1); - Py_DECREF(func); - } - - /* Clear the stack of the function object. Also removes - the arguments in case they weren't consumed already - (fast_function() and err_args() leave them on the stack). - */ - while ((*pp_stack) > pfunc) { - w = EXT_POP(*pp_stack); - Py_DECREF(w); - PCALL(PCALL_POP); - } - return x; + int na = oparg & 0xff; + int nk = (oparg>>8) & 0xff; + int n = na + 2 * nk; + PyObject **pfunc = (*pp_stack) - n - 1; + PyObject *func = *pfunc; + PyObject *x, *w; + + /* Always dispatch PyCFunction first, because these are + presumed to be the most frequent callable object. + */ + if (PyCFunction_Check(func) && nk == 0) { + int flags = PyCFunction_GET_FLAGS(func); + PyThreadState *tstate = PyThreadState_GET(); + + PCALL(PCALL_CFUNCTION); + if (flags & (METH_NOARGS | METH_O)) { + PyCFunction meth = PyCFunction_GET_FUNCTION(func); + PyObject *self = PyCFunction_GET_SELF(func); + if (flags & METH_NOARGS && na == 0) { + C_TRACE(x, (*meth)(self,NULL)); + } + else if (flags & METH_O && na == 1) { + PyObject *arg = EXT_POP(*pp_stack); + C_TRACE(x, (*meth)(self,arg)); + Py_DECREF(arg); + } + else { + err_args(func, flags, na); + x = NULL; + } + } + else { + PyObject *callargs; + callargs = load_args(pp_stack, na); + READ_TIMESTAMP(*pintr0); + C_TRACE(x, PyCFunction_Call(func,callargs,NULL)); + READ_TIMESTAMP(*pintr1); + Py_XDECREF(callargs); + } + } else { + if (PyMethod_Check(func) && PyMethod_GET_SELF(func) != NULL) { + /* optimize access to bound methods */ + PyObject *self = PyMethod_GET_SELF(func); + PCALL(PCALL_METHOD); + PCALL(PCALL_BOUND_METHOD); + Py_INCREF(self); + func = PyMethod_GET_FUNCTION(func); + Py_INCREF(func); + Py_DECREF(*pfunc); + *pfunc = self; + na++; + n++; + } else + Py_INCREF(func); + READ_TIMESTAMP(*pintr0); + if (PyFunction_Check(func)) + x = fast_function(func, pp_stack, n, na, nk); + else + x = do_call(func, pp_stack, na, nk); + READ_TIMESTAMP(*pintr1); + Py_DECREF(func); + } + + /* Clear the stack of the function object. Also removes + the arguments in case they weren't consumed already + (fast_function() and err_args() leave them on the stack). + */ + while ((*pp_stack) > pfunc) { + w = EXT_POP(*pp_stack); + Py_DECREF(w); + PCALL(PCALL_POP); + } + return x; } /* The fast_function() function optimize calls for which no argument @@ -3919,275 +3919,275 @@ static PyObject * fast_function(PyObject *func, PyObject ***pp_stack, int n, int na, int nk) { - PyCodeObject *co = (PyCodeObject *)PyFunction_GET_CODE(func); - PyObject *globals = PyFunction_GET_GLOBALS(func); - PyObject *argdefs = PyFunction_GET_DEFAULTS(func); - PyObject *kwdefs = PyFunction_GET_KW_DEFAULTS(func); - PyObject **d = NULL; - int nd = 0; - - PCALL(PCALL_FUNCTION); - PCALL(PCALL_FAST_FUNCTION); - if (argdefs == NULL && co->co_argcount == n && - co->co_kwonlyargcount == 0 && nk==0 && - co->co_flags == (CO_OPTIMIZED | CO_NEWLOCALS | CO_NOFREE)) { - PyFrameObject *f; - PyObject *retval = NULL; - PyThreadState *tstate = PyThreadState_GET(); - PyObject **fastlocals, **stack; - int i; - - PCALL(PCALL_FASTER_FUNCTION); - assert(globals != NULL); - /* XXX Perhaps we should create a specialized - PyFrame_New() that doesn't take locals, but does - take builtins without sanity checking them. - */ - assert(tstate != NULL); - f = PyFrame_New(tstate, co, globals, NULL); - if (f == NULL) - return NULL; - - fastlocals = f->f_localsplus; - stack = (*pp_stack) - n; - - for (i = 0; i < n; i++) { - Py_INCREF(*stack); - fastlocals[i] = *stack++; - } - retval = PyEval_EvalFrameEx(f,0); - ++tstate->recursion_depth; - Py_DECREF(f); - --tstate->recursion_depth; - return retval; - } - if (argdefs != NULL) { - d = &PyTuple_GET_ITEM(argdefs, 0); - nd = Py_SIZE(argdefs); - } - return PyEval_EvalCodeEx(co, globals, - (PyObject *)NULL, (*pp_stack)-n, na, - (*pp_stack)-2*nk, nk, d, nd, kwdefs, - PyFunction_GET_CLOSURE(func)); + PyCodeObject *co = (PyCodeObject *)PyFunction_GET_CODE(func); + PyObject *globals = PyFunction_GET_GLOBALS(func); + PyObject *argdefs = PyFunction_GET_DEFAULTS(func); + PyObject *kwdefs = PyFunction_GET_KW_DEFAULTS(func); + PyObject **d = NULL; + int nd = 0; + + PCALL(PCALL_FUNCTION); + PCALL(PCALL_FAST_FUNCTION); + if (argdefs == NULL && co->co_argcount == n && + co->co_kwonlyargcount == 0 && nk==0 && + co->co_flags == (CO_OPTIMIZED | CO_NEWLOCALS | CO_NOFREE)) { + PyFrameObject *f; + PyObject *retval = NULL; + PyThreadState *tstate = PyThreadState_GET(); + PyObject **fastlocals, **stack; + int i; + + PCALL(PCALL_FASTER_FUNCTION); + assert(globals != NULL); + /* XXX Perhaps we should create a specialized + PyFrame_New() that doesn't take locals, but does + take builtins without sanity checking them. + */ + assert(tstate != NULL); + f = PyFrame_New(tstate, co, globals, NULL); + if (f == NULL) + return NULL; + + fastlocals = f->f_localsplus; + stack = (*pp_stack) - n; + + for (i = 0; i < n; i++) { + Py_INCREF(*stack); + fastlocals[i] = *stack++; + } + retval = PyEval_EvalFrameEx(f,0); + ++tstate->recursion_depth; + Py_DECREF(f); + --tstate->recursion_depth; + return retval; + } + if (argdefs != NULL) { + d = &PyTuple_GET_ITEM(argdefs, 0); + nd = Py_SIZE(argdefs); + } + return PyEval_EvalCodeEx(co, globals, + (PyObject *)NULL, (*pp_stack)-n, na, + (*pp_stack)-2*nk, nk, d, nd, kwdefs, + PyFunction_GET_CLOSURE(func)); } static PyObject * update_keyword_args(PyObject *orig_kwdict, int nk, PyObject ***pp_stack, PyObject *func) { - PyObject *kwdict = NULL; - if (orig_kwdict == NULL) - kwdict = PyDict_New(); - else { - kwdict = PyDict_Copy(orig_kwdict); - Py_DECREF(orig_kwdict); - } - if (kwdict == NULL) - return NULL; - while (--nk >= 0) { - int err; - PyObject *value = EXT_POP(*pp_stack); - PyObject *key = EXT_POP(*pp_stack); - if (PyDict_GetItem(kwdict, key) != NULL) { - PyErr_Format(PyExc_TypeError, - "%.200s%s got multiple values " - "for keyword argument '%U'", - PyEval_GetFuncName(func), - PyEval_GetFuncDesc(func), - key); - Py_DECREF(key); - Py_DECREF(value); - Py_DECREF(kwdict); - return NULL; - } - err = PyDict_SetItem(kwdict, key, value); - Py_DECREF(key); - Py_DECREF(value); - if (err) { - Py_DECREF(kwdict); - return NULL; - } - } - return kwdict; + PyObject *kwdict = NULL; + if (orig_kwdict == NULL) + kwdict = PyDict_New(); + else { + kwdict = PyDict_Copy(orig_kwdict); + Py_DECREF(orig_kwdict); + } + if (kwdict == NULL) + return NULL; + while (--nk >= 0) { + int err; + PyObject *value = EXT_POP(*pp_stack); + PyObject *key = EXT_POP(*pp_stack); + if (PyDict_GetItem(kwdict, key) != NULL) { + PyErr_Format(PyExc_TypeError, + "%.200s%s got multiple values " + "for keyword argument '%U'", + PyEval_GetFuncName(func), + PyEval_GetFuncDesc(func), + key); + Py_DECREF(key); + Py_DECREF(value); + Py_DECREF(kwdict); + return NULL; + } + err = PyDict_SetItem(kwdict, key, value); + Py_DECREF(key); + Py_DECREF(value); + if (err) { + Py_DECREF(kwdict); + return NULL; + } + } + return kwdict; } static PyObject * update_star_args(int nstack, int nstar, PyObject *stararg, - PyObject ***pp_stack) + PyObject ***pp_stack) { - PyObject *callargs, *w; + PyObject *callargs, *w; - callargs = PyTuple_New(nstack + nstar); - if (callargs == NULL) { - return NULL; - } - if (nstar) { - int i; - for (i = 0; i < nstar; i++) { - PyObject *a = PyTuple_GET_ITEM(stararg, i); - Py_INCREF(a); - PyTuple_SET_ITEM(callargs, nstack + i, a); - } - } - while (--nstack >= 0) { - w = EXT_POP(*pp_stack); - PyTuple_SET_ITEM(callargs, nstack, w); - } - return callargs; + callargs = PyTuple_New(nstack + nstar); + if (callargs == NULL) { + return NULL; + } + if (nstar) { + int i; + for (i = 0; i < nstar; i++) { + PyObject *a = PyTuple_GET_ITEM(stararg, i); + Py_INCREF(a); + PyTuple_SET_ITEM(callargs, nstack + i, a); + } + } + while (--nstack >= 0) { + w = EXT_POP(*pp_stack); + PyTuple_SET_ITEM(callargs, nstack, w); + } + return callargs; } static PyObject * load_args(PyObject ***pp_stack, int na) { - PyObject *args = PyTuple_New(na); - PyObject *w; + PyObject *args = PyTuple_New(na); + PyObject *w; - if (args == NULL) - return NULL; - while (--na >= 0) { - w = EXT_POP(*pp_stack); - PyTuple_SET_ITEM(args, na, w); - } - return args; + if (args == NULL) + return NULL; + while (--na >= 0) { + w = EXT_POP(*pp_stack); + PyTuple_SET_ITEM(args, na, w); + } + return args; } static PyObject * do_call(PyObject *func, PyObject ***pp_stack, int na, int nk) { - PyObject *callargs = NULL; - PyObject *kwdict = NULL; - PyObject *result = NULL; - - if (nk > 0) { - kwdict = update_keyword_args(NULL, nk, pp_stack, func); - if (kwdict == NULL) - goto call_fail; - } - callargs = load_args(pp_stack, na); - if (callargs == NULL) - goto call_fail; + PyObject *callargs = NULL; + PyObject *kwdict = NULL; + PyObject *result = NULL; + + if (nk > 0) { + kwdict = update_keyword_args(NULL, nk, pp_stack, func); + if (kwdict == NULL) + goto call_fail; + } + callargs = load_args(pp_stack, na); + if (callargs == NULL) + goto call_fail; #ifdef CALL_PROFILE - /* At this point, we have to look at the type of func to - update the call stats properly. Do it here so as to avoid - exposing the call stats machinery outside ceval.c - */ - if (PyFunction_Check(func)) - PCALL(PCALL_FUNCTION); - else if (PyMethod_Check(func)) - PCALL(PCALL_METHOD); - else if (PyType_Check(func)) - PCALL(PCALL_TYPE); - else if (PyCFunction_Check(func)) - PCALL(PCALL_CFUNCTION); - else - PCALL(PCALL_OTHER); -#endif - if (PyCFunction_Check(func)) { - PyThreadState *tstate = PyThreadState_GET(); - C_TRACE(result, PyCFunction_Call(func, callargs, kwdict)); - } - else - result = PyObject_Call(func, callargs, kwdict); + /* At this point, we have to look at the type of func to + update the call stats properly. Do it here so as to avoid + exposing the call stats machinery outside ceval.c + */ + if (PyFunction_Check(func)) + PCALL(PCALL_FUNCTION); + else if (PyMethod_Check(func)) + PCALL(PCALL_METHOD); + else if (PyType_Check(func)) + PCALL(PCALL_TYPE); + else if (PyCFunction_Check(func)) + PCALL(PCALL_CFUNCTION); + else + PCALL(PCALL_OTHER); +#endif + if (PyCFunction_Check(func)) { + PyThreadState *tstate = PyThreadState_GET(); + C_TRACE(result, PyCFunction_Call(func, callargs, kwdict)); + } + else + result = PyObject_Call(func, callargs, kwdict); call_fail: - Py_XDECREF(callargs); - Py_XDECREF(kwdict); - return result; + Py_XDECREF(callargs); + Py_XDECREF(kwdict); + return result; } static PyObject * ext_do_call(PyObject *func, PyObject ***pp_stack, int flags, int na, int nk) { - int nstar = 0; - PyObject *callargs = NULL; - PyObject *stararg = NULL; - PyObject *kwdict = NULL; - PyObject *result = NULL; - - if (flags & CALL_FLAG_KW) { - kwdict = EXT_POP(*pp_stack); - if (!PyDict_Check(kwdict)) { - PyObject *d; - d = PyDict_New(); - if (d == NULL) - goto ext_call_fail; - if (PyDict_Update(d, kwdict) != 0) { - Py_DECREF(d); - /* PyDict_Update raises attribute - * error (percolated from an attempt - * to get 'keys' attribute) instead of - * a type error if its second argument - * is not a mapping. - */ - if (PyErr_ExceptionMatches(PyExc_AttributeError)) { - PyErr_Format(PyExc_TypeError, - "%.200s%.200s argument after ** " - "must be a mapping, not %.200s", - PyEval_GetFuncName(func), - PyEval_GetFuncDesc(func), - kwdict->ob_type->tp_name); - } - goto ext_call_fail; - } - Py_DECREF(kwdict); - kwdict = d; - } - } - if (flags & CALL_FLAG_VAR) { - stararg = EXT_POP(*pp_stack); - if (!PyTuple_Check(stararg)) { - PyObject *t = NULL; - t = PySequence_Tuple(stararg); - if (t == NULL) { - if (PyErr_ExceptionMatches(PyExc_TypeError)) { - PyErr_Format(PyExc_TypeError, - "%.200s%.200s argument after * " - "must be a sequence, not %200s", - PyEval_GetFuncName(func), - PyEval_GetFuncDesc(func), - stararg->ob_type->tp_name); - } - goto ext_call_fail; - } - Py_DECREF(stararg); - stararg = t; - } - nstar = PyTuple_GET_SIZE(stararg); - } - if (nk > 0) { - kwdict = update_keyword_args(kwdict, nk, pp_stack, func); - if (kwdict == NULL) - goto ext_call_fail; - } - callargs = update_star_args(na, nstar, stararg, pp_stack); - if (callargs == NULL) - goto ext_call_fail; + int nstar = 0; + PyObject *callargs = NULL; + PyObject *stararg = NULL; + PyObject *kwdict = NULL; + PyObject *result = NULL; + + if (flags & CALL_FLAG_KW) { + kwdict = EXT_POP(*pp_stack); + if (!PyDict_Check(kwdict)) { + PyObject *d; + d = PyDict_New(); + if (d == NULL) + goto ext_call_fail; + if (PyDict_Update(d, kwdict) != 0) { + Py_DECREF(d); + /* PyDict_Update raises attribute + * error (percolated from an attempt + * to get 'keys' attribute) instead of + * a type error if its second argument + * is not a mapping. + */ + if (PyErr_ExceptionMatches(PyExc_AttributeError)) { + PyErr_Format(PyExc_TypeError, + "%.200s%.200s argument after ** " + "must be a mapping, not %.200s", + PyEval_GetFuncName(func), + PyEval_GetFuncDesc(func), + kwdict->ob_type->tp_name); + } + goto ext_call_fail; + } + Py_DECREF(kwdict); + kwdict = d; + } + } + if (flags & CALL_FLAG_VAR) { + stararg = EXT_POP(*pp_stack); + if (!PyTuple_Check(stararg)) { + PyObject *t = NULL; + t = PySequence_Tuple(stararg); + if (t == NULL) { + if (PyErr_ExceptionMatches(PyExc_TypeError)) { + PyErr_Format(PyExc_TypeError, + "%.200s%.200s argument after * " + "must be a sequence, not %200s", + PyEval_GetFuncName(func), + PyEval_GetFuncDesc(func), + stararg->ob_type->tp_name); + } + goto ext_call_fail; + } + Py_DECREF(stararg); + stararg = t; + } + nstar = PyTuple_GET_SIZE(stararg); + } + if (nk > 0) { + kwdict = update_keyword_args(kwdict, nk, pp_stack, func); + if (kwdict == NULL) + goto ext_call_fail; + } + callargs = update_star_args(na, nstar, stararg, pp_stack); + if (callargs == NULL) + goto ext_call_fail; #ifdef CALL_PROFILE - /* At this point, we have to look at the type of func to - update the call stats properly. Do it here so as to avoid - exposing the call stats machinery outside ceval.c - */ - if (PyFunction_Check(func)) - PCALL(PCALL_FUNCTION); - else if (PyMethod_Check(func)) - PCALL(PCALL_METHOD); - else if (PyType_Check(func)) - PCALL(PCALL_TYPE); - else if (PyCFunction_Check(func)) - PCALL(PCALL_CFUNCTION); - else - PCALL(PCALL_OTHER); -#endif - if (PyCFunction_Check(func)) { - PyThreadState *tstate = PyThreadState_GET(); - C_TRACE(result, PyCFunction_Call(func, callargs, kwdict)); - } - else - result = PyObject_Call(func, callargs, kwdict); + /* At this point, we have to look at the type of func to + update the call stats properly. Do it here so as to avoid + exposing the call stats machinery outside ceval.c + */ + if (PyFunction_Check(func)) + PCALL(PCALL_FUNCTION); + else if (PyMethod_Check(func)) + PCALL(PCALL_METHOD); + else if (PyType_Check(func)) + PCALL(PCALL_TYPE); + else if (PyCFunction_Check(func)) + PCALL(PCALL_CFUNCTION); + else + PCALL(PCALL_OTHER); +#endif + if (PyCFunction_Check(func)) { + PyThreadState *tstate = PyThreadState_GET(); + C_TRACE(result, PyCFunction_Call(func, callargs, kwdict)); + } + else + result = PyObject_Call(func, callargs, kwdict); ext_call_fail: - Py_XDECREF(callargs); - Py_XDECREF(kwdict); - Py_XDECREF(stararg); - return result; + Py_XDECREF(callargs); + Py_XDECREF(kwdict); + Py_XDECREF(stararg); + return result; } /* Extract a slice index from a PyInt or PyLong or an object with the @@ -4203,245 +4203,245 @@ int _PyEval_SliceIndex(PyObject *v, Py_ssize_t *pi) { - if (v != NULL) { - Py_ssize_t x; - if (PyIndex_Check(v)) { - x = PyNumber_AsSsize_t(v, NULL); - if (x == -1 && PyErr_Occurred()) - return 0; - } - else { - PyErr_SetString(PyExc_TypeError, - "slice indices must be integers or " - "None or have an __index__ method"); - return 0; - } - *pi = x; - } - return 1; + if (v != NULL) { + Py_ssize_t x; + if (PyIndex_Check(v)) { + x = PyNumber_AsSsize_t(v, NULL); + if (x == -1 && PyErr_Occurred()) + return 0; + } + else { + PyErr_SetString(PyExc_TypeError, + "slice indices must be integers or " + "None or have an __index__ method"); + return 0; + } + *pi = x; + } + return 1; } #define CANNOT_CATCH_MSG "catching classes that do not inherit from "\ - "BaseException is not allowed" + "BaseException is not allowed" static PyObject * cmp_outcome(int op, register PyObject *v, register PyObject *w) { - int res = 0; - switch (op) { - case PyCmp_IS: - res = (v == w); - break; - case PyCmp_IS_NOT: - res = (v != w); - break; - case PyCmp_IN: - res = PySequence_Contains(w, v); - if (res < 0) - return NULL; - break; - case PyCmp_NOT_IN: - res = PySequence_Contains(w, v); - if (res < 0) - return NULL; - res = !res; - break; - case PyCmp_EXC_MATCH: - if (PyTuple_Check(w)) { - Py_ssize_t i, length; - length = PyTuple_Size(w); - for (i = 0; i < length; i += 1) { - PyObject *exc = PyTuple_GET_ITEM(w, i); - if (!PyExceptionClass_Check(exc)) { - PyErr_SetString(PyExc_TypeError, - CANNOT_CATCH_MSG); - return NULL; - } - } - } - else { - if (!PyExceptionClass_Check(w)) { - PyErr_SetString(PyExc_TypeError, - CANNOT_CATCH_MSG); - return NULL; - } - } - res = PyErr_GivenExceptionMatches(v, w); - break; - default: - return PyObject_RichCompare(v, w, op); - } - v = res ? Py_True : Py_False; - Py_INCREF(v); - return v; + int res = 0; + switch (op) { + case PyCmp_IS: + res = (v == w); + break; + case PyCmp_IS_NOT: + res = (v != w); + break; + case PyCmp_IN: + res = PySequence_Contains(w, v); + if (res < 0) + return NULL; + break; + case PyCmp_NOT_IN: + res = PySequence_Contains(w, v); + if (res < 0) + return NULL; + res = !res; + break; + case PyCmp_EXC_MATCH: + if (PyTuple_Check(w)) { + Py_ssize_t i, length; + length = PyTuple_Size(w); + for (i = 0; i < length; i += 1) { + PyObject *exc = PyTuple_GET_ITEM(w, i); + if (!PyExceptionClass_Check(exc)) { + PyErr_SetString(PyExc_TypeError, + CANNOT_CATCH_MSG); + return NULL; + } + } + } + else { + if (!PyExceptionClass_Check(w)) { + PyErr_SetString(PyExc_TypeError, + CANNOT_CATCH_MSG); + return NULL; + } + } + res = PyErr_GivenExceptionMatches(v, w); + break; + default: + return PyObject_RichCompare(v, w, op); + } + v = res ? Py_True : Py_False; + Py_INCREF(v); + return v; } static PyObject * import_from(PyObject *v, PyObject *name) { - PyObject *x; + PyObject *x; - x = PyObject_GetAttr(v, name); - if (x == NULL && PyErr_ExceptionMatches(PyExc_AttributeError)) { - PyErr_Format(PyExc_ImportError, "cannot import name %S", name); - } - return x; + x = PyObject_GetAttr(v, name); + if (x == NULL && PyErr_ExceptionMatches(PyExc_AttributeError)) { + PyErr_Format(PyExc_ImportError, "cannot import name %S", name); + } + return x; } static int import_all_from(PyObject *locals, PyObject *v) { - PyObject *all = PyObject_GetAttrString(v, "__all__"); - PyObject *dict, *name, *value; - int skip_leading_underscores = 0; - int pos, err; - - if (all == NULL) { - if (!PyErr_ExceptionMatches(PyExc_AttributeError)) - return -1; /* Unexpected error */ - PyErr_Clear(); - dict = PyObject_GetAttrString(v, "__dict__"); - if (dict == NULL) { - if (!PyErr_ExceptionMatches(PyExc_AttributeError)) - return -1; - PyErr_SetString(PyExc_ImportError, - "from-import-* object has no __dict__ and no __all__"); - return -1; - } - all = PyMapping_Keys(dict); - Py_DECREF(dict); - if (all == NULL) - return -1; - skip_leading_underscores = 1; - } - - for (pos = 0, err = 0; ; pos++) { - name = PySequence_GetItem(all, pos); - if (name == NULL) { - if (!PyErr_ExceptionMatches(PyExc_IndexError)) - err = -1; - else - PyErr_Clear(); - break; - } - if (skip_leading_underscores && - PyUnicode_Check(name) && - PyUnicode_AS_UNICODE(name)[0] == '_') - { - Py_DECREF(name); - continue; - } - value = PyObject_GetAttr(v, name); - if (value == NULL) - err = -1; - else if (PyDict_CheckExact(locals)) - err = PyDict_SetItem(locals, name, value); - else - err = PyObject_SetItem(locals, name, value); - Py_DECREF(name); - Py_XDECREF(value); - if (err != 0) - break; - } - Py_DECREF(all); - return err; + PyObject *all = PyObject_GetAttrString(v, "__all__"); + PyObject *dict, *name, *value; + int skip_leading_underscores = 0; + int pos, err; + + if (all == NULL) { + if (!PyErr_ExceptionMatches(PyExc_AttributeError)) + return -1; /* Unexpected error */ + PyErr_Clear(); + dict = PyObject_GetAttrString(v, "__dict__"); + if (dict == NULL) { + if (!PyErr_ExceptionMatches(PyExc_AttributeError)) + return -1; + PyErr_SetString(PyExc_ImportError, + "from-import-* object has no __dict__ and no __all__"); + return -1; + } + all = PyMapping_Keys(dict); + Py_DECREF(dict); + if (all == NULL) + return -1; + skip_leading_underscores = 1; + } + + for (pos = 0, err = 0; ; pos++) { + name = PySequence_GetItem(all, pos); + if (name == NULL) { + if (!PyErr_ExceptionMatches(PyExc_IndexError)) + err = -1; + else + PyErr_Clear(); + break; + } + if (skip_leading_underscores && + PyUnicode_Check(name) && + PyUnicode_AS_UNICODE(name)[0] == '_') + { + Py_DECREF(name); + continue; + } + value = PyObject_GetAttr(v, name); + if (value == NULL) + err = -1; + else if (PyDict_CheckExact(locals)) + err = PyDict_SetItem(locals, name, value); + else + err = PyObject_SetItem(locals, name, value); + Py_DECREF(name); + Py_XDECREF(value); + if (err != 0) + break; + } + Py_DECREF(all); + return err; } static void format_exc_check_arg(PyObject *exc, const char *format_str, PyObject *obj) { - const char *obj_str; + const char *obj_str; - if (!obj) - return; + if (!obj) + return; - obj_str = _PyUnicode_AsString(obj); - if (!obj_str) - return; + obj_str = _PyUnicode_AsString(obj); + if (!obj_str) + return; - PyErr_Format(exc, format_str, obj_str); + PyErr_Format(exc, format_str, obj_str); } static PyObject * unicode_concatenate(PyObject *v, PyObject *w, - PyFrameObject *f, unsigned char *next_instr) + PyFrameObject *f, unsigned char *next_instr) { - /* This function implements 'variable += expr' when both arguments - are (Unicode) strings. */ - Py_ssize_t v_len = PyUnicode_GET_SIZE(v); - Py_ssize_t w_len = PyUnicode_GET_SIZE(w); - Py_ssize_t new_len = v_len + w_len; - if (new_len < 0) { - PyErr_SetString(PyExc_OverflowError, - "strings are too large to concat"); - return NULL; - } - - if (v->ob_refcnt == 2) { - /* In the common case, there are 2 references to the value - * stored in 'variable' when the += is performed: one on the - * value stack (in 'v') and one still stored in the - * 'variable'. We try to delete the variable now to reduce - * the refcnt to 1. - */ - switch (*next_instr) { - case STORE_FAST: - { - int oparg = PEEKARG(); - PyObject **fastlocals = f->f_localsplus; - if (GETLOCAL(oparg) == v) - SETLOCAL(oparg, NULL); - break; - } - case STORE_DEREF: - { - PyObject **freevars = (f->f_localsplus + - f->f_code->co_nlocals); - PyObject *c = freevars[PEEKARG()]; - if (PyCell_GET(c) == v) - PyCell_Set(c, NULL); - break; - } - case STORE_NAME: - { - PyObject *names = f->f_code->co_names; - PyObject *name = GETITEM(names, PEEKARG()); - PyObject *locals = f->f_locals; - if (PyDict_CheckExact(locals) && - PyDict_GetItem(locals, name) == v) { - if (PyDict_DelItem(locals, name) != 0) { - PyErr_Clear(); - } - } - break; - } - } - } - - if (v->ob_refcnt == 1 && !PyUnicode_CHECK_INTERNED(v)) { - /* Now we own the last reference to 'v', so we can resize it - * in-place. - */ - if (PyUnicode_Resize(&v, new_len) != 0) { - /* XXX if PyUnicode_Resize() fails, 'v' has been - * deallocated so it cannot be put back into - * 'variable'. The MemoryError is raised when there - * is no value in 'variable', which might (very - * remotely) be a cause of incompatibilities. - */ - return NULL; - } - /* copy 'w' into the newly allocated area of 'v' */ - memcpy(PyUnicode_AS_UNICODE(v) + v_len, - PyUnicode_AS_UNICODE(w), w_len*sizeof(Py_UNICODE)); - return v; - } - else { - /* When in-place resizing is not an option. */ - w = PyUnicode_Concat(v, w); - Py_DECREF(v); - return w; - } + /* This function implements 'variable += expr' when both arguments + are (Unicode) strings. */ + Py_ssize_t v_len = PyUnicode_GET_SIZE(v); + Py_ssize_t w_len = PyUnicode_GET_SIZE(w); + Py_ssize_t new_len = v_len + w_len; + if (new_len < 0) { + PyErr_SetString(PyExc_OverflowError, + "strings are too large to concat"); + return NULL; + } + + if (v->ob_refcnt == 2) { + /* In the common case, there are 2 references to the value + * stored in 'variable' when the += is performed: one on the + * value stack (in 'v') and one still stored in the + * 'variable'. We try to delete the variable now to reduce + * the refcnt to 1. + */ + switch (*next_instr) { + case STORE_FAST: + { + int oparg = PEEKARG(); + PyObject **fastlocals = f->f_localsplus; + if (GETLOCAL(oparg) == v) + SETLOCAL(oparg, NULL); + break; + } + case STORE_DEREF: + { + PyObject **freevars = (f->f_localsplus + + f->f_code->co_nlocals); + PyObject *c = freevars[PEEKARG()]; + if (PyCell_GET(c) == v) + PyCell_Set(c, NULL); + break; + } + case STORE_NAME: + { + PyObject *names = f->f_code->co_names; + PyObject *name = GETITEM(names, PEEKARG()); + PyObject *locals = f->f_locals; + if (PyDict_CheckExact(locals) && + PyDict_GetItem(locals, name) == v) { + if (PyDict_DelItem(locals, name) != 0) { + PyErr_Clear(); + } + } + break; + } + } + } + + if (v->ob_refcnt == 1 && !PyUnicode_CHECK_INTERNED(v)) { + /* Now we own the last reference to 'v', so we can resize it + * in-place. + */ + if (PyUnicode_Resize(&v, new_len) != 0) { + /* XXX if PyUnicode_Resize() fails, 'v' has been + * deallocated so it cannot be put back into + * 'variable'. The MemoryError is raised when there + * is no value in 'variable', which might (very + * remotely) be a cause of incompatibilities. + */ + return NULL; + } + /* copy 'w' into the newly allocated area of 'v' */ + memcpy(PyUnicode_AS_UNICODE(v) + v_len, + PyUnicode_AS_UNICODE(w), w_len*sizeof(Py_UNICODE)); + return v; + } + else { + /* When in-place resizing is not an option. */ + w = PyUnicode_Concat(v, w); + Py_DECREF(v); + return w; + } } #ifdef DYNAMIC_EXECUTION_PROFILE @@ -4449,40 +4449,40 @@ static PyObject * getarray(long a[256]) { - int i; - PyObject *l = PyList_New(256); - if (l == NULL) return NULL; - for (i = 0; i < 256; i++) { - PyObject *x = PyLong_FromLong(a[i]); - if (x == NULL) { - Py_DECREF(l); - return NULL; - } - PyList_SetItem(l, i, x); - } - for (i = 0; i < 256; i++) - a[i] = 0; - return l; + int i; + PyObject *l = PyList_New(256); + if (l == NULL) return NULL; + for (i = 0; i < 256; i++) { + PyObject *x = PyLong_FromLong(a[i]); + if (x == NULL) { + Py_DECREF(l); + return NULL; + } + PyList_SetItem(l, i, x); + } + for (i = 0; i < 256; i++) + a[i] = 0; + return l; } PyObject * _Py_GetDXProfile(PyObject *self, PyObject *args) { #ifndef DXPAIRS - return getarray(dxp); + return getarray(dxp); #else - int i; - PyObject *l = PyList_New(257); - if (l == NULL) return NULL; - for (i = 0; i < 257; i++) { - PyObject *x = getarray(dxpairs[i]); - if (x == NULL) { - Py_DECREF(l); - return NULL; - } - PyList_SetItem(l, i, x); - } - return l; + int i; + PyObject *l = PyList_New(257); + if (l == NULL) return NULL; + for (i = 0; i < 257; i++) { + PyObject *x = getarray(dxpairs[i]); + if (x == NULL) { + Py_DECREF(l); + return NULL; + } + PyList_SetItem(l, i, x); + } + return l; #endif } Modified: python/branches/py3k-jit/Python/codecs.c ============================================================================== --- python/branches/py3k-jit/Python/codecs.c (original) +++ python/branches/py3k-jit/Python/codecs.c Mon May 10 23:55:43 2010 @@ -30,14 +30,14 @@ { PyInterpreterState *interp = PyThreadState_GET()->interp; if (interp->codec_search_path == NULL && _PyCodecRegistry_Init()) - goto onError; + goto onError; if (search_function == NULL) { - PyErr_BadArgument(); - goto onError; + PyErr_BadArgument(); + goto onError; } if (!PyCallable_Check(search_function)) { - PyErr_SetString(PyExc_TypeError, "argument must be callable"); - goto onError; + PyErr_SetString(PyExc_TypeError, "argument must be callable"); + goto onError; } return PyList_Append(interp->codec_search_path, search_function); @@ -57,8 +57,8 @@ PyObject *v; if (len > PY_SSIZE_T_MAX) { - PyErr_SetString(PyExc_OverflowError, "string is too large"); - return NULL; + PyErr_SetString(PyExc_OverflowError, "string is too large"); + return NULL; } p = PyMem_Malloc(len + 1); @@ -70,7 +70,7 @@ ch = '-'; else ch = tolower(Py_CHARMASK(ch)); - p[i] = ch; + p[i] = ch; } p[i] = '\0'; v = PyUnicode_FromString(p); @@ -102,78 +102,78 @@ Py_ssize_t i, len; if (encoding == NULL) { - PyErr_BadArgument(); - goto onError; + PyErr_BadArgument(); + goto onError; } interp = PyThreadState_GET()->interp; if (interp->codec_search_path == NULL && _PyCodecRegistry_Init()) - goto onError; + goto onError; /* Convert the encoding to a normalized Python string: all characters are converted to lower case, spaces and hyphens are replaced with underscores. */ v = normalizestring(encoding); if (v == NULL) - goto onError; + goto onError; PyUnicode_InternInPlace(&v); /* First, try to lookup the name in the registry dictionary */ result = PyDict_GetItem(interp->codec_search_cache, v); if (result != NULL) { - Py_INCREF(result); - Py_DECREF(v); - return result; + Py_INCREF(result); + Py_DECREF(v); + return result; } /* Next, scan the search functions in order of registration */ args = PyTuple_New(1); if (args == NULL) - goto onError; + goto onError; PyTuple_SET_ITEM(args,0,v); len = PyList_Size(interp->codec_search_path); if (len < 0) - goto onError; + goto onError; if (len == 0) { - PyErr_SetString(PyExc_LookupError, - "no codec search functions registered: " - "can't find encoding"); - goto onError; + PyErr_SetString(PyExc_LookupError, + "no codec search functions registered: " + "can't find encoding"); + goto onError; } for (i = 0; i < len; i++) { - PyObject *func; + PyObject *func; - func = PyList_GetItem(interp->codec_search_path, i); - if (func == NULL) - goto onError; - result = PyEval_CallObject(func, args); - if (result == NULL) - goto onError; - if (result == Py_None) { - Py_DECREF(result); - continue; - } - if (!PyTuple_Check(result) || PyTuple_GET_SIZE(result) != 4) { - PyErr_SetString(PyExc_TypeError, - "codec search functions must return 4-tuples"); - Py_DECREF(result); - goto onError; - } - break; + func = PyList_GetItem(interp->codec_search_path, i); + if (func == NULL) + goto onError; + result = PyEval_CallObject(func, args); + if (result == NULL) + goto onError; + if (result == Py_None) { + Py_DECREF(result); + continue; + } + if (!PyTuple_Check(result) || PyTuple_GET_SIZE(result) != 4) { + PyErr_SetString(PyExc_TypeError, + "codec search functions must return 4-tuples"); + Py_DECREF(result); + goto onError; + } + break; } if (i == len) { - /* XXX Perhaps we should cache misses too ? */ - PyErr_Format(PyExc_LookupError, + /* XXX Perhaps we should cache misses too ? */ + PyErr_Format(PyExc_LookupError, "unknown encoding: %s", encoding); - goto onError; + goto onError; } /* Cache and return the result */ if (PyDict_SetItem(interp->codec_search_cache, v, result) < 0) { - Py_DECREF(result); - goto onError; + Py_DECREF(result); + goto onError; } Py_DECREF(args); return result; @@ -188,38 +188,38 @@ int PyCodec_KnownEncoding(const char *encoding) { PyObject *codecs; - + codecs = _PyCodec_Lookup(encoding); if (!codecs) { - PyErr_Clear(); - return 0; + PyErr_Clear(); + return 0; } else { - Py_DECREF(codecs); - return 1; + Py_DECREF(codecs); + return 1; } } static PyObject *args_tuple(PyObject *object, - const char *errors) + const char *errors) { PyObject *args; args = PyTuple_New(1 + (errors != NULL)); if (args == NULL) - return NULL; + return NULL; Py_INCREF(object); PyTuple_SET_ITEM(args,0,object); if (errors) { - PyObject *v; + PyObject *v; - v = PyUnicode_FromString(errors); - if (v == NULL) { - Py_DECREF(args); - return NULL; - } - PyTuple_SET_ITEM(args, 1, v); + v = PyUnicode_FromString(errors); + if (v == NULL) { + Py_DECREF(args); + return NULL; + } + PyTuple_SET_ITEM(args, 1, v); } return args; } @@ -234,7 +234,7 @@ codecs = _PyCodec_Lookup(encoding); if (codecs == NULL) - return NULL; + return NULL; v = PyTuple_GET_ITEM(codecs, index); Py_DECREF(codecs); Py_INCREF(v); @@ -245,22 +245,22 @@ static PyObject *codec_getincrementalcodec(const char *encoding, - const char *errors, - const char *attrname) + const char *errors, + const char *attrname) { PyObject *codecs, *ret, *inccodec; codecs = _PyCodec_Lookup(encoding); if (codecs == NULL) - return NULL; + return NULL; inccodec = PyObject_GetAttrString(codecs, attrname); Py_DECREF(codecs); if (inccodec == NULL) - return NULL; + return NULL; if (errors) - ret = PyObject_CallFunction(inccodec, "s", errors); + ret = PyObject_CallFunction(inccodec, "s", errors); else - ret = PyObject_CallFunction(inccodec, NULL); + ret = PyObject_CallFunction(inccodec, NULL); Py_DECREF(inccodec); return ret; } @@ -269,21 +269,21 @@ static PyObject *codec_getstreamcodec(const char *encoding, - PyObject *stream, - const char *errors, - const int index) + PyObject *stream, + const char *errors, + const int index) { PyObject *codecs, *streamcodec, *codeccls; codecs = _PyCodec_Lookup(encoding); if (codecs == NULL) - return NULL; + return NULL; codeccls = PyTuple_GET_ITEM(codecs, index); if (errors != NULL) - streamcodec = PyObject_CallFunction(codeccls, "Os", stream, errors); + streamcodec = PyObject_CallFunction(codeccls, "Os", stream, errors); else - streamcodec = PyObject_CallFunction(codeccls, "O", stream); + streamcodec = PyObject_CallFunction(codeccls, "O", stream); Py_DECREF(codecs); return streamcodec; } @@ -305,27 +305,27 @@ } PyObject *PyCodec_IncrementalEncoder(const char *encoding, - const char *errors) + const char *errors) { return codec_getincrementalcodec(encoding, errors, "incrementalencoder"); } PyObject *PyCodec_IncrementalDecoder(const char *encoding, - const char *errors) + const char *errors) { return codec_getincrementalcodec(encoding, errors, "incrementaldecoder"); } PyObject *PyCodec_StreamReader(const char *encoding, - PyObject *stream, - const char *errors) + PyObject *stream, + const char *errors) { return codec_getstreamcodec(encoding, stream, errors, 2); } PyObject *PyCodec_StreamWriter(const char *encoding, - PyObject *stream, - const char *errors) + PyObject *stream, + const char *errors) { return codec_getstreamcodec(encoding, stream, errors, 3); } @@ -336,8 +336,8 @@ errors is passed to the encoder factory as argument if non-NULL. */ PyObject *PyCodec_Encode(PyObject *object, - const char *encoding, - const char *errors) + const char *encoding, + const char *errors) { PyObject *encoder = NULL; PyObject *args = NULL, *result = NULL; @@ -345,21 +345,21 @@ encoder = PyCodec_Encoder(encoding); if (encoder == NULL) - goto onError; + goto onError; args = args_tuple(object, errors); if (args == NULL) - goto onError; + goto onError; result = PyEval_CallObject(encoder, args); if (result == NULL) - goto onError; + goto onError; if (!PyTuple_Check(result) || - PyTuple_GET_SIZE(result) != 2) { - PyErr_SetString(PyExc_TypeError, - "encoder must return a tuple (object, integer)"); - goto onError; + PyTuple_GET_SIZE(result) != 2) { + PyErr_SetString(PyExc_TypeError, + "encoder must return a tuple (object, integer)"); + goto onError; } v = PyTuple_GET_ITEM(result,0); Py_INCREF(v); @@ -369,7 +369,7 @@ Py_DECREF(encoder); Py_DECREF(result); return v; - + onError: Py_XDECREF(result); Py_XDECREF(args); @@ -383,8 +383,8 @@ errors is passed to the decoder factory as argument if non-NULL. */ PyObject *PyCodec_Decode(PyObject *object, - const char *encoding, - const char *errors) + const char *encoding, + const char *errors) { PyObject *decoder = NULL; PyObject *args = NULL, *result = NULL; @@ -392,20 +392,20 @@ decoder = PyCodec_Decoder(encoding); if (decoder == NULL) - goto onError; + goto onError; args = args_tuple(object, errors); if (args == NULL) - goto onError; + goto onError; result = PyEval_CallObject(decoder,args); if (result == NULL) - goto onError; + goto onError; if (!PyTuple_Check(result) || - PyTuple_GET_SIZE(result) != 2) { - PyErr_SetString(PyExc_TypeError, - "decoder must return a tuple (object,integer)"); - goto onError; + PyTuple_GET_SIZE(result) != 2) { + PyErr_SetString(PyExc_TypeError, + "decoder must return a tuple (object,integer)"); + goto onError; } v = PyTuple_GET_ITEM(result,0); Py_INCREF(v); @@ -433,13 +433,13 @@ { PyInterpreterState *interp = PyThreadState_GET()->interp; if (interp->codec_search_path == NULL && _PyCodecRegistry_Init()) - return -1; + return -1; if (!PyCallable_Check(error)) { - PyErr_SetString(PyExc_TypeError, "handler must be callable"); - return -1; + PyErr_SetString(PyExc_TypeError, "handler must be callable"); + return -1; } return PyDict_SetItemString(interp->codec_error_registry, - (char *)name, error); + (char *)name, error); } /* Lookup the error handling callback function registered under the @@ -451,15 +451,15 @@ PyInterpreterState *interp = PyThreadState_GET()->interp; if (interp->codec_search_path == NULL && _PyCodecRegistry_Init()) - return NULL; + return NULL; if (name==NULL) - name = "strict"; + name = "strict"; handler = PyDict_GetItemString(interp->codec_error_registry, (char *)name); if (!handler) - PyErr_Format(PyExc_LookupError, "unknown error handler name '%.400s'", name); + PyErr_Format(PyExc_LookupError, "unknown error handler name '%.400s'", name); else - Py_INCREF(handler); + Py_INCREF(handler); return handler; } @@ -482,7 +482,7 @@ if (PyExceptionInstance_Check(exc)) PyErr_SetObject(PyExceptionInstance_Class(exc), exc); else - PyErr_SetString(PyExc_TypeError, "codec must pass exception instance"); + PyErr_SetString(PyExc_TypeError, "codec must pass exception instance"); return NULL; } @@ -491,20 +491,20 @@ { Py_ssize_t end; if (PyObject_IsInstance(exc, PyExc_UnicodeEncodeError)) { - if (PyUnicodeEncodeError_GetEnd(exc, &end)) - return NULL; + if (PyUnicodeEncodeError_GetEnd(exc, &end)) + return NULL; } else if (PyObject_IsInstance(exc, PyExc_UnicodeDecodeError)) { - if (PyUnicodeDecodeError_GetEnd(exc, &end)) - return NULL; + if (PyUnicodeDecodeError_GetEnd(exc, &end)) + return NULL; } else if (PyObject_IsInstance(exc, PyExc_UnicodeTranslateError)) { - if (PyUnicodeTranslateError_GetEnd(exc, &end)) - return NULL; + if (PyUnicodeTranslateError_GetEnd(exc, &end)) + return NULL; } else { - wrong_exception_type(exc); - return NULL; + wrong_exception_type(exc); + return NULL; } /* ouch: passing NULL, 0, pos gives None instead of u'' */ return Py_BuildValue("(u#n)", &end, 0, end); @@ -519,155 +519,155 @@ Py_ssize_t i; if (PyObject_IsInstance(exc, PyExc_UnicodeEncodeError)) { - PyObject *res; - Py_UNICODE *p; - if (PyUnicodeEncodeError_GetStart(exc, &start)) - return NULL; - if (PyUnicodeEncodeError_GetEnd(exc, &end)) - return NULL; - res = PyUnicode_FromUnicode(NULL, end-start); - if (res == NULL) - return NULL; - for (p = PyUnicode_AS_UNICODE(res), i = start; - i0) { - *outp++ = '0' + c/base; - c %= base; - base /= 10; - } - *outp++ = ';'; - } - restuple = Py_BuildValue("(On)", res, end); - Py_DECREF(res); - Py_DECREF(object); - return restuple; + while (digits-->0) { + *outp++ = '0' + c/base; + c %= base; + base /= 10; + } + *outp++ = ';'; + } + restuple = Py_BuildValue("(On)", res, end); + Py_DECREF(res); + Py_DECREF(object); + return restuple; } else { - wrong_exception_type(exc); - return NULL; + wrong_exception_type(exc); + return NULL; } } @@ -679,72 +679,72 @@ PyObject *PyCodec_BackslashReplaceErrors(PyObject *exc) { if (PyObject_IsInstance(exc, PyExc_UnicodeEncodeError)) { - PyObject *restuple; - PyObject *object; - Py_ssize_t start; - Py_ssize_t end; - PyObject *res; - Py_UNICODE *p; - Py_UNICODE *startp; - Py_UNICODE *outp; - int ressize; - if (PyUnicodeEncodeError_GetStart(exc, &start)) - return NULL; - if (PyUnicodeEncodeError_GetEnd(exc, &end)) - return NULL; - if (!(object = PyUnicodeEncodeError_GetObject(exc))) - return NULL; - startp = PyUnicode_AS_UNICODE(object); - for (p = startp+start, ressize = 0; p < startp+end; ++p) { + PyObject *restuple; + PyObject *object; + Py_ssize_t start; + Py_ssize_t end; + PyObject *res; + Py_UNICODE *p; + Py_UNICODE *startp; + Py_UNICODE *outp; + int ressize; + if (PyUnicodeEncodeError_GetStart(exc, &start)) + return NULL; + if (PyUnicodeEncodeError_GetEnd(exc, &end)) + return NULL; + if (!(object = PyUnicodeEncodeError_GetObject(exc))) + return NULL; + startp = PyUnicode_AS_UNICODE(object); + for (p = startp+start, ressize = 0; p < startp+end; ++p) { #ifdef Py_UNICODE_WIDE - if (*p >= 0x00010000) - ressize += 1+1+8; - else + if (*p >= 0x00010000) + ressize += 1+1+8; + else #endif - if (*p >= 0x100) { - ressize += 1+1+4; - } - else - ressize += 1+1+2; - } - res = PyUnicode_FromUnicode(NULL, ressize); - if (res==NULL) - return NULL; - for (p = startp+start, outp = PyUnicode_AS_UNICODE(res); - p < startp+end; ++p) { - Py_UNICODE c = *p; - *outp++ = '\\'; + if (*p >= 0x100) { + ressize += 1+1+4; + } + else + ressize += 1+1+2; + } + res = PyUnicode_FromUnicode(NULL, ressize); + if (res==NULL) + return NULL; + for (p = startp+start, outp = PyUnicode_AS_UNICODE(res); + p < startp+end; ++p) { + Py_UNICODE c = *p; + *outp++ = '\\'; #ifdef Py_UNICODE_WIDE - if (c >= 0x00010000) { - *outp++ = 'U'; - *outp++ = hexdigits[(c>>28)&0xf]; - *outp++ = hexdigits[(c>>24)&0xf]; - *outp++ = hexdigits[(c>>20)&0xf]; - *outp++ = hexdigits[(c>>16)&0xf]; - *outp++ = hexdigits[(c>>12)&0xf]; - *outp++ = hexdigits[(c>>8)&0xf]; - } - else + if (c >= 0x00010000) { + *outp++ = 'U'; + *outp++ = hexdigits[(c>>28)&0xf]; + *outp++ = hexdigits[(c>>24)&0xf]; + *outp++ = hexdigits[(c>>20)&0xf]; + *outp++ = hexdigits[(c>>16)&0xf]; + *outp++ = hexdigits[(c>>12)&0xf]; + *outp++ = hexdigits[(c>>8)&0xf]; + } + else #endif - if (c >= 0x100) { - *outp++ = 'u'; - *outp++ = hexdigits[(c>>12)&0xf]; - *outp++ = hexdigits[(c>>8)&0xf]; - } - else - *outp++ = 'x'; - *outp++ = hexdigits[(c>>4)&0xf]; - *outp++ = hexdigits[c&0xf]; - } - - restuple = Py_BuildValue("(On)", res, end); - Py_DECREF(res); - Py_DECREF(object); - return restuple; + if (c >= 0x100) { + *outp++ = 'u'; + *outp++ = hexdigits[(c>>12)&0xf]; + *outp++ = hexdigits[(c>>8)&0xf]; + } + else + *outp++ = 'x'; + *outp++ = hexdigits[(c>>4)&0xf]; + *outp++ = hexdigits[c&0xf]; + } + + restuple = Py_BuildValue("(On)", res, end); + Py_DECREF(res); + Py_DECREF(object); + return restuple; } else { - wrong_exception_type(exc); - return NULL; + wrong_exception_type(exc); + return NULL; } } @@ -759,73 +759,73 @@ Py_ssize_t end; PyObject *res; if (PyObject_IsInstance(exc, PyExc_UnicodeEncodeError)) { - Py_UNICODE *p; - Py_UNICODE *startp; - char *outp; - if (PyUnicodeEncodeError_GetStart(exc, &start)) - return NULL; - if (PyUnicodeEncodeError_GetEnd(exc, &end)) - return NULL; - if (!(object = PyUnicodeEncodeError_GetObject(exc))) - return NULL; - startp = PyUnicode_AS_UNICODE(object); - res = PyBytes_FromStringAndSize(NULL, 3*(end-start)); - if (!res) { - Py_DECREF(object); - return NULL; - } - outp = PyBytes_AsString(res); - for (p = startp+start; p < startp+end; p++) { - Py_UNICODE ch = *p; - if (ch < 0xd800 || ch > 0xdfff) { - /* Not a surrogate, fail with original exception */ - PyErr_SetObject(PyExceptionInstance_Class(exc), exc); - Py_DECREF(res); - Py_DECREF(object); - return NULL; - } - *outp++ = (char)(0xe0 | (ch >> 12)); - *outp++ = (char)(0x80 | ((ch >> 6) & 0x3f)); - *outp++ = (char)(0x80 | (ch & 0x3f)); - } - restuple = Py_BuildValue("(On)", res, end); - Py_DECREF(res); - Py_DECREF(object); - return restuple; + Py_UNICODE *p; + Py_UNICODE *startp; + char *outp; + if (PyUnicodeEncodeError_GetStart(exc, &start)) + return NULL; + if (PyUnicodeEncodeError_GetEnd(exc, &end)) + return NULL; + if (!(object = PyUnicodeEncodeError_GetObject(exc))) + return NULL; + startp = PyUnicode_AS_UNICODE(object); + res = PyBytes_FromStringAndSize(NULL, 3*(end-start)); + if (!res) { + Py_DECREF(object); + return NULL; + } + outp = PyBytes_AsString(res); + for (p = startp+start; p < startp+end; p++) { + Py_UNICODE ch = *p; + if (ch < 0xd800 || ch > 0xdfff) { + /* Not a surrogate, fail with original exception */ + PyErr_SetObject(PyExceptionInstance_Class(exc), exc); + Py_DECREF(res); + Py_DECREF(object); + return NULL; + } + *outp++ = (char)(0xe0 | (ch >> 12)); + *outp++ = (char)(0x80 | ((ch >> 6) & 0x3f)); + *outp++ = (char)(0x80 | (ch & 0x3f)); + } + restuple = Py_BuildValue("(On)", res, end); + Py_DECREF(res); + Py_DECREF(object); + return restuple; } else if (PyObject_IsInstance(exc, PyExc_UnicodeDecodeError)) { - unsigned char *p; - Py_UNICODE ch = 0; - if (PyUnicodeDecodeError_GetStart(exc, &start)) - return NULL; - if (!(object = PyUnicodeDecodeError_GetObject(exc))) - return NULL; - if (!(p = (unsigned char*)PyBytes_AsString(object))) { - Py_DECREF(object); - return NULL; - } - /* Try decoding a single surrogate character. If - there are more, let the codec call us again. */ - p += start; - if ((p[0] & 0xf0) == 0xe0 || - (p[1] & 0xc0) == 0x80 || - (p[2] & 0xc0) == 0x80) { - /* it's a three-byte code */ - ch = ((p[0] & 0x0f) << 12) + ((p[1] & 0x3f) << 6) + (p[2] & 0x3f); - if (ch < 0xd800 || ch > 0xdfff) - /* it's not a surrogate - fail */ - ch = 0; - } - Py_DECREF(object); - if (ch == 0) { - PyErr_SetObject(PyExceptionInstance_Class(exc), exc); - return NULL; - } - return Py_BuildValue("(u#n)", &ch, 1, start+3); + unsigned char *p; + Py_UNICODE ch = 0; + if (PyUnicodeDecodeError_GetStart(exc, &start)) + return NULL; + if (!(object = PyUnicodeDecodeError_GetObject(exc))) + return NULL; + if (!(p = (unsigned char*)PyBytes_AsString(object))) { + Py_DECREF(object); + return NULL; + } + /* Try decoding a single surrogate character. If + there are more, let the codec call us again. */ + p += start; + if ((p[0] & 0xf0) == 0xe0 || + (p[1] & 0xc0) == 0x80 || + (p[2] & 0xc0) == 0x80) { + /* it's a three-byte code */ + ch = ((p[0] & 0x0f) << 12) + ((p[1] & 0x3f) << 6) + (p[2] & 0x3f); + if (ch < 0xd800 || ch > 0xdfff) + /* it's not a surrogate - fail */ + ch = 0; + } + Py_DECREF(object); + if (ch == 0) { + PyErr_SetObject(PyExceptionInstance_Class(exc), exc); + return NULL; + } + return Py_BuildValue("(u#n)", &ch, 1, start+3); } else { - wrong_exception_type(exc); - return NULL; + wrong_exception_type(exc); + return NULL; } } @@ -838,74 +838,74 @@ Py_ssize_t end; PyObject *res; if (PyObject_IsInstance(exc, PyExc_UnicodeEncodeError)) { - Py_UNICODE *p; - Py_UNICODE *startp; - char *outp; - if (PyUnicodeEncodeError_GetStart(exc, &start)) - return NULL; - if (PyUnicodeEncodeError_GetEnd(exc, &end)) - return NULL; - if (!(object = PyUnicodeEncodeError_GetObject(exc))) - return NULL; - startp = PyUnicode_AS_UNICODE(object); - res = PyBytes_FromStringAndSize(NULL, end-start); - if (!res) { - Py_DECREF(object); - return NULL; - } - outp = PyBytes_AsString(res); - for (p = startp+start; p < startp+end; p++) { - Py_UNICODE ch = *p; - if (ch < 0xdc80 || ch > 0xdcff) { - /* Not a UTF-8b surrogate, fail with original exception */ - PyErr_SetObject(PyExceptionInstance_Class(exc), exc); - Py_DECREF(res); - Py_DECREF(object); - return NULL; - } - *outp++ = ch - 0xdc00; - } - restuple = Py_BuildValue("(On)", res, end); - Py_DECREF(res); - Py_DECREF(object); - return restuple; + Py_UNICODE *p; + Py_UNICODE *startp; + char *outp; + if (PyUnicodeEncodeError_GetStart(exc, &start)) + return NULL; + if (PyUnicodeEncodeError_GetEnd(exc, &end)) + return NULL; + if (!(object = PyUnicodeEncodeError_GetObject(exc))) + return NULL; + startp = PyUnicode_AS_UNICODE(object); + res = PyBytes_FromStringAndSize(NULL, end-start); + if (!res) { + Py_DECREF(object); + return NULL; + } + outp = PyBytes_AsString(res); + for (p = startp+start; p < startp+end; p++) { + Py_UNICODE ch = *p; + if (ch < 0xdc80 || ch > 0xdcff) { + /* Not a UTF-8b surrogate, fail with original exception */ + PyErr_SetObject(PyExceptionInstance_Class(exc), exc); + Py_DECREF(res); + Py_DECREF(object); + return NULL; + } + *outp++ = ch - 0xdc00; + } + restuple = Py_BuildValue("(On)", res, end); + Py_DECREF(res); + Py_DECREF(object); + return restuple; } else if (PyObject_IsInstance(exc, PyExc_UnicodeDecodeError)) { - unsigned char *p; - Py_UNICODE ch[4]; /* decode up to 4 bad bytes. */ - int consumed = 0; - if (PyUnicodeDecodeError_GetStart(exc, &start)) - return NULL; - if (PyUnicodeDecodeError_GetEnd(exc, &end)) - return NULL; - if (!(object = PyUnicodeDecodeError_GetObject(exc))) - return NULL; - if (!(p = (unsigned char*)PyBytes_AsString(object))) { - Py_DECREF(object); - return NULL; - } - while (consumed < 4 && consumed < end-start) { - /* Refuse to escape ASCII bytes. */ - if (p[start+consumed] < 128) - break; - ch[consumed] = 0xdc00 + p[start+consumed]; - consumed++; - } - Py_DECREF(object); - if (!consumed) { - /* codec complained about ASCII byte. */ - PyErr_SetObject(PyExceptionInstance_Class(exc), exc); - return NULL; - } - return Py_BuildValue("(u#n)", ch, consumed, start+consumed); + unsigned char *p; + Py_UNICODE ch[4]; /* decode up to 4 bad bytes. */ + int consumed = 0; + if (PyUnicodeDecodeError_GetStart(exc, &start)) + return NULL; + if (PyUnicodeDecodeError_GetEnd(exc, &end)) + return NULL; + if (!(object = PyUnicodeDecodeError_GetObject(exc))) + return NULL; + if (!(p = (unsigned char*)PyBytes_AsString(object))) { + Py_DECREF(object); + return NULL; + } + while (consumed < 4 && consumed < end-start) { + /* Refuse to escape ASCII bytes. */ + if (p[start+consumed] < 128) + break; + ch[consumed] = 0xdc00 + p[start+consumed]; + consumed++; + } + Py_DECREF(object); + if (!consumed) { + /* codec complained about ASCII byte. */ + PyErr_SetObject(PyExceptionInstance_Class(exc), exc); + return NULL; + } + return Py_BuildValue("(u#n)", ch, consumed, start+consumed); } else { - wrong_exception_type(exc); - return NULL; + wrong_exception_type(exc); + return NULL; } } - + static PyObject *strict_errors(PyObject *self, PyObject *exc) { return PyCodec_StrictErrors(exc); @@ -948,78 +948,78 @@ static int _PyCodecRegistry_Init(void) { static struct { - char *name; - PyMethodDef def; + char *name; + PyMethodDef def; } methods[] = { - { - "strict", - { - "strict_errors", - strict_errors, - METH_O, - PyDoc_STR("Implements the 'strict' error handling, which " - "raises a UnicodeError on coding errors.") - } - }, - { - "ignore", - { - "ignore_errors", - ignore_errors, - METH_O, - PyDoc_STR("Implements the 'ignore' error handling, which " - "ignores malformed data and continues.") - } - }, - { - "replace", - { - "replace_errors", - replace_errors, - METH_O, - PyDoc_STR("Implements the 'replace' error handling, which " - "replaces malformed data with a replacement marker.") - } - }, - { - "xmlcharrefreplace", - { - "xmlcharrefreplace_errors", - xmlcharrefreplace_errors, - METH_O, - PyDoc_STR("Implements the 'xmlcharrefreplace' error handling, " - "which replaces an unencodable character with the " - "appropriate XML character reference.") - } - }, - { - "backslashreplace", - { - "backslashreplace_errors", - backslashreplace_errors, - METH_O, - PyDoc_STR("Implements the 'backslashreplace' error handling, " - "which replaces an unencodable character with a " - "backslashed escape sequence.") - } - }, - { - "surrogatepass", - { - "surrogatepass", - surrogatepass_errors, - METH_O - } - }, - { - "surrogateescape", - { - "surrogateescape", - surrogateescape_errors, - METH_O - } - } + { + "strict", + { + "strict_errors", + strict_errors, + METH_O, + PyDoc_STR("Implements the 'strict' error handling, which " + "raises a UnicodeError on coding errors.") + } + }, + { + "ignore", + { + "ignore_errors", + ignore_errors, + METH_O, + PyDoc_STR("Implements the 'ignore' error handling, which " + "ignores malformed data and continues.") + } + }, + { + "replace", + { + "replace_errors", + replace_errors, + METH_O, + PyDoc_STR("Implements the 'replace' error handling, which " + "replaces malformed data with a replacement marker.") + } + }, + { + "xmlcharrefreplace", + { + "xmlcharrefreplace_errors", + xmlcharrefreplace_errors, + METH_O, + PyDoc_STR("Implements the 'xmlcharrefreplace' error handling, " + "which replaces an unencodable character with the " + "appropriate XML character reference.") + } + }, + { + "backslashreplace", + { + "backslashreplace_errors", + backslashreplace_errors, + METH_O, + PyDoc_STR("Implements the 'backslashreplace' error handling, " + "which replaces an unencodable character with a " + "backslashed escape sequence.") + } + }, + { + "surrogatepass", + { + "surrogatepass", + surrogatepass_errors, + METH_O + } + }, + { + "surrogateescape", + { + "surrogateescape", + surrogateescape_errors, + METH_O + } + } }; PyInterpreterState *interp = PyThreadState_GET()->interp; @@ -1027,42 +1027,42 @@ unsigned i; if (interp->codec_search_path != NULL) - return 0; + return 0; interp->codec_search_path = PyList_New(0); interp->codec_search_cache = PyDict_New(); interp->codec_error_registry = PyDict_New(); if (interp->codec_error_registry) { - for (i = 0; i < sizeof(methods)/sizeof(methods[0]); ++i) { - PyObject *func = PyCFunction_New(&methods[i].def, NULL); - int res; - if (!func) - Py_FatalError("can't initialize codec error registry"); - res = PyCodec_RegisterError(methods[i].name, func); - Py_DECREF(func); - if (res) - Py_FatalError("can't initialize codec error registry"); - } + for (i = 0; i < sizeof(methods)/sizeof(methods[0]); ++i) { + PyObject *func = PyCFunction_New(&methods[i].def, NULL); + int res; + if (!func) + Py_FatalError("can't initialize codec error registry"); + res = PyCodec_RegisterError(methods[i].name, func); + Py_DECREF(func); + if (res) + Py_FatalError("can't initialize codec error registry"); + } } if (interp->codec_search_path == NULL || - interp->codec_search_cache == NULL || - interp->codec_error_registry == NULL) - Py_FatalError("can't initialize codec registry"); + interp->codec_search_cache == NULL || + interp->codec_error_registry == NULL) + Py_FatalError("can't initialize codec registry"); mod = PyImport_ImportModuleNoBlock("encodings"); if (mod == NULL) { - if (PyErr_ExceptionMatches(PyExc_ImportError)) { - /* Ignore ImportErrors... this is done so that - distributions can disable the encodings package. Note - that other errors are not masked, e.g. SystemErrors - raised to inform the user of an error in the Python - configuration are still reported back to the user. */ - PyErr_Clear(); - return 0; - } - return -1; + if (PyErr_ExceptionMatches(PyExc_ImportError)) { + /* Ignore ImportErrors... this is done so that + distributions can disable the encodings package. Note + that other errors are not masked, e.g. SystemErrors + raised to inform the user of an error in the Python + configuration are still reported back to the user. */ + PyErr_Clear(); + return 0; + } + return -1; } Py_DECREF(mod); interp->codecs_initialized = 1; Modified: python/branches/py3k-jit/Python/compile.c ============================================================================== --- python/branches/py3k-jit/Python/compile.c (original) +++ python/branches/py3k-jit/Python/compile.c Mon May 10 23:55:43 2010 @@ -5,10 +5,10 @@ * PyCodeObject. The compiler makes several passes to build the code * object: * 1. Checks for future statements. See future.c - * 2. Builds a symbol table. See symtable.c. + * 2. Builds a symbol table. See symtable.c. * 3. Generate code for basic blocks. See compiler_mod() in this file. * 4. Assemble the basic blocks into final code. See assemble() in - * this file. + * this file. * 5. Optimize the byte code (peephole optimizations). See peephole.c * * Note that compiler_mod() suggests module, but the module ast type @@ -45,37 +45,37 @@ #define COMP_DICTCOMP 3 struct instr { - unsigned i_jabs : 1; - unsigned i_jrel : 1; - unsigned i_hasarg : 1; - unsigned char i_opcode; - int i_oparg; - struct basicblock_ *i_target; /* target block (if jump instruction) */ - int i_lineno; + unsigned i_jabs : 1; + unsigned i_jrel : 1; + unsigned i_hasarg : 1; + unsigned char i_opcode; + int i_oparg; + struct basicblock_ *i_target; /* target block (if jump instruction) */ + int i_lineno; }; typedef struct basicblock_ { /* Each basicblock in a compilation unit is linked via b_list in the reverse order that the block are allocated. b_list points to the next block, not to be confused with b_next, which is next by control flow. */ - struct basicblock_ *b_list; - /* number of instructions used */ - int b_iused; - /* length of instruction array (b_instr) */ - int b_ialloc; - /* pointer to an array of instructions, initially NULL */ - struct instr *b_instr; - /* If b_next is non-NULL, it is a pointer to the next - block reached by normal control flow. */ - struct basicblock_ *b_next; - /* b_seen is used to perform a DFS of basicblocks. */ - unsigned b_seen : 1; - /* b_return is true if a RETURN_VALUE opcode is inserted. */ - unsigned b_return : 1; - /* depth of stack upon entry of block, computed by stackdepth() */ - int b_startdepth; - /* instruction offset for block, computed by assemble_jump_offsets() */ - int b_offset; + struct basicblock_ *b_list; + /* number of instructions used */ + int b_iused; + /* length of instruction array (b_instr) */ + int b_ialloc; + /* pointer to an array of instructions, initially NULL */ + struct instr *b_instr; + /* If b_next is non-NULL, it is a pointer to the next + block reached by normal control flow. */ + struct basicblock_ *b_next; + /* b_seen is used to perform a DFS of basicblocks. */ + unsigned b_seen : 1; + /* b_return is true if a RETURN_VALUE opcode is inserted. */ + unsigned b_return : 1; + /* depth of stack upon entry of block, computed by stackdepth() */ + int b_startdepth; + /* instruction offset for block, computed by assemble_jump_offsets() */ + int b_offset; } basicblock; /* fblockinfo tracks the current frame block. @@ -88,64 +88,64 @@ enum fblocktype { LOOP, EXCEPT, FINALLY_TRY, FINALLY_END }; struct fblockinfo { - enum fblocktype fb_type; - basicblock *fb_block; + enum fblocktype fb_type; + basicblock *fb_block; }; /* The following items change on entry and exit of code blocks. They must be saved and restored when returning to a block. */ struct compiler_unit { - PySTEntryObject *u_ste; + PySTEntryObject *u_ste; - PyObject *u_name; - /* The following fields are dicts that map objects to - the index of them in co_XXX. The index is used as - the argument for opcodes that refer to those collections. - */ - PyObject *u_consts; /* all constants */ - PyObject *u_names; /* all names */ - PyObject *u_varnames; /* local variables */ - PyObject *u_cellvars; /* cell variables */ - PyObject *u_freevars; /* free variables */ - - PyObject *u_private; /* for private name mangling */ - - int u_argcount; /* number of arguments for block */ - int u_kwonlyargcount; /* number of keyword only arguments for block */ - /* Pointer to the most recently allocated block. By following b_list - members, you can reach all early allocated blocks. */ - basicblock *u_blocks; - basicblock *u_curblock; /* pointer to current block */ - - int u_nfblocks; - struct fblockinfo u_fblock[CO_MAXBLOCKS]; - - int u_firstlineno; /* the first lineno of the block */ - int u_lineno; /* the lineno for the current stmt */ - int u_lineno_set; /* boolean to indicate whether instr - has been generated with current lineno */ + PyObject *u_name; + /* The following fields are dicts that map objects to + the index of them in co_XXX. The index is used as + the argument for opcodes that refer to those collections. + */ + PyObject *u_consts; /* all constants */ + PyObject *u_names; /* all names */ + PyObject *u_varnames; /* local variables */ + PyObject *u_cellvars; /* cell variables */ + PyObject *u_freevars; /* free variables */ + + PyObject *u_private; /* for private name mangling */ + + int u_argcount; /* number of arguments for block */ + int u_kwonlyargcount; /* number of keyword only arguments for block */ + /* Pointer to the most recently allocated block. By following b_list + members, you can reach all early allocated blocks. */ + basicblock *u_blocks; + basicblock *u_curblock; /* pointer to current block */ + + int u_nfblocks; + struct fblockinfo u_fblock[CO_MAXBLOCKS]; + + int u_firstlineno; /* the first lineno of the block */ + int u_lineno; /* the lineno for the current stmt */ + int u_lineno_set; /* boolean to indicate whether instr + has been generated with current lineno */ }; -/* This struct captures the global state of a compilation. +/* This struct captures the global state of a compilation. The u pointer points to the current compilation unit, while units -for enclosing blocks are stored in c_stack. The u and c_stack are +for enclosing blocks are stored in c_stack. The u and c_stack are managed by compiler_enter_scope() and compiler_exit_scope(). */ struct compiler { - const char *c_filename; - struct symtable *c_st; - PyFutureFeatures *c_future; /* pointer to module's __future__ */ - PyCompilerFlags *c_flags; - - int c_interactive; /* true if in interactive mode */ - int c_nestlevel; - - struct compiler_unit *u; /* compiler state for current block */ - PyObject *c_stack; /* Python list holding compiler_unit ptrs */ - PyArena *c_arena; /* pointer to memory allocation arena */ + const char *c_filename; + struct symtable *c_st; + PyFutureFeatures *c_future; /* pointer to module's __future__ */ + PyCompilerFlags *c_flags; + + int c_interactive; /* true if in interactive mode */ + int c_nestlevel; + + struct compiler_unit *u; /* compiler state for current block */ + PyObject *c_stack; /* Python list holding compiler_unit ptrs */ + PyArena *c_arena; /* pointer to memory allocation arena */ }; static int compiler_enter_scope(struct compiler *, identifier, void *, int); @@ -166,12 +166,12 @@ static int compiler_visit_expr(struct compiler *, expr_ty); static int compiler_augassign(struct compiler *, stmt_ty); static int compiler_visit_slice(struct compiler *, slice_ty, - expr_context_ty); + expr_context_ty); static int compiler_push_fblock(struct compiler *, enum fblocktype, - basicblock *); + basicblock *); static void compiler_pop_fblock(struct compiler *, enum fblocktype, - basicblock *); + basicblock *); /* Returns true if there is a loop on the fblock stack. */ static int compiler_in_loop(struct compiler *); @@ -180,10 +180,10 @@ static int compiler_with(struct compiler *, stmt_ty); static int compiler_call_helper(struct compiler *c, int n, - asdl_seq *args, - asdl_seq *keywords, - expr_ty starargs, - expr_ty kwargs); + asdl_seq *args, + asdl_seq *keywords, + expr_ty starargs, + expr_ty kwargs); static PyCodeObject *assemble(struct compiler *, int addNone); static PyObject *__doc__; @@ -193,172 +193,172 @@ PyObject * _Py_Mangle(PyObject *privateobj, PyObject *ident) { - /* Name mangling: __private becomes _classname__private. - This is independent from how the name is used. */ - const Py_UNICODE *p, *name = PyUnicode_AS_UNICODE(ident); - Py_UNICODE *buffer; - size_t nlen, plen; - if (privateobj == NULL || !PyUnicode_Check(privateobj) || - name == NULL || name[0] != '_' || name[1] != '_') { - Py_INCREF(ident); - return ident; - } - p = PyUnicode_AS_UNICODE(privateobj); - nlen = Py_UNICODE_strlen(name); - /* Don't mangle __id__ or names with dots. - - The only time a name with a dot can occur is when - we are compiling an import statement that has a - package name. - - TODO(jhylton): Decide whether we want to support - mangling of the module name, e.g. __M.X. - */ - if ((name[nlen-1] == '_' && name[nlen-2] == '_') - || Py_UNICODE_strchr(name, '.')) { - Py_INCREF(ident); - return ident; /* Don't mangle __whatever__ */ - } - /* Strip leading underscores from class name */ - while (*p == '_') - p++; - if (*p == 0) { - Py_INCREF(ident); - return ident; /* Don't mangle if class is just underscores */ - } - plen = Py_UNICODE_strlen(p); - - assert(1 <= PY_SSIZE_T_MAX - nlen); - assert(1 + nlen <= PY_SSIZE_T_MAX - plen); - - ident = PyUnicode_FromStringAndSize(NULL, 1 + nlen + plen); - if (!ident) - return 0; - /* ident = "_" + p[:plen] + name # i.e. 1+plen+nlen bytes */ - buffer = PyUnicode_AS_UNICODE(ident); - buffer[0] = '_'; - Py_UNICODE_strncpy(buffer+1, p, plen); - Py_UNICODE_strcpy(buffer+1+plen, name); - return ident; + /* Name mangling: __private becomes _classname__private. + This is independent from how the name is used. */ + const Py_UNICODE *p, *name = PyUnicode_AS_UNICODE(ident); + Py_UNICODE *buffer; + size_t nlen, plen; + if (privateobj == NULL || !PyUnicode_Check(privateobj) || + name == NULL || name[0] != '_' || name[1] != '_') { + Py_INCREF(ident); + return ident; + } + p = PyUnicode_AS_UNICODE(privateobj); + nlen = Py_UNICODE_strlen(name); + /* Don't mangle __id__ or names with dots. + + The only time a name with a dot can occur is when + we are compiling an import statement that has a + package name. + + TODO(jhylton): Decide whether we want to support + mangling of the module name, e.g. __M.X. + */ + if ((name[nlen-1] == '_' && name[nlen-2] == '_') + || Py_UNICODE_strchr(name, '.')) { + Py_INCREF(ident); + return ident; /* Don't mangle __whatever__ */ + } + /* Strip leading underscores from class name */ + while (*p == '_') + p++; + if (*p == 0) { + Py_INCREF(ident); + return ident; /* Don't mangle if class is just underscores */ + } + plen = Py_UNICODE_strlen(p); + + assert(1 <= PY_SSIZE_T_MAX - nlen); + assert(1 + nlen <= PY_SSIZE_T_MAX - plen); + + ident = PyUnicode_FromStringAndSize(NULL, 1 + nlen + plen); + if (!ident) + return 0; + /* ident = "_" + p[:plen] + name # i.e. 1+plen+nlen bytes */ + buffer = PyUnicode_AS_UNICODE(ident); + buffer[0] = '_'; + Py_UNICODE_strncpy(buffer+1, p, plen); + Py_UNICODE_strcpy(buffer+1+plen, name); + return ident; } static int compiler_init(struct compiler *c) { - memset(c, 0, sizeof(struct compiler)); + memset(c, 0, sizeof(struct compiler)); - c->c_stack = PyList_New(0); - if (!c->c_stack) - return 0; + c->c_stack = PyList_New(0); + if (!c->c_stack) + return 0; - return 1; + return 1; } PyCodeObject * PyAST_Compile(mod_ty mod, const char *filename, PyCompilerFlags *flags, - PyArena *arena) + PyArena *arena) { - struct compiler c; - PyCodeObject *co = NULL; - PyCompilerFlags local_flags; - int merged; - - if (!__doc__) { - __doc__ = PyUnicode_InternFromString("__doc__"); - if (!__doc__) - return NULL; - } - - if (!compiler_init(&c)) - return NULL; - c.c_filename = filename; - c.c_arena = arena; - c.c_future = PyFuture_FromAST(mod, filename); - if (c.c_future == NULL) - goto finally; - if (!flags) { - local_flags.cf_flags = 0; - flags = &local_flags; - } - merged = c.c_future->ff_features | flags->cf_flags; - c.c_future->ff_features = merged; - flags->cf_flags = merged; - c.c_flags = flags; - c.c_nestlevel = 0; - - c.c_st = PySymtable_Build(mod, filename, c.c_future); - if (c.c_st == NULL) { - if (!PyErr_Occurred()) - PyErr_SetString(PyExc_SystemError, "no symtable"); - goto finally; - } + struct compiler c; + PyCodeObject *co = NULL; + PyCompilerFlags local_flags; + int merged; + + if (!__doc__) { + __doc__ = PyUnicode_InternFromString("__doc__"); + if (!__doc__) + return NULL; + } + + if (!compiler_init(&c)) + return NULL; + c.c_filename = filename; + c.c_arena = arena; + c.c_future = PyFuture_FromAST(mod, filename); + if (c.c_future == NULL) + goto finally; + if (!flags) { + local_flags.cf_flags = 0; + flags = &local_flags; + } + merged = c.c_future->ff_features | flags->cf_flags; + c.c_future->ff_features = merged; + flags->cf_flags = merged; + c.c_flags = flags; + c.c_nestlevel = 0; + + c.c_st = PySymtable_Build(mod, filename, c.c_future); + if (c.c_st == NULL) { + if (!PyErr_Occurred()) + PyErr_SetString(PyExc_SystemError, "no symtable"); + goto finally; + } - co = compiler_mod(&c, mod); + co = compiler_mod(&c, mod); finally: - compiler_free(&c); - assert(co || PyErr_Occurred()); - return co; + compiler_free(&c); + assert(co || PyErr_Occurred()); + return co; } PyCodeObject * PyNode_Compile(struct _node *n, const char *filename) { - PyCodeObject *co = NULL; - mod_ty mod; - PyArena *arena = PyArena_New(); - if (!arena) - return NULL; - mod = PyAST_FromNode(n, NULL, filename, arena); - if (mod) - co = PyAST_Compile(mod, filename, NULL, arena); - PyArena_Free(arena); - return co; + PyCodeObject *co = NULL; + mod_ty mod; + PyArena *arena = PyArena_New(); + if (!arena) + return NULL; + mod = PyAST_FromNode(n, NULL, filename, arena); + if (mod) + co = PyAST_Compile(mod, filename, NULL, arena); + PyArena_Free(arena); + return co; } static void compiler_free(struct compiler *c) { - if (c->c_st) - PySymtable_Free(c->c_st); - if (c->c_future) - PyObject_Free(c->c_future); - Py_DECREF(c->c_stack); + if (c->c_st) + PySymtable_Free(c->c_st); + if (c->c_future) + PyObject_Free(c->c_future); + Py_DECREF(c->c_stack); } static PyObject * list2dict(PyObject *list) { - Py_ssize_t i, n; - PyObject *v, *k; - PyObject *dict = PyDict_New(); - if (!dict) return NULL; - - n = PyList_Size(list); - for (i = 0; i < n; i++) { - v = PyLong_FromLong(i); - if (!v) { - Py_DECREF(dict); - return NULL; - } - k = PyList_GET_ITEM(list, i); - k = PyTuple_Pack(2, k, k->ob_type); - if (k == NULL || PyDict_SetItem(dict, k, v) < 0) { - Py_XDECREF(k); - Py_DECREF(v); - Py_DECREF(dict); - return NULL; - } - Py_DECREF(k); - Py_DECREF(v); - } - return dict; + Py_ssize_t i, n; + PyObject *v, *k; + PyObject *dict = PyDict_New(); + if (!dict) return NULL; + + n = PyList_Size(list); + for (i = 0; i < n; i++) { + v = PyLong_FromLong(i); + if (!v) { + Py_DECREF(dict); + return NULL; + } + k = PyList_GET_ITEM(list, i); + k = PyTuple_Pack(2, k, k->ob_type); + if (k == NULL || PyDict_SetItem(dict, k, v) < 0) { + Py_XDECREF(k); + Py_DECREF(v); + Py_DECREF(dict); + return NULL; + } + Py_DECREF(k); + Py_DECREF(v); + } + return dict; } /* Return new dict containing names from src that match scope(s). src is a symbol table dictionary. If the scope of a name matches -either scope_type or flag is set, insert it into the new dict. The +either scope_type or flag is set, insert it into the new dict. The values are integers, starting at offset and increasing by one for each key. */ @@ -366,182 +366,182 @@ static PyObject * dictbytype(PyObject *src, int scope_type, int flag, int offset) { - Py_ssize_t pos = 0, i = offset, scope; - PyObject *k, *v, *dest = PyDict_New(); + Py_ssize_t pos = 0, i = offset, scope; + PyObject *k, *v, *dest = PyDict_New(); - assert(offset >= 0); - if (dest == NULL) - return NULL; - - while (PyDict_Next(src, &pos, &k, &v)) { - /* XXX this should probably be a macro in symtable.h */ - long vi; - assert(PyLong_Check(v)); - vi = PyLong_AS_LONG(v); - scope = (vi >> SCOPE_OFFSET) & SCOPE_MASK; - - if (scope == scope_type || vi & flag) { - PyObject *tuple, *item = PyLong_FromLong(i); - if (item == NULL) { - Py_DECREF(dest); - return NULL; - } - i++; - tuple = PyTuple_Pack(2, k, k->ob_type); - if (!tuple || PyDict_SetItem(dest, tuple, item) < 0) { - Py_DECREF(item); - Py_DECREF(dest); - Py_XDECREF(tuple); - return NULL; - } - Py_DECREF(item); - Py_DECREF(tuple); - } - } - return dest; + assert(offset >= 0); + if (dest == NULL) + return NULL; + + while (PyDict_Next(src, &pos, &k, &v)) { + /* XXX this should probably be a macro in symtable.h */ + long vi; + assert(PyLong_Check(v)); + vi = PyLong_AS_LONG(v); + scope = (vi >> SCOPE_OFFSET) & SCOPE_MASK; + + if (scope == scope_type || vi & flag) { + PyObject *tuple, *item = PyLong_FromLong(i); + if (item == NULL) { + Py_DECREF(dest); + return NULL; + } + i++; + tuple = PyTuple_Pack(2, k, k->ob_type); + if (!tuple || PyDict_SetItem(dest, tuple, item) < 0) { + Py_DECREF(item); + Py_DECREF(dest); + Py_XDECREF(tuple); + return NULL; + } + Py_DECREF(item); + Py_DECREF(tuple); + } + } + return dest; } static void compiler_unit_check(struct compiler_unit *u) { - basicblock *block; - for (block = u->u_blocks; block != NULL; block = block->b_list) { - assert((void *)block != (void *)0xcbcbcbcb); - assert((void *)block != (void *)0xfbfbfbfb); - assert((void *)block != (void *)0xdbdbdbdb); - if (block->b_instr != NULL) { - assert(block->b_ialloc > 0); - assert(block->b_iused > 0); - assert(block->b_ialloc >= block->b_iused); - } - else { - assert (block->b_iused == 0); - assert (block->b_ialloc == 0); - } - } + basicblock *block; + for (block = u->u_blocks; block != NULL; block = block->b_list) { + assert((void *)block != (void *)0xcbcbcbcb); + assert((void *)block != (void *)0xfbfbfbfb); + assert((void *)block != (void *)0xdbdbdbdb); + if (block->b_instr != NULL) { + assert(block->b_ialloc > 0); + assert(block->b_iused > 0); + assert(block->b_ialloc >= block->b_iused); + } + else { + assert (block->b_iused == 0); + assert (block->b_ialloc == 0); + } + } } static void compiler_unit_free(struct compiler_unit *u) { - basicblock *b, *next; + basicblock *b, *next; - compiler_unit_check(u); - b = u->u_blocks; - while (b != NULL) { - if (b->b_instr) - PyObject_Free((void *)b->b_instr); - next = b->b_list; - PyObject_Free((void *)b); - b = next; - } - Py_CLEAR(u->u_ste); - Py_CLEAR(u->u_name); - Py_CLEAR(u->u_consts); - Py_CLEAR(u->u_names); - Py_CLEAR(u->u_varnames); - Py_CLEAR(u->u_freevars); - Py_CLEAR(u->u_cellvars); - Py_CLEAR(u->u_private); - PyObject_Free(u); + compiler_unit_check(u); + b = u->u_blocks; + while (b != NULL) { + if (b->b_instr) + PyObject_Free((void *)b->b_instr); + next = b->b_list; + PyObject_Free((void *)b); + b = next; + } + Py_CLEAR(u->u_ste); + Py_CLEAR(u->u_name); + Py_CLEAR(u->u_consts); + Py_CLEAR(u->u_names); + Py_CLEAR(u->u_varnames); + Py_CLEAR(u->u_freevars); + Py_CLEAR(u->u_cellvars); + Py_CLEAR(u->u_private); + PyObject_Free(u); } static int compiler_enter_scope(struct compiler *c, identifier name, void *key, - int lineno) + int lineno) { - struct compiler_unit *u; + struct compiler_unit *u; - u = (struct compiler_unit *)PyObject_Malloc(sizeof( - struct compiler_unit)); - if (!u) { - PyErr_NoMemory(); - return 0; - } - memset(u, 0, sizeof(struct compiler_unit)); - u->u_argcount = 0; - u->u_kwonlyargcount = 0; - u->u_ste = PySymtable_Lookup(c->c_st, key); - if (!u->u_ste) { - compiler_unit_free(u); - return 0; - } - Py_INCREF(name); - u->u_name = name; - u->u_varnames = list2dict(u->u_ste->ste_varnames); - u->u_cellvars = dictbytype(u->u_ste->ste_symbols, CELL, 0, 0); - if (!u->u_varnames || !u->u_cellvars) { - compiler_unit_free(u); - return 0; - } - - u->u_freevars = dictbytype(u->u_ste->ste_symbols, FREE, DEF_FREE_CLASS, - PyDict_Size(u->u_cellvars)); - if (!u->u_freevars) { - compiler_unit_free(u); - return 0; - } - - u->u_blocks = NULL; - u->u_nfblocks = 0; - u->u_firstlineno = lineno; - u->u_lineno = 0; - u->u_lineno_set = 0; - u->u_consts = PyDict_New(); - if (!u->u_consts) { - compiler_unit_free(u); - return 0; - } - u->u_names = PyDict_New(); - if (!u->u_names) { - compiler_unit_free(u); - return 0; - } - - u->u_private = NULL; - - /* Push the old compiler_unit on the stack. */ - if (c->u) { - PyObject *capsule = PyCapsule_New(c->u, COMPILER_CAPSULE_NAME_COMPILER_UNIT, NULL); - if (!capsule || PyList_Append(c->c_stack, capsule) < 0) { - Py_XDECREF(capsule); - compiler_unit_free(u); - return 0; - } - Py_DECREF(capsule); - u->u_private = c->u->u_private; - Py_XINCREF(u->u_private); - } - c->u = u; - - c->c_nestlevel++; - if (compiler_use_new_block(c) == NULL) - return 0; + u = (struct compiler_unit *)PyObject_Malloc(sizeof( + struct compiler_unit)); + if (!u) { + PyErr_NoMemory(); + return 0; + } + memset(u, 0, sizeof(struct compiler_unit)); + u->u_argcount = 0; + u->u_kwonlyargcount = 0; + u->u_ste = PySymtable_Lookup(c->c_st, key); + if (!u->u_ste) { + compiler_unit_free(u); + return 0; + } + Py_INCREF(name); + u->u_name = name; + u->u_varnames = list2dict(u->u_ste->ste_varnames); + u->u_cellvars = dictbytype(u->u_ste->ste_symbols, CELL, 0, 0); + if (!u->u_varnames || !u->u_cellvars) { + compiler_unit_free(u); + return 0; + } + + u->u_freevars = dictbytype(u->u_ste->ste_symbols, FREE, DEF_FREE_CLASS, + PyDict_Size(u->u_cellvars)); + if (!u->u_freevars) { + compiler_unit_free(u); + return 0; + } + + u->u_blocks = NULL; + u->u_nfblocks = 0; + u->u_firstlineno = lineno; + u->u_lineno = 0; + u->u_lineno_set = 0; + u->u_consts = PyDict_New(); + if (!u->u_consts) { + compiler_unit_free(u); + return 0; + } + u->u_names = PyDict_New(); + if (!u->u_names) { + compiler_unit_free(u); + return 0; + } + + u->u_private = NULL; + + /* Push the old compiler_unit on the stack. */ + if (c->u) { + PyObject *capsule = PyCapsule_New(c->u, COMPILER_CAPSULE_NAME_COMPILER_UNIT, NULL); + if (!capsule || PyList_Append(c->c_stack, capsule) < 0) { + Py_XDECREF(capsule); + compiler_unit_free(u); + return 0; + } + Py_DECREF(capsule); + u->u_private = c->u->u_private; + Py_XINCREF(u->u_private); + } + c->u = u; + + c->c_nestlevel++; + if (compiler_use_new_block(c) == NULL) + return 0; - return 1; + return 1; } static void compiler_exit_scope(struct compiler *c) { - int n; - PyObject *capsule; + int n; + PyObject *capsule; - c->c_nestlevel--; - compiler_unit_free(c->u); - /* Restore c->u to the parent unit. */ - n = PyList_GET_SIZE(c->c_stack) - 1; - if (n >= 0) { - capsule = PyList_GET_ITEM(c->c_stack, n); - c->u = (struct compiler_unit *)PyCapsule_GetPointer(capsule, COMPILER_CAPSULE_NAME_COMPILER_UNIT); - assert(c->u); - /* we are deleting from a list so this really shouldn't fail */ - if (PySequence_DelItem(c->c_stack, n) < 0) - Py_FatalError("compiler_exit_scope()"); - compiler_unit_check(c->u); - } - else - c->u = NULL; + c->c_nestlevel--; + compiler_unit_free(c->u); + /* Restore c->u to the parent unit. */ + n = PyList_GET_SIZE(c->c_stack) - 1; + if (n >= 0) { + capsule = PyList_GET_ITEM(c->c_stack, n); + c->u = (struct compiler_unit *)PyCapsule_GetPointer(capsule, COMPILER_CAPSULE_NAME_COMPILER_UNIT); + assert(c->u); + /* we are deleting from a list so this really shouldn't fail */ + if (PySequence_DelItem(c->c_stack, n) < 0) + Py_FatalError("compiler_exit_scope()"); + compiler_unit_check(c->u); + } + else + c->u = NULL; } @@ -552,50 +552,50 @@ static basicblock * compiler_new_block(struct compiler *c) { - basicblock *b; - struct compiler_unit *u; + basicblock *b; + struct compiler_unit *u; - u = c->u; - b = (basicblock *)PyObject_Malloc(sizeof(basicblock)); - if (b == NULL) { - PyErr_NoMemory(); - return NULL; - } - memset((void *)b, 0, sizeof(basicblock)); - /* Extend the singly linked list of blocks with new block. */ - b->b_list = u->u_blocks; - u->u_blocks = b; - return b; + u = c->u; + b = (basicblock *)PyObject_Malloc(sizeof(basicblock)); + if (b == NULL) { + PyErr_NoMemory(); + return NULL; + } + memset((void *)b, 0, sizeof(basicblock)); + /* Extend the singly linked list of blocks with new block. */ + b->b_list = u->u_blocks; + u->u_blocks = b; + return b; } static basicblock * compiler_use_new_block(struct compiler *c) { - basicblock *block = compiler_new_block(c); - if (block == NULL) - return NULL; - c->u->u_curblock = block; - return block; + basicblock *block = compiler_new_block(c); + if (block == NULL) + return NULL; + c->u->u_curblock = block; + return block; } static basicblock * compiler_next_block(struct compiler *c) { - basicblock *block = compiler_new_block(c); - if (block == NULL) - return NULL; - c->u->u_curblock->b_next = block; - c->u->u_curblock = block; - return block; + basicblock *block = compiler_new_block(c); + if (block == NULL) + return NULL; + c->u->u_curblock->b_next = block; + c->u->u_curblock = block; + return block; } static basicblock * compiler_use_next_block(struct compiler *c, basicblock *block) { - assert(block != NULL); - c->u->u_curblock->b_next = block; - c->u->u_curblock = block; - return block; + assert(block != NULL); + c->u->u_curblock->b_next = block; + c->u->u_curblock = block; + return block; } /* Returns the offset of the next instruction in the current block's @@ -606,44 +606,44 @@ static int compiler_next_instr(struct compiler *c, basicblock *b) { - assert(b != NULL); - if (b->b_instr == NULL) { - b->b_instr = (struct instr *)PyObject_Malloc( - sizeof(struct instr) * DEFAULT_BLOCK_SIZE); - if (b->b_instr == NULL) { - PyErr_NoMemory(); - return -1; - } - b->b_ialloc = DEFAULT_BLOCK_SIZE; - memset((char *)b->b_instr, 0, - sizeof(struct instr) * DEFAULT_BLOCK_SIZE); - } - else if (b->b_iused == b->b_ialloc) { - struct instr *tmp; - size_t oldsize, newsize; - oldsize = b->b_ialloc * sizeof(struct instr); - newsize = oldsize << 1; - - if (oldsize > (PY_SIZE_MAX >> 1)) { - PyErr_NoMemory(); - return -1; - } - - if (newsize == 0) { - PyErr_NoMemory(); - return -1; - } - b->b_ialloc <<= 1; - tmp = (struct instr *)PyObject_Realloc( - (void *)b->b_instr, newsize); - if (tmp == NULL) { - PyErr_NoMemory(); - return -1; - } - b->b_instr = tmp; - memset((char *)b->b_instr + oldsize, 0, newsize - oldsize); - } - return b->b_iused++; + assert(b != NULL); + if (b->b_instr == NULL) { + b->b_instr = (struct instr *)PyObject_Malloc( + sizeof(struct instr) * DEFAULT_BLOCK_SIZE); + if (b->b_instr == NULL) { + PyErr_NoMemory(); + return -1; + } + b->b_ialloc = DEFAULT_BLOCK_SIZE; + memset((char *)b->b_instr, 0, + sizeof(struct instr) * DEFAULT_BLOCK_SIZE); + } + else if (b->b_iused == b->b_ialloc) { + struct instr *tmp; + size_t oldsize, newsize; + oldsize = b->b_ialloc * sizeof(struct instr); + newsize = oldsize << 1; + + if (oldsize > (PY_SIZE_MAX >> 1)) { + PyErr_NoMemory(); + return -1; + } + + if (newsize == 0) { + PyErr_NoMemory(); + return -1; + } + b->b_ialloc <<= 1; + tmp = (struct instr *)PyObject_Realloc( + (void *)b->b_instr, newsize); + if (tmp == NULL) { + PyErr_NoMemory(); + return -1; + } + b->b_instr = tmp; + memset((char *)b->b_instr + oldsize, 0, newsize - oldsize); + } + return b->b_iused++; } /* Set the i_lineno member of the instruction at offset off if the @@ -661,210 +661,210 @@ static void compiler_set_lineno(struct compiler *c, int off) { - basicblock *b; - if (c->u->u_lineno_set) - return; - c->u->u_lineno_set = 1; - b = c->u->u_curblock; - b->b_instr[off].i_lineno = c->u->u_lineno; + basicblock *b; + if (c->u->u_lineno_set) + return; + c->u->u_lineno_set = 1; + b = c->u->u_curblock; + b->b_instr[off].i_lineno = c->u->u_lineno; } static int opcode_stack_effect(int opcode, int oparg) { - switch (opcode) { - case POP_TOP: - return -1; - case ROT_TWO: - case ROT_THREE: - return 0; - case DUP_TOP: - return 1; - case ROT_FOUR: - return 0; - - case UNARY_POSITIVE: - case UNARY_NEGATIVE: - case UNARY_NOT: - case UNARY_INVERT: - return 0; - - case SET_ADD: - case LIST_APPEND: - return -1; - case MAP_ADD: - return -2; - - case BINARY_POWER: - case BINARY_MULTIPLY: - case BINARY_MODULO: - case BINARY_ADD: - case BINARY_SUBTRACT: - case BINARY_SUBSCR: - case BINARY_FLOOR_DIVIDE: - case BINARY_TRUE_DIVIDE: - return -1; - case INPLACE_FLOOR_DIVIDE: - case INPLACE_TRUE_DIVIDE: - return -1; - - case INPLACE_ADD: - case INPLACE_SUBTRACT: - case INPLACE_MULTIPLY: - case INPLACE_MODULO: - return -1; - case STORE_SUBSCR: - return -3; - case STORE_MAP: - return -2; - case DELETE_SUBSCR: - return -2; - - case BINARY_LSHIFT: - case BINARY_RSHIFT: - case BINARY_AND: - case BINARY_XOR: - case BINARY_OR: - return -1; - case INPLACE_POWER: - return -1; - case GET_ITER: - return 0; - - case PRINT_EXPR: - return -1; - case LOAD_BUILD_CLASS: - return 1; - case INPLACE_LSHIFT: - case INPLACE_RSHIFT: - case INPLACE_AND: - case INPLACE_XOR: - case INPLACE_OR: - return -1; - case BREAK_LOOP: - return 0; - case SETUP_WITH: - return 7; - case WITH_CLEANUP: - return -1; /* XXX Sometimes more */ - case STORE_LOCALS: - return -1; - case RETURN_VALUE: - return -1; - case IMPORT_STAR: - return -1; - case YIELD_VALUE: - return 0; - - case POP_BLOCK: - return 0; - case POP_EXCEPT: - return 0; /* -3 except if bad bytecode */ - case END_FINALLY: - return -1; /* or -2 or -3 if exception occurred */ - - case STORE_NAME: - return -1; - case DELETE_NAME: - return 0; - case UNPACK_SEQUENCE: - return oparg-1; - case UNPACK_EX: - return (oparg&0xFF) + (oparg>>8); - case FOR_ITER: - return 1; /* or -1, at end of iterator */ - - case STORE_ATTR: - return -2; - case DELETE_ATTR: - return -1; - case STORE_GLOBAL: - return -1; - case DELETE_GLOBAL: - return 0; - case DUP_TOPX: - return oparg; - case LOAD_CONST: - return 1; - case LOAD_NAME: - return 1; - case BUILD_TUPLE: - case BUILD_LIST: - case BUILD_SET: - return 1-oparg; - case BUILD_MAP: - return 1; - case LOAD_ATTR: - return 0; - case COMPARE_OP: - return -1; - case IMPORT_NAME: - return -1; - case IMPORT_FROM: - return 1; - - case JUMP_FORWARD: - case JUMP_IF_TRUE_OR_POP: /* -1 if jump not taken */ - case JUMP_IF_FALSE_OR_POP: /* "" */ - case JUMP_ABSOLUTE: - return 0; - - case POP_JUMP_IF_FALSE: - case POP_JUMP_IF_TRUE: - return -1; - - case LOAD_GLOBAL: - return 1; - - case CONTINUE_LOOP: - return 0; - case SETUP_LOOP: - return 0; - case SETUP_EXCEPT: - case SETUP_FINALLY: - return 6; /* can push 3 values for the new exception - + 3 others for the previous exception state */ - - case LOAD_FAST: - return 1; - case STORE_FAST: - return -1; - case DELETE_FAST: - return 0; + switch (opcode) { + case POP_TOP: + return -1; + case ROT_TWO: + case ROT_THREE: + return 0; + case DUP_TOP: + return 1; + case ROT_FOUR: + return 0; + + case UNARY_POSITIVE: + case UNARY_NEGATIVE: + case UNARY_NOT: + case UNARY_INVERT: + return 0; + + case SET_ADD: + case LIST_APPEND: + return -1; + case MAP_ADD: + return -2; + + case BINARY_POWER: + case BINARY_MULTIPLY: + case BINARY_MODULO: + case BINARY_ADD: + case BINARY_SUBTRACT: + case BINARY_SUBSCR: + case BINARY_FLOOR_DIVIDE: + case BINARY_TRUE_DIVIDE: + return -1; + case INPLACE_FLOOR_DIVIDE: + case INPLACE_TRUE_DIVIDE: + return -1; + + case INPLACE_ADD: + case INPLACE_SUBTRACT: + case INPLACE_MULTIPLY: + case INPLACE_MODULO: + return -1; + case STORE_SUBSCR: + return -3; + case STORE_MAP: + return -2; + case DELETE_SUBSCR: + return -2; + + case BINARY_LSHIFT: + case BINARY_RSHIFT: + case BINARY_AND: + case BINARY_XOR: + case BINARY_OR: + return -1; + case INPLACE_POWER: + return -1; + case GET_ITER: + return 0; + + case PRINT_EXPR: + return -1; + case LOAD_BUILD_CLASS: + return 1; + case INPLACE_LSHIFT: + case INPLACE_RSHIFT: + case INPLACE_AND: + case INPLACE_XOR: + case INPLACE_OR: + return -1; + case BREAK_LOOP: + return 0; + case SETUP_WITH: + return 7; + case WITH_CLEANUP: + return -1; /* XXX Sometimes more */ + case STORE_LOCALS: + return -1; + case RETURN_VALUE: + return -1; + case IMPORT_STAR: + return -1; + case YIELD_VALUE: + return 0; + + case POP_BLOCK: + return 0; + case POP_EXCEPT: + return 0; /* -3 except if bad bytecode */ + case END_FINALLY: + return -1; /* or -2 or -3 if exception occurred */ + + case STORE_NAME: + return -1; + case DELETE_NAME: + return 0; + case UNPACK_SEQUENCE: + return oparg-1; + case UNPACK_EX: + return (oparg&0xFF) + (oparg>>8); + case FOR_ITER: + return 1; /* or -1, at end of iterator */ + + case STORE_ATTR: + return -2; + case DELETE_ATTR: + return -1; + case STORE_GLOBAL: + return -1; + case DELETE_GLOBAL: + return 0; + case DUP_TOPX: + return oparg; + case LOAD_CONST: + return 1; + case LOAD_NAME: + return 1; + case BUILD_TUPLE: + case BUILD_LIST: + case BUILD_SET: + return 1-oparg; + case BUILD_MAP: + return 1; + case LOAD_ATTR: + return 0; + case COMPARE_OP: + return -1; + case IMPORT_NAME: + return -1; + case IMPORT_FROM: + return 1; + + case JUMP_FORWARD: + case JUMP_IF_TRUE_OR_POP: /* -1 if jump not taken */ + case JUMP_IF_FALSE_OR_POP: /* "" */ + case JUMP_ABSOLUTE: + return 0; + + case POP_JUMP_IF_FALSE: + case POP_JUMP_IF_TRUE: + return -1; + + case LOAD_GLOBAL: + return 1; + + case CONTINUE_LOOP: + return 0; + case SETUP_LOOP: + return 0; + case SETUP_EXCEPT: + case SETUP_FINALLY: + return 6; /* can push 3 values for the new exception + + 3 others for the previous exception state */ + + case LOAD_FAST: + return 1; + case STORE_FAST: + return -1; + case DELETE_FAST: + return 0; - case RAISE_VARARGS: - return -oparg; + case RAISE_VARARGS: + return -oparg; #define NARGS(o) (((o) % 256) + 2*(((o) / 256) % 256)) - case CALL_FUNCTION: - return -NARGS(oparg); - case CALL_FUNCTION_VAR: - case CALL_FUNCTION_KW: - return -NARGS(oparg)-1; - case CALL_FUNCTION_VAR_KW: - return -NARGS(oparg)-2; - case MAKE_FUNCTION: - return -NARGS(oparg) - ((oparg >> 16) & 0xffff); - case MAKE_CLOSURE: - return -1 - NARGS(oparg) - ((oparg >> 16) & 0xffff); + case CALL_FUNCTION: + return -NARGS(oparg); + case CALL_FUNCTION_VAR: + case CALL_FUNCTION_KW: + return -NARGS(oparg)-1; + case CALL_FUNCTION_VAR_KW: + return -NARGS(oparg)-2; + case MAKE_FUNCTION: + return -NARGS(oparg) - ((oparg >> 16) & 0xffff); + case MAKE_CLOSURE: + return -1 - NARGS(oparg) - ((oparg >> 16) & 0xffff); #undef NARGS - case BUILD_SLICE: - if (oparg == 3) - return -2; - else - return -1; - - case LOAD_CLOSURE: - return 1; - case LOAD_DEREF: - return 1; - case STORE_DEREF: - return -1; - default: - fprintf(stderr, "opcode = %d\n", opcode); - Py_FatalError("opcode_stack_effect()"); + case BUILD_SLICE: + if (oparg == 3) + return -2; + else + return -1; + + case LOAD_CLOSURE: + return 1; + case LOAD_DEREF: + return 1; + case STORE_DEREF: + return -1; + default: + fprintf(stderr, "opcode = %d\n", opcode); + Py_FatalError("opcode_stack_effect()"); - } - return 0; /* not reachable */ + } + return 0; /* not reachable */ } /* Add an opcode with no argument. @@ -874,116 +874,116 @@ static int compiler_addop(struct compiler *c, int opcode) { - basicblock *b; - struct instr *i; - int off; - off = compiler_next_instr(c, c->u->u_curblock); - if (off < 0) - return 0; - b = c->u->u_curblock; - i = &b->b_instr[off]; - i->i_opcode = opcode; - i->i_hasarg = 0; - if (opcode == RETURN_VALUE) - b->b_return = 1; - compiler_set_lineno(c, off); - return 1; + basicblock *b; + struct instr *i; + int off; + off = compiler_next_instr(c, c->u->u_curblock); + if (off < 0) + return 0; + b = c->u->u_curblock; + i = &b->b_instr[off]; + i->i_opcode = opcode; + i->i_hasarg = 0; + if (opcode == RETURN_VALUE) + b->b_return = 1; + compiler_set_lineno(c, off); + return 1; } static int compiler_add_o(struct compiler *c, PyObject *dict, PyObject *o) { - PyObject *t, *v; - Py_ssize_t arg; - double d; - - /* necessary to make sure types aren't coerced (e.g., int and long) */ - /* _and_ to distinguish 0.0 from -0.0 e.g. on IEEE platforms */ - if (PyFloat_Check(o)) { - d = PyFloat_AS_DOUBLE(o); - /* all we need is to make the tuple different in either the 0.0 - * or -0.0 case from all others, just to avoid the "coercion". - */ - if (d == 0.0 && copysign(1.0, d) < 0.0) - t = PyTuple_Pack(3, o, o->ob_type, Py_None); - else - t = PyTuple_Pack(2, o, o->ob_type); - } - else if (PyComplex_Check(o)) { - Py_complex z; - int real_negzero, imag_negzero; - /* For the complex case we must make complex(x, 0.) - different from complex(x, -0.) and complex(0., y) - different from complex(-0., y), for any x and y. - All four complex zeros must be distinguished.*/ - z = PyComplex_AsCComplex(o); - real_negzero = z.real == 0.0 && copysign(1.0, z.real) < 0.0; - imag_negzero = z.imag == 0.0 && copysign(1.0, z.imag) < 0.0; - if (real_negzero && imag_negzero) { - t = PyTuple_Pack(5, o, o->ob_type, - Py_None, Py_None, Py_None); - } - else if (imag_negzero) { - t = PyTuple_Pack(4, o, o->ob_type, Py_None, Py_None); - } - else if (real_negzero) { - t = PyTuple_Pack(3, o, o->ob_type, Py_None); - } - else { - t = PyTuple_Pack(2, o, o->ob_type); - } - } - else { - t = PyTuple_Pack(2, o, o->ob_type); - } - if (t == NULL) - return -1; - - v = PyDict_GetItem(dict, t); - if (!v) { - if (PyErr_Occurred()) - return -1; - arg = PyDict_Size(dict); - v = PyLong_FromLong(arg); - if (!v) { - Py_DECREF(t); - return -1; - } - if (PyDict_SetItem(dict, t, v) < 0) { - Py_DECREF(t); - Py_DECREF(v); - return -1; - } - Py_DECREF(v); - } - else - arg = PyLong_AsLong(v); - Py_DECREF(t); - return arg; + PyObject *t, *v; + Py_ssize_t arg; + double d; + + /* necessary to make sure types aren't coerced (e.g., int and long) */ + /* _and_ to distinguish 0.0 from -0.0 e.g. on IEEE platforms */ + if (PyFloat_Check(o)) { + d = PyFloat_AS_DOUBLE(o); + /* all we need is to make the tuple different in either the 0.0 + * or -0.0 case from all others, just to avoid the "coercion". + */ + if (d == 0.0 && copysign(1.0, d) < 0.0) + t = PyTuple_Pack(3, o, o->ob_type, Py_None); + else + t = PyTuple_Pack(2, o, o->ob_type); + } + else if (PyComplex_Check(o)) { + Py_complex z; + int real_negzero, imag_negzero; + /* For the complex case we must make complex(x, 0.) + different from complex(x, -0.) and complex(0., y) + different from complex(-0., y), for any x and y. + All four complex zeros must be distinguished.*/ + z = PyComplex_AsCComplex(o); + real_negzero = z.real == 0.0 && copysign(1.0, z.real) < 0.0; + imag_negzero = z.imag == 0.0 && copysign(1.0, z.imag) < 0.0; + if (real_negzero && imag_negzero) { + t = PyTuple_Pack(5, o, o->ob_type, + Py_None, Py_None, Py_None); + } + else if (imag_negzero) { + t = PyTuple_Pack(4, o, o->ob_type, Py_None, Py_None); + } + else if (real_negzero) { + t = PyTuple_Pack(3, o, o->ob_type, Py_None); + } + else { + t = PyTuple_Pack(2, o, o->ob_type); + } + } + else { + t = PyTuple_Pack(2, o, o->ob_type); + } + if (t == NULL) + return -1; + + v = PyDict_GetItem(dict, t); + if (!v) { + if (PyErr_Occurred()) + return -1; + arg = PyDict_Size(dict); + v = PyLong_FromLong(arg); + if (!v) { + Py_DECREF(t); + return -1; + } + if (PyDict_SetItem(dict, t, v) < 0) { + Py_DECREF(t); + Py_DECREF(v); + return -1; + } + Py_DECREF(v); + } + else + arg = PyLong_AsLong(v); + Py_DECREF(t); + return arg; } static int compiler_addop_o(struct compiler *c, int opcode, PyObject *dict, - PyObject *o) + PyObject *o) { int arg = compiler_add_o(c, dict, o); if (arg < 0) - return 0; + return 0; return compiler_addop_i(c, opcode, arg); } static int compiler_addop_name(struct compiler *c, int opcode, PyObject *dict, - PyObject *o) + PyObject *o) { int arg; PyObject *mangled = _Py_Mangle(c->u->u_private, o); if (!mangled) - return 0; + return 0; arg = compiler_add_o(c, dict, mangled); Py_DECREF(mangled); if (arg < 0) - return 0; + return 0; return compiler_addop_i(c, opcode, arg); } @@ -994,43 +994,43 @@ static int compiler_addop_i(struct compiler *c, int opcode, int oparg) { - struct instr *i; - int off; - off = compiler_next_instr(c, c->u->u_curblock); - if (off < 0) - return 0; - i = &c->u->u_curblock->b_instr[off]; - i->i_opcode = opcode; - i->i_oparg = oparg; - i->i_hasarg = 1; - compiler_set_lineno(c, off); - return 1; + struct instr *i; + int off; + off = compiler_next_instr(c, c->u->u_curblock); + if (off < 0) + return 0; + i = &c->u->u_curblock->b_instr[off]; + i->i_opcode = opcode; + i->i_oparg = oparg; + i->i_hasarg = 1; + compiler_set_lineno(c, off); + return 1; } static int compiler_addop_j(struct compiler *c, int opcode, basicblock *b, int absolute) { - struct instr *i; - int off; + struct instr *i; + int off; - assert(b != NULL); - off = compiler_next_instr(c, c->u->u_curblock); - if (off < 0) - return 0; - i = &c->u->u_curblock->b_instr[off]; - i->i_opcode = opcode; - i->i_target = b; - i->i_hasarg = 1; - if (absolute) - i->i_jabs = 1; - else - i->i_jrel = 1; - compiler_set_lineno(c, off); - return 1; + assert(b != NULL); + off = compiler_next_instr(c, c->u->u_curblock); + if (off < 0) + return 0; + i = &c->u->u_curblock->b_instr[off]; + i->i_opcode = opcode; + i->i_target = b; + i->i_hasarg = 1; + if (absolute) + i->i_jabs = 1; + else + i->i_jrel = 1; + compiler_set_lineno(c, off); + return 1; } -/* The distinction between NEW_BLOCK and NEXT_BLOCK is subtle. (I'd - like to find better names.) NEW_BLOCK() creates a new block and sets +/* The distinction between NEW_BLOCK and NEXT_BLOCK is subtle. (I'd + like to find better names.) NEW_BLOCK() creates a new block and sets it as the current block. NEXT_BLOCK() also creates an implicit jump from the current block to the new block. */ @@ -1041,50 +1041,50 @@ #define NEW_BLOCK(C) { \ - if (compiler_use_new_block((C)) == NULL) \ - return 0; \ + if (compiler_use_new_block((C)) == NULL) \ + return 0; \ } #define NEXT_BLOCK(C) { \ - if (compiler_next_block((C)) == NULL) \ - return 0; \ + if (compiler_next_block((C)) == NULL) \ + return 0; \ } #define ADDOP(C, OP) { \ - if (!compiler_addop((C), (OP))) \ - return 0; \ + if (!compiler_addop((C), (OP))) \ + return 0; \ } #define ADDOP_IN_SCOPE(C, OP) { \ - if (!compiler_addop((C), (OP))) { \ - compiler_exit_scope(c); \ - return 0; \ - } \ + if (!compiler_addop((C), (OP))) { \ + compiler_exit_scope(c); \ + return 0; \ + } \ } #define ADDOP_O(C, OP, O, TYPE) { \ - if (!compiler_addop_o((C), (OP), (C)->u->u_ ## TYPE, (O))) \ - return 0; \ + if (!compiler_addop_o((C), (OP), (C)->u->u_ ## TYPE, (O))) \ + return 0; \ } #define ADDOP_NAME(C, OP, O, TYPE) { \ - if (!compiler_addop_name((C), (OP), (C)->u->u_ ## TYPE, (O))) \ - return 0; \ + if (!compiler_addop_name((C), (OP), (C)->u->u_ ## TYPE, (O))) \ + return 0; \ } #define ADDOP_I(C, OP, O) { \ - if (!compiler_addop_i((C), (OP), (O))) \ - return 0; \ + if (!compiler_addop_i((C), (OP), (O))) \ + return 0; \ } #define ADDOP_JABS(C, OP, O) { \ - if (!compiler_addop_j((C), (OP), (O), 1)) \ - return 0; \ + if (!compiler_addop_j((C), (OP), (O), 1)) \ + return 0; \ } #define ADDOP_JREL(C, OP, O) { \ - if (!compiler_addop_j((C), (OP), (O), 0)) \ - return 0; \ + if (!compiler_addop_j((C), (OP), (O), 0)) \ + return 0; \ } /* VISIT and VISIT_SEQ takes an ASDL type as their second argument. They use @@ -1092,49 +1092,49 @@ */ #define VISIT(C, TYPE, V) {\ - if (!compiler_visit_ ## TYPE((C), (V))) \ - return 0; \ + if (!compiler_visit_ ## TYPE((C), (V))) \ + return 0; \ } #define VISIT_IN_SCOPE(C, TYPE, V) {\ - if (!compiler_visit_ ## TYPE((C), (V))) { \ - compiler_exit_scope(c); \ - return 0; \ - } \ + if (!compiler_visit_ ## TYPE((C), (V))) { \ + compiler_exit_scope(c); \ + return 0; \ + } \ } #define VISIT_SLICE(C, V, CTX) {\ - if (!compiler_visit_slice((C), (V), (CTX))) \ - return 0; \ + if (!compiler_visit_slice((C), (V), (CTX))) \ + return 0; \ } #define VISIT_SEQ(C, TYPE, SEQ) { \ - int _i; \ - asdl_seq *seq = (SEQ); /* avoid variable capture */ \ - for (_i = 0; _i < asdl_seq_LEN(seq); _i++) { \ - TYPE ## _ty elt = (TYPE ## _ty)asdl_seq_GET(seq, _i); \ - if (!compiler_visit_ ## TYPE((C), elt)) \ - return 0; \ - } \ + int _i; \ + asdl_seq *seq = (SEQ); /* avoid variable capture */ \ + for (_i = 0; _i < asdl_seq_LEN(seq); _i++) { \ + TYPE ## _ty elt = (TYPE ## _ty)asdl_seq_GET(seq, _i); \ + if (!compiler_visit_ ## TYPE((C), elt)) \ + return 0; \ + } \ } #define VISIT_SEQ_IN_SCOPE(C, TYPE, SEQ) { \ - int _i; \ - asdl_seq *seq = (SEQ); /* avoid variable capture */ \ - for (_i = 0; _i < asdl_seq_LEN(seq); _i++) { \ - TYPE ## _ty elt = (TYPE ## _ty)asdl_seq_GET(seq, _i); \ - if (!compiler_visit_ ## TYPE((C), elt)) { \ - compiler_exit_scope(c); \ - return 0; \ - } \ - } \ + int _i; \ + asdl_seq *seq = (SEQ); /* avoid variable capture */ \ + for (_i = 0; _i < asdl_seq_LEN(seq); _i++) { \ + TYPE ## _ty elt = (TYPE ## _ty)asdl_seq_GET(seq, _i); \ + if (!compiler_visit_ ## TYPE((C), elt)) { \ + compiler_exit_scope(c); \ + return 0; \ + } \ + } \ } static int compiler_isdocstring(stmt_ty s) { if (s->kind != Expr_kind) - return 0; + return 0; return s->v.Expr.value->kind == Str_kind; } @@ -1143,67 +1143,67 @@ static int compiler_body(struct compiler *c, asdl_seq *stmts) { - int i = 0; - stmt_ty st; + int i = 0; + stmt_ty st; - if (!asdl_seq_LEN(stmts)) - return 1; - st = (stmt_ty)asdl_seq_GET(stmts, 0); - if (compiler_isdocstring(st) && Py_OptimizeFlag < 2) { - /* don't generate docstrings if -OO */ - i = 1; - VISIT(c, expr, st->v.Expr.value); - if (!compiler_nameop(c, __doc__, Store)) - return 0; - } - for (; i < asdl_seq_LEN(stmts); i++) - VISIT(c, stmt, (stmt_ty)asdl_seq_GET(stmts, i)); - return 1; + if (!asdl_seq_LEN(stmts)) + return 1; + st = (stmt_ty)asdl_seq_GET(stmts, 0); + if (compiler_isdocstring(st) && Py_OptimizeFlag < 2) { + /* don't generate docstrings if -OO */ + i = 1; + VISIT(c, expr, st->v.Expr.value); + if (!compiler_nameop(c, __doc__, Store)) + return 0; + } + for (; i < asdl_seq_LEN(stmts); i++) + VISIT(c, stmt, (stmt_ty)asdl_seq_GET(stmts, i)); + return 1; } static PyCodeObject * compiler_mod(struct compiler *c, mod_ty mod) { - PyCodeObject *co; - int addNone = 1; - static PyObject *module; - if (!module) { - module = PyUnicode_InternFromString(""); - if (!module) - return NULL; - } - /* Use 0 for firstlineno initially, will fixup in assemble(). */ - if (!compiler_enter_scope(c, module, mod, 0)) - return NULL; - switch (mod->kind) { - case Module_kind: - if (!compiler_body(c, mod->v.Module.body)) { - compiler_exit_scope(c); - return 0; - } - break; - case Interactive_kind: - c->c_interactive = 1; - VISIT_SEQ_IN_SCOPE(c, stmt, - mod->v.Interactive.body); - break; - case Expression_kind: - VISIT_IN_SCOPE(c, expr, mod->v.Expression.body); - addNone = 0; - break; - case Suite_kind: - PyErr_SetString(PyExc_SystemError, - "suite should not be possible"); - return 0; - default: - PyErr_Format(PyExc_SystemError, - "module kind %d should not be possible", - mod->kind); - return 0; - } - co = assemble(c, addNone); - compiler_exit_scope(c); - return co; + PyCodeObject *co; + int addNone = 1; + static PyObject *module; + if (!module) { + module = PyUnicode_InternFromString(""); + if (!module) + return NULL; + } + /* Use 0 for firstlineno initially, will fixup in assemble(). */ + if (!compiler_enter_scope(c, module, mod, 0)) + return NULL; + switch (mod->kind) { + case Module_kind: + if (!compiler_body(c, mod->v.Module.body)) { + compiler_exit_scope(c); + return 0; + } + break; + case Interactive_kind: + c->c_interactive = 1; + VISIT_SEQ_IN_SCOPE(c, stmt, + mod->v.Interactive.body); + break; + case Expression_kind: + VISIT_IN_SCOPE(c, expr, mod->v.Expression.body); + addNone = 0; + break; + case Suite_kind: + PyErr_SetString(PyExc_SystemError, + "suite should not be possible"); + return 0; + default: + PyErr_Format(PyExc_SystemError, + "module kind %d should not be possible", + mod->kind); + return 0; + } + co = assemble(c, addNone); + compiler_exit_scope(c); + return co; } /* The test for LOCAL must come before the test for FREE in order to @@ -1214,24 +1214,24 @@ static int get_ref_type(struct compiler *c, PyObject *name) { - int scope = PyST_GetScope(c->u->u_ste, name); - if (scope == 0) { - char buf[350]; - PyOS_snprintf(buf, sizeof(buf), - "unknown scope for %.100s in %.100s(%s) in %s\n" - "symbols: %s\nlocals: %s\nglobals: %s", - PyBytes_AS_STRING(name), - PyBytes_AS_STRING(c->u->u_name), - PyObject_REPR(c->u->u_ste->ste_id), - c->c_filename, - PyObject_REPR(c->u->u_ste->ste_symbols), - PyObject_REPR(c->u->u_varnames), - PyObject_REPR(c->u->u_names) - ); - Py_FatalError(buf); - } + int scope = PyST_GetScope(c->u->u_ste, name); + if (scope == 0) { + char buf[350]; + PyOS_snprintf(buf, sizeof(buf), + "unknown scope for %.100s in %.100s(%s) in %s\n" + "symbols: %s\nlocals: %s\nglobals: %s", + PyBytes_AS_STRING(name), + PyBytes_AS_STRING(c->u->u_name), + PyObject_REPR(c->u->u_ste->ste_id), + c->c_filename, + PyObject_REPR(c->u->u_ste->ste_symbols), + PyObject_REPR(c->u->u_varnames), + PyObject_REPR(c->u->u_names) + ); + Py_FatalError(buf); + } - return scope; + return scope; } static int @@ -1240,636 +1240,636 @@ PyObject *k, *v; k = PyTuple_Pack(2, name, name->ob_type); if (k == NULL) - return -1; + return -1; v = PyDict_GetItem(dict, k); Py_DECREF(k); if (v == NULL) - return -1; + return -1; return PyLong_AS_LONG(v); } static int compiler_make_closure(struct compiler *c, PyCodeObject *co, int args) { - int i, free = PyCode_GetNumFree(co); - if (free == 0) { - ADDOP_O(c, LOAD_CONST, (PyObject*)co, consts); - ADDOP_I(c, MAKE_FUNCTION, args); - return 1; - } - for (i = 0; i < free; ++i) { - /* Bypass com_addop_varname because it will generate - LOAD_DEREF but LOAD_CLOSURE is needed. - */ - PyObject *name = PyTuple_GET_ITEM(co->co_freevars, i); - int arg, reftype; - - /* Special case: If a class contains a method with a - free variable that has the same name as a method, - the name will be considered free *and* local in the - class. It should be handled by the closure, as - well as by the normal name loookup logic. - */ - reftype = get_ref_type(c, name); - if (reftype == CELL) - arg = compiler_lookup_arg(c->u->u_cellvars, name); - else /* (reftype == FREE) */ - arg = compiler_lookup_arg(c->u->u_freevars, name); - if (arg == -1) { - fprintf(stderr, - "lookup %s in %s %d %d\n" - "freevars of %s: %s\n", - PyObject_REPR(name), - PyBytes_AS_STRING(c->u->u_name), - reftype, arg, - _PyUnicode_AsString(co->co_name), - PyObject_REPR(co->co_freevars)); - Py_FatalError("compiler_make_closure()"); - } - ADDOP_I(c, LOAD_CLOSURE, arg); - } - ADDOP_I(c, BUILD_TUPLE, free); - ADDOP_O(c, LOAD_CONST, (PyObject*)co, consts); - ADDOP_I(c, MAKE_CLOSURE, args); - return 1; + int i, free = PyCode_GetNumFree(co); + if (free == 0) { + ADDOP_O(c, LOAD_CONST, (PyObject*)co, consts); + ADDOP_I(c, MAKE_FUNCTION, args); + return 1; + } + for (i = 0; i < free; ++i) { + /* Bypass com_addop_varname because it will generate + LOAD_DEREF but LOAD_CLOSURE is needed. + */ + PyObject *name = PyTuple_GET_ITEM(co->co_freevars, i); + int arg, reftype; + + /* Special case: If a class contains a method with a + free variable that has the same name as a method, + the name will be considered free *and* local in the + class. It should be handled by the closure, as + well as by the normal name loookup logic. + */ + reftype = get_ref_type(c, name); + if (reftype == CELL) + arg = compiler_lookup_arg(c->u->u_cellvars, name); + else /* (reftype == FREE) */ + arg = compiler_lookup_arg(c->u->u_freevars, name); + if (arg == -1) { + fprintf(stderr, + "lookup %s in %s %d %d\n" + "freevars of %s: %s\n", + PyObject_REPR(name), + PyBytes_AS_STRING(c->u->u_name), + reftype, arg, + _PyUnicode_AsString(co->co_name), + PyObject_REPR(co->co_freevars)); + Py_FatalError("compiler_make_closure()"); + } + ADDOP_I(c, LOAD_CLOSURE, arg); + } + ADDOP_I(c, BUILD_TUPLE, free); + ADDOP_O(c, LOAD_CONST, (PyObject*)co, consts); + ADDOP_I(c, MAKE_CLOSURE, args); + return 1; } static int compiler_decorators(struct compiler *c, asdl_seq* decos) { - int i; + int i; - if (!decos) - return 1; + if (!decos) + return 1; - for (i = 0; i < asdl_seq_LEN(decos); i++) { - VISIT(c, expr, (expr_ty)asdl_seq_GET(decos, i)); - } - return 1; + for (i = 0; i < asdl_seq_LEN(decos); i++) { + VISIT(c, expr, (expr_ty)asdl_seq_GET(decos, i)); + } + return 1; } static int compiler_visit_kwonlydefaults(struct compiler *c, asdl_seq *kwonlyargs, - asdl_seq *kw_defaults) + asdl_seq *kw_defaults) { - int i, default_count = 0; - for (i = 0; i < asdl_seq_LEN(kwonlyargs); i++) { - arg_ty arg = asdl_seq_GET(kwonlyargs, i); - expr_ty default_ = asdl_seq_GET(kw_defaults, i); - if (default_) { - ADDOP_O(c, LOAD_CONST, arg->arg, consts); - if (!compiler_visit_expr(c, default_)) { - return -1; - } - default_count++; - } - } - return default_count; + int i, default_count = 0; + for (i = 0; i < asdl_seq_LEN(kwonlyargs); i++) { + arg_ty arg = asdl_seq_GET(kwonlyargs, i); + expr_ty default_ = asdl_seq_GET(kw_defaults, i); + if (default_) { + ADDOP_O(c, LOAD_CONST, arg->arg, consts); + if (!compiler_visit_expr(c, default_)) { + return -1; + } + default_count++; + } + } + return default_count; } static int compiler_visit_argannotation(struct compiler *c, identifier id, expr_ty annotation, PyObject *names) { - if (annotation) { - VISIT(c, expr, annotation); - if (PyList_Append(names, id)) - return -1; - } - return 0; + if (annotation) { + VISIT(c, expr, annotation); + if (PyList_Append(names, id)) + return -1; + } + return 0; } static int compiler_visit_argannotations(struct compiler *c, asdl_seq* args, PyObject *names) { - int i, error; - for (i = 0; i < asdl_seq_LEN(args); i++) { - arg_ty arg = (arg_ty)asdl_seq_GET(args, i); - error = compiler_visit_argannotation( - c, - arg->arg, - arg->annotation, - names); - if (error) - return error; - } - return 0; + int i, error; + for (i = 0; i < asdl_seq_LEN(args); i++) { + arg_ty arg = (arg_ty)asdl_seq_GET(args, i); + error = compiler_visit_argannotation( + c, + arg->arg, + arg->annotation, + names); + if (error) + return error; + } + return 0; } static int compiler_visit_annotations(struct compiler *c, arguments_ty args, expr_ty returns) { - /* Push arg annotations and a list of the argument names. Return the # - of items pushed. The expressions are evaluated out-of-order wrt the - source code. - - More than 2^16-1 annotations is a SyntaxError. Returns -1 on error. - */ - static identifier return_str; - PyObject *names; - int len; - names = PyList_New(0); - if (!names) - return -1; - - if (compiler_visit_argannotations(c, args->args, names)) - goto error; - if (args->varargannotation && - compiler_visit_argannotation(c, args->vararg, - args->varargannotation, names)) - goto error; - if (compiler_visit_argannotations(c, args->kwonlyargs, names)) - goto error; - if (args->kwargannotation && - compiler_visit_argannotation(c, args->kwarg, - args->kwargannotation, names)) - goto error; - - if (!return_str) { - return_str = PyUnicode_InternFromString("return"); - if (!return_str) - goto error; - } - if (compiler_visit_argannotation(c, return_str, returns, names)) { - goto error; - } - - len = PyList_GET_SIZE(names); - if (len > 65534) { - /* len must fit in 16 bits, and len is incremented below */ - PyErr_SetString(PyExc_SyntaxError, - "too many annotations"); - goto error; - } - if (len) { - /* convert names to a tuple and place on stack */ - PyObject *elt; - int i; - PyObject *s = PyTuple_New(len); - if (!s) - goto error; - for (i = 0; i < len; i++) { - elt = PyList_GET_ITEM(names, i); - Py_INCREF(elt); - PyTuple_SET_ITEM(s, i, elt); - } - ADDOP_O(c, LOAD_CONST, s, consts); - Py_DECREF(s); - len++; /* include the just-pushed tuple */ - } - Py_DECREF(names); - return len; + /* Push arg annotations and a list of the argument names. Return the # + of items pushed. The expressions are evaluated out-of-order wrt the + source code. + + More than 2^16-1 annotations is a SyntaxError. Returns -1 on error. + */ + static identifier return_str; + PyObject *names; + int len; + names = PyList_New(0); + if (!names) + return -1; + + if (compiler_visit_argannotations(c, args->args, names)) + goto error; + if (args->varargannotation && + compiler_visit_argannotation(c, args->vararg, + args->varargannotation, names)) + goto error; + if (compiler_visit_argannotations(c, args->kwonlyargs, names)) + goto error; + if (args->kwargannotation && + compiler_visit_argannotation(c, args->kwarg, + args->kwargannotation, names)) + goto error; + + if (!return_str) { + return_str = PyUnicode_InternFromString("return"); + if (!return_str) + goto error; + } + if (compiler_visit_argannotation(c, return_str, returns, names)) { + goto error; + } + + len = PyList_GET_SIZE(names); + if (len > 65534) { + /* len must fit in 16 bits, and len is incremented below */ + PyErr_SetString(PyExc_SyntaxError, + "too many annotations"); + goto error; + } + if (len) { + /* convert names to a tuple and place on stack */ + PyObject *elt; + int i; + PyObject *s = PyTuple_New(len); + if (!s) + goto error; + for (i = 0; i < len; i++) { + elt = PyList_GET_ITEM(names, i); + Py_INCREF(elt); + PyTuple_SET_ITEM(s, i, elt); + } + ADDOP_O(c, LOAD_CONST, s, consts); + Py_DECREF(s); + len++; /* include the just-pushed tuple */ + } + Py_DECREF(names); + return len; error: - Py_DECREF(names); - return -1; + Py_DECREF(names); + return -1; } static int compiler_function(struct compiler *c, stmt_ty s) { - PyCodeObject *co; - PyObject *first_const = Py_None; - arguments_ty args = s->v.FunctionDef.args; - expr_ty returns = s->v.FunctionDef.returns; - asdl_seq* decos = s->v.FunctionDef.decorator_list; - stmt_ty st; - int i, n, docstring, kw_default_count = 0, arglength; - int num_annotations; - - assert(s->kind == FunctionDef_kind); - - if (!compiler_decorators(c, decos)) - return 0; - if (args->kwonlyargs) { - int res = compiler_visit_kwonlydefaults(c, args->kwonlyargs, - args->kw_defaults); - if (res < 0) - return 0; - kw_default_count = res; - } - if (args->defaults) - VISIT_SEQ(c, expr, args->defaults); - num_annotations = compiler_visit_annotations(c, args, returns); - if (num_annotations < 0) - return 0; - assert((num_annotations & 0xFFFF) == num_annotations); - - if (!compiler_enter_scope(c, s->v.FunctionDef.name, (void *)s, - s->lineno)) - return 0; - - st = (stmt_ty)asdl_seq_GET(s->v.FunctionDef.body, 0); - docstring = compiler_isdocstring(st); - if (docstring && Py_OptimizeFlag < 2) - first_const = st->v.Expr.value->v.Str.s; - if (compiler_add_o(c, c->u->u_consts, first_const) < 0) { - compiler_exit_scope(c); - return 0; - } - - c->u->u_argcount = asdl_seq_LEN(args->args); - c->u->u_kwonlyargcount = asdl_seq_LEN(args->kwonlyargs); - n = asdl_seq_LEN(s->v.FunctionDef.body); - /* if there was a docstring, we need to skip the first statement */ - for (i = docstring; i < n; i++) { - st = (stmt_ty)asdl_seq_GET(s->v.FunctionDef.body, i); - VISIT_IN_SCOPE(c, stmt, st); - } - co = assemble(c, 1); - compiler_exit_scope(c); - if (co == NULL) - return 0; - - arglength = asdl_seq_LEN(args->defaults); - arglength |= kw_default_count << 8; - arglength |= num_annotations << 16; - compiler_make_closure(c, co, arglength); - Py_DECREF(co); - - /* decorators */ - for (i = 0; i < asdl_seq_LEN(decos); i++) { - ADDOP_I(c, CALL_FUNCTION, 1); - } + PyCodeObject *co; + PyObject *first_const = Py_None; + arguments_ty args = s->v.FunctionDef.args; + expr_ty returns = s->v.FunctionDef.returns; + asdl_seq* decos = s->v.FunctionDef.decorator_list; + stmt_ty st; + int i, n, docstring, kw_default_count = 0, arglength; + int num_annotations; + + assert(s->kind == FunctionDef_kind); + + if (!compiler_decorators(c, decos)) + return 0; + if (args->kwonlyargs) { + int res = compiler_visit_kwonlydefaults(c, args->kwonlyargs, + args->kw_defaults); + if (res < 0) + return 0; + kw_default_count = res; + } + if (args->defaults) + VISIT_SEQ(c, expr, args->defaults); + num_annotations = compiler_visit_annotations(c, args, returns); + if (num_annotations < 0) + return 0; + assert((num_annotations & 0xFFFF) == num_annotations); + + if (!compiler_enter_scope(c, s->v.FunctionDef.name, (void *)s, + s->lineno)) + return 0; + + st = (stmt_ty)asdl_seq_GET(s->v.FunctionDef.body, 0); + docstring = compiler_isdocstring(st); + if (docstring && Py_OptimizeFlag < 2) + first_const = st->v.Expr.value->v.Str.s; + if (compiler_add_o(c, c->u->u_consts, first_const) < 0) { + compiler_exit_scope(c); + return 0; + } - return compiler_nameop(c, s->v.FunctionDef.name, Store); + c->u->u_argcount = asdl_seq_LEN(args->args); + c->u->u_kwonlyargcount = asdl_seq_LEN(args->kwonlyargs); + n = asdl_seq_LEN(s->v.FunctionDef.body); + /* if there was a docstring, we need to skip the first statement */ + for (i = docstring; i < n; i++) { + st = (stmt_ty)asdl_seq_GET(s->v.FunctionDef.body, i); + VISIT_IN_SCOPE(c, stmt, st); + } + co = assemble(c, 1); + compiler_exit_scope(c); + if (co == NULL) + return 0; + + arglength = asdl_seq_LEN(args->defaults); + arglength |= kw_default_count << 8; + arglength |= num_annotations << 16; + compiler_make_closure(c, co, arglength); + Py_DECREF(co); + + /* decorators */ + for (i = 0; i < asdl_seq_LEN(decos); i++) { + ADDOP_I(c, CALL_FUNCTION, 1); + } + + return compiler_nameop(c, s->v.FunctionDef.name, Store); } static int compiler_class(struct compiler *c, stmt_ty s) { - PyCodeObject *co; - PyObject *str; - int i; - asdl_seq* decos = s->v.ClassDef.decorator_list; - - if (!compiler_decorators(c, decos)) - return 0; + PyCodeObject *co; + PyObject *str; + int i; + asdl_seq* decos = s->v.ClassDef.decorator_list; + + if (!compiler_decorators(c, decos)) + return 0; + + /* ultimately generate code for: + = __build_class__(, , *, **) + where: + is a function/closure created from the class body; + it has a single argument (__locals__) where the dict + (or MutableSequence) representing the locals is passed + is the class name + is the positional arguments and *varargs argument + is the keyword arguments and **kwds argument + This borrows from compiler_call. + */ + + /* 1. compile the class body into a code object */ + if (!compiler_enter_scope(c, s->v.ClassDef.name, (void *)s, s->lineno)) + return 0; + /* this block represents what we do in the new scope */ + { + /* use the class name for name mangling */ + Py_INCREF(s->v.ClassDef.name); + Py_XDECREF(c->u->u_private); + c->u->u_private = s->v.ClassDef.name; + /* force it to have one mandatory argument */ + c->u->u_argcount = 1; + /* load the first argument (__locals__) ... */ + ADDOP_I(c, LOAD_FAST, 0); + /* ... and store it into f_locals */ + ADDOP_IN_SCOPE(c, STORE_LOCALS); + /* load (global) __name__ ... */ + str = PyUnicode_InternFromString("__name__"); + if (!str || !compiler_nameop(c, str, Load)) { + Py_XDECREF(str); + compiler_exit_scope(c); + return 0; + } + Py_DECREF(str); + /* ... and store it as __module__ */ + str = PyUnicode_InternFromString("__module__"); + if (!str || !compiler_nameop(c, str, Store)) { + Py_XDECREF(str); + compiler_exit_scope(c); + return 0; + } + Py_DECREF(str); + /* compile the body proper */ + if (!compiler_body(c, s->v.ClassDef.body)) { + compiler_exit_scope(c); + return 0; + } + /* return the (empty) __class__ cell */ + str = PyUnicode_InternFromString("__class__"); + if (str == NULL) { + compiler_exit_scope(c); + return 0; + } + i = compiler_lookup_arg(c->u->u_cellvars, str); + Py_DECREF(str); + if (i == -1) { + /* This happens when nobody references the cell */ + PyErr_Clear(); + /* Return None */ + ADDOP_O(c, LOAD_CONST, Py_None, consts); + } + else { + /* Return the cell where to store __class__ */ + ADDOP_I(c, LOAD_CLOSURE, i); + } + ADDOP_IN_SCOPE(c, RETURN_VALUE); + /* create the code object */ + co = assemble(c, 1); + } + /* leave the new scope */ + compiler_exit_scope(c); + if (co == NULL) + return 0; + + /* 2. load the 'build_class' function */ + ADDOP(c, LOAD_BUILD_CLASS); + + /* 3. load a function (or closure) made from the code object */ + compiler_make_closure(c, co, 0); + Py_DECREF(co); + + /* 4. load class name */ + ADDOP_O(c, LOAD_CONST, s->v.ClassDef.name, consts); + + /* 5. generate the rest of the code for the call */ + if (!compiler_call_helper(c, 2, + s->v.ClassDef.bases, + s->v.ClassDef.keywords, + s->v.ClassDef.starargs, + s->v.ClassDef.kwargs)) + return 0; + + /* 6. apply decorators */ + for (i = 0; i < asdl_seq_LEN(decos); i++) { + ADDOP_I(c, CALL_FUNCTION, 1); + } - /* ultimately generate code for: - = __build_class__(, , *, **) - where: - is a function/closure created from the class body; - it has a single argument (__locals__) where the dict - (or MutableSequence) representing the locals is passed - is the class name - is the positional arguments and *varargs argument - is the keyword arguments and **kwds argument - This borrows from compiler_call. - */ - - /* 1. compile the class body into a code object */ - if (!compiler_enter_scope(c, s->v.ClassDef.name, (void *)s, s->lineno)) - return 0; - /* this block represents what we do in the new scope */ - { - /* use the class name for name mangling */ - Py_INCREF(s->v.ClassDef.name); - Py_XDECREF(c->u->u_private); - c->u->u_private = s->v.ClassDef.name; - /* force it to have one mandatory argument */ - c->u->u_argcount = 1; - /* load the first argument (__locals__) ... */ - ADDOP_I(c, LOAD_FAST, 0); - /* ... and store it into f_locals */ - ADDOP_IN_SCOPE(c, STORE_LOCALS); - /* load (global) __name__ ... */ - str = PyUnicode_InternFromString("__name__"); - if (!str || !compiler_nameop(c, str, Load)) { - Py_XDECREF(str); - compiler_exit_scope(c); - return 0; - } - Py_DECREF(str); - /* ... and store it as __module__ */ - str = PyUnicode_InternFromString("__module__"); - if (!str || !compiler_nameop(c, str, Store)) { - Py_XDECREF(str); - compiler_exit_scope(c); - return 0; - } - Py_DECREF(str); - /* compile the body proper */ - if (!compiler_body(c, s->v.ClassDef.body)) { - compiler_exit_scope(c); - return 0; - } - /* return the (empty) __class__ cell */ - str = PyUnicode_InternFromString("__class__"); - if (str == NULL) { - compiler_exit_scope(c); - return 0; - } - i = compiler_lookup_arg(c->u->u_cellvars, str); - Py_DECREF(str); - if (i == -1) { - /* This happens when nobody references the cell */ - PyErr_Clear(); - /* Return None */ - ADDOP_O(c, LOAD_CONST, Py_None, consts); - } - else { - /* Return the cell where to store __class__ */ - ADDOP_I(c, LOAD_CLOSURE, i); - } - ADDOP_IN_SCOPE(c, RETURN_VALUE); - /* create the code object */ - co = assemble(c, 1); - } - /* leave the new scope */ - compiler_exit_scope(c); - if (co == NULL) - return 0; - - /* 2. load the 'build_class' function */ - ADDOP(c, LOAD_BUILD_CLASS); - - /* 3. load a function (or closure) made from the code object */ - compiler_make_closure(c, co, 0); - Py_DECREF(co); - - /* 4. load class name */ - ADDOP_O(c, LOAD_CONST, s->v.ClassDef.name, consts); - - /* 5. generate the rest of the code for the call */ - if (!compiler_call_helper(c, 2, - s->v.ClassDef.bases, - s->v.ClassDef.keywords, - s->v.ClassDef.starargs, - s->v.ClassDef.kwargs)) - return 0; - - /* 6. apply decorators */ - for (i = 0; i < asdl_seq_LEN(decos); i++) { - ADDOP_I(c, CALL_FUNCTION, 1); - } - - /* 7. store into */ - if (!compiler_nameop(c, s->v.ClassDef.name, Store)) - return 0; - return 1; + /* 7. store into */ + if (!compiler_nameop(c, s->v.ClassDef.name, Store)) + return 0; + return 1; } static int compiler_ifexp(struct compiler *c, expr_ty e) { - basicblock *end, *next; - - assert(e->kind == IfExp_kind); - end = compiler_new_block(c); - if (end == NULL) - return 0; - next = compiler_new_block(c); - if (next == NULL) - return 0; - VISIT(c, expr, e->v.IfExp.test); - ADDOP_JABS(c, POP_JUMP_IF_FALSE, next); - VISIT(c, expr, e->v.IfExp.body); - ADDOP_JREL(c, JUMP_FORWARD, end); - compiler_use_next_block(c, next); - VISIT(c, expr, e->v.IfExp.orelse); - compiler_use_next_block(c, end); - return 1; + basicblock *end, *next; + + assert(e->kind == IfExp_kind); + end = compiler_new_block(c); + if (end == NULL) + return 0; + next = compiler_new_block(c); + if (next == NULL) + return 0; + VISIT(c, expr, e->v.IfExp.test); + ADDOP_JABS(c, POP_JUMP_IF_FALSE, next); + VISIT(c, expr, e->v.IfExp.body); + ADDOP_JREL(c, JUMP_FORWARD, end); + compiler_use_next_block(c, next); + VISIT(c, expr, e->v.IfExp.orelse); + compiler_use_next_block(c, end); + return 1; } static int compiler_lambda(struct compiler *c, expr_ty e) { - PyCodeObject *co; - static identifier name; - int kw_default_count = 0, arglength; - arguments_ty args = e->v.Lambda.args; - assert(e->kind == Lambda_kind); - - if (!name) { - name = PyUnicode_InternFromString(""); - if (!name) - return 0; - } - - if (args->kwonlyargs) { - int res = compiler_visit_kwonlydefaults(c, args->kwonlyargs, - args->kw_defaults); - if (res < 0) return 0; - kw_default_count = res; - } - if (args->defaults) - VISIT_SEQ(c, expr, args->defaults); - if (!compiler_enter_scope(c, name, (void *)e, e->lineno)) - return 0; - - /* Make None the first constant, so the lambda can't have a - docstring. */ - if (compiler_add_o(c, c->u->u_consts, Py_None) < 0) - return 0; - - c->u->u_argcount = asdl_seq_LEN(args->args); - c->u->u_kwonlyargcount = asdl_seq_LEN(args->kwonlyargs); - VISIT_IN_SCOPE(c, expr, e->v.Lambda.body); - if (c->u->u_ste->ste_generator) { - ADDOP_IN_SCOPE(c, POP_TOP); - } - else { - ADDOP_IN_SCOPE(c, RETURN_VALUE); - } - co = assemble(c, 1); - compiler_exit_scope(c); - if (co == NULL) - return 0; - - arglength = asdl_seq_LEN(args->defaults); - arglength |= kw_default_count << 8; - compiler_make_closure(c, co, arglength); - Py_DECREF(co); + PyCodeObject *co; + static identifier name; + int kw_default_count = 0, arglength; + arguments_ty args = e->v.Lambda.args; + assert(e->kind == Lambda_kind); + + if (!name) { + name = PyUnicode_InternFromString(""); + if (!name) + return 0; + } - return 1; + if (args->kwonlyargs) { + int res = compiler_visit_kwonlydefaults(c, args->kwonlyargs, + args->kw_defaults); + if (res < 0) return 0; + kw_default_count = res; + } + if (args->defaults) + VISIT_SEQ(c, expr, args->defaults); + if (!compiler_enter_scope(c, name, (void *)e, e->lineno)) + return 0; + + /* Make None the first constant, so the lambda can't have a + docstring. */ + if (compiler_add_o(c, c->u->u_consts, Py_None) < 0) + return 0; + + c->u->u_argcount = asdl_seq_LEN(args->args); + c->u->u_kwonlyargcount = asdl_seq_LEN(args->kwonlyargs); + VISIT_IN_SCOPE(c, expr, e->v.Lambda.body); + if (c->u->u_ste->ste_generator) { + ADDOP_IN_SCOPE(c, POP_TOP); + } + else { + ADDOP_IN_SCOPE(c, RETURN_VALUE); + } + co = assemble(c, 1); + compiler_exit_scope(c); + if (co == NULL) + return 0; + + arglength = asdl_seq_LEN(args->defaults); + arglength |= kw_default_count << 8; + compiler_make_closure(c, co, arglength); + Py_DECREF(co); + + return 1; } static int compiler_if(struct compiler *c, stmt_ty s) { - basicblock *end, *next; - int constant; - assert(s->kind == If_kind); - end = compiler_new_block(c); - if (end == NULL) - return 0; - - constant = expr_constant(s->v.If.test); - /* constant = 0: "if 0" - * constant = 1: "if 1", "if 2", ... - * constant = -1: rest */ - if (constant == 0) { - if (s->v.If.orelse) - VISIT_SEQ(c, stmt, s->v.If.orelse); - } else if (constant == 1) { - VISIT_SEQ(c, stmt, s->v.If.body); - } else { - if (s->v.If.orelse) { - next = compiler_new_block(c); - if (next == NULL) - return 0; - } - else - next = end; - VISIT(c, expr, s->v.If.test); - ADDOP_JABS(c, POP_JUMP_IF_FALSE, next); - VISIT_SEQ(c, stmt, s->v.If.body); - ADDOP_JREL(c, JUMP_FORWARD, end); - if (s->v.If.orelse) { - compiler_use_next_block(c, next); - VISIT_SEQ(c, stmt, s->v.If.orelse); - } - } - compiler_use_next_block(c, end); - return 1; + basicblock *end, *next; + int constant; + assert(s->kind == If_kind); + end = compiler_new_block(c); + if (end == NULL) + return 0; + + constant = expr_constant(s->v.If.test); + /* constant = 0: "if 0" + * constant = 1: "if 1", "if 2", ... + * constant = -1: rest */ + if (constant == 0) { + if (s->v.If.orelse) + VISIT_SEQ(c, stmt, s->v.If.orelse); + } else if (constant == 1) { + VISIT_SEQ(c, stmt, s->v.If.body); + } else { + if (s->v.If.orelse) { + next = compiler_new_block(c); + if (next == NULL) + return 0; + } + else + next = end; + VISIT(c, expr, s->v.If.test); + ADDOP_JABS(c, POP_JUMP_IF_FALSE, next); + VISIT_SEQ(c, stmt, s->v.If.body); + ADDOP_JREL(c, JUMP_FORWARD, end); + if (s->v.If.orelse) { + compiler_use_next_block(c, next); + VISIT_SEQ(c, stmt, s->v.If.orelse); + } + } + compiler_use_next_block(c, end); + return 1; } static int compiler_for(struct compiler *c, stmt_ty s) { - basicblock *start, *cleanup, *end; + basicblock *start, *cleanup, *end; - start = compiler_new_block(c); - cleanup = compiler_new_block(c); - end = compiler_new_block(c); - if (start == NULL || end == NULL || cleanup == NULL) - return 0; - ADDOP_JREL(c, SETUP_LOOP, end); - if (!compiler_push_fblock(c, LOOP, start)) - return 0; - VISIT(c, expr, s->v.For.iter); - ADDOP(c, GET_ITER); - compiler_use_next_block(c, start); - ADDOP_JREL(c, FOR_ITER, cleanup); - VISIT(c, expr, s->v.For.target); - VISIT_SEQ(c, stmt, s->v.For.body); - ADDOP_JABS(c, JUMP_ABSOLUTE, start); - compiler_use_next_block(c, cleanup); - ADDOP(c, POP_BLOCK); - compiler_pop_fblock(c, LOOP, start); - VISIT_SEQ(c, stmt, s->v.For.orelse); - compiler_use_next_block(c, end); - return 1; + start = compiler_new_block(c); + cleanup = compiler_new_block(c); + end = compiler_new_block(c); + if (start == NULL || end == NULL || cleanup == NULL) + return 0; + ADDOP_JREL(c, SETUP_LOOP, end); + if (!compiler_push_fblock(c, LOOP, start)) + return 0; + VISIT(c, expr, s->v.For.iter); + ADDOP(c, GET_ITER); + compiler_use_next_block(c, start); + ADDOP_JREL(c, FOR_ITER, cleanup); + VISIT(c, expr, s->v.For.target); + VISIT_SEQ(c, stmt, s->v.For.body); + ADDOP_JABS(c, JUMP_ABSOLUTE, start); + compiler_use_next_block(c, cleanup); + ADDOP(c, POP_BLOCK); + compiler_pop_fblock(c, LOOP, start); + VISIT_SEQ(c, stmt, s->v.For.orelse); + compiler_use_next_block(c, end); + return 1; } static int compiler_while(struct compiler *c, stmt_ty s) { - basicblock *loop, *orelse, *end, *anchor = NULL; - int constant = expr_constant(s->v.While.test); + basicblock *loop, *orelse, *end, *anchor = NULL; + int constant = expr_constant(s->v.While.test); + + if (constant == 0) { + if (s->v.While.orelse) + VISIT_SEQ(c, stmt, s->v.While.orelse); + return 1; + } + loop = compiler_new_block(c); + end = compiler_new_block(c); + if (constant == -1) { + anchor = compiler_new_block(c); + if (anchor == NULL) + return 0; + } + if (loop == NULL || end == NULL) + return 0; + if (s->v.While.orelse) { + orelse = compiler_new_block(c); + if (orelse == NULL) + return 0; + } + else + orelse = NULL; + + ADDOP_JREL(c, SETUP_LOOP, end); + compiler_use_next_block(c, loop); + if (!compiler_push_fblock(c, LOOP, loop)) + return 0; + if (constant == -1) { + VISIT(c, expr, s->v.While.test); + ADDOP_JABS(c, POP_JUMP_IF_FALSE, anchor); + } + VISIT_SEQ(c, stmt, s->v.While.body); + ADDOP_JABS(c, JUMP_ABSOLUTE, loop); - if (constant == 0) { - if (s->v.While.orelse) - VISIT_SEQ(c, stmt, s->v.While.orelse); - return 1; - } - loop = compiler_new_block(c); - end = compiler_new_block(c); - if (constant == -1) { - anchor = compiler_new_block(c); - if (anchor == NULL) - return 0; - } - if (loop == NULL || end == NULL) - return 0; - if (s->v.While.orelse) { - orelse = compiler_new_block(c); - if (orelse == NULL) - return 0; - } - else - orelse = NULL; - - ADDOP_JREL(c, SETUP_LOOP, end); - compiler_use_next_block(c, loop); - if (!compiler_push_fblock(c, LOOP, loop)) - return 0; - if (constant == -1) { - VISIT(c, expr, s->v.While.test); - ADDOP_JABS(c, POP_JUMP_IF_FALSE, anchor); - } - VISIT_SEQ(c, stmt, s->v.While.body); - ADDOP_JABS(c, JUMP_ABSOLUTE, loop); - - /* XXX should the two POP instructions be in a separate block - if there is no else clause ? - */ - - if (constant == -1) { - compiler_use_next_block(c, anchor); - ADDOP(c, POP_BLOCK); - } - compiler_pop_fblock(c, LOOP, loop); - if (orelse != NULL) /* what if orelse is just pass? */ - VISIT_SEQ(c, stmt, s->v.While.orelse); - compiler_use_next_block(c, end); + /* XXX should the two POP instructions be in a separate block + if there is no else clause ? + */ + + if (constant == -1) { + compiler_use_next_block(c, anchor); + ADDOP(c, POP_BLOCK); + } + compiler_pop_fblock(c, LOOP, loop); + if (orelse != NULL) /* what if orelse is just pass? */ + VISIT_SEQ(c, stmt, s->v.While.orelse); + compiler_use_next_block(c, end); - return 1; + return 1; } static int compiler_continue(struct compiler *c) { - static const char LOOP_ERROR_MSG[] = "'continue' not properly in loop"; - static const char IN_FINALLY_ERROR_MSG[] = - "'continue' not supported inside 'finally' clause"; - int i; - - if (!c->u->u_nfblocks) - return compiler_error(c, LOOP_ERROR_MSG); - i = c->u->u_nfblocks - 1; - switch (c->u->u_fblock[i].fb_type) { - case LOOP: - ADDOP_JABS(c, JUMP_ABSOLUTE, c->u->u_fblock[i].fb_block); - break; - case EXCEPT: - case FINALLY_TRY: - while (--i >= 0 && c->u->u_fblock[i].fb_type != LOOP) { - /* Prevent continue anywhere under a finally - even if hidden in a sub-try or except. */ - if (c->u->u_fblock[i].fb_type == FINALLY_END) - return compiler_error(c, IN_FINALLY_ERROR_MSG); - } - if (i == -1) - return compiler_error(c, LOOP_ERROR_MSG); - ADDOP_JABS(c, CONTINUE_LOOP, c->u->u_fblock[i].fb_block); - break; - case FINALLY_END: - return compiler_error(c, IN_FINALLY_ERROR_MSG); - } + static const char LOOP_ERROR_MSG[] = "'continue' not properly in loop"; + static const char IN_FINALLY_ERROR_MSG[] = + "'continue' not supported inside 'finally' clause"; + int i; + + if (!c->u->u_nfblocks) + return compiler_error(c, LOOP_ERROR_MSG); + i = c->u->u_nfblocks - 1; + switch (c->u->u_fblock[i].fb_type) { + case LOOP: + ADDOP_JABS(c, JUMP_ABSOLUTE, c->u->u_fblock[i].fb_block); + break; + case EXCEPT: + case FINALLY_TRY: + while (--i >= 0 && c->u->u_fblock[i].fb_type != LOOP) { + /* Prevent continue anywhere under a finally + even if hidden in a sub-try or except. */ + if (c->u->u_fblock[i].fb_type == FINALLY_END) + return compiler_error(c, IN_FINALLY_ERROR_MSG); + } + if (i == -1) + return compiler_error(c, LOOP_ERROR_MSG); + ADDOP_JABS(c, CONTINUE_LOOP, c->u->u_fblock[i].fb_block); + break; + case FINALLY_END: + return compiler_error(c, IN_FINALLY_ERROR_MSG); + } - return 1; + return 1; } /* Code generated for "try: finally: " is as follows: - - SETUP_FINALLY L - - POP_BLOCK - LOAD_CONST - L: - END_FINALLY - + + SETUP_FINALLY L + + POP_BLOCK + LOAD_CONST + L: + END_FINALLY + The special instructions use the block stack. Each block stack entry contains the instruction that created it (here SETUP_FINALLY), the level of the value stack at the time the block stack entry was created, and a label (here L). - + SETUP_FINALLY: - Pushes the current value stack level and the label - onto the block stack. + Pushes the current value stack level and the label + onto the block stack. POP_BLOCK: - Pops en entry from the block stack, and pops the value - stack until its level is the same as indicated on the - block stack. (The label is ignored.) + Pops en entry from the block stack, and pops the value + stack until its level is the same as indicated on the + block stack. (The label is ignored.) END_FINALLY: - Pops a variable number of entries from the *value* stack - and re-raises the exception they specify. The number of - entries popped depends on the (pseudo) exception type. - + Pops a variable number of entries from the *value* stack + and re-raises the exception they specify. The number of + entries popped depends on the (pseudo) exception type. + The block stack is unwound when an exception is raised: when a SETUP_FINALLY entry is found, the exception is pushed onto the value stack (and the exception condition is cleared), @@ -1880,29 +1880,29 @@ static int compiler_try_finally(struct compiler *c, stmt_ty s) { - basicblock *body, *end; - body = compiler_new_block(c); - end = compiler_new_block(c); - if (body == NULL || end == NULL) - return 0; - - ADDOP_JREL(c, SETUP_FINALLY, end); - compiler_use_next_block(c, body); - if (!compiler_push_fblock(c, FINALLY_TRY, body)) - return 0; - VISIT_SEQ(c, stmt, s->v.TryFinally.body); - ADDOP(c, POP_BLOCK); - compiler_pop_fblock(c, FINALLY_TRY, body); - - ADDOP_O(c, LOAD_CONST, Py_None, consts); - compiler_use_next_block(c, end); - if (!compiler_push_fblock(c, FINALLY_END, end)) - return 0; - VISIT_SEQ(c, stmt, s->v.TryFinally.finalbody); - ADDOP(c, END_FINALLY); - compiler_pop_fblock(c, FINALLY_END, end); + basicblock *body, *end; + body = compiler_new_block(c); + end = compiler_new_block(c); + if (body == NULL || end == NULL) + return 0; + + ADDOP_JREL(c, SETUP_FINALLY, end); + compiler_use_next_block(c, body); + if (!compiler_push_fblock(c, FINALLY_TRY, body)) + return 0; + VISIT_SEQ(c, stmt, s->v.TryFinally.body); + ADDOP(c, POP_BLOCK); + compiler_pop_fblock(c, FINALLY_TRY, body); - return 1; + ADDOP_O(c, LOAD_CONST, Py_None, consts); + compiler_use_next_block(c, end); + if (!compiler_push_fblock(c, FINALLY_END, end)) + return 0; + VISIT_SEQ(c, stmt, s->v.TryFinally.finalbody); + ADDOP(c, END_FINALLY); + compiler_pop_fblock(c, FINALLY_END, end); + + return 1; } /* @@ -1910,864 +1910,864 @@ (The contents of the value stack is shown in [], with the top at the right; 'tb' is trace-back info, 'val' the exception's associated value, and 'exc' the exception.) - - Value stack Label Instruction Argument - [] SETUP_EXCEPT L1 - [] - [] POP_BLOCK - [] JUMP_FORWARD L0 - - [tb, val, exc] L1: DUP ) - [tb, val, exc, exc] ) - [tb, val, exc, exc, E1] COMPARE_OP EXC_MATCH ) only if E1 - [tb, val, exc, 1-or-0] POP_JUMP_IF_FALSE L2 ) - [tb, val, exc] POP - [tb, val] (or POP if no V1) - [tb] POP - [] - JUMP_FORWARD L0 - - [tb, val, exc] L2: DUP + + Value stack Label Instruction Argument + [] SETUP_EXCEPT L1 + [] + [] POP_BLOCK + [] JUMP_FORWARD L0 + + [tb, val, exc] L1: DUP ) + [tb, val, exc, exc] ) + [tb, val, exc, exc, E1] COMPARE_OP EXC_MATCH ) only if E1 + [tb, val, exc, 1-or-0] POP_JUMP_IF_FALSE L2 ) + [tb, val, exc] POP + [tb, val] (or POP if no V1) + [tb] POP + [] + JUMP_FORWARD L0 + + [tb, val, exc] L2: DUP .............................etc....................... - [tb, val, exc] Ln+1: END_FINALLY # re-raise exception - - [] L0: - + [tb, val, exc] Ln+1: END_FINALLY # re-raise exception + + [] L0: + Of course, parts are not generated if Vi or Ei is not present. */ static int compiler_try_except(struct compiler *c, stmt_ty s) { - basicblock *body, *orelse, *except, *end; - int i, n; + basicblock *body, *orelse, *except, *end; + int i, n; - body = compiler_new_block(c); - except = compiler_new_block(c); - orelse = compiler_new_block(c); - end = compiler_new_block(c); - if (body == NULL || except == NULL || orelse == NULL || end == NULL) - return 0; - ADDOP_JREL(c, SETUP_EXCEPT, except); - compiler_use_next_block(c, body); - if (!compiler_push_fblock(c, EXCEPT, body)) - return 0; - VISIT_SEQ(c, stmt, s->v.TryExcept.body); - ADDOP(c, POP_BLOCK); - compiler_pop_fblock(c, EXCEPT, body); - ADDOP_JREL(c, JUMP_FORWARD, orelse); - n = asdl_seq_LEN(s->v.TryExcept.handlers); - compiler_use_next_block(c, except); - for (i = 0; i < n; i++) { - excepthandler_ty handler = (excepthandler_ty)asdl_seq_GET( - s->v.TryExcept.handlers, i); - if (!handler->v.ExceptHandler.type && i < n-1) - return compiler_error(c, "default 'except:' must be last"); - c->u->u_lineno_set = 0; - c->u->u_lineno = handler->lineno; - except = compiler_new_block(c); - if (except == NULL) - return 0; - if (handler->v.ExceptHandler.type) { - ADDOP(c, DUP_TOP); - VISIT(c, expr, handler->v.ExceptHandler.type); - ADDOP_I(c, COMPARE_OP, PyCmp_EXC_MATCH); - ADDOP_JABS(c, POP_JUMP_IF_FALSE, except); - } - ADDOP(c, POP_TOP); - if (handler->v.ExceptHandler.name) { - basicblock *cleanup_end, *cleanup_body; - - cleanup_end = compiler_new_block(c); - cleanup_body = compiler_new_block(c); - if(!(cleanup_end || cleanup_body)) - return 0; + body = compiler_new_block(c); + except = compiler_new_block(c); + orelse = compiler_new_block(c); + end = compiler_new_block(c); + if (body == NULL || except == NULL || orelse == NULL || end == NULL) + return 0; + ADDOP_JREL(c, SETUP_EXCEPT, except); + compiler_use_next_block(c, body); + if (!compiler_push_fblock(c, EXCEPT, body)) + return 0; + VISIT_SEQ(c, stmt, s->v.TryExcept.body); + ADDOP(c, POP_BLOCK); + compiler_pop_fblock(c, EXCEPT, body); + ADDOP_JREL(c, JUMP_FORWARD, orelse); + n = asdl_seq_LEN(s->v.TryExcept.handlers); + compiler_use_next_block(c, except); + for (i = 0; i < n; i++) { + excepthandler_ty handler = (excepthandler_ty)asdl_seq_GET( + s->v.TryExcept.handlers, i); + if (!handler->v.ExceptHandler.type && i < n-1) + return compiler_error(c, "default 'except:' must be last"); + c->u->u_lineno_set = 0; + c->u->u_lineno = handler->lineno; + except = compiler_new_block(c); + if (except == NULL) + return 0; + if (handler->v.ExceptHandler.type) { + ADDOP(c, DUP_TOP); + VISIT(c, expr, handler->v.ExceptHandler.type); + ADDOP_I(c, COMPARE_OP, PyCmp_EXC_MATCH); + ADDOP_JABS(c, POP_JUMP_IF_FALSE, except); + } + ADDOP(c, POP_TOP); + if (handler->v.ExceptHandler.name) { + basicblock *cleanup_end, *cleanup_body; - compiler_nameop(c, handler->v.ExceptHandler.name, Store); - ADDOP(c, POP_TOP); + cleanup_end = compiler_new_block(c); + cleanup_body = compiler_new_block(c); + if(!(cleanup_end || cleanup_body)) + return 0; - /* - try: - # body - except type as name: - try: - # body - finally: - name = None - del name - */ - - /* second try: */ - ADDOP_JREL(c, SETUP_FINALLY, cleanup_end); - compiler_use_next_block(c, cleanup_body); - if (!compiler_push_fblock(c, FINALLY_TRY, cleanup_body)) - return 0; - - /* second # body */ - VISIT_SEQ(c, stmt, handler->v.ExceptHandler.body); - ADDOP(c, POP_BLOCK); - ADDOP(c, POP_EXCEPT); - compiler_pop_fblock(c, FINALLY_TRY, cleanup_body); - - /* finally: */ - ADDOP_O(c, LOAD_CONST, Py_None, consts); - compiler_use_next_block(c, cleanup_end); - if (!compiler_push_fblock(c, FINALLY_END, cleanup_end)) - return 0; + compiler_nameop(c, handler->v.ExceptHandler.name, Store); + ADDOP(c, POP_TOP); - /* name = None */ - ADDOP_O(c, LOAD_CONST, Py_None, consts); - compiler_nameop(c, handler->v.ExceptHandler.name, Store); + /* + try: + # body + except type as name: + try: + # body + finally: + name = None + del name + */ + + /* second try: */ + ADDOP_JREL(c, SETUP_FINALLY, cleanup_end); + compiler_use_next_block(c, cleanup_body); + if (!compiler_push_fblock(c, FINALLY_TRY, cleanup_body)) + return 0; + + /* second # body */ + VISIT_SEQ(c, stmt, handler->v.ExceptHandler.body); + ADDOP(c, POP_BLOCK); + ADDOP(c, POP_EXCEPT); + compiler_pop_fblock(c, FINALLY_TRY, cleanup_body); + + /* finally: */ + ADDOP_O(c, LOAD_CONST, Py_None, consts); + compiler_use_next_block(c, cleanup_end); + if (!compiler_push_fblock(c, FINALLY_END, cleanup_end)) + return 0; + + /* name = None */ + ADDOP_O(c, LOAD_CONST, Py_None, consts); + compiler_nameop(c, handler->v.ExceptHandler.name, Store); - /* del name */ - compiler_nameop(c, handler->v.ExceptHandler.name, Del); + /* del name */ + compiler_nameop(c, handler->v.ExceptHandler.name, Del); - ADDOP(c, END_FINALLY); - compiler_pop_fblock(c, FINALLY_END, cleanup_end); - } - else { - basicblock *cleanup_body; + ADDOP(c, END_FINALLY); + compiler_pop_fblock(c, FINALLY_END, cleanup_end); + } + else { + basicblock *cleanup_body; - cleanup_body = compiler_new_block(c); - if(!cleanup_body) - return 0; + cleanup_body = compiler_new_block(c); + if(!cleanup_body) + return 0; - ADDOP(c, POP_TOP); ADDOP(c, POP_TOP); - compiler_use_next_block(c, cleanup_body); - if (!compiler_push_fblock(c, FINALLY_TRY, cleanup_body)) - return 0; - VISIT_SEQ(c, stmt, handler->v.ExceptHandler.body); - ADDOP(c, POP_EXCEPT); - compiler_pop_fblock(c, FINALLY_TRY, cleanup_body); - } - ADDOP_JREL(c, JUMP_FORWARD, end); - compiler_use_next_block(c, except); - } - ADDOP(c, END_FINALLY); - compiler_use_next_block(c, orelse); - VISIT_SEQ(c, stmt, s->v.TryExcept.orelse); - compiler_use_next_block(c, end); - return 1; + ADDOP(c, POP_TOP); + compiler_use_next_block(c, cleanup_body); + if (!compiler_push_fblock(c, FINALLY_TRY, cleanup_body)) + return 0; + VISIT_SEQ(c, stmt, handler->v.ExceptHandler.body); + ADDOP(c, POP_EXCEPT); + compiler_pop_fblock(c, FINALLY_TRY, cleanup_body); + } + ADDOP_JREL(c, JUMP_FORWARD, end); + compiler_use_next_block(c, except); + } + ADDOP(c, END_FINALLY); + compiler_use_next_block(c, orelse); + VISIT_SEQ(c, stmt, s->v.TryExcept.orelse); + compiler_use_next_block(c, end); + return 1; } static int compiler_import_as(struct compiler *c, identifier name, identifier asname) { - /* The IMPORT_NAME opcode was already generated. This function - merely needs to bind the result to a name. + /* The IMPORT_NAME opcode was already generated. This function + merely needs to bind the result to a name. - If there is a dot in name, we need to split it and emit a - LOAD_ATTR for each name. - */ - const Py_UNICODE *src = PyUnicode_AS_UNICODE(name); - const Py_UNICODE *dot = Py_UNICODE_strchr(src, '.'); - if (dot) { - /* Consume the base module name to get the first attribute */ - src = dot + 1; - while (dot) { - /* NB src is only defined when dot != NULL */ - PyObject *attr; - dot = Py_UNICODE_strchr(src, '.'); - attr = PyUnicode_FromUnicode(src, - dot ? dot - src : Py_UNICODE_strlen(src)); - if (!attr) - return -1; - ADDOP_O(c, LOAD_ATTR, attr, names); - Py_DECREF(attr); - src = dot + 1; - } - } - return compiler_nameop(c, asname, Store); + If there is a dot in name, we need to split it and emit a + LOAD_ATTR for each name. + */ + const Py_UNICODE *src = PyUnicode_AS_UNICODE(name); + const Py_UNICODE *dot = Py_UNICODE_strchr(src, '.'); + if (dot) { + /* Consume the base module name to get the first attribute */ + src = dot + 1; + while (dot) { + /* NB src is only defined when dot != NULL */ + PyObject *attr; + dot = Py_UNICODE_strchr(src, '.'); + attr = PyUnicode_FromUnicode(src, + dot ? dot - src : Py_UNICODE_strlen(src)); + if (!attr) + return -1; + ADDOP_O(c, LOAD_ATTR, attr, names); + Py_DECREF(attr); + src = dot + 1; + } + } + return compiler_nameop(c, asname, Store); } static int compiler_import(struct compiler *c, stmt_ty s) { - /* The Import node stores a module name like a.b.c as a single - string. This is convenient for all cases except - import a.b.c as d - where we need to parse that string to extract the individual - module names. - XXX Perhaps change the representation to make this case simpler? - */ - int i, n = asdl_seq_LEN(s->v.Import.names); - - for (i = 0; i < n; i++) { - alias_ty alias = (alias_ty)asdl_seq_GET(s->v.Import.names, i); - int r; - PyObject *level; - - level = PyLong_FromLong(0); - if (level == NULL) - return 0; - - ADDOP_O(c, LOAD_CONST, level, consts); - Py_DECREF(level); - ADDOP_O(c, LOAD_CONST, Py_None, consts); - ADDOP_NAME(c, IMPORT_NAME, alias->name, names); - - if (alias->asname) { - r = compiler_import_as(c, alias->name, alias->asname); - if (!r) - return r; - } - else { - identifier tmp = alias->name; - const Py_UNICODE *base = PyUnicode_AS_UNICODE(alias->name); - Py_UNICODE *dot = Py_UNICODE_strchr(base, '.'); - if (dot) - tmp = PyUnicode_FromUnicode(base, - dot - base); - r = compiler_nameop(c, tmp, Store); - if (dot) { - Py_DECREF(tmp); - } - if (!r) - return r; - } - } - return 1; + /* The Import node stores a module name like a.b.c as a single + string. This is convenient for all cases except + import a.b.c as d + where we need to parse that string to extract the individual + module names. + XXX Perhaps change the representation to make this case simpler? + */ + int i, n = asdl_seq_LEN(s->v.Import.names); + + for (i = 0; i < n; i++) { + alias_ty alias = (alias_ty)asdl_seq_GET(s->v.Import.names, i); + int r; + PyObject *level; + + level = PyLong_FromLong(0); + if (level == NULL) + return 0; + + ADDOP_O(c, LOAD_CONST, level, consts); + Py_DECREF(level); + ADDOP_O(c, LOAD_CONST, Py_None, consts); + ADDOP_NAME(c, IMPORT_NAME, alias->name, names); + + if (alias->asname) { + r = compiler_import_as(c, alias->name, alias->asname); + if (!r) + return r; + } + else { + identifier tmp = alias->name; + const Py_UNICODE *base = PyUnicode_AS_UNICODE(alias->name); + Py_UNICODE *dot = Py_UNICODE_strchr(base, '.'); + if (dot) + tmp = PyUnicode_FromUnicode(base, + dot - base); + r = compiler_nameop(c, tmp, Store); + if (dot) { + Py_DECREF(tmp); + } + if (!r) + return r; + } + } + return 1; } static int compiler_from_import(struct compiler *c, stmt_ty s) { - int i, n = asdl_seq_LEN(s->v.ImportFrom.names); + int i, n = asdl_seq_LEN(s->v.ImportFrom.names); + + PyObject *names = PyTuple_New(n); + PyObject *level; + static PyObject *empty_string; + + if (!empty_string) { + empty_string = PyUnicode_FromString(""); + if (!empty_string) + return 0; + } + + if (!names) + return 0; + + level = PyLong_FromLong(s->v.ImportFrom.level); + if (!level) { + Py_DECREF(names); + return 0; + } - PyObject *names = PyTuple_New(n); - PyObject *level; - static PyObject *empty_string; - - if (!empty_string) { - empty_string = PyUnicode_FromString(""); - if (!empty_string) - return 0; - } - - if (!names) - return 0; - - level = PyLong_FromLong(s->v.ImportFrom.level); - if (!level) { - Py_DECREF(names); - return 0; - } - - /* build up the names */ - for (i = 0; i < n; i++) { - alias_ty alias = (alias_ty)asdl_seq_GET(s->v.ImportFrom.names, i); - Py_INCREF(alias->name); - PyTuple_SET_ITEM(names, i, alias->name); - } - - if (s->lineno > c->c_future->ff_lineno && s->v.ImportFrom.module && - !PyUnicode_CompareWithASCIIString(s->v.ImportFrom.module, "__future__")) { - Py_DECREF(level); - Py_DECREF(names); - return compiler_error(c, "from __future__ imports must occur " - "at the beginning of the file"); - } - - ADDOP_O(c, LOAD_CONST, level, consts); - Py_DECREF(level); - ADDOP_O(c, LOAD_CONST, names, consts); - Py_DECREF(names); - if (s->v.ImportFrom.module) { - ADDOP_NAME(c, IMPORT_NAME, s->v.ImportFrom.module, names); - } - else { - ADDOP_NAME(c, IMPORT_NAME, empty_string, names); - } - for (i = 0; i < n; i++) { - alias_ty alias = (alias_ty)asdl_seq_GET(s->v.ImportFrom.names, i); - identifier store_name; - - if (i == 0 && *PyUnicode_AS_UNICODE(alias->name) == '*') { - assert(n == 1); - ADDOP(c, IMPORT_STAR); - return 1; - } - - ADDOP_NAME(c, IMPORT_FROM, alias->name, names); - store_name = alias->name; - if (alias->asname) - store_name = alias->asname; - - if (!compiler_nameop(c, store_name, Store)) { - Py_DECREF(names); - return 0; - } - } - /* remove imported module */ - ADDOP(c, POP_TOP); - return 1; + /* build up the names */ + for (i = 0; i < n; i++) { + alias_ty alias = (alias_ty)asdl_seq_GET(s->v.ImportFrom.names, i); + Py_INCREF(alias->name); + PyTuple_SET_ITEM(names, i, alias->name); + } + + if (s->lineno > c->c_future->ff_lineno && s->v.ImportFrom.module && + !PyUnicode_CompareWithASCIIString(s->v.ImportFrom.module, "__future__")) { + Py_DECREF(level); + Py_DECREF(names); + return compiler_error(c, "from __future__ imports must occur " + "at the beginning of the file"); + } + + ADDOP_O(c, LOAD_CONST, level, consts); + Py_DECREF(level); + ADDOP_O(c, LOAD_CONST, names, consts); + Py_DECREF(names); + if (s->v.ImportFrom.module) { + ADDOP_NAME(c, IMPORT_NAME, s->v.ImportFrom.module, names); + } + else { + ADDOP_NAME(c, IMPORT_NAME, empty_string, names); + } + for (i = 0; i < n; i++) { + alias_ty alias = (alias_ty)asdl_seq_GET(s->v.ImportFrom.names, i); + identifier store_name; + + if (i == 0 && *PyUnicode_AS_UNICODE(alias->name) == '*') { + assert(n == 1); + ADDOP(c, IMPORT_STAR); + return 1; + } + + ADDOP_NAME(c, IMPORT_FROM, alias->name, names); + store_name = alias->name; + if (alias->asname) + store_name = alias->asname; + + if (!compiler_nameop(c, store_name, Store)) { + Py_DECREF(names); + return 0; + } + } + /* remove imported module */ + ADDOP(c, POP_TOP); + return 1; } static int compiler_assert(struct compiler *c, stmt_ty s) { - static PyObject *assertion_error = NULL; - basicblock *end; + static PyObject *assertion_error = NULL; + basicblock *end; - if (Py_OptimizeFlag) - return 1; - if (assertion_error == NULL) { - assertion_error = PyUnicode_InternFromString("AssertionError"); - if (assertion_error == NULL) - return 0; - } - if (s->v.Assert.test->kind == Tuple_kind && - asdl_seq_LEN(s->v.Assert.test->v.Tuple.elts) > 0) { - const char* msg = - "assertion is always true, perhaps remove parentheses?"; - if (PyErr_WarnExplicit(PyExc_SyntaxWarning, msg, c->c_filename, - c->u->u_lineno, NULL, NULL) == -1) - return 0; - } - VISIT(c, expr, s->v.Assert.test); - end = compiler_new_block(c); - if (end == NULL) - return 0; - ADDOP_JABS(c, POP_JUMP_IF_TRUE, end); - ADDOP_O(c, LOAD_GLOBAL, assertion_error, names); - if (s->v.Assert.msg) { - VISIT(c, expr, s->v.Assert.msg); - ADDOP_I(c, CALL_FUNCTION, 1); - } - ADDOP_I(c, RAISE_VARARGS, 1); - compiler_use_next_block(c, end); - return 1; + if (Py_OptimizeFlag) + return 1; + if (assertion_error == NULL) { + assertion_error = PyUnicode_InternFromString("AssertionError"); + if (assertion_error == NULL) + return 0; + } + if (s->v.Assert.test->kind == Tuple_kind && + asdl_seq_LEN(s->v.Assert.test->v.Tuple.elts) > 0) { + const char* msg = + "assertion is always true, perhaps remove parentheses?"; + if (PyErr_WarnExplicit(PyExc_SyntaxWarning, msg, c->c_filename, + c->u->u_lineno, NULL, NULL) == -1) + return 0; + } + VISIT(c, expr, s->v.Assert.test); + end = compiler_new_block(c); + if (end == NULL) + return 0; + ADDOP_JABS(c, POP_JUMP_IF_TRUE, end); + ADDOP_O(c, LOAD_GLOBAL, assertion_error, names); + if (s->v.Assert.msg) { + VISIT(c, expr, s->v.Assert.msg); + ADDOP_I(c, CALL_FUNCTION, 1); + } + ADDOP_I(c, RAISE_VARARGS, 1); + compiler_use_next_block(c, end); + return 1; } static int compiler_visit_stmt(struct compiler *c, stmt_ty s) { - int i, n; + int i, n; - /* Always assign a lineno to the next instruction for a stmt. */ - c->u->u_lineno = s->lineno; - c->u->u_lineno_set = 0; - - switch (s->kind) { - case FunctionDef_kind: - return compiler_function(c, s); - case ClassDef_kind: - return compiler_class(c, s); - case Return_kind: - if (c->u->u_ste->ste_type != FunctionBlock) - return compiler_error(c, "'return' outside function"); - if (s->v.Return.value) { - VISIT(c, expr, s->v.Return.value); - } - else - ADDOP_O(c, LOAD_CONST, Py_None, consts); - ADDOP(c, RETURN_VALUE); - break; - case Delete_kind: - VISIT_SEQ(c, expr, s->v.Delete.targets) - break; - case Assign_kind: - n = asdl_seq_LEN(s->v.Assign.targets); - VISIT(c, expr, s->v.Assign.value); - for (i = 0; i < n; i++) { - if (i < n - 1) - ADDOP(c, DUP_TOP); - VISIT(c, expr, - (expr_ty)asdl_seq_GET(s->v.Assign.targets, i)); - } - break; - case AugAssign_kind: - return compiler_augassign(c, s); - case For_kind: - return compiler_for(c, s); - case While_kind: - return compiler_while(c, s); - case If_kind: - return compiler_if(c, s); - case Raise_kind: - n = 0; - if (s->v.Raise.exc) { - VISIT(c, expr, s->v.Raise.exc); - n++; - if (s->v.Raise.cause) { - VISIT(c, expr, s->v.Raise.cause); - n++; - } - } - ADDOP_I(c, RAISE_VARARGS, n); - break; - case TryExcept_kind: - return compiler_try_except(c, s); - case TryFinally_kind: - return compiler_try_finally(c, s); - case Assert_kind: - return compiler_assert(c, s); - case Import_kind: - return compiler_import(c, s); - case ImportFrom_kind: - return compiler_from_import(c, s); - case Global_kind: - case Nonlocal_kind: - break; - case Expr_kind: - if (c->c_interactive && c->c_nestlevel <= 1) { - VISIT(c, expr, s->v.Expr.value); - ADDOP(c, PRINT_EXPR); - } - else if (s->v.Expr.value->kind != Str_kind && - s->v.Expr.value->kind != Num_kind) { - VISIT(c, expr, s->v.Expr.value); - ADDOP(c, POP_TOP); - } - break; - case Pass_kind: - break; - case Break_kind: - if (!compiler_in_loop(c)) - return compiler_error(c, "'break' outside loop"); - ADDOP(c, BREAK_LOOP); - break; - case Continue_kind: - return compiler_continue(c); - case With_kind: - return compiler_with(c, s); - } - return 1; + /* Always assign a lineno to the next instruction for a stmt. */ + c->u->u_lineno = s->lineno; + c->u->u_lineno_set = 0; + + switch (s->kind) { + case FunctionDef_kind: + return compiler_function(c, s); + case ClassDef_kind: + return compiler_class(c, s); + case Return_kind: + if (c->u->u_ste->ste_type != FunctionBlock) + return compiler_error(c, "'return' outside function"); + if (s->v.Return.value) { + VISIT(c, expr, s->v.Return.value); + } + else + ADDOP_O(c, LOAD_CONST, Py_None, consts); + ADDOP(c, RETURN_VALUE); + break; + case Delete_kind: + VISIT_SEQ(c, expr, s->v.Delete.targets) + break; + case Assign_kind: + n = asdl_seq_LEN(s->v.Assign.targets); + VISIT(c, expr, s->v.Assign.value); + for (i = 0; i < n; i++) { + if (i < n - 1) + ADDOP(c, DUP_TOP); + VISIT(c, expr, + (expr_ty)asdl_seq_GET(s->v.Assign.targets, i)); + } + break; + case AugAssign_kind: + return compiler_augassign(c, s); + case For_kind: + return compiler_for(c, s); + case While_kind: + return compiler_while(c, s); + case If_kind: + return compiler_if(c, s); + case Raise_kind: + n = 0; + if (s->v.Raise.exc) { + VISIT(c, expr, s->v.Raise.exc); + n++; + if (s->v.Raise.cause) { + VISIT(c, expr, s->v.Raise.cause); + n++; + } + } + ADDOP_I(c, RAISE_VARARGS, n); + break; + case TryExcept_kind: + return compiler_try_except(c, s); + case TryFinally_kind: + return compiler_try_finally(c, s); + case Assert_kind: + return compiler_assert(c, s); + case Import_kind: + return compiler_import(c, s); + case ImportFrom_kind: + return compiler_from_import(c, s); + case Global_kind: + case Nonlocal_kind: + break; + case Expr_kind: + if (c->c_interactive && c->c_nestlevel <= 1) { + VISIT(c, expr, s->v.Expr.value); + ADDOP(c, PRINT_EXPR); + } + else if (s->v.Expr.value->kind != Str_kind && + s->v.Expr.value->kind != Num_kind) { + VISIT(c, expr, s->v.Expr.value); + ADDOP(c, POP_TOP); + } + break; + case Pass_kind: + break; + case Break_kind: + if (!compiler_in_loop(c)) + return compiler_error(c, "'break' outside loop"); + ADDOP(c, BREAK_LOOP); + break; + case Continue_kind: + return compiler_continue(c); + case With_kind: + return compiler_with(c, s); + } + return 1; } static int unaryop(unaryop_ty op) { - switch (op) { - case Invert: - return UNARY_INVERT; - case Not: - return UNARY_NOT; - case UAdd: - return UNARY_POSITIVE; - case USub: - return UNARY_NEGATIVE; - default: - PyErr_Format(PyExc_SystemError, - "unary op %d should not be possible", op); - return 0; - } + switch (op) { + case Invert: + return UNARY_INVERT; + case Not: + return UNARY_NOT; + case UAdd: + return UNARY_POSITIVE; + case USub: + return UNARY_NEGATIVE; + default: + PyErr_Format(PyExc_SystemError, + "unary op %d should not be possible", op); + return 0; + } } static int binop(struct compiler *c, operator_ty op) { - switch (op) { - case Add: - return BINARY_ADD; - case Sub: - return BINARY_SUBTRACT; - case Mult: - return BINARY_MULTIPLY; - case Div: - return BINARY_TRUE_DIVIDE; - case Mod: - return BINARY_MODULO; - case Pow: - return BINARY_POWER; - case LShift: - return BINARY_LSHIFT; - case RShift: - return BINARY_RSHIFT; - case BitOr: - return BINARY_OR; - case BitXor: - return BINARY_XOR; - case BitAnd: - return BINARY_AND; - case FloorDiv: - return BINARY_FLOOR_DIVIDE; - default: - PyErr_Format(PyExc_SystemError, - "binary op %d should not be possible", op); - return 0; - } + switch (op) { + case Add: + return BINARY_ADD; + case Sub: + return BINARY_SUBTRACT; + case Mult: + return BINARY_MULTIPLY; + case Div: + return BINARY_TRUE_DIVIDE; + case Mod: + return BINARY_MODULO; + case Pow: + return BINARY_POWER; + case LShift: + return BINARY_LSHIFT; + case RShift: + return BINARY_RSHIFT; + case BitOr: + return BINARY_OR; + case BitXor: + return BINARY_XOR; + case BitAnd: + return BINARY_AND; + case FloorDiv: + return BINARY_FLOOR_DIVIDE; + default: + PyErr_Format(PyExc_SystemError, + "binary op %d should not be possible", op); + return 0; + } } static int cmpop(cmpop_ty op) { - switch (op) { - case Eq: - return PyCmp_EQ; - case NotEq: - return PyCmp_NE; - case Lt: - return PyCmp_LT; - case LtE: - return PyCmp_LE; - case Gt: - return PyCmp_GT; - case GtE: - return PyCmp_GE; - case Is: - return PyCmp_IS; - case IsNot: - return PyCmp_IS_NOT; - case In: - return PyCmp_IN; - case NotIn: - return PyCmp_NOT_IN; - default: - return PyCmp_BAD; - } + switch (op) { + case Eq: + return PyCmp_EQ; + case NotEq: + return PyCmp_NE; + case Lt: + return PyCmp_LT; + case LtE: + return PyCmp_LE; + case Gt: + return PyCmp_GT; + case GtE: + return PyCmp_GE; + case Is: + return PyCmp_IS; + case IsNot: + return PyCmp_IS_NOT; + case In: + return PyCmp_IN; + case NotIn: + return PyCmp_NOT_IN; + default: + return PyCmp_BAD; + } } static int inplace_binop(struct compiler *c, operator_ty op) { - switch (op) { - case Add: - return INPLACE_ADD; - case Sub: - return INPLACE_SUBTRACT; - case Mult: - return INPLACE_MULTIPLY; - case Div: - return INPLACE_TRUE_DIVIDE; - case Mod: - return INPLACE_MODULO; - case Pow: - return INPLACE_POWER; - case LShift: - return INPLACE_LSHIFT; - case RShift: - return INPLACE_RSHIFT; - case BitOr: - return INPLACE_OR; - case BitXor: - return INPLACE_XOR; - case BitAnd: - return INPLACE_AND; - case FloorDiv: - return INPLACE_FLOOR_DIVIDE; - default: - PyErr_Format(PyExc_SystemError, - "inplace binary op %d should not be possible", op); - return 0; - } + switch (op) { + case Add: + return INPLACE_ADD; + case Sub: + return INPLACE_SUBTRACT; + case Mult: + return INPLACE_MULTIPLY; + case Div: + return INPLACE_TRUE_DIVIDE; + case Mod: + return INPLACE_MODULO; + case Pow: + return INPLACE_POWER; + case LShift: + return INPLACE_LSHIFT; + case RShift: + return INPLACE_RSHIFT; + case BitOr: + return INPLACE_OR; + case BitXor: + return INPLACE_XOR; + case BitAnd: + return INPLACE_AND; + case FloorDiv: + return INPLACE_FLOOR_DIVIDE; + default: + PyErr_Format(PyExc_SystemError, + "inplace binary op %d should not be possible", op); + return 0; + } } static int compiler_nameop(struct compiler *c, identifier name, expr_context_ty ctx) { - int op, scope, arg; - enum { OP_FAST, OP_GLOBAL, OP_DEREF, OP_NAME } optype; + int op, scope, arg; + enum { OP_FAST, OP_GLOBAL, OP_DEREF, OP_NAME } optype; + + PyObject *dict = c->u->u_names; + PyObject *mangled; + /* XXX AugStore isn't used anywhere! */ + + mangled = _Py_Mangle(c->u->u_private, name); + if (!mangled) + return 0; - PyObject *dict = c->u->u_names; - PyObject *mangled; - /* XXX AugStore isn't used anywhere! */ - - mangled = _Py_Mangle(c->u->u_private, name); - if (!mangled) - return 0; - - op = 0; - optype = OP_NAME; - scope = PyST_GetScope(c->u->u_ste, mangled); - switch (scope) { - case FREE: - dict = c->u->u_freevars; - optype = OP_DEREF; - break; - case CELL: - dict = c->u->u_cellvars; - optype = OP_DEREF; - break; - case LOCAL: - if (c->u->u_ste->ste_type == FunctionBlock) - optype = OP_FAST; - break; - case GLOBAL_IMPLICIT: - if (c->u->u_ste->ste_type == FunctionBlock && - !c->u->u_ste->ste_unoptimized) - optype = OP_GLOBAL; - break; - case GLOBAL_EXPLICIT: - optype = OP_GLOBAL; - break; - default: - /* scope can be 0 */ - break; - } - - /* XXX Leave assert here, but handle __doc__ and the like better */ - assert(scope || PyUnicode_AS_UNICODE(name)[0] == '_'); - - switch (optype) { - case OP_DEREF: - switch (ctx) { - case Load: op = LOAD_DEREF; break; - case Store: op = STORE_DEREF; break; - case AugLoad: - case AugStore: - break; - case Del: - PyErr_Format(PyExc_SyntaxError, - "can not delete variable '%S' referenced " - "in nested scope", - name); - Py_DECREF(mangled); - return 0; - case Param: - default: - PyErr_SetString(PyExc_SystemError, - "param invalid for deref variable"); - return 0; - } - break; - case OP_FAST: - switch (ctx) { - case Load: op = LOAD_FAST; break; - case Store: op = STORE_FAST; break; - case Del: op = DELETE_FAST; break; - case AugLoad: - case AugStore: - break; - case Param: - default: - PyErr_SetString(PyExc_SystemError, - "param invalid for local variable"); - return 0; - } - ADDOP_O(c, op, mangled, varnames); - Py_DECREF(mangled); - return 1; - case OP_GLOBAL: - switch (ctx) { - case Load: op = LOAD_GLOBAL; break; - case Store: op = STORE_GLOBAL; break; - case Del: op = DELETE_GLOBAL; break; - case AugLoad: - case AugStore: - break; - case Param: - default: - PyErr_SetString(PyExc_SystemError, - "param invalid for global variable"); - return 0; - } - break; - case OP_NAME: - switch (ctx) { - case Load: op = LOAD_NAME; break; - case Store: op = STORE_NAME; break; - case Del: op = DELETE_NAME; break; - case AugLoad: - case AugStore: - break; - case Param: - default: - PyErr_SetString(PyExc_SystemError, - "param invalid for name variable"); - return 0; - } - break; - } - - assert(op); - arg = compiler_add_o(c, dict, mangled); - Py_DECREF(mangled); - if (arg < 0) - return 0; - return compiler_addop_i(c, op, arg); + op = 0; + optype = OP_NAME; + scope = PyST_GetScope(c->u->u_ste, mangled); + switch (scope) { + case FREE: + dict = c->u->u_freevars; + optype = OP_DEREF; + break; + case CELL: + dict = c->u->u_cellvars; + optype = OP_DEREF; + break; + case LOCAL: + if (c->u->u_ste->ste_type == FunctionBlock) + optype = OP_FAST; + break; + case GLOBAL_IMPLICIT: + if (c->u->u_ste->ste_type == FunctionBlock && + !c->u->u_ste->ste_unoptimized) + optype = OP_GLOBAL; + break; + case GLOBAL_EXPLICIT: + optype = OP_GLOBAL; + break; + default: + /* scope can be 0 */ + break; + } + + /* XXX Leave assert here, but handle __doc__ and the like better */ + assert(scope || PyUnicode_AS_UNICODE(name)[0] == '_'); + + switch (optype) { + case OP_DEREF: + switch (ctx) { + case Load: op = LOAD_DEREF; break; + case Store: op = STORE_DEREF; break; + case AugLoad: + case AugStore: + break; + case Del: + PyErr_Format(PyExc_SyntaxError, + "can not delete variable '%S' referenced " + "in nested scope", + name); + Py_DECREF(mangled); + return 0; + case Param: + default: + PyErr_SetString(PyExc_SystemError, + "param invalid for deref variable"); + return 0; + } + break; + case OP_FAST: + switch (ctx) { + case Load: op = LOAD_FAST; break; + case Store: op = STORE_FAST; break; + case Del: op = DELETE_FAST; break; + case AugLoad: + case AugStore: + break; + case Param: + default: + PyErr_SetString(PyExc_SystemError, + "param invalid for local variable"); + return 0; + } + ADDOP_O(c, op, mangled, varnames); + Py_DECREF(mangled); + return 1; + case OP_GLOBAL: + switch (ctx) { + case Load: op = LOAD_GLOBAL; break; + case Store: op = STORE_GLOBAL; break; + case Del: op = DELETE_GLOBAL; break; + case AugLoad: + case AugStore: + break; + case Param: + default: + PyErr_SetString(PyExc_SystemError, + "param invalid for global variable"); + return 0; + } + break; + case OP_NAME: + switch (ctx) { + case Load: op = LOAD_NAME; break; + case Store: op = STORE_NAME; break; + case Del: op = DELETE_NAME; break; + case AugLoad: + case AugStore: + break; + case Param: + default: + PyErr_SetString(PyExc_SystemError, + "param invalid for name variable"); + return 0; + } + break; + } + + assert(op); + arg = compiler_add_o(c, dict, mangled); + Py_DECREF(mangled); + if (arg < 0) + return 0; + return compiler_addop_i(c, op, arg); } static int compiler_boolop(struct compiler *c, expr_ty e) { - basicblock *end; - int jumpi, i, n; - asdl_seq *s; - - assert(e->kind == BoolOp_kind); - if (e->v.BoolOp.op == And) - jumpi = JUMP_IF_FALSE_OR_POP; - else - jumpi = JUMP_IF_TRUE_OR_POP; - end = compiler_new_block(c); - if (end == NULL) - return 0; - s = e->v.BoolOp.values; - n = asdl_seq_LEN(s) - 1; - assert(n >= 0); - for (i = 0; i < n; ++i) { - VISIT(c, expr, (expr_ty)asdl_seq_GET(s, i)); - ADDOP_JABS(c, jumpi, end); - } - VISIT(c, expr, (expr_ty)asdl_seq_GET(s, n)); - compiler_use_next_block(c, end); - return 1; + basicblock *end; + int jumpi, i, n; + asdl_seq *s; + + assert(e->kind == BoolOp_kind); + if (e->v.BoolOp.op == And) + jumpi = JUMP_IF_FALSE_OR_POP; + else + jumpi = JUMP_IF_TRUE_OR_POP; + end = compiler_new_block(c); + if (end == NULL) + return 0; + s = e->v.BoolOp.values; + n = asdl_seq_LEN(s) - 1; + assert(n >= 0); + for (i = 0; i < n; ++i) { + VISIT(c, expr, (expr_ty)asdl_seq_GET(s, i)); + ADDOP_JABS(c, jumpi, end); + } + VISIT(c, expr, (expr_ty)asdl_seq_GET(s, n)); + compiler_use_next_block(c, end); + return 1; } static int compiler_list(struct compiler *c, expr_ty e) { - int n = asdl_seq_LEN(e->v.List.elts); - if (e->v.List.ctx == Store) { - int i, seen_star = 0; - for (i = 0; i < n; i++) { - expr_ty elt = asdl_seq_GET(e->v.List.elts, i); - if (elt->kind == Starred_kind && !seen_star) { - if ((i >= (1 << 8)) || - (n-i-1 >= (INT_MAX >> 8))) - return compiler_error(c, - "too many expressions in " - "star-unpacking assignment"); - ADDOP_I(c, UNPACK_EX, (i + ((n-i-1) << 8))); - seen_star = 1; - asdl_seq_SET(e->v.List.elts, i, elt->v.Starred.value); - } else if (elt->kind == Starred_kind) { - return compiler_error(c, - "two starred expressions in assignment"); - } - } - if (!seen_star) { - ADDOP_I(c, UNPACK_SEQUENCE, n); - } - } - VISIT_SEQ(c, expr, e->v.List.elts); - if (e->v.List.ctx == Load) { - ADDOP_I(c, BUILD_LIST, n); - } - return 1; + int n = asdl_seq_LEN(e->v.List.elts); + if (e->v.List.ctx == Store) { + int i, seen_star = 0; + for (i = 0; i < n; i++) { + expr_ty elt = asdl_seq_GET(e->v.List.elts, i); + if (elt->kind == Starred_kind && !seen_star) { + if ((i >= (1 << 8)) || + (n-i-1 >= (INT_MAX >> 8))) + return compiler_error(c, + "too many expressions in " + "star-unpacking assignment"); + ADDOP_I(c, UNPACK_EX, (i + ((n-i-1) << 8))); + seen_star = 1; + asdl_seq_SET(e->v.List.elts, i, elt->v.Starred.value); + } else if (elt->kind == Starred_kind) { + return compiler_error(c, + "two starred expressions in assignment"); + } + } + if (!seen_star) { + ADDOP_I(c, UNPACK_SEQUENCE, n); + } + } + VISIT_SEQ(c, expr, e->v.List.elts); + if (e->v.List.ctx == Load) { + ADDOP_I(c, BUILD_LIST, n); + } + return 1; } static int compiler_tuple(struct compiler *c, expr_ty e) { - int n = asdl_seq_LEN(e->v.Tuple.elts); - if (e->v.Tuple.ctx == Store) { - int i, seen_star = 0; - for (i = 0; i < n; i++) { - expr_ty elt = asdl_seq_GET(e->v.Tuple.elts, i); - if (elt->kind == Starred_kind && !seen_star) { - if ((i >= (1 << 8)) || - (n-i-1 >= (INT_MAX >> 8))) - return compiler_error(c, - "too many expressions in " - "star-unpacking assignment"); - ADDOP_I(c, UNPACK_EX, (i + ((n-i-1) << 8))); - seen_star = 1; - asdl_seq_SET(e->v.Tuple.elts, i, elt->v.Starred.value); - } else if (elt->kind == Starred_kind) { - return compiler_error(c, - "two starred expressions in assignment"); - } - } - if (!seen_star) { - ADDOP_I(c, UNPACK_SEQUENCE, n); - } - } - VISIT_SEQ(c, expr, e->v.Tuple.elts); - if (e->v.Tuple.ctx == Load) { - ADDOP_I(c, BUILD_TUPLE, n); - } - return 1; + int n = asdl_seq_LEN(e->v.Tuple.elts); + if (e->v.Tuple.ctx == Store) { + int i, seen_star = 0; + for (i = 0; i < n; i++) { + expr_ty elt = asdl_seq_GET(e->v.Tuple.elts, i); + if (elt->kind == Starred_kind && !seen_star) { + if ((i >= (1 << 8)) || + (n-i-1 >= (INT_MAX >> 8))) + return compiler_error(c, + "too many expressions in " + "star-unpacking assignment"); + ADDOP_I(c, UNPACK_EX, (i + ((n-i-1) << 8))); + seen_star = 1; + asdl_seq_SET(e->v.Tuple.elts, i, elt->v.Starred.value); + } else if (elt->kind == Starred_kind) { + return compiler_error(c, + "two starred expressions in assignment"); + } + } + if (!seen_star) { + ADDOP_I(c, UNPACK_SEQUENCE, n); + } + } + VISIT_SEQ(c, expr, e->v.Tuple.elts); + if (e->v.Tuple.ctx == Load) { + ADDOP_I(c, BUILD_TUPLE, n); + } + return 1; } static int compiler_compare(struct compiler *c, expr_ty e) { - int i, n; - basicblock *cleanup = NULL; + int i, n; + basicblock *cleanup = NULL; - /* XXX the logic can be cleaned up for 1 or multiple comparisons */ - VISIT(c, expr, e->v.Compare.left); - n = asdl_seq_LEN(e->v.Compare.ops); - assert(n > 0); - if (n > 1) { - cleanup = compiler_new_block(c); - if (cleanup == NULL) - return 0; - VISIT(c, expr, - (expr_ty)asdl_seq_GET(e->v.Compare.comparators, 0)); - } - for (i = 1; i < n; i++) { - ADDOP(c, DUP_TOP); - ADDOP(c, ROT_THREE); - ADDOP_I(c, COMPARE_OP, - cmpop((cmpop_ty)(asdl_seq_GET( - e->v.Compare.ops, i - 1)))); - ADDOP_JABS(c, JUMP_IF_FALSE_OR_POP, cleanup); - NEXT_BLOCK(c); - if (i < (n - 1)) - VISIT(c, expr, - (expr_ty)asdl_seq_GET(e->v.Compare.comparators, i)); - } - VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Compare.comparators, n - 1)); - ADDOP_I(c, COMPARE_OP, - cmpop((cmpop_ty)(asdl_seq_GET(e->v.Compare.ops, n - 1)))); - if (n > 1) { - basicblock *end = compiler_new_block(c); - if (end == NULL) - return 0; - ADDOP_JREL(c, JUMP_FORWARD, end); - compiler_use_next_block(c, cleanup); - ADDOP(c, ROT_TWO); - ADDOP(c, POP_TOP); - compiler_use_next_block(c, end); - } - return 1; + /* XXX the logic can be cleaned up for 1 or multiple comparisons */ + VISIT(c, expr, e->v.Compare.left); + n = asdl_seq_LEN(e->v.Compare.ops); + assert(n > 0); + if (n > 1) { + cleanup = compiler_new_block(c); + if (cleanup == NULL) + return 0; + VISIT(c, expr, + (expr_ty)asdl_seq_GET(e->v.Compare.comparators, 0)); + } + for (i = 1; i < n; i++) { + ADDOP(c, DUP_TOP); + ADDOP(c, ROT_THREE); + ADDOP_I(c, COMPARE_OP, + cmpop((cmpop_ty)(asdl_seq_GET( + e->v.Compare.ops, i - 1)))); + ADDOP_JABS(c, JUMP_IF_FALSE_OR_POP, cleanup); + NEXT_BLOCK(c); + if (i < (n - 1)) + VISIT(c, expr, + (expr_ty)asdl_seq_GET(e->v.Compare.comparators, i)); + } + VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Compare.comparators, n - 1)); + ADDOP_I(c, COMPARE_OP, + cmpop((cmpop_ty)(asdl_seq_GET(e->v.Compare.ops, n - 1)))); + if (n > 1) { + basicblock *end = compiler_new_block(c); + if (end == NULL) + return 0; + ADDOP_JREL(c, JUMP_FORWARD, end); + compiler_use_next_block(c, cleanup); + ADDOP(c, ROT_TWO); + ADDOP(c, POP_TOP); + compiler_use_next_block(c, end); + } + return 1; } static int compiler_call(struct compiler *c, expr_ty e) { - VISIT(c, expr, e->v.Call.func); - return compiler_call_helper(c, 0, - e->v.Call.args, - e->v.Call.keywords, - e->v.Call.starargs, - e->v.Call.kwargs); + VISIT(c, expr, e->v.Call.func); + return compiler_call_helper(c, 0, + e->v.Call.args, + e->v.Call.keywords, + e->v.Call.starargs, + e->v.Call.kwargs); } /* shared code between compiler_call and compiler_class */ static int compiler_call_helper(struct compiler *c, - int n, /* Args already pushed */ - asdl_seq *args, - asdl_seq *keywords, - expr_ty starargs, - expr_ty kwargs) -{ - int code = 0; - - n += asdl_seq_LEN(args); - VISIT_SEQ(c, expr, args); - if (keywords) { - VISIT_SEQ(c, keyword, keywords); - n |= asdl_seq_LEN(keywords) << 8; - } - if (starargs) { - VISIT(c, expr, starargs); - code |= 1; - } - if (kwargs) { - VISIT(c, expr, kwargs); - code |= 2; - } - switch (code) { - case 0: - ADDOP_I(c, CALL_FUNCTION, n); - break; - case 1: - ADDOP_I(c, CALL_FUNCTION_VAR, n); - break; - case 2: - ADDOP_I(c, CALL_FUNCTION_KW, n); - break; - case 3: - ADDOP_I(c, CALL_FUNCTION_VAR_KW, n); - break; - } - return 1; + int n, /* Args already pushed */ + asdl_seq *args, + asdl_seq *keywords, + expr_ty starargs, + expr_ty kwargs) +{ + int code = 0; + + n += asdl_seq_LEN(args); + VISIT_SEQ(c, expr, args); + if (keywords) { + VISIT_SEQ(c, keyword, keywords); + n |= asdl_seq_LEN(keywords) << 8; + } + if (starargs) { + VISIT(c, expr, starargs); + code |= 1; + } + if (kwargs) { + VISIT(c, expr, kwargs); + code |= 2; + } + switch (code) { + case 0: + ADDOP_I(c, CALL_FUNCTION, n); + break; + case 1: + ADDOP_I(c, CALL_FUNCTION_VAR, n); + break; + case 2: + ADDOP_I(c, CALL_FUNCTION_KW, n); + break; + case 3: + ADDOP_I(c, CALL_FUNCTION_VAR_KW, n); + break; + } + return 1; } @@ -2787,228 +2787,228 @@ */ static int -compiler_comprehension_generator(struct compiler *c, - asdl_seq *generators, int gen_index, - expr_ty elt, expr_ty val, int type) -{ - /* generate code for the iterator, then each of the ifs, - and then write to the element */ - - comprehension_ty gen; - basicblock *start, *anchor, *skip, *if_cleanup; - int i, n; - - start = compiler_new_block(c); - skip = compiler_new_block(c); - if_cleanup = compiler_new_block(c); - anchor = compiler_new_block(c); - - if (start == NULL || skip == NULL || if_cleanup == NULL || - anchor == NULL) - return 0; - - gen = (comprehension_ty)asdl_seq_GET(generators, gen_index); - - if (gen_index == 0) { - /* Receive outermost iter as an implicit argument */ - c->u->u_argcount = 1; - ADDOP_I(c, LOAD_FAST, 0); - } - else { - /* Sub-iter - calculate on the fly */ - VISIT(c, expr, gen->iter); - ADDOP(c, GET_ITER); - } - compiler_use_next_block(c, start); - ADDOP_JREL(c, FOR_ITER, anchor); - NEXT_BLOCK(c); - VISIT(c, expr, gen->target); - - /* XXX this needs to be cleaned up...a lot! */ - n = asdl_seq_LEN(gen->ifs); - for (i = 0; i < n; i++) { - expr_ty e = (expr_ty)asdl_seq_GET(gen->ifs, i); - VISIT(c, expr, e); - ADDOP_JABS(c, POP_JUMP_IF_FALSE, if_cleanup); - NEXT_BLOCK(c); - } - - if (++gen_index < asdl_seq_LEN(generators)) - if (!compiler_comprehension_generator(c, - generators, gen_index, - elt, val, type)) - return 0; - - /* only append after the last for generator */ - if (gen_index >= asdl_seq_LEN(generators)) { - /* comprehension specific code */ - switch (type) { - case COMP_GENEXP: - VISIT(c, expr, elt); - ADDOP(c, YIELD_VALUE); - ADDOP(c, POP_TOP); - break; - case COMP_LISTCOMP: - VISIT(c, expr, elt); - ADDOP_I(c, LIST_APPEND, gen_index + 1); - break; - case COMP_SETCOMP: - VISIT(c, expr, elt); - ADDOP_I(c, SET_ADD, gen_index + 1); - break; - case COMP_DICTCOMP: - /* With 'd[k] = v', v is evaluated before k, so we do - the same. */ - VISIT(c, expr, val); - VISIT(c, expr, elt); - ADDOP_I(c, MAP_ADD, gen_index + 1); - break; - default: - return 0; - } - - compiler_use_next_block(c, skip); - } - compiler_use_next_block(c, if_cleanup); - ADDOP_JABS(c, JUMP_ABSOLUTE, start); - compiler_use_next_block(c, anchor); +compiler_comprehension_generator(struct compiler *c, + asdl_seq *generators, int gen_index, + expr_ty elt, expr_ty val, int type) +{ + /* generate code for the iterator, then each of the ifs, + and then write to the element */ + + comprehension_ty gen; + basicblock *start, *anchor, *skip, *if_cleanup; + int i, n; + + start = compiler_new_block(c); + skip = compiler_new_block(c); + if_cleanup = compiler_new_block(c); + anchor = compiler_new_block(c); + + if (start == NULL || skip == NULL || if_cleanup == NULL || + anchor == NULL) + return 0; + + gen = (comprehension_ty)asdl_seq_GET(generators, gen_index); + + if (gen_index == 0) { + /* Receive outermost iter as an implicit argument */ + c->u->u_argcount = 1; + ADDOP_I(c, LOAD_FAST, 0); + } + else { + /* Sub-iter - calculate on the fly */ + VISIT(c, expr, gen->iter); + ADDOP(c, GET_ITER); + } + compiler_use_next_block(c, start); + ADDOP_JREL(c, FOR_ITER, anchor); + NEXT_BLOCK(c); + VISIT(c, expr, gen->target); + + /* XXX this needs to be cleaned up...a lot! */ + n = asdl_seq_LEN(gen->ifs); + for (i = 0; i < n; i++) { + expr_ty e = (expr_ty)asdl_seq_GET(gen->ifs, i); + VISIT(c, expr, e); + ADDOP_JABS(c, POP_JUMP_IF_FALSE, if_cleanup); + NEXT_BLOCK(c); + } + + if (++gen_index < asdl_seq_LEN(generators)) + if (!compiler_comprehension_generator(c, + generators, gen_index, + elt, val, type)) + return 0; + + /* only append after the last for generator */ + if (gen_index >= asdl_seq_LEN(generators)) { + /* comprehension specific code */ + switch (type) { + case COMP_GENEXP: + VISIT(c, expr, elt); + ADDOP(c, YIELD_VALUE); + ADDOP(c, POP_TOP); + break; + case COMP_LISTCOMP: + VISIT(c, expr, elt); + ADDOP_I(c, LIST_APPEND, gen_index + 1); + break; + case COMP_SETCOMP: + VISIT(c, expr, elt); + ADDOP_I(c, SET_ADD, gen_index + 1); + break; + case COMP_DICTCOMP: + /* With 'd[k] = v', v is evaluated before k, so we do + the same. */ + VISIT(c, expr, val); + VISIT(c, expr, elt); + ADDOP_I(c, MAP_ADD, gen_index + 1); + break; + default: + return 0; + } + + compiler_use_next_block(c, skip); + } + compiler_use_next_block(c, if_cleanup); + ADDOP_JABS(c, JUMP_ABSOLUTE, start); + compiler_use_next_block(c, anchor); - return 1; + return 1; } static int compiler_comprehension(struct compiler *c, expr_ty e, int type, identifier name, - asdl_seq *generators, expr_ty elt, expr_ty val) + asdl_seq *generators, expr_ty elt, expr_ty val) { - PyCodeObject *co = NULL; - expr_ty outermost_iter; + PyCodeObject *co = NULL; + expr_ty outermost_iter; + + outermost_iter = ((comprehension_ty) + asdl_seq_GET(generators, 0))->iter; - outermost_iter = ((comprehension_ty) - asdl_seq_GET(generators, 0))->iter; + if (!compiler_enter_scope(c, name, (void *)e, e->lineno)) + goto error; + + if (type != COMP_GENEXP) { + int op; + switch (type) { + case COMP_LISTCOMP: + op = BUILD_LIST; + break; + case COMP_SETCOMP: + op = BUILD_SET; + break; + case COMP_DICTCOMP: + op = BUILD_MAP; + break; + default: + PyErr_Format(PyExc_SystemError, + "unknown comprehension type %d", type); + goto error_in_scope; + } + + ADDOP_I(c, op, 0); + } - if (!compiler_enter_scope(c, name, (void *)e, e->lineno)) - goto error; - - if (type != COMP_GENEXP) { - int op; - switch (type) { - case COMP_LISTCOMP: - op = BUILD_LIST; - break; - case COMP_SETCOMP: - op = BUILD_SET; - break; - case COMP_DICTCOMP: - op = BUILD_MAP; - break; - default: - PyErr_Format(PyExc_SystemError, - "unknown comprehension type %d", type); - goto error_in_scope; - } - - ADDOP_I(c, op, 0); - } - - if (!compiler_comprehension_generator(c, generators, 0, elt, - val, type)) - goto error_in_scope; - - if (type != COMP_GENEXP) { - ADDOP(c, RETURN_VALUE); - } - - co = assemble(c, 1); - compiler_exit_scope(c); - if (co == NULL) - goto error; - - if (!compiler_make_closure(c, co, 0)) - goto error; - Py_DECREF(co); - - VISIT(c, expr, outermost_iter); - ADDOP(c, GET_ITER); - ADDOP_I(c, CALL_FUNCTION, 1); - return 1; + if (!compiler_comprehension_generator(c, generators, 0, elt, + val, type)) + goto error_in_scope; + + if (type != COMP_GENEXP) { + ADDOP(c, RETURN_VALUE); + } + + co = assemble(c, 1); + compiler_exit_scope(c); + if (co == NULL) + goto error; + + if (!compiler_make_closure(c, co, 0)) + goto error; + Py_DECREF(co); + + VISIT(c, expr, outermost_iter); + ADDOP(c, GET_ITER); + ADDOP_I(c, CALL_FUNCTION, 1); + return 1; error_in_scope: - compiler_exit_scope(c); + compiler_exit_scope(c); error: - Py_XDECREF(co); - return 0; + Py_XDECREF(co); + return 0; } static int compiler_genexp(struct compiler *c, expr_ty e) { - static identifier name; - if (!name) { - name = PyUnicode_FromString(""); - if (!name) - return 0; - } - assert(e->kind == GeneratorExp_kind); - return compiler_comprehension(c, e, COMP_GENEXP, name, - e->v.GeneratorExp.generators, - e->v.GeneratorExp.elt, NULL); + static identifier name; + if (!name) { + name = PyUnicode_FromString(""); + if (!name) + return 0; + } + assert(e->kind == GeneratorExp_kind); + return compiler_comprehension(c, e, COMP_GENEXP, name, + e->v.GeneratorExp.generators, + e->v.GeneratorExp.elt, NULL); } static int compiler_listcomp(struct compiler *c, expr_ty e) { - static identifier name; - if (!name) { - name = PyUnicode_FromString(""); - if (!name) - return 0; - } - assert(e->kind == ListComp_kind); - return compiler_comprehension(c, e, COMP_LISTCOMP, name, - e->v.ListComp.generators, - e->v.ListComp.elt, NULL); + static identifier name; + if (!name) { + name = PyUnicode_FromString(""); + if (!name) + return 0; + } + assert(e->kind == ListComp_kind); + return compiler_comprehension(c, e, COMP_LISTCOMP, name, + e->v.ListComp.generators, + e->v.ListComp.elt, NULL); } static int compiler_setcomp(struct compiler *c, expr_ty e) { - static identifier name; - if (!name) { - name = PyUnicode_FromString(""); - if (!name) - return 0; - } - assert(e->kind == SetComp_kind); - return compiler_comprehension(c, e, COMP_SETCOMP, name, - e->v.SetComp.generators, - e->v.SetComp.elt, NULL); + static identifier name; + if (!name) { + name = PyUnicode_FromString(""); + if (!name) + return 0; + } + assert(e->kind == SetComp_kind); + return compiler_comprehension(c, e, COMP_SETCOMP, name, + e->v.SetComp.generators, + e->v.SetComp.elt, NULL); } static int compiler_dictcomp(struct compiler *c, expr_ty e) { - static identifier name; - if (!name) { - name = PyUnicode_FromString(""); - if (!name) - return 0; - } - assert(e->kind == DictComp_kind); - return compiler_comprehension(c, e, COMP_DICTCOMP, name, - e->v.DictComp.generators, - e->v.DictComp.key, e->v.DictComp.value); + static identifier name; + if (!name) { + name = PyUnicode_FromString(""); + if (!name) + return 0; + } + assert(e->kind == DictComp_kind); + return compiler_comprehension(c, e, COMP_DICTCOMP, name, + e->v.DictComp.generators, + e->v.DictComp.key, e->v.DictComp.value); } static int compiler_visit_keyword(struct compiler *c, keyword_ty k) { - ADDOP_O(c, LOAD_CONST, k->arg, consts); - VISIT(c, expr, k->value); - return 1; + ADDOP_O(c, LOAD_CONST, k->arg, consts); + VISIT(c, expr, k->value); + return 1; } -/* Test whether expression is constant. For constants, report +/* Test whether expression is constant. For constants, report whether they are true or false. Return values: 1 for true, 0 for false, -1 for non-constant. @@ -3017,39 +3017,39 @@ static int expr_constant(expr_ty e) { - char *id; - switch (e->kind) { - case Ellipsis_kind: - return 1; - case Num_kind: - return PyObject_IsTrue(e->v.Num.n); - case Str_kind: - return PyObject_IsTrue(e->v.Str.s); - case Name_kind: - /* optimize away names that can't be reassigned */ - id = PyBytes_AS_STRING( - _PyUnicode_AsDefaultEncodedString(e->v.Name.id, NULL)); - if (strcmp(id, "True") == 0) return 1; - if (strcmp(id, "False") == 0) return 0; - if (strcmp(id, "None") == 0) return 0; - if (strcmp(id, "__debug__") == 0) - return ! Py_OptimizeFlag; - /* fall through */ - default: - return -1; - } + char *id; + switch (e->kind) { + case Ellipsis_kind: + return 1; + case Num_kind: + return PyObject_IsTrue(e->v.Num.n); + case Str_kind: + return PyObject_IsTrue(e->v.Str.s); + case Name_kind: + /* optimize away names that can't be reassigned */ + id = PyBytes_AS_STRING( + _PyUnicode_AsDefaultEncodedString(e->v.Name.id, NULL)); + if (strcmp(id, "True") == 0) return 1; + if (strcmp(id, "False") == 0) return 0; + if (strcmp(id, "None") == 0) return 0; + if (strcmp(id, "__debug__") == 0) + return ! Py_OptimizeFlag; + /* fall through */ + default: + return -1; + } } /* Implements the with statement from PEP 343. - The semantics outlined in that PEP are as follows: + The semantics outlined in that PEP are as follows: with EXPR as VAR: BLOCK - + It is implemented roughly as: - + context = EXPR exit = context.__exit__ # not calling it value = context.__enter__() @@ -3058,9 +3058,9 @@ BLOCK finally: if an exception was raised: - exc = copy of (exception, instance, traceback) + exc = copy of (exception, instance, traceback) else: - exc = (None, None, None) + exc = (None, None, None) exit(*exc) */ static int @@ -3073,7 +3073,7 @@ block = compiler_new_block(c); finally = compiler_new_block(c); if (!block || !finally) - return 0; + return 0; /* Evaluate EXPR */ VISIT(c, expr, s->v.With.context_expr); @@ -3082,15 +3082,15 @@ /* SETUP_WITH pushes a finally block. */ compiler_use_next_block(c, block); if (!compiler_push_fblock(c, FINALLY_TRY, block)) { - return 0; + return 0; } if (s->v.With.optional_vars) { - VISIT(c, expr, s->v.With.optional_vars); + VISIT(c, expr, s->v.With.optional_vars); } else { - /* Discard result from context.__enter__() */ - ADDOP(c, POP_TOP); + /* Discard result from context.__enter__() */ + ADDOP(c, POP_TOP); } /* BLOCK code */ @@ -3103,7 +3103,7 @@ ADDOP_O(c, LOAD_CONST, Py_None, consts); compiler_use_next_block(c, finally); if (!compiler_push_fblock(c, FINALLY_END, finally)) - return 0; + return 0; /* Finally block starts; context.__exit__ is on the stack under the exception or return information. Just issue our magic @@ -3119,240 +3119,240 @@ static int compiler_visit_expr(struct compiler *c, expr_ty e) { - int i, n; + int i, n; - /* If expr e has a different line number than the last expr/stmt, - set a new line number for the next instruction. - */ - if (e->lineno > c->u->u_lineno) { - c->u->u_lineno = e->lineno; - c->u->u_lineno_set = 0; - } - switch (e->kind) { - case BoolOp_kind: - return compiler_boolop(c, e); - case BinOp_kind: - VISIT(c, expr, e->v.BinOp.left); - VISIT(c, expr, e->v.BinOp.right); - ADDOP(c, binop(c, e->v.BinOp.op)); - break; - case UnaryOp_kind: - VISIT(c, expr, e->v.UnaryOp.operand); - ADDOP(c, unaryop(e->v.UnaryOp.op)); - break; - case Lambda_kind: - return compiler_lambda(c, e); - case IfExp_kind: - return compiler_ifexp(c, e); - case Dict_kind: - n = asdl_seq_LEN(e->v.Dict.values); - ADDOP_I(c, BUILD_MAP, (n>0xFFFF ? 0xFFFF : n)); - for (i = 0; i < n; i++) { - VISIT(c, expr, - (expr_ty)asdl_seq_GET(e->v.Dict.values, i)); - VISIT(c, expr, - (expr_ty)asdl_seq_GET(e->v.Dict.keys, i)); - ADDOP(c, STORE_MAP); - } - break; - case Set_kind: - n = asdl_seq_LEN(e->v.Set.elts); - VISIT_SEQ(c, expr, e->v.Set.elts); - ADDOP_I(c, BUILD_SET, n); - break; - case GeneratorExp_kind: - return compiler_genexp(c, e); - case ListComp_kind: - return compiler_listcomp(c, e); - case SetComp_kind: - return compiler_setcomp(c, e); - case DictComp_kind: - return compiler_dictcomp(c, e); - case Yield_kind: - if (c->u->u_ste->ste_type != FunctionBlock) - return compiler_error(c, "'yield' outside function"); - if (e->v.Yield.value) { - VISIT(c, expr, e->v.Yield.value); - } - else { - ADDOP_O(c, LOAD_CONST, Py_None, consts); - } - ADDOP(c, YIELD_VALUE); - break; - case Compare_kind: - return compiler_compare(c, e); - case Call_kind: - return compiler_call(c, e); - case Num_kind: - ADDOP_O(c, LOAD_CONST, e->v.Num.n, consts); - break; - case Str_kind: - ADDOP_O(c, LOAD_CONST, e->v.Str.s, consts); - break; - case Bytes_kind: - ADDOP_O(c, LOAD_CONST, e->v.Bytes.s, consts); - break; - case Ellipsis_kind: - ADDOP_O(c, LOAD_CONST, Py_Ellipsis, consts); - break; - /* The following exprs can be assignment targets. */ - case Attribute_kind: - if (e->v.Attribute.ctx != AugStore) - VISIT(c, expr, e->v.Attribute.value); - switch (e->v.Attribute.ctx) { - case AugLoad: - ADDOP(c, DUP_TOP); - /* Fall through to load */ - case Load: - ADDOP_NAME(c, LOAD_ATTR, e->v.Attribute.attr, names); - break; - case AugStore: - ADDOP(c, ROT_TWO); - /* Fall through to save */ - case Store: - ADDOP_NAME(c, STORE_ATTR, e->v.Attribute.attr, names); - break; - case Del: - ADDOP_NAME(c, DELETE_ATTR, e->v.Attribute.attr, names); - break; - case Param: - default: - PyErr_SetString(PyExc_SystemError, - "param invalid in attribute expression"); - return 0; - } - break; - case Subscript_kind: - switch (e->v.Subscript.ctx) { - case AugLoad: - VISIT(c, expr, e->v.Subscript.value); - VISIT_SLICE(c, e->v.Subscript.slice, AugLoad); - break; - case Load: - VISIT(c, expr, e->v.Subscript.value); - VISIT_SLICE(c, e->v.Subscript.slice, Load); - break; - case AugStore: - VISIT_SLICE(c, e->v.Subscript.slice, AugStore); - break; - case Store: - VISIT(c, expr, e->v.Subscript.value); - VISIT_SLICE(c, e->v.Subscript.slice, Store); - break; - case Del: - VISIT(c, expr, e->v.Subscript.value); - VISIT_SLICE(c, e->v.Subscript.slice, Del); - break; - case Param: - default: - PyErr_SetString(PyExc_SystemError, - "param invalid in subscript expression"); - return 0; - } - break; - case Starred_kind: - switch (e->v.Starred.ctx) { - case Store: - /* In all legitimate cases, the Starred node was already replaced - * by compiler_list/compiler_tuple. XXX: is that okay? */ - return compiler_error(c, - "starred assignment target must be in a list or tuple"); - default: - return compiler_error(c, - "can use starred expression only as assignment target"); - } - break; - case Name_kind: - return compiler_nameop(c, e->v.Name.id, e->v.Name.ctx); - /* child nodes of List and Tuple will have expr_context set */ - case List_kind: - return compiler_list(c, e); - case Tuple_kind: - return compiler_tuple(c, e); - } - return 1; + /* If expr e has a different line number than the last expr/stmt, + set a new line number for the next instruction. + */ + if (e->lineno > c->u->u_lineno) { + c->u->u_lineno = e->lineno; + c->u->u_lineno_set = 0; + } + switch (e->kind) { + case BoolOp_kind: + return compiler_boolop(c, e); + case BinOp_kind: + VISIT(c, expr, e->v.BinOp.left); + VISIT(c, expr, e->v.BinOp.right); + ADDOP(c, binop(c, e->v.BinOp.op)); + break; + case UnaryOp_kind: + VISIT(c, expr, e->v.UnaryOp.operand); + ADDOP(c, unaryop(e->v.UnaryOp.op)); + break; + case Lambda_kind: + return compiler_lambda(c, e); + case IfExp_kind: + return compiler_ifexp(c, e); + case Dict_kind: + n = asdl_seq_LEN(e->v.Dict.values); + ADDOP_I(c, BUILD_MAP, (n>0xFFFF ? 0xFFFF : n)); + for (i = 0; i < n; i++) { + VISIT(c, expr, + (expr_ty)asdl_seq_GET(e->v.Dict.values, i)); + VISIT(c, expr, + (expr_ty)asdl_seq_GET(e->v.Dict.keys, i)); + ADDOP(c, STORE_MAP); + } + break; + case Set_kind: + n = asdl_seq_LEN(e->v.Set.elts); + VISIT_SEQ(c, expr, e->v.Set.elts); + ADDOP_I(c, BUILD_SET, n); + break; + case GeneratorExp_kind: + return compiler_genexp(c, e); + case ListComp_kind: + return compiler_listcomp(c, e); + case SetComp_kind: + return compiler_setcomp(c, e); + case DictComp_kind: + return compiler_dictcomp(c, e); + case Yield_kind: + if (c->u->u_ste->ste_type != FunctionBlock) + return compiler_error(c, "'yield' outside function"); + if (e->v.Yield.value) { + VISIT(c, expr, e->v.Yield.value); + } + else { + ADDOP_O(c, LOAD_CONST, Py_None, consts); + } + ADDOP(c, YIELD_VALUE); + break; + case Compare_kind: + return compiler_compare(c, e); + case Call_kind: + return compiler_call(c, e); + case Num_kind: + ADDOP_O(c, LOAD_CONST, e->v.Num.n, consts); + break; + case Str_kind: + ADDOP_O(c, LOAD_CONST, e->v.Str.s, consts); + break; + case Bytes_kind: + ADDOP_O(c, LOAD_CONST, e->v.Bytes.s, consts); + break; + case Ellipsis_kind: + ADDOP_O(c, LOAD_CONST, Py_Ellipsis, consts); + break; + /* The following exprs can be assignment targets. */ + case Attribute_kind: + if (e->v.Attribute.ctx != AugStore) + VISIT(c, expr, e->v.Attribute.value); + switch (e->v.Attribute.ctx) { + case AugLoad: + ADDOP(c, DUP_TOP); + /* Fall through to load */ + case Load: + ADDOP_NAME(c, LOAD_ATTR, e->v.Attribute.attr, names); + break; + case AugStore: + ADDOP(c, ROT_TWO); + /* Fall through to save */ + case Store: + ADDOP_NAME(c, STORE_ATTR, e->v.Attribute.attr, names); + break; + case Del: + ADDOP_NAME(c, DELETE_ATTR, e->v.Attribute.attr, names); + break; + case Param: + default: + PyErr_SetString(PyExc_SystemError, + "param invalid in attribute expression"); + return 0; + } + break; + case Subscript_kind: + switch (e->v.Subscript.ctx) { + case AugLoad: + VISIT(c, expr, e->v.Subscript.value); + VISIT_SLICE(c, e->v.Subscript.slice, AugLoad); + break; + case Load: + VISIT(c, expr, e->v.Subscript.value); + VISIT_SLICE(c, e->v.Subscript.slice, Load); + break; + case AugStore: + VISIT_SLICE(c, e->v.Subscript.slice, AugStore); + break; + case Store: + VISIT(c, expr, e->v.Subscript.value); + VISIT_SLICE(c, e->v.Subscript.slice, Store); + break; + case Del: + VISIT(c, expr, e->v.Subscript.value); + VISIT_SLICE(c, e->v.Subscript.slice, Del); + break; + case Param: + default: + PyErr_SetString(PyExc_SystemError, + "param invalid in subscript expression"); + return 0; + } + break; + case Starred_kind: + switch (e->v.Starred.ctx) { + case Store: + /* In all legitimate cases, the Starred node was already replaced + * by compiler_list/compiler_tuple. XXX: is that okay? */ + return compiler_error(c, + "starred assignment target must be in a list or tuple"); + default: + return compiler_error(c, + "can use starred expression only as assignment target"); + } + break; + case Name_kind: + return compiler_nameop(c, e->v.Name.id, e->v.Name.ctx); + /* child nodes of List and Tuple will have expr_context set */ + case List_kind: + return compiler_list(c, e); + case Tuple_kind: + return compiler_tuple(c, e); + } + return 1; } static int compiler_augassign(struct compiler *c, stmt_ty s) { - expr_ty e = s->v.AugAssign.target; - expr_ty auge; + expr_ty e = s->v.AugAssign.target; + expr_ty auge; - assert(s->kind == AugAssign_kind); + assert(s->kind == AugAssign_kind); - switch (e->kind) { - case Attribute_kind: - auge = Attribute(e->v.Attribute.value, e->v.Attribute.attr, - AugLoad, e->lineno, e->col_offset, c->c_arena); - if (auge == NULL) - return 0; - VISIT(c, expr, auge); - VISIT(c, expr, s->v.AugAssign.value); - ADDOP(c, inplace_binop(c, s->v.AugAssign.op)); - auge->v.Attribute.ctx = AugStore; - VISIT(c, expr, auge); - break; - case Subscript_kind: - auge = Subscript(e->v.Subscript.value, e->v.Subscript.slice, - AugLoad, e->lineno, e->col_offset, c->c_arena); - if (auge == NULL) - return 0; - VISIT(c, expr, auge); - VISIT(c, expr, s->v.AugAssign.value); - ADDOP(c, inplace_binop(c, s->v.AugAssign.op)); - auge->v.Subscript.ctx = AugStore; - VISIT(c, expr, auge); - break; - case Name_kind: - if (!compiler_nameop(c, e->v.Name.id, Load)) - return 0; - VISIT(c, expr, s->v.AugAssign.value); - ADDOP(c, inplace_binop(c, s->v.AugAssign.op)); - return compiler_nameop(c, e->v.Name.id, Store); - default: - PyErr_Format(PyExc_SystemError, - "invalid node type (%d) for augmented assignment", - e->kind); - return 0; - } - return 1; + switch (e->kind) { + case Attribute_kind: + auge = Attribute(e->v.Attribute.value, e->v.Attribute.attr, + AugLoad, e->lineno, e->col_offset, c->c_arena); + if (auge == NULL) + return 0; + VISIT(c, expr, auge); + VISIT(c, expr, s->v.AugAssign.value); + ADDOP(c, inplace_binop(c, s->v.AugAssign.op)); + auge->v.Attribute.ctx = AugStore; + VISIT(c, expr, auge); + break; + case Subscript_kind: + auge = Subscript(e->v.Subscript.value, e->v.Subscript.slice, + AugLoad, e->lineno, e->col_offset, c->c_arena); + if (auge == NULL) + return 0; + VISIT(c, expr, auge); + VISIT(c, expr, s->v.AugAssign.value); + ADDOP(c, inplace_binop(c, s->v.AugAssign.op)); + auge->v.Subscript.ctx = AugStore; + VISIT(c, expr, auge); + break; + case Name_kind: + if (!compiler_nameop(c, e->v.Name.id, Load)) + return 0; + VISIT(c, expr, s->v.AugAssign.value); + ADDOP(c, inplace_binop(c, s->v.AugAssign.op)); + return compiler_nameop(c, e->v.Name.id, Store); + default: + PyErr_Format(PyExc_SystemError, + "invalid node type (%d) for augmented assignment", + e->kind); + return 0; + } + return 1; } static int compiler_push_fblock(struct compiler *c, enum fblocktype t, basicblock *b) { - struct fblockinfo *f; - if (c->u->u_nfblocks >= CO_MAXBLOCKS) { - PyErr_SetString(PyExc_SystemError, - "too many statically nested blocks"); - return 0; - } - f = &c->u->u_fblock[c->u->u_nfblocks++]; - f->fb_type = t; - f->fb_block = b; - return 1; + struct fblockinfo *f; + if (c->u->u_nfblocks >= CO_MAXBLOCKS) { + PyErr_SetString(PyExc_SystemError, + "too many statically nested blocks"); + return 0; + } + f = &c->u->u_fblock[c->u->u_nfblocks++]; + f->fb_type = t; + f->fb_block = b; + return 1; } static void compiler_pop_fblock(struct compiler *c, enum fblocktype t, basicblock *b) { - struct compiler_unit *u = c->u; - assert(u->u_nfblocks > 0); - u->u_nfblocks--; - assert(u->u_fblock[u->u_nfblocks].fb_type == t); - assert(u->u_fblock[u->u_nfblocks].fb_block == b); + struct compiler_unit *u = c->u; + assert(u->u_nfblocks > 0); + u->u_nfblocks--; + assert(u->u_fblock[u->u_nfblocks].fb_type == t); + assert(u->u_fblock[u->u_nfblocks].fb_block == b); } static int compiler_in_loop(struct compiler *c) { - int i; - struct compiler_unit *u = c->u; - for (i = 0; i < u->u_nfblocks; ++i) { - if (u->u_fblock[i].fb_type == LOOP) - return 1; - } - return 0; + int i; + struct compiler_unit *u = c->u; + for (i = 0; i < u->u_nfblocks; ++i) { + if (u->u_fblock[i].fb_type == LOOP) + return 1; + } + return 0; } /* Raises a SyntaxError and returns 0. If something goes wrong, a different exception may be raised. @@ -3361,143 +3361,143 @@ static int compiler_error(struct compiler *c, const char *errstr) { - PyObject *loc; - PyObject *u = NULL, *v = NULL; + PyObject *loc; + PyObject *u = NULL, *v = NULL; - loc = PyErr_ProgramText(c->c_filename, c->u->u_lineno); - if (!loc) { - Py_INCREF(Py_None); - loc = Py_None; - } - u = Py_BuildValue("(ziOO)", c->c_filename, c->u->u_lineno, - Py_None, loc); - if (!u) - goto exit; - v = Py_BuildValue("(zO)", errstr, u); - if (!v) - goto exit; - PyErr_SetObject(PyExc_SyntaxError, v); + loc = PyErr_ProgramText(c->c_filename, c->u->u_lineno); + if (!loc) { + Py_INCREF(Py_None); + loc = Py_None; + } + u = Py_BuildValue("(ziOO)", c->c_filename, c->u->u_lineno, + Py_None, loc); + if (!u) + goto exit; + v = Py_BuildValue("(zO)", errstr, u); + if (!v) + goto exit; + PyErr_SetObject(PyExc_SyntaxError, v); exit: - Py_DECREF(loc); - Py_XDECREF(u); - Py_XDECREF(v); - return 0; + Py_DECREF(loc); + Py_XDECREF(u); + Py_XDECREF(v); + return 0; } static int -compiler_handle_subscr(struct compiler *c, const char *kind, - expr_context_ty ctx) -{ - int op = 0; - - /* XXX this code is duplicated */ - switch (ctx) { - case AugLoad: /* fall through to Load */ - case Load: op = BINARY_SUBSCR; break; - case AugStore:/* fall through to Store */ - case Store: op = STORE_SUBSCR; break; - case Del: op = DELETE_SUBSCR; break; - case Param: - PyErr_Format(PyExc_SystemError, - "invalid %s kind %d in subscript\n", - kind, ctx); - return 0; - } - if (ctx == AugLoad) { - ADDOP_I(c, DUP_TOPX, 2); - } - else if (ctx == AugStore) { - ADDOP(c, ROT_THREE); - } - ADDOP(c, op); - return 1; +compiler_handle_subscr(struct compiler *c, const char *kind, + expr_context_ty ctx) +{ + int op = 0; + + /* XXX this code is duplicated */ + switch (ctx) { + case AugLoad: /* fall through to Load */ + case Load: op = BINARY_SUBSCR; break; + case AugStore:/* fall through to Store */ + case Store: op = STORE_SUBSCR; break; + case Del: op = DELETE_SUBSCR; break; + case Param: + PyErr_Format(PyExc_SystemError, + "invalid %s kind %d in subscript\n", + kind, ctx); + return 0; + } + if (ctx == AugLoad) { + ADDOP_I(c, DUP_TOPX, 2); + } + else if (ctx == AugStore) { + ADDOP(c, ROT_THREE); + } + ADDOP(c, op); + return 1; } static int compiler_slice(struct compiler *c, slice_ty s, expr_context_ty ctx) { - int n = 2; - assert(s->kind == Slice_kind); + int n = 2; + assert(s->kind == Slice_kind); - /* only handles the cases where BUILD_SLICE is emitted */ - if (s->v.Slice.lower) { - VISIT(c, expr, s->v.Slice.lower); - } - else { - ADDOP_O(c, LOAD_CONST, Py_None, consts); - } - - if (s->v.Slice.upper) { - VISIT(c, expr, s->v.Slice.upper); - } - else { - ADDOP_O(c, LOAD_CONST, Py_None, consts); - } - - if (s->v.Slice.step) { - n++; - VISIT(c, expr, s->v.Slice.step); - } - ADDOP_I(c, BUILD_SLICE, n); - return 1; + /* only handles the cases where BUILD_SLICE is emitted */ + if (s->v.Slice.lower) { + VISIT(c, expr, s->v.Slice.lower); + } + else { + ADDOP_O(c, LOAD_CONST, Py_None, consts); + } + + if (s->v.Slice.upper) { + VISIT(c, expr, s->v.Slice.upper); + } + else { + ADDOP_O(c, LOAD_CONST, Py_None, consts); + } + + if (s->v.Slice.step) { + n++; + VISIT(c, expr, s->v.Slice.step); + } + ADDOP_I(c, BUILD_SLICE, n); + return 1; } static int -compiler_visit_nested_slice(struct compiler *c, slice_ty s, - expr_context_ty ctx) -{ - switch (s->kind) { - case Slice_kind: - return compiler_slice(c, s, ctx); - case Index_kind: - VISIT(c, expr, s->v.Index.value); - break; - case ExtSlice_kind: - default: - PyErr_SetString(PyExc_SystemError, - "extended slice invalid in nested slice"); - return 0; - } - return 1; +compiler_visit_nested_slice(struct compiler *c, slice_ty s, + expr_context_ty ctx) +{ + switch (s->kind) { + case Slice_kind: + return compiler_slice(c, s, ctx); + case Index_kind: + VISIT(c, expr, s->v.Index.value); + break; + case ExtSlice_kind: + default: + PyErr_SetString(PyExc_SystemError, + "extended slice invalid in nested slice"); + return 0; + } + return 1; } static int compiler_visit_slice(struct compiler *c, slice_ty s, expr_context_ty ctx) { - char * kindname = NULL; - switch (s->kind) { - case Index_kind: - kindname = "index"; - if (ctx != AugStore) { - VISIT(c, expr, s->v.Index.value); - } - break; - case Slice_kind: - kindname = "slice"; - if (ctx != AugStore) { - if (!compiler_slice(c, s, ctx)) - return 0; - } - break; - case ExtSlice_kind: - kindname = "extended slice"; - if (ctx != AugStore) { - int i, n = asdl_seq_LEN(s->v.ExtSlice.dims); - for (i = 0; i < n; i++) { - slice_ty sub = (slice_ty)asdl_seq_GET( - s->v.ExtSlice.dims, i); - if (!compiler_visit_nested_slice(c, sub, ctx)) - return 0; - } - ADDOP_I(c, BUILD_TUPLE, n); - } - break; - default: - PyErr_Format(PyExc_SystemError, - "invalid subscript kind %d", s->kind); - return 0; - } - return compiler_handle_subscr(c, kindname, ctx); + char * kindname = NULL; + switch (s->kind) { + case Index_kind: + kindname = "index"; + if (ctx != AugStore) { + VISIT(c, expr, s->v.Index.value); + } + break; + case Slice_kind: + kindname = "slice"; + if (ctx != AugStore) { + if (!compiler_slice(c, s, ctx)) + return 0; + } + break; + case ExtSlice_kind: + kindname = "extended slice"; + if (ctx != AugStore) { + int i, n = asdl_seq_LEN(s->v.ExtSlice.dims); + for (i = 0; i < n; i++) { + slice_ty sub = (slice_ty)asdl_seq_GET( + s->v.ExtSlice.dims, i); + if (!compiler_visit_nested_slice(c, sub, ctx)) + return 0; + } + ADDOP_I(c, BUILD_TUPLE, n); + } + break; + default: + PyErr_Format(PyExc_SystemError, + "invalid subscript kind %d", s->kind); + return 0; + } + return compiler_handle_subscr(c, kindname, ctx); } /* End of the compiler section, beginning of the assembler section */ @@ -3509,73 +3509,73 @@ */ struct assembler { - PyObject *a_bytecode; /* string containing bytecode */ - int a_offset; /* offset into bytecode */ - int a_nblocks; /* number of reachable blocks */ - basicblock **a_postorder; /* list of blocks in dfs postorder */ - PyObject *a_lnotab; /* string containing lnotab */ - int a_lnotab_off; /* offset into lnotab */ - int a_lineno; /* last lineno of emitted instruction */ - int a_lineno_off; /* bytecode offset of last lineno */ + PyObject *a_bytecode; /* string containing bytecode */ + int a_offset; /* offset into bytecode */ + int a_nblocks; /* number of reachable blocks */ + basicblock **a_postorder; /* list of blocks in dfs postorder */ + PyObject *a_lnotab; /* string containing lnotab */ + int a_lnotab_off; /* offset into lnotab */ + int a_lineno; /* last lineno of emitted instruction */ + int a_lineno_off; /* bytecode offset of last lineno */ }; static void dfs(struct compiler *c, basicblock *b, struct assembler *a) { - int i; - struct instr *instr = NULL; + int i; + struct instr *instr = NULL; - if (b->b_seen) - return; - b->b_seen = 1; - if (b->b_next != NULL) - dfs(c, b->b_next, a); - for (i = 0; i < b->b_iused; i++) { - instr = &b->b_instr[i]; - if (instr->i_jrel || instr->i_jabs) - dfs(c, instr->i_target, a); - } - a->a_postorder[a->a_nblocks++] = b; + if (b->b_seen) + return; + b->b_seen = 1; + if (b->b_next != NULL) + dfs(c, b->b_next, a); + for (i = 0; i < b->b_iused; i++) { + instr = &b->b_instr[i]; + if (instr->i_jrel || instr->i_jabs) + dfs(c, instr->i_target, a); + } + a->a_postorder[a->a_nblocks++] = b; } static int stackdepth_walk(struct compiler *c, basicblock *b, int depth, int maxdepth) { - int i, target_depth; - struct instr *instr; - if (b->b_seen || b->b_startdepth >= depth) - return maxdepth; - b->b_seen = 1; - b->b_startdepth = depth; - for (i = 0; i < b->b_iused; i++) { - instr = &b->b_instr[i]; - depth += opcode_stack_effect(instr->i_opcode, instr->i_oparg); - if (depth > maxdepth) - maxdepth = depth; - assert(depth >= 0); /* invalid code or bug in stackdepth() */ - if (instr->i_jrel || instr->i_jabs) { - target_depth = depth; - if (instr->i_opcode == FOR_ITER) { - target_depth = depth-2; - } else if (instr->i_opcode == SETUP_FINALLY || - instr->i_opcode == SETUP_EXCEPT) { - target_depth = depth+3; - if (target_depth > maxdepth) - maxdepth = target_depth; - } - maxdepth = stackdepth_walk(c, instr->i_target, - target_depth, maxdepth); - if (instr->i_opcode == JUMP_ABSOLUTE || - instr->i_opcode == JUMP_FORWARD) { - goto out; /* remaining code is dead */ - } - } - } - if (b->b_next) - maxdepth = stackdepth_walk(c, b->b_next, depth, maxdepth); + int i, target_depth; + struct instr *instr; + if (b->b_seen || b->b_startdepth >= depth) + return maxdepth; + b->b_seen = 1; + b->b_startdepth = depth; + for (i = 0; i < b->b_iused; i++) { + instr = &b->b_instr[i]; + depth += opcode_stack_effect(instr->i_opcode, instr->i_oparg); + if (depth > maxdepth) + maxdepth = depth; + assert(depth >= 0); /* invalid code or bug in stackdepth() */ + if (instr->i_jrel || instr->i_jabs) { + target_depth = depth; + if (instr->i_opcode == FOR_ITER) { + target_depth = depth-2; + } else if (instr->i_opcode == SETUP_FINALLY || + instr->i_opcode == SETUP_EXCEPT) { + target_depth = depth+3; + if (target_depth > maxdepth) + maxdepth = target_depth; + } + maxdepth = stackdepth_walk(c, instr->i_target, + target_depth, maxdepth); + if (instr->i_opcode == JUMP_ABSOLUTE || + instr->i_opcode == JUMP_FORWARD) { + goto out; /* remaining code is dead */ + } + } + } + if (b->b_next) + maxdepth = stackdepth_walk(c, b->b_next, depth, maxdepth); out: - b->b_seen = 0; - return maxdepth; + b->b_seen = 0; + return maxdepth; } /* Find the flow path that needs the largest stack. We assume that @@ -3584,49 +3584,49 @@ static int stackdepth(struct compiler *c) { - basicblock *b, *entryblock; - entryblock = NULL; - for (b = c->u->u_blocks; b != NULL; b = b->b_list) { - b->b_seen = 0; - b->b_startdepth = INT_MIN; - entryblock = b; - } - if (!entryblock) - return 0; - return stackdepth_walk(c, entryblock, 0, 0); + basicblock *b, *entryblock; + entryblock = NULL; + for (b = c->u->u_blocks; b != NULL; b = b->b_list) { + b->b_seen = 0; + b->b_startdepth = INT_MIN; + entryblock = b; + } + if (!entryblock) + return 0; + return stackdepth_walk(c, entryblock, 0, 0); } static int assemble_init(struct assembler *a, int nblocks, int firstlineno) { - memset(a, 0, sizeof(struct assembler)); - a->a_lineno = firstlineno; - a->a_bytecode = PyBytes_FromStringAndSize(NULL, DEFAULT_CODE_SIZE); - if (!a->a_bytecode) - return 0; - a->a_lnotab = PyBytes_FromStringAndSize(NULL, DEFAULT_LNOTAB_SIZE); - if (!a->a_lnotab) - return 0; - if (nblocks > PY_SIZE_MAX / sizeof(basicblock *)) { - PyErr_NoMemory(); - return 0; - } - a->a_postorder = (basicblock **)PyObject_Malloc( - sizeof(basicblock *) * nblocks); - if (!a->a_postorder) { - PyErr_NoMemory(); - return 0; - } - return 1; + memset(a, 0, sizeof(struct assembler)); + a->a_lineno = firstlineno; + a->a_bytecode = PyBytes_FromStringAndSize(NULL, DEFAULT_CODE_SIZE); + if (!a->a_bytecode) + return 0; + a->a_lnotab = PyBytes_FromStringAndSize(NULL, DEFAULT_LNOTAB_SIZE); + if (!a->a_lnotab) + return 0; + if (nblocks > PY_SIZE_MAX / sizeof(basicblock *)) { + PyErr_NoMemory(); + return 0; + } + a->a_postorder = (basicblock **)PyObject_Malloc( + sizeof(basicblock *) * nblocks); + if (!a->a_postorder) { + PyErr_NoMemory(); + return 0; + } + return 1; } static void assemble_free(struct assembler *a) { - Py_XDECREF(a->a_bytecode); - Py_XDECREF(a->a_lnotab); - if (a->a_postorder) - PyObject_Free(a->a_postorder); + Py_XDECREF(a->a_bytecode); + Py_XDECREF(a->a_lnotab); + if (a->a_postorder) + PyObject_Free(a->a_postorder); } /* Return the size of a basic block in bytes. */ @@ -3634,22 +3634,22 @@ static int instrsize(struct instr *instr) { - if (!instr->i_hasarg) - return 1; /* 1 byte for the opcode*/ - if (instr->i_oparg > 0xffff) - return 6; /* 1 (opcode) + 1 (EXTENDED_ARG opcode) + 2 (oparg) + 2(oparg extended) */ - return 3; /* 1 (opcode) + 2 (oparg) */ + if (!instr->i_hasarg) + return 1; /* 1 byte for the opcode*/ + if (instr->i_oparg > 0xffff) + return 6; /* 1 (opcode) + 1 (EXTENDED_ARG opcode) + 2 (oparg) + 2(oparg extended) */ + return 3; /* 1 (opcode) + 2 (oparg) */ } static int blocksize(basicblock *b) { - int i; - int size = 0; + int i; + int size = 0; - for (i = 0; i < b->b_iused; i++) - size += instrsize(&b->b_instr[i]); - return size; + for (i = 0; i < b->b_iused; i++) + size += instrsize(&b->b_instr[i]); + return size; } /* Appends a pair to the end of the line number table, a_lnotab, representing @@ -3659,94 +3659,94 @@ static int assemble_lnotab(struct assembler *a, struct instr *i) { - int d_bytecode, d_lineno; - int len; - unsigned char *lnotab; - - d_bytecode = a->a_offset - a->a_lineno_off; - d_lineno = i->i_lineno - a->a_lineno; - - assert(d_bytecode >= 0); - assert(d_lineno >= 0); - - if(d_bytecode == 0 && d_lineno == 0) - return 1; - - if (d_bytecode > 255) { - int j, nbytes, ncodes = d_bytecode / 255; - nbytes = a->a_lnotab_off + 2 * ncodes; - len = PyBytes_GET_SIZE(a->a_lnotab); - if (nbytes >= len) { - if ((len <= INT_MAX / 2) && (len * 2 < nbytes)) - len = nbytes; - else if (len <= INT_MAX / 2) - len *= 2; - else { - PyErr_NoMemory(); - return 0; - } - if (_PyBytes_Resize(&a->a_lnotab, len) < 0) - return 0; - } - lnotab = (unsigned char *) - PyBytes_AS_STRING(a->a_lnotab) + a->a_lnotab_off; - for (j = 0; j < ncodes; j++) { - *lnotab++ = 255; - *lnotab++ = 0; - } - d_bytecode -= ncodes * 255; - a->a_lnotab_off += ncodes * 2; - } - assert(d_bytecode <= 255); - if (d_lineno > 255) { - int j, nbytes, ncodes = d_lineno / 255; - nbytes = a->a_lnotab_off + 2 * ncodes; - len = PyBytes_GET_SIZE(a->a_lnotab); - if (nbytes >= len) { - if ((len <= INT_MAX / 2) && len * 2 < nbytes) - len = nbytes; - else if (len <= INT_MAX / 2) - len *= 2; - else { - PyErr_NoMemory(); - return 0; - } - if (_PyBytes_Resize(&a->a_lnotab, len) < 0) - return 0; - } - lnotab = (unsigned char *) - PyBytes_AS_STRING(a->a_lnotab) + a->a_lnotab_off; - *lnotab++ = d_bytecode; - *lnotab++ = 255; - d_bytecode = 0; - for (j = 1; j < ncodes; j++) { - *lnotab++ = 0; - *lnotab++ = 255; - } - d_lineno -= ncodes * 255; - a->a_lnotab_off += ncodes * 2; - } - - len = PyBytes_GET_SIZE(a->a_lnotab); - if (a->a_lnotab_off + 2 >= len) { - if (_PyBytes_Resize(&a->a_lnotab, len * 2) < 0) - return 0; - } - lnotab = (unsigned char *) - PyBytes_AS_STRING(a->a_lnotab) + a->a_lnotab_off; - - a->a_lnotab_off += 2; - if (d_bytecode) { - *lnotab++ = d_bytecode; - *lnotab++ = d_lineno; - } - else { /* First line of a block; def stmt, etc. */ - *lnotab++ = 0; - *lnotab++ = d_lineno; - } - a->a_lineno = i->i_lineno; - a->a_lineno_off = a->a_offset; - return 1; + int d_bytecode, d_lineno; + int len; + unsigned char *lnotab; + + d_bytecode = a->a_offset - a->a_lineno_off; + d_lineno = i->i_lineno - a->a_lineno; + + assert(d_bytecode >= 0); + assert(d_lineno >= 0); + + if(d_bytecode == 0 && d_lineno == 0) + return 1; + + if (d_bytecode > 255) { + int j, nbytes, ncodes = d_bytecode / 255; + nbytes = a->a_lnotab_off + 2 * ncodes; + len = PyBytes_GET_SIZE(a->a_lnotab); + if (nbytes >= len) { + if ((len <= INT_MAX / 2) && (len * 2 < nbytes)) + len = nbytes; + else if (len <= INT_MAX / 2) + len *= 2; + else { + PyErr_NoMemory(); + return 0; + } + if (_PyBytes_Resize(&a->a_lnotab, len) < 0) + return 0; + } + lnotab = (unsigned char *) + PyBytes_AS_STRING(a->a_lnotab) + a->a_lnotab_off; + for (j = 0; j < ncodes; j++) { + *lnotab++ = 255; + *lnotab++ = 0; + } + d_bytecode -= ncodes * 255; + a->a_lnotab_off += ncodes * 2; + } + assert(d_bytecode <= 255); + if (d_lineno > 255) { + int j, nbytes, ncodes = d_lineno / 255; + nbytes = a->a_lnotab_off + 2 * ncodes; + len = PyBytes_GET_SIZE(a->a_lnotab); + if (nbytes >= len) { + if ((len <= INT_MAX / 2) && len * 2 < nbytes) + len = nbytes; + else if (len <= INT_MAX / 2) + len *= 2; + else { + PyErr_NoMemory(); + return 0; + } + if (_PyBytes_Resize(&a->a_lnotab, len) < 0) + return 0; + } + lnotab = (unsigned char *) + PyBytes_AS_STRING(a->a_lnotab) + a->a_lnotab_off; + *lnotab++ = d_bytecode; + *lnotab++ = 255; + d_bytecode = 0; + for (j = 1; j < ncodes; j++) { + *lnotab++ = 0; + *lnotab++ = 255; + } + d_lineno -= ncodes * 255; + a->a_lnotab_off += ncodes * 2; + } + + len = PyBytes_GET_SIZE(a->a_lnotab); + if (a->a_lnotab_off + 2 >= len) { + if (_PyBytes_Resize(&a->a_lnotab, len * 2) < 0) + return 0; + } + lnotab = (unsigned char *) + PyBytes_AS_STRING(a->a_lnotab) + a->a_lnotab_off; + + a->a_lnotab_off += 2; + if (d_bytecode) { + *lnotab++ = d_bytecode; + *lnotab++ = d_lineno; + } + else { /* First line of a block; def stmt, etc. */ + *lnotab++ = 0; + *lnotab++ = d_lineno; + } + a->a_lineno = i->i_lineno; + a->a_lineno_off = a->a_offset; + return 1; } /* assemble_emit() @@ -3757,227 +3757,227 @@ static int assemble_emit(struct assembler *a, struct instr *i) { - int size, arg = 0, ext = 0; - Py_ssize_t len = PyBytes_GET_SIZE(a->a_bytecode); - char *code; - - size = instrsize(i); - if (i->i_hasarg) { - arg = i->i_oparg; - ext = arg >> 16; - } - if (i->i_lineno && !assemble_lnotab(a, i)) - return 0; - if (a->a_offset + size >= len) { - if (len > PY_SSIZE_T_MAX / 2) - return 0; - if (_PyBytes_Resize(&a->a_bytecode, len * 2) < 0) - return 0; - } - code = PyBytes_AS_STRING(a->a_bytecode) + a->a_offset; - a->a_offset += size; - if (size == 6) { - assert(i->i_hasarg); - *code++ = (char)EXTENDED_ARG; - *code++ = ext & 0xff; - *code++ = ext >> 8; - arg &= 0xffff; - } - *code++ = i->i_opcode; - if (i->i_hasarg) { - assert(size == 3 || size == 6); - *code++ = arg & 0xff; - *code++ = arg >> 8; - } - return 1; + int size, arg = 0, ext = 0; + Py_ssize_t len = PyBytes_GET_SIZE(a->a_bytecode); + char *code; + + size = instrsize(i); + if (i->i_hasarg) { + arg = i->i_oparg; + ext = arg >> 16; + } + if (i->i_lineno && !assemble_lnotab(a, i)) + return 0; + if (a->a_offset + size >= len) { + if (len > PY_SSIZE_T_MAX / 2) + return 0; + if (_PyBytes_Resize(&a->a_bytecode, len * 2) < 0) + return 0; + } + code = PyBytes_AS_STRING(a->a_bytecode) + a->a_offset; + a->a_offset += size; + if (size == 6) { + assert(i->i_hasarg); + *code++ = (char)EXTENDED_ARG; + *code++ = ext & 0xff; + *code++ = ext >> 8; + arg &= 0xffff; + } + *code++ = i->i_opcode; + if (i->i_hasarg) { + assert(size == 3 || size == 6); + *code++ = arg & 0xff; + *code++ = arg >> 8; + } + return 1; } static void assemble_jump_offsets(struct assembler *a, struct compiler *c) { - basicblock *b; - int bsize, totsize, extended_arg_count = 0, last_extended_arg_count; - int i; - - /* Compute the size of each block and fixup jump args. - Replace block pointer with position in bytecode. */ - do { - totsize = 0; - for (i = a->a_nblocks - 1; i >= 0; i--) { - b = a->a_postorder[i]; - bsize = blocksize(b); - b->b_offset = totsize; - totsize += bsize; - } - last_extended_arg_count = extended_arg_count; - extended_arg_count = 0; - for (b = c->u->u_blocks; b != NULL; b = b->b_list) { - bsize = b->b_offset; - for (i = 0; i < b->b_iused; i++) { - struct instr *instr = &b->b_instr[i]; - /* Relative jumps are computed relative to - the instruction pointer after fetching - the jump instruction. - */ - bsize += instrsize(instr); - if (instr->i_jabs) - instr->i_oparg = instr->i_target->b_offset; - else if (instr->i_jrel) { - int delta = instr->i_target->b_offset - bsize; - instr->i_oparg = delta; - } - else - continue; - if (instr->i_oparg > 0xffff) - extended_arg_count++; - } - } - - /* XXX: This is an awful hack that could hurt performance, but - on the bright side it should work until we come up - with a better solution. - - The issue is that in the first loop blocksize() is called - which calls instrsize() which requires i_oparg be set - appropriately. There is a bootstrap problem because - i_oparg is calculated in the second loop above. - - So we loop until we stop seeing new EXTENDED_ARGs. - The only EXTENDED_ARGs that could be popping up are - ones in jump instructions. So this should converge - fairly quickly. - */ - } while (last_extended_arg_count != extended_arg_count); + basicblock *b; + int bsize, totsize, extended_arg_count = 0, last_extended_arg_count; + int i; + + /* Compute the size of each block and fixup jump args. + Replace block pointer with position in bytecode. */ + do { + totsize = 0; + for (i = a->a_nblocks - 1; i >= 0; i--) { + b = a->a_postorder[i]; + bsize = blocksize(b); + b->b_offset = totsize; + totsize += bsize; + } + last_extended_arg_count = extended_arg_count; + extended_arg_count = 0; + for (b = c->u->u_blocks; b != NULL; b = b->b_list) { + bsize = b->b_offset; + for (i = 0; i < b->b_iused; i++) { + struct instr *instr = &b->b_instr[i]; + /* Relative jumps are computed relative to + the instruction pointer after fetching + the jump instruction. + */ + bsize += instrsize(instr); + if (instr->i_jabs) + instr->i_oparg = instr->i_target->b_offset; + else if (instr->i_jrel) { + int delta = instr->i_target->b_offset - bsize; + instr->i_oparg = delta; + } + else + continue; + if (instr->i_oparg > 0xffff) + extended_arg_count++; + } + } + + /* XXX: This is an awful hack that could hurt performance, but + on the bright side it should work until we come up + with a better solution. + + The issue is that in the first loop blocksize() is called + which calls instrsize() which requires i_oparg be set + appropriately. There is a bootstrap problem because + i_oparg is calculated in the second loop above. + + So we loop until we stop seeing new EXTENDED_ARGs. + The only EXTENDED_ARGs that could be popping up are + ones in jump instructions. So this should converge + fairly quickly. + */ + } while (last_extended_arg_count != extended_arg_count); } static PyObject * dict_keys_inorder(PyObject *dict, int offset) { - PyObject *tuple, *k, *v; - Py_ssize_t i, pos = 0, size = PyDict_Size(dict); + PyObject *tuple, *k, *v; + Py_ssize_t i, pos = 0, size = PyDict_Size(dict); - tuple = PyTuple_New(size); - if (tuple == NULL) - return NULL; - while (PyDict_Next(dict, &pos, &k, &v)) { - i = PyLong_AS_LONG(v); - /* The keys of the dictionary are tuples. (see compiler_add_o) - The object we want is always first, though. */ - k = PyTuple_GET_ITEM(k, 0); - Py_INCREF(k); - assert((i - offset) < size); - assert((i - offset) >= 0); - PyTuple_SET_ITEM(tuple, i - offset, k); - } - return tuple; + tuple = PyTuple_New(size); + if (tuple == NULL) + return NULL; + while (PyDict_Next(dict, &pos, &k, &v)) { + i = PyLong_AS_LONG(v); + /* The keys of the dictionary are tuples. (see compiler_add_o) + The object we want is always first, though. */ + k = PyTuple_GET_ITEM(k, 0); + Py_INCREF(k); + assert((i - offset) < size); + assert((i - offset) >= 0); + PyTuple_SET_ITEM(tuple, i - offset, k); + } + return tuple; } static int compute_code_flags(struct compiler *c) { - PySTEntryObject *ste = c->u->u_ste; - int flags = 0, n; - if (ste->ste_type != ModuleBlock) - flags |= CO_NEWLOCALS; - if (ste->ste_type == FunctionBlock) { - if (!ste->ste_unoptimized) - flags |= CO_OPTIMIZED; - if (ste->ste_nested) - flags |= CO_NESTED; - if (ste->ste_generator) - flags |= CO_GENERATOR; - if (ste->ste_varargs) - flags |= CO_VARARGS; - if (ste->ste_varkeywords) - flags |= CO_VARKEYWORDS; - } - - /* (Only) inherit compilerflags in PyCF_MASK */ - flags |= (c->c_flags->cf_flags & PyCF_MASK); - - n = PyDict_Size(c->u->u_freevars); - if (n < 0) - return -1; - if (n == 0) { - n = PyDict_Size(c->u->u_cellvars); - if (n < 0) - return -1; - if (n == 0) { - flags |= CO_NOFREE; - } - } + PySTEntryObject *ste = c->u->u_ste; + int flags = 0, n; + if (ste->ste_type != ModuleBlock) + flags |= CO_NEWLOCALS; + if (ste->ste_type == FunctionBlock) { + if (!ste->ste_unoptimized) + flags |= CO_OPTIMIZED; + if (ste->ste_nested) + flags |= CO_NESTED; + if (ste->ste_generator) + flags |= CO_GENERATOR; + if (ste->ste_varargs) + flags |= CO_VARARGS; + if (ste->ste_varkeywords) + flags |= CO_VARKEYWORDS; + } + + /* (Only) inherit compilerflags in PyCF_MASK */ + flags |= (c->c_flags->cf_flags & PyCF_MASK); + + n = PyDict_Size(c->u->u_freevars); + if (n < 0) + return -1; + if (n == 0) { + n = PyDict_Size(c->u->u_cellvars); + if (n < 0) + return -1; + if (n == 0) { + flags |= CO_NOFREE; + } + } - return flags; + return flags; } static PyCodeObject * makecode(struct compiler *c, struct assembler *a) { - PyObject *tmp; - PyCodeObject *co = NULL; - PyObject *consts = NULL; - PyObject *names = NULL; - PyObject *varnames = NULL; - PyObject *filename = NULL; - PyObject *name = NULL; - PyObject *freevars = NULL; - PyObject *cellvars = NULL; - PyObject *bytecode = NULL; - int nlocals, flags; - - tmp = dict_keys_inorder(c->u->u_consts, 0); - if (!tmp) - goto error; - consts = PySequence_List(tmp); /* optimize_code requires a list */ - Py_DECREF(tmp); - - names = dict_keys_inorder(c->u->u_names, 0); - varnames = dict_keys_inorder(c->u->u_varnames, 0); - if (!consts || !names || !varnames) - goto error; - - cellvars = dict_keys_inorder(c->u->u_cellvars, 0); - if (!cellvars) - goto error; - freevars = dict_keys_inorder(c->u->u_freevars, PyTuple_Size(cellvars)); - if (!freevars) - goto error; - filename = PyUnicode_DecodeFSDefault(c->c_filename); - if (!filename) - goto error; - - nlocals = PyDict_Size(c->u->u_varnames); - flags = compute_code_flags(c); - if (flags < 0) - goto error; - - bytecode = PyCode_Optimize(a->a_bytecode, consts, names, a->a_lnotab); - if (!bytecode) - goto error; - - tmp = PyList_AsTuple(consts); /* PyCode_New requires a tuple */ - if (!tmp) - goto error; - Py_DECREF(consts); - consts = tmp; - - co = PyCode_New(c->u->u_argcount, c->u->u_kwonlyargcount, - nlocals, stackdepth(c), flags, - bytecode, consts, names, varnames, - freevars, cellvars, - filename, c->u->u_name, - c->u->u_firstlineno, - a->a_lnotab); + PyObject *tmp; + PyCodeObject *co = NULL; + PyObject *consts = NULL; + PyObject *names = NULL; + PyObject *varnames = NULL; + PyObject *filename = NULL; + PyObject *name = NULL; + PyObject *freevars = NULL; + PyObject *cellvars = NULL; + PyObject *bytecode = NULL; + int nlocals, flags; + + tmp = dict_keys_inorder(c->u->u_consts, 0); + if (!tmp) + goto error; + consts = PySequence_List(tmp); /* optimize_code requires a list */ + Py_DECREF(tmp); + + names = dict_keys_inorder(c->u->u_names, 0); + varnames = dict_keys_inorder(c->u->u_varnames, 0); + if (!consts || !names || !varnames) + goto error; + + cellvars = dict_keys_inorder(c->u->u_cellvars, 0); + if (!cellvars) + goto error; + freevars = dict_keys_inorder(c->u->u_freevars, PyTuple_Size(cellvars)); + if (!freevars) + goto error; + filename = PyUnicode_DecodeFSDefault(c->c_filename); + if (!filename) + goto error; + + nlocals = PyDict_Size(c->u->u_varnames); + flags = compute_code_flags(c); + if (flags < 0) + goto error; + + bytecode = PyCode_Optimize(a->a_bytecode, consts, names, a->a_lnotab); + if (!bytecode) + goto error; + + tmp = PyList_AsTuple(consts); /* PyCode_New requires a tuple */ + if (!tmp) + goto error; + Py_DECREF(consts); + consts = tmp; + + co = PyCode_New(c->u->u_argcount, c->u->u_kwonlyargcount, + nlocals, stackdepth(c), flags, + bytecode, consts, names, varnames, + freevars, cellvars, + filename, c->u->u_name, + c->u->u_firstlineno, + a->a_lnotab); error: - Py_XDECREF(consts); - Py_XDECREF(names); - Py_XDECREF(varnames); - Py_XDECREF(filename); - Py_XDECREF(name); - Py_XDECREF(freevars); - Py_XDECREF(cellvars); - Py_XDECREF(bytecode); - return co; + Py_XDECREF(consts); + Py_XDECREF(names); + Py_XDECREF(varnames); + Py_XDECREF(filename); + Py_XDECREF(name); + Py_XDECREF(freevars); + Py_XDECREF(cellvars); + Py_XDECREF(bytecode); + return co; } @@ -3986,90 +3986,90 @@ static void dump_instr(const struct instr *i) { - const char *jrel = i->i_jrel ? "jrel " : ""; - const char *jabs = i->i_jabs ? "jabs " : ""; - char arg[128]; - - *arg = '\0'; - if (i->i_hasarg) - sprintf(arg, "arg: %d ", i->i_oparg); + const char *jrel = i->i_jrel ? "jrel " : ""; + const char *jabs = i->i_jabs ? "jabs " : ""; + char arg[128]; + + *arg = '\0'; + if (i->i_hasarg) + sprintf(arg, "arg: %d ", i->i_oparg); - fprintf(stderr, "line: %d, opcode: %d %s%s%s\n", - i->i_lineno, i->i_opcode, arg, jabs, jrel); + fprintf(stderr, "line: %d, opcode: %d %s%s%s\n", + i->i_lineno, i->i_opcode, arg, jabs, jrel); } static void dump_basicblock(const basicblock *b) { - const char *seen = b->b_seen ? "seen " : ""; - const char *b_return = b->b_return ? "return " : ""; - fprintf(stderr, "used: %d, depth: %d, offset: %d %s%s\n", - b->b_iused, b->b_startdepth, b->b_offset, seen, b_return); - if (b->b_instr) { - int i; - for (i = 0; i < b->b_iused; i++) { - fprintf(stderr, " [%02d] ", i); - dump_instr(b->b_instr + i); - } - } + const char *seen = b->b_seen ? "seen " : ""; + const char *b_return = b->b_return ? "return " : ""; + fprintf(stderr, "used: %d, depth: %d, offset: %d %s%s\n", + b->b_iused, b->b_startdepth, b->b_offset, seen, b_return); + if (b->b_instr) { + int i; + for (i = 0; i < b->b_iused; i++) { + fprintf(stderr, " [%02d] ", i); + dump_instr(b->b_instr + i); + } + } } #endif static PyCodeObject * assemble(struct compiler *c, int addNone) { - basicblock *b, *entryblock; - struct assembler a; - int i, j, nblocks; - PyCodeObject *co = NULL; - - /* Make sure every block that falls off the end returns None. - XXX NEXT_BLOCK() isn't quite right, because if the last - block ends with a jump or return b_next shouldn't set. - */ - if (!c->u->u_curblock->b_return) { - NEXT_BLOCK(c); - if (addNone) - ADDOP_O(c, LOAD_CONST, Py_None, consts); - ADDOP(c, RETURN_VALUE); - } - - nblocks = 0; - entryblock = NULL; - for (b = c->u->u_blocks; b != NULL; b = b->b_list) { - nblocks++; - entryblock = b; - } - - /* Set firstlineno if it wasn't explicitly set. */ - if (!c->u->u_firstlineno) { - if (entryblock && entryblock->b_instr) - c->u->u_firstlineno = entryblock->b_instr->i_lineno; - else - c->u->u_firstlineno = 1; - } - if (!assemble_init(&a, nblocks, c->u->u_firstlineno)) - goto error; - dfs(c, entryblock, &a); - - /* Can't modify the bytecode after computing jump offsets. */ - assemble_jump_offsets(&a, c); - - /* Emit code in reverse postorder from dfs. */ - for (i = a.a_nblocks - 1; i >= 0; i--) { - b = a.a_postorder[i]; - for (j = 0; j < b->b_iused; j++) - if (!assemble_emit(&a, &b->b_instr[j])) - goto error; - } - - if (_PyBytes_Resize(&a.a_lnotab, a.a_lnotab_off) < 0) - goto error; - if (_PyBytes_Resize(&a.a_bytecode, a.a_offset) < 0) - goto error; + basicblock *b, *entryblock; + struct assembler a; + int i, j, nblocks; + PyCodeObject *co = NULL; + + /* Make sure every block that falls off the end returns None. + XXX NEXT_BLOCK() isn't quite right, because if the last + block ends with a jump or return b_next shouldn't set. + */ + if (!c->u->u_curblock->b_return) { + NEXT_BLOCK(c); + if (addNone) + ADDOP_O(c, LOAD_CONST, Py_None, consts); + ADDOP(c, RETURN_VALUE); + } + + nblocks = 0; + entryblock = NULL; + for (b = c->u->u_blocks; b != NULL; b = b->b_list) { + nblocks++; + entryblock = b; + } + + /* Set firstlineno if it wasn't explicitly set. */ + if (!c->u->u_firstlineno) { + if (entryblock && entryblock->b_instr) + c->u->u_firstlineno = entryblock->b_instr->i_lineno; + else + c->u->u_firstlineno = 1; + } + if (!assemble_init(&a, nblocks, c->u->u_firstlineno)) + goto error; + dfs(c, entryblock, &a); + + /* Can't modify the bytecode after computing jump offsets. */ + assemble_jump_offsets(&a, c); + + /* Emit code in reverse postorder from dfs. */ + for (i = a.a_nblocks - 1; i >= 0; i--) { + b = a.a_postorder[i]; + for (j = 0; j < b->b_iused; j++) + if (!assemble_emit(&a, &b->b_instr[j])) + goto error; + } + + if (_PyBytes_Resize(&a.a_lnotab, a.a_lnotab_off) < 0) + goto error; + if (_PyBytes_Resize(&a.a_bytecode, a.a_offset) < 0) + goto error; - co = makecode(c, &a); + co = makecode(c, &a); error: - assemble_free(&a); - return co; + assemble_free(&a); + return co; } Modified: python/branches/py3k-jit/Python/dynload_aix.c ============================================================================== --- python/branches/py3k-jit/Python/dynload_aix.c (original) +++ python/branches/py3k-jit/Python/dynload_aix.c Mon May 10 23:55:43 2010 @@ -4,10 +4,10 @@ #include "Python.h" #include "importdl.h" -#include /* for isdigit() */ -#include /* for global errno */ -#include /* for strerror() */ -#include /* for malloc(), free() */ +#include /* for isdigit() */ +#include /* for global errno */ +#include /* for strerror() */ +#include /* for malloc(), free() */ #include @@ -22,85 +22,85 @@ extern char *Py_GetProgramName(void); typedef struct Module { - struct Module *next; - void *entry; + struct Module *next; + void *entry; } Module, *ModulePtr; const struct filedescr _PyImport_DynLoadFiletab[] = { - {".so", "rb", C_EXTENSION}, - {"module.so", "rb", C_EXTENSION}, - {0, 0} + {".so", "rb", C_EXTENSION}, + {"module.so", "rb", C_EXTENSION}, + {0, 0} }; static int aix_getoldmodules(void **modlistptr) { - register ModulePtr modptr, prevmodptr; - register struct ld_info *ldiptr; - register char *ldibuf; - register int errflag, bufsize = 1024; - register unsigned int offset; - char *progname = Py_GetProgramName(); - - /* - -- Get the list of loaded modules into ld_info structures. - */ - if ((ldibuf = malloc(bufsize)) == NULL) { - PyErr_SetString(PyExc_ImportError, strerror(errno)); - return -1; - } - while ((errflag = loadquery(L_GETINFO, ldibuf, bufsize)) == -1 - && errno == ENOMEM) { - free(ldibuf); - bufsize += 1024; - if ((ldibuf = malloc(bufsize)) == NULL) { - PyErr_SetString(PyExc_ImportError, strerror(errno)); - return -1; - } - } - if (errflag == -1) { - PyErr_SetString(PyExc_ImportError, strerror(errno)); - return -1; - } - /* - -- Make the modules list from the ld_info structures. - */ - ldiptr = (struct ld_info *)ldibuf; - prevmodptr = NULL; - do { - if (strstr(progname, ldiptr->ldinfo_filename) == NULL && - strstr(ldiptr->ldinfo_filename, "python") == NULL) { - /* - -- Extract only the modules belonging to the main - -- executable + those containing "python" as a - -- substring (like the "python[version]" binary or - -- "libpython[version].a" in case it's a shared lib). - */ - offset = (unsigned int)ldiptr->ldinfo_next; - ldiptr = (struct ld_info *)((char*)ldiptr + offset); - continue; - } - if ((modptr = (ModulePtr)malloc(sizeof(Module))) == NULL) { - PyErr_SetString(PyExc_ImportError, strerror(errno)); - while (*modlistptr) { - modptr = (ModulePtr)*modlistptr; - *modlistptr = (void *)modptr->next; - free(modptr); - } - return -1; - } - modptr->entry = ldiptr->ldinfo_dataorg; - modptr->next = NULL; - if (prevmodptr == NULL) - *modlistptr = (void *)modptr; - else - prevmodptr->next = modptr; - prevmodptr = modptr; - offset = (unsigned int)ldiptr->ldinfo_next; - ldiptr = (struct ld_info *)((char*)ldiptr + offset); - } while (offset); - free(ldibuf); - return 0; + register ModulePtr modptr, prevmodptr; + register struct ld_info *ldiptr; + register char *ldibuf; + register int errflag, bufsize = 1024; + register unsigned int offset; + char *progname = Py_GetProgramName(); + + /* + -- Get the list of loaded modules into ld_info structures. + */ + if ((ldibuf = malloc(bufsize)) == NULL) { + PyErr_SetString(PyExc_ImportError, strerror(errno)); + return -1; + } + while ((errflag = loadquery(L_GETINFO, ldibuf, bufsize)) == -1 + && errno == ENOMEM) { + free(ldibuf); + bufsize += 1024; + if ((ldibuf = malloc(bufsize)) == NULL) { + PyErr_SetString(PyExc_ImportError, strerror(errno)); + return -1; + } + } + if (errflag == -1) { + PyErr_SetString(PyExc_ImportError, strerror(errno)); + return -1; + } + /* + -- Make the modules list from the ld_info structures. + */ + ldiptr = (struct ld_info *)ldibuf; + prevmodptr = NULL; + do { + if (strstr(progname, ldiptr->ldinfo_filename) == NULL && + strstr(ldiptr->ldinfo_filename, "python") == NULL) { + /* + -- Extract only the modules belonging to the main + -- executable + those containing "python" as a + -- substring (like the "python[version]" binary or + -- "libpython[version].a" in case it's a shared lib). + */ + offset = (unsigned int)ldiptr->ldinfo_next; + ldiptr = (struct ld_info *)((char*)ldiptr + offset); + continue; + } + if ((modptr = (ModulePtr)malloc(sizeof(Module))) == NULL) { + PyErr_SetString(PyExc_ImportError, strerror(errno)); + while (*modlistptr) { + modptr = (ModulePtr)*modlistptr; + *modlistptr = (void *)modptr->next; + free(modptr); + } + return -1; + } + modptr->entry = ldiptr->ldinfo_dataorg; + modptr->next = NULL; + if (prevmodptr == NULL) + *modlistptr = (void *)modptr; + else + prevmodptr->next = modptr; + prevmodptr = modptr; + offset = (unsigned int)ldiptr->ldinfo_next; + ldiptr = (struct ld_info *)((char*)ldiptr + offset); + } while (offset); + free(ldibuf); + return 0; } @@ -108,76 +108,76 @@ aix_loaderror(const char *pathname) { - char *message[1024], errbuf[1024]; - register int i,j; + char *message[1024], errbuf[1024]; + register int i,j; - struct errtab { - int errNo; - char *errstr; - } load_errtab[] = { - {L_ERROR_TOOMANY, "too many errors, rest skipped."}, - {L_ERROR_NOLIB, "can't load library:"}, - {L_ERROR_UNDEF, "can't find symbol in library:"}, - {L_ERROR_RLDBAD, - "RLD index out of range or bad relocation type:"}, - {L_ERROR_FORMAT, "not a valid, executable xcoff file:"}, - {L_ERROR_MEMBER, - "file not an archive or does not contain requested member:"}, - {L_ERROR_TYPE, "symbol table mismatch:"}, - {L_ERROR_ALIGN, "text alignment in file is wrong."}, - {L_ERROR_SYSTEM, "System error:"}, - {L_ERROR_ERRNO, NULL} - }; + struct errtab { + int errNo; + char *errstr; + } load_errtab[] = { + {L_ERROR_TOOMANY, "too many errors, rest skipped."}, + {L_ERROR_NOLIB, "can't load library:"}, + {L_ERROR_UNDEF, "can't find symbol in library:"}, + {L_ERROR_RLDBAD, + "RLD index out of range or bad relocation type:"}, + {L_ERROR_FORMAT, "not a valid, executable xcoff file:"}, + {L_ERROR_MEMBER, + "file not an archive or does not contain requested member:"}, + {L_ERROR_TYPE, "symbol table mismatch:"}, + {L_ERROR_ALIGN, "text alignment in file is wrong."}, + {L_ERROR_SYSTEM, "System error:"}, + {L_ERROR_ERRNO, NULL} + }; -#define LOAD_ERRTAB_LEN (sizeof(load_errtab)/sizeof(load_errtab[0])) +#define LOAD_ERRTAB_LEN (sizeof(load_errtab)/sizeof(load_errtab[0])) #define ERRBUF_APPEND(s) strncat(errbuf, s, sizeof(errbuf)-strlen(errbuf)-1) - PyOS_snprintf(errbuf, sizeof(errbuf), "from module %.200s ", pathname); + PyOS_snprintf(errbuf, sizeof(errbuf), "from module %.200s ", pathname); - if (!loadquery(L_GETMESSAGES, &message[0], sizeof(message))) { - ERRBUF_APPEND(strerror(errno)); - ERRBUF_APPEND("\n"); - } - for(i = 0; message[i] && *message[i]; i++) { - int nerr = atoi(message[i]); - for (j=0; j const struct filedescr _PyImport_DynLoadFiletab[] = { - {".so", "rb", C_EXTENSION}, - {"module.so", "rb", C_EXTENSION}, - {0, 0} + {".so", "rb", C_EXTENSION}, + {"module.so", "rb", C_EXTENSION}, + {0, 0} }; /* @@ -29,86 +29,86 @@ #define LINKOPTIONS NSLINKMODULE_OPTION_BINDNOW|NSLINKMODULE_OPTION_RETURN_ON_ERROR #else #define LINKOPTIONS NSLINKMODULE_OPTION_BINDNOW| \ - NSLINKMODULE_OPTION_RETURN_ON_ERROR|NSLINKMODULE_OPTION_PRIVATE + NSLINKMODULE_OPTION_RETURN_ON_ERROR|NSLINKMODULE_OPTION_PRIVATE #endif dl_funcptr _PyImport_GetDynLoadFunc(const char *fqname, const char *shortname, - const char *pathname, FILE *fp) + const char *pathname, FILE *fp) { - dl_funcptr p = NULL; - char funcname[258]; - NSObjectFileImageReturnCode rc; - NSObjectFileImage image; - NSModule newModule; - NSSymbol theSym; - const char *errString; - char errBuf[512]; + dl_funcptr p = NULL; + char funcname[258]; + NSObjectFileImageReturnCode rc; + NSObjectFileImage image; + NSModule newModule; + NSSymbol theSym; + const char *errString; + char errBuf[512]; - PyOS_snprintf(funcname, sizeof(funcname), "_PyInit_%.200s", shortname); + PyOS_snprintf(funcname, sizeof(funcname), "_PyInit_%.200s", shortname); #ifdef USE_DYLD_GLOBAL_NAMESPACE - if (NSIsSymbolNameDefined(funcname)) { - theSym = NSLookupAndBindSymbol(funcname); - p = (dl_funcptr)NSAddressOfSymbol(theSym); - return p; - } + if (NSIsSymbolNameDefined(funcname)) { + theSym = NSLookupAndBindSymbol(funcname); + p = (dl_funcptr)NSAddressOfSymbol(theSym); + return p; + } #endif - rc = NSCreateObjectFileImageFromFile(pathname, &image); - switch(rc) { - default: - case NSObjectFileImageFailure: - case NSObjectFileImageFormat: - /* for these a message is printed on stderr by dyld */ - errString = "Can't create object file image"; - break; - case NSObjectFileImageSuccess: - errString = NULL; - break; - case NSObjectFileImageInappropriateFile: - errString = "Inappropriate file type for dynamic loading"; - break; - case NSObjectFileImageArch: - errString = "Wrong CPU type in object file"; - break; - case NSObjectFileImageAccess: - errString = "Can't read object file (no access)"; - break; - } - if (errString == NULL) { - newModule = NSLinkModule(image, pathname, LINKOPTIONS); - if (newModule == NULL) { - int errNo; - const char *fileName, *moreErrorStr; - NSLinkEditErrors c; - NSLinkEditError( &c, &errNo, &fileName, &moreErrorStr ); - PyOS_snprintf(errBuf, 512, "Failure linking new module: %s: %s", - fileName, moreErrorStr); - errString = errBuf; - } - } - if (errString != NULL) { - PyErr_SetString(PyExc_ImportError, errString); - return NULL; - } + rc = NSCreateObjectFileImageFromFile(pathname, &image); + switch(rc) { + default: + case NSObjectFileImageFailure: + case NSObjectFileImageFormat: + /* for these a message is printed on stderr by dyld */ + errString = "Can't create object file image"; + break; + case NSObjectFileImageSuccess: + errString = NULL; + break; + case NSObjectFileImageInappropriateFile: + errString = "Inappropriate file type for dynamic loading"; + break; + case NSObjectFileImageArch: + errString = "Wrong CPU type in object file"; + break; + case NSObjectFileImageAccess: + errString = "Can't read object file (no access)"; + break; + } + if (errString == NULL) { + newModule = NSLinkModule(image, pathname, LINKOPTIONS); + if (newModule == NULL) { + int errNo; + const char *fileName, *moreErrorStr; + NSLinkEditErrors c; + NSLinkEditError( &c, &errNo, &fileName, &moreErrorStr ); + PyOS_snprintf(errBuf, 512, "Failure linking new module: %s: %s", + fileName, moreErrorStr); + errString = errBuf; + } + } + if (errString != NULL) { + PyErr_SetString(PyExc_ImportError, errString); + return NULL; + } #ifdef USE_DYLD_GLOBAL_NAMESPACE - if (!NSIsSymbolNameDefined(funcname)) { - /* UnlinkModule() isn't implemented in current versions, but calling it does no harm */ - /* NSUnLinkModule(newModule, FALSE); removed: causes problems for ObjC code */ - PyErr_Format(PyExc_ImportError, - "Loaded module does not contain symbol %.200s", - funcname); - return NULL; - } - theSym = NSLookupAndBindSymbol(funcname); + if (!NSIsSymbolNameDefined(funcname)) { + /* UnlinkModule() isn't implemented in current versions, but calling it does no harm */ + /* NSUnLinkModule(newModule, FALSE); removed: causes problems for ObjC code */ + PyErr_Format(PyExc_ImportError, + "Loaded module does not contain symbol %.200s", + funcname); + return NULL; + } + theSym = NSLookupAndBindSymbol(funcname); #else - theSym = NSLookupSymbolInModule(newModule, funcname); - if ( theSym == NULL ) { - /* NSUnLinkModule(newModule, FALSE); removed: causes problems for ObjC code */ - PyErr_Format(PyExc_ImportError, - "Loaded module does not contain symbol %.200s", - funcname); - return NULL; - } + theSym = NSLookupSymbolInModule(newModule, funcname); + if ( theSym == NULL ) { + /* NSUnLinkModule(newModule, FALSE); removed: causes problems for ObjC code */ + PyErr_Format(PyExc_ImportError, + "Loaded module does not contain symbol %.200s", + funcname); + return NULL; + } #endif - p = (dl_funcptr)NSAddressOfSymbol(theSym); - return p; + p = (dl_funcptr)NSAddressOfSymbol(theSym); + return p; } Modified: python/branches/py3k-jit/Python/dynload_os2.c ============================================================================== --- python/branches/py3k-jit/Python/dynload_os2.c (original) +++ python/branches/py3k-jit/Python/dynload_os2.c Mon May 10 23:55:43 2010 @@ -10,37 +10,37 @@ const struct filedescr _PyImport_DynLoadFiletab[] = { - {".pyd", "rb", C_EXTENSION}, - {".dll", "rb", C_EXTENSION}, - {0, 0} + {".pyd", "rb", C_EXTENSION}, + {".dll", "rb", C_EXTENSION}, + {0, 0} }; dl_funcptr _PyImport_GetDynLoadFunc(const char *fqname, const char *shortname, - const char *pathname, FILE *fp) + const char *pathname, FILE *fp) { - dl_funcptr p; - APIRET rc; - HMODULE hDLL; - char failreason[256]; - char funcname[258]; - - rc = DosLoadModule(failreason, - sizeof(failreason), - pathname, - &hDLL); - - if (rc != NO_ERROR) { - char errBuf[256]; - PyOS_snprintf(errBuf, sizeof(errBuf), - "DLL load failed, rc = %d: %.200s", - rc, failreason); - PyErr_SetString(PyExc_ImportError, errBuf); - return NULL; - } - - PyOS_snprintf(funcname, sizeof(funcname), "PyInit_%.200s", shortname); - rc = DosQueryProcAddr(hDLL, 0L, funcname, &p); - if (rc != NO_ERROR) - p = NULL; /* Signify Failure to Acquire Entrypoint */ - return p; + dl_funcptr p; + APIRET rc; + HMODULE hDLL; + char failreason[256]; + char funcname[258]; + + rc = DosLoadModule(failreason, + sizeof(failreason), + pathname, + &hDLL); + + if (rc != NO_ERROR) { + char errBuf[256]; + PyOS_snprintf(errBuf, sizeof(errBuf), + "DLL load failed, rc = %d: %.200s", + rc, failreason); + PyErr_SetString(PyExc_ImportError, errBuf); + return NULL; + } + + PyOS_snprintf(funcname, sizeof(funcname), "PyInit_%.200s", shortname); + rc = DosQueryProcAddr(hDLL, 0L, funcname, &p); + if (rc != NO_ERROR) + p = NULL; /* Signify Failure to Acquire Entrypoint */ + return p; } Modified: python/branches/py3k-jit/Python/dynload_shlib.c ============================================================================== --- python/branches/py3k-jit/Python/dynload_shlib.c (original) +++ python/branches/py3k-jit/Python/dynload_shlib.c Mon May 10 23:55:43 2010 @@ -33,111 +33,111 @@ const struct filedescr _PyImport_DynLoadFiletab[] = { #ifdef __CYGWIN__ - {".dll", "rb", C_EXTENSION}, - {"module.dll", "rb", C_EXTENSION}, + {".dll", "rb", C_EXTENSION}, + {"module.dll", "rb", C_EXTENSION}, #else #if defined(PYOS_OS2) && defined(PYCC_GCC) - {".pyd", "rb", C_EXTENSION}, - {".dll", "rb", C_EXTENSION}, + {".pyd", "rb", C_EXTENSION}, + {".dll", "rb", C_EXTENSION}, #else #ifdef __VMS - {".exe", "rb", C_EXTENSION}, - {".EXE", "rb", C_EXTENSION}, - {"module.exe", "rb", C_EXTENSION}, - {"MODULE.EXE", "rb", C_EXTENSION}, + {".exe", "rb", C_EXTENSION}, + {".EXE", "rb", C_EXTENSION}, + {"module.exe", "rb", C_EXTENSION}, + {"MODULE.EXE", "rb", C_EXTENSION}, #else - {".so", "rb", C_EXTENSION}, - {"module.so", "rb", C_EXTENSION}, + {".so", "rb", C_EXTENSION}, + {"module.so", "rb", C_EXTENSION}, #endif #endif #endif - {0, 0} + {0, 0} }; static struct { - dev_t dev; + dev_t dev; #ifdef __VMS - ino_t ino[3]; + ino_t ino[3]; #else - ino_t ino; + ino_t ino; #endif - void *handle; + void *handle; } handles[128]; static int nhandles = 0; dl_funcptr _PyImport_GetDynLoadFunc(const char *fqname, const char *shortname, - const char *pathname, FILE *fp) + const char *pathname, FILE *fp) { - dl_funcptr p; - void *handle; - char funcname[258]; - char pathbuf[260]; - int dlopenflags=0; - - if (strchr(pathname, '/') == NULL) { - /* Prefix bare filename with "./" */ - PyOS_snprintf(pathbuf, sizeof(pathbuf), "./%-.255s", pathname); - pathname = pathbuf; - } - - PyOS_snprintf(funcname, sizeof(funcname), - LEAD_UNDERSCORE "PyInit_%.200s", shortname); - - if (fp != NULL) { - int i; - struct stat statb; - fstat(fileno(fp), &statb); - for (i = 0; i < nhandles; i++) { - if (statb.st_dev == handles[i].dev && - statb.st_ino == handles[i].ino) { - p = (dl_funcptr) dlsym(handles[i].handle, - funcname); - return p; - } - } - if (nhandles < 128) { - handles[nhandles].dev = statb.st_dev; + dl_funcptr p; + void *handle; + char funcname[258]; + char pathbuf[260]; + int dlopenflags=0; + + if (strchr(pathname, '/') == NULL) { + /* Prefix bare filename with "./" */ + PyOS_snprintf(pathbuf, sizeof(pathbuf), "./%-.255s", pathname); + pathname = pathbuf; + } + + PyOS_snprintf(funcname, sizeof(funcname), + LEAD_UNDERSCORE "PyInit_%.200s", shortname); + + if (fp != NULL) { + int i; + struct stat statb; + fstat(fileno(fp), &statb); + for (i = 0; i < nhandles; i++) { + if (statb.st_dev == handles[i].dev && + statb.st_ino == handles[i].ino) { + p = (dl_funcptr) dlsym(handles[i].handle, + funcname); + return p; + } + } + if (nhandles < 128) { + handles[nhandles].dev = statb.st_dev; #ifdef __VMS - handles[nhandles].ino[0] = statb.st_ino[0]; - handles[nhandles].ino[1] = statb.st_ino[1]; - handles[nhandles].ino[2] = statb.st_ino[2]; + handles[nhandles].ino[0] = statb.st_ino[0]; + handles[nhandles].ino[1] = statb.st_ino[1]; + handles[nhandles].ino[2] = statb.st_ino[2]; #else - handles[nhandles].ino = statb.st_ino; + handles[nhandles].ino = statb.st_ino; #endif - } - } + } + } #if !(defined(PYOS_OS2) && defined(PYCC_GCC)) - dlopenflags = PyThreadState_GET()->interp->dlopenflags; + dlopenflags = PyThreadState_GET()->interp->dlopenflags; #endif - if (Py_VerboseFlag) - PySys_WriteStderr("dlopen(\"%s\", %x);\n", pathname, - dlopenflags); + if (Py_VerboseFlag) + PySys_WriteStderr("dlopen(\"%s\", %x);\n", pathname, + dlopenflags); #ifdef __VMS - /* VMS currently don't allow a pathname, use a logical name instead */ - /* Concatenate 'python_module_' and shortname */ - /* so "import vms.bar" will use the logical python_module_bar */ - /* As C module use only one name space this is probably not a */ - /* important limitation */ - PyOS_snprintf(pathbuf, sizeof(pathbuf), "python_module_%-.200s", - shortname); - pathname = pathbuf; -#endif - - handle = dlopen(pathname, dlopenflags); - - if (handle == NULL) { - const char *error = dlerror(); - if (error == NULL) - error = "unknown dlopen() error"; - PyErr_SetString(PyExc_ImportError, error); - return NULL; - } - if (fp != NULL && nhandles < 128) - handles[nhandles++].handle = handle; - p = (dl_funcptr) dlsym(handle, funcname); - return p; + /* VMS currently don't allow a pathname, use a logical name instead */ + /* Concatenate 'python_module_' and shortname */ + /* so "import vms.bar" will use the logical python_module_bar */ + /* As C module use only one name space this is probably not a */ + /* important limitation */ + PyOS_snprintf(pathbuf, sizeof(pathbuf), "python_module_%-.200s", + shortname); + pathname = pathbuf; +#endif + + handle = dlopen(pathname, dlopenflags); + + if (handle == NULL) { + const char *error = dlerror(); + if (error == NULL) + error = "unknown dlopen() error"; + PyErr_SetString(PyExc_ImportError, error); + return NULL; + } + if (fp != NULL && nhandles < 128) + handles[nhandles++].handle = handle; + p = (dl_funcptr) dlsym(handle, funcname); + return p; } Modified: python/branches/py3k-jit/Python/dynload_win.c ============================================================================== --- python/branches/py3k-jit/Python/dynload_win.c (original) +++ python/branches/py3k-jit/Python/dynload_win.c Mon May 10 23:55:43 2010 @@ -17,11 +17,11 @@ const struct filedescr _PyImport_DynLoadFiletab[] = { #ifdef _DEBUG - {"_d.pyd", "rb", C_EXTENSION}, + {"_d.pyd", "rb", C_EXTENSION}, #else - {".pyd", "rb", C_EXTENSION}, + {".pyd", "rb", C_EXTENSION}, #endif - {0, 0} + {0, 0} }; @@ -29,18 +29,18 @@ C RTL implementations */ static int strcasecmp (char *string1, char *string2) -{ - int first, second; +{ + int first, second; - do { - first = tolower(*string1); - second = tolower(*string2); - string1++; - string2++; - } while (first && first == second); + do { + first = tolower(*string1); + second = tolower(*string2); + string1++; + string2++; + } while (first && first == second); - return (first - second); -} + return (first - second); +} /* Function to return the name of the "python" DLL that the supplied module @@ -66,213 +66,213 @@ static char *GetPythonImport (HINSTANCE hModule) { - unsigned char *dllbase, *import_data, *import_name; - DWORD pe_offset, opt_offset; - WORD opt_magic; - int num_dict_off, import_off; - - /* Safety check input */ - if (hModule == NULL) { - return NULL; - } - - /* Module instance is also the base load address. First portion of - memory is the MS-DOS loader, which holds the offset to the PE - header (from the load base) at 0x3C */ - dllbase = (unsigned char *)hModule; - pe_offset = DWORD_AT(dllbase + 0x3C); - - /* The PE signature must be "PE\0\0" */ - if (memcmp(dllbase+pe_offset,"PE\0\0",4)) { - return NULL; - } - - /* Following the PE signature is the standard COFF header (20 - bytes) and then the optional header. The optional header starts - with a magic value of 0x10B for PE32 or 0x20B for PE32+ (PE32+ - uses 64-bits for some fields). It might also be 0x107 for a ROM - image, but we don't process that here. - - The optional header ends with a data dictionary that directly - points to certain types of data, among them the import entries - (in the second table entry). Based on the header type, we - determine offsets for the data dictionary count and the entry - within the dictionary pointing to the imports. */ - - opt_offset = pe_offset + 4 + 20; - opt_magic = WORD_AT(dllbase+opt_offset); - if (opt_magic == 0x10B) { - /* PE32 */ - num_dict_off = 92; - import_off = 104; - } else if (opt_magic == 0x20B) { - /* PE32+ */ - num_dict_off = 108; - import_off = 120; - } else { - /* Unsupported */ - return NULL; - } - - /* Now if an import table exists, offset to it and walk the list of - imports. The import table is an array (ending when an entry has - empty values) of structures (20 bytes each), which contains (at - offset 12) a relative address (to the module base) at which a - string constant holding the import name is located. */ - - if (DWORD_AT(dllbase + opt_offset + num_dict_off) >= 2) { - /* We have at least 2 tables - the import table is the second - one. But still it may be that the table size is zero */ - if (0 == DWORD_AT(dllbase + opt_offset + import_off + sizeof(DWORD))) - return NULL; - import_data = dllbase + DWORD_AT(dllbase + - opt_offset + - import_off); - while (DWORD_AT(import_data)) { - import_name = dllbase + DWORD_AT(import_data+12); - if (strlen(import_name) >= 6 && - !strncmp(import_name,"python",6)) { - char *pch; - - /* Ensure python prefix is followed only - by numbers to the end of the basename */ - pch = import_name + 6; + unsigned char *dllbase, *import_data, *import_name; + DWORD pe_offset, opt_offset; + WORD opt_magic; + int num_dict_off, import_off; + + /* Safety check input */ + if (hModule == NULL) { + return NULL; + } + + /* Module instance is also the base load address. First portion of + memory is the MS-DOS loader, which holds the offset to the PE + header (from the load base) at 0x3C */ + dllbase = (unsigned char *)hModule; + pe_offset = DWORD_AT(dllbase + 0x3C); + + /* The PE signature must be "PE\0\0" */ + if (memcmp(dllbase+pe_offset,"PE\0\0",4)) { + return NULL; + } + + /* Following the PE signature is the standard COFF header (20 + bytes) and then the optional header. The optional header starts + with a magic value of 0x10B for PE32 or 0x20B for PE32+ (PE32+ + uses 64-bits for some fields). It might also be 0x107 for a ROM + image, but we don't process that here. + + The optional header ends with a data dictionary that directly + points to certain types of data, among them the import entries + (in the second table entry). Based on the header type, we + determine offsets for the data dictionary count and the entry + within the dictionary pointing to the imports. */ + + opt_offset = pe_offset + 4 + 20; + opt_magic = WORD_AT(dllbase+opt_offset); + if (opt_magic == 0x10B) { + /* PE32 */ + num_dict_off = 92; + import_off = 104; + } else if (opt_magic == 0x20B) { + /* PE32+ */ + num_dict_off = 108; + import_off = 120; + } else { + /* Unsupported */ + return NULL; + } + + /* Now if an import table exists, offset to it and walk the list of + imports. The import table is an array (ending when an entry has + empty values) of structures (20 bytes each), which contains (at + offset 12) a relative address (to the module base) at which a + string constant holding the import name is located. */ + + if (DWORD_AT(dllbase + opt_offset + num_dict_off) >= 2) { + /* We have at least 2 tables - the import table is the second + one. But still it may be that the table size is zero */ + if (0 == DWORD_AT(dllbase + opt_offset + import_off + sizeof(DWORD))) + return NULL; + import_data = dllbase + DWORD_AT(dllbase + + opt_offset + + import_off); + while (DWORD_AT(import_data)) { + import_name = dllbase + DWORD_AT(import_data+12); + if (strlen(import_name) >= 6 && + !strncmp(import_name,"python",6)) { + char *pch; + + /* Ensure python prefix is followed only + by numbers to the end of the basename */ + pch = import_name + 6; #ifdef _DEBUG - while (*pch && pch[0] != '_' && pch[1] != 'd' && pch[2] != '.') { + while (*pch && pch[0] != '_' && pch[1] != 'd' && pch[2] != '.') { #else - while (*pch && *pch != '.') { + while (*pch && *pch != '.') { #endif - if (*pch >= '0' && *pch <= '9') { - pch++; - } else { - pch = NULL; - break; - } - } - - if (pch) { - /* Found it - return the name */ - return import_name; - } - } - import_data += 20; - } - } + if (*pch >= '0' && *pch <= '9') { + pch++; + } else { + pch = NULL; + break; + } + } + + if (pch) { + /* Found it - return the name */ + return import_name; + } + } + import_data += 20; + } + } - return NULL; + return NULL; } dl_funcptr _PyImport_GetDynLoadFunc(const char *fqname, const char *shortname, - const char *pathname, FILE *fp) + const char *pathname, FILE *fp) { - dl_funcptr p; - char funcname[258], *import_python; + dl_funcptr p; + char funcname[258], *import_python; - PyOS_snprintf(funcname, sizeof(funcname), "PyInit_%.200s", shortname); + PyOS_snprintf(funcname, sizeof(funcname), "PyInit_%.200s", shortname); - { - HINSTANCE hDLL = NULL; - char pathbuf[260]; - LPTSTR dummy; - unsigned int old_mode; - ULONG_PTR cookie = 0; - /* We use LoadLibraryEx so Windows looks for dependent DLLs - in directory of pathname first. However, Windows95 - can sometimes not work correctly unless the absolute - path is used. If GetFullPathName() fails, the LoadLibrary - will certainly fail too, so use its error code */ - - /* Don't display a message box when Python can't load a DLL */ - old_mode = SetErrorMode(SEM_FAILCRITICALERRORS); - - if (GetFullPathName(pathname, - sizeof(pathbuf), - pathbuf, - &dummy)) { - ULONG_PTR cookie = _Py_ActivateActCtx(); - /* XXX This call doesn't exist in Windows CE */ - hDLL = LoadLibraryEx(pathname, NULL, - LOAD_WITH_ALTERED_SEARCH_PATH); - _Py_DeactivateActCtx(cookie); - } - - /* restore old error mode settings */ - SetErrorMode(old_mode); - - if (hDLL==NULL){ - PyObject *message; - unsigned int errorCode; - - /* Get an error string from Win32 error code */ - wchar_t theInfo[256]; /* Pointer to error text - from system */ - int theLength; /* Length of error text */ - - errorCode = GetLastError(); - - theLength = FormatMessageW( - FORMAT_MESSAGE_FROM_SYSTEM | - FORMAT_MESSAGE_IGNORE_INSERTS, /* flags */ - NULL, /* message source */ - errorCode, /* the message (error) ID */ - MAKELANGID(LANG_NEUTRAL, - SUBLANG_DEFAULT), - /* Default language */ - theInfo, /* the buffer */ - sizeof(theInfo), /* the buffer size */ - NULL); /* no additional format args. */ - - /* Problem: could not get the error message. - This should not happen if called correctly. */ - if (theLength == 0) { - message = PyUnicode_FromFormat( - "DLL load failed with error code %d", - errorCode); - } else { - /* For some reason a \r\n - is appended to the text */ - if (theLength >= 2 && - theInfo[theLength-2] == '\r' && - theInfo[theLength-1] == '\n') { - theLength -= 2; - theInfo[theLength] = '\0'; - } - message = PyUnicode_FromString( - "DLL load failed: "); - - PyUnicode_AppendAndDel(&message, - PyUnicode_FromUnicode( - theInfo, - theLength)); - } - PyErr_SetObject(PyExc_ImportError, message); - Py_XDECREF(message); - return NULL; - } else { - char buffer[256]; + { + HINSTANCE hDLL = NULL; + char pathbuf[260]; + LPTSTR dummy; + unsigned int old_mode; + ULONG_PTR cookie = 0; + /* We use LoadLibraryEx so Windows looks for dependent DLLs + in directory of pathname first. However, Windows95 + can sometimes not work correctly unless the absolute + path is used. If GetFullPathName() fails, the LoadLibrary + will certainly fail too, so use its error code */ + + /* Don't display a message box when Python can't load a DLL */ + old_mode = SetErrorMode(SEM_FAILCRITICALERRORS); + + if (GetFullPathName(pathname, + sizeof(pathbuf), + pathbuf, + &dummy)) { + ULONG_PTR cookie = _Py_ActivateActCtx(); + /* XXX This call doesn't exist in Windows CE */ + hDLL = LoadLibraryEx(pathname, NULL, + LOAD_WITH_ALTERED_SEARCH_PATH); + _Py_DeactivateActCtx(cookie); + } + + /* restore old error mode settings */ + SetErrorMode(old_mode); + + if (hDLL==NULL){ + PyObject *message; + unsigned int errorCode; + + /* Get an error string from Win32 error code */ + wchar_t theInfo[256]; /* Pointer to error text + from system */ + int theLength; /* Length of error text */ + + errorCode = GetLastError(); + + theLength = FormatMessageW( + FORMAT_MESSAGE_FROM_SYSTEM | + FORMAT_MESSAGE_IGNORE_INSERTS, /* flags */ + NULL, /* message source */ + errorCode, /* the message (error) ID */ + MAKELANGID(LANG_NEUTRAL, + SUBLANG_DEFAULT), + /* Default language */ + theInfo, /* the buffer */ + sizeof(theInfo), /* the buffer size */ + NULL); /* no additional format args. */ + + /* Problem: could not get the error message. + This should not happen if called correctly. */ + if (theLength == 0) { + message = PyUnicode_FromFormat( + "DLL load failed with error code %d", + errorCode); + } else { + /* For some reason a \r\n + is appended to the text */ + if (theLength >= 2 && + theInfo[theLength-2] == '\r' && + theInfo[theLength-1] == '\n') { + theLength -= 2; + theInfo[theLength] = '\0'; + } + message = PyUnicode_FromString( + "DLL load failed: "); + + PyUnicode_AppendAndDel(&message, + PyUnicode_FromUnicode( + theInfo, + theLength)); + } + PyErr_SetObject(PyExc_ImportError, message); + Py_XDECREF(message); + return NULL; + } else { + char buffer[256]; #ifdef _DEBUG - PyOS_snprintf(buffer, sizeof(buffer), "python%d%d_d.dll", + PyOS_snprintf(buffer, sizeof(buffer), "python%d%d_d.dll", #else - PyOS_snprintf(buffer, sizeof(buffer), "python%d%d.dll", + PyOS_snprintf(buffer, sizeof(buffer), "python%d%d.dll", #endif - PY_MAJOR_VERSION,PY_MINOR_VERSION); - import_python = GetPythonImport(hDLL); + PY_MAJOR_VERSION,PY_MINOR_VERSION); + import_python = GetPythonImport(hDLL); - if (import_python && - strcasecmp(buffer,import_python)) { - PyOS_snprintf(buffer, sizeof(buffer), - "Module use of %.150s conflicts " - "with this version of Python.", - import_python); - PyErr_SetString(PyExc_ImportError,buffer); - FreeLibrary(hDLL); - return NULL; - } - } - p = GetProcAddress(hDLL, funcname); - } + if (import_python && + strcasecmp(buffer,import_python)) { + PyOS_snprintf(buffer, sizeof(buffer), + "Module use of %.150s conflicts " + "with this version of Python.", + import_python); + PyErr_SetString(PyExc_ImportError,buffer); + FreeLibrary(hDLL); + return NULL; + } + } + p = GetProcAddress(hDLL, funcname); + } - return p; + return p; } Modified: python/branches/py3k-jit/Python/errors.c ============================================================================== --- python/branches/py3k-jit/Python/errors.c (original) +++ python/branches/py3k-jit/Python/errors.c Mon May 10 23:55:43 2010 @@ -24,166 +24,166 @@ void PyErr_Restore(PyObject *type, PyObject *value, PyObject *traceback) { - PyThreadState *tstate = PyThreadState_GET(); - PyObject *oldtype, *oldvalue, *oldtraceback; + PyThreadState *tstate = PyThreadState_GET(); + PyObject *oldtype, *oldvalue, *oldtraceback; - if (traceback != NULL && !PyTraceBack_Check(traceback)) { - /* XXX Should never happen -- fatal error instead? */ - /* Well, it could be None. */ - Py_DECREF(traceback); - traceback = NULL; - } - - /* Save these in locals to safeguard against recursive - invocation through Py_XDECREF */ - oldtype = tstate->curexc_type; - oldvalue = tstate->curexc_value; - oldtraceback = tstate->curexc_traceback; - - tstate->curexc_type = type; - tstate->curexc_value = value; - tstate->curexc_traceback = traceback; - - Py_XDECREF(oldtype); - Py_XDECREF(oldvalue); - Py_XDECREF(oldtraceback); + if (traceback != NULL && !PyTraceBack_Check(traceback)) { + /* XXX Should never happen -- fatal error instead? */ + /* Well, it could be None. */ + Py_DECREF(traceback); + traceback = NULL; + } + + /* Save these in locals to safeguard against recursive + invocation through Py_XDECREF */ + oldtype = tstate->curexc_type; + oldvalue = tstate->curexc_value; + oldtraceback = tstate->curexc_traceback; + + tstate->curexc_type = type; + tstate->curexc_value = value; + tstate->curexc_traceback = traceback; + + Py_XDECREF(oldtype); + Py_XDECREF(oldvalue); + Py_XDECREF(oldtraceback); } void PyErr_SetObject(PyObject *exception, PyObject *value) { - PyThreadState *tstate = PyThreadState_GET(); - PyObject *exc_value; - PyObject *tb = NULL; - - if (exception != NULL && - !PyExceptionClass_Check(exception)) { - PyErr_Format(PyExc_SystemError, - "exception %R not a BaseException subclass", - exception); - return; - } - Py_XINCREF(value); - exc_value = tstate->exc_value; - if (exc_value != NULL && exc_value != Py_None) { - /* Implicit exception chaining */ - Py_INCREF(exc_value); - if (value == NULL || !PyExceptionInstance_Check(value)) { - /* We must normalize the value right now */ - PyObject *args, *fixed_value; - if (value == NULL || value == Py_None) - args = PyTuple_New(0); - else if (PyTuple_Check(value)) { - Py_INCREF(value); - args = value; - } - else - args = PyTuple_Pack(1, value); - fixed_value = args ? - PyEval_CallObject(exception, args) : NULL; - Py_XDECREF(args); - Py_XDECREF(value); - if (fixed_value == NULL) - return; - value = fixed_value; - } - /* Avoid reference cycles through the context chain. - This is O(chain length) but context chains are - usually very short. Sensitive readers may try - to inline the call to PyException_GetContext. */ - if (exc_value != value) { - PyObject *o = exc_value, *context; - while ((context = PyException_GetContext(o))) { - Py_DECREF(context); - if (context == value) { - PyException_SetContext(o, NULL); - break; - } - o = context; - } - PyException_SetContext(value, exc_value); - } else { - Py_DECREF(exc_value); - } - } - if (value != NULL && PyExceptionInstance_Check(value)) - tb = PyException_GetTraceback(value); - Py_XINCREF(exception); - PyErr_Restore(exception, value, tb); + PyThreadState *tstate = PyThreadState_GET(); + PyObject *exc_value; + PyObject *tb = NULL; + + if (exception != NULL && + !PyExceptionClass_Check(exception)) { + PyErr_Format(PyExc_SystemError, + "exception %R not a BaseException subclass", + exception); + return; + } + Py_XINCREF(value); + exc_value = tstate->exc_value; + if (exc_value != NULL && exc_value != Py_None) { + /* Implicit exception chaining */ + Py_INCREF(exc_value); + if (value == NULL || !PyExceptionInstance_Check(value)) { + /* We must normalize the value right now */ + PyObject *args, *fixed_value; + if (value == NULL || value == Py_None) + args = PyTuple_New(0); + else if (PyTuple_Check(value)) { + Py_INCREF(value); + args = value; + } + else + args = PyTuple_Pack(1, value); + fixed_value = args ? + PyEval_CallObject(exception, args) : NULL; + Py_XDECREF(args); + Py_XDECREF(value); + if (fixed_value == NULL) + return; + value = fixed_value; + } + /* Avoid reference cycles through the context chain. + This is O(chain length) but context chains are + usually very short. Sensitive readers may try + to inline the call to PyException_GetContext. */ + if (exc_value != value) { + PyObject *o = exc_value, *context; + while ((context = PyException_GetContext(o))) { + Py_DECREF(context); + if (context == value) { + PyException_SetContext(o, NULL); + break; + } + o = context; + } + PyException_SetContext(value, exc_value); + } else { + Py_DECREF(exc_value); + } + } + if (value != NULL && PyExceptionInstance_Check(value)) + tb = PyException_GetTraceback(value); + Py_XINCREF(exception); + PyErr_Restore(exception, value, tb); } void PyErr_SetNone(PyObject *exception) { - PyErr_SetObject(exception, (PyObject *)NULL); + PyErr_SetObject(exception, (PyObject *)NULL); } void PyErr_SetString(PyObject *exception, const char *string) { - PyObject *value = PyUnicode_FromString(string); - PyErr_SetObject(exception, value); - Py_XDECREF(value); + PyObject *value = PyUnicode_FromString(string); + PyErr_SetObject(exception, value); + Py_XDECREF(value); } PyObject * PyErr_Occurred(void) { - PyThreadState *tstate = PyThreadState_GET(); + PyThreadState *tstate = PyThreadState_GET(); - return tstate->curexc_type; + return tstate->curexc_type; } int PyErr_GivenExceptionMatches(PyObject *err, PyObject *exc) { - if (err == NULL || exc == NULL) { - /* maybe caused by "import exceptions" that failed early on */ - return 0; - } - if (PyTuple_Check(exc)) { - Py_ssize_t i, n; - n = PyTuple_Size(exc); - for (i = 0; i < n; i++) { - /* Test recursively */ - if (PyErr_GivenExceptionMatches( - err, PyTuple_GET_ITEM(exc, i))) - { - return 1; - } - } - return 0; - } - /* err might be an instance, so check its class. */ - if (PyExceptionInstance_Check(err)) - err = PyExceptionInstance_Class(err); - - if (PyExceptionClass_Check(err) && PyExceptionClass_Check(exc)) { - int res = 0; - PyObject *exception, *value, *tb; - PyErr_Fetch(&exception, &value, &tb); - /* PyObject_IsSubclass() can recurse and therefore is - not safe (see test_bad_getattr in test.pickletester). */ - res = PyType_IsSubtype((PyTypeObject *)err, (PyTypeObject *)exc); - /* This function must not fail, so print the error here */ - if (res == -1) { - PyErr_WriteUnraisable(err); - res = 0; - } - PyErr_Restore(exception, value, tb); - return res; - } + if (err == NULL || exc == NULL) { + /* maybe caused by "import exceptions" that failed early on */ + return 0; + } + if (PyTuple_Check(exc)) { + Py_ssize_t i, n; + n = PyTuple_Size(exc); + for (i = 0; i < n; i++) { + /* Test recursively */ + if (PyErr_GivenExceptionMatches( + err, PyTuple_GET_ITEM(exc, i))) + { + return 1; + } + } + return 0; + } + /* err might be an instance, so check its class. */ + if (PyExceptionInstance_Check(err)) + err = PyExceptionInstance_Class(err); + + if (PyExceptionClass_Check(err) && PyExceptionClass_Check(exc)) { + int res = 0; + PyObject *exception, *value, *tb; + PyErr_Fetch(&exception, &value, &tb); + /* PyObject_IsSubclass() can recurse and therefore is + not safe (see test_bad_getattr in test.pickletester). */ + res = PyType_IsSubtype((PyTypeObject *)err, (PyTypeObject *)exc); + /* This function must not fail, so print the error here */ + if (res == -1) { + PyErr_WriteUnraisable(err); + res = 0; + } + PyErr_Restore(exception, value, tb); + return res; + } - return err == exc; + return err == exc; } int PyErr_ExceptionMatches(PyObject *exc) { - return PyErr_GivenExceptionMatches(PyErr_Occurred(), exc); + return PyErr_GivenExceptionMatches(PyErr_Occurred(), exc); } @@ -191,128 +191,128 @@ eval_code2(), do_raise(), and PyErr_Print() XXX: should PyErr_NormalizeException() also call - PyException_SetTraceback() with the resulting value and tb? + PyException_SetTraceback() with the resulting value and tb? */ void PyErr_NormalizeException(PyObject **exc, PyObject **val, PyObject **tb) { - PyObject *type = *exc; - PyObject *value = *val; - PyObject *inclass = NULL; - PyObject *initial_tb = NULL; - PyThreadState *tstate = NULL; - - if (type == NULL) { - /* There was no exception, so nothing to do. */ - return; - } - - /* If PyErr_SetNone() was used, the value will have been actually - set to NULL. - */ - if (!value) { - value = Py_None; - Py_INCREF(value); - } - - if (PyExceptionInstance_Check(value)) - inclass = PyExceptionInstance_Class(value); - - /* Normalize the exception so that if the type is a class, the - value will be an instance. - */ - if (PyExceptionClass_Check(type)) { - /* if the value was not an instance, or is not an instance - whose class is (or is derived from) type, then use the - value as an argument to instantiation of the type - class. - */ - if (!inclass || !PyObject_IsSubclass(inclass, type)) { - PyObject *args, *res; - - if (value == Py_None) - args = PyTuple_New(0); - else if (PyTuple_Check(value)) { - Py_INCREF(value); - args = value; - } - else - args = PyTuple_Pack(1, value); - - if (args == NULL) - goto finally; - res = PyEval_CallObject(type, args); - Py_DECREF(args); - if (res == NULL) - goto finally; - Py_DECREF(value); - value = res; - } - /* if the class of the instance doesn't exactly match the - class of the type, believe the instance - */ - else if (inclass != type) { - Py_DECREF(type); - type = inclass; - Py_INCREF(type); - } - } - *exc = type; - *val = value; - return; + PyObject *type = *exc; + PyObject *value = *val; + PyObject *inclass = NULL; + PyObject *initial_tb = NULL; + PyThreadState *tstate = NULL; + + if (type == NULL) { + /* There was no exception, so nothing to do. */ + return; + } + + /* If PyErr_SetNone() was used, the value will have been actually + set to NULL. + */ + if (!value) { + value = Py_None; + Py_INCREF(value); + } + + if (PyExceptionInstance_Check(value)) + inclass = PyExceptionInstance_Class(value); + + /* Normalize the exception so that if the type is a class, the + value will be an instance. + */ + if (PyExceptionClass_Check(type)) { + /* if the value was not an instance, or is not an instance + whose class is (or is derived from) type, then use the + value as an argument to instantiation of the type + class. + */ + if (!inclass || !PyObject_IsSubclass(inclass, type)) { + PyObject *args, *res; + + if (value == Py_None) + args = PyTuple_New(0); + else if (PyTuple_Check(value)) { + Py_INCREF(value); + args = value; + } + else + args = PyTuple_Pack(1, value); + + if (args == NULL) + goto finally; + res = PyEval_CallObject(type, args); + Py_DECREF(args); + if (res == NULL) + goto finally; + Py_DECREF(value); + value = res; + } + /* if the class of the instance doesn't exactly match the + class of the type, believe the instance + */ + else if (inclass != type) { + Py_DECREF(type); + type = inclass; + Py_INCREF(type); + } + } + *exc = type; + *val = value; + return; finally: - Py_DECREF(type); - Py_DECREF(value); - /* If the new exception doesn't set a traceback and the old - exception had a traceback, use the old traceback for the - new exception. It's better than nothing. - */ - initial_tb = *tb; - PyErr_Fetch(exc, val, tb); - if (initial_tb != NULL) { - if (*tb == NULL) - *tb = initial_tb; - else - Py_DECREF(initial_tb); - } - /* normalize recursively */ - tstate = PyThreadState_GET(); - if (++tstate->recursion_depth > Py_GetRecursionLimit()) { - --tstate->recursion_depth; - /* throw away the old exception... */ - Py_DECREF(*exc); - Py_DECREF(*val); - /* ... and use the recursion error instead */ - *exc = PyExc_RuntimeError; - *val = PyExc_RecursionErrorInst; - Py_INCREF(*exc); - Py_INCREF(*val); - /* just keeping the old traceback */ - return; - } - PyErr_NormalizeException(exc, val, tb); - --tstate->recursion_depth; + Py_DECREF(type); + Py_DECREF(value); + /* If the new exception doesn't set a traceback and the old + exception had a traceback, use the old traceback for the + new exception. It's better than nothing. + */ + initial_tb = *tb; + PyErr_Fetch(exc, val, tb); + if (initial_tb != NULL) { + if (*tb == NULL) + *tb = initial_tb; + else + Py_DECREF(initial_tb); + } + /* normalize recursively */ + tstate = PyThreadState_GET(); + if (++tstate->recursion_depth > Py_GetRecursionLimit()) { + --tstate->recursion_depth; + /* throw away the old exception... */ + Py_DECREF(*exc); + Py_DECREF(*val); + /* ... and use the recursion error instead */ + *exc = PyExc_RuntimeError; + *val = PyExc_RecursionErrorInst; + Py_INCREF(*exc); + Py_INCREF(*val); + /* just keeping the old traceback */ + return; + } + PyErr_NormalizeException(exc, val, tb); + --tstate->recursion_depth; } void PyErr_Fetch(PyObject **p_type, PyObject **p_value, PyObject **p_traceback) { - PyThreadState *tstate = PyThreadState_GET(); + PyThreadState *tstate = PyThreadState_GET(); - *p_type = tstate->curexc_type; - *p_value = tstate->curexc_value; - *p_traceback = tstate->curexc_traceback; - - tstate->curexc_type = NULL; - tstate->curexc_value = NULL; - tstate->curexc_traceback = NULL; + *p_type = tstate->curexc_type; + *p_value = tstate->curexc_value; + *p_traceback = tstate->curexc_traceback; + + tstate->curexc_type = NULL; + tstate->curexc_value = NULL; + tstate->curexc_traceback = NULL; } void PyErr_Clear(void) { - PyErr_Restore(NULL, NULL, NULL); + PyErr_Restore(NULL, NULL, NULL); } /* Convenience functions to set a type error exception and return 0 */ @@ -320,284 +320,284 @@ int PyErr_BadArgument(void) { - PyErr_SetString(PyExc_TypeError, - "bad argument type for built-in operation"); - return 0; + PyErr_SetString(PyExc_TypeError, + "bad argument type for built-in operation"); + return 0; } PyObject * PyErr_NoMemory(void) { - if (PyErr_ExceptionMatches(PyExc_MemoryError)) - /* already current */ - return NULL; - - /* raise the pre-allocated instance if it still exists */ - if (PyExc_MemoryErrorInst) - { - /* Clear the previous traceback, otherwise it will be appended - * to the current one. - * - * The following statement is not likely to raise any error; - * if it does, we simply discard it. - */ - PyException_SetTraceback(PyExc_MemoryErrorInst, Py_None); - - PyErr_SetObject(PyExc_MemoryError, PyExc_MemoryErrorInst); - } - else - /* this will probably fail since there's no memory and hee, - hee, we have to instantiate this class - */ - PyErr_SetNone(PyExc_MemoryError); + if (PyErr_ExceptionMatches(PyExc_MemoryError)) + /* already current */ + return NULL; + + /* raise the pre-allocated instance if it still exists */ + if (PyExc_MemoryErrorInst) + { + /* Clear the previous traceback, otherwise it will be appended + * to the current one. + * + * The following statement is not likely to raise any error; + * if it does, we simply discard it. + */ + PyException_SetTraceback(PyExc_MemoryErrorInst, Py_None); + + PyErr_SetObject(PyExc_MemoryError, PyExc_MemoryErrorInst); + } + else + /* this will probably fail since there's no memory and hee, + hee, we have to instantiate this class + */ + PyErr_SetNone(PyExc_MemoryError); - return NULL; + return NULL; } PyObject * PyErr_SetFromErrnoWithFilenameObject(PyObject *exc, PyObject *filenameObject) { - PyObject *message; - PyObject *v; - int i = errno; + PyObject *message; + PyObject *v; + int i = errno; #ifndef MS_WINDOWS - char *s; + char *s; #else - WCHAR *s_buf = NULL; + WCHAR *s_buf = NULL; #endif /* Unix/Windows */ #ifdef EINTR - if (i == EINTR && PyErr_CheckSignals()) - return NULL; + if (i == EINTR && PyErr_CheckSignals()) + return NULL; #endif #ifndef MS_WINDOWS - if (i == 0) - s = "Error"; /* Sometimes errno didn't get set */ - else - s = strerror(i); - message = PyUnicode_DecodeUTF8(s, strlen(s), "ignore"); + if (i == 0) + s = "Error"; /* Sometimes errno didn't get set */ + else + s = strerror(i); + message = PyUnicode_DecodeUTF8(s, strlen(s), "ignore"); #else - if (i == 0) - message = PyUnicode_FromString("Error"); /* Sometimes errno didn't get set */ - else - { - /* Note that the Win32 errors do not lineup with the - errno error. So if the error is in the MSVC error - table, we use it, otherwise we assume it really _is_ - a Win32 error code - */ - if (i > 0 && i < _sys_nerr) { - message = PyUnicode_FromString(_sys_errlist[i]); - } - else { - int len = FormatMessageW( - FORMAT_MESSAGE_ALLOCATE_BUFFER | - FORMAT_MESSAGE_FROM_SYSTEM | - FORMAT_MESSAGE_IGNORE_INSERTS, - NULL, /* no message source */ - i, - MAKELANGID(LANG_NEUTRAL, - SUBLANG_DEFAULT), - /* Default language */ - (LPWSTR) &s_buf, - 0, /* size not used */ - NULL); /* no args */ - if (len==0) { - /* Only ever seen this in out-of-mem - situations */ - s_buf = NULL; - message = PyUnicode_FromFormat("Windows Error 0x%X", i); - } else { - /* remove trailing cr/lf and dots */ - while (len > 0 && (s_buf[len-1] <= L' ' || s_buf[len-1] == L'.')) - s_buf[--len] = L'\0'; - message = PyUnicode_FromUnicode(s_buf, len); - } - } - } + if (i == 0) + message = PyUnicode_FromString("Error"); /* Sometimes errno didn't get set */ + else + { + /* Note that the Win32 errors do not lineup with the + errno error. So if the error is in the MSVC error + table, we use it, otherwise we assume it really _is_ + a Win32 error code + */ + if (i > 0 && i < _sys_nerr) { + message = PyUnicode_FromString(_sys_errlist[i]); + } + else { + int len = FormatMessageW( + FORMAT_MESSAGE_ALLOCATE_BUFFER | + FORMAT_MESSAGE_FROM_SYSTEM | + FORMAT_MESSAGE_IGNORE_INSERTS, + NULL, /* no message source */ + i, + MAKELANGID(LANG_NEUTRAL, + SUBLANG_DEFAULT), + /* Default language */ + (LPWSTR) &s_buf, + 0, /* size not used */ + NULL); /* no args */ + if (len==0) { + /* Only ever seen this in out-of-mem + situations */ + s_buf = NULL; + message = PyUnicode_FromFormat("Windows Error 0x%X", i); + } else { + /* remove trailing cr/lf and dots */ + while (len > 0 && (s_buf[len-1] <= L' ' || s_buf[len-1] == L'.')) + s_buf[--len] = L'\0'; + message = PyUnicode_FromUnicode(s_buf, len); + } + } + } #endif /* Unix/Windows */ - if (message == NULL) - { + if (message == NULL) + { #ifdef MS_WINDOWS - LocalFree(s_buf); + LocalFree(s_buf); #endif - return NULL; - } + return NULL; + } - if (filenameObject != NULL) - v = Py_BuildValue("(iOO)", i, message, filenameObject); - else - v = Py_BuildValue("(iO)", i, message); - Py_DECREF(message); - - if (v != NULL) { - PyErr_SetObject(exc, v); - Py_DECREF(v); - } + if (filenameObject != NULL) + v = Py_BuildValue("(iOO)", i, message, filenameObject); + else + v = Py_BuildValue("(iO)", i, message); + Py_DECREF(message); + + if (v != NULL) { + PyErr_SetObject(exc, v); + Py_DECREF(v); + } #ifdef MS_WINDOWS - LocalFree(s_buf); + LocalFree(s_buf); #endif - return NULL; + return NULL; } PyObject * PyErr_SetFromErrnoWithFilename(PyObject *exc, const char *filename) { - PyObject *name = filename ? PyUnicode_DecodeFSDefault(filename) : NULL; - PyObject *result = PyErr_SetFromErrnoWithFilenameObject(exc, name); - Py_XDECREF(name); - return result; + PyObject *name = filename ? PyUnicode_DecodeFSDefault(filename) : NULL; + PyObject *result = PyErr_SetFromErrnoWithFilenameObject(exc, name); + Py_XDECREF(name); + return result; } #ifdef MS_WINDOWS PyObject * PyErr_SetFromErrnoWithUnicodeFilename(PyObject *exc, const Py_UNICODE *filename) { - PyObject *name = filename ? - PyUnicode_FromUnicode(filename, wcslen(filename)) : - NULL; - PyObject *result = PyErr_SetFromErrnoWithFilenameObject(exc, name); - Py_XDECREF(name); - return result; + PyObject *name = filename ? + PyUnicode_FromUnicode(filename, wcslen(filename)) : + NULL; + PyObject *result = PyErr_SetFromErrnoWithFilenameObject(exc, name); + Py_XDECREF(name); + return result; } #endif /* MS_WINDOWS */ PyObject * PyErr_SetFromErrno(PyObject *exc) { - return PyErr_SetFromErrnoWithFilenameObject(exc, NULL); + return PyErr_SetFromErrnoWithFilenameObject(exc, NULL); } #ifdef MS_WINDOWS /* Windows specific error code handling */ PyObject *PyErr_SetExcFromWindowsErrWithFilenameObject( - PyObject *exc, - int ierr, - PyObject *filenameObject) -{ - int len; - WCHAR *s_buf = NULL; /* Free via LocalFree */ - PyObject *message; - PyObject *v; - DWORD err = (DWORD)ierr; - if (err==0) err = GetLastError(); - len = FormatMessageW( - /* Error API error */ - FORMAT_MESSAGE_ALLOCATE_BUFFER | - FORMAT_MESSAGE_FROM_SYSTEM | - FORMAT_MESSAGE_IGNORE_INSERTS, - NULL, /* no message source */ - err, - MAKELANGID(LANG_NEUTRAL, - SUBLANG_DEFAULT), /* Default language */ - (LPWSTR) &s_buf, - 0, /* size not used */ - NULL); /* no args */ - if (len==0) { - /* Only seen this in out of mem situations */ - message = PyUnicode_FromFormat("Windows Error 0x%X", err); - s_buf = NULL; - } else { - /* remove trailing cr/lf and dots */ - while (len > 0 && (s_buf[len-1] <= L' ' || s_buf[len-1] == L'.')) - s_buf[--len] = L'\0'; - message = PyUnicode_FromUnicode(s_buf, len); - } - - if (message == NULL) - { - LocalFree(s_buf); - return NULL; - } - - if (filenameObject != NULL) - v = Py_BuildValue("(iOO)", err, message, filenameObject); - else - v = Py_BuildValue("(iO)", err, message); - Py_DECREF(message); - - if (v != NULL) { - PyErr_SetObject(exc, v); - Py_DECREF(v); - } - LocalFree(s_buf); - return NULL; + PyObject *exc, + int ierr, + PyObject *filenameObject) +{ + int len; + WCHAR *s_buf = NULL; /* Free via LocalFree */ + PyObject *message; + PyObject *v; + DWORD err = (DWORD)ierr; + if (err==0) err = GetLastError(); + len = FormatMessageW( + /* Error API error */ + FORMAT_MESSAGE_ALLOCATE_BUFFER | + FORMAT_MESSAGE_FROM_SYSTEM | + FORMAT_MESSAGE_IGNORE_INSERTS, + NULL, /* no message source */ + err, + MAKELANGID(LANG_NEUTRAL, + SUBLANG_DEFAULT), /* Default language */ + (LPWSTR) &s_buf, + 0, /* size not used */ + NULL); /* no args */ + if (len==0) { + /* Only seen this in out of mem situations */ + message = PyUnicode_FromFormat("Windows Error 0x%X", err); + s_buf = NULL; + } else { + /* remove trailing cr/lf and dots */ + while (len > 0 && (s_buf[len-1] <= L' ' || s_buf[len-1] == L'.')) + s_buf[--len] = L'\0'; + message = PyUnicode_FromUnicode(s_buf, len); + } + + if (message == NULL) + { + LocalFree(s_buf); + return NULL; + } + + if (filenameObject != NULL) + v = Py_BuildValue("(iOO)", err, message, filenameObject); + else + v = Py_BuildValue("(iO)", err, message); + Py_DECREF(message); + + if (v != NULL) { + PyErr_SetObject(exc, v); + Py_DECREF(v); + } + LocalFree(s_buf); + return NULL; } PyObject *PyErr_SetExcFromWindowsErrWithFilename( - PyObject *exc, - int ierr, - const char *filename) -{ - PyObject *name = filename ? PyUnicode_FromString(filename) : NULL; - PyObject *ret = PyErr_SetExcFromWindowsErrWithFilenameObject(exc, - ierr, - name); - Py_XDECREF(name); - return ret; + PyObject *exc, + int ierr, + const char *filename) +{ + PyObject *name = filename ? PyUnicode_FromString(filename) : NULL; + PyObject *ret = PyErr_SetExcFromWindowsErrWithFilenameObject(exc, + ierr, + name); + Py_XDECREF(name); + return ret; } PyObject *PyErr_SetExcFromWindowsErrWithUnicodeFilename( - PyObject *exc, - int ierr, - const Py_UNICODE *filename) -{ - PyObject *name = filename ? - PyUnicode_FromUnicode(filename, wcslen(filename)) : - NULL; - PyObject *ret = PyErr_SetExcFromWindowsErrWithFilenameObject(exc, - ierr, - name); - Py_XDECREF(name); - return ret; + PyObject *exc, + int ierr, + const Py_UNICODE *filename) +{ + PyObject *name = filename ? + PyUnicode_FromUnicode(filename, wcslen(filename)) : + NULL; + PyObject *ret = PyErr_SetExcFromWindowsErrWithFilenameObject(exc, + ierr, + name); + Py_XDECREF(name); + return ret; } PyObject *PyErr_SetExcFromWindowsErr(PyObject *exc, int ierr) { - return PyErr_SetExcFromWindowsErrWithFilename(exc, ierr, NULL); + return PyErr_SetExcFromWindowsErrWithFilename(exc, ierr, NULL); } PyObject *PyErr_SetFromWindowsErr(int ierr) { - return PyErr_SetExcFromWindowsErrWithFilename(PyExc_WindowsError, - ierr, NULL); + return PyErr_SetExcFromWindowsErrWithFilename(PyExc_WindowsError, + ierr, NULL); } PyObject *PyErr_SetFromWindowsErrWithFilename( - int ierr, - const char *filename) + int ierr, + const char *filename) { - PyObject *name = filename ? PyUnicode_FromString(filename) : NULL; - PyObject *result = PyErr_SetExcFromWindowsErrWithFilenameObject( - PyExc_WindowsError, - ierr, name); - Py_XDECREF(name); - return result; + PyObject *name = filename ? PyUnicode_FromString(filename) : NULL; + PyObject *result = PyErr_SetExcFromWindowsErrWithFilenameObject( + PyExc_WindowsError, + ierr, name); + Py_XDECREF(name); + return result; } PyObject *PyErr_SetFromWindowsErrWithUnicodeFilename( - int ierr, - const Py_UNICODE *filename) + int ierr, + const Py_UNICODE *filename) { - PyObject *name = filename ? - PyUnicode_FromUnicode(filename, wcslen(filename)) : - NULL; - PyObject *result = PyErr_SetExcFromWindowsErrWithFilenameObject( - PyExc_WindowsError, - ierr, name); - Py_XDECREF(name); - return result; + PyObject *name = filename ? + PyUnicode_FromUnicode(filename, wcslen(filename)) : + NULL; + PyObject *result = PyErr_SetExcFromWindowsErrWithFilenameObject( + PyExc_WindowsError, + ierr, name); + Py_XDECREF(name); + return result; } #endif /* MS_WINDOWS */ void _PyErr_BadInternalCall(const char *filename, int lineno) { - PyErr_Format(PyExc_SystemError, - "%s:%d: bad argument to internal function", - filename, lineno); + PyErr_Format(PyExc_SystemError, + "%s:%d: bad argument to internal function", + filename, lineno); } /* Remove the preprocessor macro for PyErr_BadInternalCall() so that we can @@ -606,8 +606,8 @@ void PyErr_BadInternalCall(void) { - PyErr_Format(PyExc_SystemError, - "bad argument to internal function"); + PyErr_Format(PyExc_SystemError, + "bad argument to internal function"); } #define PyErr_BadInternalCall() _PyErr_BadInternalCall(__FILE__, __LINE__) @@ -616,20 +616,20 @@ PyObject * PyErr_Format(PyObject *exception, const char *format, ...) { - va_list vargs; - PyObject* string; + va_list vargs; + PyObject* string; #ifdef HAVE_STDARG_PROTOTYPES - va_start(vargs, format); + va_start(vargs, format); #else - va_start(vargs); + va_start(vargs); #endif - string = PyUnicode_FromFormatV(format, vargs); - PyErr_SetObject(exception, string); - Py_XDECREF(string); - va_end(vargs); - return NULL; + string = PyUnicode_FromFormatV(format, vargs); + PyErr_SetObject(exception, string); + Py_XDECREF(string); + va_end(vargs); + return NULL; } @@ -637,85 +637,85 @@ PyObject * PyErr_NewException(const char *name, PyObject *base, PyObject *dict) { - const char *dot; - PyObject *modulename = NULL; - PyObject *classname = NULL; - PyObject *mydict = NULL; - PyObject *bases = NULL; - PyObject *result = NULL; - dot = strrchr(name, '.'); - if (dot == NULL) { - PyErr_SetString(PyExc_SystemError, - "PyErr_NewException: name must be module.class"); - return NULL; - } - if (base == NULL) - base = PyExc_Exception; - if (dict == NULL) { - dict = mydict = PyDict_New(); - if (dict == NULL) - goto failure; - } - if (PyDict_GetItemString(dict, "__module__") == NULL) { - modulename = PyUnicode_FromStringAndSize(name, - (Py_ssize_t)(dot-name)); - if (modulename == NULL) - goto failure; - if (PyDict_SetItemString(dict, "__module__", modulename) != 0) - goto failure; - } - if (PyTuple_Check(base)) { - bases = base; - /* INCREF as we create a new ref in the else branch */ - Py_INCREF(bases); - } else { - bases = PyTuple_Pack(1, base); - if (bases == NULL) - goto failure; - } - /* Create a real new-style class. */ - result = PyObject_CallFunction((PyObject *)&PyType_Type, "UOO", - dot+1, bases, dict); + const char *dot; + PyObject *modulename = NULL; + PyObject *classname = NULL; + PyObject *mydict = NULL; + PyObject *bases = NULL; + PyObject *result = NULL; + dot = strrchr(name, '.'); + if (dot == NULL) { + PyErr_SetString(PyExc_SystemError, + "PyErr_NewException: name must be module.class"); + return NULL; + } + if (base == NULL) + base = PyExc_Exception; + if (dict == NULL) { + dict = mydict = PyDict_New(); + if (dict == NULL) + goto failure; + } + if (PyDict_GetItemString(dict, "__module__") == NULL) { + modulename = PyUnicode_FromStringAndSize(name, + (Py_ssize_t)(dot-name)); + if (modulename == NULL) + goto failure; + if (PyDict_SetItemString(dict, "__module__", modulename) != 0) + goto failure; + } + if (PyTuple_Check(base)) { + bases = base; + /* INCREF as we create a new ref in the else branch */ + Py_INCREF(bases); + } else { + bases = PyTuple_Pack(1, base); + if (bases == NULL) + goto failure; + } + /* Create a real new-style class. */ + result = PyObject_CallFunction((PyObject *)&PyType_Type, "UOO", + dot+1, bases, dict); failure: - Py_XDECREF(bases); - Py_XDECREF(mydict); - Py_XDECREF(classname); - Py_XDECREF(modulename); - return result; + Py_XDECREF(bases); + Py_XDECREF(mydict); + Py_XDECREF(classname); + Py_XDECREF(modulename); + return result; } /* Create an exception with docstring */ PyObject * PyErr_NewExceptionWithDoc(const char *name, const char *doc, - PyObject *base, PyObject *dict) + PyObject *base, PyObject *dict) { - int result; - PyObject *ret = NULL; - PyObject *mydict = NULL; /* points to the dict only if we create it */ - PyObject *docobj; - - if (dict == NULL) { - dict = mydict = PyDict_New(); - if (dict == NULL) { - return NULL; - } - } - - if (doc != NULL) { - docobj = PyUnicode_FromString(doc); - if (docobj == NULL) - goto failure; - result = PyDict_SetItemString(dict, "__doc__", docobj); - Py_DECREF(docobj); - if (result < 0) - goto failure; - } + int result; + PyObject *ret = NULL; + PyObject *mydict = NULL; /* points to the dict only if we create it */ + PyObject *docobj; + + if (dict == NULL) { + dict = mydict = PyDict_New(); + if (dict == NULL) { + return NULL; + } + } + + if (doc != NULL) { + docobj = PyUnicode_FromString(doc); + if (docobj == NULL) + goto failure; + result = PyDict_SetItemString(dict, "__doc__", docobj); + Py_DECREF(docobj); + if (result < 0) + goto failure; + } - ret = PyErr_NewException(name, base, dict); + ret = PyErr_NewException(name, base, dict); failure: - Py_XDECREF(mydict); - return ret; + Py_XDECREF(mydict); + return ret; } @@ -724,52 +724,52 @@ void PyErr_WriteUnraisable(PyObject *obj) { - PyObject *f, *t, *v, *tb; - PyErr_Fetch(&t, &v, &tb); - f = PySys_GetObject("stderr"); - if (f != NULL && f != Py_None) { - PyFile_WriteString("Exception ", f); - if (t) { - PyObject* moduleName; - char* className; - assert(PyExceptionClass_Check(t)); - className = PyExceptionClass_Name(t); - if (className != NULL) { - char *dot = strrchr(className, '.'); - if (dot != NULL) - className = dot+1; - } - - moduleName = PyObject_GetAttrString(t, "__module__"); - if (moduleName == NULL) - PyFile_WriteString("", f); - else { - char* modstr = _PyUnicode_AsString(moduleName); - if (modstr && - strcmp(modstr, "builtins") != 0) - { - PyFile_WriteString(modstr, f); - PyFile_WriteString(".", f); - } - } - if (className == NULL) - PyFile_WriteString("", f); - else - PyFile_WriteString(className, f); - if (v && v != Py_None) { - PyFile_WriteString(": ", f); - PyFile_WriteObject(v, f, 0); - } - Py_XDECREF(moduleName); - } - PyFile_WriteString(" in ", f); - PyFile_WriteObject(obj, f, 0); - PyFile_WriteString(" ignored\n", f); - PyErr_Clear(); /* Just in case */ - } - Py_XDECREF(t); - Py_XDECREF(v); - Py_XDECREF(tb); + PyObject *f, *t, *v, *tb; + PyErr_Fetch(&t, &v, &tb); + f = PySys_GetObject("stderr"); + if (f != NULL && f != Py_None) { + PyFile_WriteString("Exception ", f); + if (t) { + PyObject* moduleName; + char* className; + assert(PyExceptionClass_Check(t)); + className = PyExceptionClass_Name(t); + if (className != NULL) { + char *dot = strrchr(className, '.'); + if (dot != NULL) + className = dot+1; + } + + moduleName = PyObject_GetAttrString(t, "__module__"); + if (moduleName == NULL) + PyFile_WriteString("", f); + else { + char* modstr = _PyUnicode_AsString(moduleName); + if (modstr && + strcmp(modstr, "builtins") != 0) + { + PyFile_WriteString(modstr, f); + PyFile_WriteString(".", f); + } + } + if (className == NULL) + PyFile_WriteString("", f); + else + PyFile_WriteString(className, f); + if (v && v != Py_None) { + PyFile_WriteString(": ", f); + PyFile_WriteObject(v, f, 0); + } + Py_XDECREF(moduleName); + } + PyFile_WriteString(" in ", f); + PyFile_WriteObject(obj, f, 0); + PyFile_WriteString(" ignored\n", f); + PyErr_Clear(); /* Just in case */ + } + Py_XDECREF(t); + Py_XDECREF(v); + Py_XDECREF(tb); } extern PyObject *PyModule_GetWarningsModule(void); @@ -782,59 +782,59 @@ void PyErr_SyntaxLocation(const char *filename, int lineno) { - PyObject *exc, *v, *tb, *tmp; + PyObject *exc, *v, *tb, *tmp; - /* add attributes for the line number and filename for the error */ - PyErr_Fetch(&exc, &v, &tb); - PyErr_NormalizeException(&exc, &v, &tb); - /* XXX check that it is, indeed, a syntax error. It might not - * be, though. */ - tmp = PyLong_FromLong(lineno); - if (tmp == NULL) - PyErr_Clear(); - else { - if (PyObject_SetAttrString(v, "lineno", tmp)) - PyErr_Clear(); - Py_DECREF(tmp); - } - if (filename != NULL) { - tmp = PyUnicode_FromString(filename); - if (tmp == NULL) - PyErr_Clear(); - else { - if (PyObject_SetAttrString(v, "filename", tmp)) - PyErr_Clear(); - Py_DECREF(tmp); - } - - tmp = PyErr_ProgramText(filename, lineno); - if (tmp) { - if (PyObject_SetAttrString(v, "text", tmp)) - PyErr_Clear(); - Py_DECREF(tmp); - } - } - if (PyObject_SetAttrString(v, "offset", Py_None)) { - PyErr_Clear(); - } - if (exc != PyExc_SyntaxError) { - if (!PyObject_HasAttrString(v, "msg")) { - tmp = PyObject_Str(v); - if (tmp) { - if (PyObject_SetAttrString(v, "msg", tmp)) - PyErr_Clear(); - Py_DECREF(tmp); - } else { - PyErr_Clear(); - } - } - if (!PyObject_HasAttrString(v, "print_file_and_line")) { - if (PyObject_SetAttrString(v, "print_file_and_line", - Py_None)) - PyErr_Clear(); - } - } - PyErr_Restore(exc, v, tb); + /* add attributes for the line number and filename for the error */ + PyErr_Fetch(&exc, &v, &tb); + PyErr_NormalizeException(&exc, &v, &tb); + /* XXX check that it is, indeed, a syntax error. It might not + * be, though. */ + tmp = PyLong_FromLong(lineno); + if (tmp == NULL) + PyErr_Clear(); + else { + if (PyObject_SetAttrString(v, "lineno", tmp)) + PyErr_Clear(); + Py_DECREF(tmp); + } + if (filename != NULL) { + tmp = PyUnicode_FromString(filename); + if (tmp == NULL) + PyErr_Clear(); + else { + if (PyObject_SetAttrString(v, "filename", tmp)) + PyErr_Clear(); + Py_DECREF(tmp); + } + + tmp = PyErr_ProgramText(filename, lineno); + if (tmp) { + if (PyObject_SetAttrString(v, "text", tmp)) + PyErr_Clear(); + Py_DECREF(tmp); + } + } + if (PyObject_SetAttrString(v, "offset", Py_None)) { + PyErr_Clear(); + } + if (exc != PyExc_SyntaxError) { + if (!PyObject_HasAttrString(v, "msg")) { + tmp = PyObject_Str(v); + if (tmp) { + if (PyObject_SetAttrString(v, "msg", tmp)) + PyErr_Clear(); + Py_DECREF(tmp); + } else { + PyErr_Clear(); + } + } + if (!PyObject_HasAttrString(v, "print_file_and_line")) { + if (PyObject_SetAttrString(v, "print_file_and_line", + Py_None)) + PyErr_Clear(); + } + } + PyErr_Restore(exc, v, tb); } /* Attempt to load the line of text that the exception refers to. If it @@ -846,41 +846,41 @@ PyObject * PyErr_ProgramText(const char *filename, int lineno) { - FILE *fp; - int i; - char linebuf[1000]; - - if (filename == NULL || *filename == '\0' || lineno <= 0) - return NULL; - fp = fopen(filename, "r" PY_STDIOTEXTMODE); - if (fp == NULL) - return NULL; - for (i = 0; i < lineno; i++) { - char *pLastChar = &linebuf[sizeof(linebuf) - 2]; - do { - *pLastChar = '\0'; - if (Py_UniversalNewlineFgets(linebuf, sizeof linebuf, - fp, NULL) == NULL) - break; - /* fgets read *something*; if it didn't get as - far as pLastChar, it must have found a newline - or hit the end of the file; if pLastChar is \n, - it obviously found a newline; else we haven't - yet seen a newline, so must continue */ - } while (*pLastChar != '\0' && *pLastChar != '\n'); - } - fclose(fp); - if (i == lineno) { - char *p = linebuf; - PyObject *res; - while (*p == ' ' || *p == '\t' || *p == '\014') - p++; - res = PyUnicode_FromString(p); - if (res == NULL) - PyErr_Clear(); - return res; - } - return NULL; + FILE *fp; + int i; + char linebuf[1000]; + + if (filename == NULL || *filename == '\0' || lineno <= 0) + return NULL; + fp = fopen(filename, "r" PY_STDIOTEXTMODE); + if (fp == NULL) + return NULL; + for (i = 0; i < lineno; i++) { + char *pLastChar = &linebuf[sizeof(linebuf) - 2]; + do { + *pLastChar = '\0'; + if (Py_UniversalNewlineFgets(linebuf, sizeof linebuf, + fp, NULL) == NULL) + break; + /* fgets read *something*; if it didn't get as + far as pLastChar, it must have found a newline + or hit the end of the file; if pLastChar is \n, + it obviously found a newline; else we haven't + yet seen a newline, so must continue */ + } while (*pLastChar != '\0' && *pLastChar != '\n'); + } + fclose(fp); + if (i == lineno) { + char *p = linebuf; + PyObject *res; + while (*p == ' ' || *p == '\t' || *p == '\014') + p++; + res = PyUnicode_FromString(p); + if (res == NULL) + PyErr_Clear(); + return res; + } + return NULL; } #ifdef __cplusplus Modified: python/branches/py3k-jit/Python/frozen.c ============================================================================== --- python/branches/py3k-jit/Python/frozen.c (original) +++ python/branches/py3k-jit/Python/frozen.c Mon May 10 23:55:43 2010 @@ -12,25 +12,25 @@ the appropriate bytes from M___main__.c. */ static unsigned char M___hello__[] = { - 99,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0, - 0,64,0,0,0,115,10,0,0,0,100,1,0,90,1,0, - 100,0,0,83,40,2,0,0,0,78,84,40,2,0,0,0, - 117,4,0,0,0,84,114,117,101,117,11,0,0,0,105,110, - 105,116,105,97,108,105,122,101,100,40,0,0,0,0,40,0, - 0,0,0,40,0,0,0,0,117,7,0,0,0,102,108,97, - 103,46,112,121,117,8,0,0,0,60,109,111,100,117,108,101, - 62,1,0,0,0,115,0,0,0,0, + 99,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0, + 0,64,0,0,0,115,10,0,0,0,100,1,0,90,1,0, + 100,0,0,83,40,2,0,0,0,78,84,40,2,0,0,0, + 117,4,0,0,0,84,114,117,101,117,11,0,0,0,105,110, + 105,116,105,97,108,105,122,101,100,40,0,0,0,0,40,0, + 0,0,0,40,0,0,0,0,117,7,0,0,0,102,108,97, + 103,46,112,121,117,8,0,0,0,60,109,111,100,117,108,101, + 62,1,0,0,0,115,0,0,0,0, }; #define SIZE (int)sizeof(M___hello__) static struct _frozen _PyImport_FrozenModules[] = { - /* Test module */ - {"__hello__", M___hello__, SIZE}, - /* Test package (negative size indicates package-ness) */ - {"__phello__", M___hello__, -SIZE}, - {"__phello__.spam", M___hello__, SIZE}, - {0, 0, 0} /* sentinel */ + /* Test module */ + {"__hello__", M___hello__, SIZE}, + /* Test package (negative size indicates package-ness) */ + {"__phello__", M___hello__, -SIZE}, + {"__phello__.spam", M___hello__, SIZE}, + {0, 0, 0} /* sentinel */ }; /* Embedding apps may change this pointer to point to their favorite Modified: python/branches/py3k-jit/Python/frozenmain.c ============================================================================== --- python/branches/py3k-jit/Python/frozenmain.c (original) +++ python/branches/py3k-jit/Python/frozenmain.c Mon May 10 23:55:43 2010 @@ -15,96 +15,96 @@ int Py_FrozenMain(int argc, char **argv) { - char *p; - int i, n, sts; - int inspect = 0; - int unbuffered = 0; - char *oldloc; - wchar_t **argv_copy = PyMem_Malloc(sizeof(wchar_t*)*argc); - /* We need a second copies, as Python might modify the first one. */ - wchar_t **argv_copy2 = PyMem_Malloc(sizeof(wchar_t*)*argc); - - Py_FrozenFlag = 1; /* Suppress errors from getpath.c */ - - if ((p = Py_GETENV("PYTHONINSPECT")) && *p != '\0') - inspect = 1; - if ((p = Py_GETENV("PYTHONUNBUFFERED")) && *p != '\0') - unbuffered = 1; - - if (unbuffered) { - setbuf(stdin, (char *)NULL); - setbuf(stdout, (char *)NULL); - setbuf(stderr, (char *)NULL); - } - - if (!argv_copy) { - fprintf(stderr, "out of memory\n"); - return 1; - } - - oldloc = setlocale(LC_ALL, NULL); - setlocale(LC_ALL, ""); - for (i = 0; i < argc; i++) { + char *p; + int i, n, sts; + int inspect = 0; + int unbuffered = 0; + char *oldloc; + wchar_t **argv_copy = PyMem_Malloc(sizeof(wchar_t*)*argc); + /* We need a second copies, as Python might modify the first one. */ + wchar_t **argv_copy2 = PyMem_Malloc(sizeof(wchar_t*)*argc); + + Py_FrozenFlag = 1; /* Suppress errors from getpath.c */ + + if ((p = Py_GETENV("PYTHONINSPECT")) && *p != '\0') + inspect = 1; + if ((p = Py_GETENV("PYTHONUNBUFFERED")) && *p != '\0') + unbuffered = 1; + + if (unbuffered) { + setbuf(stdin, (char *)NULL); + setbuf(stdout, (char *)NULL); + setbuf(stderr, (char *)NULL); + } + + if (!argv_copy) { + fprintf(stderr, "out of memory\n"); + return 1; + } + + oldloc = setlocale(LC_ALL, NULL); + setlocale(LC_ALL, ""); + for (i = 0; i < argc; i++) { #ifdef HAVE_BROKEN_MBSTOWCS - size_t argsize = strlen(argv[i]); + size_t argsize = strlen(argv[i]); #else - size_t argsize = mbstowcs(NULL, argv[i], 0); + size_t argsize = mbstowcs(NULL, argv[i], 0); #endif - size_t count; - if (argsize == (size_t)-1) { - fprintf(stderr, "Could not convert argument %d to string\n", i); - return 1; - } - argv_copy[i] = PyMem_Malloc((argsize+1)*sizeof(wchar_t)); - argv_copy2[i] = argv_copy[i]; - if (!argv_copy[i]) { - fprintf(stderr, "out of memory\n"); - return 1; - } - count = mbstowcs(argv_copy[i], argv[i], argsize+1); - if (count == (size_t)-1) { - fprintf(stderr, "Could not convert argument %d to string\n", i); - return 1; - } - } - setlocale(LC_ALL, oldloc); + size_t count; + if (argsize == (size_t)-1) { + fprintf(stderr, "Could not convert argument %d to string\n", i); + return 1; + } + argv_copy[i] = PyMem_Malloc((argsize+1)*sizeof(wchar_t)); + argv_copy2[i] = argv_copy[i]; + if (!argv_copy[i]) { + fprintf(stderr, "out of memory\n"); + return 1; + } + count = mbstowcs(argv_copy[i], argv[i], argsize+1); + if (count == (size_t)-1) { + fprintf(stderr, "Could not convert argument %d to string\n", i); + return 1; + } + } + setlocale(LC_ALL, oldloc); #ifdef MS_WINDOWS - PyInitFrozenExtensions(); + PyInitFrozenExtensions(); #endif /* MS_WINDOWS */ - Py_SetProgramName(argv_copy[0]); - Py_Initialize(); + Py_SetProgramName(argv_copy[0]); + Py_Initialize(); #ifdef MS_WINDOWS - PyWinFreeze_ExeInit(); + PyWinFreeze_ExeInit(); #endif - if (Py_VerboseFlag) - fprintf(stderr, "Python %s\n%s\n", - Py_GetVersion(), Py_GetCopyright()); - - PySys_SetArgv(argc, argv_copy); - - n = PyImport_ImportFrozenModule("__main__"); - if (n == 0) - Py_FatalError("__main__ not frozen"); - if (n < 0) { - PyErr_Print(); - sts = 1; - } - else - sts = 0; + if (Py_VerboseFlag) + fprintf(stderr, "Python %s\n%s\n", + Py_GetVersion(), Py_GetCopyright()); + + PySys_SetArgv(argc, argv_copy); + + n = PyImport_ImportFrozenModule("__main__"); + if (n == 0) + Py_FatalError("__main__ not frozen"); + if (n < 0) { + PyErr_Print(); + sts = 1; + } + else + sts = 0; - if (inspect && isatty((int)fileno(stdin))) - sts = PyRun_AnyFile(stdin, "") != 0; + if (inspect && isatty((int)fileno(stdin))) + sts = PyRun_AnyFile(stdin, "") != 0; #ifdef MS_WINDOWS - PyWinFreeze_ExeTerm(); + PyWinFreeze_ExeTerm(); #endif - Py_Finalize(); - for (i = 0; i < argc; i++) { - PyMem_Free(argv_copy2[i]); - } - PyMem_Free(argv_copy); - PyMem_Free(argv_copy2); - return sts; + Py_Finalize(); + for (i = 0; i < argc; i++) { + PyMem_Free(argv_copy2[i]); + } + PyMem_Free(argv_copy); + PyMem_Free(argv_copy2); + return sts; } Modified: python/branches/py3k-jit/Python/future.c ============================================================================== --- python/branches/py3k-jit/Python/future.c (original) +++ python/branches/py3k-jit/Python/future.c Mon May 10 23:55:43 2010 @@ -14,131 +14,131 @@ static int future_check_features(PyFutureFeatures *ff, stmt_ty s, const char *filename) { - int i; - asdl_seq *names; + int i; + asdl_seq *names; - assert(s->kind == ImportFrom_kind); + assert(s->kind == ImportFrom_kind); - names = s->v.ImportFrom.names; - for (i = 0; i < asdl_seq_LEN(names); i++) { - alias_ty name = (alias_ty)asdl_seq_GET(names, i); - const char *feature = _PyUnicode_AsString(name->name); - if (!feature) - return 0; - if (strcmp(feature, FUTURE_NESTED_SCOPES) == 0) { - continue; - } else if (strcmp(feature, FUTURE_GENERATORS) == 0) { - continue; - } else if (strcmp(feature, FUTURE_DIVISION) == 0) { - continue; - } else if (strcmp(feature, FUTURE_ABSOLUTE_IMPORT) == 0) { - continue; - } else if (strcmp(feature, FUTURE_WITH_STATEMENT) == 0) { - continue; - } else if (strcmp(feature, FUTURE_PRINT_FUNCTION) == 0) { - continue; - } else if (strcmp(feature, FUTURE_UNICODE_LITERALS) == 0) { - continue; - } else if (strcmp(feature, FUTURE_BARRY_AS_BDFL) == 0) { - ff->ff_features |= CO_FUTURE_BARRY_AS_BDFL; - } else if (strcmp(feature, "braces") == 0) { - PyErr_SetString(PyExc_SyntaxError, - "not a chance"); - PyErr_SyntaxLocation(filename, s->lineno); - return 0; - } else { - PyErr_Format(PyExc_SyntaxError, - UNDEFINED_FUTURE_FEATURE, feature); - PyErr_SyntaxLocation(filename, s->lineno); - return 0; - } - } - return 1; + names = s->v.ImportFrom.names; + for (i = 0; i < asdl_seq_LEN(names); i++) { + alias_ty name = (alias_ty)asdl_seq_GET(names, i); + const char *feature = _PyUnicode_AsString(name->name); + if (!feature) + return 0; + if (strcmp(feature, FUTURE_NESTED_SCOPES) == 0) { + continue; + } else if (strcmp(feature, FUTURE_GENERATORS) == 0) { + continue; + } else if (strcmp(feature, FUTURE_DIVISION) == 0) { + continue; + } else if (strcmp(feature, FUTURE_ABSOLUTE_IMPORT) == 0) { + continue; + } else if (strcmp(feature, FUTURE_WITH_STATEMENT) == 0) { + continue; + } else if (strcmp(feature, FUTURE_PRINT_FUNCTION) == 0) { + continue; + } else if (strcmp(feature, FUTURE_UNICODE_LITERALS) == 0) { + continue; + } else if (strcmp(feature, FUTURE_BARRY_AS_BDFL) == 0) { + ff->ff_features |= CO_FUTURE_BARRY_AS_BDFL; + } else if (strcmp(feature, "braces") == 0) { + PyErr_SetString(PyExc_SyntaxError, + "not a chance"); + PyErr_SyntaxLocation(filename, s->lineno); + return 0; + } else { + PyErr_Format(PyExc_SyntaxError, + UNDEFINED_FUTURE_FEATURE, feature); + PyErr_SyntaxLocation(filename, s->lineno); + return 0; + } + } + return 1; } static int future_parse(PyFutureFeatures *ff, mod_ty mod, const char *filename) { - int i, found_docstring = 0, done = 0, prev_line = 0; + int i, found_docstring = 0, done = 0, prev_line = 0; - static PyObject *future; - if (!future) { - future = PyUnicode_InternFromString("__future__"); - if (!future) - return 0; - } - - if (!(mod->kind == Module_kind || mod->kind == Interactive_kind)) - return 1; - - /* A subsequent pass will detect future imports that don't - appear at the beginning of the file. There's one case, - however, that is easier to handle here: A series of imports - joined by semi-colons, where the first import is a future - statement but some subsequent import has the future form - but is preceded by a regular import. - */ - - - for (i = 0; i < asdl_seq_LEN(mod->v.Module.body); i++) { - stmt_ty s = (stmt_ty)asdl_seq_GET(mod->v.Module.body, i); - - if (done && s->lineno > prev_line) - return 1; - prev_line = s->lineno; - - /* The tests below will return from this function unless it is - still possible to find a future statement. The only things - that can precede a future statement are another future - statement and a doc string. - */ - - if (s->kind == ImportFrom_kind) { - if (s->v.ImportFrom.module == future) { - if (done) { - PyErr_SetString(PyExc_SyntaxError, - ERR_LATE_FUTURE); - PyErr_SyntaxLocation(filename, - s->lineno); - return 0; - } - if (!future_check_features(ff, s, filename)) - return 0; - ff->ff_lineno = s->lineno; - } - else - done = 1; - } - else if (s->kind == Expr_kind && !found_docstring) { - expr_ty e = s->v.Expr.value; - if (e->kind != Str_kind) - done = 1; - else - found_docstring = 1; - } - else - done = 1; - } - return 1; + static PyObject *future; + if (!future) { + future = PyUnicode_InternFromString("__future__"); + if (!future) + return 0; + } + + if (!(mod->kind == Module_kind || mod->kind == Interactive_kind)) + return 1; + + /* A subsequent pass will detect future imports that don't + appear at the beginning of the file. There's one case, + however, that is easier to handle here: A series of imports + joined by semi-colons, where the first import is a future + statement but some subsequent import has the future form + but is preceded by a regular import. + */ + + + for (i = 0; i < asdl_seq_LEN(mod->v.Module.body); i++) { + stmt_ty s = (stmt_ty)asdl_seq_GET(mod->v.Module.body, i); + + if (done && s->lineno > prev_line) + return 1; + prev_line = s->lineno; + + /* The tests below will return from this function unless it is + still possible to find a future statement. The only things + that can precede a future statement are another future + statement and a doc string. + */ + + if (s->kind == ImportFrom_kind) { + if (s->v.ImportFrom.module == future) { + if (done) { + PyErr_SetString(PyExc_SyntaxError, + ERR_LATE_FUTURE); + PyErr_SyntaxLocation(filename, + s->lineno); + return 0; + } + if (!future_check_features(ff, s, filename)) + return 0; + ff->ff_lineno = s->lineno; + } + else + done = 1; + } + else if (s->kind == Expr_kind && !found_docstring) { + expr_ty e = s->v.Expr.value; + if (e->kind != Str_kind) + done = 1; + else + found_docstring = 1; + } + else + done = 1; + } + return 1; } PyFutureFeatures * PyFuture_FromAST(mod_ty mod, const char *filename) { - PyFutureFeatures *ff; + PyFutureFeatures *ff; - ff = (PyFutureFeatures *)PyObject_Malloc(sizeof(PyFutureFeatures)); - if (ff == NULL) { - PyErr_NoMemory(); - return NULL; - } - ff->ff_features = 0; - ff->ff_lineno = -1; - - if (!future_parse(ff, mod, filename)) { - PyObject_Free(ff); - return NULL; - } - return ff; + ff = (PyFutureFeatures *)PyObject_Malloc(sizeof(PyFutureFeatures)); + if (ff == NULL) { + PyErr_NoMemory(); + return NULL; + } + ff->ff_features = 0; + ff->ff_lineno = -1; + + if (!future_parse(ff, mod, filename)) { + PyObject_Free(ff); + return NULL; + } + return ff; } Modified: python/branches/py3k-jit/Python/getargs.c ============================================================================== --- python/branches/py3k-jit/Python/getargs.c (original) +++ python/branches/py3k-jit/Python/getargs.c Mon May 10 23:55:43 2010 @@ -14,9 +14,9 @@ int PyArg_VaParse(PyObject *, const char *, va_list); int PyArg_ParseTupleAndKeywords(PyObject *, PyObject *, - const char *, char **, ...); + const char *, char **, ...); int PyArg_VaParseTupleAndKeywords(PyObject *, PyObject *, - const char *, char **, va_list); + const char *, char **, va_list); #ifdef HAVE_DECLSPEC_DLL /* Export functions */ @@ -40,100 +40,100 @@ static char *convertitem(PyObject *, const char **, va_list *, int, int *, char *, size_t, PyObject **); static char *converttuple(PyObject *, const char **, va_list *, int, - int *, char *, size_t, int, PyObject **); + int *, char *, size_t, int, PyObject **); static char *convertsimple(PyObject *, const char **, va_list *, int, char *, - size_t, PyObject **); + size_t, PyObject **); static Py_ssize_t convertbuffer(PyObject *, void **p, char **); static int getbuffer(PyObject *, Py_buffer *, char**); static int vgetargskeywords(PyObject *, PyObject *, - const char *, char **, va_list *, int); + const char *, char **, va_list *, int); static char *skipitem(const char **, va_list *, int); int PyArg_Parse(PyObject *args, const char *format, ...) { - int retval; - va_list va; + int retval; + va_list va; - va_start(va, format); - retval = vgetargs1(args, format, &va, FLAG_COMPAT); - va_end(va); - return retval; + va_start(va, format); + retval = vgetargs1(args, format, &va, FLAG_COMPAT); + va_end(va); + return retval; } int _PyArg_Parse_SizeT(PyObject *args, char *format, ...) { - int retval; - va_list va; + int retval; + va_list va; - va_start(va, format); - retval = vgetargs1(args, format, &va, FLAG_COMPAT|FLAG_SIZE_T); - va_end(va); - return retval; + va_start(va, format); + retval = vgetargs1(args, format, &va, FLAG_COMPAT|FLAG_SIZE_T); + va_end(va); + return retval; } int PyArg_ParseTuple(PyObject *args, const char *format, ...) { - int retval; - va_list va; + int retval; + va_list va; - va_start(va, format); - retval = vgetargs1(args, format, &va, 0); - va_end(va); - return retval; + va_start(va, format); + retval = vgetargs1(args, format, &va, 0); + va_end(va); + return retval; } int _PyArg_ParseTuple_SizeT(PyObject *args, char *format, ...) { - int retval; - va_list va; + int retval; + va_list va; - va_start(va, format); - retval = vgetargs1(args, format, &va, FLAG_SIZE_T); - va_end(va); - return retval; + va_start(va, format); + retval = vgetargs1(args, format, &va, FLAG_SIZE_T); + va_end(va); + return retval; } int PyArg_VaParse(PyObject *args, const char *format, va_list va) { - va_list lva; + va_list lva; #ifdef VA_LIST_IS_ARRAY - memcpy(lva, va, sizeof(va_list)); + memcpy(lva, va, sizeof(va_list)); #else #ifdef __va_copy - __va_copy(lva, va); + __va_copy(lva, va); #else - lva = va; + lva = va; #endif #endif - return vgetargs1(args, format, &lva, 0); + return vgetargs1(args, format, &lva, 0); } int _PyArg_VaParse_SizeT(PyObject *args, char *format, va_list va) { - va_list lva; + va_list lva; #ifdef VA_LIST_IS_ARRAY - memcpy(lva, va, sizeof(va_list)); + memcpy(lva, va, sizeof(va_list)); #else #ifdef __va_copy - __va_copy(lva, va); + __va_copy(lva, va); #else - lva = va; + lva = va; #endif #endif - return vgetargs1(args, format, &lva, FLAG_SIZE_T); + return vgetargs1(args, format, &lva, FLAG_SIZE_T); } @@ -146,261 +146,261 @@ static void cleanup_ptr(PyObject *self) { - void *ptr = PyCapsule_GetPointer(self, GETARGS_CAPSULE_NAME_CLEANUP_PTR); - if (ptr) { - PyMem_FREE(ptr); - } + void *ptr = PyCapsule_GetPointer(self, GETARGS_CAPSULE_NAME_CLEANUP_PTR); + if (ptr) { + PyMem_FREE(ptr); + } } static void cleanup_buffer(PyObject *self) { - Py_buffer *ptr = (Py_buffer *)PyCapsule_GetPointer(self, GETARGS_CAPSULE_NAME_CLEANUP_BUFFER); - if (ptr) { - PyBuffer_Release(ptr); - } + Py_buffer *ptr = (Py_buffer *)PyCapsule_GetPointer(self, GETARGS_CAPSULE_NAME_CLEANUP_BUFFER); + if (ptr) { + PyBuffer_Release(ptr); + } } static int addcleanup(void *ptr, PyObject **freelist, PyCapsule_Destructor destr) { - PyObject *cobj; - const char *name; + PyObject *cobj; + const char *name; - if (!*freelist) { - *freelist = PyList_New(0); - if (!*freelist) { - destr(ptr); - return -1; - } - } - - if (destr == cleanup_ptr) { - name = GETARGS_CAPSULE_NAME_CLEANUP_PTR; - } else if (destr == cleanup_buffer) { - name = GETARGS_CAPSULE_NAME_CLEANUP_BUFFER; - } else { - return -1; - } - cobj = PyCapsule_New(ptr, name, destr); - if (!cobj) { - destr(ptr); - return -1; - } - if (PyList_Append(*freelist, cobj)) { - Py_DECREF(cobj); - return -1; - } + if (!*freelist) { + *freelist = PyList_New(0); + if (!*freelist) { + destr(ptr); + return -1; + } + } + + if (destr == cleanup_ptr) { + name = GETARGS_CAPSULE_NAME_CLEANUP_PTR; + } else if (destr == cleanup_buffer) { + name = GETARGS_CAPSULE_NAME_CLEANUP_BUFFER; + } else { + return -1; + } + cobj = PyCapsule_New(ptr, name, destr); + if (!cobj) { + destr(ptr); + return -1; + } + if (PyList_Append(*freelist, cobj)) { Py_DECREF(cobj); - return 0; + return -1; + } + Py_DECREF(cobj); + return 0; } static void cleanup_convert(PyObject *self) { - typedef int (*destr_t)(PyObject *, void *); - destr_t destr = (destr_t)PyCapsule_GetContext(self); - void *ptr = PyCapsule_GetPointer(self, - GETARGS_CAPSULE_NAME_CLEANUP_CONVERT); - if (ptr && destr) - destr(NULL, ptr); + typedef int (*destr_t)(PyObject *, void *); + destr_t destr = (destr_t)PyCapsule_GetContext(self); + void *ptr = PyCapsule_GetPointer(self, + GETARGS_CAPSULE_NAME_CLEANUP_CONVERT); + if (ptr && destr) + destr(NULL, ptr); } static int addcleanup_convert(void *ptr, PyObject **freelist, int (*destr)(PyObject*,void*)) { - PyObject *cobj; - if (!*freelist) { - *freelist = PyList_New(0); - if (!*freelist) { - destr(NULL, ptr); - return -1; - } - } - cobj = PyCapsule_New(ptr, GETARGS_CAPSULE_NAME_CLEANUP_CONVERT, - cleanup_convert); - if (!cobj) { - destr(NULL, ptr); - return -1; - } - if (PyCapsule_SetContext(cobj, destr) == -1) { - /* This really should not happen. */ - Py_FatalError("capsule refused setting of context."); - } - if (PyList_Append(*freelist, cobj)) { - Py_DECREF(cobj); /* This will also call destr. */ - return -1; - } - Py_DECREF(cobj); - return 0; + PyObject *cobj; + if (!*freelist) { + *freelist = PyList_New(0); + if (!*freelist) { + destr(NULL, ptr); + return -1; + } + } + cobj = PyCapsule_New(ptr, GETARGS_CAPSULE_NAME_CLEANUP_CONVERT, + cleanup_convert); + if (!cobj) { + destr(NULL, ptr); + return -1; + } + if (PyCapsule_SetContext(cobj, destr) == -1) { + /* This really should not happen. */ + Py_FatalError("capsule refused setting of context."); + } + if (PyList_Append(*freelist, cobj)) { + Py_DECREF(cobj); /* This will also call destr. */ + return -1; + } + Py_DECREF(cobj); + return 0; } static int cleanreturn(int retval, PyObject *freelist) { - if (freelist && retval != 0) { - /* We were successful, reset the destructors so that they - don't get called. */ - Py_ssize_t len = PyList_GET_SIZE(freelist), i; - for (i = 0; i < len; i++) - PyCapsule_SetDestructor(PyList_GET_ITEM(freelist, i), NULL); - } - Py_XDECREF(freelist); - return retval; + if (freelist && retval != 0) { + /* We were successful, reset the destructors so that they + don't get called. */ + Py_ssize_t len = PyList_GET_SIZE(freelist), i; + for (i = 0; i < len; i++) + PyCapsule_SetDestructor(PyList_GET_ITEM(freelist, i), NULL); + } + Py_XDECREF(freelist); + return retval; } static int vgetargs1(PyObject *args, const char *format, va_list *p_va, int flags) { - char msgbuf[256]; - int levels[32]; - const char *fname = NULL; - const char *message = NULL; - int min = -1; - int max = 0; - int level = 0; - int endfmt = 0; - const char *formatsave = format; - Py_ssize_t i, len; - char *msg; - PyObject *freelist = NULL; - int compat = flags & FLAG_COMPAT; - - assert(compat || (args != (PyObject*)NULL)); - flags = flags & ~FLAG_COMPAT; - - while (endfmt == 0) { - int c = *format++; - switch (c) { - case '(': - if (level == 0) - max++; - level++; - if (level >= 30) - Py_FatalError("too many tuple nesting levels " - "in argument format string"); - break; - case ')': - if (level == 0) - Py_FatalError("excess ')' in getargs format"); - else - level--; - break; - case '\0': - endfmt = 1; - break; - case ':': - fname = format; - endfmt = 1; - break; - case ';': - message = format; - endfmt = 1; - break; - default: - if (level == 0) { - if (c == 'O') - max++; - else if (isalpha(Py_CHARMASK(c))) { - if (c != 'e') /* skip encoded */ - max++; - } else if (c == '|') - min = max; - } - break; - } - } - - if (level != 0) - Py_FatalError(/* '(' */ "missing ')' in getargs format"); - - if (min < 0) - min = max; - - format = formatsave; - - if (compat) { - if (max == 0) { - if (args == NULL) - return 1; - PyOS_snprintf(msgbuf, sizeof(msgbuf), - "%.200s%s takes no arguments", - fname==NULL ? "function" : fname, - fname==NULL ? "" : "()"); - PyErr_SetString(PyExc_TypeError, msgbuf); - return 0; - } - else if (min == 1 && max == 1) { - if (args == NULL) { - PyOS_snprintf(msgbuf, sizeof(msgbuf), - "%.200s%s takes at least one argument", - fname==NULL ? "function" : fname, - fname==NULL ? "" : "()"); - PyErr_SetString(PyExc_TypeError, msgbuf); - return 0; - } - msg = convertitem(args, &format, p_va, flags, levels, - msgbuf, sizeof(msgbuf), &freelist); - if (msg == NULL) - return cleanreturn(1, freelist); - seterror(levels[0], msg, levels+1, fname, message); - return cleanreturn(0, freelist); - } - else { - PyErr_SetString(PyExc_SystemError, - "old style getargs format uses new features"); - return 0; - } - } - - if (!PyTuple_Check(args)) { - PyErr_SetString(PyExc_SystemError, - "new style getargs format but argument is not a tuple"); - return 0; - } - - len = PyTuple_GET_SIZE(args); - - if (len < min || max < len) { - if (message == NULL) { - PyOS_snprintf(msgbuf, sizeof(msgbuf), - "%.150s%s takes %s %d argument%s " - "(%ld given)", - fname==NULL ? "function" : fname, - fname==NULL ? "" : "()", - min==max ? "exactly" - : len < min ? "at least" : "at most", - len < min ? min : max, - (len < min ? min : max) == 1 ? "" : "s", - Py_SAFE_DOWNCAST(len, Py_ssize_t, long)); - message = msgbuf; - } - PyErr_SetString(PyExc_TypeError, message); - return 0; - } - - for (i = 0; i < len; i++) { - if (*format == '|') - format++; - msg = convertitem(PyTuple_GET_ITEM(args, i), &format, p_va, - flags, levels, msgbuf, - sizeof(msgbuf), &freelist); - if (msg) { - seterror(i+1, msg, levels, fname, msg); - return cleanreturn(0, freelist); - } - } - - if (*format != '\0' && !isalpha(Py_CHARMASK(*format)) && - *format != '(' && - *format != '|' && *format != ':' && *format != ';') { - PyErr_Format(PyExc_SystemError, - "bad format string: %.200s", formatsave); - return cleanreturn(0, freelist); - } + char msgbuf[256]; + int levels[32]; + const char *fname = NULL; + const char *message = NULL; + int min = -1; + int max = 0; + int level = 0; + int endfmt = 0; + const char *formatsave = format; + Py_ssize_t i, len; + char *msg; + PyObject *freelist = NULL; + int compat = flags & FLAG_COMPAT; + + assert(compat || (args != (PyObject*)NULL)); + flags = flags & ~FLAG_COMPAT; + + while (endfmt == 0) { + int c = *format++; + switch (c) { + case '(': + if (level == 0) + max++; + level++; + if (level >= 30) + Py_FatalError("too many tuple nesting levels " + "in argument format string"); + break; + case ')': + if (level == 0) + Py_FatalError("excess ')' in getargs format"); + else + level--; + break; + case '\0': + endfmt = 1; + break; + case ':': + fname = format; + endfmt = 1; + break; + case ';': + message = format; + endfmt = 1; + break; + default: + if (level == 0) { + if (c == 'O') + max++; + else if (isalpha(Py_CHARMASK(c))) { + if (c != 'e') /* skip encoded */ + max++; + } else if (c == '|') + min = max; + } + break; + } + } + + if (level != 0) + Py_FatalError(/* '(' */ "missing ')' in getargs format"); + + if (min < 0) + min = max; + + format = formatsave; + + if (compat) { + if (max == 0) { + if (args == NULL) + return 1; + PyOS_snprintf(msgbuf, sizeof(msgbuf), + "%.200s%s takes no arguments", + fname==NULL ? "function" : fname, + fname==NULL ? "" : "()"); + PyErr_SetString(PyExc_TypeError, msgbuf); + return 0; + } + else if (min == 1 && max == 1) { + if (args == NULL) { + PyOS_snprintf(msgbuf, sizeof(msgbuf), + "%.200s%s takes at least one argument", + fname==NULL ? "function" : fname, + fname==NULL ? "" : "()"); + PyErr_SetString(PyExc_TypeError, msgbuf); + return 0; + } + msg = convertitem(args, &format, p_va, flags, levels, + msgbuf, sizeof(msgbuf), &freelist); + if (msg == NULL) + return cleanreturn(1, freelist); + seterror(levels[0], msg, levels+1, fname, message); + return cleanreturn(0, freelist); + } + else { + PyErr_SetString(PyExc_SystemError, + "old style getargs format uses new features"); + return 0; + } + } + + if (!PyTuple_Check(args)) { + PyErr_SetString(PyExc_SystemError, + "new style getargs format but argument is not a tuple"); + return 0; + } + + len = PyTuple_GET_SIZE(args); + + if (len < min || max < len) { + if (message == NULL) { + PyOS_snprintf(msgbuf, sizeof(msgbuf), + "%.150s%s takes %s %d argument%s " + "(%ld given)", + fname==NULL ? "function" : fname, + fname==NULL ? "" : "()", + min==max ? "exactly" + : len < min ? "at least" : "at most", + len < min ? min : max, + (len < min ? min : max) == 1 ? "" : "s", + Py_SAFE_DOWNCAST(len, Py_ssize_t, long)); + message = msgbuf; + } + PyErr_SetString(PyExc_TypeError, message); + return 0; + } + + for (i = 0; i < len; i++) { + if (*format == '|') + format++; + msg = convertitem(PyTuple_GET_ITEM(args, i), &format, p_va, + flags, levels, msgbuf, + sizeof(msgbuf), &freelist); + if (msg) { + seterror(i+1, msg, levels, fname, msg); + return cleanreturn(0, freelist); + } + } + + if (*format != '\0' && !isalpha(Py_CHARMASK(*format)) && + *format != '(' && + *format != '|' && *format != ':' && *format != ';') { + PyErr_Format(PyExc_SystemError, + "bad format string: %.200s", formatsave); + return cleanreturn(0, freelist); + } - return cleanreturn(1, freelist); + return cleanreturn(1, freelist); } @@ -409,37 +409,37 @@ seterror(int iarg, const char *msg, int *levels, const char *fname, const char *message) { - char buf[512]; - int i; - char *p = buf; - - if (PyErr_Occurred()) - return; - else if (message == NULL) { - if (fname != NULL) { - PyOS_snprintf(p, sizeof(buf), "%.200s() ", fname); - p += strlen(p); - } - if (iarg != 0) { - PyOS_snprintf(p, sizeof(buf) - (p - buf), - "argument %d", iarg); - i = 0; - p += strlen(p); - while (levels[i] > 0 && i < 32 && (int)(p-buf) < 220) { - PyOS_snprintf(p, sizeof(buf) - (p - buf), - ", item %d", levels[i]-1); - p += strlen(p); - i++; - } - } - else { - PyOS_snprintf(p, sizeof(buf) - (p - buf), "argument"); - p += strlen(p); - } - PyOS_snprintf(p, sizeof(buf) - (p - buf), " %.256s", msg); - message = buf; - } - PyErr_SetString(PyExc_TypeError, message); + char buf[512]; + int i; + char *p = buf; + + if (PyErr_Occurred()) + return; + else if (message == NULL) { + if (fname != NULL) { + PyOS_snprintf(p, sizeof(buf), "%.200s() ", fname); + p += strlen(p); + } + if (iarg != 0) { + PyOS_snprintf(p, sizeof(buf) - (p - buf), + "argument %d", iarg); + i = 0; + p += strlen(p); + while (levels[i] > 0 && i < 32 && (int)(p-buf) < 220) { + PyOS_snprintf(p, sizeof(buf) - (p - buf), + ", item %d", levels[i]-1); + p += strlen(p); + i++; + } + } + else { + PyOS_snprintf(p, sizeof(buf) - (p - buf), "argument"); + p += strlen(p); + } + PyOS_snprintf(p, sizeof(buf) - (p - buf), " %.256s", msg); + message = buf; + } + PyErr_SetString(PyExc_TypeError, message); } @@ -455,9 +455,9 @@ *p_va is undefined, *levels is a 0-terminated list of item numbers, *msgbuf contains an error message, whose format is: - "must be , not ", where: - is the name of the expected type, and - is the name of the actual type, + "must be , not ", where: + is the name of the expected type, and + is the name of the actual type, and msgbuf is returned. */ @@ -466,72 +466,72 @@ int *levels, char *msgbuf, size_t bufsize, int toplevel, PyObject **freelist) { - int level = 0; - int n = 0; - const char *format = *p_format; - int i; - - for (;;) { - int c = *format++; - if (c == '(') { - if (level == 0) - n++; - level++; - } - else if (c == ')') { - if (level == 0) - break; - level--; - } - else if (c == ':' || c == ';' || c == '\0') - break; - else if (level == 0 && isalpha(Py_CHARMASK(c))) - n++; - } - - if (!PySequence_Check(arg) || PyBytes_Check(arg)) { - levels[0] = 0; - PyOS_snprintf(msgbuf, bufsize, - toplevel ? "expected %d arguments, not %.50s" : - "must be %d-item sequence, not %.50s", - n, - arg == Py_None ? "None" : arg->ob_type->tp_name); - return msgbuf; - } - - if ((i = PySequence_Size(arg)) != n) { - levels[0] = 0; - PyOS_snprintf(msgbuf, bufsize, - toplevel ? "expected %d arguments, not %d" : - "must be sequence of length %d, not %d", - n, i); - return msgbuf; - } - - format = *p_format; - for (i = 0; i < n; i++) { - char *msg; - PyObject *item; - item = PySequence_GetItem(arg, i); - if (item == NULL) { - PyErr_Clear(); - levels[0] = i+1; - levels[1] = 0; - strncpy(msgbuf, "is not retrievable", bufsize); - return msgbuf; - } - msg = convertitem(item, &format, p_va, flags, levels+1, - msgbuf, bufsize, freelist); - /* PySequence_GetItem calls tp->sq_item, which INCREFs */ - Py_XDECREF(item); - if (msg != NULL) { - levels[0] = i+1; - return msg; - } - } + int level = 0; + int n = 0; + const char *format = *p_format; + int i; + + for (;;) { + int c = *format++; + if (c == '(') { + if (level == 0) + n++; + level++; + } + else if (c == ')') { + if (level == 0) + break; + level--; + } + else if (c == ':' || c == ';' || c == '\0') + break; + else if (level == 0 && isalpha(Py_CHARMASK(c))) + n++; + } + + if (!PySequence_Check(arg) || PyBytes_Check(arg)) { + levels[0] = 0; + PyOS_snprintf(msgbuf, bufsize, + toplevel ? "expected %d arguments, not %.50s" : + "must be %d-item sequence, not %.50s", + n, + arg == Py_None ? "None" : arg->ob_type->tp_name); + return msgbuf; + } + + if ((i = PySequence_Size(arg)) != n) { + levels[0] = 0; + PyOS_snprintf(msgbuf, bufsize, + toplevel ? "expected %d arguments, not %d" : + "must be sequence of length %d, not %d", + n, i); + return msgbuf; + } + + format = *p_format; + for (i = 0; i < n; i++) { + char *msg; + PyObject *item; + item = PySequence_GetItem(arg, i); + if (item == NULL) { + PyErr_Clear(); + levels[0] = i+1; + levels[1] = 0; + strncpy(msgbuf, "is not retrievable", bufsize); + return msgbuf; + } + msg = convertitem(item, &format, p_va, flags, levels+1, + msgbuf, bufsize, freelist); + /* PySequence_GetItem calls tp->sq_item, which INCREFs */ + Py_XDECREF(item); + if (msg != NULL) { + levels[0] = i+1; + return msg; + } + } - *p_format = format; - return NULL; + *p_format = format; + return NULL; } @@ -541,43 +541,43 @@ convertitem(PyObject *arg, const char **p_format, va_list *p_va, int flags, int *levels, char *msgbuf, size_t bufsize, PyObject **freelist) { - char *msg; - const char *format = *p_format; + char *msg; + const char *format = *p_format; - if (*format == '(' /* ')' */) { - format++; - msg = converttuple(arg, &format, p_va, flags, levels, msgbuf, - bufsize, 0, freelist); - if (msg == NULL) - format++; - } - else { - msg = convertsimple(arg, &format, p_va, flags, - msgbuf, bufsize, freelist); - if (msg != NULL) - levels[0] = 0; - } - if (msg == NULL) - *p_format = format; - return msg; + if (*format == '(' /* ')' */) { + format++; + msg = converttuple(arg, &format, p_va, flags, levels, msgbuf, + bufsize, 0, freelist); + if (msg == NULL) + format++; + } + else { + msg = convertsimple(arg, &format, p_va, flags, + msgbuf, bufsize, freelist); + if (msg != NULL) + levels[0] = 0; + } + if (msg == NULL) + *p_format = format; + return msg; } #define UNICODE_DEFAULT_ENCODING(arg) \ - _PyUnicode_AsDefaultEncodedString(arg, NULL) + _PyUnicode_AsDefaultEncodedString(arg, NULL) /* Format an error message generated by convertsimple(). */ static char * converterr(const char *expected, PyObject *arg, char *msgbuf, size_t bufsize) { - assert(expected != NULL); - assert(arg != NULL); - PyOS_snprintf(msgbuf, bufsize, - "must be %.50s, not %.50s", expected, - arg == Py_None ? "None" : arg->ob_type->tp_name); - return msgbuf; + assert(expected != NULL); + assert(arg != NULL); + PyOS_snprintf(msgbuf, bufsize, + "must be %.50s, not %.50s", expected, + arg == Py_None ? "None" : arg->ob_type->tp_name); + return msgbuf; } #define CONV_UNICODE "(unicode conversion error)" @@ -587,12 +587,12 @@ static int float_argument_warning(PyObject *arg) { - if (PyFloat_Check(arg) && - PyErr_Warn(PyExc_DeprecationWarning, - "integer argument expected, got float" )) - return 1; - else - return 0; + if (PyFloat_Check(arg) && + PyErr_Warn(PyExc_DeprecationWarning, + "integer argument expected, got float" )) + return 1; + else + return 0; } /* Explicitly check for float arguments when integers are expected. @@ -600,13 +600,13 @@ static int float_argument_error(PyObject *arg) { - if (PyFloat_Check(arg)) { - PyErr_SetString(PyExc_TypeError, - "integer argument expected, got float" ); - return 1; - } - else - return 0; + if (PyFloat_Check(arg)) { + PyErr_SetString(PyExc_TypeError, + "integer argument expected, got float" ); + return 1; + } + else + return 0; } /* Convert a non-tuple argument. Return NULL if conversion went OK, @@ -622,837 +622,837 @@ convertsimple(PyObject *arg, const char **p_format, va_list *p_va, int flags, char *msgbuf, size_t bufsize, PyObject **freelist) { - /* For # codes */ -#define FETCH_SIZE int *q=NULL;Py_ssize_t *q2=NULL;\ - if (flags & FLAG_SIZE_T) q2=va_arg(*p_va, Py_ssize_t*); \ - else q=va_arg(*p_va, int*); + /* For # codes */ +#define FETCH_SIZE int *q=NULL;Py_ssize_t *q2=NULL;\ + if (flags & FLAG_SIZE_T) q2=va_arg(*p_va, Py_ssize_t*); \ + else q=va_arg(*p_va, int*); #define STORE_SIZE(s) if (flags & FLAG_SIZE_T) *q2=s; else *q=s; #define BUFFER_LEN ((flags & FLAG_SIZE_T) ? *q2:*q) - const char *format = *p_format; - char c = *format++; - PyObject *uarg; - - switch (c) { - - case 'b': { /* unsigned byte -- very short int */ - char *p = va_arg(*p_va, char *); - long ival; - if (float_argument_error(arg)) - return converterr("integer", arg, msgbuf, bufsize); - ival = PyLong_AsLong(arg); - if (ival == -1 && PyErr_Occurred()) - return converterr("integer", arg, msgbuf, bufsize); - else if (ival < 0) { - PyErr_SetString(PyExc_OverflowError, - "unsigned byte integer is less than minimum"); - return converterr("integer", arg, msgbuf, bufsize); - } - else if (ival > UCHAR_MAX) { - PyErr_SetString(PyExc_OverflowError, - "unsigned byte integer is greater than maximum"); - return converterr("integer", arg, msgbuf, bufsize); - } - else - *p = (unsigned char) ival; - break; - } - - case 'B': {/* byte sized bitfield - both signed and unsigned - values allowed */ - char *p = va_arg(*p_va, char *); - long ival; - if (float_argument_error(arg)) - return converterr("integer", arg, msgbuf, bufsize); - ival = PyLong_AsUnsignedLongMask(arg); - if (ival == -1 && PyErr_Occurred()) - return converterr("integer", arg, msgbuf, bufsize); - else - *p = (unsigned char) ival; - break; - } - - case 'h': {/* signed short int */ - short *p = va_arg(*p_va, short *); - long ival; - if (float_argument_error(arg)) - return converterr("integer", arg, msgbuf, bufsize); - ival = PyLong_AsLong(arg); - if (ival == -1 && PyErr_Occurred()) - return converterr("integer", arg, msgbuf, bufsize); - else if (ival < SHRT_MIN) { - PyErr_SetString(PyExc_OverflowError, - "signed short integer is less than minimum"); - return converterr("integer", arg, msgbuf, bufsize); - } - else if (ival > SHRT_MAX) { - PyErr_SetString(PyExc_OverflowError, - "signed short integer is greater than maximum"); - return converterr("integer", arg, msgbuf, bufsize); - } - else - *p = (short) ival; - break; - } - - case 'H': { /* short int sized bitfield, both signed and - unsigned allowed */ - unsigned short *p = va_arg(*p_va, unsigned short *); - long ival; - if (float_argument_error(arg)) - return converterr("integer", arg, msgbuf, bufsize); - ival = PyLong_AsUnsignedLongMask(arg); - if (ival == -1 && PyErr_Occurred()) - return converterr("integer", arg, msgbuf, bufsize); - else - *p = (unsigned short) ival; - break; - } - - case 'i': {/* signed int */ - int *p = va_arg(*p_va, int *); - long ival; - if (float_argument_error(arg)) - return converterr("integer", arg, msgbuf, bufsize); - ival = PyLong_AsLong(arg); - if (ival == -1 && PyErr_Occurred()) - return converterr("integer", arg, msgbuf, bufsize); - else if (ival > INT_MAX) { - PyErr_SetString(PyExc_OverflowError, - "signed integer is greater than maximum"); - return converterr("integer", arg, msgbuf, bufsize); - } - else if (ival < INT_MIN) { - PyErr_SetString(PyExc_OverflowError, - "signed integer is less than minimum"); - return converterr("integer", arg, msgbuf, bufsize); - } - else - *p = ival; - break; - } - - case 'I': { /* int sized bitfield, both signed and - unsigned allowed */ - unsigned int *p = va_arg(*p_va, unsigned int *); - unsigned int ival; - if (float_argument_error(arg)) - return converterr("integer", arg, msgbuf, bufsize); - ival = (unsigned int)PyLong_AsUnsignedLongMask(arg); - if (ival == (unsigned int)-1 && PyErr_Occurred()) - return converterr("integer", arg, msgbuf, bufsize); - else - *p = ival; - break; - } - - case 'n': /* Py_ssize_t */ - { - PyObject *iobj; - Py_ssize_t *p = va_arg(*p_va, Py_ssize_t *); - Py_ssize_t ival = -1; - if (float_argument_error(arg)) - return converterr("integer", arg, msgbuf, bufsize); - iobj = PyNumber_Index(arg); - if (iobj != NULL) { - ival = PyLong_AsSsize_t(iobj); - Py_DECREF(iobj); - } - if (ival == -1 && PyErr_Occurred()) - return converterr("integer", arg, msgbuf, bufsize); - *p = ival; - break; - } - case 'l': {/* long int */ - long *p = va_arg(*p_va, long *); - long ival; - if (float_argument_error(arg)) - return converterr("integer", arg, msgbuf, bufsize); - ival = PyLong_AsLong(arg); - if (ival == -1 && PyErr_Occurred()) - return converterr("integer", arg, msgbuf, bufsize); - else - *p = ival; - break; - } - - case 'k': { /* long sized bitfield */ - unsigned long *p = va_arg(*p_va, unsigned long *); - unsigned long ival; - if (PyLong_Check(arg)) - ival = PyLong_AsUnsignedLongMask(arg); - else - return converterr("integer", arg, msgbuf, bufsize); - *p = ival; - break; - } + const char *format = *p_format; + char c = *format++; + PyObject *uarg; + + switch (c) { + + case 'b': { /* unsigned byte -- very short int */ + char *p = va_arg(*p_va, char *); + long ival; + if (float_argument_error(arg)) + return converterr("integer", arg, msgbuf, bufsize); + ival = PyLong_AsLong(arg); + if (ival == -1 && PyErr_Occurred()) + return converterr("integer", arg, msgbuf, bufsize); + else if (ival < 0) { + PyErr_SetString(PyExc_OverflowError, + "unsigned byte integer is less than minimum"); + return converterr("integer", arg, msgbuf, bufsize); + } + else if (ival > UCHAR_MAX) { + PyErr_SetString(PyExc_OverflowError, + "unsigned byte integer is greater than maximum"); + return converterr("integer", arg, msgbuf, bufsize); + } + else + *p = (unsigned char) ival; + break; + } + + case 'B': {/* byte sized bitfield - both signed and unsigned + values allowed */ + char *p = va_arg(*p_va, char *); + long ival; + if (float_argument_error(arg)) + return converterr("integer", arg, msgbuf, bufsize); + ival = PyLong_AsUnsignedLongMask(arg); + if (ival == -1 && PyErr_Occurred()) + return converterr("integer", arg, msgbuf, bufsize); + else + *p = (unsigned char) ival; + break; + } + + case 'h': {/* signed short int */ + short *p = va_arg(*p_va, short *); + long ival; + if (float_argument_error(arg)) + return converterr("integer", arg, msgbuf, bufsize); + ival = PyLong_AsLong(arg); + if (ival == -1 && PyErr_Occurred()) + return converterr("integer", arg, msgbuf, bufsize); + else if (ival < SHRT_MIN) { + PyErr_SetString(PyExc_OverflowError, + "signed short integer is less than minimum"); + return converterr("integer", arg, msgbuf, bufsize); + } + else if (ival > SHRT_MAX) { + PyErr_SetString(PyExc_OverflowError, + "signed short integer is greater than maximum"); + return converterr("integer", arg, msgbuf, bufsize); + } + else + *p = (short) ival; + break; + } + + case 'H': { /* short int sized bitfield, both signed and + unsigned allowed */ + unsigned short *p = va_arg(*p_va, unsigned short *); + long ival; + if (float_argument_error(arg)) + return converterr("integer", arg, msgbuf, bufsize); + ival = PyLong_AsUnsignedLongMask(arg); + if (ival == -1 && PyErr_Occurred()) + return converterr("integer", arg, msgbuf, bufsize); + else + *p = (unsigned short) ival; + break; + } + + case 'i': {/* signed int */ + int *p = va_arg(*p_va, int *); + long ival; + if (float_argument_error(arg)) + return converterr("integer", arg, msgbuf, bufsize); + ival = PyLong_AsLong(arg); + if (ival == -1 && PyErr_Occurred()) + return converterr("integer", arg, msgbuf, bufsize); + else if (ival > INT_MAX) { + PyErr_SetString(PyExc_OverflowError, + "signed integer is greater than maximum"); + return converterr("integer", arg, msgbuf, bufsize); + } + else if (ival < INT_MIN) { + PyErr_SetString(PyExc_OverflowError, + "signed integer is less than minimum"); + return converterr("integer", arg, msgbuf, bufsize); + } + else + *p = ival; + break; + } + + case 'I': { /* int sized bitfield, both signed and + unsigned allowed */ + unsigned int *p = va_arg(*p_va, unsigned int *); + unsigned int ival; + if (float_argument_error(arg)) + return converterr("integer", arg, msgbuf, bufsize); + ival = (unsigned int)PyLong_AsUnsignedLongMask(arg); + if (ival == (unsigned int)-1 && PyErr_Occurred()) + return converterr("integer", arg, msgbuf, bufsize); + else + *p = ival; + break; + } + + case 'n': /* Py_ssize_t */ + { + PyObject *iobj; + Py_ssize_t *p = va_arg(*p_va, Py_ssize_t *); + Py_ssize_t ival = -1; + if (float_argument_error(arg)) + return converterr("integer", arg, msgbuf, bufsize); + iobj = PyNumber_Index(arg); + if (iobj != NULL) { + ival = PyLong_AsSsize_t(iobj); + Py_DECREF(iobj); + } + if (ival == -1 && PyErr_Occurred()) + return converterr("integer", arg, msgbuf, bufsize); + *p = ival; + break; + } + case 'l': {/* long int */ + long *p = va_arg(*p_va, long *); + long ival; + if (float_argument_error(arg)) + return converterr("integer", arg, msgbuf, bufsize); + ival = PyLong_AsLong(arg); + if (ival == -1 && PyErr_Occurred()) + return converterr("integer", arg, msgbuf, bufsize); + else + *p = ival; + break; + } + + case 'k': { /* long sized bitfield */ + unsigned long *p = va_arg(*p_va, unsigned long *); + unsigned long ival; + if (PyLong_Check(arg)) + ival = PyLong_AsUnsignedLongMask(arg); + else + return converterr("integer", arg, msgbuf, bufsize); + *p = ival; + break; + } #ifdef HAVE_LONG_LONG - case 'L': {/* PY_LONG_LONG */ - PY_LONG_LONG *p = va_arg( *p_va, PY_LONG_LONG * ); - PY_LONG_LONG ival; - if (float_argument_warning(arg)) - return converterr("long", arg, msgbuf, bufsize); - ival = PyLong_AsLongLong(arg); - if (ival == (PY_LONG_LONG)-1 && PyErr_Occurred() ) { - return converterr("long", arg, msgbuf, bufsize); - } else { - *p = ival; - } - break; - } - - case 'K': { /* long long sized bitfield */ - unsigned PY_LONG_LONG *p = va_arg(*p_va, unsigned PY_LONG_LONG *); - unsigned PY_LONG_LONG ival; - if (PyLong_Check(arg)) - ival = PyLong_AsUnsignedLongLongMask(arg); - else - return converterr("integer", arg, msgbuf, bufsize); - *p = ival; - break; - } + case 'L': {/* PY_LONG_LONG */ + PY_LONG_LONG *p = va_arg( *p_va, PY_LONG_LONG * ); + PY_LONG_LONG ival; + if (float_argument_warning(arg)) + return converterr("long", arg, msgbuf, bufsize); + ival = PyLong_AsLongLong(arg); + if (ival == (PY_LONG_LONG)-1 && PyErr_Occurred() ) { + return converterr("long", arg, msgbuf, bufsize); + } else { + *p = ival; + } + break; + } + + case 'K': { /* long long sized bitfield */ + unsigned PY_LONG_LONG *p = va_arg(*p_va, unsigned PY_LONG_LONG *); + unsigned PY_LONG_LONG ival; + if (PyLong_Check(arg)) + ival = PyLong_AsUnsignedLongLongMask(arg); + else + return converterr("integer", arg, msgbuf, bufsize); + *p = ival; + break; + } #endif - case 'f': {/* float */ - float *p = va_arg(*p_va, float *); - double dval = PyFloat_AsDouble(arg); - if (PyErr_Occurred()) - return converterr("float", arg, msgbuf, bufsize); - else - *p = (float) dval; - break; - } - - case 'd': {/* double */ - double *p = va_arg(*p_va, double *); - double dval = PyFloat_AsDouble(arg); - if (PyErr_Occurred()) - return converterr("float", arg, msgbuf, bufsize); - else - *p = dval; - break; - } - - case 'D': {/* complex double */ - Py_complex *p = va_arg(*p_va, Py_complex *); - Py_complex cval; - cval = PyComplex_AsCComplex(arg); - if (PyErr_Occurred()) - return converterr("complex", arg, msgbuf, bufsize); - else - *p = cval; - break; - } - - case 'c': {/* char */ - char *p = va_arg(*p_va, char *); - if (PyBytes_Check(arg) && PyBytes_Size(arg) == 1) - *p = PyBytes_AS_STRING(arg)[0]; - else - return converterr("a byte string of length 1", arg, msgbuf, bufsize); - break; - } - - case 'C': {/* unicode char */ - int *p = va_arg(*p_va, int *); - if (PyUnicode_Check(arg) && - PyUnicode_GET_SIZE(arg) == 1) - *p = PyUnicode_AS_UNICODE(arg)[0]; - else - return converterr("a unicode character", arg, msgbuf, bufsize); - break; - } - - /* XXX WAAAAH! 's', 'y', 'z', 'u', 'Z', 'e', 'w', 't' codes all - need to be cleaned up! */ - - case 's': {/* text string */ - if (*format == '*') { - Py_buffer *p = (Py_buffer *)va_arg(*p_va, Py_buffer *); - - if (PyUnicode_Check(arg)) { - uarg = UNICODE_DEFAULT_ENCODING(arg); - if (uarg == NULL) - return converterr(CONV_UNICODE, - arg, msgbuf, bufsize); - PyBuffer_FillInfo(p, arg, - PyBytes_AS_STRING(uarg), PyBytes_GET_SIZE(uarg), - 1, 0); - } - else { /* any buffer-like object */ - char *buf; - if (getbuffer(arg, p, &buf) < 0) - return converterr(buf, arg, msgbuf, bufsize); - } - if (addcleanup(p, freelist, cleanup_buffer)) { - return converterr( - "(cleanup problem)", - arg, msgbuf, bufsize); - } - format++; - } else if (*format == '#') { - void **p = (void **)va_arg(*p_va, char **); - FETCH_SIZE; - - if (PyUnicode_Check(arg)) { - uarg = UNICODE_DEFAULT_ENCODING(arg); - if (uarg == NULL) - return converterr(CONV_UNICODE, - arg, msgbuf, bufsize); - *p = PyBytes_AS_STRING(uarg); - STORE_SIZE(PyBytes_GET_SIZE(uarg)); - } - else { /* any buffer-like object */ - /* XXX Really? */ - char *buf; - Py_ssize_t count = convertbuffer(arg, p, &buf); - if (count < 0) - return converterr(buf, arg, msgbuf, bufsize); - STORE_SIZE(count); - } - format++; - } else { - char **p = va_arg(*p_va, char **); - - if (PyUnicode_Check(arg)) { - uarg = UNICODE_DEFAULT_ENCODING(arg); - if (uarg == NULL) - return converterr(CONV_UNICODE, - arg, msgbuf, bufsize); - *p = PyBytes_AS_STRING(uarg); - } - else - return converterr("string", arg, msgbuf, bufsize); - if ((Py_ssize_t) strlen(*p) != PyBytes_GET_SIZE(uarg)) - return converterr("string without null bytes", - arg, msgbuf, bufsize); - } - break; - } - - case 'y': {/* any buffer-like object, but not PyUnicode */ - void **p = (void **)va_arg(*p_va, char **); - char *buf; - Py_ssize_t count; - if (*format == '*') { - if (getbuffer(arg, (Py_buffer*)p, &buf) < 0) - return converterr(buf, arg, msgbuf, bufsize); - format++; - if (addcleanup(p, freelist, cleanup_buffer)) { - return converterr( - "(cleanup problem)", - arg, msgbuf, bufsize); - } - break; - } - count = convertbuffer(arg, p, &buf); - if (count < 0) - return converterr(buf, arg, msgbuf, bufsize); - else if (*format == '#') { - FETCH_SIZE; - STORE_SIZE(count); - format++; - } - break; - } - - case 'z': {/* like 's' or 's#', but None is okay, stored as NULL */ - if (*format == '*') { - Py_buffer *p = (Py_buffer *)va_arg(*p_va, Py_buffer *); - - if (arg == Py_None) - PyBuffer_FillInfo(p, NULL, NULL, 0, 1, 0); - else if (PyUnicode_Check(arg)) { - uarg = UNICODE_DEFAULT_ENCODING(arg); - if (uarg == NULL) - return converterr(CONV_UNICODE, - arg, msgbuf, bufsize); - PyBuffer_FillInfo(p, arg, - PyBytes_AS_STRING(uarg), PyBytes_GET_SIZE(uarg), - 1, 0); - } - else { /* any buffer-like object */ - char *buf; - if (getbuffer(arg, p, &buf) < 0) - return converterr(buf, arg, msgbuf, bufsize); - } - if (addcleanup(p, freelist, cleanup_buffer)) { - return converterr( - "(cleanup problem)", - arg, msgbuf, bufsize); - } - format++; - } else if (*format == '#') { /* any buffer-like object */ - void **p = (void **)va_arg(*p_va, char **); - FETCH_SIZE; - - if (arg == Py_None) { - *p = 0; - STORE_SIZE(0); - } - else if (PyUnicode_Check(arg)) { - uarg = UNICODE_DEFAULT_ENCODING(arg); - if (uarg == NULL) - return converterr(CONV_UNICODE, - arg, msgbuf, bufsize); - *p = PyBytes_AS_STRING(uarg); - STORE_SIZE(PyBytes_GET_SIZE(uarg)); - } - else { /* any buffer-like object */ - /* XXX Really? */ - char *buf; - Py_ssize_t count = convertbuffer(arg, p, &buf); - if (count < 0) - return converterr(buf, arg, msgbuf, bufsize); - STORE_SIZE(count); - } - format++; - } else { - char **p = va_arg(*p_va, char **); - uarg = NULL; - - if (arg == Py_None) - *p = 0; - else if (PyBytes_Check(arg)) { - /* Enable null byte check below */ - uarg = arg; - *p = PyBytes_AS_STRING(arg); - } - else if (PyUnicode_Check(arg)) { - uarg = UNICODE_DEFAULT_ENCODING(arg); - if (uarg == NULL) - return converterr(CONV_UNICODE, - arg, msgbuf, bufsize); - *p = PyBytes_AS_STRING(uarg); - } - else - return converterr("string or None", - arg, msgbuf, bufsize); - if (*format == '#') { - FETCH_SIZE; - assert(0); /* XXX redundant with if-case */ - if (arg == Py_None) { - STORE_SIZE(0); - } - else { - STORE_SIZE(PyBytes_Size(arg)); - } - format++; - } - else if (*p != NULL && uarg != NULL && - (Py_ssize_t) strlen(*p) != PyBytes_GET_SIZE(uarg)) - return converterr( - "string without null bytes or None", - arg, msgbuf, bufsize); - } - break; - } - - case 'Z': {/* unicode, may be NULL (None) */ - if (*format == '#') { /* any buffer-like object */ - Py_UNICODE **p = va_arg(*p_va, Py_UNICODE **); - FETCH_SIZE; - - if (arg == Py_None) { - *p = 0; - STORE_SIZE(0); - } - else if (PyUnicode_Check(arg)) { - *p = PyUnicode_AS_UNICODE(arg); - STORE_SIZE(PyUnicode_GET_SIZE(arg)); - } - format++; - } else { - Py_UNICODE **p = va_arg(*p_va, Py_UNICODE **); - - if (arg == Py_None) - *p = 0; - else if (PyUnicode_Check(arg)) - *p = PyUnicode_AS_UNICODE(arg); - else - return converterr("string or None", - arg, msgbuf, bufsize); - } - break; - } - - case 'e': {/* encoded string */ - char **buffer; - const char *encoding; - PyObject *s; - int recode_strings; - Py_ssize_t size; - const char *ptr; - - /* Get 'e' parameter: the encoding name */ - encoding = (const char *)va_arg(*p_va, const char *); - if (encoding == NULL) - encoding = PyUnicode_GetDefaultEncoding(); - - /* Get output buffer parameter: - 's' (recode all objects via Unicode) or - 't' (only recode non-string objects) - */ - if (*format == 's') - recode_strings = 1; - else if (*format == 't') - recode_strings = 0; - else - return converterr( - "(unknown parser marker combination)", - arg, msgbuf, bufsize); - buffer = (char **)va_arg(*p_va, char **); - format++; - if (buffer == NULL) - return converterr("(buffer is NULL)", - arg, msgbuf, bufsize); - - /* Encode object */ - if (!recode_strings && - (PyBytes_Check(arg) || PyByteArray_Check(arg))) { - s = arg; - Py_INCREF(s); - if (PyObject_AsCharBuffer(s, &ptr, &size) < 0) - return converterr("(AsCharBuffer failed)", - arg, msgbuf, bufsize); - } - else { - PyObject *u; - - /* Convert object to Unicode */ - u = PyUnicode_FromObject(arg); - if (u == NULL) - return converterr( - "string or unicode or text buffer", - arg, msgbuf, bufsize); - - /* Encode object; use default error handling */ - s = PyUnicode_AsEncodedString(u, - encoding, - NULL); - Py_DECREF(u); - if (s == NULL) - return converterr("(encoding failed)", - arg, msgbuf, bufsize); - if (!PyBytes_Check(s)) { - Py_DECREF(s); - return converterr( - "(encoder failed to return bytes)", - arg, msgbuf, bufsize); - } - size = PyBytes_GET_SIZE(s); - ptr = PyBytes_AS_STRING(s); - if (ptr == NULL) - ptr = ""; - } - - /* Write output; output is guaranteed to be 0-terminated */ - if (*format == '#') { - /* Using buffer length parameter '#': - - - if *buffer is NULL, a new buffer of the - needed size is allocated and the data - copied into it; *buffer is updated to point - to the new buffer; the caller is - responsible for PyMem_Free()ing it after - usage - - - if *buffer is not NULL, the data is - copied to *buffer; *buffer_len has to be - set to the size of the buffer on input; - buffer overflow is signalled with an error; - buffer has to provide enough room for the - encoded string plus the trailing 0-byte - - - in both cases, *buffer_len is updated to - the size of the buffer /excluding/ the - trailing 0-byte - - */ - FETCH_SIZE; - - format++; - if (q == NULL && q2 == NULL) { - Py_DECREF(s); - return converterr( - "(buffer_len is NULL)", - arg, msgbuf, bufsize); - } - if (*buffer == NULL) { - *buffer = PyMem_NEW(char, size + 1); - if (*buffer == NULL) { - Py_DECREF(s); - return converterr( - "(memory error)", - arg, msgbuf, bufsize); - } - if (addcleanup(*buffer, freelist, cleanup_ptr)) { - Py_DECREF(s); - return converterr( - "(cleanup problem)", - arg, msgbuf, bufsize); - } - } else { - if (size + 1 > BUFFER_LEN) { - Py_DECREF(s); - return converterr( - "(buffer overflow)", - arg, msgbuf, bufsize); - } - } - memcpy(*buffer, ptr, size+1); - STORE_SIZE(size); - } else { - /* Using a 0-terminated buffer: - - - the encoded string has to be 0-terminated - for this variant to work; if it is not, an - error raised - - - a new buffer of the needed size is - allocated and the data copied into it; - *buffer is updated to point to the new - buffer; the caller is responsible for - PyMem_Free()ing it after usage - - */ - if ((Py_ssize_t)strlen(ptr) != size) { - Py_DECREF(s); - return converterr( - "encoded string without NULL bytes", - arg, msgbuf, bufsize); - } - *buffer = PyMem_NEW(char, size + 1); - if (*buffer == NULL) { - Py_DECREF(s); - return converterr("(memory error)", - arg, msgbuf, bufsize); - } - if (addcleanup(*buffer, freelist, cleanup_ptr)) { - Py_DECREF(s); - return converterr("(cleanup problem)", - arg, msgbuf, bufsize); - } - memcpy(*buffer, ptr, size+1); - } - Py_DECREF(s); - break; - } - - case 'u': {/* raw unicode buffer (Py_UNICODE *) */ - Py_UNICODE **p = va_arg(*p_va, Py_UNICODE **); - if (!PyUnicode_Check(arg)) - return converterr("str", arg, msgbuf, bufsize); - *p = PyUnicode_AS_UNICODE(arg); - if (*format == '#') { /* store pointer and size */ - FETCH_SIZE; - STORE_SIZE(PyUnicode_GET_SIZE(arg)); - format++; - } - break; - } - - case 'S': { /* PyBytes object */ - PyObject **p = va_arg(*p_va, PyObject **); - if (PyBytes_Check(arg)) - *p = arg; - else - return converterr("bytes", arg, msgbuf, bufsize); - break; - } - - case 'Y': { /* PyByteArray object */ - PyObject **p = va_arg(*p_va, PyObject **); - if (PyByteArray_Check(arg)) - *p = arg; - else - return converterr("buffer", arg, msgbuf, bufsize); - break; - } - - case 'U': { /* PyUnicode object */ - PyObject **p = va_arg(*p_va, PyObject **); - if (PyUnicode_Check(arg)) - *p = arg; - else - return converterr("str", arg, msgbuf, bufsize); - break; - } - - case 'O': { /* object */ - PyTypeObject *type; - PyObject **p; - if (*format == '!') { - type = va_arg(*p_va, PyTypeObject*); - p = va_arg(*p_va, PyObject **); - format++; - if (PyType_IsSubtype(arg->ob_type, type)) - *p = arg; - else - return converterr(type->tp_name, arg, msgbuf, bufsize); - - } - else if (*format == '?') { - inquiry pred = va_arg(*p_va, inquiry); - p = va_arg(*p_va, PyObject **); - format++; - if ((*pred)(arg)) - *p = arg; - else - return converterr("(unspecified)", - arg, msgbuf, bufsize); - - } - else if (*format == '&') { - typedef int (*converter)(PyObject *, void *); - converter convert = va_arg(*p_va, converter); - void *addr = va_arg(*p_va, void *); - int res; - format++; - if (! (res = (*convert)(arg, addr))) - return converterr("(unspecified)", - arg, msgbuf, bufsize); - if (res == Py_CLEANUP_SUPPORTED && - addcleanup_convert(addr, freelist, convert) == -1) - return converterr("(cleanup problem)", - arg, msgbuf, bufsize); - } - else { - p = va_arg(*p_va, PyObject **); - *p = arg; - } - break; - } - - - case 'w': { /* memory buffer, read-write access */ - void **p = va_arg(*p_va, void **); - PyBufferProcs *pb = arg->ob_type->tp_as_buffer; - Py_ssize_t count; - int temp=-1; - Py_buffer view; - - if (pb && pb->bf_releasebuffer && *format != '*') - /* Buffer must be released, yet caller does not use - the Py_buffer protocol. */ - return converterr("pinned buffer", arg, msgbuf, bufsize); - - - if (pb && pb->bf_getbuffer && *format == '*') { - /* Caller is interested in Py_buffer, and the object - supports it directly. */ - format++; - if (PyObject_GetBuffer(arg, (Py_buffer*)p, PyBUF_WRITABLE) < 0) { - PyErr_Clear(); - return converterr("read-write buffer", arg, msgbuf, bufsize); - } - if (addcleanup(p, freelist, cleanup_buffer)) { - return converterr( - "(cleanup problem)", - arg, msgbuf, bufsize); - } - if (!PyBuffer_IsContiguous((Py_buffer*)p, 'C')) - return converterr("contiguous buffer", arg, msgbuf, bufsize); - break; - } - - /* Here we have processed w*, only w and w# remain. */ - if (pb == NULL || - pb->bf_getbuffer == NULL || - ((temp = PyObject_GetBuffer(arg, &view, - PyBUF_SIMPLE)) != 0) || - view.readonly == 1) { - if (temp==0) { - PyBuffer_Release(&view); - } - return converterr("single-segment read-write buffer", - arg, msgbuf, bufsize); + case 'f': {/* float */ + float *p = va_arg(*p_va, float *); + double dval = PyFloat_AsDouble(arg); + if (PyErr_Occurred()) + return converterr("float", arg, msgbuf, bufsize); + else + *p = (float) dval; + break; + } + + case 'd': {/* double */ + double *p = va_arg(*p_va, double *); + double dval = PyFloat_AsDouble(arg); + if (PyErr_Occurred()) + return converterr("float", arg, msgbuf, bufsize); + else + *p = dval; + break; + } + + case 'D': {/* complex double */ + Py_complex *p = va_arg(*p_va, Py_complex *); + Py_complex cval; + cval = PyComplex_AsCComplex(arg); + if (PyErr_Occurred()) + return converterr("complex", arg, msgbuf, bufsize); + else + *p = cval; + break; + } + + case 'c': {/* char */ + char *p = va_arg(*p_va, char *); + if (PyBytes_Check(arg) && PyBytes_Size(arg) == 1) + *p = PyBytes_AS_STRING(arg)[0]; + else + return converterr("a byte string of length 1", arg, msgbuf, bufsize); + break; + } + + case 'C': {/* unicode char */ + int *p = va_arg(*p_va, int *); + if (PyUnicode_Check(arg) && + PyUnicode_GET_SIZE(arg) == 1) + *p = PyUnicode_AS_UNICODE(arg)[0]; + else + return converterr("a unicode character", arg, msgbuf, bufsize); + break; + } + + /* XXX WAAAAH! 's', 'y', 'z', 'u', 'Z', 'e', 'w', 't' codes all + need to be cleaned up! */ + + case 's': {/* text string */ + if (*format == '*') { + Py_buffer *p = (Py_buffer *)va_arg(*p_va, Py_buffer *); + + if (PyUnicode_Check(arg)) { + uarg = UNICODE_DEFAULT_ENCODING(arg); + if (uarg == NULL) + return converterr(CONV_UNICODE, + arg, msgbuf, bufsize); + PyBuffer_FillInfo(p, arg, + PyBytes_AS_STRING(uarg), PyBytes_GET_SIZE(uarg), + 1, 0); + } + else { /* any buffer-like object */ + char *buf; + if (getbuffer(arg, p, &buf) < 0) + return converterr(buf, arg, msgbuf, bufsize); + } + if (addcleanup(p, freelist, cleanup_buffer)) { + return converterr( + "(cleanup problem)", + arg, msgbuf, bufsize); + } + format++; + } else if (*format == '#') { + void **p = (void **)va_arg(*p_va, char **); + FETCH_SIZE; + + if (PyUnicode_Check(arg)) { + uarg = UNICODE_DEFAULT_ENCODING(arg); + if (uarg == NULL) + return converterr(CONV_UNICODE, + arg, msgbuf, bufsize); + *p = PyBytes_AS_STRING(uarg); + STORE_SIZE(PyBytes_GET_SIZE(uarg)); + } + else { /* any buffer-like object */ + /* XXX Really? */ + char *buf; + Py_ssize_t count = convertbuffer(arg, p, &buf); + if (count < 0) + return converterr(buf, arg, msgbuf, bufsize); + STORE_SIZE(count); + } + format++; + } else { + char **p = va_arg(*p_va, char **); + + if (PyUnicode_Check(arg)) { + uarg = UNICODE_DEFAULT_ENCODING(arg); + if (uarg == NULL) + return converterr(CONV_UNICODE, + arg, msgbuf, bufsize); + *p = PyBytes_AS_STRING(uarg); + } + else + return converterr("string", arg, msgbuf, bufsize); + if ((Py_ssize_t) strlen(*p) != PyBytes_GET_SIZE(uarg)) + return converterr("string without null bytes", + arg, msgbuf, bufsize); + } + break; + } + + case 'y': {/* any buffer-like object, but not PyUnicode */ + void **p = (void **)va_arg(*p_va, char **); + char *buf; + Py_ssize_t count; + if (*format == '*') { + if (getbuffer(arg, (Py_buffer*)p, &buf) < 0) + return converterr(buf, arg, msgbuf, bufsize); + format++; + if (addcleanup(p, freelist, cleanup_buffer)) { + return converterr( + "(cleanup problem)", + arg, msgbuf, bufsize); + } + break; + } + count = convertbuffer(arg, p, &buf); + if (count < 0) + return converterr(buf, arg, msgbuf, bufsize); + else if (*format == '#') { + FETCH_SIZE; + STORE_SIZE(count); + format++; + } + break; + } + + case 'z': {/* like 's' or 's#', but None is okay, stored as NULL */ + if (*format == '*') { + Py_buffer *p = (Py_buffer *)va_arg(*p_va, Py_buffer *); + + if (arg == Py_None) + PyBuffer_FillInfo(p, NULL, NULL, 0, 1, 0); + else if (PyUnicode_Check(arg)) { + uarg = UNICODE_DEFAULT_ENCODING(arg); + if (uarg == NULL) + return converterr(CONV_UNICODE, + arg, msgbuf, bufsize); + PyBuffer_FillInfo(p, arg, + PyBytes_AS_STRING(uarg), PyBytes_GET_SIZE(uarg), + 1, 0); + } + else { /* any buffer-like object */ + char *buf; + if (getbuffer(arg, p, &buf) < 0) + return converterr(buf, arg, msgbuf, bufsize); + } + if (addcleanup(p, freelist, cleanup_buffer)) { + return converterr( + "(cleanup problem)", + arg, msgbuf, bufsize); + } + format++; + } else if (*format == '#') { /* any buffer-like object */ + void **p = (void **)va_arg(*p_va, char **); + FETCH_SIZE; + + if (arg == Py_None) { + *p = 0; + STORE_SIZE(0); + } + else if (PyUnicode_Check(arg)) { + uarg = UNICODE_DEFAULT_ENCODING(arg); + if (uarg == NULL) + return converterr(CONV_UNICODE, + arg, msgbuf, bufsize); + *p = PyBytes_AS_STRING(uarg); + STORE_SIZE(PyBytes_GET_SIZE(uarg)); + } + else { /* any buffer-like object */ + /* XXX Really? */ + char *buf; + Py_ssize_t count = convertbuffer(arg, p, &buf); + if (count < 0) + return converterr(buf, arg, msgbuf, bufsize); + STORE_SIZE(count); + } + format++; + } else { + char **p = va_arg(*p_va, char **); + uarg = NULL; + + if (arg == Py_None) + *p = 0; + else if (PyBytes_Check(arg)) { + /* Enable null byte check below */ + uarg = arg; + *p = PyBytes_AS_STRING(arg); + } + else if (PyUnicode_Check(arg)) { + uarg = UNICODE_DEFAULT_ENCODING(arg); + if (uarg == NULL) + return converterr(CONV_UNICODE, + arg, msgbuf, bufsize); + *p = PyBytes_AS_STRING(uarg); + } + else + return converterr("string or None", + arg, msgbuf, bufsize); + if (*format == '#') { + FETCH_SIZE; + assert(0); /* XXX redundant with if-case */ + if (arg == Py_None) { + STORE_SIZE(0); + } + else { + STORE_SIZE(PyBytes_Size(arg)); + } + format++; + } + else if (*p != NULL && uarg != NULL && + (Py_ssize_t) strlen(*p) != PyBytes_GET_SIZE(uarg)) + return converterr( + "string without null bytes or None", + arg, msgbuf, bufsize); + } + break; + } + + case 'Z': {/* unicode, may be NULL (None) */ + if (*format == '#') { /* any buffer-like object */ + Py_UNICODE **p = va_arg(*p_va, Py_UNICODE **); + FETCH_SIZE; + + if (arg == Py_None) { + *p = 0; + STORE_SIZE(0); + } + else if (PyUnicode_Check(arg)) { + *p = PyUnicode_AS_UNICODE(arg); + STORE_SIZE(PyUnicode_GET_SIZE(arg)); + } + format++; + } else { + Py_UNICODE **p = va_arg(*p_va, Py_UNICODE **); + + if (arg == Py_None) + *p = 0; + else if (PyUnicode_Check(arg)) + *p = PyUnicode_AS_UNICODE(arg); + else + return converterr("string or None", + arg, msgbuf, bufsize); + } + break; + } + + case 'e': {/* encoded string */ + char **buffer; + const char *encoding; + PyObject *s; + int recode_strings; + Py_ssize_t size; + const char *ptr; + + /* Get 'e' parameter: the encoding name */ + encoding = (const char *)va_arg(*p_va, const char *); + if (encoding == NULL) + encoding = PyUnicode_GetDefaultEncoding(); + + /* Get output buffer parameter: + 's' (recode all objects via Unicode) or + 't' (only recode non-string objects) + */ + if (*format == 's') + recode_strings = 1; + else if (*format == 't') + recode_strings = 0; + else + return converterr( + "(unknown parser marker combination)", + arg, msgbuf, bufsize); + buffer = (char **)va_arg(*p_va, char **); + format++; + if (buffer == NULL) + return converterr("(buffer is NULL)", + arg, msgbuf, bufsize); + + /* Encode object */ + if (!recode_strings && + (PyBytes_Check(arg) || PyByteArray_Check(arg))) { + s = arg; + Py_INCREF(s); + if (PyObject_AsCharBuffer(s, &ptr, &size) < 0) + return converterr("(AsCharBuffer failed)", + arg, msgbuf, bufsize); + } + else { + PyObject *u; + + /* Convert object to Unicode */ + u = PyUnicode_FromObject(arg); + if (u == NULL) + return converterr( + "string or unicode or text buffer", + arg, msgbuf, bufsize); + + /* Encode object; use default error handling */ + s = PyUnicode_AsEncodedString(u, + encoding, + NULL); + Py_DECREF(u); + if (s == NULL) + return converterr("(encoding failed)", + arg, msgbuf, bufsize); + if (!PyBytes_Check(s)) { + Py_DECREF(s); + return converterr( + "(encoder failed to return bytes)", + arg, msgbuf, bufsize); + } + size = PyBytes_GET_SIZE(s); + ptr = PyBytes_AS_STRING(s); + if (ptr == NULL) + ptr = ""; + } + + /* Write output; output is guaranteed to be 0-terminated */ + if (*format == '#') { + /* Using buffer length parameter '#': + + - if *buffer is NULL, a new buffer of the + needed size is allocated and the data + copied into it; *buffer is updated to point + to the new buffer; the caller is + responsible for PyMem_Free()ing it after + usage + + - if *buffer is not NULL, the data is + copied to *buffer; *buffer_len has to be + set to the size of the buffer on input; + buffer overflow is signalled with an error; + buffer has to provide enough room for the + encoded string plus the trailing 0-byte + + - in both cases, *buffer_len is updated to + the size of the buffer /excluding/ the + trailing 0-byte + + */ + FETCH_SIZE; + + format++; + if (q == NULL && q2 == NULL) { + Py_DECREF(s); + return converterr( + "(buffer_len is NULL)", + arg, msgbuf, bufsize); + } + if (*buffer == NULL) { + *buffer = PyMem_NEW(char, size + 1); + if (*buffer == NULL) { + Py_DECREF(s); + return converterr( + "(memory error)", + arg, msgbuf, bufsize); + } + if (addcleanup(*buffer, freelist, cleanup_ptr)) { + Py_DECREF(s); + return converterr( + "(cleanup problem)", + arg, msgbuf, bufsize); + } + } else { + if (size + 1 > BUFFER_LEN) { + Py_DECREF(s); + return converterr( + "(buffer overflow)", + arg, msgbuf, bufsize); } + } + memcpy(*buffer, ptr, size+1); + STORE_SIZE(size); + } else { + /* Using a 0-terminated buffer: + + - the encoded string has to be 0-terminated + for this variant to work; if it is not, an + error raised + + - a new buffer of the needed size is + allocated and the data copied into it; + *buffer is updated to point to the new + buffer; the caller is responsible for + PyMem_Free()ing it after usage + + */ + if ((Py_ssize_t)strlen(ptr) != size) { + Py_DECREF(s); + return converterr( + "encoded string without NULL bytes", + arg, msgbuf, bufsize); + } + *buffer = PyMem_NEW(char, size + 1); + if (*buffer == NULL) { + Py_DECREF(s); + return converterr("(memory error)", + arg, msgbuf, bufsize); + } + if (addcleanup(*buffer, freelist, cleanup_ptr)) { + Py_DECREF(s); + return converterr("(cleanup problem)", + arg, msgbuf, bufsize); + } + memcpy(*buffer, ptr, size+1); + } + Py_DECREF(s); + break; + } + + case 'u': {/* raw unicode buffer (Py_UNICODE *) */ + Py_UNICODE **p = va_arg(*p_va, Py_UNICODE **); + if (!PyUnicode_Check(arg)) + return converterr("str", arg, msgbuf, bufsize); + *p = PyUnicode_AS_UNICODE(arg); + if (*format == '#') { /* store pointer and size */ + FETCH_SIZE; + STORE_SIZE(PyUnicode_GET_SIZE(arg)); + format++; + } + break; + } + + case 'S': { /* PyBytes object */ + PyObject **p = va_arg(*p_va, PyObject **); + if (PyBytes_Check(arg)) + *p = arg; + else + return converterr("bytes", arg, msgbuf, bufsize); + break; + } + + case 'Y': { /* PyByteArray object */ + PyObject **p = va_arg(*p_va, PyObject **); + if (PyByteArray_Check(arg)) + *p = arg; + else + return converterr("buffer", arg, msgbuf, bufsize); + break; + } + + case 'U': { /* PyUnicode object */ + PyObject **p = va_arg(*p_va, PyObject **); + if (PyUnicode_Check(arg)) + *p = arg; + else + return converterr("str", arg, msgbuf, bufsize); + break; + } + + case 'O': { /* object */ + PyTypeObject *type; + PyObject **p; + if (*format == '!') { + type = va_arg(*p_va, PyTypeObject*); + p = va_arg(*p_va, PyObject **); + format++; + if (PyType_IsSubtype(arg->ob_type, type)) + *p = arg; + else + return converterr(type->tp_name, arg, msgbuf, bufsize); + + } + else if (*format == '?') { + inquiry pred = va_arg(*p_va, inquiry); + p = va_arg(*p_va, PyObject **); + format++; + if ((*pred)(arg)) + *p = arg; + else + return converterr("(unspecified)", + arg, msgbuf, bufsize); + + } + else if (*format == '&') { + typedef int (*converter)(PyObject *, void *); + converter convert = va_arg(*p_va, converter); + void *addr = va_arg(*p_va, void *); + int res; + format++; + if (! (res = (*convert)(arg, addr))) + return converterr("(unspecified)", + arg, msgbuf, bufsize); + if (res == Py_CLEANUP_SUPPORTED && + addcleanup_convert(addr, freelist, convert) == -1) + return converterr("(cleanup problem)", + arg, msgbuf, bufsize); + } + else { + p = va_arg(*p_va, PyObject **); + *p = arg; + } + break; + } + + + case 'w': { /* memory buffer, read-write access */ + void **p = va_arg(*p_va, void **); + PyBufferProcs *pb = arg->ob_type->tp_as_buffer; + Py_ssize_t count; + int temp=-1; + Py_buffer view; + + if (pb && pb->bf_releasebuffer && *format != '*') + /* Buffer must be released, yet caller does not use + the Py_buffer protocol. */ + return converterr("pinned buffer", arg, msgbuf, bufsize); + + + if (pb && pb->bf_getbuffer && *format == '*') { + /* Caller is interested in Py_buffer, and the object + supports it directly. */ + format++; + if (PyObject_GetBuffer(arg, (Py_buffer*)p, PyBUF_WRITABLE) < 0) { + PyErr_Clear(); + return converterr("read-write buffer", arg, msgbuf, bufsize); + } + if (addcleanup(p, freelist, cleanup_buffer)) { + return converterr( + "(cleanup problem)", + arg, msgbuf, bufsize); + } + if (!PyBuffer_IsContiguous((Py_buffer*)p, 'C')) + return converterr("contiguous buffer", arg, msgbuf, bufsize); + break; + } + + /* Here we have processed w*, only w and w# remain. */ + if (pb == NULL || + pb->bf_getbuffer == NULL || + ((temp = PyObject_GetBuffer(arg, &view, + PyBUF_SIMPLE)) != 0) || + view.readonly == 1) { + if (temp==0) { + PyBuffer_Release(&view); + } + return converterr("single-segment read-write buffer", + arg, msgbuf, bufsize); + } + + if ((count = view.len) < 0) + return converterr("(unspecified)", arg, msgbuf, bufsize); + *p = view.buf; + if (*format == '#') { + FETCH_SIZE; + STORE_SIZE(count); + format++; + } + break; + } + + /*TEO: This can be eliminated --- here only for backward + compatibility */ + case 't': { /* 8-bit character buffer, read-only access */ + char **p = va_arg(*p_va, char **); + PyBufferProcs *pb = arg->ob_type->tp_as_buffer; + Py_ssize_t count; + Py_buffer view; - if ((count = view.len) < 0) - return converterr("(unspecified)", arg, msgbuf, bufsize); - *p = view.buf; - if (*format == '#') { - FETCH_SIZE; - STORE_SIZE(count); - format++; - } - break; - } - - /*TEO: This can be eliminated --- here only for backward - compatibility */ - case 't': { /* 8-bit character buffer, read-only access */ - char **p = va_arg(*p_va, char **); - PyBufferProcs *pb = arg->ob_type->tp_as_buffer; - Py_ssize_t count; - Py_buffer view; - - if (*format++ != '#') - return converterr( - "invalid use of 't' format character", - arg, msgbuf, bufsize); - if (pb == NULL || pb->bf_getbuffer == NULL) - return converterr( - "bytes or read-only character buffer", - arg, msgbuf, bufsize); - - if (PyObject_GetBuffer(arg, &view, PyBUF_SIMPLE) != 0) - return converterr("string or single-segment read-only buffer", - arg, msgbuf, bufsize); - - count = view.len; - *p = view.buf; - if (pb->bf_releasebuffer) - return converterr( - "string or pinned buffer", - arg, msgbuf, bufsize); - - PyBuffer_Release(&view); - - if (count < 0) - return converterr("(unspecified)", arg, msgbuf, bufsize); - { - FETCH_SIZE; - STORE_SIZE(count); - } - break; - } + if (*format++ != '#') + return converterr( + "invalid use of 't' format character", + arg, msgbuf, bufsize); + if (pb == NULL || pb->bf_getbuffer == NULL) + return converterr( + "bytes or read-only character buffer", + arg, msgbuf, bufsize); + + if (PyObject_GetBuffer(arg, &view, PyBUF_SIMPLE) != 0) + return converterr("string or single-segment read-only buffer", + arg, msgbuf, bufsize); - default: - return converterr("impossible", arg, msgbuf, bufsize); + count = view.len; + *p = view.buf; + if (pb->bf_releasebuffer) + return converterr( + "string or pinned buffer", + arg, msgbuf, bufsize); + + PyBuffer_Release(&view); + + if (count < 0) + return converterr("(unspecified)", arg, msgbuf, bufsize); + { + FETCH_SIZE; + STORE_SIZE(count); + } + break; + } - } + default: + return converterr("impossible", arg, msgbuf, bufsize); - *p_format = format; - return NULL; + } + + *p_format = format; + return NULL; } static Py_ssize_t convertbuffer(PyObject *arg, void **p, char **errmsg) { - PyBufferProcs *pb = arg->ob_type->tp_as_buffer; - Py_ssize_t count; - Py_buffer view; - - *errmsg = NULL; - *p = NULL; - if (pb == NULL || - pb->bf_getbuffer == NULL || - pb->bf_releasebuffer != NULL) { - *errmsg = "bytes or read-only buffer"; - return -1; - } - - if (PyObject_GetBuffer(arg, &view, PyBUF_SIMPLE) != 0) { - *errmsg = "bytes or single-segment read-only buffer"; - return -1; - } - count = view.len; - *p = view.buf; - PyBuffer_Release(&view); - return count; + PyBufferProcs *pb = arg->ob_type->tp_as_buffer; + Py_ssize_t count; + Py_buffer view; + + *errmsg = NULL; + *p = NULL; + if (pb == NULL || + pb->bf_getbuffer == NULL || + pb->bf_releasebuffer != NULL) { + *errmsg = "bytes or read-only buffer"; + return -1; + } + + if (PyObject_GetBuffer(arg, &view, PyBUF_SIMPLE) != 0) { + *errmsg = "bytes or single-segment read-only buffer"; + return -1; + } + count = view.len; + *p = view.buf; + PyBuffer_Release(&view); + return count; } /* XXX for 3.x, getbuffer and convertbuffer can probably @@ -1460,32 +1460,32 @@ static int getbuffer(PyObject *arg, Py_buffer *view, char **errmsg) { - void *buf; - Py_ssize_t count; - PyBufferProcs *pb = arg->ob_type->tp_as_buffer; - if (pb == NULL) { - *errmsg = "bytes or buffer"; - return -1; - } - if (pb->bf_getbuffer) { - if (PyObject_GetBuffer(arg, view, 0) < 0) { - *errmsg = "convertible to a buffer"; - return -1; - } - if (!PyBuffer_IsContiguous(view, 'C')) { - *errmsg = "contiguous buffer"; - return -1; - } - return 0; - } - - count = convertbuffer(arg, &buf, errmsg); - if (count < 0) { - *errmsg = "convertible to a buffer"; - return count; - } - PyBuffer_FillInfo(view, NULL, buf, count, 1, 0); - return 0; + void *buf; + Py_ssize_t count; + PyBufferProcs *pb = arg->ob_type->tp_as_buffer; + if (pb == NULL) { + *errmsg = "bytes or buffer"; + return -1; + } + if (pb->bf_getbuffer) { + if (PyObject_GetBuffer(arg, view, 0) < 0) { + *errmsg = "convertible to a buffer"; + return -1; + } + if (!PyBuffer_IsContiguous(view, 'C')) { + *errmsg = "contiguous buffer"; + return -1; + } + return 0; + } + + count = convertbuffer(arg, &buf, errmsg); + if (count < 0) { + *errmsg = "convertible to a buffer"; + return count; + } + PyBuffer_FillInfo(view, NULL, buf, count, 1, 0); + return 0; } /* Support for keyword arguments donated by @@ -1494,51 +1494,51 @@ /* Return false (0) for error, else true. */ int PyArg_ParseTupleAndKeywords(PyObject *args, - PyObject *keywords, - const char *format, - char **kwlist, ...) -{ - int retval; - va_list va; - - if ((args == NULL || !PyTuple_Check(args)) || - (keywords != NULL && !PyDict_Check(keywords)) || - format == NULL || - kwlist == NULL) - { - PyErr_BadInternalCall(); - return 0; - } - - va_start(va, kwlist); - retval = vgetargskeywords(args, keywords, format, kwlist, &va, 0); - va_end(va); - return retval; + PyObject *keywords, + const char *format, + char **kwlist, ...) +{ + int retval; + va_list va; + + if ((args == NULL || !PyTuple_Check(args)) || + (keywords != NULL && !PyDict_Check(keywords)) || + format == NULL || + kwlist == NULL) + { + PyErr_BadInternalCall(); + return 0; + } + + va_start(va, kwlist); + retval = vgetargskeywords(args, keywords, format, kwlist, &va, 0); + va_end(va); + return retval; } int _PyArg_ParseTupleAndKeywords_SizeT(PyObject *args, - PyObject *keywords, - const char *format, - char **kwlist, ...) -{ - int retval; - va_list va; - - if ((args == NULL || !PyTuple_Check(args)) || - (keywords != NULL && !PyDict_Check(keywords)) || - format == NULL || - kwlist == NULL) - { - PyErr_BadInternalCall(); - return 0; - } - - va_start(va, kwlist); - retval = vgetargskeywords(args, keywords, format, - kwlist, &va, FLAG_SIZE_T); - va_end(va); - return retval; + PyObject *keywords, + const char *format, + char **kwlist, ...) +{ + int retval; + va_list va; + + if ((args == NULL || !PyTuple_Check(args)) || + (keywords != NULL && !PyDict_Check(keywords)) || + format == NULL || + kwlist == NULL) + { + PyErr_BadInternalCall(); + return 0; + } + + va_start(va, kwlist); + retval = vgetargskeywords(args, keywords, format, + kwlist, &va, FLAG_SIZE_T); + va_end(va); + return retval; } @@ -1548,422 +1548,422 @@ const char *format, char **kwlist, va_list va) { - int retval; - va_list lva; + int retval; + va_list lva; - if ((args == NULL || !PyTuple_Check(args)) || - (keywords != NULL && !PyDict_Check(keywords)) || - format == NULL || - kwlist == NULL) - { - PyErr_BadInternalCall(); - return 0; - } + if ((args == NULL || !PyTuple_Check(args)) || + (keywords != NULL && !PyDict_Check(keywords)) || + format == NULL || + kwlist == NULL) + { + PyErr_BadInternalCall(); + return 0; + } #ifdef VA_LIST_IS_ARRAY - memcpy(lva, va, sizeof(va_list)); + memcpy(lva, va, sizeof(va_list)); #else #ifdef __va_copy - __va_copy(lva, va); + __va_copy(lva, va); #else - lva = va; + lva = va; #endif #endif - retval = vgetargskeywords(args, keywords, format, kwlist, &lva, 0); - return retval; + retval = vgetargskeywords(args, keywords, format, kwlist, &lva, 0); + return retval; } int _PyArg_VaParseTupleAndKeywords_SizeT(PyObject *args, - PyObject *keywords, - const char *format, - char **kwlist, va_list va) -{ - int retval; - va_list lva; - - if ((args == NULL || !PyTuple_Check(args)) || - (keywords != NULL && !PyDict_Check(keywords)) || - format == NULL || - kwlist == NULL) - { - PyErr_BadInternalCall(); - return 0; - } + PyObject *keywords, + const char *format, + char **kwlist, va_list va) +{ + int retval; + va_list lva; + + if ((args == NULL || !PyTuple_Check(args)) || + (keywords != NULL && !PyDict_Check(keywords)) || + format == NULL || + kwlist == NULL) + { + PyErr_BadInternalCall(); + return 0; + } #ifdef VA_LIST_IS_ARRAY - memcpy(lva, va, sizeof(va_list)); + memcpy(lva, va, sizeof(va_list)); #else #ifdef __va_copy - __va_copy(lva, va); + __va_copy(lva, va); #else - lva = va; + lva = va; #endif #endif - retval = vgetargskeywords(args, keywords, format, - kwlist, &lva, FLAG_SIZE_T); - return retval; + retval = vgetargskeywords(args, keywords, format, + kwlist, &lva, FLAG_SIZE_T); + return retval; } int PyArg_ValidateKeywordArguments(PyObject *kwargs) { - if (!PyDict_CheckExact(kwargs)) { - PyErr_BadInternalCall(); - return 0; - } - if (!_PyDict_HasOnlyStringKeys(kwargs)) { - PyErr_SetString(PyExc_TypeError, - "keyword arguments must be strings"); - return 0; - } - return 1; + if (!PyDict_CheckExact(kwargs)) { + PyErr_BadInternalCall(); + return 0; + } + if (!_PyDict_HasOnlyStringKeys(kwargs)) { + PyErr_SetString(PyExc_TypeError, + "keyword arguments must be strings"); + return 0; + } + return 1; } #define IS_END_OF_FORMAT(c) (c == '\0' || c == ';' || c == ':') static int vgetargskeywords(PyObject *args, PyObject *keywords, const char *format, - char **kwlist, va_list *p_va, int flags) + char **kwlist, va_list *p_va, int flags) { - char msgbuf[512]; - int levels[32]; - const char *fname, *msg, *custom_msg, *keyword; - int min = INT_MAX; - int i, len, nargs, nkeywords; - PyObject *freelist = NULL, *current_arg; - - assert(args != NULL && PyTuple_Check(args)); - assert(keywords == NULL || PyDict_Check(keywords)); - assert(format != NULL); - assert(kwlist != NULL); - assert(p_va != NULL); - - /* grab the function name or custom error msg first (mutually exclusive) */ - fname = strchr(format, ':'); - if (fname) { - fname++; - custom_msg = NULL; - } - else { - custom_msg = strchr(format,';'); - if (custom_msg) - custom_msg++; - } - - /* scan kwlist and get greatest possible nbr of args */ - for (len=0; kwlist[len]; len++) - continue; - - nargs = PyTuple_GET_SIZE(args); - nkeywords = (keywords == NULL) ? 0 : PyDict_Size(keywords); - if (nargs + nkeywords > len) { - PyErr_Format(PyExc_TypeError, "%s%s takes at most %d " - "argument%s (%d given)", - (fname == NULL) ? "function" : fname, - (fname == NULL) ? "" : "()", - len, - (len == 1) ? "" : "s", - nargs + nkeywords); - return 0; - } - - /* convert tuple args and keyword args in same loop, using kwlist to drive process */ - for (i = 0; i < len; i++) { - keyword = kwlist[i]; - if (*format == '|') { - min = i; - format++; - } - if (IS_END_OF_FORMAT(*format)) { - PyErr_Format(PyExc_RuntimeError, - "More keyword list entries (%d) than " - "format specifiers (%d)", len, i); - return cleanreturn(0, freelist); - } - current_arg = NULL; - if (nkeywords) { - current_arg = PyDict_GetItemString(keywords, keyword); - } - if (current_arg) { - --nkeywords; - if (i < nargs) { - /* arg present in tuple and in dict */ - PyErr_Format(PyExc_TypeError, - "Argument given by name ('%s') " - "and position (%d)", - keyword, i+1); - return cleanreturn(0, freelist); - } - } - else if (nkeywords && PyErr_Occurred()) - return cleanreturn(0, freelist); - else if (i < nargs) - current_arg = PyTuple_GET_ITEM(args, i); - - if (current_arg) { - msg = convertitem(current_arg, &format, p_va, flags, - levels, msgbuf, sizeof(msgbuf), &freelist); - if (msg) { - seterror(i+1, msg, levels, fname, custom_msg); - return cleanreturn(0, freelist); - } - continue; - } - - if (i < min) { - PyErr_Format(PyExc_TypeError, "Required argument " - "'%s' (pos %d) not found", - keyword, i+1); - return cleanreturn(0, freelist); - } - /* current code reports success when all required args - * fulfilled and no keyword args left, with no further - * validation. XXX Maybe skip this in debug build ? - */ - if (!nkeywords) - return cleanreturn(1, freelist); - - /* We are into optional args, skip thru to any remaining - * keyword args */ - msg = skipitem(&format, p_va, flags); - if (msg) { - PyErr_Format(PyExc_RuntimeError, "%s: '%s'", msg, - format); - return cleanreturn(0, freelist); - } - } - - if (!IS_END_OF_FORMAT(*format) && *format != '|') { - PyErr_Format(PyExc_RuntimeError, - "more argument specifiers than keyword list entries " - "(remaining format:'%s')", format); - return cleanreturn(0, freelist); - } - - /* make sure there are no extraneous keyword arguments */ - if (nkeywords > 0) { - PyObject *key, *value; - Py_ssize_t pos = 0; - while (PyDict_Next(keywords, &pos, &key, &value)) { - int match = 0; - char *ks; - if (!PyUnicode_Check(key)) { - PyErr_SetString(PyExc_TypeError, - "keywords must be strings"); - return cleanreturn(0, freelist); - } - ks = _PyUnicode_AsString(key); - for (i = 0; i < len; i++) { - if (!strcmp(ks, kwlist[i])) { - match = 1; - break; - } - } - if (!match) { - PyErr_Format(PyExc_TypeError, - "'%s' is an invalid keyword " - "argument for this function", - ks); - return cleanreturn(0, freelist); - } - } - } + char msgbuf[512]; + int levels[32]; + const char *fname, *msg, *custom_msg, *keyword; + int min = INT_MAX; + int i, len, nargs, nkeywords; + PyObject *freelist = NULL, *current_arg; + + assert(args != NULL && PyTuple_Check(args)); + assert(keywords == NULL || PyDict_Check(keywords)); + assert(format != NULL); + assert(kwlist != NULL); + assert(p_va != NULL); + + /* grab the function name or custom error msg first (mutually exclusive) */ + fname = strchr(format, ':'); + if (fname) { + fname++; + custom_msg = NULL; + } + else { + custom_msg = strchr(format,';'); + if (custom_msg) + custom_msg++; + } + + /* scan kwlist and get greatest possible nbr of args */ + for (len=0; kwlist[len]; len++) + continue; + + nargs = PyTuple_GET_SIZE(args); + nkeywords = (keywords == NULL) ? 0 : PyDict_Size(keywords); + if (nargs + nkeywords > len) { + PyErr_Format(PyExc_TypeError, "%s%s takes at most %d " + "argument%s (%d given)", + (fname == NULL) ? "function" : fname, + (fname == NULL) ? "" : "()", + len, + (len == 1) ? "" : "s", + nargs + nkeywords); + return 0; + } + + /* convert tuple args and keyword args in same loop, using kwlist to drive process */ + for (i = 0; i < len; i++) { + keyword = kwlist[i]; + if (*format == '|') { + min = i; + format++; + } + if (IS_END_OF_FORMAT(*format)) { + PyErr_Format(PyExc_RuntimeError, + "More keyword list entries (%d) than " + "format specifiers (%d)", len, i); + return cleanreturn(0, freelist); + } + current_arg = NULL; + if (nkeywords) { + current_arg = PyDict_GetItemString(keywords, keyword); + } + if (current_arg) { + --nkeywords; + if (i < nargs) { + /* arg present in tuple and in dict */ + PyErr_Format(PyExc_TypeError, + "Argument given by name ('%s') " + "and position (%d)", + keyword, i+1); + return cleanreturn(0, freelist); + } + } + else if (nkeywords && PyErr_Occurred()) + return cleanreturn(0, freelist); + else if (i < nargs) + current_arg = PyTuple_GET_ITEM(args, i); + + if (current_arg) { + msg = convertitem(current_arg, &format, p_va, flags, + levels, msgbuf, sizeof(msgbuf), &freelist); + if (msg) { + seterror(i+1, msg, levels, fname, custom_msg); + return cleanreturn(0, freelist); + } + continue; + } + + if (i < min) { + PyErr_Format(PyExc_TypeError, "Required argument " + "'%s' (pos %d) not found", + keyword, i+1); + return cleanreturn(0, freelist); + } + /* current code reports success when all required args + * fulfilled and no keyword args left, with no further + * validation. XXX Maybe skip this in debug build ? + */ + if (!nkeywords) + return cleanreturn(1, freelist); + + /* We are into optional args, skip thru to any remaining + * keyword args */ + msg = skipitem(&format, p_va, flags); + if (msg) { + PyErr_Format(PyExc_RuntimeError, "%s: '%s'", msg, + format); + return cleanreturn(0, freelist); + } + } + + if (!IS_END_OF_FORMAT(*format) && *format != '|') { + PyErr_Format(PyExc_RuntimeError, + "more argument specifiers than keyword list entries " + "(remaining format:'%s')", format); + return cleanreturn(0, freelist); + } + + /* make sure there are no extraneous keyword arguments */ + if (nkeywords > 0) { + PyObject *key, *value; + Py_ssize_t pos = 0; + while (PyDict_Next(keywords, &pos, &key, &value)) { + int match = 0; + char *ks; + if (!PyUnicode_Check(key)) { + PyErr_SetString(PyExc_TypeError, + "keywords must be strings"); + return cleanreturn(0, freelist); + } + ks = _PyUnicode_AsString(key); + for (i = 0; i < len; i++) { + if (!strcmp(ks, kwlist[i])) { + match = 1; + break; + } + } + if (!match) { + PyErr_Format(PyExc_TypeError, + "'%s' is an invalid keyword " + "argument for this function", + ks); + return cleanreturn(0, freelist); + } + } + } - return cleanreturn(1, freelist); + return cleanreturn(1, freelist); } static char * skipitem(const char **p_format, va_list *p_va, int flags) { - const char *format = *p_format; - char c = *format++; + const char *format = *p_format; + char c = *format++; - switch (c) { + switch (c) { - /* simple codes - * The individual types (second arg of va_arg) are irrelevant */ + /* simple codes + * The individual types (second arg of va_arg) are irrelevant */ - case 'b': /* byte -- very short int */ - case 'B': /* byte as bitfield */ - case 'h': /* short int */ - case 'H': /* short int as bitfield */ - case 'i': /* int */ - case 'I': /* int sized bitfield */ - case 'l': /* long int */ - case 'k': /* long int sized bitfield */ + case 'b': /* byte -- very short int */ + case 'B': /* byte as bitfield */ + case 'h': /* short int */ + case 'H': /* short int as bitfield */ + case 'i': /* int */ + case 'I': /* int sized bitfield */ + case 'l': /* long int */ + case 'k': /* long int sized bitfield */ #ifdef HAVE_LONG_LONG - case 'L': /* PY_LONG_LONG */ - case 'K': /* PY_LONG_LONG sized bitfield */ + case 'L': /* PY_LONG_LONG */ + case 'K': /* PY_LONG_LONG sized bitfield */ #endif - case 'f': /* float */ - case 'd': /* double */ - case 'D': /* complex double */ - case 'c': /* char */ - case 'C': /* unicode char */ - { - (void) va_arg(*p_va, void *); - break; - } - - case 'n': /* Py_ssize_t */ - { - (void) va_arg(*p_va, Py_ssize_t *); - break; - } - - /* string codes */ - - case 'e': /* string with encoding */ - { - (void) va_arg(*p_va, const char *); - if (!(*format == 's' || *format == 't')) - /* after 'e', only 's' and 't' is allowed */ - goto err; - format++; - /* explicit fallthrough to string cases */ - } - - case 's': /* string */ - case 'z': /* string or None */ - case 'y': /* bytes */ - case 'u': /* unicode string */ - case 't': /* buffer, read-only */ - case 'w': /* buffer, read-write */ - { - (void) va_arg(*p_va, char **); - if (*format == '#') { - if (flags & FLAG_SIZE_T) - (void) va_arg(*p_va, Py_ssize_t *); - else - (void) va_arg(*p_va, int *); - format++; - } else if ((c == 's' || c == 'z' || c == 'y') && *format == '*') { - format++; - } - break; - } - - /* object codes */ - - case 'S': /* string object */ - case 'Y': /* string object */ - case 'U': /* unicode string object */ - { - (void) va_arg(*p_va, PyObject **); - break; - } - - case 'O': /* object */ - { - if (*format == '!') { - format++; - (void) va_arg(*p_va, PyTypeObject*); - (void) va_arg(*p_va, PyObject **); - } - else if (*format == '&') { - typedef int (*converter)(PyObject *, void *); - (void) va_arg(*p_va, converter); - (void) va_arg(*p_va, void *); - format++; - } - else { - (void) va_arg(*p_va, PyObject **); - } - break; - } - - case '(': /* bypass tuple, not handled at all previously */ - { - char *msg; - for (;;) { - if (*format==')') - break; - if (IS_END_OF_FORMAT(*format)) - return "Unmatched left paren in format " - "string"; - msg = skipitem(&format, p_va, flags); - if (msg) - return msg; - } - format++; - break; - } + case 'f': /* float */ + case 'd': /* double */ + case 'D': /* complex double */ + case 'c': /* char */ + case 'C': /* unicode char */ + { + (void) va_arg(*p_va, void *); + break; + } + + case 'n': /* Py_ssize_t */ + { + (void) va_arg(*p_va, Py_ssize_t *); + break; + } + + /* string codes */ + + case 'e': /* string with encoding */ + { + (void) va_arg(*p_va, const char *); + if (!(*format == 's' || *format == 't')) + /* after 'e', only 's' and 't' is allowed */ + goto err; + format++; + /* explicit fallthrough to string cases */ + } + + case 's': /* string */ + case 'z': /* string or None */ + case 'y': /* bytes */ + case 'u': /* unicode string */ + case 't': /* buffer, read-only */ + case 'w': /* buffer, read-write */ + { + (void) va_arg(*p_va, char **); + if (*format == '#') { + if (flags & FLAG_SIZE_T) + (void) va_arg(*p_va, Py_ssize_t *); + else + (void) va_arg(*p_va, int *); + format++; + } else if ((c == 's' || c == 'z' || c == 'y') && *format == '*') { + format++; + } + break; + } + + /* object codes */ + + case 'S': /* string object */ + case 'Y': /* string object */ + case 'U': /* unicode string object */ + { + (void) va_arg(*p_va, PyObject **); + break; + } + + case 'O': /* object */ + { + if (*format == '!') { + format++; + (void) va_arg(*p_va, PyTypeObject*); + (void) va_arg(*p_va, PyObject **); + } + else if (*format == '&') { + typedef int (*converter)(PyObject *, void *); + (void) va_arg(*p_va, converter); + (void) va_arg(*p_va, void *); + format++; + } + else { + (void) va_arg(*p_va, PyObject **); + } + break; + } + + case '(': /* bypass tuple, not handled at all previously */ + { + char *msg; + for (;;) { + if (*format==')') + break; + if (IS_END_OF_FORMAT(*format)) + return "Unmatched left paren in format " + "string"; + msg = skipitem(&format, p_va, flags); + if (msg) + return msg; + } + format++; + break; + } - case ')': - return "Unmatched right paren in format string"; + case ')': + return "Unmatched right paren in format string"; - default: + default: err: - return "impossible"; + return "impossible"; - } + } - *p_format = format; - return NULL; + *p_format = format; + return NULL; } int PyArg_UnpackTuple(PyObject *args, const char *name, Py_ssize_t min, Py_ssize_t max, ...) { - Py_ssize_t i, l; - PyObject **o; - va_list vargs; + Py_ssize_t i, l; + PyObject **o; + va_list vargs; #ifdef HAVE_STDARG_PROTOTYPES - va_start(vargs, max); + va_start(vargs, max); #else - va_start(vargs); + va_start(vargs); #endif - assert(min >= 0); - assert(min <= max); - if (!PyTuple_Check(args)) { - PyErr_SetString(PyExc_SystemError, - "PyArg_UnpackTuple() argument list is not a tuple"); - return 0; - } - l = PyTuple_GET_SIZE(args); - if (l < min) { - if (name != NULL) - PyErr_Format( - PyExc_TypeError, - "%s expected %s%zd arguments, got %zd", - name, (min == max ? "" : "at least "), min, l); - else - PyErr_Format( - PyExc_TypeError, - "unpacked tuple should have %s%zd elements," - " but has %zd", - (min == max ? "" : "at least "), min, l); - va_end(vargs); - return 0; - } - if (l > max) { - if (name != NULL) - PyErr_Format( - PyExc_TypeError, - "%s expected %s%zd arguments, got %zd", - name, (min == max ? "" : "at most "), max, l); - else - PyErr_Format( - PyExc_TypeError, - "unpacked tuple should have %s%zd elements," - " but has %zd", - (min == max ? "" : "at most "), max, l); - va_end(vargs); - return 0; - } - for (i = 0; i < l; i++) { - o = va_arg(vargs, PyObject **); - *o = PyTuple_GET_ITEM(args, i); - } - va_end(vargs); - return 1; + assert(min >= 0); + assert(min <= max); + if (!PyTuple_Check(args)) { + PyErr_SetString(PyExc_SystemError, + "PyArg_UnpackTuple() argument list is not a tuple"); + return 0; + } + l = PyTuple_GET_SIZE(args); + if (l < min) { + if (name != NULL) + PyErr_Format( + PyExc_TypeError, + "%s expected %s%zd arguments, got %zd", + name, (min == max ? "" : "at least "), min, l); + else + PyErr_Format( + PyExc_TypeError, + "unpacked tuple should have %s%zd elements," + " but has %zd", + (min == max ? "" : "at least "), min, l); + va_end(vargs); + return 0; + } + if (l > max) { + if (name != NULL) + PyErr_Format( + PyExc_TypeError, + "%s expected %s%zd arguments, got %zd", + name, (min == max ? "" : "at most "), max, l); + else + PyErr_Format( + PyExc_TypeError, + "unpacked tuple should have %s%zd elements," + " but has %zd", + (min == max ? "" : "at most "), max, l); + va_end(vargs); + return 0; + } + for (i = 0; i < l; i++) { + o = va_arg(vargs, PyObject **); + *o = PyTuple_GET_ITEM(args, i); + } + va_end(vargs); + return 1; } @@ -1975,18 +1975,18 @@ int _PyArg_NoKeywords(const char *funcname, PyObject *kw) { - if (kw == NULL) - return 1; - if (!PyDict_CheckExact(kw)) { - PyErr_BadInternalCall(); - return 0; - } - if (PyDict_Size(kw) == 0) - return 1; - - PyErr_Format(PyExc_TypeError, "%s does not take keyword arguments", - funcname); - return 0; + if (kw == NULL) + return 1; + if (!PyDict_CheckExact(kw)) { + PyErr_BadInternalCall(); + return 0; + } + if (PyDict_Size(kw) == 0) + return 1; + + PyErr_Format(PyExc_TypeError, "%s does not take keyword arguments", + funcname); + return 0; } #ifdef __cplusplus }; Modified: python/branches/py3k-jit/Python/getcwd.c ============================================================================== --- python/branches/py3k-jit/Python/getcwd.c (original) +++ python/branches/py3k-jit/Python/getcwd.c Mon May 10 23:55:43 2010 @@ -26,24 +26,24 @@ char * getcwd(char *buf, int size) { - char localbuf[MAXPATHLEN+1]; - char *ret; - - if (size <= 0) { - errno = EINVAL; - return NULL; - } - ret = getwd(localbuf); - if (ret != NULL && strlen(localbuf) >= (size_t)size) { - errno = ERANGE; - return NULL; - } - if (ret == NULL) { - errno = EACCES; /* Most likely error */ - return NULL; - } - strncpy(buf, localbuf, size); - return buf; + char localbuf[MAXPATHLEN+1]; + char *ret; + + if (size <= 0) { + errno = EINVAL; + return NULL; + } + ret = getwd(localbuf); + if (ret != NULL && strlen(localbuf) >= (size_t)size) { + errno = ERANGE; + return NULL; + } + if (ret == NULL) { + errno = EACCES; /* Most likely error */ + return NULL; + } + strncpy(buf, localbuf, size); + return buf; } #else /* !HAVE_GETWD */ @@ -57,27 +57,27 @@ char * getcwd(char *buf, int size) { - FILE *fp; - char *p; - int sts; - if (size <= 0) { - errno = EINVAL; - return NULL; - } - if ((fp = popen(PWD_CMD, "r")) == NULL) - return NULL; - if (fgets(buf, size, fp) == NULL || (sts = pclose(fp)) != 0) { - errno = EACCES; /* Most likely error */ - return NULL; - } - for (p = buf; *p != '\n'; p++) { - if (*p == '\0') { - errno = ERANGE; - return NULL; - } - } - *p = '\0'; - return buf; + FILE *fp; + char *p; + int sts; + if (size <= 0) { + errno = EINVAL; + return NULL; + } + if ((fp = popen(PWD_CMD, "r")) == NULL) + return NULL; + if (fgets(buf, size, fp) == NULL || (sts = pclose(fp)) != 0) { + errno = EACCES; /* Most likely error */ + return NULL; + } + for (p = buf; *p != '\n'; p++) { + if (*p == '\0') { + errno = ERANGE; + return NULL; + } + } + *p = '\0'; + return buf; } #endif /* !HAVE_GETWD */ Modified: python/branches/py3k-jit/Python/getopt.c ============================================================================== --- python/branches/py3k-jit/Python/getopt.c (original) +++ python/branches/py3k-jit/Python/getopt.c Mon May 10 23:55:43 2010 @@ -7,8 +7,8 @@ * * All Rights Reserved * - * Permission to use, copy, modify, and distribute this software and its - * documentation for any purpose and without fee is hereby granted, + * 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, this permission notice and * the following disclaimer notice appear unmodified in all copies. * @@ -43,84 +43,84 @@ int _PyOS_GetOpt(int argc, wchar_t **argv, wchar_t *optstring) { - static wchar_t *opt_ptr = L""; - wchar_t *ptr; - wchar_t option; + static wchar_t *opt_ptr = L""; + wchar_t *ptr; + wchar_t option; - if (*opt_ptr == '\0') { + if (*opt_ptr == '\0') { - if (_PyOS_optind >= argc) - return -1; + if (_PyOS_optind >= argc) + return -1; #ifdef MS_WINDOWS - else if (wcscmp(argv[_PyOS_optind], L"/?") == 0) { - ++_PyOS_optind; - return 'h'; - } + else if (wcscmp(argv[_PyOS_optind], L"/?") == 0) { + ++_PyOS_optind; + return 'h'; + } #endif - else if (argv[_PyOS_optind][0] != L'-' || - argv[_PyOS_optind][1] == L'\0' /* lone dash */ ) - return -1; - - else if (wcscmp(argv[_PyOS_optind], L"--") == 0) { - ++_PyOS_optind; - return -1; - } - - else if (wcscmp(argv[_PyOS_optind], L"--help") == 0) { - ++_PyOS_optind; - return 'h'; - } - - else if (wcscmp(argv[_PyOS_optind], L"--version") == 0) { - ++_PyOS_optind; - return 'V'; - } - - - opt_ptr = &argv[_PyOS_optind++][1]; - } - - if ( (option = *opt_ptr++) == L'\0') - return -1; - - if (option == 'J') { - fprintf(stderr, "-J is reserved for Jython\n"); - return '_'; - } - - if (option == 'X') { - fprintf(stderr, - "-X is reserved for implementation-specific arguments\n"); - return '_'; - } - - if ((ptr = wcschr(optstring, option)) == NULL) { - if (_PyOS_opterr) - fprintf(stderr, "Unknown option: -%c\n", (char)option); - - return '_'; - } - - if (*(ptr + 1) == L':') { - if (*opt_ptr != L'\0') { - _PyOS_optarg = opt_ptr; - opt_ptr = L""; - } - - else { - if (_PyOS_optind >= argc) { - if (_PyOS_opterr) - fprintf(stderr, - "Argument expected for the -%c option\n", (char)option); - return '_'; - } - - _PyOS_optarg = argv[_PyOS_optind++]; - } - } + else if (argv[_PyOS_optind][0] != L'-' || + argv[_PyOS_optind][1] == L'\0' /* lone dash */ ) + return -1; + + else if (wcscmp(argv[_PyOS_optind], L"--") == 0) { + ++_PyOS_optind; + return -1; + } + + else if (wcscmp(argv[_PyOS_optind], L"--help") == 0) { + ++_PyOS_optind; + return 'h'; + } + + else if (wcscmp(argv[_PyOS_optind], L"--version") == 0) { + ++_PyOS_optind; + return 'V'; + } + + + opt_ptr = &argv[_PyOS_optind++][1]; + } + + if ( (option = *opt_ptr++) == L'\0') + return -1; + + if (option == 'J') { + fprintf(stderr, "-J is reserved for Jython\n"); + return '_'; + } + + if (option == 'X') { + fprintf(stderr, + "-X is reserved for implementation-specific arguments\n"); + return '_'; + } + + if ((ptr = wcschr(optstring, option)) == NULL) { + if (_PyOS_opterr) + fprintf(stderr, "Unknown option: -%c\n", (char)option); + + return '_'; + } + + if (*(ptr + 1) == L':') { + if (*opt_ptr != L'\0') { + _PyOS_optarg = opt_ptr; + opt_ptr = L""; + } + + else { + if (_PyOS_optind >= argc) { + if (_PyOS_opterr) + fprintf(stderr, + "Argument expected for the -%c option\n", (char)option); + return '_'; + } + + _PyOS_optarg = argv[_PyOS_optind++]; + } + } - return option; + return option; } #ifdef __cplusplus Modified: python/branches/py3k-jit/Python/import.c ============================================================================== --- python/branches/py3k-jit/Python/import.c (original) +++ python/branches/py3k-jit/Python/import.c Mon May 10 23:55:43 2010 @@ -76,31 +76,31 @@ Python 2.5b3: 62101 (fix wrong code: for x, in ...) Python 2.5b3: 62111 (fix wrong code: x += yield) Python 2.5c1: 62121 (fix wrong lnotab with for loops and - storing constants that should have been removed) + storing constants that should have been removed) Python 2.5c2: 62131 (fix wrong code: for x, in ... in listcomp/genexp) Python 2.6a0: 62151 (peephole optimizations and STORE_MAP opcode) Python 2.6a1: 62161 (WITH_CLEANUP optimization) Python 3000: 3000 - 3010 (removed UNARY_CONVERT) - 3020 (added BUILD_SET) - 3030 (added keyword-only parameters) - 3040 (added signature annotations) - 3050 (print becomes a function) - 3060 (PEP 3115 metaclass syntax) - 3061 (string literals become unicode) - 3071 (PEP 3109 raise changes) - 3081 (PEP 3137 make __file__ and __name__ unicode) - 3091 (kill str8 interning) - 3101 (merge from 2.6a0, see 62151) - 3103 (__file__ points to source file) + 3010 (removed UNARY_CONVERT) + 3020 (added BUILD_SET) + 3030 (added keyword-only parameters) + 3040 (added signature annotations) + 3050 (print becomes a function) + 3060 (PEP 3115 metaclass syntax) + 3061 (string literals become unicode) + 3071 (PEP 3109 raise changes) + 3081 (PEP 3137 make __file__ and __name__ unicode) + 3091 (kill str8 interning) + 3101 (merge from 2.6a0, see 62151) + 3103 (__file__ points to source file) Python 3.0a4: 3111 (WITH_CLEANUP optimization). Python 3.0a5: 3131 (lexical exception stacking, including POP_EXCEPT) Python 3.1a0: 3141 (optimize list, set and dict comprehensions: - change LIST_APPEND and SET_ADD, add MAP_ADD) + change LIST_APPEND and SET_ADD, add MAP_ADD) Python 3.1a0: 3151 (optimize conditional branches: - introduce POP_JUMP_IF_FALSE and POP_JUMP_IF_TRUE) + introduce POP_JUMP_IF_FALSE and POP_JUMP_IF_TRUE) Python 3.2a0: 3160 (add SETUP_WITH) - tag: cpython-32 + tag: cpython-32 */ /* If you change MAGIC, you must change TAG and you must insert the old value @@ -128,12 +128,12 @@ struct filedescr * _PyImport_Filetab = NULL; static const struct filedescr _PyImport_StandardFiletab[] = { - {".py", "U", PY_SOURCE}, + {".py", "U", PY_SOURCE}, #ifdef MS_WINDOWS - {".pyw", "U", PY_SOURCE}, + {".pyw", "U", PY_SOURCE}, #endif - {".pyc", "rb", PY_COMPILED}, - {0, 0} + {".pyc", "rb", PY_COMPILED}, + {0, 0} }; @@ -142,119 +142,119 @@ void _PyImport_Init(void) { - const struct filedescr *scan; - struct filedescr *filetab; - int countD = 0; - int countS = 0; - - /* prepare _PyImport_Filetab: copy entries from - _PyImport_DynLoadFiletab and _PyImport_StandardFiletab. - */ + const struct filedescr *scan; + struct filedescr *filetab; + int countD = 0; + int countS = 0; + + /* prepare _PyImport_Filetab: copy entries from + _PyImport_DynLoadFiletab and _PyImport_StandardFiletab. + */ #ifdef HAVE_DYNAMIC_LOADING - for (scan = _PyImport_DynLoadFiletab; scan->suffix != NULL; ++scan) - ++countD; + for (scan = _PyImport_DynLoadFiletab; scan->suffix != NULL; ++scan) + ++countD; #endif - for (scan = _PyImport_StandardFiletab; scan->suffix != NULL; ++scan) - ++countS; - filetab = PyMem_NEW(struct filedescr, countD + countS + 1); - if (filetab == NULL) - Py_FatalError("Can't initialize import file table."); + for (scan = _PyImport_StandardFiletab; scan->suffix != NULL; ++scan) + ++countS; + filetab = PyMem_NEW(struct filedescr, countD + countS + 1); + if (filetab == NULL) + Py_FatalError("Can't initialize import file table."); #ifdef HAVE_DYNAMIC_LOADING - memcpy(filetab, _PyImport_DynLoadFiletab, - countD * sizeof(struct filedescr)); + memcpy(filetab, _PyImport_DynLoadFiletab, + countD * sizeof(struct filedescr)); #endif - memcpy(filetab + countD, _PyImport_StandardFiletab, - countS * sizeof(struct filedescr)); - filetab[countD + countS].suffix = NULL; - - _PyImport_Filetab = filetab; - - if (Py_OptimizeFlag) { - /* Replace ".pyc" with ".pyo" in _PyImport_Filetab */ - for (; filetab->suffix != NULL; filetab++) { - if (strcmp(filetab->suffix, ".pyc") == 0) - filetab->suffix = ".pyo"; - } - } + memcpy(filetab + countD, _PyImport_StandardFiletab, + countS * sizeof(struct filedescr)); + filetab[countD + countS].suffix = NULL; + + _PyImport_Filetab = filetab; + + if (Py_OptimizeFlag) { + /* Replace ".pyc" with ".pyo" in _PyImport_Filetab */ + for (; filetab->suffix != NULL; filetab++) { + if (strcmp(filetab->suffix, ".pyc") == 0) + filetab->suffix = ".pyo"; + } + } } void _PyImportHooks_Init(void) { - PyObject *v, *path_hooks = NULL, *zimpimport; - int err = 0; + PyObject *v, *path_hooks = NULL, *zimpimport; + int err = 0; - /* adding sys.path_hooks and sys.path_importer_cache, setting up - zipimport */ - if (PyType_Ready(&PyNullImporter_Type) < 0) - goto error; - - if (Py_VerboseFlag) - PySys_WriteStderr("# installing zipimport hook\n"); - - v = PyList_New(0); - if (v == NULL) - goto error; - err = PySys_SetObject("meta_path", v); - Py_DECREF(v); - if (err) - goto error; - v = PyDict_New(); - if (v == NULL) - goto error; - err = PySys_SetObject("path_importer_cache", v); - Py_DECREF(v); - if (err) - goto error; - path_hooks = PyList_New(0); - if (path_hooks == NULL) - goto error; - err = PySys_SetObject("path_hooks", path_hooks); - if (err) { + /* adding sys.path_hooks and sys.path_importer_cache, setting up + zipimport */ + if (PyType_Ready(&PyNullImporter_Type) < 0) + goto error; + + if (Py_VerboseFlag) + PySys_WriteStderr("# installing zipimport hook\n"); + + v = PyList_New(0); + if (v == NULL) + goto error; + err = PySys_SetObject("meta_path", v); + Py_DECREF(v); + if (err) + goto error; + v = PyDict_New(); + if (v == NULL) + goto error; + err = PySys_SetObject("path_importer_cache", v); + Py_DECREF(v); + if (err) + goto error; + path_hooks = PyList_New(0); + if (path_hooks == NULL) + goto error; + err = PySys_SetObject("path_hooks", path_hooks); + if (err) { error: - PyErr_Print(); - Py_FatalError("initializing sys.meta_path, sys.path_hooks, " - "path_importer_cache, or NullImporter failed" - ); - } - - zimpimport = PyImport_ImportModule("zipimport"); - if (zimpimport == NULL) { - PyErr_Clear(); /* No zip import module -- okay */ - if (Py_VerboseFlag) - PySys_WriteStderr("# can't import zipimport\n"); - } - else { - PyObject *zipimporter = PyObject_GetAttrString(zimpimport, - "zipimporter"); - Py_DECREF(zimpimport); - if (zipimporter == NULL) { - PyErr_Clear(); /* No zipimporter object -- okay */ - if (Py_VerboseFlag) - PySys_WriteStderr( - "# can't import zipimport.zipimporter\n"); - } - else { - /* sys.path_hooks.append(zipimporter) */ - err = PyList_Append(path_hooks, zipimporter); - Py_DECREF(zipimporter); - if (err) - goto error; - if (Py_VerboseFlag) - PySys_WriteStderr( - "# installed zipimport hook\n"); - } - } - Py_DECREF(path_hooks); + PyErr_Print(); + Py_FatalError("initializing sys.meta_path, sys.path_hooks, " + "path_importer_cache, or NullImporter failed" + ); + } + + zimpimport = PyImport_ImportModule("zipimport"); + if (zimpimport == NULL) { + PyErr_Clear(); /* No zip import module -- okay */ + if (Py_VerboseFlag) + PySys_WriteStderr("# can't import zipimport\n"); + } + else { + PyObject *zipimporter = PyObject_GetAttrString(zimpimport, + "zipimporter"); + Py_DECREF(zimpimport); + if (zipimporter == NULL) { + PyErr_Clear(); /* No zipimporter object -- okay */ + if (Py_VerboseFlag) + PySys_WriteStderr( + "# can't import zipimport.zipimporter\n"); + } + else { + /* sys.path_hooks.append(zipimporter) */ + err = PyList_Append(path_hooks, zipimporter); + Py_DECREF(zipimporter); + if (err) + goto error; + if (Py_VerboseFlag) + PySys_WriteStderr( + "# installed zipimport hook\n"); + } + } + Py_DECREF(path_hooks); } void _PyImport_Fini(void) { - Py_XDECREF(extensions); - extensions = NULL; - PyMem_DEL(_PyImport_Filetab); - _PyImport_Filetab = NULL; + Py_XDECREF(extensions); + extensions = NULL; + PyMem_DEL(_PyImport_Filetab); + _PyImport_Filetab = NULL; } @@ -273,42 +273,42 @@ void _PyImport_AcquireLock(void) { - long me = PyThread_get_thread_ident(); - if (me == -1) - return; /* Too bad */ - if (import_lock == NULL) { - import_lock = PyThread_allocate_lock(); - if (import_lock == NULL) - return; /* Nothing much we can do. */ - } - if (import_lock_thread == me) { - import_lock_level++; - return; - } - if (import_lock_thread != -1 || !PyThread_acquire_lock(import_lock, 0)) - { - PyThreadState *tstate = PyEval_SaveThread(); - PyThread_acquire_lock(import_lock, 1); - PyEval_RestoreThread(tstate); - } - import_lock_thread = me; - import_lock_level = 1; + long me = PyThread_get_thread_ident(); + if (me == -1) + return; /* Too bad */ + if (import_lock == NULL) { + import_lock = PyThread_allocate_lock(); + if (import_lock == NULL) + return; /* Nothing much we can do. */ + } + if (import_lock_thread == me) { + import_lock_level++; + return; + } + if (import_lock_thread != -1 || !PyThread_acquire_lock(import_lock, 0)) + { + PyThreadState *tstate = PyEval_SaveThread(); + PyThread_acquire_lock(import_lock, 1); + PyEval_RestoreThread(tstate); + } + import_lock_thread = me; + import_lock_level = 1; } int _PyImport_ReleaseLock(void) { - long me = PyThread_get_thread_ident(); - if (me == -1 || import_lock == NULL) - return 0; /* Too bad */ - if (import_lock_thread != me) - return -1; - import_lock_level--; - if (import_lock_level == 0) { - import_lock_thread = -1; - PyThread_release_lock(import_lock); - } - return 1; + long me = PyThread_get_thread_ident(); + if (me == -1 || import_lock == NULL) + return 0; /* Too bad */ + if (import_lock_thread != me) + return -1; + import_lock_level--; + if (import_lock_level == 0) { + import_lock_thread = -1; + PyThread_release_lock(import_lock); + } + return 1; } /* This function is called from PyOS_AfterFork to ensure that newly @@ -319,10 +319,10 @@ void _PyImport_ReInitLock(void) { - if (import_lock != NULL) - import_lock = PyThread_allocate_lock(); - import_lock_thread = -1; - import_lock_level = 0; + if (import_lock != NULL) + import_lock = PyThread_allocate_lock(); + import_lock_thread = -1; + import_lock_level = 0; } #endif @@ -331,9 +331,9 @@ imp_lock_held(PyObject *self, PyObject *noargs) { #ifdef WITH_THREAD - return PyBool_FromLong(import_lock_thread != -1); + return PyBool_FromLong(import_lock_thread != -1); #else - return PyBool_FromLong(0); + return PyBool_FromLong(0); #endif } @@ -341,32 +341,32 @@ imp_acquire_lock(PyObject *self, PyObject *noargs) { #ifdef WITH_THREAD - _PyImport_AcquireLock(); + _PyImport_AcquireLock(); #endif - Py_INCREF(Py_None); - return Py_None; + Py_INCREF(Py_None); + return Py_None; } static PyObject * imp_release_lock(PyObject *self, PyObject *noargs) { #ifdef WITH_THREAD - if (_PyImport_ReleaseLock() < 0) { - PyErr_SetString(PyExc_RuntimeError, - "not holding the import lock"); - return NULL; - } + if (_PyImport_ReleaseLock() < 0) { + PyErr_SetString(PyExc_RuntimeError, + "not holding the import lock"); + return NULL; + } #endif - Py_INCREF(Py_None); - return Py_None; + Py_INCREF(Py_None); + return Py_None; } static void imp_modules_reloading_clear(void) { - PyInterpreterState *interp = PyThreadState_Get()->interp; - if (interp->modules_reloading != NULL) - PyDict_Clear(interp->modules_reloading); + PyInterpreterState *interp = PyThreadState_Get()->interp; + if (interp->modules_reloading != NULL) + PyDict_Clear(interp->modules_reloading); } /* Helper for sys */ @@ -374,28 +374,28 @@ PyObject * PyImport_GetModuleDict(void) { - PyInterpreterState *interp = PyThreadState_GET()->interp; - if (interp->modules == NULL) - Py_FatalError("PyImport_GetModuleDict: no module dictionary!"); - return interp->modules; + PyInterpreterState *interp = PyThreadState_GET()->interp; + if (interp->modules == NULL) + Py_FatalError("PyImport_GetModuleDict: no module dictionary!"); + return interp->modules; } /* List of names to clear in sys */ static char* sys_deletes[] = { - "path", "argv", "ps1", "ps2", - "last_type", "last_value", "last_traceback", - "path_hooks", "path_importer_cache", "meta_path", - /* misc stuff */ - "flags", "float_info", - NULL + "path", "argv", "ps1", "ps2", + "last_type", "last_value", "last_traceback", + "path_hooks", "path_importer_cache", "meta_path", + /* misc stuff */ + "flags", "float_info", + NULL }; static char* sys_files[] = { - "stdin", "__stdin__", - "stdout", "__stdout__", - "stderr", "__stderr__", - NULL + "stdin", "__stdin__", + "stdout", "__stdout__", + "stderr", "__stderr__", + NULL }; @@ -404,132 +404,132 @@ void PyImport_Cleanup(void) { - Py_ssize_t pos, ndone; - char *name; - PyObject *key, *value, *dict; - PyInterpreterState *interp = PyThreadState_GET()->interp; - PyObject *modules = interp->modules; - - if (modules == NULL) - return; /* Already done */ - - /* Delete some special variables first. These are common - places where user values hide and people complain when their - destructors fail. Since the modules containing them are - deleted *last* of all, they would come too late in the normal - destruction order. Sigh. */ - - value = PyDict_GetItemString(modules, "builtins"); - if (value != NULL && PyModule_Check(value)) { - dict = PyModule_GetDict(value); - if (Py_VerboseFlag) - PySys_WriteStderr("# clear builtins._\n"); - PyDict_SetItemString(dict, "_", Py_None); - } - value = PyDict_GetItemString(modules, "sys"); - if (value != NULL && PyModule_Check(value)) { - char **p; - PyObject *v; - dict = PyModule_GetDict(value); - for (p = sys_deletes; *p != NULL; p++) { - if (Py_VerboseFlag) - PySys_WriteStderr("# clear sys.%s\n", *p); - PyDict_SetItemString(dict, *p, Py_None); - } - for (p = sys_files; *p != NULL; p+=2) { - if (Py_VerboseFlag) - PySys_WriteStderr("# restore sys.%s\n", *p); - v = PyDict_GetItemString(dict, *(p+1)); - if (v == NULL) - v = Py_None; - PyDict_SetItemString(dict, *p, v); - } - } - - /* First, delete __main__ */ - value = PyDict_GetItemString(modules, "__main__"); - if (value != NULL && PyModule_Check(value)) { - if (Py_VerboseFlag) - PySys_WriteStderr("# cleanup __main__\n"); - _PyModule_Clear(value); - PyDict_SetItemString(modules, "__main__", Py_None); - } - - /* The special treatment of "builtins" here is because even - when it's not referenced as a module, its dictionary is - referenced by almost every module's __builtins__. Since - deleting a module clears its dictionary (even if there are - references left to it), we need to delete the "builtins" - module last. Likewise, we don't delete sys until the very - end because it is implicitly referenced (e.g. by print). - - Also note that we 'delete' modules by replacing their entry - in the modules dict with None, rather than really deleting - them; this avoids a rehash of the modules dictionary and - also marks them as "non existent" so they won't be - re-imported. */ - - /* Next, repeatedly delete modules with a reference count of - one (skipping builtins and sys) and delete them */ - do { - ndone = 0; - pos = 0; - while (PyDict_Next(modules, &pos, &key, &value)) { - if (value->ob_refcnt != 1) - continue; - if (PyUnicode_Check(key) && PyModule_Check(value)) { - name = _PyUnicode_AsString(key); - if (strcmp(name, "builtins") == 0) - continue; - if (strcmp(name, "sys") == 0) - continue; - if (Py_VerboseFlag) - PySys_WriteStderr( - "# cleanup[1] %s\n", name); - _PyModule_Clear(value); - PyDict_SetItem(modules, key, Py_None); - ndone++; - } - } - } while (ndone > 0); - - /* Next, delete all modules (still skipping builtins and sys) */ - pos = 0; - while (PyDict_Next(modules, &pos, &key, &value)) { - if (PyUnicode_Check(key) && PyModule_Check(value)) { - name = _PyUnicode_AsString(key); - if (strcmp(name, "builtins") == 0) - continue; - if (strcmp(name, "sys") == 0) - continue; - if (Py_VerboseFlag) - PySys_WriteStderr("# cleanup[2] %s\n", name); - _PyModule_Clear(value); - PyDict_SetItem(modules, key, Py_None); - } - } - - /* Next, delete sys and builtins (in that order) */ - value = PyDict_GetItemString(modules, "sys"); - if (value != NULL && PyModule_Check(value)) { - if (Py_VerboseFlag) - PySys_WriteStderr("# cleanup sys\n"); - _PyModule_Clear(value); - PyDict_SetItemString(modules, "sys", Py_None); - } - value = PyDict_GetItemString(modules, "builtins"); - if (value != NULL && PyModule_Check(value)) { - if (Py_VerboseFlag) - PySys_WriteStderr("# cleanup builtins\n"); - _PyModule_Clear(value); - PyDict_SetItemString(modules, "builtins", Py_None); - } - - /* Finally, clear and delete the modules directory */ - PyDict_Clear(modules); - interp->modules = NULL; - Py_DECREF(modules); - Py_CLEAR(interp->modules_reloading); + Py_ssize_t pos, ndone; + char *name; + PyObject *key, *value, *dict; + PyInterpreterState *interp = PyThreadState_GET()->interp; + PyObject *modules = interp->modules; + + if (modules == NULL) + return; /* Already done */ + + /* Delete some special variables first. These are common + places where user values hide and people complain when their + destructors fail. Since the modules containing them are + deleted *last* of all, they would come too late in the normal + destruction order. Sigh. */ + + value = PyDict_GetItemString(modules, "builtins"); + if (value != NULL && PyModule_Check(value)) { + dict = PyModule_GetDict(value); + if (Py_VerboseFlag) + PySys_WriteStderr("# clear builtins._\n"); + PyDict_SetItemString(dict, "_", Py_None); + } + value = PyDict_GetItemString(modules, "sys"); + if (value != NULL && PyModule_Check(value)) { + char **p; + PyObject *v; + dict = PyModule_GetDict(value); + for (p = sys_deletes; *p != NULL; p++) { + if (Py_VerboseFlag) + PySys_WriteStderr("# clear sys.%s\n", *p); + PyDict_SetItemString(dict, *p, Py_None); + } + for (p = sys_files; *p != NULL; p+=2) { + if (Py_VerboseFlag) + PySys_WriteStderr("# restore sys.%s\n", *p); + v = PyDict_GetItemString(dict, *(p+1)); + if (v == NULL) + v = Py_None; + PyDict_SetItemString(dict, *p, v); + } + } + + /* First, delete __main__ */ + value = PyDict_GetItemString(modules, "__main__"); + if (value != NULL && PyModule_Check(value)) { + if (Py_VerboseFlag) + PySys_WriteStderr("# cleanup __main__\n"); + _PyModule_Clear(value); + PyDict_SetItemString(modules, "__main__", Py_None); + } + + /* The special treatment of "builtins" here is because even + when it's not referenced as a module, its dictionary is + referenced by almost every module's __builtins__. Since + deleting a module clears its dictionary (even if there are + references left to it), we need to delete the "builtins" + module last. Likewise, we don't delete sys until the very + end because it is implicitly referenced (e.g. by print). + + Also note that we 'delete' modules by replacing their entry + in the modules dict with None, rather than really deleting + them; this avoids a rehash of the modules dictionary and + also marks them as "non existent" so they won't be + re-imported. */ + + /* Next, repeatedly delete modules with a reference count of + one (skipping builtins and sys) and delete them */ + do { + ndone = 0; + pos = 0; + while (PyDict_Next(modules, &pos, &key, &value)) { + if (value->ob_refcnt != 1) + continue; + if (PyUnicode_Check(key) && PyModule_Check(value)) { + name = _PyUnicode_AsString(key); + if (strcmp(name, "builtins") == 0) + continue; + if (strcmp(name, "sys") == 0) + continue; + if (Py_VerboseFlag) + PySys_WriteStderr( + "# cleanup[1] %s\n", name); + _PyModule_Clear(value); + PyDict_SetItem(modules, key, Py_None); + ndone++; + } + } + } while (ndone > 0); + + /* Next, delete all modules (still skipping builtins and sys) */ + pos = 0; + while (PyDict_Next(modules, &pos, &key, &value)) { + if (PyUnicode_Check(key) && PyModule_Check(value)) { + name = _PyUnicode_AsString(key); + if (strcmp(name, "builtins") == 0) + continue; + if (strcmp(name, "sys") == 0) + continue; + if (Py_VerboseFlag) + PySys_WriteStderr("# cleanup[2] %s\n", name); + _PyModule_Clear(value); + PyDict_SetItem(modules, key, Py_None); + } + } + + /* Next, delete sys and builtins (in that order) */ + value = PyDict_GetItemString(modules, "sys"); + if (value != NULL && PyModule_Check(value)) { + if (Py_VerboseFlag) + PySys_WriteStderr("# cleanup sys\n"); + _PyModule_Clear(value); + PyDict_SetItemString(modules, "sys", Py_None); + } + value = PyDict_GetItemString(modules, "builtins"); + if (value != NULL && PyModule_Check(value)) { + if (Py_VerboseFlag) + PySys_WriteStderr("# cleanup builtins\n"); + _PyModule_Clear(value); + PyDict_SetItemString(modules, "builtins", Py_None); + } + + /* Finally, clear and delete the modules directory */ + PyDict_Clear(modules); + interp->modules = NULL; + Py_DECREF(modules); + Py_CLEAR(interp->modules_reloading); } @@ -538,14 +538,14 @@ long PyImport_GetMagicNumber(void) { - return pyc_magic; + return pyc_magic; } const char * PyImport_GetMagicTag(void) { - return pyc_tag; + return pyc_tag; } /* Magic for extension modules (built-in as well as dynamically @@ -567,89 +567,89 @@ int _PyImport_FixupExtension(PyObject *mod, char *name, char *filename) { - PyObject *modules, *dict; - struct PyModuleDef *def; - if (extensions == NULL) { - extensions = PyDict_New(); - if (extensions == NULL) - return -1; - } - if (mod == NULL || !PyModule_Check(mod)) { - PyErr_BadInternalCall(); - return -1; - } - def = PyModule_GetDef(mod); - if (!def) { - PyErr_BadInternalCall(); - return -1; - } - modules = PyImport_GetModuleDict(); - if (PyDict_SetItemString(modules, name, mod) < 0) - return -1; - if (_PyState_AddModule(mod, def) < 0) { - PyDict_DelItemString(modules, name); - return -1; - } - if (def->m_size == -1) { - if (def->m_base.m_copy) { - /* Somebody already imported the module, - likely under a different name. - XXX this should really not happen. */ - Py_DECREF(def->m_base.m_copy); - def->m_base.m_copy = NULL; - } - dict = PyModule_GetDict(mod); - if (dict == NULL) - return -1; - def->m_base.m_copy = PyDict_Copy(dict); - if (def->m_base.m_copy == NULL) - return -1; - } - PyDict_SetItemString(extensions, filename, (PyObject*)def); - return 0; + PyObject *modules, *dict; + struct PyModuleDef *def; + if (extensions == NULL) { + extensions = PyDict_New(); + if (extensions == NULL) + return -1; + } + if (mod == NULL || !PyModule_Check(mod)) { + PyErr_BadInternalCall(); + return -1; + } + def = PyModule_GetDef(mod); + if (!def) { + PyErr_BadInternalCall(); + return -1; + } + modules = PyImport_GetModuleDict(); + if (PyDict_SetItemString(modules, name, mod) < 0) + return -1; + if (_PyState_AddModule(mod, def) < 0) { + PyDict_DelItemString(modules, name); + return -1; + } + if (def->m_size == -1) { + if (def->m_base.m_copy) { + /* Somebody already imported the module, + likely under a different name. + XXX this should really not happen. */ + Py_DECREF(def->m_base.m_copy); + def->m_base.m_copy = NULL; + } + dict = PyModule_GetDict(mod); + if (dict == NULL) + return -1; + def->m_base.m_copy = PyDict_Copy(dict); + if (def->m_base.m_copy == NULL) + return -1; + } + PyDict_SetItemString(extensions, filename, (PyObject*)def); + return 0; } PyObject * _PyImport_FindExtension(char *name, char *filename) { - PyObject *mod, *mdict; - PyModuleDef* def; - if (extensions == NULL) - return NULL; - def = (PyModuleDef*)PyDict_GetItemString(extensions, filename); - if (def == NULL) - return NULL; - if (def->m_size == -1) { - /* Module does not support repeated initialization */ - if (def->m_base.m_copy == NULL) - return NULL; - mod = PyImport_AddModule(name); - if (mod == NULL) - return NULL; - mdict = PyModule_GetDict(mod); - if (mdict == NULL) - return NULL; - if (PyDict_Update(mdict, def->m_base.m_copy)) - return NULL; - } - else { - if (def->m_base.m_init == NULL) - return NULL; - mod = def->m_base.m_init(); - if (mod == NULL) - return NULL; - PyDict_SetItemString(PyImport_GetModuleDict(), name, mod); - Py_DECREF(mod); - } - if (_PyState_AddModule(mod, def) < 0) { - PyDict_DelItemString(PyImport_GetModuleDict(), name); - Py_DECREF(mod); - return NULL; - } - if (Py_VerboseFlag) - PySys_WriteStderr("import %s # previously loaded (%s)\n", - name, filename); - return mod; + PyObject *mod, *mdict; + PyModuleDef* def; + if (extensions == NULL) + return NULL; + def = (PyModuleDef*)PyDict_GetItemString(extensions, filename); + if (def == NULL) + return NULL; + if (def->m_size == -1) { + /* Module does not support repeated initialization */ + if (def->m_base.m_copy == NULL) + return NULL; + mod = PyImport_AddModule(name); + if (mod == NULL) + return NULL; + mdict = PyModule_GetDict(mod); + if (mdict == NULL) + return NULL; + if (PyDict_Update(mdict, def->m_base.m_copy)) + return NULL; + } + else { + if (def->m_base.m_init == NULL) + return NULL; + mod = def->m_base.m_init(); + if (mod == NULL) + return NULL; + PyDict_SetItemString(PyImport_GetModuleDict(), name, mod); + Py_DECREF(mod); + } + if (_PyState_AddModule(mod, def) < 0) { + PyDict_DelItemString(PyImport_GetModuleDict(), name); + Py_DECREF(mod); + return NULL; + } + if (Py_VerboseFlag) + PySys_WriteStderr("import %s # previously loaded (%s)\n", + name, filename); + return mod; } @@ -663,40 +663,40 @@ PyObject * PyImport_AddModule(const char *name) { - PyObject *modules = PyImport_GetModuleDict(); - PyObject *m; + PyObject *modules = PyImport_GetModuleDict(); + PyObject *m; - if ((m = PyDict_GetItemString(modules, name)) != NULL && - PyModule_Check(m)) - return m; - m = PyModule_New(name); - if (m == NULL) - return NULL; - if (PyDict_SetItemString(modules, name, m) != 0) { - Py_DECREF(m); - return NULL; - } - Py_DECREF(m); /* Yes, it still exists, in modules! */ + if ((m = PyDict_GetItemString(modules, name)) != NULL && + PyModule_Check(m)) + return m; + m = PyModule_New(name); + if (m == NULL) + return NULL; + if (PyDict_SetItemString(modules, name, m) != 0) { + Py_DECREF(m); + return NULL; + } + Py_DECREF(m); /* Yes, it still exists, in modules! */ - return m; + return m; } /* Remove name from sys.modules, if it's there. */ static void remove_module(const char *name) { - PyObject *modules = PyImport_GetModuleDict(); - if (PyDict_GetItemString(modules, name) == NULL) - return; - if (PyDict_DelItemString(modules, name) < 0) - Py_FatalError("import: deleting existing key in" - "sys.modules failed"); + PyObject *modules = PyImport_GetModuleDict(); + if (PyDict_GetItemString(modules, name) == NULL) + return; + if (PyDict_DelItemString(modules, name) < 0) + Py_FatalError("import: deleting existing key in" + "sys.modules failed"); } static PyObject * get_sourcefile(char *file); static char *make_source_pathname(char *pathname, char *buf); static char *make_compiled_pathname(char *pathname, char *buf, size_t buflen, - int debug); + int debug); /* Execute a code object in a module and return the module object * WITH INCREMENTED REFERENCE COUNT. If an error occurs, name is @@ -711,83 +711,83 @@ PyObject * PyImport_ExecCodeModule(char *name, PyObject *co) { - return PyImport_ExecCodeModuleWithPathnames( - name, co, (char *)NULL, (char *)NULL); + return PyImport_ExecCodeModuleWithPathnames( + name, co, (char *)NULL, (char *)NULL); } PyObject * PyImport_ExecCodeModuleEx(char *name, PyObject *co, char *pathname) { - return PyImport_ExecCodeModuleWithPathnames( - name, co, pathname, (char *)NULL); + return PyImport_ExecCodeModuleWithPathnames( + name, co, pathname, (char *)NULL); } PyObject * PyImport_ExecCodeModuleWithPathnames(char *name, PyObject *co, char *pathname, - char *cpathname) + char *cpathname) { - PyObject *modules = PyImport_GetModuleDict(); - PyObject *m, *d, *v; + PyObject *modules = PyImport_GetModuleDict(); + PyObject *m, *d, *v; - m = PyImport_AddModule(name); - if (m == NULL) - return NULL; - /* If the module is being reloaded, we get the old module back - and re-use its dict to exec the new code. */ - d = PyModule_GetDict(m); - if (PyDict_GetItemString(d, "__builtins__") == NULL) { - if (PyDict_SetItemString(d, "__builtins__", - PyEval_GetBuiltins()) != 0) - goto error; - } - /* Remember the filename as the __file__ attribute */ - v = NULL; - if (pathname != NULL) { - v = get_sourcefile(pathname); - if (v == NULL) - PyErr_Clear(); - } - if (v == NULL) { - v = ((PyCodeObject *)co)->co_filename; - Py_INCREF(v); - } - if (PyDict_SetItemString(d, "__file__", v) != 0) - PyErr_Clear(); /* Not important enough to report */ - Py_DECREF(v); - - /* Remember the pyc path name as the __cached__ attribute. */ - if (cpathname == NULL) { - v = Py_None; - Py_INCREF(v); - } - else if ((v = PyUnicode_FromString(cpathname)) == NULL) { - PyErr_Clear(); /* Not important enough to report */ - v = Py_None; - Py_INCREF(v); - } - if (PyDict_SetItemString(d, "__cached__", v) != 0) - PyErr_Clear(); /* Not important enough to report */ - Py_DECREF(v); - - v = PyEval_EvalCode((PyCodeObject *)co, d, d); - if (v == NULL) - goto error; - Py_DECREF(v); - - if ((m = PyDict_GetItemString(modules, name)) == NULL) { - PyErr_Format(PyExc_ImportError, - "Loaded module %.200s not found in sys.modules", - name); - return NULL; - } + m = PyImport_AddModule(name); + if (m == NULL) + return NULL; + /* If the module is being reloaded, we get the old module back + and re-use its dict to exec the new code. */ + d = PyModule_GetDict(m); + if (PyDict_GetItemString(d, "__builtins__") == NULL) { + if (PyDict_SetItemString(d, "__builtins__", + PyEval_GetBuiltins()) != 0) + goto error; + } + /* Remember the filename as the __file__ attribute */ + v = NULL; + if (pathname != NULL) { + v = get_sourcefile(pathname); + if (v == NULL) + PyErr_Clear(); + } + if (v == NULL) { + v = ((PyCodeObject *)co)->co_filename; + Py_INCREF(v); + } + if (PyDict_SetItemString(d, "__file__", v) != 0) + PyErr_Clear(); /* Not important enough to report */ + Py_DECREF(v); + + /* Remember the pyc path name as the __cached__ attribute. */ + if (cpathname == NULL) { + v = Py_None; + Py_INCREF(v); + } + else if ((v = PyUnicode_FromString(cpathname)) == NULL) { + PyErr_Clear(); /* Not important enough to report */ + v = Py_None; + Py_INCREF(v); + } + if (PyDict_SetItemString(d, "__cached__", v) != 0) + PyErr_Clear(); /* Not important enough to report */ + Py_DECREF(v); + + v = PyEval_EvalCode((PyCodeObject *)co, d, d); + if (v == NULL) + goto error; + Py_DECREF(v); + + if ((m = PyDict_GetItemString(modules, name)) == NULL) { + PyErr_Format(PyExc_ImportError, + "Loaded module %.200s not found in sys.modules", + name); + return NULL; + } - Py_INCREF(m); + Py_INCREF(m); - return m; + return m; error: - remove_module(name); - return NULL; + remove_module(name); + return NULL; } @@ -797,18 +797,18 @@ static char * rightmost_sep(char *s) { - char *found, c; - for (found = NULL; (c = *s); s++) { - if (c == SEP + char *found, c; + for (found = NULL; (c = *s); s++) { + if (c == SEP #ifdef ALTSEP - || c == ALTSEP + || c == ALTSEP #endif - ) - { - found = s; - } - } - return found; + ) + { + found = s; + } + } + return found; } @@ -820,104 +820,104 @@ static char * make_compiled_pathname(char *pathname, char *buf, size_t buflen, int debug) { - /* foo.py -> __pycache__/foo..pyc */ - size_t len = strlen(pathname); - size_t i, save; - char *pos; - int sep = SEP; - - /* Sanity check that the buffer has roughly enough space to hold what - will eventually be the full path to the compiled file. The 5 extra - bytes include the slash afer __pycache__, the two extra dots, the - extra trailing character ('c' or 'o') and null. This isn't exact - because the contents of the buffer can affect how many actual - characters of the string get into the buffer. We'll do a final - sanity check before writing the extension to ensure we do not - overflow the buffer. - */ - if (len + strlen(CACHEDIR) + strlen(pyc_tag) + 5 > buflen) - return NULL; - - /* Find the last path separator and copy everything from the start of - the source string up to and including the separator. - */ - if ((pos = rightmost_sep(pathname)) == NULL) { - i = 0; - } - else { - sep = *pos; - i = pos - pathname + 1; - strncpy(buf, pathname, i); - } - - save = i; - buf[i++] = '\0'; - /* Add __pycache__/ */ - strcat(buf, CACHEDIR); - i += strlen(CACHEDIR) - 1; - buf[i++] = sep; - buf[i++] = '\0'; - /* Add the base filename, but remove the .py or .pyw extension, since - the tag name must go before the extension. - */ - strcat(buf, pathname + save); - if ((pos = strrchr(buf, '.')) != NULL) - *++pos = '\0'; - strcat(buf, pyc_tag); - /* The length test above assumes that we're only adding one character - to the end of what would normally be the extension. What if there - is no extension, or the string ends in '.' or '.p', and otherwise - fills the buffer? By appending 4 more characters onto the string - here, we could overrun the buffer. - - As a simple example, let's say buflen=32 and the input string is - 'xxx.py'. strlen() would be 6 and the test above would yield: - - (6 + 11 + 10 + 5 == 32) > 32 - - which is false and so the name mangling would continue. This would - be fine because we'd end up with this string in buf: - - __pycache__/xxx.cpython-32.pyc\0 - - strlen(of that) == 30 + the nul fits inside a 32 character buffer. - We can even handle an input string of say 'xxxxx' above because - that's (5 + 11 + 10 + 5 == 31) > 32 which is also false. Name - mangling that yields: - - __pycache__/xxxxxcpython-32.pyc\0 - - which is 32 characters including the nul, and thus fits in the - buffer. However, an input string of 'xxxxxx' would yield a result - string of: - - __pycache__/xxxxxxcpython-32.pyc\0 - - which is 33 characters long (including the nul), thus overflowing - the buffer, even though the first test would fail, i.e.: the input - string is also 6 characters long, so 32 > 32 is false. - - The reason the first test fails but we still overflow the buffer is - that the test above only expects to add one extra character to be - added to the extension, and here we're adding three (pyc). We - don't add the first dot, so that reclaims one of expected - positions, leaving us overflowing by 1 byte (3 extra - 1 reclaimed - dot - 1 expected extra == 1 overflowed). - - The best we can do is ensure that we still have enough room in the - target buffer before we write the extension. Because it's always - only the extension that can cause the overflow, and never the other - path bytes we've written, it's sufficient to just do one more test - here. Still, the assertion that follows can't hurt. - */ + /* foo.py -> __pycache__/foo..pyc */ + size_t len = strlen(pathname); + size_t i, save; + char *pos; + int sep = SEP; + + /* Sanity check that the buffer has roughly enough space to hold what + will eventually be the full path to the compiled file. The 5 extra + bytes include the slash afer __pycache__, the two extra dots, the + extra trailing character ('c' or 'o') and null. This isn't exact + because the contents of the buffer can affect how many actual + characters of the string get into the buffer. We'll do a final + sanity check before writing the extension to ensure we do not + overflow the buffer. + */ + if (len + strlen(CACHEDIR) + strlen(pyc_tag) + 5 > buflen) + return NULL; + + /* Find the last path separator and copy everything from the start of + the source string up to and including the separator. + */ + if ((pos = rightmost_sep(pathname)) == NULL) { + i = 0; + } + else { + sep = *pos; + i = pos - pathname + 1; + strncpy(buf, pathname, i); + } + + save = i; + buf[i++] = '\0'; + /* Add __pycache__/ */ + strcat(buf, CACHEDIR); + i += strlen(CACHEDIR) - 1; + buf[i++] = sep; + buf[i++] = '\0'; + /* Add the base filename, but remove the .py or .pyw extension, since + the tag name must go before the extension. + */ + strcat(buf, pathname + save); + if ((pos = strrchr(buf, '.')) != NULL) + *++pos = '\0'; + strcat(buf, pyc_tag); + /* The length test above assumes that we're only adding one character + to the end of what would normally be the extension. What if there + is no extension, or the string ends in '.' or '.p', and otherwise + fills the buffer? By appending 4 more characters onto the string + here, we could overrun the buffer. + + As a simple example, let's say buflen=32 and the input string is + 'xxx.py'. strlen() would be 6 and the test above would yield: + + (6 + 11 + 10 + 5 == 32) > 32 + + which is false and so the name mangling would continue. This would + be fine because we'd end up with this string in buf: + + __pycache__/xxx.cpython-32.pyc\0 + + strlen(of that) == 30 + the nul fits inside a 32 character buffer. + We can even handle an input string of say 'xxxxx' above because + that's (5 + 11 + 10 + 5 == 31) > 32 which is also false. Name + mangling that yields: + + __pycache__/xxxxxcpython-32.pyc\0 + + which is 32 characters including the nul, and thus fits in the + buffer. However, an input string of 'xxxxxx' would yield a result + string of: + + __pycache__/xxxxxxcpython-32.pyc\0 + + which is 33 characters long (including the nul), thus overflowing + the buffer, even though the first test would fail, i.e.: the input + string is also 6 characters long, so 32 > 32 is false. + + The reason the first test fails but we still overflow the buffer is + that the test above only expects to add one extra character to be + added to the extension, and here we're adding three (pyc). We + don't add the first dot, so that reclaims one of expected + positions, leaving us overflowing by 1 byte (3 extra - 1 reclaimed + dot - 1 expected extra == 1 overflowed). + + The best we can do is ensure that we still have enough room in the + target buffer before we write the extension. Because it's always + only the extension that can cause the overflow, and never the other + path bytes we've written, it's sufficient to just do one more test + here. Still, the assertion that follows can't hurt. + */ #if 0 - printf("strlen(buf): %d; buflen: %d\n", (int)strlen(buf), (int)buflen); + printf("strlen(buf): %d; buflen: %d\n", (int)strlen(buf), (int)buflen); #endif - if (strlen(buf) + 5 > buflen) - return NULL; - strcat(buf, debug ? ".pyc" : ".pyo"); - assert(strlen(buf) < buflen); - return buf; + if (strlen(buf) + 5 > buflen) + return NULL; + strcat(buf, debug ? ".pyc" : ".pyo"); + assert(strlen(buf) < buflen); + return buf; } @@ -926,52 +926,52 @@ for any file existence, however, if the pyc file name does not match PEP 3147 style, NULL is returned. buf must be at least as big as pathname; the resulting path will always be shorter. */ - + static char * make_source_pathname(char *pathname, char *buf) { - /* __pycache__/foo..pyc -> foo.py */ - size_t i, j; - char *left, *right, *dot0, *dot1, sep; - - /* Look back two slashes from the end. In between these two slashes - must be the string __pycache__ or this is not a PEP 3147 style - path. It's possible for there to be only one slash. - */ - if ((right = rightmost_sep(pathname)) == NULL) - return NULL; - sep = *right; - *right = '\0'; - left = rightmost_sep(pathname); - *right = sep; - if (left == NULL) - left = pathname; - else - left++; - if (right-left != strlen(CACHEDIR) || - strncmp(left, CACHEDIR, right-left) != 0) - return NULL; - - /* Now verify that the path component to the right of the last slash - has two dots in it. - */ - if ((dot0 = strchr(right + 1, '.')) == NULL) - return NULL; - if ((dot1 = strchr(dot0 + 1, '.')) == NULL) - return NULL; - /* Too many dots? */ - if (strchr(dot1 + 1, '.') != NULL) - return NULL; - - /* This is a PEP 3147 path. Start by copying everything from the - start of pathname up to and including the leftmost slash. Then - copy the file's basename, removing the magic tag and adding a .py - suffix. - */ - strncpy(buf, pathname, (i=left-pathname)); - strncpy(buf+i, right+1, (j=dot0-right)); - strcpy(buf+i+j, "py"); - return buf; + /* __pycache__/foo..pyc -> foo.py */ + size_t i, j; + char *left, *right, *dot0, *dot1, sep; + + /* Look back two slashes from the end. In between these two slashes + must be the string __pycache__ or this is not a PEP 3147 style + path. It's possible for there to be only one slash. + */ + if ((right = rightmost_sep(pathname)) == NULL) + return NULL; + sep = *right; + *right = '\0'; + left = rightmost_sep(pathname); + *right = sep; + if (left == NULL) + left = pathname; + else + left++; + if (right-left != strlen(CACHEDIR) || + strncmp(left, CACHEDIR, right-left) != 0) + return NULL; + + /* Now verify that the path component to the right of the last slash + has two dots in it. + */ + if ((dot0 = strchr(right + 1, '.')) == NULL) + return NULL; + if ((dot1 = strchr(dot0 + 1, '.')) == NULL) + return NULL; + /* Too many dots? */ + if (strchr(dot1 + 1, '.') != NULL) + return NULL; + + /* This is a PEP 3147 path. Start by copying everything from the + start of pathname up to and including the leftmost slash. Then + copy the file's basename, removing the magic tag and adding a .py + suffix. + */ + strncpy(buf, pathname, (i=left-pathname)); + strncpy(buf+i, right+1, (j=dot0-right)); + strcpy(buf+i+j, "py"); + return buf; } /* Given a pathname for a Python source file, its time of last @@ -984,30 +984,30 @@ static FILE * check_compiled_module(char *pathname, time_t mtime, char *cpathname) { - FILE *fp; - long magic; - long pyc_mtime; - - fp = fopen(cpathname, "rb"); - if (fp == NULL) - return NULL; - magic = PyMarshal_ReadLongFromFile(fp); - if (magic != pyc_magic) { - if (Py_VerboseFlag) - PySys_WriteStderr("# %s has bad magic\n", cpathname); - fclose(fp); - return NULL; - } - pyc_mtime = PyMarshal_ReadLongFromFile(fp); - if (pyc_mtime != mtime) { - if (Py_VerboseFlag) - PySys_WriteStderr("# %s has bad mtime\n", cpathname); - fclose(fp); - return NULL; - } - if (Py_VerboseFlag) - PySys_WriteStderr("# %s matches %s\n", cpathname, pathname); - return fp; + FILE *fp; + long magic; + long pyc_mtime; + + fp = fopen(cpathname, "rb"); + if (fp == NULL) + return NULL; + magic = PyMarshal_ReadLongFromFile(fp); + if (magic != pyc_magic) { + if (Py_VerboseFlag) + PySys_WriteStderr("# %s has bad magic\n", cpathname); + fclose(fp); + return NULL; + } + pyc_mtime = PyMarshal_ReadLongFromFile(fp); + if (pyc_mtime != mtime) { + if (Py_VerboseFlag) + PySys_WriteStderr("# %s has bad mtime\n", cpathname); + fclose(fp); + return NULL; + } + if (Py_VerboseFlag) + PySys_WriteStderr("# %s matches %s\n", cpathname, pathname); + return fp; } @@ -1016,18 +1016,18 @@ static PyCodeObject * read_compiled_module(char *cpathname, FILE *fp) { - PyObject *co; + PyObject *co; - co = PyMarshal_ReadLastObjectFromFile(fp); - if (co == NULL) - return NULL; - if (!PyCode_Check(co)) { - PyErr_Format(PyExc_ImportError, - "Non-code object in %.200s", cpathname); - Py_DECREF(co); - return NULL; - } - return (PyCodeObject *)co; + co = PyMarshal_ReadLastObjectFromFile(fp); + if (co == NULL) + return NULL; + if (!PyCode_Check(co)) { + PyErr_Format(PyExc_ImportError, + "Non-code object in %.200s", cpathname); + Py_DECREF(co); + return NULL; + } + return (PyCodeObject *)co; } @@ -1037,28 +1037,28 @@ static PyObject * load_compiled_module(char *name, char *cpathname, FILE *fp) { - long magic; - PyCodeObject *co; - PyObject *m; - - magic = PyMarshal_ReadLongFromFile(fp); - if (magic != pyc_magic) { - PyErr_Format(PyExc_ImportError, - "Bad magic number in %.200s", cpathname); - return NULL; - } - (void) PyMarshal_ReadLongFromFile(fp); - co = read_compiled_module(cpathname, fp); - if (co == NULL) - return NULL; - if (Py_VerboseFlag) - PySys_WriteStderr("import %s # precompiled from %s\n", - name, cpathname); - m = PyImport_ExecCodeModuleWithPathnames( - name, (PyObject *)co, cpathname, cpathname); - Py_DECREF(co); + long magic; + PyCodeObject *co; + PyObject *m; + + magic = PyMarshal_ReadLongFromFile(fp); + if (magic != pyc_magic) { + PyErr_Format(PyExc_ImportError, + "Bad magic number in %.200s", cpathname); + return NULL; + } + (void) PyMarshal_ReadLongFromFile(fp); + co = read_compiled_module(cpathname, fp); + if (co == NULL) + return NULL; + if (Py_VerboseFlag) + PySys_WriteStderr("import %s # precompiled from %s\n", + name, cpathname); + m = PyImport_ExecCodeModuleWithPathnames( + name, (PyObject *)co, cpathname, cpathname); + Py_DECREF(co); - return m; + return m; } /* Parse a source file and return the corresponding code object */ @@ -1066,22 +1066,22 @@ static PyCodeObject * parse_source_module(const char *pathname, FILE *fp) { - PyCodeObject *co = NULL; - mod_ty mod; - PyCompilerFlags flags; - PyArena *arena = PyArena_New(); - if (arena == NULL) - return NULL; - - flags.cf_flags = 0; - mod = PyParser_ASTFromFile(fp, pathname, NULL, - Py_file_input, 0, 0, &flags, - NULL, arena); - if (mod) { - co = PyAST_Compile(mod, pathname, NULL, arena); - } - PyArena_Free(arena); - return co; + PyCodeObject *co = NULL; + mod_ty mod; + PyCompilerFlags flags; + PyArena *arena = PyArena_New(); + if (arena == NULL) + return NULL; + + flags.cf_flags = 0; + mod = PyParser_ASTFromFile(fp, pathname, NULL, + Py_file_input, 0, 0, &flags, + NULL, arena); + if (mod) { + co = PyAST_Compile(mod, pathname, NULL, arena); + } + PyArena_Free(arena); + return co; } @@ -1091,30 +1091,30 @@ open_exclusive(char *filename, mode_t mode) { #if defined(O_EXCL)&&defined(O_CREAT)&&defined(O_WRONLY)&&defined(O_TRUNC) - /* Use O_EXCL to avoid a race condition when another process tries to - write the same file. When that happens, our open() call fails, - which is just fine (since it's only a cache). - XXX If the file exists and is writable but the directory is not - writable, the file will never be written. Oh well. - */ - int fd; - (void) unlink(filename); - fd = open(filename, O_EXCL|O_CREAT|O_WRONLY|O_TRUNC + /* Use O_EXCL to avoid a race condition when another process tries to + write the same file. When that happens, our open() call fails, + which is just fine (since it's only a cache). + XXX If the file exists and is writable but the directory is not + writable, the file will never be written. Oh well. + */ + int fd; + (void) unlink(filename); + fd = open(filename, O_EXCL|O_CREAT|O_WRONLY|O_TRUNC #ifdef O_BINARY - |O_BINARY /* necessary for Windows */ + |O_BINARY /* necessary for Windows */ #endif #ifdef __VMS - , mode, "ctxt=bin", "shr=nil" + , mode, "ctxt=bin", "shr=nil" #else - , mode + , mode #endif - ); - if (fd < 0) - return NULL; - return fdopen(fd, "wb"); + ); + if (fd < 0) + return NULL; + return fdopen(fd, "wb"); #else - /* Best we can do -- on Windows this can't happen anyway */ - return fopen(filename, "wb"); + /* Best we can do -- on Windows this can't happen anyway */ + return fopen(filename, "wb"); #endif } @@ -1127,116 +1127,116 @@ static void write_compiled_module(PyCodeObject *co, char *cpathname, struct stat *srcstat) { - FILE *fp; - char *dirpath; - time_t mtime = srcstat->st_mtime; + FILE *fp; + char *dirpath; + time_t mtime = srcstat->st_mtime; #ifdef MS_WINDOWS /* since Windows uses different permissions */ - mode_t mode = srcstat->st_mode & ~S_IEXEC; - mode_t dirmode = srcstat->st_mode | S_IEXEC; /* XXX Is this correct - for Windows? - 2010-04-07 BAW */ + mode_t mode = srcstat->st_mode & ~S_IEXEC; + mode_t dirmode = srcstat->st_mode | S_IEXEC; /* XXX Is this correct + for Windows? + 2010-04-07 BAW */ #else - mode_t mode = srcstat->st_mode & ~S_IXUSR & ~S_IXGRP & ~S_IXOTH; - mode_t dirmode = (srcstat->st_mode | - S_IXUSR | S_IXGRP | S_IXOTH | - S_IWUSR | S_IWGRP | S_IWOTH); -#endif - int saved; - - /* Ensure that the __pycache__ directory exists. */ - dirpath = rightmost_sep(cpathname); - if (dirpath == NULL) { - if (Py_VerboseFlag) - PySys_WriteStderr( - "# no %s path found %s\n", - CACHEDIR, cpathname); - return; - } - saved = *dirpath; - *dirpath = '\0'; - /* XXX call os.mkdir() or maybe CreateDirectoryA() on Windows? */ - if (mkdir(cpathname, dirmode) < 0 && errno != EEXIST) { - *dirpath = saved; - if (Py_VerboseFlag) - PySys_WriteStderr( - "# cannot create cache dir %s\n", cpathname); - return; - } - *dirpath = saved; - - fp = open_exclusive(cpathname, mode); - if (fp == NULL) { - if (Py_VerboseFlag) - PySys_WriteStderr( - "# can't create %s\n", cpathname); - return; - } - PyMarshal_WriteLongToFile(pyc_magic, fp, Py_MARSHAL_VERSION); - /* First write a 0 for mtime */ - PyMarshal_WriteLongToFile(0L, fp, Py_MARSHAL_VERSION); - PyMarshal_WriteObjectToFile((PyObject *)co, fp, Py_MARSHAL_VERSION); - if (fflush(fp) != 0 || ferror(fp)) { - if (Py_VerboseFlag) - PySys_WriteStderr("# can't write %s\n", cpathname); - /* Don't keep partial file */ - fclose(fp); - (void) unlink(cpathname); - return; - } - /* Now write the true mtime */ - fseek(fp, 4L, 0); - assert(mtime < LONG_MAX); - PyMarshal_WriteLongToFile((long)mtime, fp, Py_MARSHAL_VERSION); - fflush(fp); - fclose(fp); - if (Py_VerboseFlag) - PySys_WriteStderr("# wrote %s\n", cpathname); + mode_t mode = srcstat->st_mode & ~S_IXUSR & ~S_IXGRP & ~S_IXOTH; + mode_t dirmode = (srcstat->st_mode | + S_IXUSR | S_IXGRP | S_IXOTH | + S_IWUSR | S_IWGRP | S_IWOTH); +#endif + int saved; + + /* Ensure that the __pycache__ directory exists. */ + dirpath = rightmost_sep(cpathname); + if (dirpath == NULL) { + if (Py_VerboseFlag) + PySys_WriteStderr( + "# no %s path found %s\n", + CACHEDIR, cpathname); + return; + } + saved = *dirpath; + *dirpath = '\0'; + /* XXX call os.mkdir() or maybe CreateDirectoryA() on Windows? */ + if (mkdir(cpathname, dirmode) < 0 && errno != EEXIST) { + *dirpath = saved; + if (Py_VerboseFlag) + PySys_WriteStderr( + "# cannot create cache dir %s\n", cpathname); + return; + } + *dirpath = saved; + + fp = open_exclusive(cpathname, mode); + if (fp == NULL) { + if (Py_VerboseFlag) + PySys_WriteStderr( + "# can't create %s\n", cpathname); + return; + } + PyMarshal_WriteLongToFile(pyc_magic, fp, Py_MARSHAL_VERSION); + /* First write a 0 for mtime */ + PyMarshal_WriteLongToFile(0L, fp, Py_MARSHAL_VERSION); + PyMarshal_WriteObjectToFile((PyObject *)co, fp, Py_MARSHAL_VERSION); + if (fflush(fp) != 0 || ferror(fp)) { + if (Py_VerboseFlag) + PySys_WriteStderr("# can't write %s\n", cpathname); + /* Don't keep partial file */ + fclose(fp); + (void) unlink(cpathname); + return; + } + /* Now write the true mtime */ + fseek(fp, 4L, 0); + assert(mtime < LONG_MAX); + PyMarshal_WriteLongToFile((long)mtime, fp, Py_MARSHAL_VERSION); + fflush(fp); + fclose(fp); + if (Py_VerboseFlag) + PySys_WriteStderr("# wrote %s\n", cpathname); } static void update_code_filenames(PyCodeObject *co, PyObject *oldname, PyObject *newname) { - PyObject *constants, *tmp; - Py_ssize_t i, n; + PyObject *constants, *tmp; + Py_ssize_t i, n; - if (PyUnicode_Compare(co->co_filename, oldname)) - return; + if (PyUnicode_Compare(co->co_filename, oldname)) + return; - tmp = co->co_filename; - co->co_filename = newname; - Py_INCREF(co->co_filename); - Py_DECREF(tmp); - - constants = co->co_consts; - n = PyTuple_GET_SIZE(constants); - for (i = 0; i < n; i++) { - tmp = PyTuple_GET_ITEM(constants, i); - if (PyCode_Check(tmp)) - update_code_filenames((PyCodeObject *)tmp, - oldname, newname); - } + tmp = co->co_filename; + co->co_filename = newname; + Py_INCREF(co->co_filename); + Py_DECREF(tmp); + + constants = co->co_consts; + n = PyTuple_GET_SIZE(constants); + for (i = 0; i < n; i++) { + tmp = PyTuple_GET_ITEM(constants, i); + if (PyCode_Check(tmp)) + update_code_filenames((PyCodeObject *)tmp, + oldname, newname); + } } static int update_compiled_module(PyCodeObject *co, char *pathname) { - PyObject *oldname, *newname; + PyObject *oldname, *newname; - newname = PyUnicode_DecodeFSDefault(pathname); - if (newname == NULL) - return -1; - - if (!PyUnicode_Compare(co->co_filename, newname)) { - Py_DECREF(newname); - return 0; - } - - oldname = co->co_filename; - Py_INCREF(oldname); - update_code_filenames(co, oldname, newname); - Py_DECREF(oldname); - Py_DECREF(newname); - return 1; + newname = PyUnicode_DecodeFSDefault(pathname); + if (newname == NULL) + return -1; + + if (!PyUnicode_Compare(co->co_filename, newname)) { + Py_DECREF(newname); + return 0; + } + + oldname = co->co_filename; + Py_INCREF(oldname); + update_code_filenames(co, oldname, newname); + Py_DECREF(oldname); + Py_DECREF(newname); + return 1; } /* Load a source module from a given file and return its module @@ -1246,63 +1246,63 @@ static PyObject * load_source_module(char *name, char *pathname, FILE *fp) { - struct stat st; - FILE *fpc; - char buf[MAXPATHLEN+1]; - char *cpathname; - PyCodeObject *co; - PyObject *m; - - if (fstat(fileno(fp), &st) != 0) { - PyErr_Format(PyExc_RuntimeError, - "unable to get file status from '%s'", - pathname); - return NULL; - } + struct stat st; + FILE *fpc; + char buf[MAXPATHLEN+1]; + char *cpathname; + PyCodeObject *co; + PyObject *m; + + if (fstat(fileno(fp), &st) != 0) { + PyErr_Format(PyExc_RuntimeError, + "unable to get file status from '%s'", + pathname); + return NULL; + } #if SIZEOF_TIME_T > 4 - /* Python's .pyc timestamp handling presumes that the timestamp fits - in 4 bytes. This will be fine until sometime in the year 2038, - when a 4-byte signed time_t will overflow. - */ - if (st.st_mtime >> 32) { - PyErr_SetString(PyExc_OverflowError, - "modification time overflows a 4 byte field"); - return NULL; - } -#endif - cpathname = make_compiled_pathname( - pathname, buf, (size_t)MAXPATHLEN + 1, !Py_OptimizeFlag); - if (cpathname != NULL && - (fpc = check_compiled_module(pathname, st.st_mtime, cpathname))) { - co = read_compiled_module(cpathname, fpc); - fclose(fpc); - if (co == NULL) - return NULL; - if (update_compiled_module(co, pathname) < 0) - return NULL; - if (Py_VerboseFlag) - PySys_WriteStderr("import %s # precompiled from %s\n", - name, cpathname); - pathname = cpathname; - } - else { - co = parse_source_module(pathname, fp); - if (co == NULL) - return NULL; - if (Py_VerboseFlag) - PySys_WriteStderr("import %s # from %s\n", - name, pathname); - if (cpathname) { - PyObject *ro = PySys_GetObject("dont_write_bytecode"); - if (ro == NULL || !PyObject_IsTrue(ro)) - write_compiled_module(co, cpathname, &st); - } - } - m = PyImport_ExecCodeModuleWithPathnames( - name, (PyObject *)co, pathname, cpathname); - Py_DECREF(co); + /* Python's .pyc timestamp handling presumes that the timestamp fits + in 4 bytes. This will be fine until sometime in the year 2038, + when a 4-byte signed time_t will overflow. + */ + if (st.st_mtime >> 32) { + PyErr_SetString(PyExc_OverflowError, + "modification time overflows a 4 byte field"); + return NULL; + } +#endif + cpathname = make_compiled_pathname( + pathname, buf, (size_t)MAXPATHLEN + 1, !Py_OptimizeFlag); + if (cpathname != NULL && + (fpc = check_compiled_module(pathname, st.st_mtime, cpathname))) { + co = read_compiled_module(cpathname, fpc); + fclose(fpc); + if (co == NULL) + return NULL; + if (update_compiled_module(co, pathname) < 0) + return NULL; + if (Py_VerboseFlag) + PySys_WriteStderr("import %s # precompiled from %s\n", + name, cpathname); + pathname = cpathname; + } + else { + co = parse_source_module(pathname, fp); + if (co == NULL) + return NULL; + if (Py_VerboseFlag) + PySys_WriteStderr("import %s # from %s\n", + name, pathname); + if (cpathname) { + PyObject *ro = PySys_GetObject("dont_write_bytecode"); + if (ro == NULL || !PyObject_IsTrue(ro)) + write_compiled_module(co, cpathname, &st); + } + } + m = PyImport_ExecCodeModuleWithPathnames( + name, (PyObject *)co, pathname, cpathname); + Py_DECREF(co); - return m; + return m; } /* Get source file -> unicode or None @@ -1311,44 +1311,44 @@ static PyObject * get_sourcefile(char *file) { - char py[MAXPATHLEN + 1]; - Py_ssize_t len; - PyObject *u; - struct stat statbuf; - - if (!file || !*file) { - Py_RETURN_NONE; - } - - len = strlen(file); - /* match '*.py?' */ - if (len > MAXPATHLEN || PyOS_strnicmp(&file[len-4], ".py", 3) != 0) { - return PyUnicode_DecodeFSDefault(file); - } - - /* Start by trying to turn PEP 3147 path into source path. If that - * fails, just chop off the trailing character, i.e. legacy pyc path - * to py. - */ - if (make_source_pathname(file, py) == NULL) { - strncpy(py, file, len-1); - py[len-1] = '\0'; - } - - if (stat(py, &statbuf) == 0 && - S_ISREG(statbuf.st_mode)) { - u = PyUnicode_DecodeFSDefault(py); - } - else { - u = PyUnicode_DecodeFSDefault(file); - } - return u; + char py[MAXPATHLEN + 1]; + Py_ssize_t len; + PyObject *u; + struct stat statbuf; + + if (!file || !*file) { + Py_RETURN_NONE; + } + + len = strlen(file); + /* match '*.py?' */ + if (len > MAXPATHLEN || PyOS_strnicmp(&file[len-4], ".py", 3) != 0) { + return PyUnicode_DecodeFSDefault(file); + } + + /* Start by trying to turn PEP 3147 path into source path. If that + * fails, just chop off the trailing character, i.e. legacy pyc path + * to py. + */ + if (make_source_pathname(file, py) == NULL) { + strncpy(py, file, len-1); + py[len-1] = '\0'; + } + + if (stat(py, &statbuf) == 0 && + S_ISREG(statbuf.st_mode)) { + u = PyUnicode_DecodeFSDefault(py); + } + else { + u = PyUnicode_DecodeFSDefault(file); + } + return u; } /* Forward */ static PyObject *load_module(char *, FILE *, char *, int, PyObject *); static struct filedescr *find_module(char *, char *, PyObject *, - char *, size_t, FILE **, PyObject **); + char *, size_t, FILE **, PyObject **); static struct _frozen * find_frozen(char *); /* Load a package and return its module object WITH INCREMENTED @@ -1357,54 +1357,54 @@ static PyObject * load_package(char *name, char *pathname) { - PyObject *m, *d; - PyObject *file = NULL; - PyObject *path = NULL; - int err; - char buf[MAXPATHLEN+1]; - FILE *fp = NULL; - struct filedescr *fdp; - - m = PyImport_AddModule(name); - if (m == NULL) - return NULL; - if (Py_VerboseFlag) - PySys_WriteStderr("import %s # directory %s\n", - name, pathname); - d = PyModule_GetDict(m); - file = get_sourcefile(pathname); - if (file == NULL) - goto error; - path = Py_BuildValue("[O]", file); - if (path == NULL) - goto error; - err = PyDict_SetItemString(d, "__file__", file); - if (err == 0) - err = PyDict_SetItemString(d, "__path__", path); - if (err != 0) - goto error; - buf[0] = '\0'; - fdp = find_module(name, "__init__", path, buf, sizeof(buf), &fp, NULL); - if (fdp == NULL) { - if (PyErr_ExceptionMatches(PyExc_ImportError)) { - PyErr_Clear(); - Py_INCREF(m); - } - else - m = NULL; - goto cleanup; - } - m = load_module(name, fp, buf, fdp->type, NULL); - if (fp != NULL) - fclose(fp); - goto cleanup; + PyObject *m, *d; + PyObject *file = NULL; + PyObject *path = NULL; + int err; + char buf[MAXPATHLEN+1]; + FILE *fp = NULL; + struct filedescr *fdp; + + m = PyImport_AddModule(name); + if (m == NULL) + return NULL; + if (Py_VerboseFlag) + PySys_WriteStderr("import %s # directory %s\n", + name, pathname); + d = PyModule_GetDict(m); + file = get_sourcefile(pathname); + if (file == NULL) + goto error; + path = Py_BuildValue("[O]", file); + if (path == NULL) + goto error; + err = PyDict_SetItemString(d, "__file__", file); + if (err == 0) + err = PyDict_SetItemString(d, "__path__", path); + if (err != 0) + goto error; + buf[0] = '\0'; + fdp = find_module(name, "__init__", path, buf, sizeof(buf), &fp, NULL); + if (fdp == NULL) { + if (PyErr_ExceptionMatches(PyExc_ImportError)) { + PyErr_Clear(); + Py_INCREF(m); + } + else + m = NULL; + goto cleanup; + } + m = load_module(name, fp, buf, fdp->type, NULL); + if (fp != NULL) + fclose(fp); + goto cleanup; error: - m = NULL; + m = NULL; cleanup: - Py_XDECREF(path); - Py_XDECREF(file); - return m; + Py_XDECREF(path); + Py_XDECREF(file); + return m; } @@ -1413,16 +1413,16 @@ static int is_builtin(char *name) { - int i; - for (i = 0; PyImport_Inittab[i].name != NULL; i++) { - if (strcmp(name, PyImport_Inittab[i].name) == 0) { - if (PyImport_Inittab[i].initfunc == NULL) - return -1; - else - return 1; - } - } - return 0; + int i; + for (i = 0; PyImport_Inittab[i].name != NULL; i++) { + if (strcmp(name, PyImport_Inittab[i].name) == 0) { + if (PyImport_Inittab[i].initfunc == NULL) + return -1; + else + return 1; + } + } + return 0; } @@ -1436,72 +1436,72 @@ static PyObject * get_path_importer(PyObject *path_importer_cache, PyObject *path_hooks, - PyObject *p) + PyObject *p) { - PyObject *importer; - Py_ssize_t j, nhooks; + PyObject *importer; + Py_ssize_t j, nhooks; - /* These conditions are the caller's responsibility: */ - assert(PyList_Check(path_hooks)); - assert(PyDict_Check(path_importer_cache)); - - nhooks = PyList_Size(path_hooks); - if (nhooks < 0) - return NULL; /* Shouldn't happen */ - - importer = PyDict_GetItem(path_importer_cache, p); - if (importer != NULL) - return importer; - - /* set path_importer_cache[p] to None to avoid recursion */ - if (PyDict_SetItem(path_importer_cache, p, Py_None) != 0) - return NULL; - - for (j = 0; j < nhooks; j++) { - PyObject *hook = PyList_GetItem(path_hooks, j); - if (hook == NULL) - return NULL; - importer = PyObject_CallFunctionObjArgs(hook, p, NULL); - if (importer != NULL) - break; - - if (!PyErr_ExceptionMatches(PyExc_ImportError)) { - return NULL; - } - PyErr_Clear(); - } - if (importer == NULL) { - importer = PyObject_CallFunctionObjArgs( - (PyObject *)&PyNullImporter_Type, p, NULL - ); - if (importer == NULL) { - if (PyErr_ExceptionMatches(PyExc_ImportError)) { - PyErr_Clear(); - return Py_None; - } - } - } - if (importer != NULL) { - int err = PyDict_SetItem(path_importer_cache, p, importer); - Py_DECREF(importer); - if (err != 0) - return NULL; - } - return importer; + /* These conditions are the caller's responsibility: */ + assert(PyList_Check(path_hooks)); + assert(PyDict_Check(path_importer_cache)); + + nhooks = PyList_Size(path_hooks); + if (nhooks < 0) + return NULL; /* Shouldn't happen */ + + importer = PyDict_GetItem(path_importer_cache, p); + if (importer != NULL) + return importer; + + /* set path_importer_cache[p] to None to avoid recursion */ + if (PyDict_SetItem(path_importer_cache, p, Py_None) != 0) + return NULL; + + for (j = 0; j < nhooks; j++) { + PyObject *hook = PyList_GetItem(path_hooks, j); + if (hook == NULL) + return NULL; + importer = PyObject_CallFunctionObjArgs(hook, p, NULL); + if (importer != NULL) + break; + + if (!PyErr_ExceptionMatches(PyExc_ImportError)) { + return NULL; + } + PyErr_Clear(); + } + if (importer == NULL) { + importer = PyObject_CallFunctionObjArgs( + (PyObject *)&PyNullImporter_Type, p, NULL + ); + if (importer == NULL) { + if (PyErr_ExceptionMatches(PyExc_ImportError)) { + PyErr_Clear(); + return Py_None; + } + } + } + if (importer != NULL) { + int err = PyDict_SetItem(path_importer_cache, p, importer); + Py_DECREF(importer); + if (err != 0) + return NULL; + } + return importer; } PyAPI_FUNC(PyObject *) PyImport_GetImporter(PyObject *path) { - PyObject *importer=NULL, *path_importer_cache=NULL, *path_hooks=NULL; + PyObject *importer=NULL, *path_importer_cache=NULL, *path_hooks=NULL; - if ((path_importer_cache = PySys_GetObject("path_importer_cache"))) { - if ((path_hooks = PySys_GetObject("path_hooks"))) { - importer = get_path_importer(path_importer_cache, - path_hooks, path); - } - } - Py_XINCREF(importer); /* get_path_importer returns a borrowed reference */ - return importer; + if ((path_importer_cache = PySys_GetObject("path_importer_cache"))) { + if ((path_hooks = PySys_GetObject("path_hooks"))) { + importer = get_path_importer(path_importer_cache, + path_hooks, path); + } + } + Py_XINCREF(importer); /* get_path_importer returns a borrowed reference */ + return importer; } /* Search the path (default sys.path) for a module. Return the @@ -1510,7 +1510,7 @@ #ifdef MS_COREDLL extern FILE *PyWin_FindRegisteredModule(const char *, struct filedescr **, - char *, Py_ssize_t); + char *, Py_ssize_t); #endif static int case_ok(char *, Py_ssize_t, Py_ssize_t, char *); @@ -1519,276 +1519,276 @@ static struct filedescr * find_module(char *fullname, char *subname, PyObject *path, char *buf, - size_t buflen, FILE **p_fp, PyObject **p_loader) + size_t buflen, FILE **p_fp, PyObject **p_loader) { - Py_ssize_t i, npath; - size_t len, namelen; - struct filedescr *fdp = NULL; - char *filemode; - FILE *fp = NULL; - PyObject *path_hooks, *path_importer_cache; - struct stat statbuf; - static struct filedescr fd_frozen = {"", "", PY_FROZEN}; - static struct filedescr fd_builtin = {"", "", C_BUILTIN}; - static struct filedescr fd_package = {"", "", PKG_DIRECTORY}; - char name[MAXPATHLEN+1]; + Py_ssize_t i, npath; + size_t len, namelen; + struct filedescr *fdp = NULL; + char *filemode; + FILE *fp = NULL; + PyObject *path_hooks, *path_importer_cache; + struct stat statbuf; + static struct filedescr fd_frozen = {"", "", PY_FROZEN}; + static struct filedescr fd_builtin = {"", "", C_BUILTIN}; + static struct filedescr fd_package = {"", "", PKG_DIRECTORY}; + char name[MAXPATHLEN+1]; #if defined(PYOS_OS2) - size_t saved_len; - size_t saved_namelen; - char *saved_buf = NULL; -#endif - if (p_loader != NULL) - *p_loader = NULL; - - if (strlen(subname) > MAXPATHLEN) { - PyErr_SetString(PyExc_OverflowError, - "module name is too long"); - return NULL; - } - strcpy(name, subname); - - /* sys.meta_path import hook */ - if (p_loader != NULL) { - PyObject *meta_path; - - meta_path = PySys_GetObject("meta_path"); - if (meta_path == NULL || !PyList_Check(meta_path)) { - PyErr_SetString(PyExc_ImportError, - "sys.meta_path must be a list of " - "import hooks"); - return NULL; - } - Py_INCREF(meta_path); /* zap guard */ - npath = PyList_Size(meta_path); - for (i = 0; i < npath; i++) { - PyObject *loader; - PyObject *hook = PyList_GetItem(meta_path, i); - loader = PyObject_CallMethod(hook, "find_module", - "sO", fullname, - path != NULL ? - path : Py_None); - if (loader == NULL) { - Py_DECREF(meta_path); - return NULL; /* true error */ - } - if (loader != Py_None) { - /* a loader was found */ - *p_loader = loader; - Py_DECREF(meta_path); - return &importhookdescr; - } - Py_DECREF(loader); - } - Py_DECREF(meta_path); - } - - if (find_frozen(fullname) != NULL) { - strcpy(buf, fullname); - return &fd_frozen; - } - - if (path == NULL) { - if (is_builtin(name)) { - strcpy(buf, name); - return &fd_builtin; - } + size_t saved_len; + size_t saved_namelen; + char *saved_buf = NULL; +#endif + if (p_loader != NULL) + *p_loader = NULL; + + if (strlen(subname) > MAXPATHLEN) { + PyErr_SetString(PyExc_OverflowError, + "module name is too long"); + return NULL; + } + strcpy(name, subname); + + /* sys.meta_path import hook */ + if (p_loader != NULL) { + PyObject *meta_path; + + meta_path = PySys_GetObject("meta_path"); + if (meta_path == NULL || !PyList_Check(meta_path)) { + PyErr_SetString(PyExc_ImportError, + "sys.meta_path must be a list of " + "import hooks"); + return NULL; + } + Py_INCREF(meta_path); /* zap guard */ + npath = PyList_Size(meta_path); + for (i = 0; i < npath; i++) { + PyObject *loader; + PyObject *hook = PyList_GetItem(meta_path, i); + loader = PyObject_CallMethod(hook, "find_module", + "sO", fullname, + path != NULL ? + path : Py_None); + if (loader == NULL) { + Py_DECREF(meta_path); + return NULL; /* true error */ + } + if (loader != Py_None) { + /* a loader was found */ + *p_loader = loader; + Py_DECREF(meta_path); + return &importhookdescr; + } + Py_DECREF(loader); + } + Py_DECREF(meta_path); + } + + if (find_frozen(fullname) != NULL) { + strcpy(buf, fullname); + return &fd_frozen; + } + + if (path == NULL) { + if (is_builtin(name)) { + strcpy(buf, name); + return &fd_builtin; + } #ifdef MS_COREDLL - fp = PyWin_FindRegisteredModule(name, &fdp, buf, buflen); - if (fp != NULL) { - *p_fp = fp; - return fdp; - } -#endif - path = PySys_GetObject("path"); - } - - if (path == NULL || !PyList_Check(path)) { - PyErr_SetString(PyExc_ImportError, - "sys.path must be a list of directory names"); - return NULL; - } - - path_hooks = PySys_GetObject("path_hooks"); - if (path_hooks == NULL || !PyList_Check(path_hooks)) { - PyErr_SetString(PyExc_ImportError, - "sys.path_hooks must be a list of " - "import hooks"); - return NULL; - } - path_importer_cache = PySys_GetObject("path_importer_cache"); - if (path_importer_cache == NULL || - !PyDict_Check(path_importer_cache)) { - PyErr_SetString(PyExc_ImportError, - "sys.path_importer_cache must be a dict"); - return NULL; - } - - npath = PyList_Size(path); - namelen = strlen(name); - for (i = 0; i < npath; i++) { - PyObject *v = PyList_GetItem(path, i); - PyObject *origv = v; - const char *base; - Py_ssize_t size; - if (!v) - return NULL; - if (PyUnicode_Check(v)) { - v = PyUnicode_AsEncodedString(v, - Py_FileSystemDefaultEncoding, NULL); - if (v == NULL) - return NULL; - } - else if (!PyBytes_Check(v)) - continue; - else - Py_INCREF(v); - - base = PyBytes_AS_STRING(v); - size = PyBytes_GET_SIZE(v); - len = size; - if (len + 2 + namelen + MAXSUFFIXSIZE >= buflen) { - Py_DECREF(v); - continue; /* Too long */ - } - strcpy(buf, base); - Py_DECREF(v); - - if (strlen(buf) != len) { - continue; /* v contains '\0' */ - } - - /* sys.path_hooks import hook */ - if (p_loader != NULL) { - PyObject *importer; - - importer = get_path_importer(path_importer_cache, - path_hooks, origv); - if (importer == NULL) { - return NULL; - } - /* Note: importer is a borrowed reference */ - if (importer != Py_None) { - PyObject *loader; - loader = PyObject_CallMethod(importer, - "find_module", - "s", fullname); - if (loader == NULL) - return NULL; /* error */ - if (loader != Py_None) { - /* a loader was found */ - *p_loader = loader; - return &importhookdescr; - } - Py_DECREF(loader); - continue; - } - } - /* no hook was found, use builtin import */ + fp = PyWin_FindRegisteredModule(name, &fdp, buf, buflen); + if (fp != NULL) { + *p_fp = fp; + return fdp; + } +#endif + path = PySys_GetObject("path"); + } + + if (path == NULL || !PyList_Check(path)) { + PyErr_SetString(PyExc_ImportError, + "sys.path must be a list of directory names"); + return NULL; + } + + path_hooks = PySys_GetObject("path_hooks"); + if (path_hooks == NULL || !PyList_Check(path_hooks)) { + PyErr_SetString(PyExc_ImportError, + "sys.path_hooks must be a list of " + "import hooks"); + return NULL; + } + path_importer_cache = PySys_GetObject("path_importer_cache"); + if (path_importer_cache == NULL || + !PyDict_Check(path_importer_cache)) { + PyErr_SetString(PyExc_ImportError, + "sys.path_importer_cache must be a dict"); + return NULL; + } + + npath = PyList_Size(path); + namelen = strlen(name); + for (i = 0; i < npath; i++) { + PyObject *v = PyList_GetItem(path, i); + PyObject *origv = v; + const char *base; + Py_ssize_t size; + if (!v) + return NULL; + if (PyUnicode_Check(v)) { + v = PyUnicode_AsEncodedString(v, + Py_FileSystemDefaultEncoding, NULL); + if (v == NULL) + return NULL; + } + else if (!PyBytes_Check(v)) + continue; + else + Py_INCREF(v); + + base = PyBytes_AS_STRING(v); + size = PyBytes_GET_SIZE(v); + len = size; + if (len + 2 + namelen + MAXSUFFIXSIZE >= buflen) { + Py_DECREF(v); + continue; /* Too long */ + } + strcpy(buf, base); + Py_DECREF(v); + + if (strlen(buf) != len) { + continue; /* v contains '\0' */ + } + + /* sys.path_hooks import hook */ + if (p_loader != NULL) { + PyObject *importer; + + importer = get_path_importer(path_importer_cache, + path_hooks, origv); + if (importer == NULL) { + return NULL; + } + /* Note: importer is a borrowed reference */ + if (importer != Py_None) { + PyObject *loader; + loader = PyObject_CallMethod(importer, + "find_module", + "s", fullname); + if (loader == NULL) + return NULL; /* error */ + if (loader != Py_None) { + /* a loader was found */ + *p_loader = loader; + return &importhookdescr; + } + Py_DECREF(loader); + continue; + } + } + /* no hook was found, use builtin import */ - if (len > 0 && buf[len-1] != SEP + if (len > 0 && buf[len-1] != SEP #ifdef ALTSEP - && buf[len-1] != ALTSEP + && buf[len-1] != ALTSEP #endif - ) - buf[len++] = SEP; - strcpy(buf+len, name); - len += namelen; + ) + buf[len++] = SEP; + strcpy(buf+len, name); + len += namelen; - /* Check for package import (buf holds a directory name, - and there's an __init__ module in that directory */ + /* Check for package import (buf holds a directory name, + and there's an __init__ module in that directory */ #ifdef HAVE_STAT - if (stat(buf, &statbuf) == 0 && /* it exists */ - S_ISDIR(statbuf.st_mode) && /* it's a directory */ - case_ok(buf, len, namelen, name)) { /* case matches */ - if (find_init_module(buf)) { /* and has __init__.py */ - return &fd_package; - } - else { - char warnstr[MAXPATHLEN+80]; - sprintf(warnstr, "Not importing directory " - "'%.*s': missing __init__.py", - MAXPATHLEN, buf); - if (PyErr_WarnEx(PyExc_ImportWarning, - warnstr, 1)) { - return NULL; - } - } - } + if (stat(buf, &statbuf) == 0 && /* it exists */ + S_ISDIR(statbuf.st_mode) && /* it's a directory */ + case_ok(buf, len, namelen, name)) { /* case matches */ + if (find_init_module(buf)) { /* and has __init__.py */ + return &fd_package; + } + else { + char warnstr[MAXPATHLEN+80]; + sprintf(warnstr, "Not importing directory " + "'%.*s': missing __init__.py", + MAXPATHLEN, buf); + if (PyErr_WarnEx(PyExc_ImportWarning, + warnstr, 1)) { + return NULL; + } + } + } #endif #if defined(PYOS_OS2) - /* take a snapshot of the module spec for restoration - * after the 8 character DLL hackery - */ - saved_buf = strdup(buf); - saved_len = len; - saved_namelen = namelen; + /* take a snapshot of the module spec for restoration + * after the 8 character DLL hackery + */ + saved_buf = strdup(buf); + saved_len = len; + saved_namelen = namelen; #endif /* PYOS_OS2 */ - for (fdp = _PyImport_Filetab; fdp->suffix != NULL; fdp++) { + for (fdp = _PyImport_Filetab; fdp->suffix != NULL; fdp++) { #if defined(PYOS_OS2) && defined(HAVE_DYNAMIC_LOADING) - /* OS/2 limits DLLs to 8 character names (w/o - extension) - * so if the name is longer than that and its a - * dynamically loaded module we're going to try, - * truncate the name before trying - */ - if (strlen(subname) > 8) { - /* is this an attempt to load a C extension? */ - const struct filedescr *scan; - scan = _PyImport_DynLoadFiletab; - while (scan->suffix != NULL) { - if (!strcmp(scan->suffix, fdp->suffix)) - break; - else - scan++; - } - if (scan->suffix != NULL) { - /* yes, so truncate the name */ - namelen = 8; - len -= strlen(subname) - namelen; - buf[len] = '\0'; - } - } + /* OS/2 limits DLLs to 8 character names (w/o + extension) + * so if the name is longer than that and its a + * dynamically loaded module we're going to try, + * truncate the name before trying + */ + if (strlen(subname) > 8) { + /* is this an attempt to load a C extension? */ + const struct filedescr *scan; + scan = _PyImport_DynLoadFiletab; + while (scan->suffix != NULL) { + if (!strcmp(scan->suffix, fdp->suffix)) + break; + else + scan++; + } + if (scan->suffix != NULL) { + /* yes, so truncate the name */ + namelen = 8; + len -= strlen(subname) - namelen; + buf[len] = '\0'; + } + } #endif /* PYOS_OS2 */ - strcpy(buf+len, fdp->suffix); - if (Py_VerboseFlag > 1) - PySys_WriteStderr("# trying %s\n", buf); - filemode = fdp->mode; - if (filemode[0] == 'U') - filemode = "r" PY_STDIOTEXTMODE; - fp = fopen(buf, filemode); - if (fp != NULL) { - if (case_ok(buf, len, namelen, name)) - break; - else { /* continue search */ - fclose(fp); - fp = NULL; - } - } + strcpy(buf+len, fdp->suffix); + if (Py_VerboseFlag > 1) + PySys_WriteStderr("# trying %s\n", buf); + filemode = fdp->mode; + if (filemode[0] == 'U') + filemode = "r" PY_STDIOTEXTMODE; + fp = fopen(buf, filemode); + if (fp != NULL) { + if (case_ok(buf, len, namelen, name)) + break; + else { /* continue search */ + fclose(fp); + fp = NULL; + } + } #if defined(PYOS_OS2) - /* restore the saved snapshot */ - strcpy(buf, saved_buf); - len = saved_len; - namelen = saved_namelen; + /* restore the saved snapshot */ + strcpy(buf, saved_buf); + len = saved_len; + namelen = saved_namelen; #endif - } + } #if defined(PYOS_OS2) - /* don't need/want the module name snapshot anymore */ - if (saved_buf) - { - free(saved_buf); - saved_buf = NULL; - } -#endif - if (fp != NULL) - break; - } - if (fp == NULL) { - PyErr_Format(PyExc_ImportError, - "No module named %.200s", name); - return NULL; - } - *p_fp = fp; - return fdp; + /* don't need/want the module name snapshot anymore */ + if (saved_buf) + { + free(saved_buf); + saved_buf = NULL; + } +#endif + if (fp != NULL) + break; + } + if (fp == NULL) { + PyErr_Format(PyExc_ImportError, + "No module named %.200s", name); + return NULL; + } + *p_fp = fp; + return fdp; } /* Helpers for main.c @@ -1796,15 +1796,15 @@ */ struct filedescr * _PyImport_FindModule(const char *name, PyObject *path, char *buf, - size_t buflen, FILE **p_fp, PyObject **p_loader) + size_t buflen, FILE **p_fp, PyObject **p_loader) { - return find_module((char *) name, (char *) name, path, - buf, buflen, p_fp, p_loader); + return find_module((char *) name, (char *) name, path, + buf, buflen, p_fp, p_loader); } PyAPI_FUNC(int) _PyImport_IsScript(struct filedescr * fd) { - return fd->type == PY_SOURCE || fd->type == PY_COMPILED; + return fd->type == PY_SOURCE || fd->type == PY_COMPILED; } /* case_ok(char* buf, Py_ssize_t len, Py_ssize_t namelen, char* name) @@ -1860,103 +1860,103 @@ /* MS_WINDOWS */ #if defined(MS_WINDOWS) - WIN32_FIND_DATA data; - HANDLE h; + WIN32_FIND_DATA data; + HANDLE h; - if (Py_GETENV("PYTHONCASEOK") != NULL) - return 1; + if (Py_GETENV("PYTHONCASEOK") != NULL) + return 1; - h = FindFirstFile(buf, &data); - if (h == INVALID_HANDLE_VALUE) { - PyErr_Format(PyExc_NameError, - "Can't find file for module %.100s\n(filename %.300s)", - name, buf); - return 0; - } - FindClose(h); - return strncmp(data.cFileName, name, namelen) == 0; + h = FindFirstFile(buf, &data); + if (h == INVALID_HANDLE_VALUE) { + PyErr_Format(PyExc_NameError, + "Can't find file for module %.100s\n(filename %.300s)", + name, buf); + return 0; + } + FindClose(h); + return strncmp(data.cFileName, name, namelen) == 0; /* DJGPP */ #elif defined(DJGPP) - struct ffblk ffblk; - int done; + struct ffblk ffblk; + int done; - if (Py_GETENV("PYTHONCASEOK") != NULL) - return 1; + if (Py_GETENV("PYTHONCASEOK") != NULL) + return 1; - done = findfirst(buf, &ffblk, FA_ARCH|FA_RDONLY|FA_HIDDEN|FA_DIREC); - if (done) { - PyErr_Format(PyExc_NameError, - "Can't find file for module %.100s\n(filename %.300s)", - name, buf); - return 0; - } - return strncmp(ffblk.ff_name, name, namelen) == 0; + done = findfirst(buf, &ffblk, FA_ARCH|FA_RDONLY|FA_HIDDEN|FA_DIREC); + if (done) { + PyErr_Format(PyExc_NameError, + "Can't find file for module %.100s\n(filename %.300s)", + name, buf); + return 0; + } + return strncmp(ffblk.ff_name, name, namelen) == 0; /* new-fangled macintosh (macosx) or Cygwin */ #elif (defined(__MACH__) && defined(__APPLE__) || defined(__CYGWIN__)) && defined(HAVE_DIRENT_H) - DIR *dirp; - struct dirent *dp; - char dirname[MAXPATHLEN + 1]; - const int dirlen = len - namelen - 1; /* don't want trailing SEP */ - - if (Py_GETENV("PYTHONCASEOK") != NULL) - return 1; - - /* Copy the dir component into dirname; substitute "." if empty */ - if (dirlen <= 0) { - dirname[0] = '.'; - dirname[1] = '\0'; - } - else { - assert(dirlen <= MAXPATHLEN); - memcpy(dirname, buf, dirlen); - dirname[dirlen] = '\0'; - } - /* Open the directory and search the entries for an exact match. */ - dirp = opendir(dirname); - if (dirp) { - char *nameWithExt = buf + len - namelen; - while ((dp = readdir(dirp)) != NULL) { - const int thislen = + DIR *dirp; + struct dirent *dp; + char dirname[MAXPATHLEN + 1]; + const int dirlen = len - namelen - 1; /* don't want trailing SEP */ + + if (Py_GETENV("PYTHONCASEOK") != NULL) + return 1; + + /* Copy the dir component into dirname; substitute "." if empty */ + if (dirlen <= 0) { + dirname[0] = '.'; + dirname[1] = '\0'; + } + else { + assert(dirlen <= MAXPATHLEN); + memcpy(dirname, buf, dirlen); + dirname[dirlen] = '\0'; + } + /* Open the directory and search the entries for an exact match. */ + dirp = opendir(dirname); + if (dirp) { + char *nameWithExt = buf + len - namelen; + while ((dp = readdir(dirp)) != NULL) { + const int thislen = #ifdef _DIRENT_HAVE_D_NAMELEN - dp->d_namlen; + dp->d_namlen; #else - strlen(dp->d_name); + strlen(dp->d_name); #endif - if (thislen >= namelen && - strcmp(dp->d_name, nameWithExt) == 0) { - (void)closedir(dirp); - return 1; /* Found */ - } - } - (void)closedir(dirp); - } - return 0 ; /* Not found */ + if (thislen >= namelen && + strcmp(dp->d_name, nameWithExt) == 0) { + (void)closedir(dirp); + return 1; /* Found */ + } + } + (void)closedir(dirp); + } + return 0 ; /* Not found */ /* OS/2 */ #elif defined(PYOS_OS2) - HDIR hdir = 1; - ULONG srchcnt = 1; - FILEFINDBUF3 ffbuf; - APIRET rc; - - if (Py_GETENV("PYTHONCASEOK") != NULL) - return 1; - - rc = DosFindFirst(buf, - &hdir, - FILE_READONLY | FILE_HIDDEN | FILE_SYSTEM | FILE_DIRECTORY, - &ffbuf, sizeof(ffbuf), - &srchcnt, - FIL_STANDARD); - if (rc != NO_ERROR) - return 0; - return strncmp(ffbuf.achName, name, namelen) == 0; + HDIR hdir = 1; + ULONG srchcnt = 1; + FILEFINDBUF3 ffbuf; + APIRET rc; + + if (Py_GETENV("PYTHONCASEOK") != NULL) + return 1; + + rc = DosFindFirst(buf, + &hdir, + FILE_READONLY | FILE_HIDDEN | FILE_SYSTEM | FILE_DIRECTORY, + &ffbuf, sizeof(ffbuf), + &srchcnt, + FIL_STANDARD); + if (rc != NO_ERROR) + return 0; + return strncmp(ffbuf.achName, name, namelen) == 0; /* assuming it's a case-sensitive filesystem, so there's nothing to do! */ #else - return 1; + return 1; #endif } @@ -1967,46 +1967,46 @@ static int find_init_module(char *buf) { - const size_t save_len = strlen(buf); - size_t i = save_len; - char *pname; /* pointer to start of __init__ */ - struct stat statbuf; - -/* For calling case_ok(buf, len, namelen, name): - * /a/b/c/d/e/f/g/h/i/j/k/some_long_module_name.py\0 - * ^ ^ ^ ^ - * |--------------------- buf ---------------------| - * |------------------- len ------------------| - * |------ name -------| - * |----- namelen -----| + const size_t save_len = strlen(buf); + size_t i = save_len; + char *pname; /* pointer to start of __init__ */ + struct stat statbuf; + +/* For calling case_ok(buf, len, namelen, name): + * /a/b/c/d/e/f/g/h/i/j/k/some_long_module_name.py\0 + * ^ ^ ^ ^ + * |--------------------- buf ---------------------| + * |------------------- len ------------------| + * |------ name -------| + * |----- namelen -----| */ - if (save_len + 13 >= MAXPATHLEN) - return 0; - buf[i++] = SEP; - pname = buf + i; - strcpy(pname, "__init__.py"); - if (stat(buf, &statbuf) == 0) { - if (case_ok(buf, - save_len + 9, /* len("/__init__") */ - 8, /* len("__init__") */ - pname)) { - buf[save_len] = '\0'; - return 1; - } - } - i += strlen(pname); - strcpy(buf+i, Py_OptimizeFlag ? "o" : "c"); - if (stat(buf, &statbuf) == 0) { - if (case_ok(buf, - save_len + 9, /* len("/__init__") */ - 8, /* len("__init__") */ - pname)) { - buf[save_len] = '\0'; - return 1; - } - } - buf[save_len] = '\0'; - return 0; + if (save_len + 13 >= MAXPATHLEN) + return 0; + buf[i++] = SEP; + pname = buf + i; + strcpy(pname, "__init__.py"); + if (stat(buf, &statbuf) == 0) { + if (case_ok(buf, + save_len + 9, /* len("/__init__") */ + 8, /* len("__init__") */ + pname)) { + buf[save_len] = '\0'; + return 1; + } + } + i += strlen(pname); + strcpy(buf+i, Py_OptimizeFlag ? "o" : "c"); + if (stat(buf, &statbuf) == 0) { + if (case_ok(buf, + save_len + 9, /* len("/__init__") */ + 8, /* len("__init__") */ + pname)) { + buf[save_len] = '\0'; + return 1; + } + } + buf[save_len] = '\0'; + return 0; } #endif /* HAVE_STAT */ @@ -2020,93 +2020,93 @@ static PyObject * load_module(char *name, FILE *fp, char *pathname, int type, PyObject *loader) { - PyObject *modules; - PyObject *m; - int err; - - /* First check that there's an open file (if we need one) */ - switch (type) { - case PY_SOURCE: - case PY_COMPILED: - if (fp == NULL) { - PyErr_Format(PyExc_ValueError, - "file object required for import (type code %d)", - type); - return NULL; - } - } - - switch (type) { - - case PY_SOURCE: - m = load_source_module(name, pathname, fp); - break; - - case PY_COMPILED: - m = load_compiled_module(name, pathname, fp); - break; + PyObject *modules; + PyObject *m; + int err; + + /* First check that there's an open file (if we need one) */ + switch (type) { + case PY_SOURCE: + case PY_COMPILED: + if (fp == NULL) { + PyErr_Format(PyExc_ValueError, + "file object required for import (type code %d)", + type); + return NULL; + } + } + + switch (type) { + + case PY_SOURCE: + m = load_source_module(name, pathname, fp); + break; + + case PY_COMPILED: + m = load_compiled_module(name, pathname, fp); + break; #ifdef HAVE_DYNAMIC_LOADING - case C_EXTENSION: - m = _PyImport_LoadDynamicModule(name, pathname, fp); - break; -#endif - - case PKG_DIRECTORY: - m = load_package(name, pathname); - break; - - case C_BUILTIN: - case PY_FROZEN: - if (pathname != NULL && pathname[0] != '\0') - name = pathname; - if (type == C_BUILTIN) - err = init_builtin(name); - else - err = PyImport_ImportFrozenModule(name); - if (err < 0) - return NULL; - if (err == 0) { - PyErr_Format(PyExc_ImportError, - "Purported %s module %.200s not found", - type == C_BUILTIN ? - "builtin" : "frozen", - name); - return NULL; - } - modules = PyImport_GetModuleDict(); - m = PyDict_GetItemString(modules, name); - if (m == NULL) { - PyErr_Format( - PyExc_ImportError, - "%s module %.200s not properly initialized", - type == C_BUILTIN ? - "builtin" : "frozen", - name); - return NULL; - } - Py_INCREF(m); - break; - - case IMP_HOOK: { - if (loader == NULL) { - PyErr_SetString(PyExc_ImportError, - "import hook without loader"); - return NULL; - } - m = PyObject_CallMethod(loader, "load_module", "s", name); - break; - } - - default: - PyErr_Format(PyExc_ImportError, - "Don't know how to import %.200s (type code %d)", - name, type); - m = NULL; + case C_EXTENSION: + m = _PyImport_LoadDynamicModule(name, pathname, fp); + break; +#endif + + case PKG_DIRECTORY: + m = load_package(name, pathname); + break; + + case C_BUILTIN: + case PY_FROZEN: + if (pathname != NULL && pathname[0] != '\0') + name = pathname; + if (type == C_BUILTIN) + err = init_builtin(name); + else + err = PyImport_ImportFrozenModule(name); + if (err < 0) + return NULL; + if (err == 0) { + PyErr_Format(PyExc_ImportError, + "Purported %s module %.200s not found", + type == C_BUILTIN ? + "builtin" : "frozen", + name); + return NULL; + } + modules = PyImport_GetModuleDict(); + m = PyDict_GetItemString(modules, name); + if (m == NULL) { + PyErr_Format( + PyExc_ImportError, + "%s module %.200s not properly initialized", + type == C_BUILTIN ? + "builtin" : "frozen", + name); + return NULL; + } + Py_INCREF(m); + break; + + case IMP_HOOK: { + if (loader == NULL) { + PyErr_SetString(PyExc_ImportError, + "import hook without loader"); + return NULL; + } + m = PyObject_CallMethod(loader, "load_module", "s", name); + break; + } + + default: + PyErr_Format(PyExc_ImportError, + "Don't know how to import %.200s (type code %d)", + name, type); + m = NULL; - } + } - return m; + return m; } @@ -2117,34 +2117,34 @@ static int init_builtin(char *name) { - struct _inittab *p; + struct _inittab *p; - if (_PyImport_FindExtension(name, name) != NULL) - return 1; + if (_PyImport_FindExtension(name, name) != NULL) + return 1; - for (p = PyImport_Inittab; p->name != NULL; p++) { - PyObject *mod; - if (strcmp(name, p->name) == 0) { - if (p->initfunc == NULL) { - PyErr_Format(PyExc_ImportError, - "Cannot re-init internal module %.200s", - name); - return -1; - } - if (Py_VerboseFlag) - PySys_WriteStderr("import %s # builtin\n", name); - mod = (*p->initfunc)(); - if (mod == 0) - return -1; - if (_PyImport_FixupExtension(mod, name, name) < 0) - return -1; - /* FixupExtension has put the module into sys.modules, - so we can release our own reference. */ - Py_DECREF(mod); - return 1; - } - } - return 0; + for (p = PyImport_Inittab; p->name != NULL; p++) { + PyObject *mod; + if (strcmp(name, p->name) == 0) { + if (p->initfunc == NULL) { + PyErr_Format(PyExc_ImportError, + "Cannot re-init internal module %.200s", + name); + return -1; + } + if (Py_VerboseFlag) + PySys_WriteStderr("import %s # builtin\n", name); + mod = (*p->initfunc)(); + if (mod == 0) + return -1; + if (_PyImport_FixupExtension(mod, name, name) < 0) + return -1; + /* FixupExtension has put the module into sys.modules, + so we can release our own reference. */ + Py_DECREF(mod); + return 1; + } + } + return 0; } @@ -2153,63 +2153,63 @@ static struct _frozen * find_frozen(char *name) { - struct _frozen *p; + struct _frozen *p; - if (!name) - return NULL; + if (!name) + return NULL; - for (p = PyImport_FrozenModules; ; p++) { - if (p->name == NULL) - return NULL; - if (strcmp(p->name, name) == 0) - break; - } - return p; + for (p = PyImport_FrozenModules; ; p++) { + if (p->name == NULL) + return NULL; + if (strcmp(p->name, name) == 0) + break; + } + return p; } static PyObject * get_frozen_object(char *name) { - struct _frozen *p = find_frozen(name); - int size; + struct _frozen *p = find_frozen(name); + int size; - if (p == NULL) { - PyErr_Format(PyExc_ImportError, - "No such frozen object named %.200s", - name); - return NULL; - } - if (p->code == NULL) { - PyErr_Format(PyExc_ImportError, - "Excluded frozen object named %.200s", - name); - return NULL; - } - size = p->size; - if (size < 0) - size = -size; - return PyMarshal_ReadObjectFromString((char *)p->code, size); + if (p == NULL) { + PyErr_Format(PyExc_ImportError, + "No such frozen object named %.200s", + name); + return NULL; + } + if (p->code == NULL) { + PyErr_Format(PyExc_ImportError, + "Excluded frozen object named %.200s", + name); + return NULL; + } + size = p->size; + if (size < 0) + size = -size; + return PyMarshal_ReadObjectFromString((char *)p->code, size); } static PyObject * is_frozen_package(char *name) { - struct _frozen *p = find_frozen(name); - int size; + struct _frozen *p = find_frozen(name); + int size; - if (p == NULL) { - PyErr_Format(PyExc_ImportError, - "No such frozen object named %.200s", - name); - return NULL; - } - - size = p->size; - - if (size < 0) - Py_RETURN_TRUE; - else - Py_RETURN_FALSE; + if (p == NULL) { + PyErr_Format(PyExc_ImportError, + "No such frozen object named %.200s", + name); + return NULL; + } + + size = p->size; + + if (size < 0) + Py_RETURN_TRUE; + else + Py_RETURN_FALSE; } @@ -2221,67 +2221,67 @@ int PyImport_ImportFrozenModule(char *name) { - struct _frozen *p = find_frozen(name); - PyObject *co; - PyObject *m; - int ispackage; - int size; - - if (p == NULL) - return 0; - if (p->code == NULL) { - PyErr_Format(PyExc_ImportError, - "Excluded frozen object named %.200s", - name); - return -1; - } - size = p->size; - ispackage = (size < 0); - if (ispackage) - size = -size; - if (Py_VerboseFlag) - PySys_WriteStderr("import %s # frozen%s\n", - name, ispackage ? " package" : ""); - co = PyMarshal_ReadObjectFromString((char *)p->code, size); - if (co == NULL) - return -1; - if (!PyCode_Check(co)) { - PyErr_Format(PyExc_TypeError, - "frozen object %.200s is not a code object", - name); - goto err_return; - } - if (ispackage) { - /* Set __path__ to the package name */ - PyObject *d, *s, *l; - int err; - m = PyImport_AddModule(name); - if (m == NULL) - goto err_return; - d = PyModule_GetDict(m); - s = PyUnicode_InternFromString(name); - if (s == NULL) - goto err_return; - l = PyList_New(1); - if (l == NULL) { - Py_DECREF(s); - goto err_return; - } - PyList_SET_ITEM(l, 0, s); - err = PyDict_SetItemString(d, "__path__", l); - Py_DECREF(l); - if (err != 0) - goto err_return; - } - m = PyImport_ExecCodeModuleEx(name, co, ""); - if (m == NULL) - goto err_return; - Py_DECREF(co); - Py_DECREF(m); - return 1; + struct _frozen *p = find_frozen(name); + PyObject *co; + PyObject *m; + int ispackage; + int size; + + if (p == NULL) + return 0; + if (p->code == NULL) { + PyErr_Format(PyExc_ImportError, + "Excluded frozen object named %.200s", + name); + return -1; + } + size = p->size; + ispackage = (size < 0); + if (ispackage) + size = -size; + if (Py_VerboseFlag) + PySys_WriteStderr("import %s # frozen%s\n", + name, ispackage ? " package" : ""); + co = PyMarshal_ReadObjectFromString((char *)p->code, size); + if (co == NULL) + return -1; + if (!PyCode_Check(co)) { + PyErr_Format(PyExc_TypeError, + "frozen object %.200s is not a code object", + name); + goto err_return; + } + if (ispackage) { + /* Set __path__ to the package name */ + PyObject *d, *s, *l; + int err; + m = PyImport_AddModule(name); + if (m == NULL) + goto err_return; + d = PyModule_GetDict(m); + s = PyUnicode_InternFromString(name); + if (s == NULL) + goto err_return; + l = PyList_New(1); + if (l == NULL) { + Py_DECREF(s); + goto err_return; + } + PyList_SET_ITEM(l, 0, s); + err = PyDict_SetItemString(d, "__path__", l); + Py_DECREF(l); + if (err != 0) + goto err_return; + } + m = PyImport_ExecCodeModuleEx(name, co, ""); + if (m == NULL) + goto err_return; + Py_DECREF(co); + Py_DECREF(m); + return 1; err_return: - Py_DECREF(co); - return -1; + Py_DECREF(co); + return -1; } @@ -2291,15 +2291,15 @@ PyObject * PyImport_ImportModule(const char *name) { - PyObject *pname; - PyObject *result; + PyObject *pname; + PyObject *result; - pname = PyUnicode_FromString(name); - if (pname == NULL) - return NULL; - result = PyImport_Import(pname); - Py_DECREF(pname); - return result; + pname = PyUnicode_FromString(name); + if (pname == NULL) + return NULL; + result = PyImport_Import(pname); + Py_DECREF(pname); + return result; } /* Import a module without blocking @@ -2314,137 +2314,137 @@ PyObject * PyImport_ImportModuleNoBlock(const char *name) { - PyObject *result; - PyObject *modules; - long me; - - /* Try to get the module from sys.modules[name] */ - modules = PyImport_GetModuleDict(); - if (modules == NULL) - return NULL; - - result = PyDict_GetItemString(modules, name); - if (result != NULL) { - Py_INCREF(result); - return result; - } - else { - PyErr_Clear(); - } + PyObject *result; + PyObject *modules; + long me; + + /* Try to get the module from sys.modules[name] */ + modules = PyImport_GetModuleDict(); + if (modules == NULL) + return NULL; + + result = PyDict_GetItemString(modules, name); + if (result != NULL) { + Py_INCREF(result); + return result; + } + else { + PyErr_Clear(); + } #ifdef WITH_THREAD - /* check the import lock - * me might be -1 but I ignore the error here, the lock function - * takes care of the problem */ - me = PyThread_get_thread_ident(); - if (import_lock_thread == -1 || import_lock_thread == me) { - /* no thread or me is holding the lock */ - return PyImport_ImportModule(name); - } - else { - PyErr_Format(PyExc_ImportError, - "Failed to import %.200s because the import lock" - "is held by another thread.", - name); - return NULL; - } + /* check the import lock + * me might be -1 but I ignore the error here, the lock function + * takes care of the problem */ + me = PyThread_get_thread_ident(); + if (import_lock_thread == -1 || import_lock_thread == me) { + /* no thread or me is holding the lock */ + return PyImport_ImportModule(name); + } + else { + PyErr_Format(PyExc_ImportError, + "Failed to import %.200s because the import lock" + "is held by another thread.", + name); + return NULL; + } #else - return PyImport_ImportModule(name); + return PyImport_ImportModule(name); #endif } /* Forward declarations for helper routines */ static PyObject *get_parent(PyObject *globals, char *buf, - Py_ssize_t *p_buflen, int level); + Py_ssize_t *p_buflen, int level); static PyObject *load_next(PyObject *mod, PyObject *altmod, - char **p_name, char *buf, Py_ssize_t *p_buflen); + char **p_name, char *buf, Py_ssize_t *p_buflen); static int mark_miss(char *name); static int ensure_fromlist(PyObject *mod, PyObject *fromlist, - char *buf, Py_ssize_t buflen, int recursive); + char *buf, Py_ssize_t buflen, int recursive); static PyObject * import_submodule(PyObject *mod, char *name, char *fullname); /* The Magnum Opus of dotted-name import :-) */ static PyObject * import_module_level(char *name, PyObject *globals, PyObject *locals, - PyObject *fromlist, int level) + PyObject *fromlist, int level) { - char buf[MAXPATHLEN+1]; - Py_ssize_t buflen = 0; - PyObject *parent, *head, *next, *tail; + char buf[MAXPATHLEN+1]; + Py_ssize_t buflen = 0; + PyObject *parent, *head, *next, *tail; - if (strchr(name, '/') != NULL + if (strchr(name, '/') != NULL #ifdef MS_WINDOWS - || strchr(name, '\\') != NULL + || strchr(name, '\\') != NULL #endif - ) { - PyErr_SetString(PyExc_ImportError, - "Import by filename is not supported."); - return NULL; - } - - parent = get_parent(globals, buf, &buflen, level); - if (parent == NULL) - return NULL; - - head = load_next(parent, Py_None, &name, buf, &buflen); - if (head == NULL) - return NULL; - - tail = head; - Py_INCREF(tail); - while (name) { - next = load_next(tail, tail, &name, buf, &buflen); - Py_DECREF(tail); - if (next == NULL) { - Py_DECREF(head); - return NULL; - } - tail = next; - } - if (tail == Py_None) { - /* If tail is Py_None, both get_parent and load_next found - an empty module name: someone called __import__("") or - doctored faulty bytecode */ - Py_DECREF(tail); - Py_DECREF(head); - PyErr_SetString(PyExc_ValueError, - "Empty module name"); - return NULL; - } - - if (fromlist != NULL) { - if (fromlist == Py_None || !PyObject_IsTrue(fromlist)) - fromlist = NULL; - } - - if (fromlist == NULL) { - Py_DECREF(tail); - return head; - } - - Py_DECREF(head); - if (!ensure_fromlist(tail, fromlist, buf, buflen, 0)) { - Py_DECREF(tail); - return NULL; - } + ) { + PyErr_SetString(PyExc_ImportError, + "Import by filename is not supported."); + return NULL; + } + + parent = get_parent(globals, buf, &buflen, level); + if (parent == NULL) + return NULL; + + head = load_next(parent, Py_None, &name, buf, &buflen); + if (head == NULL) + return NULL; + + tail = head; + Py_INCREF(tail); + while (name) { + next = load_next(tail, tail, &name, buf, &buflen); + Py_DECREF(tail); + if (next == NULL) { + Py_DECREF(head); + return NULL; + } + tail = next; + } + if (tail == Py_None) { + /* If tail is Py_None, both get_parent and load_next found + an empty module name: someone called __import__("") or + doctored faulty bytecode */ + Py_DECREF(tail); + Py_DECREF(head); + PyErr_SetString(PyExc_ValueError, + "Empty module name"); + return NULL; + } + + if (fromlist != NULL) { + if (fromlist == Py_None || !PyObject_IsTrue(fromlist)) + fromlist = NULL; + } + + if (fromlist == NULL) { + Py_DECREF(tail); + return head; + } + + Py_DECREF(head); + if (!ensure_fromlist(tail, fromlist, buf, buflen, 0)) { + Py_DECREF(tail); + return NULL; + } - return tail; + return tail; } PyObject * PyImport_ImportModuleLevel(char *name, PyObject *globals, PyObject *locals, - PyObject *fromlist, int level) + PyObject *fromlist, int level) { - PyObject *result; - _PyImport_AcquireLock(); - result = import_module_level(name, globals, locals, fromlist, level); - if (_PyImport_ReleaseLock() < 0) { - Py_XDECREF(result); - PyErr_SetString(PyExc_RuntimeError, - "not holding the import lock"); - return NULL; - } - return result; + PyObject *result; + _PyImport_AcquireLock(); + result = import_module_level(name, globals, locals, fromlist, level); + if (_PyImport_ReleaseLock() < 0) { + Py_XDECREF(result); + PyErr_SetString(PyExc_RuntimeError, + "not holding the import lock"); + return NULL; + } + return result; } /* Return the package that an import is being performed in. If globals comes @@ -2461,420 +2461,420 @@ static PyObject * get_parent(PyObject *globals, char *buf, Py_ssize_t *p_buflen, int level) { - static PyObject *namestr = NULL; - static PyObject *pathstr = NULL; - static PyObject *pkgstr = NULL; - PyObject *pkgname, *modname, *modpath, *modules, *parent; - int orig_level = level; - - if (globals == NULL || !PyDict_Check(globals) || !level) - return Py_None; - - if (namestr == NULL) { - namestr = PyUnicode_InternFromString("__name__"); - if (namestr == NULL) - return NULL; - } - if (pathstr == NULL) { - pathstr = PyUnicode_InternFromString("__path__"); - if (pathstr == NULL) - return NULL; - } - if (pkgstr == NULL) { - pkgstr = PyUnicode_InternFromString("__package__"); - if (pkgstr == NULL) - return NULL; - } - - *buf = '\0'; - *p_buflen = 0; - pkgname = PyDict_GetItem(globals, pkgstr); - - if ((pkgname != NULL) && (pkgname != Py_None)) { - /* __package__ is set, so use it */ - char *pkgname_str; - Py_ssize_t len; - - if (!PyUnicode_Check(pkgname)) { - PyErr_SetString(PyExc_ValueError, - "__package__ set to non-string"); - return NULL; - } - pkgname_str = _PyUnicode_AsStringAndSize(pkgname, &len); - if (len == 0) { - if (level > 0) { - PyErr_SetString(PyExc_ValueError, - "Attempted relative import in non-package"); - return NULL; - } - return Py_None; - } - if (len > MAXPATHLEN) { - PyErr_SetString(PyExc_ValueError, - "Package name too long"); - return NULL; - } - strcpy(buf, pkgname_str); - } else { - /* __package__ not set, so figure it out and set it */ - modname = PyDict_GetItem(globals, namestr); - if (modname == NULL || !PyUnicode_Check(modname)) - return Py_None; - - modpath = PyDict_GetItem(globals, pathstr); - if (modpath != NULL) { - /* __path__ is set, so modname is already the package name */ - char *modname_str; - Py_ssize_t len; - int error; - - modname_str = _PyUnicode_AsStringAndSize(modname, &len); - if (len > MAXPATHLEN) { - PyErr_SetString(PyExc_ValueError, - "Module name too long"); - return NULL; - } - strcpy(buf, modname_str); - error = PyDict_SetItem(globals, pkgstr, modname); - if (error) { - PyErr_SetString(PyExc_ValueError, - "Could not set __package__"); - return NULL; - } - } else { - /* Normal module, so work out the package name if any */ - char *start = _PyUnicode_AsString(modname); - char *lastdot = strrchr(start, '.'); - size_t len; - int error; - if (lastdot == NULL && level > 0) { - PyErr_SetString(PyExc_ValueError, - "Attempted relative import in non-package"); - return NULL; - } - if (lastdot == NULL) { - error = PyDict_SetItem(globals, pkgstr, Py_None); - if (error) { - PyErr_SetString(PyExc_ValueError, - "Could not set __package__"); - return NULL; - } - return Py_None; - } - len = lastdot - start; - if (len >= MAXPATHLEN) { - PyErr_SetString(PyExc_ValueError, - "Module name too long"); - return NULL; - } - strncpy(buf, start, len); - buf[len] = '\0'; - pkgname = PyUnicode_FromString(buf); - if (pkgname == NULL) { - return NULL; - } - error = PyDict_SetItem(globals, pkgstr, pkgname); - Py_DECREF(pkgname); - if (error) { - PyErr_SetString(PyExc_ValueError, - "Could not set __package__"); - return NULL; - } - } - } - while (--level > 0) { - char *dot = strrchr(buf, '.'); - if (dot == NULL) { - PyErr_SetString(PyExc_ValueError, - "Attempted relative import beyond " - "toplevel package"); - return NULL; - } - *dot = '\0'; - } - *p_buflen = strlen(buf); - - modules = PyImport_GetModuleDict(); - parent = PyDict_GetItemString(modules, buf); - if (parent == NULL) { - if (orig_level < 1) { - PyObject *err_msg = PyBytes_FromFormat( - "Parent module '%.200s' not found " - "while handling absolute import", buf); - if (err_msg == NULL) { - return NULL; - } - if (!PyErr_WarnEx(PyExc_RuntimeWarning, - PyBytes_AsString(err_msg), 1)) { - *buf = '\0'; - *p_buflen = 0; - parent = Py_None; - } - Py_DECREF(err_msg); - } else { - PyErr_Format(PyExc_SystemError, - "Parent module '%.200s' not loaded, " - "cannot perform relative import", buf); - } - } - return parent; - /* We expect, but can't guarantee, if parent != None, that: - - parent.__name__ == buf - - parent.__dict__ is globals - If this is violated... Who cares? */ + static PyObject *namestr = NULL; + static PyObject *pathstr = NULL; + static PyObject *pkgstr = NULL; + PyObject *pkgname, *modname, *modpath, *modules, *parent; + int orig_level = level; + + if (globals == NULL || !PyDict_Check(globals) || !level) + return Py_None; + + if (namestr == NULL) { + namestr = PyUnicode_InternFromString("__name__"); + if (namestr == NULL) + return NULL; + } + if (pathstr == NULL) { + pathstr = PyUnicode_InternFromString("__path__"); + if (pathstr == NULL) + return NULL; + } + if (pkgstr == NULL) { + pkgstr = PyUnicode_InternFromString("__package__"); + if (pkgstr == NULL) + return NULL; + } + + *buf = '\0'; + *p_buflen = 0; + pkgname = PyDict_GetItem(globals, pkgstr); + + if ((pkgname != NULL) && (pkgname != Py_None)) { + /* __package__ is set, so use it */ + char *pkgname_str; + Py_ssize_t len; + + if (!PyUnicode_Check(pkgname)) { + PyErr_SetString(PyExc_ValueError, + "__package__ set to non-string"); + return NULL; + } + pkgname_str = _PyUnicode_AsStringAndSize(pkgname, &len); + if (len == 0) { + if (level > 0) { + PyErr_SetString(PyExc_ValueError, + "Attempted relative import in non-package"); + return NULL; + } + return Py_None; + } + if (len > MAXPATHLEN) { + PyErr_SetString(PyExc_ValueError, + "Package name too long"); + return NULL; + } + strcpy(buf, pkgname_str); + } else { + /* __package__ not set, so figure it out and set it */ + modname = PyDict_GetItem(globals, namestr); + if (modname == NULL || !PyUnicode_Check(modname)) + return Py_None; + + modpath = PyDict_GetItem(globals, pathstr); + if (modpath != NULL) { + /* __path__ is set, so modname is already the package name */ + char *modname_str; + Py_ssize_t len; + int error; + + modname_str = _PyUnicode_AsStringAndSize(modname, &len); + if (len > MAXPATHLEN) { + PyErr_SetString(PyExc_ValueError, + "Module name too long"); + return NULL; + } + strcpy(buf, modname_str); + error = PyDict_SetItem(globals, pkgstr, modname); + if (error) { + PyErr_SetString(PyExc_ValueError, + "Could not set __package__"); + return NULL; + } + } else { + /* Normal module, so work out the package name if any */ + char *start = _PyUnicode_AsString(modname); + char *lastdot = strrchr(start, '.'); + size_t len; + int error; + if (lastdot == NULL && level > 0) { + PyErr_SetString(PyExc_ValueError, + "Attempted relative import in non-package"); + return NULL; + } + if (lastdot == NULL) { + error = PyDict_SetItem(globals, pkgstr, Py_None); + if (error) { + PyErr_SetString(PyExc_ValueError, + "Could not set __package__"); + return NULL; + } + return Py_None; + } + len = lastdot - start; + if (len >= MAXPATHLEN) { + PyErr_SetString(PyExc_ValueError, + "Module name too long"); + return NULL; + } + strncpy(buf, start, len); + buf[len] = '\0'; + pkgname = PyUnicode_FromString(buf); + if (pkgname == NULL) { + return NULL; + } + error = PyDict_SetItem(globals, pkgstr, pkgname); + Py_DECREF(pkgname); + if (error) { + PyErr_SetString(PyExc_ValueError, + "Could not set __package__"); + return NULL; + } + } + } + while (--level > 0) { + char *dot = strrchr(buf, '.'); + if (dot == NULL) { + PyErr_SetString(PyExc_ValueError, + "Attempted relative import beyond " + "toplevel package"); + return NULL; + } + *dot = '\0'; + } + *p_buflen = strlen(buf); + + modules = PyImport_GetModuleDict(); + parent = PyDict_GetItemString(modules, buf); + if (parent == NULL) { + if (orig_level < 1) { + PyObject *err_msg = PyBytes_FromFormat( + "Parent module '%.200s' not found " + "while handling absolute import", buf); + if (err_msg == NULL) { + return NULL; + } + if (!PyErr_WarnEx(PyExc_RuntimeWarning, + PyBytes_AsString(err_msg), 1)) { + *buf = '\0'; + *p_buflen = 0; + parent = Py_None; + } + Py_DECREF(err_msg); + } else { + PyErr_Format(PyExc_SystemError, + "Parent module '%.200s' not loaded, " + "cannot perform relative import", buf); + } + } + return parent; + /* We expect, but can't guarantee, if parent != None, that: + - parent.__name__ == buf + - parent.__dict__ is globals + If this is violated... Who cares? */ } /* altmod is either None or same as mod */ static PyObject * load_next(PyObject *mod, PyObject *altmod, char **p_name, char *buf, - Py_ssize_t *p_buflen) + Py_ssize_t *p_buflen) { - char *name = *p_name; - char *dot = strchr(name, '.'); - size_t len; - char *p; - PyObject *result; - - if (strlen(name) == 0) { - /* completely empty module name should only happen in - 'from . import' (or '__import__("")')*/ - Py_INCREF(mod); - *p_name = NULL; - return mod; - } - - if (dot == NULL) { - *p_name = NULL; - len = strlen(name); - } - else { - *p_name = dot+1; - len = dot-name; - } - if (len == 0) { - PyErr_SetString(PyExc_ValueError, - "Empty module name"); - return NULL; - } - - p = buf + *p_buflen; - if (p != buf) - *p++ = '.'; - if (p+len-buf >= MAXPATHLEN) { - PyErr_SetString(PyExc_ValueError, - "Module name too long"); - return NULL; - } - strncpy(p, name, len); - p[len] = '\0'; - *p_buflen = p+len-buf; - - result = import_submodule(mod, p, buf); - if (result == Py_None && altmod != mod) { - Py_DECREF(result); - /* Here, altmod must be None and mod must not be None */ - result = import_submodule(altmod, p, p); - if (result != NULL && result != Py_None) { - if (mark_miss(buf) != 0) { - Py_DECREF(result); - return NULL; - } - strncpy(buf, name, len); - buf[len] = '\0'; - *p_buflen = len; - } - } - if (result == NULL) - return NULL; - - if (result == Py_None) { - Py_DECREF(result); - PyErr_Format(PyExc_ImportError, - "No module named %.200s", name); - return NULL; - } + char *name = *p_name; + char *dot = strchr(name, '.'); + size_t len; + char *p; + PyObject *result; + + if (strlen(name) == 0) { + /* completely empty module name should only happen in + 'from . import' (or '__import__("")')*/ + Py_INCREF(mod); + *p_name = NULL; + return mod; + } + + if (dot == NULL) { + *p_name = NULL; + len = strlen(name); + } + else { + *p_name = dot+1; + len = dot-name; + } + if (len == 0) { + PyErr_SetString(PyExc_ValueError, + "Empty module name"); + return NULL; + } + + p = buf + *p_buflen; + if (p != buf) + *p++ = '.'; + if (p+len-buf >= MAXPATHLEN) { + PyErr_SetString(PyExc_ValueError, + "Module name too long"); + return NULL; + } + strncpy(p, name, len); + p[len] = '\0'; + *p_buflen = p+len-buf; + + result = import_submodule(mod, p, buf); + if (result == Py_None && altmod != mod) { + Py_DECREF(result); + /* Here, altmod must be None and mod must not be None */ + result = import_submodule(altmod, p, p); + if (result != NULL && result != Py_None) { + if (mark_miss(buf) != 0) { + Py_DECREF(result); + return NULL; + } + strncpy(buf, name, len); + buf[len] = '\0'; + *p_buflen = len; + } + } + if (result == NULL) + return NULL; + + if (result == Py_None) { + Py_DECREF(result); + PyErr_Format(PyExc_ImportError, + "No module named %.200s", name); + return NULL; + } - return result; + return result; } static int mark_miss(char *name) { - PyObject *modules = PyImport_GetModuleDict(); - return PyDict_SetItemString(modules, name, Py_None); + PyObject *modules = PyImport_GetModuleDict(); + return PyDict_SetItemString(modules, name, Py_None); } static int ensure_fromlist(PyObject *mod, PyObject *fromlist, char *buf, Py_ssize_t buflen, - int recursive) + int recursive) { - int i; + int i; - if (!PyObject_HasAttrString(mod, "__path__")) - return 1; + if (!PyObject_HasAttrString(mod, "__path__")) + return 1; - for (i = 0; ; i++) { - PyObject *item = PySequence_GetItem(fromlist, i); - int hasit; - if (item == NULL) { - if (PyErr_ExceptionMatches(PyExc_IndexError)) { - PyErr_Clear(); - return 1; - } - return 0; - } - if (!PyUnicode_Check(item)) { - PyErr_SetString(PyExc_TypeError, - "Item in ``from list'' not a string"); - Py_DECREF(item); - return 0; - } - if (PyUnicode_AS_UNICODE(item)[0] == '*') { - PyObject *all; - Py_DECREF(item); - /* See if the package defines __all__ */ - if (recursive) - continue; /* Avoid endless recursion */ - all = PyObject_GetAttrString(mod, "__all__"); - if (all == NULL) - PyErr_Clear(); - else { - int ret = ensure_fromlist(mod, all, buf, buflen, 1); - Py_DECREF(all); - if (!ret) - return 0; - } - continue; - } - hasit = PyObject_HasAttr(mod, item); - if (!hasit) { - PyObject *item8; - char *subname; - PyObject *submod; - char *p; - if (!Py_FileSystemDefaultEncoding) { - item8 = PyUnicode_EncodeASCII(PyUnicode_AsUnicode(item), - PyUnicode_GetSize(item), - NULL); - } else { - item8 = PyUnicode_AsEncodedString(item, - Py_FileSystemDefaultEncoding, NULL); - } - if (!item8) { - PyErr_SetString(PyExc_ValueError, "Cannot encode path item"); - return 0; - } - subname = PyBytes_AS_STRING(item8); - if (buflen + strlen(subname) >= MAXPATHLEN) { - PyErr_SetString(PyExc_ValueError, - "Module name too long"); - Py_DECREF(item); - return 0; - } - p = buf + buflen; - *p++ = '.'; - strcpy(p, subname); - submod = import_submodule(mod, subname, buf); - Py_DECREF(item8); - Py_XDECREF(submod); - if (submod == NULL) { - Py_DECREF(item); - return 0; - } - } - Py_DECREF(item); - } + for (i = 0; ; i++) { + PyObject *item = PySequence_GetItem(fromlist, i); + int hasit; + if (item == NULL) { + if (PyErr_ExceptionMatches(PyExc_IndexError)) { + PyErr_Clear(); + return 1; + } + return 0; + } + if (!PyUnicode_Check(item)) { + PyErr_SetString(PyExc_TypeError, + "Item in ``from list'' not a string"); + Py_DECREF(item); + return 0; + } + if (PyUnicode_AS_UNICODE(item)[0] == '*') { + PyObject *all; + Py_DECREF(item); + /* See if the package defines __all__ */ + if (recursive) + continue; /* Avoid endless recursion */ + all = PyObject_GetAttrString(mod, "__all__"); + if (all == NULL) + PyErr_Clear(); + else { + int ret = ensure_fromlist(mod, all, buf, buflen, 1); + Py_DECREF(all); + if (!ret) + return 0; + } + continue; + } + hasit = PyObject_HasAttr(mod, item); + if (!hasit) { + PyObject *item8; + char *subname; + PyObject *submod; + char *p; + if (!Py_FileSystemDefaultEncoding) { + item8 = PyUnicode_EncodeASCII(PyUnicode_AsUnicode(item), + PyUnicode_GetSize(item), + NULL); + } else { + item8 = PyUnicode_AsEncodedString(item, + Py_FileSystemDefaultEncoding, NULL); + } + if (!item8) { + PyErr_SetString(PyExc_ValueError, "Cannot encode path item"); + return 0; + } + subname = PyBytes_AS_STRING(item8); + if (buflen + strlen(subname) >= MAXPATHLEN) { + PyErr_SetString(PyExc_ValueError, + "Module name too long"); + Py_DECREF(item); + return 0; + } + p = buf + buflen; + *p++ = '.'; + strcpy(p, subname); + submod = import_submodule(mod, subname, buf); + Py_DECREF(item8); + Py_XDECREF(submod); + if (submod == NULL) { + Py_DECREF(item); + return 0; + } + } + Py_DECREF(item); + } - /* NOTREACHED */ + /* NOTREACHED */ } static int add_submodule(PyObject *mod, PyObject *submod, char *fullname, char *subname, - PyObject *modules) + PyObject *modules) { - if (mod == Py_None) - return 1; - /* Irrespective of the success of this load, make a - reference to it in the parent package module. A copy gets - saved in the modules dictionary under the full name, so get a - reference from there, if need be. (The exception is when the - load failed with a SyntaxError -- then there's no trace in - sys.modules. In that case, of course, do nothing extra.) */ - if (submod == NULL) { - submod = PyDict_GetItemString(modules, fullname); - if (submod == NULL) - return 1; - } - if (PyModule_Check(mod)) { - /* We can't use setattr here since it can give a - * spurious warning if the submodule name shadows a - * builtin name */ - PyObject *dict = PyModule_GetDict(mod); - if (!dict) - return 0; - if (PyDict_SetItemString(dict, subname, submod) < 0) - return 0; - } - else { - if (PyObject_SetAttrString(mod, subname, submod) < 0) - return 0; - } - return 1; + if (mod == Py_None) + return 1; + /* Irrespective of the success of this load, make a + reference to it in the parent package module. A copy gets + saved in the modules dictionary under the full name, so get a + reference from there, if need be. (The exception is when the + load failed with a SyntaxError -- then there's no trace in + sys.modules. In that case, of course, do nothing extra.) */ + if (submod == NULL) { + submod = PyDict_GetItemString(modules, fullname); + if (submod == NULL) + return 1; + } + if (PyModule_Check(mod)) { + /* We can't use setattr here since it can give a + * spurious warning if the submodule name shadows a + * builtin name */ + PyObject *dict = PyModule_GetDict(mod); + if (!dict) + return 0; + if (PyDict_SetItemString(dict, subname, submod) < 0) + return 0; + } + else { + if (PyObject_SetAttrString(mod, subname, submod) < 0) + return 0; + } + return 1; } static PyObject * import_submodule(PyObject *mod, char *subname, char *fullname) { - PyObject *modules = PyImport_GetModuleDict(); - PyObject *m = NULL; + PyObject *modules = PyImport_GetModuleDict(); + PyObject *m = NULL; - /* Require: - if mod == None: subname == fullname - else: mod.__name__ + "." + subname == fullname - */ - - if ((m = PyDict_GetItemString(modules, fullname)) != NULL) { - Py_INCREF(m); - } - else { - PyObject *path, *loader = NULL; - char buf[MAXPATHLEN+1]; - struct filedescr *fdp; - FILE *fp = NULL; - - if (mod == Py_None) - path = NULL; - else { - path = PyObject_GetAttrString(mod, "__path__"); - if (path == NULL) { - PyErr_Clear(); - Py_INCREF(Py_None); - return Py_None; - } - } - - buf[0] = '\0'; - fdp = find_module(fullname, subname, path, buf, MAXPATHLEN+1, - &fp, &loader); - Py_XDECREF(path); - if (fdp == NULL) { - if (!PyErr_ExceptionMatches(PyExc_ImportError)) - return NULL; - PyErr_Clear(); - Py_INCREF(Py_None); - return Py_None; - } - m = load_module(fullname, fp, buf, fdp->type, loader); - Py_XDECREF(loader); - if (fp) - fclose(fp); - if (!add_submodule(mod, m, fullname, subname, modules)) { - Py_XDECREF(m); - m = NULL; - } - } + /* Require: + if mod == None: subname == fullname + else: mod.__name__ + "." + subname == fullname + */ + + if ((m = PyDict_GetItemString(modules, fullname)) != NULL) { + Py_INCREF(m); + } + else { + PyObject *path, *loader = NULL; + char buf[MAXPATHLEN+1]; + struct filedescr *fdp; + FILE *fp = NULL; + + if (mod == Py_None) + path = NULL; + else { + path = PyObject_GetAttrString(mod, "__path__"); + if (path == NULL) { + PyErr_Clear(); + Py_INCREF(Py_None); + return Py_None; + } + } + + buf[0] = '\0'; + fdp = find_module(fullname, subname, path, buf, MAXPATHLEN+1, + &fp, &loader); + Py_XDECREF(path); + if (fdp == NULL) { + if (!PyErr_ExceptionMatches(PyExc_ImportError)) + return NULL; + PyErr_Clear(); + Py_INCREF(Py_None); + return Py_None; + } + m = load_module(fullname, fp, buf, fdp->type, loader); + Py_XDECREF(loader); + if (fp) + fclose(fp); + if (!add_submodule(mod, m, fullname, subname, modules)) { + Py_XDECREF(m); + m = NULL; + } + } - return m; + return m; } @@ -2884,96 +2884,96 @@ PyObject * PyImport_ReloadModule(PyObject *m) { - PyInterpreterState *interp = PyThreadState_Get()->interp; - PyObject *modules_reloading = interp->modules_reloading; - PyObject *modules = PyImport_GetModuleDict(); - PyObject *path = NULL, *loader = NULL, *existing_m = NULL; - char *name, *subname; - char buf[MAXPATHLEN+1]; - struct filedescr *fdp; - FILE *fp = NULL; - PyObject *newm; - - if (modules_reloading == NULL) { - Py_FatalError("PyImport_ReloadModule: " - "no modules_reloading dictionary!"); - return NULL; - } - - if (m == NULL || !PyModule_Check(m)) { - PyErr_SetString(PyExc_TypeError, - "reload() argument must be module"); - return NULL; - } - name = (char*)PyModule_GetName(m); - if (name == NULL) - return NULL; - if (m != PyDict_GetItemString(modules, name)) { - PyErr_Format(PyExc_ImportError, - "reload(): module %.200s not in sys.modules", - name); - return NULL; - } - existing_m = PyDict_GetItemString(modules_reloading, name); - if (existing_m != NULL) { - /* Due to a recursive reload, this module is already - being reloaded. */ - Py_INCREF(existing_m); - return existing_m; - } - if (PyDict_SetItemString(modules_reloading, name, m) < 0) - return NULL; - - subname = strrchr(name, '.'); - if (subname == NULL) - subname = name; - else { - PyObject *parentname, *parent; - parentname = PyUnicode_FromStringAndSize(name, (subname-name)); - if (parentname == NULL) { - imp_modules_reloading_clear(); - return NULL; - } - parent = PyDict_GetItem(modules, parentname); - if (parent == NULL) { - PyErr_Format(PyExc_ImportError, - "reload(): parent %U not in sys.modules", - parentname); - Py_DECREF(parentname); - imp_modules_reloading_clear(); - return NULL; - } - Py_DECREF(parentname); - subname++; - path = PyObject_GetAttrString(parent, "__path__"); - if (path == NULL) - PyErr_Clear(); - } - buf[0] = '\0'; - fdp = find_module(name, subname, path, buf, MAXPATHLEN+1, &fp, &loader); - Py_XDECREF(path); - - if (fdp == NULL) { - Py_XDECREF(loader); - imp_modules_reloading_clear(); - return NULL; - } - - newm = load_module(name, fp, buf, fdp->type, loader); - Py_XDECREF(loader); - - if (fp) - fclose(fp); - if (newm == NULL) { - /* load_module probably removed name from modules because of - * the error. Put back the original module object. We're - * going to return NULL in this case regardless of whether - * replacing name succeeds, so the return value is ignored. - */ - PyDict_SetItemString(modules, name, m); - } - imp_modules_reloading_clear(); - return newm; + PyInterpreterState *interp = PyThreadState_Get()->interp; + PyObject *modules_reloading = interp->modules_reloading; + PyObject *modules = PyImport_GetModuleDict(); + PyObject *path = NULL, *loader = NULL, *existing_m = NULL; + char *name, *subname; + char buf[MAXPATHLEN+1]; + struct filedescr *fdp; + FILE *fp = NULL; + PyObject *newm; + + if (modules_reloading == NULL) { + Py_FatalError("PyImport_ReloadModule: " + "no modules_reloading dictionary!"); + return NULL; + } + + if (m == NULL || !PyModule_Check(m)) { + PyErr_SetString(PyExc_TypeError, + "reload() argument must be module"); + return NULL; + } + name = (char*)PyModule_GetName(m); + if (name == NULL) + return NULL; + if (m != PyDict_GetItemString(modules, name)) { + PyErr_Format(PyExc_ImportError, + "reload(): module %.200s not in sys.modules", + name); + return NULL; + } + existing_m = PyDict_GetItemString(modules_reloading, name); + if (existing_m != NULL) { + /* Due to a recursive reload, this module is already + being reloaded. */ + Py_INCREF(existing_m); + return existing_m; + } + if (PyDict_SetItemString(modules_reloading, name, m) < 0) + return NULL; + + subname = strrchr(name, '.'); + if (subname == NULL) + subname = name; + else { + PyObject *parentname, *parent; + parentname = PyUnicode_FromStringAndSize(name, (subname-name)); + if (parentname == NULL) { + imp_modules_reloading_clear(); + return NULL; + } + parent = PyDict_GetItem(modules, parentname); + if (parent == NULL) { + PyErr_Format(PyExc_ImportError, + "reload(): parent %U not in sys.modules", + parentname); + Py_DECREF(parentname); + imp_modules_reloading_clear(); + return NULL; + } + Py_DECREF(parentname); + subname++; + path = PyObject_GetAttrString(parent, "__path__"); + if (path == NULL) + PyErr_Clear(); + } + buf[0] = '\0'; + fdp = find_module(name, subname, path, buf, MAXPATHLEN+1, &fp, &loader); + Py_XDECREF(path); + + if (fdp == NULL) { + Py_XDECREF(loader); + imp_modules_reloading_clear(); + return NULL; + } + + newm = load_module(name, fp, buf, fdp->type, loader); + Py_XDECREF(loader); + + if (fp) + fclose(fp); + if (newm == NULL) { + /* load_module probably removed name from modules because of + * the error. Put back the original module object. We're + * going to return NULL in this case regardless of whether + * replacing name succeeds, so the return value is ignored. + */ + PyDict_SetItemString(modules, name, m); + } + imp_modules_reloading_clear(); + return newm; } @@ -2989,68 +2989,68 @@ PyObject * PyImport_Import(PyObject *module_name) { - static PyObject *silly_list = NULL; - static PyObject *builtins_str = NULL; - static PyObject *import_str = NULL; - PyObject *globals = NULL; - PyObject *import = NULL; - PyObject *builtins = NULL; - PyObject *r = NULL; - - /* Initialize constant string objects */ - if (silly_list == NULL) { - import_str = PyUnicode_InternFromString("__import__"); - if (import_str == NULL) - return NULL; - builtins_str = PyUnicode_InternFromString("__builtins__"); - if (builtins_str == NULL) - return NULL; - silly_list = Py_BuildValue("[s]", "__doc__"); - if (silly_list == NULL) - return NULL; - } - - /* Get the builtins from current globals */ - globals = PyEval_GetGlobals(); - if (globals != NULL) { - Py_INCREF(globals); - builtins = PyObject_GetItem(globals, builtins_str); - if (builtins == NULL) - goto err; - } - else { - /* No globals -- use standard builtins, and fake globals */ - builtins = PyImport_ImportModuleLevel("builtins", - NULL, NULL, NULL, 0); - if (builtins == NULL) - return NULL; - globals = Py_BuildValue("{OO}", builtins_str, builtins); - if (globals == NULL) - goto err; - } - - /* Get the __import__ function from the builtins */ - if (PyDict_Check(builtins)) { - import = PyObject_GetItem(builtins, import_str); - if (import == NULL) - PyErr_SetObject(PyExc_KeyError, import_str); - } - else - import = PyObject_GetAttr(builtins, import_str); - if (import == NULL) - goto err; - - /* Call the __import__ function with the proper argument list - * Always use absolute import here. */ - r = PyObject_CallFunction(import, "OOOOi", module_name, globals, - globals, silly_list, 0, NULL); + static PyObject *silly_list = NULL; + static PyObject *builtins_str = NULL; + static PyObject *import_str = NULL; + PyObject *globals = NULL; + PyObject *import = NULL; + PyObject *builtins = NULL; + PyObject *r = NULL; + + /* Initialize constant string objects */ + if (silly_list == NULL) { + import_str = PyUnicode_InternFromString("__import__"); + if (import_str == NULL) + return NULL; + builtins_str = PyUnicode_InternFromString("__builtins__"); + if (builtins_str == NULL) + return NULL; + silly_list = Py_BuildValue("[s]", "__doc__"); + if (silly_list == NULL) + return NULL; + } + + /* Get the builtins from current globals */ + globals = PyEval_GetGlobals(); + if (globals != NULL) { + Py_INCREF(globals); + builtins = PyObject_GetItem(globals, builtins_str); + if (builtins == NULL) + goto err; + } + else { + /* No globals -- use standard builtins, and fake globals */ + builtins = PyImport_ImportModuleLevel("builtins", + NULL, NULL, NULL, 0); + if (builtins == NULL) + return NULL; + globals = Py_BuildValue("{OO}", builtins_str, builtins); + if (globals == NULL) + goto err; + } + + /* Get the __import__ function from the builtins */ + if (PyDict_Check(builtins)) { + import = PyObject_GetItem(builtins, import_str); + if (import == NULL) + PyErr_SetObject(PyExc_KeyError, import_str); + } + else + import = PyObject_GetAttr(builtins, import_str); + if (import == NULL) + goto err; + + /* Call the __import__ function with the proper argument list + * Always use absolute import here. */ + r = PyObject_CallFunction(import, "OOOOi", module_name, globals, + globals, silly_list, 0, NULL); err: - Py_XDECREF(globals); - Py_XDECREF(builtins); - Py_XDECREF(import); + Py_XDECREF(globals); + Py_XDECREF(builtins); + Py_XDECREF(import); - return r; + return r; } @@ -3061,257 +3061,257 @@ static PyObject * imp_make_magic(long magic) { - char buf[4]; + char buf[4]; - buf[0] = (char) ((magic >> 0) & 0xff); - buf[1] = (char) ((magic >> 8) & 0xff); - buf[2] = (char) ((magic >> 16) & 0xff); - buf[3] = (char) ((magic >> 24) & 0xff); + buf[0] = (char) ((magic >> 0) & 0xff); + buf[1] = (char) ((magic >> 8) & 0xff); + buf[2] = (char) ((magic >> 16) & 0xff); + buf[3] = (char) ((magic >> 24) & 0xff); - return PyBytes_FromStringAndSize(buf, 4); -}; + return PyBytes_FromStringAndSize(buf, 4); +}; static PyObject * imp_get_magic(PyObject *self, PyObject *noargs) { - return imp_make_magic(pyc_magic); + return imp_make_magic(pyc_magic); } static PyObject * imp_get_tag(PyObject *self, PyObject *noargs) { - return PyUnicode_FromString(pyc_tag); + return PyUnicode_FromString(pyc_tag); } static PyObject * imp_get_suffixes(PyObject *self, PyObject *noargs) { - PyObject *list; - struct filedescr *fdp; + PyObject *list; + struct filedescr *fdp; - list = PyList_New(0); - if (list == NULL) - return NULL; - for (fdp = _PyImport_Filetab; fdp->suffix != NULL; fdp++) { - PyObject *item = Py_BuildValue("ssi", - fdp->suffix, fdp->mode, fdp->type); - if (item == NULL) { - Py_DECREF(list); - return NULL; - } - if (PyList_Append(list, item) < 0) { - Py_DECREF(list); - Py_DECREF(item); - return NULL; - } - Py_DECREF(item); - } - return list; + list = PyList_New(0); + if (list == NULL) + return NULL; + for (fdp = _PyImport_Filetab; fdp->suffix != NULL; fdp++) { + PyObject *item = Py_BuildValue("ssi", + fdp->suffix, fdp->mode, fdp->type); + if (item == NULL) { + Py_DECREF(list); + return NULL; + } + if (PyList_Append(list, item) < 0) { + Py_DECREF(list); + Py_DECREF(item); + return NULL; + } + Py_DECREF(item); + } + return list; } static PyObject * call_find_module(char *name, PyObject *path) { - extern int fclose(FILE *); - PyObject *fob, *ret; - PyObject *pathobj; - struct filedescr *fdp; - char pathname[MAXPATHLEN+1]; - FILE *fp = NULL; - int fd = -1; - char *found_encoding = NULL; - char *encoding = NULL; - - pathname[0] = '\0'; - if (path == Py_None) - path = NULL; - fdp = find_module(NULL, name, path, pathname, MAXPATHLEN+1, &fp, NULL); - if (fdp == NULL) - return NULL; - if (fp != NULL) { - fd = fileno(fp); - if (fd != -1) - fd = dup(fd); - fclose(fp); - fp = NULL; - } - if (fd != -1) { - if (strchr(fdp->mode, 'b') == NULL) { - /* PyTokenizer_FindEncoding() returns PyMem_MALLOC'ed - memory. */ - found_encoding = PyTokenizer_FindEncoding(fd); - lseek(fd, 0, 0); /* Reset position */ - if (found_encoding == NULL && PyErr_Occurred()) - return NULL; - encoding = (found_encoding != NULL) ? found_encoding : - (char*)PyUnicode_GetDefaultEncoding(); - } - fob = PyFile_FromFd(fd, pathname, fdp->mode, -1, - (char*)encoding, NULL, NULL, 1); - if (fob == NULL) { - close(fd); - PyMem_FREE(found_encoding); - return NULL; - } - } - else { - fob = Py_None; - Py_INCREF(fob); - } - pathobj = PyUnicode_DecodeFSDefault(pathname); - ret = Py_BuildValue("NN(ssi)", - fob, pathobj, fdp->suffix, fdp->mode, fdp->type); - PyMem_FREE(found_encoding); + extern int fclose(FILE *); + PyObject *fob, *ret; + PyObject *pathobj; + struct filedescr *fdp; + char pathname[MAXPATHLEN+1]; + FILE *fp = NULL; + int fd = -1; + char *found_encoding = NULL; + char *encoding = NULL; + + pathname[0] = '\0'; + if (path == Py_None) + path = NULL; + fdp = find_module(NULL, name, path, pathname, MAXPATHLEN+1, &fp, NULL); + if (fdp == NULL) + return NULL; + if (fp != NULL) { + fd = fileno(fp); + if (fd != -1) + fd = dup(fd); + fclose(fp); + fp = NULL; + } + if (fd != -1) { + if (strchr(fdp->mode, 'b') == NULL) { + /* PyTokenizer_FindEncoding() returns PyMem_MALLOC'ed + memory. */ + found_encoding = PyTokenizer_FindEncoding(fd); + lseek(fd, 0, 0); /* Reset position */ + if (found_encoding == NULL && PyErr_Occurred()) + return NULL; + encoding = (found_encoding != NULL) ? found_encoding : + (char*)PyUnicode_GetDefaultEncoding(); + } + fob = PyFile_FromFd(fd, pathname, fdp->mode, -1, + (char*)encoding, NULL, NULL, 1); + if (fob == NULL) { + close(fd); + PyMem_FREE(found_encoding); + return NULL; + } + } + else { + fob = Py_None; + Py_INCREF(fob); + } + pathobj = PyUnicode_DecodeFSDefault(pathname); + ret = Py_BuildValue("NN(ssi)", + fob, pathobj, fdp->suffix, fdp->mode, fdp->type); + PyMem_FREE(found_encoding); - return ret; + return ret; } static PyObject * imp_find_module(PyObject *self, PyObject *args) { - char *name; - PyObject *ret, *path = NULL; - if (!PyArg_ParseTuple(args, "es|O:find_module", - Py_FileSystemDefaultEncoding, &name, - &path)) - return NULL; - ret = call_find_module(name, path); - PyMem_Free(name); - return ret; + char *name; + PyObject *ret, *path = NULL; + if (!PyArg_ParseTuple(args, "es|O:find_module", + Py_FileSystemDefaultEncoding, &name, + &path)) + return NULL; + ret = call_find_module(name, path); + PyMem_Free(name); + return ret; } static PyObject * imp_init_builtin(PyObject *self, PyObject *args) { - char *name; - int ret; - PyObject *m; - if (!PyArg_ParseTuple(args, "s:init_builtin", &name)) - return NULL; - ret = init_builtin(name); - if (ret < 0) - return NULL; - if (ret == 0) { - Py_INCREF(Py_None); - return Py_None; - } - m = PyImport_AddModule(name); - Py_XINCREF(m); - return m; + char *name; + int ret; + PyObject *m; + if (!PyArg_ParseTuple(args, "s:init_builtin", &name)) + return NULL; + ret = init_builtin(name); + if (ret < 0) + return NULL; + if (ret == 0) { + Py_INCREF(Py_None); + return Py_None; + } + m = PyImport_AddModule(name); + Py_XINCREF(m); + return m; } static PyObject * imp_init_frozen(PyObject *self, PyObject *args) { - char *name; - int ret; - PyObject *m; - if (!PyArg_ParseTuple(args, "s:init_frozen", &name)) - return NULL; - ret = PyImport_ImportFrozenModule(name); - if (ret < 0) - return NULL; - if (ret == 0) { - Py_INCREF(Py_None); - return Py_None; - } - m = PyImport_AddModule(name); - Py_XINCREF(m); - return m; + char *name; + int ret; + PyObject *m; + if (!PyArg_ParseTuple(args, "s:init_frozen", &name)) + return NULL; + ret = PyImport_ImportFrozenModule(name); + if (ret < 0) + return NULL; + if (ret == 0) { + Py_INCREF(Py_None); + return Py_None; + } + m = PyImport_AddModule(name); + Py_XINCREF(m); + return m; } static PyObject * imp_get_frozen_object(PyObject *self, PyObject *args) { - char *name; + char *name; - if (!PyArg_ParseTuple(args, "s:get_frozen_object", &name)) - return NULL; - return get_frozen_object(name); + if (!PyArg_ParseTuple(args, "s:get_frozen_object", &name)) + return NULL; + return get_frozen_object(name); } static PyObject * imp_is_frozen_package(PyObject *self, PyObject *args) { - char *name; + char *name; - if (!PyArg_ParseTuple(args, "s:is_frozen_package", &name)) - return NULL; - return is_frozen_package(name); + if (!PyArg_ParseTuple(args, "s:is_frozen_package", &name)) + return NULL; + return is_frozen_package(name); } static PyObject * imp_is_builtin(PyObject *self, PyObject *args) { - char *name; - if (!PyArg_ParseTuple(args, "s:is_builtin", &name)) - return NULL; - return PyLong_FromLong(is_builtin(name)); + char *name; + if (!PyArg_ParseTuple(args, "s:is_builtin", &name)) + return NULL; + return PyLong_FromLong(is_builtin(name)); } static PyObject * imp_is_frozen(PyObject *self, PyObject *args) { - char *name; - struct _frozen *p; - if (!PyArg_ParseTuple(args, "s:is_frozen", &name)) - return NULL; - p = find_frozen(name); - return PyBool_FromLong((long) (p == NULL ? 0 : p->size)); + char *name; + struct _frozen *p; + if (!PyArg_ParseTuple(args, "s:is_frozen", &name)) + return NULL; + p = find_frozen(name); + return PyBool_FromLong((long) (p == NULL ? 0 : p->size)); } static FILE * get_file(char *pathname, PyObject *fob, char *mode) { - FILE *fp; - if (mode[0] == 'U') - mode = "r" PY_STDIOTEXTMODE; - if (fob == NULL) { - fp = fopen(pathname, mode); - } - else { - int fd = PyObject_AsFileDescriptor(fob); - if (fd == -1) - return NULL; - if (!_PyVerify_fd(fd)) - goto error; - /* the FILE struct gets a new fd, so that it can be closed - * independently of the file descriptor given - */ - fd = dup(fd); - if (fd == -1) - goto error; - fp = fdopen(fd, mode); - } - if (fp) - return fp; + FILE *fp; + if (mode[0] == 'U') + mode = "r" PY_STDIOTEXTMODE; + if (fob == NULL) { + fp = fopen(pathname, mode); + } + else { + int fd = PyObject_AsFileDescriptor(fob); + if (fd == -1) + return NULL; + if (!_PyVerify_fd(fd)) + goto error; + /* the FILE struct gets a new fd, so that it can be closed + * independently of the file descriptor given + */ + fd = dup(fd); + if (fd == -1) + goto error; + fp = fdopen(fd, mode); + } + if (fp) + return fp; error: - PyErr_SetFromErrno(PyExc_IOError); - return NULL; + PyErr_SetFromErrno(PyExc_IOError); + return NULL; } static PyObject * imp_load_compiled(PyObject *self, PyObject *args) { - char *name; - char *pathname; - PyObject *fob = NULL; - PyObject *m; - FILE *fp; - if (!PyArg_ParseTuple(args, "ses|O:load_compiled", - &name, - Py_FileSystemDefaultEncoding, &pathname, - &fob)) - return NULL; - fp = get_file(pathname, fob, "rb"); - if (fp == NULL) { - PyMem_Free(pathname); - return NULL; - } - m = load_compiled_module(name, pathname, fp); - fclose(fp); - PyMem_Free(pathname); - return m; + char *name; + char *pathname; + PyObject *fob = NULL; + PyObject *m; + FILE *fp; + if (!PyArg_ParseTuple(args, "ses|O:load_compiled", + &name, + Py_FileSystemDefaultEncoding, &pathname, + &fob)) + return NULL; + fp = get_file(pathname, fob, "rb"); + if (fp == NULL) { + PyMem_Free(pathname); + return NULL; + } + m = load_compiled_module(name, pathname, fp); + fclose(fp); + PyMem_Free(pathname); + return m; } #ifdef HAVE_DYNAMIC_LOADING @@ -3319,28 +3319,28 @@ static PyObject * imp_load_dynamic(PyObject *self, PyObject *args) { - char *name; - char *pathname; - PyObject *fob = NULL; - PyObject *m; - FILE *fp = NULL; - if (!PyArg_ParseTuple(args, "ses|O:load_dynamic", - &name, - Py_FileSystemDefaultEncoding, &pathname, - &fob)) - return NULL; - if (fob) { - fp = get_file(pathname, fob, "r"); - if (fp == NULL) { - PyMem_Free(pathname); - return NULL; - } - } - m = _PyImport_LoadDynamicModule(name, pathname, fp); - PyMem_Free(pathname); - if (fp) - fclose(fp); - return m; + char *name; + char *pathname; + PyObject *fob = NULL; + PyObject *m; + FILE *fp = NULL; + if (!PyArg_ParseTuple(args, "ses|O:load_dynamic", + &name, + Py_FileSystemDefaultEncoding, &pathname, + &fob)) + return NULL; + if (fob) { + fp = get_file(pathname, fob, "r"); + if (fp == NULL) { + PyMem_Free(pathname); + return NULL; + } + } + m = _PyImport_LoadDynamicModule(name, pathname, fp); + PyMem_Free(pathname); + if (fp) + fclose(fp); + return m; } #endif /* HAVE_DYNAMIC_LOADING */ @@ -3348,99 +3348,99 @@ static PyObject * imp_load_source(PyObject *self, PyObject *args) { - char *name; - char *pathname; - PyObject *fob = NULL; - PyObject *m; - FILE *fp; - if (!PyArg_ParseTuple(args, "ses|O:load_source", - &name, - Py_FileSystemDefaultEncoding, &pathname, - &fob)) - return NULL; - fp = get_file(pathname, fob, "r"); - if (fp == NULL) { - PyMem_Free(pathname); - return NULL; - } - m = load_source_module(name, pathname, fp); - PyMem_Free(pathname); - fclose(fp); - return m; + char *name; + char *pathname; + PyObject *fob = NULL; + PyObject *m; + FILE *fp; + if (!PyArg_ParseTuple(args, "ses|O:load_source", + &name, + Py_FileSystemDefaultEncoding, &pathname, + &fob)) + return NULL; + fp = get_file(pathname, fob, "r"); + if (fp == NULL) { + PyMem_Free(pathname); + return NULL; + } + m = load_source_module(name, pathname, fp); + PyMem_Free(pathname); + fclose(fp); + return m; } static PyObject * imp_load_module(PyObject *self, PyObject *args) { - char *name; - PyObject *fob; - char *pathname; - PyObject * ret; - char *suffix; /* Unused */ - char *mode; - int type; - FILE *fp; - - if (!PyArg_ParseTuple(args, "sOes(ssi):load_module", - &name, &fob, - Py_FileSystemDefaultEncoding, &pathname, - &suffix, &mode, &type)) - return NULL; - if (*mode) { - /* Mode must start with 'r' or 'U' and must not contain '+'. - Implicit in this test is the assumption that the mode - may contain other modifiers like 'b' or 't'. */ - - if (!(*mode == 'r' || *mode == 'U') || strchr(mode, '+')) { - PyErr_Format(PyExc_ValueError, - "invalid file open mode %.200s", mode); - PyMem_Free(pathname); - return NULL; - } - } - if (fob == Py_None) - fp = NULL; - else { - fp = get_file(NULL, fob, mode); - if (fp == NULL) { - PyMem_Free(pathname); - return NULL; - } - } - ret = load_module(name, fp, pathname, type, NULL); - PyMem_Free(pathname); - if (fp) - fclose(fp); - return ret; + char *name; + PyObject *fob; + char *pathname; + PyObject * ret; + char *suffix; /* Unused */ + char *mode; + int type; + FILE *fp; + + if (!PyArg_ParseTuple(args, "sOes(ssi):load_module", + &name, &fob, + Py_FileSystemDefaultEncoding, &pathname, + &suffix, &mode, &type)) + return NULL; + if (*mode) { + /* Mode must start with 'r' or 'U' and must not contain '+'. + Implicit in this test is the assumption that the mode + may contain other modifiers like 'b' or 't'. */ + + if (!(*mode == 'r' || *mode == 'U') || strchr(mode, '+')) { + PyErr_Format(PyExc_ValueError, + "invalid file open mode %.200s", mode); + PyMem_Free(pathname); + return NULL; + } + } + if (fob == Py_None) + fp = NULL; + else { + fp = get_file(NULL, fob, mode); + if (fp == NULL) { + PyMem_Free(pathname); + return NULL; + } + } + ret = load_module(name, fp, pathname, type, NULL); + PyMem_Free(pathname); + if (fp) + fclose(fp); + return ret; } static PyObject * imp_load_package(PyObject *self, PyObject *args) { - char *name; - char *pathname; - PyObject * ret; - if (!PyArg_ParseTuple(args, "ses:load_package", - &name, Py_FileSystemDefaultEncoding, &pathname)) - return NULL; - ret = load_package(name, pathname); - PyMem_Free(pathname); - return ret; + char *name; + char *pathname; + PyObject * ret; + if (!PyArg_ParseTuple(args, "ses:load_package", + &name, Py_FileSystemDefaultEncoding, &pathname)) + return NULL; + ret = load_package(name, pathname); + PyMem_Free(pathname); + return ret; } static PyObject * imp_new_module(PyObject *self, PyObject *args) { - char *name; - if (!PyArg_ParseTuple(args, "s:new_module", &name)) - return NULL; - return PyModule_New(name); + char *name; + if (!PyArg_ParseTuple(args, "s:new_module", &name)) + return NULL; + return PyModule_New(name); } static PyObject * imp_reload(PyObject *self, PyObject *v) { - return PyImport_ReloadModule(v); + return PyImport_ReloadModule(v); } PyDoc_STRVAR(doc_reload, @@ -3451,30 +3451,30 @@ static PyObject * imp_cache_from_source(PyObject *self, PyObject *args, PyObject *kws) { - static char *kwlist[] = {"path", "debug_override", NULL}; + static char *kwlist[] = {"path", "debug_override", NULL}; - char buf[MAXPATHLEN+1]; - char *pathname, *cpathname; - PyObject *debug_override = Py_None; - int debug = !Py_OptimizeFlag; - - if (!PyArg_ParseTupleAndKeywords( - args, kws, "es|O", kwlist, - Py_FileSystemDefaultEncoding, &pathname, &debug_override)) - return NULL; - - if (debug_override != Py_None) - if ((debug = PyObject_IsTrue(debug_override)) < 0) - return NULL; - - cpathname = make_compiled_pathname(pathname, buf, MAXPATHLEN+1, debug); - PyMem_Free(pathname); - - if (cpathname == NULL) { - PyErr_Format(PyExc_SystemError, "path buffer too short"); - return NULL; - } - return PyUnicode_FromString(buf); + char buf[MAXPATHLEN+1]; + char *pathname, *cpathname; + PyObject *debug_override = Py_None; + int debug = !Py_OptimizeFlag; + + if (!PyArg_ParseTupleAndKeywords( + args, kws, "es|O", kwlist, + Py_FileSystemDefaultEncoding, &pathname, &debug_override)) + return NULL; + + if (debug_override != Py_None) + if ((debug = PyObject_IsTrue(debug_override)) < 0) + return NULL; + + cpathname = make_compiled_pathname(pathname, buf, MAXPATHLEN+1, debug); + PyMem_Free(pathname); + + if (cpathname == NULL) { + PyErr_Format(PyExc_SystemError, "path buffer too short"); + return NULL; + } + return PyUnicode_FromString(buf); } PyDoc_STRVAR(doc_cache_from_source, @@ -3490,24 +3490,24 @@ static PyObject * imp_source_from_cache(PyObject *self, PyObject *args, PyObject *kws) { - static char *kwlist[] = {"path", NULL}; + static char *kwlist[] = {"path", NULL}; - char *pathname; - char buf[MAXPATHLEN+1]; + char *pathname; + char buf[MAXPATHLEN+1]; - if (!PyArg_ParseTupleAndKeywords( - args, kws, "es", kwlist, - Py_FileSystemDefaultEncoding, &pathname)) - return NULL; - - if (make_source_pathname(pathname, buf) == NULL) { - PyErr_Format(PyExc_ValueError, "Not a PEP 3147 pyc path: %s", - pathname); - PyMem_Free(pathname); - return NULL; - } - PyMem_Free(pathname); - return PyUnicode_FromString(buf); + if (!PyArg_ParseTupleAndKeywords( + args, kws, "es", kwlist, + Py_FileSystemDefaultEncoding, &pathname)) + return NULL; + + if (make_source_pathname(pathname, buf) == NULL) { + PyErr_Format(PyExc_ValueError, "Not a PEP 3147 pyc path: %s", + pathname); + PyMem_Free(pathname); + return NULL; + } + PyMem_Free(pathname); + return PyUnicode_FromString(buf); } PyDoc_STRVAR(doc_source_from_cache, @@ -3571,46 +3571,46 @@ On platforms without threads, this function does nothing."); static PyMethodDef imp_methods[] = { - {"find_module", imp_find_module, METH_VARARGS, doc_find_module}, - {"get_magic", imp_get_magic, METH_NOARGS, doc_get_magic}, - {"get_tag", imp_get_tag, METH_NOARGS, doc_get_tag}, - {"get_suffixes", imp_get_suffixes, METH_NOARGS, doc_get_suffixes}, - {"load_module", imp_load_module, METH_VARARGS, doc_load_module}, - {"new_module", imp_new_module, METH_VARARGS, doc_new_module}, - {"lock_held", imp_lock_held, METH_NOARGS, doc_lock_held}, - {"acquire_lock", imp_acquire_lock, METH_NOARGS, doc_acquire_lock}, - {"release_lock", imp_release_lock, METH_NOARGS, doc_release_lock}, - {"reload", imp_reload, METH_O, doc_reload}, - {"cache_from_source", (PyCFunction)imp_cache_from_source, - METH_VARARGS | METH_KEYWORDS, doc_cache_from_source}, - {"source_from_cache", (PyCFunction)imp_source_from_cache, - METH_VARARGS | METH_KEYWORDS, doc_source_from_cache}, - /* The rest are obsolete */ - {"get_frozen_object", imp_get_frozen_object, METH_VARARGS}, - {"is_frozen_package", imp_is_frozen_package, METH_VARARGS}, - {"init_builtin", imp_init_builtin, METH_VARARGS}, - {"init_frozen", imp_init_frozen, METH_VARARGS}, - {"is_builtin", imp_is_builtin, METH_VARARGS}, - {"is_frozen", imp_is_frozen, METH_VARARGS}, - {"load_compiled", imp_load_compiled, METH_VARARGS}, + {"find_module", imp_find_module, METH_VARARGS, doc_find_module}, + {"get_magic", imp_get_magic, METH_NOARGS, doc_get_magic}, + {"get_tag", imp_get_tag, METH_NOARGS, doc_get_tag}, + {"get_suffixes", imp_get_suffixes, METH_NOARGS, doc_get_suffixes}, + {"load_module", imp_load_module, METH_VARARGS, doc_load_module}, + {"new_module", imp_new_module, METH_VARARGS, doc_new_module}, + {"lock_held", imp_lock_held, METH_NOARGS, doc_lock_held}, + {"acquire_lock", imp_acquire_lock, METH_NOARGS, doc_acquire_lock}, + {"release_lock", imp_release_lock, METH_NOARGS, doc_release_lock}, + {"reload", imp_reload, METH_O, doc_reload}, + {"cache_from_source", (PyCFunction)imp_cache_from_source, + METH_VARARGS | METH_KEYWORDS, doc_cache_from_source}, + {"source_from_cache", (PyCFunction)imp_source_from_cache, + METH_VARARGS | METH_KEYWORDS, doc_source_from_cache}, + /* The rest are obsolete */ + {"get_frozen_object", imp_get_frozen_object, METH_VARARGS}, + {"is_frozen_package", imp_is_frozen_package, METH_VARARGS}, + {"init_builtin", imp_init_builtin, METH_VARARGS}, + {"init_frozen", imp_init_frozen, METH_VARARGS}, + {"is_builtin", imp_is_builtin, METH_VARARGS}, + {"is_frozen", imp_is_frozen, METH_VARARGS}, + {"load_compiled", imp_load_compiled, METH_VARARGS}, #ifdef HAVE_DYNAMIC_LOADING - {"load_dynamic", imp_load_dynamic, METH_VARARGS}, + {"load_dynamic", imp_load_dynamic, METH_VARARGS}, #endif - {"load_package", imp_load_package, METH_VARARGS}, - {"load_source", imp_load_source, METH_VARARGS}, - {NULL, NULL} /* sentinel */ + {"load_package", imp_load_package, METH_VARARGS}, + {"load_source", imp_load_source, METH_VARARGS}, + {NULL, NULL} /* sentinel */ }; static int setint(PyObject *d, char *name, int value) { - PyObject *v; - int err; + PyObject *v; + int err; - v = PyLong_FromLong((long)value); - err = PyDict_SetItemString(d, name, v); - Py_XDECREF(v); - return err; + v = PyLong_FromLong((long)value); + err = PyDict_SetItemString(d, name, v); + Py_XDECREF(v); + return err; } typedef struct { @@ -3620,158 +3620,158 @@ static int NullImporter_init(NullImporter *self, PyObject *args, PyObject *kwds) { - char *path; - Py_ssize_t pathlen; + char *path; + Py_ssize_t pathlen; - if (!_PyArg_NoKeywords("NullImporter()", kwds)) - return -1; + if (!_PyArg_NoKeywords("NullImporter()", kwds)) + return -1; - if (!PyArg_ParseTuple(args, "es:NullImporter", - Py_FileSystemDefaultEncoding, &path)) - return -1; - - pathlen = strlen(path); - if (pathlen == 0) { - PyMem_Free(path); - PyErr_SetString(PyExc_ImportError, "empty pathname"); - return -1; - } else { + if (!PyArg_ParseTuple(args, "es:NullImporter", + Py_FileSystemDefaultEncoding, &path)) + return -1; + + pathlen = strlen(path); + if (pathlen == 0) { + PyMem_Free(path); + PyErr_SetString(PyExc_ImportError, "empty pathname"); + return -1; + } else { #ifndef MS_WINDOWS - struct stat statbuf; - int rv; + struct stat statbuf; + int rv; - rv = stat(path, &statbuf); - PyMem_Free(path); - if (rv == 0) { - /* it exists */ - if (S_ISDIR(statbuf.st_mode)) { - /* it's a directory */ - PyErr_SetString(PyExc_ImportError, - "existing directory"); - return -1; - } - } + rv = stat(path, &statbuf); + PyMem_Free(path); + if (rv == 0) { + /* it exists */ + if (S_ISDIR(statbuf.st_mode)) { + /* it's a directory */ + PyErr_SetString(PyExc_ImportError, + "existing directory"); + return -1; + } + } #else /* MS_WINDOWS */ - DWORD rv; - /* see issue1293 and issue3677: - * stat() on Windows doesn't recognise paths like - * "e:\\shared\\" and "\\\\whiterab-c2znlh\\shared" as dirs. - */ - rv = GetFileAttributesA(path); - PyMem_Free(path); - if (rv != INVALID_FILE_ATTRIBUTES) { - /* it exists */ - if (rv & FILE_ATTRIBUTE_DIRECTORY) { - /* it's a directory */ - PyErr_SetString(PyExc_ImportError, - "existing directory"); - return -1; - } - } + DWORD rv; + /* see issue1293 and issue3677: + * stat() on Windows doesn't recognise paths like + * "e:\\shared\\" and "\\\\whiterab-c2znlh\\shared" as dirs. + */ + rv = GetFileAttributesA(path); + PyMem_Free(path); + if (rv != INVALID_FILE_ATTRIBUTES) { + /* it exists */ + if (rv & FILE_ATTRIBUTE_DIRECTORY) { + /* it's a directory */ + PyErr_SetString(PyExc_ImportError, + "existing directory"); + return -1; + } + } #endif - } - return 0; + } + return 0; } static PyObject * NullImporter_find_module(NullImporter *self, PyObject *args) { - Py_RETURN_NONE; + Py_RETURN_NONE; } static PyMethodDef NullImporter_methods[] = { - {"find_module", (PyCFunction)NullImporter_find_module, METH_VARARGS, - "Always return None" - }, - {NULL} /* Sentinel */ + {"find_module", (PyCFunction)NullImporter_find_module, METH_VARARGS, + "Always return None" + }, + {NULL} /* Sentinel */ }; PyTypeObject PyNullImporter_Type = { - PyVarObject_HEAD_INIT(NULL, 0) - "imp.NullImporter", /*tp_name*/ - sizeof(NullImporter), /*tp_basicsize*/ - 0, /*tp_itemsize*/ - 0, /*tp_dealloc*/ - 0, /*tp_print*/ - 0, /*tp_getattr*/ - 0, /*tp_setattr*/ - 0, /*tp_reserved*/ - 0, /*tp_repr*/ - 0, /*tp_as_number*/ - 0, /*tp_as_sequence*/ - 0, /*tp_as_mapping*/ - 0, /*tp_hash */ - 0, /*tp_call*/ - 0, /*tp_str*/ - 0, /*tp_getattro*/ - 0, /*tp_setattro*/ - 0, /*tp_as_buffer*/ - Py_TPFLAGS_DEFAULT, /*tp_flags*/ - "Null importer object", /* tp_doc */ - 0, /* tp_traverse */ - 0, /* tp_clear */ - 0, /* tp_richcompare */ - 0, /* tp_weaklistoffset */ - 0, /* tp_iter */ - 0, /* tp_iternext */ - NullImporter_methods, /* tp_methods */ - 0, /* tp_members */ - 0, /* tp_getset */ - 0, /* tp_base */ - 0, /* tp_dict */ - 0, /* tp_descr_get */ - 0, /* tp_descr_set */ - 0, /* tp_dictoffset */ - (initproc)NullImporter_init, /* tp_init */ - 0, /* tp_alloc */ - PyType_GenericNew /* tp_new */ + PyVarObject_HEAD_INIT(NULL, 0) + "imp.NullImporter", /*tp_name*/ + sizeof(NullImporter), /*tp_basicsize*/ + 0, /*tp_itemsize*/ + 0, /*tp_dealloc*/ + 0, /*tp_print*/ + 0, /*tp_getattr*/ + 0, /*tp_setattr*/ + 0, /*tp_reserved*/ + 0, /*tp_repr*/ + 0, /*tp_as_number*/ + 0, /*tp_as_sequence*/ + 0, /*tp_as_mapping*/ + 0, /*tp_hash */ + 0, /*tp_call*/ + 0, /*tp_str*/ + 0, /*tp_getattro*/ + 0, /*tp_setattro*/ + 0, /*tp_as_buffer*/ + Py_TPFLAGS_DEFAULT, /*tp_flags*/ + "Null importer object", /* tp_doc */ + 0, /* tp_traverse */ + 0, /* tp_clear */ + 0, /* tp_richcompare */ + 0, /* tp_weaklistoffset */ + 0, /* tp_iter */ + 0, /* tp_iternext */ + NullImporter_methods, /* tp_methods */ + 0, /* tp_members */ + 0, /* tp_getset */ + 0, /* tp_base */ + 0, /* tp_dict */ + 0, /* tp_descr_get */ + 0, /* tp_descr_set */ + 0, /* tp_dictoffset */ + (initproc)NullImporter_init, /* tp_init */ + 0, /* tp_alloc */ + PyType_GenericNew /* tp_new */ }; static struct PyModuleDef impmodule = { - PyModuleDef_HEAD_INIT, - "imp", - doc_imp, - 0, - imp_methods, - NULL, - NULL, - NULL, - NULL + PyModuleDef_HEAD_INIT, + "imp", + doc_imp, + 0, + imp_methods, + NULL, + NULL, + NULL, + NULL }; PyMODINIT_FUNC PyInit_imp(void) { - PyObject *m, *d; + PyObject *m, *d; - if (PyType_Ready(&PyNullImporter_Type) < 0) - return NULL; + if (PyType_Ready(&PyNullImporter_Type) < 0) + return NULL; - m = PyModule_Create(&impmodule); - if (m == NULL) - goto failure; - d = PyModule_GetDict(m); - if (d == NULL) - goto failure; - - if (setint(d, "SEARCH_ERROR", SEARCH_ERROR) < 0) goto failure; - if (setint(d, "PY_SOURCE", PY_SOURCE) < 0) goto failure; - if (setint(d, "PY_COMPILED", PY_COMPILED) < 0) goto failure; - if (setint(d, "C_EXTENSION", C_EXTENSION) < 0) goto failure; - if (setint(d, "PY_RESOURCE", PY_RESOURCE) < 0) goto failure; - if (setint(d, "PKG_DIRECTORY", PKG_DIRECTORY) < 0) goto failure; - if (setint(d, "C_BUILTIN", C_BUILTIN) < 0) goto failure; - if (setint(d, "PY_FROZEN", PY_FROZEN) < 0) goto failure; - if (setint(d, "PY_CODERESOURCE", PY_CODERESOURCE) < 0) goto failure; - if (setint(d, "IMP_HOOK", IMP_HOOK) < 0) goto failure; - - Py_INCREF(&PyNullImporter_Type); - PyModule_AddObject(m, "NullImporter", (PyObject *)&PyNullImporter_Type); - return m; + m = PyModule_Create(&impmodule); + if (m == NULL) + goto failure; + d = PyModule_GetDict(m); + if (d == NULL) + goto failure; + + if (setint(d, "SEARCH_ERROR", SEARCH_ERROR) < 0) goto failure; + if (setint(d, "PY_SOURCE", PY_SOURCE) < 0) goto failure; + if (setint(d, "PY_COMPILED", PY_COMPILED) < 0) goto failure; + if (setint(d, "C_EXTENSION", C_EXTENSION) < 0) goto failure; + if (setint(d, "PY_RESOURCE", PY_RESOURCE) < 0) goto failure; + if (setint(d, "PKG_DIRECTORY", PKG_DIRECTORY) < 0) goto failure; + if (setint(d, "C_BUILTIN", C_BUILTIN) < 0) goto failure; + if (setint(d, "PY_FROZEN", PY_FROZEN) < 0) goto failure; + if (setint(d, "PY_CODERESOURCE", PY_CODERESOURCE) < 0) goto failure; + if (setint(d, "IMP_HOOK", IMP_HOOK) < 0) goto failure; + + Py_INCREF(&PyNullImporter_Type); + PyModule_AddObject(m, "NullImporter", (PyObject *)&PyNullImporter_Type); + return m; failure: - Py_XDECREF(m); - return NULL; + Py_XDECREF(m); + return NULL; } @@ -3785,31 +3785,31 @@ int PyImport_ExtendInittab(struct _inittab *newtab) { - static struct _inittab *our_copy = NULL; - struct _inittab *p; - int i, n; - - /* Count the number of entries in both tables */ - for (n = 0; newtab[n].name != NULL; n++) - ; - if (n == 0) - return 0; /* Nothing to do */ - for (i = 0; PyImport_Inittab[i].name != NULL; i++) - ; - - /* Allocate new memory for the combined table */ - p = our_copy; - PyMem_RESIZE(p, struct _inittab, i+n+1); - if (p == NULL) - return -1; - - /* Copy the tables into the new memory */ - if (our_copy != PyImport_Inittab) - memcpy(p, PyImport_Inittab, (i+1) * sizeof(struct _inittab)); - PyImport_Inittab = our_copy = p; - memcpy(p+i, newtab, (n+1) * sizeof(struct _inittab)); + static struct _inittab *our_copy = NULL; + struct _inittab *p; + int i, n; + + /* Count the number of entries in both tables */ + for (n = 0; newtab[n].name != NULL; n++) + ; + if (n == 0) + return 0; /* Nothing to do */ + for (i = 0; PyImport_Inittab[i].name != NULL; i++) + ; + + /* Allocate new memory for the combined table */ + p = our_copy; + PyMem_RESIZE(p, struct _inittab, i+n+1); + if (p == NULL) + return -1; + + /* Copy the tables into the new memory */ + if (our_copy != PyImport_Inittab) + memcpy(p, PyImport_Inittab, (i+1) * sizeof(struct _inittab)); + PyImport_Inittab = our_copy = p; + memcpy(p+i, newtab, (n+1) * sizeof(struct _inittab)); - return 0; + return 0; } /* Shorthand to add a single entry given a name and a function */ @@ -3817,14 +3817,14 @@ int PyImport_AppendInittab(const char *name, PyObject* (*initfunc)(void)) { - struct _inittab newtab[2]; + struct _inittab newtab[2]; - memset(newtab, '\0', sizeof newtab); + memset(newtab, '\0', sizeof newtab); - newtab[0].name = (char *)name; - newtab[0].initfunc = initfunc; + newtab[0].name = (char *)name; + newtab[0].initfunc = initfunc; - return PyImport_ExtendInittab(newtab); + return PyImport_ExtendInittab(newtab); } #ifdef __cplusplus Modified: python/branches/py3k-jit/Python/importdl.c ============================================================================== --- python/branches/py3k-jit/Python/importdl.c (original) +++ python/branches/py3k-jit/Python/importdl.c Mon May 10 23:55:43 2010 @@ -13,76 +13,76 @@ #include "importdl.h" extern dl_funcptr _PyImport_GetDynLoadFunc(const char *name, - const char *shortname, - const char *pathname, FILE *fp); + const char *shortname, + const char *pathname, FILE *fp); PyObject * _PyImport_LoadDynamicModule(char *name, char *pathname, FILE *fp) { - PyObject *m; - PyObject *path; - char *lastdot, *shortname, *packagecontext, *oldcontext; - dl_funcptr p0; - PyObject* (*p)(void); - struct PyModuleDef *def; - - if ((m = _PyImport_FindExtension(name, pathname)) != NULL) { - Py_INCREF(m); - return m; - } - lastdot = strrchr(name, '.'); - if (lastdot == NULL) { - packagecontext = NULL; - shortname = name; - } - else { - packagecontext = name; - shortname = lastdot+1; - } - - p0 = _PyImport_GetDynLoadFunc(name, shortname, pathname, fp); - p = (PyObject*(*)(void))p0; - if (PyErr_Occurred()) - return NULL; - if (p == NULL) { - PyErr_Format(PyExc_ImportError, - "dynamic module does not define init function (PyInit_%.200s)", - shortname); - return NULL; - } - oldcontext = _Py_PackageContext; - _Py_PackageContext = packagecontext; - m = (*p)(); - _Py_PackageContext = oldcontext; - if (m == NULL) - return NULL; - - if (PyErr_Occurred()) { - Py_DECREF(m); - PyErr_Format(PyExc_SystemError, - "initialization of %s raised unreported exception", - shortname); - return NULL; - } - - /* Remember pointer to module init function. */ - def = PyModule_GetDef(m); - def->m_base.m_init = p; - - /* Remember the filename as the __file__ attribute */ - path = PyUnicode_DecodeFSDefault(pathname); - if (PyModule_AddObject(m, "__file__", path) < 0) - PyErr_Clear(); /* Not important enough to report */ - - if (_PyImport_FixupExtension(m, name, pathname) < 0) - return NULL; - if (Py_VerboseFlag) - PySys_WriteStderr( - "import %s # dynamically loaded from %s\n", - name, pathname); - return m; + PyObject *m; + PyObject *path; + char *lastdot, *shortname, *packagecontext, *oldcontext; + dl_funcptr p0; + PyObject* (*p)(void); + struct PyModuleDef *def; + + if ((m = _PyImport_FindExtension(name, pathname)) != NULL) { + Py_INCREF(m); + return m; + } + lastdot = strrchr(name, '.'); + if (lastdot == NULL) { + packagecontext = NULL; + shortname = name; + } + else { + packagecontext = name; + shortname = lastdot+1; + } + + p0 = _PyImport_GetDynLoadFunc(name, shortname, pathname, fp); + p = (PyObject*(*)(void))p0; + if (PyErr_Occurred()) + return NULL; + if (p == NULL) { + PyErr_Format(PyExc_ImportError, + "dynamic module does not define init function (PyInit_%.200s)", + shortname); + return NULL; + } + oldcontext = _Py_PackageContext; + _Py_PackageContext = packagecontext; + m = (*p)(); + _Py_PackageContext = oldcontext; + if (m == NULL) + return NULL; + + if (PyErr_Occurred()) { + Py_DECREF(m); + PyErr_Format(PyExc_SystemError, + "initialization of %s raised unreported exception", + shortname); + return NULL; + } + + /* Remember pointer to module init function. */ + def = PyModule_GetDef(m); + def->m_base.m_init = p; + + /* Remember the filename as the __file__ attribute */ + path = PyUnicode_DecodeFSDefault(pathname); + if (PyModule_AddObject(m, "__file__", path) < 0) + PyErr_Clear(); /* Not important enough to report */ + + if (_PyImport_FixupExtension(m, name, pathname) < 0) + return NULL; + if (Py_VerboseFlag) + PySys_WriteStderr( + "import %s # dynamically loaded from %s\n", + name, pathname); + return m; } #endif /* HAVE_DYNAMIC_LOADING */ Modified: python/branches/py3k-jit/Python/importdl.h ============================================================================== --- python/branches/py3k-jit/Python/importdl.h (original) +++ python/branches/py3k-jit/Python/importdl.h Mon May 10 23:55:43 2010 @@ -8,28 +8,28 @@ /* Definitions for dynamic loading of extension modules */ enum filetype { - SEARCH_ERROR, - PY_SOURCE, - PY_COMPILED, - C_EXTENSION, - PY_RESOURCE, /* Mac only */ - PKG_DIRECTORY, - C_BUILTIN, - PY_FROZEN, - PY_CODERESOURCE, /* Mac only */ - IMP_HOOK + SEARCH_ERROR, + PY_SOURCE, + PY_COMPILED, + C_EXTENSION, + PY_RESOURCE, /* Mac only */ + PKG_DIRECTORY, + C_BUILTIN, + PY_FROZEN, + PY_CODERESOURCE, /* Mac only */ + IMP_HOOK }; struct filedescr { - char *suffix; - char *mode; - enum filetype type; + char *suffix; + char *mode; + enum filetype type; }; extern struct filedescr * _PyImport_Filetab; extern const struct filedescr _PyImport_DynLoadFiletab[]; extern PyObject *_PyImport_LoadDynamicModule(char *name, char *pathname, - FILE *); + FILE *); /* Max length of module suffix searched for -- accommodates "module.slb" */ #define MAXSUFFIXSIZE 12 Modified: python/branches/py3k-jit/Python/makeopcodetargets.py ============================================================================== --- python/branches/py3k-jit/Python/makeopcodetargets.py (original) +++ python/branches/py3k-jit/Python/makeopcodetargets.py Mon May 10 23:55:43 2010 @@ -28,7 +28,7 @@ continue targets[op] = "TARGET_%s" % opname f.write("static void *opcode_targets[256] = {\n") - f.write(",\n".join(["\t&&%s" % s for s in targets])) + f.write(",\n".join([" &&%s" % s for s in targets])) f.write("\n};\n") Modified: python/branches/py3k-jit/Python/marshal.c ============================================================================== --- python/branches/py3k-jit/Python/marshal.c (original) +++ python/branches/py3k-jit/Python/marshal.c Mon May 10 23:55:43 2010 @@ -24,28 +24,28 @@ #define MAX_MARSHAL_STACK_DEPTH 2000 #endif -#define TYPE_NULL '0' -#define TYPE_NONE 'N' -#define TYPE_FALSE 'F' -#define TYPE_TRUE 'T' -#define TYPE_STOPITER 'S' -#define TYPE_ELLIPSIS '.' -#define TYPE_INT 'i' -#define TYPE_INT64 'I' -#define TYPE_FLOAT 'f' -#define TYPE_BINARY_FLOAT 'g' -#define TYPE_COMPLEX 'x' -#define TYPE_BINARY_COMPLEX 'y' -#define TYPE_LONG 'l' -#define TYPE_STRING 's' -#define TYPE_TUPLE '(' -#define TYPE_LIST '[' -#define TYPE_DICT '{' -#define TYPE_CODE 'c' -#define TYPE_UNICODE 'u' -#define TYPE_UNKNOWN '?' -#define TYPE_SET '<' -#define TYPE_FROZENSET '>' +#define TYPE_NULL '0' +#define TYPE_NONE 'N' +#define TYPE_FALSE 'F' +#define TYPE_TRUE 'T' +#define TYPE_STOPITER 'S' +#define TYPE_ELLIPSIS '.' +#define TYPE_INT 'i' +#define TYPE_INT64 'I' +#define TYPE_FLOAT 'f' +#define TYPE_BINARY_FLOAT 'g' +#define TYPE_COMPLEX 'x' +#define TYPE_BINARY_COMPLEX 'y' +#define TYPE_LONG 'l' +#define TYPE_STRING 's' +#define TYPE_TUPLE '(' +#define TYPE_LIST '[' +#define TYPE_DICT '{' +#define TYPE_CODE 'c' +#define TYPE_UNICODE 'u' +#define TYPE_UNKNOWN '?' +#define TYPE_SET '<' +#define TYPE_FROZENSET '>' #define WFERR_OK 0 #define WFERR_UNMARSHALLABLE 1 @@ -53,79 +53,79 @@ #define WFERR_NOMEMORY 3 typedef struct { - FILE *fp; - int error; /* see WFERR_* values */ - int depth; - /* If fp == NULL, the following are valid: */ - PyObject *str; - char *ptr; - char *end; - PyObject *strings; /* dict on marshal, list on unmarshal */ - int version; + FILE *fp; + int error; /* see WFERR_* values */ + int depth; + /* If fp == NULL, the following are valid: */ + PyObject *str; + char *ptr; + char *end; + PyObject *strings; /* dict on marshal, list on unmarshal */ + int version; } WFILE; #define w_byte(c, p) if (((p)->fp)) putc((c), (p)->fp); \ - else if ((p)->ptr != (p)->end) *(p)->ptr++ = (c); \ - else w_more(c, p) + else if ((p)->ptr != (p)->end) *(p)->ptr++ = (c); \ + else w_more(c, p) static void w_more(int c, WFILE *p) { - Py_ssize_t size, newsize; - if (p->str == NULL) - return; /* An error already occurred */ - size = PyBytes_Size(p->str); - newsize = size + size + 1024; - if (newsize > 32*1024*1024) { - newsize = size + (size >> 3); /* 12.5% overallocation */ - } - if (_PyBytes_Resize(&p->str, newsize) != 0) { - p->ptr = p->end = NULL; - } - else { - p->ptr = PyBytes_AS_STRING((PyBytesObject *)p->str) + size; - p->end = - PyBytes_AS_STRING((PyBytesObject *)p->str) + newsize; - *p->ptr++ = Py_SAFE_DOWNCAST(c, int, char); - } + Py_ssize_t size, newsize; + if (p->str == NULL) + return; /* An error already occurred */ + size = PyBytes_Size(p->str); + newsize = size + size + 1024; + if (newsize > 32*1024*1024) { + newsize = size + (size >> 3); /* 12.5% overallocation */ + } + if (_PyBytes_Resize(&p->str, newsize) != 0) { + p->ptr = p->end = NULL; + } + else { + p->ptr = PyBytes_AS_STRING((PyBytesObject *)p->str) + size; + p->end = + PyBytes_AS_STRING((PyBytesObject *)p->str) + newsize; + *p->ptr++ = Py_SAFE_DOWNCAST(c, int, char); + } } static void w_string(char *s, int n, WFILE *p) { - if (p->fp != NULL) { - fwrite(s, 1, n, p->fp); - } - else { - while (--n >= 0) { - w_byte(*s, p); - s++; - } - } + if (p->fp != NULL) { + fwrite(s, 1, n, p->fp); + } + else { + while (--n >= 0) { + w_byte(*s, p); + s++; + } + } } static void w_short(int x, WFILE *p) { - w_byte((char)( x & 0xff), p); - w_byte((char)((x>> 8) & 0xff), p); + w_byte((char)( x & 0xff), p); + w_byte((char)((x>> 8) & 0xff), p); } static void w_long(long x, WFILE *p) { - w_byte((char)( x & 0xff), p); - w_byte((char)((x>> 8) & 0xff), p); - w_byte((char)((x>>16) & 0xff), p); - w_byte((char)((x>>24) & 0xff), p); + w_byte((char)( x & 0xff), p); + w_byte((char)((x>> 8) & 0xff), p); + w_byte((char)((x>>16) & 0xff), p); + w_byte((char)((x>>24) & 0xff), p); } #if SIZEOF_LONG > 4 static void w_long64(long x, WFILE *p) { - w_long(x, p); - w_long(x>>32, p); + w_long(x, p); + w_long(x>>32, p); } #endif @@ -144,322 +144,322 @@ static void w_PyLong(const PyLongObject *ob, WFILE *p) { - Py_ssize_t i, j, n, l; - digit d; + Py_ssize_t i, j, n, l; + digit d; - w_byte(TYPE_LONG, p); - if (Py_SIZE(ob) == 0) { - w_long((long)0, p); - return; - } - - /* set l to number of base PyLong_MARSHAL_BASE digits */ - n = ABS(Py_SIZE(ob)); - l = (n-1) * PyLong_MARSHAL_RATIO; - d = ob->ob_digit[n-1]; - assert(d != 0); /* a PyLong is always normalized */ - do { - d >>= PyLong_MARSHAL_SHIFT; - l++; - } while (d != 0); - w_long((long)(Py_SIZE(ob) > 0 ? l : -l), p); - - for (i=0; i < n-1; i++) { - d = ob->ob_digit[i]; - for (j=0; j < PyLong_MARSHAL_RATIO; j++) { - w_short(d & PyLong_MARSHAL_MASK, p); - d >>= PyLong_MARSHAL_SHIFT; - } - assert (d == 0); - } - d = ob->ob_digit[n-1]; - do { - w_short(d & PyLong_MARSHAL_MASK, p); - d >>= PyLong_MARSHAL_SHIFT; - } while (d != 0); + w_byte(TYPE_LONG, p); + if (Py_SIZE(ob) == 0) { + w_long((long)0, p); + return; + } + + /* set l to number of base PyLong_MARSHAL_BASE digits */ + n = ABS(Py_SIZE(ob)); + l = (n-1) * PyLong_MARSHAL_RATIO; + d = ob->ob_digit[n-1]; + assert(d != 0); /* a PyLong is always normalized */ + do { + d >>= PyLong_MARSHAL_SHIFT; + l++; + } while (d != 0); + w_long((long)(Py_SIZE(ob) > 0 ? l : -l), p); + + for (i=0; i < n-1; i++) { + d = ob->ob_digit[i]; + for (j=0; j < PyLong_MARSHAL_RATIO; j++) { + w_short(d & PyLong_MARSHAL_MASK, p); + d >>= PyLong_MARSHAL_SHIFT; + } + assert (d == 0); + } + d = ob->ob_digit[n-1]; + do { + w_short(d & PyLong_MARSHAL_MASK, p); + d >>= PyLong_MARSHAL_SHIFT; + } while (d != 0); } static void w_object(PyObject *v, WFILE *p) { - Py_ssize_t i, n; + Py_ssize_t i, n; - p->depth++; + p->depth++; - if (p->depth > MAX_MARSHAL_STACK_DEPTH) { - p->error = WFERR_NESTEDTOODEEP; - } - else if (v == NULL) { - w_byte(TYPE_NULL, p); - } - else if (v == Py_None) { - w_byte(TYPE_NONE, p); - } - else if (v == PyExc_StopIteration) { - w_byte(TYPE_STOPITER, p); - } - else if (v == Py_Ellipsis) { - w_byte(TYPE_ELLIPSIS, p); - } - else if (v == Py_False) { - w_byte(TYPE_FALSE, p); - } - else if (v == Py_True) { - w_byte(TYPE_TRUE, p); - } - else if (PyLong_CheckExact(v)) { - long x = PyLong_AsLong(v); - if ((x == -1) && PyErr_Occurred()) { - PyLongObject *ob = (PyLongObject *)v; - PyErr_Clear(); - w_PyLong(ob, p); - } - else { + if (p->depth > MAX_MARSHAL_STACK_DEPTH) { + p->error = WFERR_NESTEDTOODEEP; + } + else if (v == NULL) { + w_byte(TYPE_NULL, p); + } + else if (v == Py_None) { + w_byte(TYPE_NONE, p); + } + else if (v == PyExc_StopIteration) { + w_byte(TYPE_STOPITER, p); + } + else if (v == Py_Ellipsis) { + w_byte(TYPE_ELLIPSIS, p); + } + else if (v == Py_False) { + w_byte(TYPE_FALSE, p); + } + else if (v == Py_True) { + w_byte(TYPE_TRUE, p); + } + else if (PyLong_CheckExact(v)) { + long x = PyLong_AsLong(v); + if ((x == -1) && PyErr_Occurred()) { + PyLongObject *ob = (PyLongObject *)v; + PyErr_Clear(); + w_PyLong(ob, p); + } + else { #if SIZEOF_LONG > 4 - long y = Py_ARITHMETIC_RIGHT_SHIFT(long, x, 31); - if (y && y != -1) { - w_byte(TYPE_INT64, p); - w_long64(x, p); - } - else + long y = Py_ARITHMETIC_RIGHT_SHIFT(long, x, 31); + if (y && y != -1) { + w_byte(TYPE_INT64, p); + w_long64(x, p); + } + else #endif - { - w_byte(TYPE_INT, p); - w_long(x, p); - } - } - } - else if (PyFloat_CheckExact(v)) { - if (p->version > 1) { - unsigned char buf[8]; - if (_PyFloat_Pack8(PyFloat_AsDouble(v), - buf, 1) < 0) { - p->error = WFERR_UNMARSHALLABLE; - return; - } - w_byte(TYPE_BINARY_FLOAT, p); - w_string((char*)buf, 8, p); - } - else { - char *buf = PyOS_double_to_string(PyFloat_AS_DOUBLE(v), - 'g', 17, 0, NULL); - if (!buf) { - p->error = WFERR_NOMEMORY; - return; - } - n = strlen(buf); - w_byte(TYPE_FLOAT, p); - w_byte((int)n, p); - w_string(buf, (int)n, p); - PyMem_Free(buf); - } - } - else if (PyComplex_CheckExact(v)) { - if (p->version > 1) { - unsigned char buf[8]; - if (_PyFloat_Pack8(PyComplex_RealAsDouble(v), - buf, 1) < 0) { - p->error = WFERR_UNMARSHALLABLE; - return; - } - w_byte(TYPE_BINARY_COMPLEX, p); - w_string((char*)buf, 8, p); - if (_PyFloat_Pack8(PyComplex_ImagAsDouble(v), - buf, 1) < 0) { - p->error = WFERR_UNMARSHALLABLE; - return; - } - w_string((char*)buf, 8, p); - } - else { - char *buf; - w_byte(TYPE_COMPLEX, p); - buf = PyOS_double_to_string(PyComplex_RealAsDouble(v), - 'g', 17, 0, NULL); - if (!buf) { - p->error = WFERR_NOMEMORY; - return; - } - n = strlen(buf); - w_byte((int)n, p); - w_string(buf, (int)n, p); - PyMem_Free(buf); - buf = PyOS_double_to_string(PyComplex_ImagAsDouble(v), - 'g', 17, 0, NULL); - if (!buf) { - p->error = WFERR_NOMEMORY; - return; - } - n = strlen(buf); - w_byte((int)n, p); - w_string(buf, (int)n, p); - PyMem_Free(buf); - } - } - else if (PyBytes_CheckExact(v)) { - w_byte(TYPE_STRING, p); - n = PyBytes_GET_SIZE(v); - if (n > INT_MAX) { - /* huge strings are not supported */ - p->depth--; - p->error = WFERR_UNMARSHALLABLE; - return; - } - w_long((long)n, p); - w_string(PyBytes_AS_STRING(v), (int)n, p); - } - else if (PyUnicode_CheckExact(v)) { - PyObject *utf8; - utf8 = PyUnicode_EncodeUTF8(PyUnicode_AS_UNICODE(v), - PyUnicode_GET_SIZE(v), - "surrogatepass"); - if (utf8 == NULL) { - p->depth--; - p->error = WFERR_UNMARSHALLABLE; - return; - } - w_byte(TYPE_UNICODE, p); - n = PyBytes_GET_SIZE(utf8); - if (n > INT_MAX) { - p->depth--; - p->error = WFERR_UNMARSHALLABLE; - return; - } - w_long((long)n, p); - w_string(PyBytes_AS_STRING(utf8), (int)n, p); - Py_DECREF(utf8); - } - else if (PyTuple_CheckExact(v)) { - w_byte(TYPE_TUPLE, p); - n = PyTuple_Size(v); - w_long((long)n, p); - for (i = 0; i < n; i++) { - w_object(PyTuple_GET_ITEM(v, i), p); - } - } - else if (PyList_CheckExact(v)) { - w_byte(TYPE_LIST, p); - n = PyList_GET_SIZE(v); - w_long((long)n, p); - for (i = 0; i < n; i++) { - w_object(PyList_GET_ITEM(v, i), p); - } - } - else if (PyDict_CheckExact(v)) { - Py_ssize_t pos; - PyObject *key, *value; - w_byte(TYPE_DICT, p); - /* This one is NULL object terminated! */ - pos = 0; - while (PyDict_Next(v, &pos, &key, &value)) { - w_object(key, p); - w_object(value, p); - } - w_object((PyObject *)NULL, p); - } - else if (PyAnySet_CheckExact(v)) { - PyObject *value, *it; - - if (PyObject_TypeCheck(v, &PySet_Type)) - w_byte(TYPE_SET, p); - else - w_byte(TYPE_FROZENSET, p); - n = PyObject_Size(v); - if (n == -1) { - p->depth--; - p->error = WFERR_UNMARSHALLABLE; - return; - } - w_long((long)n, p); - it = PyObject_GetIter(v); - if (it == NULL) { - p->depth--; - p->error = WFERR_UNMARSHALLABLE; - return; - } - while ((value = PyIter_Next(it)) != NULL) { - w_object(value, p); - Py_DECREF(value); - } - Py_DECREF(it); - if (PyErr_Occurred()) { - p->depth--; - p->error = WFERR_UNMARSHALLABLE; - return; - } - } - else if (PyCode_Check(v)) { - PyCodeObject *co = (PyCodeObject *)v; - w_byte(TYPE_CODE, p); - w_long(co->co_argcount, p); - w_long(co->co_kwonlyargcount, p); - w_long(co->co_nlocals, p); - w_long(co->co_stacksize, p); - w_long(co->co_flags, p); - w_object(co->co_code, p); - w_object(co->co_consts, p); - w_object(co->co_names, p); - w_object(co->co_varnames, p); - w_object(co->co_freevars, p); - w_object(co->co_cellvars, p); - w_object(co->co_filename, p); - w_object(co->co_name, p); - w_long(co->co_firstlineno, p); - w_object(co->co_lnotab, p); - } - else if (PyObject_CheckBuffer(v)) { - /* Write unknown buffer-style objects as a string */ - char *s; - PyBufferProcs *pb = v->ob_type->tp_as_buffer; - Py_buffer view; - if ((*pb->bf_getbuffer)(v, &view, PyBUF_SIMPLE) != 0) { - w_byte(TYPE_UNKNOWN, p); - p->error = WFERR_UNMARSHALLABLE; - } - w_byte(TYPE_STRING, p); - n = view.len; - s = view.buf; - if (n > INT_MAX) { - p->depth--; - p->error = WFERR_UNMARSHALLABLE; - return; - } - w_long((long)n, p); - w_string(s, (int)n, p); - if (pb->bf_releasebuffer != NULL) - (*pb->bf_releasebuffer)(v, &view); - } - else { - w_byte(TYPE_UNKNOWN, p); - p->error = WFERR_UNMARSHALLABLE; - } - p->depth--; + { + w_byte(TYPE_INT, p); + w_long(x, p); + } + } + } + else if (PyFloat_CheckExact(v)) { + if (p->version > 1) { + unsigned char buf[8]; + if (_PyFloat_Pack8(PyFloat_AsDouble(v), + buf, 1) < 0) { + p->error = WFERR_UNMARSHALLABLE; + return; + } + w_byte(TYPE_BINARY_FLOAT, p); + w_string((char*)buf, 8, p); + } + else { + char *buf = PyOS_double_to_string(PyFloat_AS_DOUBLE(v), + 'g', 17, 0, NULL); + if (!buf) { + p->error = WFERR_NOMEMORY; + return; + } + n = strlen(buf); + w_byte(TYPE_FLOAT, p); + w_byte((int)n, p); + w_string(buf, (int)n, p); + PyMem_Free(buf); + } + } + else if (PyComplex_CheckExact(v)) { + if (p->version > 1) { + unsigned char buf[8]; + if (_PyFloat_Pack8(PyComplex_RealAsDouble(v), + buf, 1) < 0) { + p->error = WFERR_UNMARSHALLABLE; + return; + } + w_byte(TYPE_BINARY_COMPLEX, p); + w_string((char*)buf, 8, p); + if (_PyFloat_Pack8(PyComplex_ImagAsDouble(v), + buf, 1) < 0) { + p->error = WFERR_UNMARSHALLABLE; + return; + } + w_string((char*)buf, 8, p); + } + else { + char *buf; + w_byte(TYPE_COMPLEX, p); + buf = PyOS_double_to_string(PyComplex_RealAsDouble(v), + 'g', 17, 0, NULL); + if (!buf) { + p->error = WFERR_NOMEMORY; + return; + } + n = strlen(buf); + w_byte((int)n, p); + w_string(buf, (int)n, p); + PyMem_Free(buf); + buf = PyOS_double_to_string(PyComplex_ImagAsDouble(v), + 'g', 17, 0, NULL); + if (!buf) { + p->error = WFERR_NOMEMORY; + return; + } + n = strlen(buf); + w_byte((int)n, p); + w_string(buf, (int)n, p); + PyMem_Free(buf); + } + } + else if (PyBytes_CheckExact(v)) { + w_byte(TYPE_STRING, p); + n = PyBytes_GET_SIZE(v); + if (n > INT_MAX) { + /* huge strings are not supported */ + p->depth--; + p->error = WFERR_UNMARSHALLABLE; + return; + } + w_long((long)n, p); + w_string(PyBytes_AS_STRING(v), (int)n, p); + } + else if (PyUnicode_CheckExact(v)) { + PyObject *utf8; + utf8 = PyUnicode_EncodeUTF8(PyUnicode_AS_UNICODE(v), + PyUnicode_GET_SIZE(v), + "surrogatepass"); + if (utf8 == NULL) { + p->depth--; + p->error = WFERR_UNMARSHALLABLE; + return; + } + w_byte(TYPE_UNICODE, p); + n = PyBytes_GET_SIZE(utf8); + if (n > INT_MAX) { + p->depth--; + p->error = WFERR_UNMARSHALLABLE; + return; + } + w_long((long)n, p); + w_string(PyBytes_AS_STRING(utf8), (int)n, p); + Py_DECREF(utf8); + } + else if (PyTuple_CheckExact(v)) { + w_byte(TYPE_TUPLE, p); + n = PyTuple_Size(v); + w_long((long)n, p); + for (i = 0; i < n; i++) { + w_object(PyTuple_GET_ITEM(v, i), p); + } + } + else if (PyList_CheckExact(v)) { + w_byte(TYPE_LIST, p); + n = PyList_GET_SIZE(v); + w_long((long)n, p); + for (i = 0; i < n; i++) { + w_object(PyList_GET_ITEM(v, i), p); + } + } + else if (PyDict_CheckExact(v)) { + Py_ssize_t pos; + PyObject *key, *value; + w_byte(TYPE_DICT, p); + /* This one is NULL object terminated! */ + pos = 0; + while (PyDict_Next(v, &pos, &key, &value)) { + w_object(key, p); + w_object(value, p); + } + w_object((PyObject *)NULL, p); + } + else if (PyAnySet_CheckExact(v)) { + PyObject *value, *it; + + if (PyObject_TypeCheck(v, &PySet_Type)) + w_byte(TYPE_SET, p); + else + w_byte(TYPE_FROZENSET, p); + n = PyObject_Size(v); + if (n == -1) { + p->depth--; + p->error = WFERR_UNMARSHALLABLE; + return; + } + w_long((long)n, p); + it = PyObject_GetIter(v); + if (it == NULL) { + p->depth--; + p->error = WFERR_UNMARSHALLABLE; + return; + } + while ((value = PyIter_Next(it)) != NULL) { + w_object(value, p); + Py_DECREF(value); + } + Py_DECREF(it); + if (PyErr_Occurred()) { + p->depth--; + p->error = WFERR_UNMARSHALLABLE; + return; + } + } + else if (PyCode_Check(v)) { + PyCodeObject *co = (PyCodeObject *)v; + w_byte(TYPE_CODE, p); + w_long(co->co_argcount, p); + w_long(co->co_kwonlyargcount, p); + w_long(co->co_nlocals, p); + w_long(co->co_stacksize, p); + w_long(co->co_flags, p); + w_object(co->co_code, p); + w_object(co->co_consts, p); + w_object(co->co_names, p); + w_object(co->co_varnames, p); + w_object(co->co_freevars, p); + w_object(co->co_cellvars, p); + w_object(co->co_filename, p); + w_object(co->co_name, p); + w_long(co->co_firstlineno, p); + w_object(co->co_lnotab, p); + } + else if (PyObject_CheckBuffer(v)) { + /* Write unknown buffer-style objects as a string */ + char *s; + PyBufferProcs *pb = v->ob_type->tp_as_buffer; + Py_buffer view; + if ((*pb->bf_getbuffer)(v, &view, PyBUF_SIMPLE) != 0) { + w_byte(TYPE_UNKNOWN, p); + p->error = WFERR_UNMARSHALLABLE; + } + w_byte(TYPE_STRING, p); + n = view.len; + s = view.buf; + if (n > INT_MAX) { + p->depth--; + p->error = WFERR_UNMARSHALLABLE; + return; + } + w_long((long)n, p); + w_string(s, (int)n, p); + if (pb->bf_releasebuffer != NULL) + (*pb->bf_releasebuffer)(v, &view); + } + else { + w_byte(TYPE_UNKNOWN, p); + p->error = WFERR_UNMARSHALLABLE; + } + p->depth--; } /* version currently has no effect for writing longs. */ void PyMarshal_WriteLongToFile(long x, FILE *fp, int version) { - WFILE wf; - wf.fp = fp; - wf.error = WFERR_OK; - wf.depth = 0; - wf.strings = NULL; - wf.version = version; - w_long(x, &wf); + WFILE wf; + wf.fp = fp; + wf.error = WFERR_OK; + wf.depth = 0; + wf.strings = NULL; + wf.version = version; + w_long(x, &wf); } void PyMarshal_WriteObjectToFile(PyObject *x, FILE *fp, int version) { - WFILE wf; - wf.fp = fp; - wf.error = WFERR_OK; - wf.depth = 0; - wf.strings = (version > 0) ? PyDict_New() : NULL; - wf.version = version; - w_object(x, &wf); - Py_XDECREF(wf.strings); + WFILE wf; + wf.fp = fp; + wf.error = WFERR_OK; + wf.depth = 0; + wf.strings = (version > 0) ? PyDict_New() : NULL; + wf.version = version; + w_object(x, &wf); + Py_XDECREF(wf.strings); } typedef WFILE RFILE; /* Same struct with different invariants */ @@ -471,49 +471,49 @@ static int r_string(char *s, int n, RFILE *p) { - if (p->fp != NULL) - /* The result fits into int because it must be <=n. */ - return (int)fread(s, 1, n, p->fp); - if (p->end - p->ptr < n) - n = (int)(p->end - p->ptr); - memcpy(s, p->ptr, n); - p->ptr += n; - return n; + if (p->fp != NULL) + /* The result fits into int because it must be <=n. */ + return (int)fread(s, 1, n, p->fp); + if (p->end - p->ptr < n) + n = (int)(p->end - p->ptr); + memcpy(s, p->ptr, n); + p->ptr += n; + return n; } static int r_short(RFILE *p) { - register short x; - x = r_byte(p); - x |= r_byte(p) << 8; - /* Sign-extension, in case short greater than 16 bits */ - x |= -(x & 0x8000); - return x; + register short x; + x = r_byte(p); + x |= r_byte(p) << 8; + /* Sign-extension, in case short greater than 16 bits */ + x |= -(x & 0x8000); + return x; } static long r_long(RFILE *p) { - register long x; - register FILE *fp = p->fp; - if (fp) { - x = getc(fp); - x |= (long)getc(fp) << 8; - x |= (long)getc(fp) << 16; - x |= (long)getc(fp) << 24; - } - else { - x = rs_byte(p); - x |= (long)rs_byte(p) << 8; - x |= (long)rs_byte(p) << 16; - x |= (long)rs_byte(p) << 24; - } + register long x; + register FILE *fp = p->fp; + if (fp) { + x = getc(fp); + x |= (long)getc(fp) << 8; + x |= (long)getc(fp) << 16; + x |= (long)getc(fp) << 24; + } + else { + x = rs_byte(p); + x |= (long)rs_byte(p) << 8; + x |= (long)rs_byte(p) << 16; + x |= (long)rs_byte(p) << 24; + } #if SIZEOF_LONG > 4 - /* Sign extension for 64-bit machines */ - x |= -(x & 0x80000000L); + /* Sign extension for 64-bit machines */ + x |= -(x & 0x80000000L); #endif - return x; + return x; } /* r_long64 deals with the TYPE_INT64 code. On a machine with @@ -526,534 +526,534 @@ static PyObject * r_long64(RFILE *p) { - long lo4 = r_long(p); - long hi4 = r_long(p); + long lo4 = r_long(p); + long hi4 = r_long(p); #if SIZEOF_LONG > 4 - long x = (hi4 << 32) | (lo4 & 0xFFFFFFFFL); - return PyLong_FromLong(x); + long x = (hi4 << 32) | (lo4 & 0xFFFFFFFFL); + return PyLong_FromLong(x); #else - unsigned char buf[8]; - int one = 1; - int is_little_endian = (int)*(char*)&one; - if (is_little_endian) { - memcpy(buf, &lo4, 4); - memcpy(buf+4, &hi4, 4); - } - else { - memcpy(buf, &hi4, 4); - memcpy(buf+4, &lo4, 4); - } - return _PyLong_FromByteArray(buf, 8, is_little_endian, 1); + unsigned char buf[8]; + int one = 1; + int is_little_endian = (int)*(char*)&one; + if (is_little_endian) { + memcpy(buf, &lo4, 4); + memcpy(buf+4, &hi4, 4); + } + else { + memcpy(buf, &hi4, 4); + memcpy(buf+4, &lo4, 4); + } + return _PyLong_FromByteArray(buf, 8, is_little_endian, 1); #endif } static PyObject * r_PyLong(RFILE *p) { - PyLongObject *ob; - int size, i, j, md, shorts_in_top_digit; - long n; - digit d; - - n = r_long(p); - if (n == 0) - return (PyObject *)_PyLong_New(0); - if (n < -INT_MAX || n > INT_MAX) { - PyErr_SetString(PyExc_ValueError, - "bad marshal data (long size out of range)"); - return NULL; - } - - size = 1 + (ABS(n) - 1) / PyLong_MARSHAL_RATIO; - shorts_in_top_digit = 1 + (ABS(n) - 1) % PyLong_MARSHAL_RATIO; - ob = _PyLong_New(size); - if (ob == NULL) - return NULL; - Py_SIZE(ob) = n > 0 ? size : -size; - - for (i = 0; i < size-1; i++) { - d = 0; - for (j=0; j < PyLong_MARSHAL_RATIO; j++) { - md = r_short(p); - if (md < 0 || md > PyLong_MARSHAL_BASE) - goto bad_digit; - d += (digit)md << j*PyLong_MARSHAL_SHIFT; - } - ob->ob_digit[i] = d; - } - d = 0; - for (j=0; j < shorts_in_top_digit; j++) { - md = r_short(p); - if (md < 0 || md > PyLong_MARSHAL_BASE) - goto bad_digit; - /* topmost marshal digit should be nonzero */ - if (md == 0 && j == shorts_in_top_digit - 1) { - Py_DECREF(ob); - PyErr_SetString(PyExc_ValueError, - "bad marshal data (unnormalized long data)"); - return NULL; - } - d += (digit)md << j*PyLong_MARSHAL_SHIFT; - } - /* top digit should be nonzero, else the resulting PyLong won't be - normalized */ - ob->ob_digit[size-1] = d; - return (PyObject *)ob; + PyLongObject *ob; + int size, i, j, md, shorts_in_top_digit; + long n; + digit d; + + n = r_long(p); + if (n == 0) + return (PyObject *)_PyLong_New(0); + if (n < -INT_MAX || n > INT_MAX) { + PyErr_SetString(PyExc_ValueError, + "bad marshal data (long size out of range)"); + return NULL; + } + + size = 1 + (ABS(n) - 1) / PyLong_MARSHAL_RATIO; + shorts_in_top_digit = 1 + (ABS(n) - 1) % PyLong_MARSHAL_RATIO; + ob = _PyLong_New(size); + if (ob == NULL) + return NULL; + Py_SIZE(ob) = n > 0 ? size : -size; + + for (i = 0; i < size-1; i++) { + d = 0; + for (j=0; j < PyLong_MARSHAL_RATIO; j++) { + md = r_short(p); + if (md < 0 || md > PyLong_MARSHAL_BASE) + goto bad_digit; + d += (digit)md << j*PyLong_MARSHAL_SHIFT; + } + ob->ob_digit[i] = d; + } + d = 0; + for (j=0; j < shorts_in_top_digit; j++) { + md = r_short(p); + if (md < 0 || md > PyLong_MARSHAL_BASE) + goto bad_digit; + /* topmost marshal digit should be nonzero */ + if (md == 0 && j == shorts_in_top_digit - 1) { + Py_DECREF(ob); + PyErr_SetString(PyExc_ValueError, + "bad marshal data (unnormalized long data)"); + return NULL; + } + d += (digit)md << j*PyLong_MARSHAL_SHIFT; + } + /* top digit should be nonzero, else the resulting PyLong won't be + normalized */ + ob->ob_digit[size-1] = d; + return (PyObject *)ob; bad_digit: - Py_DECREF(ob); - PyErr_SetString(PyExc_ValueError, - "bad marshal data (digit out of range in long)"); - return NULL; + Py_DECREF(ob); + PyErr_SetString(PyExc_ValueError, + "bad marshal data (digit out of range in long)"); + return NULL; } static PyObject * r_object(RFILE *p) { - /* NULL is a valid return value, it does not necessarily means that - an exception is set. */ - PyObject *v, *v2; - long i, n; - int type = r_byte(p); - PyObject *retval; - - p->depth++; - - if (p->depth > MAX_MARSHAL_STACK_DEPTH) { - p->depth--; - PyErr_SetString(PyExc_ValueError, "recursion limit exceeded"); - return NULL; - } - - switch (type) { - - case EOF: - PyErr_SetString(PyExc_EOFError, - "EOF read where object expected"); - retval = NULL; - break; - - case TYPE_NULL: - retval = NULL; - break; - - case TYPE_NONE: - Py_INCREF(Py_None); - retval = Py_None; - break; - - case TYPE_STOPITER: - Py_INCREF(PyExc_StopIteration); - retval = PyExc_StopIteration; - break; - - case TYPE_ELLIPSIS: - Py_INCREF(Py_Ellipsis); - retval = Py_Ellipsis; - break; - - case TYPE_FALSE: - Py_INCREF(Py_False); - retval = Py_False; - break; - - case TYPE_TRUE: - Py_INCREF(Py_True); - retval = Py_True; - break; - - case TYPE_INT: - retval = PyLong_FromLong(r_long(p)); - break; - - case TYPE_INT64: - retval = r_long64(p); - break; - - case TYPE_LONG: - retval = r_PyLong(p); - break; - - case TYPE_FLOAT: - { - char buf[256]; - double dx; - retval = NULL; - n = r_byte(p); - if (n == EOF || r_string(buf, (int)n, p) != n) { - PyErr_SetString(PyExc_EOFError, - "EOF read where object expected"); - break; - } - buf[n] = '\0'; - dx = PyOS_string_to_double(buf, NULL, NULL); - if (dx == -1.0 && PyErr_Occurred()) - break; - retval = PyFloat_FromDouble(dx); - break; - } - - case TYPE_BINARY_FLOAT: - { - unsigned char buf[8]; - double x; - if (r_string((char*)buf, 8, p) != 8) { - PyErr_SetString(PyExc_EOFError, - "EOF read where object expected"); - retval = NULL; - break; - } - x = _PyFloat_Unpack8(buf, 1); - if (x == -1.0 && PyErr_Occurred()) { - retval = NULL; - break; - } - retval = PyFloat_FromDouble(x); - break; - } - - case TYPE_COMPLEX: - { - char buf[256]; - Py_complex c; - retval = NULL; - n = r_byte(p); - if (n == EOF || r_string(buf, (int)n, p) != n) { - PyErr_SetString(PyExc_EOFError, - "EOF read where object expected"); - break; - } - buf[n] = '\0'; - c.real = PyOS_string_to_double(buf, NULL, NULL); - if (c.real == -1.0 && PyErr_Occurred()) - break; - n = r_byte(p); - if (n == EOF || r_string(buf, (int)n, p) != n) { - PyErr_SetString(PyExc_EOFError, - "EOF read where object expected"); - break; - } - buf[n] = '\0'; - c.imag = PyOS_string_to_double(buf, NULL, NULL); - if (c.imag == -1.0 && PyErr_Occurred()) - break; - retval = PyComplex_FromCComplex(c); - break; - } - - case TYPE_BINARY_COMPLEX: - { - unsigned char buf[8]; - Py_complex c; - if (r_string((char*)buf, 8, p) != 8) { - PyErr_SetString(PyExc_EOFError, - "EOF read where object expected"); - retval = NULL; - break; - } - c.real = _PyFloat_Unpack8(buf, 1); - if (c.real == -1.0 && PyErr_Occurred()) { - retval = NULL; - break; - } - if (r_string((char*)buf, 8, p) != 8) { - PyErr_SetString(PyExc_EOFError, - "EOF read where object expected"); - retval = NULL; - break; - } - c.imag = _PyFloat_Unpack8(buf, 1); - if (c.imag == -1.0 && PyErr_Occurred()) { - retval = NULL; - break; - } - retval = PyComplex_FromCComplex(c); - break; - } - - case TYPE_STRING: - n = r_long(p); - if (n < 0 || n > INT_MAX) { - PyErr_SetString(PyExc_ValueError, "bad marshal data (string size out of range)"); - retval = NULL; - break; - } - v = PyBytes_FromStringAndSize((char *)NULL, n); - if (v == NULL) { - retval = NULL; - break; - } - if (r_string(PyBytes_AS_STRING(v), (int)n, p) != n) { - Py_DECREF(v); - PyErr_SetString(PyExc_EOFError, - "EOF read where object expected"); - retval = NULL; - break; - } - retval = v; - break; - - case TYPE_UNICODE: - { - char *buffer; - - n = r_long(p); - if (n < 0 || n > INT_MAX) { - PyErr_SetString(PyExc_ValueError, "bad marshal data (unicode size out of range)"); - retval = NULL; - break; - } - buffer = PyMem_NEW(char, n); - if (buffer == NULL) { - retval = PyErr_NoMemory(); - break; - } - if (r_string(buffer, (int)n, p) != n) { - PyMem_DEL(buffer); - PyErr_SetString(PyExc_EOFError, - "EOF read where object expected"); - retval = NULL; - break; - } - v = PyUnicode_DecodeUTF8(buffer, n, "surrogatepass"); - PyMem_DEL(buffer); - retval = v; - break; - } - - case TYPE_TUPLE: - n = r_long(p); - if (n < 0 || n > INT_MAX) { - PyErr_SetString(PyExc_ValueError, "bad marshal data (tuple size out of range)"); - retval = NULL; - break; - } - v = PyTuple_New((int)n); - if (v == NULL) { - retval = NULL; - break; - } - for (i = 0; i < n; i++) { - v2 = r_object(p); - if ( v2 == NULL ) { - if (!PyErr_Occurred()) - PyErr_SetString(PyExc_TypeError, - "NULL object in marshal data for tuple"); - Py_DECREF(v); - v = NULL; - break; - } - PyTuple_SET_ITEM(v, (int)i, v2); - } - retval = v; - break; - - case TYPE_LIST: - n = r_long(p); - if (n < 0 || n > INT_MAX) { - PyErr_SetString(PyExc_ValueError, "bad marshal data (list size out of range)"); - retval = NULL; - break; - } - v = PyList_New((int)n); - if (v == NULL) { - retval = NULL; - break; - } - for (i = 0; i < n; i++) { - v2 = r_object(p); - if ( v2 == NULL ) { - if (!PyErr_Occurred()) - PyErr_SetString(PyExc_TypeError, - "NULL object in marshal data for list"); - Py_DECREF(v); - v = NULL; - break; - } - PyList_SET_ITEM(v, (int)i, v2); - } - retval = v; - break; - - case TYPE_DICT: - v = PyDict_New(); - if (v == NULL) { - retval = NULL; - break; - } - for (;;) { - PyObject *key, *val; - key = r_object(p); - if (key == NULL) - break; - val = r_object(p); - if (val != NULL) - PyDict_SetItem(v, key, val); - Py_DECREF(key); - Py_XDECREF(val); - } - if (PyErr_Occurred()) { - Py_DECREF(v); - v = NULL; - } - retval = v; - break; - - case TYPE_SET: - case TYPE_FROZENSET: - n = r_long(p); - if (n < 0 || n > INT_MAX) { - PyErr_SetString(PyExc_ValueError, "bad marshal data (set size out of range)"); - retval = NULL; - break; - } - v = (type == TYPE_SET) ? PySet_New(NULL) : PyFrozenSet_New(NULL); - if (v == NULL) { - retval = NULL; - break; - } - for (i = 0; i < n; i++) { - v2 = r_object(p); - if ( v2 == NULL ) { - if (!PyErr_Occurred()) - PyErr_SetString(PyExc_TypeError, - "NULL object in marshal data for set"); - Py_DECREF(v); - v = NULL; - break; - } - if (PySet_Add(v, v2) == -1) { - Py_DECREF(v); - Py_DECREF(v2); - v = NULL; - break; - } - Py_DECREF(v2); - } - retval = v; - break; - - case TYPE_CODE: - { - int argcount; - int kwonlyargcount; - int nlocals; - int stacksize; - int flags; - PyObject *code = NULL; - PyObject *consts = NULL; - PyObject *names = NULL; - PyObject *varnames = NULL; - PyObject *freevars = NULL; - PyObject *cellvars = NULL; - PyObject *filename = NULL; - PyObject *name = NULL; - int firstlineno; - PyObject *lnotab = NULL; - - v = NULL; - - /* XXX ignore long->int overflows for now */ - argcount = (int)r_long(p); - kwonlyargcount = (int)r_long(p); - nlocals = (int)r_long(p); - stacksize = (int)r_long(p); - flags = (int)r_long(p); - code = r_object(p); - if (code == NULL) - goto code_error; - consts = r_object(p); - if (consts == NULL) - goto code_error; - names = r_object(p); - if (names == NULL) - goto code_error; - varnames = r_object(p); - if (varnames == NULL) - goto code_error; - freevars = r_object(p); - if (freevars == NULL) - goto code_error; - cellvars = r_object(p); - if (cellvars == NULL) - goto code_error; - filename = r_object(p); - if (filename == NULL) - goto code_error; - name = r_object(p); - if (name == NULL) - goto code_error; - firstlineno = (int)r_long(p); - lnotab = r_object(p); - if (lnotab == NULL) - goto code_error; - - v = (PyObject *) PyCode_New( - argcount, kwonlyargcount, - nlocals, stacksize, flags, - code, consts, names, varnames, - freevars, cellvars, filename, name, - firstlineno, lnotab); - - code_error: - Py_XDECREF(code); - Py_XDECREF(consts); - Py_XDECREF(names); - Py_XDECREF(varnames); - Py_XDECREF(freevars); - Py_XDECREF(cellvars); - Py_XDECREF(filename); - Py_XDECREF(name); - Py_XDECREF(lnotab); - } - retval = v; - break; - - default: - /* Bogus data got written, which isn't ideal. - This will let you keep working and recover. */ - PyErr_SetString(PyExc_ValueError, "bad marshal data (unknown type code)"); - retval = NULL; - break; - - } - p->depth--; - return retval; + /* NULL is a valid return value, it does not necessarily means that + an exception is set. */ + PyObject *v, *v2; + long i, n; + int type = r_byte(p); + PyObject *retval; + + p->depth++; + + if (p->depth > MAX_MARSHAL_STACK_DEPTH) { + p->depth--; + PyErr_SetString(PyExc_ValueError, "recursion limit exceeded"); + return NULL; + } + + switch (type) { + + case EOF: + PyErr_SetString(PyExc_EOFError, + "EOF read where object expected"); + retval = NULL; + break; + + case TYPE_NULL: + retval = NULL; + break; + + case TYPE_NONE: + Py_INCREF(Py_None); + retval = Py_None; + break; + + case TYPE_STOPITER: + Py_INCREF(PyExc_StopIteration); + retval = PyExc_StopIteration; + break; + + case TYPE_ELLIPSIS: + Py_INCREF(Py_Ellipsis); + retval = Py_Ellipsis; + break; + + case TYPE_FALSE: + Py_INCREF(Py_False); + retval = Py_False; + break; + + case TYPE_TRUE: + Py_INCREF(Py_True); + retval = Py_True; + break; + + case TYPE_INT: + retval = PyLong_FromLong(r_long(p)); + break; + + case TYPE_INT64: + retval = r_long64(p); + break; + + case TYPE_LONG: + retval = r_PyLong(p); + break; + + case TYPE_FLOAT: + { + char buf[256]; + double dx; + retval = NULL; + n = r_byte(p); + if (n == EOF || r_string(buf, (int)n, p) != n) { + PyErr_SetString(PyExc_EOFError, + "EOF read where object expected"); + break; + } + buf[n] = '\0'; + dx = PyOS_string_to_double(buf, NULL, NULL); + if (dx == -1.0 && PyErr_Occurred()) + break; + retval = PyFloat_FromDouble(dx); + break; + } + + case TYPE_BINARY_FLOAT: + { + unsigned char buf[8]; + double x; + if (r_string((char*)buf, 8, p) != 8) { + PyErr_SetString(PyExc_EOFError, + "EOF read where object expected"); + retval = NULL; + break; + } + x = _PyFloat_Unpack8(buf, 1); + if (x == -1.0 && PyErr_Occurred()) { + retval = NULL; + break; + } + retval = PyFloat_FromDouble(x); + break; + } + + case TYPE_COMPLEX: + { + char buf[256]; + Py_complex c; + retval = NULL; + n = r_byte(p); + if (n == EOF || r_string(buf, (int)n, p) != n) { + PyErr_SetString(PyExc_EOFError, + "EOF read where object expected"); + break; + } + buf[n] = '\0'; + c.real = PyOS_string_to_double(buf, NULL, NULL); + if (c.real == -1.0 && PyErr_Occurred()) + break; + n = r_byte(p); + if (n == EOF || r_string(buf, (int)n, p) != n) { + PyErr_SetString(PyExc_EOFError, + "EOF read where object expected"); + break; + } + buf[n] = '\0'; + c.imag = PyOS_string_to_double(buf, NULL, NULL); + if (c.imag == -1.0 && PyErr_Occurred()) + break; + retval = PyComplex_FromCComplex(c); + break; + } + + case TYPE_BINARY_COMPLEX: + { + unsigned char buf[8]; + Py_complex c; + if (r_string((char*)buf, 8, p) != 8) { + PyErr_SetString(PyExc_EOFError, + "EOF read where object expected"); + retval = NULL; + break; + } + c.real = _PyFloat_Unpack8(buf, 1); + if (c.real == -1.0 && PyErr_Occurred()) { + retval = NULL; + break; + } + if (r_string((char*)buf, 8, p) != 8) { + PyErr_SetString(PyExc_EOFError, + "EOF read where object expected"); + retval = NULL; + break; + } + c.imag = _PyFloat_Unpack8(buf, 1); + if (c.imag == -1.0 && PyErr_Occurred()) { + retval = NULL; + break; + } + retval = PyComplex_FromCComplex(c); + break; + } + + case TYPE_STRING: + n = r_long(p); + if (n < 0 || n > INT_MAX) { + PyErr_SetString(PyExc_ValueError, "bad marshal data (string size out of range)"); + retval = NULL; + break; + } + v = PyBytes_FromStringAndSize((char *)NULL, n); + if (v == NULL) { + retval = NULL; + break; + } + if (r_string(PyBytes_AS_STRING(v), (int)n, p) != n) { + Py_DECREF(v); + PyErr_SetString(PyExc_EOFError, + "EOF read where object expected"); + retval = NULL; + break; + } + retval = v; + break; + + case TYPE_UNICODE: + { + char *buffer; + + n = r_long(p); + if (n < 0 || n > INT_MAX) { + PyErr_SetString(PyExc_ValueError, "bad marshal data (unicode size out of range)"); + retval = NULL; + break; + } + buffer = PyMem_NEW(char, n); + if (buffer == NULL) { + retval = PyErr_NoMemory(); + break; + } + if (r_string(buffer, (int)n, p) != n) { + PyMem_DEL(buffer); + PyErr_SetString(PyExc_EOFError, + "EOF read where object expected"); + retval = NULL; + break; + } + v = PyUnicode_DecodeUTF8(buffer, n, "surrogatepass"); + PyMem_DEL(buffer); + retval = v; + break; + } + + case TYPE_TUPLE: + n = r_long(p); + if (n < 0 || n > INT_MAX) { + PyErr_SetString(PyExc_ValueError, "bad marshal data (tuple size out of range)"); + retval = NULL; + break; + } + v = PyTuple_New((int)n); + if (v == NULL) { + retval = NULL; + break; + } + for (i = 0; i < n; i++) { + v2 = r_object(p); + if ( v2 == NULL ) { + if (!PyErr_Occurred()) + PyErr_SetString(PyExc_TypeError, + "NULL object in marshal data for tuple"); + Py_DECREF(v); + v = NULL; + break; + } + PyTuple_SET_ITEM(v, (int)i, v2); + } + retval = v; + break; + + case TYPE_LIST: + n = r_long(p); + if (n < 0 || n > INT_MAX) { + PyErr_SetString(PyExc_ValueError, "bad marshal data (list size out of range)"); + retval = NULL; + break; + } + v = PyList_New((int)n); + if (v == NULL) { + retval = NULL; + break; + } + for (i = 0; i < n; i++) { + v2 = r_object(p); + if ( v2 == NULL ) { + if (!PyErr_Occurred()) + PyErr_SetString(PyExc_TypeError, + "NULL object in marshal data for list"); + Py_DECREF(v); + v = NULL; + break; + } + PyList_SET_ITEM(v, (int)i, v2); + } + retval = v; + break; + + case TYPE_DICT: + v = PyDict_New(); + if (v == NULL) { + retval = NULL; + break; + } + for (;;) { + PyObject *key, *val; + key = r_object(p); + if (key == NULL) + break; + val = r_object(p); + if (val != NULL) + PyDict_SetItem(v, key, val); + Py_DECREF(key); + Py_XDECREF(val); + } + if (PyErr_Occurred()) { + Py_DECREF(v); + v = NULL; + } + retval = v; + break; + + case TYPE_SET: + case TYPE_FROZENSET: + n = r_long(p); + if (n < 0 || n > INT_MAX) { + PyErr_SetString(PyExc_ValueError, "bad marshal data (set size out of range)"); + retval = NULL; + break; + } + v = (type == TYPE_SET) ? PySet_New(NULL) : PyFrozenSet_New(NULL); + if (v == NULL) { + retval = NULL; + break; + } + for (i = 0; i < n; i++) { + v2 = r_object(p); + if ( v2 == NULL ) { + if (!PyErr_Occurred()) + PyErr_SetString(PyExc_TypeError, + "NULL object in marshal data for set"); + Py_DECREF(v); + v = NULL; + break; + } + if (PySet_Add(v, v2) == -1) { + Py_DECREF(v); + Py_DECREF(v2); + v = NULL; + break; + } + Py_DECREF(v2); + } + retval = v; + break; + + case TYPE_CODE: + { + int argcount; + int kwonlyargcount; + int nlocals; + int stacksize; + int flags; + PyObject *code = NULL; + PyObject *consts = NULL; + PyObject *names = NULL; + PyObject *varnames = NULL; + PyObject *freevars = NULL; + PyObject *cellvars = NULL; + PyObject *filename = NULL; + PyObject *name = NULL; + int firstlineno; + PyObject *lnotab = NULL; + + v = NULL; + + /* XXX ignore long->int overflows for now */ + argcount = (int)r_long(p); + kwonlyargcount = (int)r_long(p); + nlocals = (int)r_long(p); + stacksize = (int)r_long(p); + flags = (int)r_long(p); + code = r_object(p); + if (code == NULL) + goto code_error; + consts = r_object(p); + if (consts == NULL) + goto code_error; + names = r_object(p); + if (names == NULL) + goto code_error; + varnames = r_object(p); + if (varnames == NULL) + goto code_error; + freevars = r_object(p); + if (freevars == NULL) + goto code_error; + cellvars = r_object(p); + if (cellvars == NULL) + goto code_error; + filename = r_object(p); + if (filename == NULL) + goto code_error; + name = r_object(p); + if (name == NULL) + goto code_error; + firstlineno = (int)r_long(p); + lnotab = r_object(p); + if (lnotab == NULL) + goto code_error; + + v = (PyObject *) PyCode_New( + argcount, kwonlyargcount, + nlocals, stacksize, flags, + code, consts, names, varnames, + freevars, cellvars, filename, name, + firstlineno, lnotab); + + code_error: + Py_XDECREF(code); + Py_XDECREF(consts); + Py_XDECREF(names); + Py_XDECREF(varnames); + Py_XDECREF(freevars); + Py_XDECREF(cellvars); + Py_XDECREF(filename); + Py_XDECREF(name); + Py_XDECREF(lnotab); + } + retval = v; + break; + + default: + /* Bogus data got written, which isn't ideal. + This will let you keep working and recover. */ + PyErr_SetString(PyExc_ValueError, "bad marshal data (unknown type code)"); + retval = NULL; + break; + + } + p->depth--; + return retval; } static PyObject * read_object(RFILE *p) { - PyObject *v; - if (PyErr_Occurred()) { - fprintf(stderr, "XXX readobject called with exception set\n"); - return NULL; - } - v = r_object(p); - if (v == NULL && !PyErr_Occurred()) - PyErr_SetString(PyExc_TypeError, "NULL object in marshal data for object"); - return v; + PyObject *v; + if (PyErr_Occurred()) { + fprintf(stderr, "XXX readobject called with exception set\n"); + return NULL; + } + v = r_object(p); + if (v == NULL && !PyErr_Occurred()) + PyErr_SetString(PyExc_TypeError, "NULL object in marshal data for object"); + return v; } int PyMarshal_ReadShortFromFile(FILE *fp) { - RFILE rf; - assert(fp); - rf.fp = fp; - rf.strings = NULL; - rf.end = rf.ptr = NULL; - return r_short(&rf); + RFILE rf; + assert(fp); + rf.fp = fp; + rf.strings = NULL; + rf.end = rf.ptr = NULL; + return r_short(&rf); } long PyMarshal_ReadLongFromFile(FILE *fp) { - RFILE rf; - rf.fp = fp; - rf.strings = NULL; - rf.ptr = rf.end = NULL; - return r_long(&rf); + RFILE rf; + rf.fp = fp; + rf.strings = NULL; + rf.ptr = rf.end = NULL; + return r_long(&rf); } #ifdef HAVE_FSTAT @@ -1061,11 +1061,11 @@ static off_t getfilesize(FILE *fp) { - struct stat st; - if (fstat(fileno(fp), &st) != 0) - return -1; - else - return st.st_size; + struct stat st; + if (fstat(fileno(fp), &st) != 0) + return -1; + else + return st.st_size; } #endif @@ -1081,27 +1081,27 @@ /* REASONABLE_FILE_LIMIT is by defn something big enough for Tkinter.pyc. */ #define REASONABLE_FILE_LIMIT (1L << 18) #ifdef HAVE_FSTAT - off_t filesize; - filesize = getfilesize(fp); - if (filesize > 0 && filesize <= REASONABLE_FILE_LIMIT) { - char* pBuf = (char *)PyMem_MALLOC(filesize); - if (pBuf != NULL) { - PyObject* v; - size_t n; - /* filesize must fit into an int, because it - is smaller than REASONABLE_FILE_LIMIT */ - n = fread(pBuf, 1, (int)filesize, fp); - v = PyMarshal_ReadObjectFromString(pBuf, n); - PyMem_FREE(pBuf); - return v; - } + off_t filesize; + filesize = getfilesize(fp); + if (filesize > 0 && filesize <= REASONABLE_FILE_LIMIT) { + char* pBuf = (char *)PyMem_MALLOC(filesize); + if (pBuf != NULL) { + PyObject* v; + size_t n; + /* filesize must fit into an int, because it + is smaller than REASONABLE_FILE_LIMIT */ + n = fread(pBuf, 1, (int)filesize, fp); + v = PyMarshal_ReadObjectFromString(pBuf, n); + PyMem_FREE(pBuf); + return v; + } - } + } #endif - /* We don't have fstat, or we do but the file is larger than - * REASONABLE_FILE_LIMIT or malloc failed -- read a byte at a time. - */ - return PyMarshal_ReadObjectFromFile(fp); + /* We don't have fstat, or we do but the file is larger than + * REASONABLE_FILE_LIMIT or malloc failed -- read a byte at a time. + */ + return PyMarshal_ReadObjectFromFile(fp); #undef REASONABLE_FILE_LIMIT } @@ -1109,77 +1109,77 @@ PyObject * PyMarshal_ReadObjectFromFile(FILE *fp) { - RFILE rf; - PyObject *result; - rf.fp = fp; - rf.strings = PyList_New(0); - rf.depth = 0; - rf.ptr = rf.end = NULL; - result = r_object(&rf); - Py_DECREF(rf.strings); - return result; + RFILE rf; + PyObject *result; + rf.fp = fp; + rf.strings = PyList_New(0); + rf.depth = 0; + rf.ptr = rf.end = NULL; + result = r_object(&rf); + Py_DECREF(rf.strings); + return result; } PyObject * PyMarshal_ReadObjectFromString(char *str, Py_ssize_t len) { - RFILE rf; - PyObject *result; - rf.fp = NULL; - rf.ptr = str; - rf.end = str + len; - rf.strings = PyList_New(0); - rf.depth = 0; - result = r_object(&rf); - Py_DECREF(rf.strings); - return result; + RFILE rf; + PyObject *result; + rf.fp = NULL; + rf.ptr = str; + rf.end = str + len; + rf.strings = PyList_New(0); + rf.depth = 0; + result = r_object(&rf); + Py_DECREF(rf.strings); + return result; } PyObject * PyMarshal_WriteObjectToString(PyObject *x, int version) { - WFILE wf; - PyObject *res = NULL; + WFILE wf; + PyObject *res = NULL; - wf.fp = NULL; - wf.str = PyBytes_FromStringAndSize((char *)NULL, 50); - if (wf.str == NULL) - return NULL; - wf.ptr = PyBytes_AS_STRING((PyBytesObject *)wf.str); - wf.end = wf.ptr + PyBytes_Size(wf.str); - wf.error = WFERR_OK; - wf.depth = 0; - wf.version = version; - wf.strings = (version > 0) ? PyDict_New() : NULL; - w_object(x, &wf); - Py_XDECREF(wf.strings); - if (wf.str != NULL) { - char *base = PyBytes_AS_STRING((PyBytesObject *)wf.str); - if (wf.ptr - base > PY_SSIZE_T_MAX) { - Py_DECREF(wf.str); - PyErr_SetString(PyExc_OverflowError, - "too much marshal data for a string"); - return NULL; - } - if (_PyBytes_Resize(&wf.str, (Py_ssize_t)(wf.ptr - base)) < 0) - return NULL; - } - if (wf.error != WFERR_OK) { - Py_XDECREF(wf.str); - if (wf.error == WFERR_NOMEMORY) - PyErr_NoMemory(); - else - PyErr_SetString(PyExc_ValueError, - (wf.error==WFERR_UNMARSHALLABLE)?"unmarshallable object" - :"object too deeply nested to marshal"); - return NULL; - } - if (wf.str != NULL) { - /* XXX Quick hack -- need to do this differently */ - res = PyBytes_FromObject(wf.str); - Py_DECREF(wf.str); - } - return res; + wf.fp = NULL; + wf.str = PyBytes_FromStringAndSize((char *)NULL, 50); + if (wf.str == NULL) + return NULL; + wf.ptr = PyBytes_AS_STRING((PyBytesObject *)wf.str); + wf.end = wf.ptr + PyBytes_Size(wf.str); + wf.error = WFERR_OK; + wf.depth = 0; + wf.version = version; + wf.strings = (version > 0) ? PyDict_New() : NULL; + w_object(x, &wf); + Py_XDECREF(wf.strings); + if (wf.str != NULL) { + char *base = PyBytes_AS_STRING((PyBytesObject *)wf.str); + if (wf.ptr - base > PY_SSIZE_T_MAX) { + Py_DECREF(wf.str); + PyErr_SetString(PyExc_OverflowError, + "too much marshal data for a string"); + return NULL; + } + if (_PyBytes_Resize(&wf.str, (Py_ssize_t)(wf.ptr - base)) < 0) + return NULL; + } + if (wf.error != WFERR_OK) { + Py_XDECREF(wf.str); + if (wf.error == WFERR_NOMEMORY) + PyErr_NoMemory(); + else + PyErr_SetString(PyExc_ValueError, + (wf.error==WFERR_UNMARSHALLABLE)?"unmarshallable object" + :"object too deeply nested to marshal"); + return NULL; + } + if (wf.str != NULL) { + /* XXX Quick hack -- need to do this differently */ + res = PyBytes_FromObject(wf.str); + Py_DECREF(wf.str); + } + return res; } /* And an interface for Python programs... */ @@ -1187,20 +1187,20 @@ static PyObject * marshal_dump(PyObject *self, PyObject *args) { - /* XXX Quick hack -- need to do this differently */ - PyObject *x; - PyObject *f; - int version = Py_MARSHAL_VERSION; - PyObject *s; - PyObject *res; - if (!PyArg_ParseTuple(args, "OO|i:dump", &x, &f, &version)) - return NULL; - s = PyMarshal_WriteObjectToString(x, version); - if (s == NULL) - return NULL; - res = PyObject_CallMethod(f, "write", "O", s); - Py_DECREF(s); - return res; + /* XXX Quick hack -- need to do this differently */ + PyObject *x; + PyObject *f; + int version = Py_MARSHAL_VERSION; + PyObject *s; + PyObject *res; + if (!PyArg_ParseTuple(args, "OO|i:dump", &x, &f, &version)) + return NULL; + s = PyMarshal_WriteObjectToString(x, version); + if (s == NULL) + return NULL; + res = PyObject_CallMethod(f, "write", "O", s); + Py_DECREF(s); + return res; } PyDoc_STRVAR(dump_doc, @@ -1219,35 +1219,35 @@ static PyObject * marshal_load(PyObject *self, PyObject *f) { - /* XXX Quick hack -- need to do this differently */ - PyObject *data, *result; - RFILE rf; - data = PyObject_CallMethod(f, "read", ""); - if (data == NULL) - return NULL; - rf.fp = NULL; - if (PyBytes_Check(data)) { - rf.ptr = PyBytes_AS_STRING(data); - rf.end = rf.ptr + PyBytes_GET_SIZE(data); - } - else if (PyBytes_Check(data)) { - rf.ptr = PyBytes_AS_STRING(data); - rf.end = rf.ptr + PyBytes_GET_SIZE(data); - } - else { - PyErr_Format(PyExc_TypeError, - "f.read() returned neither string " - "nor bytes but %.100s", - data->ob_type->tp_name); - Py_DECREF(data); - return NULL; - } - rf.strings = PyList_New(0); - rf.depth = 0; - result = read_object(&rf); - Py_DECREF(rf.strings); - Py_DECREF(data); - return result; + /* XXX Quick hack -- need to do this differently */ + PyObject *data, *result; + RFILE rf; + data = PyObject_CallMethod(f, "read", ""); + if (data == NULL) + return NULL; + rf.fp = NULL; + if (PyBytes_Check(data)) { + rf.ptr = PyBytes_AS_STRING(data); + rf.end = rf.ptr + PyBytes_GET_SIZE(data); + } + else if (PyBytes_Check(data)) { + rf.ptr = PyBytes_AS_STRING(data); + rf.end = rf.ptr + PyBytes_GET_SIZE(data); + } + else { + PyErr_Format(PyExc_TypeError, + "f.read() returned neither string " + "nor bytes but %.100s", + data->ob_type->tp_name); + Py_DECREF(data); + return NULL; + } + rf.strings = PyList_New(0); + rf.depth = 0; + result = read_object(&rf); + Py_DECREF(rf.strings); + Py_DECREF(data); + return result; } PyDoc_STRVAR(load_doc, @@ -1266,11 +1266,11 @@ static PyObject * marshal_dumps(PyObject *self, PyObject *args) { - PyObject *x; - int version = Py_MARSHAL_VERSION; - if (!PyArg_ParseTuple(args, "O|i:dumps", &x, &version)) - return NULL; - return PyMarshal_WriteObjectToString(x, version); + PyObject *x; + int version = Py_MARSHAL_VERSION; + if (!PyArg_ParseTuple(args, "O|i:dumps", &x, &version)) + return NULL; + return PyMarshal_WriteObjectToString(x, version); } PyDoc_STRVAR(dumps_doc, @@ -1286,24 +1286,24 @@ static PyObject * marshal_loads(PyObject *self, PyObject *args) { - RFILE rf; - Py_buffer p; - char *s; - Py_ssize_t n; - PyObject* result; - if (!PyArg_ParseTuple(args, "s*:loads", &p)) - return NULL; - s = p.buf; - n = p.len; - rf.fp = NULL; - rf.ptr = s; - rf.end = s + n; - rf.strings = PyList_New(0); - rf.depth = 0; - result = read_object(&rf); - Py_DECREF(rf.strings); - PyBuffer_Release(&p); - return result; + RFILE rf; + Py_buffer p; + char *s; + Py_ssize_t n; + PyObject* result; + if (!PyArg_ParseTuple(args, "s*:loads", &p)) + return NULL; + s = p.buf; + n = p.len; + rf.fp = NULL; + rf.ptr = s; + rf.end = s + n; + rf.strings = PyList_New(0); + rf.depth = 0; + result = read_object(&rf); + Py_DECREF(rf.strings); + PyBuffer_Release(&p); + return result; } PyDoc_STRVAR(loads_doc, @@ -1314,11 +1314,11 @@ ignored."); static PyMethodDef marshal_methods[] = { - {"dump", marshal_dump, METH_VARARGS, dump_doc}, - {"load", marshal_load, METH_O, load_doc}, - {"dumps", marshal_dumps, METH_VARARGS, dumps_doc}, - {"loads", marshal_loads, METH_VARARGS, loads_doc}, - {NULL, NULL} /* sentinel */ + {"dump", marshal_dump, METH_VARARGS, dump_doc}, + {"load", marshal_load, METH_O, load_doc}, + {"dumps", marshal_dumps, METH_VARARGS, dumps_doc}, + {"loads", marshal_loads, METH_VARARGS, loads_doc}, + {NULL, NULL} /* sentinel */ }; @@ -1353,23 +1353,23 @@ static struct PyModuleDef marshalmodule = { - PyModuleDef_HEAD_INIT, - "marshal", - module_doc, - 0, - marshal_methods, - NULL, - NULL, - NULL, - NULL + PyModuleDef_HEAD_INIT, + "marshal", + module_doc, + 0, + marshal_methods, + NULL, + NULL, + NULL, + NULL }; PyMODINIT_FUNC PyMarshal_Init(void) { - PyObject *mod = PyModule_Create(&marshalmodule); - if (mod == NULL) - return NULL; - PyModule_AddIntConstant(mod, "version", Py_MARSHAL_VERSION); - return mod; + PyObject *mod = PyModule_Create(&marshalmodule); + if (mod == NULL) + return NULL; + PyModule_AddIntConstant(mod, "version", Py_MARSHAL_VERSION); + return mod; } Modified: python/branches/py3k-jit/Python/modsupport.c ============================================================================== --- python/branches/py3k-jit/Python/modsupport.c (original) +++ python/branches/py3k-jit/Python/modsupport.c Mon May 10 23:55:43 2010 @@ -16,41 +16,41 @@ static int countformat(const char *format, int endchar) { - int count = 0; - int level = 0; - while (level > 0 || *format != endchar) { - switch (*format) { - case '\0': - /* Premature end */ - PyErr_SetString(PyExc_SystemError, - "unmatched paren in format"); - return -1; - case '(': - case '[': - case '{': - if (level == 0) - count++; - level++; - break; - case ')': - case ']': - case '}': - level--; - break; - case '#': - case '&': - case ',': - case ':': - case ' ': - case '\t': - break; - default: - if (level == 0) - count++; - } - format++; - } - return count; + int count = 0; + int level = 0; + while (level > 0 || *format != endchar) { + switch (*format) { + case '\0': + /* Premature end */ + PyErr_SetString(PyExc_SystemError, + "unmatched paren in format"); + return -1; + case '(': + case '[': + case '{': + if (level == 0) + count++; + level++; + break; + case ')': + case ']': + case '}': + level--; + break; + case '#': + case '&': + case ',': + case ':': + case ' ': + case '\t': + break; + default: + if (level == 0) + count++; + } + format++; + } + return count; } @@ -66,550 +66,550 @@ static PyObject * do_mkdict(const char **p_format, va_list *p_va, int endchar, int n, int flags) { - PyObject *d; - int i; - int itemfailed = 0; - if (n < 0) - return NULL; - if ((d = PyDict_New()) == NULL) - return NULL; - /* Note that we can't bail immediately on error as this will leak - refcounts on any 'N' arguments. */ - for (i = 0; i < n; i+= 2) { - PyObject *k, *v; - int err; - k = do_mkvalue(p_format, p_va, flags); - if (k == NULL) { - itemfailed = 1; - Py_INCREF(Py_None); - k = Py_None; - } - v = do_mkvalue(p_format, p_va, flags); - if (v == NULL) { - itemfailed = 1; - Py_INCREF(Py_None); - v = Py_None; - } - err = PyDict_SetItem(d, k, v); - Py_DECREF(k); - Py_DECREF(v); - if (err < 0 || itemfailed) { - Py_DECREF(d); - return NULL; - } - } - if (d != NULL && **p_format != endchar) { - Py_DECREF(d); - d = NULL; - PyErr_SetString(PyExc_SystemError, - "Unmatched paren in format"); - } - else if (endchar) - ++*p_format; - return d; + PyObject *d; + int i; + int itemfailed = 0; + if (n < 0) + return NULL; + if ((d = PyDict_New()) == NULL) + return NULL; + /* Note that we can't bail immediately on error as this will leak + refcounts on any 'N' arguments. */ + for (i = 0; i < n; i+= 2) { + PyObject *k, *v; + int err; + k = do_mkvalue(p_format, p_va, flags); + if (k == NULL) { + itemfailed = 1; + Py_INCREF(Py_None); + k = Py_None; + } + v = do_mkvalue(p_format, p_va, flags); + if (v == NULL) { + itemfailed = 1; + Py_INCREF(Py_None); + v = Py_None; + } + err = PyDict_SetItem(d, k, v); + Py_DECREF(k); + Py_DECREF(v); + if (err < 0 || itemfailed) { + Py_DECREF(d); + return NULL; + } + } + if (d != NULL && **p_format != endchar) { + Py_DECREF(d); + d = NULL; + PyErr_SetString(PyExc_SystemError, + "Unmatched paren in format"); + } + else if (endchar) + ++*p_format; + return d; } static PyObject * do_mklist(const char **p_format, va_list *p_va, int endchar, int n, int flags) { - PyObject *v; - int i; - int itemfailed = 0; - if (n < 0) - return NULL; - v = PyList_New(n); - if (v == NULL) - return NULL; - /* Note that we can't bail immediately on error as this will leak - refcounts on any 'N' arguments. */ - for (i = 0; i < n; i++) { - PyObject *w = do_mkvalue(p_format, p_va, flags); - if (w == NULL) { - itemfailed = 1; - Py_INCREF(Py_None); - w = Py_None; - } - PyList_SET_ITEM(v, i, w); - } - - if (itemfailed) { - /* do_mkvalue() should have already set an error */ - Py_DECREF(v); - return NULL; - } - if (**p_format != endchar) { - Py_DECREF(v); - PyErr_SetString(PyExc_SystemError, - "Unmatched paren in format"); - return NULL; - } - if (endchar) - ++*p_format; - return v; + PyObject *v; + int i; + int itemfailed = 0; + if (n < 0) + return NULL; + v = PyList_New(n); + if (v == NULL) + return NULL; + /* Note that we can't bail immediately on error as this will leak + refcounts on any 'N' arguments. */ + for (i = 0; i < n; i++) { + PyObject *w = do_mkvalue(p_format, p_va, flags); + if (w == NULL) { + itemfailed = 1; + Py_INCREF(Py_None); + w = Py_None; + } + PyList_SET_ITEM(v, i, w); + } + + if (itemfailed) { + /* do_mkvalue() should have already set an error */ + Py_DECREF(v); + return NULL; + } + if (**p_format != endchar) { + Py_DECREF(v); + PyErr_SetString(PyExc_SystemError, + "Unmatched paren in format"); + return NULL; + } + if (endchar) + ++*p_format; + return v; } static int _ustrlen(Py_UNICODE *u) { - int i = 0; - Py_UNICODE *v = u; - while (*v != 0) { i++; v++; } - return i; + int i = 0; + Py_UNICODE *v = u; + while (*v != 0) { i++; v++; } + return i; } static PyObject * do_mktuple(const char **p_format, va_list *p_va, int endchar, int n, int flags) { - PyObject *v; - int i; - int itemfailed = 0; - if (n < 0) - return NULL; - if ((v = PyTuple_New(n)) == NULL) - return NULL; - /* Note that we can't bail immediately on error as this will leak - refcounts on any 'N' arguments. */ - for (i = 0; i < n; i++) { - PyObject *w = do_mkvalue(p_format, p_va, flags); - if (w == NULL) { - itemfailed = 1; - Py_INCREF(Py_None); - w = Py_None; - } - PyTuple_SET_ITEM(v, i, w); - } - if (itemfailed) { - /* do_mkvalue() should have already set an error */ - Py_DECREF(v); - return NULL; - } - if (**p_format != endchar) { - Py_DECREF(v); - PyErr_SetString(PyExc_SystemError, - "Unmatched paren in format"); - return NULL; - } - if (endchar) - ++*p_format; - return v; + PyObject *v; + int i; + int itemfailed = 0; + if (n < 0) + return NULL; + if ((v = PyTuple_New(n)) == NULL) + return NULL; + /* Note that we can't bail immediately on error as this will leak + refcounts on any 'N' arguments. */ + for (i = 0; i < n; i++) { + PyObject *w = do_mkvalue(p_format, p_va, flags); + if (w == NULL) { + itemfailed = 1; + Py_INCREF(Py_None); + w = Py_None; + } + PyTuple_SET_ITEM(v, i, w); + } + if (itemfailed) { + /* do_mkvalue() should have already set an error */ + Py_DECREF(v); + return NULL; + } + if (**p_format != endchar) { + Py_DECREF(v); + PyErr_SetString(PyExc_SystemError, + "Unmatched paren in format"); + return NULL; + } + if (endchar) + ++*p_format; + return v; } static PyObject * do_mkvalue(const char **p_format, va_list *p_va, int flags) { - for (;;) { - switch (*(*p_format)++) { - case '(': - return do_mktuple(p_format, p_va, ')', - countformat(*p_format, ')'), flags); - - case '[': - return do_mklist(p_format, p_va, ']', - countformat(*p_format, ']'), flags); - - case '{': - return do_mkdict(p_format, p_va, '}', - countformat(*p_format, '}'), flags); - - case 'b': - case 'B': - case 'h': - case 'i': - return PyLong_FromLong((long)va_arg(*p_va, int)); - - case 'H': - return PyLong_FromLong((long)va_arg(*p_va, unsigned int)); - - case 'I': - { - unsigned int n; - n = va_arg(*p_va, unsigned int); - return PyLong_FromUnsignedLong(n); - } - - case 'n': + for (;;) { + switch (*(*p_format)++) { + case '(': + return do_mktuple(p_format, p_va, ')', + countformat(*p_format, ')'), flags); + + case '[': + return do_mklist(p_format, p_va, ']', + countformat(*p_format, ']'), flags); + + case '{': + return do_mkdict(p_format, p_va, '}', + countformat(*p_format, '}'), flags); + + case 'b': + case 'B': + case 'h': + case 'i': + return PyLong_FromLong((long)va_arg(*p_va, int)); + + case 'H': + return PyLong_FromLong((long)va_arg(*p_va, unsigned int)); + + case 'I': + { + unsigned int n; + n = va_arg(*p_va, unsigned int); + return PyLong_FromUnsignedLong(n); + } + + case 'n': #if SIZEOF_SIZE_T!=SIZEOF_LONG - return PyLong_FromSsize_t(va_arg(*p_va, Py_ssize_t)); + return PyLong_FromSsize_t(va_arg(*p_va, Py_ssize_t)); #endif - /* Fall through from 'n' to 'l' if Py_ssize_t is long */ - case 'l': - return PyLong_FromLong(va_arg(*p_va, long)); - - case 'k': - { - unsigned long n; - n = va_arg(*p_va, unsigned long); - return PyLong_FromUnsignedLong(n); - } + /* Fall through from 'n' to 'l' if Py_ssize_t is long */ + case 'l': + return PyLong_FromLong(va_arg(*p_va, long)); + + case 'k': + { + unsigned long n; + n = va_arg(*p_va, unsigned long); + return PyLong_FromUnsignedLong(n); + } #ifdef HAVE_LONG_LONG - case 'L': - return PyLong_FromLongLong((PY_LONG_LONG)va_arg(*p_va, PY_LONG_LONG)); + case 'L': + return PyLong_FromLongLong((PY_LONG_LONG)va_arg(*p_va, PY_LONG_LONG)); - case 'K': - return PyLong_FromUnsignedLongLong((PY_LONG_LONG)va_arg(*p_va, unsigned PY_LONG_LONG)); + case 'K': + return PyLong_FromUnsignedLongLong((PY_LONG_LONG)va_arg(*p_va, unsigned PY_LONG_LONG)); #endif - case 'u': - { - PyObject *v; - Py_UNICODE *u = va_arg(*p_va, Py_UNICODE *); - Py_ssize_t n; - if (**p_format == '#') { - ++*p_format; - if (flags & FLAG_SIZE_T) - n = va_arg(*p_va, Py_ssize_t); - else - n = va_arg(*p_va, int); - } - else - n = -1; - if (u == NULL) { - v = Py_None; - Py_INCREF(v); - } - else { - if (n < 0) - n = _ustrlen(u); - v = PyUnicode_FromUnicode(u, n); - } - return v; - } - case 'f': - case 'd': - return PyFloat_FromDouble( - (double)va_arg(*p_va, va_double)); - - case 'D': - return PyComplex_FromCComplex( - *((Py_complex *)va_arg(*p_va, Py_complex *))); - - case 'c': - { - char p[1]; - p[0] = (char)va_arg(*p_va, int); - return PyBytes_FromStringAndSize(p, 1); - } - case 'C': - { - int i = va_arg(*p_va, int); - if (i < 0 || i > PyUnicode_GetMax()) { - PyErr_SetString(PyExc_OverflowError, - "%c arg not in range(0x110000)"); - return NULL; - } - return PyUnicode_FromOrdinal(i); - } - - case 's': - case 'z': - { - PyObject *v; - char *str = va_arg(*p_va, char *); - Py_ssize_t n; - if (**p_format == '#') { - ++*p_format; - if (flags & FLAG_SIZE_T) - n = va_arg(*p_va, Py_ssize_t); - else - n = va_arg(*p_va, int); - } - else - n = -1; - if (str == NULL) { - v = Py_None; - Py_INCREF(v); - } - else { - if (n < 0) { - size_t m = strlen(str); - if (m > PY_SSIZE_T_MAX) { - PyErr_SetString(PyExc_OverflowError, - "string too long for Python string"); - return NULL; - } - n = (Py_ssize_t)m; - } - v = PyUnicode_FromStringAndSize(str, n); - } - return v; - } - - case 'U': - { - PyObject *v; - char *str = va_arg(*p_va, char *); - Py_ssize_t n; - if (**p_format == '#') { - ++*p_format; - if (flags & FLAG_SIZE_T) - n = va_arg(*p_va, Py_ssize_t); - else - n = va_arg(*p_va, int); - } - else - n = -1; - if (str == NULL) { - v = Py_None; - Py_INCREF(v); - } - else { - if (n < 0) { - size_t m = strlen(str); - if (m > PY_SSIZE_T_MAX) { - PyErr_SetString(PyExc_OverflowError, - "string too long for Python string"); - return NULL; - } - n = (Py_ssize_t)m; - } - v = PyUnicode_FromStringAndSize(str, n); - } - return v; - } - - case 'y': - { - PyObject *v; - char *str = va_arg(*p_va, char *); - Py_ssize_t n; - if (**p_format == '#') { - ++*p_format; - if (flags & FLAG_SIZE_T) - n = va_arg(*p_va, Py_ssize_t); - else - n = va_arg(*p_va, int); - } - else - n = -1; - if (str == NULL) { - v = Py_None; - Py_INCREF(v); - } - else { - if (n < 0) { - size_t m = strlen(str); - if (m > PY_SSIZE_T_MAX) { - PyErr_SetString(PyExc_OverflowError, - "string too long for Python bytes"); - return NULL; - } - n = (Py_ssize_t)m; - } - v = PyBytes_FromStringAndSize(str, n); - } - return v; - } - - case 'N': - case 'S': - case 'O': - if (**p_format == '&') { - typedef PyObject *(*converter)(void *); - converter func = va_arg(*p_va, converter); - void *arg = va_arg(*p_va, void *); - ++*p_format; - return (*func)(arg); - } - else { - PyObject *v; - v = va_arg(*p_va, PyObject *); - if (v != NULL) { - if (*(*p_format - 1) != 'N') - Py_INCREF(v); - } - else if (!PyErr_Occurred()) - /* If a NULL was passed - * because a call that should - * have constructed a value - * failed, that's OK, and we - * pass the error on; but if - * no error occurred it's not - * clear that the caller knew - * what she was doing. */ - PyErr_SetString(PyExc_SystemError, - "NULL object passed to Py_BuildValue"); - return v; - } - - case ':': - case ',': - case ' ': - case '\t': - break; - - default: - PyErr_SetString(PyExc_SystemError, - "bad format char passed to Py_BuildValue"); - return NULL; + case 'u': + { + PyObject *v; + Py_UNICODE *u = va_arg(*p_va, Py_UNICODE *); + Py_ssize_t n; + if (**p_format == '#') { + ++*p_format; + if (flags & FLAG_SIZE_T) + n = va_arg(*p_va, Py_ssize_t); + else + n = va_arg(*p_va, int); + } + else + n = -1; + if (u == NULL) { + v = Py_None; + Py_INCREF(v); + } + else { + if (n < 0) + n = _ustrlen(u); + v = PyUnicode_FromUnicode(u, n); + } + return v; + } + case 'f': + case 'd': + return PyFloat_FromDouble( + (double)va_arg(*p_va, va_double)); + + case 'D': + return PyComplex_FromCComplex( + *((Py_complex *)va_arg(*p_va, Py_complex *))); + + case 'c': + { + char p[1]; + p[0] = (char)va_arg(*p_va, int); + return PyBytes_FromStringAndSize(p, 1); + } + case 'C': + { + int i = va_arg(*p_va, int); + if (i < 0 || i > PyUnicode_GetMax()) { + PyErr_SetString(PyExc_OverflowError, + "%c arg not in range(0x110000)"); + return NULL; + } + return PyUnicode_FromOrdinal(i); + } + + case 's': + case 'z': + { + PyObject *v; + char *str = va_arg(*p_va, char *); + Py_ssize_t n; + if (**p_format == '#') { + ++*p_format; + if (flags & FLAG_SIZE_T) + n = va_arg(*p_va, Py_ssize_t); + else + n = va_arg(*p_va, int); + } + else + n = -1; + if (str == NULL) { + v = Py_None; + Py_INCREF(v); + } + else { + if (n < 0) { + size_t m = strlen(str); + if (m > PY_SSIZE_T_MAX) { + PyErr_SetString(PyExc_OverflowError, + "string too long for Python string"); + return NULL; + } + n = (Py_ssize_t)m; + } + v = PyUnicode_FromStringAndSize(str, n); + } + return v; + } + + case 'U': + { + PyObject *v; + char *str = va_arg(*p_va, char *); + Py_ssize_t n; + if (**p_format == '#') { + ++*p_format; + if (flags & FLAG_SIZE_T) + n = va_arg(*p_va, Py_ssize_t); + else + n = va_arg(*p_va, int); + } + else + n = -1; + if (str == NULL) { + v = Py_None; + Py_INCREF(v); + } + else { + if (n < 0) { + size_t m = strlen(str); + if (m > PY_SSIZE_T_MAX) { + PyErr_SetString(PyExc_OverflowError, + "string too long for Python string"); + return NULL; + } + n = (Py_ssize_t)m; + } + v = PyUnicode_FromStringAndSize(str, n); + } + return v; + } + + case 'y': + { + PyObject *v; + char *str = va_arg(*p_va, char *); + Py_ssize_t n; + if (**p_format == '#') { + ++*p_format; + if (flags & FLAG_SIZE_T) + n = va_arg(*p_va, Py_ssize_t); + else + n = va_arg(*p_va, int); + } + else + n = -1; + if (str == NULL) { + v = Py_None; + Py_INCREF(v); + } + else { + if (n < 0) { + size_t m = strlen(str); + if (m > PY_SSIZE_T_MAX) { + PyErr_SetString(PyExc_OverflowError, + "string too long for Python bytes"); + return NULL; + } + n = (Py_ssize_t)m; + } + v = PyBytes_FromStringAndSize(str, n); + } + return v; + } + + case 'N': + case 'S': + case 'O': + if (**p_format == '&') { + typedef PyObject *(*converter)(void *); + converter func = va_arg(*p_va, converter); + void *arg = va_arg(*p_va, void *); + ++*p_format; + return (*func)(arg); + } + else { + PyObject *v; + v = va_arg(*p_va, PyObject *); + if (v != NULL) { + if (*(*p_format - 1) != 'N') + Py_INCREF(v); + } + else if (!PyErr_Occurred()) + /* If a NULL was passed + * because a call that should + * have constructed a value + * failed, that's OK, and we + * pass the error on; but if + * no error occurred it's not + * clear that the caller knew + * what she was doing. */ + PyErr_SetString(PyExc_SystemError, + "NULL object passed to Py_BuildValue"); + return v; + } + + case ':': + case ',': + case ' ': + case '\t': + break; + + default: + PyErr_SetString(PyExc_SystemError, + "bad format char passed to Py_BuildValue"); + return NULL; - } - } + } + } } PyObject * Py_BuildValue(const char *format, ...) { - va_list va; - PyObject* retval; - va_start(va, format); - retval = va_build_value(format, va, 0); - va_end(va); - return retval; + va_list va; + PyObject* retval; + va_start(va, format); + retval = va_build_value(format, va, 0); + va_end(va); + return retval; } PyObject * _Py_BuildValue_SizeT(const char *format, ...) { - va_list va; - PyObject* retval; - va_start(va, format); - retval = va_build_value(format, va, FLAG_SIZE_T); - va_end(va); - return retval; + va_list va; + PyObject* retval; + va_start(va, format); + retval = va_build_value(format, va, FLAG_SIZE_T); + va_end(va); + return retval; } PyObject * Py_VaBuildValue(const char *format, va_list va) { - return va_build_value(format, va, 0); + return va_build_value(format, va, 0); } PyObject * _Py_VaBuildValue_SizeT(const char *format, va_list va) { - return va_build_value(format, va, FLAG_SIZE_T); + return va_build_value(format, va, FLAG_SIZE_T); } static PyObject * va_build_value(const char *format, va_list va, int flags) { - const char *f = format; - int n = countformat(f, '\0'); - va_list lva; + const char *f = format; + int n = countformat(f, '\0'); + va_list lva; #ifdef VA_LIST_IS_ARRAY - memcpy(lva, va, sizeof(va_list)); + memcpy(lva, va, sizeof(va_list)); #else #ifdef __va_copy - __va_copy(lva, va); + __va_copy(lva, va); #else - lva = va; + lva = va; #endif #endif - if (n < 0) - return NULL; - if (n == 0) { - Py_INCREF(Py_None); - return Py_None; - } - if (n == 1) - return do_mkvalue(&f, &lva, flags); - return do_mktuple(&f, &lva, '\0', n, flags); + if (n < 0) + return NULL; + if (n == 0) { + Py_INCREF(Py_None); + return Py_None; + } + if (n == 1) + return do_mkvalue(&f, &lva, flags); + return do_mktuple(&f, &lva, '\0', n, flags); } PyObject * PyEval_CallFunction(PyObject *obj, const char *format, ...) { - va_list vargs; - PyObject *args; - PyObject *res; + va_list vargs; + PyObject *args; + PyObject *res; - va_start(vargs, format); + va_start(vargs, format); - args = Py_VaBuildValue(format, vargs); - va_end(vargs); + args = Py_VaBuildValue(format, vargs); + va_end(vargs); - if (args == NULL) - return NULL; + if (args == NULL) + return NULL; - res = PyEval_CallObject(obj, args); - Py_DECREF(args); + res = PyEval_CallObject(obj, args); + Py_DECREF(args); - return res; + return res; } PyObject * PyEval_CallMethod(PyObject *obj, const char *methodname, const char *format, ...) { - va_list vargs; - PyObject *meth; - PyObject *args; - PyObject *res; - - meth = PyObject_GetAttrString(obj, methodname); - if (meth == NULL) - return NULL; - - va_start(vargs, format); - - args = Py_VaBuildValue(format, vargs); - va_end(vargs); - - if (args == NULL) { - Py_DECREF(meth); - return NULL; - } - - res = PyEval_CallObject(meth, args); - Py_DECREF(meth); - Py_DECREF(args); + va_list vargs; + PyObject *meth; + PyObject *args; + PyObject *res; + + meth = PyObject_GetAttrString(obj, methodname); + if (meth == NULL) + return NULL; + + va_start(vargs, format); + + args = Py_VaBuildValue(format, vargs); + va_end(vargs); + + if (args == NULL) { + Py_DECREF(meth); + return NULL; + } + + res = PyEval_CallObject(meth, args); + Py_DECREF(meth); + Py_DECREF(args); - return res; + return res; } int PyModule_AddObject(PyObject *m, const char *name, PyObject *o) { - PyObject *dict; - if (!PyModule_Check(m)) { - PyErr_SetString(PyExc_TypeError, - "PyModule_AddObject() needs module as first arg"); - return -1; - } - if (!o) { - if (!PyErr_Occurred()) - PyErr_SetString(PyExc_TypeError, - "PyModule_AddObject() needs non-NULL value"); - return -1; - } - - dict = PyModule_GetDict(m); - if (dict == NULL) { - /* Internal error -- modules must have a dict! */ - PyErr_Format(PyExc_SystemError, "module '%s' has no __dict__", - PyModule_GetName(m)); - return -1; - } - if (PyDict_SetItemString(dict, name, o)) - return -1; - Py_DECREF(o); - return 0; + PyObject *dict; + if (!PyModule_Check(m)) { + PyErr_SetString(PyExc_TypeError, + "PyModule_AddObject() needs module as first arg"); + return -1; + } + if (!o) { + if (!PyErr_Occurred()) + PyErr_SetString(PyExc_TypeError, + "PyModule_AddObject() needs non-NULL value"); + return -1; + } + + dict = PyModule_GetDict(m); + if (dict == NULL) { + /* Internal error -- modules must have a dict! */ + PyErr_Format(PyExc_SystemError, "module '%s' has no __dict__", + PyModule_GetName(m)); + return -1; + } + if (PyDict_SetItemString(dict, name, o)) + return -1; + Py_DECREF(o); + return 0; } -int +int PyModule_AddIntConstant(PyObject *m, const char *name, long value) { - PyObject *o = PyLong_FromLong(value); - if (!o) - return -1; - if (PyModule_AddObject(m, name, o) == 0) - return 0; - Py_DECREF(o); - return -1; + PyObject *o = PyLong_FromLong(value); + if (!o) + return -1; + if (PyModule_AddObject(m, name, o) == 0) + return 0; + Py_DECREF(o); + return -1; } -int +int PyModule_AddStringConstant(PyObject *m, const char *name, const char *value) { - PyObject *o = PyUnicode_FromString(value); - if (!o) - return -1; - if (PyModule_AddObject(m, name, o) == 0) - return 0; - Py_DECREF(o); - return -1; + PyObject *o = PyUnicode_FromString(value); + if (!o) + return -1; + if (PyModule_AddObject(m, name, o) == 0) + return 0; + Py_DECREF(o); + return -1; } Modified: python/branches/py3k-jit/Python/mysnprintf.c ============================================================================== --- python/branches/py3k-jit/Python/mysnprintf.c (original) +++ python/branches/py3k-jit/Python/mysnprintf.c Mon May 10 23:55:43 2010 @@ -19,20 +19,20 @@ Return value (rv): - When 0 <= rv < size, the output conversion was unexceptional, and - rv characters were written to str (excluding a trailing \0 byte at - str[rv]). - - When rv >= size, output conversion was truncated, and a buffer of - size rv+1 would have been needed to avoid truncation. str[size-1] - is \0 in this case. - - When rv < 0, "something bad happened". str[size-1] is \0 in this - case too, but the rest of str is unreliable. It could be that - an error in format codes was detected by libc, or on platforms - with a non-C99 vsnprintf simply that the buffer wasn't big enough - to avoid truncation, or on platforms without any vsnprintf that - PyMem_Malloc couldn't obtain space for a temp buffer. + When 0 <= rv < size, the output conversion was unexceptional, and + rv characters were written to str (excluding a trailing \0 byte at + str[rv]). + + When rv >= size, output conversion was truncated, and a buffer of + size rv+1 would have been needed to avoid truncation. str[size-1] + is \0 in this case. + + When rv < 0, "something bad happened". str[size-1] is \0 in this + case too, but the rest of str is unreliable. It could be that + an error in format codes was detected by libc, or on platforms + with a non-C99 vsnprintf simply that the buffer wasn't big enough + to avoid truncation, or on platforms without any vsnprintf that + PyMem_Malloc couldn't obtain space for a temp buffer. CAUTION: Unlike C99, str != NULL and size > 0 are required. */ @@ -40,65 +40,65 @@ int PyOS_snprintf(char *str, size_t size, const char *format, ...) { - int rc; - va_list va; + int rc; + va_list va; - va_start(va, format); - rc = PyOS_vsnprintf(str, size, format, va); - va_end(va); - return rc; + va_start(va, format); + rc = PyOS_vsnprintf(str, size, format, va); + va_end(va); + return rc; } int PyOS_vsnprintf(char *str, size_t size, const char *format, va_list va) { - int len; /* # bytes written, excluding \0 */ + int len; /* # bytes written, excluding \0 */ #ifdef HAVE_SNPRINTF #define _PyOS_vsnprintf_EXTRA_SPACE 1 #else #define _PyOS_vsnprintf_EXTRA_SPACE 512 - char *buffer; + char *buffer; #endif - assert(str != NULL); - assert(size > 0); - assert(format != NULL); - /* We take a size_t as input but return an int. Sanity check - * our input so that it won't cause an overflow in the - * vsnprintf return value or the buffer malloc size. */ - if (size > INT_MAX - _PyOS_vsnprintf_EXTRA_SPACE) { - len = -666; - goto Done; - } + assert(str != NULL); + assert(size > 0); + assert(format != NULL); + /* We take a size_t as input but return an int. Sanity check + * our input so that it won't cause an overflow in the + * vsnprintf return value or the buffer malloc size. */ + if (size > INT_MAX - _PyOS_vsnprintf_EXTRA_SPACE) { + len = -666; + goto Done; + } #ifdef HAVE_SNPRINTF - len = vsnprintf(str, size, format, va); + len = vsnprintf(str, size, format, va); #else - /* Emulate it. */ - buffer = PyMem_MALLOC(size + _PyOS_vsnprintf_EXTRA_SPACE); - if (buffer == NULL) { - len = -666; - goto Done; - } - - len = vsprintf(buffer, format, va); - if (len < 0) - /* ignore the error */; - - else if ((size_t)len >= size + _PyOS_vsnprintf_EXTRA_SPACE) - Py_FatalError("Buffer overflow in PyOS_snprintf/PyOS_vsnprintf"); - - else { - const size_t to_copy = (size_t)len < size ? - (size_t)len : size - 1; - assert(to_copy < size); - memcpy(str, buffer, to_copy); - str[to_copy] = '\0'; - } - PyMem_FREE(buffer); + /* Emulate it. */ + buffer = PyMem_MALLOC(size + _PyOS_vsnprintf_EXTRA_SPACE); + if (buffer == NULL) { + len = -666; + goto Done; + } + + len = vsprintf(buffer, format, va); + if (len < 0) + /* ignore the error */; + + else if ((size_t)len >= size + _PyOS_vsnprintf_EXTRA_SPACE) + Py_FatalError("Buffer overflow in PyOS_snprintf/PyOS_vsnprintf"); + + else { + const size_t to_copy = (size_t)len < size ? + (size_t)len : size - 1; + assert(to_copy < size); + memcpy(str, buffer, to_copy); + str[to_copy] = '\0'; + } + PyMem_FREE(buffer); #endif Done: - if (size > 0) - str[size-1] = '\0'; - return len; + if (size > 0) + str[size-1] = '\0'; + return len; #undef _PyOS_vsnprintf_EXTRA_SPACE } Modified: python/branches/py3k-jit/Python/mystrtoul.c ============================================================================== --- python/branches/py3k-jit/Python/mystrtoul.c (original) +++ python/branches/py3k-jit/Python/mystrtoul.c Mon May 10 23:55:43 2010 @@ -18,43 +18,43 @@ * i * base doesn't overflow unsigned long. */ static unsigned long smallmax[] = { - 0, /* bases 0 and 1 are invalid */ - 0, - ULONG_MAX / 2, - ULONG_MAX / 3, - ULONG_MAX / 4, - ULONG_MAX / 5, - ULONG_MAX / 6, - ULONG_MAX / 7, - ULONG_MAX / 8, - ULONG_MAX / 9, - ULONG_MAX / 10, - ULONG_MAX / 11, - ULONG_MAX / 12, - ULONG_MAX / 13, - ULONG_MAX / 14, - ULONG_MAX / 15, - ULONG_MAX / 16, - ULONG_MAX / 17, - ULONG_MAX / 18, - ULONG_MAX / 19, - ULONG_MAX / 20, - ULONG_MAX / 21, - ULONG_MAX / 22, - ULONG_MAX / 23, - ULONG_MAX / 24, - ULONG_MAX / 25, - ULONG_MAX / 26, - ULONG_MAX / 27, - ULONG_MAX / 28, - ULONG_MAX / 29, - ULONG_MAX / 30, - ULONG_MAX / 31, - ULONG_MAX / 32, - ULONG_MAX / 33, - ULONG_MAX / 34, - ULONG_MAX / 35, - ULONG_MAX / 36, + 0, /* bases 0 and 1 are invalid */ + 0, + ULONG_MAX / 2, + ULONG_MAX / 3, + ULONG_MAX / 4, + ULONG_MAX / 5, + ULONG_MAX / 6, + ULONG_MAX / 7, + ULONG_MAX / 8, + ULONG_MAX / 9, + ULONG_MAX / 10, + ULONG_MAX / 11, + ULONG_MAX / 12, + ULONG_MAX / 13, + ULONG_MAX / 14, + ULONG_MAX / 15, + ULONG_MAX / 16, + ULONG_MAX / 17, + ULONG_MAX / 18, + ULONG_MAX / 19, + ULONG_MAX / 20, + ULONG_MAX / 21, + ULONG_MAX / 22, + ULONG_MAX / 23, + ULONG_MAX / 24, + ULONG_MAX / 25, + ULONG_MAX / 26, + ULONG_MAX / 27, + ULONG_MAX / 28, + ULONG_MAX / 29, + ULONG_MAX / 30, + ULONG_MAX / 31, + ULONG_MAX / 32, + ULONG_MAX / 33, + ULONG_MAX / 34, + ULONG_MAX / 35, + ULONG_MAX / 36, }; /* maximum digits that can't ever overflow for bases 2 through 36, @@ -63,229 +63,229 @@ */ #if SIZEOF_LONG == 4 static int digitlimit[] = { - 0, 0, 32, 20, 16, 13, 12, 11, 10, 10, /* 0 - 9 */ - 9, 9, 8, 8, 8, 8, 8, 7, 7, 7, /* 10 - 19 */ - 7, 7, 7, 7, 6, 6, 6, 6, 6, 6, /* 20 - 29 */ - 6, 6, 6, 6, 6, 6, 6}; /* 30 - 36 */ + 0, 0, 32, 20, 16, 13, 12, 11, 10, 10, /* 0 - 9 */ + 9, 9, 8, 8, 8, 8, 8, 7, 7, 7, /* 10 - 19 */ + 7, 7, 7, 7, 6, 6, 6, 6, 6, 6, /* 20 - 29 */ + 6, 6, 6, 6, 6, 6, 6}; /* 30 - 36 */ #elif SIZEOF_LONG == 8 /* [int(math.floor(math.log(2**64, i))) for i in range(2, 37)] */ static int digitlimit[] = { - 0, 0, 64, 40, 32, 27, 24, 22, 21, 20, /* 0 - 9 */ - 19, 18, 17, 17, 16, 16, 16, 15, 15, 15, /* 10 - 19 */ - 14, 14, 14, 14, 13, 13, 13, 13, 13, 13, /* 20 - 29 */ - 13, 12, 12, 12, 12, 12, 12}; /* 30 - 36 */ + 0, 0, 64, 40, 32, 27, 24, 22, 21, 20, /* 0 - 9 */ + 19, 18, 17, 17, 16, 16, 16, 15, 15, 15, /* 10 - 19 */ + 14, 14, 14, 14, 13, 13, 13, 13, 13, 13, /* 20 - 29 */ + 13, 12, 12, 12, 12, 12, 12}; /* 30 - 36 */ #else #error "Need table for SIZEOF_LONG" #endif /* -** strtoul -** This is a general purpose routine for converting -** an ascii string to an integer in an arbitrary base. -** Leading white space is ignored. If 'base' is zero -** it looks for a leading 0b, 0o or 0x to tell which -** base. If these are absent it defaults to 10. -** Base must be 0 or between 2 and 36 (inclusive). -** If 'ptr' is non-NULL it will contain a pointer to -** the end of the scan. -** Errors due to bad pointers will probably result in -** exceptions - we don't check for them. +** strtoul +** This is a general purpose routine for converting +** an ascii string to an integer in an arbitrary base. +** Leading white space is ignored. If 'base' is zero +** it looks for a leading 0b, 0o or 0x to tell which +** base. If these are absent it defaults to 10. +** Base must be 0 or between 2 and 36 (inclusive). +** If 'ptr' is non-NULL it will contain a pointer to +** the end of the scan. +** Errors due to bad pointers will probably result in +** exceptions - we don't check for them. */ unsigned long PyOS_strtoul(register char *str, char **ptr, int base) { - register unsigned long result = 0; /* return value of the function */ - register int c; /* current input character */ - register int ovlimit; /* required digits to overflow */ - - /* skip leading white space */ - while (*str && isspace(Py_CHARMASK(*str))) - ++str; - - /* check for leading 0b, 0o or 0x for auto-base or base 16 */ - switch (base) { - case 0: /* look for leading 0b, 0o or 0x */ - if (*str == '0') { - ++str; - if (*str == 'x' || *str == 'X') { - /* there must be at least one digit after 0x */ - if (_PyLong_DigitValue[Py_CHARMASK(str[1])] >= 16) { - if (ptr) - *ptr = str; - return 0; - } - ++str; - base = 16; - } else if (*str == 'o' || *str == 'O') { - /* there must be at least one digit after 0o */ - if (_PyLong_DigitValue[Py_CHARMASK(str[1])] >= 8) { - if (ptr) - *ptr = str; - return 0; - } - ++str; - base = 8; - } else if (*str == 'b' || *str == 'B') { - /* there must be at least one digit after 0b */ - if (_PyLong_DigitValue[Py_CHARMASK(str[1])] >= 2) { - if (ptr) - *ptr = str; - return 0; - } - ++str; - base = 2; - } else { - /* skip all zeroes... */ - while (*str == '0') - ++str; - while (isspace(Py_CHARMASK(*str))) - ++str; - if (ptr) - *ptr = str; - return 0; - } - } - else - base = 10; - break; - - /* even with explicit base, skip leading 0? prefix */ - case 16: - if (*str == '0') { - ++str; - if (*str == 'x' || *str == 'X') { - /* there must be at least one digit after 0x */ - if (_PyLong_DigitValue[Py_CHARMASK(str[1])] >= 16) { - if (ptr) - *ptr = str; - return 0; - } - ++str; - } - } - break; - case 8: - if (*str == '0') { - ++str; - if (*str == 'o' || *str == 'O') { - /* there must be at least one digit after 0o */ - if (_PyLong_DigitValue[Py_CHARMASK(str[1])] >= 8) { - if (ptr) - *ptr = str; - return 0; - } - ++str; - } - } - break; - case 2: - if(*str == '0') { - ++str; - if (*str == 'b' || *str == 'B') { - /* there must be at least one digit after 0b */ - if (_PyLong_DigitValue[Py_CHARMASK(str[1])] >= 2) { - if (ptr) - *ptr = str; - return 0; - } - ++str; - } - } - break; - } - - /* catch silly bases */ - if (base < 2 || base > 36) { - if (ptr) - *ptr = str; - return 0; - } - - /* skip leading zeroes */ - while (*str == '0') - ++str; - - /* base is guaranteed to be in [2, 36] at this point */ - ovlimit = digitlimit[base]; - - /* do the conversion until non-digit character encountered */ - while ((c = _PyLong_DigitValue[Py_CHARMASK(*str)]) < base) { - if (ovlimit > 0) /* no overflow check required */ - result = result * base + c; - else { /* requires overflow check */ - register unsigned long temp_result; - - if (ovlimit < 0) /* guaranteed overflow */ - goto overflowed; - - /* there could be an overflow */ - /* check overflow just from shifting */ - if (result > smallmax[base]) - goto overflowed; - - result *= base; - - /* check overflow from the digit's value */ - temp_result = result + c; - if (temp_result < result) - goto overflowed; - - result = temp_result; - } - - ++str; - --ovlimit; - } - - /* set pointer to point to the last character scanned */ - if (ptr) - *ptr = str; + register unsigned long result = 0; /* return value of the function */ + register int c; /* current input character */ + register int ovlimit; /* required digits to overflow */ + + /* skip leading white space */ + while (*str && isspace(Py_CHARMASK(*str))) + ++str; + + /* check for leading 0b, 0o or 0x for auto-base or base 16 */ + switch (base) { + case 0: /* look for leading 0b, 0o or 0x */ + if (*str == '0') { + ++str; + if (*str == 'x' || *str == 'X') { + /* there must be at least one digit after 0x */ + if (_PyLong_DigitValue[Py_CHARMASK(str[1])] >= 16) { + if (ptr) + *ptr = str; + return 0; + } + ++str; + base = 16; + } else if (*str == 'o' || *str == 'O') { + /* there must be at least one digit after 0o */ + if (_PyLong_DigitValue[Py_CHARMASK(str[1])] >= 8) { + if (ptr) + *ptr = str; + return 0; + } + ++str; + base = 8; + } else if (*str == 'b' || *str == 'B') { + /* there must be at least one digit after 0b */ + if (_PyLong_DigitValue[Py_CHARMASK(str[1])] >= 2) { + if (ptr) + *ptr = str; + return 0; + } + ++str; + base = 2; + } else { + /* skip all zeroes... */ + while (*str == '0') + ++str; + while (isspace(Py_CHARMASK(*str))) + ++str; + if (ptr) + *ptr = str; + return 0; + } + } + else + base = 10; + break; + + /* even with explicit base, skip leading 0? prefix */ + case 16: + if (*str == '0') { + ++str; + if (*str == 'x' || *str == 'X') { + /* there must be at least one digit after 0x */ + if (_PyLong_DigitValue[Py_CHARMASK(str[1])] >= 16) { + if (ptr) + *ptr = str; + return 0; + } + ++str; + } + } + break; + case 8: + if (*str == '0') { + ++str; + if (*str == 'o' || *str == 'O') { + /* there must be at least one digit after 0o */ + if (_PyLong_DigitValue[Py_CHARMASK(str[1])] >= 8) { + if (ptr) + *ptr = str; + return 0; + } + ++str; + } + } + break; + case 2: + if(*str == '0') { + ++str; + if (*str == 'b' || *str == 'B') { + /* there must be at least one digit after 0b */ + if (_PyLong_DigitValue[Py_CHARMASK(str[1])] >= 2) { + if (ptr) + *ptr = str; + return 0; + } + ++str; + } + } + break; + } + + /* catch silly bases */ + if (base < 2 || base > 36) { + if (ptr) + *ptr = str; + return 0; + } + + /* skip leading zeroes */ + while (*str == '0') + ++str; + + /* base is guaranteed to be in [2, 36] at this point */ + ovlimit = digitlimit[base]; + + /* do the conversion until non-digit character encountered */ + while ((c = _PyLong_DigitValue[Py_CHARMASK(*str)]) < base) { + if (ovlimit > 0) /* no overflow check required */ + result = result * base + c; + else { /* requires overflow check */ + register unsigned long temp_result; + + if (ovlimit < 0) /* guaranteed overflow */ + goto overflowed; + + /* there could be an overflow */ + /* check overflow just from shifting */ + if (result > smallmax[base]) + goto overflowed; + + result *= base; + + /* check overflow from the digit's value */ + temp_result = result + c; + if (temp_result < result) + goto overflowed; + + result = temp_result; + } + + ++str; + --ovlimit; + } + + /* set pointer to point to the last character scanned */ + if (ptr) + *ptr = str; - return result; + return result; overflowed: - if (ptr) { - /* spool through remaining digit characters */ - while (_PyLong_DigitValue[Py_CHARMASK(*str)] < base) - ++str; - *ptr = str; - } - errno = ERANGE; - return (unsigned long)-1; + if (ptr) { + /* spool through remaining digit characters */ + while (_PyLong_DigitValue[Py_CHARMASK(*str)] < base) + ++str; + *ptr = str; + } + errno = ERANGE; + return (unsigned long)-1; } /* Checking for overflow in PyOS_strtol is a PITA; see comments * about PY_ABS_LONG_MIN in longobject.c. */ -#define PY_ABS_LONG_MIN (0-(unsigned long)LONG_MIN) +#define PY_ABS_LONG_MIN (0-(unsigned long)LONG_MIN) long PyOS_strtol(char *str, char **ptr, int base) { - long result; - unsigned long uresult; - char sign; - - while (*str && isspace(Py_CHARMASK(*str))) - str++; - - sign = *str; - if (sign == '+' || sign == '-') - str++; - - uresult = PyOS_strtoul(str, ptr, base); - - if (uresult <= (unsigned long)LONG_MAX) { - result = (long)uresult; - if (sign == '-') - result = -result; - } - else if (sign == '-' && uresult == PY_ABS_LONG_MIN) { - result = LONG_MIN; - } - else { - errno = ERANGE; - result = LONG_MAX; - } - return result; + long result; + unsigned long uresult; + char sign; + + while (*str && isspace(Py_CHARMASK(*str))) + str++; + + sign = *str; + if (sign == '+' || sign == '-') + str++; + + uresult = PyOS_strtoul(str, ptr, base); + + if (uresult <= (unsigned long)LONG_MAX) { + result = (long)uresult; + if (sign == '-') + result = -result; + } + else if (sign == '-' && uresult == PY_ABS_LONG_MIN) { + result = LONG_MIN; + } + else { + errno = ERANGE; + result = LONG_MAX; + } + return result; } Modified: python/branches/py3k-jit/Python/opcode_targets.h ============================================================================== --- python/branches/py3k-jit/Python/opcode_targets.h (original) +++ python/branches/py3k-jit/Python/opcode_targets.h Mon May 10 23:55:43 2010 @@ -1,258 +1,258 @@ static void *opcode_targets[256] = { - &&_unknown_opcode, - &&TARGET_POP_TOP, - &&TARGET_ROT_TWO, - &&TARGET_ROT_THREE, - &&TARGET_DUP_TOP, - &&TARGET_ROT_FOUR, - &&_unknown_opcode, - &&_unknown_opcode, - &&_unknown_opcode, - &&TARGET_NOP, - &&TARGET_UNARY_POSITIVE, - &&TARGET_UNARY_NEGATIVE, - &&TARGET_UNARY_NOT, - &&_unknown_opcode, - &&_unknown_opcode, - &&TARGET_UNARY_INVERT, - &&_unknown_opcode, - &&_unknown_opcode, - &&_unknown_opcode, - &&TARGET_BINARY_POWER, - &&TARGET_BINARY_MULTIPLY, - &&_unknown_opcode, - &&TARGET_BINARY_MODULO, - &&TARGET_BINARY_ADD, - &&TARGET_BINARY_SUBTRACT, - &&TARGET_BINARY_SUBSCR, - &&TARGET_BINARY_FLOOR_DIVIDE, - &&TARGET_BINARY_TRUE_DIVIDE, - &&TARGET_INPLACE_FLOOR_DIVIDE, - &&TARGET_INPLACE_TRUE_DIVIDE, - &&_unknown_opcode, - &&_unknown_opcode, - &&_unknown_opcode, - &&_unknown_opcode, - &&_unknown_opcode, - &&_unknown_opcode, - &&_unknown_opcode, - &&_unknown_opcode, - &&_unknown_opcode, - &&_unknown_opcode, - &&_unknown_opcode, - &&_unknown_opcode, - &&_unknown_opcode, - &&_unknown_opcode, - &&_unknown_opcode, - &&_unknown_opcode, - &&_unknown_opcode, - &&_unknown_opcode, - &&_unknown_opcode, - &&_unknown_opcode, - &&_unknown_opcode, - &&_unknown_opcode, - &&_unknown_opcode, - &&_unknown_opcode, - &&TARGET_STORE_MAP, - &&TARGET_INPLACE_ADD, - &&TARGET_INPLACE_SUBTRACT, - &&TARGET_INPLACE_MULTIPLY, - &&_unknown_opcode, - &&TARGET_INPLACE_MODULO, - &&TARGET_STORE_SUBSCR, - &&TARGET_DELETE_SUBSCR, - &&TARGET_BINARY_LSHIFT, - &&TARGET_BINARY_RSHIFT, - &&TARGET_BINARY_AND, - &&TARGET_BINARY_XOR, - &&TARGET_BINARY_OR, - &&TARGET_INPLACE_POWER, - &&TARGET_GET_ITER, - &&TARGET_STORE_LOCALS, - &&TARGET_PRINT_EXPR, - &&TARGET_LOAD_BUILD_CLASS, - &&_unknown_opcode, - &&_unknown_opcode, - &&_unknown_opcode, - &&TARGET_INPLACE_LSHIFT, - &&TARGET_INPLACE_RSHIFT, - &&TARGET_INPLACE_AND, - &&TARGET_INPLACE_XOR, - &&TARGET_INPLACE_OR, - &&TARGET_BREAK_LOOP, - &&TARGET_WITH_CLEANUP, - &&_unknown_opcode, - &&TARGET_RETURN_VALUE, - &&TARGET_IMPORT_STAR, - &&_unknown_opcode, - &&TARGET_YIELD_VALUE, - &&TARGET_POP_BLOCK, - &&TARGET_END_FINALLY, - &&TARGET_POP_EXCEPT, - &&TARGET_STORE_NAME, - &&TARGET_DELETE_NAME, - &&TARGET_UNPACK_SEQUENCE, - &&TARGET_FOR_ITER, - &&TARGET_UNPACK_EX, - &&TARGET_STORE_ATTR, - &&TARGET_DELETE_ATTR, - &&TARGET_STORE_GLOBAL, - &&TARGET_DELETE_GLOBAL, - &&TARGET_DUP_TOPX, - &&TARGET_LOAD_CONST, - &&TARGET_LOAD_NAME, - &&TARGET_BUILD_TUPLE, - &&TARGET_BUILD_LIST, - &&TARGET_BUILD_SET, - &&TARGET_BUILD_MAP, - &&TARGET_LOAD_ATTR, - &&TARGET_COMPARE_OP, - &&TARGET_IMPORT_NAME, - &&TARGET_IMPORT_FROM, - &&TARGET_JUMP_FORWARD, - &&TARGET_JUMP_IF_FALSE_OR_POP, - &&TARGET_JUMP_IF_TRUE_OR_POP, - &&TARGET_JUMP_ABSOLUTE, - &&TARGET_POP_JUMP_IF_FALSE, - &&TARGET_POP_JUMP_IF_TRUE, - &&TARGET_LOAD_GLOBAL, - &&_unknown_opcode, - &&_unknown_opcode, - &&TARGET_CONTINUE_LOOP, - &&TARGET_SETUP_LOOP, - &&TARGET_SETUP_EXCEPT, - &&TARGET_SETUP_FINALLY, - &&_unknown_opcode, - &&TARGET_LOAD_FAST, - &&TARGET_STORE_FAST, - &&TARGET_DELETE_FAST, - &&_unknown_opcode, - &&_unknown_opcode, - &&_unknown_opcode, - &&TARGET_RAISE_VARARGS, - &&TARGET_CALL_FUNCTION, - &&TARGET_MAKE_FUNCTION, - &&TARGET_BUILD_SLICE, - &&TARGET_MAKE_CLOSURE, - &&TARGET_LOAD_CLOSURE, - &&TARGET_LOAD_DEREF, - &&TARGET_STORE_DEREF, - &&_unknown_opcode, - &&_unknown_opcode, - &&TARGET_CALL_FUNCTION_VAR, - &&TARGET_CALL_FUNCTION_KW, - &&TARGET_CALL_FUNCTION_VAR_KW, - &&TARGET_SETUP_WITH, - &&TARGET_EXTENDED_ARG, - &&TARGET_LIST_APPEND, - &&TARGET_SET_ADD, - &&TARGET_MAP_ADD, - &&_unknown_opcode, - &&_unknown_opcode, - &&_unknown_opcode, - &&_unknown_opcode, - &&_unknown_opcode, - &&_unknown_opcode, - &&_unknown_opcode, - &&_unknown_opcode, - &&_unknown_opcode, - &&_unknown_opcode, - &&_unknown_opcode, - &&_unknown_opcode, - &&_unknown_opcode, - &&_unknown_opcode, - &&_unknown_opcode, - &&_unknown_opcode, - &&_unknown_opcode, - &&_unknown_opcode, - &&_unknown_opcode, - &&_unknown_opcode, - &&_unknown_opcode, - &&_unknown_opcode, - &&_unknown_opcode, - &&_unknown_opcode, - &&_unknown_opcode, - &&_unknown_opcode, - &&_unknown_opcode, - &&_unknown_opcode, - &&_unknown_opcode, - &&_unknown_opcode, - &&_unknown_opcode, - &&_unknown_opcode, - &&_unknown_opcode, - &&_unknown_opcode, - &&_unknown_opcode, - &&_unknown_opcode, - &&_unknown_opcode, - &&_unknown_opcode, - &&_unknown_opcode, - &&_unknown_opcode, - &&_unknown_opcode, - &&_unknown_opcode, - &&_unknown_opcode, - &&_unknown_opcode, - &&_unknown_opcode, - &&_unknown_opcode, - &&_unknown_opcode, - &&_unknown_opcode, - &&_unknown_opcode, - &&_unknown_opcode, - &&_unknown_opcode, - &&_unknown_opcode, - &&_unknown_opcode, - &&_unknown_opcode, - &&_unknown_opcode, - &&_unknown_opcode, - &&_unknown_opcode, - &&_unknown_opcode, - &&_unknown_opcode, - &&_unknown_opcode, - &&_unknown_opcode, - &&_unknown_opcode, - &&_unknown_opcode, - &&_unknown_opcode, - &&_unknown_opcode, - &&_unknown_opcode, - &&_unknown_opcode, - &&_unknown_opcode, - &&_unknown_opcode, - &&_unknown_opcode, - &&_unknown_opcode, - &&_unknown_opcode, - &&_unknown_opcode, - &&_unknown_opcode, - &&_unknown_opcode, - &&_unknown_opcode, - &&_unknown_opcode, - &&_unknown_opcode, - &&_unknown_opcode, - &&_unknown_opcode, - &&_unknown_opcode, - &&_unknown_opcode, - &&_unknown_opcode, - &&_unknown_opcode, - &&_unknown_opcode, - &&_unknown_opcode, - &&_unknown_opcode, - &&_unknown_opcode, - &&_unknown_opcode, - &&_unknown_opcode, - &&_unknown_opcode, - &&_unknown_opcode, - &&_unknown_opcode, - &&_unknown_opcode, - &&_unknown_opcode, - &&_unknown_opcode, - &&_unknown_opcode, - &&_unknown_opcode, - &&_unknown_opcode, - &&_unknown_opcode, - &&_unknown_opcode, - &&_unknown_opcode, - &&_unknown_opcode, - &&_unknown_opcode, - &&_unknown_opcode, - &&_unknown_opcode, - &&_unknown_opcode, - &&_unknown_opcode + &&_unknown_opcode, + &&TARGET_POP_TOP, + &&TARGET_ROT_TWO, + &&TARGET_ROT_THREE, + &&TARGET_DUP_TOP, + &&TARGET_ROT_FOUR, + &&_unknown_opcode, + &&_unknown_opcode, + &&_unknown_opcode, + &&TARGET_NOP, + &&TARGET_UNARY_POSITIVE, + &&TARGET_UNARY_NEGATIVE, + &&TARGET_UNARY_NOT, + &&_unknown_opcode, + &&_unknown_opcode, + &&TARGET_UNARY_INVERT, + &&_unknown_opcode, + &&_unknown_opcode, + &&_unknown_opcode, + &&TARGET_BINARY_POWER, + &&TARGET_BINARY_MULTIPLY, + &&_unknown_opcode, + &&TARGET_BINARY_MODULO, + &&TARGET_BINARY_ADD, + &&TARGET_BINARY_SUBTRACT, + &&TARGET_BINARY_SUBSCR, + &&TARGET_BINARY_FLOOR_DIVIDE, + &&TARGET_BINARY_TRUE_DIVIDE, + &&TARGET_INPLACE_FLOOR_DIVIDE, + &&TARGET_INPLACE_TRUE_DIVIDE, + &&_unknown_opcode, + &&_unknown_opcode, + &&_unknown_opcode, + &&_unknown_opcode, + &&_unknown_opcode, + &&_unknown_opcode, + &&_unknown_opcode, + &&_unknown_opcode, + &&_unknown_opcode, + &&_unknown_opcode, + &&_unknown_opcode, + &&_unknown_opcode, + &&_unknown_opcode, + &&_unknown_opcode, + &&_unknown_opcode, + &&_unknown_opcode, + &&_unknown_opcode, + &&_unknown_opcode, + &&_unknown_opcode, + &&_unknown_opcode, + &&_unknown_opcode, + &&_unknown_opcode, + &&_unknown_opcode, + &&_unknown_opcode, + &&TARGET_STORE_MAP, + &&TARGET_INPLACE_ADD, + &&TARGET_INPLACE_SUBTRACT, + &&TARGET_INPLACE_MULTIPLY, + &&_unknown_opcode, + &&TARGET_INPLACE_MODULO, + &&TARGET_STORE_SUBSCR, + &&TARGET_DELETE_SUBSCR, + &&TARGET_BINARY_LSHIFT, + &&TARGET_BINARY_RSHIFT, + &&TARGET_BINARY_AND, + &&TARGET_BINARY_XOR, + &&TARGET_BINARY_OR, + &&TARGET_INPLACE_POWER, + &&TARGET_GET_ITER, + &&TARGET_STORE_LOCALS, + &&TARGET_PRINT_EXPR, + &&TARGET_LOAD_BUILD_CLASS, + &&_unknown_opcode, + &&_unknown_opcode, + &&_unknown_opcode, + &&TARGET_INPLACE_LSHIFT, + &&TARGET_INPLACE_RSHIFT, + &&TARGET_INPLACE_AND, + &&TARGET_INPLACE_XOR, + &&TARGET_INPLACE_OR, + &&TARGET_BREAK_LOOP, + &&TARGET_WITH_CLEANUP, + &&_unknown_opcode, + &&TARGET_RETURN_VALUE, + &&TARGET_IMPORT_STAR, + &&_unknown_opcode, + &&TARGET_YIELD_VALUE, + &&TARGET_POP_BLOCK, + &&TARGET_END_FINALLY, + &&TARGET_POP_EXCEPT, + &&TARGET_STORE_NAME, + &&TARGET_DELETE_NAME, + &&TARGET_UNPACK_SEQUENCE, + &&TARGET_FOR_ITER, + &&TARGET_UNPACK_EX, + &&TARGET_STORE_ATTR, + &&TARGET_DELETE_ATTR, + &&TARGET_STORE_GLOBAL, + &&TARGET_DELETE_GLOBAL, + &&TARGET_DUP_TOPX, + &&TARGET_LOAD_CONST, + &&TARGET_LOAD_NAME, + &&TARGET_BUILD_TUPLE, + &&TARGET_BUILD_LIST, + &&TARGET_BUILD_SET, + &&TARGET_BUILD_MAP, + &&TARGET_LOAD_ATTR, + &&TARGET_COMPARE_OP, + &&TARGET_IMPORT_NAME, + &&TARGET_IMPORT_FROM, + &&TARGET_JUMP_FORWARD, + &&TARGET_JUMP_IF_FALSE_OR_POP, + &&TARGET_JUMP_IF_TRUE_OR_POP, + &&TARGET_JUMP_ABSOLUTE, + &&TARGET_POP_JUMP_IF_FALSE, + &&TARGET_POP_JUMP_IF_TRUE, + &&TARGET_LOAD_GLOBAL, + &&_unknown_opcode, + &&_unknown_opcode, + &&TARGET_CONTINUE_LOOP, + &&TARGET_SETUP_LOOP, + &&TARGET_SETUP_EXCEPT, + &&TARGET_SETUP_FINALLY, + &&_unknown_opcode, + &&TARGET_LOAD_FAST, + &&TARGET_STORE_FAST, + &&TARGET_DELETE_FAST, + &&_unknown_opcode, + &&_unknown_opcode, + &&_unknown_opcode, + &&TARGET_RAISE_VARARGS, + &&TARGET_CALL_FUNCTION, + &&TARGET_MAKE_FUNCTION, + &&TARGET_BUILD_SLICE, + &&TARGET_MAKE_CLOSURE, + &&TARGET_LOAD_CLOSURE, + &&TARGET_LOAD_DEREF, + &&TARGET_STORE_DEREF, + &&_unknown_opcode, + &&_unknown_opcode, + &&TARGET_CALL_FUNCTION_VAR, + &&TARGET_CALL_FUNCTION_KW, + &&TARGET_CALL_FUNCTION_VAR_KW, + &&TARGET_SETUP_WITH, + &&TARGET_EXTENDED_ARG, + &&TARGET_LIST_APPEND, + &&TARGET_SET_ADD, + &&TARGET_MAP_ADD, + &&_unknown_opcode, + &&_unknown_opcode, + &&_unknown_opcode, + &&_unknown_opcode, + &&_unknown_opcode, + &&_unknown_opcode, + &&_unknown_opcode, + &&_unknown_opcode, + &&_unknown_opcode, + &&_unknown_opcode, + &&_unknown_opcode, + &&_unknown_opcode, + &&_unknown_opcode, + &&_unknown_opcode, + &&_unknown_opcode, + &&_unknown_opcode, + &&_unknown_opcode, + &&_unknown_opcode, + &&_unknown_opcode, + &&_unknown_opcode, + &&_unknown_opcode, + &&_unknown_opcode, + &&_unknown_opcode, + &&_unknown_opcode, + &&_unknown_opcode, + &&_unknown_opcode, + &&_unknown_opcode, + &&_unknown_opcode, + &&_unknown_opcode, + &&_unknown_opcode, + &&_unknown_opcode, + &&_unknown_opcode, + &&_unknown_opcode, + &&_unknown_opcode, + &&_unknown_opcode, + &&_unknown_opcode, + &&_unknown_opcode, + &&_unknown_opcode, + &&_unknown_opcode, + &&_unknown_opcode, + &&_unknown_opcode, + &&_unknown_opcode, + &&_unknown_opcode, + &&_unknown_opcode, + &&_unknown_opcode, + &&_unknown_opcode, + &&_unknown_opcode, + &&_unknown_opcode, + &&_unknown_opcode, + &&_unknown_opcode, + &&_unknown_opcode, + &&_unknown_opcode, + &&_unknown_opcode, + &&_unknown_opcode, + &&_unknown_opcode, + &&_unknown_opcode, + &&_unknown_opcode, + &&_unknown_opcode, + &&_unknown_opcode, + &&_unknown_opcode, + &&_unknown_opcode, + &&_unknown_opcode, + &&_unknown_opcode, + &&_unknown_opcode, + &&_unknown_opcode, + &&_unknown_opcode, + &&_unknown_opcode, + &&_unknown_opcode, + &&_unknown_opcode, + &&_unknown_opcode, + &&_unknown_opcode, + &&_unknown_opcode, + &&_unknown_opcode, + &&_unknown_opcode, + &&_unknown_opcode, + &&_unknown_opcode, + &&_unknown_opcode, + &&_unknown_opcode, + &&_unknown_opcode, + &&_unknown_opcode, + &&_unknown_opcode, + &&_unknown_opcode, + &&_unknown_opcode, + &&_unknown_opcode, + &&_unknown_opcode, + &&_unknown_opcode, + &&_unknown_opcode, + &&_unknown_opcode, + &&_unknown_opcode, + &&_unknown_opcode, + &&_unknown_opcode, + &&_unknown_opcode, + &&_unknown_opcode, + &&_unknown_opcode, + &&_unknown_opcode, + &&_unknown_opcode, + &&_unknown_opcode, + &&_unknown_opcode, + &&_unknown_opcode, + &&_unknown_opcode, + &&_unknown_opcode, + &&_unknown_opcode, + &&_unknown_opcode, + &&_unknown_opcode, + &&_unknown_opcode, + &&_unknown_opcode, + &&_unknown_opcode, + &&_unknown_opcode }; Modified: python/branches/py3k-jit/Python/peephole.c ============================================================================== --- python/branches/py3k-jit/Python/peephole.c (original) +++ python/branches/py3k-jit/Python/peephole.c Mon May 10 23:55:43 2010 @@ -12,271 +12,271 @@ #include "opcode.h" #define GETARG(arr, i) ((int)((arr[i+2]<<8) + arr[i+1])) -#define UNCONDITIONAL_JUMP(op) (op==JUMP_ABSOLUTE || op==JUMP_FORWARD) +#define UNCONDITIONAL_JUMP(op) (op==JUMP_ABSOLUTE || op==JUMP_FORWARD) #define CONDITIONAL_JUMP(op) (op==POP_JUMP_IF_FALSE || op==POP_JUMP_IF_TRUE \ - || op==JUMP_IF_FALSE_OR_POP || op==JUMP_IF_TRUE_OR_POP) + || op==JUMP_IF_FALSE_OR_POP || op==JUMP_IF_TRUE_OR_POP) #define ABSOLUTE_JUMP(op) (op==JUMP_ABSOLUTE || op==CONTINUE_LOOP \ - || op==POP_JUMP_IF_FALSE || op==POP_JUMP_IF_TRUE \ - || op==JUMP_IF_FALSE_OR_POP || op==JUMP_IF_TRUE_OR_POP) + || op==POP_JUMP_IF_FALSE || op==POP_JUMP_IF_TRUE \ + || op==JUMP_IF_FALSE_OR_POP || op==JUMP_IF_TRUE_OR_POP) #define JUMPS_ON_TRUE(op) (op==POP_JUMP_IF_TRUE || op==JUMP_IF_TRUE_OR_POP) #define GETJUMPTGT(arr, i) (GETARG(arr,i) + (ABSOLUTE_JUMP(arr[i]) ? 0 : i+3)) #define SETARG(arr, i, val) arr[i+2] = val>>8; arr[i+1] = val & 255 #define CODESIZE(op) (HAS_ARG(op) ? 3 : 1) #define ISBASICBLOCK(blocks, start, bytes) \ - (blocks[start]==blocks[start+bytes-1]) + (blocks[start]==blocks[start+bytes-1]) /* Replace LOAD_CONST c1. LOAD_CONST c2 ... LOAD_CONST cn BUILD_TUPLE n - with LOAD_CONST (c1, c2, ... cn). + with LOAD_CONST (c1, c2, ... cn). The consts table must still be in list form so that the new constant (c1, c2, ... cn) can be appended. Called with codestr pointing to the first LOAD_CONST. - Bails out with no change if one or more of the LOAD_CONSTs is missing. + Bails out with no change if one or more of the LOAD_CONSTs is missing. Also works for BUILD_LIST and BUILT_SET when followed by an "in" or "not in" test; for BUILD_SET it assembles a frozenset rather than a tuple. */ static int tuple_of_constants(unsigned char *codestr, Py_ssize_t n, PyObject *consts) { - PyObject *newconst, *constant; - Py_ssize_t i, arg, len_consts; + PyObject *newconst, *constant; + Py_ssize_t i, arg, len_consts; - /* Pre-conditions */ - assert(PyList_CheckExact(consts)); - assert(codestr[n*3] == BUILD_TUPLE || codestr[n*3] == BUILD_LIST || codestr[n*3] == BUILD_SET); - assert(GETARG(codestr, (n*3)) == n); - for (i=0 ; i 20) { - Py_DECREF(newconst); - return 0; - } - - /* Append folded constant into consts table */ - len_consts = PyList_GET_SIZE(consts); - if (PyList_Append(consts, newconst)) { - Py_DECREF(newconst); - return 0; - } - Py_DECREF(newconst); - - /* Write NOP NOP NOP NOP LOAD_CONST newconst */ - memset(codestr, NOP, 4); - codestr[4] = LOAD_CONST; - SETARG(codestr, 4, len_consts); - return 1; + PyObject *newconst, *v, *w; + Py_ssize_t len_consts, size; + int opcode; + + /* Pre-conditions */ + assert(PyList_CheckExact(consts)); + assert(codestr[0] == LOAD_CONST); + assert(codestr[3] == LOAD_CONST); + + /* Create new constant */ + v = PyList_GET_ITEM(consts, GETARG(codestr, 0)); + w = PyList_GET_ITEM(consts, GETARG(codestr, 3)); + opcode = codestr[6]; + switch (opcode) { + case BINARY_POWER: + newconst = PyNumber_Power(v, w, Py_None); + break; + case BINARY_MULTIPLY: + newconst = PyNumber_Multiply(v, w); + break; + case BINARY_TRUE_DIVIDE: + newconst = PyNumber_TrueDivide(v, w); + break; + case BINARY_FLOOR_DIVIDE: + newconst = PyNumber_FloorDivide(v, w); + break; + case BINARY_MODULO: + newconst = PyNumber_Remainder(v, w); + break; + case BINARY_ADD: + newconst = PyNumber_Add(v, w); + break; + case BINARY_SUBTRACT: + newconst = PyNumber_Subtract(v, w); + break; + case BINARY_SUBSCR: + newconst = PyObject_GetItem(v, w); + break; + case BINARY_LSHIFT: + newconst = PyNumber_Lshift(v, w); + break; + case BINARY_RSHIFT: + newconst = PyNumber_Rshift(v, w); + break; + case BINARY_AND: + newconst = PyNumber_And(v, w); + break; + case BINARY_XOR: + newconst = PyNumber_Xor(v, w); + break; + case BINARY_OR: + newconst = PyNumber_Or(v, w); + break; + default: + /* Called with an unknown opcode */ + PyErr_Format(PyExc_SystemError, + "unexpected binary operation %d on a constant", + opcode); + return 0; + } + if (newconst == NULL) { + PyErr_Clear(); + return 0; + } + size = PyObject_Size(newconst); + if (size == -1) + PyErr_Clear(); + else if (size > 20) { + Py_DECREF(newconst); + return 0; + } + + /* Append folded constant into consts table */ + len_consts = PyList_GET_SIZE(consts); + if (PyList_Append(consts, newconst)) { + Py_DECREF(newconst); + return 0; + } + Py_DECREF(newconst); + + /* Write NOP NOP NOP NOP LOAD_CONST newconst */ + memset(codestr, NOP, 4); + codestr[4] = LOAD_CONST; + SETARG(codestr, 4, len_consts); + return 1; } static int fold_unaryops_on_constants(unsigned char *codestr, PyObject *consts) { - PyObject *newconst=NULL, *v; - Py_ssize_t len_consts; - int opcode; - - /* Pre-conditions */ - assert(PyList_CheckExact(consts)); - assert(codestr[0] == LOAD_CONST); - - /* Create new constant */ - v = PyList_GET_ITEM(consts, GETARG(codestr, 0)); - opcode = codestr[3]; - switch (opcode) { - case UNARY_NEGATIVE: - /* Preserve the sign of -0.0 */ - if (PyObject_IsTrue(v) == 1) - newconst = PyNumber_Negative(v); - break; - case UNARY_INVERT: - newconst = PyNumber_Invert(v); - break; - case UNARY_POSITIVE: - newconst = PyNumber_Positive(v); - break; - default: - /* Called with an unknown opcode */ - PyErr_Format(PyExc_SystemError, - "unexpected unary operation %d on a constant", - opcode); - return 0; - } - if (newconst == NULL) { - PyErr_Clear(); - return 0; - } - - /* Append folded constant into consts table */ - len_consts = PyList_GET_SIZE(consts); - if (PyList_Append(consts, newconst)) { - Py_DECREF(newconst); - return 0; - } - Py_DECREF(newconst); - - /* Write NOP LOAD_CONST newconst */ - codestr[0] = NOP; - codestr[1] = LOAD_CONST; - SETARG(codestr, 1, len_consts); - return 1; + PyObject *newconst=NULL, *v; + Py_ssize_t len_consts; + int opcode; + + /* Pre-conditions */ + assert(PyList_CheckExact(consts)); + assert(codestr[0] == LOAD_CONST); + + /* Create new constant */ + v = PyList_GET_ITEM(consts, GETARG(codestr, 0)); + opcode = codestr[3]; + switch (opcode) { + case UNARY_NEGATIVE: + /* Preserve the sign of -0.0 */ + if (PyObject_IsTrue(v) == 1) + newconst = PyNumber_Negative(v); + break; + case UNARY_INVERT: + newconst = PyNumber_Invert(v); + break; + case UNARY_POSITIVE: + newconst = PyNumber_Positive(v); + break; + default: + /* Called with an unknown opcode */ + PyErr_Format(PyExc_SystemError, + "unexpected unary operation %d on a constant", + opcode); + return 0; + } + if (newconst == NULL) { + PyErr_Clear(); + return 0; + } + + /* Append folded constant into consts table */ + len_consts = PyList_GET_SIZE(consts); + if (PyList_Append(consts, newconst)) { + Py_DECREF(newconst); + return 0; + } + Py_DECREF(newconst); + + /* Write NOP LOAD_CONST newconst */ + codestr[0] = NOP; + codestr[1] = LOAD_CONST; + SETARG(codestr, 1, len_consts); + return 1; } static unsigned int * markblocks(unsigned char *code, Py_ssize_t len) { - unsigned int *blocks = (unsigned int *)PyMem_Malloc(len*sizeof(int)); - int i,j, opcode, blockcnt = 0; + unsigned int *blocks = (unsigned int *)PyMem_Malloc(len*sizeof(int)); + int i,j, opcode, blockcnt = 0; - if (blocks == NULL) { - PyErr_NoMemory(); - return NULL; - } - memset(blocks, 0, len*sizeof(int)); - - /* Mark labels in the first pass */ - for (i=0 ; i= 255. EXTENDED_ARG can appear before MAKE_FUNCTION; in this case both opcodes are skipped. EXTENDED_ARG preceding any other opcode causes the optimizer to bail. Optimizations are restricted to simple transformations occuring within a - single basic block. All transformations keep the code size the same or - smaller. For those that reduce size, the gaps are initially filled with - NOPs. Later those NOPs are removed and the jump addresses retargeted in + single basic block. All transformations keep the code size the same or + smaller. For those that reduce size, the gaps are initially filled with + NOPs. Later those NOPs are removed and the jump addresses retargeted in a single pass. Line numbering is adjusted accordingly. */ PyObject * PyCode_Optimize(PyObject *code, PyObject* consts, PyObject *names, PyObject *lineno_obj) { - Py_ssize_t i, j, codelen; - int nops, h, adj; - int tgt, tgttgt, opcode; - unsigned char *codestr = NULL; - unsigned char *lineno; - int *addrmap = NULL; - int new_line, cum_orig_line, last_line, tabsiz; - int cumlc=0, lastlc=0; /* Count runs of consecutive LOAD_CONSTs */ - unsigned int *blocks = NULL; - char *name; - - /* Bail out if an exception is set */ - if (PyErr_Occurred()) - goto exitError; - - /* Bypass optimization when the lineno table is too complex */ - assert(PyBytes_Check(lineno_obj)); - lineno = (unsigned char*)PyBytes_AS_STRING(lineno_obj); - tabsiz = PyBytes_GET_SIZE(lineno_obj); - if (memchr(lineno, 255, tabsiz) != NULL) - goto exitUnchanged; - - /* Avoid situations where jump retargeting could overflow */ - assert(PyBytes_Check(code)); - codelen = PyBytes_GET_SIZE(code); - if (codelen > 32700) - goto exitUnchanged; - - /* Make a modifiable copy of the code string */ - codestr = (unsigned char *)PyMem_Malloc(codelen); - if (codestr == NULL) - goto exitError; - codestr = (unsigned char *)memcpy(codestr, - PyBytes_AS_STRING(code), codelen); - - /* Verify that RETURN_VALUE terminates the codestring. This allows - the various transformation patterns to look ahead several - instructions without additional checks to make sure they are not - looking beyond the end of the code string. - */ - if (codestr[codelen-1] != RETURN_VALUE) - goto exitUnchanged; - - /* Mapping to new jump targets after NOPs are removed */ - addrmap = (int *)PyMem_Malloc(codelen * sizeof(int)); - if (addrmap == NULL) - goto exitError; - - blocks = markblocks(codestr, codelen); - if (blocks == NULL) - goto exitError; - assert(PyList_Check(consts)); - - for (i=0 ; i a is not b - not a in b --> a not in b - not a is not b --> a is b - not a not in b --> a in b - */ - case COMPARE_OP: - j = GETARG(codestr, i); - if (j < 6 || j > 9 || - codestr[i+3] != UNARY_NOT || - !ISBASICBLOCK(blocks,i,4)) - continue; - SETARG(codestr, i, (j^1)); - codestr[i+3] = NOP; - break; - - /* Replace LOAD_GLOBAL/LOAD_NAME None/True/False - with LOAD_CONST None/True/False */ - case LOAD_NAME: - case LOAD_GLOBAL: - j = GETARG(codestr, i); - name = _PyUnicode_AsString(PyTuple_GET_ITEM(names, j)); - h = load_global(codestr, i, name, consts); - if (h < 0) - goto exitError; - else if (h == 0) - continue; - cumlc = lastlc + 1; - break; - - /* Skip over LOAD_CONST trueconst - POP_JUMP_IF_FALSE xx. This improves - "while 1" performance. */ - case LOAD_CONST: - cumlc = lastlc + 1; - j = GETARG(codestr, i); - if (codestr[i+3] != POP_JUMP_IF_FALSE || - !ISBASICBLOCK(blocks,i,6) || - !PyObject_IsTrue(PyList_GET_ITEM(consts, j))) - continue; - memset(codestr+i, NOP, 6); - cumlc = 0; - break; - - /* Try to fold tuples of constants (includes a case for lists and sets - which are only used for "in" and "not in" tests). - Skip over BUILD_SEQN 1 UNPACK_SEQN 1. - Replace BUILD_SEQN 2 UNPACK_SEQN 2 with ROT2. - Replace BUILD_SEQN 3 UNPACK_SEQN 3 with ROT3 ROT2. */ - case BUILD_TUPLE: - case BUILD_LIST: - case BUILD_SET: - j = GETARG(codestr, i); - h = i - 3 * j; - if (h >= 0 && - j <= lastlc && - ((opcode == BUILD_TUPLE && - ISBASICBLOCK(blocks, h, 3*(j+1))) || - ((opcode == BUILD_LIST || opcode == BUILD_SET) && - codestr[i+3]==COMPARE_OP && - ISBASICBLOCK(blocks, h, 3*(j+2)) && - (GETARG(codestr,i+3)==6 || - GETARG(codestr,i+3)==7))) && - tuple_of_constants(&codestr[h], j, consts)) { - assert(codestr[i] == LOAD_CONST); - cumlc = 1; - break; - } - if (codestr[i+3] != UNPACK_SEQUENCE || - !ISBASICBLOCK(blocks,i,6) || - j != GETARG(codestr, i+3)) - continue; - if (j == 1) { - memset(codestr+i, NOP, 6); - } else if (j == 2) { - codestr[i] = ROT_TWO; - memset(codestr+i+1, NOP, 5); - } else if (j == 3) { - codestr[i] = ROT_THREE; - codestr[i+1] = ROT_TWO; - memset(codestr+i+2, NOP, 4); - } - break; - - /* Fold binary ops on constants. - LOAD_CONST c1 LOAD_CONST c2 BINOP --> LOAD_CONST binop(c1,c2) */ - case BINARY_POWER: - case BINARY_MULTIPLY: - case BINARY_TRUE_DIVIDE: - case BINARY_FLOOR_DIVIDE: - case BINARY_MODULO: - case BINARY_ADD: - case BINARY_SUBTRACT: - case BINARY_SUBSCR: - case BINARY_LSHIFT: - case BINARY_RSHIFT: - case BINARY_AND: - case BINARY_XOR: - case BINARY_OR: - if (lastlc >= 2 && - ISBASICBLOCK(blocks, i-6, 7) && - fold_binops_on_constants(&codestr[i-6], consts)) { - i -= 2; - assert(codestr[i] == LOAD_CONST); - cumlc = 1; - } - break; - - /* Fold unary ops on constants. - LOAD_CONST c1 UNARY_OP --> LOAD_CONST unary_op(c) */ - case UNARY_NEGATIVE: - case UNARY_INVERT: - case UNARY_POSITIVE: - if (lastlc >= 1 && - ISBASICBLOCK(blocks, i-3, 4) && - fold_unaryops_on_constants(&codestr[i-3], consts)) { - i -= 2; - assert(codestr[i] == LOAD_CONST); - cumlc = 1; - } - break; - - /* Simplify conditional jump to conditional jump where the - result of the first test implies the success of a similar - test or the failure of the opposite test. - Arises in code like: - "if a and b:" - "if a or b:" - "a and b or c" - "(a and b) and c" - x:JUMP_IF_FALSE_OR_POP y y:JUMP_IF_FALSE_OR_POP z - --> x:JUMP_IF_FALSE_OR_POP z - x:JUMP_IF_FALSE_OR_POP y y:JUMP_IF_TRUE_OR_POP z - --> x:POP_JUMP_IF_FALSE y+3 - where y+3 is the instruction following the second test. - */ - case JUMP_IF_FALSE_OR_POP: - case JUMP_IF_TRUE_OR_POP: - tgt = GETJUMPTGT(codestr, i); - j = codestr[tgt]; - if (CONDITIONAL_JUMP(j)) { - /* NOTE: all possible jumps here are - absolute! */ - if (JUMPS_ON_TRUE(j) == JUMPS_ON_TRUE(opcode)) { - /* The second jump will be - taken iff the first is. */ - tgttgt = GETJUMPTGT(codestr, tgt); - /* The current opcode inherits - its target's stack behaviour */ - codestr[i] = j; - SETARG(codestr, i, tgttgt); - goto reoptimize_current; - } else { - /* The second jump is not taken - if the first is (so jump past - it), and all conditional - jumps pop their argument when - they're not taken (so change - the first jump to pop its - argument when it's taken). */ - if (JUMPS_ON_TRUE(opcode)) - codestr[i] = POP_JUMP_IF_TRUE; - else - codestr[i] = POP_JUMP_IF_FALSE; - SETARG(codestr, i, (tgt + 3)); - goto reoptimize_current; - } - } - /* Intentional fallthrough */ - - /* Replace jumps to unconditional jumps */ - case POP_JUMP_IF_FALSE: - case POP_JUMP_IF_TRUE: - case FOR_ITER: - case JUMP_FORWARD: - case JUMP_ABSOLUTE: - case CONTINUE_LOOP: - case SETUP_LOOP: - case SETUP_EXCEPT: - case SETUP_FINALLY: - case SETUP_WITH: - tgt = GETJUMPTGT(codestr, i); - /* Replace JUMP_* to a RETURN into just a RETURN */ - if (UNCONDITIONAL_JUMP(opcode) && - codestr[tgt] == RETURN_VALUE) { - codestr[i] = RETURN_VALUE; - memset(codestr+i+1, NOP, 2); - continue; - } - if (!UNCONDITIONAL_JUMP(codestr[tgt])) - continue; - tgttgt = GETJUMPTGT(codestr, tgt); - if (opcode == JUMP_FORWARD) /* JMP_ABS can go backwards */ - opcode = JUMP_ABSOLUTE; - if (!ABSOLUTE_JUMP(opcode)) - tgttgt -= i + 3; /* Calc relative jump addr */ - if (tgttgt < 0) /* No backward relative jumps */ - continue; - codestr[i] = opcode; - SETARG(codestr, i, tgttgt); - break; - - case EXTENDED_ARG: - if (codestr[i+3] != MAKE_FUNCTION) - goto exitUnchanged; - /* don't visit MAKE_FUNCTION as GETARG will be wrong */ - i += 3; - break; - - /* Replace RETURN LOAD_CONST None RETURN with just RETURN */ - /* Remove unreachable JUMPs after RETURN */ - case RETURN_VALUE: - if (i+4 >= codelen) - continue; - if (codestr[i+4] == RETURN_VALUE && - ISBASICBLOCK(blocks,i,5)) - memset(codestr+i+1, NOP, 4); - else if (UNCONDITIONAL_JUMP(codestr[i+1]) && - ISBASICBLOCK(blocks,i,4)) - memset(codestr+i+1, NOP, 3); - break; - } - } - - /* Fixup linenotab */ - for (i=0, nops=0 ; i 32700) + goto exitUnchanged; + + /* Make a modifiable copy of the code string */ + codestr = (unsigned char *)PyMem_Malloc(codelen); + if (codestr == NULL) + goto exitError; + codestr = (unsigned char *)memcpy(codestr, + PyBytes_AS_STRING(code), codelen); + + /* Verify that RETURN_VALUE terminates the codestring. This allows + the various transformation patterns to look ahead several + instructions without additional checks to make sure they are not + looking beyond the end of the code string. + */ + if (codestr[codelen-1] != RETURN_VALUE) + goto exitUnchanged; + + /* Mapping to new jump targets after NOPs are removed */ + addrmap = (int *)PyMem_Malloc(codelen * sizeof(int)); + if (addrmap == NULL) + goto exitError; + + blocks = markblocks(codestr, codelen); + if (blocks == NULL) + goto exitError; + assert(PyList_Check(consts)); + + for (i=0 ; i a is not b + not a in b --> a not in b + not a is not b --> a is b + not a not in b --> a in b + */ + case COMPARE_OP: + j = GETARG(codestr, i); + if (j < 6 || j > 9 || + codestr[i+3] != UNARY_NOT || + !ISBASICBLOCK(blocks,i,4)) + continue; + SETARG(codestr, i, (j^1)); + codestr[i+3] = NOP; + break; + + /* Replace LOAD_GLOBAL/LOAD_NAME None/True/False + with LOAD_CONST None/True/False */ + case LOAD_NAME: + case LOAD_GLOBAL: + j = GETARG(codestr, i); + name = _PyUnicode_AsString(PyTuple_GET_ITEM(names, j)); + h = load_global(codestr, i, name, consts); + if (h < 0) + goto exitError; + else if (h == 0) + continue; + cumlc = lastlc + 1; + break; + + /* Skip over LOAD_CONST trueconst + POP_JUMP_IF_FALSE xx. This improves + "while 1" performance. */ + case LOAD_CONST: + cumlc = lastlc + 1; + j = GETARG(codestr, i); + if (codestr[i+3] != POP_JUMP_IF_FALSE || + !ISBASICBLOCK(blocks,i,6) || + !PyObject_IsTrue(PyList_GET_ITEM(consts, j))) + continue; + memset(codestr+i, NOP, 6); + cumlc = 0; + break; + + /* Try to fold tuples of constants (includes a case for lists and sets + which are only used for "in" and "not in" tests). + Skip over BUILD_SEQN 1 UNPACK_SEQN 1. + Replace BUILD_SEQN 2 UNPACK_SEQN 2 with ROT2. + Replace BUILD_SEQN 3 UNPACK_SEQN 3 with ROT3 ROT2. */ + case BUILD_TUPLE: + case BUILD_LIST: + case BUILD_SET: + j = GETARG(codestr, i); + h = i - 3 * j; + if (h >= 0 && + j <= lastlc && + ((opcode == BUILD_TUPLE && + ISBASICBLOCK(blocks, h, 3*(j+1))) || + ((opcode == BUILD_LIST || opcode == BUILD_SET) && + codestr[i+3]==COMPARE_OP && + ISBASICBLOCK(blocks, h, 3*(j+2)) && + (GETARG(codestr,i+3)==6 || + GETARG(codestr,i+3)==7))) && + tuple_of_constants(&codestr[h], j, consts)) { + assert(codestr[i] == LOAD_CONST); + cumlc = 1; + break; + } + if (codestr[i+3] != UNPACK_SEQUENCE || + !ISBASICBLOCK(blocks,i,6) || + j != GETARG(codestr, i+3)) + continue; + if (j == 1) { + memset(codestr+i, NOP, 6); + } else if (j == 2) { + codestr[i] = ROT_TWO; + memset(codestr+i+1, NOP, 5); + } else if (j == 3) { + codestr[i] = ROT_THREE; + codestr[i+1] = ROT_TWO; + memset(codestr+i+2, NOP, 4); + } + break; + + /* Fold binary ops on constants. + LOAD_CONST c1 LOAD_CONST c2 BINOP --> LOAD_CONST binop(c1,c2) */ + case BINARY_POWER: + case BINARY_MULTIPLY: + case BINARY_TRUE_DIVIDE: + case BINARY_FLOOR_DIVIDE: + case BINARY_MODULO: + case BINARY_ADD: + case BINARY_SUBTRACT: + case BINARY_SUBSCR: + case BINARY_LSHIFT: + case BINARY_RSHIFT: + case BINARY_AND: + case BINARY_XOR: + case BINARY_OR: + if (lastlc >= 2 && + ISBASICBLOCK(blocks, i-6, 7) && + fold_binops_on_constants(&codestr[i-6], consts)) { + i -= 2; + assert(codestr[i] == LOAD_CONST); + cumlc = 1; + } + break; + + /* Fold unary ops on constants. + LOAD_CONST c1 UNARY_OP --> LOAD_CONST unary_op(c) */ + case UNARY_NEGATIVE: + case UNARY_INVERT: + case UNARY_POSITIVE: + if (lastlc >= 1 && + ISBASICBLOCK(blocks, i-3, 4) && + fold_unaryops_on_constants(&codestr[i-3], consts)) { + i -= 2; + assert(codestr[i] == LOAD_CONST); + cumlc = 1; + } + break; + + /* Simplify conditional jump to conditional jump where the + result of the first test implies the success of a similar + test or the failure of the opposite test. + Arises in code like: + "if a and b:" + "if a or b:" + "a and b or c" + "(a and b) and c" + x:JUMP_IF_FALSE_OR_POP y y:JUMP_IF_FALSE_OR_POP z + --> x:JUMP_IF_FALSE_OR_POP z + x:JUMP_IF_FALSE_OR_POP y y:JUMP_IF_TRUE_OR_POP z + --> x:POP_JUMP_IF_FALSE y+3 + where y+3 is the instruction following the second test. + */ + case JUMP_IF_FALSE_OR_POP: + case JUMP_IF_TRUE_OR_POP: + tgt = GETJUMPTGT(codestr, i); + j = codestr[tgt]; + if (CONDITIONAL_JUMP(j)) { + /* NOTE: all possible jumps here are + absolute! */ + if (JUMPS_ON_TRUE(j) == JUMPS_ON_TRUE(opcode)) { + /* The second jump will be + taken iff the first is. */ + tgttgt = GETJUMPTGT(codestr, tgt); + /* The current opcode inherits + its target's stack behaviour */ + codestr[i] = j; + SETARG(codestr, i, tgttgt); + goto reoptimize_current; + } else { + /* The second jump is not taken + if the first is (so jump past + it), and all conditional + jumps pop their argument when + they're not taken (so change + the first jump to pop its + argument when it's taken). */ + if (JUMPS_ON_TRUE(opcode)) + codestr[i] = POP_JUMP_IF_TRUE; + else + codestr[i] = POP_JUMP_IF_FALSE; + SETARG(codestr, i, (tgt + 3)); + goto reoptimize_current; + } + } + /* Intentional fallthrough */ + + /* Replace jumps to unconditional jumps */ + case POP_JUMP_IF_FALSE: + case POP_JUMP_IF_TRUE: + case FOR_ITER: + case JUMP_FORWARD: + case JUMP_ABSOLUTE: + case CONTINUE_LOOP: + case SETUP_LOOP: + case SETUP_EXCEPT: + case SETUP_FINALLY: + case SETUP_WITH: + tgt = GETJUMPTGT(codestr, i); + /* Replace JUMP_* to a RETURN into just a RETURN */ + if (UNCONDITIONAL_JUMP(opcode) && + codestr[tgt] == RETURN_VALUE) { + codestr[i] = RETURN_VALUE; + memset(codestr+i+1, NOP, 2); + continue; + } + if (!UNCONDITIONAL_JUMP(codestr[tgt])) + continue; + tgttgt = GETJUMPTGT(codestr, tgt); + if (opcode == JUMP_FORWARD) /* JMP_ABS can go backwards */ + opcode = JUMP_ABSOLUTE; + if (!ABSOLUTE_JUMP(opcode)) + tgttgt -= i + 3; /* Calc relative jump addr */ + if (tgttgt < 0) /* No backward relative jumps */ + continue; + codestr[i] = opcode; + SETARG(codestr, i, tgttgt); + break; + + case EXTENDED_ARG: + if (codestr[i+3] != MAKE_FUNCTION) + goto exitUnchanged; + /* don't visit MAKE_FUNCTION as GETARG will be wrong */ + i += 3; + break; + + /* Replace RETURN LOAD_CONST None RETURN with just RETURN */ + /* Remove unreachable JUMPs after RETURN */ + case RETURN_VALUE: + if (i+4 >= codelen) + continue; + if (codestr[i+4] == RETURN_VALUE && + ISBASICBLOCK(blocks,i,5)) + memset(codestr+i+1, NOP, 4); + else if (UNCONDITIONAL_JUMP(codestr[i+1]) && + ISBASICBLOCK(blocks,i,4)) + memset(codestr+i+1, NOP, 3); + break; + } + } + + /* Fixup linenotab */ + for (i=0, nops=0 ; iab_size = size; - b->ab_mem = (void *)(b + 1); - b->ab_next = NULL; - b->ab_offset = ROUNDUP((Py_uintptr_t)(b->ab_mem)) - - (Py_uintptr_t)(b->ab_mem); - return b; + /* Allocate header and block as one unit. + ab_mem points just past header. */ + block *b = (block *)malloc(sizeof(block) + size); + if (!b) + return NULL; + b->ab_size = size; + b->ab_mem = (void *)(b + 1); + b->ab_next = NULL; + b->ab_offset = ROUNDUP((Py_uintptr_t)(b->ab_mem)) - + (Py_uintptr_t)(b->ab_mem); + return b; } static void block_free(block *b) { - while (b) { - block *next = b->ab_next; - free(b); - b = next; - } + while (b) { + block *next = b->ab_next; + free(b); + b = next; + } } static void * block_alloc(block *b, size_t size) { - void *p; - assert(b); - size = ROUNDUP(size); - if (b->ab_offset + size > b->ab_size) { - /* If we need to allocate more memory than will fit in - the default block, allocate a one-off block that is - exactly the right size. */ - /* TODO(jhylton): Think about space waste at end of block */ - block *newbl = block_new( - size < DEFAULT_BLOCK_SIZE ? - DEFAULT_BLOCK_SIZE : size); - if (!newbl) - return NULL; - assert(!b->ab_next); - b->ab_next = newbl; - b = newbl; - } - - assert(b->ab_offset + size <= b->ab_size); - p = (void *)(((char *)b->ab_mem) + b->ab_offset); - b->ab_offset += size; - return p; + void *p; + assert(b); + size = ROUNDUP(size); + if (b->ab_offset + size > b->ab_size) { + /* If we need to allocate more memory than will fit in + the default block, allocate a one-off block that is + exactly the right size. */ + /* TODO(jhylton): Think about space waste at end of block */ + block *newbl = block_new( + size < DEFAULT_BLOCK_SIZE ? + DEFAULT_BLOCK_SIZE : size); + if (!newbl) + return NULL; + assert(!b->ab_next); + b->ab_next = newbl; + b = newbl; + } + + assert(b->ab_offset + size <= b->ab_size); + p = (void *)(((char *)b->ab_mem) + b->ab_offset); + b->ab_offset += size; + return p; } PyArena * PyArena_New() { - PyArena* arena = (PyArena *)malloc(sizeof(PyArena)); - if (!arena) - return (PyArena*)PyErr_NoMemory(); - - arena->a_head = block_new(DEFAULT_BLOCK_SIZE); - arena->a_cur = arena->a_head; - if (!arena->a_head) { - free((void *)arena); - return (PyArena*)PyErr_NoMemory(); - } - arena->a_objects = PyList_New(0); - if (!arena->a_objects) { - block_free(arena->a_head); - free((void *)arena); - return (PyArena*)PyErr_NoMemory(); - } + PyArena* arena = (PyArena *)malloc(sizeof(PyArena)); + if (!arena) + return (PyArena*)PyErr_NoMemory(); + + arena->a_head = block_new(DEFAULT_BLOCK_SIZE); + arena->a_cur = arena->a_head; + if (!arena->a_head) { + free((void *)arena); + return (PyArena*)PyErr_NoMemory(); + } + arena->a_objects = PyList_New(0); + if (!arena->a_objects) { + block_free(arena->a_head); + free((void *)arena); + return (PyArena*)PyErr_NoMemory(); + } #if defined(Py_DEBUG) - arena->total_allocs = 0; - arena->total_size = 0; - arena->total_blocks = 1; - arena->total_block_size = DEFAULT_BLOCK_SIZE; - arena->total_big_blocks = 0; + arena->total_allocs = 0; + arena->total_size = 0; + arena->total_blocks = 1; + arena->total_block_size = DEFAULT_BLOCK_SIZE; + arena->total_big_blocks = 0; #endif - return arena; + return arena; } void PyArena_Free(PyArena *arena) { - int r; - assert(arena); + int r; + assert(arena); #if defined(Py_DEBUG) - /* - fprintf(stderr, - "alloc=%d size=%d blocks=%d block_size=%d big=%d objects=%d\n", - arena->total_allocs, arena->total_size, arena->total_blocks, - arena->total_block_size, arena->total_big_blocks, - PyList_Size(arena->a_objects)); - */ + /* + fprintf(stderr, + "alloc=%d size=%d blocks=%d block_size=%d big=%d objects=%d\n", + arena->total_allocs, arena->total_size, arena->total_blocks, + arena->total_block_size, arena->total_big_blocks, + PyList_Size(arena->a_objects)); + */ #endif - block_free(arena->a_head); - /* This property normally holds, except when the code being compiled - is sys.getobjects(0), in which case there will be two references. - assert(arena->a_objects->ob_refcnt == 1); - */ - - /* Clear all the elements from the list. This is necessary - to guarantee that they will be DECREFed. */ - r = PyList_SetSlice(arena->a_objects, - 0, PyList_GET_SIZE(arena->a_objects), NULL); - assert(r == 0); - assert(PyList_GET_SIZE(arena->a_objects) == 0); - Py_DECREF(arena->a_objects); - free(arena); + block_free(arena->a_head); + /* This property normally holds, except when the code being compiled + is sys.getobjects(0), in which case there will be two references. + assert(arena->a_objects->ob_refcnt == 1); + */ + + /* Clear all the elements from the list. This is necessary + to guarantee that they will be DECREFed. */ + r = PyList_SetSlice(arena->a_objects, + 0, PyList_GET_SIZE(arena->a_objects), NULL); + assert(r == 0); + assert(PyList_GET_SIZE(arena->a_objects) == 0); + Py_DECREF(arena->a_objects); + free(arena); } void * PyArena_Malloc(PyArena *arena, size_t size) { - void *p = block_alloc(arena->a_cur, size); - if (!p) - return PyErr_NoMemory(); + void *p = block_alloc(arena->a_cur, size); + if (!p) + return PyErr_NoMemory(); #if defined(Py_DEBUG) - arena->total_allocs++; - arena->total_size += size; + arena->total_allocs++; + arena->total_size += size; #endif - /* Reset cur if we allocated a new block. */ - if (arena->a_cur->ab_next) { - arena->a_cur = arena->a_cur->ab_next; + /* Reset cur if we allocated a new block. */ + if (arena->a_cur->ab_next) { + arena->a_cur = arena->a_cur->ab_next; #if defined(Py_DEBUG) - arena->total_blocks++; - arena->total_block_size += arena->a_cur->ab_size; - if (arena->a_cur->ab_size > DEFAULT_BLOCK_SIZE) - ++arena->total_big_blocks; + arena->total_blocks++; + arena->total_block_size += arena->a_cur->ab_size; + if (arena->a_cur->ab_size > DEFAULT_BLOCK_SIZE) + ++arena->total_big_blocks; #endif - } - return p; + } + return p; } int PyArena_AddPyObject(PyArena *arena, PyObject *obj) { - int r = PyList_Append(arena->a_objects, obj); - if (r >= 0) { - Py_DECREF(obj); - } - return r; + int r = PyList_Append(arena->a_objects, obj); + if (r >= 0) { + Py_DECREF(obj); + } + return r; } Modified: python/branches/py3k-jit/Python/pymath.c ============================================================================== --- python/branches/py3k-jit/Python/pymath.c (original) +++ python/branches/py3k-jit/Python/pymath.c Mon May 10 23:55:43 2010 @@ -7,9 +7,9 @@ thus rounding from extended precision to double precision. */ double _Py_force_double(double x) { - volatile double y; - y = x; - return y; + volatile double y; + y = x; + return y; } #endif @@ -34,21 +34,21 @@ #ifndef HAVE_HYPOT double hypot(double x, double y) { - double yx; + double yx; - x = fabs(x); - y = fabs(y); - if (x < y) { - double temp = x; - x = y; - y = temp; - } - if (x == 0.) - return 0.; - else { - yx = y/x; - return x*sqrt(1.+yx*yx); - } + x = fabs(x); + y = fabs(y); + if (x < y) { + double temp = x; + x = y; + y = temp; + } + if (x == 0.) + return 0.; + else { + yx = y/x; + return x*sqrt(1.+yx*yx); + } } #endif /* HAVE_HYPOT */ @@ -56,12 +56,12 @@ double copysign(double x, double y) { - /* use atan2 to distinguish -0. from 0. */ - if (y > 0. || (y == 0. && atan2(y, -1.) > 0.)) { - return fabs(x); - } else { - return -fabs(x); - } + /* use atan2 to distinguish -0. from 0. */ + if (y > 0. || (y == 0. && atan2(y, -1.) > 0.)) { + return fabs(x); + } else { + return -fabs(x); + } } #endif /* HAVE_COPYSIGN */ @@ -73,7 +73,7 @@ absx = fabs(x); y = floor(absx); if (absx - y >= 0.5) - y += 1.0; + y += 1.0; return copysign(y, x); } #endif /* HAVE_ROUND */ Modified: python/branches/py3k-jit/Python/pystate.c ============================================================================== --- python/branches/py3k-jit/Python/pystate.c (original) +++ python/branches/py3k-jit/Python/pystate.c Mon May 10 23:55:43 2010 @@ -60,95 +60,95 @@ PyInterpreterState * PyInterpreterState_New(void) { - PyInterpreterState *interp = (PyInterpreterState *) - malloc(sizeof(PyInterpreterState)); + PyInterpreterState *interp = (PyInterpreterState *) + malloc(sizeof(PyInterpreterState)); - if (interp != NULL) { - HEAD_INIT(); + if (interp != NULL) { + HEAD_INIT(); #ifdef WITH_THREAD - if (head_mutex == NULL) - Py_FatalError("Can't initialize threads for interpreter"); + if (head_mutex == NULL) + Py_FatalError("Can't initialize threads for interpreter"); #endif - interp->modules = NULL; - interp->modules_reloading = NULL; - interp->modules_by_index = NULL; - interp->sysdict = NULL; - interp->builtins = NULL; - interp->tstate_head = NULL; - interp->codec_search_path = NULL; - interp->codec_search_cache = NULL; - interp->codec_error_registry = NULL; - interp->codecs_initialized = 0; + interp->modules = NULL; + interp->modules_reloading = NULL; + interp->modules_by_index = NULL; + interp->sysdict = NULL; + interp->builtins = NULL; + interp->tstate_head = NULL; + interp->codec_search_path = NULL; + interp->codec_search_cache = NULL; + interp->codec_error_registry = NULL; + interp->codecs_initialized = 0; #ifdef HAVE_DLOPEN #ifdef RTLD_NOW - interp->dlopenflags = RTLD_NOW; + interp->dlopenflags = RTLD_NOW; #else - interp->dlopenflags = RTLD_LAZY; + interp->dlopenflags = RTLD_LAZY; #endif #endif #ifdef WITH_TSC - interp->tscdump = 0; + interp->tscdump = 0; #endif - HEAD_LOCK(); - interp->next = interp_head; - interp_head = interp; - HEAD_UNLOCK(); - } + HEAD_LOCK(); + interp->next = interp_head; + interp_head = interp; + HEAD_UNLOCK(); + } - return interp; + return interp; } void PyInterpreterState_Clear(PyInterpreterState *interp) { - PyThreadState *p; - HEAD_LOCK(); - for (p = interp->tstate_head; p != NULL; p = p->next) - PyThreadState_Clear(p); - HEAD_UNLOCK(); - Py_CLEAR(interp->codec_search_path); - Py_CLEAR(interp->codec_search_cache); - Py_CLEAR(interp->codec_error_registry); - Py_CLEAR(interp->modules); - Py_CLEAR(interp->modules_by_index); - Py_CLEAR(interp->modules_reloading); - Py_CLEAR(interp->sysdict); - Py_CLEAR(interp->builtins); + PyThreadState *p; + HEAD_LOCK(); + for (p = interp->tstate_head; p != NULL; p = p->next) + PyThreadState_Clear(p); + HEAD_UNLOCK(); + Py_CLEAR(interp->codec_search_path); + Py_CLEAR(interp->codec_search_cache); + Py_CLEAR(interp->codec_error_registry); + Py_CLEAR(interp->modules); + Py_CLEAR(interp->modules_by_index); + Py_CLEAR(interp->modules_reloading); + Py_CLEAR(interp->sysdict); + Py_CLEAR(interp->builtins); } static void zapthreads(PyInterpreterState *interp) { - PyThreadState *p; - /* No need to lock the mutex here because this should only happen - when the threads are all really dead (XXX famous last words). */ - while ((p = interp->tstate_head) != NULL) { - PyThreadState_Delete(p); - } + PyThreadState *p; + /* No need to lock the mutex here because this should only happen + when the threads are all really dead (XXX famous last words). */ + while ((p = interp->tstate_head) != NULL) { + PyThreadState_Delete(p); + } } void PyInterpreterState_Delete(PyInterpreterState *interp) { - PyInterpreterState **p; - zapthreads(interp); - HEAD_LOCK(); - for (p = &interp_head; ; p = &(*p)->next) { - if (*p == NULL) - Py_FatalError( - "PyInterpreterState_Delete: invalid interp"); - if (*p == interp) - break; - } - if (interp->tstate_head != NULL) - Py_FatalError("PyInterpreterState_Delete: remaining threads"); - *p = interp->next; - HEAD_UNLOCK(); - free(interp); + PyInterpreterState **p; + zapthreads(interp); + HEAD_LOCK(); + for (p = &interp_head; ; p = &(*p)->next) { + if (*p == NULL) + Py_FatalError( + "PyInterpreterState_Delete: invalid interp"); + if (*p == interp) + break; + } + if (interp->tstate_head != NULL) + Py_FatalError("PyInterpreterState_Delete: remaining threads"); + *p = interp->next; + HEAD_UNLOCK(); + free(interp); } @@ -156,141 +156,141 @@ static struct _frame * threadstate_getframe(PyThreadState *self) { - return self->frame; + return self->frame; } static PyThreadState * new_threadstate(PyInterpreterState *interp, int init) { - PyThreadState *tstate = (PyThreadState *)malloc(sizeof(PyThreadState)); + PyThreadState *tstate = (PyThreadState *)malloc(sizeof(PyThreadState)); - if (_PyThreadState_GetFrame == NULL) - _PyThreadState_GetFrame = threadstate_getframe; + if (_PyThreadState_GetFrame == NULL) + _PyThreadState_GetFrame = threadstate_getframe; - if (tstate != NULL) { - tstate->interp = interp; + if (tstate != NULL) { + tstate->interp = interp; - tstate->frame = NULL; - tstate->recursion_depth = 0; - tstate->overflowed = 0; - tstate->recursion_critical = 0; - tstate->tracing = 0; - tstate->use_tracing = 0; - tstate->tick_counter = 0; - tstate->gilstate_counter = 0; - tstate->async_exc = NULL; + tstate->frame = NULL; + tstate->recursion_depth = 0; + tstate->overflowed = 0; + tstate->recursion_critical = 0; + tstate->tracing = 0; + tstate->use_tracing = 0; + tstate->tick_counter = 0; + tstate->gilstate_counter = 0; + tstate->async_exc = NULL; #ifdef WITH_THREAD - tstate->thread_id = PyThread_get_thread_ident(); + tstate->thread_id = PyThread_get_thread_ident(); #else - tstate->thread_id = 0; + tstate->thread_id = 0; #endif - tstate->dict = NULL; + tstate->dict = NULL; - tstate->curexc_type = NULL; - tstate->curexc_value = NULL; - tstate->curexc_traceback = NULL; - - tstate->exc_type = NULL; - tstate->exc_value = NULL; - tstate->exc_traceback = NULL; - - tstate->c_profilefunc = NULL; - tstate->c_tracefunc = NULL; - tstate->c_profileobj = NULL; - tstate->c_traceobj = NULL; - - if (init) - _PyThreadState_Init(tstate); - - HEAD_LOCK(); - tstate->next = interp->tstate_head; - interp->tstate_head = tstate; - HEAD_UNLOCK(); - } + tstate->curexc_type = NULL; + tstate->curexc_value = NULL; + tstate->curexc_traceback = NULL; + + tstate->exc_type = NULL; + tstate->exc_value = NULL; + tstate->exc_traceback = NULL; + + tstate->c_profilefunc = NULL; + tstate->c_tracefunc = NULL; + tstate->c_profileobj = NULL; + tstate->c_traceobj = NULL; + + if (init) + _PyThreadState_Init(tstate); + + HEAD_LOCK(); + tstate->next = interp->tstate_head; + interp->tstate_head = tstate; + HEAD_UNLOCK(); + } - return tstate; + return tstate; } PyThreadState * PyThreadState_New(PyInterpreterState *interp) { - return new_threadstate(interp, 1); + return new_threadstate(interp, 1); } PyThreadState * _PyThreadState_Prealloc(PyInterpreterState *interp) { - return new_threadstate(interp, 0); + return new_threadstate(interp, 0); } void _PyThreadState_Init(PyThreadState *tstate) { #ifdef WITH_THREAD - _PyGILState_NoteThreadState(tstate); + _PyGILState_NoteThreadState(tstate); #endif } PyObject* PyState_FindModule(struct PyModuleDef* m) { - Py_ssize_t index = m->m_base.m_index; - PyInterpreterState *state = PyThreadState_GET()->interp; - PyObject *res; - if (index == 0) - return NULL; - if (state->modules_by_index == NULL) - return NULL; - if (index > PyList_GET_SIZE(state->modules_by_index)) - return NULL; - res = PyList_GET_ITEM(state->modules_by_index, index); - return res==Py_None ? NULL : res; + Py_ssize_t index = m->m_base.m_index; + PyInterpreterState *state = PyThreadState_GET()->interp; + PyObject *res; + if (index == 0) + return NULL; + if (state->modules_by_index == NULL) + return NULL; + if (index > PyList_GET_SIZE(state->modules_by_index)) + return NULL; + res = PyList_GET_ITEM(state->modules_by_index, index); + return res==Py_None ? NULL : res; } int _PyState_AddModule(PyObject* module, struct PyModuleDef* def) { - PyInterpreterState *state = PyThreadState_GET()->interp; - if (!def) - return -1; - if (!state->modules_by_index) { - state->modules_by_index = PyList_New(0); - if (!state->modules_by_index) - return -1; - } - while(PyList_GET_SIZE(state->modules_by_index) <= def->m_base.m_index) - if (PyList_Append(state->modules_by_index, Py_None) < 0) - return -1; - Py_INCREF(module); - return PyList_SetItem(state->modules_by_index, - def->m_base.m_index, module); + PyInterpreterState *state = PyThreadState_GET()->interp; + if (!def) + return -1; + if (!state->modules_by_index) { + state->modules_by_index = PyList_New(0); + if (!state->modules_by_index) + return -1; + } + while(PyList_GET_SIZE(state->modules_by_index) <= def->m_base.m_index) + if (PyList_Append(state->modules_by_index, Py_None) < 0) + return -1; + Py_INCREF(module); + return PyList_SetItem(state->modules_by_index, + def->m_base.m_index, module); } void PyThreadState_Clear(PyThreadState *tstate) { - if (Py_VerboseFlag && tstate->frame != NULL) - fprintf(stderr, - "PyThreadState_Clear: warning: thread still has a frame\n"); - - Py_CLEAR(tstate->frame); - - Py_CLEAR(tstate->dict); - Py_CLEAR(tstate->async_exc); - - Py_CLEAR(tstate->curexc_type); - Py_CLEAR(tstate->curexc_value); - Py_CLEAR(tstate->curexc_traceback); - - Py_CLEAR(tstate->exc_type); - Py_CLEAR(tstate->exc_value); - Py_CLEAR(tstate->exc_traceback); - - tstate->c_profilefunc = NULL; - tstate->c_tracefunc = NULL; - Py_CLEAR(tstate->c_profileobj); - Py_CLEAR(tstate->c_traceobj); + if (Py_VerboseFlag && tstate->frame != NULL) + fprintf(stderr, + "PyThreadState_Clear: warning: thread still has a frame\n"); + + Py_CLEAR(tstate->frame); + + Py_CLEAR(tstate->dict); + Py_CLEAR(tstate->async_exc); + + Py_CLEAR(tstate->curexc_type); + Py_CLEAR(tstate->curexc_value); + Py_CLEAR(tstate->curexc_traceback); + + Py_CLEAR(tstate->exc_type); + Py_CLEAR(tstate->exc_value); + Py_CLEAR(tstate->exc_traceback); + + tstate->c_profilefunc = NULL; + tstate->c_tracefunc = NULL; + Py_CLEAR(tstate->c_profileobj); + Py_CLEAR(tstate->c_traceobj); } @@ -298,50 +298,50 @@ static void tstate_delete_common(PyThreadState *tstate) { - PyInterpreterState *interp; - PyThreadState **p; - PyThreadState *prev_p = NULL; - if (tstate == NULL) - Py_FatalError("PyThreadState_Delete: NULL tstate"); - interp = tstate->interp; - if (interp == NULL) - Py_FatalError("PyThreadState_Delete: NULL interp"); - HEAD_LOCK(); - for (p = &interp->tstate_head; ; p = &(*p)->next) { - if (*p == NULL) - Py_FatalError( - "PyThreadState_Delete: invalid tstate"); - if (*p == tstate) - break; - /* Sanity check. These states should never happen but if - * they do we must abort. Otherwise we'll end up spinning in - * in a tight loop with the lock held. A similar check is done - * in thread.c find_key(). */ - if (*p == prev_p) - Py_FatalError( - "PyThreadState_Delete: small circular list(!)" - " and tstate not found."); - prev_p = *p; - if ((*p)->next == interp->tstate_head) - Py_FatalError( - "PyThreadState_Delete: circular list(!) and" - " tstate not found."); - } - *p = tstate->next; - HEAD_UNLOCK(); - free(tstate); + PyInterpreterState *interp; + PyThreadState **p; + PyThreadState *prev_p = NULL; + if (tstate == NULL) + Py_FatalError("PyThreadState_Delete: NULL tstate"); + interp = tstate->interp; + if (interp == NULL) + Py_FatalError("PyThreadState_Delete: NULL interp"); + HEAD_LOCK(); + for (p = &interp->tstate_head; ; p = &(*p)->next) { + if (*p == NULL) + Py_FatalError( + "PyThreadState_Delete: invalid tstate"); + if (*p == tstate) + break; + /* Sanity check. These states should never happen but if + * they do we must abort. Otherwise we'll end up spinning in + * in a tight loop with the lock held. A similar check is done + * in thread.c find_key(). */ + if (*p == prev_p) + Py_FatalError( + "PyThreadState_Delete: small circular list(!)" + " and tstate not found."); + prev_p = *p; + if ((*p)->next == interp->tstate_head) + Py_FatalError( + "PyThreadState_Delete: circular list(!) and" + " tstate not found."); + } + *p = tstate->next; + HEAD_UNLOCK(); + free(tstate); } void PyThreadState_Delete(PyThreadState *tstate) { - if (tstate == _Py_atomic_load_relaxed(&_PyThreadState_Current)) - Py_FatalError("PyThreadState_Delete: tstate is still current"); - tstate_delete_common(tstate); + if (tstate == _Py_atomic_load_relaxed(&_PyThreadState_Current)) + Py_FatalError("PyThreadState_Delete: tstate is still current"); + tstate_delete_common(tstate); #ifdef WITH_THREAD - if (autoTLSkey && PyThread_get_key_value(autoTLSkey) == tstate) - PyThread_delete_key_value(autoTLSkey); + if (autoTLSkey && PyThread_get_key_value(autoTLSkey) == tstate) + PyThread_delete_key_value(autoTLSkey); #endif /* WITH_THREAD */ } @@ -350,16 +350,16 @@ void PyThreadState_DeleteCurrent() { - PyThreadState *tstate = (PyThreadState*)_Py_atomic_load_relaxed( - &_PyThreadState_Current); - if (tstate == NULL) - Py_FatalError( - "PyThreadState_DeleteCurrent: no current tstate"); - _Py_atomic_store_relaxed(&_PyThreadState_Current, NULL); - tstate_delete_common(tstate); - if (autoTLSkey && PyThread_get_key_value(autoTLSkey) == tstate) - PyThread_delete_key_value(autoTLSkey); - PyEval_ReleaseLock(); + PyThreadState *tstate = (PyThreadState*)_Py_atomic_load_relaxed( + &_PyThreadState_Current); + if (tstate == NULL) + Py_FatalError( + "PyThreadState_DeleteCurrent: no current tstate"); + _Py_atomic_store_relaxed(&_PyThreadState_Current, NULL); + tstate_delete_common(tstate); + if (autoTLSkey && PyThread_get_key_value(autoTLSkey) == tstate) + PyThread_delete_key_value(autoTLSkey); + PyEval_ReleaseLock(); } #endif /* WITH_THREAD */ @@ -367,39 +367,39 @@ PyThreadState * PyThreadState_Get(void) { - PyThreadState *tstate = (PyThreadState*)_Py_atomic_load_relaxed( - &_PyThreadState_Current); - if (tstate == NULL) - Py_FatalError("PyThreadState_Get: no current thread"); + PyThreadState *tstate = (PyThreadState*)_Py_atomic_load_relaxed( + &_PyThreadState_Current); + if (tstate == NULL) + Py_FatalError("PyThreadState_Get: no current thread"); - return tstate; + return tstate; } PyThreadState * PyThreadState_Swap(PyThreadState *newts) { - PyThreadState *oldts = (PyThreadState*)_Py_atomic_load_relaxed( - &_PyThreadState_Current); + PyThreadState *oldts = (PyThreadState*)_Py_atomic_load_relaxed( + &_PyThreadState_Current); - _Py_atomic_store_relaxed(&_PyThreadState_Current, newts); - /* It should not be possible for more than one thread state - to be used for a thread. Check this the best we can in debug - builds. - */ + _Py_atomic_store_relaxed(&_PyThreadState_Current, newts); + /* It should not be possible for more than one thread state + to be used for a thread. Check this the best we can in debug + builds. + */ #if defined(Py_DEBUG) && defined(WITH_THREAD) - if (newts) { - /* This can be called from PyEval_RestoreThread(). Similar - to it, we need to ensure errno doesn't change. - */ - int err = errno; - PyThreadState *check = PyGILState_GetThisThreadState(); - if (check && check->interp == newts->interp && check != newts) - Py_FatalError("Invalid thread state for this thread"); - errno = err; - } + if (newts) { + /* This can be called from PyEval_RestoreThread(). Similar + to it, we need to ensure errno doesn't change. + */ + int err = errno; + PyThreadState *check = PyGILState_GetThisThreadState(); + if (check && check->interp == newts->interp && check != newts) + Py_FatalError("Invalid thread state for this thread"); + errno = err; + } #endif - return oldts; + return oldts; } /* An extension mechanism to store arbitrary additional per-thread state. @@ -411,18 +411,18 @@ PyObject * PyThreadState_GetDict(void) { - PyThreadState *tstate = (PyThreadState*)_Py_atomic_load_relaxed( - &_PyThreadState_Current); - if (tstate == NULL) - return NULL; - - if (tstate->dict == NULL) { - PyObject *d; - tstate->dict = d = PyDict_New(); - if (d == NULL) - PyErr_Clear(); - } - return tstate->dict; + PyThreadState *tstate = (PyThreadState*)_Py_atomic_load_relaxed( + &_PyThreadState_Current); + if (tstate == NULL) + return NULL; + + if (tstate->dict == NULL) { + PyObject *d; + tstate->dict = d = PyDict_New(); + if (d == NULL) + PyErr_Clear(); + } + return tstate->dict; } @@ -436,37 +436,37 @@ int PyThreadState_SetAsyncExc(long id, PyObject *exc) { - PyThreadState *tstate = PyThreadState_GET(); - PyInterpreterState *interp = tstate->interp; - PyThreadState *p; - - /* Although the GIL is held, a few C API functions can be called - * without the GIL held, and in particular some that create and - * destroy thread and interpreter states. Those can mutate the - * list of thread states we're traversing, so to prevent that we lock - * head_mutex for the duration. - */ - HEAD_LOCK(); - for (p = interp->tstate_head; p != NULL; p = p->next) { - if (p->thread_id == id) { - /* Tricky: we need to decref the current value - * (if any) in p->async_exc, but that can in turn - * allow arbitrary Python code to run, including - * perhaps calls to this function. To prevent - * deadlock, we need to release head_mutex before - * the decref. - */ - PyObject *old_exc = p->async_exc; - Py_XINCREF(exc); - p->async_exc = exc; - HEAD_UNLOCK(); - Py_XDECREF(old_exc); - _PyEval_SignalAsyncExc(); - return 1; - } - } - HEAD_UNLOCK(); - return 0; + PyThreadState *tstate = PyThreadState_GET(); + PyInterpreterState *interp = tstate->interp; + PyThreadState *p; + + /* Although the GIL is held, a few C API functions can be called + * without the GIL held, and in particular some that create and + * destroy thread and interpreter states. Those can mutate the + * list of thread states we're traversing, so to prevent that we lock + * head_mutex for the duration. + */ + HEAD_LOCK(); + for (p = interp->tstate_head; p != NULL; p = p->next) { + if (p->thread_id == id) { + /* Tricky: we need to decref the current value + * (if any) in p->async_exc, but that can in turn + * allow arbitrary Python code to run, including + * perhaps calls to this function. To prevent + * deadlock, we need to release head_mutex before + * the decref. + */ + PyObject *old_exc = p->async_exc; + Py_XINCREF(exc); + p->async_exc = exc; + HEAD_UNLOCK(); + Py_XDECREF(old_exc); + _PyEval_SignalAsyncExc(); + return 1; + } + } + HEAD_UNLOCK(); + return 0; } @@ -476,22 +476,22 @@ PyInterpreterState * PyInterpreterState_Head(void) { - return interp_head; + return interp_head; } PyInterpreterState * PyInterpreterState_Next(PyInterpreterState *interp) { - return interp->next; + return interp->next; } PyThreadState * PyInterpreterState_ThreadHead(PyInterpreterState *interp) { - return interp->tstate_head; + return interp->tstate_head; } PyThreadState * PyThreadState_Next(PyThreadState *tstate) { - return tstate->next; + return tstate->next; } /* The implementation of sys._current_frames(). This is intended to be @@ -502,44 +502,44 @@ PyObject * _PyThread_CurrentFrames(void) { - PyObject *result; - PyInterpreterState *i; + PyObject *result; + PyInterpreterState *i; - result = PyDict_New(); - if (result == NULL) - return NULL; - - /* for i in all interpreters: - * for t in all of i's thread states: - * if t's frame isn't NULL, map t's id to its frame - * Because these lists can mutute even when the GIL is held, we - * need to grab head_mutex for the duration. - */ - HEAD_LOCK(); - for (i = interp_head; i != NULL; i = i->next) { - PyThreadState *t; - for (t = i->tstate_head; t != NULL; t = t->next) { - PyObject *id; - int stat; - struct _frame *frame = t->frame; - if (frame == NULL) - continue; - id = PyLong_FromLong(t->thread_id); - if (id == NULL) - goto Fail; - stat = PyDict_SetItem(result, id, (PyObject *)frame); - Py_DECREF(id); - if (stat < 0) - goto Fail; - } - } - HEAD_UNLOCK(); - return result; + result = PyDict_New(); + if (result == NULL) + return NULL; + + /* for i in all interpreters: + * for t in all of i's thread states: + * if t's frame isn't NULL, map t's id to its frame + * Because these lists can mutute even when the GIL is held, we + * need to grab head_mutex for the duration. + */ + HEAD_LOCK(); + for (i = interp_head; i != NULL; i = i->next) { + PyThreadState *t; + for (t = i->tstate_head; t != NULL; t = t->next) { + PyObject *id; + int stat; + struct _frame *frame = t->frame; + if (frame == NULL) + continue; + id = PyLong_FromLong(t->thread_id); + if (id == NULL) + goto Fail; + stat = PyDict_SetItem(result, id, (PyObject *)frame); + Py_DECREF(id); + if (stat < 0) + goto Fail; + } + } + HEAD_UNLOCK(); + return result; Fail: - HEAD_UNLOCK(); - Py_DECREF(result); - return NULL; + HEAD_UNLOCK(); + Py_DECREF(result); + return NULL; } /* Python "auto thread state" API. */ @@ -556,9 +556,9 @@ static int PyThreadState_IsCurrent(PyThreadState *tstate) { - /* Must be the tstate for this thread */ - assert(PyGILState_GetThisThreadState()==tstate); - return tstate == _Py_atomic_load_relaxed(&_PyThreadState_Current); + /* Must be the tstate for this thread */ + assert(PyGILState_GetThisThreadState()==tstate); + return tstate == _Py_atomic_load_relaxed(&_PyThreadState_Current); } /* Internal initialization/finalization functions called by @@ -567,21 +567,21 @@ void _PyGILState_Init(PyInterpreterState *i, PyThreadState *t) { - assert(i && t); /* must init with valid states */ - autoTLSkey = PyThread_create_key(); - autoInterpreterState = i; - assert(PyThread_get_key_value(autoTLSkey) == NULL); - assert(t->gilstate_counter == 0); + assert(i && t); /* must init with valid states */ + autoTLSkey = PyThread_create_key(); + autoInterpreterState = i; + assert(PyThread_get_key_value(autoTLSkey) == NULL); + assert(t->gilstate_counter == 0); - _PyGILState_NoteThreadState(t); + _PyGILState_NoteThreadState(t); } void _PyGILState_Fini(void) { - PyThread_delete_key(autoTLSkey); - autoTLSkey = 0; - autoInterpreterState = NULL; + PyThread_delete_key(autoTLSkey); + autoTLSkey = 0; + autoInterpreterState = NULL; } /* When a thread state is created for a thread by some mechanism other than @@ -592,113 +592,113 @@ static void _PyGILState_NoteThreadState(PyThreadState* tstate) { - /* If autoTLSkey is 0, this must be the very first threadstate created - in Py_Initialize(). Don't do anything for now (we'll be back here - when _PyGILState_Init is called). */ - if (!autoTLSkey) - return; - - /* Stick the thread state for this thread in thread local storage. - - The only situation where you can legitimately have more than one - thread state for an OS level thread is when there are multiple - interpreters, when: - - a) You shouldn't really be using the PyGILState_ APIs anyway, - and: - - b) The slightly odd way PyThread_set_key_value works (see - comments by its implementation) means that the first thread - state created for that given OS level thread will "win", - which seems reasonable behaviour. - */ - if (PyThread_set_key_value(autoTLSkey, (void *)tstate) < 0) - Py_FatalError("Couldn't create autoTLSkey mapping"); + /* If autoTLSkey is 0, this must be the very first threadstate created + in Py_Initialize(). Don't do anything for now (we'll be back here + when _PyGILState_Init is called). */ + if (!autoTLSkey) + return; + + /* Stick the thread state for this thread in thread local storage. + + The only situation where you can legitimately have more than one + thread state for an OS level thread is when there are multiple + interpreters, when: + + a) You shouldn't really be using the PyGILState_ APIs anyway, + and: + + b) The slightly odd way PyThread_set_key_value works (see + comments by its implementation) means that the first thread + state created for that given OS level thread will "win", + which seems reasonable behaviour. + */ + if (PyThread_set_key_value(autoTLSkey, (void *)tstate) < 0) + Py_FatalError("Couldn't create autoTLSkey mapping"); - /* PyGILState_Release must not try to delete this thread state. */ - tstate->gilstate_counter = 1; + /* PyGILState_Release must not try to delete this thread state. */ + tstate->gilstate_counter = 1; } /* The public functions */ PyThreadState * PyGILState_GetThisThreadState(void) { - if (autoInterpreterState == NULL || autoTLSkey == 0) - return NULL; - return (PyThreadState *)PyThread_get_key_value(autoTLSkey); + if (autoInterpreterState == NULL || autoTLSkey == 0) + return NULL; + return (PyThreadState *)PyThread_get_key_value(autoTLSkey); } PyGILState_STATE PyGILState_Ensure(void) { - int current; - PyThreadState *tcur; - /* Note that we do not auto-init Python here - apart from - potential races with 2 threads auto-initializing, pep-311 - spells out other issues. Embedders are expected to have - called Py_Initialize() and usually PyEval_InitThreads(). - */ - assert(autoInterpreterState); /* Py_Initialize() hasn't been called! */ - tcur = (PyThreadState *)PyThread_get_key_value(autoTLSkey); - if (tcur == NULL) { - /* Create a new thread state for this thread */ - tcur = PyThreadState_New(autoInterpreterState); - if (tcur == NULL) - Py_FatalError("Couldn't create thread-state for new thread"); - /* This is our thread state! We'll need to delete it in the - matching call to PyGILState_Release(). */ - tcur->gilstate_counter = 0; - current = 0; /* new thread state is never current */ - } - else - current = PyThreadState_IsCurrent(tcur); - if (current == 0) - PyEval_RestoreThread(tcur); - /* Update our counter in the thread-state - no need for locks: - - tcur will remain valid as we hold the GIL. - - the counter is safe as we are the only thread "allowed" - to modify this value - */ - ++tcur->gilstate_counter; - return current ? PyGILState_LOCKED : PyGILState_UNLOCKED; + int current; + PyThreadState *tcur; + /* Note that we do not auto-init Python here - apart from + potential races with 2 threads auto-initializing, pep-311 + spells out other issues. Embedders are expected to have + called Py_Initialize() and usually PyEval_InitThreads(). + */ + assert(autoInterpreterState); /* Py_Initialize() hasn't been called! */ + tcur = (PyThreadState *)PyThread_get_key_value(autoTLSkey); + if (tcur == NULL) { + /* Create a new thread state for this thread */ + tcur = PyThreadState_New(autoInterpreterState); + if (tcur == NULL) + Py_FatalError("Couldn't create thread-state for new thread"); + /* This is our thread state! We'll need to delete it in the + matching call to PyGILState_Release(). */ + tcur->gilstate_counter = 0; + current = 0; /* new thread state is never current */ + } + else + current = PyThreadState_IsCurrent(tcur); + if (current == 0) + PyEval_RestoreThread(tcur); + /* Update our counter in the thread-state - no need for locks: + - tcur will remain valid as we hold the GIL. + - the counter is safe as we are the only thread "allowed" + to modify this value + */ + ++tcur->gilstate_counter; + return current ? PyGILState_LOCKED : PyGILState_UNLOCKED; } void PyGILState_Release(PyGILState_STATE oldstate) { - PyThreadState *tcur = (PyThreadState *)PyThread_get_key_value( - autoTLSkey); - if (tcur == NULL) - Py_FatalError("auto-releasing thread-state, " - "but no thread-state for this thread"); - /* We must hold the GIL and have our thread state current */ - /* XXX - remove the check - the assert should be fine, - but while this is very new (April 2003), the extra check - by release-only users can't hurt. - */ - if (! PyThreadState_IsCurrent(tcur)) - Py_FatalError("This thread state must be current when releasing"); - assert(PyThreadState_IsCurrent(tcur)); - --tcur->gilstate_counter; - assert(tcur->gilstate_counter >= 0); /* illegal counter value */ - - /* If we're going to destroy this thread-state, we must - * clear it while the GIL is held, as destructors may run. - */ - if (tcur->gilstate_counter == 0) { - /* can't have been locked when we created it */ - assert(oldstate == PyGILState_UNLOCKED); - PyThreadState_Clear(tcur); - /* Delete the thread-state. Note this releases the GIL too! - * It's vital that the GIL be held here, to avoid shutdown - * races; see bugs 225673 and 1061968 (that nasty bug has a - * habit of coming back). - */ - PyThreadState_DeleteCurrent(); - } - /* Release the lock if necessary */ - else if (oldstate == PyGILState_UNLOCKED) - PyEval_SaveThread(); + PyThreadState *tcur = (PyThreadState *)PyThread_get_key_value( + autoTLSkey); + if (tcur == NULL) + Py_FatalError("auto-releasing thread-state, " + "but no thread-state for this thread"); + /* We must hold the GIL and have our thread state current */ + /* XXX - remove the check - the assert should be fine, + but while this is very new (April 2003), the extra check + by release-only users can't hurt. + */ + if (! PyThreadState_IsCurrent(tcur)) + Py_FatalError("This thread state must be current when releasing"); + assert(PyThreadState_IsCurrent(tcur)); + --tcur->gilstate_counter; + assert(tcur->gilstate_counter >= 0); /* illegal counter value */ + + /* If we're going to destroy this thread-state, we must + * clear it while the GIL is held, as destructors may run. + */ + if (tcur->gilstate_counter == 0) { + /* can't have been locked when we created it */ + assert(oldstate == PyGILState_UNLOCKED); + PyThreadState_Clear(tcur); + /* Delete the thread-state. Note this releases the GIL too! + * It's vital that the GIL be held here, to avoid shutdown + * races; see bugs 225673 and 1061968 (that nasty bug has a + * habit of coming back). + */ + PyThreadState_DeleteCurrent(); + } + /* Release the lock if necessary */ + else if (oldstate == PyGILState_UNLOCKED) + PyEval_SaveThread(); } #ifdef __cplusplus Modified: python/branches/py3k-jit/Python/pystrcmp.c ============================================================================== --- python/branches/py3k-jit/Python/pystrcmp.c (original) +++ python/branches/py3k-jit/Python/pystrcmp.c Mon May 10 23:55:43 2010 @@ -6,21 +6,21 @@ int PyOS_mystrnicmp(const char *s1, const char *s2, Py_ssize_t size) { - if (size == 0) - return 0; - while ((--size > 0) && - (tolower((unsigned)*s1) == tolower((unsigned)*s2))) { - if (!*s1++ || !*s2++) - break; - } - return tolower((unsigned)*s1) - tolower((unsigned)*s2); + if (size == 0) + return 0; + while ((--size > 0) && + (tolower((unsigned)*s1) == tolower((unsigned)*s2))) { + if (!*s1++ || !*s2++) + break; + } + return tolower((unsigned)*s1) - tolower((unsigned)*s2); } int PyOS_mystricmp(const char *s1, const char *s2) { - while (*s1 && (tolower((unsigned)*s1++) == tolower((unsigned)*s2++))) { - ; - } - return (tolower((unsigned)*s1) - tolower((unsigned)*s2)); + while (*s1 && (tolower((unsigned)*s1++) == tolower((unsigned)*s2++))) { + ; + } + return (tolower((unsigned)*s1) - tolower((unsigned)*s2)); } Modified: python/branches/py3k-jit/Python/pystrtod.c ============================================================================== --- python/branches/py3k-jit/Python/pystrtod.c (original) +++ python/branches/py3k-jit/Python/pystrtod.c Mon May 10 23:55:43 2010 @@ -9,11 +9,11 @@ static int case_insensitive_match(const char *s, const char *t) { - while(*t && Py_TOLOWER(*s) == *t) { - s++; - t++; - } - return *t ? 0 : 1; + while(*t && Py_TOLOWER(*s) == *t) { + s++; + t++; + } + return *t ? 0 : 1; } /* _Py_parse_inf_or_nan: Attempt to parse a string of the form "nan", "inf" or @@ -25,36 +25,36 @@ double _Py_parse_inf_or_nan(const char *p, char **endptr) { - double retval; - const char *s; - int negate = 0; - - s = p; - if (*s == '-') { - negate = 1; - s++; - } - else if (*s == '+') { - s++; - } - if (case_insensitive_match(s, "inf")) { - s += 3; - if (case_insensitive_match(s, "inity")) - s += 5; - retval = negate ? -Py_HUGE_VAL : Py_HUGE_VAL; - } + double retval; + const char *s; + int negate = 0; + + s = p; + if (*s == '-') { + negate = 1; + s++; + } + else if (*s == '+') { + s++; + } + if (case_insensitive_match(s, "inf")) { + s += 3; + if (case_insensitive_match(s, "inity")) + s += 5; + retval = negate ? -Py_HUGE_VAL : Py_HUGE_VAL; + } #ifdef Py_NAN - else if (case_insensitive_match(s, "nan")) { - s += 3; - retval = negate ? -Py_NAN : Py_NAN; - } + else if (case_insensitive_match(s, "nan")) { + s += 3; + retval = negate ? -Py_NAN : Py_NAN; + } #endif - else { - s = p; - retval = -1.0; - } - *endptr = (char *)s; - return retval; + else { + s = p; + retval = -1.0; + } + *endptr = (char *)s; + return retval; } /** @@ -62,7 +62,7 @@ * @nptr: the string to convert to a numeric value. * @endptr: if non-%NULL, it returns the character after * the last character used in the conversion. - * + * * Converts a string to a #gdouble value. * This function behaves like the standard strtod() function * does in the C locale. It does this without actually @@ -79,7 +79,7 @@ * stored in %errno. If the correct value would cause underflow, * zero is returned and %ERANGE is stored in %errno. * If memory allocation fails, %ENOMEM is stored in %errno. - * + * * This function resets %errno before calling strtod() so that * you can reliably detect overflow and underflow. * @@ -91,23 +91,23 @@ static double _PyOS_ascii_strtod(const char *nptr, char **endptr) { - double result; - _Py_SET_53BIT_PRECISION_HEADER; + double result; + _Py_SET_53BIT_PRECISION_HEADER; - assert(nptr != NULL); - /* Set errno to zero, so that we can distinguish zero results - and underflows */ - errno = 0; - - _Py_SET_53BIT_PRECISION_START; - result = _Py_dg_strtod(nptr, endptr); - _Py_SET_53BIT_PRECISION_END; - - if (*endptr == nptr) - /* string might represent an inf or nan */ - result = _Py_parse_inf_or_nan(nptr, endptr); + assert(nptr != NULL); + /* Set errno to zero, so that we can distinguish zero results + and underflows */ + errno = 0; + + _Py_SET_53BIT_PRECISION_START; + result = _Py_dg_strtod(nptr, endptr); + _Py_SET_53BIT_PRECISION_END; + + if (*endptr == nptr) + /* string might represent an inf or nan */ + result = _Py_parse_inf_or_nan(nptr, endptr); - return result; + return result; } @@ -124,148 +124,148 @@ static double _PyOS_ascii_strtod(const char *nptr, char **endptr) { - char *fail_pos; - double val = -1.0; - struct lconv *locale_data; - const char *decimal_point; - size_t decimal_point_len; - const char *p, *decimal_point_pos; - const char *end = NULL; /* Silence gcc */ - const char *digits_pos = NULL; - int negate = 0; - - assert(nptr != NULL); - - fail_pos = NULL; - - locale_data = localeconv(); - decimal_point = locale_data->decimal_point; - decimal_point_len = strlen(decimal_point); - - assert(decimal_point_len != 0); - - decimal_point_pos = NULL; - - /* Parse infinities and nans */ - val = _Py_parse_inf_or_nan(nptr, endptr); - if (*endptr != nptr) - return val; - - /* Set errno to zero, so that we can distinguish zero results - and underflows */ - errno = 0; - - /* We process the optional sign manually, then pass the remainder to - the system strtod. This ensures that the result of an underflow - has the correct sign. (bug #1725) */ - p = nptr; - /* Process leading sign, if present */ - if (*p == '-') { - negate = 1; - p++; - } - else if (*p == '+') { - p++; - } - - /* Some platform strtods accept hex floats; Python shouldn't (at the - moment), so we check explicitly for strings starting with '0x'. */ - if (*p == '0' && (*(p+1) == 'x' || *(p+1) == 'X')) - goto invalid_string; - - /* Check that what's left begins with a digit or decimal point */ - if (!Py_ISDIGIT(*p) && *p != '.') - goto invalid_string; - - digits_pos = p; - if (decimal_point[0] != '.' || - decimal_point[1] != 0) - { - /* Look for a '.' in the input; if present, it'll need to be - swapped for the current locale's decimal point before we - call strtod. On the other hand, if we find the current - locale's decimal point then the input is invalid. */ - while (Py_ISDIGIT(*p)) - p++; - - if (*p == '.') - { - decimal_point_pos = p++; - - /* locate end of number */ - while (Py_ISDIGIT(*p)) - p++; - - if (*p == 'e' || *p == 'E') - p++; - if (*p == '+' || *p == '-') - p++; - while (Py_ISDIGIT(*p)) - p++; - end = p; - } - else if (strncmp(p, decimal_point, decimal_point_len) == 0) - /* Python bug #1417699 */ - goto invalid_string; - /* For the other cases, we need not convert the decimal - point */ - } - - if (decimal_point_pos) { - char *copy, *c; - /* Create a copy of the input, with the '.' converted to the - locale-specific decimal point */ - copy = (char *)PyMem_MALLOC(end - digits_pos + - 1 + decimal_point_len); - if (copy == NULL) { - *endptr = (char *)nptr; - errno = ENOMEM; - return val; - } - - c = copy; - memcpy(c, digits_pos, decimal_point_pos - digits_pos); - c += decimal_point_pos - digits_pos; - memcpy(c, decimal_point, decimal_point_len); - c += decimal_point_len; - memcpy(c, decimal_point_pos + 1, - end - (decimal_point_pos + 1)); - c += end - (decimal_point_pos + 1); - *c = 0; - - val = strtod(copy, &fail_pos); - - if (fail_pos) - { - if (fail_pos > decimal_point_pos) - fail_pos = (char *)digits_pos + - (fail_pos - copy) - - (decimal_point_len - 1); - else - fail_pos = (char *)digits_pos + - (fail_pos - copy); - } - - PyMem_FREE(copy); - - } - else { - val = strtod(digits_pos, &fail_pos); - } - - if (fail_pos == digits_pos) - goto invalid_string; - - if (negate && fail_pos != nptr) - val = -val; - *endptr = fail_pos; + char *fail_pos; + double val = -1.0; + struct lconv *locale_data; + const char *decimal_point; + size_t decimal_point_len; + const char *p, *decimal_point_pos; + const char *end = NULL; /* Silence gcc */ + const char *digits_pos = NULL; + int negate = 0; + + assert(nptr != NULL); + + fail_pos = NULL; + + locale_data = localeconv(); + decimal_point = locale_data->decimal_point; + decimal_point_len = strlen(decimal_point); + + assert(decimal_point_len != 0); + + decimal_point_pos = NULL; + + /* Parse infinities and nans */ + val = _Py_parse_inf_or_nan(nptr, endptr); + if (*endptr != nptr) + return val; + + /* Set errno to zero, so that we can distinguish zero results + and underflows */ + errno = 0; + + /* We process the optional sign manually, then pass the remainder to + the system strtod. This ensures that the result of an underflow + has the correct sign. (bug #1725) */ + p = nptr; + /* Process leading sign, if present */ + if (*p == '-') { + negate = 1; + p++; + } + else if (*p == '+') { + p++; + } + + /* Some platform strtods accept hex floats; Python shouldn't (at the + moment), so we check explicitly for strings starting with '0x'. */ + if (*p == '0' && (*(p+1) == 'x' || *(p+1) == 'X')) + goto invalid_string; + + /* Check that what's left begins with a digit or decimal point */ + if (!Py_ISDIGIT(*p) && *p != '.') + goto invalid_string; + + digits_pos = p; + if (decimal_point[0] != '.' || + decimal_point[1] != 0) + { + /* Look for a '.' in the input; if present, it'll need to be + swapped for the current locale's decimal point before we + call strtod. On the other hand, if we find the current + locale's decimal point then the input is invalid. */ + while (Py_ISDIGIT(*p)) + p++; + + if (*p == '.') + { + decimal_point_pos = p++; + + /* locate end of number */ + while (Py_ISDIGIT(*p)) + p++; + + if (*p == 'e' || *p == 'E') + p++; + if (*p == '+' || *p == '-') + p++; + while (Py_ISDIGIT(*p)) + p++; + end = p; + } + else if (strncmp(p, decimal_point, decimal_point_len) == 0) + /* Python bug #1417699 */ + goto invalid_string; + /* For the other cases, we need not convert the decimal + point */ + } + + if (decimal_point_pos) { + char *copy, *c; + /* Create a copy of the input, with the '.' converted to the + locale-specific decimal point */ + copy = (char *)PyMem_MALLOC(end - digits_pos + + 1 + decimal_point_len); + if (copy == NULL) { + *endptr = (char *)nptr; + errno = ENOMEM; + return val; + } + + c = copy; + memcpy(c, digits_pos, decimal_point_pos - digits_pos); + c += decimal_point_pos - digits_pos; + memcpy(c, decimal_point, decimal_point_len); + c += decimal_point_len; + memcpy(c, decimal_point_pos + 1, + end - (decimal_point_pos + 1)); + c += end - (decimal_point_pos + 1); + *c = 0; + + val = strtod(copy, &fail_pos); + + if (fail_pos) + { + if (fail_pos > decimal_point_pos) + fail_pos = (char *)digits_pos + + (fail_pos - copy) - + (decimal_point_len - 1); + else + fail_pos = (char *)digits_pos + + (fail_pos - copy); + } + + PyMem_FREE(copy); + + } + else { + val = strtod(digits_pos, &fail_pos); + } + + if (fail_pos == digits_pos) + goto invalid_string; + + if (negate && fail_pos != nptr) + val = -val; + *endptr = fail_pos; - return val; + return val; invalid_string: - *endptr = (char*)nptr; - errno = EINVAL; - return -1.0; + *endptr = (char*)nptr; + errno = EINVAL; + return -1.0; } #endif @@ -296,39 +296,39 @@ double PyOS_string_to_double(const char *s, - char **endptr, - PyObject *overflow_exception) + char **endptr, + PyObject *overflow_exception) { - double x, result=-1.0; - char *fail_pos; + double x, result=-1.0; + char *fail_pos; - errno = 0; - PyFPE_START_PROTECT("PyOS_string_to_double", return -1.0) - x = _PyOS_ascii_strtod(s, &fail_pos); - PyFPE_END_PROTECT(x) - - if (errno == ENOMEM) { - PyErr_NoMemory(); - fail_pos = (char *)s; - } - else if (!endptr && (fail_pos == s || *fail_pos != '\0')) - PyErr_Format(PyExc_ValueError, - "could not convert string to float: " - "%.200s", s); - else if (fail_pos == s) - PyErr_Format(PyExc_ValueError, - "could not convert string to float: " - "%.200s", s); - else if (errno == ERANGE && fabs(x) >= 1.0 && overflow_exception) - PyErr_Format(overflow_exception, - "value too large to convert to float: " - "%.200s", s); - else - result = x; - - if (endptr != NULL) - *endptr = fail_pos; - return result; + errno = 0; + PyFPE_START_PROTECT("PyOS_string_to_double", return -1.0) + x = _PyOS_ascii_strtod(s, &fail_pos); + PyFPE_END_PROTECT(x) + + if (errno == ENOMEM) { + PyErr_NoMemory(); + fail_pos = (char *)s; + } + else if (!endptr && (fail_pos == s || *fail_pos != '\0')) + PyErr_Format(PyExc_ValueError, + "could not convert string to float: " + "%.200s", s); + else if (fail_pos == s) + PyErr_Format(PyExc_ValueError, + "could not convert string to float: " + "%.200s", s); + else if (errno == ERANGE && fabs(x) >= 1.0 && overflow_exception) + PyErr_Format(overflow_exception, + "value too large to convert to float: " + "%.200s", s); + else + result = x; + + if (endptr != NULL) + *endptr = fail_pos; + return result; } #ifdef PY_NO_SHORT_FLOAT_REPR @@ -339,30 +339,30 @@ Py_LOCAL_INLINE(void) change_decimal_from_locale_to_dot(char* buffer) { - struct lconv *locale_data = localeconv(); - const char *decimal_point = locale_data->decimal_point; + struct lconv *locale_data = localeconv(); + const char *decimal_point = locale_data->decimal_point; - if (decimal_point[0] != '.' || decimal_point[1] != 0) { - size_t decimal_point_len = strlen(decimal_point); + if (decimal_point[0] != '.' || decimal_point[1] != 0) { + size_t decimal_point_len = strlen(decimal_point); - if (*buffer == '+' || *buffer == '-') - buffer++; - while (Py_ISDIGIT(*buffer)) - buffer++; - if (strncmp(buffer, decimal_point, decimal_point_len) == 0) { - *buffer = '.'; - buffer++; - if (decimal_point_len > 1) { - /* buffer needs to get smaller */ - size_t rest_len = strlen(buffer + - (decimal_point_len - 1)); - memmove(buffer, - buffer + (decimal_point_len - 1), - rest_len); - buffer[rest_len] = 0; - } - } - } + if (*buffer == '+' || *buffer == '-') + buffer++; + while (Py_ISDIGIT(*buffer)) + buffer++; + if (strncmp(buffer, decimal_point, decimal_point_len) == 0) { + *buffer = '.'; + buffer++; + if (decimal_point_len > 1) { + /* buffer needs to get smaller */ + size_t rest_len = strlen(buffer + + (decimal_point_len - 1)); + memmove(buffer, + buffer + (decimal_point_len - 1), + rest_len); + buffer[rest_len] = 0; + } + } + } } @@ -377,65 +377,65 @@ Py_LOCAL_INLINE(void) ensure_minimum_exponent_length(char* buffer, size_t buf_size) { - char *p = strpbrk(buffer, "eE"); - if (p && (*(p + 1) == '-' || *(p + 1) == '+')) { - char *start = p + 2; - int exponent_digit_cnt = 0; - int leading_zero_cnt = 0; - int in_leading_zeros = 1; - int significant_digit_cnt; - - /* Skip over the exponent and the sign. */ - p += 2; - - /* Find the end of the exponent, keeping track of leading - zeros. */ - while (*p && Py_ISDIGIT(*p)) { - if (in_leading_zeros && *p == '0') - ++leading_zero_cnt; - if (*p != '0') - in_leading_zeros = 0; - ++p; - ++exponent_digit_cnt; - } - - significant_digit_cnt = exponent_digit_cnt - leading_zero_cnt; - if (exponent_digit_cnt == MIN_EXPONENT_DIGITS) { - /* If there are 2 exactly digits, we're done, - regardless of what they contain */ - } - else if (exponent_digit_cnt > MIN_EXPONENT_DIGITS) { - int extra_zeros_cnt; - - /* There are more than 2 digits in the exponent. See - if we can delete some of the leading zeros */ - if (significant_digit_cnt < MIN_EXPONENT_DIGITS) - significant_digit_cnt = MIN_EXPONENT_DIGITS; - extra_zeros_cnt = exponent_digit_cnt - - significant_digit_cnt; - - /* Delete extra_zeros_cnt worth of characters from the - front of the exponent */ - assert(extra_zeros_cnt >= 0); - - /* Add one to significant_digit_cnt to copy the - trailing 0 byte, thus setting the length */ - memmove(start, - start + extra_zeros_cnt, - significant_digit_cnt + 1); - } - else { - /* If there are fewer than 2 digits, add zeros - until there are 2, if there's enough room */ - int zeros = MIN_EXPONENT_DIGITS - exponent_digit_cnt; - if (start + zeros + exponent_digit_cnt + 1 - < buffer + buf_size) { - memmove(start + zeros, start, - exponent_digit_cnt + 1); - memset(start, '0', zeros); - } - } - } + char *p = strpbrk(buffer, "eE"); + if (p && (*(p + 1) == '-' || *(p + 1) == '+')) { + char *start = p + 2; + int exponent_digit_cnt = 0; + int leading_zero_cnt = 0; + int in_leading_zeros = 1; + int significant_digit_cnt; + + /* Skip over the exponent and the sign. */ + p += 2; + + /* Find the end of the exponent, keeping track of leading + zeros. */ + while (*p && Py_ISDIGIT(*p)) { + if (in_leading_zeros && *p == '0') + ++leading_zero_cnt; + if (*p != '0') + in_leading_zeros = 0; + ++p; + ++exponent_digit_cnt; + } + + significant_digit_cnt = exponent_digit_cnt - leading_zero_cnt; + if (exponent_digit_cnt == MIN_EXPONENT_DIGITS) { + /* If there are 2 exactly digits, we're done, + regardless of what they contain */ + } + else if (exponent_digit_cnt > MIN_EXPONENT_DIGITS) { + int extra_zeros_cnt; + + /* There are more than 2 digits in the exponent. See + if we can delete some of the leading zeros */ + if (significant_digit_cnt < MIN_EXPONENT_DIGITS) + significant_digit_cnt = MIN_EXPONENT_DIGITS; + extra_zeros_cnt = exponent_digit_cnt - + significant_digit_cnt; + + /* Delete extra_zeros_cnt worth of characters from the + front of the exponent */ + assert(extra_zeros_cnt >= 0); + + /* Add one to significant_digit_cnt to copy the + trailing 0 byte, thus setting the length */ + memmove(start, + start + extra_zeros_cnt, + significant_digit_cnt + 1); + } + else { + /* If there are fewer than 2 digits, add zeros + until there are 2, if there's enough room */ + int zeros = MIN_EXPONENT_DIGITS - exponent_digit_cnt; + if (start + zeros + exponent_digit_cnt + 1 + < buffer + buf_size) { + memmove(start + zeros, start, + exponent_digit_cnt + 1); + memset(start, '0', zeros); + } + } + } } /* Remove trailing zeros after the decimal point from a numeric string; also @@ -445,40 +445,40 @@ Py_LOCAL_INLINE(void) remove_trailing_zeros(char *buffer) { - char *old_fraction_end, *new_fraction_end, *end, *p; + char *old_fraction_end, *new_fraction_end, *end, *p; - p = buffer; - if (*p == '-' || *p == '+') - /* Skip leading sign, if present */ - ++p; - while (Py_ISDIGIT(*p)) - ++p; - - /* if there's no decimal point there's nothing to do */ - if (*p++ != '.') - return; - - /* scan any digits after the point */ - while (Py_ISDIGIT(*p)) - ++p; - old_fraction_end = p; - - /* scan up to ending '\0' */ - while (*p != '\0') - p++; - /* +1 to make sure that we move the null byte as well */ - end = p+1; - - /* scan back from fraction_end, looking for removable zeros */ - p = old_fraction_end; - while (*(p-1) == '0') - --p; - /* and remove point if we've got that far */ - if (*(p-1) == '.') - --p; - new_fraction_end = p; + p = buffer; + if (*p == '-' || *p == '+') + /* Skip leading sign, if present */ + ++p; + while (Py_ISDIGIT(*p)) + ++p; + + /* if there's no decimal point there's nothing to do */ + if (*p++ != '.') + return; + + /* scan any digits after the point */ + while (Py_ISDIGIT(*p)) + ++p; + old_fraction_end = p; + + /* scan up to ending '\0' */ + while (*p != '\0') + p++; + /* +1 to make sure that we move the null byte as well */ + end = p+1; + + /* scan back from fraction_end, looking for removable zeros */ + p = old_fraction_end; + while (*(p-1) == '0') + --p; + /* and remove point if we've got that far */ + if (*(p-1) == '.') + --p; + new_fraction_end = p; - memmove(new_fraction_end, old_fraction_end, end-old_fraction_end); + memmove(new_fraction_end, old_fraction_end, end-old_fraction_end); } /* Ensure that buffer has a decimal point in it. The decimal point will not @@ -491,91 +491,91 @@ Py_LOCAL_INLINE(char *) ensure_decimal_point(char* buffer, size_t buf_size, int precision) { - int digit_count, insert_count = 0, convert_to_exp = 0; - char *chars_to_insert, *digits_start; + int digit_count, insert_count = 0, convert_to_exp = 0; + char *chars_to_insert, *digits_start; - /* search for the first non-digit character */ - char *p = buffer; - if (*p == '-' || *p == '+') - /* Skip leading sign, if present. I think this could only - ever be '-', but it can't hurt to check for both. */ - ++p; - digits_start = p; - while (*p && Py_ISDIGIT(*p)) - ++p; - digit_count = Py_SAFE_DOWNCAST(p - digits_start, Py_ssize_t, int); - - if (*p == '.') { - if (Py_ISDIGIT(*(p+1))) { - /* Nothing to do, we already have a decimal - point and a digit after it */ - } - else { - /* We have a decimal point, but no following - digit. Insert a zero after the decimal. */ - /* can't ever get here via PyOS_double_to_string */ - assert(precision == -1); - ++p; - chars_to_insert = "0"; - insert_count = 1; - } - } - else if (!(*p == 'e' || *p == 'E')) { - /* Don't add ".0" if we have an exponent. */ - if (digit_count == precision) { - /* issue 5864: don't add a trailing .0 in the case - where the '%g'-formatted result already has as many - significant digits as were requested. Switch to - exponential notation instead. */ - convert_to_exp = 1; - /* no exponent, no point, and we shouldn't land here - for infs and nans, so we must be at the end of the - string. */ - assert(*p == '\0'); - } - else { - assert(precision == -1 || digit_count < precision); - chars_to_insert = ".0"; - insert_count = 2; - } - } - if (insert_count) { - size_t buf_len = strlen(buffer); - if (buf_len + insert_count + 1 >= buf_size) { - /* If there is not enough room in the buffer - for the additional text, just skip it. It's - not worth generating an error over. */ - } - else { - memmove(p + insert_count, p, - buffer + strlen(buffer) - p + 1); - memcpy(p, chars_to_insert, insert_count); - } - } - if (convert_to_exp) { - int written; - size_t buf_avail; - p = digits_start; - /* insert decimal point */ - assert(digit_count >= 1); - memmove(p+2, p+1, digit_count); /* safe, but overwrites nul */ - p[1] = '.'; - p += digit_count+1; - assert(p <= buf_size+buffer); - buf_avail = buf_size+buffer-p; - if (buf_avail == 0) - return NULL; - /* Add exponent. It's okay to use lower case 'e': we only - arrive here as a result of using the empty format code or - repr/str builtins and those never want an upper case 'E' */ - written = PyOS_snprintf(p, buf_avail, "e%+.02d", digit_count-1); - if (!(0 <= written && - written < Py_SAFE_DOWNCAST(buf_avail, size_t, int))) - /* output truncated, or something else bad happened */ - return NULL; - remove_trailing_zeros(buffer); - } - return buffer; + /* search for the first non-digit character */ + char *p = buffer; + if (*p == '-' || *p == '+') + /* Skip leading sign, if present. I think this could only + ever be '-', but it can't hurt to check for both. */ + ++p; + digits_start = p; + while (*p && Py_ISDIGIT(*p)) + ++p; + digit_count = Py_SAFE_DOWNCAST(p - digits_start, Py_ssize_t, int); + + if (*p == '.') { + if (Py_ISDIGIT(*(p+1))) { + /* Nothing to do, we already have a decimal + point and a digit after it */ + } + else { + /* We have a decimal point, but no following + digit. Insert a zero after the decimal. */ + /* can't ever get here via PyOS_double_to_string */ + assert(precision == -1); + ++p; + chars_to_insert = "0"; + insert_count = 1; + } + } + else if (!(*p == 'e' || *p == 'E')) { + /* Don't add ".0" if we have an exponent. */ + if (digit_count == precision) { + /* issue 5864: don't add a trailing .0 in the case + where the '%g'-formatted result already has as many + significant digits as were requested. Switch to + exponential notation instead. */ + convert_to_exp = 1; + /* no exponent, no point, and we shouldn't land here + for infs and nans, so we must be at the end of the + string. */ + assert(*p == '\0'); + } + else { + assert(precision == -1 || digit_count < precision); + chars_to_insert = ".0"; + insert_count = 2; + } + } + if (insert_count) { + size_t buf_len = strlen(buffer); + if (buf_len + insert_count + 1 >= buf_size) { + /* If there is not enough room in the buffer + for the additional text, just skip it. It's + not worth generating an error over. */ + } + else { + memmove(p + insert_count, p, + buffer + strlen(buffer) - p + 1); + memcpy(p, chars_to_insert, insert_count); + } + } + if (convert_to_exp) { + int written; + size_t buf_avail; + p = digits_start; + /* insert decimal point */ + assert(digit_count >= 1); + memmove(p+2, p+1, digit_count); /* safe, but overwrites nul */ + p[1] = '.'; + p += digit_count+1; + assert(p <= buf_size+buffer); + buf_avail = buf_size+buffer-p; + if (buf_avail == 0) + return NULL; + /* Add exponent. It's okay to use lower case 'e': we only + arrive here as a result of using the empty format code or + repr/str builtins and those never want an upper case 'E' */ + written = PyOS_snprintf(p, buf_avail, "e%+.02d", digit_count-1); + if (!(0 <= written && + written < Py_SAFE_DOWNCAST(buf_avail, size_t, int))) + /* output truncated, or something else bad happened */ + return NULL; + remove_trailing_zeros(buffer); + } + return buffer; } /* see FORMATBUFLEN in unicodeobject.c */ @@ -586,7 +586,7 @@ * @buffer: A buffer to place the resulting string in * @buf_size: The length of the buffer. * @format: The printf()-style format to use for the - * code to use for converting. + * code to use for converting. * @d: The #gdouble to convert * @precision: The precision to use when formatting. * @@ -594,7 +594,7 @@ * decimal point. To format the number you pass in * a printf()-style format string. Allowed conversion * specifiers are 'e', 'E', 'f', 'F', 'g', 'G', and 'Z'. - * + * * 'Z' is the same as 'g', except it always has a decimal and * at least one digit after the decimal. * @@ -602,83 +602,83 @@ * On failure returns NULL but does not set any Python exception. **/ static char * -_PyOS_ascii_formatd(char *buffer, - size_t buf_size, - const char *format, - double d, - int precision) +_PyOS_ascii_formatd(char *buffer, + size_t buf_size, + const char *format, + double d, + int precision) { - char format_char; - size_t format_len = strlen(format); + char format_char; + size_t format_len = strlen(format); - /* Issue 2264: code 'Z' requires copying the format. 'Z' is 'g', but - also with at least one character past the decimal. */ - char tmp_format[FLOAT_FORMATBUFLEN]; - - /* The last character in the format string must be the format char */ - format_char = format[format_len - 1]; - - if (format[0] != '%') - return NULL; - - /* I'm not sure why this test is here. It's ensuring that the format - string after the first character doesn't have a single quote, a - lowercase l, or a percent. This is the reverse of the commented-out - test about 10 lines ago. */ - if (strpbrk(format + 1, "'l%")) - return NULL; - - /* Also curious about this function is that it accepts format strings - like "%xg", which are invalid for floats. In general, the - interface to this function is not very good, but changing it is - difficult because it's a public API. */ - - if (!(format_char == 'e' || format_char == 'E' || - format_char == 'f' || format_char == 'F' || - format_char == 'g' || format_char == 'G' || - format_char == 'Z')) - return NULL; - - /* Map 'Z' format_char to 'g', by copying the format string and - replacing the final char with a 'g' */ - if (format_char == 'Z') { - if (format_len + 1 >= sizeof(tmp_format)) { - /* The format won't fit in our copy. Error out. In - practice, this will never happen and will be - detected by returning NULL */ - return NULL; - } - strcpy(tmp_format, format); - tmp_format[format_len - 1] = 'g'; - format = tmp_format; - } - - - /* Have PyOS_snprintf do the hard work */ - PyOS_snprintf(buffer, buf_size, format, d); - - /* Do various fixups on the return string */ - - /* Get the current locale, and find the decimal point string. - Convert that string back to a dot. */ - change_decimal_from_locale_to_dot(buffer); - - /* If an exponent exists, ensure that the exponent is at least - MIN_EXPONENT_DIGITS digits, providing the buffer is large enough - for the extra zeros. Also, if there are more than - MIN_EXPONENT_DIGITS, remove as many zeros as possible until we get - back to MIN_EXPONENT_DIGITS */ - ensure_minimum_exponent_length(buffer, buf_size); - - /* If format_char is 'Z', make sure we have at least one character - after the decimal point (and make sure we have a decimal point); - also switch to exponential notation in some edge cases where the - extra character would produce more significant digits that we - really want. */ - if (format_char == 'Z') - buffer = ensure_decimal_point(buffer, buf_size, precision); + /* Issue 2264: code 'Z' requires copying the format. 'Z' is 'g', but + also with at least one character past the decimal. */ + char tmp_format[FLOAT_FORMATBUFLEN]; + + /* The last character in the format string must be the format char */ + format_char = format[format_len - 1]; + + if (format[0] != '%') + return NULL; + + /* I'm not sure why this test is here. It's ensuring that the format + string after the first character doesn't have a single quote, a + lowercase l, or a percent. This is the reverse of the commented-out + test about 10 lines ago. */ + if (strpbrk(format + 1, "'l%")) + return NULL; + + /* Also curious about this function is that it accepts format strings + like "%xg", which are invalid for floats. In general, the + interface to this function is not very good, but changing it is + difficult because it's a public API. */ + + if (!(format_char == 'e' || format_char == 'E' || + format_char == 'f' || format_char == 'F' || + format_char == 'g' || format_char == 'G' || + format_char == 'Z')) + return NULL; + + /* Map 'Z' format_char to 'g', by copying the format string and + replacing the final char with a 'g' */ + if (format_char == 'Z') { + if (format_len + 1 >= sizeof(tmp_format)) { + /* The format won't fit in our copy. Error out. In + practice, this will never happen and will be + detected by returning NULL */ + return NULL; + } + strcpy(tmp_format, format); + tmp_format[format_len - 1] = 'g'; + format = tmp_format; + } + + + /* Have PyOS_snprintf do the hard work */ + PyOS_snprintf(buffer, buf_size, format, d); + + /* Do various fixups on the return string */ + + /* Get the current locale, and find the decimal point string. + Convert that string back to a dot. */ + change_decimal_from_locale_to_dot(buffer); + + /* If an exponent exists, ensure that the exponent is at least + MIN_EXPONENT_DIGITS digits, providing the buffer is large enough + for the extra zeros. Also, if there are more than + MIN_EXPONENT_DIGITS, remove as many zeros as possible until we get + back to MIN_EXPONENT_DIGITS */ + ensure_minimum_exponent_length(buffer, buf_size); + + /* If format_char is 'Z', make sure we have at least one character + after the decimal point (and make sure we have a decimal point); + also switch to exponential notation in some edge cases where the + extra character would produce more significant digits that we + really want. */ + if (format_char == 'Z') + buffer = ensure_decimal_point(buffer, buf_size, precision); - return buffer; + return buffer; } /* The fallback code to use if _Py_dg_dtoa is not available. */ @@ -689,146 +689,146 @@ int flags, int *type) { - char format[32]; - Py_ssize_t bufsize; - char *buf; - int t, exp; - int upper = 0; - - /* Validate format_code, and map upper and lower case */ - switch (format_code) { - case 'e': /* exponent */ - case 'f': /* fixed */ - case 'g': /* general */ - break; - case 'E': - upper = 1; - format_code = 'e'; - break; - case 'F': - upper = 1; - format_code = 'f'; - break; - case 'G': - upper = 1; - format_code = 'g'; - break; - case 'r': /* repr format */ - /* Supplied precision is unused, must be 0. */ - if (precision != 0) { - PyErr_BadInternalCall(); - return NULL; - } - /* The repr() precision (17 significant decimal digits) is the - minimal number that is guaranteed to have enough precision - so that if the number is read back in the exact same binary - value is recreated. This is true for IEEE floating point - by design, and also happens to work for all other modern - hardware. */ - precision = 17; - format_code = 'g'; - break; - default: - PyErr_BadInternalCall(); - return NULL; - } - - /* Here's a quick-and-dirty calculation to figure out how big a buffer - we need. In general, for a finite float we need: - - 1 byte for each digit of the decimal significand, and - - 1 for a possible sign - 1 for a possible decimal point - 2 for a possible [eE][+-] - 1 for each digit of the exponent; if we allow 19 digits - total then we're safe up to exponents of 2**63. - 1 for the trailing nul byte - - This gives a total of 24 + the number of digits in the significand, - and the number of digits in the significand is: - - for 'g' format: at most precision, except possibly - when precision == 0, when it's 1. - for 'e' format: precision+1 - for 'f' format: precision digits after the point, at least 1 - before. To figure out how many digits appear before the point - we have to examine the size of the number. If fabs(val) < 1.0 - then there will be only one digit before the point. If - fabs(val) >= 1.0, then there are at most - - 1+floor(log10(ceiling(fabs(val)))) - - digits before the point (where the 'ceiling' allows for the - possibility that the rounding rounds the integer part of val - up). A safe upper bound for the above quantity is - 1+floor(exp/3), where exp is the unique integer such that 0.5 - <= fabs(val)/2**exp < 1.0. This exp can be obtained from - frexp. - - So we allow room for precision+1 digits for all formats, plus an - extra floor(exp/3) digits for 'f' format. - - */ - - if (Py_IS_NAN(val) || Py_IS_INFINITY(val)) - /* 3 for 'inf'/'nan', 1 for sign, 1 for '\0' */ - bufsize = 5; - else { - bufsize = 25 + precision; - if (format_code == 'f' && fabs(val) >= 1.0) { - frexp(val, &exp); - bufsize += exp/3; - } - } - - buf = PyMem_Malloc(bufsize); - if (buf == NULL) { - PyErr_NoMemory(); - return NULL; - } - - /* Handle nan and inf. */ - if (Py_IS_NAN(val)) { - strcpy(buf, "nan"); - t = Py_DTST_NAN; - } else if (Py_IS_INFINITY(val)) { - if (copysign(1., val) == 1.) - strcpy(buf, "inf"); - else - strcpy(buf, "-inf"); - t = Py_DTST_INFINITE; - } else { - t = Py_DTST_FINITE; - if (flags & Py_DTSF_ADD_DOT_0) - format_code = 'Z'; - - PyOS_snprintf(format, sizeof(format), "%%%s.%i%c", - (flags & Py_DTSF_ALT ? "#" : ""), precision, - format_code); - _PyOS_ascii_formatd(buf, bufsize, format, val, precision); - } - - /* Add sign when requested. It's convenient (esp. when formatting - complex numbers) to include a sign even for inf and nan. */ - if (flags & Py_DTSF_SIGN && buf[0] != '-') { - size_t len = strlen(buf); - /* the bufsize calculations above should ensure that we've got - space to add a sign */ - assert((size_t)bufsize >= len+2); - memmove(buf+1, buf, len+1); - buf[0] = '+'; - } - if (upper) { - /* Convert to upper case. */ - char *p1; - for (p1 = buf; *p1; p1++) - *p1 = Py_TOUPPER(*p1); - } - - if (type) - *type = t; - return buf; + char format[32]; + Py_ssize_t bufsize; + char *buf; + int t, exp; + int upper = 0; + + /* Validate format_code, and map upper and lower case */ + switch (format_code) { + case 'e': /* exponent */ + case 'f': /* fixed */ + case 'g': /* general */ + break; + case 'E': + upper = 1; + format_code = 'e'; + break; + case 'F': + upper = 1; + format_code = 'f'; + break; + case 'G': + upper = 1; + format_code = 'g'; + break; + case 'r': /* repr format */ + /* Supplied precision is unused, must be 0. */ + if (precision != 0) { + PyErr_BadInternalCall(); + return NULL; + } + /* The repr() precision (17 significant decimal digits) is the + minimal number that is guaranteed to have enough precision + so that if the number is read back in the exact same binary + value is recreated. This is true for IEEE floating point + by design, and also happens to work for all other modern + hardware. */ + precision = 17; + format_code = 'g'; + break; + default: + PyErr_BadInternalCall(); + return NULL; + } + + /* Here's a quick-and-dirty calculation to figure out how big a buffer + we need. In general, for a finite float we need: + + 1 byte for each digit of the decimal significand, and + + 1 for a possible sign + 1 for a possible decimal point + 2 for a possible [eE][+-] + 1 for each digit of the exponent; if we allow 19 digits + total then we're safe up to exponents of 2**63. + 1 for the trailing nul byte + + This gives a total of 24 + the number of digits in the significand, + and the number of digits in the significand is: + + for 'g' format: at most precision, except possibly + when precision == 0, when it's 1. + for 'e' format: precision+1 + for 'f' format: precision digits after the point, at least 1 + before. To figure out how many digits appear before the point + we have to examine the size of the number. If fabs(val) < 1.0 + then there will be only one digit before the point. If + fabs(val) >= 1.0, then there are at most + + 1+floor(log10(ceiling(fabs(val)))) + + digits before the point (where the 'ceiling' allows for the + possibility that the rounding rounds the integer part of val + up). A safe upper bound for the above quantity is + 1+floor(exp/3), where exp is the unique integer such that 0.5 + <= fabs(val)/2**exp < 1.0. This exp can be obtained from + frexp. + + So we allow room for precision+1 digits for all formats, plus an + extra floor(exp/3) digits for 'f' format. + + */ + + if (Py_IS_NAN(val) || Py_IS_INFINITY(val)) + /* 3 for 'inf'/'nan', 1 for sign, 1 for '\0' */ + bufsize = 5; + else { + bufsize = 25 + precision; + if (format_code == 'f' && fabs(val) >= 1.0) { + frexp(val, &exp); + bufsize += exp/3; + } + } + + buf = PyMem_Malloc(bufsize); + if (buf == NULL) { + PyErr_NoMemory(); + return NULL; + } + + /* Handle nan and inf. */ + if (Py_IS_NAN(val)) { + strcpy(buf, "nan"); + t = Py_DTST_NAN; + } else if (Py_IS_INFINITY(val)) { + if (copysign(1., val) == 1.) + strcpy(buf, "inf"); + else + strcpy(buf, "-inf"); + t = Py_DTST_INFINITE; + } else { + t = Py_DTST_FINITE; + if (flags & Py_DTSF_ADD_DOT_0) + format_code = 'Z'; + + PyOS_snprintf(format, sizeof(format), "%%%s.%i%c", + (flags & Py_DTSF_ALT ? "#" : ""), precision, + format_code); + _PyOS_ascii_formatd(buf, bufsize, format, val, precision); + } + + /* Add sign when requested. It's convenient (esp. when formatting + complex numbers) to include a sign even for inf and nan. */ + if (flags & Py_DTSF_SIGN && buf[0] != '-') { + size_t len = strlen(buf); + /* the bufsize calculations above should ensure that we've got + space to add a sign */ + assert((size_t)bufsize >= len+2); + memmove(buf+1, buf, len+1); + buf[0] = '+'; + } + if (upper) { + /* Convert to upper case. */ + char *p1; + for (p1 = buf; *p1; p1++) + *p1 = Py_TOUPPER(*p1); + } + + if (type) + *type = t; + return buf; } #else @@ -843,14 +843,14 @@ /* The lengths of these are known to the code below, so don't change them */ static char *lc_float_strings[] = { - "inf", - "nan", - "e", + "inf", + "nan", + "e", }; static char *uc_float_strings[] = { - "INF", - "NAN", - "E", + "INF", + "NAN", + "E", }; @@ -874,9 +874,9 @@ be nonzero. type, if non-NULL, will be set to one of these constants to identify the type of the 'd' argument: - Py_DTST_FINITE - Py_DTST_INFINITE - Py_DTST_NAN + Py_DTST_FINITE + Py_DTST_INFINITE + Py_DTST_NAN Returns a PyMem_Malloc'd block of memory containing the resulting string, or NULL on error. If NULL is returned, the Python error has been set. @@ -884,315 +884,315 @@ static char * format_float_short(double d, char format_code, - int mode, Py_ssize_t precision, - int always_add_sign, int add_dot_0_if_integer, - int use_alt_formatting, char **float_strings, int *type) + int mode, Py_ssize_t precision, + int always_add_sign, int add_dot_0_if_integer, + int use_alt_formatting, char **float_strings, int *type) { - char *buf = NULL; - char *p = NULL; - Py_ssize_t bufsize = 0; - char *digits, *digits_end; - int decpt_as_int, sign, exp_len, exp = 0, use_exp = 0; - Py_ssize_t decpt, digits_len, vdigits_start, vdigits_end; - _Py_SET_53BIT_PRECISION_HEADER; - - /* _Py_dg_dtoa returns a digit string (no decimal point or exponent). - Must be matched by a call to _Py_dg_freedtoa. */ - _Py_SET_53BIT_PRECISION_START; - digits = _Py_dg_dtoa(d, mode, precision, &decpt_as_int, &sign, - &digits_end); - _Py_SET_53BIT_PRECISION_END; - - decpt = (Py_ssize_t)decpt_as_int; - if (digits == NULL) { - /* The only failure mode is no memory. */ - PyErr_NoMemory(); - goto exit; - } - assert(digits_end != NULL && digits_end >= digits); - digits_len = digits_end - digits; - - if (digits_len && !Py_ISDIGIT(digits[0])) { - /* Infinities and nans here; adapt Gay's output, - so convert Infinity to inf and NaN to nan, and - ignore sign of nan. Then return. */ - - /* ignore the actual sign of a nan */ - if (digits[0] == 'n' || digits[0] == 'N') - sign = 0; - - /* We only need 5 bytes to hold the result "+inf\0" . */ - bufsize = 5; /* Used later in an assert. */ - buf = (char *)PyMem_Malloc(bufsize); - if (buf == NULL) { - PyErr_NoMemory(); - goto exit; - } - p = buf; - - if (sign == 1) { - *p++ = '-'; - } - else if (always_add_sign) { - *p++ = '+'; - } - if (digits[0] == 'i' || digits[0] == 'I') { - strncpy(p, float_strings[OFS_INF], 3); - p += 3; - - if (type) - *type = Py_DTST_INFINITE; - } - else if (digits[0] == 'n' || digits[0] == 'N') { - strncpy(p, float_strings[OFS_NAN], 3); - p += 3; - - if (type) - *type = Py_DTST_NAN; - } - else { - /* shouldn't get here: Gay's code should always return - something starting with a digit, an 'I', or 'N' */ - strncpy(p, "ERR", 3); - p += 3; - assert(0); - } - goto exit; - } - - /* The result must be finite (not inf or nan). */ - if (type) - *type = Py_DTST_FINITE; - - - /* We got digits back, format them. We may need to pad 'digits' - either on the left or right (or both) with extra zeros, so in - general the resulting string has the form - - [][] - - where either of the pieces could be empty, and there's a - decimal point that could appear either in or in the - leading or trailing . - - Imagine an infinite 'virtual' string vdigits, consisting of the - string 'digits' (starting at index 0) padded on both the left and - right with infinite strings of zeros. We want to output a slice - - vdigits[vdigits_start : vdigits_end] - - of this virtual string. Thus if vdigits_start < 0 then we'll end - up producing some leading zeros; if vdigits_end > digits_len there - will be trailing zeros in the output. The next section of code - determines whether to use an exponent or not, figures out the - position 'decpt' of the decimal point, and computes 'vdigits_start' - and 'vdigits_end'. */ - vdigits_end = digits_len; - switch (format_code) { - case 'e': - use_exp = 1; - vdigits_end = precision; - break; - case 'f': - vdigits_end = decpt + precision; - break; - case 'g': - if (decpt <= -4 || decpt > - (add_dot_0_if_integer ? precision-1 : precision)) - use_exp = 1; - if (use_alt_formatting) - vdigits_end = precision; - break; - case 'r': - /* convert to exponential format at 1e16. We used to convert - at 1e17, but that gives odd-looking results for some values - when a 16-digit 'shortest' repr is padded with bogus zeros. - For example, repr(2e16+8) would give 20000000000000010.0; - the true value is 20000000000000008.0. */ - if (decpt <= -4 || decpt > 16) - use_exp = 1; - break; - default: - PyErr_BadInternalCall(); - goto exit; - } - - /* if using an exponent, reset decimal point position to 1 and adjust - exponent accordingly.*/ - if (use_exp) { - exp = decpt - 1; - decpt = 1; - } - /* ensure vdigits_start < decpt <= vdigits_end, or vdigits_start < - decpt < vdigits_end if add_dot_0_if_integer and no exponent */ - vdigits_start = decpt <= 0 ? decpt-1 : 0; - if (!use_exp && add_dot_0_if_integer) - vdigits_end = vdigits_end > decpt ? vdigits_end : decpt + 1; - else - vdigits_end = vdigits_end > decpt ? vdigits_end : decpt; - - /* double check inequalities */ - assert(vdigits_start <= 0 && - 0 <= digits_len && - digits_len <= vdigits_end); - /* decimal point should be in (vdigits_start, vdigits_end] */ - assert(vdigits_start < decpt && decpt <= vdigits_end); - - /* Compute an upper bound how much memory we need. This might be a few - chars too long, but no big deal. */ - bufsize = - /* sign, decimal point and trailing 0 byte */ - 3 + - - /* total digit count (including zero padding on both sides) */ - (vdigits_end - vdigits_start) + - - /* exponent "e+100", max 3 numerical digits */ - (use_exp ? 5 : 0); - - /* Now allocate the memory and initialize p to point to the start of - it. */ - buf = (char *)PyMem_Malloc(bufsize); - if (buf == NULL) { - PyErr_NoMemory(); - goto exit; - } - p = buf; - - /* Add a negative sign if negative, and a plus sign if non-negative - and always_add_sign is true. */ - if (sign == 1) - *p++ = '-'; - else if (always_add_sign) - *p++ = '+'; - - /* note that exactly one of the three 'if' conditions is true, - so we include exactly one decimal point */ - /* Zero padding on left of digit string */ - if (decpt <= 0) { - memset(p, '0', decpt-vdigits_start); - p += decpt - vdigits_start; - *p++ = '.'; - memset(p, '0', 0-decpt); - p += 0-decpt; - } - else { - memset(p, '0', 0-vdigits_start); - p += 0 - vdigits_start; - } - - /* Digits, with included decimal point */ - if (0 < decpt && decpt <= digits_len) { - strncpy(p, digits, decpt-0); - p += decpt-0; - *p++ = '.'; - strncpy(p, digits+decpt, digits_len-decpt); - p += digits_len-decpt; - } - else { - strncpy(p, digits, digits_len); - p += digits_len; - } - - /* And zeros on the right */ - if (digits_len < decpt) { - memset(p, '0', decpt-digits_len); - p += decpt-digits_len; - *p++ = '.'; - memset(p, '0', vdigits_end-decpt); - p += vdigits_end-decpt; - } - else { - memset(p, '0', vdigits_end-digits_len); - p += vdigits_end-digits_len; - } - - /* Delete a trailing decimal pt unless using alternative formatting. */ - if (p[-1] == '.' && !use_alt_formatting) - p--; - - /* Now that we've done zero padding, add an exponent if needed. */ - if (use_exp) { - *p++ = float_strings[OFS_E][0]; - exp_len = sprintf(p, "%+.02d", exp); - p += exp_len; - } + char *buf = NULL; + char *p = NULL; + Py_ssize_t bufsize = 0; + char *digits, *digits_end; + int decpt_as_int, sign, exp_len, exp = 0, use_exp = 0; + Py_ssize_t decpt, digits_len, vdigits_start, vdigits_end; + _Py_SET_53BIT_PRECISION_HEADER; + + /* _Py_dg_dtoa returns a digit string (no decimal point or exponent). + Must be matched by a call to _Py_dg_freedtoa. */ + _Py_SET_53BIT_PRECISION_START; + digits = _Py_dg_dtoa(d, mode, precision, &decpt_as_int, &sign, + &digits_end); + _Py_SET_53BIT_PRECISION_END; + + decpt = (Py_ssize_t)decpt_as_int; + if (digits == NULL) { + /* The only failure mode is no memory. */ + PyErr_NoMemory(); + goto exit; + } + assert(digits_end != NULL && digits_end >= digits); + digits_len = digits_end - digits; + + if (digits_len && !Py_ISDIGIT(digits[0])) { + /* Infinities and nans here; adapt Gay's output, + so convert Infinity to inf and NaN to nan, and + ignore sign of nan. Then return. */ + + /* ignore the actual sign of a nan */ + if (digits[0] == 'n' || digits[0] == 'N') + sign = 0; + + /* We only need 5 bytes to hold the result "+inf\0" . */ + bufsize = 5; /* Used later in an assert. */ + buf = (char *)PyMem_Malloc(bufsize); + if (buf == NULL) { + PyErr_NoMemory(); + goto exit; + } + p = buf; + + if (sign == 1) { + *p++ = '-'; + } + else if (always_add_sign) { + *p++ = '+'; + } + if (digits[0] == 'i' || digits[0] == 'I') { + strncpy(p, float_strings[OFS_INF], 3); + p += 3; + + if (type) + *type = Py_DTST_INFINITE; + } + else if (digits[0] == 'n' || digits[0] == 'N') { + strncpy(p, float_strings[OFS_NAN], 3); + p += 3; + + if (type) + *type = Py_DTST_NAN; + } + else { + /* shouldn't get here: Gay's code should always return + something starting with a digit, an 'I', or 'N' */ + strncpy(p, "ERR", 3); + p += 3; + assert(0); + } + goto exit; + } + + /* The result must be finite (not inf or nan). */ + if (type) + *type = Py_DTST_FINITE; + + + /* We got digits back, format them. We may need to pad 'digits' + either on the left or right (or both) with extra zeros, so in + general the resulting string has the form + + [][] + + where either of the pieces could be empty, and there's a + decimal point that could appear either in or in the + leading or trailing . + + Imagine an infinite 'virtual' string vdigits, consisting of the + string 'digits' (starting at index 0) padded on both the left and + right with infinite strings of zeros. We want to output a slice + + vdigits[vdigits_start : vdigits_end] + + of this virtual string. Thus if vdigits_start < 0 then we'll end + up producing some leading zeros; if vdigits_end > digits_len there + will be trailing zeros in the output. The next section of code + determines whether to use an exponent or not, figures out the + position 'decpt' of the decimal point, and computes 'vdigits_start' + and 'vdigits_end'. */ + vdigits_end = digits_len; + switch (format_code) { + case 'e': + use_exp = 1; + vdigits_end = precision; + break; + case 'f': + vdigits_end = decpt + precision; + break; + case 'g': + if (decpt <= -4 || decpt > + (add_dot_0_if_integer ? precision-1 : precision)) + use_exp = 1; + if (use_alt_formatting) + vdigits_end = precision; + break; + case 'r': + /* convert to exponential format at 1e16. We used to convert + at 1e17, but that gives odd-looking results for some values + when a 16-digit 'shortest' repr is padded with bogus zeros. + For example, repr(2e16+8) would give 20000000000000010.0; + the true value is 20000000000000008.0. */ + if (decpt <= -4 || decpt > 16) + use_exp = 1; + break; + default: + PyErr_BadInternalCall(); + goto exit; + } + + /* if using an exponent, reset decimal point position to 1 and adjust + exponent accordingly.*/ + if (use_exp) { + exp = decpt - 1; + decpt = 1; + } + /* ensure vdigits_start < decpt <= vdigits_end, or vdigits_start < + decpt < vdigits_end if add_dot_0_if_integer and no exponent */ + vdigits_start = decpt <= 0 ? decpt-1 : 0; + if (!use_exp && add_dot_0_if_integer) + vdigits_end = vdigits_end > decpt ? vdigits_end : decpt + 1; + else + vdigits_end = vdigits_end > decpt ? vdigits_end : decpt; + + /* double check inequalities */ + assert(vdigits_start <= 0 && + 0 <= digits_len && + digits_len <= vdigits_end); + /* decimal point should be in (vdigits_start, vdigits_end] */ + assert(vdigits_start < decpt && decpt <= vdigits_end); + + /* Compute an upper bound how much memory we need. This might be a few + chars too long, but no big deal. */ + bufsize = + /* sign, decimal point and trailing 0 byte */ + 3 + + + /* total digit count (including zero padding on both sides) */ + (vdigits_end - vdigits_start) + + + /* exponent "e+100", max 3 numerical digits */ + (use_exp ? 5 : 0); + + /* Now allocate the memory and initialize p to point to the start of + it. */ + buf = (char *)PyMem_Malloc(bufsize); + if (buf == NULL) { + PyErr_NoMemory(); + goto exit; + } + p = buf; + + /* Add a negative sign if negative, and a plus sign if non-negative + and always_add_sign is true. */ + if (sign == 1) + *p++ = '-'; + else if (always_add_sign) + *p++ = '+'; + + /* note that exactly one of the three 'if' conditions is true, + so we include exactly one decimal point */ + /* Zero padding on left of digit string */ + if (decpt <= 0) { + memset(p, '0', decpt-vdigits_start); + p += decpt - vdigits_start; + *p++ = '.'; + memset(p, '0', 0-decpt); + p += 0-decpt; + } + else { + memset(p, '0', 0-vdigits_start); + p += 0 - vdigits_start; + } + + /* Digits, with included decimal point */ + if (0 < decpt && decpt <= digits_len) { + strncpy(p, digits, decpt-0); + p += decpt-0; + *p++ = '.'; + strncpy(p, digits+decpt, digits_len-decpt); + p += digits_len-decpt; + } + else { + strncpy(p, digits, digits_len); + p += digits_len; + } + + /* And zeros on the right */ + if (digits_len < decpt) { + memset(p, '0', decpt-digits_len); + p += decpt-digits_len; + *p++ = '.'; + memset(p, '0', vdigits_end-decpt); + p += vdigits_end-decpt; + } + else { + memset(p, '0', vdigits_end-digits_len); + p += vdigits_end-digits_len; + } + + /* Delete a trailing decimal pt unless using alternative formatting. */ + if (p[-1] == '.' && !use_alt_formatting) + p--; + + /* Now that we've done zero padding, add an exponent if needed. */ + if (use_exp) { + *p++ = float_strings[OFS_E][0]; + exp_len = sprintf(p, "%+.02d", exp); + p += exp_len; + } exit: - if (buf) { - *p = '\0'; - /* It's too late if this fails, as we've already stepped on - memory that isn't ours. But it's an okay debugging test. */ - assert(p-buf < bufsize); - } - if (digits) - _Py_dg_freedtoa(digits); + if (buf) { + *p = '\0'; + /* It's too late if this fails, as we've already stepped on + memory that isn't ours. But it's an okay debugging test. */ + assert(p-buf < bufsize); + } + if (digits) + _Py_dg_freedtoa(digits); - return buf; + return buf; } PyAPI_FUNC(char *) PyOS_double_to_string(double val, - char format_code, - int precision, - int flags, - int *type) + char format_code, + int precision, + int flags, + int *type) { - char **float_strings = lc_float_strings; - int mode; + char **float_strings = lc_float_strings; + int mode; - /* Validate format_code, and map upper and lower case. Compute the - mode and make any adjustments as needed. */ - switch (format_code) { - /* exponent */ - case 'E': - float_strings = uc_float_strings; - format_code = 'e'; - /* Fall through. */ - case 'e': - mode = 2; - precision++; - break; - - /* fixed */ - case 'F': - float_strings = uc_float_strings; - format_code = 'f'; - /* Fall through. */ - case 'f': - mode = 3; - break; - - /* general */ - case 'G': - float_strings = uc_float_strings; - format_code = 'g'; - /* Fall through. */ - case 'g': - mode = 2; - /* precision 0 makes no sense for 'g' format; interpret as 1 */ - if (precision == 0) - precision = 1; - break; - - /* repr format */ - case 'r': - mode = 0; - /* Supplied precision is unused, must be 0. */ - if (precision != 0) { - PyErr_BadInternalCall(); - return NULL; - } - break; - - default: - PyErr_BadInternalCall(); - return NULL; - } - - return format_float_short(val, format_code, mode, precision, - flags & Py_DTSF_SIGN, - flags & Py_DTSF_ADD_DOT_0, - flags & Py_DTSF_ALT, - float_strings, type); + /* Validate format_code, and map upper and lower case. Compute the + mode and make any adjustments as needed. */ + switch (format_code) { + /* exponent */ + case 'E': + float_strings = uc_float_strings; + format_code = 'e'; + /* Fall through. */ + case 'e': + mode = 2; + precision++; + break; + + /* fixed */ + case 'F': + float_strings = uc_float_strings; + format_code = 'f'; + /* Fall through. */ + case 'f': + mode = 3; + break; + + /* general */ + case 'G': + float_strings = uc_float_strings; + format_code = 'g'; + /* Fall through. */ + case 'g': + mode = 2; + /* precision 0 makes no sense for 'g' format; interpret as 1 */ + if (precision == 0) + precision = 1; + break; + + /* repr format */ + case 'r': + mode = 0; + /* Supplied precision is unused, must be 0. */ + if (precision != 0) { + PyErr_BadInternalCall(); + return NULL; + } + break; + + default: + PyErr_BadInternalCall(); + return NULL; + } + + return format_float_short(val, format_code, mode, precision, + flags & Py_DTSF_SIGN, + flags & Py_DTSF_ADD_DOT_0, + flags & Py_DTSF_ALT, + float_strings, type); } #endif /* ifdef PY_NO_SHORT_FLOAT_REPR */ Modified: python/branches/py3k-jit/Python/pythonrun.c ============================================================================== --- python/branches/py3k-jit/Python/pythonrun.c (original) +++ python/branches/py3k-jit/Python/pythonrun.c Mon May 10 23:55:43 2010 @@ -42,9 +42,9 @@ #ifndef Py_REF_DEBUG #define PRINT_TOTAL_REFS() #else /* Py_REF_DEBUG */ -#define PRINT_TOTAL_REFS() fprintf(stderr, \ - "[%" PY_FORMAT_SIZE_T "d refs]\n", \ - _Py_GetRefTotal()) +#define PRINT_TOTAL_REFS() fprintf(stderr, \ + "[%" PY_FORMAT_SIZE_T "d refs]\n", \ + _Py_GetRefTotal()) #endif #ifdef __cplusplus @@ -61,9 +61,9 @@ static int initstdio(void); static void flush_io(void); static PyObject *run_mod(mod_ty, const char *, PyObject *, PyObject *, - PyCompilerFlags *, PyArena *); + PyCompilerFlags *, PyArena *); static PyObject *run_pyc_file(FILE *, const char *, PyObject *, PyObject *, - PyCompilerFlags *); + PyCompilerFlags *); static void err_input(perrdetail *); static void initsigs(void); static void call_py_exitfuncs(void); @@ -97,7 +97,7 @@ PyObject * PyModule_GetWarningsModule(void) { - return PyImport_ImportModule("warnings"); + return PyImport_ImportModule("warnings"); } static int initialized = 0; @@ -107,7 +107,7 @@ int Py_IsInitialized(void) { - return initialized; + return initialized; } /* Global initializations. Can be undone by Py_Finalize(). Don't @@ -125,191 +125,191 @@ static int add_flag(int flag, const char *envs) { - int env = atoi(envs); - if (flag < env) - flag = env; - if (flag < 1) - flag = 1; - return flag; + int env = atoi(envs); + if (flag < env) + flag = env; + if (flag < 1) + flag = 1; + return flag; } #if defined(HAVE_LANGINFO_H) && defined(CODESET) static char* get_codeset(void) { - char* codeset; - PyObject *codec, *name; + char* codeset; + PyObject *codec, *name; - codeset = nl_langinfo(CODESET); - if (!codeset || codeset[0] == '\0') - return NULL; - - codec = _PyCodec_Lookup(codeset); - if (!codec) - goto error; - - name = PyObject_GetAttrString(codec, "name"); - Py_CLEAR(codec); - if (!name) - goto error; - - codeset = strdup(_PyUnicode_AsString(name)); - Py_DECREF(name); - return codeset; + codeset = nl_langinfo(CODESET); + if (!codeset || codeset[0] == '\0') + return NULL; + + codec = _PyCodec_Lookup(codeset); + if (!codec) + goto error; + + name = PyObject_GetAttrString(codec, "name"); + Py_CLEAR(codec); + if (!name) + goto error; + + codeset = strdup(_PyUnicode_AsString(name)); + Py_DECREF(name); + return codeset; error: - Py_XDECREF(codec); - PyErr_Clear(); - return NULL; + Py_XDECREF(codec); + PyErr_Clear(); + return NULL; } #endif void Py_InitializeEx(int install_sigs) { - PyInterpreterState *interp; - PyThreadState *tstate; - PyObject *bimod, *sysmod, *pstderr; - char *p; + PyInterpreterState *interp; + PyThreadState *tstate; + PyObject *bimod, *sysmod, *pstderr; + char *p; #if defined(HAVE_LANGINFO_H) && defined(CODESET) - char *codeset; + char *codeset; #endif - extern void _Py_ReadyTypes(void); + extern void _Py_ReadyTypes(void); - if (initialized) - return; - initialized = 1; + if (initialized) + return; + initialized = 1; #if defined(HAVE_LANGINFO_H) && defined(HAVE_SETLOCALE) - /* Set up the LC_CTYPE locale, so we can obtain - the locale's charset without having to switch - locales. */ - setlocale(LC_CTYPE, ""); -#endif - - if ((p = Py_GETENV("PYTHONDEBUG")) && *p != '\0') - Py_DebugFlag = add_flag(Py_DebugFlag, p); - if ((p = Py_GETENV("PYTHONVERBOSE")) && *p != '\0') - Py_VerboseFlag = add_flag(Py_VerboseFlag, p); - if ((p = Py_GETENV("PYTHONOPTIMIZE")) && *p != '\0') - Py_OptimizeFlag = add_flag(Py_OptimizeFlag, p); - if ((p = Py_GETENV("PYTHONDONTWRITEBYTECODE")) && *p != '\0') - Py_DontWriteBytecodeFlag = add_flag(Py_DontWriteBytecodeFlag, p); - - interp = PyInterpreterState_New(); - if (interp == NULL) - Py_FatalError("Py_Initialize: can't make first interpreter"); - - tstate = PyThreadState_New(interp); - if (tstate == NULL) - Py_FatalError("Py_Initialize: can't make first thread"); - (void) PyThreadState_Swap(tstate); - - _Py_ReadyTypes(); - - if (!_PyFrame_Init()) - Py_FatalError("Py_Initialize: can't init frames"); - - if (!_PyLong_Init()) - Py_FatalError("Py_Initialize: can't init longs"); - - if (!PyByteArray_Init()) - Py_FatalError("Py_Initialize: can't init bytearray"); - - _PyFloat_Init(); - - interp->modules = PyDict_New(); - if (interp->modules == NULL) - Py_FatalError("Py_Initialize: can't make modules dictionary"); - interp->modules_reloading = PyDict_New(); - if (interp->modules_reloading == NULL) - Py_FatalError("Py_Initialize: can't make modules_reloading dictionary"); - - /* Init Unicode implementation; relies on the codec registry */ - _PyUnicode_Init(); - - bimod = _PyBuiltin_Init(); - if (bimod == NULL) - Py_FatalError("Py_Initialize: can't initialize builtins modules"); - _PyImport_FixupExtension(bimod, "builtins", "builtins"); - interp->builtins = PyModule_GetDict(bimod); - if (interp->builtins == NULL) - Py_FatalError("Py_Initialize: can't initialize builtins dict"); - Py_INCREF(interp->builtins); - - /* initialize builtin exceptions */ - _PyExc_Init(); - - sysmod = _PySys_Init(); - if (sysmod == NULL) - Py_FatalError("Py_Initialize: can't initialize sys"); - interp->sysdict = PyModule_GetDict(sysmod); - if (interp->sysdict == NULL) - Py_FatalError("Py_Initialize: can't initialize sys dict"); - Py_INCREF(interp->sysdict); - _PyImport_FixupExtension(sysmod, "sys", "sys"); - PySys_SetPath(Py_GetPath()); - PyDict_SetItemString(interp->sysdict, "modules", - interp->modules); - - /* Set up a preliminary stderr printer until we have enough - infrastructure for the io module in place. */ - pstderr = PyFile_NewStdPrinter(fileno(stderr)); - if (pstderr == NULL) - Py_FatalError("Py_Initialize: can't set preliminary stderr"); - PySys_SetObject("stderr", pstderr); - PySys_SetObject("__stderr__", pstderr); + /* Set up the LC_CTYPE locale, so we can obtain + the locale's charset without having to switch + locales. */ + setlocale(LC_CTYPE, ""); +#endif + + if ((p = Py_GETENV("PYTHONDEBUG")) && *p != '\0') + Py_DebugFlag = add_flag(Py_DebugFlag, p); + if ((p = Py_GETENV("PYTHONVERBOSE")) && *p != '\0') + Py_VerboseFlag = add_flag(Py_VerboseFlag, p); + if ((p = Py_GETENV("PYTHONOPTIMIZE")) && *p != '\0') + Py_OptimizeFlag = add_flag(Py_OptimizeFlag, p); + if ((p = Py_GETENV("PYTHONDONTWRITEBYTECODE")) && *p != '\0') + Py_DontWriteBytecodeFlag = add_flag(Py_DontWriteBytecodeFlag, p); + + interp = PyInterpreterState_New(); + if (interp == NULL) + Py_FatalError("Py_Initialize: can't make first interpreter"); + + tstate = PyThreadState_New(interp); + if (tstate == NULL) + Py_FatalError("Py_Initialize: can't make first thread"); + (void) PyThreadState_Swap(tstate); + + _Py_ReadyTypes(); + + if (!_PyFrame_Init()) + Py_FatalError("Py_Initialize: can't init frames"); + + if (!_PyLong_Init()) + Py_FatalError("Py_Initialize: can't init longs"); + + if (!PyByteArray_Init()) + Py_FatalError("Py_Initialize: can't init bytearray"); + + _PyFloat_Init(); + + interp->modules = PyDict_New(); + if (interp->modules == NULL) + Py_FatalError("Py_Initialize: can't make modules dictionary"); + interp->modules_reloading = PyDict_New(); + if (interp->modules_reloading == NULL) + Py_FatalError("Py_Initialize: can't make modules_reloading dictionary"); + + /* Init Unicode implementation; relies on the codec registry */ + _PyUnicode_Init(); + + bimod = _PyBuiltin_Init(); + if (bimod == NULL) + Py_FatalError("Py_Initialize: can't initialize builtins modules"); + _PyImport_FixupExtension(bimod, "builtins", "builtins"); + interp->builtins = PyModule_GetDict(bimod); + if (interp->builtins == NULL) + Py_FatalError("Py_Initialize: can't initialize builtins dict"); + Py_INCREF(interp->builtins); + + /* initialize builtin exceptions */ + _PyExc_Init(); + + sysmod = _PySys_Init(); + if (sysmod == NULL) + Py_FatalError("Py_Initialize: can't initialize sys"); + interp->sysdict = PyModule_GetDict(sysmod); + if (interp->sysdict == NULL) + Py_FatalError("Py_Initialize: can't initialize sys dict"); + Py_INCREF(interp->sysdict); + _PyImport_FixupExtension(sysmod, "sys", "sys"); + PySys_SetPath(Py_GetPath()); + PyDict_SetItemString(interp->sysdict, "modules", + interp->modules); + + /* Set up a preliminary stderr printer until we have enough + infrastructure for the io module in place. */ + pstderr = PyFile_NewStdPrinter(fileno(stderr)); + if (pstderr == NULL) + Py_FatalError("Py_Initialize: can't set preliminary stderr"); + PySys_SetObject("stderr", pstderr); + PySys_SetObject("__stderr__", pstderr); - _PyImport_Init(); + _PyImport_Init(); - _PyImportHooks_Init(); + _PyImportHooks_Init(); #if defined(HAVE_LANGINFO_H) && defined(CODESET) - /* On Unix, set the file system encoding according to the - user's preference, if the CODESET names a well-known - Python codec, and Py_FileSystemDefaultEncoding isn't - initialized by other means. Also set the encoding of - stdin and stdout if these are terminals. */ - - codeset = get_codeset(); - if (codeset) { - if (!Py_FileSystemDefaultEncoding) - Py_FileSystemDefaultEncoding = codeset; - else - free(codeset); - } -#endif - - if (install_sigs) - initsigs(); /* Signal handling stuff, including initintr() */ - - /* Initialize warnings. */ - _PyWarnings_Init(); - if (PySys_HasWarnOptions()) { - PyObject *warnings_module = PyImport_ImportModule("warnings"); - if (!warnings_module) - PyErr_Clear(); - Py_XDECREF(warnings_module); - } - - initmain(); /* Module __main__ */ - if (initstdio() < 0) - Py_FatalError( - "Py_Initialize: can't initialize sys standard streams"); + /* On Unix, set the file system encoding according to the + user's preference, if the CODESET names a well-known + Python codec, and Py_FileSystemDefaultEncoding isn't + initialized by other means. Also set the encoding of + stdin and stdout if these are terminals. */ + + codeset = get_codeset(); + if (codeset) { + if (!Py_FileSystemDefaultEncoding) + Py_FileSystemDefaultEncoding = codeset; + else + free(codeset); + } +#endif + + if (install_sigs) + initsigs(); /* Signal handling stuff, including initintr() */ + + /* Initialize warnings. */ + _PyWarnings_Init(); + if (PySys_HasWarnOptions()) { + PyObject *warnings_module = PyImport_ImportModule("warnings"); + if (!warnings_module) + PyErr_Clear(); + Py_XDECREF(warnings_module); + } + + initmain(); /* Module __main__ */ + if (initstdio() < 0) + Py_FatalError( + "Py_Initialize: can't initialize sys standard streams"); - /* auto-thread-state API, if available */ + /* auto-thread-state API, if available */ #ifdef WITH_THREAD - _PyGILState_Init(interp, tstate); + _PyGILState_Init(interp, tstate); #endif /* WITH_THREAD */ - if (!Py_NoSiteFlag) - initsite(); /* Module site */ + if (!Py_NoSiteFlag) + initsite(); /* Module site */ } void Py_Initialize(void) { - Py_InitializeEx(1); + Py_InitializeEx(1); } @@ -322,25 +322,25 @@ static void flush_std_files(void) { - PyObject *fout = PySys_GetObject("stdout"); - PyObject *ferr = PySys_GetObject("stderr"); - PyObject *tmp; - - if (fout != NULL && fout != Py_None) { - tmp = PyObject_CallMethod(fout, "flush", ""); - if (tmp == NULL) - PyErr_Clear(); - else - Py_DECREF(tmp); - } - - if (ferr != NULL || ferr != Py_None) { - tmp = PyObject_CallMethod(ferr, "flush", ""); - if (tmp == NULL) - PyErr_Clear(); - else - Py_DECREF(tmp); - } + PyObject *fout = PySys_GetObject("stdout"); + PyObject *ferr = PySys_GetObject("stderr"); + PyObject *tmp; + + if (fout != NULL && fout != Py_None) { + tmp = PyObject_CallMethod(fout, "flush", ""); + if (tmp == NULL) + PyErr_Clear(); + else + Py_DECREF(tmp); + } + + if (ferr != NULL || ferr != Py_None) { + tmp = PyObject_CallMethod(ferr, "flush", ""); + if (tmp == NULL) + PyErr_Clear(); + else + Py_DECREF(tmp); + } } /* Undo the effect of Py_Initialize(). @@ -360,169 +360,169 @@ void Py_Finalize(void) { - PyInterpreterState *interp; - PyThreadState *tstate; + PyInterpreterState *interp; + PyThreadState *tstate; - if (!initialized) - return; + if (!initialized) + return; - wait_for_thread_shutdown(); + wait_for_thread_shutdown(); - /* The interpreter is still entirely intact at this point, and the - * exit funcs may be relying on that. In particular, if some thread - * or exit func is still waiting to do an import, the import machinery - * expects Py_IsInitialized() to return true. So don't say the - * interpreter is uninitialized until after the exit funcs have run. - * Note that Threading.py uses an exit func to do a join on all the - * threads created thru it, so this also protects pending imports in - * the threads created via Threading. - */ - call_py_exitfuncs(); - initialized = 0; - - /* Flush stdout+stderr */ - flush_std_files(); - - /* Get current thread state and interpreter pointer */ - tstate = PyThreadState_GET(); - interp = tstate->interp; - - /* Disable signal handling */ - PyOS_FiniInterrupts(); - - /* Clear type lookup cache */ - PyType_ClearCache(); - - /* Collect garbage. This may call finalizers; it's nice to call these - * before all modules are destroyed. - * XXX If a __del__ or weakref callback is triggered here, and tries to - * XXX import a module, bad things can happen, because Python no - * XXX longer believes it's initialized. - * XXX Fatal Python error: Interpreter not initialized (version mismatch?) - * XXX is easy to provoke that way. I've also seen, e.g., - * XXX Exception exceptions.ImportError: 'No module named sha' - * XXX in ignored - * XXX but I'm unclear on exactly how that one happens. In any case, - * XXX I haven't seen a real-life report of either of these. - */ - PyGC_Collect(); + /* The interpreter is still entirely intact at this point, and the + * exit funcs may be relying on that. In particular, if some thread + * or exit func is still waiting to do an import, the import machinery + * expects Py_IsInitialized() to return true. So don't say the + * interpreter is uninitialized until after the exit funcs have run. + * Note that Threading.py uses an exit func to do a join on all the + * threads created thru it, so this also protects pending imports in + * the threads created via Threading. + */ + call_py_exitfuncs(); + initialized = 0; + + /* Flush stdout+stderr */ + flush_std_files(); + + /* Get current thread state and interpreter pointer */ + tstate = PyThreadState_GET(); + interp = tstate->interp; + + /* Disable signal handling */ + PyOS_FiniInterrupts(); + + /* Clear type lookup cache */ + PyType_ClearCache(); + + /* Collect garbage. This may call finalizers; it's nice to call these + * before all modules are destroyed. + * XXX If a __del__ or weakref callback is triggered here, and tries to + * XXX import a module, bad things can happen, because Python no + * XXX longer believes it's initialized. + * XXX Fatal Python error: Interpreter not initialized (version mismatch?) + * XXX is easy to provoke that way. I've also seen, e.g., + * XXX Exception exceptions.ImportError: 'No module named sha' + * XXX in ignored + * XXX but I'm unclear on exactly how that one happens. In any case, + * XXX I haven't seen a real-life report of either of these. + */ + PyGC_Collect(); #ifdef COUNT_ALLOCS - /* With COUNT_ALLOCS, it helps to run GC multiple times: - each collection might release some types from the type - list, so they become garbage. */ - while (PyGC_Collect() > 0) - /* nothing */; -#endif - - /* Destroy all modules */ - PyImport_Cleanup(); - - /* Flush stdout+stderr (again, in case more was printed) */ - flush_std_files(); - - /* Collect final garbage. This disposes of cycles created by - * new-style class definitions, for example. - * XXX This is disabled because it caused too many problems. If - * XXX a __del__ or weakref callback triggers here, Python code has - * XXX a hard time running, because even the sys module has been - * XXX cleared out (sys.stdout is gone, sys.excepthook is gone, etc). - * XXX One symptom is a sequence of information-free messages - * XXX coming from threads (if a __del__ or callback is invoked, - * XXX other threads can execute too, and any exception they encounter - * XXX triggers a comedy of errors as subsystem after subsystem - * XXX fails to find what it *expects* to find in sys to help report - * XXX the exception and consequent unexpected failures). I've also - * XXX seen segfaults then, after adding print statements to the - * XXX Python code getting called. - */ + /* With COUNT_ALLOCS, it helps to run GC multiple times: + each collection might release some types from the type + list, so they become garbage. */ + while (PyGC_Collect() > 0) + /* nothing */; +#endif + + /* Destroy all modules */ + PyImport_Cleanup(); + + /* Flush stdout+stderr (again, in case more was printed) */ + flush_std_files(); + + /* Collect final garbage. This disposes of cycles created by + * new-style class definitions, for example. + * XXX This is disabled because it caused too many problems. If + * XXX a __del__ or weakref callback triggers here, Python code has + * XXX a hard time running, because even the sys module has been + * XXX cleared out (sys.stdout is gone, sys.excepthook is gone, etc). + * XXX One symptom is a sequence of information-free messages + * XXX coming from threads (if a __del__ or callback is invoked, + * XXX other threads can execute too, and any exception they encounter + * XXX triggers a comedy of errors as subsystem after subsystem + * XXX fails to find what it *expects* to find in sys to help report + * XXX the exception and consequent unexpected failures). I've also + * XXX seen segfaults then, after adding print statements to the + * XXX Python code getting called. + */ #if 0 - PyGC_Collect(); + PyGC_Collect(); #endif - /* Destroy the database used by _PyImport_{Fixup,Find}Extension */ - _PyImport_Fini(); + /* Destroy the database used by _PyImport_{Fixup,Find}Extension */ + _PyImport_Fini(); - /* Debugging stuff */ + /* Debugging stuff */ #ifdef COUNT_ALLOCS - dump_counts(stdout); + dump_counts(stdout); #endif - PRINT_TOTAL_REFS(); + PRINT_TOTAL_REFS(); #ifdef Py_TRACE_REFS - /* Display all objects still alive -- this can invoke arbitrary - * __repr__ overrides, so requires a mostly-intact interpreter. - * Alas, a lot of stuff may still be alive now that will be cleaned - * up later. - */ - if (Py_GETENV("PYTHONDUMPREFS")) - _Py_PrintReferences(stderr); + /* Display all objects still alive -- this can invoke arbitrary + * __repr__ overrides, so requires a mostly-intact interpreter. + * Alas, a lot of stuff may still be alive now that will be cleaned + * up later. + */ + if (Py_GETENV("PYTHONDUMPREFS")) + _Py_PrintReferences(stderr); #endif /* Py_TRACE_REFS */ - /* Clear interpreter state */ - PyInterpreterState_Clear(interp); + /* Clear interpreter state */ + PyInterpreterState_Clear(interp); - /* Now we decref the exception classes. After this point nothing - can raise an exception. That's okay, because each Fini() method - below has been checked to make sure no exceptions are ever - raised. - */ + /* Now we decref the exception classes. After this point nothing + can raise an exception. That's okay, because each Fini() method + below has been checked to make sure no exceptions are ever + raised. + */ - _PyExc_Fini(); + _PyExc_Fini(); - /* Cleanup auto-thread-state */ + /* Cleanup auto-thread-state */ #ifdef WITH_THREAD - _PyGILState_Fini(); + _PyGILState_Fini(); #endif /* WITH_THREAD */ - /* Delete current thread */ - PyThreadState_Swap(NULL); - PyInterpreterState_Delete(interp); - - /* Sundry finalizers */ - PyMethod_Fini(); - PyFrame_Fini(); - PyCFunction_Fini(); - PyTuple_Fini(); - PyList_Fini(); - PySet_Fini(); - PyBytes_Fini(); - PyByteArray_Fini(); - PyLong_Fini(); - PyFloat_Fini(); - PyDict_Fini(); - - /* Cleanup Unicode implementation */ - _PyUnicode_Fini(); - - /* reset file system default encoding */ - if (!Py_HasFileSystemDefaultEncoding) { - free((char*)Py_FileSystemDefaultEncoding); - Py_FileSystemDefaultEncoding = NULL; - } - - /* XXX Still allocated: - - various static ad-hoc pointers to interned strings - - int and float free list blocks - - whatever various modules and libraries allocate - */ + /* Delete current thread */ + PyThreadState_Swap(NULL); + PyInterpreterState_Delete(interp); + + /* Sundry finalizers */ + PyMethod_Fini(); + PyFrame_Fini(); + PyCFunction_Fini(); + PyTuple_Fini(); + PyList_Fini(); + PySet_Fini(); + PyBytes_Fini(); + PyByteArray_Fini(); + PyLong_Fini(); + PyFloat_Fini(); + PyDict_Fini(); + + /* Cleanup Unicode implementation */ + _PyUnicode_Fini(); + + /* reset file system default encoding */ + if (!Py_HasFileSystemDefaultEncoding) { + free((char*)Py_FileSystemDefaultEncoding); + Py_FileSystemDefaultEncoding = NULL; + } + + /* XXX Still allocated: + - various static ad-hoc pointers to interned strings + - int and float free list blocks + - whatever various modules and libraries allocate + */ - PyGrammar_RemoveAccelerators(&_PyParser_Grammar); + PyGrammar_RemoveAccelerators(&_PyParser_Grammar); #ifdef Py_TRACE_REFS - /* Display addresses (& refcnts) of all objects still alive. - * An address can be used to find the repr of the object, printed - * above by _Py_PrintReferences. - */ - if (Py_GETENV("PYTHONDUMPREFS")) - _Py_PrintReferenceAddresses(stderr); + /* Display addresses (& refcnts) of all objects still alive. + * An address can be used to find the repr of the object, printed + * above by _Py_PrintReferences. + */ + if (Py_GETENV("PYTHONDUMPREFS")) + _Py_PrintReferenceAddresses(stderr); #endif /* Py_TRACE_REFS */ #ifdef PYMALLOC_DEBUG - if (Py_GETENV("PYTHONMALLOCSTATS")) - _PyObject_DebugMallocStats(); + if (Py_GETENV("PYTHONMALLOCSTATS")) + _PyObject_DebugMallocStats(); #endif - call_ll_exitfuncs(); + call_ll_exitfuncs(); } /* Create and initialize a new interpreter and thread, and return the @@ -541,81 +541,81 @@ PyThreadState * Py_NewInterpreter(void) { - PyInterpreterState *interp; - PyThreadState *tstate, *save_tstate; - PyObject *bimod, *sysmod; - - if (!initialized) - Py_FatalError("Py_NewInterpreter: call Py_Initialize first"); - - interp = PyInterpreterState_New(); - if (interp == NULL) - return NULL; - - tstate = PyThreadState_New(interp); - if (tstate == NULL) { - PyInterpreterState_Delete(interp); - return NULL; - } - - save_tstate = PyThreadState_Swap(tstate); - - /* XXX The following is lax in error checking */ - - interp->modules = PyDict_New(); - interp->modules_reloading = PyDict_New(); - - bimod = _PyImport_FindExtension("builtins", "builtins"); - if (bimod != NULL) { - interp->builtins = PyModule_GetDict(bimod); - if (interp->builtins == NULL) - goto handle_error; - Py_INCREF(interp->builtins); - } - - /* initialize builtin exceptions */ - _PyExc_Init(); - - sysmod = _PyImport_FindExtension("sys", "sys"); - if (bimod != NULL && sysmod != NULL) { - PyObject *pstderr; - interp->sysdict = PyModule_GetDict(sysmod); - if (interp->sysdict == NULL) - goto handle_error; - Py_INCREF(interp->sysdict); - PySys_SetPath(Py_GetPath()); - PyDict_SetItemString(interp->sysdict, "modules", - interp->modules); - /* Set up a preliminary stderr printer until we have enough - infrastructure for the io module in place. */ - pstderr = PyFile_NewStdPrinter(fileno(stderr)); - if (pstderr == NULL) - Py_FatalError("Py_Initialize: can't set preliminary stderr"); - PySys_SetObject("stderr", pstderr); - PySys_SetObject("__stderr__", pstderr); - - _PyImportHooks_Init(); - if (initstdio() < 0) - Py_FatalError( - "Py_Initialize: can't initialize sys standard streams"); - initmain(); - if (!Py_NoSiteFlag) - initsite(); - } + PyInterpreterState *interp; + PyThreadState *tstate, *save_tstate; + PyObject *bimod, *sysmod; + + if (!initialized) + Py_FatalError("Py_NewInterpreter: call Py_Initialize first"); + + interp = PyInterpreterState_New(); + if (interp == NULL) + return NULL; + + tstate = PyThreadState_New(interp); + if (tstate == NULL) { + PyInterpreterState_Delete(interp); + return NULL; + } + + save_tstate = PyThreadState_Swap(tstate); + + /* XXX The following is lax in error checking */ + + interp->modules = PyDict_New(); + interp->modules_reloading = PyDict_New(); + + bimod = _PyImport_FindExtension("builtins", "builtins"); + if (bimod != NULL) { + interp->builtins = PyModule_GetDict(bimod); + if (interp->builtins == NULL) + goto handle_error; + Py_INCREF(interp->builtins); + } + + /* initialize builtin exceptions */ + _PyExc_Init(); + + sysmod = _PyImport_FindExtension("sys", "sys"); + if (bimod != NULL && sysmod != NULL) { + PyObject *pstderr; + interp->sysdict = PyModule_GetDict(sysmod); + if (interp->sysdict == NULL) + goto handle_error; + Py_INCREF(interp->sysdict); + PySys_SetPath(Py_GetPath()); + PyDict_SetItemString(interp->sysdict, "modules", + interp->modules); + /* Set up a preliminary stderr printer until we have enough + infrastructure for the io module in place. */ + pstderr = PyFile_NewStdPrinter(fileno(stderr)); + if (pstderr == NULL) + Py_FatalError("Py_Initialize: can't set preliminary stderr"); + PySys_SetObject("stderr", pstderr); + PySys_SetObject("__stderr__", pstderr); + + _PyImportHooks_Init(); + if (initstdio() < 0) + Py_FatalError( + "Py_Initialize: can't initialize sys standard streams"); + initmain(); + if (!Py_NoSiteFlag) + initsite(); + } - if (!PyErr_Occurred()) - return tstate; + if (!PyErr_Occurred()) + return tstate; handle_error: - /* Oops, it didn't work. Undo it all. */ + /* Oops, it didn't work. Undo it all. */ - PyErr_Print(); - PyThreadState_Clear(tstate); - PyThreadState_Swap(save_tstate); - PyThreadState_Delete(tstate); - PyInterpreterState_Delete(interp); + PyErr_Print(); + PyThreadState_Clear(tstate); + PyThreadState_Swap(save_tstate); + PyThreadState_Delete(tstate); + PyInterpreterState_Delete(interp); - return NULL; + return NULL; } /* Delete an interpreter and its last thread. This requires that the @@ -633,19 +633,19 @@ void Py_EndInterpreter(PyThreadState *tstate) { - PyInterpreterState *interp = tstate->interp; + PyInterpreterState *interp = tstate->interp; - if (tstate != PyThreadState_GET()) - Py_FatalError("Py_EndInterpreter: thread is not current"); - if (tstate->frame != NULL) - Py_FatalError("Py_EndInterpreter: thread still has a frame"); - if (tstate != interp->tstate_head || tstate->next != NULL) - Py_FatalError("Py_EndInterpreter: not the last thread"); - - PyImport_Cleanup(); - PyInterpreterState_Clear(interp); - PyThreadState_Swap(NULL); - PyInterpreterState_Delete(interp); + if (tstate != PyThreadState_GET()) + Py_FatalError("Py_EndInterpreter: thread is not current"); + if (tstate->frame != NULL) + Py_FatalError("Py_EndInterpreter: thread still has a frame"); + if (tstate != interp->tstate_head || tstate->next != NULL) + Py_FatalError("Py_EndInterpreter: not the last thread"); + + PyImport_Cleanup(); + PyInterpreterState_Clear(interp); + PyThreadState_Swap(NULL); + PyInterpreterState_Delete(interp); } static wchar_t *progname = L"python"; @@ -653,14 +653,14 @@ void Py_SetProgramName(wchar_t *pn) { - if (pn && *pn) - progname = pn; + if (pn && *pn) + progname = pn; } wchar_t * Py_GetProgramName(void) { - return progname; + return progname; } static wchar_t *default_home = NULL; @@ -669,23 +669,23 @@ void Py_SetPythonHome(wchar_t *home) { - default_home = home; + default_home = home; } wchar_t * Py_GetPythonHome(void) { - wchar_t *home = default_home; - if (home == NULL && !Py_IgnoreEnvironmentFlag) { - char* chome = Py_GETENV("PYTHONHOME"); - if (chome) { - size_t r = mbstowcs(env_home, chome, PATH_MAX+1); - if (r != (size_t)-1 && r <= PATH_MAX) - home = env_home; - } + wchar_t *home = default_home; + if (home == NULL && !Py_IgnoreEnvironmentFlag) { + char* chome = Py_GETENV("PYTHONHOME"); + if (chome) { + size_t r = mbstowcs(env_home, chome, PATH_MAX+1); + if (r != (size_t)-1 && r <= PATH_MAX) + home = env_home; + } - } - return home; + } + return home; } /* Create __main__ module */ @@ -693,18 +693,18 @@ static void initmain(void) { - PyObject *m, *d; - m = PyImport_AddModule("__main__"); - if (m == NULL) - Py_FatalError("can't create __main__ module"); - d = PyModule_GetDict(m); - if (PyDict_GetItemString(d, "__builtins__") == NULL) { - PyObject *bimod = PyImport_ImportModule("builtins"); - if (bimod == NULL || - PyDict_SetItemString(d, "__builtins__", bimod) != 0) - Py_FatalError("can't add __builtins__ to __main__"); - Py_DECREF(bimod); - } + PyObject *m, *d; + m = PyImport_AddModule("__main__"); + if (m == NULL) + Py_FatalError("can't create __main__ module"); + d = PyModule_GetDict(m); + if (PyDict_GetItemString(d, "__builtins__") == NULL) { + PyObject *bimod = PyImport_ImportModule("builtins"); + if (bimod == NULL || + PyDict_SetItemString(d, "__builtins__", bimod) != 0) + Py_FatalError("can't add __builtins__ to __main__"); + Py_DECREF(bimod); + } } /* Import the site module (not into __main__ though) */ @@ -712,386 +712,386 @@ static void initsite(void) { - PyObject *m; - m = PyImport_ImportModule("site"); - if (m == NULL) { - PyErr_Print(); - Py_Finalize(); - exit(1); - } - else { - Py_DECREF(m); - } + PyObject *m; + m = PyImport_ImportModule("site"); + if (m == NULL) { + PyErr_Print(); + Py_Finalize(); + exit(1); + } + else { + Py_DECREF(m); + } } static PyObject* create_stdio(PyObject* io, - int fd, int write_mode, char* name, - char* encoding, char* errors) + int fd, int write_mode, char* name, + char* encoding, char* errors) { - PyObject *buf = NULL, *stream = NULL, *text = NULL, *raw = NULL, *res; - const char* mode; - PyObject *line_buffering; - int buffering, isatty; - - /* stdin is always opened in buffered mode, first because it shouldn't - make a difference in common use cases, second because TextIOWrapper - depends on the presence of a read1() method which only exists on - buffered streams. - */ - if (Py_UnbufferedStdioFlag && write_mode) - buffering = 0; - else - buffering = -1; - if (write_mode) - mode = "wb"; - else - mode = "rb"; - buf = PyObject_CallMethod(io, "open", "isiOOOi", - fd, mode, buffering, - Py_None, Py_None, Py_None, 0); - if (buf == NULL) - goto error; - - if (buffering) { - raw = PyObject_GetAttrString(buf, "raw"); - if (raw == NULL) - goto error; - } - else { - raw = buf; - Py_INCREF(raw); - } - - text = PyUnicode_FromString(name); - if (text == NULL || PyObject_SetAttrString(raw, "name", text) < 0) - goto error; - res = PyObject_CallMethod(raw, "isatty", ""); - if (res == NULL) - goto error; - isatty = PyObject_IsTrue(res); - Py_DECREF(res); - if (isatty == -1) - goto error; - if (isatty || Py_UnbufferedStdioFlag) - line_buffering = Py_True; - else - line_buffering = Py_False; - - Py_CLEAR(raw); - Py_CLEAR(text); - - stream = PyObject_CallMethod(io, "TextIOWrapper", "OsssO", - buf, encoding, errors, - "\n", line_buffering); - Py_CLEAR(buf); - if (stream == NULL) - goto error; - - if (write_mode) - mode = "w"; - else - mode = "r"; - text = PyUnicode_FromString(mode); - if (!text || PyObject_SetAttrString(stream, "mode", text) < 0) - goto error; - Py_CLEAR(text); - return stream; + PyObject *buf = NULL, *stream = NULL, *text = NULL, *raw = NULL, *res; + const char* mode; + PyObject *line_buffering; + int buffering, isatty; + + /* stdin is always opened in buffered mode, first because it shouldn't + make a difference in common use cases, second because TextIOWrapper + depends on the presence of a read1() method which only exists on + buffered streams. + */ + if (Py_UnbufferedStdioFlag && write_mode) + buffering = 0; + else + buffering = -1; + if (write_mode) + mode = "wb"; + else + mode = "rb"; + buf = PyObject_CallMethod(io, "open", "isiOOOi", + fd, mode, buffering, + Py_None, Py_None, Py_None, 0); + if (buf == NULL) + goto error; + + if (buffering) { + raw = PyObject_GetAttrString(buf, "raw"); + if (raw == NULL) + goto error; + } + else { + raw = buf; + Py_INCREF(raw); + } + + text = PyUnicode_FromString(name); + if (text == NULL || PyObject_SetAttrString(raw, "name", text) < 0) + goto error; + res = PyObject_CallMethod(raw, "isatty", ""); + if (res == NULL) + goto error; + isatty = PyObject_IsTrue(res); + Py_DECREF(res); + if (isatty == -1) + goto error; + if (isatty || Py_UnbufferedStdioFlag) + line_buffering = Py_True; + else + line_buffering = Py_False; + + Py_CLEAR(raw); + Py_CLEAR(text); + + stream = PyObject_CallMethod(io, "TextIOWrapper", "OsssO", + buf, encoding, errors, + "\n", line_buffering); + Py_CLEAR(buf); + if (stream == NULL) + goto error; + + if (write_mode) + mode = "w"; + else + mode = "r"; + text = PyUnicode_FromString(mode); + if (!text || PyObject_SetAttrString(stream, "mode", text) < 0) + goto error; + Py_CLEAR(text); + return stream; error: - Py_XDECREF(buf); - Py_XDECREF(stream); - Py_XDECREF(text); - Py_XDECREF(raw); - return NULL; + Py_XDECREF(buf); + Py_XDECREF(stream); + Py_XDECREF(text); + Py_XDECREF(raw); + return NULL; } /* Initialize sys.stdin, stdout, stderr and builtins.open */ static int initstdio(void) { - PyObject *iomod = NULL, *wrapper; - PyObject *bimod = NULL; - PyObject *m; - PyObject *std = NULL; - int status = 0, fd; - PyObject * encoding_attr; - char *encoding = NULL, *errors; - - /* Hack to avoid a nasty recursion issue when Python is invoked - in verbose mode: pre-import the Latin-1 and UTF-8 codecs */ - if ((m = PyImport_ImportModule("encodings.utf_8")) == NULL) { - goto error; - } - Py_DECREF(m); - - if (!(m = PyImport_ImportModule("encodings.latin_1"))) { - goto error; - } - Py_DECREF(m); - - if (!(bimod = PyImport_ImportModule("builtins"))) { - goto error; - } - - if (!(iomod = PyImport_ImportModule("io"))) { - goto error; - } - if (!(wrapper = PyObject_GetAttrString(iomod, "OpenWrapper"))) { - goto error; - } - - /* Set builtins.open */ - if (PyObject_SetAttrString(bimod, "open", wrapper) == -1) { - goto error; - } - - encoding = Py_GETENV("PYTHONIOENCODING"); - errors = NULL; - if (encoding) { - encoding = strdup(encoding); - errors = strchr(encoding, ':'); - if (errors) { - *errors = '\0'; - errors++; - } - } - - /* Set sys.stdin */ - fd = fileno(stdin); - /* Under some conditions stdin, stdout and stderr may not be connected - * and fileno() may point to an invalid file descriptor. For example - * GUI apps don't have valid standard streams by default. - */ - if (fd < 0) { + PyObject *iomod = NULL, *wrapper; + PyObject *bimod = NULL; + PyObject *m; + PyObject *std = NULL; + int status = 0, fd; + PyObject * encoding_attr; + char *encoding = NULL, *errors; + + /* Hack to avoid a nasty recursion issue when Python is invoked + in verbose mode: pre-import the Latin-1 and UTF-8 codecs */ + if ((m = PyImport_ImportModule("encodings.utf_8")) == NULL) { + goto error; + } + Py_DECREF(m); + + if (!(m = PyImport_ImportModule("encodings.latin_1"))) { + goto error; + } + Py_DECREF(m); + + if (!(bimod = PyImport_ImportModule("builtins"))) { + goto error; + } + + if (!(iomod = PyImport_ImportModule("io"))) { + goto error; + } + if (!(wrapper = PyObject_GetAttrString(iomod, "OpenWrapper"))) { + goto error; + } + + /* Set builtins.open */ + if (PyObject_SetAttrString(bimod, "open", wrapper) == -1) { + goto error; + } + + encoding = Py_GETENV("PYTHONIOENCODING"); + errors = NULL; + if (encoding) { + encoding = strdup(encoding); + errors = strchr(encoding, ':'); + if (errors) { + *errors = '\0'; + errors++; + } + } + + /* Set sys.stdin */ + fd = fileno(stdin); + /* Under some conditions stdin, stdout and stderr may not be connected + * and fileno() may point to an invalid file descriptor. For example + * GUI apps don't have valid standard streams by default. + */ + if (fd < 0) { #ifdef MS_WINDOWS - std = Py_None; - Py_INCREF(std); + std = Py_None; + Py_INCREF(std); #else - goto error; + goto error; #endif - } - else { - std = create_stdio(iomod, fd, 0, "", encoding, errors); - if (std == NULL) - goto error; - } /* if (fd < 0) */ - PySys_SetObject("__stdin__", std); - PySys_SetObject("stdin", std); - Py_DECREF(std); - - /* Set sys.stdout */ - fd = fileno(stdout); - if (fd < 0) { + } + else { + std = create_stdio(iomod, fd, 0, "", encoding, errors); + if (std == NULL) + goto error; + } /* if (fd < 0) */ + PySys_SetObject("__stdin__", std); + PySys_SetObject("stdin", std); + Py_DECREF(std); + + /* Set sys.stdout */ + fd = fileno(stdout); + if (fd < 0) { #ifdef MS_WINDOWS - std = Py_None; - Py_INCREF(std); + std = Py_None; + Py_INCREF(std); #else - goto error; + goto error; #endif - } - else { - std = create_stdio(iomod, fd, 1, "", encoding, errors); - if (std == NULL) - goto error; - } /* if (fd < 0) */ - PySys_SetObject("__stdout__", std); - PySys_SetObject("stdout", std); - Py_DECREF(std); + } + else { + std = create_stdio(iomod, fd, 1, "", encoding, errors); + if (std == NULL) + goto error; + } /* if (fd < 0) */ + PySys_SetObject("__stdout__", std); + PySys_SetObject("stdout", std); + Py_DECREF(std); #if 1 /* Disable this if you have trouble debugging bootstrap stuff */ - /* Set sys.stderr, replaces the preliminary stderr */ - fd = fileno(stderr); - if (fd < 0) { + /* Set sys.stderr, replaces the preliminary stderr */ + fd = fileno(stderr); + if (fd < 0) { #ifdef MS_WINDOWS - std = Py_None; - Py_INCREF(std); + std = Py_None; + Py_INCREF(std); #else - goto error; + goto error; #endif - } - else { - std = create_stdio(iomod, fd, 1, "", encoding, "backslashreplace"); - if (std == NULL) - goto error; - } /* if (fd < 0) */ - - /* Same as hack above, pre-import stderr's codec to avoid recursion - when import.c tries to write to stderr in verbose mode. */ - encoding_attr = PyObject_GetAttrString(std, "encoding"); - if (encoding_attr != NULL) { - const char * encoding; - encoding = _PyUnicode_AsString(encoding_attr); - if (encoding != NULL) { - _PyCodec_Lookup(encoding); - } - } - PyErr_Clear(); /* Not a fatal error if codec isn't available */ - - PySys_SetObject("__stderr__", std); - PySys_SetObject("stderr", std); - Py_DECREF(std); + } + else { + std = create_stdio(iomod, fd, 1, "", encoding, "backslashreplace"); + if (std == NULL) + goto error; + } /* if (fd < 0) */ + + /* Same as hack above, pre-import stderr's codec to avoid recursion + when import.c tries to write to stderr in verbose mode. */ + encoding_attr = PyObject_GetAttrString(std, "encoding"); + if (encoding_attr != NULL) { + const char * encoding; + encoding = _PyUnicode_AsString(encoding_attr); + if (encoding != NULL) { + _PyCodec_Lookup(encoding); + } + } + PyErr_Clear(); /* Not a fatal error if codec isn't available */ + + PySys_SetObject("__stderr__", std); + PySys_SetObject("stderr", std); + Py_DECREF(std); #endif - if (0) { + if (0) { error: - status = -1; - } + status = -1; + } - if (encoding) - free(encoding); - Py_XDECREF(bimod); - Py_XDECREF(iomod); - return status; + if (encoding) + free(encoding); + Py_XDECREF(bimod); + Py_XDECREF(iomod); + return status; } /* Parse input from a file and execute it */ int PyRun_AnyFileExFlags(FILE *fp, const char *filename, int closeit, - PyCompilerFlags *flags) + PyCompilerFlags *flags) { - if (filename == NULL) - filename = "???"; - if (Py_FdIsInteractive(fp, filename)) { - int err = PyRun_InteractiveLoopFlags(fp, filename, flags); - if (closeit) - fclose(fp); - return err; - } - else - return PyRun_SimpleFileExFlags(fp, filename, closeit, flags); + if (filename == NULL) + filename = "???"; + if (Py_FdIsInteractive(fp, filename)) { + int err = PyRun_InteractiveLoopFlags(fp, filename, flags); + if (closeit) + fclose(fp); + return err; + } + else + return PyRun_SimpleFileExFlags(fp, filename, closeit, flags); } int PyRun_InteractiveLoopFlags(FILE *fp, const char *filename, PyCompilerFlags *flags) { - PyObject *v; - int ret; - PyCompilerFlags local_flags; - - if (flags == NULL) { - flags = &local_flags; - local_flags.cf_flags = 0; - } - v = PySys_GetObject("ps1"); - if (v == NULL) { - PySys_SetObject("ps1", v = PyUnicode_FromString(">>> ")); - Py_XDECREF(v); - } - v = PySys_GetObject("ps2"); - if (v == NULL) { - PySys_SetObject("ps2", v = PyUnicode_FromString("... ")); - Py_XDECREF(v); - } - for (;;) { - ret = PyRun_InteractiveOneFlags(fp, filename, flags); - PRINT_TOTAL_REFS(); - if (ret == E_EOF) - return 0; - /* - if (ret == E_NOMEM) - return -1; - */ - } + PyObject *v; + int ret; + PyCompilerFlags local_flags; + + if (flags == NULL) { + flags = &local_flags; + local_flags.cf_flags = 0; + } + v = PySys_GetObject("ps1"); + if (v == NULL) { + PySys_SetObject("ps1", v = PyUnicode_FromString(">>> ")); + Py_XDECREF(v); + } + v = PySys_GetObject("ps2"); + if (v == NULL) { + PySys_SetObject("ps2", v = PyUnicode_FromString("... ")); + Py_XDECREF(v); + } + for (;;) { + ret = PyRun_InteractiveOneFlags(fp, filename, flags); + PRINT_TOTAL_REFS(); + if (ret == E_EOF) + return 0; + /* + if (ret == E_NOMEM) + return -1; + */ + } } /* compute parser flags based on compiler flags */ static int PARSER_FLAGS(PyCompilerFlags *flags) { - int parser_flags = 0; - if (!flags) - return 0; - if (flags->cf_flags & PyCF_DONT_IMPLY_DEDENT) - parser_flags |= PyPARSE_DONT_IMPLY_DEDENT; - if (flags->cf_flags & PyCF_IGNORE_COOKIE) - parser_flags |= PyPARSE_IGNORE_COOKIE; - if (flags->cf_flags & CO_FUTURE_BARRY_AS_BDFL) - parser_flags |= PyPARSE_BARRY_AS_BDFL; - return parser_flags; + int parser_flags = 0; + if (!flags) + return 0; + if (flags->cf_flags & PyCF_DONT_IMPLY_DEDENT) + parser_flags |= PyPARSE_DONT_IMPLY_DEDENT; + if (flags->cf_flags & PyCF_IGNORE_COOKIE) + parser_flags |= PyPARSE_IGNORE_COOKIE; + if (flags->cf_flags & CO_FUTURE_BARRY_AS_BDFL) + parser_flags |= PyPARSE_BARRY_AS_BDFL; + return parser_flags; } #if 0 /* Keep an example of flags with future keyword support. */ #define PARSER_FLAGS(flags) \ - ((flags) ? ((((flags)->cf_flags & PyCF_DONT_IMPLY_DEDENT) ? \ - PyPARSE_DONT_IMPLY_DEDENT : 0) \ - | ((flags)->cf_flags & CO_FUTURE_WITH_STATEMENT ? \ - PyPARSE_WITH_IS_KEYWORD : 0)) : 0) + ((flags) ? ((((flags)->cf_flags & PyCF_DONT_IMPLY_DEDENT) ? \ + PyPARSE_DONT_IMPLY_DEDENT : 0) \ + | ((flags)->cf_flags & CO_FUTURE_WITH_STATEMENT ? \ + PyPARSE_WITH_IS_KEYWORD : 0)) : 0) #endif int PyRun_InteractiveOneFlags(FILE *fp, const char *filename, PyCompilerFlags *flags) { - PyObject *m, *d, *v, *w, *oenc = NULL; - mod_ty mod; - PyArena *arena; - char *ps1 = "", *ps2 = "", *enc = NULL; - int errcode = 0; - - if (fp == stdin) { - /* Fetch encoding from sys.stdin */ - v = PySys_GetObject("stdin"); - if (v == NULL || v == Py_None) - return -1; - oenc = PyObject_GetAttrString(v, "encoding"); - if (!oenc) - return -1; - enc = _PyUnicode_AsString(oenc); - } - v = PySys_GetObject("ps1"); - if (v != NULL) { - v = PyObject_Str(v); - if (v == NULL) - PyErr_Clear(); - else if (PyUnicode_Check(v)) - ps1 = _PyUnicode_AsString(v); - } - w = PySys_GetObject("ps2"); - if (w != NULL) { - w = PyObject_Str(w); - if (w == NULL) - PyErr_Clear(); - else if (PyUnicode_Check(w)) - ps2 = _PyUnicode_AsString(w); - } - arena = PyArena_New(); - if (arena == NULL) { - Py_XDECREF(v); - Py_XDECREF(w); - Py_XDECREF(oenc); - return -1; - } - mod = PyParser_ASTFromFile(fp, filename, enc, - Py_single_input, ps1, ps2, - flags, &errcode, arena); - Py_XDECREF(v); - Py_XDECREF(w); - Py_XDECREF(oenc); - if (mod == NULL) { - PyArena_Free(arena); - if (errcode == E_EOF) { - PyErr_Clear(); - return E_EOF; - } - PyErr_Print(); - return -1; - } - m = PyImport_AddModule("__main__"); - if (m == NULL) { - PyArena_Free(arena); - return -1; - } - d = PyModule_GetDict(m); - v = run_mod(mod, filename, d, d, flags, arena); - PyArena_Free(arena); - flush_io(); - if (v == NULL) { - PyErr_Print(); - return -1; - } - Py_DECREF(v); - return 0; + PyObject *m, *d, *v, *w, *oenc = NULL; + mod_ty mod; + PyArena *arena; + char *ps1 = "", *ps2 = "", *enc = NULL; + int errcode = 0; + + if (fp == stdin) { + /* Fetch encoding from sys.stdin */ + v = PySys_GetObject("stdin"); + if (v == NULL || v == Py_None) + return -1; + oenc = PyObject_GetAttrString(v, "encoding"); + if (!oenc) + return -1; + enc = _PyUnicode_AsString(oenc); + } + v = PySys_GetObject("ps1"); + if (v != NULL) { + v = PyObject_Str(v); + if (v == NULL) + PyErr_Clear(); + else if (PyUnicode_Check(v)) + ps1 = _PyUnicode_AsString(v); + } + w = PySys_GetObject("ps2"); + if (w != NULL) { + w = PyObject_Str(w); + if (w == NULL) + PyErr_Clear(); + else if (PyUnicode_Check(w)) + ps2 = _PyUnicode_AsString(w); + } + arena = PyArena_New(); + if (arena == NULL) { + Py_XDECREF(v); + Py_XDECREF(w); + Py_XDECREF(oenc); + return -1; + } + mod = PyParser_ASTFromFile(fp, filename, enc, + Py_single_input, ps1, ps2, + flags, &errcode, arena); + Py_XDECREF(v); + Py_XDECREF(w); + Py_XDECREF(oenc); + if (mod == NULL) { + PyArena_Free(arena); + if (errcode == E_EOF) { + PyErr_Clear(); + return E_EOF; + } + PyErr_Print(); + return -1; + } + m = PyImport_AddModule("__main__"); + if (m == NULL) { + PyArena_Free(arena); + return -1; + } + d = PyModule_GetDict(m); + v = run_mod(mod, filename, d, d, flags, arena); + PyArena_Free(arena); + flush_io(); + if (v == NULL) { + PyErr_Print(); + return -1; + } + Py_DECREF(v); + return 0; } /* Check whether a file maybe a pyc file: Look at the extension, @@ -1100,739 +1100,739 @@ static int maybe_pyc_file(FILE *fp, const char* filename, const char* ext, int closeit) { - if (strcmp(ext, ".pyc") == 0 || strcmp(ext, ".pyo") == 0) - return 1; + if (strcmp(ext, ".pyc") == 0 || strcmp(ext, ".pyo") == 0) + return 1; - /* Only look into the file if we are allowed to close it, since - it then should also be seekable. */ - if (closeit) { - /* Read only two bytes of the magic. If the file was opened in - text mode, the bytes 3 and 4 of the magic (\r\n) might not - be read as they are on disk. */ - unsigned int halfmagic = PyImport_GetMagicNumber() & 0xFFFF; - unsigned char buf[2]; - /* Mess: In case of -x, the stream is NOT at its start now, - and ungetc() was used to push back the first newline, - which makes the current stream position formally undefined, - and a x-platform nightmare. - Unfortunately, we have no direct way to know whether -x - was specified. So we use a terrible hack: if the current - stream position is not 0, we assume -x was specified, and - give up. Bug 132850 on SourceForge spells out the - hopelessness of trying anything else (fseek and ftell - don't work predictably x-platform for text-mode files). - */ - int ispyc = 0; - if (ftell(fp) == 0) { - if (fread(buf, 1, 2, fp) == 2 && - ((unsigned int)buf[1]<<8 | buf[0]) == halfmagic) - ispyc = 1; - rewind(fp); - } - return ispyc; - } - return 0; + /* Only look into the file if we are allowed to close it, since + it then should also be seekable. */ + if (closeit) { + /* Read only two bytes of the magic. If the file was opened in + text mode, the bytes 3 and 4 of the magic (\r\n) might not + be read as they are on disk. */ + unsigned int halfmagic = PyImport_GetMagicNumber() & 0xFFFF; + unsigned char buf[2]; + /* Mess: In case of -x, the stream is NOT at its start now, + and ungetc() was used to push back the first newline, + which makes the current stream position formally undefined, + and a x-platform nightmare. + Unfortunately, we have no direct way to know whether -x + was specified. So we use a terrible hack: if the current + stream position is not 0, we assume -x was specified, and + give up. Bug 132850 on SourceForge spells out the + hopelessness of trying anything else (fseek and ftell + don't work predictably x-platform for text-mode files). + */ + int ispyc = 0; + if (ftell(fp) == 0) { + if (fread(buf, 1, 2, fp) == 2 && + ((unsigned int)buf[1]<<8 | buf[0]) == halfmagic) + ispyc = 1; + rewind(fp); + } + return ispyc; + } + return 0; } int PyRun_SimpleFileExFlags(FILE *fp, const char *filename, int closeit, - PyCompilerFlags *flags) + PyCompilerFlags *flags) { - PyObject *m, *d, *v; - const char *ext; - int set_file_name = 0, ret, len; - - m = PyImport_AddModule("__main__"); - if (m == NULL) - return -1; - d = PyModule_GetDict(m); - if (PyDict_GetItemString(d, "__file__") == NULL) { - PyObject *f; - f = PyUnicode_DecodeFSDefault(filename); - if (f == NULL) - return -1; - if (PyDict_SetItemString(d, "__file__", f) < 0) { - Py_DECREF(f); - return -1; - } - if (PyDict_SetItemString(d, "__cached__", Py_None) < 0) - return -1; - set_file_name = 1; - Py_DECREF(f); - } - len = strlen(filename); - ext = filename + len - (len > 4 ? 4 : 0); - if (maybe_pyc_file(fp, filename, ext, closeit)) { - /* Try to run a pyc file. First, re-open in binary */ - if (closeit) - fclose(fp); - if ((fp = fopen(filename, "rb")) == NULL) { - fprintf(stderr, "python: Can't reopen .pyc file\n"); - ret = -1; - goto done; - } - /* Turn on optimization if a .pyo file is given */ - if (strcmp(ext, ".pyo") == 0) - Py_OptimizeFlag = 1; - v = run_pyc_file(fp, filename, d, d, flags); - } else { - v = PyRun_FileExFlags(fp, filename, Py_file_input, d, d, - closeit, flags); - } - flush_io(); - if (v == NULL) { - PyErr_Print(); - ret = -1; - goto done; - } - Py_DECREF(v); - ret = 0; + PyObject *m, *d, *v; + const char *ext; + int set_file_name = 0, ret, len; + + m = PyImport_AddModule("__main__"); + if (m == NULL) + return -1; + d = PyModule_GetDict(m); + if (PyDict_GetItemString(d, "__file__") == NULL) { + PyObject *f; + f = PyUnicode_DecodeFSDefault(filename); + if (f == NULL) + return -1; + if (PyDict_SetItemString(d, "__file__", f) < 0) { + Py_DECREF(f); + return -1; + } + if (PyDict_SetItemString(d, "__cached__", Py_None) < 0) + return -1; + set_file_name = 1; + Py_DECREF(f); + } + len = strlen(filename); + ext = filename + len - (len > 4 ? 4 : 0); + if (maybe_pyc_file(fp, filename, ext, closeit)) { + /* Try to run a pyc file. First, re-open in binary */ + if (closeit) + fclose(fp); + if ((fp = fopen(filename, "rb")) == NULL) { + fprintf(stderr, "python: Can't reopen .pyc file\n"); + ret = -1; + goto done; + } + /* Turn on optimization if a .pyo file is given */ + if (strcmp(ext, ".pyo") == 0) + Py_OptimizeFlag = 1; + v = run_pyc_file(fp, filename, d, d, flags); + } else { + v = PyRun_FileExFlags(fp, filename, Py_file_input, d, d, + closeit, flags); + } + flush_io(); + if (v == NULL) { + PyErr_Print(); + ret = -1; + goto done; + } + Py_DECREF(v); + ret = 0; done: - if (set_file_name && PyDict_DelItemString(d, "__file__")) - PyErr_Clear(); - return ret; + if (set_file_name && PyDict_DelItemString(d, "__file__")) + PyErr_Clear(); + return ret; } int PyRun_SimpleStringFlags(const char *command, PyCompilerFlags *flags) { - PyObject *m, *d, *v; - m = PyImport_AddModule("__main__"); - if (m == NULL) - return -1; - d = PyModule_GetDict(m); - v = PyRun_StringFlags(command, Py_file_input, d, d, flags); - if (v == NULL) { - PyErr_Print(); - return -1; - } - Py_DECREF(v); - return 0; + PyObject *m, *d, *v; + m = PyImport_AddModule("__main__"); + if (m == NULL) + return -1; + d = PyModule_GetDict(m); + v = PyRun_StringFlags(command, Py_file_input, d, d, flags); + if (v == NULL) { + PyErr_Print(); + return -1; + } + Py_DECREF(v); + return 0; } static int parse_syntax_error(PyObject *err, PyObject **message, const char **filename, - int *lineno, int *offset, const char **text) + int *lineno, int *offset, const char **text) { - long hold; - PyObject *v; + long hold; + PyObject *v; - /* old style errors */ - if (PyTuple_Check(err)) - return PyArg_ParseTuple(err, "O(ziiz)", message, filename, - lineno, offset, text); - - /* new style errors. `err' is an instance */ - - if (! (v = PyObject_GetAttrString(err, "msg"))) - goto finally; - *message = v; - - if (!(v = PyObject_GetAttrString(err, "filename"))) - goto finally; - if (v == Py_None) - *filename = NULL; - else if (! (*filename = _PyUnicode_AsString(v))) - goto finally; - - Py_DECREF(v); - if (!(v = PyObject_GetAttrString(err, "lineno"))) - goto finally; - hold = PyLong_AsLong(v); - Py_DECREF(v); - v = NULL; - if (hold < 0 && PyErr_Occurred()) - goto finally; - *lineno = (int)hold; - - if (!(v = PyObject_GetAttrString(err, "offset"))) - goto finally; - if (v == Py_None) { - *offset = -1; - Py_DECREF(v); - v = NULL; - } else { - hold = PyLong_AsLong(v); - Py_DECREF(v); - v = NULL; - if (hold < 0 && PyErr_Occurred()) - goto finally; - *offset = (int)hold; - } - - if (!(v = PyObject_GetAttrString(err, "text"))) - goto finally; - if (v == Py_None) - *text = NULL; - else if (!PyUnicode_Check(v) || - !(*text = _PyUnicode_AsString(v))) - goto finally; - Py_DECREF(v); - return 1; + /* old style errors */ + if (PyTuple_Check(err)) + return PyArg_ParseTuple(err, "O(ziiz)", message, filename, + lineno, offset, text); + + /* new style errors. `err' is an instance */ + + if (! (v = PyObject_GetAttrString(err, "msg"))) + goto finally; + *message = v; + + if (!(v = PyObject_GetAttrString(err, "filename"))) + goto finally; + if (v == Py_None) + *filename = NULL; + else if (! (*filename = _PyUnicode_AsString(v))) + goto finally; + + Py_DECREF(v); + if (!(v = PyObject_GetAttrString(err, "lineno"))) + goto finally; + hold = PyLong_AsLong(v); + Py_DECREF(v); + v = NULL; + if (hold < 0 && PyErr_Occurred()) + goto finally; + *lineno = (int)hold; + + if (!(v = PyObject_GetAttrString(err, "offset"))) + goto finally; + if (v == Py_None) { + *offset = -1; + Py_DECREF(v); + v = NULL; + } else { + hold = PyLong_AsLong(v); + Py_DECREF(v); + v = NULL; + if (hold < 0 && PyErr_Occurred()) + goto finally; + *offset = (int)hold; + } + + if (!(v = PyObject_GetAttrString(err, "text"))) + goto finally; + if (v == Py_None) + *text = NULL; + else if (!PyUnicode_Check(v) || + !(*text = _PyUnicode_AsString(v))) + goto finally; + Py_DECREF(v); + return 1; finally: - Py_XDECREF(v); - return 0; + Py_XDECREF(v); + return 0; } void PyErr_Print(void) { - PyErr_PrintEx(1); + PyErr_PrintEx(1); } static void print_error_text(PyObject *f, int offset, const char *text) { - char *nl; - if (offset >= 0) { - if (offset > 0 && offset == (int)strlen(text)) - offset--; - for (;;) { - nl = strchr(text, '\n'); - if (nl == NULL || nl-text >= offset) - break; - offset -= (int)(nl+1-text); - text = nl+1; - } - while (*text == ' ' || *text == '\t') { - text++; - offset--; - } - } - PyFile_WriteString(" ", f); - PyFile_WriteString(text, f); - if (*text == '\0' || text[strlen(text)-1] != '\n') - PyFile_WriteString("\n", f); - if (offset == -1) - return; - PyFile_WriteString(" ", f); - offset--; - while (offset > 0) { - PyFile_WriteString(" ", f); - offset--; - } - PyFile_WriteString("^\n", f); + char *nl; + if (offset >= 0) { + if (offset > 0 && offset == (int)strlen(text)) + offset--; + for (;;) { + nl = strchr(text, '\n'); + if (nl == NULL || nl-text >= offset) + break; + offset -= (int)(nl+1-text); + text = nl+1; + } + while (*text == ' ' || *text == '\t') { + text++; + offset--; + } + } + PyFile_WriteString(" ", f); + PyFile_WriteString(text, f); + if (*text == '\0' || text[strlen(text)-1] != '\n') + PyFile_WriteString("\n", f); + if (offset == -1) + return; + PyFile_WriteString(" ", f); + offset--; + while (offset > 0) { + PyFile_WriteString(" ", f); + offset--; + } + PyFile_WriteString("^\n", f); } static void handle_system_exit(void) { - PyObject *exception, *value, *tb; - int exitcode = 0; + PyObject *exception, *value, *tb; + int exitcode = 0; - if (Py_InspectFlag) - /* Don't exit if -i flag was given. This flag is set to 0 - * when entering interactive mode for inspecting. */ - return; - - PyErr_Fetch(&exception, &value, &tb); - fflush(stdout); - if (value == NULL || value == Py_None) - goto done; - if (PyExceptionInstance_Check(value)) { - /* The error code should be in the `code' attribute. */ - PyObject *code = PyObject_GetAttrString(value, "code"); - if (code) { - Py_DECREF(value); - value = code; - if (value == Py_None) - goto done; - } - /* If we failed to dig out the 'code' attribute, - just let the else clause below print the error. */ - } - if (PyLong_Check(value)) - exitcode = (int)PyLong_AsLong(value); - else { - PyObject_Print(value, stderr, Py_PRINT_RAW); - PySys_WriteStderr("\n"); - exitcode = 1; - } + if (Py_InspectFlag) + /* Don't exit if -i flag was given. This flag is set to 0 + * when entering interactive mode for inspecting. */ + return; + + PyErr_Fetch(&exception, &value, &tb); + fflush(stdout); + if (value == NULL || value == Py_None) + goto done; + if (PyExceptionInstance_Check(value)) { + /* The error code should be in the `code' attribute. */ + PyObject *code = PyObject_GetAttrString(value, "code"); + if (code) { + Py_DECREF(value); + value = code; + if (value == Py_None) + goto done; + } + /* If we failed to dig out the 'code' attribute, + just let the else clause below print the error. */ + } + if (PyLong_Check(value)) + exitcode = (int)PyLong_AsLong(value); + else { + PyObject_Print(value, stderr, Py_PRINT_RAW); + PySys_WriteStderr("\n"); + exitcode = 1; + } done: - /* Restore and clear the exception info, in order to properly decref - * the exception, value, and traceback. If we just exit instead, - * these leak, which confuses PYTHONDUMPREFS output, and may prevent - * some finalizers from running. - */ - PyErr_Restore(exception, value, tb); - PyErr_Clear(); - Py_Exit(exitcode); - /* NOTREACHED */ + /* Restore and clear the exception info, in order to properly decref + * the exception, value, and traceback. If we just exit instead, + * these leak, which confuses PYTHONDUMPREFS output, and may prevent + * some finalizers from running. + */ + PyErr_Restore(exception, value, tb); + PyErr_Clear(); + Py_Exit(exitcode); + /* NOTREACHED */ } void PyErr_PrintEx(int set_sys_last_vars) { - PyObject *exception, *v, *tb, *hook; + PyObject *exception, *v, *tb, *hook; - if (PyErr_ExceptionMatches(PyExc_SystemExit)) { - handle_system_exit(); - } - PyErr_Fetch(&exception, &v, &tb); - if (exception == NULL) - return; - PyErr_NormalizeException(&exception, &v, &tb); - if (tb == NULL) { - tb = Py_None; - Py_INCREF(tb); - } - PyException_SetTraceback(v, tb); - if (exception == NULL) - return; - /* Now we know v != NULL too */ - if (set_sys_last_vars) { - PySys_SetObject("last_type", exception); - PySys_SetObject("last_value", v); - PySys_SetObject("last_traceback", tb); - } - hook = PySys_GetObject("excepthook"); - if (hook) { - PyObject *args = PyTuple_Pack(3, exception, v, tb); - PyObject *result = PyEval_CallObject(hook, args); - if (result == NULL) { - PyObject *exception2, *v2, *tb2; - if (PyErr_ExceptionMatches(PyExc_SystemExit)) { - handle_system_exit(); - } - PyErr_Fetch(&exception2, &v2, &tb2); - PyErr_NormalizeException(&exception2, &v2, &tb2); - /* It should not be possible for exception2 or v2 - to be NULL. However PyErr_Display() can't - tolerate NULLs, so just be safe. */ - if (exception2 == NULL) { - exception2 = Py_None; - Py_INCREF(exception2); - } - if (v2 == NULL) { - v2 = Py_None; - Py_INCREF(v2); - } - fflush(stdout); - PySys_WriteStderr("Error in sys.excepthook:\n"); - PyErr_Display(exception2, v2, tb2); - PySys_WriteStderr("\nOriginal exception was:\n"); - PyErr_Display(exception, v, tb); - Py_DECREF(exception2); - Py_DECREF(v2); - Py_XDECREF(tb2); - } - Py_XDECREF(result); - Py_XDECREF(args); - } else { - PySys_WriteStderr("sys.excepthook is missing\n"); - PyErr_Display(exception, v, tb); - } - Py_XDECREF(exception); - Py_XDECREF(v); - Py_XDECREF(tb); + if (PyErr_ExceptionMatches(PyExc_SystemExit)) { + handle_system_exit(); + } + PyErr_Fetch(&exception, &v, &tb); + if (exception == NULL) + return; + PyErr_NormalizeException(&exception, &v, &tb); + if (tb == NULL) { + tb = Py_None; + Py_INCREF(tb); + } + PyException_SetTraceback(v, tb); + if (exception == NULL) + return; + /* Now we know v != NULL too */ + if (set_sys_last_vars) { + PySys_SetObject("last_type", exception); + PySys_SetObject("last_value", v); + PySys_SetObject("last_traceback", tb); + } + hook = PySys_GetObject("excepthook"); + if (hook) { + PyObject *args = PyTuple_Pack(3, exception, v, tb); + PyObject *result = PyEval_CallObject(hook, args); + if (result == NULL) { + PyObject *exception2, *v2, *tb2; + if (PyErr_ExceptionMatches(PyExc_SystemExit)) { + handle_system_exit(); + } + PyErr_Fetch(&exception2, &v2, &tb2); + PyErr_NormalizeException(&exception2, &v2, &tb2); + /* It should not be possible for exception2 or v2 + to be NULL. However PyErr_Display() can't + tolerate NULLs, so just be safe. */ + if (exception2 == NULL) { + exception2 = Py_None; + Py_INCREF(exception2); + } + if (v2 == NULL) { + v2 = Py_None; + Py_INCREF(v2); + } + fflush(stdout); + PySys_WriteStderr("Error in sys.excepthook:\n"); + PyErr_Display(exception2, v2, tb2); + PySys_WriteStderr("\nOriginal exception was:\n"); + PyErr_Display(exception, v, tb); + Py_DECREF(exception2); + Py_DECREF(v2); + Py_XDECREF(tb2); + } + Py_XDECREF(result); + Py_XDECREF(args); + } else { + PySys_WriteStderr("sys.excepthook is missing\n"); + PyErr_Display(exception, v, tb); + } + Py_XDECREF(exception); + Py_XDECREF(v); + Py_XDECREF(tb); } static void print_exception(PyObject *f, PyObject *value) { - int err = 0; - PyObject *type, *tb; + int err = 0; + PyObject *type, *tb; - if (!PyExceptionInstance_Check(value)) { - PyFile_WriteString("TypeError: print_exception(): Exception expected for value, ", f); - PyFile_WriteString(Py_TYPE(value)->tp_name, f); - PyFile_WriteString(" found\n", f); - return; - } - - Py_INCREF(value); - fflush(stdout); - type = (PyObject *) Py_TYPE(value); - tb = PyException_GetTraceback(value); - if (tb && tb != Py_None) - err = PyTraceBack_Print(tb, f); - if (err == 0 && - PyObject_HasAttrString(value, "print_file_and_line")) - { - PyObject *message; - const char *filename, *text; - int lineno, offset; - if (!parse_syntax_error(value, &message, &filename, - &lineno, &offset, &text)) - PyErr_Clear(); - else { - char buf[10]; - PyFile_WriteString(" File \"", f); - if (filename == NULL) - PyFile_WriteString("", f); - else - PyFile_WriteString(filename, f); - PyFile_WriteString("\", line ", f); - PyOS_snprintf(buf, sizeof(buf), "%d", lineno); - PyFile_WriteString(buf, f); - PyFile_WriteString("\n", f); - if (text != NULL) - print_error_text(f, offset, text); - Py_DECREF(value); - value = message; - /* Can't be bothered to check all those - PyFile_WriteString() calls */ - if (PyErr_Occurred()) - err = -1; - } - } - if (err) { - /* Don't do anything else */ - } - else { - PyObject* moduleName; - char* className; - assert(PyExceptionClass_Check(type)); - className = PyExceptionClass_Name(type); - if (className != NULL) { - char *dot = strrchr(className, '.'); - if (dot != NULL) - className = dot+1; - } - - moduleName = PyObject_GetAttrString(type, "__module__"); - if (moduleName == NULL || !PyUnicode_Check(moduleName)) - { - Py_DECREF(moduleName); - err = PyFile_WriteString("", f); - } - else { - char* modstr = _PyUnicode_AsString(moduleName); - if (modstr && strcmp(modstr, "builtins")) - { - err = PyFile_WriteString(modstr, f); - err += PyFile_WriteString(".", f); - } - Py_DECREF(moduleName); - } - if (err == 0) { - if (className == NULL) - err = PyFile_WriteString("", f); - else - err = PyFile_WriteString(className, f); - } - } - if (err == 0 && (value != Py_None)) { - PyObject *s = PyObject_Str(value); - /* only print colon if the str() of the - object is not the empty string - */ - if (s == NULL) - err = -1; - else if (!PyUnicode_Check(s) || - PyUnicode_GetSize(s) != 0) - err = PyFile_WriteString(": ", f); - if (err == 0) - err = PyFile_WriteObject(s, f, Py_PRINT_RAW); - Py_XDECREF(s); - } - /* try to write a newline in any case */ - err += PyFile_WriteString("\n", f); - Py_XDECREF(tb); - Py_DECREF(value); - /* If an error happened here, don't show it. - XXX This is wrong, but too many callers rely on this behavior. */ - if (err != 0) - PyErr_Clear(); + if (!PyExceptionInstance_Check(value)) { + PyFile_WriteString("TypeError: print_exception(): Exception expected for value, ", f); + PyFile_WriteString(Py_TYPE(value)->tp_name, f); + PyFile_WriteString(" found\n", f); + return; + } + + Py_INCREF(value); + fflush(stdout); + type = (PyObject *) Py_TYPE(value); + tb = PyException_GetTraceback(value); + if (tb && tb != Py_None) + err = PyTraceBack_Print(tb, f); + if (err == 0 && + PyObject_HasAttrString(value, "print_file_and_line")) + { + PyObject *message; + const char *filename, *text; + int lineno, offset; + if (!parse_syntax_error(value, &message, &filename, + &lineno, &offset, &text)) + PyErr_Clear(); + else { + char buf[10]; + PyFile_WriteString(" File \"", f); + if (filename == NULL) + PyFile_WriteString("", f); + else + PyFile_WriteString(filename, f); + PyFile_WriteString("\", line ", f); + PyOS_snprintf(buf, sizeof(buf), "%d", lineno); + PyFile_WriteString(buf, f); + PyFile_WriteString("\n", f); + if (text != NULL) + print_error_text(f, offset, text); + Py_DECREF(value); + value = message; + /* Can't be bothered to check all those + PyFile_WriteString() calls */ + if (PyErr_Occurred()) + err = -1; + } + } + if (err) { + /* Don't do anything else */ + } + else { + PyObject* moduleName; + char* className; + assert(PyExceptionClass_Check(type)); + className = PyExceptionClass_Name(type); + if (className != NULL) { + char *dot = strrchr(className, '.'); + if (dot != NULL) + className = dot+1; + } + + moduleName = PyObject_GetAttrString(type, "__module__"); + if (moduleName == NULL || !PyUnicode_Check(moduleName)) + { + Py_DECREF(moduleName); + err = PyFile_WriteString("", f); + } + else { + char* modstr = _PyUnicode_AsString(moduleName); + if (modstr && strcmp(modstr, "builtins")) + { + err = PyFile_WriteString(modstr, f); + err += PyFile_WriteString(".", f); + } + Py_DECREF(moduleName); + } + if (err == 0) { + if (className == NULL) + err = PyFile_WriteString("", f); + else + err = PyFile_WriteString(className, f); + } + } + if (err == 0 && (value != Py_None)) { + PyObject *s = PyObject_Str(value); + /* only print colon if the str() of the + object is not the empty string + */ + if (s == NULL) + err = -1; + else if (!PyUnicode_Check(s) || + PyUnicode_GetSize(s) != 0) + err = PyFile_WriteString(": ", f); + if (err == 0) + err = PyFile_WriteObject(s, f, Py_PRINT_RAW); + Py_XDECREF(s); + } + /* try to write a newline in any case */ + err += PyFile_WriteString("\n", f); + Py_XDECREF(tb); + Py_DECREF(value); + /* If an error happened here, don't show it. + XXX This is wrong, but too many callers rely on this behavior. */ + if (err != 0) + PyErr_Clear(); } static const char *cause_message = - "\nThe above exception was the direct cause " - "of the following exception:\n\n"; + "\nThe above exception was the direct cause " + "of the following exception:\n\n"; static const char *context_message = - "\nDuring handling of the above exception, " - "another exception occurred:\n\n"; + "\nDuring handling of the above exception, " + "another exception occurred:\n\n"; static void print_exception_recursive(PyObject *f, PyObject *value, PyObject *seen) { - int err = 0, res; - PyObject *cause, *context; + int err = 0, res; + PyObject *cause, *context; - if (seen != NULL) { - /* Exception chaining */ - if (PySet_Add(seen, value) == -1) - PyErr_Clear(); - else if (PyExceptionInstance_Check(value)) { - cause = PyException_GetCause(value); - context = PyException_GetContext(value); - if (cause) { - res = PySet_Contains(seen, cause); - if (res == -1) - PyErr_Clear(); - if (res == 0) { - print_exception_recursive( - f, cause, seen); - err |= PyFile_WriteString( - cause_message, f); - } - } - else if (context) { - res = PySet_Contains(seen, context); - if (res == -1) - PyErr_Clear(); - if (res == 0) { - print_exception_recursive( - f, context, seen); - err |= PyFile_WriteString( - context_message, f); - } - } - Py_XDECREF(context); - Py_XDECREF(cause); - } - } - print_exception(f, value); - if (err != 0) - PyErr_Clear(); + if (seen != NULL) { + /* Exception chaining */ + if (PySet_Add(seen, value) == -1) + PyErr_Clear(); + else if (PyExceptionInstance_Check(value)) { + cause = PyException_GetCause(value); + context = PyException_GetContext(value); + if (cause) { + res = PySet_Contains(seen, cause); + if (res == -1) + PyErr_Clear(); + if (res == 0) { + print_exception_recursive( + f, cause, seen); + err |= PyFile_WriteString( + cause_message, f); + } + } + else if (context) { + res = PySet_Contains(seen, context); + if (res == -1) + PyErr_Clear(); + if (res == 0) { + print_exception_recursive( + f, context, seen); + err |= PyFile_WriteString( + context_message, f); + } + } + Py_XDECREF(context); + Py_XDECREF(cause); + } + } + print_exception(f, value); + if (err != 0) + PyErr_Clear(); } void PyErr_Display(PyObject *exception, PyObject *value, PyObject *tb) { - PyObject *seen; - PyObject *f = PySys_GetObject("stderr"); - if (f == Py_None) { - /* pass */ - } - else if (f == NULL) { - _PyObject_Dump(value); - fprintf(stderr, "lost sys.stderr\n"); - } - else { - /* We choose to ignore seen being possibly NULL, and report - at least the main exception (it could be a MemoryError). - */ - seen = PySet_New(NULL); - if (seen == NULL) - PyErr_Clear(); - print_exception_recursive(f, value, seen); - Py_XDECREF(seen); - } + PyObject *seen; + PyObject *f = PySys_GetObject("stderr"); + if (f == Py_None) { + /* pass */ + } + else if (f == NULL) { + _PyObject_Dump(value); + fprintf(stderr, "lost sys.stderr\n"); + } + else { + /* We choose to ignore seen being possibly NULL, and report + at least the main exception (it could be a MemoryError). + */ + seen = PySet_New(NULL); + if (seen == NULL) + PyErr_Clear(); + print_exception_recursive(f, value, seen); + Py_XDECREF(seen); + } } PyObject * PyRun_StringFlags(const char *str, int start, PyObject *globals, - PyObject *locals, PyCompilerFlags *flags) + PyObject *locals, PyCompilerFlags *flags) { - PyObject *ret = NULL; - mod_ty mod; - PyArena *arena = PyArena_New(); - if (arena == NULL) - return NULL; - - mod = PyParser_ASTFromString(str, "", start, flags, arena); - if (mod != NULL) - ret = run_mod(mod, "", globals, locals, flags, arena); - PyArena_Free(arena); - return ret; + PyObject *ret = NULL; + mod_ty mod; + PyArena *arena = PyArena_New(); + if (arena == NULL) + return NULL; + + mod = PyParser_ASTFromString(str, "", start, flags, arena); + if (mod != NULL) + ret = run_mod(mod, "", globals, locals, flags, arena); + PyArena_Free(arena); + return ret; } PyObject * PyRun_FileExFlags(FILE *fp, const char *filename, int start, PyObject *globals, - PyObject *locals, int closeit, PyCompilerFlags *flags) + PyObject *locals, int closeit, PyCompilerFlags *flags) { - PyObject *ret; - mod_ty mod; - PyArena *arena = PyArena_New(); - if (arena == NULL) - return NULL; - - mod = PyParser_ASTFromFile(fp, filename, NULL, start, 0, 0, - flags, NULL, arena); - if (closeit) - fclose(fp); - if (mod == NULL) { - PyArena_Free(arena); - return NULL; - } - ret = run_mod(mod, filename, globals, locals, flags, arena); - PyArena_Free(arena); - return ret; + PyObject *ret; + mod_ty mod; + PyArena *arena = PyArena_New(); + if (arena == NULL) + return NULL; + + mod = PyParser_ASTFromFile(fp, filename, NULL, start, 0, 0, + flags, NULL, arena); + if (closeit) + fclose(fp); + if (mod == NULL) { + PyArena_Free(arena); + return NULL; + } + ret = run_mod(mod, filename, globals, locals, flags, arena); + PyArena_Free(arena); + return ret; } static void flush_io(void) { - PyObject *f, *r; - PyObject *type, *value, *traceback; + PyObject *f, *r; + PyObject *type, *value, *traceback; - /* Save the current exception */ - PyErr_Fetch(&type, &value, &traceback); + /* Save the current exception */ + PyErr_Fetch(&type, &value, &traceback); - f = PySys_GetObject("stderr"); - if (f != NULL) { - r = PyObject_CallMethod(f, "flush", ""); - if (r) - Py_DECREF(r); - else - PyErr_Clear(); - } - f = PySys_GetObject("stdout"); - if (f != NULL) { - r = PyObject_CallMethod(f, "flush", ""); - if (r) - Py_DECREF(r); - else - PyErr_Clear(); - } + f = PySys_GetObject("stderr"); + if (f != NULL) { + r = PyObject_CallMethod(f, "flush", ""); + if (r) + Py_DECREF(r); + else + PyErr_Clear(); + } + f = PySys_GetObject("stdout"); + if (f != NULL) { + r = PyObject_CallMethod(f, "flush", ""); + if (r) + Py_DECREF(r); + else + PyErr_Clear(); + } - PyErr_Restore(type, value, traceback); + PyErr_Restore(type, value, traceback); } static PyObject * run_mod(mod_ty mod, const char *filename, PyObject *globals, PyObject *locals, - PyCompilerFlags *flags, PyArena *arena) + PyCompilerFlags *flags, PyArena *arena) { - PyCodeObject *co; - PyObject *v; - co = PyAST_Compile(mod, filename, flags, arena); - if (co == NULL) - return NULL; - v = PyEval_EvalCode(co, globals, locals); - Py_DECREF(co); - return v; + PyCodeObject *co; + PyObject *v; + co = PyAST_Compile(mod, filename, flags, arena); + if (co == NULL) + return NULL; + v = PyEval_EvalCode(co, globals, locals); + Py_DECREF(co); + return v; } static PyObject * run_pyc_file(FILE *fp, const char *filename, PyObject *globals, - PyObject *locals, PyCompilerFlags *flags) + PyObject *locals, PyCompilerFlags *flags) { - PyCodeObject *co; - PyObject *v; - long magic; - long PyImport_GetMagicNumber(void); - - magic = PyMarshal_ReadLongFromFile(fp); - if (magic != PyImport_GetMagicNumber()) { - PyErr_SetString(PyExc_RuntimeError, - "Bad magic number in .pyc file"); - return NULL; - } - (void) PyMarshal_ReadLongFromFile(fp); - v = PyMarshal_ReadLastObjectFromFile(fp); - fclose(fp); - if (v == NULL || !PyCode_Check(v)) { - Py_XDECREF(v); - PyErr_SetString(PyExc_RuntimeError, - "Bad code object in .pyc file"); - return NULL; - } - co = (PyCodeObject *)v; - v = PyEval_EvalCode(co, globals, locals); - if (v && flags) - flags->cf_flags |= (co->co_flags & PyCF_MASK); - Py_DECREF(co); - return v; + PyCodeObject *co; + PyObject *v; + long magic; + long PyImport_GetMagicNumber(void); + + magic = PyMarshal_ReadLongFromFile(fp); + if (magic != PyImport_GetMagicNumber()) { + PyErr_SetString(PyExc_RuntimeError, + "Bad magic number in .pyc file"); + return NULL; + } + (void) PyMarshal_ReadLongFromFile(fp); + v = PyMarshal_ReadLastObjectFromFile(fp); + fclose(fp); + if (v == NULL || !PyCode_Check(v)) { + Py_XDECREF(v); + PyErr_SetString(PyExc_RuntimeError, + "Bad code object in .pyc file"); + return NULL; + } + co = (PyCodeObject *)v; + v = PyEval_EvalCode(co, globals, locals); + if (v && flags) + flags->cf_flags |= (co->co_flags & PyCF_MASK); + Py_DECREF(co); + return v; } PyObject * Py_CompileStringFlags(const char *str, const char *filename, int start, - PyCompilerFlags *flags) + PyCompilerFlags *flags) { - PyCodeObject *co; - mod_ty mod; - PyArena *arena = PyArena_New(); - if (arena == NULL) - return NULL; - - mod = PyParser_ASTFromString(str, filename, start, flags, arena); - if (mod == NULL) { - PyArena_Free(arena); - return NULL; - } - if (flags && (flags->cf_flags & PyCF_ONLY_AST)) { - PyObject *result = PyAST_mod2obj(mod); - PyArena_Free(arena); - return result; - } - co = PyAST_Compile(mod, filename, flags, arena); - PyArena_Free(arena); - return (PyObject *)co; + PyCodeObject *co; + mod_ty mod; + PyArena *arena = PyArena_New(); + if (arena == NULL) + return NULL; + + mod = PyParser_ASTFromString(str, filename, start, flags, arena); + if (mod == NULL) { + PyArena_Free(arena); + return NULL; + } + if (flags && (flags->cf_flags & PyCF_ONLY_AST)) { + PyObject *result = PyAST_mod2obj(mod); + PyArena_Free(arena); + return result; + } + co = PyAST_Compile(mod, filename, flags, arena); + PyArena_Free(arena); + return (PyObject *)co; } struct symtable * Py_SymtableString(const char *str, const char *filename, int start) { - struct symtable *st; - mod_ty mod; - PyCompilerFlags flags; - PyArena *arena = PyArena_New(); - if (arena == NULL) - return NULL; - - flags.cf_flags = 0; - mod = PyParser_ASTFromString(str, filename, start, &flags, arena); - if (mod == NULL) { - PyArena_Free(arena); - return NULL; - } - st = PySymtable_Build(mod, filename, 0); - PyArena_Free(arena); - return st; + struct symtable *st; + mod_ty mod; + PyCompilerFlags flags; + PyArena *arena = PyArena_New(); + if (arena == NULL) + return NULL; + + flags.cf_flags = 0; + mod = PyParser_ASTFromString(str, filename, start, &flags, arena); + if (mod == NULL) { + PyArena_Free(arena); + return NULL; + } + st = PySymtable_Build(mod, filename, 0); + PyArena_Free(arena); + return st; } /* Preferred access to parser is through AST. */ mod_ty PyParser_ASTFromString(const char *s, const char *filename, int start, - PyCompilerFlags *flags, PyArena *arena) + PyCompilerFlags *flags, PyArena *arena) { - mod_ty mod; - PyCompilerFlags localflags; - perrdetail err; - int iflags = PARSER_FLAGS(flags); - - node *n = PyParser_ParseStringFlagsFilenameEx(s, filename, - &_PyParser_Grammar, start, &err, - &iflags); - if (flags == NULL) { - localflags.cf_flags = 0; - flags = &localflags; - } - if (n) { - flags->cf_flags |= iflags & PyCF_MASK; - mod = PyAST_FromNode(n, flags, filename, arena); - PyNode_Free(n); - return mod; - } - else { - err_input(&err); - return NULL; - } + mod_ty mod; + PyCompilerFlags localflags; + perrdetail err; + int iflags = PARSER_FLAGS(flags); + + node *n = PyParser_ParseStringFlagsFilenameEx(s, filename, + &_PyParser_Grammar, start, &err, + &iflags); + if (flags == NULL) { + localflags.cf_flags = 0; + flags = &localflags; + } + if (n) { + flags->cf_flags |= iflags & PyCF_MASK; + mod = PyAST_FromNode(n, flags, filename, arena); + PyNode_Free(n); + return mod; + } + else { + err_input(&err); + return NULL; + } } mod_ty PyParser_ASTFromFile(FILE *fp, const char *filename, const char* enc, - int start, char *ps1, - char *ps2, PyCompilerFlags *flags, int *errcode, - PyArena *arena) -{ - mod_ty mod; - PyCompilerFlags localflags; - perrdetail err; - int iflags = PARSER_FLAGS(flags); - - node *n = PyParser_ParseFileFlagsEx(fp, filename, enc, - &_PyParser_Grammar, - start, ps1, ps2, &err, &iflags); - if (flags == NULL) { - localflags.cf_flags = 0; - flags = &localflags; - } - if (n) { - flags->cf_flags |= iflags & PyCF_MASK; - mod = PyAST_FromNode(n, flags, filename, arena); - PyNode_Free(n); - return mod; - } - else { - err_input(&err); - if (errcode) - *errcode = err.error; - return NULL; - } + int start, char *ps1, + char *ps2, PyCompilerFlags *flags, int *errcode, + PyArena *arena) +{ + mod_ty mod; + PyCompilerFlags localflags; + perrdetail err; + int iflags = PARSER_FLAGS(flags); + + node *n = PyParser_ParseFileFlagsEx(fp, filename, enc, + &_PyParser_Grammar, + start, ps1, ps2, &err, &iflags); + if (flags == NULL) { + localflags.cf_flags = 0; + flags = &localflags; + } + if (n) { + flags->cf_flags |= iflags & PyCF_MASK; + mod = PyAST_FromNode(n, flags, filename, arena); + PyNode_Free(n); + return mod; + } + else { + err_input(&err); + if (errcode) + *errcode = err.error; + return NULL; + } } /* Simplified interface to parsefile -- return node or set exception */ @@ -1840,14 +1840,14 @@ node * PyParser_SimpleParseFileFlags(FILE *fp, const char *filename, int start, int flags) { - perrdetail err; - node *n = PyParser_ParseFileFlags(fp, filename, NULL, - &_PyParser_Grammar, - start, NULL, NULL, &err, flags); - if (n == NULL) - err_input(&err); + perrdetail err; + node *n = PyParser_ParseFileFlags(fp, filename, NULL, + &_PyParser_Grammar, + start, NULL, NULL, &err, flags); + if (n == NULL) + err_input(&err); - return n; + return n; } /* Simplified interface to parsestring -- return node or set exception */ @@ -1855,30 +1855,30 @@ node * PyParser_SimpleParseStringFlags(const char *str, int start, int flags) { - perrdetail err; - node *n = PyParser_ParseStringFlags(str, &_PyParser_Grammar, - start, &err, flags); - if (n == NULL) - err_input(&err); - return n; + perrdetail err; + node *n = PyParser_ParseStringFlags(str, &_PyParser_Grammar, + start, &err, flags); + if (n == NULL) + err_input(&err); + return n; } node * PyParser_SimpleParseStringFlagsFilename(const char *str, const char *filename, - int start, int flags) + int start, int flags) { - perrdetail err; - node *n = PyParser_ParseStringFlagsFilename(str, filename, - &_PyParser_Grammar, start, &err, flags); - if (n == NULL) - err_input(&err); - return n; + perrdetail err; + node *n = PyParser_ParseStringFlagsFilename(str, filename, + &_PyParser_Grammar, start, &err, flags); + if (n == NULL) + err_input(&err); + return n; } node * PyParser_SimpleParseStringFilename(const char *str, const char *filename, int start) { - return PyParser_SimpleParseStringFlagsFilename(str, filename, start, 0); + return PyParser_SimpleParseStringFlagsFilename(str, filename, start, 0); } /* May want to move a more generalized form of this to parsetok.c or @@ -1887,7 +1887,7 @@ void PyParser_SetError(perrdetail *err) { - err_input(err); + err_input(err); } /* Set the error appropriate to the given input error code (see errcode.h) */ @@ -1895,110 +1895,110 @@ static void err_input(perrdetail *err) { - PyObject *v, *w, *errtype, *errtext; - PyObject *msg_obj = NULL; - char *msg = NULL; - errtype = PyExc_SyntaxError; - switch (err->error) { - case E_ERROR: - return; - case E_SYNTAX: - errtype = PyExc_IndentationError; - if (err->expected == INDENT) - msg = "expected an indented block"; - else if (err->token == INDENT) - msg = "unexpected indent"; - else if (err->token == DEDENT) - msg = "unexpected unindent"; - else { - errtype = PyExc_SyntaxError; - msg = "invalid syntax"; - } - break; - case E_TOKEN: - msg = "invalid token"; - break; - case E_EOFS: - msg = "EOF while scanning triple-quoted string literal"; - break; - case E_EOLS: - msg = "EOL while scanning string literal"; - break; - case E_INTR: - if (!PyErr_Occurred()) - PyErr_SetNone(PyExc_KeyboardInterrupt); - goto cleanup; - case E_NOMEM: - PyErr_NoMemory(); - goto cleanup; - case E_EOF: - msg = "unexpected EOF while parsing"; - break; - case E_TABSPACE: - errtype = PyExc_TabError; - msg = "inconsistent use of tabs and spaces in indentation"; - break; - case E_OVERFLOW: - msg = "expression too long"; - break; - case E_DEDENT: - errtype = PyExc_IndentationError; - msg = "unindent does not match any outer indentation level"; - break; - case E_TOODEEP: - errtype = PyExc_IndentationError; - msg = "too many levels of indentation"; - break; - case E_DECODE: { - PyObject *type, *value, *tb; - PyErr_Fetch(&type, &value, &tb); - msg = "unknown decode error"; - if (value != NULL) - msg_obj = PyObject_Str(value); - Py_XDECREF(type); - Py_XDECREF(value); - Py_XDECREF(tb); - break; - } - case E_LINECONT: - msg = "unexpected character after line continuation character"; - break; - - case E_IDENTIFIER: - msg = "invalid character in identifier"; - break; - default: - fprintf(stderr, "error=%d\n", err->error); - msg = "unknown parsing error"; - break; - } - /* err->text may not be UTF-8 in case of decoding errors. - Explicitly convert to an object. */ - if (!err->text) { - errtext = Py_None; - Py_INCREF(Py_None); - } else { - errtext = PyUnicode_DecodeUTF8(err->text, strlen(err->text), - "replace"); - } - v = Py_BuildValue("(ziiN)", err->filename, - err->lineno, err->offset, errtext); - if (v != NULL) { - if (msg_obj) - w = Py_BuildValue("(OO)", msg_obj, v); - else - w = Py_BuildValue("(sO)", msg, v); - } else - w = NULL; - Py_XDECREF(v); - PyErr_SetObject(errtype, w); - Py_XDECREF(w); + PyObject *v, *w, *errtype, *errtext; + PyObject *msg_obj = NULL; + char *msg = NULL; + errtype = PyExc_SyntaxError; + switch (err->error) { + case E_ERROR: + return; + case E_SYNTAX: + errtype = PyExc_IndentationError; + if (err->expected == INDENT) + msg = "expected an indented block"; + else if (err->token == INDENT) + msg = "unexpected indent"; + else if (err->token == DEDENT) + msg = "unexpected unindent"; + else { + errtype = PyExc_SyntaxError; + msg = "invalid syntax"; + } + break; + case E_TOKEN: + msg = "invalid token"; + break; + case E_EOFS: + msg = "EOF while scanning triple-quoted string literal"; + break; + case E_EOLS: + msg = "EOL while scanning string literal"; + break; + case E_INTR: + if (!PyErr_Occurred()) + PyErr_SetNone(PyExc_KeyboardInterrupt); + goto cleanup; + case E_NOMEM: + PyErr_NoMemory(); + goto cleanup; + case E_EOF: + msg = "unexpected EOF while parsing"; + break; + case E_TABSPACE: + errtype = PyExc_TabError; + msg = "inconsistent use of tabs and spaces in indentation"; + break; + case E_OVERFLOW: + msg = "expression too long"; + break; + case E_DEDENT: + errtype = PyExc_IndentationError; + msg = "unindent does not match any outer indentation level"; + break; + case E_TOODEEP: + errtype = PyExc_IndentationError; + msg = "too many levels of indentation"; + break; + case E_DECODE: { + PyObject *type, *value, *tb; + PyErr_Fetch(&type, &value, &tb); + msg = "unknown decode error"; + if (value != NULL) + msg_obj = PyObject_Str(value); + Py_XDECREF(type); + Py_XDECREF(value); + Py_XDECREF(tb); + break; + } + case E_LINECONT: + msg = "unexpected character after line continuation character"; + break; + + case E_IDENTIFIER: + msg = "invalid character in identifier"; + break; + default: + fprintf(stderr, "error=%d\n", err->error); + msg = "unknown parsing error"; + break; + } + /* err->text may not be UTF-8 in case of decoding errors. + Explicitly convert to an object. */ + if (!err->text) { + errtext = Py_None; + Py_INCREF(Py_None); + } else { + errtext = PyUnicode_DecodeUTF8(err->text, strlen(err->text), + "replace"); + } + v = Py_BuildValue("(ziiN)", err->filename, + err->lineno, err->offset, errtext); + if (v != NULL) { + if (msg_obj) + w = Py_BuildValue("(OO)", msg_obj, v); + else + w = Py_BuildValue("(sO)", msg, v); + } else + w = NULL; + Py_XDECREF(v); + PyErr_SetObject(errtype, w); + Py_XDECREF(w); cleanup: - Py_XDECREF(msg_obj); - if (err->text != NULL) { - PyObject_FREE(err->text); - err->text = NULL; - } + Py_XDECREF(msg_obj); + if (err->text != NULL) { + PyObject_FREE(err->text); + err->text = NULL; + } } /* Print fatal error message and abort */ @@ -2006,32 +2006,32 @@ void Py_FatalError(const char *msg) { - fprintf(stderr, "Fatal Python error: %s\n", msg); - fflush(stderr); /* it helps in Windows debug build */ - if (PyErr_Occurred()) { - PyErr_Print(); - } + fprintf(stderr, "Fatal Python error: %s\n", msg); + fflush(stderr); /* it helps in Windows debug build */ + if (PyErr_Occurred()) { + PyErr_Print(); + } #ifdef MS_WINDOWS - { - size_t len = strlen(msg); - WCHAR* buffer; - size_t i; - - /* Convert the message to wchar_t. This uses a simple one-to-one - conversion, assuming that the this error message actually uses ASCII - only. If this ceases to be true, we will have to convert. */ - buffer = alloca( (len+1) * (sizeof *buffer)); - for( i=0; i<=len; ++i) - buffer[i] = msg[i]; - OutputDebugStringW(L"Fatal Python error: "); - OutputDebugStringW(buffer); - OutputDebugStringW(L"\n"); - } + { + size_t len = strlen(msg); + WCHAR* buffer; + size_t i; + + /* Convert the message to wchar_t. This uses a simple one-to-one + conversion, assuming that the this error message actually uses ASCII + only. If this ceases to be true, we will have to convert. */ + buffer = alloca( (len+1) * (sizeof *buffer)); + for( i=0; i<=len; ++i) + buffer[i] = msg[i]; + OutputDebugStringW(L"Fatal Python error: "); + OutputDebugStringW(buffer); + OutputDebugStringW(L"\n"); + } #ifdef _DEBUG - DebugBreak(); + DebugBreak(); #endif #endif /* MS_WINDOWS */ - abort(); + abort(); } /* Clean up and exit */ @@ -2044,17 +2044,17 @@ /* For the atexit module. */ void _Py_PyAtExit(void (*func)(void)) { - pyexitfunc = func; + pyexitfunc = func; } static void call_py_exitfuncs(void) { - if (pyexitfunc == NULL) - return; + if (pyexitfunc == NULL) + return; - (*pyexitfunc)(); - PyErr_Clear(); + (*pyexitfunc)(); + PyErr_Clear(); } /* Wait until threading._shutdown completes, provided @@ -2065,23 +2065,23 @@ wait_for_thread_shutdown(void) { #ifdef WITH_THREAD - PyObject *result; - PyThreadState *tstate = PyThreadState_GET(); - PyObject *threading = PyMapping_GetItemString(tstate->interp->modules, - "threading"); - if (threading == NULL) { - /* threading not imported */ - PyErr_Clear(); - return; - } - result = PyObject_CallMethod(threading, "_shutdown", ""); - if (result == NULL) { - PyErr_WriteUnraisable(threading); - } - else { - Py_DECREF(result); - } - Py_DECREF(threading); + PyObject *result; + PyThreadState *tstate = PyThreadState_GET(); + PyObject *threading = PyMapping_GetItemString(tstate->interp->modules, + "threading"); + if (threading == NULL) { + /* threading not imported */ + PyErr_Clear(); + return; + } + result = PyObject_CallMethod(threading, "_shutdown", ""); + if (result == NULL) { + PyErr_WriteUnraisable(threading); + } + else { + Py_DECREF(result); + } + Py_DECREF(threading); #endif } @@ -2091,43 +2091,43 @@ int Py_AtExit(void (*func)(void)) { - if (nexitfuncs >= NEXITFUNCS) - return -1; - exitfuncs[nexitfuncs++] = func; - return 0; + if (nexitfuncs >= NEXITFUNCS) + return -1; + exitfuncs[nexitfuncs++] = func; + return 0; } static void call_ll_exitfuncs(void) { - while (nexitfuncs > 0) - (*exitfuncs[--nexitfuncs])(); + while (nexitfuncs > 0) + (*exitfuncs[--nexitfuncs])(); - fflush(stdout); - fflush(stderr); + fflush(stdout); + fflush(stderr); } void Py_Exit(int sts) { - Py_Finalize(); + Py_Finalize(); - exit(sts); + exit(sts); } static void initsigs(void) { #ifdef SIGPIPE - PyOS_setsig(SIGPIPE, SIG_IGN); + PyOS_setsig(SIGPIPE, SIG_IGN); #endif #ifdef SIGXFZ - PyOS_setsig(SIGXFZ, SIG_IGN); + PyOS_setsig(SIGXFZ, SIG_IGN); #endif #ifdef SIGXFSZ - PyOS_setsig(SIGXFSZ, SIG_IGN); + PyOS_setsig(SIGXFSZ, SIG_IGN); #endif - PyOS_InitInterrupts(); /* May imply initsignal() */ + PyOS_InitInterrupts(); /* May imply initsignal() */ } @@ -2141,13 +2141,13 @@ _Py_RestoreSignals(void) { #ifdef SIGPIPE - PyOS_setsig(SIGPIPE, SIG_DFL); + PyOS_setsig(SIGPIPE, SIG_DFL); #endif #ifdef SIGXFZ - PyOS_setsig(SIGXFZ, SIG_DFL); + PyOS_setsig(SIGXFZ, SIG_DFL); #endif #ifdef SIGXFSZ - PyOS_setsig(SIGXFSZ, SIG_DFL); + PyOS_setsig(SIGXFSZ, SIG_DFL); #endif } @@ -2161,13 +2161,13 @@ int Py_FdIsInteractive(FILE *fp, const char *filename) { - if (isatty((int)fileno(fp))) - return 1; - if (!Py_InteractiveFlag) - return 0; - return (filename == NULL) || - (strcmp(filename, "") == 0) || - (strcmp(filename, "???") == 0); + if (isatty((int)fileno(fp))) + return 1; + if (!Py_InteractiveFlag) + return 0; + return (filename == NULL) || + (strcmp(filename, "") == 0) || + (strcmp(filename, "???") == 0); } @@ -2185,21 +2185,21 @@ int PyOS_CheckStack(void) { - __try { - /* alloca throws a stack overflow exception if there's - not enough space left on the stack */ - alloca(PYOS_STACK_MARGIN * sizeof(void*)); - return 0; - } __except (GetExceptionCode() == STATUS_STACK_OVERFLOW ? - EXCEPTION_EXECUTE_HANDLER : - EXCEPTION_CONTINUE_SEARCH) { - int errcode = _resetstkoflw(); - if (errcode == 0) - { - Py_FatalError("Could not reset the stack!"); - } - } - return 1; + __try { + /* alloca throws a stack overflow exception if there's + not enough space left on the stack */ + alloca(PYOS_STACK_MARGIN * sizeof(void*)); + return 0; + } __except (GetExceptionCode() == STATUS_STACK_OVERFLOW ? + EXCEPTION_EXECUTE_HANDLER : + EXCEPTION_CONTINUE_SEARCH) { + int errcode = _resetstkoflw(); + if (errcode == 0) + { + Py_FatalError("Could not reset the stack!"); + } + } + return 1; } #endif /* WIN32 && _MSC_VER */ @@ -2215,33 +2215,33 @@ PyOS_getsig(int sig) { #ifdef HAVE_SIGACTION - struct sigaction context; - if (sigaction(sig, NULL, &context) == -1) - return SIG_ERR; - return context.sa_handler; + struct sigaction context; + if (sigaction(sig, NULL, &context) == -1) + return SIG_ERR; + return context.sa_handler; #else - PyOS_sighandler_t handler; + PyOS_sighandler_t handler; /* Special signal handling for the secure CRT in Visual Studio 2005 */ #if defined(_MSC_VER) && _MSC_VER >= 1400 - switch (sig) { - /* Only these signals are valid */ - case SIGINT: - case SIGILL: - case SIGFPE: - case SIGSEGV: - case SIGTERM: - case SIGBREAK: - case SIGABRT: - break; - /* Don't call signal() with other values or it will assert */ - default: - return SIG_ERR; - } + switch (sig) { + /* Only these signals are valid */ + case SIGINT: + case SIGILL: + case SIGFPE: + case SIGSEGV: + case SIGTERM: + case SIGBREAK: + case SIGABRT: + break; + /* Don't call signal() with other values or it will assert */ + default: + return SIG_ERR; + } #endif /* _MSC_VER && _MSC_VER >= 1400 */ - handler = signal(sig, SIG_IGN); - if (handler != SIG_ERR) - signal(sig, handler); - return handler; + handler = signal(sig, SIG_IGN); + if (handler != SIG_ERR) + signal(sig, handler); + return handler; #endif } @@ -2254,24 +2254,24 @@ PyOS_setsig(int sig, PyOS_sighandler_t handler) { #ifdef HAVE_SIGACTION - /* Some code in Modules/signalmodule.c depends on sigaction() being - * used here if HAVE_SIGACTION is defined. Fix that if this code - * changes to invalidate that assumption. - */ - struct sigaction context, ocontext; - context.sa_handler = handler; - sigemptyset(&context.sa_mask); - context.sa_flags = 0; - if (sigaction(sig, &context, &ocontext) == -1) - return SIG_ERR; - return ocontext.sa_handler; + /* Some code in Modules/signalmodule.c depends on sigaction() being + * used here if HAVE_SIGACTION is defined. Fix that if this code + * changes to invalidate that assumption. + */ + struct sigaction context, ocontext; + context.sa_handler = handler; + sigemptyset(&context.sa_mask); + context.sa_flags = 0; + if (sigaction(sig, &context, &ocontext) == -1) + return SIG_ERR; + return ocontext.sa_handler; #else - PyOS_sighandler_t oldhandler; - oldhandler = signal(sig, handler); + PyOS_sighandler_t oldhandler; + oldhandler = signal(sig, handler); #ifdef HAVE_SIGINTERRUPT - siginterrupt(sig, 1); + siginterrupt(sig, 1); #endif - return oldhandler; + return oldhandler; #endif } @@ -2281,71 +2281,71 @@ PyAPI_FUNC(node *) PyParser_SimpleParseFile(FILE *fp, const char *filename, int start) { - return PyParser_SimpleParseFileFlags(fp, filename, start, 0); + return PyParser_SimpleParseFileFlags(fp, filename, start, 0); } #undef PyParser_SimpleParseString PyAPI_FUNC(node *) PyParser_SimpleParseString(const char *str, int start) { - return PyParser_SimpleParseStringFlags(str, start, 0); + return PyParser_SimpleParseStringFlags(str, start, 0); } #undef PyRun_AnyFile PyAPI_FUNC(int) PyRun_AnyFile(FILE *fp, const char *name) { - return PyRun_AnyFileExFlags(fp, name, 0, NULL); + return PyRun_AnyFileExFlags(fp, name, 0, NULL); } #undef PyRun_AnyFileEx PyAPI_FUNC(int) PyRun_AnyFileEx(FILE *fp, const char *name, int closeit) { - return PyRun_AnyFileExFlags(fp, name, closeit, NULL); + return PyRun_AnyFileExFlags(fp, name, closeit, NULL); } #undef PyRun_AnyFileFlags PyAPI_FUNC(int) PyRun_AnyFileFlags(FILE *fp, const char *name, PyCompilerFlags *flags) { - return PyRun_AnyFileExFlags(fp, name, 0, flags); + return PyRun_AnyFileExFlags(fp, name, 0, flags); } #undef PyRun_File PyAPI_FUNC(PyObject *) PyRun_File(FILE *fp, const char *p, int s, PyObject *g, PyObject *l) { - return PyRun_FileExFlags(fp, p, s, g, l, 0, NULL); + return PyRun_FileExFlags(fp, p, s, g, l, 0, NULL); } #undef PyRun_FileEx PyAPI_FUNC(PyObject *) PyRun_FileEx(FILE *fp, const char *p, int s, PyObject *g, PyObject *l, int c) { - return PyRun_FileExFlags(fp, p, s, g, l, c, NULL); + return PyRun_FileExFlags(fp, p, s, g, l, c, NULL); } #undef PyRun_FileFlags PyAPI_FUNC(PyObject *) PyRun_FileFlags(FILE *fp, const char *p, int s, PyObject *g, PyObject *l, - PyCompilerFlags *flags) + PyCompilerFlags *flags) { - return PyRun_FileExFlags(fp, p, s, g, l, 0, flags); + return PyRun_FileExFlags(fp, p, s, g, l, 0, flags); } #undef PyRun_SimpleFile PyAPI_FUNC(int) PyRun_SimpleFile(FILE *f, const char *p) { - return PyRun_SimpleFileExFlags(f, p, 0, NULL); + return PyRun_SimpleFileExFlags(f, p, 0, NULL); } #undef PyRun_SimpleFileEx PyAPI_FUNC(int) PyRun_SimpleFileEx(FILE *f, const char *p, int c) { - return PyRun_SimpleFileExFlags(f, p, c, NULL); + return PyRun_SimpleFileExFlags(f, p, c, NULL); } @@ -2353,35 +2353,35 @@ PyAPI_FUNC(PyObject *) PyRun_String(const char *str, int s, PyObject *g, PyObject *l) { - return PyRun_StringFlags(str, s, g, l, NULL); + return PyRun_StringFlags(str, s, g, l, NULL); } #undef PyRun_SimpleString PyAPI_FUNC(int) PyRun_SimpleString(const char *s) { - return PyRun_SimpleStringFlags(s, NULL); + return PyRun_SimpleStringFlags(s, NULL); } #undef Py_CompileString PyAPI_FUNC(PyObject *) Py_CompileString(const char *str, const char *p, int s) { - return Py_CompileStringFlags(str, p, s, NULL); + return Py_CompileStringFlags(str, p, s, NULL); } #undef PyRun_InteractiveOne PyAPI_FUNC(int) PyRun_InteractiveOne(FILE *f, const char *p) { - return PyRun_InteractiveOneFlags(f, p, NULL); + return PyRun_InteractiveOneFlags(f, p, NULL); } #undef PyRun_InteractiveLoop PyAPI_FUNC(int) PyRun_InteractiveLoop(FILE *f, const char *p) { - return PyRun_InteractiveLoopFlags(f, p, NULL); + return PyRun_InteractiveLoopFlags(f, p, NULL); } #ifdef __cplusplus Modified: python/branches/py3k-jit/Python/structmember.c ============================================================================== --- python/branches/py3k-jit/Python/structmember.c (original) +++ python/branches/py3k-jit/Python/structmember.c Mon May 10 23:55:43 2010 @@ -8,293 +8,293 @@ PyObject * PyMember_GetOne(const char *addr, PyMemberDef *l) { - PyObject *v; + PyObject *v; - addr += l->offset; - switch (l->type) { - case T_BOOL: - v = PyBool_FromLong(*(char*)addr); - break; - case T_BYTE: - v = PyLong_FromLong(*(char*)addr); - break; - case T_UBYTE: - v = PyLong_FromUnsignedLong(*(unsigned char*)addr); - break; - case T_SHORT: - v = PyLong_FromLong(*(short*)addr); - break; - case T_USHORT: - v = PyLong_FromUnsignedLong(*(unsigned short*)addr); - break; - case T_INT: - v = PyLong_FromLong(*(int*)addr); - break; - case T_UINT: - v = PyLong_FromUnsignedLong(*(unsigned int*)addr); - break; - case T_LONG: - v = PyLong_FromLong(*(long*)addr); - break; - case T_ULONG: - v = PyLong_FromUnsignedLong(*(unsigned long*)addr); - break; - case T_PYSSIZET: - v = PyLong_FromSsize_t(*(Py_ssize_t*)addr); - break; - case T_FLOAT: - v = PyFloat_FromDouble((double)*(float*)addr); - break; - case T_DOUBLE: - v = PyFloat_FromDouble(*(double*)addr); - break; - case T_STRING: - if (*(char**)addr == NULL) { - Py_INCREF(Py_None); - v = Py_None; - } - else - v = PyUnicode_FromString(*(char**)addr); - break; - case T_STRING_INPLACE: - v = PyUnicode_FromString((char*)addr); - break; - case T_CHAR: - v = PyUnicode_FromStringAndSize((char*)addr, 1); - break; - case T_OBJECT: - v = *(PyObject **)addr; - if (v == NULL) - v = Py_None; - Py_INCREF(v); - break; - case T_OBJECT_EX: - v = *(PyObject **)addr; - if (v == NULL) - PyErr_SetString(PyExc_AttributeError, l->name); - Py_XINCREF(v); - break; + addr += l->offset; + switch (l->type) { + case T_BOOL: + v = PyBool_FromLong(*(char*)addr); + break; + case T_BYTE: + v = PyLong_FromLong(*(char*)addr); + break; + case T_UBYTE: + v = PyLong_FromUnsignedLong(*(unsigned char*)addr); + break; + case T_SHORT: + v = PyLong_FromLong(*(short*)addr); + break; + case T_USHORT: + v = PyLong_FromUnsignedLong(*(unsigned short*)addr); + break; + case T_INT: + v = PyLong_FromLong(*(int*)addr); + break; + case T_UINT: + v = PyLong_FromUnsignedLong(*(unsigned int*)addr); + break; + case T_LONG: + v = PyLong_FromLong(*(long*)addr); + break; + case T_ULONG: + v = PyLong_FromUnsignedLong(*(unsigned long*)addr); + break; + case T_PYSSIZET: + v = PyLong_FromSsize_t(*(Py_ssize_t*)addr); + break; + case T_FLOAT: + v = PyFloat_FromDouble((double)*(float*)addr); + break; + case T_DOUBLE: + v = PyFloat_FromDouble(*(double*)addr); + break; + case T_STRING: + if (*(char**)addr == NULL) { + Py_INCREF(Py_None); + v = Py_None; + } + else + v = PyUnicode_FromString(*(char**)addr); + break; + case T_STRING_INPLACE: + v = PyUnicode_FromString((char*)addr); + break; + case T_CHAR: + v = PyUnicode_FromStringAndSize((char*)addr, 1); + break; + case T_OBJECT: + v = *(PyObject **)addr; + if (v == NULL) + v = Py_None; + Py_INCREF(v); + break; + case T_OBJECT_EX: + v = *(PyObject **)addr; + if (v == NULL) + PyErr_SetString(PyExc_AttributeError, l->name); + Py_XINCREF(v); + break; #ifdef HAVE_LONG_LONG - case T_LONGLONG: - v = PyLong_FromLongLong(*(PY_LONG_LONG *)addr); - break; - case T_ULONGLONG: - v = PyLong_FromUnsignedLongLong(*(unsigned PY_LONG_LONG *)addr); - break; + case T_LONGLONG: + v = PyLong_FromLongLong(*(PY_LONG_LONG *)addr); + break; + case T_ULONGLONG: + v = PyLong_FromUnsignedLongLong(*(unsigned PY_LONG_LONG *)addr); + break; #endif /* HAVE_LONG_LONG */ - case T_NONE: - v = Py_None; - Py_INCREF(v); - break; - default: - PyErr_SetString(PyExc_SystemError, "bad memberdescr type"); - v = NULL; - } - return v; + case T_NONE: + v = Py_None; + Py_INCREF(v); + break; + default: + PyErr_SetString(PyExc_SystemError, "bad memberdescr type"); + v = NULL; + } + return v; } -#define WARN(msg) \ - do { \ - if (PyErr_WarnEx(PyExc_RuntimeWarning, msg, 1) < 0) \ - return -1; \ +#define WARN(msg) \ + do { \ + if (PyErr_WarnEx(PyExc_RuntimeWarning, msg, 1) < 0) \ + return -1; \ } while (0) int PyMember_SetOne(char *addr, PyMemberDef *l, PyObject *v) { - PyObject *oldv; + PyObject *oldv; - addr += l->offset; + addr += l->offset; - if ((l->flags & READONLY)) - { - PyErr_SetString(PyExc_AttributeError, "readonly attribute"); - return -1; - } - if (v == NULL) { - if (l->type == T_OBJECT_EX) { - /* Check if the attribute is set. */ - if (*(PyObject **)addr == NULL) { - PyErr_SetString(PyExc_AttributeError, l->name); - return -1; - } - } - else if (l->type != T_OBJECT) { - PyErr_SetString(PyExc_TypeError, - "can't delete numeric/char attribute"); - return -1; - } - } - switch (l->type) { - case T_BOOL:{ - if (!PyBool_Check(v)) { - PyErr_SetString(PyExc_TypeError, - "attribute value type must be bool"); - return -1; - } - if (v == Py_True) - *(char*)addr = (char) 1; - else - *(char*)addr = (char) 0; - break; - } - case T_BYTE:{ - long long_val = PyLong_AsLong(v); - if ((long_val == -1) && PyErr_Occurred()) - return -1; - *(char*)addr = (char)long_val; - /* XXX: For compatibility, only warn about truncations - for now. */ - if ((long_val > CHAR_MAX) || (long_val < CHAR_MIN)) - WARN("Truncation of value to char"); - break; - } - case T_UBYTE:{ - long long_val = PyLong_AsLong(v); - if ((long_val == -1) && PyErr_Occurred()) - return -1; - *(unsigned char*)addr = (unsigned char)long_val; - if ((long_val > UCHAR_MAX) || (long_val < 0)) - WARN("Truncation of value to unsigned char"); - break; - } - case T_SHORT:{ - long long_val = PyLong_AsLong(v); - if ((long_val == -1) && PyErr_Occurred()) - return -1; - *(short*)addr = (short)long_val; - if ((long_val > SHRT_MAX) || (long_val < SHRT_MIN)) - WARN("Truncation of value to short"); - break; - } - case T_USHORT:{ - long long_val = PyLong_AsLong(v); - if ((long_val == -1) && PyErr_Occurred()) - return -1; - *(unsigned short*)addr = (unsigned short)long_val; - if ((long_val > USHRT_MAX) || (long_val < 0)) - WARN("Truncation of value to unsigned short"); - break; - } - case T_INT:{ - long long_val = PyLong_AsLong(v); - if ((long_val == -1) && PyErr_Occurred()) - return -1; - *(int *)addr = (int)long_val; - if ((long_val > INT_MAX) || (long_val < INT_MIN)) - WARN("Truncation of value to int"); - break; - } - case T_UINT:{ - unsigned long ulong_val = PyLong_AsUnsignedLong(v); - if ((ulong_val == (unsigned long)-1) && PyErr_Occurred()) { - /* XXX: For compatibility, accept negative int values - as well. */ - PyErr_Clear(); - ulong_val = PyLong_AsLong(v); - if ((ulong_val == (unsigned long)-1) && - PyErr_Occurred()) - return -1; - *(unsigned int *)addr = (unsigned int)ulong_val; - WARN("Writing negative value into unsigned field"); - } else - *(unsigned int *)addr = (unsigned int)ulong_val; - if (ulong_val > UINT_MAX) - WARN("Truncation of value to unsigned int"); - break; - } - case T_LONG:{ - *(long*)addr = PyLong_AsLong(v); - if ((*(long*)addr == -1) && PyErr_Occurred()) - return -1; - break; - } - case T_ULONG:{ - *(unsigned long*)addr = PyLong_AsUnsignedLong(v); - if ((*(unsigned long*)addr == (unsigned long)-1) - && PyErr_Occurred()) { - /* XXX: For compatibility, accept negative int values - as well. */ - PyErr_Clear(); - *(unsigned long*)addr = PyLong_AsLong(v); - if ((*(unsigned long*)addr == (unsigned long)-1) - && PyErr_Occurred()) - return -1; - WARN("Writing negative value into unsigned field"); - } - break; - } - case T_PYSSIZET:{ - *(Py_ssize_t*)addr = PyLong_AsSsize_t(v); - if ((*(Py_ssize_t*)addr == (Py_ssize_t)-1) - && PyErr_Occurred()) - return -1; - break; - } - case T_FLOAT:{ - double double_val = PyFloat_AsDouble(v); - if ((double_val == -1) && PyErr_Occurred()) - return -1; - *(float*)addr = (float)double_val; - break; - } - case T_DOUBLE: - *(double*)addr = PyFloat_AsDouble(v); - if ((*(double*)addr == -1) && PyErr_Occurred()) - return -1; - break; - case T_OBJECT: - case T_OBJECT_EX: - Py_XINCREF(v); - oldv = *(PyObject **)addr; - *(PyObject **)addr = v; - Py_XDECREF(oldv); - break; - case T_CHAR: { - char *string; - Py_ssize_t len; + if ((l->flags & READONLY)) + { + PyErr_SetString(PyExc_AttributeError, "readonly attribute"); + return -1; + } + if (v == NULL) { + if (l->type == T_OBJECT_EX) { + /* Check if the attribute is set. */ + if (*(PyObject **)addr == NULL) { + PyErr_SetString(PyExc_AttributeError, l->name); + return -1; + } + } + else if (l->type != T_OBJECT) { + PyErr_SetString(PyExc_TypeError, + "can't delete numeric/char attribute"); + return -1; + } + } + switch (l->type) { + case T_BOOL:{ + if (!PyBool_Check(v)) { + PyErr_SetString(PyExc_TypeError, + "attribute value type must be bool"); + return -1; + } + if (v == Py_True) + *(char*)addr = (char) 1; + else + *(char*)addr = (char) 0; + break; + } + case T_BYTE:{ + long long_val = PyLong_AsLong(v); + if ((long_val == -1) && PyErr_Occurred()) + return -1; + *(char*)addr = (char)long_val; + /* XXX: For compatibility, only warn about truncations + for now. */ + if ((long_val > CHAR_MAX) || (long_val < CHAR_MIN)) + WARN("Truncation of value to char"); + break; + } + case T_UBYTE:{ + long long_val = PyLong_AsLong(v); + if ((long_val == -1) && PyErr_Occurred()) + return -1; + *(unsigned char*)addr = (unsigned char)long_val; + if ((long_val > UCHAR_MAX) || (long_val < 0)) + WARN("Truncation of value to unsigned char"); + break; + } + case T_SHORT:{ + long long_val = PyLong_AsLong(v); + if ((long_val == -1) && PyErr_Occurred()) + return -1; + *(short*)addr = (short)long_val; + if ((long_val > SHRT_MAX) || (long_val < SHRT_MIN)) + WARN("Truncation of value to short"); + break; + } + case T_USHORT:{ + long long_val = PyLong_AsLong(v); + if ((long_val == -1) && PyErr_Occurred()) + return -1; + *(unsigned short*)addr = (unsigned short)long_val; + if ((long_val > USHRT_MAX) || (long_val < 0)) + WARN("Truncation of value to unsigned short"); + break; + } + case T_INT:{ + long long_val = PyLong_AsLong(v); + if ((long_val == -1) && PyErr_Occurred()) + return -1; + *(int *)addr = (int)long_val; + if ((long_val > INT_MAX) || (long_val < INT_MIN)) + WARN("Truncation of value to int"); + break; + } + case T_UINT:{ + unsigned long ulong_val = PyLong_AsUnsignedLong(v); + if ((ulong_val == (unsigned long)-1) && PyErr_Occurred()) { + /* XXX: For compatibility, accept negative int values + as well. */ + PyErr_Clear(); + ulong_val = PyLong_AsLong(v); + if ((ulong_val == (unsigned long)-1) && + PyErr_Occurred()) + return -1; + *(unsigned int *)addr = (unsigned int)ulong_val; + WARN("Writing negative value into unsigned field"); + } else + *(unsigned int *)addr = (unsigned int)ulong_val; + if (ulong_val > UINT_MAX) + WARN("Truncation of value to unsigned int"); + break; + } + case T_LONG:{ + *(long*)addr = PyLong_AsLong(v); + if ((*(long*)addr == -1) && PyErr_Occurred()) + return -1; + break; + } + case T_ULONG:{ + *(unsigned long*)addr = PyLong_AsUnsignedLong(v); + if ((*(unsigned long*)addr == (unsigned long)-1) + && PyErr_Occurred()) { + /* XXX: For compatibility, accept negative int values + as well. */ + PyErr_Clear(); + *(unsigned long*)addr = PyLong_AsLong(v); + if ((*(unsigned long*)addr == (unsigned long)-1) + && PyErr_Occurred()) + return -1; + WARN("Writing negative value into unsigned field"); + } + break; + } + case T_PYSSIZET:{ + *(Py_ssize_t*)addr = PyLong_AsSsize_t(v); + if ((*(Py_ssize_t*)addr == (Py_ssize_t)-1) + && PyErr_Occurred()) + return -1; + break; + } + case T_FLOAT:{ + double double_val = PyFloat_AsDouble(v); + if ((double_val == -1) && PyErr_Occurred()) + return -1; + *(float*)addr = (float)double_val; + break; + } + case T_DOUBLE: + *(double*)addr = PyFloat_AsDouble(v); + if ((*(double*)addr == -1) && PyErr_Occurred()) + return -1; + break; + case T_OBJECT: + case T_OBJECT_EX: + Py_XINCREF(v); + oldv = *(PyObject **)addr; + *(PyObject **)addr = v; + Py_XDECREF(oldv); + break; + case T_CHAR: { + char *string; + Py_ssize_t len; - if (!PyUnicode_Check(v)) { - PyErr_BadArgument(); - return -1; - } - string = _PyUnicode_AsStringAndSize(v, &len); - if (len != 1) { - PyErr_BadArgument(); - return -1; - } - *(char*)addr = string[0]; - break; - } - case T_STRING: - case T_STRING_INPLACE: - PyErr_SetString(PyExc_TypeError, "readonly attribute"); - return -1; + if (!PyUnicode_Check(v)) { + PyErr_BadArgument(); + return -1; + } + string = _PyUnicode_AsStringAndSize(v, &len); + if (len != 1) { + PyErr_BadArgument(); + return -1; + } + *(char*)addr = string[0]; + break; + } + case T_STRING: + case T_STRING_INPLACE: + PyErr_SetString(PyExc_TypeError, "readonly attribute"); + return -1; #ifdef HAVE_LONG_LONG - case T_LONGLONG:{ - PY_LONG_LONG value; - *(PY_LONG_LONG*)addr = value = PyLong_AsLongLong(v); - if ((value == -1) && PyErr_Occurred()) - return -1; - break; - } - case T_ULONGLONG:{ - unsigned PY_LONG_LONG value; - /* ??? PyLong_AsLongLong accepts an int, but PyLong_AsUnsignedLongLong - doesn't ??? */ - if (PyLong_Check(v)) - *(unsigned PY_LONG_LONG*)addr = value = PyLong_AsUnsignedLongLong(v); - else - *(unsigned PY_LONG_LONG*)addr = value = PyLong_AsLong(v); - if ((value == (unsigned PY_LONG_LONG)-1) && PyErr_Occurred()) - return -1; - break; - } + case T_LONGLONG:{ + PY_LONG_LONG value; + *(PY_LONG_LONG*)addr = value = PyLong_AsLongLong(v); + if ((value == -1) && PyErr_Occurred()) + return -1; + break; + } + case T_ULONGLONG:{ + unsigned PY_LONG_LONG value; + /* ??? PyLong_AsLongLong accepts an int, but PyLong_AsUnsignedLongLong + doesn't ??? */ + if (PyLong_Check(v)) + *(unsigned PY_LONG_LONG*)addr = value = PyLong_AsUnsignedLongLong(v); + else + *(unsigned PY_LONG_LONG*)addr = value = PyLong_AsLong(v); + if ((value == (unsigned PY_LONG_LONG)-1) && PyErr_Occurred()) + return -1; + break; + } #endif /* HAVE_LONG_LONG */ - default: - PyErr_Format(PyExc_SystemError, - "bad memberdescr type for %s", l->name); - return -1; - } - return 0; + default: + PyErr_Format(PyExc_SystemError, + "bad memberdescr type for %s", l->name); + return -1; + } + return 0; } Modified: python/branches/py3k-jit/Python/symtable.c ============================================================================== --- python/branches/py3k-jit/Python/symtable.c (original) +++ python/branches/py3k-jit/Python/symtable.c Mon May 10 23:55:43 2010 @@ -25,145 +25,145 @@ static PySTEntryObject * ste_new(struct symtable *st, identifier name, _Py_block_ty block, - void *key, int lineno) + void *key, int lineno) { - PySTEntryObject *ste = NULL; - PyObject *k; + PySTEntryObject *ste = NULL; + PyObject *k; - k = PyLong_FromVoidPtr(key); - if (k == NULL) - goto fail; - ste = PyObject_New(PySTEntryObject, &PySTEntry_Type); - if (ste == NULL) - goto fail; - ste->ste_table = st; - ste->ste_id = k; - - ste->ste_name = name; - Py_INCREF(name); - - ste->ste_symbols = NULL; - ste->ste_varnames = NULL; - ste->ste_children = NULL; - - ste->ste_symbols = PyDict_New(); - if (ste->ste_symbols == NULL) - goto fail; - - ste->ste_varnames = PyList_New(0); - if (ste->ste_varnames == NULL) - goto fail; - - ste->ste_children = PyList_New(0); - if (ste->ste_children == NULL) - goto fail; - - ste->ste_type = block; - ste->ste_unoptimized = 0; - ste->ste_nested = 0; - ste->ste_free = 0; - ste->ste_varargs = 0; - ste->ste_varkeywords = 0; - ste->ste_opt_lineno = 0; - ste->ste_lineno = lineno; - - if (st->st_cur != NULL && - (st->st_cur->ste_nested || - st->st_cur->ste_type == FunctionBlock)) - ste->ste_nested = 1; - ste->ste_child_free = 0; - ste->ste_generator = 0; - ste->ste_returns_value = 0; - - if (PyDict_SetItem(st->st_blocks, ste->ste_id, (PyObject *)ste) < 0) - goto fail; - - return ste; + k = PyLong_FromVoidPtr(key); + if (k == NULL) + goto fail; + ste = PyObject_New(PySTEntryObject, &PySTEntry_Type); + if (ste == NULL) + goto fail; + ste->ste_table = st; + ste->ste_id = k; + + ste->ste_name = name; + Py_INCREF(name); + + ste->ste_symbols = NULL; + ste->ste_varnames = NULL; + ste->ste_children = NULL; + + ste->ste_symbols = PyDict_New(); + if (ste->ste_symbols == NULL) + goto fail; + + ste->ste_varnames = PyList_New(0); + if (ste->ste_varnames == NULL) + goto fail; + + ste->ste_children = PyList_New(0); + if (ste->ste_children == NULL) + goto fail; + + ste->ste_type = block; + ste->ste_unoptimized = 0; + ste->ste_nested = 0; + ste->ste_free = 0; + ste->ste_varargs = 0; + ste->ste_varkeywords = 0; + ste->ste_opt_lineno = 0; + ste->ste_lineno = lineno; + + if (st->st_cur != NULL && + (st->st_cur->ste_nested || + st->st_cur->ste_type == FunctionBlock)) + ste->ste_nested = 1; + ste->ste_child_free = 0; + ste->ste_generator = 0; + ste->ste_returns_value = 0; + + if (PyDict_SetItem(st->st_blocks, ste->ste_id, (PyObject *)ste) < 0) + goto fail; + + return ste; fail: - Py_XDECREF(ste); - return NULL; + Py_XDECREF(ste); + return NULL; } static PyObject * ste_repr(PySTEntryObject *ste) { - return PyUnicode_FromFormat("", - ste->ste_name, - PyLong_AS_LONG(ste->ste_id), ste->ste_lineno); + return PyUnicode_FromFormat("", + ste->ste_name, + PyLong_AS_LONG(ste->ste_id), ste->ste_lineno); } static void ste_dealloc(PySTEntryObject *ste) { - ste->ste_table = NULL; - Py_XDECREF(ste->ste_id); - Py_XDECREF(ste->ste_name); - Py_XDECREF(ste->ste_symbols); - Py_XDECREF(ste->ste_varnames); - Py_XDECREF(ste->ste_children); - PyObject_Del(ste); + ste->ste_table = NULL; + Py_XDECREF(ste->ste_id); + Py_XDECREF(ste->ste_name); + Py_XDECREF(ste->ste_symbols); + Py_XDECREF(ste->ste_varnames); + Py_XDECREF(ste->ste_children); + PyObject_Del(ste); } #define OFF(x) offsetof(PySTEntryObject, x) static PyMemberDef ste_memberlist[] = { - {"id", T_OBJECT, OFF(ste_id), READONLY}, - {"name", T_OBJECT, OFF(ste_name), READONLY}, - {"symbols", T_OBJECT, OFF(ste_symbols), READONLY}, - {"varnames", T_OBJECT, OFF(ste_varnames), READONLY}, - {"children", T_OBJECT, OFF(ste_children), READONLY}, - {"optimized",T_INT, OFF(ste_unoptimized), READONLY}, - {"nested", T_INT, OFF(ste_nested), READONLY}, - {"type", T_INT, OFF(ste_type), READONLY}, - {"lineno", T_INT, OFF(ste_lineno), READONLY}, - {NULL} + {"id", T_OBJECT, OFF(ste_id), READONLY}, + {"name", T_OBJECT, OFF(ste_name), READONLY}, + {"symbols", T_OBJECT, OFF(ste_symbols), READONLY}, + {"varnames", T_OBJECT, OFF(ste_varnames), READONLY}, + {"children", T_OBJECT, OFF(ste_children), READONLY}, + {"optimized",T_INT, OFF(ste_unoptimized), READONLY}, + {"nested", T_INT, OFF(ste_nested), READONLY}, + {"type", T_INT, OFF(ste_type), READONLY}, + {"lineno", T_INT, OFF(ste_lineno), READONLY}, + {NULL} }; PyTypeObject PySTEntry_Type = { - PyVarObject_HEAD_INIT(&PyType_Type, 0) - "symtable entry", - sizeof(PySTEntryObject), - 0, - (destructor)ste_dealloc, /* tp_dealloc */ - 0, /* tp_print */ - 0, /* tp_getattr */ - 0, /* tp_setattr */ - 0, /* tp_reserved */ - (reprfunc)ste_repr, /* tp_repr */ - 0, /* tp_as_number */ - 0, /* tp_as_sequence */ - 0, /* tp_as_mapping */ - 0, /* tp_hash */ - 0, /* tp_call */ - 0, /* tp_str */ - PyObject_GenericGetAttr, /* tp_getattro */ - 0, /* tp_setattro */ - 0, /* tp_as_buffer */ - Py_TPFLAGS_DEFAULT, /* tp_flags */ - 0, /* tp_doc */ - 0, /* tp_traverse */ - 0, /* tp_clear */ - 0, /* tp_richcompare */ - 0, /* tp_weaklistoffset */ - 0, /* tp_iter */ - 0, /* tp_iternext */ - 0, /* tp_methods */ - ste_memberlist, /* tp_members */ - 0, /* tp_getset */ - 0, /* tp_base */ - 0, /* tp_dict */ - 0, /* tp_descr_get */ - 0, /* tp_descr_set */ - 0, /* tp_dictoffset */ - 0, /* tp_init */ - 0, /* tp_alloc */ - 0, /* tp_new */ + PyVarObject_HEAD_INIT(&PyType_Type, 0) + "symtable entry", + sizeof(PySTEntryObject), + 0, + (destructor)ste_dealloc, /* tp_dealloc */ + 0, /* tp_print */ + 0, /* tp_getattr */ + 0, /* tp_setattr */ + 0, /* tp_reserved */ + (reprfunc)ste_repr, /* tp_repr */ + 0, /* tp_as_number */ + 0, /* tp_as_sequence */ + 0, /* tp_as_mapping */ + 0, /* tp_hash */ + 0, /* tp_call */ + 0, /* tp_str */ + PyObject_GenericGetAttr, /* tp_getattro */ + 0, /* tp_setattro */ + 0, /* tp_as_buffer */ + Py_TPFLAGS_DEFAULT, /* tp_flags */ + 0, /* tp_doc */ + 0, /* tp_traverse */ + 0, /* tp_clear */ + 0, /* tp_richcompare */ + 0, /* tp_weaklistoffset */ + 0, /* tp_iter */ + 0, /* tp_iternext */ + 0, /* tp_methods */ + ste_memberlist, /* tp_members */ + 0, /* tp_getset */ + 0, /* tp_base */ + 0, /* tp_dict */ + 0, /* tp_descr_get */ + 0, /* tp_descr_set */ + 0, /* tp_dictoffset */ + 0, /* tp_init */ + 0, /* tp_alloc */ + 0, /* tp_new */ }; static int symtable_analyze(struct symtable *st); static int symtable_warn(struct symtable *st, char *msg, int lineno); -static int symtable_enter_block(struct symtable *st, identifier name, - _Py_block_ty block, void *ast, int lineno); +static int symtable_enter_block(struct symtable *st, identifier name, + _Py_block_ty block, void *ast, int lineno); static int symtable_exit_block(struct symtable *st, void *ast); static int symtable_visit_stmt(struct symtable *st, stmt_ty s); static int symtable_visit_expr(struct symtable *st, expr_ty s); @@ -184,11 +184,11 @@ static identifier top = NULL, lambda = NULL, genexpr = NULL, - listcomp = NULL, setcomp = NULL, dictcomp = NULL, - __class__ = NULL, __locals__ = NULL; + listcomp = NULL, setcomp = NULL, dictcomp = NULL, + __class__ = NULL, __locals__ = NULL; #define GET_IDENTIFIER(VAR) \ - ((VAR) ? (VAR) : ((VAR) = PyUnicode_InternFromString(# VAR))) + ((VAR) ? (VAR) : ((VAR) = PyUnicode_InternFromString(# VAR))) #define DUPLICATE_ARGUMENT \ "duplicate argument '%U' in function definition" @@ -196,135 +196,135 @@ static struct symtable * symtable_new(void) { - struct symtable *st; + struct symtable *st; - st = (struct symtable *)PyMem_Malloc(sizeof(struct symtable)); - if (st == NULL) - return NULL; - - st->st_filename = NULL; - st->st_blocks = NULL; - - if ((st->st_stack = PyList_New(0)) == NULL) - goto fail; - if ((st->st_blocks = PyDict_New()) == NULL) - goto fail; - st->st_cur = NULL; - st->st_private = NULL; - return st; + st = (struct symtable *)PyMem_Malloc(sizeof(struct symtable)); + if (st == NULL) + return NULL; + + st->st_filename = NULL; + st->st_blocks = NULL; + + if ((st->st_stack = PyList_New(0)) == NULL) + goto fail; + if ((st->st_blocks = PyDict_New()) == NULL) + goto fail; + st->st_cur = NULL; + st->st_private = NULL; + return st; fail: - PySymtable_Free(st); - return NULL; + PySymtable_Free(st); + return NULL; } struct symtable * PySymtable_Build(mod_ty mod, const char *filename, PyFutureFeatures *future) { - struct symtable *st = symtable_new(); - asdl_seq *seq; - int i; - - if (st == NULL) - return st; - st->st_filename = filename; - st->st_future = future; - /* Make the initial symbol information gathering pass */ - if (!GET_IDENTIFIER(top) || - !symtable_enter_block(st, top, ModuleBlock, (void *)mod, 0)) { - PySymtable_Free(st); - return NULL; - } - - st->st_top = st->st_cur; - st->st_cur->ste_unoptimized = OPT_TOPLEVEL; - switch (mod->kind) { - case Module_kind: - seq = mod->v.Module.body; - for (i = 0; i < asdl_seq_LEN(seq); i++) - if (!symtable_visit_stmt(st, - (stmt_ty)asdl_seq_GET(seq, i))) - goto error; - break; - case Expression_kind: - if (!symtable_visit_expr(st, mod->v.Expression.body)) - goto error; - break; - case Interactive_kind: - seq = mod->v.Interactive.body; - for (i = 0; i < asdl_seq_LEN(seq); i++) - if (!symtable_visit_stmt(st, - (stmt_ty)asdl_seq_GET(seq, i))) - goto error; - break; - case Suite_kind: - PyErr_SetString(PyExc_RuntimeError, - "this compiler does not handle Suites"); - goto error; - } - if (!symtable_exit_block(st, (void *)mod)) { - PySymtable_Free(st); - return NULL; - } - /* Make the second symbol analysis pass */ - if (symtable_analyze(st)) - return st; - PySymtable_Free(st); - return NULL; + struct symtable *st = symtable_new(); + asdl_seq *seq; + int i; + + if (st == NULL) + return st; + st->st_filename = filename; + st->st_future = future; + /* Make the initial symbol information gathering pass */ + if (!GET_IDENTIFIER(top) || + !symtable_enter_block(st, top, ModuleBlock, (void *)mod, 0)) { + PySymtable_Free(st); + return NULL; + } + + st->st_top = st->st_cur; + st->st_cur->ste_unoptimized = OPT_TOPLEVEL; + switch (mod->kind) { + case Module_kind: + seq = mod->v.Module.body; + for (i = 0; i < asdl_seq_LEN(seq); i++) + if (!symtable_visit_stmt(st, + (stmt_ty)asdl_seq_GET(seq, i))) + goto error; + break; + case Expression_kind: + if (!symtable_visit_expr(st, mod->v.Expression.body)) + goto error; + break; + case Interactive_kind: + seq = mod->v.Interactive.body; + for (i = 0; i < asdl_seq_LEN(seq); i++) + if (!symtable_visit_stmt(st, + (stmt_ty)asdl_seq_GET(seq, i))) + goto error; + break; + case Suite_kind: + PyErr_SetString(PyExc_RuntimeError, + "this compiler does not handle Suites"); + goto error; + } + if (!symtable_exit_block(st, (void *)mod)) { + PySymtable_Free(st); + return NULL; + } + /* Make the second symbol analysis pass */ + if (symtable_analyze(st)) + return st; + PySymtable_Free(st); + return NULL; error: - (void) symtable_exit_block(st, (void *)mod); - PySymtable_Free(st); - return NULL; + (void) symtable_exit_block(st, (void *)mod); + PySymtable_Free(st); + return NULL; } void PySymtable_Free(struct symtable *st) { - Py_XDECREF(st->st_blocks); - Py_XDECREF(st->st_stack); - PyMem_Free((void *)st); + Py_XDECREF(st->st_blocks); + Py_XDECREF(st->st_stack); + PyMem_Free((void *)st); } PySTEntryObject * PySymtable_Lookup(struct symtable *st, void *key) { - PyObject *k, *v; + PyObject *k, *v; - k = PyLong_FromVoidPtr(key); - if (k == NULL) - return NULL; - v = PyDict_GetItem(st->st_blocks, k); - if (v) { - assert(PySTEntry_Check(v)); - Py_INCREF(v); - } - else { - PyErr_SetString(PyExc_KeyError, - "unknown symbol table entry"); - } + k = PyLong_FromVoidPtr(key); + if (k == NULL) + return NULL; + v = PyDict_GetItem(st->st_blocks, k); + if (v) { + assert(PySTEntry_Check(v)); + Py_INCREF(v); + } + else { + PyErr_SetString(PyExc_KeyError, + "unknown symbol table entry"); + } - Py_DECREF(k); - return (PySTEntryObject *)v; + Py_DECREF(k); + return (PySTEntryObject *)v; } -int +int PyST_GetScope(PySTEntryObject *ste, PyObject *name) { - PyObject *v = PyDict_GetItem(ste->ste_symbols, name); - if (!v) - return 0; - assert(PyLong_Check(v)); - return (PyLong_AS_LONG(v) >> SCOPE_OFFSET) & SCOPE_MASK; + PyObject *v = PyDict_GetItem(ste->ste_symbols, name); + if (!v) + return 0; + assert(PyLong_Check(v)); + return (PyLong_AS_LONG(v) >> SCOPE_OFFSET) & SCOPE_MASK; } /* Analyze raw symbol information to determine scope of each name. The next several functions are helpers for symtable_analyze(), - which determines whether a name is local, global, or free. In addition, + which determines whether a name is local, global, or free. In addition, it determines which local variables are cell variables; they provide - bindings that are used for free variables in enclosed blocks. + bindings that are used for free variables in enclosed blocks. - There are also two kinds of global variables, implicit and explicit. An + There are also two kinds of global variables, implicit and explicit. An explicit global is declared with the global statement. An implicit global is a free variable for which the compiler has found no binding in an enclosing function scope. The implicit global is either a global @@ -340,7 +340,7 @@ PySTEntryObjects created during pass 1. When a function is entered during the second pass, the parent passes - the set of all name bindings visible to its children. These bindings + the set of all name bindings visible to its children. These bindings are used to determine if non-local variables are free or implicit globals. Names which are explicitly declared nonlocal must exist in this set of visible names - if they do not, a syntax error is raised. After doing @@ -363,14 +363,14 @@ */ #define SET_SCOPE(DICT, NAME, I) { \ - PyObject *o = PyLong_FromLong(I); \ - if (!o) \ - return 0; \ - if (PyDict_SetItem((DICT), (NAME), o) < 0) { \ - Py_DECREF(o); \ - return 0; \ - } \ - Py_DECREF(o); \ + PyObject *o = PyLong_FromLong(I); \ + if (!o) \ + return 0; \ + if (PyDict_SetItem((DICT), (NAME), o) < 0) { \ + Py_DECREF(o); \ + return 0; \ + } \ + Py_DECREF(o); \ } /* Decide on scope of name, given flags. @@ -380,86 +380,86 @@ global. A name that was global can be changed to local. */ -static int +static int analyze_name(PySTEntryObject *ste, PyObject *scopes, PyObject *name, long flags, - PyObject *bound, PyObject *local, PyObject *free, - PyObject *global) + PyObject *bound, PyObject *local, PyObject *free, + PyObject *global) { - if (flags & DEF_GLOBAL) { - if (flags & DEF_PARAM) { - PyErr_Format(PyExc_SyntaxError, - "name '%U' is parameter and global", - name); - PyErr_SyntaxLocation(ste->ste_table->st_filename, - ste->ste_lineno); - - return 0; - } - if (flags & DEF_NONLOCAL) { - PyErr_Format(PyExc_SyntaxError, - "name '%U' is nonlocal and global", - name); - return 0; - } - SET_SCOPE(scopes, name, GLOBAL_EXPLICIT); - if (PySet_Add(global, name) < 0) - return 0; - if (bound && (PySet_Discard(bound, name) < 0)) - return 0; - return 1; - } + if (flags & DEF_GLOBAL) { + if (flags & DEF_PARAM) { + PyErr_Format(PyExc_SyntaxError, + "name '%U' is parameter and global", + name); + PyErr_SyntaxLocation(ste->ste_table->st_filename, + ste->ste_lineno); + + return 0; + } if (flags & DEF_NONLOCAL) { - if (flags & DEF_PARAM) { - PyErr_Format(PyExc_SyntaxError, - "name '%U' is parameter and nonlocal", - name); - return 0; - } - if (!bound) { - PyErr_Format(PyExc_SyntaxError, - "nonlocal declaration not allowed at module level"); - return 0; - } - if (!PySet_Contains(bound, name)) { - PyErr_Format(PyExc_SyntaxError, - "no binding for nonlocal '%U' found", - name); - - return 0; - } - SET_SCOPE(scopes, name, FREE); - ste->ste_free = 1; - return PySet_Add(free, name) >= 0; - } - if (flags & DEF_BOUND) { - SET_SCOPE(scopes, name, LOCAL); - if (PySet_Add(local, name) < 0) - return 0; - if (PySet_Discard(global, name) < 0) - return 0; - return 1; - } - /* If an enclosing block has a binding for this name, it - is a free variable rather than a global variable. - Note that having a non-NULL bound implies that the block - is nested. - */ - if (bound && PySet_Contains(bound, name)) { - SET_SCOPE(scopes, name, FREE); - ste->ste_free = 1; - return PySet_Add(free, name) >= 0; - } - /* If a parent has a global statement, then call it global - explicit? It could also be global implicit. - */ - if (global && PySet_Contains(global, name)) { - SET_SCOPE(scopes, name, GLOBAL_IMPLICIT); - return 1; - } - if (ste->ste_nested) - ste->ste_free = 1; - SET_SCOPE(scopes, name, GLOBAL_IMPLICIT); - return 1; + PyErr_Format(PyExc_SyntaxError, + "name '%U' is nonlocal and global", + name); + return 0; + } + SET_SCOPE(scopes, name, GLOBAL_EXPLICIT); + if (PySet_Add(global, name) < 0) + return 0; + if (bound && (PySet_Discard(bound, name) < 0)) + return 0; + return 1; + } + if (flags & DEF_NONLOCAL) { + if (flags & DEF_PARAM) { + PyErr_Format(PyExc_SyntaxError, + "name '%U' is parameter and nonlocal", + name); + return 0; + } + if (!bound) { + PyErr_Format(PyExc_SyntaxError, + "nonlocal declaration not allowed at module level"); + return 0; + } + if (!PySet_Contains(bound, name)) { + PyErr_Format(PyExc_SyntaxError, + "no binding for nonlocal '%U' found", + name); + + return 0; + } + SET_SCOPE(scopes, name, FREE); + ste->ste_free = 1; + return PySet_Add(free, name) >= 0; + } + if (flags & DEF_BOUND) { + SET_SCOPE(scopes, name, LOCAL); + if (PySet_Add(local, name) < 0) + return 0; + if (PySet_Discard(global, name) < 0) + return 0; + return 1; + } + /* If an enclosing block has a binding for this name, it + is a free variable rather than a global variable. + Note that having a non-NULL bound implies that the block + is nested. + */ + if (bound && PySet_Contains(bound, name)) { + SET_SCOPE(scopes, name, FREE); + ste->ste_free = 1; + return PySet_Add(free, name) >= 0; + } + /* If a parent has a global statement, then call it global + explicit? It could also be global implicit. + */ + if (global && PySet_Contains(global, name)) { + SET_SCOPE(scopes, name, GLOBAL_IMPLICIT); + return 1; + } + if (ste->ste_nested) + ste->ste_free = 1; + SET_SCOPE(scopes, name, GLOBAL_IMPLICIT); + return 1; } #undef SET_SCOPE @@ -478,153 +478,153 @@ static int analyze_cells(PyObject *scopes, PyObject *free, const char *restricted) { - PyObject *name, *v, *v_cell; - int success = 0; - Py_ssize_t pos = 0; - - v_cell = PyLong_FromLong(CELL); - if (!v_cell) - return 0; - while (PyDict_Next(scopes, &pos, &name, &v)) { - long scope; - assert(PyLong_Check(v)); - scope = PyLong_AS_LONG(v); - if (scope != LOCAL) - continue; - if (!PySet_Contains(free, name)) - continue; - if (restricted != NULL && - PyUnicode_CompareWithASCIIString(name, restricted)) - continue; - /* Replace LOCAL with CELL for this name, and remove - from free. It is safe to replace the value of name - in the dict, because it will not cause a resize. - */ - if (PyDict_SetItem(scopes, name, v_cell) < 0) - goto error; - if (PySet_Discard(free, name) < 0) - goto error; - } - success = 1; + PyObject *name, *v, *v_cell; + int success = 0; + Py_ssize_t pos = 0; + + v_cell = PyLong_FromLong(CELL); + if (!v_cell) + return 0; + while (PyDict_Next(scopes, &pos, &name, &v)) { + long scope; + assert(PyLong_Check(v)); + scope = PyLong_AS_LONG(v); + if (scope != LOCAL) + continue; + if (!PySet_Contains(free, name)) + continue; + if (restricted != NULL && + PyUnicode_CompareWithASCIIString(name, restricted)) + continue; + /* Replace LOCAL with CELL for this name, and remove + from free. It is safe to replace the value of name + in the dict, because it will not cause a resize. + */ + if (PyDict_SetItem(scopes, name, v_cell) < 0) + goto error; + if (PySet_Discard(free, name) < 0) + goto error; + } + success = 1; error: - Py_DECREF(v_cell); - return success; + Py_DECREF(v_cell); + return success; } /* Check for illegal statements in unoptimized namespaces */ static int check_unoptimized(const PySTEntryObject* ste) { - const char* trailer; + const char* trailer; - if (ste->ste_type != FunctionBlock || !ste->ste_unoptimized - || !(ste->ste_free || ste->ste_child_free)) - return 1; - - trailer = (ste->ste_child_free ? - "contains a nested function with free variables" : - "is a nested function"); - - switch (ste->ste_unoptimized) { - case OPT_TOPLEVEL: /* import * at top-level is fine */ - return 1; - case OPT_IMPORT_STAR: - PyErr_Format(PyExc_SyntaxError, - "import * is not allowed in function '%U' because it %s", - ste->ste_name, trailer); - break; - } - - PyErr_SyntaxLocation(ste->ste_table->st_filename, - ste->ste_opt_lineno); - return 0; + if (ste->ste_type != FunctionBlock || !ste->ste_unoptimized + || !(ste->ste_free || ste->ste_child_free)) + return 1; + + trailer = (ste->ste_child_free ? + "contains a nested function with free variables" : + "is a nested function"); + + switch (ste->ste_unoptimized) { + case OPT_TOPLEVEL: /* import * at top-level is fine */ + return 1; + case OPT_IMPORT_STAR: + PyErr_Format(PyExc_SyntaxError, + "import * is not allowed in function '%U' because it %s", + ste->ste_name, trailer); + break; + } + + PyErr_SyntaxLocation(ste->ste_table->st_filename, + ste->ste_opt_lineno); + return 0; } -/* Enter the final scope information into the ste_symbols dict. - * +/* Enter the final scope information into the ste_symbols dict. + * * All arguments are dicts. Modifies symbols, others are read-only. */ static int -update_symbols(PyObject *symbols, PyObject *scopes, +update_symbols(PyObject *symbols, PyObject *scopes, PyObject *bound, PyObject *free, int classflag) { - PyObject *name = NULL, *itr = NULL; - PyObject *v = NULL, *v_scope = NULL, *v_new = NULL, *v_free = NULL; - Py_ssize_t pos = 0; - - /* Update scope information for all symbols in this scope */ - while (PyDict_Next(symbols, &pos, &name, &v)) { - long scope, flags; - assert(PyLong_Check(v)); - flags = PyLong_AS_LONG(v); - v_scope = PyDict_GetItem(scopes, name); - assert(v_scope && PyLong_Check(v_scope)); - scope = PyLong_AS_LONG(v_scope); - flags |= (scope << SCOPE_OFFSET); - v_new = PyLong_FromLong(flags); - if (!v_new) - return 0; - if (PyDict_SetItem(symbols, name, v_new) < 0) { - Py_DECREF(v_new); - return 0; - } - Py_DECREF(v_new); - } - - /* Record not yet resolved free variables from children (if any) */ - v_free = PyLong_FromLong(FREE << SCOPE_OFFSET); - if (!v_free) - return 0; - - itr = PyObject_GetIter(free); - if (!itr) - goto error; - - while ((name = PyIter_Next(itr))) { - v = PyDict_GetItem(symbols, name); - - /* Handle symbol that already exists in this scope */ - if (v) { - /* Handle a free variable in a method of - the class that has the same name as a local - or global in the class scope. - */ - if (classflag && - PyLong_AS_LONG(v) & (DEF_BOUND | DEF_GLOBAL)) { - long flags = PyLong_AS_LONG(v) | DEF_FREE_CLASS; - v_new = PyLong_FromLong(flags); - if (!v_new) { - goto error; - } - if (PyDict_SetItem(symbols, name, v_new) < 0) { - Py_DECREF(v_new); - goto error; - } - Py_DECREF(v_new); - } - /* It's a cell, or already free in this scope */ - Py_DECREF(name); - continue; - } - /* Handle global symbol */ - if (!PySet_Contains(bound, name)) { - Py_DECREF(name); - continue; /* it's a global */ - } - /* Propagate new free symbol up the lexical stack */ - if (PyDict_SetItem(symbols, name, v_free) < 0) { - goto error; - } - Py_DECREF(name); - } - Py_DECREF(itr); - Py_DECREF(v_free); - return 1; + PyObject *name = NULL, *itr = NULL; + PyObject *v = NULL, *v_scope = NULL, *v_new = NULL, *v_free = NULL; + Py_ssize_t pos = 0; + + /* Update scope information for all symbols in this scope */ + while (PyDict_Next(symbols, &pos, &name, &v)) { + long scope, flags; + assert(PyLong_Check(v)); + flags = PyLong_AS_LONG(v); + v_scope = PyDict_GetItem(scopes, name); + assert(v_scope && PyLong_Check(v_scope)); + scope = PyLong_AS_LONG(v_scope); + flags |= (scope << SCOPE_OFFSET); + v_new = PyLong_FromLong(flags); + if (!v_new) + return 0; + if (PyDict_SetItem(symbols, name, v_new) < 0) { + Py_DECREF(v_new); + return 0; + } + Py_DECREF(v_new); + } + + /* Record not yet resolved free variables from children (if any) */ + v_free = PyLong_FromLong(FREE << SCOPE_OFFSET); + if (!v_free) + return 0; + + itr = PyObject_GetIter(free); + if (!itr) + goto error; + + while ((name = PyIter_Next(itr))) { + v = PyDict_GetItem(symbols, name); + + /* Handle symbol that already exists in this scope */ + if (v) { + /* Handle a free variable in a method of + the class that has the same name as a local + or global in the class scope. + */ + if (classflag && + PyLong_AS_LONG(v) & (DEF_BOUND | DEF_GLOBAL)) { + long flags = PyLong_AS_LONG(v) | DEF_FREE_CLASS; + v_new = PyLong_FromLong(flags); + if (!v_new) { + goto error; + } + if (PyDict_SetItem(symbols, name, v_new) < 0) { + Py_DECREF(v_new); + goto error; + } + Py_DECREF(v_new); + } + /* It's a cell, or already free in this scope */ + Py_DECREF(name); + continue; + } + /* Handle global symbol */ + if (!PySet_Contains(bound, name)) { + Py_DECREF(name); + continue; /* it's a global */ + } + /* Propagate new free symbol up the lexical stack */ + if (PyDict_SetItem(symbols, name, v_free) < 0) { + goto error; + } + Py_DECREF(name); + } + Py_DECREF(itr); + Py_DECREF(v_free); + return 1; error: - Py_XDECREF(v_free); - Py_XDECREF(itr); - Py_XDECREF(name); - return 0; -} + Py_XDECREF(v_free); + Py_XDECREF(itr); + Py_XDECREF(name); + return 0; +} /* Make final symbol table decisions for block of ste. @@ -647,238 +647,238 @@ */ static int -analyze_child_block(PySTEntryObject *entry, PyObject *bound, PyObject *free, - PyObject *global, PyObject* child_free); +analyze_child_block(PySTEntryObject *entry, PyObject *bound, PyObject *free, + PyObject *global, PyObject* child_free); static int -analyze_block(PySTEntryObject *ste, PyObject *bound, PyObject *free, - PyObject *global) +analyze_block(PySTEntryObject *ste, PyObject *bound, PyObject *free, + PyObject *global) { - PyObject *name, *v, *local = NULL, *scopes = NULL, *newbound = NULL; - PyObject *newglobal = NULL, *newfree = NULL, *allfree = NULL; - PyObject *temp; - int i, success = 0; - Py_ssize_t pos = 0; - - local = PySet_New(NULL); /* collect new names bound in block */ - if (!local) - goto error; - scopes = PyDict_New(); /* collect scopes defined for each name */ - if (!scopes) - goto error; - - /* Allocate new global and bound variable dictionaries. These - dictionaries hold the names visible in nested blocks. For - ClassBlocks, the bound and global names are initialized - before analyzing names, because class bindings aren't - visible in methods. For other blocks, they are initialized - after names are analyzed. - */ - - /* TODO(jhylton): Package these dicts in a struct so that we - can write reasonable helper functions? - */ - newglobal = PySet_New(NULL); - if (!newglobal) - goto error; - newfree = PySet_New(NULL); - if (!newfree) - goto error; - newbound = PySet_New(NULL); - if (!newbound) - goto error; - - /* Class namespace has no effect on names visible in - nested functions, so populate the global and bound - sets to be passed to child blocks before analyzing - this one. - */ - if (ste->ste_type == ClassBlock) { - /* Pass down known globals */ - temp = PyNumber_InPlaceOr(newglobal, global); - if (!temp) - goto error; - Py_DECREF(temp); - /* Pass down previously bound symbols */ - if (bound) { - temp = PyNumber_InPlaceOr(newbound, bound); - if (!temp) - goto error; - Py_DECREF(temp); - } - } - - while (PyDict_Next(ste->ste_symbols, &pos, &name, &v)) { - long flags = PyLong_AS_LONG(v); - if (!analyze_name(ste, scopes, name, flags, - bound, local, free, global)) - goto error; - } - - /* Populate global and bound sets to be passed to children. */ - if (ste->ste_type != ClassBlock) { - /* Add function locals to bound set */ - if (ste->ste_type == FunctionBlock) { - temp = PyNumber_InPlaceOr(newbound, local); - if (!temp) - goto error; - Py_DECREF(temp); - } - /* Pass down previously bound symbols */ - if (bound) { - temp = PyNumber_InPlaceOr(newbound, bound); - if (!temp) - goto error; - Py_DECREF(temp); - } - /* Pass down known globals */ - temp = PyNumber_InPlaceOr(newglobal, global); - if (!temp) - goto error; - Py_DECREF(temp); - } - else { - /* Special-case __class__ */ - if (!GET_IDENTIFIER(__class__)) - goto error; - assert(PySet_Contains(local, __class__) == 1); - if (PySet_Add(newbound, __class__) < 0) - goto error; - } - - /* Recursively call analyze_block() on each child block. - - newbound, newglobal now contain the names visible in - nested blocks. The free variables in the children will - be collected in allfree. - */ - allfree = PySet_New(NULL); - if (!allfree) - goto error; - for (i = 0; i < PyList_GET_SIZE(ste->ste_children); ++i) { - PyObject *c = PyList_GET_ITEM(ste->ste_children, i); - PySTEntryObject* entry; - assert(c && PySTEntry_Check(c)); - entry = (PySTEntryObject*)c; - if (!analyze_child_block(entry, newbound, newfree, newglobal, - allfree)) - goto error; - /* Check if any children have free variables */ - if (entry->ste_free || entry->ste_child_free) - ste->ste_child_free = 1; - } - - temp = PyNumber_InPlaceOr(newfree, allfree); - if (!temp) - goto error; - Py_DECREF(temp); - - /* Check if any local variables must be converted to cell variables */ - if (ste->ste_type == FunctionBlock && !analyze_cells(scopes, newfree, - NULL)) - goto error; - else if (ste->ste_type == ClassBlock && !analyze_cells(scopes, newfree, - "__class__")) - goto error; - /* Records the results of the analysis in the symbol table entry */ - if (!update_symbols(ste->ste_symbols, scopes, bound, newfree, - ste->ste_type == ClassBlock)) - goto error; - if (!check_unoptimized(ste)) - goto error; - - temp = PyNumber_InPlaceOr(free, newfree); - if (!temp) - goto error; - Py_DECREF(temp); - success = 1; + PyObject *name, *v, *local = NULL, *scopes = NULL, *newbound = NULL; + PyObject *newglobal = NULL, *newfree = NULL, *allfree = NULL; + PyObject *temp; + int i, success = 0; + Py_ssize_t pos = 0; + + local = PySet_New(NULL); /* collect new names bound in block */ + if (!local) + goto error; + scopes = PyDict_New(); /* collect scopes defined for each name */ + if (!scopes) + goto error; + + /* Allocate new global and bound variable dictionaries. These + dictionaries hold the names visible in nested blocks. For + ClassBlocks, the bound and global names are initialized + before analyzing names, because class bindings aren't + visible in methods. For other blocks, they are initialized + after names are analyzed. + */ + + /* TODO(jhylton): Package these dicts in a struct so that we + can write reasonable helper functions? + */ + newglobal = PySet_New(NULL); + if (!newglobal) + goto error; + newfree = PySet_New(NULL); + if (!newfree) + goto error; + newbound = PySet_New(NULL); + if (!newbound) + goto error; + + /* Class namespace has no effect on names visible in + nested functions, so populate the global and bound + sets to be passed to child blocks before analyzing + this one. + */ + if (ste->ste_type == ClassBlock) { + /* Pass down known globals */ + temp = PyNumber_InPlaceOr(newglobal, global); + if (!temp) + goto error; + Py_DECREF(temp); + /* Pass down previously bound symbols */ + if (bound) { + temp = PyNumber_InPlaceOr(newbound, bound); + if (!temp) + goto error; + Py_DECREF(temp); + } + } + + while (PyDict_Next(ste->ste_symbols, &pos, &name, &v)) { + long flags = PyLong_AS_LONG(v); + if (!analyze_name(ste, scopes, name, flags, + bound, local, free, global)) + goto error; + } + + /* Populate global and bound sets to be passed to children. */ + if (ste->ste_type != ClassBlock) { + /* Add function locals to bound set */ + if (ste->ste_type == FunctionBlock) { + temp = PyNumber_InPlaceOr(newbound, local); + if (!temp) + goto error; + Py_DECREF(temp); + } + /* Pass down previously bound symbols */ + if (bound) { + temp = PyNumber_InPlaceOr(newbound, bound); + if (!temp) + goto error; + Py_DECREF(temp); + } + /* Pass down known globals */ + temp = PyNumber_InPlaceOr(newglobal, global); + if (!temp) + goto error; + Py_DECREF(temp); + } + else { + /* Special-case __class__ */ + if (!GET_IDENTIFIER(__class__)) + goto error; + assert(PySet_Contains(local, __class__) == 1); + if (PySet_Add(newbound, __class__) < 0) + goto error; + } + + /* Recursively call analyze_block() on each child block. + + newbound, newglobal now contain the names visible in + nested blocks. The free variables in the children will + be collected in allfree. + */ + allfree = PySet_New(NULL); + if (!allfree) + goto error; + for (i = 0; i < PyList_GET_SIZE(ste->ste_children); ++i) { + PyObject *c = PyList_GET_ITEM(ste->ste_children, i); + PySTEntryObject* entry; + assert(c && PySTEntry_Check(c)); + entry = (PySTEntryObject*)c; + if (!analyze_child_block(entry, newbound, newfree, newglobal, + allfree)) + goto error; + /* Check if any children have free variables */ + if (entry->ste_free || entry->ste_child_free) + ste->ste_child_free = 1; + } + + temp = PyNumber_InPlaceOr(newfree, allfree); + if (!temp) + goto error; + Py_DECREF(temp); + + /* Check if any local variables must be converted to cell variables */ + if (ste->ste_type == FunctionBlock && !analyze_cells(scopes, newfree, + NULL)) + goto error; + else if (ste->ste_type == ClassBlock && !analyze_cells(scopes, newfree, + "__class__")) + goto error; + /* Records the results of the analysis in the symbol table entry */ + if (!update_symbols(ste->ste_symbols, scopes, bound, newfree, + ste->ste_type == ClassBlock)) + goto error; + if (!check_unoptimized(ste)) + goto error; + + temp = PyNumber_InPlaceOr(free, newfree); + if (!temp) + goto error; + Py_DECREF(temp); + success = 1; error: - Py_XDECREF(scopes); - Py_XDECREF(local); - Py_XDECREF(newbound); - Py_XDECREF(newglobal); - Py_XDECREF(newfree); - Py_XDECREF(allfree); - if (!success) - assert(PyErr_Occurred()); - return success; + Py_XDECREF(scopes); + Py_XDECREF(local); + Py_XDECREF(newbound); + Py_XDECREF(newglobal); + Py_XDECREF(newfree); + Py_XDECREF(allfree); + if (!success) + assert(PyErr_Occurred()); + return success; } static int -analyze_child_block(PySTEntryObject *entry, PyObject *bound, PyObject *free, - PyObject *global, PyObject* child_free) -{ - PyObject *temp_bound = NULL, *temp_global = NULL, *temp_free = NULL; - PyObject *temp; - - /* Copy the bound and global dictionaries. - - These dictionary are used by all blocks enclosed by the - current block. The analyze_block() call modifies these - dictionaries. - - */ - temp_bound = PySet_New(bound); - if (!temp_bound) - goto error; - temp_free = PySet_New(free); - if (!temp_free) - goto error; - temp_global = PySet_New(global); - if (!temp_global) - goto error; - - if (!analyze_block(entry, temp_bound, temp_free, temp_global)) - goto error; - temp = PyNumber_InPlaceOr(child_free, temp_free); - if (!temp) - goto error; - Py_DECREF(temp); - Py_DECREF(temp_bound); - Py_DECREF(temp_free); - Py_DECREF(temp_global); - return 1; +analyze_child_block(PySTEntryObject *entry, PyObject *bound, PyObject *free, + PyObject *global, PyObject* child_free) +{ + PyObject *temp_bound = NULL, *temp_global = NULL, *temp_free = NULL; + PyObject *temp; + + /* Copy the bound and global dictionaries. + + These dictionary are used by all blocks enclosed by the + current block. The analyze_block() call modifies these + dictionaries. + + */ + temp_bound = PySet_New(bound); + if (!temp_bound) + goto error; + temp_free = PySet_New(free); + if (!temp_free) + goto error; + temp_global = PySet_New(global); + if (!temp_global) + goto error; + + if (!analyze_block(entry, temp_bound, temp_free, temp_global)) + goto error; + temp = PyNumber_InPlaceOr(child_free, temp_free); + if (!temp) + goto error; + Py_DECREF(temp); + Py_DECREF(temp_bound); + Py_DECREF(temp_free); + Py_DECREF(temp_global); + return 1; error: - Py_XDECREF(temp_bound); - Py_XDECREF(temp_free); - Py_XDECREF(temp_global); - return 0; + Py_XDECREF(temp_bound); + Py_XDECREF(temp_free); + Py_XDECREF(temp_global); + return 0; } static int symtable_analyze(struct symtable *st) { - PyObject *free, *global; - int r; + PyObject *free, *global; + int r; - free = PySet_New(NULL); - if (!free) - return 0; - global = PySet_New(NULL); - if (!global) { - Py_DECREF(free); - return 0; - } - r = analyze_block(st->st_top, NULL, free, global); - Py_DECREF(free); - Py_DECREF(global); - return r; + free = PySet_New(NULL); + if (!free) + return 0; + global = PySet_New(NULL); + if (!global) { + Py_DECREF(free); + return 0; + } + r = analyze_block(st->st_top, NULL, free, global); + Py_DECREF(free); + Py_DECREF(global); + return r; } static int symtable_warn(struct symtable *st, char *msg, int lineno) { - if (PyErr_WarnExplicit(PyExc_SyntaxWarning, msg, st->st_filename, - lineno, NULL, NULL) < 0) { - if (PyErr_ExceptionMatches(PyExc_SyntaxWarning)) { - PyErr_SetString(PyExc_SyntaxError, msg); - PyErr_SyntaxLocation(st->st_filename, - st->st_cur->ste_lineno); - } - return 0; - } - return 1; + if (PyErr_WarnExplicit(PyExc_SyntaxWarning, msg, st->st_filename, + lineno, NULL, NULL) < 0) { + if (PyErr_ExceptionMatches(PyExc_SyntaxWarning)) { + PyErr_SetString(PyExc_SyntaxError, msg); + PyErr_SyntaxLocation(st->st_filename, + st->st_cur->ste_lineno); + } + return 0; + } + return 1; } /* symtable_enter_block() gets a reference via ste_new. @@ -889,792 +889,792 @@ static int symtable_exit_block(struct symtable *st, void *ast) { - Py_ssize_t end; + Py_ssize_t end; - Py_CLEAR(st->st_cur); - end = PyList_GET_SIZE(st->st_stack) - 1; - if (end >= 0) { - st->st_cur = (PySTEntryObject *)PyList_GET_ITEM(st->st_stack, - end); - if (st->st_cur == NULL) - return 0; - Py_INCREF(st->st_cur); - if (PySequence_DelItem(st->st_stack, end) < 0) - return 0; - } - return 1; + Py_CLEAR(st->st_cur); + end = PyList_GET_SIZE(st->st_stack) - 1; + if (end >= 0) { + st->st_cur = (PySTEntryObject *)PyList_GET_ITEM(st->st_stack, + end); + if (st->st_cur == NULL) + return 0; + Py_INCREF(st->st_cur); + if (PySequence_DelItem(st->st_stack, end) < 0) + return 0; + } + return 1; } static int -symtable_enter_block(struct symtable *st, identifier name, _Py_block_ty block, - void *ast, int lineno) -{ - PySTEntryObject *prev = NULL; - - if (st->st_cur) { - prev = st->st_cur; - if (PyList_Append(st->st_stack, (PyObject *)st->st_cur) < 0) { - return 0; - } - Py_DECREF(st->st_cur); - } - st->st_cur = ste_new(st, name, block, ast, lineno); - if (st->st_cur == NULL) - return 0; - if (name == GET_IDENTIFIER(top)) - st->st_global = st->st_cur->ste_symbols; - if (prev) { - if (PyList_Append(prev->ste_children, - (PyObject *)st->st_cur) < 0) { - return 0; - } - } - return 1; +symtable_enter_block(struct symtable *st, identifier name, _Py_block_ty block, + void *ast, int lineno) +{ + PySTEntryObject *prev = NULL; + + if (st->st_cur) { + prev = st->st_cur; + if (PyList_Append(st->st_stack, (PyObject *)st->st_cur) < 0) { + return 0; + } + Py_DECREF(st->st_cur); + } + st->st_cur = ste_new(st, name, block, ast, lineno); + if (st->st_cur == NULL) + return 0; + if (name == GET_IDENTIFIER(top)) + st->st_global = st->st_cur->ste_symbols; + if (prev) { + if (PyList_Append(prev->ste_children, + (PyObject *)st->st_cur) < 0) { + return 0; + } + } + return 1; } static long symtable_lookup(struct symtable *st, PyObject *name) { - PyObject *o; - PyObject *mangled = _Py_Mangle(st->st_private, name); - if (!mangled) - return 0; - o = PyDict_GetItem(st->st_cur->ste_symbols, mangled); - Py_DECREF(mangled); - if (!o) - return 0; - return PyLong_AsLong(o); + PyObject *o; + PyObject *mangled = _Py_Mangle(st->st_private, name); + if (!mangled) + return 0; + o = PyDict_GetItem(st->st_cur->ste_symbols, mangled); + Py_DECREF(mangled); + if (!o) + return 0; + return PyLong_AsLong(o); } static int -symtable_add_def(struct symtable *st, PyObject *name, int flag) -{ - PyObject *o; - PyObject *dict; - long val; - PyObject *mangled = _Py_Mangle(st->st_private, name); - - - if (!mangled) - return 0; - dict = st->st_cur->ste_symbols; - if ((o = PyDict_GetItem(dict, mangled))) { - val = PyLong_AS_LONG(o); - if ((flag & DEF_PARAM) && (val & DEF_PARAM)) { - /* Is it better to use 'mangled' or 'name' here? */ - PyErr_Format(PyExc_SyntaxError, DUPLICATE_ARGUMENT, name); - PyErr_SyntaxLocation(st->st_filename, - st->st_cur->ste_lineno); - goto error; - } - val |= flag; - } else - val = flag; - o = PyLong_FromLong(val); +symtable_add_def(struct symtable *st, PyObject *name, int flag) +{ + PyObject *o; + PyObject *dict; + long val; + PyObject *mangled = _Py_Mangle(st->st_private, name); + + + if (!mangled) + return 0; + dict = st->st_cur->ste_symbols; + if ((o = PyDict_GetItem(dict, mangled))) { + val = PyLong_AS_LONG(o); + if ((flag & DEF_PARAM) && (val & DEF_PARAM)) { + /* Is it better to use 'mangled' or 'name' here? */ + PyErr_Format(PyExc_SyntaxError, DUPLICATE_ARGUMENT, name); + PyErr_SyntaxLocation(st->st_filename, + st->st_cur->ste_lineno); + goto error; + } + val |= flag; + } else + val = flag; + o = PyLong_FromLong(val); + if (o == NULL) + goto error; + if (PyDict_SetItem(dict, mangled, o) < 0) { + Py_DECREF(o); + goto error; + } + Py_DECREF(o); + + if (flag & DEF_PARAM) { + if (PyList_Append(st->st_cur->ste_varnames, mangled) < 0) + goto error; + } else if (flag & DEF_GLOBAL) { + /* XXX need to update DEF_GLOBAL for other flags too; + perhaps only DEF_FREE_GLOBAL */ + val = flag; + if ((o = PyDict_GetItem(st->st_global, mangled))) { + val |= PyLong_AS_LONG(o); + } + o = PyLong_FromLong(val); if (o == NULL) - goto error; - if (PyDict_SetItem(dict, mangled, o) < 0) { - Py_DECREF(o); - goto error; - } - Py_DECREF(o); - - if (flag & DEF_PARAM) { - if (PyList_Append(st->st_cur->ste_varnames, mangled) < 0) - goto error; - } else if (flag & DEF_GLOBAL) { - /* XXX need to update DEF_GLOBAL for other flags too; - perhaps only DEF_FREE_GLOBAL */ - val = flag; - if ((o = PyDict_GetItem(st->st_global, mangled))) { - val |= PyLong_AS_LONG(o); - } - o = PyLong_FromLong(val); - if (o == NULL) - goto error; - if (PyDict_SetItem(st->st_global, mangled, o) < 0) { - Py_DECREF(o); - goto error; - } - Py_DECREF(o); - } - Py_DECREF(mangled); - return 1; + goto error; + if (PyDict_SetItem(st->st_global, mangled, o) < 0) { + Py_DECREF(o); + goto error; + } + Py_DECREF(o); + } + Py_DECREF(mangled); + return 1; error: - Py_DECREF(mangled); - return 0; + Py_DECREF(mangled); + return 0; } /* VISIT, VISIT_SEQ and VIST_SEQ_TAIL take an ASDL type as their second argument. They use the ASDL name to synthesize the name of the C type and the visit - function. - + function. + VISIT_SEQ_TAIL permits the start of an ASDL sequence to be skipped, which is useful if the first node in the sequence requires special treatment. */ #define VISIT(ST, TYPE, V) \ - if (!symtable_visit_ ## TYPE((ST), (V))) \ - return 0; + if (!symtable_visit_ ## TYPE((ST), (V))) \ + return 0; #define VISIT_IN_BLOCK(ST, TYPE, V, S) \ - if (!symtable_visit_ ## TYPE((ST), (V))) { \ - symtable_exit_block((ST), (S)); \ - return 0; \ - } + if (!symtable_visit_ ## TYPE((ST), (V))) { \ + symtable_exit_block((ST), (S)); \ + return 0; \ + } #define VISIT_SEQ(ST, TYPE, SEQ) { \ - int i; \ - asdl_seq *seq = (SEQ); /* avoid variable capture */ \ - for (i = 0; i < asdl_seq_LEN(seq); i++) { \ - TYPE ## _ty elt = (TYPE ## _ty)asdl_seq_GET(seq, i); \ - if (!symtable_visit_ ## TYPE((ST), elt)) \ - return 0; \ - } \ + int i; \ + asdl_seq *seq = (SEQ); /* avoid variable capture */ \ + for (i = 0; i < asdl_seq_LEN(seq); i++) { \ + TYPE ## _ty elt = (TYPE ## _ty)asdl_seq_GET(seq, i); \ + if (!symtable_visit_ ## TYPE((ST), elt)) \ + return 0; \ + } \ } #define VISIT_SEQ_IN_BLOCK(ST, TYPE, SEQ, S) { \ - int i; \ - asdl_seq *seq = (SEQ); /* avoid variable capture */ \ - for (i = 0; i < asdl_seq_LEN(seq); i++) { \ - TYPE ## _ty elt = (TYPE ## _ty)asdl_seq_GET(seq, i); \ - if (!symtable_visit_ ## TYPE((ST), elt)) { \ - symtable_exit_block((ST), (S)); \ - return 0; \ - } \ - } \ + int i; \ + asdl_seq *seq = (SEQ); /* avoid variable capture */ \ + for (i = 0; i < asdl_seq_LEN(seq); i++) { \ + TYPE ## _ty elt = (TYPE ## _ty)asdl_seq_GET(seq, i); \ + if (!symtable_visit_ ## TYPE((ST), elt)) { \ + symtable_exit_block((ST), (S)); \ + return 0; \ + } \ + } \ } #define VISIT_SEQ_TAIL(ST, TYPE, SEQ, START) { \ - int i; \ - asdl_seq *seq = (SEQ); /* avoid variable capture */ \ - for (i = (START); i < asdl_seq_LEN(seq); i++) { \ - TYPE ## _ty elt = (TYPE ## _ty)asdl_seq_GET(seq, i); \ - if (!symtable_visit_ ## TYPE((ST), elt)) \ - return 0; \ - } \ + int i; \ + asdl_seq *seq = (SEQ); /* avoid variable capture */ \ + for (i = (START); i < asdl_seq_LEN(seq); i++) { \ + TYPE ## _ty elt = (TYPE ## _ty)asdl_seq_GET(seq, i); \ + if (!symtable_visit_ ## TYPE((ST), elt)) \ + return 0; \ + } \ } #define VISIT_SEQ_TAIL_IN_BLOCK(ST, TYPE, SEQ, START, S) { \ - int i; \ - asdl_seq *seq = (SEQ); /* avoid variable capture */ \ - for (i = (START); i < asdl_seq_LEN(seq); i++) { \ - TYPE ## _ty elt = (TYPE ## _ty)asdl_seq_GET(seq, i); \ - if (!symtable_visit_ ## TYPE((ST), elt)) { \ - symtable_exit_block((ST), (S)); \ - return 0; \ - } \ - } \ + int i; \ + asdl_seq *seq = (SEQ); /* avoid variable capture */ \ + for (i = (START); i < asdl_seq_LEN(seq); i++) { \ + TYPE ## _ty elt = (TYPE ## _ty)asdl_seq_GET(seq, i); \ + if (!symtable_visit_ ## TYPE((ST), elt)) { \ + symtable_exit_block((ST), (S)); \ + return 0; \ + } \ + } \ } #define VISIT_KWONLYDEFAULTS(ST, KW_DEFAULTS) { \ - int i = 0; \ - asdl_seq *seq = (KW_DEFAULTS); /* avoid variable capture */ \ - for (i = 0; i < asdl_seq_LEN(seq); i++) { \ - expr_ty elt = (expr_ty)asdl_seq_GET(seq, i); \ - if (!elt) continue; /* can be NULL */ \ - if (!symtable_visit_expr((ST), elt)) \ - return 0; \ - } \ + int i = 0; \ + asdl_seq *seq = (KW_DEFAULTS); /* avoid variable capture */ \ + for (i = 0; i < asdl_seq_LEN(seq); i++) { \ + expr_ty elt = (expr_ty)asdl_seq_GET(seq, i); \ + if (!elt) continue; /* can be NULL */ \ + if (!symtable_visit_expr((ST), elt)) \ + return 0; \ + } \ } static int symtable_new_tmpname(struct symtable *st) { - char tmpname[256]; - identifier tmp; + char tmpname[256]; + identifier tmp; - PyOS_snprintf(tmpname, sizeof(tmpname), "_[%d]", - ++st->st_cur->ste_tmpname); - tmp = PyUnicode_InternFromString(tmpname); - if (!tmp) - return 0; - if (!symtable_add_def(st, tmp, DEF_LOCAL)) - return 0; - Py_DECREF(tmp); - return 1; + PyOS_snprintf(tmpname, sizeof(tmpname), "_[%d]", + ++st->st_cur->ste_tmpname); + tmp = PyUnicode_InternFromString(tmpname); + if (!tmp) + return 0; + if (!symtable_add_def(st, tmp, DEF_LOCAL)) + return 0; + Py_DECREF(tmp); + return 1; } static int symtable_visit_stmt(struct symtable *st, stmt_ty s) { - switch (s->kind) { - case FunctionDef_kind: - if (!symtable_add_def(st, s->v.FunctionDef.name, DEF_LOCAL)) - return 0; - if (s->v.FunctionDef.args->defaults) - VISIT_SEQ(st, expr, s->v.FunctionDef.args->defaults); - if (s->v.FunctionDef.args->kw_defaults) - VISIT_KWONLYDEFAULTS(st, - s->v.FunctionDef.args->kw_defaults); - if (!symtable_visit_annotations(st, s)) - return 0; - if (s->v.FunctionDef.decorator_list) - VISIT_SEQ(st, expr, s->v.FunctionDef.decorator_list); - if (!symtable_enter_block(st, s->v.FunctionDef.name, - FunctionBlock, (void *)s, s->lineno)) - return 0; - VISIT_IN_BLOCK(st, arguments, s->v.FunctionDef.args, s); - VISIT_SEQ_IN_BLOCK(st, stmt, s->v.FunctionDef.body, s); - if (!symtable_exit_block(st, s)) - return 0; - break; - case ClassDef_kind: { - PyObject *tmp; - if (!symtable_add_def(st, s->v.ClassDef.name, DEF_LOCAL)) - return 0; - VISIT_SEQ(st, expr, s->v.ClassDef.bases); - VISIT_SEQ(st, keyword, s->v.ClassDef.keywords); - if (s->v.ClassDef.starargs) - VISIT(st, expr, s->v.ClassDef.starargs); - if (s->v.ClassDef.kwargs) - VISIT(st, expr, s->v.ClassDef.kwargs); - if (s->v.ClassDef.decorator_list) - VISIT_SEQ(st, expr, s->v.ClassDef.decorator_list); - if (!symtable_enter_block(st, s->v.ClassDef.name, ClassBlock, - (void *)s, s->lineno)) - return 0; - if (!GET_IDENTIFIER(__class__) || - !symtable_add_def(st, __class__, DEF_LOCAL) || - !GET_IDENTIFIER(__locals__) || - !symtable_add_def(st, __locals__, DEF_PARAM)) { - symtable_exit_block(st, s); - return 0; - } - tmp = st->st_private; - st->st_private = s->v.ClassDef.name; - VISIT_SEQ_IN_BLOCK(st, stmt, s->v.ClassDef.body, s); - st->st_private = tmp; - if (!symtable_exit_block(st, s)) - return 0; - break; - } - case Return_kind: - if (s->v.Return.value) { - VISIT(st, expr, s->v.Return.value); - st->st_cur->ste_returns_value = 1; - if (st->st_cur->ste_generator) { - PyErr_SetString(PyExc_SyntaxError, - RETURN_VAL_IN_GENERATOR); - PyErr_SyntaxLocation(st->st_filename, - s->lineno); - return 0; - } - } - break; - case Delete_kind: - VISIT_SEQ(st, expr, s->v.Delete.targets); - break; - case Assign_kind: - VISIT_SEQ(st, expr, s->v.Assign.targets); - VISIT(st, expr, s->v.Assign.value); - break; - case AugAssign_kind: - VISIT(st, expr, s->v.AugAssign.target); - VISIT(st, expr, s->v.AugAssign.value); - break; - case For_kind: - VISIT(st, expr, s->v.For.target); - VISIT(st, expr, s->v.For.iter); - VISIT_SEQ(st, stmt, s->v.For.body); - if (s->v.For.orelse) - VISIT_SEQ(st, stmt, s->v.For.orelse); - break; - case While_kind: - VISIT(st, expr, s->v.While.test); - VISIT_SEQ(st, stmt, s->v.While.body); - if (s->v.While.orelse) - VISIT_SEQ(st, stmt, s->v.While.orelse); - break; - case If_kind: - /* XXX if 0: and lookup_yield() hacks */ - VISIT(st, expr, s->v.If.test); - VISIT_SEQ(st, stmt, s->v.If.body); - if (s->v.If.orelse) - VISIT_SEQ(st, stmt, s->v.If.orelse); - break; - case Raise_kind: - if (s->v.Raise.exc) { - VISIT(st, expr, s->v.Raise.exc); - if (s->v.Raise.cause) { - VISIT(st, expr, s->v.Raise.cause); + switch (s->kind) { + case FunctionDef_kind: + if (!symtable_add_def(st, s->v.FunctionDef.name, DEF_LOCAL)) + return 0; + if (s->v.FunctionDef.args->defaults) + VISIT_SEQ(st, expr, s->v.FunctionDef.args->defaults); + if (s->v.FunctionDef.args->kw_defaults) + VISIT_KWONLYDEFAULTS(st, + s->v.FunctionDef.args->kw_defaults); + if (!symtable_visit_annotations(st, s)) + return 0; + if (s->v.FunctionDef.decorator_list) + VISIT_SEQ(st, expr, s->v.FunctionDef.decorator_list); + if (!symtable_enter_block(st, s->v.FunctionDef.name, + FunctionBlock, (void *)s, s->lineno)) + return 0; + VISIT_IN_BLOCK(st, arguments, s->v.FunctionDef.args, s); + VISIT_SEQ_IN_BLOCK(st, stmt, s->v.FunctionDef.body, s); + if (!symtable_exit_block(st, s)) + return 0; + break; + case ClassDef_kind: { + PyObject *tmp; + if (!symtable_add_def(st, s->v.ClassDef.name, DEF_LOCAL)) + return 0; + VISIT_SEQ(st, expr, s->v.ClassDef.bases); + VISIT_SEQ(st, keyword, s->v.ClassDef.keywords); + if (s->v.ClassDef.starargs) + VISIT(st, expr, s->v.ClassDef.starargs); + if (s->v.ClassDef.kwargs) + VISIT(st, expr, s->v.ClassDef.kwargs); + if (s->v.ClassDef.decorator_list) + VISIT_SEQ(st, expr, s->v.ClassDef.decorator_list); + if (!symtable_enter_block(st, s->v.ClassDef.name, ClassBlock, + (void *)s, s->lineno)) + return 0; + if (!GET_IDENTIFIER(__class__) || + !symtable_add_def(st, __class__, DEF_LOCAL) || + !GET_IDENTIFIER(__locals__) || + !symtable_add_def(st, __locals__, DEF_PARAM)) { + symtable_exit_block(st, s); + return 0; + } + tmp = st->st_private; + st->st_private = s->v.ClassDef.name; + VISIT_SEQ_IN_BLOCK(st, stmt, s->v.ClassDef.body, s); + st->st_private = tmp; + if (!symtable_exit_block(st, s)) + return 0; + break; + } + case Return_kind: + if (s->v.Return.value) { + VISIT(st, expr, s->v.Return.value); + st->st_cur->ste_returns_value = 1; + if (st->st_cur->ste_generator) { + PyErr_SetString(PyExc_SyntaxError, + RETURN_VAL_IN_GENERATOR); + PyErr_SyntaxLocation(st->st_filename, + s->lineno); + return 0; } - } - break; - case TryExcept_kind: - VISIT_SEQ(st, stmt, s->v.TryExcept.body); - VISIT_SEQ(st, stmt, s->v.TryExcept.orelse); - VISIT_SEQ(st, excepthandler, s->v.TryExcept.handlers); - break; - case TryFinally_kind: - VISIT_SEQ(st, stmt, s->v.TryFinally.body); - VISIT_SEQ(st, stmt, s->v.TryFinally.finalbody); - break; - case Assert_kind: - VISIT(st, expr, s->v.Assert.test); - if (s->v.Assert.msg) - VISIT(st, expr, s->v.Assert.msg); - break; - case Import_kind: - VISIT_SEQ(st, alias, s->v.Import.names); - /* XXX Don't have the lineno available inside - visit_alias */ - if (st->st_cur->ste_unoptimized && !st->st_cur->ste_opt_lineno) - st->st_cur->ste_opt_lineno = s->lineno; - break; - case ImportFrom_kind: - VISIT_SEQ(st, alias, s->v.ImportFrom.names); - /* XXX Don't have the lineno available inside - visit_alias */ - if (st->st_cur->ste_unoptimized && !st->st_cur->ste_opt_lineno) - st->st_cur->ste_opt_lineno = s->lineno; - break; - case Global_kind: { - int i; - asdl_seq *seq = s->v.Global.names; - for (i = 0; i < asdl_seq_LEN(seq); i++) { - identifier name = (identifier)asdl_seq_GET(seq, i); - char *c_name = _PyUnicode_AsString(name); - long cur = symtable_lookup(st, name); - if (cur < 0) - return 0; - if (cur & (DEF_LOCAL | USE)) { - char buf[256]; - if (cur & DEF_LOCAL) - PyOS_snprintf(buf, sizeof(buf), - GLOBAL_AFTER_ASSIGN, - c_name); - else - PyOS_snprintf(buf, sizeof(buf), - GLOBAL_AFTER_USE, - c_name); - if (!symtable_warn(st, buf, s->lineno)) - return 0; - } - if (!symtable_add_def(st, name, DEF_GLOBAL)) - return 0; - } - break; - } - case Nonlocal_kind: { - int i; - asdl_seq *seq = s->v.Nonlocal.names; - for (i = 0; i < asdl_seq_LEN(seq); i++) { - identifier name = (identifier)asdl_seq_GET(seq, i); - char *c_name = _PyUnicode_AsString(name); - long cur = symtable_lookup(st, name); - if (cur < 0) - return 0; - if (cur & (DEF_LOCAL | USE)) { - char buf[256]; - if (cur & DEF_LOCAL) - PyOS_snprintf(buf, sizeof(buf), - NONLOCAL_AFTER_ASSIGN, - c_name); - else - PyOS_snprintf(buf, sizeof(buf), - NONLOCAL_AFTER_USE, - c_name); - if (!symtable_warn(st, buf, s->lineno)) - return 0; - } - if (!symtable_add_def(st, name, DEF_NONLOCAL)) - return 0; - } - break; - } - case Expr_kind: - VISIT(st, expr, s->v.Expr.value); - break; - case Pass_kind: - case Break_kind: - case Continue_kind: - /* nothing to do here */ - break; - case With_kind: - VISIT(st, expr, s->v.With.context_expr); - if (s->v.With.optional_vars) { - VISIT(st, expr, s->v.With.optional_vars); - } - VISIT_SEQ(st, stmt, s->v.With.body); - break; - } - return 1; + } + break; + case Delete_kind: + VISIT_SEQ(st, expr, s->v.Delete.targets); + break; + case Assign_kind: + VISIT_SEQ(st, expr, s->v.Assign.targets); + VISIT(st, expr, s->v.Assign.value); + break; + case AugAssign_kind: + VISIT(st, expr, s->v.AugAssign.target); + VISIT(st, expr, s->v.AugAssign.value); + break; + case For_kind: + VISIT(st, expr, s->v.For.target); + VISIT(st, expr, s->v.For.iter); + VISIT_SEQ(st, stmt, s->v.For.body); + if (s->v.For.orelse) + VISIT_SEQ(st, stmt, s->v.For.orelse); + break; + case While_kind: + VISIT(st, expr, s->v.While.test); + VISIT_SEQ(st, stmt, s->v.While.body); + if (s->v.While.orelse) + VISIT_SEQ(st, stmt, s->v.While.orelse); + break; + case If_kind: + /* XXX if 0: and lookup_yield() hacks */ + VISIT(st, expr, s->v.If.test); + VISIT_SEQ(st, stmt, s->v.If.body); + if (s->v.If.orelse) + VISIT_SEQ(st, stmt, s->v.If.orelse); + break; + case Raise_kind: + if (s->v.Raise.exc) { + VISIT(st, expr, s->v.Raise.exc); + if (s->v.Raise.cause) { + VISIT(st, expr, s->v.Raise.cause); + } + } + break; + case TryExcept_kind: + VISIT_SEQ(st, stmt, s->v.TryExcept.body); + VISIT_SEQ(st, stmt, s->v.TryExcept.orelse); + VISIT_SEQ(st, excepthandler, s->v.TryExcept.handlers); + break; + case TryFinally_kind: + VISIT_SEQ(st, stmt, s->v.TryFinally.body); + VISIT_SEQ(st, stmt, s->v.TryFinally.finalbody); + break; + case Assert_kind: + VISIT(st, expr, s->v.Assert.test); + if (s->v.Assert.msg) + VISIT(st, expr, s->v.Assert.msg); + break; + case Import_kind: + VISIT_SEQ(st, alias, s->v.Import.names); + /* XXX Don't have the lineno available inside + visit_alias */ + if (st->st_cur->ste_unoptimized && !st->st_cur->ste_opt_lineno) + st->st_cur->ste_opt_lineno = s->lineno; + break; + case ImportFrom_kind: + VISIT_SEQ(st, alias, s->v.ImportFrom.names); + /* XXX Don't have the lineno available inside + visit_alias */ + if (st->st_cur->ste_unoptimized && !st->st_cur->ste_opt_lineno) + st->st_cur->ste_opt_lineno = s->lineno; + break; + case Global_kind: { + int i; + asdl_seq *seq = s->v.Global.names; + for (i = 0; i < asdl_seq_LEN(seq); i++) { + identifier name = (identifier)asdl_seq_GET(seq, i); + char *c_name = _PyUnicode_AsString(name); + long cur = symtable_lookup(st, name); + if (cur < 0) + return 0; + if (cur & (DEF_LOCAL | USE)) { + char buf[256]; + if (cur & DEF_LOCAL) + PyOS_snprintf(buf, sizeof(buf), + GLOBAL_AFTER_ASSIGN, + c_name); + else + PyOS_snprintf(buf, sizeof(buf), + GLOBAL_AFTER_USE, + c_name); + if (!symtable_warn(st, buf, s->lineno)) + return 0; + } + if (!symtable_add_def(st, name, DEF_GLOBAL)) + return 0; + } + break; + } + case Nonlocal_kind: { + int i; + asdl_seq *seq = s->v.Nonlocal.names; + for (i = 0; i < asdl_seq_LEN(seq); i++) { + identifier name = (identifier)asdl_seq_GET(seq, i); + char *c_name = _PyUnicode_AsString(name); + long cur = symtable_lookup(st, name); + if (cur < 0) + return 0; + if (cur & (DEF_LOCAL | USE)) { + char buf[256]; + if (cur & DEF_LOCAL) + PyOS_snprintf(buf, sizeof(buf), + NONLOCAL_AFTER_ASSIGN, + c_name); + else + PyOS_snprintf(buf, sizeof(buf), + NONLOCAL_AFTER_USE, + c_name); + if (!symtable_warn(st, buf, s->lineno)) + return 0; + } + if (!symtable_add_def(st, name, DEF_NONLOCAL)) + return 0; + } + break; + } + case Expr_kind: + VISIT(st, expr, s->v.Expr.value); + break; + case Pass_kind: + case Break_kind: + case Continue_kind: + /* nothing to do here */ + break; + case With_kind: + VISIT(st, expr, s->v.With.context_expr); + if (s->v.With.optional_vars) { + VISIT(st, expr, s->v.With.optional_vars); + } + VISIT_SEQ(st, stmt, s->v.With.body); + break; + } + return 1; } -static int +static int symtable_visit_expr(struct symtable *st, expr_ty e) { - switch (e->kind) { - case BoolOp_kind: - VISIT_SEQ(st, expr, e->v.BoolOp.values); - break; - case BinOp_kind: - VISIT(st, expr, e->v.BinOp.left); - VISIT(st, expr, e->v.BinOp.right); - break; - case UnaryOp_kind: - VISIT(st, expr, e->v.UnaryOp.operand); - break; - case Lambda_kind: { - if (!GET_IDENTIFIER(lambda)) - return 0; - if (e->v.Lambda.args->defaults) - VISIT_SEQ(st, expr, e->v.Lambda.args->defaults); - if (!symtable_enter_block(st, lambda, - FunctionBlock, (void *)e, e->lineno)) - return 0; - VISIT_IN_BLOCK(st, arguments, e->v.Lambda.args, (void*)e); - VISIT_IN_BLOCK(st, expr, e->v.Lambda.body, (void*)e); - if (!symtable_exit_block(st, (void *)e)) - return 0; - break; - } - case IfExp_kind: - VISIT(st, expr, e->v.IfExp.test); - VISIT(st, expr, e->v.IfExp.body); - VISIT(st, expr, e->v.IfExp.orelse); - break; - case Dict_kind: - VISIT_SEQ(st, expr, e->v.Dict.keys); - VISIT_SEQ(st, expr, e->v.Dict.values); - break; - case Set_kind: - VISIT_SEQ(st, expr, e->v.Set.elts); - break; - case GeneratorExp_kind: - if (!symtable_visit_genexp(st, e)) - return 0; - break; - case ListComp_kind: - if (!symtable_visit_listcomp(st, e)) - return 0; - break; - case SetComp_kind: - if (!symtable_visit_setcomp(st, e)) - return 0; - break; - case DictComp_kind: - if (!symtable_visit_dictcomp(st, e)) - return 0; - break; - case Yield_kind: - if (e->v.Yield.value) - VISIT(st, expr, e->v.Yield.value); - st->st_cur->ste_generator = 1; - if (st->st_cur->ste_returns_value) { - PyErr_SetString(PyExc_SyntaxError, - RETURN_VAL_IN_GENERATOR); - PyErr_SyntaxLocation(st->st_filename, - e->lineno); - return 0; - } - break; - case Compare_kind: - VISIT(st, expr, e->v.Compare.left); - VISIT_SEQ(st, expr, e->v.Compare.comparators); - break; - case Call_kind: - VISIT(st, expr, e->v.Call.func); - VISIT_SEQ(st, expr, e->v.Call.args); - VISIT_SEQ(st, keyword, e->v.Call.keywords); - if (e->v.Call.starargs) - VISIT(st, expr, e->v.Call.starargs); - if (e->v.Call.kwargs) - VISIT(st, expr, e->v.Call.kwargs); - break; - case Num_kind: - case Str_kind: - case Bytes_kind: - case Ellipsis_kind: - /* Nothing to do here. */ - break; - /* The following exprs can be assignment targets. */ - case Attribute_kind: - VISIT(st, expr, e->v.Attribute.value); - break; - case Subscript_kind: - VISIT(st, expr, e->v.Subscript.value); - VISIT(st, slice, e->v.Subscript.slice); - break; - case Starred_kind: - VISIT(st, expr, e->v.Starred.value); - break; - case Name_kind: - if (!symtable_add_def(st, e->v.Name.id, - e->v.Name.ctx == Load ? USE : DEF_LOCAL)) - return 0; - /* Special-case super: it counts as a use of __class__ */ - if (e->v.Name.ctx == Load && - st->st_cur->ste_type == FunctionBlock && - !PyUnicode_CompareWithASCIIString(e->v.Name.id, "super")) { - if (!GET_IDENTIFIER(__class__) || - !symtable_add_def(st, __class__, USE)) - return 0; - } - break; - /* child nodes of List and Tuple will have expr_context set */ - case List_kind: - VISIT_SEQ(st, expr, e->v.List.elts); - break; - case Tuple_kind: - VISIT_SEQ(st, expr, e->v.Tuple.elts); - break; - } - return 1; + switch (e->kind) { + case BoolOp_kind: + VISIT_SEQ(st, expr, e->v.BoolOp.values); + break; + case BinOp_kind: + VISIT(st, expr, e->v.BinOp.left); + VISIT(st, expr, e->v.BinOp.right); + break; + case UnaryOp_kind: + VISIT(st, expr, e->v.UnaryOp.operand); + break; + case Lambda_kind: { + if (!GET_IDENTIFIER(lambda)) + return 0; + if (e->v.Lambda.args->defaults) + VISIT_SEQ(st, expr, e->v.Lambda.args->defaults); + if (!symtable_enter_block(st, lambda, + FunctionBlock, (void *)e, e->lineno)) + return 0; + VISIT_IN_BLOCK(st, arguments, e->v.Lambda.args, (void*)e); + VISIT_IN_BLOCK(st, expr, e->v.Lambda.body, (void*)e); + if (!symtable_exit_block(st, (void *)e)) + return 0; + break; + } + case IfExp_kind: + VISIT(st, expr, e->v.IfExp.test); + VISIT(st, expr, e->v.IfExp.body); + VISIT(st, expr, e->v.IfExp.orelse); + break; + case Dict_kind: + VISIT_SEQ(st, expr, e->v.Dict.keys); + VISIT_SEQ(st, expr, e->v.Dict.values); + break; + case Set_kind: + VISIT_SEQ(st, expr, e->v.Set.elts); + break; + case GeneratorExp_kind: + if (!symtable_visit_genexp(st, e)) + return 0; + break; + case ListComp_kind: + if (!symtable_visit_listcomp(st, e)) + return 0; + break; + case SetComp_kind: + if (!symtable_visit_setcomp(st, e)) + return 0; + break; + case DictComp_kind: + if (!symtable_visit_dictcomp(st, e)) + return 0; + break; + case Yield_kind: + if (e->v.Yield.value) + VISIT(st, expr, e->v.Yield.value); + st->st_cur->ste_generator = 1; + if (st->st_cur->ste_returns_value) { + PyErr_SetString(PyExc_SyntaxError, + RETURN_VAL_IN_GENERATOR); + PyErr_SyntaxLocation(st->st_filename, + e->lineno); + return 0; + } + break; + case Compare_kind: + VISIT(st, expr, e->v.Compare.left); + VISIT_SEQ(st, expr, e->v.Compare.comparators); + break; + case Call_kind: + VISIT(st, expr, e->v.Call.func); + VISIT_SEQ(st, expr, e->v.Call.args); + VISIT_SEQ(st, keyword, e->v.Call.keywords); + if (e->v.Call.starargs) + VISIT(st, expr, e->v.Call.starargs); + if (e->v.Call.kwargs) + VISIT(st, expr, e->v.Call.kwargs); + break; + case Num_kind: + case Str_kind: + case Bytes_kind: + case Ellipsis_kind: + /* Nothing to do here. */ + break; + /* The following exprs can be assignment targets. */ + case Attribute_kind: + VISIT(st, expr, e->v.Attribute.value); + break; + case Subscript_kind: + VISIT(st, expr, e->v.Subscript.value); + VISIT(st, slice, e->v.Subscript.slice); + break; + case Starred_kind: + VISIT(st, expr, e->v.Starred.value); + break; + case Name_kind: + if (!symtable_add_def(st, e->v.Name.id, + e->v.Name.ctx == Load ? USE : DEF_LOCAL)) + return 0; + /* Special-case super: it counts as a use of __class__ */ + if (e->v.Name.ctx == Load && + st->st_cur->ste_type == FunctionBlock && + !PyUnicode_CompareWithASCIIString(e->v.Name.id, "super")) { + if (!GET_IDENTIFIER(__class__) || + !symtable_add_def(st, __class__, USE)) + return 0; + } + break; + /* child nodes of List and Tuple will have expr_context set */ + case List_kind: + VISIT_SEQ(st, expr, e->v.List.elts); + break; + case Tuple_kind: + VISIT_SEQ(st, expr, e->v.Tuple.elts); + break; + } + return 1; } static int symtable_implicit_arg(struct symtable *st, int pos) { - PyObject *id = PyUnicode_FromFormat(".%d", pos); - if (id == NULL) - return 0; - if (!symtable_add_def(st, id, DEF_PARAM)) { - Py_DECREF(id); - return 0; - } - Py_DECREF(id); - return 1; + PyObject *id = PyUnicode_FromFormat(".%d", pos); + if (id == NULL) + return 0; + if (!symtable_add_def(st, id, DEF_PARAM)) { + Py_DECREF(id); + return 0; + } + Py_DECREF(id); + return 1; } -static int +static int symtable_visit_params(struct symtable *st, asdl_seq *args) { - int i; + int i; + + if (!args) + return -1; - if (!args) - return -1; - - for (i = 0; i < asdl_seq_LEN(args); i++) { - arg_ty arg = (arg_ty)asdl_seq_GET(args, i); - if (!symtable_add_def(st, arg->arg, DEF_PARAM)) - return 0; - } + for (i = 0; i < asdl_seq_LEN(args); i++) { + arg_ty arg = (arg_ty)asdl_seq_GET(args, i); + if (!symtable_add_def(st, arg->arg, DEF_PARAM)) + return 0; + } - return 1; + return 1; } -static int +static int symtable_visit_argannotations(struct symtable *st, asdl_seq *args) { - int i; + int i; + + if (!args) + return -1; - if (!args) - return -1; - - for (i = 0; i < asdl_seq_LEN(args); i++) { - arg_ty arg = (arg_ty)asdl_seq_GET(args, i); - if (arg->annotation) - VISIT(st, expr, arg->annotation); - } + for (i = 0; i < asdl_seq_LEN(args); i++) { + arg_ty arg = (arg_ty)asdl_seq_GET(args, i); + if (arg->annotation) + VISIT(st, expr, arg->annotation); + } - return 1; + return 1; } static int symtable_visit_annotations(struct symtable *st, stmt_ty s) { - arguments_ty a = s->v.FunctionDef.args; - - if (a->args && !symtable_visit_argannotations(st, a->args)) - return 0; - if (a->varargannotation) - VISIT(st, expr, a->varargannotation); - if (a->kwargannotation) - VISIT(st, expr, a->kwargannotation); - if (a->kwonlyargs && !symtable_visit_argannotations(st, a->kwonlyargs)) - return 0; - if (s->v.FunctionDef.returns) - VISIT(st, expr, s->v.FunctionDef.returns); - return 1; + arguments_ty a = s->v.FunctionDef.args; + + if (a->args && !symtable_visit_argannotations(st, a->args)) + return 0; + if (a->varargannotation) + VISIT(st, expr, a->varargannotation); + if (a->kwargannotation) + VISIT(st, expr, a->kwargannotation); + if (a->kwonlyargs && !symtable_visit_argannotations(st, a->kwonlyargs)) + return 0; + if (s->v.FunctionDef.returns) + VISIT(st, expr, s->v.FunctionDef.returns); + return 1; } -static int +static int symtable_visit_arguments(struct symtable *st, arguments_ty a) { - /* skip default arguments inside function block - XXX should ast be different? - */ - if (a->args && !symtable_visit_params(st, a->args)) - return 0; - if (a->kwonlyargs && !symtable_visit_params(st, a->kwonlyargs)) - return 0; - if (a->vararg) { - if (!symtable_add_def(st, a->vararg, DEF_PARAM)) - return 0; - st->st_cur->ste_varargs = 1; - } - if (a->kwarg) { - if (!symtable_add_def(st, a->kwarg, DEF_PARAM)) - return 0; - st->st_cur->ste_varkeywords = 1; - } - return 1; + /* skip default arguments inside function block + XXX should ast be different? + */ + if (a->args && !symtable_visit_params(st, a->args)) + return 0; + if (a->kwonlyargs && !symtable_visit_params(st, a->kwonlyargs)) + return 0; + if (a->vararg) { + if (!symtable_add_def(st, a->vararg, DEF_PARAM)) + return 0; + st->st_cur->ste_varargs = 1; + } + if (a->kwarg) { + if (!symtable_add_def(st, a->kwarg, DEF_PARAM)) + return 0; + st->st_cur->ste_varkeywords = 1; + } + return 1; } -static int +static int symtable_visit_excepthandler(struct symtable *st, excepthandler_ty eh) { - if (eh->v.ExceptHandler.type) - VISIT(st, expr, eh->v.ExceptHandler.type); - if (eh->v.ExceptHandler.name) - if (!symtable_add_def(st, eh->v.ExceptHandler.name, DEF_LOCAL)) - return 0; - VISIT_SEQ(st, stmt, eh->v.ExceptHandler.body); - return 1; + if (eh->v.ExceptHandler.type) + VISIT(st, expr, eh->v.ExceptHandler.type); + if (eh->v.ExceptHandler.name) + if (!symtable_add_def(st, eh->v.ExceptHandler.name, DEF_LOCAL)) + return 0; + VISIT_SEQ(st, stmt, eh->v.ExceptHandler.body); + return 1; } -static int +static int symtable_visit_alias(struct symtable *st, alias_ty a) { - /* Compute store_name, the name actually bound by the import - operation. It is diferent than a->name when a->name is a - dotted package name (e.g. spam.eggs) - */ - PyObject *store_name; - PyObject *name = (a->asname == NULL) ? a->name : a->asname; - const Py_UNICODE *base = PyUnicode_AS_UNICODE(name); - Py_UNICODE *dot = Py_UNICODE_strchr(base, '.'); - if (dot) { - store_name = PyUnicode_FromUnicode(base, dot - base); - if (!store_name) - return 0; - } - else { - store_name = name; - Py_INCREF(store_name); - } - if (PyUnicode_CompareWithASCIIString(name, "*")) { - int r = symtable_add_def(st, store_name, DEF_IMPORT); - Py_DECREF(store_name); - return r; - } - else { - if (st->st_cur->ste_type != ModuleBlock) { - int lineno = st->st_cur->ste_lineno; - PyErr_SetString(PyExc_SyntaxError, IMPORT_STAR_WARNING); - PyErr_SyntaxLocation(st->st_filename, lineno); - Py_DECREF(store_name); - return 0; - } - st->st_cur->ste_unoptimized |= OPT_IMPORT_STAR; - Py_DECREF(store_name); - return 1; - } + /* Compute store_name, the name actually bound by the import + operation. It is diferent than a->name when a->name is a + dotted package name (e.g. spam.eggs) + */ + PyObject *store_name; + PyObject *name = (a->asname == NULL) ? a->name : a->asname; + const Py_UNICODE *base = PyUnicode_AS_UNICODE(name); + Py_UNICODE *dot = Py_UNICODE_strchr(base, '.'); + if (dot) { + store_name = PyUnicode_FromUnicode(base, dot - base); + if (!store_name) + return 0; + } + else { + store_name = name; + Py_INCREF(store_name); + } + if (PyUnicode_CompareWithASCIIString(name, "*")) { + int r = symtable_add_def(st, store_name, DEF_IMPORT); + Py_DECREF(store_name); + return r; + } + else { + if (st->st_cur->ste_type != ModuleBlock) { + int lineno = st->st_cur->ste_lineno; + PyErr_SetString(PyExc_SyntaxError, IMPORT_STAR_WARNING); + PyErr_SyntaxLocation(st->st_filename, lineno); + Py_DECREF(store_name); + return 0; + } + st->st_cur->ste_unoptimized |= OPT_IMPORT_STAR; + Py_DECREF(store_name); + return 1; + } } -static int +static int symtable_visit_comprehension(struct symtable *st, comprehension_ty lc) { - VISIT(st, expr, lc->target); - VISIT(st, expr, lc->iter); - VISIT_SEQ(st, expr, lc->ifs); - return 1; + VISIT(st, expr, lc->target); + VISIT(st, expr, lc->iter); + VISIT_SEQ(st, expr, lc->ifs); + return 1; } -static int +static int symtable_visit_keyword(struct symtable *st, keyword_ty k) { - VISIT(st, expr, k->value); - return 1; + VISIT(st, expr, k->value); + return 1; } -static int +static int symtable_visit_slice(struct symtable *st, slice_ty s) { - switch (s->kind) { - case Slice_kind: - if (s->v.Slice.lower) - VISIT(st, expr, s->v.Slice.lower) - if (s->v.Slice.upper) - VISIT(st, expr, s->v.Slice.upper) - if (s->v.Slice.step) - VISIT(st, expr, s->v.Slice.step) - break; - case ExtSlice_kind: - VISIT_SEQ(st, slice, s->v.ExtSlice.dims) - break; - case Index_kind: - VISIT(st, expr, s->v.Index.value) - break; - } - return 1; + switch (s->kind) { + case Slice_kind: + if (s->v.Slice.lower) + VISIT(st, expr, s->v.Slice.lower) + if (s->v.Slice.upper) + VISIT(st, expr, s->v.Slice.upper) + if (s->v.Slice.step) + VISIT(st, expr, s->v.Slice.step) + break; + case ExtSlice_kind: + VISIT_SEQ(st, slice, s->v.ExtSlice.dims) + break; + case Index_kind: + VISIT(st, expr, s->v.Index.value) + break; + } + return 1; } -static int +static int symtable_handle_comprehension(struct symtable *st, expr_ty e, identifier scope_name, asdl_seq *generators, expr_ty elt, expr_ty value) { - int is_generator = (e->kind == GeneratorExp_kind); - int needs_tmp = !is_generator; - comprehension_ty outermost = ((comprehension_ty) - asdl_seq_GET(generators, 0)); - /* Outermost iterator is evaluated in current scope */ - VISIT(st, expr, outermost->iter); - /* Create comprehension scope for the rest */ - if (!scope_name || - !symtable_enter_block(st, scope_name, FunctionBlock, (void *)e, e->lineno)) { - return 0; - } - st->st_cur->ste_generator = is_generator; - /* Outermost iter is received as an argument */ - if (!symtable_implicit_arg(st, 0)) { - symtable_exit_block(st, (void *)e); - return 0; - } - /* Allocate temporary name if needed */ - if (needs_tmp && !symtable_new_tmpname(st)) { - symtable_exit_block(st, (void *)e); - return 0; - } - VISIT_IN_BLOCK(st, expr, outermost->target, (void*)e); - VISIT_SEQ_IN_BLOCK(st, expr, outermost->ifs, (void*)e); - VISIT_SEQ_TAIL_IN_BLOCK(st, comprehension, - generators, 1, (void*)e); - if (value) - VISIT_IN_BLOCK(st, expr, value, (void*)e); - VISIT_IN_BLOCK(st, expr, elt, (void*)e); - return symtable_exit_block(st, (void *)e); + int is_generator = (e->kind == GeneratorExp_kind); + int needs_tmp = !is_generator; + comprehension_ty outermost = ((comprehension_ty) + asdl_seq_GET(generators, 0)); + /* Outermost iterator is evaluated in current scope */ + VISIT(st, expr, outermost->iter); + /* Create comprehension scope for the rest */ + if (!scope_name || + !symtable_enter_block(st, scope_name, FunctionBlock, (void *)e, e->lineno)) { + return 0; + } + st->st_cur->ste_generator = is_generator; + /* Outermost iter is received as an argument */ + if (!symtable_implicit_arg(st, 0)) { + symtable_exit_block(st, (void *)e); + return 0; + } + /* Allocate temporary name if needed */ + if (needs_tmp && !symtable_new_tmpname(st)) { + symtable_exit_block(st, (void *)e); + return 0; + } + VISIT_IN_BLOCK(st, expr, outermost->target, (void*)e); + VISIT_SEQ_IN_BLOCK(st, expr, outermost->ifs, (void*)e); + VISIT_SEQ_TAIL_IN_BLOCK(st, comprehension, + generators, 1, (void*)e); + if (value) + VISIT_IN_BLOCK(st, expr, value, (void*)e); + VISIT_IN_BLOCK(st, expr, elt, (void*)e); + return symtable_exit_block(st, (void *)e); } -static int +static int symtable_visit_genexp(struct symtable *st, expr_ty e) { - return symtable_handle_comprehension(st, e, GET_IDENTIFIER(genexpr), - e->v.GeneratorExp.generators, - e->v.GeneratorExp.elt, NULL); + return symtable_handle_comprehension(st, e, GET_IDENTIFIER(genexpr), + e->v.GeneratorExp.generators, + e->v.GeneratorExp.elt, NULL); } -static int +static int symtable_visit_listcomp(struct symtable *st, expr_ty e) { - return symtable_handle_comprehension(st, e, GET_IDENTIFIER(listcomp), - e->v.ListComp.generators, - e->v.ListComp.elt, NULL); + return symtable_handle_comprehension(st, e, GET_IDENTIFIER(listcomp), + e->v.ListComp.generators, + e->v.ListComp.elt, NULL); } static int symtable_visit_setcomp(struct symtable *st, expr_ty e) { - return symtable_handle_comprehension(st, e, GET_IDENTIFIER(setcomp), - e->v.SetComp.generators, - e->v.SetComp.elt, NULL); + return symtable_handle_comprehension(st, e, GET_IDENTIFIER(setcomp), + e->v.SetComp.generators, + e->v.SetComp.elt, NULL); } static int symtable_visit_dictcomp(struct symtable *st, expr_ty e) { - return symtable_handle_comprehension(st, e, GET_IDENTIFIER(dictcomp), - e->v.DictComp.generators, - e->v.DictComp.key, - e->v.DictComp.value); + return symtable_handle_comprehension(st, e, GET_IDENTIFIER(dictcomp), + e->v.DictComp.generators, + e->v.DictComp.key, + e->v.DictComp.value); } Modified: python/branches/py3k-jit/Python/sysmodule.c ============================================================================== --- python/branches/py3k-jit/Python/sysmodule.c (original) +++ python/branches/py3k-jit/Python/sysmodule.c Mon May 10 23:55:43 2010 @@ -45,63 +45,63 @@ PyObject * PySys_GetObject(const char *name) { - PyThreadState *tstate = PyThreadState_GET(); - PyObject *sd = tstate->interp->sysdict; - if (sd == NULL) - return NULL; - return PyDict_GetItemString(sd, name); + PyThreadState *tstate = PyThreadState_GET(); + PyObject *sd = tstate->interp->sysdict; + if (sd == NULL) + return NULL; + return PyDict_GetItemString(sd, name); } int PySys_SetObject(const char *name, PyObject *v) { - PyThreadState *tstate = PyThreadState_GET(); - PyObject *sd = tstate->interp->sysdict; - if (v == NULL) { - if (PyDict_GetItemString(sd, name) == NULL) - return 0; - else - return PyDict_DelItemString(sd, name); - } - else - return PyDict_SetItemString(sd, name, v); + PyThreadState *tstate = PyThreadState_GET(); + PyObject *sd = tstate->interp->sysdict; + if (v == NULL) { + if (PyDict_GetItemString(sd, name) == NULL) + return 0; + else + return PyDict_DelItemString(sd, name); + } + else + return PyDict_SetItemString(sd, name, v); } static PyObject * sys_displayhook(PyObject *self, PyObject *o) { - PyObject *outf; - PyInterpreterState *interp = PyThreadState_GET()->interp; - PyObject *modules = interp->modules; - PyObject *builtins = PyDict_GetItemString(modules, "builtins"); - - if (builtins == NULL) { - PyErr_SetString(PyExc_RuntimeError, "lost builtins module"); - return NULL; - } - - /* Print value except if None */ - /* After printing, also assign to '_' */ - /* Before, set '_' to None to avoid recursion */ - if (o == Py_None) { - Py_INCREF(Py_None); - return Py_None; - } - if (PyObject_SetAttrString(builtins, "_", Py_None) != 0) - return NULL; - outf = PySys_GetObject("stdout"); - if (outf == NULL || outf == Py_None) { - PyErr_SetString(PyExc_RuntimeError, "lost sys.stdout"); - return NULL; - } - if (PyFile_WriteObject(o, outf, 0) != 0) - return NULL; - if (PyFile_WriteString("\n", outf) != 0) - return NULL; - if (PyObject_SetAttrString(builtins, "_", o) != 0) - return NULL; - Py_INCREF(Py_None); - return Py_None; + PyObject *outf; + PyInterpreterState *interp = PyThreadState_GET()->interp; + PyObject *modules = interp->modules; + PyObject *builtins = PyDict_GetItemString(modules, "builtins"); + + if (builtins == NULL) { + PyErr_SetString(PyExc_RuntimeError, "lost builtins module"); + return NULL; + } + + /* Print value except if None */ + /* After printing, also assign to '_' */ + /* Before, set '_' to None to avoid recursion */ + if (o == Py_None) { + Py_INCREF(Py_None); + return Py_None; + } + if (PyObject_SetAttrString(builtins, "_", Py_None) != 0) + return NULL; + outf = PySys_GetObject("stdout"); + if (outf == NULL || outf == Py_None) { + PyErr_SetString(PyExc_RuntimeError, "lost sys.stdout"); + return NULL; + } + if (PyFile_WriteObject(o, outf, 0) != 0) + return NULL; + if (PyFile_WriteString("\n", outf) != 0) + return NULL; + if (PyObject_SetAttrString(builtins, "_", o) != 0) + return NULL; + Py_INCREF(Py_None); + return Py_None; } PyDoc_STRVAR(displayhook_doc, @@ -113,12 +113,12 @@ static PyObject * sys_excepthook(PyObject* self, PyObject* args) { - PyObject *exc, *value, *tb; - if (!PyArg_UnpackTuple(args, "excepthook", 3, 3, &exc, &value, &tb)) - return NULL; - PyErr_Display(exc, value, tb); - Py_INCREF(Py_None); - return Py_None; + PyObject *exc, *value, *tb; + if (!PyArg_UnpackTuple(args, "excepthook", 3, 3, &exc, &value, &tb)) + return NULL; + PyErr_Display(exc, value, tb); + Py_INCREF(Py_None); + return Py_None; } PyDoc_STRVAR(excepthook_doc, @@ -130,14 +130,14 @@ static PyObject * sys_exc_info(PyObject *self, PyObject *noargs) { - PyThreadState *tstate; - tstate = PyThreadState_GET(); - return Py_BuildValue( - "(OOO)", - tstate->exc_type != NULL ? tstate->exc_type : Py_None, - tstate->exc_value != NULL ? tstate->exc_value : Py_None, - tstate->exc_traceback != NULL ? - tstate->exc_traceback : Py_None); + PyThreadState *tstate; + tstate = PyThreadState_GET(); + return Py_BuildValue( + "(OOO)", + tstate->exc_type != NULL ? tstate->exc_type : Py_None, + tstate->exc_value != NULL ? tstate->exc_value : Py_None, + tstate->exc_traceback != NULL ? + tstate->exc_traceback : Py_None); } PyDoc_STRVAR(exc_info_doc, @@ -150,12 +150,12 @@ static PyObject * sys_exit(PyObject *self, PyObject *args) { - PyObject *exit_code = 0; - if (!PyArg_UnpackTuple(args, "exit", 0, 1, &exit_code)) - return NULL; - /* Raise SystemExit so callers may catch it or clean up. */ - PyErr_SetObject(PyExc_SystemExit, exit_code); - return NULL; + PyObject *exit_code = 0; + if (!PyArg_UnpackTuple(args, "exit", 0, 1, &exit_code)) + return NULL; + /* Raise SystemExit so callers may catch it or clean up. */ + PyErr_SetObject(PyExc_SystemExit, exit_code); + return NULL; } PyDoc_STRVAR(exit_doc, @@ -172,7 +172,7 @@ static PyObject * sys_getdefaultencoding(PyObject *self) { - return PyUnicode_FromString(PyUnicode_GetDefaultEncoding()); + return PyUnicode_FromString(PyUnicode_GetDefaultEncoding()); } PyDoc_STRVAR(getdefaultencoding_doc, @@ -185,13 +185,13 @@ static PyObject * sys_setdefaultencoding(PyObject *self, PyObject *args) { - char *encoding; - if (!PyArg_ParseTuple(args, "s:setdefaultencoding", &encoding)) - return NULL; - if (PyUnicode_SetDefaultEncoding(encoding)) - return NULL; - Py_INCREF(Py_None); - return Py_None; + char *encoding; + if (!PyArg_ParseTuple(args, "s:setdefaultencoding", &encoding)) + return NULL; + if (PyUnicode_SetDefaultEncoding(encoding)) + return NULL; + Py_INCREF(Py_None); + return Py_None; } PyDoc_STRVAR(setdefaultencoding_doc, @@ -203,10 +203,10 @@ static PyObject * sys_getfilesystemencoding(PyObject *self) { - if (Py_FileSystemDefaultEncoding) - return PyUnicode_FromString(Py_FileSystemDefaultEncoding); - Py_INCREF(Py_None); - return Py_None; + if (Py_FileSystemDefaultEncoding) + return PyUnicode_FromString(Py_FileSystemDefaultEncoding); + Py_INCREF(Py_None); + return Py_None; } PyDoc_STRVAR(getfilesystemencoding_doc, @@ -219,13 +219,13 @@ static PyObject * sys_setfilesystemencoding(PyObject *self, PyObject *args) { - PyObject *new_encoding; - if (!PyArg_ParseTuple(args, "U:setfilesystemencoding", &new_encoding)) - return NULL; - if (_Py_SetFileSystemEncoding(new_encoding)) - return NULL; - Py_INCREF(Py_None); - return Py_None; + PyObject *new_encoding; + if (!PyArg_ParseTuple(args, "U:setfilesystemencoding", &new_encoding)) + return NULL; + if (_Py_SetFileSystemEncoding(new_encoding)) + return NULL; + Py_INCREF(Py_None); + return Py_None; } PyDoc_STRVAR(setfilesystemencoding_doc, @@ -238,19 +238,19 @@ static PyObject * sys_intern(PyObject *self, PyObject *args) { - PyObject *s; - if (!PyArg_ParseTuple(args, "U:intern", &s)) - return NULL; - if (PyUnicode_CheckExact(s)) { - Py_INCREF(s); - PyUnicode_InternInPlace(&s); - return s; - } - else { - PyErr_Format(PyExc_TypeError, - "can't intern %.400s", s->ob_type->tp_name); - return NULL; - } + PyObject *s; + if (!PyArg_ParseTuple(args, "U:intern", &s)) + return NULL; + if (PyUnicode_CheckExact(s)) { + Py_INCREF(s); + PyUnicode_InternInPlace(&s); + return s; + } + else { + PyErr_Format(PyExc_TypeError, + "can't intern %.400s", s->ob_type->tp_name); + return NULL; + } } PyDoc_STRVAR(intern_doc, @@ -271,116 +271,116 @@ static int trace_init(void) { - static char *whatnames[7] = {"call", "exception", "line", "return", - "c_call", "c_exception", "c_return"}; - PyObject *name; - int i; - for (i = 0; i < 7; ++i) { - if (whatstrings[i] == NULL) { - name = PyUnicode_InternFromString(whatnames[i]); - if (name == NULL) - return -1; - whatstrings[i] = name; - } - } - return 0; + static char *whatnames[7] = {"call", "exception", "line", "return", + "c_call", "c_exception", "c_return"}; + PyObject *name; + int i; + for (i = 0; i < 7; ++i) { + if (whatstrings[i] == NULL) { + name = PyUnicode_InternFromString(whatnames[i]); + if (name == NULL) + return -1; + whatstrings[i] = name; + } + } + return 0; } static PyObject * call_trampoline(PyThreadState *tstate, PyObject* callback, - PyFrameObject *frame, int what, PyObject *arg) + PyFrameObject *frame, int what, PyObject *arg) { - PyObject *args = PyTuple_New(3); - PyObject *whatstr; - PyObject *result; - - if (args == NULL) - return NULL; - Py_INCREF(frame); - whatstr = whatstrings[what]; - Py_INCREF(whatstr); - if (arg == NULL) - arg = Py_None; - Py_INCREF(arg); - PyTuple_SET_ITEM(args, 0, (PyObject *)frame); - PyTuple_SET_ITEM(args, 1, whatstr); - PyTuple_SET_ITEM(args, 2, arg); - - /* call the Python-level function */ - PyFrame_FastToLocals(frame); - result = PyEval_CallObject(callback, args); - PyFrame_LocalsToFast(frame, 1); - if (result == NULL) - PyTraceBack_Here(frame); - - /* cleanup */ - Py_DECREF(args); - return result; + PyObject *args = PyTuple_New(3); + PyObject *whatstr; + PyObject *result; + + if (args == NULL) + return NULL; + Py_INCREF(frame); + whatstr = whatstrings[what]; + Py_INCREF(whatstr); + if (arg == NULL) + arg = Py_None; + Py_INCREF(arg); + PyTuple_SET_ITEM(args, 0, (PyObject *)frame); + PyTuple_SET_ITEM(args, 1, whatstr); + PyTuple_SET_ITEM(args, 2, arg); + + /* call the Python-level function */ + PyFrame_FastToLocals(frame); + result = PyEval_CallObject(callback, args); + PyFrame_LocalsToFast(frame, 1); + if (result == NULL) + PyTraceBack_Here(frame); + + /* cleanup */ + Py_DECREF(args); + return result; } static int profile_trampoline(PyObject *self, PyFrameObject *frame, - int what, PyObject *arg) + int what, PyObject *arg) { - PyThreadState *tstate = frame->f_tstate; - PyObject *result; + PyThreadState *tstate = frame->f_tstate; + PyObject *result; - if (arg == NULL) - arg = Py_None; - result = call_trampoline(tstate, self, frame, what, arg); - if (result == NULL) { - PyEval_SetProfile(NULL, NULL); - return -1; - } - Py_DECREF(result); - return 0; + if (arg == NULL) + arg = Py_None; + result = call_trampoline(tstate, self, frame, what, arg); + if (result == NULL) { + PyEval_SetProfile(NULL, NULL); + return -1; + } + Py_DECREF(result); + return 0; } static int trace_trampoline(PyObject *self, PyFrameObject *frame, - int what, PyObject *arg) + int what, PyObject *arg) { - PyThreadState *tstate = frame->f_tstate; - PyObject *callback; - PyObject *result; - - if (what == PyTrace_CALL) - callback = self; - else - callback = frame->f_trace; - if (callback == NULL) - return 0; - result = call_trampoline(tstate, callback, frame, what, arg); - if (result == NULL) { - PyEval_SetTrace(NULL, NULL); - Py_XDECREF(frame->f_trace); - frame->f_trace = NULL; - return -1; - } - if (result != Py_None) { - PyObject *temp = frame->f_trace; - frame->f_trace = NULL; - Py_XDECREF(temp); - frame->f_trace = result; - } - else { - Py_DECREF(result); - } - return 0; + PyThreadState *tstate = frame->f_tstate; + PyObject *callback; + PyObject *result; + + if (what == PyTrace_CALL) + callback = self; + else + callback = frame->f_trace; + if (callback == NULL) + return 0; + result = call_trampoline(tstate, callback, frame, what, arg); + if (result == NULL) { + PyEval_SetTrace(NULL, NULL); + Py_XDECREF(frame->f_trace); + frame->f_trace = NULL; + return -1; + } + if (result != Py_None) { + PyObject *temp = frame->f_trace; + frame->f_trace = NULL; + Py_XDECREF(temp); + frame->f_trace = result; + } + else { + Py_DECREF(result); + } + return 0; } static PyObject * sys_settrace(PyObject *self, PyObject *args) { - if (trace_init() == -1) - return NULL; - if (args == Py_None) - PyEval_SetTrace(NULL, NULL); - else - PyEval_SetTrace(trace_trampoline, args); - Py_INCREF(Py_None); - return Py_None; + if (trace_init() == -1) + return NULL; + if (args == Py_None) + PyEval_SetTrace(NULL, NULL); + else + PyEval_SetTrace(trace_trampoline, args); + Py_INCREF(Py_None); + return Py_None; } PyDoc_STRVAR(settrace_doc, @@ -393,13 +393,13 @@ static PyObject * sys_gettrace(PyObject *self, PyObject *args) { - PyThreadState *tstate = PyThreadState_GET(); - PyObject *temp = tstate->c_traceobj; + PyThreadState *tstate = PyThreadState_GET(); + PyObject *temp = tstate->c_traceobj; - if (temp == NULL) - temp = Py_None; - Py_INCREF(temp); - return temp; + if (temp == NULL) + temp = Py_None; + Py_INCREF(temp); + return temp; } PyDoc_STRVAR(gettrace_doc, @@ -412,14 +412,14 @@ static PyObject * sys_setprofile(PyObject *self, PyObject *args) { - if (trace_init() == -1) - return NULL; - if (args == Py_None) - PyEval_SetProfile(NULL, NULL); - else - PyEval_SetProfile(profile_trampoline, args); - Py_INCREF(Py_None); - return Py_None; + if (trace_init() == -1) + return NULL; + if (args == Py_None) + PyEval_SetProfile(NULL, NULL); + else + PyEval_SetProfile(profile_trampoline, args); + Py_INCREF(Py_None); + return Py_None; } PyDoc_STRVAR(setprofile_doc, @@ -432,13 +432,13 @@ static PyObject * sys_getprofile(PyObject *self, PyObject *args) { - PyThreadState *tstate = PyThreadState_GET(); - PyObject *temp = tstate->c_profileobj; + PyThreadState *tstate = PyThreadState_GET(); + PyObject *temp = tstate->c_profileobj; - if (temp == NULL) - temp = Py_None; - Py_INCREF(temp); - return temp; + if (temp == NULL) + temp = Py_None; + Py_INCREF(temp); + return temp; } PyDoc_STRVAR(getprofile_doc, @@ -453,15 +453,15 @@ static PyObject * sys_setcheckinterval(PyObject *self, PyObject *args) { - if (PyErr_WarnEx(PyExc_DeprecationWarning, - "sys.getcheckinterval() and sys.setcheckinterval() " - "are deprecated. Use sys.setswitchinterval() " - "instead.", 1) < 0) - return NULL; - if (!PyArg_ParseTuple(args, "i:setcheckinterval", &_check_interval)) - return NULL; - Py_INCREF(Py_None); - return Py_None; + if (PyErr_WarnEx(PyExc_DeprecationWarning, + "sys.getcheckinterval() and sys.setcheckinterval() " + "are deprecated. Use sys.setswitchinterval() " + "instead.", 1) < 0) + return NULL; + if (!PyArg_ParseTuple(args, "i:setcheckinterval", &_check_interval)) + return NULL; + Py_INCREF(Py_None); + return Py_None; } PyDoc_STRVAR(setcheckinterval_doc, @@ -474,12 +474,12 @@ static PyObject * sys_getcheckinterval(PyObject *self, PyObject *args) { - if (PyErr_WarnEx(PyExc_DeprecationWarning, - "sys.getcheckinterval() and sys.setcheckinterval() " - "are deprecated. Use sys.getswitchinterval() " - "instead.", 1) < 0) - return NULL; - return PyLong_FromLong(_check_interval); + if (PyErr_WarnEx(PyExc_DeprecationWarning, + "sys.getcheckinterval() and sys.setcheckinterval() " + "are deprecated. Use sys.getswitchinterval() " + "instead.", 1) < 0) + return NULL; + return PyLong_FromLong(_check_interval); } PyDoc_STRVAR(getcheckinterval_doc, @@ -490,17 +490,17 @@ static PyObject * sys_setswitchinterval(PyObject *self, PyObject *args) { - double d; - if (!PyArg_ParseTuple(args, "d:setswitchinterval", &d)) - return NULL; - if (d <= 0.0) { - PyErr_SetString(PyExc_ValueError, - "switch interval must be strictly positive"); - return NULL; - } - _PyEval_SetSwitchInterval((unsigned long) (1e6 * d)); - Py_INCREF(Py_None); - return Py_None; + double d; + if (!PyArg_ParseTuple(args, "d:setswitchinterval", &d)) + return NULL; + if (d <= 0.0) { + PyErr_SetString(PyExc_ValueError, + "switch interval must be strictly positive"); + return NULL; + } + _PyEval_SetSwitchInterval((unsigned long) (1e6 * d)); + Py_INCREF(Py_None); + return Py_None; } PyDoc_STRVAR(setswitchinterval_doc, @@ -518,7 +518,7 @@ static PyObject * sys_getswitchinterval(PyObject *self, PyObject *args) { - return PyFloat_FromDouble(1e-6 * _PyEval_GetSwitchInterval()); + return PyFloat_FromDouble(1e-6 * _PyEval_GetSwitchInterval()); } PyDoc_STRVAR(getswitchinterval_doc, @@ -531,17 +531,17 @@ static PyObject * sys_settscdump(PyObject *self, PyObject *args) { - int bool; - PyThreadState *tstate = PyThreadState_Get(); + int bool; + PyThreadState *tstate = PyThreadState_Get(); - if (!PyArg_ParseTuple(args, "i:settscdump", &bool)) - return NULL; - if (bool) - tstate->interp->tscdump = 1; - else - tstate->interp->tscdump = 0; - Py_INCREF(Py_None); - return Py_None; + if (!PyArg_ParseTuple(args, "i:settscdump", &bool)) + return NULL; + if (bool) + tstate->interp->tscdump = 1; + else + tstate->interp->tscdump = 0; + Py_INCREF(Py_None); + return Py_None; } @@ -557,17 +557,17 @@ static PyObject * sys_setrecursionlimit(PyObject *self, PyObject *args) { - int new_limit; - if (!PyArg_ParseTuple(args, "i:setrecursionlimit", &new_limit)) - return NULL; - if (new_limit <= 0) { - PyErr_SetString(PyExc_ValueError, - "recursion limit must be positive"); - return NULL; - } - Py_SetRecursionLimit(new_limit); - Py_INCREF(Py_None); - return Py_None; + int new_limit; + if (!PyArg_ParseTuple(args, "i:setrecursionlimit", &new_limit)) + return NULL; + if (new_limit <= 0) { + PyErr_SetString(PyExc_ValueError, + "recursion limit must be positive"); + return NULL; + } + Py_SetRecursionLimit(new_limit); + Py_INCREF(Py_None); + return Py_None; } PyDoc_STRVAR(setrecursionlimit_doc, @@ -582,7 +582,7 @@ static PyObject * sys_getrecursionlimit(PyObject *self) { - return PyLong_FromLong(Py_GetRecursionLimit()); + return PyLong_FromLong(Py_GetRecursionLimit()); } PyDoc_STRVAR(getrecursionlimit_doc, @@ -610,52 +610,52 @@ static PyTypeObject WindowsVersionType = {0, 0, 0, 0, 0, 0}; static PyStructSequence_Field windows_version_fields[] = { - {"major", "Major version number"}, - {"minor", "Minor version number"}, - {"build", "Build number"}, - {"platform", "Operating system platform"}, - {"service_pack", "Latest Service Pack installed on the system"}, - {"service_pack_major", "Service Pack major version number"}, - {"service_pack_minor", "Service Pack minor version number"}, - {"suite_mask", "Bit mask identifying available product suites"}, - {"product_type", "System product type"}, - {0} + {"major", "Major version number"}, + {"minor", "Minor version number"}, + {"build", "Build number"}, + {"platform", "Operating system platform"}, + {"service_pack", "Latest Service Pack installed on the system"}, + {"service_pack_major", "Service Pack major version number"}, + {"service_pack_minor", "Service Pack minor version number"}, + {"suite_mask", "Bit mask identifying available product suites"}, + {"product_type", "System product type"}, + {0} }; static PyStructSequence_Desc windows_version_desc = { - "sys.getwindowsversion", /* name */ - getwindowsversion_doc, /* doc */ - windows_version_fields, /* fields */ - 5 /* For backward compatibility, - only the first 5 items are accessible - via indexing, the rest are name only */ + "sys.getwindowsversion", /* name */ + getwindowsversion_doc, /* doc */ + windows_version_fields, /* fields */ + 5 /* For backward compatibility, + only the first 5 items are accessible + via indexing, the rest are name only */ }; static PyObject * sys_getwindowsversion(PyObject *self) { - PyObject *version; - int pos = 0; - OSVERSIONINFOEX ver; - ver.dwOSVersionInfoSize = sizeof(ver); - if (!GetVersionEx((OSVERSIONINFO*) &ver)) - return PyErr_SetFromWindowsErr(0); - - version = PyStructSequence_New(&WindowsVersionType); - if (version == NULL) - return NULL; - - PyStructSequence_SET_ITEM(version, pos++, PyLong_FromLong(ver.dwMajorVersion)); - PyStructSequence_SET_ITEM(version, pos++, PyLong_FromLong(ver.dwMinorVersion)); - PyStructSequence_SET_ITEM(version, pos++, PyLong_FromLong(ver.dwBuildNumber)); - PyStructSequence_SET_ITEM(version, pos++, PyLong_FromLong(ver.dwPlatformId)); - PyStructSequence_SET_ITEM(version, pos++, PyUnicode_FromString(ver.szCSDVersion)); - PyStructSequence_SET_ITEM(version, pos++, PyLong_FromLong(ver.wServicePackMajor)); - PyStructSequence_SET_ITEM(version, pos++, PyLong_FromLong(ver.wServicePackMinor)); - PyStructSequence_SET_ITEM(version, pos++, PyLong_FromLong(ver.wSuiteMask)); - PyStructSequence_SET_ITEM(version, pos++, PyLong_FromLong(ver.wProductType)); + PyObject *version; + int pos = 0; + OSVERSIONINFOEX ver; + ver.dwOSVersionInfoSize = sizeof(ver); + if (!GetVersionEx((OSVERSIONINFO*) &ver)) + return PyErr_SetFromWindowsErr(0); + + version = PyStructSequence_New(&WindowsVersionType); + if (version == NULL) + return NULL; + + PyStructSequence_SET_ITEM(version, pos++, PyLong_FromLong(ver.dwMajorVersion)); + PyStructSequence_SET_ITEM(version, pos++, PyLong_FromLong(ver.dwMinorVersion)); + PyStructSequence_SET_ITEM(version, pos++, PyLong_FromLong(ver.dwBuildNumber)); + PyStructSequence_SET_ITEM(version, pos++, PyLong_FromLong(ver.dwPlatformId)); + PyStructSequence_SET_ITEM(version, pos++, PyUnicode_FromString(ver.szCSDVersion)); + PyStructSequence_SET_ITEM(version, pos++, PyLong_FromLong(ver.wServicePackMajor)); + PyStructSequence_SET_ITEM(version, pos++, PyLong_FromLong(ver.wServicePackMinor)); + PyStructSequence_SET_ITEM(version, pos++, PyLong_FromLong(ver.wSuiteMask)); + PyStructSequence_SET_ITEM(version, pos++, PyLong_FromLong(ver.wProductType)); - return version; + return version; } #endif /* MS_WINDOWS */ @@ -664,15 +664,15 @@ static PyObject * sys_setdlopenflags(PyObject *self, PyObject *args) { - int new_val; - PyThreadState *tstate = PyThreadState_GET(); - if (!PyArg_ParseTuple(args, "i:setdlopenflags", &new_val)) - return NULL; - if (!tstate) - return NULL; - tstate->interp->dlopenflags = new_val; - Py_INCREF(Py_None); - return Py_None; + int new_val; + PyThreadState *tstate = PyThreadState_GET(); + if (!PyArg_ParseTuple(args, "i:setdlopenflags", &new_val)) + return NULL; + if (!tstate) + return NULL; + tstate->interp->dlopenflags = new_val; + Py_INCREF(Py_None); + return Py_None; } PyDoc_STRVAR(setdlopenflags_doc, @@ -690,10 +690,10 @@ static PyObject * sys_getdlopenflags(PyObject *self, PyObject *args) { - PyThreadState *tstate = PyThreadState_GET(); - if (!tstate) - return NULL; - return PyLong_FromLong(tstate->interp->dlopenflags); + PyThreadState *tstate = PyThreadState_GET(); + if (!tstate) + return NULL; + return PyLong_FromLong(tstate->interp->dlopenflags); } PyDoc_STRVAR(getdlopenflags_doc, @@ -702,7 +702,7 @@ Return the current value of the flags that are used for dlopen calls.\n\ The flag constants are defined in the ctypes and DLFCN modules."); -#endif /* HAVE_DLOPEN */ +#endif /* HAVE_DLOPEN */ #ifdef USE_MALLOPT /* Link with -lmalloc (or -lmpc) on an SGI */ @@ -711,70 +711,70 @@ static PyObject * sys_mdebug(PyObject *self, PyObject *args) { - int flag; - if (!PyArg_ParseTuple(args, "i:mdebug", &flag)) - return NULL; - mallopt(M_DEBUG, flag); - Py_INCREF(Py_None); - return Py_None; + int flag; + if (!PyArg_ParseTuple(args, "i:mdebug", &flag)) + return NULL; + mallopt(M_DEBUG, flag); + Py_INCREF(Py_None); + return Py_None; } #endif /* USE_MALLOPT */ static PyObject * sys_getsizeof(PyObject *self, PyObject *args, PyObject *kwds) { - PyObject *res = NULL; - static PyObject *str__sizeof__ = NULL, *gc_head_size = NULL; - static char *kwlist[] = {"object", "default", 0}; - PyObject *o, *dflt = NULL; - PyObject *method; - - if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|O:getsizeof", - kwlist, &o, &dflt)) - return NULL; - - /* Initialize static variable for GC head size */ - if (gc_head_size == NULL) { - gc_head_size = PyLong_FromSsize_t(sizeof(PyGC_Head)); - if (gc_head_size == NULL) - return NULL; - } - - /* Make sure the type is initialized. float gets initialized late */ - if (PyType_Ready(Py_TYPE(o)) < 0) - return NULL; - - method = _PyObject_LookupSpecial(o, "__sizeof__", - &str__sizeof__); - if (method == NULL) { - if (!PyErr_Occurred()) - PyErr_Format(PyExc_TypeError, - "Type %.100s doesn't define __sizeof__", - Py_TYPE(o)->tp_name); - } - else { - res = PyObject_CallFunctionObjArgs(method, NULL); - Py_DECREF(method); - } - - /* Has a default value been given */ - if ((res == NULL) && (dflt != NULL) && - PyErr_ExceptionMatches(PyExc_TypeError)) - { - PyErr_Clear(); - Py_INCREF(dflt); - return dflt; - } - else if (res == NULL) - return res; - - /* add gc_head size */ - if (PyObject_IS_GC(o)) { - PyObject *tmp = res; - res = PyNumber_Add(tmp, gc_head_size); - Py_DECREF(tmp); - } - return res; + PyObject *res = NULL; + static PyObject *str__sizeof__ = NULL, *gc_head_size = NULL; + static char *kwlist[] = {"object", "default", 0}; + PyObject *o, *dflt = NULL; + PyObject *method; + + if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|O:getsizeof", + kwlist, &o, &dflt)) + return NULL; + + /* Initialize static variable for GC head size */ + if (gc_head_size == NULL) { + gc_head_size = PyLong_FromSsize_t(sizeof(PyGC_Head)); + if (gc_head_size == NULL) + return NULL; + } + + /* Make sure the type is initialized. float gets initialized late */ + if (PyType_Ready(Py_TYPE(o)) < 0) + return NULL; + + method = _PyObject_LookupSpecial(o, "__sizeof__", + &str__sizeof__); + if (method == NULL) { + if (!PyErr_Occurred()) + PyErr_Format(PyExc_TypeError, + "Type %.100s doesn't define __sizeof__", + Py_TYPE(o)->tp_name); + } + else { + res = PyObject_CallFunctionObjArgs(method, NULL); + Py_DECREF(method); + } + + /* Has a default value been given */ + if ((res == NULL) && (dflt != NULL) && + PyErr_ExceptionMatches(PyExc_TypeError)) + { + PyErr_Clear(); + Py_INCREF(dflt); + return dflt; + } + else if (res == NULL) + return res; + + /* add gc_head size */ + if (PyObject_IS_GC(o)) { + PyObject *tmp = res; + res = PyNumber_Add(tmp, gc_head_size); + Py_DECREF(tmp); + } + return res; } PyDoc_STRVAR(getsizeof_doc, @@ -785,14 +785,14 @@ static PyObject * sys_getrefcount(PyObject *self, PyObject *arg) { - return PyLong_FromSsize_t(arg->ob_refcnt); + return PyLong_FromSsize_t(arg->ob_refcnt); } #ifdef Py_REF_DEBUG static PyObject * sys_gettotalrefcount(PyObject *self) { - return PyLong_FromSsize_t(_Py_GetRefTotal()); + return PyLong_FromSsize_t(_Py_GetRefTotal()); } #endif /* Py_REF_DEBUG */ @@ -808,9 +808,9 @@ static PyObject * sys_getcounts(PyObject *self) { - extern PyObject *get_counts(void); + extern PyObject *get_counts(void); - return get_counts(); + return get_counts(); } #endif @@ -829,23 +829,23 @@ static PyObject * sys_getframe(PyObject *self, PyObject *args) { - PyFrameObject *f = PyThreadState_GET()->frame; - int depth = -1; + PyFrameObject *f = PyThreadState_GET()->frame; + int depth = -1; - if (!PyArg_ParseTuple(args, "|i:_getframe", &depth)) - return NULL; + if (!PyArg_ParseTuple(args, "|i:_getframe", &depth)) + return NULL; - while (depth > 0 && f != NULL) { - f = f->f_back; - --depth; - } - if (f == NULL) { - PyErr_SetString(PyExc_ValueError, - "call stack is not deep enough"); - return NULL; - } - Py_INCREF(f); - return (PyObject*)f; + while (depth > 0 && f != NULL) { + f = f->f_back; + --depth; + } + if (f == NULL) { + PyErr_SetString(PyExc_ValueError, + "call stack is not deep enough"); + return NULL; + } + Py_INCREF(f); + return (PyObject*)f; } PyDoc_STRVAR(current_frames_doc, @@ -860,7 +860,7 @@ static PyObject * sys_current_frames(PyObject *self, PyObject *noargs) { - return _PyThread_CurrentFrames(); + return _PyThread_CurrentFrames(); } PyDoc_STRVAR(call_tracing_doc, @@ -874,10 +874,10 @@ static PyObject * sys_call_tracing(PyObject *self, PyObject *args) { - PyObject *func, *funcargs; - if (!PyArg_ParseTuple(args, "OO!:call_tracing", &func, &PyTuple_Type, &funcargs)) - return NULL; - return _PyEval_CallTracing(func, funcargs); + PyObject *func, *funcargs; + if (!PyArg_ParseTuple(args, "OO!:call_tracing", &func, &PyTuple_Type, &funcargs)) + return NULL; + return _PyEval_CallTracing(func, funcargs); } PyDoc_STRVAR(callstats_doc, @@ -924,8 +924,8 @@ static PyObject * sys_clear_type_cache(PyObject* self, PyObject* args) { - PyType_ClearCache(); - Py_RETURN_NONE; + PyType_ClearCache(); + Py_RETURN_NONE; } PyDoc_STRVAR(sys_clear_type_cache__doc__, @@ -934,107 +934,107 @@ static PyMethodDef sys_methods[] = { - /* Might as well keep this in alphabetic order */ - {"callstats", (PyCFunction)PyEval_GetCallStats, METH_NOARGS, - callstats_doc}, - {"_clear_type_cache", sys_clear_type_cache, METH_NOARGS, - sys_clear_type_cache__doc__}, - {"_current_frames", sys_current_frames, METH_NOARGS, - current_frames_doc}, - {"displayhook", sys_displayhook, METH_O, displayhook_doc}, - {"exc_info", sys_exc_info, METH_NOARGS, exc_info_doc}, - {"excepthook", sys_excepthook, METH_VARARGS, excepthook_doc}, - {"exit", sys_exit, METH_VARARGS, exit_doc}, - {"getdefaultencoding", (PyCFunction)sys_getdefaultencoding, - METH_NOARGS, getdefaultencoding_doc}, + /* Might as well keep this in alphabetic order */ + {"callstats", (PyCFunction)PyEval_GetCallStats, METH_NOARGS, + callstats_doc}, + {"_clear_type_cache", sys_clear_type_cache, METH_NOARGS, + sys_clear_type_cache__doc__}, + {"_current_frames", sys_current_frames, METH_NOARGS, + current_frames_doc}, + {"displayhook", sys_displayhook, METH_O, displayhook_doc}, + {"exc_info", sys_exc_info, METH_NOARGS, exc_info_doc}, + {"excepthook", sys_excepthook, METH_VARARGS, excepthook_doc}, + {"exit", sys_exit, METH_VARARGS, exit_doc}, + {"getdefaultencoding", (PyCFunction)sys_getdefaultencoding, + METH_NOARGS, getdefaultencoding_doc}, #ifdef HAVE_DLOPEN - {"getdlopenflags", (PyCFunction)sys_getdlopenflags, METH_NOARGS, - getdlopenflags_doc}, + {"getdlopenflags", (PyCFunction)sys_getdlopenflags, METH_NOARGS, + getdlopenflags_doc}, #endif #ifdef COUNT_ALLOCS - {"getcounts", (PyCFunction)sys_getcounts, METH_NOARGS}, + {"getcounts", (PyCFunction)sys_getcounts, METH_NOARGS}, #endif #ifdef DYNAMIC_EXECUTION_PROFILE - {"getdxp", _Py_GetDXProfile, METH_VARARGS}, + {"getdxp", _Py_GetDXProfile, METH_VARARGS}, #endif - {"getfilesystemencoding", (PyCFunction)sys_getfilesystemencoding, - METH_NOARGS, getfilesystemencoding_doc}, + {"getfilesystemencoding", (PyCFunction)sys_getfilesystemencoding, + METH_NOARGS, getfilesystemencoding_doc}, #ifdef Py_TRACE_REFS - {"getobjects", _Py_GetObjects, METH_VARARGS}, + {"getobjects", _Py_GetObjects, METH_VARARGS}, #endif #ifdef Py_REF_DEBUG - {"gettotalrefcount", (PyCFunction)sys_gettotalrefcount, METH_NOARGS}, + {"gettotalrefcount", (PyCFunction)sys_gettotalrefcount, METH_NOARGS}, #endif - {"getrefcount", (PyCFunction)sys_getrefcount, METH_O, getrefcount_doc}, - {"getrecursionlimit", (PyCFunction)sys_getrecursionlimit, METH_NOARGS, - getrecursionlimit_doc}, - {"getsizeof", (PyCFunction)sys_getsizeof, - METH_VARARGS | METH_KEYWORDS, getsizeof_doc}, - {"_getframe", sys_getframe, METH_VARARGS, getframe_doc}, + {"getrefcount", (PyCFunction)sys_getrefcount, METH_O, getrefcount_doc}, + {"getrecursionlimit", (PyCFunction)sys_getrecursionlimit, METH_NOARGS, + getrecursionlimit_doc}, + {"getsizeof", (PyCFunction)sys_getsizeof, + METH_VARARGS | METH_KEYWORDS, getsizeof_doc}, + {"_getframe", sys_getframe, METH_VARARGS, getframe_doc}, #ifdef MS_WINDOWS - {"getwindowsversion", (PyCFunction)sys_getwindowsversion, METH_NOARGS, - getwindowsversion_doc}, + {"getwindowsversion", (PyCFunction)sys_getwindowsversion, METH_NOARGS, + getwindowsversion_doc}, #endif /* MS_WINDOWS */ - {"intern", sys_intern, METH_VARARGS, intern_doc}, + {"intern", sys_intern, METH_VARARGS, intern_doc}, #ifdef USE_MALLOPT - {"mdebug", sys_mdebug, METH_VARARGS}, + {"mdebug", sys_mdebug, METH_VARARGS}, #endif - {"setdefaultencoding", sys_setdefaultencoding, METH_VARARGS, - setdefaultencoding_doc}, - {"setfilesystemencoding", sys_setfilesystemencoding, METH_VARARGS, - setfilesystemencoding_doc}, - {"setcheckinterval", sys_setcheckinterval, METH_VARARGS, - setcheckinterval_doc}, - {"getcheckinterval", sys_getcheckinterval, METH_NOARGS, - getcheckinterval_doc}, + {"setdefaultencoding", sys_setdefaultencoding, METH_VARARGS, + setdefaultencoding_doc}, + {"setfilesystemencoding", sys_setfilesystemencoding, METH_VARARGS, + setfilesystemencoding_doc}, + {"setcheckinterval", sys_setcheckinterval, METH_VARARGS, + setcheckinterval_doc}, + {"getcheckinterval", sys_getcheckinterval, METH_NOARGS, + getcheckinterval_doc}, #ifdef WITH_THREAD - {"setswitchinterval", sys_setswitchinterval, METH_VARARGS, - setswitchinterval_doc}, - {"getswitchinterval", sys_getswitchinterval, METH_NOARGS, - getswitchinterval_doc}, + {"setswitchinterval", sys_setswitchinterval, METH_VARARGS, + setswitchinterval_doc}, + {"getswitchinterval", sys_getswitchinterval, METH_NOARGS, + getswitchinterval_doc}, #endif #ifdef HAVE_DLOPEN - {"setdlopenflags", sys_setdlopenflags, METH_VARARGS, - setdlopenflags_doc}, + {"setdlopenflags", sys_setdlopenflags, METH_VARARGS, + setdlopenflags_doc}, #endif - {"setprofile", sys_setprofile, METH_O, setprofile_doc}, - {"getprofile", sys_getprofile, METH_NOARGS, getprofile_doc}, - {"setrecursionlimit", sys_setrecursionlimit, METH_VARARGS, - setrecursionlimit_doc}, + {"setprofile", sys_setprofile, METH_O, setprofile_doc}, + {"getprofile", sys_getprofile, METH_NOARGS, getprofile_doc}, + {"setrecursionlimit", sys_setrecursionlimit, METH_VARARGS, + setrecursionlimit_doc}, #ifdef WITH_TSC - {"settscdump", sys_settscdump, METH_VARARGS, settscdump_doc}, + {"settscdump", sys_settscdump, METH_VARARGS, settscdump_doc}, #endif - {"settrace", sys_settrace, METH_O, settrace_doc}, - {"gettrace", sys_gettrace, METH_NOARGS, gettrace_doc}, - {"call_tracing", sys_call_tracing, METH_VARARGS, call_tracing_doc}, - {NULL, NULL} /* sentinel */ + {"settrace", sys_settrace, METH_O, settrace_doc}, + {"gettrace", sys_gettrace, METH_NOARGS, gettrace_doc}, + {"call_tracing", sys_call_tracing, METH_VARARGS, call_tracing_doc}, + {NULL, NULL} /* sentinel */ }; static PyObject * list_builtin_module_names(void) { - PyObject *list = PyList_New(0); - int i; - if (list == NULL) - return NULL; - for (i = 0; PyImport_Inittab[i].name != NULL; i++) { - PyObject *name = PyUnicode_FromString( - PyImport_Inittab[i].name); - if (name == NULL) - break; - PyList_Append(list, name); - Py_DECREF(name); - } - if (PyList_Sort(list) != 0) { - Py_DECREF(list); - list = NULL; - } - if (list) { - PyObject *v = PyList_AsTuple(list); - Py_DECREF(list); - list = v; - } - return list; + PyObject *list = PyList_New(0); + int i; + if (list == NULL) + return NULL; + for (i = 0; PyImport_Inittab[i].name != NULL; i++) { + PyObject *name = PyUnicode_FromString( + PyImport_Inittab[i].name); + if (name == NULL) + break; + PyList_Append(list, name); + Py_DECREF(name); + } + if (PyList_Sort(list) != 0) { + Py_DECREF(list); + list = NULL; + } + if (list) { + PyObject *v = PyList_AsTuple(list); + Py_DECREF(list); + list = v; + } + return list; } static PyObject *warnoptions = NULL; @@ -1042,27 +1042,27 @@ void PySys_ResetWarnOptions(void) { - if (warnoptions == NULL || !PyList_Check(warnoptions)) - return; - PyList_SetSlice(warnoptions, 0, PyList_GET_SIZE(warnoptions), NULL); + if (warnoptions == NULL || !PyList_Check(warnoptions)) + return; + PyList_SetSlice(warnoptions, 0, PyList_GET_SIZE(warnoptions), NULL); } void PySys_AddWarnOption(const wchar_t *s) { - PyObject *str; + PyObject *str; - if (warnoptions == NULL || !PyList_Check(warnoptions)) { - Py_XDECREF(warnoptions); - warnoptions = PyList_New(0); - if (warnoptions == NULL) - return; - } - str = PyUnicode_FromWideChar(s, -1); - if (str != NULL) { - PyList_Append(warnoptions, str); - Py_DECREF(str); - } + if (warnoptions == NULL || !PyList_Check(warnoptions)) { + Py_XDECREF(warnoptions); + warnoptions = PyList_New(0); + if (warnoptions == NULL) + return; + } + str = PyUnicode_FromWideChar(s, -1); + if (str != NULL) { + PyList_Append(warnoptions, str); + Py_DECREF(str); + } } int @@ -1174,64 +1174,64 @@ static void svnversion_init(void) { - const char *python, *br_start, *br_end, *br_end2, *svnversion; - Py_ssize_t len; - int istag = 0; - - if (svn_initialized) - return; - - python = strstr(headurl, "/python/"); - if (!python) { - strcpy(branch, "unknown branch"); - strcpy(shortbranch, "unknown"); - } - else { - br_start = python + 8; - br_end = strchr(br_start, '/'); - assert(br_end); - - /* Works even for trunk, - as we are in trunk/Python/sysmodule.c */ - br_end2 = strchr(br_end+1, '/'); - - istag = strncmp(br_start, "tags", 4) == 0; - if (strncmp(br_start, "trunk", 5) == 0) { - strcpy(branch, "trunk"); - strcpy(shortbranch, "trunk"); - } - else if (istag || strncmp(br_start, "branches", 8) == 0) { - len = br_end2 - br_start; - strncpy(branch, br_start, len); - branch[len] = '\0'; - - len = br_end2 - (br_end + 1); - strncpy(shortbranch, br_end + 1, len); - shortbranch[len] = '\0'; - } - else { - Py_FatalError("bad HeadURL"); - return; - } - } - - - svnversion = _Py_svnversion(); - if (strcmp(svnversion, "Unversioned directory") != 0 && strcmp(svnversion, "exported") != 0) - svn_revision = svnversion; - else if (istag) { - len = strlen(_patchlevel_revision); - assert(len >= 13); - assert(len < (sizeof(patchlevel_revision) + 13)); - strncpy(patchlevel_revision, _patchlevel_revision + 11, - len - 13); - patchlevel_revision[len - 13] = '\0'; - svn_revision = patchlevel_revision; - } - else - svn_revision = ""; + const char *python, *br_start, *br_end, *br_end2, *svnversion; + Py_ssize_t len; + int istag = 0; + + if (svn_initialized) + return; + + python = strstr(headurl, "/python/"); + if (!python) { + strcpy(branch, "unknown branch"); + strcpy(shortbranch, "unknown"); + } + else { + br_start = python + 8; + br_end = strchr(br_start, '/'); + assert(br_end); + + /* Works even for trunk, + as we are in trunk/Python/sysmodule.c */ + br_end2 = strchr(br_end+1, '/'); + + istag = strncmp(br_start, "tags", 4) == 0; + if (strncmp(br_start, "trunk", 5) == 0) { + strcpy(branch, "trunk"); + strcpy(shortbranch, "trunk"); + } + else if (istag || strncmp(br_start, "branches", 8) == 0) { + len = br_end2 - br_start; + strncpy(branch, br_start, len); + branch[len] = '\0'; + + len = br_end2 - (br_end + 1); + strncpy(shortbranch, br_end + 1, len); + shortbranch[len] = '\0'; + } + else { + Py_FatalError("bad HeadURL"); + return; + } + } + + + svnversion = _Py_svnversion(); + if (strcmp(svnversion, "Unversioned directory") != 0 && strcmp(svnversion, "exported") != 0) + svn_revision = svnversion; + else if (istag) { + len = strlen(_patchlevel_revision); + assert(len >= 13); + assert(len < (sizeof(patchlevel_revision) + 13)); + strncpy(patchlevel_revision, _patchlevel_revision + 11, + len - 13); + patchlevel_revision[len - 13] = '\0'; + svn_revision = patchlevel_revision; + } + else + svn_revision = ""; - svn_initialized = 1; + svn_initialized = 1; } /* Return svnversion output if available. @@ -1240,15 +1240,15 @@ const char* Py_SubversionRevision() { - svnversion_init(); - return svn_revision; + svnversion_init(); + return svn_revision; } const char* Py_SubversionShortBranch() { - svnversion_init(); - return shortbranch; + svnversion_init(); + return shortbranch; } @@ -1260,71 +1260,71 @@ static PyTypeObject FlagsType; static PyStructSequence_Field flags_fields[] = { - {"debug", "-d"}, - {"division_warning", "-Q"}, - {"inspect", "-i"}, - {"interactive", "-i"}, - {"optimize", "-O or -OO"}, - {"dont_write_bytecode", "-B"}, - {"no_user_site", "-s"}, - {"no_site", "-S"}, - {"ignore_environment", "-E"}, - {"verbose", "-v"}, + {"debug", "-d"}, + {"division_warning", "-Q"}, + {"inspect", "-i"}, + {"interactive", "-i"}, + {"optimize", "-O or -OO"}, + {"dont_write_bytecode", "-B"}, + {"no_user_site", "-s"}, + {"no_site", "-S"}, + {"ignore_environment", "-E"}, + {"verbose", "-v"}, #ifdef RISCOS - {"riscos_wimp", "???"}, + {"riscos_wimp", "???"}, #endif - /* {"unbuffered", "-u"}, */ - /* {"skip_first", "-x"}, */ - {"bytes_warning", "-b"}, - {0} + /* {"unbuffered", "-u"}, */ + /* {"skip_first", "-x"}, */ + {"bytes_warning", "-b"}, + {0} }; static PyStructSequence_Desc flags_desc = { - "sys.flags", /* name */ - flags__doc__, /* doc */ - flags_fields, /* fields */ + "sys.flags", /* name */ + flags__doc__, /* doc */ + flags_fields, /* fields */ #ifdef RISCOS - 12 + 12 #else - 11 + 11 #endif }; static PyObject* make_flags(void) { - int pos = 0; - PyObject *seq; + int pos = 0; + PyObject *seq; - seq = PyStructSequence_New(&FlagsType); - if (seq == NULL) - return NULL; + seq = PyStructSequence_New(&FlagsType); + if (seq == NULL) + return NULL; #define SetFlag(flag) \ - PyStructSequence_SET_ITEM(seq, pos++, PyLong_FromLong(flag)) + PyStructSequence_SET_ITEM(seq, pos++, PyLong_FromLong(flag)) - SetFlag(Py_DebugFlag); - SetFlag(Py_DivisionWarningFlag); - SetFlag(Py_InspectFlag); - SetFlag(Py_InteractiveFlag); - SetFlag(Py_OptimizeFlag); - SetFlag(Py_DontWriteBytecodeFlag); - SetFlag(Py_NoUserSiteDirectory); - SetFlag(Py_NoSiteFlag); - SetFlag(Py_IgnoreEnvironmentFlag); - SetFlag(Py_VerboseFlag); + SetFlag(Py_DebugFlag); + SetFlag(Py_DivisionWarningFlag); + SetFlag(Py_InspectFlag); + SetFlag(Py_InteractiveFlag); + SetFlag(Py_OptimizeFlag); + SetFlag(Py_DontWriteBytecodeFlag); + SetFlag(Py_NoUserSiteDirectory); + SetFlag(Py_NoSiteFlag); + SetFlag(Py_IgnoreEnvironmentFlag); + SetFlag(Py_VerboseFlag); #ifdef RISCOS - SetFlag(Py_RISCOSWimpFlag); + SetFlag(Py_RISCOSWimpFlag); #endif - /* SetFlag(saw_unbuffered_flag); */ - /* SetFlag(skipfirstline); */ + /* SetFlag(saw_unbuffered_flag); */ + /* SetFlag(skipfirstline); */ SetFlag(Py_BytesWarningFlag); #undef SetFlag - if (PyErr_Occurred()) { - return NULL; - } - return seq; + if (PyErr_Occurred()) { + return NULL; + } + return seq; } PyDoc_STRVAR(version_info__doc__, @@ -1335,330 +1335,330 @@ static PyTypeObject VersionInfoType; static PyStructSequence_Field version_info_fields[] = { - {"major", "Major release number"}, - {"minor", "Minor release number"}, - {"micro", "Patch release number"}, - {"releaselevel", "'alpha', 'beta', 'candidate', or 'release'"}, - {"serial", "Serial release number"}, - {0} + {"major", "Major release number"}, + {"minor", "Minor release number"}, + {"micro", "Patch release number"}, + {"releaselevel", "'alpha', 'beta', 'candidate', or 'release'"}, + {"serial", "Serial release number"}, + {0} }; static PyStructSequence_Desc version_info_desc = { - "sys.version_info", /* name */ - version_info__doc__, /* doc */ - version_info_fields, /* fields */ - 5 + "sys.version_info", /* name */ + version_info__doc__, /* doc */ + version_info_fields, /* fields */ + 5 }; static PyObject * make_version_info(void) { - PyObject *version_info; - char *s; - int pos = 0; - - version_info = PyStructSequence_New(&VersionInfoType); - if (version_info == NULL) { - return NULL; - } - - /* - * These release level checks are mutually exclusive and cover - * the field, so don't get too fancy with the pre-processor! - */ + PyObject *version_info; + char *s; + int pos = 0; + + version_info = PyStructSequence_New(&VersionInfoType); + if (version_info == NULL) { + return NULL; + } + + /* + * These release level checks are mutually exclusive and cover + * the field, so don't get too fancy with the pre-processor! + */ #if PY_RELEASE_LEVEL == PY_RELEASE_LEVEL_ALPHA - s = "alpha"; + s = "alpha"; #elif PY_RELEASE_LEVEL == PY_RELEASE_LEVEL_BETA - s = "beta"; + s = "beta"; #elif PY_RELEASE_LEVEL == PY_RELEASE_LEVEL_GAMMA - s = "candidate"; + s = "candidate"; #elif PY_RELEASE_LEVEL == PY_RELEASE_LEVEL_FINAL - s = "final"; + s = "final"; #endif #define SetIntItem(flag) \ - PyStructSequence_SET_ITEM(version_info, pos++, PyLong_FromLong(flag)) + PyStructSequence_SET_ITEM(version_info, pos++, PyLong_FromLong(flag)) #define SetStrItem(flag) \ - PyStructSequence_SET_ITEM(version_info, pos++, PyUnicode_FromString(flag)) + PyStructSequence_SET_ITEM(version_info, pos++, PyUnicode_FromString(flag)) - SetIntItem(PY_MAJOR_VERSION); - SetIntItem(PY_MINOR_VERSION); - SetIntItem(PY_MICRO_VERSION); - SetStrItem(s); - SetIntItem(PY_RELEASE_SERIAL); + SetIntItem(PY_MAJOR_VERSION); + SetIntItem(PY_MINOR_VERSION); + SetIntItem(PY_MICRO_VERSION); + SetStrItem(s); + SetIntItem(PY_RELEASE_SERIAL); #undef SetIntItem #undef SetStrItem - if (PyErr_Occurred()) { - Py_CLEAR(version_info); - return NULL; - } - return version_info; + if (PyErr_Occurred()) { + Py_CLEAR(version_info); + return NULL; + } + return version_info; } static struct PyModuleDef sysmodule = { - PyModuleDef_HEAD_INIT, - "sys", - sys_doc, - -1, /* multiple "initialization" just copies the module dict. */ - sys_methods, - NULL, - NULL, - NULL, - NULL + PyModuleDef_HEAD_INIT, + "sys", + sys_doc, + -1, /* multiple "initialization" just copies the module dict. */ + sys_methods, + NULL, + NULL, + NULL, + NULL }; PyObject * _PySys_Init(void) { - PyObject *m, *v, *sysdict; - char *s; + PyObject *m, *v, *sysdict; + char *s; - m = PyModule_Create(&sysmodule); - if (m == NULL) - return NULL; - sysdict = PyModule_GetDict(m); -#define SET_SYS_FROM_STRING(key, value) \ - v = value; \ - if (v != NULL) \ - PyDict_SetItemString(sysdict, key, v); \ - Py_XDECREF(v) - - /* Check that stdin is not a directory - Using shell redirection, you can redirect stdin to a directory, - crashing the Python interpreter. Catch this common mistake here - and output a useful error message. Note that under MS Windows, - the shell already prevents that. */ + m = PyModule_Create(&sysmodule); + if (m == NULL) + return NULL; + sysdict = PyModule_GetDict(m); +#define SET_SYS_FROM_STRING(key, value) \ + v = value; \ + if (v != NULL) \ + PyDict_SetItemString(sysdict, key, v); \ + Py_XDECREF(v) + + /* Check that stdin is not a directory + Using shell redirection, you can redirect stdin to a directory, + crashing the Python interpreter. Catch this common mistake here + and output a useful error message. Note that under MS Windows, + the shell already prevents that. */ #if !defined(MS_WINDOWS) - { - struct stat sb; - if (fstat(fileno(stdin), &sb) == 0 && - S_ISDIR(sb.st_mode)) { - /* There's nothing more we can do. */ - /* Py_FatalError() will core dump, so just exit. */ - PySys_WriteStderr("Python error: is a directory, cannot continue\n"); - exit(EXIT_FAILURE); - } - } -#endif - - /* stdin/stdout/stderr are now set by pythonrun.c */ - - PyDict_SetItemString(sysdict, "__displayhook__", - PyDict_GetItemString(sysdict, "displayhook")); - PyDict_SetItemString(sysdict, "__excepthook__", - PyDict_GetItemString(sysdict, "excepthook")); - SET_SYS_FROM_STRING("version", - PyUnicode_FromString(Py_GetVersion())); - SET_SYS_FROM_STRING("hexversion", - PyLong_FromLong(PY_VERSION_HEX)); - svnversion_init(); - SET_SYS_FROM_STRING("subversion", - Py_BuildValue("(UUU)", "CPython", branch, - svn_revision)); - SET_SYS_FROM_STRING("dont_write_bytecode", - PyBool_FromLong(Py_DontWriteBytecodeFlag)); - SET_SYS_FROM_STRING("api_version", - PyLong_FromLong(PYTHON_API_VERSION)); - SET_SYS_FROM_STRING("copyright", - PyUnicode_FromString(Py_GetCopyright())); - SET_SYS_FROM_STRING("platform", - PyUnicode_FromString(Py_GetPlatform())); - SET_SYS_FROM_STRING("executable", - PyUnicode_FromWideChar( - Py_GetProgramFullPath(), -1)); - SET_SYS_FROM_STRING("prefix", - PyUnicode_FromWideChar(Py_GetPrefix(), -1)); - SET_SYS_FROM_STRING("exec_prefix", - PyUnicode_FromWideChar(Py_GetExecPrefix(), -1)); - SET_SYS_FROM_STRING("maxsize", - PyLong_FromSsize_t(PY_SSIZE_T_MAX)); - SET_SYS_FROM_STRING("float_info", - PyFloat_GetInfo()); - SET_SYS_FROM_STRING("int_info", - PyLong_GetInfo()); - SET_SYS_FROM_STRING("maxunicode", - PyLong_FromLong(PyUnicode_GetMax())); - SET_SYS_FROM_STRING("builtin_module_names", - list_builtin_module_names()); - { - /* Assumes that longs are at least 2 bytes long. - Should be safe! */ - unsigned long number = 1; - char *value; - - s = (char *) &number; - if (s[0] == 0) - value = "big"; - else - value = "little"; - SET_SYS_FROM_STRING("byteorder", - PyUnicode_FromString(value)); - } + { + struct stat sb; + if (fstat(fileno(stdin), &sb) == 0 && + S_ISDIR(sb.st_mode)) { + /* There's nothing more we can do. */ + /* Py_FatalError() will core dump, so just exit. */ + PySys_WriteStderr("Python error: is a directory, cannot continue\n"); + exit(EXIT_FAILURE); + } + } +#endif + + /* stdin/stdout/stderr are now set by pythonrun.c */ + + PyDict_SetItemString(sysdict, "__displayhook__", + PyDict_GetItemString(sysdict, "displayhook")); + PyDict_SetItemString(sysdict, "__excepthook__", + PyDict_GetItemString(sysdict, "excepthook")); + SET_SYS_FROM_STRING("version", + PyUnicode_FromString(Py_GetVersion())); + SET_SYS_FROM_STRING("hexversion", + PyLong_FromLong(PY_VERSION_HEX)); + svnversion_init(); + SET_SYS_FROM_STRING("subversion", + Py_BuildValue("(UUU)", "CPython", branch, + svn_revision)); + SET_SYS_FROM_STRING("dont_write_bytecode", + PyBool_FromLong(Py_DontWriteBytecodeFlag)); + SET_SYS_FROM_STRING("api_version", + PyLong_FromLong(PYTHON_API_VERSION)); + SET_SYS_FROM_STRING("copyright", + PyUnicode_FromString(Py_GetCopyright())); + SET_SYS_FROM_STRING("platform", + PyUnicode_FromString(Py_GetPlatform())); + SET_SYS_FROM_STRING("executable", + PyUnicode_FromWideChar( + Py_GetProgramFullPath(), -1)); + SET_SYS_FROM_STRING("prefix", + PyUnicode_FromWideChar(Py_GetPrefix(), -1)); + SET_SYS_FROM_STRING("exec_prefix", + PyUnicode_FromWideChar(Py_GetExecPrefix(), -1)); + SET_SYS_FROM_STRING("maxsize", + PyLong_FromSsize_t(PY_SSIZE_T_MAX)); + SET_SYS_FROM_STRING("float_info", + PyFloat_GetInfo()); + SET_SYS_FROM_STRING("int_info", + PyLong_GetInfo()); + SET_SYS_FROM_STRING("maxunicode", + PyLong_FromLong(PyUnicode_GetMax())); + SET_SYS_FROM_STRING("builtin_module_names", + list_builtin_module_names()); + { + /* Assumes that longs are at least 2 bytes long. + Should be safe! */ + unsigned long number = 1; + char *value; + + s = (char *) &number; + if (s[0] == 0) + value = "big"; + else + value = "little"; + SET_SYS_FROM_STRING("byteorder", + PyUnicode_FromString(value)); + } #ifdef MS_COREDLL - SET_SYS_FROM_STRING("dllhandle", - PyLong_FromVoidPtr(PyWin_DLLhModule)); - SET_SYS_FROM_STRING("winver", - PyUnicode_FromString(PyWin_DLLVersionString)); -#endif - if (warnoptions == NULL) { - warnoptions = PyList_New(0); - } - else { - Py_INCREF(warnoptions); - } - if (warnoptions != NULL) { - PyDict_SetItemString(sysdict, "warnoptions", warnoptions); - } - - /* version_info */ - if (VersionInfoType.tp_name == 0) - PyStructSequence_InitType(&VersionInfoType, &version_info_desc); - SET_SYS_FROM_STRING("version_info", make_version_info()); - /* prevent user from creating new instances */ - VersionInfoType.tp_init = NULL; - VersionInfoType.tp_new = NULL; - - /* flags */ - if (FlagsType.tp_name == 0) - PyStructSequence_InitType(&FlagsType, &flags_desc); - SET_SYS_FROM_STRING("flags", make_flags()); - /* prevent user from creating new instances */ - FlagsType.tp_init = NULL; - FlagsType.tp_new = NULL; + SET_SYS_FROM_STRING("dllhandle", + PyLong_FromVoidPtr(PyWin_DLLhModule)); + SET_SYS_FROM_STRING("winver", + PyUnicode_FromString(PyWin_DLLVersionString)); +#endif + if (warnoptions == NULL) { + warnoptions = PyList_New(0); + } + else { + Py_INCREF(warnoptions); + } + if (warnoptions != NULL) { + PyDict_SetItemString(sysdict, "warnoptions", warnoptions); + } + + /* version_info */ + if (VersionInfoType.tp_name == 0) + PyStructSequence_InitType(&VersionInfoType, &version_info_desc); + SET_SYS_FROM_STRING("version_info", make_version_info()); + /* prevent user from creating new instances */ + VersionInfoType.tp_init = NULL; + VersionInfoType.tp_new = NULL; + + /* flags */ + if (FlagsType.tp_name == 0) + PyStructSequence_InitType(&FlagsType, &flags_desc); + SET_SYS_FROM_STRING("flags", make_flags()); + /* prevent user from creating new instances */ + FlagsType.tp_init = NULL; + FlagsType.tp_new = NULL; #if defined(MS_WINDOWS) - /* getwindowsversion */ - if (WindowsVersionType.tp_name == 0) - PyStructSequence_InitType(&WindowsVersionType, &windows_version_desc); - /* prevent user from creating new instances */ - WindowsVersionType.tp_init = NULL; - WindowsVersionType.tp_new = NULL; + /* getwindowsversion */ + if (WindowsVersionType.tp_name == 0) + PyStructSequence_InitType(&WindowsVersionType, &windows_version_desc); + /* prevent user from creating new instances */ + WindowsVersionType.tp_init = NULL; + WindowsVersionType.tp_new = NULL; #endif - /* float repr style: 0.03 (short) vs 0.029999999999999999 (legacy) */ + /* float repr style: 0.03 (short) vs 0.029999999999999999 (legacy) */ #ifndef PY_NO_SHORT_FLOAT_REPR - SET_SYS_FROM_STRING("float_repr_style", - PyUnicode_FromString("short")); + SET_SYS_FROM_STRING("float_repr_style", + PyUnicode_FromString("short")); #else - SET_SYS_FROM_STRING("float_repr_style", - PyUnicode_FromString("legacy")); + SET_SYS_FROM_STRING("float_repr_style", + PyUnicode_FromString("legacy")); #endif #undef SET_SYS_FROM_STRING - if (PyErr_Occurred()) - return NULL; - return m; + if (PyErr_Occurred()) + return NULL; + return m; } static PyObject * makepathobject(const wchar_t *path, wchar_t delim) { - int i, n; - const wchar_t *p; - PyObject *v, *w; - - n = 1; - p = path; - while ((p = wcschr(p, delim)) != NULL) { - n++; - p++; - } - v = PyList_New(n); - if (v == NULL) - return NULL; - for (i = 0; ; i++) { - p = wcschr(path, delim); - if (p == NULL) - p = path + wcslen(path); /* End of string */ - w = PyUnicode_FromWideChar(path, (Py_ssize_t)(p - path)); - if (w == NULL) { - Py_DECREF(v); - return NULL; - } - PyList_SetItem(v, i, w); - if (*p == '\0') - break; - path = p+1; - } - return v; + int i, n; + const wchar_t *p; + PyObject *v, *w; + + n = 1; + p = path; + while ((p = wcschr(p, delim)) != NULL) { + n++; + p++; + } + v = PyList_New(n); + if (v == NULL) + return NULL; + for (i = 0; ; i++) { + p = wcschr(path, delim); + if (p == NULL) + p = path + wcslen(path); /* End of string */ + w = PyUnicode_FromWideChar(path, (Py_ssize_t)(p - path)); + if (w == NULL) { + Py_DECREF(v); + return NULL; + } + PyList_SetItem(v, i, w); + if (*p == '\0') + break; + path = p+1; + } + return v; } void PySys_SetPath(const wchar_t *path) { - PyObject *v; - if ((v = makepathobject(path, DELIM)) == NULL) - Py_FatalError("can't create sys.path"); - if (PySys_SetObject("path", v) != 0) - Py_FatalError("can't assign sys.path"); - Py_DECREF(v); + PyObject *v; + if ((v = makepathobject(path, DELIM)) == NULL) + Py_FatalError("can't create sys.path"); + if (PySys_SetObject("path", v) != 0) + Py_FatalError("can't assign sys.path"); + Py_DECREF(v); } static PyObject * makeargvobject(int argc, wchar_t **argv) { - PyObject *av; - if (argc <= 0 || argv == NULL) { - /* Ensure at least one (empty) argument is seen */ - static wchar_t *empty_argv[1] = {L""}; - argv = empty_argv; - argc = 1; - } - av = PyList_New(argc); - if (av != NULL) { - int i; - for (i = 0; i < argc; i++) { + PyObject *av; + if (argc <= 0 || argv == NULL) { + /* Ensure at least one (empty) argument is seen */ + static wchar_t *empty_argv[1] = {L""}; + argv = empty_argv; + argc = 1; + } + av = PyList_New(argc); + if (av != NULL) { + int i; + for (i = 0; i < argc; i++) { #ifdef __VMS - PyObject *v; + PyObject *v; - /* argv[0] is the script pathname if known */ - if (i == 0) { - char* fn = decc$translate_vms(argv[0]); - if ((fn == (char *)0) || fn == (char *)-1) - v = PyUnicode_FromString(argv[0]); - else - v = PyUnicode_FromString( - decc$translate_vms(argv[0])); - } else - v = PyUnicode_FromString(argv[i]); + /* argv[0] is the script pathname if known */ + if (i == 0) { + char* fn = decc$translate_vms(argv[0]); + if ((fn == (char *)0) || fn == (char *)-1) + v = PyUnicode_FromString(argv[0]); + else + v = PyUnicode_FromString( + decc$translate_vms(argv[0])); + } else + v = PyUnicode_FromString(argv[i]); #else - PyObject *v = PyUnicode_FromWideChar(argv[i], -1); + PyObject *v = PyUnicode_FromWideChar(argv[i], -1); #endif - if (v == NULL) { - Py_DECREF(av); - av = NULL; - break; - } - PyList_SetItem(av, i, v); - } - } - return av; + if (v == NULL) { + Py_DECREF(av); + av = NULL; + break; + } + PyList_SetItem(av, i, v); + } + } + return av; } #ifdef HAVE_REALPATH static wchar_t* _wrealpath(const wchar_t *path, wchar_t *resolved_path) { - char cpath[PATH_MAX]; - char cresolved_path[PATH_MAX]; - char *res; - size_t r; - r = wcstombs(cpath, path, PATH_MAX); - if (r == (size_t)-1 || r >= PATH_MAX) { - errno = EINVAL; - return NULL; - } - res = realpath(cpath, cresolved_path); - if (res == NULL) - return NULL; - r = mbstowcs(resolved_path, cresolved_path, PATH_MAX); - if (r == (size_t)-1 || r >= PATH_MAX) { - errno = EINVAL; - return NULL; - } - return resolved_path; + char cpath[PATH_MAX]; + char cresolved_path[PATH_MAX]; + char *res; + size_t r; + r = wcstombs(cpath, path, PATH_MAX); + if (r == (size_t)-1 || r >= PATH_MAX) { + errno = EINVAL; + return NULL; + } + res = realpath(cpath, cresolved_path); + if (res == NULL) + return NULL; + r = mbstowcs(resolved_path, cresolved_path, PATH_MAX); + if (r == (size_t)-1 || r >= PATH_MAX) { + errno = EINVAL; + return NULL; + } + return resolved_path; } #endif @@ -1666,101 +1666,101 @@ PySys_SetArgv(int argc, wchar_t **argv) { #if defined(HAVE_REALPATH) - wchar_t fullpath[MAXPATHLEN]; + wchar_t fullpath[MAXPATHLEN]; #elif defined(MS_WINDOWS) && !defined(MS_WINCE) - wchar_t fullpath[MAX_PATH]; + wchar_t fullpath[MAX_PATH]; #endif - PyObject *av = makeargvobject(argc, argv); - PyObject *path = PySys_GetObject("path"); - if (av == NULL) - Py_FatalError("no mem for sys.argv"); - if (PySys_SetObject("argv", av) != 0) - Py_FatalError("can't assign sys.argv"); - if (path != NULL) { - wchar_t *argv0 = argv[0]; - wchar_t *p = NULL; - Py_ssize_t n = 0; - PyObject *a; - extern int _Py_wreadlink(const wchar_t *, wchar_t *, size_t); + PyObject *av = makeargvobject(argc, argv); + PyObject *path = PySys_GetObject("path"); + if (av == NULL) + Py_FatalError("no mem for sys.argv"); + if (PySys_SetObject("argv", av) != 0) + Py_FatalError("can't assign sys.argv"); + if (path != NULL) { + wchar_t *argv0 = argv[0]; + wchar_t *p = NULL; + Py_ssize_t n = 0; + PyObject *a; + extern int _Py_wreadlink(const wchar_t *, wchar_t *, size_t); #ifdef HAVE_READLINK - wchar_t link[MAXPATHLEN+1]; - wchar_t argv0copy[2*MAXPATHLEN+1]; - int nr = 0; - if (argc > 0 && argv0 != NULL && wcscmp(argv0, L"-c") != 0) - nr = _Py_wreadlink(argv0, link, MAXPATHLEN); - if (nr > 0) { - /* It's a symlink */ - link[nr] = '\0'; - if (link[0] == SEP) - argv0 = link; /* Link to absolute path */ - else if (wcschr(link, SEP) == NULL) - ; /* Link without path */ - else { - /* Must join(dirname(argv0), link) */ - wchar_t *q = wcsrchr(argv0, SEP); - if (q == NULL) - argv0 = link; /* argv0 without path */ - else { - /* Must make a copy */ - wcscpy(argv0copy, argv0); - q = wcsrchr(argv0copy, SEP); - wcscpy(q+1, link); - argv0 = argv0copy; - } - } - } + wchar_t link[MAXPATHLEN+1]; + wchar_t argv0copy[2*MAXPATHLEN+1]; + int nr = 0; + if (argc > 0 && argv0 != NULL && wcscmp(argv0, L"-c") != 0) + nr = _Py_wreadlink(argv0, link, MAXPATHLEN); + if (nr > 0) { + /* It's a symlink */ + link[nr] = '\0'; + if (link[0] == SEP) + argv0 = link; /* Link to absolute path */ + else if (wcschr(link, SEP) == NULL) + ; /* Link without path */ + else { + /* Must join(dirname(argv0), link) */ + wchar_t *q = wcsrchr(argv0, SEP); + if (q == NULL) + argv0 = link; /* argv0 without path */ + else { + /* Must make a copy */ + wcscpy(argv0copy, argv0); + q = wcsrchr(argv0copy, SEP); + wcscpy(q+1, link); + argv0 = argv0copy; + } + } + } #endif /* HAVE_READLINK */ #if SEP == '\\' /* Special case for MS filename syntax */ - if (argc > 0 && argv0 != NULL && wcscmp(argv0, L"-c") != 0) { - wchar_t *q; + if (argc > 0 && argv0 != NULL && wcscmp(argv0, L"-c") != 0) { + wchar_t *q; #if defined(MS_WINDOWS) && !defined(MS_WINCE) - /* This code here replaces the first element in argv with the full - path that it represents. Under CE, there are no relative paths so - the argument must be the full path anyway. */ - wchar_t *ptemp; - if (GetFullPathNameW(argv0, - sizeof(fullpath)/sizeof(fullpath[0]), - fullpath, - &ptemp)) { - argv0 = fullpath; - } -#endif - p = wcsrchr(argv0, SEP); - /* Test for alternate separator */ - q = wcsrchr(p ? p : argv0, '/'); - if (q != NULL) - p = q; - if (p != NULL) { - n = p + 1 - argv0; - if (n > 1 && p[-1] != ':') - n--; /* Drop trailing separator */ - } - } + /* This code here replaces the first element in argv with the full + path that it represents. Under CE, there are no relative paths so + the argument must be the full path anyway. */ + wchar_t *ptemp; + if (GetFullPathNameW(argv0, + sizeof(fullpath)/sizeof(fullpath[0]), + fullpath, + &ptemp)) { + argv0 = fullpath; + } +#endif + p = wcsrchr(argv0, SEP); + /* Test for alternate separator */ + q = wcsrchr(p ? p : argv0, '/'); + if (q != NULL) + p = q; + if (p != NULL) { + n = p + 1 - argv0; + if (n > 1 && p[-1] != ':') + n--; /* Drop trailing separator */ + } + } #else /* All other filename syntaxes */ - if (argc > 0 && argv0 != NULL && wcscmp(argv0, L"-c") != 0) { + if (argc > 0 && argv0 != NULL && wcscmp(argv0, L"-c") != 0) { #if defined(HAVE_REALPATH) - if (_wrealpath(argv0, fullpath)) { - argv0 = fullpath; - } -#endif - p = wcsrchr(argv0, SEP); - } - if (p != NULL) { - n = p + 1 - argv0; + if (_wrealpath(argv0, fullpath)) { + argv0 = fullpath; + } +#endif + p = wcsrchr(argv0, SEP); + } + if (p != NULL) { + n = p + 1 - argv0; #if SEP == '/' /* Special case for Unix filename syntax */ - if (n > 1) - n--; /* Drop trailing separator */ + if (n > 1) + n--; /* Drop trailing separator */ #endif /* Unix */ - } + } #endif /* All others */ - a = PyUnicode_FromWideChar(argv0, n); - if (a == NULL) - Py_FatalError("no mem for sys.path insertion"); - if (PyList_Insert(path, 0, a) < 0) - Py_FatalError("sys.path.insert(0) failed"); - Py_DECREF(a); - } - Py_DECREF(av); + a = PyUnicode_FromWideChar(argv0, n); + if (a == NULL) + Py_FatalError("no mem for sys.path insertion"); + if (PyList_Insert(path, 0, a) < 0) + Py_FatalError("sys.path.insert(0) failed"); + Py_DECREF(a); + } + Py_DECREF(av); } /* Reimplementation of PyFile_WriteString() no calling indirectly @@ -1769,37 +1769,37 @@ static int sys_pyfile_write(const char *text, PyObject *file) { - PyObject *unicode = NULL, *writer = NULL, *args = NULL, *result = NULL; - int err; + PyObject *unicode = NULL, *writer = NULL, *args = NULL, *result = NULL; + int err; - unicode = PyUnicode_FromString(text); - if (unicode == NULL) - goto error; - - writer = PyObject_GetAttrString(file, "write"); - if (writer == NULL) - goto error; - - args = PyTuple_Pack(1, unicode); - if (args == NULL) - goto error; - - result = PyEval_CallObject(writer, args); - if (result == NULL) { - goto error; - } else { - err = 0; - goto finally; - } + unicode = PyUnicode_FromString(text); + if (unicode == NULL) + goto error; + + writer = PyObject_GetAttrString(file, "write"); + if (writer == NULL) + goto error; + + args = PyTuple_Pack(1, unicode); + if (args == NULL) + goto error; + + result = PyEval_CallObject(writer, args); + if (result == NULL) { + goto error; + } else { + err = 0; + goto finally; + } error: - err = -1; + err = -1; finally: - Py_XDECREF(unicode); - Py_XDECREF(writer); - Py_XDECREF(args); - Py_XDECREF(result); - return err; + Py_XDECREF(unicode); + Py_XDECREF(writer); + Py_XDECREF(args); + Py_XDECREF(result); + return err; } @@ -1834,44 +1834,44 @@ static void mywrite(char *name, FILE *fp, const char *format, va_list va) { - PyObject *file; - PyObject *error_type, *error_value, *error_traceback; - char buffer[1001]; - int written; - - PyErr_Fetch(&error_type, &error_value, &error_traceback); - file = PySys_GetObject(name); - written = PyOS_vsnprintf(buffer, sizeof(buffer), format, va); - if (sys_pyfile_write(buffer, file) != 0) { - PyErr_Clear(); - fputs(buffer, fp); - } - if (written < 0 || (size_t)written >= sizeof(buffer)) { - const char *truncated = "... truncated"; - if (sys_pyfile_write(truncated, file) != 0) { - PyErr_Clear(); - fputs(truncated, fp); - } - } - PyErr_Restore(error_type, error_value, error_traceback); + PyObject *file; + PyObject *error_type, *error_value, *error_traceback; + char buffer[1001]; + int written; + + PyErr_Fetch(&error_type, &error_value, &error_traceback); + file = PySys_GetObject(name); + written = PyOS_vsnprintf(buffer, sizeof(buffer), format, va); + if (sys_pyfile_write(buffer, file) != 0) { + PyErr_Clear(); + fputs(buffer, fp); + } + if (written < 0 || (size_t)written >= sizeof(buffer)) { + const char *truncated = "... truncated"; + if (sys_pyfile_write(truncated, file) != 0) { + PyErr_Clear(); + fputs(truncated, fp); + } + } + PyErr_Restore(error_type, error_value, error_traceback); } void PySys_WriteStdout(const char *format, ...) { - va_list va; + va_list va; - va_start(va, format); - mywrite("stdout", stdout, format, va); - va_end(va); + va_start(va, format); + mywrite("stdout", stdout, format, va); + va_end(va); } void PySys_WriteStderr(const char *format, ...) { - va_list va; + va_list va; - va_start(va, format); - mywrite("stderr", stderr, format, va); - va_end(va); + va_start(va, format); + mywrite("stderr", stderr, format, va); + va_end(va); } Modified: python/branches/py3k-jit/Python/thread.c ============================================================================== --- python/branches/py3k-jit/Python/thread.c (original) +++ python/branches/py3k-jit/Python/thread.c Mon May 10 23:55:43 2010 @@ -40,7 +40,7 @@ #endif /* Check if we're running on HP-UX and _SC_THREADS is defined. If so, then - enough of the Posix threads package is implimented to support python + enough of the Posix threads package is implimented to support python threads. This is valid for HP-UX 11.23 running on an ia64 system. If needed, add @@ -58,8 +58,8 @@ #ifdef Py_DEBUG static int thread_debug = 0; -#define dprintf(args) (void)((thread_debug & 1) && printf args) -#define d2printf(args) ((thread_debug & 8) && printf args) +#define dprintf(args) (void)((thread_debug & 1) && printf args) +#define d2printf(args) ((thread_debug & 8) && printf args) #else #define dprintf(args) #define d2printf(args) @@ -73,20 +73,20 @@ PyThread_init_thread(void) { #ifdef Py_DEBUG - char *p = Py_GETENV("PYTHONTHREADDEBUG"); + char *p = Py_GETENV("PYTHONTHREADDEBUG"); - if (p) { - if (*p) - thread_debug = atoi(p); - else - thread_debug = 1; - } + if (p) { + if (*p) + thread_debug = atoi(p); + else + thread_debug = 1; + } #endif /* Py_DEBUG */ - if (initialized) - return; - initialized = 1; - dprintf(("PyThread_init_thread called\n")); - PyThread__init_thread(); + if (initialized) + return; + initialized = 1; + dprintf(("PyThread_init_thread called\n")); + PyThread__init_thread(); } /* Support for runtime thread stack size tuning. @@ -145,21 +145,21 @@ size_t PyThread_get_stacksize(void) { - return _pythread_stacksize; + return _pythread_stacksize; } /* Only platforms defining a THREAD_SET_STACKSIZE() macro in thread_.h support changing the stack size. Return 0 if stack size is valid, - -1 if stack size value is invalid, - -2 if setting stack size is not supported. */ + -1 if stack size value is invalid, + -2 if setting stack size is not supported. */ int PyThread_set_stacksize(size_t size) { #if defined(THREAD_SET_STACKSIZE) - return THREAD_SET_STACKSIZE(size); + return THREAD_SET_STACKSIZE(size); #else - return -2; + return -2; #endif } @@ -211,15 +211,15 @@ * to enforce exclusion internally. */ struct key { - /* Next record in the list, or NULL if this is the last record. */ - struct key *next; + /* Next record in the list, or NULL if this is the last record. */ + struct key *next; - /* The thread id, according to PyThread_get_thread_ident(). */ - long id; + /* The thread id, according to PyThread_get_thread_ident(). */ + long id; - /* The key and its associated value. */ - int key; - void *value; + /* The key and its associated value. */ + int key; + void *value; }; static struct key *keyhead = NULL; @@ -250,41 +250,41 @@ static struct key * find_key(int key, void *value) { - struct key *p, *prev_p; - long id = PyThread_get_thread_ident(); + struct key *p, *prev_p; + long id = PyThread_get_thread_ident(); - if (!keymutex) - return NULL; - PyThread_acquire_lock(keymutex, 1); - prev_p = NULL; - for (p = keyhead; p != NULL; p = p->next) { - if (p->id == id && p->key == key) - goto Done; - /* Sanity check. These states should never happen but if - * they do we must abort. Otherwise we'll end up spinning in - * in a tight loop with the lock held. A similar check is done - * in pystate.c tstate_delete_common(). */ - if (p == prev_p) - Py_FatalError("tls find_key: small circular list(!)"); - prev_p = p; - if (p->next == keyhead) - Py_FatalError("tls find_key: circular list(!)"); - } - if (value == NULL) { - assert(p == NULL); - goto Done; - } - p = (struct key *)malloc(sizeof(struct key)); - if (p != NULL) { - p->id = id; - p->key = key; - p->value = value; - p->next = keyhead; - keyhead = p; - } + if (!keymutex) + return NULL; + PyThread_acquire_lock(keymutex, 1); + prev_p = NULL; + for (p = keyhead; p != NULL; p = p->next) { + if (p->id == id && p->key == key) + goto Done; + /* Sanity check. These states should never happen but if + * they do we must abort. Otherwise we'll end up spinning in + * in a tight loop with the lock held. A similar check is done + * in pystate.c tstate_delete_common(). */ + if (p == prev_p) + Py_FatalError("tls find_key: small circular list(!)"); + prev_p = p; + if (p->next == keyhead) + Py_FatalError("tls find_key: circular list(!)"); + } + if (value == NULL) { + assert(p == NULL); + goto Done; + } + p = (struct key *)malloc(sizeof(struct key)); + if (p != NULL) { + p->id = id; + p->key = key; + p->value = value; + p->next = keyhead; + keyhead = p; + } Done: - PyThread_release_lock(keymutex); - return p; + PyThread_release_lock(keymutex); + return p; } /* Return a new key. This must be called before any other functions in @@ -294,32 +294,32 @@ int PyThread_create_key(void) { - /* All parts of this function are wrong if it's called by multiple - * threads simultaneously. - */ - if (keymutex == NULL) - keymutex = PyThread_allocate_lock(); - return ++nkeys; + /* All parts of this function are wrong if it's called by multiple + * threads simultaneously. + */ + if (keymutex == NULL) + keymutex = PyThread_allocate_lock(); + return ++nkeys; } /* Forget the associations for key across *all* threads. */ void PyThread_delete_key(int key) { - struct key *p, **q; + struct key *p, **q; - PyThread_acquire_lock(keymutex, 1); - q = &keyhead; - while ((p = *q) != NULL) { - if (p->key == key) { - *q = p->next; - free((void *)p); - /* NB This does *not* free p->value! */ - } - else - q = &p->next; - } - PyThread_release_lock(keymutex); + PyThread_acquire_lock(keymutex, 1); + q = &keyhead; + while ((p = *q) != NULL) { + if (p->key == key) { + *q = p->next; + free((void *)p); + /* NB This does *not* free p->value! */ + } + else + q = &p->next; + } + PyThread_release_lock(keymutex); } /* Confusing: If the current thread has an association for key, @@ -331,14 +331,14 @@ int PyThread_set_key_value(int key, void *value) { - struct key *p; + struct key *p; - assert(value != NULL); - p = find_key(key, value); - if (p == NULL) - return -1; - else - return 0; + assert(value != NULL); + p = find_key(key, value); + if (p == NULL) + return -1; + else + return 0; } /* Retrieve the value associated with key in the current thread, or NULL @@ -347,34 +347,34 @@ void * PyThread_get_key_value(int key) { - struct key *p = find_key(key, NULL); + struct key *p = find_key(key, NULL); - if (p == NULL) - return NULL; - else - return p->value; + if (p == NULL) + return NULL; + else + return p->value; } /* Forget the current thread's association for key, if any. */ void PyThread_delete_key_value(int key) { - long id = PyThread_get_thread_ident(); - struct key *p, **q; + long id = PyThread_get_thread_ident(); + struct key *p, **q; - PyThread_acquire_lock(keymutex, 1); - q = &keyhead; - while ((p = *q) != NULL) { - if (p->key == key && p->id == id) { - *q = p->next; - free((void *)p); - /* NB This does *not* free p->value! */ - break; - } - else - q = &p->next; - } - PyThread_release_lock(keymutex); + PyThread_acquire_lock(keymutex, 1); + q = &keyhead; + while ((p = *q) != NULL) { + if (p->key == key && p->id == id) { + *q = p->next; + free((void *)p); + /* NB This does *not* free p->value! */ + break; + } + else + q = &p->next; + } + PyThread_release_lock(keymutex); } /* Forget everything not associated with the current thread id. @@ -385,27 +385,27 @@ void PyThread_ReInitTLS(void) { - long id = PyThread_get_thread_ident(); - struct key *p, **q; + long id = PyThread_get_thread_ident(); + struct key *p, **q; - if (!keymutex) - return; - - /* As with interpreter_lock in PyEval_ReInitThreads() - we just create a new lock without freeing the old one */ - keymutex = PyThread_allocate_lock(); - - /* Delete all keys which do not match the current thread id */ - q = &keyhead; - while ((p = *q) != NULL) { - if (p->id != id) { - *q = p->next; - free((void *)p); - /* NB This does *not* free p->value! */ - } - else - q = &p->next; - } + if (!keymutex) + return; + + /* As with interpreter_lock in PyEval_ReInitThreads() + we just create a new lock without freeing the old one */ + keymutex = PyThread_allocate_lock(); + + /* Delete all keys which do not match the current thread id */ + q = &keyhead; + while ((p = *q) != NULL) { + if (p->id != id) { + *q = p->next; + free((void *)p); + /* NB This does *not* free p->value! */ + } + else + q = &p->next; + } } #endif /* Py_HAVE_NATIVE_TLS */ Modified: python/branches/py3k-jit/Python/thread_cthread.h ============================================================================== --- python/branches/py3k-jit/Python/thread_cthread.h (original) +++ python/branches/py3k-jit/Python/thread_cthread.h Mon May 10 23:55:43 2010 @@ -14,12 +14,12 @@ PyThread__init_thread(void) { #ifndef HURD_C_THREADS - /* Roland McGrath said this should not be used since this is - done while linking to threads */ - cthread_init(); + /* Roland McGrath said this should not be used since this is + done while linking to threads */ + cthread_init(); #else /* do nothing */ - ; + ; #endif } @@ -29,34 +29,34 @@ long PyThread_start_new_thread(void (*func)(void *), void *arg) { - int success = 0; /* init not needed when SOLARIS_THREADS and */ - /* C_THREADS implemented properly */ + int success = 0; /* init not needed when SOLARIS_THREADS and */ + /* C_THREADS implemented properly */ - dprintf(("PyThread_start_new_thread called\n")); - if (!initialized) - PyThread_init_thread(); - /* looks like solaris detaches the thread to never rejoin - * so well do it here - */ - cthread_detach(cthread_fork((cthread_fn_t) func, arg)); - return success < 0 ? -1 : 0; + dprintf(("PyThread_start_new_thread called\n")); + if (!initialized) + PyThread_init_thread(); + /* looks like solaris detaches the thread to never rejoin + * so well do it here + */ + cthread_detach(cthread_fork((cthread_fn_t) func, arg)); + return success < 0 ? -1 : 0; } long PyThread_get_thread_ident(void) { - if (!initialized) - PyThread_init_thread(); - return (long) cthread_self(); + if (!initialized) + PyThread_init_thread(); + return (long) cthread_self(); } void PyThread_exit_thread(void) { - dprintf(("PyThread_exit_thread called\n")); - if (!initialized) - exit(0); - cthread_exit(0); + dprintf(("PyThread_exit_thread called\n")); + if (!initialized) + exit(0); + cthread_exit(0); } /* @@ -65,48 +65,48 @@ PyThread_type_lock PyThread_allocate_lock(void) { - mutex_t lock; + mutex_t lock; - dprintf(("PyThread_allocate_lock called\n")); - if (!initialized) - PyThread_init_thread(); - - lock = mutex_alloc(); - if (mutex_init(lock)) { - perror("mutex_init"); - free((void *) lock); - lock = 0; - } - dprintf(("PyThread_allocate_lock() -> %p\n", lock)); - return (PyThread_type_lock) lock; + dprintf(("PyThread_allocate_lock called\n")); + if (!initialized) + PyThread_init_thread(); + + lock = mutex_alloc(); + if (mutex_init(lock)) { + perror("mutex_init"); + free((void *) lock); + lock = 0; + } + dprintf(("PyThread_allocate_lock() -> %p\n", lock)); + return (PyThread_type_lock) lock; } void PyThread_free_lock(PyThread_type_lock lock) { - dprintf(("PyThread_free_lock(%p) called\n", lock)); - mutex_free(lock); + dprintf(("PyThread_free_lock(%p) called\n", lock)); + mutex_free(lock); } int PyThread_acquire_lock(PyThread_type_lock lock, int waitflag) { - int success = FALSE; + int success = FALSE; - dprintf(("PyThread_acquire_lock(%p, %d) called\n", lock, waitflag)); - if (waitflag) { /* blocking */ - mutex_lock((mutex_t)lock); - success = TRUE; - } else { /* non blocking */ - success = mutex_try_lock((mutex_t)lock); - } - dprintf(("PyThread_acquire_lock(%p, %d) -> %d\n", lock, waitflag, success)); - return success; + dprintf(("PyThread_acquire_lock(%p, %d) called\n", lock, waitflag)); + if (waitflag) { /* blocking */ + mutex_lock((mutex_t)lock); + success = TRUE; + } else { /* non blocking */ + success = mutex_try_lock((mutex_t)lock); + } + dprintf(("PyThread_acquire_lock(%p, %d) -> %d\n", lock, waitflag, success)); + return success; } void PyThread_release_lock(PyThread_type_lock lock) { - dprintf(("PyThread_release_lock(%p) called\n", lock)); - mutex_unlock((mutex_t )lock); + dprintf(("PyThread_release_lock(%p) called\n", lock)); + mutex_unlock((mutex_t )lock); } Modified: python/branches/py3k-jit/Python/thread_foobar.h ============================================================================== --- python/branches/py3k-jit/Python/thread_foobar.h (original) +++ python/branches/py3k-jit/Python/thread_foobar.h Mon May 10 23:55:43 2010 @@ -13,28 +13,28 @@ long PyThread_start_new_thread(void (*func)(void *), void *arg) { - int success = 0; /* init not needed when SOLARIS_THREADS and */ - /* C_THREADS implemented properly */ + int success = 0; /* init not needed when SOLARIS_THREADS and */ + /* C_THREADS implemented properly */ - dprintf(("PyThread_start_new_thread called\n")); - if (!initialized) - PyThread_init_thread(); - return success < 0 ? -1 : 0; + dprintf(("PyThread_start_new_thread called\n")); + if (!initialized) + PyThread_init_thread(); + return success < 0 ? -1 : 0; } long PyThread_get_thread_ident(void) { - if (!initialized) - PyThread_init_thread(); + if (!initialized) + PyThread_init_thread(); } void PyThread_exit_thread(void) { - dprintf(("PyThread_exit_thread called\n")); - if (!initialized) - exit(0); + dprintf(("PyThread_exit_thread called\n")); + if (!initialized) + exit(0); } /* @@ -44,32 +44,32 @@ PyThread_allocate_lock(void) { - dprintf(("PyThread_allocate_lock called\n")); - if (!initialized) - PyThread_init_thread(); + dprintf(("PyThread_allocate_lock called\n")); + if (!initialized) + PyThread_init_thread(); - dprintf(("PyThread_allocate_lock() -> %p\n", lock)); - return (PyThread_type_lock) lock; + dprintf(("PyThread_allocate_lock() -> %p\n", lock)); + return (PyThread_type_lock) lock; } void PyThread_free_lock(PyThread_type_lock lock) { - dprintf(("PyThread_free_lock(%p) called\n", lock)); + dprintf(("PyThread_free_lock(%p) called\n", lock)); } int PyThread_acquire_lock(PyThread_type_lock lock, int waitflag) { - int success; + int success; - dprintf(("PyThread_acquire_lock(%p, %d) called\n", lock, waitflag)); - dprintf(("PyThread_acquire_lock(%p, %d) -> %d\n", lock, waitflag, success)); - return success; + dprintf(("PyThread_acquire_lock(%p, %d) called\n", lock, waitflag)); + dprintf(("PyThread_acquire_lock(%p, %d) -> %d\n", lock, waitflag, success)); + return success; } void PyThread_release_lock(PyThread_type_lock lock) { - dprintf(("PyThread_release_lock(%p) called\n", lock)); + dprintf(("PyThread_release_lock(%p) called\n", lock)); } Modified: python/branches/py3k-jit/Python/thread_lwp.h ============================================================================== --- python/branches/py3k-jit/Python/thread_lwp.h (original) +++ python/branches/py3k-jit/Python/thread_lwp.h Mon May 10 23:55:43 2010 @@ -3,13 +3,13 @@ #include #include -#define STACKSIZE 1000 /* stacksize for a thread */ -#define NSTACKS 2 /* # stacks to be put in cache initially */ +#define STACKSIZE 1000 /* stacksize for a thread */ +#define NSTACKS 2 /* # stacks to be put in cache initially */ struct lock { - int lock_locked; - cv_t lock_condvar; - mon_t lock_monitor; + int lock_locked; + cv_t lock_condvar; + mon_t lock_monitor; }; @@ -18,7 +18,7 @@ */ static void PyThread__init_thread(void) { - lwp_setstkcache(STACKSIZE, NSTACKS); + lwp_setstkcache(STACKSIZE, NSTACKS); } /* @@ -28,31 +28,31 @@ long PyThread_start_new_thread(void (*func)(void *), void *arg) { - thread_t tid; - int success; - dprintf(("PyThread_start_new_thread called\n")); - if (!initialized) - PyThread_init_thread(); - success = lwp_create(&tid, func, MINPRIO, 0, lwp_newstk(), 1, arg); - return success < 0 ? -1 : 0; + thread_t tid; + int success; + dprintf(("PyThread_start_new_thread called\n")); + if (!initialized) + PyThread_init_thread(); + success = lwp_create(&tid, func, MINPRIO, 0, lwp_newstk(), 1, arg); + return success < 0 ? -1 : 0; } long PyThread_get_thread_ident(void) { - thread_t tid; - if (!initialized) - PyThread_init_thread(); - if (lwp_self(&tid) < 0) - return -1; - return tid.thread_id; + thread_t tid; + if (!initialized) + PyThread_init_thread(); + if (lwp_self(&tid) < 0) + return -1; + return tid.thread_id; } void PyThread_exit_thread(void) { - dprintf(("PyThread_exit_thread called\n")); - if (!initialized) - exit(0); - lwp_destroy(SELF); + dprintf(("PyThread_exit_thread called\n")); + if (!initialized) + exit(0); + lwp_destroy(SELF); } /* @@ -60,54 +60,54 @@ */ PyThread_type_lock PyThread_allocate_lock(void) { - struct lock *lock; - extern char *malloc(size_t); + struct lock *lock; + extern char *malloc(size_t); - dprintf(("PyThread_allocate_lock called\n")); - if (!initialized) - PyThread_init_thread(); - - lock = (struct lock *) malloc(sizeof(struct lock)); - lock->lock_locked = 0; - (void) mon_create(&lock->lock_monitor); - (void) cv_create(&lock->lock_condvar, lock->lock_monitor); - dprintf(("PyThread_allocate_lock() -> %p\n", lock)); - return (PyThread_type_lock) lock; + dprintf(("PyThread_allocate_lock called\n")); + if (!initialized) + PyThread_init_thread(); + + lock = (struct lock *) malloc(sizeof(struct lock)); + lock->lock_locked = 0; + (void) mon_create(&lock->lock_monitor); + (void) cv_create(&lock->lock_condvar, lock->lock_monitor); + dprintf(("PyThread_allocate_lock() -> %p\n", lock)); + return (PyThread_type_lock) lock; } void PyThread_free_lock(PyThread_type_lock lock) { - dprintf(("PyThread_free_lock(%p) called\n", lock)); - mon_destroy(((struct lock *) lock)->lock_monitor); - free((char *) lock); + dprintf(("PyThread_free_lock(%p) called\n", lock)); + mon_destroy(((struct lock *) lock)->lock_monitor); + free((char *) lock); } int PyThread_acquire_lock(PyThread_type_lock lock, int waitflag) { - int success; + int success; - dprintf(("PyThread_acquire_lock(%p, %d) called\n", lock, waitflag)); - success = 0; + dprintf(("PyThread_acquire_lock(%p, %d) called\n", lock, waitflag)); + success = 0; - (void) mon_enter(((struct lock *) lock)->lock_monitor); - if (waitflag) - while (((struct lock *) lock)->lock_locked) - cv_wait(((struct lock *) lock)->lock_condvar); - if (!((struct lock *) lock)->lock_locked) { - success = 1; - ((struct lock *) lock)->lock_locked = 1; - } - cv_broadcast(((struct lock *) lock)->lock_condvar); - mon_exit(((struct lock *) lock)->lock_monitor); - dprintf(("PyThread_acquire_lock(%p, %d) -> %d\n", lock, waitflag, success)); - return success; + (void) mon_enter(((struct lock *) lock)->lock_monitor); + if (waitflag) + while (((struct lock *) lock)->lock_locked) + cv_wait(((struct lock *) lock)->lock_condvar); + if (!((struct lock *) lock)->lock_locked) { + success = 1; + ((struct lock *) lock)->lock_locked = 1; + } + cv_broadcast(((struct lock *) lock)->lock_condvar); + mon_exit(((struct lock *) lock)->lock_monitor); + dprintf(("PyThread_acquire_lock(%p, %d) -> %d\n", lock, waitflag, success)); + return success; } void PyThread_release_lock(PyThread_type_lock lock) { - dprintf(("PyThread_release_lock(%p) called\n", lock)); - (void) mon_enter(((struct lock *) lock)->lock_monitor); - ((struct lock *) lock)->lock_locked = 0; - cv_broadcast(((struct lock *) lock)->lock_condvar); - mon_exit(((struct lock *) lock)->lock_monitor); + dprintf(("PyThread_release_lock(%p) called\n", lock)); + (void) mon_enter(((struct lock *) lock)->lock_monitor); + ((struct lock *) lock)->lock_locked = 0; + cv_broadcast(((struct lock *) lock)->lock_condvar); + mon_exit(((struct lock *) lock)->lock_monitor); } Modified: python/branches/py3k-jit/Python/thread_nt.h ============================================================================== --- python/branches/py3k-jit/Python/thread_nt.h (original) +++ python/branches/py3k-jit/Python/thread_nt.h Mon May 10 23:55:43 2010 @@ -10,81 +10,81 @@ #endif typedef struct NRMUTEX { - LONG owned ; - DWORD thread_id ; - HANDLE hevent ; + LONG owned ; + DWORD thread_id ; + HANDLE hevent ; } NRMUTEX, *PNRMUTEX ; BOOL InitializeNonRecursiveMutex(PNRMUTEX mutex) { - mutex->owned = -1 ; /* No threads have entered NonRecursiveMutex */ - mutex->thread_id = 0 ; - mutex->hevent = CreateEvent(NULL, FALSE, FALSE, NULL) ; - return mutex->hevent != NULL ; /* TRUE if the mutex is created */ + mutex->owned = -1 ; /* No threads have entered NonRecursiveMutex */ + mutex->thread_id = 0 ; + mutex->hevent = CreateEvent(NULL, FALSE, FALSE, NULL) ; + return mutex->hevent != NULL ; /* TRUE if the mutex is created */ } VOID DeleteNonRecursiveMutex(PNRMUTEX mutex) { - /* No in-use check */ - CloseHandle(mutex->hevent) ; - mutex->hevent = NULL ; /* Just in case */ + /* No in-use check */ + CloseHandle(mutex->hevent) ; + mutex->hevent = NULL ; /* Just in case */ } DWORD EnterNonRecursiveMutex(PNRMUTEX mutex, DWORD milliseconds) { - /* Assume that the thread waits successfully */ - DWORD ret ; + /* Assume that the thread waits successfully */ + DWORD ret ; - /* InterlockedIncrement(&mutex->owned) == 0 means that no thread currently owns the mutex */ - if (milliseconds == 0) - { - if (InterlockedCompareExchange(&mutex->owned, 0, -1) != -1) - return WAIT_TIMEOUT ; - ret = WAIT_OBJECT_0 ; - } - else - ret = InterlockedIncrement(&mutex->owned) ? - /* Some thread owns the mutex, let's wait... */ - WaitForSingleObject(mutex->hevent, milliseconds) : WAIT_OBJECT_0 ; + /* InterlockedIncrement(&mutex->owned) == 0 means that no thread currently owns the mutex */ + if (milliseconds == 0) + { + if (InterlockedCompareExchange(&mutex->owned, 0, -1) != -1) + return WAIT_TIMEOUT ; + ret = WAIT_OBJECT_0 ; + } + else + ret = InterlockedIncrement(&mutex->owned) ? + /* Some thread owns the mutex, let's wait... */ + WaitForSingleObject(mutex->hevent, milliseconds) : WAIT_OBJECT_0 ; - mutex->thread_id = GetCurrentThreadId() ; /* We own it */ - return ret ; + mutex->thread_id = GetCurrentThreadId() ; /* We own it */ + return ret ; } BOOL LeaveNonRecursiveMutex(PNRMUTEX mutex) { - /* We don't own the mutex */ - mutex->thread_id = 0 ; - return - InterlockedDecrement(&mutex->owned) < 0 || - SetEvent(mutex->hevent) ; /* Other threads are waiting, wake one on them up */ + /* We don't own the mutex */ + mutex->thread_id = 0 ; + return + InterlockedDecrement(&mutex->owned) < 0 || + SetEvent(mutex->hevent) ; /* Other threads are waiting, wake one on them up */ } PNRMUTEX AllocNonRecursiveMutex(void) { - PNRMUTEX mutex = (PNRMUTEX)malloc(sizeof(NRMUTEX)) ; - if (mutex && !InitializeNonRecursiveMutex(mutex)) - { - free(mutex) ; - mutex = NULL ; - } - return mutex ; + PNRMUTEX mutex = (PNRMUTEX)malloc(sizeof(NRMUTEX)) ; + if (mutex && !InitializeNonRecursiveMutex(mutex)) + { + free(mutex) ; + mutex = NULL ; + } + return mutex ; } void FreeNonRecursiveMutex(PNRMUTEX mutex) { - if (mutex) - { - DeleteNonRecursiveMutex(mutex) ; - free(mutex) ; - } + if (mutex) + { + DeleteNonRecursiveMutex(mutex) ; + free(mutex) ; + } } long PyThread_get_thread_ident(void); @@ -102,8 +102,8 @@ */ typedef struct { - void (*func)(void*); - void *arg; + void (*func)(void*); + void *arg; } callobj; /* thunker to call adapt between the function type used by the system's @@ -115,66 +115,66 @@ #endif bootstrap(void *call) { - callobj *obj = (callobj*)call; - void (*func)(void*) = obj->func; - void *arg = obj->arg; - HeapFree(GetProcessHeap(), 0, obj); - func(arg); - return 0; + callobj *obj = (callobj*)call; + void (*func)(void*) = obj->func; + void *arg = obj->arg; + HeapFree(GetProcessHeap(), 0, obj); + func(arg); + return 0; } long PyThread_start_new_thread(void (*func)(void *), void *arg) { - HANDLE hThread; - unsigned threadID; - callobj *obj; - - dprintf(("%ld: PyThread_start_new_thread called\n", - PyThread_get_thread_ident())); - if (!initialized) - PyThread_init_thread(); - - obj = (callobj*)HeapAlloc(GetProcessHeap(), 0, sizeof(*obj)); - if (!obj) - return -1; - obj->func = func; - obj->arg = arg; + HANDLE hThread; + unsigned threadID; + callobj *obj; + + dprintf(("%ld: PyThread_start_new_thread called\n", + PyThread_get_thread_ident())); + if (!initialized) + PyThread_init_thread(); + + obj = (callobj*)HeapAlloc(GetProcessHeap(), 0, sizeof(*obj)); + if (!obj) + return -1; + obj->func = func; + obj->arg = arg; #if defined(MS_WINCE) - hThread = CreateThread(NULL, - Py_SAFE_DOWNCAST(_pythread_stacksize, Py_ssize_t, SIZE_T), - bootstrap, obj, 0, &threadID); + hThread = CreateThread(NULL, + Py_SAFE_DOWNCAST(_pythread_stacksize, Py_ssize_t, SIZE_T), + bootstrap, obj, 0, &threadID); #else - hThread = (HANDLE)_beginthreadex(0, - Py_SAFE_DOWNCAST(_pythread_stacksize, - Py_ssize_t, unsigned int), - bootstrap, obj, - 0, &threadID); + hThread = (HANDLE)_beginthreadex(0, + Py_SAFE_DOWNCAST(_pythread_stacksize, + Py_ssize_t, unsigned int), + bootstrap, obj, + 0, &threadID); #endif - if (hThread == 0) { + if (hThread == 0) { #if defined(MS_WINCE) - /* Save error in variable, to prevent PyThread_get_thread_ident - from clobbering it. */ - unsigned e = GetLastError(); - dprintf(("%ld: PyThread_start_new_thread failed, win32 error code %u\n", - PyThread_get_thread_ident(), e)); + /* Save error in variable, to prevent PyThread_get_thread_ident + from clobbering it. */ + unsigned e = GetLastError(); + dprintf(("%ld: PyThread_start_new_thread failed, win32 error code %u\n", + PyThread_get_thread_ident(), e)); #else - /* I've seen errno == EAGAIN here, which means "there are - * too many threads". - */ - int e = errno; - dprintf(("%ld: PyThread_start_new_thread failed, errno %d\n", - PyThread_get_thread_ident(), e)); + /* I've seen errno == EAGAIN here, which means "there are + * too many threads". + */ + int e = errno; + dprintf(("%ld: PyThread_start_new_thread failed, errno %d\n", + PyThread_get_thread_ident(), e)); #endif - threadID = (unsigned)-1; - HeapFree(GetProcessHeap(), 0, obj); - } - else { - dprintf(("%ld: PyThread_start_new_thread succeeded: %p\n", - PyThread_get_thread_ident(), (void*)hThread)); - CloseHandle(hThread); - } - return (long) threadID; + threadID = (unsigned)-1; + HeapFree(GetProcessHeap(), 0, obj); + } + else { + dprintf(("%ld: PyThread_start_new_thread succeeded: %p\n", + PyThread_get_thread_ident(), (void*)hThread)); + CloseHandle(hThread); + } + return (long) threadID; } /* @@ -184,22 +184,22 @@ long PyThread_get_thread_ident(void) { - if (!initialized) - PyThread_init_thread(); + if (!initialized) + PyThread_init_thread(); - return GetCurrentThreadId(); + return GetCurrentThreadId(); } void PyThread_exit_thread(void) { - dprintf(("%ld: PyThread_exit_thread called\n", PyThread_get_thread_ident())); - if (!initialized) - exit(0); + dprintf(("%ld: PyThread_exit_thread called\n", PyThread_get_thread_ident())); + if (!initialized) + exit(0); #if defined(MS_WINCE) - ExitThread(0); + ExitThread(0); #else - _endthreadex(0); + _endthreadex(0); #endif } @@ -211,25 +211,25 @@ PyThread_type_lock PyThread_allocate_lock(void) { - PNRMUTEX aLock; + PNRMUTEX aLock; - dprintf(("PyThread_allocate_lock called\n")); - if (!initialized) - PyThread_init_thread(); + dprintf(("PyThread_allocate_lock called\n")); + if (!initialized) + PyThread_init_thread(); - aLock = AllocNonRecursiveMutex() ; + aLock = AllocNonRecursiveMutex() ; - dprintf(("%ld: PyThread_allocate_lock() -> %p\n", PyThread_get_thread_ident(), aLock)); + dprintf(("%ld: PyThread_allocate_lock() -> %p\n", PyThread_get_thread_ident(), aLock)); - return (PyThread_type_lock) aLock; + return (PyThread_type_lock) aLock; } void PyThread_free_lock(PyThread_type_lock aLock) { - dprintf(("%ld: PyThread_free_lock(%p) called\n", PyThread_get_thread_ident(),aLock)); + dprintf(("%ld: PyThread_free_lock(%p) called\n", PyThread_get_thread_ident(),aLock)); - FreeNonRecursiveMutex(aLock) ; + FreeNonRecursiveMutex(aLock) ; } /* @@ -241,48 +241,48 @@ int PyThread_acquire_lock_timed(PyThread_type_lock aLock, PY_TIMEOUT_T microseconds) { - int success ; - PY_TIMEOUT_T milliseconds; + int success ; + PY_TIMEOUT_T milliseconds; - if (microseconds >= 0) { - milliseconds = microseconds / 1000; - if (microseconds % 1000 > 0) - ++milliseconds; - if ((DWORD) milliseconds != milliseconds) - Py_FatalError("Timeout too large for a DWORD, " - "please check PY_TIMEOUT_MAX"); - } - else - milliseconds = INFINITE; - - dprintf(("%ld: PyThread_acquire_lock_timed(%p, %lld) called\n", - PyThread_get_thread_ident(), aLock, microseconds)); + if (microseconds >= 0) { + milliseconds = microseconds / 1000; + if (microseconds % 1000 > 0) + ++milliseconds; + if ((DWORD) milliseconds != milliseconds) + Py_FatalError("Timeout too large for a DWORD, " + "please check PY_TIMEOUT_MAX"); + } + else + milliseconds = INFINITE; + + dprintf(("%ld: PyThread_acquire_lock_timed(%p, %lld) called\n", + PyThread_get_thread_ident(), aLock, microseconds)); - success = aLock && EnterNonRecursiveMutex((PNRMUTEX) aLock, (DWORD) milliseconds) == WAIT_OBJECT_0 ; + success = aLock && EnterNonRecursiveMutex((PNRMUTEX) aLock, (DWORD) milliseconds) == WAIT_OBJECT_0 ; - dprintf(("%ld: PyThread_acquire_lock(%p, %lld) -> %d\n", - PyThread_get_thread_ident(), aLock, microseconds, success)); + dprintf(("%ld: PyThread_acquire_lock(%p, %lld) -> %d\n", + PyThread_get_thread_ident(), aLock, microseconds, success)); - return success; + return success; } int PyThread_acquire_lock(PyThread_type_lock aLock, int waitflag) { - return PyThread_acquire_lock_timed(aLock, waitflag ? -1 : 0); + return PyThread_acquire_lock_timed(aLock, waitflag ? -1 : 0); } void PyThread_release_lock(PyThread_type_lock aLock) { - dprintf(("%ld: PyThread_release_lock(%p) called\n", PyThread_get_thread_ident(),aLock)); + dprintf(("%ld: PyThread_release_lock(%p) called\n", PyThread_get_thread_ident(),aLock)); - if (!(aLock && LeaveNonRecursiveMutex((PNRMUTEX) aLock))) - dprintf(("%ld: Could not PyThread_release_lock(%p) error: %ld\n", PyThread_get_thread_ident(), aLock, GetLastError())); + if (!(aLock && LeaveNonRecursiveMutex((PNRMUTEX) aLock))) + dprintf(("%ld: Could not PyThread_release_lock(%p) error: %ld\n", PyThread_get_thread_ident(), aLock, GetLastError())); } /* minimum/maximum thread stack sizes supported */ -#define THREAD_MIN_STACKSIZE 0x8000 /* 32kB */ -#define THREAD_MAX_STACKSIZE 0x10000000 /* 256MB */ +#define THREAD_MIN_STACKSIZE 0x8000 /* 32kB */ +#define THREAD_MAX_STACKSIZE 0x10000000 /* 256MB */ /* set the thread stack size. * Return 0 if size is valid, -1 otherwise. @@ -290,22 +290,22 @@ static int _pythread_nt_set_stacksize(size_t size) { - /* set to default */ - if (size == 0) { - _pythread_stacksize = 0; - return 0; - } - - /* valid range? */ - if (size >= THREAD_MIN_STACKSIZE && size < THREAD_MAX_STACKSIZE) { - _pythread_stacksize = size; - return 0; - } + /* set to default */ + if (size == 0) { + _pythread_stacksize = 0; + return 0; + } + + /* valid range? */ + if (size >= THREAD_MIN_STACKSIZE && size < THREAD_MAX_STACKSIZE) { + _pythread_stacksize = size; + return 0; + } - return -1; + return -1; } -#define THREAD_SET_STACKSIZE(x) _pythread_nt_set_stacksize(x) +#define THREAD_SET_STACKSIZE(x) _pythread_nt_set_stacksize(x) /* use native Windows TLS functions */ @@ -315,13 +315,13 @@ int PyThread_create_key(void) { - return (int) TlsAlloc(); + return (int) TlsAlloc(); } void PyThread_delete_key(int key) { - TlsFree(key); + TlsFree(key); } /* We must be careful to emulate the strange semantics implemented in thread.c, @@ -330,42 +330,42 @@ int PyThread_set_key_value(int key, void *value) { - BOOL ok; - void *oldvalue; + BOOL ok; + void *oldvalue; - assert(value != NULL); - oldvalue = TlsGetValue(key); - if (oldvalue != NULL) - /* ignore value if already set */ - return 0; - ok = TlsSetValue(key, value); - if (!ok) - return -1; - return 0; + assert(value != NULL); + oldvalue = TlsGetValue(key); + if (oldvalue != NULL) + /* ignore value if already set */ + return 0; + ok = TlsSetValue(key, value); + if (!ok) + return -1; + return 0; } void * PyThread_get_key_value(int key) { - /* because TLS is used in the Py_END_ALLOW_THREAD macro, - * it is necessary to preserve the windows error state, because - * it is assumed to be preserved across the call to the macro. - * Ideally, the macro should be fixed, but it is simpler to - * do it here. - */ - DWORD error = GetLastError(); - void *result = TlsGetValue(key); - SetLastError(error); - return result; + /* because TLS is used in the Py_END_ALLOW_THREAD macro, + * it is necessary to preserve the windows error state, because + * it is assumed to be preserved across the call to the macro. + * Ideally, the macro should be fixed, but it is simpler to + * do it here. + */ + DWORD error = GetLastError(); + void *result = TlsGetValue(key); + SetLastError(error); + return result; } void PyThread_delete_key_value(int key) { - /* NULL is used as "key missing", and it is also the default - * given by TlsGetValue() if nothing has been set yet. - */ - TlsSetValue(key, NULL); + /* NULL is used as "key missing", and it is also the default + * given by TlsGetValue() if nothing has been set yet. + */ + TlsSetValue(key, NULL); } /* reinitialization of TLS is not necessary after fork when using Modified: python/branches/py3k-jit/Python/thread_os2.h ============================================================================== --- python/branches/py3k-jit/Python/thread_os2.h (original) +++ python/branches/py3k-jit/Python/thread_os2.h Mon May 10 23:55:43 2010 @@ -16,10 +16,10 @@ /* default thread stack size of 64kB */ #if !defined(THREAD_STACK_SIZE) -#define THREAD_STACK_SIZE 0x10000 +#define THREAD_STACK_SIZE 0x10000 #endif -#define OS2_STACKSIZE(x) (x ? x : THREAD_STACK_SIZE) +#define OS2_STACKSIZE(x) (x ? x : THREAD_STACK_SIZE) /* * Initialization of the C package, should not be needed. @@ -35,113 +35,113 @@ long PyThread_start_new_thread(void (*func)(void *), void *arg) { - int thread_id; + int thread_id; - thread_id = _beginthread(func, - NULL, - OS2_STACKSIZE(_pythread_stacksize), - arg); - - if (thread_id == -1) { - dprintf(("_beginthread failed. return %ld\n", errno)); - } + thread_id = _beginthread(func, + NULL, + OS2_STACKSIZE(_pythread_stacksize), + arg); + + if (thread_id == -1) { + dprintf(("_beginthread failed. return %ld\n", errno)); + } - return thread_id; + return thread_id; } long PyThread_get_thread_ident(void) { #if !defined(PYCC_GCC) - PPIB pib; - PTIB tib; + PPIB pib; + PTIB tib; #endif - if (!initialized) - PyThread_init_thread(); + if (!initialized) + PyThread_init_thread(); #if defined(PYCC_GCC) - return _gettid(); + return _gettid(); #else - DosGetInfoBlocks(&tib, &pib); - return tib->tib_ptib2->tib2_ultid; + DosGetInfoBlocks(&tib, &pib); + return tib->tib_ptib2->tib2_ultid; #endif } void PyThread_exit_thread(void) { - dprintf(("%ld: PyThread_exit_thread called\n", - PyThread_get_thread_ident())); - if (!initialized) - exit(0); - _endthread(); + dprintf(("%ld: PyThread_exit_thread called\n", + PyThread_get_thread_ident())); + if (!initialized) + exit(0); + _endthread(); } /* * Lock support. This is implemented with an event semaphore and critical - * sections to make it behave more like a posix mutex than its OS/2 + * sections to make it behave more like a posix mutex than its OS/2 * counterparts. */ typedef struct os2_lock_t { - int is_set; - HEV changed; + int is_set; + HEV changed; } *type_os2_lock; -PyThread_type_lock +PyThread_type_lock PyThread_allocate_lock(void) { #if defined(PYCC_GCC) - _fmutex *sem = malloc(sizeof(_fmutex)); - if (!initialized) - PyThread_init_thread(); - dprintf(("%ld: PyThread_allocate_lock() -> %lx\n", - PyThread_get_thread_ident(), - (long)sem)); - if (_fmutex_create(sem, 0)) { - free(sem); - sem = NULL; - } - return (PyThread_type_lock)sem; + _fmutex *sem = malloc(sizeof(_fmutex)); + if (!initialized) + PyThread_init_thread(); + dprintf(("%ld: PyThread_allocate_lock() -> %lx\n", + PyThread_get_thread_ident(), + (long)sem)); + if (_fmutex_create(sem, 0)) { + free(sem); + sem = NULL; + } + return (PyThread_type_lock)sem; #else - APIRET rc; - type_os2_lock lock = (type_os2_lock)malloc(sizeof(struct os2_lock_t)); + APIRET rc; + type_os2_lock lock = (type_os2_lock)malloc(sizeof(struct os2_lock_t)); - dprintf(("PyThread_allocate_lock called\n")); - if (!initialized) - PyThread_init_thread(); + dprintf(("PyThread_allocate_lock called\n")); + if (!initialized) + PyThread_init_thread(); - lock->is_set = 0; + lock->is_set = 0; - DosCreateEventSem(NULL, &lock->changed, 0, 0); + DosCreateEventSem(NULL, &lock->changed, 0, 0); - dprintf(("%ld: PyThread_allocate_lock() -> %p\n", - PyThread_get_thread_ident(), - lock->changed)); + dprintf(("%ld: PyThread_allocate_lock() -> %p\n", + PyThread_get_thread_ident(), + lock->changed)); - return (PyThread_type_lock)lock; + return (PyThread_type_lock)lock; #endif } -void +void PyThread_free_lock(PyThread_type_lock aLock) { #if !defined(PYCC_GCC) - type_os2_lock lock = (type_os2_lock)aLock; + type_os2_lock lock = (type_os2_lock)aLock; #endif - dprintf(("%ld: PyThread_free_lock(%p) called\n", - PyThread_get_thread_ident(),aLock)); + dprintf(("%ld: PyThread_free_lock(%p) called\n", + PyThread_get_thread_ident(),aLock)); #if defined(PYCC_GCC) - if (aLock) { - _fmutex_close((_fmutex *)aLock); - free((_fmutex *)aLock); - } + if (aLock) { + _fmutex_close((_fmutex *)aLock); + free((_fmutex *)aLock); + } #else - DosCloseEventSem(lock->changed); - free(aLock); + DosCloseEventSem(lock->changed); + free(aLock); #endif } @@ -150,98 +150,98 @@ * * and 0 if the lock was not acquired. */ -int +int PyThread_acquire_lock(PyThread_type_lock aLock, int waitflag) { #if !defined(PYCC_GCC) - int done = 0; - ULONG count; - PID pid = 0; - TID tid = 0; - type_os2_lock lock = (type_os2_lock)aLock; + int done = 0; + ULONG count; + PID pid = 0; + TID tid = 0; + type_os2_lock lock = (type_os2_lock)aLock; #endif - dprintf(("%ld: PyThread_acquire_lock(%p, %d) called\n", - PyThread_get_thread_ident(), - aLock, - waitflag)); + dprintf(("%ld: PyThread_acquire_lock(%p, %d) called\n", + PyThread_get_thread_ident(), + aLock, + waitflag)); #if defined(PYCC_GCC) - /* always successful if the lock doesn't exist */ - if (aLock && - _fmutex_request((_fmutex *)aLock, waitflag ? 0 : _FMR_NOWAIT)) - return 0; + /* always successful if the lock doesn't exist */ + if (aLock && + _fmutex_request((_fmutex *)aLock, waitflag ? 0 : _FMR_NOWAIT)) + return 0; #else - while (!done) { - /* if the lock is currently set, we have to wait for - * the state to change - */ - if (lock->is_set) { - if (!waitflag) - return 0; - DosWaitEventSem(lock->changed, SEM_INDEFINITE_WAIT); - } - - /* enter a critical section and try to get the semaphore. If - * it is still locked, we will try again. - */ - if (DosEnterCritSec()) - return 0; - - if (!lock->is_set) { - lock->is_set = 1; - DosResetEventSem(lock->changed, &count); - done = 1; - } + while (!done) { + /* if the lock is currently set, we have to wait for + * the state to change + */ + if (lock->is_set) { + if (!waitflag) + return 0; + DosWaitEventSem(lock->changed, SEM_INDEFINITE_WAIT); + } + + /* enter a critical section and try to get the semaphore. If + * it is still locked, we will try again. + */ + if (DosEnterCritSec()) + return 0; + + if (!lock->is_set) { + lock->is_set = 1; + DosResetEventSem(lock->changed, &count); + done = 1; + } - DosExitCritSec(); - } + DosExitCritSec(); + } #endif - return 1; + return 1; } void PyThread_release_lock(PyThread_type_lock aLock) { #if !defined(PYCC_GCC) - type_os2_lock lock = (type_os2_lock)aLock; + type_os2_lock lock = (type_os2_lock)aLock; #endif - dprintf(("%ld: PyThread_release_lock(%p) called\n", - PyThread_get_thread_ident(), - aLock)); + dprintf(("%ld: PyThread_release_lock(%p) called\n", + PyThread_get_thread_ident(), + aLock)); #if defined(PYCC_GCC) - if (aLock) - _fmutex_release((_fmutex *)aLock); + if (aLock) + _fmutex_release((_fmutex *)aLock); #else - if (!lock->is_set) { - dprintf(("%ld: Could not PyThread_release_lock(%p) error: %l\n", - PyThread_get_thread_ident(), - aLock, - GetLastError())); - return; - } - - if (DosEnterCritSec()) { - dprintf(("%ld: Could not PyThread_release_lock(%p) error: %l\n", - PyThread_get_thread_ident(), - aLock, - GetLastError())); - return; - } + if (!lock->is_set) { + dprintf(("%ld: Could not PyThread_release_lock(%p) error: %l\n", + PyThread_get_thread_ident(), + aLock, + GetLastError())); + return; + } + + if (DosEnterCritSec()) { + dprintf(("%ld: Could not PyThread_release_lock(%p) error: %l\n", + PyThread_get_thread_ident(), + aLock, + GetLastError())); + return; + } - lock->is_set = 0; - DosPostEventSem(lock->changed); + lock->is_set = 0; + DosPostEventSem(lock->changed); - DosExitCritSec(); + DosExitCritSec(); #endif } /* minimum/maximum thread stack sizes supported */ -#define THREAD_MIN_STACKSIZE 0x8000 /* 32kB */ -#define THREAD_MAX_STACKSIZE 0x2000000 /* 32MB */ +#define THREAD_MIN_STACKSIZE 0x8000 /* 32kB */ +#define THREAD_MAX_STACKSIZE 0x2000000 /* 32MB */ /* set the thread stack size. * Return 0 if size is valid, -1 otherwise. @@ -249,19 +249,19 @@ static int _pythread_os2_set_stacksize(size_t size) { - /* set to default */ - if (size == 0) { - _pythread_stacksize = 0; - return 0; - } - - /* valid range? */ - if (size >= THREAD_MIN_STACKSIZE && size < THREAD_MAX_STACKSIZE) { - _pythread_stacksize = size; - return 0; - } + /* set to default */ + if (size == 0) { + _pythread_stacksize = 0; + return 0; + } + + /* valid range? */ + if (size >= THREAD_MIN_STACKSIZE && size < THREAD_MAX_STACKSIZE) { + _pythread_stacksize = size; + return 0; + } - return -1; + return -1; } -#define THREAD_SET_STACKSIZE(x) _pythread_os2_set_stacksize(x) +#define THREAD_SET_STACKSIZE(x) _pythread_os2_set_stacksize(x) Modified: python/branches/py3k-jit/Python/thread_pth.h ============================================================================== --- python/branches/py3k-jit/Python/thread_pth.h (original) +++ python/branches/py3k-jit/Python/thread_pth.h Mon May 10 23:55:43 2010 @@ -3,7 +3,7 @@ http://www.gnu.org/software/pth 2000-05-03 Andy Dustman - Adapted from Posix threads interface + Adapted from Posix threads interface 12 May 1997 -- david arnold */ @@ -22,10 +22,10 @@ */ typedef struct { - char locked; /* 0=unlocked, 1=locked */ - /* a pair to handle an acquire of a locked lock */ - pth_cond_t lock_released; - pth_mutex_t mut; + char locked; /* 0=unlocked, 1=locked */ + /* a pair to handle an acquire of a locked lock */ + pth_cond_t lock_released; + pth_mutex_t mut; } pth_lock; #define CHECK_STATUS(name) if (status == -1) { printf("%d ", status); perror(name); error = 1; } @@ -38,10 +38,10 @@ static void PyThread__init_thread(void) { - pth_init(); - PyThread_attr = pth_attr_new(); - pth_attr_set(PyThread_attr, PTH_ATTR_STACK_SIZE, 1<<18); - pth_attr_set(PyThread_attr, PTH_ATTR_JOINABLE, FALSE); + pth_init(); + PyThread_attr = pth_attr_new(); + pth_attr_set(PyThread_attr, PTH_ATTR_STACK_SIZE, 1<<18); + pth_attr_set(PyThread_attr, PTH_ATTR_JOINABLE, FALSE); } /* @@ -51,35 +51,35 @@ long PyThread_start_new_thread(void (*func)(void *), void *arg) { - pth_t th; - dprintf(("PyThread_start_new_thread called\n")); - if (!initialized) - PyThread_init_thread(); - - th = pth_spawn(PyThread_attr, - (void* (*)(void *))func, - (void *)arg - ); + pth_t th; + dprintf(("PyThread_start_new_thread called\n")); + if (!initialized) + PyThread_init_thread(); + + th = pth_spawn(PyThread_attr, + (void* (*)(void *))func, + (void *)arg + ); - return th; + return th; } long PyThread_get_thread_ident(void) { - volatile pth_t threadid; - if (!initialized) - PyThread_init_thread(); - /* Jump through some hoops for Alpha OSF/1 */ - threadid = pth_self(); - return (long) *(long *) &threadid; + volatile pth_t threadid; + if (!initialized) + PyThread_init_thread(); + /* Jump through some hoops for Alpha OSF/1 */ + threadid = pth_self(); + return (long) *(long *) &threadid; } void PyThread_exit_thread(void) { - dprintf(("PyThread_exit_thread called\n")); - if (!initialized) { - exit(0); - } + dprintf(("PyThread_exit_thread called\n")); + if (!initialized) { + exit(0); + } } /* @@ -87,92 +87,92 @@ */ PyThread_type_lock PyThread_allocate_lock(void) { - pth_lock *lock; - int status, error = 0; + pth_lock *lock; + int status, error = 0; - dprintf(("PyThread_allocate_lock called\n")); - if (!initialized) - PyThread_init_thread(); - - lock = (pth_lock *) malloc(sizeof(pth_lock)); - memset((void *)lock, '\0', sizeof(pth_lock)); - if (lock) { - lock->locked = 0; - status = pth_mutex_init(&lock->mut); - CHECK_STATUS("pth_mutex_init"); - status = pth_cond_init(&lock->lock_released); - CHECK_STATUS("pth_cond_init"); - if (error) { - free((void *)lock); - lock = NULL; - } - } - dprintf(("PyThread_allocate_lock() -> %p\n", lock)); - return (PyThread_type_lock) lock; + dprintf(("PyThread_allocate_lock called\n")); + if (!initialized) + PyThread_init_thread(); + + lock = (pth_lock *) malloc(sizeof(pth_lock)); + memset((void *)lock, '\0', sizeof(pth_lock)); + if (lock) { + lock->locked = 0; + status = pth_mutex_init(&lock->mut); + CHECK_STATUS("pth_mutex_init"); + status = pth_cond_init(&lock->lock_released); + CHECK_STATUS("pth_cond_init"); + if (error) { + free((void *)lock); + lock = NULL; + } + } + dprintf(("PyThread_allocate_lock() -> %p\n", lock)); + return (PyThread_type_lock) lock; } void PyThread_free_lock(PyThread_type_lock lock) { - pth_lock *thelock = (pth_lock *)lock; + pth_lock *thelock = (pth_lock *)lock; - dprintf(("PyThread_free_lock(%p) called\n", lock)); + dprintf(("PyThread_free_lock(%p) called\n", lock)); - free((void *)thelock); + free((void *)thelock); } int PyThread_acquire_lock(PyThread_type_lock lock, int waitflag) { - int success; - pth_lock *thelock = (pth_lock *)lock; - int status, error = 0; - - dprintf(("PyThread_acquire_lock(%p, %d) called\n", lock, waitflag)); - - status = pth_mutex_acquire(&thelock->mut, !waitflag, NULL); - CHECK_STATUS("pth_mutex_acquire[1]"); - success = thelock->locked == 0; - if (success) thelock->locked = 1; - status = pth_mutex_release( &thelock->mut ); - CHECK_STATUS("pth_mutex_release[1]"); - - if ( !success && waitflag ) { - /* continue trying until we get the lock */ - - /* mut must be locked by me -- part of the condition - * protocol */ - status = pth_mutex_acquire( &thelock->mut, !waitflag, NULL ); - CHECK_STATUS("pth_mutex_acquire[2]"); - while ( thelock->locked ) { - status = pth_cond_await(&thelock->lock_released, - &thelock->mut, NULL); - CHECK_STATUS("pth_cond_await"); - } - thelock->locked = 1; - status = pth_mutex_release( &thelock->mut ); - CHECK_STATUS("pth_mutex_release[2]"); - success = 1; + int success; + pth_lock *thelock = (pth_lock *)lock; + int status, error = 0; + + dprintf(("PyThread_acquire_lock(%p, %d) called\n", lock, waitflag)); + + status = pth_mutex_acquire(&thelock->mut, !waitflag, NULL); + CHECK_STATUS("pth_mutex_acquire[1]"); + success = thelock->locked == 0; + if (success) thelock->locked = 1; + status = pth_mutex_release( &thelock->mut ); + CHECK_STATUS("pth_mutex_release[1]"); + + if ( !success && waitflag ) { + /* continue trying until we get the lock */ + + /* mut must be locked by me -- part of the condition + * protocol */ + status = pth_mutex_acquire( &thelock->mut, !waitflag, NULL ); + CHECK_STATUS("pth_mutex_acquire[2]"); + while ( thelock->locked ) { + status = pth_cond_await(&thelock->lock_released, + &thelock->mut, NULL); + CHECK_STATUS("pth_cond_await"); } - if (error) success = 0; - dprintf(("PyThread_acquire_lock(%p, %d) -> %d\n", lock, waitflag, success)); - return success; + thelock->locked = 1; + status = pth_mutex_release( &thelock->mut ); + CHECK_STATUS("pth_mutex_release[2]"); + success = 1; + } + if (error) success = 0; + dprintf(("PyThread_acquire_lock(%p, %d) -> %d\n", lock, waitflag, success)); + return success; } void PyThread_release_lock(PyThread_type_lock lock) { - pth_lock *thelock = (pth_lock *)lock; - int status, error = 0; + pth_lock *thelock = (pth_lock *)lock; + int status, error = 0; - dprintf(("PyThread_release_lock(%p) called\n", lock)); + dprintf(("PyThread_release_lock(%p) called\n", lock)); - status = pth_mutex_acquire( &thelock->mut, 0, NULL ); - CHECK_STATUS("pth_mutex_acquire[3]"); + status = pth_mutex_acquire( &thelock->mut, 0, NULL ); + CHECK_STATUS("pth_mutex_acquire[3]"); - thelock->locked = 0; + thelock->locked = 0; - status = pth_mutex_release( &thelock->mut ); - CHECK_STATUS("pth_mutex_release[3]"); + status = pth_mutex_release( &thelock->mut ); + CHECK_STATUS("pth_mutex_release[3]"); - /* wake up someone (anyone, if any) waiting on the lock */ - status = pth_cond_notify( &thelock->lock_released, 0 ); - CHECK_STATUS("pth_cond_notify"); + /* wake up someone (anyone, if any) waiting on the lock */ + status = pth_cond_notify( &thelock->lock_released, 0 ); + CHECK_STATUS("pth_cond_notify"); } Modified: python/branches/py3k-jit/Python/thread_pthread.h ============================================================================== --- python/branches/py3k-jit/Python/thread_pthread.h (original) +++ python/branches/py3k-jit/Python/thread_pthread.h Mon May 10 23:55:43 2010 @@ -16,10 +16,10 @@ be conditional on _POSIX_THREAD_ATTR_STACKSIZE being defined. */ #ifdef _POSIX_THREAD_ATTR_STACKSIZE #ifndef THREAD_STACK_SIZE -#define THREAD_STACK_SIZE 0 /* use default stack size */ +#define THREAD_STACK_SIZE 0 /* use default stack size */ #endif /* for safety, ensure a viable minimum stacksize */ -#define THREAD_STACK_MIN 0x8000 /* 32kB */ +#define THREAD_STACK_MIN 0x8000 /* 32kB */ #else /* !_POSIX_THREAD_ATTR_STACKSIZE */ #ifdef THREAD_STACK_SIZE #error "THREAD_STACK_SIZE defined but _POSIX_THREAD_ATTR_STACKSIZE undefined" @@ -28,9 +28,9 @@ /* The POSIX spec says that implementations supporting the sem_* family of functions must indicate this by defining - _POSIX_SEMAPHORES. */ + _POSIX_SEMAPHORES. */ #ifdef _POSIX_SEMAPHORES -/* On FreeBSD 4.x, _POSIX_SEMAPHORES is defined empty, so +/* On FreeBSD 4.x, _POSIX_SEMAPHORES is defined empty, so we need to add 0 to make it work there as well. */ #if (_POSIX_SEMAPHORES+0) == -1 #define HAVE_BROKEN_POSIX_SEMAPHORES @@ -92,14 +92,14 @@ #define MICROSECONDS_TO_TIMESPEC(microseconds, ts) \ do { \ - struct timeval tv; \ - GETTIMEOFDAY(&tv); \ - tv.tv_usec += microseconds % 1000000; \ - tv.tv_sec += microseconds / 1000000; \ - tv.tv_sec += tv.tv_usec / 1000000; \ - tv.tv_usec %= 1000000; \ - ts.tv_sec = tv.tv_sec; \ - ts.tv_nsec = tv.tv_usec * 1000; \ + struct timeval tv; \ + GETTIMEOFDAY(&tv); \ + tv.tv_usec += microseconds % 1000000; \ + tv.tv_sec += microseconds / 1000000; \ + tv.tv_sec += tv.tv_usec / 1000000; \ + tv.tv_usec %= 1000000; \ + ts.tv_sec = tv.tv_sec; \ + ts.tv_nsec = tv.tv_usec * 1000; \ } while(0) @@ -119,10 +119,10 @@ */ typedef struct { - char locked; /* 0=unlocked, 1=locked */ - /* a pair to handle an acquire of a locked lock */ - pthread_cond_t lock_released; - pthread_mutex_t mut; + char locked; /* 0=unlocked, 1=locked */ + /* a pair to handle an acquire of a locked lock */ + pthread_cond_t lock_released; + pthread_mutex_t mut; } pthread_lock; #define CHECK_STATUS(name) if (status != 0) { perror(name); error = 1; } @@ -140,11 +140,11 @@ static void PyThread__init_thread(void) { - /* DO AN INIT BY STARTING THE THREAD */ - static int dummy = 0; - pthread_t thread1; - pthread_create(&thread1, NULL, (void *) _noop, &dummy); - pthread_join(thread1, NULL); + /* DO AN INIT BY STARTING THE THREAD */ + static int dummy = 0; + pthread_t thread1; + pthread_create(&thread1, NULL, (void *) _noop, &dummy); + pthread_join(thread1, NULL); } #else /* !_HAVE_BSDI */ @@ -153,7 +153,7 @@ PyThread__init_thread(void) { #if defined(_AIX) && defined(__GNUC__) - pthread_init(); + pthread_init(); #endif } @@ -167,59 +167,59 @@ long PyThread_start_new_thread(void (*func)(void *), void *arg) { - pthread_t th; - int status; + pthread_t th; + int status; #if defined(THREAD_STACK_SIZE) || defined(PTHREAD_SYSTEM_SCHED_SUPPORTED) - pthread_attr_t attrs; + pthread_attr_t attrs; #endif #if defined(THREAD_STACK_SIZE) - size_t tss; + size_t tss; #endif - dprintf(("PyThread_start_new_thread called\n")); - if (!initialized) - PyThread_init_thread(); + dprintf(("PyThread_start_new_thread called\n")); + if (!initialized) + PyThread_init_thread(); #if defined(THREAD_STACK_SIZE) || defined(PTHREAD_SYSTEM_SCHED_SUPPORTED) - if (pthread_attr_init(&attrs) != 0) - return -1; + if (pthread_attr_init(&attrs) != 0) + return -1; #endif #if defined(THREAD_STACK_SIZE) - tss = (_pythread_stacksize != 0) ? _pythread_stacksize - : THREAD_STACK_SIZE; - if (tss != 0) { - if (pthread_attr_setstacksize(&attrs, tss) != 0) { - pthread_attr_destroy(&attrs); - return -1; - } - } + tss = (_pythread_stacksize != 0) ? _pythread_stacksize + : THREAD_STACK_SIZE; + if (tss != 0) { + if (pthread_attr_setstacksize(&attrs, tss) != 0) { + pthread_attr_destroy(&attrs); + return -1; + } + } #endif #if defined(PTHREAD_SYSTEM_SCHED_SUPPORTED) - pthread_attr_setscope(&attrs, PTHREAD_SCOPE_SYSTEM); + pthread_attr_setscope(&attrs, PTHREAD_SCOPE_SYSTEM); #endif - status = pthread_create(&th, + status = pthread_create(&th, #if defined(THREAD_STACK_SIZE) || defined(PTHREAD_SYSTEM_SCHED_SUPPORTED) - &attrs, + &attrs, #else - (pthread_attr_t*)NULL, + (pthread_attr_t*)NULL, #endif - (void* (*)(void *))func, - (void *)arg - ); + (void* (*)(void *))func, + (void *)arg + ); #if defined(THREAD_STACK_SIZE) || defined(PTHREAD_SYSTEM_SCHED_SUPPORTED) - pthread_attr_destroy(&attrs); + pthread_attr_destroy(&attrs); #endif - if (status != 0) - return -1; + if (status != 0) + return -1; - pthread_detach(th); + pthread_detach(th); #if SIZEOF_PTHREAD_T <= SIZEOF_LONG - return (long) th; + return (long) th; #else - return (long) *(long *) &th; + return (long) *(long *) &th; #endif } @@ -230,28 +230,28 @@ - It is not clear that the 'volatile' (for AIX?) and ugly casting in the latter return statement (for Alpha OSF/1) are any longer necessary. */ -long +long PyThread_get_thread_ident(void) { - volatile pthread_t threadid; - if (!initialized) - PyThread_init_thread(); - /* Jump through some hoops for Alpha OSF/1 */ - threadid = pthread_self(); + volatile pthread_t threadid; + if (!initialized) + PyThread_init_thread(); + /* Jump through some hoops for Alpha OSF/1 */ + threadid = pthread_self(); #if SIZEOF_PTHREAD_T <= SIZEOF_LONG - return (long) threadid; + return (long) threadid; #else - return (long) *(long *) &threadid; + return (long) *(long *) &threadid; #endif } -void +void PyThread_exit_thread(void) { - dprintf(("PyThread_exit_thread called\n")); - if (!initialized) { - exit(0); - } + dprintf(("PyThread_exit_thread called\n")); + if (!initialized) { + exit(0); + } } #ifdef USE_SEMAPHORES @@ -260,47 +260,47 @@ * Lock support. */ -PyThread_type_lock +PyThread_type_lock PyThread_allocate_lock(void) { - sem_t *lock; - int status, error = 0; + sem_t *lock; + int status, error = 0; - dprintf(("PyThread_allocate_lock called\n")); - if (!initialized) - PyThread_init_thread(); + dprintf(("PyThread_allocate_lock called\n")); + if (!initialized) + PyThread_init_thread(); - lock = (sem_t *)malloc(sizeof(sem_t)); + lock = (sem_t *)malloc(sizeof(sem_t)); - if (lock) { - status = sem_init(lock,0,1); - CHECK_STATUS("sem_init"); + if (lock) { + status = sem_init(lock,0,1); + CHECK_STATUS("sem_init"); - if (error) { - free((void *)lock); - lock = NULL; - } - } + if (error) { + free((void *)lock); + lock = NULL; + } + } - dprintf(("PyThread_allocate_lock() -> %p\n", lock)); - return (PyThread_type_lock)lock; + dprintf(("PyThread_allocate_lock() -> %p\n", lock)); + return (PyThread_type_lock)lock; } -void +void PyThread_free_lock(PyThread_type_lock lock) { - sem_t *thelock = (sem_t *)lock; - int status, error = 0; + sem_t *thelock = (sem_t *)lock; + int status, error = 0; - dprintf(("PyThread_free_lock(%p) called\n", lock)); + dprintf(("PyThread_free_lock(%p) called\n", lock)); - if (!thelock) - return; + if (!thelock) + return; - status = sem_destroy(thelock); - CHECK_STATUS("sem_destroy"); + status = sem_destroy(thelock); + CHECK_STATUS("sem_destroy"); - free((void *)thelock); + free((void *)thelock); } /* @@ -312,66 +312,66 @@ static int fix_status(int status) { - return (status == -1) ? errno : status; + return (status == -1) ? errno : status; } int PyThread_acquire_lock_timed(PyThread_type_lock lock, PY_TIMEOUT_T microseconds) { - int success; - sem_t *thelock = (sem_t *)lock; - int status, error = 0; - struct timespec ts; - - dprintf(("PyThread_acquire_lock_timed(%p, %lld) called\n", - lock, microseconds)); - - if (microseconds > 0) - MICROSECONDS_TO_TIMESPEC(microseconds, ts); - do { - if (microseconds > 0) - status = fix_status(sem_timedwait(thelock, &ts)); - else if (microseconds == 0) - status = fix_status(sem_trywait(thelock)); - else - status = fix_status(sem_wait(thelock)); - } while (status == EINTR); /* Retry if interrupted by a signal */ - - if (microseconds > 0) { - if (status != ETIMEDOUT) - CHECK_STATUS("sem_timedwait"); - } - else if (microseconds == 0) { - if (status != EAGAIN) - CHECK_STATUS("sem_trywait"); - } - else { - CHECK_STATUS("sem_wait"); - } - - success = (status == 0) ? 1 : 0; - - dprintf(("PyThread_acquire_lock_timed(%p, %lld) -> %d\n", - lock, microseconds, success)); - return success; + int success; + sem_t *thelock = (sem_t *)lock; + int status, error = 0; + struct timespec ts; + + dprintf(("PyThread_acquire_lock_timed(%p, %lld) called\n", + lock, microseconds)); + + if (microseconds > 0) + MICROSECONDS_TO_TIMESPEC(microseconds, ts); + do { + if (microseconds > 0) + status = fix_status(sem_timedwait(thelock, &ts)); + else if (microseconds == 0) + status = fix_status(sem_trywait(thelock)); + else + status = fix_status(sem_wait(thelock)); + } while (status == EINTR); /* Retry if interrupted by a signal */ + + if (microseconds > 0) { + if (status != ETIMEDOUT) + CHECK_STATUS("sem_timedwait"); + } + else if (microseconds == 0) { + if (status != EAGAIN) + CHECK_STATUS("sem_trywait"); + } + else { + CHECK_STATUS("sem_wait"); + } + + success = (status == 0) ? 1 : 0; + + dprintf(("PyThread_acquire_lock_timed(%p, %lld) -> %d\n", + lock, microseconds, success)); + return success; } -int +int PyThread_acquire_lock(PyThread_type_lock lock, int waitflag) { - return PyThread_acquire_lock_timed(lock, waitflag ? -1 : 0); + return PyThread_acquire_lock_timed(lock, waitflag ? -1 : 0); } -void +void PyThread_release_lock(PyThread_type_lock lock) { - sem_t *thelock = (sem_t *)lock; - int status, error = 0; + sem_t *thelock = (sem_t *)lock; + int status, error = 0; - dprintf(("PyThread_release_lock(%p) called\n", lock)); + dprintf(("PyThread_release_lock(%p) called\n", lock)); - status = sem_post(thelock); - CHECK_STATUS("sem_post"); + status = sem_post(thelock); + CHECK_STATUS("sem_post"); } #else /* USE_SEMAPHORES */ @@ -379,137 +379,137 @@ /* * Lock support. */ -PyThread_type_lock +PyThread_type_lock PyThread_allocate_lock(void) { - pthread_lock *lock; - int status, error = 0; + pthread_lock *lock; + int status, error = 0; - dprintf(("PyThread_allocate_lock called\n")); - if (!initialized) - PyThread_init_thread(); - - lock = (pthread_lock *) malloc(sizeof(pthread_lock)); - if (lock) { - memset((void *)lock, '\0', sizeof(pthread_lock)); - lock->locked = 0; - - status = pthread_mutex_init(&lock->mut, - pthread_mutexattr_default); - CHECK_STATUS("pthread_mutex_init"); - /* Mark the pthread mutex underlying a Python mutex as - pure happens-before. We can't simply mark the - Python-level mutex as a mutex because it can be - acquired and released in different threads, which - will cause errors. */ - _Py_ANNOTATE_PURE_HAPPENS_BEFORE_MUTEX(&lock->mut); - - status = pthread_cond_init(&lock->lock_released, - pthread_condattr_default); - CHECK_STATUS("pthread_cond_init"); - - if (error) { - free((void *)lock); - lock = 0; - } - } + dprintf(("PyThread_allocate_lock called\n")); + if (!initialized) + PyThread_init_thread(); + + lock = (pthread_lock *) malloc(sizeof(pthread_lock)); + if (lock) { + memset((void *)lock, '\0', sizeof(pthread_lock)); + lock->locked = 0; + + status = pthread_mutex_init(&lock->mut, + pthread_mutexattr_default); + CHECK_STATUS("pthread_mutex_init"); + /* Mark the pthread mutex underlying a Python mutex as + pure happens-before. We can't simply mark the + Python-level mutex as a mutex because it can be + acquired and released in different threads, which + will cause errors. */ + _Py_ANNOTATE_PURE_HAPPENS_BEFORE_MUTEX(&lock->mut); + + status = pthread_cond_init(&lock->lock_released, + pthread_condattr_default); + CHECK_STATUS("pthread_cond_init"); + + if (error) { + free((void *)lock); + lock = 0; + } + } - dprintf(("PyThread_allocate_lock() -> %p\n", lock)); - return (PyThread_type_lock) lock; + dprintf(("PyThread_allocate_lock() -> %p\n", lock)); + return (PyThread_type_lock) lock; } -void +void PyThread_free_lock(PyThread_type_lock lock) { - pthread_lock *thelock = (pthread_lock *)lock; - int status, error = 0; + pthread_lock *thelock = (pthread_lock *)lock; + int status, error = 0; - dprintf(("PyThread_free_lock(%p) called\n", lock)); + dprintf(("PyThread_free_lock(%p) called\n", lock)); - status = pthread_mutex_destroy( &thelock->mut ); - CHECK_STATUS("pthread_mutex_destroy"); + status = pthread_mutex_destroy( &thelock->mut ); + CHECK_STATUS("pthread_mutex_destroy"); - status = pthread_cond_destroy( &thelock->lock_released ); - CHECK_STATUS("pthread_cond_destroy"); + status = pthread_cond_destroy( &thelock->lock_released ); + CHECK_STATUS("pthread_cond_destroy"); - free((void *)thelock); + free((void *)thelock); } int PyThread_acquire_lock_timed(PyThread_type_lock lock, PY_TIMEOUT_T microseconds) { - int success; - pthread_lock *thelock = (pthread_lock *)lock; - int status, error = 0; - - dprintf(("PyThread_acquire_lock_timed(%p, %lld) called\n", - lock, microseconds)); - - status = pthread_mutex_lock( &thelock->mut ); - CHECK_STATUS("pthread_mutex_lock[1]"); - success = thelock->locked == 0; - - if (!success && microseconds != 0) { - struct timespec ts; - if (microseconds > 0) - MICROSECONDS_TO_TIMESPEC(microseconds, ts); - /* continue trying until we get the lock */ - - /* mut must be locked by me -- part of the condition - * protocol */ - while (thelock->locked) { - if (microseconds > 0) { - status = pthread_cond_timedwait( - &thelock->lock_released, - &thelock->mut, &ts); - if (status == ETIMEDOUT) - break; - CHECK_STATUS("pthread_cond_timed_wait"); - } - else { - status = pthread_cond_wait( - &thelock->lock_released, - &thelock->mut); - CHECK_STATUS("pthread_cond_wait"); - } - } - success = (status == 0); - } - if (success) thelock->locked = 1; - status = pthread_mutex_unlock( &thelock->mut ); - CHECK_STATUS("pthread_mutex_unlock[1]"); - - if (error) success = 0; - dprintf(("PyThread_acquire_lock_timed(%p, %lld) -> %d\n", - lock, microseconds, success)); - return success; + int success; + pthread_lock *thelock = (pthread_lock *)lock; + int status, error = 0; + + dprintf(("PyThread_acquire_lock_timed(%p, %lld) called\n", + lock, microseconds)); + + status = pthread_mutex_lock( &thelock->mut ); + CHECK_STATUS("pthread_mutex_lock[1]"); + success = thelock->locked == 0; + + if (!success && microseconds != 0) { + struct timespec ts; + if (microseconds > 0) + MICROSECONDS_TO_TIMESPEC(microseconds, ts); + /* continue trying until we get the lock */ + + /* mut must be locked by me -- part of the condition + * protocol */ + while (thelock->locked) { + if (microseconds > 0) { + status = pthread_cond_timedwait( + &thelock->lock_released, + &thelock->mut, &ts); + if (status == ETIMEDOUT) + break; + CHECK_STATUS("pthread_cond_timed_wait"); + } + else { + status = pthread_cond_wait( + &thelock->lock_released, + &thelock->mut); + CHECK_STATUS("pthread_cond_wait"); + } + } + success = (status == 0); + } + if (success) thelock->locked = 1; + status = pthread_mutex_unlock( &thelock->mut ); + CHECK_STATUS("pthread_mutex_unlock[1]"); + + if (error) success = 0; + dprintf(("PyThread_acquire_lock_timed(%p, %lld) -> %d\n", + lock, microseconds, success)); + return success; } -int +int PyThread_acquire_lock(PyThread_type_lock lock, int waitflag) { - return PyThread_acquire_lock_timed(lock, waitflag ? -1 : 0); + return PyThread_acquire_lock_timed(lock, waitflag ? -1 : 0); } -void +void PyThread_release_lock(PyThread_type_lock lock) { - pthread_lock *thelock = (pthread_lock *)lock; - int status, error = 0; + pthread_lock *thelock = (pthread_lock *)lock; + int status, error = 0; - dprintf(("PyThread_release_lock(%p) called\n", lock)); + dprintf(("PyThread_release_lock(%p) called\n", lock)); - status = pthread_mutex_lock( &thelock->mut ); - CHECK_STATUS("pthread_mutex_lock[3]"); + status = pthread_mutex_lock( &thelock->mut ); + CHECK_STATUS("pthread_mutex_lock[3]"); - thelock->locked = 0; + thelock->locked = 0; - status = pthread_mutex_unlock( &thelock->mut ); - CHECK_STATUS("pthread_mutex_unlock[3]"); + status = pthread_mutex_unlock( &thelock->mut ); + CHECK_STATUS("pthread_mutex_unlock[3]"); - /* wake up someone (anyone, if any) waiting on the lock */ - status = pthread_cond_signal( &thelock->lock_released ); - CHECK_STATUS("pthread_cond_signal"); + /* wake up someone (anyone, if any) waiting on the lock */ + status = pthread_cond_signal( &thelock->lock_released ); + CHECK_STATUS("pthread_cond_signal"); } #endif /* USE_SEMAPHORES */ @@ -522,39 +522,39 @@ _pythread_pthread_set_stacksize(size_t size) { #if defined(THREAD_STACK_SIZE) - pthread_attr_t attrs; - size_t tss_min; - int rc = 0; + pthread_attr_t attrs; + size_t tss_min; + int rc = 0; #endif - /* set to default */ - if (size == 0) { - _pythread_stacksize = 0; - return 0; - } + /* set to default */ + if (size == 0) { + _pythread_stacksize = 0; + return 0; + } #if defined(THREAD_STACK_SIZE) #if defined(PTHREAD_STACK_MIN) - tss_min = PTHREAD_STACK_MIN > THREAD_STACK_MIN ? PTHREAD_STACK_MIN - : THREAD_STACK_MIN; + tss_min = PTHREAD_STACK_MIN > THREAD_STACK_MIN ? PTHREAD_STACK_MIN + : THREAD_STACK_MIN; #else - tss_min = THREAD_STACK_MIN; + tss_min = THREAD_STACK_MIN; #endif - if (size >= tss_min) { - /* validate stack size by setting thread attribute */ - if (pthread_attr_init(&attrs) == 0) { - rc = pthread_attr_setstacksize(&attrs, size); - pthread_attr_destroy(&attrs); - if (rc == 0) { - _pythread_stacksize = size; - return 0; - } - } - } - return -1; + if (size >= tss_min) { + /* validate stack size by setting thread attribute */ + if (pthread_attr_init(&attrs) == 0) { + rc = pthread_attr_setstacksize(&attrs, size); + pthread_attr_destroy(&attrs); + if (rc == 0) { + _pythread_stacksize = size; + return 0; + } + } + } + return -1; #else - return -2; + return -2; #endif } -#define THREAD_SET_STACKSIZE(x) _pythread_pthread_set_stacksize(x) +#define THREAD_SET_STACKSIZE(x) _pythread_pthread_set_stacksize(x) Modified: python/branches/py3k-jit/Python/thread_sgi.h ============================================================================== --- python/branches/py3k-jit/Python/thread_sgi.h (original) +++ python/branches/py3k-jit/Python/thread_sgi.h Mon May 10 23:55:43 2010 @@ -8,67 +8,67 @@ #include #include -#define HDR_SIZE 2680 /* sizeof(ushdr_t) */ -#define MAXPROC 100 /* max # of threads that can be started */ +#define HDR_SIZE 2680 /* sizeof(ushdr_t) */ +#define MAXPROC 100 /* max # of threads that can be started */ static usptr_t *shared_arena; -static ulock_t count_lock; /* protection for some variables */ -static ulock_t wait_lock; /* lock used to wait for other threads */ -static int waiting_for_threads; /* protected by count_lock */ -static int nthreads; /* protected by count_lock */ +static ulock_t count_lock; /* protection for some variables */ +static ulock_t wait_lock; /* lock used to wait for other threads */ +static int waiting_for_threads; /* protected by count_lock */ +static int nthreads; /* protected by count_lock */ static int exit_status; -static int exiting; /* we're already exiting (for maybe_exit) */ -static pid_t my_pid; /* PID of main thread */ +static int exiting; /* we're already exiting (for maybe_exit) */ +static pid_t my_pid; /* PID of main thread */ static struct pidlist { - pid_t parent; - pid_t child; -} pidlist[MAXPROC]; /* PIDs of other threads; protected by count_lock */ -static int maxpidindex; /* # of PIDs in pidlist */ + pid_t parent; + pid_t child; +} pidlist[MAXPROC]; /* PIDs of other threads; protected by count_lock */ +static int maxpidindex; /* # of PIDs in pidlist */ /* * Initialization. */ static void PyThread__init_thread(void) { #ifdef USE_DL - long addr, size; + long addr, size; #endif /* USE_DL */ #ifdef USE_DL - if ((size = usconfig(CONF_INITSIZE, 64*1024)) < 0) - perror("usconfig - CONF_INITSIZE (check)"); - if (usconfig(CONF_INITSIZE, size) < 0) - perror("usconfig - CONF_INITSIZE (reset)"); - addr = (long) dl_getrange(size + HDR_SIZE); - dprintf(("trying to use addr %p-%p for shared arena\n", addr, addr+size)); - errno = 0; - if ((addr = usconfig(CONF_ATTACHADDR, addr)) < 0 && errno != 0) - perror("usconfig - CONF_ATTACHADDR (set)"); -#endif /* USE_DL */ - if (usconfig(CONF_INITUSERS, 16) < 0) - perror("usconfig - CONF_INITUSERS"); - my_pid = getpid(); /* so that we know which is the main thread */ - if (usconfig(CONF_ARENATYPE, US_SHAREDONLY) < 0) - perror("usconfig - CONF_ARENATYPE"); - usconfig(CONF_LOCKTYPE, US_DEBUG); /* XXX */ + if ((size = usconfig(CONF_INITSIZE, 64*1024)) < 0) + perror("usconfig - CONF_INITSIZE (check)"); + if (usconfig(CONF_INITSIZE, size) < 0) + perror("usconfig - CONF_INITSIZE (reset)"); + addr = (long) dl_getrange(size + HDR_SIZE); + dprintf(("trying to use addr %p-%p for shared arena\n", addr, addr+size)); + errno = 0; + if ((addr = usconfig(CONF_ATTACHADDR, addr)) < 0 && errno != 0) + perror("usconfig - CONF_ATTACHADDR (set)"); +#endif /* USE_DL */ + if (usconfig(CONF_INITUSERS, 16) < 0) + perror("usconfig - CONF_INITUSERS"); + my_pid = getpid(); /* so that we know which is the main thread */ + if (usconfig(CONF_ARENATYPE, US_SHAREDONLY) < 0) + perror("usconfig - CONF_ARENATYPE"); + usconfig(CONF_LOCKTYPE, US_DEBUG); /* XXX */ #ifdef Py_DEBUG - if (thread_debug & 4) - usconfig(CONF_LOCKTYPE, US_DEBUGPLUS); - else if (thread_debug & 2) - usconfig(CONF_LOCKTYPE, US_DEBUG); + if (thread_debug & 4) + usconfig(CONF_LOCKTYPE, US_DEBUGPLUS); + else if (thread_debug & 2) + usconfig(CONF_LOCKTYPE, US_DEBUG); #endif /* Py_DEBUG */ - if ((shared_arena = usinit(tmpnam(0))) == 0) - perror("usinit"); + if ((shared_arena = usinit(tmpnam(0))) == 0) + perror("usinit"); #ifdef USE_DL - if (usconfig(CONF_ATTACHADDR, addr) < 0) /* reset address */ - perror("usconfig - CONF_ATTACHADDR (reset)"); + if (usconfig(CONF_ATTACHADDR, addr) < 0) /* reset address */ + perror("usconfig - CONF_ATTACHADDR (reset)"); #endif /* USE_DL */ - if ((count_lock = usnewlock(shared_arena)) == NULL) - perror("usnewlock (count_lock)"); - (void) usinitlock(count_lock); - if ((wait_lock = usnewlock(shared_arena)) == NULL) - perror("usnewlock (wait_lock)"); - dprintf(("arena start: %p, arena size: %ld\n", shared_arena, (long) usconfig(CONF_GETSIZE, shared_arena))); + if ((count_lock = usnewlock(shared_arena)) == NULL) + perror("usnewlock (count_lock)"); + (void) usinitlock(count_lock); + if ((wait_lock = usnewlock(shared_arena)) == NULL) + perror("usnewlock (wait_lock)"); + dprintf(("arena start: %p, arena size: %ld\n", shared_arena, (long) usconfig(CONF_GETSIZE, shared_arena))); } /* @@ -77,138 +77,138 @@ static void clean_threads(void) { - int i, j; - pid_t mypid, pid; + int i, j; + pid_t mypid, pid; - /* clean up any exited threads */ - mypid = getpid(); - i = 0; - while (i < maxpidindex) { - if (pidlist[i].parent == mypid && (pid = pidlist[i].child) > 0) { - pid = waitpid(pid, 0, WNOHANG); - if (pid > 0) { - /* a thread has exited */ - pidlist[i] = pidlist[--maxpidindex]; - /* remove references to children of dead proc */ - for (j = 0; j < maxpidindex; j++) - if (pidlist[j].parent == pid) - pidlist[j].child = -1; - continue; /* don't increment i */ - } - } - i++; - } - /* clean up the list */ - i = 0; - while (i < maxpidindex) { - if (pidlist[i].child == -1) { - pidlist[i] = pidlist[--maxpidindex]; - continue; /* don't increment i */ - } - i++; - } + /* clean up any exited threads */ + mypid = getpid(); + i = 0; + while (i < maxpidindex) { + if (pidlist[i].parent == mypid && (pid = pidlist[i].child) > 0) { + pid = waitpid(pid, 0, WNOHANG); + if (pid > 0) { + /* a thread has exited */ + pidlist[i] = pidlist[--maxpidindex]; + /* remove references to children of dead proc */ + for (j = 0; j < maxpidindex; j++) + if (pidlist[j].parent == pid) + pidlist[j].child = -1; + continue; /* don't increment i */ + } + } + i++; + } + /* clean up the list */ + i = 0; + while (i < maxpidindex) { + if (pidlist[i].child == -1) { + pidlist[i] = pidlist[--maxpidindex]; + continue; /* don't increment i */ + } + i++; + } } long PyThread_start_new_thread(void (*func)(void *), void *arg) { #ifdef USE_DL - long addr, size; - static int local_initialized = 0; + long addr, size; + static int local_initialized = 0; #endif /* USE_DL */ - int success = 0; /* init not needed when SOLARIS_THREADS and */ - /* C_THREADS implemented properly */ + int success = 0; /* init not needed when SOLARIS_THREADS and */ + /* C_THREADS implemented properly */ - dprintf(("PyThread_start_new_thread called\n")); - if (!initialized) - PyThread_init_thread(); - switch (ussetlock(count_lock)) { - case 0: return 0; - case -1: perror("ussetlock (count_lock)"); - } - if (maxpidindex >= MAXPROC) - success = -1; - else { -#ifdef USE_DL - if (!local_initialized) { - if ((size = usconfig(CONF_INITSIZE, 64*1024)) < 0) - perror("usconfig - CONF_INITSIZE (check)"); - if (usconfig(CONF_INITSIZE, size) < 0) - perror("usconfig - CONF_INITSIZE (reset)"); - addr = (long) dl_getrange(size + HDR_SIZE); - dprintf(("trying to use addr %p-%p for sproc\n", - addr, addr+size)); - errno = 0; - if ((addr = usconfig(CONF_ATTACHADDR, addr)) < 0 && - errno != 0) - perror("usconfig - CONF_ATTACHADDR (set)"); - } -#endif /* USE_DL */ - clean_threads(); - if ((success = sproc(func, PR_SALL, arg)) < 0) - perror("sproc"); -#ifdef USE_DL - if (!local_initialized) { - if (usconfig(CONF_ATTACHADDR, addr) < 0) - /* reset address */ - perror("usconfig - CONF_ATTACHADDR (reset)"); - local_initialized = 1; - } -#endif /* USE_DL */ - if (success >= 0) { - nthreads++; - pidlist[maxpidindex].parent = getpid(); - pidlist[maxpidindex++].child = success; - dprintf(("pidlist[%d] = %d\n", - maxpidindex-1, success)); - } - } - if (usunsetlock(count_lock) < 0) - perror("usunsetlock (count_lock)"); - return success; + dprintf(("PyThread_start_new_thread called\n")); + if (!initialized) + PyThread_init_thread(); + switch (ussetlock(count_lock)) { + case 0: return 0; + case -1: perror("ussetlock (count_lock)"); + } + if (maxpidindex >= MAXPROC) + success = -1; + else { +#ifdef USE_DL + if (!local_initialized) { + if ((size = usconfig(CONF_INITSIZE, 64*1024)) < 0) + perror("usconfig - CONF_INITSIZE (check)"); + if (usconfig(CONF_INITSIZE, size) < 0) + perror("usconfig - CONF_INITSIZE (reset)"); + addr = (long) dl_getrange(size + HDR_SIZE); + dprintf(("trying to use addr %p-%p for sproc\n", + addr, addr+size)); + errno = 0; + if ((addr = usconfig(CONF_ATTACHADDR, addr)) < 0 && + errno != 0) + perror("usconfig - CONF_ATTACHADDR (set)"); + } +#endif /* USE_DL */ + clean_threads(); + if ((success = sproc(func, PR_SALL, arg)) < 0) + perror("sproc"); +#ifdef USE_DL + if (!local_initialized) { + if (usconfig(CONF_ATTACHADDR, addr) < 0) + /* reset address */ + perror("usconfig - CONF_ATTACHADDR (reset)"); + local_initialized = 1; + } +#endif /* USE_DL */ + if (success >= 0) { + nthreads++; + pidlist[maxpidindex].parent = getpid(); + pidlist[maxpidindex++].child = success; + dprintf(("pidlist[%d] = %d\n", + maxpidindex-1, success)); + } + } + if (usunsetlock(count_lock) < 0) + perror("usunsetlock (count_lock)"); + return success; } long PyThread_get_thread_ident(void) { - return getpid(); + return getpid(); } void PyThread_exit_thread(void) { - dprintf(("PyThread_exit_thread called\n")); - if (!initialized) - exit(0); - if (ussetlock(count_lock) < 0) - perror("ussetlock (count_lock)"); - nthreads--; - if (getpid() == my_pid) { - /* main thread; wait for other threads to exit */ - exiting = 1; - waiting_for_threads = 1; - if (ussetlock(wait_lock) < 0) - perror("ussetlock (wait_lock)"); - for (;;) { - if (nthreads < 0) { - dprintf(("really exit (%d)\n", exit_status)); - exit(exit_status); - } - if (usunsetlock(count_lock) < 0) - perror("usunsetlock (count_lock)"); - dprintf(("waiting for other threads (%d)\n", nthreads)); - if (ussetlock(wait_lock) < 0) - perror("ussetlock (wait_lock)"); - if (ussetlock(count_lock) < 0) - perror("ussetlock (count_lock)"); - } - } - /* not the main thread */ - if (waiting_for_threads) { - dprintf(("main thread is waiting\n")); - if (usunsetlock(wait_lock) < 0) - perror("usunsetlock (wait_lock)"); - } - if (usunsetlock(count_lock) < 0) - perror("usunsetlock (count_lock)"); - _exit(0); + dprintf(("PyThread_exit_thread called\n")); + if (!initialized) + exit(0); + if (ussetlock(count_lock) < 0) + perror("ussetlock (count_lock)"); + nthreads--; + if (getpid() == my_pid) { + /* main thread; wait for other threads to exit */ + exiting = 1; + waiting_for_threads = 1; + if (ussetlock(wait_lock) < 0) + perror("ussetlock (wait_lock)"); + for (;;) { + if (nthreads < 0) { + dprintf(("really exit (%d)\n", exit_status)); + exit(exit_status); + } + if (usunsetlock(count_lock) < 0) + perror("usunsetlock (count_lock)"); + dprintf(("waiting for other threads (%d)\n", nthreads)); + if (ussetlock(wait_lock) < 0) + perror("ussetlock (wait_lock)"); + if (ussetlock(count_lock) < 0) + perror("ussetlock (count_lock)"); + } + } + /* not the main thread */ + if (waiting_for_threads) { + dprintf(("main thread is waiting\n")); + if (usunsetlock(wait_lock) < 0) + perror("usunsetlock (wait_lock)"); + } + if (usunsetlock(count_lock) < 0) + perror("usunsetlock (count_lock)"); + _exit(0); } /* @@ -216,44 +216,44 @@ */ PyThread_type_lock PyThread_allocate_lock(void) { - ulock_t lock; + ulock_t lock; - dprintf(("PyThread_allocate_lock called\n")); - if (!initialized) - PyThread_init_thread(); - - if ((lock = usnewlock(shared_arena)) == NULL) - perror("usnewlock"); - (void) usinitlock(lock); - dprintf(("PyThread_allocate_lock() -> %p\n", lock)); - return (PyThread_type_lock) lock; + dprintf(("PyThread_allocate_lock called\n")); + if (!initialized) + PyThread_init_thread(); + + if ((lock = usnewlock(shared_arena)) == NULL) + perror("usnewlock"); + (void) usinitlock(lock); + dprintf(("PyThread_allocate_lock() -> %p\n", lock)); + return (PyThread_type_lock) lock; } void PyThread_free_lock(PyThread_type_lock lock) { - dprintf(("PyThread_free_lock(%p) called\n", lock)); - usfreelock((ulock_t) lock, shared_arena); + dprintf(("PyThread_free_lock(%p) called\n", lock)); + usfreelock((ulock_t) lock, shared_arena); } int PyThread_acquire_lock(PyThread_type_lock lock, int waitflag) { - int success; + int success; - dprintf(("PyThread_acquire_lock(%p, %d) called\n", lock, waitflag)); - errno = 0; /* clear it just in case */ - if (waitflag) - success = ussetlock((ulock_t) lock); - else - success = uscsetlock((ulock_t) lock, 1); /* Try it once */ - if (success < 0) - perror(waitflag ? "ussetlock" : "uscsetlock"); - dprintf(("PyThread_acquire_lock(%p, %d) -> %d\n", lock, waitflag, success)); - return success; + dprintf(("PyThread_acquire_lock(%p, %d) called\n", lock, waitflag)); + errno = 0; /* clear it just in case */ + if (waitflag) + success = ussetlock((ulock_t) lock); + else + success = uscsetlock((ulock_t) lock, 1); /* Try it once */ + if (success < 0) + perror(waitflag ? "ussetlock" : "uscsetlock"); + dprintf(("PyThread_acquire_lock(%p, %d) -> %d\n", lock, waitflag, success)); + return success; } void PyThread_release_lock(PyThread_type_lock lock) { - dprintf(("PyThread_release_lock(%p) called\n", lock)); - if (usunsetlock((ulock_t) lock) < 0) - perror("usunsetlock"); + dprintf(("PyThread_release_lock(%p) called\n", lock)); + if (usunsetlock((ulock_t) lock) < 0) + perror("usunsetlock"); } Modified: python/branches/py3k-jit/Python/thread_solaris.h ============================================================================== --- python/branches/py3k-jit/Python/thread_solaris.h (original) +++ python/branches/py3k-jit/Python/thread_solaris.h Mon May 10 23:55:43 2010 @@ -17,114 +17,114 @@ * Thread support. */ struct func_arg { - void (*func)(void *); - void *arg; + void (*func)(void *); + void *arg; }; static void * new_func(void *funcarg) { - void (*func)(void *); - void *arg; + void (*func)(void *); + void *arg; - func = ((struct func_arg *) funcarg)->func; - arg = ((struct func_arg *) funcarg)->arg; - free(funcarg); - (*func)(arg); - return 0; + func = ((struct func_arg *) funcarg)->func; + arg = ((struct func_arg *) funcarg)->arg; + free(funcarg); + (*func)(arg); + return 0; } long PyThread_start_new_thread(void (*func)(void *), void *arg) { - thread_t tid; - struct func_arg *funcarg; + thread_t tid; + struct func_arg *funcarg; - dprintf(("PyThread_start_new_thread called\n")); - if (!initialized) - PyThread_init_thread(); - funcarg = (struct func_arg *) malloc(sizeof(struct func_arg)); - funcarg->func = func; - funcarg->arg = arg; - if (thr_create(0, 0, new_func, funcarg, - THR_DETACHED | THR_NEW_LWP, &tid)) { - perror("thr_create"); - free((void *) funcarg); - return -1; - } - return tid; + dprintf(("PyThread_start_new_thread called\n")); + if (!initialized) + PyThread_init_thread(); + funcarg = (struct func_arg *) malloc(sizeof(struct func_arg)); + funcarg->func = func; + funcarg->arg = arg; + if (thr_create(0, 0, new_func, funcarg, + THR_DETACHED | THR_NEW_LWP, &tid)) { + perror("thr_create"); + free((void *) funcarg); + return -1; + } + return tid; } long PyThread_get_thread_ident(void) { - if (!initialized) - PyThread_init_thread(); - return thr_self(); + if (!initialized) + PyThread_init_thread(); + return thr_self(); } -void +void PyThread_exit_thread(void) { - dprintf(("PyThread_exit_thread called\n")); - if (!initialized) - exit(0); - thr_exit(0); + dprintf(("PyThread_exit_thread called\n")); + if (!initialized) + exit(0); + thr_exit(0); } /* * Lock support. */ -PyThread_type_lock +PyThread_type_lock PyThread_allocate_lock(void) { - mutex_t *lock; + mutex_t *lock; - dprintf(("PyThread_allocate_lock called\n")); - if (!initialized) - PyThread_init_thread(); - - lock = (mutex_t *) malloc(sizeof(mutex_t)); - if (mutex_init(lock, USYNC_THREAD, 0)) { - perror("mutex_init"); - free((void *) lock); - lock = 0; - } - dprintf(("PyThread_allocate_lock() -> %p\n", lock)); - return (PyThread_type_lock) lock; + dprintf(("PyThread_allocate_lock called\n")); + if (!initialized) + PyThread_init_thread(); + + lock = (mutex_t *) malloc(sizeof(mutex_t)); + if (mutex_init(lock, USYNC_THREAD, 0)) { + perror("mutex_init"); + free((void *) lock); + lock = 0; + } + dprintf(("PyThread_allocate_lock() -> %p\n", lock)); + return (PyThread_type_lock) lock; } -void +void PyThread_free_lock(PyThread_type_lock lock) { - dprintf(("PyThread_free_lock(%p) called\n", lock)); - mutex_destroy((mutex_t *) lock); - free((void *) lock); + dprintf(("PyThread_free_lock(%p) called\n", lock)); + mutex_destroy((mutex_t *) lock); + free((void *) lock); } -int +int PyThread_acquire_lock(PyThread_type_lock lock, int waitflag) { - int success; + int success; - dprintf(("PyThread_acquire_lock(%p, %d) called\n", lock, waitflag)); - if (waitflag) - success = mutex_lock((mutex_t *) lock); - else - success = mutex_trylock((mutex_t *) lock); - if (success < 0) - perror(waitflag ? "mutex_lock" : "mutex_trylock"); - else - success = !success; /* solaris does it the other way round */ - dprintf(("PyThread_acquire_lock(%p, %d) -> %d\n", lock, waitflag, success)); - return success; + dprintf(("PyThread_acquire_lock(%p, %d) called\n", lock, waitflag)); + if (waitflag) + success = mutex_lock((mutex_t *) lock); + else + success = mutex_trylock((mutex_t *) lock); + if (success < 0) + perror(waitflag ? "mutex_lock" : "mutex_trylock"); + else + success = !success; /* solaris does it the other way round */ + dprintf(("PyThread_acquire_lock(%p, %d) -> %d\n", lock, waitflag, success)); + return success; } -void +void PyThread_release_lock(PyThread_type_lock lock) { - dprintf(("PyThread_release_lock(%p) called\n", lock)); - if (mutex_unlock((mutex_t *) lock)) - perror("mutex_unlock"); + dprintf(("PyThread_release_lock(%p) called\n", lock)); + if (mutex_unlock((mutex_t *) lock)) + perror("mutex_unlock"); } Modified: python/branches/py3k-jit/Python/thread_wince.h ============================================================================== --- python/branches/py3k-jit/Python/thread_wince.h (original) +++ python/branches/py3k-jit/Python/thread_wince.h Mon May 10 23:55:43 2010 @@ -24,21 +24,21 @@ */ long PyThread_start_new_thread(void (*func)(void *), void *arg) { - long rv; - int success = -1; + long rv; + int success = -1; - dprintf(("%ld: PyThread_start_new_thread called\n", PyThread_get_thread_ident())); - if (!initialized) - PyThread_init_thread(); - - rv = _beginthread(func, 0, arg); /* use default stack size */ - - if (rv != -1) { - success = 0; - dprintf(("%ld: PyThread_start_new_thread succeeded:\n", PyThread_get_thread_ident())); - } + dprintf(("%ld: PyThread_start_new_thread called\n", PyThread_get_thread_ident())); + if (!initialized) + PyThread_init_thread(); + + rv = _beginthread(func, 0, arg); /* use default stack size */ - return success; + if (rv != -1) { + success = 0; + dprintf(("%ld: PyThread_start_new_thread succeeded:\n", PyThread_get_thread_ident())); + } + + return success; } /* @@ -47,18 +47,18 @@ */ long PyThread_get_thread_ident(void) { - if (!initialized) - PyThread_init_thread(); - - return GetCurrentThreadId(); + if (!initialized) + PyThread_init_thread(); + + return GetCurrentThreadId(); } void PyThread_exit_thread(void) { - dprintf(("%ld: PyThread_exit_thread called\n", PyThread_get_thread_ident())); - if (!initialized) - exit(0); - _endthread(); + dprintf(("%ld: PyThread_exit_thread called\n", PyThread_get_thread_ident())); + if (!initialized) + exit(0); + _endthread(); } /* @@ -72,12 +72,12 @@ dprintf(("PyThread_allocate_lock called\n")); if (!initialized) - PyThread_init_thread(); + PyThread_init_thread(); aLock = CreateEvent(NULL, /* Security attributes */ - 0, /* Manual-Reset */ - 1, /* Is initially signalled */ - NULL); /* Name of event */ + 0, /* Manual-Reset */ + 1, /* Is initially signalled */ + NULL); /* Name of event */ dprintf(("%ld: PyThread_allocate_lock() -> %p\n", PyThread_get_thread_ident(), aLock)); @@ -107,22 +107,22 @@ #ifndef DEBUG waitResult = WaitForSingleObject(aLock, (waitflag ? INFINITE : 0)); #else - /* To aid in debugging, we regularly wake up. This allows us to - break into the debugger */ - while (TRUE) { - waitResult = WaitForSingleObject(aLock, waitflag ? 3000 : 0); - if (waitflag==0 || (waitflag && waitResult == WAIT_OBJECT_0)) - break; - } + /* To aid in debugging, we regularly wake up. This allows us to + break into the debugger */ + while (TRUE) { + waitResult = WaitForSingleObject(aLock, waitflag ? 3000 : 0); + if (waitflag==0 || (waitflag && waitResult == WAIT_OBJECT_0)) + break; + } #endif if (waitResult != WAIT_OBJECT_0) { - success = 0; /* We failed */ + success = 0; /* We failed */ } - dprintf(("%ld: PyThread_acquire_lock(%p, %d) -> %d\n", PyThread_get_thread_ident(),aLock, waitflag, success)); + dprintf(("%ld: PyThread_acquire_lock(%p, %d) -> %d\n", PyThread_get_thread_ident(),aLock, waitflag, success)); - return success; + return success; } void PyThread_release_lock(PyThread_type_lock aLock) @@ -130,7 +130,7 @@ dprintf(("%ld: PyThread_release_lock(%p) called\n", PyThread_get_thread_ident(),aLock)); if (!SetEvent(aLock)) - dprintf(("%ld: Could not PyThread_release_lock(%p) error: %l\n", PyThread_get_thread_ident(), aLock, GetLastError())); + dprintf(("%ld: Could not PyThread_release_lock(%p) error: %l\n", PyThread_get_thread_ident(), aLock, GetLastError())); } Modified: python/branches/py3k-jit/Python/traceback.c ============================================================================== --- python/branches/py3k-jit/Python/traceback.c (original) +++ python/branches/py3k-jit/Python/traceback.c Mon May 10 23:55:43 2010 @@ -30,303 +30,303 @@ }; static PyMemberDef tb_memberlist[] = { - {"tb_next", T_OBJECT, OFF(tb_next), READONLY}, - {"tb_frame", T_OBJECT, OFF(tb_frame), READONLY}, - {"tb_lasti", T_INT, OFF(tb_lasti), READONLY}, - {"tb_lineno", T_INT, OFF(tb_lineno), READONLY}, - {NULL} /* Sentinel */ + {"tb_next", T_OBJECT, OFF(tb_next), READONLY}, + {"tb_frame", T_OBJECT, OFF(tb_frame), READONLY}, + {"tb_lasti", T_INT, OFF(tb_lasti), READONLY}, + {"tb_lineno", T_INT, OFF(tb_lineno), READONLY}, + {NULL} /* Sentinel */ }; static void tb_dealloc(PyTracebackObject *tb) { - PyObject_GC_UnTrack(tb); - Py_TRASHCAN_SAFE_BEGIN(tb) - Py_XDECREF(tb->tb_next); - Py_XDECREF(tb->tb_frame); - PyObject_GC_Del(tb); - Py_TRASHCAN_SAFE_END(tb) + PyObject_GC_UnTrack(tb); + Py_TRASHCAN_SAFE_BEGIN(tb) + Py_XDECREF(tb->tb_next); + Py_XDECREF(tb->tb_frame); + PyObject_GC_Del(tb); + Py_TRASHCAN_SAFE_END(tb) } static int tb_traverse(PyTracebackObject *tb, visitproc visit, void *arg) { - Py_VISIT(tb->tb_next); - Py_VISIT(tb->tb_frame); - return 0; + Py_VISIT(tb->tb_next); + Py_VISIT(tb->tb_frame); + return 0; } static void tb_clear(PyTracebackObject *tb) { - Py_CLEAR(tb->tb_next); - Py_CLEAR(tb->tb_frame); + Py_CLEAR(tb->tb_next); + Py_CLEAR(tb->tb_frame); } PyTypeObject PyTraceBack_Type = { - PyVarObject_HEAD_INIT(&PyType_Type, 0) - "traceback", - sizeof(PyTracebackObject), - 0, - (destructor)tb_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)tb_traverse, /* tp_traverse */ - (inquiry)tb_clear, /* tp_clear */ - 0, /* tp_richcompare */ - 0, /* tp_weaklistoffset */ - 0, /* tp_iter */ - 0, /* tp_iternext */ - tb_methods, /* tp_methods */ - tb_memberlist, /* tp_members */ - 0, /* tp_getset */ - 0, /* tp_base */ - 0, /* tp_dict */ + PyVarObject_HEAD_INIT(&PyType_Type, 0) + "traceback", + sizeof(PyTracebackObject), + 0, + (destructor)tb_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)tb_traverse, /* tp_traverse */ + (inquiry)tb_clear, /* tp_clear */ + 0, /* tp_richcompare */ + 0, /* tp_weaklistoffset */ + 0, /* tp_iter */ + 0, /* tp_iternext */ + tb_methods, /* tp_methods */ + tb_memberlist, /* tp_members */ + 0, /* tp_getset */ + 0, /* tp_base */ + 0, /* tp_dict */ }; static PyTracebackObject * newtracebackobject(PyTracebackObject *next, PyFrameObject *frame) { - PyTracebackObject *tb; - if ((next != NULL && !PyTraceBack_Check(next)) || - frame == NULL || !PyFrame_Check(frame)) { - PyErr_BadInternalCall(); - return NULL; - } - tb = PyObject_GC_New(PyTracebackObject, &PyTraceBack_Type); - if (tb != NULL) { - Py_XINCREF(next); - tb->tb_next = next; - Py_XINCREF(frame); - tb->tb_frame = frame; - tb->tb_lasti = frame->f_lasti; - tb->tb_lineno = PyFrame_GetLineNumber(frame); - PyObject_GC_Track(tb); - } - return tb; + PyTracebackObject *tb; + if ((next != NULL && !PyTraceBack_Check(next)) || + frame == NULL || !PyFrame_Check(frame)) { + PyErr_BadInternalCall(); + return NULL; + } + tb = PyObject_GC_New(PyTracebackObject, &PyTraceBack_Type); + if (tb != NULL) { + Py_XINCREF(next); + tb->tb_next = next; + Py_XINCREF(frame); + tb->tb_frame = frame; + tb->tb_lasti = frame->f_lasti; + tb->tb_lineno = PyFrame_GetLineNumber(frame); + PyObject_GC_Track(tb); + } + return tb; } int PyTraceBack_Here(PyFrameObject *frame) { - PyThreadState *tstate = PyThreadState_GET(); - PyTracebackObject *oldtb = (PyTracebackObject *) tstate->curexc_traceback; - PyTracebackObject *tb = newtracebackobject(oldtb, frame); - if (tb == NULL) - return -1; - tstate->curexc_traceback = (PyObject *)tb; - Py_XDECREF(oldtb); - return 0; + PyThreadState *tstate = PyThreadState_GET(); + PyTracebackObject *oldtb = (PyTracebackObject *) tstate->curexc_traceback; + PyTracebackObject *tb = newtracebackobject(oldtb, frame); + if (tb == NULL) + return -1; + tstate->curexc_traceback = (PyObject *)tb; + Py_XDECREF(oldtb); + return 0; } static int _Py_FindSourceFile(const char* filename, char* namebuf, size_t namelen, int open_flags) { - int i; - int fd = -1; - PyObject *v; - Py_ssize_t _npath; - int npath; - size_t taillen; - PyObject *syspath; - const char* path; - const char* tail; - Py_ssize_t len; - - /* Search tail of filename in sys.path before giving up */ - tail = strrchr(filename, SEP); - if (tail == NULL) - tail = filename; - else - tail++; - taillen = strlen(tail); - - syspath = PySys_GetObject("path"); - if (syspath == NULL || !PyList_Check(syspath)) - return -1; - _npath = PyList_Size(syspath); - npath = Py_SAFE_DOWNCAST(_npath, Py_ssize_t, int); - - for (i = 0; i < npath; i++) { - v = PyList_GetItem(syspath, i); - if (v == NULL) { - PyErr_Clear(); - break; - } - if (!PyUnicode_Check(v)) - continue; - path = _PyUnicode_AsStringAndSize(v, &len); - if (len + 1 + (Py_ssize_t)taillen >= (Py_ssize_t)namelen - 1) - continue; /* Too long */ - strcpy(namebuf, path); - if (strlen(namebuf) != len) - continue; /* v contains '\0' */ - if (len > 0 && namebuf[len-1] != SEP) - namebuf[len++] = SEP; - strcpy(namebuf+len, tail); - Py_BEGIN_ALLOW_THREADS - fd = open(namebuf, open_flags); - Py_END_ALLOW_THREADS - if (0 <= fd) { - return fd; - } - } - return -1; + int i; + int fd = -1; + PyObject *v; + Py_ssize_t _npath; + int npath; + size_t taillen; + PyObject *syspath; + const char* path; + const char* tail; + Py_ssize_t len; + + /* Search tail of filename in sys.path before giving up */ + tail = strrchr(filename, SEP); + if (tail == NULL) + tail = filename; + else + tail++; + taillen = strlen(tail); + + syspath = PySys_GetObject("path"); + if (syspath == NULL || !PyList_Check(syspath)) + return -1; + _npath = PyList_Size(syspath); + npath = Py_SAFE_DOWNCAST(_npath, Py_ssize_t, int); + + for (i = 0; i < npath; i++) { + v = PyList_GetItem(syspath, i); + if (v == NULL) { + PyErr_Clear(); + break; + } + if (!PyUnicode_Check(v)) + continue; + path = _PyUnicode_AsStringAndSize(v, &len); + if (len + 1 + (Py_ssize_t)taillen >= (Py_ssize_t)namelen - 1) + continue; /* Too long */ + strcpy(namebuf, path); + if (strlen(namebuf) != len) + continue; /* v contains '\0' */ + if (len > 0 && namebuf[len-1] != SEP) + namebuf[len++] = SEP; + strcpy(namebuf+len, tail); + Py_BEGIN_ALLOW_THREADS + fd = open(namebuf, open_flags); + Py_END_ALLOW_THREADS + if (0 <= fd) { + return fd; + } + } + return -1; } int _Py_DisplaySourceLine(PyObject *f, const char *filename, int lineno, int indent) { - int err = 0; - int fd; - int i; - char *found_encoding; - char *encoding; - PyObject *fob = NULL; - PyObject *lineobj = NULL; + int err = 0; + int fd; + int i; + char *found_encoding; + char *encoding; + PyObject *fob = NULL; + PyObject *lineobj = NULL; #ifdef O_BINARY - const int open_flags = O_RDONLY | O_BINARY; /* necessary for Windows */ + const int open_flags = O_RDONLY | O_BINARY; /* necessary for Windows */ #else - const int open_flags = O_RDONLY; + const int open_flags = O_RDONLY; #endif - char buf[MAXPATHLEN+1]; - Py_UNICODE *u, *p; - Py_ssize_t len; - - /* open the file */ - if (filename == NULL) - return 0; - Py_BEGIN_ALLOW_THREADS - fd = open(filename, open_flags); - Py_END_ALLOW_THREADS - if (fd < 0) { - fd = _Py_FindSourceFile(filename, buf, sizeof(buf), open_flags); - if (fd < 0) - return 0; - filename = buf; - } - - /* use the right encoding to decode the file as unicode */ - found_encoding = PyTokenizer_FindEncoding(fd); - encoding = (found_encoding != NULL) ? found_encoding : - (char*)PyUnicode_GetDefaultEncoding(); - lseek(fd, 0, 0); /* Reset position */ - fob = PyFile_FromFd(fd, (char*)filename, "r", -1, (char*)encoding, - NULL, NULL, 1); - PyMem_FREE(found_encoding); - if (fob == NULL) { - PyErr_Clear(); - close(fd); - return 0; - } - - /* get the line number lineno */ - for (i = 0; i < lineno; i++) { - Py_XDECREF(lineobj); - lineobj = PyFile_GetLine(fob, -1); - if (!lineobj) { - err = -1; - break; - } - } - Py_DECREF(fob); - if (!lineobj || !PyUnicode_Check(lineobj)) { - Py_XDECREF(lineobj); - return err; - } - - /* remove the indentation of the line */ - u = PyUnicode_AS_UNICODE(lineobj); - len = PyUnicode_GET_SIZE(lineobj); - for (p=u; *p == ' ' || *p == '\t' || *p == '\014'; p++) - len--; - if (u != p) { - PyObject *truncated; - truncated = PyUnicode_FromUnicode(p, len); - if (truncated) { - Py_DECREF(lineobj); - lineobj = truncated; - } else { - PyErr_Clear(); - } - } - - /* Write some spaces before the line */ - strcpy(buf, " "); - assert (strlen(buf) == 10); - while (indent > 0) { - if(indent < 10) - buf[indent] = '\0'; - err = PyFile_WriteString(buf, f); - if (err != 0) - break; - indent -= 10; - } - - /* finally display the line */ - if (err == 0) - err = PyFile_WriteObject(lineobj, f, Py_PRINT_RAW); - Py_DECREF(lineobj); - if (err == 0) - err = PyFile_WriteString("\n", f); - return err; + char buf[MAXPATHLEN+1]; + Py_UNICODE *u, *p; + Py_ssize_t len; + + /* open the file */ + if (filename == NULL) + return 0; + Py_BEGIN_ALLOW_THREADS + fd = open(filename, open_flags); + Py_END_ALLOW_THREADS + if (fd < 0) { + fd = _Py_FindSourceFile(filename, buf, sizeof(buf), open_flags); + if (fd < 0) + return 0; + filename = buf; + } + + /* use the right encoding to decode the file as unicode */ + found_encoding = PyTokenizer_FindEncoding(fd); + encoding = (found_encoding != NULL) ? found_encoding : + (char*)PyUnicode_GetDefaultEncoding(); + lseek(fd, 0, 0); /* Reset position */ + fob = PyFile_FromFd(fd, (char*)filename, "r", -1, (char*)encoding, + NULL, NULL, 1); + PyMem_FREE(found_encoding); + if (fob == NULL) { + PyErr_Clear(); + close(fd); + return 0; + } + + /* get the line number lineno */ + for (i = 0; i < lineno; i++) { + Py_XDECREF(lineobj); + lineobj = PyFile_GetLine(fob, -1); + if (!lineobj) { + err = -1; + break; + } + } + Py_DECREF(fob); + if (!lineobj || !PyUnicode_Check(lineobj)) { + Py_XDECREF(lineobj); + return err; + } + + /* remove the indentation of the line */ + u = PyUnicode_AS_UNICODE(lineobj); + len = PyUnicode_GET_SIZE(lineobj); + for (p=u; *p == ' ' || *p == '\t' || *p == '\014'; p++) + len--; + if (u != p) { + PyObject *truncated; + truncated = PyUnicode_FromUnicode(p, len); + if (truncated) { + Py_DECREF(lineobj); + lineobj = truncated; + } else { + PyErr_Clear(); + } + } + + /* Write some spaces before the line */ + strcpy(buf, " "); + assert (strlen(buf) == 10); + while (indent > 0) { + if(indent < 10) + buf[indent] = '\0'; + err = PyFile_WriteString(buf, f); + if (err != 0) + break; + indent -= 10; + } + + /* finally display the line */ + if (err == 0) + err = PyFile_WriteObject(lineobj, f, Py_PRINT_RAW); + Py_DECREF(lineobj); + if (err == 0) + err = PyFile_WriteString("\n", f); + return err; } static int tb_displayline(PyObject *f, const char *filename, int lineno, const char *name) { - int err = 0; - char linebuf[2000]; + int err = 0; + char linebuf[2000]; - if (filename == NULL || name == NULL) - return -1; - /* This is needed by Emacs' compile command */ + if (filename == NULL || name == NULL) + return -1; + /* This is needed by Emacs' compile command */ #define FMT " File \"%.500s\", line %d, in %.500s\n" - PyOS_snprintf(linebuf, sizeof(linebuf), FMT, filename, lineno, name); - err = PyFile_WriteString(linebuf, f); - if (err != 0) - return err; - return _Py_DisplaySourceLine(f, filename, lineno, 4); + PyOS_snprintf(linebuf, sizeof(linebuf), FMT, filename, lineno, name); + err = PyFile_WriteString(linebuf, f); + if (err != 0) + return err; + return _Py_DisplaySourceLine(f, filename, lineno, 4); } static int tb_printinternal(PyTracebackObject *tb, PyObject *f, long limit) { - int err = 0; - long depth = 0; - PyTracebackObject *tb1 = tb; - while (tb1 != NULL) { - depth++; - tb1 = tb1->tb_next; - } - while (tb != NULL && err == 0) { - if (depth <= limit) { - err = tb_displayline(f, - _PyUnicode_AsString( - tb->tb_frame->f_code->co_filename), - tb->tb_lineno, - _PyUnicode_AsString(tb->tb_frame->f_code->co_name)); - } - depth--; - tb = tb->tb_next; - if (err == 0) - err = PyErr_CheckSignals(); - } - return err; + int err = 0; + long depth = 0; + PyTracebackObject *tb1 = tb; + while (tb1 != NULL) { + depth++; + tb1 = tb1->tb_next; + } + while (tb != NULL && err == 0) { + if (depth <= limit) { + err = tb_displayline(f, + _PyUnicode_AsString( + tb->tb_frame->f_code->co_filename), + tb->tb_lineno, + _PyUnicode_AsString(tb->tb_frame->f_code->co_name)); + } + depth--; + tb = tb->tb_next; + if (err == 0) + err = PyErr_CheckSignals(); + } + return err; } #define PyTraceBack_LIMIT 1000 @@ -334,40 +334,40 @@ int PyTraceBack_Print(PyObject *v, PyObject *f) { - int err; - PyObject *limitv; - long limit = PyTraceBack_LIMIT; - - if (v == NULL) - return 0; - if (!PyTraceBack_Check(v)) { - PyErr_BadInternalCall(); - return -1; - } - limitv = PySys_GetObject("tracebacklimit"); - if (limitv) { - PyObject *exc_type, *exc_value, *exc_tb; - - PyErr_Fetch(&exc_type, &exc_value, &exc_tb); - limit = PyLong_AsLong(limitv); - if (limit == -1 && PyErr_Occurred()) { - if (PyErr_ExceptionMatches(PyExc_OverflowError)) { - limit = PyTraceBack_LIMIT; - } - else { - Py_XDECREF(exc_type); - Py_XDECREF(exc_value); - Py_XDECREF(exc_tb); - return 0; - } - } - else if (limit <= 0) { - limit = PyTraceBack_LIMIT; - } - PyErr_Restore(exc_type, exc_value, exc_tb); - } - err = PyFile_WriteString("Traceback (most recent call last):\n", f); - if (!err) - err = tb_printinternal((PyTracebackObject *)v, f, limit); - return err; + int err; + PyObject *limitv; + long limit = PyTraceBack_LIMIT; + + if (v == NULL) + return 0; + if (!PyTraceBack_Check(v)) { + PyErr_BadInternalCall(); + return -1; + } + limitv = PySys_GetObject("tracebacklimit"); + if (limitv) { + PyObject *exc_type, *exc_value, *exc_tb; + + PyErr_Fetch(&exc_type, &exc_value, &exc_tb); + limit = PyLong_AsLong(limitv); + if (limit == -1 && PyErr_Occurred()) { + if (PyErr_ExceptionMatches(PyExc_OverflowError)) { + limit = PyTraceBack_LIMIT; + } + else { + Py_XDECREF(exc_type); + Py_XDECREF(exc_value); + Py_XDECREF(exc_tb); + return 0; + } + } + else if (limit <= 0) { + limit = PyTraceBack_LIMIT; + } + PyErr_Restore(exc_type, exc_value, exc_tb); + } + err = PyFile_WriteString("Traceback (most recent call last):\n", f); + if (!err) + err = tb_printinternal((PyTracebackObject *)v, f, limit); + return err; } Modified: python/branches/py3k-jit/Tools/msi/msisupport.c ============================================================================== --- python/branches/py3k-jit/Tools/msi/msisupport.c (original) +++ python/branches/py3k-jit/Tools/msi/msisupport.c Mon May 10 23:55:43 2010 @@ -7,13 +7,13 @@ */ static UINT debug(MSIHANDLE hInstall, LPCSTR msg) { - MSIHANDLE hRec = MsiCreateRecord(1); - if (!hRec || MsiRecordSetStringA(hRec, 1, msg) != ERROR_SUCCESS) { - return ERROR_INSTALL_FAILURE; - } - MsiProcessMessage(hInstall, INSTALLMESSAGE_INFO, hRec); - MsiCloseHandle(hRec); - return ERROR_SUCCESS; + MSIHANDLE hRec = MsiCreateRecord(1); + if (!hRec || MsiRecordSetStringA(hRec, 1, msg) != ERROR_SUCCESS) { + return ERROR_INSTALL_FAILURE; + } + MsiProcessMessage(hInstall, INSTALLMESSAGE_INFO, hRec); + MsiCloseHandle(hRec); + return ERROR_SUCCESS; } /* Check whether the TARGETDIR exists and is a directory. @@ -22,27 +22,27 @@ UINT __declspec(dllexport) __stdcall CheckDir(MSIHANDLE hInstall) { #define PSIZE 1024 - WCHAR wpath[PSIZE]; - char path[PSIZE]; - UINT result; - DWORD size = PSIZE; - DWORD attributes; - - - result = MsiGetPropertyW(hInstall, L"TARGETDIR", wpath, &size); - if (result != ERROR_SUCCESS) - return result; - wpath[size] = L'\0'; - path[size] = L'\0'; - - attributes = GetFileAttributesW(wpath); - if (attributes == INVALID_FILE_ATTRIBUTES || - !(attributes & FILE_ATTRIBUTE_DIRECTORY)) - { - return MsiSetPropertyA(hInstall, "TargetExists", "0"); - } else { - return MsiSetPropertyA(hInstall, "TargetExists", "1"); - } + WCHAR wpath[PSIZE]; + char path[PSIZE]; + UINT result; + DWORD size = PSIZE; + DWORD attributes; + + + result = MsiGetPropertyW(hInstall, L"TARGETDIR", wpath, &size); + if (result != ERROR_SUCCESS) + return result; + wpath[size] = L'\0'; + path[size] = L'\0'; + + attributes = GetFileAttributesW(wpath); + if (attributes == INVALID_FILE_ATTRIBUTES || + !(attributes & FILE_ATTRIBUTE_DIRECTORY)) + { + return MsiSetPropertyA(hInstall, "TargetExists", "0"); + } else { + return MsiSetPropertyA(hInstall, "TargetExists", "1"); + } } /* Update the state of the REGISTRY.tcl component according to the @@ -51,41 +51,41 @@ */ UINT __declspec(dllexport) __stdcall UpdateEditIDLE(MSIHANDLE hInstall) { - INSTALLSTATE ext_old, ext_new, tcl_old, tcl_new, reg_new; - UINT result; + INSTALLSTATE ext_old, ext_new, tcl_old, tcl_new, reg_new; + UINT result; - result = MsiGetFeatureStateA(hInstall, "Extensions", &ext_old, &ext_new); - if (result != ERROR_SUCCESS) - return result; - result = MsiGetFeatureStateA(hInstall, "TclTk", &tcl_old, &tcl_new); - if (result != ERROR_SUCCESS) - return result; - - /* If the current state is Absent, and the user did not select - the feature in the UI, Installer apparently sets the "selected" - state to unknown. Update it to the current value, then. */ - if (ext_new == INSTALLSTATE_UNKNOWN) - ext_new = ext_old; - if (tcl_new == INSTALLSTATE_UNKNOWN) - tcl_new = tcl_old; - - // XXX consider current state of REGISTRY.tcl? - if (((tcl_new == INSTALLSTATE_LOCAL) || - (tcl_new == INSTALLSTATE_SOURCE) || - (tcl_new == INSTALLSTATE_DEFAULT)) && - ((ext_new == INSTALLSTATE_LOCAL) || - (ext_new == INSTALLSTATE_SOURCE) || - (ext_new == INSTALLSTATE_DEFAULT))) { - reg_new = INSTALLSTATE_SOURCE; - } else { - reg_new = INSTALLSTATE_ABSENT; - } - result = MsiSetComponentStateA(hInstall, "REGISTRY.tcl", reg_new); - return result; + result = MsiGetFeatureStateA(hInstall, "Extensions", &ext_old, &ext_new); + if (result != ERROR_SUCCESS) + return result; + result = MsiGetFeatureStateA(hInstall, "TclTk", &tcl_old, &tcl_new); + if (result != ERROR_SUCCESS) + return result; + + /* If the current state is Absent, and the user did not select + the feature in the UI, Installer apparently sets the "selected" + state to unknown. Update it to the current value, then. */ + if (ext_new == INSTALLSTATE_UNKNOWN) + ext_new = ext_old; + if (tcl_new == INSTALLSTATE_UNKNOWN) + tcl_new = tcl_old; + + // XXX consider current state of REGISTRY.tcl? + if (((tcl_new == INSTALLSTATE_LOCAL) || + (tcl_new == INSTALLSTATE_SOURCE) || + (tcl_new == INSTALLSTATE_DEFAULT)) && + ((ext_new == INSTALLSTATE_LOCAL) || + (ext_new == INSTALLSTATE_SOURCE) || + (ext_new == INSTALLSTATE_DEFAULT))) { + reg_new = INSTALLSTATE_SOURCE; + } else { + reg_new = INSTALLSTATE_ABSENT; + } + result = MsiSetComponentStateA(hInstall, "REGISTRY.tcl", reg_new); + return result; } -BOOL APIENTRY DllMain(HANDLE hModule, - DWORD ul_reason_for_call, +BOOL APIENTRY DllMain(HANDLE hModule, + DWORD ul_reason_for_call, LPVOID lpReserved) { return TRUE; From python-checkins at python.org Tue May 11 00:50:01 2010 From: python-checkins at python.org (collin.winter) Date: Tue, 11 May 2010 00:50:01 +0200 (CEST) Subject: [Python-checkins] r81069 - in python/branches/py3k-jit: Doc/library/exceptions.rst Doc/library/ftplib.rst Doc/reference/lexical_analysis.rst Doc/whatsnew/3.2.rst Lib/ftplib.py Lib/test/test_asyncore.py Lib/test/test_ftplib.py Lib/unittest/__main__.py Lib/unittest/main.py Misc/ACKS Misc/NEWS Modules/audioop.c Objects/longobject.c Message-ID: <20100510225001.49A02EE981@mail.python.org> Author: collin.winter Date: Tue May 11 00:50:00 2010 New Revision: 81069 Log: Merged revisions 81041,81044,81047,81056-81057,81061,81063-81064 via svnmerge from svn+ssh://pythondev at svn.python.org/python/branches/py3k ................ r81041 | giampaolo.rodola | 2010-05-10 07:53:29 -0700 (Mon, 10 May 2010) | 1 line Fix issue #4972: adds ftplib.FTP context manager protocol ................ r81044 | giampaolo.rodola | 2010-05-10 08:40:49 -0700 (Mon, 10 May 2010) | 9 lines Merged revisions 81043 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r81043 | giampaolo.rodola | 2010-05-10 17:33:22 +0200 (lun, 10 mag 2010) | 1 line Issue #8490: adds a more solid test suite for asyncore ........ ................ r81047 | mark.dickinson | 2010-05-10 09:27:45 -0700 (Mon, 10 May 2010) | 10 lines Merged revisions 81045 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r81045 | mark.dickinson | 2010-05-10 17:07:42 +0100 (Mon, 10 May 2010) | 3 lines Issue #8674: Fix incorrect and UB-inducing overflow checks in audioop module. Thanks Tomas Hoger for the patch. ........ ................ r81056 | michael.foord | 2010-05-10 13:23:58 -0700 (Mon, 10 May 2010) | 9 lines Merged revisions 81055 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r81055 | michael.foord | 2010-05-10 21:21:16 +0100 (Mon, 10 May 2010) | 1 line Improving help message for python -m unittest. Issue 8303. ........ ................ r81057 | benjamin.peterson | 2010-05-10 13:49:20 -0700 (Mon, 10 May 2010) | 1 line remove reference to second argument to raise #8676 ................ r81061 | georg.brandl | 2010-05-10 14:17:00 -0700 (Mon, 10 May 2010) | 1 line Fix nits in the lexical analysis section: \u requires four digits, backtick is not allowed in source in 3.x. ................ r81063 | mark.dickinson | 2010-05-10 14:27:53 -0700 (Mon, 10 May 2010) | 9 lines Merged revisions 81036 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r81036 | mark.dickinson | 2010-05-09 21:30:29 +0100 (Sun, 09 May 2010) | 1 line Post-detabification cleanup: whitespace fixes and long line rewraps only. ........ ................ r81064 | mark.dickinson | 2010-05-10 14:37:34 -0700 (Mon, 10 May 2010) | 9 lines Merged revisions 81037 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r81037 | mark.dickinson | 2010-05-09 21:42:09 +0100 (Sun, 09 May 2010) | 1 line Wrap multiline macros in a 'do {} while(0)', for safety. ........ ................ Modified: python/branches/py3k-jit/ (props changed) python/branches/py3k-jit/Doc/library/exceptions.rst python/branches/py3k-jit/Doc/library/ftplib.rst python/branches/py3k-jit/Doc/reference/lexical_analysis.rst python/branches/py3k-jit/Doc/whatsnew/3.2.rst python/branches/py3k-jit/Lib/ftplib.py python/branches/py3k-jit/Lib/test/test_asyncore.py python/branches/py3k-jit/Lib/test/test_ftplib.py python/branches/py3k-jit/Lib/unittest/__main__.py python/branches/py3k-jit/Lib/unittest/main.py python/branches/py3k-jit/Misc/ACKS python/branches/py3k-jit/Misc/NEWS python/branches/py3k-jit/Modules/audioop.c python/branches/py3k-jit/Objects/longobject.c Modified: python/branches/py3k-jit/Doc/library/exceptions.rst ============================================================================== --- python/branches/py3k-jit/Doc/library/exceptions.rst (original) +++ python/branches/py3k-jit/Doc/library/exceptions.rst Tue May 11 00:50:00 2010 @@ -20,10 +20,10 @@ built-in functions. Except where mentioned, they have an "associated value" indicating the detailed cause of the error. This may be a string or a tuple containing several items of information (e.g., an error code and a string -explaining the code). The associated value is the second argument to the -:keyword:`raise` statement. If the exception class is derived from the standard -root class :exc:`BaseException`, the associated value is present as the -exception instance's :attr:`args` attribute. +explaining the code). The associated value is usually passed to the exception +class's constructor. If the exception class is derived from the standard root +class :exc:`BaseException`, the associated value is present as the exception +instance's :attr:`args` attribute. User code can raise built-in exceptions. This can be used to test an exception handler or to report an error condition "just like" the situation in which the Modified: python/branches/py3k-jit/Doc/library/ftplib.rst ============================================================================== --- python/branches/py3k-jit/Doc/library/ftplib.rst (original) +++ python/branches/py3k-jit/Doc/library/ftplib.rst Tue May 11 00:50:00 2010 @@ -46,6 +46,25 @@ connection attempt (if is not specified, the global default timeout setting will be used). + :class:`FTP` class supports the :keyword:`with` statement. Here is a sample + on how using it: + + >>> from ftplib import FTP + >>> with FTP("ftp1.at.proftpd.org") as ftp: + ... ftp.login() + ... ftp.dir() + ... + '230 Anonymous login ok, restrictions apply.' + dr-xr-xr-x 9 ftp ftp 154 May 6 10:43 . + dr-xr-xr-x 9 ftp ftp 154 May 6 10:43 .. + dr-xr-xr-x 5 ftp ftp 4096 May 6 10:43 CentOS + dr-xr-xr-x 3 ftp ftp 18 Jul 10 2008 Fedora + >>> + + .. versionchanged:: 3.2 + Support for the :keyword:`with` statement was added. + + .. class:: FTP_TLS(host='', user='', passwd='', acct='', [keyfile[, certfile[, timeout]]]) A :class:`FTP` subclass which adds TLS support to FTP as described in Modified: python/branches/py3k-jit/Doc/reference/lexical_analysis.rst ============================================================================== --- python/branches/py3k-jit/Doc/reference/lexical_analysis.rst (original) +++ python/branches/py3k-jit/Doc/reference/lexical_analysis.rst Tue May 11 00:50:00 2010 @@ -512,13 +512,13 @@ (4) Individual code units which form parts of a surrogate pair can be encoded using - this escape sequence. Unlike in Standard C, exactly two hex digits are required. + this escape sequence. Exactly four hex digits are required. (5) Any Unicode character can be encoded this way, but characters outside the Basic Multilingual Plane (BMP) will be encoded using a surrogate pair if Python is - compiled to use 16-bit code units (the default). Individual code units which - form parts of a surrogate pair can be encoded using this escape sequence. + compiled to use 16-bit code units (the default). Exactly eight hex digits + are required. .. index:: unrecognized escape sequence @@ -700,4 +700,4 @@ The following printing ASCII characters are not used in Python. Their occurrence outside string literals and comments is an unconditional error:: - $ ? + $ ? ` Modified: python/branches/py3k-jit/Doc/whatsnew/3.2.rst ============================================================================== --- python/branches/py3k-jit/Doc/whatsnew/3.2.rst (original) +++ python/branches/py3k-jit/Doc/whatsnew/3.2.rst Tue May 11 00:50:00 2010 @@ -66,6 +66,9 @@ New, Improved, and Deprecated Modules ===================================== +* The :class:`ftplib.FTP` class now supports the context manager protocol + (Contributed by Tarek Ziad? and Giampaolo Rodol?; :issue:`4972`.) + * The previously deprecated :func:`string.maketrans` function has been removed in favor of the static methods, :meth:`bytes.maketrans` and :meth:`bytearray.maketrans`. This change solves the confusion around which Modified: python/branches/py3k-jit/Lib/ftplib.py ============================================================================== --- python/branches/py3k-jit/Lib/ftplib.py (original) +++ python/branches/py3k-jit/Lib/ftplib.py Tue May 11 00:50:00 2010 @@ -120,6 +120,20 @@ if user: self.login(user, passwd, acct) + def __enter__(self): + return self + + # Context management protocol: try to quit() if active + def __exit__(self, *args): + if self.sock is not None: + try: + self.quit() + except (socket.error, EOFError): + pass + finally: + if self.sock is not None: + self.close() + def connect(self, host='', port=0, timeout=-999): '''Connect to host. Arguments are: - host: hostname to connect to (string, default previous host) Modified: python/branches/py3k-jit/Lib/test/test_asyncore.py ============================================================================== --- python/branches/py3k-jit/Lib/test/test_asyncore.py (original) +++ python/branches/py3k-jit/Lib/test/test_asyncore.py Tue May 11 00:50:00 2010 @@ -419,11 +419,285 @@ self.assertEqual(open(TESTFN, 'rb').read(), self.d + d1 + d2) +class BaseTestHandler(asyncore.dispatcher): + + def __init__(self, sock=None): + asyncore.dispatcher.__init__(self, sock) + self.flag = False + + def handle_accept(self): + raise Exception("handle_accept not supposed to be called") + + def handle_connect(self): + raise Exception("handle_connect not supposed to be called") + + def handle_expt(self): + raise Exception("handle_expt not supposed to be called") + + def handle_close(self): + raise Exception("handle_close not supposed to be called") + + def handle_error(self): + raise + + +class TCPServer(asyncore.dispatcher): + """A server which listens on an address and dispatches the + connection to a handler. + """ + + def __init__(self, handler=BaseTestHandler, host=HOST, port=0): + asyncore.dispatcher.__init__(self) + self.create_socket(socket.AF_INET, socket.SOCK_STREAM) + self.set_reuse_addr() + self.bind((host, port)) + self.listen(5) + self.handler = handler + + @property + def address(self): + return self.socket.getsockname()[:2] + + def handle_accept(self): + sock, addr = self.accept() + self.handler(sock) + + def handle_error(self): + raise + + +class BaseClient(BaseTestHandler): + + def __init__(self, address): + BaseTestHandler.__init__(self) + self.create_socket(socket.AF_INET, socket.SOCK_STREAM) + self.connect(address) + + def handle_connect(self): + pass + + +class BaseTestAPI(unittest.TestCase): + + def tearDown(self): + asyncore.close_all() + + def loop_waiting_for_flag(self, instance, timeout=5): + timeout = float(timeout) / 100 + count = 100 + while asyncore.socket_map and count > 0: + asyncore.loop(timeout=0.01, count=1, use_poll=self.use_poll) + if instance.flag: + return + count -= 1 + time.sleep(timeout) + self.fail("flag not set") + + def test_handle_connect(self): + # make sure handle_connect is called on connect() + + class TestClient(BaseClient): + def handle_connect(self): + self.flag = True + + server = TCPServer() + client = TestClient(server.address) + self.loop_waiting_for_flag(client) + + def test_handle_accept(self): + # make sure handle_accept() is called when a client connects + + class TestListener(BaseTestHandler): + + def __init__(self): + BaseTestHandler.__init__(self) + self.create_socket(socket.AF_INET, socket.SOCK_STREAM) + self.bind((HOST, 0)) + self.listen(5) + self.address = self.socket.getsockname()[:2] + + def handle_accept(self): + self.flag = True + + server = TestListener() + client = BaseClient(server.address) + self.loop_waiting_for_flag(server) + + def test_handle_read(self): + # make sure handle_read is called on data received + + class TestClient(BaseClient): + def handle_read(self): + self.flag = True + + class TestHandler(BaseTestHandler): + def __init__(self, conn): + BaseTestHandler.__init__(self, conn) + self.send(b'x' * 1024) + + server = TCPServer(TestHandler) + client = TestClient(server.address) + self.loop_waiting_for_flag(client) + + def test_handle_write(self): + # make sure handle_write is called + + class TestClient(BaseClient): + def handle_write(self): + self.flag = True + + server = TCPServer() + client = TestClient(server.address) + self.loop_waiting_for_flag(client) + + def test_handle_close(self): + # make sure handle_close is called when the other end closes + # the connection + + class TestClient(BaseClient): + + def handle_read(self): + # in order to make handle_close be called we are supposed + # to make at least one recv() call + self.recv(1024) + + def handle_close(self): + self.flag = True + self.close() + + class TestHandler(BaseTestHandler): + def __init__(self, conn): + BaseTestHandler.__init__(self, conn) + self.close() + + server = TCPServer(TestHandler) + client = TestClient(server.address) + self.loop_waiting_for_flag(client) + + @unittest.skipIf(sys.platform.startswith("sunos"), + "OOB support is broken on Solaris") + def test_handle_expt(self): + # Make sure handle_expt is called on OOB data received. + # Note: this might fail on some platforms as OOB data is + # tenuously supported and rarely used. + + class TestClient(BaseClient): + def handle_expt(self): + self.flag = True + + class TestHandler(BaseTestHandler): + def __init__(self, conn): + BaseTestHandler.__init__(self, conn) + self.socket.send(bytes(chr(244), 'latin-1'), socket.MSG_OOB) + + server = TCPServer(TestHandler) + client = TestClient(server.address) + self.loop_waiting_for_flag(client) + + def test_handle_error(self): + + class TestClient(BaseClient): + def handle_write(self): + 1.0 / 0 + def handle_error(self): + self.flag = True + try: + raise + except ZeroDivisionError: + pass + else: + raise Exception("exception not raised") + + server = TCPServer() + client = TestClient(server.address) + self.loop_waiting_for_flag(client) + + def test_connection_attributes(self): + server = TCPServer() + client = BaseClient(server.address) + + # we start disconnected + self.assertFalse(server.connected) + self.assertTrue(server.accepting) + # XXX - Solaris seems to connect() immediately even without + # starting the poller. This is something which should be + # fixed as handle_connect() gets called immediately even if + # no connection actually took place (see issue #8490). + if not sys.platform.startswith("sunos"): + self.assertFalse(client.connected) + self.assertFalse(client.accepting) + + # execute some loops so that client connects to server + asyncore.loop(timeout=0.01, use_poll=self.use_poll, count=100) + self.assertFalse(server.connected) + self.assertTrue(server.accepting) + self.assertTrue(client.connected) + self.assertFalse(client.accepting) + + # disconnect the client + client.close() + self.assertFalse(server.connected) + self.assertTrue(server.accepting) + self.assertFalse(client.connected) + self.assertFalse(client.accepting) + + # stop serving + server.close() + self.assertFalse(server.connected) + self.assertFalse(server.accepting) + + def test_create_socket(self): + s = asyncore.dispatcher() + s.create_socket(socket.AF_INET, socket.SOCK_STREAM) + self.assertEqual(s.socket.family, socket.AF_INET) + self.assertEqual(s.socket.type, socket.SOCK_STREAM) + + def test_bind(self): + s1 = asyncore.dispatcher() + s1.create_socket(socket.AF_INET, socket.SOCK_STREAM) + s1.bind((HOST, 0)) + s1.listen(5) + port = s1.socket.getsockname()[1] + + s2 = asyncore.dispatcher() + s2.create_socket(socket.AF_INET, socket.SOCK_STREAM) + # EADDRINUSE indicates the socket was correctly bound + self.assertRaises(socket.error, s2.bind, (HOST, port)) + + def test_set_reuse_addr(self): + sock = socket.socket() + try: + sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) + except socket.error: + unittest.skip("SO_REUSEADDR not supported on this platform") + else: + # if SO_REUSEADDR succeeded for sock we expect asyncore + # to do the same + s = asyncore.dispatcher(socket.socket()) + self.assertFalse(s.socket.getsockopt(socket.SOL_SOCKET, + socket.SO_REUSEADDR)) + s.create_socket(socket.AF_INET, socket.SOCK_STREAM) + s.set_reuse_addr() + self.assertTrue(s.socket.getsockopt(socket.SOL_SOCKET, + socket.SO_REUSEADDR)) + finally: + sock.close() + + +class TestAPI_UseSelect(BaseTestAPI): + use_poll = False + +class TestAPI_UsePoll(BaseTestAPI): + use_poll = True + + def test_main(): tests = [HelperFunctionTests, DispatcherTests, DispatcherWithSendTests, - DispatcherWithSendTests_UsePoll] + DispatcherWithSendTests_UsePoll, TestAPI_UseSelect] if hasattr(asyncore, 'file_wrapper'): tests.append(FileWrapperTest) + if hasattr(select, 'poll'): + tests.append(TestAPI_UsePoll) run_unittest(*tests) Modified: python/branches/py3k-jit/Lib/test/test_ftplib.py ============================================================================== --- python/branches/py3k-jit/Lib/test/test_ftplib.py (original) +++ python/branches/py3k-jit/Lib/test/test_ftplib.py Tue May 11 00:50:00 2010 @@ -10,6 +10,7 @@ import io import errno import os +import time try: import ssl except ImportError: @@ -137,6 +138,9 @@ # sends back the received string (used by the test suite) self.push(arg) + def cmd_noop(self, arg): + self.push('200 noop ok') + def cmd_user(self, arg): self.push('331 username ok') @@ -218,6 +222,7 @@ self.active = False self.active_lock = threading.Lock() self.host, self.port = self.socket.getsockname()[:2] + self.handler_instance = None def start(self): assert not self.active @@ -241,8 +246,7 @@ def handle_accept(self): conn, addr = self.accept() - self.handler = self.handler(conn) - self.close() + self.handler_instance = self.handler(conn) def handle_connect(self): self.close() @@ -459,12 +463,12 @@ def test_rename(self): self.client.rename('a', 'b') - self.server.handler.next_response = '200' + self.server.handler_instance.next_response = '200' self.assertRaises(ftplib.error_reply, self.client.rename, 'a', 'b') def test_delete(self): self.client.delete('foo') - self.server.handler.next_response = '199' + self.server.handler_instance.next_response = '199' self.assertRaises(ftplib.error_reply, self.client.delete, 'foo') def test_size(self): @@ -512,7 +516,7 @@ def test_storbinary(self): f = io.BytesIO(RETR_DATA.encode('ascii')) self.client.storbinary('stor', f) - self.assertEqual(self.server.handler.last_received_data, RETR_DATA) + self.assertEqual(self.server.handler_instance.last_received_data, RETR_DATA) # test new callback arg flag = [] f.seek(0) @@ -524,12 +528,12 @@ for r in (30, '30'): f.seek(0) self.client.storbinary('stor', f, rest=r) - self.assertEqual(self.server.handler.rest, str(r)) + self.assertEqual(self.server.handler_instance.rest, str(r)) def test_storlines(self): f = io.BytesIO(RETR_DATA.replace('\r\n', '\n').encode('ascii')) self.client.storlines('stor', f) - self.assertEqual(self.server.handler.last_received_data, RETR_DATA) + self.assertEqual(self.server.handler_instance.last_received_data, RETR_DATA) # test new callback arg flag = [] f.seek(0) @@ -548,14 +552,59 @@ def test_makeport(self): self.client.makeport() # IPv4 is in use, just make sure send_eprt has not been used - self.assertEqual(self.server.handler.last_received_cmd, 'port') + self.assertEqual(self.server.handler_instance.last_received_cmd, 'port') def test_makepasv(self): host, port = self.client.makepasv() conn = socket.create_connection((host, port), 2) conn.close() # IPv4 is in use, just make sure send_epsv has not been used - self.assertEqual(self.server.handler.last_received_cmd, 'pasv') + self.assertEqual(self.server.handler_instance.last_received_cmd, 'pasv') + + def test_with_statement(self): + self.client.quit() + + def is_client_connected(): + if self.client.sock is None: + return False + try: + self.client.sendcmd('noop') + except (socket.error, EOFError): + return False + return True + + # base test + with ftplib.FTP(timeout=2) as self.client: + self.client.connect(self.server.host, self.server.port) + self.client.sendcmd('noop') + self.assertTrue(is_client_connected()) + self.assertEqual(self.server.handler_instance.last_received_cmd, 'quit') + self.assertFalse(is_client_connected()) + + # QUIT sent inside the with block + with ftplib.FTP(timeout=2) as self.client: + self.client.connect(self.server.host, self.server.port) + self.client.sendcmd('noop') + self.client.quit() + self.assertEqual(self.server.handler_instance.last_received_cmd, 'quit') + self.assertFalse(is_client_connected()) + + # force a wrong response code to be sent on QUIT: error_perm + # is expected and the connection is supposed to be closed + try: + with ftplib.FTP(timeout=2) as self.client: + self.client.connect(self.server.host, self.server.port) + self.client.sendcmd('noop') + self.server.handler_instance.next_response = '550 error on quit' + except ftplib.error_perm as err: + self.assertEqual(str(err), '550 error on quit') + else: + self.fail('Exception not raised') + # needed to give the threaded server some time to set the attribute + # which otherwise would still be == 'noop' + time.sleep(0.1) + self.assertEqual(self.server.handler_instance.last_received_cmd, 'quit') + self.assertFalse(is_client_connected()) class TestIPv6Environment(TestCase): @@ -575,13 +624,13 @@ def test_makeport(self): self.client.makeport() - self.assertEqual(self.server.handler.last_received_cmd, 'eprt') + self.assertEqual(self.server.handler_instance.last_received_cmd, 'eprt') def test_makepasv(self): host, port = self.client.makepasv() conn = socket.create_connection((host, port), 2) conn.close() - self.assertEqual(self.server.handler.last_received_cmd, 'epsv') + self.assertEqual(self.server.handler_instance.last_received_cmd, 'epsv') def test_transfer(self): def retr(): Modified: python/branches/py3k-jit/Lib/unittest/__main__.py ============================================================================== --- python/branches/py3k-jit/Lib/unittest/__main__.py (original) +++ python/branches/py3k-jit/Lib/unittest/__main__.py Tue May 11 00:50:00 2010 @@ -2,7 +2,7 @@ import sys if sys.argv[0].endswith("__main__.py"): - sys.argv[0] = "unittest" + sys.argv[0] = "python -m unittest" __unittest = True Modified: python/branches/py3k-jit/Lib/unittest/main.py ============================================================================== --- python/branches/py3k-jit/Lib/unittest/main.py (original) +++ python/branches/py3k-jit/Lib/unittest/main.py Tue May 11 00:50:00 2010 @@ -22,10 +22,9 @@ -q, --quiet Minimal output %(failfast)s%(catchbreak)s%(buffer)s Examples: - %(progName)s test_module - run tests from test_module - %(progName)s test_module.TestClass - run tests from - test_module.TestClass - %(progName)s test_module.TestClass.test_method - run specified test method + %(progName)s test_module - run tests from test_module + %(progName)s module.TestClass - run tests from module.TestClass + %(progName)s module.Class.test_method - run specified test method [tests] can be a list of any number of test modules, classes and test methods. @@ -68,7 +67,7 @@ USAGE = USAGE_FROM_MODULE # defaults for testing - failfast = catchbreak = buffer = None + failfast = catchbreak = buffer = progName = None def __init__(self, module='__main__', defaultTest=None, argv=None, testRunner=None, testLoader=loader.defaultTestLoader, @@ -160,8 +159,10 @@ def _do_discovery(self, argv, Loader=loader.TestLoader): # handle command line args for test discovery + self.progName = '%s discover' % self.progName import optparse parser = optparse.OptionParser() + parser.prog = self.progName parser.add_option('-v', '--verbose', dest='verbose', default=False, help='Verbose output', action='store_true') if self.failfast != False: Modified: python/branches/py3k-jit/Misc/ACKS ============================================================================== --- python/branches/py3k-jit/Misc/ACKS (original) +++ python/branches/py3k-jit/Misc/ACKS Tue May 11 00:50:00 2010 @@ -343,6 +343,7 @@ Gregor Hoffleit Chris Hoffman Albert Hofkamp +Tomas Hoger Jonathan Hogg Gerrit Holl Shane Holloway Modified: python/branches/py3k-jit/Misc/NEWS ============================================================================== --- python/branches/py3k-jit/Misc/NEWS (original) +++ python/branches/py3k-jit/Misc/NEWS Tue May 11 00:50:00 2010 @@ -351,6 +351,9 @@ Library ------- +- Issue #4972: Add support for the context manager protocol to the ftplib.FTP + class. + - Issue #8664: In py_compile, create __pycache__ when the compiled path is given. @@ -1111,6 +1114,9 @@ Extension Modules ----------------- +- Issue #8674: Fixed a number of incorrect or undefined-behaviour-inducing + overflow checks in the audioop module. + - Issue #8644: The accuracy of td.total_seconds() has been improved (by calculating with integer arithmetic instead of float arithmetic internally): the result is now always correctly rounded, and is equivalent to td / Modified: python/branches/py3k-jit/Modules/audioop.c ============================================================================== --- python/branches/py3k-jit/Modules/audioop.c (original) +++ python/branches/py3k-jit/Modules/audioop.c Tue May 11 00:50:00 2010 @@ -834,7 +834,7 @@ audioop_tostereo(PyObject *self, PyObject *args) { signed char *cp, *ncp; - int len, new_len, size, val1, val2, val = 0; + int len, size, val1, val2, val = 0; double fac1, fac2, fval, maxval; PyObject *rv; int i; @@ -851,14 +851,13 @@ return 0; } - new_len = len*2; - if (new_len < 0) { + if (len > INT_MAX/2) { PyErr_SetString(PyExc_MemoryError, "not enough memory for output buffer"); return 0; } - rv = PyBytes_FromStringAndSize(NULL, new_len); + rv = PyBytes_FromStringAndSize(NULL, len*2); if ( rv == 0 ) return 0; ncp = (signed char *)PyBytes_AsString(rv); @@ -1021,7 +1020,7 @@ { signed char *cp; unsigned char *ncp; - int len, new_len, size, size2, val = 0; + int len, size, size2, val = 0; PyObject *rv; int i, j; @@ -1035,13 +1034,12 @@ return 0; } - new_len = (len/size)*size2; - if (new_len < 0) { + if (len/size > INT_MAX/size2) { PyErr_SetString(PyExc_MemoryError, "not enough memory for output buffer"); return 0; } - rv = PyBytes_FromStringAndSize(NULL, new_len); + rv = PyBytes_FromStringAndSize(NULL, (len/size)*size2); if ( rv == 0 ) return 0; ncp = (unsigned char *)PyBytes_AsString(rv); @@ -1077,7 +1075,6 @@ int chan, d, *prev_i, *cur_i, cur_o; PyObject *state, *samps, *str, *rv = NULL; int bytes_per_frame; - size_t alloc_size; weightA = 1; weightB = 0; @@ -1120,14 +1117,13 @@ inrate /= d; outrate /= d; - alloc_size = sizeof(int) * (unsigned)nchannels; - if (alloc_size < (unsigned)nchannels) { + if ((size_t)nchannels > PY_SIZE_MAX/sizeof(int)) { PyErr_SetString(PyExc_MemoryError, "not enough memory for output buffer"); return 0; } - prev_i = (int *) malloc(alloc_size); - cur_i = (int *) malloc(alloc_size); + prev_i = (int *) malloc(nchannels * sizeof(int)); + cur_i = (int *) malloc(nchannels * sizeof(int)); if (prev_i == NULL || cur_i == NULL) { (void) PyErr_NoMemory(); goto exit; @@ -1300,7 +1296,7 @@ unsigned char *cp; unsigned char cval; signed char *ncp; - int len, new_len, size, val; + int len, size, val; PyObject *rv; int i; @@ -1313,18 +1309,17 @@ return 0; } - new_len = len*size; - if (new_len < 0) { + if (len > INT_MAX/size) { PyErr_SetString(PyExc_MemoryError, "not enough memory for output buffer"); return 0; } - rv = PyBytes_FromStringAndSize(NULL, new_len); + rv = PyBytes_FromStringAndSize(NULL, len*size); if ( rv == 0 ) return 0; ncp = (signed char *)PyBytes_AsString(rv); - for ( i=0; i < new_len; i += size ) { + for ( i=0; i < len*size; i += size ) { cval = *cp++; val = st_ulaw2linear16(cval); @@ -1374,7 +1369,7 @@ unsigned char *cp; unsigned char cval; signed char *ncp; - int len, new_len, size, val; + int len, size, val; PyObject *rv; int i; @@ -1387,18 +1382,17 @@ return 0; } - new_len = len*size; - if (new_len < 0) { + if (len > INT_MAX/size) { PyErr_SetString(PyExc_MemoryError, "not enough memory for output buffer"); return 0; } - rv = PyBytes_FromStringAndSize(NULL, new_len); + rv = PyBytes_FromStringAndSize(NULL, len*size); if ( rv == 0 ) return 0; ncp = (signed char *)PyBytes_AsString(rv); - for ( i=0; i < new_len; i += size ) { + for ( i=0; i < len*size; i += size ) { cval = *cp++; val = st_alaw2linear16(cval); @@ -1523,7 +1517,7 @@ { signed char *cp; signed char *ncp; - int len, new_len, size, valpred, step, delta, index, sign, vpdiff; + int len, size, valpred, step, delta, index, sign, vpdiff; PyObject *rv, *str, *state; int i, inputbuffer = 0, bufferstep; @@ -1545,13 +1539,12 @@ } else if ( !PyArg_ParseTuple(state, "ii", &valpred, &index) ) return 0; - new_len = len*size*2; - if (new_len < 0) { + if (len > (INT_MAX/2)/size) { PyErr_SetString(PyExc_MemoryError, "not enough memory for output buffer"); return 0; } - str = PyBytes_FromStringAndSize(NULL, new_len); + str = PyBytes_FromStringAndSize(NULL, len*size*2); if ( str == 0 ) return 0; ncp = (signed char *)PyBytes_AsString(str); @@ -1559,7 +1552,7 @@ step = stepsizeTable[index]; bufferstep = 0; - for ( i=0; i < new_len; i += size ) { + for ( i=0; i < len*size*2; i += size ) { /* Step 1 - get the delta value and compute next index */ if ( bufferstep ) { delta = inputbuffer & 0xf; Modified: python/branches/py3k-jit/Objects/longobject.c ============================================================================== --- python/branches/py3k-jit/Objects/longobject.c (original) +++ python/branches/py3k-jit/Objects/longobject.c Tue May 11 00:50:00 2010 @@ -95,8 +95,10 @@ #define MAX(x, y) ((x) < (y) ? (y) : (x)) #define MIN(x, y) ((x) > (y) ? (y) : (x)) -#define SIGCHECK(PyTryBlock) \ - if (PyErr_CheckSignals()) PyTryBlock \ +#define SIGCHECK(PyTryBlock) \ + do { \ + if (PyErr_CheckSignals()) PyTryBlock \ + } while(0) /* Normalize (remove leading zeros from) a long int object. Doesn't attempt to free the storage--in most cases, due to the nature @@ -278,12 +280,12 @@ neg = 0; if (Py_IS_INFINITY(dval)) { PyErr_SetString(PyExc_OverflowError, - "cannot convert float infinity to integer"); + "cannot convert float infinity to integer"); return NULL; } if (Py_IS_NAN(dval)) { PyErr_SetString(PyExc_ValueError, - "cannot convert float NaN to integer"); + "cannot convert float NaN to integer"); return NULL; } if (dval < 0.0) { @@ -404,7 +406,7 @@ /* res is already set to -1 */ } } - exit: + exit: if (do_decref) { Py_DECREF(vv); } @@ -474,7 +476,7 @@ } /* else overflow */ - overflow: + overflow: PyErr_SetString(PyExc_OverflowError, "Python int too large to convert to C ssize_t"); return -1; @@ -504,7 +506,7 @@ x = 0; if (i < 0) { PyErr_SetString(PyExc_OverflowError, - "can't convert negative value to unsigned int"); + "can't convert negative value to unsigned int"); return (unsigned long) -1; } switch (i) { @@ -516,7 +518,8 @@ x = (x << PyLong_SHIFT) | v->ob_digit[i]; if ((x >> PyLong_SHIFT) != prev) { PyErr_SetString(PyExc_OverflowError, - "python int too large to convert to C unsigned long"); + "python int too large to convert " + "to C unsigned long"); return (unsigned long) -1; } } @@ -671,7 +674,7 @@ } return result; -Overflow: + Overflow: PyErr_SetString(PyExc_OverflowError, "int has too many bits " "to express in a platform size_t"); return (size_t)-1; @@ -681,7 +684,7 @@ _PyLong_FromByteArray(const unsigned char* bytes, size_t n, int little_endian, int is_signed) { - const unsigned char* pstartbyte;/* LSB of bytes */ + const unsigned char* pstartbyte; /* LSB of bytes */ int incr; /* direction to move pstartbyte */ const unsigned char* pendbyte; /* MSB of bytes */ size_t numsignificantbytes; /* number of bytes that matter */ @@ -769,8 +772,7 @@ if (accumbits >= PyLong_SHIFT) { /* There's enough to fill a Python digit. */ assert(idigit < ndigits); - v->ob_digit[idigit] = (digit)(accum & - PyLong_MASK); + v->ob_digit[idigit] = (digit)(accum & PyLong_MASK); ++idigit; accum >>= PyLong_SHIFT; accumbits -= PyLong_SHIFT; @@ -795,9 +797,9 @@ int little_endian, int is_signed) { Py_ssize_t i; /* index into v->ob_digit */ - Py_ssize_t ndigits; /* |v->ob_size| */ + Py_ssize_t ndigits; /* |v->ob_size| */ twodigits accum; /* sliding register */ - unsigned int accumbits; /* # bits in accum */ + unsigned int accumbits; /* # bits in accum */ int do_twos_comp; /* store 2's-comp? is_signed and v < 0 */ digit carry; /* for computing 2's-comp */ size_t j; /* # bytes filled */ @@ -810,7 +812,7 @@ ndigits = -(Py_SIZE(v)); if (!is_signed) { PyErr_SetString(PyExc_OverflowError, - "can't convert negative int to unsigned"); + "can't convert negative int to unsigned"); return -1; } do_twos_comp = 1; @@ -856,8 +858,7 @@ /* Count # of sign bits -- they needn't be stored, * although for signed conversion we need later to * make sure at least one sign bit gets stored. */ - digit s = do_twos_comp ? thisdigit ^ PyLong_MASK : - thisdigit; + digit s = do_twos_comp ? thisdigit ^ PyLong_MASK : thisdigit; while (s != 0) { s >>= 1; accumbits++; @@ -917,7 +918,7 @@ return 0; -Overflow: + Overflow: PyErr_SetString(PyExc_OverflowError, "int too big to convert"); return -1; @@ -986,7 +987,7 @@ */ #define IS_LITTLE_ENDIAN (int)*(unsigned char*)&one -#define PY_ABS_LLONG_MIN (0-(unsigned PY_LONG_LONG)PY_LLONG_MIN) +#define PY_ABS_LLONG_MIN (0-(unsigned PY_LONG_LONG)PY_LLONG_MIN) /* Create a new long int object from a C PY_LONG_LONG int. */ @@ -1172,9 +1173,8 @@ case 0: return 0; case 1: return v->ob_digit[0]; } - res = _PyLong_AsByteArray( - (PyLongObject *)vv, (unsigned char *)&bytes, - SIZEOF_LONG_LONG, IS_LITTLE_ENDIAN, 1); + res = _PyLong_AsByteArray((PyLongObject *)vv, (unsigned char *)&bytes, + SIZEOF_LONG_LONG, IS_LITTLE_ENDIAN, 1); /* Plan 9 can't handle PY_LONG_LONG in ? : expressions */ if (res < 0) @@ -1205,9 +1205,8 @@ case 1: return v->ob_digit[0]; } - res = _PyLong_AsByteArray( - (PyLongObject *)vv, (unsigned char *)&bytes, - SIZEOF_LONG_LONG, IS_LITTLE_ENDIAN, 0); + res = _PyLong_AsByteArray((PyLongObject *)vv, (unsigned char *)&bytes, + SIZEOF_LONG_LONG, IS_LITTLE_ENDIAN, 0); /* Plan 9 can't handle PY_LONG_LONG in ? : expressions */ if (res < 0) @@ -1373,7 +1372,7 @@ /* res is already set to -1 */ } } - exit: + exit: if (do_decref) { Py_DECREF(vv); } @@ -1382,11 +1381,13 @@ #endif /* HAVE_LONG_LONG */ -#define CHECK_BINOP(v,w) \ - if (!PyLong_Check(v) || !PyLong_Check(w)) { \ - Py_INCREF(Py_NotImplemented); \ - return Py_NotImplemented; \ - } +#define CHECK_BINOP(v,w) \ + do { \ + if (!PyLong_Check(v) || !PyLong_Check(w)) { \ + Py_INCREF(Py_NotImplemented); \ + return Py_NotImplemented; \ + } \ + } while(0) /* bits_in_digit(d) returns the unique integer k such that 2**(k-1) <= d < 2**k if d is nonzero, else 0. */ @@ -1600,9 +1601,9 @@ } /* check for keyboard interrupt */ SIGCHECK({ - Py_DECREF(scratch); - return NULL; - }) + Py_DECREF(scratch); + return NULL; + }); } /* pout should have at least one digit, so that the case when a = 0 works correctly */ @@ -1998,8 +1999,8 @@ twodigits convmax = base; int i = 1; - log_base_BASE[base] = log((double)base) / - log((double)PyLong_BASE); + log_base_BASE[base] = (log((double)base) / + log((double)PyLong_BASE)); for (;;) { twodigits next = convmax * base; if (next > PyLong_BASE) @@ -2043,7 +2044,7 @@ c = (digit)_PyLong_DigitValue[Py_CHARMASK(*str++)]; for (i = 1; i < convwidth && str != scan; ++i, ++str) { c = (twodigits)(c * base + - (int)_PyLong_DigitValue[Py_CHARMASK(*str)]); + (int)_PyLong_DigitValue[Py_CHARMASK(*str)]); assert(c < PyLong_BASE); } @@ -2116,7 +2117,7 @@ long_normalize(z); return (PyObject *) maybe_small_long(z); - onError: + onError: Py_XDECREF(z); slen = strlen(orig_str) < 200 ? strlen(orig_str) : 200; strobj = PyUnicode_FromStringAndSize(orig_str, slen); @@ -2272,12 +2273,12 @@ single-digit quotient q, remainder in vk[0:size_w]. */ SIGCHECK({ - Py_DECREF(a); - Py_DECREF(w); - Py_DECREF(v); - *prem = NULL; - return NULL; - }) + Py_DECREF(a); + Py_DECREF(w); + Py_DECREF(v); + *prem = NULL; + return NULL; + }); /* estimate quotient digit q; may overestimate by 1 (rare) */ vtop = vk[size_w]; @@ -2303,7 +2304,7 @@ (stwodigits)q * (stwodigits)w0[i]; vk[i] = (digit)z & PyLong_MASK; zhi = (sdigit)Py_ARITHMETIC_RIGHT_SHIFT(stwodigits, - z, PyLong_SHIFT); + z, PyLong_SHIFT); } /* add w back if q was too large (this branch taken rarely) */ @@ -2370,7 +2371,7 @@ if (a_size >= (PY_SSIZE_T_MAX - 1) / PyLong_SHIFT + 1 && (a_size > (PY_SSIZE_T_MAX - 1) / PyLong_SHIFT + 1 || a_bits > (PY_SSIZE_T_MAX - 1) % PyLong_SHIFT + 1)) - goto overflow; + goto overflow; a_bits = (a_size - 1) * PyLong_SHIFT + a_bits; /* Shift the first DBL_MANT_DIG + 2 bits of a into x_digits[0:x_size] @@ -2428,7 +2429,8 @@ break; } } - assert(1 <= x_size && x_size <= (Py_ssize_t)(sizeof(x_digits)/sizeof(digit))); + assert(1 <= x_size && + x_size <= (Py_ssize_t)(sizeof(x_digits)/sizeof(digit))); /* Round, and convert to double. */ x_digits[0] += half_even_correction[x_digits[0] & 7]; @@ -2603,8 +2605,8 @@ if (size_a < size_b) { { PyLongObject *temp = a; a = b; b = temp; } { Py_ssize_t size_temp = size_a; - size_a = size_b; - size_b = size_temp; } + size_a = size_b; + size_b = size_temp; } } z = _PyLong_New(size_a+1); if (z == NULL) @@ -2639,8 +2641,8 @@ sign = -1; { PyLongObject *temp = a; a = b; b = temp; } { Py_ssize_t size_temp = size_a; - size_a = size_b; - size_b = size_temp; } + size_a = size_b; + size_b = size_temp; } } else if (size_a == size_b) { /* Find highest digit where a and b differ: */ @@ -2768,9 +2770,9 @@ digit *paend = a->ob_digit + size_a; SIGCHECK({ - Py_DECREF(z); - return NULL; - }) + Py_DECREF(z); + return NULL; + }); carry = *pz + f * f; *pz++ = (digit)(carry & PyLong_MASK); @@ -2806,9 +2808,9 @@ digit *pbend = b->ob_digit + size_b; SIGCHECK({ - Py_DECREF(z); - return NULL; - }) + Py_DECREF(z); + return NULL; + }); while (pb < pbend) { carry += *pz + *pb++ * f; @@ -2832,7 +2834,10 @@ Returns 0 on success, -1 on failure. */ static int -kmul_split(PyLongObject *n, Py_ssize_t size, PyLongObject **high, PyLongObject **low) +kmul_split(PyLongObject *n, + Py_ssize_t size, + PyLongObject **high, + PyLongObject **low) { PyLongObject *hi, *lo; Py_ssize_t size_lo, size_hi; @@ -3021,7 +3026,7 @@ return long_normalize(ret); - fail: + fail: Py_XDECREF(ret); Py_XDECREF(ah); Py_XDECREF(al); @@ -3131,7 +3136,7 @@ Py_DECREF(bslice); return long_normalize(ret); - fail: + fail: Py_DECREF(ret); Py_XDECREF(bslice); return NULL; @@ -3414,7 +3419,7 @@ here. Both a and b would have to be enormous, using close to SIZE_T_MAX bytes of memory each. */ PyErr_SetString(PyExc_OverflowError, - "intermediate overflow during division"); + "intermediate overflow during division"); goto error; } x = _PyLong_New(a_size + shift_digits + 1); @@ -3578,7 +3583,7 @@ if (Py_SIZE(b) < 0) { /* if exponent is negative */ if (c) { PyErr_SetString(PyExc_TypeError, "pow() 2nd argument " - "cannot be negative when 3rd argument specified"); + "cannot be negative when 3rd argument specified"); goto Error; } else { @@ -3644,26 +3649,28 @@ * is NULL. */ #define REDUCE(X) \ - if (c != NULL) { \ - if (l_divmod(X, c, NULL, &temp) < 0) \ - goto Error; \ - Py_XDECREF(X); \ - X = temp; \ - temp = NULL; \ - } + do { \ + if (c != NULL) { \ + if (l_divmod(X, c, NULL, &temp) < 0) \ + goto Error; \ + Py_XDECREF(X); \ + X = temp; \ + temp = NULL; \ + } \ + } while(0) /* Multiply two values, then reduce the result: result = X*Y % c. If c is NULL, skip the mod. */ -#define MULT(X, Y, result) \ -{ \ - temp = (PyLongObject *)long_mul(X, Y); \ - if (temp == NULL) \ - goto Error; \ - Py_XDECREF(result); \ - result = temp; \ - temp = NULL; \ - REDUCE(result) \ -} +#define MULT(X, Y, result) \ + do { \ + temp = (PyLongObject *)long_mul(X, Y); \ + if (temp == NULL) \ + goto Error; \ + Py_XDECREF(result); \ + result = temp; \ + temp = NULL; \ + REDUCE(result); \ + } while(0) if (Py_SIZE(b) <= FIVEARY_CUTOFF) { /* Left-to-right binary exponentiation (HAC Algorithm 14.79) */ @@ -3672,9 +3679,9 @@ digit bi = b->ob_digit[i]; for (j = (digit)1 << (PyLong_SHIFT-1); j != 0; j >>= 1) { - MULT(z, z, z) + MULT(z, z, z); if (bi & j) - MULT(z, a, z) + MULT(z, a, z); } } } @@ -3683,7 +3690,7 @@ Py_INCREF(z); /* still holds 1L */ table[0] = z; for (i = 1; i < 32; ++i) - MULT(table[i-1], a, table[i]) + MULT(table[i-1], a, table[i]); for (i = Py_SIZE(b) - 1; i >= 0; --i) { const digit bi = b->ob_digit[i]; @@ -3691,9 +3698,9 @@ for (j = PyLong_SHIFT - 5; j >= 0; j -= 5) { const int index = (bi >> j) & 0x1f; for (k = 0; k < 5; ++k) - MULT(z, z, z) + MULT(z, z, z); if (index) - MULT(z, table[index], z) + MULT(z, table[index], z); } } } @@ -3708,13 +3715,13 @@ } goto Done; - Error: + Error: if (z != NULL) { Py_DECREF(z); z = NULL; } /* fall through */ - Done: + Done: if (Py_SIZE(b) > FIVEARY_CUTOFF) { for (i = 0; i < 32; ++i) Py_XDECREF(table[i]); @@ -3819,12 +3826,11 @@ for (i = 0, j = wordshift; i < newsize; i++, j++) { z->ob_digit[i] = (a->ob_digit[j] >> loshift) & lomask; if (i+1 < newsize) - z->ob_digit[i] |= - (a->ob_digit[j+1] << hishift) & himask; + z->ob_digit[i] |= (a->ob_digit[j+1] << hishift) & himask; } z = long_normalize(z); } -rshift_error: + rshift_error: return (PyObject *) maybe_small_long(z); } @@ -3874,7 +3880,7 @@ else assert(!accum); z = long_normalize(z); -lshift_error: + lshift_error: return (PyObject *) maybe_small_long(z); } @@ -3900,7 +3906,7 @@ static PyObject * long_bitwise(PyLongObject *a, int op, /* '&', '|', '^' */ - PyLongObject *b) + PyLongObject *b) { int nega, negb, negz; Py_ssize_t size_a, size_b, size_z, i; @@ -4103,15 +4109,15 @@ /* We only see this if there's a null byte in x, x is a bytes or buffer, *and* a base is given. */ PyErr_Format(PyExc_ValueError, - "invalid literal for int() with base %d: %R", - base, x); + "invalid literal for int() with base %d: %R", + base, x); return NULL; } return PyLong_FromString(string, NULL, base); } else { PyErr_SetString(PyExc_TypeError, - "int() can't convert non-string with explicit base"); + "int() can't convert non-string with explicit base"); return NULL; } } @@ -4371,7 +4377,7 @@ return (PyObject *)result; -error: + error: Py_DECREF(result); return NULL; } @@ -4633,40 +4639,40 @@ converting a non-string."); static PyNumberMethods long_as_number = { - (binaryfunc) long_add, /*nb_add*/ - (binaryfunc) long_sub, /*nb_subtract*/ - (binaryfunc) long_mul, /*nb_multiply*/ - long_mod, /*nb_remainder*/ - long_divmod, /*nb_divmod*/ - long_pow, /*nb_power*/ - (unaryfunc) long_neg, /*nb_negative*/ - (unaryfunc) long_long, /*tp_positive*/ - (unaryfunc) long_abs, /*tp_absolute*/ - (inquiry) long_bool, /*tp_bool*/ - (unaryfunc) long_invert, /*nb_invert*/ - long_lshift, /*nb_lshift*/ - (binaryfunc) long_rshift, /*nb_rshift*/ - long_and, /*nb_and*/ - long_xor, /*nb_xor*/ - long_or, /*nb_or*/ - long_long, /*nb_int*/ - 0, /*nb_reserved*/ - long_float, /*nb_float*/ - 0, /* nb_inplace_add */ - 0, /* nb_inplace_subtract */ - 0, /* nb_inplace_multiply */ - 0, /* nb_inplace_remainder */ - 0, /* nb_inplace_power */ - 0, /* nb_inplace_lshift */ - 0, /* nb_inplace_rshift */ - 0, /* nb_inplace_and */ - 0, /* nb_inplace_xor */ - 0, /* nb_inplace_or */ - long_div, /* nb_floor_divide */ - long_true_divide, /* nb_true_divide */ - 0, /* nb_inplace_floor_divide */ - 0, /* nb_inplace_true_divide */ - long_long, /* nb_index */ + (binaryfunc)long_add, /*nb_add*/ + (binaryfunc)long_sub, /*nb_subtract*/ + (binaryfunc)long_mul, /*nb_multiply*/ + long_mod, /*nb_remainder*/ + long_divmod, /*nb_divmod*/ + long_pow, /*nb_power*/ + (unaryfunc)long_neg, /*nb_negative*/ + (unaryfunc)long_long, /*tp_positive*/ + (unaryfunc)long_abs, /*tp_absolute*/ + (inquiry)long_bool, /*tp_bool*/ + (unaryfunc)long_invert, /*nb_invert*/ + long_lshift, /*nb_lshift*/ + (binaryfunc)long_rshift, /*nb_rshift*/ + long_and, /*nb_and*/ + long_xor, /*nb_xor*/ + long_or, /*nb_or*/ + long_long, /*nb_int*/ + 0, /*nb_reserved*/ + long_float, /*nb_float*/ + 0, /* nb_inplace_add */ + 0, /* nb_inplace_subtract */ + 0, /* nb_inplace_multiply */ + 0, /* nb_inplace_remainder */ + 0, /* nb_inplace_power */ + 0, /* nb_inplace_lshift */ + 0, /* nb_inplace_rshift */ + 0, /* nb_inplace_and */ + 0, /* nb_inplace_xor */ + 0, /* nb_inplace_or */ + long_div, /* nb_floor_divide */ + long_true_divide, /* nb_true_divide */ + 0, /* nb_inplace_floor_divide */ + 0, /* nb_inplace_true_divide */ + long_long, /* nb_index */ }; PyTypeObject PyLong_Type = { @@ -4722,8 +4728,7 @@ static PyStructSequence_Field int_info_fields[] = { {"bits_per_digit", "size of a digit in bits"}, - {"sizeof_digit", "size in bytes of the C type used to " - "represent a digit"}, + {"sizeof_digit", "size in bytes of the C type used to represent a digit"}, {NULL, NULL} }; From python-checkins at python.org Tue May 11 01:13:41 2010 From: python-checkins at python.org (andrew.kuchling) Date: Tue, 11 May 2010 01:13:41 +0200 (CEST) Subject: [Python-checkins] r81070 - python/trunk/Doc/library/socket.rst Message-ID: <20100510231341.551A3EE9A5@mail.python.org> Author: andrew.kuchling Date: Tue May 11 01:13:41 2010 New Revision: 81070 Log: Fix typo Modified: python/trunk/Doc/library/socket.rst Modified: python/trunk/Doc/library/socket.rst ============================================================================== --- python/trunk/Doc/library/socket.rst (original) +++ python/trunk/Doc/library/socket.rst Tue May 11 01:13:41 2010 @@ -722,7 +722,7 @@ Set a timeout on blocking socket operations. The *value* argument can be a nonnegative float expressing seconds, or ``None``. If a float is given, - subsequent socket operations will raise an :exc:`timeout` exception if the + subsequent socket operations will raise a :exc:`timeout` exception if the timeout period *value* has elapsed before the operation has completed. Setting a timeout of ``None`` disables timeouts on socket operations. ``s.settimeout(0.0)`` is equivalent to ``s.setblocking(0)``; From python-checkins at python.org Tue May 11 01:14:27 2010 From: python-checkins at python.org (andrew.kuchling) Date: Tue, 11 May 2010 01:14:27 +0200 (CEST) Subject: [Python-checkins] r81071 - in python/branches/py3k: Modules/_cursesmodule.c Message-ID: <20100510231427.030A8EE9A5@mail.python.org> Author: andrew.kuchling Date: Tue May 11 01:14:26 2010 New Revision: 81071 Log: Merged revisions 81049 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r81049 | andrew.kuchling | 2010-05-10 13:18:25 -0400 (Mon, 10 May 2010) | 1 line Move { out of #if...#else block; this confuses Emacs' C-mode ........ Modified: python/branches/py3k/ (props changed) python/branches/py3k/Modules/_cursesmodule.c Modified: python/branches/py3k/Modules/_cursesmodule.c ============================================================================== --- python/branches/py3k/Modules/_cursesmodule.c (original) +++ python/branches/py3k/Modules/_cursesmodule.c Tue May 11 01:14:26 2010 @@ -1234,10 +1234,11 @@ int rtn; #ifndef WINDOW_HAS_FLAGS - if (0) { + if (0) #else - if (self->win->_flags & _ISPAD) { + if (self->win->_flags & _ISPAD) #endif + { switch(PyTuple_Size(args)) { case 6: if (!PyArg_ParseTuple(args, @@ -1403,10 +1404,11 @@ int rtn; #ifndef WINDOW_HAS_FLAGS - if (0) { + if (0) #else - if (self->win->_flags & _ISPAD) { + if (self->win->_flags & _ISPAD) #endif + { switch(PyTuple_Size(args)) { case 6: if (!PyArg_ParseTuple(args, From solipsis at pitrou.net Tue May 11 01:23:56 2010 From: solipsis at pitrou.net (solipsis at pitrou.net) Date: Tue, 11 May 2010 01:23:56 +0200 (CEST) Subject: [Python-checkins] Daily py3k reference leaks (r81057): sum=0 Message-ID: <20100510232356.776251770A@ns6635.ovh.net> py3k results for svn r81057 (hg cset 2362ae278dfb) -------------------------------------------------- Command line was: ['./python', '-m', 'test.regrtest', '-uall', '-R', '3:3:/home/antoine/py3k/refleaks/reflogqbS45z', '-x'] From python-checkins at python.org Tue May 11 01:24:09 2010 From: python-checkins at python.org (andrew.kuchling) Date: Tue, 11 May 2010 01:24:09 +0200 (CEST) Subject: [Python-checkins] r81072 - python/trunk/Modules/_cursesmodule.c Message-ID: <20100510232409.4C3ADEEA42@mail.python.org> Author: andrew.kuchling Date: Tue May 11 01:24:09 2010 New Revision: 81072 Log: Break long line in macros Modified: python/trunk/Modules/_cursesmodule.c Modified: python/trunk/Modules/_cursesmodule.c ============================================================================== --- python/trunk/Modules/_cursesmodule.c (original) +++ python/trunk/Modules/_cursesmodule.c Tue May 11 01:24:09 2010 @@ -243,42 +243,49 @@ */ #define Window_NoArgNoReturnFunction(X) \ -static PyObject *PyCursesWindow_ ## X (PyCursesWindowObject *self, PyObject *args) \ +static PyObject *PyCursesWindow_ ## X \ +(PyCursesWindowObject *self, PyObject *args) \ { return PyCursesCheckERR(X(self->win), # X); } #define Window_NoArgTrueFalseFunction(X) \ -static PyObject * PyCursesWindow_ ## X (PyCursesWindowObject *self) \ +static PyObject * PyCursesWindow_ ## X \ +(PyCursesWindowObject *self) \ { \ if (X (self->win) == FALSE) { Py_INCREF(Py_False); return Py_False; } \ else { Py_INCREF(Py_True); return Py_True; } } #define Window_NoArgNoReturnVoidFunction(X) \ -static PyObject * PyCursesWindow_ ## X (PyCursesWindowObject *self) \ +static PyObject * PyCursesWindow_ ## X \ +(PyCursesWindowObject *self) \ { \ X(self->win); Py_INCREF(Py_None); return Py_None; } #define Window_NoArg2TupleReturnFunction(X, TYPE, ERGSTR) \ -static PyObject * PyCursesWindow_ ## X (PyCursesWindowObject *self) \ +static PyObject * PyCursesWindow_ ## X \ +(PyCursesWindowObject *self) \ { \ TYPE arg1, arg2; \ X(self->win,arg1,arg2); return Py_BuildValue(ERGSTR, arg1, arg2); } #define Window_OneArgNoReturnVoidFunction(X, TYPE, PARSESTR) \ -static PyObject * PyCursesWindow_ ## X (PyCursesWindowObject *self, PyObject *args) \ +static PyObject * PyCursesWindow_ ## X \ +(PyCursesWindowObject *self, PyObject *args) \ { \ TYPE arg1; \ if (!PyArg_ParseTuple(args, PARSESTR, &arg1)) return NULL; \ X(self->win,arg1); Py_INCREF(Py_None); return Py_None; } #define Window_OneArgNoReturnFunction(X, TYPE, PARSESTR) \ -static PyObject * PyCursesWindow_ ## X (PyCursesWindowObject *self, PyObject *args) \ +static PyObject * PyCursesWindow_ ## X \ +(PyCursesWindowObject *self, PyObject *args) \ { \ TYPE arg1; \ if (!PyArg_ParseTuple(args,PARSESTR, &arg1)) return NULL; \ return PyCursesCheckERR(X(self->win, arg1), # X); } #define Window_TwoArgNoReturnFunction(X, TYPE, PARSESTR) \ -static PyObject * PyCursesWindow_ ## X (PyCursesWindowObject *self, PyObject *args) \ +static PyObject * PyCursesWindow_ ## X \ +(PyCursesWindowObject *self, PyObject *args) \ { \ TYPE arg1, arg2; \ if (!PyArg_ParseTuple(args,PARSESTR, &arg1, &arg2)) return NULL; \ From python-checkins at python.org Tue May 11 01:27:01 2010 From: python-checkins at python.org (andrew.kuchling) Date: Tue, 11 May 2010 01:27:01 +0200 (CEST) Subject: [Python-checkins] r81073 - python/trunk/Modules/_cursesmodule.c Message-ID: <20100510232701.51638EE9FA@mail.python.org> Author: andrew.kuchling Date: Tue May 11 01:27:01 2010 New Revision: 81073 Log: Use ';' after initialization macros to avoid confusing re-indenters Modified: python/trunk/Modules/_cursesmodule.c Modified: python/trunk/Modules/_cursesmodule.c ============================================================================== --- python/trunk/Modules/_cursesmodule.c (original) +++ python/trunk/Modules/_cursesmodule.c Tue May 11 01:27:01 2010 @@ -1705,8 +1705,8 @@ { short color,r,g,b; - PyCursesInitialised - PyCursesInitialisedColor + PyCursesInitialised; + PyCursesInitialisedColor; if (!PyArg_ParseTuple(args, "h:color_content", &color)) return NULL; @@ -1724,8 +1724,8 @@ { int n; - PyCursesInitialised - PyCursesInitialisedColor + PyCursesInitialised; + PyCursesInitialisedColor; if (!PyArg_ParseTuple(args, "i:color_pair", &n)) return NULL; return PyInt_FromLong((long) (n << 8)); @@ -1736,7 +1736,7 @@ { int vis,erg; - PyCursesInitialised + PyCursesInitialised; if (!PyArg_ParseTuple(args, "i:curs_set", &vis)) return NULL; @@ -1751,7 +1751,7 @@ { int ms; - PyCursesInitialised + PyCursesInitialised; if (!PyArg_ParseTuple(args, "i:delay_output", &ms)) return NULL; @@ -1763,7 +1763,7 @@ { char ch; - PyCursesInitialised + PyCursesInitialised; ch = erasechar(); @@ -1776,7 +1776,7 @@ int x = 0; int y = 0; - PyCursesInitialised + PyCursesInitialised; getsyx(y, x); @@ -1790,7 +1790,7 @@ int rtn; MEVENT event; - PyCursesInitialised + PyCursesInitialised; rtn = getmouse( &event ); if (rtn == ERR) { @@ -1808,7 +1808,7 @@ { MEVENT event; - PyCursesInitialised + PyCursesInitialised; if (!PyArg_ParseTuple(args, "hiiil", &event.id, &event.x, &event.y, &event.z, @@ -1824,7 +1824,7 @@ { WINDOW *win; - PyCursesInitialised + PyCursesInitialised; if (!PyFile_Check(temp)) { PyErr_SetString(PyExc_TypeError, "argument must be a file object"); @@ -1846,7 +1846,7 @@ { unsigned char tenths; - PyCursesInitialised + PyCursesInitialised; if (!PyArg_ParseTuple(args, "b:halfdelay", &tenths)) return NULL; @@ -1859,7 +1859,7 @@ { int ch; - PyCursesInitialised + PyCursesInitialised; if (!PyArg_ParseTuple(args,"i",&ch)) return NULL; @@ -1877,8 +1877,8 @@ { short color, r, g, b; - PyCursesInitialised - PyCursesInitialisedColor + PyCursesInitialised; + PyCursesInitialisedColor; switch(PyTuple_Size(args)) { case 4: @@ -1897,8 +1897,8 @@ { short pair, f, b; - PyCursesInitialised - PyCursesInitialisedColor + PyCursesInitialised; + PyCursesInitialisedColor; if (PyTuple_Size(args) != 3) { PyErr_SetString(PyExc_TypeError, "init_pair requires 3 arguments"); @@ -2071,7 +2071,7 @@ { int ch; - PyCursesInitialised + PyCursesInitialised; switch(PyTuple_Size(args)) { case 1: @@ -2093,7 +2093,7 @@ int columns; int result; - PyCursesInitialised + PyCursesInitialised; if (!PyArg_ParseTuple(args,"ii:is_term_resized", &lines, &columns)) return NULL; @@ -2115,7 +2115,7 @@ const char *knp; int ch; - PyCursesInitialised + PyCursesInitialised; if (!PyArg_ParseTuple(args,"i",&ch)) return NULL; @@ -2144,7 +2144,7 @@ { int ch; - PyCursesInitialised + PyCursesInitialised; switch(PyTuple_Size(args)) { case 1: @@ -2163,7 +2163,7 @@ PyCurses_MouseInterval(PyObject *self, PyObject *args) { int interval; - PyCursesInitialised + PyCursesInitialised; if (!PyArg_ParseTuple(args,"i;interval",&interval)) return NULL; @@ -2176,7 +2176,7 @@ int newmask; mmask_t oldmask, availmask; - PyCursesInitialised + PyCursesInitialised; if (!PyArg_ParseTuple(args,"i;mousemask",&newmask)) return NULL; availmask = mousemask(newmask, &oldmask); @@ -2189,7 +2189,7 @@ { int ms; - PyCursesInitialised + PyCursesInitialised; if (!PyArg_ParseTuple(args, "i;ms", &ms)) return NULL; return Py_BuildValue("i", napms(ms)); @@ -2202,7 +2202,7 @@ WINDOW *win; int nlines, ncols; - PyCursesInitialised + PyCursesInitialised; if (!PyArg_ParseTuple(args,"ii;nlines,ncols",&nlines,&ncols)) return NULL; @@ -2222,7 +2222,7 @@ WINDOW *win; int nlines, ncols, begin_y=0, begin_x=0; - PyCursesInitialised + PyCursesInitialised; switch (PyTuple_Size(args)) { case 2: @@ -2253,8 +2253,8 @@ { short pair,f,b; - PyCursesInitialised - PyCursesInitialisedColor + PyCursesInitialised; + PyCursesInitialisedColor; switch(PyTuple_Size(args)) { case 1: @@ -2279,8 +2279,8 @@ { int n; - PyCursesInitialised - PyCursesInitialisedColor + PyCursesInitialised; + PyCursesInitialisedColor; switch(PyTuple_Size(args)) { case 1: @@ -2309,7 +2309,7 @@ { int flag = 0; - PyCursesInitialised + PyCursesInitialised; switch(PyTuple_Size(args)) { case 0: @@ -2385,7 +2385,7 @@ int columns; PyObject *result; - PyCursesInitialised + PyCursesInitialised; if (!PyArg_ParseTuple(args,"ii:resizeterm", &lines, &columns)) return NULL; @@ -2409,7 +2409,7 @@ PyObject *result; - PyCursesInitialised + PyCursesInitialised; if (!PyArg_ParseTuple(args,"ii:resize_term", &lines, &columns)) return NULL; @@ -2428,7 +2428,7 @@ { int y,x; - PyCursesInitialised + PyCursesInitialised; if (PyTuple_Size(args)!=2) { PyErr_SetString(PyExc_TypeError, "setsyx requires 2 arguments"); @@ -2449,7 +2449,7 @@ int code; PyObject *c, *cp; - PyCursesInitialised + PyCursesInitialised; code = start_color(); if (code != ERR) { @@ -2541,7 +2541,7 @@ { int fd; - PyCursesInitialised + PyCursesInitialised; if (!PyArg_ParseTuple(args,"i;fd",&fd)) return NULL; @@ -2554,7 +2554,7 @@ PyObject *temp; chtype ch; - PyCursesInitialised + PyCursesInitialised; if (!PyArg_ParseTuple(args,"O;ch or int",&temp)) return NULL; @@ -2576,7 +2576,7 @@ PyObject *temp; int ch; - PyCursesInitialised + PyCursesInitialised; if (!PyArg_ParseTuple(args,"O;ch or int",&temp)) return NULL; @@ -2617,8 +2617,8 @@ { int code; - PyCursesInitialised - PyCursesInitialisedColor + PyCursesInitialised; + PyCursesInitialisedColor; code = use_default_colors(); if (code != ERR) { From python-checkins at python.org Tue May 11 01:28:29 2010 From: python-checkins at python.org (andrew.kuchling) Date: Tue, 11 May 2010 01:28:29 +0200 (CEST) Subject: [Python-checkins] r81074 - in python/branches/py3k: Modules/_cursesmodule.c Message-ID: <20100510232829.01294EEA47@mail.python.org> Author: andrew.kuchling Date: Tue May 11 01:28:28 2010 New Revision: 81074 Log: Merged revisions 81072 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r81072 | andrew.kuchling | 2010-05-10 19:24:09 -0400 (Mon, 10 May 2010) | 1 line Break long line in macros ........ Modified: python/branches/py3k/ (props changed) python/branches/py3k/Modules/_cursesmodule.c Modified: python/branches/py3k/Modules/_cursesmodule.c ============================================================================== --- python/branches/py3k/Modules/_cursesmodule.c (original) +++ python/branches/py3k/Modules/_cursesmodule.c Tue May 11 01:28:28 2010 @@ -251,42 +251,49 @@ */ #define Window_NoArgNoReturnFunction(X) \ -static PyObject *PyCursesWindow_ ## X (PyCursesWindowObject *self, PyObject *args) \ +static PyObject *PyCursesWindow_ ## X \ +(PyCursesWindowObject *self, PyObject *args) \ { return PyCursesCheckERR(X(self->win), # X); } #define Window_NoArgTrueFalseFunction(X) \ -static PyObject * PyCursesWindow_ ## X (PyCursesWindowObject *self) \ +static PyObject * PyCursesWindow_ ## X \ +(PyCursesWindowObject *self) \ { \ if (X (self->win) == FALSE) { Py_INCREF(Py_False); return Py_False; } \ else { Py_INCREF(Py_True); return Py_True; } } #define Window_NoArgNoReturnVoidFunction(X) \ -static PyObject * PyCursesWindow_ ## X (PyCursesWindowObject *self) \ +static PyObject * PyCursesWindow_ ## X \ +(PyCursesWindowObject *self) \ { \ X(self->win); Py_INCREF(Py_None); return Py_None; } #define Window_NoArg2TupleReturnFunction(X, TYPE, ERGSTR) \ -static PyObject * PyCursesWindow_ ## X (PyCursesWindowObject *self) \ +static PyObject * PyCursesWindow_ ## X \ +(PyCursesWindowObject *self) \ { \ TYPE arg1, arg2; \ X(self->win,arg1,arg2); return Py_BuildValue(ERGSTR, arg1, arg2); } #define Window_OneArgNoReturnVoidFunction(X, TYPE, PARSESTR) \ -static PyObject * PyCursesWindow_ ## X (PyCursesWindowObject *self, PyObject *args) \ +static PyObject * PyCursesWindow_ ## X \ +(PyCursesWindowObject *self, PyObject *args) \ { \ TYPE arg1; \ if (!PyArg_ParseTuple(args, PARSESTR, &arg1)) return NULL; \ X(self->win,arg1); Py_INCREF(Py_None); return Py_None; } #define Window_OneArgNoReturnFunction(X, TYPE, PARSESTR) \ -static PyObject * PyCursesWindow_ ## X (PyCursesWindowObject *self, PyObject *args) \ +static PyObject * PyCursesWindow_ ## X \ +(PyCursesWindowObject *self, PyObject *args) \ { \ TYPE arg1; \ if (!PyArg_ParseTuple(args,PARSESTR, &arg1)) return NULL; \ return PyCursesCheckERR(X(self->win, arg1), # X); } #define Window_TwoArgNoReturnFunction(X, TYPE, PARSESTR) \ -static PyObject * PyCursesWindow_ ## X (PyCursesWindowObject *self, PyObject *args) \ +static PyObject * PyCursesWindow_ ## X \ +(PyCursesWindowObject *self, PyObject *args) \ { \ TYPE arg1, arg2; \ if (!PyArg_ParseTuple(args,PARSESTR, &arg1, &arg2)) return NULL; \ From python-checkins at python.org Tue May 11 01:30:25 2010 From: python-checkins at python.org (andrew.kuchling) Date: Tue, 11 May 2010 01:30:25 +0200 (CEST) Subject: [Python-checkins] r81075 - in python/branches/py3k: Modules/_cursesmodule.c Message-ID: <20100510233025.5BDE7EB9C@mail.python.org> Author: andrew.kuchling Date: Tue May 11 01:30:25 2010 New Revision: 81075 Log: Merged revisions 81073 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r81073 | andrew.kuchling | 2010-05-10 19:27:01 -0400 (Mon, 10 May 2010) | 1 line Use ';' after initialization macros to avoid confusing re-indenters ........ Modified: python/branches/py3k/ (props changed) python/branches/py3k/Modules/_cursesmodule.c Modified: python/branches/py3k/Modules/_cursesmodule.c ============================================================================== --- python/branches/py3k/Modules/_cursesmodule.c (original) +++ python/branches/py3k/Modules/_cursesmodule.c Tue May 11 01:30:25 2010 @@ -1748,8 +1748,8 @@ { short color,r,g,b; - PyCursesInitialised - PyCursesInitialisedColor + PyCursesInitialised; + PyCursesInitialisedColor; if (!PyArg_ParseTuple(args, "h:color_content", &color)) return NULL; @@ -1767,8 +1767,8 @@ { int n; - PyCursesInitialised - PyCursesInitialisedColor + PyCursesInitialised; + PyCursesInitialisedColor; if (!PyArg_ParseTuple(args, "i:color_pair", &n)) return NULL; return PyLong_FromLong((long) (n << 8)); @@ -1779,7 +1779,7 @@ { int vis,erg; - PyCursesInitialised + PyCursesInitialised; if (!PyArg_ParseTuple(args, "i:curs_set", &vis)) return NULL; @@ -1794,7 +1794,7 @@ { int ms; - PyCursesInitialised + PyCursesInitialised; if (!PyArg_ParseTuple(args, "i:delay_output", &ms)) return NULL; @@ -1806,7 +1806,7 @@ { char ch; - PyCursesInitialised + PyCursesInitialised; ch = erasechar(); @@ -1819,7 +1819,7 @@ int x = 0; int y = 0; - PyCursesInitialised + PyCursesInitialised; getsyx(y, x); @@ -1833,7 +1833,7 @@ int rtn; MEVENT event; - PyCursesInitialised + PyCursesInitialised; rtn = getmouse( &event ); if (rtn == ERR) { @@ -1851,7 +1851,7 @@ { MEVENT event; - PyCursesInitialised + PyCursesInitialised; if (!PyArg_ParseTuple(args, "hiiil", &event.id, &event.x, &event.y, &event.z, @@ -1872,7 +1872,7 @@ size_t datalen; WINDOW *win; - PyCursesInitialised + PyCursesInitialised; strcpy(fn, "/tmp/py.curses.getwin.XXXXXX"); fd = mkstemp(fn); @@ -1923,7 +1923,7 @@ { unsigned char tenths; - PyCursesInitialised + PyCursesInitialised; if (!PyArg_ParseTuple(args, "b:halfdelay", &tenths)) return NULL; @@ -1936,7 +1936,7 @@ { int ch; - PyCursesInitialised + PyCursesInitialised; if (!PyArg_ParseTuple(args,"i",&ch)) return NULL; @@ -1954,8 +1954,8 @@ { short color, r, g, b; - PyCursesInitialised - PyCursesInitialisedColor + PyCursesInitialised; + PyCursesInitialisedColor; switch(PyTuple_Size(args)) { case 4: @@ -1974,8 +1974,8 @@ { short pair, f, b; - PyCursesInitialised - PyCursesInitialisedColor + PyCursesInitialised; + PyCursesInitialisedColor; if (PyTuple_Size(args) != 3) { PyErr_SetString(PyExc_TypeError, "init_pair requires 3 arguments"); @@ -2148,7 +2148,7 @@ { int ch; - PyCursesInitialised + PyCursesInitialised; switch(PyTuple_Size(args)) { case 1: @@ -2170,7 +2170,7 @@ int columns; int result; - PyCursesInitialised + PyCursesInitialised; if (!PyArg_ParseTuple(args,"ii:is_term_resized", &lines, &columns)) return NULL; @@ -2192,7 +2192,7 @@ const char *knp; int ch; - PyCursesInitialised + PyCursesInitialised; if (!PyArg_ParseTuple(args,"i",&ch)) return NULL; @@ -2221,7 +2221,7 @@ { int ch; - PyCursesInitialised + PyCursesInitialised; switch(PyTuple_Size(args)) { case 1: @@ -2240,7 +2240,7 @@ PyCurses_MouseInterval(PyObject *self, PyObject *args) { int interval; - PyCursesInitialised + PyCursesInitialised; if (!PyArg_ParseTuple(args,"i;interval",&interval)) return NULL; @@ -2253,7 +2253,7 @@ int newmask; mmask_t oldmask, availmask; - PyCursesInitialised + PyCursesInitialised; if (!PyArg_ParseTuple(args,"i;mousemask",&newmask)) return NULL; availmask = mousemask(newmask, &oldmask); @@ -2266,7 +2266,7 @@ { int ms; - PyCursesInitialised + PyCursesInitialised; if (!PyArg_ParseTuple(args, "i;ms", &ms)) return NULL; return Py_BuildValue("i", napms(ms)); @@ -2279,7 +2279,7 @@ WINDOW *win; int nlines, ncols; - PyCursesInitialised + PyCursesInitialised; if (!PyArg_ParseTuple(args,"ii;nlines,ncols",&nlines,&ncols)) return NULL; @@ -2299,7 +2299,7 @@ WINDOW *win; int nlines, ncols, begin_y=0, begin_x=0; - PyCursesInitialised + PyCursesInitialised; switch (PyTuple_Size(args)) { case 2: @@ -2330,8 +2330,8 @@ { short pair,f,b; - PyCursesInitialised - PyCursesInitialisedColor + PyCursesInitialised; + PyCursesInitialisedColor; switch(PyTuple_Size(args)) { case 1: @@ -2356,8 +2356,8 @@ { int n; - PyCursesInitialised - PyCursesInitialisedColor + PyCursesInitialised; + PyCursesInitialisedColor; switch(PyTuple_Size(args)) { case 1: @@ -2386,7 +2386,7 @@ { int flag = 0; - PyCursesInitialised + PyCursesInitialised; switch(PyTuple_Size(args)) { case 0: @@ -2462,7 +2462,7 @@ int columns; PyObject *result; - PyCursesInitialised + PyCursesInitialised; if (!PyArg_ParseTuple(args,"ii:resizeterm", &lines, &columns)) return NULL; @@ -2486,7 +2486,7 @@ PyObject *result; - PyCursesInitialised + PyCursesInitialised; if (!PyArg_ParseTuple(args,"ii:resize_term", &lines, &columns)) return NULL; @@ -2505,7 +2505,7 @@ { int y,x; - PyCursesInitialised + PyCursesInitialised; if (PyTuple_Size(args)!=2) { PyErr_SetString(PyExc_TypeError, "setsyx requires 2 arguments"); @@ -2526,7 +2526,7 @@ int code; PyObject *c, *cp; - PyCursesInitialised + PyCursesInitialised; code = start_color(); if (code != ERR) { @@ -2618,7 +2618,7 @@ { int fd; - PyCursesInitialised + PyCursesInitialised; if (!PyArg_ParseTuple(args,"i;fd",&fd)) return NULL; @@ -2631,7 +2631,7 @@ PyObject *temp; chtype ch; - PyCursesInitialised + PyCursesInitialised; if (!PyArg_ParseTuple(args,"O;ch or int",&temp)) return NULL; @@ -2649,7 +2649,7 @@ PyObject *temp; chtype ch; - PyCursesInitialised + PyCursesInitialised; if (!PyArg_ParseTuple(args,"O;ch or int",&temp)) return NULL; @@ -2686,8 +2686,8 @@ { int code; - PyCursesInitialised - PyCursesInitialisedColor + PyCursesInitialised; + PyCursesInitialisedColor; code = use_default_colors(); if (code != ERR) { From python-checkins at python.org Tue May 11 02:07:48 2010 From: python-checkins at python.org (benjamin.peterson) Date: Tue, 11 May 2010 02:07:48 +0200 (CEST) Subject: [Python-checkins] r81076 - python/branches/py3k/Lib/unittest/case.py Message-ID: <20100511000748.F21D1EE981@mail.python.org> Author: benjamin.peterson Date: Tue May 11 02:07:48 2010 New Revision: 81076 Log: remove now useless __ne__ Modified: python/branches/py3k/Lib/unittest/case.py Modified: python/branches/py3k/Lib/unittest/case.py ============================================================================== --- python/branches/py3k/Lib/unittest/case.py (original) +++ python/branches/py3k/Lib/unittest/case.py Tue May 11 02:07:48 2010 @@ -264,9 +264,6 @@ return self._testMethodName == other._testMethodName - def __ne__(self, other): - return not self == other - def __hash__(self): return hash((type(self), self._testMethodName)) From python-checkins at python.org Tue May 11 10:55:06 2010 From: python-checkins at python.org (mark.dickinson) Date: Tue, 11 May 2010 10:55:06 +0200 (CEST) Subject: [Python-checkins] r81077 - in python/trunk: configure configure.in Message-ID: <20100511085506.AD5A7EE9CE@mail.python.org> Author: mark.dickinson Date: Tue May 11 10:55:06 2010 New Revision: 81077 Log: Issue #8510: Remove nested 'main' functions (causing failure) in 3 configure tests; remove some unnecessary '#include "confdefs.h"' lines. Thanks Roumen Petrov. Modified: python/trunk/configure python/trunk/configure.in Modified: python/trunk/configure ============================================================================== --- python/trunk/configure (original) +++ python/trunk/configure Tue May 11 10:55:06 2010 @@ -1,5 +1,5 @@ #! /bin/sh -# From configure.in Revision: 80970 . +# From configure.in Revision: 81004 . # Guess values for system-dependent variables and create Makefiles. # Generated by GNU Autoconf 2.65 for python 2.7. # @@ -5410,7 +5410,7 @@ int main () { -int main() { return 0; } + ; return 0; } @@ -5602,7 +5602,7 @@ int main () { -int main() { return 0; } + ; return 0; } @@ -5644,7 +5644,7 @@ int main () { -int main() { return 0; } + ; return 0; } @@ -9731,7 +9731,6 @@ cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ -#include "confdefs.h" #include int @@ -9760,7 +9759,6 @@ cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ -#include "confdefs.h" #include int @@ -9789,7 +9787,6 @@ cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ -#include "confdefs.h" #include int @@ -10109,7 +10106,6 @@ cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ -#include "confdefs.h" #include int @@ -10139,7 +10135,6 @@ cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ -#include "confdefs.h" #include #include #include @@ -10172,7 +10167,6 @@ cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ -#include "confdefs.h" #include #include #include @@ -10205,7 +10199,6 @@ cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ -#include "confdefs.h" #include #ifdef HAVE_GRP_H #include Modified: python/trunk/configure.in ============================================================================== --- python/trunk/configure.in (original) +++ python/trunk/configure.in Tue May 11 10:55:06 2010 @@ -979,7 +979,7 @@ CC="$CC -fno-strict-aliasing" AC_CACHE_VAL(ac_cv_no_strict_aliasing_ok, AC_COMPILE_IFELSE( - [AC_LANG_PROGRAM([[]], [[int main() { return 0; }]])], + [AC_LANG_PROGRAM([[]], [[]])], [ac_cv_no_strict_aliasing_ok=yes], [ac_cv_no_strict_aliasing_ok=no])) CC="$ac_save_cc" @@ -1150,7 +1150,7 @@ [ac_save_cc="$CC" CC="$CC -OPT:Olimit=0" AC_COMPILE_IFELSE( - [AC_LANG_PROGRAM([[]], [[int main() { return 0; }]])], + [AC_LANG_PROGRAM([[]], [[]])], [ac_cv_opt_olimit_ok=yes], [ac_cv_opt_olimit_ok=no] ) @@ -1173,7 +1173,7 @@ [ac_save_cc="$CC" CC="$CC -Olimit 1500" AC_COMPILE_IFELSE( - [AC_LANG_PROGRAM([[]], [[int main() { return 0; }]])], + [AC_LANG_PROGRAM([[]], [[]])], [ac_cv_olimit_ok=yes], [ac_cv_olimit_ok=no] ) @@ -2781,7 +2781,6 @@ AC_MSG_CHECKING(for ctermid_r) AC_COMPILE_IFELSE([AC_LANG_PROGRAM([[ -#include "confdefs.h" #include ]], [[void* p = ctermid_r]])], [AC_DEFINE(HAVE_CTERMID_R, 1, Define if you have the 'ctermid_r' function.) @@ -2791,7 +2790,6 @@ AC_MSG_CHECKING(for flock) AC_COMPILE_IFELSE([AC_LANG_PROGRAM([[ -#include "confdefs.h" #include ]], [[void* p = flock]])], [AC_DEFINE(HAVE_FLOCK, 1, Define if you have the 'flock' function.) @@ -2801,7 +2799,6 @@ AC_MSG_CHECKING(for getpagesize) AC_COMPILE_IFELSE([AC_LANG_PROGRAM([[ -#include "confdefs.h" #include ]], [[void* p = getpagesize]])], [AC_DEFINE(HAVE_GETPAGESIZE, 1, Define if you have the 'getpagesize' function.) @@ -2892,7 +2889,6 @@ AC_MSG_CHECKING(for hstrerror) AC_LINK_IFELSE([AC_LANG_PROGRAM([[ -#include "confdefs.h" #include ]], [[void* p = hstrerror; hstrerror(0)]])], [AC_DEFINE(HAVE_HSTRERROR, 1, Define if you have the 'hstrerror' function.) @@ -2902,7 +2898,6 @@ AC_MSG_CHECKING(for inet_aton) AC_LINK_IFELSE([AC_LANG_PROGRAM([[ -#include "confdefs.h" #include #include #include @@ -2915,7 +2910,6 @@ AC_MSG_CHECKING(for inet_pton) AC_COMPILE_IFELSE([AC_LANG_PROGRAM([[ -#include "confdefs.h" #include #include #include @@ -2929,7 +2923,6 @@ # On some systems, setgroups is in unistd.h, on others, in grp.h AC_MSG_CHECKING(for setgroups) AC_COMPILE_IFELSE([AC_LANG_PROGRAM([[ -#include "confdefs.h" #include #ifdef HAVE_GRP_H #include From python-checkins at python.org Tue May 11 11:23:08 2010 From: python-checkins at python.org (mark.dickinson) Date: Tue, 11 May 2010 11:23:08 +0200 (CEST) Subject: [Python-checkins] r81078 - in python/branches/py3k: configure configure.in Message-ID: <20100511092308.7D44BEE9C5@mail.python.org> Author: mark.dickinson Date: Tue May 11 11:23:07 2010 New Revision: 81078 Log: Recorded merge of revisions 81077 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r81077 | mark.dickinson | 2010-05-11 09:55:06 +0100 (Tue, 11 May 2010) | 3 lines Issue #8510: Remove nested 'main' functions (causing failure) in 3 configure tests; remove some unnecessary '#include "confdefs.h"' lines. Thanks Roumen Petrov. ........ Modified: python/branches/py3k/ (props changed) python/branches/py3k/configure python/branches/py3k/configure.in Modified: python/branches/py3k/configure ============================================================================== --- python/branches/py3k/configure (original) +++ python/branches/py3k/configure Tue May 11 11:23:07 2010 @@ -1,5 +1,5 @@ #! /bin/sh -# From configure.in Revision: 80728 . +# From configure.in Revision: 80834 . # Guess values for system-dependent variables and create Makefiles. # Generated by GNU Autoconf 2.65 for python 3.2. # @@ -5337,7 +5337,7 @@ int main () { -int main() { return 0; } + ; return 0; } @@ -5350,11 +5350,11 @@ cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ - + void f(int **x) {} int main () { -void f(int **x) {} int main() { double *x; f((int **) &x); return 0; } +double *x; f((int **) &x); ; return 0; } @@ -5557,7 +5557,7 @@ int main () { -int main() { return 0; } + ; return 0; } @@ -5599,7 +5599,7 @@ int main () { -int main() { return 0; } + ; return 0; } @@ -9548,7 +9548,6 @@ cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ -#include "confdefs.h" #include int @@ -9577,7 +9576,6 @@ cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ -#include "confdefs.h" #include int @@ -9606,7 +9604,6 @@ cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ -#include "confdefs.h" #include int @@ -9926,7 +9923,6 @@ cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ -#include "confdefs.h" #include int @@ -9956,7 +9952,6 @@ cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ -#include "confdefs.h" #include #include #include @@ -9989,7 +9984,6 @@ cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ -#include "confdefs.h" #include #include #include @@ -10022,7 +10016,6 @@ cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ -#include "confdefs.h" #include #ifdef HAVE_GRP_H #include Modified: python/branches/py3k/configure.in ============================================================================== --- python/branches/py3k/configure.in (original) +++ python/branches/py3k/configure.in Tue May 11 11:23:07 2010 @@ -916,14 +916,14 @@ AC_CACHE_VAL(ac_cv_no_strict_aliasing, AC_COMPILE_IFELSE( [ - AC_LANG_PROGRAM([[]], [[int main() { return 0; }]]) + AC_LANG_PROGRAM([[]], [[]]) ],[ CC="$ac_save_cc -fstrict-aliasing" CFLAGS="$CFLAGS -Werror -Wstrict-aliasing" AC_COMPILE_IFELSE( [ - AC_LANG_PROGRAM([[]], - [[void f(int **x) {} int main() { double *x; f((int **) &x); return 0; }]]) + AC_LANG_PROGRAM([[void f(int **x) {}]], + [[double *x; f((int **) &x);]]) ],[ ac_cv_no_strict_aliasing=no ],[ @@ -1099,7 +1099,7 @@ [ac_save_cc="$CC" CC="$CC -OPT:Olimit=0" AC_COMPILE_IFELSE( - [AC_LANG_PROGRAM([[]], [[int main() { return 0; }]])], + [AC_LANG_PROGRAM([[]], [[]])], [ac_cv_opt_olimit_ok=yes], [ac_cv_opt_olimit_ok=no] ) @@ -1122,7 +1122,7 @@ [ac_save_cc="$CC" CC="$CC -Olimit 1500" AC_COMPILE_IFELSE( - [AC_LANG_PROGRAM([[]], [[int main() { return 0; }]])], + [AC_LANG_PROGRAM([[]], [[]])], [ac_cv_olimit_ok=yes], [ac_cv_olimit_ok=no] ) @@ -2663,7 +2663,6 @@ AC_MSG_CHECKING(for ctermid_r) AC_COMPILE_IFELSE([AC_LANG_PROGRAM([[ -#include "confdefs.h" #include ]], [[void* p = ctermid_r]])], [AC_DEFINE(HAVE_CTERMID_R, 1, Define if you have the 'ctermid_r' function.) @@ -2673,7 +2672,6 @@ AC_MSG_CHECKING(for flock) AC_COMPILE_IFELSE([AC_LANG_PROGRAM([[ -#include "confdefs.h" #include ]], [[void* p = flock]])], [AC_DEFINE(HAVE_FLOCK, 1, Define if you have the 'flock' function.) @@ -2683,7 +2681,6 @@ AC_MSG_CHECKING(for getpagesize) AC_COMPILE_IFELSE([AC_LANG_PROGRAM([[ -#include "confdefs.h" #include ]], [[void* p = getpagesize]])], [AC_DEFINE(HAVE_GETPAGESIZE, 1, Define if you have the 'getpagesize' function.) @@ -2774,7 +2771,6 @@ AC_MSG_CHECKING(for hstrerror) AC_LINK_IFELSE([AC_LANG_PROGRAM([[ -#include "confdefs.h" #include ]], [[void* p = hstrerror; hstrerror(0)]])], [AC_DEFINE(HAVE_HSTRERROR, 1, Define if you have the 'hstrerror' function.) @@ -2784,7 +2780,6 @@ AC_MSG_CHECKING(for inet_aton) AC_LINK_IFELSE([AC_LANG_PROGRAM([[ -#include "confdefs.h" #include #include #include @@ -2797,7 +2792,6 @@ AC_MSG_CHECKING(for inet_pton) AC_COMPILE_IFELSE([AC_LANG_PROGRAM([[ -#include "confdefs.h" #include #include #include @@ -2811,7 +2805,6 @@ # On some systems, setgroups is in unistd.h, on others, in grp.h AC_MSG_CHECKING(for setgroups) AC_COMPILE_IFELSE([AC_LANG_PROGRAM([[ -#include "confdefs.h" #include #ifdef HAVE_GRP_H #include From python-checkins at python.org Tue May 11 15:05:30 2010 From: python-checkins at python.org (mark.dickinson) Date: Tue, 11 May 2010 15:05:30 +0200 (CEST) Subject: [Python-checkins] r81079 - python/trunk/Modules/audioop.c Message-ID: <20100511130530.98F66EE995@mail.python.org> Author: mark.dickinson Date: Tue May 11 15:05:30 2010 New Revision: 81079 Log: Issue #8674: fix another bogus overflow check in audioop module. Modified: python/trunk/Modules/audioop.c Modified: python/trunk/Modules/audioop.c ============================================================================== --- python/trunk/Modules/audioop.c (original) +++ python/trunk/Modules/audioop.c Tue May 11 15:05:30 2010 @@ -1153,25 +1153,16 @@ ceiling(len*outrate/inrate) output frames, and each frame requires bytes_per_frame bytes. Computing this without spurious overflow is the challenge; we can - settle for a reasonable upper bound, though. */ - int ceiling; /* the number of output frames */ - int nbytes; /* the number of output bytes needed */ - int q = len / inrate; - /* Now len = q * inrate + r exactly (with r = len % inrate), - and this is less than q * inrate + inrate = (q+1)*inrate. - So a reasonable upper bound on len*outrate/inrate is - ((q+1)*inrate)*outrate/inrate = - (q+1)*outrate. - */ - ceiling = (q+1) * outrate; - nbytes = ceiling * bytes_per_frame; - /* See whether anything overflowed; if not, get the space. */ - if (q+1 < 0 || - ceiling / outrate != q+1 || - nbytes / bytes_per_frame != ceiling) + settle for a reasonable upper bound, though, in this + case ceiling(len/inrate) * outrate. */ + + /* compute ceiling(len/inrate) without overflow */ + int q = len > 0 ? 1 + (len - 1) / inrate : 0; + if (outrate > INT_MAX / q / bytes_per_frame) str = NULL; else - str = PyString_FromStringAndSize(NULL, nbytes); + str = PyString_FromStringAndSize(NULL, + q * outrate * bytes_per_frame); if (str == NULL) { PyErr_SetString(PyExc_MemoryError, From python-checkins at python.org Tue May 11 15:08:26 2010 From: python-checkins at python.org (mark.dickinson) Date: Tue, 11 May 2010 15:08:26 +0200 (CEST) Subject: [Python-checkins] r81080 - in python/branches/release26-maint: Modules/audioop.c Message-ID: <20100511130826.595E9E320@mail.python.org> Author: mark.dickinson Date: Tue May 11 15:08:26 2010 New Revision: 81080 Log: Merged revisions 81079 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r81079 | mark.dickinson | 2010-05-11 14:05:30 +0100 (Tue, 11 May 2010) | 1 line Issue #8674: fix another bogus overflow check in audioop module. ........ Modified: python/branches/release26-maint/ (props changed) python/branches/release26-maint/Modules/audioop.c Modified: python/branches/release26-maint/Modules/audioop.c ============================================================================== --- python/branches/release26-maint/Modules/audioop.c (original) +++ python/branches/release26-maint/Modules/audioop.c Tue May 11 15:08:26 2010 @@ -1155,25 +1155,16 @@ ceiling(len*outrate/inrate) output frames, and each frame requires bytes_per_frame bytes. Computing this without spurious overflow is the challenge; we can - settle for a reasonable upper bound, though. */ - int ceiling; /* the number of output frames */ - int nbytes; /* the number of output bytes needed */ - int q = len / inrate; - /* Now len = q * inrate + r exactly (with r = len % inrate), - and this is less than q * inrate + inrate = (q+1)*inrate. - So a reasonable upper bound on len*outrate/inrate is - ((q+1)*inrate)*outrate/inrate = - (q+1)*outrate. - */ - ceiling = (q+1) * outrate; - nbytes = ceiling * bytes_per_frame; - /* See whether anything overflowed; if not, get the space. */ - if (q+1 < 0 || - ceiling / outrate != q+1 || - nbytes / bytes_per_frame != ceiling) + settle for a reasonable upper bound, though, in this + case ceiling(len/inrate) * outrate. */ + + /* compute ceiling(len/inrate) without overflow */ + int q = len > 0 ? 1 + (len - 1) / inrate : 0; + if (outrate > INT_MAX / q / bytes_per_frame) str = NULL; else - str = PyString_FromStringAndSize(NULL, nbytes); + str = PyString_FromStringAndSize(NULL, + q * outrate * bytes_per_frame); if (str == NULL) { PyErr_SetString(PyExc_MemoryError, From python-checkins at python.org Tue May 11 15:09:58 2010 From: python-checkins at python.org (mark.dickinson) Date: Tue, 11 May 2010 15:09:58 +0200 (CEST) Subject: [Python-checkins] r81081 - in python/branches/py3k: Modules/audioop.c Message-ID: <20100511130958.6D899EE981@mail.python.org> Author: mark.dickinson Date: Tue May 11 15:09:58 2010 New Revision: 81081 Log: Merged revisions 81079 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r81079 | mark.dickinson | 2010-05-11 14:05:30 +0100 (Tue, 11 May 2010) | 1 line Issue #8674: fix another bogus overflow check in audioop module. ........ Modified: python/branches/py3k/ (props changed) python/branches/py3k/Modules/audioop.c Modified: python/branches/py3k/Modules/audioop.c ============================================================================== --- python/branches/py3k/Modules/audioop.c (original) +++ python/branches/py3k/Modules/audioop.c Tue May 11 15:09:58 2010 @@ -1160,25 +1160,16 @@ ceiling(len*outrate/inrate) output frames, and each frame requires bytes_per_frame bytes. Computing this without spurious overflow is the challenge; we can - settle for a reasonable upper bound, though. */ - int ceiling; /* the number of output frames */ - int nbytes; /* the number of output bytes needed */ - int q = len / inrate; - /* Now len = q * inrate + r exactly (with r = len % inrate), - and this is less than q * inrate + inrate = (q+1)*inrate. - So a reasonable upper bound on len*outrate/inrate is - ((q+1)*inrate)*outrate/inrate = - (q+1)*outrate. - */ - ceiling = (q+1) * outrate; - nbytes = ceiling * bytes_per_frame; - /* See whether anything overflowed; if not, get the space. */ - if (q+1 < 0 || - ceiling / outrate != q+1 || - nbytes / bytes_per_frame != ceiling) + settle for a reasonable upper bound, though, in this + case ceiling(len/inrate) * outrate. */ + + /* compute ceiling(len/inrate) without overflow */ + int q = len > 0 ? 1 + (len - 1) / inrate : 0; + if (outrate > INT_MAX / q / bytes_per_frame) str = NULL; else - str = PyBytes_FromStringAndSize(NULL, nbytes); + str = PyBytes_FromStringAndSize(NULL, + q * outrate * bytes_per_frame); if (str == NULL) { PyErr_SetString(PyExc_MemoryError, From python-checkins at python.org Tue May 11 15:11:13 2010 From: python-checkins at python.org (mark.dickinson) Date: Tue, 11 May 2010 15:11:13 +0200 (CEST) Subject: [Python-checkins] r81082 - in python/branches/release31-maint: Modules/audioop.c Message-ID: <20100511131113.0A006EC3E@mail.python.org> Author: mark.dickinson Date: Tue May 11 15:11:12 2010 New Revision: 81082 Log: Merged revisions 81081 via svnmerge from svn+ssh://pythondev at svn.python.org/python/branches/py3k ................ r81081 | mark.dickinson | 2010-05-11 14:09:58 +0100 (Tue, 11 May 2010) | 9 lines Merged revisions 81079 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r81079 | mark.dickinson | 2010-05-11 14:05:30 +0100 (Tue, 11 May 2010) | 1 line Issue #8674: fix another bogus overflow check in audioop module. ........ ................ Modified: python/branches/release31-maint/ (props changed) python/branches/release31-maint/Modules/audioop.c Modified: python/branches/release31-maint/Modules/audioop.c ============================================================================== --- python/branches/release31-maint/Modules/audioop.c (original) +++ python/branches/release31-maint/Modules/audioop.c Tue May 11 15:11:12 2010 @@ -1160,25 +1160,16 @@ ceiling(len*outrate/inrate) output frames, and each frame requires bytes_per_frame bytes. Computing this without spurious overflow is the challenge; we can - settle for a reasonable upper bound, though. */ - int ceiling; /* the number of output frames */ - int nbytes; /* the number of output bytes needed */ - int q = len / inrate; - /* Now len = q * inrate + r exactly (with r = len % inrate), - and this is less than q * inrate + inrate = (q+1)*inrate. - So a reasonable upper bound on len*outrate/inrate is - ((q+1)*inrate)*outrate/inrate = - (q+1)*outrate. - */ - ceiling = (q+1) * outrate; - nbytes = ceiling * bytes_per_frame; - /* See whether anything overflowed; if not, get the space. */ - if (q+1 < 0 || - ceiling / outrate != q+1 || - nbytes / bytes_per_frame != ceiling) + settle for a reasonable upper bound, though, in this + case ceiling(len/inrate) * outrate. */ + + /* compute ceiling(len/inrate) without overflow */ + int q = len > 0 ? 1 + (len - 1) / inrate : 0; + if (outrate > INT_MAX / q / bytes_per_frame) str = NULL; else - str = PyBytes_FromStringAndSize(NULL, nbytes); + str = PyBytes_FromStringAndSize(NULL, + q * outrate * bytes_per_frame); if (str == NULL) { PyErr_SetString(PyExc_MemoryError, From python-checkins at python.org Tue May 11 15:34:35 2010 From: python-checkins at python.org (mark.dickinson) Date: Tue, 11 May 2010 15:34:35 +0200 (CEST) Subject: [Python-checkins] r81083 - in python/branches/py3k: Misc/NEWS Modules/audioop.c Message-ID: <20100511133435.C11B4F10A@mail.python.org> Author: mark.dickinson Date: Tue May 11 15:34:35 2010 New Revision: 81083 Log: Issue #8657: Make the audioop module PY_SSIZE_T_CLEAN. Modified: python/branches/py3k/Misc/NEWS python/branches/py3k/Modules/audioop.c Modified: python/branches/py3k/Misc/NEWS ============================================================================== --- python/branches/py3k/Misc/NEWS (original) +++ python/branches/py3k/Misc/NEWS Tue May 11 15:34:35 2010 @@ -351,6 +351,9 @@ Library ------- +- The audioop module now supports sound fragments of length greater + than 2**31 bytes on 64-bit machines, and is PY_SSIZE_T_CLEAN. + - Issue #4972: Add support for the context manager protocol to the ftplib.FTP class. Modified: python/branches/py3k/Modules/audioop.c ============================================================================== --- python/branches/py3k/Modules/audioop.c (original) +++ python/branches/py3k/Modules/audioop.c Tue May 11 15:34:35 2010 @@ -1,6 +1,8 @@ /* audioopmodule - Module to detect peak values in arrays */ +#define PY_SSIZE_T_CLEAN + #include "Python.h" #if SIZEOF_INT == 4 @@ -299,10 +301,10 @@ audioop_getsample(PyObject *self, PyObject *args) { signed char *cp; - int len, size, val = 0; - int i; + Py_ssize_t len, i; + int size, val = 0; - if ( !PyArg_ParseTuple(args, "s#ii:getsample", &cp, &len, &size, &i) ) + if ( !PyArg_ParseTuple(args, "s#in:getsample", &cp, &len, &size, &i) ) return 0; if ( size != 1 && size != 2 && size != 4 ) { PyErr_SetString(AudioopError, "Size should be 1, 2 or 4"); @@ -322,8 +324,8 @@ audioop_max(PyObject *self, PyObject *args) { signed char *cp; - int len, size, val = 0; - int i; + Py_ssize_t len, i; + int size, val = 0; int max = 0; if ( !PyArg_ParseTuple(args, "s#i:max", &cp, &len, &size) ) @@ -346,8 +348,8 @@ audioop_minmax(PyObject *self, PyObject *args) { signed char *cp; - int len, size, val = 0; - int i; + Py_ssize_t len, i; + int size, val = 0; int min = 0x7fffffff, max = -0x7fffffff; if (!PyArg_ParseTuple(args, "s#i:minmax", &cp, &len, &size)) @@ -370,8 +372,8 @@ audioop_avg(PyObject *self, PyObject *args) { signed char *cp; - int len, size, val = 0; - int i; + Py_ssize_t len, i; + int size, val = 0; double avg = 0.0; if ( !PyArg_ParseTuple(args, "s#i:avg", &cp, &len, &size) ) @@ -397,8 +399,8 @@ audioop_rms(PyObject *self, PyObject *args) { signed char *cp; - int len, size, val = 0; - int i; + Py_ssize_t len, i; + int size, val = 0; double sum_squares = 0.0; if ( !PyArg_ParseTuple(args, "s#i:rms", &cp, &len, &size) ) @@ -420,9 +422,9 @@ return PyLong_FromLong(val); } -static double _sum2(short *a, short *b, int len) +static double _sum2(short *a, short *b, Py_ssize_t len) { - int i; + Py_ssize_t i; double sum = 0.0; for( i=0; i INT_MAX/2) { + if (len > PY_SSIZE_T_MAX/2) { PyErr_SetString(PyExc_MemoryError, "not enough memory for output buffer"); return 0; @@ -893,9 +896,9 @@ audioop_add(PyObject *self, PyObject *args) { signed char *cp1, *cp2, *ncp; - int len1, len2, size, val1 = 0, val2 = 0, maxval, newval; + Py_ssize_t len1, len2, i; + int size, val1 = 0, val2 = 0, maxval, newval; PyObject *rv; - int i; if ( !PyArg_ParseTuple(args, "s#s#i:add", &cp1, &len1, &cp2, &len2, &size ) ) @@ -946,9 +949,9 @@ audioop_bias(PyObject *self, PyObject *args) { signed char *cp, *ncp; - int len, size, val = 0; + Py_ssize_t len, i; + int size, val = 0; PyObject *rv; - int i; int bias; if ( !PyArg_ParseTuple(args, "s#ii:bias", @@ -983,9 +986,9 @@ { signed char *cp; unsigned char *ncp; - int len, size, val = 0; + Py_ssize_t len, i, j; + int size, val = 0; PyObject *rv; - int i, j; if ( !PyArg_ParseTuple(args, "s#i:reverse", &cp, &len, &size) ) @@ -1020,9 +1023,9 @@ { signed char *cp; unsigned char *ncp; - int len, size, size2, val = 0; + Py_ssize_t len, i, j; + int size, size2, val = 0; PyObject *rv; - int i, j; if ( !PyArg_ParseTuple(args, "s#ii:lin2lin", &cp, &len, &size, &size2) ) @@ -1034,7 +1037,7 @@ return 0; } - if (len/size > INT_MAX/size2) { + if (len/size > PY_SSIZE_T_MAX/size2) { PyErr_SetString(PyExc_MemoryError, "not enough memory for output buffer"); return 0; @@ -1071,7 +1074,8 @@ audioop_ratecv(PyObject *self, PyObject *args) { char *cp, *ncp; - int len, size, nchannels, inrate, outrate, weightA, weightB; + Py_ssize_t len; + int size, nchannels, inrate, outrate, weightA, weightB; int chan, d, *prev_i, *cur_i, cur_o; PyObject *state, *samps, *str, *rv = NULL; int bytes_per_frame; @@ -1164,8 +1168,8 @@ case ceiling(len/inrate) * outrate. */ /* compute ceiling(len/inrate) without overflow */ - int q = len > 0 ? 1 + (len - 1) / inrate : 0; - if (outrate > INT_MAX / q / bytes_per_frame) + Py_ssize_t q = len > 0 ? 1 + (len - 1) / inrate : 0; + if (outrate > PY_SSIZE_T_MAX / q / bytes_per_frame) str = NULL; else str = PyBytes_FromStringAndSize(NULL, @@ -1194,7 +1198,7 @@ goto exit; /* We have checked before that the length * of the string fits into int. */ - len = (int)(ncp - PyBytes_AsString(str)); + len = (Py_ssize_t)(ncp - PyBytes_AsString(str)); rv = PyBytes_FromStringAndSize (PyBytes_AsString(str), len); Py_DECREF(str); @@ -1253,9 +1257,9 @@ { signed char *cp; unsigned char *ncp; - int len, size, val = 0; + Py_ssize_t len, i; + int size, val = 0; PyObject *rv; - int i; if ( !PyArg_ParseTuple(args, "s#i:lin2ulaw", &cp, &len, &size) ) @@ -1287,9 +1291,9 @@ unsigned char *cp; unsigned char cval; signed char *ncp; - int len, size, val; + Py_ssize_t len, i; + int size, val; PyObject *rv; - int i; if ( !PyArg_ParseTuple(args, "s#i:ulaw2lin", &cp, &len, &size) ) @@ -1300,7 +1304,7 @@ return 0; } - if (len > INT_MAX/size) { + if (len > PY_SSIZE_T_MAX/size) { PyErr_SetString(PyExc_MemoryError, "not enough memory for output buffer"); return 0; @@ -1326,9 +1330,9 @@ { signed char *cp; unsigned char *ncp; - int len, size, val = 0; + Py_ssize_t len, i; + int size, val = 0; PyObject *rv; - int i; if ( !PyArg_ParseTuple(args, "s#i:lin2alaw", &cp, &len, &size) ) @@ -1360,9 +1364,9 @@ unsigned char *cp; unsigned char cval; signed char *ncp; - int len, size, val; + Py_ssize_t len, i; + int size, val; PyObject *rv; - int i; if ( !PyArg_ParseTuple(args, "s#i:alaw2lin", &cp, &len, &size) ) @@ -1373,7 +1377,7 @@ return 0; } - if (len > INT_MAX/size) { + if (len > PY_SSIZE_T_MAX/size) { PyErr_SetString(PyExc_MemoryError, "not enough memory for output buffer"); return 0; @@ -1399,10 +1403,11 @@ { signed char *cp; signed char *ncp; - int len, size, val = 0, step, valpred, delta, + Py_ssize_t len, i; + int size, val = 0, step, valpred, delta, index, sign, vpdiff, diff; PyObject *rv, *state, *str; - int i, outputbuffer = 0, bufferstep; + int outputbuffer = 0, bufferstep; if ( !PyArg_ParseTuple(args, "s#iO:lin2adpcm", &cp, &len, &size, &state) ) @@ -1508,9 +1513,10 @@ { signed char *cp; signed char *ncp; - int len, size, valpred, step, delta, index, sign, vpdiff; + Py_ssize_t len, i; + int size, valpred, step, delta, index, sign, vpdiff; PyObject *rv, *str, *state; - int i, inputbuffer = 0, bufferstep; + int inputbuffer = 0, bufferstep; if ( !PyArg_ParseTuple(args, "s#iO:adpcm2lin", &cp, &len, &size, &state) ) @@ -1530,7 +1536,7 @@ } else if ( !PyArg_ParseTuple(state, "ii", &valpred, &index) ) return 0; - if (len > (INT_MAX/2)/size) { + if (len > (PY_SSIZE_T_MAX/2)/size) { PyErr_SetString(PyExc_MemoryError, "not enough memory for output buffer"); return 0; From python-checkins at python.org Tue May 11 16:00:04 2010 From: python-checkins at python.org (giampaolo.rodola) Date: Tue, 11 May 2010 16:00:04 +0200 (CEST) Subject: [Python-checkins] r81084 - python/branches/py3k/Misc/maintainers.rst Message-ID: <20100511140004.7CA2EEE9B0@mail.python.org> Author: giampaolo.rodola Date: Tue May 11 16:00:04 2010 New Revision: 81084 Log: adding myself to 'testing' interest area of maintainers.rst file Modified: python/branches/py3k/Misc/maintainers.rst Modified: python/branches/py3k/Misc/maintainers.rst ============================================================================== --- python/branches/py3k/Misc/maintainers.rst (original) +++ python/branches/py3k/Misc/maintainers.rst Tue May 11 16:00:04 2010 @@ -287,7 +287,7 @@ gvanrossum, anthonybaxter str.format eric.smith time and dates lemburg -testing michael.foord, pitrou +testing michael.foord, pitrou, giampaolo.rodola threads tracker unicode lemburg, ezio.melotti, haypo From python-checkins at python.org Tue May 11 18:35:53 2010 From: python-checkins at python.org (tarek.ziade) Date: Tue, 11 May 2010 18:35:53 +0200 Subject: [Python-checkins] distutils2: started distutils2.converter - a lib2to3 based refactoring tool that cna be Message-ID: tarek.ziade pushed 1d2e757f5a7a to distutils2: http://hg.python.org/distutils2/rev/1d2e757f5a7a changeset: 134:1d2e757f5a7a tag: tip user: Tarek Ziade date: Tue May 11 18:35:45 2010 +0200 summary: started distutils2.converter - a lib2to3 based refactoring tool that cna be used to refactor a distutils or setuptools project into a distutils2 one files: src/distutils2/converter/__init__.py, src/distutils2/converter/fixers/__init__.py, src/distutils2/converter/fixers/fix_imports.py, src/distutils2/converter/refactor.py, src/distutils2/tests/test_converter.py diff --git a/src/distutils2/converter/__init__.py b/src/distutils2/converter/__init__.py new file mode 100644 --- /dev/null +++ b/src/distutils2/converter/__init__.py @@ -0,0 +1,8 @@ +"""distutils2.converter + +This package provide a refactoring tool to transform a +setuptools or distutils project into a distutils2 one. +""" + +from distutils2.converter.refactor import DistutilsRefactoringTool + diff --git a/src/distutils2/converter/fixers/__init__.py b/src/distutils2/converter/fixers/__init__.py new file mode 100644 --- /dev/null +++ b/src/distutils2/converter/fixers/__init__.py @@ -0,0 +1,4 @@ +"""distutils2.converter.fixers + +Contains all fixers for the converter. +""" diff --git a/src/distutils2/converter/fixers/fix_imports.py b/src/distutils2/converter/fixers/fix_imports.py new file mode 100644 --- /dev/null +++ b/src/distutils2/converter/fixers/fix_imports.py @@ -0,0 +1,29 @@ +"""distutils2.converter.fixers.fix_imports + +Fixer for import statements in setup.py +""" +from lib2to3.fixer_base import BaseFix +from lib2to3.fixer_util import FromImport, syms, token + +class FixImports(BaseFix): + """Makes sure all import in setup.py are translated""" + + PATTERN = """ + import_from< 'from' imp=any 'import' ['('] any [')'] > + | + import_name< 'import' imp=any > + """ + + def transform(self, node, results): + imp = results['imp'] + if node.type != syms.import_from: + return + + while not hasattr(imp, 'value'): + imp = imp.children[0] + + if imp.value == 'distutils': + imp.value = 'distutils2' + imp.changed() + return node + diff --git a/src/distutils2/converter/refactor.py b/src/distutils2/converter/refactor.py new file mode 100644 --- /dev/null +++ b/src/distutils2/converter/refactor.py @@ -0,0 +1,17 @@ +"""distutils2.converter.refactor + +Provides DistutilsRefactoringTool, a class that register fixers used +to refactor distutils or setuptools packages into distutils2 ones. +""" +from lib2to3.refactor import RefactoringTool + +_DISTUTILS_FIXERS = ['distutils2.converter.fixers.fix_imports'] + +class DistutilsRefactoringTool(RefactoringTool): + + def __init__(self, fixer_names=_DISTUTILS_FIXERS, options=None, + explicit=None): + + super(DistutilsRefactoringTool, self).__init__(fixer_names, options, + explicit) + diff --git a/src/distutils2/tests/test_converter.py b/src/distutils2/tests/test_converter.py new file mode 100644 --- /dev/null +++ b/src/distutils2/tests/test_converter.py @@ -0,0 +1,28 @@ +"""Tests for distutils.converter.""" +import unittest2 +from distutils2.converter import DistutilsRefactoringTool + +_ORIGINAL = """\ +from distutils.core import setup + +setup(name='Foo') +""" + +_WANTED = """\ +from distutils2.core import setup + +setup(name='Foo') +""" +class ConverterTestCase(unittest2.TestCase): + + def test_import(self): + # simplest case: renaming distutils import in setup.py + ref = DistutilsRefactoringTool() + res = ref.refactor_string(_ORIGINAL, 'setup.py') + self.assertEquals(str(res), _WANTED) + +def test_suite(): + return unittest2.makeSuite(ConverterTestCase) + +if __name__ == '__main__': + run_unittest(test_suite()) -- Repository URL: http://hg.python.org/distutils2 From python-checkins at python.org Tue May 11 19:57:09 2010 From: python-checkins at python.org (mark.dickinson) Date: Tue, 11 May 2010 19:57:09 +0200 (CEST) Subject: [Python-checkins] r81085 - python/branches/py3k/Modules/_cursesmodule.c Message-ID: <20100511175709.BB2F2EE9C3@mail.python.org> Author: mark.dickinson Date: Tue May 11 19:57:09 2010 New Revision: 81085 Log: Issue #8677: Make curses module PY_SSIZE_T_CLEAN. Modified: python/branches/py3k/Modules/_cursesmodule.c Modified: python/branches/py3k/Modules/_cursesmodule.c ============================================================================== --- python/branches/py3k/Modules/_cursesmodule.c (original) +++ python/branches/py3k/Modules/_cursesmodule.c Tue May 11 19:57:09 2010 @@ -100,6 +100,8 @@ /* Includes */ +#define PY_SSIZE_T_CLEAN + #include "Python.h" @@ -1382,7 +1384,7 @@ fseek(fp, 0, 0); while (1) { char buf[BUFSIZ]; - int n = fread(buf, 1, BUFSIZ, fp); + Py_ssize_t n = fread(buf, 1, BUFSIZ, fp); if (n <= 0) break; Py_DECREF(res); From python-checkins at python.org Tue May 11 19:58:55 2010 From: python-checkins at python.org (collin.winter) Date: Tue, 11 May 2010 19:58:55 +0200 (CEST) Subject: [Python-checkins] r81086 - in python/branches/py3k-jit: Lib/unittest/case.py Misc/NEWS Misc/maintainers.rst Modules/_cursesmodule.c Modules/audioop.c configure configure.in Message-ID: <20100511175855.C7532EE8E@mail.python.org> Author: collin.winter Date: Tue May 11 19:58:55 2010 New Revision: 81086 Log: Merged revisions 81071,81074-81076,81078,81081,81083-81084 via svnmerge from svn+ssh://pythondev at svn.python.org/python/branches/py3k ................ r81071 | andrew.kuchling | 2010-05-10 16:14:26 -0700 (Mon, 10 May 2010) | 9 lines Merged revisions 81049 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r81049 | andrew.kuchling | 2010-05-10 13:18:25 -0400 (Mon, 10 May 2010) | 1 line Move { out of #if...#else block; this confuses Emacs' C-mode ........ ................ r81074 | andrew.kuchling | 2010-05-10 16:28:28 -0700 (Mon, 10 May 2010) | 9 lines Merged revisions 81072 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r81072 | andrew.kuchling | 2010-05-10 19:24:09 -0400 (Mon, 10 May 2010) | 1 line Break long line in macros ........ ................ r81075 | andrew.kuchling | 2010-05-10 16:30:25 -0700 (Mon, 10 May 2010) | 9 lines Merged revisions 81073 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r81073 | andrew.kuchling | 2010-05-10 19:27:01 -0400 (Mon, 10 May 2010) | 1 line Use ';' after initialization macros to avoid confusing re-indenters ........ ................ r81076 | benjamin.peterson | 2010-05-10 17:07:48 -0700 (Mon, 10 May 2010) | 1 line remove now useless __ne__ ................ r81078 | mark.dickinson | 2010-05-11 02:23:07 -0700 (Tue, 11 May 2010) | 10 lines Recorded merge of revisions 81077 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r81077 | mark.dickinson | 2010-05-11 09:55:06 +0100 (Tue, 11 May 2010) | 3 lines Issue #8510: Remove nested 'main' functions (causing failure) in 3 configure tests; remove some unnecessary '#include "confdefs.h"' lines. Thanks Roumen Petrov. ........ ................ r81081 | mark.dickinson | 2010-05-11 06:09:58 -0700 (Tue, 11 May 2010) | 9 lines Merged revisions 81079 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r81079 | mark.dickinson | 2010-05-11 14:05:30 +0100 (Tue, 11 May 2010) | 1 line Issue #8674: fix another bogus overflow check in audioop module. ........ ................ r81083 | mark.dickinson | 2010-05-11 06:34:35 -0700 (Tue, 11 May 2010) | 2 lines Issue #8657: Make the audioop module PY_SSIZE_T_CLEAN. ................ r81084 | giampaolo.rodola | 2010-05-11 07:00:04 -0700 (Tue, 11 May 2010) | 1 line adding myself to 'testing' interest area of maintainers.rst file ................ Modified: python/branches/py3k-jit/ (props changed) python/branches/py3k-jit/Lib/unittest/case.py python/branches/py3k-jit/Misc/NEWS python/branches/py3k-jit/Misc/maintainers.rst python/branches/py3k-jit/Modules/_cursesmodule.c python/branches/py3k-jit/Modules/audioop.c python/branches/py3k-jit/configure python/branches/py3k-jit/configure.in Modified: python/branches/py3k-jit/Lib/unittest/case.py ============================================================================== --- python/branches/py3k-jit/Lib/unittest/case.py (original) +++ python/branches/py3k-jit/Lib/unittest/case.py Tue May 11 19:58:55 2010 @@ -264,9 +264,6 @@ return self._testMethodName == other._testMethodName - def __ne__(self, other): - return not self == other - def __hash__(self): return hash((type(self), self._testMethodName)) Modified: python/branches/py3k-jit/Misc/NEWS ============================================================================== --- python/branches/py3k-jit/Misc/NEWS (original) +++ python/branches/py3k-jit/Misc/NEWS Tue May 11 19:58:55 2010 @@ -351,6 +351,9 @@ Library ------- +- The audioop module now supports sound fragments of length greater + than 2**31 bytes on 64-bit machines, and is PY_SSIZE_T_CLEAN. + - Issue #4972: Add support for the context manager protocol to the ftplib.FTP class. Modified: python/branches/py3k-jit/Misc/maintainers.rst ============================================================================== --- python/branches/py3k-jit/Misc/maintainers.rst (original) +++ python/branches/py3k-jit/Misc/maintainers.rst Tue May 11 19:58:55 2010 @@ -288,7 +288,7 @@ gvanrossum, anthonybaxter str.format eric.smith time and dates lemburg -testing michael.foord, pitrou +testing michael.foord, pitrou, giampaolo.rodola threads tracker unicode lemburg, ezio.melotti, haypo Modified: python/branches/py3k-jit/Modules/_cursesmodule.c ============================================================================== --- python/branches/py3k-jit/Modules/_cursesmodule.c (original) +++ python/branches/py3k-jit/Modules/_cursesmodule.c Tue May 11 19:58:55 2010 @@ -251,42 +251,49 @@ */ #define Window_NoArgNoReturnFunction(X) \ -static PyObject *PyCursesWindow_ ## X (PyCursesWindowObject *self, PyObject *args) \ +static PyObject *PyCursesWindow_ ## X \ +(PyCursesWindowObject *self, PyObject *args) \ { return PyCursesCheckERR(X(self->win), # X); } #define Window_NoArgTrueFalseFunction(X) \ -static PyObject * PyCursesWindow_ ## X (PyCursesWindowObject *self) \ +static PyObject * PyCursesWindow_ ## X \ +(PyCursesWindowObject *self) \ { \ if (X (self->win) == FALSE) { Py_INCREF(Py_False); return Py_False; } \ else { Py_INCREF(Py_True); return Py_True; } } #define Window_NoArgNoReturnVoidFunction(X) \ -static PyObject * PyCursesWindow_ ## X (PyCursesWindowObject *self) \ +static PyObject * PyCursesWindow_ ## X \ +(PyCursesWindowObject *self) \ { \ X(self->win); Py_INCREF(Py_None); return Py_None; } #define Window_NoArg2TupleReturnFunction(X, TYPE, ERGSTR) \ -static PyObject * PyCursesWindow_ ## X (PyCursesWindowObject *self) \ +static PyObject * PyCursesWindow_ ## X \ +(PyCursesWindowObject *self) \ { \ TYPE arg1, arg2; \ X(self->win,arg1,arg2); return Py_BuildValue(ERGSTR, arg1, arg2); } #define Window_OneArgNoReturnVoidFunction(X, TYPE, PARSESTR) \ -static PyObject * PyCursesWindow_ ## X (PyCursesWindowObject *self, PyObject *args) \ +static PyObject * PyCursesWindow_ ## X \ +(PyCursesWindowObject *self, PyObject *args) \ { \ TYPE arg1; \ if (!PyArg_ParseTuple(args, PARSESTR, &arg1)) return NULL; \ X(self->win,arg1); Py_INCREF(Py_None); return Py_None; } #define Window_OneArgNoReturnFunction(X, TYPE, PARSESTR) \ -static PyObject * PyCursesWindow_ ## X (PyCursesWindowObject *self, PyObject *args) \ +static PyObject * PyCursesWindow_ ## X \ +(PyCursesWindowObject *self, PyObject *args) \ { \ TYPE arg1; \ if (!PyArg_ParseTuple(args,PARSESTR, &arg1)) return NULL; \ return PyCursesCheckERR(X(self->win, arg1), # X); } #define Window_TwoArgNoReturnFunction(X, TYPE, PARSESTR) \ -static PyObject * PyCursesWindow_ ## X (PyCursesWindowObject *self, PyObject *args) \ +static PyObject * PyCursesWindow_ ## X \ +(PyCursesWindowObject *self, PyObject *args) \ { \ TYPE arg1, arg2; \ if (!PyArg_ParseTuple(args,PARSESTR, &arg1, &arg2)) return NULL; \ @@ -1234,10 +1241,11 @@ int rtn; #ifndef WINDOW_HAS_FLAGS - if (0) { + if (0) #else - if (self->win->_flags & _ISPAD) { + if (self->win->_flags & _ISPAD) #endif + { switch(PyTuple_Size(args)) { case 6: if (!PyArg_ParseTuple(args, @@ -1403,10 +1411,11 @@ int rtn; #ifndef WINDOW_HAS_FLAGS - if (0) { + if (0) #else - if (self->win->_flags & _ISPAD) { + if (self->win->_flags & _ISPAD) #endif + { switch(PyTuple_Size(args)) { case 6: if (!PyArg_ParseTuple(args, @@ -1739,8 +1748,8 @@ { short color,r,g,b; - PyCursesInitialised - PyCursesInitialisedColor + PyCursesInitialised; + PyCursesInitialisedColor; if (!PyArg_ParseTuple(args, "h:color_content", &color)) return NULL; @@ -1758,8 +1767,8 @@ { int n; - PyCursesInitialised - PyCursesInitialisedColor + PyCursesInitialised; + PyCursesInitialisedColor; if (!PyArg_ParseTuple(args, "i:color_pair", &n)) return NULL; return PyLong_FromLong((long) (n << 8)); @@ -1770,7 +1779,7 @@ { int vis,erg; - PyCursesInitialised + PyCursesInitialised; if (!PyArg_ParseTuple(args, "i:curs_set", &vis)) return NULL; @@ -1785,7 +1794,7 @@ { int ms; - PyCursesInitialised + PyCursesInitialised; if (!PyArg_ParseTuple(args, "i:delay_output", &ms)) return NULL; @@ -1797,7 +1806,7 @@ { char ch; - PyCursesInitialised + PyCursesInitialised; ch = erasechar(); @@ -1810,7 +1819,7 @@ int x = 0; int y = 0; - PyCursesInitialised + PyCursesInitialised; getsyx(y, x); @@ -1824,7 +1833,7 @@ int rtn; MEVENT event; - PyCursesInitialised + PyCursesInitialised; rtn = getmouse( &event ); if (rtn == ERR) { @@ -1842,7 +1851,7 @@ { MEVENT event; - PyCursesInitialised + PyCursesInitialised; if (!PyArg_ParseTuple(args, "hiiil", &event.id, &event.x, &event.y, &event.z, @@ -1863,7 +1872,7 @@ size_t datalen; WINDOW *win; - PyCursesInitialised + PyCursesInitialised; strcpy(fn, "/tmp/py.curses.getwin.XXXXXX"); fd = mkstemp(fn); @@ -1914,7 +1923,7 @@ { unsigned char tenths; - PyCursesInitialised + PyCursesInitialised; if (!PyArg_ParseTuple(args, "b:halfdelay", &tenths)) return NULL; @@ -1927,7 +1936,7 @@ { int ch; - PyCursesInitialised + PyCursesInitialised; if (!PyArg_ParseTuple(args,"i",&ch)) return NULL; @@ -1945,8 +1954,8 @@ { short color, r, g, b; - PyCursesInitialised - PyCursesInitialisedColor + PyCursesInitialised; + PyCursesInitialisedColor; switch(PyTuple_Size(args)) { case 4: @@ -1965,8 +1974,8 @@ { short pair, f, b; - PyCursesInitialised - PyCursesInitialisedColor + PyCursesInitialised; + PyCursesInitialisedColor; if (PyTuple_Size(args) != 3) { PyErr_SetString(PyExc_TypeError, "init_pair requires 3 arguments"); @@ -2139,7 +2148,7 @@ { int ch; - PyCursesInitialised + PyCursesInitialised; switch(PyTuple_Size(args)) { case 1: @@ -2161,7 +2170,7 @@ int columns; int result; - PyCursesInitialised + PyCursesInitialised; if (!PyArg_ParseTuple(args,"ii:is_term_resized", &lines, &columns)) return NULL; @@ -2183,7 +2192,7 @@ const char *knp; int ch; - PyCursesInitialised + PyCursesInitialised; if (!PyArg_ParseTuple(args,"i",&ch)) return NULL; @@ -2212,7 +2221,7 @@ { int ch; - PyCursesInitialised + PyCursesInitialised; switch(PyTuple_Size(args)) { case 1: @@ -2231,7 +2240,7 @@ PyCurses_MouseInterval(PyObject *self, PyObject *args) { int interval; - PyCursesInitialised + PyCursesInitialised; if (!PyArg_ParseTuple(args,"i;interval",&interval)) return NULL; @@ -2244,7 +2253,7 @@ int newmask; mmask_t oldmask, availmask; - PyCursesInitialised + PyCursesInitialised; if (!PyArg_ParseTuple(args,"i;mousemask",&newmask)) return NULL; availmask = mousemask(newmask, &oldmask); @@ -2257,7 +2266,7 @@ { int ms; - PyCursesInitialised + PyCursesInitialised; if (!PyArg_ParseTuple(args, "i;ms", &ms)) return NULL; return Py_BuildValue("i", napms(ms)); @@ -2270,7 +2279,7 @@ WINDOW *win; int nlines, ncols; - PyCursesInitialised + PyCursesInitialised; if (!PyArg_ParseTuple(args,"ii;nlines,ncols",&nlines,&ncols)) return NULL; @@ -2290,7 +2299,7 @@ WINDOW *win; int nlines, ncols, begin_y=0, begin_x=0; - PyCursesInitialised + PyCursesInitialised; switch (PyTuple_Size(args)) { case 2: @@ -2321,8 +2330,8 @@ { short pair,f,b; - PyCursesInitialised - PyCursesInitialisedColor + PyCursesInitialised; + PyCursesInitialisedColor; switch(PyTuple_Size(args)) { case 1: @@ -2347,8 +2356,8 @@ { int n; - PyCursesInitialised - PyCursesInitialisedColor + PyCursesInitialised; + PyCursesInitialisedColor; switch(PyTuple_Size(args)) { case 1: @@ -2377,7 +2386,7 @@ { int flag = 0; - PyCursesInitialised + PyCursesInitialised; switch(PyTuple_Size(args)) { case 0: @@ -2453,7 +2462,7 @@ int columns; PyObject *result; - PyCursesInitialised + PyCursesInitialised; if (!PyArg_ParseTuple(args,"ii:resizeterm", &lines, &columns)) return NULL; @@ -2477,7 +2486,7 @@ PyObject *result; - PyCursesInitialised + PyCursesInitialised; if (!PyArg_ParseTuple(args,"ii:resize_term", &lines, &columns)) return NULL; @@ -2496,7 +2505,7 @@ { int y,x; - PyCursesInitialised + PyCursesInitialised; if (PyTuple_Size(args)!=2) { PyErr_SetString(PyExc_TypeError, "setsyx requires 2 arguments"); @@ -2517,7 +2526,7 @@ int code; PyObject *c, *cp; - PyCursesInitialised + PyCursesInitialised; code = start_color(); if (code != ERR) { @@ -2609,7 +2618,7 @@ { int fd; - PyCursesInitialised + PyCursesInitialised; if (!PyArg_ParseTuple(args,"i;fd",&fd)) return NULL; @@ -2622,7 +2631,7 @@ PyObject *temp; chtype ch; - PyCursesInitialised + PyCursesInitialised; if (!PyArg_ParseTuple(args,"O;ch or int",&temp)) return NULL; @@ -2640,7 +2649,7 @@ PyObject *temp; chtype ch; - PyCursesInitialised + PyCursesInitialised; if (!PyArg_ParseTuple(args,"O;ch or int",&temp)) return NULL; @@ -2677,8 +2686,8 @@ { int code; - PyCursesInitialised - PyCursesInitialisedColor + PyCursesInitialised; + PyCursesInitialisedColor; code = use_default_colors(); if (code != ERR) { Modified: python/branches/py3k-jit/Modules/audioop.c ============================================================================== --- python/branches/py3k-jit/Modules/audioop.c (original) +++ python/branches/py3k-jit/Modules/audioop.c Tue May 11 19:58:55 2010 @@ -1,6 +1,8 @@ /* audioopmodule - Module to detect peak values in arrays */ +#define PY_SSIZE_T_CLEAN + #include "Python.h" #if SIZEOF_INT == 4 @@ -299,10 +301,10 @@ audioop_getsample(PyObject *self, PyObject *args) { signed char *cp; - int len, size, val = 0; - int i; + Py_ssize_t len, i; + int size, val = 0; - if ( !PyArg_ParseTuple(args, "s#ii:getsample", &cp, &len, &size, &i) ) + if ( !PyArg_ParseTuple(args, "s#in:getsample", &cp, &len, &size, &i) ) return 0; if ( size != 1 && size != 2 && size != 4 ) { PyErr_SetString(AudioopError, "Size should be 1, 2 or 4"); @@ -322,8 +324,8 @@ audioop_max(PyObject *self, PyObject *args) { signed char *cp; - int len, size, val = 0; - int i; + Py_ssize_t len, i; + int size, val = 0; int max = 0; if ( !PyArg_ParseTuple(args, "s#i:max", &cp, &len, &size) ) @@ -346,8 +348,8 @@ audioop_minmax(PyObject *self, PyObject *args) { signed char *cp; - int len, size, val = 0; - int i; + Py_ssize_t len, i; + int size, val = 0; int min = 0x7fffffff, max = -0x7fffffff; if (!PyArg_ParseTuple(args, "s#i:minmax", &cp, &len, &size)) @@ -370,8 +372,8 @@ audioop_avg(PyObject *self, PyObject *args) { signed char *cp; - int len, size, val = 0; - int i; + Py_ssize_t len, i; + int size, val = 0; double avg = 0.0; if ( !PyArg_ParseTuple(args, "s#i:avg", &cp, &len, &size) ) @@ -397,8 +399,8 @@ audioop_rms(PyObject *self, PyObject *args) { signed char *cp; - int len, size, val = 0; - int i; + Py_ssize_t len, i; + int size, val = 0; double sum_squares = 0.0; if ( !PyArg_ParseTuple(args, "s#i:rms", &cp, &len, &size) ) @@ -420,9 +422,9 @@ return PyLong_FromLong(val); } -static double _sum2(short *a, short *b, int len) +static double _sum2(short *a, short *b, Py_ssize_t len) { - int i; + Py_ssize_t i; double sum = 0.0; for( i=0; i INT_MAX/2) { + if (len > PY_SSIZE_T_MAX/2) { PyErr_SetString(PyExc_MemoryError, "not enough memory for output buffer"); return 0; @@ -893,9 +896,9 @@ audioop_add(PyObject *self, PyObject *args) { signed char *cp1, *cp2, *ncp; - int len1, len2, size, val1 = 0, val2 = 0, maxval, newval; + Py_ssize_t len1, len2, i; + int size, val1 = 0, val2 = 0, maxval, newval; PyObject *rv; - int i; if ( !PyArg_ParseTuple(args, "s#s#i:add", &cp1, &len1, &cp2, &len2, &size ) ) @@ -946,9 +949,9 @@ audioop_bias(PyObject *self, PyObject *args) { signed char *cp, *ncp; - int len, size, val = 0; + Py_ssize_t len, i; + int size, val = 0; PyObject *rv; - int i; int bias; if ( !PyArg_ParseTuple(args, "s#ii:bias", @@ -983,9 +986,9 @@ { signed char *cp; unsigned char *ncp; - int len, size, val = 0; + Py_ssize_t len, i, j; + int size, val = 0; PyObject *rv; - int i, j; if ( !PyArg_ParseTuple(args, "s#i:reverse", &cp, &len, &size) ) @@ -1020,9 +1023,9 @@ { signed char *cp; unsigned char *ncp; - int len, size, size2, val = 0; + Py_ssize_t len, i, j; + int size, size2, val = 0; PyObject *rv; - int i, j; if ( !PyArg_ParseTuple(args, "s#ii:lin2lin", &cp, &len, &size, &size2) ) @@ -1034,7 +1037,7 @@ return 0; } - if (len/size > INT_MAX/size2) { + if (len/size > PY_SSIZE_T_MAX/size2) { PyErr_SetString(PyExc_MemoryError, "not enough memory for output buffer"); return 0; @@ -1071,7 +1074,8 @@ audioop_ratecv(PyObject *self, PyObject *args) { char *cp, *ncp; - int len, size, nchannels, inrate, outrate, weightA, weightB; + Py_ssize_t len; + int size, nchannels, inrate, outrate, weightA, weightB; int chan, d, *prev_i, *cur_i, cur_o; PyObject *state, *samps, *str, *rv = NULL; int bytes_per_frame; @@ -1160,25 +1164,16 @@ ceiling(len*outrate/inrate) output frames, and each frame requires bytes_per_frame bytes. Computing this without spurious overflow is the challenge; we can - settle for a reasonable upper bound, though. */ - int ceiling; /* the number of output frames */ - int nbytes; /* the number of output bytes needed */ - int q = len / inrate; - /* Now len = q * inrate + r exactly (with r = len % inrate), - and this is less than q * inrate + inrate = (q+1)*inrate. - So a reasonable upper bound on len*outrate/inrate is - ((q+1)*inrate)*outrate/inrate = - (q+1)*outrate. - */ - ceiling = (q+1) * outrate; - nbytes = ceiling * bytes_per_frame; - /* See whether anything overflowed; if not, get the space. */ - if (q+1 < 0 || - ceiling / outrate != q+1 || - nbytes / bytes_per_frame != ceiling) + settle for a reasonable upper bound, though, in this + case ceiling(len/inrate) * outrate. */ + + /* compute ceiling(len/inrate) without overflow */ + Py_ssize_t q = len > 0 ? 1 + (len - 1) / inrate : 0; + if (outrate > PY_SSIZE_T_MAX / q / bytes_per_frame) str = NULL; else - str = PyBytes_FromStringAndSize(NULL, nbytes); + str = PyBytes_FromStringAndSize(NULL, + q * outrate * bytes_per_frame); if (str == NULL) { PyErr_SetString(PyExc_MemoryError, @@ -1203,7 +1198,7 @@ goto exit; /* We have checked before that the length * of the string fits into int. */ - len = (int)(ncp - PyBytes_AsString(str)); + len = (Py_ssize_t)(ncp - PyBytes_AsString(str)); rv = PyBytes_FromStringAndSize (PyBytes_AsString(str), len); Py_DECREF(str); @@ -1262,9 +1257,9 @@ { signed char *cp; unsigned char *ncp; - int len, size, val = 0; + Py_ssize_t len, i; + int size, val = 0; PyObject *rv; - int i; if ( !PyArg_ParseTuple(args, "s#i:lin2ulaw", &cp, &len, &size) ) @@ -1296,9 +1291,9 @@ unsigned char *cp; unsigned char cval; signed char *ncp; - int len, size, val; + Py_ssize_t len, i; + int size, val; PyObject *rv; - int i; if ( !PyArg_ParseTuple(args, "s#i:ulaw2lin", &cp, &len, &size) ) @@ -1309,7 +1304,7 @@ return 0; } - if (len > INT_MAX/size) { + if (len > PY_SSIZE_T_MAX/size) { PyErr_SetString(PyExc_MemoryError, "not enough memory for output buffer"); return 0; @@ -1335,9 +1330,9 @@ { signed char *cp; unsigned char *ncp; - int len, size, val = 0; + Py_ssize_t len, i; + int size, val = 0; PyObject *rv; - int i; if ( !PyArg_ParseTuple(args, "s#i:lin2alaw", &cp, &len, &size) ) @@ -1369,9 +1364,9 @@ unsigned char *cp; unsigned char cval; signed char *ncp; - int len, size, val; + Py_ssize_t len, i; + int size, val; PyObject *rv; - int i; if ( !PyArg_ParseTuple(args, "s#i:alaw2lin", &cp, &len, &size) ) @@ -1382,7 +1377,7 @@ return 0; } - if (len > INT_MAX/size) { + if (len > PY_SSIZE_T_MAX/size) { PyErr_SetString(PyExc_MemoryError, "not enough memory for output buffer"); return 0; @@ -1408,10 +1403,11 @@ { signed char *cp; signed char *ncp; - int len, size, val = 0, step, valpred, delta, + Py_ssize_t len, i; + int size, val = 0, step, valpred, delta, index, sign, vpdiff, diff; PyObject *rv, *state, *str; - int i, outputbuffer = 0, bufferstep; + int outputbuffer = 0, bufferstep; if ( !PyArg_ParseTuple(args, "s#iO:lin2adpcm", &cp, &len, &size, &state) ) @@ -1517,9 +1513,10 @@ { signed char *cp; signed char *ncp; - int len, size, valpred, step, delta, index, sign, vpdiff; + Py_ssize_t len, i; + int size, valpred, step, delta, index, sign, vpdiff; PyObject *rv, *str, *state; - int i, inputbuffer = 0, bufferstep; + int inputbuffer = 0, bufferstep; if ( !PyArg_ParseTuple(args, "s#iO:adpcm2lin", &cp, &len, &size, &state) ) @@ -1539,7 +1536,7 @@ } else if ( !PyArg_ParseTuple(state, "ii", &valpred, &index) ) return 0; - if (len > (INT_MAX/2)/size) { + if (len > (PY_SSIZE_T_MAX/2)/size) { PyErr_SetString(PyExc_MemoryError, "not enough memory for output buffer"); return 0; Modified: python/branches/py3k-jit/configure ============================================================================== --- python/branches/py3k-jit/configure (original) +++ python/branches/py3k-jit/configure Tue May 11 19:58:55 2010 @@ -1,5 +1,5 @@ #! /bin/sh -# From configure.in Revision: 80728 . +# From configure.in Revision: 80834 . # Guess values for system-dependent variables and create Makefiles. # Generated by GNU Autoconf 2.65 for python 3.2. # @@ -5337,7 +5337,7 @@ int main () { -int main() { return 0; } + ; return 0; } @@ -5350,11 +5350,11 @@ cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ - + void f(int **x) {} int main () { -void f(int **x) {} int main() { double *x; f((int **) &x); return 0; } +double *x; f((int **) &x); ; return 0; } @@ -5557,7 +5557,7 @@ int main () { -int main() { return 0; } + ; return 0; } @@ -5599,7 +5599,7 @@ int main () { -int main() { return 0; } + ; return 0; } @@ -9548,7 +9548,6 @@ cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ -#include "confdefs.h" #include int @@ -9577,7 +9576,6 @@ cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ -#include "confdefs.h" #include int @@ -9606,7 +9604,6 @@ cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ -#include "confdefs.h" #include int @@ -9926,7 +9923,6 @@ cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ -#include "confdefs.h" #include int @@ -9956,7 +9952,6 @@ cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ -#include "confdefs.h" #include #include #include @@ -9989,7 +9984,6 @@ cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ -#include "confdefs.h" #include #include #include @@ -10022,7 +10016,6 @@ cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ -#include "confdefs.h" #include #ifdef HAVE_GRP_H #include Modified: python/branches/py3k-jit/configure.in ============================================================================== --- python/branches/py3k-jit/configure.in (original) +++ python/branches/py3k-jit/configure.in Tue May 11 19:58:55 2010 @@ -916,14 +916,14 @@ AC_CACHE_VAL(ac_cv_no_strict_aliasing, AC_COMPILE_IFELSE( [ - AC_LANG_PROGRAM([[]], [[int main() { return 0; }]]) + AC_LANG_PROGRAM([[]], [[]]) ],[ CC="$ac_save_cc -fstrict-aliasing" CFLAGS="$CFLAGS -Werror -Wstrict-aliasing" AC_COMPILE_IFELSE( [ - AC_LANG_PROGRAM([[]], - [[void f(int **x) {} int main() { double *x; f((int **) &x); return 0; }]]) + AC_LANG_PROGRAM([[void f(int **x) {}]], + [[double *x; f((int **) &x);]]) ],[ ac_cv_no_strict_aliasing=no ],[ @@ -1099,7 +1099,7 @@ [ac_save_cc="$CC" CC="$CC -OPT:Olimit=0" AC_COMPILE_IFELSE( - [AC_LANG_PROGRAM([[]], [[int main() { return 0; }]])], + [AC_LANG_PROGRAM([[]], [[]])], [ac_cv_opt_olimit_ok=yes], [ac_cv_opt_olimit_ok=no] ) @@ -1122,7 +1122,7 @@ [ac_save_cc="$CC" CC="$CC -Olimit 1500" AC_COMPILE_IFELSE( - [AC_LANG_PROGRAM([[]], [[int main() { return 0; }]])], + [AC_LANG_PROGRAM([[]], [[]])], [ac_cv_olimit_ok=yes], [ac_cv_olimit_ok=no] ) @@ -2663,7 +2663,6 @@ AC_MSG_CHECKING(for ctermid_r) AC_COMPILE_IFELSE([AC_LANG_PROGRAM([[ -#include "confdefs.h" #include ]], [[void* p = ctermid_r]])], [AC_DEFINE(HAVE_CTERMID_R, 1, Define if you have the 'ctermid_r' function.) @@ -2673,7 +2672,6 @@ AC_MSG_CHECKING(for flock) AC_COMPILE_IFELSE([AC_LANG_PROGRAM([[ -#include "confdefs.h" #include ]], [[void* p = flock]])], [AC_DEFINE(HAVE_FLOCK, 1, Define if you have the 'flock' function.) @@ -2683,7 +2681,6 @@ AC_MSG_CHECKING(for getpagesize) AC_COMPILE_IFELSE([AC_LANG_PROGRAM([[ -#include "confdefs.h" #include ]], [[void* p = getpagesize]])], [AC_DEFINE(HAVE_GETPAGESIZE, 1, Define if you have the 'getpagesize' function.) @@ -2774,7 +2771,6 @@ AC_MSG_CHECKING(for hstrerror) AC_LINK_IFELSE([AC_LANG_PROGRAM([[ -#include "confdefs.h" #include ]], [[void* p = hstrerror; hstrerror(0)]])], [AC_DEFINE(HAVE_HSTRERROR, 1, Define if you have the 'hstrerror' function.) @@ -2784,7 +2780,6 @@ AC_MSG_CHECKING(for inet_aton) AC_LINK_IFELSE([AC_LANG_PROGRAM([[ -#include "confdefs.h" #include #include #include @@ -2797,7 +2792,6 @@ AC_MSG_CHECKING(for inet_pton) AC_COMPILE_IFELSE([AC_LANG_PROGRAM([[ -#include "confdefs.h" #include #include #include @@ -2811,7 +2805,6 @@ # On some systems, setgroups is in unistd.h, on others, in grp.h AC_MSG_CHECKING(for setgroups) AC_COMPILE_IFELSE([AC_LANG_PROGRAM([[ -#include "confdefs.h" #include #ifdef HAVE_GRP_H #include From python-checkins at python.org Tue May 11 20:12:27 2010 From: python-checkins at python.org (fred.drake) Date: Tue, 11 May 2010 20:12:27 +0200 (CEST) Subject: [Python-checkins] r81087 - python/trunk/Doc/library/httplib.rst Message-ID: <20100511181227.8A97AEE98A@mail.python.org> Author: fred.drake Date: Tue May 11 20:12:27 2010 New Revision: 81087 Log: fix typo Modified: python/trunk/Doc/library/httplib.rst Modified: python/trunk/Doc/library/httplib.rst ============================================================================== --- python/trunk/Doc/library/httplib.rst (original) +++ python/trunk/Doc/library/httplib.rst Tue May 11 20:12:27 2010 @@ -560,8 +560,8 @@ >>> data2 = r2.read() >>> conn.close() -Here is an example session that uses ``HEAD`` method. Note that ``HEAD`` method -never returns any data. :: +Here is an example session that uses the ``HEAD`` method. Note that``HEAD`` +method never returns any data. :: >>> import httplib From python-checkins at python.org Tue May 11 21:13:13 2010 From: python-checkins at python.org (brian.curtin) Date: Tue, 11 May 2010 21:13:13 +0200 (CEST) Subject: [Python-checkins] r81088 - python/trunk/Doc/library/_winreg.rst Message-ID: <20100511191313.963BDEC97@mail.python.org> Author: brian.curtin Date: Tue May 11 21:13:13 2010 New Revision: 81088 Log: #8575 - Update and reorganize some _winreg contents. I've removed the hopeful note about a future higher-level module since it's been in there for quite a long time and nothing of the sort has come up. There are a few places where markup was added to cross-reference other sections, and many of the external links have been removed and now point to newly created sections containing previously undocumented information. The Value Types section was created and it's contents were taken from a function-specific area, since it applies to more than just that function. It fits in better with the other newly documented constants. Modified: python/trunk/Doc/library/_winreg.rst Modified: python/trunk/Doc/library/_winreg.rst ============================================================================== --- python/trunk/Doc/library/_winreg.rst (original) +++ python/trunk/Doc/library/_winreg.rst Tue May 11 21:13:13 2010 @@ -19,10 +19,6 @@ to ensure that the handles are closed correctly, even if the programmer neglects to explicitly close them. -This module exposes a very low-level interface to the Windows registry; it is -expected that in the future a new module will be created offering a higher-level -interface to the registry API. - This module offers the following functions: @@ -31,9 +27,9 @@ Closes a previously opened registry key. The *hkey* argument specifies a previously opened key. - Note that if *hkey* is not closed using this method (or via - :meth:`handle.Close`), it is closed when the *hkey* object is destroyed by - Python. + .. note:: + If *hkey* is not closed using this method (or via :meth:`hkey.Close() `), + it is closed when the *hkey* object is destroyed by Python. .. function:: ConnectRegistry(computer_name, key) @@ -55,8 +51,8 @@ Creates or opens the specified key, returning a :ref:`handle object `. - *key* is an already open key, or one of the predefined :const:`HKEY_\*` - constants. + *key* is an already open key, or one of the predefined + :ref:`HKEY_* constants `. *sub_key* is a string that names the key this method opens or creates. @@ -74,18 +70,16 @@ Creates or opens the specified key, returning a :ref:`handle object `. - *key* is an already open key, or one of the predefined :const:`HKEY_\*` - constants. + *key* is an already open key, or one of the predefined + :ref:`HKEY_* constants `. *sub_key* is a string that names the key this method opens or creates. *res* is a reserved integer, and must be zero. The default is zero. *sam* is an integer that specifies an access mask that describes the desired - security access for the key. Default is :const:`KEY_ALL_ACCESS`. See the - `Win32 documentation - `__ for - other allowed values. + security access for the key. Default is :const:`KEY_ALL_ACCESS`. See + :ref:`Access Rights ` for other allowed values. If *key* is one of the predefined keys, *sub_key* may be ``None``. In that @@ -103,8 +97,8 @@ Deletes the specified key. - *key* is an already open key, or any one of the predefined :const:`HKEY_\*` - constants. + *key* is an already open key, or any one of the predefined + :ref:`HKEY_* constants `. *sub_key* is a string that must be a subkey of the key identified by the *key* parameter. This value must not be ``None``, and the key may not have subkeys. @@ -122,10 +116,11 @@ .. note:: The :func:`DeleteKeyEx` function is implemented with the RegDeleteKeyEx Windows API function, which is specific to 64-bit versions of Windows. - See http://msdn.microsoft.com/en-us/library/ms724847%28VS.85%29.aspx + See the `RegDeleteKeyEx documentation + `__. - *key* is an already open key, or any one of the predefined :const:`HKEY_\*` - constants. + *key* is an already open key, or any one of the predefined + :ref:`HKEY_* constants `. *sub_key* is a string that must be a subkey of the key identified by the *key* parameter. This value must not be ``None``, and the key may not have @@ -134,10 +129,8 @@ *res* is a reserved integer, and must be zero. The default is zero. *sam* is an integer that specifies an access mask that describes the desired - security access for the key. Default is :const:`KEY_WOW64_64KEY`. See the - `Win32 documentation - `__ for - other allowed values. + security access for the key. Default is :const:`KEY_WOW64_64KEY`. See + :ref:`Access Rights ` for other allowed values. *This method can not delete keys with subkeys.* @@ -154,8 +147,8 @@ Removes a named value from a registry key. - *key* is an already open key, or one of the predefined :const:`HKEY_\*` - constants. + *key* is an already open key, or one of the predefined + :ref:`HKEY_* constants `. *value* is a string that identifies the value to remove. @@ -164,8 +157,8 @@ Enumerates subkeys of an open registry key, returning a string. - *key* is an already open key, or any one of the predefined :const:`HKEY_\*` - constants. + *key* is an already open key, or any one of the predefined + :ref:`HKEY_* constants `. *index* is an integer that identifies the index of the key to retrieve. @@ -178,8 +171,8 @@ Enumerates values of an open registry key, returning a tuple. - *key* is an already open key, or any one of the predefined :const:`HKEY_\*` - constants. + *key* is an already open key, or any one of the predefined + :ref:`HKEY_* constants `. *index* is an integer that identifies the index of the value to retrieve. @@ -219,8 +212,8 @@ Writes all the attributes of a key to the registry. - *key* is an already open key, or one of the predefined :const:`HKEY_\*` - constants. + *key* is an already open key, or one of the predefined + :ref:`HKEY_* constants `. It is not necessary to call :func:`FlushKey` to change a key. Registry changes are flushed to disk by the registry using its lazy flusher. Registry changes are @@ -241,7 +234,7 @@ from a specified file into that subkey. *key* is a handle returned by :func:`ConnectRegistry` or one of the constants - :const:`HKEY_USER` or :const:`HKEY_LOCAL_MACHINE`. + :const:`HKEY_USERS` or :const:`HKEY_LOCAL_MACHINE`. *sub_key* is a string that identifies the subkey to load. @@ -251,7 +244,7 @@ A call to :func:`LoadKey` fails if the calling process does not have the :const:`SE_RESTORE_PRIVILEGE` privilege. Note that privileges are different - from permissions -- see the `Win32 documentation + from permissions -- see the `RegLoadKey documentation `__ for more details. @@ -263,18 +256,16 @@ Opens the specified key, returning a :ref:`handle object `. - *key* is an already open key, or any one of the predefined :const:`HKEY_\*` - constants. + *key* is an already open key, or any one of the predefined + :ref:`HKEY_* constants `. *sub_key* is a string that identifies the sub_key to open. *res* is a reserved integer, and must be zero. The default is zero. *sam* is an integer that specifies an access mask that describes the desired - security access for the key. Default is :const:`KEY_READ`. See the `Win32 - documentation - `__ for - other allowed values. + security access for the key. Default is :const:`KEY_READ`. See + :ref:`Access Rights ` for other allowed values. The result is a new handle to the specified key. @@ -291,8 +282,8 @@ Returns information about a key, as a tuple. - *key* is an already open key, or one of the predefined :const:`HKEY_\*` - constants. + *key* is an already open key, or one of the predefined + :ref:`HKEY_* constants `. The result is a tuple of 3 items: @@ -315,8 +306,8 @@ Retrieves the unnamed value for a key, as a string. - *key* is an already open key, or one of the predefined :const:`HKEY_\*` - constants. + *key* is an already open key, or one of the predefined + :ref:`HKEY_* constants `. *sub_key* is a string that holds the name of the subkey with which the value is associated. If this parameter is ``None`` or empty, the function retrieves the @@ -333,8 +324,8 @@ Retrieves the type and data for a specified value name associated with an open registry key. - *key* is an already open key, or one of the predefined :const:`HKEY_\*` - constants. + *key* is an already open key, or one of the predefined + :ref:`HKEY_* constants `. *value_name* is a string indicating the value to query. @@ -355,8 +346,8 @@ Saves the specified key, and all its subkeys to the specified file. - *key* is an already open key, or one of the predefined :const:`HKEY_\*` - constants. + *key* is an already open key, or one of the predefined + :ref:`HKEY_* constants `. *file_name* is the name of the file to save registry data to. This file cannot already exist. If this filename includes an extension, it cannot be @@ -366,8 +357,10 @@ If *key* represents a key on a remote computer, the path described by *file_name* is relative to the remote computer. The caller of this method must possess the :const:`SeBackupPrivilege` security privilege. Note that - privileges are different than permissions -- see the Win32 documentation for - more details. + privileges are different than permissions -- see the + `Conflicts Between User Rights and Permissions documentation + `__ + for more details. This function passes NULL for *security_attributes* to the API. @@ -376,8 +369,8 @@ Associates a value with a specified key. - *key* is an already open key, or one of the predefined :const:`HKEY_\*` - constants. + *key* is an already open key, or one of the predefined + :ref:`HKEY_* constants `. *sub_key* is a string that names the subkey with which the value is associated. @@ -402,42 +395,14 @@ Stores data in the value field of an open registry key. - *key* is an already open key, or one of the predefined :const:`HKEY_\*` - constants. + *key* is an already open key, or one of the predefined + :ref:`HKEY_* constants `. *value_name* is a string that names the subkey with which the value is associated. - *type* is an integer that specifies the type of the data. This should be one - of the following constants defined in this module: - - +----------------------------------+---------------------------------------------+ - | Constant | Meaning | - +==================================+=============================================+ - | :const:`REG_BINARY` | Binary data in any form. | - +----------------------------------+---------------------------------------------+ - | :const:`REG_DWORD` | A 32-bit number. | - +----------------------------------+---------------------------------------------+ - | :const:`REG_DWORD_LITTLE_ENDIAN` | A 32-bit number in little-endian format. | - +----------------------------------+---------------------------------------------+ - | :const:`REG_DWORD_BIG_ENDIAN` | A 32-bit number in big-endian format. | - +----------------------------------+---------------------------------------------+ - | :const:`REG_EXPAND_SZ` | Null-terminated string containing | - | | references to environment variables | - | | (``%PATH%``). | - +----------------------------------+---------------------------------------------+ - | :const:`REG_LINK` | A Unicode symbolic link. | - +----------------------------------+---------------------------------------------+ - | :const:`REG_MULTI_SZ` | A sequence of null-terminated strings, | - | | terminated by two null characters. (Python | - | | handles this termination automatically.) | - +----------------------------------+---------------------------------------------+ - | :const:`REG_NONE` | No defined value type. | - +----------------------------------+---------------------------------------------+ - | :const:`REG_RESOURCE_LIST` | A device-driver resource list. | - +----------------------------------+---------------------------------------------+ - | :const:`REG_SZ` | A null-terminated string. | - +----------------------------------+---------------------------------------------+ + *type* is an integer that specifies the type of the data. See + :ref:`Value Types ` for the available types. *reserved* can be anything -- zero is always passed to the API. @@ -459,8 +424,8 @@ Disables registry reflection for 32-bit processes running on a 64-bit operating system. - *key* is an already open key, or one of the predefined :const:`HKEY_\*` - constants. + *key* is an already open key, or one of the predefined + :ref:`HKEY_* constants `. Will generally raise :exc:`NotImplemented` if executed on a 32-bit operating system. @@ -474,8 +439,8 @@ Restores registry reflection for the specified disabled key. - *key* is an already open key, or one of the predefined :const:`HKEY_\*` - constants. + *key* is an already open key, or one of the predefined + :ref:`HKEY_* constants `. Will generally raise :exc:`NotImplemented` if executed on a 32-bit operating system. @@ -487,8 +452,8 @@ Determines the reflection state for the specified key. - *key* is an already open key, or one of the predefined :const:`HKEY_\*` - constants. + *key* is an already open key, or one of the predefined + :ref:`HKEY_* constants `. Returns ``True`` if reflection is disabled. @@ -496,6 +461,195 @@ operating system. +.. _constants: + +Constants +------------------ + +The following constants are defined for use in many :mod:`_winreg` functions. + +.. _hkey-constants: + +HKEY_* Constants +++++++++++++++++ + +.. data:: HKEY_CLASSES_ROOT + + Registry entries subordinate to this key define types (or classes) of + documents and the properties associated with those types. Shell and + COM applications use the information stored under this key. + + +.. data:: HKEY_CURRENT_USER + + Registry entries subordinate to this key define the preferences of + the current user. These preferences include the settings of + environment variables, data about program groups, colors, printers, + network connections, and application preferences. + +.. data:: HKEY_LOCAL_MACHINE + + Registry entries subordinate to this key define the physical state + of the computer, including data about the bus type, system memory, + and installed hardware and software. + +.. data:: HKEY_USERS + + Registry entries subordinate to this key define the default user + configuration for new users on the local computer and the user + configuration for the current user. + +.. data:: HKEY_PERFORMANCE_DATA + + Registry entries subordinate to this key allow you to access + performance data. The data is not actually stored in the registry; + the registry functions cause the system to collect the data from + its source. + + +.. data:: HKEY_CURRENT_CONFIG + + Contains information about the current hardware profile of the + local computer system. + +.. data:: HKEY_DYN_DATA + + This key is not used in versions of Windows after 98. + + +.. _access-rights: + +Access Rights ++++++++++++++ + +For more information, see `Registry Key Security and Access +`__. + +.. data:: KEY_ALL_ACCESS + + Combines the STANDARD_RIGHTS_REQUIRED, :const:`KEY_QUERY_VALUE`, + :const:`KEY_SET_VALUE`, :const:`KEY_CREATE_SUB_KEY`, + :const:`KEY_ENUMERATE_SUB_KEYS`, :const:`KEY_NOTIFY`, + and :const:`KEY_CREATE_LINK` access rights. + +.. data:: KEY_WRITE + + Combines the STANDARD_RIGHTS_WRITE, :const:`KEY_SET_VALUE`, and + :const:`KEY_CREATE_SUB_KEY` access rights. + +.. data:: KEY_READ + + Combines the STANDARD_RIGHTS_READ, :const:`KEY_QUERY_VALUE`, + :const:`KEY_ENUMERATE_SUB_KEYS`, and :const:`KEY_NOTIFY` values. + +.. data:: KEY_EXECUTE + + Equivalent to :const:`KEY_READ`. + +.. data:: KEY_QUERY_VALUE + + Required to query the values of a registry key. + +.. data:: KEY_SET_VALUE + + Required to create, delete, or set a registry value. + +.. data:: KEY_CREATE_SUB_KEY + + Required to create a subkey of a registry key. + +.. data:: KEY_ENUMERATE_SUB_KEYS + + Required to enumerate the subkeys of a registry key. + +.. data:: KEY_NOTIFY + + Required to request change notifications for a registry key or for + subkeys of a registry key. + +.. data:: KEY_CREATE_LINK + + Reserved for system use. + + +.. _64-bit-access-rights: + +64-bit Specific +*************** + +For more information, see `Accesing an Alternate Registry View +`__. + +.. data:: KEY_WOW64_64KEY + + Indicates that an application on 64-bit Windows should operate on + the 64-bit registry view. + +.. data:: KEY_WOW64_32KEY + + Indicates that an application on 64-bit Windows should operate on + the 32-bit registry view. + + +.. _value-types: + +Value Types ++++++++++++ + +For more information, see `Registry Value Types +`__. + +.. data:: REG_BINARY + + Binary data in any form. + +.. data:: REG_DWORD + + 32-bit number. + +.. data:: REG_DWORD_LITTLE_ENDIAN + + A 32-bit number in little-endian format. + +.. data:: REG_DWORD_BIG_ENDIAN + + A 32-bit number in big-endian format. + +.. data:: REG_EXPAND_SZ + + Null-terminated string containing references to environment + variables (``%PATH%``). + +.. data:: REG_LINK + + A Unicode symbolic link. + +.. data:: REG_MULTI_SZ + + A sequence of null-terminated strings, terminated by two null characters. + (Python handles this termination automatically.) + +.. data:: REG_NONE + + No defined value type. + +.. data:: REG_RESOURCE_LIST + + A device-driver resource list. + +.. data:: REG_FULL_RESOURCE_DESCRIPTOR + + A hardware setting. + +.. data:: REG_RESOURCE_REQUIREMENTS_LIST + + A hardware resource list. + +.. data:: REG_SZ + + A null-terminated string. + + .. _handle-object: Registry Handle Objects From python-checkins at python.org Tue May 11 21:32:26 2010 From: python-checkins at python.org (brian.curtin) Date: Tue, 11 May 2010 21:32:26 +0200 (CEST) Subject: [Python-checkins] r81089 - in python/branches/release26-maint: Doc/library/_winreg.rst Message-ID: <20100511193226.9CC2DC917@mail.python.org> Author: brian.curtin Date: Tue May 11 21:32:26 2010 New Revision: 81089 Log: Backport of r81088, plus the exposure of the previously undocumented *ReflectionKey functions. Apparently that was not backported. Merged revisions 81088 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r81088 | brian.curtin | 2010-05-11 14:13:13 -0500 (Tue, 11 May 2010) | 13 lines #8575 - Update and reorganize some _winreg contents. I've removed the hopeful note about a future higher-level module since it's been in there for quite a long time and nothing of the sort has come up. There are a few places where markup was added to cross-reference other sections, and many of the external links have been removed and now point to newly created sections containing previously undocumented information. The Value Types section was created and it's contents were taken from a function-specific area, since it applies to more than just that function. It fits in better with the other newly documented constants. ........ Modified: python/branches/release26-maint/ (props changed) python/branches/release26-maint/Doc/library/_winreg.rst Modified: python/branches/release26-maint/Doc/library/_winreg.rst ============================================================================== --- python/branches/release26-maint/Doc/library/_winreg.rst (original) +++ python/branches/release26-maint/Doc/library/_winreg.rst Tue May 11 21:32:26 2010 @@ -19,10 +19,6 @@ to ensure that the handles are closed correctly, even if the programmer neglects to explicitly close them. -This module exposes a very low-level interface to the Windows registry; it is -expected that in the future a new module will be created offering a higher-level -interface to the registry API. - This module offers the following functions: @@ -31,9 +27,9 @@ Closes a previously opened registry key. The *hkey* argument specifies a previously opened key. - Note that if *hkey* is not closed using this method (or via - :meth:`handle.Close`), it is closed when the *hkey* object is destroyed by - Python. + .. note:: + If *hkey* is not closed using this method (or via :meth:`hkey.Close() `), + it is closed when the *hkey* object is destroyed by Python. .. function:: ConnectRegistry(computer_name, key) @@ -55,8 +51,8 @@ Creates or opens the specified key, returning a :ref:`handle object `. - *key* is an already open key, or one of the predefined :const:`HKEY_\*` - constants. + *key* is an already open key, or one of the predefined + :ref:`HKEY_* constants `. *sub_key* is a string that names the key this method opens or creates. @@ -73,8 +69,8 @@ Deletes the specified key. - *key* is an already open key, or any one of the predefined :const:`HKEY_\*` - constants. + *key* is an already open key, or any one of the predefined + :ref:`HKEY_* constants `. *sub_key* is a string that must be a subkey of the key identified by the *key* parameter. This value must not be ``None``, and the key may not have subkeys. @@ -89,8 +85,8 @@ Removes a named value from a registry key. - *key* is an already open key, or one of the predefined :const:`HKEY_\*` - constants. + *key* is an already open key, or one of the predefined + :ref:`HKEY_* constants `. *value* is a string that identifies the value to remove. @@ -99,8 +95,8 @@ Enumerates subkeys of an open registry key, returning a string. - *key* is an already open key, or any one of the predefined :const:`HKEY_\*` - constants. + *key* is an already open key, or any one of the predefined + :ref:`HKEY_* constants `. *index* is an integer that identifies the index of the key to retrieve. @@ -113,8 +109,8 @@ Enumerates values of an open registry key, returning a tuple. - *key* is an already open key, or any one of the predefined :const:`HKEY_\*` - constants. + *key* is an already open key, or any one of the predefined + :ref:`HKEY_* constants `. *index* is an integer that identifies the index of the value to retrieve. @@ -154,8 +150,8 @@ Writes all the attributes of a key to the registry. - *key* is an already open key, or one of the predefined :const:`HKEY_\*` - constants. + *key* is an already open key, or one of the predefined + :ref:`HKEY_* constants `. It is not necessary to call :func:`FlushKey` to change a key. Registry changes are flushed to disk by the registry using its lazy flusher. Registry changes are @@ -176,7 +172,7 @@ from a specified file into that subkey. *key* is a handle returned by :func:`ConnectRegistry` or one of the constants - :const:`HKEY_USER` or :const:`HKEY_LOCAL_MACHINE`. + :const:`HKEY_USERS` or :const:`HKEY_LOCAL_MACHINE`. *sub_key* is a string that identifies the subkey to load. @@ -186,7 +182,7 @@ A call to :func:`LoadKey` fails if the calling process does not have the :const:`SE_RESTORE_PRIVILEGE` privilege. Note that privileges are different - from permissions -- see the `Win32 documentation + from permissions -- see the `RegLoadKey documentation `_ for more details. @@ -198,18 +194,16 @@ Opens the specified key, returning a :ref:`handle object `. - *key* is an already open key, or any one of the predefined :const:`HKEY_\*` - constants. + *key* is an already open key, or any one of the predefined + :ref:`HKEY_* constants `. *sub_key* is a string that identifies the sub_key to open. *res* is a reserved integer, and must be zero. The default is zero. *sam* is an integer that specifies an access mask that describes the desired - security access for the key. Default is :const:`KEY_READ`. See the `Win32 - documentation - `_ for - other allowed values. + security access for the key. Default is :const:`KEY_READ`. See + :ref:`Access Rights ` for other allowed values. The result is a new handle to the specified key. @@ -226,8 +220,8 @@ Returns information about a key, as a tuple. - *key* is an already open key, or one of the predefined :const:`HKEY_\*` - constants. + *key* is an already open key, or one of the predefined + :ref:`HKEY_* constants `. The result is a tuple of 3 items: @@ -250,8 +244,8 @@ Retrieves the unnamed value for a key, as a string. - *key* is an already open key, or one of the predefined :const:`HKEY_\*` - constants. + *key* is an already open key, or one of the predefined + :ref:`HKEY_* constants `. *sub_key* is a string that holds the name of the subkey with which the value is associated. If this parameter is ``None`` or empty, the function retrieves the @@ -268,8 +262,8 @@ Retrieves the type and data for a specified value name associated with an open registry key. - *key* is an already open key, or one of the predefined :const:`HKEY_\*` - constants. + *key* is an already open key, or one of the predefined + :ref:`HKEY_* constants `. *value_name* is a string indicating the value to query. @@ -290,8 +284,8 @@ Saves the specified key, and all its subkeys to the specified file. - *key* is an already open key, or one of the predefined :const:`HKEY_\*` - constants. + *key* is an already open key, or one of the predefined + :ref:`HKEY_* constants `. *file_name* is the name of the file to save registry data to. This file cannot already exist. If this filename includes an extension, it cannot be @@ -301,8 +295,10 @@ If *key* represents a key on a remote computer, the path described by *file_name* is relative to the remote computer. The caller of this method must possess the :const:`SeBackupPrivilege` security privilege. Note that - privileges are different than permissions -- see the Win32 documentation for - more details. + privileges are different than permissions -- see the + `Conflicts Between User Rights and Permissions documentation + `__ + for more details. This function passes NULL for *security_attributes* to the API. @@ -311,8 +307,8 @@ Associates a value with a specified key. - *key* is an already open key, or one of the predefined :const:`HKEY_\*` - constants. + *key* is an already open key, or one of the predefined + :ref:`HKEY_* constants `. *sub_key* is a string that names the subkey with which the value is associated. @@ -337,42 +333,14 @@ Stores data in the value field of an open registry key. - *key* is an already open key, or one of the predefined :const:`HKEY_\*` - constants. + *key* is an already open key, or one of the predefined + :ref:`HKEY_* constants `. *value_name* is a string that names the subkey with which the value is associated. - *type* is an integer that specifies the type of the data. This should be one - of the following constants defined in this module: - - +----------------------------------+---------------------------------------------+ - | Constant | Meaning | - +==================================+=============================================+ - | :const:`REG_BINARY` | Binary data in any form. | - +----------------------------------+---------------------------------------------+ - | :const:`REG_DWORD` | A 32-bit number. | - +----------------------------------+---------------------------------------------+ - | :const:`REG_DWORD_LITTLE_ENDIAN` | A 32-bit number in little-endian format. | - +----------------------------------+---------------------------------------------+ - | :const:`REG_DWORD_BIG_ENDIAN` | A 32-bit number in big-endian format. | - +----------------------------------+---------------------------------------------+ - | :const:`REG_EXPAND_SZ` | Null-terminated string containing | - | | references to environment variables | - | | (``%PATH%``). | - +----------------------------------+---------------------------------------------+ - | :const:`REG_LINK` | A Unicode symbolic link. | - +----------------------------------+---------------------------------------------+ - | :const:`REG_MULTI_SZ` | A sequence of null-terminated strings, | - | | terminated by two null characters. (Python | - | | handles this termination automatically.) | - +----------------------------------+---------------------------------------------+ - | :const:`REG_NONE` | No defined value type. | - +----------------------------------+---------------------------------------------+ - | :const:`REG_RESOURCE_LIST` | A device-driver resource list. | - +----------------------------------+---------------------------------------------+ - | :const:`REG_SZ` | A null-terminated string. | - +----------------------------------+---------------------------------------------+ + *type* is an integer that specifies the type of the data. See + :ref:`Value Types ` for the available types. *reserved* can be anything -- zero is always passed to the API. @@ -389,6 +357,237 @@ registry. This helps the registry perform efficiently. +.. function:: DisableReflectionKey(key) + + Disables registry reflection for 32-bit processes running on a 64-bit + operating system. + + *key* is an already open key, or one of the predefined + :ref:`HKEY_* constants `. + + Will generally raise :exc:`NotImplemented` if executed on a 32-bit + operating system. + + If the key is not on the reflection list, the function succeeds but has no + effect. Disabling reflection for a key does not affect reflection of any + subkeys. + + +.. function:: EnableReflectionKey(key) + + Restores registry reflection for the specified disabled key. + + *key* is an already open key, or one of the predefined + :ref:`HKEY_* constants `. + + Will generally raise :exc:`NotImplemented` if executed on a 32-bit + operating system. + + Restoring reflection for a key does not affect reflection of any subkeys. + + +.. function:: QueryReflectionKey(key) + + Determines the reflection state for the specified key. + + *key* is an already open key, or one of the predefined + :ref:`HKEY_* constants `. + + Returns ``True`` if reflection is disabled. + + Will generally raise :exc:`NotImplemented` if executed on a 32-bit + operating system. + + +.. _constants: + +Constants +------------------ + +The following constants are defined for use in many :mod:`_winreg` functions. + +.. _hkey-constants: + +HKEY_* Constants +++++++++++++++++ + +.. data:: HKEY_CLASSES_ROOT + + Registry entries subordinate to this key define types (or classes) of + documents and the properties associated with those types. Shell and + COM applications use the information stored under this key. + + +.. data:: HKEY_CURRENT_USER + + Registry entries subordinate to this key define the preferences of + the current user. These preferences include the settings of + environment variables, data about program groups, colors, printers, + network connections, and application preferences. + +.. data:: HKEY_LOCAL_MACHINE + + Registry entries subordinate to this key define the physical state + of the computer, including data about the bus type, system memory, + and installed hardware and software. + +.. data:: HKEY_USERS + + Registry entries subordinate to this key define the default user + configuration for new users on the local computer and the user + configuration for the current user. + +.. data:: HKEY_PERFORMANCE_DATA + + Registry entries subordinate to this key allow you to access + performance data. The data is not actually stored in the registry; + the registry functions cause the system to collect the data from + its source. + + +.. data:: HKEY_CURRENT_CONFIG + + Contains information about the current hardware profile of the + local computer system. + +.. data:: HKEY_DYN_DATA + + This key is not used in versions of Windows after 98. + + +.. _access-rights: + +Access Rights ++++++++++++++ + +For more information, see `Registry Key Security and Access +`__. + +.. data:: KEY_ALL_ACCESS + + Combines the STANDARD_RIGHTS_REQUIRED, :const:`KEY_QUERY_VALUE`, + :const:`KEY_SET_VALUE`, :const:`KEY_CREATE_SUB_KEY`, + :const:`KEY_ENUMERATE_SUB_KEYS`, :const:`KEY_NOTIFY`, + and :const:`KEY_CREATE_LINK` access rights. + +.. data:: KEY_WRITE + + Combines the STANDARD_RIGHTS_WRITE, :const:`KEY_SET_VALUE`, and + :const:`KEY_CREATE_SUB_KEY` access rights. + +.. data:: KEY_READ + + Combines the STANDARD_RIGHTS_READ, :const:`KEY_QUERY_VALUE`, + :const:`KEY_ENUMERATE_SUB_KEYS`, and :const:`KEY_NOTIFY` values. + +.. data:: KEY_EXECUTE + + Equivalent to :const:`KEY_READ`. + +.. data:: KEY_QUERY_VALUE + + Required to query the values of a registry key. + +.. data:: KEY_SET_VALUE + + Required to create, delete, or set a registry value. + +.. data:: KEY_CREATE_SUB_KEY + + Required to create a subkey of a registry key. + +.. data:: KEY_ENUMERATE_SUB_KEYS + + Required to enumerate the subkeys of a registry key. + +.. data:: KEY_NOTIFY + + Required to request change notifications for a registry key or for + subkeys of a registry key. + +.. data:: KEY_CREATE_LINK + + Reserved for system use. + + +.. _64-bit-access-rights: + +64-bit Specific +*************** + +For more information, see `Accesing an Alternate Registry View +`__. + +.. data:: KEY_WOW64_64KEY + + Indicates that an application on 64-bit Windows should operate on + the 64-bit registry view. + +.. data:: KEY_WOW64_32KEY + + Indicates that an application on 64-bit Windows should operate on + the 32-bit registry view. + + +.. _value-types: + +Value Types ++++++++++++ + +For more information, see `Registry Value Types +`__. + +.. data:: REG_BINARY + + Binary data in any form. + +.. data:: REG_DWORD + + 32-bit number. + +.. data:: REG_DWORD_LITTLE_ENDIAN + + A 32-bit number in little-endian format. + +.. data:: REG_DWORD_BIG_ENDIAN + + A 32-bit number in big-endian format. + +.. data:: REG_EXPAND_SZ + + Null-terminated string containing references to environment + variables (``%PATH%``). + +.. data:: REG_LINK + + A Unicode symbolic link. + +.. data:: REG_MULTI_SZ + + A sequence of null-terminated strings, terminated by two null characters. + (Python handles this termination automatically.) + +.. data:: REG_NONE + + No defined value type. + +.. data:: REG_RESOURCE_LIST + + A device-driver resource list. + +.. data:: REG_FULL_RESOURCE_DESCRIPTOR + + A hardware setting. + +.. data:: REG_RESOURCE_REQUIREMENTS_LIST + + A hardware resource list. + +.. data:: REG_SZ + + A null-terminated string. + + .. _handle-object: Registry Handle Objects From python-checkins at python.org Tue May 11 22:35:47 2010 From: python-checkins at python.org (brian.curtin) Date: Tue, 11 May 2010 22:35:47 +0200 (CEST) Subject: [Python-checkins] r81090 - python/branches/py3k/Doc/library/winreg.rst Message-ID: <20100511203547.33E29EC4B@mail.python.org> Author: brian.curtin Date: Tue May 11 22:35:47 2010 New Revision: 81090 Log: #8575 - Update and reorganize some _winreg contents. I've removed the hopeful note about a future higher-level module since it's been in there for quite a long time and nothing of the sort has come up. There are a few places where markup was added to cross-reference other sections, and many of the external links have been removed and now point to newly created sections containing previously undocumented information. The Value Types section was created and it's contents were taken from a function-specific area, since it applies to more than just that function. It fits in better with the other newly documented constants. Modified: python/branches/py3k/Doc/library/winreg.rst Modified: python/branches/py3k/Doc/library/winreg.rst ============================================================================== --- python/branches/py3k/Doc/library/winreg.rst (original) +++ python/branches/py3k/Doc/library/winreg.rst Tue May 11 22:35:47 2010 @@ -12,10 +12,6 @@ handles are closed correctly, even if the programmer neglects to explicitly close them. -This module exposes a very low-level interface to the Windows registry; it is -expected that in the future a new ``winreg`` module will be created offering a -higher-level interface to the registry API. - This module offers the following functions: @@ -24,9 +20,9 @@ Closes a previously opened registry key. The hkey argument specifies a previously opened key. - Note that if *hkey* is not closed using this method (or via - :meth:`handle.Close`), it is closed when the *hkey* object is destroyed by - Python. + .. note:: + If *hkey* is not closed using this method (or via :meth:`hkey.Close() `), + it is closed when the *hkey* object is destroyed by Python. .. function:: ConnectRegistry(computer_name, key) @@ -48,8 +44,8 @@ Creates or opens the specified key, returning a :ref:`handle object `. - *key* is an already open key, or one of the predefined :const:`HKEY_\*` - constants. + *key* is an already open key, or one of the predefined + :ref:`HKEY_* constants `. *sub_key* is a string that names the key this method opens or creates. @@ -67,15 +63,16 @@ Creates or opens the specified key, returning a :ref:`handle object `. - *key* is an already open key, or one of the predefined :const:`HKEY_\*` - constants. + *key* is an already open key, or one of the predefined + :ref:`HKEY_* constants `. *sub_key* is a string that names the key this method opens or creates. *res* is a reserved integer, and must be zero. The default is zero. *sam* is an integer that specifies an access mask that describes the desired - security access for the key. Default is :const:`KEY_ALL_ACCESS` + security access for the key. Default is :const:`KEY_ALL_ACCESS`. See + :ref:`Access Rights ` for other allowed values. If *key* is one of the predefined keys, *sub_key* may be ``None``. In that case, the handle returned is the same key handle passed in to the function. @@ -92,8 +89,8 @@ Deletes the specified key. - *key* is an already open key, or any one of the predefined :const:`HKEY_\*` - constants. + *key* is an already open key, or one of the predefined + :ref:`HKEY_* constants `. *sub_key* is a string that must be a subkey of the key identified by the *key* parameter. This value must not be ``None``, and the key may not have subkeys. @@ -111,10 +108,11 @@ .. note:: The :func:`DeleteKeyEx` function is implemented with the RegDeleteKeyEx Windows API function, which is specific to 64-bit versions of Windows. - See http://msdn.microsoft.com/en-us/library/ms724847%28VS.85%29.aspx + See the `RegDeleteKeyEx documentation + `__. - *key* is an already open key, or any one of the predefined :const:`HKEY_\*` - constants. + *key* is an already open key, or one of the predefined + :ref:`HKEY_* constants `. *sub_key* is a string that must be a subkey of the key identified by the *key* parameter. This value must not be ``None``, and the key may not have @@ -123,7 +121,8 @@ *res* is a reserved integer, and must be zero. The default is zero. *sam* is an integer that specifies an access mask that describes the - desired security access for the key. Default is :const:`KEY_WOW64_64KEY` + security access for the key. Default is :const:`KEY_ALL_ACCESS`. See + :ref:`Access Rights ` for other allowed values. *This method can not delete keys with subkeys.* @@ -139,8 +138,8 @@ Removes a named value from a registry key. - *key* is an already open key, or one of the predefined :const:`HKEY_\*` - constants. + *key* is an already open key, or one of the predefined + :ref:`HKEY_* constants `. *value* is a string that identifies the value to remove. @@ -149,8 +148,8 @@ Enumerates subkeys of an open registry key, returning a string. - *key* is an already open key, or any one of the predefined :const:`HKEY_\*` - constants. + *key* is an already open key, or one of the predefined + :ref:`HKEY_* constants `. *index* is an integer that identifies the index of the key to retrieve. @@ -163,8 +162,8 @@ Enumerates values of an open registry key, returning a tuple. - *key* is an already open key, or any one of the predefined :const:`HKEY_\*` - constants. + *key* is an already open key, or one of the predefined + :ref:`HKEY_* constants `. *index* is an integer that identifies the index of the value to retrieve. @@ -200,8 +199,8 @@ Writes all the attributes of a key to the registry. - *key* is an already open key, or one of the predefined :const:`HKEY_\*` - constants. + *key* is an already open key, or one of the predefined + :ref:`HKEY_* constants `. It is not necessary to call :func:`FlushKey` to change a key. Registry changes are flushed to disk by the registry using its lazy flusher. Registry changes are @@ -221,8 +220,8 @@ Creates a subkey under the specified key and stores registration information from a specified file into that subkey. - *key* is an already open key, or any of the predefined :const:`HKEY_\*` - constants. + *key* is a handle returned by :func:`ConnectRegistry` or one of the constants + :const:`HKEY_USERS` or :const:`HKEY_LOCAL_MACHINE`. *sub_key* is a string that identifies the sub_key to load. @@ -232,7 +231,9 @@ A call to LoadKey() fails if the calling process does not have the :const:`SE_RESTORE_PRIVILEGE` privilege. Note that privileges are different than - permissions -- see the Win32 documentation for more details. + from permissions -- see the `RegLoadKey documentation + `__ for + more details. If *key* is a handle returned by :func:`ConnectRegistry`, then the path specified in *fileName* is relative to the remote computer. @@ -245,15 +246,16 @@ Opens the specified key, returning a :ref:`handle object `. - *key* is an already open key, or any one of the predefined :const:`HKEY_\*` - constants. + *key* is an already open key, or one of the predefined + :ref:`HKEY_* constants `. *sub_key* is a string that identifies the sub_key to open. *res* is a reserved integer, and must be zero. The default is zero. *sam* is an integer that specifies an access mask that describes the desired - security access for the key. Default is :const:`KEY_READ`. + security access for the key. Default is :const:`KEY_READ`. See + :ref:`Access Rights ` for other allowed values. The result is a new handle to the specified key. @@ -270,8 +272,8 @@ Returns information about a key, as a tuple. - *key* is an already open key, or one of the predefined :const:`HKEY_\*` - constants. + *key* is an already open key, or one of the predefined + :ref:`HKEY_* constants `. The result is a tuple of 3 items: @@ -294,8 +296,8 @@ Retrieves the unnamed value for a key, as a string. - *key* is an already open key, or one of the predefined :const:`HKEY_\*` - constants. + *key* is an already open key, or one of the predefined + :ref:`HKEY_* constants `. *sub_key* is a string that holds the name of the subkey with which the value is associated. If this parameter is ``None`` or empty, the function retrieves the @@ -312,8 +314,8 @@ Retrieves the type and data for a specified value name associated with an open registry key. - *key* is an already open key, or one of the predefined :const:`HKEY_\*` - constants. + *key* is an already open key, or one of the predefined + :ref:`HKEY_* constants `. *value_name* is a string indicating the value to query. @@ -333,8 +335,8 @@ Saves the specified key, and all its subkeys to the specified file. - *key* is an already open key, or one of the predefined :const:`HKEY_\*` - constants. + *key* is an already open key, or one of the predefined + :ref:`HKEY_* constants `. *file_name* is the name of the file to save registry data to. This file cannot already exist. If this filename includes an extension, it cannot be used on file @@ -344,8 +346,10 @@ If *key* represents a key on a remote computer, the path described by *file_name* is relative to the remote computer. The caller of this method must possess the :const:`SeBackupPrivilege` security privilege. Note that - privileges are different than permissions -- see the Win32 documentation for - more details. + privileges are different than permissions -- see the + `Conflicts Between User Rights and Permissions documentation + `__ + for more details. This function passes NULL for *security_attributes* to the API. @@ -354,8 +358,8 @@ Associates a value with a specified key. - *key* is an already open key, or one of the predefined :const:`HKEY_\*` - constants. + *key* is an already open key, or one of the predefined + :ref:`HKEY_* constants `. *sub_key* is a string that names the subkey with which the value is associated. @@ -380,42 +384,14 @@ Stores data in the value field of an open registry key. - *key* is an already open key, or one of the predefined :const:`HKEY_\*` - constants. + *key* is an already open key, or one of the predefined + :ref:`HKEY_* constants `. *value_name* is a string that names the subkey with which the value is associated. - *type* is an integer that specifies the type of the data. This should be one - of the following constants defined in this module: - - +----------------------------------+---------------------------------------------+ - | Constant | Meaning | - +==================================+=============================================+ - | :const:`REG_BINARY` | Binary data in any form. | - +----------------------------------+---------------------------------------------+ - | :const:`REG_DWORD` | A 32-bit number. | - +----------------------------------+---------------------------------------------+ - | :const:`REG_DWORD_LITTLE_ENDIAN` | A 32-bit number in little-endian format. | - +----------------------------------+---------------------------------------------+ - | :const:`REG_DWORD_BIG_ENDIAN` | A 32-bit number in big-endian format. | - +----------------------------------+---------------------------------------------+ - | :const:`REG_EXPAND_SZ` | Null-terminated string containing | - | | references to environment variables | - | | (``%PATH%``). | - +----------------------------------+---------------------------------------------+ - | :const:`REG_LINK` | A Unicode symbolic link. | - +----------------------------------+---------------------------------------------+ - | :const:`REG_MULTI_SZ` | A sequence of null-terminated strings, | - | | terminated by two null characters. (Python | - | | handles this termination automatically.) | - +----------------------------------+---------------------------------------------+ - | :const:`REG_NONE` | No defined value type. | - +----------------------------------+---------------------------------------------+ - | :const:`REG_RESOURCE_LIST` | A device-driver resource list. | - +----------------------------------+---------------------------------------------+ - | :const:`REG_SZ` | A null-terminated string. | - +----------------------------------+---------------------------------------------+ + *type* is an integer that specifies the type of the data. See + :ref:`Value Types ` for the available types. *reserved* can be anything -- zero is always passed to the API. @@ -437,8 +413,8 @@ Disables registry reflection for 32-bit processes running on a 64-bit Operating System. - *key* is an already open key, or one of the predefined :const:`HKEY_\*` - constants. + *key* is an already open key, or one of the predefined + :ref:`HKEY_* constants `. Will generally raise :exc:`NotImplemented` if executed on a 32-bit Operating System. @@ -452,8 +428,8 @@ Restores registry reflection for the specified disabled key. - *key* is an already open key, or one of the predefined :const:`HKEY_\*` - constants. + *key* is an already open key, or one of the predefined + :ref:`HKEY_* constants `. Will generally raise :exc:`NotImplemented` if executed on a 32-bit Operating System. @@ -465,8 +441,8 @@ Determines the reflection state for the specified key. - *key* is an already open key, or one of the predefined :const:`HKEY_\*` - constants. + *key* is an already open key, or one of the predefined + :ref:`HKEY_* constants `. Returns ``True`` if reflection is disabled. @@ -474,6 +450,195 @@ Operating System. +.. _constants: + +Constants +------------------ + +The following constants are defined for use in many :mod:`_winreg` functions. + +.. _hkey-constants: + +HKEY_* Constants +++++++++++++++++ + +.. data:: HKEY_CLASSES_ROOT + + Registry entries subordinate to this key define types (or classes) of + documents and the properties associated with those types. Shell and + COM applications use the information stored under this key. + + +.. data:: HKEY_CURRENT_USER + + Registry entries subordinate to this key define the preferences of + the current user. These preferences include the settings of + environment variables, data about program groups, colors, printers, + network connections, and application preferences. + +.. data:: HKEY_LOCAL_MACHINE + + Registry entries subordinate to this key define the physical state + of the computer, including data about the bus type, system memory, + and installed hardware and software. + +.. data:: HKEY_USERS + + Registry entries subordinate to this key define the default user + configuration for new users on the local computer and the user + configuration for the current user. + +.. data:: HKEY_PERFORMANCE_DATA + + Registry entries subordinate to this key allow you to access + performance data. The data is not actually stored in the registry; + the registry functions cause the system to collect the data from + its source. + + +.. data:: HKEY_CURRENT_CONFIG + + Contains information about the current hardware profile of the + local computer system. + +.. data:: HKEY_DYN_DATA + + This key is not used in versions of Windows after 98. + + +.. _access-rights: + +Access Rights ++++++++++++++ + +For more information, see `Registry Key Security and Access +`__. + +.. data:: KEY_ALL_ACCESS + + Combines the STANDARD_RIGHTS_REQUIRED, :const:`KEY_QUERY_VALUE`, + :const:`KEY_SET_VALUE`, :const:`KEY_CREATE_SUB_KEY`, + :const:`KEY_ENUMERATE_SUB_KEYS`, :const:`KEY_NOTIFY`, + and :const:`KEY_CREATE_LINK` access rights. + +.. data:: KEY_WRITE + + Combines the STANDARD_RIGHTS_WRITE, :const:`KEY_SET_VALUE`, and + :const:`KEY_CREATE_SUB_KEY` access rights. + +.. data:: KEY_READ + + Combines the STANDARD_RIGHTS_READ, :const:`KEY_QUERY_VALUE`, + :const:`KEY_ENUMERATE_SUB_KEYS`, and :const:`KEY_NOTIFY` values. + +.. data:: KEY_EXECUTE + + Equivalent to :const:`KEY_READ`. + +.. data:: KEY_QUERY_VALUE + + Required to query the values of a registry key. + +.. data:: KEY_SET_VALUE + + Required to create, delete, or set a registry value. + +.. data:: KEY_CREATE_SUB_KEY + + Required to create a subkey of a registry key. + +.. data:: KEY_ENUMERATE_SUB_KEYS + + Required to enumerate the subkeys of a registry key. + +.. data:: KEY_NOTIFY + + Required to request change notifications for a registry key or for + subkeys of a registry key. + +.. data:: KEY_CREATE_LINK + + Reserved for system use. + + +.. _64-bit-access-rights: + +64-bit Specific +*************** + +For more information, see `Accesing an Alternate Registry View +`__. + +.. data:: KEY_WOW64_64KEY + + Indicates that an application on 64-bit Windows should operate on + the 64-bit registry view. + +.. data:: KEY_WOW64_32KEY + + Indicates that an application on 64-bit Windows should operate on + the 32-bit registry view. + + +.. _value-types: + +Value Types ++++++++++++ + +For more information, see `Registry Value Types +`__. + +.. data:: REG_BINARY + + Binary data in any form. + +.. data:: REG_DWORD + + 32-bit number. + +.. data:: REG_DWORD_LITTLE_ENDIAN + + A 32-bit number in little-endian format. + +.. data:: REG_DWORD_BIG_ENDIAN + + A 32-bit number in big-endian format. + +.. data:: REG_EXPAND_SZ + + Null-terminated string containing references to environment + variables (``%PATH%``). + +.. data:: REG_LINK + + A Unicode symbolic link. + +.. data:: REG_MULTI_SZ + + A sequence of null-terminated strings, terminated by two null characters. + (Python handles this termination automatically.) + +.. data:: REG_NONE + + No defined value type. + +.. data:: REG_RESOURCE_LIST + + A device-driver resource list. + +.. data:: REG_FULL_RESOURCE_DESCRIPTOR + + A hardware setting. + +.. data:: REG_RESOURCE_REQUIREMENTS_LIST + + A hardware resource list. + +.. data:: REG_SZ + + A null-terminated string. + + .. _handle-object: Registry Handle Objects From python-checkins at python.org Tue May 11 22:46:13 2010 From: python-checkins at python.org (brian.curtin) Date: Tue, 11 May 2010 22:46:13 +0200 (CEST) Subject: [Python-checkins] r81091 - in python/branches/release31-maint: Doc/library/winreg.rst Message-ID: <20100511204613.2F675EE9D5@mail.python.org> Author: brian.curtin Date: Tue May 11 22:46:12 2010 New Revision: 81091 Log: Backport of r81090, plus the exposure of the previously undocumented *ReflectionKey functions. Apparently that was not backported. Merged revisions 81090 via svnmerge from svn+ssh://pythondev at svn.python.org/python/branches/py3k ........ r81090 | brian.curtin | 2010-05-11 15:35:47 -0500 (Tue, 11 May 2010) | 13 lines #8575 - Update and reorganize some _winreg contents. I've removed the hopeful note about a future higher-level module since it's been in there for quite a long time and nothing of the sort has come up. There are a few places where markup was added to cross-reference other sections, and many of the external links have been removed and now point to newly created sections containing previously undocumented information. The Value Types section was created and it's contents were taken from a function-specific area, since it applies to more than just that function. It fits in better with the other newly documented constants. ........ Modified: python/branches/release31-maint/ (props changed) python/branches/release31-maint/Doc/library/winreg.rst Modified: python/branches/release31-maint/Doc/library/winreg.rst ============================================================================== --- python/branches/release31-maint/Doc/library/winreg.rst (original) +++ python/branches/release31-maint/Doc/library/winreg.rst Tue May 11 22:46:12 2010 @@ -12,10 +12,6 @@ handles are closed correctly, even if the programmer neglects to explicitly close them. -This module exposes a very low-level interface to the Windows registry; it is -expected that in the future a new ``winreg`` module will be created offering a -higher-level interface to the registry API. - This module offers the following functions: @@ -24,9 +20,9 @@ Closes a previously opened registry key. The hkey argument specifies a previously opened key. - Note that if *hkey* is not closed using this method (or via - :meth:`handle.Close`), it is closed when the *hkey* object is destroyed by - Python. + .. note:: + If *hkey* is not closed using this method (or via :meth:`hkey.Close() `), + it is closed when the *hkey* object is destroyed by Python. .. function:: ConnectRegistry(computer_name, key) @@ -48,8 +44,8 @@ Creates or opens the specified key, returning a :ref:`handle object `. - *key* is an already open key, or one of the predefined :const:`HKEY_\*` - constants. + *key* is an already open key, or one of the predefined + :ref:`HKEY_* constants `. *sub_key* is a string that names the key this method opens or creates. @@ -66,8 +62,8 @@ Deletes the specified key. - *key* is an already open key, or any one of the predefined :const:`HKEY_\*` - constants. + *key* is an already open key, or one of the predefined + :ref:`HKEY_* constants `. *sub_key* is a string that must be a subkey of the key identified by the *key* parameter. This value must not be ``None``, and the key may not have subkeys. @@ -82,8 +78,8 @@ Removes a named value from a registry key. - *key* is an already open key, or one of the predefined :const:`HKEY_\*` - constants. + *key* is an already open key, or one of the predefined + :ref:`HKEY_* constants `. *value* is a string that identifies the value to remove. @@ -92,8 +88,8 @@ Enumerates subkeys of an open registry key, returning a string. - *key* is an already open key, or any one of the predefined :const:`HKEY_\*` - constants. + *key* is an already open key, or one of the predefined + :ref:`HKEY_* constants `. *index* is an integer that identifies the index of the key to retrieve. @@ -106,8 +102,8 @@ Enumerates values of an open registry key, returning a tuple. - *key* is an already open key, or any one of the predefined :const:`HKEY_\*` - constants. + *key* is an already open key, or one of the predefined + :ref:`HKEY_* constants `. *index* is an integer that identifies the index of the value to retrieve. @@ -143,8 +139,8 @@ Writes all the attributes of a key to the registry. - *key* is an already open key, or one of the predefined :const:`HKEY_\*` - constants. + *key* is an already open key, or one of the predefined + :ref:`HKEY_* constants `. It is not necessary to call :func:`FlushKey` to change a key. Registry changes are flushed to disk by the registry using its lazy flusher. Registry changes are @@ -164,8 +160,8 @@ Creates a subkey under the specified key and stores registration information from a specified file into that subkey. - *key* is an already open key, or any of the predefined :const:`HKEY_\*` - constants. + *key* is a handle returned by :func:`ConnectRegistry` or one of the constants + :const:`HKEY_USERS` or :const:`HKEY_LOCAL_MACHINE`. *sub_key* is a string that identifies the sub_key to load. @@ -175,7 +171,9 @@ A call to LoadKey() fails if the calling process does not have the :const:`SE_RESTORE_PRIVILEGE` privilege. Note that privileges are different than - permissions -- see the Win32 documentation for more details. + from permissions -- see the `RegLoadKey documentation + `__ for + more details. If *key* is a handle returned by :func:`ConnectRegistry`, then the path specified in *fileName* is relative to the remote computer. @@ -188,15 +186,16 @@ Opens the specified key, returning a :ref:`handle object `. - *key* is an already open key, or any one of the predefined :const:`HKEY_\*` - constants. + *key* is an already open key, or one of the predefined + :ref:`HKEY_* constants `. *sub_key* is a string that identifies the sub_key to open. *res* is a reserved integer, and must be zero. The default is zero. *sam* is an integer that specifies an access mask that describes the desired - security access for the key. Default is :const:`KEY_READ`. + security access for the key. Default is :const:`KEY_READ`. See + :ref:`Access Rights ` for other allowed values. The result is a new handle to the specified key. @@ -213,8 +212,8 @@ Returns information about a key, as a tuple. - *key* is an already open key, or one of the predefined :const:`HKEY_\*` - constants. + *key* is an already open key, or one of the predefined + :ref:`HKEY_* constants `. The result is a tuple of 3 items: @@ -237,8 +236,8 @@ Retrieves the unnamed value for a key, as a string. - *key* is an already open key, or one of the predefined :const:`HKEY_\*` - constants. + *key* is an already open key, or one of the predefined + :ref:`HKEY_* constants `. *sub_key* is a string that holds the name of the subkey with which the value is associated. If this parameter is ``None`` or empty, the function retrieves the @@ -255,8 +254,8 @@ Retrieves the type and data for a specified value name associated with an open registry key. - *key* is an already open key, or one of the predefined :const:`HKEY_\*` - constants. + *key* is an already open key, or one of the predefined + :ref:`HKEY_* constants `. *value_name* is a string indicating the value to query. @@ -276,8 +275,8 @@ Saves the specified key, and all its subkeys to the specified file. - *key* is an already open key, or one of the predefined :const:`HKEY_\*` - constants. + *key* is an already open key, or one of the predefined + :ref:`HKEY_* constants `. *file_name* is the name of the file to save registry data to. This file cannot already exist. If this filename includes an extension, it cannot be used on file @@ -287,8 +286,10 @@ If *key* represents a key on a remote computer, the path described by *file_name* is relative to the remote computer. The caller of this method must possess the :const:`SeBackupPrivilege` security privilege. Note that - privileges are different than permissions -- see the Win32 documentation for - more details. + privileges are different than permissions -- see the + `Conflicts Between User Rights and Permissions documentation + `__ + for more details. This function passes NULL for *security_attributes* to the API. @@ -297,8 +298,8 @@ Associates a value with a specified key. - *key* is an already open key, or one of the predefined :const:`HKEY_\*` - constants. + *key* is an already open key, or one of the predefined + :ref:`HKEY_* constants `. *sub_key* is a string that names the subkey with which the value is associated. @@ -323,42 +324,14 @@ Stores data in the value field of an open registry key. - *key* is an already open key, or one of the predefined :const:`HKEY_\*` - constants. + *key* is an already open key, or one of the predefined + :ref:`HKEY_* constants `. *value_name* is a string that names the subkey with which the value is associated. - *type* is an integer that specifies the type of the data. This should be one - of the following constants defined in this module: - - +----------------------------------+---------------------------------------------+ - | Constant | Meaning | - +==================================+=============================================+ - | :const:`REG_BINARY` | Binary data in any form. | - +----------------------------------+---------------------------------------------+ - | :const:`REG_DWORD` | A 32-bit number. | - +----------------------------------+---------------------------------------------+ - | :const:`REG_DWORD_LITTLE_ENDIAN` | A 32-bit number in little-endian format. | - +----------------------------------+---------------------------------------------+ - | :const:`REG_DWORD_BIG_ENDIAN` | A 32-bit number in big-endian format. | - +----------------------------------+---------------------------------------------+ - | :const:`REG_EXPAND_SZ` | Null-terminated string containing | - | | references to environment variables | - | | (``%PATH%``). | - +----------------------------------+---------------------------------------------+ - | :const:`REG_LINK` | A Unicode symbolic link. | - +----------------------------------+---------------------------------------------+ - | :const:`REG_MULTI_SZ` | A sequence of null-terminated strings, | - | | terminated by two null characters. (Python | - | | handles this termination automatically.) | - +----------------------------------+---------------------------------------------+ - | :const:`REG_NONE` | No defined value type. | - +----------------------------------+---------------------------------------------+ - | :const:`REG_RESOURCE_LIST` | A device-driver resource list. | - +----------------------------------+---------------------------------------------+ - | :const:`REG_SZ` | A null-terminated string. | - +----------------------------------+---------------------------------------------+ + *type* is an integer that specifies the type of the data. See + :ref:`Value Types ` for the available types. *reserved* can be anything -- zero is always passed to the API. @@ -375,6 +348,237 @@ registry. This helps the registry perform efficiently. +.. function:: DisableReflectionKey(key) + + Disables registry reflection for 32-bit processes running on a 64-bit + Operating System. + + *key* is an already open key, or one of the predefined + :ref:`HKEY_* constants `. + + Will generally raise :exc:`NotImplemented` if executed on a 32-bit + Operating System. + + If the key is not on the reflection list, the function succeeds but has no + effect. Disabling reflection for a key does not affect reflection of any + subkeys. + + +.. function:: EnableReflectionKey(key) + + Restores registry reflection for the specified disabled key. + + *key* is an already open key, or one of the predefined + :ref:`HKEY_* constants `. + + Will generally raise :exc:`NotImplemented` if executed on a 32-bit + Operating System. + + Restoring reflection for a key does not affect reflection of any subkeys. + + +.. function:: QueryReflectionKey(key) + + Determines the reflection state for the specified key. + + *key* is an already open key, or one of the predefined + :ref:`HKEY_* constants `. + + Returns ``True`` if reflection is disabled. + + Will generally raise :exc:`NotImplemented` if executed on a 32-bit + Operating System. + + +.. _constants: + +Constants +------------------ + +The following constants are defined for use in many :mod:`_winreg` functions. + +.. _hkey-constants: + +HKEY_* Constants +++++++++++++++++ + +.. data:: HKEY_CLASSES_ROOT + + Registry entries subordinate to this key define types (or classes) of + documents and the properties associated with those types. Shell and + COM applications use the information stored under this key. + + +.. data:: HKEY_CURRENT_USER + + Registry entries subordinate to this key define the preferences of + the current user. These preferences include the settings of + environment variables, data about program groups, colors, printers, + network connections, and application preferences. + +.. data:: HKEY_LOCAL_MACHINE + + Registry entries subordinate to this key define the physical state + of the computer, including data about the bus type, system memory, + and installed hardware and software. + +.. data:: HKEY_USERS + + Registry entries subordinate to this key define the default user + configuration for new users on the local computer and the user + configuration for the current user. + +.. data:: HKEY_PERFORMANCE_DATA + + Registry entries subordinate to this key allow you to access + performance data. The data is not actually stored in the registry; + the registry functions cause the system to collect the data from + its source. + + +.. data:: HKEY_CURRENT_CONFIG + + Contains information about the current hardware profile of the + local computer system. + +.. data:: HKEY_DYN_DATA + + This key is not used in versions of Windows after 98. + + +.. _access-rights: + +Access Rights ++++++++++++++ + +For more information, see `Registry Key Security and Access +`__. + +.. data:: KEY_ALL_ACCESS + + Combines the STANDARD_RIGHTS_REQUIRED, :const:`KEY_QUERY_VALUE`, + :const:`KEY_SET_VALUE`, :const:`KEY_CREATE_SUB_KEY`, + :const:`KEY_ENUMERATE_SUB_KEYS`, :const:`KEY_NOTIFY`, + and :const:`KEY_CREATE_LINK` access rights. + +.. data:: KEY_WRITE + + Combines the STANDARD_RIGHTS_WRITE, :const:`KEY_SET_VALUE`, and + :const:`KEY_CREATE_SUB_KEY` access rights. + +.. data:: KEY_READ + + Combines the STANDARD_RIGHTS_READ, :const:`KEY_QUERY_VALUE`, + :const:`KEY_ENUMERATE_SUB_KEYS`, and :const:`KEY_NOTIFY` values. + +.. data:: KEY_EXECUTE + + Equivalent to :const:`KEY_READ`. + +.. data:: KEY_QUERY_VALUE + + Required to query the values of a registry key. + +.. data:: KEY_SET_VALUE + + Required to create, delete, or set a registry value. + +.. data:: KEY_CREATE_SUB_KEY + + Required to create a subkey of a registry key. + +.. data:: KEY_ENUMERATE_SUB_KEYS + + Required to enumerate the subkeys of a registry key. + +.. data:: KEY_NOTIFY + + Required to request change notifications for a registry key or for + subkeys of a registry key. + +.. data:: KEY_CREATE_LINK + + Reserved for system use. + + +.. _64-bit-access-rights: + +64-bit Specific +*************** + +For more information, see `Accesing an Alternate Registry View +`__. + +.. data:: KEY_WOW64_64KEY + + Indicates that an application on 64-bit Windows should operate on + the 64-bit registry view. + +.. data:: KEY_WOW64_32KEY + + Indicates that an application on 64-bit Windows should operate on + the 32-bit registry view. + + +.. _value-types: + +Value Types ++++++++++++ + +For more information, see `Registry Value Types +`__. + +.. data:: REG_BINARY + + Binary data in any form. + +.. data:: REG_DWORD + + 32-bit number. + +.. data:: REG_DWORD_LITTLE_ENDIAN + + A 32-bit number in little-endian format. + +.. data:: REG_DWORD_BIG_ENDIAN + + A 32-bit number in big-endian format. + +.. data:: REG_EXPAND_SZ + + Null-terminated string containing references to environment + variables (``%PATH%``). + +.. data:: REG_LINK + + A Unicode symbolic link. + +.. data:: REG_MULTI_SZ + + A sequence of null-terminated strings, terminated by two null characters. + (Python handles this termination automatically.) + +.. data:: REG_NONE + + No defined value type. + +.. data:: REG_RESOURCE_LIST + + A device-driver resource list. + +.. data:: REG_FULL_RESOURCE_DESCRIPTOR + + A hardware setting. + +.. data:: REG_RESOURCE_REQUIREMENTS_LIST + + A hardware resource list. + +.. data:: REG_SZ + + A null-terminated string. + + .. _handle-object: Registry Handle Objects From python-checkins at python.org Wed May 12 00:05:24 2010 From: python-checkins at python.org (collin.winter) Date: Wed, 12 May 2010 00:05:24 +0200 (CEST) Subject: [Python-checkins] r81092 - in python/branches/py3k-jit: Doc/library/winreg.rst Modules/_cursesmodule.c Message-ID: <20100511220524.D7E09EE9C4@mail.python.org> Author: collin.winter Date: Wed May 12 00:05:24 2010 New Revision: 81092 Log: Merged revisions 81085,81090 via svnmerge from svn+ssh://pythondev at svn.python.org/python/branches/py3k ........ r81085 | mark.dickinson | 2010-05-11 10:57:09 -0700 (Tue, 11 May 2010) | 1 line Issue #8677: Make curses module PY_SSIZE_T_CLEAN. ........ r81090 | brian.curtin | 2010-05-11 13:35:47 -0700 (Tue, 11 May 2010) | 13 lines #8575 - Update and reorganize some _winreg contents. I've removed the hopeful note about a future higher-level module since it's been in there for quite a long time and nothing of the sort has come up. There are a few places where markup was added to cross-reference other sections, and many of the external links have been removed and now point to newly created sections containing previously undocumented information. The Value Types section was created and it's contents were taken from a function-specific area, since it applies to more than just that function. It fits in better with the other newly documented constants. ........ Modified: python/branches/py3k-jit/ (props changed) python/branches/py3k-jit/Doc/library/winreg.rst python/branches/py3k-jit/Modules/_cursesmodule.c Modified: python/branches/py3k-jit/Doc/library/winreg.rst ============================================================================== --- python/branches/py3k-jit/Doc/library/winreg.rst (original) +++ python/branches/py3k-jit/Doc/library/winreg.rst Wed May 12 00:05:24 2010 @@ -12,10 +12,6 @@ handles are closed correctly, even if the programmer neglects to explicitly close them. -This module exposes a very low-level interface to the Windows registry; it is -expected that in the future a new ``winreg`` module will be created offering a -higher-level interface to the registry API. - This module offers the following functions: @@ -24,9 +20,9 @@ Closes a previously opened registry key. The hkey argument specifies a previously opened key. - Note that if *hkey* is not closed using this method (or via - :meth:`handle.Close`), it is closed when the *hkey* object is destroyed by - Python. + .. note:: + If *hkey* is not closed using this method (or via :meth:`hkey.Close() `), + it is closed when the *hkey* object is destroyed by Python. .. function:: ConnectRegistry(computer_name, key) @@ -48,8 +44,8 @@ Creates or opens the specified key, returning a :ref:`handle object `. - *key* is an already open key, or one of the predefined :const:`HKEY_\*` - constants. + *key* is an already open key, or one of the predefined + :ref:`HKEY_* constants `. *sub_key* is a string that names the key this method opens or creates. @@ -67,15 +63,16 @@ Creates or opens the specified key, returning a :ref:`handle object `. - *key* is an already open key, or one of the predefined :const:`HKEY_\*` - constants. + *key* is an already open key, or one of the predefined + :ref:`HKEY_* constants `. *sub_key* is a string that names the key this method opens or creates. *res* is a reserved integer, and must be zero. The default is zero. *sam* is an integer that specifies an access mask that describes the desired - security access for the key. Default is :const:`KEY_ALL_ACCESS` + security access for the key. Default is :const:`KEY_ALL_ACCESS`. See + :ref:`Access Rights ` for other allowed values. If *key* is one of the predefined keys, *sub_key* may be ``None``. In that case, the handle returned is the same key handle passed in to the function. @@ -92,8 +89,8 @@ Deletes the specified key. - *key* is an already open key, or any one of the predefined :const:`HKEY_\*` - constants. + *key* is an already open key, or one of the predefined + :ref:`HKEY_* constants `. *sub_key* is a string that must be a subkey of the key identified by the *key* parameter. This value must not be ``None``, and the key may not have subkeys. @@ -111,10 +108,11 @@ .. note:: The :func:`DeleteKeyEx` function is implemented with the RegDeleteKeyEx Windows API function, which is specific to 64-bit versions of Windows. - See http://msdn.microsoft.com/en-us/library/ms724847%28VS.85%29.aspx + See the `RegDeleteKeyEx documentation + `__. - *key* is an already open key, or any one of the predefined :const:`HKEY_\*` - constants. + *key* is an already open key, or one of the predefined + :ref:`HKEY_* constants `. *sub_key* is a string that must be a subkey of the key identified by the *key* parameter. This value must not be ``None``, and the key may not have @@ -123,7 +121,8 @@ *res* is a reserved integer, and must be zero. The default is zero. *sam* is an integer that specifies an access mask that describes the - desired security access for the key. Default is :const:`KEY_WOW64_64KEY` + security access for the key. Default is :const:`KEY_ALL_ACCESS`. See + :ref:`Access Rights ` for other allowed values. *This method can not delete keys with subkeys.* @@ -139,8 +138,8 @@ Removes a named value from a registry key. - *key* is an already open key, or one of the predefined :const:`HKEY_\*` - constants. + *key* is an already open key, or one of the predefined + :ref:`HKEY_* constants `. *value* is a string that identifies the value to remove. @@ -149,8 +148,8 @@ Enumerates subkeys of an open registry key, returning a string. - *key* is an already open key, or any one of the predefined :const:`HKEY_\*` - constants. + *key* is an already open key, or one of the predefined + :ref:`HKEY_* constants `. *index* is an integer that identifies the index of the key to retrieve. @@ -163,8 +162,8 @@ Enumerates values of an open registry key, returning a tuple. - *key* is an already open key, or any one of the predefined :const:`HKEY_\*` - constants. + *key* is an already open key, or one of the predefined + :ref:`HKEY_* constants `. *index* is an integer that identifies the index of the value to retrieve. @@ -200,8 +199,8 @@ Writes all the attributes of a key to the registry. - *key* is an already open key, or one of the predefined :const:`HKEY_\*` - constants. + *key* is an already open key, or one of the predefined + :ref:`HKEY_* constants `. It is not necessary to call :func:`FlushKey` to change a key. Registry changes are flushed to disk by the registry using its lazy flusher. Registry changes are @@ -221,8 +220,8 @@ Creates a subkey under the specified key and stores registration information from a specified file into that subkey. - *key* is an already open key, or any of the predefined :const:`HKEY_\*` - constants. + *key* is a handle returned by :func:`ConnectRegistry` or one of the constants + :const:`HKEY_USERS` or :const:`HKEY_LOCAL_MACHINE`. *sub_key* is a string that identifies the sub_key to load. @@ -232,7 +231,9 @@ A call to LoadKey() fails if the calling process does not have the :const:`SE_RESTORE_PRIVILEGE` privilege. Note that privileges are different than - permissions -- see the Win32 documentation for more details. + from permissions -- see the `RegLoadKey documentation + `__ for + more details. If *key* is a handle returned by :func:`ConnectRegistry`, then the path specified in *fileName* is relative to the remote computer. @@ -245,15 +246,16 @@ Opens the specified key, returning a :ref:`handle object `. - *key* is an already open key, or any one of the predefined :const:`HKEY_\*` - constants. + *key* is an already open key, or one of the predefined + :ref:`HKEY_* constants `. *sub_key* is a string that identifies the sub_key to open. *res* is a reserved integer, and must be zero. The default is zero. *sam* is an integer that specifies an access mask that describes the desired - security access for the key. Default is :const:`KEY_READ`. + security access for the key. Default is :const:`KEY_READ`. See + :ref:`Access Rights ` for other allowed values. The result is a new handle to the specified key. @@ -270,8 +272,8 @@ Returns information about a key, as a tuple. - *key* is an already open key, or one of the predefined :const:`HKEY_\*` - constants. + *key* is an already open key, or one of the predefined + :ref:`HKEY_* constants `. The result is a tuple of 3 items: @@ -294,8 +296,8 @@ Retrieves the unnamed value for a key, as a string. - *key* is an already open key, or one of the predefined :const:`HKEY_\*` - constants. + *key* is an already open key, or one of the predefined + :ref:`HKEY_* constants `. *sub_key* is a string that holds the name of the subkey with which the value is associated. If this parameter is ``None`` or empty, the function retrieves the @@ -312,8 +314,8 @@ Retrieves the type and data for a specified value name associated with an open registry key. - *key* is an already open key, or one of the predefined :const:`HKEY_\*` - constants. + *key* is an already open key, or one of the predefined + :ref:`HKEY_* constants `. *value_name* is a string indicating the value to query. @@ -333,8 +335,8 @@ Saves the specified key, and all its subkeys to the specified file. - *key* is an already open key, or one of the predefined :const:`HKEY_\*` - constants. + *key* is an already open key, or one of the predefined + :ref:`HKEY_* constants `. *file_name* is the name of the file to save registry data to. This file cannot already exist. If this filename includes an extension, it cannot be used on file @@ -344,8 +346,10 @@ If *key* represents a key on a remote computer, the path described by *file_name* is relative to the remote computer. The caller of this method must possess the :const:`SeBackupPrivilege` security privilege. Note that - privileges are different than permissions -- see the Win32 documentation for - more details. + privileges are different than permissions -- see the + `Conflicts Between User Rights and Permissions documentation + `__ + for more details. This function passes NULL for *security_attributes* to the API. @@ -354,8 +358,8 @@ Associates a value with a specified key. - *key* is an already open key, or one of the predefined :const:`HKEY_\*` - constants. + *key* is an already open key, or one of the predefined + :ref:`HKEY_* constants `. *sub_key* is a string that names the subkey with which the value is associated. @@ -380,42 +384,14 @@ Stores data in the value field of an open registry key. - *key* is an already open key, or one of the predefined :const:`HKEY_\*` - constants. + *key* is an already open key, or one of the predefined + :ref:`HKEY_* constants `. *value_name* is a string that names the subkey with which the value is associated. - *type* is an integer that specifies the type of the data. This should be one - of the following constants defined in this module: - - +----------------------------------+---------------------------------------------+ - | Constant | Meaning | - +==================================+=============================================+ - | :const:`REG_BINARY` | Binary data in any form. | - +----------------------------------+---------------------------------------------+ - | :const:`REG_DWORD` | A 32-bit number. | - +----------------------------------+---------------------------------------------+ - | :const:`REG_DWORD_LITTLE_ENDIAN` | A 32-bit number in little-endian format. | - +----------------------------------+---------------------------------------------+ - | :const:`REG_DWORD_BIG_ENDIAN` | A 32-bit number in big-endian format. | - +----------------------------------+---------------------------------------------+ - | :const:`REG_EXPAND_SZ` | Null-terminated string containing | - | | references to environment variables | - | | (``%PATH%``). | - +----------------------------------+---------------------------------------------+ - | :const:`REG_LINK` | A Unicode symbolic link. | - +----------------------------------+---------------------------------------------+ - | :const:`REG_MULTI_SZ` | A sequence of null-terminated strings, | - | | terminated by two null characters. (Python | - | | handles this termination automatically.) | - +----------------------------------+---------------------------------------------+ - | :const:`REG_NONE` | No defined value type. | - +----------------------------------+---------------------------------------------+ - | :const:`REG_RESOURCE_LIST` | A device-driver resource list. | - +----------------------------------+---------------------------------------------+ - | :const:`REG_SZ` | A null-terminated string. | - +----------------------------------+---------------------------------------------+ + *type* is an integer that specifies the type of the data. See + :ref:`Value Types ` for the available types. *reserved* can be anything -- zero is always passed to the API. @@ -437,8 +413,8 @@ Disables registry reflection for 32-bit processes running on a 64-bit Operating System. - *key* is an already open key, or one of the predefined :const:`HKEY_\*` - constants. + *key* is an already open key, or one of the predefined + :ref:`HKEY_* constants `. Will generally raise :exc:`NotImplemented` if executed on a 32-bit Operating System. @@ -452,8 +428,8 @@ Restores registry reflection for the specified disabled key. - *key* is an already open key, or one of the predefined :const:`HKEY_\*` - constants. + *key* is an already open key, or one of the predefined + :ref:`HKEY_* constants `. Will generally raise :exc:`NotImplemented` if executed on a 32-bit Operating System. @@ -465,8 +441,8 @@ Determines the reflection state for the specified key. - *key* is an already open key, or one of the predefined :const:`HKEY_\*` - constants. + *key* is an already open key, or one of the predefined + :ref:`HKEY_* constants `. Returns ``True`` if reflection is disabled. @@ -474,6 +450,195 @@ Operating System. +.. _constants: + +Constants +------------------ + +The following constants are defined for use in many :mod:`_winreg` functions. + +.. _hkey-constants: + +HKEY_* Constants +++++++++++++++++ + +.. data:: HKEY_CLASSES_ROOT + + Registry entries subordinate to this key define types (or classes) of + documents and the properties associated with those types. Shell and + COM applications use the information stored under this key. + + +.. data:: HKEY_CURRENT_USER + + Registry entries subordinate to this key define the preferences of + the current user. These preferences include the settings of + environment variables, data about program groups, colors, printers, + network connections, and application preferences. + +.. data:: HKEY_LOCAL_MACHINE + + Registry entries subordinate to this key define the physical state + of the computer, including data about the bus type, system memory, + and installed hardware and software. + +.. data:: HKEY_USERS + + Registry entries subordinate to this key define the default user + configuration for new users on the local computer and the user + configuration for the current user. + +.. data:: HKEY_PERFORMANCE_DATA + + Registry entries subordinate to this key allow you to access + performance data. The data is not actually stored in the registry; + the registry functions cause the system to collect the data from + its source. + + +.. data:: HKEY_CURRENT_CONFIG + + Contains information about the current hardware profile of the + local computer system. + +.. data:: HKEY_DYN_DATA + + This key is not used in versions of Windows after 98. + + +.. _access-rights: + +Access Rights ++++++++++++++ + +For more information, see `Registry Key Security and Access +`__. + +.. data:: KEY_ALL_ACCESS + + Combines the STANDARD_RIGHTS_REQUIRED, :const:`KEY_QUERY_VALUE`, + :const:`KEY_SET_VALUE`, :const:`KEY_CREATE_SUB_KEY`, + :const:`KEY_ENUMERATE_SUB_KEYS`, :const:`KEY_NOTIFY`, + and :const:`KEY_CREATE_LINK` access rights. + +.. data:: KEY_WRITE + + Combines the STANDARD_RIGHTS_WRITE, :const:`KEY_SET_VALUE`, and + :const:`KEY_CREATE_SUB_KEY` access rights. + +.. data:: KEY_READ + + Combines the STANDARD_RIGHTS_READ, :const:`KEY_QUERY_VALUE`, + :const:`KEY_ENUMERATE_SUB_KEYS`, and :const:`KEY_NOTIFY` values. + +.. data:: KEY_EXECUTE + + Equivalent to :const:`KEY_READ`. + +.. data:: KEY_QUERY_VALUE + + Required to query the values of a registry key. + +.. data:: KEY_SET_VALUE + + Required to create, delete, or set a registry value. + +.. data:: KEY_CREATE_SUB_KEY + + Required to create a subkey of a registry key. + +.. data:: KEY_ENUMERATE_SUB_KEYS + + Required to enumerate the subkeys of a registry key. + +.. data:: KEY_NOTIFY + + Required to request change notifications for a registry key or for + subkeys of a registry key. + +.. data:: KEY_CREATE_LINK + + Reserved for system use. + + +.. _64-bit-access-rights: + +64-bit Specific +*************** + +For more information, see `Accesing an Alternate Registry View +`__. + +.. data:: KEY_WOW64_64KEY + + Indicates that an application on 64-bit Windows should operate on + the 64-bit registry view. + +.. data:: KEY_WOW64_32KEY + + Indicates that an application on 64-bit Windows should operate on + the 32-bit registry view. + + +.. _value-types: + +Value Types ++++++++++++ + +For more information, see `Registry Value Types +`__. + +.. data:: REG_BINARY + + Binary data in any form. + +.. data:: REG_DWORD + + 32-bit number. + +.. data:: REG_DWORD_LITTLE_ENDIAN + + A 32-bit number in little-endian format. + +.. data:: REG_DWORD_BIG_ENDIAN + + A 32-bit number in big-endian format. + +.. data:: REG_EXPAND_SZ + + Null-terminated string containing references to environment + variables (``%PATH%``). + +.. data:: REG_LINK + + A Unicode symbolic link. + +.. data:: REG_MULTI_SZ + + A sequence of null-terminated strings, terminated by two null characters. + (Python handles this termination automatically.) + +.. data:: REG_NONE + + No defined value type. + +.. data:: REG_RESOURCE_LIST + + A device-driver resource list. + +.. data:: REG_FULL_RESOURCE_DESCRIPTOR + + A hardware setting. + +.. data:: REG_RESOURCE_REQUIREMENTS_LIST + + A hardware resource list. + +.. data:: REG_SZ + + A null-terminated string. + + .. _handle-object: Registry Handle Objects Modified: python/branches/py3k-jit/Modules/_cursesmodule.c ============================================================================== --- python/branches/py3k-jit/Modules/_cursesmodule.c (original) +++ python/branches/py3k-jit/Modules/_cursesmodule.c Wed May 12 00:05:24 2010 @@ -100,6 +100,8 @@ /* Includes */ +#define PY_SSIZE_T_CLEAN + #include "Python.h" @@ -1382,7 +1384,7 @@ fseek(fp, 0, 0); while (1) { char buf[BUFSIZ]; - int n = fread(buf, 1, BUFSIZ, fp); + Py_ssize_t n = fread(buf, 1, BUFSIZ, fp); if (n <= 0) break; Py_DECREF(res); From python-checkins at python.org Wed May 12 00:32:18 2010 From: python-checkins at python.org (collin.winter) Date: Wed, 12 May 2010 00:32:18 +0200 (CEST) Subject: [Python-checkins] r81093 - in python/branches/py3k-jit: Lib/sysconfig.py Makefile.pre.in Misc/python-config.in Unittests/PySmallPtrSetTest.cc Unittests/StatsTest.cc Util Util/PySmallPtrSet.cc Util/PySmallPtrSet.h Util/Stats.cc Util/Stats.h configure configure.in pyconfig.h.in Message-ID: <20100511223218.91F0EE3E6@mail.python.org> Author: collin.winter Date: Wed May 12 00:32:18 2010 New Revision: 81093 Log: Hook LLVM into the py3k-jit branch's build process; add utility code and tests to verify that LLVM is working correctly. This currently builds statically against LLVM; this will be addressed in a follow-up commit. Reviewed at http://codereview.appspot.com/917043. Added: python/branches/py3k-jit/Unittests/PySmallPtrSetTest.cc python/branches/py3k-jit/Unittests/StatsTest.cc python/branches/py3k-jit/Util/ python/branches/py3k-jit/Util/PySmallPtrSet.cc python/branches/py3k-jit/Util/PySmallPtrSet.h python/branches/py3k-jit/Util/Stats.cc python/branches/py3k-jit/Util/Stats.h Modified: python/branches/py3k-jit/ (props changed) python/branches/py3k-jit/Lib/sysconfig.py python/branches/py3k-jit/Makefile.pre.in python/branches/py3k-jit/Misc/python-config.in python/branches/py3k-jit/configure python/branches/py3k-jit/configure.in python/branches/py3k-jit/pyconfig.h.in Modified: python/branches/py3k-jit/Lib/sysconfig.py ============================================================================== --- python/branches/py3k-jit/Lib/sysconfig.py (original) +++ python/branches/py3k-jit/Lib/sysconfig.py Wed May 12 00:32:18 2010 @@ -266,26 +266,52 @@ return os.path.join(get_path('stdlib'), "config", "Makefile") -def _init_posix(vars): - """Initialize the module as appropriate for POSIX systems.""" - # load the installed Makefile: - makefile = _get_makefile_filename() - try: - _parse_makefile(makefile, vars) - except IOError as e: - msg = "invalid Python installation: unable to open %s" % makefile - if hasattr(e, "strerror"): - msg = msg + " (%s)" % e.strerror - raise IOError(msg) - # load the installed pyconfig.h: - config_h = get_config_h_filename() +def _get_sysconfig_filename(): + """Return absolute pathname of the installed sysconfig file.""" + if _PYTHON_BUILD: + return os.path.join(_PROJECT_BASE, "sysconfig") + return os.path.join(get_path("stdlib"), "config", "sysconfig") + + +# Simple wrapper around parse_config_h() to simplify _parse_config_file(). +def _parse_config_h_filename(filename, g=None): + with open(filename) as fp: + return parse_config_h(fp, g) + + +def _parse_config_file(filename, parse_func, config_dict): + """Parse a config file into a common dict. + + Args: + filename: name of the config file. + parse_func: function to use to parse the file. This will be given + `filename` and `config_dict` as arguments, and should update + `config_dict` in-place. + config_dict: dictionary to update in-place. + + Raises: + IOError: if the file could not be opened. + """ try: - parse_config_h(open(config_h), vars) + parse_func(filename, config_dict) except IOError as e: - msg = "invalid Python installation: unable to open %s" % config_h + msg = "invalid Python installation: unable to open %s" % filename if hasattr(e, "strerror"): msg = msg + " (%s)" % e.strerror raise IOError(msg) + + +def _init_posix(vars): + """Initialize the module as appropriate for POSIX systems.""" + # Load the installed Makefile. + _parse_config_file(_get_makefile_filename(), _parse_makefile, vars) + + # Load the installed pyconfig.h. + _parse_config_file(get_config_h_filename(), _parse_config_h_filename, vars) + + # Load the installed sysconfig file. + _parse_config_file(_get_sysconfig_filename(), _parse_makefile, vars) + # On MacOSX we need to check the setting of the environment variable # MACOSX_DEPLOYMENT_TARGET: configure bases some choices on it so # it needs to be compatible. Modified: python/branches/py3k-jit/Makefile.pre.in ============================================================================== --- python/branches/py3k-jit/Makefile.pre.in (original) +++ python/branches/py3k-jit/Makefile.pre.in Wed May 12 00:32:18 2010 @@ -35,6 +35,7 @@ AR= @AR@ RANLIB= @RANLIB@ SVNVERSION= @SVNVERSION@ +FORCE_C= @FORCE_C@ GNULD= @GNULD@ @@ -60,10 +61,11 @@ OPT= @OPT@ BASECFLAGS= @BASECFLAGS@ CFLAGS= $(BASECFLAGS) @CFLAGS@ $(OPT) $(EXTRA_CFLAGS) +CXXFLAGS= $(BASECXXFLAGS) $(OPT) $(EXTRA_CXXFLAGS) # 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@ +CPPFLAGS= -I. -IInclude -I$(srcdir) -I$(srcdir)/Include @CPPFLAGS@ LDFLAGS= @LDFLAGS@ LDLAST= @LDLAST@ SGI_ABI= @SGI_ABI@ @@ -74,6 +76,16 @@ CFLAGSFORSHARED=@CFLAGSFORSHARED@ # C flags used for building the interpreter object files PY_CFLAGS= $(CFLAGS) $(CPPFLAGS) $(CFLAGSFORSHARED) -DPy_BUILD_CORE +PY_CXXFLAGS= $(CXXFLAGS) $(CPPFLAGS) $(CFLAGSFORSHARED) -DPy_BUILD_CORE -Wno-write-strings + +# LLVM integration options +WITH_LLVM= @WITH_LLVM@ +LLVM_CONFIG= @LLVM_CONFIG@ +LLVM_INC_DIR= @LLVM_INC_DIR@ +LLVM_BIN_DIR= @LLVM_BIN_DIR@ +LLVM_CXXFLAGS= @LLVM_CXXFLAGS@ +LLVM_LDFLAGS= @LLVM_LDFLAGS@ +LLVM_LIB_PATHS= @LLVM_LIB_PATHS@ # Machine-dependent subdirectories @@ -322,6 +334,12 @@ $(MACHDEP_OBJS) \ $(THREADOBJ) +# configure will do a LLVM_PYTHON_OBJS substitution that will expand +# to one of these. This convolution is done to support BSD make. +EMPTY= +LLVM_PYTHON_OBJS= \ + Util/PySmallPtrSet.o \ + Util/Stats.o ########################################################################## # Objects @@ -371,6 +389,7 @@ $(PARSER_OBJS) \ $(OBJECT_OBJS) \ $(PYTHON_OBJS) \ + $(@LLVM_PYTHON_OBJS@) \ $(MODULE_OBJS) \ $(SIGNAL_OBJS) \ $(MODOBJS) @@ -408,12 +427,16 @@ $(MAKE) clean $(MAKE) all CFLAGS="$(CFLAGS) -O0 -pg -fprofile-arcs -ftest-coverage" LIBS="$(LIBS) -lgcov" +sysconfig: + @case $(WITH_LLVM) in \ + 1) ( echo "LLVM_CXXFLAGS=$(LLVM_CXXFLAGS)"; echo "LLVM_LDFLAGS=$(LLVM_LDFLAGS)" ) > sysconfig;; \ + 0) touch sysconfig;; \ + esac # Build the interpreter -$(BUILDPYTHON): Modules/python.o $(LIBRARY) $(LDLIBRARY) - $(LINKCC) $(LDFLAGS) $(LINKFORSHARED) -o $@ \ - Modules/python.o \ - $(BLDLIBRARY) $(LIBS) $(MODLIBS) $(SYSLIBS) $(LDLAST) +$(BUILDPYTHON): sysconfig Modules/python.o $(LIBRARY) $(LDLIBRARY) + $(LINKCC) $(LDFLAGS) $(LINKFORSHARED) -o $@ Modules/python.o \ + $(BLDLIBRARY) $(LIBS) $(MODLIBS) $(SYSLIBS) $(LLVM_LDFLAGS) $(LDLAST) platform: $(BUILDPYTHON) $(RUNSHARED) ./$(BUILDPYTHON) -E -c 'import sys ; from sysconfig import get_platform ; print(get_platform()+"-"+sys.version[0:3])' >platform @@ -433,25 +456,25 @@ $(AR) $(ARFLAGS) $@ Modules/getbuildinfo.o $(AR) $(ARFLAGS) $@ $(PARSER_OBJS) $(AR) $(ARFLAGS) $@ $(OBJECT_OBJS) - $(AR) $(ARFLAGS) $@ $(PYTHON_OBJS) + $(AR) $(ARFLAGS) $@ $(PYTHON_OBJS) $(@LLVM_PYTHON_OBJS@) $(AR) $(ARFLAGS) $@ $(MODULE_OBJS) $(SIGNAL_OBJS) $(AR) $(ARFLAGS) $@ $(MODOBJS) $(RANLIB) $@ libpython$(VERSION).so: $(LIBRARY_OBJS) if test $(INSTSONAME) != $(LDLIBRARY); then \ - $(LDSHARED) $(LDFLAGS) -Wl,-h$(INSTSONAME) -o $(INSTSONAME) $(LIBRARY_OBJS) $(MODLIBS) $(SHLIBS) $(LIBC) $(LIBM) $(LDLAST); \ + $(LDSHARED) $(LLVM_LDFLAGS) $(LDFLAGS) -Wl,-h$(INSTSONAME) -o $(INSTSONAME) $(LIBRARY_OBJS) $(MODLIBS) $(SHLIBS) $(LIBC) $(LIBM) $(LDLAST); \ $(LN) -f $(INSTSONAME) $@; \ else \ - $(LDSHARED) $(LDFLAGS) -o $@ $(LIBRARY_OBJS) $(MODLIBS) $(SHLIBS) $(LIBC) $(LIBM) $(LDLAST); \ + $(LDSHARED) $(LLVM_LDFLAGS) $(LDFLAGS) -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 $(LLVM_LDFLAGS) $(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) $(LDFLAGS) -o $@ $(LIBRARY_OBJS) $(MODLIBS) $(SHLIBS) $(LIBC) $(LIBM) $(LDLAST) + $(LDSHARED) $(LLVM_LDFLAGS) $(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 @@ -497,7 +520,7 @@ # for a shared core library; otherwise, this rule is a noop. $(DLLLIBRARY) libpython$(VERSION).dll.a: $(LIBRARY_OBJS) if test -n "$(DLLLIBRARY)"; then \ - $(LDSHARED) $(LDFLAGS) -Wl,--out-implib=$@ -o $(DLLLIBRARY) $^ \ + $(LDSHARED) $(LLVM_LDFLAGS) $(LDFLAGS) -Wl,--out-implib=$@ -o $(DLLLIBRARY) $^ \ $(LIBS) $(MODLIBS) $(SYSLIBS) $(LDLAST); \ else true; \ fi @@ -537,6 +560,7 @@ Modules/getbuildinfo.o: $(PARSER_OBJS) \ $(OBJECT_OBJS) \ $(PYTHON_OBJS) \ + $(@LLVM_PYTHON_OBJS@) \ $(MODULE_OBJS) \ $(SIGNAL_OBJS) \ $(MODOBJS) \ @@ -717,6 +741,10 @@ # even without a C++ compiler. All commands are prefixed with - to make this # happen. +LLVM_UNITTEST_SRCS := \ + $(srcdir)/Unittests/PySmallPtrSetTest.cc \ + $(srcdir)/Unittests/StatsTest.cc + UNITTEST_SRCS := $(LIBRARY) \ $(srcdir)/Unittests/DatetimeTest.cc \ $(srcdir)/Unittests/DictTest.cc \ @@ -725,7 +753,8 @@ $(srcdir)/Unittests/ObjectTest.cc \ $(srcdir)/Unittests/UnicodeTest.cc \ $(srcdir)/Unittests/pytest_main.cc \ - Unittests/googletest/gtest.o + $(@LLVM_UNITTEST_SRCS@) \ + Unittests/googletest/gtest.o \ Unittests/googletest/gtest.o: -$(CXX) -c $(PY_CXXFLAGS) -I$(srcdir)/Unittests/googletest \ @@ -733,9 +762,13 @@ $(srcdir)/Unittests/googletest/src/gtest-all.cc # The python-config line needs to come last, or this will be broken on Linux. +# +# gcc's TR1 header depends on RTTI, so force googletest to use +# its own tuple implementation. AllUnitTests: $(UNITTEST_SRCS) $(srcdir)/Unittests/*.h build_all python-config -$(CXX) $(CPPFLAGS) -I$(srcdir)/Unittests/googletest/include -o $@ \ $(UNITTEST_SRCS) -L. $(LDFLAGS) \ + -DGTEST_HAS_RTTI=0 -DGTEST_HAS_TR1_TUPLE=0 \ `$(RUNSHARED) ./$(BUILDPYTHON) ./python-config --cflags --ldflags` @@ -1162,6 +1195,9 @@ .c.o: $(CC) -c $(PY_CFLAGS) -o $@ $< +.cc.o: + $(CXX) -c $(LLVM_CXXFLAGS) $(PY_CXXFLAGS) -o $@ $< + # Run reindent on the library reindent: ./$(BUILDPYTHON) $(srcdir)/Tools/scripts/reindent.py -r $(srcdir)/Lib @@ -1213,6 +1249,7 @@ find . -name '*.s[ol]' -exec rm -f {} ';' find build -name 'fficonfig.h' -exec rm -f {} ';' || true find build -name 'fficonfig.py' -exec rm -f {} ';' || true + rm -f sysconfig -rm -f Lib/lib2to3/*Grammar*.pickle profile-removal: Modified: python/branches/py3k-jit/Misc/python-config.in ============================================================================== --- python/branches/py3k-jit/Misc/python-config.in (original) +++ python/branches/py3k-jit/Misc/python-config.in Wed May 12 00:32:18 2010 @@ -41,6 +41,7 @@ '-I' + sysconfig.get_path('platinclude')] if opt == '--cflags': flags.extend(getvar('CFLAGS').split()) + flags.extend(getvar('LLVM_CXXFLAGS').split()) print(' '.join(flags)) elif opt in ('--libs', '--ldflags'): @@ -51,6 +52,7 @@ if opt == '--ldflags': if not getvar('Py_ENABLE_SHARED'): libs.insert(0, '-L' + getvar('LIBPL')) + libs.extend(getvar('LLVM_LDFLAGS').split()) libs.extend(getvar('LINKFORSHARED').split()) print(' '.join(libs)) Added: python/branches/py3k-jit/Unittests/PySmallPtrSetTest.cc ============================================================================== --- (empty file) +++ python/branches/py3k-jit/Unittests/PySmallPtrSetTest.cc Wed May 12 00:32:18 2010 @@ -0,0 +1,58 @@ +#include "Util/PySmallPtrSet.h" +#include "gtest/gtest.h" + + +TEST(PySmallPtrSet, Basic) +{ + PySmallPtrSet *set = PySmallPtrSet_New(); + ASSERT_TRUE(set != NULL); + EXPECT_EQ(0u, PySmallPtrSet_Size(set)); + + PyObject *five = (PyObject *)5; + PyObject *six = (PyObject *)6; + EXPECT_EQ(1, PySmallPtrSet_Insert(set, five)); + EXPECT_EQ(1u, PySmallPtrSet_Size(set)); + + // Insert additional element; size goes up. + EXPECT_EQ(1, PySmallPtrSet_Insert(set, six)); + EXPECT_EQ(2u, PySmallPtrSet_Size(set)); + + // Insert duplicate element; size unchanged. + EXPECT_EQ(0, PySmallPtrSet_Insert(set, five)); + EXPECT_EQ(2u, PySmallPtrSet_Size(set)); + + // Erase elements. + EXPECT_EQ(1, PySmallPtrSet_Erase(set, five)); + EXPECT_EQ(1, PySmallPtrSet_Erase(set, six)); + EXPECT_EQ(0u, PySmallPtrSet_Size(set)); + + // Erase missing element. + EXPECT_EQ(0, PySmallPtrSet_Erase(set, five)); + + PySmallPtrSet_Del(set); +} + + +static void +my_iter_func(PyObject *obj, void *counter) +{ + (*(int *)counter) += 2; +} + +TEST(PySmallPtrSet, Iteration) +{ + int counter = 0; + + PySmallPtrSet *set = PySmallPtrSet_New(); + ASSERT_TRUE(set != NULL); + + PyObject *five = (PyObject *)5; + PyObject *six = (PyObject *)6; + EXPECT_EQ(1, PySmallPtrSet_Insert(set, five)); + EXPECT_EQ(1, PySmallPtrSet_Insert(set, six)); + + PySmallPtrSet_ForEach(set, my_iter_func, &counter); + EXPECT_EQ(4, counter); + + PySmallPtrSet_Del(set); +} Added: python/branches/py3k-jit/Unittests/StatsTest.cc ============================================================================== --- (empty file) +++ python/branches/py3k-jit/Unittests/StatsTest.cc Wed May 12 00:32:18 2010 @@ -0,0 +1,18 @@ +#include "Util/Stats.h" +#include "llvm/ADT/STLExtras.h" +#include "gtest/gtest.h" +#include + +using llvm::array_endof; + +TEST(Stats_Median, Odd) +{ + int values[] = {1, 7, 15}; + EXPECT_EQ(7, Median(std::vector(values, array_endof(values)))); +} + +TEST(Stats_Median, Even) +{ + float values[] = {1, 7, 8, 15}; + EXPECT_EQ(7.5, Median(std::vector(values, array_endof(values)))); +} Added: python/branches/py3k-jit/Util/PySmallPtrSet.cc ============================================================================== --- (empty file) +++ python/branches/py3k-jit/Util/PySmallPtrSet.cc Wed May 12 00:32:18 2010 @@ -0,0 +1,68 @@ +#include "Util/PySmallPtrSet.h" + +#include "llvm/ADT/SmallPtrSet.h" +#include "llvm/ADT/SmallVector.h" + + +typedef llvm::SmallPtrSet PySmallPtrSet_Impl; + +typedef struct PySmallPtrSet { + PySmallPtrSet_Impl llvm_set; +} PySmallPtrSet; + + +// C'tors, d'tors +PySmallPtrSet * +PySmallPtrSet_New() +{ + PySmallPtrSet *set = PyMem_New(PySmallPtrSet, 1); + if (set == NULL) + return NULL; + new(set)PySmallPtrSet(); + + return set; +} + +void +PySmallPtrSet_Del(PySmallPtrSet *set) +{ + set->~PySmallPtrSet(); + PyMem_Free(set); +} + +int +PySmallPtrSet_Insert(PySmallPtrSet *set, PyObject *obj) +{ + return set->llvm_set.insert(obj); +} + +int +PySmallPtrSet_Erase(PySmallPtrSet *set, PyObject *obj) +{ + return set->llvm_set.erase(obj); +} + +unsigned +PySmallPtrSet_Size(PySmallPtrSet *set) +{ + return set->llvm_set.size(); +} + +int +PySmallPtrSet_Count(PySmallPtrSet *set, PyObject *obj) +{ + return set->llvm_set.count(obj); +} + +void +PySmallPtrSet_ForEach(PySmallPtrSet *set, PySmallPtrSetCallback callback, + void *callback_arg) +{ + // Copy the original set in case the callback modifies the set. + llvm::SmallVector contents(set->llvm_set.begin(), + set->llvm_set.end()); + for (llvm::SmallVector::iterator i = contents.begin(), + end = contents.end(); i != end; ++i) { + callback(*i, callback_arg); + } +} Added: python/branches/py3k-jit/Util/PySmallPtrSet.h ============================================================================== --- (empty file) +++ python/branches/py3k-jit/Util/PySmallPtrSet.h Wed May 12 00:32:18 2010 @@ -0,0 +1,51 @@ +//===----------------------------------------------------------------------===// +// +// This file defines C wrappers for an llvm::SmallPtrSet +// +//===----------------------------------------------------------------------===// + +#ifndef UTIL_PYSMALLPTRSET_H +#define UTIL_PYSMALLPTRSET_H + +#ifdef __cplusplus +extern "C" { +#endif + +#include "Python.h" + + +typedef struct PySmallPtrSet PySmallPtrSet; +typedef void(*PySmallPtrSetCallback)(PyObject *, void *); + + +// C'tors, d'tors +PySmallPtrSet *PySmallPtrSet_New(void); +void PySmallPtrSet_Del(PySmallPtrSet *); + +/// Insert - This returns 1 if the pointer was new to the set, 0 if it +/// was already in the set. +int PySmallPtrSet_Insert(PySmallPtrSet *, PyObject *); + +/// Erase - If the set contains the specified pointer, remove it and return +/// 1, otherwise return 0. +int PySmallPtrSet_Erase(PySmallPtrSet *, PyObject *); + +/// Get the size of the set. +unsigned PySmallPtrSet_Size(PySmallPtrSet *); + +/// Count - Return 1 if the specified pointer is in the set. +int PySmallPtrSet_Count(PySmallPtrSet *, PyObject *); + +// Iterating over a C++ collection from C is a major pain in the ass, so we do +// this: given a function pointer, call it once for each element in the set. +// The void * will be provided as a second argument to the callback. +// It is acceptable for the callback to modify the set; this will not change +// the iteration behaviour. +void PySmallPtrSet_ForEach(PySmallPtrSet *, PySmallPtrSetCallback, void *); + + +#ifdef __cplusplus +} +#endif + +#endif // UTIL_PYSMALLPTRSET_H Added: python/branches/py3k-jit/Util/Stats.cc ============================================================================== --- (empty file) +++ python/branches/py3k-jit/Util/Stats.cc Wed May 12 00:32:18 2010 @@ -0,0 +1,22 @@ +#include "Util/Stats.h" + +#include "pyconfig.h" + +#if HAVE_GETTIMEOFDAY +#include +int64_t Timer::GetTime() +{ + struct timeval tv; +#ifdef GETTIMEOFDAY_NO_TZ + gettimeofday(&tv); +#else + gettimeofday(&tv, 0); +#endif + return int64_t(tv.tv_sec) * 1000000000 + int64_t(tv.tv_usec) * 1000; +} +#else // Need a different definition on other platforms. +int64_t Timer::GetTime() +{ + return 0; +} +#endif // HAVE_GETTIMEOFDAY Added: python/branches/py3k-jit/Util/Stats.h ============================================================================== --- (empty file) +++ python/branches/py3k-jit/Util/Stats.h Wed May 12 00:32:18 2010 @@ -0,0 +1,93 @@ +// -*- C++ -*- +#ifndef UTIL_STATS_H +#define UTIL_STATS_H + +#ifndef __cplusplus +#error This header expects to be included only in C++ source +#endif + +#include "llvm/Support/MutexGuard.h" +#include "llvm/Support/raw_ostream.h" + +#include +#include +#include + +// Calculate the median of a given data set. This assumes that the data is +// sorted. +template +ValueTy +Median(const std::vector &data) +{ + size_t mid_point = data.size() / 2; + if (data.size() % 2 == 0) { + ValueTy first = data[mid_point]; + ValueTy second = data[mid_point - 1]; + return (first + second) / 2; + } else { + return data[mid_point]; + } +} + + +// Base class useful for collecting stats on vectors of individual data points. +// This is intended to be used with llvm::ManagedStatic and will print +// min, median, mean, max and sum statistics about the data vector when the +// process shuts down. +template +class DataVectorStats { +public: + typedef std::vector DataType; + + // Append a new data point to the vector. This is thread-safe. + void RecordDataPoint(ValueTy data_point) { + llvm::MutexGuard locked(this->lock_); + this->data_.push_back(data_point); + } + + DataVectorStats(const char *const name) : name_(name) {} + + ~DataVectorStats() { + DataType data = this->data_; + if (data.size() == 0) + return; + ValueTy sum = std::accumulate(data.begin(), data.end(), ValueTy()); + std::sort(data.begin(), data.end()); + + llvm::errs() << "\n" << this->name_ << ":\n"; + llvm::errs() << "N: " << data.size() << "\n"; + llvm::errs() << "Min: " << data[0] << "\n"; + llvm::errs() << "Median: " << Median(data) << "\n"; + llvm::errs() << "Mean: " << sum / data.size() << "\n"; + llvm::errs() << "Max: " << *(data.end() - 1) << "\n"; + llvm::errs() << "Sum: " << sum << "\n"; + } + +private: + const char *const name_; + llvm::sys::Mutex lock_; + DataType data_; +}; + +/// An instance of this class records the time in ns between its +/// construction and destruction into a DataVectorStats. +class Timer { +public: + Timer(DataVectorStats &stat) + : stat_(stat), start_time_(this->GetTime()) {} + ~Timer() { + int64_t end_time = this->GetTime(); + int64_t elapsed = end_time - this->start_time_; + stat_.RecordDataPoint(elapsed); + } +private: + // Returns the current time in nanoseconds. It doesn't matter + // what these ns count from since we only use them to compute time + // changes. + static int64_t GetTime(); + + DataVectorStats &stat_; + const int64_t start_time_; +}; + +#endif // UTIL_STATS_H Modified: python/branches/py3k-jit/configure ============================================================================== --- python/branches/py3k-jit/configure (original) +++ python/branches/py3k-jit/configure Wed May 12 00:32:18 2010 @@ -1,5 +1,5 @@ #! /bin/sh -# From configure.in Revision: 80834 . +# From configure.in Revision: 81086 . # Guess values for system-dependent variables and create Makefiles. # Generated by GNU Autoconf 2.65 for python 3.2. # @@ -625,6 +625,8 @@ LDCXXSHARED LDSHARED SO +FORCE_C +BASECXXFLAGS LIBTOOL_CRUFT OTHER_LIBTOOL_OPT UNIVERSAL_ARCH_FLAGS @@ -660,6 +662,14 @@ LDFLAGS CFLAGS CC +LLVM_LIB_PATHS +LLVM_LDFLAGS +LLVM_CXXFLAGS +LLVM_BIN_DIR +LLVM_INC_DIR +LLVM_PYTHON_OBJS +WITH_LLVM +LLVM_CONFIG EXPORT_MACOSX_DEPLOYMENT_TARGET CONFIGURE_MACOSX_DEPLOYMENT_TARGET SGI_ABI @@ -727,6 +737,7 @@ with_framework_name enable_framework with_gcc +with_llvm with_cxx_main with_suffix enable_shared @@ -742,7 +753,6 @@ with_thread enable_ipv6 with_doc_strings -with_tsc with_pymalloc with_valgrind with_wctype_functions @@ -752,10 +762,13 @@ enable_big_digits with_wide_unicode with_computed_gotos +with_instrumentation +with_tsc ' ac_precious_vars='build_alias host_alias target_alias +LLVM_CONFIG CC CFLAGS LDFLAGS @@ -1393,6 +1406,11 @@ specify an alternate name of the framework built with --enable-framework --without-gcc never use gcc + --with(out)-llvm[=DIRECTORY] + build against a preinstalled LLVM or disable LLVM + integration entirely. Note that Python built with + --without-llvm cannot load extension modules built + with --with-llvm or vice-versa. --with-cxx-main= compile main() and link python executable with C++ compiler @@ -1413,7 +1431,6 @@ --with(out)-thread[=DIRECTORY] deprecated; use --with(out)-threads --with(out)-doc-strings disable/enable documentation strings - --with(out)-tsc enable/disable timestamp counter profile --with(out)-pymalloc disable/enable specialized mallocs --with-valgrind Enable Valgrind support --with-wctype-functions use wctype.h functions @@ -1423,8 +1440,12 @@ --with-wide-unicode Use 4-byte Unicode characters (default is 2 bytes) --with-computed-gotos Use computed gotos / threaded dispatch in evaluation loop (not available on all compilers) + --with-instrumentation Compile in a bunch of runtime instrumentation useful + for optimizing Python itself. Requires --with-llvm. + --with(out)-tsc enable/disable timestamp counter profile Some influential environment variables: + LLVM_CONFIG LLVM configuration script CC C compiler command CFLAGS C compiler flags LDFLAGS linker flags, e.g. -L if you have libraries in a @@ -3176,6 +3197,247 @@ (it is also a good idea to do 'make clean' before compiling)" "$LINENO" 5 fi +# Check for --with-llvm=DIRECTORY or --without-llvm. +# +# Check for this really early so we can use it to toggle LINKCC. +# +# Expected behaviour: +# - Omit --with-llvm: use llvm-config we find in the path or $LLVM_CONFIG +# - --with-llvm (no DIRECTORY): Same +# - --with-llvm=DIRECTORY: use the LLVM installed in DIRECTORY +# - --without-llvm: disable everything that requires LLVM + +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for --with(out)-llvm" >&5 +$as_echo_n "checking for --with(out)-llvm... " >&6; } + +# Check whether --with-llvm was given. +if test "${with_llvm+set}" = set; then : + withval=$with_llvm; with_llvm=$withval +else + with_llvm=yes +fi + + +if test "$with_llvm" = "no" +then + { $as_echo "$as_me:${as_lineno-$LINENO}: result: disabled" >&5 +$as_echo "disabled" >&6; } + WITH_LLVM=0 + LLVM_PYTHON_OBJS="EMPTY" +else + { $as_echo "$as_me:${as_lineno-$LINENO}: result: $with_llvm" >&5 +$as_echo "$with_llvm" >&6; } + WITH_LLVM=1 + LLVM_PYTHON_OBJS="LLVM_PYTHON_OBJS" + if test "$with_llvm" = "yes" + then + # Extract the first word of "llvm-config", so it can be a program name with args. +set dummy llvm-config; ac_word=$2 +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 +$as_echo_n "checking for $ac_word... " >&6; } +if test "${ac_cv_path_LLVM_CONFIG+set}" = set; then : + $as_echo_n "(cached) " >&6 +else + case $LLVM_CONFIG in + [\\/]* | ?:[\\/]*) + ac_cv_path_LLVM_CONFIG="$LLVM_CONFIG" # Let the user override the test with a path. + ;; + *) + as_save_IFS=$IFS; IFS=$PATH_SEPARATOR +for as_dir in $PATH +do + IFS=$as_save_IFS + test -z "$as_dir" && as_dir=. + for ac_exec_ext in '' $ac_executable_extensions; do + if { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_test_x "$as_dir/$ac_word$ac_exec_ext"; }; then + ac_cv_path_LLVM_CONFIG="$as_dir/$ac_word$ac_exec_ext" + $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 + break 2 + fi +done + done +IFS=$as_save_IFS + + ;; +esac +fi +LLVM_CONFIG=$ac_cv_path_LLVM_CONFIG +if test -n "$LLVM_CONFIG"; then + { $as_echo "$as_me:${as_lineno-$LINENO}: result: $LLVM_CONFIG" >&5 +$as_echo "$LLVM_CONFIG" >&6; } +else + { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 +$as_echo "no" >&6; } +fi + + + if test -z "$LLVM_CONFIG" + then + as_fn_error "cannot find llvm-config on the PATH" "$LINENO" 5 + fi + else + # Extract the first word of "llvm-config", so it can be a program name with args. +set dummy llvm-config; ac_word=$2 +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 +$as_echo_n "checking for $ac_word... " >&6; } +if test "${ac_cv_path_LLVM_CONFIG+set}" = set; then : + $as_echo_n "(cached) " >&6 +else + case $LLVM_CONFIG in + [\\/]* | ?:[\\/]*) + ac_cv_path_LLVM_CONFIG="$LLVM_CONFIG" # Let the user override the test with a path. + ;; + *) + as_save_IFS=$IFS; IFS=$PATH_SEPARATOR +for as_dir in $with_llvm/bin +do + IFS=$as_save_IFS + test -z "$as_dir" && as_dir=. + for ac_exec_ext in '' $ac_executable_extensions; do + if { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_test_x "$as_dir/$ac_word$ac_exec_ext"; }; then + ac_cv_path_LLVM_CONFIG="$as_dir/$ac_word$ac_exec_ext" + $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 + break 2 + fi +done + done +IFS=$as_save_IFS + + ;; +esac +fi +LLVM_CONFIG=$ac_cv_path_LLVM_CONFIG +if test -n "$LLVM_CONFIG"; then + { $as_echo "$as_me:${as_lineno-$LINENO}: result: $LLVM_CONFIG" >&5 +$as_echo "$LLVM_CONFIG" >&6; } +else + { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 +$as_echo "no" >&6; } +fi + + + if test -z "$LLVM_CONFIG" + then + as_fn_error "cannot find llvm-config in $with_llvm/bin" "$LINENO" 5 + fi + fi + + LLVM_INC_DIR=`$LLVM_CONFIG --includedir` + LLVM_BIN_DIR=`$LLVM_CONFIG --bindir` + LLVM_CXXFLAGS=`$LLVM_CONFIG jit bitreader backend --cxxflags` + LLVM_LDFLAGS=`$LLVM_CONFIG jit bitreader backend --ldflags --libs | awk '{ORS=" "} {print $0}'` + LLVM_LIB_PATHS=`$LLVM_CONFIG jit bitreader backend --libfiles` + + as_ac_File=`$as_echo "ac_cv_file_"$LLVM_BIN_DIR/clang"" | $as_tr_sh` +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for \"$LLVM_BIN_DIR/clang\"" >&5 +$as_echo_n "checking for \"$LLVM_BIN_DIR/clang\"... " >&6; } +if { as_var=$as_ac_File; eval "test \"\${$as_var+set}\" = set"; }; then : + $as_echo_n "(cached) " >&6 +else + test "$cross_compiling" = yes && + as_fn_error "cannot check for file existence when cross compiling" "$LINENO" 5 +if test -r ""$LLVM_BIN_DIR/clang""; then + eval "$as_ac_File=yes" +else + eval "$as_ac_File=no" +fi +fi +eval ac_res=\$$as_ac_File + { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_res" >&5 +$as_echo "$ac_res" >&6; } +eval as_val=\$$as_ac_File + if test "x$as_val" = x""yes; then : + +else + as_fn_error "Did not find clang in $LLVM_BIN_DIR" "$LINENO" 5 +fi + + as_ac_File=`$as_echo "ac_cv_file_"$LLVM_BIN_DIR/opt"" | $as_tr_sh` +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for \"$LLVM_BIN_DIR/opt\"" >&5 +$as_echo_n "checking for \"$LLVM_BIN_DIR/opt\"... " >&6; } +if { as_var=$as_ac_File; eval "test \"\${$as_var+set}\" = set"; }; then : + $as_echo_n "(cached) " >&6 +else + test "$cross_compiling" = yes && + as_fn_error "cannot check for file existence when cross compiling" "$LINENO" 5 +if test -r ""$LLVM_BIN_DIR/opt""; then + eval "$as_ac_File=yes" +else + eval "$as_ac_File=no" +fi +fi +eval ac_res=\$$as_ac_File + { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_res" >&5 +$as_echo "$ac_res" >&6; } +eval as_val=\$$as_ac_File + if test "x$as_val" = x""yes; then : + +else + as_fn_error "Did not find opt in $LLVM_BIN_DIR" "$LINENO" 5 +fi + + as_ac_File=`$as_echo "ac_cv_file_"$LLVM_BIN_DIR/llvm-link"" | $as_tr_sh` +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for \"$LLVM_BIN_DIR/llvm-link\"" >&5 +$as_echo_n "checking for \"$LLVM_BIN_DIR/llvm-link\"... " >&6; } +if { as_var=$as_ac_File; eval "test \"\${$as_var+set}\" = set"; }; then : + $as_echo_n "(cached) " >&6 +else + test "$cross_compiling" = yes && + as_fn_error "cannot check for file existence when cross compiling" "$LINENO" 5 +if test -r ""$LLVM_BIN_DIR/llvm-link""; then + eval "$as_ac_File=yes" +else + eval "$as_ac_File=no" +fi +fi +eval ac_res=\$$as_ac_File + { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_res" >&5 +$as_echo "$ac_res" >&6; } +eval as_val=\$$as_ac_File + if test "x$as_val" = x""yes; then : + +else + as_fn_error "Did not find llvm-link in $LLVM_BIN_DIR" "$LINENO" 5 +fi + + as_ac_File=`$as_echo "ac_cv_file_"$LLVM_BIN_DIR/llvm-dis"" | $as_tr_sh` +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for \"$LLVM_BIN_DIR/llvm-dis\"" >&5 +$as_echo_n "checking for \"$LLVM_BIN_DIR/llvm-dis\"... " >&6; } +if { as_var=$as_ac_File; eval "test \"\${$as_var+set}\" = set"; }; then : + $as_echo_n "(cached) " >&6 +else + test "$cross_compiling" = yes && + as_fn_error "cannot check for file existence when cross compiling" "$LINENO" 5 +if test -r ""$LLVM_BIN_DIR/llvm-dis""; then + eval "$as_ac_File=yes" +else + eval "$as_ac_File=no" +fi +fi +eval ac_res=\$$as_ac_File + { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_res" >&5 +$as_echo "$ac_res" >&6; } +eval as_val=\$$as_ac_File + if test "x$as_val" = x""yes; then : + +else + as_fn_error "Did not find llvm-dis in $LLVM_BIN_DIR" "$LINENO" 5 +fi + + + +$as_echo "#define WITH_LLVM 1" >>confdefs.h + +fi + + + + + + + + + # If the user set CFLAGS, use this instead of the automatically # determined setting preset_cflags="$CFLAGS" @@ -3996,16 +4258,31 @@ CXX=$withval fi;; esac + else - with_cxx_main=no - MAINCC='$(CC)' + case "$with_llvm" in + no) with_cxx_main=no + MAINCC='$(CC)';; + *) with_cxx_main=yes + MAINCC='$(CXX)';; + esac fi { $as_echo "$as_me:${as_lineno-$LINENO}: result: $with_cxx_main" >&5 $as_echo "$with_cxx_main" >&6; } +if test "$with_cxx_main" = "no" +then + if test "$with_llvm" != "no" + then + as_fn_error "\"Cannot specify both --without-cxx-main and --with-llvm\"" "$LINENO" 5; + fi +fi + +# Use this in preference to AC_PROG_CXX, since --with-cxx-main=foo will override +# CXX. preset_cxx="$CXX" if test -z "$CXX" then @@ -4722,10 +4999,9 @@ LDLIBRARYDIR='' RUNSHARED='' -# LINKCC is the command that links the python executable -- default is $(CC). -# If CXX is set, and if it is needed to link a main function that was -# compiled with CXX, LINKCC is CXX instead. Always using CXX is undesirable: -# python might then depend on the C++ runtime +# LINKCC is the command that links the python executable -- this depends on +# the values of --with-llvm and --with-cxx-main. +# Always using CXX is undesirable: python might then depend on the C++ runtime # This is altered for AIX in order to build the export list before # linking. @@ -4839,7 +5115,7 @@ if test "$enable_framework" then LDLIBRARY='$(PYTHONFRAMEWORKDIR)/Versions/$(VERSION)/$(PYTHONFRAMEWORK)' - RUNSHARED=DYLD_FRAMEWORK_PATH="`pwd`:$DYLD_FRAMEWORK_PATH" + RUNSHARED=DYLD_FRAMEWORK_PATH="$(shell pwd):$DYLD_FRAMEWORK_PATH" BLDLIBRARY='' else BLDLIBRARY='$(LDLIBRARY)' @@ -4858,13 +5134,13 @@ SunOS*) LDLIBRARY='libpython$(VERSION).so' BLDLIBRARY='-Wl,-R,$(LIBDIR) -L. -lpython$(VERSION)' - RUNSHARED=LD_LIBRARY_PATH=`pwd`:${LD_LIBRARY_PATH} + RUNSHARED='LD_LIBRARY_PATH=$(shell pwd):${LD_LIBRARY_PATH}' INSTSONAME="$LDLIBRARY".$SOVERSION ;; Linux*|GNU*|NetBSD*|FreeBSD*|DragonFly*) LDLIBRARY='libpython$(VERSION).so' BLDLIBRARY='-L. -lpython$(VERSION)' - RUNSHARED=LD_LIBRARY_PATH=`pwd`:${LD_LIBRARY_PATH} + RUNSHARED='LD_LIBRARY_PATH=$(shell pwd):${LD_LIBRARY_PATH}' case $ac_sys_system in FreeBSD*) SOVERSION=`echo $SOVERSION|cut -d "." -f 1` @@ -4882,17 +5158,17 @@ ;; esac BLDLIBRARY='-Wl,+b,$(LIBDIR) -L. -lpython$(VERSION)' - RUNSHARED=SHLIB_PATH=`pwd`:${SHLIB_PATH} + RUNSHARED='SHLIB_PATH=$(shell pwd):${SHLIB_PATH}' ;; OSF*) LDLIBRARY='libpython$(VERSION).so' BLDLIBRARY='-rpath $(LIBDIR) -L. -lpython$(VERSION)' - RUNSHARED=LD_LIBRARY_PATH=`pwd`:${LD_LIBRARY_PATH} + RUNSHARED='LD_LIBRARY_PATH=$(shell pwd):${LD_LIBRARY_PATH}' ;; Darwin*) LDLIBRARY='libpython$(VERSION).dylib' BLDLIBRARY='-L. -lpython$(VERSION)' - RUNSHARED='DYLD_LIBRARY_PATH=`pwd`:${DYLD_LIBRARY_PATH}' + RUNSHARED='DYLD_LIBRARY_PATH=$(shell pwd):${DYLD_LIBRARY_PATH}' ;; esac @@ -5256,6 +5532,23 @@ fi +if test "$with_llvm" != "no" +then + LLVM_BUILD_MODE=`$LLVM_CONFIG --build-mode` + if echo $LLVM_BUILD_MODE | grep -e -Asserts &>/dev/null + then + if test "$Py_DEBUG" = "true" + then + as_fn_error "--with-pydebug requires +Asserts LLVM. Got \"$LLVM_BUILD_MODE\"" "$LINENO" 5 + fi + else + if test "$Py_DEBUG" != "true" + then + as_fn_error "--without-pydebug requires -Asserts LLVM. Got \"$LLVM_BUILD_MODE\"" "$LINENO" 5 + fi + fi +fi + # XXX Shouldn't the code above that fiddles with BASECFLAGS and OPT be # merged with this chunk of code? @@ -5276,25 +5569,18 @@ then case $GCC in yes) - if test "$CC" != 'g++' ; then - STRICT_PROTO="-Wstrict-prototypes" - fi - # For gcc 4.x we need to use -fwrapv so lets check if its supported - if "$CC" -v --help 2>/dev/null |grep -- -fwrapv > /dev/null; then - WRAP="-fwrapv" - fi case $ac_cv_prog_cc_g in yes) if test "$Py_DEBUG" = 'true' ; then # Optimization messes up debuggers, so turn it off for # debug builds. - OPT="-g -O0 -Wall $STRICT_PROTO" + OPT="-g -O0 -Wall" else - OPT="-g $WRAP -O3 -Wall $STRICT_PROTO" + OPT="-g $WRAP -O3 -Wall" fi ;; *) - OPT="-O3 -Wall $STRICT_PROTO" + OPT="-O3 -Wall" ;; esac case $ac_sys_system in @@ -5388,6 +5674,43 @@ BASECFLAGS="$BASECFLAGS -fno-strict-aliasing" fi + # Python violates C99 rules by treating signed overflow as + # 2s-compliment. GCC 4+ can generate bad code because of that, so + # use -fwrapv if it's supported + { $as_echo "$as_me:${as_lineno-$LINENO}: checking whether $CC accepts -fwrapv" >&5 +$as_echo_n "checking whether $CC accepts -fwrapv... " >&6; } + ac_save_cc="$CC" + CC="$CC -fwrapv" + if test "$cross_compiling" = yes; then : + ac_cv_fwrapv_ok=no +else + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ +int main() { return 0; } +_ACEOF +if ac_fn_c_try_run "$LINENO"; then : + ac_cv_fwrapv_ok=yes +else + ac_cv_fwrapv_ok=no +fi +rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext \ + conftest.$ac_objext conftest.beam conftest.$ac_ext +fi + + CC="$ac_save_cc" + { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_fwrapv_ok" >&5 +$as_echo "$ac_cv_fwrapv_ok" >&6; } + if test $ac_cv_fwrapv_ok = yes + then + BASECFLAGS="$BASECFLAGS -fwrapv" + fi + + BASECFLAGS="$BASECFLAGS -Wall" + + if test "$CC" != 'g++' ; then + STRICT_PROTO="-Wstrict-prototypes" + fi + # if using gcc on alpha, use -mieee to get (near) full IEEE 754 # support. Without this, treatment of subnormals doesn't follow # the standard. @@ -7422,6 +7745,22 @@ ;; esac + +# Only add -Wstrict-prototypes to the C flags, not C++. We do this +# after BASECFLAGS is fully set up. +BASECXXFLAGS="$BASECFLAGS" +BASECFLAGS="$BASECFLAGS $STRICT_PROTO" + +# We force C compilation for some files so that we don't have to rename them. +# Otherwise when configured --without-llvm, gcc will see the .cc extension and +# compile the file as C++, which creates a dependency on libstdc++. + +FORCE_C="" +if test "$GCC" == "yes" +then + FORCE_C="-x c" +fi + # Set info about shared libraries. @@ -8996,7 +9335,7 @@ ipv6type=$i ipv6lib=inet6 ipv6libdir=/usr/inet6/lib - BASECFLAGS="-I/usr/inet6/include $BASECFLAGS" + CPPFLAGS="-I/usr/inet6/include $CPPFLAGS" fi ;; solaris) @@ -9039,7 +9378,7 @@ ipv6type=$i; ipv6lib=v6; ipv6libdir=/usr/local/v6/lib; - BASECFLAGS="-I/usr/local/v6/include $BASECFLAGS" + CPPFLAGS="-I/usr/local/v6/include $CPPFLAGS" fi rm -f conftest* @@ -9141,29 +9480,6 @@ $as_echo "$with_doc_strings" >&6; } # Check for Python-specific malloc support -{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for --with-tsc" >&5 -$as_echo_n "checking for --with-tsc... " >&6; } - -# Check whether --with-tsc was given. -if test "${with_tsc+set}" = set; then : - withval=$with_tsc; -if test "$withval" != no -then - -$as_echo "#define WITH_TSC 1" >>confdefs.h - - { $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5 -$as_echo "yes" >&6; } -else { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 -$as_echo "no" >&6; } -fi -else - { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 -$as_echo "no" >&6; } -fi - - -# Check for Python-specific malloc support { $as_echo "$as_me:${as_lineno-$LINENO}: checking for --with-pymalloc" >&5 $as_echo_n "checking for --with-pymalloc... " >&6; } @@ -13544,12 +13860,57 @@ fi +# Check for --with-instrumentation +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for --with-instrumentation" >&5 +$as_echo_n "checking for --with-instrumentation... " >&6; } +# Check whether --with-instrumentation was given. +if test "${with_instrumentation+set}" = set; then : + withval=$with_instrumentation; +fi -case $ac_sys_system in - OSF*) as_fn_error "OSF* systems are deprecated unless somebody volunteers. Check http://bugs.python.org/issue8606" "$LINENO" 5 ;; -esac +if test "$with_instrumentation" = yes +then + +$as_echo "#define Py_WITH_INSTRUMENTATION 1" >>confdefs.h + + { $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +$as_echo "yes" >&6; }; + if test "WITH_LLVM" = "0" + then + as_fn_error "--with-instrumentation requires --with-llvm" "$LINENO" 5 + fi +else + { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 +$as_echo "no" >&6; }; +fi + +# Check fine-grained interpreter profiling using hardware counters. +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for --with-tsc" >&5 +$as_echo_n "checking for --with-tsc... " >&6; } + +# Check whether --with-tsc was given. +if test "${with_tsc+set}" = set; then : + withval=$with_tsc; +if test "$withval" != no +then + +$as_echo "#define WITH_TSC 1" >>confdefs.h + + { $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +$as_echo "yes" >&6; } + if test "WITH_LLVM" = "0" + then + as_fn_error "--with-tsc requires --with-llvm" "$LINENO" 5 + fi +else { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 +$as_echo "no" >&6; } +fi +else + { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 +$as_echo "no" >&6; } +fi @@ -13560,7 +13921,7 @@ done -SRCDIRS="Parser Grammar Objects Python Modules Mac Unittests Unittests/googletest" +SRCDIRS="Parser Grammar Objects Python Modules Mac Unittests Unittests/googletest Util" { $as_echo "$as_me:${as_lineno-$LINENO}: checking for build directories" >&5 $as_echo_n "checking for build directories... " >&6; } for dir in $SRCDIRS; do Modified: python/branches/py3k-jit/configure.in ============================================================================== --- python/branches/py3k-jit/configure.in (original) +++ python/branches/py3k-jit/configure.in Wed May 12 00:32:18 2010 @@ -26,7 +26,7 @@ dnl Last slash shouldn't be stripped if prefix=/ if test "$prefix" != "/"; then prefix=`echo "$prefix" | sed -e 's/\/$//g'` -fi +fi dnl This is for stuff that absolutely must end up in pyconfig.h. dnl Please use pyport.h instead, if possible. @@ -478,6 +478,82 @@ (it is also a good idea to do 'make clean' before compiling)]) fi +# Check for --with-llvm=DIRECTORY or --without-llvm. +# +# Check for this really early so we can use it to toggle LINKCC. +# +# Expected behaviour: +# - Omit --with-llvm: use llvm-config we find in the path or $LLVM_CONFIG +# - --with-llvm (no DIRECTORY): Same +# - --with-llvm=DIRECTORY: use the LLVM installed in DIRECTORY +# - --without-llvm: disable everything that requires LLVM +dnl quadrigraphs "@<:@" and "@:>@" produce "[" and "]" in the output +AC_ARG_VAR(LLVM_CONFIG, [LLVM configuration script]) +AC_MSG_CHECKING(for --with(out)-llvm) +AC_ARG_WITH(llvm, + AS_HELP_STRING([--with(out)-llvm@<:@=DIRECTORY@:>@], + [build against a preinstalled LLVM + or disable LLVM integration entirely. Note that + Python built with --without-llvm cannot load + extension modules built with --with-llvm or + vice-versa.]), + [with_llvm=$withval], + [with_llvm=yes]) + +if test "$with_llvm" = "no" +then + AC_MSG_RESULT(disabled) + WITH_LLVM=0 + LLVM_PYTHON_OBJS="EMPTY" + LLVM_UNITTEST_SRCS="EMPTY" +else + AC_MSG_RESULT($with_llvm) + WITH_LLVM=1 + LLVM_PYTHON_OBJS="LLVM_PYTHON_OBJS" + LLVM_UNITTEST_SRCS="LLVM_UNITTEST_SRCS" + if test "$with_llvm" = "yes" + then + AC_PATH_PROG(LLVM_CONFIG, llvm-config) + if test -z "$LLVM_CONFIG" + then + AC_MSG_ERROR([cannot find llvm-config on the PATH]) + fi + else + AC_PATH_PROG(LLVM_CONFIG, llvm-config, [], [$with_llvm/bin]) + if test -z "$LLVM_CONFIG" + then + AC_MSG_ERROR([cannot find llvm-config in $with_llvm/bin]) + fi + fi + + LLVM_INC_DIR=`$LLVM_CONFIG --includedir` + LLVM_BIN_DIR=`$LLVM_CONFIG --bindir` + LLVM_CXXFLAGS=`$LLVM_CONFIG jit bitreader backend --cxxflags` + LLVM_LDFLAGS=`$LLVM_CONFIG jit bitreader backend --ldflags --libs | awk '{ORS=" "} {print $0}'` + LLVM_LIB_PATHS=`$LLVM_CONFIG jit bitreader backend --libfiles` + + AC_CHECK_FILE("$LLVM_BIN_DIR/clang", + [], [AC_MSG_ERROR([Did not find clang in $LLVM_BIN_DIR])]) + AC_CHECK_FILE("$LLVM_BIN_DIR/opt", + [], [AC_MSG_ERROR([Did not find opt in $LLVM_BIN_DIR])]) + AC_CHECK_FILE("$LLVM_BIN_DIR/llvm-link", + [], [AC_MSG_ERROR([Did not find llvm-link in $LLVM_BIN_DIR])]) + AC_CHECK_FILE("$LLVM_BIN_DIR/llvm-dis", + [], [AC_MSG_ERROR([Did not find llvm-dis in $LLVM_BIN_DIR])]) + + AC_DEFINE(WITH_LLVM, 1, + [Use LLVM for code generation. This makes things fast.]) +fi +AC_SUBST(WITH_LLVM) +AC_SUBST(LLVM_PYTHON_OBJS) +AC_SUBST(LLVM_UNITTEST_SRCS) +AC_SUBST(LLVM_INC_DIR) +AC_SUBST(LLVM_BIN_DIR) +AC_SUBST(LLVM_CXXFLAGS) +AC_SUBST(LLVM_LDFLAGS) +AC_SUBST(LLVM_LIB_PATHS) + + # If the user set CFLAGS, use this instead of the automatically # determined setting preset_cflags="$CFLAGS" @@ -506,12 +582,27 @@ then CXX=$withval fi;; - esac], [ - with_cxx_main=no - MAINCC='$(CC)' + esac +], [ + case "$with_llvm" in + no) with_cxx_main=no + MAINCC='$(CC)';; + *) with_cxx_main=yes + MAINCC='$(CXX)';; + esac ]) AC_MSG_RESULT($with_cxx_main) +if test "$with_cxx_main" = "no" +then + if test "$with_llvm" != "no" + then + AC_MSG_ERROR("Cannot specify both --without-cxx-main and --with-llvm"); + fi +fi + +# Use this in preference to AC_PROG_CXX, since --with-cxx-main=foo will override +# CXX. preset_cxx="$CXX" if test -z "$CXX" then @@ -632,10 +723,9 @@ LDLIBRARYDIR='' RUNSHARED='' -# LINKCC is the command that links the python executable -- default is $(CC). -# If CXX is set, and if it is needed to link a main function that was -# compiled with CXX, LINKCC is CXX instead. Always using CXX is undesirable: -# python might then depend on the C++ runtime +# LINKCC is the command that links the python executable -- this depends on +# the values of --with-llvm and --with-cxx-main. +# Always using CXX is undesirable: python might then depend on the C++ runtime # This is altered for AIX in order to build the export list before # linking. AC_SUBST(LINKCC) @@ -723,7 +813,7 @@ if test "$enable_framework" then LDLIBRARY='$(PYTHONFRAMEWORKDIR)/Versions/$(VERSION)/$(PYTHONFRAMEWORK)' - RUNSHARED=DYLD_FRAMEWORK_PATH="`pwd`:$DYLD_FRAMEWORK_PATH" + RUNSHARED=DYLD_FRAMEWORK_PATH="$(shell pwd):$DYLD_FRAMEWORK_PATH" BLDLIBRARY='' else BLDLIBRARY='$(LDLIBRARY)' @@ -740,13 +830,13 @@ SunOS*) LDLIBRARY='libpython$(VERSION).so' BLDLIBRARY='-Wl,-R,$(LIBDIR) -L. -lpython$(VERSION)' - RUNSHARED=LD_LIBRARY_PATH=`pwd`:${LD_LIBRARY_PATH} + RUNSHARED='LD_LIBRARY_PATH=$(shell pwd):${LD_LIBRARY_PATH}' INSTSONAME="$LDLIBRARY".$SOVERSION ;; Linux*|GNU*|NetBSD*|FreeBSD*|DragonFly*) LDLIBRARY='libpython$(VERSION).so' BLDLIBRARY='-L. -lpython$(VERSION)' - RUNSHARED=LD_LIBRARY_PATH=`pwd`:${LD_LIBRARY_PATH} + RUNSHARED='LD_LIBRARY_PATH=$(shell pwd):${LD_LIBRARY_PATH}' case $ac_sys_system in FreeBSD*) SOVERSION=`echo $SOVERSION|cut -d "." -f 1` @@ -764,17 +854,17 @@ ;; esac BLDLIBRARY='-Wl,+b,$(LIBDIR) -L. -lpython$(VERSION)' - RUNSHARED=SHLIB_PATH=`pwd`:${SHLIB_PATH} + RUNSHARED='SHLIB_PATH=$(shell pwd):${SHLIB_PATH}' ;; OSF*) LDLIBRARY='libpython$(VERSION).so' BLDLIBRARY='-rpath $(LIBDIR) -L. -lpython$(VERSION)' - RUNSHARED=LD_LIBRARY_PATH=`pwd`:${LD_LIBRARY_PATH} + RUNSHARED='LD_LIBRARY_PATH=$(shell pwd):${LD_LIBRARY_PATH}' ;; Darwin*) LDLIBRARY='libpython$(VERSION).dylib' BLDLIBRARY='-L. -lpython$(VERSION)' - RUNSHARED='DYLD_LIBRARY_PATH=`pwd`:${DYLD_LIBRARY_PATH}' + RUNSHARED='DYLD_LIBRARY_PATH=$(shell pwd):${DYLD_LIBRARY_PATH}' ;; esac @@ -843,6 +933,23 @@ fi], [AC_MSG_RESULT(no)]) +if test "$with_llvm" != "no" +then + LLVM_BUILD_MODE=`$LLVM_CONFIG --build-mode` + if echo $LLVM_BUILD_MODE | grep -e -Asserts &>/dev/null + then + if test "$Py_DEBUG" = "true" + then + AC_MSG_ERROR([--with-pydebug requires +Asserts LLVM. Got "$LLVM_BUILD_MODE"]) + fi + else + if test "$Py_DEBUG" != "true" + then + AC_MSG_ERROR([--without-pydebug requires -Asserts LLVM. Got "$LLVM_BUILD_MODE"]) + fi + fi +fi + # XXX Shouldn't the code above that fiddles with BASECFLAGS and OPT be # merged with this chunk of code? @@ -863,25 +970,18 @@ then case $GCC in yes) - if test "$CC" != 'g++' ; then - STRICT_PROTO="-Wstrict-prototypes" - fi - # For gcc 4.x we need to use -fwrapv so lets check if its supported - if "$CC" -v --help 2>/dev/null |grep -- -fwrapv > /dev/null; then - WRAP="-fwrapv" - fi case $ac_cv_prog_cc_g in yes) if test "$Py_DEBUG" = 'true' ; then # Optimization messes up debuggers, so turn it off for # debug builds. - OPT="-g -O0 -Wall $STRICT_PROTO" + OPT="-g -O0 -Wall" else - OPT="-g $WRAP -O3 -Wall $STRICT_PROTO" + OPT="-g $WRAP -O3 -Wall" fi ;; *) - OPT="-O3 -Wall $STRICT_PROTO" + OPT="-O3 -Wall" ;; esac case $ac_sys_system in @@ -940,6 +1040,29 @@ BASECFLAGS="$BASECFLAGS -fno-strict-aliasing" fi + # Python violates C99 rules by treating signed overflow as + # 2s-compliment. GCC 4+ can generate bad code because of that, so + # use -fwrapv if it's supported + AC_MSG_CHECKING(whether $CC accepts -fwrapv) + ac_save_cc="$CC" + CC="$CC -fwrapv" + AC_TRY_RUN([int main() { return 0; }], + ac_cv_fwrapv_ok=yes, + ac_cv_fwrapv_ok=no, + ac_cv_fwrapv_ok=no) + CC="$ac_save_cc" + AC_MSG_RESULT($ac_cv_fwrapv_ok) + if test $ac_cv_fwrapv_ok = yes + then + BASECFLAGS="$BASECFLAGS -fwrapv" + fi + + BASECFLAGS="$BASECFLAGS -Wall" + + if test "$CC" != 'g++' ; then + STRICT_PROTO="-Wstrict-prototypes" + fi + # if using gcc on alpha, use -mieee to get (near) full IEEE 754 # support. Without this, treatment of subnormals doesn't follow # the standard. @@ -1653,6 +1776,22 @@ ;; esac +AC_SUBST(BASECXXFLAGS) +# Only add -Wstrict-prototypes to the C flags, not C++. We do this +# after BASECFLAGS is fully set up. +BASECXXFLAGS="$BASECFLAGS" +BASECFLAGS="$BASECFLAGS $STRICT_PROTO" + +# We force C compilation for some files so that we don't have to rename them. +# Otherwise when configured --without-llvm, gcc will see the .cc extension and +# compile the file as C++, which creates a dependency on libstdc++. +AC_SUBST(FORCE_C) +FORCE_C="" +if test "$GCC" == "yes" +then + FORCE_C="-x c" +fi + # Set info about shared libraries. AC_SUBST(SO) AC_SUBST(LDSHARED) @@ -2385,7 +2524,7 @@ ipv6type=$i ipv6lib=inet6 ipv6libdir=/usr/inet6/lib - BASECFLAGS="-I/usr/inet6/include $BASECFLAGS" + CPPFLAGS="-I/usr/inet6/include $CPPFLAGS" fi ;; solaris) @@ -2415,7 +2554,7 @@ [ipv6type=$i; ipv6lib=v6; ipv6libdir=/usr/local/v6/lib; - BASECFLAGS="-I/usr/local/v6/include $BASECFLAGS"]) + CPPFLAGS="-I/usr/local/v6/include $CPPFLAGS"]) ;; zeta) AC_EGREP_CPP(yes, [ @@ -2477,19 +2616,6 @@ AC_MSG_RESULT($with_doc_strings) # Check for Python-specific malloc support -AC_MSG_CHECKING(for --with-tsc) -AC_ARG_WITH(tsc, - AS_HELP_STRING([--with(out)-tsc],[enable/disable timestamp counter profile]),[ -if test "$withval" != no -then - AC_DEFINE(WITH_TSC, 1, - [Define to profile with the Pentium timestamp counter]) - AC_MSG_RESULT(yes) -else AC_MSG_RESULT(no) -fi], -[AC_MSG_RESULT(no)]) - -# Check for Python-specific malloc support AC_MSG_CHECKING(for --with-pymalloc) AC_ARG_WITH(pymalloc, AS_HELP_STRING([--with(out)-pymalloc], [disable/enable specialized mallocs])) @@ -4149,21 +4275,52 @@ [Use computed gotos / threaded dispatch in evaluation loop (not available on all compilers)]), [ if test "$withval" != no -then +then AC_DEFINE(USE_COMPUTED_GOTOS, 1, - [Define if you want to use computed gotos in ceval.c.]) + [Define if you want to use computed gotos in ceval.c.]) AC_MSG_RESULT(yes) else AC_MSG_RESULT(no) fi], [AC_MSG_RESULT(no)]) +# Check for --with-instrumentation +AC_MSG_CHECKING(for --with-instrumentation) +AC_ARG_WITH(instrumentation, + AS_HELP_STRING([--with-instrumentation], + [Compile in a bunch of runtime instrumentation useful + for optimizing Python itself. Requires --with-llvm.])) + +if test "$with_instrumentation" = yes +then + AC_DEFINE(Py_WITH_INSTRUMENTATION, 1, + [Compile in a bunch of runtime instrumentation useful for optimizing + Python itself.]) + AC_MSG_RESULT(yes); + if test "WITH_LLVM" = "0" + then + AC_MSG_ERROR([--with-instrumentation requires --with-llvm]) + fi +else + AC_MSG_RESULT(no); +fi - -case $ac_sys_system in - OSF*) AC_MSG_ERROR(OSF* systems are deprecated unless somebody volunteers. Check http://bugs.python.org/issue8606) ;; -esac - - +# Check fine-grained interpreter profiling using hardware counters. +AC_MSG_CHECKING(for --with-tsc) +AC_ARG_WITH(tsc, + AS_HELP_STRING([--with(out)-tsc], + [enable/disable timestamp counter profile]), [ +if test "$withval" != no +then + AC_DEFINE(WITH_TSC, 1, + [Define to profile with the Pentium timestamp counter]) + AC_MSG_RESULT(yes) + if test "WITH_LLVM" = "0" + then + AC_MSG_ERROR([--with-tsc requires --with-llvm]) + fi +else AC_MSG_RESULT(no) +fi], +[AC_MSG_RESULT(no)]) AC_SUBST(THREADHEADERS) @@ -4173,7 +4330,7 @@ done AC_SUBST(SRCDIRS) -SRCDIRS="Parser Grammar Objects Python Modules Mac Unittests Unittests/googletest" +SRCDIRS="Parser Grammar Objects Python Modules Mac Unittests Unittests/googletest Util" AC_MSG_CHECKING(for build directories) for dir in $SRCDIRS; do if test ! -d $dir; then Modified: python/branches/py3k-jit/pyconfig.h.in ============================================================================== --- python/branches/py3k-jit/pyconfig.h.in (original) +++ python/branches/py3k-jit/pyconfig.h.in Wed May 12 00:32:18 2010 @@ -958,6 +958,10 @@ /* Define as the size of the unicode type. */ #undef Py_UNICODE_SIZE +/* Compile in a bunch of runtime instrumentation useful for optimizing Python + itself. */ +#undef Py_WITH_INSTRUMENTATION + /* assume C89 semantics that RETSIGTYPE is always void */ #undef RETSIGTYPE @@ -1086,6 +1090,9 @@ /* Define to 1 if libintl is needed for locale functions. */ #undef WITH_LIBINTL +/* Use LLVM for code generation. This makes things fast. */ +#undef WITH_LLVM + /* Define if you want to produce an OpenStep/Rhapsody framework (shared library plus accessory files). */ #undef WITH_NEXT_FRAMEWORK From nnorwitz at gmail.com Wed May 12 00:56:13 2010 From: nnorwitz at gmail.com (Neal Norwitz) Date: Tue, 11 May 2010 18:56:13 -0400 Subject: [Python-checkins] Python Regression Test Failures refleak (1) Message-ID: <20100511225613.GA23819@kbk-i386-bb.psfb.org> More important issues: ---------------------- test_bz2 leaked [77, 0, 0] references, sum=77 Less important issues: ---------------------- From solipsis at pitrou.net Wed May 12 01:22:52 2010 From: solipsis at pitrou.net (solipsis at pitrou.net) Date: Wed, 12 May 2010 01:22:52 +0200 (CEST) Subject: [Python-checkins] Daily py3k reference leaks (r81090): sum=0 Message-ID: <20100511232252.C807B1770A@ns6635.ovh.net> py3k results for svn r81090 (hg cset 9338f086861a) -------------------------------------------------- Command line was: ['./python', '-m', 'test.regrtest', '-uall', '-R', '3:3:/home/antoine/py3k/refleaks/refloge1X_Xh', '-x'] From python-checkins at python.org Wed May 12 01:32:31 2010 From: python-checkins at python.org (antoine.pitrou) Date: Wed, 12 May 2010 01:32:31 +0200 (CEST) Subject: [Python-checkins] r81094 - in python/trunk: Lib/test/test_zlib.py Misc/NEWS Message-ID: <20100511233231.67EEFEE982@mail.python.org> Author: antoine.pitrou Date: Wed May 12 01:32:31 2010 New Revision: 81094 Log: Issue #8672: Add a zlib test ensuring that an incomplete stream can be handled by a decompressor object without errors (it returns incomplete uncompressed data). Modified: python/trunk/Lib/test/test_zlib.py python/trunk/Misc/NEWS Modified: python/trunk/Lib/test/test_zlib.py ============================================================================== --- python/trunk/Lib/test/test_zlib.py (original) +++ python/trunk/Lib/test/test_zlib.py Wed May 12 01:32:31 2010 @@ -361,6 +361,19 @@ dco = zlib.decompressobj() self.assertEqual(dco.flush(), "") # Returns nothing + def test_decompress_incomplete_stream(self): + # This is 'foo', deflated + x = 'x\x9cK\xcb\xcf\x07\x00\x02\x82\x01E' + # For the record + self.assertEqual(zlib.decompress(x), 'foo') + self.assertRaises(zlib.error, zlib.decompress, x[:-5]) + # Omitting the stream end works with decompressor objects + # (see issue #8672). + dco = zlib.decompressobj() + y = dco.decompress(x[:-5]) + y += dco.flush() + self.assertEqual(y, 'foo') + if hasattr(zlib.compressobj(), "copy"): def test_compresscopy(self): # Test copying a compression object Modified: python/trunk/Misc/NEWS ============================================================================== --- python/trunk/Misc/NEWS (original) +++ python/trunk/Misc/NEWS Wed May 12 01:32:31 2010 @@ -216,6 +216,10 @@ Tests ----- +- Issue #8672: Add a zlib test ensuring that an incomplete stream can be + handled by a decompressor object without errors (it returns incomplete + uncompressed data). + - Issue #8490: asyncore now has a more solid test suite which actually tests its API. From python-checkins at python.org Wed May 12 01:33:53 2010 From: python-checkins at python.org (antoine.pitrou) Date: Wed, 12 May 2010 01:33:53 +0200 (CEST) Subject: [Python-checkins] r81095 - in python/branches/release26-maint: Lib/test/test_zlib.py Misc/NEWS Message-ID: <20100511233353.5E4CBEE981@mail.python.org> Author: antoine.pitrou Date: Wed May 12 01:33:53 2010 New Revision: 81095 Log: Merged revisions 81094 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r81094 | antoine.pitrou | 2010-05-12 01:32:31 +0200 (mer., 12 mai 2010) | 6 lines Issue #8672: Add a zlib test ensuring that an incomplete stream can be handled by a decompressor object without errors (it returns incomplete uncompressed data). ........ Modified: python/branches/release26-maint/ (props changed) python/branches/release26-maint/Lib/test/test_zlib.py python/branches/release26-maint/Misc/NEWS Modified: python/branches/release26-maint/Lib/test/test_zlib.py ============================================================================== --- python/branches/release26-maint/Lib/test/test_zlib.py (original) +++ python/branches/release26-maint/Lib/test/test_zlib.py Wed May 12 01:33:53 2010 @@ -360,6 +360,19 @@ dco = zlib.decompressobj() self.assertEqual(dco.flush(), "") # Returns nothing + def test_decompress_incomplete_stream(self): + # This is 'foo', deflated + x = 'x\x9cK\xcb\xcf\x07\x00\x02\x82\x01E' + # For the record + self.assertEqual(zlib.decompress(x), 'foo') + self.assertRaises(zlib.error, zlib.decompress, x[:-5]) + # Omitting the stream end works with decompressor objects + # (see issue #8672). + dco = zlib.decompressobj() + y = dco.decompress(x[:-5]) + y += dco.flush() + self.assertEqual(y, 'foo') + if hasattr(zlib.compressobj(), "copy"): def test_compresscopy(self): # Test copying a compression object Modified: python/branches/release26-maint/Misc/NEWS ============================================================================== --- python/branches/release26-maint/Misc/NEWS (original) +++ python/branches/release26-maint/Misc/NEWS Wed May 12 01:33:53 2010 @@ -186,6 +186,10 @@ Tests ----- +- Issue #8672: Add a zlib test ensuring that an incomplete stream can be + handled by a decompressor object without errors (it returns incomplete + uncompressed data). + - Issue #8629: Disable some test_ssl tests, since they give different results with OpenSSL 1.0.0 and higher. From python-checkins at python.org Wed May 12 01:36:41 2010 From: python-checkins at python.org (antoine.pitrou) Date: Wed, 12 May 2010 01:36:41 +0200 (CEST) Subject: [Python-checkins] r81096 - in python/branches/py3k: Lib/test/test_zlib.py Misc/NEWS Message-ID: <20100511233641.21472EE981@mail.python.org> Author: antoine.pitrou Date: Wed May 12 01:36:40 2010 New Revision: 81096 Log: Merged revisions 81094 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r81094 | antoine.pitrou | 2010-05-12 01:32:31 +0200 (mer., 12 mai 2010) | 6 lines Issue #8672: Add a zlib test ensuring that an incomplete stream can be handled by a decompressor object without errors (it returns incomplete uncompressed data). ........ Modified: python/branches/py3k/ (props changed) python/branches/py3k/Lib/test/test_zlib.py python/branches/py3k/Misc/NEWS Modified: python/branches/py3k/Lib/test/test_zlib.py ============================================================================== --- python/branches/py3k/Lib/test/test_zlib.py (original) +++ python/branches/py3k/Lib/test/test_zlib.py Wed May 12 01:36:40 2010 @@ -379,6 +379,19 @@ dco = zlib.decompressobj() self.assertEqual(dco.flush(), b"") # Returns nothing + def test_decompress_incomplete_stream(self): + # This is 'foo', deflated + x = b'x\x9cK\xcb\xcf\x07\x00\x02\x82\x01E' + # For the record + self.assertEqual(zlib.decompress(x), b'foo') + self.assertRaises(zlib.error, zlib.decompress, x[:-5]) + # Omitting the stream end works with decompressor objects + # (see issue #8672). + dco = zlib.decompressobj() + y = dco.decompress(x[:-5]) + y += dco.flush() + self.assertEqual(y, b'foo') + if hasattr(zlib.compressobj(), "copy"): def test_compresscopy(self): # Test copying a compression object Modified: python/branches/py3k/Misc/NEWS ============================================================================== --- python/branches/py3k/Misc/NEWS (original) +++ python/branches/py3k/Misc/NEWS Wed May 12 01:36:40 2010 @@ -1276,6 +1276,10 @@ Tests ----- +- Issue #8672: Add a zlib test ensuring that an incomplete stream can be + handled by a decompressor object without errors (it returns incomplete + uncompressed data). + - Issue #8533: regrtest uses backslashreplace error handler for stdout to avoid UnicodeEncodeError (write non-ASCII character to stdout using ASCII encoding) From python-checkins at python.org Wed May 12 01:38:15 2010 From: python-checkins at python.org (antoine.pitrou) Date: Wed, 12 May 2010 01:38:15 +0200 (CEST) Subject: [Python-checkins] r81097 - in python/branches/release31-maint: Lib/test/test_zlib.py Misc/NEWS Message-ID: <20100511233815.57835EE981@mail.python.org> Author: antoine.pitrou Date: Wed May 12 01:38:15 2010 New Revision: 81097 Log: Merged revisions 81096 via svnmerge from svn+ssh://pythondev at svn.python.org/python/branches/py3k ................ r81096 | antoine.pitrou | 2010-05-12 01:36:40 +0200 (mer., 12 mai 2010) | 11 lines Merged revisions 81094 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r81094 | antoine.pitrou | 2010-05-12 01:32:31 +0200 (mer., 12 mai 2010) | 6 lines Issue #8672: Add a zlib test ensuring that an incomplete stream can be handled by a decompressor object without errors (it returns incomplete uncompressed data). ........ ................ Modified: python/branches/release31-maint/ (props changed) python/branches/release31-maint/Lib/test/test_zlib.py python/branches/release31-maint/Misc/NEWS Modified: python/branches/release31-maint/Lib/test/test_zlib.py ============================================================================== --- python/branches/release31-maint/Lib/test/test_zlib.py (original) +++ python/branches/release31-maint/Lib/test/test_zlib.py Wed May 12 01:38:15 2010 @@ -379,6 +379,19 @@ dco = zlib.decompressobj() self.assertEqual(dco.flush(), b"") # Returns nothing + def test_decompress_incomplete_stream(self): + # This is 'foo', deflated + x = b'x\x9cK\xcb\xcf\x07\x00\x02\x82\x01E' + # For the record + self.assertEqual(zlib.decompress(x), b'foo') + self.assertRaises(zlib.error, zlib.decompress, x[:-5]) + # Omitting the stream end works with decompressor objects + # (see issue #8672). + dco = zlib.decompressobj() + y = dco.decompress(x[:-5]) + y += dco.flush() + self.assertEqual(y, b'foo') + if hasattr(zlib.compressobj(), "copy"): def test_compresscopy(self): # Test copying a compression object Modified: python/branches/release31-maint/Misc/NEWS ============================================================================== --- python/branches/release31-maint/Misc/NEWS (original) +++ python/branches/release31-maint/Misc/NEWS Wed May 12 01:38:15 2010 @@ -176,6 +176,10 @@ Tests ----- +- Issue #8672: Add a zlib test ensuring that an incomplete stream can be + handled by a decompressor object without errors (it returns incomplete + uncompressed data). + - Issue #8629: Disable some test_ssl tests, since they give different results with OpenSSL 1.0.0 and higher. From python-checkins at python.org Wed May 12 01:42:28 2010 From: python-checkins at python.org (antoine.pitrou) Date: Wed, 12 May 2010 01:42:28 +0200 (CEST) Subject: [Python-checkins] r81098 - in python/trunk: Lib/test/test_zlib.py Misc/NEWS Modules/zlibmodule.c Message-ID: <20100511234228.34874EE981@mail.python.org> Author: antoine.pitrou Date: Wed May 12 01:42:28 2010 New Revision: 81098 Log: Issue #8681: Make the zlib module's error messages more informative when the zlib itself doesn't give any detailed explanation. Modified: python/trunk/Lib/test/test_zlib.py python/trunk/Misc/NEWS python/trunk/Modules/zlibmodule.c Modified: python/trunk/Lib/test/test_zlib.py ============================================================================== --- python/trunk/Lib/test/test_zlib.py (original) +++ python/trunk/Lib/test/test_zlib.py Wed May 12 01:42:28 2010 @@ -135,6 +135,13 @@ x = zlib.compress(data) self.assertEqual(zlib.decompress(x), data) + def test_incomplete_stream(self): + # An useful error message is given + x = zlib.compress(HAMLET_SCENE) + self.assertRaisesRegexp(zlib.error, + "Error -5 while decompressing data: incomplete or truncated stream", + zlib.decompress, x[:-1]) + # Memory use of the following functions takes into account overallocation @precisionbigmemtest(size=_1G + 1024 * 1024, memuse=3) Modified: python/trunk/Misc/NEWS ============================================================================== --- python/trunk/Misc/NEWS (original) +++ python/trunk/Misc/NEWS Wed May 12 01:42:28 2010 @@ -62,6 +62,9 @@ Library ------- +- Issue #8681: Make the zlib module's error messages more informative when + the zlib itself doesn't give any detailed explanation. + - Issue #8571: Fix an internal error when compressing or decompressing a chunk larger than 1GB with the zlib module's compressor and decompressor objects. Modified: python/trunk/Modules/zlibmodule.c ============================================================================== --- python/trunk/Modules/zlibmodule.c (original) +++ python/trunk/Modules/zlibmodule.c Wed May 12 01:42:28 2010 @@ -72,10 +72,24 @@ static void zlib_error(z_stream zst, int err, char *msg) { - if (zst.msg == Z_NULL) + const char *zmsg = zst.msg; + if (zmsg == Z_NULL) { + switch (err) { + case Z_BUF_ERROR: + zmsg = "incomplete or truncated stream"; + break; + case Z_STREAM_ERROR: + zmsg = "inconsistent stream state"; + break; + case Z_DATA_ERROR: + zmsg = "invalid input data"; + break; + } + } + if (zmsg == Z_NULL) PyErr_Format(ZlibError, "Error %d %s", err, msg); else - PyErr_Format(ZlibError, "Error %d %s: %.200s", err, msg, zst.msg); + PyErr_Format(ZlibError, "Error %d %s: %.200s", err, msg, zmsg); } PyDoc_STRVAR(compressobj__doc__, @@ -248,8 +262,7 @@ * process the inflate call() due to an error in the data. */ if (zst.avail_out > 0) { - PyErr_Format(ZlibError, "Error %i while decompressing data", - err); + zlib_error(zst, err, "while decompressing data"); inflateEnd(&zst); goto error; } From python-checkins at python.org Wed May 12 01:45:55 2010 From: python-checkins at python.org (antoine.pitrou) Date: Wed, 12 May 2010 01:45:55 +0200 (CEST) Subject: [Python-checkins] r81099 - in python/branches/release26-maint: Lib/test/test_zlib.py Misc/NEWS Modules/zlibmodule.c Message-ID: <20100511234555.535E4EE981@mail.python.org> Author: antoine.pitrou Date: Wed May 12 01:45:55 2010 New Revision: 81099 Log: Merged revisions 81098 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r81098 | antoine.pitrou | 2010-05-12 01:42:28 +0200 (mer., 12 mai 2010) | 5 lines Issue #8681: Make the zlib module's error messages more informative when the zlib itself doesn't give any detailed explanation. ........ Modified: python/branches/release26-maint/ (props changed) python/branches/release26-maint/Lib/test/test_zlib.py python/branches/release26-maint/Misc/NEWS python/branches/release26-maint/Modules/zlibmodule.c Modified: python/branches/release26-maint/Lib/test/test_zlib.py ============================================================================== --- python/branches/release26-maint/Lib/test/test_zlib.py (original) +++ python/branches/release26-maint/Lib/test/test_zlib.py Wed May 12 01:45:55 2010 @@ -134,6 +134,18 @@ x = zlib.compress(data) self.assertEqual(zlib.decompress(x), data) + def test_incomplete_stream(self): + # An useful error message is given + x = zlib.compress(HAMLET_SCENE) + try: + zlib.decompress(x[:-1]) + except zlib.error as e: + self.assertTrue( + "Error -5 while decompressing data: incomplete or truncated stream" + in str(e), str(e)) + else: + self.fail("zlib.error not raised") + # Memory use of the following functions takes into account overallocation @precisionbigmemtest(size=_1G + 1024 * 1024, memuse=3) Modified: python/branches/release26-maint/Misc/NEWS ============================================================================== --- python/branches/release26-maint/Misc/NEWS (original) +++ python/branches/release26-maint/Misc/NEWS Wed May 12 01:45:55 2010 @@ -39,6 +39,9 @@ Library ------- +- Issue #8681: Make the zlib module's error messages more informative when + the zlib itself doesn't give any detailed explanation. + - Issue #8674: Fixed a number of incorrect or undefined-behaviour-inducing overflow checks in the audioop module. Modified: python/branches/release26-maint/Modules/zlibmodule.c ============================================================================== --- python/branches/release26-maint/Modules/zlibmodule.c (original) +++ python/branches/release26-maint/Modules/zlibmodule.c Wed May 12 01:45:55 2010 @@ -72,10 +72,24 @@ static void zlib_error(z_stream zst, int err, char *msg) { - if (zst.msg == Z_NULL) + const char *zmsg = zst.msg; + if (zmsg == Z_NULL) { + switch (err) { + case Z_BUF_ERROR: + zmsg = "incomplete or truncated stream"; + break; + case Z_STREAM_ERROR: + zmsg = "inconsistent stream state"; + break; + case Z_DATA_ERROR: + zmsg = "invalid input data"; + break; + } + } + if (zmsg == Z_NULL) PyErr_Format(ZlibError, "Error %d %s", err, msg); else - PyErr_Format(ZlibError, "Error %d %s: %.200s", err, msg, zst.msg); + PyErr_Format(ZlibError, "Error %d %s: %.200s", err, msg, zmsg); } PyDoc_STRVAR(compressobj__doc__, @@ -248,8 +262,7 @@ * process the inflate call() due to an error in the data. */ if (zst.avail_out > 0) { - PyErr_Format(ZlibError, "Error %i while decompressing data", - err); + zlib_error(zst, err, "while decompressing data"); inflateEnd(&zst); goto error; } From python-checkins at python.org Wed May 12 01:46:03 2010 From: python-checkins at python.org (antoine.pitrou) Date: Wed, 12 May 2010 01:46:03 +0200 (CEST) Subject: [Python-checkins] r81100 - in python/branches/py3k: Lib/test/test_zlib.py Misc/NEWS Modules/zlibmodule.c Message-ID: <20100511234603.062B2EE9BE@mail.python.org> Author: antoine.pitrou Date: Wed May 12 01:46:02 2010 New Revision: 81100 Log: Merged revisions 81098 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r81098 | antoine.pitrou | 2010-05-12 01:42:28 +0200 (mer., 12 mai 2010) | 5 lines Issue #8681: Make the zlib module's error messages more informative when the zlib itself doesn't give any detailed explanation. ........ Modified: python/branches/py3k/ (props changed) python/branches/py3k/Lib/test/test_zlib.py python/branches/py3k/Misc/NEWS python/branches/py3k/Modules/zlibmodule.c Modified: python/branches/py3k/Lib/test/test_zlib.py ============================================================================== --- python/branches/py3k/Lib/test/test_zlib.py (original) +++ python/branches/py3k/Lib/test/test_zlib.py Wed May 12 01:46:02 2010 @@ -140,6 +140,13 @@ for ob in x, bytearray(x): self.assertEqual(zlib.decompress(ob), data) + def test_incomplete_stream(self): + # An useful error message is given + x = zlib.compress(HAMLET_SCENE) + self.assertRaisesRegexp(zlib.error, + "Error -5 while decompressing data: incomplete or truncated stream", + zlib.decompress, x[:-1]) + # Memory use of the following functions takes into account overallocation @precisionbigmemtest(size=_1G + 1024 * 1024, memuse=3) Modified: python/branches/py3k/Misc/NEWS ============================================================================== --- python/branches/py3k/Misc/NEWS (original) +++ python/branches/py3k/Misc/NEWS Wed May 12 01:46:02 2010 @@ -351,6 +351,9 @@ Library ------- +- Issue #8681: Make the zlib module's error messages more informative when + the zlib itself doesn't give any detailed explanation. + - The audioop module now supports sound fragments of length greater than 2**31 bytes on 64-bit machines, and is PY_SSIZE_T_CLEAN. Modified: python/branches/py3k/Modules/zlibmodule.c ============================================================================== --- python/branches/py3k/Modules/zlibmodule.c (original) +++ python/branches/py3k/Modules/zlibmodule.c Wed May 12 01:46:02 2010 @@ -52,10 +52,24 @@ static void zlib_error(z_stream zst, int err, char *msg) { - if (zst.msg == Z_NULL) + const char *zmsg = zst.msg; + if (zmsg == Z_NULL) { + switch (err) { + case Z_BUF_ERROR: + zmsg = "incomplete or truncated stream"; + break; + case Z_STREAM_ERROR: + zmsg = "inconsistent stream state"; + break; + case Z_DATA_ERROR: + zmsg = "invalid input data"; + break; + } + } + if (zmsg == Z_NULL) PyErr_Format(ZlibError, "Error %d %s", err, msg); else - PyErr_Format(ZlibError, "Error %d %s: %.200s", err, msg, zst.msg); + PyErr_Format(ZlibError, "Error %d %s: %.200s", err, msg, zmsg); } PyDoc_STRVAR(compressobj__doc__, @@ -241,8 +255,7 @@ * process the inflate call() due to an error in the data. */ if (zst.avail_out > 0) { - PyErr_Format(ZlibError, "Error %i while decompressing data", - err); + zlib_error(zst, err, "while decompressing data"); inflateEnd(&zst); goto error; } From python-checkins at python.org Wed May 12 01:49:58 2010 From: python-checkins at python.org (antoine.pitrou) Date: Wed, 12 May 2010 01:49:58 +0200 (CEST) Subject: [Python-checkins] r81101 - in python/branches/release31-maint: Lib/test/test_zlib.py Misc/NEWS Modules/zlibmodule.c Message-ID: <20100511234958.382A6EE9CC@mail.python.org> Author: antoine.pitrou Date: Wed May 12 01:49:58 2010 New Revision: 81101 Log: Merged revisions 81100 via svnmerge from svn+ssh://pythondev at svn.python.org/python/branches/py3k ................ r81100 | antoine.pitrou | 2010-05-12 01:46:02 +0200 (mer., 12 mai 2010) | 10 lines Merged revisions 81098 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r81098 | antoine.pitrou | 2010-05-12 01:42:28 +0200 (mer., 12 mai 2010) | 5 lines Issue #8681: Make the zlib module's error messages more informative when the zlib itself doesn't give any detailed explanation. ........ ................ Modified: python/branches/release31-maint/ (props changed) python/branches/release31-maint/Lib/test/test_zlib.py python/branches/release31-maint/Misc/NEWS python/branches/release31-maint/Modules/zlibmodule.c Modified: python/branches/release31-maint/Lib/test/test_zlib.py ============================================================================== --- python/branches/release31-maint/Lib/test/test_zlib.py (original) +++ python/branches/release31-maint/Lib/test/test_zlib.py Wed May 12 01:49:58 2010 @@ -140,6 +140,13 @@ for ob in x, bytearray(x): self.assertEqual(zlib.decompress(ob), data) + def test_incomplete_stream(self): + # An useful error message is given + x = zlib.compress(HAMLET_SCENE) + self.assertRaisesRegexp(zlib.error, + "Error -5 while decompressing data: incomplete or truncated stream", + zlib.decompress, x[:-1]) + # Memory use of the following functions takes into account overallocation @precisionbigmemtest(size=_1G + 1024 * 1024, memuse=3) Modified: python/branches/release31-maint/Misc/NEWS ============================================================================== --- python/branches/release31-maint/Misc/NEWS (original) +++ python/branches/release31-maint/Misc/NEWS Wed May 12 01:49:58 2010 @@ -40,6 +40,9 @@ Library ------- +- Issue #8681: Make the zlib module's error messages more informative when + the zlib itself doesn't give any detailed explanation. + - Issue #8674: Fixed a number of incorrect or undefined-behaviour-inducing overflow checks in the audioop module. Modified: python/branches/release31-maint/Modules/zlibmodule.c ============================================================================== --- python/branches/release31-maint/Modules/zlibmodule.c (original) +++ python/branches/release31-maint/Modules/zlibmodule.c Wed May 12 01:49:58 2010 @@ -52,10 +52,24 @@ static void zlib_error(z_stream zst, int err, char *msg) { - if (zst.msg == Z_NULL) + const char *zmsg = zst.msg; + if (zmsg == Z_NULL) { + switch (err) { + case Z_BUF_ERROR: + zmsg = "incomplete or truncated stream"; + break; + case Z_STREAM_ERROR: + zmsg = "inconsistent stream state"; + break; + case Z_DATA_ERROR: + zmsg = "invalid input data"; + break; + } + } + if (zmsg == Z_NULL) PyErr_Format(ZlibError, "Error %d %s", err, msg); else - PyErr_Format(ZlibError, "Error %d %s: %.200s", err, msg, zst.msg); + PyErr_Format(ZlibError, "Error %d %s: %.200s", err, msg, zmsg); } PyDoc_STRVAR(compressobj__doc__, @@ -241,8 +255,7 @@ * process the inflate call() due to an error in the data. */ if (zst.avail_out > 0) { - PyErr_Format(ZlibError, "Error %i while decompressing data", - err); + zlib_error(zst, err, "while decompressing data"); inflateEnd(&zst); goto error; } From python-checkins at python.org Wed May 12 02:29:27 2010 From: python-checkins at python.org (giampaolo.rodola) Date: Wed, 12 May 2010 02:29:27 +0200 (CEST) Subject: [Python-checkins] r81102 - python/trunk/Lib/test/test_asyncore.py Message-ID: <20100512002927.3BE86EE986@mail.python.org> Author: giampaolo.rodola Date: Wed May 12 02:29:27 2010 New Revision: 81102 Log: Removed the assertion that dispatcher.connected attribute must be False after a single connect() call. Solaris and FreeBSD buildbots failures showed how connect() can succeed even in a single call. All bo failures should definitively be fixed now. Modified: python/trunk/Lib/test/test_asyncore.py Modified: python/trunk/Lib/test/test_asyncore.py ============================================================================== --- python/trunk/Lib/test/test_asyncore.py (original) +++ python/trunk/Lib/test/test_asyncore.py Wed May 12 02:29:27 2010 @@ -618,12 +618,8 @@ # we start disconnected self.assertFalse(server.connected) self.assertTrue(server.accepting) - # XXX - Solaris seems to connect() immediately even without - # starting the poller. This is something which should be - # fixed as handle_connect() gets called immediately even if - # no connection actually took place (see issue #8490). - if not sys.platform.startswith("sunos"): - self.assertFalse(client.connected) + # this can't be taken for granted across all platforms + #self.assertFalse(client.connected) self.assertFalse(client.accepting) # execute some loops so that client connects to server From python-checkins at python.org Wed May 12 02:33:15 2010 From: python-checkins at python.org (giampaolo.rodola) Date: Wed, 12 May 2010 02:33:15 +0200 (CEST) Subject: [Python-checkins] r81103 - in python/branches/py3k: Lib/test/test_asyncore.py Message-ID: <20100512003315.8A28BEE986@mail.python.org> Author: giampaolo.rodola Date: Wed May 12 02:33:15 2010 New Revision: 81103 Log: Merged revisions 81102 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r81102 | giampaolo.rodola | 2010-05-12 02:29:27 +0200 (mer, 12 mag 2010) | 1 line Removed the assertion that dispatcher.connected attribute must be False after a single connect() call. Solaris and FreeBSD buildbots failures showed how connect() can succeed even in a single call. All bo failures should definitively be fixed now. ........ Modified: python/branches/py3k/ (props changed) python/branches/py3k/Lib/test/test_asyncore.py Modified: python/branches/py3k/Lib/test/test_asyncore.py ============================================================================== --- python/branches/py3k/Lib/test/test_asyncore.py (original) +++ python/branches/py3k/Lib/test/test_asyncore.py Wed May 12 02:33:15 2010 @@ -619,12 +619,8 @@ # we start disconnected self.assertFalse(server.connected) self.assertTrue(server.accepting) - # XXX - Solaris seems to connect() immediately even without - # starting the poller. This is something which should be - # fixed as handle_connect() gets called immediately even if - # no connection actually took place (see issue #8490). - if not sys.platform.startswith("sunos"): - self.assertFalse(client.connected) + # this can't be taken for granted across all platforms + #self.assertFalse(client.connected) self.assertFalse(client.accepting) # execute some loops so that client connects to server From python-checkins at python.org Wed May 12 02:38:45 2010 From: python-checkins at python.org (andrew.kuchling) Date: Wed, 12 May 2010 02:38:45 +0200 (CEST) Subject: [Python-checkins] r81104 - python/trunk/Doc/whatsnew/2.7.rst Message-ID: <20100512003845.2E3C4EE993@mail.python.org> Author: andrew.kuchling Date: Wed May 12 02:38:44 2010 New Revision: 81104 Log: Revision pass: lots of edits, typo fixes, rearrangements Modified: python/trunk/Doc/whatsnew/2.7.rst Modified: python/trunk/Doc/whatsnew/2.7.rst ============================================================================== --- python/trunk/Doc/whatsnew/2.7.rst (original) +++ python/trunk/Doc/whatsnew/2.7.rst Wed May 12 02:38:44 2010 @@ -56,12 +56,7 @@ release of 2.7 is currently scheduled for July 2010; the detailed schedule is described in :pep:`373`. -Python 2.7 is planned to be the last of the 2.x releases, so we worked -on making it a good release for the long term. To help with porting -to Python 3, several new features from the Python 3.x series have been -included in 2.7. - -Numeric handling has been improved in many ways, both for +Numeric handling has been improved in many ways, for both floating-point numbers and for the :class:`Decimal` class. There are some useful additions to the standard library, such as a greatly enhanced :mod:`unittest` module, the :mod:`argparse` module for @@ -69,6 +64,11 @@ :class:`Counter` classes in the :mod:`collections` module, and many other improvements. +Python 2.7 is planned to be the last of the 2.x releases, so we worked +on making it a good release for the long term. To help with porting +to Python 3, several new features from the Python 3.x series have been +included in 2.7. + This article doesn't attempt to provide a complete specification of the new features, but instead provides a convenient overview. For full details, you should refer to the documentation for Python 2.7 at @@ -98,7 +98,7 @@ releases beyond the typical two years. * A policy decision was made to silence warnings only of interest to - developers by default. :exc:`DeprecationWarning` and its + developers. :exc:`DeprecationWarning` and its descendants are now ignored unless otherwise requested, preventing users from seeing warnings triggered by an application. This change was also made in the branch that will become Python 3.2. (Discussed @@ -113,13 +113,13 @@ applications who are not directly involved in the development of those applications. :exc:`DeprecationWarning` messages are irrelevant to such users, making them worry about an application - that's actually working correctly and burdening the developers of - these applications with responding to these concerns. + that's actually working correctly and burdening application developers + with responding to these concerns. You can re-enable display of :exc:`DeprecationWarning` messages by running Python with the :option:`-Wdefault` (short form: :option:`-Wd`) switch, or by setting the :envvar:`PYTHONWARNINGS` - environment variable to ``"default"`` or ``"d"``) before running + environment variable to ``"default"`` (or ``"d"``) before running Python. Python code can also re-enable them by calling ``warnings.simplefilter('default')``. @@ -139,24 +139,26 @@ * Multiple context managers in a single :keyword:`with` statement. * A new version of the :mod:`io` library, rewritten in C for performance. * The ordered-dictionary type described in :ref:`pep-0372`. -* The new format specifier described in :ref:`pep-0378`. +* The new ``","`` format specifier described in :ref:`pep-0378`. * The :class:`memoryview` object. -* A small subset of the :mod:`importlib` module `described below <#importlib-section>`__. +* A small subset of the :mod:`importlib` module, + `described below <#importlib-section>`__. * Float-to-string and string-to-float conversions now round their - results more correctly. And :func:`repr` of a floating-point + results more correctly, and :func:`repr` of a floating-point number *x* returns a result that's guaranteed to round back to the same number when converted back to a string. * The :ctype:`PyCapsule` type, used to provide a C API for extension modules. * The :cfunc:`PyLong_AsLongAndOverflow` C API function. -One porting change: the :option:`-3` switch now automatically -enables the :option:`-Qwarn` switch that causes warnings -about using classic division with integers and long integers. - Other new Python3-mode warnings include: * :func:`operator.isCallable` and :func:`operator.sequenceIncludes`, - which are not supported in 3.x. + which are not supported in 3.x, now trigger warnings. +* The :option:`-3` switch now automatically + enables the :option:`-Qwarn` switch that causes warnings + about using classic division with integers and long integers. + + .. ======================================================================== .. Large, PEP-level features and changes should be described here. @@ -170,16 +172,16 @@ Regular Python dictionaries iterate over key/value pairs in arbitrary order. Over the years, a number of authors have written alternative implementations that remember the order that the keys were originally inserted. Based on -the experiences from those implementations, a new -:class:`~collections.OrderedDict` class has been introduced in the -:mod:`collections` module. +the experiences from those implementations, 2.7 introduces a new +:class:`~collections.OrderedDict` class in the :mod:`collections` module. -The :class:`~collections.OrderedDict` API is substantially the same as regular -dictionaries but will iterate over keys and values in a guaranteed order +The :class:`~collections.OrderedDict` API provides the same interface as regular +dictionaries but iterates over keys and values in a guaranteed order depending on when a key was first inserted:: >>> from collections import OrderedDict - >>> d = OrderedDict([('first', 1), ('second', 2), + >>> d = OrderedDict([('first', 1), + ... ('second', 2), ... ('third', 3)]) >>> d.items() [('first', 1), ('second', 2), ('third', 3)] @@ -216,9 +218,11 @@ Comparing two ordered dictionaries checks both the keys and values, and requires that the insertion order was the same:: - >>> od1 = OrderedDict([('first', 1), ('second', 2), + >>> od1 = OrderedDict([('first', 1), + ... ('second', 2), ... ('third', 3)]) - >>> od2 = OrderedDict([('third', 3), ('first', 1), + >>> od2 = OrderedDict([('third', 3), + ... ('first', 1), ... ('second', 2)]) >>> od1 == od2 False @@ -239,9 +243,9 @@ The standard library now supports use of ordered dictionaries in several modules. -* The :mod:`ConfigParser` module uses them by default, letting - configuration files be read, modified, and then written back in their original - order. +* The :mod:`ConfigParser` module uses them by default, meaning that + configuration files can now read, modified, and then written back + in their original order. * The :meth:`~collections.somenamedtuple._asdict()` method for :func:`collections.namedtuple` now returns an ordered dictionary with the @@ -265,7 +269,7 @@ ================================================= To make program output more readable, it can be useful to add -separators to large numbers and render them as +separators to large numbers, rendering them as 18,446,744,073,709,551,616 instead of 18446744073709551616. The fully general solution for doing this is the :mod:`locale` module, @@ -301,13 +305,13 @@ ====================================================== The :mod:`argparse` module for parsing command-line arguments was -added, intended as a more powerful replacement for the +added as a more powerful replacement for the :mod:`optparse` module. This means Python now supports three different modules for parsing command-line arguments: :mod:`getopt`, :mod:`optparse`, and :mod:`argparse`. The :mod:`getopt` module closely resembles the C -:cfunc:`getopt` function, so it remains useful if you're writing a +library's :cfunc:`getopt` function, so it remains useful if you're writing a Python prototype that will eventually be rewritten in C. :mod:`optparse` becomes redundant, but there are no plans to remove it because there are many scripts still using it, and there's no @@ -359,23 +363,28 @@ -o FILE direct output to FILE instead of stdout -C NUM display NUM lines of added context -Similarly to :mod:`optparse`, the command-line switches and arguments +As with :mod:`optparse`, the command-line switches and arguments are returned as an object with attributes named by the *dest* parameters:: -> ./python.exe argparse-example.py -v - {'output': None, 'is_verbose': True, 'context': 0, 'inputs': []} + {'output': None, + 'is_verbose': True, + 'context': 0, + 'inputs': []} -> ./python.exe argparse-example.py -v -o /tmp/output -C 4 file1 file2 - {'output': '/tmp/output', 'is_verbose': True, 'context': 4, + {'output': '/tmp/output', + 'is_verbose': True, + 'context': 4, 'inputs': ['file1', 'file2']} :mod:`argparse` has much fancier validation than :mod:`optparse`; you can specify an exact number of arguments as an integer, 0 or more arguments by passing ``'*'``, 1 or more by passing ``'+'``, or an optional argument with ``'?'``. A top-level parser can contain -sub-parsers, so you can define subcommands that have different sets of +sub-parsers to define subcommands that have different sets of switches, as in ``svn commit``, ``svn checkout``, etc. You can -specify an argument type as :class:`~argparse.FileType`, which will +specify an argument's type as :class:`~argparse.FileType`, which will automatically open files for you and understands that ``'-'`` means standard input or output. @@ -384,6 +393,8 @@ `argparse module documentation `__ `Upgrading optparse code to use argparse `__ + Part of the Python documentation, describing how to convert + code that uses :mod:`optparse`. :pep:`389` - argparse - New Command Line Parsing Module PEP written and implemented by Steven Bethard. @@ -391,26 +402,25 @@ PEP 391: Dictionary-Based Configuration For Logging ==================================================== -.. not documented in library reference yet. +.. XXX not documented in library reference yet; add link here once it's added. -The :mod:`logging` module is very flexible; an application can define +The :mod:`logging` module is very flexible; applications can define a tree of logging subsystems, and each logger in this tree can filter out certain messages, format them differently, and direct messages to a varying number of handlers. All this flexibility can require a lot of configuration. You can write Python statements to create objects and set their properties, -but a complex set-up would require verbose but boring code. +but a complex set-up requires verbose but boring code. :mod:`logging` also supports a :func:`~logging.config.fileConfig` function that parses a file, but the file format doesn't support configuring filters, and it's messier to generate programmatically. Python 2.7 adds a :func:`~logging.config.dictConfig` function that -uses a dictionary, and there are many ways to produce a dictionary -from different sources. You can construct one with code, of course. -Python's standard library now includes a JSON parser, so you could -parse a file containing JSON, or you could use a YAML parsing library -if one is installed. +uses a dictionary to configure logging. There are many ways to +produce a dictionary from different sources: construct one with code; +parse a file containing JSON; or use a YAML parsing library if one is +installed. The following example configures two loggers, the root logger and a logger named "network". Messages sent to the root logger will be @@ -424,17 +434,18 @@ import logging.config configdict = { - 'version': 1, # Must be 1 at present + 'version': 1, # Configuration schema in use; must be 1 for now 'formatters': { 'standard': { - 'format': '%(asctime)s %(name)-15s %(levelname)-8s %(message)s'}}, + 'format': ('%(asctime)s %(name)-15s ' + '%(levelname)-8s %(message)s')}}, 'handlers': {'netlog': {'backupCount': 10, - 'class': 'logging.handlers.RotatingFileHandler', - 'filename': '/logs/network.log', - 'formatter': 'standard', - 'level': 'INFO', - 'maxBytes': 1024*1024}, + 'class': 'logging.handlers.RotatingFileHandler', + 'filename': '/logs/network.log', + 'formatter': 'standard', + 'level': 'INFO', + 'maxBytes': 1024*1024}, 'syslog': {'class': 'logging.handlers.SysLogHandler', 'formatter': 'standard', 'level': 'ERROR'}}, @@ -497,7 +508,7 @@ It's not possible to change the return values of :meth:`keys`, :meth:`values`, and :meth:`items` in Python 2.7 because too much code would break. Instead the 3.x versions were added under the new names -of :meth:`viewkeys`, :meth:`viewvalues`, and :meth:`viewitems`. +:meth:`viewkeys`, :meth:`viewvalues`, and :meth:`viewitems`. :: @@ -507,8 +518,9 @@ >>> d.viewkeys() dict_keys([0, 130, 10, 140, 20, 150, 30, ..., 250]) -Views can be iterated over, but they also behave like sets. The ``&`` -operator performs intersection, and ``|`` performs a union:: +Views can be iterated over, but the key and item views also behave +like sets. The ``&`` operator performs intersection, and ``|`` +performs a union:: >>> d1 = dict((i*10, chr(65+i)) for i in range(26)) >>> d2 = dict((i**.5, i) for i in range(1000)) @@ -566,13 +578,13 @@ >>> m2 -The content of the view can be converted to a string of bytes or to +The content of the view can be converted to a string of bytes or a list of integers: >>> m2.tobytes() 'abcdefghijklmnopqrstuvwxyz' >>> m2.tolist() - [97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122] + [97, 98, 99, 100, 101, 102, 103, ... 121, 122] >>> :class:`memoryview` objects allow modifying the underlying object if @@ -657,8 +669,8 @@ in many different places: :func:`str` on floats and complex numbers; the :class:`float` and :class:`complex` constructors; - numeric formatting; serialization and - deserialization of floats and complex numbers using the + numeric formatting; serializing and + deserializing floats and complex numbers using the :mod:`marshal`, :mod:`pickle` and :mod:`json` modules; parsing of float and imaginary literals in Python code; @@ -673,7 +685,7 @@ .. maybe add an example? The rounding library responsible for this improvement works on - Windows, and on Unix platforms using the gcc, icc, or suncc + Windows and on Unix platforms using the gcc, icc, or suncc compilers. There may be a small number of platforms where correct operation of this code cannot be guaranteed, so the code is not used on such systems. You can find out which code is being used @@ -683,6 +695,33 @@ Implemented by Eric Smith and Mark Dickinson, using David Gay's :file:`dtoa.c` library; :issue:`7117`. +* Conversions from long integers and regular integers to floating + point now round differently, returning the floating-point number + closest to the number. This doesn't matter for small integers that + can be converted exactly, but for large numbers that will + unavoidably lose precision, Python 2.7 now approximates more + closely. For example, Python 2.6 computed the following:: + + >>> n = 295147905179352891391 + >>> float(n) + 2.9514790517935283e+20 + >>> n - long(float(n)) + 65535L + + Python 2.7's floating-point result is larger, but much closer to the + true value:: + + >>> n = 295147905179352891391 + >>> float(n) + 2.9514790517935289e+20 + >>> n - long(float(n)) + -1L + + (Implemented by Mark Dickinson; :issue:`3166`.) + + Integer division is also more accurate in its rounding behaviours. (Also + implemented by Mark Dickinson; :issue:`1811`.) + * The :meth:`str.format` method now supports automatic numbering of the replacement fields. This makes using :meth:`str.format` more closely resemble using ``%s`` formatting:: @@ -713,8 +752,8 @@ A low-level change: the :meth:`object.__format__` method now triggers a :exc:`PendingDeprecationWarning` if it's passed a format string, because the :meth:`__format__` method for :class:`object` converts - the object to a string representation and formats that. The method - used to silently apply the format string to the string + the object to a string representation and formats that. Previously + the method silently applied the format string to the string representation, but that could hide mistakes in Python code. If you're supplying formatting information such as an alignment or precision, presumably you're expecting the formatting to be applied @@ -737,33 +776,6 @@ (Contributed by Fredrik Johansson and Victor Stinner; :issue:`3439`.) -* Conversions from long integers and regular integers to floating - point now round differently, returning the floating-point number - closest to the number. This doesn't matter for small integers that - can be converted exactly, but for large numbers that will - unavoidably lose precision, Python 2.7 now approximates more - closely. For example, Python 2.6 computed the following:: - - >>> n = 295147905179352891391 - >>> float(n) - 2.9514790517935283e+20 - >>> n - long(float(n)) - 65535L - - Python 2.7's floating-point result is larger, but much closer to the - true value:: - - >>> n = 295147905179352891391 - >>> float(n) - 2.9514790517935289e+20 - >>> n - long(float(n)) - -1L - - (Implemented by Mark Dickinson; :issue:`3166`.) - - Integer division is also more accurate in its rounding behaviours. (Also - implemented by Mark Dickinson; :issue:`1811`.) - * It's now possible for a subclass of the built-in :class:`unicode` type to override the :meth:`__unicode__` method. (Implemented by Victor Stinner; :issue:`1583863`.) @@ -796,7 +808,7 @@ (fixed by Stefan Krah; :issue:`5677`). * The Python tokenizer now translates line endings itself, so the - :func:`compile` built-in function can now accept code using any + :func:`compile` built-in function now accepts code using any line-ending convention. Additionally, it no longer requires that the code end in a newline. @@ -829,7 +841,7 @@ For example, the following setting will print warnings every time they occur, but turn warnings from the :mod:`Cookie` module into an error. (The exact syntax for setting an environment variable varies -across operating systems and shells, so it may be different for you.) +across operating systems and shells.) :: @@ -865,7 +877,7 @@ any of them. This would previously take quadratic time for garbage collection, but now the number of full garbage collections is reduced as the number of objects on the heap grows. - The new logic is to only perform a full garbage collection pass when + The new logic only performs a full garbage collection pass when the middle generation has been collected 10 times and when the number of survivor objects from the middle generation exceeds 10% of the number of objects in the oldest generation. (Suggested by Martin @@ -975,10 +987,10 @@ The new version features better Python 3.x compatibility, various bug fixes, and adds several new BerkeleyDB flags and methods. (Updated by Jes?s Cea Avi?n; :issue:`8156`. The pybsddb - changelog can be browsed at http://hg.jcea.es/pybsddb/file/tip/ChangeLog.) + changelog can be read at http://hg.jcea.es/pybsddb/file/tip/ChangeLog.) * The :mod:`bz2` module's :class:`~bz2.BZ2File` now supports the context - management protocol, so you can write ``with bz2.BZ2File(...) as f: ...``. + management protocol, so you can write ``with bz2.BZ2File(...) as f:``. (Contributed by Hagen F?rstenau; :issue:`3860`.) * New class: the :class:`~collections.Counter` class in the :mod:`collections` @@ -1003,7 +1015,7 @@ >>> c['z'] 0 - There are three additional :class:`~collections.Counter` methods: + There are three additional :class:`~collections.Counter` methods. :meth:`~collections.Counter.most_common` returns the N most common elements and their counts. :meth:`~collections.Counter.elements` returns an iterator over the contained elements, repeating each @@ -1030,12 +1042,20 @@ .. revision 79660 - The new :class:`~collections.OrderedDict` class is described in the earlier + New class: :class:`~collections.OrderedDict` is described in the earlier section :ref:`pep-0372`. + New method: The :class:`~collections.deque` data type now has a + :meth:`~collections.deque.count` method that returns the number of + contained elements equal to the supplied argument *x*, and a + :meth:`~collections.deque.reverse` method that reverses the elements + of the deque in-place. :class:`deque` also exposes its maximum + length as the read-only :attr:`~collections.deque.maxlen` attribute. + (Both features added by Raymond Hettinger.) + The :class:`~collections.namedtuple` class now has an optional *rename* parameter. If *rename* is true, field names that are invalid because they've - been repeated or that aren't legal Python identifiers will be + been repeated or aren't legal Python identifiers will be renamed to legal names that are derived from the field's position within the list of fields: @@ -1046,14 +1066,6 @@ (Added by Raymond Hettinger; :issue:`1818`.) - The :class:`~collections.deque` data type now has a - :meth:`~collections.deque.count` method that returns the number of - contained elements equal to the supplied argument *x*, and a - :meth:`~collections.deque.reverse` method that reverses the elements - of the deque in-place. :class:`deque` also exposes its maximum - length as the read-only :attr:`~collections.deque.maxlen` attribute. - (Both features added by Raymond Hettinger.) - * Constructors for the parsing classes in the :mod:`ConfigParser` module now take a *allow_no_value* parameter, defaulting to false; if true, options without values will be allowed. For example:: @@ -1074,14 +1086,14 @@ >>> print config.get('mysqld', 'unknown') Traceback (most recent call last): ... - ConfigParser.NoOptionError: No option 'unknown' in section: 'mysqld' + NoOptionError: No option 'unknown' in section: 'mysqld' (Contributed by Mats Kindahl; :issue:`7005`.) * Deprecated function: :func:`contextlib.nested`, which allows handling more than one context manager with a single :keyword:`with` - statement, has been deprecated, because :keyword:`with` supports - multiple context managers syntactically now. + statement, has been deprecated, because the :keyword:`with` statement + now supports multiple context managers. * The :mod:`copy` module's :func:`~copy.deepcopy` function will now correctly copy bound instance methods. (Implemented by @@ -1101,7 +1113,7 @@ * New method: the :class:`~decimal.Decimal` class gained a :meth:`~decimal.Decimal.from_float` class method that performs an exact conversion of a floating-point number to a :class:`~decimal.Decimal`. - Note that this is an **exact** conversion that strives for the + This exact conversion strives for the closest decimal approximation to the floating-point representation's value; the resulting decimal value will therefore still include the inaccuracy, if any. @@ -1119,19 +1131,19 @@ :class:`Decimal`. (Fixed by Mark Dickinson; :issue:`2531`.) - Most of the methods of the :class:`~decimal.Context` class now accept integers - as well as :class:`~decimal.Decimal` instances; the only exceptions are the - :meth:`~decimal.Context.canonical` and :meth:`~decimal.Context.is_canonical` - methods. (Patch by Juan Jos? Conti; :issue:`7633`.) - The constructor for :class:`~decimal.Decimal` now accepts floating-point numbers (added by Raymond Hettinger; :issue:`8257`) and non-European Unicode characters such as Arabic-Indic digits (contributed by Mark Dickinson; :issue:`6595`). + Most of the methods of the :class:`~decimal.Context` class now accept integers + as well as :class:`~decimal.Decimal` instances; the only exceptions are the + :meth:`~decimal.Context.canonical` and :meth:`~decimal.Context.is_canonical` + methods. (Patch by Juan Jos? Conti; :issue:`7633`.) + When using :class:`~decimal.Decimal` instances with a string's :meth:`~str.format` method, the default alignment was previously - left-alignment. This has been changed to right-alignment, which seems + left-alignment. This has been changed to right-alignment, which is more sensible for numeric types. (Changed by Mark Dickinson; :issue:`6857`.) Comparisons involving a signaling NaN value (or ``sNAN``) now signal @@ -1156,17 +1168,18 @@ rationals added in :issue:`5812`, and float/decimal in :issue:`8294`.) - An oversight was fixed, making the :class:`Fraction` match the other - numeric types; ordering comparisons (``<``, ``<=``, ``>``, ``>=``) between + Ordering comparisons (``<``, ``<=``, ``>``, ``>=``) between fractions and complex numbers now raise a :exc:`TypeError`. + This fixes an oversight, making the :class:`Fraction` match the other + numeric types. .. revision 79455 -* New class: a new :class:`~ftplib.FTP_TLS` class in +* New class: :class:`~ftplib.FTP_TLS` in the :mod:`ftplib` module provides secure FTP connections using TLS encapsulation of authentication as well as subsequent control and data transfers. - (Contributed by Giampaolo Rodola', :issue:`2054`.) + (Contributed by Giampaolo Rodola; :issue:`2054`.) The :meth:`~ftplib.FTP.storbinary` method for binary uploads can now restart uploads thanks to an added *rest* parameter (patch by Pablo Mouzo; @@ -1192,7 +1205,7 @@ otherwise. (Contributed by Antoine Pitrou; :issue:`4688`.) * The :mod:`gzip` module's :class:`~gzip.GzipFile` now supports the context - management protocol, so you can write ``with gzip.GzipFile(...) as f: ...`` + management protocol, so you can write ``with gzip.GzipFile(...) as f:`` (contributed by Hagen F?rstenau; :issue:`3860`), and it now implements the :class:`io.BufferedIOBase` ABC, so you can wrap it with :class:`io.BufferedReader` for faster processing @@ -1208,7 +1221,7 @@ * New attribute: the :mod:`hashlib` module now has an :attr:`~hashlib.hashlib.algorithms` attribute containing a tuple naming the supported algorithms. In Python 2.7, ``hashlib.algorithms`` contains - ``('md5', 'sha1', 'sha224', 'sha256', 'sha384', 'sha512')`` + ``('md5', 'sha1', 'sha224', 'sha256', 'sha384', 'sha512')``. (Contributed by Carl Chenet; :issue:`7418`.) * The default :class:`~httplib.HTTPResponse` class used by the :mod:`httplib` module now @@ -1221,7 +1234,7 @@ (Contributed by Eldon Ziegler; :issue:`3972`.) * The :mod:`ihooks` module now supports relative imports. Note that - :mod:`ihooks` is an older module used to support customizing imports, + :mod:`ihooks` is an older module for customizing imports, superseded by the :mod:`imputil` module added in Python 2.0. (Relative import support added by Neil Schemenauer.) @@ -1239,9 +1252,9 @@ >>> def f(a, b=1, *pos, **named): ... pass >>> getcallargs(f, 1, 2, 3) - {'a': 1, 'named': {}, 'b': 2, 'pos': (3,)} + {'a': 1, 'b': 2, 'pos': (3,), 'named': {}} >>> getcallargs(f, a=2, x=4) - {'a': 2, 'named': {'x': 4}, 'b': 1, 'pos': ()} + {'a': 2, 'b': 1, 'pos': (), 'named': {'x': 4}} >>> getcallargs(f) Traceback (most recent call last): ... @@ -1292,8 +1305,8 @@ floats or :class:`~decimal.Decimal` instances. (Implemented by Raymond Hettinger; :issue:`5032`.) - :func:`itertools.combinations` and :func:`itertools.product` were - previously raising :exc:`ValueError` for values of *r* larger than + :func:`itertools.combinations` and :func:`itertools.product` + previously raised :exc:`ValueError` for values of *r* larger than the input iterable. This was deemed a specification error, so they now return an empty iterator. (Fixed by Raymond Hettinger; :issue:`4816`.) @@ -1343,7 +1356,8 @@ real, effective, and saved GIDs and UIDs; :func:`~os.setresgid` and :func:`~os.setresuid`, which set real, effective, and saved GIDs and UIDs to new values; - :func:`~os.initgroups`. (GID/UID functions + :func:`~os.initgroups`, which initialize the group access list + for the current process. (GID/UID functions contributed by Travis H.; :issue:`6508`. Support for initgroups added by Jean-Paul Calderone; :issue:`7333`.) @@ -1393,9 +1407,9 @@ * New functions: in the :mod:`site` module, three new functions return various site- and user-specific paths. :func:`~site.getsitepackages` returns a list containing all - global site-packages directories, and + global site-packages directories, :func:`~site.getusersitepackages` returns the path of the user's - site-packages directory. + site-packages directory, and :func:`~site.getuserbase` returns the value of the :envvar:`USER_BASE` environment variable, giving the path to a directory that can be used to store data. @@ -1461,7 +1475,7 @@ Another change makes the extension load all of OpenSSL's ciphers and digest algorithms so that they're all available. Some SSL - certificates couldn't be verified, reporting an 'unknown algorithm' + certificates couldn't be verified, reporting an "unknown algorithm" error. (Reported by Beda Kosata, and fixed by Antoine Pitrou; :issue:`8484`.) @@ -1531,7 +1545,7 @@ :mod:`tarfile` now supports filtering the :class:`~tarfile.TarInfo` objects being added to a tar file. When you call :meth:`~tarfile.TarFile.add`, - instance, you may supply an optional *filter* argument + you may supply an optional *filter* argument that's a callable. The *filter* callable will be passed the :class:`~tarfile.TarInfo` for every file being added, and can modify and return it. If the callable returns ``None``, the file will be excluded from the @@ -1609,7 +1623,7 @@ (Contributed by Kristj?n Valur J?nsson; :issue:`6267`.) * The :mod:`zipfile` module's :class:`~zipfile.ZipFile` now supports the context - management protocol, so you can write ``with zipfile.ZipFile(...) as f: ...``. + management protocol, so you can write ``with zipfile.ZipFile(...) as f:``. (Contributed by Brian Curtin; :issue:`5511`.) :mod:`zipfile` now also supports archiving empty directories and @@ -1661,9 +1675,9 @@ >>> anydbm >>> # Relative import - >>> sysconfig = import_module('..sysconfig', 'distutils.command') - >>> sysconfig - + >>> file_util = import_module('..file_util', 'distutils.command') + >>> file_util + :mod:`importlib` was implemented by Brett Cannon and introduced in Python 3.1. @@ -1710,7 +1724,7 @@ on being added to Tcl/Tck release 8.5. To learn more, read the :mod:`ttk` module documentation. You may also -wish to read Tcl/Tk manual page describing the +wish to read the Tcl/Tk manual page describing the Ttk theme engine, available at http://www.tcl.tk/man/tcl8.5/TkCmd/ttk_intro.htm. Some screenshots of the Python/Ttk code in use are at @@ -1751,17 +1765,17 @@ * :option:`-b` or :option:`--buffer` will buffer the standard output and standard error streams during each test. If the test passes, - any resulting output will be discard; on failure, the buffered + any resulting output will be discarded; on failure, the buffered output will be displayed. * :option:`-c` or :option:`--catch` will cause the control-C interrupt to be handled more gracefully. Instead of interrupting the test process immediately, the currently running test will be completed - and then the resulting partial results will be reported. If you're - impatient, a second press of control-C will cause an immediate + and then the partial results up to the interruption will be reported. + If you're impatient, a second press of control-C will cause an immediate interruption. - This control-C handler tries to avoid interfering when the code + This control-C handler tries to avoid causing problems when the code being tested or the tests being run have defined a signal handler of their own, by noticing that a signal handler was already set and calling it. If this doesn't work for you, there's a @@ -1773,12 +1787,12 @@ continuing to execute further tests. (Suggested by Cliff Dyer and implemented by Michael Foord; :issue:`8074`.) -The progress messages now shows 'x' for expected failures +The progress messages now show 'x' for expected failures and 'u' for unexpected successes when run in verbose mode. (Contributed by Benjamin Peterson.) Test cases can raise the :exc:`~unittest.SkipTest` exception to skip a -test. (:issue:`1034053`.) +test (:issue:`1034053`). The error messages for :meth:`~unittest.TestCase.assertEqual`, :meth:`~unittest.TestCase.assertTrue`, and :meth:`~unittest.TestCase.assertFalse` @@ -1788,7 +1802,7 @@ provide will be printed for failures. (Added by Michael Foord; :issue:`5663`.) The :meth:`~unittest.TestCase.assertRaises` method now -return a context handler when called without providing a callable +returns a context handler when called without providing a callable object to run. For example, you can write this:: with self.assertRaises(KeyError): @@ -1808,7 +1822,7 @@ The methods :meth:`~unittest.TestCase.addCleanup` and :meth:`~unittest.TestCase.doCleanups` were added. -:meth:`~unittest.TestCase.addCleanup` allows you to add cleanup functions that +:meth:`~unittest.TestCase.addCleanup` lets you add cleanup functions that will be called unconditionally (after :meth:`~unittest.TestCase.setUp` if :meth:`~unittest.TestCase.setUp` fails, otherwise after :meth:`~unittest.TestCase.tearDown`). This allows for much simpler resource allocation and deallocation during tests @@ -1887,13 +1901,13 @@ objects being compared are of the specified type. This function should compare the two objects and raise an exception if they don't match; it's a good idea for the function to provide additional - information about why the two objects are matching, much as the new + information about why the two objects aren't matching, much as the new sequence comparison methods do. :func:`unittest.main` now takes an optional ``exit`` argument. If -False, :func:`~unittest.main` doesn't call :func:`sys.exit`, allowing it to be -used from the interactive interpreter. (Contributed by J. Pablo -Fern?ndez; :issue:`3379`.) +False, :func:`~unittest.main` doesn't call :func:`sys.exit`, allowing +:func:`main` to be used from the interactive interpreter. +(Contributed by J. Pablo Fern?ndez; :issue:`3379`.) :class:`~unittest.TestResult` has new :meth:`~unittest.TestResult.startTestRun` and :meth:`~unittest.TestResult.stopTestRun` methods that are called immediately before @@ -1916,17 +1930,17 @@ --------------------------------- The version of the ElementTree library included with Python was updated to -version 1.3. Some of the new features in ElementTree 1.3 are: +version 1.3. Some of the new features are: * The various parsing functions now take a *parser* keyword argument - that can be used to provide an :class:`XMLParser` instance that will - be used. This makes it possible to override the file's internal encoding: + giving an :class:`XMLParser` instance that will + be used. This makes it possible to override the file's internal encoding:: p = ET.XMLParser(encoding='utf-8') t = ET.XML("""""", parser=p) - Errors in parsing XML now raise a :exc:`ParseError` exception. - Instances of :exc:`ParseError` have a :attr:`position` attribute + Errors in parsing XML now raise a :exc:`ParseError` exception, whose + instances have a :attr:`position` attribute containing a (*line*, *column*) tuple giving the location of the problem. * ElementTree's code for converting trees to a string has been @@ -1937,15 +1951,15 @@ elements as ```` instead of ````, and text mode will skip over elements and only output the text chunks. If you set the :attr:`tag` attribute of an element to ``None`` but - leaves its children in place, the element will be omitted when the + leave its children in place, the element will be omitted when the tree is written out, so you don't need to do more extensive rearrangement to remove a single element. - Namespace aspects have also been improved. All the ``xmlns:`` - declarations are now put on the root element and not scattered throughout - the resulting output. You can set the default namespace for a tree + Namespace handling has also been improved. All ``xmlns:`` + declarations are now output on the root element, not scattered throughout + the resulting XML. You can set the default namespace for a tree by setting the :attr:`default_namespace` attribute and can - register new prefixes with :meth:`regsiter_namespace`. In XML mode, + register new prefixes with :meth:`register_namespace`. In XML mode, you can use the true/false *xml_declaration* parameter to suppress the XML declaration. @@ -1967,10 +1981,9 @@ * New :class:`Element` method: :meth:`iter` yields the children of the element as a generator. It's also possible to write ``for child in - elem: ...`` to loop over an element's children. The existing method - :meth:`getiterator` is now deprecated. :meth:`getchildren` is - another similar method that constructs and returns a list of - children; it's also deprecated. + elem:`` to loop over an element's children. The existing method + :meth:`getiterator` is now deprecated, as is :meth:`getchildren` + which constructs and returns a list of children. * New :class:`Element` method: :meth:`itertext` yields all chunks of text that are descendants of the element. For example:: @@ -1982,13 +1995,13 @@ # Outputs ['\n ', '1', ' ', '2', ' ', '3', '\n'] print list(t.itertext()) -* Deprecated: using an element as a Boolean (i.e., ``if elem: ...``) - would return true if the element had any children, or false if - there were no children. This behaviour will eventually change or be removed - because it's confusing (``None`` is false, but so is a childless element?), - so it will now trigger a :exc:`FutureWarning`. In your code, - you should be explicit: write ``len(elem) != 0`` if you're interested in - the number of children, or ``elem is not None`` Instead, +* Deprecated: using an element as a Boolean (i.e., ``if elem:``) would + return true if the element had any children, or false if there were + no children. This behaviour is confusing -- ``None`` is false, but + so is a childless element? -- so it will now trigger a + :exc:`FutureWarning`. In your code, you should be explicit: write + ``len(elem) != 0`` if you're interested in the number of children, + or ``elem is not None``. Fredrik Lundh develops ElementTree and produced the 1.3 version; you can read his article describing 1.3 at @@ -2009,9 +2022,9 @@ `__. When you begin debugging an executable program P, GDB will look for a file named ``P-gdb.py`` and automatically read it. Dave Malcolm - contributed a :file:`python-gdb.py` that adds a number of useful - commands when debugging Python itself. For example, there are - ``py-up`` and ``py-down`` that go up or down one Python stack frame, + contributed a :file:`python-gdb.py` that adds a number of + commands useful when debugging Python itself. For example, + ``py-up`` and ``py-down`` go up or down one Python stack frame, which usually corresponds to several C stack frames. ``py-print`` prints the value of a Python variable, and ``py-bt`` prints the Python stack trace. (Added as a result of :issue:`8032`.) @@ -2028,7 +2041,7 @@ * New function: :cfunc:`PyCode_NewEmpty` creates an empty code object; only the filename, function name, and first line number are required. - This is useful to extension modules that are attempting to + This is useful for extension modules that are attempting to construct a more useful traceback stack. Previously such extensions needed to call :cfunc:`PyCode_New`, which had many more arguments. (Added by Jeffrey Yasskin.) @@ -2036,7 +2049,7 @@ * New function: :cfunc:`PyErr_NewExceptionWithDoc` creates a new exception class, just as the existing :cfunc:`PyErr_NewException` does, but takes an extra ``char *`` argument containing the docstring for the - new exception class. (Added by the 'lekma' user on the Python bug tracker; + new exception class. (Added by 'lekma' on the Python bug tracker; :issue:`7033`.) * New function: :cfunc:`PyFrame_GetLineNumber` takes a frame object @@ -2078,11 +2091,11 @@ * Removed function: :cmacro:`PyEval_CallObject` is now only available as a macro. A function version was being kept around to preserve ABI linking compatibility, but that was in 1997; it can certainly be - deleted. (Removed by Antoine Pitrou; :issue:`8276`.) + deleted by now. (Removed by Antoine Pitrou; :issue:`8276`.) * New format codes: the :cfunc:`PyFormat_FromString`, - :cfunc:`PyFormat_FromStringV`, and :cfunc:`PyErr_Format` now - accepts ``%lld`` and ``%llu`` format codes for displaying values of + :cfunc:`PyFormat_FromStringV`, and :cfunc:`PyErr_Format` functions now + accept ``%lld`` and ``%llu`` format codes for displaying C's :ctype:`long long` types. (Contributed by Mark Dickinson; :issue:`7228`.) @@ -2096,7 +2109,7 @@ ever release the lock, since the other threads weren't replicated, and the child process would no longer be able to perform imports. - Python 2.7 now acquires the import lock before performing an + Python 2.7 acquires the import lock before performing an :func:`os.fork`, and will also clean up any locks created using the :mod:`threading` module. C extension modules that have internal locks, or that call :cfunc:`fork()` themselves, will not benefit @@ -2123,15 +2136,15 @@ building the :mod:`pyexpat` module to use the system Expat library. (Contributed by Arfrever Frehtes Taifersar Arahesis; :issue:`7609`.) -* New configure option: compiling Python with the +* New configure option: the :option:`--with-valgrind` option will now disable the pymalloc allocator, which is difficult for the Valgrind memory-error detector to analyze correctly. Valgrind will therefore be better at detecting memory leaks and overruns. (Contributed by James Henstridge; :issue:`2422`.) -* New configure option: you can now supply no arguments to - :option:`--with-dbmliborder=` in order to build none of the various +* New configure option: you can now supply an empty string to + :option:`--with-dbmliborder=` in order to disable all of the various DBM modules. (Added by Arfrever Frehtes Taifersar Arahesis; :issue:`6491`.) @@ -2158,15 +2171,15 @@ ------------------- Python 3.1 adds a new C datatype, :ctype:`PyCapsule`, for providing a -C API to an extension module. A capsule is essentially the holder for -a C ``void *`` pointer, and is bound to a module attribute; for +C API to an extension module. A capsule is essentially the holder of +a C ``void *`` pointer, and is made available as a module attribute; for example, the :mod:`socket` module's API is exposed as ``socket.CAPI``, -and :mod:`unicodedata` calls it ``ucnhash_CAPI``. Other extensions +and :mod:`unicodedata` exposes ``ucnhash_CAPI``. Other extensions can import the module, access its dictionary to get the capsule object, and then get the ``void *`` pointer, which will usually point -to an array of pointers to the various API functions. +to an array of pointers to the module's various API functions. -There is an existing data type that already does this, +There is an existing data type already used for this, :ctype:`PyCObject`, but it doesn't provide type safety. Evil code written in pure Python could cause a segmentation fault by taking a :ctype:`PyCObject` from module A and somehow substituting it for the @@ -2224,10 +2237,10 @@ * The :func:`os.kill` function now works on Windows. The signal value can be the constants :const:`CTRL_C_EVENT`, - :const:`CTRL_BREAK_EVENT`, or any integer. The Control-C and - Control-Break keystroke events can be sent to subprocesses; any - other value will use the :cfunc:`TerminateProcess` API. - (Contributed by Miki Tebeka; :issue:`1220212`.) + :const:`CTRL_BREAK_EVENT`, or any integer. The first two constants + will send Control-C and Control-Break keystroke events to + subprocesses; any other value will use the :cfunc:`TerminateProcess` + API. (Contributed by Miki Tebeka; :issue:`1220212`.) * The :func:`os.listdir` function now correctly fails for an empty path. (Fixed by Hirokazu Yamamoto; :issue:`5913`.) @@ -2259,7 +2272,7 @@ * Two benchmark scripts, :file:`iobench` and :file:`ccbench`, were added to the :file:`Tools` directory. :file:`iobench` measures the - speed of built-in file I/O objects (as returned by :func:`open`) + speed of the built-in file I/O objects returned by :func:`open` while performing various operations, and :file:`ccbench` is a concurrency benchmark that tries to measure computing throughput, thread switching latency, and IO processing bandwidth when @@ -2354,6 +2367,14 @@ identifier instead of the previous default value of ``'python'``. (Changed by Sean Reifschneider; :issue:`8451`.) +* The :mod:`tarfile` module's default error handling has changed, to + no longer suppress fatal errors. The default error level was previously 0, + which meant that errors would only result in a message being written to the + debug log, but because the debug log is not activated by default, + these errors go unnoticed. The default error level is now 1, + which raises an exception if there's an error. + (Changed by Lars Gust?bel; :issue:`7357`.) + * The :mod:`urlparse` module's :func:`~urlparse.urlsplit` now handles unknown URL schemes in a fashion compliant with :rfc:`3986`: if the URL is of the form ``"://..."``, the text before the From python-checkins at python.org Wed May 12 02:40:47 2010 From: python-checkins at python.org (andrew.kuchling) Date: Wed, 12 May 2010 02:40:47 +0200 (CEST) Subject: [Python-checkins] r81105 - python/trunk/Doc/howto/functional.rst Message-ID: <20100512004047.C5471E3E6@mail.python.org> Author: andrew.kuchling Date: Wed May 12 02:40:47 2010 New Revision: 81105 Log: Let's call this done Modified: python/trunk/Doc/howto/functional.rst Modified: python/trunk/Doc/howto/functional.rst ============================================================================== --- python/trunk/Doc/howto/functional.rst (original) +++ python/trunk/Doc/howto/functional.rst Wed May 12 02:40:47 2010 @@ -5,9 +5,6 @@ :Author: A. M. Kuchling :Release: 0.31 -(This is a first draft. Please send comments/error reports/suggestions to -amk at amk.ca.) - In this document, we'll take a tour of Python's features suitable for implementing programs in a functional style. After an introduction to the concepts of functional programming, we'll look at language features such as From python-checkins at python.org Wed May 12 03:22:03 2010 From: python-checkins at python.org (fred.drake) Date: Wed, 12 May 2010 03:22:03 +0200 (CEST) Subject: [Python-checkins] r81106 - python/trunk/Doc/library/httplib.rst Message-ID: <20100512012203.B58FEEE986@mail.python.org> Author: fred.drake Date: Wed May 12 03:22:03 2010 New Revision: 81106 Log: fix error introduced in previous commit, and the adjacent additional typo Modified: python/trunk/Doc/library/httplib.rst Modified: python/trunk/Doc/library/httplib.rst ============================================================================== --- python/trunk/Doc/library/httplib.rst (original) +++ python/trunk/Doc/library/httplib.rst Wed May 12 03:22:03 2010 @@ -560,9 +560,8 @@ >>> data2 = r2.read() >>> conn.close() -Here is an example session that uses the ``HEAD`` method. Note that``HEAD`` -method never returns any data. :: - +Here is an example session that uses the ``HEAD`` method. Note that the +``HEAD`` method never returns any data. :: >>> import httplib >>> conn = httplib.HTTPConnection("www.python.org") From python-checkins at python.org Wed May 12 03:36:11 2010 From: python-checkins at python.org (fred.drake) Date: Wed, 12 May 2010 03:36:11 +0200 (CEST) Subject: [Python-checkins] r81107 - in python/branches/py3k: Doc/library/http.client.rst Message-ID: <20100512013611.9411CEE9E3@mail.python.org> Author: fred.drake Date: Wed May 12 03:36:11 2010 New Revision: 81107 Log: Merged revisions 81087,81106 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r81087 | fred.drake | 2010-05-11 14:12:27 -0400 (Tue, 11 May 2010) | 2 lines fix typo ........ r81106 | fred.drake | 2010-05-11 21:22:03 -0400 (Tue, 11 May 2010) | 2 lines fix error introduced in previous commit, and the adjacent additional typo ........ Modified: python/branches/py3k/ (props changed) python/branches/py3k/Doc/library/http.client.rst Modified: python/branches/py3k/Doc/library/http.client.rst ============================================================================== --- python/branches/py3k/Doc/library/http.client.rst (original) +++ python/branches/py3k/Doc/library/http.client.rst Wed May 12 03:36:11 2010 @@ -521,9 +521,8 @@ >>> data2 = r2.read() >>> conn.close() -Here is an example session that uses ``HEAD`` method. Note that ``HEAD`` method -never returns any data. :: - +Here is an example session that uses the ``HEAD`` method. Note that the +``HEAD`` method never returns any data. :: >>> import http.client >>> conn = http.client.HTTPConnection("www.python.org") From python-checkins at python.org Wed May 12 04:24:50 2010 From: python-checkins at python.org (fred.drake) Date: Wed, 12 May 2010 04:24:50 +0200 (CEST) Subject: [Python-checkins] r81108 - python/trunk/Doc/library/xml.dom.rst Message-ID: <20100512022450.50E2DC8FB@mail.python.org> Author: fred.drake Date: Wed May 12 04:24:50 2010 New Revision: 81108 Log: - clarify Attr.name comment on the presence of colons in namespace mode - document Attr.value - wrap some long lines Modified: python/trunk/Doc/library/xml.dom.rst Modified: python/trunk/Doc/library/xml.dom.rst ============================================================================== --- python/trunk/Doc/library/xml.dom.rst (original) +++ python/trunk/Doc/library/xml.dom.rst Wed May 12 04:24:50 2010 @@ -705,18 +705,27 @@ .. attribute:: Attr.name - The attribute name. In a namespace-using document it may have colons in it. + The attribute name. + In a namespace-using document it may include a colon. .. attribute:: Attr.localName - The part of the name following the colon if there is one, else the entire name. + The part of the name following the colon if there is one, else the + entire name. This is a read-only attribute. .. attribute:: Attr.prefix - The part of the name preceding the colon if there is one, else the empty string. + The part of the name preceding the colon if there is one, else the + empty string. + + +.. attribute:: Attr.value + + The text value of the attribute. This is a synonym for the + :attr:`nodeValue` attribute. .. _dom-attributelist-objects: From python-checkins at python.org Wed May 12 04:34:50 2010 From: python-checkins at python.org (fred.drake) Date: Wed, 12 May 2010 04:34:50 +0200 (CEST) Subject: [Python-checkins] r81109 - in python/branches/py3k: Doc/library/xml.dom.rst Message-ID: <20100512023450.CA767EE9B5@mail.python.org> Author: fred.drake Date: Wed May 12 04:34:50 2010 New Revision: 81109 Log: Merged revisions 81108 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r81108 | fred.drake | 2010-05-11 22:24:50 -0400 (Tue, 11 May 2010) | 4 lines - clarify Attr.name comment on the presence of colons in namespace mode - document Attr.value - wrap some long lines ........ Modified: python/branches/py3k/ (props changed) python/branches/py3k/Doc/library/xml.dom.rst Modified: python/branches/py3k/Doc/library/xml.dom.rst ============================================================================== --- python/branches/py3k/Doc/library/xml.dom.rst (original) +++ python/branches/py3k/Doc/library/xml.dom.rst Wed May 12 04:34:50 2010 @@ -693,18 +693,27 @@ .. attribute:: Attr.name - The attribute name. In a namespace-using document it may have colons in it. + The attribute name. + In a namespace-using document it may include a colon. .. attribute:: Attr.localName - The part of the name following the colon if there is one, else the entire name. + The part of the name following the colon if there is one, else the + entire name. This is a read-only attribute. .. attribute:: Attr.prefix - The part of the name preceding the colon if there is one, else the empty string. + The part of the name preceding the colon if there is one, else the + empty string. + + +.. attribute:: Attr.value + + The text value of the attribute. This is a synonym for the + :attr:`nodeValue` attribute. .. _dom-attributelist-objects: From python-checkins at python.org Wed May 12 08:52:19 2010 From: python-checkins at python.org (jeffrey.yasskin) Date: Wed, 12 May 2010 08:52:19 +0200 (CEST) Subject: [Python-checkins] r81110 - python/branches/py3k-jit/Util/PySmallPtrSet.h Message-ID: <20100512065219.F2541EEA25@mail.python.org> Author: jeffrey.yasskin Date: Wed May 12 08:52:19 2010 New Revision: 81110 Log: Pull Python.h out of the extern "C" section. Modified: python/branches/py3k-jit/Util/PySmallPtrSet.h Modified: python/branches/py3k-jit/Util/PySmallPtrSet.h ============================================================================== --- python/branches/py3k-jit/Util/PySmallPtrSet.h (original) +++ python/branches/py3k-jit/Util/PySmallPtrSet.h Wed May 12 08:52:19 2010 @@ -7,13 +7,12 @@ #ifndef UTIL_PYSMALLPTRSET_H #define UTIL_PYSMALLPTRSET_H +#include "Python.h" + #ifdef __cplusplus extern "C" { #endif -#include "Python.h" - - typedef struct PySmallPtrSet PySmallPtrSet; typedef void(*PySmallPtrSetCallback)(PyObject *, void *); From python-checkins at python.org Wed May 12 12:39:57 2010 From: python-checkins at python.org (tarek.ziade) Date: Wed, 12 May 2010 12:39:57 +0200 Subject: [Python-checkins] distutils2: now test_conversion will try to convert files from conversions/XX_before.py and Message-ID: tarek.ziade pushed d090528dd899 to distutils2: http://hg.python.org/distutils2/rev/d090528dd899 changeset: 135:d090528dd899 tag: tip user: Tarek Ziade date: Wed May 12 12:39:46 2010 +0200 summary: now test_conversion will try to convert files from conversions/XX_before.py and assert the result is conversions/XX_after.py. This will make it easier to add more refactoring use cases. files: src/distutils2/tests/conversions/01_after.py, src/distutils2/tests/conversions/01_before.py, src/distutils2/tests/test_converter.py diff --git a/src/distutils2/tests/conversions/01_after.py b/src/distutils2/tests/conversions/01_after.py new file mode 100644 --- /dev/null +++ b/src/distutils2/tests/conversions/01_after.py @@ -0,0 +1,4 @@ +from distutils2.core import setup + +setup(name='Foo') + diff --git a/src/distutils2/tests/conversions/01_before.py b/src/distutils2/tests/conversions/01_before.py new file mode 100644 --- /dev/null +++ b/src/distutils2/tests/conversions/01_before.py @@ -0,0 +1,4 @@ +from distutils.core import setup + +setup(name='Foo') + diff --git a/src/distutils2/tests/test_converter.py b/src/distutils2/tests/test_converter.py --- a/src/distutils2/tests/test_converter.py +++ b/src/distutils2/tests/test_converter.py @@ -1,5 +1,9 @@ """Tests for distutils.converter.""" +import os import unittest2 + +_CURDIR = os.path.dirname(__file__) + from distutils2.converter import DistutilsRefactoringTool _ORIGINAL = """\ @@ -13,13 +17,32 @@ setup(name='Foo') """ + +def _read_file(path): + # yes, distutils2 is 2.4 compatible, so, no with... + f = open(path) + try: + return f.read() + finally: + f.close() + + class ConverterTestCase(unittest2.TestCase): - def test_import(self): - # simplest case: renaming distutils import in setup.py + + def test_conversions(self): + # for all XX_before in the conversions/ dir + # we run the refactoring tool ref = DistutilsRefactoringTool() - res = ref.refactor_string(_ORIGINAL, 'setup.py') - self.assertEquals(str(res), _WANTED) + convdir = os.path.join(_CURDIR, 'conversions') + for file_ in os.listdir(convdir): + if 'after' in file_ or not file_.endswith('py'): + continue + original = _read_file(os.path.join(convdir, file_)) + wanted = file_.replace('before', 'after') + wanted = _read_file(os.path.join(convdir, wanted)) + res = ref.refactor_string(original, 'setup.py') + self.assertEquals(str(res), wanted) def test_suite(): return unittest2.makeSuite(ConverterTestCase) -- Repository URL: http://hg.python.org/distutils2 From python-checkins at python.org Wed May 12 15:56:07 2010 From: python-checkins at python.org (andrew.kuchling) Date: Wed, 12 May 2010 15:56:07 +0200 (CEST) Subject: [Python-checkins] r81114 - python/trunk/Doc/documenting/style.rst Message-ID: <20100512135607.6449DFD22@mail.python.org> Author: andrew.kuchling Date: Wed May 12 15:56:07 2010 New Revision: 81114 Log: Grammar fix Modified: python/trunk/Doc/documenting/style.rst Modified: python/trunk/Doc/documenting/style.rst ============================================================================== --- python/trunk/Doc/documenting/style.rst (original) +++ python/trunk/Doc/documenting/style.rst Wed May 12 15:56:07 2010 @@ -7,7 +7,7 @@ wherever possible. This particular style guide was selected mostly because it seems reasonable and is easy to get online. -Topics which are not covered in the Apple's style guide will be discussed in +Topics which are not covered in Apple's style guide will be discussed in this document. All reST files use an indentation of 3 spaces. The maximum line length is 80 From python-checkins at python.org Wed May 12 16:02:35 2010 From: python-checkins at python.org (antoine.pitrou) Date: Wed, 12 May 2010 16:02:35 +0200 (CEST) Subject: [Python-checkins] r81115 - python/trunk/Modules/_ssl.c Message-ID: <20100512140235.2B7F8EE996@mail.python.org> Author: antoine.pitrou Date: Wed May 12 16:02:34 2010 New Revision: 81115 Log: Improve _ssl.c formatting Modified: python/trunk/Modules/_ssl.c Modified: python/trunk/Modules/_ssl.c ============================================================================== --- python/trunk/Modules/_ssl.c (original) +++ python/trunk/Modules/_ssl.c Wed May 12 16:02:34 2010 @@ -181,8 +181,7 @@ break; case SSL_ERROR_WANT_X509_LOOKUP: p = PY_SSL_ERROR_WANT_X509_LOOKUP; - errstr = - "The operation did not complete (X509 lookup)"; + errstr = "The operation did not complete (X509 lookup)"; break; case SSL_ERROR_WANT_CONNECT: p = PY_SSL_ERROR_WANT_CONNECT; @@ -193,15 +192,14 @@ unsigned long e = ERR_get_error(); if (e == 0) { if (ret == 0 || !obj->Socket) { - p = PY_SSL_ERROR_EOF; - errstr = - "EOF occurred in violation of protocol"; + p = PY_SSL_ERROR_EOF; + errstr = "EOF occurred in violation of protocol"; } else if (ret == -1) { - /* underlying BIO reported an I/O error */ - return obj->Socket->errorhandler(); + /* underlying BIO reported an I/O error */ + return obj->Socket->errorhandler(); } else { /* possible? */ - p = PY_SSL_ERROR_SYSCALL; - errstr = "Some I/O error occurred"; + p = PY_SSL_ERROR_SYSCALL; + errstr = "Some I/O error occurred"; } } else { p = PY_SSL_ERROR_SYSCALL; @@ -218,8 +216,7 @@ /* XXX Protected by global interpreter lock */ errstr = ERR_error_string(e, NULL); else { /* possible? */ - errstr = - "A failure in the SSL library occurred"; + errstr = "A failure in the SSL library occurred"; } break; } @@ -324,7 +321,7 @@ if (certreq != PY_SSL_CERT_NONE) { if (cacerts_file == NULL) { errstr = ERRSTR("No root certificates specified for " - "verification of other-side certificates."); + "verification of other-side certificates."); goto fail; } else { PySSL_BEGIN_ALLOW_THREADS @@ -481,15 +478,15 @@ } if (sockstate == SOCKET_HAS_TIMED_OUT) { PyErr_SetString(PySSLErrorObject, - ERRSTR("The handshake operation timed out")); + ERRSTR("The handshake operation timed out")); return NULL; } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) { PyErr_SetString(PySSLErrorObject, - ERRSTR("Underlying socket has been closed.")); + ERRSTR("Underlying socket has been closed.")); return NULL; } else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) { PyErr_SetString(PySSLErrorObject, - ERRSTR("Underlying socket too large for select().")); + ERRSTR("Underlying socket too large for select().")); return NULL; } else if (sockstate == SOCKET_IS_NONBLOCKING) { break; @@ -552,7 +549,7 @@ goto fail; } value_obj = PyUnicode_DecodeUTF8((char *) valuebuf, - buflen, "strict"); + buflen, "strict"); OPENSSL_free(valuebuf); if (value_obj == NULL) { Py_DECREF(name_obj); @@ -1205,11 +1202,9 @@ goto error; } if (err == SSL_ERROR_WANT_READ) { - sockstate = - check_socket_and_wait_for_timeout(self->Socket, 0); + sockstate = check_socket_and_wait_for_timeout(self->Socket, 0); } else if (err == SSL_ERROR_WANT_WRITE) { - sockstate = - check_socket_and_wait_for_timeout(self->Socket, 1); + sockstate = check_socket_and_wait_for_timeout(self->Socket, 1); } else { sockstate = SOCKET_OPERATION_OK; } @@ -1296,7 +1291,7 @@ return NULL; } else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) { PyErr_SetString(PySSLErrorObject, - "Underlying socket too large for select()."); + "Underlying socket too large for select()."); Py_DECREF(buf); return NULL; } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) { @@ -1305,7 +1300,7 @@ { Py_DECREF(buf); PyErr_SetString(PySSLErrorObject, - "Socket closed without SSL shutdown handshake"); + "Socket closed without SSL shutdown handshake"); return NULL; } else { /* should contain a zero-length string */ @@ -1324,11 +1319,9 @@ return NULL; } if (err == SSL_ERROR_WANT_READ) { - sockstate = - check_socket_and_wait_for_timeout(self->Socket, 0); + sockstate = check_socket_and_wait_for_timeout(self->Socket, 0); } else if (err == SSL_ERROR_WANT_WRITE) { - sockstate = - check_socket_and_wait_for_timeout(self->Socket, 1); + sockstate = check_socket_and_wait_for_timeout(self->Socket, 1); } else if ((err == SSL_ERROR_ZERO_RETURN) && (SSL_get_shutdown(self->ssl) == SSL_RECEIVED_SHUTDOWN)) @@ -1499,7 +1492,7 @@ double entropy; if (!PyArg_ParseTuple(args, "s#d:RAND_add", &buf, &len, &entropy)) - return NULL; + return NULL; RAND_add(buf, len, entropy); Py_INCREF(Py_None); return Py_None; @@ -1530,15 +1523,15 @@ int bytes; if (!PyString_Check(arg)) - return PyErr_Format(PyExc_TypeError, - "RAND_egd() expected string, found %s", - Py_TYPE(arg)->tp_name); + return PyErr_Format(PyExc_TypeError, + "RAND_egd() expected string, found %s", + Py_TYPE(arg)->tp_name); bytes = RAND_egd(PyString_AS_STRING(arg)); if (bytes == -1) { - PyErr_SetString(PySSLErrorObject, - "EGD connection failed or EGD did not return " - "enough data to seed the PRNG"); - return NULL; + PyErr_SetString(PySSLErrorObject, + "EGD connection failed or EGD did not return " + "enough data to seed the PRNG"); + return NULL; } return PyInt_FromLong(bytes); } From python-checkins at python.org Wed May 12 16:05:24 2010 From: python-checkins at python.org (antoine.pitrou) Date: Wed, 12 May 2010 16:05:24 +0200 (CEST) Subject: [Python-checkins] r81116 - in python/branches/py3k: Modules/_ssl.c Message-ID: <20100512140524.7C5EEEE9B1@mail.python.org> Author: antoine.pitrou Date: Wed May 12 16:05:24 2010 New Revision: 81116 Log: Merged revisions 81115 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r81115 | antoine.pitrou | 2010-05-12 16:02:34 +0200 (mer., 12 mai 2010) | 3 lines Improve _ssl.c formatting ........ Modified: python/branches/py3k/ (props changed) python/branches/py3k/Modules/_ssl.c Modified: python/branches/py3k/Modules/_ssl.c ============================================================================== --- python/branches/py3k/Modules/_ssl.c (original) +++ python/branches/py3k/Modules/_ssl.c Wed May 12 16:05:24 2010 @@ -182,8 +182,7 @@ break; case SSL_ERROR_WANT_X509_LOOKUP: p = PY_SSL_ERROR_WANT_X509_LOOKUP; - errstr = - "The operation did not complete (X509 lookup)"; + errstr = "The operation did not complete (X509 lookup)"; break; case SSL_ERROR_WANT_CONNECT: p = PY_SSL_ERROR_WANT_CONNECT; @@ -196,15 +195,14 @@ PySocketSockObject *s = (PySocketSockObject *) PyWeakref_GetObject(obj->Socket); if (ret == 0 || (((PyObject *)s) == Py_None)) { - p = PY_SSL_ERROR_EOF; - errstr = - "EOF occurred in violation of protocol"; + p = PY_SSL_ERROR_EOF; + errstr = "EOF occurred in violation of protocol"; } else if (ret == -1) { - /* underlying BIO reported an I/O error */ - return s->errorhandler(); + /* underlying BIO reported an I/O error */ + return s->errorhandler(); } else { /* possible? */ - p = PY_SSL_ERROR_SYSCALL; - errstr = "Some I/O error occurred"; + p = PY_SSL_ERROR_SYSCALL; + errstr = "Some I/O error occurred"; } } else { p = PY_SSL_ERROR_SYSCALL; @@ -221,8 +219,7 @@ /* XXX Protected by global interpreter lock */ errstr = ERR_error_string(e, NULL); else { /* possible? */ - errstr = - "A failure in the SSL library occurred"; + errstr = "A failure in the SSL library occurred"; } break; } @@ -325,7 +322,7 @@ if (certreq != PY_SSL_CERT_NONE) { if (cacerts_file == NULL) { errstr = ERRSTR("No root certificates specified for " - "verification of other-side certificates."); + "verification of other-side certificates."); goto fail; } else { PySSL_BEGIN_ALLOW_THREADS @@ -490,15 +487,15 @@ } if (sockstate == SOCKET_HAS_TIMED_OUT) { PyErr_SetString(PySSLErrorObject, - ERRSTR("The handshake operation timed out")); + ERRSTR("The handshake operation timed out")); return NULL; } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) { PyErr_SetString(PySSLErrorObject, - ERRSTR("Underlying socket has been closed.")); + ERRSTR("Underlying socket has been closed.")); return NULL; } else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) { PyErr_SetString(PySSLErrorObject, - ERRSTR("Underlying socket too large for select().")); + ERRSTR("Underlying socket too large for select().")); return NULL; } else if (sockstate == SOCKET_IS_NONBLOCKING) { break; @@ -544,7 +541,7 @@ goto fail; } value_obj = PyUnicode_DecodeUTF8((char *) valuebuf, - buflen, "strict"); + buflen, "strict"); OPENSSL_free(valuebuf); if (value_obj == NULL) { Py_DECREF(name_obj); @@ -1217,11 +1214,9 @@ goto error; } if (err == SSL_ERROR_WANT_READ) { - sockstate = - check_socket_and_wait_for_timeout(sock, 0); + sockstate = check_socket_and_wait_for_timeout(sock, 0); } else if (err == SSL_ERROR_WANT_WRITE) { - sockstate = - check_socket_and_wait_for_timeout(sock, 1); + sockstate = check_socket_and_wait_for_timeout(sock, 1); } else { sockstate = SOCKET_OPERATION_OK; } @@ -1334,7 +1329,7 @@ goto error; } else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) { PyErr_SetString(PySSLErrorObject, - "Underlying socket too large for select()."); + "Underlying socket too large for select()."); goto error; } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) { count = 0; @@ -1350,11 +1345,9 @@ if (PyErr_CheckSignals()) goto error; if (err == SSL_ERROR_WANT_READ) { - sockstate = - check_socket_and_wait_for_timeout(sock, 0); + sockstate = check_socket_and_wait_for_timeout(sock, 0); } else if (err == SSL_ERROR_WANT_WRITE) { - sockstate = - check_socket_and_wait_for_timeout(sock, 1); + sockstate = check_socket_and_wait_for_timeout(sock, 1); } else if ((err == SSL_ERROR_ZERO_RETURN) && (SSL_get_shutdown(self->ssl) == SSL_RECEIVED_SHUTDOWN)) @@ -1547,7 +1540,7 @@ double entropy; if (!PyArg_ParseTuple(args, "s#d:RAND_add", &buf, &len, &entropy)) - return NULL; + return NULL; RAND_add(buf, len, entropy); Py_INCREF(Py_None); return Py_None; @@ -1578,15 +1571,15 @@ int bytes; if (!PyUnicode_Check(arg)) - return PyErr_Format(PyExc_TypeError, - "RAND_egd() expected string, found %s", - Py_TYPE(arg)->tp_name); + return PyErr_Format(PyExc_TypeError, + "RAND_egd() expected string, found %s", + Py_TYPE(arg)->tp_name); bytes = RAND_egd(_PyUnicode_AsString(arg)); if (bytes == -1) { - PyErr_SetString(PySSLErrorObject, - "EGD connection failed or EGD did not return " - "enough data to seed the PRNG"); - return NULL; + PyErr_SetString(PySSLErrorObject, + "EGD connection failed or EGD did not return " + "enough data to seed the PRNG"); + return NULL; } return PyLong_FromLong(bytes); } From python-checkins at python.org Wed May 12 16:05:34 2010 From: python-checkins at python.org (antoine.pitrou) Date: Wed, 12 May 2010 16:05:34 +0200 (CEST) Subject: [Python-checkins] r81117 - in python/branches/release26-maint: Modules/_ssl.c Message-ID: <20100512140534.A0A3AEE9AF@mail.python.org> Author: antoine.pitrou Date: Wed May 12 16:05:34 2010 New Revision: 81117 Log: Merged revisions 81115 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r81115 | antoine.pitrou | 2010-05-12 16:02:34 +0200 (mer., 12 mai 2010) | 3 lines Improve _ssl.c formatting ........ Modified: python/branches/release26-maint/ (props changed) python/branches/release26-maint/Modules/_ssl.c Modified: python/branches/release26-maint/Modules/_ssl.c ============================================================================== --- python/branches/release26-maint/Modules/_ssl.c (original) +++ python/branches/release26-maint/Modules/_ssl.c Wed May 12 16:05:34 2010 @@ -181,8 +181,7 @@ break; case SSL_ERROR_WANT_X509_LOOKUP: p = PY_SSL_ERROR_WANT_X509_LOOKUP; - errstr = - "The operation did not complete (X509 lookup)"; + errstr = "The operation did not complete (X509 lookup)"; break; case SSL_ERROR_WANT_CONNECT: p = PY_SSL_ERROR_WANT_CONNECT; @@ -193,15 +192,14 @@ unsigned long e = ERR_get_error(); if (e == 0) { if (ret == 0 || !obj->Socket) { - p = PY_SSL_ERROR_EOF; - errstr = - "EOF occurred in violation of protocol"; + p = PY_SSL_ERROR_EOF; + errstr = "EOF occurred in violation of protocol"; } else if (ret == -1) { - /* underlying BIO reported an I/O error */ - return obj->Socket->errorhandler(); + /* underlying BIO reported an I/O error */ + return obj->Socket->errorhandler(); } else { /* possible? */ - p = PY_SSL_ERROR_SYSCALL; - errstr = "Some I/O error occurred"; + p = PY_SSL_ERROR_SYSCALL; + errstr = "Some I/O error occurred"; } } else { p = PY_SSL_ERROR_SYSCALL; @@ -218,8 +216,7 @@ /* XXX Protected by global interpreter lock */ errstr = ERR_error_string(e, NULL); else { /* possible? */ - errstr = - "A failure in the SSL library occurred"; + errstr = "A failure in the SSL library occurred"; } break; } @@ -316,7 +313,7 @@ if (certreq != PY_SSL_CERT_NONE) { if (cacerts_file == NULL) { errstr = ERRSTR("No root certificates specified for " - "verification of other-side certificates."); + "verification of other-side certificates."); goto fail; } else { PySSL_BEGIN_ALLOW_THREADS @@ -472,15 +469,15 @@ } if (sockstate == SOCKET_HAS_TIMED_OUT) { PyErr_SetString(PySSLErrorObject, - ERRSTR("The handshake operation timed out")); + ERRSTR("The handshake operation timed out")); return NULL; } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) { PyErr_SetString(PySSLErrorObject, - ERRSTR("Underlying socket has been closed.")); + ERRSTR("Underlying socket has been closed.")); return NULL; } else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) { PyErr_SetString(PySSLErrorObject, - ERRSTR("Underlying socket too large for select().")); + ERRSTR("Underlying socket too large for select().")); return NULL; } else if (sockstate == SOCKET_IS_NONBLOCKING) { break; @@ -543,7 +540,7 @@ goto fail; } value_obj = PyUnicode_DecodeUTF8((char *) valuebuf, - buflen, "strict"); + buflen, "strict"); OPENSSL_free(valuebuf); if (value_obj == NULL) { Py_DECREF(name_obj); @@ -1193,11 +1190,9 @@ return NULL; } if (err == SSL_ERROR_WANT_READ) { - sockstate = - check_socket_and_wait_for_timeout(self->Socket, 0); + sockstate = check_socket_and_wait_for_timeout(self->Socket, 0); } else if (err == SSL_ERROR_WANT_WRITE) { - sockstate = - check_socket_and_wait_for_timeout(self->Socket, 1); + sockstate = check_socket_and_wait_for_timeout(self->Socket, 1); } else { sockstate = SOCKET_OPERATION_OK; } @@ -1278,7 +1273,7 @@ return NULL; } else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) { PyErr_SetString(PySSLErrorObject, - "Underlying socket too large for select()."); + "Underlying socket too large for select()."); Py_DECREF(buf); return NULL; } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) { @@ -1287,7 +1282,7 @@ { Py_DECREF(buf); PyErr_SetString(PySSLErrorObject, - "Socket closed without SSL shutdown handshake"); + "Socket closed without SSL shutdown handshake"); return NULL; } else { /* should contain a zero-length string */ @@ -1307,11 +1302,9 @@ return NULL; } if (err == SSL_ERROR_WANT_READ) { - sockstate = - check_socket_and_wait_for_timeout(self->Socket, 0); + sockstate = check_socket_and_wait_for_timeout(self->Socket, 0); } else if (err == SSL_ERROR_WANT_WRITE) { - sockstate = - check_socket_and_wait_for_timeout(self->Socket, 1); + sockstate = check_socket_and_wait_for_timeout(self->Socket, 1); } else if ((err == SSL_ERROR_ZERO_RETURN) && (SSL_get_shutdown(self->ssl) == SSL_RECEIVED_SHUTDOWN)) @@ -1482,7 +1475,7 @@ double entropy; if (!PyArg_ParseTuple(args, "s#d:RAND_add", &buf, &len, &entropy)) - return NULL; + return NULL; RAND_add(buf, len, entropy); Py_INCREF(Py_None); return Py_None; @@ -1513,15 +1506,15 @@ int bytes; if (!PyString_Check(arg)) - return PyErr_Format(PyExc_TypeError, - "RAND_egd() expected string, found %s", - Py_TYPE(arg)->tp_name); + return PyErr_Format(PyExc_TypeError, + "RAND_egd() expected string, found %s", + Py_TYPE(arg)->tp_name); bytes = RAND_egd(PyString_AS_STRING(arg)); if (bytes == -1) { - PyErr_SetString(PySSLErrorObject, - "EGD connection failed or EGD did not return " - "enough data to seed the PRNG"); - return NULL; + PyErr_SetString(PySSLErrorObject, + "EGD connection failed or EGD did not return " + "enough data to seed the PRNG"); + return NULL; } return PyInt_FromLong(bytes); } From python-checkins at python.org Wed May 12 16:08:45 2010 From: python-checkins at python.org (antoine.pitrou) Date: Wed, 12 May 2010 16:08:45 +0200 (CEST) Subject: [Python-checkins] r81118 - in python/branches/release31-maint: Modules/_ssl.c Message-ID: <20100512140845.CB57EE8EB@mail.python.org> Author: antoine.pitrou Date: Wed May 12 16:08:45 2010 New Revision: 81118 Log: Merged revisions 81116 via svnmerge from svn+ssh://pythondev at svn.python.org/python/branches/py3k ................ r81116 | antoine.pitrou | 2010-05-12 16:05:24 +0200 (mer., 12 mai 2010) | 9 lines Merged revisions 81115 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r81115 | antoine.pitrou | 2010-05-12 16:02:34 +0200 (mer., 12 mai 2010) | 3 lines Improve _ssl.c formatting ........ ................ Modified: python/branches/release31-maint/ (props changed) python/branches/release31-maint/Modules/_ssl.c Modified: python/branches/release31-maint/Modules/_ssl.c ============================================================================== --- python/branches/release31-maint/Modules/_ssl.c (original) +++ python/branches/release31-maint/Modules/_ssl.c Wed May 12 16:08:45 2010 @@ -182,8 +182,7 @@ break; case SSL_ERROR_WANT_X509_LOOKUP: p = PY_SSL_ERROR_WANT_X509_LOOKUP; - errstr = - "The operation did not complete (X509 lookup)"; + errstr = "The operation did not complete (X509 lookup)"; break; case SSL_ERROR_WANT_CONNECT: p = PY_SSL_ERROR_WANT_CONNECT; @@ -196,15 +195,14 @@ PySocketSockObject *s = (PySocketSockObject *) PyWeakref_GetObject(obj->Socket); if (ret == 0 || (((PyObject *)s) == Py_None)) { - p = PY_SSL_ERROR_EOF; - errstr = - "EOF occurred in violation of protocol"; + p = PY_SSL_ERROR_EOF; + errstr = "EOF occurred in violation of protocol"; } else if (ret == -1) { - /* underlying BIO reported an I/O error */ - return s->errorhandler(); + /* underlying BIO reported an I/O error */ + return s->errorhandler(); } else { /* possible? */ - p = PY_SSL_ERROR_SYSCALL; - errstr = "Some I/O error occurred"; + p = PY_SSL_ERROR_SYSCALL; + errstr = "Some I/O error occurred"; } } else { p = PY_SSL_ERROR_SYSCALL; @@ -221,8 +219,7 @@ /* XXX Protected by global interpreter lock */ errstr = ERR_error_string(e, NULL); else { /* possible? */ - errstr = - "A failure in the SSL library occurred"; + errstr = "A failure in the SSL library occurred"; } break; } @@ -317,7 +314,7 @@ if (certreq != PY_SSL_CERT_NONE) { if (cacerts_file == NULL) { errstr = ERRSTR("No root certificates specified for " - "verification of other-side certificates."); + "verification of other-side certificates."); goto fail; } else { PySSL_BEGIN_ALLOW_THREADS @@ -480,15 +477,15 @@ } if (sockstate == SOCKET_HAS_TIMED_OUT) { PyErr_SetString(PySSLErrorObject, - ERRSTR("The handshake operation timed out")); + ERRSTR("The handshake operation timed out")); return NULL; } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) { PyErr_SetString(PySSLErrorObject, - ERRSTR("Underlying socket has been closed.")); + ERRSTR("Underlying socket has been closed.")); return NULL; } else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) { PyErr_SetString(PySSLErrorObject, - ERRSTR("Underlying socket too large for select().")); + ERRSTR("Underlying socket too large for select().")); return NULL; } else if (sockstate == SOCKET_IS_NONBLOCKING) { break; @@ -534,7 +531,7 @@ goto fail; } value_obj = PyUnicode_DecodeUTF8((char *) valuebuf, - buflen, "strict"); + buflen, "strict"); OPENSSL_free(valuebuf); if (value_obj == NULL) { Py_DECREF(name_obj); @@ -1208,11 +1205,9 @@ return NULL; } if (err == SSL_ERROR_WANT_READ) { - sockstate = - check_socket_and_wait_for_timeout(sock, 0); + sockstate = check_socket_and_wait_for_timeout(sock, 0); } else if (err == SSL_ERROR_WANT_WRITE) { - sockstate = - check_socket_and_wait_for_timeout(sock, 1); + sockstate = check_socket_and_wait_for_timeout(sock, 1); } else { sockstate = SOCKET_OPERATION_OK; } @@ -1319,7 +1314,7 @@ goto error; } else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) { PyErr_SetString(PySSLErrorObject, - "Underlying socket too large for select()."); + "Underlying socket too large for select()."); goto error; } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) { count = 0; @@ -1335,11 +1330,9 @@ if (PyErr_CheckSignals()) goto error; if (err == SSL_ERROR_WANT_READ) { - sockstate = - check_socket_and_wait_for_timeout(sock, 0); + sockstate = check_socket_and_wait_for_timeout(sock, 0); } else if (err == SSL_ERROR_WANT_WRITE) { - sockstate = - check_socket_and_wait_for_timeout(sock, 1); + sockstate = check_socket_and_wait_for_timeout(sock, 1); } else if ((err == SSL_ERROR_ZERO_RETURN) && (SSL_get_shutdown(self->ssl) == SSL_RECEIVED_SHUTDOWN)) @@ -1532,7 +1525,7 @@ double entropy; if (!PyArg_ParseTuple(args, "s#d:RAND_add", &buf, &len, &entropy)) - return NULL; + return NULL; RAND_add(buf, len, entropy); Py_INCREF(Py_None); return Py_None; @@ -1563,15 +1556,15 @@ int bytes; if (!PyUnicode_Check(arg)) - return PyErr_Format(PyExc_TypeError, - "RAND_egd() expected string, found %s", - Py_TYPE(arg)->tp_name); + return PyErr_Format(PyExc_TypeError, + "RAND_egd() expected string, found %s", + Py_TYPE(arg)->tp_name); bytes = RAND_egd(_PyUnicode_AsString(arg)); if (bytes == -1) { - PyErr_SetString(PySSLErrorObject, - "EGD connection failed or EGD did not return " - "enough data to seed the PRNG"); - return NULL; + PyErr_SetString(PySSLErrorObject, + "EGD connection failed or EGD did not return " + "enough data to seed the PRNG"); + return NULL; } return PyLong_FromLong(bytes); } From python-checkins at python.org Wed May 12 18:51:15 2010 From: python-checkins at python.org (jeffrey.yasskin) Date: Wed, 12 May 2010 18:51:15 +0200 (CEST) Subject: [Python-checkins] r81122 - in python/branches/py3k-jit: Include/code.h JIT JIT/jit_notes.txt Lib/test/support.py Lib/test/test_code.py Lib/test/test_sys.py Objects/codeobject.c Python/ceval.c Message-ID: <20100512165115.9A635EC24@mail.python.org> Author: jeffrey.yasskin Date: Wed May 12 18:51:15 2010 New Revision: 81122 Log: Import the code hotness model to py3k-jit. This will help test the background thread even before we have JITting hooked up. Added: python/branches/py3k-jit/JIT/ python/branches/py3k-jit/JIT/jit_notes.txt Modified: python/branches/py3k-jit/Include/code.h python/branches/py3k-jit/Lib/test/support.py python/branches/py3k-jit/Lib/test/test_code.py python/branches/py3k-jit/Lib/test/test_sys.py python/branches/py3k-jit/Objects/codeobject.c python/branches/py3k-jit/Python/ceval.c Modified: python/branches/py3k-jit/Include/code.h ============================================================================== --- python/branches/py3k-jit/Include/code.h (original) +++ python/branches/py3k-jit/Include/code.h Wed May 12 18:51:15 2010 @@ -28,6 +28,11 @@ Objects/lnotab_notes.txt for details. */ void *co_zombieframe; /* for optimization only (see frameobject.c) */ PyObject *co_weakreflist; /* to support weakrefs to code objects */ +#ifdef WITH_LLVM + /* Measure of how hot this code object is. This will be used to + decide which code objects are worth sending through LLVM. */ + long co_hotness; +#endif /* WITH_LLVM */ } PyCodeObject; /* Masks for co_flags above */ Added: python/branches/py3k-jit/JIT/jit_notes.txt ============================================================================== --- (empty file) +++ python/branches/py3k-jit/JIT/jit_notes.txt Wed May 12 18:51:15 2010 @@ -0,0 +1,43 @@ +How CPython Uses LLVM to JIT +============================ + +This document tries to provide a high-level overview of how LLVM is used inside +Python, including details of all the optimizations implemented for +LLVM-generated Python machine code. This document should be as developer-centric +as possible: it should be able to answer questions like, "how does Python +determine function hotness" and also "where is that implemented?". + +Hotness model: finding critical functions +----------------------------------------- + +TODO: Hotness is currently only measured, not acted on. + +We use an online model to estimate which functions are most critical to an +application's performance. This model is as follows: + +- Each code object has a hotness level (the co_hotness field). + - For each function entry, add 10 to the hotness level. + - For each loop backedge, add 1 to the hotness level. +- If the hotness level exceeds a given threshold (see ceval.c), + compile the code object to machine code via LLVM. This check is done on + function-entry and generator re-entry. + +There several classes of functions we're trying to catch with this model: + +- Straight-line utility functions (lots of invocations, low running time). +- Loop-heavy main functions (few invocations, high running time). +- Long-running generators (few invocations, long lifetime). + +Miscellaneous notes: +- JIT compilation is always disabled during startup by temporarily forcing `-j + never`. This improves startup time by disabling compilation and feedback + collection. + +Previous models: +- Simple call count-based model (10000 calls == hot). This was implemented as + an obviously-deficient baseline to be improved upon. +- Previously, we didn't check code hotness on generator re-entry, which we + changed to catch long-running generators that are called once. + +Relevant Files: +- Python/ceval.c - definition, use of the hotness model. Modified: python/branches/py3k-jit/Lib/test/support.py ============================================================================== --- python/branches/py3k-jit/Lib/test/support.py (original) +++ python/branches/py3k-jit/Lib/test/support.py Wed May 12 18:51:15 2010 @@ -38,7 +38,7 @@ "set_memlimit", "bigmemtest", "bigaddrspacetest", "BasicTestRunner", "run_unittest", "run_doctest", "threading_setup", "threading_cleanup", "reap_children", "cpython_only", "check_impl_detail", "get_attribute", - "swap_item", "swap_attr", + "swap_item", "swap_attr", "WITH_LLVM" ] @@ -1222,3 +1222,8 @@ yield finally: del obj[item] + +# WITH_LLVM is true if Python was compiled with LLVM support. +def foo(): pass +WITH_LLVM = hasattr(foo.__code__, "co_hotness") +del foo Modified: python/branches/py3k-jit/Lib/test/test_code.py ============================================================================== --- python/branches/py3k-jit/Lib/test/test_code.py (original) +++ python/branches/py3k-jit/Lib/test/test_code.py Wed May 12 18:51:15 2010 @@ -124,6 +124,25 @@ print("consts:", tuple(consts(co.co_consts))) +def new_code(function_name, def_string, globals_dict=None): + """Compiles function_name, defined in def_string into a new code object. + + Compiles and runs def_string in a temporary namespace, with the specified + globals dict if any, and returns the function named 'function_name' out of + that namespace. + + This allows us to track things that change in a code object as it's called + repeatedly. Simply defining a local function would re-use the same code + object for each function + + """ + namespace = {} + if globals_dict is None: + globals_dict = {} + exec(def_string, globals_dict, namespace) + return namespace[function_name] + + class CodeTest(unittest.TestCase): def test_newempty(self): @@ -133,6 +152,121 @@ self.assertEquals(co.co_firstlineno, 15) +HOTNESS_CALL = 10 +HOTNESS_ITER = 1 + + at unittest.skipUnless(hasattr(new_code.__code__, "co_hotness"), + "Only applies with LLVM compiled in.") +class HotnessTest(unittest.TestCase): + + def setUp(self): + self.while_loop = new_code("while_loop", """ +def while_loop(x): + while x > 0: + x = x - 1 +""") + + def test_new_code_has_0_hotness(self): + self.assertEquals(self.while_loop.__code__.co_hotness, 0) + + def test_call_adds_10_hotness(self): + self.while_loop(0) + self.assertEquals(self.while_loop.__code__.co_hotness, HOTNESS_CALL) + self.while_loop(0) + self.assertEquals(self.while_loop.__code__.co_hotness, 2 * HOTNESS_CALL) + + list(map(self.while_loop, [0])) # Don't go through fast_function. + self.assertEquals(self.while_loop.__code__.co_hotness, 3 * HOTNESS_CALL) + + kwargs = new_code("kwargs", """ +def kwargs(**kwa): + return kwa +""") + self.assertEquals(kwargs.__code__.co_hotness, 0) + kwargs(a=3, b=4) # Also doesn't go through fast_function. + self.assertEquals(kwargs.__code__.co_hotness, HOTNESS_CALL) + + def test_iteration_adds_1_hotness(self): + self.while_loop(1) + self.assertEquals(self.while_loop.__code__.co_hotness, + HOTNESS_CALL + HOTNESS_ITER) + self.while_loop(36) + self.assertEquals(self.while_loop.__code__.co_hotness, + 2 * HOTNESS_CALL + 37 * HOTNESS_ITER) + + for_loop = new_code("for_loop", """ +def for_loop(): + for x in range(17): + pass +""") + self.assertEquals(for_loop.__code__.co_hotness, 0) + for_loop() + self.assertEquals(for_loop.__code__.co_hotness, + HOTNESS_CALL + 17 * HOTNESS_ITER) + + def test_nested_for_loop_hotness(self): + # Verify our understanding of how the hotness model deals with nested + # for loops. This can be confusing, and we don't want to change it + # accidentally. + foo = new_code("foo", """ +def foo(): + for x in range(50): + for y in range(70): + pass +""") + self.assertEqual(foo.__code__.co_hotness, 0) + foo() + self.assertEqual(foo.__code__.co_hotness, + HOTNESS_CALL + HOTNESS_ITER * 3500 + + HOTNESS_ITER * 50) + + def test_for_loop_jump_threading_hotness(self): + # Regression test: the bytecode peephole optimizer does some limited + # jump threading, which caused problems for one earlier attempt at + # tuning the hotness model. + foo = new_code("foo", """ +def foo(): + for x in range(30): + if x % 2: # Alternate between the two branches + x = 8 # Nonsense +""") + self.assertEqual(foo.__code__.co_hotness, 0) + foo() + + hotness = HOTNESS_CALL + HOTNESS_ITER * 30 + + def test_early_for_loop_exit_hotness(self): + # Make sure we understand how the hotness model counts early exits from + # for loops. + foo = new_code("foo", """ +def foo(): + for x in range(1000): + return True +""") + self.assertEqual(foo.__code__.co_hotness, 0) + foo() + + # Note that we don't count the loop in any way, since we never take + # a loop backedge. + self.assertEqual(foo.__code__.co_hotness, HOTNESS_CALL) + + def test_generator_hotness(self): + foo = new_code("foo", """ +def foo(): + yield 5 + yield 6 +""") + # Generator object created, but not run yet. This counts as the call. + l = foo() + self.assertEqual(foo.__code__.co_hotness, HOTNESS_CALL) + + next(l) # Enter the generator. This is not a call. + self.assertEqual(foo.__code__.co_hotness, HOTNESS_CALL) + next(l) # Neither is this. + self.assertEqual(foo.__code__.co_hotness, HOTNESS_CALL) + + + class CodeWeakRefTest(unittest.TestCase): def test_basic(self): @@ -162,7 +296,7 @@ from test.support import run_doctest, run_unittest from test import test_code run_doctest(test_code, verbose) - run_unittest(CodeTest, CodeWeakRefTest) + run_unittest(CodeTest, HotnessTest, CodeWeakRefTest) if __name__ == "__main__": Modified: python/branches/py3k-jit/Lib/test/test_sys.py ============================================================================== --- python/branches/py3k-jit/Lib/test/test_sys.py (original) +++ python/branches/py3k-jit/Lib/test/test_sys.py Wed May 12 18:51:15 2010 @@ -6,6 +6,7 @@ import textwrap import warnings import operator +from test.support import WITH_LLVM # count the number of test runs, used to create unique # strings to intern in test_intern() @@ -593,7 +594,10 @@ return inner check(get_cell().__closure__[0], size(h + 'P')) # code - check(get_cell().__code__, size(h + '5i8Pi3P')) + if WITH_LLVM: + check(get_cell().__code__, size(h + '5i8Pi3Pl')) + else: + check(get_cell().__code__, size(h + '5i8Pi3P')) # complex check(complex(0,1), size(h + '2d')) # method_descriptor (descriptor object) Modified: python/branches/py3k-jit/Objects/codeobject.c ============================================================================== --- python/branches/py3k-jit/Objects/codeobject.c (original) +++ python/branches/py3k-jit/Objects/codeobject.c Wed May 12 18:51:15 2010 @@ -109,6 +109,9 @@ co->co_lnotab = lnotab; co->co_zombieframe = NULL; co->co_weakreflist = NULL; +#ifdef WITH_LLVM + co->co_hotness = 0; +#endif /* WITH_LLVM */ } return co; } @@ -179,6 +182,9 @@ {"co_name", T_OBJECT, OFF(co_name), READONLY}, {"co_firstlineno", T_INT, OFF(co_firstlineno), READONLY}, {"co_lnotab", T_OBJECT, OFF(co_lnotab), READONLY}, +#ifdef WITH_LLVM + {"co_hotness", T_INT, OFF(co_hotness), READONLY}, +#endif {NULL} /* Sentinel */ }; Modified: python/branches/py3k-jit/Python/ceval.c ============================================================================== --- python/branches/py3k-jit/Python/ceval.c (original) +++ python/branches/py3k-jit/Python/ceval.c Wed May 12 18:51:15 2010 @@ -116,6 +116,11 @@ PyObject *); static PyObject * update_star_args(int, int, PyObject *, PyObject ***); static PyObject * load_args(PyObject ***, int); + +#ifdef WITH_LLVM +static inline void mark_called(PyCodeObject *co); +#endif /* WITH_LLVM */ + #define CALL_FLAG_VAR 1 #define CALL_FLAG_KW 2 @@ -963,6 +968,14 @@ #define JUMPTO(x) (next_instr = first_instr + (x)) #define JUMPBY(x) (next_instr += (x)) +/* Feedback-gathering macros */ +#ifdef WITH_LLVM +#define UPDATE_HOTNESS_JABS() \ + do { if (oparg <= f->f_lasti) ++co->co_hotness; } while (0) +#else +#define UPDATE_HOTNESS_JABS() +#endif /* WITH_LLVM */ + /* OpCode prediction macros Some opcodes tend to come in pairs thus making it possible to predict the second code when the first is run. For example, @@ -2373,6 +2386,7 @@ } if (w == Py_False) { Py_DECREF(w); + UPDATE_HOTNESS_JABS(); JUMPTO(oparg); FAST_DISPATCH(); } @@ -2380,8 +2394,10 @@ Py_DECREF(w); if (err > 0) err = 0; - else if (err == 0) + else if (err == 0) { + UPDATE_HOTNESS_JABS(); JUMPTO(oparg); + } else break; DISPATCH(); @@ -2395,6 +2411,7 @@ } if (w == Py_True) { Py_DECREF(w); + UPDATE_HOTNESS_JABS(); JUMPTO(oparg); FAST_DISPATCH(); } @@ -2402,6 +2419,7 @@ Py_DECREF(w); if (err > 0) { err = 0; + UPDATE_HOTNESS_JABS(); JUMPTO(oparg); } else if (err == 0) @@ -2418,6 +2436,7 @@ FAST_DISPATCH(); } if (w == Py_False) { + UPDATE_HOTNESS_JABS(); JUMPTO(oparg); FAST_DISPATCH(); } @@ -2427,8 +2446,10 @@ Py_DECREF(w); err = 0; } - else if (err == 0) + else if (err == 0) { + UPDATE_HOTNESS_JABS(); JUMPTO(oparg); + } else break; DISPATCH(); @@ -2441,12 +2462,14 @@ FAST_DISPATCH(); } if (w == Py_True) { + UPDATE_HOTNESS_JABS(); JUMPTO(oparg); FAST_DISPATCH(); } err = PyObject_IsTrue(w); if (err > 0) { err = 0; + UPDATE_HOTNESS_JABS(); JUMPTO(oparg); } else if (err == 0) { @@ -2459,6 +2482,7 @@ PREDICTED_WITH_ARG(JUMP_ABSOLUTE); TARGET(JUMP_ABSOLUTE) + UPDATE_HOTNESS_JABS(); JUMPTO(oparg); #if FAST_LOOPS /* Enabling this path speeds-up all while and for-loops by bypassing @@ -2514,6 +2538,9 @@ goto fast_block_end; TARGET(CONTINUE_LOOP) +#ifdef WITH_LLVM + ++co->co_hotness; +#endif retval = PyLong_FromLong(oparg); if (!retval) { x = NULL; @@ -3080,6 +3107,13 @@ if (f == NULL) return NULL; +#ifdef WITH_LLVM + /* This is where a code object is considered "called". Doing it here + * instead of PyEval_EvalFrame() makes support for generators somewhat + * cleaner. */ + mark_called(co); +#endif /* WITH_LLVM */ + fastlocals = f->f_localsplus; freevars = f->f_localsplus + co->co_nlocals; @@ -3793,6 +3827,14 @@ nargs); } +#ifdef WITH_LLVM +static inline void +mark_called(PyCodeObject *co) +{ + co->co_hotness += 10; +} +#endif /* WITH_LLVM */ + #define C_TRACE(x, call) \ if (tstate->use_tracing && tstate->c_profilefunc) { \ if (call_trace(tstate->c_profilefunc, \ @@ -3947,6 +3989,9 @@ f = PyFrame_New(tstate, co, globals, NULL); if (f == NULL) return NULL; +#ifdef WITH_LLVM + mark_called(co); +#endif fastlocals = f->f_localsplus; stack = (*pp_stack) - n; From python-checkins at python.org Wed May 12 20:56:48 2010 From: python-checkins at python.org (andrew.kuchling) Date: Wed, 12 May 2010 20:56:48 +0200 (CEST) Subject: [Python-checkins] r81125 - python/trunk/Doc/library/logging.rst Message-ID: <20100512185648.C544FEE99A@mail.python.org> Author: andrew.kuchling Date: Wed May 12 20:56:48 2010 New Revision: 81125 Log: #8696: add documentation for logging.config.dictConfig (PEP 391) Modified: python/trunk/Doc/library/logging.rst Modified: python/trunk/Doc/library/logging.rst ============================================================================== --- python/trunk/Doc/library/logging.rst (original) +++ python/trunk/Doc/library/logging.rst Wed May 12 20:56:48 2010 @@ -323,24 +323,34 @@ Configuring Logging ^^^^^^^^^^^^^^^^^^^ -Programmers can configure logging either by creating loggers, handlers, and -formatters explicitly in a main module with the configuration methods listed -above (using Python code), or by creating a logging config file. The following -code is an example of configuring a very simple logger, a console handler, and a -simple formatter in a Python module:: +Programmers can configure logging in three ways: + +1. Creating loggers, handlers, and formatters explicitly using Python + code that calls the configuration methods listed above. +2. Creating a logging config file and reading it using the :func:`fileConfig` + function. +3. Creating a dictionary of configuration information and passing it + to the :func:`dictConfig` function. + +The following example configures a very simple logger, a console +handler, and a simple formatter using Python code: import logging # create logger logger = logging.getLogger("simple_example") logger.setLevel(logging.DEBUG) + # create console handler and set level to debug ch = logging.StreamHandler() ch.setLevel(logging.DEBUG) + # create formatter formatter = logging.Formatter("%(asctime)s - %(name)s - %(levelname)s - %(message)s") + # add formatter to ch ch.setFormatter(formatter) + # add ch to logger logger.addHandler(ch) @@ -2620,17 +2630,57 @@ in :mod:`logging` itself) and defining handlers which are declared either in :mod:`logging` or :mod:`logging.handlers`. +.. function:: dictConfig(config) + + Takes the logging configuration from a dictionary. The contents of + this dictionary are described in :ref:`logging-config-dictschema` + below. + + If an error is encountered during configuration, this function will + raise a :exc:`ValueError`, :exc:`TypeError`, :exc:`AttributeError` + or :exc:`ImportError` with a suitably descriptive message. The + following is a (possibly incomplete) list of conditions which will + raise an error: + + * A ``level`` which is not a string or which is a string not + corresponding to an actual logging level. + * A ``propagate`` value which is not a boolean. + * An id which does not have a corresponding destination. + * A non-existent handler id found during an incremental call. + * An invalid logger name. + * Inability to resolve to an internal or external object. + + Parsing is performed by the :class:`DictConfigurator` class, whose + constructor is passed the dictionary used for configuration, and + has a :meth:`configure` method. The :mod:`logging.config` module + has a callable attribute :attr:`dictConfigClass` + which is initially set to :class:`DictConfigurator`. + You can replace the value of :attr:`dictConfigClass` with a + suitable implementation of your own. + + :func:`dictConfig` calls :attr:`dictConfigClass` passing + the specified dictionary, and then calls the :meth:`configure` method on + the returned object to put the configuration into effect:: + + def dictConfig(config): + dictConfigClass(config).configure() + + For example, a subclass of :class:`DictConfigurator` could call + ``DictConfigurator.__init__()`` in its own :meth:`__init__()`, then + set up custom prefixes which would be usable in the subsequent + :meth:`configure` call. :attr:`dictConfigClass` would be bound to + this new subclass, and then :func:`dictConfig` could be called exactly as + in the default, uncustomized state. .. function:: fileConfig(fname[, defaults]) Reads the logging configuration from a :mod:`ConfigParser`\-format file named *fname*. This function can be called several times from an application, - allowing an end user the ability to select from various pre-canned + allowing an end user to select from various pre-canned configurations (if the developer provides a mechanism to present the choices and load the chosen configuration). Defaults to be passed to the ConfigParser can be specified in the *defaults* argument. - .. function:: listen([port]) Starts up a socket server on the specified port, and listens for new @@ -2653,6 +2703,402 @@ :func:`listen`. +.. _logging-config-dictschema: + +Configuration dictionary schema +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +Describing a logging configuration requires listing the various +objects to create and the connections between them; for example, you +may create a handler named "console" and then say that the logger +named "startup" will send its messages to the "console" handler. +These objects aren't limited to those provided by the :mod:`logging` +module because you might write your own formatter or handler class. +The parameters to these classes may also need to include external +objects such as ``sys.stderr``. The syntax for describing these +objects and connections is defined in :ref:`logging-config-dict-connections` +below. + +Dictionary Schema Details +""""""""""""""""""""""""" + +The dictionary passed to :func:`dictConfig` must contain the following +keys: + +* `version` - to be set to an integer value representing the schema + version. The only valid value at present is 1, but having this key + allows the schema to evolve while still preserving backwards + compatibility. + +All other keys are optional, but if present they will be interpreted +as described below. In all cases below where a 'configuring dict' is +mentioned, it will be checked for the special ``'()'`` key to see if a +custom instantiation is required. If so, the mechanism described +above is used to instantiate; otherwise, the context is used to +determine how to instantiate. + +* `formatters` - the corresponding value will be a dict in which each + key is a formatter id and each value is a dict describing how to + configure the corresponding Formatter instance. + + The configuring dict is searched for keys ``format`` and ``datefmt`` + (with defaults of ``None``) and these are used to construct a + :class:`logging.Formatter` instance. + +* `filters` - the corresponding value will be a dict in which each key + is a filter id and each value is a dict describing how to configure + the corresponding Filter instance. + + The configuring dict is searched for the key ``name`` (defaulting to the + empty string) and this is used to construct a :class:`logging.Filter` + instance. + +* `handlers` - the corresponding value will be a dict in which each + key is a handler id and each value is a dict describing how to + configure the corresponding Handler instance. + + The configuring dict is searched for the following keys: + + * ``class`` (mandatory). This is the fully qualified name of the + handler class. + + * ``level`` (optional). The level of the handler. + + * ``formatter`` (optional). The id of the formatter for this + handler. + + * ``filters`` (optional). A list of ids of the filters for this + handler. + + All *other* keys are passed through as keyword arguments to the + handler's constructor. For example, given the snippet:: + + handlers: + console: + class : logging.StreamHandler + formatter: brief + level : INFO + filters: [allow_foo] + stream : ext://sys.stdout + file: + class : logging.handlers.RotatingFileHandler + formatter: precise + filename: logconfig.log + maxBytes: 1024 + backupCount: 3 + + the handler with id ``console`` is instantiated as a + :class:`logging.StreamHandler`, using ``sys.stdout`` as the underlying + stream. The handler with id ``file`` is instantiated as a + :class:`logging.handlers.RotatingFileHandler` with the keyword arguments + ``filename='logconfig.log', maxBytes=1024, backupCount=3``. + +* `loggers` - the corresponding value will be a dict in which each key + is a logger name and each value is a dict describing how to + configure the corresponding Logger instance. + + The configuring dict is searched for the following keys: + + * ``level`` (optional). The level of the logger. + + * ``propagate`` (optional). The propagation setting of the logger. + + * ``filters`` (optional). A list of ids of the filters for this + logger. + + * ``handlers`` (optional). A list of ids of the handlers for this + logger. + + The specified loggers will be configured according to the level, + propagation, filters and handlers specified. + +* `root` - this will be the configuration for the root logger. + Processing of the configuration will be as for any logger, except + that the ``propagate`` setting will not be applicable. + +* `incremental` - whether the configuration is to be interpreted as + incremental to the existing configuration. This value defaults to + ``False``, which means that the specified configuration replaces the + existing configuration with the same semantics as used by the + existing :func:`fileConfig` API. + + If the specified value is ``True``, the configuration is processed + as described in the section on :ref:`logging-config-dict-incremental`. + +* `disable_existing_loggers` - whether any existing loggers are to be + disabled. This setting mirrors the parameter of the same name in + :func:`fileConfig`. If absent, this parameter defaults to ``True``. + This value is ignored if `incremental` is ``True``. + +.. _logging-config-dict-incremental: + +Incremental Configuration +""""""""""""""""""""""""" + +It is difficult to provide complete flexibility for incremental +configuration. For example, because objects such as filters +and formatters are anonymous, once a configuration is set up, it is +not possible to refer to such anonymous objects when augmenting a +configuration. + +Furthermore, there is not a compelling case for arbitrarily altering +the object graph of loggers, handlers, filters, formatters at +run-time, once a configuration is set up; the verbosity of loggers and +handlers can be controlled just by setting levels (and, in the case of +loggers, propagation flags). Changing the object graph arbitrarily in +a safe way is problematic in a multi-threaded environment; while not +impossible, the benefits are not worth the complexity it adds to the +implementation. + +Thus, when the ``incremental`` key of a configuration dict is present +and is ``True``, the system will completely ignore any ``formatters`` and +``filters`` entries, and process only the ``level`` +settings in the ``handlers`` entries, and the ``level`` and +``propagate`` settings in the ``loggers`` and ``root`` entries. + +Using a value in the configuration dict lets configurations to be sent +over the wire as pickled dicts to a socket listener. Thus, the logging +verbosity of a long-running application can be altered over time with +no need to stop and restart the application. + +.. _logging-config-dict-connections: + +Object connections +"""""""""""""""""" + +The schema describes a set of logging objects - loggers, +handlers, formatters, filters - which are connected to each other in +an object graph. Thus, the schema needs to represent connections +between the objects. For example, say that, once configured, a +particular logger has attached to it a particular handler. For the +purposes of this discussion, we can say that the logger represents the +source, and the handler the destination, of a connection between the +two. Of course in the configured objects this is represented by the +logger holding a reference to the handler. In the configuration dict, +this is done by giving each destination object an id which identifies +it unambiguously, and then using the id in the source object's +configuration to indicate that a connection exists between the source +and the destination object with that id. + +So, for example, consider the following YAML snippet:: + + formatters: + brief: + # configuration for formatter with id 'brief' goes here + precise: + # configuration for formatter with id 'precise' goes here + handlers: + h1: #This is an id + # configuration of handler with id 'h1' goes here + formatter: brief + h2: #This is another id + # configuration of handler with id 'h2' goes here + formatter: precise + loggers: + foo.bar.baz: + # other configuration for logger 'foo.bar.baz' + handlers: [h1, h2] + +(Note: YAML used here because it's a little more readable than the +equivalent Python source form for the dictionary.) + +The ids for loggers are the logger names which would be used +programmatically to obtain a reference to those loggers, e.g. +``foo.bar.baz``. The ids for Formatters and Filters can be any string +value (such as ``brief``, ``precise`` above) and they are transient, +in that they are only meaningful for processing the configuration +dictionary and used to determine connections between objects, and are +not persisted anywhere when the configuration call is complete. + +The above snippet indicates that logger named ``foo.bar.baz`` should +have two handlers attached to it, which are described by the handler +ids ``h1`` and ``h2``. The formatter for ``h1`` is that described by id +``brief``, and the formatter for ``h2`` is that described by id +``precise``. + + +.. _logging-config-dict-userdef: + +User-defined objects +"""""""""""""""""""" + +The schema supports user-defined objects for handlers, filters and +formatters. (Loggers do not need to have different types for +different instances, so there is no support in this configuration +schema for user-defined logger classes.) + +Objects to be configured are described by dictionaries +which detail their configuration. In some places, the logging system +will be able to infer from the context how an object is to be +instantiated, but when a user-defined object is to be instantiated, +the system will not know how to do this. In order to provide complete +flexibility for user-defined object instantiation, the user needs +to provide a 'factory' - a callable which is called with a +configuration dictionary and which returns the instantiated object. +This is signalled by an absolute import path to the factory being +made available under the special key ``'()'``. Here's a concrete +example:: + + formatters: + brief: + format: '%(message)s' + default: + format: '%(asctime)s %(levelname)-8s %(name)-15s %(message)s' + datefmt: '%Y-%m-%d %H:%M:%S' + custom: + (): my.package.customFormatterFactory + bar: baz + spam: 99.9 + answer: 42 + +The above YAML snippet defines three formatters. The first, with id +``brief``, is a standard :class:`logging.Formatter` instance with the +specified format string. The second, with id ``default``, has a +longer format and also defines the time format explicitly, and will +result in a :class:`logging.Formatter` initialized with those two format +strings. Shown in Python source form, the ``brief`` and ``default`` +formatters have configuration sub-dictionaries:: + + { + 'format' : '%(message)s' + } + +and:: + + { + 'format' : '%(asctime)s %(levelname)-8s %(name)-15s %(message)s', + 'datefmt' : '%Y-%m-%d %H:%M:%S' + } + +respectively, and as these dictionaries do not contain the special key +``'()'``, the instantiation is inferred from the context: as a result, +standard :class:`logging.Formatter` instances are created. The +configuration sub-dictionary for the third formatter, with id +``custom``, is:: + + { + '()' : 'my.package.customFormatterFactory', + 'bar' : 'baz', + 'spam' : 99.9, + 'answer' : 42 + } + +and this contains the special key ``'()'``, which means that +user-defined instantiation is wanted. In this case, the specified +factory callable will be used. If it is an actual callable it will be +used directly - otherwise, if you specify a string (as in the example) +the actual callable will be located using normal import mechanisms. +The callable will be called with the **remaining** items in the +configuration sub-dictionary as keyword arguments. In the above +example, the formatter with id ``custom`` will be assumed to be +returned by the call:: + + my.package.customFormatterFactory(bar='baz', spam=99.9, answer=42) + +The key ``'()'`` has been used as the special key because it is not a +valid keyword parameter name, and so will not clash with the names of +the keyword arguments used in the call. The ``'()'`` also serves as a +mnemonic that the corresponding value is a callable. + + +.. _logging-config-dict-externalobj: + +Access to external objects +"""""""""""""""""""""""""" + +There are times where a configuration needs to refer to objects +external to the configuration, for example ``sys.stderr``. If the +configuration dict is constructed using Python code, this is +straightforward, but a problem arises when the configuration is +provided via a text file (e.g. JSON, YAML). In a text file, there is +no standard way to distinguish ``sys.stderr`` from the literal string +``'sys.stderr'``. To facilitate this distinction, the configuration +system looks for certain special prefixes in string values and +treat them specially. For example, if the literal string +``'ext://sys.stderr'`` is provided as a value in the configuration, +then the ``ext://`` will be stripped off and the remainder of the +value processed using normal import mechanisms. + +The handling of such prefixes is done in a way analogous to protocol +handling: there is a generic mechanism to look for prefixes which +match the regular expression ``^(?P[a-z]+)://(?P.*)$`` +whereby, if the ``prefix`` is recognised, the ``suffix`` is processed +in a prefix-dependent manner and the result of the processing replaces +the string value. If the prefix is not recognised, then the string +value will be left as-is. + + +.. _logging-config-dict-internalobj: + +Access to internal objects +"""""""""""""""""""""""""" + +As well as external objects, there is sometimes also a need to refer +to objects in the configuration. This will be done implicitly by the +configuration system for things that it knows about. For example, the +string value ``'DEBUG'`` for a ``level`` in a logger or handler will +automatically be converted to the value ``logging.DEBUG``, and the +``handlers``, ``filters`` and ``formatter`` entries will take an +object id and resolve to the appropriate destination object. + +However, a more generic mechanism is needed for user-defined +objects which are not known to the :mod:`logging` module. For +example, consider :class:`logging.handlers.MemoryHandler`, which takes +a ``target`` argument which is another handler to delegate to. Since +the system already knows about this class, then in the configuration, +the given ``target`` just needs to be the object id of the relevant +target handler, and the system will resolve to the handler from the +id. If, however, a user defines a ``my.package.MyHandler`` which has +an ``alternate`` handler, the configuration system would not know that +the ``alternate`` referred to a handler. To cater for this, a generic +resolution system allows the user to specify:: + + handlers: + file: + # configuration of file handler goes here + + custom: + (): my.package.MyHandler + alternate: cfg://handlers.file + +The literal string ``'cfg://handlers.file'`` will be resolved in an +analogous way to strings with the ``ext://`` prefix, but looking +in the configuration itself rather than the import namespace. The +mechanism allows access by dot or by index, in a similar way to +that provided by ``str.format``. Thus, given the following snippet:: + + handlers: + email: + class: logging.handlers.SMTPHandler + mailhost: localhost + fromaddr: my_app at domain.tld + toaddrs: + - support_team at domain.tld + - dev_team at domain.tld + subject: Houston, we have a problem. + +in the configuration, the string ``'cfg://handlers'`` would resolve to +the dict with key ``handlers``, the string ``'cfg://handlers.email`` +would resolve to the dict with key ``email`` in the ``handlers`` dict, +and so on. The string ``'cfg://handlers.email.toaddrs[1]`` would +resolve to ``'dev_team.domain.tld'`` and the string +``'cfg://handlers.email.toaddrs[0]'`` would resolve to the value +``'support_team at domain.tld'``. The ``subject`` value could be accessed +using either ``'cfg://handlers.email.subject'`` or, equivalently, +``'cfg://handlers.email[subject]'``. The latter form only needs to be +used if the key contains spaces or non-alphanumeric characters. If an +index value consists only of decimal digits, access will be attempted +using the corresponding integer value, falling back to the string +value if needed. + +Given a string ``cfg://handlers.myhandler.mykey.123``, this will +resolve to ``config_dict['handlers']['myhandler']['mykey']['123']``. +If the string is specified as ``cfg://handlers.myhandler.mykey[123]``, +the system will attempt to retrieve the value from +``config_dict['handlers']['myhandler']['mykey'][123]``, and fall back +to ``config_dict['handlers']['myhandler']['mykey']['123']`` if that +fails. + .. _logging-config-fileformat: Configuration file format From python-checkins at python.org Wed May 12 21:53:36 2010 From: python-checkins at python.org (mark.dickinson) Date: Wed, 12 May 2010 21:53:36 +0200 (CEST) Subject: [Python-checkins] r81126 - python/trunk/Lib/test/test_math.py Message-ID: <20100512195336.58F50EE9A2@mail.python.org> Author: mark.dickinson Date: Wed May 12 21:53:36 2010 New Revision: 81126 Log: Fix unused variable in test_factorial. Modified: python/trunk/Lib/test/test_math.py Modified: python/trunk/Lib/test/test_math.py ============================================================================== --- python/trunk/Lib/test/test_math.py (original) +++ python/trunk/Lib/test/test_math.py Wed May 12 21:53:36 2010 @@ -375,7 +375,7 @@ return result values = range(10) + [50, 100, 500] random.shuffle(values) - for x in range(10): + for x in values: for cast in (int, long, float): self.assertEqual(math.factorial(cast(x)), fact(x), (x, fact(x), math.factorial(x))) self.assertRaises(ValueError, math.factorial, -1) From python-checkins at python.org Wed May 12 21:54:51 2010 From: python-checkins at python.org (mark.dickinson) Date: Wed, 12 May 2010 21:54:51 +0200 (CEST) Subject: [Python-checkins] r81127 - in python/branches/py3k: Lib/test/test_math.py Message-ID: <20100512195451.90563EE9B4@mail.python.org> Author: mark.dickinson Date: Wed May 12 21:54:51 2010 New Revision: 81127 Log: Merged revisions 81126 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r81126 | mark.dickinson | 2010-05-12 20:53:36 +0100 (Wed, 12 May 2010) | 1 line Fix unused variable in test_factorial. ........ Modified: python/branches/py3k/ (props changed) python/branches/py3k/Lib/test/test_math.py Modified: python/branches/py3k/Lib/test/test_math.py ============================================================================== --- python/branches/py3k/Lib/test/test_math.py (original) +++ python/branches/py3k/Lib/test/test_math.py Wed May 12 21:54:51 2010 @@ -372,7 +372,7 @@ return result values = list(range(10)) + [50, 100, 500] random.shuffle(values) - for x in range(10): + for x in values: for cast in (int, float): self.assertEqual(math.factorial(cast(x)), fact(x), (x, fact(x), math.factorial(x))) self.assertRaises(ValueError, math.factorial, -1) From python-checkins at python.org Wed May 12 21:56:10 2010 From: python-checkins at python.org (mark.dickinson) Date: Wed, 12 May 2010 21:56:10 +0200 (CEST) Subject: [Python-checkins] r81128 - in python/branches/release26-maint: Lib/test/test_math.py Message-ID: <20100512195610.7A4AFEE9B4@mail.python.org> Author: mark.dickinson Date: Wed May 12 21:56:10 2010 New Revision: 81128 Log: Merged revisions 81126 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r81126 | mark.dickinson | 2010-05-12 20:53:36 +0100 (Wed, 12 May 2010) | 1 line Fix unused variable in test_factorial. ........ Modified: python/branches/release26-maint/ (props changed) python/branches/release26-maint/Lib/test/test_math.py Modified: python/branches/release26-maint/Lib/test/test_math.py ============================================================================== --- python/branches/release26-maint/Lib/test/test_math.py (original) +++ python/branches/release26-maint/Lib/test/test_math.py Wed May 12 21:56:10 2010 @@ -292,7 +292,7 @@ return result values = range(10) + [50, 100, 500] random.shuffle(values) - for x in range(10): + for x in values: for cast in (int, long, float): self.assertEqual(math.factorial(cast(x)), fact(x), (x, fact(x), math.factorial(x))) self.assertRaises(ValueError, math.factorial, -1) From python-checkins at python.org Wed May 12 21:57:07 2010 From: python-checkins at python.org (mark.dickinson) Date: Wed, 12 May 2010 21:57:07 +0200 (CEST) Subject: [Python-checkins] r81129 - in python/branches/release31-maint: Lib/test/test_math.py Message-ID: <20100512195707.45750EE9B8@mail.python.org> Author: mark.dickinson Date: Wed May 12 21:57:07 2010 New Revision: 81129 Log: Merged revisions 81127 via svnmerge from svn+ssh://pythondev at svn.python.org/python/branches/py3k ................ r81127 | mark.dickinson | 2010-05-12 20:54:51 +0100 (Wed, 12 May 2010) | 9 lines Merged revisions 81126 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r81126 | mark.dickinson | 2010-05-12 20:53:36 +0100 (Wed, 12 May 2010) | 1 line Fix unused variable in test_factorial. ........ ................ Modified: python/branches/release31-maint/ (props changed) python/branches/release31-maint/Lib/test/test_math.py Modified: python/branches/release31-maint/Lib/test/test_math.py ============================================================================== --- python/branches/release31-maint/Lib/test/test_math.py (original) +++ python/branches/release31-maint/Lib/test/test_math.py Wed May 12 21:57:07 2010 @@ -294,7 +294,7 @@ return result values = list(range(10)) + [50, 100, 500] random.shuffle(values) - for x in range(10): + for x in values: for cast in (int, float): self.assertEqual(math.factorial(cast(x)), fact(x), (x, fact(x), math.factorial(x))) self.assertRaises(ValueError, math.factorial, -1) From ncoghlan at gmail.com Wed May 12 23:15:20 2010 From: ncoghlan at gmail.com (Nick Coghlan) Date: Thu, 13 May 2010 07:15:20 +1000 Subject: [Python-checkins] r81125 - python/trunk/Doc/library/logging.rst In-Reply-To: <20100512185648.C544FEE99A@mail.python.org> References: <20100512185648.C544FEE99A@mail.python.org> Message-ID: <4BEB1A68.9030406@gmail.com> andrew.kuchling wrote: > +All other keys are optional, but if present they will be interpreted > +as described below. In all cases below where a 'configuring dict' is > +mentioned, it will be checked for the special ``'()'`` key to see if a > +custom instantiation is required. If so, the mechanism described > +above is used to instantiate; otherwise, the context is used to > +determine how to instantiate. "described above" should be a cross-reference to the "User-defined objects" section instead. Cheers, Nick. -- Nick Coghlan | ncoghlan at gmail.com | Brisbane, Australia --------------------------------------------------------------- From solipsis at pitrou.net Thu May 13 01:22:41 2010 From: solipsis at pitrou.net (solipsis at pitrou.net) Date: Thu, 13 May 2010 01:22:41 +0200 (CEST) Subject: [Python-checkins] Daily py3k reference leaks (r81127): sum=1 Message-ID: <20100512232241.C73F01770A@ns6635.ovh.net> py3k results for svn r81127 (hg cset dfd7ecc3e929) -------------------------------------------------- test_multiprocessing leaked [0, 1, 0] references, sum=1 Command line was: ['./python', '-m', 'test.regrtest', '-uall', '-R', '3:3:/home/antoine/py3k/refleaks/reflogJdA0zd', '-x'] From python-checkins at python.org Thu May 13 05:25:21 2010 From: python-checkins at python.org (senthil.kumaran) Date: Thu, 13 May 2010 05:25:21 +0200 (CEST) Subject: [Python-checkins] r81130 - in python/trunk/Lib: test/test_urlparse.py urlparse.py Message-ID: <20100513032521.EA129EE98C@mail.python.org> Author: senthil.kumaran Date: Thu May 13 05:25:21 2010 New Revision: 81130 Log: Fix Issue8657 - adding git and git+ssh as know schemes. Modified: python/trunk/Lib/test/test_urlparse.py python/trunk/Lib/urlparse.py Modified: python/trunk/Lib/test/test_urlparse.py ============================================================================== --- python/trunk/Lib/test/test_urlparse.py (original) +++ python/trunk/Lib/test/test_urlparse.py Thu May 13 05:25:21 2010 @@ -103,7 +103,12 @@ ('svn+ssh', 'svn.zope.org', '/repos/main/ZConfig/trunk/', '', '', ''), ('svn+ssh', 'svn.zope.org', '/repos/main/ZConfig/trunk/', - '', '')) + '', '')), + ('git+ssh://git at github.com/user/project.git', + ('git+ssh', 'git at github.com','/user/project.git', + '','',''), + ('git+ssh', 'git at github.com','/user/project.git', + '', '')) ] for url, parsed, split in testcases: self.checkRoundtrips(url, parsed, split) Modified: python/trunk/Lib/urlparse.py ============================================================================== --- python/trunk/Lib/urlparse.py (original) +++ python/trunk/Lib/urlparse.py Thu May 13 05:25:21 2010 @@ -38,7 +38,7 @@ uses_netloc = ['ftp', 'http', 'gopher', 'nntp', 'telnet', 'imap', 'wais', 'file', 'mms', 'https', 'shttp', 'snews', 'prospero', 'rtsp', 'rtspu', 'rsync', '', - 'svn', 'svn+ssh', 'sftp','nfs'] + 'svn', 'svn+ssh', 'sftp','nfs','git', 'git+ssh'] non_hierarchical = ['gopher', 'hdl', 'mailto', 'news', 'telnet', 'wais', 'imap', 'snews', 'sip', 'sips'] uses_params = ['ftp', 'hdl', 'prospero', 'http', 'imap', From python-checkins at python.org Thu May 13 05:32:27 2010 From: python-checkins at python.org (senthil.kumaran) Date: Thu, 13 May 2010 05:32:27 +0200 (CEST) Subject: [Python-checkins] r81131 - in python/branches/release26-maint: Lib/test/test_urlparse.py Lib/urlparse.py Message-ID: <20100513033227.2099CEE9DD@mail.python.org> Author: senthil.kumaran Date: Thu May 13 05:32:26 2010 New Revision: 81131 Log: Merged revisions 81130 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r81130 | senthil.kumaran | 2010-05-13 08:55:21 +0530 (Thu, 13 May 2010) | 3 lines Fix Issue8657 - adding git and git+ssh as know schemes. ........ Modified: python/branches/release26-maint/ (props changed) python/branches/release26-maint/Lib/test/test_urlparse.py python/branches/release26-maint/Lib/urlparse.py Modified: python/branches/release26-maint/Lib/test/test_urlparse.py ============================================================================== --- python/branches/release26-maint/Lib/test/test_urlparse.py (original) +++ python/branches/release26-maint/Lib/test/test_urlparse.py Thu May 13 05:32:26 2010 @@ -100,7 +100,12 @@ ('svn+ssh', 'svn.zope.org', '/repos/main/ZConfig/trunk/', '', '', ''), ('svn+ssh', 'svn.zope.org', '/repos/main/ZConfig/trunk/', - '', '')) + '', '')), + ('git+ssh://git at github.com/user/project.git', + ('git+ssh', 'git at github.com','/user/project.git', + '','',''), + ('git+ssh', 'git at github.com','/user/project.git', + '', '')) ] for url, parsed, split in testcases: self.checkRoundtrips(url, parsed, split) Modified: python/branches/release26-maint/Lib/urlparse.py ============================================================================== --- python/branches/release26-maint/Lib/urlparse.py (original) +++ python/branches/release26-maint/Lib/urlparse.py Thu May 13 05:32:26 2010 @@ -5,21 +5,22 @@ RFC 3986 (STD66): "Uniform Resource Identifiers" by T. Berners-Lee, R. Fielding and L. Masinter, January 2005. -RFC2396: "Uniform Resource Identifiers (URI)": Generic Syntax by T. +RFC 2396: "Uniform Resource Identifiers (URI)": Generic Syntax by T. Berners-Lee, R. Fielding, and L. Masinter, August 1998. -RFC2368: "The mailto URL scheme", by P.Hoffman , L Masinter, J. Zwinski, July 1998. +RFC 2368: "The mailto URL scheme", by P.Hoffman , L Masinter, J. Zwinski, July 1998. RFC 1808: "Relative Uniform Resource Locators", by R. Fielding, UC Irvine, June 1995. -RFC1738: "Uniform Resource Locators (URL)" by T. Berners-Lee, L. Masinter, M. +RFC 1738: "Uniform Resource Locators (URL)" by T. Berners-Lee, L. Masinter, M. McCahill, December 1994 -RFC 3986 is considered the current standard and any changes to urlparse module -should conform to this. urlparse module is not entirely compliant with this. -The defacto scenarios of parsing are considered sometimes and for backward -compatiblity purposes, older RFC uses of parsing are retained. The testcases in +RFC 3986 is considered the current standard and any future changes to +urlparse module should conform with it. The urlparse module is +currently not entirely compliant with this RFC due to defacto +scenarios for parsing, and for backward compatibility purposes, some +parsing quirks from older RFCs are retained. The testcases in test_urlparse.py provides a good indicator of parsing behavior. """ @@ -34,7 +35,7 @@ uses_netloc = ['ftp', 'http', 'gopher', 'nntp', 'telnet', 'imap', 'wais', 'file', 'mms', 'https', 'shttp', 'snews', 'prospero', 'rtsp', 'rtspu', 'rsync', '', - 'svn', 'svn+ssh', 'sftp'] + 'svn', 'svn+ssh', 'sftp','nfs','git', 'git+ssh'] non_hierarchical = ['gopher', 'hdl', 'mailto', 'news', 'telnet', 'wais', 'imap', 'snews', 'sip', 'sips'] uses_params = ['ftp', 'hdl', 'prospero', 'http', 'imap', From python-checkins at python.org Thu May 13 05:37:24 2010 From: python-checkins at python.org (senthil.kumaran) Date: Thu, 13 May 2010 05:37:24 +0200 (CEST) Subject: [Python-checkins] r81132 - in python/branches/py3k: Lib/test/test_urlparse.py Lib/urllib/parse.py Message-ID: <20100513033724.0FDFCEE9E3@mail.python.org> Author: senthil.kumaran Date: Thu May 13 05:37:23 2010 New Revision: 81132 Log: Merged revisions 81130 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r81130 | senthil.kumaran | 2010-05-13 08:55:21 +0530 (Thu, 13 May 2010) | 3 lines Fix Issue8657 - adding git and git+ssh as know schemes. ........ Modified: python/branches/py3k/ (props changed) python/branches/py3k/Lib/test/test_urlparse.py python/branches/py3k/Lib/urllib/parse.py Modified: python/branches/py3k/Lib/test/test_urlparse.py ============================================================================== --- python/branches/py3k/Lib/test/test_urlparse.py (original) +++ python/branches/py3k/Lib/test/test_urlparse.py Thu May 13 05:37:23 2010 @@ -104,7 +104,12 @@ ('svn+ssh', 'svn.zope.org', '/repos/main/ZConfig/trunk/', '', '', ''), ('svn+ssh', 'svn.zope.org', '/repos/main/ZConfig/trunk/', - '', '')) + '', '')), + ('git+ssh://git at github.com/user/project.git', + ('git+ssh', 'git at github.com','/user/project.git', + '','',''), + ('git+ssh', 'git at github.com','/user/project.git', + '', '')) ] for url, parsed, split in testcases: self.checkRoundtrips(url, parsed, split) Modified: python/branches/py3k/Lib/urllib/parse.py ============================================================================== --- python/branches/py3k/Lib/urllib/parse.py (original) +++ python/branches/py3k/Lib/urllib/parse.py Thu May 13 05:37:23 2010 @@ -41,7 +41,7 @@ uses_netloc = ['ftp', 'http', 'gopher', 'nntp', 'telnet', 'imap', 'wais', 'file', 'mms', 'https', 'shttp', 'snews', 'prospero', 'rtsp', 'rtspu', 'rsync', '', - 'svn', 'svn+ssh', 'sftp','nfs'] + 'svn', 'svn+ssh', 'sftp', 'nfs',' git', 'git+ssh'] non_hierarchical = ['gopher', 'hdl', 'mailto', 'news', 'telnet', 'wais', 'imap', 'snews', 'sip', 'sips'] uses_params = ['ftp', 'hdl', 'prospero', 'http', 'imap', From python-checkins at python.org Thu May 13 05:43:13 2010 From: python-checkins at python.org (senthil.kumaran) Date: Thu, 13 May 2010 05:43:13 +0200 (CEST) Subject: [Python-checkins] r81133 - in python/branches/release31-maint: Lib/test/test_urlparse.py Lib/urllib/parse.py Message-ID: <20100513034313.475CDEE9E9@mail.python.org> Author: senthil.kumaran Date: Thu May 13 05:43:13 2010 New Revision: 81133 Log: Merged revisions 81132 via svnmerge from svn+ssh://pythondev at svn.python.org/python/branches/py3k ................ r81132 | senthil.kumaran | 2010-05-13 09:07:23 +0530 (Thu, 13 May 2010) | 9 lines Merged revisions 81130 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r81130 | senthil.kumaran | 2010-05-13 08:55:21 +0530 (Thu, 13 May 2010) | 3 lines Fix Issue8657 - adding git and git+ssh as know schemes. ........ ................ Modified: python/branches/release31-maint/ (props changed) python/branches/release31-maint/Lib/test/test_urlparse.py python/branches/release31-maint/Lib/urllib/parse.py Modified: python/branches/release31-maint/Lib/test/test_urlparse.py ============================================================================== --- python/branches/release31-maint/Lib/test/test_urlparse.py (original) +++ python/branches/release31-maint/Lib/test/test_urlparse.py Thu May 13 05:43:13 2010 @@ -104,7 +104,12 @@ ('svn+ssh', 'svn.zope.org', '/repos/main/ZConfig/trunk/', '', '', ''), ('svn+ssh', 'svn.zope.org', '/repos/main/ZConfig/trunk/', - '', '')) + '', '')), + ('git+ssh://git at github.com/user/project.git', + ('git+ssh', 'git at github.com','/user/project.git', + '','',''), + ('git+ssh', 'git at github.com','/user/project.git', + '', '')) ] for url, parsed, split in testcases: self.checkRoundtrips(url, parsed, split) Modified: python/branches/release31-maint/Lib/urllib/parse.py ============================================================================== --- python/branches/release31-maint/Lib/urllib/parse.py (original) +++ python/branches/release31-maint/Lib/urllib/parse.py Thu May 13 05:43:13 2010 @@ -38,7 +38,7 @@ uses_netloc = ['ftp', 'http', 'gopher', 'nntp', 'telnet', 'imap', 'wais', 'file', 'mms', 'https', 'shttp', 'snews', 'prospero', 'rtsp', 'rtspu', 'rsync', '', - 'svn', 'svn+ssh', 'sftp','nfs'] + 'svn', 'svn+ssh', 'sftp', 'nfs',' git', 'git+ssh'] non_hierarchical = ['gopher', 'hdl', 'mailto', 'news', 'telnet', 'wais', 'imap', 'snews', 'sip', 'sips'] uses_params = ['ftp', 'hdl', 'prospero', 'http', 'imap', From nnorwitz at gmail.com Thu May 13 12:39:41 2010 From: nnorwitz at gmail.com (Neal Norwitz) Date: Thu, 13 May 2010 06:39:41 -0400 Subject: [Python-checkins] Python Regression Test Failures refleak (1) Message-ID: <20100513103941.GA10711@kbk-i386-bb.psfb.org> More important issues: ---------------------- test_bz2 leaked [0, 82, 0] references, sum=82 Less important issues: ---------------------- test_threadsignals leaked [0, 0, -8] references, sum=-8 From python-checkins at python.org Thu May 13 13:52:22 2010 From: python-checkins at python.org (mark.dickinson) Date: Thu, 13 May 2010 13:52:22 +0200 (CEST) Subject: [Python-checkins] r81134 - python/branches/py3k/Python/dtoa.c Message-ID: <20100513115222.C95BBEE991@mail.python.org> Author: mark.dickinson Date: Thu May 13 13:52:22 2010 New Revision: 81134 Log: Remove unnecessary assignments. Modified: python/branches/py3k/Python/dtoa.c Modified: python/branches/py3k/Python/dtoa.c ============================================================================== --- python/branches/py3k/Python/dtoa.c (original) +++ python/branches/py3k/Python/dtoa.c Thu May 13 13:52:22 2010 @@ -1382,7 +1382,6 @@ Bigint *b, *d; int b2, d2, dd, i, nd, nd0, odd, p2, p5; - dd = 0; /* silence compiler warning about possibly unused variable */ nd = bc->nd; nd0 = bc->nd0; p5 = nd + bc->e0; @@ -2362,7 +2361,7 @@ /* set pointers to NULL, to silence gcc compiler warnings and make cleanup easier on error */ - mlo = mhi = b = S = 0; + mlo = mhi = S = 0; s0 = 0; u.d = dd; @@ -2713,8 +2712,6 @@ * and for all and pass them and a shift to quorem, so it * can do shifts and ors to compute the numerator for q. */ - if ((i = ((s5 ? 32 - hi0bits(S->x[S->wds-1]) : 1) + s2) & 0x1f)) - i = 32 - i; #define iInc 28 i = dshift(S, s2); b2 += i; From python-checkins at python.org Thu May 13 18:18:14 2010 From: python-checkins at python.org (victor.stinner) Date: Thu, 13 May 2010 18:18:14 +0200 (CEST) Subject: [Python-checkins] r81135 - python/trunk/Lib/test/test_genericpath.py Message-ID: <20100513161814.F076FEEA2F@mail.python.org> Author: victor.stinner Date: Thu May 13 18:18:14 2010 New Revision: 81135 Log: Issue #8422, test_genericpath: skip the creation of a directory with an invalid UTF name on Mac OS X because the OS deny it (the name have to be a valid UTF8 string). Merge r80163 from py3k branch. Modified: python/trunk/Lib/test/test_genericpath.py Modified: python/trunk/Lib/test/test_genericpath.py ============================================================================== --- python/trunk/Lib/test/test_genericpath.py (original) +++ python/trunk/Lib/test/test_genericpath.py Thu May 13 18:18:14 2010 @@ -6,6 +6,7 @@ from test import test_support import os import genericpath +import sys def safe_rmdir(dirname): @@ -236,6 +237,9 @@ for path in (u'', u'fuu', u'f\xf9\xf9', u'/fuu', u'U:\\'): self.assertIsInstance(abspath(path), unicode) + @unittest.skipIf(sys.platform == 'darwin', + "Mac OS X deny the creation of a directory with an invalid utf8 name") + def test_nonascii_abspath(self): # Test non-ASCII, non-UTF8 bytes in the path. with test_support.temp_cwd('\xe7w\xf0'): self.test_abspath() From python-checkins at python.org Thu May 13 18:20:26 2010 From: python-checkins at python.org (victor.stinner) Date: Thu, 13 May 2010 18:20:26 +0200 (CEST) Subject: [Python-checkins] r81136 - python/branches/py3k Message-ID: <20100513162026.96862EEA2F@mail.python.org> Author: victor.stinner Date: Thu May 13 18:20:26 2010 New Revision: 81136 Log: Blocked revisions 81135 via svnmerge (r81135 is a merge of r80163 from py3k) ........ r81135 | victor.stinner | 2010-05-13 18:18:14 +0200 (jeu., 13 mai 2010) | 6 lines Issue #8422, test_genericpath: skip the creation of a directory with an invalid UTF name on Mac OS X because the OS deny it (the name have to be a valid UTF8 string). Merge r80163 from py3k branch. ........ Modified: python/branches/py3k/ (props changed) From python-checkins at python.org Thu May 13 18:22:15 2010 From: python-checkins at python.org (victor.stinner) Date: Thu, 13 May 2010 18:22:15 +0200 (CEST) Subject: [Python-checkins] r81137 - python/trunk/Lib/test/test_genericpath.py Message-ID: <20100513162215.2FDF7EEA3B@mail.python.org> Author: victor.stinner Date: Thu May 13 18:22:15 2010 New Revision: 81137 Log: Fix verb tense in skip message. Ooops, merge also r80334 (patch by r.david.murray) Modified: python/trunk/Lib/test/test_genericpath.py Modified: python/trunk/Lib/test/test_genericpath.py ============================================================================== --- python/trunk/Lib/test/test_genericpath.py (original) +++ python/trunk/Lib/test/test_genericpath.py Thu May 13 18:22:15 2010 @@ -238,7 +238,7 @@ self.assertIsInstance(abspath(path), unicode) @unittest.skipIf(sys.platform == 'darwin', - "Mac OS X deny the creation of a directory with an invalid utf8 name") + "Mac OS X denies the creation of a directory with an invalid utf8 name") def test_nonascii_abspath(self): # Test non-ASCII, non-UTF8 bytes in the path. with test_support.temp_cwd('\xe7w\xf0'): From python-checkins at python.org Thu May 13 18:23:09 2010 From: python-checkins at python.org (victor.stinner) Date: Thu, 13 May 2010 18:23:09 +0200 (CEST) Subject: [Python-checkins] r81138 - python/branches/py3k Message-ID: <20100513162309.2D673EEA3C@mail.python.org> Author: victor.stinner Date: Thu May 13 18:23:09 2010 New Revision: 81138 Log: Blocked revisions 81137 via svnmerge ........ r81137 | victor.stinner | 2010-05-13 18:22:15 +0200 (jeu., 13 mai 2010) | 4 lines Fix verb tense in skip message. Ooops, merge also r80334 (patch by r.david.murray) ........ Modified: python/branches/py3k/ (props changed) From python-checkins at python.org Thu May 13 18:24:45 2010 From: python-checkins at python.org (victor.stinner) Date: Thu, 13 May 2010 18:24:45 +0200 (CEST) Subject: [Python-checkins] r81139 - python/branches/release26-maint Message-ID: <20100513162445.D503BEE9F1@mail.python.org> Author: victor.stinner Date: Thu May 13 18:24:45 2010 New Revision: 81139 Log: Blocked revisions 81135,81137 via svnmerge ........ r81135 | victor.stinner | 2010-05-13 18:18:14 +0200 (jeu., 13 mai 2010) | 6 lines Issue #8422, test_genericpath: skip the creation of a directory with an invalid UTF name on Mac OS X because the OS deny it (the name have to be a valid UTF8 string). Merge r80163 from py3k branch. ........ r81137 | victor.stinner | 2010-05-13 18:22:15 +0200 (jeu., 13 mai 2010) | 4 lines Fix verb tense in skip message. Ooops, merge also r80334 (patch by r.david.murray) ........ Modified: python/branches/release26-maint/ (props changed) From python-checkins at python.org Thu May 13 19:05:29 2010 From: python-checkins at python.org (florent.xicluna) Date: Thu, 13 May 2010 19:05:29 +0200 (CEST) Subject: [Python-checkins] r81140 - python/trunk/Lib/test/regrtest.py Message-ID: <20100513170529.8F903EEA18@mail.python.org> Author: florent.xicluna Date: Thu May 13 19:05:29 2010 New Revision: 81140 Log: Add sensible information about the OS X platform to diagnose issue #8423: test_pep277 fails on "x86 Tiger" buildbot but not on "PPC Tiger". Modified: python/trunk/Lib/test/regrtest.py Modified: python/trunk/Lib/test/regrtest.py ============================================================================== --- python/trunk/Lib/test/regrtest.py (original) +++ python/trunk/Lib/test/regrtest.py Thu May 13 19:05:29 2010 @@ -426,7 +426,12 @@ # Print basic platform information print "==", platform.python_implementation(), \ " ".join(sys.version.split()) - print "== ", platform.platform(aliased=True) + print "== ", platform.platform(aliased=True), \ + "%s-endian" % sys.byteorder, + if sys.platform == 'darwin': + print platform.mac_ver() + else: + print print "== ", os.getcwd() alltests = findtests(testdir, stdtests, nottests) From python-checkins at python.org Thu May 13 20:16:06 2010 From: python-checkins at python.org (florent.xicluna) Date: Thu, 13 May 2010 20:16:06 +0200 (CEST) Subject: [Python-checkins] r81141 - python/trunk/Lib/test/regrtest.py Message-ID: <20100513181606.38457EE9D7@mail.python.org> Author: florent.xicluna Date: Thu May 13 20:16:06 2010 New Revision: 81141 Log: Revert the additional OS X information (r81140). Keep the endianness information. Modified: python/trunk/Lib/test/regrtest.py Modified: python/trunk/Lib/test/regrtest.py ============================================================================== --- python/trunk/Lib/test/regrtest.py (original) +++ python/trunk/Lib/test/regrtest.py Thu May 13 20:16:06 2010 @@ -427,11 +427,7 @@ print "==", platform.python_implementation(), \ " ".join(sys.version.split()) print "== ", platform.platform(aliased=True), \ - "%s-endian" % sys.byteorder, - if sys.platform == 'darwin': - print platform.mac_ver() - else: - print + "%s-endian" % sys.byteorder print "== ", os.getcwd() alltests = findtests(testdir, stdtests, nottests) From python-checkins at python.org Thu May 13 20:31:05 2010 From: python-checkins at python.org (jeffrey.yasskin) Date: Thu, 13 May 2010 20:31:05 +0200 (CEST) Subject: [Python-checkins] r81142 - in python/branches/py3k: Lib/test/test_capi.py Modules/_testcapimodule.c Python/errors.c Message-ID: <20100513183105.8927CEE9F1@mail.python.org> Author: jeffrey.yasskin Date: Thu May 13 20:31:05 2010 New Revision: 81142 Log: Make PyErr_Occurred return NULL if there is no current thread. Previously it would Py_FatalError, which called PyErr_Occurred, resulting in a semi-infinite recursion. Fixes issue 3605. Modified: python/branches/py3k/Lib/test/test_capi.py python/branches/py3k/Modules/_testcapimodule.c python/branches/py3k/Python/errors.c Modified: python/branches/py3k/Lib/test/test_capi.py ============================================================================== --- python/branches/py3k/Lib/test/test_capi.py (original) +++ python/branches/py3k/Lib/test/test_capi.py Thu May 13 20:31:05 2010 @@ -2,9 +2,10 @@ # these are all functions _testcapi exports whose name begins with 'test_'. from __future__ import with_statement +import random +import subprocess import sys import time -import random import unittest from test import support try: @@ -35,6 +36,19 @@ self.assertEqual(testfunction.attribute, "test") self.assertRaises(AttributeError, setattr, inst.testfunction, "attribute", "test") + def test_no_FatalError_infinite_loop(self): + p = subprocess.Popen([sys.executable, "-c", + 'import _testcapi;' + '_testcapi.crash_no_current_thread()'], + stdout=subprocess.PIPE, + stderr=subprocess.PIPE) + (out, err) = p.communicate() + self.assertEqual(out, b'') + # This used to cause an infinite loop. + self.assertEqual(err, + b'Fatal Python error:' + b' PyThreadState_Get: no current thread\n') + @unittest.skipUnless(threading, 'Threading required for this test.') class TestPendingCalls(unittest.TestCase): Modified: python/branches/py3k/Modules/_testcapimodule.c ============================================================================== --- python/branches/py3k/Modules/_testcapimodule.c (original) +++ python/branches/py3k/Modules/_testcapimodule.c Thu May 13 20:31:05 2010 @@ -2005,6 +2005,17 @@ return PyErr_NewExceptionWithDoc(name, doc, base, dict); } +/* Test that the fatal error from not having a current thread doesn't + cause an infinite loop. Run via Lib/test/test_capi.py */ +static PyObject * +crash_no_current_thread(PyObject *self) +{ + Py_BEGIN_ALLOW_THREADS + PyErr_SetString(PyExc_SystemError, "bork bork bork"); + Py_END_ALLOW_THREADS + return NULL; +} + static PyMethodDef TestMethods[] = { {"raise_exception", raise_exception, METH_VARARGS}, {"raise_memoryerror", (PyCFunction)raise_memoryerror, METH_NOARGS}, @@ -2069,6 +2080,7 @@ {"code_newempty", code_newempty, METH_VARARGS}, {"make_exception_with_doc", (PyCFunction)make_exception_with_doc, METH_VARARGS | METH_KEYWORDS}, + {"crash_no_current_thread", (PyCFunction)crash_no_current_thread, METH_NOARGS}, {NULL, NULL} /* sentinel */ }; Modified: python/branches/py3k/Python/errors.c ============================================================================== --- python/branches/py3k/Python/errors.c (original) +++ python/branches/py3k/Python/errors.c Thu May 13 20:31:05 2010 @@ -130,9 +130,14 @@ PyObject * PyErr_Occurred(void) { - PyThreadState *tstate = PyThreadState_GET(); + /* If there is no thread state, PyThreadState_GET calls + Py_FatalError, which calls PyErr_Occurred. To avoid the + resulting infinite loop, we inline PyThreadState_GET here and + treat no thread as no error. */ + PyThreadState *tstate = + ((PyThreadState*)_Py_atomic_load_relaxed(&_PyThreadState_Current)); - return tstate->curexc_type; + return tstate == NULL ? NULL : tstate->curexc_type; } From python-checkins at python.org Thu May 13 20:36:35 2010 From: python-checkins at python.org (martin.v.loewis) Date: Thu, 13 May 2010 20:36:35 +0200 (CEST) Subject: [Python-checkins] r81143 - tracker/instances/python-dev/lib/openid.py Message-ID: <20100513183635.3941EEE9CB@mail.python.org> Author: martin.v.loewis Date: Thu May 13 20:36:35 2010 New Revision: 81143 Log: Add logging support Modified: tracker/instances/python-dev/lib/openid.py Modified: tracker/instances/python-dev/lib/openid.py ============================================================================== --- tracker/instances/python-dev/lib/openid.py (original) +++ tracker/instances/python-dev/lib/openid.py Thu May 13 20:36:35 2010 @@ -11,7 +11,7 @@ # - direct requests require https # - as a signature algorithm, HMAC-SHA1 is requested -import urlparse, urllib, httplib, BeautifulSoup, time +import urlparse, urllib, httplib, BeautifulSoup, time, os import cStringIO, base64, hmac, sha, datetime, re, binascii, struct import itertools @@ -31,6 +31,8 @@ # Don't use urllib, since it sometimes selects HTTP/1.1 (e.g. in PyPI) # and then fails to parse chunked responses. +logfile = None + def normalize_uri(uri): """Normalize an uri according to OpenID section 7.2. Return a pair type,value, where type can be either 'xri' or 'uri'.""" @@ -536,6 +538,62 @@ # TODO: SREG 1.1 return +if logfile: + reqno = 0 + + def log_line(l): + f = open(logfile, 'a') + f.write(l) + f.close() + if reqno % 1000 == 0: + if os.stat(logfile).st_size > 10**7: + try: + os.unlink(logfile+".1") + except: + pass + os.rename(logfile, logfile+".1") + + def enter(func, params): + global reqno + reqno += 1 + log_line("%d %d %d enter %s %s\n" % (int(time.time()), os.getpid(), reqno, func, params)) + return reqno + + def exit(reqno): + log_line("%d %d %d exit\n" % (int(time.time()), os.getpid(), reqno)) + + orig_normalize_uri = normalize_uri + def normalize_uri(uri): + reqno = enter("normalize_uri", uri) + try: + return orig_normalize_uri(uri) + finally: + exit(reqno) + + orig_discover = discover + def discover(url): + reqno = enter("discover", url) + try: + return orig_discover(url) + finally: + exit(reqno) + + orig_associate = associate + def associate(services, url): + reqno = enter("associate", url) + try: + return orig_associate(services, url) + finally: + exit(reqno) + + orig_request_authentication = request_authentication + def request_authentication(*args, **kw): + reqno = enter("request_authentication", args[1]) + try: + return orig_request_authentication(*args, **kw) + finally: + exit(reqno) + ################ Test Server ################################# From python-checkins at python.org Thu May 13 22:21:46 2010 From: python-checkins at python.org (collin.winter) Date: Thu, 13 May 2010 22:21:46 +0200 (CEST) Subject: [Python-checkins] r81144 - python/branches/py3k-jit/JIT_TODO.txt Message-ID: <20100513202146.78284EEA4A@mail.python.org> Author: collin.winter Date: Thu May 13 22:21:46 2010 New Revision: 81144 Log: Update JIT_TODO.txt Modified: python/branches/py3k-jit/JIT_TODO.txt Modified: python/branches/py3k-jit/JIT_TODO.txt ============================================================================== --- python/branches/py3k-jit/JIT_TODO.txt (original) +++ python/branches/py3k-jit/JIT_TODO.txt Thu May 13 22:21:46 2010 @@ -23,10 +23,6 @@ - r676 - r688 Some of these may need public discussion. -- Add support to configure/Makefile.pre.in for building against installed LLVM. -- Import general-purpose utility code: - - Stats.{h,cc} - - PySmallPtrSet - Adapt JIT compiler to Python 3. - Cure cancer. @@ -46,4 +42,8 @@ - Add C/C++ unittests: - Create a Unittests/ directory. - Import googletest 1.4.0. - - Start writing tests. \ No newline at end of file + - Start writing tests. +- Add support for building against installed LLVM (r81093). +- Import general-purpose utility code (r81093): + - Stats.{h,cc} + - PySmallPtrSet From python-checkins at python.org Thu May 13 23:14:10 2010 From: python-checkins at python.org (benjamin.peterson) Date: Thu, 13 May 2010 23:14:10 +0200 (CEST) Subject: [Python-checkins] r81145 - python/trunk/Doc/c-api/list.rst Message-ID: <20100513211410.402D4EEA20@mail.python.org> Author: benjamin.peterson Date: Thu May 13 23:14:10 2010 New Revision: 81145 Log: rip out mention of types.ListType #8703 Modified: python/trunk/Doc/c-api/list.rst Modified: python/trunk/Doc/c-api/list.rst ============================================================================== --- python/trunk/Doc/c-api/list.rst (original) +++ python/trunk/Doc/c-api/list.rst Thu May 13 23:14:10 2010 @@ -15,11 +15,8 @@ .. cvar:: PyTypeObject PyList_Type - .. index:: single: ListType (in module types) - - This instance of :ctype:`PyTypeObject` represents the Python list type. - This is the same object as ``list`` and ``types.ListType`` in the Python - layer. + This instance of :ctype:`PyTypeObject` represents the Python list type. This + is the same object as ``list`` in the Python layer. .. cfunction:: int PyList_Check(PyObject *p) From python-checkins at python.org Thu May 13 23:16:51 2010 From: python-checkins at python.org (benjamin.peterson) Date: Thu, 13 May 2010 23:16:51 +0200 (CEST) Subject: [Python-checkins] r81146 - in python/branches/py3k: Doc/c-api/list.rst Message-ID: <20100513211651.3CB1BC917@mail.python.org> Author: benjamin.peterson Date: Thu May 13 23:16:51 2010 New Revision: 81146 Log: Merged revisions 81145 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r81145 | benjamin.peterson | 2010-05-13 16:14:10 -0500 (Thu, 13 May 2010) | 1 line rip out mention of types.ListType #8703 ........ Modified: python/branches/py3k/ (props changed) python/branches/py3k/Doc/c-api/list.rst Modified: python/branches/py3k/Doc/c-api/list.rst ============================================================================== --- python/branches/py3k/Doc/c-api/list.rst (original) +++ python/branches/py3k/Doc/c-api/list.rst Thu May 13 23:16:51 2010 @@ -15,11 +15,8 @@ .. cvar:: PyTypeObject PyList_Type - .. index:: single: ListType (in module types) - - This instance of :ctype:`PyTypeObject` represents the Python list type. - This is the same object as ``list`` and ``types.ListType`` in the Python - layer. + This instance of :ctype:`PyTypeObject` represents the Python list type. This + is the same object as ``list`` in the Python layer. .. cfunction:: int PyList_Check(PyObject *p) From python-checkins at python.org Thu May 13 23:16:53 2010 From: python-checkins at python.org (benjamin.peterson) Date: Thu, 13 May 2010 23:16:53 +0200 (CEST) Subject: [Python-checkins] r81147 - in python/branches/release26-maint: Doc/c-api/list.rst Message-ID: <20100513211653.7D1D8C917@mail.python.org> Author: benjamin.peterson Date: Thu May 13 23:16:53 2010 New Revision: 81147 Log: Merged revisions 81145 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r81145 | benjamin.peterson | 2010-05-13 16:14:10 -0500 (Thu, 13 May 2010) | 1 line rip out mention of types.ListType #8703 ........ Modified: python/branches/release26-maint/ (props changed) python/branches/release26-maint/Doc/c-api/list.rst Modified: python/branches/release26-maint/Doc/c-api/list.rst ============================================================================== --- python/branches/release26-maint/Doc/c-api/list.rst (original) +++ python/branches/release26-maint/Doc/c-api/list.rst Thu May 13 23:16:53 2010 @@ -15,11 +15,8 @@ .. cvar:: PyTypeObject PyList_Type - .. index:: single: ListType (in module types) - - This instance of :ctype:`PyTypeObject` represents the Python list type. - This is the same object as ``list`` and ``types.ListType`` in the Python - layer. + This instance of :ctype:`PyTypeObject` represents the Python list type. This + is the same object as ``list`` in the Python layer. .. cfunction:: int PyList_Check(PyObject *p) From python-checkins at python.org Thu May 13 23:29:30 2010 From: python-checkins at python.org (jeffrey.yasskin) Date: Thu, 13 May 2010 23:29:30 +0200 (CEST) Subject: [Python-checkins] r81148 - in python/branches/py3k-jit: Doc/library/http.client.rst Doc/library/xml.dom.rst Lib/test/test_asyncore.py Lib/test/test_capi.py Lib/test/test_math.py Lib/test/test_urlparse.py Lib/test/test_zlib.py Lib/urllib/parse.py Misc/NEWS Modules/_ssl.c Modules/_testcapimodule.c Modules/zlibmodule.c Python/dtoa.c Python/errors.c Message-ID: <20100513212930.B2667EE9DD@mail.python.org> Author: jeffrey.yasskin Date: Thu May 13 23:29:30 2010 New Revision: 81148 Log: Merged revisions 81096,81100,81103,81107,81109,81116,81127,81132,81134,81136,81138,81142 via svnmerge from svn+ssh://pythondev at svn.python.org/python/branches/py3k ................ r81096 | antoine.pitrou | 2010-05-11 16:36:40 -0700 (Tue, 11 May 2010) | 11 lines Merged revisions 81094 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r81094 | antoine.pitrou | 2010-05-12 01:32:31 +0200 (mer., 12 mai 2010) | 6 lines Issue #8672: Add a zlib test ensuring that an incomplete stream can be handled by a decompressor object without errors (it returns incomplete uncompressed data). ........ ................ r81100 | antoine.pitrou | 2010-05-11 16:46:02 -0700 (Tue, 11 May 2010) | 10 lines Merged revisions 81098 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r81098 | antoine.pitrou | 2010-05-12 01:42:28 +0200 (mer., 12 mai 2010) | 5 lines Issue #8681: Make the zlib module's error messages more informative when the zlib itself doesn't give any detailed explanation. ........ ................ r81103 | giampaolo.rodola | 2010-05-11 17:33:15 -0700 (Tue, 11 May 2010) | 9 lines Merged revisions 81102 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r81102 | giampaolo.rodola | 2010-05-12 02:29:27 +0200 (mer, 12 mag 2010) | 1 line Removed the assertion that dispatcher.connected attribute must be False after a single connect() call. Solaris and FreeBSD buildbots failures showed how connect() can succeed even in a single call. All bo failures should definitively be fixed now. ........ ................ r81107 | fred.drake | 2010-05-11 18:36:11 -0700 (Tue, 11 May 2010) | 13 lines Merged revisions 81087,81106 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r81087 | fred.drake | 2010-05-11 14:12:27 -0400 (Tue, 11 May 2010) | 2 lines fix typo ........ r81106 | fred.drake | 2010-05-11 21:22:03 -0400 (Tue, 11 May 2010) | 2 lines fix error introduced in previous commit, and the adjacent additional typo ........ ................ r81109 | fred.drake | 2010-05-11 19:34:50 -0700 (Tue, 11 May 2010) | 11 lines Merged revisions 81108 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r81108 | fred.drake | 2010-05-11 22:24:50 -0400 (Tue, 11 May 2010) | 4 lines - clarify Attr.name comment on the presence of colons in namespace mode - document Attr.value - wrap some long lines ........ ................ r81116 | antoine.pitrou | 2010-05-12 07:05:24 -0700 (Wed, 12 May 2010) | 9 lines Merged revisions 81115 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r81115 | antoine.pitrou | 2010-05-12 16:02:34 +0200 (mer., 12 mai 2010) | 3 lines Improve _ssl.c formatting ........ ................ r81127 | mark.dickinson | 2010-05-12 12:54:51 -0700 (Wed, 12 May 2010) | 9 lines Merged revisions 81126 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r81126 | mark.dickinson | 2010-05-12 20:53:36 +0100 (Wed, 12 May 2010) | 1 line Fix unused variable in test_factorial. ........ ................ r81132 | senthil.kumaran | 2010-05-12 20:37:23 -0700 (Wed, 12 May 2010) | 9 lines Merged revisions 81130 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r81130 | senthil.kumaran | 2010-05-13 08:55:21 +0530 (Thu, 13 May 2010) | 3 lines Fix Issue8657 - adding git and git+ssh as know schemes. ........ ................ r81134 | mark.dickinson | 2010-05-13 04:52:22 -0700 (Thu, 13 May 2010) | 1 line Remove unnecessary assignments. ................ r81136 | victor.stinner | 2010-05-13 09:20:26 -0700 (Thu, 13 May 2010) | 12 lines Blocked revisions 81135 via svnmerge (r81135 is a merge of r80163 from py3k) ........ r81135 | victor.stinner | 2010-05-13 18:18:14 +0200 (jeu., 13 mai 2010) | 6 lines Issue #8422, test_genericpath: skip the creation of a directory with an invalid UTF name on Mac OS X because the OS deny it (the name have to be a valid UTF8 string). Merge r80163 from py3k branch. ........ ................ r81138 | victor.stinner | 2010-05-13 09:23:09 -0700 (Thu, 13 May 2010) | 10 lines Blocked revisions 81137 via svnmerge ........ r81137 | victor.stinner | 2010-05-13 18:22:15 +0200 (jeu., 13 mai 2010) | 4 lines Fix verb tense in skip message. Ooops, merge also r80334 (patch by r.david.murray) ........ ................ r81142 | jeffrey.yasskin | 2010-05-13 11:31:05 -0700 (Thu, 13 May 2010) | 6 lines Make PyErr_Occurred return NULL if there is no current thread. Previously it would Py_FatalError, which called PyErr_Occurred, resulting in a semi-infinite recursion. Fixes issue 3605. ................ Modified: python/branches/py3k-jit/ (props changed) python/branches/py3k-jit/Doc/library/http.client.rst python/branches/py3k-jit/Doc/library/xml.dom.rst python/branches/py3k-jit/Lib/test/test_asyncore.py python/branches/py3k-jit/Lib/test/test_capi.py python/branches/py3k-jit/Lib/test/test_math.py python/branches/py3k-jit/Lib/test/test_urlparse.py python/branches/py3k-jit/Lib/test/test_zlib.py python/branches/py3k-jit/Lib/urllib/parse.py python/branches/py3k-jit/Misc/NEWS python/branches/py3k-jit/Modules/_ssl.c python/branches/py3k-jit/Modules/_testcapimodule.c python/branches/py3k-jit/Modules/zlibmodule.c python/branches/py3k-jit/Python/dtoa.c python/branches/py3k-jit/Python/errors.c Modified: python/branches/py3k-jit/Doc/library/http.client.rst ============================================================================== --- python/branches/py3k-jit/Doc/library/http.client.rst (original) +++ python/branches/py3k-jit/Doc/library/http.client.rst Thu May 13 23:29:30 2010 @@ -521,9 +521,8 @@ >>> data2 = r2.read() >>> conn.close() -Here is an example session that uses ``HEAD`` method. Note that ``HEAD`` method -never returns any data. :: - +Here is an example session that uses the ``HEAD`` method. Note that the +``HEAD`` method never returns any data. :: >>> import http.client >>> conn = http.client.HTTPConnection("www.python.org") Modified: python/branches/py3k-jit/Doc/library/xml.dom.rst ============================================================================== --- python/branches/py3k-jit/Doc/library/xml.dom.rst (original) +++ python/branches/py3k-jit/Doc/library/xml.dom.rst Thu May 13 23:29:30 2010 @@ -693,18 +693,27 @@ .. attribute:: Attr.name - The attribute name. In a namespace-using document it may have colons in it. + The attribute name. + In a namespace-using document it may include a colon. .. attribute:: Attr.localName - The part of the name following the colon if there is one, else the entire name. + The part of the name following the colon if there is one, else the + entire name. This is a read-only attribute. .. attribute:: Attr.prefix - The part of the name preceding the colon if there is one, else the empty string. + The part of the name preceding the colon if there is one, else the + empty string. + + +.. attribute:: Attr.value + + The text value of the attribute. This is a synonym for the + :attr:`nodeValue` attribute. .. _dom-attributelist-objects: Modified: python/branches/py3k-jit/Lib/test/test_asyncore.py ============================================================================== --- python/branches/py3k-jit/Lib/test/test_asyncore.py (original) +++ python/branches/py3k-jit/Lib/test/test_asyncore.py Thu May 13 23:29:30 2010 @@ -619,12 +619,8 @@ # we start disconnected self.assertFalse(server.connected) self.assertTrue(server.accepting) - # XXX - Solaris seems to connect() immediately even without - # starting the poller. This is something which should be - # fixed as handle_connect() gets called immediately even if - # no connection actually took place (see issue #8490). - if not sys.platform.startswith("sunos"): - self.assertFalse(client.connected) + # this can't be taken for granted across all platforms + #self.assertFalse(client.connected) self.assertFalse(client.accepting) # execute some loops so that client connects to server Modified: python/branches/py3k-jit/Lib/test/test_capi.py ============================================================================== --- python/branches/py3k-jit/Lib/test/test_capi.py (original) +++ python/branches/py3k-jit/Lib/test/test_capi.py Thu May 13 23:29:30 2010 @@ -2,9 +2,10 @@ # these are all functions _testcapi exports whose name begins with 'test_'. from __future__ import with_statement +import random +import subprocess import sys import time -import random import unittest from test import support try: @@ -35,6 +36,19 @@ self.assertEqual(testfunction.attribute, "test") self.assertRaises(AttributeError, setattr, inst.testfunction, "attribute", "test") + def test_no_FatalError_infinite_loop(self): + p = subprocess.Popen([sys.executable, "-c", + 'import _testcapi;' + '_testcapi.crash_no_current_thread()'], + stdout=subprocess.PIPE, + stderr=subprocess.PIPE) + (out, err) = p.communicate() + self.assertEqual(out, b'') + # This used to cause an infinite loop. + self.assertEqual(err, + b'Fatal Python error:' + b' PyThreadState_Get: no current thread\n') + @unittest.skipUnless(threading, 'Threading required for this test.') class TestPendingCalls(unittest.TestCase): Modified: python/branches/py3k-jit/Lib/test/test_math.py ============================================================================== --- python/branches/py3k-jit/Lib/test/test_math.py (original) +++ python/branches/py3k-jit/Lib/test/test_math.py Thu May 13 23:29:30 2010 @@ -372,7 +372,7 @@ return result values = list(range(10)) + [50, 100, 500] random.shuffle(values) - for x in range(10): + for x in values: for cast in (int, float): self.assertEqual(math.factorial(cast(x)), fact(x), (x, fact(x), math.factorial(x))) self.assertRaises(ValueError, math.factorial, -1) Modified: python/branches/py3k-jit/Lib/test/test_urlparse.py ============================================================================== --- python/branches/py3k-jit/Lib/test/test_urlparse.py (original) +++ python/branches/py3k-jit/Lib/test/test_urlparse.py Thu May 13 23:29:30 2010 @@ -104,7 +104,12 @@ ('svn+ssh', 'svn.zope.org', '/repos/main/ZConfig/trunk/', '', '', ''), ('svn+ssh', 'svn.zope.org', '/repos/main/ZConfig/trunk/', - '', '')) + '', '')), + ('git+ssh://git at github.com/user/project.git', + ('git+ssh', 'git at github.com','/user/project.git', + '','',''), + ('git+ssh', 'git at github.com','/user/project.git', + '', '')) ] for url, parsed, split in testcases: self.checkRoundtrips(url, parsed, split) Modified: python/branches/py3k-jit/Lib/test/test_zlib.py ============================================================================== --- python/branches/py3k-jit/Lib/test/test_zlib.py (original) +++ python/branches/py3k-jit/Lib/test/test_zlib.py Thu May 13 23:29:30 2010 @@ -140,6 +140,13 @@ for ob in x, bytearray(x): self.assertEqual(zlib.decompress(ob), data) + def test_incomplete_stream(self): + # An useful error message is given + x = zlib.compress(HAMLET_SCENE) + self.assertRaisesRegexp(zlib.error, + "Error -5 while decompressing data: incomplete or truncated stream", + zlib.decompress, x[:-1]) + # Memory use of the following functions takes into account overallocation @precisionbigmemtest(size=_1G + 1024 * 1024, memuse=3) @@ -379,6 +386,19 @@ dco = zlib.decompressobj() self.assertEqual(dco.flush(), b"") # Returns nothing + def test_decompress_incomplete_stream(self): + # This is 'foo', deflated + x = b'x\x9cK\xcb\xcf\x07\x00\x02\x82\x01E' + # For the record + self.assertEqual(zlib.decompress(x), b'foo') + self.assertRaises(zlib.error, zlib.decompress, x[:-5]) + # Omitting the stream end works with decompressor objects + # (see issue #8672). + dco = zlib.decompressobj() + y = dco.decompress(x[:-5]) + y += dco.flush() + self.assertEqual(y, b'foo') + if hasattr(zlib.compressobj(), "copy"): def test_compresscopy(self): # Test copying a compression object Modified: python/branches/py3k-jit/Lib/urllib/parse.py ============================================================================== --- python/branches/py3k-jit/Lib/urllib/parse.py (original) +++ python/branches/py3k-jit/Lib/urllib/parse.py Thu May 13 23:29:30 2010 @@ -41,7 +41,7 @@ uses_netloc = ['ftp', 'http', 'gopher', 'nntp', 'telnet', 'imap', 'wais', 'file', 'mms', 'https', 'shttp', 'snews', 'prospero', 'rtsp', 'rtspu', 'rsync', '', - 'svn', 'svn+ssh', 'sftp','nfs'] + 'svn', 'svn+ssh', 'sftp', 'nfs',' git', 'git+ssh'] non_hierarchical = ['gopher', 'hdl', 'mailto', 'news', 'telnet', 'wais', 'imap', 'snews', 'sip', 'sips'] uses_params = ['ftp', 'hdl', 'prospero', 'http', 'imap', Modified: python/branches/py3k-jit/Misc/NEWS ============================================================================== --- python/branches/py3k-jit/Misc/NEWS (original) +++ python/branches/py3k-jit/Misc/NEWS Thu May 13 23:29:30 2010 @@ -351,6 +351,9 @@ Library ------- +- Issue #8681: Make the zlib module's error messages more informative when + the zlib itself doesn't give any detailed explanation. + - The audioop module now supports sound fragments of length greater than 2**31 bytes on 64-bit machines, and is PY_SSIZE_T_CLEAN. @@ -1276,6 +1279,10 @@ Tests ----- +- Issue #8672: Add a zlib test ensuring that an incomplete stream can be + handled by a decompressor object without errors (it returns incomplete + uncompressed data). + - Issue #8533: regrtest uses backslashreplace error handler for stdout to avoid UnicodeEncodeError (write non-ASCII character to stdout using ASCII encoding) Modified: python/branches/py3k-jit/Modules/_ssl.c ============================================================================== --- python/branches/py3k-jit/Modules/_ssl.c (original) +++ python/branches/py3k-jit/Modules/_ssl.c Thu May 13 23:29:30 2010 @@ -182,8 +182,7 @@ break; case SSL_ERROR_WANT_X509_LOOKUP: p = PY_SSL_ERROR_WANT_X509_LOOKUP; - errstr = - "The operation did not complete (X509 lookup)"; + errstr = "The operation did not complete (X509 lookup)"; break; case SSL_ERROR_WANT_CONNECT: p = PY_SSL_ERROR_WANT_CONNECT; @@ -196,15 +195,14 @@ PySocketSockObject *s = (PySocketSockObject *) PyWeakref_GetObject(obj->Socket); if (ret == 0 || (((PyObject *)s) == Py_None)) { - p = PY_SSL_ERROR_EOF; - errstr = - "EOF occurred in violation of protocol"; + p = PY_SSL_ERROR_EOF; + errstr = "EOF occurred in violation of protocol"; } else if (ret == -1) { - /* underlying BIO reported an I/O error */ - return s->errorhandler(); + /* underlying BIO reported an I/O error */ + return s->errorhandler(); } else { /* possible? */ - p = PY_SSL_ERROR_SYSCALL; - errstr = "Some I/O error occurred"; + p = PY_SSL_ERROR_SYSCALL; + errstr = "Some I/O error occurred"; } } else { p = PY_SSL_ERROR_SYSCALL; @@ -221,8 +219,7 @@ /* XXX Protected by global interpreter lock */ errstr = ERR_error_string(e, NULL); else { /* possible? */ - errstr = - "A failure in the SSL library occurred"; + errstr = "A failure in the SSL library occurred"; } break; } @@ -325,7 +322,7 @@ if (certreq != PY_SSL_CERT_NONE) { if (cacerts_file == NULL) { errstr = ERRSTR("No root certificates specified for " - "verification of other-side certificates."); + "verification of other-side certificates."); goto fail; } else { PySSL_BEGIN_ALLOW_THREADS @@ -490,15 +487,15 @@ } if (sockstate == SOCKET_HAS_TIMED_OUT) { PyErr_SetString(PySSLErrorObject, - ERRSTR("The handshake operation timed out")); + ERRSTR("The handshake operation timed out")); return NULL; } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) { PyErr_SetString(PySSLErrorObject, - ERRSTR("Underlying socket has been closed.")); + ERRSTR("Underlying socket has been closed.")); return NULL; } else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) { PyErr_SetString(PySSLErrorObject, - ERRSTR("Underlying socket too large for select().")); + ERRSTR("Underlying socket too large for select().")); return NULL; } else if (sockstate == SOCKET_IS_NONBLOCKING) { break; @@ -544,7 +541,7 @@ goto fail; } value_obj = PyUnicode_DecodeUTF8((char *) valuebuf, - buflen, "strict"); + buflen, "strict"); OPENSSL_free(valuebuf); if (value_obj == NULL) { Py_DECREF(name_obj); @@ -1217,11 +1214,9 @@ goto error; } if (err == SSL_ERROR_WANT_READ) { - sockstate = - check_socket_and_wait_for_timeout(sock, 0); + sockstate = check_socket_and_wait_for_timeout(sock, 0); } else if (err == SSL_ERROR_WANT_WRITE) { - sockstate = - check_socket_and_wait_for_timeout(sock, 1); + sockstate = check_socket_and_wait_for_timeout(sock, 1); } else { sockstate = SOCKET_OPERATION_OK; } @@ -1334,7 +1329,7 @@ goto error; } else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) { PyErr_SetString(PySSLErrorObject, - "Underlying socket too large for select()."); + "Underlying socket too large for select()."); goto error; } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) { count = 0; @@ -1350,11 +1345,9 @@ if (PyErr_CheckSignals()) goto error; if (err == SSL_ERROR_WANT_READ) { - sockstate = - check_socket_and_wait_for_timeout(sock, 0); + sockstate = check_socket_and_wait_for_timeout(sock, 0); } else if (err == SSL_ERROR_WANT_WRITE) { - sockstate = - check_socket_and_wait_for_timeout(sock, 1); + sockstate = check_socket_and_wait_for_timeout(sock, 1); } else if ((err == SSL_ERROR_ZERO_RETURN) && (SSL_get_shutdown(self->ssl) == SSL_RECEIVED_SHUTDOWN)) @@ -1547,7 +1540,7 @@ double entropy; if (!PyArg_ParseTuple(args, "s#d:RAND_add", &buf, &len, &entropy)) - return NULL; + return NULL; RAND_add(buf, len, entropy); Py_INCREF(Py_None); return Py_None; @@ -1578,15 +1571,15 @@ int bytes; if (!PyUnicode_Check(arg)) - return PyErr_Format(PyExc_TypeError, - "RAND_egd() expected string, found %s", - Py_TYPE(arg)->tp_name); + return PyErr_Format(PyExc_TypeError, + "RAND_egd() expected string, found %s", + Py_TYPE(arg)->tp_name); bytes = RAND_egd(_PyUnicode_AsString(arg)); if (bytes == -1) { - PyErr_SetString(PySSLErrorObject, - "EGD connection failed or EGD did not return " - "enough data to seed the PRNG"); - return NULL; + PyErr_SetString(PySSLErrorObject, + "EGD connection failed or EGD did not return " + "enough data to seed the PRNG"); + return NULL; } return PyLong_FromLong(bytes); } Modified: python/branches/py3k-jit/Modules/_testcapimodule.c ============================================================================== --- python/branches/py3k-jit/Modules/_testcapimodule.c (original) +++ python/branches/py3k-jit/Modules/_testcapimodule.c Thu May 13 23:29:30 2010 @@ -1597,6 +1597,17 @@ return PyErr_NewExceptionWithDoc(name, doc, base, dict); } +/* Test that the fatal error from not having a current thread doesn't + cause an infinite loop. Run via Lib/test/test_capi.py */ +static PyObject * +crash_no_current_thread(PyObject *self) +{ + Py_BEGIN_ALLOW_THREADS + PyErr_SetString(PyExc_SystemError, "bork bork bork"); + Py_END_ALLOW_THREADS + return NULL; +} + static PyMethodDef TestMethods[] = { {"raise_exception", raise_exception, METH_VARARGS}, {"raise_memoryerror", (PyCFunction)raise_memoryerror, METH_NOARGS}, @@ -1650,6 +1661,7 @@ {"code_newempty", code_newempty, METH_VARARGS}, {"make_exception_with_doc", (PyCFunction)make_exception_with_doc, METH_VARARGS | METH_KEYWORDS}, + {"crash_no_current_thread", (PyCFunction)crash_no_current_thread, METH_NOARGS}, {NULL, NULL} /* sentinel */ }; Modified: python/branches/py3k-jit/Modules/zlibmodule.c ============================================================================== --- python/branches/py3k-jit/Modules/zlibmodule.c (original) +++ python/branches/py3k-jit/Modules/zlibmodule.c Thu May 13 23:29:30 2010 @@ -52,10 +52,24 @@ static void zlib_error(z_stream zst, int err, char *msg) { - if (zst.msg == Z_NULL) + const char *zmsg = zst.msg; + if (zmsg == Z_NULL) { + switch (err) { + case Z_BUF_ERROR: + zmsg = "incomplete or truncated stream"; + break; + case Z_STREAM_ERROR: + zmsg = "inconsistent stream state"; + break; + case Z_DATA_ERROR: + zmsg = "invalid input data"; + break; + } + } + if (zmsg == Z_NULL) PyErr_Format(ZlibError, "Error %d %s", err, msg); else - PyErr_Format(ZlibError, "Error %d %s: %.200s", err, msg, zst.msg); + PyErr_Format(ZlibError, "Error %d %s: %.200s", err, msg, zmsg); } PyDoc_STRVAR(compressobj__doc__, @@ -241,8 +255,7 @@ * process the inflate call() due to an error in the data. */ if (zst.avail_out > 0) { - PyErr_Format(ZlibError, "Error %i while decompressing data", - err); + zlib_error(zst, err, "while decompressing data"); inflateEnd(&zst); goto error; } Modified: python/branches/py3k-jit/Python/dtoa.c ============================================================================== --- python/branches/py3k-jit/Python/dtoa.c (original) +++ python/branches/py3k-jit/Python/dtoa.c Thu May 13 23:29:30 2010 @@ -1382,7 +1382,6 @@ Bigint *b, *d; int b2, d2, dd, i, nd, nd0, odd, p2, p5; - dd = 0; /* silence compiler warning about possibly unused variable */ nd = bc->nd; nd0 = bc->nd0; p5 = nd + bc->e0; @@ -2362,7 +2361,7 @@ /* set pointers to NULL, to silence gcc compiler warnings and make cleanup easier on error */ - mlo = mhi = b = S = 0; + mlo = mhi = S = 0; s0 = 0; u.d = dd; @@ -2713,8 +2712,6 @@ * and for all and pass them and a shift to quorem, so it * can do shifts and ors to compute the numerator for q. */ - if ((i = ((s5 ? 32 - hi0bits(S->x[S->wds-1]) : 1) + s2) & 0x1f)) - i = 32 - i; #define iInc 28 i = dshift(S, s2); b2 += i; Modified: python/branches/py3k-jit/Python/errors.c ============================================================================== --- python/branches/py3k-jit/Python/errors.c (original) +++ python/branches/py3k-jit/Python/errors.c Thu May 13 23:29:30 2010 @@ -130,9 +130,14 @@ PyObject * PyErr_Occurred(void) { - PyThreadState *tstate = PyThreadState_GET(); + /* If there is no thread state, PyThreadState_GET calls + Py_FatalError, which calls PyErr_Occurred. To avoid the + resulting infinite loop, we inline PyThreadState_GET here and + treat no thread as no error. */ + PyThreadState *tstate = + ((PyThreadState*)_Py_atomic_load_relaxed(&_PyThreadState_Current)); - return tstate->curexc_type; + return tstate == NULL ? NULL : tstate->curexc_type; } From python-checkins at python.org Thu May 13 23:40:01 2010 From: python-checkins at python.org (florent.xicluna) Date: Thu, 13 May 2010 23:40:01 +0200 (CEST) Subject: [Python-checkins] r81149 - python/trunk/Lib/test/test_pep277.py Message-ID: <20100513214001.6A773F68CE@mail.python.org> Author: florent.xicluna Date: Thu May 13 23:40:01 2010 New Revision: 81149 Log: Better test skipping, with message in the log. Modified: python/trunk/Lib/test/test_pep277.py Modified: python/trunk/Lib/test/test_pep277.py ============================================================================== --- python/trunk/Lib/test/test_pep277.py (original) +++ python/trunk/Lib/test/test_pep277.py Thu May 13 23:40:01 2010 @@ -40,6 +40,18 @@ # NFKC(u'\u2001') == NFKC(u'\u2003') ]) + +# Is it Unicode-friendly? +if not os.path.supports_unicode_filenames: + fsencoding = sys.getfilesystemencoding() or sys.getdefaultencoding() + try: + for name in filenames: + name.encode(fsencoding) + except UnicodeEncodeError: + raise unittest.SkipTest("only NT+ and systems with " + "Unicode-friendly filesystem encoding") + + # Destroy directory dirname and all files under it, to one level. def deltree(dirname): # Don't hide legitimate errors: if one of these suckers exists, it's @@ -63,14 +75,8 @@ files = set() for name in self.files: name = os.path.join(test_support.TESTFN, self.norm(name)) - try: - f = open(name, 'w') - except UnicodeEncodeError: - if not os.path.supports_unicode_filenames: - self.skipTest("only NT+ and systems with Unicode-friendly" - "filesystem encoding") - f.write((name+'\n').encode("utf-8")) - f.close() + with open(name, 'w') as f: + f.write((name+'\n').encode("utf-8")) os.stat(name) files.add(name) self.files = files From python-checkins at python.org Thu May 13 23:41:05 2010 From: python-checkins at python.org (florent.xicluna) Date: Thu, 13 May 2010 23:41:05 +0200 (CEST) Subject: [Python-checkins] r81150 - python/trunk/Lib/test/test_pep277.py Message-ID: <20100513214105.EB9C3EE9B3@mail.python.org> Author: florent.xicluna Date: Thu May 13 23:41:05 2010 New Revision: 81150 Log: Improve test feedback to troubleshoot issue #8423 on OS X. Modified: python/trunk/Lib/test/test_pep277.py Modified: python/trunk/Lib/test/test_pep277.py ============================================================================== --- python/trunk/Lib/test/test_pep277.py (original) +++ python/trunk/Lib/test/test_pep277.py Thu May 13 23:41:05 2010 @@ -130,10 +130,14 @@ if sys.platform == 'darwin': files = set(normalize('NFD', file) for file in files) for name in others: - if sys.platform == 'darwin' and normalize('NFD', name) in files: + if sys.platform == 'darwin': # Mac OS X decomposes Unicode names. See comment above. - os.stat(name) - continue + try: + os.stat(name) + if normalize('NFD', name) in files: + continue + except OSError: + pass self._apply_failure(open, name, IOError) self._apply_failure(os.stat, name, OSError) self._apply_failure(os.chdir, name, OSError) @@ -152,7 +156,16 @@ sf0 = set(normalize('NFD', unicode(f)) for f in self.files) f2 = [normalize('NFD', unicode(f)) for f in f2] sf2 = set(os.path.join(unicode(test_support.TESTFN), f) for f in f2) - self.assertEqual(sf0, sf2) + try: + self.assertEqual(sf0, sf2) + except self.failureException: + if sys.platform != 'darwin': + raise + # XXX Troubleshoot issue #8423 + f2 = os.listdir(unicode(test_support.TESTFN, + sys.getfilesystemencoding())) + sf2 = set(os.path.join(unicode(test_support.TESTFN), f) for f in f2) + self.assertEqual(set(self.files), sf2) self.assertEqual(len(f1), len(f2)) def test_rename(self): From solipsis at pitrou.net Fri May 14 01:24:45 2010 From: solipsis at pitrou.net (solipsis at pitrou.net) Date: Fri, 14 May 2010 01:24:45 +0200 (CEST) Subject: [Python-checkins] Daily py3k reference leaks (r81142): sum=0 Message-ID: <20100513232445.3EE511770A@ns6635.ovh.net> py3k results for svn r81142 (hg cset 158c3faea7a9) -------------------------------------------------- Command line was: ['./python', '-m', 'test.regrtest', '-uall', '-R', '3:3:/home/antoine/py3k/refleaks/reflogMEetnU', '-x'] From python-checkins at python.org Fri May 14 01:46:48 2010 From: python-checkins at python.org (florent.xicluna) Date: Fri, 14 May 2010 01:46:48 +0200 (CEST) Subject: [Python-checkins] r81151 - python/trunk/Lib/test/test_pep277.py Message-ID: <20100513234648.C17E7EEA3F@mail.python.org> Author: florent.xicluna Date: Fri May 14 01:46:48 2010 New Revision: 81151 Log: Revert changeset r81150 which helped diagnose issue #8423 on some OS X buildbot. Modified: python/trunk/Lib/test/test_pep277.py Modified: python/trunk/Lib/test/test_pep277.py ============================================================================== --- python/trunk/Lib/test/test_pep277.py (original) +++ python/trunk/Lib/test/test_pep277.py Fri May 14 01:46:48 2010 @@ -130,14 +130,10 @@ if sys.platform == 'darwin': files = set(normalize('NFD', file) for file in files) for name in others: - if sys.platform == 'darwin': + if sys.platform == 'darwin' and normalize('NFD', name) in files: # Mac OS X decomposes Unicode names. See comment above. - try: - os.stat(name) - if normalize('NFD', name) in files: - continue - except OSError: - pass + os.stat(name) + continue self._apply_failure(open, name, IOError) self._apply_failure(os.stat, name, OSError) self._apply_failure(os.chdir, name, OSError) @@ -156,16 +152,7 @@ sf0 = set(normalize('NFD', unicode(f)) for f in self.files) f2 = [normalize('NFD', unicode(f)) for f in f2] sf2 = set(os.path.join(unicode(test_support.TESTFN), f) for f in f2) - try: - self.assertEqual(sf0, sf2) - except self.failureException: - if sys.platform != 'darwin': - raise - # XXX Troubleshoot issue #8423 - f2 = os.listdir(unicode(test_support.TESTFN, - sys.getfilesystemencoding())) - sf2 = set(os.path.join(unicode(test_support.TESTFN), f) for f in f2) - self.assertEqual(set(self.files), sf2) + self.assertEqual(sf0, sf2) self.assertEqual(len(f1), len(f2)) def test_rename(self): From python-checkins at python.org Fri May 14 01:59:41 2010 From: python-checkins at python.org (brett.cannon) Date: Fri, 14 May 2010 01:59:41 +0200 (CEST) Subject: [Python-checkins] r81152 - in python/trunk: Lib/test/test_site.py Misc/NEWS Message-ID: <20100513235941.70C25EE9B3@mail.python.org> Author: brett.cannon Date: Fri May 14 01:59:41 2010 New Revision: 81152 Log: test_site was failing under darwin for non-framework builds because a test was assuming framework-specific site-packages directories were being used. Modified: python/trunk/Lib/test/test_site.py python/trunk/Misc/NEWS Modified: python/trunk/Lib/test/test_site.py ============================================================================== --- python/trunk/Lib/test/test_site.py (original) +++ python/trunk/Lib/test/test_site.py Fri May 14 01:59:41 2010 @@ -182,7 +182,8 @@ self.assertEquals(dirs[1], wanted) # let's try the specific Apple location - if sys.platform == "darwin": + if (sys.platform == "darwin" and + sysconfig.get_config_var("PYTHONFRAMEWORK")): site.PREFIXES = ['Python.framework'] dirs = site.getsitepackages() self.assertEqual(len(dirs), 4) Modified: python/trunk/Misc/NEWS ============================================================================== --- python/trunk/Misc/NEWS (original) +++ python/trunk/Misc/NEWS Fri May 14 01:59:41 2010 @@ -21,6 +21,14 @@ - Issue #8674: Fixed a number of incorrect or undefined-behaviour-inducing overflow checks in the audioop module. +Tests +----- + +- On darwin, test_site assumed that a framework build was being used, leading + to a failure where four directories were expected for site-packages instead + of two in a non-framework build. + + What's New in Python 2.7 beta 2? ================================ From python-checkins at python.org Fri May 14 02:04:56 2010 From: python-checkins at python.org (brett.cannon) Date: Fri, 14 May 2010 02:04:56 +0200 (CEST) Subject: [Python-checkins] r81153 - in python/branches/py3k: Lib/test/test_site.py Message-ID: <20100514000456.9BEB6EE9B3@mail.python.org> Author: brett.cannon Date: Fri May 14 02:04:56 2010 New Revision: 81153 Log: Merged revisions 81152 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r81152 | brett.cannon | 2010-05-13 16:59:41 -0700 (Thu, 13 May 2010) | 3 lines test_site was failing under darwin for non-framework builds because a test was assuming framework-specific site-packages directories were being used. ........ Modified: python/branches/py3k/ (props changed) python/branches/py3k/Lib/test/test_site.py Modified: python/branches/py3k/Lib/test/test_site.py ============================================================================== --- python/branches/py3k/Lib/test/test_site.py (original) +++ python/branches/py3k/Lib/test/test_site.py Fri May 14 02:04:56 2010 @@ -181,7 +181,8 @@ self.assertEquals(dirs[1], wanted) # let's try the specific Apple location - if sys.platform == "darwin": + if (sys.platform == "darwin" and + sysconfig.get_config_var("PYTHONFRAMEWORK")): site.PREFIXES = ['Python.framework'] dirs = site.getsitepackages() self.assertEqual(len(dirs), 4) From python-checkins at python.org Fri May 14 02:21:48 2010 From: python-checkins at python.org (brett.cannon) Date: Fri, 14 May 2010 02:21:48 +0200 (CEST) Subject: [Python-checkins] r81154 - in python/trunk: Lib/subprocess.py Misc/NEWS Message-ID: <20100514002148.4482CEEA3D@mail.python.org> Author: brett.cannon Date: Fri May 14 02:21:48 2010 New Revision: 81154 Log: subprocess.Popen.__del__ referenced global objects, which is a no-no thanks to interpreter shutdown semantics. Same issue goes for the methods that __del__ called. Now all the methods capture the global objects it needs as default values to private parameters (could have stuck them on the class object itself, but since the objects have nothing directly to do with the class that seemed wrong). There is no test as making one that works is hard. This patch was verified against a consistently failing test in Mercurial's test suite, though, so it has been tested in some regard. Closes issue #5099. Thanks to Mary Stern for the bug report and Gabriel Genellina for writing another patch for the same issue and attempting to write a test. Modified: python/trunk/Lib/subprocess.py python/trunk/Misc/NEWS Modified: python/trunk/Lib/subprocess.py ============================================================================== --- python/trunk/Lib/subprocess.py (original) +++ python/trunk/Lib/subprocess.py Fri May 14 02:21:48 2010 @@ -413,7 +413,6 @@ if mswindows: - from _subprocess import CREATE_NEW_CONSOLE, CREATE_NEW_PROCESS_GROUP import threading import msvcrt import _subprocess @@ -442,6 +441,7 @@ "check_output", "CalledProcessError"] if mswindows: + from _subprocess import CREATE_NEW_CONSOLE, CREATE_NEW_PROCESS_GROUP __all__.extend(["CREATE_NEW_CONSOLE", "CREATE_NEW_PROCESS_GROUP"]) try: MAXFD = os.sysconf("SC_OPEN_MAX") @@ -699,12 +699,12 @@ return data - def __del__(self, sys=sys): + def __del__(self, _maxint=sys.maxint, _active=_active): if not self._child_created: # We didn't get to successfully create a child process. return # In case the child hasn't been waited on, check if it's done. - self._internal_poll(_deadstate=sys.maxint) + self._internal_poll(_deadstate=_maxint) if self.returncode is None and _active is not None: # Child is still running, keep us alive until we can wait on it. _active.append(self) @@ -907,13 +907,20 @@ errwrite.Close() - def _internal_poll(self, _deadstate=None): + def _internal_poll(self, _deadstate=None, + _WaitForSingleObject=WaitForSingleObject, + _WAIT_OBJECT_0=WAIT_OBJECT_0, + _GetExitCodeProcess=GetExitCodeProcess): """Check if child process has terminated. Returns returncode - attribute.""" + attribute. + + This method is called by __del__, so it can only refer to objects + in its local scope. + + """ if self.returncode is None: - if(_subprocess.WaitForSingleObject(self._handle, 0) == - _subprocess.WAIT_OBJECT_0): - self.returncode = _subprocess.GetExitCodeProcess(self._handle) + if _WaitForSingleObject(self._handle, 0) == _WAIT_OBJECT_0: + self.returncode = _GetExitCodeProcess(self._handle) return self.returncode @@ -1194,25 +1201,35 @@ raise child_exception - def _handle_exitstatus(self, sts): - if os.WIFSIGNALED(sts): - self.returncode = -os.WTERMSIG(sts) - elif os.WIFEXITED(sts): - self.returncode = os.WEXITSTATUS(sts) + def _handle_exitstatus(self, sts, _WIFSIGNALED=os.WIFSIGNALED, + _WTERMSIG=os.WTERMSIG, _WIFEXITED=os.WIFEXITED, + _WEXITSTATUS=os.WEXITSTATUS): + # This method is called (indirectly) by __del__, so it cannot + # refer to anything outside of its local scope.""" + if _WIFSIGNALED(sts): + self.returncode = -_WTERMSIG(sts) + elif _WIFEXITED(sts): + self.returncode = _WEXITSTATUS(sts) else: # Should never happen raise RuntimeError("Unknown child exit status!") - def _internal_poll(self, _deadstate=None): + def _internal_poll(self, _deadstate=None, _waitpid=os.waitpid, + _WNOHANG=os.WNOHANG, _os_error=os.error): """Check if child process has terminated. Returns returncode - attribute.""" + attribute. + + This method is called by __del__, so it cannot reference anything + outside of the local scope (nor can any methods it calls). + + """ if self.returncode is None: try: - pid, sts = os.waitpid(self.pid, os.WNOHANG) + pid, sts = _waitpid(self.pid, _WNOHANG) if pid == self.pid: self._handle_exitstatus(sts) - except os.error: + except _os_error: if _deadstate is not None: self.returncode = _deadstate return self.returncode Modified: python/trunk/Misc/NEWS ============================================================================== --- python/trunk/Misc/NEWS (original) +++ python/trunk/Misc/NEWS Fri May 14 02:21:48 2010 @@ -15,6 +15,10 @@ Library ------- +- Issue #5099: subprocess.Popen's __del__ method (and the methods it calls) + referenced global objects, causing errors to pop up during interpreter + shutdown. + Extension Modules ----------------- From python-checkins at python.org Fri May 14 02:33:40 2010 From: python-checkins at python.org (brett.cannon) Date: Fri, 14 May 2010 02:33:40 +0200 (CEST) Subject: [Python-checkins] r81155 - in python/branches/py3k: Lib/subprocess.py Message-ID: <20100514003340.99B6CEE9B9@mail.python.org> Author: brett.cannon Date: Fri May 14 02:33:40 2010 New Revision: 81155 Log: Merged revisions 81154 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r81154 | brett.cannon | 2010-05-13 17:21:48 -0700 (Thu, 13 May 2010) | 15 lines subprocess.Popen.__del__ referenced global objects, which is a no-no thanks to interpreter shutdown semantics. Same issue goes for the methods that __del__ called. Now all the methods capture the global objects it needs as default values to private parameters (could have stuck them on the class object itself, but since the objects have nothing directly to do with the class that seemed wrong). There is no test as making one that works is hard. This patch was verified against a consistently failing test in Mercurial's test suite, though, so it has been tested in some regard. Closes issue #5099. Thanks to Mary Stern for the bug report and Gabriel Genellina for writing another patch for the same issue and attempting to write a test. ........ Modified: python/branches/py3k/ (props changed) python/branches/py3k/Lib/subprocess.py Modified: python/branches/py3k/Lib/subprocess.py ============================================================================== --- python/branches/py3k/Lib/subprocess.py (original) +++ python/branches/py3k/Lib/subprocess.py Fri May 14 02:33:40 2010 @@ -356,7 +356,6 @@ if mswindows: - from _subprocess import CREATE_NEW_CONSOLE, CREATE_NEW_PROCESS_GROUP import threading import msvcrt import _subprocess @@ -394,6 +393,7 @@ "getoutput", "check_output", "CalledProcessError"] if mswindows: + from _subprocess import CREATE_NEW_CONSOLE, CREATE_NEW_PROCESS_GROUP __all__.extend(["CREATE_NEW_CONSOLE", "CREATE_NEW_PROCESS_GROUP"]) try: MAXFD = os.sysconf("SC_OPEN_MAX") @@ -698,12 +698,12 @@ return data.decode(encoding) - def __del__(self, sys=sys): + def __del__(self, _maxsize=sys.maxsize, _active=_active): if not self._child_created: # We didn't get to successfully create a child process. return # In case the child hasn't been waited on, check if it's done. - self._internal_poll(_deadstate=sys.maxsize) + self._internal_poll(_deadstate=_maxsize) if self.returncode is None and _active is not None: # Child is still running, keep us alive until we can wait on it. _active.append(self) @@ -907,13 +907,20 @@ errwrite.Close() - def _internal_poll(self, _deadstate=None): + def _internal_poll(self, _deadstate=None, + _WaitForSingleObject=WaitForSingleObject, + _WAIT_OBJECT_0=WAIT_OBJECT_0, + _GetExitCodeProcess=GetExitCodeProcess): """Check if child process has terminated. Returns returncode - attribute.""" + attribute. + + This method is called by __del__, so it can only refer to objects + in its local scope. + + """ if self.returncode is None: - if(_subprocess.WaitForSingleObject(self._handle, 0) == - _subprocess.WAIT_OBJECT_0): - self.returncode = _subprocess.GetExitCodeProcess(self._handle) + if _WaitForSingleObject(self._handle, 0) == _WAIT_OBJECT_0: + self.returncode = _GetExitCodeProcess(self._handle) return self.returncode @@ -1252,25 +1259,35 @@ raise child_exception_type(err_msg) - def _handle_exitstatus(self, sts): - if os.WIFSIGNALED(sts): - self.returncode = -os.WTERMSIG(sts) - elif os.WIFEXITED(sts): - self.returncode = os.WEXITSTATUS(sts) + def _handle_exitstatus(self, sts, _WIFSIGNALED=os.WIFSIGNALED, + _WTERMSIG=os.WTERMSIG, _WIFEXITED=os.WIFEXITED, + _WEXITSTATUS=os.WEXITSTATUS): + # This method is called (indirectly) by __del__, so it cannot + # refer to anything outside of its local scope.""" + if _WIFSIGNALED(sts): + self.returncode = -_WTERMSIG(sts) + elif _WIFEXITED(sts): + self.returncode = _WEXITSTATUS(sts) else: # Should never happen raise RuntimeError("Unknown child exit status!") - def _internal_poll(self, _deadstate=None): + def _internal_poll(self, _deadstate=None, _waitpid=os.waitpid, + _WNOHANG=os.WNOHANG, _os_error=os.error): """Check if child process has terminated. Returns returncode - attribute.""" + attribute. + + This method is called by __del__, so it cannot reference anything + outside of the local scope (nor can any methods it calls). + + """ if self.returncode is None: try: - pid, sts = os.waitpid(self.pid, os.WNOHANG) + pid, sts = _waitpid(self.pid, _WNOHANG) if pid == self.pid: self._handle_exitstatus(sts) - except os.error: + except _os_error: if _deadstate is not None: self.returncode = _deadstate return self.returncode From python-checkins at python.org Fri May 14 02:59:09 2010 From: python-checkins at python.org (victor.stinner) Date: Fri, 14 May 2010 02:59:09 +0200 (CEST) Subject: [Python-checkins] r81156 - python/branches/py3k/Python/pythonrun.c Message-ID: <20100514005909.B68AAEE992@mail.python.org> Author: victor.stinner Date: Fri May 14 02:59:09 2010 New Revision: 81156 Log: Issue #4653: fix typo in flush_std_files() Don't call sys.stderr.flush() if sys has no stderr attribute or if sys.stderr==None. Modified: python/branches/py3k/Python/pythonrun.c Modified: python/branches/py3k/Python/pythonrun.c ============================================================================== --- python/branches/py3k/Python/pythonrun.c (original) +++ python/branches/py3k/Python/pythonrun.c Fri May 14 02:59:09 2010 @@ -334,7 +334,7 @@ Py_DECREF(tmp); } - if (ferr != NULL || ferr != Py_None) { + if (ferr != NULL && ferr != Py_None) { tmp = PyObject_CallMethod(ferr, "flush", ""); if (tmp == NULL) PyErr_Clear(); From python-checkins at python.org Fri May 14 03:03:14 2010 From: python-checkins at python.org (victor.stinner) Date: Fri, 14 May 2010 03:03:14 +0200 (CEST) Subject: [Python-checkins] r81157 - in python/branches/release31-maint: Python/pythonrun.c Message-ID: <20100514010314.EED0CC917@mail.python.org> Author: victor.stinner Date: Fri May 14 03:03:14 2010 New Revision: 81157 Log: Merged revisions 81156 via svnmerge from svn+ssh://pythondev at svn.python.org/python/branches/py3k ........ r81156 | victor.stinner | 2010-05-14 02:59:09 +0200 (ven., 14 mai 2010) | 5 lines Issue #4653: fix typo in flush_std_files() Don't call sys.stderr.flush() if sys has no stderr attribute or if sys.stderr==None. ........ Modified: python/branches/release31-maint/ (props changed) python/branches/release31-maint/Python/pythonrun.c Modified: python/branches/release31-maint/Python/pythonrun.c ============================================================================== --- python/branches/release31-maint/Python/pythonrun.c (original) +++ python/branches/release31-maint/Python/pythonrun.c Fri May 14 03:03:14 2010 @@ -334,7 +334,7 @@ Py_DECREF(tmp); } - if (ferr != NULL || ferr != Py_None) { + if (ferr != NULL && ferr != Py_None) { tmp = PyObject_CallMethod(ferr, "flush", ""); if (tmp == NULL) PyErr_Clear(); From python-checkins at python.org Fri May 14 03:26:08 2010 From: python-checkins at python.org (brett.cannon) Date: Fri, 14 May 2010 03:26:08 +0200 (CEST) Subject: [Python-checkins] r81158 - in python/branches/release26-maint: Lib/subprocess.py Misc/NEWS Message-ID: <20100514012608.7B46FEE992@mail.python.org> Author: brett.cannon Date: Fri May 14 03:26:08 2010 New Revision: 81158 Log: Merged revisions 81154 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r81154 | brett.cannon | 2010-05-13 17:21:48 -0700 (Thu, 13 May 2010) | 15 lines subprocess.Popen.__del__ referenced global objects, which is a no-no thanks to interpreter shutdown semantics. Same issue goes for the methods that __del__ called. Now all the methods capture the global objects it needs as default values to private parameters (could have stuck them on the class object itself, but since the objects have nothing directly to do with the class that seemed wrong). There is no test as making one that works is hard. This patch was verified against a consistently failing test in Mercurial's test suite, though, so it has been tested in some regard. Closes issue #5099. Thanks to Mary Stern for the bug report and Gabriel Genellina for writing another patch for the same issue and attempting to write a test. ........ Modified: python/branches/release26-maint/ (props changed) python/branches/release26-maint/Lib/subprocess.py python/branches/release26-maint/Misc/NEWS Modified: python/branches/release26-maint/Lib/subprocess.py ============================================================================== --- python/branches/release26-maint/Lib/subprocess.py (original) +++ python/branches/release26-maint/Lib/subprocess.py Fri May 14 03:26:08 2010 @@ -650,12 +650,12 @@ return data - def __del__(self, sys=sys): + def __del__(self, _maxint=sys.maxint, _active=_active): if not self._child_created: # We didn't get to successfully create a child process. return # In case the child hasn't been waited on, check if it's done. - self._internal_poll(_deadstate=sys.maxint) + self._internal_poll(_deadstate=_maxint) if self.returncode is None and _active is not None: # Child is still running, keep us alive until we can wait on it. _active.append(self) @@ -858,13 +858,20 @@ errwrite.Close() - def _internal_poll(self, _deadstate=None): + def _internal_poll(self, _deadstate=None, + _WaitForSingleObject=WaitForSingleObject, + _WAIT_OBJECT_0=WAIT_OBJECT_0, + _GetExitCodeProcess=GetExitCodeProcess): """Check if child process has terminated. Returns returncode - attribute.""" + attribute. + + This method is called by __del__, so it can only refer to objects + in its local scope. + + """ if self.returncode is None: - if(_subprocess.WaitForSingleObject(self._handle, 0) == - _subprocess.WAIT_OBJECT_0): - self.returncode = _subprocess.GetExitCodeProcess(self._handle) + if _WaitForSingleObject(self._handle, 0) == _WAIT_OBJECT_0: + self.returncode = _GetExitCodeProcess(self._handle) return self.returncode @@ -1132,25 +1139,35 @@ raise child_exception - def _handle_exitstatus(self, sts): - if os.WIFSIGNALED(sts): - self.returncode = -os.WTERMSIG(sts) - elif os.WIFEXITED(sts): - self.returncode = os.WEXITSTATUS(sts) + def _handle_exitstatus(self, sts, _WIFSIGNALED=os.WIFSIGNALED, + _WTERMSIG=os.WTERMSIG, _WIFEXITED=os.WIFEXITED, + _WEXITSTATUS=os.WEXITSTATUS): + # This method is called (indirectly) by __del__, so it cannot + # refer to anything outside of its local scope.""" + if _WIFSIGNALED(sts): + self.returncode = -_WTERMSIG(sts) + elif _WIFEXITED(sts): + self.returncode = _WEXITSTATUS(sts) else: # Should never happen raise RuntimeError("Unknown child exit status!") - def _internal_poll(self, _deadstate=None): + def _internal_poll(self, _deadstate=None, _waitpid=os.waitpid, + _WNOHANG=os.WNOHANG, _os_error=os.error): """Check if child process has terminated. Returns returncode - attribute.""" + attribute. + + This method is called by __del__, so it cannot reference anything + outside of the local scope (nor can any methods it calls). + + """ if self.returncode is None: try: - pid, sts = os.waitpid(self.pid, os.WNOHANG) + pid, sts = _waitpid(self.pid, _WNOHANG) if pid == self.pid: self._handle_exitstatus(sts) - except os.error: + except _os_error: if _deadstate is not None: self.returncode = _deadstate return self.returncode Modified: python/branches/release26-maint/Misc/NEWS ============================================================================== --- python/branches/release26-maint/Misc/NEWS (original) +++ python/branches/release26-maint/Misc/NEWS Fri May 14 03:26:08 2010 @@ -39,6 +39,9 @@ Library ------- +- Issue #5099: subprocess.Popen.__del__ no longer references global objects, + leading to issues during interpreter shutdown. + - Issue #8681: Make the zlib module's error messages more informative when the zlib itself doesn't give any detailed explanation. From python-checkins at python.org Fri May 14 03:28:56 2010 From: python-checkins at python.org (brett.cannon) Date: Fri, 14 May 2010 03:28:56 +0200 (CEST) Subject: [Python-checkins] r81159 - in python/branches/release31-maint: Lib/subprocess.py Misc/NEWS Message-ID: <20100514012856.73CD2EE992@mail.python.org> Author: brett.cannon Date: Fri May 14 03:28:56 2010 New Revision: 81159 Log: Backport r81155. Modified: python/branches/release31-maint/Lib/subprocess.py python/branches/release31-maint/Misc/NEWS Modified: python/branches/release31-maint/Lib/subprocess.py ============================================================================== --- python/branches/release31-maint/Lib/subprocess.py (original) +++ python/branches/release31-maint/Lib/subprocess.py Fri May 14 03:28:56 2010 @@ -675,12 +675,12 @@ return data.decode(encoding) - def __del__(self, sys=sys): + def __del__(self, _maxsize=sys.maxsize, _active=_active): if not self._child_created: # We didn't get to successfully create a child process. return # In case the child hasn't been waited on, check if it's done. - self._internal_poll(_deadstate=sys.maxsize) + self._internal_poll(_deadstate=_maxsize) if self.returncode is None and _active is not None: # Child is still running, keep us alive until we can wait on it. _active.append(self) @@ -883,13 +883,20 @@ errwrite.Close() - def _internal_poll(self, _deadstate=None): + def _internal_poll(self, _deadstate=None, + _WaitForSingleObject=WaitForSingleObject, + _WAIT_OBJECT_0=WAIT_OBJECT_0, + _GetExitCodeProcess=GetExitCodeProcess): """Check if child process has terminated. Returns returncode - attribute.""" + attribute. + + This method is called by __del__, so it can only refer to objects + in its local scope. + + """ if self.returncode is None: - if(_subprocess.WaitForSingleObject(self._handle, 0) == - _subprocess.WAIT_OBJECT_0): - self.returncode = _subprocess.GetExitCodeProcess(self._handle) + if _WaitForSingleObject(self._handle, 0) == _WAIT_OBJECT_0: + self.returncode = _GetExitCodeProcess(self._handle) return self.returncode @@ -1150,25 +1157,35 @@ raise child_exception - def _handle_exitstatus(self, sts): - if os.WIFSIGNALED(sts): - self.returncode = -os.WTERMSIG(sts) - elif os.WIFEXITED(sts): - self.returncode = os.WEXITSTATUS(sts) + def _handle_exitstatus(self, sts, _WIFSIGNALED=os.WIFSIGNALED, + _WTERMSIG=os.WTERMSIG, _WIFEXITED=os.WIFEXITED, + _WEXITSTATUS=os.WEXITSTATUS): + # This method is called (indirectly) by __del__, so it cannot + # refer to anything outside of its local scope.""" + if _WIFSIGNALED(sts): + self.returncode = -_WTERMSIG(sts) + elif _WIFEXITED(sts): + self.returncode = _WEXITSTATUS(sts) else: # Should never happen raise RuntimeError("Unknown child exit status!") - def _internal_poll(self, _deadstate=None): + def _internal_poll(self, _deadstate=None, _waitpid=os.waitpid, + _WNOHANG=os.WNOHANG, _os_error=os.error): """Check if child process has terminated. Returns returncode - attribute.""" + attribute. + + This method is called by __del__, so it cannot reference anything + outside of the local scope (nor can any methods it calls). + + """ if self.returncode is None: try: - pid, sts = os.waitpid(self.pid, os.WNOHANG) + pid, sts = _waitpid(self.pid, _WNOHANG) if pid == self.pid: self._handle_exitstatus(sts) - except os.error: + except _os_error: if _deadstate is not None: self.returncode = _deadstate return self.returncode Modified: python/branches/release31-maint/Misc/NEWS ============================================================================== --- python/branches/release31-maint/Misc/NEWS (original) +++ python/branches/release31-maint/Misc/NEWS Fri May 14 03:28:56 2010 @@ -40,6 +40,9 @@ Library ------- +- Issue #5099: subprocess.Popen.__del__ no longer references global objects + to prevent issues during interpreter shutdown. + - Issue #8681: Make the zlib module's error messages more informative when the zlib itself doesn't give any detailed explanation. From python-checkins at python.org Fri May 14 03:33:36 2010 From: python-checkins at python.org (benjamin.peterson) Date: Fri, 14 May 2010 03:33:36 +0200 (CEST) Subject: [Python-checkins] r81160 - in python/branches/release31-maint: Doc/c-api/list.rst Message-ID: <20100514013336.8DB12EEA56@mail.python.org> Author: benjamin.peterson Date: Fri May 14 03:33:36 2010 New Revision: 81160 Log: Merged revisions 81146 via svnmerge from svn+ssh://pythondev at svn.python.org/python/branches/py3k ................ r81146 | benjamin.peterson | 2010-05-13 16:16:51 -0500 (Thu, 13 May 2010) | 9 lines Merged revisions 81145 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r81145 | benjamin.peterson | 2010-05-13 16:14:10 -0500 (Thu, 13 May 2010) | 1 line rip out mention of types.ListType #8703 ........ ................ Modified: python/branches/release31-maint/ (props changed) python/branches/release31-maint/Doc/c-api/list.rst Modified: python/branches/release31-maint/Doc/c-api/list.rst ============================================================================== --- python/branches/release31-maint/Doc/c-api/list.rst (original) +++ python/branches/release31-maint/Doc/c-api/list.rst Fri May 14 03:33:36 2010 @@ -15,11 +15,8 @@ .. cvar:: PyTypeObject PyList_Type - .. index:: single: ListType (in module types) - - This instance of :ctype:`PyTypeObject` represents the Python list type. - This is the same object as ``list`` and ``types.ListType`` in the Python - layer. + This instance of :ctype:`PyTypeObject` represents the Python list type. This + is the same object as ``list`` in the Python layer. .. cfunction:: int PyList_Check(PyObject *p) From python-checkins at python.org Fri May 14 12:32:59 2010 From: python-checkins at python.org (martin.v.loewis) Date: Fri, 14 May 2010 12:32:59 +0200 (CEST) Subject: [Python-checkins] r81161 - tracker/roundup-src/roundup/scripts/roundup_server.py Message-ID: <20100514103259.55487EE983@mail.python.org> Author: martin.v.loewis Date: Fri May 14 12:32:59 2010 New Revision: 81161 Log: Add logging for in-progress requests. Modified: tracker/roundup-src/roundup/scripts/roundup_server.py Modified: tracker/roundup-src/roundup/scripts/roundup_server.py ============================================================================== --- tracker/roundup-src/roundup/scripts/roundup_server.py (original) +++ tracker/roundup-src/roundup/scripts/roundup_server.py Fri May 14 12:32:59 2010 @@ -233,7 +233,22 @@ traceback.print_exc() sys.stdin = save_stdin - do_GET = do_POST = do_HEAD = run_cgi + def run_cgi_outer(self): + "Log requests that are in progress" + if self.CONFIG and self.CONFIG['LOGFILE']: + jobfile = os.path.join(os.path.dirname(self.CONFIG['LOGFILE']), str(os.getpid())) + try: + f = open(jobfile, "w") + f.write(self.path) + f.close() + return self.run_cgi() + finally: + pass + #os.unlink(jobfile) + else: + return self.run_cgi() + + do_GET = do_POST = do_HEAD = run_cgi_outer def index(self): ''' Print up an index of the available trackers From python-checkins at python.org Fri May 14 12:35:55 2010 From: python-checkins at python.org (martin.v.loewis) Date: Fri, 14 May 2010 12:35:55 +0200 (CEST) Subject: [Python-checkins] r81162 - tracker/roundup-src/roundup/scripts/roundup_server.py Message-ID: <20100514103555.184E0EE983@mail.python.org> Author: martin.v.loewis Date: Fri May 14 12:35:54 2010 New Revision: 81162 Log: Reactivate deletion of files. Modified: tracker/roundup-src/roundup/scripts/roundup_server.py Modified: tracker/roundup-src/roundup/scripts/roundup_server.py ============================================================================== --- tracker/roundup-src/roundup/scripts/roundup_server.py (original) +++ tracker/roundup-src/roundup/scripts/roundup_server.py Fri May 14 12:35:54 2010 @@ -243,8 +243,7 @@ f.close() return self.run_cgi() finally: - pass - #os.unlink(jobfile) + os.unlink(jobfile) else: return self.run_cgi() From python-checkins at python.org Fri May 14 16:20:07 2010 From: python-checkins at python.org (victor.stinner) Date: Fri, 14 May 2010 16:20:07 +0200 (CEST) Subject: [Python-checkins] r81163 - in python/trunk/Doc: howto/cporting.rst library/pkgutil.rst library/runpy.rst library/threading.rst library/wsgiref.rst library/zipimport.rst Message-ID: <20100514142007.73B2AEEA2D@mail.python.org> Author: victor.stinner Date: Fri May 14 16:20:07 2010 New Revision: 81163 Log: Doc: replace PEP xxx by :pep:`xxx` to create a link on the PEP Modified: python/trunk/Doc/howto/cporting.rst python/trunk/Doc/library/pkgutil.rst python/trunk/Doc/library/runpy.rst python/trunk/Doc/library/threading.rst python/trunk/Doc/library/wsgiref.rst python/trunk/Doc/library/zipimport.rst Modified: python/trunk/Doc/howto/cporting.rst ============================================================================== --- python/trunk/Doc/howto/cporting.rst (original) +++ python/trunk/Doc/howto/cporting.rst Fri May 14 16:20:07 2010 @@ -118,7 +118,7 @@ Module initialization and state =============================== -Python 3.0 has a revamped extension module initialization system. (See PEP +Python 3.0 has a revamped extension module initialization system. (See :pep:`3121`.) Instead of storing module state in globals, they should be stored in an interpreter specific structure. Creating modules that act correctly in both 2.x and 3.0 is tricky. The following simple example demonstrates how. :: Modified: python/trunk/Doc/library/pkgutil.rst ============================================================================== --- python/trunk/Doc/library/pkgutil.rst (original) +++ python/trunk/Doc/library/pkgutil.rst Fri May 14 16:20:07 2010 @@ -45,7 +45,7 @@ Get a resource from a package. - This is a wrapper for the PEP 302 loader :func:`get_data` API. The package + This is a wrapper for the :pep:`302` loader :func:`get_data` API. The package argument should be the name of a package, in standard module format (foo.bar). The resource argument should be in the form of a relative filename, using ``/`` as the path separator. The parent directory name @@ -60,5 +60,5 @@ d = os.path.dirname(sys.modules[package].__file__) data = open(os.path.join(d, resource), 'rb').read() - If the package cannot be located or loaded, or it uses a PEP 302 loader + If the package cannot be located or loaded, or it uses a :pep:`302` loader which does not support :func:`get_data`, then None is returned. Modified: python/trunk/Doc/library/runpy.rst ============================================================================== --- python/trunk/Doc/library/runpy.rst (original) +++ python/trunk/Doc/library/runpy.rst Fri May 14 16:20:07 2010 @@ -20,7 +20,7 @@ Execute the code of the specified module and return the resulting module globals dictionary. The module's code is first located using the standard - import mechanism (refer to PEP 302 for details) and then executed in a + import mechanism (refer to :pep:`302` for details) and then executed in a fresh module namespace. If the supplied module name refers to a package rather than a normal @@ -47,7 +47,7 @@ loader does not make filename information available, this variable is set to :const:`None`. - ``__loader__`` is set to the PEP 302 module loader used to retrieve the + ``__loader__`` is set to the :pep:`302` module loader used to retrieve the code for the module (This loader may be a wrapper around the standard import mechanism). @@ -105,7 +105,7 @@ loader does not make filename information available, this variable is set to :const:`None`. For a simple script, this will be set to ``file_path``. - ``__loader__`` is set to the PEP 302 module loader used to retrieve the + ``__loader__`` is set to the :pep:`302` module loader used to retrieve the code for the module (This loader may be a wrapper around the standard import mechanism). For a simple script, this will be set to :const:`None`. Modified: python/trunk/Doc/library/threading.rst ============================================================================== --- python/trunk/Doc/library/threading.rst (original) +++ python/trunk/Doc/library/threading.rst Fri May 14 16:20:07 2010 @@ -14,7 +14,7 @@ .. note:: - Starting with Python 2.6, this module provides PEP 8 compliant aliases and + Starting with Python 2.6, this module provides :pep:`8` compliant aliases and properties to replace the ``camelCase`` names that were inspired by Java's threading API. This updated API is compatible with that of the :mod:`multiprocessing` module. However, no schedule has been set for the Modified: python/trunk/Doc/library/wsgiref.rst ============================================================================== --- python/trunk/Doc/library/wsgiref.rst (original) +++ python/trunk/Doc/library/wsgiref.rst Fri May 14 16:20:07 2010 @@ -712,7 +712,7 @@ # use a function (note that you're not limited to a function, you can # use a class for example). The first argument passed to the function # is a dictionary containing CGI-style envrironment variables and the - # second variable is the callable object (see PEP333) + # second variable is the callable object (see :pep:`333`) def hello_world_app(environ, start_response): status = '200 OK' # HTTP Status headers = [('Content-type', 'text/plain')] # HTTP Headers Modified: python/trunk/Doc/library/zipimport.rst ============================================================================== --- python/trunk/Doc/library/zipimport.rst (original) +++ python/trunk/Doc/library/zipimport.rst Fri May 14 16:20:07 2010 @@ -41,12 +41,12 @@ Documentation on the ZIP file format by Phil Katz, the creator of the format and algorithms used. - :pep:`0273` - Import Modules from Zip Archives + :pep:`273` - Import Modules from Zip Archives Written by James C. Ahlstrom, who also provided an implementation. Python 2.3 follows the specification in PEP 273, but uses an implementation written by Just van Rossum that uses the import hooks described in PEP 302. - :pep:`0302` - New Import Hooks + :pep:`302` - New Import Hooks The PEP to add the import hooks that help this module work. From python-checkins at python.org Fri May 14 16:30:11 2010 From: python-checkins at python.org (victor.stinner) Date: Fri, 14 May 2010 16:30:11 +0200 (CEST) Subject: [Python-checkins] r81164 - in python/branches/release26-maint: Doc/howto/cporting.rst Doc/library/pkgutil.rst Doc/library/runpy.rst Doc/library/threading.rst Doc/library/wsgiref.rst Doc/library/zipimport.rst Message-ID: <20100514143011.E7874EEAA8@mail.python.org> Author: victor.stinner Date: Fri May 14 16:30:11 2010 New Revision: 81164 Log: Merged revisions 81163 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r81163 | victor.stinner | 2010-05-14 16:20:07 +0200 (ven., 14 mai 2010) | 2 lines Doc: replace PEP xxx by :pep:`xxx` to create a link on the PEP ........ Modified: python/branches/release26-maint/ (props changed) python/branches/release26-maint/Doc/howto/cporting.rst python/branches/release26-maint/Doc/library/pkgutil.rst python/branches/release26-maint/Doc/library/runpy.rst python/branches/release26-maint/Doc/library/threading.rst python/branches/release26-maint/Doc/library/wsgiref.rst python/branches/release26-maint/Doc/library/zipimport.rst Modified: python/branches/release26-maint/Doc/howto/cporting.rst ============================================================================== --- python/branches/release26-maint/Doc/howto/cporting.rst (original) +++ python/branches/release26-maint/Doc/howto/cporting.rst Fri May 14 16:30:11 2010 @@ -118,7 +118,7 @@ Module initialization and state =============================== -Python 3.0 has a revamped extension module initialization system. (See PEP +Python 3.0 has a revamped extension module initialization system. (See :pep:`3121`.) Instead of storing module state in globals, they should be stored in an interpreter specific structure. Creating modules that act correctly in both 2.x and 3.0 is tricky. The following simple example demonstrates how. :: Modified: python/branches/release26-maint/Doc/library/pkgutil.rst ============================================================================== --- python/branches/release26-maint/Doc/library/pkgutil.rst (original) +++ python/branches/release26-maint/Doc/library/pkgutil.rst Fri May 14 16:30:11 2010 @@ -45,7 +45,7 @@ Get a resource from a package. - This is a wrapper for the PEP 302 loader :func:`get_data` API. The package + This is a wrapper for the :pep:`302` loader :func:`get_data` API. The package argument should be the name of a package, in standard module format (foo.bar). The resource argument should be in the form of a relative filename, using ``/`` as the path separator. The parent directory name @@ -60,5 +60,5 @@ d = os.path.dirname(sys.modules[package].__file__) data = open(os.path.join(d, resource), 'rb').read() - If the package cannot be located or loaded, or it uses a PEP 302 loader + If the package cannot be located or loaded, or it uses a :pep:`302` loader which does not support :func:`get_data`, then None is returned. Modified: python/branches/release26-maint/Doc/library/runpy.rst ============================================================================== --- python/branches/release26-maint/Doc/library/runpy.rst (original) +++ python/branches/release26-maint/Doc/library/runpy.rst Fri May 14 16:30:11 2010 @@ -25,7 +25,7 @@ Execute the code of the specified module and return the resulting module globals dictionary. The module's code is first located using the standard import - mechanism (refer to PEP 302 for details) and then executed in a fresh module + mechanism (refer to :pep:`302` for details) and then executed in a fresh module namespace. The optional dictionary argument *init_globals* may be used to pre-populate the @@ -41,7 +41,7 @@ ``__name__`` is set to *run_name* if this optional argument is supplied, and the *mod_name* argument otherwise. - ``__loader__`` is set to the PEP 302 module loader used to retrieve the code for + ``__loader__`` is set to the :pep:`302` module loader used to retrieve the code for the module (This loader may be a wrapper around the standard import mechanism). ``__file__`` is set to the name provided by the module loader. If the loader Modified: python/branches/release26-maint/Doc/library/threading.rst ============================================================================== --- python/branches/release26-maint/Doc/library/threading.rst (original) +++ python/branches/release26-maint/Doc/library/threading.rst Fri May 14 16:30:11 2010 @@ -14,7 +14,7 @@ .. note:: - Starting with Python 2.6, this module provides PEP 8 compliant aliases and + Starting with Python 2.6, this module provides :pep:`8` compliant aliases and properties to replace the ``camelCase`` names that were inspired by Java's threading API. This updated API is compatible with that of the :mod:`multiprocessing` module. However, no schedule has been set for the Modified: python/branches/release26-maint/Doc/library/wsgiref.rst ============================================================================== --- python/branches/release26-maint/Doc/library/wsgiref.rst (original) +++ python/branches/release26-maint/Doc/library/wsgiref.rst Fri May 14 16:30:11 2010 @@ -712,7 +712,7 @@ # use a function (note that you're not limited to a function, you can # use a class for example). The first argument passed to the function # is a dictionary containing CGI-style envrironment variables and the - # second variable is the callable object (see PEP333) + # second variable is the callable object (see :pep:`333`) def hello_world_app(environ, start_response): status = '200 OK' # HTTP Status headers = [('Content-type', 'text/plain')] # HTTP Headers Modified: python/branches/release26-maint/Doc/library/zipimport.rst ============================================================================== --- python/branches/release26-maint/Doc/library/zipimport.rst (original) +++ python/branches/release26-maint/Doc/library/zipimport.rst Fri May 14 16:30:11 2010 @@ -41,12 +41,12 @@ Documentation on the ZIP file format by Phil Katz, the creator of the format and algorithms used. - :pep:`0273` - Import Modules from Zip Archives + :pep:`273` - Import Modules from Zip Archives Written by James C. Ahlstrom, who also provided an implementation. Python 2.3 follows the specification in PEP 273, but uses an implementation written by Just van Rossum that uses the import hooks described in PEP 302. - :pep:`0302` - New Import Hooks + :pep:`302` - New Import Hooks The PEP to add the import hooks that help this module work. From python-checkins at python.org Fri May 14 16:36:19 2010 From: python-checkins at python.org (victor.stinner) Date: Fri, 14 May 2010 16:36:19 +0200 (CEST) Subject: [Python-checkins] r81165 - in python/branches/py3k: Doc/howto/cporting.rst Doc/library/imp.rst Doc/library/pkgutil.rst Doc/library/runpy.rst Doc/library/wsgiref.rst Doc/library/zipimport.rst Message-ID: <20100514143619.209C8EEA34@mail.python.org> Author: victor.stinner Date: Fri May 14 16:36:18 2010 New Revision: 81165 Log: Merged revisions 81163 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r81163 | victor.stinner | 2010-05-14 16:20:07 +0200 (ven., 14 mai 2010) | 2 lines Doc: replace PEP xxx by :pep:`xxx` to create a link on the PEP ........ Modified: python/branches/py3k/ (props changed) python/branches/py3k/Doc/howto/cporting.rst python/branches/py3k/Doc/library/imp.rst python/branches/py3k/Doc/library/pkgutil.rst python/branches/py3k/Doc/library/runpy.rst python/branches/py3k/Doc/library/wsgiref.rst python/branches/py3k/Doc/library/zipimport.rst Modified: python/branches/py3k/Doc/howto/cporting.rst ============================================================================== --- python/branches/py3k/Doc/howto/cporting.rst (original) +++ python/branches/py3k/Doc/howto/cporting.rst Fri May 14 16:36:18 2010 @@ -120,7 +120,7 @@ Module initialization and state =============================== -Python 3.0 has a revamped extension module initialization system. (See PEP +Python 3.0 has a revamped extension module initialization system. (See :pep:`3121`.) Instead of storing module state in globals, they should be stored in an interpreter specific structure. Creating modules that act correctly in both 2.x and 3.0 is tricky. The following simple example demonstrates how. :: Modified: python/branches/py3k/Doc/library/imp.rst ============================================================================== --- python/branches/py3k/Doc/library/imp.rst (original) +++ python/branches/py3k/Doc/library/imp.rst Fri May 14 16:36:18 2010 @@ -211,7 +211,7 @@ .. function:: cache_from_source(path, debug_override=None) - Return the PEP 3147 path to the byte-compiled file associated with the + Return the :pep:`3147` path to the byte-compiled file associated with the source *path*. For example, if *path* is ``/foo/bar/baz.py`` the return value would be ``/foo/bar/__pycache__/baz.cpython-32.pyc`` for Python 3.2. The ``cpython-32`` string comes from the current magic tag (see @@ -225,15 +225,15 @@ .. function:: source_from_cache(path) - Given the *path* to a PEP 3147 file name, return the associated source code + Given the *path* to a :pep:`3147` file name, return the associated source code file path. For example, if *path* is ``/foo/bar/__pycache__/baz.cpython-32.pyc`` the returned path would be ``/foo/bar/baz.py``. *path* need not exist, however if it does not conform - to PEP 3147 format, a ``ValueError`` is raised. + to :pep:`3147` format, a ``ValueError`` is raised. .. function:: get_tag() - Return the PEP 3147 magic tag string matching this version of Python's + Return the :pep:`3147` magic tag string matching this version of Python's magic number, as returned by :func:`get_magic`. Modified: python/branches/py3k/Doc/library/pkgutil.rst ============================================================================== --- python/branches/py3k/Doc/library/pkgutil.rst (original) +++ python/branches/py3k/Doc/library/pkgutil.rst Fri May 14 16:36:18 2010 @@ -41,7 +41,7 @@ Get a resource from a package. - This is a wrapper for the PEP 302 loader :func:`get_data` API. The package + This is a wrapper for the :pep:`302` loader :func:`get_data` API. The package argument should be the name of a package, in standard module format (foo.bar). The resource argument should be in the form of a relative filename, using ``/`` as the path separator. The parent directory name @@ -56,5 +56,5 @@ d = os.path.dirname(sys.modules[package].__file__) data = open(os.path.join(d, resource), 'rb').read() - If the package cannot be located or loaded, or it uses a PEP 302 loader + If the package cannot be located or loaded, or it uses a :pep:`302` loader which does not support :func:`get_data`, then None is returned. Modified: python/branches/py3k/Doc/library/runpy.rst ============================================================================== --- python/branches/py3k/Doc/library/runpy.rst (original) +++ python/branches/py3k/Doc/library/runpy.rst Fri May 14 16:36:18 2010 @@ -18,7 +18,7 @@ Execute the code of the specified module and return the resulting module globals dictionary. The module's code is first located using the standard - import mechanism (refer to PEP 302 for details) and then executed in a + import mechanism (refer to :pep:`302` for details) and then executed in a fresh module namespace. If the supplied module name refers to a package rather than a normal @@ -48,7 +48,7 @@ ``__cached__`` will be set to ``None``. - ``__loader__`` is set to the PEP 302 module loader used to retrieve the + ``__loader__`` is set to the :pep:`302` module loader used to retrieve the code for the module (This loader may be a wrapper around the standard import mechanism). @@ -106,7 +106,7 @@ loader does not make filename information available, this variable is set to :const:`None`. For a simple script, this will be set to ``file_path``. - ``__loader__`` is set to the PEP 302 module loader used to retrieve the + ``__loader__`` is set to the :pep:`302` module loader used to retrieve the code for the module (This loader may be a wrapper around the standard import mechanism). For a simple script, this will be set to :const:`None`. Modified: python/branches/py3k/Doc/library/wsgiref.rst ============================================================================== --- python/branches/py3k/Doc/library/wsgiref.rst (original) +++ python/branches/py3k/Doc/library/wsgiref.rst Fri May 14 16:36:18 2010 @@ -710,7 +710,7 @@ # use a function (note that you're not limited to a function, you can # use a class for example). The first argument passed to the function # is a dictionary containing CGI-style envrironment variables and the - # second variable is the callable object (see PEP333) + # second variable is the callable object (see :pep:`333`) def hello_world_app(environ, start_response): status = b'200 OK' # HTTP Status headers = [(b'Content-type', b'text/plain; charset=utf-8')] # HTTP Headers Modified: python/branches/py3k/Doc/library/zipimport.rst ============================================================================== --- python/branches/py3k/Doc/library/zipimport.rst (original) +++ python/branches/py3k/Doc/library/zipimport.rst Fri May 14 16:36:18 2010 @@ -34,12 +34,12 @@ Documentation on the ZIP file format by Phil Katz, the creator of the format and algorithms used. - :pep:`0273` - Import Modules from Zip Archives + :pep:`273` - Import Modules from Zip Archives Written by James C. Ahlstrom, who also provided an implementation. Python 2.3 follows the specification in PEP 273, but uses an implementation written by Just van Rossum that uses the import hooks described in PEP 302. - :pep:`0302` - New Import Hooks + :pep:`302` - New Import Hooks The PEP to add the import hooks that help this module work. From python-checkins at python.org Fri May 14 17:53:20 2010 From: python-checkins at python.org (victor.stinner) Date: Fri, 14 May 2010 17:53:20 +0200 (CEST) Subject: [Python-checkins] r81166 - python/trunk/Doc/c-api/unicode.rst Message-ID: <20100514155320.5A735EEA0B@mail.python.org> Author: victor.stinner Date: Fri May 14 17:53:20 2010 New Revision: 81166 Log: Issue #8711: add paragraph titles to c-api/unicode.rst (Python2 doesn't have PyUnicode_DecodeFSDefault*() functions) Modified: python/trunk/Doc/c-api/unicode.rst Modified: python/trunk/Doc/c-api/unicode.rst ============================================================================== --- python/trunk/Doc/c-api/unicode.rst (original) +++ python/trunk/Doc/c-api/unicode.rst Fri May 14 17:53:20 2010 @@ -11,11 +11,12 @@ ^^^^^^^^^^^^^^^ +Unicode Type +"""""""""""" + These are the basic Unicode object types used for the Unicode implementation in Python: -.. % --- Unicode Type ------------------------------------------------------- - .. ctype:: Py_UNICODE @@ -105,12 +106,13 @@ .. versionadded:: 2.6 +Unicode Character Properties +"""""""""""""""""""""""""""" + Unicode provides many different character properties. The most often needed ones are available through these macros which are mapped to C functions depending on the Python configuration. -.. % --- Unicode character properties --------------------------------------- - .. cfunction:: int Py_UNICODE_ISSPACE(Py_UNICODE ch) @@ -196,11 +198,13 @@ Return the character *ch* converted to a double. Return ``-1.0`` if this is not possible. This macro does not raise exceptions. + +Plain Py_UNICODE +"""""""""""""""" + To create Unicode objects and access their basic sequence properties, use these APIs: -.. % --- Plain Py_UNICODE --------------------------------------------------- - .. cfunction:: PyObject* PyUnicode_FromUnicode(const Py_UNICODE *u, Py_ssize_t size) @@ -258,8 +262,11 @@ Support is optimized if Python's own :ctype:`Py_UNICODE` type is identical to the system's :ctype:`wchar_t`. -.. % --- wchar_t support for platforms which support it --------------------- +wchar_t Support +""""""""""""""" + +wchar_t support for platforms which support it: .. cfunction:: PyObject* PyUnicode_FromWideChar(const wchar_t *w, Py_ssize_t size) @@ -312,9 +319,11 @@ The codecs all use a similar interface. Only deviation from the following generic ones are documented for simplicity. -These are the generic codec APIs: -.. % --- Generic Codecs ----------------------------------------------------- +Generic Codecs +"""""""""""""" + +These are the generic codec APIs: .. cfunction:: PyObject* PyUnicode_Decode(const char *s, Py_ssize_t size, const char *encoding, const char *errors) @@ -351,9 +360,11 @@ the Python codec registry. Return *NULL* if an exception was raised by the codec. -These are the UTF-8 codec APIs: -.. % --- UTF-8 Codecs ------------------------------------------------------- +UTF-8 Codecs +"""""""""""" + +These are the UTF-8 codec APIs: .. cfunction:: PyObject* PyUnicode_DecodeUTF8(const char *s, Py_ssize_t size, const char *errors) @@ -396,9 +407,11 @@ object. Error handling is "strict". Return *NULL* if an exception was raised by the codec. -These are the UTF-32 codec APIs: -.. % --- UTF-32 Codecs ------------------------------------------------------ */ +UTF-32 Codecs +""""""""""""" + +These are the UTF-32 codec APIs: .. cfunction:: PyObject* PyUnicode_DecodeUTF32(const char *s, Py_ssize_t size, const char *errors, int *byteorder) @@ -471,9 +484,10 @@ .. versionadded:: 2.6 -These are the UTF-16 codec APIs: +UTF-16 Codecs +""""""""""""" -.. % --- UTF-16 Codecs ------------------------------------------------------ */ +These are the UTF-16 codec APIs: .. cfunction:: PyObject* PyUnicode_DecodeUTF16(const char *s, Py_ssize_t size, const char *errors, int *byteorder) @@ -552,9 +566,11 @@ string always starts with a BOM mark. Error handling is "strict". Return *NULL* if an exception was raised by the codec. -These are the "Unicode Escape" codec APIs: -.. % --- Unicode-Escape Codecs ---------------------------------------------- +Unicode-Escape Codecs +""""""""""""""""""""" + +These are the "Unicode Escape" codec APIs: .. cfunction:: PyObject* PyUnicode_DecodeUnicodeEscape(const char *s, Py_ssize_t size, const char *errors) @@ -584,9 +600,11 @@ string object. Error handling is "strict". Return *NULL* if an exception was raised by the codec. -These are the "Raw Unicode Escape" codec APIs: -.. % --- Raw-Unicode-Escape Codecs ------------------------------------------ +Raw-Unicode-Escape Codecs +""""""""""""""""""""""""" + +These are the "Raw Unicode Escape" codec APIs: .. cfunction:: PyObject* PyUnicode_DecodeRawUnicodeEscape(const char *s, Py_ssize_t size, const char *errors) @@ -616,11 +634,13 @@ Python string object. Error handling is "strict". Return *NULL* if an exception was raised by the codec. + +Latin-1 Codecs +"""""""""""""" + These are the Latin-1 codec APIs: Latin-1 corresponds to the first 256 Unicode ordinals and only these are accepted by the codecs during encoding. -.. % --- Latin-1 Codecs ----------------------------------------------------- - .. cfunction:: PyObject* PyUnicode_DecodeLatin1(const char *s, Py_ssize_t size, const char *errors) @@ -648,11 +668,13 @@ object. Error handling is "strict". Return *NULL* if an exception was raised by the codec. + +ASCII Codecs +"""""""""""" + These are the ASCII codec APIs. Only 7-bit ASCII data is accepted. All other codes generate errors. -.. % --- ASCII Codecs ------------------------------------------------------- - .. cfunction:: PyObject* PyUnicode_DecodeASCII(const char *s, Py_ssize_t size, const char *errors) @@ -680,9 +702,11 @@ object. Error handling is "strict". Return *NULL* if an exception was raised by the codec. -These are the mapping codec APIs: -.. % --- Character Map Codecs ----------------------------------------------- +Character Map Codecs +"""""""""""""""""""" + +These are the mapping codec APIs: This codec is special in that it can be used to implement many different codecs (and this is in fact what was done to obtain most of the standard codecs @@ -765,7 +789,9 @@ DBCS) is a class of encodings, not just one. The target encoding is defined by the user settings on the machine running the codec. -.. % --- MBCS codecs for Windows -------------------------------------------- + +MBCS codecs for Windows +""""""""""""""""""""""" .. cfunction:: PyObject* PyUnicode_DecodeMBCS(const char *s, Py_ssize_t size, const char *errors) @@ -804,8 +830,9 @@ object. Error handling is "strict". Return *NULL* if an exception was raised by the codec. -.. % --- Methods & Slots ---------------------------------------------------- +Methods & Slots +""""""""""""""" .. _unicodemethodsandslots: From python-checkins at python.org Fri May 14 17:55:12 2010 From: python-checkins at python.org (victor.stinner) Date: Fri, 14 May 2010 17:55:12 +0200 (CEST) Subject: [Python-checkins] r81167 - in python/branches/release26-maint: Doc/c-api/unicode.rst Message-ID: <20100514155512.58026EEAE9@mail.python.org> Author: victor.stinner Date: Fri May 14 17:55:12 2010 New Revision: 81167 Log: Merged revisions 81166 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r81166 | victor.stinner | 2010-05-14 17:53:20 +0200 (ven., 14 mai 2010) | 4 lines Issue #8711: add paragraph titles to c-api/unicode.rst (Python2 doesn't have PyUnicode_DecodeFSDefault*() functions) ........ Modified: python/branches/release26-maint/ (props changed) python/branches/release26-maint/Doc/c-api/unicode.rst Modified: python/branches/release26-maint/Doc/c-api/unicode.rst ============================================================================== --- python/branches/release26-maint/Doc/c-api/unicode.rst (original) +++ python/branches/release26-maint/Doc/c-api/unicode.rst Fri May 14 17:55:12 2010 @@ -11,11 +11,12 @@ ^^^^^^^^^^^^^^^ +Unicode Type +"""""""""""" + These are the basic Unicode object types used for the Unicode implementation in Python: -.. % --- Unicode Type ------------------------------------------------------- - .. ctype:: Py_UNICODE @@ -105,12 +106,13 @@ .. versionadded:: 2.6 +Unicode Character Properties +"""""""""""""""""""""""""""" + Unicode provides many different character properties. The most often needed ones are available through these macros which are mapped to C functions depending on the Python configuration. -.. % --- Unicode character properties --------------------------------------- - .. cfunction:: int Py_UNICODE_ISSPACE(Py_UNICODE ch) @@ -196,11 +198,13 @@ Return the character *ch* converted to a double. Return ``-1.0`` if this is not possible. This macro does not raise exceptions. + +Plain Py_UNICODE +"""""""""""""""" + To create Unicode objects and access their basic sequence properties, use these APIs: -.. % --- Plain Py_UNICODE --------------------------------------------------- - .. cfunction:: PyObject* PyUnicode_FromUnicode(const Py_UNICODE *u, Py_ssize_t size) @@ -258,8 +262,11 @@ Support is optimized if Python's own :ctype:`Py_UNICODE` type is identical to the system's :ctype:`wchar_t`. -.. % --- wchar_t support for platforms which support it --------------------- +wchar_t Support +""""""""""""""" + +wchar_t support for platforms which support it: .. cfunction:: PyObject* PyUnicode_FromWideChar(const wchar_t *w, Py_ssize_t size) @@ -312,9 +319,11 @@ The codecs all use a similar interface. Only deviation from the following generic ones are documented for simplicity. -These are the generic codec APIs: -.. % --- Generic Codecs ----------------------------------------------------- +Generic Codecs +"""""""""""""" + +These are the generic codec APIs: .. cfunction:: PyObject* PyUnicode_Decode(const char *s, Py_ssize_t size, const char *encoding, const char *errors) @@ -351,9 +360,11 @@ the Python codec registry. Return *NULL* if an exception was raised by the codec. -These are the UTF-8 codec APIs: -.. % --- UTF-8 Codecs ------------------------------------------------------- +UTF-8 Codecs +"""""""""""" + +These are the UTF-8 codec APIs: .. cfunction:: PyObject* PyUnicode_DecodeUTF8(const char *s, Py_ssize_t size, const char *errors) @@ -396,9 +407,11 @@ object. Error handling is "strict". Return *NULL* if an exception was raised by the codec. -These are the UTF-32 codec APIs: -.. % --- UTF-32 Codecs ------------------------------------------------------ */ +UTF-32 Codecs +""""""""""""" + +These are the UTF-32 codec APIs: .. cfunction:: PyObject* PyUnicode_DecodeUTF32(const char *s, Py_ssize_t size, const char *errors, int *byteorder) @@ -471,9 +484,10 @@ .. versionadded:: 2.6 -These are the UTF-16 codec APIs: +UTF-16 Codecs +""""""""""""" -.. % --- UTF-16 Codecs ------------------------------------------------------ */ +These are the UTF-16 codec APIs: .. cfunction:: PyObject* PyUnicode_DecodeUTF16(const char *s, Py_ssize_t size, const char *errors, int *byteorder) @@ -552,9 +566,11 @@ string always starts with a BOM mark. Error handling is "strict". Return *NULL* if an exception was raised by the codec. -These are the "Unicode Escape" codec APIs: -.. % --- Unicode-Escape Codecs ---------------------------------------------- +Unicode-Escape Codecs +""""""""""""""""""""" + +These are the "Unicode Escape" codec APIs: .. cfunction:: PyObject* PyUnicode_DecodeUnicodeEscape(const char *s, Py_ssize_t size, const char *errors) @@ -584,9 +600,11 @@ string object. Error handling is "strict". Return *NULL* if an exception was raised by the codec. -These are the "Raw Unicode Escape" codec APIs: -.. % --- Raw-Unicode-Escape Codecs ------------------------------------------ +Raw-Unicode-Escape Codecs +""""""""""""""""""""""""" + +These are the "Raw Unicode Escape" codec APIs: .. cfunction:: PyObject* PyUnicode_DecodeRawUnicodeEscape(const char *s, Py_ssize_t size, const char *errors) @@ -616,11 +634,13 @@ Python string object. Error handling is "strict". Return *NULL* if an exception was raised by the codec. + +Latin-1 Codecs +"""""""""""""" + These are the Latin-1 codec APIs: Latin-1 corresponds to the first 256 Unicode ordinals and only these are accepted by the codecs during encoding. -.. % --- Latin-1 Codecs ----------------------------------------------------- - .. cfunction:: PyObject* PyUnicode_DecodeLatin1(const char *s, Py_ssize_t size, const char *errors) @@ -648,11 +668,13 @@ object. Error handling is "strict". Return *NULL* if an exception was raised by the codec. + +ASCII Codecs +"""""""""""" + These are the ASCII codec APIs. Only 7-bit ASCII data is accepted. All other codes generate errors. -.. % --- ASCII Codecs ------------------------------------------------------- - .. cfunction:: PyObject* PyUnicode_DecodeASCII(const char *s, Py_ssize_t size, const char *errors) @@ -680,9 +702,11 @@ object. Error handling is "strict". Return *NULL* if an exception was raised by the codec. -These are the mapping codec APIs: -.. % --- Character Map Codecs ----------------------------------------------- +Character Map Codecs +"""""""""""""""""""" + +These are the mapping codec APIs: This codec is special in that it can be used to implement many different codecs (and this is in fact what was done to obtain most of the standard codecs @@ -765,7 +789,9 @@ DBCS) is a class of encodings, not just one. The target encoding is defined by the user settings on the machine running the codec. -.. % --- MBCS codecs for Windows -------------------------------------------- + +MBCS codecs for Windows +""""""""""""""""""""""" .. cfunction:: PyObject* PyUnicode_DecodeMBCS(const char *s, Py_ssize_t size, const char *errors) @@ -804,8 +830,9 @@ object. Error handling is "strict". Return *NULL* if an exception was raised by the codec. -.. % --- Methods & Slots ---------------------------------------------------- +Methods & Slots +""""""""""""""" .. _unicodemethodsandslots: From python-checkins at python.org Fri May 14 17:58:55 2010 From: python-checkins at python.org (victor.stinner) Date: Fri, 14 May 2010 17:58:55 +0200 (CEST) Subject: [Python-checkins] r81168 - in python/branches/py3k: Doc/c-api/unicode.rst Include/unicodeobject.h Message-ID: <20100514155855.545E7EEAE8@mail.python.org> Author: victor.stinner Date: Fri May 14 17:58:55 2010 New Revision: 81168 Log: Issue #8711: Document PyUnicode_DecodeFSDefault*() functions * Add paragraph titles to c-api/unicode.rst. * Fix PyUnicode_DecodeFSDefault*() comment: it now uses the "surrogateescape" error handler (and not "replace") * Remove "The function is intended to be used for paths and file names only during bootstrapping process where the codecs are not set up." from PyUnicode_FSConverter() comment: it is used after the bootstrapping and for other purposes than file names Modified: python/branches/py3k/ (props changed) python/branches/py3k/Doc/c-api/unicode.rst python/branches/py3k/Include/unicodeobject.h Modified: python/branches/py3k/Doc/c-api/unicode.rst ============================================================================== --- python/branches/py3k/Doc/c-api/unicode.rst (original) +++ python/branches/py3k/Doc/c-api/unicode.rst Fri May 14 17:58:55 2010 @@ -10,11 +10,12 @@ Unicode Objects ^^^^^^^^^^^^^^^ +Unicode Type +"""""""""""" + These are the basic Unicode object types used for the Unicode implementation in Python: -.. % --- Unicode Type ------------------------------------------------------- - .. ctype:: Py_UNICODE @@ -89,12 +90,13 @@ Clear the free list. Return the total number of freed items. +Unicode Character Properties +"""""""""""""""""""""""""""" + Unicode provides many different character properties. The most often needed ones are available through these macros which are mapped to C functions depending on the Python configuration. -.. % --- Unicode character properties --------------------------------------- - .. cfunction:: int Py_UNICODE_ISSPACE(Py_UNICODE ch) @@ -192,11 +194,13 @@ Return the character *ch* converted to a double. Return ``-1.0`` if this is not possible. This macro does not raise exceptions. + +Plain Py_UNICODE +"""""""""""""""" + To create Unicode objects and access their basic sequence properties, use these APIs: -.. % --- Plain Py_UNICODE --------------------------------------------------- - .. cfunction:: PyObject* PyUnicode_FromUnicode(const Py_UNICODE *u, Py_ssize_t size) @@ -364,9 +368,47 @@ Support is optimized if Python's own :ctype:`Py_UNICODE` type is identical to the system's :ctype:`wchar_t`. -.. % --- wchar_t support for platforms which support it --------------------- + +File System Encoding +"""""""""""""""""""" + +To encode and decode file names and other environment strings, +:cdata:`Py_FileSystemEncoding` should be used as the encoding, and +``"surrogateescape"`` should be used as the error handler (:pep:`383`). To +encode file names during argument parsing, the ``"O&"`` converter should be +used, passsing :func:PyUnicode_FSConverter as the conversion function: + +.. cfunction:: int PyUnicode_FSConverter(PyObject* obj, void* result) + + Convert *obj* into *result*, using :cdata:`Py_FileSystemDefaultEncoding`, + and the ``"surrogateescape"`` error handler. *result* must be a + ``PyObject*``, return a :func:`bytes` object which must be released if it + is no longer used. + + .. versionadded:: 3.1 + +.. cfunction:: PyObject* PyUnicode_DecodeFSDefaultAndSize(const char *s, Py_ssize_t size) + + Decode a null-terminated string using :cdata:`Py_FileSystemDefaultEncoding` + and the ``"surrogateescape"`` error handler. + + If :cdata:`Py_FileSystemDefaultEncoding` is not set, fall back to UTF-8. + + Use :func:`PyUnicode_DecodeFSDefaultAndSize` if you know the string length. + +.. cfunction:: PyObject* PyUnicode_DecodeFSDefault(const char *s) + + Decode a string using :cdata:`Py_FileSystemDefaultEncoding` and + the ``"surrogateescape"`` error handler. + + If :cdata:`Py_FileSystemDefaultEncoding` is not set, fall back to UTF-8. +wchar_t Support +""""""""""""""" + +wchar_t support for platforms which support it: + .. cfunction:: PyObject* PyUnicode_FromWideChar(const wchar_t *w, Py_ssize_t size) Create a Unicode object from the :ctype:`wchar_t` buffer *w* of the given size. @@ -413,9 +455,11 @@ The codecs all use a similar interface. Only deviation from the following generic ones are documented for simplicity. -These are the generic codec APIs: -.. % --- Generic Codecs ----------------------------------------------------- +Generic Codecs +"""""""""""""" + +These are the generic codec APIs: .. cfunction:: PyObject* PyUnicode_Decode(const char *s, Py_ssize_t size, const char *encoding, const char *errors) @@ -444,9 +488,11 @@ using the Python codec registry. Return *NULL* if an exception was raised by the codec. -These are the UTF-8 codec APIs: -.. % --- UTF-8 Codecs ------------------------------------------------------- +UTF-8 Codecs +"""""""""""" + +These are the UTF-8 codec APIs: .. cfunction:: PyObject* PyUnicode_DecodeUTF8(const char *s, Py_ssize_t size, const char *errors) @@ -476,9 +522,11 @@ object. Error handling is "strict". Return *NULL* if an exception was raised by the codec. -These are the UTF-32 codec APIs: -.. % --- UTF-32 Codecs ------------------------------------------------------ */ +UTF-32 Codecs +""""""""""""" + +These are the UTF-32 codec APIs: .. cfunction:: PyObject* PyUnicode_DecodeUTF32(const char *s, Py_ssize_t size, const char *errors, int *byteorder) @@ -543,9 +591,10 @@ Return *NULL* if an exception was raised by the codec. -These are the UTF-16 codec APIs: +UTF-16 Codecs +""""""""""""" -.. % --- UTF-16 Codecs ------------------------------------------------------ */ +These are the UTF-16 codec APIs: .. cfunction:: PyObject* PyUnicode_DecodeUTF16(const char *s, Py_ssize_t size, const char *errors, int *byteorder) @@ -609,9 +658,11 @@ order. The string always starts with a BOM mark. Error handling is "strict". Return *NULL* if an exception was raised by the codec. -These are the "Unicode Escape" codec APIs: -.. % --- Unicode-Escape Codecs ---------------------------------------------- +Unicode-Escape Codecs +""""""""""""""""""""" + +These are the "Unicode Escape" codec APIs: .. cfunction:: PyObject* PyUnicode_DecodeUnicodeEscape(const char *s, Py_ssize_t size, const char *errors) @@ -633,9 +684,11 @@ string object. Error handling is "strict". Return *NULL* if an exception was raised by the codec. -These are the "Raw Unicode Escape" codec APIs: -.. % --- Raw-Unicode-Escape Codecs ------------------------------------------ +Raw-Unicode-Escape Codecs +""""""""""""""""""""""""" + +These are the "Raw Unicode Escape" codec APIs: .. cfunction:: PyObject* PyUnicode_DecodeRawUnicodeEscape(const char *s, Py_ssize_t size, const char *errors) @@ -657,11 +710,13 @@ Python string object. Error handling is "strict". Return *NULL* if an exception was raised by the codec. + +Latin-1 Codecs +"""""""""""""" + These are the Latin-1 codec APIs: Latin-1 corresponds to the first 256 Unicode ordinals and only these are accepted by the codecs during encoding. -.. % --- Latin-1 Codecs ----------------------------------------------------- - .. cfunction:: PyObject* PyUnicode_DecodeLatin1(const char *s, Py_ssize_t size, const char *errors) @@ -682,11 +737,13 @@ object. Error handling is "strict". Return *NULL* if an exception was raised by the codec. + +ASCII Codecs +"""""""""""" + These are the ASCII codec APIs. Only 7-bit ASCII data is accepted. All other codes generate errors. -.. % --- ASCII Codecs ------------------------------------------------------- - .. cfunction:: PyObject* PyUnicode_DecodeASCII(const char *s, Py_ssize_t size, const char *errors) @@ -707,9 +764,11 @@ object. Error handling is "strict". Return *NULL* if an exception was raised by the codec. -These are the mapping codec APIs: -.. % --- Character Map Codecs ----------------------------------------------- +Character Map Codecs +"""""""""""""""""""" + +These are the mapping codec APIs: This codec is special in that it can be used to implement many different codecs (and this is in fact what was done to obtain most of the standard codecs @@ -778,7 +837,9 @@ DBCS) is a class of encodings, not just one. The target encoding is defined by the user settings on the machine running the codec. -.. % --- MBCS codecs for Windows -------------------------------------------- + +MBCS codecs for Windows +""""""""""""""""""""""" .. cfunction:: PyObject* PyUnicode_DecodeMBCS(const char *s, Py_ssize_t size, const char *errors) @@ -808,20 +869,9 @@ object. Error handling is "strict". Return *NULL* if an exception was raised by the codec. -For decoding file names and other environment strings, :cdata:`Py_FileSystemEncoding` -should be used as the encoding, and ``"surrogateescape"`` should be used as the error -handler. For encoding file names during argument parsing, the ``O&`` converter should -be used, passsing PyUnicode_FSConverter as the conversion function: - -.. cfunction:: int PyUnicode_FSConverter(PyObject* obj, void* result) - - Convert *obj* into *result*, using the file system encoding, and the ``surrogateescape`` - error handler. *result* must be a ``PyObject*``, yielding a bytes or bytearray object - which must be released if it is no longer used. - - .. versionadded:: 3.1 -.. % --- Methods & Slots ---------------------------------------------------- +Methods & Slots +""""""""""""""" .. _unicodemethodsandslots: Modified: python/branches/py3k/Include/unicodeobject.h ============================================================================== --- python/branches/py3k/Include/unicodeobject.h (original) +++ python/branches/py3k/Include/unicodeobject.h Fri May 14 17:58:55 2010 @@ -1240,25 +1240,29 @@ /* --- File system encoding ---------------------------------------------- */ /* ParseTuple converter which converts a Unicode object into the file - system encoding as a bytes object, using the PEP 383 error handler; bytes - objects are output as-is. */ + system encoding as a bytes object, using the "surrogateescape" error + handler; bytes objects are output as-is. */ PyAPI_FUNC(int) PyUnicode_FSConverter(PyObject*, void*); -/* Decode a null-terminated string using Py_FileSystemDefaultEncoding. +/* Decode a null-terminated string using Py_FileSystemDefaultEncoding + and the "surrogateescape" error handler. - If the encoding is supported by one of the built-in codecs (i.e., UTF-8, - UTF-16, UTF-32, Latin-1 or MBCS), otherwise fallback to UTF-8 and replace - invalid characters with '?'. + If Py_FileSystemDefaultEncoding is not set, fall back to UTF-8. - The function is intended to be used for paths and file names only - during bootstrapping process where the codecs are not set up. + Use PyUnicode_DecodeFSDefaultAndSize() if you have the string length. */ PyAPI_FUNC(PyObject*) PyUnicode_DecodeFSDefault( const char *s /* encoded string */ ); +/* Decode a string using Py_FileSystemDefaultEncoding + and the "surrogateescape" error handler. + + If Py_FileSystemDefaultEncoding is not set, fall back to UTF-8. +*/ + PyAPI_FUNC(PyObject*) PyUnicode_DecodeFSDefaultAndSize( const char *s, /* encoded string */ Py_ssize_t size /* size */ From python-checkins at python.org Fri May 14 18:08:46 2010 From: python-checkins at python.org (victor.stinner) Date: Fri, 14 May 2010 18:08:46 +0200 (CEST) Subject: [Python-checkins] r81169 - in python/branches/release31-maint: Doc/c-api/unicode.rst Include/unicodeobject.h Message-ID: <20100514160846.EC172E188@mail.python.org> Author: victor.stinner Date: Fri May 14 18:08:46 2010 New Revision: 81169 Log: Merged revisions 81168 via svnmerge from svn+ssh://pythondev at svn.python.org/python/branches/py3k ........ r81168 | victor.stinner | 2010-05-14 17:58:55 +0200 (ven., 14 mai 2010) | 10 lines Issue #8711: Document PyUnicode_DecodeFSDefault*() functions * Add paragraph titles to c-api/unicode.rst. * Fix PyUnicode_DecodeFSDefault*() comment: it now uses the "surrogateescape" error handler (and not "replace") * Remove "The function is intended to be used for paths and file names only during bootstrapping process where the codecs are not set up." from PyUnicode_FSConverter() comment: it is used after the bootstrapping and for other purposes than file names ........ Modified: python/branches/release31-maint/ (props changed) python/branches/release31-maint/Doc/c-api/unicode.rst python/branches/release31-maint/Include/unicodeobject.h Modified: python/branches/release31-maint/Doc/c-api/unicode.rst ============================================================================== --- python/branches/release31-maint/Doc/c-api/unicode.rst (original) +++ python/branches/release31-maint/Doc/c-api/unicode.rst Fri May 14 18:08:46 2010 @@ -10,11 +10,12 @@ Unicode Objects ^^^^^^^^^^^^^^^ +Unicode Type +"""""""""""" + These are the basic Unicode object types used for the Unicode implementation in Python: -.. % --- Unicode Type ------------------------------------------------------- - .. ctype:: Py_UNICODE @@ -89,12 +90,13 @@ Clear the free list. Return the total number of freed items. +Unicode Character Properties +"""""""""""""""""""""""""""" + Unicode provides many different character properties. The most often needed ones are available through these macros which are mapped to C functions depending on the Python configuration. -.. % --- Unicode character properties --------------------------------------- - .. cfunction:: int Py_UNICODE_ISSPACE(Py_UNICODE ch) @@ -192,11 +194,13 @@ Return the character *ch* converted to a double. Return ``-1.0`` if this is not possible. This macro does not raise exceptions. + +Plain Py_UNICODE +"""""""""""""""" + To create Unicode objects and access their basic sequence properties, use these APIs: -.. % --- Plain Py_UNICODE --------------------------------------------------- - .. cfunction:: PyObject* PyUnicode_FromUnicode(const Py_UNICODE *u, Py_ssize_t size) @@ -346,9 +350,47 @@ Support is optimized if Python's own :ctype:`Py_UNICODE` type is identical to the system's :ctype:`wchar_t`. -.. % --- wchar_t support for platforms which support it --------------------- + +File System Encoding +"""""""""""""""""""" + +To encode and decode file names and other environment strings, +:cdata:`Py_FileSystemEncoding` should be used as the encoding, and +``"surrogateescape"`` should be used as the error handler (:pep:`383`). To +encode file names during argument parsing, the ``"O&"`` converter should be +used, passsing :func:PyUnicode_FSConverter as the conversion function: + +.. cfunction:: int PyUnicode_FSConverter(PyObject* obj, void* result) + + Convert *obj* into *result*, using :cdata:`Py_FileSystemDefaultEncoding`, + and the ``"surrogateescape"`` error handler. *result* must be a + ``PyObject*``, return a :func:`bytes` object which must be released if it + is no longer used. + + .. versionadded:: 3.1 + +.. cfunction:: PyObject* PyUnicode_DecodeFSDefaultAndSize(const char *s, Py_ssize_t size) + + Decode a null-terminated string using :cdata:`Py_FileSystemDefaultEncoding` + and the ``"surrogateescape"`` error handler. + + If :cdata:`Py_FileSystemDefaultEncoding` is not set, fall back to UTF-8. + + Use :func:`PyUnicode_DecodeFSDefaultAndSize` if you know the string length. + +.. cfunction:: PyObject* PyUnicode_DecodeFSDefault(const char *s) + + Decode a string using :cdata:`Py_FileSystemDefaultEncoding` and + the ``"surrogateescape"`` error handler. + + If :cdata:`Py_FileSystemDefaultEncoding` is not set, fall back to UTF-8. +wchar_t Support +""""""""""""""" + +wchar_t support for platforms which support it: + .. cfunction:: PyObject* PyUnicode_FromWideChar(const wchar_t *w, Py_ssize_t size) Create a Unicode object from the :ctype:`wchar_t` buffer *w* of the given size. @@ -395,9 +437,11 @@ The codecs all use a similar interface. Only deviation from the following generic ones are documented for simplicity. -These are the generic codec APIs: -.. % --- Generic Codecs ----------------------------------------------------- +Generic Codecs +"""""""""""""" + +These are the generic codec APIs: .. cfunction:: PyObject* PyUnicode_Decode(const char *s, Py_ssize_t size, const char *encoding, const char *errors) @@ -426,9 +470,11 @@ using the Python codec registry. Return *NULL* if an exception was raised by the codec. -These are the UTF-8 codec APIs: -.. % --- UTF-8 Codecs ------------------------------------------------------- +UTF-8 Codecs +"""""""""""" + +These are the UTF-8 codec APIs: .. cfunction:: PyObject* PyUnicode_DecodeUTF8(const char *s, Py_ssize_t size, const char *errors) @@ -458,9 +504,11 @@ object. Error handling is "strict". Return *NULL* if an exception was raised by the codec. -These are the UTF-32 codec APIs: -.. % --- UTF-32 Codecs ------------------------------------------------------ */ +UTF-32 Codecs +""""""""""""" + +These are the UTF-32 codec APIs: .. cfunction:: PyObject* PyUnicode_DecodeUTF32(const char *s, Py_ssize_t size, const char *errors, int *byteorder) @@ -525,9 +573,10 @@ Return *NULL* if an exception was raised by the codec. -These are the UTF-16 codec APIs: +UTF-16 Codecs +""""""""""""" -.. % --- UTF-16 Codecs ------------------------------------------------------ */ +These are the UTF-16 codec APIs: .. cfunction:: PyObject* PyUnicode_DecodeUTF16(const char *s, Py_ssize_t size, const char *errors, int *byteorder) @@ -591,9 +640,11 @@ order. The string always starts with a BOM mark. Error handling is "strict". Return *NULL* if an exception was raised by the codec. -These are the "Unicode Escape" codec APIs: -.. % --- Unicode-Escape Codecs ---------------------------------------------- +Unicode-Escape Codecs +""""""""""""""""""""" + +These are the "Unicode Escape" codec APIs: .. cfunction:: PyObject* PyUnicode_DecodeUnicodeEscape(const char *s, Py_ssize_t size, const char *errors) @@ -615,9 +666,11 @@ string object. Error handling is "strict". Return *NULL* if an exception was raised by the codec. -These are the "Raw Unicode Escape" codec APIs: -.. % --- Raw-Unicode-Escape Codecs ------------------------------------------ +Raw-Unicode-Escape Codecs +""""""""""""""""""""""""" + +These are the "Raw Unicode Escape" codec APIs: .. cfunction:: PyObject* PyUnicode_DecodeRawUnicodeEscape(const char *s, Py_ssize_t size, const char *errors) @@ -639,11 +692,13 @@ Python string object. Error handling is "strict". Return *NULL* if an exception was raised by the codec. + +Latin-1 Codecs +"""""""""""""" + These are the Latin-1 codec APIs: Latin-1 corresponds to the first 256 Unicode ordinals and only these are accepted by the codecs during encoding. -.. % --- Latin-1 Codecs ----------------------------------------------------- - .. cfunction:: PyObject* PyUnicode_DecodeLatin1(const char *s, Py_ssize_t size, const char *errors) @@ -664,11 +719,13 @@ object. Error handling is "strict". Return *NULL* if an exception was raised by the codec. + +ASCII Codecs +"""""""""""" + These are the ASCII codec APIs. Only 7-bit ASCII data is accepted. All other codes generate errors. -.. % --- ASCII Codecs ------------------------------------------------------- - .. cfunction:: PyObject* PyUnicode_DecodeASCII(const char *s, Py_ssize_t size, const char *errors) @@ -689,9 +746,11 @@ object. Error handling is "strict". Return *NULL* if an exception was raised by the codec. -These are the mapping codec APIs: -.. % --- Character Map Codecs ----------------------------------------------- +Character Map Codecs +"""""""""""""""""""" + +These are the mapping codec APIs: This codec is special in that it can be used to implement many different codecs (and this is in fact what was done to obtain most of the standard codecs @@ -760,7 +819,9 @@ DBCS) is a class of encodings, not just one. The target encoding is defined by the user settings on the machine running the codec. -.. % --- MBCS codecs for Windows -------------------------------------------- + +MBCS codecs for Windows +""""""""""""""""""""""" .. cfunction:: PyObject* PyUnicode_DecodeMBCS(const char *s, Py_ssize_t size, const char *errors) @@ -790,20 +851,9 @@ object. Error handling is "strict". Return *NULL* if an exception was raised by the codec. -For decoding file names and other environment strings, :cdata:`Py_FileSystemEncoding` -should be used as the encoding, and ``"surrogateescape"`` should be used as the error -handler. For encoding file names during argument parsing, the ``O&`` converter should -be used, passsing PyUnicode_FSConverter as the conversion function: - -.. cfunction:: int PyUnicode_FSConverter(PyObject* obj, void* result) - - Convert *obj* into *result*, using the file system encoding, and the ``surrogateescape`` - error handler. *result* must be a ``PyObject*``, yielding a bytes or bytearray object - which must be released if it is no longer used. - - .. versionadded:: 3.1 -.. % --- Methods & Slots ---------------------------------------------------- +Methods & Slots +""""""""""""""" .. _unicodemethodsandslots: Modified: python/branches/release31-maint/Include/unicodeobject.h ============================================================================== --- python/branches/release31-maint/Include/unicodeobject.h (original) +++ python/branches/release31-maint/Include/unicodeobject.h Fri May 14 18:08:46 2010 @@ -1238,25 +1238,29 @@ /* --- File system encoding ---------------------------------------------- */ /* ParseTuple converter which converts a Unicode object into the file - system encoding, using the PEP 383 error handler; bytes objects are - output as-is. */ + system encoding as a bytes object, using the "surrogateescape" error + handler; bytes objects are output as-is. */ PyAPI_FUNC(int) PyUnicode_FSConverter(PyObject*, void*); -/* Decode a null-terminated string using Py_FileSystemDefaultEncoding. +/* Decode a null-terminated string using Py_FileSystemDefaultEncoding + and the "surrogateescape" error handler. - If the encoding is supported by one of the built-in codecs (i.e., UTF-8, - UTF-16, UTF-32, Latin-1 or MBCS), otherwise fallback to UTF-8 and replace - invalid characters with '?'. + If Py_FileSystemDefaultEncoding is not set, fall back to UTF-8. - The function is intended to be used for paths and file names only - during bootstrapping process where the codecs are not set up. + Use PyUnicode_DecodeFSDefaultAndSize() if you have the string length. */ PyAPI_FUNC(PyObject*) PyUnicode_DecodeFSDefault( const char *s /* encoded string */ ); +/* Decode a string using Py_FileSystemDefaultEncoding + and the "surrogateescape" error handler. + + If Py_FileSystemDefaultEncoding is not set, fall back to UTF-8. +*/ + PyAPI_FUNC(PyObject*) PyUnicode_DecodeFSDefaultAndSize( const char *s, /* encoded string */ Py_ssize_t size /* size */ From python-checkins at python.org Fri May 14 18:35:39 2010 From: python-checkins at python.org (victor.stinner) Date: Fri, 14 May 2010 18:35:39 +0200 (CEST) Subject: [Python-checkins] r81170 - python/branches/py3k/Modules/posixmodule.c Message-ID: <20100514163539.D14D6EEA03@mail.python.org> Author: victor.stinner Date: Fri May 14 18:35:39 2010 New Revision: 81170 Log: posix_listdir(), posix_readlink(): avoid temporary PyBytes object Use directly PyUnicode_DecodeFSDefaultAndSize() instead of PyBytes_FromStringAndSize() + PyUnicode_FromEncodedObject() if the argument is unicode. Modified: python/branches/py3k/Modules/posixmodule.c Modified: python/branches/py3k/Modules/posixmodule.c ============================================================================== --- python/branches/py3k/Modules/posixmodule.c (original) +++ python/branches/py3k/Modules/posixmodule.c Fri May 14 18:35:39 2010 @@ -2364,33 +2364,17 @@ (NAMLEN(ep) == 1 || (ep->d_name[1] == '.' && NAMLEN(ep) == 2))) continue; - v = PyBytes_FromStringAndSize(ep->d_name, NAMLEN(ep)); + if (arg_is_unicode) + v = PyUnicode_DecodeFSDefaultAndSize(ep->d_name, NAMLEN(ep)); + else + v = PyBytes_FromStringAndSize(ep->d_name, NAMLEN(ep)); if (v == NULL) { - Py_DECREF(d); - d = NULL; + Py_CLEAR(d); break; } - if (arg_is_unicode) { - PyObject *w; - - w = PyUnicode_FromEncodedObject(v, - Py_FileSystemDefaultEncoding, - "surrogateescape"); - Py_DECREF(v); - if (w != NULL) - v = w; - else { - /* Encoding failed to decode ASCII bytes. - Raise exception. */ - Py_DECREF(d); - d = NULL; - break; - } - } if (PyList_Append(d, v) != 0) { Py_DECREF(v); - Py_DECREF(d); - d = NULL; + Py_CLEAR(d); break; } Py_DECREF(v); @@ -4605,22 +4589,10 @@ return posix_error_with_allocated_filename(opath); Py_DECREF(opath); - v = PyBytes_FromStringAndSize(buf, n); - if (arg_is_unicode) { - PyObject *w; - - w = PyUnicode_FromEncodedObject(v, - Py_FileSystemDefaultEncoding, - "surrogateescape"); - if (w != NULL) { - Py_DECREF(v); - v = w; - } - else { - v = NULL; - } - } - return v; + if (arg_is_unicode) + return PyUnicode_DecodeFSDefaultAndSize(buf, n); + else + return PyBytes_FromStringAndSize(buf, n); } #endif /* HAVE_READLINK */ From python-checkins at python.org Fri May 14 18:39:10 2010 From: python-checkins at python.org (victor.stinner) Date: Fri, 14 May 2010 18:39:10 +0200 (CEST) Subject: [Python-checkins] r81171 - in python/branches/release31-maint: Modules/posixmodule.c Message-ID: <20100514163910.570B2EEABA@mail.python.org> Author: victor.stinner Date: Fri May 14 18:39:10 2010 New Revision: 81171 Log: Merged revisions 81170 via svnmerge from svn+ssh://pythondev at svn.python.org/python/branches/py3k ........ r81170 | victor.stinner | 2010-05-14 18:35:39 +0200 (ven., 14 mai 2010) | 6 lines posix_listdir(), posix_readlink(): avoid temporary PyBytes object Use directly PyUnicode_DecodeFSDefaultAndSize() instead of PyBytes_FromStringAndSize() + PyUnicode_FromEncodedObject() if the argument is unicode. ........ Modified: python/branches/release31-maint/ (props changed) python/branches/release31-maint/Modules/posixmodule.c Modified: python/branches/release31-maint/Modules/posixmodule.c ============================================================================== --- python/branches/release31-maint/Modules/posixmodule.c (original) +++ python/branches/release31-maint/Modules/posixmodule.c Fri May 14 18:39:10 2010 @@ -2515,33 +2515,17 @@ (NAMLEN(ep) == 1 || (ep->d_name[1] == '.' && NAMLEN(ep) == 2))) continue; - v = PyBytes_FromStringAndSize(ep->d_name, NAMLEN(ep)); + if (arg_is_unicode) + v = PyUnicode_DecodeFSDefaultAndSize(ep->d_name, NAMLEN(ep)); + else + v = PyBytes_FromStringAndSize(ep->d_name, NAMLEN(ep)); if (v == NULL) { - Py_DECREF(d); - d = NULL; + Py_CLEAR(d); break; } - if (arg_is_unicode) { - PyObject *w; - - w = PyUnicode_FromEncodedObject(v, - Py_FileSystemDefaultEncoding, - "surrogateescape"); - Py_DECREF(v); - if (w != NULL) - v = w; - else { - /* Encoding failed to decode ASCII bytes. - Raise exception. */ - Py_DECREF(d); - d = NULL; - break; - } - } if (PyList_Append(d, v) != 0) { Py_DECREF(v); - Py_DECREF(d); - d = NULL; + Py_CLEAR(d); break; } Py_DECREF(v); @@ -4676,22 +4660,10 @@ return posix_error_with_allocated_filename(opath); release_bytes(opath); - v = PyBytes_FromStringAndSize(buf, n); - if (arg_is_unicode) { - PyObject *w; - - w = PyUnicode_FromEncodedObject(v, - Py_FileSystemDefaultEncoding, - "surrogateescape"); - if (w != NULL) { - Py_DECREF(v); - v = w; - } - else { - v = NULL; - } - } - return v; + if (arg_is_unicode) + return PyUnicode_DecodeFSDefaultAndSize(buf, n); + else + return PyBytes_FromStringAndSize(buf, n); } #endif /* HAVE_READLINK */ From python-checkins at python.org Fri May 14 19:31:19 2010 From: python-checkins at python.org (martin.v.loewis) Date: Fri, 14 May 2010 19:31:19 +0200 (CEST) Subject: [Python-checkins] r81172 - tracker/roundup-src/roundup/cgi/templating.py Message-ID: <20100514173119.A199BEEB1D@mail.python.org> Author: martin.v.loewis Date: Fri May 14 19:31:19 2010 New Revision: 81172 Log: Ban grouping or sorting on multilink properties. Modified: tracker/roundup-src/roundup/cgi/templating.py Modified: tracker/roundup-src/roundup/cgi/templating.py ============================================================================== --- tracker/roundup-src/roundup/cgi/templating.py (original) +++ tracker/roundup-src/roundup/cgi/templating.py Fri May 14 19:31:19 2010 @@ -2386,6 +2386,8 @@ dir, name = '+', f if cls and cls.get_transitive_prop(name) is None: self.client.error_message.append("Unknown property "+name) + elif cls and isinstance(cls.get_transitive_prop(name), hyperdb.Multilink): + self.client.error_message.append("Cannot group or sort by "+name) else: var.append((dir, name)) From python-checkins at python.org Fri May 14 20:07:39 2010 From: python-checkins at python.org (victor.stinner) Date: Fri, 14 May 2010 20:07:39 +0200 (CEST) Subject: [Python-checkins] r81173 - python/branches/release31-maint/Modules/posixmodule.c Message-ID: <20100514180739.4BAC9EE9F6@mail.python.org> Author: victor.stinner Date: Fri May 14 20:07:39 2010 New Revision: 81173 Log: Revert r81171 (posix_listdir(), posix_readlink(): avoid temporary PyBytes object) PyUnicode_DecodeFSDefault*() doesn't use surrogateescape error handler, and so PyUnicode_FromEncodedObject(v, Py_FileSystemDefaultEncoding, "surrogateescape") cannot be replaced by PyUnicode_DecodeFSDefault(). It's a bad idea to try to fix surrogates things in Python 3.1... Modified: python/branches/release31-maint/Modules/posixmodule.c Modified: python/branches/release31-maint/Modules/posixmodule.c ============================================================================== --- python/branches/release31-maint/Modules/posixmodule.c (original) +++ python/branches/release31-maint/Modules/posixmodule.c Fri May 14 20:07:39 2010 @@ -2515,17 +2515,33 @@ (NAMLEN(ep) == 1 || (ep->d_name[1] == '.' && NAMLEN(ep) == 2))) continue; - if (arg_is_unicode) - v = PyUnicode_DecodeFSDefaultAndSize(ep->d_name, NAMLEN(ep)); - else - v = PyBytes_FromStringAndSize(ep->d_name, NAMLEN(ep)); + v = PyBytes_FromStringAndSize(ep->d_name, NAMLEN(ep)); if (v == NULL) { - Py_CLEAR(d); + Py_DECREF(d); + d = NULL; break; } + if (arg_is_unicode) { + PyObject *w; + + w = PyUnicode_FromEncodedObject(v, + Py_FileSystemDefaultEncoding, + "surrogateescape"); + Py_DECREF(v); + if (w != NULL) + v = w; + else { + /* Encoding failed to decode ASCII bytes. + Raise exception. */ + Py_DECREF(d); + d = NULL; + break; + } + } if (PyList_Append(d, v) != 0) { Py_DECREF(v); - Py_CLEAR(d); + Py_DECREF(d); + d = NULL; break; } Py_DECREF(v); @@ -4660,10 +4676,22 @@ return posix_error_with_allocated_filename(opath); release_bytes(opath); - if (arg_is_unicode) - return PyUnicode_DecodeFSDefaultAndSize(buf, n); - else - return PyBytes_FromStringAndSize(buf, n); + v = PyBytes_FromStringAndSize(buf, n); + if (arg_is_unicode) { + PyObject *w; + + w = PyUnicode_FromEncodedObject(v, + Py_FileSystemDefaultEncoding, + "surrogateescape"); + if (w != NULL) { + Py_DECREF(v); + v = w; + } + else { + v = NULL; + } + } + return v; } #endif /* HAVE_READLINK */ From python-checkins at python.org Fri May 14 20:51:40 2010 From: python-checkins at python.org (jeffrey.yasskin) Date: Fri, 14 May 2010 20:51:40 +0200 (CEST) Subject: [Python-checkins] r81174 - in python/branches/py3k-jit: Include/ceval.h Makefile.pre.in Python/ceval.c Python/ceval_gil.h Python/pythonrun.c Unittests/ThreadTest.cc Message-ID: <20100514185140.57E05EEB1E@mail.python.org> Author: jeffrey.yasskin Date: Fri May 14 20:51:40 2010 New Revision: 81174 Log: Fix a problem where initializing threads and then finalizing and re-initializing the interpreter would cause any use of the gil to crash. Added: python/branches/py3k-jit/Unittests/ThreadTest.cc Modified: python/branches/py3k-jit/Include/ceval.h python/branches/py3k-jit/Makefile.pre.in python/branches/py3k-jit/Python/ceval.c python/branches/py3k-jit/Python/ceval_gil.h python/branches/py3k-jit/Python/pythonrun.c Modified: python/branches/py3k-jit/Include/ceval.h ============================================================================== --- python/branches/py3k-jit/Include/ceval.h (original) +++ python/branches/py3k-jit/Include/ceval.h Fri May 14 20:51:40 2010 @@ -165,6 +165,7 @@ PyAPI_FUNC(void) PyEval_AcquireThread(PyThreadState *tstate); PyAPI_FUNC(void) PyEval_ReleaseThread(PyThreadState *tstate); PyAPI_FUNC(void) PyEval_ReInitThreads(void); +PyAPI_FUNC(void) PyEval_UnInitThreads(void); PyAPI_FUNC(void) _PyEval_SetSwitchInterval(unsigned long microseconds); PyAPI_FUNC(unsigned long) _PyEval_GetSwitchInterval(void); Modified: python/branches/py3k-jit/Makefile.pre.in ============================================================================== --- python/branches/py3k-jit/Makefile.pre.in (original) +++ python/branches/py3k-jit/Makefile.pre.in Fri May 14 20:51:40 2010 @@ -751,6 +751,7 @@ $(srcdir)/Unittests/GetArgsTest.cc \ $(srcdir)/Unittests/ListTest.cc \ $(srcdir)/Unittests/ObjectTest.cc \ + $(srcdir)/Unittests/ThreadTest.cc \ $(srcdir)/Unittests/UnicodeTest.cc \ $(srcdir)/Unittests/pytest_main.cc \ $(@LLVM_UNITTEST_SRCS@) \ Modified: python/branches/py3k-jit/Python/ceval.c ============================================================================== --- python/branches/py3k-jit/Python/ceval.c (original) +++ python/branches/py3k-jit/Python/ceval.c Fri May 14 20:51:40 2010 @@ -389,6 +389,16 @@ Py_DECREF(threading); } +/* This function is called from Py_Finalize to destroy the gil. No + other threads may be running when it is called. */ +void +PyEval_UnInitThreads(void) +{ + if (!gil_created()) + return; + destroy_gil(); +} + #else static _Py_atomic_int eval_breaker = {0}; static _Py_atomic_int gil_drop_request = {0}; Modified: python/branches/py3k-jit/Python/ceval_gil.h ============================================================================== --- python/branches/py3k-jit/Python/ceval_gil.h (original) +++ python/branches/py3k-jit/Python/ceval_gil.h Fri May 14 20:51:40 2010 @@ -95,6 +95,9 @@ #define MUTEX_INIT(mut) \ if (pthread_mutex_init(&mut, NULL)) { \ Py_FatalError("pthread_mutex_init(" #mut ") failed"); }; +#define MUTEX_DESTROY(mut) \ + if (pthread_mutex_destroy(&mut)) { \ + Py_FatalError("pthread_mutex_destroy(" #mut ") failed"); }; #define MUTEX_LOCK(mut) \ if (pthread_mutex_lock(&mut)) { \ Py_FatalError("pthread_mutex_lock(" #mut ") failed"); }; @@ -106,6 +109,9 @@ #define COND_INIT(cond) \ if (pthread_cond_init(&cond, NULL)) { \ Py_FatalError("pthread_cond_init(" #cond ") failed"); }; +#define COND_DESTROY(cond) \ + if (pthread_cond_destroy(&cond)) { \ + Py_FatalError("pthread_cond_destroy(" #cond ") failed"); }; #define COND_RESET(cond) #define COND_SIGNAL(cond) \ if (pthread_cond_signal(&cond)) { \ @@ -145,6 +151,9 @@ #define MUTEX_INIT(mut) \ if (!(mut = CreateMutex(NULL, FALSE, NULL))) { \ Py_FatalError("CreateMutex(" #mut ") failed"); }; +#define MUTEX_DESTROY(mut) \ + if (!CloseHandle(mut)) { \ + Py_FatalError("CloseHandle(" #mut ") failed to destroy mutex"); }; #define MUTEX_LOCK(mut) \ if (WaitForSingleObject(mut, INFINITE) != WAIT_OBJECT_0) { \ Py_FatalError("WaitForSingleObject(" #mut ") failed"); }; @@ -172,6 +181,9 @@ /* auto-reset, non-signalled */ \ if (!(cond = CreateEvent(NULL, FALSE, FALSE, NULL))) { \ Py_FatalError("CreateMutex(" #cond ") failed"); }; +#define COND_DESTROY(cond) \ + if (!CloseHandle(cond)) { \ + Py_FatalError("CloseHandle(" #cond ") failed to destroy event"); }; #define COND_RESET(cond) \ if (!ResetEvent(cond)) { \ Py_FatalError("ResetEvent(" #cond ") failed"); }; @@ -256,6 +268,21 @@ create_gil(); } +/* Requires that no other threads are running anymore. */ +static void destroy_gil(void) +{ + MUTEX_DESTROY(gil_mutex); +#ifdef FORCE_SWITCHING + MUTEX_DESTROY(switch_mutex); +#endif + COND_DESTROY(gil_cond); +#ifdef FORCE_SWITCHING + COND_DESTROY(switch_cond); +#endif + _Py_atomic_store_relaxed(&gil_locked, -1); + _Py_ANNOTATE_RWLOCK_DESTROY(&gil_locked); +} + static void drop_gil(PyThreadState *tstate) { /* NOTE: tstate is allowed to be NULL. */ Modified: python/branches/py3k-jit/Python/pythonrun.c ============================================================================== --- python/branches/py3k-jit/Python/pythonrun.c (original) +++ python/branches/py3k-jit/Python/pythonrun.c Fri May 14 20:51:40 2010 @@ -478,6 +478,7 @@ /* Delete current thread */ PyThreadState_Swap(NULL); PyInterpreterState_Delete(interp); + PyEval_UnInitThreads(); /* Sundry finalizers */ PyMethod_Fini(); Added: python/branches/py3k-jit/Unittests/ThreadTest.cc ============================================================================== --- (empty file) +++ python/branches/py3k-jit/Unittests/ThreadTest.cc Fri May 14 20:51:40 2010 @@ -0,0 +1,28 @@ +#include "Python.h" + +#include "gtest/gtest.h" +#include "pytest.h" + +namespace { + +class ThreadTest : public ::testing::Test { + PythonSetupTeardown setup_teardown_; +}; + +TEST_F(ThreadTest, InitThreadsAcrossFinalize) +{ + PyEval_InitThreads(); + + Py_Finalize(); + // Make it more likely that we get a different address for the + // PyThreadState in the new interpreter. + void *p = malloc(sizeof(PyThreadState)); + Py_Initialize(); + free(p); + + PyEval_InitThreads(); + Py_BEGIN_ALLOW_THREADS; // Used to crash. + Py_END_ALLOW_THREADS; +} + +} // anonymous namespace From python-checkins at python.org Fri May 14 22:08:55 2010 From: python-checkins at python.org (victor.stinner) Date: Fri, 14 May 2010 22:08:55 +0200 (CEST) Subject: [Python-checkins] r81175 - python/branches/release31-maint/Lib/test/support.py Message-ID: <20100514200855.DDCF6EEB25@mail.python.org> Author: victor.stinner Date: Fri May 14 22:08:55 2010 New Revision: 81175 Log: test/support.py: remove TESTFN if it is a directory Because of my previous commit (r81171), test_os failed without removing TESTFN directory (shutil.rmtree() was broken). Some buildbots still have a @test directory and some tests fail because of that. The bug is reproductible with: mkdir @test touch @test/abc ./python Lib/test/regrtest.py test_site Modified: python/branches/release31-maint/Lib/test/support.py Modified: python/branches/release31-maint/Lib/test/support.py ============================================================================== --- python/branches/release31-maint/Lib/test/support.py (original) +++ python/branches/release31-maint/Lib/test/support.py Fri May 14 22:08:55 2010 @@ -365,6 +365,10 @@ 'Unicode filename tests may not be effective' % TESTFN_UNICODE_UNENCODEABLE) +if os.path.isdir(TESTFN): + # a test failed (eg. test_os) without removing TESTFN directory + shutil.rmtree(TESTFN) + # Make sure we can write to TESTFN, try in /tmp if we can't fp = None try: From python-checkins at python.org Fri May 14 22:36:12 2010 From: python-checkins at python.org (tarek.ziade) Date: Fri, 14 May 2010 22:36:12 +0200 Subject: [Python-checkins] distutils2: makes sure this feature is run only under >2.6 Message-ID: tarek.ziade pushed 8924a69d0800 to distutils2: http://hg.python.org/distutils2/rev/8924a69d0800 changeset: 136:8924a69d0800 user: Tarek Ziade date: Wed May 12 15:38:03 2010 +0200 summary: makes sure this feature is run only under >2.6 files: src/distutils2/tests/test_converter.py diff --git a/src/distutils2/tests/test_converter.py b/src/distutils2/tests/test_converter.py --- a/src/distutils2/tests/test_converter.py +++ b/src/distutils2/tests/test_converter.py @@ -1,23 +1,11 @@ """Tests for distutils.converter.""" import os +import sys import unittest2 +from distutils2.converter import DistutilsRefactoringTool _CURDIR = os.path.dirname(__file__) -from distutils2.converter import DistutilsRefactoringTool - -_ORIGINAL = """\ -from distutils.core import setup - -setup(name='Foo') -""" - -_WANTED = """\ -from distutils2.core import setup - -setup(name='Foo') -""" - def _read_file(path): # yes, distutils2 is 2.4 compatible, so, no with... f = open(path) @@ -29,7 +17,7 @@ class ConverterTestCase(unittest2.TestCase): - + @unittest2.skipUnless(not sys.version < '2.6', 'Needs Python >=2.6') def test_conversions(self): # for all XX_before in the conversions/ dir # we run the refactoring tool -- Repository URL: http://hg.python.org/distutils2 From python-checkins at python.org Fri May 14 22:36:12 2010 From: python-checkins at python.org (tarek.ziade) Date: Fri, 14 May 2010 22:36:12 +0200 Subject: [Python-checkins] distutils2: removing the text_file module. TextFile is very complex where one or two Message-ID: tarek.ziade pushed d35f803e3b3b to distutils2: http://hg.python.org/distutils2/rev/d35f803e3b3b changeset: 138:d35f803e3b3b user: Tarek Ziade date: Wed May 12 16:36:27 2010 +0200 summary: removing the text_file module. TextFile is very complex where one or two regexps can do the job for our unique use case (in the sdist command) files: src/distutils2/command/sdist.py, src/distutils2/tests/test_text_file.py, src/distutils2/text_file.py diff --git a/src/distutils2/command/sdist.py b/src/distutils2/command/sdist.py --- a/src/distutils2/command/sdist.py +++ b/src/distutils2/command/sdist.py @@ -10,6 +10,8 @@ from glob import glob from warnings import warn from shutil import rmtree +import re + try: from shutil import get_archive_formats except ImportError: @@ -17,7 +19,6 @@ from distutils2.core import Command from distutils2 import util -from distutils2.text_file import TextFile from distutils2.errors import (DistutilsPlatformError, DistutilsOptionError, DistutilsTemplateError) from distutils2.filelist import FileList @@ -36,6 +37,10 @@ FancyGetopt(formats).print_help( "List of available source distribution formats:") +# a \ followed by some spaces + EOL +_COLLAPSE_PATTERN = re.compile('\\\w\n', re.M) +_COMMENTED_LINE = re.compile('^#.*\n$|^\w*\n$', re.M) + class sdist(Command): description = "create a source distribution (tarball, zip file, etc.)" @@ -337,19 +342,21 @@ 'self.filelist', which updates itself accordingly. """ log.info("reading manifest template '%s'", self.template) - template = TextFile(self.template, - strip_comments=1, - skip_blanks=1, - join_lines=1, - lstrip_ws=1, - rstrip_ws=1, - collapse_join=1) - while 1: - line = template.readline() - if line is None: # end of file - break + f = open(self.template) + try: + content = f.read() + # first, let's unwrap collapsed lines + content = _COLLAPSE_PATTERN.replace(content, '') + # next, let's remove commented lines and empty lines + content = _COMMENTED_LINE.replace(content, '') + # now we have our cleaned up lines + lines = [line.strip() for line in content.split('\n')] + finally: + f.close() + + for line in lines: try: self.filelist.process_template_line(line) except DistutilsTemplateError, msg: diff --git a/src/distutils2/tests/test_text_file.py b/src/distutils2/tests/test_text_file.py deleted file mode 100644 --- a/src/distutils2/tests/test_text_file.py +++ /dev/null @@ -1,88 +0,0 @@ -"""Tests for distutils.text_file.""" -import os -import unittest2 -from distutils2.text_file import TextFile -from distutils2.tests import support - -TEST_DATA = """# test file - -line 3 \\ -# intervening comment - continues on next line -""" - -class TextFileTestCase(support.TempdirManager, unittest2.TestCase): - - def test_class(self): - # old tests moved from text_file.__main__ - # so they are really called by the buildbots - - # result 1: no fancy options - result1 = ['# test file\n', '\n', 'line 3 \\\n', - '# intervening comment\n', - ' continues on next line\n'] - - # result 2: just strip comments - result2 = ["\n", - "line 3 \\\n", - " continues on next line\n"] - - # result 3: just strip blank lines - result3 = ["# test file\n", - "line 3 \\\n", - "# intervening comment\n", - " continues on next line\n"] - - # result 4: default, strip comments, blank lines, - # and trailing whitespace - result4 = ["line 3 \\", - " continues on next line"] - - # result 5: strip comments and blanks, plus join lines (but don't - # "collapse" joined lines - result5 = ["line 3 continues on next line"] - - # result 6: strip comments and blanks, plus join lines (and - # "collapse" joined lines - result6 = ["line 3 continues on next line"] - - def test_input(count, description, file, expected_result): - result = file.readlines() - self.assertEquals(result, expected_result) - - tmpdir = self.mkdtemp() - filename = os.path.join(tmpdir, "test.txt") - out_file = open(filename, "w") - try: - out_file.write(TEST_DATA) - finally: - out_file.close() - - in_file = TextFile (filename, strip_comments=0, skip_blanks=0, - lstrip_ws=0, rstrip_ws=0) - test_input (1, "no processing", in_file, result1) - - in_file = TextFile (filename, strip_comments=1, skip_blanks=0, - lstrip_ws=0, rstrip_ws=0) - test_input (2, "strip comments", in_file, result2) - - in_file = TextFile (filename, strip_comments=0, skip_blanks=1, - lstrip_ws=0, rstrip_ws=0) - test_input (3, "strip blanks", in_file, result3) - - in_file = TextFile (filename) - test_input (4, "default processing", in_file, result4) - - in_file = TextFile (filename, strip_comments=1, skip_blanks=1, - join_lines=1, rstrip_ws=1) - test_input (5, "join lines without collapsing", in_file, result5) - - in_file = TextFile (filename, strip_comments=1, skip_blanks=1, - join_lines=1, rstrip_ws=1, collapse_join=1) - test_input (6, "join lines with collapsing", in_file, result6) - -def test_suite(): - return unittest2.makeSuite(TextFileTestCase) - -if __name__ == "__main__": - unittest2.main(defaultTest="test_suite") diff --git a/src/distutils2/text_file.py b/src/distutils2/text_file.py deleted file mode 100644 --- a/src/distutils2/text_file.py +++ /dev/null @@ -1,304 +0,0 @@ -"""text_file - -provides the TextFile class, which gives an interface to text files -that (optionally) takes care of stripping comments, ignoring blank -lines, and joining lines with backslashes.""" - -__revision__ = "$Id: text_file.py 76956 2009-12-21 01:22:46Z tarek.ziade $" - -import sys - - -class TextFile: - - """Provides a file-like object that takes care of all the things you - commonly want to do when processing a text file that has some - line-by-line syntax: strip comments (as long as "#" is your - comment character), skip blank lines, join adjacent lines by - escaping the newline (ie. backslash at end of line), strip - leading and/or trailing whitespace. All of these are optional - and independently controllable. - - Provides a 'warn()' method so you can generate warning messages that - report physical line number, even if the logical line in question - spans multiple physical lines. Also provides 'unreadline()' for - implementing line-at-a-time lookahead. - - Constructor is called as: - - TextFile (filename=None, file=None, **options) - - It bombs (RuntimeError) if both 'filename' and 'file' are None; - 'filename' should be a string, and 'file' a file object (or - something that provides 'readline()' and 'close()' methods). It is - recommended that you supply at least 'filename', so that TextFile - can include it in warning messages. If 'file' is not supplied, - TextFile creates its own using the 'open()' builtin. - - The options are all boolean, and affect the value returned by - 'readline()': - strip_comments [default: true] - strip from "#" to end-of-line, as well as any whitespace - leading up to the "#" -- unless it is escaped by a backslash - lstrip_ws [default: false] - strip leading whitespace from each line before returning it - rstrip_ws [default: true] - strip trailing whitespace (including line terminator!) from - each line before returning it - skip_blanks [default: true} - skip lines that are empty *after* stripping comments and - whitespace. (If both lstrip_ws and rstrip_ws are false, - then some lines may consist of solely whitespace: these will - *not* be skipped, even if 'skip_blanks' is true.) - join_lines [default: false] - if a backslash is the last non-newline character on a line - after stripping comments and whitespace, join the following line - to it to form one "logical line"; if N consecutive lines end - with a backslash, then N+1 physical lines will be joined to - form one logical line. - collapse_join [default: false] - strip leading whitespace from lines that are joined to their - predecessor; only matters if (join_lines and not lstrip_ws) - - Note that since 'rstrip_ws' can strip the trailing newline, the - semantics of 'readline()' must differ from those of the builtin file - object's 'readline()' method! In particular, 'readline()' returns - None for end-of-file: an empty string might just be a blank line (or - an all-whitespace line), if 'rstrip_ws' is true but 'skip_blanks' is - not.""" - - default_options = { 'strip_comments': 1, - 'skip_blanks': 1, - 'lstrip_ws': 0, - 'rstrip_ws': 1, - 'join_lines': 0, - 'collapse_join': 0, - } - - def __init__ (self, filename=None, file=None, **options): - """Construct a new TextFile object. At least one of 'filename' - (a string) and 'file' (a file-like object) must be supplied. - They keyword argument options are described above and affect - the values returned by 'readline()'.""" - - if filename is None and file is None: - raise RuntimeError, \ - "you must supply either or both of 'filename' and 'file'" - - # set values for all options -- either from client option hash - # or fallback to default_options - for opt in self.default_options.keys(): - if opt in options: - setattr (self, opt, options[opt]) - - else: - setattr (self, opt, self.default_options[opt]) - - # sanity check client option hash - for opt in options.keys(): - if opt not in self.default_options: - raise KeyError, "invalid TextFile option '%s'" % opt - - if file is None: - self.open (filename) - else: - self.filename = filename - self.file = file - self.current_line = 0 # assuming that file is at BOF! - - # 'linebuf' is a stack of lines that will be emptied before we - # actually read from the file; it's only populated by an - # 'unreadline()' operation - self.linebuf = [] - - - def open (self, filename): - """Open a new file named 'filename'. This overrides both the - 'filename' and 'file' arguments to the constructor.""" - - self.filename = filename - self.file = open (self.filename, 'r') - self.current_line = 0 - - - def close (self): - """Close the current file and forget everything we know about it - (filename, current line number).""" - - self.file.close () - self.file = None - self.filename = None - self.current_line = None - - - def gen_error (self, msg, line=None): - outmsg = [] - if line is None: - line = self.current_line - outmsg.append(self.filename + ", ") - if isinstance(line, (list, tuple)): - outmsg.append("lines %d-%d: " % tuple (line)) - else: - outmsg.append("line %d: " % line) - outmsg.append(str(msg)) - return ''.join(outmsg) - - - def error (self, msg, line=None): - raise ValueError, "error: " + self.gen_error(msg, line) - - def warn (self, msg, line=None): - """Print (to stderr) a warning message tied to the current logical - line in the current file. If the current logical line in the - file spans multiple physical lines, the warning refers to the - whole range, eg. "lines 3-5". If 'line' supplied, it overrides - the current line number; it may be a list or tuple to indicate a - range of physical lines, or an integer for a single physical - line.""" - sys.stderr.write("warning: " + self.gen_error(msg, line) + "\n") - - - def readline (self): - """Read and return a single logical line from the current file (or - from an internal buffer if lines have previously been "unread" - with 'unreadline()'). If the 'join_lines' option is true, this - may involve reading multiple physical lines concatenated into a - single string. Updates the current line number, so calling - 'warn()' after 'readline()' emits a warning about the physical - line(s) just read. Returns None on end-of-file, since the empty - string can occur if 'rstrip_ws' is true but 'strip_blanks' is - not.""" - - # If any "unread" lines waiting in 'linebuf', return the top - # one. (We don't actually buffer read-ahead data -- lines only - # get put in 'linebuf' if the client explicitly does an - # 'unreadline()'. - if self.linebuf: - line = self.linebuf[-1] - del self.linebuf[-1] - return line - - buildup_line = '' - - while 1: - # read the line, make it None if EOF - line = self.file.readline() - if line == '': line = None - - if self.strip_comments and line: - - # Look for the first "#" in the line. If none, never - # mind. If we find one and it's the first character, or - # is not preceded by "\", then it starts a comment -- - # strip the comment, strip whitespace before it, and - # carry on. Otherwise, it's just an escaped "#", so - # unescape it (and any other escaped "#"'s that might be - # lurking in there) and otherwise leave the line alone. - - pos = line.find("#") - if pos == -1: # no "#" -- no comments - pass - - # It's definitely a comment -- either "#" is the first - # character, or it's elsewhere and unescaped. - elif pos == 0 or line[pos-1] != "\\": - # Have to preserve the trailing newline, because it's - # the job of a later step (rstrip_ws) to remove it -- - # and if rstrip_ws is false, we'd better preserve it! - # (NB. this means that if the final line is all comment - # and has no trailing newline, we will think that it's - # EOF; I think that's OK.) - eol = (line[-1] == '\n') and '\n' or '' - line = line[0:pos] + eol - - # If all that's left is whitespace, then skip line - # *now*, before we try to join it to 'buildup_line' -- - # that way constructs like - # hello \\ - # # comment that should be ignored - # there - # result in "hello there". - if line.strip() == "": - continue - - else: # it's an escaped "#" - line = line.replace("\\#", "#") - - - # did previous line end with a backslash? then accumulate - if self.join_lines and buildup_line: - # oops: end of file - if line is None: - self.warn ("continuation line immediately precedes " - "end-of-file") - return buildup_line - - if self.collapse_join: - line = line.lstrip() - line = buildup_line + line - - # careful: pay attention to line number when incrementing it - if isinstance(self.current_line, list): - self.current_line[1] = self.current_line[1] + 1 - else: - self.current_line = [self.current_line, - self.current_line+1] - # just an ordinary line, read it as usual - else: - if line is None: # eof - return None - - # still have to be careful about incrementing the line number! - if isinstance(self.current_line, list): - self.current_line = self.current_line[1] + 1 - else: - self.current_line = self.current_line + 1 - - - # strip whitespace however the client wants (leading and - # trailing, or one or the other, or neither) - if self.lstrip_ws and self.rstrip_ws: - line = line.strip() - elif self.lstrip_ws: - line = line.lstrip() - elif self.rstrip_ws: - line = line.rstrip() - - # blank line (whether we rstrip'ed or not)? skip to next line - # if appropriate - if (line == '' or line == '\n') and self.skip_blanks: - continue - - if self.join_lines: - if line[-1] == '\\': - buildup_line = line[:-1] - continue - - if line[-2:] == '\\\n': - buildup_line = line[0:-2] + '\n' - continue - - # well, I guess there's some actual content there: return it - return line - - # readline () - - - def readlines (self): - """Read and return the list of all logical lines remaining in the - current file.""" - - lines = [] - while 1: - line = self.readline() - if line is None: - return lines - lines.append (line) - - - def unreadline (self, line): - """Push 'line' (a string) onto an internal buffer that will be - checked by future 'readline()' calls. Handy for implementing - a parser with line-at-a-time lookahead.""" - - self.linebuf.append (line) -- Repository URL: http://hg.python.org/distutils2 From python-checkins at python.org Fri May 14 22:36:12 2010 From: python-checkins at python.org (tarek.ziade) Date: Fri, 14 May 2010 22:36:12 +0200 Subject: [Python-checkins] distutils2: fancy output Message-ID: tarek.ziade pushed 33bd9af05048 to distutils2: http://hg.python.org/distutils2/rev/33bd9af05048 changeset: 143:33bd9af05048 user: Tarek Ziade date: Wed May 12 17:42:42 2010 +0200 summary: fancy output files: src/tests.sh diff --git a/src/tests.sh b/src/tests.sh --- a/src/tests.sh +++ b/src/tests.sh @@ -1,5 +1,12 @@ #!/bin/sh +echo Testing with Python 2.4.... python2.4 runtests.py -q + +echo +echo Testing with Python 2.5.... python2.5 runtests.py -q + +echo +echo Testing with Python 2.6.... python2.6 runtests.py -q -- Repository URL: http://hg.python.org/distutils2 From python-checkins at python.org Fri May 14 22:36:12 2010 From: python-checkins at python.org (tarek.ziade) Date: Fri, 14 May 2010 22:36:12 +0200 Subject: [Python-checkins] distutils2: added a first version of the fixer that renames setup() options. Message-ID: tarek.ziade pushed 16f2b107e867 to distutils2: http://hg.python.org/distutils2/rev/16f2b107e867 changeset: 137:16f2b107e867 user: Tarek Ziade date: Wed May 12 15:38:43 2010 +0200 summary: added a first version of the fixer that renames setup() options. files: src/distutils2/converter/fixers/fix_setup_options.py, src/distutils2/converter/refactor.py, src/distutils2/tests/conversions/02_after.py, src/distutils2/tests/conversions/02_before.py diff --git a/src/distutils2/converter/fixers/fix_setup_options.py b/src/distutils2/converter/fixers/fix_setup_options.py new file mode 100644 --- /dev/null +++ b/src/distutils2/converter/fixers/fix_setup_options.py @@ -0,0 +1,49 @@ +"""Fixer for setup() options. + +All distutils or setuptools options are translated +into PEP 345-style options. +""" + +# Local imports +from lib2to3 import pytree +from lib2to3.pgen2 import token +from lib2to3 import fixer_base +from lib2to3.fixer_util import Assign, Name, Newline, Number, Subscript, syms + +# XXX where is that defined ? +_ARGLIST = 259 +_ARG = 260 + +# name mapping : we want to convert +# all old-style options to distutils2 style +_OLD_NAMES = {'url': 'home_page', + 'long_description': 'description', + 'description': 'summary'} + +class FixSetupOptions(fixer_base.BaseFix): + + # XXX need to find something better here : + # identify a setup call, whatever alias is used + PATTERN = """ + power< name='setup' trailer< '(' [any] ')' > any* > + """ + + def _fix_name(self, node): + for child in node.children: + if child.type != token.NAME: + self._fix_name(child) + else: + # let's see if it's a left operator + sibling = child.get_next_sibling() + if sibling is None or sibling.type != token.EQUAL: + # nope + return + if child.value in _OLD_NAMES: + child.value = _OLD_NAMES[child.value] + child.changed() + + def transform(self, node, results): + trailer = node.children[1] + self._fix_name(trailer) + return node + diff --git a/src/distutils2/converter/refactor.py b/src/distutils2/converter/refactor.py --- a/src/distutils2/converter/refactor.py +++ b/src/distutils2/converter/refactor.py @@ -3,15 +3,26 @@ Provides DistutilsRefactoringTool, a class that register fixers used to refactor distutils or setuptools packages into distutils2 ones. """ -from lib2to3.refactor import RefactoringTool +try: + from lib2to3.refactor import RefactoringTool + _LIB2TO3 = True +except ImportError: + # we need 2.6 at least to run this + _LIB2TO3 = False -_DISTUTILS_FIXERS = ['distutils2.converter.fixers.fix_imports'] +_DISTUTILS_FIXERS = ['distutils2.converter.fixers.fix_imports', + 'distutils2.converter.fixers.fix_setup_options'] -class DistutilsRefactoringTool(RefactoringTool): +if _LIB2TO3: + class DistutilsRefactoringTool(RefactoringTool): - def __init__(self, fixer_names=_DISTUTILS_FIXERS, options=None, - explicit=None): + def __init__(self, fixer_names=_DISTUTILS_FIXERS, options=None, + explicit=None): - super(DistutilsRefactoringTool, self).__init__(fixer_names, options, - explicit) + super(DistutilsRefactoringTool, self).__init__(fixer_names, options, + explicit) +else: + class DistutilsRefactoringTool(object): + def __init__(self, *args, **kw): + raise NotImplementedError('Not available if run from Python < 2.6') diff --git a/src/distutils2/tests/conversions/02_after.py b/src/distutils2/tests/conversions/02_after.py new file mode 100644 --- /dev/null +++ b/src/distutils2/tests/conversions/02_after.py @@ -0,0 +1,46 @@ +# -*- encoding: utf8 -*- +import sys +import os +from distutils2.core import setup, Extension +from distutils2.errors import CCompilerError, DistutilsError, CompileError +from distutils2.command.build_ext import build_ext as distutils_build_ext + +VERSION = "0.1" + +class build_ext(distutils_build_ext): + + def build_extension(self, ext): + try: + return distutils_build_ext.build_extension(self, ext) + except (CCompilerError, DistutilsError, CompileError), e: + pass + +def _get_ext_modules(): + levenshtein = Extension('_levenshtein', + sources=[os.path.join('texttools', + '_levenshtein.c')]) + return [levenshtein] + +with open('README.txt') as f: + LONG_DESCRIPTION = f.read() + +setup(name="TextTools", version=VERSION, author="Tarek Ziade", + author_email="tarek at ziade.org", + home_page="http://bitbucket.org/tarek/texttools", + summary="Text manipulation utilities", + description=LONG_DESCRIPTION, + keywords="text,guess,levenshtein", + classifiers=[ + 'Development Status :: 4 - Beta', + 'Intended Audience :: Developers', + 'License :: OSI Approved :: Python Software Foundation License' + ], + cmdclass={'build_ext': build_ext}, + packages=['texttools'], + package_dir={'texttools': 'texttools'}, + package_data={'texttools': [os.path.join('samples', '*.txt')]}, + scripts=[os.path.join('scripts', 'levenshtein.py'), + os.path.join('scripts', 'guesslang.py')], + ext_modules=_get_ext_modules() + ) + diff --git a/src/distutils2/tests/conversions/02_before.py b/src/distutils2/tests/conversions/02_before.py new file mode 100644 --- /dev/null +++ b/src/distutils2/tests/conversions/02_before.py @@ -0,0 +1,46 @@ +# -*- encoding: utf8 -*- +import sys +import os +from distutils.core import setup, Extension +from distutils.errors import CCompilerError, DistutilsError, CompileError +from distutils.command.build_ext import build_ext as distutils_build_ext + +VERSION = "0.1" + +class build_ext(distutils_build_ext): + + def build_extension(self, ext): + try: + return distutils_build_ext.build_extension(self, ext) + except (CCompilerError, DistutilsError, CompileError), e: + pass + +def _get_ext_modules(): + levenshtein = Extension('_levenshtein', + sources=[os.path.join('texttools', + '_levenshtein.c')]) + return [levenshtein] + +with open('README.txt') as f: + LONG_DESCRIPTION = f.read() + +setup(name="TextTools", version=VERSION, author="Tarek Ziade", + author_email="tarek at ziade.org", + url="http://bitbucket.org/tarek/texttools", + description="Text manipulation utilities", + long_description=LONG_DESCRIPTION, + keywords="text,guess,levenshtein", + classifiers=[ + 'Development Status :: 4 - Beta', + 'Intended Audience :: Developers', + 'License :: OSI Approved :: Python Software Foundation License' + ], + cmdclass={'build_ext': build_ext}, + packages=['texttools'], + package_dir={'texttools': 'texttools'}, + package_data={'texttools': [os.path.join('samples', '*.txt')]}, + scripts=[os.path.join('scripts', 'levenshtein.py'), + os.path.join('scripts', 'guesslang.py')], + ext_modules=_get_ext_modules() + ) + -- Repository URL: http://hg.python.org/distutils2 From python-checkins at python.org Fri May 14 22:36:12 2010 From: python-checkins at python.org (tarek.ziade) Date: Fri, 14 May 2010 22:36:12 +0200 Subject: [Python-checkins] distutils2: fixed a typo Message-ID: tarek.ziade pushed d39ac9e6a8d1 to distutils2: http://hg.python.org/distutils2/rev/d39ac9e6a8d1 changeset: 141:d39ac9e6a8d1 user: Tarek Ziade date: Wed May 12 17:31:32 2010 +0200 summary: fixed a typo files: src/distutils2/manifest.py diff --git a/src/distutils2/manifest.py b/src/distutils2/manifest.py --- a/src/distutils2/manifest.py +++ b/src/distutils2/manifest.py @@ -15,8 +15,8 @@ import logging from distutils2.util import write_file, convert_path -from distutils2.exceptions import (DistutilsTemplateError, - DistutilsInternalError) +from distutils2.errors import (DistutilsTemplateError, + DistutilsInternalError) __all__ = ['Manifest'] -- Repository URL: http://hg.python.org/distutils2 From python-checkins at python.org Fri May 14 22:36:12 2010 From: python-checkins at python.org (tarek.ziade) Date: Fri, 14 May 2010 22:36:12 +0200 Subject: [Python-checkins] distutils2: added a global test script to make sure we test all python versions Message-ID: tarek.ziade pushed d3c63381653d to distutils2: http://hg.python.org/distutils2/rev/d3c63381653d changeset: 142:d3c63381653d user: Tarek Ziade date: Wed May 12 17:40:03 2010 +0200 summary: added a global test script to make sure we test all python versions files: src/distutils2/tests/__init__.py, src/runtests.py, src/tests.sh diff --git a/src/distutils2/tests/__init__.py b/src/distutils2/tests/__init__.py --- a/src/distutils2/tests/__init__.py +++ b/src/distutils2/tests/__init__.py @@ -20,8 +20,6 @@ here = os.path.dirname(__file__) -verbose = 1 - def test_suite(): suite = unittest2.TestSuite() @@ -48,10 +46,10 @@ return result -def _run_suite(suite): +def _run_suite(suite, verbose=1): """Run tests from a unittest2.TestSuite-derived class.""" if verbose: - runner = unittest2.TextTestRunner(sys.stdout, verbosity=2) + runner = unittest2.TextTestRunner(sys.stdout, verbose=2) else: runner = BasicTestRunner() @@ -66,7 +64,7 @@ raise TestFailed(err) -def run_unittest(*classes): +def run_unittest(classes, verbose=1): """Run tests from unittest2.TestCase-derived classes. Extracted from stdlib test.test_support and modified to support unittest2. @@ -83,7 +81,7 @@ suite.addTest(cls) else: suite.addTest(unittest2.makeSuite(cls)) - _run_suite(suite) + _run_suite(suite, verbose) def reap_children(): diff --git a/src/runtests.py b/src/runtests.py --- a/src/runtests.py +++ b/src/runtests.py @@ -2,17 +2,22 @@ The tests for distutils2 are defined in the distutils2.tests package; """ - +import sys import distutils2.tests from distutils2.tests import run_unittest, reap_children - from distutils2._backport.tests import test_suite as btest_suite def test_main(): - run_unittest(distutils2.tests.test_suite()) - run_unittest(btest_suite()) + # just supporting -q right now + # to enable detailed/quiet output + if len(sys.argv) > 1: + verbose = sys.argv[-1] != '-q' + else: + verbose = 1 + + run_unittest([distutils2.tests.test_suite(), btest_suite()], + verbose=verbose) reap_children() - if __name__ == "__main__": test_main() diff --git a/src/tests.sh b/src/tests.sh new file mode 100755 --- /dev/null +++ b/src/tests.sh @@ -0,0 +1,5 @@ +#!/bin/sh +python2.4 runtests.py -q +python2.5 runtests.py -q +python2.6 runtests.py -q + -- Repository URL: http://hg.python.org/distutils2 From python-checkins at python.org Fri May 14 22:36:12 2010 From: python-checkins at python.org (tarek.ziade) Date: Fri, 14 May 2010 22:36:12 +0200 Subject: [Python-checkins] distutils2: Refactored the Manifest reader/writer. Extracted partalliy the Message-ID: tarek.ziade pushed ab0989313509 to distutils2: http://hg.python.org/distutils2/rev/ab0989313509 changeset: 140:ab0989313509 user: Tarek Ziade date: Wed May 12 17:30:18 2010 +0200 summary: Refactored the Manifest reader/writer. Extracted partalliy the files: src/distutils2/command/sdist.py, src/distutils2/filelist.py, src/distutils2/manifest.py, src/distutils2/metadata.py, src/distutils2/tests/test_filelist.py, src/distutils2/tests/test_sdist.py diff --git a/src/distutils2/command/sdist.py b/src/distutils2/command/sdist.py --- a/src/distutils2/command/sdist.py +++ b/src/distutils2/command/sdist.py @@ -21,7 +21,7 @@ from distutils2 import util from distutils2.errors import (DistutilsPlatformError, DistutilsOptionError, DistutilsTemplateError) -from distutils2.filelist import FileList +from distutils2.manifest import Manifest from distutils2 import log from distutils2.util import convert_path, newer @@ -162,7 +162,7 @@ def run(self): # 'filelist' contains the list of files that will make up the # manifest - self.filelist = FileList() + self.filelist = Manifest() # Run sub commands for cmd_name in self.get_sub_commands(): @@ -224,6 +224,7 @@ # do nothing (unless --force or --manifest-only) # 4) no manifest, no template: generate w/ warning ("defaults only") + manifest_outofdate = (template_exists and (template_newer or setup_newer)) force_regen = self.force_manifest or self.manifest_only @@ -245,13 +246,11 @@ if self.prune: self.prune_file_list() - self.filelist.sort() - self.filelist.remove_duplicates() - self.write_manifest() + self.filelist.write(self.manifest) # Don't regenerate the manifest, just read it in. else: - self.read_manifest() + self.filelist.read(self.manifest) def add_defaults(self): """Add all the default files to self.filelist: @@ -335,34 +334,6 @@ build_scripts = self.get_finalized_command('build_scripts') self.filelist.extend(build_scripts.get_source_files()) - def read_template(self): - """Read and parse manifest template file named by self.template. - - (usually "MANIFEST.in") The parsing and processing is done by - 'self.filelist', which updates itself accordingly. - """ - log.info("reading manifest template '%s'", self.template) - - f = open(self.template) - try: - content = f.read() - # first, let's unwrap collapsed lines - content = _COLLAPSE_PATTERN.replace(content, '') - # next, let's remove commented lines and empty lines - content = _COMMENTED_LINE.replace(content, '') - - # now we have our cleaned up lines - lines = [line.strip() for line in content.split('\n')] - finally: - f.close() - - for line in lines: - try: - self.filelist.process_template_line(line) - except DistutilsTemplateError, msg: - self.warn("%s, line %d: %s" % (template.filename, - template.current_line, - msg)) def prune_file_list(self): """Prune off branches that might slip into the file list as created @@ -390,30 +361,6 @@ vcs_ptrn = r'(^|%s)(%s)(%s).*' % (seps, '|'.join(vcs_dirs), seps) self.filelist.exclude_pattern(vcs_ptrn, is_regex=1) - def write_manifest(self): - """Write the file list in 'self.filelist' (presumably as filled in - by 'add_defaults()' and 'read_template()') to the manifest file - named by 'self.manifest'. - """ - self.execute(util.write_file, - (self.manifest, self.filelist.files), - "writing manifest file '%s'" % self.manifest) - - def read_manifest(self): - """Read the manifest file (named by 'self.manifest') and use it to - fill in 'self.filelist', the list of files to include in the source - distribution. - """ - log.info("reading manifest file '%s'", self.manifest) - manifest = open(self.manifest) - while 1: - line = manifest.readline() - if line == '': # end of file - break - if line[-1] == '\n': - line = line[0:-1] - self.filelist.append(line) - manifest.close() def make_release_tree(self, base_dir, files): """Create the directory tree that will become the source diff --git a/src/distutils2/filelist.py b/src/distutils2/filelist.py deleted file mode 100644 --- a/src/distutils2/filelist.py +++ /dev/null @@ -1,306 +0,0 @@ -"""distutils.filelist - -Provides the FileList class, used for poking about the filesystem -and building lists of files. -""" - -__revision__ = "$Id: filelist.py 75196 2009-10-03 00:07:35Z tarek.ziade $" - -import os, re -import fnmatch -from distutils2.util import convert_path -from distutils2.errors import DistutilsTemplateError, DistutilsInternalError -from distutils2 import log - -class FileList(object): - """A list of files built by on exploring the filesystem and filtered by - applying various patterns to what we find there. - - Instance attributes: - dir - directory from which files will be taken -- only used if - 'allfiles' not supplied to constructor - files - list of filenames currently being built/filtered/manipulated - allfiles - complete list of files under consideration (ie. without any - filtering applied) - """ - - def __init__(self): - self.allfiles = None - self.files = [] - - def findall(self, dir=os.curdir): - self.allfiles = findall(dir) - - # -- List-like methods --------------------------------------------- - - def append(self, item): - self.files.append(item) - - def extend(self, items): - self.files.extend(items) - - def sort(self): - # Not a strict lexical sort! - sortable_files = map(os.path.split, self.files) - sortable_files.sort() - self.files = [] - for sort_tuple in sortable_files: - self.files.append(os.path.join(*sort_tuple)) - - - # -- Other miscellaneous utility methods --------------------------- - - def remove_duplicates(self): - # Assumes list has been sorted! - for i in range(len(self.files) - 1, 0, -1): - if self.files[i] == self.files[i - 1]: - del self.files[i] - - - # -- "File template" methods --------------------------------------- - - def _parse_template_line(self, line): - words = line.split() - action = words[0] - - patterns = dir = dir_pattern = None - - if action in ('include', 'exclude', - 'global-include', 'global-exclude'): - if len(words) < 2: - raise DistutilsTemplateError, \ - "'%s' expects ..." % action - - patterns = map(convert_path, words[1:]) - - elif action in ('recursive-include', 'recursive-exclude'): - if len(words) < 3: - raise DistutilsTemplateError, \ - "'%s' expects ..." % action - - dir = convert_path(words[1]) - patterns = map(convert_path, words[2:]) - - elif action in ('graft', 'prune'): - if len(words) != 2: - raise DistutilsTemplateError, \ - "'%s' expects a single " % action - - dir_pattern = convert_path(words[1]) - - else: - raise DistutilsTemplateError, "unknown action '%s'" % action - - return (action, patterns, dir, dir_pattern) - - def process_template_line(self, line): - # Parse the line: split it up, make sure the right number of words - # is there, and return the relevant words. 'action' is always - # defined: it's the first word of the line. Which of the other - # three are defined depends on the action; it'll be either - # patterns, (dir and patterns), or (dir_pattern). - action, patterns, dir, dir_pattern = self._parse_template_line(line) - - # OK, now we know that the action is valid and we have the - # right number of words on the line for that action -- so we - # can proceed with minimal error-checking. - if action == 'include': - for pattern in patterns: - if not self.include_pattern(pattern, anchor=1): - log.warn("warning: no files found matching '%s'", - pattern) - - elif action == 'exclude': - for pattern in patterns: - if not self.exclude_pattern(pattern, anchor=1): - log.warn(("warning: no previously-included files " - "found matching '%s'"), pattern) - - elif action == 'global-include': - for pattern in patterns: - if not self.include_pattern(pattern, anchor=0): - log.warn(("warning: no files found matching '%s' " + - "anywhere in distribution"), pattern) - - elif action == 'global-exclude': - for pattern in patterns: - if not self.exclude_pattern(pattern, anchor=0): - log.warn(("warning: no previously-included files matching " - "'%s' found anywhere in distribution"), - pattern) - - elif action == 'recursive-include': - for pattern in patterns: - if not self.include_pattern(pattern, prefix=dir): - log.warn(("warning: no files found matching '%s' " + - "under directory '%s'"), - pattern, dir) - - elif action == 'recursive-exclude': - for pattern in patterns: - if not self.exclude_pattern(pattern, prefix=dir): - log.warn(("warning: no previously-included files matching " - "'%s' found under directory '%s'"), - pattern, dir) - - elif action == 'graft': - if not self.include_pattern(None, prefix=dir_pattern): - log.warn("warning: no directories found matching '%s'", - dir_pattern) - - elif action == 'prune': - if not self.exclude_pattern(None, prefix=dir_pattern): - log.warn(("no previously-included directories found " + - "matching '%s'"), dir_pattern) - else: - raise DistutilsInternalError, \ - "this cannot happen: invalid action '%s'" % action - - # -- Filtering/selection methods ----------------------------------- - - def include_pattern(self, pattern, anchor=1, prefix=None, is_regex=0): - """Select strings (presumably filenames) from 'self.files' that - match 'pattern', a Unix-style wildcard (glob) pattern. - - Patterns are not quite the same as implemented by the 'fnmatch' - module: '*' and '?' match non-special characters, where "special" - is platform-dependent: slash on Unix; colon, slash, and backslash on - DOS/Windows; and colon on Mac OS. - - If 'anchor' is true (the default), then the pattern match is more - stringent: "*.py" will match "foo.py" but not "foo/bar.py". If - 'anchor' is false, both of these will match. - - If 'prefix' is supplied, then only filenames starting with 'prefix' - (itself a pattern) and ending with 'pattern', with anything in between - them, will match. 'anchor' is ignored in this case. - - If 'is_regex' is true, 'anchor' and 'prefix' are ignored, and - 'pattern' is assumed to be either a string containing a regex or a - regex object -- no translation is done, the regex is just compiled - and used as-is. - - Selected strings will be added to self.files. - - Return 1 if files are found. - """ - files_found = 0 - pattern_re = translate_pattern(pattern, anchor, prefix, is_regex) - # delayed loading of allfiles list - if self.allfiles is None: - self.findall() - - for name in self.allfiles: - if pattern_re.search(name): - self.files.append(name) - files_found = 1 - - return files_found - - - def exclude_pattern(self, pattern, anchor=1, prefix=None, is_regex=0): - """Remove strings (presumably filenames) from 'files' that match - 'pattern'. - - Other parameters are the same as for 'include_pattern()', above. - The list 'self.files' is modified in place. Return 1 if files are - found. - """ - files_found = 0 - pattern_re = translate_pattern(pattern, anchor, prefix, is_regex) - for i in range(len(self.files)-1, -1, -1): - if pattern_re.search(self.files[i]): - del self.files[i] - files_found = 1 - - return files_found - - -# ---------------------------------------------------------------------- -# Utility functions - -def findall(dir=os.curdir): - """Find all files under 'dir' and return the list of full filenames - (relative to 'dir'). - """ - from stat import ST_MODE, S_ISREG, S_ISDIR, S_ISLNK - - list = [] - stack = [dir] - pop = stack.pop - push = stack.append - - while stack: - dir = pop() - names = os.listdir(dir) - - for name in names: - if dir != os.curdir: # avoid the dreaded "./" syndrome - fullname = os.path.join(dir, name) - else: - fullname = name - - # Avoid excess stat calls -- just one will do, thank you! - stat = os.stat(fullname) - mode = stat[ST_MODE] - if S_ISREG(mode): - list.append(fullname) - elif S_ISDIR(mode) and not S_ISLNK(mode): - push(fullname) - - return list - - -def glob_to_re(pattern): - """Translate a shell-like glob pattern to a regular expression. - - Return a string containing the regex. Differs from - 'fnmatch.translate()' in that '*' does not match "special characters" - (which are platform-specific). - """ - pattern_re = fnmatch.translate(pattern) - - # '?' and '*' in the glob pattern become '.' and '.*' in the RE, which - # IMHO is wrong -- '?' and '*' aren't supposed to match slash in Unix, - # and by extension they shouldn't match such "special characters" under - # any OS. So change all non-escaped dots in the RE to match any - # character except the special characters. - # XXX currently the "special characters" are just slash -- i.e. this is - # Unix-only. - pattern_re = re.sub(r'((? ..." % action) + + patterns = map(convert_path, words[1:]) + + elif action in ('recursive-include', 'recursive-exclude'): + if len(words) < 3: + raise DistutilsTemplateError( + "'%s' expects ..." % action) + + dir = convert_path(words[1]) + patterns = map(convert_path, words[2:]) + + elif action in ('graft', 'prune'): + if len(words) != 2: + raise DistutilsTemplateError( + "'%s' expects a single " % action) + + dir_pattern = convert_path(words[1]) + + else: + raise DistutilsTemplateError("unknown action '%s'" % action) + + return action, patterns, dir, dir_pattern + + def _process_template_line(self, line): + # Parse the line: split it up, make sure the right number of words + # is there, and return the relevant words. 'action' is always + # defined: it's the first word of the line. Which of the other + # three are defined depends on the action; it'll be either + # patterns, (dir and patterns), or (dir_pattern). + action, patterns, dir, dir_pattern = self._parse_template_line(line) + + # OK, now we know that the action is valid and we have the + # right number of words on the line for that action -- so we + # can proceed with minimal error-checking. + if action == 'include': + for pattern in patterns: + if not self._include_pattern(pattern, anchor=1): + logging.warning("warning: no files found matching '%s'", + pattern) + + elif action == 'exclude': + for pattern in patterns: + if not self.exclude_pattern(pattern, anchor=1): + logging.warning(("warning: no previously-included files " + "found matching '%s'"), pattern) + + elif action == 'global-include': + for pattern in patterns: + if not self._include_pattern(pattern, anchor=0): + logging.warning(("warning: no files found matching '%s' " + + "anywhere in distribution"), pattern) + + elif action == 'global-exclude': + for pattern in patterns: + if not self.exclude_pattern(pattern, anchor=0): + logging.warning(("warning: no previously-included files " + "matching '%s' found anywhere in distribution"), + pattern) + + elif action == 'recursive-include': + for pattern in patterns: + if not self._include_pattern(pattern, prefix=dir): + logging.warning(("warning: no files found matching '%s' " + "under directory '%s'"), + pattern, dir) + + elif action == 'recursive-exclude': + for pattern in patterns: + if not self.exclude_pattern(pattern, prefix=dir): + logging.warning(("warning: no previously-included files " + "matching '%s' found under directory '%s'"), + pattern, dir) + + elif action == 'graft': + if not self._include_pattern(None, prefix=dir_pattern): + logging.warning("warning: no directories found matching '%s'", + dir_pattern) + + elif action == 'prune': + if not self.exclude_pattern(None, prefix=dir_pattern): + logging.warning(("no previously-included directories found " + + "matching '%s'"), dir_pattern) + else: + raise DistutilsInternalError( + "this cannot happen: invalid action '%s'" % action) + + def _include_pattern(self, pattern, anchor=1, prefix=None, is_regex=0): + """Select strings (presumably filenames) from 'self.files' that + match 'pattern', a Unix-style wildcard (glob) pattern. + + Patterns are not quite the same as implemented by the 'fnmatch' + module: '*' and '?' match non-special characters, where "special" + is platform-dependent: slash on Unix; colon, slash, and backslash on + DOS/Windows; and colon on Mac OS. + + If 'anchor' is true (the default), then the pattern match is more + stringent: "*.py" will match "foo.py" but not "foo/bar.py". If + 'anchor' is false, both of these will match. + + If 'prefix' is supplied, then only filenames starting with 'prefix' + (itself a pattern) and ending with 'pattern', with anything in between + them, will match. 'anchor' is ignored in this case. + + If 'is_regex' is true, 'anchor' and 'prefix' are ignored, and + 'pattern' is assumed to be either a string containing a regex or a + regex object -- no translation is done, the regex is just compiled + and used as-is. + + Selected strings will be added to self.files. + + Return 1 if files are found. + """ + files_found = 0 + pattern_re = _translate_pattern(pattern, anchor, prefix, is_regex) + + # delayed loading of allfiles list + if self.allfiles is None: + self.findall() + + for name in self.allfiles: + if pattern_re.search(name): + self.files.append(name) + files_found = 1 + + return files_found + + + +# +# Utility functions +# + +def _findall(dir=os.curdir): + """Find all files under 'dir' and return the list of full filenames + (relative to 'dir'). + """ + from stat import ST_MODE, S_ISREG, S_ISDIR, S_ISLNK + + list = [] + stack = [dir] + pop = stack.pop + push = stack.append + + while stack: + dir = pop() + names = os.listdir(dir) + + for name in names: + if dir != os.curdir: # avoid the dreaded "./" syndrome + fullname = os.path.join(dir, name) + else: + fullname = name + + # Avoid excess stat calls -- just one will do, thank you! + stat = os.stat(fullname) + mode = stat[ST_MODE] + if S_ISREG(mode): + list.append(fullname) + elif S_ISDIR(mode) and not S_ISLNK(mode): + push(fullname) + + return list + + + +def _glob_to_re(pattern): + """Translate a shell-like glob pattern to a regular expression. + + Return a string containing the regex. Differs from + 'fnmatch.translate()' in that '*' does not match "special characters" + (which are platform-specific). + """ + pattern_re = fnmatch.translate(pattern) + + # '?' and '*' in the glob pattern become '.' and '.*' in the RE, which + # IMHO is wrong -- '?' and '*' aren't supposed to match slash in Unix, + # and by extension they shouldn't match such "special characters" under + # any OS. So change all non-escaped dots in the RE to match any + # character except the special characters. + # XXX currently the "special characters" are just slash -- i.e. this is + # Unix-only. + pattern_re = re.sub(r'((? tarek.ziade pushed c7c0e2ee9376 to distutils2: http://hg.python.org/distutils2/rev/c7c0e2ee9376 changeset: 144:c7c0e2ee9376 user: Tarek Ziade date: Wed May 12 17:44:26 2010 +0200 summary: make sure unittest2 is present files: src/runtests.py diff --git a/src/runtests.py b/src/runtests.py --- a/src/runtests.py +++ b/src/runtests.py @@ -3,11 +3,11 @@ The tests for distutils2 are defined in the distutils2.tests package; """ import sys -import distutils2.tests -from distutils2.tests import run_unittest, reap_children -from distutils2._backport.tests import test_suite as btest_suite def test_main(): + import distutils2.tests + from distutils2.tests import run_unittest, reap_children + from distutils2._backport.tests import test_suite as btest_suite # just supporting -q right now # to enable detailed/quiet output if len(sys.argv) > 1: @@ -20,4 +20,10 @@ reap_children() if __name__ == "__main__": + try: + import unittest2 + except ImportError: + print('!!! You need to install unittest2') + sys.exit(1) + test_main() -- Repository URL: http://hg.python.org/distutils2 From python-checkins at python.org Fri May 14 22:36:12 2010 From: python-checkins at python.org (tarek.ziade) Date: Fri, 14 May 2010 22:36:12 +0200 Subject: [Python-checkins] distutils2: make sure we have a global, up-to-date distutils.tests.verbose flag Message-ID: tarek.ziade pushed fabe7c59979a to distutils2: http://hg.python.org/distutils2/rev/fabe7c59979a changeset: 145:fabe7c59979a user: Tarek Ziade date: Wed May 12 17:47:30 2010 +0200 summary: make sure we have a global, up-to-date distutils.tests.verbose flag files: src/distutils2/tests/__init__.py, src/runtests.py diff --git a/src/distutils2/tests/__init__.py b/src/distutils2/tests/__init__.py --- a/src/distutils2/tests/__init__.py +++ b/src/distutils2/tests/__init__.py @@ -20,6 +20,7 @@ here = os.path.dirname(__file__) +verbose = 1 def test_suite(): suite = unittest2.TestSuite() @@ -46,10 +47,12 @@ return result -def _run_suite(suite, verbose=1): +def _run_suite(suite, verbose_=1): """Run tests from a unittest2.TestSuite-derived class.""" - if verbose: - runner = unittest2.TextTestRunner(sys.stdout, verbose=2) + global verbose + verbose = verbose_ + if verbose_: + runner = unittest2.TextTestRunner(sys.stdout, verbosity=2) else: runner = BasicTestRunner() @@ -64,7 +67,7 @@ raise TestFailed(err) -def run_unittest(classes, verbose=1): +def run_unittest(classes, verbose_=1): """Run tests from unittest2.TestCase-derived classes. Extracted from stdlib test.test_support and modified to support unittest2. @@ -81,7 +84,7 @@ suite.addTest(cls) else: suite.addTest(unittest2.makeSuite(cls)) - _run_suite(suite, verbose) + _run_suite(suite, verbose_) def reap_children(): diff --git a/src/runtests.py b/src/runtests.py --- a/src/runtests.py +++ b/src/runtests.py @@ -16,7 +16,7 @@ verbose = 1 run_unittest([distutils2.tests.test_suite(), btest_suite()], - verbose=verbose) + verbose_=verbose) reap_children() if __name__ == "__main__": -- Repository URL: http://hg.python.org/distutils2 From python-checkins at python.org Fri May 14 22:36:12 2010 From: python-checkins at python.org (tarek.ziade) Date: Fri, 14 May 2010 22:36:12 +0200 Subject: [Python-checkins] distutils2: cleaned up Message-ID: tarek.ziade pushed aeb3bf5ad682 to distutils2: http://hg.python.org/distutils2/rev/aeb3bf5ad682 changeset: 151:aeb3bf5ad682 tag: tip user: Tarek Ziade date: Fri May 14 17:58:49 2010 +0200 summary: cleaned up files: src/distutils2/converter/fixers/fix_imports.py, src/distutils2/converter/fixers/fix_setup_options.py diff --git a/src/distutils2/converter/fixers/fix_imports.py b/src/distutils2/converter/fixers/fix_imports.py --- a/src/distutils2/converter/fixers/fix_imports.py +++ b/src/distutils2/converter/fixers/fix_imports.py @@ -3,7 +3,8 @@ Fixer for import statements in setup.py """ from lib2to3.fixer_base import BaseFix -from lib2to3.fixer_util import FromImport, syms, token +from lib2to3.fixer_util import syms + class FixImports(BaseFix): """Makes sure all import in setup.py are translated""" @@ -39,5 +40,3 @@ imp.changed() return node - - diff --git a/src/distutils2/converter/fixers/fix_setup_options.py b/src/distutils2/converter/fixers/fix_setup_options.py --- a/src/distutils2/converter/fixers/fix_setup_options.py +++ b/src/distutils2/converter/fixers/fix_setup_options.py @@ -3,15 +3,11 @@ All distutils or setuptools options are translated into PEP 345-style options. """ - -# Local imports from lib2to3.pytree import Leaf, Node from lib2to3.pgen2 import token -from lib2to3 import fixer_base -from lib2to3.fixer_util import Assign, Name, Newline, Number, Subscript, syms +from lib2to3.fixer_base import BaseFix # XXX where is that defined ? -_ARGLIST = 259 _ARG = 260 # name mapping : we want to convert @@ -20,10 +16,11 @@ 'long_description': 'description', 'description': 'summary', 'install_requires': 'requires_dist'} + _SEQUENCE_NAMES = ['requires_dist'] -class FixSetupOptions(fixer_base.BaseFix): +class FixSetupOptions(BaseFix): # XXX need to find something better here : # identify a setup call, whatever alias is used @@ -38,7 +35,7 @@ if len(nodes) > 0: nodes[0].prefix = u"" return Node(self.syms.trailer, - [lbrace]+ + [lbrace] + [node.clone() for node in nodes] + [Leaf(token.RBRACE, u"]")]) @@ -81,4 +78,3 @@ if changed: node.changed() return node - -- Repository URL: http://hg.python.org/distutils2 From python-checkins at python.org Fri May 14 22:36:12 2010 From: python-checkins at python.org (tarek.ziade) Date: Fri, 14 May 2010 22:36:12 +0200 Subject: [Python-checkins] distutils2: added swp extension Message-ID: tarek.ziade pushed 302bf07f4fe7 to distutils2: http://hg.python.org/distutils2/rev/302bf07f4fe7 changeset: 139:302bf07f4fe7 user: Tarek Ziade date: Wed May 12 17:20:39 2010 +0200 summary: added swp extension files: .hgignore diff --git a/.hgignore b/.hgignore --- a/.hgignore +++ b/.hgignore @@ -1,3 +1,5 @@ .*\.pyc$ .*\.pyo$ ^docs/build +.*\.swp$ + -- Repository URL: http://hg.python.org/distutils2 From python-checkins at python.org Fri May 14 22:36:12 2010 From: python-checkins at python.org (tarek.ziade) Date: Fri, 14 May 2010 22:36:12 +0200 Subject: [Python-checkins] distutils2: added a setuptools use case in the converter Message-ID: tarek.ziade pushed 53dfb044602c to distutils2: http://hg.python.org/distutils2/rev/53dfb044602c changeset: 146:53dfb044602c user: Tarek Ziade date: Fri May 14 16:46:00 2010 +0200 summary: added a setuptools use case in the converter files: src/distutils2/converter/fixers/fix_imports.py, src/distutils2/converter/fixers/fix_setup_options.py diff --git a/src/distutils2/converter/fixers/fix_imports.py b/src/distutils2/converter/fixers/fix_imports.py --- a/src/distutils2/converter/fixers/fix_imports.py +++ b/src/distutils2/converter/fixers/fix_imports.py @@ -27,3 +27,17 @@ imp.changed() return node + if imp.value == 'setuptools': + # catching "from setuptools import setup" + pattern = [] + next = imp.get_next_sibling() + while next is not None: + pattern.append(next.value) + next = next.get_next_sibling() + if pattern == ['import', 'setup']: + imp.value = 'distutils2.core' + imp.changed() + + return node + + diff --git a/src/distutils2/converter/fixers/fix_setup_options.py b/src/distutils2/converter/fixers/fix_setup_options.py --- a/src/distutils2/converter/fixers/fix_setup_options.py +++ b/src/distutils2/converter/fixers/fix_setup_options.py @@ -18,7 +18,14 @@ # all old-style options to distutils2 style _OLD_NAMES = {'url': 'home_page', 'long_description': 'description', - 'description': 'summary'} + 'description': 'summary', + 'install_requires': 'requires_dist'} + +# XXX see what we want to do for these.. +_INCOMPATIBLE_OPTIONS = ['entry_points', + 'include_package_data', + 'zip_safe', + 'namespace_packages'] class FixSetupOptions(fixer_base.BaseFix): @@ -28,22 +35,38 @@ power< name='setup' trailer< '(' [any] ')' > any* > """ - def _fix_name(self, node): - for child in node.children: - if child.type != token.NAME: - self._fix_name(child) - else: - # let's see if it's a left operator - sibling = child.get_next_sibling() - if sibling is None or sibling.type != token.EQUAL: - # nope - return - if child.value in _OLD_NAMES: - child.value = _OLD_NAMES[child.value] - child.changed() + def _fix_name(self, argument, remove_list): + name = argument.children[0] + sibling = name.get_next_sibling() + if sibling is None or sibling.type != token.EQUAL: + return False + + if name.value in _OLD_NAMES: + name.value = _OLD_NAMES[name.value] + elif name.value in _INCOMPATIBLE_OPTIONS: + # removing the args, and the comma + # behind + next_token = name.parent.get_next_sibling() + if next_token.type == 12: + remove_list.append(next_token) + remove_list.append(name.parent) + return True def transform(self, node, results): - trailer = node.children[1] - self._fix_name(trailer) + arglist = node.children[1].children[1] + remove_list = [] + changed = False + + for subnode in arglist.children: + if subnode.type != _ARG: + continue + if self._fix_name(subnode, remove_list) and not changed: + changed = True + + for subnode in remove_list: + subnode.remove() + + if changed: + node.changed() return node -- Repository URL: http://hg.python.org/distutils2 From python-checkins at python.org Fri May 14 22:36:12 2010 From: python-checkins at python.org (tarek.ziade) Date: Fri, 14 May 2010 22:36:12 +0200 Subject: [Python-checkins] distutils2: replacing a string by a list when possible Message-ID: tarek.ziade pushed 89afa1684670 to distutils2: http://hg.python.org/distutils2/rev/89afa1684670 changeset: 150:89afa1684670 user: Tarek Ziade date: Fri May 14 17:53:48 2010 +0200 summary: replacing a string by a list when possible files: src/distutils2/converter/fixers/fix_setup_options.py, src/distutils2/tests/conversions/03_after.py diff --git a/src/distutils2/converter/fixers/fix_setup_options.py b/src/distutils2/converter/fixers/fix_setup_options.py --- a/src/distutils2/converter/fixers/fix_setup_options.py +++ b/src/distutils2/converter/fixers/fix_setup_options.py @@ -5,7 +5,7 @@ """ # Local imports -from lib2to3 import pytree +from lib2to3.pytree import Leaf, Node from lib2to3.pgen2 import token from lib2to3 import fixer_base from lib2to3.fixer_util import Assign, Name, Newline, Number, Subscript, syms @@ -20,6 +20,7 @@ 'long_description': 'description', 'description': 'summary', 'install_requires': 'requires_dist'} +_SEQUENCE_NAMES = ['requires_dist'] class FixSetupOptions(fixer_base.BaseFix): @@ -30,14 +31,35 @@ power< name='setup' trailer< '(' [any] ')' > any* > """ + def _get_list(self, *nodes): + """A List node, filled""" + lbrace = Leaf(token.LBRACE, u"[") + lbrace.prefix = u" " + if len(nodes) > 0: + nodes[0].prefix = u"" + return Node(self.syms.trailer, + [lbrace]+ + [node.clone() for node in nodes] + + [Leaf(token.RBRACE, u"]")]) + def _fix_name(self, argument, remove_list): name = argument.children[0] - sibling = name.get_next_sibling() + next = name.get_next_sibling + sibling = next() if sibling is None or sibling.type != token.EQUAL: return False if name.value in _OLD_NAMES: name.value = _OLD_NAMES[name.value] + if name.value in _SEQUENCE_NAMES: + right_operand = next().get_next_sibling() + # replacing string -> list[string] + if right_operand.type == token.STRING: + # we want this to be a list now + new_node = self._get_list(right_operand) + right_operand.replace(new_node) + + return True return False diff --git a/src/distutils2/tests/conversions/03_after.py b/src/distutils2/tests/conversions/03_after.py --- a/src/distutils2/tests/conversions/03_after.py +++ b/src/distutils2/tests/conversions/03_after.py @@ -80,7 +80,7 @@ packages = ['zc', 'zc.buildout'], package_dir = {'': 'src'}, namespace_packages = ['zc'], - requires_dist = 'setuptools', + requires_dist = ['setuptools'], include_package_data = True, entry_points = entry_points, zip_safe=False, -- Repository URL: http://hg.python.org/distutils2 From python-checkins at python.org Fri May 14 22:36:12 2010 From: python-checkins at python.org (tarek.ziade) Date: Fri, 14 May 2010 22:36:12 +0200 Subject: [Python-checkins] distutils2: one more case Message-ID: tarek.ziade pushed 4235fd5e0d6b to distutils2: http://hg.python.org/distutils2/rev/4235fd5e0d6b changeset: 148:4235fd5e0d6b user: Tarek Ziade date: Fri May 14 16:51:22 2010 +0200 summary: one more case files: src/distutils2/tests/conversions/04_after.py, src/distutils2/tests/conversions/04_before.py diff --git a/src/distutils2/tests/conversions/04_after.py b/src/distutils2/tests/conversions/04_after.py new file mode 100644 --- /dev/null +++ b/src/distutils2/tests/conversions/04_after.py @@ -0,0 +1,69 @@ +import sys, os +try: + from distutils2.core import setup + kw = {'entry_points': + """[console_scripts]\nvirtualenv = virtualenv:main\n""", + 'zip_safe': False} +except ImportError: + from distutils2.core import setup + if sys.platform == 'win32': + print('Note: without Setuptools installed you will have to use "python -m virtualenv ENV"') + else: + kw = {'scripts': ['scripts/virtualenv']} +import re + +here = os.path.dirname(os.path.abspath(__file__)) + +## Figure out the version from virtualenv.py: +version_re = re.compile( + r'virtualenv_version = "(.*?)"') +fp = open(os.path.join(here, 'virtualenv.py')) +version = None +for line in fp: + match = version_re.search(line) + if match: + version = match.group(1) + break +else: + raise Exception("Cannot find version in virtualenv.py") +fp.close() + +## Get long_description from index.txt: +f = open(os.path.join(here, 'docs', 'index.txt')) +long_description = f.read().strip() +long_description = long_description.split('split here', 1)[1] +f.close() + +## A warning just for Ian (related to distribution): +try: + import getpass +except ImportError: + is_ianb = False +else: + is_ianb = getpass.getuser() == 'ianb' + +if is_ianb and 'register' in sys.argv: + if 'hg tip\n~~~~~~' in long_description: + print >> sys.stderr, ( + "WARNING: hg tip is in index.txt") + +setup(name='virtualenv', + version=version, + summary="Virtual Python Environment builder", + description=long_description, + classifiers=[ + 'Development Status :: 4 - Beta', + 'Intended Audience :: Developers', + 'License :: OSI Approved :: MIT License', + ], + keywords='setuptools deployment installation distutils', + author='Ian Bicking', + author_email='ianb at colorstudy.com', + home_page='http://virtualenv.openplans.org', + license='MIT', + use_2to3=True, + py_modules=['virtualenv'], + packages=['virtualenv_support'], + package_data={'virtualenv_support': ['*-py%s.egg' % sys.version[:3], '*.tar.gz']}, + **kw + ) diff --git a/src/distutils2/tests/conversions/04_before.py b/src/distutils2/tests/conversions/04_before.py new file mode 100644 --- /dev/null +++ b/src/distutils2/tests/conversions/04_before.py @@ -0,0 +1,69 @@ +import sys, os +try: + from setuptools import setup + kw = {'entry_points': + """[console_scripts]\nvirtualenv = virtualenv:main\n""", + 'zip_safe': False} +except ImportError: + from distutils.core import setup + if sys.platform == 'win32': + print('Note: without Setuptools installed you will have to use "python -m virtualenv ENV"') + else: + kw = {'scripts': ['scripts/virtualenv']} +import re + +here = os.path.dirname(os.path.abspath(__file__)) + +## Figure out the version from virtualenv.py: +version_re = re.compile( + r'virtualenv_version = "(.*?)"') +fp = open(os.path.join(here, 'virtualenv.py')) +version = None +for line in fp: + match = version_re.search(line) + if match: + version = match.group(1) + break +else: + raise Exception("Cannot find version in virtualenv.py") +fp.close() + +## Get long_description from index.txt: +f = open(os.path.join(here, 'docs', 'index.txt')) +long_description = f.read().strip() +long_description = long_description.split('split here', 1)[1] +f.close() + +## A warning just for Ian (related to distribution): +try: + import getpass +except ImportError: + is_ianb = False +else: + is_ianb = getpass.getuser() == 'ianb' + +if is_ianb and 'register' in sys.argv: + if 'hg tip\n~~~~~~' in long_description: + print >> sys.stderr, ( + "WARNING: hg tip is in index.txt") + +setup(name='virtualenv', + version=version, + description="Virtual Python Environment builder", + long_description=long_description, + classifiers=[ + 'Development Status :: 4 - Beta', + 'Intended Audience :: Developers', + 'License :: OSI Approved :: MIT License', + ], + keywords='setuptools deployment installation distutils', + author='Ian Bicking', + author_email='ianb at colorstudy.com', + url='http://virtualenv.openplans.org', + license='MIT', + use_2to3=True, + py_modules=['virtualenv'], + packages=['virtualenv_support'], + package_data={'virtualenv_support': ['*-py%s.egg' % sys.version[:3], '*.tar.gz']}, + **kw + ) -- Repository URL: http://hg.python.org/distutils2 From python-checkins at python.org Fri May 14 22:36:12 2010 From: python-checkins at python.org (tarek.ziade) Date: Fri, 14 May 2010 22:36:12 +0200 Subject: [Python-checkins] distutils2: on a second thought, let's keep the old arguments that are not renamed. Message-ID: tarek.ziade pushed 9fd27cd75533 to distutils2: http://hg.python.org/distutils2/rev/9fd27cd75533 changeset: 149:9fd27cd75533 user: Tarek Ziade date: Fri May 14 16:54:41 2010 +0200 summary: on a second thought, let's keep the old arguments that are not renamed. distutils2 will just display a warning files: src/distutils2/converter/fixers/fix_setup_options.py, src/distutils2/tests/conversions/03_after.py diff --git a/src/distutils2/converter/fixers/fix_setup_options.py b/src/distutils2/converter/fixers/fix_setup_options.py --- a/src/distutils2/converter/fixers/fix_setup_options.py +++ b/src/distutils2/converter/fixers/fix_setup_options.py @@ -21,11 +21,6 @@ 'description': 'summary', 'install_requires': 'requires_dist'} -# XXX see what we want to do for these.. -_INCOMPATIBLE_OPTIONS = ['entry_points', - 'include_package_data', - 'zip_safe', - 'namespace_packages'] class FixSetupOptions(fixer_base.BaseFix): @@ -43,14 +38,9 @@ if name.value in _OLD_NAMES: name.value = _OLD_NAMES[name.value] - elif name.value in _INCOMPATIBLE_OPTIONS: - # removing the args, and the comma - # behind - next_token = name.parent.get_next_sibling() - if next_token.type == 12: - remove_list.append(next_token) - remove_list.append(name.parent) - return True + return True + + return False def transform(self, node, results): arglist = node.children[1].children[1] diff --git a/src/distutils2/tests/conversions/03_after.py b/src/distutils2/tests/conversions/03_after.py --- a/src/distutils2/tests/conversions/03_after.py +++ b/src/distutils2/tests/conversions/03_after.py @@ -79,7 +79,11 @@ data_files = [('.', ['README.txt'])], packages = ['zc', 'zc.buildout'], package_dir = {'': 'src'}, + namespace_packages = ['zc'], requires_dist = 'setuptools', + include_package_data = True, + entry_points = entry_points, + zip_safe=False, classifiers = [ 'Intended Audience :: Developers', 'License :: OSI Approved :: Zope Public License', -- Repository URL: http://hg.python.org/distutils2 From python-checkins at python.org Fri May 14 22:36:12 2010 From: python-checkins at python.org (tarek.ziade) Date: Fri, 14 May 2010 22:36:12 +0200 Subject: [Python-checkins] distutils2: forgot to add the samples Message-ID: tarek.ziade pushed 83701e36e875 to distutils2: http://hg.python.org/distutils2/rev/83701e36e875 changeset: 147:83701e36e875 user: Tarek Ziade date: Fri May 14 16:49:20 2010 +0200 summary: forgot to add the samples files: src/distutils2/tests/conversions/03_after.py, src/distutils2/tests/conversions/03_before.py diff --git a/src/distutils2/tests/conversions/03_after.py b/src/distutils2/tests/conversions/03_after.py new file mode 100644 --- /dev/null +++ b/src/distutils2/tests/conversions/03_after.py @@ -0,0 +1,89 @@ +############################################################################## +# +# Copyright (c) 2006-2009 Zope Corporation and Contributors. +# All Rights Reserved. +# +# This software is subject to the provisions of the Zope Public License, +# Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution. +# THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED +# WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +# WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS +# FOR A PARTICULAR PURPOSE. +# +############################################################################## +name = "zc.buildout" +version = "1.5.0dev" + +import os +from distutils2.core import setup + +def read(*rnames): + return open(os.path.join(os.path.dirname(__file__), *rnames)).read() + +long_description=( + read('README.txt') + + '\n' + + 'Detailed Documentation\n' + '**********************\n' + + '\n' + + read('src', 'zc', 'buildout', 'buildout.txt') + + '\n' + + read('src', 'zc', 'buildout', 'unzip.txt') + + '\n' + + read('src', 'zc', 'buildout', 'repeatable.txt') + + '\n' + + read('src', 'zc', 'buildout', 'download.txt') + + '\n' + + read('src', 'zc', 'buildout', 'downloadcache.txt') + + '\n' + + read('src', 'zc', 'buildout', 'extends-cache.txt') + + '\n' + + read('src', 'zc', 'buildout', 'setup.txt') + + '\n' + + read('src', 'zc', 'buildout', 'update.txt') + + '\n' + + read('src', 'zc', 'buildout', 'debugging.txt') + + '\n' + + read('src', 'zc', 'buildout', 'testing.txt') + + '\n' + + read('src', 'zc', 'buildout', 'easy_install.txt') + + '\n' + + read('src', 'zc', 'buildout', 'distribute.txt') + + '\n' + + read('CHANGES.txt') + + '\n' + + 'Download\n' + '**********************\n' + ) + +entry_points = """ +[console_scripts] +buildout = %(name)s.buildout:main + +[zc.buildout] +debug = %(name)s.testrecipes:Debug + +""" % dict(name=name) + +setup( + name = name, + version = version, + author = "Jim Fulton", + author_email = "jim at zope.com", + summary = "System for managing development buildouts", + description=long_description, + license = "ZPL 2.1", + keywords = "development build", + home_page='http://buildout.org', + + data_files = [('.', ['README.txt'])], + packages = ['zc', 'zc.buildout'], + package_dir = {'': 'src'}, + requires_dist = 'setuptools', + classifiers = [ + 'Intended Audience :: Developers', + 'License :: OSI Approved :: Zope Public License', + 'Topic :: Software Development :: Build Tools', + 'Topic :: Software Development :: Libraries :: Python Modules', + ], + ) diff --git a/src/distutils2/tests/conversions/03_before.py b/src/distutils2/tests/conversions/03_before.py new file mode 100644 --- /dev/null +++ b/src/distutils2/tests/conversions/03_before.py @@ -0,0 +1,93 @@ +############################################################################## +# +# Copyright (c) 2006-2009 Zope Corporation and Contributors. +# All Rights Reserved. +# +# This software is subject to the provisions of the Zope Public License, +# Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution. +# THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED +# WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +# WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS +# FOR A PARTICULAR PURPOSE. +# +############################################################################## +name = "zc.buildout" +version = "1.5.0dev" + +import os +from setuptools import setup + +def read(*rnames): + return open(os.path.join(os.path.dirname(__file__), *rnames)).read() + +long_description=( + read('README.txt') + + '\n' + + 'Detailed Documentation\n' + '**********************\n' + + '\n' + + read('src', 'zc', 'buildout', 'buildout.txt') + + '\n' + + read('src', 'zc', 'buildout', 'unzip.txt') + + '\n' + + read('src', 'zc', 'buildout', 'repeatable.txt') + + '\n' + + read('src', 'zc', 'buildout', 'download.txt') + + '\n' + + read('src', 'zc', 'buildout', 'downloadcache.txt') + + '\n' + + read('src', 'zc', 'buildout', 'extends-cache.txt') + + '\n' + + read('src', 'zc', 'buildout', 'setup.txt') + + '\n' + + read('src', 'zc', 'buildout', 'update.txt') + + '\n' + + read('src', 'zc', 'buildout', 'debugging.txt') + + '\n' + + read('src', 'zc', 'buildout', 'testing.txt') + + '\n' + + read('src', 'zc', 'buildout', 'easy_install.txt') + + '\n' + + read('src', 'zc', 'buildout', 'distribute.txt') + + '\n' + + read('CHANGES.txt') + + '\n' + + 'Download\n' + '**********************\n' + ) + +entry_points = """ +[console_scripts] +buildout = %(name)s.buildout:main + +[zc.buildout] +debug = %(name)s.testrecipes:Debug + +""" % dict(name=name) + +setup( + name = name, + version = version, + author = "Jim Fulton", + author_email = "jim at zope.com", + description = "System for managing development buildouts", + long_description=long_description, + license = "ZPL 2.1", + keywords = "development build", + url='http://buildout.org', + + data_files = [('.', ['README.txt'])], + packages = ['zc', 'zc.buildout'], + package_dir = {'': 'src'}, + namespace_packages = ['zc'], + install_requires = 'setuptools', + include_package_data = True, + entry_points = entry_points, + zip_safe=False, + classifiers = [ + 'Intended Audience :: Developers', + 'License :: OSI Approved :: Zope Public License', + 'Topic :: Software Development :: Build Tools', + 'Topic :: Software Development :: Libraries :: Python Modules', + ], + ) -- Repository URL: http://hg.python.org/distutils2 From python-checkins at python.org Fri May 14 22:49:36 2010 From: python-checkins at python.org (jeffrey.yasskin) Date: Fri, 14 May 2010 22:49:36 +0200 (CEST) Subject: [Python-checkins] r81176 - in python/branches/py3k-jit: Makefile.pre.in Unittests/pytest_main.cc Message-ID: <20100514204936.D0184EEB43@mail.python.org> Author: jeffrey.yasskin Date: Fri May 14 22:49:36 2010 New Revision: 81176 Log: Fix `make ctest` under 64-bit valgrind. We were hacking the conversion from char* to wchar_t*, and we had ssize_t-cleanliness wrong. Modified: python/branches/py3k-jit/Makefile.pre.in python/branches/py3k-jit/Unittests/pytest_main.cc Modified: python/branches/py3k-jit/Makefile.pre.in ============================================================================== --- python/branches/py3k-jit/Makefile.pre.in (original) +++ python/branches/py3k-jit/Makefile.pre.in Fri May 14 22:49:36 2010 @@ -767,7 +767,8 @@ # gcc's TR1 header depends on RTTI, so force googletest to use # its own tuple implementation. AllUnitTests: $(UNITTEST_SRCS) $(srcdir)/Unittests/*.h build_all python-config - -$(CXX) $(CPPFLAGS) -I$(srcdir)/Unittests/googletest/include -o $@ \ + -$(CXX) $(CPPFLAGS) -DPY_SSIZE_T_CLEAN \ + -I$(srcdir)/Unittests/googletest/include -o $@ \ $(UNITTEST_SRCS) -L. $(LDFLAGS) \ -DGTEST_HAS_RTTI=0 -DGTEST_HAS_TR1_TUPLE=0 \ `$(RUNSHARED) ./$(BUILDPYTHON) ./python-config --cflags --ldflags` Modified: python/branches/py3k-jit/Unittests/pytest_main.cc ============================================================================== --- python/branches/py3k-jit/Unittests/pytest_main.cc (original) +++ python/branches/py3k-jit/Unittests/pytest_main.cc Fri May 14 22:49:36 2010 @@ -30,6 +30,7 @@ // Modified for Python to pass the name of this program. #include +#include #include @@ -38,8 +39,11 @@ int main(int argc, char **argv) { std::cout << "Running main() from gtest_main.cc\n"; - Py_SetProgramName((wchar_t *)argv[0]); + wchar_t *argv0_copy = _Py_char2wchar(argv[0]); + Py_SetProgramName(argv0_copy); testing::InitGoogleTest(&argc, argv); - return RUN_ALL_TESTS(); + int result = RUN_ALL_TESTS(); + PyMem_Free(argv0_copy); + return result; } From python-checkins at python.org Fri May 14 22:51:58 2010 From: python-checkins at python.org (jeffrey.yasskin) Date: Fri, 14 May 2010 22:51:58 +0200 (CEST) Subject: [Python-checkins] r81177 - python/branches/py3k-jit/Unittests/pytest_main.cc Message-ID: <20100514205158.941CBE794@mail.python.org> Author: jeffrey.yasskin Date: Fri May 14 22:51:58 2010 New Revision: 81177 Log: Oops, missed that Collin had comments. Modified: python/branches/py3k-jit/Unittests/pytest_main.cc Modified: python/branches/py3k-jit/Unittests/pytest_main.cc ============================================================================== --- python/branches/py3k-jit/Unittests/pytest_main.cc (original) +++ python/branches/py3k-jit/Unittests/pytest_main.cc Fri May 14 22:51:58 2010 @@ -27,17 +27,16 @@ // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -// Modified for Python to pass the name of this program. +// Modified from gtest_main for Python to pass the name of this program. #include -#include #include #include "Python.h" int main(int argc, char **argv) { - std::cout << "Running main() from gtest_main.cc\n"; + std::cout << "Running main() from pytest_main.cc\n"; wchar_t *argv0_copy = _Py_char2wchar(argv[0]); Py_SetProgramName(argv0_copy); From python-checkins at python.org Fri May 14 23:40:31 2010 From: python-checkins at python.org (collin.winter) Date: Fri, 14 May 2010 23:40:31 +0200 (CEST) Subject: [Python-checkins] r81178 - in python/branches/py3k-jit: Modules/_testcapimodule.c Unittests/GetArgsTest.cc Message-ID: <20100514214031.62D34EE9ED@mail.python.org> Author: collin.winter Date: Fri May 14 23:40:31 2010 New Revision: 81178 Log: Revert r79815. Modified: python/branches/py3k-jit/Modules/_testcapimodule.c python/branches/py3k-jit/Unittests/GetArgsTest.cc Modified: python/branches/py3k-jit/Modules/_testcapimodule.c ============================================================================== --- python/branches/py3k-jit/Modules/_testcapimodule.c (original) +++ python/branches/py3k-jit/Modules/_testcapimodule.c Fri May 14 23:40:31 2010 @@ -807,58 +807,6 @@ } #endif -/* Test Z and Z# codes for PyArg_ParseTuple */ -static PyObject * -test_Z_code(PyObject *self) -{ - PyObject *tuple, *obj; - Py_UNICODE *value1, *value2; - Py_ssize_t len1, len2; - - tuple = PyTuple_New(2); - if (tuple == NULL) - return NULL; - - obj = PyUnicode_FromString("test"); - PyTuple_SET_ITEM(tuple, 0, obj); - Py_INCREF(Py_None); - PyTuple_SET_ITEM(tuple, 1, Py_None); - - /* swap values on purpose */ - value1 = NULL; - value2 = PyUnicode_AS_UNICODE(obj); - - /* Test Z for both values */ - if (PyArg_ParseTuple(tuple, "ZZ:test_Z_code", &value1, &value2) < 0) - return NULL; - if (value1 != PyUnicode_AS_UNICODE(obj)) - return raiseTestError("test_Z_code", - "Z code returned wrong value for 'test'"); - if (value2 != NULL) - return raiseTestError("test_Z_code", - "Z code returned wrong value for None"); - - value1 = NULL; - value2 = PyUnicode_AS_UNICODE(obj); - len1 = -1; - len2 = -1; - - /* Test Z# for both values */ - if (PyArg_ParseTuple(tuple, "Z#Z#:test_Z_code", &value1, &len1, - &value2, &len2) < 0) - return NULL; - if (value1 != PyUnicode_AS_UNICODE(obj) || - len1 != PyUnicode_GET_SIZE(obj)) - return raiseTestError("test_Z_code", - "Z# code returned wrong values for 'test'"); - if (value2 != NULL || - len2 != 0) - return raiseTestError("test_Z_code", - "Z# code returned wrong values for None'"); - - Py_DECREF(tuple); - Py_RETURN_NONE; -} static PyObject * test_widechar(PyObject *self) @@ -1646,7 +1594,6 @@ {"codec_incrementaldecoder", (PyCFunction)codec_incrementaldecoder, METH_VARARGS}, #endif - {"test_Z_code", (PyCFunction)test_Z_code, METH_NOARGS}, {"test_widechar", (PyCFunction)test_widechar, METH_NOARGS}, #ifdef WITH_THREAD {"_test_thread_state", test_thread_state, METH_VARARGS}, Modified: python/branches/py3k-jit/Unittests/GetArgsTest.cc ============================================================================== --- python/branches/py3k-jit/Unittests/GetArgsTest.cc (original) +++ python/branches/py3k-jit/Unittests/GetArgsTest.cc Fri May 14 23:40:31 2010 @@ -183,3 +183,42 @@ Py_DECREF(tuple); } + + +// Test the Z and Z# codes for PyArg_ParseTuple. +TEST_F(GetArgsTest, FormatCode_Z) +{ + PyObject *tuple = PyTuple_New(2); + ASSERT_TRUE(tuple != NULL); + + PyObject *obj = PyUnicode_FromString("test"); + PyTuple_SET_ITEM(tuple, 0, obj); + Py_INCREF(Py_None); + PyTuple_SET_ITEM(tuple, 1, Py_None); + + // Swap values on purpose. + Py_UNICODE *value1 = NULL; + Py_UNICODE *value2 = PyUnicode_AS_UNICODE(obj); + + /* Test Z for both values. */ + EXPECT_GE(PyArg_ParseTuple(tuple, "ZZ:FormatCode_Z", &value1, &value2), 0); + EXPECT_EQ(value1, PyUnicode_AS_UNICODE(obj)) + << "Z code returned wrong value for 'test'"; + EXPECT_TRUE(value2 == NULL) << "Z code returned wrong value for None"; + + value1 = NULL; + value2 = PyUnicode_AS_UNICODE(obj); + Py_ssize_t len1 = -1; + Py_ssize_t len2 = -1; + + // Test Z# for both values. + EXPECT_GE(PyArg_ParseTuple(tuple, "Z#Z#:FormatCode_Z", &value1, &len1, + &value2, &len2), 0); + EXPECT_EQ(PyUnicode_AS_UNICODE(obj), value1); + EXPECT_EQ(PyUnicode_GET_SIZE(obj), len1); + EXPECT_TRUE(value2 == NULL); + EXPECT_EQ(0, len2); + + Py_DECREF(tuple); + +} From python-checkins at python.org Fri May 14 23:52:26 2010 From: python-checkins at python.org (victor.stinner) Date: Fri, 14 May 2010 23:52:26 +0200 (CEST) Subject: [Python-checkins] r81179 - python/trunk/Lib/subprocess.py Message-ID: <20100514215226.B401BEEB04@mail.python.org> Author: victor.stinner Date: Fri May 14 23:52:26 2010 New Revision: 81179 Log: Fix regression introduced by r81154 (Issue #5099, subprocess destructor) Modified: python/trunk/Lib/subprocess.py Modified: python/trunk/Lib/subprocess.py ============================================================================== --- python/trunk/Lib/subprocess.py (original) +++ python/trunk/Lib/subprocess.py Fri May 14 23:52:26 2010 @@ -908,9 +908,9 @@ def _internal_poll(self, _deadstate=None, - _WaitForSingleObject=WaitForSingleObject, - _WAIT_OBJECT_0=WAIT_OBJECT_0, - _GetExitCodeProcess=GetExitCodeProcess): + _WaitForSingleObject=_subprocess.WaitForSingleObject, + _WAIT_OBJECT_0=_subprocess.WAIT_OBJECT_0, + _GetExitCodeProcess=_subprocess.GetExitCodeProcess): """Check if child process has terminated. Returns returncode attribute. From python-checkins at python.org Fri May 14 23:53:32 2010 From: python-checkins at python.org (victor.stinner) Date: Fri, 14 May 2010 23:53:32 +0200 (CEST) Subject: [Python-checkins] r81180 - in python/branches/release26-maint: Lib/subprocess.py Message-ID: <20100514215332.66A8BEEB3C@mail.python.org> Author: victor.stinner Date: Fri May 14 23:53:32 2010 New Revision: 81180 Log: Merged revisions 81179 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r81179 | victor.stinner | 2010-05-14 23:52:26 +0200 (ven., 14 mai 2010) | 2 lines Fix regression introduced by r81154 (Issue #5099, subprocess destructor) ........ Modified: python/branches/release26-maint/ (props changed) python/branches/release26-maint/Lib/subprocess.py Modified: python/branches/release26-maint/Lib/subprocess.py ============================================================================== --- python/branches/release26-maint/Lib/subprocess.py (original) +++ python/branches/release26-maint/Lib/subprocess.py Fri May 14 23:53:32 2010 @@ -859,9 +859,9 @@ def _internal_poll(self, _deadstate=None, - _WaitForSingleObject=WaitForSingleObject, - _WAIT_OBJECT_0=WAIT_OBJECT_0, - _GetExitCodeProcess=GetExitCodeProcess): + _WaitForSingleObject=_subprocess.WaitForSingleObject, + _WAIT_OBJECT_0=_subprocess.WAIT_OBJECT_0, + _GetExitCodeProcess=_subprocess.GetExitCodeProcess): """Check if child process has terminated. Returns returncode attribute. From python-checkins at python.org Fri May 14 23:53:45 2010 From: python-checkins at python.org (victor.stinner) Date: Fri, 14 May 2010 23:53:45 +0200 (CEST) Subject: [Python-checkins] r81181 - in python/branches/py3k: Lib/subprocess.py Message-ID: <20100514215345.90997EEB47@mail.python.org> Author: victor.stinner Date: Fri May 14 23:53:45 2010 New Revision: 81181 Log: Merged revisions 81179 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r81179 | victor.stinner | 2010-05-14 23:52:26 +0200 (ven., 14 mai 2010) | 2 lines Fix regression introduced by r81154 (Issue #5099, subprocess destructor) ........ Modified: python/branches/py3k/ (props changed) python/branches/py3k/Lib/subprocess.py Modified: python/branches/py3k/Lib/subprocess.py ============================================================================== --- python/branches/py3k/Lib/subprocess.py (original) +++ python/branches/py3k/Lib/subprocess.py Fri May 14 23:53:45 2010 @@ -908,9 +908,9 @@ def _internal_poll(self, _deadstate=None, - _WaitForSingleObject=WaitForSingleObject, - _WAIT_OBJECT_0=WAIT_OBJECT_0, - _GetExitCodeProcess=GetExitCodeProcess): + _WaitForSingleObject=_subprocess.WaitForSingleObject, + _WAIT_OBJECT_0=_subprocess.WAIT_OBJECT_0, + _GetExitCodeProcess=_subprocess.GetExitCodeProcess): """Check if child process has terminated. Returns returncode attribute. From python-checkins at python.org Fri May 14 23:57:26 2010 From: python-checkins at python.org (victor.stinner) Date: Fri, 14 May 2010 23:57:26 +0200 (CEST) Subject: [Python-checkins] r81182 - in python/branches/release31-maint: Lib/subprocess.py Message-ID: <20100514215726.05E0EEEB25@mail.python.org> Author: victor.stinner Date: Fri May 14 23:57:25 2010 New Revision: 81182 Log: Merged revisions 81181 via svnmerge from svn+ssh://pythondev at svn.python.org/python/branches/py3k ................ r81181 | victor.stinner | 2010-05-14 23:53:45 +0200 (ven., 14 mai 2010) | 9 lines Merged revisions 81179 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r81179 | victor.stinner | 2010-05-14 23:52:26 +0200 (ven., 14 mai 2010) | 2 lines Fix regression introduced by r81154 (Issue #5099, subprocess destructor) ........ ................ Modified: python/branches/release31-maint/ (props changed) python/branches/release31-maint/Lib/subprocess.py Modified: python/branches/release31-maint/Lib/subprocess.py ============================================================================== --- python/branches/release31-maint/Lib/subprocess.py (original) +++ python/branches/release31-maint/Lib/subprocess.py Fri May 14 23:57:25 2010 @@ -884,9 +884,9 @@ def _internal_poll(self, _deadstate=None, - _WaitForSingleObject=WaitForSingleObject, - _WAIT_OBJECT_0=WAIT_OBJECT_0, - _GetExitCodeProcess=GetExitCodeProcess): + _WaitForSingleObject=_subprocess.WaitForSingleObject, + _WAIT_OBJECT_0=_subprocess.WAIT_OBJECT_0, + _GetExitCodeProcess=_subprocess.GetExitCodeProcess): """Check if child process has terminated. Returns returncode attribute. From jimjjewett at gmail.com Sat May 15 00:32:14 2010 From: jimjjewett at gmail.com (Jim Jewett) Date: Fri, 14 May 2010 18:32:14 -0400 Subject: [Python-checkins] distutils2: removing the text_file module. TextFile is very complex where one or two In-Reply-To: References: Message-ID: On Fri, May 14, 2010 at 4:36 PM, tarek.ziade wrote: > tarek.ziade pushed d35f803e3b3b to distutils2: > > http://hg.python.org/distutils2/rev/d35f803e3b3b > changeset: ? 138:d35f803e3b3b > user: ? ? ? ?Tarek Ziade > date: ? ? ? ?Wed May 12 16:36:27 2010 +0200 > summary: ? ? removing the text_file module. TextFile is very complex where one or two regexps can do the job for our unique use case (in the sdist command) Are you sure sure those regexps do the same thing? The comment for _COLLAPSE_PATTERN looks like it ought to be a line continuation backslash character. But when I try to understand the actual pattern, it seems to be looking for lines whose final character is alphanumeric (and whose second-to-last character is a backslash). Similarly, the _COMMENTED_LINE pattern looks like it could miss indented comments as well as comments stuck at the ends of a code lines. # catch this # miss this def f(self): # and leave this comment too > +# a \ followed by some spaces + EOL > +_COLLAPSE_PATTERN = re.compile('\\\w\n', re.M) > +_COMMENTED_LINE = re.compile('^#.*\n$|^\w*\n$', re.M) > + From solipsis at pitrou.net Sat May 15 01:24:20 2010 From: solipsis at pitrou.net (solipsis at pitrou.net) Date: Sat, 15 May 2010 01:24:20 +0200 (CEST) Subject: [Python-checkins] Daily py3k reference leaks (r81170): sum=1 Message-ID: <20100514232420.E80361770A@ns6635.ovh.net> py3k results for svn r81170 (hg cset 61fd7ca33725) -------------------------------------------------- test_multiprocessing leaked [1, 0, 0] references, sum=1 Command line was: ['./python', '-m', 'test.regrtest', '-uall', '-R', '3:3:/home/antoine/py3k/refleaks/reflog_ykono', '-x'] From python-checkins at python.org Sat May 15 03:40:41 2010 From: python-checkins at python.org (victor.stinner) Date: Sat, 15 May 2010 03:40:41 +0200 (CEST) Subject: [Python-checkins] r81183 - python/branches/py3k/Lib/test/test_capi.py Message-ID: <20100515014041.911A6EE98D@mail.python.org> Author: victor.stinner Date: Sat May 15 03:40:41 2010 New Revision: 81183 Log: Fix test_capi for Windows: strip newline characters Fix test_no_FatalError_infinite_loop() introduced by r81142 (issue #3605). Modified: python/branches/py3k/Lib/test/test_capi.py Modified: python/branches/py3k/Lib/test/test_capi.py ============================================================================== --- python/branches/py3k/Lib/test/test_capi.py (original) +++ python/branches/py3k/Lib/test/test_capi.py Sat May 15 03:40:41 2010 @@ -45,9 +45,9 @@ (out, err) = p.communicate() self.assertEqual(out, b'') # This used to cause an infinite loop. - self.assertEqual(err, + self.assertEqual(err.rstrip(), b'Fatal Python error:' - b' PyThreadState_Get: no current thread\n') + b' PyThreadState_Get: no current thread') @unittest.skipUnless(threading, 'Threading required for this test.') From python-checkins at python.org Sat May 15 03:42:04 2010 From: python-checkins at python.org (victor.stinner) Date: Sat, 15 May 2010 03:42:04 +0200 (CEST) Subject: [Python-checkins] r81184 - python/branches/release31-maint Message-ID: <20100515014204.712ACEE98D@mail.python.org> Author: victor.stinner Date: Sat May 15 03:42:04 2010 New Revision: 81184 Log: Blocked revisions 81183 via svnmerge ........ r81183 | victor.stinner | 2010-05-15 03:40:41 +0200 (sam., 15 mai 2010) | 4 lines Fix test_capi for Windows: strip newline characters Fix test_no_FatalError_infinite_loop() introduced by r81142 (issue #3605). ........ Modified: python/branches/release31-maint/ (props changed) From python-checkins at python.org Sat May 15 10:58:23 2010 From: python-checkins at python.org (tarek.ziade) Date: Sat, 15 May 2010 10:58:23 +0200 Subject: [Python-checkins] distutils2: added some test coverage and fixed the regexps Message-ID: tarek.ziade pushed a960210179a9 to distutils2: http://hg.python.org/distutils2/rev/a960210179a9 changeset: 152:a960210179a9 tag: tip user: Tarek Ziade date: Sat May 15 10:58:13 2010 +0200 summary: added some test coverage and fixed the regexps files: src/distutils2/manifest.py, src/distutils2/tests/test_manifest.py diff --git a/src/distutils2/manifest.py b/src/distutils2/manifest.py --- a/src/distutils2/manifest.py +++ b/src/distutils2/manifest.py @@ -21,9 +21,8 @@ __all__ = ['Manifest'] # a \ followed by some spaces + EOL -_COLLAPSE_PATTERN = re.compile('\\\w\n', re.M) -_COMMENTED_LINE = re.compile('^#.*\n$|^\w*\n$', re.M) - +_COLLAPSE_PATTERN = re.compile('\\\w*\n', re.M) +_COMMENTED_LINE = re.compile('#.*?(?=\n)|^\w*\n|\n(?=$)', re.M|re.S) class Manifest(object): """A list of files built by on exploring the filesystem and filtered by @@ -70,9 +69,10 @@ try: content = f.read() # first, let's unwrap collapsed lines - content = _COLLAPSE_PATTERN.replace(content, '') + content = _COLLAPSE_PATTERN.sub('', content) + # next, let's remove commented lines and empty lines - content = _COMMENTED_LINE.replace(content, '') + content = _COMMENTED_LINE.sub('', content) # now we have our cleaned up lines lines = [line.strip() for line in content.split('\n')] @@ -83,7 +83,7 @@ try: self._process_template_line(line) except DistutilsTemplateError, msg: - self.warn("%s, %s" % (path, msg)) + logging.warning("%s, %s" % (path, msg)) def write(self, path): """Write the file list in 'self.filelist' (presumably as filled in @@ -176,51 +176,50 @@ if action == 'include': for pattern in patterns: if not self._include_pattern(pattern, anchor=1): - logging.warning("warning: no files found matching '%s'", + logging.warning("warning: no files found matching '%s'" % pattern) elif action == 'exclude': for pattern in patterns: if not self.exclude_pattern(pattern, anchor=1): logging.warning(("warning: no previously-included files " - "found matching '%s'"), pattern) + "found matching '%s'") % pattern) elif action == 'global-include': for pattern in patterns: if not self._include_pattern(pattern, anchor=0): logging.warning(("warning: no files found matching '%s' " + - "anywhere in distribution"), pattern) + "anywhere in distribution") % pattern) elif action == 'global-exclude': for pattern in patterns: if not self.exclude_pattern(pattern, anchor=0): logging.warning(("warning: no previously-included files " - "matching '%s' found anywhere in distribution"), + "matching '%s' found anywhere in distribution") % pattern) elif action == 'recursive-include': for pattern in patterns: if not self._include_pattern(pattern, prefix=dir): logging.warning(("warning: no files found matching '%s' " - "under directory '%s'"), - pattern, dir) + "under directory '%s'" % (pattern, dir))) elif action == 'recursive-exclude': for pattern in patterns: if not self.exclude_pattern(pattern, prefix=dir): logging.warning(("warning: no previously-included files " - "matching '%s' found under directory '%s'"), - pattern, dir) + "matching '%s' found under directory '%s'") % + (pattern, dir)) elif action == 'graft': if not self._include_pattern(None, prefix=dir_pattern): - logging.warning("warning: no directories found matching '%s'", + logging.warning("warning: no directories found matching '%s'" % dir_pattern) elif action == 'prune': if not self.exclude_pattern(None, prefix=dir_pattern): logging.warning(("no previously-included directories found " + - "matching '%s'"), dir_pattern) + "matching '%s'") % dir_pattern) else: raise DistutilsInternalError( "this cannot happen: invalid action '%s'" % action) diff --git a/src/distutils2/tests/test_manifest.py b/src/distutils2/tests/test_manifest.py new file mode 100644 --- /dev/null +++ b/src/distutils2/tests/test_manifest.py @@ -0,0 +1,57 @@ +"""Tests for distutils.manifest.""" +import unittest2 +import os +import sys +import logging + +from distutils2.tests import support +from distutils2.manifest import Manifest + +_MANIFEST = """\ +recursive-include foo *.py # ok +# nothing here + +# + +recursive-include bar \\ + *.dat *.txt +""" + +class ManifestTestCase(support.TempdirManager, + unittest2.TestCase): + + def test_manifest_reader(self): + + tmpdir = self.mkdtemp() + MANIFEST = os.path.join(tmpdir, 'MANIFEST.in') + f = open(MANIFEST, 'w') + try: + f.write(_MANIFEST) + finally: + f.close() + manifest = Manifest() + + warns = [] + def _warn(msg): + warns.append(msg) + + old_warn = logging.warning + logging.warning = _warn + try: + manifest.read_template(MANIFEST) + finally: + logging.warning = old_warn + + # the manifest should have been read + # and 3 warnings issued (we ddidn't provided the files) + self.assertEquals(len(warns), 3) + for warn in warns: + self.assertIn('warning: no files found matching', warn) + + + +def test_suite(): + return unittest2.makeSuite(ManifestTestCase) + +if __name__ == '__main__': + run_unittest(test_suite()) -- Repository URL: http://hg.python.org/distutils2 From ziade.tarek at gmail.com Sat May 15 10:58:39 2010 From: ziade.tarek at gmail.com (=?ISO-8859-1?Q?Tarek_Ziad=E9?=) Date: Sat, 15 May 2010 03:58:39 -0500 Subject: [Python-checkins] distutils2: removing the text_file module. TextFile is very complex where one or two In-Reply-To: References: Message-ID: On Fri, May 14, 2010 at 5:32 PM, Jim Jewett wrote: [..] > > Are you sure sure those regexps do the same thing? They don't, thanks for catching this. I thought this was covered by a test, but no, so I've added some tests and fixed it. Regards Tarek From python-checkins at python.org Sat May 15 11:31:08 2010 From: python-checkins at python.org (stefan.krah) Date: Sat, 15 May 2010 11:31:08 +0200 (CEST) Subject: [Python-checkins] r81185 - python/trunk/Lib/test/test_signal.py Message-ID: <20100515093108.CA522EE98D@mail.python.org> Author: stefan.krah Date: Sat May 15 11:31:08 2010 New Revision: 81185 Log: If the timeout is exceeded, count the tests as skipped instead of just issuing a warning. Modified: python/trunk/Lib/test/test_signal.py Modified: python/trunk/Lib/test/test_signal.py ============================================================================== --- python/trunk/Lib/test/test_signal.py (original) +++ python/trunk/Lib/test/test_signal.py Sat May 15 11:31:08 2010 @@ -431,9 +431,8 @@ if signal.getitimer(self.itimer) == (0.0, 0.0): break # sig_vtalrm handler stopped this itimer else: # Issue 8424 - sys.stdout.write("test_itimer_virtual: timeout: likely cause: " - "machine too slow or load too high.\n") - return + raise unittest.SkipTest("timeout: likely cause: machine too slow " + "or load too high") # virtual itimer should be (0.0, 0.0) now self.assertEquals(signal.getitimer(self.itimer), (0.0, 0.0)) @@ -455,9 +454,8 @@ if signal.getitimer(self.itimer) == (0.0, 0.0): break # sig_prof handler stopped this itimer else: # Issue 8424 - sys.stdout.write("test_itimer_prof: timeout: likely cause: " - "machine too slow or load too high.\n") - return + raise unittest.SkipTest("timeout: likely cause: machine too slow " + "or load too high") # profiling itimer should be (0.0, 0.0) now self.assertEquals(signal.getitimer(self.itimer), (0.0, 0.0)) From python-checkins at python.org Sat May 15 11:34:51 2010 From: python-checkins at python.org (stefan.krah) Date: Sat, 15 May 2010 11:34:51 +0200 (CEST) Subject: [Python-checkins] r81186 - python/branches/release26-maint/Lib/test/test_signal.py Message-ID: <20100515093451.02967EE98D@mail.python.org> Author: stefan.krah Date: Sat May 15 11:34:50 2010 New Revision: 81186 Log: Use stderr instead of stdout for warning. Modified: python/branches/release26-maint/Lib/test/test_signal.py Modified: python/branches/release26-maint/Lib/test/test_signal.py ============================================================================== --- python/branches/release26-maint/Lib/test/test_signal.py (original) +++ python/branches/release26-maint/Lib/test/test_signal.py Sat May 15 11:34:50 2010 @@ -450,7 +450,7 @@ if signal.getitimer(self.itimer) == (0.0, 0.0): break # sig_vtalrm handler stopped this itimer else: # Issue 8424 - sys.stdout.write("test_itimer_virtual: timeout: likely cause: " + sys.stderr.write("test_itimer_virtual: timeout: likely cause: " "machine too slow or load too high.\n") return From python-checkins at python.org Sat May 15 11:37:55 2010 From: python-checkins at python.org (stefan.krah) Date: Sat, 15 May 2010 11:37:55 +0200 (CEST) Subject: [Python-checkins] r81187 - python/branches/release26-maint Message-ID: <20100515093755.0DAD4EE98D@mail.python.org> Author: stefan.krah Date: Sat May 15 11:37:54 2010 New Revision: 81187 Log: Blocked revisions 81185 via svnmerge ........ r81185 | stefan.krah | 2010-05-15 11:31:08 +0200 (Sat, 15 May 2010) | 4 lines If the timeout is exceeded, count the tests as skipped instead of just issuing a warning. ........ Modified: python/branches/release26-maint/ (props changed) From python-checkins at python.org Sat May 15 11:41:27 2010 From: python-checkins at python.org (stefan.krah) Date: Sat, 15 May 2010 11:41:27 +0200 (CEST) Subject: [Python-checkins] r81188 - in python/branches/py3k: Lib/test/test_signal.py Message-ID: <20100515094127.A2D45EE987@mail.python.org> Author: stefan.krah Date: Sat May 15 11:41:27 2010 New Revision: 81188 Log: Merged revisions 81185 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r81185 | stefan.krah | 2010-05-15 11:31:08 +0200 (Sat, 15 May 2010) | 4 lines If the timeout is exceeded, count the tests as skipped instead of just issuing a warning. ........ Modified: python/branches/py3k/ (props changed) python/branches/py3k/Lib/test/test_signal.py Modified: python/branches/py3k/Lib/test/test_signal.py ============================================================================== --- python/branches/py3k/Lib/test/test_signal.py (original) +++ python/branches/py3k/Lib/test/test_signal.py Sat May 15 11:41:27 2010 @@ -431,9 +431,8 @@ if signal.getitimer(self.itimer) == (0.0, 0.0): break # sig_vtalrm handler stopped this itimer else: # Issue 8424 - sys.stdout.write("test_itimer_virtual: timeout: likely cause: " - "machine too slow or load too high.\n") - return + raise unittest.SkipTest("timeout: likely cause: machine too slow " + "or load too high") # virtual itimer should be (0.0, 0.0) now self.assertEquals(signal.getitimer(self.itimer), (0.0, 0.0)) @@ -455,9 +454,8 @@ if signal.getitimer(self.itimer) == (0.0, 0.0): break # sig_prof handler stopped this itimer else: # Issue 8424 - sys.stdout.write("test_itimer_prof: timeout: likely cause: " - "machine too slow or load too high.\n") - return + raise unittest.SkipTest("timeout: likely cause: machine too slow " + "or load too high") # profiling itimer should be (0.0, 0.0) now self.assertEquals(signal.getitimer(self.itimer), (0.0, 0.0)) From python-checkins at python.org Sat May 15 11:45:07 2010 From: python-checkins at python.org (stefan.krah) Date: Sat, 15 May 2010 11:45:07 +0200 (CEST) Subject: [Python-checkins] r81189 - in python/branches/release31-maint: Lib/test/test_signal.py Message-ID: <20100515094507.A033FEE983@mail.python.org> Author: stefan.krah Date: Sat May 15 11:45:07 2010 New Revision: 81189 Log: Merged revisions 81188 via svnmerge from svn+ssh://pythondev at svn.python.org/python/branches/py3k ................ r81188 | stefan.krah | 2010-05-15 11:41:27 +0200 (Sat, 15 May 2010) | 10 lines Merged revisions 81185 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r81185 | stefan.krah | 2010-05-15 11:31:08 +0200 (Sat, 15 May 2010) | 4 lines If the timeout is exceeded, count the tests as skipped instead of just issuing a warning. ........ ................ Modified: python/branches/release31-maint/ (props changed) python/branches/release31-maint/Lib/test/test_signal.py Modified: python/branches/release31-maint/Lib/test/test_signal.py ============================================================================== --- python/branches/release31-maint/Lib/test/test_signal.py (original) +++ python/branches/release31-maint/Lib/test/test_signal.py Sat May 15 11:45:07 2010 @@ -431,9 +431,8 @@ if signal.getitimer(self.itimer) == (0.0, 0.0): break # sig_vtalrm handler stopped this itimer else: # Issue 8424 - sys.stdout.write("test_itimer_virtual: timeout: likely cause: " - "machine too slow or load too high.\n") - return + raise unittest.SkipTest("timeout: likely cause: machine too slow " + "or load too high") # virtual itimer should be (0.0, 0.0) now self.assertEquals(signal.getitimer(self.itimer), (0.0, 0.0)) @@ -455,9 +454,8 @@ if signal.getitimer(self.itimer) == (0.0, 0.0): break # sig_prof handler stopped this itimer else: # Issue 8424 - sys.stdout.write("test_itimer_prof: timeout: likely cause: " - "machine too slow or load too high.\n") - return + raise unittest.SkipTest("timeout: likely cause: machine too slow " + "or load too high") # profiling itimer should be (0.0, 0.0) now self.assertEquals(signal.getitimer(self.itimer), (0.0, 0.0)) From python-checkins at python.org Sat May 15 14:27:16 2010 From: python-checkins at python.org (victor.stinner) Date: Sat, 15 May 2010 14:27:16 +0200 (CEST) Subject: [Python-checkins] r81190 - in python/branches/py3k: Doc/library/sys.rst Misc/NEWS Python/bltinmodule.c Python/pythonrun.c Message-ID: <20100515122716.55C8BEE9F6@mail.python.org> Author: victor.stinner Date: Sat May 15 14:27:16 2010 New Revision: 81190 Log: Issue #8610: Load file system codec at startup, and display a fatal error on failure. Set the file system encoding to utf-8 (instead of None) if getting the locale encoding failed, or if nl_langinfo(CODESET) function is missing. Modified: python/branches/py3k/Doc/library/sys.rst python/branches/py3k/Misc/NEWS python/branches/py3k/Python/bltinmodule.c python/branches/py3k/Python/pythonrun.c Modified: python/branches/py3k/Doc/library/sys.rst ============================================================================== --- python/branches/py3k/Doc/library/sys.rst (original) +++ python/branches/py3k/Doc/library/sys.rst Sat May 15 14:27:16 2010 @@ -298,15 +298,13 @@ .. function:: getfilesystemencoding() - Return the name of the encoding used to convert Unicode filenames into system - file names, or ``None`` if the system default encoding is used. The result value - depends on the operating system: + Return the name of the encoding used to convert Unicode filenames into + system file names. The result value depends on the operating system: * On Mac OS X, the encoding is ``'utf-8'``. * On Unix, the encoding is the user's preference according to the result of - nl_langinfo(CODESET), or ``None`` if the ``nl_langinfo(CODESET)`` - failed. + nl_langinfo(CODESET), or ``'utf-8'`` if ``nl_langinfo(CODESET)`` failed. * On Windows NT+, file names are Unicode natively, so no conversion is performed. :func:`getfilesystemencoding` still returns ``'mbcs'``, as @@ -316,6 +314,10 @@ * On Windows 9x, the encoding is ``'mbcs'``. + .. versionchanged:: 3.2 + On Unix, use ``'utf-8'`` instead of ``None`` if ``nl_langinfo(CODESET)`` + failed. :func:`getfilesystemencoding` result cannot be ``None``. + .. function:: getrefcount(object) Modified: python/branches/py3k/Misc/NEWS ============================================================================== --- python/branches/py3k/Misc/NEWS (original) +++ python/branches/py3k/Misc/NEWS Sat May 15 14:27:16 2010 @@ -12,6 +12,10 @@ Core and Builtins ----------------- +- Issue #8610: Load file system codec at startup, and display a fatal error on + failure. Set the file system encoding to utf-8 (instead of None) if getting + the locale encoding failed, or if nl_langinfo(CODESET) function is missing. + - PyFile_FromFd() uses PyUnicode_DecodeFSDefault() instead of PyUnicode_FromString() to support surrogates in the filename and use the right encoding Modified: python/branches/py3k/Python/bltinmodule.c ============================================================================== --- python/branches/py3k/Python/bltinmodule.c (original) +++ python/branches/py3k/Python/bltinmodule.c Sat May 15 14:27:16 2010 @@ -9,6 +9,10 @@ #include +#ifdef HAVE_LANGINFO_H +#include /* CODESET */ +#endif + /* The default encoding used by the platform file system APIs Can remain NULL for all platforms that don't have such a concept @@ -21,9 +25,12 @@ #elif defined(__APPLE__) const char *Py_FileSystemDefaultEncoding = "utf-8"; int Py_HasFileSystemDefaultEncoding = 1; -#else -const char *Py_FileSystemDefaultEncoding = NULL; /* use default */ +#elif defined(HAVE_LANGINFO_H) && defined(CODESET) +const char *Py_FileSystemDefaultEncoding = NULL; /* set by initfsencoding() */ int Py_HasFileSystemDefaultEncoding = 0; +#else +const char *Py_FileSystemDefaultEncoding = "utf-8"; +int Py_HasFileSystemDefaultEncoding = 1; #endif int Modified: python/branches/py3k/Python/pythonrun.c ============================================================================== --- python/branches/py3k/Python/pythonrun.c (original) +++ python/branches/py3k/Python/pythonrun.c Sat May 15 14:27:16 2010 @@ -57,6 +57,7 @@ /* Forward */ static void initmain(void); +static void initfsencoding(void); static void initsite(void); static int initstdio(void); static void flush_io(void); @@ -159,7 +160,6 @@ error: Py_XDECREF(codec); - PyErr_Clear(); return NULL; } #endif @@ -171,9 +171,6 @@ PyThreadState *tstate; PyObject *bimod, *sysmod, *pstderr; char *p; -#if defined(HAVE_LANGINFO_H) && defined(CODESET) - char *codeset; -#endif extern void _Py_ReadyTypes(void); if (initialized) @@ -264,21 +261,7 @@ _PyImportHooks_Init(); -#if defined(HAVE_LANGINFO_H) && defined(CODESET) - /* On Unix, set the file system encoding according to the - user's preference, if the CODESET names a well-known - Python codec, and Py_FileSystemDefaultEncoding isn't - initialized by other means. Also set the encoding of - stdin and stdout if these are terminals. */ - - codeset = get_codeset(); - if (codeset) { - if (!Py_FileSystemDefaultEncoding) - Py_FileSystemDefaultEncoding = codeset; - else - free(codeset); - } -#endif + initfsencoding(); if (install_sigs) initsigs(); /* Signal handling stuff, including initintr() */ @@ -496,7 +479,7 @@ _PyUnicode_Fini(); /* reset file system default encoding */ - if (!Py_HasFileSystemDefaultEncoding) { + if (!Py_HasFileSystemDefaultEncoding && Py_FileSystemDefaultEncoding) { free((char*)Py_FileSystemDefaultEncoding); Py_FileSystemDefaultEncoding = NULL; } @@ -707,6 +690,45 @@ } } +static void +initfsencoding(void) +{ + PyObject *codec; +#if defined(HAVE_LANGINFO_H) && defined(CODESET) + char *codeset; + + /* On Unix, set the file system encoding according to the + user's preference, if the CODESET names a well-known + Python codec, and Py_FileSystemDefaultEncoding isn't + initialized by other means. Also set the encoding of + stdin and stdout if these are terminals. */ + codeset = get_codeset(); + if (codeset != NULL) { + Py_FileSystemDefaultEncoding = codeset; + Py_HasFileSystemDefaultEncoding = 0; + return; + } + + PyErr_Clear(); + fprintf(stderr, + "Unable to get the locale encoding: " + "fallback to utf-8\n"); + Py_FileSystemDefaultEncoding = "utf-8"; + Py_HasFileSystemDefaultEncoding = 1; +#endif + + /* the encoding is mbcs, utf-8 or ascii */ + codec = _PyCodec_Lookup(Py_FileSystemDefaultEncoding); + if (!codec) { + /* Such error can only occurs in critical situations: no more + * memory, import a module of the standard library failed, + * etc. */ + Py_FatalError("Py_Initialize: unable to load the file system codec"); + } else { + Py_DECREF(codec); + } +} + /* Import the site module (not into __main__ though) */ static void From python-checkins at python.org Sat May 15 14:28:16 2010 From: python-checkins at python.org (victor.stinner) Date: Sat, 15 May 2010 14:28:16 +0200 (CEST) Subject: [Python-checkins] r81191 - python/branches/release31-maint Message-ID: <20100515122816.4B292EE9F6@mail.python.org> Author: victor.stinner Date: Sat May 15 14:28:16 2010 New Revision: 81191 Log: Blocked revisions 81190 via svnmerge ........ r81190 | victor.stinner | 2010-05-15 14:27:16 +0200 (sam., 15 mai 2010) | 4 lines Issue #8610: Load file system codec at startup, and display a fatal error on failure. Set the file system encoding to utf-8 (instead of None) if getting the locale encoding failed, or if nl_langinfo(CODESET) function is missing. ........ Modified: python/branches/release31-maint/ (props changed) From python-checkins at python.org Sat May 15 15:14:32 2010 From: python-checkins at python.org (victor.stinner) Date: Sat, 15 May 2010 15:14:32 +0200 (CEST) Subject: [Python-checkins] r81192 - in python/branches/py3k: Misc/NEWS Objects/unicodeobject.c Message-ID: <20100515131432.E729FEE9A5@mail.python.org> Author: victor.stinner Date: Sat May 15 15:14:32 2010 New Revision: 81192 Log: Enable shortcuts for common encodings in PyUnicode_AsEncodedString() for any error handler, not only the default error handler (strict) Modified: python/branches/py3k/Misc/NEWS python/branches/py3k/Objects/unicodeobject.c Modified: python/branches/py3k/Misc/NEWS ============================================================================== --- python/branches/py3k/Misc/NEWS (original) +++ python/branches/py3k/Misc/NEWS Sat May 15 15:14:32 2010 @@ -12,6 +12,9 @@ Core and Builtins ----------------- +- Enable shortcuts for common encodings in PyUnicode_AsEncodedString() for any + error handler, not only the default error handler (strict) + - Issue #8610: Load file system codec at startup, and display a fatal error on failure. Set the file system encoding to utf-8 (instead of None) if getting the locale encoding failed, or if nl_langinfo(CODESET) function is missing. Modified: python/branches/py3k/Objects/unicodeobject.c ============================================================================== --- python/branches/py3k/Objects/unicodeobject.c (original) +++ python/branches/py3k/Objects/unicodeobject.c Sat May 15 15:14:32 2010 @@ -1476,31 +1476,39 @@ encoding = PyUnicode_GetDefaultEncoding(); /* Shortcuts for common default encodings */ - if (errors == NULL) { - if (strcmp(encoding, "utf-8") == 0) - return PyUnicode_AsUTF8String(unicode); - else if (strcmp(encoding, "latin-1") == 0) - return PyUnicode_AsLatin1String(unicode); + if (strcmp(encoding, "utf-8") == 0) + return PyUnicode_EncodeUTF8(PyUnicode_AS_UNICODE(unicode), + PyUnicode_GET_SIZE(unicode), + errors); + else if (strcmp(encoding, "latin-1") == 0) + return PyUnicode_EncodeLatin1(PyUnicode_AS_UNICODE(unicode), + PyUnicode_GET_SIZE(unicode), + errors); #if defined(MS_WINDOWS) && defined(HAVE_USABLE_WCHAR_T) - else if (strcmp(encoding, "mbcs") == 0) - return PyUnicode_AsMBCSString(unicode); -#endif - else if (strcmp(encoding, "ascii") == 0) - return PyUnicode_AsASCIIString(unicode); - /* During bootstrap, we may need to find the encodings - package, to load the file system encoding, and require the - file system encoding in order to load the encodings - package. - - Break out of this dependency by assuming that the path to - the encodings module is ASCII-only. XXX could try wcstombs - instead, if the file system encoding is the locale's - encoding. */ - else if (Py_FileSystemDefaultEncoding && - strcmp(encoding, Py_FileSystemDefaultEncoding) == 0 && - !PyThreadState_GET()->interp->codecs_initialized) - return PyUnicode_AsASCIIString(unicode); - } + else if (strcmp(encoding, "mbcs") == 0) + return PyUnicode_EncodeMBCS(PyUnicode_AS_UNICODE(unicode), + PyUnicode_GET_SIZE(unicode), + errors); +#endif + else if (strcmp(encoding, "ascii") == 0) + return PyUnicode_EncodeASCII(PyUnicode_AS_UNICODE(unicode), + PyUnicode_GET_SIZE(unicode), + errors); + /* During bootstrap, we may need to find the encodings + package, to load the file system encoding, and require the + file system encoding in order to load the encodings + package. + + Break out of this dependency by assuming that the path to + the encodings module is ASCII-only. XXX could try wcstombs + instead, if the file system encoding is the locale's + encoding. */ + else if (Py_FileSystemDefaultEncoding && + strcmp(encoding, Py_FileSystemDefaultEncoding) == 0 && + !PyThreadState_GET()->interp->codecs_initialized) + return PyUnicode_EncodeASCII(PyUnicode_AS_UNICODE(unicode), + PyUnicode_GET_SIZE(unicode), + errors); /* Encode via the codec registry */ v = PyCodec_Encode(unicode, encoding, errors); From python-checkins at python.org Sat May 15 16:06:57 2010 From: python-checkins at python.org (victor.stinner) Date: Sat, 15 May 2010 16:06:57 +0200 (CEST) Subject: [Python-checkins] r81193 - python/branches/release31-maint Message-ID: <20100515140657.AAC58EE9A5@mail.python.org> Author: victor.stinner Date: Sat May 15 16:06:57 2010 New Revision: 81193 Log: Blocked revisions 81192 via svnmerge ........ r81192 | victor.stinner | 2010-05-15 15:14:32 +0200 (sam., 15 mai 2010) | 3 lines Enable shortcuts for common encodings in PyUnicode_AsEncodedString() for any error handler, not only the default error handler (strict) ........ Modified: python/branches/release31-maint/ (props changed) From python-checkins at python.org Sat May 15 18:27:28 2010 From: python-checkins at python.org (victor.stinner) Date: Sat, 15 May 2010 18:27:28 +0200 (CEST) Subject: [Python-checkins] r81194 - in python/branches/py3k: Doc/c-api/unicode.rst Include/unicodeobject.h Misc/NEWS Modules/_io/fileio.c Modules/_tkinter.c Modules/grpmodule.c Modules/pwdmodule.c Modules/spwdmodule.c Objects/unicodeobject.c Python/import.c Message-ID: <20100515162728.20703EEAA1@mail.python.org> Author: victor.stinner Date: Sat May 15 18:27:27 2010 New Revision: 81194 Log: Issue #8715: Create PyUnicode_EncodeFSDefault() function: Encode a Unicode object to Py_FileSystemDefaultEncoding with the "surrogateescape" error handler, return a bytes object. If Py_FileSystemDefaultEncoding is not set, fall back to UTF-8. Modified: python/branches/py3k/Doc/c-api/unicode.rst python/branches/py3k/Include/unicodeobject.h python/branches/py3k/Misc/NEWS python/branches/py3k/Modules/_io/fileio.c python/branches/py3k/Modules/_tkinter.c python/branches/py3k/Modules/grpmodule.c python/branches/py3k/Modules/pwdmodule.c python/branches/py3k/Modules/spwdmodule.c python/branches/py3k/Objects/unicodeobject.c python/branches/py3k/Python/import.c Modified: python/branches/py3k/Doc/c-api/unicode.rst ============================================================================== --- python/branches/py3k/Doc/c-api/unicode.rst (original) +++ python/branches/py3k/Doc/c-api/unicode.rst Sat May 15 18:27:27 2010 @@ -396,6 +396,7 @@ Use :func:`PyUnicode_DecodeFSDefaultAndSize` if you know the string length. + .. cfunction:: PyObject* PyUnicode_DecodeFSDefault(const char *s) Decode a string using :cdata:`Py_FileSystemDefaultEncoding` and @@ -404,6 +405,16 @@ If :cdata:`Py_FileSystemDefaultEncoding` is not set, fall back to UTF-8. +.. cfunction:: PyObject* PyUnicode_EncodeFSDefault(PyObject *unicode) + + Encode a Unicode object to :cdata:`Py_FileSystemDefaultEncoding` with the + ``'surrogateescape'`` error handler, return a :func:`bytes` object. + + If :cdata:`Py_FileSystemDefaultEncoding` is not set, fall back to UTF-8. + + .. versionadded:: 3.2 + + wchar_t Support """"""""""""""" Modified: python/branches/py3k/Include/unicodeobject.h ============================================================================== --- python/branches/py3k/Include/unicodeobject.h (original) +++ python/branches/py3k/Include/unicodeobject.h Sat May 15 18:27:27 2010 @@ -1268,6 +1268,16 @@ Py_ssize_t size /* size */ ); +/* Encode a Unicode object to Py_FileSystemDefaultEncoding with the + "surrogateescape" error handler, return a bytes object. + + If Py_FileSystemDefaultEncoding is not set, fall back to UTF-8. +*/ + +PyAPI_FUNC(PyObject*) PyUnicode_EncodeFSDefault( + PyObject *unicode + ); + /* --- Methods & Slots ---------------------------------------------------- These are capable of handling Unicode objects and strings on input Modified: python/branches/py3k/Misc/NEWS ============================================================================== --- python/branches/py3k/Misc/NEWS (original) +++ python/branches/py3k/Misc/NEWS Sat May 15 18:27:27 2010 @@ -12,6 +12,11 @@ Core and Builtins ----------------- +- Issue #8715: Create PyUnicode_EncodeFSDefault() function: Encode a Unicode + object to Py_FileSystemDefaultEncoding with the "surrogateescape" error + handler, return a bytes object. If Py_FileSystemDefaultEncoding is not set, + fall back to UTF-8. + - Enable shortcuts for common encodings in PyUnicode_AsEncodedString() for any error handler, not only the default error handler (strict) Modified: python/branches/py3k/Modules/_io/fileio.c ============================================================================== --- python/branches/py3k/Modules/_io/fileio.c (original) +++ python/branches/py3k/Modules/_io/fileio.c Sat May 15 18:27:27 2010 @@ -247,8 +247,7 @@ if (u == NULL) return -1; - stringobj = PyUnicode_AsEncodedString( - u, Py_FileSystemDefaultEncoding, "surrogateescape"); + stringobj = PyUnicode_EncodeFSDefault(u); Py_DECREF(u); if (stringobj == NULL) return -1; Modified: python/branches/py3k/Modules/_tkinter.c ============================================================================== --- python/branches/py3k/Modules/_tkinter.c (original) +++ python/branches/py3k/Modules/_tkinter.c Sat May 15 18:27:27 2010 @@ -3147,9 +3147,7 @@ it also helps Tcl find its encodings. */ uexe = PyUnicode_FromWideChar(Py_GetProgramName(), -1); if (uexe) { - cexe = PyUnicode_AsEncodedString(uexe, - Py_FileSystemDefaultEncoding, - NULL); + cexe = PyUnicode_EncodeFSDefault(uexe); if (cexe) Tcl_FindExecutable(PyBytes_AsString(cexe)); Py_XDECREF(cexe); Modified: python/branches/py3k/Modules/grpmodule.c ============================================================================== --- python/branches/py3k/Modules/grpmodule.c (original) +++ python/branches/py3k/Modules/grpmodule.c Sat May 15 18:27:27 2010 @@ -111,8 +111,7 @@ if (!PyArg_ParseTuple(args, "U:getgrnam", &arg)) return NULL; - if ((bytes = PyUnicode_AsEncodedString(arg, Py_FileSystemDefaultEncoding, - "surrogateescape")) == NULL) + if ((bytes = PyUnicode_EncodeFSDefault(arg)) == NULL) return NULL; if (PyBytes_AsStringAndSize(bytes, &name, NULL) == -1) goto out; Modified: python/branches/py3k/Modules/pwdmodule.c ============================================================================== --- python/branches/py3k/Modules/pwdmodule.c (original) +++ python/branches/py3k/Modules/pwdmodule.c Sat May 15 18:27:27 2010 @@ -132,9 +132,7 @@ if (!PyArg_ParseTuple(args, "U:getpwnam", &arg)) return NULL; - if ((bytes = PyUnicode_AsEncodedString(arg, - Py_FileSystemDefaultEncoding, - "surrogateescape")) == NULL) + if ((bytes = PyUnicode_EncodeFSDefault(arg)) == NULL) return NULL; if (PyBytes_AsStringAndSize(bytes, &name, NULL) == -1) goto out; Modified: python/branches/py3k/Modules/spwdmodule.c ============================================================================== --- python/branches/py3k/Modules/spwdmodule.c (original) +++ python/branches/py3k/Modules/spwdmodule.c Sat May 15 18:27:27 2010 @@ -118,9 +118,7 @@ if (!PyArg_ParseTuple(args, "U:getspnam", &arg)) return NULL; - if ((bytes = PyUnicode_AsEncodedString(arg, - Py_FileSystemDefaultEncoding, - "surrogateescape")) == NULL) + if ((bytes = PyUnicode_EncodeFSDefault(arg)) == NULL) return NULL; if (PyBytes_AsStringAndSize(bytes, &name, NULL) == -1) goto out; Modified: python/branches/py3k/Objects/unicodeobject.c ============================================================================== --- python/branches/py3k/Objects/unicodeobject.c (original) +++ python/branches/py3k/Objects/unicodeobject.c Sat May 15 18:27:27 2010 @@ -1461,6 +1461,18 @@ return NULL; } +PyObject *PyUnicode_EncodeFSDefault(PyObject *unicode) +{ + if (Py_FileSystemDefaultEncoding) + return PyUnicode_AsEncodedString(unicode, + Py_FileSystemDefaultEncoding, + "surrogateescape"); + else + return PyUnicode_EncodeUTF8(PyUnicode_AS_UNICODE(unicode), + PyUnicode_GET_SIZE(unicode), + "surrogateescape"); +} + PyObject *PyUnicode_AsEncodedString(PyObject *unicode, const char *encoding, const char *errors) @@ -1646,9 +1658,7 @@ arg = PyUnicode_FromObject(arg); if (!arg) return 0; - output = PyUnicode_AsEncodedObject(arg, - Py_FileSystemDefaultEncoding, - "surrogateescape"); + output = PyUnicode_EncodeFSDefault(arg); Py_DECREF(arg); if (!output) return 0; Modified: python/branches/py3k/Python/import.c ============================================================================== --- python/branches/py3k/Python/import.c (original) +++ python/branches/py3k/Python/import.c Sat May 15 18:27:27 2010 @@ -1633,8 +1633,7 @@ if (!v) return NULL; if (PyUnicode_Check(v)) { - v = PyUnicode_AsEncodedString(v, - Py_FileSystemDefaultEncoding, NULL); + v = PyUnicode_EncodeFSDefault(v); if (v == NULL) return NULL; } @@ -2752,14 +2751,7 @@ char *subname; PyObject *submod; char *p; - if (!Py_FileSystemDefaultEncoding) { - item8 = PyUnicode_EncodeASCII(PyUnicode_AsUnicode(item), - PyUnicode_GetSize(item), - NULL); - } else { - item8 = PyUnicode_AsEncodedString(item, - Py_FileSystemDefaultEncoding, NULL); - } + item8 = PyUnicode_EncodeFSDefault(item); if (!item8) { PyErr_SetString(PyExc_ValueError, "Cannot encode path item"); return 0; From python-checkins at python.org Sat May 15 18:28:22 2010 From: python-checkins at python.org (victor.stinner) Date: Sat, 15 May 2010 18:28:22 +0200 (CEST) Subject: [Python-checkins] r81195 - python/branches/release31-maint Message-ID: <20100515162822.6FD8FEEAE0@mail.python.org> Author: victor.stinner Date: Sat May 15 18:28:22 2010 New Revision: 81195 Log: Blocked revisions 81194 via svnmerge ........ r81194 | victor.stinner | 2010-05-15 18:27:27 +0200 (sam., 15 mai 2010) | 5 lines Issue #8715: Create PyUnicode_EncodeFSDefault() function: Encode a Unicode object to Py_FileSystemDefaultEncoding with the "surrogateescape" error handler, return a bytes object. If Py_FileSystemDefaultEncoding is not set, fall back to UTF-8. ........ Modified: python/branches/release31-maint/ (props changed) From python-checkins at python.org Sat May 15 19:02:39 2010 From: python-checkins at python.org (mark.dickinson) Date: Sat, 15 May 2010 19:02:39 +0200 (CEST) Subject: [Python-checkins] r81196 - in python/branches/py3k: Lib/test/test_math.py Misc/NEWS Modules/mathmodule.c Message-ID: <20100515170239.12C68EE9DB@mail.python.org> Author: mark.dickinson Date: Sat May 15 19:02:38 2010 New Revision: 81196 Log: Issue #8692: Improve performance of math.factorial: (1) use a different algorithm that roughly halves the total number of multiplications required and results in more balanced multiplications (2) use a lookup table for small arguments (3) fast accumulation of products in C integer arithmetic rather than PyLong arithmetic when possible. Typical speedup, from unscientific testing on a 64-bit laptop, is 4.5x to 6.5x for arguments in the range 100 - 10000. Patch by Daniel Stutzbach; extensive reviews by Alexander Belopolsky. Modified: python/branches/py3k/Lib/test/test_math.py python/branches/py3k/Misc/NEWS python/branches/py3k/Modules/mathmodule.c Modified: python/branches/py3k/Lib/test/test_math.py ============================================================================== --- python/branches/py3k/Lib/test/test_math.py (original) +++ python/branches/py3k/Lib/test/test_math.py Sat May 15 19:02:38 2010 @@ -60,6 +60,56 @@ return "error = {} ulps; permitted error = {} ulps".format(ulps_error, ulps) +# Here's a pure Python version of the math.factorial algorithm, for +# documentation and comparison purposes. +# +# Formula: +# +# factorial(n) = factorial_odd_part(n) << (n - count_set_bits(n)) +# +# where +# +# factorial_odd_part(n) = product_{i >= 0} product_{0 < j <= n >> i; j odd} j +# +# The outer product above is an infinite product, but once i >= n.bit_length, +# (n >> i) < 1 and the corresponding term of the product is empty. So only the +# finitely many terms for 0 <= i < n.bit_length() contribute anything. +# +# We iterate downwards from i == n.bit_length() - 1 to i == 0. The inner +# product in the formula above starts at 1 for i == n.bit_length(); for each i +# < n.bit_length() we get the inner product for i from that for i + 1 by +# multiplying by all j in {n >> i+1 < j <= n >> i; j odd}. In Python terms, +# this set is range((n >> i+1) + 1 | 1, (n >> i) + 1 | 1, 2). + +def count_set_bits(n): + """Number of '1' bits in binary expansion of a nonnnegative integer.""" + return 1 + count_set_bits(n & n - 1) if n else 0 + +def partial_product(start, stop): + """Product of integers in range(start, stop, 2), computed recursively. + start and stop should both be odd, with start <= stop. + + """ + numfactors = (stop - start) >> 1 + if not numfactors: + return 1 + elif numfactors == 1: + return start + else: + mid = (start + numfactors) | 1 + return partial_product(start, mid) * partial_product(mid, stop) + +def py_factorial(n): + """Factorial of nonnegative integer n, via "Binary Split Factorial Formula" + described at http://www.luschny.de/math/factorial/binarysplitfact.html + + """ + inner = outer = 1 + for i in reversed(range(n.bit_length())): + inner *= partial_product((n >> i + 1) + 1 | 1, (n >> i) + 1 | 1) + outer *= inner + return outer << (n - count_set_bits(n)) + def acc_check(expected, got, rel_err=2e-15, abs_err = 5e-323): """Determine whether non-NaN floats a and b are equal to within a (small) rounding error. The default values for rel_err and @@ -365,18 +415,19 @@ self.ftest('fabs(1)', math.fabs(1), 1) def testFactorial(self): - def fact(n): - result = 1 - for i in range(1, int(n)+1): - result *= i - return result - values = list(range(10)) + [50, 100, 500] - random.shuffle(values) - for x in values: - for cast in (int, float): - self.assertEqual(math.factorial(cast(x)), fact(x), (x, fact(x), math.factorial(x))) + self.assertEqual(math.factorial(0), 1) + self.assertEqual(math.factorial(0.0), 1) + total = 1 + for i in range(1, 1000): + total *= i + self.assertEqual(math.factorial(i), total) + self.assertEqual(math.factorial(float(i)), total) + self.assertEqual(math.factorial(i), py_factorial(i)) self.assertRaises(ValueError, math.factorial, -1) + self.assertRaises(ValueError, math.factorial, -1.0) self.assertRaises(ValueError, math.factorial, math.pi) + self.assertRaises(OverflowError, math.factorial, sys.maxsize+1) + self.assertRaises(OverflowError, math.factorial, 10e100) def testFloor(self): self.assertRaises(TypeError, math.floor) Modified: python/branches/py3k/Misc/NEWS ============================================================================== --- python/branches/py3k/Misc/NEWS (original) +++ python/branches/py3k/Misc/NEWS Sat May 15 19:02:38 2010 @@ -1132,6 +1132,12 @@ Extension Modules ----------------- +- Issue #8692: Optimize math.factorial: replace the previous naive + algorithm with an improved 'binary-split' algorithm that uses fewer + multiplications and allows many of the multiplications to be + performed using plain C integer arithmetic instead of PyLong + arithmetic. Also uses a lookup table for small arguments. + - Issue #8674: Fixed a number of incorrect or undefined-behaviour-inducing overflow checks in the audioop module. Modified: python/branches/py3k/Modules/mathmodule.c ============================================================================== --- python/branches/py3k/Modules/mathmodule.c (original) +++ python/branches/py3k/Modules/mathmodule.c Sat May 15 19:02:38 2010 @@ -1129,18 +1129,239 @@ Return an accurate floating point sum of values in the iterable.\n\ Assumes IEEE-754 floating point arithmetic."); +/* Return the smallest integer k such that n < 2**k, or 0 if n == 0. + * Equivalent to floor(lg(x))+1. Also equivalent to: bitwidth_of_type - + * count_leading_zero_bits(x) + */ + +/* XXX: This routine does more or less the same thing as + * bits_in_digit() in Objects/longobject.c. Someday it would be nice to + * consolidate them. On BSD, there's a library function called fls() + * that we could use, and GCC provides __builtin_clz(). + */ + +static unsigned long +bit_length(unsigned long n) +{ + unsigned long len = 0; + while (n != 0) { + ++len; + n >>= 1; + } + return len; +} + +static unsigned long +count_set_bits(unsigned long n) +{ + unsigned long count = 0; + while (n != 0) { + ++count; + n &= n - 1; /* clear least significant bit */ + } + return count; +} + +/* Divide-and-conquer factorial algorithm + * + * Based on the formula and psuedo-code provided at: + * http://www.luschny.de/math/factorial/binarysplitfact.html + * + * Faster algorithms exist, but they're more complicated and depend on + * a fast prime factoriazation algorithm. + * + * Notes on the algorithm + * ---------------------- + * + * factorial(n) is written in the form 2**k * m, with m odd. k and m are + * computed separately, and then combined using a left shift. + * + * The function factorial_odd_part computes the odd part m (i.e., the greatest + * odd divisor) of factorial(n), using the formula: + * + * factorial_odd_part(n) = + * + * product_{i >= 0} product_{0 < j <= n / 2**i, j odd} j + * + * Example: factorial_odd_part(20) = + * + * (1) * + * (1) * + * (1 * 3 * 5) * + * (1 * 3 * 5 * 7 * 9) + * (1 * 3 * 5 * 7 * 9 * 11 * 13 * 15 * 17 * 19) + * + * Here i goes from large to small: the first term corresponds to i=4 (any + * larger i gives an empty product), and the last term corresponds to i=0. + * Each term can be computed from the last by multiplying by the extra odd + * numbers required: e.g., to get from the penultimate term to the last one, + * we multiply by (11 * 13 * 15 * 17 * 19). + * + * To see a hint of why this formula works, here are the same numbers as above + * but with the even parts (i.e., the appropriate powers of 2) included. For + * each subterm in the product for i, we multiply that subterm by 2**i: + * + * factorial(20) = + * + * (16) * + * (8) * + * (4 * 12 * 20) * + * (2 * 6 * 10 * 14 * 18) * + * (1 * 3 * 5 * 7 * 9 * 11 * 13 * 15 * 17 * 19) + * + * The factorial_partial_product function computes the product of all odd j in + * range(start, stop) for given start and stop. It's used to compute the + * partial products like (11 * 13 * 15 * 17 * 19) in the example above. It + * operates recursively, repeatedly splitting the range into two roughly equal + * pieces until the subranges are small enough to be computed using only C + * integer arithmetic. + * + * The two-valuation k (i.e., the exponent of the largest power of 2 dividing + * the factorial) is computed independently in the main math_factorial + * function. By standard results, its value is: + * + * two_valuation = n//2 + n//4 + n//8 + .... + * + * It can be shown (e.g., by complete induction on n) that two_valuation is + * equal to n - count_set_bits(n), where count_set_bits(n) gives the number of + * '1'-bits in the binary expansion of n. + */ + +/* factorial_partial_product: Compute product(range(start, stop, 2)) using + * divide and conquer. Assumes start and stop are odd and stop > start. + * max_bits must be >= bit_length(stop - 2). */ + +static PyObject * +factorial_partial_product(unsigned long start, unsigned long stop, + unsigned long max_bits) +{ + unsigned long midpoint, num_operands; + PyObject *left = NULL, *right = NULL, *result = NULL; + + /* If the return value will fit an unsigned long, then we can + * multiply in a tight, fast loop where each multiply is O(1). + * Compute an upper bound on the number of bits required to store + * the answer. + * + * Storing some integer z requires floor(lg(z))+1 bits, which is + * conveniently the value returned by bit_length(z). The + * product x*y will require at most + * bit_length(x) + bit_length(y) bits to store, based + * on the idea that lg product = lg x + lg y. + * + * We know that stop - 2 is the largest number to be multiplied. From + * there, we have: bit_length(answer) <= num_operands * + * bit_length(stop - 2) + */ + + num_operands = (stop - start) / 2; + /* The "num_operands <= 8 * SIZEOF_LONG" check guards against the + * unlikely case of an overflow in num_operands * max_bits. */ + if (num_operands <= 8 * SIZEOF_LONG && + num_operands * max_bits <= 8 * SIZEOF_LONG) { + unsigned long j, total; + for (total = start, j = start + 2; j < stop; j += 2) + total *= j; + return PyLong_FromUnsignedLong(total); + } + + /* find midpoint of range(start, stop), rounded up to next odd number. */ + midpoint = (start + num_operands) | 1; + left = factorial_partial_product(start, midpoint, + bit_length(midpoint - 2)); + if (left == NULL) + goto error; + right = factorial_partial_product(midpoint, stop, max_bits); + if (right == NULL) + goto error; + result = PyNumber_Multiply(left, right); + + error: + Py_XDECREF(left); + Py_XDECREF(right); + return result; +} + +/* factorial_odd_part: compute the odd part of factorial(n). */ + +static PyObject * +factorial_odd_part(unsigned long n) +{ + long i; + unsigned long v, lower, upper; + PyObject *partial, *tmp, *inner, *outer; + + inner = PyLong_FromLong(1); + if (inner == NULL) + return NULL; + outer = inner; + Py_INCREF(outer); + + upper = 3; + for (i = bit_length(n) - 2; i >= 0; i--) { + v = n >> i; + if (v <= 2) + continue; + lower = upper; + /* (v + 1) | 1 = least odd integer strictly larger than n / 2**i */ + upper = (v + 1) | 1; + /* Here inner is the product of all odd integers j in the range (0, + n/2**(i+1)]. The factorial_partial_product call below gives the + product of all odd integers j in the range (n/2**(i+1), n/2**i]. */ + partial = factorial_partial_product(lower, upper, bit_length(upper-2)); + /* inner *= partial */ + if (partial == NULL) + goto error; + tmp = PyNumber_Multiply(inner, partial); + Py_DECREF(partial); + if (tmp == NULL) + goto error; + Py_DECREF(inner); + inner = tmp; + /* Now inner is the product of all odd integers j in the range (0, + n/2**i], giving the inner product in the formula above. */ + + /* outer *= inner; */ + tmp = PyNumber_Multiply(outer, inner); + if (tmp == NULL) + goto error; + Py_DECREF(outer); + outer = tmp; + } + + goto done; + + error: + Py_DECREF(outer); + done: + Py_DECREF(inner); + return outer; +} + +/* Lookup table for small factorial values */ + +static const unsigned long SmallFactorials[] = { + 1, 1, 2, 6, 24, 120, 720, 5040, 40320, + 362880, 3628800, 39916800, 479001600, +#if SIZEOF_LONG >= 8 + 6227020800, 87178291200, 1307674368000, + 20922789888000, 355687428096000, 6402373705728000, + 121645100408832000, 2432902008176640000 +#endif +}; + static PyObject * math_factorial(PyObject *self, PyObject *arg) { - long i, x; - PyObject *result, *iobj, *newresult; + long x; + PyObject *result, *odd_part, *two_valuation; if (PyFloat_Check(arg)) { PyObject *lx; double dx = PyFloat_AS_DOUBLE((PyFloatObject *)arg); if (!(Py_IS_FINITE(dx) && dx == floor(dx))) { PyErr_SetString(PyExc_ValueError, - "factorial() only accepts integral values"); + "factorial() only accepts integral values"); return NULL; } lx = PyLong_FromDouble(dx); @@ -1156,29 +1377,28 @@ return NULL; if (x < 0) { PyErr_SetString(PyExc_ValueError, - "factorial() not defined for negative values"); + "factorial() not defined for negative values"); return NULL; } - result = (PyObject *)PyLong_FromLong(1); - if (result == NULL) + /* use lookup table if x is small */ + if (x < (long)(sizeof(SmallFactorials)/sizeof(SmallFactorials[0]))) + return PyLong_FromUnsignedLong(SmallFactorials[x]); + + /* else express in the form odd_part * 2**two_valuation, and compute as + odd_part << two_valuation. */ + odd_part = factorial_odd_part(x); + if (odd_part == NULL) + return NULL; + two_valuation = PyLong_FromLong(x - count_set_bits(x)); + if (two_valuation == NULL) { + Py_DECREF(odd_part); return NULL; - for (i=1 ; i<=x ; i++) { - iobj = (PyObject *)PyLong_FromLong(i); - if (iobj == NULL) - goto error; - newresult = PyNumber_Multiply(result, iobj); - Py_DECREF(iobj); - if (newresult == NULL) - goto error; - Py_DECREF(result); - result = newresult; } + result = PyNumber_Lshift(odd_part, two_valuation); + Py_DECREF(two_valuation); + Py_DECREF(odd_part); return result; - -error: - Py_DECREF(result); - return NULL; } PyDoc_STRVAR(math_factorial_doc, From python-checkins at python.org Sat May 15 19:42:02 2010 From: python-checkins at python.org (benjamin.peterson) Date: Sat, 15 May 2010 19:42:02 +0200 (CEST) Subject: [Python-checkins] r81197 - python/branches/py3k/Doc/c-api/unicode.rst Message-ID: <20100515174202.6245DEEA5A@mail.python.org> Author: benjamin.peterson Date: Sat May 15 19:42:02 2010 New Revision: 81197 Log: fix run-on sentence Modified: python/branches/py3k/Doc/c-api/unicode.rst Modified: python/branches/py3k/Doc/c-api/unicode.rst ============================================================================== --- python/branches/py3k/Doc/c-api/unicode.rst (original) +++ python/branches/py3k/Doc/c-api/unicode.rst Sat May 15 19:42:02 2010 @@ -408,7 +408,7 @@ .. cfunction:: PyObject* PyUnicode_EncodeFSDefault(PyObject *unicode) Encode a Unicode object to :cdata:`Py_FileSystemDefaultEncoding` with the - ``'surrogateescape'`` error handler, return a :func:`bytes` object. + ``'surrogateescape'`` error handler, and return :class:`bytes`. If :cdata:`Py_FileSystemDefaultEncoding` is not set, fall back to UTF-8. From python-checkins at python.org Sat May 15 19:43:18 2010 From: python-checkins at python.org (benjamin.peterson) Date: Sat, 15 May 2010 19:43:18 +0200 (CEST) Subject: [Python-checkins] r81198 - python/branches/py3k/Include/unicodeobject.h Message-ID: <20100515174318.688B5EEA1C@mail.python.org> Author: benjamin.peterson Date: Sat May 15 19:43:18 2010 New Revision: 81198 Log: rephrase Modified: python/branches/py3k/Include/unicodeobject.h Modified: python/branches/py3k/Include/unicodeobject.h ============================================================================== --- python/branches/py3k/Include/unicodeobject.h (original) +++ python/branches/py3k/Include/unicodeobject.h Sat May 15 19:43:18 2010 @@ -1250,7 +1250,7 @@ If Py_FileSystemDefaultEncoding is not set, fall back to UTF-8. - Use PyUnicode_DecodeFSDefaultAndSize() if you have the string length. + Use PyUnicode_DecodeFSDefaultAndSize() if the string length is known. */ PyAPI_FUNC(PyObject*) PyUnicode_DecodeFSDefault( @@ -1269,7 +1269,7 @@ ); /* Encode a Unicode object to Py_FileSystemDefaultEncoding with the - "surrogateescape" error handler, return a bytes object. + "surrogateescape" error handler, and return bytes. If Py_FileSystemDefaultEncoding is not set, fall back to UTF-8. */ From python-checkins at python.org Sat May 15 19:43:57 2010 From: python-checkins at python.org (benjamin.peterson) Date: Sat, 15 May 2010 19:43:57 +0200 (CEST) Subject: [Python-checkins] r81199 - python/branches/py3k/Misc/NEWS Message-ID: <20100515174357.A63CCEEA87@mail.python.org> Author: benjamin.peterson Date: Sat May 15 19:43:57 2010 New Revision: 81199 Log: fix one more runon Modified: python/branches/py3k/Misc/NEWS Modified: python/branches/py3k/Misc/NEWS ============================================================================== --- python/branches/py3k/Misc/NEWS (original) +++ python/branches/py3k/Misc/NEWS Sat May 15 19:43:57 2010 @@ -14,8 +14,8 @@ - Issue #8715: Create PyUnicode_EncodeFSDefault() function: Encode a Unicode object to Py_FileSystemDefaultEncoding with the "surrogateescape" error - handler, return a bytes object. If Py_FileSystemDefaultEncoding is not set, - fall back to UTF-8. + handler, and return bytes. If Py_FileSystemDefaultEncoding is not set, fall + back to UTF-8. - Enable shortcuts for common encodings in PyUnicode_AsEncodedString() for any error handler, not only the default error handler (strict) From python-checkins at python.org Sat May 15 19:48:55 2010 From: python-checkins at python.org (benjamin.peterson) Date: Sat, 15 May 2010 19:48:55 +0200 (CEST) Subject: [Python-checkins] r81200 - python/trunk/Lib/test/test_signal.py Message-ID: <20100515174855.58FAAEEAE7@mail.python.org> Author: benjamin.peterson Date: Sat May 15 19:48:55 2010 New Revision: 81200 Log: use TestCase skip method Modified: python/trunk/Lib/test/test_signal.py Modified: python/trunk/Lib/test/test_signal.py ============================================================================== --- python/trunk/Lib/test/test_signal.py (original) +++ python/trunk/Lib/test/test_signal.py Sat May 15 19:48:55 2010 @@ -431,8 +431,8 @@ if signal.getitimer(self.itimer) == (0.0, 0.0): break # sig_vtalrm handler stopped this itimer else: # Issue 8424 - raise unittest.SkipTest("timeout: likely cause: machine too slow " - "or load too high") + self.skipTest("timeout: likely cause: machine too slow or load too " + "high") # virtual itimer should be (0.0, 0.0) now self.assertEquals(signal.getitimer(self.itimer), (0.0, 0.0)) @@ -454,8 +454,8 @@ if signal.getitimer(self.itimer) == (0.0, 0.0): break # sig_prof handler stopped this itimer else: # Issue 8424 - raise unittest.SkipTest("timeout: likely cause: machine too slow " - "or load too high") + self.skipTest("timeout: likely cause: machine too slow or load too " + "high") # profiling itimer should be (0.0, 0.0) now self.assertEquals(signal.getitimer(self.itimer), (0.0, 0.0)) From python-checkins at python.org Sat May 15 19:52:13 2010 From: python-checkins at python.org (benjamin.peterson) Date: Sat, 15 May 2010 19:52:13 +0200 (CEST) Subject: [Python-checkins] r81201 - in python/branches/py3k: Lib/test/test_signal.py Message-ID: <20100515175213.17AD5EEA05@mail.python.org> Author: benjamin.peterson Date: Sat May 15 19:52:12 2010 New Revision: 81201 Log: Merged revisions 81200 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r81200 | benjamin.peterson | 2010-05-15 12:48:55 -0500 (Sat, 15 May 2010) | 1 line use TestCase skip method ........ Modified: python/branches/py3k/ (props changed) python/branches/py3k/Lib/test/test_signal.py Modified: python/branches/py3k/Lib/test/test_signal.py ============================================================================== --- python/branches/py3k/Lib/test/test_signal.py (original) +++ python/branches/py3k/Lib/test/test_signal.py Sat May 15 19:52:12 2010 @@ -431,8 +431,8 @@ if signal.getitimer(self.itimer) == (0.0, 0.0): break # sig_vtalrm handler stopped this itimer else: # Issue 8424 - raise unittest.SkipTest("timeout: likely cause: machine too slow " - "or load too high") + self.skipTest("timeout: likely cause: machine too slow or load too " + "high") # virtual itimer should be (0.0, 0.0) now self.assertEquals(signal.getitimer(self.itimer), (0.0, 0.0)) @@ -454,8 +454,8 @@ if signal.getitimer(self.itimer) == (0.0, 0.0): break # sig_prof handler stopped this itimer else: # Issue 8424 - raise unittest.SkipTest("timeout: likely cause: machine too slow " - "or load too high") + self.skipTest("timeout: likely cause: machine too slow or load too " + "high") # profiling itimer should be (0.0, 0.0) now self.assertEquals(signal.getitimer(self.itimer), (0.0, 0.0)) From python-checkins at python.org Sat May 15 20:00:56 2010 From: python-checkins at python.org (benjamin.peterson) Date: Sat, 15 May 2010 20:00:56 +0200 (CEST) Subject: [Python-checkins] r81202 - in python/branches/release31-maint: Lib/test/test_signal.py Message-ID: <20100515180056.37BE6EEA1C@mail.python.org> Author: benjamin.peterson Date: Sat May 15 20:00:56 2010 New Revision: 81202 Log: Merged revisions 81201 via svnmerge from svn+ssh://pythondev at svn.python.org/python/branches/py3k ................ r81201 | benjamin.peterson | 2010-05-15 12:52:12 -0500 (Sat, 15 May 2010) | 9 lines Merged revisions 81200 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r81200 | benjamin.peterson | 2010-05-15 12:48:55 -0500 (Sat, 15 May 2010) | 1 line use TestCase skip method ........ ................ Modified: python/branches/release31-maint/ (props changed) python/branches/release31-maint/Lib/test/test_signal.py Modified: python/branches/release31-maint/Lib/test/test_signal.py ============================================================================== --- python/branches/release31-maint/Lib/test/test_signal.py (original) +++ python/branches/release31-maint/Lib/test/test_signal.py Sat May 15 20:00:56 2010 @@ -431,8 +431,8 @@ if signal.getitimer(self.itimer) == (0.0, 0.0): break # sig_vtalrm handler stopped this itimer else: # Issue 8424 - raise unittest.SkipTest("timeout: likely cause: machine too slow " - "or load too high") + self.skipTest("timeout: likely cause: machine too slow or load too " + "high") # virtual itimer should be (0.0, 0.0) now self.assertEquals(signal.getitimer(self.itimer), (0.0, 0.0)) @@ -454,8 +454,8 @@ if signal.getitimer(self.itimer) == (0.0, 0.0): break # sig_prof handler stopped this itimer else: # Issue 8424 - raise unittest.SkipTest("timeout: likely cause: machine too slow " - "or load too high") + self.skipTest("timeout: likely cause: machine too slow or load too " + "high") # profiling itimer should be (0.0, 0.0) now self.assertEquals(signal.getitimer(self.itimer), (0.0, 0.0)) From python-checkins at python.org Sat May 15 22:33:07 2010 From: python-checkins at python.org (antoine.pitrou) Date: Sat, 15 May 2010 22:33:07 +0200 (CEST) Subject: [Python-checkins] r81203 - in python/branches/release26-maint: Lib/io.py Lib/test/test_io.py Misc/NEWS Message-ID: <20100515203307.95BD4EE9A4@mail.python.org> Author: antoine.pitrou Date: Sat May 15 22:33:07 2010 New Revision: 81203 Log: Issue #7640: In the new `io` module, fix relative seek() for buffered readable streams when the internal buffer isn't empty. Patch by Pascal Chambon. Modified: python/branches/release26-maint/Lib/io.py python/branches/release26-maint/Lib/test/test_io.py python/branches/release26-maint/Misc/NEWS Modified: python/branches/release26-maint/Lib/io.py ============================================================================== --- python/branches/release26-maint/Lib/io.py (original) +++ python/branches/release26-maint/Lib/io.py Sat May 15 22:33:07 2010 @@ -1199,6 +1199,10 @@ self.flush() # First do the raw seek, then empty the read buffer, so that # if the raw seek fails, we don't lose buffered data forever. + if self._read_buf and whence == 1: + # Undo read ahead. + with self._read_lock: + self.raw.seek(self._read_pos - len(self._read_buf), 1) pos = self.raw.seek(pos, whence) with self._read_lock: self._reset_read_buf() Modified: python/branches/release26-maint/Lib/test/test_io.py ============================================================================== --- python/branches/release26-maint/Lib/test/test_io.py (original) +++ python/branches/release26-maint/Lib/test/test_io.py Sat May 15 22:33:07 2010 @@ -107,6 +107,10 @@ self.assertEqual(f.truncate(12), 12) self.assertEqual(f.tell(), 13) + self.assertEqual(f.write(b"hij"), 3) + self.assertEqual(f.seek(0,1), 16) + self.assertEqual(f.tell(), 16) + self.assertEqual(f.truncate(12), 12) self.assertRaises(TypeError, f.seek, 0.0) def read_ops(self, f, buffered=False): @@ -129,6 +133,10 @@ self.assertEqual(f.seek(-6, 1), 5) self.assertEqual(f.read(5), b" worl") self.assertEqual(f.tell(), 10) + f.seek(0) + f.read(2) + f.seek(0, 1) + self.assertEqual(f.tell(), 2) self.assertRaises(TypeError, f.seek, 0.0) if buffered: f.seek(0) @@ -182,6 +190,13 @@ self.assertEqual(f.writable(), False) self.assertEqual(f.seekable(), True) self.read_ops(f, True) + f = io.open(test_support.TESTFN, "r+b") + self.assertEqual(f.readable(), True) + self.assertEqual(f.writable(), True) + self.assertEqual(f.seekable(), True) + self.write_ops(f) + f.seek(0) + self.read_ops(f, True) f.close() def test_readline(self): @@ -513,7 +528,7 @@ self.assertEquals(b"abcdefghijkl", writer._write_stack[0]) def testWriteNonBlocking(self): - raw = MockNonBlockWriterIO((9, 2, 22, -6, 10, 12, 12)) + raw = MockNonBlockWriterIO((9, 2, 10, -6, 10, 8, 12)) bufio = io.BufferedWriter(raw, 8, 16) bufio.write(b"asdf") Modified: python/branches/release26-maint/Misc/NEWS ============================================================================== --- python/branches/release26-maint/Misc/NEWS (original) +++ python/branches/release26-maint/Misc/NEWS Sat May 15 22:33:07 2010 @@ -39,6 +39,10 @@ Library ------- +- Issue #7640: In the new `io` module, fix relative seek() for buffered + readable streams when the internal buffer isn't empty. Patch by Pascal + Chambon. + - Issue #5099: subprocess.Popen.__del__ no longer references global objects, leading to issues during interpreter shutdown. From python-checkins at python.org Sat May 15 22:35:12 2010 From: python-checkins at python.org (amaury.forgeotdarc) Date: Sat, 15 May 2010 22:35:12 +0200 (CEST) Subject: [Python-checkins] r81204 - python/branches/py3k/Modules/posixmodule.c Message-ID: <20100515203512.DE966EEB0F@mail.python.org> Author: amaury.forgeotdarc Date: Sat May 15 22:35:12 2010 New Revision: 81204 Log: Remove unused variable, and fix a compilation warning on Windows. Modified: python/branches/py3k/Modules/posixmodule.c Modified: python/branches/py3k/Modules/posixmodule.c ============================================================================== --- python/branches/py3k/Modules/posixmodule.c (original) +++ python/branches/py3k/Modules/posixmodule.c Sat May 15 22:35:12 2010 @@ -4062,7 +4062,7 @@ static PyObject * win32_kill(PyObject *self, PyObject *args) { - PyObject *result, handle_obj; + PyObject *result; DWORD pid, sig, err; HANDLE handle; From python-checkins at python.org Sat May 15 23:01:00 2010 From: python-checkins at python.org (victor.stinner) Date: Sat, 15 May 2010 23:01:00 +0200 (CEST) Subject: [Python-checkins] r81205 - python/trunk/Misc/NEWS Message-ID: <20100515210100.1608BEE9BF@mail.python.org> Author: victor.stinner Date: Sat May 15 23:00:59 2010 New Revision: 81205 Log: NEWS: strip trailing spaces Modified: python/trunk/Misc/NEWS Modified: python/trunk/Misc/NEWS ============================================================================== --- python/trunk/Misc/NEWS (original) +++ python/trunk/Misc/NEWS Sat May 15 23:00:59 2010 @@ -83,9 +83,9 @@ - Issue #8573: asyncore _strerror() function might throw ValueError. -- Issue #8483: asyncore.dispatcher's __getattr__ method produced confusing - error messages when accessing undefined class attributes because of the cheap - inheritance with the underlying socket object. +- Issue #8483: asyncore.dispatcher's __getattr__ method produced confusing + error messages when accessing undefined class attributes because of the cheap + inheritance with the underlying socket object. The cheap inheritance has been deprecated. - Issue #4265: shutil.copyfile() was leaking file descriptors when disk fills. @@ -120,7 +120,7 @@ - Issue #7192: webbrowser.get("firefox") now wors on Mac OS X, as does webbrowser.get("safari"). -- Issue #8577: distutils.sysconfig.get_python_inc() now makes a difference +- Issue #8577: distutils.sysconfig.get_python_inc() now makes a difference between the build dir and the source dir when looking for "python.h" or "Include". @@ -235,7 +235,7 @@ handled by a decompressor object without errors (it returns incomplete uncompressed data). -- Issue #8490: asyncore now has a more solid test suite which actually tests +- Issue #8490: asyncore now has a more solid test suite which actually tests its API. - Issue #8576: Remove use of find_unused_port() in test_smtplib and @@ -454,7 +454,7 @@ - Addition of -b command line option to unittest for buffering stdout / stderr during test runs. -- Issue #1220212: Added os.kill support for Windows, including support for +- Issue #1220212: Added os.kill support for Windows, including support for sending CTRL+C and CTRL+BREAK events to console subprocesses. Extension Modules @@ -485,7 +485,7 @@ and the set of integer codes for which it was used differed between native packing and standard packing.) -- Issue #7347: _winreg: Add CreateKeyEx and DeleteKeyEx, as well as fix a +- Issue #7347: _winreg: Add CreateKeyEx and DeleteKeyEx, as well as fix a bug in the return value of QueryReflectionKey. Tools/Demos From python-checkins at python.org Sat May 15 23:03:33 2010 From: python-checkins at python.org (victor.stinner) Date: Sat, 15 May 2010 23:03:33 +0200 (CEST) Subject: [Python-checkins] r81206 - in python/branches/release26-maint: Misc/NEWS Message-ID: <20100515210333.DAFEDEEB0E@mail.python.org> Author: victor.stinner Date: Sat May 15 23:03:33 2010 New Revision: 81206 Log: Recorded merge of revisions 81205 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r81205 | victor.stinner | 2010-05-15 23:00:59 +0200 (sam., 15 mai 2010) | 2 lines NEWS: strip trailing spaces ........ Modified: python/branches/release26-maint/ (props changed) python/branches/release26-maint/Misc/NEWS Modified: python/branches/release26-maint/Misc/NEWS ============================================================================== --- python/branches/release26-maint/Misc/NEWS (original) +++ python/branches/release26-maint/Misc/NEWS Sat May 15 23:03:33 2010 @@ -58,8 +58,8 @@ - Issue #8573: asyncore _strerror() function might throw ValueError. -- Issue #8483: asyncore.dispatcher's __getattr__ method produced confusing - error messages when accessing undefined class attributes because of the cheap +- Issue #8483: asyncore.dispatcher's __getattr__ method produced confusing + error messages when accessing undefined class attributes because of the cheap inheritance with the underlying socket object. - Issue #4265: shutil.copyfile() was leaking file descriptors when disk fills. @@ -89,7 +89,7 @@ - Issue #8354: The siginterrupt setting is now preserved for all signals, not just SIGCHLD. -- Issue #8577: distutils.sysconfig.get_python_inc() now makes a difference +- Issue #8577: distutils.sysconfig.get_python_inc() now makes a difference between the build dir and the source dir when looking for "python.h" or "Include". @@ -239,7 +239,7 @@ - Reverting the changes made in r78432. Discussed in the tracker issue #7540. -- Issue #8107: Fixed test_distutils so it doesn't crash when the source +- Issue #8107: Fixed test_distutils so it doesn't crash when the source directory cannot be found. Extension Modules @@ -416,7 +416,7 @@ - Fix variations of extending deques: d.extend(d) d.extendleft(d) d+=d -- Issue #1923: Fixed the removal of meaningful spaces when PKG-INFO is +- Issue #1923: Fixed the removal of meaningful spaces when PKG-INFO is generated in Distutils. Patch by Stephen Emslie. - Issue #4120: Drop reference to CRT from manifest when building extensions @@ -535,7 +535,7 @@ Documentation ------------- - + - Updating `Using Python` documentation to include description of CPython's -J, -U and -X options. @@ -551,7 +551,7 @@ - Issue #7498: test_multiprocessing now uses test_support.find_unused_port instead of a hardcoded port number in test_rapid_restart. -- Issue #7431: use TESTFN in test_linecache instead of trying to create a +- Issue #7431: use TESTFN in test_linecache instead of trying to create a file in the Lib/test directory, which might be read-only for the user running the tests. @@ -1106,7 +1106,7 @@ - Issue #5387: Fixed mmap.move crash by integer overflow. -- Issue #3807: _multiprocessing build fails when configure is passed +- Issue #3807: _multiprocessing build fails when configure is passed --without-threads argument. When this occurs, _multiprocessing will be disabled, and not compiled. From python-checkins at python.org Sat May 15 23:04:43 2010 From: python-checkins at python.org (victor.stinner) Date: Sat, 15 May 2010 23:04:43 +0200 (CEST) Subject: [Python-checkins] r81207 - in python/branches/py3k: Misc/NEWS Message-ID: <20100515210443.BEE8FEEB2A@mail.python.org> Author: victor.stinner Date: Sat May 15 23:04:43 2010 New Revision: 81207 Log: Recorded merge of revisions 81205 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r81205 | victor.stinner | 2010-05-15 23:00:59 +0200 (sam., 15 mai 2010) | 2 lines NEWS: strip trailing spaces ........ Modified: python/branches/py3k/ (props changed) python/branches/py3k/Misc/NEWS Modified: python/branches/py3k/Misc/NEWS ============================================================================== --- python/branches/py3k/Misc/NEWS (original) +++ python/branches/py3k/Misc/NEWS Sat May 15 23:04:43 2010 @@ -389,9 +389,9 @@ - Issue #8573: asyncore _strerror() function might throw ValueError. -- Issue #8483: asyncore.dispatcher's __getattr__ method produced confusing - error messages when accessing undefined class attributes because of the cheap - inheritance with the underlying socket object. +- Issue #8483: asyncore.dispatcher's __getattr__ method produced confusing + error messages when accessing undefined class attributes because of the cheap + inheritance with the underlying socket object. The cheap inheritance has been deprecated. - Issue #4265: shutil.copyfile() was leaking file descriptors when disk fills. @@ -488,7 +488,7 @@ - Issue #6547: Added the ignore_dangling_symlinks option to shutil.copytree. -- Issue #1540112: Now allowing the choice of a copy function in +- Issue #1540112: Now allowing the choice of a copy function in shutil.copytree. - Issue #4814: timeout parameter is now applied also for connections resulting @@ -803,7 +803,7 @@ Initial patch by Brian Curtin. - Issue #7556: Make sure Distutils' msvc9compile reads and writes the - MSVC XML Manifest file in text mode so string patterns can be used + MSVC XML Manifest file in text mode so string patterns can be used in regular expressions. - Issue #7552: Removed line feed in the base64 Authorization header in @@ -834,13 +834,13 @@ - Issue #6986: Fix crash in the JSON C accelerator when called with the wrong parameter types. Patch by Victor Stinner. -- Issue #7457: added a read_pkg_file method to +- Issue #7457: added a read_pkg_file method to distutils.dist.DistributionMetadata. - logging: Added optional `secure` parameter to SMTPHandler, to enable use of TLS with authentication credentials. -- Issue #1923: Fixed the removal of meaningful spaces when PKG-INFO is +- Issue #1923: Fixed the removal of meaningful spaces when PKG-INFO is generated in Distutils. Patch by Stephen Emslie. - Issue #4120: Drop reference to CRT from manifest when building extensions with @@ -878,7 +878,7 @@ - Issue #6123: tarfile now opens empty archives correctly and consistently raises ReadError on empty files. -- Issue #7354: distutils.tests.test_msvc9compiler - dragfullwindows can +- Issue #7354: distutils.tests.test_msvc9compiler - dragfullwindows can be 2. - Issue #5037: Proxy the __bytes__ special method instead to __bytes__ instead @@ -916,12 +916,12 @@ - Issue #7893: ``unittest.TextTestResult`` is made public and a ``resultclass`` argument added to the TextTestRunner constructor allowing a different result class to be used without having to subclass. - + - Issue 7588: ``unittest.TextTestResult.getDescription`` now includes the test name in failure reports even if the test has a docstring. - Issue #3001: Add a C implementation of recursive locks which is used by - default when instantiating a `threading.RLock` object. This makes + default when instantiating a `threading.RLock` object. This makes recursive locks as fast as regular non-recursive locks (previously, they were slower by 10x to 15x). @@ -1367,7 +1367,7 @@ - Issue #7498: test_multiprocessing now uses test.support.find_unused_port instead of a hardcoded port number in test_rapid_restart. -- Issue #7431: use TESTFN in test_linecache instead of trying to create a +- Issue #7431: use TESTFN in test_linecache instead of trying to create a file in the Lib/test directory, which might be read-only for the user running the tests. @@ -2251,7 +2251,7 @@ - Issue #7071: byte-compilation in Distutils is now done with respect to sys.dont_write_bytecode. -- Issue #7066: archive_util.make_archive now restores the cwd if an error is +- Issue #7066: archive_util.make_archive now restores the cwd if an error is raised. Initial patch by Ezio Melotti. - Issue #6516: Added owner/group support when creating tar archives in From python-checkins at python.org Sat May 15 23:05:33 2010 From: python-checkins at python.org (victor.stinner) Date: Sat, 15 May 2010 23:05:33 +0200 (CEST) Subject: [Python-checkins] r81208 - in python/branches/release31-maint: Misc/NEWS Message-ID: <20100515210533.D81AFEEB1F@mail.python.org> Author: victor.stinner Date: Sat May 15 23:05:33 2010 New Revision: 81208 Log: Recorded merge of revisions 81207 via svnmerge from svn+ssh://pythondev at svn.python.org/python/branches/py3k ................ r81207 | victor.stinner | 2010-05-15 23:04:43 +0200 (sam., 15 mai 2010) | 9 lines Recorded merge of revisions 81205 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r81205 | victor.stinner | 2010-05-15 23:00:59 +0200 (sam., 15 mai 2010) | 2 lines NEWS: strip trailing spaces ........ ................ Modified: python/branches/release31-maint/ (props changed) python/branches/release31-maint/Misc/NEWS Modified: python/branches/release31-maint/Misc/NEWS ============================================================================== --- python/branches/release31-maint/Misc/NEWS (original) +++ python/branches/release31-maint/Misc/NEWS Sat May 15 23:05:33 2010 @@ -55,8 +55,8 @@ - Issue #8573: asyncore _strerror() function might throw ValueError. -- Issue #8483: asyncore.dispatcher's __getattr__ method produced confusing - error messages when accessing undefined class attributes because of the cheap +- Issue #8483: asyncore.dispatcher's __getattr__ method produced confusing + error messages when accessing undefined class attributes because of the cheap inheritance with the underlying socket object. - Issue #7472: Fixed typo in email.encoders module; messages using ISO-2022 @@ -426,7 +426,7 @@ opening an empty or very small file. - Issue #7556: Make sure Distutils' msvc9compile reads and writes the - MSVC XML Manifest file in text mode so string patterns can be used + MSVC XML Manifest file in text mode so string patterns can be used in regular expressions. - Issue #7552: Removed line feed in the base64 Authorization header in @@ -452,7 +452,7 @@ - Issue #6986: Fix crash in the JSON C accelerator when called with the wrong parameter types. Patch by Victor Stinner. -- Issue #1923: Fixed the removal of meaningful spaces when PKG-INFO is +- Issue #1923: Fixed the removal of meaningful spaces when PKG-INFO is generated in Distutils. Patch by Stephen Emslie. - Issue #4120: Drop reference to CRT from manifest when building extensions with @@ -466,7 +466,7 @@ - Issue #1488943: difflib.Differ() doesn't always add hints for tab characters -- Issue #7354: distutils.tests.test_msvc9compiler - dragfullwindows can +- Issue #7354: distutils.tests.test_msvc9compiler - dragfullwindows can be 2. - Issue #3976: pprint for sets, frozensets, and dicts now succeed when @@ -530,7 +530,7 @@ - Issue #5833: Fix extra space character in readline completion with the GNU readline library version 6.0. -- Issue #6894: Fixed the issue urllib2 doesn't respect "no_proxy" environment +- Issue #6894: Fixed the issue urllib2 doesn't respect "no_proxy" environment - Issue #7082: When falling back to the MIME 'name' parameter, the correct place to look for it is the Content-Type header. @@ -625,7 +625,7 @@ - Issue #7498: test_multiprocessing now uses test.support.find_unused_port instead of a hardcoded port number in test_rapid_restart. -- Issue #7431: use TESTFN in test_linecache instead of trying to create a +- Issue #7431: use TESTFN in test_linecache instead of trying to create a file in the Lib/test directory, which might be read-only for the user running the tests. @@ -685,7 +685,7 @@ - Issue #6802: Fix build issues on MacOSX 10.6 - Issue #6801 : symmetric_difference_update also accepts |. - Thanks to Carl Chenet. + Thanks to Carl Chenet. - Issue #7541: when using ``python-config`` with a framework install the compiler might use the wrong library. @@ -760,7 +760,7 @@ occur when writing to a BufferedRandom object (e.g. a file opened in "rb+" or "wb+" mode) after having buffered a certain amount of data for reading. This bug was not present in the pure Python implementation. - + - Issue #6622: Fix "local variable 'secret' referenced before assignment" bug in POP3.apop. @@ -893,7 +893,7 @@ ------- - Issue #6438: Fixed distutils.cygwinccompiler.get_versions : the regular -expression string pattern was trying to match against a bytes returned by +expression string pattern was trying to match against a bytes returned by Popen. Tested under win32 to build the py-postgresql project. - Issue #6258: Support AMD64 in bdist_msi. @@ -1652,21 +1652,21 @@ Library ------- -- Issue #6545: Removed assert statements in distutils.Extension, so the +- Issue #6545: Removed assert statements in distutils.Extension, so the behavior is similar when used with -O. -- Issue #6459: distutils.command.build_ext.get_export_symbols now uses the - "PyInit" prefix, rather than "init". +- Issue #6459: distutils.command.build_ext.get_export_symbols now uses the + "PyInit" prefix, rather than "init". - Issue #6433: fixed issues with multiprocessing.pool.map hanging on empty list -- Issue #6455: Fixed test_build_ext under win32. +- Issue #6455: Fixed test_build_ext under win32. - Issue #6413: Fixed the log level in distutils.dist for announce. - Issue #6403: Fixed package path usage in build_ext. -- Issue #6365: Distutils build_ext inplace mode was copying the compiled +- Issue #6365: Distutils build_ext inplace mode was copying the compiled extension in a subdirectory if the extension name had dots. - Issue #6287: Added the license field in Distutils documentation. From python-checkins at python.org Sat May 15 23:34:28 2010 From: python-checkins at python.org (antoine.pitrou) Date: Sat, 15 May 2010 23:34:28 +0200 (CEST) Subject: [Python-checkins] r81209 - python/branches/py3k/Makefile.pre.in Message-ID: <20100515213428.10871EE987@mail.python.org> Author: antoine.pitrou Date: Sat May 15 23:34:27 2010 New Revision: 81209 Log: Issue #8665: Fix `make pycremoval` exiting with non-zero status. Modified: python/branches/py3k/Makefile.pre.in Modified: python/branches/py3k/Makefile.pre.in ============================================================================== --- python/branches/py3k/Makefile.pre.in (original) +++ python/branches/py3k/Makefile.pre.in Sat May 15 23:34:27 2010 @@ -1165,7 +1165,7 @@ # files, which clobber removes as well pycremoval: -find $(srcdir) -name '*.py[co]' -exec rm -f {} ';' - -find $(srcdir) -name '__pycache__' -exec rmdir {} ';' + -find $(srcdir) -name '__pycache__' -exec rmdir {} '+' rmtestturds: -rm -f *BAD *GOOD *SKIPPED From python-checkins at python.org Sat May 15 23:45:30 2010 From: python-checkins at python.org (amaury.forgeotdarc) Date: Sat, 15 May 2010 23:45:30 +0200 (CEST) Subject: [Python-checkins] r81210 - python/trunk/Modules/posixmodule.c Message-ID: <20100515214530.957E5EEA86@mail.python.org> Author: amaury.forgeotdarc Date: Sat May 15 23:45:30 2010 New Revision: 81210 Log: Remove unused variable, and fix a compilation warning on Windows Modified: python/trunk/Modules/posixmodule.c Modified: python/trunk/Modules/posixmodule.c ============================================================================== --- python/trunk/Modules/posixmodule.c (original) +++ python/trunk/Modules/posixmodule.c Sat May 15 23:45:30 2010 @@ -4083,7 +4083,7 @@ static PyObject * win32_kill(PyObject *self, PyObject *args) { - PyObject *result, handle_obj; + PyObject *result; DWORD pid, sig, err; HANDLE handle; From python-checkins at python.org Sat May 15 23:49:45 2010 From: python-checkins at python.org (amaury.forgeotdarc) Date: Sat, 15 May 2010 23:49:45 +0200 (CEST) Subject: [Python-checkins] r81211 - python/branches/py3k Message-ID: <20100515214945.333DDEE9B4@mail.python.org> Author: amaury.forgeotdarc Date: Sat May 15 23:49:45 2010 New Revision: 81211 Log: Blocked revisions 81210 via svnmerge ........ r81210 | amaury.forgeotdarc | 2010-05-15 23:45:30 +0200 (sam., 15 mai 2010) | 2 lines Remove unused variable, and fix a compilation warning on Windows ........ Modified: python/branches/py3k/ (props changed) From python-checkins at python.org Sun May 16 00:01:20 2010 From: python-checkins at python.org (stefan.krah) Date: Sun, 16 May 2010 00:01:20 +0200 (CEST) Subject: [Python-checkins] r81212 - in python/branches/py3k-cdecimal: Doc/c-api/list.rst Doc/c-api/unicode.rst Doc/howto/cporting.rst Doc/library/imp.rst Doc/library/pkgutil.rst Doc/library/runpy.rst Doc/library/sys.rst Doc/library/wsgiref.rst Doc/library/zipimport.rst Include/unicodeobject.h Lib/subprocess.py Lib/test/test_capi.py Lib/test/test_math.py Lib/test/test_signal.py Lib/test/test_site.py Lib/test/test_urlparse.py Lib/urllib/parse.py Makefile.pre.in Misc/NEWS Modules/_io/fileio.c Modules/_ssl.c Modules/_testcapimodule.c Modules/_tkinter.c Modules/grpmodule.c Modules/mathmodule.c Modules/posixmodule.c Modules/pwdmodule.c Modules/spwdmodule.c Objects/unicodeobject.c Python/bltinmodule.c Python/dtoa.c Python/errors.c Python/import.c Python/pythonrun.c Message-ID: <20100515220120.231C8EE9A9@mail.python.org> Author: stefan.krah Date: Sun May 16 00:01:19 2010 New Revision: 81212 Log: Merged revisions 81116,81127,81132,81134,81136,81138,81142,81146,81153,81155-81156,81165,81168,81170,81181,81183,81188,81190,81192,81194,81196-81199,81201,81204,81207,81209,81211 via svnmerge from svn+ssh://pythondev at svn.python.org/python/branches/py3k ................ r81116 | antoine.pitrou | 2010-05-12 16:05:24 +0200 (Wed, 12 May 2010) | 9 lines Merged revisions 81115 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r81115 | antoine.pitrou | 2010-05-12 16:02:34 +0200 (mer., 12 mai 2010) | 3 lines Improve _ssl.c formatting ........ ................ r81127 | mark.dickinson | 2010-05-12 21:54:51 +0200 (Wed, 12 May 2010) | 9 lines Merged revisions 81126 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r81126 | mark.dickinson | 2010-05-12 20:53:36 +0100 (Wed, 12 May 2010) | 1 line Fix unused variable in test_factorial. ........ ................ r81132 | senthil.kumaran | 2010-05-13 05:37:23 +0200 (Thu, 13 May 2010) | 9 lines Merged revisions 81130 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r81130 | senthil.kumaran | 2010-05-13 08:55:21 +0530 (Thu, 13 May 2010) | 3 lines Fix Issue8657 - adding git and git+ssh as know schemes. ........ ................ r81134 | mark.dickinson | 2010-05-13 13:52:22 +0200 (Thu, 13 May 2010) | 1 line Remove unnecessary assignments. ................ r81136 | victor.stinner | 2010-05-13 18:20:26 +0200 (Thu, 13 May 2010) | 12 lines Blocked revisions 81135 via svnmerge (r81135 is a merge of r80163 from py3k) ........ r81135 | victor.stinner | 2010-05-13 18:18:14 +0200 (jeu., 13 mai 2010) | 6 lines Issue #8422, test_genericpath: skip the creation of a directory with an invalid UTF name on Mac OS X because the OS deny it (the name have to be a valid UTF8 string). Merge r80163 from py3k branch. ........ ................ r81138 | victor.stinner | 2010-05-13 18:23:09 +0200 (Thu, 13 May 2010) | 10 lines Blocked revisions 81137 via svnmerge ........ r81137 | victor.stinner | 2010-05-13 18:22:15 +0200 (jeu., 13 mai 2010) | 4 lines Fix verb tense in skip message. Ooops, merge also r80334 (patch by r.david.murray) ........ ................ r81142 | jeffrey.yasskin | 2010-05-13 20:31:05 +0200 (Thu, 13 May 2010) | 6 lines Make PyErr_Occurred return NULL if there is no current thread. Previously it would Py_FatalError, which called PyErr_Occurred, resulting in a semi-infinite recursion. Fixes issue 3605. ................ r81146 | benjamin.peterson | 2010-05-13 23:16:51 +0200 (Thu, 13 May 2010) | 9 lines Merged revisions 81145 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r81145 | benjamin.peterson | 2010-05-13 16:14:10 -0500 (Thu, 13 May 2010) | 1 line rip out mention of types.ListType #8703 ........ ................ r81153 | brett.cannon | 2010-05-14 02:04:56 +0200 (Fri, 14 May 2010) | 10 lines Merged revisions 81152 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r81152 | brett.cannon | 2010-05-13 16:59:41 -0700 (Thu, 13 May 2010) | 3 lines test_site was failing under darwin for non-framework builds because a test was assuming framework-specific site-packages directories were being used. ........ ................ r81155 | brett.cannon | 2010-05-14 02:33:40 +0200 (Fri, 14 May 2010) | 22 lines Merged revisions 81154 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r81154 | brett.cannon | 2010-05-13 17:21:48 -0700 (Thu, 13 May 2010) | 15 lines subprocess.Popen.__del__ referenced global objects, which is a no-no thanks to interpreter shutdown semantics. Same issue goes for the methods that __del__ called. Now all the methods capture the global objects it needs as default values to private parameters (could have stuck them on the class object itself, but since the objects have nothing directly to do with the class that seemed wrong). There is no test as making one that works is hard. This patch was verified against a consistently failing test in Mercurial's test suite, though, so it has been tested in some regard. Closes issue #5099. Thanks to Mary Stern for the bug report and Gabriel Genellina for writing another patch for the same issue and attempting to write a test. ........ ................ r81156 | victor.stinner | 2010-05-14 02:59:09 +0200 (Fri, 14 May 2010) | 5 lines Issue #4653: fix typo in flush_std_files() Don't call sys.stderr.flush() if sys has no stderr attribute or if sys.stderr==None. ................ r81165 | victor.stinner | 2010-05-14 16:36:18 +0200 (Fri, 14 May 2010) | 9 lines Merged revisions 81163 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r81163 | victor.stinner | 2010-05-14 16:20:07 +0200 (ven., 14 mai 2010) | 2 lines Doc: replace PEP xxx by :pep:`xxx` to create a link on the PEP ........ ................ r81168 | victor.stinner | 2010-05-14 17:58:55 +0200 (Fri, 14 May 2010) | 10 lines Issue #8711: Document PyUnicode_DecodeFSDefault*() functions * Add paragraph titles to c-api/unicode.rst. * Fix PyUnicode_DecodeFSDefault*() comment: it now uses the "surrogateescape" error handler (and not "replace") * Remove "The function is intended to be used for paths and file names only during bootstrapping process where the codecs are not set up." from PyUnicode_FSConverter() comment: it is used after the bootstrapping and for other purposes than file names ................ r81170 | victor.stinner | 2010-05-14 18:35:39 +0200 (Fri, 14 May 2010) | 6 lines posix_listdir(), posix_readlink(): avoid temporary PyBytes object Use directly PyUnicode_DecodeFSDefaultAndSize() instead of PyBytes_FromStringAndSize() + PyUnicode_FromEncodedObject() if the argument is unicode. ................ r81181 | victor.stinner | 2010-05-14 23:53:45 +0200 (Fri, 14 May 2010) | 9 lines Merged revisions 81179 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r81179 | victor.stinner | 2010-05-14 23:52:26 +0200 (ven., 14 mai 2010) | 2 lines Fix regression introduced by r81154 (Issue #5099, subprocess destructor) ........ ................ r81183 | victor.stinner | 2010-05-15 03:40:41 +0200 (Sat, 15 May 2010) | 4 lines Fix test_capi for Windows: strip newline characters Fix test_no_FatalError_infinite_loop() introduced by r81142 (issue #3605). ................ r81188 | stefan.krah | 2010-05-15 11:41:27 +0200 (Sat, 15 May 2010) | 10 lines Merged revisions 81185 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r81185 | stefan.krah | 2010-05-15 11:31:08 +0200 (Sat, 15 May 2010) | 4 lines If the timeout is exceeded, count the tests as skipped instead of just issuing a warning. ........ ................ r81190 | victor.stinner | 2010-05-15 14:27:16 +0200 (Sat, 15 May 2010) | 4 lines Issue #8610: Load file system codec at startup, and display a fatal error on failure. Set the file system encoding to utf-8 (instead of None) if getting the locale encoding failed, or if nl_langinfo(CODESET) function is missing. ................ r81192 | victor.stinner | 2010-05-15 15:14:32 +0200 (Sat, 15 May 2010) | 3 lines Enable shortcuts for common encodings in PyUnicode_AsEncodedString() for any error handler, not only the default error handler (strict) ................ r81194 | victor.stinner | 2010-05-15 18:27:27 +0200 (Sat, 15 May 2010) | 5 lines Issue #8715: Create PyUnicode_EncodeFSDefault() function: Encode a Unicode object to Py_FileSystemDefaultEncoding with the "surrogateescape" error handler, return a bytes object. If Py_FileSystemDefaultEncoding is not set, fall back to UTF-8. ................ r81196 | mark.dickinson | 2010-05-15 19:02:38 +0200 (Sat, 15 May 2010) | 13 lines Issue #8692: Improve performance of math.factorial: (1) use a different algorithm that roughly halves the total number of multiplications required and results in more balanced multiplications (2) use a lookup table for small arguments (3) fast accumulation of products in C integer arithmetic rather than PyLong arithmetic when possible. Typical speedup, from unscientific testing on a 64-bit laptop, is 4.5x to 6.5x for arguments in the range 100 - 10000. Patch by Daniel Stutzbach; extensive reviews by Alexander Belopolsky. ................ r81197 | benjamin.peterson | 2010-05-15 19:42:02 +0200 (Sat, 15 May 2010) | 1 line fix run-on sentence ................ r81198 | benjamin.peterson | 2010-05-15 19:43:18 +0200 (Sat, 15 May 2010) | 1 line rephrase ................ r81199 | benjamin.peterson | 2010-05-15 19:43:57 +0200 (Sat, 15 May 2010) | 1 line fix one more runon ................ r81201 | benjamin.peterson | 2010-05-15 19:52:12 +0200 (Sat, 15 May 2010) | 9 lines Merged revisions 81200 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r81200 | benjamin.peterson | 2010-05-15 12:48:55 -0500 (Sat, 15 May 2010) | 1 line use TestCase skip method ........ ................ r81204 | amaury.forgeotdarc | 2010-05-15 22:35:12 +0200 (Sat, 15 May 2010) | 2 lines Remove unused variable, and fix a compilation warning on Windows. ................ r81207 | victor.stinner | 2010-05-15 23:04:43 +0200 (Sat, 15 May 2010) | 9 lines Recorded merge of revisions 81205 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r81205 | victor.stinner | 2010-05-15 23:00:59 +0200 (sam., 15 mai 2010) | 2 lines NEWS: strip trailing spaces ........ ................ r81209 | antoine.pitrou | 2010-05-15 23:34:27 +0200 (Sat, 15 May 2010) | 3 lines Issue #8665: Fix `make pycremoval` exiting with non-zero status. ................ r81211 | amaury.forgeotdarc | 2010-05-15 23:49:45 +0200 (Sat, 15 May 2010) | 8 lines Blocked revisions 81210 via svnmerge ........ r81210 | amaury.forgeotdarc | 2010-05-15 23:45:30 +0200 (sam., 15 mai 2010) | 2 lines Remove unused variable, and fix a compilation warning on Windows ........ ................ Modified: python/branches/py3k-cdecimal/ (props changed) python/branches/py3k-cdecimal/Doc/c-api/list.rst python/branches/py3k-cdecimal/Doc/c-api/unicode.rst python/branches/py3k-cdecimal/Doc/howto/cporting.rst python/branches/py3k-cdecimal/Doc/library/imp.rst python/branches/py3k-cdecimal/Doc/library/pkgutil.rst python/branches/py3k-cdecimal/Doc/library/runpy.rst python/branches/py3k-cdecimal/Doc/library/sys.rst python/branches/py3k-cdecimal/Doc/library/wsgiref.rst python/branches/py3k-cdecimal/Doc/library/zipimport.rst python/branches/py3k-cdecimal/Include/unicodeobject.h python/branches/py3k-cdecimal/Lib/subprocess.py python/branches/py3k-cdecimal/Lib/test/test_capi.py python/branches/py3k-cdecimal/Lib/test/test_math.py python/branches/py3k-cdecimal/Lib/test/test_signal.py python/branches/py3k-cdecimal/Lib/test/test_site.py python/branches/py3k-cdecimal/Lib/test/test_urlparse.py python/branches/py3k-cdecimal/Lib/urllib/parse.py python/branches/py3k-cdecimal/Makefile.pre.in python/branches/py3k-cdecimal/Misc/NEWS python/branches/py3k-cdecimal/Modules/_io/fileio.c python/branches/py3k-cdecimal/Modules/_ssl.c python/branches/py3k-cdecimal/Modules/_testcapimodule.c python/branches/py3k-cdecimal/Modules/_tkinter.c python/branches/py3k-cdecimal/Modules/grpmodule.c python/branches/py3k-cdecimal/Modules/mathmodule.c python/branches/py3k-cdecimal/Modules/posixmodule.c python/branches/py3k-cdecimal/Modules/pwdmodule.c python/branches/py3k-cdecimal/Modules/spwdmodule.c python/branches/py3k-cdecimal/Objects/unicodeobject.c python/branches/py3k-cdecimal/Python/bltinmodule.c python/branches/py3k-cdecimal/Python/dtoa.c python/branches/py3k-cdecimal/Python/errors.c python/branches/py3k-cdecimal/Python/import.c python/branches/py3k-cdecimal/Python/pythonrun.c Modified: python/branches/py3k-cdecimal/Doc/c-api/list.rst ============================================================================== --- python/branches/py3k-cdecimal/Doc/c-api/list.rst (original) +++ python/branches/py3k-cdecimal/Doc/c-api/list.rst Sun May 16 00:01:19 2010 @@ -15,11 +15,8 @@ .. cvar:: PyTypeObject PyList_Type - .. index:: single: ListType (in module types) - - This instance of :ctype:`PyTypeObject` represents the Python list type. - This is the same object as ``list`` and ``types.ListType`` in the Python - layer. + This instance of :ctype:`PyTypeObject` represents the Python list type. This + is the same object as ``list`` in the Python layer. .. cfunction:: int PyList_Check(PyObject *p) Modified: python/branches/py3k-cdecimal/Doc/c-api/unicode.rst ============================================================================== --- python/branches/py3k-cdecimal/Doc/c-api/unicode.rst (original) +++ python/branches/py3k-cdecimal/Doc/c-api/unicode.rst Sun May 16 00:01:19 2010 @@ -10,11 +10,12 @@ Unicode Objects ^^^^^^^^^^^^^^^ +Unicode Type +"""""""""""" + These are the basic Unicode object types used for the Unicode implementation in Python: -.. % --- Unicode Type ------------------------------------------------------- - .. ctype:: Py_UNICODE @@ -89,12 +90,13 @@ Clear the free list. Return the total number of freed items. +Unicode Character Properties +"""""""""""""""""""""""""""" + Unicode provides many different character properties. The most often needed ones are available through these macros which are mapped to C functions depending on the Python configuration. -.. % --- Unicode character properties --------------------------------------- - .. cfunction:: int Py_UNICODE_ISSPACE(Py_UNICODE ch) @@ -192,11 +194,13 @@ Return the character *ch* converted to a double. Return ``-1.0`` if this is not possible. This macro does not raise exceptions. + +Plain Py_UNICODE +"""""""""""""""" + To create Unicode objects and access their basic sequence properties, use these APIs: -.. % --- Plain Py_UNICODE --------------------------------------------------- - .. cfunction:: PyObject* PyUnicode_FromUnicode(const Py_UNICODE *u, Py_ssize_t size) @@ -364,8 +368,57 @@ Support is optimized if Python's own :ctype:`Py_UNICODE` type is identical to the system's :ctype:`wchar_t`. -.. % --- wchar_t support for platforms which support it --------------------- +File System Encoding +"""""""""""""""""""" + +To encode and decode file names and other environment strings, +:cdata:`Py_FileSystemEncoding` should be used as the encoding, and +``"surrogateescape"`` should be used as the error handler (:pep:`383`). To +encode file names during argument parsing, the ``"O&"`` converter should be +used, passsing :func:PyUnicode_FSConverter as the conversion function: + +.. cfunction:: int PyUnicode_FSConverter(PyObject* obj, void* result) + + Convert *obj* into *result*, using :cdata:`Py_FileSystemDefaultEncoding`, + and the ``"surrogateescape"`` error handler. *result* must be a + ``PyObject*``, return a :func:`bytes` object which must be released if it + is no longer used. + + .. versionadded:: 3.1 + +.. cfunction:: PyObject* PyUnicode_DecodeFSDefaultAndSize(const char *s, Py_ssize_t size) + + Decode a null-terminated string using :cdata:`Py_FileSystemDefaultEncoding` + and the ``"surrogateescape"`` error handler. + + If :cdata:`Py_FileSystemDefaultEncoding` is not set, fall back to UTF-8. + + Use :func:`PyUnicode_DecodeFSDefaultAndSize` if you know the string length. + + +.. cfunction:: PyObject* PyUnicode_DecodeFSDefault(const char *s) + + Decode a string using :cdata:`Py_FileSystemDefaultEncoding` and + the ``"surrogateescape"`` error handler. + + If :cdata:`Py_FileSystemDefaultEncoding` is not set, fall back to UTF-8. + + +.. cfunction:: PyObject* PyUnicode_EncodeFSDefault(PyObject *unicode) + + Encode a Unicode object to :cdata:`Py_FileSystemDefaultEncoding` with the + ``'surrogateescape'`` error handler, and return :class:`bytes`. + + If :cdata:`Py_FileSystemDefaultEncoding` is not set, fall back to UTF-8. + + .. versionadded:: 3.2 + + +wchar_t Support +""""""""""""""" + +wchar_t support for platforms which support it: .. cfunction:: PyObject* PyUnicode_FromWideChar(const wchar_t *w, Py_ssize_t size) @@ -413,9 +466,11 @@ The codecs all use a similar interface. Only deviation from the following generic ones are documented for simplicity. -These are the generic codec APIs: -.. % --- Generic Codecs ----------------------------------------------------- +Generic Codecs +"""""""""""""" + +These are the generic codec APIs: .. cfunction:: PyObject* PyUnicode_Decode(const char *s, Py_ssize_t size, const char *encoding, const char *errors) @@ -444,9 +499,11 @@ using the Python codec registry. Return *NULL* if an exception was raised by the codec. -These are the UTF-8 codec APIs: -.. % --- UTF-8 Codecs ------------------------------------------------------- +UTF-8 Codecs +"""""""""""" + +These are the UTF-8 codec APIs: .. cfunction:: PyObject* PyUnicode_DecodeUTF8(const char *s, Py_ssize_t size, const char *errors) @@ -476,9 +533,11 @@ object. Error handling is "strict". Return *NULL* if an exception was raised by the codec. -These are the UTF-32 codec APIs: -.. % --- UTF-32 Codecs ------------------------------------------------------ */ +UTF-32 Codecs +""""""""""""" + +These are the UTF-32 codec APIs: .. cfunction:: PyObject* PyUnicode_DecodeUTF32(const char *s, Py_ssize_t size, const char *errors, int *byteorder) @@ -543,9 +602,10 @@ Return *NULL* if an exception was raised by the codec. -These are the UTF-16 codec APIs: +UTF-16 Codecs +""""""""""""" -.. % --- UTF-16 Codecs ------------------------------------------------------ */ +These are the UTF-16 codec APIs: .. cfunction:: PyObject* PyUnicode_DecodeUTF16(const char *s, Py_ssize_t size, const char *errors, int *byteorder) @@ -609,9 +669,11 @@ order. The string always starts with a BOM mark. Error handling is "strict". Return *NULL* if an exception was raised by the codec. -These are the "Unicode Escape" codec APIs: -.. % --- Unicode-Escape Codecs ---------------------------------------------- +Unicode-Escape Codecs +""""""""""""""""""""" + +These are the "Unicode Escape" codec APIs: .. cfunction:: PyObject* PyUnicode_DecodeUnicodeEscape(const char *s, Py_ssize_t size, const char *errors) @@ -633,9 +695,11 @@ string object. Error handling is "strict". Return *NULL* if an exception was raised by the codec. -These are the "Raw Unicode Escape" codec APIs: -.. % --- Raw-Unicode-Escape Codecs ------------------------------------------ +Raw-Unicode-Escape Codecs +""""""""""""""""""""""""" + +These are the "Raw Unicode Escape" codec APIs: .. cfunction:: PyObject* PyUnicode_DecodeRawUnicodeEscape(const char *s, Py_ssize_t size, const char *errors) @@ -657,11 +721,13 @@ Python string object. Error handling is "strict". Return *NULL* if an exception was raised by the codec. + +Latin-1 Codecs +"""""""""""""" + These are the Latin-1 codec APIs: Latin-1 corresponds to the first 256 Unicode ordinals and only these are accepted by the codecs during encoding. -.. % --- Latin-1 Codecs ----------------------------------------------------- - .. cfunction:: PyObject* PyUnicode_DecodeLatin1(const char *s, Py_ssize_t size, const char *errors) @@ -682,11 +748,13 @@ object. Error handling is "strict". Return *NULL* if an exception was raised by the codec. + +ASCII Codecs +"""""""""""" + These are the ASCII codec APIs. Only 7-bit ASCII data is accepted. All other codes generate errors. -.. % --- ASCII Codecs ------------------------------------------------------- - .. cfunction:: PyObject* PyUnicode_DecodeASCII(const char *s, Py_ssize_t size, const char *errors) @@ -707,9 +775,11 @@ object. Error handling is "strict". Return *NULL* if an exception was raised by the codec. -These are the mapping codec APIs: -.. % --- Character Map Codecs ----------------------------------------------- +Character Map Codecs +"""""""""""""""""""" + +These are the mapping codec APIs: This codec is special in that it can be used to implement many different codecs (and this is in fact what was done to obtain most of the standard codecs @@ -778,7 +848,9 @@ DBCS) is a class of encodings, not just one. The target encoding is defined by the user settings on the machine running the codec. -.. % --- MBCS codecs for Windows -------------------------------------------- + +MBCS codecs for Windows +""""""""""""""""""""""" .. cfunction:: PyObject* PyUnicode_DecodeMBCS(const char *s, Py_ssize_t size, const char *errors) @@ -808,20 +880,9 @@ object. Error handling is "strict". Return *NULL* if an exception was raised by the codec. -For decoding file names and other environment strings, :cdata:`Py_FileSystemEncoding` -should be used as the encoding, and ``"surrogateescape"`` should be used as the error -handler. For encoding file names during argument parsing, the ``O&`` converter should -be used, passsing PyUnicode_FSConverter as the conversion function: - -.. cfunction:: int PyUnicode_FSConverter(PyObject* obj, void* result) - - Convert *obj* into *result*, using the file system encoding, and the ``surrogateescape`` - error handler. *result* must be a ``PyObject*``, yielding a bytes or bytearray object - which must be released if it is no longer used. - - .. versionadded:: 3.1 -.. % --- Methods & Slots ---------------------------------------------------- +Methods & Slots +""""""""""""""" .. _unicodemethodsandslots: Modified: python/branches/py3k-cdecimal/Doc/howto/cporting.rst ============================================================================== --- python/branches/py3k-cdecimal/Doc/howto/cporting.rst (original) +++ python/branches/py3k-cdecimal/Doc/howto/cporting.rst Sun May 16 00:01:19 2010 @@ -120,7 +120,7 @@ Module initialization and state =============================== -Python 3.0 has a revamped extension module initialization system. (See PEP +Python 3.0 has a revamped extension module initialization system. (See :pep:`3121`.) Instead of storing module state in globals, they should be stored in an interpreter specific structure. Creating modules that act correctly in both 2.x and 3.0 is tricky. The following simple example demonstrates how. :: Modified: python/branches/py3k-cdecimal/Doc/library/imp.rst ============================================================================== --- python/branches/py3k-cdecimal/Doc/library/imp.rst (original) +++ python/branches/py3k-cdecimal/Doc/library/imp.rst Sun May 16 00:01:19 2010 @@ -211,7 +211,7 @@ .. function:: cache_from_source(path, debug_override=None) - Return the PEP 3147 path to the byte-compiled file associated with the + Return the :pep:`3147` path to the byte-compiled file associated with the source *path*. For example, if *path* is ``/foo/bar/baz.py`` the return value would be ``/foo/bar/__pycache__/baz.cpython-32.pyc`` for Python 3.2. The ``cpython-32`` string comes from the current magic tag (see @@ -225,15 +225,15 @@ .. function:: source_from_cache(path) - Given the *path* to a PEP 3147 file name, return the associated source code + Given the *path* to a :pep:`3147` file name, return the associated source code file path. For example, if *path* is ``/foo/bar/__pycache__/baz.cpython-32.pyc`` the returned path would be ``/foo/bar/baz.py``. *path* need not exist, however if it does not conform - to PEP 3147 format, a ``ValueError`` is raised. + to :pep:`3147` format, a ``ValueError`` is raised. .. function:: get_tag() - Return the PEP 3147 magic tag string matching this version of Python's + Return the :pep:`3147` magic tag string matching this version of Python's magic number, as returned by :func:`get_magic`. Modified: python/branches/py3k-cdecimal/Doc/library/pkgutil.rst ============================================================================== --- python/branches/py3k-cdecimal/Doc/library/pkgutil.rst (original) +++ python/branches/py3k-cdecimal/Doc/library/pkgutil.rst Sun May 16 00:01:19 2010 @@ -41,7 +41,7 @@ Get a resource from a package. - This is a wrapper for the PEP 302 loader :func:`get_data` API. The package + This is a wrapper for the :pep:`302` loader :func:`get_data` API. The package argument should be the name of a package, in standard module format (foo.bar). The resource argument should be in the form of a relative filename, using ``/`` as the path separator. The parent directory name @@ -56,5 +56,5 @@ d = os.path.dirname(sys.modules[package].__file__) data = open(os.path.join(d, resource), 'rb').read() - If the package cannot be located or loaded, or it uses a PEP 302 loader + If the package cannot be located or loaded, or it uses a :pep:`302` loader which does not support :func:`get_data`, then None is returned. Modified: python/branches/py3k-cdecimal/Doc/library/runpy.rst ============================================================================== --- python/branches/py3k-cdecimal/Doc/library/runpy.rst (original) +++ python/branches/py3k-cdecimal/Doc/library/runpy.rst Sun May 16 00:01:19 2010 @@ -18,7 +18,7 @@ Execute the code of the specified module and return the resulting module globals dictionary. The module's code is first located using the standard - import mechanism (refer to PEP 302 for details) and then executed in a + import mechanism (refer to :pep:`302` for details) and then executed in a fresh module namespace. If the supplied module name refers to a package rather than a normal @@ -48,7 +48,7 @@ ``__cached__`` will be set to ``None``. - ``__loader__`` is set to the PEP 302 module loader used to retrieve the + ``__loader__`` is set to the :pep:`302` module loader used to retrieve the code for the module (This loader may be a wrapper around the standard import mechanism). @@ -106,7 +106,7 @@ loader does not make filename information available, this variable is set to :const:`None`. For a simple script, this will be set to ``file_path``. - ``__loader__`` is set to the PEP 302 module loader used to retrieve the + ``__loader__`` is set to the :pep:`302` module loader used to retrieve the code for the module (This loader may be a wrapper around the standard import mechanism). For a simple script, this will be set to :const:`None`. Modified: python/branches/py3k-cdecimal/Doc/library/sys.rst ============================================================================== --- python/branches/py3k-cdecimal/Doc/library/sys.rst (original) +++ python/branches/py3k-cdecimal/Doc/library/sys.rst Sun May 16 00:01:19 2010 @@ -298,15 +298,13 @@ .. function:: getfilesystemencoding() - Return the name of the encoding used to convert Unicode filenames into system - file names, or ``None`` if the system default encoding is used. The result value - depends on the operating system: + Return the name of the encoding used to convert Unicode filenames into + system file names. The result value depends on the operating system: * On Mac OS X, the encoding is ``'utf-8'``. * On Unix, the encoding is the user's preference according to the result of - nl_langinfo(CODESET), or ``None`` if the ``nl_langinfo(CODESET)`` - failed. + nl_langinfo(CODESET), or ``'utf-8'`` if ``nl_langinfo(CODESET)`` failed. * On Windows NT+, file names are Unicode natively, so no conversion is performed. :func:`getfilesystemencoding` still returns ``'mbcs'``, as @@ -316,6 +314,10 @@ * On Windows 9x, the encoding is ``'mbcs'``. + .. versionchanged:: 3.2 + On Unix, use ``'utf-8'`` instead of ``None`` if ``nl_langinfo(CODESET)`` + failed. :func:`getfilesystemencoding` result cannot be ``None``. + .. function:: getrefcount(object) Modified: python/branches/py3k-cdecimal/Doc/library/wsgiref.rst ============================================================================== --- python/branches/py3k-cdecimal/Doc/library/wsgiref.rst (original) +++ python/branches/py3k-cdecimal/Doc/library/wsgiref.rst Sun May 16 00:01:19 2010 @@ -710,7 +710,7 @@ # use a function (note that you're not limited to a function, you can # use a class for example). The first argument passed to the function # is a dictionary containing CGI-style envrironment variables and the - # second variable is the callable object (see PEP333) + # second variable is the callable object (see :pep:`333`) def hello_world_app(environ, start_response): status = b'200 OK' # HTTP Status headers = [(b'Content-type', b'text/plain; charset=utf-8')] # HTTP Headers Modified: python/branches/py3k-cdecimal/Doc/library/zipimport.rst ============================================================================== --- python/branches/py3k-cdecimal/Doc/library/zipimport.rst (original) +++ python/branches/py3k-cdecimal/Doc/library/zipimport.rst Sun May 16 00:01:19 2010 @@ -34,12 +34,12 @@ Documentation on the ZIP file format by Phil Katz, the creator of the format and algorithms used. - :pep:`0273` - Import Modules from Zip Archives + :pep:`273` - Import Modules from Zip Archives Written by James C. Ahlstrom, who also provided an implementation. Python 2.3 follows the specification in PEP 273, but uses an implementation written by Just van Rossum that uses the import hooks described in PEP 302. - :pep:`0302` - New Import Hooks + :pep:`302` - New Import Hooks The PEP to add the import hooks that help this module work. Modified: python/branches/py3k-cdecimal/Include/unicodeobject.h ============================================================================== --- python/branches/py3k-cdecimal/Include/unicodeobject.h (original) +++ python/branches/py3k-cdecimal/Include/unicodeobject.h Sun May 16 00:01:19 2010 @@ -1240,30 +1240,44 @@ /* --- File system encoding ---------------------------------------------- */ /* ParseTuple converter which converts a Unicode object into the file - system encoding as a bytes object, using the PEP 383 error handler; bytes - objects are output as-is. */ + system encoding as a bytes object, using the "surrogateescape" error + handler; bytes objects are output as-is. */ PyAPI_FUNC(int) PyUnicode_FSConverter(PyObject*, void*); -/* Decode a null-terminated string using Py_FileSystemDefaultEncoding. +/* Decode a null-terminated string using Py_FileSystemDefaultEncoding + and the "surrogateescape" error handler. - If the encoding is supported by one of the built-in codecs (i.e., UTF-8, - UTF-16, UTF-32, Latin-1 or MBCS), otherwise fallback to UTF-8 and replace - invalid characters with '?'. + If Py_FileSystemDefaultEncoding is not set, fall back to UTF-8. - The function is intended to be used for paths and file names only - during bootstrapping process where the codecs are not set up. + Use PyUnicode_DecodeFSDefaultAndSize() if the string length is known. */ PyAPI_FUNC(PyObject*) PyUnicode_DecodeFSDefault( const char *s /* encoded string */ ); +/* Decode a string using Py_FileSystemDefaultEncoding + and the "surrogateescape" error handler. + + If Py_FileSystemDefaultEncoding is not set, fall back to UTF-8. +*/ + PyAPI_FUNC(PyObject*) PyUnicode_DecodeFSDefaultAndSize( const char *s, /* encoded string */ Py_ssize_t size /* size */ ); +/* Encode a Unicode object to Py_FileSystemDefaultEncoding with the + "surrogateescape" error handler, and return bytes. + + If Py_FileSystemDefaultEncoding is not set, fall back to UTF-8. +*/ + +PyAPI_FUNC(PyObject*) PyUnicode_EncodeFSDefault( + PyObject *unicode + ); + /* --- Methods & Slots ---------------------------------------------------- These are capable of handling Unicode objects and strings on input Modified: python/branches/py3k-cdecimal/Lib/subprocess.py ============================================================================== --- python/branches/py3k-cdecimal/Lib/subprocess.py (original) +++ python/branches/py3k-cdecimal/Lib/subprocess.py Sun May 16 00:01:19 2010 @@ -356,7 +356,6 @@ if mswindows: - from _subprocess import CREATE_NEW_CONSOLE, CREATE_NEW_PROCESS_GROUP import threading import msvcrt import _subprocess @@ -394,6 +393,7 @@ "getoutput", "check_output", "CalledProcessError"] if mswindows: + from _subprocess import CREATE_NEW_CONSOLE, CREATE_NEW_PROCESS_GROUP __all__.extend(["CREATE_NEW_CONSOLE", "CREATE_NEW_PROCESS_GROUP"]) try: MAXFD = os.sysconf("SC_OPEN_MAX") @@ -698,12 +698,12 @@ return data.decode(encoding) - def __del__(self, sys=sys): + def __del__(self, _maxsize=sys.maxsize, _active=_active): if not self._child_created: # We didn't get to successfully create a child process. return # In case the child hasn't been waited on, check if it's done. - self._internal_poll(_deadstate=sys.maxsize) + self._internal_poll(_deadstate=_maxsize) if self.returncode is None and _active is not None: # Child is still running, keep us alive until we can wait on it. _active.append(self) @@ -907,13 +907,20 @@ errwrite.Close() - def _internal_poll(self, _deadstate=None): + def _internal_poll(self, _deadstate=None, + _WaitForSingleObject=_subprocess.WaitForSingleObject, + _WAIT_OBJECT_0=_subprocess.WAIT_OBJECT_0, + _GetExitCodeProcess=_subprocess.GetExitCodeProcess): """Check if child process has terminated. Returns returncode - attribute.""" + attribute. + + This method is called by __del__, so it can only refer to objects + in its local scope. + + """ if self.returncode is None: - if(_subprocess.WaitForSingleObject(self._handle, 0) == - _subprocess.WAIT_OBJECT_0): - self.returncode = _subprocess.GetExitCodeProcess(self._handle) + if _WaitForSingleObject(self._handle, 0) == _WAIT_OBJECT_0: + self.returncode = _GetExitCodeProcess(self._handle) return self.returncode @@ -1252,25 +1259,35 @@ raise child_exception_type(err_msg) - def _handle_exitstatus(self, sts): - if os.WIFSIGNALED(sts): - self.returncode = -os.WTERMSIG(sts) - elif os.WIFEXITED(sts): - self.returncode = os.WEXITSTATUS(sts) + def _handle_exitstatus(self, sts, _WIFSIGNALED=os.WIFSIGNALED, + _WTERMSIG=os.WTERMSIG, _WIFEXITED=os.WIFEXITED, + _WEXITSTATUS=os.WEXITSTATUS): + # This method is called (indirectly) by __del__, so it cannot + # refer to anything outside of its local scope.""" + if _WIFSIGNALED(sts): + self.returncode = -_WTERMSIG(sts) + elif _WIFEXITED(sts): + self.returncode = _WEXITSTATUS(sts) else: # Should never happen raise RuntimeError("Unknown child exit status!") - def _internal_poll(self, _deadstate=None): + def _internal_poll(self, _deadstate=None, _waitpid=os.waitpid, + _WNOHANG=os.WNOHANG, _os_error=os.error): """Check if child process has terminated. Returns returncode - attribute.""" + attribute. + + This method is called by __del__, so it cannot reference anything + outside of the local scope (nor can any methods it calls). + + """ if self.returncode is None: try: - pid, sts = os.waitpid(self.pid, os.WNOHANG) + pid, sts = _waitpid(self.pid, _WNOHANG) if pid == self.pid: self._handle_exitstatus(sts) - except os.error: + except _os_error: if _deadstate is not None: self.returncode = _deadstate return self.returncode Modified: python/branches/py3k-cdecimal/Lib/test/test_capi.py ============================================================================== --- python/branches/py3k-cdecimal/Lib/test/test_capi.py (original) +++ python/branches/py3k-cdecimal/Lib/test/test_capi.py Sun May 16 00:01:19 2010 @@ -2,9 +2,10 @@ # these are all functions _testcapi exports whose name begins with 'test_'. from __future__ import with_statement +import random +import subprocess import sys import time -import random import unittest from test import support try: @@ -35,6 +36,19 @@ self.assertEqual(testfunction.attribute, "test") self.assertRaises(AttributeError, setattr, inst.testfunction, "attribute", "test") + def test_no_FatalError_infinite_loop(self): + p = subprocess.Popen([sys.executable, "-c", + 'import _testcapi;' + '_testcapi.crash_no_current_thread()'], + stdout=subprocess.PIPE, + stderr=subprocess.PIPE) + (out, err) = p.communicate() + self.assertEqual(out, b'') + # This used to cause an infinite loop. + self.assertEqual(err.rstrip(), + b'Fatal Python error:' + b' PyThreadState_Get: no current thread') + @unittest.skipUnless(threading, 'Threading required for this test.') class TestPendingCalls(unittest.TestCase): Modified: python/branches/py3k-cdecimal/Lib/test/test_math.py ============================================================================== --- python/branches/py3k-cdecimal/Lib/test/test_math.py (original) +++ python/branches/py3k-cdecimal/Lib/test/test_math.py Sun May 16 00:01:19 2010 @@ -60,6 +60,56 @@ return "error = {} ulps; permitted error = {} ulps".format(ulps_error, ulps) +# Here's a pure Python version of the math.factorial algorithm, for +# documentation and comparison purposes. +# +# Formula: +# +# factorial(n) = factorial_odd_part(n) << (n - count_set_bits(n)) +# +# where +# +# factorial_odd_part(n) = product_{i >= 0} product_{0 < j <= n >> i; j odd} j +# +# The outer product above is an infinite product, but once i >= n.bit_length, +# (n >> i) < 1 and the corresponding term of the product is empty. So only the +# finitely many terms for 0 <= i < n.bit_length() contribute anything. +# +# We iterate downwards from i == n.bit_length() - 1 to i == 0. The inner +# product in the formula above starts at 1 for i == n.bit_length(); for each i +# < n.bit_length() we get the inner product for i from that for i + 1 by +# multiplying by all j in {n >> i+1 < j <= n >> i; j odd}. In Python terms, +# this set is range((n >> i+1) + 1 | 1, (n >> i) + 1 | 1, 2). + +def count_set_bits(n): + """Number of '1' bits in binary expansion of a nonnnegative integer.""" + return 1 + count_set_bits(n & n - 1) if n else 0 + +def partial_product(start, stop): + """Product of integers in range(start, stop, 2), computed recursively. + start and stop should both be odd, with start <= stop. + + """ + numfactors = (stop - start) >> 1 + if not numfactors: + return 1 + elif numfactors == 1: + return start + else: + mid = (start + numfactors) | 1 + return partial_product(start, mid) * partial_product(mid, stop) + +def py_factorial(n): + """Factorial of nonnegative integer n, via "Binary Split Factorial Formula" + described at http://www.luschny.de/math/factorial/binarysplitfact.html + + """ + inner = outer = 1 + for i in reversed(range(n.bit_length())): + inner *= partial_product((n >> i + 1) + 1 | 1, (n >> i) + 1 | 1) + outer *= inner + return outer << (n - count_set_bits(n)) + def acc_check(expected, got, rel_err=2e-15, abs_err = 5e-323): """Determine whether non-NaN floats a and b are equal to within a (small) rounding error. The default values for rel_err and @@ -365,18 +415,19 @@ self.ftest('fabs(1)', math.fabs(1), 1) def testFactorial(self): - def fact(n): - result = 1 - for i in range(1, int(n)+1): - result *= i - return result - values = list(range(10)) + [50, 100, 500] - random.shuffle(values) - for x in range(10): - for cast in (int, float): - self.assertEqual(math.factorial(cast(x)), fact(x), (x, fact(x), math.factorial(x))) + self.assertEqual(math.factorial(0), 1) + self.assertEqual(math.factorial(0.0), 1) + total = 1 + for i in range(1, 1000): + total *= i + self.assertEqual(math.factorial(i), total) + self.assertEqual(math.factorial(float(i)), total) + self.assertEqual(math.factorial(i), py_factorial(i)) self.assertRaises(ValueError, math.factorial, -1) + self.assertRaises(ValueError, math.factorial, -1.0) self.assertRaises(ValueError, math.factorial, math.pi) + self.assertRaises(OverflowError, math.factorial, sys.maxsize+1) + self.assertRaises(OverflowError, math.factorial, 10e100) def testFloor(self): self.assertRaises(TypeError, math.floor) Modified: python/branches/py3k-cdecimal/Lib/test/test_signal.py ============================================================================== --- python/branches/py3k-cdecimal/Lib/test/test_signal.py (original) +++ python/branches/py3k-cdecimal/Lib/test/test_signal.py Sun May 16 00:01:19 2010 @@ -431,9 +431,8 @@ if signal.getitimer(self.itimer) == (0.0, 0.0): break # sig_vtalrm handler stopped this itimer else: # Issue 8424 - sys.stdout.write("test_itimer_virtual: timeout: likely cause: " - "machine too slow or load too high.\n") - return + self.skipTest("timeout: likely cause: machine too slow or load too " + "high") # virtual itimer should be (0.0, 0.0) now self.assertEquals(signal.getitimer(self.itimer), (0.0, 0.0)) @@ -455,9 +454,8 @@ if signal.getitimer(self.itimer) == (0.0, 0.0): break # sig_prof handler stopped this itimer else: # Issue 8424 - sys.stdout.write("test_itimer_prof: timeout: likely cause: " - "machine too slow or load too high.\n") - return + self.skipTest("timeout: likely cause: machine too slow or load too " + "high") # profiling itimer should be (0.0, 0.0) now self.assertEquals(signal.getitimer(self.itimer), (0.0, 0.0)) Modified: python/branches/py3k-cdecimal/Lib/test/test_site.py ============================================================================== --- python/branches/py3k-cdecimal/Lib/test/test_site.py (original) +++ python/branches/py3k-cdecimal/Lib/test/test_site.py Sun May 16 00:01:19 2010 @@ -181,7 +181,8 @@ self.assertEquals(dirs[1], wanted) # let's try the specific Apple location - if sys.platform == "darwin": + if (sys.platform == "darwin" and + sysconfig.get_config_var("PYTHONFRAMEWORK")): site.PREFIXES = ['Python.framework'] dirs = site.getsitepackages() self.assertEqual(len(dirs), 4) Modified: python/branches/py3k-cdecimal/Lib/test/test_urlparse.py ============================================================================== --- python/branches/py3k-cdecimal/Lib/test/test_urlparse.py (original) +++ python/branches/py3k-cdecimal/Lib/test/test_urlparse.py Sun May 16 00:01:19 2010 @@ -104,7 +104,12 @@ ('svn+ssh', 'svn.zope.org', '/repos/main/ZConfig/trunk/', '', '', ''), ('svn+ssh', 'svn.zope.org', '/repos/main/ZConfig/trunk/', - '', '')) + '', '')), + ('git+ssh://git at github.com/user/project.git', + ('git+ssh', 'git at github.com','/user/project.git', + '','',''), + ('git+ssh', 'git at github.com','/user/project.git', + '', '')) ] for url, parsed, split in testcases: self.checkRoundtrips(url, parsed, split) Modified: python/branches/py3k-cdecimal/Lib/urllib/parse.py ============================================================================== --- python/branches/py3k-cdecimal/Lib/urllib/parse.py (original) +++ python/branches/py3k-cdecimal/Lib/urllib/parse.py Sun May 16 00:01:19 2010 @@ -41,7 +41,7 @@ uses_netloc = ['ftp', 'http', 'gopher', 'nntp', 'telnet', 'imap', 'wais', 'file', 'mms', 'https', 'shttp', 'snews', 'prospero', 'rtsp', 'rtspu', 'rsync', '', - 'svn', 'svn+ssh', 'sftp','nfs'] + 'svn', 'svn+ssh', 'sftp', 'nfs',' git', 'git+ssh'] non_hierarchical = ['gopher', 'hdl', 'mailto', 'news', 'telnet', 'wais', 'imap', 'snews', 'sip', 'sips'] uses_params = ['ftp', 'hdl', 'prospero', 'http', 'imap', Modified: python/branches/py3k-cdecimal/Makefile.pre.in ============================================================================== --- python/branches/py3k-cdecimal/Makefile.pre.in (original) +++ python/branches/py3k-cdecimal/Makefile.pre.in Sun May 16 00:01:19 2010 @@ -1166,7 +1166,7 @@ # files, which clobber removes as well pycremoval: -find $(srcdir) -name '*.py[co]' -exec rm -f {} ';' - -find $(srcdir) -name '__pycache__' -exec rmdir {} ';' + -find $(srcdir) -name '__pycache__' -exec rmdir {} '+' rmtestturds: -rm -f *BAD *GOOD *SKIPPED Modified: python/branches/py3k-cdecimal/Misc/NEWS ============================================================================== --- python/branches/py3k-cdecimal/Misc/NEWS (original) +++ python/branches/py3k-cdecimal/Misc/NEWS Sun May 16 00:01:19 2010 @@ -12,6 +12,18 @@ Core and Builtins ----------------- +- Issue #8715: Create PyUnicode_EncodeFSDefault() function: Encode a Unicode + object to Py_FileSystemDefaultEncoding with the "surrogateescape" error + handler, and return bytes. If Py_FileSystemDefaultEncoding is not set, fall + back to UTF-8. + +- Enable shortcuts for common encodings in PyUnicode_AsEncodedString() for any + error handler, not only the default error handler (strict) + +- Issue #8610: Load file system codec at startup, and display a fatal error on + failure. Set the file system encoding to utf-8 (instead of None) if getting + the locale encoding failed, or if nl_langinfo(CODESET) function is missing. + - PyFile_FromFd() uses PyUnicode_DecodeFSDefault() instead of PyUnicode_FromString() to support surrogates in the filename and use the right encoding @@ -377,9 +389,9 @@ - Issue #8573: asyncore _strerror() function might throw ValueError. -- Issue #8483: asyncore.dispatcher's __getattr__ method produced confusing - error messages when accessing undefined class attributes because of the cheap - inheritance with the underlying socket object. +- Issue #8483: asyncore.dispatcher's __getattr__ method produced confusing + error messages when accessing undefined class attributes because of the cheap + inheritance with the underlying socket object. The cheap inheritance has been deprecated. - Issue #4265: shutil.copyfile() was leaking file descriptors when disk fills. @@ -476,7 +488,7 @@ - Issue #6547: Added the ignore_dangling_symlinks option to shutil.copytree. -- Issue #1540112: Now allowing the choice of a copy function in +- Issue #1540112: Now allowing the choice of a copy function in shutil.copytree. - Issue #4814: timeout parameter is now applied also for connections resulting @@ -791,7 +803,7 @@ Initial patch by Brian Curtin. - Issue #7556: Make sure Distutils' msvc9compile reads and writes the - MSVC XML Manifest file in text mode so string patterns can be used + MSVC XML Manifest file in text mode so string patterns can be used in regular expressions. - Issue #7552: Removed line feed in the base64 Authorization header in @@ -822,13 +834,13 @@ - Issue #6986: Fix crash in the JSON C accelerator when called with the wrong parameter types. Patch by Victor Stinner. -- Issue #7457: added a read_pkg_file method to +- Issue #7457: added a read_pkg_file method to distutils.dist.DistributionMetadata. - logging: Added optional `secure` parameter to SMTPHandler, to enable use of TLS with authentication credentials. -- Issue #1923: Fixed the removal of meaningful spaces when PKG-INFO is +- Issue #1923: Fixed the removal of meaningful spaces when PKG-INFO is generated in Distutils. Patch by Stephen Emslie. - Issue #4120: Drop reference to CRT from manifest when building extensions with @@ -866,7 +878,7 @@ - Issue #6123: tarfile now opens empty archives correctly and consistently raises ReadError on empty files. -- Issue #7354: distutils.tests.test_msvc9compiler - dragfullwindows can +- Issue #7354: distutils.tests.test_msvc9compiler - dragfullwindows can be 2. - Issue #5037: Proxy the __bytes__ special method instead to __bytes__ instead @@ -904,12 +916,12 @@ - Issue #7893: ``unittest.TextTestResult`` is made public and a ``resultclass`` argument added to the TextTestRunner constructor allowing a different result class to be used without having to subclass. - + - Issue 7588: ``unittest.TextTestResult.getDescription`` now includes the test name in failure reports even if the test has a docstring. - Issue #3001: Add a C implementation of recursive locks which is used by - default when instantiating a `threading.RLock` object. This makes + default when instantiating a `threading.RLock` object. This makes recursive locks as fast as regular non-recursive locks (previously, they were slower by 10x to 15x). @@ -1120,6 +1132,12 @@ Extension Modules ----------------- +- Issue #8692: Optimize math.factorial: replace the previous naive + algorithm with an improved 'binary-split' algorithm that uses fewer + multiplications and allows many of the multiplications to be + performed using plain C integer arithmetic instead of PyLong + arithmetic. Also uses a lookup table for small arguments. + - Issue #8674: Fixed a number of incorrect or undefined-behaviour-inducing overflow checks in the audioop module. @@ -1349,7 +1367,7 @@ - Issue #7498: test_multiprocessing now uses test.support.find_unused_port instead of a hardcoded port number in test_rapid_restart. -- Issue #7431: use TESTFN in test_linecache instead of trying to create a +- Issue #7431: use TESTFN in test_linecache instead of trying to create a file in the Lib/test directory, which might be read-only for the user running the tests. @@ -2233,7 +2251,7 @@ - Issue #7071: byte-compilation in Distutils is now done with respect to sys.dont_write_bytecode. -- Issue #7066: archive_util.make_archive now restores the cwd if an error is +- Issue #7066: archive_util.make_archive now restores the cwd if an error is raised. Initial patch by Ezio Melotti. - Issue #6516: Added owner/group support when creating tar archives in Modified: python/branches/py3k-cdecimal/Modules/_io/fileio.c ============================================================================== --- python/branches/py3k-cdecimal/Modules/_io/fileio.c (original) +++ python/branches/py3k-cdecimal/Modules/_io/fileio.c Sun May 16 00:01:19 2010 @@ -247,8 +247,7 @@ if (u == NULL) return -1; - stringobj = PyUnicode_AsEncodedString( - u, Py_FileSystemDefaultEncoding, "surrogateescape"); + stringobj = PyUnicode_EncodeFSDefault(u); Py_DECREF(u); if (stringobj == NULL) return -1; Modified: python/branches/py3k-cdecimal/Modules/_ssl.c ============================================================================== --- python/branches/py3k-cdecimal/Modules/_ssl.c (original) +++ python/branches/py3k-cdecimal/Modules/_ssl.c Sun May 16 00:01:19 2010 @@ -182,8 +182,7 @@ break; case SSL_ERROR_WANT_X509_LOOKUP: p = PY_SSL_ERROR_WANT_X509_LOOKUP; - errstr = - "The operation did not complete (X509 lookup)"; + errstr = "The operation did not complete (X509 lookup)"; break; case SSL_ERROR_WANT_CONNECT: p = PY_SSL_ERROR_WANT_CONNECT; @@ -196,15 +195,14 @@ PySocketSockObject *s = (PySocketSockObject *) PyWeakref_GetObject(obj->Socket); if (ret == 0 || (((PyObject *)s) == Py_None)) { - p = PY_SSL_ERROR_EOF; - errstr = - "EOF occurred in violation of protocol"; + p = PY_SSL_ERROR_EOF; + errstr = "EOF occurred in violation of protocol"; } else if (ret == -1) { - /* underlying BIO reported an I/O error */ - return s->errorhandler(); + /* underlying BIO reported an I/O error */ + return s->errorhandler(); } else { /* possible? */ - p = PY_SSL_ERROR_SYSCALL; - errstr = "Some I/O error occurred"; + p = PY_SSL_ERROR_SYSCALL; + errstr = "Some I/O error occurred"; } } else { p = PY_SSL_ERROR_SYSCALL; @@ -221,8 +219,7 @@ /* XXX Protected by global interpreter lock */ errstr = ERR_error_string(e, NULL); else { /* possible? */ - errstr = - "A failure in the SSL library occurred"; + errstr = "A failure in the SSL library occurred"; } break; } @@ -325,7 +322,7 @@ if (certreq != PY_SSL_CERT_NONE) { if (cacerts_file == NULL) { errstr = ERRSTR("No root certificates specified for " - "verification of other-side certificates."); + "verification of other-side certificates."); goto fail; } else { PySSL_BEGIN_ALLOW_THREADS @@ -490,15 +487,15 @@ } if (sockstate == SOCKET_HAS_TIMED_OUT) { PyErr_SetString(PySSLErrorObject, - ERRSTR("The handshake operation timed out")); + ERRSTR("The handshake operation timed out")); return NULL; } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) { PyErr_SetString(PySSLErrorObject, - ERRSTR("Underlying socket has been closed.")); + ERRSTR("Underlying socket has been closed.")); return NULL; } else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) { PyErr_SetString(PySSLErrorObject, - ERRSTR("Underlying socket too large for select().")); + ERRSTR("Underlying socket too large for select().")); return NULL; } else if (sockstate == SOCKET_IS_NONBLOCKING) { break; @@ -544,7 +541,7 @@ goto fail; } value_obj = PyUnicode_DecodeUTF8((char *) valuebuf, - buflen, "strict"); + buflen, "strict"); OPENSSL_free(valuebuf); if (value_obj == NULL) { Py_DECREF(name_obj); @@ -1217,11 +1214,9 @@ goto error; } if (err == SSL_ERROR_WANT_READ) { - sockstate = - check_socket_and_wait_for_timeout(sock, 0); + sockstate = check_socket_and_wait_for_timeout(sock, 0); } else if (err == SSL_ERROR_WANT_WRITE) { - sockstate = - check_socket_and_wait_for_timeout(sock, 1); + sockstate = check_socket_and_wait_for_timeout(sock, 1); } else { sockstate = SOCKET_OPERATION_OK; } @@ -1334,7 +1329,7 @@ goto error; } else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) { PyErr_SetString(PySSLErrorObject, - "Underlying socket too large for select()."); + "Underlying socket too large for select()."); goto error; } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) { count = 0; @@ -1350,11 +1345,9 @@ if (PyErr_CheckSignals()) goto error; if (err == SSL_ERROR_WANT_READ) { - sockstate = - check_socket_and_wait_for_timeout(sock, 0); + sockstate = check_socket_and_wait_for_timeout(sock, 0); } else if (err == SSL_ERROR_WANT_WRITE) { - sockstate = - check_socket_and_wait_for_timeout(sock, 1); + sockstate = check_socket_and_wait_for_timeout(sock, 1); } else if ((err == SSL_ERROR_ZERO_RETURN) && (SSL_get_shutdown(self->ssl) == SSL_RECEIVED_SHUTDOWN)) @@ -1547,7 +1540,7 @@ double entropy; if (!PyArg_ParseTuple(args, "s#d:RAND_add", &buf, &len, &entropy)) - return NULL; + return NULL; RAND_add(buf, len, entropy); Py_INCREF(Py_None); return Py_None; @@ -1578,15 +1571,15 @@ int bytes; if (!PyUnicode_Check(arg)) - return PyErr_Format(PyExc_TypeError, - "RAND_egd() expected string, found %s", - Py_TYPE(arg)->tp_name); + return PyErr_Format(PyExc_TypeError, + "RAND_egd() expected string, found %s", + Py_TYPE(arg)->tp_name); bytes = RAND_egd(_PyUnicode_AsString(arg)); if (bytes == -1) { - PyErr_SetString(PySSLErrorObject, - "EGD connection failed or EGD did not return " - "enough data to seed the PRNG"); - return NULL; + PyErr_SetString(PySSLErrorObject, + "EGD connection failed or EGD did not return " + "enough data to seed the PRNG"); + return NULL; } return PyLong_FromLong(bytes); } Modified: python/branches/py3k-cdecimal/Modules/_testcapimodule.c ============================================================================== --- python/branches/py3k-cdecimal/Modules/_testcapimodule.c (original) +++ python/branches/py3k-cdecimal/Modules/_testcapimodule.c Sun May 16 00:01:19 2010 @@ -2005,6 +2005,17 @@ return PyErr_NewExceptionWithDoc(name, doc, base, dict); } +/* Test that the fatal error from not having a current thread doesn't + cause an infinite loop. Run via Lib/test/test_capi.py */ +static PyObject * +crash_no_current_thread(PyObject *self) +{ + Py_BEGIN_ALLOW_THREADS + PyErr_SetString(PyExc_SystemError, "bork bork bork"); + Py_END_ALLOW_THREADS + return NULL; +} + static PyMethodDef TestMethods[] = { {"raise_exception", raise_exception, METH_VARARGS}, {"raise_memoryerror", (PyCFunction)raise_memoryerror, METH_NOARGS}, @@ -2069,6 +2080,7 @@ {"code_newempty", code_newempty, METH_VARARGS}, {"make_exception_with_doc", (PyCFunction)make_exception_with_doc, METH_VARARGS | METH_KEYWORDS}, + {"crash_no_current_thread", (PyCFunction)crash_no_current_thread, METH_NOARGS}, {NULL, NULL} /* sentinel */ }; Modified: python/branches/py3k-cdecimal/Modules/_tkinter.c ============================================================================== --- python/branches/py3k-cdecimal/Modules/_tkinter.c (original) +++ python/branches/py3k-cdecimal/Modules/_tkinter.c Sun May 16 00:01:19 2010 @@ -3147,9 +3147,7 @@ it also helps Tcl find its encodings. */ uexe = PyUnicode_FromWideChar(Py_GetProgramName(), -1); if (uexe) { - cexe = PyUnicode_AsEncodedString(uexe, - Py_FileSystemDefaultEncoding, - NULL); + cexe = PyUnicode_EncodeFSDefault(uexe); if (cexe) Tcl_FindExecutable(PyBytes_AsString(cexe)); Py_XDECREF(cexe); Modified: python/branches/py3k-cdecimal/Modules/grpmodule.c ============================================================================== --- python/branches/py3k-cdecimal/Modules/grpmodule.c (original) +++ python/branches/py3k-cdecimal/Modules/grpmodule.c Sun May 16 00:01:19 2010 @@ -111,8 +111,7 @@ if (!PyArg_ParseTuple(args, "U:getgrnam", &arg)) return NULL; - if ((bytes = PyUnicode_AsEncodedString(arg, Py_FileSystemDefaultEncoding, - "surrogateescape")) == NULL) + if ((bytes = PyUnicode_EncodeFSDefault(arg)) == NULL) return NULL; if (PyBytes_AsStringAndSize(bytes, &name, NULL) == -1) goto out; Modified: python/branches/py3k-cdecimal/Modules/mathmodule.c ============================================================================== --- python/branches/py3k-cdecimal/Modules/mathmodule.c (original) +++ python/branches/py3k-cdecimal/Modules/mathmodule.c Sun May 16 00:01:19 2010 @@ -1129,18 +1129,239 @@ Return an accurate floating point sum of values in the iterable.\n\ Assumes IEEE-754 floating point arithmetic."); +/* Return the smallest integer k such that n < 2**k, or 0 if n == 0. + * Equivalent to floor(lg(x))+1. Also equivalent to: bitwidth_of_type - + * count_leading_zero_bits(x) + */ + +/* XXX: This routine does more or less the same thing as + * bits_in_digit() in Objects/longobject.c. Someday it would be nice to + * consolidate them. On BSD, there's a library function called fls() + * that we could use, and GCC provides __builtin_clz(). + */ + +static unsigned long +bit_length(unsigned long n) +{ + unsigned long len = 0; + while (n != 0) { + ++len; + n >>= 1; + } + return len; +} + +static unsigned long +count_set_bits(unsigned long n) +{ + unsigned long count = 0; + while (n != 0) { + ++count; + n &= n - 1; /* clear least significant bit */ + } + return count; +} + +/* Divide-and-conquer factorial algorithm + * + * Based on the formula and psuedo-code provided at: + * http://www.luschny.de/math/factorial/binarysplitfact.html + * + * Faster algorithms exist, but they're more complicated and depend on + * a fast prime factoriazation algorithm. + * + * Notes on the algorithm + * ---------------------- + * + * factorial(n) is written in the form 2**k * m, with m odd. k and m are + * computed separately, and then combined using a left shift. + * + * The function factorial_odd_part computes the odd part m (i.e., the greatest + * odd divisor) of factorial(n), using the formula: + * + * factorial_odd_part(n) = + * + * product_{i >= 0} product_{0 < j <= n / 2**i, j odd} j + * + * Example: factorial_odd_part(20) = + * + * (1) * + * (1) * + * (1 * 3 * 5) * + * (1 * 3 * 5 * 7 * 9) + * (1 * 3 * 5 * 7 * 9 * 11 * 13 * 15 * 17 * 19) + * + * Here i goes from large to small: the first term corresponds to i=4 (any + * larger i gives an empty product), and the last term corresponds to i=0. + * Each term can be computed from the last by multiplying by the extra odd + * numbers required: e.g., to get from the penultimate term to the last one, + * we multiply by (11 * 13 * 15 * 17 * 19). + * + * To see a hint of why this formula works, here are the same numbers as above + * but with the even parts (i.e., the appropriate powers of 2) included. For + * each subterm in the product for i, we multiply that subterm by 2**i: + * + * factorial(20) = + * + * (16) * + * (8) * + * (4 * 12 * 20) * + * (2 * 6 * 10 * 14 * 18) * + * (1 * 3 * 5 * 7 * 9 * 11 * 13 * 15 * 17 * 19) + * + * The factorial_partial_product function computes the product of all odd j in + * range(start, stop) for given start and stop. It's used to compute the + * partial products like (11 * 13 * 15 * 17 * 19) in the example above. It + * operates recursively, repeatedly splitting the range into two roughly equal + * pieces until the subranges are small enough to be computed using only C + * integer arithmetic. + * + * The two-valuation k (i.e., the exponent of the largest power of 2 dividing + * the factorial) is computed independently in the main math_factorial + * function. By standard results, its value is: + * + * two_valuation = n//2 + n//4 + n//8 + .... + * + * It can be shown (e.g., by complete induction on n) that two_valuation is + * equal to n - count_set_bits(n), where count_set_bits(n) gives the number of + * '1'-bits in the binary expansion of n. + */ + +/* factorial_partial_product: Compute product(range(start, stop, 2)) using + * divide and conquer. Assumes start and stop are odd and stop > start. + * max_bits must be >= bit_length(stop - 2). */ + +static PyObject * +factorial_partial_product(unsigned long start, unsigned long stop, + unsigned long max_bits) +{ + unsigned long midpoint, num_operands; + PyObject *left = NULL, *right = NULL, *result = NULL; + + /* If the return value will fit an unsigned long, then we can + * multiply in a tight, fast loop where each multiply is O(1). + * Compute an upper bound on the number of bits required to store + * the answer. + * + * Storing some integer z requires floor(lg(z))+1 bits, which is + * conveniently the value returned by bit_length(z). The + * product x*y will require at most + * bit_length(x) + bit_length(y) bits to store, based + * on the idea that lg product = lg x + lg y. + * + * We know that stop - 2 is the largest number to be multiplied. From + * there, we have: bit_length(answer) <= num_operands * + * bit_length(stop - 2) + */ + + num_operands = (stop - start) / 2; + /* The "num_operands <= 8 * SIZEOF_LONG" check guards against the + * unlikely case of an overflow in num_operands * max_bits. */ + if (num_operands <= 8 * SIZEOF_LONG && + num_operands * max_bits <= 8 * SIZEOF_LONG) { + unsigned long j, total; + for (total = start, j = start + 2; j < stop; j += 2) + total *= j; + return PyLong_FromUnsignedLong(total); + } + + /* find midpoint of range(start, stop), rounded up to next odd number. */ + midpoint = (start + num_operands) | 1; + left = factorial_partial_product(start, midpoint, + bit_length(midpoint - 2)); + if (left == NULL) + goto error; + right = factorial_partial_product(midpoint, stop, max_bits); + if (right == NULL) + goto error; + result = PyNumber_Multiply(left, right); + + error: + Py_XDECREF(left); + Py_XDECREF(right); + return result; +} + +/* factorial_odd_part: compute the odd part of factorial(n). */ + +static PyObject * +factorial_odd_part(unsigned long n) +{ + long i; + unsigned long v, lower, upper; + PyObject *partial, *tmp, *inner, *outer; + + inner = PyLong_FromLong(1); + if (inner == NULL) + return NULL; + outer = inner; + Py_INCREF(outer); + + upper = 3; + for (i = bit_length(n) - 2; i >= 0; i--) { + v = n >> i; + if (v <= 2) + continue; + lower = upper; + /* (v + 1) | 1 = least odd integer strictly larger than n / 2**i */ + upper = (v + 1) | 1; + /* Here inner is the product of all odd integers j in the range (0, + n/2**(i+1)]. The factorial_partial_product call below gives the + product of all odd integers j in the range (n/2**(i+1), n/2**i]. */ + partial = factorial_partial_product(lower, upper, bit_length(upper-2)); + /* inner *= partial */ + if (partial == NULL) + goto error; + tmp = PyNumber_Multiply(inner, partial); + Py_DECREF(partial); + if (tmp == NULL) + goto error; + Py_DECREF(inner); + inner = tmp; + /* Now inner is the product of all odd integers j in the range (0, + n/2**i], giving the inner product in the formula above. */ + + /* outer *= inner; */ + tmp = PyNumber_Multiply(outer, inner); + if (tmp == NULL) + goto error; + Py_DECREF(outer); + outer = tmp; + } + + goto done; + + error: + Py_DECREF(outer); + done: + Py_DECREF(inner); + return outer; +} + +/* Lookup table for small factorial values */ + +static const unsigned long SmallFactorials[] = { + 1, 1, 2, 6, 24, 120, 720, 5040, 40320, + 362880, 3628800, 39916800, 479001600, +#if SIZEOF_LONG >= 8 + 6227020800, 87178291200, 1307674368000, + 20922789888000, 355687428096000, 6402373705728000, + 121645100408832000, 2432902008176640000 +#endif +}; + static PyObject * math_factorial(PyObject *self, PyObject *arg) { - long i, x; - PyObject *result, *iobj, *newresult; + long x; + PyObject *result, *odd_part, *two_valuation; if (PyFloat_Check(arg)) { PyObject *lx; double dx = PyFloat_AS_DOUBLE((PyFloatObject *)arg); if (!(Py_IS_FINITE(dx) && dx == floor(dx))) { PyErr_SetString(PyExc_ValueError, - "factorial() only accepts integral values"); + "factorial() only accepts integral values"); return NULL; } lx = PyLong_FromDouble(dx); @@ -1156,29 +1377,28 @@ return NULL; if (x < 0) { PyErr_SetString(PyExc_ValueError, - "factorial() not defined for negative values"); + "factorial() not defined for negative values"); return NULL; } - result = (PyObject *)PyLong_FromLong(1); - if (result == NULL) + /* use lookup table if x is small */ + if (x < (long)(sizeof(SmallFactorials)/sizeof(SmallFactorials[0]))) + return PyLong_FromUnsignedLong(SmallFactorials[x]); + + /* else express in the form odd_part * 2**two_valuation, and compute as + odd_part << two_valuation. */ + odd_part = factorial_odd_part(x); + if (odd_part == NULL) + return NULL; + two_valuation = PyLong_FromLong(x - count_set_bits(x)); + if (two_valuation == NULL) { + Py_DECREF(odd_part); return NULL; - for (i=1 ; i<=x ; i++) { - iobj = (PyObject *)PyLong_FromLong(i); - if (iobj == NULL) - goto error; - newresult = PyNumber_Multiply(result, iobj); - Py_DECREF(iobj); - if (newresult == NULL) - goto error; - Py_DECREF(result); - result = newresult; } + result = PyNumber_Lshift(odd_part, two_valuation); + Py_DECREF(two_valuation); + Py_DECREF(odd_part); return result; - -error: - Py_DECREF(result); - return NULL; } PyDoc_STRVAR(math_factorial_doc, Modified: python/branches/py3k-cdecimal/Modules/posixmodule.c ============================================================================== --- python/branches/py3k-cdecimal/Modules/posixmodule.c (original) +++ python/branches/py3k-cdecimal/Modules/posixmodule.c Sun May 16 00:01:19 2010 @@ -2364,33 +2364,17 @@ (NAMLEN(ep) == 1 || (ep->d_name[1] == '.' && NAMLEN(ep) == 2))) continue; - v = PyBytes_FromStringAndSize(ep->d_name, NAMLEN(ep)); + if (arg_is_unicode) + v = PyUnicode_DecodeFSDefaultAndSize(ep->d_name, NAMLEN(ep)); + else + v = PyBytes_FromStringAndSize(ep->d_name, NAMLEN(ep)); if (v == NULL) { - Py_DECREF(d); - d = NULL; + Py_CLEAR(d); break; } - if (arg_is_unicode) { - PyObject *w; - - w = PyUnicode_FromEncodedObject(v, - Py_FileSystemDefaultEncoding, - "surrogateescape"); - Py_DECREF(v); - if (w != NULL) - v = w; - else { - /* Encoding failed to decode ASCII bytes. - Raise exception. */ - Py_DECREF(d); - d = NULL; - break; - } - } if (PyList_Append(d, v) != 0) { Py_DECREF(v); - Py_DECREF(d); - d = NULL; + Py_CLEAR(d); break; } Py_DECREF(v); @@ -4078,7 +4062,7 @@ static PyObject * win32_kill(PyObject *self, PyObject *args) { - PyObject *result, handle_obj; + PyObject *result; DWORD pid, sig, err; HANDLE handle; @@ -4605,22 +4589,10 @@ return posix_error_with_allocated_filename(opath); Py_DECREF(opath); - v = PyBytes_FromStringAndSize(buf, n); - if (arg_is_unicode) { - PyObject *w; - - w = PyUnicode_FromEncodedObject(v, - Py_FileSystemDefaultEncoding, - "surrogateescape"); - if (w != NULL) { - Py_DECREF(v); - v = w; - } - else { - v = NULL; - } - } - return v; + if (arg_is_unicode) + return PyUnicode_DecodeFSDefaultAndSize(buf, n); + else + return PyBytes_FromStringAndSize(buf, n); } #endif /* HAVE_READLINK */ Modified: python/branches/py3k-cdecimal/Modules/pwdmodule.c ============================================================================== --- python/branches/py3k-cdecimal/Modules/pwdmodule.c (original) +++ python/branches/py3k-cdecimal/Modules/pwdmodule.c Sun May 16 00:01:19 2010 @@ -132,9 +132,7 @@ if (!PyArg_ParseTuple(args, "U:getpwnam", &arg)) return NULL; - if ((bytes = PyUnicode_AsEncodedString(arg, - Py_FileSystemDefaultEncoding, - "surrogateescape")) == NULL) + if ((bytes = PyUnicode_EncodeFSDefault(arg)) == NULL) return NULL; if (PyBytes_AsStringAndSize(bytes, &name, NULL) == -1) goto out; Modified: python/branches/py3k-cdecimal/Modules/spwdmodule.c ============================================================================== --- python/branches/py3k-cdecimal/Modules/spwdmodule.c (original) +++ python/branches/py3k-cdecimal/Modules/spwdmodule.c Sun May 16 00:01:19 2010 @@ -118,9 +118,7 @@ if (!PyArg_ParseTuple(args, "U:getspnam", &arg)) return NULL; - if ((bytes = PyUnicode_AsEncodedString(arg, - Py_FileSystemDefaultEncoding, - "surrogateescape")) == NULL) + if ((bytes = PyUnicode_EncodeFSDefault(arg)) == NULL) return NULL; if (PyBytes_AsStringAndSize(bytes, &name, NULL) == -1) goto out; Modified: python/branches/py3k-cdecimal/Objects/unicodeobject.c ============================================================================== --- python/branches/py3k-cdecimal/Objects/unicodeobject.c (original) +++ python/branches/py3k-cdecimal/Objects/unicodeobject.c Sun May 16 00:01:19 2010 @@ -1461,6 +1461,18 @@ return NULL; } +PyObject *PyUnicode_EncodeFSDefault(PyObject *unicode) +{ + if (Py_FileSystemDefaultEncoding) + return PyUnicode_AsEncodedString(unicode, + Py_FileSystemDefaultEncoding, + "surrogateescape"); + else + return PyUnicode_EncodeUTF8(PyUnicode_AS_UNICODE(unicode), + PyUnicode_GET_SIZE(unicode), + "surrogateescape"); +} + PyObject *PyUnicode_AsEncodedString(PyObject *unicode, const char *encoding, const char *errors) @@ -1476,31 +1488,39 @@ encoding = PyUnicode_GetDefaultEncoding(); /* Shortcuts for common default encodings */ - if (errors == NULL) { - if (strcmp(encoding, "utf-8") == 0) - return PyUnicode_AsUTF8String(unicode); - else if (strcmp(encoding, "latin-1") == 0) - return PyUnicode_AsLatin1String(unicode); + if (strcmp(encoding, "utf-8") == 0) + return PyUnicode_EncodeUTF8(PyUnicode_AS_UNICODE(unicode), + PyUnicode_GET_SIZE(unicode), + errors); + else if (strcmp(encoding, "latin-1") == 0) + return PyUnicode_EncodeLatin1(PyUnicode_AS_UNICODE(unicode), + PyUnicode_GET_SIZE(unicode), + errors); #if defined(MS_WINDOWS) && defined(HAVE_USABLE_WCHAR_T) - else if (strcmp(encoding, "mbcs") == 0) - return PyUnicode_AsMBCSString(unicode); -#endif - else if (strcmp(encoding, "ascii") == 0) - return PyUnicode_AsASCIIString(unicode); - /* During bootstrap, we may need to find the encodings - package, to load the file system encoding, and require the - file system encoding in order to load the encodings - package. - - Break out of this dependency by assuming that the path to - the encodings module is ASCII-only. XXX could try wcstombs - instead, if the file system encoding is the locale's - encoding. */ - else if (Py_FileSystemDefaultEncoding && - strcmp(encoding, Py_FileSystemDefaultEncoding) == 0 && - !PyThreadState_GET()->interp->codecs_initialized) - return PyUnicode_AsASCIIString(unicode); - } + else if (strcmp(encoding, "mbcs") == 0) + return PyUnicode_EncodeMBCS(PyUnicode_AS_UNICODE(unicode), + PyUnicode_GET_SIZE(unicode), + errors); +#endif + else if (strcmp(encoding, "ascii") == 0) + return PyUnicode_EncodeASCII(PyUnicode_AS_UNICODE(unicode), + PyUnicode_GET_SIZE(unicode), + errors); + /* During bootstrap, we may need to find the encodings + package, to load the file system encoding, and require the + file system encoding in order to load the encodings + package. + + Break out of this dependency by assuming that the path to + the encodings module is ASCII-only. XXX could try wcstombs + instead, if the file system encoding is the locale's + encoding. */ + else if (Py_FileSystemDefaultEncoding && + strcmp(encoding, Py_FileSystemDefaultEncoding) == 0 && + !PyThreadState_GET()->interp->codecs_initialized) + return PyUnicode_EncodeASCII(PyUnicode_AS_UNICODE(unicode), + PyUnicode_GET_SIZE(unicode), + errors); /* Encode via the codec registry */ v = PyCodec_Encode(unicode, encoding, errors); @@ -1638,9 +1658,7 @@ arg = PyUnicode_FromObject(arg); if (!arg) return 0; - output = PyUnicode_AsEncodedObject(arg, - Py_FileSystemDefaultEncoding, - "surrogateescape"); + output = PyUnicode_EncodeFSDefault(arg); Py_DECREF(arg); if (!output) return 0; Modified: python/branches/py3k-cdecimal/Python/bltinmodule.c ============================================================================== --- python/branches/py3k-cdecimal/Python/bltinmodule.c (original) +++ python/branches/py3k-cdecimal/Python/bltinmodule.c Sun May 16 00:01:19 2010 @@ -9,6 +9,10 @@ #include +#ifdef HAVE_LANGINFO_H +#include /* CODESET */ +#endif + /* The default encoding used by the platform file system APIs Can remain NULL for all platforms that don't have such a concept @@ -21,9 +25,12 @@ #elif defined(__APPLE__) const char *Py_FileSystemDefaultEncoding = "utf-8"; int Py_HasFileSystemDefaultEncoding = 1; -#else -const char *Py_FileSystemDefaultEncoding = NULL; /* use default */ +#elif defined(HAVE_LANGINFO_H) && defined(CODESET) +const char *Py_FileSystemDefaultEncoding = NULL; /* set by initfsencoding() */ int Py_HasFileSystemDefaultEncoding = 0; +#else +const char *Py_FileSystemDefaultEncoding = "utf-8"; +int Py_HasFileSystemDefaultEncoding = 1; #endif int Modified: python/branches/py3k-cdecimal/Python/dtoa.c ============================================================================== --- python/branches/py3k-cdecimal/Python/dtoa.c (original) +++ python/branches/py3k-cdecimal/Python/dtoa.c Sun May 16 00:01:19 2010 @@ -1382,7 +1382,6 @@ Bigint *b, *d; int b2, d2, dd, i, nd, nd0, odd, p2, p5; - dd = 0; /* silence compiler warning about possibly unused variable */ nd = bc->nd; nd0 = bc->nd0; p5 = nd + bc->e0; @@ -2362,7 +2361,7 @@ /* set pointers to NULL, to silence gcc compiler warnings and make cleanup easier on error */ - mlo = mhi = b = S = 0; + mlo = mhi = S = 0; s0 = 0; u.d = dd; @@ -2713,8 +2712,6 @@ * and for all and pass them and a shift to quorem, so it * can do shifts and ors to compute the numerator for q. */ - if ((i = ((s5 ? 32 - hi0bits(S->x[S->wds-1]) : 1) + s2) & 0x1f)) - i = 32 - i; #define iInc 28 i = dshift(S, s2); b2 += i; Modified: python/branches/py3k-cdecimal/Python/errors.c ============================================================================== --- python/branches/py3k-cdecimal/Python/errors.c (original) +++ python/branches/py3k-cdecimal/Python/errors.c Sun May 16 00:01:19 2010 @@ -130,9 +130,14 @@ PyObject * PyErr_Occurred(void) { - PyThreadState *tstate = PyThreadState_GET(); + /* If there is no thread state, PyThreadState_GET calls + Py_FatalError, which calls PyErr_Occurred. To avoid the + resulting infinite loop, we inline PyThreadState_GET here and + treat no thread as no error. */ + PyThreadState *tstate = + ((PyThreadState*)_Py_atomic_load_relaxed(&_PyThreadState_Current)); - return tstate->curexc_type; + return tstate == NULL ? NULL : tstate->curexc_type; } Modified: python/branches/py3k-cdecimal/Python/import.c ============================================================================== --- python/branches/py3k-cdecimal/Python/import.c (original) +++ python/branches/py3k-cdecimal/Python/import.c Sun May 16 00:01:19 2010 @@ -1633,8 +1633,7 @@ if (!v) return NULL; if (PyUnicode_Check(v)) { - v = PyUnicode_AsEncodedString(v, - Py_FileSystemDefaultEncoding, NULL); + v = PyUnicode_EncodeFSDefault(v); if (v == NULL) return NULL; } @@ -2752,14 +2751,7 @@ char *subname; PyObject *submod; char *p; - if (!Py_FileSystemDefaultEncoding) { - item8 = PyUnicode_EncodeASCII(PyUnicode_AsUnicode(item), - PyUnicode_GetSize(item), - NULL); - } else { - item8 = PyUnicode_AsEncodedString(item, - Py_FileSystemDefaultEncoding, NULL); - } + item8 = PyUnicode_EncodeFSDefault(item); if (!item8) { PyErr_SetString(PyExc_ValueError, "Cannot encode path item"); return 0; Modified: python/branches/py3k-cdecimal/Python/pythonrun.c ============================================================================== --- python/branches/py3k-cdecimal/Python/pythonrun.c (original) +++ python/branches/py3k-cdecimal/Python/pythonrun.c Sun May 16 00:01:19 2010 @@ -57,6 +57,7 @@ /* Forward */ static void initmain(void); +static void initfsencoding(void); static void initsite(void); static int initstdio(void); static void flush_io(void); @@ -159,7 +160,6 @@ error: Py_XDECREF(codec); - PyErr_Clear(); return NULL; } #endif @@ -171,9 +171,6 @@ PyThreadState *tstate; PyObject *bimod, *sysmod, *pstderr; char *p; -#if defined(HAVE_LANGINFO_H) && defined(CODESET) - char *codeset; -#endif extern void _Py_ReadyTypes(void); if (initialized) @@ -264,21 +261,7 @@ _PyImportHooks_Init(); -#if defined(HAVE_LANGINFO_H) && defined(CODESET) - /* On Unix, set the file system encoding according to the - user's preference, if the CODESET names a well-known - Python codec, and Py_FileSystemDefaultEncoding isn't - initialized by other means. Also set the encoding of - stdin and stdout if these are terminals. */ - - codeset = get_codeset(); - if (codeset) { - if (!Py_FileSystemDefaultEncoding) - Py_FileSystemDefaultEncoding = codeset; - else - free(codeset); - } -#endif + initfsencoding(); if (install_sigs) initsigs(); /* Signal handling stuff, including initintr() */ @@ -334,7 +317,7 @@ Py_DECREF(tmp); } - if (ferr != NULL || ferr != Py_None) { + if (ferr != NULL && ferr != Py_None) { tmp = PyObject_CallMethod(ferr, "flush", ""); if (tmp == NULL) PyErr_Clear(); @@ -496,7 +479,7 @@ _PyUnicode_Fini(); /* reset file system default encoding */ - if (!Py_HasFileSystemDefaultEncoding) { + if (!Py_HasFileSystemDefaultEncoding && Py_FileSystemDefaultEncoding) { free((char*)Py_FileSystemDefaultEncoding); Py_FileSystemDefaultEncoding = NULL; } @@ -707,6 +690,45 @@ } } +static void +initfsencoding(void) +{ + PyObject *codec; +#if defined(HAVE_LANGINFO_H) && defined(CODESET) + char *codeset; + + /* On Unix, set the file system encoding according to the + user's preference, if the CODESET names a well-known + Python codec, and Py_FileSystemDefaultEncoding isn't + initialized by other means. Also set the encoding of + stdin and stdout if these are terminals. */ + codeset = get_codeset(); + if (codeset != NULL) { + Py_FileSystemDefaultEncoding = codeset; + Py_HasFileSystemDefaultEncoding = 0; + return; + } + + PyErr_Clear(); + fprintf(stderr, + "Unable to get the locale encoding: " + "fallback to utf-8\n"); + Py_FileSystemDefaultEncoding = "utf-8"; + Py_HasFileSystemDefaultEncoding = 1; +#endif + + /* the encoding is mbcs, utf-8 or ascii */ + codec = _PyCodec_Lookup(Py_FileSystemDefaultEncoding); + if (!codec) { + /* Such error can only occurs in critical situations: no more + * memory, import a module of the standard library failed, + * etc. */ + Py_FatalError("Py_Initialize: unable to load the file system codec"); + } else { + Py_DECREF(codec); + } +} + /* Import the site module (not into __main__ though) */ static void From python-checkins at python.org Sun May 16 00:19:27 2010 From: python-checkins at python.org (victor.stinner) Date: Sun, 16 May 2010 00:19:27 +0200 (CEST) Subject: [Python-checkins] r81213 - python/trunk/Modules/_cursesmodule.c Message-ID: <20100515221927.64C5BEEB3B@mail.python.org> Author: victor.stinner Date: Sun May 16 00:19:27 2010 New Revision: 81213 Log: reindent _cursesmodule.c Use untabify.py + emacs (python3 mode) + manual editions for Py_BEGIN_ALLOW_THREADS / Py_END_ALLOW_THREADS Modified: python/trunk/Modules/_cursesmodule.c Modified: python/trunk/Modules/_cursesmodule.c ============================================================================== --- python/trunk/Modules/_cursesmodule.c (original) +++ python/trunk/Modules/_cursesmodule.c Sun May 16 00:19:27 2010 @@ -33,66 +33,66 @@ /* -A number of SysV or ncurses functions don't have wrappers yet; if you -need a given function, add it and send a patch. See -http://www.python.org/dev/patches/ for instructions on how to submit -patches to Python. - -Here's a list of currently unsupported functions: - - addchnstr addchstr color_set define_key - del_curterm delscreen dupwin inchnstr inchstr innstr keyok - mcprint mvaddchnstr mvaddchstr mvcur mvinchnstr - mvinchstr mvinnstr mmvwaddchnstr mvwaddchstr - mvwinchnstr mvwinchstr mvwinnstr newterm - restartterm ripoffline scr_dump - scr_init scr_restore scr_set scrl set_curterm set_term setterm - tgetent tgetflag tgetnum tgetstr tgoto timeout tputs - vidattr vidputs waddchnstr waddchstr - wcolor_set winchnstr winchstr winnstr wmouse_trafo wscrl - -Low-priority: - slk_attr slk_attr_off slk_attr_on slk_attr_set slk_attroff - slk_attron slk_attrset slk_clear slk_color slk_init slk_label - slk_noutrefresh slk_refresh slk_restore slk_set slk_touch - -Menu extension (ncurses and probably SYSV): - current_item free_item free_menu item_count item_description - item_index item_init item_name item_opts item_opts_off - item_opts_on item_term item_userptr item_value item_visible - menu_back menu_driver menu_fore menu_format menu_grey - menu_init menu_items menu_mark menu_opts menu_opts_off - menu_opts_on menu_pad menu_pattern menu_request_by_name - menu_request_name menu_spacing menu_sub menu_term menu_userptr - menu_win new_item new_menu pos_menu_cursor post_menu - scale_menu set_current_item set_item_init set_item_opts - set_item_term set_item_userptr set_item_value set_menu_back - set_menu_fore set_menu_format set_menu_grey set_menu_init - set_menu_items set_menu_mark set_menu_opts set_menu_pad - set_menu_pattern set_menu_spacing set_menu_sub set_menu_term - set_menu_userptr set_menu_win set_top_row top_row unpost_menu - -Form extension (ncurses and probably SYSV): - current_field data_ahead data_behind dup_field - dynamic_fieldinfo field_arg field_back field_buffer - field_count field_fore field_index field_info field_init - field_just field_opts field_opts_off field_opts_on field_pad - field_status field_term field_type field_userptr form_driver - form_fields form_init form_opts form_opts_off form_opts_on - form_page form_request_by_name form_request_name form_sub - form_term form_userptr form_win free_field free_form - link_field link_fieldtype move_field new_field new_form - new_page pos_form_cursor post_form scale_form - set_current_field set_field_back set_field_buffer - set_field_fore set_field_init set_field_just set_field_opts - set_field_pad set_field_status set_field_term set_field_type - set_field_userptr set_fieldtype_arg set_fieldtype_choice - set_form_fields set_form_init set_form_opts set_form_page - set_form_sub set_form_term set_form_userptr set_form_win - set_max_field set_new_page unpost_form + A number of SysV or ncurses functions don't have wrappers yet; if you + need a given function, add it and send a patch. See + http://www.python.org/dev/patches/ for instructions on how to submit + patches to Python. + + Here's a list of currently unsupported functions: + + addchnstr addchstr color_set define_key + del_curterm delscreen dupwin inchnstr inchstr innstr keyok + mcprint mvaddchnstr mvaddchstr mvcur mvinchnstr + mvinchstr mvinnstr mmvwaddchnstr mvwaddchstr + mvwinchnstr mvwinchstr mvwinnstr newterm + restartterm ripoffline scr_dump + scr_init scr_restore scr_set scrl set_curterm set_term setterm + tgetent tgetflag tgetnum tgetstr tgoto timeout tputs + vidattr vidputs waddchnstr waddchstr + wcolor_set winchnstr winchstr winnstr wmouse_trafo wscrl + + Low-priority: + slk_attr slk_attr_off slk_attr_on slk_attr_set slk_attroff + slk_attron slk_attrset slk_clear slk_color slk_init slk_label + slk_noutrefresh slk_refresh slk_restore slk_set slk_touch + + Menu extension (ncurses and probably SYSV): + current_item free_item free_menu item_count item_description + item_index item_init item_name item_opts item_opts_off + item_opts_on item_term item_userptr item_value item_visible + menu_back menu_driver menu_fore menu_format menu_grey + menu_init menu_items menu_mark menu_opts menu_opts_off + menu_opts_on menu_pad menu_pattern menu_request_by_name + menu_request_name menu_spacing menu_sub menu_term menu_userptr + menu_win new_item new_menu pos_menu_cursor post_menu + scale_menu set_current_item set_item_init set_item_opts + set_item_term set_item_userptr set_item_value set_menu_back + set_menu_fore set_menu_format set_menu_grey set_menu_init + set_menu_items set_menu_mark set_menu_opts set_menu_pad + set_menu_pattern set_menu_spacing set_menu_sub set_menu_term + set_menu_userptr set_menu_win set_top_row top_row unpost_menu + + Form extension (ncurses and probably SYSV): + current_field data_ahead data_behind dup_field + dynamic_fieldinfo field_arg field_back field_buffer + field_count field_fore field_index field_info field_init + field_just field_opts field_opts_off field_opts_on field_pad + field_status field_term field_type field_userptr form_driver + form_fields form_init form_opts form_opts_off form_opts_on + form_page form_request_by_name form_request_name form_sub + form_term form_userptr form_win free_field free_form + link_field link_fieldtype move_field new_field new_form + new_page pos_form_cursor post_form scale_form + set_current_field set_field_back set_field_buffer + set_field_fore set_field_init set_field_just set_field_opts + set_field_pad set_field_status set_field_term set_field_type + set_field_userptr set_fieldtype_arg set_fieldtype_choice + set_form_fields set_form_init set_form_opts set_form_page + set_form_sub set_form_term set_form_userptr set_form_win + set_max_field set_new_page unpost_form - */ +*/ /* Release Number */ @@ -113,9 +113,9 @@ #define CURSES_MODULE #include "py_curses.h" -/* These prototypes are in , but including this header - #defines many common symbols (such as "lines") which breaks the - curses module in other ways. So the code will just specify +/* These prototypes are in , but including this header + #defines many common symbols (such as "lines") which breaks the + curses module in other ways. So the code will just specify explicit prototypes here. */ extern int setupterm(char *,int,int *); #ifdef __sgi @@ -145,23 +145,23 @@ static int initialisedcolors = FALSE; /* Utility Macros */ -#define PyCursesSetupTermCalled \ - if (initialised_setupterm != TRUE) { \ - PyErr_SetString(PyCursesError, \ - "must call (at least) setupterm() first"); \ - return 0; } - -#define PyCursesInitialised \ - if (initialised != TRUE) { \ - PyErr_SetString(PyCursesError, \ - "must call initscr() first"); \ - return 0; } - -#define PyCursesInitialisedColor \ - if (initialisedcolors != TRUE) { \ - PyErr_SetString(PyCursesError, \ - "must call start_color() first"); \ - return 0; } +#define PyCursesSetupTermCalled \ + if (initialised_setupterm != TRUE) { \ + PyErr_SetString(PyCursesError, \ + "must call (at least) setupterm() first"); \ + return 0; } + +#define PyCursesInitialised \ + if (initialised != TRUE) { \ + PyErr_SetString(PyCursesError, \ + "must call initscr() first"); \ + return 0; } + +#define PyCursesInitialisedColor \ + if (initialisedcolors != TRUE) { \ + PyErr_SetString(PyCursesError, \ + "must call start_color() first"); \ + return 0; } #ifndef MIN #define MIN(x,y) ((x) < (y) ? (x) : (y)) @@ -170,7 +170,7 @@ /* Utility Functions */ /* - * Check the return code from a curses function and return None + * Check the return code from a curses function and return None * or raise an exception as appropriate. These are exported using the * capsule API. */ @@ -178,36 +178,36 @@ static PyObject * PyCursesCheckERR(int code, char *fname) { - if (code != ERR) { - Py_INCREF(Py_None); - return Py_None; - } else { - if (fname == NULL) { - PyErr_SetString(PyCursesError, catchall_ERR); + if (code != ERR) { + Py_INCREF(Py_None); + return Py_None; } else { - PyErr_Format(PyCursesError, "%s() returned ERR", fname); + if (fname == NULL) { + PyErr_SetString(PyCursesError, catchall_ERR); + } else { + PyErr_Format(PyCursesError, "%s() returned ERR", fname); + } + return NULL; } - return NULL; - } } -static int +static int PyCurses_ConvertToChtype(PyObject *obj, chtype *ch) { - if (PyInt_Check(obj)) { - *ch = (chtype) PyInt_AsLong(obj); - } else if(PyString_Check(obj) - && (PyString_Size(obj) == 1)) { - *ch = (chtype) *PyString_AsString(obj); - } else { - return 0; - } - return 1; + if (PyInt_Check(obj)) { + *ch = (chtype) PyInt_AsLong(obj); + } else if(PyString_Check(obj) + && (PyString_Size(obj) == 1)) { + *ch = (chtype) *PyString_AsString(obj); + } else { + return 0; + } + return 1; } /* Function versions of the 3 functions for testing whether curses has been initialised or not. */ - + static int func_PyCursesSetupTermCalled(void) { PyCursesSetupTermCalled; @@ -240,56 +240,56 @@ TYPE - parameter Type ERGSTR - format string for construction of the return value PARSESTR - format string for argument parsing - */ +*/ -#define Window_NoArgNoReturnFunction(X) \ -static PyObject *PyCursesWindow_ ## X \ -(PyCursesWindowObject *self, PyObject *args) \ -{ return PyCursesCheckERR(X(self->win), # X); } - -#define Window_NoArgTrueFalseFunction(X) \ -static PyObject * PyCursesWindow_ ## X \ -(PyCursesWindowObject *self) \ -{ \ - if (X (self->win) == FALSE) { Py_INCREF(Py_False); return Py_False; } \ - else { Py_INCREF(Py_True); return Py_True; } } - -#define Window_NoArgNoReturnVoidFunction(X) \ -static PyObject * PyCursesWindow_ ## X \ -(PyCursesWindowObject *self) \ -{ \ - X(self->win); Py_INCREF(Py_None); return Py_None; } - -#define Window_NoArg2TupleReturnFunction(X, TYPE, ERGSTR) \ -static PyObject * PyCursesWindow_ ## X \ -(PyCursesWindowObject *self) \ -{ \ - TYPE arg1, arg2; \ - X(self->win,arg1,arg2); return Py_BuildValue(ERGSTR, arg1, arg2); } - -#define Window_OneArgNoReturnVoidFunction(X, TYPE, PARSESTR) \ -static PyObject * PyCursesWindow_ ## X \ -(PyCursesWindowObject *self, PyObject *args) \ -{ \ - TYPE arg1; \ - if (!PyArg_ParseTuple(args, PARSESTR, &arg1)) return NULL; \ - X(self->win,arg1); Py_INCREF(Py_None); return Py_None; } - -#define Window_OneArgNoReturnFunction(X, TYPE, PARSESTR) \ -static PyObject * PyCursesWindow_ ## X \ -(PyCursesWindowObject *self, PyObject *args) \ -{ \ - TYPE arg1; \ - if (!PyArg_ParseTuple(args,PARSESTR, &arg1)) return NULL; \ - return PyCursesCheckERR(X(self->win, arg1), # X); } - -#define Window_TwoArgNoReturnFunction(X, TYPE, PARSESTR) \ -static PyObject * PyCursesWindow_ ## X \ -(PyCursesWindowObject *self, PyObject *args) \ -{ \ - TYPE arg1, arg2; \ - if (!PyArg_ParseTuple(args,PARSESTR, &arg1, &arg2)) return NULL; \ - return PyCursesCheckERR(X(self->win, arg1, arg2), # X); } +#define Window_NoArgNoReturnFunction(X) \ + static PyObject *PyCursesWindow_ ## X \ + (PyCursesWindowObject *self, PyObject *args) \ + { return PyCursesCheckERR(X(self->win), # X); } + +#define Window_NoArgTrueFalseFunction(X) \ + static PyObject * PyCursesWindow_ ## X \ + (PyCursesWindowObject *self) \ + { \ + if (X (self->win) == FALSE) { Py_INCREF(Py_False); return Py_False; } \ + else { Py_INCREF(Py_True); return Py_True; } } + +#define Window_NoArgNoReturnVoidFunction(X) \ + static PyObject * PyCursesWindow_ ## X \ + (PyCursesWindowObject *self) \ + { \ + X(self->win); Py_INCREF(Py_None); return Py_None; } + +#define Window_NoArg2TupleReturnFunction(X, TYPE, ERGSTR) \ + static PyObject * PyCursesWindow_ ## X \ + (PyCursesWindowObject *self) \ + { \ + TYPE arg1, arg2; \ + X(self->win,arg1,arg2); return Py_BuildValue(ERGSTR, arg1, arg2); } + +#define Window_OneArgNoReturnVoidFunction(X, TYPE, PARSESTR) \ + static PyObject * PyCursesWindow_ ## X \ + (PyCursesWindowObject *self, PyObject *args) \ + { \ + TYPE arg1; \ + if (!PyArg_ParseTuple(args, PARSESTR, &arg1)) return NULL; \ + X(self->win,arg1); Py_INCREF(Py_None); return Py_None; } + +#define Window_OneArgNoReturnFunction(X, TYPE, PARSESTR) \ + static PyObject * PyCursesWindow_ ## X \ + (PyCursesWindowObject *self, PyObject *args) \ + { \ + TYPE arg1; \ + if (!PyArg_ParseTuple(args,PARSESTR, &arg1)) return NULL; \ + return PyCursesCheckERR(X(self->win, arg1), # X); } + +#define Window_TwoArgNoReturnFunction(X, TYPE, PARSESTR) \ + static PyObject * PyCursesWindow_ ## X \ + (PyCursesWindowObject *self, PyObject *args) \ + { \ + TYPE arg1, arg2; \ + if (!PyArg_ParseTuple(args,PARSESTR, &arg1, &arg2)) return NULL; \ + return PyCursesCheckERR(X(self->win, arg1, arg2), # X); } /* ------------- WINDOW routines --------------- */ @@ -350,19 +350,19 @@ static PyObject * PyCursesWindow_New(WINDOW *win) { - PyCursesWindowObject *wo; + PyCursesWindowObject *wo; - wo = PyObject_NEW(PyCursesWindowObject, &PyCursesWindow_Type); - if (wo == NULL) return NULL; - wo->win = win; - return (PyObject *)wo; + wo = PyObject_NEW(PyCursesWindowObject, &PyCursesWindow_Type); + if (wo == NULL) return NULL; + wo->win = win; + return (PyObject *)wo; } static void PyCursesWindow_Dealloc(PyCursesWindowObject *wo) { - if (wo->win != stdscr) delwin(wo->win); - PyObject_DEL(wo); + if (wo->win != stdscr) delwin(wo->win); + PyObject_DEL(wo); } /* Addch, Addstr, Addnstr */ @@ -370,287 +370,287 @@ static PyObject * PyCursesWindow_AddCh(PyCursesWindowObject *self, PyObject *args) { - int rtn, x, y, use_xy = FALSE; - PyObject *temp; - chtype ch = 0; - attr_t attr = A_NORMAL; - long lattr; - - switch (PyTuple_Size(args)) { - case 1: - if (!PyArg_ParseTuple(args, "O;ch or int", &temp)) - return NULL; - break; - case 2: - if (!PyArg_ParseTuple(args, "Ol;ch or int,attr", &temp, &lattr)) - return NULL; - attr = lattr; - break; - case 3: - if (!PyArg_ParseTuple(args,"iiO;y,x,ch or int", &y, &x, &temp)) - return NULL; - use_xy = TRUE; - break; - case 4: - if (!PyArg_ParseTuple(args,"iiOl;y,x,ch or int, attr", - &y, &x, &temp, &lattr)) - return NULL; - attr = lattr; - use_xy = TRUE; - break; - default: - PyErr_SetString(PyExc_TypeError, "addch requires 1 to 4 arguments"); - return NULL; - } - - if (!PyCurses_ConvertToChtype(temp, &ch)) { - PyErr_SetString(PyExc_TypeError, "argument 1 or 3 must be a ch or an int"); - return NULL; - } - - if (use_xy == TRUE) - rtn = mvwaddch(self->win,y,x, ch | attr); - else { - rtn = waddch(self->win, ch | attr); - } - return PyCursesCheckERR(rtn, "addch"); + int rtn, x, y, use_xy = FALSE; + PyObject *temp; + chtype ch = 0; + attr_t attr = A_NORMAL; + long lattr; + + switch (PyTuple_Size(args)) { + case 1: + if (!PyArg_ParseTuple(args, "O;ch or int", &temp)) + return NULL; + break; + case 2: + if (!PyArg_ParseTuple(args, "Ol;ch or int,attr", &temp, &lattr)) + return NULL; + attr = lattr; + break; + case 3: + if (!PyArg_ParseTuple(args,"iiO;y,x,ch or int", &y, &x, &temp)) + return NULL; + use_xy = TRUE; + break; + case 4: + if (!PyArg_ParseTuple(args,"iiOl;y,x,ch or int, attr", + &y, &x, &temp, &lattr)) + return NULL; + attr = lattr; + use_xy = TRUE; + break; + default: + PyErr_SetString(PyExc_TypeError, "addch requires 1 to 4 arguments"); + return NULL; + } + + if (!PyCurses_ConvertToChtype(temp, &ch)) { + PyErr_SetString(PyExc_TypeError, "argument 1 or 3 must be a ch or an int"); + return NULL; + } + + if (use_xy == TRUE) + rtn = mvwaddch(self->win,y,x, ch | attr); + else { + rtn = waddch(self->win, ch | attr); + } + return PyCursesCheckERR(rtn, "addch"); } static PyObject * PyCursesWindow_AddStr(PyCursesWindowObject *self, PyObject *args) { - int rtn; - int x, y; - char *str; - attr_t attr = A_NORMAL , attr_old = A_NORMAL; - long lattr; - int use_xy = FALSE, use_attr = FALSE; - - switch (PyTuple_Size(args)) { - case 1: - if (!PyArg_ParseTuple(args,"s;str", &str)) - return NULL; - break; - case 2: - if (!PyArg_ParseTuple(args,"sl;str,attr", &str, &lattr)) - return NULL; - attr = lattr; - use_attr = TRUE; - break; - case 3: - if (!PyArg_ParseTuple(args,"iis;int,int,str", &y, &x, &str)) - return NULL; - use_xy = TRUE; - break; - case 4: - if (!PyArg_ParseTuple(args,"iisl;int,int,str,attr", &y, &x, &str, &lattr)) - return NULL; - attr = lattr; - use_xy = use_attr = TRUE; - break; - default: - PyErr_SetString(PyExc_TypeError, "addstr requires 1 to 4 arguments"); - return NULL; - } - - if (use_attr == TRUE) { - attr_old = getattrs(self->win); - (void)wattrset(self->win,attr); - } - if (use_xy == TRUE) - rtn = mvwaddstr(self->win,y,x,str); - else - rtn = waddstr(self->win,str); - if (use_attr == TRUE) - (void)wattrset(self->win,attr_old); - return PyCursesCheckERR(rtn, "addstr"); + int rtn; + int x, y; + char *str; + attr_t attr = A_NORMAL , attr_old = A_NORMAL; + long lattr; + int use_xy = FALSE, use_attr = FALSE; + + switch (PyTuple_Size(args)) { + case 1: + if (!PyArg_ParseTuple(args,"s;str", &str)) + return NULL; + break; + case 2: + if (!PyArg_ParseTuple(args,"sl;str,attr", &str, &lattr)) + return NULL; + attr = lattr; + use_attr = TRUE; + break; + case 3: + if (!PyArg_ParseTuple(args,"iis;int,int,str", &y, &x, &str)) + return NULL; + use_xy = TRUE; + break; + case 4: + if (!PyArg_ParseTuple(args,"iisl;int,int,str,attr", &y, &x, &str, &lattr)) + return NULL; + attr = lattr; + use_xy = use_attr = TRUE; + break; + default: + PyErr_SetString(PyExc_TypeError, "addstr requires 1 to 4 arguments"); + return NULL; + } + + if (use_attr == TRUE) { + attr_old = getattrs(self->win); + (void)wattrset(self->win,attr); + } + if (use_xy == TRUE) + rtn = mvwaddstr(self->win,y,x,str); + else + rtn = waddstr(self->win,str); + if (use_attr == TRUE) + (void)wattrset(self->win,attr_old); + return PyCursesCheckERR(rtn, "addstr"); } static PyObject * PyCursesWindow_AddNStr(PyCursesWindowObject *self, PyObject *args) { - int rtn, x, y, n; - char *str; - attr_t attr = A_NORMAL , attr_old = A_NORMAL; - long lattr; - int use_xy = FALSE, use_attr = FALSE; - - switch (PyTuple_Size(args)) { - case 2: - if (!PyArg_ParseTuple(args,"si;str,n", &str, &n)) - return NULL; - break; - case 3: - if (!PyArg_ParseTuple(args,"sil;str,n,attr", &str, &n, &lattr)) - return NULL; - attr = lattr; - use_attr = TRUE; - break; - case 4: - if (!PyArg_ParseTuple(args,"iisi;y,x,str,n", &y, &x, &str, &n)) - return NULL; - use_xy = TRUE; - break; - case 5: - if (!PyArg_ParseTuple(args,"iisil;y,x,str,n,attr", &y, &x, &str, &n, &lattr)) - return NULL; - attr = lattr; - use_xy = use_attr = TRUE; - break; - default: - PyErr_SetString(PyExc_TypeError, "addnstr requires 2 to 5 arguments"); - return NULL; - } - - if (use_attr == TRUE) { - attr_old = getattrs(self->win); - (void)wattrset(self->win,attr); - } - if (use_xy == TRUE) - rtn = mvwaddnstr(self->win,y,x,str,n); - else - rtn = waddnstr(self->win,str,n); - if (use_attr == TRUE) - (void)wattrset(self->win,attr_old); - return PyCursesCheckERR(rtn, "addnstr"); + int rtn, x, y, n; + char *str; + attr_t attr = A_NORMAL , attr_old = A_NORMAL; + long lattr; + int use_xy = FALSE, use_attr = FALSE; + + switch (PyTuple_Size(args)) { + case 2: + if (!PyArg_ParseTuple(args,"si;str,n", &str, &n)) + return NULL; + break; + case 3: + if (!PyArg_ParseTuple(args,"sil;str,n,attr", &str, &n, &lattr)) + return NULL; + attr = lattr; + use_attr = TRUE; + break; + case 4: + if (!PyArg_ParseTuple(args,"iisi;y,x,str,n", &y, &x, &str, &n)) + return NULL; + use_xy = TRUE; + break; + case 5: + if (!PyArg_ParseTuple(args,"iisil;y,x,str,n,attr", &y, &x, &str, &n, &lattr)) + return NULL; + attr = lattr; + use_xy = use_attr = TRUE; + break; + default: + PyErr_SetString(PyExc_TypeError, "addnstr requires 2 to 5 arguments"); + return NULL; + } + + if (use_attr == TRUE) { + attr_old = getattrs(self->win); + (void)wattrset(self->win,attr); + } + if (use_xy == TRUE) + rtn = mvwaddnstr(self->win,y,x,str,n); + else + rtn = waddnstr(self->win,str,n); + if (use_attr == TRUE) + (void)wattrset(self->win,attr_old); + return PyCursesCheckERR(rtn, "addnstr"); } static PyObject * PyCursesWindow_Bkgd(PyCursesWindowObject *self, PyObject *args) { - PyObject *temp; - chtype bkgd; - attr_t attr = A_NORMAL; - long lattr; + PyObject *temp; + chtype bkgd; + attr_t attr = A_NORMAL; + long lattr; - switch (PyTuple_Size(args)) { + switch (PyTuple_Size(args)) { case 1: - if (!PyArg_ParseTuple(args, "O;ch or int", &temp)) - return NULL; - break; + if (!PyArg_ParseTuple(args, "O;ch or int", &temp)) + return NULL; + break; case 2: - if (!PyArg_ParseTuple(args,"Ol;ch or int,attr", &temp, &lattr)) - return NULL; - attr = lattr; - break; + if (!PyArg_ParseTuple(args,"Ol;ch or int,attr", &temp, &lattr)) + return NULL; + attr = lattr; + break; default: - PyErr_SetString(PyExc_TypeError, "bkgd requires 1 or 2 arguments"); - return NULL; - } + PyErr_SetString(PyExc_TypeError, "bkgd requires 1 or 2 arguments"); + return NULL; + } - if (!PyCurses_ConvertToChtype(temp, &bkgd)) { - PyErr_SetString(PyExc_TypeError, "argument 1 or 3 must be a ch or an int"); - return NULL; - } + if (!PyCurses_ConvertToChtype(temp, &bkgd)) { + PyErr_SetString(PyExc_TypeError, "argument 1 or 3 must be a ch or an int"); + return NULL; + } - return PyCursesCheckERR(wbkgd(self->win, bkgd | attr), "bkgd"); + return PyCursesCheckERR(wbkgd(self->win, bkgd | attr), "bkgd"); } static PyObject * PyCursesWindow_AttrOff(PyCursesWindowObject *self, PyObject *args) { - long lattr; - if (!PyArg_ParseTuple(args,"l;attr", &lattr)) - return NULL; - return PyCursesCheckERR(wattroff(self->win, (attr_t)lattr), "attroff"); + long lattr; + if (!PyArg_ParseTuple(args,"l;attr", &lattr)) + return NULL; + return PyCursesCheckERR(wattroff(self->win, (attr_t)lattr), "attroff"); } static PyObject * PyCursesWindow_AttrOn(PyCursesWindowObject *self, PyObject *args) { - long lattr; - if (!PyArg_ParseTuple(args,"l;attr", &lattr)) - return NULL; - return PyCursesCheckERR(wattron(self->win, (attr_t)lattr), "attron"); + long lattr; + if (!PyArg_ParseTuple(args,"l;attr", &lattr)) + return NULL; + return PyCursesCheckERR(wattron(self->win, (attr_t)lattr), "attron"); } static PyObject * PyCursesWindow_AttrSet(PyCursesWindowObject *self, PyObject *args) { - long lattr; - if (!PyArg_ParseTuple(args,"l;attr", &lattr)) - return NULL; - return PyCursesCheckERR(wattrset(self->win, (attr_t)lattr), "attrset"); + long lattr; + if (!PyArg_ParseTuple(args,"l;attr", &lattr)) + return NULL; + return PyCursesCheckERR(wattrset(self->win, (attr_t)lattr), "attrset"); } static PyObject * PyCursesWindow_BkgdSet(PyCursesWindowObject *self, PyObject *args) { - PyObject *temp; - chtype bkgd; - attr_t attr = A_NORMAL; - long lattr; + PyObject *temp; + chtype bkgd; + attr_t attr = A_NORMAL; + long lattr; - switch (PyTuple_Size(args)) { + switch (PyTuple_Size(args)) { case 1: - if (!PyArg_ParseTuple(args, "O;ch or int", &temp)) - return NULL; - break; + if (!PyArg_ParseTuple(args, "O;ch or int", &temp)) + return NULL; + break; case 2: - if (!PyArg_ParseTuple(args,"Ol;ch or int,attr", &temp, &lattr)) - return NULL; - attr = lattr; - break; + if (!PyArg_ParseTuple(args,"Ol;ch or int,attr", &temp, &lattr)) + return NULL; + attr = lattr; + break; default: - PyErr_SetString(PyExc_TypeError, "bkgdset requires 1 or 2 arguments"); - return NULL; - } + PyErr_SetString(PyExc_TypeError, "bkgdset requires 1 or 2 arguments"); + return NULL; + } - if (!PyCurses_ConvertToChtype(temp, &bkgd)) { - PyErr_SetString(PyExc_TypeError, "argument 1 must be a ch or an int"); - return NULL; - } + if (!PyCurses_ConvertToChtype(temp, &bkgd)) { + PyErr_SetString(PyExc_TypeError, "argument 1 must be a ch or an int"); + return NULL; + } - wbkgdset(self->win, bkgd | attr); - return PyCursesCheckERR(0, "bkgdset"); + wbkgdset(self->win, bkgd | attr); + return PyCursesCheckERR(0, "bkgdset"); } static PyObject * PyCursesWindow_Border(PyCursesWindowObject *self, PyObject *args) { - PyObject *temp[8]; - chtype ch[8]; - int i; - - /* Clear the array of parameters */ - for(i=0; i<8; i++) { - temp[i] = NULL; - ch[i] = 0; - } - - if (!PyArg_ParseTuple(args,"|OOOOOOOO;ls,rs,ts,bs,tl,tr,bl,br", - &temp[0], &temp[1], &temp[2], &temp[3], - &temp[4], &temp[5], &temp[6], &temp[7])) - return NULL; - - for(i=0; i<8; i++) { - if (temp[i] != NULL && !PyCurses_ConvertToChtype(temp[i], &ch[i])) { - PyErr_Format(PyExc_TypeError, - "argument %i must be a ch or an int", i+1); - return NULL; - } - } - - wborder(self->win, - ch[0], ch[1], ch[2], ch[3], - ch[4], ch[5], ch[6], ch[7]); - Py_INCREF(Py_None); - return Py_None; + PyObject *temp[8]; + chtype ch[8]; + int i; + + /* Clear the array of parameters */ + for(i=0; i<8; i++) { + temp[i] = NULL; + ch[i] = 0; + } + + if (!PyArg_ParseTuple(args,"|OOOOOOOO;ls,rs,ts,bs,tl,tr,bl,br", + &temp[0], &temp[1], &temp[2], &temp[3], + &temp[4], &temp[5], &temp[6], &temp[7])) + return NULL; + + for(i=0; i<8; i++) { + if (temp[i] != NULL && !PyCurses_ConvertToChtype(temp[i], &ch[i])) { + PyErr_Format(PyExc_TypeError, + "argument %i must be a ch or an int", i+1); + return NULL; + } + } + + wborder(self->win, + ch[0], ch[1], ch[2], ch[3], + ch[4], ch[5], ch[6], ch[7]); + Py_INCREF(Py_None); + return Py_None; } static PyObject * PyCursesWindow_Box(PyCursesWindowObject *self, PyObject *args) { - chtype ch1=0,ch2=0; - switch(PyTuple_Size(args)){ - case 0: break; - default: - if (!PyArg_ParseTuple(args,"ll;vertint,horint", &ch1, &ch2)) - return NULL; - } - box(self->win,ch1,ch2); - Py_INCREF(Py_None); - return Py_None; + chtype ch1=0,ch2=0; + switch(PyTuple_Size(args)){ + case 0: break; + default: + if (!PyArg_ParseTuple(args,"ll;vertint,horint", &ch1, &ch2)) + return NULL; + } + box(self->win,ch1,ch2); + Py_INCREF(Py_None); + return Py_None; } #if defined(HAVE_NCURSES_H) || defined(MVWDELCH_IS_EXPRESSION) @@ -658,10 +658,10 @@ #else int py_mvwdelch(WINDOW *w, int y, int x) { - mvwdelch(w,y,x); - /* On HP/UX, mvwdelch already returns. On other systems, - we may well run into this return statement. */ - return 0; + mvwdelch(w,y,x); + /* On HP/UX, mvwdelch already returns. On other systems, + we may well run into this return statement. */ + return 0; } #endif @@ -670,603 +670,603 @@ static PyObject * PyCursesWindow_ChgAt(PyCursesWindowObject *self, PyObject *args) { - int rtn; - int x, y; - int num = -1; - short color; - attr_t attr = A_NORMAL; - long lattr; - int use_xy = FALSE; + int rtn; + int x, y; + int num = -1; + short color; + attr_t attr = A_NORMAL; + long lattr; + int use_xy = FALSE; - switch (PyTuple_Size(args)) { - case 1: - if (!PyArg_ParseTuple(args,"l;attr", &lattr)) - return NULL; - attr = lattr; - break; - case 2: - if (!PyArg_ParseTuple(args,"il;n,attr", &num, &lattr)) - return NULL; - attr = lattr; - break; - case 3: - if (!PyArg_ParseTuple(args,"iil;int,int,attr", &y, &x, &lattr)) - return NULL; - attr = lattr; - use_xy = TRUE; - break; - case 4: - if (!PyArg_ParseTuple(args,"iiil;int,int,n,attr", &y, &x, &num, &lattr)) - return NULL; - attr = lattr; - use_xy = TRUE; - break; - default: - PyErr_SetString(PyExc_TypeError, "chgat requires 1 to 4 arguments"); - return NULL; - } - - color = (short)((attr >> 8) & 0xff); - attr = attr - (color << 8); - - if (use_xy == TRUE) { - rtn = mvwchgat(self->win,y,x,num,attr,color,NULL); - touchline(self->win,y,1); - } else { - getyx(self->win,y,x); - rtn = wchgat(self->win,num,attr,color,NULL); - touchline(self->win,y,1); - } - return PyCursesCheckERR(rtn, "chgat"); + switch (PyTuple_Size(args)) { + case 1: + if (!PyArg_ParseTuple(args,"l;attr", &lattr)) + return NULL; + attr = lattr; + break; + case 2: + if (!PyArg_ParseTuple(args,"il;n,attr", &num, &lattr)) + return NULL; + attr = lattr; + break; + case 3: + if (!PyArg_ParseTuple(args,"iil;int,int,attr", &y, &x, &lattr)) + return NULL; + attr = lattr; + use_xy = TRUE; + break; + case 4: + if (!PyArg_ParseTuple(args,"iiil;int,int,n,attr", &y, &x, &num, &lattr)) + return NULL; + attr = lattr; + use_xy = TRUE; + break; + default: + PyErr_SetString(PyExc_TypeError, "chgat requires 1 to 4 arguments"); + return NULL; + } + + color = (short)((attr >> 8) & 0xff); + attr = attr - (color << 8); + + if (use_xy == TRUE) { + rtn = mvwchgat(self->win,y,x,num,attr,color,NULL); + touchline(self->win,y,1); + } else { + getyx(self->win,y,x); + rtn = wchgat(self->win,num,attr,color,NULL); + touchline(self->win,y,1); + } + return PyCursesCheckERR(rtn, "chgat"); } static PyObject * PyCursesWindow_DelCh(PyCursesWindowObject *self, PyObject *args) { - int rtn; - int x, y; + int rtn; + int x, y; - switch (PyTuple_Size(args)) { - case 0: - rtn = wdelch(self->win); - break; - case 2: - if (!PyArg_ParseTuple(args,"ii;y,x", &y, &x)) - return NULL; - rtn = py_mvwdelch(self->win,y,x); - break; - default: - PyErr_SetString(PyExc_TypeError, "delch requires 0 or 2 arguments"); - return NULL; - } - return PyCursesCheckERR(rtn, "[mv]wdelch"); + switch (PyTuple_Size(args)) { + case 0: + rtn = wdelch(self->win); + break; + case 2: + if (!PyArg_ParseTuple(args,"ii;y,x", &y, &x)) + return NULL; + rtn = py_mvwdelch(self->win,y,x); + break; + default: + PyErr_SetString(PyExc_TypeError, "delch requires 0 or 2 arguments"); + return NULL; + } + return PyCursesCheckERR(rtn, "[mv]wdelch"); } static PyObject * PyCursesWindow_DerWin(PyCursesWindowObject *self, PyObject *args) { - WINDOW *win; - int nlines, ncols, begin_y, begin_x; + WINDOW *win; + int nlines, ncols, begin_y, begin_x; - nlines = 0; - ncols = 0; - switch (PyTuple_Size(args)) { - case 2: - if (!PyArg_ParseTuple(args,"ii;begin_y,begin_x",&begin_y,&begin_x)) - return NULL; - break; - case 4: - if (!PyArg_ParseTuple(args, "iiii;nlines,ncols,begin_y,begin_x", - &nlines,&ncols,&begin_y,&begin_x)) - return NULL; - break; - default: - PyErr_SetString(PyExc_TypeError, "derwin requires 2 or 4 arguments"); - return NULL; - } - - win = derwin(self->win,nlines,ncols,begin_y,begin_x); - - if (win == NULL) { - PyErr_SetString(PyCursesError, catchall_NULL); - return NULL; - } + nlines = 0; + ncols = 0; + switch (PyTuple_Size(args)) { + case 2: + if (!PyArg_ParseTuple(args,"ii;begin_y,begin_x",&begin_y,&begin_x)) + return NULL; + break; + case 4: + if (!PyArg_ParseTuple(args, "iiii;nlines,ncols,begin_y,begin_x", + &nlines,&ncols,&begin_y,&begin_x)) + return NULL; + break; + default: + PyErr_SetString(PyExc_TypeError, "derwin requires 2 or 4 arguments"); + return NULL; + } + + win = derwin(self->win,nlines,ncols,begin_y,begin_x); + + if (win == NULL) { + PyErr_SetString(PyCursesError, catchall_NULL); + return NULL; + } - return (PyObject *)PyCursesWindow_New(win); + return (PyObject *)PyCursesWindow_New(win); } static PyObject * PyCursesWindow_EchoChar(PyCursesWindowObject *self, PyObject *args) { - PyObject *temp; - chtype ch; - attr_t attr = A_NORMAL; - long lattr; - - switch (PyTuple_Size(args)) { - case 1: - if (!PyArg_ParseTuple(args,"O;ch or int", &temp)) - return NULL; - break; - case 2: - if (!PyArg_ParseTuple(args,"Ol;ch or int,attr", &temp, &lattr)) - return NULL; - attr = lattr; - break; - default: - PyErr_SetString(PyExc_TypeError, "echochar requires 1 or 2 arguments"); - - - return NULL; - } - - if (!PyCurses_ConvertToChtype(temp, &ch)) { - PyErr_SetString(PyExc_TypeError, "argument 1 must be a ch or an int"); - return NULL; - } - + PyObject *temp; + chtype ch; + attr_t attr = A_NORMAL; + long lattr; + + switch (PyTuple_Size(args)) { + case 1: + if (!PyArg_ParseTuple(args,"O;ch or int", &temp)) + return NULL; + break; + case 2: + if (!PyArg_ParseTuple(args,"Ol;ch or int,attr", &temp, &lattr)) + return NULL; + attr = lattr; + break; + default: + PyErr_SetString(PyExc_TypeError, "echochar requires 1 or 2 arguments"); + + + return NULL; + } + + if (!PyCurses_ConvertToChtype(temp, &ch)) { + PyErr_SetString(PyExc_TypeError, "argument 1 must be a ch or an int"); + return NULL; + } + #ifdef WINDOW_HAS_FLAGS - if (self->win->_flags & _ISPAD) - return PyCursesCheckERR(pechochar(self->win, ch | attr), - "echochar"); - else + if (self->win->_flags & _ISPAD) + return PyCursesCheckERR(pechochar(self->win, ch | attr), + "echochar"); + else #endif - return PyCursesCheckERR(wechochar(self->win, ch | attr), - "echochar"); + return PyCursesCheckERR(wechochar(self->win, ch | attr), + "echochar"); } #ifdef NCURSES_MOUSE_VERSION static PyObject * PyCursesWindow_Enclose(PyCursesWindowObject *self, PyObject *args) { - int x, y; - if (!PyArg_ParseTuple(args,"ii;y,x", &y, &x)) - return NULL; + int x, y; + if (!PyArg_ParseTuple(args,"ii;y,x", &y, &x)) + return NULL; - return PyInt_FromLong( wenclose(self->win,y,x) ); + return PyInt_FromLong( wenclose(self->win,y,x) ); } #endif static PyObject * PyCursesWindow_GetBkgd(PyCursesWindowObject *self) { - return PyInt_FromLong((long) getbkgd(self->win)); + return PyInt_FromLong((long) getbkgd(self->win)); } static PyObject * PyCursesWindow_GetCh(PyCursesWindowObject *self, PyObject *args) { - int x, y; - int rtn; + int x, y; + int rtn; - switch (PyTuple_Size(args)) { - case 0: - Py_BEGIN_ALLOW_THREADS - rtn = wgetch(self->win); - Py_END_ALLOW_THREADS - break; - case 2: - if (!PyArg_ParseTuple(args,"ii;y,x",&y,&x)) - return NULL; - Py_BEGIN_ALLOW_THREADS - rtn = mvwgetch(self->win,y,x); - Py_END_ALLOW_THREADS - break; - default: - PyErr_SetString(PyExc_TypeError, "getch requires 0 or 2 arguments"); - return NULL; - } - return PyInt_FromLong((long)rtn); + switch (PyTuple_Size(args)) { + case 0: + Py_BEGIN_ALLOW_THREADS + rtn = wgetch(self->win); + Py_END_ALLOW_THREADS + break; + case 2: + if (!PyArg_ParseTuple(args,"ii;y,x",&y,&x)) + return NULL; + Py_BEGIN_ALLOW_THREADS + rtn = mvwgetch(self->win,y,x); + Py_END_ALLOW_THREADS + break; + default: + PyErr_SetString(PyExc_TypeError, "getch requires 0 or 2 arguments"); + return NULL; + } + return PyInt_FromLong((long)rtn); } static PyObject * PyCursesWindow_GetKey(PyCursesWindowObject *self, PyObject *args) { - int x, y; - int rtn; + int x, y; + int rtn; - switch (PyTuple_Size(args)) { - case 0: - Py_BEGIN_ALLOW_THREADS - rtn = wgetch(self->win); - Py_END_ALLOW_THREADS - break; - case 2: - if (!PyArg_ParseTuple(args,"ii;y,x",&y,&x)) - return NULL; - Py_BEGIN_ALLOW_THREADS - rtn = mvwgetch(self->win,y,x); - Py_END_ALLOW_THREADS - break; - default: - PyErr_SetString(PyExc_TypeError, "getkey requires 0 or 2 arguments"); - return NULL; - } - if (rtn == ERR) { - /* getch() returns ERR in nodelay mode */ - PyErr_SetString(PyCursesError, "no input"); - return NULL; - } else if (rtn<=255) { - return Py_BuildValue("c", rtn); - } else { - const char *knp; + switch (PyTuple_Size(args)) { + case 0: + Py_BEGIN_ALLOW_THREADS + rtn = wgetch(self->win); + Py_END_ALLOW_THREADS + break; + case 2: + if (!PyArg_ParseTuple(args,"ii;y,x",&y,&x)) + return NULL; + Py_BEGIN_ALLOW_THREADS + rtn = mvwgetch(self->win,y,x); + Py_END_ALLOW_THREADS + break; + default: + PyErr_SetString(PyExc_TypeError, "getkey requires 0 or 2 arguments"); + return NULL; + } + if (rtn == ERR) { + /* getch() returns ERR in nodelay mode */ + PyErr_SetString(PyCursesError, "no input"); + return NULL; + } else if (rtn<=255) { + return Py_BuildValue("c", rtn); + } else { + const char *knp; #if defined(__NetBSD__) - knp = unctrl(rtn); + knp = unctrl(rtn); #else - knp = keyname(rtn); + knp = keyname(rtn); #endif - return PyString_FromString((knp == NULL) ? "" : knp); - } + return PyString_FromString((knp == NULL) ? "" : knp); + } } static PyObject * PyCursesWindow_GetStr(PyCursesWindowObject *self, PyObject *args) { - int x, y, n; - char rtn[1024]; /* This should be big enough.. I hope */ - int rtn2; - - switch (PyTuple_Size(args)) { - case 0: - Py_BEGIN_ALLOW_THREADS - rtn2 = wgetnstr(self->win,rtn, 1023); - Py_END_ALLOW_THREADS - break; - case 1: - if (!PyArg_ParseTuple(args,"i;n", &n)) - return NULL; - Py_BEGIN_ALLOW_THREADS - rtn2 = wgetnstr(self->win,rtn,MIN(n, 1023)); - Py_END_ALLOW_THREADS - break; - case 2: - if (!PyArg_ParseTuple(args,"ii;y,x",&y,&x)) - return NULL; - Py_BEGIN_ALLOW_THREADS + int x, y, n; + char rtn[1024]; /* This should be big enough.. I hope */ + int rtn2; + + switch (PyTuple_Size(args)) { + case 0: + Py_BEGIN_ALLOW_THREADS + rtn2 = wgetnstr(self->win,rtn, 1023); + Py_END_ALLOW_THREADS + break; + case 1: + if (!PyArg_ParseTuple(args,"i;n", &n)) + return NULL; + Py_BEGIN_ALLOW_THREADS + rtn2 = wgetnstr(self->win,rtn,MIN(n, 1023)); + Py_END_ALLOW_THREADS + break; + case 2: + if (!PyArg_ParseTuple(args,"ii;y,x",&y,&x)) + return NULL; + Py_BEGIN_ALLOW_THREADS #ifdef STRICT_SYSV_CURSES - rtn2 = wmove(self->win,y,x)==ERR ? ERR : wgetnstr(self->win, rtn, 1023); + rtn2 = wmove(self->win,y,x)==ERR ? ERR : wgetnstr(self->win, rtn, 1023); #else - rtn2 = mvwgetnstr(self->win,y,x,rtn, 1023); + rtn2 = mvwgetnstr(self->win,y,x,rtn, 1023); #endif - Py_END_ALLOW_THREADS - break; - case 3: - if (!PyArg_ParseTuple(args,"iii;y,x,n", &y, &x, &n)) - return NULL; + Py_END_ALLOW_THREADS + break; + case 3: + if (!PyArg_ParseTuple(args,"iii;y,x,n", &y, &x, &n)) + return NULL; #ifdef STRICT_SYSV_CURSES - Py_BEGIN_ALLOW_THREADS - rtn2 = wmove(self->win,y,x)==ERR ? ERR : - wgetnstr(self->win, rtn, MIN(n, 1023)); - Py_END_ALLOW_THREADS + Py_BEGIN_ALLOW_THREADS + rtn2 = wmove(self->win,y,x)==ERR ? ERR : + wgetnstr(self->win, rtn, MIN(n, 1023)); + Py_END_ALLOW_THREADS #else - Py_BEGIN_ALLOW_THREADS - rtn2 = mvwgetnstr(self->win, y, x, rtn, MIN(n, 1023)); - Py_END_ALLOW_THREADS -#endif - break; - default: - PyErr_SetString(PyExc_TypeError, "getstr requires 0 to 3 arguments"); - return NULL; - } - if (rtn2 == ERR) - rtn[0] = 0; - return PyString_FromString(rtn); + Py_BEGIN_ALLOW_THREADS + rtn2 = mvwgetnstr(self->win, y, x, rtn, MIN(n, 1023)); + Py_END_ALLOW_THREADS +#endif + break; + default: + PyErr_SetString(PyExc_TypeError, "getstr requires 0 to 3 arguments"); + return NULL; + } + if (rtn2 == ERR) + rtn[0] = 0; + return PyString_FromString(rtn); } static PyObject * PyCursesWindow_Hline(PyCursesWindowObject *self, PyObject *args) { - PyObject *temp; - chtype ch; - int n, x, y, code = OK; - attr_t attr = A_NORMAL; - long lattr; - - switch (PyTuple_Size(args)) { - case 2: - if (!PyArg_ParseTuple(args, "Oi;ch or int,n", &temp, &n)) - return NULL; - break; - case 3: - if (!PyArg_ParseTuple(args, "Oil;ch or int,n,attr", &temp, &n, &lattr)) - return NULL; - attr = lattr; - break; - case 4: - if (!PyArg_ParseTuple(args, "iiOi;y,x,ch or int,n", &y, &x, &temp, &n)) - return NULL; - code = wmove(self->win, y, x); - break; - case 5: - if (!PyArg_ParseTuple(args, "iiOil; y,x,ch or int,n,attr", - &y, &x, &temp, &n, &lattr)) - return NULL; - attr = lattr; - code = wmove(self->win, y, x); - break; - default: - PyErr_SetString(PyExc_TypeError, "hline requires 2 to 5 arguments"); - return NULL; - } + PyObject *temp; + chtype ch; + int n, x, y, code = OK; + attr_t attr = A_NORMAL; + long lattr; - if (code != ERR) { - if (!PyCurses_ConvertToChtype(temp, &ch)) { - PyErr_SetString(PyExc_TypeError, - "argument 1 or 3 must be a ch or an int"); - return NULL; - } - return PyCursesCheckERR(whline(self->win, ch | attr, n), "hline"); - } else - return PyCursesCheckERR(code, "wmove"); + switch (PyTuple_Size(args)) { + case 2: + if (!PyArg_ParseTuple(args, "Oi;ch or int,n", &temp, &n)) + return NULL; + break; + case 3: + if (!PyArg_ParseTuple(args, "Oil;ch or int,n,attr", &temp, &n, &lattr)) + return NULL; + attr = lattr; + break; + case 4: + if (!PyArg_ParseTuple(args, "iiOi;y,x,ch or int,n", &y, &x, &temp, &n)) + return NULL; + code = wmove(self->win, y, x); + break; + case 5: + if (!PyArg_ParseTuple(args, "iiOil; y,x,ch or int,n,attr", + &y, &x, &temp, &n, &lattr)) + return NULL; + attr = lattr; + code = wmove(self->win, y, x); + break; + default: + PyErr_SetString(PyExc_TypeError, "hline requires 2 to 5 arguments"); + return NULL; + } + + if (code != ERR) { + if (!PyCurses_ConvertToChtype(temp, &ch)) { + PyErr_SetString(PyExc_TypeError, + "argument 1 or 3 must be a ch or an int"); + return NULL; + } + return PyCursesCheckERR(whline(self->win, ch | attr, n), "hline"); + } else + return PyCursesCheckERR(code, "wmove"); } static PyObject * PyCursesWindow_InsCh(PyCursesWindowObject *self, PyObject *args) { - int rtn, x, y, use_xy = FALSE; - PyObject *temp; - chtype ch = 0; - attr_t attr = A_NORMAL; - long lattr; - - switch (PyTuple_Size(args)) { - case 1: - if (!PyArg_ParseTuple(args, "O;ch or int", &temp)) - return NULL; - break; - case 2: - if (!PyArg_ParseTuple(args, "Ol;ch or int,attr", &temp, &lattr)) - return NULL; - attr = lattr; - break; - case 3: - if (!PyArg_ParseTuple(args,"iiO;y,x,ch or int", &y, &x, &temp)) - return NULL; - use_xy = TRUE; - break; - case 4: - if (!PyArg_ParseTuple(args,"iiOl;y,x,ch or int, attr", &y, &x, &temp, &lattr)) - return NULL; - attr = lattr; - use_xy = TRUE; - break; - default: - PyErr_SetString(PyExc_TypeError, "insch requires 1 or 4 arguments"); - return NULL; - } - - if (!PyCurses_ConvertToChtype(temp, &ch)) { - PyErr_SetString(PyExc_TypeError, - "argument 1 or 3 must be a ch or an int"); - return NULL; - } - - if (use_xy == TRUE) - rtn = mvwinsch(self->win,y,x, ch | attr); - else { - rtn = winsch(self->win, ch | attr); - } - return PyCursesCheckERR(rtn, "insch"); + int rtn, x, y, use_xy = FALSE; + PyObject *temp; + chtype ch = 0; + attr_t attr = A_NORMAL; + long lattr; + + switch (PyTuple_Size(args)) { + case 1: + if (!PyArg_ParseTuple(args, "O;ch or int", &temp)) + return NULL; + break; + case 2: + if (!PyArg_ParseTuple(args, "Ol;ch or int,attr", &temp, &lattr)) + return NULL; + attr = lattr; + break; + case 3: + if (!PyArg_ParseTuple(args,"iiO;y,x,ch or int", &y, &x, &temp)) + return NULL; + use_xy = TRUE; + break; + case 4: + if (!PyArg_ParseTuple(args,"iiOl;y,x,ch or int, attr", &y, &x, &temp, &lattr)) + return NULL; + attr = lattr; + use_xy = TRUE; + break; + default: + PyErr_SetString(PyExc_TypeError, "insch requires 1 or 4 arguments"); + return NULL; + } + + if (!PyCurses_ConvertToChtype(temp, &ch)) { + PyErr_SetString(PyExc_TypeError, + "argument 1 or 3 must be a ch or an int"); + return NULL; + } + + if (use_xy == TRUE) + rtn = mvwinsch(self->win,y,x, ch | attr); + else { + rtn = winsch(self->win, ch | attr); + } + return PyCursesCheckERR(rtn, "insch"); } static PyObject * PyCursesWindow_InCh(PyCursesWindowObject *self, PyObject *args) { - int x, y, rtn; + int x, y, rtn; - switch (PyTuple_Size(args)) { - case 0: - rtn = winch(self->win); - break; - case 2: - if (!PyArg_ParseTuple(args,"ii;y,x",&y,&x)) - return NULL; - rtn = mvwinch(self->win,y,x); - break; - default: - PyErr_SetString(PyExc_TypeError, "inch requires 0 or 2 arguments"); - return NULL; - } - return PyInt_FromLong((long) rtn); + switch (PyTuple_Size(args)) { + case 0: + rtn = winch(self->win); + break; + case 2: + if (!PyArg_ParseTuple(args,"ii;y,x",&y,&x)) + return NULL; + rtn = mvwinch(self->win,y,x); + break; + default: + PyErr_SetString(PyExc_TypeError, "inch requires 0 or 2 arguments"); + return NULL; + } + return PyInt_FromLong((long) rtn); } static PyObject * PyCursesWindow_InStr(PyCursesWindowObject *self, PyObject *args) { - int x, y, n; - char rtn[1024]; /* This should be big enough.. I hope */ - int rtn2; - - switch (PyTuple_Size(args)) { - case 0: - rtn2 = winnstr(self->win,rtn, 1023); - break; - case 1: - if (!PyArg_ParseTuple(args,"i;n", &n)) - return NULL; - rtn2 = winnstr(self->win,rtn,MIN(n,1023)); - break; - case 2: - if (!PyArg_ParseTuple(args,"ii;y,x",&y,&x)) - return NULL; - rtn2 = mvwinnstr(self->win,y,x,rtn,1023); - break; - case 3: - if (!PyArg_ParseTuple(args, "iii;y,x,n", &y, &x, &n)) - return NULL; - rtn2 = mvwinnstr(self->win, y, x, rtn, MIN(n,1023)); - break; - default: - PyErr_SetString(PyExc_TypeError, "instr requires 0 or 3 arguments"); - return NULL; - } - if (rtn2 == ERR) - rtn[0] = 0; - return PyString_FromString(rtn); + int x, y, n; + char rtn[1024]; /* This should be big enough.. I hope */ + int rtn2; + + switch (PyTuple_Size(args)) { + case 0: + rtn2 = winnstr(self->win,rtn, 1023); + break; + case 1: + if (!PyArg_ParseTuple(args,"i;n", &n)) + return NULL; + rtn2 = winnstr(self->win,rtn,MIN(n,1023)); + break; + case 2: + if (!PyArg_ParseTuple(args,"ii;y,x",&y,&x)) + return NULL; + rtn2 = mvwinnstr(self->win,y,x,rtn,1023); + break; + case 3: + if (!PyArg_ParseTuple(args, "iii;y,x,n", &y, &x, &n)) + return NULL; + rtn2 = mvwinnstr(self->win, y, x, rtn, MIN(n,1023)); + break; + default: + PyErr_SetString(PyExc_TypeError, "instr requires 0 or 3 arguments"); + return NULL; + } + if (rtn2 == ERR) + rtn[0] = 0; + return PyString_FromString(rtn); } static PyObject * PyCursesWindow_InsStr(PyCursesWindowObject *self, PyObject *args) { - int rtn; - int x, y; - char *str; - attr_t attr = A_NORMAL , attr_old = A_NORMAL; - long lattr; - int use_xy = FALSE, use_attr = FALSE; - - switch (PyTuple_Size(args)) { - case 1: - if (!PyArg_ParseTuple(args,"s;str", &str)) - return NULL; - break; - case 2: - if (!PyArg_ParseTuple(args,"sl;str,attr", &str, &lattr)) - return NULL; - attr = lattr; - use_attr = TRUE; - break; - case 3: - if (!PyArg_ParseTuple(args,"iis;y,x,str", &y, &x, &str)) - return NULL; - use_xy = TRUE; - break; - case 4: - if (!PyArg_ParseTuple(args,"iisl;y,x,str,attr", &y, &x, &str, &lattr)) - return NULL; - attr = lattr; - use_xy = use_attr = TRUE; - break; - default: - PyErr_SetString(PyExc_TypeError, "insstr requires 1 to 4 arguments"); - return NULL; - } - - if (use_attr == TRUE) { - attr_old = getattrs(self->win); - (void)wattrset(self->win,attr); - } - if (use_xy == TRUE) - rtn = mvwinsstr(self->win,y,x,str); - else - rtn = winsstr(self->win,str); - if (use_attr == TRUE) - (void)wattrset(self->win,attr_old); - return PyCursesCheckERR(rtn, "insstr"); + int rtn; + int x, y; + char *str; + attr_t attr = A_NORMAL , attr_old = A_NORMAL; + long lattr; + int use_xy = FALSE, use_attr = FALSE; + + switch (PyTuple_Size(args)) { + case 1: + if (!PyArg_ParseTuple(args,"s;str", &str)) + return NULL; + break; + case 2: + if (!PyArg_ParseTuple(args,"sl;str,attr", &str, &lattr)) + return NULL; + attr = lattr; + use_attr = TRUE; + break; + case 3: + if (!PyArg_ParseTuple(args,"iis;y,x,str", &y, &x, &str)) + return NULL; + use_xy = TRUE; + break; + case 4: + if (!PyArg_ParseTuple(args,"iisl;y,x,str,attr", &y, &x, &str, &lattr)) + return NULL; + attr = lattr; + use_xy = use_attr = TRUE; + break; + default: + PyErr_SetString(PyExc_TypeError, "insstr requires 1 to 4 arguments"); + return NULL; + } + + if (use_attr == TRUE) { + attr_old = getattrs(self->win); + (void)wattrset(self->win,attr); + } + if (use_xy == TRUE) + rtn = mvwinsstr(self->win,y,x,str); + else + rtn = winsstr(self->win,str); + if (use_attr == TRUE) + (void)wattrset(self->win,attr_old); + return PyCursesCheckERR(rtn, "insstr"); } static PyObject * PyCursesWindow_InsNStr(PyCursesWindowObject *self, PyObject *args) { - int rtn, x, y, n; - char *str; - attr_t attr = A_NORMAL , attr_old = A_NORMAL; - long lattr; - int use_xy = FALSE, use_attr = FALSE; - - switch (PyTuple_Size(args)) { - case 2: - if (!PyArg_ParseTuple(args,"si;str,n", &str, &n)) - return NULL; - break; - case 3: - if (!PyArg_ParseTuple(args,"sil;str,n,attr", &str, &n, &lattr)) - return NULL; - attr = lattr; - use_attr = TRUE; - break; - case 4: - if (!PyArg_ParseTuple(args,"iisi;y,x,str,n", &y, &x, &str, &n)) - return NULL; - use_xy = TRUE; - break; - case 5: - if (!PyArg_ParseTuple(args,"iisil;y,x,str,n,attr", &y, &x, &str, &n, &lattr)) - return NULL; - attr = lattr; - use_xy = use_attr = TRUE; - break; - default: - PyErr_SetString(PyExc_TypeError, "insnstr requires 2 to 5 arguments"); - return NULL; - } - - if (use_attr == TRUE) { - attr_old = getattrs(self->win); - (void)wattrset(self->win,attr); - } - if (use_xy == TRUE) - rtn = mvwinsnstr(self->win,y,x,str,n); - else - rtn = winsnstr(self->win,str,n); - if (use_attr == TRUE) - (void)wattrset(self->win,attr_old); - return PyCursesCheckERR(rtn, "insnstr"); + int rtn, x, y, n; + char *str; + attr_t attr = A_NORMAL , attr_old = A_NORMAL; + long lattr; + int use_xy = FALSE, use_attr = FALSE; + + switch (PyTuple_Size(args)) { + case 2: + if (!PyArg_ParseTuple(args,"si;str,n", &str, &n)) + return NULL; + break; + case 3: + if (!PyArg_ParseTuple(args,"sil;str,n,attr", &str, &n, &lattr)) + return NULL; + attr = lattr; + use_attr = TRUE; + break; + case 4: + if (!PyArg_ParseTuple(args,"iisi;y,x,str,n", &y, &x, &str, &n)) + return NULL; + use_xy = TRUE; + break; + case 5: + if (!PyArg_ParseTuple(args,"iisil;y,x,str,n,attr", &y, &x, &str, &n, &lattr)) + return NULL; + attr = lattr; + use_xy = use_attr = TRUE; + break; + default: + PyErr_SetString(PyExc_TypeError, "insnstr requires 2 to 5 arguments"); + return NULL; + } + + if (use_attr == TRUE) { + attr_old = getattrs(self->win); + (void)wattrset(self->win,attr); + } + if (use_xy == TRUE) + rtn = mvwinsnstr(self->win,y,x,str,n); + else + rtn = winsnstr(self->win,str,n); + if (use_attr == TRUE) + (void)wattrset(self->win,attr_old); + return PyCursesCheckERR(rtn, "insnstr"); } static PyObject * PyCursesWindow_Is_LineTouched(PyCursesWindowObject *self, PyObject *args) { - int line, erg; - if (!PyArg_ParseTuple(args,"i;line", &line)) - return NULL; - erg = is_linetouched(self->win, line); - if (erg == ERR) { - PyErr_SetString(PyExc_TypeError, - "is_linetouched: line number outside of boundaries"); - return NULL; - } else - if (erg == FALSE) { - Py_INCREF(Py_False); - return Py_False; - } else { - Py_INCREF(Py_True); - return Py_True; - } + int line, erg; + if (!PyArg_ParseTuple(args,"i;line", &line)) + return NULL; + erg = is_linetouched(self->win, line); + if (erg == ERR) { + PyErr_SetString(PyExc_TypeError, + "is_linetouched: line number outside of boundaries"); + return NULL; + } else + if (erg == FALSE) { + Py_INCREF(Py_False); + return Py_False; + } else { + Py_INCREF(Py_True); + return Py_True; + } } static PyObject * PyCursesWindow_NoOutRefresh(PyCursesWindowObject *self, PyObject *args) { - int pminrow,pmincol,sminrow,smincol,smaxrow,smaxcol; - int rtn; + int pminrow,pmincol,sminrow,smincol,smaxrow,smaxcol; + int rtn; #ifndef WINDOW_HAS_FLAGS - if (0) + if (0) #else - if (self->win->_flags & _ISPAD) + if (self->win->_flags & _ISPAD) #endif - { - switch(PyTuple_Size(args)) { - case 6: - if (!PyArg_ParseTuple(args, - "iiiiii;" \ - "pminrow,pmincol,sminrow,smincol,smaxrow,smaxcol", - &pminrow, &pmincol, &sminrow, - &smincol, &smaxrow, &smaxcol)) - return NULL; - Py_BEGIN_ALLOW_THREADS - rtn = pnoutrefresh(self->win, - pminrow, pmincol, sminrow, - smincol, smaxrow, smaxcol); - Py_END_ALLOW_THREADS - return PyCursesCheckERR(rtn, "pnoutrefresh"); - default: - PyErr_SetString(PyCursesError, - "noutrefresh() called for a pad " - "requires 6 arguments"); - return NULL; - } - } else { - if (!PyArg_ParseTuple(args, ":noutrefresh")) - return NULL; - - Py_BEGIN_ALLOW_THREADS - rtn = wnoutrefresh(self->win); - Py_END_ALLOW_THREADS - return PyCursesCheckERR(rtn, "wnoutrefresh"); - } + { + switch(PyTuple_Size(args)) { + case 6: + if (!PyArg_ParseTuple(args, + "iiiiii;" \ + "pminrow,pmincol,sminrow,smincol,smaxrow,smaxcol", + &pminrow, &pmincol, &sminrow, + &smincol, &smaxrow, &smaxcol)) + return NULL; + Py_BEGIN_ALLOW_THREADS + rtn = pnoutrefresh(self->win, + pminrow, pmincol, sminrow, + smincol, smaxrow, smaxcol); + Py_END_ALLOW_THREADS + return PyCursesCheckERR(rtn, "pnoutrefresh"); + default: + PyErr_SetString(PyCursesError, + "noutrefresh() called for a pad " + "requires 6 arguments"); + return NULL; + } + } else { + if (!PyArg_ParseTuple(args, ":noutrefresh")) + return NULL; + + Py_BEGIN_ALLOW_THREADS + rtn = wnoutrefresh(self->win); + Py_END_ALLOW_THREADS + return PyCursesCheckERR(rtn, "wnoutrefresh"); + } } static PyObject * @@ -1276,34 +1276,34 @@ int use_copywin = FALSE; int sminrow, smincol, dminrow, dmincol, dmaxrow, dmaxcol; int rtn; - + switch (PyTuple_Size(args)) { case 1: - if (!PyArg_ParseTuple(args, "O!;window object", - &PyCursesWindow_Type, &temp)) - return NULL; - break; + if (!PyArg_ParseTuple(args, "O!;window object", + &PyCursesWindow_Type, &temp)) + return NULL; + break; case 7: - if (!PyArg_ParseTuple(args, "O!iiiiii;window object, int, int, int, int, int, int", - &PyCursesWindow_Type, &temp, &sminrow, &smincol, - &dminrow, &dmincol, &dmaxrow, &dmaxcol)) - return NULL; - use_copywin = TRUE; - break; - default: - PyErr_SetString(PyExc_TypeError, - "overlay requires one or seven arguments"); - return NULL; + if (!PyArg_ParseTuple(args, "O!iiiiii;window object, int, int, int, int, int, int", + &PyCursesWindow_Type, &temp, &sminrow, &smincol, + &dminrow, &dmincol, &dmaxrow, &dmaxcol)) + return NULL; + use_copywin = TRUE; + break; + default: + PyErr_SetString(PyExc_TypeError, + "overlay requires one or seven arguments"); + return NULL; } if (use_copywin == TRUE) { - rtn = copywin(self->win, temp->win, sminrow, smincol, - dminrow, dmincol, dmaxrow, dmaxcol, TRUE); - return PyCursesCheckERR(rtn, "copywin"); + rtn = copywin(self->win, temp->win, sminrow, smincol, + dminrow, dmincol, dmaxrow, dmaxcol, TRUE); + return PyCursesCheckERR(rtn, "copywin"); } else { - rtn = overlay(self->win, temp->win); - return PyCursesCheckERR(rtn, "overlay"); + rtn = overlay(self->win, temp->win); + return PyCursesCheckERR(rtn, "overlay"); } } @@ -1314,342 +1314,342 @@ int use_copywin = FALSE; int sminrow, smincol, dminrow, dmincol, dmaxrow, dmaxcol; int rtn; - + switch (PyTuple_Size(args)) { case 1: - if (!PyArg_ParseTuple(args, "O!;window object", - &PyCursesWindow_Type, &temp)) - return NULL; - break; + if (!PyArg_ParseTuple(args, "O!;window object", + &PyCursesWindow_Type, &temp)) + return NULL; + break; case 7: - if (!PyArg_ParseTuple(args, "O!iiiiii;window object, int, int, int, int, int, int", - &PyCursesWindow_Type, &temp, &sminrow, &smincol, - &dminrow, &dmincol, &dmaxrow, &dmaxcol)) - return NULL; - use_copywin = TRUE; - break; - default: - PyErr_SetString(PyExc_TypeError, - "overwrite requires one or seven arguments"); - return NULL; + if (!PyArg_ParseTuple(args, "O!iiiiii;window object, int, int, int, int, int, int", + &PyCursesWindow_Type, &temp, &sminrow, &smincol, + &dminrow, &dmincol, &dmaxrow, &dmaxcol)) + return NULL; + use_copywin = TRUE; + break; + default: + PyErr_SetString(PyExc_TypeError, + "overwrite requires one or seven arguments"); + return NULL; } if (use_copywin == TRUE) { - rtn = copywin(self->win, temp->win, sminrow, smincol, - dminrow, dmincol, dmaxrow, dmaxcol, FALSE); + rtn = copywin(self->win, temp->win, sminrow, smincol, + dminrow, dmincol, dmaxrow, dmaxcol, FALSE); return PyCursesCheckERR(rtn, "copywin"); } else { - rtn = overwrite(self->win, temp->win); - return PyCursesCheckERR(rtn, "overwrite"); + rtn = overwrite(self->win, temp->win); + return PyCursesCheckERR(rtn, "overwrite"); } } static PyObject * PyCursesWindow_PutWin(PyCursesWindowObject *self, PyObject *args) { - PyObject *temp; - - if (!PyArg_ParseTuple(args, "O;fileobj", &temp)) - return NULL; - if (!PyFile_Check(temp)) { - PyErr_SetString(PyExc_TypeError, "argument must be a file object"); - return NULL; - } - return PyCursesCheckERR(putwin(self->win, PyFile_AsFile(temp)), - "putwin"); + PyObject *temp; + + if (!PyArg_ParseTuple(args, "O;fileobj", &temp)) + return NULL; + if (!PyFile_Check(temp)) { + PyErr_SetString(PyExc_TypeError, "argument must be a file object"); + return NULL; + } + return PyCursesCheckERR(putwin(self->win, PyFile_AsFile(temp)), + "putwin"); } static PyObject * PyCursesWindow_RedrawLine(PyCursesWindowObject *self, PyObject *args) { - int beg, num; - if (!PyArg_ParseTuple(args, "ii;beg,num", &beg, &num)) - return NULL; - return PyCursesCheckERR(wredrawln(self->win,beg,num), "redrawln"); + int beg, num; + if (!PyArg_ParseTuple(args, "ii;beg,num", &beg, &num)) + return NULL; + return PyCursesCheckERR(wredrawln(self->win,beg,num), "redrawln"); } static PyObject * PyCursesWindow_Refresh(PyCursesWindowObject *self, PyObject *args) { - int pminrow,pmincol,sminrow,smincol,smaxrow,smaxcol; - int rtn; - + int pminrow,pmincol,sminrow,smincol,smaxrow,smaxcol; + int rtn; + #ifndef WINDOW_HAS_FLAGS - if (0) + if (0) #else - if (self->win->_flags & _ISPAD) + if (self->win->_flags & _ISPAD) #endif - { - switch(PyTuple_Size(args)) { - case 6: - if (!PyArg_ParseTuple(args, - "iiiiii;" \ - "pminrow,pmincol,sminrow,smincol,smaxrow,smaxcol", - &pminrow, &pmincol, &sminrow, - &smincol, &smaxrow, &smaxcol)) - return NULL; - - Py_BEGIN_ALLOW_THREADS - rtn = prefresh(self->win, - pminrow, pmincol, sminrow, - smincol, smaxrow, smaxcol); - Py_END_ALLOW_THREADS - return PyCursesCheckERR(rtn, "prefresh"); - default: - PyErr_SetString(PyCursesError, - "refresh() for a pad requires 6 arguments"); - return NULL; - } - } else { - if (!PyArg_ParseTuple(args, ":refresh")) - return NULL; - Py_BEGIN_ALLOW_THREADS - rtn = wrefresh(self->win); - Py_END_ALLOW_THREADS - return PyCursesCheckERR(rtn, "prefresh"); - } + { + switch(PyTuple_Size(args)) { + case 6: + if (!PyArg_ParseTuple(args, + "iiiiii;" \ + "pminrow,pmincol,sminrow,smincol,smaxrow,smaxcol", + &pminrow, &pmincol, &sminrow, + &smincol, &smaxrow, &smaxcol)) + return NULL; + + Py_BEGIN_ALLOW_THREADS + rtn = prefresh(self->win, + pminrow, pmincol, sminrow, + smincol, smaxrow, smaxcol); + Py_END_ALLOW_THREADS + return PyCursesCheckERR(rtn, "prefresh"); + default: + PyErr_SetString(PyCursesError, + "refresh() for a pad requires 6 arguments"); + return NULL; + } + } else { + if (!PyArg_ParseTuple(args, ":refresh")) + return NULL; + Py_BEGIN_ALLOW_THREADS + rtn = wrefresh(self->win); + Py_END_ALLOW_THREADS + return PyCursesCheckERR(rtn, "prefresh"); + } } static PyObject * PyCursesWindow_SetScrollRegion(PyCursesWindowObject *self, PyObject *args) { - int x, y; - if (!PyArg_ParseTuple(args,"ii;top, bottom",&y,&x)) - return NULL; - return PyCursesCheckERR(wsetscrreg(self->win,y,x), "wsetscrreg"); + int x, y; + if (!PyArg_ParseTuple(args,"ii;top, bottom",&y,&x)) + return NULL; + return PyCursesCheckERR(wsetscrreg(self->win,y,x), "wsetscrreg"); } static PyObject * PyCursesWindow_SubWin(PyCursesWindowObject *self, PyObject *args) { - WINDOW *win; - int nlines, ncols, begin_y, begin_x; + WINDOW *win; + int nlines, ncols, begin_y, begin_x; - nlines = 0; - ncols = 0; - switch (PyTuple_Size(args)) { - case 2: - if (!PyArg_ParseTuple(args,"ii;begin_y,begin_x",&begin_y,&begin_x)) - return NULL; - break; - case 4: - if (!PyArg_ParseTuple(args, "iiii;nlines,ncols,begin_y,begin_x", - &nlines,&ncols,&begin_y,&begin_x)) - return NULL; - break; - default: - PyErr_SetString(PyExc_TypeError, "subwin requires 2 or 4 arguments"); - return NULL; - } + nlines = 0; + ncols = 0; + switch (PyTuple_Size(args)) { + case 2: + if (!PyArg_ParseTuple(args,"ii;begin_y,begin_x",&begin_y,&begin_x)) + return NULL; + break; + case 4: + if (!PyArg_ParseTuple(args, "iiii;nlines,ncols,begin_y,begin_x", + &nlines,&ncols,&begin_y,&begin_x)) + return NULL; + break; + default: + PyErr_SetString(PyExc_TypeError, "subwin requires 2 or 4 arguments"); + return NULL; + } - /* printf("Subwin: %i %i %i %i \n", nlines, ncols, begin_y, begin_x); */ + /* printf("Subwin: %i %i %i %i \n", nlines, ncols, begin_y, begin_x); */ #ifdef WINDOW_HAS_FLAGS - if (self->win->_flags & _ISPAD) - win = subpad(self->win, nlines, ncols, begin_y, begin_x); - else -#endif - win = subwin(self->win, nlines, ncols, begin_y, begin_x); - - if (win == NULL) { - PyErr_SetString(PyCursesError, catchall_NULL); - return NULL; - } - - return (PyObject *)PyCursesWindow_New(win); + if (self->win->_flags & _ISPAD) + win = subpad(self->win, nlines, ncols, begin_y, begin_x); + else +#endif + win = subwin(self->win, nlines, ncols, begin_y, begin_x); + + if (win == NULL) { + PyErr_SetString(PyCursesError, catchall_NULL); + return NULL; + } + + return (PyObject *)PyCursesWindow_New(win); } static PyObject * PyCursesWindow_Scroll(PyCursesWindowObject *self, PyObject *args) { - int nlines; - switch(PyTuple_Size(args)) { - case 0: - return PyCursesCheckERR(scroll(self->win), "scroll"); - case 1: - if (!PyArg_ParseTuple(args, "i;nlines", &nlines)) - return NULL; - return PyCursesCheckERR(wscrl(self->win, nlines), "scroll"); - default: - PyErr_SetString(PyExc_TypeError, "scroll requires 0 or 1 arguments"); - return NULL; - } + int nlines; + switch(PyTuple_Size(args)) { + case 0: + return PyCursesCheckERR(scroll(self->win), "scroll"); + case 1: + if (!PyArg_ParseTuple(args, "i;nlines", &nlines)) + return NULL; + return PyCursesCheckERR(wscrl(self->win, nlines), "scroll"); + default: + PyErr_SetString(PyExc_TypeError, "scroll requires 0 or 1 arguments"); + return NULL; + } } static PyObject * PyCursesWindow_TouchLine(PyCursesWindowObject *self, PyObject *args) { - int st, cnt, val; - switch (PyTuple_Size(args)) { - case 2: - if (!PyArg_ParseTuple(args,"ii;start,count",&st,&cnt)) - return NULL; - return PyCursesCheckERR(touchline(self->win,st,cnt), "touchline"); - case 3: - if (!PyArg_ParseTuple(args, "iii;start,count,val", &st, &cnt, &val)) - return NULL; - return PyCursesCheckERR(wtouchln(self->win, st, cnt, val), "touchline"); - default: - PyErr_SetString(PyExc_TypeError, "touchline requires 2 or 3 arguments"); - return NULL; - } + int st, cnt, val; + switch (PyTuple_Size(args)) { + case 2: + if (!PyArg_ParseTuple(args,"ii;start,count",&st,&cnt)) + return NULL; + return PyCursesCheckERR(touchline(self->win,st,cnt), "touchline"); + case 3: + if (!PyArg_ParseTuple(args, "iii;start,count,val", &st, &cnt, &val)) + return NULL; + return PyCursesCheckERR(wtouchln(self->win, st, cnt, val), "touchline"); + default: + PyErr_SetString(PyExc_TypeError, "touchline requires 2 or 3 arguments"); + return NULL; + } } static PyObject * PyCursesWindow_Vline(PyCursesWindowObject *self, PyObject *args) { - PyObject *temp; - chtype ch; - int n, x, y, code = OK; - attr_t attr = A_NORMAL; - long lattr; - - switch (PyTuple_Size(args)) { - case 2: - if (!PyArg_ParseTuple(args, "Oi;ch or int,n", &temp, &n)) - return NULL; - break; - case 3: - if (!PyArg_ParseTuple(args, "Oil;ch or int,n,attr", &temp, &n, &lattr)) - return NULL; - attr = lattr; - break; - case 4: - if (!PyArg_ParseTuple(args, "iiOi;y,x,ch or int,n", &y, &x, &temp, &n)) - return NULL; - code = wmove(self->win, y, x); - break; - case 5: - if (!PyArg_ParseTuple(args, "iiOil; y,x,ch or int,n,attr", - &y, &x, &temp, &n, &lattr)) - return NULL; - attr = lattr; - code = wmove(self->win, y, x); - break; - default: - PyErr_SetString(PyExc_TypeError, "vline requires 2 to 5 arguments"); - return NULL; - } + PyObject *temp; + chtype ch; + int n, x, y, code = OK; + attr_t attr = A_NORMAL; + long lattr; - if (code != ERR) { - if (!PyCurses_ConvertToChtype(temp, &ch)) { - PyErr_SetString(PyExc_TypeError, - "argument 1 or 3 must be a ch or an int"); - return NULL; - } - return PyCursesCheckERR(wvline(self->win, ch | attr, n), "vline"); - } else - return PyCursesCheckERR(code, "wmove"); + switch (PyTuple_Size(args)) { + case 2: + if (!PyArg_ParseTuple(args, "Oi;ch or int,n", &temp, &n)) + return NULL; + break; + case 3: + if (!PyArg_ParseTuple(args, "Oil;ch or int,n,attr", &temp, &n, &lattr)) + return NULL; + attr = lattr; + break; + case 4: + if (!PyArg_ParseTuple(args, "iiOi;y,x,ch or int,n", &y, &x, &temp, &n)) + return NULL; + code = wmove(self->win, y, x); + break; + case 5: + if (!PyArg_ParseTuple(args, "iiOil; y,x,ch or int,n,attr", + &y, &x, &temp, &n, &lattr)) + return NULL; + attr = lattr; + code = wmove(self->win, y, x); + break; + default: + PyErr_SetString(PyExc_TypeError, "vline requires 2 to 5 arguments"); + return NULL; + } + + if (code != ERR) { + if (!PyCurses_ConvertToChtype(temp, &ch)) { + PyErr_SetString(PyExc_TypeError, + "argument 1 or 3 must be a ch or an int"); + return NULL; + } + return PyCursesCheckERR(wvline(self->win, ch | attr, n), "vline"); + } else + return PyCursesCheckERR(code, "wmove"); } static PyMethodDef PyCursesWindow_Methods[] = { - {"addch", (PyCFunction)PyCursesWindow_AddCh, METH_VARARGS}, - {"addnstr", (PyCFunction)PyCursesWindow_AddNStr, METH_VARARGS}, - {"addstr", (PyCFunction)PyCursesWindow_AddStr, METH_VARARGS}, - {"attroff", (PyCFunction)PyCursesWindow_AttrOff, METH_VARARGS}, - {"attron", (PyCFunction)PyCursesWindow_AttrOn, METH_VARARGS}, - {"attrset", (PyCFunction)PyCursesWindow_AttrSet, METH_VARARGS}, - {"bkgd", (PyCFunction)PyCursesWindow_Bkgd, METH_VARARGS}, - {"chgat", (PyCFunction)PyCursesWindow_ChgAt, METH_VARARGS}, - {"bkgdset", (PyCFunction)PyCursesWindow_BkgdSet, METH_VARARGS}, - {"border", (PyCFunction)PyCursesWindow_Border, METH_VARARGS}, - {"box", (PyCFunction)PyCursesWindow_Box, METH_VARARGS}, - {"clear", (PyCFunction)PyCursesWindow_wclear, METH_NOARGS}, - {"clearok", (PyCFunction)PyCursesWindow_clearok, METH_VARARGS}, - {"clrtobot", (PyCFunction)PyCursesWindow_wclrtobot, METH_NOARGS}, - {"clrtoeol", (PyCFunction)PyCursesWindow_wclrtoeol, METH_NOARGS}, - {"cursyncup", (PyCFunction)PyCursesWindow_wcursyncup, METH_NOARGS}, - {"delch", (PyCFunction)PyCursesWindow_DelCh, METH_VARARGS}, - {"deleteln", (PyCFunction)PyCursesWindow_wdeleteln, METH_NOARGS}, - {"derwin", (PyCFunction)PyCursesWindow_DerWin, METH_VARARGS}, - {"echochar", (PyCFunction)PyCursesWindow_EchoChar, METH_VARARGS}, + {"addch", (PyCFunction)PyCursesWindow_AddCh, METH_VARARGS}, + {"addnstr", (PyCFunction)PyCursesWindow_AddNStr, METH_VARARGS}, + {"addstr", (PyCFunction)PyCursesWindow_AddStr, METH_VARARGS}, + {"attroff", (PyCFunction)PyCursesWindow_AttrOff, METH_VARARGS}, + {"attron", (PyCFunction)PyCursesWindow_AttrOn, METH_VARARGS}, + {"attrset", (PyCFunction)PyCursesWindow_AttrSet, METH_VARARGS}, + {"bkgd", (PyCFunction)PyCursesWindow_Bkgd, METH_VARARGS}, + {"chgat", (PyCFunction)PyCursesWindow_ChgAt, METH_VARARGS}, + {"bkgdset", (PyCFunction)PyCursesWindow_BkgdSet, METH_VARARGS}, + {"border", (PyCFunction)PyCursesWindow_Border, METH_VARARGS}, + {"box", (PyCFunction)PyCursesWindow_Box, METH_VARARGS}, + {"clear", (PyCFunction)PyCursesWindow_wclear, METH_NOARGS}, + {"clearok", (PyCFunction)PyCursesWindow_clearok, METH_VARARGS}, + {"clrtobot", (PyCFunction)PyCursesWindow_wclrtobot, METH_NOARGS}, + {"clrtoeol", (PyCFunction)PyCursesWindow_wclrtoeol, METH_NOARGS}, + {"cursyncup", (PyCFunction)PyCursesWindow_wcursyncup, METH_NOARGS}, + {"delch", (PyCFunction)PyCursesWindow_DelCh, METH_VARARGS}, + {"deleteln", (PyCFunction)PyCursesWindow_wdeleteln, METH_NOARGS}, + {"derwin", (PyCFunction)PyCursesWindow_DerWin, METH_VARARGS}, + {"echochar", (PyCFunction)PyCursesWindow_EchoChar, METH_VARARGS}, #ifdef NCURSES_MOUSE_VERSION - {"enclose", (PyCFunction)PyCursesWindow_Enclose, METH_VARARGS}, + {"enclose", (PyCFunction)PyCursesWindow_Enclose, METH_VARARGS}, #endif - {"erase", (PyCFunction)PyCursesWindow_werase, METH_NOARGS}, - {"getbegyx", (PyCFunction)PyCursesWindow_getbegyx, METH_NOARGS}, - {"getbkgd", (PyCFunction)PyCursesWindow_GetBkgd, METH_NOARGS}, - {"getch", (PyCFunction)PyCursesWindow_GetCh, METH_VARARGS}, - {"getkey", (PyCFunction)PyCursesWindow_GetKey, METH_VARARGS}, - {"getmaxyx", (PyCFunction)PyCursesWindow_getmaxyx, METH_NOARGS}, - {"getparyx", (PyCFunction)PyCursesWindow_getparyx, METH_NOARGS}, - {"getstr", (PyCFunction)PyCursesWindow_GetStr, METH_VARARGS}, - {"getyx", (PyCFunction)PyCursesWindow_getyx, METH_NOARGS}, - {"hline", (PyCFunction)PyCursesWindow_Hline, METH_VARARGS}, - {"idcok", (PyCFunction)PyCursesWindow_idcok, METH_VARARGS}, - {"idlok", (PyCFunction)PyCursesWindow_idlok, METH_VARARGS}, - {"immedok", (PyCFunction)PyCursesWindow_immedok, METH_VARARGS}, - {"inch", (PyCFunction)PyCursesWindow_InCh, METH_VARARGS}, - {"insch", (PyCFunction)PyCursesWindow_InsCh, METH_VARARGS}, - {"insdelln", (PyCFunction)PyCursesWindow_winsdelln, METH_VARARGS}, - {"insertln", (PyCFunction)PyCursesWindow_winsertln, METH_NOARGS}, - {"insnstr", (PyCFunction)PyCursesWindow_InsNStr, METH_VARARGS}, - {"insstr", (PyCFunction)PyCursesWindow_InsStr, METH_VARARGS}, - {"instr", (PyCFunction)PyCursesWindow_InStr, METH_VARARGS}, - {"is_linetouched", (PyCFunction)PyCursesWindow_Is_LineTouched, METH_VARARGS}, - {"is_wintouched", (PyCFunction)PyCursesWindow_is_wintouched, METH_NOARGS}, - {"keypad", (PyCFunction)PyCursesWindow_keypad, METH_VARARGS}, - {"leaveok", (PyCFunction)PyCursesWindow_leaveok, METH_VARARGS}, - {"move", (PyCFunction)PyCursesWindow_wmove, METH_VARARGS}, - {"mvderwin", (PyCFunction)PyCursesWindow_mvderwin, METH_VARARGS}, - {"mvwin", (PyCFunction)PyCursesWindow_mvwin, METH_VARARGS}, - {"nodelay", (PyCFunction)PyCursesWindow_nodelay, METH_VARARGS}, - {"notimeout", (PyCFunction)PyCursesWindow_notimeout, METH_VARARGS}, - {"noutrefresh", (PyCFunction)PyCursesWindow_NoOutRefresh, METH_VARARGS}, - /* Backward compatibility alias -- remove in Python 2.3 */ - {"nooutrefresh", (PyCFunction)PyCursesWindow_NoOutRefresh, METH_VARARGS}, - {"overlay", (PyCFunction)PyCursesWindow_Overlay, METH_VARARGS}, - {"overwrite", (PyCFunction)PyCursesWindow_Overwrite, - METH_VARARGS}, - {"putwin", (PyCFunction)PyCursesWindow_PutWin, METH_VARARGS}, - {"redrawln", (PyCFunction)PyCursesWindow_RedrawLine, METH_VARARGS}, - {"redrawwin", (PyCFunction)PyCursesWindow_redrawwin, METH_NOARGS}, - {"refresh", (PyCFunction)PyCursesWindow_Refresh, METH_VARARGS}, + {"erase", (PyCFunction)PyCursesWindow_werase, METH_NOARGS}, + {"getbegyx", (PyCFunction)PyCursesWindow_getbegyx, METH_NOARGS}, + {"getbkgd", (PyCFunction)PyCursesWindow_GetBkgd, METH_NOARGS}, + {"getch", (PyCFunction)PyCursesWindow_GetCh, METH_VARARGS}, + {"getkey", (PyCFunction)PyCursesWindow_GetKey, METH_VARARGS}, + {"getmaxyx", (PyCFunction)PyCursesWindow_getmaxyx, METH_NOARGS}, + {"getparyx", (PyCFunction)PyCursesWindow_getparyx, METH_NOARGS}, + {"getstr", (PyCFunction)PyCursesWindow_GetStr, METH_VARARGS}, + {"getyx", (PyCFunction)PyCursesWindow_getyx, METH_NOARGS}, + {"hline", (PyCFunction)PyCursesWindow_Hline, METH_VARARGS}, + {"idcok", (PyCFunction)PyCursesWindow_idcok, METH_VARARGS}, + {"idlok", (PyCFunction)PyCursesWindow_idlok, METH_VARARGS}, + {"immedok", (PyCFunction)PyCursesWindow_immedok, METH_VARARGS}, + {"inch", (PyCFunction)PyCursesWindow_InCh, METH_VARARGS}, + {"insch", (PyCFunction)PyCursesWindow_InsCh, METH_VARARGS}, + {"insdelln", (PyCFunction)PyCursesWindow_winsdelln, METH_VARARGS}, + {"insertln", (PyCFunction)PyCursesWindow_winsertln, METH_NOARGS}, + {"insnstr", (PyCFunction)PyCursesWindow_InsNStr, METH_VARARGS}, + {"insstr", (PyCFunction)PyCursesWindow_InsStr, METH_VARARGS}, + {"instr", (PyCFunction)PyCursesWindow_InStr, METH_VARARGS}, + {"is_linetouched", (PyCFunction)PyCursesWindow_Is_LineTouched, METH_VARARGS}, + {"is_wintouched", (PyCFunction)PyCursesWindow_is_wintouched, METH_NOARGS}, + {"keypad", (PyCFunction)PyCursesWindow_keypad, METH_VARARGS}, + {"leaveok", (PyCFunction)PyCursesWindow_leaveok, METH_VARARGS}, + {"move", (PyCFunction)PyCursesWindow_wmove, METH_VARARGS}, + {"mvderwin", (PyCFunction)PyCursesWindow_mvderwin, METH_VARARGS}, + {"mvwin", (PyCFunction)PyCursesWindow_mvwin, METH_VARARGS}, + {"nodelay", (PyCFunction)PyCursesWindow_nodelay, METH_VARARGS}, + {"notimeout", (PyCFunction)PyCursesWindow_notimeout, METH_VARARGS}, + {"noutrefresh", (PyCFunction)PyCursesWindow_NoOutRefresh, METH_VARARGS}, + /* Backward compatibility alias -- remove in Python 2.3 */ + {"nooutrefresh", (PyCFunction)PyCursesWindow_NoOutRefresh, METH_VARARGS}, + {"overlay", (PyCFunction)PyCursesWindow_Overlay, METH_VARARGS}, + {"overwrite", (PyCFunction)PyCursesWindow_Overwrite, + METH_VARARGS}, + {"putwin", (PyCFunction)PyCursesWindow_PutWin, METH_VARARGS}, + {"redrawln", (PyCFunction)PyCursesWindow_RedrawLine, METH_VARARGS}, + {"redrawwin", (PyCFunction)PyCursesWindow_redrawwin, METH_NOARGS}, + {"refresh", (PyCFunction)PyCursesWindow_Refresh, METH_VARARGS}, #ifndef STRICT_SYSV_CURSES - {"resize", (PyCFunction)PyCursesWindow_wresize, METH_VARARGS}, + {"resize", (PyCFunction)PyCursesWindow_wresize, METH_VARARGS}, #endif - {"scroll", (PyCFunction)PyCursesWindow_Scroll, METH_VARARGS}, - {"scrollok", (PyCFunction)PyCursesWindow_scrollok, METH_VARARGS}, - {"setscrreg", (PyCFunction)PyCursesWindow_SetScrollRegion, METH_VARARGS}, - {"standend", (PyCFunction)PyCursesWindow_wstandend, METH_NOARGS}, - {"standout", (PyCFunction)PyCursesWindow_wstandout, METH_NOARGS}, - {"subpad", (PyCFunction)PyCursesWindow_SubWin, METH_VARARGS}, - {"subwin", (PyCFunction)PyCursesWindow_SubWin, METH_VARARGS}, - {"syncdown", (PyCFunction)PyCursesWindow_wsyncdown, METH_NOARGS}, - {"syncok", (PyCFunction)PyCursesWindow_syncok, METH_VARARGS}, - {"syncup", (PyCFunction)PyCursesWindow_wsyncup, METH_NOARGS}, - {"timeout", (PyCFunction)PyCursesWindow_wtimeout, METH_VARARGS}, - {"touchline", (PyCFunction)PyCursesWindow_TouchLine, METH_VARARGS}, - {"touchwin", (PyCFunction)PyCursesWindow_touchwin, METH_NOARGS}, - {"untouchwin", (PyCFunction)PyCursesWindow_untouchwin, METH_NOARGS}, - {"vline", (PyCFunction)PyCursesWindow_Vline, METH_VARARGS}, - {NULL, NULL} /* sentinel */ + {"scroll", (PyCFunction)PyCursesWindow_Scroll, METH_VARARGS}, + {"scrollok", (PyCFunction)PyCursesWindow_scrollok, METH_VARARGS}, + {"setscrreg", (PyCFunction)PyCursesWindow_SetScrollRegion, METH_VARARGS}, + {"standend", (PyCFunction)PyCursesWindow_wstandend, METH_NOARGS}, + {"standout", (PyCFunction)PyCursesWindow_wstandout, METH_NOARGS}, + {"subpad", (PyCFunction)PyCursesWindow_SubWin, METH_VARARGS}, + {"subwin", (PyCFunction)PyCursesWindow_SubWin, METH_VARARGS}, + {"syncdown", (PyCFunction)PyCursesWindow_wsyncdown, METH_NOARGS}, + {"syncok", (PyCFunction)PyCursesWindow_syncok, METH_VARARGS}, + {"syncup", (PyCFunction)PyCursesWindow_wsyncup, METH_NOARGS}, + {"timeout", (PyCFunction)PyCursesWindow_wtimeout, METH_VARARGS}, + {"touchline", (PyCFunction)PyCursesWindow_TouchLine, METH_VARARGS}, + {"touchwin", (PyCFunction)PyCursesWindow_touchwin, METH_NOARGS}, + {"untouchwin", (PyCFunction)PyCursesWindow_untouchwin, METH_NOARGS}, + {"vline", (PyCFunction)PyCursesWindow_Vline, METH_VARARGS}, + {NULL, NULL} /* sentinel */ }; static PyObject * PyCursesWindow_GetAttr(PyCursesWindowObject *self, char *name) { - return Py_FindMethod(PyCursesWindow_Methods, (PyObject *)self, name); + return Py_FindMethod(PyCursesWindow_Methods, (PyObject *)self, name); } /* -------------------------------------------------------*/ PyTypeObject PyCursesWindow_Type = { - PyVarObject_HEAD_INIT(NULL, 0) - "_curses.curses window", /*tp_name*/ - sizeof(PyCursesWindowObject), /*tp_basicsize*/ - 0, /*tp_itemsize*/ - /* methods */ - (destructor)PyCursesWindow_Dealloc, /*tp_dealloc*/ - 0, /*tp_print*/ - (getattrfunc)PyCursesWindow_GetAttr, /*tp_getattr*/ - (setattrfunc)0, /*tp_setattr*/ - 0, /*tp_compare*/ - 0, /*tp_repr*/ - 0, /*tp_as_number*/ - 0, /*tp_as_sequence*/ - 0, /*tp_as_mapping*/ - 0, /*tp_hash*/ + PyVarObject_HEAD_INIT(NULL, 0) + "_curses.curses window", /*tp_name*/ + sizeof(PyCursesWindowObject), /*tp_basicsize*/ + 0, /*tp_itemsize*/ + /* methods */ + (destructor)PyCursesWindow_Dealloc, /*tp_dealloc*/ + 0, /*tp_print*/ + (getattrfunc)PyCursesWindow_GetAttr, /*tp_getattr*/ + (setattrfunc)0, /*tp_setattr*/ + 0, /*tp_compare*/ + 0, /*tp_repr*/ + 0, /*tp_as_number*/ + 0, /*tp_as_sequence*/ + 0, /*tp_as_mapping*/ + 0, /*tp_hash*/ }; /********************************************************************* @@ -1693,418 +1693,418 @@ static PyObject * PyCurses_filter(PyObject *self) { - /* not checking for PyCursesInitialised here since filter() must - be called before initscr() */ - filter(); - Py_INCREF(Py_None); - return Py_None; + /* not checking for PyCursesInitialised here since filter() must + be called before initscr() */ + filter(); + Py_INCREF(Py_None); + return Py_None; } static PyObject * PyCurses_Color_Content(PyObject *self, PyObject *args) { - short color,r,g,b; + short color,r,g,b; - PyCursesInitialised; - PyCursesInitialisedColor; + PyCursesInitialised; + PyCursesInitialisedColor; - if (!PyArg_ParseTuple(args, "h:color_content", &color)) return NULL; + if (!PyArg_ParseTuple(args, "h:color_content", &color)) return NULL; - if (color_content(color, &r, &g, &b) != ERR) - return Py_BuildValue("(iii)", r, g, b); - else { - PyErr_SetString(PyCursesError, - "Argument 1 was out of range. Check value of COLORS."); - return NULL; - } + if (color_content(color, &r, &g, &b) != ERR) + return Py_BuildValue("(iii)", r, g, b); + else { + PyErr_SetString(PyCursesError, + "Argument 1 was out of range. Check value of COLORS."); + return NULL; + } } static PyObject * PyCurses_color_pair(PyObject *self, PyObject *args) { - int n; + int n; - PyCursesInitialised; - PyCursesInitialisedColor; + PyCursesInitialised; + PyCursesInitialisedColor; - if (!PyArg_ParseTuple(args, "i:color_pair", &n)) return NULL; - return PyInt_FromLong((long) (n << 8)); + if (!PyArg_ParseTuple(args, "i:color_pair", &n)) return NULL; + return PyInt_FromLong((long) (n << 8)); } static PyObject * PyCurses_Curs_Set(PyObject *self, PyObject *args) { - int vis,erg; + int vis,erg; - PyCursesInitialised; + PyCursesInitialised; - if (!PyArg_ParseTuple(args, "i:curs_set", &vis)) return NULL; + if (!PyArg_ParseTuple(args, "i:curs_set", &vis)) return NULL; - erg = curs_set(vis); - if (erg == ERR) return PyCursesCheckERR(erg, "curs_set"); + erg = curs_set(vis); + if (erg == ERR) return PyCursesCheckERR(erg, "curs_set"); - return PyInt_FromLong((long) erg); + return PyInt_FromLong((long) erg); } static PyObject * PyCurses_Delay_Output(PyObject *self, PyObject *args) { - int ms; + int ms; - PyCursesInitialised; + PyCursesInitialised; - if (!PyArg_ParseTuple(args, "i:delay_output", &ms)) return NULL; + if (!PyArg_ParseTuple(args, "i:delay_output", &ms)) return NULL; - return PyCursesCheckERR(delay_output(ms), "delay_output"); + return PyCursesCheckERR(delay_output(ms), "delay_output"); } static PyObject * PyCurses_EraseChar(PyObject *self) { - char ch; + char ch; - PyCursesInitialised; + PyCursesInitialised; - ch = erasechar(); + ch = erasechar(); - return PyString_FromStringAndSize(&ch, 1); + return PyString_FromStringAndSize(&ch, 1); } static PyObject * PyCurses_getsyx(PyObject *self) { - int x = 0; - int y = 0; + int x = 0; + int y = 0; - PyCursesInitialised; + PyCursesInitialised; - getsyx(y, x); + getsyx(y, x); - return Py_BuildValue("(ii)", y, x); + return Py_BuildValue("(ii)", y, x); } #ifdef NCURSES_MOUSE_VERSION static PyObject * PyCurses_GetMouse(PyObject *self) { - int rtn; - MEVENT event; + int rtn; + MEVENT event; - PyCursesInitialised; + PyCursesInitialised; - rtn = getmouse( &event ); - if (rtn == ERR) { - PyErr_SetString(PyCursesError, "getmouse() returned ERR"); - return NULL; - } - return Py_BuildValue("(hiiil)", - (short)event.id, - event.x, event.y, event.z, - (long) event.bstate); + rtn = getmouse( &event ); + if (rtn == ERR) { + PyErr_SetString(PyCursesError, "getmouse() returned ERR"); + return NULL; + } + return Py_BuildValue("(hiiil)", + (short)event.id, + event.x, event.y, event.z, + (long) event.bstate); } static PyObject * PyCurses_UngetMouse(PyObject *self, PyObject *args) { - MEVENT event; + MEVENT event; - PyCursesInitialised; - if (!PyArg_ParseTuple(args, "hiiil", - &event.id, - &event.x, &event.y, &event.z, - (int *) &event.bstate)) - return NULL; + PyCursesInitialised; + if (!PyArg_ParseTuple(args, "hiiil", + &event.id, + &event.x, &event.y, &event.z, + (int *) &event.bstate)) + return NULL; - return PyCursesCheckERR(ungetmouse(&event), "ungetmouse"); + return PyCursesCheckERR(ungetmouse(&event), "ungetmouse"); } #endif static PyObject * PyCurses_GetWin(PyCursesWindowObject *self, PyObject *temp) { - WINDOW *win; + WINDOW *win; - PyCursesInitialised; + PyCursesInitialised; - if (!PyFile_Check(temp)) { - PyErr_SetString(PyExc_TypeError, "argument must be a file object"); - return NULL; - } + if (!PyFile_Check(temp)) { + PyErr_SetString(PyExc_TypeError, "argument must be a file object"); + return NULL; + } - win = getwin(PyFile_AsFile(temp)); + win = getwin(PyFile_AsFile(temp)); - if (win == NULL) { - PyErr_SetString(PyCursesError, catchall_NULL); - return NULL; - } + if (win == NULL) { + PyErr_SetString(PyCursesError, catchall_NULL); + return NULL; + } - return PyCursesWindow_New(win); + return PyCursesWindow_New(win); } static PyObject * PyCurses_HalfDelay(PyObject *self, PyObject *args) { - unsigned char tenths; + unsigned char tenths; - PyCursesInitialised; + PyCursesInitialised; - if (!PyArg_ParseTuple(args, "b:halfdelay", &tenths)) return NULL; + if (!PyArg_ParseTuple(args, "b:halfdelay", &tenths)) return NULL; - return PyCursesCheckERR(halfdelay(tenths), "halfdelay"); + return PyCursesCheckERR(halfdelay(tenths), "halfdelay"); } #ifndef STRICT_SYSV_CURSES - /* No has_key! */ +/* No has_key! */ static PyObject * PyCurses_has_key(PyObject *self, PyObject *args) { - int ch; + int ch; - PyCursesInitialised; + PyCursesInitialised; - if (!PyArg_ParseTuple(args,"i",&ch)) return NULL; + if (!PyArg_ParseTuple(args,"i",&ch)) return NULL; - if (has_key(ch) == FALSE) { - Py_INCREF(Py_False); - return Py_False; - } - Py_INCREF(Py_True); - return Py_True; + if (has_key(ch) == FALSE) { + Py_INCREF(Py_False); + return Py_False; + } + Py_INCREF(Py_True); + return Py_True; } #endif /* STRICT_SYSV_CURSES */ static PyObject * PyCurses_Init_Color(PyObject *self, PyObject *args) { - short color, r, g, b; + short color, r, g, b; - PyCursesInitialised; - PyCursesInitialisedColor; + PyCursesInitialised; + PyCursesInitialisedColor; - switch(PyTuple_Size(args)) { - case 4: - if (!PyArg_ParseTuple(args, "hhhh;color,r,g,b", &color, &r, &g, &b)) return NULL; - break; - default: - PyErr_SetString(PyExc_TypeError, "init_color requires 4 arguments"); - return NULL; - } + switch(PyTuple_Size(args)) { + case 4: + if (!PyArg_ParseTuple(args, "hhhh;color,r,g,b", &color, &r, &g, &b)) return NULL; + break; + default: + PyErr_SetString(PyExc_TypeError, "init_color requires 4 arguments"); + return NULL; + } - return PyCursesCheckERR(init_color(color, r, g, b), "init_color"); + return PyCursesCheckERR(init_color(color, r, g, b), "init_color"); } static PyObject * PyCurses_Init_Pair(PyObject *self, PyObject *args) { - short pair, f, b; + short pair, f, b; - PyCursesInitialised; - PyCursesInitialisedColor; + PyCursesInitialised; + PyCursesInitialisedColor; - if (PyTuple_Size(args) != 3) { - PyErr_SetString(PyExc_TypeError, "init_pair requires 3 arguments"); - return NULL; - } + if (PyTuple_Size(args) != 3) { + PyErr_SetString(PyExc_TypeError, "init_pair requires 3 arguments"); + return NULL; + } - if (!PyArg_ParseTuple(args, "hhh;pair, f, b", &pair, &f, &b)) return NULL; + if (!PyArg_ParseTuple(args, "hhh;pair, f, b", &pair, &f, &b)) return NULL; - return PyCursesCheckERR(init_pair(pair, f, b), "init_pair"); + return PyCursesCheckERR(init_pair(pair, f, b), "init_pair"); } static PyObject *ModDict; -static PyObject * +static PyObject * PyCurses_InitScr(PyObject *self) { - WINDOW *win; + WINDOW *win; - if (initialised == TRUE) { - wrefresh(stdscr); - return (PyObject *)PyCursesWindow_New(stdscr); - } + if (initialised == TRUE) { + wrefresh(stdscr); + return (PyObject *)PyCursesWindow_New(stdscr); + } - win = initscr(); + win = initscr(); - if (win == NULL) { - PyErr_SetString(PyCursesError, catchall_NULL); - return NULL; - } + if (win == NULL) { + PyErr_SetString(PyCursesError, catchall_NULL); + return NULL; + } - initialised = initialised_setupterm = TRUE; + initialised = initialised_setupterm = TRUE; /* This was moved from initcurses() because it core dumped on SGI, where they're not defined until you've called initscr() */ -#define SetDictInt(string,ch) \ - do { \ - PyObject *o = PyInt_FromLong((long) (ch)); \ - if (o && PyDict_SetItemString(ModDict, string, o) == 0) { \ - Py_DECREF(o); \ - } \ +#define SetDictInt(string,ch) \ + do { \ + PyObject *o = PyInt_FromLong((long) (ch)); \ + if (o && PyDict_SetItemString(ModDict, string, o) == 0) { \ + Py_DECREF(o); \ + } \ } while (0) - /* Here are some graphic symbols you can use */ - SetDictInt("ACS_ULCORNER", (ACS_ULCORNER)); - SetDictInt("ACS_LLCORNER", (ACS_LLCORNER)); - SetDictInt("ACS_URCORNER", (ACS_URCORNER)); - SetDictInt("ACS_LRCORNER", (ACS_LRCORNER)); - SetDictInt("ACS_LTEE", (ACS_LTEE)); - SetDictInt("ACS_RTEE", (ACS_RTEE)); - SetDictInt("ACS_BTEE", (ACS_BTEE)); - SetDictInt("ACS_TTEE", (ACS_TTEE)); - SetDictInt("ACS_HLINE", (ACS_HLINE)); - SetDictInt("ACS_VLINE", (ACS_VLINE)); - SetDictInt("ACS_PLUS", (ACS_PLUS)); + /* Here are some graphic symbols you can use */ + SetDictInt("ACS_ULCORNER", (ACS_ULCORNER)); + SetDictInt("ACS_LLCORNER", (ACS_LLCORNER)); + SetDictInt("ACS_URCORNER", (ACS_URCORNER)); + SetDictInt("ACS_LRCORNER", (ACS_LRCORNER)); + SetDictInt("ACS_LTEE", (ACS_LTEE)); + SetDictInt("ACS_RTEE", (ACS_RTEE)); + SetDictInt("ACS_BTEE", (ACS_BTEE)); + SetDictInt("ACS_TTEE", (ACS_TTEE)); + SetDictInt("ACS_HLINE", (ACS_HLINE)); + SetDictInt("ACS_VLINE", (ACS_VLINE)); + SetDictInt("ACS_PLUS", (ACS_PLUS)); #if !defined(__hpux) || defined(HAVE_NCURSES_H) - /* On HP/UX 11, these are of type cchar_t, which is not an - integral type. If this is a problem on more platforms, a - configure test should be added to determine whether ACS_S1 - is of integral type. */ - SetDictInt("ACS_S1", (ACS_S1)); - SetDictInt("ACS_S9", (ACS_S9)); - SetDictInt("ACS_DIAMOND", (ACS_DIAMOND)); - SetDictInt("ACS_CKBOARD", (ACS_CKBOARD)); - SetDictInt("ACS_DEGREE", (ACS_DEGREE)); - SetDictInt("ACS_PLMINUS", (ACS_PLMINUS)); - SetDictInt("ACS_BULLET", (ACS_BULLET)); - SetDictInt("ACS_LARROW", (ACS_LARROW)); - SetDictInt("ACS_RARROW", (ACS_RARROW)); - SetDictInt("ACS_DARROW", (ACS_DARROW)); - SetDictInt("ACS_UARROW", (ACS_UARROW)); - SetDictInt("ACS_BOARD", (ACS_BOARD)); - SetDictInt("ACS_LANTERN", (ACS_LANTERN)); - SetDictInt("ACS_BLOCK", (ACS_BLOCK)); -#endif - SetDictInt("ACS_BSSB", (ACS_ULCORNER)); - SetDictInt("ACS_SSBB", (ACS_LLCORNER)); - SetDictInt("ACS_BBSS", (ACS_URCORNER)); - SetDictInt("ACS_SBBS", (ACS_LRCORNER)); - SetDictInt("ACS_SBSS", (ACS_RTEE)); - SetDictInt("ACS_SSSB", (ACS_LTEE)); - SetDictInt("ACS_SSBS", (ACS_BTEE)); - SetDictInt("ACS_BSSS", (ACS_TTEE)); - SetDictInt("ACS_BSBS", (ACS_HLINE)); - SetDictInt("ACS_SBSB", (ACS_VLINE)); - SetDictInt("ACS_SSSS", (ACS_PLUS)); + /* On HP/UX 11, these are of type cchar_t, which is not an + integral type. If this is a problem on more platforms, a + configure test should be added to determine whether ACS_S1 + is of integral type. */ + SetDictInt("ACS_S1", (ACS_S1)); + SetDictInt("ACS_S9", (ACS_S9)); + SetDictInt("ACS_DIAMOND", (ACS_DIAMOND)); + SetDictInt("ACS_CKBOARD", (ACS_CKBOARD)); + SetDictInt("ACS_DEGREE", (ACS_DEGREE)); + SetDictInt("ACS_PLMINUS", (ACS_PLMINUS)); + SetDictInt("ACS_BULLET", (ACS_BULLET)); + SetDictInt("ACS_LARROW", (ACS_LARROW)); + SetDictInt("ACS_RARROW", (ACS_RARROW)); + SetDictInt("ACS_DARROW", (ACS_DARROW)); + SetDictInt("ACS_UARROW", (ACS_UARROW)); + SetDictInt("ACS_BOARD", (ACS_BOARD)); + SetDictInt("ACS_LANTERN", (ACS_LANTERN)); + SetDictInt("ACS_BLOCK", (ACS_BLOCK)); +#endif + SetDictInt("ACS_BSSB", (ACS_ULCORNER)); + SetDictInt("ACS_SSBB", (ACS_LLCORNER)); + SetDictInt("ACS_BBSS", (ACS_URCORNER)); + SetDictInt("ACS_SBBS", (ACS_LRCORNER)); + SetDictInt("ACS_SBSS", (ACS_RTEE)); + SetDictInt("ACS_SSSB", (ACS_LTEE)); + SetDictInt("ACS_SSBS", (ACS_BTEE)); + SetDictInt("ACS_BSSS", (ACS_TTEE)); + SetDictInt("ACS_BSBS", (ACS_HLINE)); + SetDictInt("ACS_SBSB", (ACS_VLINE)); + SetDictInt("ACS_SSSS", (ACS_PLUS)); - /* The following are never available with strict SYSV curses */ + /* The following are never available with strict SYSV curses */ #ifdef ACS_S3 - SetDictInt("ACS_S3", (ACS_S3)); + SetDictInt("ACS_S3", (ACS_S3)); #endif #ifdef ACS_S7 - SetDictInt("ACS_S7", (ACS_S7)); + SetDictInt("ACS_S7", (ACS_S7)); #endif #ifdef ACS_LEQUAL - SetDictInt("ACS_LEQUAL", (ACS_LEQUAL)); + SetDictInt("ACS_LEQUAL", (ACS_LEQUAL)); #endif #ifdef ACS_GEQUAL - SetDictInt("ACS_GEQUAL", (ACS_GEQUAL)); + SetDictInt("ACS_GEQUAL", (ACS_GEQUAL)); #endif #ifdef ACS_PI - SetDictInt("ACS_PI", (ACS_PI)); + SetDictInt("ACS_PI", (ACS_PI)); #endif #ifdef ACS_NEQUAL - SetDictInt("ACS_NEQUAL", (ACS_NEQUAL)); + SetDictInt("ACS_NEQUAL", (ACS_NEQUAL)); #endif #ifdef ACS_STERLING - SetDictInt("ACS_STERLING", (ACS_STERLING)); + SetDictInt("ACS_STERLING", (ACS_STERLING)); #endif - SetDictInt("LINES", LINES); - SetDictInt("COLS", COLS); + SetDictInt("LINES", LINES); + SetDictInt("COLS", COLS); - return (PyObject *)PyCursesWindow_New(win); + return (PyObject *)PyCursesWindow_New(win); } static PyObject * PyCurses_setupterm(PyObject* self, PyObject *args, PyObject* keywds) { - int fd = -1; - int err; - char* termstr = NULL; - - static char *kwlist[] = {"term", "fd", NULL}; - - if (!PyArg_ParseTupleAndKeywords( - args, keywds, "|zi:setupterm", kwlist, &termstr, &fd)) { - return NULL; - } - - if (fd == -1) { - PyObject* sys_stdout; - - sys_stdout = PySys_GetObject("stdout"); - - if (sys_stdout == NULL) { - PyErr_SetString( - PyCursesError, - "lost sys.stdout"); - return NULL; - } - - fd = PyObject_AsFileDescriptor(sys_stdout); - - if (fd == -1) { - return NULL; - } - } - - if (setupterm(termstr,fd,&err) == ERR) { - char* s = "setupterm: unknown error"; - - if (err == 0) { - s = "setupterm: could not find terminal"; - } else if (err == -1) { - s = "setupterm: could not find terminfo database"; - } - - PyErr_SetString(PyCursesError,s); - return NULL; - } + int fd = -1; + int err; + char* termstr = NULL; - initialised_setupterm = TRUE; + static char *kwlist[] = {"term", "fd", NULL}; + + if (!PyArg_ParseTupleAndKeywords( + args, keywds, "|zi:setupterm", kwlist, &termstr, &fd)) { + return NULL; + } - Py_INCREF(Py_None); - return Py_None; + if (fd == -1) { + PyObject* sys_stdout; + + sys_stdout = PySys_GetObject("stdout"); + + if (sys_stdout == NULL) { + PyErr_SetString( + PyCursesError, + "lost sys.stdout"); + return NULL; + } + + fd = PyObject_AsFileDescriptor(sys_stdout); + + if (fd == -1) { + return NULL; + } + } + + if (setupterm(termstr,fd,&err) == ERR) { + char* s = "setupterm: unknown error"; + + if (err == 0) { + s = "setupterm: could not find terminal"; + } else if (err == -1) { + s = "setupterm: could not find terminfo database"; + } + + PyErr_SetString(PyCursesError,s); + return NULL; + } + + initialised_setupterm = TRUE; + + Py_INCREF(Py_None); + return Py_None; } static PyObject * PyCurses_IntrFlush(PyObject *self, PyObject *args) { - int ch; + int ch; - PyCursesInitialised; + PyCursesInitialised; - switch(PyTuple_Size(args)) { - case 1: - if (!PyArg_ParseTuple(args,"i;True(1), False(0)",&ch)) return NULL; - break; - default: - PyErr_SetString(PyExc_TypeError, "intrflush requires 1 argument"); - return NULL; - } + switch(PyTuple_Size(args)) { + case 1: + if (!PyArg_ParseTuple(args,"i;True(1), False(0)",&ch)) return NULL; + break; + default: + PyErr_SetString(PyExc_TypeError, "intrflush requires 1 argument"); + return NULL; + } - return PyCursesCheckERR(intrflush(NULL,ch), "intrflush"); + return PyCursesCheckERR(intrflush(NULL,ch), "intrflush"); } #ifdef HAVE_CURSES_IS_TERM_RESIZED static PyObject * PyCurses_Is_Term_Resized(PyObject *self, PyObject *args) { - int lines; - int columns; - int result; - - PyCursesInitialised; - - if (!PyArg_ParseTuple(args,"ii:is_term_resized", &lines, &columns)) - return NULL; - result = is_term_resized(lines, columns); - if (result == TRUE) { - Py_INCREF(Py_True); - return Py_True; - } else { - Py_INCREF(Py_False); - return Py_False; - } + int lines; + int columns; + int result; + + PyCursesInitialised; + + if (!PyArg_ParseTuple(args,"ii:is_term_resized", &lines, &columns)) + return NULL; + result = is_term_resized(lines, columns); + if (result == TRUE) { + Py_INCREF(Py_True); + return Py_True; + } else { + Py_INCREF(Py_False); + return Py_False; + } } #endif /* HAVE_CURSES_IS_TERM_RESIZED */ @@ -2112,75 +2112,75 @@ static PyObject * PyCurses_KeyName(PyObject *self, PyObject *args) { - const char *knp; - int ch; + const char *knp; + int ch; - PyCursesInitialised; + PyCursesInitialised; - if (!PyArg_ParseTuple(args,"i",&ch)) return NULL; + if (!PyArg_ParseTuple(args,"i",&ch)) return NULL; - if (ch < 0) { - PyErr_SetString(PyExc_ValueError, "invalid key number"); - return NULL; - } - knp = keyname(ch); + if (ch < 0) { + PyErr_SetString(PyExc_ValueError, "invalid key number"); + return NULL; + } + knp = keyname(ch); - return PyString_FromString((knp == NULL) ? "" : (char *)knp); + return PyString_FromString((knp == NULL) ? "" : (char *)knp); } #endif -static PyObject * -PyCurses_KillChar(PyObject *self) -{ - char ch; +static PyObject * +PyCurses_KillChar(PyObject *self) +{ + char ch; - ch = killchar(); + ch = killchar(); - return PyString_FromStringAndSize(&ch, 1); -} + return PyString_FromStringAndSize(&ch, 1); +} static PyObject * PyCurses_Meta(PyObject *self, PyObject *args) { - int ch; + int ch; - PyCursesInitialised; + PyCursesInitialised; - switch(PyTuple_Size(args)) { - case 1: - if (!PyArg_ParseTuple(args,"i;True(1), False(0)",&ch)) return NULL; - break; - default: - PyErr_SetString(PyExc_TypeError, "meta requires 1 argument"); - return NULL; - } + switch(PyTuple_Size(args)) { + case 1: + if (!PyArg_ParseTuple(args,"i;True(1), False(0)",&ch)) return NULL; + break; + default: + PyErr_SetString(PyExc_TypeError, "meta requires 1 argument"); + return NULL; + } - return PyCursesCheckERR(meta(stdscr, ch), "meta"); + return PyCursesCheckERR(meta(stdscr, ch), "meta"); } #ifdef NCURSES_MOUSE_VERSION static PyObject * PyCurses_MouseInterval(PyObject *self, PyObject *args) { - int interval; - PyCursesInitialised; + int interval; + PyCursesInitialised; - if (!PyArg_ParseTuple(args,"i;interval",&interval)) - return NULL; - return PyCursesCheckERR(mouseinterval(interval), "mouseinterval"); + if (!PyArg_ParseTuple(args,"i;interval",&interval)) + return NULL; + return PyCursesCheckERR(mouseinterval(interval), "mouseinterval"); } static PyObject * PyCurses_MouseMask(PyObject *self, PyObject *args) { - int newmask; - mmask_t oldmask, availmask; + int newmask; + mmask_t oldmask, availmask; - PyCursesInitialised; - if (!PyArg_ParseTuple(args,"i;mousemask",&newmask)) - return NULL; - availmask = mousemask(newmask, &oldmask); - return Py_BuildValue("(ll)", (long)availmask, (long)oldmask); + PyCursesInitialised; + if (!PyArg_ParseTuple(args,"i;mousemask",&newmask)) + return NULL; + availmask = mousemask(newmask, &oldmask); + return Py_BuildValue("(ll)", (long)availmask, (long)oldmask); } #endif @@ -2199,133 +2199,133 @@ static PyObject * PyCurses_NewPad(PyObject *self, PyObject *args) { - WINDOW *win; - int nlines, ncols; + WINDOW *win; + int nlines, ncols; - PyCursesInitialised; + PyCursesInitialised; - if (!PyArg_ParseTuple(args,"ii;nlines,ncols",&nlines,&ncols)) return NULL; + if (!PyArg_ParseTuple(args,"ii;nlines,ncols",&nlines,&ncols)) return NULL; - win = newpad(nlines, ncols); - - if (win == NULL) { - PyErr_SetString(PyCursesError, catchall_NULL); - return NULL; - } + win = newpad(nlines, ncols); - return (PyObject *)PyCursesWindow_New(win); + if (win == NULL) { + PyErr_SetString(PyCursesError, catchall_NULL); + return NULL; + } + + return (PyObject *)PyCursesWindow_New(win); } static PyObject * PyCurses_NewWindow(PyObject *self, PyObject *args) { - WINDOW *win; - int nlines, ncols, begin_y=0, begin_x=0; + WINDOW *win; + int nlines, ncols, begin_y=0, begin_x=0; - PyCursesInitialised; + PyCursesInitialised; + + switch (PyTuple_Size(args)) { + case 2: + if (!PyArg_ParseTuple(args,"ii;nlines,ncols",&nlines,&ncols)) + return NULL; + break; + case 4: + if (!PyArg_ParseTuple(args, "iiii;nlines,ncols,begin_y,begin_x", + &nlines,&ncols,&begin_y,&begin_x)) + return NULL; + break; + default: + PyErr_SetString(PyExc_TypeError, "newwin requires 2 or 4 arguments"); + return NULL; + } - switch (PyTuple_Size(args)) { - case 2: - if (!PyArg_ParseTuple(args,"ii;nlines,ncols",&nlines,&ncols)) - return NULL; - break; - case 4: - if (!PyArg_ParseTuple(args, "iiii;nlines,ncols,begin_y,begin_x", - &nlines,&ncols,&begin_y,&begin_x)) - return NULL; - break; - default: - PyErr_SetString(PyExc_TypeError, "newwin requires 2 or 4 arguments"); - return NULL; - } - - win = newwin(nlines,ncols,begin_y,begin_x); - if (win == NULL) { - PyErr_SetString(PyCursesError, catchall_NULL); - return NULL; - } + win = newwin(nlines,ncols,begin_y,begin_x); + if (win == NULL) { + PyErr_SetString(PyCursesError, catchall_NULL); + return NULL; + } - return (PyObject *)PyCursesWindow_New(win); + return (PyObject *)PyCursesWindow_New(win); } static PyObject * PyCurses_Pair_Content(PyObject *self, PyObject *args) { - short pair,f,b; + short pair,f,b; - PyCursesInitialised; - PyCursesInitialisedColor; + PyCursesInitialised; + PyCursesInitialisedColor; - switch(PyTuple_Size(args)) { - case 1: - if (!PyArg_ParseTuple(args, "h;pair", &pair)) return NULL; - break; - default: - PyErr_SetString(PyExc_TypeError, "pair_content requires 1 argument"); - return NULL; - } - - if (pair_content(pair, &f, &b)==ERR) { - PyErr_SetString(PyCursesError, - "Argument 1 was out of range. (1..COLOR_PAIRS-1)"); - return NULL; - } + switch(PyTuple_Size(args)) { + case 1: + if (!PyArg_ParseTuple(args, "h;pair", &pair)) return NULL; + break; + default: + PyErr_SetString(PyExc_TypeError, "pair_content requires 1 argument"); + return NULL; + } + + if (pair_content(pair, &f, &b)==ERR) { + PyErr_SetString(PyCursesError, + "Argument 1 was out of range. (1..COLOR_PAIRS-1)"); + return NULL; + } - return Py_BuildValue("(ii)", f, b); + return Py_BuildValue("(ii)", f, b); } static PyObject * PyCurses_pair_number(PyObject *self, PyObject *args) { - int n; + int n; - PyCursesInitialised; - PyCursesInitialisedColor; + PyCursesInitialised; + PyCursesInitialisedColor; - switch(PyTuple_Size(args)) { - case 1: - if (!PyArg_ParseTuple(args, "i;pairvalue", &n)) return NULL; - break; - default: - PyErr_SetString(PyExc_TypeError, - "pair_number requires 1 argument"); - return NULL; - } + switch(PyTuple_Size(args)) { + case 1: + if (!PyArg_ParseTuple(args, "i;pairvalue", &n)) return NULL; + break; + default: + PyErr_SetString(PyExc_TypeError, + "pair_number requires 1 argument"); + return NULL; + } - return PyInt_FromLong((long) ((n & A_COLOR) >> 8)); + return PyInt_FromLong((long) ((n & A_COLOR) >> 8)); } static PyObject * PyCurses_Putp(PyObject *self, PyObject *args) { - char *str; + char *str; - if (!PyArg_ParseTuple(args,"s;str", &str)) return NULL; - return PyCursesCheckERR(putp(str), "putp"); + if (!PyArg_ParseTuple(args,"s;str", &str)) return NULL; + return PyCursesCheckERR(putp(str), "putp"); } static PyObject * PyCurses_QiFlush(PyObject *self, PyObject *args) { - int flag = 0; + int flag = 0; - PyCursesInitialised; + PyCursesInitialised; - switch(PyTuple_Size(args)) { - case 0: - qiflush(); - Py_INCREF(Py_None); - return Py_None; - case 1: - if (!PyArg_ParseTuple(args, "i;True(1) or False(0)", &flag)) return NULL; - if (flag) qiflush(); - else noqiflush(); - Py_INCREF(Py_None); - return Py_None; - default: - PyErr_SetString(PyExc_TypeError, "qiflush requires 0 or 1 arguments"); - return NULL; - } + switch(PyTuple_Size(args)) { + case 0: + qiflush(); + Py_INCREF(Py_None); + return Py_None; + case 1: + if (!PyArg_ParseTuple(args, "i;True(1) or False(0)", &flag)) return NULL; + if (flag) qiflush(); + else noqiflush(); + Py_INCREF(Py_None); + return Py_None; + default: + PyErr_SetString(PyExc_TypeError, "qiflush requires 0 or 1 arguments"); + return NULL; + } } /* Internal helper used for updating curses.LINES, curses.COLS, _curses.LINES @@ -2334,46 +2334,46 @@ static int update_lines_cols(void) { - PyObject *o; - PyObject *m = PyImport_ImportModuleNoBlock("curses"); + PyObject *o; + PyObject *m = PyImport_ImportModuleNoBlock("curses"); - if (!m) - return 0; + if (!m) + return 0; - o = PyInt_FromLong(LINES); - if (!o) { - Py_DECREF(m); - return 0; - } - if (PyObject_SetAttrString(m, "LINES", o)) { - Py_DECREF(m); - Py_DECREF(o); - return 0; - } - if (PyDict_SetItemString(ModDict, "LINES", o)) { - Py_DECREF(m); + o = PyInt_FromLong(LINES); + if (!o) { + Py_DECREF(m); + return 0; + } + if (PyObject_SetAttrString(m, "LINES", o)) { + Py_DECREF(m); + Py_DECREF(o); + return 0; + } + if (PyDict_SetItemString(ModDict, "LINES", o)) { + Py_DECREF(m); + Py_DECREF(o); + return 0; + } Py_DECREF(o); - return 0; - } - Py_DECREF(o); - o = PyInt_FromLong(COLS); - if (!o) { - Py_DECREF(m); - return 0; - } - if (PyObject_SetAttrString(m, "COLS", o)) { - Py_DECREF(m); + o = PyInt_FromLong(COLS); + if (!o) { + Py_DECREF(m); + return 0; + } + if (PyObject_SetAttrString(m, "COLS", o)) { + Py_DECREF(m); + Py_DECREF(o); + return 0; + } + if (PyDict_SetItemString(ModDict, "COLS", o)) { + Py_DECREF(m); + Py_DECREF(o); + return 0; + } Py_DECREF(o); - return 0; - } - if (PyDict_SetItemString(ModDict, "COLS", o)) { Py_DECREF(m); - Py_DECREF(o); - return 0; - } - Py_DECREF(o); - Py_DECREF(m); - return 1; + return 1; } #endif @@ -2381,21 +2381,21 @@ static PyObject * PyCurses_ResizeTerm(PyObject *self, PyObject *args) { - int lines; - int columns; - PyObject *result; - - PyCursesInitialised; - - if (!PyArg_ParseTuple(args,"ii:resizeterm", &lines, &columns)) - return NULL; - - result = PyCursesCheckERR(resizeterm(lines, columns), "resizeterm"); - if (!result) - return NULL; - if (!update_lines_cols()) - return NULL; - return result; + int lines; + int columns; + PyObject *result; + + PyCursesInitialised; + + if (!PyArg_ParseTuple(args,"ii:resizeterm", &lines, &columns)) + return NULL; + + result = PyCursesCheckERR(resizeterm(lines, columns), "resizeterm"); + if (!result) + return NULL; + if (!update_lines_cols()) + return NULL; + return result; } #endif @@ -2404,326 +2404,326 @@ static PyObject * PyCurses_Resize_Term(PyObject *self, PyObject *args) { - int lines; - int columns; + int lines; + int columns; - PyObject *result; + PyObject *result; - PyCursesInitialised; + PyCursesInitialised; - if (!PyArg_ParseTuple(args,"ii:resize_term", &lines, &columns)) - return NULL; - - result = PyCursesCheckERR(resize_term(lines, columns), "resize_term"); - if (!result) - return NULL; - if (!update_lines_cols()) - return NULL; - return result; + if (!PyArg_ParseTuple(args,"ii:resize_term", &lines, &columns)) + return NULL; + + result = PyCursesCheckERR(resize_term(lines, columns), "resize_term"); + if (!result) + return NULL; + if (!update_lines_cols()) + return NULL; + return result; } #endif /* HAVE_CURSES_RESIZE_TERM */ static PyObject * PyCurses_setsyx(PyObject *self, PyObject *args) { - int y,x; + int y,x; - PyCursesInitialised; + PyCursesInitialised; - if (PyTuple_Size(args)!=2) { - PyErr_SetString(PyExc_TypeError, "setsyx requires 2 arguments"); - return NULL; - } + if (PyTuple_Size(args)!=2) { + PyErr_SetString(PyExc_TypeError, "setsyx requires 2 arguments"); + return NULL; + } - if (!PyArg_ParseTuple(args, "ii;y, x", &y, &x)) return NULL; + if (!PyArg_ParseTuple(args, "ii;y, x", &y, &x)) return NULL; - setsyx(y,x); + setsyx(y,x); - Py_INCREF(Py_None); - return Py_None; + Py_INCREF(Py_None); + return Py_None; } static PyObject * PyCurses_Start_Color(PyObject *self) { - int code; - PyObject *c, *cp; + int code; + PyObject *c, *cp; - PyCursesInitialised; + PyCursesInitialised; - code = start_color(); - if (code != ERR) { - initialisedcolors = TRUE; - c = PyInt_FromLong((long) COLORS); - PyDict_SetItemString(ModDict, "COLORS", c); - Py_DECREF(c); - cp = PyInt_FromLong((long) COLOR_PAIRS); - PyDict_SetItemString(ModDict, "COLOR_PAIRS", cp); - Py_DECREF(cp); - Py_INCREF(Py_None); - return Py_None; - } else { - PyErr_SetString(PyCursesError, "start_color() returned ERR"); - return NULL; - } + code = start_color(); + if (code != ERR) { + initialisedcolors = TRUE; + c = PyInt_FromLong((long) COLORS); + PyDict_SetItemString(ModDict, "COLORS", c); + Py_DECREF(c); + cp = PyInt_FromLong((long) COLOR_PAIRS); + PyDict_SetItemString(ModDict, "COLOR_PAIRS", cp); + Py_DECREF(cp); + Py_INCREF(Py_None); + return Py_None; + } else { + PyErr_SetString(PyCursesError, "start_color() returned ERR"); + return NULL; + } } static PyObject * PyCurses_tigetflag(PyObject *self, PyObject *args) { - char *capname; + char *capname; - PyCursesSetupTermCalled; - - if (!PyArg_ParseTuple(args, "s", &capname)) - return NULL; + PyCursesSetupTermCalled; - return PyInt_FromLong( (long) tigetflag( capname ) ); + if (!PyArg_ParseTuple(args, "s", &capname)) + return NULL; + + return PyInt_FromLong( (long) tigetflag( capname ) ); } static PyObject * PyCurses_tigetnum(PyObject *self, PyObject *args) { - char *capname; + char *capname; - PyCursesSetupTermCalled; - - if (!PyArg_ParseTuple(args, "s", &capname)) - return NULL; + PyCursesSetupTermCalled; - return PyInt_FromLong( (long) tigetnum( capname ) ); + if (!PyArg_ParseTuple(args, "s", &capname)) + return NULL; + + return PyInt_FromLong( (long) tigetnum( capname ) ); } static PyObject * PyCurses_tigetstr(PyObject *self, PyObject *args) { - char *capname; + char *capname; + + PyCursesSetupTermCalled; - PyCursesSetupTermCalled; - - if (!PyArg_ParseTuple(args, "s", &capname)) - return NULL; - - capname = tigetstr( capname ); - if (capname == 0 || capname == (char*) -1) { - Py_INCREF(Py_None); - return Py_None; - } - return PyString_FromString( capname ); + if (!PyArg_ParseTuple(args, "s", &capname)) + return NULL; + + capname = tigetstr( capname ); + if (capname == 0 || capname == (char*) -1) { + Py_INCREF(Py_None); + return Py_None; + } + return PyString_FromString( capname ); } static PyObject * PyCurses_tparm(PyObject *self, PyObject *args) { - char* fmt; - char* result = NULL; - int i1=0,i2=0,i3=0,i4=0,i5=0,i6=0,i7=0,i8=0,i9=0; - - PyCursesSetupTermCalled; - - if (!PyArg_ParseTuple(args, "s|iiiiiiiii:tparm", - &fmt, &i1, &i2, &i3, &i4, - &i5, &i6, &i7, &i8, &i9)) { - return NULL; - } - - result = tparm(fmt,i1,i2,i3,i4,i5,i6,i7,i8,i9); - if (!result) { - PyErr_SetString(PyCursesError, "tparm() returned NULL"); - return NULL; - } + char* fmt; + char* result = NULL; + int i1=0,i2=0,i3=0,i4=0,i5=0,i6=0,i7=0,i8=0,i9=0; + + PyCursesSetupTermCalled; + + if (!PyArg_ParseTuple(args, "s|iiiiiiiii:tparm", + &fmt, &i1, &i2, &i3, &i4, + &i5, &i6, &i7, &i8, &i9)) { + return NULL; + } + + result = tparm(fmt,i1,i2,i3,i4,i5,i6,i7,i8,i9); + if (!result) { + PyErr_SetString(PyCursesError, "tparm() returned NULL"); + return NULL; + } - return PyString_FromString(result); + return PyString_FromString(result); } static PyObject * PyCurses_TypeAhead(PyObject *self, PyObject *args) { - int fd; + int fd; - PyCursesInitialised; + PyCursesInitialised; - if (!PyArg_ParseTuple(args,"i;fd",&fd)) return NULL; + if (!PyArg_ParseTuple(args,"i;fd",&fd)) return NULL; - return PyCursesCheckERR(typeahead( fd ), "typeahead"); + return PyCursesCheckERR(typeahead( fd ), "typeahead"); } static PyObject * PyCurses_UnCtrl(PyObject *self, PyObject *args) { - PyObject *temp; - chtype ch; + PyObject *temp; + chtype ch; - PyCursesInitialised; + PyCursesInitialised; - if (!PyArg_ParseTuple(args,"O;ch or int",&temp)) return NULL; + if (!PyArg_ParseTuple(args,"O;ch or int",&temp)) return NULL; - if (PyInt_Check(temp)) - ch = (chtype) PyInt_AsLong(temp); - else if (PyString_Check(temp)) - ch = (chtype) *PyString_AsString(temp); - else { - PyErr_SetString(PyExc_TypeError, "argument must be a ch or an int"); - return NULL; - } + if (PyInt_Check(temp)) + ch = (chtype) PyInt_AsLong(temp); + else if (PyString_Check(temp)) + ch = (chtype) *PyString_AsString(temp); + else { + PyErr_SetString(PyExc_TypeError, "argument must be a ch or an int"); + return NULL; + } - return PyString_FromString(unctrl(ch)); + return PyString_FromString(unctrl(ch)); } static PyObject * PyCurses_UngetCh(PyObject *self, PyObject *args) { - PyObject *temp; - int ch; + PyObject *temp; + int ch; - PyCursesInitialised; + PyCursesInitialised; - if (!PyArg_ParseTuple(args,"O;ch or int",&temp)) return NULL; + if (!PyArg_ParseTuple(args,"O;ch or int",&temp)) return NULL; - if (PyInt_Check(temp)) - ch = (int) PyInt_AsLong(temp); - else if (PyString_Check(temp)) - ch = (int) *PyString_AsString(temp); - else { - PyErr_SetString(PyExc_TypeError, "argument must be a ch or an int"); - return NULL; - } + if (PyInt_Check(temp)) + ch = (int) PyInt_AsLong(temp); + else if (PyString_Check(temp)) + ch = (int) *PyString_AsString(temp); + else { + PyErr_SetString(PyExc_TypeError, "argument must be a ch or an int"); + return NULL; + } - return PyCursesCheckERR(ungetch(ch), "ungetch"); + return PyCursesCheckERR(ungetch(ch), "ungetch"); } static PyObject * PyCurses_Use_Env(PyObject *self, PyObject *args) { - int flag; + int flag; - switch(PyTuple_Size(args)) { - case 1: - if (!PyArg_ParseTuple(args,"i;True(1), False(0)",&flag)) - return NULL; - break; - default: - PyErr_SetString(PyExc_TypeError, "use_env requires 1 argument"); - return NULL; - } - use_env(flag); - Py_INCREF(Py_None); - return Py_None; + switch(PyTuple_Size(args)) { + case 1: + if (!PyArg_ParseTuple(args,"i;True(1), False(0)",&flag)) + return NULL; + break; + default: + PyErr_SetString(PyExc_TypeError, "use_env requires 1 argument"); + return NULL; + } + use_env(flag); + Py_INCREF(Py_None); + return Py_None; } #ifndef STRICT_SYSV_CURSES static PyObject * PyCurses_Use_Default_Colors(PyObject *self) { - int code; + int code; - PyCursesInitialised; - PyCursesInitialisedColor; + PyCursesInitialised; + PyCursesInitialisedColor; - code = use_default_colors(); - if (code != ERR) { - Py_INCREF(Py_None); - return Py_None; - } else { - PyErr_SetString(PyCursesError, "use_default_colors() returned ERR"); - return NULL; - } + code = use_default_colors(); + if (code != ERR) { + Py_INCREF(Py_None); + return Py_None; + } else { + PyErr_SetString(PyCursesError, "use_default_colors() returned ERR"); + return NULL; + } } #endif /* STRICT_SYSV_CURSES */ /* List of functions defined in the module */ static PyMethodDef PyCurses_methods[] = { - {"baudrate", (PyCFunction)PyCurses_baudrate, METH_NOARGS}, - {"beep", (PyCFunction)PyCurses_beep, METH_NOARGS}, - {"can_change_color", (PyCFunction)PyCurses_can_change_color, METH_NOARGS}, - {"cbreak", (PyCFunction)PyCurses_cbreak, METH_VARARGS}, - {"color_content", (PyCFunction)PyCurses_Color_Content, METH_VARARGS}, - {"color_pair", (PyCFunction)PyCurses_color_pair, METH_VARARGS}, - {"curs_set", (PyCFunction)PyCurses_Curs_Set, METH_VARARGS}, - {"def_prog_mode", (PyCFunction)PyCurses_def_prog_mode, METH_NOARGS}, - {"def_shell_mode", (PyCFunction)PyCurses_def_shell_mode, METH_NOARGS}, - {"delay_output", (PyCFunction)PyCurses_Delay_Output, METH_VARARGS}, - {"doupdate", (PyCFunction)PyCurses_doupdate, METH_NOARGS}, - {"echo", (PyCFunction)PyCurses_echo, METH_VARARGS}, - {"endwin", (PyCFunction)PyCurses_endwin, METH_NOARGS}, - {"erasechar", (PyCFunction)PyCurses_EraseChar, METH_NOARGS}, - {"filter", (PyCFunction)PyCurses_filter, METH_NOARGS}, - {"flash", (PyCFunction)PyCurses_flash, METH_NOARGS}, - {"flushinp", (PyCFunction)PyCurses_flushinp, METH_NOARGS}, + {"baudrate", (PyCFunction)PyCurses_baudrate, METH_NOARGS}, + {"beep", (PyCFunction)PyCurses_beep, METH_NOARGS}, + {"can_change_color", (PyCFunction)PyCurses_can_change_color, METH_NOARGS}, + {"cbreak", (PyCFunction)PyCurses_cbreak, METH_VARARGS}, + {"color_content", (PyCFunction)PyCurses_Color_Content, METH_VARARGS}, + {"color_pair", (PyCFunction)PyCurses_color_pair, METH_VARARGS}, + {"curs_set", (PyCFunction)PyCurses_Curs_Set, METH_VARARGS}, + {"def_prog_mode", (PyCFunction)PyCurses_def_prog_mode, METH_NOARGS}, + {"def_shell_mode", (PyCFunction)PyCurses_def_shell_mode, METH_NOARGS}, + {"delay_output", (PyCFunction)PyCurses_Delay_Output, METH_VARARGS}, + {"doupdate", (PyCFunction)PyCurses_doupdate, METH_NOARGS}, + {"echo", (PyCFunction)PyCurses_echo, METH_VARARGS}, + {"endwin", (PyCFunction)PyCurses_endwin, METH_NOARGS}, + {"erasechar", (PyCFunction)PyCurses_EraseChar, METH_NOARGS}, + {"filter", (PyCFunction)PyCurses_filter, METH_NOARGS}, + {"flash", (PyCFunction)PyCurses_flash, METH_NOARGS}, + {"flushinp", (PyCFunction)PyCurses_flushinp, METH_NOARGS}, #ifdef NCURSES_MOUSE_VERSION - {"getmouse", (PyCFunction)PyCurses_GetMouse, METH_NOARGS}, - {"ungetmouse", (PyCFunction)PyCurses_UngetMouse, METH_VARARGS}, + {"getmouse", (PyCFunction)PyCurses_GetMouse, METH_NOARGS}, + {"ungetmouse", (PyCFunction)PyCurses_UngetMouse, METH_VARARGS}, #endif - {"getsyx", (PyCFunction)PyCurses_getsyx, METH_NOARGS}, - {"getwin", (PyCFunction)PyCurses_GetWin, METH_O}, - {"has_colors", (PyCFunction)PyCurses_has_colors, METH_NOARGS}, - {"has_ic", (PyCFunction)PyCurses_has_ic, METH_NOARGS}, - {"has_il", (PyCFunction)PyCurses_has_il, METH_NOARGS}, + {"getsyx", (PyCFunction)PyCurses_getsyx, METH_NOARGS}, + {"getwin", (PyCFunction)PyCurses_GetWin, METH_O}, + {"has_colors", (PyCFunction)PyCurses_has_colors, METH_NOARGS}, + {"has_ic", (PyCFunction)PyCurses_has_ic, METH_NOARGS}, + {"has_il", (PyCFunction)PyCurses_has_il, METH_NOARGS}, #ifndef STRICT_SYSV_CURSES - {"has_key", (PyCFunction)PyCurses_has_key, METH_VARARGS}, + {"has_key", (PyCFunction)PyCurses_has_key, METH_VARARGS}, #endif - {"halfdelay", (PyCFunction)PyCurses_HalfDelay, METH_VARARGS}, - {"init_color", (PyCFunction)PyCurses_Init_Color, METH_VARARGS}, - {"init_pair", (PyCFunction)PyCurses_Init_Pair, METH_VARARGS}, - {"initscr", (PyCFunction)PyCurses_InitScr, METH_NOARGS}, - {"intrflush", (PyCFunction)PyCurses_IntrFlush, METH_VARARGS}, - {"isendwin", (PyCFunction)PyCurses_isendwin, METH_NOARGS}, + {"halfdelay", (PyCFunction)PyCurses_HalfDelay, METH_VARARGS}, + {"init_color", (PyCFunction)PyCurses_Init_Color, METH_VARARGS}, + {"init_pair", (PyCFunction)PyCurses_Init_Pair, METH_VARARGS}, + {"initscr", (PyCFunction)PyCurses_InitScr, METH_NOARGS}, + {"intrflush", (PyCFunction)PyCurses_IntrFlush, METH_VARARGS}, + {"isendwin", (PyCFunction)PyCurses_isendwin, METH_NOARGS}, #ifdef HAVE_CURSES_IS_TERM_RESIZED - {"is_term_resized", (PyCFunction)PyCurses_Is_Term_Resized, METH_VARARGS}, + {"is_term_resized", (PyCFunction)PyCurses_Is_Term_Resized, METH_VARARGS}, #endif #if !defined(__NetBSD__) - {"keyname", (PyCFunction)PyCurses_KeyName, METH_VARARGS}, + {"keyname", (PyCFunction)PyCurses_KeyName, METH_VARARGS}, #endif - {"killchar", (PyCFunction)PyCurses_KillChar, METH_NOARGS}, - {"longname", (PyCFunction)PyCurses_longname, METH_NOARGS}, - {"meta", (PyCFunction)PyCurses_Meta, METH_VARARGS}, + {"killchar", (PyCFunction)PyCurses_KillChar, METH_NOARGS}, + {"longname", (PyCFunction)PyCurses_longname, METH_NOARGS}, + {"meta", (PyCFunction)PyCurses_Meta, METH_VARARGS}, #ifdef NCURSES_MOUSE_VERSION - {"mouseinterval", (PyCFunction)PyCurses_MouseInterval, METH_VARARGS}, - {"mousemask", (PyCFunction)PyCurses_MouseMask, METH_VARARGS}, + {"mouseinterval", (PyCFunction)PyCurses_MouseInterval, METH_VARARGS}, + {"mousemask", (PyCFunction)PyCurses_MouseMask, METH_VARARGS}, #endif - {"napms", (PyCFunction)PyCurses_Napms, METH_VARARGS}, - {"newpad", (PyCFunction)PyCurses_NewPad, METH_VARARGS}, - {"newwin", (PyCFunction)PyCurses_NewWindow, METH_VARARGS}, - {"nl", (PyCFunction)PyCurses_nl, METH_VARARGS}, - {"nocbreak", (PyCFunction)PyCurses_nocbreak, METH_NOARGS}, - {"noecho", (PyCFunction)PyCurses_noecho, METH_NOARGS}, - {"nonl", (PyCFunction)PyCurses_nonl, METH_NOARGS}, - {"noqiflush", (PyCFunction)PyCurses_noqiflush, METH_NOARGS}, - {"noraw", (PyCFunction)PyCurses_noraw, METH_NOARGS}, - {"pair_content", (PyCFunction)PyCurses_Pair_Content, METH_VARARGS}, - {"pair_number", (PyCFunction)PyCurses_pair_number, METH_VARARGS}, - {"putp", (PyCFunction)PyCurses_Putp, METH_VARARGS}, - {"qiflush", (PyCFunction)PyCurses_QiFlush, METH_VARARGS}, - {"raw", (PyCFunction)PyCurses_raw, METH_VARARGS}, - {"reset_prog_mode", (PyCFunction)PyCurses_reset_prog_mode, METH_NOARGS}, - {"reset_shell_mode", (PyCFunction)PyCurses_reset_shell_mode, METH_NOARGS}, - {"resetty", (PyCFunction)PyCurses_resetty, METH_NOARGS}, + {"napms", (PyCFunction)PyCurses_Napms, METH_VARARGS}, + {"newpad", (PyCFunction)PyCurses_NewPad, METH_VARARGS}, + {"newwin", (PyCFunction)PyCurses_NewWindow, METH_VARARGS}, + {"nl", (PyCFunction)PyCurses_nl, METH_VARARGS}, + {"nocbreak", (PyCFunction)PyCurses_nocbreak, METH_NOARGS}, + {"noecho", (PyCFunction)PyCurses_noecho, METH_NOARGS}, + {"nonl", (PyCFunction)PyCurses_nonl, METH_NOARGS}, + {"noqiflush", (PyCFunction)PyCurses_noqiflush, METH_NOARGS}, + {"noraw", (PyCFunction)PyCurses_noraw, METH_NOARGS}, + {"pair_content", (PyCFunction)PyCurses_Pair_Content, METH_VARARGS}, + {"pair_number", (PyCFunction)PyCurses_pair_number, METH_VARARGS}, + {"putp", (PyCFunction)PyCurses_Putp, METH_VARARGS}, + {"qiflush", (PyCFunction)PyCurses_QiFlush, METH_VARARGS}, + {"raw", (PyCFunction)PyCurses_raw, METH_VARARGS}, + {"reset_prog_mode", (PyCFunction)PyCurses_reset_prog_mode, METH_NOARGS}, + {"reset_shell_mode", (PyCFunction)PyCurses_reset_shell_mode, METH_NOARGS}, + {"resetty", (PyCFunction)PyCurses_resetty, METH_NOARGS}, #ifdef HAVE_CURSES_RESIZETERM - {"resizeterm", (PyCFunction)PyCurses_ResizeTerm, METH_VARARGS}, + {"resizeterm", (PyCFunction)PyCurses_ResizeTerm, METH_VARARGS}, #endif #ifdef HAVE_CURSES_RESIZE_TERM - {"resize_term", (PyCFunction)PyCurses_Resize_Term, METH_VARARGS}, + {"resize_term", (PyCFunction)PyCurses_Resize_Term, METH_VARARGS}, #endif - {"savetty", (PyCFunction)PyCurses_savetty, METH_NOARGS}, - {"setsyx", (PyCFunction)PyCurses_setsyx, METH_VARARGS}, - {"setupterm", (PyCFunction)PyCurses_setupterm, - METH_VARARGS|METH_KEYWORDS}, - {"start_color", (PyCFunction)PyCurses_Start_Color, METH_NOARGS}, - {"termattrs", (PyCFunction)PyCurses_termattrs, METH_NOARGS}, - {"termname", (PyCFunction)PyCurses_termname, METH_NOARGS}, - {"tigetflag", (PyCFunction)PyCurses_tigetflag, METH_VARARGS}, - {"tigetnum", (PyCFunction)PyCurses_tigetnum, METH_VARARGS}, - {"tigetstr", (PyCFunction)PyCurses_tigetstr, METH_VARARGS}, - {"tparm", (PyCFunction)PyCurses_tparm, METH_VARARGS}, - {"typeahead", (PyCFunction)PyCurses_TypeAhead, METH_VARARGS}, - {"unctrl", (PyCFunction)PyCurses_UnCtrl, METH_VARARGS}, - {"ungetch", (PyCFunction)PyCurses_UngetCh, METH_VARARGS}, - {"use_env", (PyCFunction)PyCurses_Use_Env, METH_VARARGS}, + {"savetty", (PyCFunction)PyCurses_savetty, METH_NOARGS}, + {"setsyx", (PyCFunction)PyCurses_setsyx, METH_VARARGS}, + {"setupterm", (PyCFunction)PyCurses_setupterm, + METH_VARARGS|METH_KEYWORDS}, + {"start_color", (PyCFunction)PyCurses_Start_Color, METH_NOARGS}, + {"termattrs", (PyCFunction)PyCurses_termattrs, METH_NOARGS}, + {"termname", (PyCFunction)PyCurses_termname, METH_NOARGS}, + {"tigetflag", (PyCFunction)PyCurses_tigetflag, METH_VARARGS}, + {"tigetnum", (PyCFunction)PyCurses_tigetnum, METH_VARARGS}, + {"tigetstr", (PyCFunction)PyCurses_tigetstr, METH_VARARGS}, + {"tparm", (PyCFunction)PyCurses_tparm, METH_VARARGS}, + {"typeahead", (PyCFunction)PyCurses_TypeAhead, METH_VARARGS}, + {"unctrl", (PyCFunction)PyCurses_UnCtrl, METH_VARARGS}, + {"ungetch", (PyCFunction)PyCurses_UngetCh, METH_VARARGS}, + {"use_env", (PyCFunction)PyCurses_Use_Env, METH_VARARGS}, #ifndef STRICT_SYSV_CURSES - {"use_default_colors", (PyCFunction)PyCurses_Use_Default_Colors, METH_NOARGS}, + {"use_default_colors", (PyCFunction)PyCurses_Use_Default_Colors, METH_NOARGS}, #endif - {NULL, NULL} /* sentinel */ + {NULL, NULL} /* sentinel */ }; /* Initialization function for the module */ @@ -2731,162 +2731,162 @@ PyMODINIT_FUNC init_curses(void) { - PyObject *m, *d, *v, *c_api_object; - static void *PyCurses_API[PyCurses_API_pointers]; + PyObject *m, *d, *v, *c_api_object; + static void *PyCurses_API[PyCurses_API_pointers]; - /* Initialize object type */ - Py_TYPE(&PyCursesWindow_Type) = &PyType_Type; + /* Initialize object type */ + Py_TYPE(&PyCursesWindow_Type) = &PyType_Type; - /* Initialize the C API pointer array */ - PyCurses_API[0] = (void *)&PyCursesWindow_Type; - PyCurses_API[1] = (void *)func_PyCursesSetupTermCalled; - PyCurses_API[2] = (void *)func_PyCursesInitialised; - PyCurses_API[3] = (void *)func_PyCursesInitialisedColor; - - /* Create the module and add the functions */ - m = Py_InitModule("_curses", PyCurses_methods); - if (m == NULL) - return; - - /* Add some symbolic constants to the module */ - d = PyModule_GetDict(m); - if (d == NULL) - return; - ModDict = d; /* For PyCurses_InitScr to use later */ - - /* Add a capsule for the C API */ - c_api_object = PyCapsule_New(PyCurses_API, PyCurses_CAPSULE_NAME, NULL); - PyDict_SetItemString(d, "_C_API", c_api_object); - Py_DECREF(c_api_object); - - /* For exception curses.error */ - PyCursesError = PyErr_NewException("_curses.error", NULL, NULL); - PyDict_SetItemString(d, "error", PyCursesError); - - /* Make the version available */ - v = PyString_FromString(PyCursesVersion); - PyDict_SetItemString(d, "version", v); - PyDict_SetItemString(d, "__version__", v); - Py_DECREF(v); - - SetDictInt("ERR", ERR); - SetDictInt("OK", OK); - - /* Here are some attributes you can add to chars to print */ - - SetDictInt("A_ATTRIBUTES", A_ATTRIBUTES); - SetDictInt("A_NORMAL", A_NORMAL); - SetDictInt("A_STANDOUT", A_STANDOUT); - SetDictInt("A_UNDERLINE", A_UNDERLINE); - SetDictInt("A_REVERSE", A_REVERSE); - SetDictInt("A_BLINK", A_BLINK); - SetDictInt("A_DIM", A_DIM); - SetDictInt("A_BOLD", A_BOLD); - SetDictInt("A_ALTCHARSET", A_ALTCHARSET); + /* Initialize the C API pointer array */ + PyCurses_API[0] = (void *)&PyCursesWindow_Type; + PyCurses_API[1] = (void *)func_PyCursesSetupTermCalled; + PyCurses_API[2] = (void *)func_PyCursesInitialised; + PyCurses_API[3] = (void *)func_PyCursesInitialisedColor; + + /* Create the module and add the functions */ + m = Py_InitModule("_curses", PyCurses_methods); + if (m == NULL) + return; + + /* Add some symbolic constants to the module */ + d = PyModule_GetDict(m); + if (d == NULL) + return; + ModDict = d; /* For PyCurses_InitScr to use later */ + + /* Add a capsule for the C API */ + c_api_object = PyCapsule_New(PyCurses_API, PyCurses_CAPSULE_NAME, NULL); + PyDict_SetItemString(d, "_C_API", c_api_object); + Py_DECREF(c_api_object); + + /* For exception curses.error */ + PyCursesError = PyErr_NewException("_curses.error", NULL, NULL); + PyDict_SetItemString(d, "error", PyCursesError); + + /* Make the version available */ + v = PyString_FromString(PyCursesVersion); + PyDict_SetItemString(d, "version", v); + PyDict_SetItemString(d, "__version__", v); + Py_DECREF(v); + + SetDictInt("ERR", ERR); + SetDictInt("OK", OK); + + /* Here are some attributes you can add to chars to print */ + + SetDictInt("A_ATTRIBUTES", A_ATTRIBUTES); + SetDictInt("A_NORMAL", A_NORMAL); + SetDictInt("A_STANDOUT", A_STANDOUT); + SetDictInt("A_UNDERLINE", A_UNDERLINE); + SetDictInt("A_REVERSE", A_REVERSE); + SetDictInt("A_BLINK", A_BLINK); + SetDictInt("A_DIM", A_DIM); + SetDictInt("A_BOLD", A_BOLD); + SetDictInt("A_ALTCHARSET", A_ALTCHARSET); #if !defined(__NetBSD__) - SetDictInt("A_INVIS", A_INVIS); + SetDictInt("A_INVIS", A_INVIS); #endif - SetDictInt("A_PROTECT", A_PROTECT); - SetDictInt("A_CHARTEXT", A_CHARTEXT); - SetDictInt("A_COLOR", A_COLOR); + SetDictInt("A_PROTECT", A_PROTECT); + SetDictInt("A_CHARTEXT", A_CHARTEXT); + SetDictInt("A_COLOR", A_COLOR); - /* The following are never available with strict SYSV curses */ + /* The following are never available with strict SYSV curses */ #ifdef A_HORIZONTAL - SetDictInt("A_HORIZONTAL", A_HORIZONTAL); + SetDictInt("A_HORIZONTAL", A_HORIZONTAL); #endif #ifdef A_LEFT - SetDictInt("A_LEFT", A_LEFT); + SetDictInt("A_LEFT", A_LEFT); #endif #ifdef A_LOW - SetDictInt("A_LOW", A_LOW); + SetDictInt("A_LOW", A_LOW); #endif #ifdef A_RIGHT - SetDictInt("A_RIGHT", A_RIGHT); + SetDictInt("A_RIGHT", A_RIGHT); #endif #ifdef A_TOP - SetDictInt("A_TOP", A_TOP); + SetDictInt("A_TOP", A_TOP); #endif #ifdef A_VERTICAL - SetDictInt("A_VERTICAL", A_VERTICAL); + SetDictInt("A_VERTICAL", A_VERTICAL); #endif - SetDictInt("COLOR_BLACK", COLOR_BLACK); - SetDictInt("COLOR_RED", COLOR_RED); - SetDictInt("COLOR_GREEN", COLOR_GREEN); - SetDictInt("COLOR_YELLOW", COLOR_YELLOW); - SetDictInt("COLOR_BLUE", COLOR_BLUE); - SetDictInt("COLOR_MAGENTA", COLOR_MAGENTA); - SetDictInt("COLOR_CYAN", COLOR_CYAN); - SetDictInt("COLOR_WHITE", COLOR_WHITE); + SetDictInt("COLOR_BLACK", COLOR_BLACK); + SetDictInt("COLOR_RED", COLOR_RED); + SetDictInt("COLOR_GREEN", COLOR_GREEN); + SetDictInt("COLOR_YELLOW", COLOR_YELLOW); + SetDictInt("COLOR_BLUE", COLOR_BLUE); + SetDictInt("COLOR_MAGENTA", COLOR_MAGENTA); + SetDictInt("COLOR_CYAN", COLOR_CYAN); + SetDictInt("COLOR_WHITE", COLOR_WHITE); #ifdef NCURSES_MOUSE_VERSION - /* Mouse-related constants */ - SetDictInt("BUTTON1_PRESSED", BUTTON1_PRESSED); - SetDictInt("BUTTON1_RELEASED", BUTTON1_RELEASED); - SetDictInt("BUTTON1_CLICKED", BUTTON1_CLICKED); - SetDictInt("BUTTON1_DOUBLE_CLICKED", BUTTON1_DOUBLE_CLICKED); - SetDictInt("BUTTON1_TRIPLE_CLICKED", BUTTON1_TRIPLE_CLICKED); - - SetDictInt("BUTTON2_PRESSED", BUTTON2_PRESSED); - SetDictInt("BUTTON2_RELEASED", BUTTON2_RELEASED); - SetDictInt("BUTTON2_CLICKED", BUTTON2_CLICKED); - SetDictInt("BUTTON2_DOUBLE_CLICKED", BUTTON2_DOUBLE_CLICKED); - SetDictInt("BUTTON2_TRIPLE_CLICKED", BUTTON2_TRIPLE_CLICKED); - - SetDictInt("BUTTON3_PRESSED", BUTTON3_PRESSED); - SetDictInt("BUTTON3_RELEASED", BUTTON3_RELEASED); - SetDictInt("BUTTON3_CLICKED", BUTTON3_CLICKED); - SetDictInt("BUTTON3_DOUBLE_CLICKED", BUTTON3_DOUBLE_CLICKED); - SetDictInt("BUTTON3_TRIPLE_CLICKED", BUTTON3_TRIPLE_CLICKED); - - SetDictInt("BUTTON4_PRESSED", BUTTON4_PRESSED); - SetDictInt("BUTTON4_RELEASED", BUTTON4_RELEASED); - SetDictInt("BUTTON4_CLICKED", BUTTON4_CLICKED); - SetDictInt("BUTTON4_DOUBLE_CLICKED", BUTTON4_DOUBLE_CLICKED); - SetDictInt("BUTTON4_TRIPLE_CLICKED", BUTTON4_TRIPLE_CLICKED); - - SetDictInt("BUTTON_SHIFT", BUTTON_SHIFT); - SetDictInt("BUTTON_CTRL", BUTTON_CTRL); - SetDictInt("BUTTON_ALT", BUTTON_ALT); - - SetDictInt("ALL_MOUSE_EVENTS", ALL_MOUSE_EVENTS); - SetDictInt("REPORT_MOUSE_POSITION", REPORT_MOUSE_POSITION); -#endif - /* Now set everything up for KEY_ variables */ - { - int key; - char *key_n; - char *key_n2; + /* Mouse-related constants */ + SetDictInt("BUTTON1_PRESSED", BUTTON1_PRESSED); + SetDictInt("BUTTON1_RELEASED", BUTTON1_RELEASED); + SetDictInt("BUTTON1_CLICKED", BUTTON1_CLICKED); + SetDictInt("BUTTON1_DOUBLE_CLICKED", BUTTON1_DOUBLE_CLICKED); + SetDictInt("BUTTON1_TRIPLE_CLICKED", BUTTON1_TRIPLE_CLICKED); + + SetDictInt("BUTTON2_PRESSED", BUTTON2_PRESSED); + SetDictInt("BUTTON2_RELEASED", BUTTON2_RELEASED); + SetDictInt("BUTTON2_CLICKED", BUTTON2_CLICKED); + SetDictInt("BUTTON2_DOUBLE_CLICKED", BUTTON2_DOUBLE_CLICKED); + SetDictInt("BUTTON2_TRIPLE_CLICKED", BUTTON2_TRIPLE_CLICKED); + + SetDictInt("BUTTON3_PRESSED", BUTTON3_PRESSED); + SetDictInt("BUTTON3_RELEASED", BUTTON3_RELEASED); + SetDictInt("BUTTON3_CLICKED", BUTTON3_CLICKED); + SetDictInt("BUTTON3_DOUBLE_CLICKED", BUTTON3_DOUBLE_CLICKED); + SetDictInt("BUTTON3_TRIPLE_CLICKED", BUTTON3_TRIPLE_CLICKED); + + SetDictInt("BUTTON4_PRESSED", BUTTON4_PRESSED); + SetDictInt("BUTTON4_RELEASED", BUTTON4_RELEASED); + SetDictInt("BUTTON4_CLICKED", BUTTON4_CLICKED); + SetDictInt("BUTTON4_DOUBLE_CLICKED", BUTTON4_DOUBLE_CLICKED); + SetDictInt("BUTTON4_TRIPLE_CLICKED", BUTTON4_TRIPLE_CLICKED); + + SetDictInt("BUTTON_SHIFT", BUTTON_SHIFT); + SetDictInt("BUTTON_CTRL", BUTTON_CTRL); + SetDictInt("BUTTON_ALT", BUTTON_ALT); + + SetDictInt("ALL_MOUSE_EVENTS", ALL_MOUSE_EVENTS); + SetDictInt("REPORT_MOUSE_POSITION", REPORT_MOUSE_POSITION); +#endif + /* Now set everything up for KEY_ variables */ + { + int key; + char *key_n; + char *key_n2; #if !defined(__NetBSD__) - for (key=KEY_MIN;key < KEY_MAX; key++) { - key_n = (char *)keyname(key); - if (key_n == NULL || strcmp(key_n,"UNKNOWN KEY")==0) - continue; - if (strncmp(key_n,"KEY_F(",6)==0) { - char *p1, *p2; - key_n2 = malloc(strlen(key_n)+1); - if (!key_n2) { - PyErr_NoMemory(); - break; - } - p1 = key_n; - p2 = key_n2; - while (*p1) { - if (*p1 != '(' && *p1 != ')') { - *p2 = *p1; - p2++; - } - p1++; - } - *p2 = (char)0; - } else - key_n2 = key_n; - SetDictInt(key_n2,key); - if (key_n2 != key_n) - free(key_n2); - } -#endif - SetDictInt("KEY_MIN", KEY_MIN); - SetDictInt("KEY_MAX", KEY_MAX); - } + for (key=KEY_MIN;key < KEY_MAX; key++) { + key_n = (char *)keyname(key); + if (key_n == NULL || strcmp(key_n,"UNKNOWN KEY")==0) + continue; + if (strncmp(key_n,"KEY_F(",6)==0) { + char *p1, *p2; + key_n2 = malloc(strlen(key_n)+1); + if (!key_n2) { + PyErr_NoMemory(); + break; + } + p1 = key_n; + p2 = key_n2; + while (*p1) { + if (*p1 != '(' && *p1 != ')') { + *p2 = *p1; + p2++; + } + p1++; + } + *p2 = (char)0; + } else + key_n2 = key_n; + SetDictInt(key_n2,key); + if (key_n2 != key_n) + free(key_n2); + } +#endif + SetDictInt("KEY_MIN", KEY_MIN); + SetDictInt("KEY_MAX", KEY_MAX); + } } From python-checkins at python.org Sun May 16 00:20:17 2010 From: python-checkins at python.org (brett.cannon) Date: Sun, 16 May 2010 00:20:17 +0200 (CEST) Subject: [Python-checkins] r81214 - python/branches/py3k/Lib/test/test_import.py Message-ID: <20100515222017.1B0A6EE9FB@mail.python.org> Author: brett.cannon Date: Sun May 16 00:20:16 2010 New Revision: 81214 Log: A test was not guaranteeing cleanup in the face of an exception. Modified: python/branches/py3k/Lib/test/test_import.py Modified: python/branches/py3k/Lib/test/test_import.py ============================================================================== --- python/branches/py3k/Lib/test/test_import.py (original) +++ python/branches/py3k/Lib/test/test_import.py Sun May 16 00:20:16 2010 @@ -163,13 +163,14 @@ # Need to be able to load from current dir. sys.path.append('') - # This used to crash. - exec('import ' + module) - - # Cleanup. - del sys.path[-1] - unlink(filename + 'c') - unlink(filename + 'o') + try: + # This used to crash. + exec('import ' + module) + finally: + # Cleanup. + del sys.path[-1] + unlink(filename + 'c') + unlink(filename + 'o') def test_failing_import_sticks(self): source = TESTFN + ".py" From python-checkins at python.org Sun May 16 00:23:54 2010 From: python-checkins at python.org (victor.stinner) Date: Sun, 16 May 2010 00:23:54 +0200 (CEST) Subject: [Python-checkins] r81215 - in python/branches/py3k: Modules/_cursesmodule.c Message-ID: <20100515222354.06E14EEB2E@mail.python.org> Author: victor.stinner Date: Sun May 16 00:23:53 2010 New Revision: 81215 Log: Recorded merge of revisions 81213 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r81213 | victor.stinner | 2010-05-16 00:19:27 +0200 (dim., 16 mai 2010) | 5 lines reindent _cursesmodule.c Use untabify.py + emacs (python3 mode) + manual editions for Py_BEGIN_ALLOW_THREADS / Py_END_ALLOW_THREADS ........ Modified: python/branches/py3k/ (props changed) python/branches/py3k/Modules/_cursesmodule.c Modified: python/branches/py3k/Modules/_cursesmodule.c ============================================================================== --- python/branches/py3k/Modules/_cursesmodule.c (original) +++ python/branches/py3k/Modules/_cursesmodule.c Sun May 16 00:23:53 2010 @@ -33,66 +33,66 @@ /* -A number of SysV or ncurses functions don't have wrappers yet; if you -need a given function, add it and send a patch. See -http://www.python.org/dev/patches/ for instructions on how to submit -patches to Python. - -Here's a list of currently unsupported functions: - - addchnstr addchstr color_set define_key - del_curterm delscreen dupwin inchnstr inchstr innstr keyok - mcprint mvaddchnstr mvaddchstr mvcur mvinchnstr - mvinchstr mvinnstr mmvwaddchnstr mvwaddchstr - mvwinchnstr mvwinchstr mvwinnstr newterm - restartterm ripoffline scr_dump - scr_init scr_restore scr_set scrl set_curterm set_term setterm - tgetent tgetflag tgetnum tgetstr tgoto timeout tputs - vidattr vidputs waddchnstr waddchstr - wcolor_set winchnstr winchstr winnstr wmouse_trafo wscrl - -Low-priority: - slk_attr slk_attr_off slk_attr_on slk_attr_set slk_attroff - slk_attron slk_attrset slk_clear slk_color slk_init slk_label - slk_noutrefresh slk_refresh slk_restore slk_set slk_touch - -Menu extension (ncurses and probably SYSV): - current_item free_item free_menu item_count item_description - item_index item_init item_name item_opts item_opts_off - item_opts_on item_term item_userptr item_value item_visible - menu_back menu_driver menu_fore menu_format menu_grey - menu_init menu_items menu_mark menu_opts menu_opts_off - menu_opts_on menu_pad menu_pattern menu_request_by_name - menu_request_name menu_spacing menu_sub menu_term menu_userptr - menu_win new_item new_menu pos_menu_cursor post_menu - scale_menu set_current_item set_item_init set_item_opts - set_item_term set_item_userptr set_item_value set_menu_back - set_menu_fore set_menu_format set_menu_grey set_menu_init - set_menu_items set_menu_mark set_menu_opts set_menu_pad - set_menu_pattern set_menu_spacing set_menu_sub set_menu_term - set_menu_userptr set_menu_win set_top_row top_row unpost_menu - -Form extension (ncurses and probably SYSV): - current_field data_ahead data_behind dup_field - dynamic_fieldinfo field_arg field_back field_buffer - field_count field_fore field_index field_info field_init - field_just field_opts field_opts_off field_opts_on field_pad - field_status field_term field_type field_userptr form_driver - form_fields form_init form_opts form_opts_off form_opts_on - form_page form_request_by_name form_request_name form_sub - form_term form_userptr form_win free_field free_form - link_field link_fieldtype move_field new_field new_form - new_page pos_form_cursor post_form scale_form - set_current_field set_field_back set_field_buffer - set_field_fore set_field_init set_field_just set_field_opts - set_field_pad set_field_status set_field_term set_field_type - set_field_userptr set_fieldtype_arg set_fieldtype_choice - set_form_fields set_form_init set_form_opts set_form_page - set_form_sub set_form_term set_form_userptr set_form_win - set_max_field set_new_page unpost_form + A number of SysV or ncurses functions don't have wrappers yet; if you + need a given function, add it and send a patch. See + http://www.python.org/dev/patches/ for instructions on how to submit + patches to Python. + + Here's a list of currently unsupported functions: + + addchnstr addchstr color_set define_key + del_curterm delscreen dupwin inchnstr inchstr innstr keyok + mcprint mvaddchnstr mvaddchstr mvcur mvinchnstr + mvinchstr mvinnstr mmvwaddchnstr mvwaddchstr + mvwinchnstr mvwinchstr mvwinnstr newterm + restartterm ripoffline scr_dump + scr_init scr_restore scr_set scrl set_curterm set_term setterm + tgetent tgetflag tgetnum tgetstr tgoto timeout tputs + vidattr vidputs waddchnstr waddchstr + wcolor_set winchnstr winchstr winnstr wmouse_trafo wscrl + + Low-priority: + slk_attr slk_attr_off slk_attr_on slk_attr_set slk_attroff + slk_attron slk_attrset slk_clear slk_color slk_init slk_label + slk_noutrefresh slk_refresh slk_restore slk_set slk_touch + + Menu extension (ncurses and probably SYSV): + current_item free_item free_menu item_count item_description + item_index item_init item_name item_opts item_opts_off + item_opts_on item_term item_userptr item_value item_visible + menu_back menu_driver menu_fore menu_format menu_grey + menu_init menu_items menu_mark menu_opts menu_opts_off + menu_opts_on menu_pad menu_pattern menu_request_by_name + menu_request_name menu_spacing menu_sub menu_term menu_userptr + menu_win new_item new_menu pos_menu_cursor post_menu + scale_menu set_current_item set_item_init set_item_opts + set_item_term set_item_userptr set_item_value set_menu_back + set_menu_fore set_menu_format set_menu_grey set_menu_init + set_menu_items set_menu_mark set_menu_opts set_menu_pad + set_menu_pattern set_menu_spacing set_menu_sub set_menu_term + set_menu_userptr set_menu_win set_top_row top_row unpost_menu + + Form extension (ncurses and probably SYSV): + current_field data_ahead data_behind dup_field + dynamic_fieldinfo field_arg field_back field_buffer + field_count field_fore field_index field_info field_init + field_just field_opts field_opts_off field_opts_on field_pad + field_status field_term field_type field_userptr form_driver + form_fields form_init form_opts form_opts_off form_opts_on + form_page form_request_by_name form_request_name form_sub + form_term form_userptr form_win free_field free_form + link_field link_fieldtype move_field new_field new_form + new_page pos_form_cursor post_form scale_form + set_current_field set_field_back set_field_buffer + set_field_fore set_field_init set_field_just set_field_opts + set_field_pad set_field_status set_field_term set_field_type + set_field_userptr set_fieldtype_arg set_fieldtype_choice + set_form_fields set_form_init set_form_opts set_form_page + set_form_sub set_form_term set_form_userptr set_form_win + set_max_field set_new_page unpost_form - */ +*/ /* Release Number */ @@ -116,9 +116,9 @@ #define CURSES_MODULE #include "py_curses.h" -/* These prototypes are in , but including this header - #defines many common symbols (such as "lines") which breaks the - curses module in other ways. So the code will just specify +/* These prototypes are in , but including this header + #defines many common symbols (such as "lines") which breaks the + curses module in other ways. So the code will just specify explicit prototypes here. */ extern int setupterm(char *,int,int *); #ifdef __sgi @@ -148,23 +148,23 @@ static int initialisedcolors = FALSE; /* Utility Macros */ -#define PyCursesSetupTermCalled \ - if (initialised_setupterm != TRUE) { \ - PyErr_SetString(PyCursesError, \ - "must call (at least) setupterm() first"); \ - return 0; } - -#define PyCursesInitialised \ - if (initialised != TRUE) { \ - PyErr_SetString(PyCursesError, \ - "must call initscr() first"); \ - return 0; } - -#define PyCursesInitialisedColor \ - if (initialisedcolors != TRUE) { \ - PyErr_SetString(PyCursesError, \ - "must call start_color() first"); \ - return 0; } +#define PyCursesSetupTermCalled \ + if (initialised_setupterm != TRUE) { \ + PyErr_SetString(PyCursesError, \ + "must call (at least) setupterm() first"); \ + return 0; } + +#define PyCursesInitialised \ + if (initialised != TRUE) { \ + PyErr_SetString(PyCursesError, \ + "must call initscr() first"); \ + return 0; } + +#define PyCursesInitialisedColor \ + if (initialisedcolors != TRUE) { \ + PyErr_SetString(PyCursesError, \ + "must call start_color() first"); \ + return 0; } #ifndef MIN #define MIN(x,y) ((x) < (y) ? (x) : (y)) @@ -173,51 +173,51 @@ /* Utility Functions */ /* - * Check the return code from a curses function and return None + * Check the return code from a curses function and return None * or raise an exception as appropriate. These are exported using the - * capsule API. + * capsule API. */ static PyObject * PyCursesCheckERR(int code, char *fname) { - if (code != ERR) { - Py_INCREF(Py_None); - return Py_None; - } else { - if (fname == NULL) { - PyErr_SetString(PyCursesError, catchall_ERR); + if (code != ERR) { + Py_INCREF(Py_None); + return Py_None; } else { - PyErr_Format(PyCursesError, "%s() returned ERR", fname); + if (fname == NULL) { + PyErr_SetString(PyCursesError, catchall_ERR); + } else { + PyErr_Format(PyCursesError, "%s() returned ERR", fname); + } + return NULL; } - return NULL; - } } -static int +static int PyCurses_ConvertToChtype(PyObject *obj, chtype *ch) { - if (PyLong_CheckExact(obj)) { - int overflow; - /* XXX should the truncation by the cast also be reported - as an error? */ - *ch = (chtype) PyLong_AsLongAndOverflow(obj, &overflow); - if (overflow) - return 0; - } else if(PyBytes_Check(obj) - && (PyBytes_Size(obj) == 1)) { - *ch = (chtype) *PyBytes_AsString(obj); - } else if (PyUnicode_Check(obj) && PyUnicode_GetSize(obj) == 1) { - *ch = (chtype) *PyUnicode_AS_UNICODE(obj); - } else { - return 0; - } - return 1; + if (PyLong_CheckExact(obj)) { + int overflow; + /* XXX should the truncation by the cast also be reported + as an error? */ + *ch = (chtype) PyLong_AsLongAndOverflow(obj, &overflow); + if (overflow) + return 0; + } else if(PyBytes_Check(obj) + && (PyBytes_Size(obj) == 1)) { + *ch = (chtype) *PyBytes_AsString(obj); + } else if (PyUnicode_Check(obj) && PyUnicode_GetSize(obj) == 1) { + *ch = (chtype) *PyUnicode_AS_UNICODE(obj); + } else { + return 0; + } + return 1; } /* Function versions of the 3 functions for testing whether curses has been initialised or not. */ - + static int func_PyCursesSetupTermCalled(void) { PyCursesSetupTermCalled; @@ -250,56 +250,56 @@ TYPE - parameter Type ERGSTR - format string for construction of the return value PARSESTR - format string for argument parsing - */ +*/ -#define Window_NoArgNoReturnFunction(X) \ -static PyObject *PyCursesWindow_ ## X \ -(PyCursesWindowObject *self, PyObject *args) \ -{ return PyCursesCheckERR(X(self->win), # X); } - -#define Window_NoArgTrueFalseFunction(X) \ -static PyObject * PyCursesWindow_ ## X \ -(PyCursesWindowObject *self) \ -{ \ - if (X (self->win) == FALSE) { Py_INCREF(Py_False); return Py_False; } \ - else { Py_INCREF(Py_True); return Py_True; } } - -#define Window_NoArgNoReturnVoidFunction(X) \ -static PyObject * PyCursesWindow_ ## X \ -(PyCursesWindowObject *self) \ -{ \ - X(self->win); Py_INCREF(Py_None); return Py_None; } - -#define Window_NoArg2TupleReturnFunction(X, TYPE, ERGSTR) \ -static PyObject * PyCursesWindow_ ## X \ -(PyCursesWindowObject *self) \ -{ \ - TYPE arg1, arg2; \ - X(self->win,arg1,arg2); return Py_BuildValue(ERGSTR, arg1, arg2); } - -#define Window_OneArgNoReturnVoidFunction(X, TYPE, PARSESTR) \ -static PyObject * PyCursesWindow_ ## X \ -(PyCursesWindowObject *self, PyObject *args) \ -{ \ - TYPE arg1; \ - if (!PyArg_ParseTuple(args, PARSESTR, &arg1)) return NULL; \ - X(self->win,arg1); Py_INCREF(Py_None); return Py_None; } - -#define Window_OneArgNoReturnFunction(X, TYPE, PARSESTR) \ -static PyObject * PyCursesWindow_ ## X \ -(PyCursesWindowObject *self, PyObject *args) \ -{ \ - TYPE arg1; \ - if (!PyArg_ParseTuple(args,PARSESTR, &arg1)) return NULL; \ - return PyCursesCheckERR(X(self->win, arg1), # X); } - -#define Window_TwoArgNoReturnFunction(X, TYPE, PARSESTR) \ -static PyObject * PyCursesWindow_ ## X \ -(PyCursesWindowObject *self, PyObject *args) \ -{ \ - TYPE arg1, arg2; \ - if (!PyArg_ParseTuple(args,PARSESTR, &arg1, &arg2)) return NULL; \ - return PyCursesCheckERR(X(self->win, arg1, arg2), # X); } +#define Window_NoArgNoReturnFunction(X) \ + static PyObject *PyCursesWindow_ ## X \ + (PyCursesWindowObject *self, PyObject *args) \ + { return PyCursesCheckERR(X(self->win), # X); } + +#define Window_NoArgTrueFalseFunction(X) \ + static PyObject * PyCursesWindow_ ## X \ + (PyCursesWindowObject *self) \ + { \ + if (X (self->win) == FALSE) { Py_INCREF(Py_False); return Py_False; } \ + else { Py_INCREF(Py_True); return Py_True; } } + +#define Window_NoArgNoReturnVoidFunction(X) \ + static PyObject * PyCursesWindow_ ## X \ + (PyCursesWindowObject *self) \ + { \ + X(self->win); Py_INCREF(Py_None); return Py_None; } + +#define Window_NoArg2TupleReturnFunction(X, TYPE, ERGSTR) \ + static PyObject * PyCursesWindow_ ## X \ + (PyCursesWindowObject *self) \ + { \ + TYPE arg1, arg2; \ + X(self->win,arg1,arg2); return Py_BuildValue(ERGSTR, arg1, arg2); } + +#define Window_OneArgNoReturnVoidFunction(X, TYPE, PARSESTR) \ + static PyObject * PyCursesWindow_ ## X \ + (PyCursesWindowObject *self, PyObject *args) \ + { \ + TYPE arg1; \ + if (!PyArg_ParseTuple(args, PARSESTR, &arg1)) return NULL; \ + X(self->win,arg1); Py_INCREF(Py_None); return Py_None; } + +#define Window_OneArgNoReturnFunction(X, TYPE, PARSESTR) \ + static PyObject * PyCursesWindow_ ## X \ + (PyCursesWindowObject *self, PyObject *args) \ + { \ + TYPE arg1; \ + if (!PyArg_ParseTuple(args,PARSESTR, &arg1)) return NULL; \ + return PyCursesCheckERR(X(self->win, arg1), # X); } + +#define Window_TwoArgNoReturnFunction(X, TYPE, PARSESTR) \ + static PyObject * PyCursesWindow_ ## X \ + (PyCursesWindowObject *self, PyObject *args) \ + { \ + TYPE arg1, arg2; \ + if (!PyArg_ParseTuple(args,PARSESTR, &arg1, &arg2)) return NULL; \ + return PyCursesCheckERR(X(self->win, arg1, arg2), # X); } /* ------------- WINDOW routines --------------- */ @@ -360,19 +360,19 @@ static PyObject * PyCursesWindow_New(WINDOW *win) { - PyCursesWindowObject *wo; + PyCursesWindowObject *wo; - wo = PyObject_NEW(PyCursesWindowObject, &PyCursesWindow_Type); - if (wo == NULL) return NULL; - wo->win = win; - return (PyObject *)wo; + wo = PyObject_NEW(PyCursesWindowObject, &PyCursesWindow_Type); + if (wo == NULL) return NULL; + wo->win = win; + return (PyObject *)wo; } static void PyCursesWindow_Dealloc(PyCursesWindowObject *wo) { - if (wo->win != stdscr) delwin(wo->win); - PyObject_DEL(wo); + if (wo->win != stdscr) delwin(wo->win); + PyObject_DEL(wo); } /* Addch, Addstr, Addnstr */ @@ -380,287 +380,287 @@ static PyObject * PyCursesWindow_AddCh(PyCursesWindowObject *self, PyObject *args) { - int rtn, x, y, use_xy = FALSE; - PyObject *temp; - chtype ch = 0; - attr_t attr = A_NORMAL; - long lattr; - - switch (PyTuple_Size(args)) { - case 1: - if (!PyArg_ParseTuple(args, "O;ch or int", &temp)) - return NULL; - break; - case 2: - if (!PyArg_ParseTuple(args, "Ol;ch or int,attr", &temp, &lattr)) - return NULL; - attr = lattr; - break; - case 3: - if (!PyArg_ParseTuple(args,"iiO;y,x,ch or int", &y, &x, &temp)) - return NULL; - use_xy = TRUE; - break; - case 4: - if (!PyArg_ParseTuple(args,"iiOl;y,x,ch or int, attr", - &y, &x, &temp, &lattr)) - return NULL; - attr = lattr; - use_xy = TRUE; - break; - default: - PyErr_SetString(PyExc_TypeError, "addch requires 1 to 4 arguments"); - return NULL; - } - - if (!PyCurses_ConvertToChtype(temp, &ch)) { - PyErr_SetString(PyExc_TypeError, "argument 1 or 3 must be a ch or an int"); - return NULL; - } - - if (use_xy == TRUE) - rtn = mvwaddch(self->win,y,x, ch | attr); - else { - rtn = waddch(self->win, ch | attr); - } - return PyCursesCheckERR(rtn, "addch"); + int rtn, x, y, use_xy = FALSE; + PyObject *temp; + chtype ch = 0; + attr_t attr = A_NORMAL; + long lattr; + + switch (PyTuple_Size(args)) { + case 1: + if (!PyArg_ParseTuple(args, "O;ch or int", &temp)) + return NULL; + break; + case 2: + if (!PyArg_ParseTuple(args, "Ol;ch or int,attr", &temp, &lattr)) + return NULL; + attr = lattr; + break; + case 3: + if (!PyArg_ParseTuple(args,"iiO;y,x,ch or int", &y, &x, &temp)) + return NULL; + use_xy = TRUE; + break; + case 4: + if (!PyArg_ParseTuple(args,"iiOl;y,x,ch or int, attr", + &y, &x, &temp, &lattr)) + return NULL; + attr = lattr; + use_xy = TRUE; + break; + default: + PyErr_SetString(PyExc_TypeError, "addch requires 1 to 4 arguments"); + return NULL; + } + + if (!PyCurses_ConvertToChtype(temp, &ch)) { + PyErr_SetString(PyExc_TypeError, "argument 1 or 3 must be a ch or an int"); + return NULL; + } + + if (use_xy == TRUE) + rtn = mvwaddch(self->win,y,x, ch | attr); + else { + rtn = waddch(self->win, ch | attr); + } + return PyCursesCheckERR(rtn, "addch"); } static PyObject * PyCursesWindow_AddStr(PyCursesWindowObject *self, PyObject *args) { - int rtn; - int x, y; - char *str; - attr_t attr = A_NORMAL , attr_old = A_NORMAL; - long lattr; - int use_xy = FALSE, use_attr = FALSE; - - switch (PyTuple_Size(args)) { - case 1: - if (!PyArg_ParseTuple(args,"s;str", &str)) - return NULL; - break; - case 2: - if (!PyArg_ParseTuple(args,"sl;str,attr", &str, &lattr)) - return NULL; - attr = lattr; - use_attr = TRUE; - break; - case 3: - if (!PyArg_ParseTuple(args,"iis;int,int,str", &y, &x, &str)) - return NULL; - use_xy = TRUE; - break; - case 4: - if (!PyArg_ParseTuple(args,"iisl;int,int,str,attr", &y, &x, &str, &lattr)) - return NULL; - attr = lattr; - use_xy = use_attr = TRUE; - break; - default: - PyErr_SetString(PyExc_TypeError, "addstr requires 1 to 4 arguments"); - return NULL; - } - - if (use_attr == TRUE) { - attr_old = getattrs(self->win); - (void)wattrset(self->win,attr); - } - if (use_xy == TRUE) - rtn = mvwaddstr(self->win,y,x,str); - else - rtn = waddstr(self->win,str); - if (use_attr == TRUE) - (void)wattrset(self->win,attr_old); - return PyCursesCheckERR(rtn, "addstr"); + int rtn; + int x, y; + char *str; + attr_t attr = A_NORMAL , attr_old = A_NORMAL; + long lattr; + int use_xy = FALSE, use_attr = FALSE; + + switch (PyTuple_Size(args)) { + case 1: + if (!PyArg_ParseTuple(args,"s;str", &str)) + return NULL; + break; + case 2: + if (!PyArg_ParseTuple(args,"sl;str,attr", &str, &lattr)) + return NULL; + attr = lattr; + use_attr = TRUE; + break; + case 3: + if (!PyArg_ParseTuple(args,"iis;int,int,str", &y, &x, &str)) + return NULL; + use_xy = TRUE; + break; + case 4: + if (!PyArg_ParseTuple(args,"iisl;int,int,str,attr", &y, &x, &str, &lattr)) + return NULL; + attr = lattr; + use_xy = use_attr = TRUE; + break; + default: + PyErr_SetString(PyExc_TypeError, "addstr requires 1 to 4 arguments"); + return NULL; + } + + if (use_attr == TRUE) { + attr_old = getattrs(self->win); + (void)wattrset(self->win,attr); + } + if (use_xy == TRUE) + rtn = mvwaddstr(self->win,y,x,str); + else + rtn = waddstr(self->win,str); + if (use_attr == TRUE) + (void)wattrset(self->win,attr_old); + return PyCursesCheckERR(rtn, "addstr"); } static PyObject * PyCursesWindow_AddNStr(PyCursesWindowObject *self, PyObject *args) { - int rtn, x, y, n; - char *str; - attr_t attr = A_NORMAL , attr_old = A_NORMAL; - long lattr; - int use_xy = FALSE, use_attr = FALSE; - - switch (PyTuple_Size(args)) { - case 2: - if (!PyArg_ParseTuple(args,"si;str,n", &str, &n)) - return NULL; - break; - case 3: - if (!PyArg_ParseTuple(args,"sil;str,n,attr", &str, &n, &lattr)) - return NULL; - attr = lattr; - use_attr = TRUE; - break; - case 4: - if (!PyArg_ParseTuple(args,"iisi;y,x,str,n", &y, &x, &str, &n)) - return NULL; - use_xy = TRUE; - break; - case 5: - if (!PyArg_ParseTuple(args,"iisil;y,x,str,n,attr", &y, &x, &str, &n, &lattr)) - return NULL; - attr = lattr; - use_xy = use_attr = TRUE; - break; - default: - PyErr_SetString(PyExc_TypeError, "addnstr requires 2 to 5 arguments"); - return NULL; - } - - if (use_attr == TRUE) { - attr_old = getattrs(self->win); - (void)wattrset(self->win,attr); - } - if (use_xy == TRUE) - rtn = mvwaddnstr(self->win,y,x,str,n); - else - rtn = waddnstr(self->win,str,n); - if (use_attr == TRUE) - (void)wattrset(self->win,attr_old); - return PyCursesCheckERR(rtn, "addnstr"); + int rtn, x, y, n; + char *str; + attr_t attr = A_NORMAL , attr_old = A_NORMAL; + long lattr; + int use_xy = FALSE, use_attr = FALSE; + + switch (PyTuple_Size(args)) { + case 2: + if (!PyArg_ParseTuple(args,"si;str,n", &str, &n)) + return NULL; + break; + case 3: + if (!PyArg_ParseTuple(args,"sil;str,n,attr", &str, &n, &lattr)) + return NULL; + attr = lattr; + use_attr = TRUE; + break; + case 4: + if (!PyArg_ParseTuple(args,"iisi;y,x,str,n", &y, &x, &str, &n)) + return NULL; + use_xy = TRUE; + break; + case 5: + if (!PyArg_ParseTuple(args,"iisil;y,x,str,n,attr", &y, &x, &str, &n, &lattr)) + return NULL; + attr = lattr; + use_xy = use_attr = TRUE; + break; + default: + PyErr_SetString(PyExc_TypeError, "addnstr requires 2 to 5 arguments"); + return NULL; + } + + if (use_attr == TRUE) { + attr_old = getattrs(self->win); + (void)wattrset(self->win,attr); + } + if (use_xy == TRUE) + rtn = mvwaddnstr(self->win,y,x,str,n); + else + rtn = waddnstr(self->win,str,n); + if (use_attr == TRUE) + (void)wattrset(self->win,attr_old); + return PyCursesCheckERR(rtn, "addnstr"); } static PyObject * PyCursesWindow_Bkgd(PyCursesWindowObject *self, PyObject *args) { - PyObject *temp; - chtype bkgd; - attr_t attr = A_NORMAL; - long lattr; + PyObject *temp; + chtype bkgd; + attr_t attr = A_NORMAL; + long lattr; - switch (PyTuple_Size(args)) { + switch (PyTuple_Size(args)) { case 1: - if (!PyArg_ParseTuple(args, "O;ch or int", &temp)) - return NULL; - break; + if (!PyArg_ParseTuple(args, "O;ch or int", &temp)) + return NULL; + break; case 2: - if (!PyArg_ParseTuple(args,"Ol;ch or int,attr", &temp, &lattr)) - return NULL; - attr = lattr; - break; + if (!PyArg_ParseTuple(args,"Ol;ch or int,attr", &temp, &lattr)) + return NULL; + attr = lattr; + break; default: - PyErr_SetString(PyExc_TypeError, "bkgd requires 1 or 2 arguments"); - return NULL; - } + PyErr_SetString(PyExc_TypeError, "bkgd requires 1 or 2 arguments"); + return NULL; + } - if (!PyCurses_ConvertToChtype(temp, &bkgd)) { - PyErr_SetString(PyExc_TypeError, "argument 1 or 3 must be a ch or an int"); - return NULL; - } + if (!PyCurses_ConvertToChtype(temp, &bkgd)) { + PyErr_SetString(PyExc_TypeError, "argument 1 or 3 must be a ch or an int"); + return NULL; + } - return PyCursesCheckERR(wbkgd(self->win, bkgd | attr), "bkgd"); + return PyCursesCheckERR(wbkgd(self->win, bkgd | attr), "bkgd"); } static PyObject * PyCursesWindow_AttrOff(PyCursesWindowObject *self, PyObject *args) { - long lattr; - if (!PyArg_ParseTuple(args,"l;attr", &lattr)) - return NULL; - return PyCursesCheckERR(wattroff(self->win, (attr_t)lattr), "attroff"); + long lattr; + if (!PyArg_ParseTuple(args,"l;attr", &lattr)) + return NULL; + return PyCursesCheckERR(wattroff(self->win, (attr_t)lattr), "attroff"); } static PyObject * PyCursesWindow_AttrOn(PyCursesWindowObject *self, PyObject *args) { - long lattr; - if (!PyArg_ParseTuple(args,"l;attr", &lattr)) - return NULL; - return PyCursesCheckERR(wattron(self->win, (attr_t)lattr), "attron"); + long lattr; + if (!PyArg_ParseTuple(args,"l;attr", &lattr)) + return NULL; + return PyCursesCheckERR(wattron(self->win, (attr_t)lattr), "attron"); } static PyObject * PyCursesWindow_AttrSet(PyCursesWindowObject *self, PyObject *args) { - long lattr; - if (!PyArg_ParseTuple(args,"l;attr", &lattr)) - return NULL; - return PyCursesCheckERR(wattrset(self->win, (attr_t)lattr), "attrset"); + long lattr; + if (!PyArg_ParseTuple(args,"l;attr", &lattr)) + return NULL; + return PyCursesCheckERR(wattrset(self->win, (attr_t)lattr), "attrset"); } static PyObject * PyCursesWindow_BkgdSet(PyCursesWindowObject *self, PyObject *args) { - PyObject *temp; - chtype bkgd; - attr_t attr = A_NORMAL; - long lattr; + PyObject *temp; + chtype bkgd; + attr_t attr = A_NORMAL; + long lattr; - switch (PyTuple_Size(args)) { + switch (PyTuple_Size(args)) { case 1: - if (!PyArg_ParseTuple(args, "O;ch or int", &temp)) - return NULL; - break; + if (!PyArg_ParseTuple(args, "O;ch or int", &temp)) + return NULL; + break; case 2: - if (!PyArg_ParseTuple(args,"Ol;ch or int,attr", &temp, &lattr)) - return NULL; - attr = lattr; - break; + if (!PyArg_ParseTuple(args,"Ol;ch or int,attr", &temp, &lattr)) + return NULL; + attr = lattr; + break; default: - PyErr_SetString(PyExc_TypeError, "bkgdset requires 1 or 2 arguments"); - return NULL; - } + PyErr_SetString(PyExc_TypeError, "bkgdset requires 1 or 2 arguments"); + return NULL; + } - if (!PyCurses_ConvertToChtype(temp, &bkgd)) { - PyErr_SetString(PyExc_TypeError, "argument 1 must be a ch or an int"); - return NULL; - } + if (!PyCurses_ConvertToChtype(temp, &bkgd)) { + PyErr_SetString(PyExc_TypeError, "argument 1 must be a ch or an int"); + return NULL; + } - wbkgdset(self->win, bkgd | attr); - return PyCursesCheckERR(0, "bkgdset"); + wbkgdset(self->win, bkgd | attr); + return PyCursesCheckERR(0, "bkgdset"); } static PyObject * PyCursesWindow_Border(PyCursesWindowObject *self, PyObject *args) { - PyObject *temp[8]; - chtype ch[8]; - int i; - - /* Clear the array of parameters */ - for(i=0; i<8; i++) { - temp[i] = NULL; - ch[i] = 0; - } - - if (!PyArg_ParseTuple(args,"|OOOOOOOO;ls,rs,ts,bs,tl,tr,bl,br", - &temp[0], &temp[1], &temp[2], &temp[3], - &temp[4], &temp[5], &temp[6], &temp[7])) - return NULL; - - for(i=0; i<8; i++) { - if (temp[i] != NULL && !PyCurses_ConvertToChtype(temp[i], &ch[i])) { - PyErr_Format(PyExc_TypeError, - "argument %i must be a ch or an int", i+1); - return NULL; - } - } - - wborder(self->win, - ch[0], ch[1], ch[2], ch[3], - ch[4], ch[5], ch[6], ch[7]); - Py_INCREF(Py_None); - return Py_None; + PyObject *temp[8]; + chtype ch[8]; + int i; + + /* Clear the array of parameters */ + for(i=0; i<8; i++) { + temp[i] = NULL; + ch[i] = 0; + } + + if (!PyArg_ParseTuple(args,"|OOOOOOOO;ls,rs,ts,bs,tl,tr,bl,br", + &temp[0], &temp[1], &temp[2], &temp[3], + &temp[4], &temp[5], &temp[6], &temp[7])) + return NULL; + + for(i=0; i<8; i++) { + if (temp[i] != NULL && !PyCurses_ConvertToChtype(temp[i], &ch[i])) { + PyErr_Format(PyExc_TypeError, + "argument %i must be a ch or an int", i+1); + return NULL; + } + } + + wborder(self->win, + ch[0], ch[1], ch[2], ch[3], + ch[4], ch[5], ch[6], ch[7]); + Py_INCREF(Py_None); + return Py_None; } static PyObject * PyCursesWindow_Box(PyCursesWindowObject *self, PyObject *args) { - chtype ch1=0,ch2=0; - switch(PyTuple_Size(args)){ - case 0: break; - default: - if (!PyArg_ParseTuple(args,"ll;vertint,horint", &ch1, &ch2)) - return NULL; - } - box(self->win,ch1,ch2); - Py_INCREF(Py_None); - return Py_None; + chtype ch1=0,ch2=0; + switch(PyTuple_Size(args)){ + case 0: break; + default: + if (!PyArg_ParseTuple(args,"ll;vertint,horint", &ch1, &ch2)) + return NULL; + } + box(self->win,ch1,ch2); + Py_INCREF(Py_None); + return Py_None; } #if defined(HAVE_NCURSES_H) || defined(MVWDELCH_IS_EXPRESSION) @@ -668,10 +668,10 @@ #else int py_mvwdelch(WINDOW *w, int y, int x) { - mvwdelch(w,y,x); - /* On HP/UX, mvwdelch already returns. On other systems, - we may well run into this return statement. */ - return 0; + mvwdelch(w,y,x); + /* On HP/UX, mvwdelch already returns. On other systems, + we may well run into this return statement. */ + return 0; } #endif @@ -680,603 +680,603 @@ static PyObject * PyCursesWindow_ChgAt(PyCursesWindowObject *self, PyObject *args) { - int rtn; - int x, y; - int num = -1; - short color; - attr_t attr = A_NORMAL; - long lattr; - int use_xy = FALSE; + int rtn; + int x, y; + int num = -1; + short color; + attr_t attr = A_NORMAL; + long lattr; + int use_xy = FALSE; - switch (PyTuple_Size(args)) { - case 1: - if (!PyArg_ParseTuple(args,"l;attr", &lattr)) - return NULL; - attr = lattr; - break; - case 2: - if (!PyArg_ParseTuple(args,"il;n,attr", &num, &lattr)) - return NULL; - attr = lattr; - break; - case 3: - if (!PyArg_ParseTuple(args,"iil;int,int,attr", &y, &x, &lattr)) - return NULL; - attr = lattr; - use_xy = TRUE; - break; - case 4: - if (!PyArg_ParseTuple(args,"iiil;int,int,n,attr", &y, &x, &num, &lattr)) - return NULL; - attr = lattr; - use_xy = TRUE; - break; - default: - PyErr_SetString(PyExc_TypeError, "chgat requires 1 to 4 arguments"); - return NULL; - } - - color = (short)((attr >> 8) & 0xff); - attr = attr - (color << 8); - - if (use_xy == TRUE) { - rtn = mvwchgat(self->win,y,x,num,attr,color,NULL); - touchline(self->win,y,1); - } else { - getyx(self->win,y,x); - rtn = wchgat(self->win,num,attr,color,NULL); - touchline(self->win,y,1); - } - return PyCursesCheckERR(rtn, "chgat"); + switch (PyTuple_Size(args)) { + case 1: + if (!PyArg_ParseTuple(args,"l;attr", &lattr)) + return NULL; + attr = lattr; + break; + case 2: + if (!PyArg_ParseTuple(args,"il;n,attr", &num, &lattr)) + return NULL; + attr = lattr; + break; + case 3: + if (!PyArg_ParseTuple(args,"iil;int,int,attr", &y, &x, &lattr)) + return NULL; + attr = lattr; + use_xy = TRUE; + break; + case 4: + if (!PyArg_ParseTuple(args,"iiil;int,int,n,attr", &y, &x, &num, &lattr)) + return NULL; + attr = lattr; + use_xy = TRUE; + break; + default: + PyErr_SetString(PyExc_TypeError, "chgat requires 1 to 4 arguments"); + return NULL; + } + + color = (short)((attr >> 8) & 0xff); + attr = attr - (color << 8); + + if (use_xy == TRUE) { + rtn = mvwchgat(self->win,y,x,num,attr,color,NULL); + touchline(self->win,y,1); + } else { + getyx(self->win,y,x); + rtn = wchgat(self->win,num,attr,color,NULL); + touchline(self->win,y,1); + } + return PyCursesCheckERR(rtn, "chgat"); } static PyObject * PyCursesWindow_DelCh(PyCursesWindowObject *self, PyObject *args) { - int rtn; - int x, y; + int rtn; + int x, y; - switch (PyTuple_Size(args)) { - case 0: - rtn = wdelch(self->win); - break; - case 2: - if (!PyArg_ParseTuple(args,"ii;y,x", &y, &x)) - return NULL; - rtn = py_mvwdelch(self->win,y,x); - break; - default: - PyErr_SetString(PyExc_TypeError, "delch requires 0 or 2 arguments"); - return NULL; - } - return PyCursesCheckERR(rtn, "[mv]wdelch"); + switch (PyTuple_Size(args)) { + case 0: + rtn = wdelch(self->win); + break; + case 2: + if (!PyArg_ParseTuple(args,"ii;y,x", &y, &x)) + return NULL; + rtn = py_mvwdelch(self->win,y,x); + break; + default: + PyErr_SetString(PyExc_TypeError, "delch requires 0 or 2 arguments"); + return NULL; + } + return PyCursesCheckERR(rtn, "[mv]wdelch"); } static PyObject * PyCursesWindow_DerWin(PyCursesWindowObject *self, PyObject *args) { - WINDOW *win; - int nlines, ncols, begin_y, begin_x; + WINDOW *win; + int nlines, ncols, begin_y, begin_x; - nlines = 0; - ncols = 0; - switch (PyTuple_Size(args)) { - case 2: - if (!PyArg_ParseTuple(args,"ii;begin_y,begin_x",&begin_y,&begin_x)) - return NULL; - break; - case 4: - if (!PyArg_ParseTuple(args, "iiii;nlines,ncols,begin_y,begin_x", - &nlines,&ncols,&begin_y,&begin_x)) - return NULL; - break; - default: - PyErr_SetString(PyExc_TypeError, "derwin requires 2 or 4 arguments"); - return NULL; - } - - win = derwin(self->win,nlines,ncols,begin_y,begin_x); - - if (win == NULL) { - PyErr_SetString(PyCursesError, catchall_NULL); - return NULL; - } + nlines = 0; + ncols = 0; + switch (PyTuple_Size(args)) { + case 2: + if (!PyArg_ParseTuple(args,"ii;begin_y,begin_x",&begin_y,&begin_x)) + return NULL; + break; + case 4: + if (!PyArg_ParseTuple(args, "iiii;nlines,ncols,begin_y,begin_x", + &nlines,&ncols,&begin_y,&begin_x)) + return NULL; + break; + default: + PyErr_SetString(PyExc_TypeError, "derwin requires 2 or 4 arguments"); + return NULL; + } - return (PyObject *)PyCursesWindow_New(win); + win = derwin(self->win,nlines,ncols,begin_y,begin_x); + + if (win == NULL) { + PyErr_SetString(PyCursesError, catchall_NULL); + return NULL; + } + + return (PyObject *)PyCursesWindow_New(win); } static PyObject * PyCursesWindow_EchoChar(PyCursesWindowObject *self, PyObject *args) { - PyObject *temp; - chtype ch; - attr_t attr = A_NORMAL; - long lattr; - - switch (PyTuple_Size(args)) { - case 1: - if (!PyArg_ParseTuple(args,"O;ch or int", &temp)) - return NULL; - break; - case 2: - if (!PyArg_ParseTuple(args,"Ol;ch or int,attr", &temp, &lattr)) - return NULL; - attr = lattr; - break; - default: - PyErr_SetString(PyExc_TypeError, "echochar requires 1 or 2 arguments"); - - - return NULL; - } - - if (!PyCurses_ConvertToChtype(temp, &ch)) { - PyErr_SetString(PyExc_TypeError, "argument 1 must be a ch or an int"); - return NULL; - } - + PyObject *temp; + chtype ch; + attr_t attr = A_NORMAL; + long lattr; + + switch (PyTuple_Size(args)) { + case 1: + if (!PyArg_ParseTuple(args,"O;ch or int", &temp)) + return NULL; + break; + case 2: + if (!PyArg_ParseTuple(args,"Ol;ch or int,attr", &temp, &lattr)) + return NULL; + attr = lattr; + break; + default: + PyErr_SetString(PyExc_TypeError, "echochar requires 1 or 2 arguments"); + + + return NULL; + } + + if (!PyCurses_ConvertToChtype(temp, &ch)) { + PyErr_SetString(PyExc_TypeError, "argument 1 must be a ch or an int"); + return NULL; + } + #ifdef WINDOW_HAS_FLAGS - if (self->win->_flags & _ISPAD) - return PyCursesCheckERR(pechochar(self->win, ch | attr), - "echochar"); - else + if (self->win->_flags & _ISPAD) + return PyCursesCheckERR(pechochar(self->win, ch | attr), + "echochar"); + else #endif - return PyCursesCheckERR(wechochar(self->win, ch | attr), - "echochar"); + return PyCursesCheckERR(wechochar(self->win, ch | attr), + "echochar"); } #ifdef NCURSES_MOUSE_VERSION static PyObject * PyCursesWindow_Enclose(PyCursesWindowObject *self, PyObject *args) { - int x, y; - if (!PyArg_ParseTuple(args,"ii;y,x", &y, &x)) - return NULL; + int x, y; + if (!PyArg_ParseTuple(args,"ii;y,x", &y, &x)) + return NULL; - return PyLong_FromLong( wenclose(self->win,y,x) ); + return PyLong_FromLong( wenclose(self->win,y,x) ); } #endif static PyObject * PyCursesWindow_GetBkgd(PyCursesWindowObject *self) { - return PyLong_FromLong((long) getbkgd(self->win)); + return PyLong_FromLong((long) getbkgd(self->win)); } static PyObject * PyCursesWindow_GetCh(PyCursesWindowObject *self, PyObject *args) { - int x, y; - int rtn; + int x, y; + int rtn; - switch (PyTuple_Size(args)) { - case 0: - Py_BEGIN_ALLOW_THREADS - rtn = wgetch(self->win); - Py_END_ALLOW_THREADS - break; - case 2: - if (!PyArg_ParseTuple(args,"ii;y,x",&y,&x)) - return NULL; - Py_BEGIN_ALLOW_THREADS - rtn = mvwgetch(self->win,y,x); - Py_END_ALLOW_THREADS - break; - default: - PyErr_SetString(PyExc_TypeError, "getch requires 0 or 2 arguments"); - return NULL; - } - return PyLong_FromLong((long)rtn); + switch (PyTuple_Size(args)) { + case 0: + Py_BEGIN_ALLOW_THREADS + rtn = wgetch(self->win); + Py_END_ALLOW_THREADS + break; + case 2: + if (!PyArg_ParseTuple(args,"ii;y,x",&y,&x)) + return NULL; + Py_BEGIN_ALLOW_THREADS + rtn = mvwgetch(self->win,y,x); + Py_END_ALLOW_THREADS + break; + default: + PyErr_SetString(PyExc_TypeError, "getch requires 0 or 2 arguments"); + return NULL; + } + return PyLong_FromLong((long)rtn); } static PyObject * PyCursesWindow_GetKey(PyCursesWindowObject *self, PyObject *args) { - int x, y; - int rtn; + int x, y; + int rtn; - switch (PyTuple_Size(args)) { - case 0: - Py_BEGIN_ALLOW_THREADS - rtn = wgetch(self->win); - Py_END_ALLOW_THREADS - break; - case 2: - if (!PyArg_ParseTuple(args,"ii;y,x",&y,&x)) - return NULL; - Py_BEGIN_ALLOW_THREADS - rtn = mvwgetch(self->win,y,x); - Py_END_ALLOW_THREADS - break; - default: - PyErr_SetString(PyExc_TypeError, "getkey requires 0 or 2 arguments"); - return NULL; - } - if (rtn == ERR) { - /* getch() returns ERR in nodelay mode */ - PyErr_SetString(PyCursesError, "no input"); - return NULL; - } else if (rtn<=255) { - return Py_BuildValue("C", rtn); - } else { - const char *knp; + switch (PyTuple_Size(args)) { + case 0: + Py_BEGIN_ALLOW_THREADS + rtn = wgetch(self->win); + Py_END_ALLOW_THREADS + break; + case 2: + if (!PyArg_ParseTuple(args,"ii;y,x",&y,&x)) + return NULL; + Py_BEGIN_ALLOW_THREADS + rtn = mvwgetch(self->win,y,x); + Py_END_ALLOW_THREADS + break; + default: + PyErr_SetString(PyExc_TypeError, "getkey requires 0 or 2 arguments"); + return NULL; + } + if (rtn == ERR) { + /* getch() returns ERR in nodelay mode */ + PyErr_SetString(PyCursesError, "no input"); + return NULL; + } else if (rtn<=255) { + return Py_BuildValue("C", rtn); + } else { + const char *knp; #if defined(__NetBSD__) - knp = unctrl(rtn); + knp = unctrl(rtn); #else - knp = keyname(rtn); + knp = keyname(rtn); #endif - return PyUnicode_FromString((knp == NULL) ? "" : knp); - } + return PyUnicode_FromString((knp == NULL) ? "" : knp); + } } static PyObject * PyCursesWindow_GetStr(PyCursesWindowObject *self, PyObject *args) { - int x, y, n; - char rtn[1024]; /* This should be big enough.. I hope */ - int rtn2; - - switch (PyTuple_Size(args)) { - case 0: - Py_BEGIN_ALLOW_THREADS - rtn2 = wgetnstr(self->win,rtn, 1023); - Py_END_ALLOW_THREADS - break; - case 1: - if (!PyArg_ParseTuple(args,"i;n", &n)) - return NULL; - Py_BEGIN_ALLOW_THREADS - rtn2 = wgetnstr(self->win,rtn,MIN(n, 1023)); - Py_END_ALLOW_THREADS - break; - case 2: - if (!PyArg_ParseTuple(args,"ii;y,x",&y,&x)) - return NULL; - Py_BEGIN_ALLOW_THREADS + int x, y, n; + char rtn[1024]; /* This should be big enough.. I hope */ + int rtn2; + + switch (PyTuple_Size(args)) { + case 0: + Py_BEGIN_ALLOW_THREADS + rtn2 = wgetnstr(self->win,rtn, 1023); + Py_END_ALLOW_THREADS + break; + case 1: + if (!PyArg_ParseTuple(args,"i;n", &n)) + return NULL; + Py_BEGIN_ALLOW_THREADS + rtn2 = wgetnstr(self->win,rtn,MIN(n, 1023)); + Py_END_ALLOW_THREADS + break; + case 2: + if (!PyArg_ParseTuple(args,"ii;y,x",&y,&x)) + return NULL; + Py_BEGIN_ALLOW_THREADS #ifdef STRICT_SYSV_CURSES - rtn2 = wmove(self->win,y,x)==ERR ? ERR : wgetnstr(self->win, rtn, 1023); + rtn2 = wmove(self->win,y,x)==ERR ? ERR : wgetnstr(self->win, rtn, 1023); #else - rtn2 = mvwgetnstr(self->win,y,x,rtn, 1023); + rtn2 = mvwgetnstr(self->win,y,x,rtn, 1023); #endif - Py_END_ALLOW_THREADS - break; - case 3: - if (!PyArg_ParseTuple(args,"iii;y,x,n", &y, &x, &n)) - return NULL; + Py_END_ALLOW_THREADS + break; + case 3: + if (!PyArg_ParseTuple(args,"iii;y,x,n", &y, &x, &n)) + return NULL; #ifdef STRICT_SYSV_CURSES - Py_BEGIN_ALLOW_THREADS - rtn2 = wmove(self->win,y,x)==ERR ? ERR : - wgetnstr(self->win, rtn, MIN(n, 1023)); - Py_END_ALLOW_THREADS + Py_BEGIN_ALLOW_THREADS + rtn2 = wmove(self->win,y,x)==ERR ? ERR : + wgetnstr(self->win, rtn, MIN(n, 1023)); + Py_END_ALLOW_THREADS #else - Py_BEGIN_ALLOW_THREADS - rtn2 = mvwgetnstr(self->win, y, x, rtn, MIN(n, 1023)); - Py_END_ALLOW_THREADS -#endif - break; - default: - PyErr_SetString(PyExc_TypeError, "getstr requires 0 to 3 arguments"); - return NULL; - } - if (rtn2 == ERR) - rtn[0] = 0; - return PyBytes_FromString(rtn); + Py_BEGIN_ALLOW_THREADS + rtn2 = mvwgetnstr(self->win, y, x, rtn, MIN(n, 1023)); + Py_END_ALLOW_THREADS +#endif + break; + default: + PyErr_SetString(PyExc_TypeError, "getstr requires 0 to 3 arguments"); + return NULL; + } + if (rtn2 == ERR) + rtn[0] = 0; + return PyBytes_FromString(rtn); } static PyObject * PyCursesWindow_Hline(PyCursesWindowObject *self, PyObject *args) { - PyObject *temp; - chtype ch; - int n, x, y, code = OK; - attr_t attr = A_NORMAL; - long lattr; - - switch (PyTuple_Size(args)) { - case 2: - if (!PyArg_ParseTuple(args, "Oi;ch or int,n", &temp, &n)) - return NULL; - break; - case 3: - if (!PyArg_ParseTuple(args, "Oil;ch or int,n,attr", &temp, &n, &lattr)) - return NULL; - attr = lattr; - break; - case 4: - if (!PyArg_ParseTuple(args, "iiOi;y,x,ch or int,n", &y, &x, &temp, &n)) - return NULL; - code = wmove(self->win, y, x); - break; - case 5: - if (!PyArg_ParseTuple(args, "iiOil; y,x,ch or int,n,attr", - &y, &x, &temp, &n, &lattr)) - return NULL; - attr = lattr; - code = wmove(self->win, y, x); - break; - default: - PyErr_SetString(PyExc_TypeError, "hline requires 2 to 5 arguments"); - return NULL; - } + PyObject *temp; + chtype ch; + int n, x, y, code = OK; + attr_t attr = A_NORMAL; + long lattr; - if (code != ERR) { - if (!PyCurses_ConvertToChtype(temp, &ch)) { - PyErr_SetString(PyExc_TypeError, - "argument 1 or 3 must be a ch or an int"); - return NULL; - } - return PyCursesCheckERR(whline(self->win, ch | attr, n), "hline"); - } else - return PyCursesCheckERR(code, "wmove"); + switch (PyTuple_Size(args)) { + case 2: + if (!PyArg_ParseTuple(args, "Oi;ch or int,n", &temp, &n)) + return NULL; + break; + case 3: + if (!PyArg_ParseTuple(args, "Oil;ch or int,n,attr", &temp, &n, &lattr)) + return NULL; + attr = lattr; + break; + case 4: + if (!PyArg_ParseTuple(args, "iiOi;y,x,ch or int,n", &y, &x, &temp, &n)) + return NULL; + code = wmove(self->win, y, x); + break; + case 5: + if (!PyArg_ParseTuple(args, "iiOil; y,x,ch or int,n,attr", + &y, &x, &temp, &n, &lattr)) + return NULL; + attr = lattr; + code = wmove(self->win, y, x); + break; + default: + PyErr_SetString(PyExc_TypeError, "hline requires 2 to 5 arguments"); + return NULL; + } + + if (code != ERR) { + if (!PyCurses_ConvertToChtype(temp, &ch)) { + PyErr_SetString(PyExc_TypeError, + "argument 1 or 3 must be a ch or an int"); + return NULL; + } + return PyCursesCheckERR(whline(self->win, ch | attr, n), "hline"); + } else + return PyCursesCheckERR(code, "wmove"); } static PyObject * PyCursesWindow_InsCh(PyCursesWindowObject *self, PyObject *args) { - int rtn, x, y, use_xy = FALSE; - PyObject *temp; - chtype ch = 0; - attr_t attr = A_NORMAL; - long lattr; - - switch (PyTuple_Size(args)) { - case 1: - if (!PyArg_ParseTuple(args, "O;ch or int", &temp)) - return NULL; - break; - case 2: - if (!PyArg_ParseTuple(args, "Ol;ch or int,attr", &temp, &lattr)) - return NULL; - attr = lattr; - break; - case 3: - if (!PyArg_ParseTuple(args,"iiO;y,x,ch or int", &y, &x, &temp)) - return NULL; - use_xy = TRUE; - break; - case 4: - if (!PyArg_ParseTuple(args,"iiOl;y,x,ch or int, attr", &y, &x, &temp, &lattr)) - return NULL; - attr = lattr; - use_xy = TRUE; - break; - default: - PyErr_SetString(PyExc_TypeError, "insch requires 1 or 4 arguments"); - return NULL; - } - - if (!PyCurses_ConvertToChtype(temp, &ch)) { - PyErr_SetString(PyExc_TypeError, - "argument 1 or 3 must be a ch or an int"); - return NULL; - } - - if (use_xy == TRUE) - rtn = mvwinsch(self->win,y,x, ch | attr); - else { - rtn = winsch(self->win, ch | attr); - } - return PyCursesCheckERR(rtn, "insch"); + int rtn, x, y, use_xy = FALSE; + PyObject *temp; + chtype ch = 0; + attr_t attr = A_NORMAL; + long lattr; + + switch (PyTuple_Size(args)) { + case 1: + if (!PyArg_ParseTuple(args, "O;ch or int", &temp)) + return NULL; + break; + case 2: + if (!PyArg_ParseTuple(args, "Ol;ch or int,attr", &temp, &lattr)) + return NULL; + attr = lattr; + break; + case 3: + if (!PyArg_ParseTuple(args,"iiO;y,x,ch or int", &y, &x, &temp)) + return NULL; + use_xy = TRUE; + break; + case 4: + if (!PyArg_ParseTuple(args,"iiOl;y,x,ch or int, attr", &y, &x, &temp, &lattr)) + return NULL; + attr = lattr; + use_xy = TRUE; + break; + default: + PyErr_SetString(PyExc_TypeError, "insch requires 1 or 4 arguments"); + return NULL; + } + + if (!PyCurses_ConvertToChtype(temp, &ch)) { + PyErr_SetString(PyExc_TypeError, + "argument 1 or 3 must be a ch or an int"); + return NULL; + } + + if (use_xy == TRUE) + rtn = mvwinsch(self->win,y,x, ch | attr); + else { + rtn = winsch(self->win, ch | attr); + } + return PyCursesCheckERR(rtn, "insch"); } static PyObject * PyCursesWindow_InCh(PyCursesWindowObject *self, PyObject *args) { - int x, y, rtn; + int x, y, rtn; - switch (PyTuple_Size(args)) { - case 0: - rtn = winch(self->win); - break; - case 2: - if (!PyArg_ParseTuple(args,"ii;y,x",&y,&x)) - return NULL; - rtn = mvwinch(self->win,y,x); - break; - default: - PyErr_SetString(PyExc_TypeError, "inch requires 0 or 2 arguments"); - return NULL; - } - return PyLong_FromLong((long) rtn); + switch (PyTuple_Size(args)) { + case 0: + rtn = winch(self->win); + break; + case 2: + if (!PyArg_ParseTuple(args,"ii;y,x",&y,&x)) + return NULL; + rtn = mvwinch(self->win,y,x); + break; + default: + PyErr_SetString(PyExc_TypeError, "inch requires 0 or 2 arguments"); + return NULL; + } + return PyLong_FromLong((long) rtn); } static PyObject * PyCursesWindow_InStr(PyCursesWindowObject *self, PyObject *args) { - int x, y, n; - char rtn[1024]; /* This should be big enough.. I hope */ - int rtn2; - - switch (PyTuple_Size(args)) { - case 0: - rtn2 = winnstr(self->win,rtn, 1023); - break; - case 1: - if (!PyArg_ParseTuple(args,"i;n", &n)) - return NULL; - rtn2 = winnstr(self->win,rtn,MIN(n,1023)); - break; - case 2: - if (!PyArg_ParseTuple(args,"ii;y,x",&y,&x)) - return NULL; - rtn2 = mvwinnstr(self->win,y,x,rtn,1023); - break; - case 3: - if (!PyArg_ParseTuple(args, "iii;y,x,n", &y, &x, &n)) - return NULL; - rtn2 = mvwinnstr(self->win, y, x, rtn, MIN(n,1023)); - break; - default: - PyErr_SetString(PyExc_TypeError, "instr requires 0 or 3 arguments"); - return NULL; - } - if (rtn2 == ERR) - rtn[0] = 0; - return PyBytes_FromString(rtn); + int x, y, n; + char rtn[1024]; /* This should be big enough.. I hope */ + int rtn2; + + switch (PyTuple_Size(args)) { + case 0: + rtn2 = winnstr(self->win,rtn, 1023); + break; + case 1: + if (!PyArg_ParseTuple(args,"i;n", &n)) + return NULL; + rtn2 = winnstr(self->win,rtn,MIN(n,1023)); + break; + case 2: + if (!PyArg_ParseTuple(args,"ii;y,x",&y,&x)) + return NULL; + rtn2 = mvwinnstr(self->win,y,x,rtn,1023); + break; + case 3: + if (!PyArg_ParseTuple(args, "iii;y,x,n", &y, &x, &n)) + return NULL; + rtn2 = mvwinnstr(self->win, y, x, rtn, MIN(n,1023)); + break; + default: + PyErr_SetString(PyExc_TypeError, "instr requires 0 or 3 arguments"); + return NULL; + } + if (rtn2 == ERR) + rtn[0] = 0; + return PyBytes_FromString(rtn); } static PyObject * PyCursesWindow_InsStr(PyCursesWindowObject *self, PyObject *args) { - int rtn; - int x, y; - char *str; - attr_t attr = A_NORMAL , attr_old = A_NORMAL; - long lattr; - int use_xy = FALSE, use_attr = FALSE; - - switch (PyTuple_Size(args)) { - case 1: - if (!PyArg_ParseTuple(args,"s;str", &str)) - return NULL; - break; - case 2: - if (!PyArg_ParseTuple(args,"sl;str,attr", &str, &lattr)) - return NULL; - attr = lattr; - use_attr = TRUE; - break; - case 3: - if (!PyArg_ParseTuple(args,"iis;y,x,str", &y, &x, &str)) - return NULL; - use_xy = TRUE; - break; - case 4: - if (!PyArg_ParseTuple(args,"iisl;y,x,str,attr", &y, &x, &str, &lattr)) - return NULL; - attr = lattr; - use_xy = use_attr = TRUE; - break; - default: - PyErr_SetString(PyExc_TypeError, "insstr requires 1 to 4 arguments"); - return NULL; - } - - if (use_attr == TRUE) { - attr_old = getattrs(self->win); - (void)wattrset(self->win,attr); - } - if (use_xy == TRUE) - rtn = mvwinsstr(self->win,y,x,str); - else - rtn = winsstr(self->win,str); - if (use_attr == TRUE) - (void)wattrset(self->win,attr_old); - return PyCursesCheckERR(rtn, "insstr"); + int rtn; + int x, y; + char *str; + attr_t attr = A_NORMAL , attr_old = A_NORMAL; + long lattr; + int use_xy = FALSE, use_attr = FALSE; + + switch (PyTuple_Size(args)) { + case 1: + if (!PyArg_ParseTuple(args,"s;str", &str)) + return NULL; + break; + case 2: + if (!PyArg_ParseTuple(args,"sl;str,attr", &str, &lattr)) + return NULL; + attr = lattr; + use_attr = TRUE; + break; + case 3: + if (!PyArg_ParseTuple(args,"iis;y,x,str", &y, &x, &str)) + return NULL; + use_xy = TRUE; + break; + case 4: + if (!PyArg_ParseTuple(args,"iisl;y,x,str,attr", &y, &x, &str, &lattr)) + return NULL; + attr = lattr; + use_xy = use_attr = TRUE; + break; + default: + PyErr_SetString(PyExc_TypeError, "insstr requires 1 to 4 arguments"); + return NULL; + } + + if (use_attr == TRUE) { + attr_old = getattrs(self->win); + (void)wattrset(self->win,attr); + } + if (use_xy == TRUE) + rtn = mvwinsstr(self->win,y,x,str); + else + rtn = winsstr(self->win,str); + if (use_attr == TRUE) + (void)wattrset(self->win,attr_old); + return PyCursesCheckERR(rtn, "insstr"); } static PyObject * PyCursesWindow_InsNStr(PyCursesWindowObject *self, PyObject *args) { - int rtn, x, y, n; - char *str; - attr_t attr = A_NORMAL , attr_old = A_NORMAL; - long lattr; - int use_xy = FALSE, use_attr = FALSE; - - switch (PyTuple_Size(args)) { - case 2: - if (!PyArg_ParseTuple(args,"si;str,n", &str, &n)) - return NULL; - break; - case 3: - if (!PyArg_ParseTuple(args,"sil;str,n,attr", &str, &n, &lattr)) - return NULL; - attr = lattr; - use_attr = TRUE; - break; - case 4: - if (!PyArg_ParseTuple(args,"iisi;y,x,str,n", &y, &x, &str, &n)) - return NULL; - use_xy = TRUE; - break; - case 5: - if (!PyArg_ParseTuple(args,"iisil;y,x,str,n,attr", &y, &x, &str, &n, &lattr)) - return NULL; - attr = lattr; - use_xy = use_attr = TRUE; - break; - default: - PyErr_SetString(PyExc_TypeError, "insnstr requires 2 to 5 arguments"); - return NULL; - } - - if (use_attr == TRUE) { - attr_old = getattrs(self->win); - (void)wattrset(self->win,attr); - } - if (use_xy == TRUE) - rtn = mvwinsnstr(self->win,y,x,str,n); - else - rtn = winsnstr(self->win,str,n); - if (use_attr == TRUE) - (void)wattrset(self->win,attr_old); - return PyCursesCheckERR(rtn, "insnstr"); + int rtn, x, y, n; + char *str; + attr_t attr = A_NORMAL , attr_old = A_NORMAL; + long lattr; + int use_xy = FALSE, use_attr = FALSE; + + switch (PyTuple_Size(args)) { + case 2: + if (!PyArg_ParseTuple(args,"si;str,n", &str, &n)) + return NULL; + break; + case 3: + if (!PyArg_ParseTuple(args,"sil;str,n,attr", &str, &n, &lattr)) + return NULL; + attr = lattr; + use_attr = TRUE; + break; + case 4: + if (!PyArg_ParseTuple(args,"iisi;y,x,str,n", &y, &x, &str, &n)) + return NULL; + use_xy = TRUE; + break; + case 5: + if (!PyArg_ParseTuple(args,"iisil;y,x,str,n,attr", &y, &x, &str, &n, &lattr)) + return NULL; + attr = lattr; + use_xy = use_attr = TRUE; + break; + default: + PyErr_SetString(PyExc_TypeError, "insnstr requires 2 to 5 arguments"); + return NULL; + } + + if (use_attr == TRUE) { + attr_old = getattrs(self->win); + (void)wattrset(self->win,attr); + } + if (use_xy == TRUE) + rtn = mvwinsnstr(self->win,y,x,str,n); + else + rtn = winsnstr(self->win,str,n); + if (use_attr == TRUE) + (void)wattrset(self->win,attr_old); + return PyCursesCheckERR(rtn, "insnstr"); } static PyObject * PyCursesWindow_Is_LineTouched(PyCursesWindowObject *self, PyObject *args) { - int line, erg; - if (!PyArg_ParseTuple(args,"i;line", &line)) - return NULL; - erg = is_linetouched(self->win, line); - if (erg == ERR) { - PyErr_SetString(PyExc_TypeError, - "is_linetouched: line number outside of boundaries"); - return NULL; - } else - if (erg == FALSE) { - Py_INCREF(Py_False); - return Py_False; - } else { - Py_INCREF(Py_True); - return Py_True; - } + int line, erg; + if (!PyArg_ParseTuple(args,"i;line", &line)) + return NULL; + erg = is_linetouched(self->win, line); + if (erg == ERR) { + PyErr_SetString(PyExc_TypeError, + "is_linetouched: line number outside of boundaries"); + return NULL; + } else + if (erg == FALSE) { + Py_INCREF(Py_False); + return Py_False; + } else { + Py_INCREF(Py_True); + return Py_True; + } } static PyObject * PyCursesWindow_NoOutRefresh(PyCursesWindowObject *self, PyObject *args) { - int pminrow,pmincol,sminrow,smincol,smaxrow,smaxcol; - int rtn; + int pminrow,pmincol,sminrow,smincol,smaxrow,smaxcol; + int rtn; #ifndef WINDOW_HAS_FLAGS - if (0) + if (0) #else - if (self->win->_flags & _ISPAD) + if (self->win->_flags & _ISPAD) #endif - { - switch(PyTuple_Size(args)) { - case 6: - if (!PyArg_ParseTuple(args, - "iiiiii;" \ - "pminrow,pmincol,sminrow,smincol,smaxrow,smaxcol", - &pminrow, &pmincol, &sminrow, - &smincol, &smaxrow, &smaxcol)) - return NULL; - Py_BEGIN_ALLOW_THREADS - rtn = pnoutrefresh(self->win, - pminrow, pmincol, sminrow, - smincol, smaxrow, smaxcol); - Py_END_ALLOW_THREADS - return PyCursesCheckERR(rtn, "pnoutrefresh"); - default: - PyErr_SetString(PyCursesError, - "noutrefresh() called for a pad " - "requires 6 arguments"); - return NULL; - } - } else { - if (!PyArg_ParseTuple(args, ":noutrefresh")) - return NULL; - - Py_BEGIN_ALLOW_THREADS - rtn = wnoutrefresh(self->win); - Py_END_ALLOW_THREADS - return PyCursesCheckERR(rtn, "wnoutrefresh"); - } + { + switch(PyTuple_Size(args)) { + case 6: + if (!PyArg_ParseTuple(args, + "iiiiii;" \ + "pminrow,pmincol,sminrow,smincol,smaxrow,smaxcol", + &pminrow, &pmincol, &sminrow, + &smincol, &smaxrow, &smaxcol)) + return NULL; + Py_BEGIN_ALLOW_THREADS + rtn = pnoutrefresh(self->win, + pminrow, pmincol, sminrow, + smincol, smaxrow, smaxcol); + Py_END_ALLOW_THREADS + return PyCursesCheckERR(rtn, "pnoutrefresh"); + default: + PyErr_SetString(PyCursesError, + "noutrefresh() called for a pad " + "requires 6 arguments"); + return NULL; + } + } else { + if (!PyArg_ParseTuple(args, ":noutrefresh")) + return NULL; + + Py_BEGIN_ALLOW_THREADS + rtn = wnoutrefresh(self->win); + Py_END_ALLOW_THREADS + return PyCursesCheckERR(rtn, "wnoutrefresh"); + } } static PyObject * @@ -1286,34 +1286,34 @@ int use_copywin = FALSE; int sminrow, smincol, dminrow, dmincol, dmaxrow, dmaxcol; int rtn; - + switch (PyTuple_Size(args)) { case 1: - if (!PyArg_ParseTuple(args, "O!;window object", - &PyCursesWindow_Type, &temp)) - return NULL; - break; + if (!PyArg_ParseTuple(args, "O!;window object", + &PyCursesWindow_Type, &temp)) + return NULL; + break; case 7: - if (!PyArg_ParseTuple(args, "O!iiiiii;window object, int, int, int, int, int, int", - &PyCursesWindow_Type, &temp, &sminrow, &smincol, - &dminrow, &dmincol, &dmaxrow, &dmaxcol)) - return NULL; - use_copywin = TRUE; - break; - default: - PyErr_SetString(PyExc_TypeError, - "overlay requires one or seven arguments"); - return NULL; + if (!PyArg_ParseTuple(args, "O!iiiiii;window object, int, int, int, int, int, int", + &PyCursesWindow_Type, &temp, &sminrow, &smincol, + &dminrow, &dmincol, &dmaxrow, &dmaxcol)) + return NULL; + use_copywin = TRUE; + break; + default: + PyErr_SetString(PyExc_TypeError, + "overlay requires one or seven arguments"); + return NULL; } if (use_copywin == TRUE) { - rtn = copywin(self->win, temp->win, sminrow, smincol, - dminrow, dmincol, dmaxrow, dmaxcol, TRUE); - return PyCursesCheckERR(rtn, "copywin"); + rtn = copywin(self->win, temp->win, sminrow, smincol, + dminrow, dmincol, dmaxrow, dmaxcol, TRUE); + return PyCursesCheckERR(rtn, "copywin"); } else { - rtn = overlay(self->win, temp->win); - return PyCursesCheckERR(rtn, "overlay"); + rtn = overlay(self->win, temp->win); + return PyCursesCheckERR(rtn, "overlay"); } } @@ -1324,377 +1324,377 @@ int use_copywin = FALSE; int sminrow, smincol, dminrow, dmincol, dmaxrow, dmaxcol; int rtn; - + switch (PyTuple_Size(args)) { case 1: - if (!PyArg_ParseTuple(args, "O!;window object", - &PyCursesWindow_Type, &temp)) - return NULL; - break; + if (!PyArg_ParseTuple(args, "O!;window object", + &PyCursesWindow_Type, &temp)) + return NULL; + break; case 7: - if (!PyArg_ParseTuple(args, "O!iiiiii;window object, int, int, int, int, int, int", - &PyCursesWindow_Type, &temp, &sminrow, &smincol, - &dminrow, &dmincol, &dmaxrow, &dmaxcol)) - return NULL; - use_copywin = TRUE; - break; - default: - PyErr_SetString(PyExc_TypeError, - "overwrite requires one or seven arguments"); - return NULL; + if (!PyArg_ParseTuple(args, "O!iiiiii;window object, int, int, int, int, int, int", + &PyCursesWindow_Type, &temp, &sminrow, &smincol, + &dminrow, &dmincol, &dmaxrow, &dmaxcol)) + return NULL; + use_copywin = TRUE; + break; + default: + PyErr_SetString(PyExc_TypeError, + "overwrite requires one or seven arguments"); + return NULL; } if (use_copywin == TRUE) { - rtn = copywin(self->win, temp->win, sminrow, smincol, - dminrow, dmincol, dmaxrow, dmaxcol, FALSE); + rtn = copywin(self->win, temp->win, sminrow, smincol, + dminrow, dmincol, dmaxrow, dmaxcol, FALSE); return PyCursesCheckERR(rtn, "copywin"); } else { - rtn = overwrite(self->win, temp->win); - return PyCursesCheckERR(rtn, "overwrite"); + rtn = overwrite(self->win, temp->win); + return PyCursesCheckERR(rtn, "overwrite"); } } static PyObject * PyCursesWindow_PutWin(PyCursesWindowObject *self, PyObject *stream) { - /* We have to simulate this by writing to a temporary FILE*, - then reading back, then writing to the argument stream. */ - char fn[100]; - int fd; - FILE *fp; - PyObject *res; - - strcpy(fn, "/tmp/py.curses.putwin.XXXXXX"); - fd = mkstemp(fn); - if (fd < 0) - return PyErr_SetFromErrnoWithFilename(PyExc_IOError, fn); - fp = fdopen(fd, "wb+"); - if (fp == NULL) { - close(fd); - remove(fn); - return PyErr_SetFromErrnoWithFilename(PyExc_IOError, fn); - } - res = PyCursesCheckERR(putwin(self->win, fp), "putwin"); - if (res == NULL) { + /* We have to simulate this by writing to a temporary FILE*, + then reading back, then writing to the argument stream. */ + char fn[100]; + int fd; + FILE *fp; + PyObject *res; + + strcpy(fn, "/tmp/py.curses.putwin.XXXXXX"); + fd = mkstemp(fn); + if (fd < 0) + return PyErr_SetFromErrnoWithFilename(PyExc_IOError, fn); + fp = fdopen(fd, "wb+"); + if (fp == NULL) { + close(fd); + remove(fn); + return PyErr_SetFromErrnoWithFilename(PyExc_IOError, fn); + } + res = PyCursesCheckERR(putwin(self->win, fp), "putwin"); + if (res == NULL) { + fclose(fp); + remove(fn); + return res; + } + fseek(fp, 0, 0); + while (1) { + char buf[BUFSIZ]; + Py_ssize_t n = fread(buf, 1, BUFSIZ, fp); + if (n <= 0) + break; + Py_DECREF(res); + res = PyObject_CallMethod(stream, "write", "y#", buf, n); + if (res == NULL) + break; + } fclose(fp); remove(fn); return res; - } - fseek(fp, 0, 0); - while (1) { - char buf[BUFSIZ]; - Py_ssize_t n = fread(buf, 1, BUFSIZ, fp); - if (n <= 0) - break; - Py_DECREF(res); - res = PyObject_CallMethod(stream, "write", "y#", buf, n); - if (res == NULL) - break; - } - fclose(fp); - remove(fn); - return res; } static PyObject * PyCursesWindow_RedrawLine(PyCursesWindowObject *self, PyObject *args) { - int beg, num; - if (!PyArg_ParseTuple(args, "ii;beg,num", &beg, &num)) - return NULL; - return PyCursesCheckERR(wredrawln(self->win,beg,num), "redrawln"); + int beg, num; + if (!PyArg_ParseTuple(args, "ii;beg,num", &beg, &num)) + return NULL; + return PyCursesCheckERR(wredrawln(self->win,beg,num), "redrawln"); } static PyObject * PyCursesWindow_Refresh(PyCursesWindowObject *self, PyObject *args) { - int pminrow,pmincol,sminrow,smincol,smaxrow,smaxcol; - int rtn; - + int pminrow,pmincol,sminrow,smincol,smaxrow,smaxcol; + int rtn; + #ifndef WINDOW_HAS_FLAGS - if (0) + if (0) #else - if (self->win->_flags & _ISPAD) + if (self->win->_flags & _ISPAD) #endif - { - switch(PyTuple_Size(args)) { - case 6: - if (!PyArg_ParseTuple(args, - "iiiiii;" \ - "pminrow,pmincol,sminrow,smincol,smaxrow,smaxcol", - &pminrow, &pmincol, &sminrow, - &smincol, &smaxrow, &smaxcol)) - return NULL; - - Py_BEGIN_ALLOW_THREADS - rtn = prefresh(self->win, - pminrow, pmincol, sminrow, - smincol, smaxrow, smaxcol); - Py_END_ALLOW_THREADS - return PyCursesCheckERR(rtn, "prefresh"); - default: - PyErr_SetString(PyCursesError, - "refresh() for a pad requires 6 arguments"); - return NULL; - } - } else { - if (!PyArg_ParseTuple(args, ":refresh")) - return NULL; - Py_BEGIN_ALLOW_THREADS - rtn = wrefresh(self->win); - Py_END_ALLOW_THREADS - return PyCursesCheckERR(rtn, "prefresh"); - } + { + switch(PyTuple_Size(args)) { + case 6: + if (!PyArg_ParseTuple(args, + "iiiiii;" \ + "pminrow,pmincol,sminrow,smincol,smaxrow,smaxcol", + &pminrow, &pmincol, &sminrow, + &smincol, &smaxrow, &smaxcol)) + return NULL; + + Py_BEGIN_ALLOW_THREADS + rtn = prefresh(self->win, + pminrow, pmincol, sminrow, + smincol, smaxrow, smaxcol); + Py_END_ALLOW_THREADS + return PyCursesCheckERR(rtn, "prefresh"); + default: + PyErr_SetString(PyCursesError, + "refresh() for a pad requires 6 arguments"); + return NULL; + } + } else { + if (!PyArg_ParseTuple(args, ":refresh")) + return NULL; + Py_BEGIN_ALLOW_THREADS + rtn = wrefresh(self->win); + Py_END_ALLOW_THREADS + return PyCursesCheckERR(rtn, "prefresh"); + } } static PyObject * PyCursesWindow_SetScrollRegion(PyCursesWindowObject *self, PyObject *args) { - int x, y; - if (!PyArg_ParseTuple(args,"ii;top, bottom",&y,&x)) - return NULL; - return PyCursesCheckERR(wsetscrreg(self->win,y,x), "wsetscrreg"); + int x, y; + if (!PyArg_ParseTuple(args,"ii;top, bottom",&y,&x)) + return NULL; + return PyCursesCheckERR(wsetscrreg(self->win,y,x), "wsetscrreg"); } static PyObject * PyCursesWindow_SubWin(PyCursesWindowObject *self, PyObject *args) { - WINDOW *win; - int nlines, ncols, begin_y, begin_x; + WINDOW *win; + int nlines, ncols, begin_y, begin_x; - nlines = 0; - ncols = 0; - switch (PyTuple_Size(args)) { - case 2: - if (!PyArg_ParseTuple(args,"ii;begin_y,begin_x",&begin_y,&begin_x)) - return NULL; - break; - case 4: - if (!PyArg_ParseTuple(args, "iiii;nlines,ncols,begin_y,begin_x", - &nlines,&ncols,&begin_y,&begin_x)) - return NULL; - break; - default: - PyErr_SetString(PyExc_TypeError, "subwin requires 2 or 4 arguments"); - return NULL; - } + nlines = 0; + ncols = 0; + switch (PyTuple_Size(args)) { + case 2: + if (!PyArg_ParseTuple(args,"ii;begin_y,begin_x",&begin_y,&begin_x)) + return NULL; + break; + case 4: + if (!PyArg_ParseTuple(args, "iiii;nlines,ncols,begin_y,begin_x", + &nlines,&ncols,&begin_y,&begin_x)) + return NULL; + break; + default: + PyErr_SetString(PyExc_TypeError, "subwin requires 2 or 4 arguments"); + return NULL; + } - /* printf("Subwin: %i %i %i %i \n", nlines, ncols, begin_y, begin_x); */ + /* printf("Subwin: %i %i %i %i \n", nlines, ncols, begin_y, begin_x); */ #ifdef WINDOW_HAS_FLAGS - if (self->win->_flags & _ISPAD) - win = subpad(self->win, nlines, ncols, begin_y, begin_x); - else -#endif - win = subwin(self->win, nlines, ncols, begin_y, begin_x); - - if (win == NULL) { - PyErr_SetString(PyCursesError, catchall_NULL); - return NULL; - } - - return (PyObject *)PyCursesWindow_New(win); + if (self->win->_flags & _ISPAD) + win = subpad(self->win, nlines, ncols, begin_y, begin_x); + else +#endif + win = subwin(self->win, nlines, ncols, begin_y, begin_x); + + if (win == NULL) { + PyErr_SetString(PyCursesError, catchall_NULL); + return NULL; + } + + return (PyObject *)PyCursesWindow_New(win); } static PyObject * PyCursesWindow_Scroll(PyCursesWindowObject *self, PyObject *args) { - int nlines; - switch(PyTuple_Size(args)) { - case 0: - return PyCursesCheckERR(scroll(self->win), "scroll"); - case 1: - if (!PyArg_ParseTuple(args, "i;nlines", &nlines)) - return NULL; - return PyCursesCheckERR(wscrl(self->win, nlines), "scroll"); - default: - PyErr_SetString(PyExc_TypeError, "scroll requires 0 or 1 arguments"); - return NULL; - } + int nlines; + switch(PyTuple_Size(args)) { + case 0: + return PyCursesCheckERR(scroll(self->win), "scroll"); + case 1: + if (!PyArg_ParseTuple(args, "i;nlines", &nlines)) + return NULL; + return PyCursesCheckERR(wscrl(self->win, nlines), "scroll"); + default: + PyErr_SetString(PyExc_TypeError, "scroll requires 0 or 1 arguments"); + return NULL; + } } static PyObject * PyCursesWindow_TouchLine(PyCursesWindowObject *self, PyObject *args) { - int st, cnt, val; - switch (PyTuple_Size(args)) { - case 2: - if (!PyArg_ParseTuple(args,"ii;start,count",&st,&cnt)) - return NULL; - return PyCursesCheckERR(touchline(self->win,st,cnt), "touchline"); - case 3: - if (!PyArg_ParseTuple(args, "iii;start,count,val", &st, &cnt, &val)) - return NULL; - return PyCursesCheckERR(wtouchln(self->win, st, cnt, val), "touchline"); - default: - PyErr_SetString(PyExc_TypeError, "touchline requires 2 or 3 arguments"); - return NULL; - } + int st, cnt, val; + switch (PyTuple_Size(args)) { + case 2: + if (!PyArg_ParseTuple(args,"ii;start,count",&st,&cnt)) + return NULL; + return PyCursesCheckERR(touchline(self->win,st,cnt), "touchline"); + case 3: + if (!PyArg_ParseTuple(args, "iii;start,count,val", &st, &cnt, &val)) + return NULL; + return PyCursesCheckERR(wtouchln(self->win, st, cnt, val), "touchline"); + default: + PyErr_SetString(PyExc_TypeError, "touchline requires 2 or 3 arguments"); + return NULL; + } } static PyObject * PyCursesWindow_Vline(PyCursesWindowObject *self, PyObject *args) { - PyObject *temp; - chtype ch; - int n, x, y, code = OK; - attr_t attr = A_NORMAL; - long lattr; - - switch (PyTuple_Size(args)) { - case 2: - if (!PyArg_ParseTuple(args, "Oi;ch or int,n", &temp, &n)) - return NULL; - break; - case 3: - if (!PyArg_ParseTuple(args, "Oil;ch or int,n,attr", &temp, &n, &lattr)) - return NULL; - attr = lattr; - break; - case 4: - if (!PyArg_ParseTuple(args, "iiOi;y,x,ch or int,n", &y, &x, &temp, &n)) - return NULL; - code = wmove(self->win, y, x); - break; - case 5: - if (!PyArg_ParseTuple(args, "iiOil; y,x,ch or int,n,attr", - &y, &x, &temp, &n, &lattr)) - return NULL; - attr = lattr; - code = wmove(self->win, y, x); - break; - default: - PyErr_SetString(PyExc_TypeError, "vline requires 2 to 5 arguments"); - return NULL; - } + PyObject *temp; + chtype ch; + int n, x, y, code = OK; + attr_t attr = A_NORMAL; + long lattr; - if (code != ERR) { - if (!PyCurses_ConvertToChtype(temp, &ch)) { - PyErr_SetString(PyExc_TypeError, - "argument 1 or 3 must be a ch or an int"); - return NULL; - } - return PyCursesCheckERR(wvline(self->win, ch | attr, n), "vline"); - } else - return PyCursesCheckERR(code, "wmove"); + switch (PyTuple_Size(args)) { + case 2: + if (!PyArg_ParseTuple(args, "Oi;ch or int,n", &temp, &n)) + return NULL; + break; + case 3: + if (!PyArg_ParseTuple(args, "Oil;ch or int,n,attr", &temp, &n, &lattr)) + return NULL; + attr = lattr; + break; + case 4: + if (!PyArg_ParseTuple(args, "iiOi;y,x,ch or int,n", &y, &x, &temp, &n)) + return NULL; + code = wmove(self->win, y, x); + break; + case 5: + if (!PyArg_ParseTuple(args, "iiOil; y,x,ch or int,n,attr", + &y, &x, &temp, &n, &lattr)) + return NULL; + attr = lattr; + code = wmove(self->win, y, x); + break; + default: + PyErr_SetString(PyExc_TypeError, "vline requires 2 to 5 arguments"); + return NULL; + } + + if (code != ERR) { + if (!PyCurses_ConvertToChtype(temp, &ch)) { + PyErr_SetString(PyExc_TypeError, + "argument 1 or 3 must be a ch or an int"); + return NULL; + } + return PyCursesCheckERR(wvline(self->win, ch | attr, n), "vline"); + } else + return PyCursesCheckERR(code, "wmove"); } static PyMethodDef PyCursesWindow_Methods[] = { - {"addch", (PyCFunction)PyCursesWindow_AddCh, METH_VARARGS}, - {"addnstr", (PyCFunction)PyCursesWindow_AddNStr, METH_VARARGS}, - {"addstr", (PyCFunction)PyCursesWindow_AddStr, METH_VARARGS}, - {"attroff", (PyCFunction)PyCursesWindow_AttrOff, METH_VARARGS}, - {"attron", (PyCFunction)PyCursesWindow_AttrOn, METH_VARARGS}, - {"attrset", (PyCFunction)PyCursesWindow_AttrSet, METH_VARARGS}, - {"bkgd", (PyCFunction)PyCursesWindow_Bkgd, METH_VARARGS}, - {"chgat", (PyCFunction)PyCursesWindow_ChgAt, METH_VARARGS}, - {"bkgdset", (PyCFunction)PyCursesWindow_BkgdSet, METH_VARARGS}, - {"border", (PyCFunction)PyCursesWindow_Border, METH_VARARGS}, - {"box", (PyCFunction)PyCursesWindow_Box, METH_VARARGS}, - {"clear", (PyCFunction)PyCursesWindow_wclear, METH_NOARGS}, - {"clearok", (PyCFunction)PyCursesWindow_clearok, METH_VARARGS}, - {"clrtobot", (PyCFunction)PyCursesWindow_wclrtobot, METH_NOARGS}, - {"clrtoeol", (PyCFunction)PyCursesWindow_wclrtoeol, METH_NOARGS}, - {"cursyncup", (PyCFunction)PyCursesWindow_wcursyncup, METH_NOARGS}, - {"delch", (PyCFunction)PyCursesWindow_DelCh, METH_VARARGS}, - {"deleteln", (PyCFunction)PyCursesWindow_wdeleteln, METH_NOARGS}, - {"derwin", (PyCFunction)PyCursesWindow_DerWin, METH_VARARGS}, - {"echochar", (PyCFunction)PyCursesWindow_EchoChar, METH_VARARGS}, + {"addch", (PyCFunction)PyCursesWindow_AddCh, METH_VARARGS}, + {"addnstr", (PyCFunction)PyCursesWindow_AddNStr, METH_VARARGS}, + {"addstr", (PyCFunction)PyCursesWindow_AddStr, METH_VARARGS}, + {"attroff", (PyCFunction)PyCursesWindow_AttrOff, METH_VARARGS}, + {"attron", (PyCFunction)PyCursesWindow_AttrOn, METH_VARARGS}, + {"attrset", (PyCFunction)PyCursesWindow_AttrSet, METH_VARARGS}, + {"bkgd", (PyCFunction)PyCursesWindow_Bkgd, METH_VARARGS}, + {"chgat", (PyCFunction)PyCursesWindow_ChgAt, METH_VARARGS}, + {"bkgdset", (PyCFunction)PyCursesWindow_BkgdSet, METH_VARARGS}, + {"border", (PyCFunction)PyCursesWindow_Border, METH_VARARGS}, + {"box", (PyCFunction)PyCursesWindow_Box, METH_VARARGS}, + {"clear", (PyCFunction)PyCursesWindow_wclear, METH_NOARGS}, + {"clearok", (PyCFunction)PyCursesWindow_clearok, METH_VARARGS}, + {"clrtobot", (PyCFunction)PyCursesWindow_wclrtobot, METH_NOARGS}, + {"clrtoeol", (PyCFunction)PyCursesWindow_wclrtoeol, METH_NOARGS}, + {"cursyncup", (PyCFunction)PyCursesWindow_wcursyncup, METH_NOARGS}, + {"delch", (PyCFunction)PyCursesWindow_DelCh, METH_VARARGS}, + {"deleteln", (PyCFunction)PyCursesWindow_wdeleteln, METH_NOARGS}, + {"derwin", (PyCFunction)PyCursesWindow_DerWin, METH_VARARGS}, + {"echochar", (PyCFunction)PyCursesWindow_EchoChar, METH_VARARGS}, #ifdef NCURSES_MOUSE_VERSION - {"enclose", (PyCFunction)PyCursesWindow_Enclose, METH_VARARGS}, + {"enclose", (PyCFunction)PyCursesWindow_Enclose, METH_VARARGS}, #endif - {"erase", (PyCFunction)PyCursesWindow_werase, METH_NOARGS}, - {"getbegyx", (PyCFunction)PyCursesWindow_getbegyx, METH_NOARGS}, - {"getbkgd", (PyCFunction)PyCursesWindow_GetBkgd, METH_NOARGS}, - {"getch", (PyCFunction)PyCursesWindow_GetCh, METH_VARARGS}, - {"getkey", (PyCFunction)PyCursesWindow_GetKey, METH_VARARGS}, - {"getmaxyx", (PyCFunction)PyCursesWindow_getmaxyx, METH_NOARGS}, - {"getparyx", (PyCFunction)PyCursesWindow_getparyx, METH_NOARGS}, - {"getstr", (PyCFunction)PyCursesWindow_GetStr, METH_VARARGS}, - {"getyx", (PyCFunction)PyCursesWindow_getyx, METH_NOARGS}, - {"hline", (PyCFunction)PyCursesWindow_Hline, METH_VARARGS}, - {"idcok", (PyCFunction)PyCursesWindow_idcok, METH_VARARGS}, - {"idlok", (PyCFunction)PyCursesWindow_idlok, METH_VARARGS}, - {"immedok", (PyCFunction)PyCursesWindow_immedok, METH_VARARGS}, - {"inch", (PyCFunction)PyCursesWindow_InCh, METH_VARARGS}, - {"insch", (PyCFunction)PyCursesWindow_InsCh, METH_VARARGS}, - {"insdelln", (PyCFunction)PyCursesWindow_winsdelln, METH_VARARGS}, - {"insertln", (PyCFunction)PyCursesWindow_winsertln, METH_NOARGS}, - {"insnstr", (PyCFunction)PyCursesWindow_InsNStr, METH_VARARGS}, - {"insstr", (PyCFunction)PyCursesWindow_InsStr, METH_VARARGS}, - {"instr", (PyCFunction)PyCursesWindow_InStr, METH_VARARGS}, - {"is_linetouched", (PyCFunction)PyCursesWindow_Is_LineTouched, METH_VARARGS}, - {"is_wintouched", (PyCFunction)PyCursesWindow_is_wintouched, METH_NOARGS}, - {"keypad", (PyCFunction)PyCursesWindow_keypad, METH_VARARGS}, - {"leaveok", (PyCFunction)PyCursesWindow_leaveok, METH_VARARGS}, - {"move", (PyCFunction)PyCursesWindow_wmove, METH_VARARGS}, - {"mvderwin", (PyCFunction)PyCursesWindow_mvderwin, METH_VARARGS}, - {"mvwin", (PyCFunction)PyCursesWindow_mvwin, METH_VARARGS}, - {"nodelay", (PyCFunction)PyCursesWindow_nodelay, METH_VARARGS}, - {"notimeout", (PyCFunction)PyCursesWindow_notimeout, METH_VARARGS}, - {"noutrefresh", (PyCFunction)PyCursesWindow_NoOutRefresh, METH_VARARGS}, - /* Backward compatibility alias -- remove in Python 2.3 */ - {"nooutrefresh", (PyCFunction)PyCursesWindow_NoOutRefresh, METH_VARARGS}, - {"overlay", (PyCFunction)PyCursesWindow_Overlay, METH_VARARGS}, - {"overwrite", (PyCFunction)PyCursesWindow_Overwrite, - METH_VARARGS}, - {"putwin", (PyCFunction)PyCursesWindow_PutWin, METH_O}, - {"redrawln", (PyCFunction)PyCursesWindow_RedrawLine, METH_VARARGS}, - {"redrawwin", (PyCFunction)PyCursesWindow_redrawwin, METH_NOARGS}, - {"refresh", (PyCFunction)PyCursesWindow_Refresh, METH_VARARGS}, + {"erase", (PyCFunction)PyCursesWindow_werase, METH_NOARGS}, + {"getbegyx", (PyCFunction)PyCursesWindow_getbegyx, METH_NOARGS}, + {"getbkgd", (PyCFunction)PyCursesWindow_GetBkgd, METH_NOARGS}, + {"getch", (PyCFunction)PyCursesWindow_GetCh, METH_VARARGS}, + {"getkey", (PyCFunction)PyCursesWindow_GetKey, METH_VARARGS}, + {"getmaxyx", (PyCFunction)PyCursesWindow_getmaxyx, METH_NOARGS}, + {"getparyx", (PyCFunction)PyCursesWindow_getparyx, METH_NOARGS}, + {"getstr", (PyCFunction)PyCursesWindow_GetStr, METH_VARARGS}, + {"getyx", (PyCFunction)PyCursesWindow_getyx, METH_NOARGS}, + {"hline", (PyCFunction)PyCursesWindow_Hline, METH_VARARGS}, + {"idcok", (PyCFunction)PyCursesWindow_idcok, METH_VARARGS}, + {"idlok", (PyCFunction)PyCursesWindow_idlok, METH_VARARGS}, + {"immedok", (PyCFunction)PyCursesWindow_immedok, METH_VARARGS}, + {"inch", (PyCFunction)PyCursesWindow_InCh, METH_VARARGS}, + {"insch", (PyCFunction)PyCursesWindow_InsCh, METH_VARARGS}, + {"insdelln", (PyCFunction)PyCursesWindow_winsdelln, METH_VARARGS}, + {"insertln", (PyCFunction)PyCursesWindow_winsertln, METH_NOARGS}, + {"insnstr", (PyCFunction)PyCursesWindow_InsNStr, METH_VARARGS}, + {"insstr", (PyCFunction)PyCursesWindow_InsStr, METH_VARARGS}, + {"instr", (PyCFunction)PyCursesWindow_InStr, METH_VARARGS}, + {"is_linetouched", (PyCFunction)PyCursesWindow_Is_LineTouched, METH_VARARGS}, + {"is_wintouched", (PyCFunction)PyCursesWindow_is_wintouched, METH_NOARGS}, + {"keypad", (PyCFunction)PyCursesWindow_keypad, METH_VARARGS}, + {"leaveok", (PyCFunction)PyCursesWindow_leaveok, METH_VARARGS}, + {"move", (PyCFunction)PyCursesWindow_wmove, METH_VARARGS}, + {"mvderwin", (PyCFunction)PyCursesWindow_mvderwin, METH_VARARGS}, + {"mvwin", (PyCFunction)PyCursesWindow_mvwin, METH_VARARGS}, + {"nodelay", (PyCFunction)PyCursesWindow_nodelay, METH_VARARGS}, + {"notimeout", (PyCFunction)PyCursesWindow_notimeout, METH_VARARGS}, + {"noutrefresh", (PyCFunction)PyCursesWindow_NoOutRefresh, METH_VARARGS}, + /* Backward compatibility alias -- remove in Python 2.3 */ + {"nooutrefresh", (PyCFunction)PyCursesWindow_NoOutRefresh, METH_VARARGS}, + {"overlay", (PyCFunction)PyCursesWindow_Overlay, METH_VARARGS}, + {"overwrite", (PyCFunction)PyCursesWindow_Overwrite, + METH_VARARGS}, + {"putwin", (PyCFunction)PyCursesWindow_PutWin, METH_O}, + {"redrawln", (PyCFunction)PyCursesWindow_RedrawLine, METH_VARARGS}, + {"redrawwin", (PyCFunction)PyCursesWindow_redrawwin, METH_NOARGS}, + {"refresh", (PyCFunction)PyCursesWindow_Refresh, METH_VARARGS}, #ifndef STRICT_SYSV_CURSES - {"resize", (PyCFunction)PyCursesWindow_wresize, METH_VARARGS}, + {"resize", (PyCFunction)PyCursesWindow_wresize, METH_VARARGS}, #endif - {"scroll", (PyCFunction)PyCursesWindow_Scroll, METH_VARARGS}, - {"scrollok", (PyCFunction)PyCursesWindow_scrollok, METH_VARARGS}, - {"setscrreg", (PyCFunction)PyCursesWindow_SetScrollRegion, METH_VARARGS}, - {"standend", (PyCFunction)PyCursesWindow_wstandend, METH_NOARGS}, - {"standout", (PyCFunction)PyCursesWindow_wstandout, METH_NOARGS}, - {"subpad", (PyCFunction)PyCursesWindow_SubWin, METH_VARARGS}, - {"subwin", (PyCFunction)PyCursesWindow_SubWin, METH_VARARGS}, - {"syncdown", (PyCFunction)PyCursesWindow_wsyncdown, METH_NOARGS}, - {"syncok", (PyCFunction)PyCursesWindow_syncok, METH_VARARGS}, - {"syncup", (PyCFunction)PyCursesWindow_wsyncup, METH_NOARGS}, - {"timeout", (PyCFunction)PyCursesWindow_wtimeout, METH_VARARGS}, - {"touchline", (PyCFunction)PyCursesWindow_TouchLine, METH_VARARGS}, - {"touchwin", (PyCFunction)PyCursesWindow_touchwin, METH_NOARGS}, - {"untouchwin", (PyCFunction)PyCursesWindow_untouchwin, METH_NOARGS}, - {"vline", (PyCFunction)PyCursesWindow_Vline, METH_VARARGS}, - {NULL, NULL} /* sentinel */ + {"scroll", (PyCFunction)PyCursesWindow_Scroll, METH_VARARGS}, + {"scrollok", (PyCFunction)PyCursesWindow_scrollok, METH_VARARGS}, + {"setscrreg", (PyCFunction)PyCursesWindow_SetScrollRegion, METH_VARARGS}, + {"standend", (PyCFunction)PyCursesWindow_wstandend, METH_NOARGS}, + {"standout", (PyCFunction)PyCursesWindow_wstandout, METH_NOARGS}, + {"subpad", (PyCFunction)PyCursesWindow_SubWin, METH_VARARGS}, + {"subwin", (PyCFunction)PyCursesWindow_SubWin, METH_VARARGS}, + {"syncdown", (PyCFunction)PyCursesWindow_wsyncdown, METH_NOARGS}, + {"syncok", (PyCFunction)PyCursesWindow_syncok, METH_VARARGS}, + {"syncup", (PyCFunction)PyCursesWindow_wsyncup, METH_NOARGS}, + {"timeout", (PyCFunction)PyCursesWindow_wtimeout, METH_VARARGS}, + {"touchline", (PyCFunction)PyCursesWindow_TouchLine, METH_VARARGS}, + {"touchwin", (PyCFunction)PyCursesWindow_touchwin, METH_NOARGS}, + {"untouchwin", (PyCFunction)PyCursesWindow_untouchwin, METH_NOARGS}, + {"vline", (PyCFunction)PyCursesWindow_Vline, METH_VARARGS}, + {NULL, NULL} /* sentinel */ }; /* -------------------------------------------------------*/ PyTypeObject PyCursesWindow_Type = { - PyVarObject_HEAD_INIT(NULL, 0) - "_curses.curses window", /*tp_name*/ - sizeof(PyCursesWindowObject), /*tp_basicsize*/ - 0, /*tp_itemsize*/ - /* methods */ - (destructor)PyCursesWindow_Dealloc, /*tp_dealloc*/ - 0, /*tp_print*/ - (getattrfunc)0, /*tp_getattr*/ - (setattrfunc)0, /*tp_setattr*/ - 0, /*tp_reserved*/ - 0, /*tp_repr*/ - 0, /*tp_as_number*/ - 0, /*tp_as_sequence*/ - 0, /*tp_as_mapping*/ - 0, /*tp_hash*/ - 0, /*tp_call*/ - 0, /*tp_str*/ - 0, /*tp_getattro*/ - 0, /*tp_setattro*/ - 0, /*tp_as_buffer*/ - Py_TPFLAGS_DEFAULT, /*tp_flags*/ - 0, /*tp_doc*/ - 0, /*tp_traverse*/ - 0, /*tp_clear*/ - 0, /*tp_richcompare*/ - 0, /*tp_weaklistoffset*/ - 0, /*tp_iter*/ - 0, /*tp_iternext*/ - PyCursesWindow_Methods, /*tp_methods*/ + PyVarObject_HEAD_INIT(NULL, 0) + "_curses.curses window", /*tp_name*/ + sizeof(PyCursesWindowObject), /*tp_basicsize*/ + 0, /*tp_itemsize*/ + /* methods */ + (destructor)PyCursesWindow_Dealloc, /*tp_dealloc*/ + 0, /*tp_print*/ + (getattrfunc)0, /*tp_getattr*/ + (setattrfunc)0, /*tp_setattr*/ + 0, /*tp_reserved*/ + 0, /*tp_repr*/ + 0, /*tp_as_number*/ + 0, /*tp_as_sequence*/ + 0, /*tp_as_mapping*/ + 0, /*tp_hash*/ + 0, /*tp_call*/ + 0, /*tp_str*/ + 0, /*tp_getattro*/ + 0, /*tp_setattro*/ + 0, /*tp_as_buffer*/ + Py_TPFLAGS_DEFAULT, /*tp_flags*/ + 0, /*tp_doc*/ + 0, /*tp_traverse*/ + 0, /*tp_clear*/ + 0, /*tp_richcompare*/ + 0, /*tp_weaklistoffset*/ + 0, /*tp_iter*/ + 0, /*tp_iternext*/ + PyCursesWindow_Methods, /*tp_methods*/ }; /********************************************************************* @@ -1738,452 +1738,452 @@ static PyObject * PyCurses_filter(PyObject *self) { - /* not checking for PyCursesInitialised here since filter() must - be called before initscr() */ - filter(); - Py_INCREF(Py_None); - return Py_None; + /* not checking for PyCursesInitialised here since filter() must + be called before initscr() */ + filter(); + Py_INCREF(Py_None); + return Py_None; } static PyObject * PyCurses_Color_Content(PyObject *self, PyObject *args) { - short color,r,g,b; + short color,r,g,b; - PyCursesInitialised; - PyCursesInitialisedColor; + PyCursesInitialised; + PyCursesInitialisedColor; - if (!PyArg_ParseTuple(args, "h:color_content", &color)) return NULL; + if (!PyArg_ParseTuple(args, "h:color_content", &color)) return NULL; - if (color_content(color, &r, &g, &b) != ERR) - return Py_BuildValue("(iii)", r, g, b); - else { - PyErr_SetString(PyCursesError, - "Argument 1 was out of range. Check value of COLORS."); - return NULL; - } + if (color_content(color, &r, &g, &b) != ERR) + return Py_BuildValue("(iii)", r, g, b); + else { + PyErr_SetString(PyCursesError, + "Argument 1 was out of range. Check value of COLORS."); + return NULL; + } } static PyObject * PyCurses_color_pair(PyObject *self, PyObject *args) { - int n; + int n; - PyCursesInitialised; - PyCursesInitialisedColor; + PyCursesInitialised; + PyCursesInitialisedColor; - if (!PyArg_ParseTuple(args, "i:color_pair", &n)) return NULL; - return PyLong_FromLong((long) (n << 8)); + if (!PyArg_ParseTuple(args, "i:color_pair", &n)) return NULL; + return PyLong_FromLong((long) (n << 8)); } static PyObject * PyCurses_Curs_Set(PyObject *self, PyObject *args) { - int vis,erg; + int vis,erg; - PyCursesInitialised; + PyCursesInitialised; - if (!PyArg_ParseTuple(args, "i:curs_set", &vis)) return NULL; + if (!PyArg_ParseTuple(args, "i:curs_set", &vis)) return NULL; - erg = curs_set(vis); - if (erg == ERR) return PyCursesCheckERR(erg, "curs_set"); + erg = curs_set(vis); + if (erg == ERR) return PyCursesCheckERR(erg, "curs_set"); - return PyLong_FromLong((long) erg); + return PyLong_FromLong((long) erg); } static PyObject * PyCurses_Delay_Output(PyObject *self, PyObject *args) { - int ms; + int ms; - PyCursesInitialised; + PyCursesInitialised; - if (!PyArg_ParseTuple(args, "i:delay_output", &ms)) return NULL; + if (!PyArg_ParseTuple(args, "i:delay_output", &ms)) return NULL; - return PyCursesCheckERR(delay_output(ms), "delay_output"); + return PyCursesCheckERR(delay_output(ms), "delay_output"); } static PyObject * PyCurses_EraseChar(PyObject *self) { - char ch; + char ch; - PyCursesInitialised; + PyCursesInitialised; - ch = erasechar(); + ch = erasechar(); - return PyBytes_FromStringAndSize(&ch, 1); + return PyBytes_FromStringAndSize(&ch, 1); } static PyObject * PyCurses_getsyx(PyObject *self) { - int x = 0; - int y = 0; + int x = 0; + int y = 0; - PyCursesInitialised; + PyCursesInitialised; - getsyx(y, x); + getsyx(y, x); - return Py_BuildValue("(ii)", y, x); + return Py_BuildValue("(ii)", y, x); } #ifdef NCURSES_MOUSE_VERSION static PyObject * PyCurses_GetMouse(PyObject *self) { - int rtn; - MEVENT event; + int rtn; + MEVENT event; - PyCursesInitialised; + PyCursesInitialised; - rtn = getmouse( &event ); - if (rtn == ERR) { - PyErr_SetString(PyCursesError, "getmouse() returned ERR"); - return NULL; - } - return Py_BuildValue("(hiiil)", - (short)event.id, - event.x, event.y, event.z, - (long) event.bstate); + rtn = getmouse( &event ); + if (rtn == ERR) { + PyErr_SetString(PyCursesError, "getmouse() returned ERR"); + return NULL; + } + return Py_BuildValue("(hiiil)", + (short)event.id, + event.x, event.y, event.z, + (long) event.bstate); } static PyObject * PyCurses_UngetMouse(PyObject *self, PyObject *args) { - MEVENT event; + MEVENT event; - PyCursesInitialised; - if (!PyArg_ParseTuple(args, "hiiil", - &event.id, - &event.x, &event.y, &event.z, - (int *) &event.bstate)) - return NULL; + PyCursesInitialised; + if (!PyArg_ParseTuple(args, "hiiil", + &event.id, + &event.x, &event.y, &event.z, + (int *) &event.bstate)) + return NULL; - return PyCursesCheckERR(ungetmouse(&event), "ungetmouse"); + return PyCursesCheckERR(ungetmouse(&event), "ungetmouse"); } #endif static PyObject * PyCurses_GetWin(PyCursesWindowObject *self, PyObject *stream) { - char fn[100]; - int fd; - FILE *fp; - PyObject *data; - size_t datalen; - WINDOW *win; - - PyCursesInitialised; - - strcpy(fn, "/tmp/py.curses.getwin.XXXXXX"); - fd = mkstemp(fn); - if (fd < 0) - return PyErr_SetFromErrnoWithFilename(PyExc_IOError, fn); - fp = fdopen(fd, "wb+"); - if (fp == NULL) { - close(fd); - remove(fn); - return PyErr_SetFromErrnoWithFilename(PyExc_IOError, fn); - } - data = PyObject_CallMethod(stream, "read", ""); - if (data == NULL) { - fclose(fp); - remove(fn); - return NULL; - } - if (!PyBytes_Check(data)) { - PyErr_Format(PyExc_TypeError, - "f.read() returned %.100s instead of bytes", - data->ob_type->tp_name); - Py_DECREF(data); - fclose(fp); - remove(fn); - return NULL; - } - datalen = PyBytes_GET_SIZE(data); - if (fwrite(PyBytes_AS_STRING(data), 1, datalen, fp) != datalen) { + char fn[100]; + int fd; + FILE *fp; + PyObject *data; + size_t datalen; + WINDOW *win; + + PyCursesInitialised; + + strcpy(fn, "/tmp/py.curses.getwin.XXXXXX"); + fd = mkstemp(fn); + if (fd < 0) + return PyErr_SetFromErrnoWithFilename(PyExc_IOError, fn); + fp = fdopen(fd, "wb+"); + if (fp == NULL) { + close(fd); + remove(fn); + return PyErr_SetFromErrnoWithFilename(PyExc_IOError, fn); + } + data = PyObject_CallMethod(stream, "read", ""); + if (data == NULL) { + fclose(fp); + remove(fn); + return NULL; + } + if (!PyBytes_Check(data)) { + PyErr_Format(PyExc_TypeError, + "f.read() returned %.100s instead of bytes", + data->ob_type->tp_name); + Py_DECREF(data); + fclose(fp); + remove(fn); + return NULL; + } + datalen = PyBytes_GET_SIZE(data); + if (fwrite(PyBytes_AS_STRING(data), 1, datalen, fp) != datalen) { + Py_DECREF(data); + fclose(fp); + remove(fn); + return PyErr_SetFromErrnoWithFilename(PyExc_IOError, fn); + } Py_DECREF(data); + fseek(fp, 0, 0); + win = getwin(fp); fclose(fp); remove(fn); - return PyErr_SetFromErrnoWithFilename(PyExc_IOError, fn); - } - Py_DECREF(data); - fseek(fp, 0, 0); - win = getwin(fp); - fclose(fp); - remove(fn); - if (win == NULL) { - PyErr_SetString(PyCursesError, catchall_NULL); - return NULL; - } - return PyCursesWindow_New(win); + if (win == NULL) { + PyErr_SetString(PyCursesError, catchall_NULL); + return NULL; + } + return PyCursesWindow_New(win); } static PyObject * PyCurses_HalfDelay(PyObject *self, PyObject *args) { - unsigned char tenths; + unsigned char tenths; - PyCursesInitialised; + PyCursesInitialised; - if (!PyArg_ParseTuple(args, "b:halfdelay", &tenths)) return NULL; + if (!PyArg_ParseTuple(args, "b:halfdelay", &tenths)) return NULL; - return PyCursesCheckERR(halfdelay(tenths), "halfdelay"); + return PyCursesCheckERR(halfdelay(tenths), "halfdelay"); } #ifndef STRICT_SYSV_CURSES - /* No has_key! */ +/* No has_key! */ static PyObject * PyCurses_has_key(PyObject *self, PyObject *args) { - int ch; + int ch; - PyCursesInitialised; + PyCursesInitialised; - if (!PyArg_ParseTuple(args,"i",&ch)) return NULL; + if (!PyArg_ParseTuple(args,"i",&ch)) return NULL; - if (has_key(ch) == FALSE) { - Py_INCREF(Py_False); - return Py_False; - } - Py_INCREF(Py_True); - return Py_True; + if (has_key(ch) == FALSE) { + Py_INCREF(Py_False); + return Py_False; + } + Py_INCREF(Py_True); + return Py_True; } #endif /* STRICT_SYSV_CURSES */ static PyObject * PyCurses_Init_Color(PyObject *self, PyObject *args) { - short color, r, g, b; + short color, r, g, b; - PyCursesInitialised; - PyCursesInitialisedColor; + PyCursesInitialised; + PyCursesInitialisedColor; - switch(PyTuple_Size(args)) { - case 4: - if (!PyArg_ParseTuple(args, "hhhh;color,r,g,b", &color, &r, &g, &b)) return NULL; - break; - default: - PyErr_SetString(PyExc_TypeError, "init_color requires 4 arguments"); - return NULL; - } + switch(PyTuple_Size(args)) { + case 4: + if (!PyArg_ParseTuple(args, "hhhh;color,r,g,b", &color, &r, &g, &b)) return NULL; + break; + default: + PyErr_SetString(PyExc_TypeError, "init_color requires 4 arguments"); + return NULL; + } - return PyCursesCheckERR(init_color(color, r, g, b), "init_color"); + return PyCursesCheckERR(init_color(color, r, g, b), "init_color"); } static PyObject * PyCurses_Init_Pair(PyObject *self, PyObject *args) { - short pair, f, b; + short pair, f, b; - PyCursesInitialised; - PyCursesInitialisedColor; + PyCursesInitialised; + PyCursesInitialisedColor; - if (PyTuple_Size(args) != 3) { - PyErr_SetString(PyExc_TypeError, "init_pair requires 3 arguments"); - return NULL; - } + if (PyTuple_Size(args) != 3) { + PyErr_SetString(PyExc_TypeError, "init_pair requires 3 arguments"); + return NULL; + } - if (!PyArg_ParseTuple(args, "hhh;pair, f, b", &pair, &f, &b)) return NULL; + if (!PyArg_ParseTuple(args, "hhh;pair, f, b", &pair, &f, &b)) return NULL; - return PyCursesCheckERR(init_pair(pair, f, b), "init_pair"); + return PyCursesCheckERR(init_pair(pair, f, b), "init_pair"); } static PyObject *ModDict; -static PyObject * +static PyObject * PyCurses_InitScr(PyObject *self) { - WINDOW *win; + WINDOW *win; - if (initialised == TRUE) { - wrefresh(stdscr); - return (PyObject *)PyCursesWindow_New(stdscr); - } + if (initialised == TRUE) { + wrefresh(stdscr); + return (PyObject *)PyCursesWindow_New(stdscr); + } - win = initscr(); + win = initscr(); - if (win == NULL) { - PyErr_SetString(PyCursesError, catchall_NULL); - return NULL; - } + if (win == NULL) { + PyErr_SetString(PyCursesError, catchall_NULL); + return NULL; + } - initialised = initialised_setupterm = TRUE; + initialised = initialised_setupterm = TRUE; /* This was moved from initcurses() because it core dumped on SGI, where they're not defined until you've called initscr() */ -#define SetDictInt(string,ch) \ - do { \ - PyObject *o = PyLong_FromLong((long) (ch)); \ - if (o && PyDict_SetItemString(ModDict, string, o) == 0) { \ - Py_DECREF(o); \ - } \ +#define SetDictInt(string,ch) \ + do { \ + PyObject *o = PyLong_FromLong((long) (ch)); \ + if (o && PyDict_SetItemString(ModDict, string, o) == 0) { \ + Py_DECREF(o); \ + } \ } while (0) - /* Here are some graphic symbols you can use */ - SetDictInt("ACS_ULCORNER", (ACS_ULCORNER)); - SetDictInt("ACS_LLCORNER", (ACS_LLCORNER)); - SetDictInt("ACS_URCORNER", (ACS_URCORNER)); - SetDictInt("ACS_LRCORNER", (ACS_LRCORNER)); - SetDictInt("ACS_LTEE", (ACS_LTEE)); - SetDictInt("ACS_RTEE", (ACS_RTEE)); - SetDictInt("ACS_BTEE", (ACS_BTEE)); - SetDictInt("ACS_TTEE", (ACS_TTEE)); - SetDictInt("ACS_HLINE", (ACS_HLINE)); - SetDictInt("ACS_VLINE", (ACS_VLINE)); - SetDictInt("ACS_PLUS", (ACS_PLUS)); + /* Here are some graphic symbols you can use */ + SetDictInt("ACS_ULCORNER", (ACS_ULCORNER)); + SetDictInt("ACS_LLCORNER", (ACS_LLCORNER)); + SetDictInt("ACS_URCORNER", (ACS_URCORNER)); + SetDictInt("ACS_LRCORNER", (ACS_LRCORNER)); + SetDictInt("ACS_LTEE", (ACS_LTEE)); + SetDictInt("ACS_RTEE", (ACS_RTEE)); + SetDictInt("ACS_BTEE", (ACS_BTEE)); + SetDictInt("ACS_TTEE", (ACS_TTEE)); + SetDictInt("ACS_HLINE", (ACS_HLINE)); + SetDictInt("ACS_VLINE", (ACS_VLINE)); + SetDictInt("ACS_PLUS", (ACS_PLUS)); #if !defined(__hpux) || defined(HAVE_NCURSES_H) - /* On HP/UX 11, these are of type cchar_t, which is not an - integral type. If this is a problem on more platforms, a - configure test should be added to determine whether ACS_S1 - is of integral type. */ - SetDictInt("ACS_S1", (ACS_S1)); - SetDictInt("ACS_S9", (ACS_S9)); - SetDictInt("ACS_DIAMOND", (ACS_DIAMOND)); - SetDictInt("ACS_CKBOARD", (ACS_CKBOARD)); - SetDictInt("ACS_DEGREE", (ACS_DEGREE)); - SetDictInt("ACS_PLMINUS", (ACS_PLMINUS)); - SetDictInt("ACS_BULLET", (ACS_BULLET)); - SetDictInt("ACS_LARROW", (ACS_LARROW)); - SetDictInt("ACS_RARROW", (ACS_RARROW)); - SetDictInt("ACS_DARROW", (ACS_DARROW)); - SetDictInt("ACS_UARROW", (ACS_UARROW)); - SetDictInt("ACS_BOARD", (ACS_BOARD)); - SetDictInt("ACS_LANTERN", (ACS_LANTERN)); - SetDictInt("ACS_BLOCK", (ACS_BLOCK)); -#endif - SetDictInt("ACS_BSSB", (ACS_ULCORNER)); - SetDictInt("ACS_SSBB", (ACS_LLCORNER)); - SetDictInt("ACS_BBSS", (ACS_URCORNER)); - SetDictInt("ACS_SBBS", (ACS_LRCORNER)); - SetDictInt("ACS_SBSS", (ACS_RTEE)); - SetDictInt("ACS_SSSB", (ACS_LTEE)); - SetDictInt("ACS_SSBS", (ACS_BTEE)); - SetDictInt("ACS_BSSS", (ACS_TTEE)); - SetDictInt("ACS_BSBS", (ACS_HLINE)); - SetDictInt("ACS_SBSB", (ACS_VLINE)); - SetDictInt("ACS_SSSS", (ACS_PLUS)); + /* On HP/UX 11, these are of type cchar_t, which is not an + integral type. If this is a problem on more platforms, a + configure test should be added to determine whether ACS_S1 + is of integral type. */ + SetDictInt("ACS_S1", (ACS_S1)); + SetDictInt("ACS_S9", (ACS_S9)); + SetDictInt("ACS_DIAMOND", (ACS_DIAMOND)); + SetDictInt("ACS_CKBOARD", (ACS_CKBOARD)); + SetDictInt("ACS_DEGREE", (ACS_DEGREE)); + SetDictInt("ACS_PLMINUS", (ACS_PLMINUS)); + SetDictInt("ACS_BULLET", (ACS_BULLET)); + SetDictInt("ACS_LARROW", (ACS_LARROW)); + SetDictInt("ACS_RARROW", (ACS_RARROW)); + SetDictInt("ACS_DARROW", (ACS_DARROW)); + SetDictInt("ACS_UARROW", (ACS_UARROW)); + SetDictInt("ACS_BOARD", (ACS_BOARD)); + SetDictInt("ACS_LANTERN", (ACS_LANTERN)); + SetDictInt("ACS_BLOCK", (ACS_BLOCK)); +#endif + SetDictInt("ACS_BSSB", (ACS_ULCORNER)); + SetDictInt("ACS_SSBB", (ACS_LLCORNER)); + SetDictInt("ACS_BBSS", (ACS_URCORNER)); + SetDictInt("ACS_SBBS", (ACS_LRCORNER)); + SetDictInt("ACS_SBSS", (ACS_RTEE)); + SetDictInt("ACS_SSSB", (ACS_LTEE)); + SetDictInt("ACS_SSBS", (ACS_BTEE)); + SetDictInt("ACS_BSSS", (ACS_TTEE)); + SetDictInt("ACS_BSBS", (ACS_HLINE)); + SetDictInt("ACS_SBSB", (ACS_VLINE)); + SetDictInt("ACS_SSSS", (ACS_PLUS)); - /* The following are never available with strict SYSV curses */ + /* The following are never available with strict SYSV curses */ #ifdef ACS_S3 - SetDictInt("ACS_S3", (ACS_S3)); + SetDictInt("ACS_S3", (ACS_S3)); #endif #ifdef ACS_S7 - SetDictInt("ACS_S7", (ACS_S7)); + SetDictInt("ACS_S7", (ACS_S7)); #endif #ifdef ACS_LEQUAL - SetDictInt("ACS_LEQUAL", (ACS_LEQUAL)); + SetDictInt("ACS_LEQUAL", (ACS_LEQUAL)); #endif #ifdef ACS_GEQUAL - SetDictInt("ACS_GEQUAL", (ACS_GEQUAL)); + SetDictInt("ACS_GEQUAL", (ACS_GEQUAL)); #endif #ifdef ACS_PI - SetDictInt("ACS_PI", (ACS_PI)); + SetDictInt("ACS_PI", (ACS_PI)); #endif #ifdef ACS_NEQUAL - SetDictInt("ACS_NEQUAL", (ACS_NEQUAL)); + SetDictInt("ACS_NEQUAL", (ACS_NEQUAL)); #endif #ifdef ACS_STERLING - SetDictInt("ACS_STERLING", (ACS_STERLING)); + SetDictInt("ACS_STERLING", (ACS_STERLING)); #endif - SetDictInt("LINES", LINES); - SetDictInt("COLS", COLS); + SetDictInt("LINES", LINES); + SetDictInt("COLS", COLS); - return (PyObject *)PyCursesWindow_New(win); + return (PyObject *)PyCursesWindow_New(win); } static PyObject * PyCurses_setupterm(PyObject* self, PyObject *args, PyObject* keywds) { - int fd = -1; - int err; - char* termstr = NULL; - - static char *kwlist[] = {"term", "fd", NULL}; - - if (!PyArg_ParseTupleAndKeywords( - args, keywds, "|zi:setupterm", kwlist, &termstr, &fd)) { - return NULL; - } - - if (fd == -1) { - PyObject* sys_stdout; - - sys_stdout = PySys_GetObject("stdout"); - - if (sys_stdout == NULL || sys_stdout == Py_None) { - PyErr_SetString( - PyCursesError, - "lost sys.stdout"); - return NULL; - } - - fd = PyObject_AsFileDescriptor(sys_stdout); - - if (fd == -1) { - return NULL; - } - } - - if (setupterm(termstr,fd,&err) == ERR) { - char* s = "setupterm: unknown error"; - - if (err == 0) { - s = "setupterm: could not find terminal"; - } else if (err == -1) { - s = "setupterm: could not find terminfo database"; - } - - PyErr_SetString(PyCursesError,s); - return NULL; - } + int fd = -1; + int err; + char* termstr = NULL; - initialised_setupterm = TRUE; + static char *kwlist[] = {"term", "fd", NULL}; - Py_INCREF(Py_None); - return Py_None; + if (!PyArg_ParseTupleAndKeywords( + args, keywds, "|zi:setupterm", kwlist, &termstr, &fd)) { + return NULL; + } + + if (fd == -1) { + PyObject* sys_stdout; + + sys_stdout = PySys_GetObject("stdout"); + + if (sys_stdout == NULL || sys_stdout == Py_None) { + PyErr_SetString( + PyCursesError, + "lost sys.stdout"); + return NULL; + } + + fd = PyObject_AsFileDescriptor(sys_stdout); + + if (fd == -1) { + return NULL; + } + } + + if (setupterm(termstr,fd,&err) == ERR) { + char* s = "setupterm: unknown error"; + + if (err == 0) { + s = "setupterm: could not find terminal"; + } else if (err == -1) { + s = "setupterm: could not find terminfo database"; + } + + PyErr_SetString(PyCursesError,s); + return NULL; + } + + initialised_setupterm = TRUE; + + Py_INCREF(Py_None); + return Py_None; } static PyObject * PyCurses_IntrFlush(PyObject *self, PyObject *args) { - int ch; + int ch; - PyCursesInitialised; + PyCursesInitialised; - switch(PyTuple_Size(args)) { - case 1: - if (!PyArg_ParseTuple(args,"i;True(1), False(0)",&ch)) return NULL; - break; - default: - PyErr_SetString(PyExc_TypeError, "intrflush requires 1 argument"); - return NULL; - } + switch(PyTuple_Size(args)) { + case 1: + if (!PyArg_ParseTuple(args,"i;True(1), False(0)",&ch)) return NULL; + break; + default: + PyErr_SetString(PyExc_TypeError, "intrflush requires 1 argument"); + return NULL; + } - return PyCursesCheckERR(intrflush(NULL,ch), "intrflush"); + return PyCursesCheckERR(intrflush(NULL,ch), "intrflush"); } #ifdef HAVE_CURSES_IS_TERM_RESIZED static PyObject * PyCurses_Is_Term_Resized(PyObject *self, PyObject *args) { - int lines; - int columns; - int result; - - PyCursesInitialised; - - if (!PyArg_ParseTuple(args,"ii:is_term_resized", &lines, &columns)) - return NULL; - result = is_term_resized(lines, columns); - if (result == TRUE) { - Py_INCREF(Py_True); - return Py_True; - } else { - Py_INCREF(Py_False); - return Py_False; - } + int lines; + int columns; + int result; + + PyCursesInitialised; + + if (!PyArg_ParseTuple(args,"ii:is_term_resized", &lines, &columns)) + return NULL; + result = is_term_resized(lines, columns); + if (result == TRUE) { + Py_INCREF(Py_True); + return Py_True; + } else { + Py_INCREF(Py_False); + return Py_False; + } } #endif /* HAVE_CURSES_IS_TERM_RESIZED */ @@ -2191,75 +2191,75 @@ static PyObject * PyCurses_KeyName(PyObject *self, PyObject *args) { - const char *knp; - int ch; + const char *knp; + int ch; - PyCursesInitialised; + PyCursesInitialised; - if (!PyArg_ParseTuple(args,"i",&ch)) return NULL; + if (!PyArg_ParseTuple(args,"i",&ch)) return NULL; - if (ch < 0) { - PyErr_SetString(PyExc_ValueError, "invalid key number"); - return NULL; - } - knp = keyname(ch); + if (ch < 0) { + PyErr_SetString(PyExc_ValueError, "invalid key number"); + return NULL; + } + knp = keyname(ch); - return PyBytes_FromString((knp == NULL) ? "" : (char *)knp); + return PyBytes_FromString((knp == NULL) ? "" : (char *)knp); } #endif -static PyObject * -PyCurses_KillChar(PyObject *self) -{ - char ch; +static PyObject * +PyCurses_KillChar(PyObject *self) +{ + char ch; - ch = killchar(); + ch = killchar(); - return PyBytes_FromStringAndSize(&ch, 1); -} + return PyBytes_FromStringAndSize(&ch, 1); +} static PyObject * PyCurses_Meta(PyObject *self, PyObject *args) { - int ch; + int ch; - PyCursesInitialised; + PyCursesInitialised; - switch(PyTuple_Size(args)) { - case 1: - if (!PyArg_ParseTuple(args,"i;True(1), False(0)",&ch)) return NULL; - break; - default: - PyErr_SetString(PyExc_TypeError, "meta requires 1 argument"); - return NULL; - } + switch(PyTuple_Size(args)) { + case 1: + if (!PyArg_ParseTuple(args,"i;True(1), False(0)",&ch)) return NULL; + break; + default: + PyErr_SetString(PyExc_TypeError, "meta requires 1 argument"); + return NULL; + } - return PyCursesCheckERR(meta(stdscr, ch), "meta"); + return PyCursesCheckERR(meta(stdscr, ch), "meta"); } #ifdef NCURSES_MOUSE_VERSION static PyObject * PyCurses_MouseInterval(PyObject *self, PyObject *args) { - int interval; - PyCursesInitialised; + int interval; + PyCursesInitialised; - if (!PyArg_ParseTuple(args,"i;interval",&interval)) - return NULL; - return PyCursesCheckERR(mouseinterval(interval), "mouseinterval"); + if (!PyArg_ParseTuple(args,"i;interval",&interval)) + return NULL; + return PyCursesCheckERR(mouseinterval(interval), "mouseinterval"); } static PyObject * PyCurses_MouseMask(PyObject *self, PyObject *args) { - int newmask; - mmask_t oldmask, availmask; + int newmask; + mmask_t oldmask, availmask; - PyCursesInitialised; - if (!PyArg_ParseTuple(args,"i;mousemask",&newmask)) - return NULL; - availmask = mousemask(newmask, &oldmask); - return Py_BuildValue("(ll)", (long)availmask, (long)oldmask); + PyCursesInitialised; + if (!PyArg_ParseTuple(args,"i;mousemask",&newmask)) + return NULL; + availmask = mousemask(newmask, &oldmask); + return Py_BuildValue("(ll)", (long)availmask, (long)oldmask); } #endif @@ -2278,133 +2278,133 @@ static PyObject * PyCurses_NewPad(PyObject *self, PyObject *args) { - WINDOW *win; - int nlines, ncols; + WINDOW *win; + int nlines, ncols; + + PyCursesInitialised; - PyCursesInitialised; + if (!PyArg_ParseTuple(args,"ii;nlines,ncols",&nlines,&ncols)) return NULL; - if (!PyArg_ParseTuple(args,"ii;nlines,ncols",&nlines,&ncols)) return NULL; + win = newpad(nlines, ncols); - win = newpad(nlines, ncols); - - if (win == NULL) { - PyErr_SetString(PyCursesError, catchall_NULL); - return NULL; - } + if (win == NULL) { + PyErr_SetString(PyCursesError, catchall_NULL); + return NULL; + } - return (PyObject *)PyCursesWindow_New(win); + return (PyObject *)PyCursesWindow_New(win); } static PyObject * PyCurses_NewWindow(PyObject *self, PyObject *args) { - WINDOW *win; - int nlines, ncols, begin_y=0, begin_x=0; + WINDOW *win; + int nlines, ncols, begin_y=0, begin_x=0; - PyCursesInitialised; + PyCursesInitialised; - switch (PyTuple_Size(args)) { - case 2: - if (!PyArg_ParseTuple(args,"ii;nlines,ncols",&nlines,&ncols)) - return NULL; - break; - case 4: - if (!PyArg_ParseTuple(args, "iiii;nlines,ncols,begin_y,begin_x", - &nlines,&ncols,&begin_y,&begin_x)) - return NULL; - break; - default: - PyErr_SetString(PyExc_TypeError, "newwin requires 2 or 4 arguments"); - return NULL; - } - - win = newwin(nlines,ncols,begin_y,begin_x); - if (win == NULL) { - PyErr_SetString(PyCursesError, catchall_NULL); - return NULL; - } + switch (PyTuple_Size(args)) { + case 2: + if (!PyArg_ParseTuple(args,"ii;nlines,ncols",&nlines,&ncols)) + return NULL; + break; + case 4: + if (!PyArg_ParseTuple(args, "iiii;nlines,ncols,begin_y,begin_x", + &nlines,&ncols,&begin_y,&begin_x)) + return NULL; + break; + default: + PyErr_SetString(PyExc_TypeError, "newwin requires 2 or 4 arguments"); + return NULL; + } + + win = newwin(nlines,ncols,begin_y,begin_x); + if (win == NULL) { + PyErr_SetString(PyCursesError, catchall_NULL); + return NULL; + } - return (PyObject *)PyCursesWindow_New(win); + return (PyObject *)PyCursesWindow_New(win); } static PyObject * PyCurses_Pair_Content(PyObject *self, PyObject *args) { - short pair,f,b; + short pair,f,b; + + PyCursesInitialised; + PyCursesInitialisedColor; - PyCursesInitialised; - PyCursesInitialisedColor; + switch(PyTuple_Size(args)) { + case 1: + if (!PyArg_ParseTuple(args, "h;pair", &pair)) return NULL; + break; + default: + PyErr_SetString(PyExc_TypeError, "pair_content requires 1 argument"); + return NULL; + } - switch(PyTuple_Size(args)) { - case 1: - if (!PyArg_ParseTuple(args, "h;pair", &pair)) return NULL; - break; - default: - PyErr_SetString(PyExc_TypeError, "pair_content requires 1 argument"); - return NULL; - } - - if (pair_content(pair, &f, &b)==ERR) { - PyErr_SetString(PyCursesError, - "Argument 1 was out of range. (1..COLOR_PAIRS-1)"); - return NULL; - } + if (pair_content(pair, &f, &b)==ERR) { + PyErr_SetString(PyCursesError, + "Argument 1 was out of range. (1..COLOR_PAIRS-1)"); + return NULL; + } - return Py_BuildValue("(ii)", f, b); + return Py_BuildValue("(ii)", f, b); } static PyObject * PyCurses_pair_number(PyObject *self, PyObject *args) { - int n; + int n; - PyCursesInitialised; - PyCursesInitialisedColor; + PyCursesInitialised; + PyCursesInitialisedColor; - switch(PyTuple_Size(args)) { - case 1: - if (!PyArg_ParseTuple(args, "i;pairvalue", &n)) return NULL; - break; - default: - PyErr_SetString(PyExc_TypeError, - "pair_number requires 1 argument"); - return NULL; - } + switch(PyTuple_Size(args)) { + case 1: + if (!PyArg_ParseTuple(args, "i;pairvalue", &n)) return NULL; + break; + default: + PyErr_SetString(PyExc_TypeError, + "pair_number requires 1 argument"); + return NULL; + } - return PyLong_FromLong((long) ((n & A_COLOR) >> 8)); + return PyLong_FromLong((long) ((n & A_COLOR) >> 8)); } static PyObject * PyCurses_Putp(PyObject *self, PyObject *args) { - char *str; + char *str; - if (!PyArg_ParseTuple(args,"s;str", &str)) return NULL; - return PyCursesCheckERR(putp(str), "putp"); + if (!PyArg_ParseTuple(args,"s;str", &str)) return NULL; + return PyCursesCheckERR(putp(str), "putp"); } static PyObject * PyCurses_QiFlush(PyObject *self, PyObject *args) { - int flag = 0; + int flag = 0; - PyCursesInitialised; + PyCursesInitialised; - switch(PyTuple_Size(args)) { - case 0: - qiflush(); - Py_INCREF(Py_None); - return Py_None; - case 1: - if (!PyArg_ParseTuple(args, "i;True(1) or False(0)", &flag)) return NULL; - if (flag) qiflush(); - else noqiflush(); - Py_INCREF(Py_None); - return Py_None; - default: - PyErr_SetString(PyExc_TypeError, "qiflush requires 0 or 1 arguments"); - return NULL; - } + switch(PyTuple_Size(args)) { + case 0: + qiflush(); + Py_INCREF(Py_None); + return Py_None; + case 1: + if (!PyArg_ParseTuple(args, "i;True(1) or False(0)", &flag)) return NULL; + if (flag) qiflush(); + else noqiflush(); + Py_INCREF(Py_None); + return Py_None; + default: + PyErr_SetString(PyExc_TypeError, "qiflush requires 0 or 1 arguments"); + return NULL; + } } /* Internal helper used for updating curses.LINES, curses.COLS, _curses.LINES @@ -2413,46 +2413,46 @@ static int update_lines_cols(void) { - PyObject *o; - PyObject *m = PyImport_ImportModuleNoBlock("curses"); + PyObject *o; + PyObject *m = PyImport_ImportModuleNoBlock("curses"); - if (!m) - return 0; + if (!m) + return 0; - o = PyLong_FromLong(LINES); - if (!o) { - Py_DECREF(m); - return 0; - } - if (PyObject_SetAttrString(m, "LINES", o)) { - Py_DECREF(m); - Py_DECREF(o); - return 0; - } - if (PyDict_SetItemString(ModDict, "LINES", o)) { - Py_DECREF(m); + o = PyLong_FromLong(LINES); + if (!o) { + Py_DECREF(m); + return 0; + } + if (PyObject_SetAttrString(m, "LINES", o)) { + Py_DECREF(m); + Py_DECREF(o); + return 0; + } + if (PyDict_SetItemString(ModDict, "LINES", o)) { + Py_DECREF(m); + Py_DECREF(o); + return 0; + } Py_DECREF(o); - return 0; - } - Py_DECREF(o); - o = PyLong_FromLong(COLS); - if (!o) { - Py_DECREF(m); - return 0; - } - if (PyObject_SetAttrString(m, "COLS", o)) { - Py_DECREF(m); + o = PyLong_FromLong(COLS); + if (!o) { + Py_DECREF(m); + return 0; + } + if (PyObject_SetAttrString(m, "COLS", o)) { + Py_DECREF(m); + Py_DECREF(o); + return 0; + } + if (PyDict_SetItemString(ModDict, "COLS", o)) { + Py_DECREF(m); + Py_DECREF(o); + return 0; + } Py_DECREF(o); - return 0; - } - if (PyDict_SetItemString(ModDict, "COLS", o)) { Py_DECREF(m); - Py_DECREF(o); - return 0; - } - Py_DECREF(o); - Py_DECREF(m); - return 1; + return 1; } #endif @@ -2460,21 +2460,21 @@ static PyObject * PyCurses_ResizeTerm(PyObject *self, PyObject *args) { - int lines; - int columns; - PyObject *result; - - PyCursesInitialised; - - if (!PyArg_ParseTuple(args,"ii:resizeterm", &lines, &columns)) - return NULL; - - result = PyCursesCheckERR(resizeterm(lines, columns), "resizeterm"); - if (!result) - return NULL; - if (!update_lines_cols()) - return NULL; - return result; + int lines; + int columns; + PyObject *result; + + PyCursesInitialised; + + if (!PyArg_ParseTuple(args,"ii:resizeterm", &lines, &columns)) + return NULL; + + result = PyCursesCheckERR(resizeterm(lines, columns), "resizeterm"); + if (!result) + return NULL; + if (!update_lines_cols()) + return NULL; + return result; } #endif @@ -2483,496 +2483,496 @@ static PyObject * PyCurses_Resize_Term(PyObject *self, PyObject *args) { - int lines; - int columns; + int lines; + int columns; - PyObject *result; + PyObject *result; - PyCursesInitialised; + PyCursesInitialised; - if (!PyArg_ParseTuple(args,"ii:resize_term", &lines, &columns)) - return NULL; - - result = PyCursesCheckERR(resize_term(lines, columns), "resize_term"); - if (!result) - return NULL; - if (!update_lines_cols()) - return NULL; - return result; + if (!PyArg_ParseTuple(args,"ii:resize_term", &lines, &columns)) + return NULL; + + result = PyCursesCheckERR(resize_term(lines, columns), "resize_term"); + if (!result) + return NULL; + if (!update_lines_cols()) + return NULL; + return result; } #endif /* HAVE_CURSES_RESIZE_TERM */ static PyObject * PyCurses_setsyx(PyObject *self, PyObject *args) { - int y,x; + int y,x; - PyCursesInitialised; + PyCursesInitialised; - if (PyTuple_Size(args)!=2) { - PyErr_SetString(PyExc_TypeError, "setsyx requires 2 arguments"); - return NULL; - } + if (PyTuple_Size(args)!=2) { + PyErr_SetString(PyExc_TypeError, "setsyx requires 2 arguments"); + return NULL; + } - if (!PyArg_ParseTuple(args, "ii;y, x", &y, &x)) return NULL; + if (!PyArg_ParseTuple(args, "ii;y, x", &y, &x)) return NULL; - setsyx(y,x); + setsyx(y,x); - Py_INCREF(Py_None); - return Py_None; + Py_INCREF(Py_None); + return Py_None; } static PyObject * PyCurses_Start_Color(PyObject *self) { - int code; - PyObject *c, *cp; + int code; + PyObject *c, *cp; - PyCursesInitialised; + PyCursesInitialised; - code = start_color(); - if (code != ERR) { - initialisedcolors = TRUE; - c = PyLong_FromLong((long) COLORS); - PyDict_SetItemString(ModDict, "COLORS", c); - Py_DECREF(c); - cp = PyLong_FromLong((long) COLOR_PAIRS); - PyDict_SetItemString(ModDict, "COLOR_PAIRS", cp); - Py_DECREF(cp); - Py_INCREF(Py_None); - return Py_None; - } else { - PyErr_SetString(PyCursesError, "start_color() returned ERR"); - return NULL; - } + code = start_color(); + if (code != ERR) { + initialisedcolors = TRUE; + c = PyLong_FromLong((long) COLORS); + PyDict_SetItemString(ModDict, "COLORS", c); + Py_DECREF(c); + cp = PyLong_FromLong((long) COLOR_PAIRS); + PyDict_SetItemString(ModDict, "COLOR_PAIRS", cp); + Py_DECREF(cp); + Py_INCREF(Py_None); + return Py_None; + } else { + PyErr_SetString(PyCursesError, "start_color() returned ERR"); + return NULL; + } } static PyObject * PyCurses_tigetflag(PyObject *self, PyObject *args) { - char *capname; + char *capname; - PyCursesSetupTermCalled; - - if (!PyArg_ParseTuple(args, "s", &capname)) - return NULL; + PyCursesSetupTermCalled; - return PyLong_FromLong( (long) tigetflag( capname ) ); + if (!PyArg_ParseTuple(args, "s", &capname)) + return NULL; + + return PyLong_FromLong( (long) tigetflag( capname ) ); } static PyObject * PyCurses_tigetnum(PyObject *self, PyObject *args) { - char *capname; + char *capname; - PyCursesSetupTermCalled; - - if (!PyArg_ParseTuple(args, "s", &capname)) - return NULL; + PyCursesSetupTermCalled; - return PyLong_FromLong( (long) tigetnum( capname ) ); + if (!PyArg_ParseTuple(args, "s", &capname)) + return NULL; + + return PyLong_FromLong( (long) tigetnum( capname ) ); } static PyObject * PyCurses_tigetstr(PyObject *self, PyObject *args) { - char *capname; + char *capname; + + PyCursesSetupTermCalled; - PyCursesSetupTermCalled; - - if (!PyArg_ParseTuple(args, "s", &capname)) - return NULL; - - capname = tigetstr( capname ); - if (capname == 0 || capname == (char*) -1) { - Py_INCREF(Py_None); - return Py_None; - } - return PyBytes_FromString( capname ); + if (!PyArg_ParseTuple(args, "s", &capname)) + return NULL; + + capname = tigetstr( capname ); + if (capname == 0 || capname == (char*) -1) { + Py_INCREF(Py_None); + return Py_None; + } + return PyBytes_FromString( capname ); } static PyObject * PyCurses_tparm(PyObject *self, PyObject *args) { - char* fmt; - char* result = NULL; - int i1=0,i2=0,i3=0,i4=0,i5=0,i6=0,i7=0,i8=0,i9=0; - - PyCursesSetupTermCalled; - - if (!PyArg_ParseTuple(args, "s|iiiiiiiii:tparm", - &fmt, &i1, &i2, &i3, &i4, - &i5, &i6, &i7, &i8, &i9)) { - return NULL; - } - - result = tparm(fmt,i1,i2,i3,i4,i5,i6,i7,i8,i9); - if (!result) { - PyErr_SetString(PyCursesError, "tparm() returned NULL"); - return NULL; - } + char* fmt; + char* result = NULL; + int i1=0,i2=0,i3=0,i4=0,i5=0,i6=0,i7=0,i8=0,i9=0; + + PyCursesSetupTermCalled; + + if (!PyArg_ParseTuple(args, "s|iiiiiiiii:tparm", + &fmt, &i1, &i2, &i3, &i4, + &i5, &i6, &i7, &i8, &i9)) { + return NULL; + } - return PyBytes_FromString(result); + result = tparm(fmt,i1,i2,i3,i4,i5,i6,i7,i8,i9); + if (!result) { + PyErr_SetString(PyCursesError, "tparm() returned NULL"); + return NULL; + } + + return PyBytes_FromString(result); } static PyObject * PyCurses_TypeAhead(PyObject *self, PyObject *args) { - int fd; + int fd; - PyCursesInitialised; + PyCursesInitialised; - if (!PyArg_ParseTuple(args,"i;fd",&fd)) return NULL; + if (!PyArg_ParseTuple(args,"i;fd",&fd)) return NULL; - return PyCursesCheckERR(typeahead( fd ), "typeahead"); + return PyCursesCheckERR(typeahead( fd ), "typeahead"); } static PyObject * PyCurses_UnCtrl(PyObject *self, PyObject *args) { - PyObject *temp; - chtype ch; + PyObject *temp; + chtype ch; - PyCursesInitialised; + PyCursesInitialised; - if (!PyArg_ParseTuple(args,"O;ch or int",&temp)) return NULL; + if (!PyArg_ParseTuple(args,"O;ch or int",&temp)) return NULL; - if (!PyCurses_ConvertToChtype(temp, &ch)) { - PyErr_SetString(PyExc_TypeError, "argument must be a ch or an int"); - return NULL; - } + if (!PyCurses_ConvertToChtype(temp, &ch)) { + PyErr_SetString(PyExc_TypeError, "argument must be a ch or an int"); + return NULL; + } - return PyBytes_FromString(unctrl(ch)); + return PyBytes_FromString(unctrl(ch)); } static PyObject * PyCurses_UngetCh(PyObject *self, PyObject *args) { - PyObject *temp; - chtype ch; + PyObject *temp; + chtype ch; - PyCursesInitialised; + PyCursesInitialised; - if (!PyArg_ParseTuple(args,"O;ch or int",&temp)) return NULL; + if (!PyArg_ParseTuple(args,"O;ch or int",&temp)) return NULL; - if (!PyCurses_ConvertToChtype(temp, &ch)) { - PyErr_SetString(PyExc_TypeError, "argument must be a ch or an int"); - return NULL; - } + if (!PyCurses_ConvertToChtype(temp, &ch)) { + PyErr_SetString(PyExc_TypeError, "argument must be a ch or an int"); + return NULL; + } - return PyCursesCheckERR(ungetch(ch), "ungetch"); + return PyCursesCheckERR(ungetch(ch), "ungetch"); } static PyObject * PyCurses_Use_Env(PyObject *self, PyObject *args) { - int flag; + int flag; - switch(PyTuple_Size(args)) { - case 1: - if (!PyArg_ParseTuple(args,"i;True(1), False(0)",&flag)) - return NULL; - break; - default: - PyErr_SetString(PyExc_TypeError, "use_env requires 1 argument"); - return NULL; - } - use_env(flag); - Py_INCREF(Py_None); - return Py_None; + switch(PyTuple_Size(args)) { + case 1: + if (!PyArg_ParseTuple(args,"i;True(1), False(0)",&flag)) + return NULL; + break; + default: + PyErr_SetString(PyExc_TypeError, "use_env requires 1 argument"); + return NULL; + } + use_env(flag); + Py_INCREF(Py_None); + return Py_None; } #ifndef STRICT_SYSV_CURSES static PyObject * PyCurses_Use_Default_Colors(PyObject *self) { - int code; + int code; - PyCursesInitialised; - PyCursesInitialisedColor; + PyCursesInitialised; + PyCursesInitialisedColor; - code = use_default_colors(); - if (code != ERR) { - Py_INCREF(Py_None); - return Py_None; - } else { - PyErr_SetString(PyCursesError, "use_default_colors() returned ERR"); - return NULL; - } + code = use_default_colors(); + if (code != ERR) { + Py_INCREF(Py_None); + return Py_None; + } else { + PyErr_SetString(PyCursesError, "use_default_colors() returned ERR"); + return NULL; + } } #endif /* STRICT_SYSV_CURSES */ /* List of functions defined in the module */ static PyMethodDef PyCurses_methods[] = { - {"baudrate", (PyCFunction)PyCurses_baudrate, METH_NOARGS}, - {"beep", (PyCFunction)PyCurses_beep, METH_NOARGS}, - {"can_change_color", (PyCFunction)PyCurses_can_change_color, METH_NOARGS}, - {"cbreak", (PyCFunction)PyCurses_cbreak, METH_VARARGS}, - {"color_content", (PyCFunction)PyCurses_Color_Content, METH_VARARGS}, - {"color_pair", (PyCFunction)PyCurses_color_pair, METH_VARARGS}, - {"curs_set", (PyCFunction)PyCurses_Curs_Set, METH_VARARGS}, - {"def_prog_mode", (PyCFunction)PyCurses_def_prog_mode, METH_NOARGS}, - {"def_shell_mode", (PyCFunction)PyCurses_def_shell_mode, METH_NOARGS}, - {"delay_output", (PyCFunction)PyCurses_Delay_Output, METH_VARARGS}, - {"doupdate", (PyCFunction)PyCurses_doupdate, METH_NOARGS}, - {"echo", (PyCFunction)PyCurses_echo, METH_VARARGS}, - {"endwin", (PyCFunction)PyCurses_endwin, METH_NOARGS}, - {"erasechar", (PyCFunction)PyCurses_EraseChar, METH_NOARGS}, - {"filter", (PyCFunction)PyCurses_filter, METH_NOARGS}, - {"flash", (PyCFunction)PyCurses_flash, METH_NOARGS}, - {"flushinp", (PyCFunction)PyCurses_flushinp, METH_NOARGS}, + {"baudrate", (PyCFunction)PyCurses_baudrate, METH_NOARGS}, + {"beep", (PyCFunction)PyCurses_beep, METH_NOARGS}, + {"can_change_color", (PyCFunction)PyCurses_can_change_color, METH_NOARGS}, + {"cbreak", (PyCFunction)PyCurses_cbreak, METH_VARARGS}, + {"color_content", (PyCFunction)PyCurses_Color_Content, METH_VARARGS}, + {"color_pair", (PyCFunction)PyCurses_color_pair, METH_VARARGS}, + {"curs_set", (PyCFunction)PyCurses_Curs_Set, METH_VARARGS}, + {"def_prog_mode", (PyCFunction)PyCurses_def_prog_mode, METH_NOARGS}, + {"def_shell_mode", (PyCFunction)PyCurses_def_shell_mode, METH_NOARGS}, + {"delay_output", (PyCFunction)PyCurses_Delay_Output, METH_VARARGS}, + {"doupdate", (PyCFunction)PyCurses_doupdate, METH_NOARGS}, + {"echo", (PyCFunction)PyCurses_echo, METH_VARARGS}, + {"endwin", (PyCFunction)PyCurses_endwin, METH_NOARGS}, + {"erasechar", (PyCFunction)PyCurses_EraseChar, METH_NOARGS}, + {"filter", (PyCFunction)PyCurses_filter, METH_NOARGS}, + {"flash", (PyCFunction)PyCurses_flash, METH_NOARGS}, + {"flushinp", (PyCFunction)PyCurses_flushinp, METH_NOARGS}, #ifdef NCURSES_MOUSE_VERSION - {"getmouse", (PyCFunction)PyCurses_GetMouse, METH_NOARGS}, - {"ungetmouse", (PyCFunction)PyCurses_UngetMouse, METH_VARARGS}, + {"getmouse", (PyCFunction)PyCurses_GetMouse, METH_NOARGS}, + {"ungetmouse", (PyCFunction)PyCurses_UngetMouse, METH_VARARGS}, #endif - {"getsyx", (PyCFunction)PyCurses_getsyx, METH_NOARGS}, - {"getwin", (PyCFunction)PyCurses_GetWin, METH_O}, - {"has_colors", (PyCFunction)PyCurses_has_colors, METH_NOARGS}, - {"has_ic", (PyCFunction)PyCurses_has_ic, METH_NOARGS}, - {"has_il", (PyCFunction)PyCurses_has_il, METH_NOARGS}, + {"getsyx", (PyCFunction)PyCurses_getsyx, METH_NOARGS}, + {"getwin", (PyCFunction)PyCurses_GetWin, METH_O}, + {"has_colors", (PyCFunction)PyCurses_has_colors, METH_NOARGS}, + {"has_ic", (PyCFunction)PyCurses_has_ic, METH_NOARGS}, + {"has_il", (PyCFunction)PyCurses_has_il, METH_NOARGS}, #ifndef STRICT_SYSV_CURSES - {"has_key", (PyCFunction)PyCurses_has_key, METH_VARARGS}, + {"has_key", (PyCFunction)PyCurses_has_key, METH_VARARGS}, #endif - {"halfdelay", (PyCFunction)PyCurses_HalfDelay, METH_VARARGS}, - {"init_color", (PyCFunction)PyCurses_Init_Color, METH_VARARGS}, - {"init_pair", (PyCFunction)PyCurses_Init_Pair, METH_VARARGS}, - {"initscr", (PyCFunction)PyCurses_InitScr, METH_NOARGS}, - {"intrflush", (PyCFunction)PyCurses_IntrFlush, METH_VARARGS}, - {"isendwin", (PyCFunction)PyCurses_isendwin, METH_NOARGS}, + {"halfdelay", (PyCFunction)PyCurses_HalfDelay, METH_VARARGS}, + {"init_color", (PyCFunction)PyCurses_Init_Color, METH_VARARGS}, + {"init_pair", (PyCFunction)PyCurses_Init_Pair, METH_VARARGS}, + {"initscr", (PyCFunction)PyCurses_InitScr, METH_NOARGS}, + {"intrflush", (PyCFunction)PyCurses_IntrFlush, METH_VARARGS}, + {"isendwin", (PyCFunction)PyCurses_isendwin, METH_NOARGS}, #ifdef HAVE_CURSES_IS_TERM_RESIZED - {"is_term_resized", (PyCFunction)PyCurses_Is_Term_Resized, METH_VARARGS}, + {"is_term_resized", (PyCFunction)PyCurses_Is_Term_Resized, METH_VARARGS}, #endif #if !defined(__NetBSD__) - {"keyname", (PyCFunction)PyCurses_KeyName, METH_VARARGS}, + {"keyname", (PyCFunction)PyCurses_KeyName, METH_VARARGS}, #endif - {"killchar", (PyCFunction)PyCurses_KillChar, METH_NOARGS}, - {"longname", (PyCFunction)PyCurses_longname, METH_NOARGS}, - {"meta", (PyCFunction)PyCurses_Meta, METH_VARARGS}, + {"killchar", (PyCFunction)PyCurses_KillChar, METH_NOARGS}, + {"longname", (PyCFunction)PyCurses_longname, METH_NOARGS}, + {"meta", (PyCFunction)PyCurses_Meta, METH_VARARGS}, #ifdef NCURSES_MOUSE_VERSION - {"mouseinterval", (PyCFunction)PyCurses_MouseInterval, METH_VARARGS}, - {"mousemask", (PyCFunction)PyCurses_MouseMask, METH_VARARGS}, + {"mouseinterval", (PyCFunction)PyCurses_MouseInterval, METH_VARARGS}, + {"mousemask", (PyCFunction)PyCurses_MouseMask, METH_VARARGS}, #endif - {"napms", (PyCFunction)PyCurses_Napms, METH_VARARGS}, - {"newpad", (PyCFunction)PyCurses_NewPad, METH_VARARGS}, - {"newwin", (PyCFunction)PyCurses_NewWindow, METH_VARARGS}, - {"nl", (PyCFunction)PyCurses_nl, METH_VARARGS}, - {"nocbreak", (PyCFunction)PyCurses_nocbreak, METH_NOARGS}, - {"noecho", (PyCFunction)PyCurses_noecho, METH_NOARGS}, - {"nonl", (PyCFunction)PyCurses_nonl, METH_NOARGS}, - {"noqiflush", (PyCFunction)PyCurses_noqiflush, METH_NOARGS}, - {"noraw", (PyCFunction)PyCurses_noraw, METH_NOARGS}, - {"pair_content", (PyCFunction)PyCurses_Pair_Content, METH_VARARGS}, - {"pair_number", (PyCFunction)PyCurses_pair_number, METH_VARARGS}, - {"putp", (PyCFunction)PyCurses_Putp, METH_VARARGS}, - {"qiflush", (PyCFunction)PyCurses_QiFlush, METH_VARARGS}, - {"raw", (PyCFunction)PyCurses_raw, METH_VARARGS}, - {"reset_prog_mode", (PyCFunction)PyCurses_reset_prog_mode, METH_NOARGS}, - {"reset_shell_mode", (PyCFunction)PyCurses_reset_shell_mode, METH_NOARGS}, - {"resetty", (PyCFunction)PyCurses_resetty, METH_NOARGS}, + {"napms", (PyCFunction)PyCurses_Napms, METH_VARARGS}, + {"newpad", (PyCFunction)PyCurses_NewPad, METH_VARARGS}, + {"newwin", (PyCFunction)PyCurses_NewWindow, METH_VARARGS}, + {"nl", (PyCFunction)PyCurses_nl, METH_VARARGS}, + {"nocbreak", (PyCFunction)PyCurses_nocbreak, METH_NOARGS}, + {"noecho", (PyCFunction)PyCurses_noecho, METH_NOARGS}, + {"nonl", (PyCFunction)PyCurses_nonl, METH_NOARGS}, + {"noqiflush", (PyCFunction)PyCurses_noqiflush, METH_NOARGS}, + {"noraw", (PyCFunction)PyCurses_noraw, METH_NOARGS}, + {"pair_content", (PyCFunction)PyCurses_Pair_Content, METH_VARARGS}, + {"pair_number", (PyCFunction)PyCurses_pair_number, METH_VARARGS}, + {"putp", (PyCFunction)PyCurses_Putp, METH_VARARGS}, + {"qiflush", (PyCFunction)PyCurses_QiFlush, METH_VARARGS}, + {"raw", (PyCFunction)PyCurses_raw, METH_VARARGS}, + {"reset_prog_mode", (PyCFunction)PyCurses_reset_prog_mode, METH_NOARGS}, + {"reset_shell_mode", (PyCFunction)PyCurses_reset_shell_mode, METH_NOARGS}, + {"resetty", (PyCFunction)PyCurses_resetty, METH_NOARGS}, #ifdef HAVE_CURSES_RESIZETERM - {"resizeterm", (PyCFunction)PyCurses_ResizeTerm, METH_VARARGS}, + {"resizeterm", (PyCFunction)PyCurses_ResizeTerm, METH_VARARGS}, #endif #ifdef HAVE_CURSES_RESIZE_TERM - {"resize_term", (PyCFunction)PyCurses_Resize_Term, METH_VARARGS}, + {"resize_term", (PyCFunction)PyCurses_Resize_Term, METH_VARARGS}, #endif - {"savetty", (PyCFunction)PyCurses_savetty, METH_NOARGS}, - {"setsyx", (PyCFunction)PyCurses_setsyx, METH_VARARGS}, - {"setupterm", (PyCFunction)PyCurses_setupterm, - METH_VARARGS|METH_KEYWORDS}, - {"start_color", (PyCFunction)PyCurses_Start_Color, METH_NOARGS}, - {"termattrs", (PyCFunction)PyCurses_termattrs, METH_NOARGS}, - {"termname", (PyCFunction)PyCurses_termname, METH_NOARGS}, - {"tigetflag", (PyCFunction)PyCurses_tigetflag, METH_VARARGS}, - {"tigetnum", (PyCFunction)PyCurses_tigetnum, METH_VARARGS}, - {"tigetstr", (PyCFunction)PyCurses_tigetstr, METH_VARARGS}, - {"tparm", (PyCFunction)PyCurses_tparm, METH_VARARGS}, - {"typeahead", (PyCFunction)PyCurses_TypeAhead, METH_VARARGS}, - {"unctrl", (PyCFunction)PyCurses_UnCtrl, METH_VARARGS}, - {"ungetch", (PyCFunction)PyCurses_UngetCh, METH_VARARGS}, - {"use_env", (PyCFunction)PyCurses_Use_Env, METH_VARARGS}, + {"savetty", (PyCFunction)PyCurses_savetty, METH_NOARGS}, + {"setsyx", (PyCFunction)PyCurses_setsyx, METH_VARARGS}, + {"setupterm", (PyCFunction)PyCurses_setupterm, + METH_VARARGS|METH_KEYWORDS}, + {"start_color", (PyCFunction)PyCurses_Start_Color, METH_NOARGS}, + {"termattrs", (PyCFunction)PyCurses_termattrs, METH_NOARGS}, + {"termname", (PyCFunction)PyCurses_termname, METH_NOARGS}, + {"tigetflag", (PyCFunction)PyCurses_tigetflag, METH_VARARGS}, + {"tigetnum", (PyCFunction)PyCurses_tigetnum, METH_VARARGS}, + {"tigetstr", (PyCFunction)PyCurses_tigetstr, METH_VARARGS}, + {"tparm", (PyCFunction)PyCurses_tparm, METH_VARARGS}, + {"typeahead", (PyCFunction)PyCurses_TypeAhead, METH_VARARGS}, + {"unctrl", (PyCFunction)PyCurses_UnCtrl, METH_VARARGS}, + {"ungetch", (PyCFunction)PyCurses_UngetCh, METH_VARARGS}, + {"use_env", (PyCFunction)PyCurses_Use_Env, METH_VARARGS}, #ifndef STRICT_SYSV_CURSES - {"use_default_colors", (PyCFunction)PyCurses_Use_Default_Colors, METH_NOARGS}, + {"use_default_colors", (PyCFunction)PyCurses_Use_Default_Colors, METH_NOARGS}, #endif - {NULL, NULL} /* sentinel */ + {NULL, NULL} /* sentinel */ }; /* Initialization function for the module */ static struct PyModuleDef _cursesmodule = { - PyModuleDef_HEAD_INIT, - "_curses", - NULL, - -1, - PyCurses_methods, - NULL, - NULL, - NULL, - NULL + PyModuleDef_HEAD_INIT, + "_curses", + NULL, + -1, + PyCurses_methods, + NULL, + NULL, + NULL, + NULL }; PyMODINIT_FUNC PyInit__curses(void) { - PyObject *m, *d, *v, *c_api_object; - static void *PyCurses_API[PyCurses_API_pointers]; + PyObject *m, *d, *v, *c_api_object; + static void *PyCurses_API[PyCurses_API_pointers]; + + /* Initialize object type */ + if (PyType_Ready(&PyCursesWindow_Type) < 0) + return NULL; + + /* Initialize the C API pointer array */ + PyCurses_API[0] = (void *)&PyCursesWindow_Type; + PyCurses_API[1] = (void *)func_PyCursesSetupTermCalled; + PyCurses_API[2] = (void *)func_PyCursesInitialised; + PyCurses_API[3] = (void *)func_PyCursesInitialisedColor; + + /* Create the module and add the functions */ + m = PyModule_Create(&_cursesmodule); + if (m == NULL) + return NULL; - /* Initialize object type */ - if (PyType_Ready(&PyCursesWindow_Type) < 0) - return NULL; - - /* Initialize the C API pointer array */ - PyCurses_API[0] = (void *)&PyCursesWindow_Type; - PyCurses_API[1] = (void *)func_PyCursesSetupTermCalled; - PyCurses_API[2] = (void *)func_PyCursesInitialised; - PyCurses_API[3] = (void *)func_PyCursesInitialisedColor; - - /* Create the module and add the functions */ - m = PyModule_Create(&_cursesmodule); - if (m == NULL) - return NULL; - - /* Add some symbolic constants to the module */ - d = PyModule_GetDict(m); - if (d == NULL) - return NULL; - ModDict = d; /* For PyCurses_InitScr to use later */ - - /* Add a capsule for the C API */ - c_api_object = PyCapsule_New(PyCurses_API, PyCurses_CAPSULE_NAME, NULL); - PyDict_SetItemString(d, "_C_API", c_api_object); - Py_DECREF(c_api_object); - - /* For exception curses.error */ - PyCursesError = PyErr_NewException("_curses.error", NULL, NULL); - PyDict_SetItemString(d, "error", PyCursesError); - - /* Make the version available */ - v = PyBytes_FromString(PyCursesVersion); - PyDict_SetItemString(d, "version", v); - PyDict_SetItemString(d, "__version__", v); - Py_DECREF(v); - - SetDictInt("ERR", ERR); - SetDictInt("OK", OK); - - /* Here are some attributes you can add to chars to print */ - - SetDictInt("A_ATTRIBUTES", A_ATTRIBUTES); - SetDictInt("A_NORMAL", A_NORMAL); - SetDictInt("A_STANDOUT", A_STANDOUT); - SetDictInt("A_UNDERLINE", A_UNDERLINE); - SetDictInt("A_REVERSE", A_REVERSE); - SetDictInt("A_BLINK", A_BLINK); - SetDictInt("A_DIM", A_DIM); - SetDictInt("A_BOLD", A_BOLD); - SetDictInt("A_ALTCHARSET", A_ALTCHARSET); + /* Add some symbolic constants to the module */ + d = PyModule_GetDict(m); + if (d == NULL) + return NULL; + ModDict = d; /* For PyCurses_InitScr to use later */ + + /* Add a capsule for the C API */ + c_api_object = PyCapsule_New(PyCurses_API, PyCurses_CAPSULE_NAME, NULL); + PyDict_SetItemString(d, "_C_API", c_api_object); + Py_DECREF(c_api_object); + + /* For exception curses.error */ + PyCursesError = PyErr_NewException("_curses.error", NULL, NULL); + PyDict_SetItemString(d, "error", PyCursesError); + + /* Make the version available */ + v = PyBytes_FromString(PyCursesVersion); + PyDict_SetItemString(d, "version", v); + PyDict_SetItemString(d, "__version__", v); + Py_DECREF(v); + + SetDictInt("ERR", ERR); + SetDictInt("OK", OK); + + /* Here are some attributes you can add to chars to print */ + + SetDictInt("A_ATTRIBUTES", A_ATTRIBUTES); + SetDictInt("A_NORMAL", A_NORMAL); + SetDictInt("A_STANDOUT", A_STANDOUT); + SetDictInt("A_UNDERLINE", A_UNDERLINE); + SetDictInt("A_REVERSE", A_REVERSE); + SetDictInt("A_BLINK", A_BLINK); + SetDictInt("A_DIM", A_DIM); + SetDictInt("A_BOLD", A_BOLD); + SetDictInt("A_ALTCHARSET", A_ALTCHARSET); #if !defined(__NetBSD__) - SetDictInt("A_INVIS", A_INVIS); + SetDictInt("A_INVIS", A_INVIS); #endif - SetDictInt("A_PROTECT", A_PROTECT); - SetDictInt("A_CHARTEXT", A_CHARTEXT); - SetDictInt("A_COLOR", A_COLOR); + SetDictInt("A_PROTECT", A_PROTECT); + SetDictInt("A_CHARTEXT", A_CHARTEXT); + SetDictInt("A_COLOR", A_COLOR); - /* The following are never available with strict SYSV curses */ + /* The following are never available with strict SYSV curses */ #ifdef A_HORIZONTAL - SetDictInt("A_HORIZONTAL", A_HORIZONTAL); + SetDictInt("A_HORIZONTAL", A_HORIZONTAL); #endif #ifdef A_LEFT - SetDictInt("A_LEFT", A_LEFT); + SetDictInt("A_LEFT", A_LEFT); #endif #ifdef A_LOW - SetDictInt("A_LOW", A_LOW); + SetDictInt("A_LOW", A_LOW); #endif #ifdef A_RIGHT - SetDictInt("A_RIGHT", A_RIGHT); + SetDictInt("A_RIGHT", A_RIGHT); #endif #ifdef A_TOP - SetDictInt("A_TOP", A_TOP); + SetDictInt("A_TOP", A_TOP); #endif #ifdef A_VERTICAL - SetDictInt("A_VERTICAL", A_VERTICAL); + SetDictInt("A_VERTICAL", A_VERTICAL); #endif - SetDictInt("COLOR_BLACK", COLOR_BLACK); - SetDictInt("COLOR_RED", COLOR_RED); - SetDictInt("COLOR_GREEN", COLOR_GREEN); - SetDictInt("COLOR_YELLOW", COLOR_YELLOW); - SetDictInt("COLOR_BLUE", COLOR_BLUE); - SetDictInt("COLOR_MAGENTA", COLOR_MAGENTA); - SetDictInt("COLOR_CYAN", COLOR_CYAN); - SetDictInt("COLOR_WHITE", COLOR_WHITE); + SetDictInt("COLOR_BLACK", COLOR_BLACK); + SetDictInt("COLOR_RED", COLOR_RED); + SetDictInt("COLOR_GREEN", COLOR_GREEN); + SetDictInt("COLOR_YELLOW", COLOR_YELLOW); + SetDictInt("COLOR_BLUE", COLOR_BLUE); + SetDictInt("COLOR_MAGENTA", COLOR_MAGENTA); + SetDictInt("COLOR_CYAN", COLOR_CYAN); + SetDictInt("COLOR_WHITE", COLOR_WHITE); #ifdef NCURSES_MOUSE_VERSION - /* Mouse-related constants */ - SetDictInt("BUTTON1_PRESSED", BUTTON1_PRESSED); - SetDictInt("BUTTON1_RELEASED", BUTTON1_RELEASED); - SetDictInt("BUTTON1_CLICKED", BUTTON1_CLICKED); - SetDictInt("BUTTON1_DOUBLE_CLICKED", BUTTON1_DOUBLE_CLICKED); - SetDictInt("BUTTON1_TRIPLE_CLICKED", BUTTON1_TRIPLE_CLICKED); - - SetDictInt("BUTTON2_PRESSED", BUTTON2_PRESSED); - SetDictInt("BUTTON2_RELEASED", BUTTON2_RELEASED); - SetDictInt("BUTTON2_CLICKED", BUTTON2_CLICKED); - SetDictInt("BUTTON2_DOUBLE_CLICKED", BUTTON2_DOUBLE_CLICKED); - SetDictInt("BUTTON2_TRIPLE_CLICKED", BUTTON2_TRIPLE_CLICKED); - - SetDictInt("BUTTON3_PRESSED", BUTTON3_PRESSED); - SetDictInt("BUTTON3_RELEASED", BUTTON3_RELEASED); - SetDictInt("BUTTON3_CLICKED", BUTTON3_CLICKED); - SetDictInt("BUTTON3_DOUBLE_CLICKED", BUTTON3_DOUBLE_CLICKED); - SetDictInt("BUTTON3_TRIPLE_CLICKED", BUTTON3_TRIPLE_CLICKED); - - SetDictInt("BUTTON4_PRESSED", BUTTON4_PRESSED); - SetDictInt("BUTTON4_RELEASED", BUTTON4_RELEASED); - SetDictInt("BUTTON4_CLICKED", BUTTON4_CLICKED); - SetDictInt("BUTTON4_DOUBLE_CLICKED", BUTTON4_DOUBLE_CLICKED); - SetDictInt("BUTTON4_TRIPLE_CLICKED", BUTTON4_TRIPLE_CLICKED); - - SetDictInt("BUTTON_SHIFT", BUTTON_SHIFT); - SetDictInt("BUTTON_CTRL", BUTTON_CTRL); - SetDictInt("BUTTON_ALT", BUTTON_ALT); - - SetDictInt("ALL_MOUSE_EVENTS", ALL_MOUSE_EVENTS); - SetDictInt("REPORT_MOUSE_POSITION", REPORT_MOUSE_POSITION); -#endif - /* Now set everything up for KEY_ variables */ - { - int key; - char *key_n; - char *key_n2; + /* Mouse-related constants */ + SetDictInt("BUTTON1_PRESSED", BUTTON1_PRESSED); + SetDictInt("BUTTON1_RELEASED", BUTTON1_RELEASED); + SetDictInt("BUTTON1_CLICKED", BUTTON1_CLICKED); + SetDictInt("BUTTON1_DOUBLE_CLICKED", BUTTON1_DOUBLE_CLICKED); + SetDictInt("BUTTON1_TRIPLE_CLICKED", BUTTON1_TRIPLE_CLICKED); + + SetDictInt("BUTTON2_PRESSED", BUTTON2_PRESSED); + SetDictInt("BUTTON2_RELEASED", BUTTON2_RELEASED); + SetDictInt("BUTTON2_CLICKED", BUTTON2_CLICKED); + SetDictInt("BUTTON2_DOUBLE_CLICKED", BUTTON2_DOUBLE_CLICKED); + SetDictInt("BUTTON2_TRIPLE_CLICKED", BUTTON2_TRIPLE_CLICKED); + + SetDictInt("BUTTON3_PRESSED", BUTTON3_PRESSED); + SetDictInt("BUTTON3_RELEASED", BUTTON3_RELEASED); + SetDictInt("BUTTON3_CLICKED", BUTTON3_CLICKED); + SetDictInt("BUTTON3_DOUBLE_CLICKED", BUTTON3_DOUBLE_CLICKED); + SetDictInt("BUTTON3_TRIPLE_CLICKED", BUTTON3_TRIPLE_CLICKED); + + SetDictInt("BUTTON4_PRESSED", BUTTON4_PRESSED); + SetDictInt("BUTTON4_RELEASED", BUTTON4_RELEASED); + SetDictInt("BUTTON4_CLICKED", BUTTON4_CLICKED); + SetDictInt("BUTTON4_DOUBLE_CLICKED", BUTTON4_DOUBLE_CLICKED); + SetDictInt("BUTTON4_TRIPLE_CLICKED", BUTTON4_TRIPLE_CLICKED); + + SetDictInt("BUTTON_SHIFT", BUTTON_SHIFT); + SetDictInt("BUTTON_CTRL", BUTTON_CTRL); + SetDictInt("BUTTON_ALT", BUTTON_ALT); + + SetDictInt("ALL_MOUSE_EVENTS", ALL_MOUSE_EVENTS); + SetDictInt("REPORT_MOUSE_POSITION", REPORT_MOUSE_POSITION); +#endif + /* Now set everything up for KEY_ variables */ + { + int key; + char *key_n; + char *key_n2; #if !defined(__NetBSD__) - for (key=KEY_MIN;key < KEY_MAX; key++) { - key_n = (char *)keyname(key); - if (key_n == NULL || strcmp(key_n,"UNKNOWN KEY")==0) - continue; - if (strncmp(key_n,"KEY_F(",6)==0) { - char *p1, *p2; - key_n2 = malloc(strlen(key_n)+1); - if (!key_n2) { - PyErr_NoMemory(); - break; - } - p1 = key_n; - p2 = key_n2; - while (*p1) { - if (*p1 != '(' && *p1 != ')') { - *p2 = *p1; - p2++; - } - p1++; - } - *p2 = (char)0; - } else - key_n2 = key_n; - SetDictInt(key_n2,key); - if (key_n2 != key_n) - free(key_n2); - } -#endif - SetDictInt("KEY_MIN", KEY_MIN); - SetDictInt("KEY_MAX", KEY_MAX); - } - return m; + for (key=KEY_MIN;key < KEY_MAX; key++) { + key_n = (char *)keyname(key); + if (key_n == NULL || strcmp(key_n,"UNKNOWN KEY")==0) + continue; + if (strncmp(key_n,"KEY_F(",6)==0) { + char *p1, *p2; + key_n2 = malloc(strlen(key_n)+1); + if (!key_n2) { + PyErr_NoMemory(); + break; + } + p1 = key_n; + p2 = key_n2; + while (*p1) { + if (*p1 != '(' && *p1 != ')') { + *p2 = *p1; + p2++; + } + p1++; + } + *p2 = (char)0; + } else + key_n2 = key_n; + SetDictInt(key_n2,key); + if (key_n2 != key_n) + free(key_n2); + } +#endif + SetDictInt("KEY_MIN", KEY_MIN); + SetDictInt("KEY_MAX", KEY_MAX); + } + return m; } From python-checkins at python.org Sun May 16 00:26:41 2010 From: python-checkins at python.org (victor.stinner) Date: Sun, 16 May 2010 00:26:41 +0200 (CEST) Subject: [Python-checkins] r81216 - in python/branches/release26-maint: Modules/_cursesmodule.c Message-ID: <20100515222641.A7BD3EEB53@mail.python.org> Author: victor.stinner Date: Sun May 16 00:26:41 2010 New Revision: 81216 Log: Recorded merge of revisions 81213 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r81213 | victor.stinner | 2010-05-16 00:19:27 +0200 (dim., 16 mai 2010) | 5 lines reindent _cursesmodule.c Use untabify.py + emacs (python3 mode) + manual editions for Py_BEGIN_ALLOW_THREADS / Py_END_ALLOW_THREADS ........ Modified: python/branches/release26-maint/ (props changed) python/branches/release26-maint/Modules/_cursesmodule.c Modified: python/branches/release26-maint/Modules/_cursesmodule.c ============================================================================== --- python/branches/release26-maint/Modules/_cursesmodule.c (original) +++ python/branches/release26-maint/Modules/_cursesmodule.c Sun May 16 00:26:41 2010 @@ -35,66 +35,66 @@ /* -A number of SysV or ncurses functions don't have wrappers yet; if you -need a given function, add it and send a patch. See -http://www.python.org/dev/patches/ for instructions on how to submit -patches to Python. - -Here's a list of currently unsupported functions: - - addchnstr addchstr color_set define_key - del_curterm delscreen dupwin inchnstr inchstr innstr keyok - mcprint mvaddchnstr mvaddchstr mvcur mvinchnstr - mvinchstr mvinnstr mmvwaddchnstr mvwaddchstr - mvwinchnstr mvwinchstr mvwinnstr newterm - restartterm ripoffline scr_dump - scr_init scr_restore scr_set scrl set_curterm set_term setterm - tgetent tgetflag tgetnum tgetstr tgoto timeout tputs - vidattr vidputs waddchnstr waddchstr - wcolor_set winchnstr winchstr winnstr wmouse_trafo wscrl - -Low-priority: - slk_attr slk_attr_off slk_attr_on slk_attr_set slk_attroff - slk_attron slk_attrset slk_clear slk_color slk_init slk_label - slk_noutrefresh slk_refresh slk_restore slk_set slk_touch - -Menu extension (ncurses and probably SYSV): - current_item free_item free_menu item_count item_description - item_index item_init item_name item_opts item_opts_off - item_opts_on item_term item_userptr item_value item_visible - menu_back menu_driver menu_fore menu_format menu_grey - menu_init menu_items menu_mark menu_opts menu_opts_off - menu_opts_on menu_pad menu_pattern menu_request_by_name - menu_request_name menu_spacing menu_sub menu_term menu_userptr - menu_win new_item new_menu pos_menu_cursor post_menu - scale_menu set_current_item set_item_init set_item_opts - set_item_term set_item_userptr set_item_value set_menu_back - set_menu_fore set_menu_format set_menu_grey set_menu_init - set_menu_items set_menu_mark set_menu_opts set_menu_pad - set_menu_pattern set_menu_spacing set_menu_sub set_menu_term - set_menu_userptr set_menu_win set_top_row top_row unpost_menu - -Form extension (ncurses and probably SYSV): - current_field data_ahead data_behind dup_field - dynamic_fieldinfo field_arg field_back field_buffer - field_count field_fore field_index field_info field_init - field_just field_opts field_opts_off field_opts_on field_pad - field_status field_term field_type field_userptr form_driver - form_fields form_init form_opts form_opts_off form_opts_on - form_page form_request_by_name form_request_name form_sub - form_term form_userptr form_win free_field free_form - link_field link_fieldtype move_field new_field new_form - new_page pos_form_cursor post_form scale_form - set_current_field set_field_back set_field_buffer - set_field_fore set_field_init set_field_just set_field_opts - set_field_pad set_field_status set_field_term set_field_type - set_field_userptr set_fieldtype_arg set_fieldtype_choice - set_form_fields set_form_init set_form_opts set_form_page - set_form_sub set_form_term set_form_userptr set_form_win - set_max_field set_new_page unpost_form + A number of SysV or ncurses functions don't have wrappers yet; if you + need a given function, add it and send a patch. See + http://www.python.org/dev/patches/ for instructions on how to submit + patches to Python. + + Here's a list of currently unsupported functions: + + addchnstr addchstr color_set define_key + del_curterm delscreen dupwin inchnstr inchstr innstr keyok + mcprint mvaddchnstr mvaddchstr mvcur mvinchnstr + mvinchstr mvinnstr mmvwaddchnstr mvwaddchstr + mvwinchnstr mvwinchstr mvwinnstr newterm + restartterm ripoffline scr_dump + scr_init scr_restore scr_set scrl set_curterm set_term setterm + tgetent tgetflag tgetnum tgetstr tgoto timeout tputs + vidattr vidputs waddchnstr waddchstr + wcolor_set winchnstr winchstr winnstr wmouse_trafo wscrl + + Low-priority: + slk_attr slk_attr_off slk_attr_on slk_attr_set slk_attroff + slk_attron slk_attrset slk_clear slk_color slk_init slk_label + slk_noutrefresh slk_refresh slk_restore slk_set slk_touch + + Menu extension (ncurses and probably SYSV): + current_item free_item free_menu item_count item_description + item_index item_init item_name item_opts item_opts_off + item_opts_on item_term item_userptr item_value item_visible + menu_back menu_driver menu_fore menu_format menu_grey + menu_init menu_items menu_mark menu_opts menu_opts_off + menu_opts_on menu_pad menu_pattern menu_request_by_name + menu_request_name menu_spacing menu_sub menu_term menu_userptr + menu_win new_item new_menu pos_menu_cursor post_menu + scale_menu set_current_item set_item_init set_item_opts + set_item_term set_item_userptr set_item_value set_menu_back + set_menu_fore set_menu_format set_menu_grey set_menu_init + set_menu_items set_menu_mark set_menu_opts set_menu_pad + set_menu_pattern set_menu_spacing set_menu_sub set_menu_term + set_menu_userptr set_menu_win set_top_row top_row unpost_menu + + Form extension (ncurses and probably SYSV): + current_field data_ahead data_behind dup_field + dynamic_fieldinfo field_arg field_back field_buffer + field_count field_fore field_index field_info field_init + field_just field_opts field_opts_off field_opts_on field_pad + field_status field_term field_type field_userptr form_driver + form_fields form_init form_opts form_opts_off form_opts_on + form_page form_request_by_name form_request_name form_sub + form_term form_userptr form_win free_field free_form + link_field link_fieldtype move_field new_field new_form + new_page pos_form_cursor post_form scale_form + set_current_field set_field_back set_field_buffer + set_field_fore set_field_init set_field_just set_field_opts + set_field_pad set_field_status set_field_term set_field_type + set_field_userptr set_fieldtype_arg set_fieldtype_choice + set_form_fields set_form_init set_form_opts set_form_page + set_form_sub set_form_term set_form_userptr set_form_win + set_max_field set_new_page unpost_form - */ +*/ /* Release Number */ @@ -115,9 +115,9 @@ #define CURSES_MODULE #include "py_curses.h" -/* These prototypes are in , but including this header - #defines many common symbols (such as "lines") which breaks the - curses module in other ways. So the code will just specify +/* These prototypes are in , but including this header + #defines many common symbols (such as "lines") which breaks the + curses module in other ways. So the code will just specify explicit prototypes here. */ extern int setupterm(char *,int,int *); #ifdef __sgi @@ -147,23 +147,23 @@ static int initialisedcolors = FALSE; /* Utility Macros */ -#define PyCursesSetupTermCalled \ - if (initialised_setupterm != TRUE) { \ - PyErr_SetString(PyCursesError, \ - "must call (at least) setupterm() first"); \ - return 0; } - -#define PyCursesInitialised \ - if (initialised != TRUE) { \ - PyErr_SetString(PyCursesError, \ - "must call initscr() first"); \ - return 0; } - -#define PyCursesInitialisedColor \ - if (initialisedcolors != TRUE) { \ - PyErr_SetString(PyCursesError, \ - "must call start_color() first"); \ - return 0; } +#define PyCursesSetupTermCalled \ + if (initialised_setupterm != TRUE) { \ + PyErr_SetString(PyCursesError, \ + "must call (at least) setupterm() first"); \ + return 0; } + +#define PyCursesInitialised \ + if (initialised != TRUE) { \ + PyErr_SetString(PyCursesError, \ + "must call initscr() first"); \ + return 0; } + +#define PyCursesInitialisedColor \ + if (initialisedcolors != TRUE) { \ + PyErr_SetString(PyCursesError, \ + "must call start_color() first"); \ + return 0; } #ifndef MIN #define MIN(x,y) ((x) < (y) ? (x) : (y)) @@ -172,44 +172,44 @@ /* Utility Functions */ /* - * Check the return code from a curses function and return None + * Check the return code from a curses function and return None * or raise an exception as appropriate. These are exported using the - * CObject API. + * CObject API. */ static PyObject * PyCursesCheckERR(int code, char *fname) { - if (code != ERR) { - Py_INCREF(Py_None); - return Py_None; - } else { - if (fname == NULL) { - PyErr_SetString(PyCursesError, catchall_ERR); + if (code != ERR) { + Py_INCREF(Py_None); + return Py_None; } else { - PyErr_Format(PyCursesError, "%s() returned ERR", fname); + if (fname == NULL) { + PyErr_SetString(PyCursesError, catchall_ERR); + } else { + PyErr_Format(PyCursesError, "%s() returned ERR", fname); + } + return NULL; } - return NULL; - } } -static int +static int PyCurses_ConvertToChtype(PyObject *obj, chtype *ch) { - if (PyInt_Check(obj)) { - *ch = (chtype) PyInt_AsLong(obj); - } else if(PyString_Check(obj) - && (PyString_Size(obj) == 1)) { - *ch = (chtype) *PyString_AsString(obj); - } else { - return 0; - } - return 1; + if (PyInt_Check(obj)) { + *ch = (chtype) PyInt_AsLong(obj); + } else if(PyString_Check(obj) + && (PyString_Size(obj) == 1)) { + *ch = (chtype) *PyString_AsString(obj); + } else { + return 0; + } + return 1; } /* Function versions of the 3 functions for tested whether curses has been initialised or not. */ - + static int func_PyCursesSetupTermCalled(void) { PyCursesSetupTermCalled; @@ -242,49 +242,49 @@ TYPE - parameter Type ERGSTR - format string for construction of the return value PARSESTR - format string for argument parsing - */ +*/ -#define Window_NoArgNoReturnFunction(X) \ -static PyObject *PyCursesWindow_ ## X (PyCursesWindowObject *self, PyObject *args) \ -{ return PyCursesCheckERR(X(self->win), # X); } - -#define Window_NoArgTrueFalseFunction(X) \ -static PyObject * PyCursesWindow_ ## X (PyCursesWindowObject *self) \ -{ \ - if (X (self->win) == FALSE) { Py_INCREF(Py_False); return Py_False; } \ - else { Py_INCREF(Py_True); return Py_True; } } - -#define Window_NoArgNoReturnVoidFunction(X) \ -static PyObject * PyCursesWindow_ ## X (PyCursesWindowObject *self) \ -{ \ - X(self->win); Py_INCREF(Py_None); return Py_None; } - -#define Window_NoArg2TupleReturnFunction(X, TYPE, ERGSTR) \ -static PyObject * PyCursesWindow_ ## X (PyCursesWindowObject *self) \ -{ \ - TYPE arg1, arg2; \ - X(self->win,arg1,arg2); return Py_BuildValue(ERGSTR, arg1, arg2); } - -#define Window_OneArgNoReturnVoidFunction(X, TYPE, PARSESTR) \ -static PyObject * PyCursesWindow_ ## X (PyCursesWindowObject *self, PyObject *args) \ -{ \ - TYPE arg1; \ - if (!PyArg_ParseTuple(args, PARSESTR, &arg1)) return NULL; \ - X(self->win,arg1); Py_INCREF(Py_None); return Py_None; } - -#define Window_OneArgNoReturnFunction(X, TYPE, PARSESTR) \ -static PyObject * PyCursesWindow_ ## X (PyCursesWindowObject *self, PyObject *args) \ -{ \ - TYPE arg1; \ - if (!PyArg_ParseTuple(args,PARSESTR, &arg1)) return NULL; \ - return PyCursesCheckERR(X(self->win, arg1), # X); } - -#define Window_TwoArgNoReturnFunction(X, TYPE, PARSESTR) \ -static PyObject * PyCursesWindow_ ## X (PyCursesWindowObject *self, PyObject *args) \ -{ \ - TYPE arg1, arg2; \ - if (!PyArg_ParseTuple(args,PARSESTR, &arg1, &arg2)) return NULL; \ - return PyCursesCheckERR(X(self->win, arg1, arg2), # X); } +#define Window_NoArgNoReturnFunction(X) \ + static PyObject *PyCursesWindow_ ## X (PyCursesWindowObject *self, PyObject *args) \ + { return PyCursesCheckERR(X(self->win), # X); } + +#define Window_NoArgTrueFalseFunction(X) \ + static PyObject * PyCursesWindow_ ## X (PyCursesWindowObject *self) \ + { \ + if (X (self->win) == FALSE) { Py_INCREF(Py_False); return Py_False; } \ + else { Py_INCREF(Py_True); return Py_True; } } + +#define Window_NoArgNoReturnVoidFunction(X) \ + static PyObject * PyCursesWindow_ ## X (PyCursesWindowObject *self) \ + { \ + X(self->win); Py_INCREF(Py_None); return Py_None; } + +#define Window_NoArg2TupleReturnFunction(X, TYPE, ERGSTR) \ + static PyObject * PyCursesWindow_ ## X (PyCursesWindowObject *self) \ + { \ + TYPE arg1, arg2; \ + X(self->win,arg1,arg2); return Py_BuildValue(ERGSTR, arg1, arg2); } + +#define Window_OneArgNoReturnVoidFunction(X, TYPE, PARSESTR) \ + static PyObject * PyCursesWindow_ ## X (PyCursesWindowObject *self, PyObject *args) \ + { \ + TYPE arg1; \ + if (!PyArg_ParseTuple(args, PARSESTR, &arg1)) return NULL; \ + X(self->win,arg1); Py_INCREF(Py_None); return Py_None; } + +#define Window_OneArgNoReturnFunction(X, TYPE, PARSESTR) \ + static PyObject * PyCursesWindow_ ## X (PyCursesWindowObject *self, PyObject *args) \ + { \ + TYPE arg1; \ + if (!PyArg_ParseTuple(args,PARSESTR, &arg1)) return NULL; \ + return PyCursesCheckERR(X(self->win, arg1), # X); } + +#define Window_TwoArgNoReturnFunction(X, TYPE, PARSESTR) \ + static PyObject * PyCursesWindow_ ## X (PyCursesWindowObject *self, PyObject *args) \ + { \ + TYPE arg1, arg2; \ + if (!PyArg_ParseTuple(args,PARSESTR, &arg1, &arg2)) return NULL; \ + return PyCursesCheckERR(X(self->win, arg1, arg2), # X); } /* ------------- WINDOW routines --------------- */ @@ -345,19 +345,19 @@ static PyObject * PyCursesWindow_New(WINDOW *win) { - PyCursesWindowObject *wo; + PyCursesWindowObject *wo; - wo = PyObject_NEW(PyCursesWindowObject, &PyCursesWindow_Type); - if (wo == NULL) return NULL; - wo->win = win; - return (PyObject *)wo; + wo = PyObject_NEW(PyCursesWindowObject, &PyCursesWindow_Type); + if (wo == NULL) return NULL; + wo->win = win; + return (PyObject *)wo; } static void PyCursesWindow_Dealloc(PyCursesWindowObject *wo) { - if (wo->win != stdscr) delwin(wo->win); - PyObject_DEL(wo); + if (wo->win != stdscr) delwin(wo->win); + PyObject_DEL(wo); } /* Addch, Addstr, Addnstr */ @@ -365,287 +365,287 @@ static PyObject * PyCursesWindow_AddCh(PyCursesWindowObject *self, PyObject *args) { - int rtn, x, y, use_xy = FALSE; - PyObject *temp; - chtype ch = 0; - attr_t attr = A_NORMAL; - long lattr; - - switch (PyTuple_Size(args)) { - case 1: - if (!PyArg_ParseTuple(args, "O;ch or int", &temp)) - return NULL; - break; - case 2: - if (!PyArg_ParseTuple(args, "Ol;ch or int,attr", &temp, &lattr)) - return NULL; - attr = lattr; - break; - case 3: - if (!PyArg_ParseTuple(args,"iiO;y,x,ch or int", &y, &x, &temp)) - return NULL; - use_xy = TRUE; - break; - case 4: - if (!PyArg_ParseTuple(args,"iiOl;y,x,ch or int, attr", - &y, &x, &temp, &lattr)) - return NULL; - attr = lattr; - use_xy = TRUE; - break; - default: - PyErr_SetString(PyExc_TypeError, "addch requires 1 to 4 arguments"); - return NULL; - } - - if (!PyCurses_ConvertToChtype(temp, &ch)) { - PyErr_SetString(PyExc_TypeError, "argument 1 or 3 must be a ch or an int"); - return NULL; - } - - if (use_xy == TRUE) - rtn = mvwaddch(self->win,y,x, ch | attr); - else { - rtn = waddch(self->win, ch | attr); - } - return PyCursesCheckERR(rtn, "addch"); + int rtn, x, y, use_xy = FALSE; + PyObject *temp; + chtype ch = 0; + attr_t attr = A_NORMAL; + long lattr; + + switch (PyTuple_Size(args)) { + case 1: + if (!PyArg_ParseTuple(args, "O;ch or int", &temp)) + return NULL; + break; + case 2: + if (!PyArg_ParseTuple(args, "Ol;ch or int,attr", &temp, &lattr)) + return NULL; + attr = lattr; + break; + case 3: + if (!PyArg_ParseTuple(args,"iiO;y,x,ch or int", &y, &x, &temp)) + return NULL; + use_xy = TRUE; + break; + case 4: + if (!PyArg_ParseTuple(args,"iiOl;y,x,ch or int, attr", + &y, &x, &temp, &lattr)) + return NULL; + attr = lattr; + use_xy = TRUE; + break; + default: + PyErr_SetString(PyExc_TypeError, "addch requires 1 to 4 arguments"); + return NULL; + } + + if (!PyCurses_ConvertToChtype(temp, &ch)) { + PyErr_SetString(PyExc_TypeError, "argument 1 or 3 must be a ch or an int"); + return NULL; + } + + if (use_xy == TRUE) + rtn = mvwaddch(self->win,y,x, ch | attr); + else { + rtn = waddch(self->win, ch | attr); + } + return PyCursesCheckERR(rtn, "addch"); } static PyObject * PyCursesWindow_AddStr(PyCursesWindowObject *self, PyObject *args) { - int rtn; - int x, y; - char *str; - attr_t attr = A_NORMAL , attr_old = A_NORMAL; - long lattr; - int use_xy = FALSE, use_attr = FALSE; - - switch (PyTuple_Size(args)) { - case 1: - if (!PyArg_ParseTuple(args,"s;str", &str)) - return NULL; - break; - case 2: - if (!PyArg_ParseTuple(args,"sl;str,attr", &str, &lattr)) - return NULL; - attr = lattr; - use_attr = TRUE; - break; - case 3: - if (!PyArg_ParseTuple(args,"iis;int,int,str", &y, &x, &str)) - return NULL; - use_xy = TRUE; - break; - case 4: - if (!PyArg_ParseTuple(args,"iisl;int,int,str,attr", &y, &x, &str, &lattr)) - return NULL; - attr = lattr; - use_xy = use_attr = TRUE; - break; - default: - PyErr_SetString(PyExc_TypeError, "addstr requires 1 to 4 arguments"); - return NULL; - } - - if (use_attr == TRUE) { - attr_old = getattrs(self->win); - (void)wattrset(self->win,attr); - } - if (use_xy == TRUE) - rtn = mvwaddstr(self->win,y,x,str); - else - rtn = waddstr(self->win,str); - if (use_attr == TRUE) - (void)wattrset(self->win,attr_old); - return PyCursesCheckERR(rtn, "addstr"); + int rtn; + int x, y; + char *str; + attr_t attr = A_NORMAL , attr_old = A_NORMAL; + long lattr; + int use_xy = FALSE, use_attr = FALSE; + + switch (PyTuple_Size(args)) { + case 1: + if (!PyArg_ParseTuple(args,"s;str", &str)) + return NULL; + break; + case 2: + if (!PyArg_ParseTuple(args,"sl;str,attr", &str, &lattr)) + return NULL; + attr = lattr; + use_attr = TRUE; + break; + case 3: + if (!PyArg_ParseTuple(args,"iis;int,int,str", &y, &x, &str)) + return NULL; + use_xy = TRUE; + break; + case 4: + if (!PyArg_ParseTuple(args,"iisl;int,int,str,attr", &y, &x, &str, &lattr)) + return NULL; + attr = lattr; + use_xy = use_attr = TRUE; + break; + default: + PyErr_SetString(PyExc_TypeError, "addstr requires 1 to 4 arguments"); + return NULL; + } + + if (use_attr == TRUE) { + attr_old = getattrs(self->win); + (void)wattrset(self->win,attr); + } + if (use_xy == TRUE) + rtn = mvwaddstr(self->win,y,x,str); + else + rtn = waddstr(self->win,str); + if (use_attr == TRUE) + (void)wattrset(self->win,attr_old); + return PyCursesCheckERR(rtn, "addstr"); } static PyObject * PyCursesWindow_AddNStr(PyCursesWindowObject *self, PyObject *args) { - int rtn, x, y, n; - char *str; - attr_t attr = A_NORMAL , attr_old = A_NORMAL; - long lattr; - int use_xy = FALSE, use_attr = FALSE; - - switch (PyTuple_Size(args)) { - case 2: - if (!PyArg_ParseTuple(args,"si;str,n", &str, &n)) - return NULL; - break; - case 3: - if (!PyArg_ParseTuple(args,"sil;str,n,attr", &str, &n, &lattr)) - return NULL; - attr = lattr; - use_attr = TRUE; - break; - case 4: - if (!PyArg_ParseTuple(args,"iisi;y,x,str,n", &y, &x, &str, &n)) - return NULL; - use_xy = TRUE; - break; - case 5: - if (!PyArg_ParseTuple(args,"iisil;y,x,str,n,attr", &y, &x, &str, &n, &lattr)) - return NULL; - attr = lattr; - use_xy = use_attr = TRUE; - break; - default: - PyErr_SetString(PyExc_TypeError, "addnstr requires 2 to 5 arguments"); - return NULL; - } - - if (use_attr == TRUE) { - attr_old = getattrs(self->win); - (void)wattrset(self->win,attr); - } - if (use_xy == TRUE) - rtn = mvwaddnstr(self->win,y,x,str,n); - else - rtn = waddnstr(self->win,str,n); - if (use_attr == TRUE) - (void)wattrset(self->win,attr_old); - return PyCursesCheckERR(rtn, "addnstr"); + int rtn, x, y, n; + char *str; + attr_t attr = A_NORMAL , attr_old = A_NORMAL; + long lattr; + int use_xy = FALSE, use_attr = FALSE; + + switch (PyTuple_Size(args)) { + case 2: + if (!PyArg_ParseTuple(args,"si;str,n", &str, &n)) + return NULL; + break; + case 3: + if (!PyArg_ParseTuple(args,"sil;str,n,attr", &str, &n, &lattr)) + return NULL; + attr = lattr; + use_attr = TRUE; + break; + case 4: + if (!PyArg_ParseTuple(args,"iisi;y,x,str,n", &y, &x, &str, &n)) + return NULL; + use_xy = TRUE; + break; + case 5: + if (!PyArg_ParseTuple(args,"iisil;y,x,str,n,attr", &y, &x, &str, &n, &lattr)) + return NULL; + attr = lattr; + use_xy = use_attr = TRUE; + break; + default: + PyErr_SetString(PyExc_TypeError, "addnstr requires 2 to 5 arguments"); + return NULL; + } + + if (use_attr == TRUE) { + attr_old = getattrs(self->win); + (void)wattrset(self->win,attr); + } + if (use_xy == TRUE) + rtn = mvwaddnstr(self->win,y,x,str,n); + else + rtn = waddnstr(self->win,str,n); + if (use_attr == TRUE) + (void)wattrset(self->win,attr_old); + return PyCursesCheckERR(rtn, "addnstr"); } static PyObject * PyCursesWindow_Bkgd(PyCursesWindowObject *self, PyObject *args) { - PyObject *temp; - chtype bkgd; - attr_t attr = A_NORMAL; - long lattr; + PyObject *temp; + chtype bkgd; + attr_t attr = A_NORMAL; + long lattr; - switch (PyTuple_Size(args)) { + switch (PyTuple_Size(args)) { case 1: - if (!PyArg_ParseTuple(args, "O;ch or int", &temp)) - return NULL; - break; + if (!PyArg_ParseTuple(args, "O;ch or int", &temp)) + return NULL; + break; case 2: - if (!PyArg_ParseTuple(args,"Ol;ch or int,attr", &temp, &lattr)) - return NULL; - attr = lattr; - break; + if (!PyArg_ParseTuple(args,"Ol;ch or int,attr", &temp, &lattr)) + return NULL; + attr = lattr; + break; default: - PyErr_SetString(PyExc_TypeError, "bkgd requires 1 or 2 arguments"); - return NULL; - } - - if (!PyCurses_ConvertToChtype(temp, &bkgd)) { - PyErr_SetString(PyExc_TypeError, "argument 1 or 3 must be a ch or an int"); - return NULL; - } + PyErr_SetString(PyExc_TypeError, "bkgd requires 1 or 2 arguments"); + return NULL; + } + + if (!PyCurses_ConvertToChtype(temp, &bkgd)) { + PyErr_SetString(PyExc_TypeError, "argument 1 or 3 must be a ch or an int"); + return NULL; + } - return PyCursesCheckERR(wbkgd(self->win, bkgd | attr), "bkgd"); + return PyCursesCheckERR(wbkgd(self->win, bkgd | attr), "bkgd"); } static PyObject * PyCursesWindow_AttrOff(PyCursesWindowObject *self, PyObject *args) { - long lattr; - if (!PyArg_ParseTuple(args,"l;attr", &lattr)) - return NULL; - return PyCursesCheckERR(wattroff(self->win, (attr_t)lattr), "attroff"); + long lattr; + if (!PyArg_ParseTuple(args,"l;attr", &lattr)) + return NULL; + return PyCursesCheckERR(wattroff(self->win, (attr_t)lattr), "attroff"); } static PyObject * PyCursesWindow_AttrOn(PyCursesWindowObject *self, PyObject *args) { - long lattr; - if (!PyArg_ParseTuple(args,"l;attr", &lattr)) - return NULL; - return PyCursesCheckERR(wattron(self->win, (attr_t)lattr), "attron"); + long lattr; + if (!PyArg_ParseTuple(args,"l;attr", &lattr)) + return NULL; + return PyCursesCheckERR(wattron(self->win, (attr_t)lattr), "attron"); } static PyObject * PyCursesWindow_AttrSet(PyCursesWindowObject *self, PyObject *args) { - long lattr; - if (!PyArg_ParseTuple(args,"l;attr", &lattr)) - return NULL; - return PyCursesCheckERR(wattrset(self->win, (attr_t)lattr), "attrset"); + long lattr; + if (!PyArg_ParseTuple(args,"l;attr", &lattr)) + return NULL; + return PyCursesCheckERR(wattrset(self->win, (attr_t)lattr), "attrset"); } static PyObject * PyCursesWindow_BkgdSet(PyCursesWindowObject *self, PyObject *args) { - PyObject *temp; - chtype bkgd; - attr_t attr = A_NORMAL; - long lattr; + PyObject *temp; + chtype bkgd; + attr_t attr = A_NORMAL; + long lattr; - switch (PyTuple_Size(args)) { + switch (PyTuple_Size(args)) { case 1: - if (!PyArg_ParseTuple(args, "O;ch or int", &temp)) - return NULL; - break; + if (!PyArg_ParseTuple(args, "O;ch or int", &temp)) + return NULL; + break; case 2: - if (!PyArg_ParseTuple(args,"Ol;ch or int,attr", &temp, &lattr)) - return NULL; - attr = lattr; - break; + if (!PyArg_ParseTuple(args,"Ol;ch or int,attr", &temp, &lattr)) + return NULL; + attr = lattr; + break; default: - PyErr_SetString(PyExc_TypeError, "bkgdset requires 1 or 2 arguments"); - return NULL; - } - - if (!PyCurses_ConvertToChtype(temp, &bkgd)) { - PyErr_SetString(PyExc_TypeError, "argument 1 must be a ch or an int"); - return NULL; - } + PyErr_SetString(PyExc_TypeError, "bkgdset requires 1 or 2 arguments"); + return NULL; + } + + if (!PyCurses_ConvertToChtype(temp, &bkgd)) { + PyErr_SetString(PyExc_TypeError, "argument 1 must be a ch or an int"); + return NULL; + } - wbkgdset(self->win, bkgd | attr); - return PyCursesCheckERR(0, "bkgdset"); + wbkgdset(self->win, bkgd | attr); + return PyCursesCheckERR(0, "bkgdset"); } static PyObject * PyCursesWindow_Border(PyCursesWindowObject *self, PyObject *args) { - PyObject *temp[8]; - chtype ch[8]; - int i; - - /* Clear the array of parameters */ - for(i=0; i<8; i++) { - temp[i] = NULL; - ch[i] = 0; - } - - if (!PyArg_ParseTuple(args,"|OOOOOOOO;ls,rs,ts,bs,tl,tr,bl,br", - &temp[0], &temp[1], &temp[2], &temp[3], - &temp[4], &temp[5], &temp[6], &temp[7])) - return NULL; - - for(i=0; i<8; i++) { - if (temp[i] != NULL && !PyCurses_ConvertToChtype(temp[i], &ch[i])) { - PyErr_Format(PyExc_TypeError, - "argument %i must be a ch or an int", i+1); - return NULL; - } - } - - wborder(self->win, - ch[0], ch[1], ch[2], ch[3], - ch[4], ch[5], ch[6], ch[7]); - Py_INCREF(Py_None); - return Py_None; + PyObject *temp[8]; + chtype ch[8]; + int i; + + /* Clear the array of parameters */ + for(i=0; i<8; i++) { + temp[i] = NULL; + ch[i] = 0; + } + + if (!PyArg_ParseTuple(args,"|OOOOOOOO;ls,rs,ts,bs,tl,tr,bl,br", + &temp[0], &temp[1], &temp[2], &temp[3], + &temp[4], &temp[5], &temp[6], &temp[7])) + return NULL; + + for(i=0; i<8; i++) { + if (temp[i] != NULL && !PyCurses_ConvertToChtype(temp[i], &ch[i])) { + PyErr_Format(PyExc_TypeError, + "argument %i must be a ch or an int", i+1); + return NULL; + } + } + + wborder(self->win, + ch[0], ch[1], ch[2], ch[3], + ch[4], ch[5], ch[6], ch[7]); + Py_INCREF(Py_None); + return Py_None; } static PyObject * PyCursesWindow_Box(PyCursesWindowObject *self, PyObject *args) { - chtype ch1=0,ch2=0; - switch(PyTuple_Size(args)){ - case 0: break; - default: - if (!PyArg_ParseTuple(args,"ll;vertint,horint", &ch1, &ch2)) - return NULL; - } - box(self->win,ch1,ch2); - Py_INCREF(Py_None); - return Py_None; + chtype ch1=0,ch2=0; + switch(PyTuple_Size(args)){ + case 0: break; + default: + if (!PyArg_ParseTuple(args,"ll;vertint,horint", &ch1, &ch2)) + return NULL; + } + box(self->win,ch1,ch2); + Py_INCREF(Py_None); + return Py_None; } #if defined(HAVE_NCURSES_H) || defined(MVWDELCH_IS_EXPRESSION) @@ -653,10 +653,10 @@ #else int py_mvwdelch(WINDOW *w, int y, int x) { - mvwdelch(w,y,x); - /* On HP/UX, mvwdelch already returns. On other systems, - we may well run into this return statement. */ - return 0; + mvwdelch(w,y,x); + /* On HP/UX, mvwdelch already returns. On other systems, + we may well run into this return statement. */ + return 0; } #endif @@ -665,2220 +665,2220 @@ static PyObject * PyCursesWindow_ChgAt(PyCursesWindowObject *self, PyObject *args) { - int rtn; - int x, y; - int num = -1; - short color; - attr_t attr = A_NORMAL; - long lattr; - int use_xy = FALSE; + int rtn; + int x, y; + int num = -1; + short color; + attr_t attr = A_NORMAL; + long lattr; + int use_xy = FALSE; - switch (PyTuple_Size(args)) { - case 1: - if (!PyArg_ParseTuple(args,"l;attr", &lattr)) - return NULL; - attr = lattr; - break; - case 2: - if (!PyArg_ParseTuple(args,"il;n,attr", &num, &lattr)) - return NULL; - attr = lattr; - break; - case 3: - if (!PyArg_ParseTuple(args,"iil;int,int,attr", &y, &x, &lattr)) - return NULL; - attr = lattr; - use_xy = TRUE; - break; - case 4: - if (!PyArg_ParseTuple(args,"iiil;int,int,n,attr", &y, &x, &num, &lattr)) - return NULL; - attr = lattr; - use_xy = TRUE; - break; - default: - PyErr_SetString(PyExc_TypeError, "chgat requires 1 to 4 arguments"); - return NULL; - } - - color = (short)((attr >> 8) & 0xff); - attr = attr - (color << 8); - - if (use_xy == TRUE) { - rtn = mvwchgat(self->win,y,x,num,attr,color,NULL); - touchline(self->win,y,1); - } else { - getyx(self->win,y,x); - rtn = wchgat(self->win,num,attr,color,NULL); - touchline(self->win,y,1); - } - return PyCursesCheckERR(rtn, "chgat"); + switch (PyTuple_Size(args)) { + case 1: + if (!PyArg_ParseTuple(args,"l;attr", &lattr)) + return NULL; + attr = lattr; + break; + case 2: + if (!PyArg_ParseTuple(args,"il;n,attr", &num, &lattr)) + return NULL; + attr = lattr; + break; + case 3: + if (!PyArg_ParseTuple(args,"iil;int,int,attr", &y, &x, &lattr)) + return NULL; + attr = lattr; + use_xy = TRUE; + break; + case 4: + if (!PyArg_ParseTuple(args,"iiil;int,int,n,attr", &y, &x, &num, &lattr)) + return NULL; + attr = lattr; + use_xy = TRUE; + break; + default: + PyErr_SetString(PyExc_TypeError, "chgat requires 1 to 4 arguments"); + return NULL; + } + + color = (short)((attr >> 8) & 0xff); + attr = attr - (color << 8); + + if (use_xy == TRUE) { + rtn = mvwchgat(self->win,y,x,num,attr,color,NULL); + touchline(self->win,y,1); + } else { + getyx(self->win,y,x); + rtn = wchgat(self->win,num,attr,color,NULL); + touchline(self->win,y,1); + } + return PyCursesCheckERR(rtn, "chgat"); } static PyObject * PyCursesWindow_DelCh(PyCursesWindowObject *self, PyObject *args) { - int rtn; - int x, y; + int rtn; + int x, y; - switch (PyTuple_Size(args)) { - case 0: - rtn = wdelch(self->win); - break; - case 2: - if (!PyArg_ParseTuple(args,"ii;y,x", &y, &x)) - return NULL; - rtn = py_mvwdelch(self->win,y,x); - break; - default: - PyErr_SetString(PyExc_TypeError, "delch requires 0 or 2 arguments"); - return NULL; - } - return PyCursesCheckERR(rtn, "[mv]wdelch"); + switch (PyTuple_Size(args)) { + case 0: + rtn = wdelch(self->win); + break; + case 2: + if (!PyArg_ParseTuple(args,"ii;y,x", &y, &x)) + return NULL; + rtn = py_mvwdelch(self->win,y,x); + break; + default: + PyErr_SetString(PyExc_TypeError, "delch requires 0 or 2 arguments"); + return NULL; + } + return PyCursesCheckERR(rtn, "[mv]wdelch"); } static PyObject * PyCursesWindow_DerWin(PyCursesWindowObject *self, PyObject *args) { - WINDOW *win; - int nlines, ncols, begin_y, begin_x; + WINDOW *win; + int nlines, ncols, begin_y, begin_x; - nlines = 0; - ncols = 0; - switch (PyTuple_Size(args)) { - case 2: - if (!PyArg_ParseTuple(args,"ii;begin_y,begin_x",&begin_y,&begin_x)) - return NULL; - break; - case 4: - if (!PyArg_ParseTuple(args, "iiii;nlines,ncols,begin_y,begin_x", - &nlines,&ncols,&begin_y,&begin_x)) - return NULL; - break; - default: - PyErr_SetString(PyExc_TypeError, "derwin requires 2 or 4 arguments"); - return NULL; - } - - win = derwin(self->win,nlines,ncols,begin_y,begin_x); - - if (win == NULL) { - PyErr_SetString(PyCursesError, catchall_NULL); - return NULL; - } + nlines = 0; + ncols = 0; + switch (PyTuple_Size(args)) { + case 2: + if (!PyArg_ParseTuple(args,"ii;begin_y,begin_x",&begin_y,&begin_x)) + return NULL; + break; + case 4: + if (!PyArg_ParseTuple(args, "iiii;nlines,ncols,begin_y,begin_x", + &nlines,&ncols,&begin_y,&begin_x)) + return NULL; + break; + default: + PyErr_SetString(PyExc_TypeError, "derwin requires 2 or 4 arguments"); + return NULL; + } + + win = derwin(self->win,nlines,ncols,begin_y,begin_x); + + if (win == NULL) { + PyErr_SetString(PyCursesError, catchall_NULL); + return NULL; + } - return (PyObject *)PyCursesWindow_New(win); + return (PyObject *)PyCursesWindow_New(win); } static PyObject * PyCursesWindow_EchoChar(PyCursesWindowObject *self, PyObject *args) { - PyObject *temp; - chtype ch; - attr_t attr = A_NORMAL; - long lattr; - - switch (PyTuple_Size(args)) { - case 1: - if (!PyArg_ParseTuple(args,"O;ch or int", &temp)) - return NULL; - break; - case 2: - if (!PyArg_ParseTuple(args,"Ol;ch or int,attr", &temp, &lattr)) - return NULL; - attr = lattr; - break; - default: - PyErr_SetString(PyExc_TypeError, "echochar requires 1 or 2 arguments"); - - - return NULL; - } - - if (!PyCurses_ConvertToChtype(temp, &ch)) { - PyErr_SetString(PyExc_TypeError, "argument 1 must be a ch or an int"); - return NULL; - } - + PyObject *temp; + chtype ch; + attr_t attr = A_NORMAL; + long lattr; + + switch (PyTuple_Size(args)) { + case 1: + if (!PyArg_ParseTuple(args,"O;ch or int", &temp)) + return NULL; + break; + case 2: + if (!PyArg_ParseTuple(args,"Ol;ch or int,attr", &temp, &lattr)) + return NULL; + attr = lattr; + break; + default: + PyErr_SetString(PyExc_TypeError, "echochar requires 1 or 2 arguments"); + + + return NULL; + } + + if (!PyCurses_ConvertToChtype(temp, &ch)) { + PyErr_SetString(PyExc_TypeError, "argument 1 must be a ch or an int"); + return NULL; + } + #ifdef WINDOW_HAS_FLAGS - if (self->win->_flags & _ISPAD) - return PyCursesCheckERR(pechochar(self->win, ch | attr), - "echochar"); - else + if (self->win->_flags & _ISPAD) + return PyCursesCheckERR(pechochar(self->win, ch | attr), + "echochar"); + else #endif - return PyCursesCheckERR(wechochar(self->win, ch | attr), - "echochar"); + return PyCursesCheckERR(wechochar(self->win, ch | attr), + "echochar"); } #ifdef NCURSES_MOUSE_VERSION static PyObject * PyCursesWindow_Enclose(PyCursesWindowObject *self, PyObject *args) { - int x, y; - if (!PyArg_ParseTuple(args,"ii;y,x", &y, &x)) - return NULL; + int x, y; + if (!PyArg_ParseTuple(args,"ii;y,x", &y, &x)) + return NULL; - return PyInt_FromLong( wenclose(self->win,y,x) ); + return PyInt_FromLong( wenclose(self->win,y,x) ); } #endif static PyObject * PyCursesWindow_GetBkgd(PyCursesWindowObject *self) { - return PyInt_FromLong((long) getbkgd(self->win)); + return PyInt_FromLong((long) getbkgd(self->win)); } static PyObject * PyCursesWindow_GetCh(PyCursesWindowObject *self, PyObject *args) { - int x, y; - int rtn; + int x, y; + int rtn; - switch (PyTuple_Size(args)) { - case 0: - Py_BEGIN_ALLOW_THREADS - rtn = wgetch(self->win); - Py_END_ALLOW_THREADS - break; - case 2: - if (!PyArg_ParseTuple(args,"ii;y,x",&y,&x)) - return NULL; - Py_BEGIN_ALLOW_THREADS - rtn = mvwgetch(self->win,y,x); - Py_END_ALLOW_THREADS - break; - default: - PyErr_SetString(PyExc_TypeError, "getch requires 0 or 2 arguments"); - return NULL; - } - return PyInt_FromLong((long)rtn); + switch (PyTuple_Size(args)) { + case 0: + Py_BEGIN_ALLOW_THREADS + rtn = wgetch(self->win); + Py_END_ALLOW_THREADS + break; + case 2: + if (!PyArg_ParseTuple(args,"ii;y,x",&y,&x)) + return NULL; + Py_BEGIN_ALLOW_THREADS + rtn = mvwgetch(self->win,y,x); + Py_END_ALLOW_THREADS + break; + default: + PyErr_SetString(PyExc_TypeError, "getch requires 0 or 2 arguments"); + return NULL; + } + return PyInt_FromLong((long)rtn); } static PyObject * PyCursesWindow_GetKey(PyCursesWindowObject *self, PyObject *args) { - int x, y; - int rtn; + int x, y; + int rtn; - switch (PyTuple_Size(args)) { - case 0: - Py_BEGIN_ALLOW_THREADS - rtn = wgetch(self->win); - Py_END_ALLOW_THREADS - break; - case 2: - if (!PyArg_ParseTuple(args,"ii;y,x",&y,&x)) - return NULL; - Py_BEGIN_ALLOW_THREADS - rtn = mvwgetch(self->win,y,x); - Py_END_ALLOW_THREADS - break; - default: - PyErr_SetString(PyExc_TypeError, "getkey requires 0 or 2 arguments"); - return NULL; - } - if (rtn == ERR) { - /* getch() returns ERR in nodelay mode */ - PyErr_SetString(PyCursesError, "no input"); - return NULL; - } else if (rtn<=255) { - return Py_BuildValue("c", rtn); - } else { - const char *knp; + switch (PyTuple_Size(args)) { + case 0: + Py_BEGIN_ALLOW_THREADS + rtn = wgetch(self->win); + Py_END_ALLOW_THREADS + break; + case 2: + if (!PyArg_ParseTuple(args,"ii;y,x",&y,&x)) + return NULL; + Py_BEGIN_ALLOW_THREADS + rtn = mvwgetch(self->win,y,x); + Py_END_ALLOW_THREADS + break; + default: + PyErr_SetString(PyExc_TypeError, "getkey requires 0 or 2 arguments"); + return NULL; + } + if (rtn == ERR) { + /* getch() returns ERR in nodelay mode */ + PyErr_SetString(PyCursesError, "no input"); + return NULL; + } else if (rtn<=255) { + return Py_BuildValue("c", rtn); + } else { + const char *knp; #if defined(__NetBSD__) - knp = unctrl(rtn); + knp = unctrl(rtn); #else - knp = keyname(rtn); + knp = keyname(rtn); #endif - return PyString_FromString((knp == NULL) ? "" : knp); - } + return PyString_FromString((knp == NULL) ? "" : knp); + } } static PyObject * PyCursesWindow_GetStr(PyCursesWindowObject *self, PyObject *args) { - int x, y, n; - char rtn[1024]; /* This should be big enough.. I hope */ - int rtn2; - - switch (PyTuple_Size(args)) { - case 0: - Py_BEGIN_ALLOW_THREADS - rtn2 = wgetnstr(self->win,rtn, 1023); - Py_END_ALLOW_THREADS - break; - case 1: - if (!PyArg_ParseTuple(args,"i;n", &n)) - return NULL; - Py_BEGIN_ALLOW_THREADS - rtn2 = wgetnstr(self->win,rtn,MIN(n, 1023)); - Py_END_ALLOW_THREADS - break; - case 2: - if (!PyArg_ParseTuple(args,"ii;y,x",&y,&x)) - return NULL; - Py_BEGIN_ALLOW_THREADS + int x, y, n; + char rtn[1024]; /* This should be big enough.. I hope */ + int rtn2; + + switch (PyTuple_Size(args)) { + case 0: + Py_BEGIN_ALLOW_THREADS + rtn2 = wgetnstr(self->win,rtn, 1023); + Py_END_ALLOW_THREADS + break; + case 1: + if (!PyArg_ParseTuple(args,"i;n", &n)) + return NULL; + Py_BEGIN_ALLOW_THREADS + rtn2 = wgetnstr(self->win,rtn,MIN(n, 1023)); + Py_END_ALLOW_THREADS + break; + case 2: + if (!PyArg_ParseTuple(args,"ii;y,x",&y,&x)) + return NULL; + Py_BEGIN_ALLOW_THREADS #ifdef STRICT_SYSV_CURSES - rtn2 = wmove(self->win,y,x)==ERR ? ERR : wgetnstr(self->win, rtn, 1023); + rtn2 = wmove(self->win,y,x)==ERR ? ERR : wgetnstr(self->win, rtn, 1023); #else - rtn2 = mvwgetnstr(self->win,y,x,rtn, 1023); + rtn2 = mvwgetnstr(self->win,y,x,rtn, 1023); #endif - Py_END_ALLOW_THREADS - break; - case 3: - if (!PyArg_ParseTuple(args,"iii;y,x,n", &y, &x, &n)) - return NULL; + Py_END_ALLOW_THREADS + break; + case 3: + if (!PyArg_ParseTuple(args,"iii;y,x,n", &y, &x, &n)) + return NULL; #ifdef STRICT_SYSV_CURSES - Py_BEGIN_ALLOW_THREADS - rtn2 = wmove(self->win,y,x)==ERR ? ERR : - wgetnstr(self->win, rtn, MIN(n, 1023)); - Py_END_ALLOW_THREADS + Py_BEGIN_ALLOW_THREADS + rtn2 = wmove(self->win,y,x)==ERR ? ERR : + wgetnstr(self->win, rtn, MIN(n, 1023)); + Py_END_ALLOW_THREADS #else - Py_BEGIN_ALLOW_THREADS - rtn2 = mvwgetnstr(self->win, y, x, rtn, MIN(n, 1023)); - Py_END_ALLOW_THREADS -#endif - break; - default: - PyErr_SetString(PyExc_TypeError, "getstr requires 0 to 3 arguments"); - return NULL; - } - if (rtn2 == ERR) - rtn[0] = 0; - return PyString_FromString(rtn); + Py_BEGIN_ALLOW_THREADS + rtn2 = mvwgetnstr(self->win, y, x, rtn, MIN(n, 1023)); + Py_END_ALLOW_THREADS +#endif + break; + default: + PyErr_SetString(PyExc_TypeError, "getstr requires 0 to 3 arguments"); + return NULL; + } + if (rtn2 == ERR) + rtn[0] = 0; + return PyString_FromString(rtn); } static PyObject * PyCursesWindow_Hline(PyCursesWindowObject *self, PyObject *args) { - PyObject *temp; - chtype ch; - int n, x, y, code = OK; - attr_t attr = A_NORMAL; - long lattr; - - switch (PyTuple_Size(args)) { - case 2: - if (!PyArg_ParseTuple(args, "Oi;ch or int,n", &temp, &n)) - return NULL; - break; - case 3: - if (!PyArg_ParseTuple(args, "Oil;ch or int,n,attr", &temp, &n, &lattr)) - return NULL; - attr = lattr; - break; - case 4: - if (!PyArg_ParseTuple(args, "iiOi;y,x,ch or int,n", &y, &x, &temp, &n)) - return NULL; - code = wmove(self->win, y, x); - break; - case 5: - if (!PyArg_ParseTuple(args, "iiOil; y,x,ch or int,n,attr", - &y, &x, &temp, &n, &lattr)) - return NULL; - attr = lattr; - code = wmove(self->win, y, x); - break; - default: - PyErr_SetString(PyExc_TypeError, "hline requires 2 to 5 arguments"); - return NULL; - } + PyObject *temp; + chtype ch; + int n, x, y, code = OK; + attr_t attr = A_NORMAL; + long lattr; - if (code != ERR) { - if (!PyCurses_ConvertToChtype(temp, &ch)) { - PyErr_SetString(PyExc_TypeError, - "argument 1 or 3 must be a ch or an int"); - return NULL; - } - return PyCursesCheckERR(whline(self->win, ch | attr, n), "hline"); - } else - return PyCursesCheckERR(code, "wmove"); -} + switch (PyTuple_Size(args)) { + case 2: + if (!PyArg_ParseTuple(args, "Oi;ch or int,n", &temp, &n)) + return NULL; + break; + case 3: + if (!PyArg_ParseTuple(args, "Oil;ch or int,n,attr", &temp, &n, &lattr)) + return NULL; + attr = lattr; + break; + case 4: + if (!PyArg_ParseTuple(args, "iiOi;y,x,ch or int,n", &y, &x, &temp, &n)) + return NULL; + code = wmove(self->win, y, x); + break; + case 5: + if (!PyArg_ParseTuple(args, "iiOil; y,x,ch or int,n,attr", + &y, &x, &temp, &n, &lattr)) + return NULL; + attr = lattr; + code = wmove(self->win, y, x); + break; + default: + PyErr_SetString(PyExc_TypeError, "hline requires 2 to 5 arguments"); + return NULL; + } -static PyObject * -PyCursesWindow_InsCh(PyCursesWindowObject *self, PyObject *args) -{ - int rtn, x, y, use_xy = FALSE; - PyObject *temp; - chtype ch = 0; - attr_t attr = A_NORMAL; - long lattr; - - switch (PyTuple_Size(args)) { - case 1: - if (!PyArg_ParseTuple(args, "O;ch or int", &temp)) - return NULL; - break; - case 2: - if (!PyArg_ParseTuple(args, "Ol;ch or int,attr", &temp, &lattr)) - return NULL; - attr = lattr; - break; - case 3: - if (!PyArg_ParseTuple(args,"iiO;y,x,ch or int", &y, &x, &temp)) - return NULL; - use_xy = TRUE; - break; - case 4: - if (!PyArg_ParseTuple(args,"iiOl;y,x,ch or int, attr", &y, &x, &temp, &lattr)) - return NULL; - attr = lattr; - use_xy = TRUE; - break; - default: - PyErr_SetString(PyExc_TypeError, "insch requires 1 or 4 arguments"); - return NULL; - } - - if (!PyCurses_ConvertToChtype(temp, &ch)) { - PyErr_SetString(PyExc_TypeError, - "argument 1 or 3 must be a ch or an int"); - return NULL; - } - - if (use_xy == TRUE) - rtn = mvwinsch(self->win,y,x, ch | attr); - else { - rtn = winsch(self->win, ch | attr); - } - return PyCursesCheckERR(rtn, "insch"); + if (code != ERR) { + if (!PyCurses_ConvertToChtype(temp, &ch)) { + PyErr_SetString(PyExc_TypeError, + "argument 1 or 3 must be a ch or an int"); + return NULL; + } + return PyCursesCheckERR(whline(self->win, ch | attr, n), "hline"); + } else + return PyCursesCheckERR(code, "wmove"); } static PyObject * -PyCursesWindow_InCh(PyCursesWindowObject *self, PyObject *args) +PyCursesWindow_InsCh(PyCursesWindowObject *self, PyObject *args) { - int x, y, rtn; + int rtn, x, y, use_xy = FALSE; + PyObject *temp; + chtype ch = 0; + attr_t attr = A_NORMAL; + long lattr; - switch (PyTuple_Size(args)) { - case 0: - rtn = winch(self->win); - break; - case 2: - if (!PyArg_ParseTuple(args,"ii;y,x",&y,&x)) - return NULL; - rtn = mvwinch(self->win,y,x); - break; - default: - PyErr_SetString(PyExc_TypeError, "inch requires 0 or 2 arguments"); - return NULL; - } - return PyInt_FromLong((long) rtn); -} + switch (PyTuple_Size(args)) { + case 1: + if (!PyArg_ParseTuple(args, "O;ch or int", &temp)) + return NULL; + break; + case 2: + if (!PyArg_ParseTuple(args, "Ol;ch or int,attr", &temp, &lattr)) + return NULL; + attr = lattr; + break; + case 3: + if (!PyArg_ParseTuple(args,"iiO;y,x,ch or int", &y, &x, &temp)) + return NULL; + use_xy = TRUE; + break; + case 4: + if (!PyArg_ParseTuple(args,"iiOl;y,x,ch or int, attr", &y, &x, &temp, &lattr)) + return NULL; + attr = lattr; + use_xy = TRUE; + break; + default: + PyErr_SetString(PyExc_TypeError, "insch requires 1 or 4 arguments"); + return NULL; + } -static PyObject * -PyCursesWindow_InStr(PyCursesWindowObject *self, PyObject *args) -{ - int x, y, n; - char rtn[1024]; /* This should be big enough.. I hope */ - int rtn2; - - switch (PyTuple_Size(args)) { - case 0: - rtn2 = winnstr(self->win,rtn, 1023); - break; - case 1: - if (!PyArg_ParseTuple(args,"i;n", &n)) - return NULL; - rtn2 = winnstr(self->win,rtn,MIN(n,1023)); - break; - case 2: - if (!PyArg_ParseTuple(args,"ii;y,x",&y,&x)) - return NULL; - rtn2 = mvwinnstr(self->win,y,x,rtn,1023); - break; - case 3: - if (!PyArg_ParseTuple(args, "iii;y,x,n", &y, &x, &n)) - return NULL; - rtn2 = mvwinnstr(self->win, y, x, rtn, MIN(n,1023)); - break; - default: - PyErr_SetString(PyExc_TypeError, "instr requires 0 or 3 arguments"); - return NULL; - } - if (rtn2 == ERR) - rtn[0] = 0; - return PyString_FromString(rtn); -} + if (!PyCurses_ConvertToChtype(temp, &ch)) { + PyErr_SetString(PyExc_TypeError, + "argument 1 or 3 must be a ch or an int"); + return NULL; + } -static PyObject * -PyCursesWindow_InsStr(PyCursesWindowObject *self, PyObject *args) -{ - int rtn; - int x, y; - char *str; - attr_t attr = A_NORMAL , attr_old = A_NORMAL; - long lattr; - int use_xy = FALSE, use_attr = FALSE; - - switch (PyTuple_Size(args)) { - case 1: - if (!PyArg_ParseTuple(args,"s;str", &str)) - return NULL; - break; - case 2: - if (!PyArg_ParseTuple(args,"sl;str,attr", &str, &lattr)) - return NULL; - attr = lattr; - use_attr = TRUE; - break; - case 3: - if (!PyArg_ParseTuple(args,"iis;y,x,str", &y, &x, &str)) - return NULL; - use_xy = TRUE; - break; - case 4: - if (!PyArg_ParseTuple(args,"iisl;y,x,str,attr", &y, &x, &str, &lattr)) - return NULL; - attr = lattr; - use_xy = use_attr = TRUE; - break; - default: - PyErr_SetString(PyExc_TypeError, "insstr requires 1 to 4 arguments"); - return NULL; - } - - if (use_attr == TRUE) { - attr_old = getattrs(self->win); - (void)wattrset(self->win,attr); - } - if (use_xy == TRUE) - rtn = mvwinsstr(self->win,y,x,str); - else - rtn = winsstr(self->win,str); - if (use_attr == TRUE) - (void)wattrset(self->win,attr_old); - return PyCursesCheckERR(rtn, "insstr"); + if (use_xy == TRUE) + rtn = mvwinsch(self->win,y,x, ch | attr); + else { + rtn = winsch(self->win, ch | attr); + } + return PyCursesCheckERR(rtn, "insch"); } static PyObject * -PyCursesWindow_InsNStr(PyCursesWindowObject *self, PyObject *args) +PyCursesWindow_InCh(PyCursesWindowObject *self, PyObject *args) { - int rtn, x, y, n; - char *str; - attr_t attr = A_NORMAL , attr_old = A_NORMAL; - long lattr; - int use_xy = FALSE, use_attr = FALSE; - - switch (PyTuple_Size(args)) { - case 2: - if (!PyArg_ParseTuple(args,"si;str,n", &str, &n)) - return NULL; - break; - case 3: - if (!PyArg_ParseTuple(args,"sil;str,n,attr", &str, &n, &lattr)) - return NULL; - attr = lattr; - use_attr = TRUE; - break; - case 4: - if (!PyArg_ParseTuple(args,"iisi;y,x,str,n", &y, &x, &str, &n)) - return NULL; - use_xy = TRUE; - break; - case 5: - if (!PyArg_ParseTuple(args,"iisil;y,x,str,n,attr", &y, &x, &str, &n, &lattr)) - return NULL; - attr = lattr; - use_xy = use_attr = TRUE; - break; - default: - PyErr_SetString(PyExc_TypeError, "insnstr requires 2 to 5 arguments"); - return NULL; - } - - if (use_attr == TRUE) { - attr_old = getattrs(self->win); - (void)wattrset(self->win,attr); - } - if (use_xy == TRUE) - rtn = mvwinsnstr(self->win,y,x,str,n); - else - rtn = winsnstr(self->win,str,n); - if (use_attr == TRUE) - (void)wattrset(self->win,attr_old); - return PyCursesCheckERR(rtn, "insnstr"); -} + int x, y, rtn; -static PyObject * -PyCursesWindow_Is_LineTouched(PyCursesWindowObject *self, PyObject *args) -{ - int line, erg; - if (!PyArg_ParseTuple(args,"i;line", &line)) - return NULL; - erg = is_linetouched(self->win, line); - if (erg == ERR) { - PyErr_SetString(PyExc_TypeError, - "is_linetouched: line number outside of boundaries"); - return NULL; - } else - if (erg == FALSE) { - Py_INCREF(Py_False); - return Py_False; - } else { - Py_INCREF(Py_True); - return Py_True; + switch (PyTuple_Size(args)) { + case 0: + rtn = winch(self->win); + break; + case 2: + if (!PyArg_ParseTuple(args,"ii;y,x",&y,&x)) + return NULL; + rtn = mvwinch(self->win,y,x); + break; + default: + PyErr_SetString(PyExc_TypeError, "inch requires 0 or 2 arguments"); + return NULL; } + return PyInt_FromLong((long) rtn); } static PyObject * -PyCursesWindow_NoOutRefresh(PyCursesWindowObject *self, PyObject *args) +PyCursesWindow_InStr(PyCursesWindowObject *self, PyObject *args) { - int pminrow,pmincol,sminrow,smincol,smaxrow,smaxcol; - int rtn; + int x, y, n; + char rtn[1024]; /* This should be big enough.. I hope */ + int rtn2; -#ifndef WINDOW_HAS_FLAGS - if (0) { -#else - if (self->win->_flags & _ISPAD) { -#endif - switch(PyTuple_Size(args)) { - case 6: - if (!PyArg_ParseTuple(args, - "iiiiii;" \ - "pminrow,pmincol,sminrow,smincol,smaxrow,smaxcol", - &pminrow, &pmincol, &sminrow, - &smincol, &smaxrow, &smaxcol)) - return NULL; - Py_BEGIN_ALLOW_THREADS - rtn = pnoutrefresh(self->win, - pminrow, pmincol, sminrow, - smincol, smaxrow, smaxcol); - Py_END_ALLOW_THREADS - return PyCursesCheckERR(rtn, "pnoutrefresh"); + switch (PyTuple_Size(args)) { + case 0: + rtn2 = winnstr(self->win,rtn, 1023); + break; + case 1: + if (!PyArg_ParseTuple(args,"i;n", &n)) + return NULL; + rtn2 = winnstr(self->win,rtn,MIN(n,1023)); + break; + case 2: + if (!PyArg_ParseTuple(args,"ii;y,x",&y,&x)) + return NULL; + rtn2 = mvwinnstr(self->win,y,x,rtn,1023); + break; + case 3: + if (!PyArg_ParseTuple(args, "iii;y,x,n", &y, &x, &n)) + return NULL; + rtn2 = mvwinnstr(self->win, y, x, rtn, MIN(n,1023)); + break; default: - PyErr_SetString(PyCursesError, - "noutrefresh() called for a pad " - "requires 6 arguments"); - return NULL; + PyErr_SetString(PyExc_TypeError, "instr requires 0 or 3 arguments"); + return NULL; } - } else { - if (!PyArg_ParseTuple(args, ":noutrefresh")) - return NULL; - - Py_BEGIN_ALLOW_THREADS - rtn = wnoutrefresh(self->win); - Py_END_ALLOW_THREADS - return PyCursesCheckERR(rtn, "wnoutrefresh"); - } + if (rtn2 == ERR) + rtn[0] = 0; + return PyString_FromString(rtn); } static PyObject * -PyCursesWindow_Overlay(PyCursesWindowObject *self, PyObject *args) +PyCursesWindow_InsStr(PyCursesWindowObject *self, PyObject *args) { - PyCursesWindowObject *temp; - int use_copywin = FALSE; - int sminrow, smincol, dminrow, dmincol, dmaxrow, dmaxcol; int rtn; - + int x, y; + char *str; + attr_t attr = A_NORMAL , attr_old = A_NORMAL; + long lattr; + int use_xy = FALSE, use_attr = FALSE; + switch (PyTuple_Size(args)) { case 1: - if (!PyArg_ParseTuple(args, "O!;window object", - &PyCursesWindow_Type, &temp)) - return NULL; - break; - case 7: - if (!PyArg_ParseTuple(args, "O!iiiiii;window object, int, int, int, int, int, int", - &PyCursesWindow_Type, &temp, &sminrow, &smincol, - &dminrow, &dmincol, &dmaxrow, &dmaxcol)) - return NULL; - use_copywin = TRUE; - break; + if (!PyArg_ParseTuple(args,"s;str", &str)) + return NULL; + break; + case 2: + if (!PyArg_ParseTuple(args,"sl;str,attr", &str, &lattr)) + return NULL; + attr = lattr; + use_attr = TRUE; + break; + case 3: + if (!PyArg_ParseTuple(args,"iis;y,x,str", &y, &x, &str)) + return NULL; + use_xy = TRUE; + break; + case 4: + if (!PyArg_ParseTuple(args,"iisl;y,x,str,attr", &y, &x, &str, &lattr)) + return NULL; + attr = lattr; + use_xy = use_attr = TRUE; + break; default: - PyErr_SetString(PyExc_TypeError, - "overlay requires one or seven arguments"); - return NULL; + PyErr_SetString(PyExc_TypeError, "insstr requires 1 to 4 arguments"); + return NULL; } - if (use_copywin == TRUE) { - rtn = copywin(self->win, temp->win, sminrow, smincol, - dminrow, dmincol, dmaxrow, dmaxcol, TRUE); - return PyCursesCheckERR(rtn, "copywin"); - } - else { - rtn = overlay(self->win, temp->win); - return PyCursesCheckERR(rtn, "overlay"); + if (use_attr == TRUE) { + attr_old = getattrs(self->win); + (void)wattrset(self->win,attr); } + if (use_xy == TRUE) + rtn = mvwinsstr(self->win,y,x,str); + else + rtn = winsstr(self->win,str); + if (use_attr == TRUE) + (void)wattrset(self->win,attr_old); + return PyCursesCheckERR(rtn, "insstr"); } static PyObject * -PyCursesWindow_Overwrite(PyCursesWindowObject *self, PyObject *args) +PyCursesWindow_InsNStr(PyCursesWindowObject *self, PyObject *args) { - PyCursesWindowObject *temp; - int use_copywin = FALSE; - int sminrow, smincol, dminrow, dmincol, dmaxrow, dmaxcol; - int rtn; - + int rtn, x, y, n; + char *str; + attr_t attr = A_NORMAL , attr_old = A_NORMAL; + long lattr; + int use_xy = FALSE, use_attr = FALSE; + switch (PyTuple_Size(args)) { - case 1: - if (!PyArg_ParseTuple(args, "O!;window object", - &PyCursesWindow_Type, &temp)) - return NULL; - break; - case 7: - if (!PyArg_ParseTuple(args, "O!iiiiii;window object, int, int, int, int, int, int", - &PyCursesWindow_Type, &temp, &sminrow, &smincol, - &dminrow, &dmincol, &dmaxrow, &dmaxcol)) - return NULL; - use_copywin = TRUE; - break; + case 2: + if (!PyArg_ParseTuple(args,"si;str,n", &str, &n)) + return NULL; + break; + case 3: + if (!PyArg_ParseTuple(args,"sil;str,n,attr", &str, &n, &lattr)) + return NULL; + attr = lattr; + use_attr = TRUE; + break; + case 4: + if (!PyArg_ParseTuple(args,"iisi;y,x,str,n", &y, &x, &str, &n)) + return NULL; + use_xy = TRUE; + break; + case 5: + if (!PyArg_ParseTuple(args,"iisil;y,x,str,n,attr", &y, &x, &str, &n, &lattr)) + return NULL; + attr = lattr; + use_xy = use_attr = TRUE; + break; default: - PyErr_SetString(PyExc_TypeError, - "overwrite requires one or seven arguments"); - return NULL; + PyErr_SetString(PyExc_TypeError, "insnstr requires 2 to 5 arguments"); + return NULL; } - if (use_copywin == TRUE) { - rtn = copywin(self->win, temp->win, sminrow, smincol, - dminrow, dmincol, dmaxrow, dmaxcol, FALSE); - return PyCursesCheckERR(rtn, "copywin"); - } - else { - rtn = overwrite(self->win, temp->win); - return PyCursesCheckERR(rtn, "overwrite"); + if (use_attr == TRUE) { + attr_old = getattrs(self->win); + (void)wattrset(self->win,attr); } + if (use_xy == TRUE) + rtn = mvwinsnstr(self->win,y,x,str,n); + else + rtn = winsnstr(self->win,str,n); + if (use_attr == TRUE) + (void)wattrset(self->win,attr_old); + return PyCursesCheckERR(rtn, "insnstr"); } static PyObject * -PyCursesWindow_PutWin(PyCursesWindowObject *self, PyObject *args) +PyCursesWindow_Is_LineTouched(PyCursesWindowObject *self, PyObject *args) { - PyObject *temp; - - if (!PyArg_ParseTuple(args, "O;fileobj", &temp)) - return NULL; - if (!PyFile_Check(temp)) { - PyErr_SetString(PyExc_TypeError, "argument must be a file object"); - return NULL; - } - return PyCursesCheckERR(putwin(self->win, PyFile_AsFile(temp)), - "putwin"); + int line, erg; + if (!PyArg_ParseTuple(args,"i;line", &line)) + return NULL; + erg = is_linetouched(self->win, line); + if (erg == ERR) { + PyErr_SetString(PyExc_TypeError, + "is_linetouched: line number outside of boundaries"); + return NULL; + } else + if (erg == FALSE) { + Py_INCREF(Py_False); + return Py_False; + } else { + Py_INCREF(Py_True); + return Py_True; + } } static PyObject * -PyCursesWindow_RedrawLine(PyCursesWindowObject *self, PyObject *args) +PyCursesWindow_NoOutRefresh(PyCursesWindowObject *self, PyObject *args) { - int beg, num; - if (!PyArg_ParseTuple(args, "ii;beg,num", &beg, &num)) - return NULL; - return PyCursesCheckERR(wredrawln(self->win,beg,num), "redrawln"); -} + int pminrow,pmincol,sminrow,smincol,smaxrow,smaxcol; + int rtn; -static PyObject * -PyCursesWindow_Refresh(PyCursesWindowObject *self, PyObject *args) -{ - int pminrow,pmincol,sminrow,smincol,smaxrow,smaxcol; - int rtn; - #ifndef WINDOW_HAS_FLAGS - if (0) { + if (0) { #else - if (self->win->_flags & _ISPAD) { + if (self->win->_flags & _ISPAD) { #endif - switch(PyTuple_Size(args)) { - case 6: - if (!PyArg_ParseTuple(args, - "iiiiii;" \ - "pminrow,pmincol,sminrow,smincol,smaxrow,smaxcol", - &pminrow, &pmincol, &sminrow, - &smincol, &smaxrow, &smaxcol)) - return NULL; - - Py_BEGIN_ALLOW_THREADS - rtn = prefresh(self->win, - pminrow, pmincol, sminrow, - smincol, smaxrow, smaxcol); - Py_END_ALLOW_THREADS - return PyCursesCheckERR(rtn, "prefresh"); - default: - PyErr_SetString(PyCursesError, - "refresh() for a pad requires 6 arguments"); - return NULL; - } - } else { - if (!PyArg_ParseTuple(args, ":refresh")) - return NULL; - Py_BEGIN_ALLOW_THREADS - rtn = wrefresh(self->win); - Py_END_ALLOW_THREADS - return PyCursesCheckERR(rtn, "prefresh"); - } -} + switch(PyTuple_Size(args)) { + case 6: + if (!PyArg_ParseTuple(args, + "iiiiii;" \ + "pminrow,pmincol,sminrow,smincol,smaxrow,smaxcol", + &pminrow, &pmincol, &sminrow, + &smincol, &smaxrow, &smaxcol)) + return NULL; + Py_BEGIN_ALLOW_THREADS + rtn = pnoutrefresh(self->win, + pminrow, pmincol, sminrow, + smincol, smaxrow, smaxcol); + Py_END_ALLOW_THREADS + return PyCursesCheckERR(rtn, "pnoutrefresh"); + default: + PyErr_SetString(PyCursesError, + "noutrefresh() called for a pad " + "requires 6 arguments"); + return NULL; + } + } else { + if (!PyArg_ParseTuple(args, ":noutrefresh")) + return NULL; + + Py_BEGIN_ALLOW_THREADS + rtn = wnoutrefresh(self->win); + Py_END_ALLOW_THREADS + return PyCursesCheckERR(rtn, "wnoutrefresh"); + } + } -static PyObject * -PyCursesWindow_SetScrollRegion(PyCursesWindowObject *self, PyObject *args) -{ - int x, y; - if (!PyArg_ParseTuple(args,"ii;top, bottom",&y,&x)) - return NULL; - return PyCursesCheckERR(wsetscrreg(self->win,y,x), "wsetscrreg"); -} + static PyObject * + PyCursesWindow_Overlay(PyCursesWindowObject *self, PyObject *args) + { + PyCursesWindowObject *temp; + int use_copywin = FALSE; + int sminrow, smincol, dminrow, dmincol, dmaxrow, dmaxcol; + int rtn; + + switch (PyTuple_Size(args)) { + case 1: + if (!PyArg_ParseTuple(args, "O!;window object", + &PyCursesWindow_Type, &temp)) + return NULL; + break; + case 7: + if (!PyArg_ParseTuple(args, "O!iiiiii;window object, int, int, int, int, int, int", + &PyCursesWindow_Type, &temp, &sminrow, &smincol, + &dminrow, &dmincol, &dmaxrow, &dmaxcol)) + return NULL; + use_copywin = TRUE; + break; + default: + PyErr_SetString(PyExc_TypeError, + "overlay requires one or seven arguments"); + return NULL; + } + + if (use_copywin == TRUE) { + rtn = copywin(self->win, temp->win, sminrow, smincol, + dminrow, dmincol, dmaxrow, dmaxcol, TRUE); + return PyCursesCheckERR(rtn, "copywin"); + } + else { + rtn = overlay(self->win, temp->win); + return PyCursesCheckERR(rtn, "overlay"); + } + } -static PyObject * -PyCursesWindow_SubWin(PyCursesWindowObject *self, PyObject *args) -{ - WINDOW *win; - int nlines, ncols, begin_y, begin_x; - - nlines = 0; - ncols = 0; - switch (PyTuple_Size(args)) { - case 2: - if (!PyArg_ParseTuple(args,"ii;begin_y,begin_x",&begin_y,&begin_x)) - return NULL; - break; - case 4: - if (!PyArg_ParseTuple(args, "iiii;nlines,ncols,begin_y,begin_x", - &nlines,&ncols,&begin_y,&begin_x)) - return NULL; - break; - default: - PyErr_SetString(PyExc_TypeError, "subwin requires 2 or 4 arguments"); - return NULL; - } + static PyObject * + PyCursesWindow_Overwrite(PyCursesWindowObject *self, PyObject *args) + { + PyCursesWindowObject *temp; + int use_copywin = FALSE; + int sminrow, smincol, dminrow, dmincol, dmaxrow, dmaxcol; + int rtn; + + switch (PyTuple_Size(args)) { + case 1: + if (!PyArg_ParseTuple(args, "O!;window object", + &PyCursesWindow_Type, &temp)) + return NULL; + break; + case 7: + if (!PyArg_ParseTuple(args, "O!iiiiii;window object, int, int, int, int, int, int", + &PyCursesWindow_Type, &temp, &sminrow, &smincol, + &dminrow, &dmincol, &dmaxrow, &dmaxcol)) + return NULL; + use_copywin = TRUE; + break; + default: + PyErr_SetString(PyExc_TypeError, + "overwrite requires one or seven arguments"); + return NULL; + } + + if (use_copywin == TRUE) { + rtn = copywin(self->win, temp->win, sminrow, smincol, + dminrow, dmincol, dmaxrow, dmaxcol, FALSE); + return PyCursesCheckERR(rtn, "copywin"); + } + else { + rtn = overwrite(self->win, temp->win); + return PyCursesCheckERR(rtn, "overwrite"); + } + } - /* printf("Subwin: %i %i %i %i \n", nlines, ncols, begin_y, begin_x); */ -#ifdef WINDOW_HAS_FLAGS - if (self->win->_flags & _ISPAD) - win = subpad(self->win, nlines, ncols, begin_y, begin_x); - else -#endif - win = subwin(self->win, nlines, ncols, begin_y, begin_x); - - if (win == NULL) { - PyErr_SetString(PyCursesError, catchall_NULL); - return NULL; - } - - return (PyObject *)PyCursesWindow_New(win); -} - -static PyObject * -PyCursesWindow_Scroll(PyCursesWindowObject *self, PyObject *args) -{ - int nlines; - switch(PyTuple_Size(args)) { - case 0: - return PyCursesCheckERR(scroll(self->win), "scroll"); - case 1: - if (!PyArg_ParseTuple(args, "i;nlines", &nlines)) - return NULL; - return PyCursesCheckERR(wscrl(self->win, nlines), "scroll"); - default: - PyErr_SetString(PyExc_TypeError, "scroll requires 0 or 1 arguments"); - return NULL; - } -} - -static PyObject * -PyCursesWindow_TouchLine(PyCursesWindowObject *self, PyObject *args) -{ - int st, cnt, val; - switch (PyTuple_Size(args)) { - case 2: - if (!PyArg_ParseTuple(args,"ii;start,count",&st,&cnt)) - return NULL; - return PyCursesCheckERR(touchline(self->win,st,cnt), "touchline"); - case 3: - if (!PyArg_ParseTuple(args, "iii;start,count,val", &st, &cnt, &val)) - return NULL; - return PyCursesCheckERR(wtouchln(self->win, st, cnt, val), "touchline"); - default: - PyErr_SetString(PyExc_TypeError, "touchline requires 2 or 3 arguments"); - return NULL; - } -} - -static PyObject * -PyCursesWindow_Vline(PyCursesWindowObject *self, PyObject *args) -{ - PyObject *temp; - chtype ch; - int n, x, y, code = OK; - attr_t attr = A_NORMAL; - long lattr; - - switch (PyTuple_Size(args)) { - case 2: - if (!PyArg_ParseTuple(args, "Oi;ch or int,n", &temp, &n)) - return NULL; - break; - case 3: - if (!PyArg_ParseTuple(args, "Oil;ch or int,n,attr", &temp, &n, &lattr)) - return NULL; - attr = lattr; - break; - case 4: - if (!PyArg_ParseTuple(args, "iiOi;y,x,ch or int,n", &y, &x, &temp, &n)) - return NULL; - code = wmove(self->win, y, x); - break; - case 5: - if (!PyArg_ParseTuple(args, "iiOil; y,x,ch or int,n,attr", - &y, &x, &temp, &n, &lattr)) - return NULL; - attr = lattr; - code = wmove(self->win, y, x); - break; - default: - PyErr_SetString(PyExc_TypeError, "vline requires 2 to 5 arguments"); - return NULL; - } + static PyObject * + PyCursesWindow_PutWin(PyCursesWindowObject *self, PyObject *args) + { + PyObject *temp; + + if (!PyArg_ParseTuple(args, "O;fileobj", &temp)) + return NULL; + if (!PyFile_Check(temp)) { + PyErr_SetString(PyExc_TypeError, "argument must be a file object"); + return NULL; + } + return PyCursesCheckERR(putwin(self->win, PyFile_AsFile(temp)), + "putwin"); + } - if (code != ERR) { - if (!PyCurses_ConvertToChtype(temp, &ch)) { - PyErr_SetString(PyExc_TypeError, - "argument 1 or 3 must be a ch or an int"); - return NULL; - } - return PyCursesCheckERR(wvline(self->win, ch | attr, n), "vline"); - } else - return PyCursesCheckERR(code, "wmove"); -} - -static PyMethodDef PyCursesWindow_Methods[] = { - {"addch", (PyCFunction)PyCursesWindow_AddCh, METH_VARARGS}, - {"addnstr", (PyCFunction)PyCursesWindow_AddNStr, METH_VARARGS}, - {"addstr", (PyCFunction)PyCursesWindow_AddStr, METH_VARARGS}, - {"attroff", (PyCFunction)PyCursesWindow_AttrOff, METH_VARARGS}, - {"attron", (PyCFunction)PyCursesWindow_AttrOn, METH_VARARGS}, - {"attrset", (PyCFunction)PyCursesWindow_AttrSet, METH_VARARGS}, - {"bkgd", (PyCFunction)PyCursesWindow_Bkgd, METH_VARARGS}, - {"chgat", (PyCFunction)PyCursesWindow_ChgAt, METH_VARARGS}, - {"bkgdset", (PyCFunction)PyCursesWindow_BkgdSet, METH_VARARGS}, - {"border", (PyCFunction)PyCursesWindow_Border, METH_VARARGS}, - {"box", (PyCFunction)PyCursesWindow_Box, METH_VARARGS}, - {"clear", (PyCFunction)PyCursesWindow_wclear, METH_NOARGS}, - {"clearok", (PyCFunction)PyCursesWindow_clearok, METH_VARARGS}, - {"clrtobot", (PyCFunction)PyCursesWindow_wclrtobot, METH_NOARGS}, - {"clrtoeol", (PyCFunction)PyCursesWindow_wclrtoeol, METH_NOARGS}, - {"cursyncup", (PyCFunction)PyCursesWindow_wcursyncup, METH_NOARGS}, - {"delch", (PyCFunction)PyCursesWindow_DelCh, METH_VARARGS}, - {"deleteln", (PyCFunction)PyCursesWindow_wdeleteln, METH_NOARGS}, - {"derwin", (PyCFunction)PyCursesWindow_DerWin, METH_VARARGS}, - {"echochar", (PyCFunction)PyCursesWindow_EchoChar, METH_VARARGS}, + static PyObject * + PyCursesWindow_RedrawLine(PyCursesWindowObject *self, PyObject *args) + { + int beg, num; + if (!PyArg_ParseTuple(args, "ii;beg,num", &beg, &num)) + return NULL; + return PyCursesCheckERR(wredrawln(self->win,beg,num), "redrawln"); + } + + static PyObject * + PyCursesWindow_Refresh(PyCursesWindowObject *self, PyObject *args) + { + int pminrow,pmincol,sminrow,smincol,smaxrow,smaxcol; + int rtn; + +#ifndef WINDOW_HAS_FLAGS + if (0) { +#else + if (self->win->_flags & _ISPAD) { +#endif + switch(PyTuple_Size(args)) { + case 6: + if (!PyArg_ParseTuple(args, + "iiiiii;" \ + "pminrow,pmincol,sminrow,smincol,smaxrow,smaxcol", + &pminrow, &pmincol, &sminrow, + &smincol, &smaxrow, &smaxcol)) + return NULL; + + Py_BEGIN_ALLOW_THREADS + rtn = prefresh(self->win, + pminrow, pmincol, sminrow, + smincol, smaxrow, smaxcol); + Py_END_ALLOW_THREADS + return PyCursesCheckERR(rtn, "prefresh"); + default: + PyErr_SetString(PyCursesError, + "refresh() for a pad requires 6 arguments"); + return NULL; + } + } else { + if (!PyArg_ParseTuple(args, ":refresh")) + return NULL; + Py_BEGIN_ALLOW_THREADS + rtn = wrefresh(self->win); + Py_END_ALLOW_THREADS + return PyCursesCheckERR(rtn, "prefresh"); + } + } + + static PyObject * + PyCursesWindow_SetScrollRegion(PyCursesWindowObject *self, PyObject *args) + { + int x, y; + if (!PyArg_ParseTuple(args,"ii;top, bottom",&y,&x)) + return NULL; + return PyCursesCheckERR(wsetscrreg(self->win,y,x), "wsetscrreg"); + } + + static PyObject * + PyCursesWindow_SubWin(PyCursesWindowObject *self, PyObject *args) + { + WINDOW *win; + int nlines, ncols, begin_y, begin_x; + + nlines = 0; + ncols = 0; + switch (PyTuple_Size(args)) { + case 2: + if (!PyArg_ParseTuple(args,"ii;begin_y,begin_x",&begin_y,&begin_x)) + return NULL; + break; + case 4: + if (!PyArg_ParseTuple(args, "iiii;nlines,ncols,begin_y,begin_x", + &nlines,&ncols,&begin_y,&begin_x)) + return NULL; + break; + default: + PyErr_SetString(PyExc_TypeError, "subwin requires 2 or 4 arguments"); + return NULL; + } + + /* printf("Subwin: %i %i %i %i \n", nlines, ncols, begin_y, begin_x); */ +#ifdef WINDOW_HAS_FLAGS + if (self->win->_flags & _ISPAD) + win = subpad(self->win, nlines, ncols, begin_y, begin_x); + else +#endif + win = subwin(self->win, nlines, ncols, begin_y, begin_x); + + if (win == NULL) { + PyErr_SetString(PyCursesError, catchall_NULL); + return NULL; + } + + return (PyObject *)PyCursesWindow_New(win); + } + + static PyObject * + PyCursesWindow_Scroll(PyCursesWindowObject *self, PyObject *args) + { + int nlines; + switch(PyTuple_Size(args)) { + case 0: + return PyCursesCheckERR(scroll(self->win), "scroll"); + case 1: + if (!PyArg_ParseTuple(args, "i;nlines", &nlines)) + return NULL; + return PyCursesCheckERR(wscrl(self->win, nlines), "scroll"); + default: + PyErr_SetString(PyExc_TypeError, "scroll requires 0 or 1 arguments"); + return NULL; + } + } + + static PyObject * + PyCursesWindow_TouchLine(PyCursesWindowObject *self, PyObject *args) + { + int st, cnt, val; + switch (PyTuple_Size(args)) { + case 2: + if (!PyArg_ParseTuple(args,"ii;start,count",&st,&cnt)) + return NULL; + return PyCursesCheckERR(touchline(self->win,st,cnt), "touchline"); + case 3: + if (!PyArg_ParseTuple(args, "iii;start,count,val", &st, &cnt, &val)) + return NULL; + return PyCursesCheckERR(wtouchln(self->win, st, cnt, val), "touchline"); + default: + PyErr_SetString(PyExc_TypeError, "touchline requires 2 or 3 arguments"); + return NULL; + } + } + + static PyObject * + PyCursesWindow_Vline(PyCursesWindowObject *self, PyObject *args) + { + PyObject *temp; + chtype ch; + int n, x, y, code = OK; + attr_t attr = A_NORMAL; + long lattr; + + switch (PyTuple_Size(args)) { + case 2: + if (!PyArg_ParseTuple(args, "Oi;ch or int,n", &temp, &n)) + return NULL; + break; + case 3: + if (!PyArg_ParseTuple(args, "Oil;ch or int,n,attr", &temp, &n, &lattr)) + return NULL; + attr = lattr; + break; + case 4: + if (!PyArg_ParseTuple(args, "iiOi;y,x,ch or int,n", &y, &x, &temp, &n)) + return NULL; + code = wmove(self->win, y, x); + break; + case 5: + if (!PyArg_ParseTuple(args, "iiOil; y,x,ch or int,n,attr", + &y, &x, &temp, &n, &lattr)) + return NULL; + attr = lattr; + code = wmove(self->win, y, x); + break; + default: + PyErr_SetString(PyExc_TypeError, "vline requires 2 to 5 arguments"); + return NULL; + } + + if (code != ERR) { + if (!PyCurses_ConvertToChtype(temp, &ch)) { + PyErr_SetString(PyExc_TypeError, + "argument 1 or 3 must be a ch or an int"); + return NULL; + } + return PyCursesCheckERR(wvline(self->win, ch | attr, n), "vline"); + } else + return PyCursesCheckERR(code, "wmove"); + } + + static PyMethodDef PyCursesWindow_Methods[] = { + {"addch", (PyCFunction)PyCursesWindow_AddCh, METH_VARARGS}, + {"addnstr", (PyCFunction)PyCursesWindow_AddNStr, METH_VARARGS}, + {"addstr", (PyCFunction)PyCursesWindow_AddStr, METH_VARARGS}, + {"attroff", (PyCFunction)PyCursesWindow_AttrOff, METH_VARARGS}, + {"attron", (PyCFunction)PyCursesWindow_AttrOn, METH_VARARGS}, + {"attrset", (PyCFunction)PyCursesWindow_AttrSet, METH_VARARGS}, + {"bkgd", (PyCFunction)PyCursesWindow_Bkgd, METH_VARARGS}, + {"chgat", (PyCFunction)PyCursesWindow_ChgAt, METH_VARARGS}, + {"bkgdset", (PyCFunction)PyCursesWindow_BkgdSet, METH_VARARGS}, + {"border", (PyCFunction)PyCursesWindow_Border, METH_VARARGS}, + {"box", (PyCFunction)PyCursesWindow_Box, METH_VARARGS}, + {"clear", (PyCFunction)PyCursesWindow_wclear, METH_NOARGS}, + {"clearok", (PyCFunction)PyCursesWindow_clearok, METH_VARARGS}, + {"clrtobot", (PyCFunction)PyCursesWindow_wclrtobot, METH_NOARGS}, + {"clrtoeol", (PyCFunction)PyCursesWindow_wclrtoeol, METH_NOARGS}, + {"cursyncup", (PyCFunction)PyCursesWindow_wcursyncup, METH_NOARGS}, + {"delch", (PyCFunction)PyCursesWindow_DelCh, METH_VARARGS}, + {"deleteln", (PyCFunction)PyCursesWindow_wdeleteln, METH_NOARGS}, + {"derwin", (PyCFunction)PyCursesWindow_DerWin, METH_VARARGS}, + {"echochar", (PyCFunction)PyCursesWindow_EchoChar, METH_VARARGS}, #ifdef NCURSES_MOUSE_VERSION - {"enclose", (PyCFunction)PyCursesWindow_Enclose, METH_VARARGS}, + {"enclose", (PyCFunction)PyCursesWindow_Enclose, METH_VARARGS}, #endif - {"erase", (PyCFunction)PyCursesWindow_werase, METH_NOARGS}, - {"getbegyx", (PyCFunction)PyCursesWindow_getbegyx, METH_NOARGS}, - {"getbkgd", (PyCFunction)PyCursesWindow_GetBkgd, METH_NOARGS}, - {"getch", (PyCFunction)PyCursesWindow_GetCh, METH_VARARGS}, - {"getkey", (PyCFunction)PyCursesWindow_GetKey, METH_VARARGS}, - {"getmaxyx", (PyCFunction)PyCursesWindow_getmaxyx, METH_NOARGS}, - {"getparyx", (PyCFunction)PyCursesWindow_getparyx, METH_NOARGS}, - {"getstr", (PyCFunction)PyCursesWindow_GetStr, METH_VARARGS}, - {"getyx", (PyCFunction)PyCursesWindow_getyx, METH_NOARGS}, - {"hline", (PyCFunction)PyCursesWindow_Hline, METH_VARARGS}, - {"idcok", (PyCFunction)PyCursesWindow_idcok, METH_VARARGS}, - {"idlok", (PyCFunction)PyCursesWindow_idlok, METH_VARARGS}, - {"immedok", (PyCFunction)PyCursesWindow_immedok, METH_VARARGS}, - {"inch", (PyCFunction)PyCursesWindow_InCh, METH_VARARGS}, - {"insch", (PyCFunction)PyCursesWindow_InsCh, METH_VARARGS}, - {"insdelln", (PyCFunction)PyCursesWindow_winsdelln, METH_VARARGS}, - {"insertln", (PyCFunction)PyCursesWindow_winsertln, METH_NOARGS}, - {"insnstr", (PyCFunction)PyCursesWindow_InsNStr, METH_VARARGS}, - {"insstr", (PyCFunction)PyCursesWindow_InsStr, METH_VARARGS}, - {"instr", (PyCFunction)PyCursesWindow_InStr, METH_VARARGS}, - {"is_linetouched", (PyCFunction)PyCursesWindow_Is_LineTouched, METH_VARARGS}, - {"is_wintouched", (PyCFunction)PyCursesWindow_is_wintouched, METH_NOARGS}, - {"keypad", (PyCFunction)PyCursesWindow_keypad, METH_VARARGS}, - {"leaveok", (PyCFunction)PyCursesWindow_leaveok, METH_VARARGS}, - {"move", (PyCFunction)PyCursesWindow_wmove, METH_VARARGS}, - {"mvderwin", (PyCFunction)PyCursesWindow_mvderwin, METH_VARARGS}, - {"mvwin", (PyCFunction)PyCursesWindow_mvwin, METH_VARARGS}, - {"nodelay", (PyCFunction)PyCursesWindow_nodelay, METH_VARARGS}, - {"notimeout", (PyCFunction)PyCursesWindow_notimeout, METH_VARARGS}, - {"noutrefresh", (PyCFunction)PyCursesWindow_NoOutRefresh, METH_VARARGS}, - /* Backward compatibility alias -- remove in Python 2.3 */ - {"nooutrefresh", (PyCFunction)PyCursesWindow_NoOutRefresh, METH_VARARGS}, - {"overlay", (PyCFunction)PyCursesWindow_Overlay, METH_VARARGS}, - {"overwrite", (PyCFunction)PyCursesWindow_Overwrite, - METH_VARARGS}, - {"putwin", (PyCFunction)PyCursesWindow_PutWin, METH_VARARGS}, - {"redrawln", (PyCFunction)PyCursesWindow_RedrawLine, METH_VARARGS}, - {"redrawwin", (PyCFunction)PyCursesWindow_redrawwin, METH_NOARGS}, - {"refresh", (PyCFunction)PyCursesWindow_Refresh, METH_VARARGS}, + {"erase", (PyCFunction)PyCursesWindow_werase, METH_NOARGS}, + {"getbegyx", (PyCFunction)PyCursesWindow_getbegyx, METH_NOARGS}, + {"getbkgd", (PyCFunction)PyCursesWindow_GetBkgd, METH_NOARGS}, + {"getch", (PyCFunction)PyCursesWindow_GetCh, METH_VARARGS}, + {"getkey", (PyCFunction)PyCursesWindow_GetKey, METH_VARARGS}, + {"getmaxyx", (PyCFunction)PyCursesWindow_getmaxyx, METH_NOARGS}, + {"getparyx", (PyCFunction)PyCursesWindow_getparyx, METH_NOARGS}, + {"getstr", (PyCFunction)PyCursesWindow_GetStr, METH_VARARGS}, + {"getyx", (PyCFunction)PyCursesWindow_getyx, METH_NOARGS}, + {"hline", (PyCFunction)PyCursesWindow_Hline, METH_VARARGS}, + {"idcok", (PyCFunction)PyCursesWindow_idcok, METH_VARARGS}, + {"idlok", (PyCFunction)PyCursesWindow_idlok, METH_VARARGS}, + {"immedok", (PyCFunction)PyCursesWindow_immedok, METH_VARARGS}, + {"inch", (PyCFunction)PyCursesWindow_InCh, METH_VARARGS}, + {"insch", (PyCFunction)PyCursesWindow_InsCh, METH_VARARGS}, + {"insdelln", (PyCFunction)PyCursesWindow_winsdelln, METH_VARARGS}, + {"insertln", (PyCFunction)PyCursesWindow_winsertln, METH_NOARGS}, + {"insnstr", (PyCFunction)PyCursesWindow_InsNStr, METH_VARARGS}, + {"insstr", (PyCFunction)PyCursesWindow_InsStr, METH_VARARGS}, + {"instr", (PyCFunction)PyCursesWindow_InStr, METH_VARARGS}, + {"is_linetouched", (PyCFunction)PyCursesWindow_Is_LineTouched, METH_VARARGS}, + {"is_wintouched", (PyCFunction)PyCursesWindow_is_wintouched, METH_NOARGS}, + {"keypad", (PyCFunction)PyCursesWindow_keypad, METH_VARARGS}, + {"leaveok", (PyCFunction)PyCursesWindow_leaveok, METH_VARARGS}, + {"move", (PyCFunction)PyCursesWindow_wmove, METH_VARARGS}, + {"mvderwin", (PyCFunction)PyCursesWindow_mvderwin, METH_VARARGS}, + {"mvwin", (PyCFunction)PyCursesWindow_mvwin, METH_VARARGS}, + {"nodelay", (PyCFunction)PyCursesWindow_nodelay, METH_VARARGS}, + {"notimeout", (PyCFunction)PyCursesWindow_notimeout, METH_VARARGS}, + {"noutrefresh", (PyCFunction)PyCursesWindow_NoOutRefresh, METH_VARARGS}, + /* Backward compatibility alias -- remove in Python 2.3 */ + {"nooutrefresh", (PyCFunction)PyCursesWindow_NoOutRefresh, METH_VARARGS}, + {"overlay", (PyCFunction)PyCursesWindow_Overlay, METH_VARARGS}, + {"overwrite", (PyCFunction)PyCursesWindow_Overwrite, + METH_VARARGS}, + {"putwin", (PyCFunction)PyCursesWindow_PutWin, METH_VARARGS}, + {"redrawln", (PyCFunction)PyCursesWindow_RedrawLine, METH_VARARGS}, + {"redrawwin", (PyCFunction)PyCursesWindow_redrawwin, METH_NOARGS}, + {"refresh", (PyCFunction)PyCursesWindow_Refresh, METH_VARARGS}, #ifndef STRICT_SYSV_CURSES - {"resize", (PyCFunction)PyCursesWindow_wresize, METH_VARARGS}, + {"resize", (PyCFunction)PyCursesWindow_wresize, METH_VARARGS}, #endif - {"scroll", (PyCFunction)PyCursesWindow_Scroll, METH_VARARGS}, - {"scrollok", (PyCFunction)PyCursesWindow_scrollok, METH_VARARGS}, - {"setscrreg", (PyCFunction)PyCursesWindow_SetScrollRegion, METH_VARARGS}, - {"standend", (PyCFunction)PyCursesWindow_wstandend, METH_NOARGS}, - {"standout", (PyCFunction)PyCursesWindow_wstandout, METH_NOARGS}, - {"subpad", (PyCFunction)PyCursesWindow_SubWin, METH_VARARGS}, - {"subwin", (PyCFunction)PyCursesWindow_SubWin, METH_VARARGS}, - {"syncdown", (PyCFunction)PyCursesWindow_wsyncdown, METH_NOARGS}, - {"syncok", (PyCFunction)PyCursesWindow_syncok, METH_VARARGS}, - {"syncup", (PyCFunction)PyCursesWindow_wsyncup, METH_NOARGS}, - {"timeout", (PyCFunction)PyCursesWindow_wtimeout, METH_VARARGS}, - {"touchline", (PyCFunction)PyCursesWindow_TouchLine, METH_VARARGS}, - {"touchwin", (PyCFunction)PyCursesWindow_touchwin, METH_NOARGS}, - {"untouchwin", (PyCFunction)PyCursesWindow_untouchwin, METH_NOARGS}, - {"vline", (PyCFunction)PyCursesWindow_Vline, METH_VARARGS}, - {NULL, NULL} /* sentinel */ -}; - -static PyObject * -PyCursesWindow_GetAttr(PyCursesWindowObject *self, char *name) -{ - return Py_FindMethod(PyCursesWindow_Methods, (PyObject *)self, name); -} + {"scroll", (PyCFunction)PyCursesWindow_Scroll, METH_VARARGS}, + {"scrollok", (PyCFunction)PyCursesWindow_scrollok, METH_VARARGS}, + {"setscrreg", (PyCFunction)PyCursesWindow_SetScrollRegion, METH_VARARGS}, + {"standend", (PyCFunction)PyCursesWindow_wstandend, METH_NOARGS}, + {"standout", (PyCFunction)PyCursesWindow_wstandout, METH_NOARGS}, + {"subpad", (PyCFunction)PyCursesWindow_SubWin, METH_VARARGS}, + {"subwin", (PyCFunction)PyCursesWindow_SubWin, METH_VARARGS}, + {"syncdown", (PyCFunction)PyCursesWindow_wsyncdown, METH_NOARGS}, + {"syncok", (PyCFunction)PyCursesWindow_syncok, METH_VARARGS}, + {"syncup", (PyCFunction)PyCursesWindow_wsyncup, METH_NOARGS}, + {"timeout", (PyCFunction)PyCursesWindow_wtimeout, METH_VARARGS}, + {"touchline", (PyCFunction)PyCursesWindow_TouchLine, METH_VARARGS}, + {"touchwin", (PyCFunction)PyCursesWindow_touchwin, METH_NOARGS}, + {"untouchwin", (PyCFunction)PyCursesWindow_untouchwin, METH_NOARGS}, + {"vline", (PyCFunction)PyCursesWindow_Vline, METH_VARARGS}, + {NULL, NULL} /* sentinel */ + }; + + static PyObject * + PyCursesWindow_GetAttr(PyCursesWindowObject *self, char *name) + { + return Py_FindMethod(PyCursesWindow_Methods, (PyObject *)self, name); + } /* -------------------------------------------------------*/ -PyTypeObject PyCursesWindow_Type = { - PyVarObject_HEAD_INIT(NULL, 0) - "_curses.curses window", /*tp_name*/ - sizeof(PyCursesWindowObject), /*tp_basicsize*/ - 0, /*tp_itemsize*/ - /* methods */ - (destructor)PyCursesWindow_Dealloc, /*tp_dealloc*/ - 0, /*tp_print*/ - (getattrfunc)PyCursesWindow_GetAttr, /*tp_getattr*/ - (setattrfunc)0, /*tp_setattr*/ - 0, /*tp_compare*/ - 0, /*tp_repr*/ - 0, /*tp_as_number*/ - 0, /*tp_as_sequence*/ - 0, /*tp_as_mapping*/ - 0, /*tp_hash*/ -}; + PyTypeObject PyCursesWindow_Type = { + PyVarObject_HEAD_INIT(NULL, 0) + "_curses.curses window", /*tp_name*/ + sizeof(PyCursesWindowObject), /*tp_basicsize*/ + 0, /*tp_itemsize*/ + /* methods */ + (destructor)PyCursesWindow_Dealloc, /*tp_dealloc*/ + 0, /*tp_print*/ + (getattrfunc)PyCursesWindow_GetAttr, /*tp_getattr*/ + (setattrfunc)0, /*tp_setattr*/ + 0, /*tp_compare*/ + 0, /*tp_repr*/ + 0, /*tp_as_number*/ + 0, /*tp_as_sequence*/ + 0, /*tp_as_mapping*/ + 0, /*tp_hash*/ + }; /********************************************************************* Global Functions **********************************************************************/ -NoArgNoReturnFunction(beep) -NoArgNoReturnFunction(def_prog_mode) -NoArgNoReturnFunction(def_shell_mode) -NoArgNoReturnFunction(doupdate) -NoArgNoReturnFunction(endwin) -NoArgNoReturnFunction(flash) -NoArgNoReturnFunction(nocbreak) -NoArgNoReturnFunction(noecho) -NoArgNoReturnFunction(nonl) -NoArgNoReturnFunction(noraw) -NoArgNoReturnFunction(reset_prog_mode) -NoArgNoReturnFunction(reset_shell_mode) -NoArgNoReturnFunction(resetty) -NoArgNoReturnFunction(savetty) + NoArgNoReturnFunction(beep) + NoArgNoReturnFunction(def_prog_mode) + NoArgNoReturnFunction(def_shell_mode) + NoArgNoReturnFunction(doupdate) + NoArgNoReturnFunction(endwin) + NoArgNoReturnFunction(flash) + NoArgNoReturnFunction(nocbreak) + NoArgNoReturnFunction(noecho) + NoArgNoReturnFunction(nonl) + NoArgNoReturnFunction(noraw) + NoArgNoReturnFunction(reset_prog_mode) + NoArgNoReturnFunction(reset_shell_mode) + NoArgNoReturnFunction(resetty) + NoArgNoReturnFunction(savetty) + + NoArgOrFlagNoReturnFunction(cbreak) + NoArgOrFlagNoReturnFunction(echo) + NoArgOrFlagNoReturnFunction(nl) + NoArgOrFlagNoReturnFunction(raw) + + NoArgReturnIntFunction(baudrate) + NoArgReturnIntFunction(termattrs) + + NoArgReturnStringFunction(termname) + NoArgReturnStringFunction(longname) + + NoArgTrueFalseFunction(can_change_color) + NoArgTrueFalseFunction(has_colors) + NoArgTrueFalseFunction(has_ic) + NoArgTrueFalseFunction(has_il) + NoArgTrueFalseFunction(isendwin) + NoArgNoReturnVoidFunction(flushinp) + NoArgNoReturnVoidFunction(noqiflush) + + static PyObject * + PyCurses_filter(PyObject *self) + { + /* not checking for PyCursesInitialised here since filter() must + be called before initscr() */ + filter(); + Py_INCREF(Py_None); + return Py_None; + } + + static PyObject * + PyCurses_Color_Content(PyObject *self, PyObject *args) + { + short color,r,g,b; + + PyCursesInitialised + PyCursesInitialisedColor + + if (!PyArg_ParseTuple(args, "h:color_content", &color)) return NULL; + + if (color_content(color, &r, &g, &b) != ERR) + return Py_BuildValue("(iii)", r, g, b); + else { + PyErr_SetString(PyCursesError, + "Argument 1 was out of range. Check value of COLORS."); + return NULL; + } + } + + static PyObject * + PyCurses_color_pair(PyObject *self, PyObject *args) + { + int n; + + PyCursesInitialised + PyCursesInitialisedColor + + if (!PyArg_ParseTuple(args, "i:color_pair", &n)) return NULL; + return PyInt_FromLong((long) (n << 8)); + } + + static PyObject * + PyCurses_Curs_Set(PyObject *self, PyObject *args) + { + int vis,erg; + + PyCursesInitialised + + if (!PyArg_ParseTuple(args, "i:curs_set", &vis)) return NULL; + + erg = curs_set(vis); + if (erg == ERR) return PyCursesCheckERR(erg, "curs_set"); + + return PyInt_FromLong((long) erg); + } + + static PyObject * + PyCurses_Delay_Output(PyObject *self, PyObject *args) + { + int ms; + + PyCursesInitialised + + if (!PyArg_ParseTuple(args, "i:delay_output", &ms)) return NULL; + + return PyCursesCheckERR(delay_output(ms), "delay_output"); + } + + static PyObject * + PyCurses_EraseChar(PyObject *self) + { + char ch; + + PyCursesInitialised + + ch = erasechar(); + + return PyString_FromStringAndSize(&ch, 1); + } + + static PyObject * + PyCurses_getsyx(PyObject *self) + { + int x,y; -NoArgOrFlagNoReturnFunction(cbreak) -NoArgOrFlagNoReturnFunction(echo) -NoArgOrFlagNoReturnFunction(nl) -NoArgOrFlagNoReturnFunction(raw) + PyCursesInitialised -NoArgReturnIntFunction(baudrate) -NoArgReturnIntFunction(termattrs) + getsyx(y, x); -NoArgReturnStringFunction(termname) -NoArgReturnStringFunction(longname) + return Py_BuildValue("(ii)", y, x); + } -NoArgTrueFalseFunction(can_change_color) -NoArgTrueFalseFunction(has_colors) -NoArgTrueFalseFunction(has_ic) -NoArgTrueFalseFunction(has_il) -NoArgTrueFalseFunction(isendwin) -NoArgNoReturnVoidFunction(flushinp) -NoArgNoReturnVoidFunction(noqiflush) +#ifdef NCURSES_MOUSE_VERSION + static PyObject * + PyCurses_GetMouse(PyObject *self) + { + int rtn; + MEVENT event; + + PyCursesInitialised + + rtn = getmouse( &event ); + if (rtn == ERR) { + PyErr_SetString(PyCursesError, "getmouse() returned ERR"); + return NULL; + } + return Py_BuildValue("(hiiil)", + (short)event.id, + event.x, event.y, event.z, + (long) event.bstate); + } + + static PyObject * + PyCurses_UngetMouse(PyObject *self, PyObject *args) + { + MEVENT event; + + PyCursesInitialised + if (!PyArg_ParseTuple(args, "hiiil", + &event.id, + &event.x, &event.y, &event.z, + (int *) &event.bstate)) + return NULL; + + return PyCursesCheckERR(ungetmouse(&event), "ungetmouse"); + } +#endif + + static PyObject * + PyCurses_GetWin(PyCursesWindowObject *self, PyObject *temp) + { + WINDOW *win; + + PyCursesInitialised + + if (!PyFile_Check(temp)) { + PyErr_SetString(PyExc_TypeError, "argument must be a file object"); + return NULL; + } + + win = getwin(PyFile_AsFile(temp)); + + if (win == NULL) { + PyErr_SetString(PyCursesError, catchall_NULL); + return NULL; + } + + return PyCursesWindow_New(win); + } + + static PyObject * + PyCurses_HalfDelay(PyObject *self, PyObject *args) + { + unsigned char tenths; -static PyObject * -PyCurses_filter(PyObject *self) -{ - /* not checking for PyCursesInitialised here since filter() must - be called before initscr() */ - filter(); - Py_INCREF(Py_None); - return Py_None; -} + PyCursesInitialised -static PyObject * -PyCurses_Color_Content(PyObject *self, PyObject *args) -{ - short color,r,g,b; + if (!PyArg_ParseTuple(args, "b:halfdelay", &tenths)) return NULL; - PyCursesInitialised - PyCursesInitialisedColor + return PyCursesCheckERR(halfdelay(tenths), "halfdelay"); + } - if (!PyArg_ParseTuple(args, "h:color_content", &color)) return NULL; +#ifndef STRICT_SYSV_CURSES + /* No has_key! */ + static PyObject * PyCurses_has_key(PyObject *self, PyObject *args) + { + int ch; + + PyCursesInitialised + + if (!PyArg_ParseTuple(args,"i",&ch)) return NULL; + + if (has_key(ch) == FALSE) { + Py_INCREF(Py_False); + return Py_False; + } + Py_INCREF(Py_True); + return Py_True; + } +#endif /* STRICT_SYSV_CURSES */ - if (color_content(color, &r, &g, &b) != ERR) - return Py_BuildValue("(iii)", r, g, b); - else { - PyErr_SetString(PyCursesError, - "Argument 1 was out of range. Check value of COLORS."); - return NULL; - } -} + static PyObject * + PyCurses_Init_Color(PyObject *self, PyObject *args) + { + short color, r, g, b; + + PyCursesInitialised + PyCursesInitialisedColor + + switch(PyTuple_Size(args)) { + case 4: + if (!PyArg_ParseTuple(args, "hhhh;color,r,g,b", &color, &r, &g, &b)) return NULL; + break; + default: + PyErr_SetString(PyExc_TypeError, "init_color requires 4 arguments"); + return NULL; + } + + return PyCursesCheckERR(init_color(color, r, g, b), "init_color"); + } + + static PyObject * + PyCurses_Init_Pair(PyObject *self, PyObject *args) + { + short pair, f, b; + + PyCursesInitialised + PyCursesInitialisedColor + + if (PyTuple_Size(args) != 3) { + PyErr_SetString(PyExc_TypeError, "init_pair requires 3 arguments"); + return NULL; + } + + if (!PyArg_ParseTuple(args, "hhh;pair, f, b", &pair, &f, &b)) return NULL; + + return PyCursesCheckERR(init_pair(pair, f, b), "init_pair"); + } + + static PyObject *ModDict; + + static PyObject * + PyCurses_InitScr(PyObject *self) + { + WINDOW *win; + + if (initialised == TRUE) { + wrefresh(stdscr); + return (PyObject *)PyCursesWindow_New(stdscr); + } + + win = initscr(); + + if (win == NULL) { + PyErr_SetString(PyCursesError, catchall_NULL); + return NULL; + } -static PyObject * -PyCurses_color_pair(PyObject *self, PyObject *args) -{ - int n; + initialised = initialised_setupterm = TRUE; - PyCursesInitialised - PyCursesInitialisedColor +/* This was moved from initcurses() because it core dumped on SGI, + where they're not defined until you've called initscr() */ +#define SetDictInt(string,ch) \ + do { \ + PyObject *o = PyInt_FromLong((long) (ch)); \ + if (o && PyDict_SetItemString(ModDict, string, o) == 0) { \ + Py_DECREF(o); \ + } \ + } while (0) + + /* Here are some graphic symbols you can use */ + SetDictInt("ACS_ULCORNER", (ACS_ULCORNER)); + SetDictInt("ACS_LLCORNER", (ACS_LLCORNER)); + SetDictInt("ACS_URCORNER", (ACS_URCORNER)); + SetDictInt("ACS_LRCORNER", (ACS_LRCORNER)); + SetDictInt("ACS_LTEE", (ACS_LTEE)); + SetDictInt("ACS_RTEE", (ACS_RTEE)); + SetDictInt("ACS_BTEE", (ACS_BTEE)); + SetDictInt("ACS_TTEE", (ACS_TTEE)); + SetDictInt("ACS_HLINE", (ACS_HLINE)); + SetDictInt("ACS_VLINE", (ACS_VLINE)); + SetDictInt("ACS_PLUS", (ACS_PLUS)); +#if !defined(__hpux) || defined(HAVE_NCURSES_H) + /* On HP/UX 11, these are of type cchar_t, which is not an + integral type. If this is a problem on more platforms, a + configure test should be added to determine whether ACS_S1 + is of integral type. */ + SetDictInt("ACS_S1", (ACS_S1)); + SetDictInt("ACS_S9", (ACS_S9)); + SetDictInt("ACS_DIAMOND", (ACS_DIAMOND)); + SetDictInt("ACS_CKBOARD", (ACS_CKBOARD)); + SetDictInt("ACS_DEGREE", (ACS_DEGREE)); + SetDictInt("ACS_PLMINUS", (ACS_PLMINUS)); + SetDictInt("ACS_BULLET", (ACS_BULLET)); + SetDictInt("ACS_LARROW", (ACS_LARROW)); + SetDictInt("ACS_RARROW", (ACS_RARROW)); + SetDictInt("ACS_DARROW", (ACS_DARROW)); + SetDictInt("ACS_UARROW", (ACS_UARROW)); + SetDictInt("ACS_BOARD", (ACS_BOARD)); + SetDictInt("ACS_LANTERN", (ACS_LANTERN)); + SetDictInt("ACS_BLOCK", (ACS_BLOCK)); +#endif + SetDictInt("ACS_BSSB", (ACS_ULCORNER)); + SetDictInt("ACS_SSBB", (ACS_LLCORNER)); + SetDictInt("ACS_BBSS", (ACS_URCORNER)); + SetDictInt("ACS_SBBS", (ACS_LRCORNER)); + SetDictInt("ACS_SBSS", (ACS_RTEE)); + SetDictInt("ACS_SSSB", (ACS_LTEE)); + SetDictInt("ACS_SSBS", (ACS_BTEE)); + SetDictInt("ACS_BSSS", (ACS_TTEE)); + SetDictInt("ACS_BSBS", (ACS_HLINE)); + SetDictInt("ACS_SBSB", (ACS_VLINE)); + SetDictInt("ACS_SSSS", (ACS_PLUS)); - if (!PyArg_ParseTuple(args, "i:color_pair", &n)) return NULL; - return PyInt_FromLong((long) (n << 8)); -} - -static PyObject * -PyCurses_Curs_Set(PyObject *self, PyObject *args) -{ - int vis,erg; - - PyCursesInitialised - - if (!PyArg_ParseTuple(args, "i:curs_set", &vis)) return NULL; - - erg = curs_set(vis); - if (erg == ERR) return PyCursesCheckERR(erg, "curs_set"); - - return PyInt_FromLong((long) erg); -} - -static PyObject * -PyCurses_Delay_Output(PyObject *self, PyObject *args) -{ - int ms; - - PyCursesInitialised - - if (!PyArg_ParseTuple(args, "i:delay_output", &ms)) return NULL; - - return PyCursesCheckERR(delay_output(ms), "delay_output"); -} - -static PyObject * -PyCurses_EraseChar(PyObject *self) -{ - char ch; - - PyCursesInitialised - - ch = erasechar(); - - return PyString_FromStringAndSize(&ch, 1); -} - -static PyObject * -PyCurses_getsyx(PyObject *self) -{ - int x,y; - - PyCursesInitialised - - getsyx(y, x); - - return Py_BuildValue("(ii)", y, x); -} - -#ifdef NCURSES_MOUSE_VERSION -static PyObject * -PyCurses_GetMouse(PyObject *self) -{ - int rtn; - MEVENT event; - - PyCursesInitialised - - rtn = getmouse( &event ); - if (rtn == ERR) { - PyErr_SetString(PyCursesError, "getmouse() returned ERR"); - return NULL; - } - return Py_BuildValue("(hiiil)", - (short)event.id, - event.x, event.y, event.z, - (long) event.bstate); -} - -static PyObject * -PyCurses_UngetMouse(PyObject *self, PyObject *args) -{ - MEVENT event; - - PyCursesInitialised - if (!PyArg_ParseTuple(args, "hiiil", - &event.id, - &event.x, &event.y, &event.z, - (int *) &event.bstate)) - return NULL; - - return PyCursesCheckERR(ungetmouse(&event), "ungetmouse"); -} -#endif - -static PyObject * -PyCurses_GetWin(PyCursesWindowObject *self, PyObject *temp) -{ - WINDOW *win; - - PyCursesInitialised - - if (!PyFile_Check(temp)) { - PyErr_SetString(PyExc_TypeError, "argument must be a file object"); - return NULL; - } - - win = getwin(PyFile_AsFile(temp)); - - if (win == NULL) { - PyErr_SetString(PyCursesError, catchall_NULL); - return NULL; - } - - return PyCursesWindow_New(win); -} - -static PyObject * -PyCurses_HalfDelay(PyObject *self, PyObject *args) -{ - unsigned char tenths; - - PyCursesInitialised - - if (!PyArg_ParseTuple(args, "b:halfdelay", &tenths)) return NULL; - - return PyCursesCheckERR(halfdelay(tenths), "halfdelay"); -} - -#ifndef STRICT_SYSV_CURSES - /* No has_key! */ -static PyObject * PyCurses_has_key(PyObject *self, PyObject *args) -{ - int ch; - - PyCursesInitialised - - if (!PyArg_ParseTuple(args,"i",&ch)) return NULL; - - if (has_key(ch) == FALSE) { - Py_INCREF(Py_False); - return Py_False; - } - Py_INCREF(Py_True); - return Py_True; -} -#endif /* STRICT_SYSV_CURSES */ - -static PyObject * -PyCurses_Init_Color(PyObject *self, PyObject *args) -{ - short color, r, g, b; - - PyCursesInitialised - PyCursesInitialisedColor - - switch(PyTuple_Size(args)) { - case 4: - if (!PyArg_ParseTuple(args, "hhhh;color,r,g,b", &color, &r, &g, &b)) return NULL; - break; - default: - PyErr_SetString(PyExc_TypeError, "init_color requires 4 arguments"); - return NULL; - } - - return PyCursesCheckERR(init_color(color, r, g, b), "init_color"); -} - -static PyObject * -PyCurses_Init_Pair(PyObject *self, PyObject *args) -{ - short pair, f, b; - - PyCursesInitialised - PyCursesInitialisedColor - - if (PyTuple_Size(args) != 3) { - PyErr_SetString(PyExc_TypeError, "init_pair requires 3 arguments"); - return NULL; - } - - if (!PyArg_ParseTuple(args, "hhh;pair, f, b", &pair, &f, &b)) return NULL; - - return PyCursesCheckERR(init_pair(pair, f, b), "init_pair"); -} - -static PyObject *ModDict; - -static PyObject * -PyCurses_InitScr(PyObject *self) -{ - WINDOW *win; - - if (initialised == TRUE) { - wrefresh(stdscr); - return (PyObject *)PyCursesWindow_New(stdscr); - } - - win = initscr(); - - if (win == NULL) { - PyErr_SetString(PyCursesError, catchall_NULL); - return NULL; - } - - initialised = initialised_setupterm = TRUE; - -/* This was moved from initcurses() because it core dumped on SGI, - where they're not defined until you've called initscr() */ -#define SetDictInt(string,ch) \ - do { \ - PyObject *o = PyInt_FromLong((long) (ch)); \ - if (o && PyDict_SetItemString(ModDict, string, o) == 0) { \ - Py_DECREF(o); \ - } \ - } while (0) - - /* Here are some graphic symbols you can use */ - SetDictInt("ACS_ULCORNER", (ACS_ULCORNER)); - SetDictInt("ACS_LLCORNER", (ACS_LLCORNER)); - SetDictInt("ACS_URCORNER", (ACS_URCORNER)); - SetDictInt("ACS_LRCORNER", (ACS_LRCORNER)); - SetDictInt("ACS_LTEE", (ACS_LTEE)); - SetDictInt("ACS_RTEE", (ACS_RTEE)); - SetDictInt("ACS_BTEE", (ACS_BTEE)); - SetDictInt("ACS_TTEE", (ACS_TTEE)); - SetDictInt("ACS_HLINE", (ACS_HLINE)); - SetDictInt("ACS_VLINE", (ACS_VLINE)); - SetDictInt("ACS_PLUS", (ACS_PLUS)); -#if !defined(__hpux) || defined(HAVE_NCURSES_H) - /* On HP/UX 11, these are of type cchar_t, which is not an - integral type. If this is a problem on more platforms, a - configure test should be added to determine whether ACS_S1 - is of integral type. */ - SetDictInt("ACS_S1", (ACS_S1)); - SetDictInt("ACS_S9", (ACS_S9)); - SetDictInt("ACS_DIAMOND", (ACS_DIAMOND)); - SetDictInt("ACS_CKBOARD", (ACS_CKBOARD)); - SetDictInt("ACS_DEGREE", (ACS_DEGREE)); - SetDictInt("ACS_PLMINUS", (ACS_PLMINUS)); - SetDictInt("ACS_BULLET", (ACS_BULLET)); - SetDictInt("ACS_LARROW", (ACS_LARROW)); - SetDictInt("ACS_RARROW", (ACS_RARROW)); - SetDictInt("ACS_DARROW", (ACS_DARROW)); - SetDictInt("ACS_UARROW", (ACS_UARROW)); - SetDictInt("ACS_BOARD", (ACS_BOARD)); - SetDictInt("ACS_LANTERN", (ACS_LANTERN)); - SetDictInt("ACS_BLOCK", (ACS_BLOCK)); -#endif - SetDictInt("ACS_BSSB", (ACS_ULCORNER)); - SetDictInt("ACS_SSBB", (ACS_LLCORNER)); - SetDictInt("ACS_BBSS", (ACS_URCORNER)); - SetDictInt("ACS_SBBS", (ACS_LRCORNER)); - SetDictInt("ACS_SBSS", (ACS_RTEE)); - SetDictInt("ACS_SSSB", (ACS_LTEE)); - SetDictInt("ACS_SSBS", (ACS_BTEE)); - SetDictInt("ACS_BSSS", (ACS_TTEE)); - SetDictInt("ACS_BSBS", (ACS_HLINE)); - SetDictInt("ACS_SBSB", (ACS_VLINE)); - SetDictInt("ACS_SSSS", (ACS_PLUS)); - - /* The following are never available with strict SYSV curses */ + /* The following are never available with strict SYSV curses */ #ifdef ACS_S3 - SetDictInt("ACS_S3", (ACS_S3)); + SetDictInt("ACS_S3", (ACS_S3)); #endif #ifdef ACS_S7 - SetDictInt("ACS_S7", (ACS_S7)); + SetDictInt("ACS_S7", (ACS_S7)); #endif #ifdef ACS_LEQUAL - SetDictInt("ACS_LEQUAL", (ACS_LEQUAL)); + SetDictInt("ACS_LEQUAL", (ACS_LEQUAL)); #endif #ifdef ACS_GEQUAL - SetDictInt("ACS_GEQUAL", (ACS_GEQUAL)); + SetDictInt("ACS_GEQUAL", (ACS_GEQUAL)); #endif #ifdef ACS_PI - SetDictInt("ACS_PI", (ACS_PI)); + SetDictInt("ACS_PI", (ACS_PI)); #endif #ifdef ACS_NEQUAL - SetDictInt("ACS_NEQUAL", (ACS_NEQUAL)); + SetDictInt("ACS_NEQUAL", (ACS_NEQUAL)); #endif #ifdef ACS_STERLING - SetDictInt("ACS_STERLING", (ACS_STERLING)); + SetDictInt("ACS_STERLING", (ACS_STERLING)); #endif - SetDictInt("LINES", LINES); - SetDictInt("COLS", COLS); + SetDictInt("LINES", LINES); + SetDictInt("COLS", COLS); - return (PyObject *)PyCursesWindow_New(win); -} + return (PyObject *)PyCursesWindow_New(win); + } -static PyObject * -PyCurses_setupterm(PyObject* self, PyObject *args, PyObject* keywds) -{ - int fd = -1; - int err; - char* termstr = NULL; + static PyObject * + PyCurses_setupterm(PyObject* self, PyObject *args, PyObject* keywds) + { + int fd = -1; + int err; + char* termstr = NULL; - static char *kwlist[] = {"term", "fd", NULL}; + static char *kwlist[] = {"term", "fd", NULL}; - if (!PyArg_ParseTupleAndKeywords( - args, keywds, "|zi:setupterm", kwlist, &termstr, &fd)) { - return NULL; - } - - if (fd == -1) { - PyObject* sys_stdout; + if (!PyArg_ParseTupleAndKeywords( + args, keywds, "|zi:setupterm", kwlist, &termstr, &fd)) { + return NULL; + } - sys_stdout = PySys_GetObject("stdout"); + if (fd == -1) { + PyObject* sys_stdout; - if (sys_stdout == NULL) { - PyErr_SetString( - PyCursesError, - "lost sys.stdout"); - return NULL; - } + sys_stdout = PySys_GetObject("stdout"); - fd = PyObject_AsFileDescriptor(sys_stdout); + if (sys_stdout == NULL) { + PyErr_SetString( + PyCursesError, + "lost sys.stdout"); + return NULL; + } - if (fd == -1) { - return NULL; - } - } + fd = PyObject_AsFileDescriptor(sys_stdout); - if (setupterm(termstr,fd,&err) == ERR) { - char* s = "setupterm: unknown error"; - - if (err == 0) { - s = "setupterm: could not find terminal"; - } else if (err == -1) { - s = "setupterm: could not find terminfo database"; - } + if (fd == -1) { + return NULL; + } + } - PyErr_SetString(PyCursesError,s); - return NULL; - } + if (setupterm(termstr,fd,&err) == ERR) { + char* s = "setupterm: unknown error"; - initialised_setupterm = TRUE; + if (err == 0) { + s = "setupterm: could not find terminal"; + } else if (err == -1) { + s = "setupterm: could not find terminfo database"; + } - Py_INCREF(Py_None); - return Py_None; -} + PyErr_SetString(PyCursesError,s); + return NULL; + } -static PyObject * -PyCurses_IntrFlush(PyObject *self, PyObject *args) -{ - int ch; + initialised_setupterm = TRUE; - PyCursesInitialised + Py_INCREF(Py_None); + return Py_None; + } - switch(PyTuple_Size(args)) { - case 1: - if (!PyArg_ParseTuple(args,"i;True(1), False(0)",&ch)) return NULL; - break; - default: - PyErr_SetString(PyExc_TypeError, "intrflush requires 1 argument"); - return NULL; - } + static PyObject * + PyCurses_IntrFlush(PyObject *self, PyObject *args) + { + int ch; - return PyCursesCheckERR(intrflush(NULL,ch), "intrflush"); -} + PyCursesInitialised + + switch(PyTuple_Size(args)) { + case 1: + if (!PyArg_ParseTuple(args,"i;True(1), False(0)",&ch)) return NULL; + break; + default: + PyErr_SetString(PyExc_TypeError, "intrflush requires 1 argument"); + return NULL; + } + + return PyCursesCheckERR(intrflush(NULL,ch), "intrflush"); + } #ifdef HAVE_CURSES_IS_TERM_RESIZED -static PyObject * -PyCurses_Is_Term_Resized(PyObject *self, PyObject *args) -{ - int lines; - int columns; - int result; - - PyCursesInitialised - - if (!PyArg_ParseTuple(args,"ii:is_term_resized", &lines, &columns)) - return NULL; - result = is_term_resized(lines, columns); - if (result == TRUE) { - Py_INCREF(Py_True); - return Py_True; - } else { - Py_INCREF(Py_False); - return Py_False; - } -} + static PyObject * + PyCurses_Is_Term_Resized(PyObject *self, PyObject *args) + { + int lines; + int columns; + int result; + + PyCursesInitialised + + if (!PyArg_ParseTuple(args,"ii:is_term_resized", &lines, &columns)) + return NULL; + result = is_term_resized(lines, columns); + if (result == TRUE) { + Py_INCREF(Py_True); + return Py_True; + } else { + Py_INCREF(Py_False); + return Py_False; + } + } #endif /* HAVE_CURSES_IS_TERM_RESIZED */ #if !defined(__NetBSD__) -static PyObject * -PyCurses_KeyName(PyObject *self, PyObject *args) -{ - const char *knp; - int ch; - - PyCursesInitialised + static PyObject * + PyCurses_KeyName(PyObject *self, PyObject *args) + { + const char *knp; + int ch; + + PyCursesInitialised + + if (!PyArg_ParseTuple(args,"i",&ch)) return NULL; + + if (ch < 0) { + PyErr_SetString(PyExc_ValueError, "invalid key number"); + return NULL; + } + knp = keyname(ch); + + return PyString_FromString((knp == NULL) ? "" : (char *)knp); + } +#endif + + static PyObject * + PyCurses_KillChar(PyObject *self) + { + char ch; + + ch = killchar(); + + return PyString_FromStringAndSize(&ch, 1); + } + + static PyObject * + PyCurses_Meta(PyObject *self, PyObject *args) + { + int ch; + + PyCursesInitialised + + switch(PyTuple_Size(args)) { + case 1: + if (!PyArg_ParseTuple(args,"i;True(1), False(0)",&ch)) return NULL; + break; + default: + PyErr_SetString(PyExc_TypeError, "meta requires 1 argument"); + return NULL; + } - if (!PyArg_ParseTuple(args,"i",&ch)) return NULL; - - if (ch < 0) { - PyErr_SetString(PyExc_ValueError, "invalid key number"); - return NULL; - } - knp = keyname(ch); - - return PyString_FromString((knp == NULL) ? "" : (char *)knp); -} -#endif - -static PyObject * -PyCurses_KillChar(PyObject *self) -{ - char ch; - - ch = killchar(); - - return PyString_FromStringAndSize(&ch, 1); -} - -static PyObject * -PyCurses_Meta(PyObject *self, PyObject *args) -{ - int ch; - - PyCursesInitialised - - switch(PyTuple_Size(args)) { - case 1: - if (!PyArg_ParseTuple(args,"i;True(1), False(0)",&ch)) return NULL; - break; - default: - PyErr_SetString(PyExc_TypeError, "meta requires 1 argument"); - return NULL; - } - - return PyCursesCheckERR(meta(stdscr, ch), "meta"); -} + return PyCursesCheckERR(meta(stdscr, ch), "meta"); + } #ifdef NCURSES_MOUSE_VERSION -static PyObject * -PyCurses_MouseInterval(PyObject *self, PyObject *args) -{ - int interval; - PyCursesInitialised - - if (!PyArg_ParseTuple(args,"i;interval",&interval)) - return NULL; - return PyCursesCheckERR(mouseinterval(interval), "mouseinterval"); -} - -static PyObject * -PyCurses_MouseMask(PyObject *self, PyObject *args) -{ - int newmask; - mmask_t oldmask, availmask; - - PyCursesInitialised - if (!PyArg_ParseTuple(args,"i;mousemask",&newmask)) - return NULL; - availmask = mousemask(newmask, &oldmask); - return Py_BuildValue("(ll)", (long)availmask, (long)oldmask); -} -#endif - -static PyObject * -PyCurses_Napms(PyObject *self, PyObject *args) -{ - int ms; - - PyCursesInitialised - if (!PyArg_ParseTuple(args, "i;ms", &ms)) return NULL; - - return Py_BuildValue("i", napms(ms)); -} - - -static PyObject * -PyCurses_NewPad(PyObject *self, PyObject *args) -{ - WINDOW *win; - int nlines, ncols; - - PyCursesInitialised - - if (!PyArg_ParseTuple(args,"ii;nlines,ncols",&nlines,&ncols)) return NULL; - - win = newpad(nlines, ncols); - - if (win == NULL) { - PyErr_SetString(PyCursesError, catchall_NULL); - return NULL; - } - - return (PyObject *)PyCursesWindow_New(win); -} - -static PyObject * -PyCurses_NewWindow(PyObject *self, PyObject *args) -{ - WINDOW *win; - int nlines, ncols, begin_y=0, begin_x=0; - - PyCursesInitialised - - switch (PyTuple_Size(args)) { - case 2: - if (!PyArg_ParseTuple(args,"ii;nlines,ncols",&nlines,&ncols)) - return NULL; - break; - case 4: - if (!PyArg_ParseTuple(args, "iiii;nlines,ncols,begin_y,begin_x", - &nlines,&ncols,&begin_y,&begin_x)) - return NULL; - break; - default: - PyErr_SetString(PyExc_TypeError, "newwin requires 2 or 4 arguments"); - return NULL; - } - - win = newwin(nlines,ncols,begin_y,begin_x); - if (win == NULL) { - PyErr_SetString(PyCursesError, catchall_NULL); - return NULL; - } - - return (PyObject *)PyCursesWindow_New(win); -} - -static PyObject * -PyCurses_Pair_Content(PyObject *self, PyObject *args) -{ - short pair,f,b; - - PyCursesInitialised - PyCursesInitialisedColor - - switch(PyTuple_Size(args)) { - case 1: - if (!PyArg_ParseTuple(args, "h;pair", &pair)) return NULL; - break; - default: - PyErr_SetString(PyExc_TypeError, "pair_content requires 1 argument"); - return NULL; - } - - if (pair_content(pair, &f, &b)==ERR) { - PyErr_SetString(PyCursesError, - "Argument 1 was out of range. (1..COLOR_PAIRS-1)"); - return NULL; - } - - return Py_BuildValue("(ii)", f, b); -} - -static PyObject * -PyCurses_pair_number(PyObject *self, PyObject *args) -{ - int n; - - PyCursesInitialised - PyCursesInitialisedColor - - switch(PyTuple_Size(args)) { - case 1: - if (!PyArg_ParseTuple(args, "i;pairvalue", &n)) return NULL; - break; - default: - PyErr_SetString(PyExc_TypeError, - "pair_number requires 1 argument"); - return NULL; - } - - return PyInt_FromLong((long) ((n & A_COLOR) >> 8)); -} - -static PyObject * -PyCurses_Putp(PyObject *self, PyObject *args) -{ - char *str; - - if (!PyArg_ParseTuple(args,"s;str", &str)) return NULL; - return PyCursesCheckERR(putp(str), "putp"); -} - -static PyObject * -PyCurses_QiFlush(PyObject *self, PyObject *args) -{ - int flag = 0; - - PyCursesInitialised - - switch(PyTuple_Size(args)) { - case 0: - qiflush(); - Py_INCREF(Py_None); - return Py_None; - case 1: - if (!PyArg_ParseTuple(args, "i;True(1) or False(0)", &flag)) return NULL; - if (flag) qiflush(); - else noqiflush(); - Py_INCREF(Py_None); - return Py_None; - default: - PyErr_SetString(PyExc_TypeError, "qiflush requires 0 or 1 arguments"); - return NULL; - } -} + static PyObject * + PyCurses_MouseInterval(PyObject *self, PyObject *args) + { + int interval; + PyCursesInitialised + + if (!PyArg_ParseTuple(args,"i;interval",&interval)) + return NULL; + return PyCursesCheckERR(mouseinterval(interval), "mouseinterval"); + } + + static PyObject * + PyCurses_MouseMask(PyObject *self, PyObject *args) + { + int newmask; + mmask_t oldmask, availmask; + + PyCursesInitialised + if (!PyArg_ParseTuple(args,"i;mousemask",&newmask)) + return NULL; + availmask = mousemask(newmask, &oldmask); + return Py_BuildValue("(ll)", (long)availmask, (long)oldmask); + } +#endif + + static PyObject * + PyCurses_Napms(PyObject *self, PyObject *args) + { + int ms; + + PyCursesInitialised + if (!PyArg_ParseTuple(args, "i;ms", &ms)) return NULL; + + return Py_BuildValue("i", napms(ms)); + } + + + static PyObject * + PyCurses_NewPad(PyObject *self, PyObject *args) + { + WINDOW *win; + int nlines, ncols; + + PyCursesInitialised + + if (!PyArg_ParseTuple(args,"ii;nlines,ncols",&nlines,&ncols)) return NULL; + + win = newpad(nlines, ncols); + + if (win == NULL) { + PyErr_SetString(PyCursesError, catchall_NULL); + return NULL; + } + + return (PyObject *)PyCursesWindow_New(win); + } + + static PyObject * + PyCurses_NewWindow(PyObject *self, PyObject *args) + { + WINDOW *win; + int nlines, ncols, begin_y=0, begin_x=0; + + PyCursesInitialised + + switch (PyTuple_Size(args)) { + case 2: + if (!PyArg_ParseTuple(args,"ii;nlines,ncols",&nlines,&ncols)) + return NULL; + break; + case 4: + if (!PyArg_ParseTuple(args, "iiii;nlines,ncols,begin_y,begin_x", + &nlines,&ncols,&begin_y,&begin_x)) + return NULL; + break; + default: + PyErr_SetString(PyExc_TypeError, "newwin requires 2 or 4 arguments"); + return NULL; + } + + win = newwin(nlines,ncols,begin_y,begin_x); + if (win == NULL) { + PyErr_SetString(PyCursesError, catchall_NULL); + return NULL; + } + + return (PyObject *)PyCursesWindow_New(win); + } + + static PyObject * + PyCurses_Pair_Content(PyObject *self, PyObject *args) + { + short pair,f,b; + + PyCursesInitialised + PyCursesInitialisedColor + + switch(PyTuple_Size(args)) { + case 1: + if (!PyArg_ParseTuple(args, "h;pair", &pair)) return NULL; + break; + default: + PyErr_SetString(PyExc_TypeError, "pair_content requires 1 argument"); + return NULL; + } + + if (pair_content(pair, &f, &b)==ERR) { + PyErr_SetString(PyCursesError, + "Argument 1 was out of range. (1..COLOR_PAIRS-1)"); + return NULL; + } + + return Py_BuildValue("(ii)", f, b); + } + + static PyObject * + PyCurses_pair_number(PyObject *self, PyObject *args) + { + int n; + + PyCursesInitialised + PyCursesInitialisedColor + + switch(PyTuple_Size(args)) { + case 1: + if (!PyArg_ParseTuple(args, "i;pairvalue", &n)) return NULL; + break; + default: + PyErr_SetString(PyExc_TypeError, + "pair_number requires 1 argument"); + return NULL; + } + + return PyInt_FromLong((long) ((n & A_COLOR) >> 8)); + } + + static PyObject * + PyCurses_Putp(PyObject *self, PyObject *args) + { + char *str; + + if (!PyArg_ParseTuple(args,"s;str", &str)) return NULL; + return PyCursesCheckERR(putp(str), "putp"); + } + + static PyObject * + PyCurses_QiFlush(PyObject *self, PyObject *args) + { + int flag = 0; + + PyCursesInitialised + + switch(PyTuple_Size(args)) { + case 0: + qiflush(); + Py_INCREF(Py_None); + return Py_None; + case 1: + if (!PyArg_ParseTuple(args, "i;True(1) or False(0)", &flag)) return NULL; + if (flag) qiflush(); + else noqiflush(); + Py_INCREF(Py_None); + return Py_None; + default: + PyErr_SetString(PyExc_TypeError, "qiflush requires 0 or 1 arguments"); + return NULL; + } + } /* Internal helper used for updating curses.LINES, curses.COLS, _curses.LINES * and _curses.COLS */ #if defined(HAVE_CURSES_RESIZETERM) || defined(HAVE_CURSES_RESIZE_TERM) -static int -update_lines_cols(void) -{ - PyObject *o; - PyObject *m = PyImport_ImportModuleNoBlock("curses"); - - if (!m) - return 0; - - o = PyInt_FromLong(LINES); - if (!o) { - Py_DECREF(m); - return 0; - } - if (PyObject_SetAttrString(m, "LINES", o)) { - Py_DECREF(m); - Py_DECREF(o); - return 0; - } - if (PyDict_SetItemString(ModDict, "LINES", o)) { - Py_DECREF(m); - Py_DECREF(o); - return 0; - } - Py_DECREF(o); - o = PyInt_FromLong(COLS); - if (!o) { - Py_DECREF(m); - return 0; - } - if (PyObject_SetAttrString(m, "COLS", o)) { - Py_DECREF(m); - Py_DECREF(o); - return 0; - } - if (PyDict_SetItemString(ModDict, "COLS", o)) { - Py_DECREF(m); - Py_DECREF(o); - return 0; - } - Py_DECREF(o); - Py_DECREF(m); - return 1; -} + static int + update_lines_cols(void) + { + PyObject *o; + PyObject *m = PyImport_ImportModuleNoBlock("curses"); + + if (!m) + return 0; + + o = PyInt_FromLong(LINES); + if (!o) { + Py_DECREF(m); + return 0; + } + if (PyObject_SetAttrString(m, "LINES", o)) { + Py_DECREF(m); + Py_DECREF(o); + return 0; + } + if (PyDict_SetItemString(ModDict, "LINES", o)) { + Py_DECREF(m); + Py_DECREF(o); + return 0; + } + Py_DECREF(o); + o = PyInt_FromLong(COLS); + if (!o) { + Py_DECREF(m); + return 0; + } + if (PyObject_SetAttrString(m, "COLS", o)) { + Py_DECREF(m); + Py_DECREF(o); + return 0; + } + if (PyDict_SetItemString(ModDict, "COLS", o)) { + Py_DECREF(m); + Py_DECREF(o); + return 0; + } + Py_DECREF(o); + Py_DECREF(m); + return 1; + } #endif #ifdef HAVE_CURSES_RESIZETERM -static PyObject * -PyCurses_ResizeTerm(PyObject *self, PyObject *args) -{ - int lines; - int columns; - PyObject *result; - - PyCursesInitialised - - if (!PyArg_ParseTuple(args,"ii:resizeterm", &lines, &columns)) - return NULL; - - result = PyCursesCheckERR(resizeterm(lines, columns), "resizeterm"); - if (!result) - return NULL; - if (!update_lines_cols()) - return NULL; - return result; -} + static PyObject * + PyCurses_ResizeTerm(PyObject *self, PyObject *args) + { + int lines; + int columns; + PyObject *result; + + PyCursesInitialised + + if (!PyArg_ParseTuple(args,"ii:resizeterm", &lines, &columns)) + return NULL; + + result = PyCursesCheckERR(resizeterm(lines, columns), "resizeterm"); + if (!result) + return NULL; + if (!update_lines_cols()) + return NULL; + return result; + } #endif #ifdef HAVE_CURSES_RESIZE_TERM -static PyObject * -PyCurses_Resize_Term(PyObject *self, PyObject *args) -{ - int lines; - int columns; - - PyObject *result; - - PyCursesInitialised - - if (!PyArg_ParseTuple(args,"ii:resize_term", &lines, &columns)) - return NULL; - - result = PyCursesCheckERR(resize_term(lines, columns), "resize_term"); - if (!result) - return NULL; - if (!update_lines_cols()) - return NULL; - return result; -} + static PyObject * + PyCurses_Resize_Term(PyObject *self, PyObject *args) + { + int lines; + int columns; + + PyObject *result; + + PyCursesInitialised + + if (!PyArg_ParseTuple(args,"ii:resize_term", &lines, &columns)) + return NULL; + + result = PyCursesCheckERR(resize_term(lines, columns), "resize_term"); + if (!result) + return NULL; + if (!update_lines_cols()) + return NULL; + return result; + } #endif /* HAVE_CURSES_RESIZE_TERM */ -static PyObject * -PyCurses_setsyx(PyObject *self, PyObject *args) -{ - int y,x; - - PyCursesInitialised - - if (PyTuple_Size(args)!=2) { - PyErr_SetString(PyExc_TypeError, "setsyx requires 2 arguments"); - return NULL; - } - - if (!PyArg_ParseTuple(args, "ii;y, x", &y, &x)) return NULL; - - setsyx(y,x); - - Py_INCREF(Py_None); - return Py_None; -} - -static PyObject * -PyCurses_Start_Color(PyObject *self) -{ - int code; - PyObject *c, *cp; - - PyCursesInitialised - - code = start_color(); - if (code != ERR) { - initialisedcolors = TRUE; - c = PyInt_FromLong((long) COLORS); - PyDict_SetItemString(ModDict, "COLORS", c); - Py_DECREF(c); - cp = PyInt_FromLong((long) COLOR_PAIRS); - PyDict_SetItemString(ModDict, "COLOR_PAIRS", cp); - Py_DECREF(cp); - Py_INCREF(Py_None); - return Py_None; - } else { - PyErr_SetString(PyCursesError, "start_color() returned ERR"); - return NULL; - } -} - -static PyObject * -PyCurses_tigetflag(PyObject *self, PyObject *args) -{ - char *capname; - - PyCursesSetupTermCalled; - - if (!PyArg_ParseTuple(args, "s", &capname)) - return NULL; - - return PyInt_FromLong( (long) tigetflag( capname ) ); -} - -static PyObject * -PyCurses_tigetnum(PyObject *self, PyObject *args) -{ - char *capname; - - PyCursesSetupTermCalled; - - if (!PyArg_ParseTuple(args, "s", &capname)) - return NULL; - - return PyInt_FromLong( (long) tigetnum( capname ) ); -} - -static PyObject * -PyCurses_tigetstr(PyObject *self, PyObject *args) -{ - char *capname; - - PyCursesSetupTermCalled; - - if (!PyArg_ParseTuple(args, "s", &capname)) - return NULL; - - capname = tigetstr( capname ); - if (capname == 0 || capname == (char*) -1) { - Py_INCREF(Py_None); - return Py_None; - } - return PyString_FromString( capname ); -} - -static PyObject * -PyCurses_tparm(PyObject *self, PyObject *args) -{ - char* fmt; - char* result = NULL; - int i1=0,i2=0,i3=0,i4=0,i5=0,i6=0,i7=0,i8=0,i9=0; - - PyCursesSetupTermCalled; - - if (!PyArg_ParseTuple(args, "s|iiiiiiiii:tparm", - &fmt, &i1, &i2, &i3, &i4, - &i5, &i6, &i7, &i8, &i9)) { - return NULL; - } - - result = tparm(fmt,i1,i2,i3,i4,i5,i6,i7,i8,i9); - if (!result) { - PyErr_SetString(PyCursesError, "tparm() returned NULL"); - return NULL; - } - - return PyString_FromString(result); -} - -static PyObject * -PyCurses_TypeAhead(PyObject *self, PyObject *args) -{ - int fd; - - PyCursesInitialised - - if (!PyArg_ParseTuple(args,"i;fd",&fd)) return NULL; - - return PyCursesCheckERR(typeahead( fd ), "typeahead"); -} - -static PyObject * -PyCurses_UnCtrl(PyObject *self, PyObject *args) -{ - PyObject *temp; - chtype ch; - - PyCursesInitialised - - if (!PyArg_ParseTuple(args,"O;ch or int",&temp)) return NULL; - - if (PyInt_Check(temp)) - ch = (chtype) PyInt_AsLong(temp); - else if (PyString_Check(temp)) - ch = (chtype) *PyString_AsString(temp); - else { - PyErr_SetString(PyExc_TypeError, "argument must be a ch or an int"); - return NULL; - } - - return PyString_FromString(unctrl(ch)); -} - -static PyObject * -PyCurses_UngetCh(PyObject *self, PyObject *args) -{ - PyObject *temp; - int ch; - - PyCursesInitialised - - if (!PyArg_ParseTuple(args,"O;ch or int",&temp)) return NULL; - - if (PyInt_Check(temp)) - ch = (int) PyInt_AsLong(temp); - else if (PyString_Check(temp)) - ch = (int) *PyString_AsString(temp); - else { - PyErr_SetString(PyExc_TypeError, "argument must be a ch or an int"); - return NULL; - } - - return PyCursesCheckERR(ungetch(ch), "ungetch"); -} - -static PyObject * -PyCurses_Use_Env(PyObject *self, PyObject *args) -{ - int flag; - - switch(PyTuple_Size(args)) { - case 1: - if (!PyArg_ParseTuple(args,"i;True(1), False(0)",&flag)) - return NULL; - break; - default: - PyErr_SetString(PyExc_TypeError, "use_env requires 1 argument"); - return NULL; - } - use_env(flag); - Py_INCREF(Py_None); - return Py_None; -} + static PyObject * + PyCurses_setsyx(PyObject *self, PyObject *args) + { + int y,x; + + PyCursesInitialised + + if (PyTuple_Size(args)!=2) { + PyErr_SetString(PyExc_TypeError, "setsyx requires 2 arguments"); + return NULL; + } + + if (!PyArg_ParseTuple(args, "ii;y, x", &y, &x)) return NULL; + + setsyx(y,x); + + Py_INCREF(Py_None); + return Py_None; + } + + static PyObject * + PyCurses_Start_Color(PyObject *self) + { + int code; + PyObject *c, *cp; + + PyCursesInitialised + + code = start_color(); + if (code != ERR) { + initialisedcolors = TRUE; + c = PyInt_FromLong((long) COLORS); + PyDict_SetItemString(ModDict, "COLORS", c); + Py_DECREF(c); + cp = PyInt_FromLong((long) COLOR_PAIRS); + PyDict_SetItemString(ModDict, "COLOR_PAIRS", cp); + Py_DECREF(cp); + Py_INCREF(Py_None); + return Py_None; + } else { + PyErr_SetString(PyCursesError, "start_color() returned ERR"); + return NULL; + } + } + + static PyObject * + PyCurses_tigetflag(PyObject *self, PyObject *args) + { + char *capname; + + PyCursesSetupTermCalled; + + if (!PyArg_ParseTuple(args, "s", &capname)) + return NULL; + + return PyInt_FromLong( (long) tigetflag( capname ) ); + } + + static PyObject * + PyCurses_tigetnum(PyObject *self, PyObject *args) + { + char *capname; + + PyCursesSetupTermCalled; + + if (!PyArg_ParseTuple(args, "s", &capname)) + return NULL; + + return PyInt_FromLong( (long) tigetnum( capname ) ); + } + + static PyObject * + PyCurses_tigetstr(PyObject *self, PyObject *args) + { + char *capname; + + PyCursesSetupTermCalled; + + if (!PyArg_ParseTuple(args, "s", &capname)) + return NULL; + + capname = tigetstr( capname ); + if (capname == 0 || capname == (char*) -1) { + Py_INCREF(Py_None); + return Py_None; + } + return PyString_FromString( capname ); + } + + static PyObject * + PyCurses_tparm(PyObject *self, PyObject *args) + { + char* fmt; + char* result = NULL; + int i1=0,i2=0,i3=0,i4=0,i5=0,i6=0,i7=0,i8=0,i9=0; + + PyCursesSetupTermCalled; + + if (!PyArg_ParseTuple(args, "s|iiiiiiiii:tparm", + &fmt, &i1, &i2, &i3, &i4, + &i5, &i6, &i7, &i8, &i9)) { + return NULL; + } + + result = tparm(fmt,i1,i2,i3,i4,i5,i6,i7,i8,i9); + if (!result) { + PyErr_SetString(PyCursesError, "tparm() returned NULL"); + return NULL; + } + + return PyString_FromString(result); + } + + static PyObject * + PyCurses_TypeAhead(PyObject *self, PyObject *args) + { + int fd; + + PyCursesInitialised + + if (!PyArg_ParseTuple(args,"i;fd",&fd)) return NULL; + + return PyCursesCheckERR(typeahead( fd ), "typeahead"); + } + + static PyObject * + PyCurses_UnCtrl(PyObject *self, PyObject *args) + { + PyObject *temp; + chtype ch; + + PyCursesInitialised + + if (!PyArg_ParseTuple(args,"O;ch or int",&temp)) return NULL; + + if (PyInt_Check(temp)) + ch = (chtype) PyInt_AsLong(temp); + else if (PyString_Check(temp)) + ch = (chtype) *PyString_AsString(temp); + else { + PyErr_SetString(PyExc_TypeError, "argument must be a ch or an int"); + return NULL; + } + + return PyString_FromString(unctrl(ch)); + } + + static PyObject * + PyCurses_UngetCh(PyObject *self, PyObject *args) + { + PyObject *temp; + int ch; + + PyCursesInitialised + + if (!PyArg_ParseTuple(args,"O;ch or int",&temp)) return NULL; + + if (PyInt_Check(temp)) + ch = (int) PyInt_AsLong(temp); + else if (PyString_Check(temp)) + ch = (int) *PyString_AsString(temp); + else { + PyErr_SetString(PyExc_TypeError, "argument must be a ch or an int"); + return NULL; + } + + return PyCursesCheckERR(ungetch(ch), "ungetch"); + } + + static PyObject * + PyCurses_Use_Env(PyObject *self, PyObject *args) + { + int flag; + + switch(PyTuple_Size(args)) { + case 1: + if (!PyArg_ParseTuple(args,"i;True(1), False(0)",&flag)) + return NULL; + break; + default: + PyErr_SetString(PyExc_TypeError, "use_env requires 1 argument"); + return NULL; + } + use_env(flag); + Py_INCREF(Py_None); + return Py_None; + } #ifndef STRICT_SYSV_CURSES -static PyObject * -PyCurses_Use_Default_Colors(PyObject *self) -{ - int code; - - PyCursesInitialised - PyCursesInitialisedColor - - code = use_default_colors(); - if (code != ERR) { - Py_INCREF(Py_None); - return Py_None; - } else { - PyErr_SetString(PyCursesError, "use_default_colors() returned ERR"); - return NULL; - } -} + static PyObject * + PyCurses_Use_Default_Colors(PyObject *self) + { + int code; + + PyCursesInitialised + PyCursesInitialisedColor + + code = use_default_colors(); + if (code != ERR) { + Py_INCREF(Py_None); + return Py_None; + } else { + PyErr_SetString(PyCursesError, "use_default_colors() returned ERR"); + return NULL; + } + } #endif /* STRICT_SYSV_CURSES */ /* List of functions defined in the module */ -static PyMethodDef PyCurses_methods[] = { - {"baudrate", (PyCFunction)PyCurses_baudrate, METH_NOARGS}, - {"beep", (PyCFunction)PyCurses_beep, METH_NOARGS}, - {"can_change_color", (PyCFunction)PyCurses_can_change_color, METH_NOARGS}, - {"cbreak", (PyCFunction)PyCurses_cbreak, METH_VARARGS}, - {"color_content", (PyCFunction)PyCurses_Color_Content, METH_VARARGS}, - {"color_pair", (PyCFunction)PyCurses_color_pair, METH_VARARGS}, - {"curs_set", (PyCFunction)PyCurses_Curs_Set, METH_VARARGS}, - {"def_prog_mode", (PyCFunction)PyCurses_def_prog_mode, METH_NOARGS}, - {"def_shell_mode", (PyCFunction)PyCurses_def_shell_mode, METH_NOARGS}, - {"delay_output", (PyCFunction)PyCurses_Delay_Output, METH_VARARGS}, - {"doupdate", (PyCFunction)PyCurses_doupdate, METH_NOARGS}, - {"echo", (PyCFunction)PyCurses_echo, METH_VARARGS}, - {"endwin", (PyCFunction)PyCurses_endwin, METH_NOARGS}, - {"erasechar", (PyCFunction)PyCurses_EraseChar, METH_NOARGS}, - {"filter", (PyCFunction)PyCurses_filter, METH_NOARGS}, - {"flash", (PyCFunction)PyCurses_flash, METH_NOARGS}, - {"flushinp", (PyCFunction)PyCurses_flushinp, METH_NOARGS}, + static PyMethodDef PyCurses_methods[] = { + {"baudrate", (PyCFunction)PyCurses_baudrate, METH_NOARGS}, + {"beep", (PyCFunction)PyCurses_beep, METH_NOARGS}, + {"can_change_color", (PyCFunction)PyCurses_can_change_color, METH_NOARGS}, + {"cbreak", (PyCFunction)PyCurses_cbreak, METH_VARARGS}, + {"color_content", (PyCFunction)PyCurses_Color_Content, METH_VARARGS}, + {"color_pair", (PyCFunction)PyCurses_color_pair, METH_VARARGS}, + {"curs_set", (PyCFunction)PyCurses_Curs_Set, METH_VARARGS}, + {"def_prog_mode", (PyCFunction)PyCurses_def_prog_mode, METH_NOARGS}, + {"def_shell_mode", (PyCFunction)PyCurses_def_shell_mode, METH_NOARGS}, + {"delay_output", (PyCFunction)PyCurses_Delay_Output, METH_VARARGS}, + {"doupdate", (PyCFunction)PyCurses_doupdate, METH_NOARGS}, + {"echo", (PyCFunction)PyCurses_echo, METH_VARARGS}, + {"endwin", (PyCFunction)PyCurses_endwin, METH_NOARGS}, + {"erasechar", (PyCFunction)PyCurses_EraseChar, METH_NOARGS}, + {"filter", (PyCFunction)PyCurses_filter, METH_NOARGS}, + {"flash", (PyCFunction)PyCurses_flash, METH_NOARGS}, + {"flushinp", (PyCFunction)PyCurses_flushinp, METH_NOARGS}, #ifdef NCURSES_MOUSE_VERSION - {"getmouse", (PyCFunction)PyCurses_GetMouse, METH_NOARGS}, - {"ungetmouse", (PyCFunction)PyCurses_UngetMouse, METH_VARARGS}, + {"getmouse", (PyCFunction)PyCurses_GetMouse, METH_NOARGS}, + {"ungetmouse", (PyCFunction)PyCurses_UngetMouse, METH_VARARGS}, #endif - {"getsyx", (PyCFunction)PyCurses_getsyx, METH_NOARGS}, - {"getwin", (PyCFunction)PyCurses_GetWin, METH_O}, - {"has_colors", (PyCFunction)PyCurses_has_colors, METH_NOARGS}, - {"has_ic", (PyCFunction)PyCurses_has_ic, METH_NOARGS}, - {"has_il", (PyCFunction)PyCurses_has_il, METH_NOARGS}, + {"getsyx", (PyCFunction)PyCurses_getsyx, METH_NOARGS}, + {"getwin", (PyCFunction)PyCurses_GetWin, METH_O}, + {"has_colors", (PyCFunction)PyCurses_has_colors, METH_NOARGS}, + {"has_ic", (PyCFunction)PyCurses_has_ic, METH_NOARGS}, + {"has_il", (PyCFunction)PyCurses_has_il, METH_NOARGS}, #ifndef STRICT_SYSV_CURSES - {"has_key", (PyCFunction)PyCurses_has_key, METH_VARARGS}, + {"has_key", (PyCFunction)PyCurses_has_key, METH_VARARGS}, #endif - {"halfdelay", (PyCFunction)PyCurses_HalfDelay, METH_VARARGS}, - {"init_color", (PyCFunction)PyCurses_Init_Color, METH_VARARGS}, - {"init_pair", (PyCFunction)PyCurses_Init_Pair, METH_VARARGS}, - {"initscr", (PyCFunction)PyCurses_InitScr, METH_NOARGS}, - {"intrflush", (PyCFunction)PyCurses_IntrFlush, METH_VARARGS}, - {"isendwin", (PyCFunction)PyCurses_isendwin, METH_NOARGS}, + {"halfdelay", (PyCFunction)PyCurses_HalfDelay, METH_VARARGS}, + {"init_color", (PyCFunction)PyCurses_Init_Color, METH_VARARGS}, + {"init_pair", (PyCFunction)PyCurses_Init_Pair, METH_VARARGS}, + {"initscr", (PyCFunction)PyCurses_InitScr, METH_NOARGS}, + {"intrflush", (PyCFunction)PyCurses_IntrFlush, METH_VARARGS}, + {"isendwin", (PyCFunction)PyCurses_isendwin, METH_NOARGS}, #ifdef HAVE_CURSES_IS_TERM_RESIZED - {"is_term_resized", (PyCFunction)PyCurses_Is_Term_Resized, METH_VARARGS}, + {"is_term_resized", (PyCFunction)PyCurses_Is_Term_Resized, METH_VARARGS}, #endif #if !defined(__NetBSD__) - {"keyname", (PyCFunction)PyCurses_KeyName, METH_VARARGS}, + {"keyname", (PyCFunction)PyCurses_KeyName, METH_VARARGS}, #endif - {"killchar", (PyCFunction)PyCurses_KillChar, METH_NOARGS}, - {"longname", (PyCFunction)PyCurses_longname, METH_NOARGS}, - {"meta", (PyCFunction)PyCurses_Meta, METH_VARARGS}, + {"killchar", (PyCFunction)PyCurses_KillChar, METH_NOARGS}, + {"longname", (PyCFunction)PyCurses_longname, METH_NOARGS}, + {"meta", (PyCFunction)PyCurses_Meta, METH_VARARGS}, #ifdef NCURSES_MOUSE_VERSION - {"mouseinterval", (PyCFunction)PyCurses_MouseInterval, METH_VARARGS}, - {"mousemask", (PyCFunction)PyCurses_MouseMask, METH_VARARGS}, + {"mouseinterval", (PyCFunction)PyCurses_MouseInterval, METH_VARARGS}, + {"mousemask", (PyCFunction)PyCurses_MouseMask, METH_VARARGS}, #endif - {"napms", (PyCFunction)PyCurses_Napms, METH_VARARGS}, - {"newpad", (PyCFunction)PyCurses_NewPad, METH_VARARGS}, - {"newwin", (PyCFunction)PyCurses_NewWindow, METH_VARARGS}, - {"nl", (PyCFunction)PyCurses_nl, METH_VARARGS}, - {"nocbreak", (PyCFunction)PyCurses_nocbreak, METH_NOARGS}, - {"noecho", (PyCFunction)PyCurses_noecho, METH_NOARGS}, - {"nonl", (PyCFunction)PyCurses_nonl, METH_NOARGS}, - {"noqiflush", (PyCFunction)PyCurses_noqiflush, METH_NOARGS}, - {"noraw", (PyCFunction)PyCurses_noraw, METH_NOARGS}, - {"pair_content", (PyCFunction)PyCurses_Pair_Content, METH_VARARGS}, - {"pair_number", (PyCFunction)PyCurses_pair_number, METH_VARARGS}, - {"putp", (PyCFunction)PyCurses_Putp, METH_VARARGS}, - {"qiflush", (PyCFunction)PyCurses_QiFlush, METH_VARARGS}, - {"raw", (PyCFunction)PyCurses_raw, METH_VARARGS}, - {"reset_prog_mode", (PyCFunction)PyCurses_reset_prog_mode, METH_NOARGS}, - {"reset_shell_mode", (PyCFunction)PyCurses_reset_shell_mode, METH_NOARGS}, - {"resetty", (PyCFunction)PyCurses_resetty, METH_NOARGS}, + {"napms", (PyCFunction)PyCurses_Napms, METH_VARARGS}, + {"newpad", (PyCFunction)PyCurses_NewPad, METH_VARARGS}, + {"newwin", (PyCFunction)PyCurses_NewWindow, METH_VARARGS}, + {"nl", (PyCFunction)PyCurses_nl, METH_VARARGS}, + {"nocbreak", (PyCFunction)PyCurses_nocbreak, METH_NOARGS}, + {"noecho", (PyCFunction)PyCurses_noecho, METH_NOARGS}, + {"nonl", (PyCFunction)PyCurses_nonl, METH_NOARGS}, + {"noqiflush", (PyCFunction)PyCurses_noqiflush, METH_NOARGS}, + {"noraw", (PyCFunction)PyCurses_noraw, METH_NOARGS}, + {"pair_content", (PyCFunction)PyCurses_Pair_Content, METH_VARARGS}, + {"pair_number", (PyCFunction)PyCurses_pair_number, METH_VARARGS}, + {"putp", (PyCFunction)PyCurses_Putp, METH_VARARGS}, + {"qiflush", (PyCFunction)PyCurses_QiFlush, METH_VARARGS}, + {"raw", (PyCFunction)PyCurses_raw, METH_VARARGS}, + {"reset_prog_mode", (PyCFunction)PyCurses_reset_prog_mode, METH_NOARGS}, + {"reset_shell_mode", (PyCFunction)PyCurses_reset_shell_mode, METH_NOARGS}, + {"resetty", (PyCFunction)PyCurses_resetty, METH_NOARGS}, #ifdef HAVE_CURSES_RESIZETERM - {"resizeterm", (PyCFunction)PyCurses_ResizeTerm, METH_VARARGS}, + {"resizeterm", (PyCFunction)PyCurses_ResizeTerm, METH_VARARGS}, #endif #ifdef HAVE_CURSES_RESIZE_TERM - {"resize_term", (PyCFunction)PyCurses_Resize_Term, METH_VARARGS}, + {"resize_term", (PyCFunction)PyCurses_Resize_Term, METH_VARARGS}, #endif - {"savetty", (PyCFunction)PyCurses_savetty, METH_NOARGS}, - {"setsyx", (PyCFunction)PyCurses_setsyx, METH_VARARGS}, - {"setupterm", (PyCFunction)PyCurses_setupterm, - METH_VARARGS|METH_KEYWORDS}, - {"start_color", (PyCFunction)PyCurses_Start_Color, METH_NOARGS}, - {"termattrs", (PyCFunction)PyCurses_termattrs, METH_NOARGS}, - {"termname", (PyCFunction)PyCurses_termname, METH_NOARGS}, - {"tigetflag", (PyCFunction)PyCurses_tigetflag, METH_VARARGS}, - {"tigetnum", (PyCFunction)PyCurses_tigetnum, METH_VARARGS}, - {"tigetstr", (PyCFunction)PyCurses_tigetstr, METH_VARARGS}, - {"tparm", (PyCFunction)PyCurses_tparm, METH_VARARGS}, - {"typeahead", (PyCFunction)PyCurses_TypeAhead, METH_VARARGS}, - {"unctrl", (PyCFunction)PyCurses_UnCtrl, METH_VARARGS}, - {"ungetch", (PyCFunction)PyCurses_UngetCh, METH_VARARGS}, - {"use_env", (PyCFunction)PyCurses_Use_Env, METH_VARARGS}, + {"savetty", (PyCFunction)PyCurses_savetty, METH_NOARGS}, + {"setsyx", (PyCFunction)PyCurses_setsyx, METH_VARARGS}, + {"setupterm", (PyCFunction)PyCurses_setupterm, + METH_VARARGS|METH_KEYWORDS}, + {"start_color", (PyCFunction)PyCurses_Start_Color, METH_NOARGS}, + {"termattrs", (PyCFunction)PyCurses_termattrs, METH_NOARGS}, + {"termname", (PyCFunction)PyCurses_termname, METH_NOARGS}, + {"tigetflag", (PyCFunction)PyCurses_tigetflag, METH_VARARGS}, + {"tigetnum", (PyCFunction)PyCurses_tigetnum, METH_VARARGS}, + {"tigetstr", (PyCFunction)PyCurses_tigetstr, METH_VARARGS}, + {"tparm", (PyCFunction)PyCurses_tparm, METH_VARARGS}, + {"typeahead", (PyCFunction)PyCurses_TypeAhead, METH_VARARGS}, + {"unctrl", (PyCFunction)PyCurses_UnCtrl, METH_VARARGS}, + {"ungetch", (PyCFunction)PyCurses_UngetCh, METH_VARARGS}, + {"use_env", (PyCFunction)PyCurses_Use_Env, METH_VARARGS}, #ifndef STRICT_SYSV_CURSES - {"use_default_colors", (PyCFunction)PyCurses_Use_Default_Colors, METH_NOARGS}, + {"use_default_colors", (PyCFunction)PyCurses_Use_Default_Colors, METH_NOARGS}, #endif - {NULL, NULL} /* sentinel */ -}; + {NULL, NULL} /* sentinel */ + }; /* Initialization function for the module */ -PyMODINIT_FUNC -init_curses(void) -{ - PyObject *m, *d, *v, *c_api_object; - static void *PyCurses_API[PyCurses_API_pointers]; - - /* Initialize object type */ - Py_TYPE(&PyCursesWindow_Type) = &PyType_Type; - - /* Initialize the C API pointer array */ - PyCurses_API[0] = (void *)&PyCursesWindow_Type; - PyCurses_API[1] = (void *)func_PyCursesSetupTermCalled; - PyCurses_API[2] = (void *)func_PyCursesInitialised; - PyCurses_API[3] = (void *)func_PyCursesInitialisedColor; - - /* Create the module and add the functions */ - m = Py_InitModule("_curses", PyCurses_methods); - if (m == NULL) - return; - - /* Add some symbolic constants to the module */ - d = PyModule_GetDict(m); - if (d == NULL) - return; - ModDict = d; /* For PyCurses_InitScr to use later */ - - /* Add a CObject for the C API */ - c_api_object = PyCObject_FromVoidPtr((void *)PyCurses_API, NULL); - PyDict_SetItemString(d, "_C_API", c_api_object); - Py_DECREF(c_api_object); - - /* For exception curses.error */ - PyCursesError = PyErr_NewException("_curses.error", NULL, NULL); - PyDict_SetItemString(d, "error", PyCursesError); - - /* Make the version available */ - v = PyString_FromString(PyCursesVersion); - PyDict_SetItemString(d, "version", v); - PyDict_SetItemString(d, "__version__", v); - Py_DECREF(v); - - SetDictInt("ERR", ERR); - SetDictInt("OK", OK); - - /* Here are some attributes you can add to chars to print */ - - SetDictInt("A_ATTRIBUTES", A_ATTRIBUTES); - SetDictInt("A_NORMAL", A_NORMAL); - SetDictInt("A_STANDOUT", A_STANDOUT); - SetDictInt("A_UNDERLINE", A_UNDERLINE); - SetDictInt("A_REVERSE", A_REVERSE); - SetDictInt("A_BLINK", A_BLINK); - SetDictInt("A_DIM", A_DIM); - SetDictInt("A_BOLD", A_BOLD); - SetDictInt("A_ALTCHARSET", A_ALTCHARSET); + PyMODINIT_FUNC + init_curses(void) + { + PyObject *m, *d, *v, *c_api_object; + static void *PyCurses_API[PyCurses_API_pointers]; + + /* Initialize object type */ + Py_TYPE(&PyCursesWindow_Type) = &PyType_Type; + + /* Initialize the C API pointer array */ + PyCurses_API[0] = (void *)&PyCursesWindow_Type; + PyCurses_API[1] = (void *)func_PyCursesSetupTermCalled; + PyCurses_API[2] = (void *)func_PyCursesInitialised; + PyCurses_API[3] = (void *)func_PyCursesInitialisedColor; + + /* Create the module and add the functions */ + m = Py_InitModule("_curses", PyCurses_methods); + if (m == NULL) + return; + + /* Add some symbolic constants to the module */ + d = PyModule_GetDict(m); + if (d == NULL) + return; + ModDict = d; /* For PyCurses_InitScr to use later */ + + /* Add a CObject for the C API */ + c_api_object = PyCObject_FromVoidPtr((void *)PyCurses_API, NULL); + PyDict_SetItemString(d, "_C_API", c_api_object); + Py_DECREF(c_api_object); + + /* For exception curses.error */ + PyCursesError = PyErr_NewException("_curses.error", NULL, NULL); + PyDict_SetItemString(d, "error", PyCursesError); + + /* Make the version available */ + v = PyString_FromString(PyCursesVersion); + PyDict_SetItemString(d, "version", v); + PyDict_SetItemString(d, "__version__", v); + Py_DECREF(v); + + SetDictInt("ERR", ERR); + SetDictInt("OK", OK); + + /* Here are some attributes you can add to chars to print */ + + SetDictInt("A_ATTRIBUTES", A_ATTRIBUTES); + SetDictInt("A_NORMAL", A_NORMAL); + SetDictInt("A_STANDOUT", A_STANDOUT); + SetDictInt("A_UNDERLINE", A_UNDERLINE); + SetDictInt("A_REVERSE", A_REVERSE); + SetDictInt("A_BLINK", A_BLINK); + SetDictInt("A_DIM", A_DIM); + SetDictInt("A_BOLD", A_BOLD); + SetDictInt("A_ALTCHARSET", A_ALTCHARSET); #if !defined(__NetBSD__) - SetDictInt("A_INVIS", A_INVIS); + SetDictInt("A_INVIS", A_INVIS); #endif - SetDictInt("A_PROTECT", A_PROTECT); - SetDictInt("A_CHARTEXT", A_CHARTEXT); - SetDictInt("A_COLOR", A_COLOR); + SetDictInt("A_PROTECT", A_PROTECT); + SetDictInt("A_CHARTEXT", A_CHARTEXT); + SetDictInt("A_COLOR", A_COLOR); - /* The following are never available with strict SYSV curses */ + /* The following are never available with strict SYSV curses */ #ifdef A_HORIZONTAL - SetDictInt("A_HORIZONTAL", A_HORIZONTAL); + SetDictInt("A_HORIZONTAL", A_HORIZONTAL); #endif #ifdef A_LEFT - SetDictInt("A_LEFT", A_LEFT); + SetDictInt("A_LEFT", A_LEFT); #endif #ifdef A_LOW - SetDictInt("A_LOW", A_LOW); + SetDictInt("A_LOW", A_LOW); #endif #ifdef A_RIGHT - SetDictInt("A_RIGHT", A_RIGHT); + SetDictInt("A_RIGHT", A_RIGHT); #endif #ifdef A_TOP - SetDictInt("A_TOP", A_TOP); + SetDictInt("A_TOP", A_TOP); #endif #ifdef A_VERTICAL - SetDictInt("A_VERTICAL", A_VERTICAL); + SetDictInt("A_VERTICAL", A_VERTICAL); #endif - SetDictInt("COLOR_BLACK", COLOR_BLACK); - SetDictInt("COLOR_RED", COLOR_RED); - SetDictInt("COLOR_GREEN", COLOR_GREEN); - SetDictInt("COLOR_YELLOW", COLOR_YELLOW); - SetDictInt("COLOR_BLUE", COLOR_BLUE); - SetDictInt("COLOR_MAGENTA", COLOR_MAGENTA); - SetDictInt("COLOR_CYAN", COLOR_CYAN); - SetDictInt("COLOR_WHITE", COLOR_WHITE); + SetDictInt("COLOR_BLACK", COLOR_BLACK); + SetDictInt("COLOR_RED", COLOR_RED); + SetDictInt("COLOR_GREEN", COLOR_GREEN); + SetDictInt("COLOR_YELLOW", COLOR_YELLOW); + SetDictInt("COLOR_BLUE", COLOR_BLUE); + SetDictInt("COLOR_MAGENTA", COLOR_MAGENTA); + SetDictInt("COLOR_CYAN", COLOR_CYAN); + SetDictInt("COLOR_WHITE", COLOR_WHITE); #ifdef NCURSES_MOUSE_VERSION - /* Mouse-related constants */ - SetDictInt("BUTTON1_PRESSED", BUTTON1_PRESSED); - SetDictInt("BUTTON1_RELEASED", BUTTON1_RELEASED); - SetDictInt("BUTTON1_CLICKED", BUTTON1_CLICKED); - SetDictInt("BUTTON1_DOUBLE_CLICKED", BUTTON1_DOUBLE_CLICKED); - SetDictInt("BUTTON1_TRIPLE_CLICKED", BUTTON1_TRIPLE_CLICKED); - - SetDictInt("BUTTON2_PRESSED", BUTTON2_PRESSED); - SetDictInt("BUTTON2_RELEASED", BUTTON2_RELEASED); - SetDictInt("BUTTON2_CLICKED", BUTTON2_CLICKED); - SetDictInt("BUTTON2_DOUBLE_CLICKED", BUTTON2_DOUBLE_CLICKED); - SetDictInt("BUTTON2_TRIPLE_CLICKED", BUTTON2_TRIPLE_CLICKED); - - SetDictInt("BUTTON3_PRESSED", BUTTON3_PRESSED); - SetDictInt("BUTTON3_RELEASED", BUTTON3_RELEASED); - SetDictInt("BUTTON3_CLICKED", BUTTON3_CLICKED); - SetDictInt("BUTTON3_DOUBLE_CLICKED", BUTTON3_DOUBLE_CLICKED); - SetDictInt("BUTTON3_TRIPLE_CLICKED", BUTTON3_TRIPLE_CLICKED); - - SetDictInt("BUTTON4_PRESSED", BUTTON4_PRESSED); - SetDictInt("BUTTON4_RELEASED", BUTTON4_RELEASED); - SetDictInt("BUTTON4_CLICKED", BUTTON4_CLICKED); - SetDictInt("BUTTON4_DOUBLE_CLICKED", BUTTON4_DOUBLE_CLICKED); - SetDictInt("BUTTON4_TRIPLE_CLICKED", BUTTON4_TRIPLE_CLICKED); - - SetDictInt("BUTTON_SHIFT", BUTTON_SHIFT); - SetDictInt("BUTTON_CTRL", BUTTON_CTRL); - SetDictInt("BUTTON_ALT", BUTTON_ALT); - - SetDictInt("ALL_MOUSE_EVENTS", ALL_MOUSE_EVENTS); - SetDictInt("REPORT_MOUSE_POSITION", REPORT_MOUSE_POSITION); -#endif - /* Now set everything up for KEY_ variables */ - { - int key; - char *key_n; - char *key_n2; + /* Mouse-related constants */ + SetDictInt("BUTTON1_PRESSED", BUTTON1_PRESSED); + SetDictInt("BUTTON1_RELEASED", BUTTON1_RELEASED); + SetDictInt("BUTTON1_CLICKED", BUTTON1_CLICKED); + SetDictInt("BUTTON1_DOUBLE_CLICKED", BUTTON1_DOUBLE_CLICKED); + SetDictInt("BUTTON1_TRIPLE_CLICKED", BUTTON1_TRIPLE_CLICKED); + + SetDictInt("BUTTON2_PRESSED", BUTTON2_PRESSED); + SetDictInt("BUTTON2_RELEASED", BUTTON2_RELEASED); + SetDictInt("BUTTON2_CLICKED", BUTTON2_CLICKED); + SetDictInt("BUTTON2_DOUBLE_CLICKED", BUTTON2_DOUBLE_CLICKED); + SetDictInt("BUTTON2_TRIPLE_CLICKED", BUTTON2_TRIPLE_CLICKED); + + SetDictInt("BUTTON3_PRESSED", BUTTON3_PRESSED); + SetDictInt("BUTTON3_RELEASED", BUTTON3_RELEASED); + SetDictInt("BUTTON3_CLICKED", BUTTON3_CLICKED); + SetDictInt("BUTTON3_DOUBLE_CLICKED", BUTTON3_DOUBLE_CLICKED); + SetDictInt("BUTTON3_TRIPLE_CLICKED", BUTTON3_TRIPLE_CLICKED); + + SetDictInt("BUTTON4_PRESSED", BUTTON4_PRESSED); + SetDictInt("BUTTON4_RELEASED", BUTTON4_RELEASED); + SetDictInt("BUTTON4_CLICKED", BUTTON4_CLICKED); + SetDictInt("BUTTON4_DOUBLE_CLICKED", BUTTON4_DOUBLE_CLICKED); + SetDictInt("BUTTON4_TRIPLE_CLICKED", BUTTON4_TRIPLE_CLICKED); + + SetDictInt("BUTTON_SHIFT", BUTTON_SHIFT); + SetDictInt("BUTTON_CTRL", BUTTON_CTRL); + SetDictInt("BUTTON_ALT", BUTTON_ALT); + + SetDictInt("ALL_MOUSE_EVENTS", ALL_MOUSE_EVENTS); + SetDictInt("REPORT_MOUSE_POSITION", REPORT_MOUSE_POSITION); +#endif + /* Now set everything up for KEY_ variables */ + { + int key; + char *key_n; + char *key_n2; #if !defined(__NetBSD__) - for (key=KEY_MIN;key < KEY_MAX; key++) { - key_n = (char *)keyname(key); - if (key_n == NULL || strcmp(key_n,"UNKNOWN KEY")==0) - continue; - if (strncmp(key_n,"KEY_F(",6)==0) { - char *p1, *p2; - key_n2 = malloc(strlen(key_n)+1); - if (!key_n2) { - PyErr_NoMemory(); - break; - } - p1 = key_n; - p2 = key_n2; - while (*p1) { - if (*p1 != '(' && *p1 != ')') { - *p2 = *p1; - p2++; - } - p1++; - } - *p2 = (char)0; - } else - key_n2 = key_n; - SetDictInt(key_n2,key); - if (key_n2 != key_n) - free(key_n2); - } -#endif - SetDictInt("KEY_MIN", KEY_MIN); - SetDictInt("KEY_MAX", KEY_MAX); - } -} + for (key=KEY_MIN;key < KEY_MAX; key++) { + key_n = (char *)keyname(key); + if (key_n == NULL || strcmp(key_n,"UNKNOWN KEY")==0) + continue; + if (strncmp(key_n,"KEY_F(",6)==0) { + char *p1, *p2; + key_n2 = malloc(strlen(key_n)+1); + if (!key_n2) { + PyErr_NoMemory(); + break; + } + p1 = key_n; + p2 = key_n2; + while (*p1) { + if (*p1 != '(' && *p1 != ')') { + *p2 = *p1; + p2++; + } + p1++; + } + *p2 = (char)0; + } else + key_n2 = key_n; + SetDictInt(key_n2,key); + if (key_n2 != key_n) + free(key_n2); + } +#endif + SetDictInt("KEY_MIN", KEY_MIN); + SetDictInt("KEY_MAX", KEY_MAX); + } + } From python-checkins at python.org Sun May 16 00:30:54 2010 From: python-checkins at python.org (victor.stinner) Date: Sun, 16 May 2010 00:30:54 +0200 (CEST) Subject: [Python-checkins] r81217 - in python/branches/release31-maint: Modules/_cursesmodule.c Message-ID: <20100515223054.3B796EE993@mail.python.org> Author: victor.stinner Date: Sun May 16 00:30:53 2010 New Revision: 81217 Log: Recorded merge of revisions 81215 via svnmerge from svn+ssh://pythondev at svn.python.org/python/branches/py3k ................ r81215 | victor.stinner | 2010-05-16 00:23:53 +0200 (dim., 16 mai 2010) | 12 lines Recorded merge of revisions 81213 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r81213 | victor.stinner | 2010-05-16 00:19:27 +0200 (dim., 16 mai 2010) | 5 lines reindent _cursesmodule.c Use untabify.py + emacs (python3 mode) + manual editions for Py_BEGIN_ALLOW_THREADS / Py_END_ALLOW_THREADS ........ ................ Modified: python/branches/release31-maint/ (props changed) python/branches/release31-maint/Modules/_cursesmodule.c Modified: python/branches/release31-maint/Modules/_cursesmodule.c ============================================================================== --- python/branches/release31-maint/Modules/_cursesmodule.c (original) +++ python/branches/release31-maint/Modules/_cursesmodule.c Sun May 16 00:30:53 2010 @@ -35,66 +35,66 @@ /* -A number of SysV or ncurses functions don't have wrappers yet; if you -need a given function, add it and send a patch. See -http://www.python.org/dev/patches/ for instructions on how to submit -patches to Python. - -Here's a list of currently unsupported functions: - - addchnstr addchstr color_set define_key - del_curterm delscreen dupwin inchnstr inchstr innstr keyok - mcprint mvaddchnstr mvaddchstr mvcur mvinchnstr - mvinchstr mvinnstr mmvwaddchnstr mvwaddchstr - mvwinchnstr mvwinchstr mvwinnstr newterm - restartterm ripoffline scr_dump - scr_init scr_restore scr_set scrl set_curterm set_term setterm - tgetent tgetflag tgetnum tgetstr tgoto timeout tputs - vidattr vidputs waddchnstr waddchstr - wcolor_set winchnstr winchstr winnstr wmouse_trafo wscrl - -Low-priority: - slk_attr slk_attr_off slk_attr_on slk_attr_set slk_attroff - slk_attron slk_attrset slk_clear slk_color slk_init slk_label - slk_noutrefresh slk_refresh slk_restore slk_set slk_touch - -Menu extension (ncurses and probably SYSV): - current_item free_item free_menu item_count item_description - item_index item_init item_name item_opts item_opts_off - item_opts_on item_term item_userptr item_value item_visible - menu_back menu_driver menu_fore menu_format menu_grey - menu_init menu_items menu_mark menu_opts menu_opts_off - menu_opts_on menu_pad menu_pattern menu_request_by_name - menu_request_name menu_spacing menu_sub menu_term menu_userptr - menu_win new_item new_menu pos_menu_cursor post_menu - scale_menu set_current_item set_item_init set_item_opts - set_item_term set_item_userptr set_item_value set_menu_back - set_menu_fore set_menu_format set_menu_grey set_menu_init - set_menu_items set_menu_mark set_menu_opts set_menu_pad - set_menu_pattern set_menu_spacing set_menu_sub set_menu_term - set_menu_userptr set_menu_win set_top_row top_row unpost_menu - -Form extension (ncurses and probably SYSV): - current_field data_ahead data_behind dup_field - dynamic_fieldinfo field_arg field_back field_buffer - field_count field_fore field_index field_info field_init - field_just field_opts field_opts_off field_opts_on field_pad - field_status field_term field_type field_userptr form_driver - form_fields form_init form_opts form_opts_off form_opts_on - form_page form_request_by_name form_request_name form_sub - form_term form_userptr form_win free_field free_form - link_field link_fieldtype move_field new_field new_form - new_page pos_form_cursor post_form scale_form - set_current_field set_field_back set_field_buffer - set_field_fore set_field_init set_field_just set_field_opts - set_field_pad set_field_status set_field_term set_field_type - set_field_userptr set_fieldtype_arg set_fieldtype_choice - set_form_fields set_form_init set_form_opts set_form_page - set_form_sub set_form_term set_form_userptr set_form_win - set_max_field set_new_page unpost_form + A number of SysV or ncurses functions don't have wrappers yet; if you + need a given function, add it and send a patch. See + http://www.python.org/dev/patches/ for instructions on how to submit + patches to Python. + + Here's a list of currently unsupported functions: + + addchnstr addchstr color_set define_key + del_curterm delscreen dupwin inchnstr inchstr innstr keyok + mcprint mvaddchnstr mvaddchstr mvcur mvinchnstr + mvinchstr mvinnstr mmvwaddchnstr mvwaddchstr + mvwinchnstr mvwinchstr mvwinnstr newterm + restartterm ripoffline scr_dump + scr_init scr_restore scr_set scrl set_curterm set_term setterm + tgetent tgetflag tgetnum tgetstr tgoto timeout tputs + vidattr vidputs waddchnstr waddchstr + wcolor_set winchnstr winchstr winnstr wmouse_trafo wscrl + + Low-priority: + slk_attr slk_attr_off slk_attr_on slk_attr_set slk_attroff + slk_attron slk_attrset slk_clear slk_color slk_init slk_label + slk_noutrefresh slk_refresh slk_restore slk_set slk_touch + + Menu extension (ncurses and probably SYSV): + current_item free_item free_menu item_count item_description + item_index item_init item_name item_opts item_opts_off + item_opts_on item_term item_userptr item_value item_visible + menu_back menu_driver menu_fore menu_format menu_grey + menu_init menu_items menu_mark menu_opts menu_opts_off + menu_opts_on menu_pad menu_pattern menu_request_by_name + menu_request_name menu_spacing menu_sub menu_term menu_userptr + menu_win new_item new_menu pos_menu_cursor post_menu + scale_menu set_current_item set_item_init set_item_opts + set_item_term set_item_userptr set_item_value set_menu_back + set_menu_fore set_menu_format set_menu_grey set_menu_init + set_menu_items set_menu_mark set_menu_opts set_menu_pad + set_menu_pattern set_menu_spacing set_menu_sub set_menu_term + set_menu_userptr set_menu_win set_top_row top_row unpost_menu + + Form extension (ncurses and probably SYSV): + current_field data_ahead data_behind dup_field + dynamic_fieldinfo field_arg field_back field_buffer + field_count field_fore field_index field_info field_init + field_just field_opts field_opts_off field_opts_on field_pad + field_status field_term field_type field_userptr form_driver + form_fields form_init form_opts form_opts_off form_opts_on + form_page form_request_by_name form_request_name form_sub + form_term form_userptr form_win free_field free_form + link_field link_fieldtype move_field new_field new_form + new_page pos_form_cursor post_form scale_form + set_current_field set_field_back set_field_buffer + set_field_fore set_field_init set_field_just set_field_opts + set_field_pad set_field_status set_field_term set_field_type + set_field_userptr set_fieldtype_arg set_fieldtype_choice + set_form_fields set_form_init set_form_opts set_form_page + set_form_sub set_form_term set_form_userptr set_form_win + set_max_field set_new_page unpost_form - */ +*/ /* Release Number */ @@ -116,9 +116,9 @@ #define CURSES_MODULE #include "py_curses.h" -/* These prototypes are in , but including this header - #defines many common symbols (such as "lines") which breaks the - curses module in other ways. So the code will just specify +/* These prototypes are in , but including this header + #defines many common symbols (such as "lines") which breaks the + curses module in other ways. So the code will just specify explicit prototypes here. */ extern int setupterm(char *,int,int *); #ifdef __sgi @@ -148,23 +148,23 @@ static int initialisedcolors = FALSE; /* Utility Macros */ -#define PyCursesSetupTermCalled \ - if (initialised_setupterm != TRUE) { \ - PyErr_SetString(PyCursesError, \ - "must call (at least) setupterm() first"); \ - return 0; } - -#define PyCursesInitialised \ - if (initialised != TRUE) { \ - PyErr_SetString(PyCursesError, \ - "must call initscr() first"); \ - return 0; } - -#define PyCursesInitialisedColor \ - if (initialisedcolors != TRUE) { \ - PyErr_SetString(PyCursesError, \ - "must call start_color() first"); \ - return 0; } +#define PyCursesSetupTermCalled \ + if (initialised_setupterm != TRUE) { \ + PyErr_SetString(PyCursesError, \ + "must call (at least) setupterm() first"); \ + return 0; } + +#define PyCursesInitialised \ + if (initialised != TRUE) { \ + PyErr_SetString(PyCursesError, \ + "must call initscr() first"); \ + return 0; } + +#define PyCursesInitialisedColor \ + if (initialisedcolors != TRUE) { \ + PyErr_SetString(PyCursesError, \ + "must call start_color() first"); \ + return 0; } #ifndef MIN #define MIN(x,y) ((x) < (y) ? (x) : (y)) @@ -173,51 +173,51 @@ /* Utility Functions */ /* - * Check the return code from a curses function and return None + * Check the return code from a curses function and return None * or raise an exception as appropriate. These are exported using the - * capsule API. + * capsule API. */ static PyObject * PyCursesCheckERR(int code, char *fname) { - if (code != ERR) { - Py_INCREF(Py_None); - return Py_None; - } else { - if (fname == NULL) { - PyErr_SetString(PyCursesError, catchall_ERR); + if (code != ERR) { + Py_INCREF(Py_None); + return Py_None; } else { - PyErr_Format(PyCursesError, "%s() returned ERR", fname); + if (fname == NULL) { + PyErr_SetString(PyCursesError, catchall_ERR); + } else { + PyErr_Format(PyCursesError, "%s() returned ERR", fname); + } + return NULL; } - return NULL; - } } -static int +static int PyCurses_ConvertToChtype(PyObject *obj, chtype *ch) { - if (PyLong_CheckExact(obj)) { - int overflow; - /* XXX should the truncation by the cast also be reported - as an error? */ - *ch = (chtype) PyLong_AsLongAndOverflow(obj, &overflow); - if (overflow) - return 0; - } else if(PyBytes_Check(obj) - && (PyBytes_Size(obj) == 1)) { - *ch = (chtype) *PyBytes_AsString(obj); - } else if (PyUnicode_Check(obj) && PyUnicode_GetSize(obj) == 1) { - *ch = (chtype) *PyUnicode_AS_UNICODE(obj); - } else { - return 0; - } - return 1; + if (PyLong_CheckExact(obj)) { + int overflow; + /* XXX should the truncation by the cast also be reported + as an error? */ + *ch = (chtype) PyLong_AsLongAndOverflow(obj, &overflow); + if (overflow) + return 0; + } else if(PyBytes_Check(obj) + && (PyBytes_Size(obj) == 1)) { + *ch = (chtype) *PyBytes_AsString(obj); + } else if (PyUnicode_Check(obj) && PyUnicode_GetSize(obj) == 1) { + *ch = (chtype) *PyUnicode_AS_UNICODE(obj); + } else { + return 0; + } + return 1; } /* Function versions of the 3 functions for tested whether curses has been initialised or not. */ - + static int func_PyCursesSetupTermCalled(void) { PyCursesSetupTermCalled; @@ -250,49 +250,49 @@ TYPE - parameter Type ERGSTR - format string for construction of the return value PARSESTR - format string for argument parsing - */ +*/ -#define Window_NoArgNoReturnFunction(X) \ -static PyObject *PyCursesWindow_ ## X (PyCursesWindowObject *self, PyObject *args) \ -{ return PyCursesCheckERR(X(self->win), # X); } - -#define Window_NoArgTrueFalseFunction(X) \ -static PyObject * PyCursesWindow_ ## X (PyCursesWindowObject *self) \ -{ \ - if (X (self->win) == FALSE) { Py_INCREF(Py_False); return Py_False; } \ - else { Py_INCREF(Py_True); return Py_True; } } - -#define Window_NoArgNoReturnVoidFunction(X) \ -static PyObject * PyCursesWindow_ ## X (PyCursesWindowObject *self) \ -{ \ - X(self->win); Py_INCREF(Py_None); return Py_None; } - -#define Window_NoArg2TupleReturnFunction(X, TYPE, ERGSTR) \ -static PyObject * PyCursesWindow_ ## X (PyCursesWindowObject *self) \ -{ \ - TYPE arg1, arg2; \ - X(self->win,arg1,arg2); return Py_BuildValue(ERGSTR, arg1, arg2); } - -#define Window_OneArgNoReturnVoidFunction(X, TYPE, PARSESTR) \ -static PyObject * PyCursesWindow_ ## X (PyCursesWindowObject *self, PyObject *args) \ -{ \ - TYPE arg1; \ - if (!PyArg_ParseTuple(args, PARSESTR, &arg1)) return NULL; \ - X(self->win,arg1); Py_INCREF(Py_None); return Py_None; } - -#define Window_OneArgNoReturnFunction(X, TYPE, PARSESTR) \ -static PyObject * PyCursesWindow_ ## X (PyCursesWindowObject *self, PyObject *args) \ -{ \ - TYPE arg1; \ - if (!PyArg_ParseTuple(args,PARSESTR, &arg1)) return NULL; \ - return PyCursesCheckERR(X(self->win, arg1), # X); } - -#define Window_TwoArgNoReturnFunction(X, TYPE, PARSESTR) \ -static PyObject * PyCursesWindow_ ## X (PyCursesWindowObject *self, PyObject *args) \ -{ \ - TYPE arg1, arg2; \ - if (!PyArg_ParseTuple(args,PARSESTR, &arg1, &arg2)) return NULL; \ - return PyCursesCheckERR(X(self->win, arg1, arg2), # X); } +#define Window_NoArgNoReturnFunction(X) \ + static PyObject *PyCursesWindow_ ## X (PyCursesWindowObject *self, PyObject *args) \ + { return PyCursesCheckERR(X(self->win), # X); } + +#define Window_NoArgTrueFalseFunction(X) \ + static PyObject * PyCursesWindow_ ## X (PyCursesWindowObject *self) \ + { \ + if (X (self->win) == FALSE) { Py_INCREF(Py_False); return Py_False; } \ + else { Py_INCREF(Py_True); return Py_True; } } + +#define Window_NoArgNoReturnVoidFunction(X) \ + static PyObject * PyCursesWindow_ ## X (PyCursesWindowObject *self) \ + { \ + X(self->win); Py_INCREF(Py_None); return Py_None; } + +#define Window_NoArg2TupleReturnFunction(X, TYPE, ERGSTR) \ + static PyObject * PyCursesWindow_ ## X (PyCursesWindowObject *self) \ + { \ + TYPE arg1, arg2; \ + X(self->win,arg1,arg2); return Py_BuildValue(ERGSTR, arg1, arg2); } + +#define Window_OneArgNoReturnVoidFunction(X, TYPE, PARSESTR) \ + static PyObject * PyCursesWindow_ ## X (PyCursesWindowObject *self, PyObject *args) \ + { \ + TYPE arg1; \ + if (!PyArg_ParseTuple(args, PARSESTR, &arg1)) return NULL; \ + X(self->win,arg1); Py_INCREF(Py_None); return Py_None; } + +#define Window_OneArgNoReturnFunction(X, TYPE, PARSESTR) \ + static PyObject * PyCursesWindow_ ## X (PyCursesWindowObject *self, PyObject *args) \ + { \ + TYPE arg1; \ + if (!PyArg_ParseTuple(args,PARSESTR, &arg1)) return NULL; \ + return PyCursesCheckERR(X(self->win, arg1), # X); } + +#define Window_TwoArgNoReturnFunction(X, TYPE, PARSESTR) \ + static PyObject * PyCursesWindow_ ## X (PyCursesWindowObject *self, PyObject *args) \ + { \ + TYPE arg1, arg2; \ + if (!PyArg_ParseTuple(args,PARSESTR, &arg1, &arg2)) return NULL; \ + return PyCursesCheckERR(X(self->win, arg1, arg2), # X); } /* ------------- WINDOW routines --------------- */ @@ -353,19 +353,19 @@ static PyObject * PyCursesWindow_New(WINDOW *win) { - PyCursesWindowObject *wo; + PyCursesWindowObject *wo; - wo = PyObject_NEW(PyCursesWindowObject, &PyCursesWindow_Type); - if (wo == NULL) return NULL; - wo->win = win; - return (PyObject *)wo; + wo = PyObject_NEW(PyCursesWindowObject, &PyCursesWindow_Type); + if (wo == NULL) return NULL; + wo->win = win; + return (PyObject *)wo; } static void PyCursesWindow_Dealloc(PyCursesWindowObject *wo) { - if (wo->win != stdscr) delwin(wo->win); - PyObject_DEL(wo); + if (wo->win != stdscr) delwin(wo->win); + PyObject_DEL(wo); } /* Addch, Addstr, Addnstr */ @@ -373,287 +373,287 @@ static PyObject * PyCursesWindow_AddCh(PyCursesWindowObject *self, PyObject *args) { - int rtn, x, y, use_xy = FALSE; - PyObject *temp; - chtype ch = 0; - attr_t attr = A_NORMAL; - long lattr; - - switch (PyTuple_Size(args)) { - case 1: - if (!PyArg_ParseTuple(args, "O;ch or int", &temp)) - return NULL; - break; - case 2: - if (!PyArg_ParseTuple(args, "Ol;ch or int,attr", &temp, &lattr)) - return NULL; - attr = lattr; - break; - case 3: - if (!PyArg_ParseTuple(args,"iiO;y,x,ch or int", &y, &x, &temp)) - return NULL; - use_xy = TRUE; - break; - case 4: - if (!PyArg_ParseTuple(args,"iiOl;y,x,ch or int, attr", - &y, &x, &temp, &lattr)) - return NULL; - attr = lattr; - use_xy = TRUE; - break; - default: - PyErr_SetString(PyExc_TypeError, "addch requires 1 to 4 arguments"); - return NULL; - } - - if (!PyCurses_ConvertToChtype(temp, &ch)) { - PyErr_SetString(PyExc_TypeError, "argument 1 or 3 must be a ch or an int"); - return NULL; - } - - if (use_xy == TRUE) - rtn = mvwaddch(self->win,y,x, ch | attr); - else { - rtn = waddch(self->win, ch | attr); - } - return PyCursesCheckERR(rtn, "addch"); + int rtn, x, y, use_xy = FALSE; + PyObject *temp; + chtype ch = 0; + attr_t attr = A_NORMAL; + long lattr; + + switch (PyTuple_Size(args)) { + case 1: + if (!PyArg_ParseTuple(args, "O;ch or int", &temp)) + return NULL; + break; + case 2: + if (!PyArg_ParseTuple(args, "Ol;ch or int,attr", &temp, &lattr)) + return NULL; + attr = lattr; + break; + case 3: + if (!PyArg_ParseTuple(args,"iiO;y,x,ch or int", &y, &x, &temp)) + return NULL; + use_xy = TRUE; + break; + case 4: + if (!PyArg_ParseTuple(args,"iiOl;y,x,ch or int, attr", + &y, &x, &temp, &lattr)) + return NULL; + attr = lattr; + use_xy = TRUE; + break; + default: + PyErr_SetString(PyExc_TypeError, "addch requires 1 to 4 arguments"); + return NULL; + } + + if (!PyCurses_ConvertToChtype(temp, &ch)) { + PyErr_SetString(PyExc_TypeError, "argument 1 or 3 must be a ch or an int"); + return NULL; + } + + if (use_xy == TRUE) + rtn = mvwaddch(self->win,y,x, ch | attr); + else { + rtn = waddch(self->win, ch | attr); + } + return PyCursesCheckERR(rtn, "addch"); } static PyObject * PyCursesWindow_AddStr(PyCursesWindowObject *self, PyObject *args) { - int rtn; - int x, y; - char *str; - attr_t attr = A_NORMAL , attr_old = A_NORMAL; - long lattr; - int use_xy = FALSE, use_attr = FALSE; - - switch (PyTuple_Size(args)) { - case 1: - if (!PyArg_ParseTuple(args,"s;str", &str)) - return NULL; - break; - case 2: - if (!PyArg_ParseTuple(args,"sl;str,attr", &str, &lattr)) - return NULL; - attr = lattr; - use_attr = TRUE; - break; - case 3: - if (!PyArg_ParseTuple(args,"iis;int,int,str", &y, &x, &str)) - return NULL; - use_xy = TRUE; - break; - case 4: - if (!PyArg_ParseTuple(args,"iisl;int,int,str,attr", &y, &x, &str, &lattr)) - return NULL; - attr = lattr; - use_xy = use_attr = TRUE; - break; - default: - PyErr_SetString(PyExc_TypeError, "addstr requires 1 to 4 arguments"); - return NULL; - } - - if (use_attr == TRUE) { - attr_old = getattrs(self->win); - (void)wattrset(self->win,attr); - } - if (use_xy == TRUE) - rtn = mvwaddstr(self->win,y,x,str); - else - rtn = waddstr(self->win,str); - if (use_attr == TRUE) - (void)wattrset(self->win,attr_old); - return PyCursesCheckERR(rtn, "addstr"); + int rtn; + int x, y; + char *str; + attr_t attr = A_NORMAL , attr_old = A_NORMAL; + long lattr; + int use_xy = FALSE, use_attr = FALSE; + + switch (PyTuple_Size(args)) { + case 1: + if (!PyArg_ParseTuple(args,"s;str", &str)) + return NULL; + break; + case 2: + if (!PyArg_ParseTuple(args,"sl;str,attr", &str, &lattr)) + return NULL; + attr = lattr; + use_attr = TRUE; + break; + case 3: + if (!PyArg_ParseTuple(args,"iis;int,int,str", &y, &x, &str)) + return NULL; + use_xy = TRUE; + break; + case 4: + if (!PyArg_ParseTuple(args,"iisl;int,int,str,attr", &y, &x, &str, &lattr)) + return NULL; + attr = lattr; + use_xy = use_attr = TRUE; + break; + default: + PyErr_SetString(PyExc_TypeError, "addstr requires 1 to 4 arguments"); + return NULL; + } + + if (use_attr == TRUE) { + attr_old = getattrs(self->win); + (void)wattrset(self->win,attr); + } + if (use_xy == TRUE) + rtn = mvwaddstr(self->win,y,x,str); + else + rtn = waddstr(self->win,str); + if (use_attr == TRUE) + (void)wattrset(self->win,attr_old); + return PyCursesCheckERR(rtn, "addstr"); } static PyObject * PyCursesWindow_AddNStr(PyCursesWindowObject *self, PyObject *args) { - int rtn, x, y, n; - char *str; - attr_t attr = A_NORMAL , attr_old = A_NORMAL; - long lattr; - int use_xy = FALSE, use_attr = FALSE; - - switch (PyTuple_Size(args)) { - case 2: - if (!PyArg_ParseTuple(args,"si;str,n", &str, &n)) - return NULL; - break; - case 3: - if (!PyArg_ParseTuple(args,"sil;str,n,attr", &str, &n, &lattr)) - return NULL; - attr = lattr; - use_attr = TRUE; - break; - case 4: - if (!PyArg_ParseTuple(args,"iisi;y,x,str,n", &y, &x, &str, &n)) - return NULL; - use_xy = TRUE; - break; - case 5: - if (!PyArg_ParseTuple(args,"iisil;y,x,str,n,attr", &y, &x, &str, &n, &lattr)) - return NULL; - attr = lattr; - use_xy = use_attr = TRUE; - break; - default: - PyErr_SetString(PyExc_TypeError, "addnstr requires 2 to 5 arguments"); - return NULL; - } - - if (use_attr == TRUE) { - attr_old = getattrs(self->win); - (void)wattrset(self->win,attr); - } - if (use_xy == TRUE) - rtn = mvwaddnstr(self->win,y,x,str,n); - else - rtn = waddnstr(self->win,str,n); - if (use_attr == TRUE) - (void)wattrset(self->win,attr_old); - return PyCursesCheckERR(rtn, "addnstr"); + int rtn, x, y, n; + char *str; + attr_t attr = A_NORMAL , attr_old = A_NORMAL; + long lattr; + int use_xy = FALSE, use_attr = FALSE; + + switch (PyTuple_Size(args)) { + case 2: + if (!PyArg_ParseTuple(args,"si;str,n", &str, &n)) + return NULL; + break; + case 3: + if (!PyArg_ParseTuple(args,"sil;str,n,attr", &str, &n, &lattr)) + return NULL; + attr = lattr; + use_attr = TRUE; + break; + case 4: + if (!PyArg_ParseTuple(args,"iisi;y,x,str,n", &y, &x, &str, &n)) + return NULL; + use_xy = TRUE; + break; + case 5: + if (!PyArg_ParseTuple(args,"iisil;y,x,str,n,attr", &y, &x, &str, &n, &lattr)) + return NULL; + attr = lattr; + use_xy = use_attr = TRUE; + break; + default: + PyErr_SetString(PyExc_TypeError, "addnstr requires 2 to 5 arguments"); + return NULL; + } + + if (use_attr == TRUE) { + attr_old = getattrs(self->win); + (void)wattrset(self->win,attr); + } + if (use_xy == TRUE) + rtn = mvwaddnstr(self->win,y,x,str,n); + else + rtn = waddnstr(self->win,str,n); + if (use_attr == TRUE) + (void)wattrset(self->win,attr_old); + return PyCursesCheckERR(rtn, "addnstr"); } static PyObject * PyCursesWindow_Bkgd(PyCursesWindowObject *self, PyObject *args) { - PyObject *temp; - chtype bkgd; - attr_t attr = A_NORMAL; - long lattr; + PyObject *temp; + chtype bkgd; + attr_t attr = A_NORMAL; + long lattr; - switch (PyTuple_Size(args)) { + switch (PyTuple_Size(args)) { case 1: - if (!PyArg_ParseTuple(args, "O;ch or int", &temp)) - return NULL; - break; + if (!PyArg_ParseTuple(args, "O;ch or int", &temp)) + return NULL; + break; case 2: - if (!PyArg_ParseTuple(args,"Ol;ch or int,attr", &temp, &lattr)) - return NULL; - attr = lattr; - break; + if (!PyArg_ParseTuple(args,"Ol;ch or int,attr", &temp, &lattr)) + return NULL; + attr = lattr; + break; default: - PyErr_SetString(PyExc_TypeError, "bkgd requires 1 or 2 arguments"); - return NULL; - } - - if (!PyCurses_ConvertToChtype(temp, &bkgd)) { - PyErr_SetString(PyExc_TypeError, "argument 1 or 3 must be a ch or an int"); - return NULL; - } + PyErr_SetString(PyExc_TypeError, "bkgd requires 1 or 2 arguments"); + return NULL; + } + + if (!PyCurses_ConvertToChtype(temp, &bkgd)) { + PyErr_SetString(PyExc_TypeError, "argument 1 or 3 must be a ch or an int"); + return NULL; + } - return PyCursesCheckERR(wbkgd(self->win, bkgd | attr), "bkgd"); + return PyCursesCheckERR(wbkgd(self->win, bkgd | attr), "bkgd"); } static PyObject * PyCursesWindow_AttrOff(PyCursesWindowObject *self, PyObject *args) { - long lattr; - if (!PyArg_ParseTuple(args,"l;attr", &lattr)) - return NULL; - return PyCursesCheckERR(wattroff(self->win, (attr_t)lattr), "attroff"); + long lattr; + if (!PyArg_ParseTuple(args,"l;attr", &lattr)) + return NULL; + return PyCursesCheckERR(wattroff(self->win, (attr_t)lattr), "attroff"); } static PyObject * PyCursesWindow_AttrOn(PyCursesWindowObject *self, PyObject *args) { - long lattr; - if (!PyArg_ParseTuple(args,"l;attr", &lattr)) - return NULL; - return PyCursesCheckERR(wattron(self->win, (attr_t)lattr), "attron"); + long lattr; + if (!PyArg_ParseTuple(args,"l;attr", &lattr)) + return NULL; + return PyCursesCheckERR(wattron(self->win, (attr_t)lattr), "attron"); } static PyObject * PyCursesWindow_AttrSet(PyCursesWindowObject *self, PyObject *args) { - long lattr; - if (!PyArg_ParseTuple(args,"l;attr", &lattr)) - return NULL; - return PyCursesCheckERR(wattrset(self->win, (attr_t)lattr), "attrset"); + long lattr; + if (!PyArg_ParseTuple(args,"l;attr", &lattr)) + return NULL; + return PyCursesCheckERR(wattrset(self->win, (attr_t)lattr), "attrset"); } static PyObject * PyCursesWindow_BkgdSet(PyCursesWindowObject *self, PyObject *args) { - PyObject *temp; - chtype bkgd; - attr_t attr = A_NORMAL; - long lattr; + PyObject *temp; + chtype bkgd; + attr_t attr = A_NORMAL; + long lattr; - switch (PyTuple_Size(args)) { + switch (PyTuple_Size(args)) { case 1: - if (!PyArg_ParseTuple(args, "O;ch or int", &temp)) - return NULL; - break; + if (!PyArg_ParseTuple(args, "O;ch or int", &temp)) + return NULL; + break; case 2: - if (!PyArg_ParseTuple(args,"Ol;ch or int,attr", &temp, &lattr)) - return NULL; - attr = lattr; - break; + if (!PyArg_ParseTuple(args,"Ol;ch or int,attr", &temp, &lattr)) + return NULL; + attr = lattr; + break; default: - PyErr_SetString(PyExc_TypeError, "bkgdset requires 1 or 2 arguments"); - return NULL; - } - - if (!PyCurses_ConvertToChtype(temp, &bkgd)) { - PyErr_SetString(PyExc_TypeError, "argument 1 must be a ch or an int"); - return NULL; - } + PyErr_SetString(PyExc_TypeError, "bkgdset requires 1 or 2 arguments"); + return NULL; + } + + if (!PyCurses_ConvertToChtype(temp, &bkgd)) { + PyErr_SetString(PyExc_TypeError, "argument 1 must be a ch or an int"); + return NULL; + } - wbkgdset(self->win, bkgd | attr); - return PyCursesCheckERR(0, "bkgdset"); + wbkgdset(self->win, bkgd | attr); + return PyCursesCheckERR(0, "bkgdset"); } static PyObject * PyCursesWindow_Border(PyCursesWindowObject *self, PyObject *args) { - PyObject *temp[8]; - chtype ch[8]; - int i; - - /* Clear the array of parameters */ - for(i=0; i<8; i++) { - temp[i] = NULL; - ch[i] = 0; - } - - if (!PyArg_ParseTuple(args,"|OOOOOOOO;ls,rs,ts,bs,tl,tr,bl,br", - &temp[0], &temp[1], &temp[2], &temp[3], - &temp[4], &temp[5], &temp[6], &temp[7])) - return NULL; - - for(i=0; i<8; i++) { - if (temp[i] != NULL && !PyCurses_ConvertToChtype(temp[i], &ch[i])) { - PyErr_Format(PyExc_TypeError, - "argument %i must be a ch or an int", i+1); - return NULL; - } - } - - wborder(self->win, - ch[0], ch[1], ch[2], ch[3], - ch[4], ch[5], ch[6], ch[7]); - Py_INCREF(Py_None); - return Py_None; + PyObject *temp[8]; + chtype ch[8]; + int i; + + /* Clear the array of parameters */ + for(i=0; i<8; i++) { + temp[i] = NULL; + ch[i] = 0; + } + + if (!PyArg_ParseTuple(args,"|OOOOOOOO;ls,rs,ts,bs,tl,tr,bl,br", + &temp[0], &temp[1], &temp[2], &temp[3], + &temp[4], &temp[5], &temp[6], &temp[7])) + return NULL; + + for(i=0; i<8; i++) { + if (temp[i] != NULL && !PyCurses_ConvertToChtype(temp[i], &ch[i])) { + PyErr_Format(PyExc_TypeError, + "argument %i must be a ch or an int", i+1); + return NULL; + } + } + + wborder(self->win, + ch[0], ch[1], ch[2], ch[3], + ch[4], ch[5], ch[6], ch[7]); + Py_INCREF(Py_None); + return Py_None; } static PyObject * PyCursesWindow_Box(PyCursesWindowObject *self, PyObject *args) { - chtype ch1=0,ch2=0; - switch(PyTuple_Size(args)){ - case 0: break; - default: - if (!PyArg_ParseTuple(args,"ll;vertint,horint", &ch1, &ch2)) - return NULL; - } - box(self->win,ch1,ch2); - Py_INCREF(Py_None); - return Py_None; + chtype ch1=0,ch2=0; + switch(PyTuple_Size(args)){ + case 0: break; + default: + if (!PyArg_ParseTuple(args,"ll;vertint,horint", &ch1, &ch2)) + return NULL; + } + box(self->win,ch1,ch2); + Py_INCREF(Py_None); + return Py_None; } #if defined(HAVE_NCURSES_H) || defined(MVWDELCH_IS_EXPRESSION) @@ -661,10 +661,10 @@ #else int py_mvwdelch(WINDOW *w, int y, int x) { - mvwdelch(w,y,x); - /* On HP/UX, mvwdelch already returns. On other systems, - we may well run into this return statement. */ - return 0; + mvwdelch(w,y,x); + /* On HP/UX, mvwdelch already returns. On other systems, + we may well run into this return statement. */ + return 0; } #endif @@ -673,2297 +673,2297 @@ static PyObject * PyCursesWindow_ChgAt(PyCursesWindowObject *self, PyObject *args) { - int rtn; - int x, y; - int num = -1; - short color; - attr_t attr = A_NORMAL; - long lattr; - int use_xy = FALSE; + int rtn; + int x, y; + int num = -1; + short color; + attr_t attr = A_NORMAL; + long lattr; + int use_xy = FALSE; - switch (PyTuple_Size(args)) { - case 1: - if (!PyArg_ParseTuple(args,"l;attr", &lattr)) - return NULL; - attr = lattr; - break; - case 2: - if (!PyArg_ParseTuple(args,"il;n,attr", &num, &lattr)) - return NULL; - attr = lattr; - break; - case 3: - if (!PyArg_ParseTuple(args,"iil;int,int,attr", &y, &x, &lattr)) - return NULL; - attr = lattr; - use_xy = TRUE; - break; - case 4: - if (!PyArg_ParseTuple(args,"iiil;int,int,n,attr", &y, &x, &num, &lattr)) - return NULL; - attr = lattr; - use_xy = TRUE; - break; - default: - PyErr_SetString(PyExc_TypeError, "chgat requires 1 to 4 arguments"); - return NULL; - } - - color = (short)((attr >> 8) & 0xff); - attr = attr - (color << 8); - - if (use_xy == TRUE) { - rtn = mvwchgat(self->win,y,x,num,attr,color,NULL); - touchline(self->win,y,1); - } else { - getyx(self->win,y,x); - rtn = wchgat(self->win,num,attr,color,NULL); - touchline(self->win,y,1); - } - return PyCursesCheckERR(rtn, "chgat"); + switch (PyTuple_Size(args)) { + case 1: + if (!PyArg_ParseTuple(args,"l;attr", &lattr)) + return NULL; + attr = lattr; + break; + case 2: + if (!PyArg_ParseTuple(args,"il;n,attr", &num, &lattr)) + return NULL; + attr = lattr; + break; + case 3: + if (!PyArg_ParseTuple(args,"iil;int,int,attr", &y, &x, &lattr)) + return NULL; + attr = lattr; + use_xy = TRUE; + break; + case 4: + if (!PyArg_ParseTuple(args,"iiil;int,int,n,attr", &y, &x, &num, &lattr)) + return NULL; + attr = lattr; + use_xy = TRUE; + break; + default: + PyErr_SetString(PyExc_TypeError, "chgat requires 1 to 4 arguments"); + return NULL; + } + + color = (short)((attr >> 8) & 0xff); + attr = attr - (color << 8); + + if (use_xy == TRUE) { + rtn = mvwchgat(self->win,y,x,num,attr,color,NULL); + touchline(self->win,y,1); + } else { + getyx(self->win,y,x); + rtn = wchgat(self->win,num,attr,color,NULL); + touchline(self->win,y,1); + } + return PyCursesCheckERR(rtn, "chgat"); } static PyObject * PyCursesWindow_DelCh(PyCursesWindowObject *self, PyObject *args) { - int rtn; - int x, y; + int rtn; + int x, y; - switch (PyTuple_Size(args)) { - case 0: - rtn = wdelch(self->win); - break; - case 2: - if (!PyArg_ParseTuple(args,"ii;y,x", &y, &x)) - return NULL; - rtn = py_mvwdelch(self->win,y,x); - break; - default: - PyErr_SetString(PyExc_TypeError, "delch requires 0 or 2 arguments"); - return NULL; - } - return PyCursesCheckERR(rtn, "[mv]wdelch"); + switch (PyTuple_Size(args)) { + case 0: + rtn = wdelch(self->win); + break; + case 2: + if (!PyArg_ParseTuple(args,"ii;y,x", &y, &x)) + return NULL; + rtn = py_mvwdelch(self->win,y,x); + break; + default: + PyErr_SetString(PyExc_TypeError, "delch requires 0 or 2 arguments"); + return NULL; + } + return PyCursesCheckERR(rtn, "[mv]wdelch"); } static PyObject * PyCursesWindow_DerWin(PyCursesWindowObject *self, PyObject *args) { - WINDOW *win; - int nlines, ncols, begin_y, begin_x; + WINDOW *win; + int nlines, ncols, begin_y, begin_x; - nlines = 0; - ncols = 0; - switch (PyTuple_Size(args)) { - case 2: - if (!PyArg_ParseTuple(args,"ii;begin_y,begin_x",&begin_y,&begin_x)) - return NULL; - break; - case 4: - if (!PyArg_ParseTuple(args, "iiii;nlines,ncols,begin_y,begin_x", - &nlines,&ncols,&begin_y,&begin_x)) - return NULL; - break; - default: - PyErr_SetString(PyExc_TypeError, "derwin requires 2 or 4 arguments"); - return NULL; - } - - win = derwin(self->win,nlines,ncols,begin_y,begin_x); - - if (win == NULL) { - PyErr_SetString(PyCursesError, catchall_NULL); - return NULL; - } + nlines = 0; + ncols = 0; + switch (PyTuple_Size(args)) { + case 2: + if (!PyArg_ParseTuple(args,"ii;begin_y,begin_x",&begin_y,&begin_x)) + return NULL; + break; + case 4: + if (!PyArg_ParseTuple(args, "iiii;nlines,ncols,begin_y,begin_x", + &nlines,&ncols,&begin_y,&begin_x)) + return NULL; + break; + default: + PyErr_SetString(PyExc_TypeError, "derwin requires 2 or 4 arguments"); + return NULL; + } + + win = derwin(self->win,nlines,ncols,begin_y,begin_x); + + if (win == NULL) { + PyErr_SetString(PyCursesError, catchall_NULL); + return NULL; + } - return (PyObject *)PyCursesWindow_New(win); + return (PyObject *)PyCursesWindow_New(win); } static PyObject * PyCursesWindow_EchoChar(PyCursesWindowObject *self, PyObject *args) { - PyObject *temp; - chtype ch; - attr_t attr = A_NORMAL; - long lattr; - - switch (PyTuple_Size(args)) { - case 1: - if (!PyArg_ParseTuple(args,"O;ch or int", &temp)) - return NULL; - break; - case 2: - if (!PyArg_ParseTuple(args,"Ol;ch or int,attr", &temp, &lattr)) - return NULL; - attr = lattr; - break; - default: - PyErr_SetString(PyExc_TypeError, "echochar requires 1 or 2 arguments"); - - - return NULL; - } - - if (!PyCurses_ConvertToChtype(temp, &ch)) { - PyErr_SetString(PyExc_TypeError, "argument 1 must be a ch or an int"); - return NULL; - } - + PyObject *temp; + chtype ch; + attr_t attr = A_NORMAL; + long lattr; + + switch (PyTuple_Size(args)) { + case 1: + if (!PyArg_ParseTuple(args,"O;ch or int", &temp)) + return NULL; + break; + case 2: + if (!PyArg_ParseTuple(args,"Ol;ch or int,attr", &temp, &lattr)) + return NULL; + attr = lattr; + break; + default: + PyErr_SetString(PyExc_TypeError, "echochar requires 1 or 2 arguments"); + + + return NULL; + } + + if (!PyCurses_ConvertToChtype(temp, &ch)) { + PyErr_SetString(PyExc_TypeError, "argument 1 must be a ch or an int"); + return NULL; + } + #ifdef WINDOW_HAS_FLAGS - if (self->win->_flags & _ISPAD) - return PyCursesCheckERR(pechochar(self->win, ch | attr), - "echochar"); - else + if (self->win->_flags & _ISPAD) + return PyCursesCheckERR(pechochar(self->win, ch | attr), + "echochar"); + else #endif - return PyCursesCheckERR(wechochar(self->win, ch | attr), - "echochar"); + return PyCursesCheckERR(wechochar(self->win, ch | attr), + "echochar"); } #ifdef NCURSES_MOUSE_VERSION static PyObject * PyCursesWindow_Enclose(PyCursesWindowObject *self, PyObject *args) { - int x, y; - if (!PyArg_ParseTuple(args,"ii;y,x", &y, &x)) - return NULL; + int x, y; + if (!PyArg_ParseTuple(args,"ii;y,x", &y, &x)) + return NULL; - return PyLong_FromLong( wenclose(self->win,y,x) ); + return PyLong_FromLong( wenclose(self->win,y,x) ); } #endif static PyObject * PyCursesWindow_GetBkgd(PyCursesWindowObject *self) { - return PyLong_FromLong((long) getbkgd(self->win)); + return PyLong_FromLong((long) getbkgd(self->win)); } static PyObject * PyCursesWindow_GetCh(PyCursesWindowObject *self, PyObject *args) { - int x, y; - int rtn; + int x, y; + int rtn; - switch (PyTuple_Size(args)) { - case 0: - Py_BEGIN_ALLOW_THREADS - rtn = wgetch(self->win); - Py_END_ALLOW_THREADS - break; - case 2: - if (!PyArg_ParseTuple(args,"ii;y,x",&y,&x)) - return NULL; - Py_BEGIN_ALLOW_THREADS - rtn = mvwgetch(self->win,y,x); - Py_END_ALLOW_THREADS - break; - default: - PyErr_SetString(PyExc_TypeError, "getch requires 0 or 2 arguments"); - return NULL; - } - return PyLong_FromLong((long)rtn); + switch (PyTuple_Size(args)) { + case 0: + Py_BEGIN_ALLOW_THREADS + rtn = wgetch(self->win); + Py_END_ALLOW_THREADS + break; + case 2: + if (!PyArg_ParseTuple(args,"ii;y,x",&y,&x)) + return NULL; + Py_BEGIN_ALLOW_THREADS + rtn = mvwgetch(self->win,y,x); + Py_END_ALLOW_THREADS + break; + default: + PyErr_SetString(PyExc_TypeError, "getch requires 0 or 2 arguments"); + return NULL; + } + return PyLong_FromLong((long)rtn); } static PyObject * PyCursesWindow_GetKey(PyCursesWindowObject *self, PyObject *args) { - int x, y; - int rtn; + int x, y; + int rtn; - switch (PyTuple_Size(args)) { - case 0: - Py_BEGIN_ALLOW_THREADS - rtn = wgetch(self->win); - Py_END_ALLOW_THREADS - break; - case 2: - if (!PyArg_ParseTuple(args,"ii;y,x",&y,&x)) - return NULL; - Py_BEGIN_ALLOW_THREADS - rtn = mvwgetch(self->win,y,x); - Py_END_ALLOW_THREADS - break; - default: - PyErr_SetString(PyExc_TypeError, "getkey requires 0 or 2 arguments"); - return NULL; - } - if (rtn == ERR) { - /* getch() returns ERR in nodelay mode */ - PyErr_SetString(PyCursesError, "no input"); - return NULL; - } else if (rtn<=255) { - return Py_BuildValue("C", rtn); - } else { - const char *knp; + switch (PyTuple_Size(args)) { + case 0: + Py_BEGIN_ALLOW_THREADS + rtn = wgetch(self->win); + Py_END_ALLOW_THREADS + break; + case 2: + if (!PyArg_ParseTuple(args,"ii;y,x",&y,&x)) + return NULL; + Py_BEGIN_ALLOW_THREADS + rtn = mvwgetch(self->win,y,x); + Py_END_ALLOW_THREADS + break; + default: + PyErr_SetString(PyExc_TypeError, "getkey requires 0 or 2 arguments"); + return NULL; + } + if (rtn == ERR) { + /* getch() returns ERR in nodelay mode */ + PyErr_SetString(PyCursesError, "no input"); + return NULL; + } else if (rtn<=255) { + return Py_BuildValue("C", rtn); + } else { + const char *knp; #if defined(__NetBSD__) - knp = unctrl(rtn); + knp = unctrl(rtn); #else - knp = keyname(rtn); + knp = keyname(rtn); #endif - return PyUnicode_FromString((knp == NULL) ? "" : knp); - } + return PyUnicode_FromString((knp == NULL) ? "" : knp); + } } static PyObject * PyCursesWindow_GetStr(PyCursesWindowObject *self, PyObject *args) { - int x, y, n; - char rtn[1024]; /* This should be big enough.. I hope */ - int rtn2; - - switch (PyTuple_Size(args)) { - case 0: - Py_BEGIN_ALLOW_THREADS - rtn2 = wgetnstr(self->win,rtn, 1023); - Py_END_ALLOW_THREADS - break; - case 1: - if (!PyArg_ParseTuple(args,"i;n", &n)) - return NULL; - Py_BEGIN_ALLOW_THREADS - rtn2 = wgetnstr(self->win,rtn,MIN(n, 1023)); - Py_END_ALLOW_THREADS - break; - case 2: - if (!PyArg_ParseTuple(args,"ii;y,x",&y,&x)) - return NULL; - Py_BEGIN_ALLOW_THREADS + int x, y, n; + char rtn[1024]; /* This should be big enough.. I hope */ + int rtn2; + + switch (PyTuple_Size(args)) { + case 0: + Py_BEGIN_ALLOW_THREADS + rtn2 = wgetnstr(self->win,rtn, 1023); + Py_END_ALLOW_THREADS + break; + case 1: + if (!PyArg_ParseTuple(args,"i;n", &n)) + return NULL; + Py_BEGIN_ALLOW_THREADS + rtn2 = wgetnstr(self->win,rtn,MIN(n, 1023)); + Py_END_ALLOW_THREADS + break; + case 2: + if (!PyArg_ParseTuple(args,"ii;y,x",&y,&x)) + return NULL; + Py_BEGIN_ALLOW_THREADS #ifdef STRICT_SYSV_CURSES - rtn2 = wmove(self->win,y,x)==ERR ? ERR : wgetnstr(self->win, rtn, 1023); + rtn2 = wmove(self->win,y,x)==ERR ? ERR : wgetnstr(self->win, rtn, 1023); #else - rtn2 = mvwgetnstr(self->win,y,x,rtn, 1023); + rtn2 = mvwgetnstr(self->win,y,x,rtn, 1023); #endif - Py_END_ALLOW_THREADS - break; - case 3: - if (!PyArg_ParseTuple(args,"iii;y,x,n", &y, &x, &n)) - return NULL; + Py_END_ALLOW_THREADS + break; + case 3: + if (!PyArg_ParseTuple(args,"iii;y,x,n", &y, &x, &n)) + return NULL; #ifdef STRICT_SYSV_CURSES - Py_BEGIN_ALLOW_THREADS - rtn2 = wmove(self->win,y,x)==ERR ? ERR : - wgetnstr(self->win, rtn, MIN(n, 1023)); - Py_END_ALLOW_THREADS + Py_BEGIN_ALLOW_THREADS + rtn2 = wmove(self->win,y,x)==ERR ? ERR : + wgetnstr(self->win, rtn, MIN(n, 1023)); + Py_END_ALLOW_THREADS #else - Py_BEGIN_ALLOW_THREADS - rtn2 = mvwgetnstr(self->win, y, x, rtn, MIN(n, 1023)); - Py_END_ALLOW_THREADS -#endif - break; - default: - PyErr_SetString(PyExc_TypeError, "getstr requires 0 to 3 arguments"); - return NULL; - } - if (rtn2 == ERR) - rtn[0] = 0; - return PyBytes_FromString(rtn); + Py_BEGIN_ALLOW_THREADS + rtn2 = mvwgetnstr(self->win, y, x, rtn, MIN(n, 1023)); + Py_END_ALLOW_THREADS +#endif + break; + default: + PyErr_SetString(PyExc_TypeError, "getstr requires 0 to 3 arguments"); + return NULL; + } + if (rtn2 == ERR) + rtn[0] = 0; + return PyBytes_FromString(rtn); } static PyObject * PyCursesWindow_Hline(PyCursesWindowObject *self, PyObject *args) { - PyObject *temp; - chtype ch; - int n, x, y, code = OK; - attr_t attr = A_NORMAL; - long lattr; - - switch (PyTuple_Size(args)) { - case 2: - if (!PyArg_ParseTuple(args, "Oi;ch or int,n", &temp, &n)) - return NULL; - break; - case 3: - if (!PyArg_ParseTuple(args, "Oil;ch or int,n,attr", &temp, &n, &lattr)) - return NULL; - attr = lattr; - break; - case 4: - if (!PyArg_ParseTuple(args, "iiOi;y,x,ch or int,n", &y, &x, &temp, &n)) - return NULL; - code = wmove(self->win, y, x); - break; - case 5: - if (!PyArg_ParseTuple(args, "iiOil; y,x,ch or int,n,attr", - &y, &x, &temp, &n, &lattr)) - return NULL; - attr = lattr; - code = wmove(self->win, y, x); - break; - default: - PyErr_SetString(PyExc_TypeError, "hline requires 2 to 5 arguments"); - return NULL; - } + PyObject *temp; + chtype ch; + int n, x, y, code = OK; + attr_t attr = A_NORMAL; + long lattr; - if (code != ERR) { - if (!PyCurses_ConvertToChtype(temp, &ch)) { - PyErr_SetString(PyExc_TypeError, - "argument 1 or 3 must be a ch or an int"); - return NULL; - } - return PyCursesCheckERR(whline(self->win, ch | attr, n), "hline"); - } else - return PyCursesCheckERR(code, "wmove"); -} + switch (PyTuple_Size(args)) { + case 2: + if (!PyArg_ParseTuple(args, "Oi;ch or int,n", &temp, &n)) + return NULL; + break; + case 3: + if (!PyArg_ParseTuple(args, "Oil;ch or int,n,attr", &temp, &n, &lattr)) + return NULL; + attr = lattr; + break; + case 4: + if (!PyArg_ParseTuple(args, "iiOi;y,x,ch or int,n", &y, &x, &temp, &n)) + return NULL; + code = wmove(self->win, y, x); + break; + case 5: + if (!PyArg_ParseTuple(args, "iiOil; y,x,ch or int,n,attr", + &y, &x, &temp, &n, &lattr)) + return NULL; + attr = lattr; + code = wmove(self->win, y, x); + break; + default: + PyErr_SetString(PyExc_TypeError, "hline requires 2 to 5 arguments"); + return NULL; + } -static PyObject * -PyCursesWindow_InsCh(PyCursesWindowObject *self, PyObject *args) -{ - int rtn, x, y, use_xy = FALSE; - PyObject *temp; - chtype ch = 0; - attr_t attr = A_NORMAL; - long lattr; - - switch (PyTuple_Size(args)) { - case 1: - if (!PyArg_ParseTuple(args, "O;ch or int", &temp)) - return NULL; - break; - case 2: - if (!PyArg_ParseTuple(args, "Ol;ch or int,attr", &temp, &lattr)) - return NULL; - attr = lattr; - break; - case 3: - if (!PyArg_ParseTuple(args,"iiO;y,x,ch or int", &y, &x, &temp)) - return NULL; - use_xy = TRUE; - break; - case 4: - if (!PyArg_ParseTuple(args,"iiOl;y,x,ch or int, attr", &y, &x, &temp, &lattr)) - return NULL; - attr = lattr; - use_xy = TRUE; - break; - default: - PyErr_SetString(PyExc_TypeError, "insch requires 1 or 4 arguments"); - return NULL; - } - - if (!PyCurses_ConvertToChtype(temp, &ch)) { - PyErr_SetString(PyExc_TypeError, - "argument 1 or 3 must be a ch or an int"); - return NULL; - } - - if (use_xy == TRUE) - rtn = mvwinsch(self->win,y,x, ch | attr); - else { - rtn = winsch(self->win, ch | attr); - } - return PyCursesCheckERR(rtn, "insch"); + if (code != ERR) { + if (!PyCurses_ConvertToChtype(temp, &ch)) { + PyErr_SetString(PyExc_TypeError, + "argument 1 or 3 must be a ch or an int"); + return NULL; + } + return PyCursesCheckERR(whline(self->win, ch | attr, n), "hline"); + } else + return PyCursesCheckERR(code, "wmove"); } static PyObject * -PyCursesWindow_InCh(PyCursesWindowObject *self, PyObject *args) +PyCursesWindow_InsCh(PyCursesWindowObject *self, PyObject *args) { - int x, y, rtn; + int rtn, x, y, use_xy = FALSE; + PyObject *temp; + chtype ch = 0; + attr_t attr = A_NORMAL; + long lattr; - switch (PyTuple_Size(args)) { - case 0: - rtn = winch(self->win); - break; - case 2: - if (!PyArg_ParseTuple(args,"ii;y,x",&y,&x)) - return NULL; - rtn = mvwinch(self->win,y,x); - break; - default: - PyErr_SetString(PyExc_TypeError, "inch requires 0 or 2 arguments"); - return NULL; - } - return PyLong_FromLong((long) rtn); -} + switch (PyTuple_Size(args)) { + case 1: + if (!PyArg_ParseTuple(args, "O;ch or int", &temp)) + return NULL; + break; + case 2: + if (!PyArg_ParseTuple(args, "Ol;ch or int,attr", &temp, &lattr)) + return NULL; + attr = lattr; + break; + case 3: + if (!PyArg_ParseTuple(args,"iiO;y,x,ch or int", &y, &x, &temp)) + return NULL; + use_xy = TRUE; + break; + case 4: + if (!PyArg_ParseTuple(args,"iiOl;y,x,ch or int, attr", &y, &x, &temp, &lattr)) + return NULL; + attr = lattr; + use_xy = TRUE; + break; + default: + PyErr_SetString(PyExc_TypeError, "insch requires 1 or 4 arguments"); + return NULL; + } -static PyObject * -PyCursesWindow_InStr(PyCursesWindowObject *self, PyObject *args) -{ - int x, y, n; - char rtn[1024]; /* This should be big enough.. I hope */ - int rtn2; - - switch (PyTuple_Size(args)) { - case 0: - rtn2 = winnstr(self->win,rtn, 1023); - break; - case 1: - if (!PyArg_ParseTuple(args,"i;n", &n)) - return NULL; - rtn2 = winnstr(self->win,rtn,MIN(n,1023)); - break; - case 2: - if (!PyArg_ParseTuple(args,"ii;y,x",&y,&x)) - return NULL; - rtn2 = mvwinnstr(self->win,y,x,rtn,1023); - break; - case 3: - if (!PyArg_ParseTuple(args, "iii;y,x,n", &y, &x, &n)) - return NULL; - rtn2 = mvwinnstr(self->win, y, x, rtn, MIN(n,1023)); - break; - default: - PyErr_SetString(PyExc_TypeError, "instr requires 0 or 3 arguments"); - return NULL; - } - if (rtn2 == ERR) - rtn[0] = 0; - return PyBytes_FromString(rtn); -} + if (!PyCurses_ConvertToChtype(temp, &ch)) { + PyErr_SetString(PyExc_TypeError, + "argument 1 or 3 must be a ch or an int"); + return NULL; + } -static PyObject * -PyCursesWindow_InsStr(PyCursesWindowObject *self, PyObject *args) -{ - int rtn; - int x, y; - char *str; - attr_t attr = A_NORMAL , attr_old = A_NORMAL; - long lattr; - int use_xy = FALSE, use_attr = FALSE; - - switch (PyTuple_Size(args)) { - case 1: - if (!PyArg_ParseTuple(args,"s;str", &str)) - return NULL; - break; - case 2: - if (!PyArg_ParseTuple(args,"sl;str,attr", &str, &lattr)) - return NULL; - attr = lattr; - use_attr = TRUE; - break; - case 3: - if (!PyArg_ParseTuple(args,"iis;y,x,str", &y, &x, &str)) - return NULL; - use_xy = TRUE; - break; - case 4: - if (!PyArg_ParseTuple(args,"iisl;y,x,str,attr", &y, &x, &str, &lattr)) - return NULL; - attr = lattr; - use_xy = use_attr = TRUE; - break; - default: - PyErr_SetString(PyExc_TypeError, "insstr requires 1 to 4 arguments"); - return NULL; - } - - if (use_attr == TRUE) { - attr_old = getattrs(self->win); - (void)wattrset(self->win,attr); - } - if (use_xy == TRUE) - rtn = mvwinsstr(self->win,y,x,str); - else - rtn = winsstr(self->win,str); - if (use_attr == TRUE) - (void)wattrset(self->win,attr_old); - return PyCursesCheckERR(rtn, "insstr"); + if (use_xy == TRUE) + rtn = mvwinsch(self->win,y,x, ch | attr); + else { + rtn = winsch(self->win, ch | attr); + } + return PyCursesCheckERR(rtn, "insch"); } static PyObject * -PyCursesWindow_InsNStr(PyCursesWindowObject *self, PyObject *args) +PyCursesWindow_InCh(PyCursesWindowObject *self, PyObject *args) { - int rtn, x, y, n; - char *str; - attr_t attr = A_NORMAL , attr_old = A_NORMAL; - long lattr; - int use_xy = FALSE, use_attr = FALSE; - - switch (PyTuple_Size(args)) { - case 2: - if (!PyArg_ParseTuple(args,"si;str,n", &str, &n)) - return NULL; - break; - case 3: - if (!PyArg_ParseTuple(args,"sil;str,n,attr", &str, &n, &lattr)) - return NULL; - attr = lattr; - use_attr = TRUE; - break; - case 4: - if (!PyArg_ParseTuple(args,"iisi;y,x,str,n", &y, &x, &str, &n)) - return NULL; - use_xy = TRUE; - break; - case 5: - if (!PyArg_ParseTuple(args,"iisil;y,x,str,n,attr", &y, &x, &str, &n, &lattr)) - return NULL; - attr = lattr; - use_xy = use_attr = TRUE; - break; - default: - PyErr_SetString(PyExc_TypeError, "insnstr requires 2 to 5 arguments"); - return NULL; - } - - if (use_attr == TRUE) { - attr_old = getattrs(self->win); - (void)wattrset(self->win,attr); - } - if (use_xy == TRUE) - rtn = mvwinsnstr(self->win,y,x,str,n); - else - rtn = winsnstr(self->win,str,n); - if (use_attr == TRUE) - (void)wattrset(self->win,attr_old); - return PyCursesCheckERR(rtn, "insnstr"); -} + int x, y, rtn; -static PyObject * -PyCursesWindow_Is_LineTouched(PyCursesWindowObject *self, PyObject *args) -{ - int line, erg; - if (!PyArg_ParseTuple(args,"i;line", &line)) - return NULL; - erg = is_linetouched(self->win, line); - if (erg == ERR) { - PyErr_SetString(PyExc_TypeError, - "is_linetouched: line number outside of boundaries"); - return NULL; - } else - if (erg == FALSE) { - Py_INCREF(Py_False); - return Py_False; - } else { - Py_INCREF(Py_True); - return Py_True; + switch (PyTuple_Size(args)) { + case 0: + rtn = winch(self->win); + break; + case 2: + if (!PyArg_ParseTuple(args,"ii;y,x",&y,&x)) + return NULL; + rtn = mvwinch(self->win,y,x); + break; + default: + PyErr_SetString(PyExc_TypeError, "inch requires 0 or 2 arguments"); + return NULL; } + return PyLong_FromLong((long) rtn); } static PyObject * -PyCursesWindow_NoOutRefresh(PyCursesWindowObject *self, PyObject *args) +PyCursesWindow_InStr(PyCursesWindowObject *self, PyObject *args) { - int pminrow,pmincol,sminrow,smincol,smaxrow,smaxcol; - int rtn; + int x, y, n; + char rtn[1024]; /* This should be big enough.. I hope */ + int rtn2; -#ifndef WINDOW_HAS_FLAGS - if (0) { -#else - if (self->win->_flags & _ISPAD) { -#endif - switch(PyTuple_Size(args)) { - case 6: - if (!PyArg_ParseTuple(args, - "iiiiii;" \ - "pminrow,pmincol,sminrow,smincol,smaxrow,smaxcol", - &pminrow, &pmincol, &sminrow, - &smincol, &smaxrow, &smaxcol)) - return NULL; - Py_BEGIN_ALLOW_THREADS - rtn = pnoutrefresh(self->win, - pminrow, pmincol, sminrow, - smincol, smaxrow, smaxcol); - Py_END_ALLOW_THREADS - return PyCursesCheckERR(rtn, "pnoutrefresh"); + switch (PyTuple_Size(args)) { + case 0: + rtn2 = winnstr(self->win,rtn, 1023); + break; + case 1: + if (!PyArg_ParseTuple(args,"i;n", &n)) + return NULL; + rtn2 = winnstr(self->win,rtn,MIN(n,1023)); + break; + case 2: + if (!PyArg_ParseTuple(args,"ii;y,x",&y,&x)) + return NULL; + rtn2 = mvwinnstr(self->win,y,x,rtn,1023); + break; + case 3: + if (!PyArg_ParseTuple(args, "iii;y,x,n", &y, &x, &n)) + return NULL; + rtn2 = mvwinnstr(self->win, y, x, rtn, MIN(n,1023)); + break; default: - PyErr_SetString(PyCursesError, - "noutrefresh() called for a pad " - "requires 6 arguments"); - return NULL; + PyErr_SetString(PyExc_TypeError, "instr requires 0 or 3 arguments"); + return NULL; } - } else { - if (!PyArg_ParseTuple(args, ":noutrefresh")) - return NULL; - - Py_BEGIN_ALLOW_THREADS - rtn = wnoutrefresh(self->win); - Py_END_ALLOW_THREADS - return PyCursesCheckERR(rtn, "wnoutrefresh"); - } + if (rtn2 == ERR) + rtn[0] = 0; + return PyBytes_FromString(rtn); } static PyObject * -PyCursesWindow_Overlay(PyCursesWindowObject *self, PyObject *args) +PyCursesWindow_InsStr(PyCursesWindowObject *self, PyObject *args) { - PyCursesWindowObject *temp; - int use_copywin = FALSE; - int sminrow, smincol, dminrow, dmincol, dmaxrow, dmaxcol; int rtn; - + int x, y; + char *str; + attr_t attr = A_NORMAL , attr_old = A_NORMAL; + long lattr; + int use_xy = FALSE, use_attr = FALSE; + switch (PyTuple_Size(args)) { case 1: - if (!PyArg_ParseTuple(args, "O!;window object", - &PyCursesWindow_Type, &temp)) - return NULL; - break; - case 7: - if (!PyArg_ParseTuple(args, "O!iiiiii;window object, int, int, int, int, int, int", - &PyCursesWindow_Type, &temp, &sminrow, &smincol, - &dminrow, &dmincol, &dmaxrow, &dmaxcol)) - return NULL; - use_copywin = TRUE; - break; + if (!PyArg_ParseTuple(args,"s;str", &str)) + return NULL; + break; + case 2: + if (!PyArg_ParseTuple(args,"sl;str,attr", &str, &lattr)) + return NULL; + attr = lattr; + use_attr = TRUE; + break; + case 3: + if (!PyArg_ParseTuple(args,"iis;y,x,str", &y, &x, &str)) + return NULL; + use_xy = TRUE; + break; + case 4: + if (!PyArg_ParseTuple(args,"iisl;y,x,str,attr", &y, &x, &str, &lattr)) + return NULL; + attr = lattr; + use_xy = use_attr = TRUE; + break; default: - PyErr_SetString(PyExc_TypeError, - "overlay requires one or seven arguments"); - return NULL; + PyErr_SetString(PyExc_TypeError, "insstr requires 1 to 4 arguments"); + return NULL; } - if (use_copywin == TRUE) { - rtn = copywin(self->win, temp->win, sminrow, smincol, - dminrow, dmincol, dmaxrow, dmaxcol, TRUE); - return PyCursesCheckERR(rtn, "copywin"); - } - else { - rtn = overlay(self->win, temp->win); - return PyCursesCheckERR(rtn, "overlay"); + if (use_attr == TRUE) { + attr_old = getattrs(self->win); + (void)wattrset(self->win,attr); } + if (use_xy == TRUE) + rtn = mvwinsstr(self->win,y,x,str); + else + rtn = winsstr(self->win,str); + if (use_attr == TRUE) + (void)wattrset(self->win,attr_old); + return PyCursesCheckERR(rtn, "insstr"); } static PyObject * -PyCursesWindow_Overwrite(PyCursesWindowObject *self, PyObject *args) +PyCursesWindow_InsNStr(PyCursesWindowObject *self, PyObject *args) { - PyCursesWindowObject *temp; - int use_copywin = FALSE; - int sminrow, smincol, dminrow, dmincol, dmaxrow, dmaxcol; - int rtn; - + int rtn, x, y, n; + char *str; + attr_t attr = A_NORMAL , attr_old = A_NORMAL; + long lattr; + int use_xy = FALSE, use_attr = FALSE; + switch (PyTuple_Size(args)) { - case 1: - if (!PyArg_ParseTuple(args, "O!;window object", - &PyCursesWindow_Type, &temp)) - return NULL; - break; - case 7: - if (!PyArg_ParseTuple(args, "O!iiiiii;window object, int, int, int, int, int, int", - &PyCursesWindow_Type, &temp, &sminrow, &smincol, - &dminrow, &dmincol, &dmaxrow, &dmaxcol)) - return NULL; - use_copywin = TRUE; - break; + case 2: + if (!PyArg_ParseTuple(args,"si;str,n", &str, &n)) + return NULL; + break; + case 3: + if (!PyArg_ParseTuple(args,"sil;str,n,attr", &str, &n, &lattr)) + return NULL; + attr = lattr; + use_attr = TRUE; + break; + case 4: + if (!PyArg_ParseTuple(args,"iisi;y,x,str,n", &y, &x, &str, &n)) + return NULL; + use_xy = TRUE; + break; + case 5: + if (!PyArg_ParseTuple(args,"iisil;y,x,str,n,attr", &y, &x, &str, &n, &lattr)) + return NULL; + attr = lattr; + use_xy = use_attr = TRUE; + break; default: - PyErr_SetString(PyExc_TypeError, - "overwrite requires one or seven arguments"); - return NULL; + PyErr_SetString(PyExc_TypeError, "insnstr requires 2 to 5 arguments"); + return NULL; } - if (use_copywin == TRUE) { - rtn = copywin(self->win, temp->win, sminrow, smincol, - dminrow, dmincol, dmaxrow, dmaxcol, FALSE); - return PyCursesCheckERR(rtn, "copywin"); - } - else { - rtn = overwrite(self->win, temp->win); - return PyCursesCheckERR(rtn, "overwrite"); + if (use_attr == TRUE) { + attr_old = getattrs(self->win); + (void)wattrset(self->win,attr); } + if (use_xy == TRUE) + rtn = mvwinsnstr(self->win,y,x,str,n); + else + rtn = winsnstr(self->win,str,n); + if (use_attr == TRUE) + (void)wattrset(self->win,attr_old); + return PyCursesCheckERR(rtn, "insnstr"); } static PyObject * -PyCursesWindow_PutWin(PyCursesWindowObject *self, PyObject *stream) +PyCursesWindow_Is_LineTouched(PyCursesWindowObject *self, PyObject *args) { - /* We have to simulate this by writing to a temporary FILE*, - then reading back, then writing to the argument stream. */ - char fn[100]; - int fd; - FILE *fp; - PyObject *res; - - strcpy(fn, "/tmp/py.curses.putwin.XXXXXX"); - fd = mkstemp(fn); - if (fd < 0) - return PyErr_SetFromErrnoWithFilename(PyExc_IOError, fn); - fp = fdopen(fd, "wb+"); - if (fp == NULL) { - close(fd); - remove(fn); - return PyErr_SetFromErrnoWithFilename(PyExc_IOError, fn); - } - res = PyCursesCheckERR(putwin(self->win, fp), "putwin"); - if (res == NULL) { - fclose(fp); - remove(fn); - return res; - } - fseek(fp, 0, 0); - while (1) { - char buf[BUFSIZ]; - int n = fread(buf, 1, BUFSIZ, fp); - if (n <= 0) - break; - Py_DECREF(res); - res = PyObject_CallMethod(stream, "write", "y#", buf, n); - if (res == NULL) - break; - } - fclose(fp); - remove(fn); - return res; + int line, erg; + if (!PyArg_ParseTuple(args,"i;line", &line)) + return NULL; + erg = is_linetouched(self->win, line); + if (erg == ERR) { + PyErr_SetString(PyExc_TypeError, + "is_linetouched: line number outside of boundaries"); + return NULL; + } else + if (erg == FALSE) { + Py_INCREF(Py_False); + return Py_False; + } else { + Py_INCREF(Py_True); + return Py_True; + } } static PyObject * -PyCursesWindow_RedrawLine(PyCursesWindowObject *self, PyObject *args) -{ - int beg, num; - if (!PyArg_ParseTuple(args, "ii;beg,num", &beg, &num)) - return NULL; - return PyCursesCheckERR(wredrawln(self->win,beg,num), "redrawln"); -} +PyCursesWindow_NoOutRefresh(PyCursesWindowObject *self, PyObject *args) +{ + int pminrow,pmincol,sminrow,smincol,smaxrow,smaxcol; + int rtn; -static PyObject * -PyCursesWindow_Refresh(PyCursesWindowObject *self, PyObject *args) -{ - int pminrow,pmincol,sminrow,smincol,smaxrow,smaxcol; - int rtn; - #ifndef WINDOW_HAS_FLAGS - if (0) { + if (0) { #else - if (self->win->_flags & _ISPAD) { + if (self->win->_flags & _ISPAD) { #endif - switch(PyTuple_Size(args)) { - case 6: - if (!PyArg_ParseTuple(args, - "iiiiii;" \ - "pminrow,pmincol,sminrow,smincol,smaxrow,smaxcol", - &pminrow, &pmincol, &sminrow, - &smincol, &smaxrow, &smaxcol)) - return NULL; - - Py_BEGIN_ALLOW_THREADS - rtn = prefresh(self->win, - pminrow, pmincol, sminrow, - smincol, smaxrow, smaxcol); - Py_END_ALLOW_THREADS - return PyCursesCheckERR(rtn, "prefresh"); - default: - PyErr_SetString(PyCursesError, - "refresh() for a pad requires 6 arguments"); - return NULL; - } - } else { - if (!PyArg_ParseTuple(args, ":refresh")) - return NULL; - Py_BEGIN_ALLOW_THREADS - rtn = wrefresh(self->win); - Py_END_ALLOW_THREADS - return PyCursesCheckERR(rtn, "prefresh"); - } -} + switch(PyTuple_Size(args)) { + case 6: + if (!PyArg_ParseTuple(args, + "iiiiii;" \ + "pminrow,pmincol,sminrow,smincol,smaxrow,smaxcol", + &pminrow, &pmincol, &sminrow, + &smincol, &smaxrow, &smaxcol)) + return NULL; + Py_BEGIN_ALLOW_THREADS + rtn = pnoutrefresh(self->win, + pminrow, pmincol, sminrow, + smincol, smaxrow, smaxcol); + Py_END_ALLOW_THREADS + return PyCursesCheckERR(rtn, "pnoutrefresh"); + default: + PyErr_SetString(PyCursesError, + "noutrefresh() called for a pad " + "requires 6 arguments"); + return NULL; + } + } else { + if (!PyArg_ParseTuple(args, ":noutrefresh")) + return NULL; + + Py_BEGIN_ALLOW_THREADS + rtn = wnoutrefresh(self->win); + Py_END_ALLOW_THREADS + return PyCursesCheckERR(rtn, "wnoutrefresh"); + } + } -static PyObject * -PyCursesWindow_SetScrollRegion(PyCursesWindowObject *self, PyObject *args) -{ - int x, y; - if (!PyArg_ParseTuple(args,"ii;top, bottom",&y,&x)) - return NULL; - return PyCursesCheckERR(wsetscrreg(self->win,y,x), "wsetscrreg"); -} + static PyObject * + PyCursesWindow_Overlay(PyCursesWindowObject *self, PyObject *args) + { + PyCursesWindowObject *temp; + int use_copywin = FALSE; + int sminrow, smincol, dminrow, dmincol, dmaxrow, dmaxcol; + int rtn; + + switch (PyTuple_Size(args)) { + case 1: + if (!PyArg_ParseTuple(args, "O!;window object", + &PyCursesWindow_Type, &temp)) + return NULL; + break; + case 7: + if (!PyArg_ParseTuple(args, "O!iiiiii;window object, int, int, int, int, int, int", + &PyCursesWindow_Type, &temp, &sminrow, &smincol, + &dminrow, &dmincol, &dmaxrow, &dmaxcol)) + return NULL; + use_copywin = TRUE; + break; + default: + PyErr_SetString(PyExc_TypeError, + "overlay requires one or seven arguments"); + return NULL; + } + + if (use_copywin == TRUE) { + rtn = copywin(self->win, temp->win, sminrow, smincol, + dminrow, dmincol, dmaxrow, dmaxcol, TRUE); + return PyCursesCheckERR(rtn, "copywin"); + } + else { + rtn = overlay(self->win, temp->win); + return PyCursesCheckERR(rtn, "overlay"); + } + } -static PyObject * -PyCursesWindow_SubWin(PyCursesWindowObject *self, PyObject *args) -{ - WINDOW *win; - int nlines, ncols, begin_y, begin_x; - - nlines = 0; - ncols = 0; - switch (PyTuple_Size(args)) { - case 2: - if (!PyArg_ParseTuple(args,"ii;begin_y,begin_x",&begin_y,&begin_x)) - return NULL; - break; - case 4: - if (!PyArg_ParseTuple(args, "iiii;nlines,ncols,begin_y,begin_x", - &nlines,&ncols,&begin_y,&begin_x)) - return NULL; - break; - default: - PyErr_SetString(PyExc_TypeError, "subwin requires 2 or 4 arguments"); - return NULL; - } + static PyObject * + PyCursesWindow_Overwrite(PyCursesWindowObject *self, PyObject *args) + { + PyCursesWindowObject *temp; + int use_copywin = FALSE; + int sminrow, smincol, dminrow, dmincol, dmaxrow, dmaxcol; + int rtn; + + switch (PyTuple_Size(args)) { + case 1: + if (!PyArg_ParseTuple(args, "O!;window object", + &PyCursesWindow_Type, &temp)) + return NULL; + break; + case 7: + if (!PyArg_ParseTuple(args, "O!iiiiii;window object, int, int, int, int, int, int", + &PyCursesWindow_Type, &temp, &sminrow, &smincol, + &dminrow, &dmincol, &dmaxrow, &dmaxcol)) + return NULL; + use_copywin = TRUE; + break; + default: + PyErr_SetString(PyExc_TypeError, + "overwrite requires one or seven arguments"); + return NULL; + } + + if (use_copywin == TRUE) { + rtn = copywin(self->win, temp->win, sminrow, smincol, + dminrow, dmincol, dmaxrow, dmaxcol, FALSE); + return PyCursesCheckERR(rtn, "copywin"); + } + else { + rtn = overwrite(self->win, temp->win); + return PyCursesCheckERR(rtn, "overwrite"); + } + } - /* printf("Subwin: %i %i %i %i \n", nlines, ncols, begin_y, begin_x); */ -#ifdef WINDOW_HAS_FLAGS - if (self->win->_flags & _ISPAD) - win = subpad(self->win, nlines, ncols, begin_y, begin_x); - else -#endif - win = subwin(self->win, nlines, ncols, begin_y, begin_x); - - if (win == NULL) { - PyErr_SetString(PyCursesError, catchall_NULL); - return NULL; - } - - return (PyObject *)PyCursesWindow_New(win); -} - -static PyObject * -PyCursesWindow_Scroll(PyCursesWindowObject *self, PyObject *args) -{ - int nlines; - switch(PyTuple_Size(args)) { - case 0: - return PyCursesCheckERR(scroll(self->win), "scroll"); - case 1: - if (!PyArg_ParseTuple(args, "i;nlines", &nlines)) - return NULL; - return PyCursesCheckERR(wscrl(self->win, nlines), "scroll"); - default: - PyErr_SetString(PyExc_TypeError, "scroll requires 0 or 1 arguments"); - return NULL; - } -} - -static PyObject * -PyCursesWindow_TouchLine(PyCursesWindowObject *self, PyObject *args) -{ - int st, cnt, val; - switch (PyTuple_Size(args)) { - case 2: - if (!PyArg_ParseTuple(args,"ii;start,count",&st,&cnt)) - return NULL; - return PyCursesCheckERR(touchline(self->win,st,cnt), "touchline"); - case 3: - if (!PyArg_ParseTuple(args, "iii;start,count,val", &st, &cnt, &val)) - return NULL; - return PyCursesCheckERR(wtouchln(self->win, st, cnt, val), "touchline"); - default: - PyErr_SetString(PyExc_TypeError, "touchline requires 2 or 3 arguments"); - return NULL; - } -} - -static PyObject * -PyCursesWindow_Vline(PyCursesWindowObject *self, PyObject *args) -{ - PyObject *temp; - chtype ch; - int n, x, y, code = OK; - attr_t attr = A_NORMAL; - long lattr; - - switch (PyTuple_Size(args)) { - case 2: - if (!PyArg_ParseTuple(args, "Oi;ch or int,n", &temp, &n)) - return NULL; - break; - case 3: - if (!PyArg_ParseTuple(args, "Oil;ch or int,n,attr", &temp, &n, &lattr)) - return NULL; - attr = lattr; - break; - case 4: - if (!PyArg_ParseTuple(args, "iiOi;y,x,ch or int,n", &y, &x, &temp, &n)) - return NULL; - code = wmove(self->win, y, x); - break; - case 5: - if (!PyArg_ParseTuple(args, "iiOil; y,x,ch or int,n,attr", - &y, &x, &temp, &n, &lattr)) - return NULL; - attr = lattr; - code = wmove(self->win, y, x); - break; - default: - PyErr_SetString(PyExc_TypeError, "vline requires 2 to 5 arguments"); - return NULL; - } + static PyObject * + PyCursesWindow_PutWin(PyCursesWindowObject *self, PyObject *stream) + { + /* We have to simulate this by writing to a temporary FILE*, + then reading back, then writing to the argument stream. */ + char fn[100]; + int fd; + FILE *fp; + PyObject *res; + + strcpy(fn, "/tmp/py.curses.putwin.XXXXXX"); + fd = mkstemp(fn); + if (fd < 0) + return PyErr_SetFromErrnoWithFilename(PyExc_IOError, fn); + fp = fdopen(fd, "wb+"); + if (fp == NULL) { + close(fd); + remove(fn); + return PyErr_SetFromErrnoWithFilename(PyExc_IOError, fn); + } + res = PyCursesCheckERR(putwin(self->win, fp), "putwin"); + if (res == NULL) { + fclose(fp); + remove(fn); + return res; + } + fseek(fp, 0, 0); + while (1) { + char buf[BUFSIZ]; + int n = fread(buf, 1, BUFSIZ, fp); + if (n <= 0) + break; + Py_DECREF(res); + res = PyObject_CallMethod(stream, "write", "y#", buf, n); + if (res == NULL) + break; + } + fclose(fp); + remove(fn); + return res; + } - if (code != ERR) { - if (!PyCurses_ConvertToChtype(temp, &ch)) { - PyErr_SetString(PyExc_TypeError, - "argument 1 or 3 must be a ch or an int"); - return NULL; - } - return PyCursesCheckERR(wvline(self->win, ch | attr, n), "vline"); - } else - return PyCursesCheckERR(code, "wmove"); -} - -static PyMethodDef PyCursesWindow_Methods[] = { - {"addch", (PyCFunction)PyCursesWindow_AddCh, METH_VARARGS}, - {"addnstr", (PyCFunction)PyCursesWindow_AddNStr, METH_VARARGS}, - {"addstr", (PyCFunction)PyCursesWindow_AddStr, METH_VARARGS}, - {"attroff", (PyCFunction)PyCursesWindow_AttrOff, METH_VARARGS}, - {"attron", (PyCFunction)PyCursesWindow_AttrOn, METH_VARARGS}, - {"attrset", (PyCFunction)PyCursesWindow_AttrSet, METH_VARARGS}, - {"bkgd", (PyCFunction)PyCursesWindow_Bkgd, METH_VARARGS}, - {"chgat", (PyCFunction)PyCursesWindow_ChgAt, METH_VARARGS}, - {"bkgdset", (PyCFunction)PyCursesWindow_BkgdSet, METH_VARARGS}, - {"border", (PyCFunction)PyCursesWindow_Border, METH_VARARGS}, - {"box", (PyCFunction)PyCursesWindow_Box, METH_VARARGS}, - {"clear", (PyCFunction)PyCursesWindow_wclear, METH_NOARGS}, - {"clearok", (PyCFunction)PyCursesWindow_clearok, METH_VARARGS}, - {"clrtobot", (PyCFunction)PyCursesWindow_wclrtobot, METH_NOARGS}, - {"clrtoeol", (PyCFunction)PyCursesWindow_wclrtoeol, METH_NOARGS}, - {"cursyncup", (PyCFunction)PyCursesWindow_wcursyncup, METH_NOARGS}, - {"delch", (PyCFunction)PyCursesWindow_DelCh, METH_VARARGS}, - {"deleteln", (PyCFunction)PyCursesWindow_wdeleteln, METH_NOARGS}, - {"derwin", (PyCFunction)PyCursesWindow_DerWin, METH_VARARGS}, - {"echochar", (PyCFunction)PyCursesWindow_EchoChar, METH_VARARGS}, + static PyObject * + PyCursesWindow_RedrawLine(PyCursesWindowObject *self, PyObject *args) + { + int beg, num; + if (!PyArg_ParseTuple(args, "ii;beg,num", &beg, &num)) + return NULL; + return PyCursesCheckERR(wredrawln(self->win,beg,num), "redrawln"); + } + + static PyObject * + PyCursesWindow_Refresh(PyCursesWindowObject *self, PyObject *args) + { + int pminrow,pmincol,sminrow,smincol,smaxrow,smaxcol; + int rtn; + +#ifndef WINDOW_HAS_FLAGS + if (0) { +#else + if (self->win->_flags & _ISPAD) { +#endif + switch(PyTuple_Size(args)) { + case 6: + if (!PyArg_ParseTuple(args, + "iiiiii;" \ + "pminrow,pmincol,sminrow,smincol,smaxrow,smaxcol", + &pminrow, &pmincol, &sminrow, + &smincol, &smaxrow, &smaxcol)) + return NULL; + + Py_BEGIN_ALLOW_THREADS + rtn = prefresh(self->win, + pminrow, pmincol, sminrow, + smincol, smaxrow, smaxcol); + Py_END_ALLOW_THREADS + return PyCursesCheckERR(rtn, "prefresh"); + default: + PyErr_SetString(PyCursesError, + "refresh() for a pad requires 6 arguments"); + return NULL; + } + } else { + if (!PyArg_ParseTuple(args, ":refresh")) + return NULL; + Py_BEGIN_ALLOW_THREADS + rtn = wrefresh(self->win); + Py_END_ALLOW_THREADS + return PyCursesCheckERR(rtn, "prefresh"); + } + } + + static PyObject * + PyCursesWindow_SetScrollRegion(PyCursesWindowObject *self, PyObject *args) + { + int x, y; + if (!PyArg_ParseTuple(args,"ii;top, bottom",&y,&x)) + return NULL; + return PyCursesCheckERR(wsetscrreg(self->win,y,x), "wsetscrreg"); + } + + static PyObject * + PyCursesWindow_SubWin(PyCursesWindowObject *self, PyObject *args) + { + WINDOW *win; + int nlines, ncols, begin_y, begin_x; + + nlines = 0; + ncols = 0; + switch (PyTuple_Size(args)) { + case 2: + if (!PyArg_ParseTuple(args,"ii;begin_y,begin_x",&begin_y,&begin_x)) + return NULL; + break; + case 4: + if (!PyArg_ParseTuple(args, "iiii;nlines,ncols,begin_y,begin_x", + &nlines,&ncols,&begin_y,&begin_x)) + return NULL; + break; + default: + PyErr_SetString(PyExc_TypeError, "subwin requires 2 or 4 arguments"); + return NULL; + } + + /* printf("Subwin: %i %i %i %i \n", nlines, ncols, begin_y, begin_x); */ +#ifdef WINDOW_HAS_FLAGS + if (self->win->_flags & _ISPAD) + win = subpad(self->win, nlines, ncols, begin_y, begin_x); + else +#endif + win = subwin(self->win, nlines, ncols, begin_y, begin_x); + + if (win == NULL) { + PyErr_SetString(PyCursesError, catchall_NULL); + return NULL; + } + + return (PyObject *)PyCursesWindow_New(win); + } + + static PyObject * + PyCursesWindow_Scroll(PyCursesWindowObject *self, PyObject *args) + { + int nlines; + switch(PyTuple_Size(args)) { + case 0: + return PyCursesCheckERR(scroll(self->win), "scroll"); + case 1: + if (!PyArg_ParseTuple(args, "i;nlines", &nlines)) + return NULL; + return PyCursesCheckERR(wscrl(self->win, nlines), "scroll"); + default: + PyErr_SetString(PyExc_TypeError, "scroll requires 0 or 1 arguments"); + return NULL; + } + } + + static PyObject * + PyCursesWindow_TouchLine(PyCursesWindowObject *self, PyObject *args) + { + int st, cnt, val; + switch (PyTuple_Size(args)) { + case 2: + if (!PyArg_ParseTuple(args,"ii;start,count",&st,&cnt)) + return NULL; + return PyCursesCheckERR(touchline(self->win,st,cnt), "touchline"); + case 3: + if (!PyArg_ParseTuple(args, "iii;start,count,val", &st, &cnt, &val)) + return NULL; + return PyCursesCheckERR(wtouchln(self->win, st, cnt, val), "touchline"); + default: + PyErr_SetString(PyExc_TypeError, "touchline requires 2 or 3 arguments"); + return NULL; + } + } + + static PyObject * + PyCursesWindow_Vline(PyCursesWindowObject *self, PyObject *args) + { + PyObject *temp; + chtype ch; + int n, x, y, code = OK; + attr_t attr = A_NORMAL; + long lattr; + + switch (PyTuple_Size(args)) { + case 2: + if (!PyArg_ParseTuple(args, "Oi;ch or int,n", &temp, &n)) + return NULL; + break; + case 3: + if (!PyArg_ParseTuple(args, "Oil;ch or int,n,attr", &temp, &n, &lattr)) + return NULL; + attr = lattr; + break; + case 4: + if (!PyArg_ParseTuple(args, "iiOi;y,x,ch or int,n", &y, &x, &temp, &n)) + return NULL; + code = wmove(self->win, y, x); + break; + case 5: + if (!PyArg_ParseTuple(args, "iiOil; y,x,ch or int,n,attr", + &y, &x, &temp, &n, &lattr)) + return NULL; + attr = lattr; + code = wmove(self->win, y, x); + break; + default: + PyErr_SetString(PyExc_TypeError, "vline requires 2 to 5 arguments"); + return NULL; + } + + if (code != ERR) { + if (!PyCurses_ConvertToChtype(temp, &ch)) { + PyErr_SetString(PyExc_TypeError, + "argument 1 or 3 must be a ch or an int"); + return NULL; + } + return PyCursesCheckERR(wvline(self->win, ch | attr, n), "vline"); + } else + return PyCursesCheckERR(code, "wmove"); + } + + static PyMethodDef PyCursesWindow_Methods[] = { + {"addch", (PyCFunction)PyCursesWindow_AddCh, METH_VARARGS}, + {"addnstr", (PyCFunction)PyCursesWindow_AddNStr, METH_VARARGS}, + {"addstr", (PyCFunction)PyCursesWindow_AddStr, METH_VARARGS}, + {"attroff", (PyCFunction)PyCursesWindow_AttrOff, METH_VARARGS}, + {"attron", (PyCFunction)PyCursesWindow_AttrOn, METH_VARARGS}, + {"attrset", (PyCFunction)PyCursesWindow_AttrSet, METH_VARARGS}, + {"bkgd", (PyCFunction)PyCursesWindow_Bkgd, METH_VARARGS}, + {"chgat", (PyCFunction)PyCursesWindow_ChgAt, METH_VARARGS}, + {"bkgdset", (PyCFunction)PyCursesWindow_BkgdSet, METH_VARARGS}, + {"border", (PyCFunction)PyCursesWindow_Border, METH_VARARGS}, + {"box", (PyCFunction)PyCursesWindow_Box, METH_VARARGS}, + {"clear", (PyCFunction)PyCursesWindow_wclear, METH_NOARGS}, + {"clearok", (PyCFunction)PyCursesWindow_clearok, METH_VARARGS}, + {"clrtobot", (PyCFunction)PyCursesWindow_wclrtobot, METH_NOARGS}, + {"clrtoeol", (PyCFunction)PyCursesWindow_wclrtoeol, METH_NOARGS}, + {"cursyncup", (PyCFunction)PyCursesWindow_wcursyncup, METH_NOARGS}, + {"delch", (PyCFunction)PyCursesWindow_DelCh, METH_VARARGS}, + {"deleteln", (PyCFunction)PyCursesWindow_wdeleteln, METH_NOARGS}, + {"derwin", (PyCFunction)PyCursesWindow_DerWin, METH_VARARGS}, + {"echochar", (PyCFunction)PyCursesWindow_EchoChar, METH_VARARGS}, #ifdef NCURSES_MOUSE_VERSION - {"enclose", (PyCFunction)PyCursesWindow_Enclose, METH_VARARGS}, + {"enclose", (PyCFunction)PyCursesWindow_Enclose, METH_VARARGS}, #endif - {"erase", (PyCFunction)PyCursesWindow_werase, METH_NOARGS}, - {"getbegyx", (PyCFunction)PyCursesWindow_getbegyx, METH_NOARGS}, - {"getbkgd", (PyCFunction)PyCursesWindow_GetBkgd, METH_NOARGS}, - {"getch", (PyCFunction)PyCursesWindow_GetCh, METH_VARARGS}, - {"getkey", (PyCFunction)PyCursesWindow_GetKey, METH_VARARGS}, - {"getmaxyx", (PyCFunction)PyCursesWindow_getmaxyx, METH_NOARGS}, - {"getparyx", (PyCFunction)PyCursesWindow_getparyx, METH_NOARGS}, - {"getstr", (PyCFunction)PyCursesWindow_GetStr, METH_VARARGS}, - {"getyx", (PyCFunction)PyCursesWindow_getyx, METH_NOARGS}, - {"hline", (PyCFunction)PyCursesWindow_Hline, METH_VARARGS}, - {"idcok", (PyCFunction)PyCursesWindow_idcok, METH_VARARGS}, - {"idlok", (PyCFunction)PyCursesWindow_idlok, METH_VARARGS}, - {"immedok", (PyCFunction)PyCursesWindow_immedok, METH_VARARGS}, - {"inch", (PyCFunction)PyCursesWindow_InCh, METH_VARARGS}, - {"insch", (PyCFunction)PyCursesWindow_InsCh, METH_VARARGS}, - {"insdelln", (PyCFunction)PyCursesWindow_winsdelln, METH_VARARGS}, - {"insertln", (PyCFunction)PyCursesWindow_winsertln, METH_NOARGS}, - {"insnstr", (PyCFunction)PyCursesWindow_InsNStr, METH_VARARGS}, - {"insstr", (PyCFunction)PyCursesWindow_InsStr, METH_VARARGS}, - {"instr", (PyCFunction)PyCursesWindow_InStr, METH_VARARGS}, - {"is_linetouched", (PyCFunction)PyCursesWindow_Is_LineTouched, METH_VARARGS}, - {"is_wintouched", (PyCFunction)PyCursesWindow_is_wintouched, METH_NOARGS}, - {"keypad", (PyCFunction)PyCursesWindow_keypad, METH_VARARGS}, - {"leaveok", (PyCFunction)PyCursesWindow_leaveok, METH_VARARGS}, - {"move", (PyCFunction)PyCursesWindow_wmove, METH_VARARGS}, - {"mvderwin", (PyCFunction)PyCursesWindow_mvderwin, METH_VARARGS}, - {"mvwin", (PyCFunction)PyCursesWindow_mvwin, METH_VARARGS}, - {"nodelay", (PyCFunction)PyCursesWindow_nodelay, METH_VARARGS}, - {"notimeout", (PyCFunction)PyCursesWindow_notimeout, METH_VARARGS}, - {"noutrefresh", (PyCFunction)PyCursesWindow_NoOutRefresh, METH_VARARGS}, - /* Backward compatibility alias -- remove in Python 2.3 */ - {"nooutrefresh", (PyCFunction)PyCursesWindow_NoOutRefresh, METH_VARARGS}, - {"overlay", (PyCFunction)PyCursesWindow_Overlay, METH_VARARGS}, - {"overwrite", (PyCFunction)PyCursesWindow_Overwrite, - METH_VARARGS}, - {"putwin", (PyCFunction)PyCursesWindow_PutWin, METH_O}, - {"redrawln", (PyCFunction)PyCursesWindow_RedrawLine, METH_VARARGS}, - {"redrawwin", (PyCFunction)PyCursesWindow_redrawwin, METH_NOARGS}, - {"refresh", (PyCFunction)PyCursesWindow_Refresh, METH_VARARGS}, + {"erase", (PyCFunction)PyCursesWindow_werase, METH_NOARGS}, + {"getbegyx", (PyCFunction)PyCursesWindow_getbegyx, METH_NOARGS}, + {"getbkgd", (PyCFunction)PyCursesWindow_GetBkgd, METH_NOARGS}, + {"getch", (PyCFunction)PyCursesWindow_GetCh, METH_VARARGS}, + {"getkey", (PyCFunction)PyCursesWindow_GetKey, METH_VARARGS}, + {"getmaxyx", (PyCFunction)PyCursesWindow_getmaxyx, METH_NOARGS}, + {"getparyx", (PyCFunction)PyCursesWindow_getparyx, METH_NOARGS}, + {"getstr", (PyCFunction)PyCursesWindow_GetStr, METH_VARARGS}, + {"getyx", (PyCFunction)PyCursesWindow_getyx, METH_NOARGS}, + {"hline", (PyCFunction)PyCursesWindow_Hline, METH_VARARGS}, + {"idcok", (PyCFunction)PyCursesWindow_idcok, METH_VARARGS}, + {"idlok", (PyCFunction)PyCursesWindow_idlok, METH_VARARGS}, + {"immedok", (PyCFunction)PyCursesWindow_immedok, METH_VARARGS}, + {"inch", (PyCFunction)PyCursesWindow_InCh, METH_VARARGS}, + {"insch", (PyCFunction)PyCursesWindow_InsCh, METH_VARARGS}, + {"insdelln", (PyCFunction)PyCursesWindow_winsdelln, METH_VARARGS}, + {"insertln", (PyCFunction)PyCursesWindow_winsertln, METH_NOARGS}, + {"insnstr", (PyCFunction)PyCursesWindow_InsNStr, METH_VARARGS}, + {"insstr", (PyCFunction)PyCursesWindow_InsStr, METH_VARARGS}, + {"instr", (PyCFunction)PyCursesWindow_InStr, METH_VARARGS}, + {"is_linetouched", (PyCFunction)PyCursesWindow_Is_LineTouched, METH_VARARGS}, + {"is_wintouched", (PyCFunction)PyCursesWindow_is_wintouched, METH_NOARGS}, + {"keypad", (PyCFunction)PyCursesWindow_keypad, METH_VARARGS}, + {"leaveok", (PyCFunction)PyCursesWindow_leaveok, METH_VARARGS}, + {"move", (PyCFunction)PyCursesWindow_wmove, METH_VARARGS}, + {"mvderwin", (PyCFunction)PyCursesWindow_mvderwin, METH_VARARGS}, + {"mvwin", (PyCFunction)PyCursesWindow_mvwin, METH_VARARGS}, + {"nodelay", (PyCFunction)PyCursesWindow_nodelay, METH_VARARGS}, + {"notimeout", (PyCFunction)PyCursesWindow_notimeout, METH_VARARGS}, + {"noutrefresh", (PyCFunction)PyCursesWindow_NoOutRefresh, METH_VARARGS}, + /* Backward compatibility alias -- remove in Python 2.3 */ + {"nooutrefresh", (PyCFunction)PyCursesWindow_NoOutRefresh, METH_VARARGS}, + {"overlay", (PyCFunction)PyCursesWindow_Overlay, METH_VARARGS}, + {"overwrite", (PyCFunction)PyCursesWindow_Overwrite, + METH_VARARGS}, + {"putwin", (PyCFunction)PyCursesWindow_PutWin, METH_O}, + {"redrawln", (PyCFunction)PyCursesWindow_RedrawLine, METH_VARARGS}, + {"redrawwin", (PyCFunction)PyCursesWindow_redrawwin, METH_NOARGS}, + {"refresh", (PyCFunction)PyCursesWindow_Refresh, METH_VARARGS}, #ifndef STRICT_SYSV_CURSES - {"resize", (PyCFunction)PyCursesWindow_wresize, METH_VARARGS}, + {"resize", (PyCFunction)PyCursesWindow_wresize, METH_VARARGS}, #endif - {"scroll", (PyCFunction)PyCursesWindow_Scroll, METH_VARARGS}, - {"scrollok", (PyCFunction)PyCursesWindow_scrollok, METH_VARARGS}, - {"setscrreg", (PyCFunction)PyCursesWindow_SetScrollRegion, METH_VARARGS}, - {"standend", (PyCFunction)PyCursesWindow_wstandend, METH_NOARGS}, - {"standout", (PyCFunction)PyCursesWindow_wstandout, METH_NOARGS}, - {"subpad", (PyCFunction)PyCursesWindow_SubWin, METH_VARARGS}, - {"subwin", (PyCFunction)PyCursesWindow_SubWin, METH_VARARGS}, - {"syncdown", (PyCFunction)PyCursesWindow_wsyncdown, METH_NOARGS}, - {"syncok", (PyCFunction)PyCursesWindow_syncok, METH_VARARGS}, - {"syncup", (PyCFunction)PyCursesWindow_wsyncup, METH_NOARGS}, - {"timeout", (PyCFunction)PyCursesWindow_wtimeout, METH_VARARGS}, - {"touchline", (PyCFunction)PyCursesWindow_TouchLine, METH_VARARGS}, - {"touchwin", (PyCFunction)PyCursesWindow_touchwin, METH_NOARGS}, - {"untouchwin", (PyCFunction)PyCursesWindow_untouchwin, METH_NOARGS}, - {"vline", (PyCFunction)PyCursesWindow_Vline, METH_VARARGS}, - {NULL, NULL} /* sentinel */ -}; + {"scroll", (PyCFunction)PyCursesWindow_Scroll, METH_VARARGS}, + {"scrollok", (PyCFunction)PyCursesWindow_scrollok, METH_VARARGS}, + {"setscrreg", (PyCFunction)PyCursesWindow_SetScrollRegion, METH_VARARGS}, + {"standend", (PyCFunction)PyCursesWindow_wstandend, METH_NOARGS}, + {"standout", (PyCFunction)PyCursesWindow_wstandout, METH_NOARGS}, + {"subpad", (PyCFunction)PyCursesWindow_SubWin, METH_VARARGS}, + {"subwin", (PyCFunction)PyCursesWindow_SubWin, METH_VARARGS}, + {"syncdown", (PyCFunction)PyCursesWindow_wsyncdown, METH_NOARGS}, + {"syncok", (PyCFunction)PyCursesWindow_syncok, METH_VARARGS}, + {"syncup", (PyCFunction)PyCursesWindow_wsyncup, METH_NOARGS}, + {"timeout", (PyCFunction)PyCursesWindow_wtimeout, METH_VARARGS}, + {"touchline", (PyCFunction)PyCursesWindow_TouchLine, METH_VARARGS}, + {"touchwin", (PyCFunction)PyCursesWindow_touchwin, METH_NOARGS}, + {"untouchwin", (PyCFunction)PyCursesWindow_untouchwin, METH_NOARGS}, + {"vline", (PyCFunction)PyCursesWindow_Vline, METH_VARARGS}, + {NULL, NULL} /* sentinel */ + }; /* -------------------------------------------------------*/ -PyTypeObject PyCursesWindow_Type = { - PyVarObject_HEAD_INIT(NULL, 0) - "_curses.curses window", /*tp_name*/ - sizeof(PyCursesWindowObject), /*tp_basicsize*/ - 0, /*tp_itemsize*/ - /* methods */ - (destructor)PyCursesWindow_Dealloc, /*tp_dealloc*/ - 0, /*tp_print*/ - (getattrfunc)0, /*tp_getattr*/ - (setattrfunc)0, /*tp_setattr*/ - 0, /*tp_reserved*/ - 0, /*tp_repr*/ - 0, /*tp_as_number*/ - 0, /*tp_as_sequence*/ - 0, /*tp_as_mapping*/ - 0, /*tp_hash*/ - 0, /*tp_call*/ - 0, /*tp_str*/ - 0, /*tp_getattro*/ - 0, /*tp_setattro*/ - 0, /*tp_as_buffer*/ - Py_TPFLAGS_DEFAULT, /*tp_flags*/ - 0, /*tp_doc*/ - 0, /*tp_traverse*/ - 0, /*tp_clear*/ - 0, /*tp_richcompare*/ - 0, /*tp_weaklistoffset*/ - 0, /*tp_iter*/ - 0, /*tp_iternext*/ - PyCursesWindow_Methods, /*tp_methods*/ -}; + PyTypeObject PyCursesWindow_Type = { + PyVarObject_HEAD_INIT(NULL, 0) + "_curses.curses window", /*tp_name*/ + sizeof(PyCursesWindowObject), /*tp_basicsize*/ + 0, /*tp_itemsize*/ + /* methods */ + (destructor)PyCursesWindow_Dealloc, /*tp_dealloc*/ + 0, /*tp_print*/ + (getattrfunc)0, /*tp_getattr*/ + (setattrfunc)0, /*tp_setattr*/ + 0, /*tp_reserved*/ + 0, /*tp_repr*/ + 0, /*tp_as_number*/ + 0, /*tp_as_sequence*/ + 0, /*tp_as_mapping*/ + 0, /*tp_hash*/ + 0, /*tp_call*/ + 0, /*tp_str*/ + 0, /*tp_getattro*/ + 0, /*tp_setattro*/ + 0, /*tp_as_buffer*/ + Py_TPFLAGS_DEFAULT, /*tp_flags*/ + 0, /*tp_doc*/ + 0, /*tp_traverse*/ + 0, /*tp_clear*/ + 0, /*tp_richcompare*/ + 0, /*tp_weaklistoffset*/ + 0, /*tp_iter*/ + 0, /*tp_iternext*/ + PyCursesWindow_Methods, /*tp_methods*/ + }; /********************************************************************* Global Functions **********************************************************************/ -NoArgNoReturnFunction(beep) -NoArgNoReturnFunction(def_prog_mode) -NoArgNoReturnFunction(def_shell_mode) -NoArgNoReturnFunction(doupdate) -NoArgNoReturnFunction(endwin) -NoArgNoReturnFunction(flash) -NoArgNoReturnFunction(nocbreak) -NoArgNoReturnFunction(noecho) -NoArgNoReturnFunction(nonl) -NoArgNoReturnFunction(noraw) -NoArgNoReturnFunction(reset_prog_mode) -NoArgNoReturnFunction(reset_shell_mode) -NoArgNoReturnFunction(resetty) -NoArgNoReturnFunction(savetty) + NoArgNoReturnFunction(beep) + NoArgNoReturnFunction(def_prog_mode) + NoArgNoReturnFunction(def_shell_mode) + NoArgNoReturnFunction(doupdate) + NoArgNoReturnFunction(endwin) + NoArgNoReturnFunction(flash) + NoArgNoReturnFunction(nocbreak) + NoArgNoReturnFunction(noecho) + NoArgNoReturnFunction(nonl) + NoArgNoReturnFunction(noraw) + NoArgNoReturnFunction(reset_prog_mode) + NoArgNoReturnFunction(reset_shell_mode) + NoArgNoReturnFunction(resetty) + NoArgNoReturnFunction(savetty) + + NoArgOrFlagNoReturnFunction(cbreak) + NoArgOrFlagNoReturnFunction(echo) + NoArgOrFlagNoReturnFunction(nl) + NoArgOrFlagNoReturnFunction(raw) + + NoArgReturnIntFunction(baudrate) + NoArgReturnIntFunction(termattrs) + + NoArgReturnStringFunction(termname) + NoArgReturnStringFunction(longname) + + NoArgTrueFalseFunction(can_change_color) + NoArgTrueFalseFunction(has_colors) + NoArgTrueFalseFunction(has_ic) + NoArgTrueFalseFunction(has_il) + NoArgTrueFalseFunction(isendwin) + NoArgNoReturnVoidFunction(flushinp) + NoArgNoReturnVoidFunction(noqiflush) + + static PyObject * + PyCurses_filter(PyObject *self) + { + /* not checking for PyCursesInitialised here since filter() must + be called before initscr() */ + filter(); + Py_INCREF(Py_None); + return Py_None; + } + + static PyObject * + PyCurses_Color_Content(PyObject *self, PyObject *args) + { + short color,r,g,b; + + PyCursesInitialised + PyCursesInitialisedColor + + if (!PyArg_ParseTuple(args, "h:color_content", &color)) return NULL; + + if (color_content(color, &r, &g, &b) != ERR) + return Py_BuildValue("(iii)", r, g, b); + else { + PyErr_SetString(PyCursesError, + "Argument 1 was out of range. Check value of COLORS."); + return NULL; + } + } + + static PyObject * + PyCurses_color_pair(PyObject *self, PyObject *args) + { + int n; + + PyCursesInitialised + PyCursesInitialisedColor + + if (!PyArg_ParseTuple(args, "i:color_pair", &n)) return NULL; + return PyLong_FromLong((long) (n << 8)); + } + + static PyObject * + PyCurses_Curs_Set(PyObject *self, PyObject *args) + { + int vis,erg; + + PyCursesInitialised + + if (!PyArg_ParseTuple(args, "i:curs_set", &vis)) return NULL; + + erg = curs_set(vis); + if (erg == ERR) return PyCursesCheckERR(erg, "curs_set"); + + return PyLong_FromLong((long) erg); + } + + static PyObject * + PyCurses_Delay_Output(PyObject *self, PyObject *args) + { + int ms; + + PyCursesInitialised + + if (!PyArg_ParseTuple(args, "i:delay_output", &ms)) return NULL; + + return PyCursesCheckERR(delay_output(ms), "delay_output"); + } + + static PyObject * + PyCurses_EraseChar(PyObject *self) + { + char ch; + + PyCursesInitialised + + ch = erasechar(); + + return PyBytes_FromStringAndSize(&ch, 1); + } + + static PyObject * + PyCurses_getsyx(PyObject *self) + { + int x = 0; + int y = 0; -NoArgOrFlagNoReturnFunction(cbreak) -NoArgOrFlagNoReturnFunction(echo) -NoArgOrFlagNoReturnFunction(nl) -NoArgOrFlagNoReturnFunction(raw) + PyCursesInitialised -NoArgReturnIntFunction(baudrate) -NoArgReturnIntFunction(termattrs) + getsyx(y, x); -NoArgReturnStringFunction(termname) -NoArgReturnStringFunction(longname) - -NoArgTrueFalseFunction(can_change_color) -NoArgTrueFalseFunction(has_colors) -NoArgTrueFalseFunction(has_ic) -NoArgTrueFalseFunction(has_il) -NoArgTrueFalseFunction(isendwin) -NoArgNoReturnVoidFunction(flushinp) -NoArgNoReturnVoidFunction(noqiflush) - -static PyObject * -PyCurses_filter(PyObject *self) -{ - /* not checking for PyCursesInitialised here since filter() must - be called before initscr() */ - filter(); - Py_INCREF(Py_None); - return Py_None; -} - -static PyObject * -PyCurses_Color_Content(PyObject *self, PyObject *args) -{ - short color,r,g,b; - - PyCursesInitialised - PyCursesInitialisedColor - - if (!PyArg_ParseTuple(args, "h:color_content", &color)) return NULL; - - if (color_content(color, &r, &g, &b) != ERR) - return Py_BuildValue("(iii)", r, g, b); - else { - PyErr_SetString(PyCursesError, - "Argument 1 was out of range. Check value of COLORS."); - return NULL; - } -} - -static PyObject * -PyCurses_color_pair(PyObject *self, PyObject *args) -{ - int n; - - PyCursesInitialised - PyCursesInitialisedColor - - if (!PyArg_ParseTuple(args, "i:color_pair", &n)) return NULL; - return PyLong_FromLong((long) (n << 8)); -} - -static PyObject * -PyCurses_Curs_Set(PyObject *self, PyObject *args) -{ - int vis,erg; - - PyCursesInitialised - - if (!PyArg_ParseTuple(args, "i:curs_set", &vis)) return NULL; - - erg = curs_set(vis); - if (erg == ERR) return PyCursesCheckERR(erg, "curs_set"); - - return PyLong_FromLong((long) erg); -} - -static PyObject * -PyCurses_Delay_Output(PyObject *self, PyObject *args) -{ - int ms; - - PyCursesInitialised - - if (!PyArg_ParseTuple(args, "i:delay_output", &ms)) return NULL; - - return PyCursesCheckERR(delay_output(ms), "delay_output"); -} - -static PyObject * -PyCurses_EraseChar(PyObject *self) -{ - char ch; - - PyCursesInitialised - - ch = erasechar(); - - return PyBytes_FromStringAndSize(&ch, 1); -} - -static PyObject * -PyCurses_getsyx(PyObject *self) -{ - int x = 0; - int y = 0; - - PyCursesInitialised - - getsyx(y, x); - - return Py_BuildValue("(ii)", y, x); -} + return Py_BuildValue("(ii)", y, x); + } #ifdef NCURSES_MOUSE_VERSION -static PyObject * -PyCurses_GetMouse(PyObject *self) -{ - int rtn; - MEVENT event; + static PyObject * + PyCurses_GetMouse(PyObject *self) + { + int rtn; + MEVENT event; + + PyCursesInitialised + + rtn = getmouse( &event ); + if (rtn == ERR) { + PyErr_SetString(PyCursesError, "getmouse() returned ERR"); + return NULL; + } + return Py_BuildValue("(hiiil)", + (short)event.id, + event.x, event.y, event.z, + (long) event.bstate); + } + + static PyObject * + PyCurses_UngetMouse(PyObject *self, PyObject *args) + { + MEVENT event; + + PyCursesInitialised + if (!PyArg_ParseTuple(args, "hiiil", + &event.id, + &event.x, &event.y, &event.z, + (int *) &event.bstate)) + return NULL; + + return PyCursesCheckERR(ungetmouse(&event), "ungetmouse"); + } +#endif + + static PyObject * + PyCurses_GetWin(PyCursesWindowObject *self, PyObject *stream) + { + char fn[100]; + int fd; + FILE *fp; + PyObject *data; + size_t datalen; + WINDOW *win; + + PyCursesInitialised + + strcpy(fn, "/tmp/py.curses.getwin.XXXXXX"); + fd = mkstemp(fn); + if (fd < 0) + return PyErr_SetFromErrnoWithFilename(PyExc_IOError, fn); + fp = fdopen(fd, "wb+"); + if (fp == NULL) { + close(fd); + remove(fn); + return PyErr_SetFromErrnoWithFilename(PyExc_IOError, fn); + } + data = PyObject_CallMethod(stream, "read", ""); + if (data == NULL) { + fclose(fp); + remove(fn); + return NULL; + } + if (!PyBytes_Check(data)) { + PyErr_Format(PyExc_TypeError, + "f.read() returned %.100s instead of bytes", + data->ob_type->tp_name); + Py_DECREF(data); + fclose(fp); + remove(fn); + return NULL; + } + datalen = PyBytes_GET_SIZE(data); + if (fwrite(PyBytes_AS_STRING(data), 1, datalen, fp) != datalen) { + Py_DECREF(data); + fclose(fp); + remove(fn); + return PyErr_SetFromErrnoWithFilename(PyExc_IOError, fn); + } + Py_DECREF(data); + fseek(fp, 0, 0); + win = getwin(fp); + fclose(fp); + remove(fn); + if (win == NULL) { + PyErr_SetString(PyCursesError, catchall_NULL); + return NULL; + } + return PyCursesWindow_New(win); + } + + static PyObject * + PyCurses_HalfDelay(PyObject *self, PyObject *args) + { + unsigned char tenths; - PyCursesInitialised + PyCursesInitialised - rtn = getmouse( &event ); - if (rtn == ERR) { - PyErr_SetString(PyCursesError, "getmouse() returned ERR"); - return NULL; - } - return Py_BuildValue("(hiiil)", - (short)event.id, - event.x, event.y, event.z, - (long) event.bstate); -} - -static PyObject * -PyCurses_UngetMouse(PyObject *self, PyObject *args) -{ - MEVENT event; - - PyCursesInitialised - if (!PyArg_ParseTuple(args, "hiiil", - &event.id, - &event.x, &event.y, &event.z, - (int *) &event.bstate)) - return NULL; - - return PyCursesCheckERR(ungetmouse(&event), "ungetmouse"); -} -#endif - -static PyObject * -PyCurses_GetWin(PyCursesWindowObject *self, PyObject *stream) -{ - char fn[100]; - int fd; - FILE *fp; - PyObject *data; - size_t datalen; - WINDOW *win; - - PyCursesInitialised - - strcpy(fn, "/tmp/py.curses.getwin.XXXXXX"); - fd = mkstemp(fn); - if (fd < 0) - return PyErr_SetFromErrnoWithFilename(PyExc_IOError, fn); - fp = fdopen(fd, "wb+"); - if (fp == NULL) { - close(fd); - remove(fn); - return PyErr_SetFromErrnoWithFilename(PyExc_IOError, fn); - } - data = PyObject_CallMethod(stream, "read", ""); - if (data == NULL) { - fclose(fp); - remove(fn); - return NULL; - } - if (!PyBytes_Check(data)) { - PyErr_Format(PyExc_TypeError, - "f.read() returned %.100s instead of bytes", - data->ob_type->tp_name); - Py_DECREF(data); - fclose(fp); - remove(fn); - return NULL; - } - datalen = PyBytes_GET_SIZE(data); - if (fwrite(PyBytes_AS_STRING(data), 1, datalen, fp) != datalen) { - Py_DECREF(data); - fclose(fp); - remove(fn); - return PyErr_SetFromErrnoWithFilename(PyExc_IOError, fn); - } - Py_DECREF(data); - fseek(fp, 0, 0); - win = getwin(fp); - fclose(fp); - remove(fn); - if (win == NULL) { - PyErr_SetString(PyCursesError, catchall_NULL); - return NULL; - } - return PyCursesWindow_New(win); -} - -static PyObject * -PyCurses_HalfDelay(PyObject *self, PyObject *args) -{ - unsigned char tenths; - - PyCursesInitialised + if (!PyArg_ParseTuple(args, "b:halfdelay", &tenths)) return NULL; - if (!PyArg_ParseTuple(args, "b:halfdelay", &tenths)) return NULL; - - return PyCursesCheckERR(halfdelay(tenths), "halfdelay"); -} + return PyCursesCheckERR(halfdelay(tenths), "halfdelay"); + } #ifndef STRICT_SYSV_CURSES - /* No has_key! */ -static PyObject * PyCurses_has_key(PyObject *self, PyObject *args) -{ - int ch; - - PyCursesInitialised - - if (!PyArg_ParseTuple(args,"i",&ch)) return NULL; - - if (has_key(ch) == FALSE) { - Py_INCREF(Py_False); - return Py_False; - } - Py_INCREF(Py_True); - return Py_True; -} + /* No has_key! */ + static PyObject * PyCurses_has_key(PyObject *self, PyObject *args) + { + int ch; + + PyCursesInitialised + + if (!PyArg_ParseTuple(args,"i",&ch)) return NULL; + + if (has_key(ch) == FALSE) { + Py_INCREF(Py_False); + return Py_False; + } + Py_INCREF(Py_True); + return Py_True; + } #endif /* STRICT_SYSV_CURSES */ -static PyObject * -PyCurses_Init_Color(PyObject *self, PyObject *args) -{ - short color, r, g, b; - - PyCursesInitialised - PyCursesInitialisedColor - - switch(PyTuple_Size(args)) { - case 4: - if (!PyArg_ParseTuple(args, "hhhh;color,r,g,b", &color, &r, &g, &b)) return NULL; - break; - default: - PyErr_SetString(PyExc_TypeError, "init_color requires 4 arguments"); - return NULL; - } - - return PyCursesCheckERR(init_color(color, r, g, b), "init_color"); -} - -static PyObject * -PyCurses_Init_Pair(PyObject *self, PyObject *args) -{ - short pair, f, b; - - PyCursesInitialised - PyCursesInitialisedColor - - if (PyTuple_Size(args) != 3) { - PyErr_SetString(PyExc_TypeError, "init_pair requires 3 arguments"); - return NULL; - } - - if (!PyArg_ParseTuple(args, "hhh;pair, f, b", &pair, &f, &b)) return NULL; - - return PyCursesCheckERR(init_pair(pair, f, b), "init_pair"); -} - -static PyObject *ModDict; + static PyObject * + PyCurses_Init_Color(PyObject *self, PyObject *args) + { + short color, r, g, b; + + PyCursesInitialised + PyCursesInitialisedColor + + switch(PyTuple_Size(args)) { + case 4: + if (!PyArg_ParseTuple(args, "hhhh;color,r,g,b", &color, &r, &g, &b)) return NULL; + break; + default: + PyErr_SetString(PyExc_TypeError, "init_color requires 4 arguments"); + return NULL; + } + + return PyCursesCheckERR(init_color(color, r, g, b), "init_color"); + } + + static PyObject * + PyCurses_Init_Pair(PyObject *self, PyObject *args) + { + short pair, f, b; + + PyCursesInitialised + PyCursesInitialisedColor + + if (PyTuple_Size(args) != 3) { + PyErr_SetString(PyExc_TypeError, "init_pair requires 3 arguments"); + return NULL; + } + + if (!PyArg_ParseTuple(args, "hhh;pair, f, b", &pair, &f, &b)) return NULL; + + return PyCursesCheckERR(init_pair(pair, f, b), "init_pair"); + } + + static PyObject *ModDict; + + static PyObject * + PyCurses_InitScr(PyObject *self) + { + WINDOW *win; + + if (initialised == TRUE) { + wrefresh(stdscr); + return (PyObject *)PyCursesWindow_New(stdscr); + } + + win = initscr(); + + if (win == NULL) { + PyErr_SetString(PyCursesError, catchall_NULL); + return NULL; + } -static PyObject * -PyCurses_InitScr(PyObject *self) -{ - WINDOW *win; - - if (initialised == TRUE) { - wrefresh(stdscr); - return (PyObject *)PyCursesWindow_New(stdscr); - } - - win = initscr(); - - if (win == NULL) { - PyErr_SetString(PyCursesError, catchall_NULL); - return NULL; - } - - initialised = initialised_setupterm = TRUE; + initialised = initialised_setupterm = TRUE; /* This was moved from initcurses() because it core dumped on SGI, where they're not defined until you've called initscr() */ -#define SetDictInt(string,ch) \ - do { \ - PyObject *o = PyLong_FromLong((long) (ch)); \ - if (o && PyDict_SetItemString(ModDict, string, o) == 0) { \ - Py_DECREF(o); \ - } \ - } while (0) - - /* Here are some graphic symbols you can use */ - SetDictInt("ACS_ULCORNER", (ACS_ULCORNER)); - SetDictInt("ACS_LLCORNER", (ACS_LLCORNER)); - SetDictInt("ACS_URCORNER", (ACS_URCORNER)); - SetDictInt("ACS_LRCORNER", (ACS_LRCORNER)); - SetDictInt("ACS_LTEE", (ACS_LTEE)); - SetDictInt("ACS_RTEE", (ACS_RTEE)); - SetDictInt("ACS_BTEE", (ACS_BTEE)); - SetDictInt("ACS_TTEE", (ACS_TTEE)); - SetDictInt("ACS_HLINE", (ACS_HLINE)); - SetDictInt("ACS_VLINE", (ACS_VLINE)); - SetDictInt("ACS_PLUS", (ACS_PLUS)); +#define SetDictInt(string,ch) \ + do { \ + PyObject *o = PyLong_FromLong((long) (ch)); \ + if (o && PyDict_SetItemString(ModDict, string, o) == 0) { \ + Py_DECREF(o); \ + } \ + } while (0) + + /* Here are some graphic symbols you can use */ + SetDictInt("ACS_ULCORNER", (ACS_ULCORNER)); + SetDictInt("ACS_LLCORNER", (ACS_LLCORNER)); + SetDictInt("ACS_URCORNER", (ACS_URCORNER)); + SetDictInt("ACS_LRCORNER", (ACS_LRCORNER)); + SetDictInt("ACS_LTEE", (ACS_LTEE)); + SetDictInt("ACS_RTEE", (ACS_RTEE)); + SetDictInt("ACS_BTEE", (ACS_BTEE)); + SetDictInt("ACS_TTEE", (ACS_TTEE)); + SetDictInt("ACS_HLINE", (ACS_HLINE)); + SetDictInt("ACS_VLINE", (ACS_VLINE)); + SetDictInt("ACS_PLUS", (ACS_PLUS)); #if !defined(__hpux) || defined(HAVE_NCURSES_H) - /* On HP/UX 11, these are of type cchar_t, which is not an - integral type. If this is a problem on more platforms, a - configure test should be added to determine whether ACS_S1 - is of integral type. */ - SetDictInt("ACS_S1", (ACS_S1)); - SetDictInt("ACS_S9", (ACS_S9)); - SetDictInt("ACS_DIAMOND", (ACS_DIAMOND)); - SetDictInt("ACS_CKBOARD", (ACS_CKBOARD)); - SetDictInt("ACS_DEGREE", (ACS_DEGREE)); - SetDictInt("ACS_PLMINUS", (ACS_PLMINUS)); - SetDictInt("ACS_BULLET", (ACS_BULLET)); - SetDictInt("ACS_LARROW", (ACS_LARROW)); - SetDictInt("ACS_RARROW", (ACS_RARROW)); - SetDictInt("ACS_DARROW", (ACS_DARROW)); - SetDictInt("ACS_UARROW", (ACS_UARROW)); - SetDictInt("ACS_BOARD", (ACS_BOARD)); - SetDictInt("ACS_LANTERN", (ACS_LANTERN)); - SetDictInt("ACS_BLOCK", (ACS_BLOCK)); -#endif - SetDictInt("ACS_BSSB", (ACS_ULCORNER)); - SetDictInt("ACS_SSBB", (ACS_LLCORNER)); - SetDictInt("ACS_BBSS", (ACS_URCORNER)); - SetDictInt("ACS_SBBS", (ACS_LRCORNER)); - SetDictInt("ACS_SBSS", (ACS_RTEE)); - SetDictInt("ACS_SSSB", (ACS_LTEE)); - SetDictInt("ACS_SSBS", (ACS_BTEE)); - SetDictInt("ACS_BSSS", (ACS_TTEE)); - SetDictInt("ACS_BSBS", (ACS_HLINE)); - SetDictInt("ACS_SBSB", (ACS_VLINE)); - SetDictInt("ACS_SSSS", (ACS_PLUS)); + /* On HP/UX 11, these are of type cchar_t, which is not an + integral type. If this is a problem on more platforms, a + configure test should be added to determine whether ACS_S1 + is of integral type. */ + SetDictInt("ACS_S1", (ACS_S1)); + SetDictInt("ACS_S9", (ACS_S9)); + SetDictInt("ACS_DIAMOND", (ACS_DIAMOND)); + SetDictInt("ACS_CKBOARD", (ACS_CKBOARD)); + SetDictInt("ACS_DEGREE", (ACS_DEGREE)); + SetDictInt("ACS_PLMINUS", (ACS_PLMINUS)); + SetDictInt("ACS_BULLET", (ACS_BULLET)); + SetDictInt("ACS_LARROW", (ACS_LARROW)); + SetDictInt("ACS_RARROW", (ACS_RARROW)); + SetDictInt("ACS_DARROW", (ACS_DARROW)); + SetDictInt("ACS_UARROW", (ACS_UARROW)); + SetDictInt("ACS_BOARD", (ACS_BOARD)); + SetDictInt("ACS_LANTERN", (ACS_LANTERN)); + SetDictInt("ACS_BLOCK", (ACS_BLOCK)); +#endif + SetDictInt("ACS_BSSB", (ACS_ULCORNER)); + SetDictInt("ACS_SSBB", (ACS_LLCORNER)); + SetDictInt("ACS_BBSS", (ACS_URCORNER)); + SetDictInt("ACS_SBBS", (ACS_LRCORNER)); + SetDictInt("ACS_SBSS", (ACS_RTEE)); + SetDictInt("ACS_SSSB", (ACS_LTEE)); + SetDictInt("ACS_SSBS", (ACS_BTEE)); + SetDictInt("ACS_BSSS", (ACS_TTEE)); + SetDictInt("ACS_BSBS", (ACS_HLINE)); + SetDictInt("ACS_SBSB", (ACS_VLINE)); + SetDictInt("ACS_SSSS", (ACS_PLUS)); - /* The following are never available with strict SYSV curses */ + /* The following are never available with strict SYSV curses */ #ifdef ACS_S3 - SetDictInt("ACS_S3", (ACS_S3)); + SetDictInt("ACS_S3", (ACS_S3)); #endif #ifdef ACS_S7 - SetDictInt("ACS_S7", (ACS_S7)); + SetDictInt("ACS_S7", (ACS_S7)); #endif #ifdef ACS_LEQUAL - SetDictInt("ACS_LEQUAL", (ACS_LEQUAL)); + SetDictInt("ACS_LEQUAL", (ACS_LEQUAL)); #endif #ifdef ACS_GEQUAL - SetDictInt("ACS_GEQUAL", (ACS_GEQUAL)); + SetDictInt("ACS_GEQUAL", (ACS_GEQUAL)); #endif #ifdef ACS_PI - SetDictInt("ACS_PI", (ACS_PI)); + SetDictInt("ACS_PI", (ACS_PI)); #endif #ifdef ACS_NEQUAL - SetDictInt("ACS_NEQUAL", (ACS_NEQUAL)); + SetDictInt("ACS_NEQUAL", (ACS_NEQUAL)); #endif #ifdef ACS_STERLING - SetDictInt("ACS_STERLING", (ACS_STERLING)); + SetDictInt("ACS_STERLING", (ACS_STERLING)); #endif - SetDictInt("LINES", LINES); - SetDictInt("COLS", COLS); + SetDictInt("LINES", LINES); + SetDictInt("COLS", COLS); - return (PyObject *)PyCursesWindow_New(win); -} + return (PyObject *)PyCursesWindow_New(win); + } -static PyObject * -PyCurses_setupterm(PyObject* self, PyObject *args, PyObject* keywds) -{ - int fd = -1; - int err; - char* termstr = NULL; + static PyObject * + PyCurses_setupterm(PyObject* self, PyObject *args, PyObject* keywds) + { + int fd = -1; + int err; + char* termstr = NULL; - static char *kwlist[] = {"term", "fd", NULL}; + static char *kwlist[] = {"term", "fd", NULL}; - if (!PyArg_ParseTupleAndKeywords( - args, keywds, "|zi:setupterm", kwlist, &termstr, &fd)) { - return NULL; - } - - if (fd == -1) { - PyObject* sys_stdout; + if (!PyArg_ParseTupleAndKeywords( + args, keywds, "|zi:setupterm", kwlist, &termstr, &fd)) { + return NULL; + } - sys_stdout = PySys_GetObject("stdout"); + if (fd == -1) { + PyObject* sys_stdout; - if (sys_stdout == NULL || sys_stdout == Py_None) { - PyErr_SetString( - PyCursesError, - "lost sys.stdout"); - return NULL; - } + sys_stdout = PySys_GetObject("stdout"); - fd = PyObject_AsFileDescriptor(sys_stdout); + if (sys_stdout == NULL || sys_stdout == Py_None) { + PyErr_SetString( + PyCursesError, + "lost sys.stdout"); + return NULL; + } - if (fd == -1) { - return NULL; - } - } + fd = PyObject_AsFileDescriptor(sys_stdout); - if (setupterm(termstr,fd,&err) == ERR) { - char* s = "setupterm: unknown error"; - - if (err == 0) { - s = "setupterm: could not find terminal"; - } else if (err == -1) { - s = "setupterm: could not find terminfo database"; - } + if (fd == -1) { + return NULL; + } + } - PyErr_SetString(PyCursesError,s); - return NULL; - } + if (setupterm(termstr,fd,&err) == ERR) { + char* s = "setupterm: unknown error"; - initialised_setupterm = TRUE; + if (err == 0) { + s = "setupterm: could not find terminal"; + } else if (err == -1) { + s = "setupterm: could not find terminfo database"; + } - Py_INCREF(Py_None); - return Py_None; -} + PyErr_SetString(PyCursesError,s); + return NULL; + } -static PyObject * -PyCurses_IntrFlush(PyObject *self, PyObject *args) -{ - int ch; + initialised_setupterm = TRUE; - PyCursesInitialised + Py_INCREF(Py_None); + return Py_None; + } - switch(PyTuple_Size(args)) { - case 1: - if (!PyArg_ParseTuple(args,"i;True(1), False(0)",&ch)) return NULL; - break; - default: - PyErr_SetString(PyExc_TypeError, "intrflush requires 1 argument"); - return NULL; - } + static PyObject * + PyCurses_IntrFlush(PyObject *self, PyObject *args) + { + int ch; - return PyCursesCheckERR(intrflush(NULL,ch), "intrflush"); -} + PyCursesInitialised + + switch(PyTuple_Size(args)) { + case 1: + if (!PyArg_ParseTuple(args,"i;True(1), False(0)",&ch)) return NULL; + break; + default: + PyErr_SetString(PyExc_TypeError, "intrflush requires 1 argument"); + return NULL; + } + + return PyCursesCheckERR(intrflush(NULL,ch), "intrflush"); + } #ifdef HAVE_CURSES_IS_TERM_RESIZED -static PyObject * -PyCurses_Is_Term_Resized(PyObject *self, PyObject *args) -{ - int lines; - int columns; - int result; - - PyCursesInitialised - - if (!PyArg_ParseTuple(args,"ii:is_term_resized", &lines, &columns)) - return NULL; - result = is_term_resized(lines, columns); - if (result == TRUE) { - Py_INCREF(Py_True); - return Py_True; - } else { - Py_INCREF(Py_False); - return Py_False; - } -} + static PyObject * + PyCurses_Is_Term_Resized(PyObject *self, PyObject *args) + { + int lines; + int columns; + int result; + + PyCursesInitialised + + if (!PyArg_ParseTuple(args,"ii:is_term_resized", &lines, &columns)) + return NULL; + result = is_term_resized(lines, columns); + if (result == TRUE) { + Py_INCREF(Py_True); + return Py_True; + } else { + Py_INCREF(Py_False); + return Py_False; + } + } #endif /* HAVE_CURSES_IS_TERM_RESIZED */ #if !defined(__NetBSD__) -static PyObject * -PyCurses_KeyName(PyObject *self, PyObject *args) -{ - const char *knp; - int ch; - - PyCursesInitialised - - if (!PyArg_ParseTuple(args,"i",&ch)) return NULL; - - if (ch < 0) { - PyErr_SetString(PyExc_ValueError, "invalid key number"); - return NULL; - } - knp = keyname(ch); - - return PyBytes_FromString((knp == NULL) ? "" : (char *)knp); -} -#endif - -static PyObject * -PyCurses_KillChar(PyObject *self) -{ - char ch; - - ch = killchar(); - - return PyBytes_FromStringAndSize(&ch, 1); -} - -static PyObject * -PyCurses_Meta(PyObject *self, PyObject *args) -{ - int ch; - - PyCursesInitialised + static PyObject * + PyCurses_KeyName(PyObject *self, PyObject *args) + { + const char *knp; + int ch; + + PyCursesInitialised + + if (!PyArg_ParseTuple(args,"i",&ch)) return NULL; + + if (ch < 0) { + PyErr_SetString(PyExc_ValueError, "invalid key number"); + return NULL; + } + knp = keyname(ch); + + return PyBytes_FromString((knp == NULL) ? "" : (char *)knp); + } +#endif + + static PyObject * + PyCurses_KillChar(PyObject *self) + { + char ch; + + ch = killchar(); + + return PyBytes_FromStringAndSize(&ch, 1); + } + + static PyObject * + PyCurses_Meta(PyObject *self, PyObject *args) + { + int ch; + + PyCursesInitialised + + switch(PyTuple_Size(args)) { + case 1: + if (!PyArg_ParseTuple(args,"i;True(1), False(0)",&ch)) return NULL; + break; + default: + PyErr_SetString(PyExc_TypeError, "meta requires 1 argument"); + return NULL; + } - switch(PyTuple_Size(args)) { - case 1: - if (!PyArg_ParseTuple(args,"i;True(1), False(0)",&ch)) return NULL; - break; - default: - PyErr_SetString(PyExc_TypeError, "meta requires 1 argument"); - return NULL; - } - - return PyCursesCheckERR(meta(stdscr, ch), "meta"); -} + return PyCursesCheckERR(meta(stdscr, ch), "meta"); + } #ifdef NCURSES_MOUSE_VERSION -static PyObject * -PyCurses_MouseInterval(PyObject *self, PyObject *args) -{ - int interval; - PyCursesInitialised - - if (!PyArg_ParseTuple(args,"i;interval",&interval)) - return NULL; - return PyCursesCheckERR(mouseinterval(interval), "mouseinterval"); -} - -static PyObject * -PyCurses_MouseMask(PyObject *self, PyObject *args) -{ - int newmask; - mmask_t oldmask, availmask; - - PyCursesInitialised - if (!PyArg_ParseTuple(args,"i;mousemask",&newmask)) - return NULL; - availmask = mousemask(newmask, &oldmask); - return Py_BuildValue("(ll)", (long)availmask, (long)oldmask); -} -#endif - -static PyObject * -PyCurses_Napms(PyObject *self, PyObject *args) -{ - int ms; - - PyCursesInitialised - if (!PyArg_ParseTuple(args, "i;ms", &ms)) return NULL; - - return Py_BuildValue("i", napms(ms)); -} - - -static PyObject * -PyCurses_NewPad(PyObject *self, PyObject *args) -{ - WINDOW *win; - int nlines, ncols; - - PyCursesInitialised - - if (!PyArg_ParseTuple(args,"ii;nlines,ncols",&nlines,&ncols)) return NULL; - - win = newpad(nlines, ncols); - - if (win == NULL) { - PyErr_SetString(PyCursesError, catchall_NULL); - return NULL; - } - - return (PyObject *)PyCursesWindow_New(win); -} - -static PyObject * -PyCurses_NewWindow(PyObject *self, PyObject *args) -{ - WINDOW *win; - int nlines, ncols, begin_y=0, begin_x=0; - - PyCursesInitialised - - switch (PyTuple_Size(args)) { - case 2: - if (!PyArg_ParseTuple(args,"ii;nlines,ncols",&nlines,&ncols)) - return NULL; - break; - case 4: - if (!PyArg_ParseTuple(args, "iiii;nlines,ncols,begin_y,begin_x", - &nlines,&ncols,&begin_y,&begin_x)) - return NULL; - break; - default: - PyErr_SetString(PyExc_TypeError, "newwin requires 2 or 4 arguments"); - return NULL; - } - - win = newwin(nlines,ncols,begin_y,begin_x); - if (win == NULL) { - PyErr_SetString(PyCursesError, catchall_NULL); - return NULL; - } - - return (PyObject *)PyCursesWindow_New(win); -} - -static PyObject * -PyCurses_Pair_Content(PyObject *self, PyObject *args) -{ - short pair,f,b; - - PyCursesInitialised - PyCursesInitialisedColor - - switch(PyTuple_Size(args)) { - case 1: - if (!PyArg_ParseTuple(args, "h;pair", &pair)) return NULL; - break; - default: - PyErr_SetString(PyExc_TypeError, "pair_content requires 1 argument"); - return NULL; - } - - if (pair_content(pair, &f, &b)==ERR) { - PyErr_SetString(PyCursesError, - "Argument 1 was out of range. (1..COLOR_PAIRS-1)"); - return NULL; - } - - return Py_BuildValue("(ii)", f, b); -} - -static PyObject * -PyCurses_pair_number(PyObject *self, PyObject *args) -{ - int n; - - PyCursesInitialised - PyCursesInitialisedColor - - switch(PyTuple_Size(args)) { - case 1: - if (!PyArg_ParseTuple(args, "i;pairvalue", &n)) return NULL; - break; - default: - PyErr_SetString(PyExc_TypeError, - "pair_number requires 1 argument"); - return NULL; - } - - return PyLong_FromLong((long) ((n & A_COLOR) >> 8)); -} - -static PyObject * -PyCurses_Putp(PyObject *self, PyObject *args) -{ - char *str; - - if (!PyArg_ParseTuple(args,"s;str", &str)) return NULL; - return PyCursesCheckERR(putp(str), "putp"); -} - -static PyObject * -PyCurses_QiFlush(PyObject *self, PyObject *args) -{ - int flag = 0; - - PyCursesInitialised - - switch(PyTuple_Size(args)) { - case 0: - qiflush(); - Py_INCREF(Py_None); - return Py_None; - case 1: - if (!PyArg_ParseTuple(args, "i;True(1) or False(0)", &flag)) return NULL; - if (flag) qiflush(); - else noqiflush(); - Py_INCREF(Py_None); - return Py_None; - default: - PyErr_SetString(PyExc_TypeError, "qiflush requires 0 or 1 arguments"); - return NULL; - } -} + static PyObject * + PyCurses_MouseInterval(PyObject *self, PyObject *args) + { + int interval; + PyCursesInitialised + + if (!PyArg_ParseTuple(args,"i;interval",&interval)) + return NULL; + return PyCursesCheckERR(mouseinterval(interval), "mouseinterval"); + } + + static PyObject * + PyCurses_MouseMask(PyObject *self, PyObject *args) + { + int newmask; + mmask_t oldmask, availmask; + + PyCursesInitialised + if (!PyArg_ParseTuple(args,"i;mousemask",&newmask)) + return NULL; + availmask = mousemask(newmask, &oldmask); + return Py_BuildValue("(ll)", (long)availmask, (long)oldmask); + } +#endif + + static PyObject * + PyCurses_Napms(PyObject *self, PyObject *args) + { + int ms; + + PyCursesInitialised + if (!PyArg_ParseTuple(args, "i;ms", &ms)) return NULL; + + return Py_BuildValue("i", napms(ms)); + } + + + static PyObject * + PyCurses_NewPad(PyObject *self, PyObject *args) + { + WINDOW *win; + int nlines, ncols; + + PyCursesInitialised + + if (!PyArg_ParseTuple(args,"ii;nlines,ncols",&nlines,&ncols)) return NULL; + + win = newpad(nlines, ncols); + + if (win == NULL) { + PyErr_SetString(PyCursesError, catchall_NULL); + return NULL; + } + + return (PyObject *)PyCursesWindow_New(win); + } + + static PyObject * + PyCurses_NewWindow(PyObject *self, PyObject *args) + { + WINDOW *win; + int nlines, ncols, begin_y=0, begin_x=0; + + PyCursesInitialised + + switch (PyTuple_Size(args)) { + case 2: + if (!PyArg_ParseTuple(args,"ii;nlines,ncols",&nlines,&ncols)) + return NULL; + break; + case 4: + if (!PyArg_ParseTuple(args, "iiii;nlines,ncols,begin_y,begin_x", + &nlines,&ncols,&begin_y,&begin_x)) + return NULL; + break; + default: + PyErr_SetString(PyExc_TypeError, "newwin requires 2 or 4 arguments"); + return NULL; + } + + win = newwin(nlines,ncols,begin_y,begin_x); + if (win == NULL) { + PyErr_SetString(PyCursesError, catchall_NULL); + return NULL; + } + + return (PyObject *)PyCursesWindow_New(win); + } + + static PyObject * + PyCurses_Pair_Content(PyObject *self, PyObject *args) + { + short pair,f,b; + + PyCursesInitialised + PyCursesInitialisedColor + + switch(PyTuple_Size(args)) { + case 1: + if (!PyArg_ParseTuple(args, "h;pair", &pair)) return NULL; + break; + default: + PyErr_SetString(PyExc_TypeError, "pair_content requires 1 argument"); + return NULL; + } + + if (pair_content(pair, &f, &b)==ERR) { + PyErr_SetString(PyCursesError, + "Argument 1 was out of range. (1..COLOR_PAIRS-1)"); + return NULL; + } + + return Py_BuildValue("(ii)", f, b); + } + + static PyObject * + PyCurses_pair_number(PyObject *self, PyObject *args) + { + int n; + + PyCursesInitialised + PyCursesInitialisedColor + + switch(PyTuple_Size(args)) { + case 1: + if (!PyArg_ParseTuple(args, "i;pairvalue", &n)) return NULL; + break; + default: + PyErr_SetString(PyExc_TypeError, + "pair_number requires 1 argument"); + return NULL; + } + + return PyLong_FromLong((long) ((n & A_COLOR) >> 8)); + } + + static PyObject * + PyCurses_Putp(PyObject *self, PyObject *args) + { + char *str; + + if (!PyArg_ParseTuple(args,"s;str", &str)) return NULL; + return PyCursesCheckERR(putp(str), "putp"); + } + + static PyObject * + PyCurses_QiFlush(PyObject *self, PyObject *args) + { + int flag = 0; + + PyCursesInitialised + + switch(PyTuple_Size(args)) { + case 0: + qiflush(); + Py_INCREF(Py_None); + return Py_None; + case 1: + if (!PyArg_ParseTuple(args, "i;True(1) or False(0)", &flag)) return NULL; + if (flag) qiflush(); + else noqiflush(); + Py_INCREF(Py_None); + return Py_None; + default: + PyErr_SetString(PyExc_TypeError, "qiflush requires 0 or 1 arguments"); + return NULL; + } + } /* Internal helper used for updating curses.LINES, curses.COLS, _curses.LINES * and _curses.COLS */ #if defined(HAVE_CURSES_RESIZETERM) || defined(HAVE_CURSES_RESIZE_TERM) -static int -update_lines_cols(void) -{ - PyObject *o; - PyObject *m = PyImport_ImportModuleNoBlock("curses"); - - if (!m) - return 0; - - o = PyLong_FromLong(LINES); - if (!o) { - Py_DECREF(m); - return 0; - } - if (PyObject_SetAttrString(m, "LINES", o)) { - Py_DECREF(m); - Py_DECREF(o); - return 0; - } - if (PyDict_SetItemString(ModDict, "LINES", o)) { - Py_DECREF(m); - Py_DECREF(o); - return 0; - } - Py_DECREF(o); - o = PyLong_FromLong(COLS); - if (!o) { - Py_DECREF(m); - return 0; - } - if (PyObject_SetAttrString(m, "COLS", o)) { - Py_DECREF(m); - Py_DECREF(o); - return 0; - } - if (PyDict_SetItemString(ModDict, "COLS", o)) { - Py_DECREF(m); - Py_DECREF(o); - return 0; - } - Py_DECREF(o); - Py_DECREF(m); - return 1; -} + static int + update_lines_cols(void) + { + PyObject *o; + PyObject *m = PyImport_ImportModuleNoBlock("curses"); + + if (!m) + return 0; + + o = PyLong_FromLong(LINES); + if (!o) { + Py_DECREF(m); + return 0; + } + if (PyObject_SetAttrString(m, "LINES", o)) { + Py_DECREF(m); + Py_DECREF(o); + return 0; + } + if (PyDict_SetItemString(ModDict, "LINES", o)) { + Py_DECREF(m); + Py_DECREF(o); + return 0; + } + Py_DECREF(o); + o = PyLong_FromLong(COLS); + if (!o) { + Py_DECREF(m); + return 0; + } + if (PyObject_SetAttrString(m, "COLS", o)) { + Py_DECREF(m); + Py_DECREF(o); + return 0; + } + if (PyDict_SetItemString(ModDict, "COLS", o)) { + Py_DECREF(m); + Py_DECREF(o); + return 0; + } + Py_DECREF(o); + Py_DECREF(m); + return 1; + } #endif #ifdef HAVE_CURSES_RESIZETERM -static PyObject * -PyCurses_ResizeTerm(PyObject *self, PyObject *args) -{ - int lines; - int columns; - PyObject *result; - - PyCursesInitialised - - if (!PyArg_ParseTuple(args,"ii:resizeterm", &lines, &columns)) - return NULL; - - result = PyCursesCheckERR(resizeterm(lines, columns), "resizeterm"); - if (!result) - return NULL; - if (!update_lines_cols()) - return NULL; - return result; -} + static PyObject * + PyCurses_ResizeTerm(PyObject *self, PyObject *args) + { + int lines; + int columns; + PyObject *result; + + PyCursesInitialised + + if (!PyArg_ParseTuple(args,"ii:resizeterm", &lines, &columns)) + return NULL; + + result = PyCursesCheckERR(resizeterm(lines, columns), "resizeterm"); + if (!result) + return NULL; + if (!update_lines_cols()) + return NULL; + return result; + } #endif #ifdef HAVE_CURSES_RESIZE_TERM -static PyObject * -PyCurses_Resize_Term(PyObject *self, PyObject *args) -{ - int lines; - int columns; - - PyObject *result; - - PyCursesInitialised - - if (!PyArg_ParseTuple(args,"ii:resize_term", &lines, &columns)) - return NULL; - - result = PyCursesCheckERR(resize_term(lines, columns), "resize_term"); - if (!result) - return NULL; - if (!update_lines_cols()) - return NULL; - return result; -} + static PyObject * + PyCurses_Resize_Term(PyObject *self, PyObject *args) + { + int lines; + int columns; + + PyObject *result; + + PyCursesInitialised + + if (!PyArg_ParseTuple(args,"ii:resize_term", &lines, &columns)) + return NULL; + + result = PyCursesCheckERR(resize_term(lines, columns), "resize_term"); + if (!result) + return NULL; + if (!update_lines_cols()) + return NULL; + return result; + } #endif /* HAVE_CURSES_RESIZE_TERM */ -static PyObject * -PyCurses_setsyx(PyObject *self, PyObject *args) -{ - int y,x; - - PyCursesInitialised - - if (PyTuple_Size(args)!=2) { - PyErr_SetString(PyExc_TypeError, "setsyx requires 2 arguments"); - return NULL; - } - - if (!PyArg_ParseTuple(args, "ii;y, x", &y, &x)) return NULL; - - setsyx(y,x); - - Py_INCREF(Py_None); - return Py_None; -} - -static PyObject * -PyCurses_Start_Color(PyObject *self) -{ - int code; - PyObject *c, *cp; - - PyCursesInitialised - - code = start_color(); - if (code != ERR) { - initialisedcolors = TRUE; - c = PyLong_FromLong((long) COLORS); - PyDict_SetItemString(ModDict, "COLORS", c); - Py_DECREF(c); - cp = PyLong_FromLong((long) COLOR_PAIRS); - PyDict_SetItemString(ModDict, "COLOR_PAIRS", cp); - Py_DECREF(cp); - Py_INCREF(Py_None); - return Py_None; - } else { - PyErr_SetString(PyCursesError, "start_color() returned ERR"); - return NULL; - } -} - -static PyObject * -PyCurses_tigetflag(PyObject *self, PyObject *args) -{ - char *capname; - - PyCursesSetupTermCalled; - - if (!PyArg_ParseTuple(args, "s", &capname)) - return NULL; - - return PyLong_FromLong( (long) tigetflag( capname ) ); -} - -static PyObject * -PyCurses_tigetnum(PyObject *self, PyObject *args) -{ - char *capname; - - PyCursesSetupTermCalled; - - if (!PyArg_ParseTuple(args, "s", &capname)) - return NULL; - - return PyLong_FromLong( (long) tigetnum( capname ) ); -} - -static PyObject * -PyCurses_tigetstr(PyObject *self, PyObject *args) -{ - char *capname; - - PyCursesSetupTermCalled; - - if (!PyArg_ParseTuple(args, "s", &capname)) - return NULL; - - capname = tigetstr( capname ); - if (capname == 0 || capname == (char*) -1) { - Py_INCREF(Py_None); - return Py_None; - } - return PyBytes_FromString( capname ); -} - -static PyObject * -PyCurses_tparm(PyObject *self, PyObject *args) -{ - char* fmt; - char* result = NULL; - int i1=0,i2=0,i3=0,i4=0,i5=0,i6=0,i7=0,i8=0,i9=0; - - PyCursesSetupTermCalled; - - if (!PyArg_ParseTuple(args, "s|iiiiiiiii:tparm", - &fmt, &i1, &i2, &i3, &i4, - &i5, &i6, &i7, &i8, &i9)) { - return NULL; - } - - result = tparm(fmt,i1,i2,i3,i4,i5,i6,i7,i8,i9); - if (!result) { - PyErr_SetString(PyCursesError, "tparm() returned NULL"); - return NULL; - } - - return PyBytes_FromString(result); -} - -static PyObject * -PyCurses_TypeAhead(PyObject *self, PyObject *args) -{ - int fd; - - PyCursesInitialised - - if (!PyArg_ParseTuple(args,"i;fd",&fd)) return NULL; - - return PyCursesCheckERR(typeahead( fd ), "typeahead"); -} - -static PyObject * -PyCurses_UnCtrl(PyObject *self, PyObject *args) -{ - PyObject *temp; - chtype ch; - - PyCursesInitialised - - if (!PyArg_ParseTuple(args,"O;ch or int",&temp)) return NULL; - - if (!PyCurses_ConvertToChtype(temp, &ch)) { - PyErr_SetString(PyExc_TypeError, "argument must be a ch or an int"); - return NULL; - } - - return PyBytes_FromString(unctrl(ch)); -} - -static PyObject * -PyCurses_UngetCh(PyObject *self, PyObject *args) -{ - PyObject *temp; - chtype ch; - - PyCursesInitialised - - if (!PyArg_ParseTuple(args,"O;ch or int",&temp)) return NULL; - - if (!PyCurses_ConvertToChtype(temp, &ch)) { - PyErr_SetString(PyExc_TypeError, "argument must be a ch or an int"); - return NULL; - } - - return PyCursesCheckERR(ungetch(ch), "ungetch"); -} - -static PyObject * -PyCurses_Use_Env(PyObject *self, PyObject *args) -{ - int flag; - - switch(PyTuple_Size(args)) { - case 1: - if (!PyArg_ParseTuple(args,"i;True(1), False(0)",&flag)) - return NULL; - break; - default: - PyErr_SetString(PyExc_TypeError, "use_env requires 1 argument"); - return NULL; - } - use_env(flag); - Py_INCREF(Py_None); - return Py_None; -} + static PyObject * + PyCurses_setsyx(PyObject *self, PyObject *args) + { + int y,x; + + PyCursesInitialised + + if (PyTuple_Size(args)!=2) { + PyErr_SetString(PyExc_TypeError, "setsyx requires 2 arguments"); + return NULL; + } + + if (!PyArg_ParseTuple(args, "ii;y, x", &y, &x)) return NULL; + + setsyx(y,x); + + Py_INCREF(Py_None); + return Py_None; + } + + static PyObject * + PyCurses_Start_Color(PyObject *self) + { + int code; + PyObject *c, *cp; + + PyCursesInitialised + + code = start_color(); + if (code != ERR) { + initialisedcolors = TRUE; + c = PyLong_FromLong((long) COLORS); + PyDict_SetItemString(ModDict, "COLORS", c); + Py_DECREF(c); + cp = PyLong_FromLong((long) COLOR_PAIRS); + PyDict_SetItemString(ModDict, "COLOR_PAIRS", cp); + Py_DECREF(cp); + Py_INCREF(Py_None); + return Py_None; + } else { + PyErr_SetString(PyCursesError, "start_color() returned ERR"); + return NULL; + } + } + + static PyObject * + PyCurses_tigetflag(PyObject *self, PyObject *args) + { + char *capname; + + PyCursesSetupTermCalled; + + if (!PyArg_ParseTuple(args, "s", &capname)) + return NULL; + + return PyLong_FromLong( (long) tigetflag( capname ) ); + } + + static PyObject * + PyCurses_tigetnum(PyObject *self, PyObject *args) + { + char *capname; + + PyCursesSetupTermCalled; + + if (!PyArg_ParseTuple(args, "s", &capname)) + return NULL; + + return PyLong_FromLong( (long) tigetnum( capname ) ); + } + + static PyObject * + PyCurses_tigetstr(PyObject *self, PyObject *args) + { + char *capname; + + PyCursesSetupTermCalled; + + if (!PyArg_ParseTuple(args, "s", &capname)) + return NULL; + + capname = tigetstr( capname ); + if (capname == 0 || capname == (char*) -1) { + Py_INCREF(Py_None); + return Py_None; + } + return PyBytes_FromString( capname ); + } + + static PyObject * + PyCurses_tparm(PyObject *self, PyObject *args) + { + char* fmt; + char* result = NULL; + int i1=0,i2=0,i3=0,i4=0,i5=0,i6=0,i7=0,i8=0,i9=0; + + PyCursesSetupTermCalled; + + if (!PyArg_ParseTuple(args, "s|iiiiiiiii:tparm", + &fmt, &i1, &i2, &i3, &i4, + &i5, &i6, &i7, &i8, &i9)) { + return NULL; + } + + result = tparm(fmt,i1,i2,i3,i4,i5,i6,i7,i8,i9); + if (!result) { + PyErr_SetString(PyCursesError, "tparm() returned NULL"); + return NULL; + } + + return PyBytes_FromString(result); + } + + static PyObject * + PyCurses_TypeAhead(PyObject *self, PyObject *args) + { + int fd; + + PyCursesInitialised + + if (!PyArg_ParseTuple(args,"i;fd",&fd)) return NULL; + + return PyCursesCheckERR(typeahead( fd ), "typeahead"); + } + + static PyObject * + PyCurses_UnCtrl(PyObject *self, PyObject *args) + { + PyObject *temp; + chtype ch; + + PyCursesInitialised + + if (!PyArg_ParseTuple(args,"O;ch or int",&temp)) return NULL; + + if (!PyCurses_ConvertToChtype(temp, &ch)) { + PyErr_SetString(PyExc_TypeError, "argument must be a ch or an int"); + return NULL; + } + + return PyBytes_FromString(unctrl(ch)); + } + + static PyObject * + PyCurses_UngetCh(PyObject *self, PyObject *args) + { + PyObject *temp; + chtype ch; + + PyCursesInitialised + + if (!PyArg_ParseTuple(args,"O;ch or int",&temp)) return NULL; + + if (!PyCurses_ConvertToChtype(temp, &ch)) { + PyErr_SetString(PyExc_TypeError, "argument must be a ch or an int"); + return NULL; + } + + return PyCursesCheckERR(ungetch(ch), "ungetch"); + } + + static PyObject * + PyCurses_Use_Env(PyObject *self, PyObject *args) + { + int flag; + + switch(PyTuple_Size(args)) { + case 1: + if (!PyArg_ParseTuple(args,"i;True(1), False(0)",&flag)) + return NULL; + break; + default: + PyErr_SetString(PyExc_TypeError, "use_env requires 1 argument"); + return NULL; + } + use_env(flag); + Py_INCREF(Py_None); + return Py_None; + } #ifndef STRICT_SYSV_CURSES -static PyObject * -PyCurses_Use_Default_Colors(PyObject *self) -{ - int code; - - PyCursesInitialised - PyCursesInitialisedColor - - code = use_default_colors(); - if (code != ERR) { - Py_INCREF(Py_None); - return Py_None; - } else { - PyErr_SetString(PyCursesError, "use_default_colors() returned ERR"); - return NULL; - } -} + static PyObject * + PyCurses_Use_Default_Colors(PyObject *self) + { + int code; + + PyCursesInitialised + PyCursesInitialisedColor + + code = use_default_colors(); + if (code != ERR) { + Py_INCREF(Py_None); + return Py_None; + } else { + PyErr_SetString(PyCursesError, "use_default_colors() returned ERR"); + return NULL; + } + } #endif /* STRICT_SYSV_CURSES */ /* List of functions defined in the module */ -static PyMethodDef PyCurses_methods[] = { - {"baudrate", (PyCFunction)PyCurses_baudrate, METH_NOARGS}, - {"beep", (PyCFunction)PyCurses_beep, METH_NOARGS}, - {"can_change_color", (PyCFunction)PyCurses_can_change_color, METH_NOARGS}, - {"cbreak", (PyCFunction)PyCurses_cbreak, METH_VARARGS}, - {"color_content", (PyCFunction)PyCurses_Color_Content, METH_VARARGS}, - {"color_pair", (PyCFunction)PyCurses_color_pair, METH_VARARGS}, - {"curs_set", (PyCFunction)PyCurses_Curs_Set, METH_VARARGS}, - {"def_prog_mode", (PyCFunction)PyCurses_def_prog_mode, METH_NOARGS}, - {"def_shell_mode", (PyCFunction)PyCurses_def_shell_mode, METH_NOARGS}, - {"delay_output", (PyCFunction)PyCurses_Delay_Output, METH_VARARGS}, - {"doupdate", (PyCFunction)PyCurses_doupdate, METH_NOARGS}, - {"echo", (PyCFunction)PyCurses_echo, METH_VARARGS}, - {"endwin", (PyCFunction)PyCurses_endwin, METH_NOARGS}, - {"erasechar", (PyCFunction)PyCurses_EraseChar, METH_NOARGS}, - {"filter", (PyCFunction)PyCurses_filter, METH_NOARGS}, - {"flash", (PyCFunction)PyCurses_flash, METH_NOARGS}, - {"flushinp", (PyCFunction)PyCurses_flushinp, METH_NOARGS}, + static PyMethodDef PyCurses_methods[] = { + {"baudrate", (PyCFunction)PyCurses_baudrate, METH_NOARGS}, + {"beep", (PyCFunction)PyCurses_beep, METH_NOARGS}, + {"can_change_color", (PyCFunction)PyCurses_can_change_color, METH_NOARGS}, + {"cbreak", (PyCFunction)PyCurses_cbreak, METH_VARARGS}, + {"color_content", (PyCFunction)PyCurses_Color_Content, METH_VARARGS}, + {"color_pair", (PyCFunction)PyCurses_color_pair, METH_VARARGS}, + {"curs_set", (PyCFunction)PyCurses_Curs_Set, METH_VARARGS}, + {"def_prog_mode", (PyCFunction)PyCurses_def_prog_mode, METH_NOARGS}, + {"def_shell_mode", (PyCFunction)PyCurses_def_shell_mode, METH_NOARGS}, + {"delay_output", (PyCFunction)PyCurses_Delay_Output, METH_VARARGS}, + {"doupdate", (PyCFunction)PyCurses_doupdate, METH_NOARGS}, + {"echo", (PyCFunction)PyCurses_echo, METH_VARARGS}, + {"endwin", (PyCFunction)PyCurses_endwin, METH_NOARGS}, + {"erasechar", (PyCFunction)PyCurses_EraseChar, METH_NOARGS}, + {"filter", (PyCFunction)PyCurses_filter, METH_NOARGS}, + {"flash", (PyCFunction)PyCurses_flash, METH_NOARGS}, + {"flushinp", (PyCFunction)PyCurses_flushinp, METH_NOARGS}, #ifdef NCURSES_MOUSE_VERSION - {"getmouse", (PyCFunction)PyCurses_GetMouse, METH_NOARGS}, - {"ungetmouse", (PyCFunction)PyCurses_UngetMouse, METH_VARARGS}, + {"getmouse", (PyCFunction)PyCurses_GetMouse, METH_NOARGS}, + {"ungetmouse", (PyCFunction)PyCurses_UngetMouse, METH_VARARGS}, #endif - {"getsyx", (PyCFunction)PyCurses_getsyx, METH_NOARGS}, - {"getwin", (PyCFunction)PyCurses_GetWin, METH_O}, - {"has_colors", (PyCFunction)PyCurses_has_colors, METH_NOARGS}, - {"has_ic", (PyCFunction)PyCurses_has_ic, METH_NOARGS}, - {"has_il", (PyCFunction)PyCurses_has_il, METH_NOARGS}, + {"getsyx", (PyCFunction)PyCurses_getsyx, METH_NOARGS}, + {"getwin", (PyCFunction)PyCurses_GetWin, METH_O}, + {"has_colors", (PyCFunction)PyCurses_has_colors, METH_NOARGS}, + {"has_ic", (PyCFunction)PyCurses_has_ic, METH_NOARGS}, + {"has_il", (PyCFunction)PyCurses_has_il, METH_NOARGS}, #ifndef STRICT_SYSV_CURSES - {"has_key", (PyCFunction)PyCurses_has_key, METH_VARARGS}, + {"has_key", (PyCFunction)PyCurses_has_key, METH_VARARGS}, #endif - {"halfdelay", (PyCFunction)PyCurses_HalfDelay, METH_VARARGS}, - {"init_color", (PyCFunction)PyCurses_Init_Color, METH_VARARGS}, - {"init_pair", (PyCFunction)PyCurses_Init_Pair, METH_VARARGS}, - {"initscr", (PyCFunction)PyCurses_InitScr, METH_NOARGS}, - {"intrflush", (PyCFunction)PyCurses_IntrFlush, METH_VARARGS}, - {"isendwin", (PyCFunction)PyCurses_isendwin, METH_NOARGS}, + {"halfdelay", (PyCFunction)PyCurses_HalfDelay, METH_VARARGS}, + {"init_color", (PyCFunction)PyCurses_Init_Color, METH_VARARGS}, + {"init_pair", (PyCFunction)PyCurses_Init_Pair, METH_VARARGS}, + {"initscr", (PyCFunction)PyCurses_InitScr, METH_NOARGS}, + {"intrflush", (PyCFunction)PyCurses_IntrFlush, METH_VARARGS}, + {"isendwin", (PyCFunction)PyCurses_isendwin, METH_NOARGS}, #ifdef HAVE_CURSES_IS_TERM_RESIZED - {"is_term_resized", (PyCFunction)PyCurses_Is_Term_Resized, METH_VARARGS}, + {"is_term_resized", (PyCFunction)PyCurses_Is_Term_Resized, METH_VARARGS}, #endif #if !defined(__NetBSD__) - {"keyname", (PyCFunction)PyCurses_KeyName, METH_VARARGS}, + {"keyname", (PyCFunction)PyCurses_KeyName, METH_VARARGS}, #endif - {"killchar", (PyCFunction)PyCurses_KillChar, METH_NOARGS}, - {"longname", (PyCFunction)PyCurses_longname, METH_NOARGS}, - {"meta", (PyCFunction)PyCurses_Meta, METH_VARARGS}, + {"killchar", (PyCFunction)PyCurses_KillChar, METH_NOARGS}, + {"longname", (PyCFunction)PyCurses_longname, METH_NOARGS}, + {"meta", (PyCFunction)PyCurses_Meta, METH_VARARGS}, #ifdef NCURSES_MOUSE_VERSION - {"mouseinterval", (PyCFunction)PyCurses_MouseInterval, METH_VARARGS}, - {"mousemask", (PyCFunction)PyCurses_MouseMask, METH_VARARGS}, + {"mouseinterval", (PyCFunction)PyCurses_MouseInterval, METH_VARARGS}, + {"mousemask", (PyCFunction)PyCurses_MouseMask, METH_VARARGS}, #endif - {"napms", (PyCFunction)PyCurses_Napms, METH_VARARGS}, - {"newpad", (PyCFunction)PyCurses_NewPad, METH_VARARGS}, - {"newwin", (PyCFunction)PyCurses_NewWindow, METH_VARARGS}, - {"nl", (PyCFunction)PyCurses_nl, METH_VARARGS}, - {"nocbreak", (PyCFunction)PyCurses_nocbreak, METH_NOARGS}, - {"noecho", (PyCFunction)PyCurses_noecho, METH_NOARGS}, - {"nonl", (PyCFunction)PyCurses_nonl, METH_NOARGS}, - {"noqiflush", (PyCFunction)PyCurses_noqiflush, METH_NOARGS}, - {"noraw", (PyCFunction)PyCurses_noraw, METH_NOARGS}, - {"pair_content", (PyCFunction)PyCurses_Pair_Content, METH_VARARGS}, - {"pair_number", (PyCFunction)PyCurses_pair_number, METH_VARARGS}, - {"putp", (PyCFunction)PyCurses_Putp, METH_VARARGS}, - {"qiflush", (PyCFunction)PyCurses_QiFlush, METH_VARARGS}, - {"raw", (PyCFunction)PyCurses_raw, METH_VARARGS}, - {"reset_prog_mode", (PyCFunction)PyCurses_reset_prog_mode, METH_NOARGS}, - {"reset_shell_mode", (PyCFunction)PyCurses_reset_shell_mode, METH_NOARGS}, - {"resetty", (PyCFunction)PyCurses_resetty, METH_NOARGS}, + {"napms", (PyCFunction)PyCurses_Napms, METH_VARARGS}, + {"newpad", (PyCFunction)PyCurses_NewPad, METH_VARARGS}, + {"newwin", (PyCFunction)PyCurses_NewWindow, METH_VARARGS}, + {"nl", (PyCFunction)PyCurses_nl, METH_VARARGS}, + {"nocbreak", (PyCFunction)PyCurses_nocbreak, METH_NOARGS}, + {"noecho", (PyCFunction)PyCurses_noecho, METH_NOARGS}, + {"nonl", (PyCFunction)PyCurses_nonl, METH_NOARGS}, + {"noqiflush", (PyCFunction)PyCurses_noqiflush, METH_NOARGS}, + {"noraw", (PyCFunction)PyCurses_noraw, METH_NOARGS}, + {"pair_content", (PyCFunction)PyCurses_Pair_Content, METH_VARARGS}, + {"pair_number", (PyCFunction)PyCurses_pair_number, METH_VARARGS}, + {"putp", (PyCFunction)PyCurses_Putp, METH_VARARGS}, + {"qiflush", (PyCFunction)PyCurses_QiFlush, METH_VARARGS}, + {"raw", (PyCFunction)PyCurses_raw, METH_VARARGS}, + {"reset_prog_mode", (PyCFunction)PyCurses_reset_prog_mode, METH_NOARGS}, + {"reset_shell_mode", (PyCFunction)PyCurses_reset_shell_mode, METH_NOARGS}, + {"resetty", (PyCFunction)PyCurses_resetty, METH_NOARGS}, #ifdef HAVE_CURSES_RESIZETERM - {"resizeterm", (PyCFunction)PyCurses_ResizeTerm, METH_VARARGS}, + {"resizeterm", (PyCFunction)PyCurses_ResizeTerm, METH_VARARGS}, #endif #ifdef HAVE_CURSES_RESIZE_TERM - {"resize_term", (PyCFunction)PyCurses_Resize_Term, METH_VARARGS}, + {"resize_term", (PyCFunction)PyCurses_Resize_Term, METH_VARARGS}, #endif - {"savetty", (PyCFunction)PyCurses_savetty, METH_NOARGS}, - {"setsyx", (PyCFunction)PyCurses_setsyx, METH_VARARGS}, - {"setupterm", (PyCFunction)PyCurses_setupterm, - METH_VARARGS|METH_KEYWORDS}, - {"start_color", (PyCFunction)PyCurses_Start_Color, METH_NOARGS}, - {"termattrs", (PyCFunction)PyCurses_termattrs, METH_NOARGS}, - {"termname", (PyCFunction)PyCurses_termname, METH_NOARGS}, - {"tigetflag", (PyCFunction)PyCurses_tigetflag, METH_VARARGS}, - {"tigetnum", (PyCFunction)PyCurses_tigetnum, METH_VARARGS}, - {"tigetstr", (PyCFunction)PyCurses_tigetstr, METH_VARARGS}, - {"tparm", (PyCFunction)PyCurses_tparm, METH_VARARGS}, - {"typeahead", (PyCFunction)PyCurses_TypeAhead, METH_VARARGS}, - {"unctrl", (PyCFunction)PyCurses_UnCtrl, METH_VARARGS}, - {"ungetch", (PyCFunction)PyCurses_UngetCh, METH_VARARGS}, - {"use_env", (PyCFunction)PyCurses_Use_Env, METH_VARARGS}, + {"savetty", (PyCFunction)PyCurses_savetty, METH_NOARGS}, + {"setsyx", (PyCFunction)PyCurses_setsyx, METH_VARARGS}, + {"setupterm", (PyCFunction)PyCurses_setupterm, + METH_VARARGS|METH_KEYWORDS}, + {"start_color", (PyCFunction)PyCurses_Start_Color, METH_NOARGS}, + {"termattrs", (PyCFunction)PyCurses_termattrs, METH_NOARGS}, + {"termname", (PyCFunction)PyCurses_termname, METH_NOARGS}, + {"tigetflag", (PyCFunction)PyCurses_tigetflag, METH_VARARGS}, + {"tigetnum", (PyCFunction)PyCurses_tigetnum, METH_VARARGS}, + {"tigetstr", (PyCFunction)PyCurses_tigetstr, METH_VARARGS}, + {"tparm", (PyCFunction)PyCurses_tparm, METH_VARARGS}, + {"typeahead", (PyCFunction)PyCurses_TypeAhead, METH_VARARGS}, + {"unctrl", (PyCFunction)PyCurses_UnCtrl, METH_VARARGS}, + {"ungetch", (PyCFunction)PyCurses_UngetCh, METH_VARARGS}, + {"use_env", (PyCFunction)PyCurses_Use_Env, METH_VARARGS}, #ifndef STRICT_SYSV_CURSES - {"use_default_colors", (PyCFunction)PyCurses_Use_Default_Colors, METH_NOARGS}, + {"use_default_colors", (PyCFunction)PyCurses_Use_Default_Colors, METH_NOARGS}, #endif - {NULL, NULL} /* sentinel */ -}; + {NULL, NULL} /* sentinel */ + }; /* Initialization function for the module */ -static struct PyModuleDef _cursesmodule = { - PyModuleDef_HEAD_INIT, - "_curses", - NULL, - -1, - PyCurses_methods, - NULL, - NULL, - NULL, - NULL -}; - -PyMODINIT_FUNC -PyInit__curses(void) -{ - PyObject *m, *d, *v, *c_api_object; - static void *PyCurses_API[PyCurses_API_pointers]; - - /* Initialize object type */ - if (PyType_Ready(&PyCursesWindow_Type) < 0) - return NULL; - - /* Initialize the C API pointer array */ - PyCurses_API[0] = (void *)&PyCursesWindow_Type; - PyCurses_API[1] = (void *)func_PyCursesSetupTermCalled; - PyCurses_API[2] = (void *)func_PyCursesInitialised; - PyCurses_API[3] = (void *)func_PyCursesInitialisedColor; - - /* Create the module and add the functions */ - m = PyModule_Create(&_cursesmodule); - if (m == NULL) - return NULL; - - /* Add some symbolic constants to the module */ - d = PyModule_GetDict(m); - if (d == NULL) - return NULL; - ModDict = d; /* For PyCurses_InitScr to use later */ - - /* Add a capsule for the C API */ - c_api_object = PyCapsule_New(PyCurses_API, PyCurses_CAPSULE_NAME, NULL); - PyDict_SetItemString(d, "_C_API", c_api_object); - Py_DECREF(c_api_object); - - /* For exception curses.error */ - PyCursesError = PyErr_NewException("_curses.error", NULL, NULL); - PyDict_SetItemString(d, "error", PyCursesError); - - /* Make the version available */ - v = PyBytes_FromString(PyCursesVersion); - PyDict_SetItemString(d, "version", v); - PyDict_SetItemString(d, "__version__", v); - Py_DECREF(v); - - SetDictInt("ERR", ERR); - SetDictInt("OK", OK); - - /* Here are some attributes you can add to chars to print */ - - SetDictInt("A_ATTRIBUTES", A_ATTRIBUTES); - SetDictInt("A_NORMAL", A_NORMAL); - SetDictInt("A_STANDOUT", A_STANDOUT); - SetDictInt("A_UNDERLINE", A_UNDERLINE); - SetDictInt("A_REVERSE", A_REVERSE); - SetDictInt("A_BLINK", A_BLINK); - SetDictInt("A_DIM", A_DIM); - SetDictInt("A_BOLD", A_BOLD); - SetDictInt("A_ALTCHARSET", A_ALTCHARSET); + static struct PyModuleDef _cursesmodule = { + PyModuleDef_HEAD_INIT, + "_curses", + NULL, + -1, + PyCurses_methods, + NULL, + NULL, + NULL, + NULL + }; + + PyMODINIT_FUNC + PyInit__curses(void) + { + PyObject *m, *d, *v, *c_api_object; + static void *PyCurses_API[PyCurses_API_pointers]; + + /* Initialize object type */ + if (PyType_Ready(&PyCursesWindow_Type) < 0) + return NULL; + + /* Initialize the C API pointer array */ + PyCurses_API[0] = (void *)&PyCursesWindow_Type; + PyCurses_API[1] = (void *)func_PyCursesSetupTermCalled; + PyCurses_API[2] = (void *)func_PyCursesInitialised; + PyCurses_API[3] = (void *)func_PyCursesInitialisedColor; + + /* Create the module and add the functions */ + m = PyModule_Create(&_cursesmodule); + if (m == NULL) + return NULL; + + /* Add some symbolic constants to the module */ + d = PyModule_GetDict(m); + if (d == NULL) + return NULL; + ModDict = d; /* For PyCurses_InitScr to use later */ + + /* Add a capsule for the C API */ + c_api_object = PyCapsule_New(PyCurses_API, PyCurses_CAPSULE_NAME, NULL); + PyDict_SetItemString(d, "_C_API", c_api_object); + Py_DECREF(c_api_object); + + /* For exception curses.error */ + PyCursesError = PyErr_NewException("_curses.error", NULL, NULL); + PyDict_SetItemString(d, "error", PyCursesError); + + /* Make the version available */ + v = PyBytes_FromString(PyCursesVersion); + PyDict_SetItemString(d, "version", v); + PyDict_SetItemString(d, "__version__", v); + Py_DECREF(v); + + SetDictInt("ERR", ERR); + SetDictInt("OK", OK); + + /* Here are some attributes you can add to chars to print */ + + SetDictInt("A_ATTRIBUTES", A_ATTRIBUTES); + SetDictInt("A_NORMAL", A_NORMAL); + SetDictInt("A_STANDOUT", A_STANDOUT); + SetDictInt("A_UNDERLINE", A_UNDERLINE); + SetDictInt("A_REVERSE", A_REVERSE); + SetDictInt("A_BLINK", A_BLINK); + SetDictInt("A_DIM", A_DIM); + SetDictInt("A_BOLD", A_BOLD); + SetDictInt("A_ALTCHARSET", A_ALTCHARSET); #if !defined(__NetBSD__) - SetDictInt("A_INVIS", A_INVIS); + SetDictInt("A_INVIS", A_INVIS); #endif - SetDictInt("A_PROTECT", A_PROTECT); - SetDictInt("A_CHARTEXT", A_CHARTEXT); - SetDictInt("A_COLOR", A_COLOR); + SetDictInt("A_PROTECT", A_PROTECT); + SetDictInt("A_CHARTEXT", A_CHARTEXT); + SetDictInt("A_COLOR", A_COLOR); - /* The following are never available with strict SYSV curses */ + /* The following are never available with strict SYSV curses */ #ifdef A_HORIZONTAL - SetDictInt("A_HORIZONTAL", A_HORIZONTAL); + SetDictInt("A_HORIZONTAL", A_HORIZONTAL); #endif #ifdef A_LEFT - SetDictInt("A_LEFT", A_LEFT); + SetDictInt("A_LEFT", A_LEFT); #endif #ifdef A_LOW - SetDictInt("A_LOW", A_LOW); + SetDictInt("A_LOW", A_LOW); #endif #ifdef A_RIGHT - SetDictInt("A_RIGHT", A_RIGHT); + SetDictInt("A_RIGHT", A_RIGHT); #endif #ifdef A_TOP - SetDictInt("A_TOP", A_TOP); + SetDictInt("A_TOP", A_TOP); #endif #ifdef A_VERTICAL - SetDictInt("A_VERTICAL", A_VERTICAL); + SetDictInt("A_VERTICAL", A_VERTICAL); #endif - SetDictInt("COLOR_BLACK", COLOR_BLACK); - SetDictInt("COLOR_RED", COLOR_RED); - SetDictInt("COLOR_GREEN", COLOR_GREEN); - SetDictInt("COLOR_YELLOW", COLOR_YELLOW); - SetDictInt("COLOR_BLUE", COLOR_BLUE); - SetDictInt("COLOR_MAGENTA", COLOR_MAGENTA); - SetDictInt("COLOR_CYAN", COLOR_CYAN); - SetDictInt("COLOR_WHITE", COLOR_WHITE); + SetDictInt("COLOR_BLACK", COLOR_BLACK); + SetDictInt("COLOR_RED", COLOR_RED); + SetDictInt("COLOR_GREEN", COLOR_GREEN); + SetDictInt("COLOR_YELLOW", COLOR_YELLOW); + SetDictInt("COLOR_BLUE", COLOR_BLUE); + SetDictInt("COLOR_MAGENTA", COLOR_MAGENTA); + SetDictInt("COLOR_CYAN", COLOR_CYAN); + SetDictInt("COLOR_WHITE", COLOR_WHITE); #ifdef NCURSES_MOUSE_VERSION - /* Mouse-related constants */ - SetDictInt("BUTTON1_PRESSED", BUTTON1_PRESSED); - SetDictInt("BUTTON1_RELEASED", BUTTON1_RELEASED); - SetDictInt("BUTTON1_CLICKED", BUTTON1_CLICKED); - SetDictInt("BUTTON1_DOUBLE_CLICKED", BUTTON1_DOUBLE_CLICKED); - SetDictInt("BUTTON1_TRIPLE_CLICKED", BUTTON1_TRIPLE_CLICKED); - - SetDictInt("BUTTON2_PRESSED", BUTTON2_PRESSED); - SetDictInt("BUTTON2_RELEASED", BUTTON2_RELEASED); - SetDictInt("BUTTON2_CLICKED", BUTTON2_CLICKED); - SetDictInt("BUTTON2_DOUBLE_CLICKED", BUTTON2_DOUBLE_CLICKED); - SetDictInt("BUTTON2_TRIPLE_CLICKED", BUTTON2_TRIPLE_CLICKED); - - SetDictInt("BUTTON3_PRESSED", BUTTON3_PRESSED); - SetDictInt("BUTTON3_RELEASED", BUTTON3_RELEASED); - SetDictInt("BUTTON3_CLICKED", BUTTON3_CLICKED); - SetDictInt("BUTTON3_DOUBLE_CLICKED", BUTTON3_DOUBLE_CLICKED); - SetDictInt("BUTTON3_TRIPLE_CLICKED", BUTTON3_TRIPLE_CLICKED); - - SetDictInt("BUTTON4_PRESSED", BUTTON4_PRESSED); - SetDictInt("BUTTON4_RELEASED", BUTTON4_RELEASED); - SetDictInt("BUTTON4_CLICKED", BUTTON4_CLICKED); - SetDictInt("BUTTON4_DOUBLE_CLICKED", BUTTON4_DOUBLE_CLICKED); - SetDictInt("BUTTON4_TRIPLE_CLICKED", BUTTON4_TRIPLE_CLICKED); - - SetDictInt("BUTTON_SHIFT", BUTTON_SHIFT); - SetDictInt("BUTTON_CTRL", BUTTON_CTRL); - SetDictInt("BUTTON_ALT", BUTTON_ALT); - - SetDictInt("ALL_MOUSE_EVENTS", ALL_MOUSE_EVENTS); - SetDictInt("REPORT_MOUSE_POSITION", REPORT_MOUSE_POSITION); -#endif - /* Now set everything up for KEY_ variables */ - { - int key; - char *key_n; - char *key_n2; + /* Mouse-related constants */ + SetDictInt("BUTTON1_PRESSED", BUTTON1_PRESSED); + SetDictInt("BUTTON1_RELEASED", BUTTON1_RELEASED); + SetDictInt("BUTTON1_CLICKED", BUTTON1_CLICKED); + SetDictInt("BUTTON1_DOUBLE_CLICKED", BUTTON1_DOUBLE_CLICKED); + SetDictInt("BUTTON1_TRIPLE_CLICKED", BUTTON1_TRIPLE_CLICKED); + + SetDictInt("BUTTON2_PRESSED", BUTTON2_PRESSED); + SetDictInt("BUTTON2_RELEASED", BUTTON2_RELEASED); + SetDictInt("BUTTON2_CLICKED", BUTTON2_CLICKED); + SetDictInt("BUTTON2_DOUBLE_CLICKED", BUTTON2_DOUBLE_CLICKED); + SetDictInt("BUTTON2_TRIPLE_CLICKED", BUTTON2_TRIPLE_CLICKED); + + SetDictInt("BUTTON3_PRESSED", BUTTON3_PRESSED); + SetDictInt("BUTTON3_RELEASED", BUTTON3_RELEASED); + SetDictInt("BUTTON3_CLICKED", BUTTON3_CLICKED); + SetDictInt("BUTTON3_DOUBLE_CLICKED", BUTTON3_DOUBLE_CLICKED); + SetDictInt("BUTTON3_TRIPLE_CLICKED", BUTTON3_TRIPLE_CLICKED); + + SetDictInt("BUTTON4_PRESSED", BUTTON4_PRESSED); + SetDictInt("BUTTON4_RELEASED", BUTTON4_RELEASED); + SetDictInt("BUTTON4_CLICKED", BUTTON4_CLICKED); + SetDictInt("BUTTON4_DOUBLE_CLICKED", BUTTON4_DOUBLE_CLICKED); + SetDictInt("BUTTON4_TRIPLE_CLICKED", BUTTON4_TRIPLE_CLICKED); + + SetDictInt("BUTTON_SHIFT", BUTTON_SHIFT); + SetDictInt("BUTTON_CTRL", BUTTON_CTRL); + SetDictInt("BUTTON_ALT", BUTTON_ALT); + + SetDictInt("ALL_MOUSE_EVENTS", ALL_MOUSE_EVENTS); + SetDictInt("REPORT_MOUSE_POSITION", REPORT_MOUSE_POSITION); +#endif + /* Now set everything up for KEY_ variables */ + { + int key; + char *key_n; + char *key_n2; #if !defined(__NetBSD__) - for (key=KEY_MIN;key < KEY_MAX; key++) { - key_n = (char *)keyname(key); - if (key_n == NULL || strcmp(key_n,"UNKNOWN KEY")==0) - continue; - if (strncmp(key_n,"KEY_F(",6)==0) { - char *p1, *p2; - key_n2 = malloc(strlen(key_n)+1); - if (!key_n2) { - PyErr_NoMemory(); - break; - } - p1 = key_n; - p2 = key_n2; - while (*p1) { - if (*p1 != '(' && *p1 != ')') { - *p2 = *p1; - p2++; - } - p1++; - } - *p2 = (char)0; - } else - key_n2 = key_n; - SetDictInt(key_n2,key); - if (key_n2 != key_n) - free(key_n2); - } -#endif - SetDictInt("KEY_MIN", KEY_MIN); - SetDictInt("KEY_MAX", KEY_MAX); - } - return m; -} + for (key=KEY_MIN;key < KEY_MAX; key++) { + key_n = (char *)keyname(key); + if (key_n == NULL || strcmp(key_n,"UNKNOWN KEY")==0) + continue; + if (strncmp(key_n,"KEY_F(",6)==0) { + char *p1, *p2; + key_n2 = malloc(strlen(key_n)+1); + if (!key_n2) { + PyErr_NoMemory(); + break; + } + p1 = key_n; + p2 = key_n2; + while (*p1) { + if (*p1 != '(' && *p1 != ')') { + *p2 = *p1; + p2++; + } + p1++; + } + *p2 = (char)0; + } else + key_n2 = key_n; + SetDictInt(key_n2,key); + if (key_n2 != key_n) + free(key_n2); + } +#endif + SetDictInt("KEY_MIN", KEY_MIN); + SetDictInt("KEY_MAX", KEY_MAX); + } + return m; + } From python-checkins at python.org Sun May 16 00:51:45 2010 From: python-checkins at python.org (brett.cannon) Date: Sun, 16 May 2010 00:51:45 +0200 (CEST) Subject: [Python-checkins] r81218 - python/branches/py3k/Lib/test/test_import.py Message-ID: <20100515225145.BE0D6EE9A2@mail.python.org> Author: brett.cannon Date: Sun May 16 00:51:45 2010 New Revision: 81218 Log: Fix a comment to state the right thing. Modified: python/branches/py3k/Lib/test/test_import.py Modified: python/branches/py3k/Lib/test/test_import.py ============================================================================== --- python/branches/py3k/Lib/test/test_import.py (original) +++ python/branches/py3k/Lib/test/test_import.py Sun May 16 00:51:45 2010 @@ -153,10 +153,9 @@ f.write('"",\n') f.write(']') - # Compile & remove .py file, we only need .pyc (or .pyo), but that - # must be relocated to the PEP 3147 bytecode-only location. - with open(filename, 'r') as f: - py_compile.compile(filename) + # Compile & remove .py file; we only need .pyc (or .pyo). + # Bytecode must be relocated from the PEP 3147 bytecode-only location. + py_compile.compile(filename) unlink(filename) make_legacy_pyc(filename) From python-checkins at python.org Sun May 16 00:53:24 2010 From: python-checkins at python.org (brett.cannon) Date: Sun, 16 May 2010 00:53:24 +0200 (CEST) Subject: [Python-checkins] r81219 - python/branches/py3k/Lib/test/test_import.py Message-ID: <20100515225324.36040EE993@mail.python.org> Author: brett.cannon Date: Sun May 16 00:53:24 2010 New Revision: 81219 Log: Make test_module_with_large_stack as an expected failure because of a change in importlib that is causing it to fail. Work to fix it is being tracked in issue 8727. Modified: python/branches/py3k/Lib/test/test_import.py Modified: python/branches/py3k/Lib/test/test_import.py ============================================================================== --- python/branches/py3k/Lib/test/test_import.py (original) +++ python/branches/py3k/Lib/test/test_import.py Sun May 16 00:53:24 2010 @@ -142,6 +142,7 @@ self.assertIs(orig_path, new_os.path) self.assertIsNot(orig_getenv, new_os.getenv) + @unittest.expectedFailure # Issue 8727 is tracking the fix. def test_module_with_large_stack(self, module='longlist'): # Regression test for http://bugs.python.org/issue561858. filename = module + '.py' From python-checkins at python.org Sun May 16 00:55:28 2010 From: python-checkins at python.org (victor.stinner) Date: Sun, 16 May 2010 00:55:28 +0200 (CEST) Subject: [Python-checkins] r81220 - in python/trunk: Parser/printgrammar.c Python/graminit.c Message-ID: <20100515225528.CFC1CEE990@mail.python.org> Author: victor.stinner Date: Sun May 16 00:55:28 2010 New Revision: 81220 Log: Use 4-spaces for indentation (instead of tabs) in pgen outputs Regenerate (reindent) Python/graminit.c Modified: python/trunk/Parser/printgrammar.c python/trunk/Python/graminit.c Modified: python/trunk/Parser/printgrammar.c ============================================================================== --- python/trunk/Parser/printgrammar.c (original) +++ python/trunk/Parser/printgrammar.c Sun May 16 00:55:28 2010 @@ -20,10 +20,10 @@ printdfas(g, fp); printlabels(g, fp); fprintf(fp, "grammar _PyParser_Grammar = {\n"); - fprintf(fp, "\t%d,\n", g->g_ndfas); - fprintf(fp, "\tdfas,\n"); - fprintf(fp, "\t{%d, labels},\n", g->g_ll.ll_nlabels); - fprintf(fp, "\t%d\n", g->g_start); + fprintf(fp, " %d,\n", g->g_ndfas); + fprintf(fp, " dfas,\n"); + fprintf(fp, " {%d, labels},\n", g->g_ll.ll_nlabels); + fprintf(fp, " %d\n", g->g_start); fprintf(fp, "};\n"); } @@ -53,7 +53,7 @@ i, j, s->s_narcs); a = s->s_arc; for (k = 0; k < s->s_narcs; k++, a++) - fprintf(fp, "\t{%d, %d},\n", a->a_lbl, a->a_arrow); + fprintf(fp, " {%d, %d},\n", a->a_lbl, a->a_arrow); fprintf(fp, "};\n"); } } @@ -72,7 +72,7 @@ i, d->d_nstates); s = d->d_state; for (j = 0; j < d->d_nstates; j++, s++) - fprintf(fp, "\t{%d, arcs_%d_%d},\n", + fprintf(fp, " {%d, arcs_%d_%d},\n", s->s_narcs, i, j); fprintf(fp, "};\n"); } @@ -88,9 +88,9 @@ fprintf(fp, "static dfa dfas[%d] = {\n", g->g_ndfas); d = g->g_dfa; for (i = 0; i < g->g_ndfas; i++, d++) { - fprintf(fp, "\t{%d, \"%s\", %d, %d, states_%d,\n", + fprintf(fp, " {%d, \"%s\", %d, %d, states_%d,\n", d->d_type, d->d_name, d->d_initial, d->d_nstates, i); - fprintf(fp, "\t \""); + fprintf(fp, " \""); for (j = 0; j < NBYTES(g->g_ll.ll_nlabels); j++) fprintf(fp, "\\%03o", d->d_first[j] & 0xff); fprintf(fp, "\"},\n"); @@ -108,9 +108,9 @@ l = g->g_ll.ll_label; for (i = g->g_ll.ll_nlabels; --i >= 0; l++) { if (l->lb_str == NULL) - fprintf(fp, "\t{%d, 0},\n", l->lb_type); + fprintf(fp, " {%d, 0},\n", l->lb_type); else - fprintf(fp, "\t{%d, \"%s\"},\n", + fprintf(fp, " {%d, \"%s\"},\n", l->lb_type, l->lb_str); } fprintf(fp, "};\n"); Modified: python/trunk/Python/graminit.c ============================================================================== --- python/trunk/Python/graminit.c (original) +++ python/trunk/Python/graminit.c Sun May 16 00:55:28 2010 @@ -4,2201 +4,2201 @@ #include "grammar.h" PyAPI_DATA(grammar) _PyParser_Grammar; static arc arcs_0_0[3] = { - {2, 1}, - {3, 1}, - {4, 2}, + {2, 1}, + {3, 1}, + {4, 2}, }; static arc arcs_0_1[1] = { - {0, 1}, + {0, 1}, }; static arc arcs_0_2[1] = { - {2, 1}, + {2, 1}, }; static state states_0[3] = { - {3, arcs_0_0}, - {1, arcs_0_1}, - {1, arcs_0_2}, + {3, arcs_0_0}, + {1, arcs_0_1}, + {1, arcs_0_2}, }; static arc arcs_1_0[3] = { - {2, 0}, - {6, 0}, - {7, 1}, + {2, 0}, + {6, 0}, + {7, 1}, }; static arc arcs_1_1[1] = { - {0, 1}, + {0, 1}, }; static state states_1[2] = { - {3, arcs_1_0}, - {1, arcs_1_1}, + {3, arcs_1_0}, + {1, arcs_1_1}, }; static arc arcs_2_0[1] = { - {9, 1}, + {9, 1}, }; static arc arcs_2_1[2] = { - {2, 1}, - {7, 2}, + {2, 1}, + {7, 2}, }; static arc arcs_2_2[1] = { - {0, 2}, + {0, 2}, }; static state states_2[3] = { - {1, arcs_2_0}, - {2, arcs_2_1}, - {1, arcs_2_2}, + {1, arcs_2_0}, + {2, arcs_2_1}, + {1, arcs_2_2}, }; static arc arcs_3_0[1] = { - {11, 1}, + {11, 1}, }; static arc arcs_3_1[1] = { - {12, 2}, + {12, 2}, }; static arc arcs_3_2[2] = { - {13, 3}, - {2, 4}, + {13, 3}, + {2, 4}, }; static arc arcs_3_3[2] = { - {14, 5}, - {15, 6}, + {14, 5}, + {15, 6}, }; static arc arcs_3_4[1] = { - {0, 4}, + {0, 4}, }; static arc arcs_3_5[1] = { - {15, 6}, + {15, 6}, }; static arc arcs_3_6[1] = { - {2, 4}, + {2, 4}, }; static state states_3[7] = { - {1, arcs_3_0}, - {1, arcs_3_1}, - {2, arcs_3_2}, - {2, arcs_3_3}, - {1, arcs_3_4}, - {1, arcs_3_5}, - {1, arcs_3_6}, + {1, arcs_3_0}, + {1, arcs_3_1}, + {2, arcs_3_2}, + {2, arcs_3_3}, + {1, arcs_3_4}, + {1, arcs_3_5}, + {1, arcs_3_6}, }; static arc arcs_4_0[1] = { - {10, 1}, + {10, 1}, }; static arc arcs_4_1[2] = { - {10, 1}, - {0, 1}, + {10, 1}, + {0, 1}, }; static state states_4[2] = { - {1, arcs_4_0}, - {2, arcs_4_1}, + {1, arcs_4_0}, + {2, arcs_4_1}, }; static arc arcs_5_0[1] = { - {16, 1}, + {16, 1}, }; static arc arcs_5_1[2] = { - {18, 2}, - {19, 2}, + {18, 2}, + {19, 2}, }; static arc arcs_5_2[1] = { - {0, 2}, + {0, 2}, }; static state states_5[3] = { - {1, arcs_5_0}, - {2, arcs_5_1}, - {1, arcs_5_2}, + {1, arcs_5_0}, + {2, arcs_5_1}, + {1, arcs_5_2}, }; static arc arcs_6_0[1] = { - {20, 1}, + {20, 1}, }; static arc arcs_6_1[1] = { - {21, 2}, + {21, 2}, }; static arc arcs_6_2[1] = { - {22, 3}, + {22, 3}, }; static arc arcs_6_3[1] = { - {23, 4}, + {23, 4}, }; static arc arcs_6_4[1] = { - {24, 5}, + {24, 5}, }; static arc arcs_6_5[1] = { - {0, 5}, + {0, 5}, }; static state states_6[6] = { - {1, arcs_6_0}, - {1, arcs_6_1}, - {1, arcs_6_2}, - {1, arcs_6_3}, - {1, arcs_6_4}, - {1, arcs_6_5}, + {1, arcs_6_0}, + {1, arcs_6_1}, + {1, arcs_6_2}, + {1, arcs_6_3}, + {1, arcs_6_4}, + {1, arcs_6_5}, }; static arc arcs_7_0[1] = { - {13, 1}, + {13, 1}, }; static arc arcs_7_1[2] = { - {25, 2}, - {15, 3}, + {25, 2}, + {15, 3}, }; static arc arcs_7_2[1] = { - {15, 3}, + {15, 3}, }; static arc arcs_7_3[1] = { - {0, 3}, + {0, 3}, }; static state states_7[4] = { - {1, arcs_7_0}, - {2, arcs_7_1}, - {1, arcs_7_2}, - {1, arcs_7_3}, + {1, arcs_7_0}, + {2, arcs_7_1}, + {1, arcs_7_2}, + {1, arcs_7_3}, }; static arc arcs_8_0[3] = { - {26, 1}, - {30, 2}, - {31, 3}, + {26, 1}, + {30, 2}, + {31, 3}, }; static arc arcs_8_1[3] = { - {27, 4}, - {29, 5}, - {0, 1}, + {27, 4}, + {29, 5}, + {0, 1}, }; static arc arcs_8_2[1] = { - {21, 6}, + {21, 6}, }; static arc arcs_8_3[1] = { - {21, 7}, + {21, 7}, }; static arc arcs_8_4[1] = { - {28, 8}, + {28, 8}, }; static arc arcs_8_5[4] = { - {26, 1}, - {30, 2}, - {31, 3}, - {0, 5}, + {26, 1}, + {30, 2}, + {31, 3}, + {0, 5}, }; static arc arcs_8_6[2] = { - {29, 9}, - {0, 6}, + {29, 9}, + {0, 6}, }; static arc arcs_8_7[1] = { - {0, 7}, + {0, 7}, }; static arc arcs_8_8[2] = { - {29, 5}, - {0, 8}, + {29, 5}, + {0, 8}, }; static arc arcs_8_9[1] = { - {31, 3}, + {31, 3}, }; static state states_8[10] = { - {3, arcs_8_0}, - {3, arcs_8_1}, - {1, arcs_8_2}, - {1, arcs_8_3}, - {1, arcs_8_4}, - {4, arcs_8_5}, - {2, arcs_8_6}, - {1, arcs_8_7}, - {2, arcs_8_8}, - {1, arcs_8_9}, + {3, arcs_8_0}, + {3, arcs_8_1}, + {1, arcs_8_2}, + {1, arcs_8_3}, + {1, arcs_8_4}, + {4, arcs_8_5}, + {2, arcs_8_6}, + {1, arcs_8_7}, + {2, arcs_8_8}, + {1, arcs_8_9}, }; static arc arcs_9_0[2] = { - {21, 1}, - {13, 2}, + {21, 1}, + {13, 2}, }; static arc arcs_9_1[1] = { - {0, 1}, + {0, 1}, }; static arc arcs_9_2[1] = { - {32, 3}, + {32, 3}, }; static arc arcs_9_3[1] = { - {15, 1}, + {15, 1}, }; static state states_9[4] = { - {2, arcs_9_0}, - {1, arcs_9_1}, - {1, arcs_9_2}, - {1, arcs_9_3}, + {2, arcs_9_0}, + {1, arcs_9_1}, + {1, arcs_9_2}, + {1, arcs_9_3}, }; static arc arcs_10_0[1] = { - {26, 1}, + {26, 1}, }; static arc arcs_10_1[2] = { - {29, 2}, - {0, 1}, + {29, 2}, + {0, 1}, }; static arc arcs_10_2[2] = { - {26, 1}, - {0, 2}, + {26, 1}, + {0, 2}, }; static state states_10[3] = { - {1, arcs_10_0}, - {2, arcs_10_1}, - {2, arcs_10_2}, + {1, arcs_10_0}, + {2, arcs_10_1}, + {2, arcs_10_2}, }; static arc arcs_11_0[2] = { - {3, 1}, - {4, 1}, + {3, 1}, + {4, 1}, }; static arc arcs_11_1[1] = { - {0, 1}, + {0, 1}, }; static state states_11[2] = { - {2, arcs_11_0}, - {1, arcs_11_1}, + {2, arcs_11_0}, + {1, arcs_11_1}, }; static arc arcs_12_0[1] = { - {33, 1}, + {33, 1}, }; static arc arcs_12_1[2] = { - {34, 2}, - {2, 3}, + {34, 2}, + {2, 3}, }; static arc arcs_12_2[2] = { - {33, 1}, - {2, 3}, + {33, 1}, + {2, 3}, }; static arc arcs_12_3[1] = { - {0, 3}, + {0, 3}, }; static state states_12[4] = { - {1, arcs_12_0}, - {2, arcs_12_1}, - {2, arcs_12_2}, - {1, arcs_12_3}, + {1, arcs_12_0}, + {2, arcs_12_1}, + {2, arcs_12_2}, + {1, arcs_12_3}, }; static arc arcs_13_0[9] = { - {35, 1}, - {36, 1}, - {37, 1}, - {38, 1}, - {39, 1}, - {40, 1}, - {41, 1}, - {42, 1}, - {43, 1}, + {35, 1}, + {36, 1}, + {37, 1}, + {38, 1}, + {39, 1}, + {40, 1}, + {41, 1}, + {42, 1}, + {43, 1}, }; static arc arcs_13_1[1] = { - {0, 1}, + {0, 1}, }; static state states_13[2] = { - {9, arcs_13_0}, - {1, arcs_13_1}, + {9, arcs_13_0}, + {1, arcs_13_1}, }; static arc arcs_14_0[1] = { - {9, 1}, + {9, 1}, }; static arc arcs_14_1[3] = { - {44, 2}, - {27, 3}, - {0, 1}, + {44, 2}, + {27, 3}, + {0, 1}, }; static arc arcs_14_2[2] = { - {45, 4}, - {9, 4}, + {45, 4}, + {9, 4}, }; static arc arcs_14_3[2] = { - {45, 5}, - {9, 5}, + {45, 5}, + {9, 5}, }; static arc arcs_14_4[1] = { - {0, 4}, + {0, 4}, }; static arc arcs_14_5[2] = { - {27, 3}, - {0, 5}, + {27, 3}, + {0, 5}, }; static state states_14[6] = { - {1, arcs_14_0}, - {3, arcs_14_1}, - {2, arcs_14_2}, - {2, arcs_14_3}, - {1, arcs_14_4}, - {2, arcs_14_5}, + {1, arcs_14_0}, + {3, arcs_14_1}, + {2, arcs_14_2}, + {2, arcs_14_3}, + {1, arcs_14_4}, + {2, arcs_14_5}, }; static arc arcs_15_0[12] = { - {46, 1}, - {47, 1}, - {48, 1}, - {49, 1}, - {50, 1}, - {51, 1}, - {52, 1}, - {53, 1}, - {54, 1}, - {55, 1}, - {56, 1}, - {57, 1}, + {46, 1}, + {47, 1}, + {48, 1}, + {49, 1}, + {50, 1}, + {51, 1}, + {52, 1}, + {53, 1}, + {54, 1}, + {55, 1}, + {56, 1}, + {57, 1}, }; static arc arcs_15_1[1] = { - {0, 1}, + {0, 1}, }; static state states_15[2] = { - {12, arcs_15_0}, - {1, arcs_15_1}, + {12, arcs_15_0}, + {1, arcs_15_1}, }; static arc arcs_16_0[1] = { - {58, 1}, + {58, 1}, }; static arc arcs_16_1[3] = { - {28, 2}, - {59, 3}, - {0, 1}, + {28, 2}, + {59, 3}, + {0, 1}, }; static arc arcs_16_2[2] = { - {29, 4}, - {0, 2}, + {29, 4}, + {0, 2}, }; static arc arcs_16_3[1] = { - {28, 5}, + {28, 5}, }; static arc arcs_16_4[2] = { - {28, 2}, - {0, 4}, + {28, 2}, + {0, 4}, }; static arc arcs_16_5[2] = { - {29, 6}, - {0, 5}, + {29, 6}, + {0, 5}, }; static arc arcs_16_6[1] = { - {28, 7}, + {28, 7}, }; static arc arcs_16_7[2] = { - {29, 8}, - {0, 7}, + {29, 8}, + {0, 7}, }; static arc arcs_16_8[2] = { - {28, 7}, - {0, 8}, + {28, 7}, + {0, 8}, }; static state states_16[9] = { - {1, arcs_16_0}, - {3, arcs_16_1}, - {2, arcs_16_2}, - {1, arcs_16_3}, - {2, arcs_16_4}, - {2, arcs_16_5}, - {1, arcs_16_6}, - {2, arcs_16_7}, - {2, arcs_16_8}, + {1, arcs_16_0}, + {3, arcs_16_1}, + {2, arcs_16_2}, + {1, arcs_16_3}, + {2, arcs_16_4}, + {2, arcs_16_5}, + {1, arcs_16_6}, + {2, arcs_16_7}, + {2, arcs_16_8}, }; static arc arcs_17_0[1] = { - {60, 1}, + {60, 1}, }; static arc arcs_17_1[1] = { - {61, 2}, + {61, 2}, }; static arc arcs_17_2[1] = { - {0, 2}, + {0, 2}, }; static state states_17[3] = { - {1, arcs_17_0}, - {1, arcs_17_1}, - {1, arcs_17_2}, + {1, arcs_17_0}, + {1, arcs_17_1}, + {1, arcs_17_2}, }; static arc arcs_18_0[1] = { - {62, 1}, + {62, 1}, }; static arc arcs_18_1[1] = { - {0, 1}, + {0, 1}, }; static state states_18[2] = { - {1, arcs_18_0}, - {1, arcs_18_1}, + {1, arcs_18_0}, + {1, arcs_18_1}, }; static arc arcs_19_0[5] = { - {63, 1}, - {64, 1}, - {65, 1}, - {66, 1}, - {67, 1}, + {63, 1}, + {64, 1}, + {65, 1}, + {66, 1}, + {67, 1}, }; static arc arcs_19_1[1] = { - {0, 1}, + {0, 1}, }; static state states_19[2] = { - {5, arcs_19_0}, - {1, arcs_19_1}, + {5, arcs_19_0}, + {1, arcs_19_1}, }; static arc arcs_20_0[1] = { - {68, 1}, + {68, 1}, }; static arc arcs_20_1[1] = { - {0, 1}, + {0, 1}, }; static state states_20[2] = { - {1, arcs_20_0}, - {1, arcs_20_1}, + {1, arcs_20_0}, + {1, arcs_20_1}, }; static arc arcs_21_0[1] = { - {69, 1}, + {69, 1}, }; static arc arcs_21_1[1] = { - {0, 1}, + {0, 1}, }; static state states_21[2] = { - {1, arcs_21_0}, - {1, arcs_21_1}, + {1, arcs_21_0}, + {1, arcs_21_1}, }; static arc arcs_22_0[1] = { - {70, 1}, + {70, 1}, }; static arc arcs_22_1[2] = { - {9, 2}, - {0, 1}, + {9, 2}, + {0, 1}, }; static arc arcs_22_2[1] = { - {0, 2}, + {0, 2}, }; static state states_22[3] = { - {1, arcs_22_0}, - {2, arcs_22_1}, - {1, arcs_22_2}, + {1, arcs_22_0}, + {2, arcs_22_1}, + {1, arcs_22_2}, }; static arc arcs_23_0[1] = { - {45, 1}, + {45, 1}, }; static arc arcs_23_1[1] = { - {0, 1}, + {0, 1}, }; static state states_23[2] = { - {1, arcs_23_0}, - {1, arcs_23_1}, + {1, arcs_23_0}, + {1, arcs_23_1}, }; static arc arcs_24_0[1] = { - {71, 1}, + {71, 1}, }; static arc arcs_24_1[2] = { - {28, 2}, - {0, 1}, + {28, 2}, + {0, 1}, }; static arc arcs_24_2[2] = { - {29, 3}, - {0, 2}, + {29, 3}, + {0, 2}, }; static arc arcs_24_3[1] = { - {28, 4}, + {28, 4}, }; static arc arcs_24_4[2] = { - {29, 5}, - {0, 4}, + {29, 5}, + {0, 4}, }; static arc arcs_24_5[1] = { - {28, 6}, + {28, 6}, }; static arc arcs_24_6[1] = { - {0, 6}, + {0, 6}, }; static state states_24[7] = { - {1, arcs_24_0}, - {2, arcs_24_1}, - {2, arcs_24_2}, - {1, arcs_24_3}, - {2, arcs_24_4}, - {1, arcs_24_5}, - {1, arcs_24_6}, + {1, arcs_24_0}, + {2, arcs_24_1}, + {2, arcs_24_2}, + {1, arcs_24_3}, + {2, arcs_24_4}, + {1, arcs_24_5}, + {1, arcs_24_6}, }; static arc arcs_25_0[2] = { - {72, 1}, - {73, 1}, + {72, 1}, + {73, 1}, }; static arc arcs_25_1[1] = { - {0, 1}, + {0, 1}, }; static state states_25[2] = { - {2, arcs_25_0}, - {1, arcs_25_1}, + {2, arcs_25_0}, + {1, arcs_25_1}, }; static arc arcs_26_0[1] = { - {74, 1}, + {74, 1}, }; static arc arcs_26_1[1] = { - {75, 2}, + {75, 2}, }; static arc arcs_26_2[1] = { - {0, 2}, + {0, 2}, }; static state states_26[3] = { - {1, arcs_26_0}, - {1, arcs_26_1}, - {1, arcs_26_2}, + {1, arcs_26_0}, + {1, arcs_26_1}, + {1, arcs_26_2}, }; static arc arcs_27_0[1] = { - {76, 1}, + {76, 1}, }; static arc arcs_27_1[2] = { - {77, 2}, - {12, 3}, + {77, 2}, + {12, 3}, }; static arc arcs_27_2[3] = { - {77, 2}, - {12, 3}, - {74, 4}, + {77, 2}, + {12, 3}, + {74, 4}, }; static arc arcs_27_3[1] = { - {74, 4}, + {74, 4}, }; static arc arcs_27_4[3] = { - {30, 5}, - {13, 6}, - {78, 5}, + {30, 5}, + {13, 6}, + {78, 5}, }; static arc arcs_27_5[1] = { - {0, 5}, + {0, 5}, }; static arc arcs_27_6[1] = { - {78, 7}, + {78, 7}, }; static arc arcs_27_7[1] = { - {15, 5}, + {15, 5}, }; static state states_27[8] = { - {1, arcs_27_0}, - {2, arcs_27_1}, - {3, arcs_27_2}, - {1, arcs_27_3}, - {3, arcs_27_4}, - {1, arcs_27_5}, - {1, arcs_27_6}, - {1, arcs_27_7}, + {1, arcs_27_0}, + {2, arcs_27_1}, + {3, arcs_27_2}, + {1, arcs_27_3}, + {3, arcs_27_4}, + {1, arcs_27_5}, + {1, arcs_27_6}, + {1, arcs_27_7}, }; static arc arcs_28_0[1] = { - {21, 1}, + {21, 1}, }; static arc arcs_28_1[2] = { - {80, 2}, - {0, 1}, + {80, 2}, + {0, 1}, }; static arc arcs_28_2[1] = { - {21, 3}, + {21, 3}, }; static arc arcs_28_3[1] = { - {0, 3}, + {0, 3}, }; static state states_28[4] = { - {1, arcs_28_0}, - {2, arcs_28_1}, - {1, arcs_28_2}, - {1, arcs_28_3}, + {1, arcs_28_0}, + {2, arcs_28_1}, + {1, arcs_28_2}, + {1, arcs_28_3}, }; static arc arcs_29_0[1] = { - {12, 1}, + {12, 1}, }; static arc arcs_29_1[2] = { - {80, 2}, - {0, 1}, + {80, 2}, + {0, 1}, }; static arc arcs_29_2[1] = { - {21, 3}, + {21, 3}, }; static arc arcs_29_3[1] = { - {0, 3}, + {0, 3}, }; static state states_29[4] = { - {1, arcs_29_0}, - {2, arcs_29_1}, - {1, arcs_29_2}, - {1, arcs_29_3}, + {1, arcs_29_0}, + {2, arcs_29_1}, + {1, arcs_29_2}, + {1, arcs_29_3}, }; static arc arcs_30_0[1] = { - {79, 1}, + {79, 1}, }; static arc arcs_30_1[2] = { - {29, 2}, - {0, 1}, + {29, 2}, + {0, 1}, }; static arc arcs_30_2[2] = { - {79, 1}, - {0, 2}, + {79, 1}, + {0, 2}, }; static state states_30[3] = { - {1, arcs_30_0}, - {2, arcs_30_1}, - {2, arcs_30_2}, + {1, arcs_30_0}, + {2, arcs_30_1}, + {2, arcs_30_2}, }; static arc arcs_31_0[1] = { - {81, 1}, + {81, 1}, }; static arc arcs_31_1[2] = { - {29, 0}, - {0, 1}, + {29, 0}, + {0, 1}, }; static state states_31[2] = { - {1, arcs_31_0}, - {2, arcs_31_1}, + {1, arcs_31_0}, + {2, arcs_31_1}, }; static arc arcs_32_0[1] = { - {21, 1}, + {21, 1}, }; static arc arcs_32_1[2] = { - {77, 0}, - {0, 1}, + {77, 0}, + {0, 1}, }; static state states_32[2] = { - {1, arcs_32_0}, - {2, arcs_32_1}, + {1, arcs_32_0}, + {2, arcs_32_1}, }; static arc arcs_33_0[1] = { - {82, 1}, + {82, 1}, }; static arc arcs_33_1[1] = { - {21, 2}, + {21, 2}, }; static arc arcs_33_2[2] = { - {29, 1}, - {0, 2}, + {29, 1}, + {0, 2}, }; static state states_33[3] = { - {1, arcs_33_0}, - {1, arcs_33_1}, - {2, arcs_33_2}, + {1, arcs_33_0}, + {1, arcs_33_1}, + {2, arcs_33_2}, }; static arc arcs_34_0[1] = { - {83, 1}, + {83, 1}, }; static arc arcs_34_1[1] = { - {84, 2}, + {84, 2}, }; static arc arcs_34_2[2] = { - {85, 3}, - {0, 2}, + {85, 3}, + {0, 2}, }; static arc arcs_34_3[1] = { - {28, 4}, + {28, 4}, }; static arc arcs_34_4[2] = { - {29, 5}, - {0, 4}, + {29, 5}, + {0, 4}, }; static arc arcs_34_5[1] = { - {28, 6}, + {28, 6}, }; static arc arcs_34_6[1] = { - {0, 6}, + {0, 6}, }; static state states_34[7] = { - {1, arcs_34_0}, - {1, arcs_34_1}, - {2, arcs_34_2}, - {1, arcs_34_3}, - {2, arcs_34_4}, - {1, arcs_34_5}, - {1, arcs_34_6}, + {1, arcs_34_0}, + {1, arcs_34_1}, + {2, arcs_34_2}, + {1, arcs_34_3}, + {2, arcs_34_4}, + {1, arcs_34_5}, + {1, arcs_34_6}, }; static arc arcs_35_0[1] = { - {86, 1}, + {86, 1}, }; static arc arcs_35_1[1] = { - {28, 2}, + {28, 2}, }; static arc arcs_35_2[2] = { - {29, 3}, - {0, 2}, + {29, 3}, + {0, 2}, }; static arc arcs_35_3[1] = { - {28, 4}, + {28, 4}, }; static arc arcs_35_4[1] = { - {0, 4}, + {0, 4}, }; static state states_35[5] = { - {1, arcs_35_0}, - {1, arcs_35_1}, - {2, arcs_35_2}, - {1, arcs_35_3}, - {1, arcs_35_4}, + {1, arcs_35_0}, + {1, arcs_35_1}, + {2, arcs_35_2}, + {1, arcs_35_3}, + {1, arcs_35_4}, }; static arc arcs_36_0[8] = { - {87, 1}, - {88, 1}, - {89, 1}, - {90, 1}, - {91, 1}, - {19, 1}, - {18, 1}, - {17, 1}, + {87, 1}, + {88, 1}, + {89, 1}, + {90, 1}, + {91, 1}, + {19, 1}, + {18, 1}, + {17, 1}, }; static arc arcs_36_1[1] = { - {0, 1}, + {0, 1}, }; static state states_36[2] = { - {8, arcs_36_0}, - {1, arcs_36_1}, + {8, arcs_36_0}, + {1, arcs_36_1}, }; static arc arcs_37_0[1] = { - {92, 1}, + {92, 1}, }; static arc arcs_37_1[1] = { - {28, 2}, + {28, 2}, }; static arc arcs_37_2[1] = { - {23, 3}, + {23, 3}, }; static arc arcs_37_3[1] = { - {24, 4}, + {24, 4}, }; static arc arcs_37_4[3] = { - {93, 1}, - {94, 5}, - {0, 4}, + {93, 1}, + {94, 5}, + {0, 4}, }; static arc arcs_37_5[1] = { - {23, 6}, + {23, 6}, }; static arc arcs_37_6[1] = { - {24, 7}, + {24, 7}, }; static arc arcs_37_7[1] = { - {0, 7}, + {0, 7}, }; static state states_37[8] = { - {1, arcs_37_0}, - {1, arcs_37_1}, - {1, arcs_37_2}, - {1, arcs_37_3}, - {3, arcs_37_4}, - {1, arcs_37_5}, - {1, arcs_37_6}, - {1, arcs_37_7}, + {1, arcs_37_0}, + {1, arcs_37_1}, + {1, arcs_37_2}, + {1, arcs_37_3}, + {3, arcs_37_4}, + {1, arcs_37_5}, + {1, arcs_37_6}, + {1, arcs_37_7}, }; static arc arcs_38_0[1] = { - {95, 1}, + {95, 1}, }; static arc arcs_38_1[1] = { - {28, 2}, + {28, 2}, }; static arc arcs_38_2[1] = { - {23, 3}, + {23, 3}, }; static arc arcs_38_3[1] = { - {24, 4}, + {24, 4}, }; static arc arcs_38_4[2] = { - {94, 5}, - {0, 4}, + {94, 5}, + {0, 4}, }; static arc arcs_38_5[1] = { - {23, 6}, + {23, 6}, }; static arc arcs_38_6[1] = { - {24, 7}, + {24, 7}, }; static arc arcs_38_7[1] = { - {0, 7}, + {0, 7}, }; static state states_38[8] = { - {1, arcs_38_0}, - {1, arcs_38_1}, - {1, arcs_38_2}, - {1, arcs_38_3}, - {2, arcs_38_4}, - {1, arcs_38_5}, - {1, arcs_38_6}, - {1, arcs_38_7}, + {1, arcs_38_0}, + {1, arcs_38_1}, + {1, arcs_38_2}, + {1, arcs_38_3}, + {2, arcs_38_4}, + {1, arcs_38_5}, + {1, arcs_38_6}, + {1, arcs_38_7}, }; static arc arcs_39_0[1] = { - {96, 1}, + {96, 1}, }; static arc arcs_39_1[1] = { - {61, 2}, + {61, 2}, }; static arc arcs_39_2[1] = { - {85, 3}, + {85, 3}, }; static arc arcs_39_3[1] = { - {9, 4}, + {9, 4}, }; static arc arcs_39_4[1] = { - {23, 5}, + {23, 5}, }; static arc arcs_39_5[1] = { - {24, 6}, + {24, 6}, }; static arc arcs_39_6[2] = { - {94, 7}, - {0, 6}, + {94, 7}, + {0, 6}, }; static arc arcs_39_7[1] = { - {23, 8}, + {23, 8}, }; static arc arcs_39_8[1] = { - {24, 9}, + {24, 9}, }; static arc arcs_39_9[1] = { - {0, 9}, + {0, 9}, }; static state states_39[10] = { - {1, arcs_39_0}, - {1, arcs_39_1}, - {1, arcs_39_2}, - {1, arcs_39_3}, - {1, arcs_39_4}, - {1, arcs_39_5}, - {2, arcs_39_6}, - {1, arcs_39_7}, - {1, arcs_39_8}, - {1, arcs_39_9}, + {1, arcs_39_0}, + {1, arcs_39_1}, + {1, arcs_39_2}, + {1, arcs_39_3}, + {1, arcs_39_4}, + {1, arcs_39_5}, + {2, arcs_39_6}, + {1, arcs_39_7}, + {1, arcs_39_8}, + {1, arcs_39_9}, }; static arc arcs_40_0[1] = { - {97, 1}, + {97, 1}, }; static arc arcs_40_1[1] = { - {23, 2}, + {23, 2}, }; static arc arcs_40_2[1] = { - {24, 3}, + {24, 3}, }; static arc arcs_40_3[2] = { - {98, 4}, - {99, 5}, + {98, 4}, + {99, 5}, }; static arc arcs_40_4[1] = { - {23, 6}, + {23, 6}, }; static arc arcs_40_5[1] = { - {23, 7}, + {23, 7}, }; static arc arcs_40_6[1] = { - {24, 8}, + {24, 8}, }; static arc arcs_40_7[1] = { - {24, 9}, + {24, 9}, }; static arc arcs_40_8[4] = { - {98, 4}, - {94, 10}, - {99, 5}, - {0, 8}, + {98, 4}, + {94, 10}, + {99, 5}, + {0, 8}, }; static arc arcs_40_9[1] = { - {0, 9}, + {0, 9}, }; static arc arcs_40_10[1] = { - {23, 11}, + {23, 11}, }; static arc arcs_40_11[1] = { - {24, 12}, + {24, 12}, }; static arc arcs_40_12[2] = { - {99, 5}, - {0, 12}, + {99, 5}, + {0, 12}, }; static state states_40[13] = { - {1, arcs_40_0}, - {1, arcs_40_1}, - {1, arcs_40_2}, - {2, arcs_40_3}, - {1, arcs_40_4}, - {1, arcs_40_5}, - {1, arcs_40_6}, - {1, arcs_40_7}, - {4, arcs_40_8}, - {1, arcs_40_9}, - {1, arcs_40_10}, - {1, arcs_40_11}, - {2, arcs_40_12}, + {1, arcs_40_0}, + {1, arcs_40_1}, + {1, arcs_40_2}, + {2, arcs_40_3}, + {1, arcs_40_4}, + {1, arcs_40_5}, + {1, arcs_40_6}, + {1, arcs_40_7}, + {4, arcs_40_8}, + {1, arcs_40_9}, + {1, arcs_40_10}, + {1, arcs_40_11}, + {2, arcs_40_12}, }; static arc arcs_41_0[1] = { - {100, 1}, + {100, 1}, }; static arc arcs_41_1[1] = { - {101, 2}, + {101, 2}, }; static arc arcs_41_2[2] = { - {29, 1}, - {23, 3}, + {29, 1}, + {23, 3}, }; static arc arcs_41_3[1] = { - {24, 4}, + {24, 4}, }; static arc arcs_41_4[1] = { - {0, 4}, + {0, 4}, }; static state states_41[5] = { - {1, arcs_41_0}, - {1, arcs_41_1}, - {2, arcs_41_2}, - {1, arcs_41_3}, - {1, arcs_41_4}, + {1, arcs_41_0}, + {1, arcs_41_1}, + {2, arcs_41_2}, + {1, arcs_41_3}, + {1, arcs_41_4}, }; static arc arcs_42_0[1] = { - {28, 1}, + {28, 1}, }; static arc arcs_42_1[2] = { - {80, 2}, - {0, 1}, + {80, 2}, + {0, 1}, }; static arc arcs_42_2[1] = { - {84, 3}, + {84, 3}, }; static arc arcs_42_3[1] = { - {0, 3}, + {0, 3}, }; static state states_42[4] = { - {1, arcs_42_0}, - {2, arcs_42_1}, - {1, arcs_42_2}, - {1, arcs_42_3}, + {1, arcs_42_0}, + {2, arcs_42_1}, + {1, arcs_42_2}, + {1, arcs_42_3}, }; static arc arcs_43_0[1] = { - {102, 1}, + {102, 1}, }; static arc arcs_43_1[2] = { - {28, 2}, - {0, 1}, + {28, 2}, + {0, 1}, }; static arc arcs_43_2[3] = { - {80, 3}, - {29, 3}, - {0, 2}, + {80, 3}, + {29, 3}, + {0, 2}, }; static arc arcs_43_3[1] = { - {28, 4}, + {28, 4}, }; static arc arcs_43_4[1] = { - {0, 4}, + {0, 4}, }; static state states_43[5] = { - {1, arcs_43_0}, - {2, arcs_43_1}, - {3, arcs_43_2}, - {1, arcs_43_3}, - {1, arcs_43_4}, + {1, arcs_43_0}, + {2, arcs_43_1}, + {3, arcs_43_2}, + {1, arcs_43_3}, + {1, arcs_43_4}, }; static arc arcs_44_0[2] = { - {3, 1}, - {2, 2}, + {3, 1}, + {2, 2}, }; static arc arcs_44_1[1] = { - {0, 1}, + {0, 1}, }; static arc arcs_44_2[1] = { - {103, 3}, + {103, 3}, }; static arc arcs_44_3[1] = { - {6, 4}, + {6, 4}, }; static arc arcs_44_4[2] = { - {6, 4}, - {104, 1}, + {6, 4}, + {104, 1}, }; static state states_44[5] = { - {2, arcs_44_0}, - {1, arcs_44_1}, - {1, arcs_44_2}, - {1, arcs_44_3}, - {2, arcs_44_4}, + {2, arcs_44_0}, + {1, arcs_44_1}, + {1, arcs_44_2}, + {1, arcs_44_3}, + {2, arcs_44_4}, }; static arc arcs_45_0[1] = { - {106, 1}, + {106, 1}, }; static arc arcs_45_1[2] = { - {29, 2}, - {0, 1}, + {29, 2}, + {0, 1}, }; static arc arcs_45_2[1] = { - {106, 3}, + {106, 3}, }; static arc arcs_45_3[2] = { - {29, 4}, - {0, 3}, + {29, 4}, + {0, 3}, }; static arc arcs_45_4[2] = { - {106, 3}, - {0, 4}, + {106, 3}, + {0, 4}, }; static state states_45[5] = { - {1, arcs_45_0}, - {2, arcs_45_1}, - {1, arcs_45_2}, - {2, arcs_45_3}, - {2, arcs_45_4}, + {1, arcs_45_0}, + {2, arcs_45_1}, + {1, arcs_45_2}, + {2, arcs_45_3}, + {2, arcs_45_4}, }; static arc arcs_46_0[2] = { - {107, 1}, - {108, 1}, + {107, 1}, + {108, 1}, }; static arc arcs_46_1[1] = { - {0, 1}, + {0, 1}, }; static state states_46[2] = { - {2, arcs_46_0}, - {1, arcs_46_1}, + {2, arcs_46_0}, + {1, arcs_46_1}, }; static arc arcs_47_0[1] = { - {109, 1}, + {109, 1}, }; static arc arcs_47_1[2] = { - {25, 2}, - {23, 3}, + {25, 2}, + {23, 3}, }; static arc arcs_47_2[1] = { - {23, 3}, + {23, 3}, }; static arc arcs_47_3[1] = { - {106, 4}, + {106, 4}, }; static arc arcs_47_4[1] = { - {0, 4}, + {0, 4}, }; static state states_47[5] = { - {1, arcs_47_0}, - {2, arcs_47_1}, - {1, arcs_47_2}, - {1, arcs_47_3}, - {1, arcs_47_4}, + {1, arcs_47_0}, + {2, arcs_47_1}, + {1, arcs_47_2}, + {1, arcs_47_3}, + {1, arcs_47_4}, }; static arc arcs_48_0[2] = { - {107, 1}, - {110, 2}, + {107, 1}, + {110, 2}, }; static arc arcs_48_1[2] = { - {92, 3}, - {0, 1}, + {92, 3}, + {0, 1}, }; static arc arcs_48_2[1] = { - {0, 2}, + {0, 2}, }; static arc arcs_48_3[1] = { - {107, 4}, + {107, 4}, }; static arc arcs_48_4[1] = { - {94, 5}, + {94, 5}, }; static arc arcs_48_5[1] = { - {28, 2}, + {28, 2}, }; static state states_48[6] = { - {2, arcs_48_0}, - {2, arcs_48_1}, - {1, arcs_48_2}, - {1, arcs_48_3}, - {1, arcs_48_4}, - {1, arcs_48_5}, + {2, arcs_48_0}, + {2, arcs_48_1}, + {1, arcs_48_2}, + {1, arcs_48_3}, + {1, arcs_48_4}, + {1, arcs_48_5}, }; static arc arcs_49_0[1] = { - {111, 1}, + {111, 1}, }; static arc arcs_49_1[2] = { - {112, 0}, - {0, 1}, + {112, 0}, + {0, 1}, }; static state states_49[2] = { - {1, arcs_49_0}, - {2, arcs_49_1}, + {1, arcs_49_0}, + {2, arcs_49_1}, }; static arc arcs_50_0[1] = { - {113, 1}, + {113, 1}, }; static arc arcs_50_1[2] = { - {114, 0}, - {0, 1}, + {114, 0}, + {0, 1}, }; static state states_50[2] = { - {1, arcs_50_0}, - {2, arcs_50_1}, + {1, arcs_50_0}, + {2, arcs_50_1}, }; static arc arcs_51_0[2] = { - {115, 1}, - {116, 2}, + {115, 1}, + {116, 2}, }; static arc arcs_51_1[1] = { - {113, 2}, + {113, 2}, }; static arc arcs_51_2[1] = { - {0, 2}, + {0, 2}, }; static state states_51[3] = { - {2, arcs_51_0}, - {1, arcs_51_1}, - {1, arcs_51_2}, + {2, arcs_51_0}, + {1, arcs_51_1}, + {1, arcs_51_2}, }; static arc arcs_52_0[1] = { - {84, 1}, + {84, 1}, }; static arc arcs_52_1[2] = { - {117, 0}, - {0, 1}, + {117, 0}, + {0, 1}, }; static state states_52[2] = { - {1, arcs_52_0}, - {2, arcs_52_1}, + {1, arcs_52_0}, + {2, arcs_52_1}, }; static arc arcs_53_0[10] = { - {118, 1}, - {119, 1}, - {120, 1}, - {121, 1}, - {122, 1}, - {123, 1}, - {124, 1}, - {85, 1}, - {115, 2}, - {125, 3}, + {118, 1}, + {119, 1}, + {120, 1}, + {121, 1}, + {122, 1}, + {123, 1}, + {124, 1}, + {85, 1}, + {115, 2}, + {125, 3}, }; static arc arcs_53_1[1] = { - {0, 1}, + {0, 1}, }; static arc arcs_53_2[1] = { - {85, 1}, + {85, 1}, }; static arc arcs_53_3[2] = { - {115, 1}, - {0, 3}, + {115, 1}, + {0, 3}, }; static state states_53[4] = { - {10, arcs_53_0}, - {1, arcs_53_1}, - {1, arcs_53_2}, - {2, arcs_53_3}, + {10, arcs_53_0}, + {1, arcs_53_1}, + {1, arcs_53_2}, + {2, arcs_53_3}, }; static arc arcs_54_0[1] = { - {126, 1}, + {126, 1}, }; static arc arcs_54_1[2] = { - {127, 0}, - {0, 1}, + {127, 0}, + {0, 1}, }; static state states_54[2] = { - {1, arcs_54_0}, - {2, arcs_54_1}, + {1, arcs_54_0}, + {2, arcs_54_1}, }; static arc arcs_55_0[1] = { - {128, 1}, + {128, 1}, }; static arc arcs_55_1[2] = { - {129, 0}, - {0, 1}, + {129, 0}, + {0, 1}, }; static state states_55[2] = { - {1, arcs_55_0}, - {2, arcs_55_1}, + {1, arcs_55_0}, + {2, arcs_55_1}, }; static arc arcs_56_0[1] = { - {130, 1}, + {130, 1}, }; static arc arcs_56_1[2] = { - {131, 0}, - {0, 1}, + {131, 0}, + {0, 1}, }; static state states_56[2] = { - {1, arcs_56_0}, - {2, arcs_56_1}, + {1, arcs_56_0}, + {2, arcs_56_1}, }; static arc arcs_57_0[1] = { - {132, 1}, + {132, 1}, }; static arc arcs_57_1[3] = { - {133, 0}, - {59, 0}, - {0, 1}, + {133, 0}, + {59, 0}, + {0, 1}, }; static state states_57[2] = { - {1, arcs_57_0}, - {3, arcs_57_1}, + {1, arcs_57_0}, + {3, arcs_57_1}, }; static arc arcs_58_0[1] = { - {134, 1}, + {134, 1}, }; static arc arcs_58_1[3] = { - {135, 0}, - {136, 0}, - {0, 1}, + {135, 0}, + {136, 0}, + {0, 1}, }; static state states_58[2] = { - {1, arcs_58_0}, - {3, arcs_58_1}, + {1, arcs_58_0}, + {3, arcs_58_1}, }; static arc arcs_59_0[1] = { - {137, 1}, + {137, 1}, }; static arc arcs_59_1[5] = { - {30, 0}, - {138, 0}, - {139, 0}, - {140, 0}, - {0, 1}, + {30, 0}, + {138, 0}, + {139, 0}, + {140, 0}, + {0, 1}, }; static state states_59[2] = { - {1, arcs_59_0}, - {5, arcs_59_1}, + {1, arcs_59_0}, + {5, arcs_59_1}, }; static arc arcs_60_0[4] = { - {135, 1}, - {136, 1}, - {141, 1}, - {142, 2}, + {135, 1}, + {136, 1}, + {141, 1}, + {142, 2}, }; static arc arcs_60_1[1] = { - {137, 2}, + {137, 2}, }; static arc arcs_60_2[1] = { - {0, 2}, + {0, 2}, }; static state states_60[3] = { - {4, arcs_60_0}, - {1, arcs_60_1}, - {1, arcs_60_2}, + {4, arcs_60_0}, + {1, arcs_60_1}, + {1, arcs_60_2}, }; static arc arcs_61_0[1] = { - {143, 1}, + {143, 1}, }; static arc arcs_61_1[3] = { - {144, 1}, - {31, 2}, - {0, 1}, + {144, 1}, + {31, 2}, + {0, 1}, }; static arc arcs_61_2[1] = { - {137, 3}, + {137, 3}, }; static arc arcs_61_3[1] = { - {0, 3}, + {0, 3}, }; static state states_61[4] = { - {1, arcs_61_0}, - {3, arcs_61_1}, - {1, arcs_61_2}, - {1, arcs_61_3}, + {1, arcs_61_0}, + {3, arcs_61_1}, + {1, arcs_61_2}, + {1, arcs_61_3}, }; static arc arcs_62_0[7] = { - {13, 1}, - {146, 2}, - {149, 3}, - {152, 4}, - {21, 5}, - {154, 5}, - {155, 6}, + {13, 1}, + {146, 2}, + {149, 3}, + {152, 4}, + {21, 5}, + {154, 5}, + {155, 6}, }; static arc arcs_62_1[3] = { - {45, 7}, - {145, 7}, - {15, 5}, + {45, 7}, + {145, 7}, + {15, 5}, }; static arc arcs_62_2[2] = { - {147, 8}, - {148, 5}, + {147, 8}, + {148, 5}, }; static arc arcs_62_3[2] = { - {150, 9}, - {151, 5}, + {150, 9}, + {151, 5}, }; static arc arcs_62_4[1] = { - {153, 10}, + {153, 10}, }; static arc arcs_62_5[1] = { - {0, 5}, + {0, 5}, }; static arc arcs_62_6[2] = { - {155, 6}, - {0, 6}, + {155, 6}, + {0, 6}, }; static arc arcs_62_7[1] = { - {15, 5}, + {15, 5}, }; static arc arcs_62_8[1] = { - {148, 5}, + {148, 5}, }; static arc arcs_62_9[1] = { - {151, 5}, + {151, 5}, }; static arc arcs_62_10[1] = { - {152, 5}, + {152, 5}, }; static state states_62[11] = { - {7, arcs_62_0}, - {3, arcs_62_1}, - {2, arcs_62_2}, - {2, arcs_62_3}, - {1, arcs_62_4}, - {1, arcs_62_5}, - {2, arcs_62_6}, - {1, arcs_62_7}, - {1, arcs_62_8}, - {1, arcs_62_9}, - {1, arcs_62_10}, + {7, arcs_62_0}, + {3, arcs_62_1}, + {2, arcs_62_2}, + {2, arcs_62_3}, + {1, arcs_62_4}, + {1, arcs_62_5}, + {2, arcs_62_6}, + {1, arcs_62_7}, + {1, arcs_62_8}, + {1, arcs_62_9}, + {1, arcs_62_10}, }; static arc arcs_63_0[1] = { - {28, 1}, + {28, 1}, }; static arc arcs_63_1[3] = { - {156, 2}, - {29, 3}, - {0, 1}, + {156, 2}, + {29, 3}, + {0, 1}, }; static arc arcs_63_2[1] = { - {0, 2}, + {0, 2}, }; static arc arcs_63_3[2] = { - {28, 4}, - {0, 3}, + {28, 4}, + {0, 3}, }; static arc arcs_63_4[2] = { - {29, 3}, - {0, 4}, + {29, 3}, + {0, 4}, }; static state states_63[5] = { - {1, arcs_63_0}, - {3, arcs_63_1}, - {1, arcs_63_2}, - {2, arcs_63_3}, - {2, arcs_63_4}, + {1, arcs_63_0}, + {3, arcs_63_1}, + {1, arcs_63_2}, + {2, arcs_63_3}, + {2, arcs_63_4}, }; static arc arcs_64_0[1] = { - {28, 1}, + {28, 1}, }; static arc arcs_64_1[3] = { - {157, 2}, - {29, 3}, - {0, 1}, + {157, 2}, + {29, 3}, + {0, 1}, }; static arc arcs_64_2[1] = { - {0, 2}, + {0, 2}, }; static arc arcs_64_3[2] = { - {28, 4}, - {0, 3}, + {28, 4}, + {0, 3}, }; static arc arcs_64_4[2] = { - {29, 3}, - {0, 4}, + {29, 3}, + {0, 4}, }; static state states_64[5] = { - {1, arcs_64_0}, - {3, arcs_64_1}, - {1, arcs_64_2}, - {2, arcs_64_3}, - {2, arcs_64_4}, + {1, arcs_64_0}, + {3, arcs_64_1}, + {1, arcs_64_2}, + {2, arcs_64_3}, + {2, arcs_64_4}, }; static arc arcs_65_0[1] = { - {109, 1}, + {109, 1}, }; static arc arcs_65_1[2] = { - {25, 2}, - {23, 3}, + {25, 2}, + {23, 3}, }; static arc arcs_65_2[1] = { - {23, 3}, + {23, 3}, }; static arc arcs_65_3[1] = { - {28, 4}, + {28, 4}, }; static arc arcs_65_4[1] = { - {0, 4}, + {0, 4}, }; static state states_65[5] = { - {1, arcs_65_0}, - {2, arcs_65_1}, - {1, arcs_65_2}, - {1, arcs_65_3}, - {1, arcs_65_4}, + {1, arcs_65_0}, + {2, arcs_65_1}, + {1, arcs_65_2}, + {1, arcs_65_3}, + {1, arcs_65_4}, }; static arc arcs_66_0[3] = { - {13, 1}, - {146, 2}, - {77, 3}, + {13, 1}, + {146, 2}, + {77, 3}, }; static arc arcs_66_1[2] = { - {14, 4}, - {15, 5}, + {14, 4}, + {15, 5}, }; static arc arcs_66_2[1] = { - {158, 6}, + {158, 6}, }; static arc arcs_66_3[1] = { - {21, 5}, + {21, 5}, }; static arc arcs_66_4[1] = { - {15, 5}, + {15, 5}, }; static arc arcs_66_5[1] = { - {0, 5}, + {0, 5}, }; static arc arcs_66_6[1] = { - {148, 5}, + {148, 5}, }; static state states_66[7] = { - {3, arcs_66_0}, - {2, arcs_66_1}, - {1, arcs_66_2}, - {1, arcs_66_3}, - {1, arcs_66_4}, - {1, arcs_66_5}, - {1, arcs_66_6}, + {3, arcs_66_0}, + {2, arcs_66_1}, + {1, arcs_66_2}, + {1, arcs_66_3}, + {1, arcs_66_4}, + {1, arcs_66_5}, + {1, arcs_66_6}, }; static arc arcs_67_0[1] = { - {159, 1}, + {159, 1}, }; static arc arcs_67_1[2] = { - {29, 2}, - {0, 1}, + {29, 2}, + {0, 1}, }; static arc arcs_67_2[2] = { - {159, 1}, - {0, 2}, + {159, 1}, + {0, 2}, }; static state states_67[3] = { - {1, arcs_67_0}, - {2, arcs_67_1}, - {2, arcs_67_2}, + {1, arcs_67_0}, + {2, arcs_67_1}, + {2, arcs_67_2}, }; static arc arcs_68_0[3] = { - {77, 1}, - {28, 2}, - {23, 3}, + {77, 1}, + {28, 2}, + {23, 3}, }; static arc arcs_68_1[1] = { - {77, 4}, + {77, 4}, }; static arc arcs_68_2[2] = { - {23, 3}, - {0, 2}, + {23, 3}, + {0, 2}, }; static arc arcs_68_3[3] = { - {28, 5}, - {160, 6}, - {0, 3}, + {28, 5}, + {160, 6}, + {0, 3}, }; static arc arcs_68_4[1] = { - {77, 6}, + {77, 6}, }; static arc arcs_68_5[2] = { - {160, 6}, - {0, 5}, + {160, 6}, + {0, 5}, }; static arc arcs_68_6[1] = { - {0, 6}, + {0, 6}, }; static state states_68[7] = { - {3, arcs_68_0}, - {1, arcs_68_1}, - {2, arcs_68_2}, - {3, arcs_68_3}, - {1, arcs_68_4}, - {2, arcs_68_5}, - {1, arcs_68_6}, + {3, arcs_68_0}, + {1, arcs_68_1}, + {2, arcs_68_2}, + {3, arcs_68_3}, + {1, arcs_68_4}, + {2, arcs_68_5}, + {1, arcs_68_6}, }; static arc arcs_69_0[1] = { - {23, 1}, + {23, 1}, }; static arc arcs_69_1[2] = { - {28, 2}, - {0, 1}, + {28, 2}, + {0, 1}, }; static arc arcs_69_2[1] = { - {0, 2}, + {0, 2}, }; static state states_69[3] = { - {1, arcs_69_0}, - {2, arcs_69_1}, - {1, arcs_69_2}, + {1, arcs_69_0}, + {2, arcs_69_1}, + {1, arcs_69_2}, }; static arc arcs_70_0[1] = { - {84, 1}, + {84, 1}, }; static arc arcs_70_1[2] = { - {29, 2}, - {0, 1}, + {29, 2}, + {0, 1}, }; static arc arcs_70_2[2] = { - {84, 1}, - {0, 2}, + {84, 1}, + {0, 2}, }; static state states_70[3] = { - {1, arcs_70_0}, - {2, arcs_70_1}, - {2, arcs_70_2}, + {1, arcs_70_0}, + {2, arcs_70_1}, + {2, arcs_70_2}, }; static arc arcs_71_0[1] = { - {28, 1}, + {28, 1}, }; static arc arcs_71_1[2] = { - {29, 2}, - {0, 1}, + {29, 2}, + {0, 1}, }; static arc arcs_71_2[2] = { - {28, 1}, - {0, 2}, + {28, 1}, + {0, 2}, }; static state states_71[3] = { - {1, arcs_71_0}, - {2, arcs_71_1}, - {2, arcs_71_2}, + {1, arcs_71_0}, + {2, arcs_71_1}, + {2, arcs_71_2}, }; static arc arcs_72_0[1] = { - {28, 1}, + {28, 1}, }; static arc arcs_72_1[1] = { - {23, 2}, + {23, 2}, }; static arc arcs_72_2[1] = { - {28, 3}, + {28, 3}, }; static arc arcs_72_3[2] = { - {29, 4}, - {0, 3}, + {29, 4}, + {0, 3}, }; static arc arcs_72_4[2] = { - {28, 1}, - {0, 4}, + {28, 1}, + {0, 4}, }; static state states_72[5] = { - {1, arcs_72_0}, - {1, arcs_72_1}, - {1, arcs_72_2}, - {2, arcs_72_3}, - {2, arcs_72_4}, + {1, arcs_72_0}, + {1, arcs_72_1}, + {1, arcs_72_2}, + {2, arcs_72_3}, + {2, arcs_72_4}, }; static arc arcs_73_0[1] = { - {28, 1}, + {28, 1}, }; static arc arcs_73_1[4] = { - {23, 2}, - {157, 3}, - {29, 4}, - {0, 1}, + {23, 2}, + {157, 3}, + {29, 4}, + {0, 1}, }; static arc arcs_73_2[1] = { - {28, 5}, + {28, 5}, }; static arc arcs_73_3[1] = { - {0, 3}, + {0, 3}, }; static arc arcs_73_4[2] = { - {28, 6}, - {0, 4}, + {28, 6}, + {0, 4}, }; static arc arcs_73_5[3] = { - {157, 3}, - {29, 7}, - {0, 5}, + {157, 3}, + {29, 7}, + {0, 5}, }; static arc arcs_73_6[2] = { - {29, 4}, - {0, 6}, + {29, 4}, + {0, 6}, }; static arc arcs_73_7[2] = { - {28, 8}, - {0, 7}, + {28, 8}, + {0, 7}, }; static arc arcs_73_8[1] = { - {23, 9}, + {23, 9}, }; static arc arcs_73_9[1] = { - {28, 10}, + {28, 10}, }; static arc arcs_73_10[2] = { - {29, 7}, - {0, 10}, + {29, 7}, + {0, 10}, }; static state states_73[11] = { - {1, arcs_73_0}, - {4, arcs_73_1}, - {1, arcs_73_2}, - {1, arcs_73_3}, - {2, arcs_73_4}, - {3, arcs_73_5}, - {2, arcs_73_6}, - {2, arcs_73_7}, - {1, arcs_73_8}, - {1, arcs_73_9}, - {2, arcs_73_10}, + {1, arcs_73_0}, + {4, arcs_73_1}, + {1, arcs_73_2}, + {1, arcs_73_3}, + {2, arcs_73_4}, + {3, arcs_73_5}, + {2, arcs_73_6}, + {2, arcs_73_7}, + {1, arcs_73_8}, + {1, arcs_73_9}, + {2, arcs_73_10}, }; static arc arcs_74_0[1] = { - {162, 1}, + {162, 1}, }; static arc arcs_74_1[1] = { - {21, 2}, + {21, 2}, }; static arc arcs_74_2[2] = { - {13, 3}, - {23, 4}, + {13, 3}, + {23, 4}, }; static arc arcs_74_3[2] = { - {9, 5}, - {15, 6}, + {9, 5}, + {15, 6}, }; static arc arcs_74_4[1] = { - {24, 7}, + {24, 7}, }; static arc arcs_74_5[1] = { - {15, 6}, + {15, 6}, }; static arc arcs_74_6[1] = { - {23, 4}, + {23, 4}, }; static arc arcs_74_7[1] = { - {0, 7}, + {0, 7}, }; static state states_74[8] = { - {1, arcs_74_0}, - {1, arcs_74_1}, - {2, arcs_74_2}, - {2, arcs_74_3}, - {1, arcs_74_4}, - {1, arcs_74_5}, - {1, arcs_74_6}, - {1, arcs_74_7}, + {1, arcs_74_0}, + {1, arcs_74_1}, + {2, arcs_74_2}, + {2, arcs_74_3}, + {1, arcs_74_4}, + {1, arcs_74_5}, + {1, arcs_74_6}, + {1, arcs_74_7}, }; static arc arcs_75_0[3] = { - {163, 1}, - {30, 2}, - {31, 3}, + {163, 1}, + {30, 2}, + {31, 3}, }; static arc arcs_75_1[2] = { - {29, 4}, - {0, 1}, + {29, 4}, + {0, 1}, }; static arc arcs_75_2[1] = { - {28, 5}, + {28, 5}, }; static arc arcs_75_3[1] = { - {28, 6}, + {28, 6}, }; static arc arcs_75_4[4] = { - {163, 1}, - {30, 2}, - {31, 3}, - {0, 4}, + {163, 1}, + {30, 2}, + {31, 3}, + {0, 4}, }; static arc arcs_75_5[2] = { - {29, 7}, - {0, 5}, + {29, 7}, + {0, 5}, }; static arc arcs_75_6[1] = { - {0, 6}, + {0, 6}, }; static arc arcs_75_7[2] = { - {163, 5}, - {31, 3}, + {163, 5}, + {31, 3}, }; static state states_75[8] = { - {3, arcs_75_0}, - {2, arcs_75_1}, - {1, arcs_75_2}, - {1, arcs_75_3}, - {4, arcs_75_4}, - {2, arcs_75_5}, - {1, arcs_75_6}, - {2, arcs_75_7}, + {3, arcs_75_0}, + {2, arcs_75_1}, + {1, arcs_75_2}, + {1, arcs_75_3}, + {4, arcs_75_4}, + {2, arcs_75_5}, + {1, arcs_75_6}, + {2, arcs_75_7}, }; static arc arcs_76_0[1] = { - {28, 1}, + {28, 1}, }; static arc arcs_76_1[3] = { - {157, 2}, - {27, 3}, - {0, 1}, + {157, 2}, + {27, 3}, + {0, 1}, }; static arc arcs_76_2[1] = { - {0, 2}, + {0, 2}, }; static arc arcs_76_3[1] = { - {28, 2}, + {28, 2}, }; static state states_76[4] = { - {1, arcs_76_0}, - {3, arcs_76_1}, - {1, arcs_76_2}, - {1, arcs_76_3}, + {1, arcs_76_0}, + {3, arcs_76_1}, + {1, arcs_76_2}, + {1, arcs_76_3}, }; static arc arcs_77_0[2] = { - {156, 1}, - {165, 1}, + {156, 1}, + {165, 1}, }; static arc arcs_77_1[1] = { - {0, 1}, + {0, 1}, }; static state states_77[2] = { - {2, arcs_77_0}, - {1, arcs_77_1}, + {2, arcs_77_0}, + {1, arcs_77_1}, }; static arc arcs_78_0[1] = { - {96, 1}, + {96, 1}, }; static arc arcs_78_1[1] = { - {61, 2}, + {61, 2}, }; static arc arcs_78_2[1] = { - {85, 3}, + {85, 3}, }; static arc arcs_78_3[1] = { - {105, 4}, + {105, 4}, }; static arc arcs_78_4[2] = { - {164, 5}, - {0, 4}, + {164, 5}, + {0, 4}, }; static arc arcs_78_5[1] = { - {0, 5}, + {0, 5}, }; static state states_78[6] = { - {1, arcs_78_0}, - {1, arcs_78_1}, - {1, arcs_78_2}, - {1, arcs_78_3}, - {2, arcs_78_4}, - {1, arcs_78_5}, + {1, arcs_78_0}, + {1, arcs_78_1}, + {1, arcs_78_2}, + {1, arcs_78_3}, + {2, arcs_78_4}, + {1, arcs_78_5}, }; static arc arcs_79_0[1] = { - {92, 1}, + {92, 1}, }; static arc arcs_79_1[1] = { - {106, 2}, + {106, 2}, }; static arc arcs_79_2[2] = { - {164, 3}, - {0, 2}, + {164, 3}, + {0, 2}, }; static arc arcs_79_3[1] = { - {0, 3}, + {0, 3}, }; static state states_79[4] = { - {1, arcs_79_0}, - {1, arcs_79_1}, - {2, arcs_79_2}, - {1, arcs_79_3}, + {1, arcs_79_0}, + {1, arcs_79_1}, + {2, arcs_79_2}, + {1, arcs_79_3}, }; static arc arcs_80_0[2] = { - {157, 1}, - {167, 1}, + {157, 1}, + {167, 1}, }; static arc arcs_80_1[1] = { - {0, 1}, + {0, 1}, }; static state states_80[2] = { - {2, arcs_80_0}, - {1, arcs_80_1}, + {2, arcs_80_0}, + {1, arcs_80_1}, }; static arc arcs_81_0[1] = { - {96, 1}, + {96, 1}, }; static arc arcs_81_1[1] = { - {61, 2}, + {61, 2}, }; static arc arcs_81_2[1] = { - {85, 3}, + {85, 3}, }; static arc arcs_81_3[1] = { - {107, 4}, + {107, 4}, }; static arc arcs_81_4[2] = { - {166, 5}, - {0, 4}, + {166, 5}, + {0, 4}, }; static arc arcs_81_5[1] = { - {0, 5}, + {0, 5}, }; static state states_81[6] = { - {1, arcs_81_0}, - {1, arcs_81_1}, - {1, arcs_81_2}, - {1, arcs_81_3}, - {2, arcs_81_4}, - {1, arcs_81_5}, + {1, arcs_81_0}, + {1, arcs_81_1}, + {1, arcs_81_2}, + {1, arcs_81_3}, + {2, arcs_81_4}, + {1, arcs_81_5}, }; static arc arcs_82_0[1] = { - {92, 1}, + {92, 1}, }; static arc arcs_82_1[1] = { - {106, 2}, + {106, 2}, }; static arc arcs_82_2[2] = { - {166, 3}, - {0, 2}, + {166, 3}, + {0, 2}, }; static arc arcs_82_3[1] = { - {0, 3}, + {0, 3}, }; static state states_82[4] = { - {1, arcs_82_0}, - {1, arcs_82_1}, - {2, arcs_82_2}, - {1, arcs_82_3}, + {1, arcs_82_0}, + {1, arcs_82_1}, + {2, arcs_82_2}, + {1, arcs_82_3}, }; static arc arcs_83_0[1] = { - {28, 1}, + {28, 1}, }; static arc arcs_83_1[2] = { - {29, 0}, - {0, 1}, + {29, 0}, + {0, 1}, }; static state states_83[2] = { - {1, arcs_83_0}, - {2, arcs_83_1}, + {1, arcs_83_0}, + {2, arcs_83_1}, }; static arc arcs_84_0[1] = { - {21, 1}, + {21, 1}, }; static arc arcs_84_1[1] = { - {0, 1}, + {0, 1}, }; static state states_84[2] = { - {1, arcs_84_0}, - {1, arcs_84_1}, + {1, arcs_84_0}, + {1, arcs_84_1}, }; static arc arcs_85_0[1] = { - {169, 1}, + {169, 1}, }; static arc arcs_85_1[2] = { - {9, 2}, - {0, 1}, + {9, 2}, + {0, 1}, }; static arc arcs_85_2[1] = { - {0, 2}, + {0, 2}, }; static state states_85[3] = { - {1, arcs_85_0}, - {2, arcs_85_1}, - {1, arcs_85_2}, + {1, arcs_85_0}, + {2, arcs_85_1}, + {1, arcs_85_2}, }; static dfa dfas[86] = { - {256, "single_input", 0, 3, states_0, - "\004\050\060\000\000\000\000\124\360\024\114\220\023\040\010\000\200\041\044\015\004\002"}, - {257, "file_input", 0, 2, states_1, - "\204\050\060\000\000\000\000\124\360\024\114\220\023\040\010\000\200\041\044\015\004\002"}, - {258, "eval_input", 0, 3, states_2, - "\000\040\040\000\000\000\000\000\000\000\000\000\000\040\010\000\200\041\044\015\000\000"}, - {259, "decorator", 0, 7, states_3, - "\000\010\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000"}, - {260, "decorators", 0, 2, states_4, - "\000\010\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000"}, - {261, "decorated", 0, 3, states_5, - "\000\010\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000"}, - {262, "funcdef", 0, 6, states_6, - "\000\000\020\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000"}, - {263, "parameters", 0, 4, states_7, - "\000\040\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000"}, - {264, "varargslist", 0, 10, states_8, - "\000\040\040\300\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000"}, - {265, "fpdef", 0, 4, states_9, - "\000\040\040\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000"}, - {266, "fplist", 0, 3, states_10, - "\000\040\040\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000"}, - {267, "stmt", 0, 2, states_11, - "\000\050\060\000\000\000\000\124\360\024\114\220\023\040\010\000\200\041\044\015\004\002"}, - {268, "simple_stmt", 0, 4, states_12, - "\000\040\040\000\000\000\000\124\360\024\114\000\000\040\010\000\200\041\044\015\000\002"}, - {269, "small_stmt", 0, 2, states_13, - "\000\040\040\000\000\000\000\124\360\024\114\000\000\040\010\000\200\041\044\015\000\002"}, - {270, "expr_stmt", 0, 6, states_14, - "\000\040\040\000\000\000\000\000\000\000\000\000\000\040\010\000\200\041\044\015\000\000"}, - {271, "augassign", 0, 2, states_15, - "\000\000\000\000\000\300\377\003\000\000\000\000\000\000\000\000\000\000\000\000\000\000"}, - {272, "print_stmt", 0, 9, states_16, - "\000\000\000\000\000\000\000\004\000\000\000\000\000\000\000\000\000\000\000\000\000\000"}, - {273, "del_stmt", 0, 3, states_17, - "\000\000\000\000\000\000\000\020\000\000\000\000\000\000\000\000\000\000\000\000\000\000"}, - {274, "pass_stmt", 0, 2, states_18, - "\000\000\000\000\000\000\000\100\000\000\000\000\000\000\000\000\000\000\000\000\000\000"}, - {275, "flow_stmt", 0, 2, states_19, - "\000\000\000\000\000\000\000\000\360\000\000\000\000\000\000\000\000\000\000\000\000\002"}, - {276, "break_stmt", 0, 2, states_20, - "\000\000\000\000\000\000\000\000\020\000\000\000\000\000\000\000\000\000\000\000\000\000"}, - {277, "continue_stmt", 0, 2, states_21, - "\000\000\000\000\000\000\000\000\040\000\000\000\000\000\000\000\000\000\000\000\000\000"}, - {278, "return_stmt", 0, 3, states_22, - "\000\000\000\000\000\000\000\000\100\000\000\000\000\000\000\000\000\000\000\000\000\000"}, - {279, "yield_stmt", 0, 2, states_23, - "\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\002"}, - {280, "raise_stmt", 0, 7, states_24, - "\000\000\000\000\000\000\000\000\200\000\000\000\000\000\000\000\000\000\000\000\000\000"}, - {281, "import_stmt", 0, 2, states_25, - "\000\000\000\000\000\000\000\000\000\024\000\000\000\000\000\000\000\000\000\000\000\000"}, - {282, "import_name", 0, 3, states_26, - "\000\000\000\000\000\000\000\000\000\004\000\000\000\000\000\000\000\000\000\000\000\000"}, - {283, "import_from", 0, 8, states_27, - "\000\000\000\000\000\000\000\000\000\020\000\000\000\000\000\000\000\000\000\000\000\000"}, - {284, "import_as_name", 0, 4, states_28, - "\000\000\040\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000"}, - {285, "dotted_as_name", 0, 4, states_29, - "\000\000\040\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000"}, - {286, "import_as_names", 0, 3, states_30, - "\000\000\040\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000"}, - {287, "dotted_as_names", 0, 2, states_31, - "\000\000\040\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000"}, - {288, "dotted_name", 0, 2, states_32, - "\000\000\040\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000"}, - {289, "global_stmt", 0, 3, states_33, - "\000\000\000\000\000\000\000\000\000\000\004\000\000\000\000\000\000\000\000\000\000\000"}, - {290, "exec_stmt", 0, 7, states_34, - "\000\000\000\000\000\000\000\000\000\000\010\000\000\000\000\000\000\000\000\000\000\000"}, - {291, "assert_stmt", 0, 5, states_35, - "\000\000\000\000\000\000\000\000\000\000\100\000\000\000\000\000\000\000\000\000\000\000"}, - {292, "compound_stmt", 0, 2, states_36, - "\000\010\020\000\000\000\000\000\000\000\000\220\023\000\000\000\000\000\000\000\004\000"}, - {293, "if_stmt", 0, 8, states_37, - "\000\000\000\000\000\000\000\000\000\000\000\020\000\000\000\000\000\000\000\000\000\000"}, - {294, "while_stmt", 0, 8, states_38, - "\000\000\000\000\000\000\000\000\000\000\000\200\000\000\000\000\000\000\000\000\000\000"}, - {295, "for_stmt", 0, 10, states_39, - "\000\000\000\000\000\000\000\000\000\000\000\000\001\000\000\000\000\000\000\000\000\000"}, - {296, "try_stmt", 0, 13, states_40, - "\000\000\000\000\000\000\000\000\000\000\000\000\002\000\000\000\000\000\000\000\000\000"}, - {297, "with_stmt", 0, 5, states_41, - "\000\000\000\000\000\000\000\000\000\000\000\000\020\000\000\000\000\000\000\000\000\000"}, - {298, "with_item", 0, 4, states_42, - "\000\040\040\000\000\000\000\000\000\000\000\000\000\040\010\000\200\041\044\015\000\000"}, - {299, "except_clause", 0, 5, states_43, - "\000\000\000\000\000\000\000\000\000\000\000\000\100\000\000\000\000\000\000\000\000\000"}, - {300, "suite", 0, 5, states_44, - "\004\040\040\000\000\000\000\124\360\024\114\000\000\040\010\000\200\041\044\015\000\002"}, - {301, "testlist_safe", 0, 5, states_45, - "\000\040\040\000\000\000\000\000\000\000\000\000\000\040\010\000\200\041\044\015\000\000"}, - {302, "old_test", 0, 2, states_46, - "\000\040\040\000\000\000\000\000\000\000\000\000\000\040\010\000\200\041\044\015\000\000"}, - {303, "old_lambdef", 0, 5, states_47, - "\000\000\000\000\000\000\000\000\000\000\000\000\000\040\000\000\000\000\000\000\000\000"}, - {304, "test", 0, 6, states_48, - "\000\040\040\000\000\000\000\000\000\000\000\000\000\040\010\000\200\041\044\015\000\000"}, - {305, "or_test", 0, 2, states_49, - "\000\040\040\000\000\000\000\000\000\000\000\000\000\000\010\000\200\041\044\015\000\000"}, - {306, "and_test", 0, 2, states_50, - "\000\040\040\000\000\000\000\000\000\000\000\000\000\000\010\000\200\041\044\015\000\000"}, - {307, "not_test", 0, 3, states_51, - "\000\040\040\000\000\000\000\000\000\000\000\000\000\000\010\000\200\041\044\015\000\000"}, - {308, "comparison", 0, 2, states_52, - "\000\040\040\000\000\000\000\000\000\000\000\000\000\000\000\000\200\041\044\015\000\000"}, - {309, "comp_op", 0, 4, states_53, - "\000\000\000\000\000\000\000\000\000\000\040\000\000\000\310\077\000\000\000\000\000\000"}, - {310, "expr", 0, 2, states_54, - "\000\040\040\000\000\000\000\000\000\000\000\000\000\000\000\000\200\041\044\015\000\000"}, - {311, "xor_expr", 0, 2, states_55, - "\000\040\040\000\000\000\000\000\000\000\000\000\000\000\000\000\200\041\044\015\000\000"}, - {312, "and_expr", 0, 2, states_56, - "\000\040\040\000\000\000\000\000\000\000\000\000\000\000\000\000\200\041\044\015\000\000"}, - {313, "shift_expr", 0, 2, states_57, - "\000\040\040\000\000\000\000\000\000\000\000\000\000\000\000\000\200\041\044\015\000\000"}, - {314, "arith_expr", 0, 2, states_58, - "\000\040\040\000\000\000\000\000\000\000\000\000\000\000\000\000\200\041\044\015\000\000"}, - {315, "term", 0, 2, states_59, - "\000\040\040\000\000\000\000\000\000\000\000\000\000\000\000\000\200\041\044\015\000\000"}, - {316, "factor", 0, 3, states_60, - "\000\040\040\000\000\000\000\000\000\000\000\000\000\000\000\000\200\041\044\015\000\000"}, - {317, "power", 0, 4, states_61, - "\000\040\040\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\044\015\000\000"}, - {318, "atom", 0, 11, states_62, - "\000\040\040\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\044\015\000\000"}, - {319, "listmaker", 0, 5, states_63, - "\000\040\040\000\000\000\000\000\000\000\000\000\000\040\010\000\200\041\044\015\000\000"}, - {320, "testlist_comp", 0, 5, states_64, - "\000\040\040\000\000\000\000\000\000\000\000\000\000\040\010\000\200\041\044\015\000\000"}, - {321, "lambdef", 0, 5, states_65, - "\000\000\000\000\000\000\000\000\000\000\000\000\000\040\000\000\000\000\000\000\000\000"}, - {322, "trailer", 0, 7, states_66, - "\000\040\000\000\000\000\000\000\000\040\000\000\000\000\000\000\000\000\004\000\000\000"}, - {323, "subscriptlist", 0, 3, states_67, - "\000\040\240\000\000\000\000\000\000\040\000\000\000\040\010\000\200\041\044\015\000\000"}, - {324, "subscript", 0, 7, states_68, - "\000\040\240\000\000\000\000\000\000\040\000\000\000\040\010\000\200\041\044\015\000\000"}, - {325, "sliceop", 0, 3, states_69, - "\000\000\200\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000"}, - {326, "exprlist", 0, 3, states_70, - "\000\040\040\000\000\000\000\000\000\000\000\000\000\000\000\000\200\041\044\015\000\000"}, - {327, "testlist", 0, 3, states_71, - "\000\040\040\000\000\000\000\000\000\000\000\000\000\040\010\000\200\041\044\015\000\000"}, - {328, "dictmaker", 0, 5, states_72, - "\000\040\040\000\000\000\000\000\000\000\000\000\000\040\010\000\200\041\044\015\000\000"}, - {329, "dictorsetmaker", 0, 11, states_73, - "\000\040\040\000\000\000\000\000\000\000\000\000\000\040\010\000\200\041\044\015\000\000"}, - {330, "classdef", 0, 8, states_74, - "\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\004\000"}, - {331, "arglist", 0, 8, states_75, - "\000\040\040\300\000\000\000\000\000\000\000\000\000\040\010\000\200\041\044\015\000\000"}, - {332, "argument", 0, 4, states_76, - "\000\040\040\000\000\000\000\000\000\000\000\000\000\040\010\000\200\041\044\015\000\000"}, - {333, "list_iter", 0, 2, states_77, - "\000\000\000\000\000\000\000\000\000\000\000\020\001\000\000\000\000\000\000\000\000\000"}, - {334, "list_for", 0, 6, states_78, - "\000\000\000\000\000\000\000\000\000\000\000\000\001\000\000\000\000\000\000\000\000\000"}, - {335, "list_if", 0, 4, states_79, - "\000\000\000\000\000\000\000\000\000\000\000\020\000\000\000\000\000\000\000\000\000\000"}, - {336, "comp_iter", 0, 2, states_80, - "\000\000\000\000\000\000\000\000\000\000\000\020\001\000\000\000\000\000\000\000\000\000"}, - {337, "comp_for", 0, 6, states_81, - "\000\000\000\000\000\000\000\000\000\000\000\000\001\000\000\000\000\000\000\000\000\000"}, - {338, "comp_if", 0, 4, states_82, - "\000\000\000\000\000\000\000\000\000\000\000\020\000\000\000\000\000\000\000\000\000\000"}, - {339, "testlist1", 0, 2, states_83, - "\000\040\040\000\000\000\000\000\000\000\000\000\000\040\010\000\200\041\044\015\000\000"}, - {340, "encoding_decl", 0, 2, states_84, - "\000\000\040\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000"}, - {341, "yield_expr", 0, 3, states_85, - "\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\002"}, + {256, "single_input", 0, 3, states_0, + "\004\050\060\000\000\000\000\124\360\024\114\220\023\040\010\000\200\041\044\015\004\002"}, + {257, "file_input", 0, 2, states_1, + "\204\050\060\000\000\000\000\124\360\024\114\220\023\040\010\000\200\041\044\015\004\002"}, + {258, "eval_input", 0, 3, states_2, + "\000\040\040\000\000\000\000\000\000\000\000\000\000\040\010\000\200\041\044\015\000\000"}, + {259, "decorator", 0, 7, states_3, + "\000\010\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000"}, + {260, "decorators", 0, 2, states_4, + "\000\010\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000"}, + {261, "decorated", 0, 3, states_5, + "\000\010\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000"}, + {262, "funcdef", 0, 6, states_6, + "\000\000\020\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000"}, + {263, "parameters", 0, 4, states_7, + "\000\040\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000"}, + {264, "varargslist", 0, 10, states_8, + "\000\040\040\300\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000"}, + {265, "fpdef", 0, 4, states_9, + "\000\040\040\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000"}, + {266, "fplist", 0, 3, states_10, + "\000\040\040\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000"}, + {267, "stmt", 0, 2, states_11, + "\000\050\060\000\000\000\000\124\360\024\114\220\023\040\010\000\200\041\044\015\004\002"}, + {268, "simple_stmt", 0, 4, states_12, + "\000\040\040\000\000\000\000\124\360\024\114\000\000\040\010\000\200\041\044\015\000\002"}, + {269, "small_stmt", 0, 2, states_13, + "\000\040\040\000\000\000\000\124\360\024\114\000\000\040\010\000\200\041\044\015\000\002"}, + {270, "expr_stmt", 0, 6, states_14, + "\000\040\040\000\000\000\000\000\000\000\000\000\000\040\010\000\200\041\044\015\000\000"}, + {271, "augassign", 0, 2, states_15, + "\000\000\000\000\000\300\377\003\000\000\000\000\000\000\000\000\000\000\000\000\000\000"}, + {272, "print_stmt", 0, 9, states_16, + "\000\000\000\000\000\000\000\004\000\000\000\000\000\000\000\000\000\000\000\000\000\000"}, + {273, "del_stmt", 0, 3, states_17, + "\000\000\000\000\000\000\000\020\000\000\000\000\000\000\000\000\000\000\000\000\000\000"}, + {274, "pass_stmt", 0, 2, states_18, + "\000\000\000\000\000\000\000\100\000\000\000\000\000\000\000\000\000\000\000\000\000\000"}, + {275, "flow_stmt", 0, 2, states_19, + "\000\000\000\000\000\000\000\000\360\000\000\000\000\000\000\000\000\000\000\000\000\002"}, + {276, "break_stmt", 0, 2, states_20, + "\000\000\000\000\000\000\000\000\020\000\000\000\000\000\000\000\000\000\000\000\000\000"}, + {277, "continue_stmt", 0, 2, states_21, + "\000\000\000\000\000\000\000\000\040\000\000\000\000\000\000\000\000\000\000\000\000\000"}, + {278, "return_stmt", 0, 3, states_22, + "\000\000\000\000\000\000\000\000\100\000\000\000\000\000\000\000\000\000\000\000\000\000"}, + {279, "yield_stmt", 0, 2, states_23, + "\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\002"}, + {280, "raise_stmt", 0, 7, states_24, + "\000\000\000\000\000\000\000\000\200\000\000\000\000\000\000\000\000\000\000\000\000\000"}, + {281, "import_stmt", 0, 2, states_25, + "\000\000\000\000\000\000\000\000\000\024\000\000\000\000\000\000\000\000\000\000\000\000"}, + {282, "import_name", 0, 3, states_26, + "\000\000\000\000\000\000\000\000\000\004\000\000\000\000\000\000\000\000\000\000\000\000"}, + {283, "import_from", 0, 8, states_27, + "\000\000\000\000\000\000\000\000\000\020\000\000\000\000\000\000\000\000\000\000\000\000"}, + {284, "import_as_name", 0, 4, states_28, + "\000\000\040\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000"}, + {285, "dotted_as_name", 0, 4, states_29, + "\000\000\040\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000"}, + {286, "import_as_names", 0, 3, states_30, + "\000\000\040\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000"}, + {287, "dotted_as_names", 0, 2, states_31, + "\000\000\040\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000"}, + {288, "dotted_name", 0, 2, states_32, + "\000\000\040\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000"}, + {289, "global_stmt", 0, 3, states_33, + "\000\000\000\000\000\000\000\000\000\000\004\000\000\000\000\000\000\000\000\000\000\000"}, + {290, "exec_stmt", 0, 7, states_34, + "\000\000\000\000\000\000\000\000\000\000\010\000\000\000\000\000\000\000\000\000\000\000"}, + {291, "assert_stmt", 0, 5, states_35, + "\000\000\000\000\000\000\000\000\000\000\100\000\000\000\000\000\000\000\000\000\000\000"}, + {292, "compound_stmt", 0, 2, states_36, + "\000\010\020\000\000\000\000\000\000\000\000\220\023\000\000\000\000\000\000\000\004\000"}, + {293, "if_stmt", 0, 8, states_37, + "\000\000\000\000\000\000\000\000\000\000\000\020\000\000\000\000\000\000\000\000\000\000"}, + {294, "while_stmt", 0, 8, states_38, + "\000\000\000\000\000\000\000\000\000\000\000\200\000\000\000\000\000\000\000\000\000\000"}, + {295, "for_stmt", 0, 10, states_39, + "\000\000\000\000\000\000\000\000\000\000\000\000\001\000\000\000\000\000\000\000\000\000"}, + {296, "try_stmt", 0, 13, states_40, + "\000\000\000\000\000\000\000\000\000\000\000\000\002\000\000\000\000\000\000\000\000\000"}, + {297, "with_stmt", 0, 5, states_41, + "\000\000\000\000\000\000\000\000\000\000\000\000\020\000\000\000\000\000\000\000\000\000"}, + {298, "with_item", 0, 4, states_42, + "\000\040\040\000\000\000\000\000\000\000\000\000\000\040\010\000\200\041\044\015\000\000"}, + {299, "except_clause", 0, 5, states_43, + "\000\000\000\000\000\000\000\000\000\000\000\000\100\000\000\000\000\000\000\000\000\000"}, + {300, "suite", 0, 5, states_44, + "\004\040\040\000\000\000\000\124\360\024\114\000\000\040\010\000\200\041\044\015\000\002"}, + {301, "testlist_safe", 0, 5, states_45, + "\000\040\040\000\000\000\000\000\000\000\000\000\000\040\010\000\200\041\044\015\000\000"}, + {302, "old_test", 0, 2, states_46, + "\000\040\040\000\000\000\000\000\000\000\000\000\000\040\010\000\200\041\044\015\000\000"}, + {303, "old_lambdef", 0, 5, states_47, + "\000\000\000\000\000\000\000\000\000\000\000\000\000\040\000\000\000\000\000\000\000\000"}, + {304, "test", 0, 6, states_48, + "\000\040\040\000\000\000\000\000\000\000\000\000\000\040\010\000\200\041\044\015\000\000"}, + {305, "or_test", 0, 2, states_49, + "\000\040\040\000\000\000\000\000\000\000\000\000\000\000\010\000\200\041\044\015\000\000"}, + {306, "and_test", 0, 2, states_50, + "\000\040\040\000\000\000\000\000\000\000\000\000\000\000\010\000\200\041\044\015\000\000"}, + {307, "not_test", 0, 3, states_51, + "\000\040\040\000\000\000\000\000\000\000\000\000\000\000\010\000\200\041\044\015\000\000"}, + {308, "comparison", 0, 2, states_52, + "\000\040\040\000\000\000\000\000\000\000\000\000\000\000\000\000\200\041\044\015\000\000"}, + {309, "comp_op", 0, 4, states_53, + "\000\000\000\000\000\000\000\000\000\000\040\000\000\000\310\077\000\000\000\000\000\000"}, + {310, "expr", 0, 2, states_54, + "\000\040\040\000\000\000\000\000\000\000\000\000\000\000\000\000\200\041\044\015\000\000"}, + {311, "xor_expr", 0, 2, states_55, + "\000\040\040\000\000\000\000\000\000\000\000\000\000\000\000\000\200\041\044\015\000\000"}, + {312, "and_expr", 0, 2, states_56, + "\000\040\040\000\000\000\000\000\000\000\000\000\000\000\000\000\200\041\044\015\000\000"}, + {313, "shift_expr", 0, 2, states_57, + "\000\040\040\000\000\000\000\000\000\000\000\000\000\000\000\000\200\041\044\015\000\000"}, + {314, "arith_expr", 0, 2, states_58, + "\000\040\040\000\000\000\000\000\000\000\000\000\000\000\000\000\200\041\044\015\000\000"}, + {315, "term", 0, 2, states_59, + "\000\040\040\000\000\000\000\000\000\000\000\000\000\000\000\000\200\041\044\015\000\000"}, + {316, "factor", 0, 3, states_60, + "\000\040\040\000\000\000\000\000\000\000\000\000\000\000\000\000\200\041\044\015\000\000"}, + {317, "power", 0, 4, states_61, + "\000\040\040\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\044\015\000\000"}, + {318, "atom", 0, 11, states_62, + "\000\040\040\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\044\015\000\000"}, + {319, "listmaker", 0, 5, states_63, + "\000\040\040\000\000\000\000\000\000\000\000\000\000\040\010\000\200\041\044\015\000\000"}, + {320, "testlist_comp", 0, 5, states_64, + "\000\040\040\000\000\000\000\000\000\000\000\000\000\040\010\000\200\041\044\015\000\000"}, + {321, "lambdef", 0, 5, states_65, + "\000\000\000\000\000\000\000\000\000\000\000\000\000\040\000\000\000\000\000\000\000\000"}, + {322, "trailer", 0, 7, states_66, + "\000\040\000\000\000\000\000\000\000\040\000\000\000\000\000\000\000\000\004\000\000\000"}, + {323, "subscriptlist", 0, 3, states_67, + "\000\040\240\000\000\000\000\000\000\040\000\000\000\040\010\000\200\041\044\015\000\000"}, + {324, "subscript", 0, 7, states_68, + "\000\040\240\000\000\000\000\000\000\040\000\000\000\040\010\000\200\041\044\015\000\000"}, + {325, "sliceop", 0, 3, states_69, + "\000\000\200\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000"}, + {326, "exprlist", 0, 3, states_70, + "\000\040\040\000\000\000\000\000\000\000\000\000\000\000\000\000\200\041\044\015\000\000"}, + {327, "testlist", 0, 3, states_71, + "\000\040\040\000\000\000\000\000\000\000\000\000\000\040\010\000\200\041\044\015\000\000"}, + {328, "dictmaker", 0, 5, states_72, + "\000\040\040\000\000\000\000\000\000\000\000\000\000\040\010\000\200\041\044\015\000\000"}, + {329, "dictorsetmaker", 0, 11, states_73, + "\000\040\040\000\000\000\000\000\000\000\000\000\000\040\010\000\200\041\044\015\000\000"}, + {330, "classdef", 0, 8, states_74, + "\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\004\000"}, + {331, "arglist", 0, 8, states_75, + "\000\040\040\300\000\000\000\000\000\000\000\000\000\040\010\000\200\041\044\015\000\000"}, + {332, "argument", 0, 4, states_76, + "\000\040\040\000\000\000\000\000\000\000\000\000\000\040\010\000\200\041\044\015\000\000"}, + {333, "list_iter", 0, 2, states_77, + "\000\000\000\000\000\000\000\000\000\000\000\020\001\000\000\000\000\000\000\000\000\000"}, + {334, "list_for", 0, 6, states_78, + "\000\000\000\000\000\000\000\000\000\000\000\000\001\000\000\000\000\000\000\000\000\000"}, + {335, "list_if", 0, 4, states_79, + "\000\000\000\000\000\000\000\000\000\000\000\020\000\000\000\000\000\000\000\000\000\000"}, + {336, "comp_iter", 0, 2, states_80, + "\000\000\000\000\000\000\000\000\000\000\000\020\001\000\000\000\000\000\000\000\000\000"}, + {337, "comp_for", 0, 6, states_81, + "\000\000\000\000\000\000\000\000\000\000\000\000\001\000\000\000\000\000\000\000\000\000"}, + {338, "comp_if", 0, 4, states_82, + "\000\000\000\000\000\000\000\000\000\000\000\020\000\000\000\000\000\000\000\000\000\000"}, + {339, "testlist1", 0, 2, states_83, + "\000\040\040\000\000\000\000\000\000\000\000\000\000\040\010\000\200\041\044\015\000\000"}, + {340, "encoding_decl", 0, 2, states_84, + "\000\000\040\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000"}, + {341, "yield_expr", 0, 3, states_85, + "\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\002"}, }; static label labels[170] = { - {0, "EMPTY"}, - {256, 0}, - {4, 0}, - {268, 0}, - {292, 0}, - {257, 0}, - {267, 0}, - {0, 0}, - {258, 0}, - {327, 0}, - {259, 0}, - {50, 0}, - {288, 0}, - {7, 0}, - {331, 0}, - {8, 0}, - {260, 0}, - {261, 0}, - {330, 0}, - {262, 0}, - {1, "def"}, - {1, 0}, - {263, 0}, - {11, 0}, - {300, 0}, - {264, 0}, - {265, 0}, - {22, 0}, - {304, 0}, - {12, 0}, - {16, 0}, - {36, 0}, - {266, 0}, - {269, 0}, - {13, 0}, - {270, 0}, - {272, 0}, - {273, 0}, - {274, 0}, - {275, 0}, - {281, 0}, - {289, 0}, - {290, 0}, - {291, 0}, - {271, 0}, - {341, 0}, - {37, 0}, - {38, 0}, - {39, 0}, - {40, 0}, - {41, 0}, - {42, 0}, - {43, 0}, - {44, 0}, - {45, 0}, - {46, 0}, - {47, 0}, - {49, 0}, - {1, "print"}, - {35, 0}, - {1, "del"}, - {326, 0}, - {1, "pass"}, - {276, 0}, - {277, 0}, - {278, 0}, - {280, 0}, - {279, 0}, - {1, "break"}, - {1, "continue"}, - {1, "return"}, - {1, "raise"}, - {282, 0}, - {283, 0}, - {1, "import"}, - {287, 0}, - {1, "from"}, - {23, 0}, - {286, 0}, - {284, 0}, - {1, "as"}, - {285, 0}, - {1, "global"}, - {1, "exec"}, - {310, 0}, - {1, "in"}, - {1, "assert"}, - {293, 0}, - {294, 0}, - {295, 0}, - {296, 0}, - {297, 0}, - {1, "if"}, - {1, "elif"}, - {1, "else"}, - {1, "while"}, - {1, "for"}, - {1, "try"}, - {299, 0}, - {1, "finally"}, - {1, "with"}, - {298, 0}, - {1, "except"}, - {5, 0}, - {6, 0}, - {301, 0}, - {302, 0}, - {305, 0}, - {303, 0}, - {1, "lambda"}, - {321, 0}, - {306, 0}, - {1, "or"}, - {307, 0}, - {1, "and"}, - {1, "not"}, - {308, 0}, - {309, 0}, - {20, 0}, - {21, 0}, - {28, 0}, - {31, 0}, - {30, 0}, - {29, 0}, - {29, 0}, - {1, "is"}, - {311, 0}, - {18, 0}, - {312, 0}, - {33, 0}, - {313, 0}, - {19, 0}, - {314, 0}, - {34, 0}, - {315, 0}, - {14, 0}, - {15, 0}, - {316, 0}, - {17, 0}, - {24, 0}, - {48, 0}, - {32, 0}, - {317, 0}, - {318, 0}, - {322, 0}, - {320, 0}, - {9, 0}, - {319, 0}, - {10, 0}, - {26, 0}, - {329, 0}, - {27, 0}, - {25, 0}, - {339, 0}, - {2, 0}, - {3, 0}, - {334, 0}, - {337, 0}, - {323, 0}, - {324, 0}, - {325, 0}, - {328, 0}, - {1, "class"}, - {332, 0}, - {333, 0}, - {335, 0}, - {336, 0}, - {338, 0}, - {340, 0}, - {1, "yield"}, + {0, "EMPTY"}, + {256, 0}, + {4, 0}, + {268, 0}, + {292, 0}, + {257, 0}, + {267, 0}, + {0, 0}, + {258, 0}, + {327, 0}, + {259, 0}, + {50, 0}, + {288, 0}, + {7, 0}, + {331, 0}, + {8, 0}, + {260, 0}, + {261, 0}, + {330, 0}, + {262, 0}, + {1, "def"}, + {1, 0}, + {263, 0}, + {11, 0}, + {300, 0}, + {264, 0}, + {265, 0}, + {22, 0}, + {304, 0}, + {12, 0}, + {16, 0}, + {36, 0}, + {266, 0}, + {269, 0}, + {13, 0}, + {270, 0}, + {272, 0}, + {273, 0}, + {274, 0}, + {275, 0}, + {281, 0}, + {289, 0}, + {290, 0}, + {291, 0}, + {271, 0}, + {341, 0}, + {37, 0}, + {38, 0}, + {39, 0}, + {40, 0}, + {41, 0}, + {42, 0}, + {43, 0}, + {44, 0}, + {45, 0}, + {46, 0}, + {47, 0}, + {49, 0}, + {1, "print"}, + {35, 0}, + {1, "del"}, + {326, 0}, + {1, "pass"}, + {276, 0}, + {277, 0}, + {278, 0}, + {280, 0}, + {279, 0}, + {1, "break"}, + {1, "continue"}, + {1, "return"}, + {1, "raise"}, + {282, 0}, + {283, 0}, + {1, "import"}, + {287, 0}, + {1, "from"}, + {23, 0}, + {286, 0}, + {284, 0}, + {1, "as"}, + {285, 0}, + {1, "global"}, + {1, "exec"}, + {310, 0}, + {1, "in"}, + {1, "assert"}, + {293, 0}, + {294, 0}, + {295, 0}, + {296, 0}, + {297, 0}, + {1, "if"}, + {1, "elif"}, + {1, "else"}, + {1, "while"}, + {1, "for"}, + {1, "try"}, + {299, 0}, + {1, "finally"}, + {1, "with"}, + {298, 0}, + {1, "except"}, + {5, 0}, + {6, 0}, + {301, 0}, + {302, 0}, + {305, 0}, + {303, 0}, + {1, "lambda"}, + {321, 0}, + {306, 0}, + {1, "or"}, + {307, 0}, + {1, "and"}, + {1, "not"}, + {308, 0}, + {309, 0}, + {20, 0}, + {21, 0}, + {28, 0}, + {31, 0}, + {30, 0}, + {29, 0}, + {29, 0}, + {1, "is"}, + {311, 0}, + {18, 0}, + {312, 0}, + {33, 0}, + {313, 0}, + {19, 0}, + {314, 0}, + {34, 0}, + {315, 0}, + {14, 0}, + {15, 0}, + {316, 0}, + {17, 0}, + {24, 0}, + {48, 0}, + {32, 0}, + {317, 0}, + {318, 0}, + {322, 0}, + {320, 0}, + {9, 0}, + {319, 0}, + {10, 0}, + {26, 0}, + {329, 0}, + {27, 0}, + {25, 0}, + {339, 0}, + {2, 0}, + {3, 0}, + {334, 0}, + {337, 0}, + {323, 0}, + {324, 0}, + {325, 0}, + {328, 0}, + {1, "class"}, + {332, 0}, + {333, 0}, + {335, 0}, + {336, 0}, + {338, 0}, + {340, 0}, + {1, "yield"}, }; grammar _PyParser_Grammar = { - 86, - dfas, - {170, labels}, - 256 + 86, + dfas, + {170, labels}, + 256 }; From python-checkins at python.org Sun May 16 00:58:41 2010 From: python-checkins at python.org (victor.stinner) Date: Sun, 16 May 2010 00:58:41 +0200 (CEST) Subject: [Python-checkins] r81221 - in python/branches/release26-maint: Parser/printgrammar.c Python/graminit.c Message-ID: <20100515225841.A0628EE990@mail.python.org> Author: victor.stinner Date: Sun May 16 00:58:41 2010 New Revision: 81221 Log: Merged revisions 81220 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r81220 | victor.stinner | 2010-05-16 00:55:28 +0200 (dim., 16 mai 2010) | 4 lines Use 4-spaces for indentation (instead of tabs) in pgen outputs Regenerate (reindent) Python/graminit.c ........ Modified: python/branches/release26-maint/ (props changed) python/branches/release26-maint/Parser/printgrammar.c python/branches/release26-maint/Python/graminit.c Modified: python/branches/release26-maint/Parser/printgrammar.c ============================================================================== --- python/branches/release26-maint/Parser/printgrammar.c (original) +++ python/branches/release26-maint/Parser/printgrammar.c Sun May 16 00:58:41 2010 @@ -20,10 +20,10 @@ printdfas(g, fp); printlabels(g, fp); fprintf(fp, "grammar _PyParser_Grammar = {\n"); - fprintf(fp, "\t%d,\n", g->g_ndfas); - fprintf(fp, "\tdfas,\n"); - fprintf(fp, "\t{%d, labels},\n", g->g_ll.ll_nlabels); - fprintf(fp, "\t%d\n", g->g_start); + fprintf(fp, " %d,\n", g->g_ndfas); + fprintf(fp, " dfas,\n"); + fprintf(fp, " {%d, labels},\n", g->g_ll.ll_nlabels); + fprintf(fp, " %d\n", g->g_start); fprintf(fp, "};\n"); } @@ -53,7 +53,7 @@ i, j, s->s_narcs); a = s->s_arc; for (k = 0; k < s->s_narcs; k++, a++) - fprintf(fp, "\t{%d, %d},\n", a->a_lbl, a->a_arrow); + fprintf(fp, " {%d, %d},\n", a->a_lbl, a->a_arrow); fprintf(fp, "};\n"); } } @@ -72,7 +72,7 @@ i, d->d_nstates); s = d->d_state; for (j = 0; j < d->d_nstates; j++, s++) - fprintf(fp, "\t{%d, arcs_%d_%d},\n", + fprintf(fp, " {%d, arcs_%d_%d},\n", s->s_narcs, i, j); fprintf(fp, "};\n"); } @@ -88,9 +88,9 @@ fprintf(fp, "static dfa dfas[%d] = {\n", g->g_ndfas); d = g->g_dfa; for (i = 0; i < g->g_ndfas; i++, d++) { - fprintf(fp, "\t{%d, \"%s\", %d, %d, states_%d,\n", + fprintf(fp, " {%d, \"%s\", %d, %d, states_%d,\n", d->d_type, d->d_name, d->d_initial, d->d_nstates, i); - fprintf(fp, "\t \""); + fprintf(fp, " \""); for (j = 0; j < NBYTES(g->g_ll.ll_nlabels); j++) fprintf(fp, "\\%03o", d->d_first[j] & 0xff); fprintf(fp, "\"},\n"); @@ -108,9 +108,9 @@ l = g->g_ll.ll_label; for (i = g->g_ll.ll_nlabels; --i >= 0; l++) { if (l->lb_str == NULL) - fprintf(fp, "\t{%d, 0},\n", l->lb_type); + fprintf(fp, " {%d, 0},\n", l->lb_type); else - fprintf(fp, "\t{%d, \"%s\"},\n", + fprintf(fp, " {%d, \"%s\"},\n", l->lb_type, l->lb_str); } fprintf(fp, "};\n"); Modified: python/branches/release26-maint/Python/graminit.c ============================================================================== --- python/branches/release26-maint/Python/graminit.c (original) +++ python/branches/release26-maint/Python/graminit.c Sun May 16 00:58:41 2010 @@ -4,2142 +4,2142 @@ #include "grammar.h" PyAPI_DATA(grammar) _PyParser_Grammar; static arc arcs_0_0[3] = { - {2, 1}, - {3, 1}, - {4, 2}, + {2, 1}, + {3, 1}, + {4, 2}, }; static arc arcs_0_1[1] = { - {0, 1}, + {0, 1}, }; static arc arcs_0_2[1] = { - {2, 1}, + {2, 1}, }; static state states_0[3] = { - {3, arcs_0_0}, - {1, arcs_0_1}, - {1, arcs_0_2}, + {3, arcs_0_0}, + {1, arcs_0_1}, + {1, arcs_0_2}, }; static arc arcs_1_0[3] = { - {2, 0}, - {6, 0}, - {7, 1}, + {2, 0}, + {6, 0}, + {7, 1}, }; static arc arcs_1_1[1] = { - {0, 1}, + {0, 1}, }; static state states_1[2] = { - {3, arcs_1_0}, - {1, arcs_1_1}, + {3, arcs_1_0}, + {1, arcs_1_1}, }; static arc arcs_2_0[1] = { - {9, 1}, + {9, 1}, }; static arc arcs_2_1[2] = { - {2, 1}, - {7, 2}, + {2, 1}, + {7, 2}, }; static arc arcs_2_2[1] = { - {0, 2}, + {0, 2}, }; static state states_2[3] = { - {1, arcs_2_0}, - {2, arcs_2_1}, - {1, arcs_2_2}, + {1, arcs_2_0}, + {2, arcs_2_1}, + {1, arcs_2_2}, }; static arc arcs_3_0[1] = { - {11, 1}, + {11, 1}, }; static arc arcs_3_1[1] = { - {12, 2}, + {12, 2}, }; static arc arcs_3_2[2] = { - {13, 3}, - {2, 4}, + {13, 3}, + {2, 4}, }; static arc arcs_3_3[2] = { - {14, 5}, - {15, 6}, + {14, 5}, + {15, 6}, }; static arc arcs_3_4[1] = { - {0, 4}, + {0, 4}, }; static arc arcs_3_5[1] = { - {15, 6}, + {15, 6}, }; static arc arcs_3_6[1] = { - {2, 4}, + {2, 4}, }; static state states_3[7] = { - {1, arcs_3_0}, - {1, arcs_3_1}, - {2, arcs_3_2}, - {2, arcs_3_3}, - {1, arcs_3_4}, - {1, arcs_3_5}, - {1, arcs_3_6}, + {1, arcs_3_0}, + {1, arcs_3_1}, + {2, arcs_3_2}, + {2, arcs_3_3}, + {1, arcs_3_4}, + {1, arcs_3_5}, + {1, arcs_3_6}, }; static arc arcs_4_0[1] = { - {10, 1}, + {10, 1}, }; static arc arcs_4_1[2] = { - {10, 1}, - {0, 1}, + {10, 1}, + {0, 1}, }; static state states_4[2] = { - {1, arcs_4_0}, - {2, arcs_4_1}, + {1, arcs_4_0}, + {2, arcs_4_1}, }; static arc arcs_5_0[1] = { - {16, 1}, + {16, 1}, }; static arc arcs_5_1[2] = { - {18, 2}, - {19, 2}, + {18, 2}, + {19, 2}, }; static arc arcs_5_2[1] = { - {0, 2}, + {0, 2}, }; static state states_5[3] = { - {1, arcs_5_0}, - {2, arcs_5_1}, - {1, arcs_5_2}, + {1, arcs_5_0}, + {2, arcs_5_1}, + {1, arcs_5_2}, }; static arc arcs_6_0[1] = { - {20, 1}, + {20, 1}, }; static arc arcs_6_1[1] = { - {21, 2}, + {21, 2}, }; static arc arcs_6_2[1] = { - {22, 3}, + {22, 3}, }; static arc arcs_6_3[1] = { - {23, 4}, + {23, 4}, }; static arc arcs_6_4[1] = { - {24, 5}, + {24, 5}, }; static arc arcs_6_5[1] = { - {0, 5}, + {0, 5}, }; static state states_6[6] = { - {1, arcs_6_0}, - {1, arcs_6_1}, - {1, arcs_6_2}, - {1, arcs_6_3}, - {1, arcs_6_4}, - {1, arcs_6_5}, + {1, arcs_6_0}, + {1, arcs_6_1}, + {1, arcs_6_2}, + {1, arcs_6_3}, + {1, arcs_6_4}, + {1, arcs_6_5}, }; static arc arcs_7_0[1] = { - {13, 1}, + {13, 1}, }; static arc arcs_7_1[2] = { - {25, 2}, - {15, 3}, + {25, 2}, + {15, 3}, }; static arc arcs_7_2[1] = { - {15, 3}, + {15, 3}, }; static arc arcs_7_3[1] = { - {0, 3}, + {0, 3}, }; static state states_7[4] = { - {1, arcs_7_0}, - {2, arcs_7_1}, - {1, arcs_7_2}, - {1, arcs_7_3}, + {1, arcs_7_0}, + {2, arcs_7_1}, + {1, arcs_7_2}, + {1, arcs_7_3}, }; static arc arcs_8_0[3] = { - {26, 1}, - {30, 2}, - {31, 3}, + {26, 1}, + {30, 2}, + {31, 3}, }; static arc arcs_8_1[3] = { - {27, 4}, - {29, 5}, - {0, 1}, + {27, 4}, + {29, 5}, + {0, 1}, }; static arc arcs_8_2[1] = { - {21, 6}, + {21, 6}, }; static arc arcs_8_3[1] = { - {21, 7}, + {21, 7}, }; static arc arcs_8_4[1] = { - {28, 8}, + {28, 8}, }; static arc arcs_8_5[4] = { - {26, 1}, - {30, 2}, - {31, 3}, - {0, 5}, + {26, 1}, + {30, 2}, + {31, 3}, + {0, 5}, }; static arc arcs_8_6[2] = { - {29, 9}, - {0, 6}, + {29, 9}, + {0, 6}, }; static arc arcs_8_7[1] = { - {0, 7}, + {0, 7}, }; static arc arcs_8_8[2] = { - {29, 5}, - {0, 8}, + {29, 5}, + {0, 8}, }; static arc arcs_8_9[1] = { - {31, 3}, + {31, 3}, }; static state states_8[10] = { - {3, arcs_8_0}, - {3, arcs_8_1}, - {1, arcs_8_2}, - {1, arcs_8_3}, - {1, arcs_8_4}, - {4, arcs_8_5}, - {2, arcs_8_6}, - {1, arcs_8_7}, - {2, arcs_8_8}, - {1, arcs_8_9}, + {3, arcs_8_0}, + {3, arcs_8_1}, + {1, arcs_8_2}, + {1, arcs_8_3}, + {1, arcs_8_4}, + {4, arcs_8_5}, + {2, arcs_8_6}, + {1, arcs_8_7}, + {2, arcs_8_8}, + {1, arcs_8_9}, }; static arc arcs_9_0[2] = { - {21, 1}, - {13, 2}, + {21, 1}, + {13, 2}, }; static arc arcs_9_1[1] = { - {0, 1}, + {0, 1}, }; static arc arcs_9_2[1] = { - {32, 3}, + {32, 3}, }; static arc arcs_9_3[1] = { - {15, 1}, + {15, 1}, }; static state states_9[4] = { - {2, arcs_9_0}, - {1, arcs_9_1}, - {1, arcs_9_2}, - {1, arcs_9_3}, + {2, arcs_9_0}, + {1, arcs_9_1}, + {1, arcs_9_2}, + {1, arcs_9_3}, }; static arc arcs_10_0[1] = { - {26, 1}, + {26, 1}, }; static arc arcs_10_1[2] = { - {29, 2}, - {0, 1}, + {29, 2}, + {0, 1}, }; static arc arcs_10_2[2] = { - {26, 1}, - {0, 2}, + {26, 1}, + {0, 2}, }; static state states_10[3] = { - {1, arcs_10_0}, - {2, arcs_10_1}, - {2, arcs_10_2}, + {1, arcs_10_0}, + {2, arcs_10_1}, + {2, arcs_10_2}, }; static arc arcs_11_0[2] = { - {3, 1}, - {4, 1}, + {3, 1}, + {4, 1}, }; static arc arcs_11_1[1] = { - {0, 1}, + {0, 1}, }; static state states_11[2] = { - {2, arcs_11_0}, - {1, arcs_11_1}, + {2, arcs_11_0}, + {1, arcs_11_1}, }; static arc arcs_12_0[1] = { - {33, 1}, + {33, 1}, }; static arc arcs_12_1[2] = { - {34, 2}, - {2, 3}, + {34, 2}, + {2, 3}, }; static arc arcs_12_2[2] = { - {33, 1}, - {2, 3}, + {33, 1}, + {2, 3}, }; static arc arcs_12_3[1] = { - {0, 3}, + {0, 3}, }; static state states_12[4] = { - {1, arcs_12_0}, - {2, arcs_12_1}, - {2, arcs_12_2}, - {1, arcs_12_3}, + {1, arcs_12_0}, + {2, arcs_12_1}, + {2, arcs_12_2}, + {1, arcs_12_3}, }; static arc arcs_13_0[9] = { - {35, 1}, - {36, 1}, - {37, 1}, - {38, 1}, - {39, 1}, - {40, 1}, - {41, 1}, - {42, 1}, - {43, 1}, + {35, 1}, + {36, 1}, + {37, 1}, + {38, 1}, + {39, 1}, + {40, 1}, + {41, 1}, + {42, 1}, + {43, 1}, }; static arc arcs_13_1[1] = { - {0, 1}, + {0, 1}, }; static state states_13[2] = { - {9, arcs_13_0}, - {1, arcs_13_1}, + {9, arcs_13_0}, + {1, arcs_13_1}, }; static arc arcs_14_0[1] = { - {9, 1}, + {9, 1}, }; static arc arcs_14_1[3] = { - {44, 2}, - {27, 3}, - {0, 1}, + {44, 2}, + {27, 3}, + {0, 1}, }; static arc arcs_14_2[2] = { - {45, 4}, - {9, 4}, + {45, 4}, + {9, 4}, }; static arc arcs_14_3[2] = { - {45, 5}, - {9, 5}, + {45, 5}, + {9, 5}, }; static arc arcs_14_4[1] = { - {0, 4}, + {0, 4}, }; static arc arcs_14_5[2] = { - {27, 3}, - {0, 5}, + {27, 3}, + {0, 5}, }; static state states_14[6] = { - {1, arcs_14_0}, - {3, arcs_14_1}, - {2, arcs_14_2}, - {2, arcs_14_3}, - {1, arcs_14_4}, - {2, arcs_14_5}, + {1, arcs_14_0}, + {3, arcs_14_1}, + {2, arcs_14_2}, + {2, arcs_14_3}, + {1, arcs_14_4}, + {2, arcs_14_5}, }; static arc arcs_15_0[12] = { - {46, 1}, - {47, 1}, - {48, 1}, - {49, 1}, - {50, 1}, - {51, 1}, - {52, 1}, - {53, 1}, - {54, 1}, - {55, 1}, - {56, 1}, - {57, 1}, + {46, 1}, + {47, 1}, + {48, 1}, + {49, 1}, + {50, 1}, + {51, 1}, + {52, 1}, + {53, 1}, + {54, 1}, + {55, 1}, + {56, 1}, + {57, 1}, }; static arc arcs_15_1[1] = { - {0, 1}, + {0, 1}, }; static state states_15[2] = { - {12, arcs_15_0}, - {1, arcs_15_1}, + {12, arcs_15_0}, + {1, arcs_15_1}, }; static arc arcs_16_0[1] = { - {58, 1}, + {58, 1}, }; static arc arcs_16_1[3] = { - {28, 2}, - {59, 3}, - {0, 1}, + {28, 2}, + {59, 3}, + {0, 1}, }; static arc arcs_16_2[2] = { - {29, 4}, - {0, 2}, + {29, 4}, + {0, 2}, }; static arc arcs_16_3[1] = { - {28, 5}, + {28, 5}, }; static arc arcs_16_4[2] = { - {28, 2}, - {0, 4}, + {28, 2}, + {0, 4}, }; static arc arcs_16_5[2] = { - {29, 6}, - {0, 5}, + {29, 6}, + {0, 5}, }; static arc arcs_16_6[1] = { - {28, 7}, + {28, 7}, }; static arc arcs_16_7[2] = { - {29, 8}, - {0, 7}, + {29, 8}, + {0, 7}, }; static arc arcs_16_8[2] = { - {28, 7}, - {0, 8}, + {28, 7}, + {0, 8}, }; static state states_16[9] = { - {1, arcs_16_0}, - {3, arcs_16_1}, - {2, arcs_16_2}, - {1, arcs_16_3}, - {2, arcs_16_4}, - {2, arcs_16_5}, - {1, arcs_16_6}, - {2, arcs_16_7}, - {2, arcs_16_8}, + {1, arcs_16_0}, + {3, arcs_16_1}, + {2, arcs_16_2}, + {1, arcs_16_3}, + {2, arcs_16_4}, + {2, arcs_16_5}, + {1, arcs_16_6}, + {2, arcs_16_7}, + {2, arcs_16_8}, }; static arc arcs_17_0[1] = { - {60, 1}, + {60, 1}, }; static arc arcs_17_1[1] = { - {61, 2}, + {61, 2}, }; static arc arcs_17_2[1] = { - {0, 2}, + {0, 2}, }; static state states_17[3] = { - {1, arcs_17_0}, - {1, arcs_17_1}, - {1, arcs_17_2}, + {1, arcs_17_0}, + {1, arcs_17_1}, + {1, arcs_17_2}, }; static arc arcs_18_0[1] = { - {62, 1}, + {62, 1}, }; static arc arcs_18_1[1] = { - {0, 1}, + {0, 1}, }; static state states_18[2] = { - {1, arcs_18_0}, - {1, arcs_18_1}, + {1, arcs_18_0}, + {1, arcs_18_1}, }; static arc arcs_19_0[5] = { - {63, 1}, - {64, 1}, - {65, 1}, - {66, 1}, - {67, 1}, + {63, 1}, + {64, 1}, + {65, 1}, + {66, 1}, + {67, 1}, }; static arc arcs_19_1[1] = { - {0, 1}, + {0, 1}, }; static state states_19[2] = { - {5, arcs_19_0}, - {1, arcs_19_1}, + {5, arcs_19_0}, + {1, arcs_19_1}, }; static arc arcs_20_0[1] = { - {68, 1}, + {68, 1}, }; static arc arcs_20_1[1] = { - {0, 1}, + {0, 1}, }; static state states_20[2] = { - {1, arcs_20_0}, - {1, arcs_20_1}, + {1, arcs_20_0}, + {1, arcs_20_1}, }; static arc arcs_21_0[1] = { - {69, 1}, + {69, 1}, }; static arc arcs_21_1[1] = { - {0, 1}, + {0, 1}, }; static state states_21[2] = { - {1, arcs_21_0}, - {1, arcs_21_1}, + {1, arcs_21_0}, + {1, arcs_21_1}, }; static arc arcs_22_0[1] = { - {70, 1}, + {70, 1}, }; static arc arcs_22_1[2] = { - {9, 2}, - {0, 1}, + {9, 2}, + {0, 1}, }; static arc arcs_22_2[1] = { - {0, 2}, + {0, 2}, }; static state states_22[3] = { - {1, arcs_22_0}, - {2, arcs_22_1}, - {1, arcs_22_2}, + {1, arcs_22_0}, + {2, arcs_22_1}, + {1, arcs_22_2}, }; static arc arcs_23_0[1] = { - {45, 1}, + {45, 1}, }; static arc arcs_23_1[1] = { - {0, 1}, + {0, 1}, }; static state states_23[2] = { - {1, arcs_23_0}, - {1, arcs_23_1}, + {1, arcs_23_0}, + {1, arcs_23_1}, }; static arc arcs_24_0[1] = { - {71, 1}, + {71, 1}, }; static arc arcs_24_1[2] = { - {28, 2}, - {0, 1}, + {28, 2}, + {0, 1}, }; static arc arcs_24_2[2] = { - {29, 3}, - {0, 2}, + {29, 3}, + {0, 2}, }; static arc arcs_24_3[1] = { - {28, 4}, + {28, 4}, }; static arc arcs_24_4[2] = { - {29, 5}, - {0, 4}, + {29, 5}, + {0, 4}, }; static arc arcs_24_5[1] = { - {28, 6}, + {28, 6}, }; static arc arcs_24_6[1] = { - {0, 6}, + {0, 6}, }; static state states_24[7] = { - {1, arcs_24_0}, - {2, arcs_24_1}, - {2, arcs_24_2}, - {1, arcs_24_3}, - {2, arcs_24_4}, - {1, arcs_24_5}, - {1, arcs_24_6}, + {1, arcs_24_0}, + {2, arcs_24_1}, + {2, arcs_24_2}, + {1, arcs_24_3}, + {2, arcs_24_4}, + {1, arcs_24_5}, + {1, arcs_24_6}, }; static arc arcs_25_0[2] = { - {72, 1}, - {73, 1}, + {72, 1}, + {73, 1}, }; static arc arcs_25_1[1] = { - {0, 1}, + {0, 1}, }; static state states_25[2] = { - {2, arcs_25_0}, - {1, arcs_25_1}, + {2, arcs_25_0}, + {1, arcs_25_1}, }; static arc arcs_26_0[1] = { - {74, 1}, + {74, 1}, }; static arc arcs_26_1[1] = { - {75, 2}, + {75, 2}, }; static arc arcs_26_2[1] = { - {0, 2}, + {0, 2}, }; static state states_26[3] = { - {1, arcs_26_0}, - {1, arcs_26_1}, - {1, arcs_26_2}, + {1, arcs_26_0}, + {1, arcs_26_1}, + {1, arcs_26_2}, }; static arc arcs_27_0[1] = { - {76, 1}, + {76, 1}, }; static arc arcs_27_1[2] = { - {77, 2}, - {12, 3}, + {77, 2}, + {12, 3}, }; static arc arcs_27_2[3] = { - {77, 2}, - {12, 3}, - {74, 4}, + {77, 2}, + {12, 3}, + {74, 4}, }; static arc arcs_27_3[1] = { - {74, 4}, + {74, 4}, }; static arc arcs_27_4[3] = { - {30, 5}, - {13, 6}, - {78, 5}, + {30, 5}, + {13, 6}, + {78, 5}, }; static arc arcs_27_5[1] = { - {0, 5}, + {0, 5}, }; static arc arcs_27_6[1] = { - {78, 7}, + {78, 7}, }; static arc arcs_27_7[1] = { - {15, 5}, + {15, 5}, }; static state states_27[8] = { - {1, arcs_27_0}, - {2, arcs_27_1}, - {3, arcs_27_2}, - {1, arcs_27_3}, - {3, arcs_27_4}, - {1, arcs_27_5}, - {1, arcs_27_6}, - {1, arcs_27_7}, + {1, arcs_27_0}, + {2, arcs_27_1}, + {3, arcs_27_2}, + {1, arcs_27_3}, + {3, arcs_27_4}, + {1, arcs_27_5}, + {1, arcs_27_6}, + {1, arcs_27_7}, }; static arc arcs_28_0[1] = { - {21, 1}, + {21, 1}, }; static arc arcs_28_1[2] = { - {80, 2}, - {0, 1}, + {80, 2}, + {0, 1}, }; static arc arcs_28_2[1] = { - {21, 3}, + {21, 3}, }; static arc arcs_28_3[1] = { - {0, 3}, + {0, 3}, }; static state states_28[4] = { - {1, arcs_28_0}, - {2, arcs_28_1}, - {1, arcs_28_2}, - {1, arcs_28_3}, + {1, arcs_28_0}, + {2, arcs_28_1}, + {1, arcs_28_2}, + {1, arcs_28_3}, }; static arc arcs_29_0[1] = { - {12, 1}, + {12, 1}, }; static arc arcs_29_1[2] = { - {80, 2}, - {0, 1}, + {80, 2}, + {0, 1}, }; static arc arcs_29_2[1] = { - {21, 3}, + {21, 3}, }; static arc arcs_29_3[1] = { - {0, 3}, + {0, 3}, }; static state states_29[4] = { - {1, arcs_29_0}, - {2, arcs_29_1}, - {1, arcs_29_2}, - {1, arcs_29_3}, + {1, arcs_29_0}, + {2, arcs_29_1}, + {1, arcs_29_2}, + {1, arcs_29_3}, }; static arc arcs_30_0[1] = { - {79, 1}, + {79, 1}, }; static arc arcs_30_1[2] = { - {29, 2}, - {0, 1}, + {29, 2}, + {0, 1}, }; static arc arcs_30_2[2] = { - {79, 1}, - {0, 2}, + {79, 1}, + {0, 2}, }; static state states_30[3] = { - {1, arcs_30_0}, - {2, arcs_30_1}, - {2, arcs_30_2}, + {1, arcs_30_0}, + {2, arcs_30_1}, + {2, arcs_30_2}, }; static arc arcs_31_0[1] = { - {81, 1}, + {81, 1}, }; static arc arcs_31_1[2] = { - {29, 0}, - {0, 1}, + {29, 0}, + {0, 1}, }; static state states_31[2] = { - {1, arcs_31_0}, - {2, arcs_31_1}, + {1, arcs_31_0}, + {2, arcs_31_1}, }; static arc arcs_32_0[1] = { - {21, 1}, + {21, 1}, }; static arc arcs_32_1[2] = { - {77, 0}, - {0, 1}, + {77, 0}, + {0, 1}, }; static state states_32[2] = { - {1, arcs_32_0}, - {2, arcs_32_1}, + {1, arcs_32_0}, + {2, arcs_32_1}, }; static arc arcs_33_0[1] = { - {82, 1}, + {82, 1}, }; static arc arcs_33_1[1] = { - {21, 2}, + {21, 2}, }; static arc arcs_33_2[2] = { - {29, 1}, - {0, 2}, + {29, 1}, + {0, 2}, }; static state states_33[3] = { - {1, arcs_33_0}, - {1, arcs_33_1}, - {2, arcs_33_2}, + {1, arcs_33_0}, + {1, arcs_33_1}, + {2, arcs_33_2}, }; static arc arcs_34_0[1] = { - {83, 1}, + {83, 1}, }; static arc arcs_34_1[1] = { - {84, 2}, + {84, 2}, }; static arc arcs_34_2[2] = { - {85, 3}, - {0, 2}, + {85, 3}, + {0, 2}, }; static arc arcs_34_3[1] = { - {28, 4}, + {28, 4}, }; static arc arcs_34_4[2] = { - {29, 5}, - {0, 4}, + {29, 5}, + {0, 4}, }; static arc arcs_34_5[1] = { - {28, 6}, + {28, 6}, }; static arc arcs_34_6[1] = { - {0, 6}, + {0, 6}, }; static state states_34[7] = { - {1, arcs_34_0}, - {1, arcs_34_1}, - {2, arcs_34_2}, - {1, arcs_34_3}, - {2, arcs_34_4}, - {1, arcs_34_5}, - {1, arcs_34_6}, + {1, arcs_34_0}, + {1, arcs_34_1}, + {2, arcs_34_2}, + {1, arcs_34_3}, + {2, arcs_34_4}, + {1, arcs_34_5}, + {1, arcs_34_6}, }; static arc arcs_35_0[1] = { - {86, 1}, + {86, 1}, }; static arc arcs_35_1[1] = { - {28, 2}, + {28, 2}, }; static arc arcs_35_2[2] = { - {29, 3}, - {0, 2}, + {29, 3}, + {0, 2}, }; static arc arcs_35_3[1] = { - {28, 4}, + {28, 4}, }; static arc arcs_35_4[1] = { - {0, 4}, + {0, 4}, }; static state states_35[5] = { - {1, arcs_35_0}, - {1, arcs_35_1}, - {2, arcs_35_2}, - {1, arcs_35_3}, - {1, arcs_35_4}, + {1, arcs_35_0}, + {1, arcs_35_1}, + {2, arcs_35_2}, + {1, arcs_35_3}, + {1, arcs_35_4}, }; static arc arcs_36_0[8] = { - {87, 1}, - {88, 1}, - {89, 1}, - {90, 1}, - {91, 1}, - {19, 1}, - {18, 1}, - {17, 1}, + {87, 1}, + {88, 1}, + {89, 1}, + {90, 1}, + {91, 1}, + {19, 1}, + {18, 1}, + {17, 1}, }; static arc arcs_36_1[1] = { - {0, 1}, + {0, 1}, }; static state states_36[2] = { - {8, arcs_36_0}, - {1, arcs_36_1}, + {8, arcs_36_0}, + {1, arcs_36_1}, }; static arc arcs_37_0[1] = { - {92, 1}, + {92, 1}, }; static arc arcs_37_1[1] = { - {28, 2}, + {28, 2}, }; static arc arcs_37_2[1] = { - {23, 3}, + {23, 3}, }; static arc arcs_37_3[1] = { - {24, 4}, + {24, 4}, }; static arc arcs_37_4[3] = { - {93, 1}, - {94, 5}, - {0, 4}, + {93, 1}, + {94, 5}, + {0, 4}, }; static arc arcs_37_5[1] = { - {23, 6}, + {23, 6}, }; static arc arcs_37_6[1] = { - {24, 7}, + {24, 7}, }; static arc arcs_37_7[1] = { - {0, 7}, + {0, 7}, }; static state states_37[8] = { - {1, arcs_37_0}, - {1, arcs_37_1}, - {1, arcs_37_2}, - {1, arcs_37_3}, - {3, arcs_37_4}, - {1, arcs_37_5}, - {1, arcs_37_6}, - {1, arcs_37_7}, + {1, arcs_37_0}, + {1, arcs_37_1}, + {1, arcs_37_2}, + {1, arcs_37_3}, + {3, arcs_37_4}, + {1, arcs_37_5}, + {1, arcs_37_6}, + {1, arcs_37_7}, }; static arc arcs_38_0[1] = { - {95, 1}, + {95, 1}, }; static arc arcs_38_1[1] = { - {28, 2}, + {28, 2}, }; static arc arcs_38_2[1] = { - {23, 3}, + {23, 3}, }; static arc arcs_38_3[1] = { - {24, 4}, + {24, 4}, }; static arc arcs_38_4[2] = { - {94, 5}, - {0, 4}, + {94, 5}, + {0, 4}, }; static arc arcs_38_5[1] = { - {23, 6}, + {23, 6}, }; static arc arcs_38_6[1] = { - {24, 7}, + {24, 7}, }; static arc arcs_38_7[1] = { - {0, 7}, + {0, 7}, }; static state states_38[8] = { - {1, arcs_38_0}, - {1, arcs_38_1}, - {1, arcs_38_2}, - {1, arcs_38_3}, - {2, arcs_38_4}, - {1, arcs_38_5}, - {1, arcs_38_6}, - {1, arcs_38_7}, + {1, arcs_38_0}, + {1, arcs_38_1}, + {1, arcs_38_2}, + {1, arcs_38_3}, + {2, arcs_38_4}, + {1, arcs_38_5}, + {1, arcs_38_6}, + {1, arcs_38_7}, }; static arc arcs_39_0[1] = { - {96, 1}, + {96, 1}, }; static arc arcs_39_1[1] = { - {61, 2}, + {61, 2}, }; static arc arcs_39_2[1] = { - {85, 3}, + {85, 3}, }; static arc arcs_39_3[1] = { - {9, 4}, + {9, 4}, }; static arc arcs_39_4[1] = { - {23, 5}, + {23, 5}, }; static arc arcs_39_5[1] = { - {24, 6}, + {24, 6}, }; static arc arcs_39_6[2] = { - {94, 7}, - {0, 6}, + {94, 7}, + {0, 6}, }; static arc arcs_39_7[1] = { - {23, 8}, + {23, 8}, }; static arc arcs_39_8[1] = { - {24, 9}, + {24, 9}, }; static arc arcs_39_9[1] = { - {0, 9}, + {0, 9}, }; static state states_39[10] = { - {1, arcs_39_0}, - {1, arcs_39_1}, - {1, arcs_39_2}, - {1, arcs_39_3}, - {1, arcs_39_4}, - {1, arcs_39_5}, - {2, arcs_39_6}, - {1, arcs_39_7}, - {1, arcs_39_8}, - {1, arcs_39_9}, + {1, arcs_39_0}, + {1, arcs_39_1}, + {1, arcs_39_2}, + {1, arcs_39_3}, + {1, arcs_39_4}, + {1, arcs_39_5}, + {2, arcs_39_6}, + {1, arcs_39_7}, + {1, arcs_39_8}, + {1, arcs_39_9}, }; static arc arcs_40_0[1] = { - {97, 1}, + {97, 1}, }; static arc arcs_40_1[1] = { - {23, 2}, + {23, 2}, }; static arc arcs_40_2[1] = { - {24, 3}, + {24, 3}, }; static arc arcs_40_3[2] = { - {98, 4}, - {99, 5}, + {98, 4}, + {99, 5}, }; static arc arcs_40_4[1] = { - {23, 6}, + {23, 6}, }; static arc arcs_40_5[1] = { - {23, 7}, + {23, 7}, }; static arc arcs_40_6[1] = { - {24, 8}, + {24, 8}, }; static arc arcs_40_7[1] = { - {24, 9}, + {24, 9}, }; static arc arcs_40_8[4] = { - {98, 4}, - {94, 10}, - {99, 5}, - {0, 8}, + {98, 4}, + {94, 10}, + {99, 5}, + {0, 8}, }; static arc arcs_40_9[1] = { - {0, 9}, + {0, 9}, }; static arc arcs_40_10[1] = { - {23, 11}, + {23, 11}, }; static arc arcs_40_11[1] = { - {24, 12}, + {24, 12}, }; static arc arcs_40_12[2] = { - {99, 5}, - {0, 12}, + {99, 5}, + {0, 12}, }; static state states_40[13] = { - {1, arcs_40_0}, - {1, arcs_40_1}, - {1, arcs_40_2}, - {2, arcs_40_3}, - {1, arcs_40_4}, - {1, arcs_40_5}, - {1, arcs_40_6}, - {1, arcs_40_7}, - {4, arcs_40_8}, - {1, arcs_40_9}, - {1, arcs_40_10}, - {1, arcs_40_11}, - {2, arcs_40_12}, + {1, arcs_40_0}, + {1, arcs_40_1}, + {1, arcs_40_2}, + {2, arcs_40_3}, + {1, arcs_40_4}, + {1, arcs_40_5}, + {1, arcs_40_6}, + {1, arcs_40_7}, + {4, arcs_40_8}, + {1, arcs_40_9}, + {1, arcs_40_10}, + {1, arcs_40_11}, + {2, arcs_40_12}, }; static arc arcs_41_0[1] = { - {100, 1}, + {100, 1}, }; static arc arcs_41_1[1] = { - {28, 2}, + {28, 2}, }; static arc arcs_41_2[2] = { - {101, 3}, - {23, 4}, + {101, 3}, + {23, 4}, }; static arc arcs_41_3[1] = { - {23, 4}, + {23, 4}, }; static arc arcs_41_4[1] = { - {24, 5}, + {24, 5}, }; static arc arcs_41_5[1] = { - {0, 5}, + {0, 5}, }; static state states_41[6] = { - {1, arcs_41_0}, - {1, arcs_41_1}, - {2, arcs_41_2}, - {1, arcs_41_3}, - {1, arcs_41_4}, - {1, arcs_41_5}, + {1, arcs_41_0}, + {1, arcs_41_1}, + {2, arcs_41_2}, + {1, arcs_41_3}, + {1, arcs_41_4}, + {1, arcs_41_5}, }; static arc arcs_42_0[1] = { - {80, 1}, + {80, 1}, }; static arc arcs_42_1[1] = { - {84, 2}, + {84, 2}, }; static arc arcs_42_2[1] = { - {0, 2}, + {0, 2}, }; static state states_42[3] = { - {1, arcs_42_0}, - {1, arcs_42_1}, - {1, arcs_42_2}, + {1, arcs_42_0}, + {1, arcs_42_1}, + {1, arcs_42_2}, }; static arc arcs_43_0[1] = { - {102, 1}, + {102, 1}, }; static arc arcs_43_1[2] = { - {28, 2}, - {0, 1}, + {28, 2}, + {0, 1}, }; static arc arcs_43_2[3] = { - {80, 3}, - {29, 3}, - {0, 2}, + {80, 3}, + {29, 3}, + {0, 2}, }; static arc arcs_43_3[1] = { - {28, 4}, + {28, 4}, }; static arc arcs_43_4[1] = { - {0, 4}, + {0, 4}, }; static state states_43[5] = { - {1, arcs_43_0}, - {2, arcs_43_1}, - {3, arcs_43_2}, - {1, arcs_43_3}, - {1, arcs_43_4}, + {1, arcs_43_0}, + {2, arcs_43_1}, + {3, arcs_43_2}, + {1, arcs_43_3}, + {1, arcs_43_4}, }; static arc arcs_44_0[2] = { - {3, 1}, - {2, 2}, + {3, 1}, + {2, 2}, }; static arc arcs_44_1[1] = { - {0, 1}, + {0, 1}, }; static arc arcs_44_2[1] = { - {103, 3}, + {103, 3}, }; static arc arcs_44_3[1] = { - {6, 4}, + {6, 4}, }; static arc arcs_44_4[2] = { - {6, 4}, - {104, 1}, + {6, 4}, + {104, 1}, }; static state states_44[5] = { - {2, arcs_44_0}, - {1, arcs_44_1}, - {1, arcs_44_2}, - {1, arcs_44_3}, - {2, arcs_44_4}, + {2, arcs_44_0}, + {1, arcs_44_1}, + {1, arcs_44_2}, + {1, arcs_44_3}, + {2, arcs_44_4}, }; static arc arcs_45_0[1] = { - {106, 1}, + {106, 1}, }; static arc arcs_45_1[2] = { - {29, 2}, - {0, 1}, + {29, 2}, + {0, 1}, }; static arc arcs_45_2[1] = { - {106, 3}, + {106, 3}, }; static arc arcs_45_3[2] = { - {29, 4}, - {0, 3}, + {29, 4}, + {0, 3}, }; static arc arcs_45_4[2] = { - {106, 3}, - {0, 4}, + {106, 3}, + {0, 4}, }; static state states_45[5] = { - {1, arcs_45_0}, - {2, arcs_45_1}, - {1, arcs_45_2}, - {2, arcs_45_3}, - {2, arcs_45_4}, + {1, arcs_45_0}, + {2, arcs_45_1}, + {1, arcs_45_2}, + {2, arcs_45_3}, + {2, arcs_45_4}, }; static arc arcs_46_0[2] = { - {107, 1}, - {108, 1}, + {107, 1}, + {108, 1}, }; static arc arcs_46_1[1] = { - {0, 1}, + {0, 1}, }; static state states_46[2] = { - {2, arcs_46_0}, - {1, arcs_46_1}, + {2, arcs_46_0}, + {1, arcs_46_1}, }; static arc arcs_47_0[1] = { - {109, 1}, + {109, 1}, }; static arc arcs_47_1[2] = { - {25, 2}, - {23, 3}, + {25, 2}, + {23, 3}, }; static arc arcs_47_2[1] = { - {23, 3}, + {23, 3}, }; static arc arcs_47_3[1] = { - {106, 4}, + {106, 4}, }; static arc arcs_47_4[1] = { - {0, 4}, + {0, 4}, }; static state states_47[5] = { - {1, arcs_47_0}, - {2, arcs_47_1}, - {1, arcs_47_2}, - {1, arcs_47_3}, - {1, arcs_47_4}, + {1, arcs_47_0}, + {2, arcs_47_1}, + {1, arcs_47_2}, + {1, arcs_47_3}, + {1, arcs_47_4}, }; static arc arcs_48_0[2] = { - {107, 1}, - {110, 2}, + {107, 1}, + {110, 2}, }; static arc arcs_48_1[2] = { - {92, 3}, - {0, 1}, + {92, 3}, + {0, 1}, }; static arc arcs_48_2[1] = { - {0, 2}, + {0, 2}, }; static arc arcs_48_3[1] = { - {107, 4}, + {107, 4}, }; static arc arcs_48_4[1] = { - {94, 5}, + {94, 5}, }; static arc arcs_48_5[1] = { - {28, 2}, + {28, 2}, }; static state states_48[6] = { - {2, arcs_48_0}, - {2, arcs_48_1}, - {1, arcs_48_2}, - {1, arcs_48_3}, - {1, arcs_48_4}, - {1, arcs_48_5}, + {2, arcs_48_0}, + {2, arcs_48_1}, + {1, arcs_48_2}, + {1, arcs_48_3}, + {1, arcs_48_4}, + {1, arcs_48_5}, }; static arc arcs_49_0[1] = { - {111, 1}, + {111, 1}, }; static arc arcs_49_1[2] = { - {112, 0}, - {0, 1}, + {112, 0}, + {0, 1}, }; static state states_49[2] = { - {1, arcs_49_0}, - {2, arcs_49_1}, + {1, arcs_49_0}, + {2, arcs_49_1}, }; static arc arcs_50_0[1] = { - {113, 1}, + {113, 1}, }; static arc arcs_50_1[2] = { - {114, 0}, - {0, 1}, + {114, 0}, + {0, 1}, }; static state states_50[2] = { - {1, arcs_50_0}, - {2, arcs_50_1}, + {1, arcs_50_0}, + {2, arcs_50_1}, }; static arc arcs_51_0[2] = { - {115, 1}, - {116, 2}, + {115, 1}, + {116, 2}, }; static arc arcs_51_1[1] = { - {113, 2}, + {113, 2}, }; static arc arcs_51_2[1] = { - {0, 2}, + {0, 2}, }; static state states_51[3] = { - {2, arcs_51_0}, - {1, arcs_51_1}, - {1, arcs_51_2}, + {2, arcs_51_0}, + {1, arcs_51_1}, + {1, arcs_51_2}, }; static arc arcs_52_0[1] = { - {84, 1}, + {84, 1}, }; static arc arcs_52_1[2] = { - {117, 0}, - {0, 1}, + {117, 0}, + {0, 1}, }; static state states_52[2] = { - {1, arcs_52_0}, - {2, arcs_52_1}, + {1, arcs_52_0}, + {2, arcs_52_1}, }; static arc arcs_53_0[10] = { - {118, 1}, - {119, 1}, - {120, 1}, - {121, 1}, - {122, 1}, - {123, 1}, - {124, 1}, - {85, 1}, - {115, 2}, - {125, 3}, + {118, 1}, + {119, 1}, + {120, 1}, + {121, 1}, + {122, 1}, + {123, 1}, + {124, 1}, + {85, 1}, + {115, 2}, + {125, 3}, }; static arc arcs_53_1[1] = { - {0, 1}, + {0, 1}, }; static arc arcs_53_2[1] = { - {85, 1}, + {85, 1}, }; static arc arcs_53_3[2] = { - {115, 1}, - {0, 3}, + {115, 1}, + {0, 3}, }; static state states_53[4] = { - {10, arcs_53_0}, - {1, arcs_53_1}, - {1, arcs_53_2}, - {2, arcs_53_3}, + {10, arcs_53_0}, + {1, arcs_53_1}, + {1, arcs_53_2}, + {2, arcs_53_3}, }; static arc arcs_54_0[1] = { - {126, 1}, + {126, 1}, }; static arc arcs_54_1[2] = { - {127, 0}, - {0, 1}, + {127, 0}, + {0, 1}, }; static state states_54[2] = { - {1, arcs_54_0}, - {2, arcs_54_1}, + {1, arcs_54_0}, + {2, arcs_54_1}, }; static arc arcs_55_0[1] = { - {128, 1}, + {128, 1}, }; static arc arcs_55_1[2] = { - {129, 0}, - {0, 1}, + {129, 0}, + {0, 1}, }; static state states_55[2] = { - {1, arcs_55_0}, - {2, arcs_55_1}, + {1, arcs_55_0}, + {2, arcs_55_1}, }; static arc arcs_56_0[1] = { - {130, 1}, + {130, 1}, }; static arc arcs_56_1[2] = { - {131, 0}, - {0, 1}, + {131, 0}, + {0, 1}, }; static state states_56[2] = { - {1, arcs_56_0}, - {2, arcs_56_1}, + {1, arcs_56_0}, + {2, arcs_56_1}, }; static arc arcs_57_0[1] = { - {132, 1}, + {132, 1}, }; static arc arcs_57_1[3] = { - {133, 0}, - {59, 0}, - {0, 1}, + {133, 0}, + {59, 0}, + {0, 1}, }; static state states_57[2] = { - {1, arcs_57_0}, - {3, arcs_57_1}, + {1, arcs_57_0}, + {3, arcs_57_1}, }; static arc arcs_58_0[1] = { - {134, 1}, + {134, 1}, }; static arc arcs_58_1[3] = { - {135, 0}, - {136, 0}, - {0, 1}, + {135, 0}, + {136, 0}, + {0, 1}, }; static state states_58[2] = { - {1, arcs_58_0}, - {3, arcs_58_1}, + {1, arcs_58_0}, + {3, arcs_58_1}, }; static arc arcs_59_0[1] = { - {137, 1}, + {137, 1}, }; static arc arcs_59_1[5] = { - {30, 0}, - {138, 0}, - {139, 0}, - {140, 0}, - {0, 1}, + {30, 0}, + {138, 0}, + {139, 0}, + {140, 0}, + {0, 1}, }; static state states_59[2] = { - {1, arcs_59_0}, - {5, arcs_59_1}, + {1, arcs_59_0}, + {5, arcs_59_1}, }; static arc arcs_60_0[4] = { - {135, 1}, - {136, 1}, - {141, 1}, - {142, 2}, + {135, 1}, + {136, 1}, + {141, 1}, + {142, 2}, }; static arc arcs_60_1[1] = { - {137, 2}, + {137, 2}, }; static arc arcs_60_2[1] = { - {0, 2}, + {0, 2}, }; static state states_60[3] = { - {4, arcs_60_0}, - {1, arcs_60_1}, - {1, arcs_60_2}, + {4, arcs_60_0}, + {1, arcs_60_1}, + {1, arcs_60_2}, }; static arc arcs_61_0[1] = { - {143, 1}, + {143, 1}, }; static arc arcs_61_1[3] = { - {144, 1}, - {31, 2}, - {0, 1}, + {144, 1}, + {31, 2}, + {0, 1}, }; static arc arcs_61_2[1] = { - {137, 3}, + {137, 3}, }; static arc arcs_61_3[1] = { - {0, 3}, + {0, 3}, }; static state states_61[4] = { - {1, arcs_61_0}, - {3, arcs_61_1}, - {1, arcs_61_2}, - {1, arcs_61_3}, + {1, arcs_61_0}, + {3, arcs_61_1}, + {1, arcs_61_2}, + {1, arcs_61_3}, }; static arc arcs_62_0[7] = { - {13, 1}, - {146, 2}, - {149, 3}, - {152, 4}, - {21, 5}, - {154, 5}, - {155, 6}, + {13, 1}, + {146, 2}, + {149, 3}, + {152, 4}, + {21, 5}, + {154, 5}, + {155, 6}, }; static arc arcs_62_1[3] = { - {45, 7}, - {145, 7}, - {15, 5}, + {45, 7}, + {145, 7}, + {15, 5}, }; static arc arcs_62_2[2] = { - {147, 8}, - {148, 5}, + {147, 8}, + {148, 5}, }; static arc arcs_62_3[2] = { - {150, 9}, - {151, 5}, + {150, 9}, + {151, 5}, }; static arc arcs_62_4[1] = { - {153, 10}, + {153, 10}, }; static arc arcs_62_5[1] = { - {0, 5}, + {0, 5}, }; static arc arcs_62_6[2] = { - {155, 6}, - {0, 6}, + {155, 6}, + {0, 6}, }; static arc arcs_62_7[1] = { - {15, 5}, + {15, 5}, }; static arc arcs_62_8[1] = { - {148, 5}, + {148, 5}, }; static arc arcs_62_9[1] = { - {151, 5}, + {151, 5}, }; static arc arcs_62_10[1] = { - {152, 5}, + {152, 5}, }; static state states_62[11] = { - {7, arcs_62_0}, - {3, arcs_62_1}, - {2, arcs_62_2}, - {2, arcs_62_3}, - {1, arcs_62_4}, - {1, arcs_62_5}, - {2, arcs_62_6}, - {1, arcs_62_7}, - {1, arcs_62_8}, - {1, arcs_62_9}, - {1, arcs_62_10}, + {7, arcs_62_0}, + {3, arcs_62_1}, + {2, arcs_62_2}, + {2, arcs_62_3}, + {1, arcs_62_4}, + {1, arcs_62_5}, + {2, arcs_62_6}, + {1, arcs_62_7}, + {1, arcs_62_8}, + {1, arcs_62_9}, + {1, arcs_62_10}, }; static arc arcs_63_0[1] = { - {28, 1}, + {28, 1}, }; static arc arcs_63_1[3] = { - {156, 2}, - {29, 3}, - {0, 1}, + {156, 2}, + {29, 3}, + {0, 1}, }; static arc arcs_63_2[1] = { - {0, 2}, + {0, 2}, }; static arc arcs_63_3[2] = { - {28, 4}, - {0, 3}, + {28, 4}, + {0, 3}, }; static arc arcs_63_4[2] = { - {29, 3}, - {0, 4}, + {29, 3}, + {0, 4}, }; static state states_63[5] = { - {1, arcs_63_0}, - {3, arcs_63_1}, - {1, arcs_63_2}, - {2, arcs_63_3}, - {2, arcs_63_4}, + {1, arcs_63_0}, + {3, arcs_63_1}, + {1, arcs_63_2}, + {2, arcs_63_3}, + {2, arcs_63_4}, }; static arc arcs_64_0[1] = { - {28, 1}, + {28, 1}, }; static arc arcs_64_1[3] = { - {157, 2}, - {29, 3}, - {0, 1}, + {157, 2}, + {29, 3}, + {0, 1}, }; static arc arcs_64_2[1] = { - {0, 2}, + {0, 2}, }; static arc arcs_64_3[2] = { - {28, 4}, - {0, 3}, + {28, 4}, + {0, 3}, }; static arc arcs_64_4[2] = { - {29, 3}, - {0, 4}, + {29, 3}, + {0, 4}, }; static state states_64[5] = { - {1, arcs_64_0}, - {3, arcs_64_1}, - {1, arcs_64_2}, - {2, arcs_64_3}, - {2, arcs_64_4}, + {1, arcs_64_0}, + {3, arcs_64_1}, + {1, arcs_64_2}, + {2, arcs_64_3}, + {2, arcs_64_4}, }; static arc arcs_65_0[1] = { - {109, 1}, + {109, 1}, }; static arc arcs_65_1[2] = { - {25, 2}, - {23, 3}, + {25, 2}, + {23, 3}, }; static arc arcs_65_2[1] = { - {23, 3}, + {23, 3}, }; static arc arcs_65_3[1] = { - {28, 4}, + {28, 4}, }; static arc arcs_65_4[1] = { - {0, 4}, + {0, 4}, }; static state states_65[5] = { - {1, arcs_65_0}, - {2, arcs_65_1}, - {1, arcs_65_2}, - {1, arcs_65_3}, - {1, arcs_65_4}, + {1, arcs_65_0}, + {2, arcs_65_1}, + {1, arcs_65_2}, + {1, arcs_65_3}, + {1, arcs_65_4}, }; static arc arcs_66_0[3] = { - {13, 1}, - {146, 2}, - {77, 3}, + {13, 1}, + {146, 2}, + {77, 3}, }; static arc arcs_66_1[2] = { - {14, 4}, - {15, 5}, + {14, 4}, + {15, 5}, }; static arc arcs_66_2[1] = { - {158, 6}, + {158, 6}, }; static arc arcs_66_3[1] = { - {21, 5}, + {21, 5}, }; static arc arcs_66_4[1] = { - {15, 5}, + {15, 5}, }; static arc arcs_66_5[1] = { - {0, 5}, + {0, 5}, }; static arc arcs_66_6[1] = { - {148, 5}, + {148, 5}, }; static state states_66[7] = { - {3, arcs_66_0}, - {2, arcs_66_1}, - {1, arcs_66_2}, - {1, arcs_66_3}, - {1, arcs_66_4}, - {1, arcs_66_5}, - {1, arcs_66_6}, + {3, arcs_66_0}, + {2, arcs_66_1}, + {1, arcs_66_2}, + {1, arcs_66_3}, + {1, arcs_66_4}, + {1, arcs_66_5}, + {1, arcs_66_6}, }; static arc arcs_67_0[1] = { - {159, 1}, + {159, 1}, }; static arc arcs_67_1[2] = { - {29, 2}, - {0, 1}, + {29, 2}, + {0, 1}, }; static arc arcs_67_2[2] = { - {159, 1}, - {0, 2}, + {159, 1}, + {0, 2}, }; static state states_67[3] = { - {1, arcs_67_0}, - {2, arcs_67_1}, - {2, arcs_67_2}, + {1, arcs_67_0}, + {2, arcs_67_1}, + {2, arcs_67_2}, }; static arc arcs_68_0[3] = { - {77, 1}, - {28, 2}, - {23, 3}, + {77, 1}, + {28, 2}, + {23, 3}, }; static arc arcs_68_1[1] = { - {77, 4}, + {77, 4}, }; static arc arcs_68_2[2] = { - {23, 3}, - {0, 2}, + {23, 3}, + {0, 2}, }; static arc arcs_68_3[3] = { - {28, 5}, - {160, 6}, - {0, 3}, + {28, 5}, + {160, 6}, + {0, 3}, }; static arc arcs_68_4[1] = { - {77, 6}, + {77, 6}, }; static arc arcs_68_5[2] = { - {160, 6}, - {0, 5}, + {160, 6}, + {0, 5}, }; static arc arcs_68_6[1] = { - {0, 6}, + {0, 6}, }; static state states_68[7] = { - {3, arcs_68_0}, - {1, arcs_68_1}, - {2, arcs_68_2}, - {3, arcs_68_3}, - {1, arcs_68_4}, - {2, arcs_68_5}, - {1, arcs_68_6}, + {3, arcs_68_0}, + {1, arcs_68_1}, + {2, arcs_68_2}, + {3, arcs_68_3}, + {1, arcs_68_4}, + {2, arcs_68_5}, + {1, arcs_68_6}, }; static arc arcs_69_0[1] = { - {23, 1}, + {23, 1}, }; static arc arcs_69_1[2] = { - {28, 2}, - {0, 1}, + {28, 2}, + {0, 1}, }; static arc arcs_69_2[1] = { - {0, 2}, + {0, 2}, }; static state states_69[3] = { - {1, arcs_69_0}, - {2, arcs_69_1}, - {1, arcs_69_2}, + {1, arcs_69_0}, + {2, arcs_69_1}, + {1, arcs_69_2}, }; static arc arcs_70_0[1] = { - {84, 1}, + {84, 1}, }; static arc arcs_70_1[2] = { - {29, 2}, - {0, 1}, + {29, 2}, + {0, 1}, }; static arc arcs_70_2[2] = { - {84, 1}, - {0, 2}, + {84, 1}, + {0, 2}, }; static state states_70[3] = { - {1, arcs_70_0}, - {2, arcs_70_1}, - {2, arcs_70_2}, + {1, arcs_70_0}, + {2, arcs_70_1}, + {2, arcs_70_2}, }; static arc arcs_71_0[1] = { - {28, 1}, + {28, 1}, }; static arc arcs_71_1[2] = { - {29, 2}, - {0, 1}, + {29, 2}, + {0, 1}, }; static arc arcs_71_2[2] = { - {28, 1}, - {0, 2}, + {28, 1}, + {0, 2}, }; static state states_71[3] = { - {1, arcs_71_0}, - {2, arcs_71_1}, - {2, arcs_71_2}, + {1, arcs_71_0}, + {2, arcs_71_1}, + {2, arcs_71_2}, }; static arc arcs_72_0[1] = { - {28, 1}, + {28, 1}, }; static arc arcs_72_1[1] = { - {23, 2}, + {23, 2}, }; static arc arcs_72_2[1] = { - {28, 3}, + {28, 3}, }; static arc arcs_72_3[2] = { - {29, 4}, - {0, 3}, + {29, 4}, + {0, 3}, }; static arc arcs_72_4[2] = { - {28, 1}, - {0, 4}, + {28, 1}, + {0, 4}, }; static state states_72[5] = { - {1, arcs_72_0}, - {1, arcs_72_1}, - {1, arcs_72_2}, - {2, arcs_72_3}, - {2, arcs_72_4}, + {1, arcs_72_0}, + {1, arcs_72_1}, + {1, arcs_72_2}, + {2, arcs_72_3}, + {2, arcs_72_4}, }; static arc arcs_73_0[1] = { - {161, 1}, + {161, 1}, }; static arc arcs_73_1[1] = { - {21, 2}, + {21, 2}, }; static arc arcs_73_2[2] = { - {13, 3}, - {23, 4}, + {13, 3}, + {23, 4}, }; static arc arcs_73_3[2] = { - {9, 5}, - {15, 6}, + {9, 5}, + {15, 6}, }; static arc arcs_73_4[1] = { - {24, 7}, + {24, 7}, }; static arc arcs_73_5[1] = { - {15, 6}, + {15, 6}, }; static arc arcs_73_6[1] = { - {23, 4}, + {23, 4}, }; static arc arcs_73_7[1] = { - {0, 7}, + {0, 7}, }; static state states_73[8] = { - {1, arcs_73_0}, - {1, arcs_73_1}, - {2, arcs_73_2}, - {2, arcs_73_3}, - {1, arcs_73_4}, - {1, arcs_73_5}, - {1, arcs_73_6}, - {1, arcs_73_7}, + {1, arcs_73_0}, + {1, arcs_73_1}, + {2, arcs_73_2}, + {2, arcs_73_3}, + {1, arcs_73_4}, + {1, arcs_73_5}, + {1, arcs_73_6}, + {1, arcs_73_7}, }; static arc arcs_74_0[3] = { - {162, 1}, - {30, 2}, - {31, 3}, + {162, 1}, + {30, 2}, + {31, 3}, }; static arc arcs_74_1[2] = { - {29, 4}, - {0, 1}, + {29, 4}, + {0, 1}, }; static arc arcs_74_2[1] = { - {28, 5}, + {28, 5}, }; static arc arcs_74_3[1] = { - {28, 6}, + {28, 6}, }; static arc arcs_74_4[4] = { - {162, 1}, - {30, 2}, - {31, 3}, - {0, 4}, + {162, 1}, + {30, 2}, + {31, 3}, + {0, 4}, }; static arc arcs_74_5[2] = { - {29, 7}, - {0, 5}, + {29, 7}, + {0, 5}, }; static arc arcs_74_6[1] = { - {0, 6}, + {0, 6}, }; static arc arcs_74_7[2] = { - {162, 5}, - {31, 3}, + {162, 5}, + {31, 3}, }; static state states_74[8] = { - {3, arcs_74_0}, - {2, arcs_74_1}, - {1, arcs_74_2}, - {1, arcs_74_3}, - {4, arcs_74_4}, - {2, arcs_74_5}, - {1, arcs_74_6}, - {2, arcs_74_7}, + {3, arcs_74_0}, + {2, arcs_74_1}, + {1, arcs_74_2}, + {1, arcs_74_3}, + {4, arcs_74_4}, + {2, arcs_74_5}, + {1, arcs_74_6}, + {2, arcs_74_7}, }; static arc arcs_75_0[1] = { - {28, 1}, + {28, 1}, }; static arc arcs_75_1[3] = { - {157, 2}, - {27, 3}, - {0, 1}, + {157, 2}, + {27, 3}, + {0, 1}, }; static arc arcs_75_2[1] = { - {0, 2}, + {0, 2}, }; static arc arcs_75_3[1] = { - {28, 2}, + {28, 2}, }; static state states_75[4] = { - {1, arcs_75_0}, - {3, arcs_75_1}, - {1, arcs_75_2}, - {1, arcs_75_3}, + {1, arcs_75_0}, + {3, arcs_75_1}, + {1, arcs_75_2}, + {1, arcs_75_3}, }; static arc arcs_76_0[2] = { - {156, 1}, - {164, 1}, + {156, 1}, + {164, 1}, }; static arc arcs_76_1[1] = { - {0, 1}, + {0, 1}, }; static state states_76[2] = { - {2, arcs_76_0}, - {1, arcs_76_1}, + {2, arcs_76_0}, + {1, arcs_76_1}, }; static arc arcs_77_0[1] = { - {96, 1}, + {96, 1}, }; static arc arcs_77_1[1] = { - {61, 2}, + {61, 2}, }; static arc arcs_77_2[1] = { - {85, 3}, + {85, 3}, }; static arc arcs_77_3[1] = { - {105, 4}, + {105, 4}, }; static arc arcs_77_4[2] = { - {163, 5}, - {0, 4}, + {163, 5}, + {0, 4}, }; static arc arcs_77_5[1] = { - {0, 5}, + {0, 5}, }; static state states_77[6] = { - {1, arcs_77_0}, - {1, arcs_77_1}, - {1, arcs_77_2}, - {1, arcs_77_3}, - {2, arcs_77_4}, - {1, arcs_77_5}, + {1, arcs_77_0}, + {1, arcs_77_1}, + {1, arcs_77_2}, + {1, arcs_77_3}, + {2, arcs_77_4}, + {1, arcs_77_5}, }; static arc arcs_78_0[1] = { - {92, 1}, + {92, 1}, }; static arc arcs_78_1[1] = { - {106, 2}, + {106, 2}, }; static arc arcs_78_2[2] = { - {163, 3}, - {0, 2}, + {163, 3}, + {0, 2}, }; static arc arcs_78_3[1] = { - {0, 3}, + {0, 3}, }; static state states_78[4] = { - {1, arcs_78_0}, - {1, arcs_78_1}, - {2, arcs_78_2}, - {1, arcs_78_3}, + {1, arcs_78_0}, + {1, arcs_78_1}, + {2, arcs_78_2}, + {1, arcs_78_3}, }; static arc arcs_79_0[2] = { - {157, 1}, - {166, 1}, + {157, 1}, + {166, 1}, }; static arc arcs_79_1[1] = { - {0, 1}, + {0, 1}, }; static state states_79[2] = { - {2, arcs_79_0}, - {1, arcs_79_1}, + {2, arcs_79_0}, + {1, arcs_79_1}, }; static arc arcs_80_0[1] = { - {96, 1}, + {96, 1}, }; static arc arcs_80_1[1] = { - {61, 2}, + {61, 2}, }; static arc arcs_80_2[1] = { - {85, 3}, + {85, 3}, }; static arc arcs_80_3[1] = { - {107, 4}, + {107, 4}, }; static arc arcs_80_4[2] = { - {165, 5}, - {0, 4}, + {165, 5}, + {0, 4}, }; static arc arcs_80_5[1] = { - {0, 5}, + {0, 5}, }; static state states_80[6] = { - {1, arcs_80_0}, - {1, arcs_80_1}, - {1, arcs_80_2}, - {1, arcs_80_3}, - {2, arcs_80_4}, - {1, arcs_80_5}, + {1, arcs_80_0}, + {1, arcs_80_1}, + {1, arcs_80_2}, + {1, arcs_80_3}, + {2, arcs_80_4}, + {1, arcs_80_5}, }; static arc arcs_81_0[1] = { - {92, 1}, + {92, 1}, }; static arc arcs_81_1[1] = { - {106, 2}, + {106, 2}, }; static arc arcs_81_2[2] = { - {165, 3}, - {0, 2}, + {165, 3}, + {0, 2}, }; static arc arcs_81_3[1] = { - {0, 3}, + {0, 3}, }; static state states_81[4] = { - {1, arcs_81_0}, - {1, arcs_81_1}, - {2, arcs_81_2}, - {1, arcs_81_3}, + {1, arcs_81_0}, + {1, arcs_81_1}, + {2, arcs_81_2}, + {1, arcs_81_3}, }; static arc arcs_82_0[1] = { - {28, 1}, + {28, 1}, }; static arc arcs_82_1[2] = { - {29, 0}, - {0, 1}, + {29, 0}, + {0, 1}, }; static state states_82[2] = { - {1, arcs_82_0}, - {2, arcs_82_1}, + {1, arcs_82_0}, + {2, arcs_82_1}, }; static arc arcs_83_0[1] = { - {21, 1}, + {21, 1}, }; static arc arcs_83_1[1] = { - {0, 1}, + {0, 1}, }; static state states_83[2] = { - {1, arcs_83_0}, - {1, arcs_83_1}, + {1, arcs_83_0}, + {1, arcs_83_1}, }; static arc arcs_84_0[1] = { - {168, 1}, + {168, 1}, }; static arc arcs_84_1[2] = { - {9, 2}, - {0, 1}, + {9, 2}, + {0, 1}, }; static arc arcs_84_2[1] = { - {0, 2}, + {0, 2}, }; static state states_84[3] = { - {1, arcs_84_0}, - {2, arcs_84_1}, - {1, arcs_84_2}, + {1, arcs_84_0}, + {2, arcs_84_1}, + {1, arcs_84_2}, }; static dfa dfas[85] = { - {256, "single_input", 0, 3, states_0, - "\004\050\060\000\000\000\000\124\360\024\114\220\023\040\010\000\200\041\044\015\002\001"}, - {257, "file_input", 0, 2, states_1, - "\204\050\060\000\000\000\000\124\360\024\114\220\023\040\010\000\200\041\044\015\002\001"}, - {258, "eval_input", 0, 3, states_2, - "\000\040\040\000\000\000\000\000\000\000\000\000\000\040\010\000\200\041\044\015\000\000"}, - {259, "decorator", 0, 7, states_3, - "\000\010\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000"}, - {260, "decorators", 0, 2, states_4, - "\000\010\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000"}, - {261, "decorated", 0, 3, states_5, - "\000\010\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000"}, - {262, "funcdef", 0, 6, states_6, - "\000\000\020\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000"}, - {263, "parameters", 0, 4, states_7, - "\000\040\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000"}, - {264, "varargslist", 0, 10, states_8, - "\000\040\040\300\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000"}, - {265, "fpdef", 0, 4, states_9, - "\000\040\040\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000"}, - {266, "fplist", 0, 3, states_10, - "\000\040\040\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000"}, - {267, "stmt", 0, 2, states_11, - "\000\050\060\000\000\000\000\124\360\024\114\220\023\040\010\000\200\041\044\015\002\001"}, - {268, "simple_stmt", 0, 4, states_12, - "\000\040\040\000\000\000\000\124\360\024\114\000\000\040\010\000\200\041\044\015\000\001"}, - {269, "small_stmt", 0, 2, states_13, - "\000\040\040\000\000\000\000\124\360\024\114\000\000\040\010\000\200\041\044\015\000\001"}, - {270, "expr_stmt", 0, 6, states_14, - "\000\040\040\000\000\000\000\000\000\000\000\000\000\040\010\000\200\041\044\015\000\000"}, - {271, "augassign", 0, 2, states_15, - "\000\000\000\000\000\300\377\003\000\000\000\000\000\000\000\000\000\000\000\000\000\000"}, - {272, "print_stmt", 0, 9, states_16, - "\000\000\000\000\000\000\000\004\000\000\000\000\000\000\000\000\000\000\000\000\000\000"}, - {273, "del_stmt", 0, 3, states_17, - "\000\000\000\000\000\000\000\020\000\000\000\000\000\000\000\000\000\000\000\000\000\000"}, - {274, "pass_stmt", 0, 2, states_18, - "\000\000\000\000\000\000\000\100\000\000\000\000\000\000\000\000\000\000\000\000\000\000"}, - {275, "flow_stmt", 0, 2, states_19, - "\000\000\000\000\000\000\000\000\360\000\000\000\000\000\000\000\000\000\000\000\000\001"}, - {276, "break_stmt", 0, 2, states_20, - "\000\000\000\000\000\000\000\000\020\000\000\000\000\000\000\000\000\000\000\000\000\000"}, - {277, "continue_stmt", 0, 2, states_21, - "\000\000\000\000\000\000\000\000\040\000\000\000\000\000\000\000\000\000\000\000\000\000"}, - {278, "return_stmt", 0, 3, states_22, - "\000\000\000\000\000\000\000\000\100\000\000\000\000\000\000\000\000\000\000\000\000\000"}, - {279, "yield_stmt", 0, 2, states_23, - "\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\001"}, - {280, "raise_stmt", 0, 7, states_24, - "\000\000\000\000\000\000\000\000\200\000\000\000\000\000\000\000\000\000\000\000\000\000"}, - {281, "import_stmt", 0, 2, states_25, - "\000\000\000\000\000\000\000\000\000\024\000\000\000\000\000\000\000\000\000\000\000\000"}, - {282, "import_name", 0, 3, states_26, - "\000\000\000\000\000\000\000\000\000\004\000\000\000\000\000\000\000\000\000\000\000\000"}, - {283, "import_from", 0, 8, states_27, - "\000\000\000\000\000\000\000\000\000\020\000\000\000\000\000\000\000\000\000\000\000\000"}, - {284, "import_as_name", 0, 4, states_28, - "\000\000\040\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000"}, - {285, "dotted_as_name", 0, 4, states_29, - "\000\000\040\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000"}, - {286, "import_as_names", 0, 3, states_30, - "\000\000\040\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000"}, - {287, "dotted_as_names", 0, 2, states_31, - "\000\000\040\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000"}, - {288, "dotted_name", 0, 2, states_32, - "\000\000\040\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000"}, - {289, "global_stmt", 0, 3, states_33, - "\000\000\000\000\000\000\000\000\000\000\004\000\000\000\000\000\000\000\000\000\000\000"}, - {290, "exec_stmt", 0, 7, states_34, - "\000\000\000\000\000\000\000\000\000\000\010\000\000\000\000\000\000\000\000\000\000\000"}, - {291, "assert_stmt", 0, 5, states_35, - "\000\000\000\000\000\000\000\000\000\000\100\000\000\000\000\000\000\000\000\000\000\000"}, - {292, "compound_stmt", 0, 2, states_36, - "\000\010\020\000\000\000\000\000\000\000\000\220\023\000\000\000\000\000\000\000\002\000"}, - {293, "if_stmt", 0, 8, states_37, - "\000\000\000\000\000\000\000\000\000\000\000\020\000\000\000\000\000\000\000\000\000\000"}, - {294, "while_stmt", 0, 8, states_38, - "\000\000\000\000\000\000\000\000\000\000\000\200\000\000\000\000\000\000\000\000\000\000"}, - {295, "for_stmt", 0, 10, states_39, - "\000\000\000\000\000\000\000\000\000\000\000\000\001\000\000\000\000\000\000\000\000\000"}, - {296, "try_stmt", 0, 13, states_40, - "\000\000\000\000\000\000\000\000\000\000\000\000\002\000\000\000\000\000\000\000\000\000"}, - {297, "with_stmt", 0, 6, states_41, - "\000\000\000\000\000\000\000\000\000\000\000\000\020\000\000\000\000\000\000\000\000\000"}, - {298, "with_var", 0, 3, states_42, - "\000\000\000\000\000\000\000\000\000\000\001\000\000\000\000\000\000\000\000\000\000\000"}, - {299, "except_clause", 0, 5, states_43, - "\000\000\000\000\000\000\000\000\000\000\000\000\100\000\000\000\000\000\000\000\000\000"}, - {300, "suite", 0, 5, states_44, - "\004\040\040\000\000\000\000\124\360\024\114\000\000\040\010\000\200\041\044\015\000\001"}, - {301, "testlist_safe", 0, 5, states_45, - "\000\040\040\000\000\000\000\000\000\000\000\000\000\040\010\000\200\041\044\015\000\000"}, - {302, "old_test", 0, 2, states_46, - "\000\040\040\000\000\000\000\000\000\000\000\000\000\040\010\000\200\041\044\015\000\000"}, - {303, "old_lambdef", 0, 5, states_47, - "\000\000\000\000\000\000\000\000\000\000\000\000\000\040\000\000\000\000\000\000\000\000"}, - {304, "test", 0, 6, states_48, - "\000\040\040\000\000\000\000\000\000\000\000\000\000\040\010\000\200\041\044\015\000\000"}, - {305, "or_test", 0, 2, states_49, - "\000\040\040\000\000\000\000\000\000\000\000\000\000\000\010\000\200\041\044\015\000\000"}, - {306, "and_test", 0, 2, states_50, - "\000\040\040\000\000\000\000\000\000\000\000\000\000\000\010\000\200\041\044\015\000\000"}, - {307, "not_test", 0, 3, states_51, - "\000\040\040\000\000\000\000\000\000\000\000\000\000\000\010\000\200\041\044\015\000\000"}, - {308, "comparison", 0, 2, states_52, - "\000\040\040\000\000\000\000\000\000\000\000\000\000\000\000\000\200\041\044\015\000\000"}, - {309, "comp_op", 0, 4, states_53, - "\000\000\000\000\000\000\000\000\000\000\040\000\000\000\310\077\000\000\000\000\000\000"}, - {310, "expr", 0, 2, states_54, - "\000\040\040\000\000\000\000\000\000\000\000\000\000\000\000\000\200\041\044\015\000\000"}, - {311, "xor_expr", 0, 2, states_55, - "\000\040\040\000\000\000\000\000\000\000\000\000\000\000\000\000\200\041\044\015\000\000"}, - {312, "and_expr", 0, 2, states_56, - "\000\040\040\000\000\000\000\000\000\000\000\000\000\000\000\000\200\041\044\015\000\000"}, - {313, "shift_expr", 0, 2, states_57, - "\000\040\040\000\000\000\000\000\000\000\000\000\000\000\000\000\200\041\044\015\000\000"}, - {314, "arith_expr", 0, 2, states_58, - "\000\040\040\000\000\000\000\000\000\000\000\000\000\000\000\000\200\041\044\015\000\000"}, - {315, "term", 0, 2, states_59, - "\000\040\040\000\000\000\000\000\000\000\000\000\000\000\000\000\200\041\044\015\000\000"}, - {316, "factor", 0, 3, states_60, - "\000\040\040\000\000\000\000\000\000\000\000\000\000\000\000\000\200\041\044\015\000\000"}, - {317, "power", 0, 4, states_61, - "\000\040\040\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\044\015\000\000"}, - {318, "atom", 0, 11, states_62, - "\000\040\040\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\044\015\000\000"}, - {319, "listmaker", 0, 5, states_63, - "\000\040\040\000\000\000\000\000\000\000\000\000\000\040\010\000\200\041\044\015\000\000"}, - {320, "testlist_gexp", 0, 5, states_64, - "\000\040\040\000\000\000\000\000\000\000\000\000\000\040\010\000\200\041\044\015\000\000"}, - {321, "lambdef", 0, 5, states_65, - "\000\000\000\000\000\000\000\000\000\000\000\000\000\040\000\000\000\000\000\000\000\000"}, - {322, "trailer", 0, 7, states_66, - "\000\040\000\000\000\000\000\000\000\040\000\000\000\000\000\000\000\000\004\000\000\000"}, - {323, "subscriptlist", 0, 3, states_67, - "\000\040\240\000\000\000\000\000\000\040\000\000\000\040\010\000\200\041\044\015\000\000"}, - {324, "subscript", 0, 7, states_68, - "\000\040\240\000\000\000\000\000\000\040\000\000\000\040\010\000\200\041\044\015\000\000"}, - {325, "sliceop", 0, 3, states_69, - "\000\000\200\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000"}, - {326, "exprlist", 0, 3, states_70, - "\000\040\040\000\000\000\000\000\000\000\000\000\000\000\000\000\200\041\044\015\000\000"}, - {327, "testlist", 0, 3, states_71, - "\000\040\040\000\000\000\000\000\000\000\000\000\000\040\010\000\200\041\044\015\000\000"}, - {328, "dictmaker", 0, 5, states_72, - "\000\040\040\000\000\000\000\000\000\000\000\000\000\040\010\000\200\041\044\015\000\000"}, - {329, "classdef", 0, 8, states_73, - "\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\002\000"}, - {330, "arglist", 0, 8, states_74, - "\000\040\040\300\000\000\000\000\000\000\000\000\000\040\010\000\200\041\044\015\000\000"}, - {331, "argument", 0, 4, states_75, - "\000\040\040\000\000\000\000\000\000\000\000\000\000\040\010\000\200\041\044\015\000\000"}, - {332, "list_iter", 0, 2, states_76, - "\000\000\000\000\000\000\000\000\000\000\000\020\001\000\000\000\000\000\000\000\000\000"}, - {333, "list_for", 0, 6, states_77, - "\000\000\000\000\000\000\000\000\000\000\000\000\001\000\000\000\000\000\000\000\000\000"}, - {334, "list_if", 0, 4, states_78, - "\000\000\000\000\000\000\000\000\000\000\000\020\000\000\000\000\000\000\000\000\000\000"}, - {335, "gen_iter", 0, 2, states_79, - "\000\000\000\000\000\000\000\000\000\000\000\020\001\000\000\000\000\000\000\000\000\000"}, - {336, "gen_for", 0, 6, states_80, - "\000\000\000\000\000\000\000\000\000\000\000\000\001\000\000\000\000\000\000\000\000\000"}, - {337, "gen_if", 0, 4, states_81, - "\000\000\000\000\000\000\000\000\000\000\000\020\000\000\000\000\000\000\000\000\000\000"}, - {338, "testlist1", 0, 2, states_82, - "\000\040\040\000\000\000\000\000\000\000\000\000\000\040\010\000\200\041\044\015\000\000"}, - {339, "encoding_decl", 0, 2, states_83, - "\000\000\040\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000"}, - {340, "yield_expr", 0, 3, states_84, - "\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\001"}, + {256, "single_input", 0, 3, states_0, + "\004\050\060\000\000\000\000\124\360\024\114\220\023\040\010\000\200\041\044\015\002\001"}, + {257, "file_input", 0, 2, states_1, + "\204\050\060\000\000\000\000\124\360\024\114\220\023\040\010\000\200\041\044\015\002\001"}, + {258, "eval_input", 0, 3, states_2, + "\000\040\040\000\000\000\000\000\000\000\000\000\000\040\010\000\200\041\044\015\000\000"}, + {259, "decorator", 0, 7, states_3, + "\000\010\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000"}, + {260, "decorators", 0, 2, states_4, + "\000\010\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000"}, + {261, "decorated", 0, 3, states_5, + "\000\010\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000"}, + {262, "funcdef", 0, 6, states_6, + "\000\000\020\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000"}, + {263, "parameters", 0, 4, states_7, + "\000\040\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000"}, + {264, "varargslist", 0, 10, states_8, + "\000\040\040\300\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000"}, + {265, "fpdef", 0, 4, states_9, + "\000\040\040\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000"}, + {266, "fplist", 0, 3, states_10, + "\000\040\040\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000"}, + {267, "stmt", 0, 2, states_11, + "\000\050\060\000\000\000\000\124\360\024\114\220\023\040\010\000\200\041\044\015\002\001"}, + {268, "simple_stmt", 0, 4, states_12, + "\000\040\040\000\000\000\000\124\360\024\114\000\000\040\010\000\200\041\044\015\000\001"}, + {269, "small_stmt", 0, 2, states_13, + "\000\040\040\000\000\000\000\124\360\024\114\000\000\040\010\000\200\041\044\015\000\001"}, + {270, "expr_stmt", 0, 6, states_14, + "\000\040\040\000\000\000\000\000\000\000\000\000\000\040\010\000\200\041\044\015\000\000"}, + {271, "augassign", 0, 2, states_15, + "\000\000\000\000\000\300\377\003\000\000\000\000\000\000\000\000\000\000\000\000\000\000"}, + {272, "print_stmt", 0, 9, states_16, + "\000\000\000\000\000\000\000\004\000\000\000\000\000\000\000\000\000\000\000\000\000\000"}, + {273, "del_stmt", 0, 3, states_17, + "\000\000\000\000\000\000\000\020\000\000\000\000\000\000\000\000\000\000\000\000\000\000"}, + {274, "pass_stmt", 0, 2, states_18, + "\000\000\000\000\000\000\000\100\000\000\000\000\000\000\000\000\000\000\000\000\000\000"}, + {275, "flow_stmt", 0, 2, states_19, + "\000\000\000\000\000\000\000\000\360\000\000\000\000\000\000\000\000\000\000\000\000\001"}, + {276, "break_stmt", 0, 2, states_20, + "\000\000\000\000\000\000\000\000\020\000\000\000\000\000\000\000\000\000\000\000\000\000"}, + {277, "continue_stmt", 0, 2, states_21, + "\000\000\000\000\000\000\000\000\040\000\000\000\000\000\000\000\000\000\000\000\000\000"}, + {278, "return_stmt", 0, 3, states_22, + "\000\000\000\000\000\000\000\000\100\000\000\000\000\000\000\000\000\000\000\000\000\000"}, + {279, "yield_stmt", 0, 2, states_23, + "\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\001"}, + {280, "raise_stmt", 0, 7, states_24, + "\000\000\000\000\000\000\000\000\200\000\000\000\000\000\000\000\000\000\000\000\000\000"}, + {281, "import_stmt", 0, 2, states_25, + "\000\000\000\000\000\000\000\000\000\024\000\000\000\000\000\000\000\000\000\000\000\000"}, + {282, "import_name", 0, 3, states_26, + "\000\000\000\000\000\000\000\000\000\004\000\000\000\000\000\000\000\000\000\000\000\000"}, + {283, "import_from", 0, 8, states_27, + "\000\000\000\000\000\000\000\000\000\020\000\000\000\000\000\000\000\000\000\000\000\000"}, + {284, "import_as_name", 0, 4, states_28, + "\000\000\040\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000"}, + {285, "dotted_as_name", 0, 4, states_29, + "\000\000\040\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000"}, + {286, "import_as_names", 0, 3, states_30, + "\000\000\040\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000"}, + {287, "dotted_as_names", 0, 2, states_31, + "\000\000\040\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000"}, + {288, "dotted_name", 0, 2, states_32, + "\000\000\040\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000"}, + {289, "global_stmt", 0, 3, states_33, + "\000\000\000\000\000\000\000\000\000\000\004\000\000\000\000\000\000\000\000\000\000\000"}, + {290, "exec_stmt", 0, 7, states_34, + "\000\000\000\000\000\000\000\000\000\000\010\000\000\000\000\000\000\000\000\000\000\000"}, + {291, "assert_stmt", 0, 5, states_35, + "\000\000\000\000\000\000\000\000\000\000\100\000\000\000\000\000\000\000\000\000\000\000"}, + {292, "compound_stmt", 0, 2, states_36, + "\000\010\020\000\000\000\000\000\000\000\000\220\023\000\000\000\000\000\000\000\002\000"}, + {293, "if_stmt", 0, 8, states_37, + "\000\000\000\000\000\000\000\000\000\000\000\020\000\000\000\000\000\000\000\000\000\000"}, + {294, "while_stmt", 0, 8, states_38, + "\000\000\000\000\000\000\000\000\000\000\000\200\000\000\000\000\000\000\000\000\000\000"}, + {295, "for_stmt", 0, 10, states_39, + "\000\000\000\000\000\000\000\000\000\000\000\000\001\000\000\000\000\000\000\000\000\000"}, + {296, "try_stmt", 0, 13, states_40, + "\000\000\000\000\000\000\000\000\000\000\000\000\002\000\000\000\000\000\000\000\000\000"}, + {297, "with_stmt", 0, 6, states_41, + "\000\000\000\000\000\000\000\000\000\000\000\000\020\000\000\000\000\000\000\000\000\000"}, + {298, "with_var", 0, 3, states_42, + "\000\000\000\000\000\000\000\000\000\000\001\000\000\000\000\000\000\000\000\000\000\000"}, + {299, "except_clause", 0, 5, states_43, + "\000\000\000\000\000\000\000\000\000\000\000\000\100\000\000\000\000\000\000\000\000\000"}, + {300, "suite", 0, 5, states_44, + "\004\040\040\000\000\000\000\124\360\024\114\000\000\040\010\000\200\041\044\015\000\001"}, + {301, "testlist_safe", 0, 5, states_45, + "\000\040\040\000\000\000\000\000\000\000\000\000\000\040\010\000\200\041\044\015\000\000"}, + {302, "old_test", 0, 2, states_46, + "\000\040\040\000\000\000\000\000\000\000\000\000\000\040\010\000\200\041\044\015\000\000"}, + {303, "old_lambdef", 0, 5, states_47, + "\000\000\000\000\000\000\000\000\000\000\000\000\000\040\000\000\000\000\000\000\000\000"}, + {304, "test", 0, 6, states_48, + "\000\040\040\000\000\000\000\000\000\000\000\000\000\040\010\000\200\041\044\015\000\000"}, + {305, "or_test", 0, 2, states_49, + "\000\040\040\000\000\000\000\000\000\000\000\000\000\000\010\000\200\041\044\015\000\000"}, + {306, "and_test", 0, 2, states_50, + "\000\040\040\000\000\000\000\000\000\000\000\000\000\000\010\000\200\041\044\015\000\000"}, + {307, "not_test", 0, 3, states_51, + "\000\040\040\000\000\000\000\000\000\000\000\000\000\000\010\000\200\041\044\015\000\000"}, + {308, "comparison", 0, 2, states_52, + "\000\040\040\000\000\000\000\000\000\000\000\000\000\000\000\000\200\041\044\015\000\000"}, + {309, "comp_op", 0, 4, states_53, + "\000\000\000\000\000\000\000\000\000\000\040\000\000\000\310\077\000\000\000\000\000\000"}, + {310, "expr", 0, 2, states_54, + "\000\040\040\000\000\000\000\000\000\000\000\000\000\000\000\000\200\041\044\015\000\000"}, + {311, "xor_expr", 0, 2, states_55, + "\000\040\040\000\000\000\000\000\000\000\000\000\000\000\000\000\200\041\044\015\000\000"}, + {312, "and_expr", 0, 2, states_56, + "\000\040\040\000\000\000\000\000\000\000\000\000\000\000\000\000\200\041\044\015\000\000"}, + {313, "shift_expr", 0, 2, states_57, + "\000\040\040\000\000\000\000\000\000\000\000\000\000\000\000\000\200\041\044\015\000\000"}, + {314, "arith_expr", 0, 2, states_58, + "\000\040\040\000\000\000\000\000\000\000\000\000\000\000\000\000\200\041\044\015\000\000"}, + {315, "term", 0, 2, states_59, + "\000\040\040\000\000\000\000\000\000\000\000\000\000\000\000\000\200\041\044\015\000\000"}, + {316, "factor", 0, 3, states_60, + "\000\040\040\000\000\000\000\000\000\000\000\000\000\000\000\000\200\041\044\015\000\000"}, + {317, "power", 0, 4, states_61, + "\000\040\040\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\044\015\000\000"}, + {318, "atom", 0, 11, states_62, + "\000\040\040\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\044\015\000\000"}, + {319, "listmaker", 0, 5, states_63, + "\000\040\040\000\000\000\000\000\000\000\000\000\000\040\010\000\200\041\044\015\000\000"}, + {320, "testlist_gexp", 0, 5, states_64, + "\000\040\040\000\000\000\000\000\000\000\000\000\000\040\010\000\200\041\044\015\000\000"}, + {321, "lambdef", 0, 5, states_65, + "\000\000\000\000\000\000\000\000\000\000\000\000\000\040\000\000\000\000\000\000\000\000"}, + {322, "trailer", 0, 7, states_66, + "\000\040\000\000\000\000\000\000\000\040\000\000\000\000\000\000\000\000\004\000\000\000"}, + {323, "subscriptlist", 0, 3, states_67, + "\000\040\240\000\000\000\000\000\000\040\000\000\000\040\010\000\200\041\044\015\000\000"}, + {324, "subscript", 0, 7, states_68, + "\000\040\240\000\000\000\000\000\000\040\000\000\000\040\010\000\200\041\044\015\000\000"}, + {325, "sliceop", 0, 3, states_69, + "\000\000\200\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000"}, + {326, "exprlist", 0, 3, states_70, + "\000\040\040\000\000\000\000\000\000\000\000\000\000\000\000\000\200\041\044\015\000\000"}, + {327, "testlist", 0, 3, states_71, + "\000\040\040\000\000\000\000\000\000\000\000\000\000\040\010\000\200\041\044\015\000\000"}, + {328, "dictmaker", 0, 5, states_72, + "\000\040\040\000\000\000\000\000\000\000\000\000\000\040\010\000\200\041\044\015\000\000"}, + {329, "classdef", 0, 8, states_73, + "\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\002\000"}, + {330, "arglist", 0, 8, states_74, + "\000\040\040\300\000\000\000\000\000\000\000\000\000\040\010\000\200\041\044\015\000\000"}, + {331, "argument", 0, 4, states_75, + "\000\040\040\000\000\000\000\000\000\000\000\000\000\040\010\000\200\041\044\015\000\000"}, + {332, "list_iter", 0, 2, states_76, + "\000\000\000\000\000\000\000\000\000\000\000\020\001\000\000\000\000\000\000\000\000\000"}, + {333, "list_for", 0, 6, states_77, + "\000\000\000\000\000\000\000\000\000\000\000\000\001\000\000\000\000\000\000\000\000\000"}, + {334, "list_if", 0, 4, states_78, + "\000\000\000\000\000\000\000\000\000\000\000\020\000\000\000\000\000\000\000\000\000\000"}, + {335, "gen_iter", 0, 2, states_79, + "\000\000\000\000\000\000\000\000\000\000\000\020\001\000\000\000\000\000\000\000\000\000"}, + {336, "gen_for", 0, 6, states_80, + "\000\000\000\000\000\000\000\000\000\000\000\000\001\000\000\000\000\000\000\000\000\000"}, + {337, "gen_if", 0, 4, states_81, + "\000\000\000\000\000\000\000\000\000\000\000\020\000\000\000\000\000\000\000\000\000\000"}, + {338, "testlist1", 0, 2, states_82, + "\000\040\040\000\000\000\000\000\000\000\000\000\000\040\010\000\200\041\044\015\000\000"}, + {339, "encoding_decl", 0, 2, states_83, + "\000\000\040\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000"}, + {340, "yield_expr", 0, 3, states_84, + "\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\001"}, }; static label labels[169] = { - {0, "EMPTY"}, - {256, 0}, - {4, 0}, - {268, 0}, - {292, 0}, - {257, 0}, - {267, 0}, - {0, 0}, - {258, 0}, - {327, 0}, - {259, 0}, - {50, 0}, - {288, 0}, - {7, 0}, - {330, 0}, - {8, 0}, - {260, 0}, - {261, 0}, - {329, 0}, - {262, 0}, - {1, "def"}, - {1, 0}, - {263, 0}, - {11, 0}, - {300, 0}, - {264, 0}, - {265, 0}, - {22, 0}, - {304, 0}, - {12, 0}, - {16, 0}, - {36, 0}, - {266, 0}, - {269, 0}, - {13, 0}, - {270, 0}, - {272, 0}, - {273, 0}, - {274, 0}, - {275, 0}, - {281, 0}, - {289, 0}, - {290, 0}, - {291, 0}, - {271, 0}, - {340, 0}, - {37, 0}, - {38, 0}, - {39, 0}, - {40, 0}, - {41, 0}, - {42, 0}, - {43, 0}, - {44, 0}, - {45, 0}, - {46, 0}, - {47, 0}, - {49, 0}, - {1, "print"}, - {35, 0}, - {1, "del"}, - {326, 0}, - {1, "pass"}, - {276, 0}, - {277, 0}, - {278, 0}, - {280, 0}, - {279, 0}, - {1, "break"}, - {1, "continue"}, - {1, "return"}, - {1, "raise"}, - {282, 0}, - {283, 0}, - {1, "import"}, - {287, 0}, - {1, "from"}, - {23, 0}, - {286, 0}, - {284, 0}, - {1, "as"}, - {285, 0}, - {1, "global"}, - {1, "exec"}, - {310, 0}, - {1, "in"}, - {1, "assert"}, - {293, 0}, - {294, 0}, - {295, 0}, - {296, 0}, - {297, 0}, - {1, "if"}, - {1, "elif"}, - {1, "else"}, - {1, "while"}, - {1, "for"}, - {1, "try"}, - {299, 0}, - {1, "finally"}, - {1, "with"}, - {298, 0}, - {1, "except"}, - {5, 0}, - {6, 0}, - {301, 0}, - {302, 0}, - {305, 0}, - {303, 0}, - {1, "lambda"}, - {321, 0}, - {306, 0}, - {1, "or"}, - {307, 0}, - {1, "and"}, - {1, "not"}, - {308, 0}, - {309, 0}, - {20, 0}, - {21, 0}, - {28, 0}, - {31, 0}, - {30, 0}, - {29, 0}, - {29, 0}, - {1, "is"}, - {311, 0}, - {18, 0}, - {312, 0}, - {33, 0}, - {313, 0}, - {19, 0}, - {314, 0}, - {34, 0}, - {315, 0}, - {14, 0}, - {15, 0}, - {316, 0}, - {17, 0}, - {24, 0}, - {48, 0}, - {32, 0}, - {317, 0}, - {318, 0}, - {322, 0}, - {320, 0}, - {9, 0}, - {319, 0}, - {10, 0}, - {26, 0}, - {328, 0}, - {27, 0}, - {25, 0}, - {338, 0}, - {2, 0}, - {3, 0}, - {333, 0}, - {336, 0}, - {323, 0}, - {324, 0}, - {325, 0}, - {1, "class"}, - {331, 0}, - {332, 0}, - {334, 0}, - {335, 0}, - {337, 0}, - {339, 0}, - {1, "yield"}, + {0, "EMPTY"}, + {256, 0}, + {4, 0}, + {268, 0}, + {292, 0}, + {257, 0}, + {267, 0}, + {0, 0}, + {258, 0}, + {327, 0}, + {259, 0}, + {50, 0}, + {288, 0}, + {7, 0}, + {330, 0}, + {8, 0}, + {260, 0}, + {261, 0}, + {329, 0}, + {262, 0}, + {1, "def"}, + {1, 0}, + {263, 0}, + {11, 0}, + {300, 0}, + {264, 0}, + {265, 0}, + {22, 0}, + {304, 0}, + {12, 0}, + {16, 0}, + {36, 0}, + {266, 0}, + {269, 0}, + {13, 0}, + {270, 0}, + {272, 0}, + {273, 0}, + {274, 0}, + {275, 0}, + {281, 0}, + {289, 0}, + {290, 0}, + {291, 0}, + {271, 0}, + {340, 0}, + {37, 0}, + {38, 0}, + {39, 0}, + {40, 0}, + {41, 0}, + {42, 0}, + {43, 0}, + {44, 0}, + {45, 0}, + {46, 0}, + {47, 0}, + {49, 0}, + {1, "print"}, + {35, 0}, + {1, "del"}, + {326, 0}, + {1, "pass"}, + {276, 0}, + {277, 0}, + {278, 0}, + {280, 0}, + {279, 0}, + {1, "break"}, + {1, "continue"}, + {1, "return"}, + {1, "raise"}, + {282, 0}, + {283, 0}, + {1, "import"}, + {287, 0}, + {1, "from"}, + {23, 0}, + {286, 0}, + {284, 0}, + {1, "as"}, + {285, 0}, + {1, "global"}, + {1, "exec"}, + {310, 0}, + {1, "in"}, + {1, "assert"}, + {293, 0}, + {294, 0}, + {295, 0}, + {296, 0}, + {297, 0}, + {1, "if"}, + {1, "elif"}, + {1, "else"}, + {1, "while"}, + {1, "for"}, + {1, "try"}, + {299, 0}, + {1, "finally"}, + {1, "with"}, + {298, 0}, + {1, "except"}, + {5, 0}, + {6, 0}, + {301, 0}, + {302, 0}, + {305, 0}, + {303, 0}, + {1, "lambda"}, + {321, 0}, + {306, 0}, + {1, "or"}, + {307, 0}, + {1, "and"}, + {1, "not"}, + {308, 0}, + {309, 0}, + {20, 0}, + {21, 0}, + {28, 0}, + {31, 0}, + {30, 0}, + {29, 0}, + {29, 0}, + {1, "is"}, + {311, 0}, + {18, 0}, + {312, 0}, + {33, 0}, + {313, 0}, + {19, 0}, + {314, 0}, + {34, 0}, + {315, 0}, + {14, 0}, + {15, 0}, + {316, 0}, + {17, 0}, + {24, 0}, + {48, 0}, + {32, 0}, + {317, 0}, + {318, 0}, + {322, 0}, + {320, 0}, + {9, 0}, + {319, 0}, + {10, 0}, + {26, 0}, + {328, 0}, + {27, 0}, + {25, 0}, + {338, 0}, + {2, 0}, + {3, 0}, + {333, 0}, + {336, 0}, + {323, 0}, + {324, 0}, + {325, 0}, + {1, "class"}, + {331, 0}, + {332, 0}, + {334, 0}, + {335, 0}, + {337, 0}, + {339, 0}, + {1, "yield"}, }; grammar _PyParser_Grammar = { - 85, - dfas, - {169, labels}, - 256 + 85, + dfas, + {169, labels}, + 256 }; From python-checkins at python.org Sun May 16 01:00:52 2010 From: python-checkins at python.org (victor.stinner) Date: Sun, 16 May 2010 01:00:52 +0200 (CEST) Subject: [Python-checkins] r81222 - in python/branches/py3k: Parser/printgrammar.c Python/graminit.c Message-ID: <20100515230052.2235CEEAF2@mail.python.org> Author: victor.stinner Date: Sun May 16 01:00:51 2010 New Revision: 81222 Log: Merged revisions 81220 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r81220 | victor.stinner | 2010-05-16 00:55:28 +0200 (dim., 16 mai 2010) | 4 lines Use 4-spaces for indentation (instead of tabs) in pgen outputs Regenerate (reindent) Python/graminit.c ........ Modified: python/branches/py3k/ (props changed) python/branches/py3k/Parser/printgrammar.c python/branches/py3k/Python/graminit.c Modified: python/branches/py3k/Parser/printgrammar.c ============================================================================== --- python/branches/py3k/Parser/printgrammar.c (original) +++ python/branches/py3k/Parser/printgrammar.c Sun May 16 01:00:51 2010 @@ -20,10 +20,10 @@ printdfas(g, fp); printlabels(g, fp); fprintf(fp, "grammar _PyParser_Grammar = {\n"); - fprintf(fp, "\t%d,\n", g->g_ndfas); - fprintf(fp, "\tdfas,\n"); - fprintf(fp, "\t{%d, labels},\n", g->g_ll.ll_nlabels); - fprintf(fp, "\t%d\n", g->g_start); + fprintf(fp, " %d,\n", g->g_ndfas); + fprintf(fp, " dfas,\n"); + fprintf(fp, " {%d, labels},\n", g->g_ll.ll_nlabels); + fprintf(fp, " %d\n", g->g_start); fprintf(fp, "};\n"); } @@ -53,7 +53,7 @@ i, j, s->s_narcs); a = s->s_arc; for (k = 0; k < s->s_narcs; k++, a++) - fprintf(fp, "\t{%d, %d},\n", a->a_lbl, a->a_arrow); + fprintf(fp, " {%d, %d},\n", a->a_lbl, a->a_arrow); fprintf(fp, "};\n"); } } @@ -72,7 +72,7 @@ i, d->d_nstates); s = d->d_state; for (j = 0; j < d->d_nstates; j++, s++) - fprintf(fp, "\t{%d, arcs_%d_%d},\n", + fprintf(fp, " {%d, arcs_%d_%d},\n", s->s_narcs, i, j); fprintf(fp, "};\n"); } @@ -88,9 +88,9 @@ fprintf(fp, "static dfa dfas[%d] = {\n", g->g_ndfas); d = g->g_dfa; for (i = 0; i < g->g_ndfas; i++, d++) { - fprintf(fp, "\t{%d, \"%s\", %d, %d, states_%d,\n", + fprintf(fp, " {%d, \"%s\", %d, %d, states_%d,\n", d->d_type, d->d_name, d->d_initial, d->d_nstates, i); - fprintf(fp, "\t \""); + fprintf(fp, " \""); for (j = 0; j < NBYTES(g->g_ll.ll_nlabels); j++) fprintf(fp, "\\%03o", d->d_first[j] & 0xff); fprintf(fp, "\"},\n"); @@ -108,9 +108,9 @@ l = g->g_ll.ll_label; for (i = g->g_ll.ll_nlabels; --i >= 0; l++) { if (l->lb_str == NULL) - fprintf(fp, "\t{%d, 0},\n", l->lb_type); + fprintf(fp, " {%d, 0},\n", l->lb_type); else - fprintf(fp, "\t{%d, \"%s\"},\n", + fprintf(fp, " {%d, \"%s\"},\n", l->lb_type, l->lb_str); } fprintf(fp, "};\n"); Modified: python/branches/py3k/Python/graminit.c ============================================================================== --- python/branches/py3k/Python/graminit.c (original) +++ python/branches/py3k/Python/graminit.c Sun May 16 01:00:51 2010 @@ -4,2077 +4,2077 @@ #include "grammar.h" PyAPI_DATA(grammar) _PyParser_Grammar; static arc arcs_0_0[3] = { - {2, 1}, - {3, 1}, - {4, 2}, + {2, 1}, + {3, 1}, + {4, 2}, }; static arc arcs_0_1[1] = { - {0, 1}, + {0, 1}, }; static arc arcs_0_2[1] = { - {2, 1}, + {2, 1}, }; static state states_0[3] = { - {3, arcs_0_0}, - {1, arcs_0_1}, - {1, arcs_0_2}, + {3, arcs_0_0}, + {1, arcs_0_1}, + {1, arcs_0_2}, }; static arc arcs_1_0[3] = { - {2, 0}, - {6, 0}, - {7, 1}, + {2, 0}, + {6, 0}, + {7, 1}, }; static arc arcs_1_1[1] = { - {0, 1}, + {0, 1}, }; static state states_1[2] = { - {3, arcs_1_0}, - {1, arcs_1_1}, + {3, arcs_1_0}, + {1, arcs_1_1}, }; static arc arcs_2_0[1] = { - {9, 1}, + {9, 1}, }; static arc arcs_2_1[2] = { - {2, 1}, - {7, 2}, + {2, 1}, + {7, 2}, }; static arc arcs_2_2[1] = { - {0, 2}, + {0, 2}, }; static state states_2[3] = { - {1, arcs_2_0}, - {2, arcs_2_1}, - {1, arcs_2_2}, + {1, arcs_2_0}, + {2, arcs_2_1}, + {1, arcs_2_2}, }; static arc arcs_3_0[1] = { - {11, 1}, + {11, 1}, }; static arc arcs_3_1[1] = { - {12, 2}, + {12, 2}, }; static arc arcs_3_2[2] = { - {13, 3}, - {2, 4}, + {13, 3}, + {2, 4}, }; static arc arcs_3_3[2] = { - {14, 5}, - {15, 6}, + {14, 5}, + {15, 6}, }; static arc arcs_3_4[1] = { - {0, 4}, + {0, 4}, }; static arc arcs_3_5[1] = { - {15, 6}, + {15, 6}, }; static arc arcs_3_6[1] = { - {2, 4}, + {2, 4}, }; static state states_3[7] = { - {1, arcs_3_0}, - {1, arcs_3_1}, - {2, arcs_3_2}, - {2, arcs_3_3}, - {1, arcs_3_4}, - {1, arcs_3_5}, - {1, arcs_3_6}, + {1, arcs_3_0}, + {1, arcs_3_1}, + {2, arcs_3_2}, + {2, arcs_3_3}, + {1, arcs_3_4}, + {1, arcs_3_5}, + {1, arcs_3_6}, }; static arc arcs_4_0[1] = { - {10, 1}, + {10, 1}, }; static arc arcs_4_1[2] = { - {10, 1}, - {0, 1}, + {10, 1}, + {0, 1}, }; static state states_4[2] = { - {1, arcs_4_0}, - {2, arcs_4_1}, + {1, arcs_4_0}, + {2, arcs_4_1}, }; static arc arcs_5_0[1] = { - {16, 1}, + {16, 1}, }; static arc arcs_5_1[2] = { - {18, 2}, - {19, 2}, + {18, 2}, + {19, 2}, }; static arc arcs_5_2[1] = { - {0, 2}, + {0, 2}, }; static state states_5[3] = { - {1, arcs_5_0}, - {2, arcs_5_1}, - {1, arcs_5_2}, + {1, arcs_5_0}, + {2, arcs_5_1}, + {1, arcs_5_2}, }; static arc arcs_6_0[1] = { - {20, 1}, + {20, 1}, }; static arc arcs_6_1[1] = { - {21, 2}, + {21, 2}, }; static arc arcs_6_2[1] = { - {22, 3}, + {22, 3}, }; static arc arcs_6_3[2] = { - {23, 4}, - {25, 5}, + {23, 4}, + {25, 5}, }; static arc arcs_6_4[1] = { - {24, 6}, + {24, 6}, }; static arc arcs_6_5[1] = { - {26, 7}, + {26, 7}, }; static arc arcs_6_6[1] = { - {25, 5}, + {25, 5}, }; static arc arcs_6_7[1] = { - {0, 7}, + {0, 7}, }; static state states_6[8] = { - {1, arcs_6_0}, - {1, arcs_6_1}, - {1, arcs_6_2}, - {2, arcs_6_3}, - {1, arcs_6_4}, - {1, arcs_6_5}, - {1, arcs_6_6}, - {1, arcs_6_7}, + {1, arcs_6_0}, + {1, arcs_6_1}, + {1, arcs_6_2}, + {2, arcs_6_3}, + {1, arcs_6_4}, + {1, arcs_6_5}, + {1, arcs_6_6}, + {1, arcs_6_7}, }; static arc arcs_7_0[1] = { - {13, 1}, + {13, 1}, }; static arc arcs_7_1[2] = { - {27, 2}, - {15, 3}, + {27, 2}, + {15, 3}, }; static arc arcs_7_2[1] = { - {15, 3}, + {15, 3}, }; static arc arcs_7_3[1] = { - {0, 3}, + {0, 3}, }; static state states_7[4] = { - {1, arcs_7_0}, - {2, arcs_7_1}, - {1, arcs_7_2}, - {1, arcs_7_3}, + {1, arcs_7_0}, + {2, arcs_7_1}, + {1, arcs_7_2}, + {1, arcs_7_3}, }; static arc arcs_8_0[3] = { - {28, 1}, - {31, 2}, - {32, 3}, + {28, 1}, + {31, 2}, + {32, 3}, }; static arc arcs_8_1[3] = { - {29, 4}, - {30, 5}, - {0, 1}, + {29, 4}, + {30, 5}, + {0, 1}, }; static arc arcs_8_2[3] = { - {28, 6}, - {30, 7}, - {0, 2}, + {28, 6}, + {30, 7}, + {0, 2}, }; static arc arcs_8_3[1] = { - {28, 8}, + {28, 8}, }; static arc arcs_8_4[1] = { - {24, 9}, + {24, 9}, }; static arc arcs_8_5[4] = { - {28, 1}, - {31, 2}, - {32, 3}, - {0, 5}, + {28, 1}, + {31, 2}, + {32, 3}, + {0, 5}, }; static arc arcs_8_6[2] = { - {30, 7}, - {0, 6}, + {30, 7}, + {0, 6}, }; static arc arcs_8_7[2] = { - {28, 10}, - {32, 3}, + {28, 10}, + {32, 3}, }; static arc arcs_8_8[1] = { - {0, 8}, + {0, 8}, }; static arc arcs_8_9[2] = { - {30, 5}, - {0, 9}, + {30, 5}, + {0, 9}, }; static arc arcs_8_10[3] = { - {30, 7}, - {29, 11}, - {0, 10}, + {30, 7}, + {29, 11}, + {0, 10}, }; static arc arcs_8_11[1] = { - {24, 6}, + {24, 6}, }; static state states_8[12] = { - {3, arcs_8_0}, - {3, arcs_8_1}, - {3, arcs_8_2}, - {1, arcs_8_3}, - {1, arcs_8_4}, - {4, arcs_8_5}, - {2, arcs_8_6}, - {2, arcs_8_7}, - {1, arcs_8_8}, - {2, arcs_8_9}, - {3, arcs_8_10}, - {1, arcs_8_11}, + {3, arcs_8_0}, + {3, arcs_8_1}, + {3, arcs_8_2}, + {1, arcs_8_3}, + {1, arcs_8_4}, + {4, arcs_8_5}, + {2, arcs_8_6}, + {2, arcs_8_7}, + {1, arcs_8_8}, + {2, arcs_8_9}, + {3, arcs_8_10}, + {1, arcs_8_11}, }; static arc arcs_9_0[1] = { - {21, 1}, + {21, 1}, }; static arc arcs_9_1[2] = { - {25, 2}, - {0, 1}, + {25, 2}, + {0, 1}, }; static arc arcs_9_2[1] = { - {24, 3}, + {24, 3}, }; static arc arcs_9_3[1] = { - {0, 3}, + {0, 3}, }; static state states_9[4] = { - {1, arcs_9_0}, - {2, arcs_9_1}, - {1, arcs_9_2}, - {1, arcs_9_3}, + {1, arcs_9_0}, + {2, arcs_9_1}, + {1, arcs_9_2}, + {1, arcs_9_3}, }; static arc arcs_10_0[3] = { - {34, 1}, - {31, 2}, - {32, 3}, + {34, 1}, + {31, 2}, + {32, 3}, }; static arc arcs_10_1[3] = { - {29, 4}, - {30, 5}, - {0, 1}, + {29, 4}, + {30, 5}, + {0, 1}, }; static arc arcs_10_2[3] = { - {34, 6}, - {30, 7}, - {0, 2}, + {34, 6}, + {30, 7}, + {0, 2}, }; static arc arcs_10_3[1] = { - {34, 8}, + {34, 8}, }; static arc arcs_10_4[1] = { - {24, 9}, + {24, 9}, }; static arc arcs_10_5[4] = { - {34, 1}, - {31, 2}, - {32, 3}, - {0, 5}, + {34, 1}, + {31, 2}, + {32, 3}, + {0, 5}, }; static arc arcs_10_6[2] = { - {30, 7}, - {0, 6}, + {30, 7}, + {0, 6}, }; static arc arcs_10_7[2] = { - {34, 10}, - {32, 3}, + {34, 10}, + {32, 3}, }; static arc arcs_10_8[1] = { - {0, 8}, + {0, 8}, }; static arc arcs_10_9[2] = { - {30, 5}, - {0, 9}, + {30, 5}, + {0, 9}, }; static arc arcs_10_10[3] = { - {30, 7}, - {29, 11}, - {0, 10}, + {30, 7}, + {29, 11}, + {0, 10}, }; static arc arcs_10_11[1] = { - {24, 6}, + {24, 6}, }; static state states_10[12] = { - {3, arcs_10_0}, - {3, arcs_10_1}, - {3, arcs_10_2}, - {1, arcs_10_3}, - {1, arcs_10_4}, - {4, arcs_10_5}, - {2, arcs_10_6}, - {2, arcs_10_7}, - {1, arcs_10_8}, - {2, arcs_10_9}, - {3, arcs_10_10}, - {1, arcs_10_11}, + {3, arcs_10_0}, + {3, arcs_10_1}, + {3, arcs_10_2}, + {1, arcs_10_3}, + {1, arcs_10_4}, + {4, arcs_10_5}, + {2, arcs_10_6}, + {2, arcs_10_7}, + {1, arcs_10_8}, + {2, arcs_10_9}, + {3, arcs_10_10}, + {1, arcs_10_11}, }; static arc arcs_11_0[1] = { - {21, 1}, + {21, 1}, }; static arc arcs_11_1[1] = { - {0, 1}, + {0, 1}, }; static state states_11[2] = { - {1, arcs_11_0}, - {1, arcs_11_1}, + {1, arcs_11_0}, + {1, arcs_11_1}, }; static arc arcs_12_0[2] = { - {3, 1}, - {4, 1}, + {3, 1}, + {4, 1}, }; static arc arcs_12_1[1] = { - {0, 1}, + {0, 1}, }; static state states_12[2] = { - {2, arcs_12_0}, - {1, arcs_12_1}, + {2, arcs_12_0}, + {1, arcs_12_1}, }; static arc arcs_13_0[1] = { - {35, 1}, + {35, 1}, }; static arc arcs_13_1[2] = { - {36, 2}, - {2, 3}, + {36, 2}, + {2, 3}, }; static arc arcs_13_2[2] = { - {35, 1}, - {2, 3}, + {35, 1}, + {2, 3}, }; static arc arcs_13_3[1] = { - {0, 3}, + {0, 3}, }; static state states_13[4] = { - {1, arcs_13_0}, - {2, arcs_13_1}, - {2, arcs_13_2}, - {1, arcs_13_3}, + {1, arcs_13_0}, + {2, arcs_13_1}, + {2, arcs_13_2}, + {1, arcs_13_3}, }; static arc arcs_14_0[8] = { - {37, 1}, - {38, 1}, - {39, 1}, - {40, 1}, - {41, 1}, - {42, 1}, - {43, 1}, - {44, 1}, + {37, 1}, + {38, 1}, + {39, 1}, + {40, 1}, + {41, 1}, + {42, 1}, + {43, 1}, + {44, 1}, }; static arc arcs_14_1[1] = { - {0, 1}, + {0, 1}, }; static state states_14[2] = { - {8, arcs_14_0}, - {1, arcs_14_1}, + {8, arcs_14_0}, + {1, arcs_14_1}, }; static arc arcs_15_0[1] = { - {45, 1}, + {45, 1}, }; static arc arcs_15_1[3] = { - {46, 2}, - {29, 3}, - {0, 1}, + {46, 2}, + {29, 3}, + {0, 1}, }; static arc arcs_15_2[2] = { - {47, 4}, - {9, 4}, + {47, 4}, + {9, 4}, }; static arc arcs_15_3[2] = { - {47, 5}, - {45, 5}, + {47, 5}, + {45, 5}, }; static arc arcs_15_4[1] = { - {0, 4}, + {0, 4}, }; static arc arcs_15_5[2] = { - {29, 3}, - {0, 5}, + {29, 3}, + {0, 5}, }; static state states_15[6] = { - {1, arcs_15_0}, - {3, arcs_15_1}, - {2, arcs_15_2}, - {2, arcs_15_3}, - {1, arcs_15_4}, - {2, arcs_15_5}, + {1, arcs_15_0}, + {3, arcs_15_1}, + {2, arcs_15_2}, + {2, arcs_15_3}, + {1, arcs_15_4}, + {2, arcs_15_5}, }; static arc arcs_16_0[2] = { - {24, 1}, - {48, 1}, + {24, 1}, + {48, 1}, }; static arc arcs_16_1[2] = { - {30, 2}, - {0, 1}, + {30, 2}, + {0, 1}, }; static arc arcs_16_2[3] = { - {24, 1}, - {48, 1}, - {0, 2}, + {24, 1}, + {48, 1}, + {0, 2}, }; static state states_16[3] = { - {2, arcs_16_0}, - {2, arcs_16_1}, - {3, arcs_16_2}, + {2, arcs_16_0}, + {2, arcs_16_1}, + {3, arcs_16_2}, }; static arc arcs_17_0[12] = { - {49, 1}, - {50, 1}, - {51, 1}, - {52, 1}, - {53, 1}, - {54, 1}, - {55, 1}, - {56, 1}, - {57, 1}, - {58, 1}, - {59, 1}, - {60, 1}, + {49, 1}, + {50, 1}, + {51, 1}, + {52, 1}, + {53, 1}, + {54, 1}, + {55, 1}, + {56, 1}, + {57, 1}, + {58, 1}, + {59, 1}, + {60, 1}, }; static arc arcs_17_1[1] = { - {0, 1}, + {0, 1}, }; static state states_17[2] = { - {12, arcs_17_0}, - {1, arcs_17_1}, + {12, arcs_17_0}, + {1, arcs_17_1}, }; static arc arcs_18_0[1] = { - {61, 1}, + {61, 1}, }; static arc arcs_18_1[1] = { - {62, 2}, + {62, 2}, }; static arc arcs_18_2[1] = { - {0, 2}, + {0, 2}, }; static state states_18[3] = { - {1, arcs_18_0}, - {1, arcs_18_1}, - {1, arcs_18_2}, + {1, arcs_18_0}, + {1, arcs_18_1}, + {1, arcs_18_2}, }; static arc arcs_19_0[1] = { - {63, 1}, + {63, 1}, }; static arc arcs_19_1[1] = { - {0, 1}, + {0, 1}, }; static state states_19[2] = { - {1, arcs_19_0}, - {1, arcs_19_1}, + {1, arcs_19_0}, + {1, arcs_19_1}, }; static arc arcs_20_0[5] = { - {64, 1}, - {65, 1}, - {66, 1}, - {67, 1}, - {68, 1}, + {64, 1}, + {65, 1}, + {66, 1}, + {67, 1}, + {68, 1}, }; static arc arcs_20_1[1] = { - {0, 1}, + {0, 1}, }; static state states_20[2] = { - {5, arcs_20_0}, - {1, arcs_20_1}, + {5, arcs_20_0}, + {1, arcs_20_1}, }; static arc arcs_21_0[1] = { - {69, 1}, + {69, 1}, }; static arc arcs_21_1[1] = { - {0, 1}, + {0, 1}, }; static state states_21[2] = { - {1, arcs_21_0}, - {1, arcs_21_1}, + {1, arcs_21_0}, + {1, arcs_21_1}, }; static arc arcs_22_0[1] = { - {70, 1}, + {70, 1}, }; static arc arcs_22_1[1] = { - {0, 1}, + {0, 1}, }; static state states_22[2] = { - {1, arcs_22_0}, - {1, arcs_22_1}, + {1, arcs_22_0}, + {1, arcs_22_1}, }; static arc arcs_23_0[1] = { - {71, 1}, + {71, 1}, }; static arc arcs_23_1[2] = { - {9, 2}, - {0, 1}, + {9, 2}, + {0, 1}, }; static arc arcs_23_2[1] = { - {0, 2}, + {0, 2}, }; static state states_23[3] = { - {1, arcs_23_0}, - {2, arcs_23_1}, - {1, arcs_23_2}, + {1, arcs_23_0}, + {2, arcs_23_1}, + {1, arcs_23_2}, }; static arc arcs_24_0[1] = { - {47, 1}, + {47, 1}, }; static arc arcs_24_1[1] = { - {0, 1}, + {0, 1}, }; static state states_24[2] = { - {1, arcs_24_0}, - {1, arcs_24_1}, + {1, arcs_24_0}, + {1, arcs_24_1}, }; static arc arcs_25_0[1] = { - {72, 1}, + {72, 1}, }; static arc arcs_25_1[2] = { - {24, 2}, - {0, 1}, + {24, 2}, + {0, 1}, }; static arc arcs_25_2[2] = { - {73, 3}, - {0, 2}, + {73, 3}, + {0, 2}, }; static arc arcs_25_3[1] = { - {24, 4}, + {24, 4}, }; static arc arcs_25_4[1] = { - {0, 4}, + {0, 4}, }; static state states_25[5] = { - {1, arcs_25_0}, - {2, arcs_25_1}, - {2, arcs_25_2}, - {1, arcs_25_3}, - {1, arcs_25_4}, + {1, arcs_25_0}, + {2, arcs_25_1}, + {2, arcs_25_2}, + {1, arcs_25_3}, + {1, arcs_25_4}, }; static arc arcs_26_0[2] = { - {74, 1}, - {75, 1}, + {74, 1}, + {75, 1}, }; static arc arcs_26_1[1] = { - {0, 1}, + {0, 1}, }; static state states_26[2] = { - {2, arcs_26_0}, - {1, arcs_26_1}, + {2, arcs_26_0}, + {1, arcs_26_1}, }; static arc arcs_27_0[1] = { - {76, 1}, + {76, 1}, }; static arc arcs_27_1[1] = { - {77, 2}, + {77, 2}, }; static arc arcs_27_2[1] = { - {0, 2}, + {0, 2}, }; static state states_27[3] = { - {1, arcs_27_0}, - {1, arcs_27_1}, - {1, arcs_27_2}, + {1, arcs_27_0}, + {1, arcs_27_1}, + {1, arcs_27_2}, }; static arc arcs_28_0[1] = { - {73, 1}, + {73, 1}, }; static arc arcs_28_1[3] = { - {78, 2}, - {79, 2}, - {12, 3}, + {78, 2}, + {79, 2}, + {12, 3}, }; static arc arcs_28_2[4] = { - {78, 2}, - {79, 2}, - {12, 3}, - {76, 4}, + {78, 2}, + {79, 2}, + {12, 3}, + {76, 4}, }; static arc arcs_28_3[1] = { - {76, 4}, + {76, 4}, }; static arc arcs_28_4[3] = { - {31, 5}, - {13, 6}, - {80, 5}, + {31, 5}, + {13, 6}, + {80, 5}, }; static arc arcs_28_5[1] = { - {0, 5}, + {0, 5}, }; static arc arcs_28_6[1] = { - {80, 7}, + {80, 7}, }; static arc arcs_28_7[1] = { - {15, 5}, + {15, 5}, }; static state states_28[8] = { - {1, arcs_28_0}, - {3, arcs_28_1}, - {4, arcs_28_2}, - {1, arcs_28_3}, - {3, arcs_28_4}, - {1, arcs_28_5}, - {1, arcs_28_6}, - {1, arcs_28_7}, + {1, arcs_28_0}, + {3, arcs_28_1}, + {4, arcs_28_2}, + {1, arcs_28_3}, + {3, arcs_28_4}, + {1, arcs_28_5}, + {1, arcs_28_6}, + {1, arcs_28_7}, }; static arc arcs_29_0[1] = { - {21, 1}, + {21, 1}, }; static arc arcs_29_1[2] = { - {82, 2}, - {0, 1}, + {82, 2}, + {0, 1}, }; static arc arcs_29_2[1] = { - {21, 3}, + {21, 3}, }; static arc arcs_29_3[1] = { - {0, 3}, + {0, 3}, }; static state states_29[4] = { - {1, arcs_29_0}, - {2, arcs_29_1}, - {1, arcs_29_2}, - {1, arcs_29_3}, + {1, arcs_29_0}, + {2, arcs_29_1}, + {1, arcs_29_2}, + {1, arcs_29_3}, }; static arc arcs_30_0[1] = { - {12, 1}, + {12, 1}, }; static arc arcs_30_1[2] = { - {82, 2}, - {0, 1}, + {82, 2}, + {0, 1}, }; static arc arcs_30_2[1] = { - {21, 3}, + {21, 3}, }; static arc arcs_30_3[1] = { - {0, 3}, + {0, 3}, }; static state states_30[4] = { - {1, arcs_30_0}, - {2, arcs_30_1}, - {1, arcs_30_2}, - {1, arcs_30_3}, + {1, arcs_30_0}, + {2, arcs_30_1}, + {1, arcs_30_2}, + {1, arcs_30_3}, }; static arc arcs_31_0[1] = { - {81, 1}, + {81, 1}, }; static arc arcs_31_1[2] = { - {30, 2}, - {0, 1}, + {30, 2}, + {0, 1}, }; static arc arcs_31_2[2] = { - {81, 1}, - {0, 2}, + {81, 1}, + {0, 2}, }; static state states_31[3] = { - {1, arcs_31_0}, - {2, arcs_31_1}, - {2, arcs_31_2}, + {1, arcs_31_0}, + {2, arcs_31_1}, + {2, arcs_31_2}, }; static arc arcs_32_0[1] = { - {83, 1}, + {83, 1}, }; static arc arcs_32_1[2] = { - {30, 0}, - {0, 1}, + {30, 0}, + {0, 1}, }; static state states_32[2] = { - {1, arcs_32_0}, - {2, arcs_32_1}, + {1, arcs_32_0}, + {2, arcs_32_1}, }; static arc arcs_33_0[1] = { - {21, 1}, + {21, 1}, }; static arc arcs_33_1[2] = { - {78, 0}, - {0, 1}, + {78, 0}, + {0, 1}, }; static state states_33[2] = { - {1, arcs_33_0}, - {2, arcs_33_1}, + {1, arcs_33_0}, + {2, arcs_33_1}, }; static arc arcs_34_0[1] = { - {84, 1}, + {84, 1}, }; static arc arcs_34_1[1] = { - {21, 2}, + {21, 2}, }; static arc arcs_34_2[2] = { - {30, 1}, - {0, 2}, + {30, 1}, + {0, 2}, }; static state states_34[3] = { - {1, arcs_34_0}, - {1, arcs_34_1}, - {2, arcs_34_2}, + {1, arcs_34_0}, + {1, arcs_34_1}, + {2, arcs_34_2}, }; static arc arcs_35_0[1] = { - {85, 1}, + {85, 1}, }; static arc arcs_35_1[1] = { - {21, 2}, + {21, 2}, }; static arc arcs_35_2[2] = { - {30, 1}, - {0, 2}, + {30, 1}, + {0, 2}, }; static state states_35[3] = { - {1, arcs_35_0}, - {1, arcs_35_1}, - {2, arcs_35_2}, + {1, arcs_35_0}, + {1, arcs_35_1}, + {2, arcs_35_2}, }; static arc arcs_36_0[1] = { - {86, 1}, + {86, 1}, }; static arc arcs_36_1[1] = { - {24, 2}, + {24, 2}, }; static arc arcs_36_2[2] = { - {30, 3}, - {0, 2}, + {30, 3}, + {0, 2}, }; static arc arcs_36_3[1] = { - {24, 4}, + {24, 4}, }; static arc arcs_36_4[1] = { - {0, 4}, + {0, 4}, }; static state states_36[5] = { - {1, arcs_36_0}, - {1, arcs_36_1}, - {2, arcs_36_2}, - {1, arcs_36_3}, - {1, arcs_36_4}, + {1, arcs_36_0}, + {1, arcs_36_1}, + {2, arcs_36_2}, + {1, arcs_36_3}, + {1, arcs_36_4}, }; static arc arcs_37_0[8] = { - {87, 1}, - {88, 1}, - {89, 1}, - {90, 1}, - {91, 1}, - {19, 1}, - {18, 1}, - {17, 1}, + {87, 1}, + {88, 1}, + {89, 1}, + {90, 1}, + {91, 1}, + {19, 1}, + {18, 1}, + {17, 1}, }; static arc arcs_37_1[1] = { - {0, 1}, + {0, 1}, }; static state states_37[2] = { - {8, arcs_37_0}, - {1, arcs_37_1}, + {8, arcs_37_0}, + {1, arcs_37_1}, }; static arc arcs_38_0[1] = { - {92, 1}, + {92, 1}, }; static arc arcs_38_1[1] = { - {24, 2}, + {24, 2}, }; static arc arcs_38_2[1] = { - {25, 3}, + {25, 3}, }; static arc arcs_38_3[1] = { - {26, 4}, + {26, 4}, }; static arc arcs_38_4[3] = { - {93, 1}, - {94, 5}, - {0, 4}, + {93, 1}, + {94, 5}, + {0, 4}, }; static arc arcs_38_5[1] = { - {25, 6}, + {25, 6}, }; static arc arcs_38_6[1] = { - {26, 7}, + {26, 7}, }; static arc arcs_38_7[1] = { - {0, 7}, + {0, 7}, }; static state states_38[8] = { - {1, arcs_38_0}, - {1, arcs_38_1}, - {1, arcs_38_2}, - {1, arcs_38_3}, - {3, arcs_38_4}, - {1, arcs_38_5}, - {1, arcs_38_6}, - {1, arcs_38_7}, + {1, arcs_38_0}, + {1, arcs_38_1}, + {1, arcs_38_2}, + {1, arcs_38_3}, + {3, arcs_38_4}, + {1, arcs_38_5}, + {1, arcs_38_6}, + {1, arcs_38_7}, }; static arc arcs_39_0[1] = { - {95, 1}, + {95, 1}, }; static arc arcs_39_1[1] = { - {24, 2}, + {24, 2}, }; static arc arcs_39_2[1] = { - {25, 3}, + {25, 3}, }; static arc arcs_39_3[1] = { - {26, 4}, + {26, 4}, }; static arc arcs_39_4[2] = { - {94, 5}, - {0, 4}, + {94, 5}, + {0, 4}, }; static arc arcs_39_5[1] = { - {25, 6}, + {25, 6}, }; static arc arcs_39_6[1] = { - {26, 7}, + {26, 7}, }; static arc arcs_39_7[1] = { - {0, 7}, + {0, 7}, }; static state states_39[8] = { - {1, arcs_39_0}, - {1, arcs_39_1}, - {1, arcs_39_2}, - {1, arcs_39_3}, - {2, arcs_39_4}, - {1, arcs_39_5}, - {1, arcs_39_6}, - {1, arcs_39_7}, + {1, arcs_39_0}, + {1, arcs_39_1}, + {1, arcs_39_2}, + {1, arcs_39_3}, + {2, arcs_39_4}, + {1, arcs_39_5}, + {1, arcs_39_6}, + {1, arcs_39_7}, }; static arc arcs_40_0[1] = { - {96, 1}, + {96, 1}, }; static arc arcs_40_1[1] = { - {62, 2}, + {62, 2}, }; static arc arcs_40_2[1] = { - {97, 3}, + {97, 3}, }; static arc arcs_40_3[1] = { - {9, 4}, + {9, 4}, }; static arc arcs_40_4[1] = { - {25, 5}, + {25, 5}, }; static arc arcs_40_5[1] = { - {26, 6}, + {26, 6}, }; static arc arcs_40_6[2] = { - {94, 7}, - {0, 6}, + {94, 7}, + {0, 6}, }; static arc arcs_40_7[1] = { - {25, 8}, + {25, 8}, }; static arc arcs_40_8[1] = { - {26, 9}, + {26, 9}, }; static arc arcs_40_9[1] = { - {0, 9}, + {0, 9}, }; static state states_40[10] = { - {1, arcs_40_0}, - {1, arcs_40_1}, - {1, arcs_40_2}, - {1, arcs_40_3}, - {1, arcs_40_4}, - {1, arcs_40_5}, - {2, arcs_40_6}, - {1, arcs_40_7}, - {1, arcs_40_8}, - {1, arcs_40_9}, + {1, arcs_40_0}, + {1, arcs_40_1}, + {1, arcs_40_2}, + {1, arcs_40_3}, + {1, arcs_40_4}, + {1, arcs_40_5}, + {2, arcs_40_6}, + {1, arcs_40_7}, + {1, arcs_40_8}, + {1, arcs_40_9}, }; static arc arcs_41_0[1] = { - {98, 1}, + {98, 1}, }; static arc arcs_41_1[1] = { - {25, 2}, + {25, 2}, }; static arc arcs_41_2[1] = { - {26, 3}, + {26, 3}, }; static arc arcs_41_3[2] = { - {99, 4}, - {100, 5}, + {99, 4}, + {100, 5}, }; static arc arcs_41_4[1] = { - {25, 6}, + {25, 6}, }; static arc arcs_41_5[1] = { - {25, 7}, + {25, 7}, }; static arc arcs_41_6[1] = { - {26, 8}, + {26, 8}, }; static arc arcs_41_7[1] = { - {26, 9}, + {26, 9}, }; static arc arcs_41_8[4] = { - {99, 4}, - {94, 10}, - {100, 5}, - {0, 8}, + {99, 4}, + {94, 10}, + {100, 5}, + {0, 8}, }; static arc arcs_41_9[1] = { - {0, 9}, + {0, 9}, }; static arc arcs_41_10[1] = { - {25, 11}, + {25, 11}, }; static arc arcs_41_11[1] = { - {26, 12}, + {26, 12}, }; static arc arcs_41_12[2] = { - {100, 5}, - {0, 12}, + {100, 5}, + {0, 12}, }; static state states_41[13] = { - {1, arcs_41_0}, - {1, arcs_41_1}, - {1, arcs_41_2}, - {2, arcs_41_3}, - {1, arcs_41_4}, - {1, arcs_41_5}, - {1, arcs_41_6}, - {1, arcs_41_7}, - {4, arcs_41_8}, - {1, arcs_41_9}, - {1, arcs_41_10}, - {1, arcs_41_11}, - {2, arcs_41_12}, + {1, arcs_41_0}, + {1, arcs_41_1}, + {1, arcs_41_2}, + {2, arcs_41_3}, + {1, arcs_41_4}, + {1, arcs_41_5}, + {1, arcs_41_6}, + {1, arcs_41_7}, + {4, arcs_41_8}, + {1, arcs_41_9}, + {1, arcs_41_10}, + {1, arcs_41_11}, + {2, arcs_41_12}, }; static arc arcs_42_0[1] = { - {101, 1}, + {101, 1}, }; static arc arcs_42_1[1] = { - {102, 2}, + {102, 2}, }; static arc arcs_42_2[2] = { - {30, 1}, - {25, 3}, + {30, 1}, + {25, 3}, }; static arc arcs_42_3[1] = { - {26, 4}, + {26, 4}, }; static arc arcs_42_4[1] = { - {0, 4}, + {0, 4}, }; static state states_42[5] = { - {1, arcs_42_0}, - {1, arcs_42_1}, - {2, arcs_42_2}, - {1, arcs_42_3}, - {1, arcs_42_4}, + {1, arcs_42_0}, + {1, arcs_42_1}, + {2, arcs_42_2}, + {1, arcs_42_3}, + {1, arcs_42_4}, }; static arc arcs_43_0[1] = { - {24, 1}, + {24, 1}, }; static arc arcs_43_1[2] = { - {82, 2}, - {0, 1}, + {82, 2}, + {0, 1}, }; static arc arcs_43_2[1] = { - {103, 3}, + {103, 3}, }; static arc arcs_43_3[1] = { - {0, 3}, + {0, 3}, }; static state states_43[4] = { - {1, arcs_43_0}, - {2, arcs_43_1}, - {1, arcs_43_2}, - {1, arcs_43_3}, + {1, arcs_43_0}, + {2, arcs_43_1}, + {1, arcs_43_2}, + {1, arcs_43_3}, }; static arc arcs_44_0[1] = { - {104, 1}, + {104, 1}, }; static arc arcs_44_1[2] = { - {24, 2}, - {0, 1}, + {24, 2}, + {0, 1}, }; static arc arcs_44_2[2] = { - {82, 3}, - {0, 2}, + {82, 3}, + {0, 2}, }; static arc arcs_44_3[1] = { - {21, 4}, + {21, 4}, }; static arc arcs_44_4[1] = { - {0, 4}, + {0, 4}, }; static state states_44[5] = { - {1, arcs_44_0}, - {2, arcs_44_1}, - {2, arcs_44_2}, - {1, arcs_44_3}, - {1, arcs_44_4}, + {1, arcs_44_0}, + {2, arcs_44_1}, + {2, arcs_44_2}, + {1, arcs_44_3}, + {1, arcs_44_4}, }; static arc arcs_45_0[2] = { - {3, 1}, - {2, 2}, + {3, 1}, + {2, 2}, }; static arc arcs_45_1[1] = { - {0, 1}, + {0, 1}, }; static arc arcs_45_2[1] = { - {105, 3}, + {105, 3}, }; static arc arcs_45_3[1] = { - {6, 4}, + {6, 4}, }; static arc arcs_45_4[2] = { - {6, 4}, - {106, 1}, + {6, 4}, + {106, 1}, }; static state states_45[5] = { - {2, arcs_45_0}, - {1, arcs_45_1}, - {1, arcs_45_2}, - {1, arcs_45_3}, - {2, arcs_45_4}, + {2, arcs_45_0}, + {1, arcs_45_1}, + {1, arcs_45_2}, + {1, arcs_45_3}, + {2, arcs_45_4}, }; static arc arcs_46_0[2] = { - {107, 1}, - {108, 2}, + {107, 1}, + {108, 2}, }; static arc arcs_46_1[2] = { - {92, 3}, - {0, 1}, + {92, 3}, + {0, 1}, }; static arc arcs_46_2[1] = { - {0, 2}, + {0, 2}, }; static arc arcs_46_3[1] = { - {107, 4}, + {107, 4}, }; static arc arcs_46_4[1] = { - {94, 5}, + {94, 5}, }; static arc arcs_46_5[1] = { - {24, 2}, + {24, 2}, }; static state states_46[6] = { - {2, arcs_46_0}, - {2, arcs_46_1}, - {1, arcs_46_2}, - {1, arcs_46_3}, - {1, arcs_46_4}, - {1, arcs_46_5}, + {2, arcs_46_0}, + {2, arcs_46_1}, + {1, arcs_46_2}, + {1, arcs_46_3}, + {1, arcs_46_4}, + {1, arcs_46_5}, }; static arc arcs_47_0[2] = { - {107, 1}, - {110, 1}, + {107, 1}, + {110, 1}, }; static arc arcs_47_1[1] = { - {0, 1}, + {0, 1}, }; static state states_47[2] = { - {2, arcs_47_0}, - {1, arcs_47_1}, + {2, arcs_47_0}, + {1, arcs_47_1}, }; static arc arcs_48_0[1] = { - {111, 1}, + {111, 1}, }; static arc arcs_48_1[2] = { - {33, 2}, - {25, 3}, + {33, 2}, + {25, 3}, }; static arc arcs_48_2[1] = { - {25, 3}, + {25, 3}, }; static arc arcs_48_3[1] = { - {24, 4}, + {24, 4}, }; static arc arcs_48_4[1] = { - {0, 4}, + {0, 4}, }; static state states_48[5] = { - {1, arcs_48_0}, - {2, arcs_48_1}, - {1, arcs_48_2}, - {1, arcs_48_3}, - {1, arcs_48_4}, + {1, arcs_48_0}, + {2, arcs_48_1}, + {1, arcs_48_2}, + {1, arcs_48_3}, + {1, arcs_48_4}, }; static arc arcs_49_0[1] = { - {111, 1}, + {111, 1}, }; static arc arcs_49_1[2] = { - {33, 2}, - {25, 3}, + {33, 2}, + {25, 3}, }; static arc arcs_49_2[1] = { - {25, 3}, + {25, 3}, }; static arc arcs_49_3[1] = { - {109, 4}, + {109, 4}, }; static arc arcs_49_4[1] = { - {0, 4}, + {0, 4}, }; static state states_49[5] = { - {1, arcs_49_0}, - {2, arcs_49_1}, - {1, arcs_49_2}, - {1, arcs_49_3}, - {1, arcs_49_4}, + {1, arcs_49_0}, + {2, arcs_49_1}, + {1, arcs_49_2}, + {1, arcs_49_3}, + {1, arcs_49_4}, }; static arc arcs_50_0[1] = { - {112, 1}, + {112, 1}, }; static arc arcs_50_1[2] = { - {113, 0}, - {0, 1}, + {113, 0}, + {0, 1}, }; static state states_50[2] = { - {1, arcs_50_0}, - {2, arcs_50_1}, + {1, arcs_50_0}, + {2, arcs_50_1}, }; static arc arcs_51_0[1] = { - {114, 1}, + {114, 1}, }; static arc arcs_51_1[2] = { - {115, 0}, - {0, 1}, + {115, 0}, + {0, 1}, }; static state states_51[2] = { - {1, arcs_51_0}, - {2, arcs_51_1}, + {1, arcs_51_0}, + {2, arcs_51_1}, }; static arc arcs_52_0[2] = { - {116, 1}, - {117, 2}, + {116, 1}, + {117, 2}, }; static arc arcs_52_1[1] = { - {114, 2}, + {114, 2}, }; static arc arcs_52_2[1] = { - {0, 2}, + {0, 2}, }; static state states_52[3] = { - {2, arcs_52_0}, - {1, arcs_52_1}, - {1, arcs_52_2}, + {2, arcs_52_0}, + {1, arcs_52_1}, + {1, arcs_52_2}, }; static arc arcs_53_0[1] = { - {103, 1}, + {103, 1}, }; static arc arcs_53_1[2] = { - {118, 0}, - {0, 1}, + {118, 0}, + {0, 1}, }; static state states_53[2] = { - {1, arcs_53_0}, - {2, arcs_53_1}, + {1, arcs_53_0}, + {2, arcs_53_1}, }; static arc arcs_54_0[10] = { - {119, 1}, - {120, 1}, - {121, 1}, - {122, 1}, - {123, 1}, - {124, 1}, - {125, 1}, - {97, 1}, - {116, 2}, - {126, 3}, + {119, 1}, + {120, 1}, + {121, 1}, + {122, 1}, + {123, 1}, + {124, 1}, + {125, 1}, + {97, 1}, + {116, 2}, + {126, 3}, }; static arc arcs_54_1[1] = { - {0, 1}, + {0, 1}, }; static arc arcs_54_2[1] = { - {97, 1}, + {97, 1}, }; static arc arcs_54_3[2] = { - {116, 1}, - {0, 3}, + {116, 1}, + {0, 3}, }; static state states_54[4] = { - {10, arcs_54_0}, - {1, arcs_54_1}, - {1, arcs_54_2}, - {2, arcs_54_3}, + {10, arcs_54_0}, + {1, arcs_54_1}, + {1, arcs_54_2}, + {2, arcs_54_3}, }; static arc arcs_55_0[1] = { - {31, 1}, + {31, 1}, }; static arc arcs_55_1[1] = { - {103, 2}, + {103, 2}, }; static arc arcs_55_2[1] = { - {0, 2}, + {0, 2}, }; static state states_55[3] = { - {1, arcs_55_0}, - {1, arcs_55_1}, - {1, arcs_55_2}, + {1, arcs_55_0}, + {1, arcs_55_1}, + {1, arcs_55_2}, }; static arc arcs_56_0[1] = { - {127, 1}, + {127, 1}, }; static arc arcs_56_1[2] = { - {128, 0}, - {0, 1}, + {128, 0}, + {0, 1}, }; static state states_56[2] = { - {1, arcs_56_0}, - {2, arcs_56_1}, + {1, arcs_56_0}, + {2, arcs_56_1}, }; static arc arcs_57_0[1] = { - {129, 1}, + {129, 1}, }; static arc arcs_57_1[2] = { - {130, 0}, - {0, 1}, + {130, 0}, + {0, 1}, }; static state states_57[2] = { - {1, arcs_57_0}, - {2, arcs_57_1}, + {1, arcs_57_0}, + {2, arcs_57_1}, }; static arc arcs_58_0[1] = { - {131, 1}, + {131, 1}, }; static arc arcs_58_1[2] = { - {132, 0}, - {0, 1}, + {132, 0}, + {0, 1}, }; static state states_58[2] = { - {1, arcs_58_0}, - {2, arcs_58_1}, + {1, arcs_58_0}, + {2, arcs_58_1}, }; static arc arcs_59_0[1] = { - {133, 1}, + {133, 1}, }; static arc arcs_59_1[3] = { - {134, 0}, - {135, 0}, - {0, 1}, + {134, 0}, + {135, 0}, + {0, 1}, }; static state states_59[2] = { - {1, arcs_59_0}, - {3, arcs_59_1}, + {1, arcs_59_0}, + {3, arcs_59_1}, }; static arc arcs_60_0[1] = { - {136, 1}, + {136, 1}, }; static arc arcs_60_1[3] = { - {137, 0}, - {138, 0}, - {0, 1}, + {137, 0}, + {138, 0}, + {0, 1}, }; static state states_60[2] = { - {1, arcs_60_0}, - {3, arcs_60_1}, + {1, arcs_60_0}, + {3, arcs_60_1}, }; static arc arcs_61_0[1] = { - {139, 1}, + {139, 1}, }; static arc arcs_61_1[5] = { - {31, 0}, - {140, 0}, - {141, 0}, - {142, 0}, - {0, 1}, + {31, 0}, + {140, 0}, + {141, 0}, + {142, 0}, + {0, 1}, }; static state states_61[2] = { - {1, arcs_61_0}, - {5, arcs_61_1}, + {1, arcs_61_0}, + {5, arcs_61_1}, }; static arc arcs_62_0[4] = { - {137, 1}, - {138, 1}, - {143, 1}, - {144, 2}, + {137, 1}, + {138, 1}, + {143, 1}, + {144, 2}, }; static arc arcs_62_1[1] = { - {139, 2}, + {139, 2}, }; static arc arcs_62_2[1] = { - {0, 2}, + {0, 2}, }; static state states_62[3] = { - {4, arcs_62_0}, - {1, arcs_62_1}, - {1, arcs_62_2}, + {4, arcs_62_0}, + {1, arcs_62_1}, + {1, arcs_62_2}, }; static arc arcs_63_0[1] = { - {145, 1}, + {145, 1}, }; static arc arcs_63_1[3] = { - {146, 1}, - {32, 2}, - {0, 1}, + {146, 1}, + {32, 2}, + {0, 1}, }; static arc arcs_63_2[1] = { - {139, 3}, + {139, 3}, }; static arc arcs_63_3[1] = { - {0, 3}, + {0, 3}, }; static state states_63[4] = { - {1, arcs_63_0}, - {3, arcs_63_1}, - {1, arcs_63_2}, - {1, arcs_63_3}, + {1, arcs_63_0}, + {3, arcs_63_1}, + {1, arcs_63_2}, + {1, arcs_63_3}, }; static arc arcs_64_0[10] = { - {13, 1}, - {148, 2}, - {150, 3}, - {21, 4}, - {153, 4}, - {154, 5}, - {79, 4}, - {155, 4}, - {156, 4}, - {157, 4}, + {13, 1}, + {148, 2}, + {150, 3}, + {21, 4}, + {153, 4}, + {154, 5}, + {79, 4}, + {155, 4}, + {156, 4}, + {157, 4}, }; static arc arcs_64_1[3] = { - {47, 6}, - {147, 6}, - {15, 4}, + {47, 6}, + {147, 6}, + {15, 4}, }; static arc arcs_64_2[2] = { - {147, 7}, - {149, 4}, + {147, 7}, + {149, 4}, }; static arc arcs_64_3[2] = { - {151, 8}, - {152, 4}, + {151, 8}, + {152, 4}, }; static arc arcs_64_4[1] = { - {0, 4}, + {0, 4}, }; static arc arcs_64_5[2] = { - {154, 5}, - {0, 5}, + {154, 5}, + {0, 5}, }; static arc arcs_64_6[1] = { - {15, 4}, + {15, 4}, }; static arc arcs_64_7[1] = { - {149, 4}, + {149, 4}, }; static arc arcs_64_8[1] = { - {152, 4}, + {152, 4}, }; static state states_64[9] = { - {10, arcs_64_0}, - {3, arcs_64_1}, - {2, arcs_64_2}, - {2, arcs_64_3}, - {1, arcs_64_4}, - {2, arcs_64_5}, - {1, arcs_64_6}, - {1, arcs_64_7}, - {1, arcs_64_8}, + {10, arcs_64_0}, + {3, arcs_64_1}, + {2, arcs_64_2}, + {2, arcs_64_3}, + {1, arcs_64_4}, + {2, arcs_64_5}, + {1, arcs_64_6}, + {1, arcs_64_7}, + {1, arcs_64_8}, }; static arc arcs_65_0[2] = { - {24, 1}, - {48, 1}, + {24, 1}, + {48, 1}, }; static arc arcs_65_1[3] = { - {158, 2}, - {30, 3}, - {0, 1}, + {158, 2}, + {30, 3}, + {0, 1}, }; static arc arcs_65_2[1] = { - {0, 2}, + {0, 2}, }; static arc arcs_65_3[3] = { - {24, 4}, - {48, 4}, - {0, 3}, + {24, 4}, + {48, 4}, + {0, 3}, }; static arc arcs_65_4[2] = { - {30, 3}, - {0, 4}, + {30, 3}, + {0, 4}, }; static state states_65[5] = { - {2, arcs_65_0}, - {3, arcs_65_1}, - {1, arcs_65_2}, - {3, arcs_65_3}, - {2, arcs_65_4}, + {2, arcs_65_0}, + {3, arcs_65_1}, + {1, arcs_65_2}, + {3, arcs_65_3}, + {2, arcs_65_4}, }; static arc arcs_66_0[3] = { - {13, 1}, - {148, 2}, - {78, 3}, + {13, 1}, + {148, 2}, + {78, 3}, }; static arc arcs_66_1[2] = { - {14, 4}, - {15, 5}, + {14, 4}, + {15, 5}, }; static arc arcs_66_2[1] = { - {159, 6}, + {159, 6}, }; static arc arcs_66_3[1] = { - {21, 5}, + {21, 5}, }; static arc arcs_66_4[1] = { - {15, 5}, + {15, 5}, }; static arc arcs_66_5[1] = { - {0, 5}, + {0, 5}, }; static arc arcs_66_6[1] = { - {149, 5}, + {149, 5}, }; static state states_66[7] = { - {3, arcs_66_0}, - {2, arcs_66_1}, - {1, arcs_66_2}, - {1, arcs_66_3}, - {1, arcs_66_4}, - {1, arcs_66_5}, - {1, arcs_66_6}, + {3, arcs_66_0}, + {2, arcs_66_1}, + {1, arcs_66_2}, + {1, arcs_66_3}, + {1, arcs_66_4}, + {1, arcs_66_5}, + {1, arcs_66_6}, }; static arc arcs_67_0[1] = { - {160, 1}, + {160, 1}, }; static arc arcs_67_1[2] = { - {30, 2}, - {0, 1}, + {30, 2}, + {0, 1}, }; static arc arcs_67_2[2] = { - {160, 1}, - {0, 2}, + {160, 1}, + {0, 2}, }; static state states_67[3] = { - {1, arcs_67_0}, - {2, arcs_67_1}, - {2, arcs_67_2}, + {1, arcs_67_0}, + {2, arcs_67_1}, + {2, arcs_67_2}, }; static arc arcs_68_0[2] = { - {24, 1}, - {25, 2}, + {24, 1}, + {25, 2}, }; static arc arcs_68_1[2] = { - {25, 2}, - {0, 1}, + {25, 2}, + {0, 1}, }; static arc arcs_68_2[3] = { - {24, 3}, - {161, 4}, - {0, 2}, + {24, 3}, + {161, 4}, + {0, 2}, }; static arc arcs_68_3[2] = { - {161, 4}, - {0, 3}, + {161, 4}, + {0, 3}, }; static arc arcs_68_4[1] = { - {0, 4}, + {0, 4}, }; static state states_68[5] = { - {2, arcs_68_0}, - {2, arcs_68_1}, - {3, arcs_68_2}, - {2, arcs_68_3}, - {1, arcs_68_4}, + {2, arcs_68_0}, + {2, arcs_68_1}, + {3, arcs_68_2}, + {2, arcs_68_3}, + {1, arcs_68_4}, }; static arc arcs_69_0[1] = { - {25, 1}, + {25, 1}, }; static arc arcs_69_1[2] = { - {24, 2}, - {0, 1}, + {24, 2}, + {0, 1}, }; static arc arcs_69_2[1] = { - {0, 2}, + {0, 2}, }; static state states_69[3] = { - {1, arcs_69_0}, - {2, arcs_69_1}, - {1, arcs_69_2}, + {1, arcs_69_0}, + {2, arcs_69_1}, + {1, arcs_69_2}, }; static arc arcs_70_0[2] = { - {103, 1}, - {48, 1}, + {103, 1}, + {48, 1}, }; static arc arcs_70_1[2] = { - {30, 2}, - {0, 1}, + {30, 2}, + {0, 1}, }; static arc arcs_70_2[3] = { - {103, 1}, - {48, 1}, - {0, 2}, + {103, 1}, + {48, 1}, + {0, 2}, }; static state states_70[3] = { - {2, arcs_70_0}, - {2, arcs_70_1}, - {3, arcs_70_2}, + {2, arcs_70_0}, + {2, arcs_70_1}, + {3, arcs_70_2}, }; static arc arcs_71_0[1] = { - {24, 1}, + {24, 1}, }; static arc arcs_71_1[2] = { - {30, 2}, - {0, 1}, + {30, 2}, + {0, 1}, }; static arc arcs_71_2[2] = { - {24, 1}, - {0, 2}, + {24, 1}, + {0, 2}, }; static state states_71[3] = { - {1, arcs_71_0}, - {2, arcs_71_1}, - {2, arcs_71_2}, + {1, arcs_71_0}, + {2, arcs_71_1}, + {2, arcs_71_2}, }; static arc arcs_72_0[1] = { - {24, 1}, + {24, 1}, }; static arc arcs_72_1[4] = { - {25, 2}, - {158, 3}, - {30, 4}, - {0, 1}, + {25, 2}, + {158, 3}, + {30, 4}, + {0, 1}, }; static arc arcs_72_2[1] = { - {24, 5}, + {24, 5}, }; static arc arcs_72_3[1] = { - {0, 3}, + {0, 3}, }; static arc arcs_72_4[2] = { - {24, 6}, - {0, 4}, + {24, 6}, + {0, 4}, }; static arc arcs_72_5[3] = { - {158, 3}, - {30, 7}, - {0, 5}, + {158, 3}, + {30, 7}, + {0, 5}, }; static arc arcs_72_6[2] = { - {30, 4}, - {0, 6}, + {30, 4}, + {0, 6}, }; static arc arcs_72_7[2] = { - {24, 8}, - {0, 7}, + {24, 8}, + {0, 7}, }; static arc arcs_72_8[1] = { - {25, 9}, + {25, 9}, }; static arc arcs_72_9[1] = { - {24, 10}, + {24, 10}, }; static arc arcs_72_10[2] = { - {30, 7}, - {0, 10}, + {30, 7}, + {0, 10}, }; static state states_72[11] = { - {1, arcs_72_0}, - {4, arcs_72_1}, - {1, arcs_72_2}, - {1, arcs_72_3}, - {2, arcs_72_4}, - {3, arcs_72_5}, - {2, arcs_72_6}, - {2, arcs_72_7}, - {1, arcs_72_8}, - {1, arcs_72_9}, - {2, arcs_72_10}, + {1, arcs_72_0}, + {4, arcs_72_1}, + {1, arcs_72_2}, + {1, arcs_72_3}, + {2, arcs_72_4}, + {3, arcs_72_5}, + {2, arcs_72_6}, + {2, arcs_72_7}, + {1, arcs_72_8}, + {1, arcs_72_9}, + {2, arcs_72_10}, }; static arc arcs_73_0[1] = { - {162, 1}, + {162, 1}, }; static arc arcs_73_1[1] = { - {21, 2}, + {21, 2}, }; static arc arcs_73_2[2] = { - {13, 3}, - {25, 4}, + {13, 3}, + {25, 4}, }; static arc arcs_73_3[2] = { - {14, 5}, - {15, 6}, + {14, 5}, + {15, 6}, }; static arc arcs_73_4[1] = { - {26, 7}, + {26, 7}, }; static arc arcs_73_5[1] = { - {15, 6}, + {15, 6}, }; static arc arcs_73_6[1] = { - {25, 4}, + {25, 4}, }; static arc arcs_73_7[1] = { - {0, 7}, + {0, 7}, }; static state states_73[8] = { - {1, arcs_73_0}, - {1, arcs_73_1}, - {2, arcs_73_2}, - {2, arcs_73_3}, - {1, arcs_73_4}, - {1, arcs_73_5}, - {1, arcs_73_6}, - {1, arcs_73_7}, + {1, arcs_73_0}, + {1, arcs_73_1}, + {2, arcs_73_2}, + {2, arcs_73_3}, + {1, arcs_73_4}, + {1, arcs_73_5}, + {1, arcs_73_6}, + {1, arcs_73_7}, }; static arc arcs_74_0[3] = { - {163, 1}, - {31, 2}, - {32, 3}, + {163, 1}, + {31, 2}, + {32, 3}, }; static arc arcs_74_1[2] = { - {30, 4}, - {0, 1}, + {30, 4}, + {0, 1}, }; static arc arcs_74_2[1] = { - {24, 5}, + {24, 5}, }; static arc arcs_74_3[1] = { - {24, 6}, + {24, 6}, }; static arc arcs_74_4[4] = { - {163, 1}, - {31, 2}, - {32, 3}, - {0, 4}, + {163, 1}, + {31, 2}, + {32, 3}, + {0, 4}, }; static arc arcs_74_5[2] = { - {30, 7}, - {0, 5}, + {30, 7}, + {0, 5}, }; static arc arcs_74_6[1] = { - {0, 6}, + {0, 6}, }; static arc arcs_74_7[2] = { - {163, 5}, - {32, 3}, + {163, 5}, + {32, 3}, }; static state states_74[8] = { - {3, arcs_74_0}, - {2, arcs_74_1}, - {1, arcs_74_2}, - {1, arcs_74_3}, - {4, arcs_74_4}, - {2, arcs_74_5}, - {1, arcs_74_6}, - {2, arcs_74_7}, + {3, arcs_74_0}, + {2, arcs_74_1}, + {1, arcs_74_2}, + {1, arcs_74_3}, + {4, arcs_74_4}, + {2, arcs_74_5}, + {1, arcs_74_6}, + {2, arcs_74_7}, }; static arc arcs_75_0[1] = { - {24, 1}, + {24, 1}, }; static arc arcs_75_1[3] = { - {158, 2}, - {29, 3}, - {0, 1}, + {158, 2}, + {29, 3}, + {0, 1}, }; static arc arcs_75_2[1] = { - {0, 2}, + {0, 2}, }; static arc arcs_75_3[1] = { - {24, 2}, + {24, 2}, }; static state states_75[4] = { - {1, arcs_75_0}, - {3, arcs_75_1}, - {1, arcs_75_2}, - {1, arcs_75_3}, + {1, arcs_75_0}, + {3, arcs_75_1}, + {1, arcs_75_2}, + {1, arcs_75_3}, }; static arc arcs_76_0[2] = { - {158, 1}, - {165, 1}, + {158, 1}, + {165, 1}, }; static arc arcs_76_1[1] = { - {0, 1}, + {0, 1}, }; static state states_76[2] = { - {2, arcs_76_0}, - {1, arcs_76_1}, + {2, arcs_76_0}, + {1, arcs_76_1}, }; static arc arcs_77_0[1] = { - {96, 1}, + {96, 1}, }; static arc arcs_77_1[1] = { - {62, 2}, + {62, 2}, }; static arc arcs_77_2[1] = { - {97, 3}, + {97, 3}, }; static arc arcs_77_3[1] = { - {107, 4}, + {107, 4}, }; static arc arcs_77_4[2] = { - {164, 5}, - {0, 4}, + {164, 5}, + {0, 4}, }; static arc arcs_77_5[1] = { - {0, 5}, + {0, 5}, }; static state states_77[6] = { - {1, arcs_77_0}, - {1, arcs_77_1}, - {1, arcs_77_2}, - {1, arcs_77_3}, - {2, arcs_77_4}, - {1, arcs_77_5}, + {1, arcs_77_0}, + {1, arcs_77_1}, + {1, arcs_77_2}, + {1, arcs_77_3}, + {2, arcs_77_4}, + {1, arcs_77_5}, }; static arc arcs_78_0[1] = { - {92, 1}, + {92, 1}, }; static arc arcs_78_1[1] = { - {109, 2}, + {109, 2}, }; static arc arcs_78_2[2] = { - {164, 3}, - {0, 2}, + {164, 3}, + {0, 2}, }; static arc arcs_78_3[1] = { - {0, 3}, + {0, 3}, }; static state states_78[4] = { - {1, arcs_78_0}, - {1, arcs_78_1}, - {2, arcs_78_2}, - {1, arcs_78_3}, + {1, arcs_78_0}, + {1, arcs_78_1}, + {2, arcs_78_2}, + {1, arcs_78_3}, }; static arc arcs_79_0[1] = { - {21, 1}, + {21, 1}, }; static arc arcs_79_1[1] = { - {0, 1}, + {0, 1}, }; static state states_79[2] = { - {1, arcs_79_0}, - {1, arcs_79_1}, + {1, arcs_79_0}, + {1, arcs_79_1}, }; static arc arcs_80_0[1] = { - {167, 1}, + {167, 1}, }; static arc arcs_80_1[2] = { - {9, 2}, - {0, 1}, + {9, 2}, + {0, 1}, }; static arc arcs_80_2[1] = { - {0, 2}, + {0, 2}, }; static state states_80[3] = { - {1, arcs_80_0}, - {2, arcs_80_1}, - {1, arcs_80_2}, + {1, arcs_80_0}, + {2, arcs_80_1}, + {1, arcs_80_2}, }; static dfa dfas[81] = { - {256, "single_input", 0, 3, states_0, - "\004\050\060\200\000\000\000\240\340\223\160\220\045\200\020\000\000\206\120\076\204"}, - {257, "file_input", 0, 2, states_1, - "\204\050\060\200\000\000\000\240\340\223\160\220\045\200\020\000\000\206\120\076\204"}, - {258, "eval_input", 0, 3, states_2, - "\000\040\040\000\000\000\000\000\000\200\000\000\000\200\020\000\000\206\120\076\000"}, - {259, "decorator", 0, 7, states_3, - "\000\010\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000"}, - {260, "decorators", 0, 2, states_4, - "\000\010\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000"}, - {261, "decorated", 0, 3, states_5, - "\000\010\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000"}, - {262, "funcdef", 0, 8, states_6, - "\000\000\020\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000"}, - {263, "parameters", 0, 4, states_7, - "\000\040\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000"}, - {264, "typedargslist", 0, 12, states_8, - "\000\000\040\200\001\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000"}, - {265, "tfpdef", 0, 4, states_9, - "\000\000\040\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000"}, - {266, "varargslist", 0, 12, states_10, - "\000\000\040\200\001\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000"}, - {267, "vfpdef", 0, 2, states_11, - "\000\000\040\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000"}, - {268, "stmt", 0, 2, states_12, - "\000\050\060\200\000\000\000\240\340\223\160\220\045\200\020\000\000\206\120\076\204"}, - {269, "simple_stmt", 0, 4, states_13, - "\000\040\040\200\000\000\000\240\340\223\160\000\000\200\020\000\000\206\120\076\200"}, - {270, "small_stmt", 0, 2, states_14, - "\000\040\040\200\000\000\000\240\340\223\160\000\000\200\020\000\000\206\120\076\200"}, - {271, "expr_stmt", 0, 6, states_15, - "\000\040\040\200\000\000\000\000\000\200\000\000\000\200\020\000\000\206\120\076\000"}, - {272, "testlist_star_expr", 0, 3, states_16, - "\000\040\040\200\000\000\000\000\000\200\000\000\000\200\020\000\000\206\120\076\000"}, - {273, "augassign", 0, 2, states_17, - "\000\000\000\000\000\000\376\037\000\000\000\000\000\000\000\000\000\000\000\000\000"}, - {274, "del_stmt", 0, 3, states_18, - "\000\000\000\000\000\000\000\040\000\000\000\000\000\000\000\000\000\000\000\000\000"}, - {275, "pass_stmt", 0, 2, states_19, - "\000\000\000\000\000\000\000\200\000\000\000\000\000\000\000\000\000\000\000\000\000"}, - {276, "flow_stmt", 0, 2, states_20, - "\000\000\000\000\000\000\000\000\340\001\000\000\000\000\000\000\000\000\000\000\200"}, - {277, "break_stmt", 0, 2, states_21, - "\000\000\000\000\000\000\000\000\040\000\000\000\000\000\000\000\000\000\000\000\000"}, - {278, "continue_stmt", 0, 2, states_22, - "\000\000\000\000\000\000\000\000\100\000\000\000\000\000\000\000\000\000\000\000\000"}, - {279, "return_stmt", 0, 3, states_23, - "\000\000\000\000\000\000\000\000\200\000\000\000\000\000\000\000\000\000\000\000\000"}, - {280, "yield_stmt", 0, 2, states_24, - "\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\200"}, - {281, "raise_stmt", 0, 5, states_25, - "\000\000\000\000\000\000\000\000\000\001\000\000\000\000\000\000\000\000\000\000\000"}, - {282, "import_stmt", 0, 2, states_26, - "\000\000\000\000\000\000\000\000\000\022\000\000\000\000\000\000\000\000\000\000\000"}, - {283, "import_name", 0, 3, states_27, - "\000\000\000\000\000\000\000\000\000\020\000\000\000\000\000\000\000\000\000\000\000"}, - {284, "import_from", 0, 8, states_28, - "\000\000\000\000\000\000\000\000\000\002\000\000\000\000\000\000\000\000\000\000\000"}, - {285, "import_as_name", 0, 4, states_29, - "\000\000\040\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000"}, - {286, "dotted_as_name", 0, 4, states_30, - "\000\000\040\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000"}, - {287, "import_as_names", 0, 3, states_31, - "\000\000\040\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000"}, - {288, "dotted_as_names", 0, 2, states_32, - "\000\000\040\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000"}, - {289, "dotted_name", 0, 2, states_33, - "\000\000\040\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000"}, - {290, "global_stmt", 0, 3, states_34, - "\000\000\000\000\000\000\000\000\000\000\020\000\000\000\000\000\000\000\000\000\000"}, - {291, "nonlocal_stmt", 0, 3, states_35, - "\000\000\000\000\000\000\000\000\000\000\040\000\000\000\000\000\000\000\000\000\000"}, - {292, "assert_stmt", 0, 5, states_36, - "\000\000\000\000\000\000\000\000\000\000\100\000\000\000\000\000\000\000\000\000\000"}, - {293, "compound_stmt", 0, 2, states_37, - "\000\010\020\000\000\000\000\000\000\000\000\220\045\000\000\000\000\000\000\000\004"}, - {294, "if_stmt", 0, 8, states_38, - "\000\000\000\000\000\000\000\000\000\000\000\020\000\000\000\000\000\000\000\000\000"}, - {295, "while_stmt", 0, 8, states_39, - "\000\000\000\000\000\000\000\000\000\000\000\200\000\000\000\000\000\000\000\000\000"}, - {296, "for_stmt", 0, 10, states_40, - "\000\000\000\000\000\000\000\000\000\000\000\000\001\000\000\000\000\000\000\000\000"}, - {297, "try_stmt", 0, 13, states_41, - "\000\000\000\000\000\000\000\000\000\000\000\000\004\000\000\000\000\000\000\000\000"}, - {298, "with_stmt", 0, 5, states_42, - "\000\000\000\000\000\000\000\000\000\000\000\000\040\000\000\000\000\000\000\000\000"}, - {299, "with_item", 0, 4, states_43, - "\000\040\040\000\000\000\000\000\000\200\000\000\000\200\020\000\000\206\120\076\000"}, - {300, "except_clause", 0, 5, states_44, - "\000\000\000\000\000\000\000\000\000\000\000\000\000\001\000\000\000\000\000\000\000"}, - {301, "suite", 0, 5, states_45, - "\004\040\040\200\000\000\000\240\340\223\160\000\000\200\020\000\000\206\120\076\200"}, - {302, "test", 0, 6, states_46, - "\000\040\040\000\000\000\000\000\000\200\000\000\000\200\020\000\000\206\120\076\000"}, - {303, "test_nocond", 0, 2, states_47, - "\000\040\040\000\000\000\000\000\000\200\000\000\000\200\020\000\000\206\120\076\000"}, - {304, "lambdef", 0, 5, states_48, - "\000\000\000\000\000\000\000\000\000\000\000\000\000\200\000\000\000\000\000\000\000"}, - {305, "lambdef_nocond", 0, 5, states_49, - "\000\000\000\000\000\000\000\000\000\000\000\000\000\200\000\000\000\000\000\000\000"}, - {306, "or_test", 0, 2, states_50, - "\000\040\040\000\000\000\000\000\000\200\000\000\000\000\020\000\000\206\120\076\000"}, - {307, "and_test", 0, 2, states_51, - "\000\040\040\000\000\000\000\000\000\200\000\000\000\000\020\000\000\206\120\076\000"}, - {308, "not_test", 0, 3, states_52, - "\000\040\040\000\000\000\000\000\000\200\000\000\000\000\020\000\000\206\120\076\000"}, - {309, "comparison", 0, 2, states_53, - "\000\040\040\000\000\000\000\000\000\200\000\000\000\000\000\000\000\206\120\076\000"}, - {310, "comp_op", 0, 4, states_54, - "\000\000\000\000\000\000\000\000\000\000\000\000\002\000\220\177\000\000\000\000\000"}, - {311, "star_expr", 0, 3, states_55, - "\000\000\000\200\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000"}, - {312, "expr", 0, 2, states_56, - "\000\040\040\000\000\000\000\000\000\200\000\000\000\000\000\000\000\206\120\076\000"}, - {313, "xor_expr", 0, 2, states_57, - "\000\040\040\000\000\000\000\000\000\200\000\000\000\000\000\000\000\206\120\076\000"}, - {314, "and_expr", 0, 2, states_58, - "\000\040\040\000\000\000\000\000\000\200\000\000\000\000\000\000\000\206\120\076\000"}, - {315, "shift_expr", 0, 2, states_59, - "\000\040\040\000\000\000\000\000\000\200\000\000\000\000\000\000\000\206\120\076\000"}, - {316, "arith_expr", 0, 2, states_60, - "\000\040\040\000\000\000\000\000\000\200\000\000\000\000\000\000\000\206\120\076\000"}, - {317, "term", 0, 2, states_61, - "\000\040\040\000\000\000\000\000\000\200\000\000\000\000\000\000\000\206\120\076\000"}, - {318, "factor", 0, 3, states_62, - "\000\040\040\000\000\000\000\000\000\200\000\000\000\000\000\000\000\206\120\076\000"}, - {319, "power", 0, 4, states_63, - "\000\040\040\000\000\000\000\000\000\200\000\000\000\000\000\000\000\000\120\076\000"}, - {320, "atom", 0, 9, states_64, - "\000\040\040\000\000\000\000\000\000\200\000\000\000\000\000\000\000\000\120\076\000"}, - {321, "testlist_comp", 0, 5, states_65, - "\000\040\040\200\000\000\000\000\000\200\000\000\000\200\020\000\000\206\120\076\000"}, - {322, "trailer", 0, 7, states_66, - "\000\040\000\000\000\000\000\000\000\100\000\000\000\000\000\000\000\000\020\000\000"}, - {323, "subscriptlist", 0, 3, states_67, - "\000\040\040\002\000\000\000\000\000\200\000\000\000\200\020\000\000\206\120\076\000"}, - {324, "subscript", 0, 5, states_68, - "\000\040\040\002\000\000\000\000\000\200\000\000\000\200\020\000\000\206\120\076\000"}, - {325, "sliceop", 0, 3, states_69, - "\000\000\000\002\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000"}, - {326, "exprlist", 0, 3, states_70, - "\000\040\040\200\000\000\000\000\000\200\000\000\000\000\000\000\000\206\120\076\000"}, - {327, "testlist", 0, 3, states_71, - "\000\040\040\000\000\000\000\000\000\200\000\000\000\200\020\000\000\206\120\076\000"}, - {328, "dictorsetmaker", 0, 11, states_72, - "\000\040\040\000\000\000\000\000\000\200\000\000\000\200\020\000\000\206\120\076\000"}, - {329, "classdef", 0, 8, states_73, - "\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\004"}, - {330, "arglist", 0, 8, states_74, - "\000\040\040\200\001\000\000\000\000\200\000\000\000\200\020\000\000\206\120\076\000"}, - {331, "argument", 0, 4, states_75, - "\000\040\040\000\000\000\000\000\000\200\000\000\000\200\020\000\000\206\120\076\000"}, - {332, "comp_iter", 0, 2, states_76, - "\000\000\000\000\000\000\000\000\000\000\000\020\001\000\000\000\000\000\000\000\000"}, - {333, "comp_for", 0, 6, states_77, - "\000\000\000\000\000\000\000\000\000\000\000\000\001\000\000\000\000\000\000\000\000"}, - {334, "comp_if", 0, 4, states_78, - "\000\000\000\000\000\000\000\000\000\000\000\020\000\000\000\000\000\000\000\000\000"}, - {335, "encoding_decl", 0, 2, states_79, - "\000\000\040\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000"}, - {336, "yield_expr", 0, 3, states_80, - "\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\200"}, + {256, "single_input", 0, 3, states_0, + "\004\050\060\200\000\000\000\240\340\223\160\220\045\200\020\000\000\206\120\076\204"}, + {257, "file_input", 0, 2, states_1, + "\204\050\060\200\000\000\000\240\340\223\160\220\045\200\020\000\000\206\120\076\204"}, + {258, "eval_input", 0, 3, states_2, + "\000\040\040\000\000\000\000\000\000\200\000\000\000\200\020\000\000\206\120\076\000"}, + {259, "decorator", 0, 7, states_3, + "\000\010\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000"}, + {260, "decorators", 0, 2, states_4, + "\000\010\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000"}, + {261, "decorated", 0, 3, states_5, + "\000\010\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000"}, + {262, "funcdef", 0, 8, states_6, + "\000\000\020\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000"}, + {263, "parameters", 0, 4, states_7, + "\000\040\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000"}, + {264, "typedargslist", 0, 12, states_8, + "\000\000\040\200\001\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000"}, + {265, "tfpdef", 0, 4, states_9, + "\000\000\040\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000"}, + {266, "varargslist", 0, 12, states_10, + "\000\000\040\200\001\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000"}, + {267, "vfpdef", 0, 2, states_11, + "\000\000\040\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000"}, + {268, "stmt", 0, 2, states_12, + "\000\050\060\200\000\000\000\240\340\223\160\220\045\200\020\000\000\206\120\076\204"}, + {269, "simple_stmt", 0, 4, states_13, + "\000\040\040\200\000\000\000\240\340\223\160\000\000\200\020\000\000\206\120\076\200"}, + {270, "small_stmt", 0, 2, states_14, + "\000\040\040\200\000\000\000\240\340\223\160\000\000\200\020\000\000\206\120\076\200"}, + {271, "expr_stmt", 0, 6, states_15, + "\000\040\040\200\000\000\000\000\000\200\000\000\000\200\020\000\000\206\120\076\000"}, + {272, "testlist_star_expr", 0, 3, states_16, + "\000\040\040\200\000\000\000\000\000\200\000\000\000\200\020\000\000\206\120\076\000"}, + {273, "augassign", 0, 2, states_17, + "\000\000\000\000\000\000\376\037\000\000\000\000\000\000\000\000\000\000\000\000\000"}, + {274, "del_stmt", 0, 3, states_18, + "\000\000\000\000\000\000\000\040\000\000\000\000\000\000\000\000\000\000\000\000\000"}, + {275, "pass_stmt", 0, 2, states_19, + "\000\000\000\000\000\000\000\200\000\000\000\000\000\000\000\000\000\000\000\000\000"}, + {276, "flow_stmt", 0, 2, states_20, + "\000\000\000\000\000\000\000\000\340\001\000\000\000\000\000\000\000\000\000\000\200"}, + {277, "break_stmt", 0, 2, states_21, + "\000\000\000\000\000\000\000\000\040\000\000\000\000\000\000\000\000\000\000\000\000"}, + {278, "continue_stmt", 0, 2, states_22, + "\000\000\000\000\000\000\000\000\100\000\000\000\000\000\000\000\000\000\000\000\000"}, + {279, "return_stmt", 0, 3, states_23, + "\000\000\000\000\000\000\000\000\200\000\000\000\000\000\000\000\000\000\000\000\000"}, + {280, "yield_stmt", 0, 2, states_24, + "\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\200"}, + {281, "raise_stmt", 0, 5, states_25, + "\000\000\000\000\000\000\000\000\000\001\000\000\000\000\000\000\000\000\000\000\000"}, + {282, "import_stmt", 0, 2, states_26, + "\000\000\000\000\000\000\000\000\000\022\000\000\000\000\000\000\000\000\000\000\000"}, + {283, "import_name", 0, 3, states_27, + "\000\000\000\000\000\000\000\000\000\020\000\000\000\000\000\000\000\000\000\000\000"}, + {284, "import_from", 0, 8, states_28, + "\000\000\000\000\000\000\000\000\000\002\000\000\000\000\000\000\000\000\000\000\000"}, + {285, "import_as_name", 0, 4, states_29, + "\000\000\040\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000"}, + {286, "dotted_as_name", 0, 4, states_30, + "\000\000\040\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000"}, + {287, "import_as_names", 0, 3, states_31, + "\000\000\040\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000"}, + {288, "dotted_as_names", 0, 2, states_32, + "\000\000\040\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000"}, + {289, "dotted_name", 0, 2, states_33, + "\000\000\040\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000"}, + {290, "global_stmt", 0, 3, states_34, + "\000\000\000\000\000\000\000\000\000\000\020\000\000\000\000\000\000\000\000\000\000"}, + {291, "nonlocal_stmt", 0, 3, states_35, + "\000\000\000\000\000\000\000\000\000\000\040\000\000\000\000\000\000\000\000\000\000"}, + {292, "assert_stmt", 0, 5, states_36, + "\000\000\000\000\000\000\000\000\000\000\100\000\000\000\000\000\000\000\000\000\000"}, + {293, "compound_stmt", 0, 2, states_37, + "\000\010\020\000\000\000\000\000\000\000\000\220\045\000\000\000\000\000\000\000\004"}, + {294, "if_stmt", 0, 8, states_38, + "\000\000\000\000\000\000\000\000\000\000\000\020\000\000\000\000\000\000\000\000\000"}, + {295, "while_stmt", 0, 8, states_39, + "\000\000\000\000\000\000\000\000\000\000\000\200\000\000\000\000\000\000\000\000\000"}, + {296, "for_stmt", 0, 10, states_40, + "\000\000\000\000\000\000\000\000\000\000\000\000\001\000\000\000\000\000\000\000\000"}, + {297, "try_stmt", 0, 13, states_41, + "\000\000\000\000\000\000\000\000\000\000\000\000\004\000\000\000\000\000\000\000\000"}, + {298, "with_stmt", 0, 5, states_42, + "\000\000\000\000\000\000\000\000\000\000\000\000\040\000\000\000\000\000\000\000\000"}, + {299, "with_item", 0, 4, states_43, + "\000\040\040\000\000\000\000\000\000\200\000\000\000\200\020\000\000\206\120\076\000"}, + {300, "except_clause", 0, 5, states_44, + "\000\000\000\000\000\000\000\000\000\000\000\000\000\001\000\000\000\000\000\000\000"}, + {301, "suite", 0, 5, states_45, + "\004\040\040\200\000\000\000\240\340\223\160\000\000\200\020\000\000\206\120\076\200"}, + {302, "test", 0, 6, states_46, + "\000\040\040\000\000\000\000\000\000\200\000\000\000\200\020\000\000\206\120\076\000"}, + {303, "test_nocond", 0, 2, states_47, + "\000\040\040\000\000\000\000\000\000\200\000\000\000\200\020\000\000\206\120\076\000"}, + {304, "lambdef", 0, 5, states_48, + "\000\000\000\000\000\000\000\000\000\000\000\000\000\200\000\000\000\000\000\000\000"}, + {305, "lambdef_nocond", 0, 5, states_49, + "\000\000\000\000\000\000\000\000\000\000\000\000\000\200\000\000\000\000\000\000\000"}, + {306, "or_test", 0, 2, states_50, + "\000\040\040\000\000\000\000\000\000\200\000\000\000\000\020\000\000\206\120\076\000"}, + {307, "and_test", 0, 2, states_51, + "\000\040\040\000\000\000\000\000\000\200\000\000\000\000\020\000\000\206\120\076\000"}, + {308, "not_test", 0, 3, states_52, + "\000\040\040\000\000\000\000\000\000\200\000\000\000\000\020\000\000\206\120\076\000"}, + {309, "comparison", 0, 2, states_53, + "\000\040\040\000\000\000\000\000\000\200\000\000\000\000\000\000\000\206\120\076\000"}, + {310, "comp_op", 0, 4, states_54, + "\000\000\000\000\000\000\000\000\000\000\000\000\002\000\220\177\000\000\000\000\000"}, + {311, "star_expr", 0, 3, states_55, + "\000\000\000\200\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000"}, + {312, "expr", 0, 2, states_56, + "\000\040\040\000\000\000\000\000\000\200\000\000\000\000\000\000\000\206\120\076\000"}, + {313, "xor_expr", 0, 2, states_57, + "\000\040\040\000\000\000\000\000\000\200\000\000\000\000\000\000\000\206\120\076\000"}, + {314, "and_expr", 0, 2, states_58, + "\000\040\040\000\000\000\000\000\000\200\000\000\000\000\000\000\000\206\120\076\000"}, + {315, "shift_expr", 0, 2, states_59, + "\000\040\040\000\000\000\000\000\000\200\000\000\000\000\000\000\000\206\120\076\000"}, + {316, "arith_expr", 0, 2, states_60, + "\000\040\040\000\000\000\000\000\000\200\000\000\000\000\000\000\000\206\120\076\000"}, + {317, "term", 0, 2, states_61, + "\000\040\040\000\000\000\000\000\000\200\000\000\000\000\000\000\000\206\120\076\000"}, + {318, "factor", 0, 3, states_62, + "\000\040\040\000\000\000\000\000\000\200\000\000\000\000\000\000\000\206\120\076\000"}, + {319, "power", 0, 4, states_63, + "\000\040\040\000\000\000\000\000\000\200\000\000\000\000\000\000\000\000\120\076\000"}, + {320, "atom", 0, 9, states_64, + "\000\040\040\000\000\000\000\000\000\200\000\000\000\000\000\000\000\000\120\076\000"}, + {321, "testlist_comp", 0, 5, states_65, + "\000\040\040\200\000\000\000\000\000\200\000\000\000\200\020\000\000\206\120\076\000"}, + {322, "trailer", 0, 7, states_66, + "\000\040\000\000\000\000\000\000\000\100\000\000\000\000\000\000\000\000\020\000\000"}, + {323, "subscriptlist", 0, 3, states_67, + "\000\040\040\002\000\000\000\000\000\200\000\000\000\200\020\000\000\206\120\076\000"}, + {324, "subscript", 0, 5, states_68, + "\000\040\040\002\000\000\000\000\000\200\000\000\000\200\020\000\000\206\120\076\000"}, + {325, "sliceop", 0, 3, states_69, + "\000\000\000\002\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000"}, + {326, "exprlist", 0, 3, states_70, + "\000\040\040\200\000\000\000\000\000\200\000\000\000\000\000\000\000\206\120\076\000"}, + {327, "testlist", 0, 3, states_71, + "\000\040\040\000\000\000\000\000\000\200\000\000\000\200\020\000\000\206\120\076\000"}, + {328, "dictorsetmaker", 0, 11, states_72, + "\000\040\040\000\000\000\000\000\000\200\000\000\000\200\020\000\000\206\120\076\000"}, + {329, "classdef", 0, 8, states_73, + "\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\004"}, + {330, "arglist", 0, 8, states_74, + "\000\040\040\200\001\000\000\000\000\200\000\000\000\200\020\000\000\206\120\076\000"}, + {331, "argument", 0, 4, states_75, + "\000\040\040\000\000\000\000\000\000\200\000\000\000\200\020\000\000\206\120\076\000"}, + {332, "comp_iter", 0, 2, states_76, + "\000\000\000\000\000\000\000\000\000\000\000\020\001\000\000\000\000\000\000\000\000"}, + {333, "comp_for", 0, 6, states_77, + "\000\000\000\000\000\000\000\000\000\000\000\000\001\000\000\000\000\000\000\000\000"}, + {334, "comp_if", 0, 4, states_78, + "\000\000\000\000\000\000\000\000\000\000\000\020\000\000\000\000\000\000\000\000\000"}, + {335, "encoding_decl", 0, 2, states_79, + "\000\000\040\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000"}, + {336, "yield_expr", 0, 3, states_80, + "\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\200"}, }; static label labels[168] = { - {0, "EMPTY"}, - {256, 0}, - {4, 0}, - {269, 0}, - {293, 0}, - {257, 0}, - {268, 0}, - {0, 0}, - {258, 0}, - {327, 0}, - {259, 0}, - {50, 0}, - {289, 0}, - {7, 0}, - {330, 0}, - {8, 0}, - {260, 0}, - {261, 0}, - {329, 0}, - {262, 0}, - {1, "def"}, - {1, 0}, - {263, 0}, - {51, 0}, - {302, 0}, - {11, 0}, - {301, 0}, - {264, 0}, - {265, 0}, - {22, 0}, - {12, 0}, - {16, 0}, - {36, 0}, - {266, 0}, - {267, 0}, - {270, 0}, - {13, 0}, - {271, 0}, - {274, 0}, - {275, 0}, - {276, 0}, - {282, 0}, - {290, 0}, - {291, 0}, - {292, 0}, - {272, 0}, - {273, 0}, - {336, 0}, - {311, 0}, - {37, 0}, - {38, 0}, - {39, 0}, - {40, 0}, - {41, 0}, - {42, 0}, - {43, 0}, - {44, 0}, - {45, 0}, - {46, 0}, - {47, 0}, - {49, 0}, - {1, "del"}, - {326, 0}, - {1, "pass"}, - {277, 0}, - {278, 0}, - {279, 0}, - {281, 0}, - {280, 0}, - {1, "break"}, - {1, "continue"}, - {1, "return"}, - {1, "raise"}, - {1, "from"}, - {283, 0}, - {284, 0}, - {1, "import"}, - {288, 0}, - {23, 0}, - {52, 0}, - {287, 0}, - {285, 0}, - {1, "as"}, - {286, 0}, - {1, "global"}, - {1, "nonlocal"}, - {1, "assert"}, - {294, 0}, - {295, 0}, - {296, 0}, - {297, 0}, - {298, 0}, - {1, "if"}, - {1, "elif"}, - {1, "else"}, - {1, "while"}, - {1, "for"}, - {1, "in"}, - {1, "try"}, - {300, 0}, - {1, "finally"}, - {1, "with"}, - {299, 0}, - {312, 0}, - {1, "except"}, - {5, 0}, - {6, 0}, - {306, 0}, - {304, 0}, - {303, 0}, - {305, 0}, - {1, "lambda"}, - {307, 0}, - {1, "or"}, - {308, 0}, - {1, "and"}, - {1, "not"}, - {309, 0}, - {310, 0}, - {20, 0}, - {21, 0}, - {28, 0}, - {31, 0}, - {30, 0}, - {29, 0}, - {29, 0}, - {1, "is"}, - {313, 0}, - {18, 0}, - {314, 0}, - {33, 0}, - {315, 0}, - {19, 0}, - {316, 0}, - {34, 0}, - {35, 0}, - {317, 0}, - {14, 0}, - {15, 0}, - {318, 0}, - {17, 0}, - {24, 0}, - {48, 0}, - {32, 0}, - {319, 0}, - {320, 0}, - {322, 0}, - {321, 0}, - {9, 0}, - {10, 0}, - {26, 0}, - {328, 0}, - {27, 0}, - {2, 0}, - {3, 0}, - {1, "None"}, - {1, "True"}, - {1, "False"}, - {333, 0}, - {323, 0}, - {324, 0}, - {325, 0}, - {1, "class"}, - {331, 0}, - {332, 0}, - {334, 0}, - {335, 0}, - {1, "yield"}, + {0, "EMPTY"}, + {256, 0}, + {4, 0}, + {269, 0}, + {293, 0}, + {257, 0}, + {268, 0}, + {0, 0}, + {258, 0}, + {327, 0}, + {259, 0}, + {50, 0}, + {289, 0}, + {7, 0}, + {330, 0}, + {8, 0}, + {260, 0}, + {261, 0}, + {329, 0}, + {262, 0}, + {1, "def"}, + {1, 0}, + {263, 0}, + {51, 0}, + {302, 0}, + {11, 0}, + {301, 0}, + {264, 0}, + {265, 0}, + {22, 0}, + {12, 0}, + {16, 0}, + {36, 0}, + {266, 0}, + {267, 0}, + {270, 0}, + {13, 0}, + {271, 0}, + {274, 0}, + {275, 0}, + {276, 0}, + {282, 0}, + {290, 0}, + {291, 0}, + {292, 0}, + {272, 0}, + {273, 0}, + {336, 0}, + {311, 0}, + {37, 0}, + {38, 0}, + {39, 0}, + {40, 0}, + {41, 0}, + {42, 0}, + {43, 0}, + {44, 0}, + {45, 0}, + {46, 0}, + {47, 0}, + {49, 0}, + {1, "del"}, + {326, 0}, + {1, "pass"}, + {277, 0}, + {278, 0}, + {279, 0}, + {281, 0}, + {280, 0}, + {1, "break"}, + {1, "continue"}, + {1, "return"}, + {1, "raise"}, + {1, "from"}, + {283, 0}, + {284, 0}, + {1, "import"}, + {288, 0}, + {23, 0}, + {52, 0}, + {287, 0}, + {285, 0}, + {1, "as"}, + {286, 0}, + {1, "global"}, + {1, "nonlocal"}, + {1, "assert"}, + {294, 0}, + {295, 0}, + {296, 0}, + {297, 0}, + {298, 0}, + {1, "if"}, + {1, "elif"}, + {1, "else"}, + {1, "while"}, + {1, "for"}, + {1, "in"}, + {1, "try"}, + {300, 0}, + {1, "finally"}, + {1, "with"}, + {299, 0}, + {312, 0}, + {1, "except"}, + {5, 0}, + {6, 0}, + {306, 0}, + {304, 0}, + {303, 0}, + {305, 0}, + {1, "lambda"}, + {307, 0}, + {1, "or"}, + {308, 0}, + {1, "and"}, + {1, "not"}, + {309, 0}, + {310, 0}, + {20, 0}, + {21, 0}, + {28, 0}, + {31, 0}, + {30, 0}, + {29, 0}, + {29, 0}, + {1, "is"}, + {313, 0}, + {18, 0}, + {314, 0}, + {33, 0}, + {315, 0}, + {19, 0}, + {316, 0}, + {34, 0}, + {35, 0}, + {317, 0}, + {14, 0}, + {15, 0}, + {318, 0}, + {17, 0}, + {24, 0}, + {48, 0}, + {32, 0}, + {319, 0}, + {320, 0}, + {322, 0}, + {321, 0}, + {9, 0}, + {10, 0}, + {26, 0}, + {328, 0}, + {27, 0}, + {2, 0}, + {3, 0}, + {1, "None"}, + {1, "True"}, + {1, "False"}, + {333, 0}, + {323, 0}, + {324, 0}, + {325, 0}, + {1, "class"}, + {331, 0}, + {332, 0}, + {334, 0}, + {335, 0}, + {1, "yield"}, }; grammar _PyParser_Grammar = { - 81, - dfas, - {168, labels}, - 256 + 81, + dfas, + {168, labels}, + 256 }; From python-checkins at python.org Sun May 16 01:03:16 2010 From: python-checkins at python.org (victor.stinner) Date: Sun, 16 May 2010 01:03:16 +0200 (CEST) Subject: [Python-checkins] r81223 - in python/branches/release31-maint: Parser/printgrammar.c Python/graminit.c Message-ID: <20100515230316.08034EEA96@mail.python.org> Author: victor.stinner Date: Sun May 16 01:03:15 2010 New Revision: 81223 Log: Merged revisions 81222 via svnmerge from svn+ssh://pythondev at svn.python.org/python/branches/py3k ................ r81222 | victor.stinner | 2010-05-16 01:00:51 +0200 (dim., 16 mai 2010) | 11 lines Merged revisions 81220 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r81220 | victor.stinner | 2010-05-16 00:55:28 +0200 (dim., 16 mai 2010) | 4 lines Use 4-spaces for indentation (instead of tabs) in pgen outputs Regenerate (reindent) Python/graminit.c ........ ................ Modified: python/branches/release31-maint/ (props changed) python/branches/release31-maint/Parser/printgrammar.c python/branches/release31-maint/Python/graminit.c Modified: python/branches/release31-maint/Parser/printgrammar.c ============================================================================== --- python/branches/release31-maint/Parser/printgrammar.c (original) +++ python/branches/release31-maint/Parser/printgrammar.c Sun May 16 01:03:15 2010 @@ -20,10 +20,10 @@ printdfas(g, fp); printlabels(g, fp); fprintf(fp, "grammar _PyParser_Grammar = {\n"); - fprintf(fp, "\t%d,\n", g->g_ndfas); - fprintf(fp, "\tdfas,\n"); - fprintf(fp, "\t{%d, labels},\n", g->g_ll.ll_nlabels); - fprintf(fp, "\t%d\n", g->g_start); + fprintf(fp, " %d,\n", g->g_ndfas); + fprintf(fp, " dfas,\n"); + fprintf(fp, " {%d, labels},\n", g->g_ll.ll_nlabels); + fprintf(fp, " %d\n", g->g_start); fprintf(fp, "};\n"); } @@ -53,7 +53,7 @@ i, j, s->s_narcs); a = s->s_arc; for (k = 0; k < s->s_narcs; k++, a++) - fprintf(fp, "\t{%d, %d},\n", a->a_lbl, a->a_arrow); + fprintf(fp, " {%d, %d},\n", a->a_lbl, a->a_arrow); fprintf(fp, "};\n"); } } @@ -72,7 +72,7 @@ i, d->d_nstates); s = d->d_state; for (j = 0; j < d->d_nstates; j++, s++) - fprintf(fp, "\t{%d, arcs_%d_%d},\n", + fprintf(fp, " {%d, arcs_%d_%d},\n", s->s_narcs, i, j); fprintf(fp, "};\n"); } @@ -88,9 +88,9 @@ fprintf(fp, "static dfa dfas[%d] = {\n", g->g_ndfas); d = g->g_dfa; for (i = 0; i < g->g_ndfas; i++, d++) { - fprintf(fp, "\t{%d, \"%s\", %d, %d, states_%d,\n", + fprintf(fp, " {%d, \"%s\", %d, %d, states_%d,\n", d->d_type, d->d_name, d->d_initial, d->d_nstates, i); - fprintf(fp, "\t \""); + fprintf(fp, " \""); for (j = 0; j < NBYTES(g->g_ll.ll_nlabels); j++) fprintf(fp, "\\%03o", d->d_first[j] & 0xff); fprintf(fp, "\"},\n"); @@ -108,9 +108,9 @@ l = g->g_ll.ll_label; for (i = g->g_ll.ll_nlabels; --i >= 0; l++) { if (l->lb_str == NULL) - fprintf(fp, "\t{%d, 0},\n", l->lb_type); + fprintf(fp, " {%d, 0},\n", l->lb_type); else - fprintf(fp, "\t{%d, \"%s\"},\n", + fprintf(fp, " {%d, \"%s\"},\n", l->lb_type, l->lb_str); } fprintf(fp, "};\n"); Modified: python/branches/release31-maint/Python/graminit.c ============================================================================== --- python/branches/release31-maint/Python/graminit.c (original) +++ python/branches/release31-maint/Python/graminit.c Sun May 16 01:03:15 2010 @@ -4,2067 +4,2067 @@ #include "grammar.h" PyAPI_DATA(grammar) _PyParser_Grammar; static arc arcs_0_0[3] = { - {2, 1}, - {3, 1}, - {4, 2}, + {2, 1}, + {3, 1}, + {4, 2}, }; static arc arcs_0_1[1] = { - {0, 1}, + {0, 1}, }; static arc arcs_0_2[1] = { - {2, 1}, + {2, 1}, }; static state states_0[3] = { - {3, arcs_0_0}, - {1, arcs_0_1}, - {1, arcs_0_2}, + {3, arcs_0_0}, + {1, arcs_0_1}, + {1, arcs_0_2}, }; static arc arcs_1_0[3] = { - {2, 0}, - {6, 0}, - {7, 1}, + {2, 0}, + {6, 0}, + {7, 1}, }; static arc arcs_1_1[1] = { - {0, 1}, + {0, 1}, }; static state states_1[2] = { - {3, arcs_1_0}, - {1, arcs_1_1}, + {3, arcs_1_0}, + {1, arcs_1_1}, }; static arc arcs_2_0[1] = { - {9, 1}, + {9, 1}, }; static arc arcs_2_1[2] = { - {2, 1}, - {7, 2}, + {2, 1}, + {7, 2}, }; static arc arcs_2_2[1] = { - {0, 2}, + {0, 2}, }; static state states_2[3] = { - {1, arcs_2_0}, - {2, arcs_2_1}, - {1, arcs_2_2}, + {1, arcs_2_0}, + {2, arcs_2_1}, + {1, arcs_2_2}, }; static arc arcs_3_0[1] = { - {11, 1}, + {11, 1}, }; static arc arcs_3_1[1] = { - {12, 2}, + {12, 2}, }; static arc arcs_3_2[2] = { - {13, 3}, - {2, 4}, + {13, 3}, + {2, 4}, }; static arc arcs_3_3[2] = { - {14, 5}, - {15, 6}, + {14, 5}, + {15, 6}, }; static arc arcs_3_4[1] = { - {0, 4}, + {0, 4}, }; static arc arcs_3_5[1] = { - {15, 6}, + {15, 6}, }; static arc arcs_3_6[1] = { - {2, 4}, + {2, 4}, }; static state states_3[7] = { - {1, arcs_3_0}, - {1, arcs_3_1}, - {2, arcs_3_2}, - {2, arcs_3_3}, - {1, arcs_3_4}, - {1, arcs_3_5}, - {1, arcs_3_6}, + {1, arcs_3_0}, + {1, arcs_3_1}, + {2, arcs_3_2}, + {2, arcs_3_3}, + {1, arcs_3_4}, + {1, arcs_3_5}, + {1, arcs_3_6}, }; static arc arcs_4_0[1] = { - {10, 1}, + {10, 1}, }; static arc arcs_4_1[2] = { - {10, 1}, - {0, 1}, + {10, 1}, + {0, 1}, }; static state states_4[2] = { - {1, arcs_4_0}, - {2, arcs_4_1}, + {1, arcs_4_0}, + {2, arcs_4_1}, }; static arc arcs_5_0[1] = { - {16, 1}, + {16, 1}, }; static arc arcs_5_1[2] = { - {18, 2}, - {19, 2}, + {18, 2}, + {19, 2}, }; static arc arcs_5_2[1] = { - {0, 2}, + {0, 2}, }; static state states_5[3] = { - {1, arcs_5_0}, - {2, arcs_5_1}, - {1, arcs_5_2}, + {1, arcs_5_0}, + {2, arcs_5_1}, + {1, arcs_5_2}, }; static arc arcs_6_0[1] = { - {20, 1}, + {20, 1}, }; static arc arcs_6_1[1] = { - {21, 2}, + {21, 2}, }; static arc arcs_6_2[1] = { - {22, 3}, + {22, 3}, }; static arc arcs_6_3[2] = { - {23, 4}, - {25, 5}, + {23, 4}, + {25, 5}, }; static arc arcs_6_4[1] = { - {24, 6}, + {24, 6}, }; static arc arcs_6_5[1] = { - {26, 7}, + {26, 7}, }; static arc arcs_6_6[1] = { - {25, 5}, + {25, 5}, }; static arc arcs_6_7[1] = { - {0, 7}, + {0, 7}, }; static state states_6[8] = { - {1, arcs_6_0}, - {1, arcs_6_1}, - {1, arcs_6_2}, - {2, arcs_6_3}, - {1, arcs_6_4}, - {1, arcs_6_5}, - {1, arcs_6_6}, - {1, arcs_6_7}, + {1, arcs_6_0}, + {1, arcs_6_1}, + {1, arcs_6_2}, + {2, arcs_6_3}, + {1, arcs_6_4}, + {1, arcs_6_5}, + {1, arcs_6_6}, + {1, arcs_6_7}, }; static arc arcs_7_0[1] = { - {13, 1}, + {13, 1}, }; static arc arcs_7_1[2] = { - {27, 2}, - {15, 3}, + {27, 2}, + {15, 3}, }; static arc arcs_7_2[1] = { - {15, 3}, + {15, 3}, }; static arc arcs_7_3[1] = { - {0, 3}, + {0, 3}, }; static state states_7[4] = { - {1, arcs_7_0}, - {2, arcs_7_1}, - {1, arcs_7_2}, - {1, arcs_7_3}, + {1, arcs_7_0}, + {2, arcs_7_1}, + {1, arcs_7_2}, + {1, arcs_7_3}, }; static arc arcs_8_0[3] = { - {28, 1}, - {31, 2}, - {32, 3}, + {28, 1}, + {31, 2}, + {32, 3}, }; static arc arcs_8_1[3] = { - {29, 4}, - {30, 5}, - {0, 1}, + {29, 4}, + {30, 5}, + {0, 1}, }; static arc arcs_8_2[3] = { - {28, 6}, - {30, 7}, - {0, 2}, + {28, 6}, + {30, 7}, + {0, 2}, }; static arc arcs_8_3[1] = { - {28, 8}, + {28, 8}, }; static arc arcs_8_4[1] = { - {24, 9}, + {24, 9}, }; static arc arcs_8_5[4] = { - {28, 1}, - {31, 2}, - {32, 3}, - {0, 5}, + {28, 1}, + {31, 2}, + {32, 3}, + {0, 5}, }; static arc arcs_8_6[2] = { - {30, 7}, - {0, 6}, + {30, 7}, + {0, 6}, }; static arc arcs_8_7[2] = { - {28, 10}, - {32, 3}, + {28, 10}, + {32, 3}, }; static arc arcs_8_8[1] = { - {0, 8}, + {0, 8}, }; static arc arcs_8_9[2] = { - {30, 5}, - {0, 9}, + {30, 5}, + {0, 9}, }; static arc arcs_8_10[3] = { - {30, 7}, - {29, 11}, - {0, 10}, + {30, 7}, + {29, 11}, + {0, 10}, }; static arc arcs_8_11[1] = { - {24, 6}, + {24, 6}, }; static state states_8[12] = { - {3, arcs_8_0}, - {3, arcs_8_1}, - {3, arcs_8_2}, - {1, arcs_8_3}, - {1, arcs_8_4}, - {4, arcs_8_5}, - {2, arcs_8_6}, - {2, arcs_8_7}, - {1, arcs_8_8}, - {2, arcs_8_9}, - {3, arcs_8_10}, - {1, arcs_8_11}, + {3, arcs_8_0}, + {3, arcs_8_1}, + {3, arcs_8_2}, + {1, arcs_8_3}, + {1, arcs_8_4}, + {4, arcs_8_5}, + {2, arcs_8_6}, + {2, arcs_8_7}, + {1, arcs_8_8}, + {2, arcs_8_9}, + {3, arcs_8_10}, + {1, arcs_8_11}, }; static arc arcs_9_0[1] = { - {21, 1}, + {21, 1}, }; static arc arcs_9_1[2] = { - {25, 2}, - {0, 1}, + {25, 2}, + {0, 1}, }; static arc arcs_9_2[1] = { - {24, 3}, + {24, 3}, }; static arc arcs_9_3[1] = { - {0, 3}, + {0, 3}, }; static state states_9[4] = { - {1, arcs_9_0}, - {2, arcs_9_1}, - {1, arcs_9_2}, - {1, arcs_9_3}, + {1, arcs_9_0}, + {2, arcs_9_1}, + {1, arcs_9_2}, + {1, arcs_9_3}, }; static arc arcs_10_0[3] = { - {34, 1}, - {31, 2}, - {32, 3}, + {34, 1}, + {31, 2}, + {32, 3}, }; static arc arcs_10_1[3] = { - {29, 4}, - {30, 5}, - {0, 1}, + {29, 4}, + {30, 5}, + {0, 1}, }; static arc arcs_10_2[3] = { - {34, 6}, - {30, 7}, - {0, 2}, + {34, 6}, + {30, 7}, + {0, 2}, }; static arc arcs_10_3[1] = { - {34, 8}, + {34, 8}, }; static arc arcs_10_4[1] = { - {24, 9}, + {24, 9}, }; static arc arcs_10_5[4] = { - {34, 1}, - {31, 2}, - {32, 3}, - {0, 5}, + {34, 1}, + {31, 2}, + {32, 3}, + {0, 5}, }; static arc arcs_10_6[2] = { - {30, 7}, - {0, 6}, + {30, 7}, + {0, 6}, }; static arc arcs_10_7[2] = { - {34, 10}, - {32, 3}, + {34, 10}, + {32, 3}, }; static arc arcs_10_8[1] = { - {0, 8}, + {0, 8}, }; static arc arcs_10_9[2] = { - {30, 5}, - {0, 9}, + {30, 5}, + {0, 9}, }; static arc arcs_10_10[3] = { - {30, 7}, - {29, 11}, - {0, 10}, + {30, 7}, + {29, 11}, + {0, 10}, }; static arc arcs_10_11[1] = { - {24, 6}, + {24, 6}, }; static state states_10[12] = { - {3, arcs_10_0}, - {3, arcs_10_1}, - {3, arcs_10_2}, - {1, arcs_10_3}, - {1, arcs_10_4}, - {4, arcs_10_5}, - {2, arcs_10_6}, - {2, arcs_10_7}, - {1, arcs_10_8}, - {2, arcs_10_9}, - {3, arcs_10_10}, - {1, arcs_10_11}, + {3, arcs_10_0}, + {3, arcs_10_1}, + {3, arcs_10_2}, + {1, arcs_10_3}, + {1, arcs_10_4}, + {4, arcs_10_5}, + {2, arcs_10_6}, + {2, arcs_10_7}, + {1, arcs_10_8}, + {2, arcs_10_9}, + {3, arcs_10_10}, + {1, arcs_10_11}, }; static arc arcs_11_0[1] = { - {21, 1}, + {21, 1}, }; static arc arcs_11_1[1] = { - {0, 1}, + {0, 1}, }; static state states_11[2] = { - {1, arcs_11_0}, - {1, arcs_11_1}, + {1, arcs_11_0}, + {1, arcs_11_1}, }; static arc arcs_12_0[2] = { - {3, 1}, - {4, 1}, + {3, 1}, + {4, 1}, }; static arc arcs_12_1[1] = { - {0, 1}, + {0, 1}, }; static state states_12[2] = { - {2, arcs_12_0}, - {1, arcs_12_1}, + {2, arcs_12_0}, + {1, arcs_12_1}, }; static arc arcs_13_0[1] = { - {35, 1}, + {35, 1}, }; static arc arcs_13_1[2] = { - {36, 2}, - {2, 3}, + {36, 2}, + {2, 3}, }; static arc arcs_13_2[2] = { - {35, 1}, - {2, 3}, + {35, 1}, + {2, 3}, }; static arc arcs_13_3[1] = { - {0, 3}, + {0, 3}, }; static state states_13[4] = { - {1, arcs_13_0}, - {2, arcs_13_1}, - {2, arcs_13_2}, - {1, arcs_13_3}, + {1, arcs_13_0}, + {2, arcs_13_1}, + {2, arcs_13_2}, + {1, arcs_13_3}, }; static arc arcs_14_0[8] = { - {37, 1}, - {38, 1}, - {39, 1}, - {40, 1}, - {41, 1}, - {42, 1}, - {43, 1}, - {44, 1}, + {37, 1}, + {38, 1}, + {39, 1}, + {40, 1}, + {41, 1}, + {42, 1}, + {43, 1}, + {44, 1}, }; static arc arcs_14_1[1] = { - {0, 1}, + {0, 1}, }; static state states_14[2] = { - {8, arcs_14_0}, - {1, arcs_14_1}, + {8, arcs_14_0}, + {1, arcs_14_1}, }; static arc arcs_15_0[1] = { - {9, 1}, + {9, 1}, }; static arc arcs_15_1[3] = { - {45, 2}, - {29, 3}, - {0, 1}, + {45, 2}, + {29, 3}, + {0, 1}, }; static arc arcs_15_2[2] = { - {46, 4}, - {9, 4}, + {46, 4}, + {9, 4}, }; static arc arcs_15_3[2] = { - {46, 5}, - {9, 5}, + {46, 5}, + {9, 5}, }; static arc arcs_15_4[1] = { - {0, 4}, + {0, 4}, }; static arc arcs_15_5[2] = { - {29, 3}, - {0, 5}, + {29, 3}, + {0, 5}, }; static state states_15[6] = { - {1, arcs_15_0}, - {3, arcs_15_1}, - {2, arcs_15_2}, - {2, arcs_15_3}, - {1, arcs_15_4}, - {2, arcs_15_5}, + {1, arcs_15_0}, + {3, arcs_15_1}, + {2, arcs_15_2}, + {2, arcs_15_3}, + {1, arcs_15_4}, + {2, arcs_15_5}, }; static arc arcs_16_0[12] = { - {47, 1}, - {48, 1}, - {49, 1}, - {50, 1}, - {51, 1}, - {52, 1}, - {53, 1}, - {54, 1}, - {55, 1}, - {56, 1}, - {57, 1}, - {58, 1}, + {47, 1}, + {48, 1}, + {49, 1}, + {50, 1}, + {51, 1}, + {52, 1}, + {53, 1}, + {54, 1}, + {55, 1}, + {56, 1}, + {57, 1}, + {58, 1}, }; static arc arcs_16_1[1] = { - {0, 1}, + {0, 1}, }; static state states_16[2] = { - {12, arcs_16_0}, - {1, arcs_16_1}, + {12, arcs_16_0}, + {1, arcs_16_1}, }; static arc arcs_17_0[1] = { - {59, 1}, + {59, 1}, }; static arc arcs_17_1[1] = { - {60, 2}, + {60, 2}, }; static arc arcs_17_2[1] = { - {0, 2}, + {0, 2}, }; static state states_17[3] = { - {1, arcs_17_0}, - {1, arcs_17_1}, - {1, arcs_17_2}, + {1, arcs_17_0}, + {1, arcs_17_1}, + {1, arcs_17_2}, }; static arc arcs_18_0[1] = { - {61, 1}, + {61, 1}, }; static arc arcs_18_1[1] = { - {0, 1}, + {0, 1}, }; static state states_18[2] = { - {1, arcs_18_0}, - {1, arcs_18_1}, + {1, arcs_18_0}, + {1, arcs_18_1}, }; static arc arcs_19_0[5] = { - {62, 1}, - {63, 1}, - {64, 1}, - {65, 1}, - {66, 1}, + {62, 1}, + {63, 1}, + {64, 1}, + {65, 1}, + {66, 1}, }; static arc arcs_19_1[1] = { - {0, 1}, + {0, 1}, }; static state states_19[2] = { - {5, arcs_19_0}, - {1, arcs_19_1}, + {5, arcs_19_0}, + {1, arcs_19_1}, }; static arc arcs_20_0[1] = { - {67, 1}, + {67, 1}, }; static arc arcs_20_1[1] = { - {0, 1}, + {0, 1}, }; static state states_20[2] = { - {1, arcs_20_0}, - {1, arcs_20_1}, + {1, arcs_20_0}, + {1, arcs_20_1}, }; static arc arcs_21_0[1] = { - {68, 1}, + {68, 1}, }; static arc arcs_21_1[1] = { - {0, 1}, + {0, 1}, }; static state states_21[2] = { - {1, arcs_21_0}, - {1, arcs_21_1}, + {1, arcs_21_0}, + {1, arcs_21_1}, }; static arc arcs_22_0[1] = { - {69, 1}, + {69, 1}, }; static arc arcs_22_1[2] = { - {9, 2}, - {0, 1}, + {9, 2}, + {0, 1}, }; static arc arcs_22_2[1] = { - {0, 2}, + {0, 2}, }; static state states_22[3] = { - {1, arcs_22_0}, - {2, arcs_22_1}, - {1, arcs_22_2}, + {1, arcs_22_0}, + {2, arcs_22_1}, + {1, arcs_22_2}, }; static arc arcs_23_0[1] = { - {46, 1}, + {46, 1}, }; static arc arcs_23_1[1] = { - {0, 1}, + {0, 1}, }; static state states_23[2] = { - {1, arcs_23_0}, - {1, arcs_23_1}, + {1, arcs_23_0}, + {1, arcs_23_1}, }; static arc arcs_24_0[1] = { - {70, 1}, + {70, 1}, }; static arc arcs_24_1[2] = { - {24, 2}, - {0, 1}, + {24, 2}, + {0, 1}, }; static arc arcs_24_2[2] = { - {71, 3}, - {0, 2}, + {71, 3}, + {0, 2}, }; static arc arcs_24_3[1] = { - {24, 4}, + {24, 4}, }; static arc arcs_24_4[1] = { - {0, 4}, + {0, 4}, }; static state states_24[5] = { - {1, arcs_24_0}, - {2, arcs_24_1}, - {2, arcs_24_2}, - {1, arcs_24_3}, - {1, arcs_24_4}, + {1, arcs_24_0}, + {2, arcs_24_1}, + {2, arcs_24_2}, + {1, arcs_24_3}, + {1, arcs_24_4}, }; static arc arcs_25_0[2] = { - {72, 1}, - {73, 1}, + {72, 1}, + {73, 1}, }; static arc arcs_25_1[1] = { - {0, 1}, + {0, 1}, }; static state states_25[2] = { - {2, arcs_25_0}, - {1, arcs_25_1}, + {2, arcs_25_0}, + {1, arcs_25_1}, }; static arc arcs_26_0[1] = { - {74, 1}, + {74, 1}, }; static arc arcs_26_1[1] = { - {75, 2}, + {75, 2}, }; static arc arcs_26_2[1] = { - {0, 2}, + {0, 2}, }; static state states_26[3] = { - {1, arcs_26_0}, - {1, arcs_26_1}, - {1, arcs_26_2}, + {1, arcs_26_0}, + {1, arcs_26_1}, + {1, arcs_26_2}, }; static arc arcs_27_0[1] = { - {71, 1}, + {71, 1}, }; static arc arcs_27_1[3] = { - {76, 2}, - {77, 2}, - {12, 3}, + {76, 2}, + {77, 2}, + {12, 3}, }; static arc arcs_27_2[4] = { - {76, 2}, - {77, 2}, - {12, 3}, - {74, 4}, + {76, 2}, + {77, 2}, + {12, 3}, + {74, 4}, }; static arc arcs_27_3[1] = { - {74, 4}, + {74, 4}, }; static arc arcs_27_4[3] = { - {31, 5}, - {13, 6}, - {78, 5}, + {31, 5}, + {13, 6}, + {78, 5}, }; static arc arcs_27_5[1] = { - {0, 5}, + {0, 5}, }; static arc arcs_27_6[1] = { - {78, 7}, + {78, 7}, }; static arc arcs_27_7[1] = { - {15, 5}, + {15, 5}, }; static state states_27[8] = { - {1, arcs_27_0}, - {3, arcs_27_1}, - {4, arcs_27_2}, - {1, arcs_27_3}, - {3, arcs_27_4}, - {1, arcs_27_5}, - {1, arcs_27_6}, - {1, arcs_27_7}, + {1, arcs_27_0}, + {3, arcs_27_1}, + {4, arcs_27_2}, + {1, arcs_27_3}, + {3, arcs_27_4}, + {1, arcs_27_5}, + {1, arcs_27_6}, + {1, arcs_27_7}, }; static arc arcs_28_0[1] = { - {21, 1}, + {21, 1}, }; static arc arcs_28_1[2] = { - {80, 2}, - {0, 1}, + {80, 2}, + {0, 1}, }; static arc arcs_28_2[1] = { - {21, 3}, + {21, 3}, }; static arc arcs_28_3[1] = { - {0, 3}, + {0, 3}, }; static state states_28[4] = { - {1, arcs_28_0}, - {2, arcs_28_1}, - {1, arcs_28_2}, - {1, arcs_28_3}, + {1, arcs_28_0}, + {2, arcs_28_1}, + {1, arcs_28_2}, + {1, arcs_28_3}, }; static arc arcs_29_0[1] = { - {12, 1}, + {12, 1}, }; static arc arcs_29_1[2] = { - {80, 2}, - {0, 1}, + {80, 2}, + {0, 1}, }; static arc arcs_29_2[1] = { - {21, 3}, + {21, 3}, }; static arc arcs_29_3[1] = { - {0, 3}, + {0, 3}, }; static state states_29[4] = { - {1, arcs_29_0}, - {2, arcs_29_1}, - {1, arcs_29_2}, - {1, arcs_29_3}, + {1, arcs_29_0}, + {2, arcs_29_1}, + {1, arcs_29_2}, + {1, arcs_29_3}, }; static arc arcs_30_0[1] = { - {79, 1}, + {79, 1}, }; static arc arcs_30_1[2] = { - {30, 2}, - {0, 1}, + {30, 2}, + {0, 1}, }; static arc arcs_30_2[2] = { - {79, 1}, - {0, 2}, + {79, 1}, + {0, 2}, }; static state states_30[3] = { - {1, arcs_30_0}, - {2, arcs_30_1}, - {2, arcs_30_2}, + {1, arcs_30_0}, + {2, arcs_30_1}, + {2, arcs_30_2}, }; static arc arcs_31_0[1] = { - {81, 1}, + {81, 1}, }; static arc arcs_31_1[2] = { - {30, 0}, - {0, 1}, + {30, 0}, + {0, 1}, }; static state states_31[2] = { - {1, arcs_31_0}, - {2, arcs_31_1}, + {1, arcs_31_0}, + {2, arcs_31_1}, }; static arc arcs_32_0[1] = { - {21, 1}, + {21, 1}, }; static arc arcs_32_1[2] = { - {76, 0}, - {0, 1}, + {76, 0}, + {0, 1}, }; static state states_32[2] = { - {1, arcs_32_0}, - {2, arcs_32_1}, + {1, arcs_32_0}, + {2, arcs_32_1}, }; static arc arcs_33_0[1] = { - {82, 1}, + {82, 1}, }; static arc arcs_33_1[1] = { - {21, 2}, + {21, 2}, }; static arc arcs_33_2[2] = { - {30, 1}, - {0, 2}, + {30, 1}, + {0, 2}, }; static state states_33[3] = { - {1, arcs_33_0}, - {1, arcs_33_1}, - {2, arcs_33_2}, + {1, arcs_33_0}, + {1, arcs_33_1}, + {2, arcs_33_2}, }; static arc arcs_34_0[1] = { - {83, 1}, + {83, 1}, }; static arc arcs_34_1[1] = { - {21, 2}, + {21, 2}, }; static arc arcs_34_2[2] = { - {30, 1}, - {0, 2}, + {30, 1}, + {0, 2}, }; static state states_34[3] = { - {1, arcs_34_0}, - {1, arcs_34_1}, - {2, arcs_34_2}, + {1, arcs_34_0}, + {1, arcs_34_1}, + {2, arcs_34_2}, }; static arc arcs_35_0[1] = { - {84, 1}, + {84, 1}, }; static arc arcs_35_1[1] = { - {24, 2}, + {24, 2}, }; static arc arcs_35_2[2] = { - {30, 3}, - {0, 2}, + {30, 3}, + {0, 2}, }; static arc arcs_35_3[1] = { - {24, 4}, + {24, 4}, }; static arc arcs_35_4[1] = { - {0, 4}, + {0, 4}, }; static state states_35[5] = { - {1, arcs_35_0}, - {1, arcs_35_1}, - {2, arcs_35_2}, - {1, arcs_35_3}, - {1, arcs_35_4}, + {1, arcs_35_0}, + {1, arcs_35_1}, + {2, arcs_35_2}, + {1, arcs_35_3}, + {1, arcs_35_4}, }; static arc arcs_36_0[8] = { - {85, 1}, - {86, 1}, - {87, 1}, - {88, 1}, - {89, 1}, - {19, 1}, - {18, 1}, - {17, 1}, + {85, 1}, + {86, 1}, + {87, 1}, + {88, 1}, + {89, 1}, + {19, 1}, + {18, 1}, + {17, 1}, }; static arc arcs_36_1[1] = { - {0, 1}, + {0, 1}, }; static state states_36[2] = { - {8, arcs_36_0}, - {1, arcs_36_1}, + {8, arcs_36_0}, + {1, arcs_36_1}, }; static arc arcs_37_0[1] = { - {90, 1}, + {90, 1}, }; static arc arcs_37_1[1] = { - {24, 2}, + {24, 2}, }; static arc arcs_37_2[1] = { - {25, 3}, + {25, 3}, }; static arc arcs_37_3[1] = { - {26, 4}, + {26, 4}, }; static arc arcs_37_4[3] = { - {91, 1}, - {92, 5}, - {0, 4}, + {91, 1}, + {92, 5}, + {0, 4}, }; static arc arcs_37_5[1] = { - {25, 6}, + {25, 6}, }; static arc arcs_37_6[1] = { - {26, 7}, + {26, 7}, }; static arc arcs_37_7[1] = { - {0, 7}, + {0, 7}, }; static state states_37[8] = { - {1, arcs_37_0}, - {1, arcs_37_1}, - {1, arcs_37_2}, - {1, arcs_37_3}, - {3, arcs_37_4}, - {1, arcs_37_5}, - {1, arcs_37_6}, - {1, arcs_37_7}, + {1, arcs_37_0}, + {1, arcs_37_1}, + {1, arcs_37_2}, + {1, arcs_37_3}, + {3, arcs_37_4}, + {1, arcs_37_5}, + {1, arcs_37_6}, + {1, arcs_37_7}, }; static arc arcs_38_0[1] = { - {93, 1}, + {93, 1}, }; static arc arcs_38_1[1] = { - {24, 2}, + {24, 2}, }; static arc arcs_38_2[1] = { - {25, 3}, + {25, 3}, }; static arc arcs_38_3[1] = { - {26, 4}, + {26, 4}, }; static arc arcs_38_4[2] = { - {92, 5}, - {0, 4}, + {92, 5}, + {0, 4}, }; static arc arcs_38_5[1] = { - {25, 6}, + {25, 6}, }; static arc arcs_38_6[1] = { - {26, 7}, + {26, 7}, }; static arc arcs_38_7[1] = { - {0, 7}, + {0, 7}, }; static state states_38[8] = { - {1, arcs_38_0}, - {1, arcs_38_1}, - {1, arcs_38_2}, - {1, arcs_38_3}, - {2, arcs_38_4}, - {1, arcs_38_5}, - {1, arcs_38_6}, - {1, arcs_38_7}, + {1, arcs_38_0}, + {1, arcs_38_1}, + {1, arcs_38_2}, + {1, arcs_38_3}, + {2, arcs_38_4}, + {1, arcs_38_5}, + {1, arcs_38_6}, + {1, arcs_38_7}, }; static arc arcs_39_0[1] = { - {94, 1}, + {94, 1}, }; static arc arcs_39_1[1] = { - {60, 2}, + {60, 2}, }; static arc arcs_39_2[1] = { - {95, 3}, + {95, 3}, }; static arc arcs_39_3[1] = { - {9, 4}, + {9, 4}, }; static arc arcs_39_4[1] = { - {25, 5}, + {25, 5}, }; static arc arcs_39_5[1] = { - {26, 6}, + {26, 6}, }; static arc arcs_39_6[2] = { - {92, 7}, - {0, 6}, + {92, 7}, + {0, 6}, }; static arc arcs_39_7[1] = { - {25, 8}, + {25, 8}, }; static arc arcs_39_8[1] = { - {26, 9}, + {26, 9}, }; static arc arcs_39_9[1] = { - {0, 9}, + {0, 9}, }; static state states_39[10] = { - {1, arcs_39_0}, - {1, arcs_39_1}, - {1, arcs_39_2}, - {1, arcs_39_3}, - {1, arcs_39_4}, - {1, arcs_39_5}, - {2, arcs_39_6}, - {1, arcs_39_7}, - {1, arcs_39_8}, - {1, arcs_39_9}, + {1, arcs_39_0}, + {1, arcs_39_1}, + {1, arcs_39_2}, + {1, arcs_39_3}, + {1, arcs_39_4}, + {1, arcs_39_5}, + {2, arcs_39_6}, + {1, arcs_39_7}, + {1, arcs_39_8}, + {1, arcs_39_9}, }; static arc arcs_40_0[1] = { - {96, 1}, + {96, 1}, }; static arc arcs_40_1[1] = { - {25, 2}, + {25, 2}, }; static arc arcs_40_2[1] = { - {26, 3}, + {26, 3}, }; static arc arcs_40_3[2] = { - {97, 4}, - {98, 5}, + {97, 4}, + {98, 5}, }; static arc arcs_40_4[1] = { - {25, 6}, + {25, 6}, }; static arc arcs_40_5[1] = { - {25, 7}, + {25, 7}, }; static arc arcs_40_6[1] = { - {26, 8}, + {26, 8}, }; static arc arcs_40_7[1] = { - {26, 9}, + {26, 9}, }; static arc arcs_40_8[4] = { - {97, 4}, - {92, 10}, - {98, 5}, - {0, 8}, + {97, 4}, + {92, 10}, + {98, 5}, + {0, 8}, }; static arc arcs_40_9[1] = { - {0, 9}, + {0, 9}, }; static arc arcs_40_10[1] = { - {25, 11}, + {25, 11}, }; static arc arcs_40_11[1] = { - {26, 12}, + {26, 12}, }; static arc arcs_40_12[2] = { - {98, 5}, - {0, 12}, + {98, 5}, + {0, 12}, }; static state states_40[13] = { - {1, arcs_40_0}, - {1, arcs_40_1}, - {1, arcs_40_2}, - {2, arcs_40_3}, - {1, arcs_40_4}, - {1, arcs_40_5}, - {1, arcs_40_6}, - {1, arcs_40_7}, - {4, arcs_40_8}, - {1, arcs_40_9}, - {1, arcs_40_10}, - {1, arcs_40_11}, - {2, arcs_40_12}, + {1, arcs_40_0}, + {1, arcs_40_1}, + {1, arcs_40_2}, + {2, arcs_40_3}, + {1, arcs_40_4}, + {1, arcs_40_5}, + {1, arcs_40_6}, + {1, arcs_40_7}, + {4, arcs_40_8}, + {1, arcs_40_9}, + {1, arcs_40_10}, + {1, arcs_40_11}, + {2, arcs_40_12}, }; static arc arcs_41_0[1] = { - {99, 1}, + {99, 1}, }; static arc arcs_41_1[1] = { - {100, 2}, + {100, 2}, }; static arc arcs_41_2[2] = { - {30, 1}, - {25, 3}, + {30, 1}, + {25, 3}, }; static arc arcs_41_3[1] = { - {26, 4}, + {26, 4}, }; static arc arcs_41_4[1] = { - {0, 4}, + {0, 4}, }; static state states_41[5] = { - {1, arcs_41_0}, - {1, arcs_41_1}, - {2, arcs_41_2}, - {1, arcs_41_3}, - {1, arcs_41_4}, + {1, arcs_41_0}, + {1, arcs_41_1}, + {2, arcs_41_2}, + {1, arcs_41_3}, + {1, arcs_41_4}, }; static arc arcs_42_0[1] = { - {24, 1}, + {24, 1}, }; static arc arcs_42_1[2] = { - {80, 2}, - {0, 1}, + {80, 2}, + {0, 1}, }; static arc arcs_42_2[1] = { - {101, 3}, + {101, 3}, }; static arc arcs_42_3[1] = { - {0, 3}, + {0, 3}, }; static state states_42[4] = { - {1, arcs_42_0}, - {2, arcs_42_1}, - {1, arcs_42_2}, - {1, arcs_42_3}, + {1, arcs_42_0}, + {2, arcs_42_1}, + {1, arcs_42_2}, + {1, arcs_42_3}, }; static arc arcs_43_0[1] = { - {102, 1}, + {102, 1}, }; static arc arcs_43_1[2] = { - {24, 2}, - {0, 1}, + {24, 2}, + {0, 1}, }; static arc arcs_43_2[2] = { - {80, 3}, - {0, 2}, + {80, 3}, + {0, 2}, }; static arc arcs_43_3[1] = { - {21, 4}, + {21, 4}, }; static arc arcs_43_4[1] = { - {0, 4}, + {0, 4}, }; static state states_43[5] = { - {1, arcs_43_0}, - {2, arcs_43_1}, - {2, arcs_43_2}, - {1, arcs_43_3}, - {1, arcs_43_4}, + {1, arcs_43_0}, + {2, arcs_43_1}, + {2, arcs_43_2}, + {1, arcs_43_3}, + {1, arcs_43_4}, }; static arc arcs_44_0[2] = { - {3, 1}, - {2, 2}, + {3, 1}, + {2, 2}, }; static arc arcs_44_1[1] = { - {0, 1}, + {0, 1}, }; static arc arcs_44_2[1] = { - {103, 3}, + {103, 3}, }; static arc arcs_44_3[1] = { - {6, 4}, + {6, 4}, }; static arc arcs_44_4[2] = { - {6, 4}, - {104, 1}, + {6, 4}, + {104, 1}, }; static state states_44[5] = { - {2, arcs_44_0}, - {1, arcs_44_1}, - {1, arcs_44_2}, - {1, arcs_44_3}, - {2, arcs_44_4}, + {2, arcs_44_0}, + {1, arcs_44_1}, + {1, arcs_44_2}, + {1, arcs_44_3}, + {2, arcs_44_4}, }; static arc arcs_45_0[2] = { - {105, 1}, - {106, 2}, + {105, 1}, + {106, 2}, }; static arc arcs_45_1[2] = { - {90, 3}, - {0, 1}, + {90, 3}, + {0, 1}, }; static arc arcs_45_2[1] = { - {0, 2}, + {0, 2}, }; static arc arcs_45_3[1] = { - {105, 4}, + {105, 4}, }; static arc arcs_45_4[1] = { - {92, 5}, + {92, 5}, }; static arc arcs_45_5[1] = { - {24, 2}, + {24, 2}, }; static state states_45[6] = { - {2, arcs_45_0}, - {2, arcs_45_1}, - {1, arcs_45_2}, - {1, arcs_45_3}, - {1, arcs_45_4}, - {1, arcs_45_5}, + {2, arcs_45_0}, + {2, arcs_45_1}, + {1, arcs_45_2}, + {1, arcs_45_3}, + {1, arcs_45_4}, + {1, arcs_45_5}, }; static arc arcs_46_0[2] = { - {105, 1}, - {108, 1}, + {105, 1}, + {108, 1}, }; static arc arcs_46_1[1] = { - {0, 1}, + {0, 1}, }; static state states_46[2] = { - {2, arcs_46_0}, - {1, arcs_46_1}, + {2, arcs_46_0}, + {1, arcs_46_1}, }; static arc arcs_47_0[1] = { - {109, 1}, + {109, 1}, }; static arc arcs_47_1[2] = { - {33, 2}, - {25, 3}, + {33, 2}, + {25, 3}, }; static arc arcs_47_2[1] = { - {25, 3}, + {25, 3}, }; static arc arcs_47_3[1] = { - {24, 4}, + {24, 4}, }; static arc arcs_47_4[1] = { - {0, 4}, + {0, 4}, }; static state states_47[5] = { - {1, arcs_47_0}, - {2, arcs_47_1}, - {1, arcs_47_2}, - {1, arcs_47_3}, - {1, arcs_47_4}, + {1, arcs_47_0}, + {2, arcs_47_1}, + {1, arcs_47_2}, + {1, arcs_47_3}, + {1, arcs_47_4}, }; static arc arcs_48_0[1] = { - {109, 1}, + {109, 1}, }; static arc arcs_48_1[2] = { - {33, 2}, - {25, 3}, + {33, 2}, + {25, 3}, }; static arc arcs_48_2[1] = { - {25, 3}, + {25, 3}, }; static arc arcs_48_3[1] = { - {107, 4}, + {107, 4}, }; static arc arcs_48_4[1] = { - {0, 4}, + {0, 4}, }; static state states_48[5] = { - {1, arcs_48_0}, - {2, arcs_48_1}, - {1, arcs_48_2}, - {1, arcs_48_3}, - {1, arcs_48_4}, + {1, arcs_48_0}, + {2, arcs_48_1}, + {1, arcs_48_2}, + {1, arcs_48_3}, + {1, arcs_48_4}, }; static arc arcs_49_0[1] = { - {110, 1}, + {110, 1}, }; static arc arcs_49_1[2] = { - {111, 0}, - {0, 1}, + {111, 0}, + {0, 1}, }; static state states_49[2] = { - {1, arcs_49_0}, - {2, arcs_49_1}, + {1, arcs_49_0}, + {2, arcs_49_1}, }; static arc arcs_50_0[1] = { - {112, 1}, + {112, 1}, }; static arc arcs_50_1[2] = { - {113, 0}, - {0, 1}, + {113, 0}, + {0, 1}, }; static state states_50[2] = { - {1, arcs_50_0}, - {2, arcs_50_1}, + {1, arcs_50_0}, + {2, arcs_50_1}, }; static arc arcs_51_0[2] = { - {114, 1}, - {115, 2}, + {114, 1}, + {115, 2}, }; static arc arcs_51_1[1] = { - {112, 2}, + {112, 2}, }; static arc arcs_51_2[1] = { - {0, 2}, + {0, 2}, }; static state states_51[3] = { - {2, arcs_51_0}, - {1, arcs_51_1}, - {1, arcs_51_2}, + {2, arcs_51_0}, + {1, arcs_51_1}, + {1, arcs_51_2}, }; static arc arcs_52_0[1] = { - {116, 1}, + {116, 1}, }; static arc arcs_52_1[2] = { - {117, 0}, - {0, 1}, + {117, 0}, + {0, 1}, }; static state states_52[2] = { - {1, arcs_52_0}, - {2, arcs_52_1}, + {1, arcs_52_0}, + {2, arcs_52_1}, }; static arc arcs_53_0[10] = { - {118, 1}, - {119, 1}, - {120, 1}, - {121, 1}, - {122, 1}, - {123, 1}, - {124, 1}, - {95, 1}, - {114, 2}, - {125, 3}, + {118, 1}, + {119, 1}, + {120, 1}, + {121, 1}, + {122, 1}, + {123, 1}, + {124, 1}, + {95, 1}, + {114, 2}, + {125, 3}, }; static arc arcs_53_1[1] = { - {0, 1}, + {0, 1}, }; static arc arcs_53_2[1] = { - {95, 1}, + {95, 1}, }; static arc arcs_53_3[2] = { - {114, 1}, - {0, 3}, + {114, 1}, + {0, 3}, }; static state states_53[4] = { - {10, arcs_53_0}, - {1, arcs_53_1}, - {1, arcs_53_2}, - {2, arcs_53_3}, + {10, arcs_53_0}, + {1, arcs_53_1}, + {1, arcs_53_2}, + {2, arcs_53_3}, }; static arc arcs_54_0[2] = { - {31, 1}, - {101, 2}, + {31, 1}, + {101, 2}, }; static arc arcs_54_1[1] = { - {101, 2}, + {101, 2}, }; static arc arcs_54_2[1] = { - {0, 2}, + {0, 2}, }; static state states_54[3] = { - {2, arcs_54_0}, - {1, arcs_54_1}, - {1, arcs_54_2}, + {2, arcs_54_0}, + {1, arcs_54_1}, + {1, arcs_54_2}, }; static arc arcs_55_0[1] = { - {126, 1}, + {126, 1}, }; static arc arcs_55_1[2] = { - {127, 0}, - {0, 1}, + {127, 0}, + {0, 1}, }; static state states_55[2] = { - {1, arcs_55_0}, - {2, arcs_55_1}, + {1, arcs_55_0}, + {2, arcs_55_1}, }; static arc arcs_56_0[1] = { - {128, 1}, + {128, 1}, }; static arc arcs_56_1[2] = { - {129, 0}, - {0, 1}, + {129, 0}, + {0, 1}, }; static state states_56[2] = { - {1, arcs_56_0}, - {2, arcs_56_1}, + {1, arcs_56_0}, + {2, arcs_56_1}, }; static arc arcs_57_0[1] = { - {130, 1}, + {130, 1}, }; static arc arcs_57_1[2] = { - {131, 0}, - {0, 1}, + {131, 0}, + {0, 1}, }; static state states_57[2] = { - {1, arcs_57_0}, - {2, arcs_57_1}, + {1, arcs_57_0}, + {2, arcs_57_1}, }; static arc arcs_58_0[1] = { - {132, 1}, + {132, 1}, }; static arc arcs_58_1[3] = { - {133, 0}, - {134, 0}, - {0, 1}, + {133, 0}, + {134, 0}, + {0, 1}, }; static state states_58[2] = { - {1, arcs_58_0}, - {3, arcs_58_1}, + {1, arcs_58_0}, + {3, arcs_58_1}, }; static arc arcs_59_0[1] = { - {135, 1}, + {135, 1}, }; static arc arcs_59_1[3] = { - {136, 0}, - {137, 0}, - {0, 1}, + {136, 0}, + {137, 0}, + {0, 1}, }; static state states_59[2] = { - {1, arcs_59_0}, - {3, arcs_59_1}, + {1, arcs_59_0}, + {3, arcs_59_1}, }; static arc arcs_60_0[1] = { - {138, 1}, + {138, 1}, }; static arc arcs_60_1[5] = { - {31, 0}, - {139, 0}, - {140, 0}, - {141, 0}, - {0, 1}, + {31, 0}, + {139, 0}, + {140, 0}, + {141, 0}, + {0, 1}, }; static state states_60[2] = { - {1, arcs_60_0}, - {5, arcs_60_1}, + {1, arcs_60_0}, + {5, arcs_60_1}, }; static arc arcs_61_0[4] = { - {136, 1}, - {137, 1}, - {142, 1}, - {143, 2}, + {136, 1}, + {137, 1}, + {142, 1}, + {143, 2}, }; static arc arcs_61_1[1] = { - {138, 2}, + {138, 2}, }; static arc arcs_61_2[1] = { - {0, 2}, + {0, 2}, }; static state states_61[3] = { - {4, arcs_61_0}, - {1, arcs_61_1}, - {1, arcs_61_2}, + {4, arcs_61_0}, + {1, arcs_61_1}, + {1, arcs_61_2}, }; static arc arcs_62_0[1] = { - {144, 1}, + {144, 1}, }; static arc arcs_62_1[3] = { - {145, 1}, - {32, 2}, - {0, 1}, + {145, 1}, + {32, 2}, + {0, 1}, }; static arc arcs_62_2[1] = { - {138, 3}, + {138, 3}, }; static arc arcs_62_3[1] = { - {0, 3}, + {0, 3}, }; static state states_62[4] = { - {1, arcs_62_0}, - {3, arcs_62_1}, - {1, arcs_62_2}, - {1, arcs_62_3}, + {1, arcs_62_0}, + {3, arcs_62_1}, + {1, arcs_62_2}, + {1, arcs_62_3}, }; static arc arcs_63_0[10] = { - {13, 1}, - {147, 2}, - {149, 3}, - {21, 4}, - {152, 4}, - {153, 5}, - {77, 4}, - {154, 4}, - {155, 4}, - {156, 4}, + {13, 1}, + {147, 2}, + {149, 3}, + {21, 4}, + {152, 4}, + {153, 5}, + {77, 4}, + {154, 4}, + {155, 4}, + {156, 4}, }; static arc arcs_63_1[3] = { - {46, 6}, - {146, 6}, - {15, 4}, + {46, 6}, + {146, 6}, + {15, 4}, }; static arc arcs_63_2[2] = { - {146, 7}, - {148, 4}, + {146, 7}, + {148, 4}, }; static arc arcs_63_3[2] = { - {150, 8}, - {151, 4}, + {150, 8}, + {151, 4}, }; static arc arcs_63_4[1] = { - {0, 4}, + {0, 4}, }; static arc arcs_63_5[2] = { - {153, 5}, - {0, 5}, + {153, 5}, + {0, 5}, }; static arc arcs_63_6[1] = { - {15, 4}, + {15, 4}, }; static arc arcs_63_7[1] = { - {148, 4}, + {148, 4}, }; static arc arcs_63_8[1] = { - {151, 4}, + {151, 4}, }; static state states_63[9] = { - {10, arcs_63_0}, - {3, arcs_63_1}, - {2, arcs_63_2}, - {2, arcs_63_3}, - {1, arcs_63_4}, - {2, arcs_63_5}, - {1, arcs_63_6}, - {1, arcs_63_7}, - {1, arcs_63_8}, + {10, arcs_63_0}, + {3, arcs_63_1}, + {2, arcs_63_2}, + {2, arcs_63_3}, + {1, arcs_63_4}, + {2, arcs_63_5}, + {1, arcs_63_6}, + {1, arcs_63_7}, + {1, arcs_63_8}, }; static arc arcs_64_0[1] = { - {24, 1}, + {24, 1}, }; static arc arcs_64_1[3] = { - {157, 2}, - {30, 3}, - {0, 1}, + {157, 2}, + {30, 3}, + {0, 1}, }; static arc arcs_64_2[1] = { - {0, 2}, + {0, 2}, }; static arc arcs_64_3[2] = { - {24, 4}, - {0, 3}, + {24, 4}, + {0, 3}, }; static arc arcs_64_4[2] = { - {30, 3}, - {0, 4}, + {30, 3}, + {0, 4}, }; static state states_64[5] = { - {1, arcs_64_0}, - {3, arcs_64_1}, - {1, arcs_64_2}, - {2, arcs_64_3}, - {2, arcs_64_4}, + {1, arcs_64_0}, + {3, arcs_64_1}, + {1, arcs_64_2}, + {2, arcs_64_3}, + {2, arcs_64_4}, }; static arc arcs_65_0[3] = { - {13, 1}, - {147, 2}, - {76, 3}, + {13, 1}, + {147, 2}, + {76, 3}, }; static arc arcs_65_1[2] = { - {14, 4}, - {15, 5}, + {14, 4}, + {15, 5}, }; static arc arcs_65_2[1] = { - {158, 6}, + {158, 6}, }; static arc arcs_65_3[1] = { - {21, 5}, + {21, 5}, }; static arc arcs_65_4[1] = { - {15, 5}, + {15, 5}, }; static arc arcs_65_5[1] = { - {0, 5}, + {0, 5}, }; static arc arcs_65_6[1] = { - {148, 5}, + {148, 5}, }; static state states_65[7] = { - {3, arcs_65_0}, - {2, arcs_65_1}, - {1, arcs_65_2}, - {1, arcs_65_3}, - {1, arcs_65_4}, - {1, arcs_65_5}, - {1, arcs_65_6}, + {3, arcs_65_0}, + {2, arcs_65_1}, + {1, arcs_65_2}, + {1, arcs_65_3}, + {1, arcs_65_4}, + {1, arcs_65_5}, + {1, arcs_65_6}, }; static arc arcs_66_0[1] = { - {159, 1}, + {159, 1}, }; static arc arcs_66_1[2] = { - {30, 2}, - {0, 1}, + {30, 2}, + {0, 1}, }; static arc arcs_66_2[2] = { - {159, 1}, - {0, 2}, + {159, 1}, + {0, 2}, }; static state states_66[3] = { - {1, arcs_66_0}, - {2, arcs_66_1}, - {2, arcs_66_2}, + {1, arcs_66_0}, + {2, arcs_66_1}, + {2, arcs_66_2}, }; static arc arcs_67_0[2] = { - {24, 1}, - {25, 2}, + {24, 1}, + {25, 2}, }; static arc arcs_67_1[2] = { - {25, 2}, - {0, 1}, + {25, 2}, + {0, 1}, }; static arc arcs_67_2[3] = { - {24, 3}, - {160, 4}, - {0, 2}, + {24, 3}, + {160, 4}, + {0, 2}, }; static arc arcs_67_3[2] = { - {160, 4}, - {0, 3}, + {160, 4}, + {0, 3}, }; static arc arcs_67_4[1] = { - {0, 4}, + {0, 4}, }; static state states_67[5] = { - {2, arcs_67_0}, - {2, arcs_67_1}, - {3, arcs_67_2}, - {2, arcs_67_3}, - {1, arcs_67_4}, + {2, arcs_67_0}, + {2, arcs_67_1}, + {3, arcs_67_2}, + {2, arcs_67_3}, + {1, arcs_67_4}, }; static arc arcs_68_0[1] = { - {25, 1}, + {25, 1}, }; static arc arcs_68_1[2] = { - {24, 2}, - {0, 1}, + {24, 2}, + {0, 1}, }; static arc arcs_68_2[1] = { - {0, 2}, + {0, 2}, }; static state states_68[3] = { - {1, arcs_68_0}, - {2, arcs_68_1}, - {1, arcs_68_2}, + {1, arcs_68_0}, + {2, arcs_68_1}, + {1, arcs_68_2}, }; static arc arcs_69_0[1] = { - {116, 1}, + {116, 1}, }; static arc arcs_69_1[2] = { - {30, 2}, - {0, 1}, + {30, 2}, + {0, 1}, }; static arc arcs_69_2[2] = { - {116, 1}, - {0, 2}, + {116, 1}, + {0, 2}, }; static state states_69[3] = { - {1, arcs_69_0}, - {2, arcs_69_1}, - {2, arcs_69_2}, + {1, arcs_69_0}, + {2, arcs_69_1}, + {2, arcs_69_2}, }; static arc arcs_70_0[1] = { - {24, 1}, + {24, 1}, }; static arc arcs_70_1[2] = { - {30, 2}, - {0, 1}, + {30, 2}, + {0, 1}, }; static arc arcs_70_2[2] = { - {24, 1}, - {0, 2}, + {24, 1}, + {0, 2}, }; static state states_70[3] = { - {1, arcs_70_0}, - {2, arcs_70_1}, - {2, arcs_70_2}, + {1, arcs_70_0}, + {2, arcs_70_1}, + {2, arcs_70_2}, }; static arc arcs_71_0[1] = { - {24, 1}, + {24, 1}, }; static arc arcs_71_1[4] = { - {25, 2}, - {157, 3}, - {30, 4}, - {0, 1}, + {25, 2}, + {157, 3}, + {30, 4}, + {0, 1}, }; static arc arcs_71_2[1] = { - {24, 5}, + {24, 5}, }; static arc arcs_71_3[1] = { - {0, 3}, + {0, 3}, }; static arc arcs_71_4[2] = { - {24, 6}, - {0, 4}, + {24, 6}, + {0, 4}, }; static arc arcs_71_5[3] = { - {157, 3}, - {30, 7}, - {0, 5}, + {157, 3}, + {30, 7}, + {0, 5}, }; static arc arcs_71_6[2] = { - {30, 4}, - {0, 6}, + {30, 4}, + {0, 6}, }; static arc arcs_71_7[2] = { - {24, 8}, - {0, 7}, + {24, 8}, + {0, 7}, }; static arc arcs_71_8[1] = { - {25, 9}, + {25, 9}, }; static arc arcs_71_9[1] = { - {24, 10}, + {24, 10}, }; static arc arcs_71_10[2] = { - {30, 7}, - {0, 10}, + {30, 7}, + {0, 10}, }; static state states_71[11] = { - {1, arcs_71_0}, - {4, arcs_71_1}, - {1, arcs_71_2}, - {1, arcs_71_3}, - {2, arcs_71_4}, - {3, arcs_71_5}, - {2, arcs_71_6}, - {2, arcs_71_7}, - {1, arcs_71_8}, - {1, arcs_71_9}, - {2, arcs_71_10}, + {1, arcs_71_0}, + {4, arcs_71_1}, + {1, arcs_71_2}, + {1, arcs_71_3}, + {2, arcs_71_4}, + {3, arcs_71_5}, + {2, arcs_71_6}, + {2, arcs_71_7}, + {1, arcs_71_8}, + {1, arcs_71_9}, + {2, arcs_71_10}, }; static arc arcs_72_0[1] = { - {161, 1}, + {161, 1}, }; static arc arcs_72_1[1] = { - {21, 2}, + {21, 2}, }; static arc arcs_72_2[2] = { - {13, 3}, - {25, 4}, + {13, 3}, + {25, 4}, }; static arc arcs_72_3[2] = { - {14, 5}, - {15, 6}, + {14, 5}, + {15, 6}, }; static arc arcs_72_4[1] = { - {26, 7}, + {26, 7}, }; static arc arcs_72_5[1] = { - {15, 6}, + {15, 6}, }; static arc arcs_72_6[1] = { - {25, 4}, + {25, 4}, }; static arc arcs_72_7[1] = { - {0, 7}, + {0, 7}, }; static state states_72[8] = { - {1, arcs_72_0}, - {1, arcs_72_1}, - {2, arcs_72_2}, - {2, arcs_72_3}, - {1, arcs_72_4}, - {1, arcs_72_5}, - {1, arcs_72_6}, - {1, arcs_72_7}, + {1, arcs_72_0}, + {1, arcs_72_1}, + {2, arcs_72_2}, + {2, arcs_72_3}, + {1, arcs_72_4}, + {1, arcs_72_5}, + {1, arcs_72_6}, + {1, arcs_72_7}, }; static arc arcs_73_0[3] = { - {162, 1}, - {31, 2}, - {32, 3}, + {162, 1}, + {31, 2}, + {32, 3}, }; static arc arcs_73_1[2] = { - {30, 4}, - {0, 1}, + {30, 4}, + {0, 1}, }; static arc arcs_73_2[1] = { - {24, 5}, + {24, 5}, }; static arc arcs_73_3[1] = { - {24, 6}, + {24, 6}, }; static arc arcs_73_4[4] = { - {162, 1}, - {31, 2}, - {32, 3}, - {0, 4}, + {162, 1}, + {31, 2}, + {32, 3}, + {0, 4}, }; static arc arcs_73_5[2] = { - {30, 7}, - {0, 5}, + {30, 7}, + {0, 5}, }; static arc arcs_73_6[1] = { - {0, 6}, + {0, 6}, }; static arc arcs_73_7[2] = { - {162, 5}, - {32, 3}, + {162, 5}, + {32, 3}, }; static state states_73[8] = { - {3, arcs_73_0}, - {2, arcs_73_1}, - {1, arcs_73_2}, - {1, arcs_73_3}, - {4, arcs_73_4}, - {2, arcs_73_5}, - {1, arcs_73_6}, - {2, arcs_73_7}, + {3, arcs_73_0}, + {2, arcs_73_1}, + {1, arcs_73_2}, + {1, arcs_73_3}, + {4, arcs_73_4}, + {2, arcs_73_5}, + {1, arcs_73_6}, + {2, arcs_73_7}, }; static arc arcs_74_0[1] = { - {24, 1}, + {24, 1}, }; static arc arcs_74_1[3] = { - {157, 2}, - {29, 3}, - {0, 1}, + {157, 2}, + {29, 3}, + {0, 1}, }; static arc arcs_74_2[1] = { - {0, 2}, + {0, 2}, }; static arc arcs_74_3[1] = { - {24, 2}, + {24, 2}, }; static state states_74[4] = { - {1, arcs_74_0}, - {3, arcs_74_1}, - {1, arcs_74_2}, - {1, arcs_74_3}, + {1, arcs_74_0}, + {3, arcs_74_1}, + {1, arcs_74_2}, + {1, arcs_74_3}, }; static arc arcs_75_0[2] = { - {157, 1}, - {164, 1}, + {157, 1}, + {164, 1}, }; static arc arcs_75_1[1] = { - {0, 1}, + {0, 1}, }; static state states_75[2] = { - {2, arcs_75_0}, - {1, arcs_75_1}, + {2, arcs_75_0}, + {1, arcs_75_1}, }; static arc arcs_76_0[1] = { - {94, 1}, + {94, 1}, }; static arc arcs_76_1[1] = { - {60, 2}, + {60, 2}, }; static arc arcs_76_2[1] = { - {95, 3}, + {95, 3}, }; static arc arcs_76_3[1] = { - {105, 4}, + {105, 4}, }; static arc arcs_76_4[2] = { - {163, 5}, - {0, 4}, + {163, 5}, + {0, 4}, }; static arc arcs_76_5[1] = { - {0, 5}, + {0, 5}, }; static state states_76[6] = { - {1, arcs_76_0}, - {1, arcs_76_1}, - {1, arcs_76_2}, - {1, arcs_76_3}, - {2, arcs_76_4}, - {1, arcs_76_5}, + {1, arcs_76_0}, + {1, arcs_76_1}, + {1, arcs_76_2}, + {1, arcs_76_3}, + {2, arcs_76_4}, + {1, arcs_76_5}, }; static arc arcs_77_0[1] = { - {90, 1}, + {90, 1}, }; static arc arcs_77_1[1] = { - {107, 2}, + {107, 2}, }; static arc arcs_77_2[2] = { - {163, 3}, - {0, 2}, + {163, 3}, + {0, 2}, }; static arc arcs_77_3[1] = { - {0, 3}, + {0, 3}, }; static state states_77[4] = { - {1, arcs_77_0}, - {1, arcs_77_1}, - {2, arcs_77_2}, - {1, arcs_77_3}, + {1, arcs_77_0}, + {1, arcs_77_1}, + {2, arcs_77_2}, + {1, arcs_77_3}, }; static arc arcs_78_0[1] = { - {24, 1}, + {24, 1}, }; static arc arcs_78_1[2] = { - {30, 0}, - {0, 1}, + {30, 0}, + {0, 1}, }; static state states_78[2] = { - {1, arcs_78_0}, - {2, arcs_78_1}, + {1, arcs_78_0}, + {2, arcs_78_1}, }; static arc arcs_79_0[1] = { - {21, 1}, + {21, 1}, }; static arc arcs_79_1[1] = { - {0, 1}, + {0, 1}, }; static state states_79[2] = { - {1, arcs_79_0}, - {1, arcs_79_1}, + {1, arcs_79_0}, + {1, arcs_79_1}, }; static arc arcs_80_0[1] = { - {167, 1}, + {167, 1}, }; static arc arcs_80_1[2] = { - {9, 2}, - {0, 1}, + {9, 2}, + {0, 1}, }; static arc arcs_80_2[1] = { - {0, 2}, + {0, 2}, }; static state states_80[3] = { - {1, arcs_80_0}, - {2, arcs_80_1}, - {1, arcs_80_2}, + {1, arcs_80_0}, + {2, arcs_80_1}, + {1, arcs_80_2}, }; static dfa dfas[81] = { - {256, "single_input", 0, 3, states_0, - "\004\050\060\200\000\000\000\050\370\044\034\144\011\040\004\000\000\103\050\037\202"}, - {257, "file_input", 0, 2, states_1, - "\204\050\060\200\000\000\000\050\370\044\034\144\011\040\004\000\000\103\050\037\202"}, - {258, "eval_input", 0, 3, states_2, - "\000\040\040\200\000\000\000\000\000\040\000\000\000\040\004\000\000\103\050\037\000"}, - {259, "decorator", 0, 7, states_3, - "\000\010\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000"}, - {260, "decorators", 0, 2, states_4, - "\000\010\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000"}, - {261, "decorated", 0, 3, states_5, - "\000\010\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000"}, - {262, "funcdef", 0, 8, states_6, - "\000\000\020\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000"}, - {263, "parameters", 0, 4, states_7, - "\000\040\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000"}, - {264, "typedargslist", 0, 12, states_8, - "\000\000\040\200\001\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000"}, - {265, "tfpdef", 0, 4, states_9, - "\000\000\040\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000"}, - {266, "varargslist", 0, 12, states_10, - "\000\000\040\200\001\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000"}, - {267, "vfpdef", 0, 2, states_11, - "\000\000\040\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000"}, - {268, "stmt", 0, 2, states_12, - "\000\050\060\200\000\000\000\050\370\044\034\144\011\040\004\000\000\103\050\037\202"}, - {269, "simple_stmt", 0, 4, states_13, - "\000\040\040\200\000\000\000\050\370\044\034\000\000\040\004\000\000\103\050\037\200"}, - {270, "small_stmt", 0, 2, states_14, - "\000\040\040\200\000\000\000\050\370\044\034\000\000\040\004\000\000\103\050\037\200"}, - {271, "expr_stmt", 0, 6, states_15, - "\000\040\040\200\000\000\000\000\000\040\000\000\000\040\004\000\000\103\050\037\000"}, - {272, "augassign", 0, 2, states_16, - "\000\000\000\000\000\200\377\007\000\000\000\000\000\000\000\000\000\000\000\000\000"}, - {273, "del_stmt", 0, 3, states_17, - "\000\000\000\000\000\000\000\010\000\000\000\000\000\000\000\000\000\000\000\000\000"}, - {274, "pass_stmt", 0, 2, states_18, - "\000\000\000\000\000\000\000\040\000\000\000\000\000\000\000\000\000\000\000\000\000"}, - {275, "flow_stmt", 0, 2, states_19, - "\000\000\000\000\000\000\000\000\170\000\000\000\000\000\000\000\000\000\000\000\200"}, - {276, "break_stmt", 0, 2, states_20, - "\000\000\000\000\000\000\000\000\010\000\000\000\000\000\000\000\000\000\000\000\000"}, - {277, "continue_stmt", 0, 2, states_21, - "\000\000\000\000\000\000\000\000\020\000\000\000\000\000\000\000\000\000\000\000\000"}, - {278, "return_stmt", 0, 3, states_22, - "\000\000\000\000\000\000\000\000\040\000\000\000\000\000\000\000\000\000\000\000\000"}, - {279, "yield_stmt", 0, 2, states_23, - "\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\200"}, - {280, "raise_stmt", 0, 5, states_24, - "\000\000\000\000\000\000\000\000\100\000\000\000\000\000\000\000\000\000\000\000\000"}, - {281, "import_stmt", 0, 2, states_25, - "\000\000\000\000\000\000\000\000\200\004\000\000\000\000\000\000\000\000\000\000\000"}, - {282, "import_name", 0, 3, states_26, - "\000\000\000\000\000\000\000\000\000\004\000\000\000\000\000\000\000\000\000\000\000"}, - {283, "import_from", 0, 8, states_27, - "\000\000\000\000\000\000\000\000\200\000\000\000\000\000\000\000\000\000\000\000\000"}, - {284, "import_as_name", 0, 4, states_28, - "\000\000\040\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000"}, - {285, "dotted_as_name", 0, 4, states_29, - "\000\000\040\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000"}, - {286, "import_as_names", 0, 3, states_30, - "\000\000\040\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000"}, - {287, "dotted_as_names", 0, 2, states_31, - "\000\000\040\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000"}, - {288, "dotted_name", 0, 2, states_32, - "\000\000\040\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000"}, - {289, "global_stmt", 0, 3, states_33, - "\000\000\000\000\000\000\000\000\000\000\004\000\000\000\000\000\000\000\000\000\000"}, - {290, "nonlocal_stmt", 0, 3, states_34, - "\000\000\000\000\000\000\000\000\000\000\010\000\000\000\000\000\000\000\000\000\000"}, - {291, "assert_stmt", 0, 5, states_35, - "\000\000\000\000\000\000\000\000\000\000\020\000\000\000\000\000\000\000\000\000\000"}, - {292, "compound_stmt", 0, 2, states_36, - "\000\010\020\000\000\000\000\000\000\000\000\144\011\000\000\000\000\000\000\000\002"}, - {293, "if_stmt", 0, 8, states_37, - "\000\000\000\000\000\000\000\000\000\000\000\004\000\000\000\000\000\000\000\000\000"}, - {294, "while_stmt", 0, 8, states_38, - "\000\000\000\000\000\000\000\000\000\000\000\040\000\000\000\000\000\000\000\000\000"}, - {295, "for_stmt", 0, 10, states_39, - "\000\000\000\000\000\000\000\000\000\000\000\100\000\000\000\000\000\000\000\000\000"}, - {296, "try_stmt", 0, 13, states_40, - "\000\000\000\000\000\000\000\000\000\000\000\000\001\000\000\000\000\000\000\000\000"}, - {297, "with_stmt", 0, 5, states_41, - "\000\000\000\000\000\000\000\000\000\000\000\000\010\000\000\000\000\000\000\000\000"}, - {298, "with_item", 0, 4, states_42, - "\000\040\040\200\000\000\000\000\000\040\000\000\000\040\004\000\000\103\050\037\000"}, - {299, "except_clause", 0, 5, states_43, - "\000\000\000\000\000\000\000\000\000\000\000\000\100\000\000\000\000\000\000\000\000"}, - {300, "suite", 0, 5, states_44, - "\004\040\040\200\000\000\000\050\370\044\034\000\000\040\004\000\000\103\050\037\200"}, - {301, "test", 0, 6, states_45, - "\000\040\040\200\000\000\000\000\000\040\000\000\000\040\004\000\000\103\050\037\000"}, - {302, "test_nocond", 0, 2, states_46, - "\000\040\040\200\000\000\000\000\000\040\000\000\000\040\004\000\000\103\050\037\000"}, - {303, "lambdef", 0, 5, states_47, - "\000\000\000\000\000\000\000\000\000\000\000\000\000\040\000\000\000\000\000\000\000"}, - {304, "lambdef_nocond", 0, 5, states_48, - "\000\000\000\000\000\000\000\000\000\000\000\000\000\040\000\000\000\000\000\000\000"}, - {305, "or_test", 0, 2, states_49, - "\000\040\040\200\000\000\000\000\000\040\000\000\000\000\004\000\000\103\050\037\000"}, - {306, "and_test", 0, 2, states_50, - "\000\040\040\200\000\000\000\000\000\040\000\000\000\000\004\000\000\103\050\037\000"}, - {307, "not_test", 0, 3, states_51, - "\000\040\040\200\000\000\000\000\000\040\000\000\000\000\004\000\000\103\050\037\000"}, - {308, "comparison", 0, 2, states_52, - "\000\040\040\200\000\000\000\000\000\040\000\000\000\000\000\000\000\103\050\037\000"}, - {309, "comp_op", 0, 4, states_53, - "\000\000\000\000\000\000\000\000\000\000\000\200\000\000\304\077\000\000\000\000\000"}, - {310, "star_expr", 0, 3, states_54, - "\000\040\040\200\000\000\000\000\000\040\000\000\000\000\000\000\000\103\050\037\000"}, - {311, "expr", 0, 2, states_55, - "\000\040\040\000\000\000\000\000\000\040\000\000\000\000\000\000\000\103\050\037\000"}, - {312, "xor_expr", 0, 2, states_56, - "\000\040\040\000\000\000\000\000\000\040\000\000\000\000\000\000\000\103\050\037\000"}, - {313, "and_expr", 0, 2, states_57, - "\000\040\040\000\000\000\000\000\000\040\000\000\000\000\000\000\000\103\050\037\000"}, - {314, "shift_expr", 0, 2, states_58, - "\000\040\040\000\000\000\000\000\000\040\000\000\000\000\000\000\000\103\050\037\000"}, - {315, "arith_expr", 0, 2, states_59, - "\000\040\040\000\000\000\000\000\000\040\000\000\000\000\000\000\000\103\050\037\000"}, - {316, "term", 0, 2, states_60, - "\000\040\040\000\000\000\000\000\000\040\000\000\000\000\000\000\000\103\050\037\000"}, - {317, "factor", 0, 3, states_61, - "\000\040\040\000\000\000\000\000\000\040\000\000\000\000\000\000\000\103\050\037\000"}, - {318, "power", 0, 4, states_62, - "\000\040\040\000\000\000\000\000\000\040\000\000\000\000\000\000\000\000\050\037\000"}, - {319, "atom", 0, 9, states_63, - "\000\040\040\000\000\000\000\000\000\040\000\000\000\000\000\000\000\000\050\037\000"}, - {320, "testlist_comp", 0, 5, states_64, - "\000\040\040\200\000\000\000\000\000\040\000\000\000\040\004\000\000\103\050\037\000"}, - {321, "trailer", 0, 7, states_65, - "\000\040\000\000\000\000\000\000\000\020\000\000\000\000\000\000\000\000\010\000\000"}, - {322, "subscriptlist", 0, 3, states_66, - "\000\040\040\202\000\000\000\000\000\040\000\000\000\040\004\000\000\103\050\037\000"}, - {323, "subscript", 0, 5, states_67, - "\000\040\040\202\000\000\000\000\000\040\000\000\000\040\004\000\000\103\050\037\000"}, - {324, "sliceop", 0, 3, states_68, - "\000\000\000\002\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000"}, - {325, "exprlist", 0, 3, states_69, - "\000\040\040\200\000\000\000\000\000\040\000\000\000\000\000\000\000\103\050\037\000"}, - {326, "testlist", 0, 3, states_70, - "\000\040\040\200\000\000\000\000\000\040\000\000\000\040\004\000\000\103\050\037\000"}, - {327, "dictorsetmaker", 0, 11, states_71, - "\000\040\040\200\000\000\000\000\000\040\000\000\000\040\004\000\000\103\050\037\000"}, - {328, "classdef", 0, 8, states_72, - "\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\002"}, - {329, "arglist", 0, 8, states_73, - "\000\040\040\200\001\000\000\000\000\040\000\000\000\040\004\000\000\103\050\037\000"}, - {330, "argument", 0, 4, states_74, - "\000\040\040\200\000\000\000\000\000\040\000\000\000\040\004\000\000\103\050\037\000"}, - {331, "comp_iter", 0, 2, states_75, - "\000\000\000\000\000\000\000\000\000\000\000\104\000\000\000\000\000\000\000\000\000"}, - {332, "comp_for", 0, 6, states_76, - "\000\000\000\000\000\000\000\000\000\000\000\100\000\000\000\000\000\000\000\000\000"}, - {333, "comp_if", 0, 4, states_77, - "\000\000\000\000\000\000\000\000\000\000\000\004\000\000\000\000\000\000\000\000\000"}, - {334, "testlist1", 0, 2, states_78, - "\000\040\040\200\000\000\000\000\000\040\000\000\000\040\004\000\000\103\050\037\000"}, - {335, "encoding_decl", 0, 2, states_79, - "\000\000\040\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000"}, - {336, "yield_expr", 0, 3, states_80, - "\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\200"}, + {256, "single_input", 0, 3, states_0, + "\004\050\060\200\000\000\000\050\370\044\034\144\011\040\004\000\000\103\050\037\202"}, + {257, "file_input", 0, 2, states_1, + "\204\050\060\200\000\000\000\050\370\044\034\144\011\040\004\000\000\103\050\037\202"}, + {258, "eval_input", 0, 3, states_2, + "\000\040\040\200\000\000\000\000\000\040\000\000\000\040\004\000\000\103\050\037\000"}, + {259, "decorator", 0, 7, states_3, + "\000\010\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000"}, + {260, "decorators", 0, 2, states_4, + "\000\010\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000"}, + {261, "decorated", 0, 3, states_5, + "\000\010\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000"}, + {262, "funcdef", 0, 8, states_6, + "\000\000\020\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000"}, + {263, "parameters", 0, 4, states_7, + "\000\040\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000"}, + {264, "typedargslist", 0, 12, states_8, + "\000\000\040\200\001\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000"}, + {265, "tfpdef", 0, 4, states_9, + "\000\000\040\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000"}, + {266, "varargslist", 0, 12, states_10, + "\000\000\040\200\001\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000"}, + {267, "vfpdef", 0, 2, states_11, + "\000\000\040\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000"}, + {268, "stmt", 0, 2, states_12, + "\000\050\060\200\000\000\000\050\370\044\034\144\011\040\004\000\000\103\050\037\202"}, + {269, "simple_stmt", 0, 4, states_13, + "\000\040\040\200\000\000\000\050\370\044\034\000\000\040\004\000\000\103\050\037\200"}, + {270, "small_stmt", 0, 2, states_14, + "\000\040\040\200\000\000\000\050\370\044\034\000\000\040\004\000\000\103\050\037\200"}, + {271, "expr_stmt", 0, 6, states_15, + "\000\040\040\200\000\000\000\000\000\040\000\000\000\040\004\000\000\103\050\037\000"}, + {272, "augassign", 0, 2, states_16, + "\000\000\000\000\000\200\377\007\000\000\000\000\000\000\000\000\000\000\000\000\000"}, + {273, "del_stmt", 0, 3, states_17, + "\000\000\000\000\000\000\000\010\000\000\000\000\000\000\000\000\000\000\000\000\000"}, + {274, "pass_stmt", 0, 2, states_18, + "\000\000\000\000\000\000\000\040\000\000\000\000\000\000\000\000\000\000\000\000\000"}, + {275, "flow_stmt", 0, 2, states_19, + "\000\000\000\000\000\000\000\000\170\000\000\000\000\000\000\000\000\000\000\000\200"}, + {276, "break_stmt", 0, 2, states_20, + "\000\000\000\000\000\000\000\000\010\000\000\000\000\000\000\000\000\000\000\000\000"}, + {277, "continue_stmt", 0, 2, states_21, + "\000\000\000\000\000\000\000\000\020\000\000\000\000\000\000\000\000\000\000\000\000"}, + {278, "return_stmt", 0, 3, states_22, + "\000\000\000\000\000\000\000\000\040\000\000\000\000\000\000\000\000\000\000\000\000"}, + {279, "yield_stmt", 0, 2, states_23, + "\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\200"}, + {280, "raise_stmt", 0, 5, states_24, + "\000\000\000\000\000\000\000\000\100\000\000\000\000\000\000\000\000\000\000\000\000"}, + {281, "import_stmt", 0, 2, states_25, + "\000\000\000\000\000\000\000\000\200\004\000\000\000\000\000\000\000\000\000\000\000"}, + {282, "import_name", 0, 3, states_26, + "\000\000\000\000\000\000\000\000\000\004\000\000\000\000\000\000\000\000\000\000\000"}, + {283, "import_from", 0, 8, states_27, + "\000\000\000\000\000\000\000\000\200\000\000\000\000\000\000\000\000\000\000\000\000"}, + {284, "import_as_name", 0, 4, states_28, + "\000\000\040\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000"}, + {285, "dotted_as_name", 0, 4, states_29, + "\000\000\040\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000"}, + {286, "import_as_names", 0, 3, states_30, + "\000\000\040\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000"}, + {287, "dotted_as_names", 0, 2, states_31, + "\000\000\040\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000"}, + {288, "dotted_name", 0, 2, states_32, + "\000\000\040\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000"}, + {289, "global_stmt", 0, 3, states_33, + "\000\000\000\000\000\000\000\000\000\000\004\000\000\000\000\000\000\000\000\000\000"}, + {290, "nonlocal_stmt", 0, 3, states_34, + "\000\000\000\000\000\000\000\000\000\000\010\000\000\000\000\000\000\000\000\000\000"}, + {291, "assert_stmt", 0, 5, states_35, + "\000\000\000\000\000\000\000\000\000\000\020\000\000\000\000\000\000\000\000\000\000"}, + {292, "compound_stmt", 0, 2, states_36, + "\000\010\020\000\000\000\000\000\000\000\000\144\011\000\000\000\000\000\000\000\002"}, + {293, "if_stmt", 0, 8, states_37, + "\000\000\000\000\000\000\000\000\000\000\000\004\000\000\000\000\000\000\000\000\000"}, + {294, "while_stmt", 0, 8, states_38, + "\000\000\000\000\000\000\000\000\000\000\000\040\000\000\000\000\000\000\000\000\000"}, + {295, "for_stmt", 0, 10, states_39, + "\000\000\000\000\000\000\000\000\000\000\000\100\000\000\000\000\000\000\000\000\000"}, + {296, "try_stmt", 0, 13, states_40, + "\000\000\000\000\000\000\000\000\000\000\000\000\001\000\000\000\000\000\000\000\000"}, + {297, "with_stmt", 0, 5, states_41, + "\000\000\000\000\000\000\000\000\000\000\000\000\010\000\000\000\000\000\000\000\000"}, + {298, "with_item", 0, 4, states_42, + "\000\040\040\200\000\000\000\000\000\040\000\000\000\040\004\000\000\103\050\037\000"}, + {299, "except_clause", 0, 5, states_43, + "\000\000\000\000\000\000\000\000\000\000\000\000\100\000\000\000\000\000\000\000\000"}, + {300, "suite", 0, 5, states_44, + "\004\040\040\200\000\000\000\050\370\044\034\000\000\040\004\000\000\103\050\037\200"}, + {301, "test", 0, 6, states_45, + "\000\040\040\200\000\000\000\000\000\040\000\000\000\040\004\000\000\103\050\037\000"}, + {302, "test_nocond", 0, 2, states_46, + "\000\040\040\200\000\000\000\000\000\040\000\000\000\040\004\000\000\103\050\037\000"}, + {303, "lambdef", 0, 5, states_47, + "\000\000\000\000\000\000\000\000\000\000\000\000\000\040\000\000\000\000\000\000\000"}, + {304, "lambdef_nocond", 0, 5, states_48, + "\000\000\000\000\000\000\000\000\000\000\000\000\000\040\000\000\000\000\000\000\000"}, + {305, "or_test", 0, 2, states_49, + "\000\040\040\200\000\000\000\000\000\040\000\000\000\000\004\000\000\103\050\037\000"}, + {306, "and_test", 0, 2, states_50, + "\000\040\040\200\000\000\000\000\000\040\000\000\000\000\004\000\000\103\050\037\000"}, + {307, "not_test", 0, 3, states_51, + "\000\040\040\200\000\000\000\000\000\040\000\000\000\000\004\000\000\103\050\037\000"}, + {308, "comparison", 0, 2, states_52, + "\000\040\040\200\000\000\000\000\000\040\000\000\000\000\000\000\000\103\050\037\000"}, + {309, "comp_op", 0, 4, states_53, + "\000\000\000\000\000\000\000\000\000\000\000\200\000\000\304\077\000\000\000\000\000"}, + {310, "star_expr", 0, 3, states_54, + "\000\040\040\200\000\000\000\000\000\040\000\000\000\000\000\000\000\103\050\037\000"}, + {311, "expr", 0, 2, states_55, + "\000\040\040\000\000\000\000\000\000\040\000\000\000\000\000\000\000\103\050\037\000"}, + {312, "xor_expr", 0, 2, states_56, + "\000\040\040\000\000\000\000\000\000\040\000\000\000\000\000\000\000\103\050\037\000"}, + {313, "and_expr", 0, 2, states_57, + "\000\040\040\000\000\000\000\000\000\040\000\000\000\000\000\000\000\103\050\037\000"}, + {314, "shift_expr", 0, 2, states_58, + "\000\040\040\000\000\000\000\000\000\040\000\000\000\000\000\000\000\103\050\037\000"}, + {315, "arith_expr", 0, 2, states_59, + "\000\040\040\000\000\000\000\000\000\040\000\000\000\000\000\000\000\103\050\037\000"}, + {316, "term", 0, 2, states_60, + "\000\040\040\000\000\000\000\000\000\040\000\000\000\000\000\000\000\103\050\037\000"}, + {317, "factor", 0, 3, states_61, + "\000\040\040\000\000\000\000\000\000\040\000\000\000\000\000\000\000\103\050\037\000"}, + {318, "power", 0, 4, states_62, + "\000\040\040\000\000\000\000\000\000\040\000\000\000\000\000\000\000\000\050\037\000"}, + {319, "atom", 0, 9, states_63, + "\000\040\040\000\000\000\000\000\000\040\000\000\000\000\000\000\000\000\050\037\000"}, + {320, "testlist_comp", 0, 5, states_64, + "\000\040\040\200\000\000\000\000\000\040\000\000\000\040\004\000\000\103\050\037\000"}, + {321, "trailer", 0, 7, states_65, + "\000\040\000\000\000\000\000\000\000\020\000\000\000\000\000\000\000\000\010\000\000"}, + {322, "subscriptlist", 0, 3, states_66, + "\000\040\040\202\000\000\000\000\000\040\000\000\000\040\004\000\000\103\050\037\000"}, + {323, "subscript", 0, 5, states_67, + "\000\040\040\202\000\000\000\000\000\040\000\000\000\040\004\000\000\103\050\037\000"}, + {324, "sliceop", 0, 3, states_68, + "\000\000\000\002\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000"}, + {325, "exprlist", 0, 3, states_69, + "\000\040\040\200\000\000\000\000\000\040\000\000\000\000\000\000\000\103\050\037\000"}, + {326, "testlist", 0, 3, states_70, + "\000\040\040\200\000\000\000\000\000\040\000\000\000\040\004\000\000\103\050\037\000"}, + {327, "dictorsetmaker", 0, 11, states_71, + "\000\040\040\200\000\000\000\000\000\040\000\000\000\040\004\000\000\103\050\037\000"}, + {328, "classdef", 0, 8, states_72, + "\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\002"}, + {329, "arglist", 0, 8, states_73, + "\000\040\040\200\001\000\000\000\000\040\000\000\000\040\004\000\000\103\050\037\000"}, + {330, "argument", 0, 4, states_74, + "\000\040\040\200\000\000\000\000\000\040\000\000\000\040\004\000\000\103\050\037\000"}, + {331, "comp_iter", 0, 2, states_75, + "\000\000\000\000\000\000\000\000\000\000\000\104\000\000\000\000\000\000\000\000\000"}, + {332, "comp_for", 0, 6, states_76, + "\000\000\000\000\000\000\000\000\000\000\000\100\000\000\000\000\000\000\000\000\000"}, + {333, "comp_if", 0, 4, states_77, + "\000\000\000\000\000\000\000\000\000\000\000\004\000\000\000\000\000\000\000\000\000"}, + {334, "testlist1", 0, 2, states_78, + "\000\040\040\200\000\000\000\000\000\040\000\000\000\040\004\000\000\103\050\037\000"}, + {335, "encoding_decl", 0, 2, states_79, + "\000\000\040\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000"}, + {336, "yield_expr", 0, 3, states_80, + "\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\200"}, }; static label labels[168] = { - {0, "EMPTY"}, - {256, 0}, - {4, 0}, - {269, 0}, - {292, 0}, - {257, 0}, - {268, 0}, - {0, 0}, - {258, 0}, - {326, 0}, - {259, 0}, - {50, 0}, - {288, 0}, - {7, 0}, - {329, 0}, - {8, 0}, - {260, 0}, - {261, 0}, - {328, 0}, - {262, 0}, - {1, "def"}, - {1, 0}, - {263, 0}, - {51, 0}, - {301, 0}, - {11, 0}, - {300, 0}, - {264, 0}, - {265, 0}, - {22, 0}, - {12, 0}, - {16, 0}, - {36, 0}, - {266, 0}, - {267, 0}, - {270, 0}, - {13, 0}, - {271, 0}, - {273, 0}, - {274, 0}, - {275, 0}, - {281, 0}, - {289, 0}, - {290, 0}, - {291, 0}, - {272, 0}, - {336, 0}, - {37, 0}, - {38, 0}, - {39, 0}, - {40, 0}, - {41, 0}, - {42, 0}, - {43, 0}, - {44, 0}, - {45, 0}, - {46, 0}, - {47, 0}, - {49, 0}, - {1, "del"}, - {325, 0}, - {1, "pass"}, - {276, 0}, - {277, 0}, - {278, 0}, - {280, 0}, - {279, 0}, - {1, "break"}, - {1, "continue"}, - {1, "return"}, - {1, "raise"}, - {1, "from"}, - {282, 0}, - {283, 0}, - {1, "import"}, - {287, 0}, - {23, 0}, - {52, 0}, - {286, 0}, - {284, 0}, - {1, "as"}, - {285, 0}, - {1, "global"}, - {1, "nonlocal"}, - {1, "assert"}, - {293, 0}, - {294, 0}, - {295, 0}, - {296, 0}, - {297, 0}, - {1, "if"}, - {1, "elif"}, - {1, "else"}, - {1, "while"}, - {1, "for"}, - {1, "in"}, - {1, "try"}, - {299, 0}, - {1, "finally"}, - {1, "with"}, - {298, 0}, - {311, 0}, - {1, "except"}, - {5, 0}, - {6, 0}, - {305, 0}, - {303, 0}, - {302, 0}, - {304, 0}, - {1, "lambda"}, - {306, 0}, - {1, "or"}, - {307, 0}, - {1, "and"}, - {1, "not"}, - {308, 0}, - {310, 0}, - {309, 0}, - {20, 0}, - {21, 0}, - {28, 0}, - {31, 0}, - {30, 0}, - {29, 0}, - {29, 0}, - {1, "is"}, - {312, 0}, - {18, 0}, - {313, 0}, - {33, 0}, - {314, 0}, - {19, 0}, - {315, 0}, - {34, 0}, - {35, 0}, - {316, 0}, - {14, 0}, - {15, 0}, - {317, 0}, - {17, 0}, - {24, 0}, - {48, 0}, - {32, 0}, - {318, 0}, - {319, 0}, - {321, 0}, - {320, 0}, - {9, 0}, - {10, 0}, - {26, 0}, - {327, 0}, - {27, 0}, - {2, 0}, - {3, 0}, - {1, "None"}, - {1, "True"}, - {1, "False"}, - {332, 0}, - {322, 0}, - {323, 0}, - {324, 0}, - {1, "class"}, - {330, 0}, - {331, 0}, - {333, 0}, - {334, 0}, - {335, 0}, - {1, "yield"}, + {0, "EMPTY"}, + {256, 0}, + {4, 0}, + {269, 0}, + {292, 0}, + {257, 0}, + {268, 0}, + {0, 0}, + {258, 0}, + {326, 0}, + {259, 0}, + {50, 0}, + {288, 0}, + {7, 0}, + {329, 0}, + {8, 0}, + {260, 0}, + {261, 0}, + {328, 0}, + {262, 0}, + {1, "def"}, + {1, 0}, + {263, 0}, + {51, 0}, + {301, 0}, + {11, 0}, + {300, 0}, + {264, 0}, + {265, 0}, + {22, 0}, + {12, 0}, + {16, 0}, + {36, 0}, + {266, 0}, + {267, 0}, + {270, 0}, + {13, 0}, + {271, 0}, + {273, 0}, + {274, 0}, + {275, 0}, + {281, 0}, + {289, 0}, + {290, 0}, + {291, 0}, + {272, 0}, + {336, 0}, + {37, 0}, + {38, 0}, + {39, 0}, + {40, 0}, + {41, 0}, + {42, 0}, + {43, 0}, + {44, 0}, + {45, 0}, + {46, 0}, + {47, 0}, + {49, 0}, + {1, "del"}, + {325, 0}, + {1, "pass"}, + {276, 0}, + {277, 0}, + {278, 0}, + {280, 0}, + {279, 0}, + {1, "break"}, + {1, "continue"}, + {1, "return"}, + {1, "raise"}, + {1, "from"}, + {282, 0}, + {283, 0}, + {1, "import"}, + {287, 0}, + {23, 0}, + {52, 0}, + {286, 0}, + {284, 0}, + {1, "as"}, + {285, 0}, + {1, "global"}, + {1, "nonlocal"}, + {1, "assert"}, + {293, 0}, + {294, 0}, + {295, 0}, + {296, 0}, + {297, 0}, + {1, "if"}, + {1, "elif"}, + {1, "else"}, + {1, "while"}, + {1, "for"}, + {1, "in"}, + {1, "try"}, + {299, 0}, + {1, "finally"}, + {1, "with"}, + {298, 0}, + {311, 0}, + {1, "except"}, + {5, 0}, + {6, 0}, + {305, 0}, + {303, 0}, + {302, 0}, + {304, 0}, + {1, "lambda"}, + {306, 0}, + {1, "or"}, + {307, 0}, + {1, "and"}, + {1, "not"}, + {308, 0}, + {310, 0}, + {309, 0}, + {20, 0}, + {21, 0}, + {28, 0}, + {31, 0}, + {30, 0}, + {29, 0}, + {29, 0}, + {1, "is"}, + {312, 0}, + {18, 0}, + {313, 0}, + {33, 0}, + {314, 0}, + {19, 0}, + {315, 0}, + {34, 0}, + {35, 0}, + {316, 0}, + {14, 0}, + {15, 0}, + {317, 0}, + {17, 0}, + {24, 0}, + {48, 0}, + {32, 0}, + {318, 0}, + {319, 0}, + {321, 0}, + {320, 0}, + {9, 0}, + {10, 0}, + {26, 0}, + {327, 0}, + {27, 0}, + {2, 0}, + {3, 0}, + {1, "None"}, + {1, "True"}, + {1, "False"}, + {332, 0}, + {322, 0}, + {323, 0}, + {324, 0}, + {1, "class"}, + {330, 0}, + {331, 0}, + {333, 0}, + {334, 0}, + {335, 0}, + {1, "yield"}, }; grammar _PyParser_Grammar = { - 81, - dfas, - {168, labels}, - 256 + 81, + dfas, + {168, labels}, + 256 }; From solipsis at pitrou.net Sun May 16 01:24:46 2010 From: solipsis at pitrou.net (solipsis at pitrou.net) Date: Sun, 16 May 2010 01:24:46 +0200 (CEST) Subject: [Python-checkins] Daily py3k reference leaks (r81207): sum=0 Message-ID: <20100515232446.CB1131770A@ns6635.ovh.net> py3k results for svn r81207 (hg cset 2e34949f9eb4) -------------------------------------------------- Command line was: ['./python', '-m', 'test.regrtest', '-uall', '-R', '3:3:/home/antoine/py3k/refleaks/reflogNuv49h', '-x'] From python-checkins at python.org Sun May 16 02:34:40 2010 From: python-checkins at python.org (victor.stinner) Date: Sun, 16 May 2010 02:34:40 +0200 (CEST) Subject: [Python-checkins] r81224 - python/trunk/Lib/test/list_tests.py Message-ID: <20100516003440.75FD1EE98B@mail.python.org> Author: victor.stinner Date: Sun May 16 02:34:40 2010 New Revision: 81224 Log: Use with open() as fo: ... instead of try: fo = open(...) finally: fo.close() fo is not set if the open() fails. Modified: python/trunk/Lib/test/list_tests.py Modified: python/trunk/Lib/test/list_tests.py ============================================================================== --- python/trunk/Lib/test/list_tests.py (original) +++ python/trunk/Lib/test/list_tests.py Sun May 16 02:34:40 2010 @@ -57,13 +57,11 @@ d.append(d) d.append(400) try: - fo = open(test_support.TESTFN, "wb") - print >> fo, d, - fo.close() - fo = open(test_support.TESTFN, "rb") - self.assertEqual(fo.read(), repr(d)) + with open(test_support.TESTFN, "wb") as fo: + print >> fo, d, + with open(test_support.TESTFN, "rb") as fo: + self.assertEqual(fo.read(), repr(d)) finally: - fo.close() os.remove(test_support.TESTFN) def test_set_subscript(self): From python-checkins at python.org Sun May 16 02:35:43 2010 From: python-checkins at python.org (victor.stinner) Date: Sun, 16 May 2010 02:35:43 +0200 (CEST) Subject: [Python-checkins] r81225 - in python/branches/release26-maint: Lib/test/list_tests.py Message-ID: <20100516003543.C1839EEAF1@mail.python.org> Author: victor.stinner Date: Sun May 16 02:35:43 2010 New Revision: 81225 Log: Merged revisions 81224 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r81224 | victor.stinner | 2010-05-16 02:34:40 +0200 (dim., 16 mai 2010) | 4 lines Use with open() as fo: ... instead of try: fo = open(...) finally: fo.close() fo is not set if the open() fails. ........ Modified: python/branches/release26-maint/ (props changed) python/branches/release26-maint/Lib/test/list_tests.py Modified: python/branches/release26-maint/Lib/test/list_tests.py ============================================================================== --- python/branches/release26-maint/Lib/test/list_tests.py (original) +++ python/branches/release26-maint/Lib/test/list_tests.py Sun May 16 02:35:43 2010 @@ -57,13 +57,11 @@ d.append(d) d.append(400) try: - fo = open(test_support.TESTFN, "wb") - print >> fo, d, - fo.close() - fo = open(test_support.TESTFN, "rb") - self.assertEqual(fo.read(), repr(d)) + with open(test_support.TESTFN, "wb") as fo: + print >> fo, d, + with open(test_support.TESTFN, "rb") as fo: + self.assertEqual(fo.read(), repr(d)) finally: - fo.close() os.remove(test_support.TESTFN) def test_set_subscript(self): From python-checkins at python.org Sun May 16 02:36:38 2010 From: python-checkins at python.org (victor.stinner) Date: Sun, 16 May 2010 02:36:38 +0200 (CEST) Subject: [Python-checkins] r81226 - in python/branches/py3k: Lib/test/list_tests.py Message-ID: <20100516003638.A490DEE996@mail.python.org> Author: victor.stinner Date: Sun May 16 02:36:38 2010 New Revision: 81226 Log: Merged revisions 81224 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r81224 | victor.stinner | 2010-05-16 02:34:40 +0200 (dim., 16 mai 2010) | 4 lines Use with open() as fo: ... instead of try: fo = open(...) finally: fo.close() fo is not set if the open() fails. ........ Modified: python/branches/py3k/ (props changed) python/branches/py3k/Lib/test/list_tests.py Modified: python/branches/py3k/Lib/test/list_tests.py ============================================================================== --- python/branches/py3k/Lib/test/list_tests.py (original) +++ python/branches/py3k/Lib/test/list_tests.py Sun May 16 02:36:38 2010 @@ -66,13 +66,11 @@ d.append(d) d.append(400) try: - fo = open(support.TESTFN, "w") - fo.write(str(d)) - fo.close() - fo = open(support.TESTFN, "r") - self.assertEqual(fo.read(), repr(d)) + with open(support.TESTFN, "w") as fo: + fo.write(str(d)) + with open(support.TESTFN, "r") as fo: + self.assertEqual(fo.read(), repr(d)) finally: - fo.close() os.remove(support.TESTFN) def test_set_subscript(self): From python-checkins at python.org Sun May 16 02:37:36 2010 From: python-checkins at python.org (victor.stinner) Date: Sun, 16 May 2010 02:37:36 +0200 (CEST) Subject: [Python-checkins] r81227 - in python/branches/release31-maint: Lib/test/list_tests.py Message-ID: <20100516003736.B3FEAEE9E4@mail.python.org> Author: victor.stinner Date: Sun May 16 02:37:36 2010 New Revision: 81227 Log: Merged revisions 81226 via svnmerge from svn+ssh://pythondev at svn.python.org/python/branches/py3k ................ r81226 | victor.stinner | 2010-05-16 02:36:38 +0200 (dim., 16 mai 2010) | 11 lines Merged revisions 81224 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r81224 | victor.stinner | 2010-05-16 02:34:40 +0200 (dim., 16 mai 2010) | 4 lines Use with open() as fo: ... instead of try: fo = open(...) finally: fo.close() fo is not set if the open() fails. ........ ................ Modified: python/branches/release31-maint/ (props changed) python/branches/release31-maint/Lib/test/list_tests.py Modified: python/branches/release31-maint/Lib/test/list_tests.py ============================================================================== --- python/branches/release31-maint/Lib/test/list_tests.py (original) +++ python/branches/release31-maint/Lib/test/list_tests.py Sun May 16 02:37:36 2010 @@ -66,13 +66,11 @@ d.append(d) d.append(400) try: - fo = open(support.TESTFN, "w") - fo.write(str(d)) - fo.close() - fo = open(support.TESTFN, "r") - self.assertEqual(fo.read(), repr(d)) + with open(support.TESTFN, "w") as fo: + fo.write(str(d)) + with open(support.TESTFN, "r") as fo: + self.assertEqual(fo.read(), repr(d)) finally: - fo.close() os.remove(support.TESTFN) def test_set_subscript(self): From python-checkins at python.org Sun May 16 10:39:09 2010 From: python-checkins at python.org (mark.dickinson) Date: Sun, 16 May 2010 10:39:09 +0200 (CEST) Subject: [Python-checkins] r81228 - python/branches/release31-maint Message-ID: <20100516083909.500F0EE981@mail.python.org> Author: mark.dickinson Date: Sun May 16 10:39:09 2010 New Revision: 81228 Log: Blocked revisions 81196 via svnmerge ........ r81196 | mark.dickinson | 2010-05-15 18:02:38 +0100 (Sat, 15 May 2010) | 13 lines Issue #8692: Improve performance of math.factorial: (1) use a different algorithm that roughly halves the total number of multiplications required and results in more balanced multiplications (2) use a lookup table for small arguments (3) fast accumulation of products in C integer arithmetic rather than PyLong arithmetic when possible. Typical speedup, from unscientific testing on a 64-bit laptop, is 4.5x to 6.5x for arguments in the range 100 - 10000. Patch by Daniel Stutzbach; extensive reviews by Alexander Belopolsky. ........ Modified: python/branches/release31-maint/ (props changed) From python-checkins at python.org Sun May 16 16:16:56 2010 From: python-checkins at python.org (antoine.pitrou) Date: Sun, 16 May 2010 16:16:56 +0200 (CEST) Subject: [Python-checkins] r81229 - python/trunk/Doc/library/ssl.rst Message-ID: <20100516141656.6AAF6EE98E@mail.python.org> Author: antoine.pitrou Date: Sun May 16 16:16:56 2010 New Revision: 81229 Log: Document that SSL v2 is insecure. Modified: python/trunk/Doc/library/ssl.rst Modified: python/trunk/Doc/library/ssl.rst ============================================================================== --- python/trunk/Doc/library/ssl.rst (original) +++ python/trunk/Doc/library/ssl.rst Sun May 16 16:16:56 2010 @@ -237,6 +237,10 @@ Selects SSL version 2 as the channel encryption protocol. + .. warning:: + + SSL version 2 is insecure. Its use is highly discouraged. + .. data:: PROTOCOL_SSLv23 Selects SSL version 2 or 3 as the channel encryption protocol. This is a From python-checkins at python.org Sun May 16 16:17:51 2010 From: python-checkins at python.org (antoine.pitrou) Date: Sun, 16 May 2010 16:17:51 +0200 (CEST) Subject: [Python-checkins] r81230 - in python/branches/release26-maint: Doc/library/ssl.rst Message-ID: <20100516141751.C925AEE98E@mail.python.org> Author: antoine.pitrou Date: Sun May 16 16:17:51 2010 New Revision: 81230 Log: Merged revisions 81229 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r81229 | antoine.pitrou | 2010-05-16 16:16:56 +0200 (dim., 16 mai 2010) | 3 lines Document that SSL v2 is insecure. ........ Modified: python/branches/release26-maint/ (props changed) python/branches/release26-maint/Doc/library/ssl.rst Modified: python/branches/release26-maint/Doc/library/ssl.rst ============================================================================== --- python/branches/release26-maint/Doc/library/ssl.rst (original) +++ python/branches/release26-maint/Doc/library/ssl.rst Sun May 16 16:17:51 2010 @@ -222,6 +222,10 @@ Selects SSL version 2 as the channel encryption protocol. + .. warning:: + + SSL version 2 is insecure. Its use is highly discouraged. + .. data:: PROTOCOL_SSLv23 Selects SSL version 2 or 3 as the channel encryption protocol. This is a From python-checkins at python.org Sun May 16 16:19:41 2010 From: python-checkins at python.org (antoine.pitrou) Date: Sun, 16 May 2010 16:19:41 +0200 (CEST) Subject: [Python-checkins] r81231 - in python/branches/py3k: Doc/library/ssl.rst Message-ID: <20100516141941.67681EE9B8@mail.python.org> Author: antoine.pitrou Date: Sun May 16 16:19:41 2010 New Revision: 81231 Log: Merged revisions 81229 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r81229 | antoine.pitrou | 2010-05-16 16:16:56 +0200 (dim., 16 mai 2010) | 3 lines Document that SSL v2 is insecure. ........ Modified: python/branches/py3k/ (props changed) python/branches/py3k/Doc/library/ssl.rst Modified: python/branches/py3k/Doc/library/ssl.rst ============================================================================== --- python/branches/py3k/Doc/library/ssl.rst (original) +++ python/branches/py3k/Doc/library/ssl.rst Sun May 16 16:19:41 2010 @@ -231,6 +231,10 @@ Selects SSL version 2 as the channel encryption protocol. + .. warning:: + + SSL version 2 is insecure. Its use is highly discouraged. + .. data:: PROTOCOL_SSLv23 Selects SSL version 2 or 3 as the channel encryption protocol. This is a From python-checkins at python.org Sun May 16 16:20:17 2010 From: python-checkins at python.org (antoine.pitrou) Date: Sun, 16 May 2010 16:20:17 +0200 (CEST) Subject: [Python-checkins] r81232 - in python/branches/release31-maint: Doc/library/ssl.rst Message-ID: <20100516142017.7DDDDEE9B8@mail.python.org> Author: antoine.pitrou Date: Sun May 16 16:20:17 2010 New Revision: 81232 Log: Merged revisions 81231 via svnmerge from svn+ssh://pythondev at svn.python.org/python/branches/py3k ................ r81231 | antoine.pitrou | 2010-05-16 16:19:41 +0200 (dim., 16 mai 2010) | 9 lines Merged revisions 81229 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r81229 | antoine.pitrou | 2010-05-16 16:16:56 +0200 (dim., 16 mai 2010) | 3 lines Document that SSL v2 is insecure. ........ ................ Modified: python/branches/release31-maint/ (props changed) python/branches/release31-maint/Doc/library/ssl.rst Modified: python/branches/release31-maint/Doc/library/ssl.rst ============================================================================== --- python/branches/release31-maint/Doc/library/ssl.rst (original) +++ python/branches/release31-maint/Doc/library/ssl.rst Sun May 16 16:20:17 2010 @@ -219,6 +219,10 @@ Selects SSL version 2 as the channel encryption protocol. + .. warning:: + + SSL version 2 is insecure. Its use is highly discouraged. + .. data:: PROTOCOL_SSLv23 Selects SSL version 2 or 3 as the channel encryption protocol. This is a From python-checkins at python.org Sun May 16 20:19:27 2010 From: python-checkins at python.org (antoine.pitrou) Date: Sun, 16 May 2010 20:19:27 +0200 (CEST) Subject: [Python-checkins] r81233 - in python/branches/py3k: Doc/library/ssl.rst Lib/ssl.py Lib/test/capath Lib/test/capath/6e88d7b8.0 Lib/test/capath/99d0fa06.0 Lib/test/test_ssl.py Misc/NEWS Modules/_ssl.c Message-ID: <20100516181927.8329FEEB15@mail.python.org> Author: antoine.pitrou Date: Sun May 16 20:19:27 2010 New Revision: 81233 Log: Issue #8550: Add first class `SSLContext` objects to the ssl module. Added: python/branches/py3k/Lib/test/capath/ python/branches/py3k/Lib/test/capath/6e88d7b8.0 python/branches/py3k/Lib/test/capath/99d0fa06.0 Modified: python/branches/py3k/Doc/library/ssl.rst python/branches/py3k/Lib/ssl.py python/branches/py3k/Lib/test/test_ssl.py python/branches/py3k/Misc/NEWS python/branches/py3k/Modules/_ssl.c Modified: python/branches/py3k/Doc/library/ssl.rst ============================================================================== --- python/branches/py3k/Doc/library/ssl.rst (original) +++ python/branches/py3k/Doc/library/ssl.rst Sun May 16 20:19:27 2010 @@ -36,6 +36,11 @@ connection, and a method, :meth:`cipher`, to retrieve the cipher being used for the secure connection. +For more sophisticated applications, the :class:`ssl.SSLContext` class +helps manage settings and certificates, which can then be inherited +by SSL sockets created through the :meth:`SSLContext.wrap_socket` method. + + Functions, Constants, and Exceptions ------------------------------------ @@ -64,19 +69,6 @@ connection. See the discussion of :ref:`ssl-certificates` for more information on how the certificate is stored in the ``certfile``. - Often the private key is stored in the same file as the certificate; in this - case, only the ``certfile`` parameter need be passed. If the private key is - stored in a separate file, both parameters must be used. If the private key - is stored in the ``certfile``, it should come before the first certificate in - the certificate chain:: - - -----BEGIN RSA PRIVATE KEY----- - ... (private key in base64 encoding) ... - -----END RSA PRIVATE KEY----- - -----BEGIN CERTIFICATE----- - ... (certificate in base64 PEM encoding) ... - -----END CERTIFICATE----- - The parameter ``server_side`` is a boolean which identifies whether server-side or client-side behavior is desired from this socket. @@ -208,24 +200,36 @@ .. data:: CERT_NONE - Value to pass to the ``cert_reqs`` parameter to :func:`sslobject` when no - certificates will be required or validated from the other side of the socket - connection. + Possible value for :attr:`SSLContext.verify_mode`, or the ``cert_reqs`` + parameter to :func:`wrap_socket`. In this mode (the default), no + certificates will be required from the other side of the socket connection. + If a certificate is received from the other end, no attempt to validate it + is made. + + See the discussion of :ref:`ssl-security` below. .. data:: CERT_OPTIONAL - Value to pass to the ``cert_reqs`` parameter to :func:`sslobject` when no - certificates will be required from the other side of the socket connection, - but if they are provided, will be validated. Note that use of this setting - requires a valid certificate validation file also be passed as a value of the - ``ca_certs`` parameter. + Possible value for :attr:`SSLContext.verify_mode`, or the ``cert_reqs`` + parameter to :func:`wrap_socket`. In this mode no certificates will be + required from the other side of the socket connection; but if they + are provided, validation will be attempted and an :class:`SSLError` + will be raised on failure. + + Use of this setting requires a valid set of CA certificates to + be passed, either to :meth:`SSLContext.load_verify_locations` or as a + value of the ``ca_certs`` parameter to :func:`wrap_socket`. .. data:: CERT_REQUIRED - Value to pass to the ``cert_reqs`` parameter to :func:`sslobject` when - certificates will be required from the other side of the socket connection. - Note that use of this setting requires a valid certificate validation file - also be passed as a value of the ``ca_certs`` parameter. + Possible value for :attr:`SSLContext.verify_mode`, or the ``cert_reqs`` + parameter to :func:`wrap_socket`. In this mode, certificates are + required from the other side of the socket connection; an :class:`SSLError` + will be raised if no certificate is provided, or if its validation fails. + + Use of this setting requires a valid set of CA certificates to + be passed, either to :meth:`SSLContext.load_verify_locations` or as a + value of the ``ca_certs`` parameter to :func:`wrap_socket`. .. data:: PROTOCOL_SSLv2 @@ -284,8 +288,8 @@ .. versionadded:: 3.2 -SSLSocket Objects ------------------ +SSL Sockets +----------- .. method:: SSLSocket.read(nbytes=1024, buffer=None) @@ -371,6 +375,83 @@ returned socket should always be used for further communication with the other side of the connection, rather than the original socket. + +SSL Contexts +------------ + +.. class:: SSLContext(protocol) + + An object holding various data longer-lived than single SSL connections, + such as SSL configuration options, certificate(s) and private key(s). + You must pass *protocol* which must be one of the ``PROTOCOL_*`` constants + defined in this module. :data:`PROTOCOL_SSLv23` is recommended for + maximum interoperability. + +:class:`SSLContext` objects have the following methods and attributes: + +.. method:: SSLContext.load_cert_chain(certfile, keyfile=None) + + Load a private key and the corresponding certificate. The *certfile* + string must be the path to a single file in PEM format containing the + certificate as well as any number of CA certificates needed to establish + the certificate's authenticity. The *keyfile* string, if present, must + point to a file containing the private key in. Otherwise the private + key will be taken from *certfile* as well. See the discussion of + :ref:`ssl-certificates` for more information on how the certificate + is stored in the *certfile*. + + An :class:`SSLError` is raised if the private key doesn't + match with the certificate. + +.. method:: SSLContext.load_verify_locations(cafile=None, capath=None) + + Load a set of "certification authority" (CA) certificates used to validate + other peers' certificates when :data:`verify_mode` is other than + :data:`CERT_NONE`. At least one of *cafile* or *capath* must be specified. + + The *cafile* string, if present, is the path to a file of concatenated + CA certificates in PEM format. See the discussion of + :ref:`ssl-certificates` for more information about how to arrange the + certificates in this file. + + The *capath* string, if present, is + the path to a directory containing several CA certificates in PEM format, + following an `OpenSSL specific layout + `_. + +.. method:: SSLContext.set_ciphers(ciphers) + + 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. + + .. note:: + when connected, the :meth:`SSLSocket.cipher` method of SSL sockets will + give the currently selected cipher. + +.. method:: SSLContext.wrap_socket(sock, server_side=False, do_handshake_on_connect=True, suppress_ragged_eofs=True) + + Wrap an existing Python socket *sock* and return an :class:`SSLSocket` + object. The SSL socket is tied to the context, its settings and + certificates. The parameters *server_side*, *do_handshake_on_connect* + and *suppress_ragged_eofs* have the same meaning as in the top-level + :func:`wrap_socket` function. + +.. attribute:: SSLContext.protocol + + The protocol version chosen when constructing the context. This attribute + is read-only. + +.. attribute:: SSLContext.verify_mode + + Whether to try to verify other peers' certificates and how to behave + if verification fails. This attribute must be one of + :data:`CERT_NONE`, :data:`CERT_OPTIONAL` or :data:`CERT_REQUIRED`. + + .. index:: single: certificates .. index:: single: X509 certificate @@ -416,6 +497,9 @@ ... (certificate in base64 PEM encoding) ... -----END CERTIFICATE----- +Certificate chains +^^^^^^^^^^^^^^^^^^ + The Python files which contain certificates can contain a sequence of certificates, sometimes called a *certificate chain*. This chain should start with the specific certificate for the principal who "is" the client or server, @@ -439,6 +523,9 @@ ... (the root certificate for the CA's issuer)... -----END CERTIFICATE----- +CA certificates +^^^^^^^^^^^^^^^ + If you are going to require validation of the other side of the connection's certificate, you need to provide a "CA certs" file, filled with the certificate chains for each issuer you are willing to trust. Again, this file just contains @@ -458,6 +545,25 @@ certificate to a root certificate. See :rfc:`4158` for more discussion of the way in which certification chains can be built. +Combined key and certificate +^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +Often the private key is stored in the same file as the certificate; in this +case, only the ``certfile`` parameter to :meth:`SSLContext.load_cert_chain` +and :func:`wrap_socket` needs to be passed. If the private key is stored +with the certificate, it should come before the first certificate in +the certificate chain:: + + -----BEGIN RSA PRIVATE KEY----- + ... (private key in base64 encoding) ... + -----END RSA PRIVATE KEY----- + -----BEGIN CERTIFICATE----- + ... (certificate in base64 PEM encoding) ... + -----END CERTIFICATE----- + +Self-signed certificates +^^^^^^^^^^^^^^^^^^^^^^^^ + If you are going to create a server that provides SSL-encrypted connection services, you will need to acquire a certificate for that service. There are many ways of acquiring appropriate certificates, such as buying one from a @@ -530,8 +636,7 @@ print(pprint.pformat(ssl_sock.getpeercert())) # Set a simple HTTP request -- use http.client in actual code. - ssl_sock.write("""GET / HTTP/1.0\r - Host: www.verisign.com\r\n\r\n""") + ssl_sock.write(b"GET / HTTP/1.0\r\nHost: www.verisign.com\r\n\r\n") # Read a chunk of data. Will not necessarily # read all the data returned by the server. @@ -561,39 +666,91 @@ which is a fairly poorly-formed ``subject`` field. +This other example first creates an SSL context, instructs it to verify +certificates sent by peers, and feeds it a set of recognized certificate +authorities (CA):: + + >>> context = ssl.SSLContext(ssl.PROTOCOL_SSLv23) + >>> context.verify_mode = ssl.CERT_OPTIONAL + >>> context.load_verify_locations("/etc/ssl/certs/ca-bundle.crt") + +(it is assumed your operating system places a bundle of all CA certificates +in ``/etc/ssl/certs/ca-bundle.crt``; if not, you'll get an error and have +to adjust the location) + +When you use the context to connect to a server, :const:`CERT_OPTIONAL` +validates the server certificate: it ensures that the server certificate +was signed with one of the CA certificates, and checks the signature for +correctness:: + + >>> conn = context.wrap_socket(socket.socket(socket.AF_INET)) + >>> conn.connect(("linuxfr.org", 443)) + +You should then fetch the certificate and check its fields for conformity. +Here, the ``commonName`` field in the ``subject`` matches the desired HTTPS +host ``linuxfr.org``:: + + >>> pprint.pprint(conn.getpeercert()) + {'notAfter': 'Jun 26 21:41:46 2011 GMT', + 'subject': ((('commonName', 'linuxfr.org'),),), + 'subjectAltName': (('DNS', 'linuxfr.org'), ('othername', ''))} + +Now that you are assured of its authenticity, you can proceed to talk with +the server:: + + >>> conn.write(b"HEAD / HTTP/1.0\r\nHost: linuxfr.org\r\n\r\n") + 38 + >>> pprint.pprint(conn.read().split(b"\r\n")) + [b'HTTP/1.1 302 Found', + b'Date: Sun, 16 May 2010 13:43:28 GMT', + b'Server: Apache/2.2', + b'Location: https://linuxfr.org/pub/', + b'Vary: Accept-Encoding', + b'Connection: close', + b'Content-Type: text/html; charset=iso-8859-1', + b'', + b''] + + +See the discussion of :ref:`ssl-security` below. + + Server-side operation ^^^^^^^^^^^^^^^^^^^^^ -For server operation, typically you'd need to have a server certificate, and -private key, each in a file. You'd open a socket, bind it to a port, call -:meth:`listen` on it, then start waiting for clients to connect:: +For server operation, typically you'll need to have a server certificate, and +private key, each in a file. You'll first create a context holding the key +and the certificate, so that clients can check your authenticity. Then +you'll open a socket, bind it to a port, call :meth:`listen` on it, and start +waiting for clients to connect:: import socket, ssl + context = ssl.SSLContext(ssl.PROTOCOL_TLSv1) + context.load_cert_chain(certfile="mycertfile", keyfile="mykeyfile") + bindsocket = socket.socket() bindsocket.bind(('myaddr.mydomain.com', 10023)) bindsocket.listen(5) -When one did, you'd call :meth:`accept` on the socket to get the new socket from -the other end, and use :func:`wrap_socket` to create a server-side SSL context -for it:: +When a client connects, you'll call :meth:`accept` on the socket to get the +new socket from the other end, and use the context's :meth:`SSLContext.wrap_socket` +method to create a server-side SSL socket for the connection:: while True: newsocket, fromaddr = bindsocket.accept() - connstream = ssl.wrap_socket(newsocket, - server_side=True, - certfile="mycertfile", - keyfile="mykeyfile", - ssl_version=ssl.PROTOCOL_TLSv1) - deal_with_client(connstream) + connstream = context.wrap_socket(newsocket, server_side=True) + try: + deal_with_client(connstream) + finally: + connstream.close() -Then you'd read data from the ``connstream`` and do something with it till you +Then you'll read data from the ``connstream`` and do something with it till you are finished with the client (or the client is finished with you):: def deal_with_client(connstream): - data = connstream.read() - # null data means the client is finished with us + # empty data means the client is finished with us while data: if not do_something(connstream, data): # we'll assume do_something returns False @@ -601,9 +758,41 @@ break data = connstream.read() # finished with client - connstream.close() -And go back to listening for new client connections. +And go back to listening for new client connections (of course, a real server +would probably handle each client connection in a separate thread, or put +the sockets in non-blocking mode and use an event loop). + + +.. _ssl-security: + +Security considerations +----------------------- + +Verifying certificates +^^^^^^^^^^^^^^^^^^^^^^ + +:const:`CERT_NONE` is the default. Since it does not authenticate the other +peer, it can be insecure, especially in client mode where most of time you +would like to ensure the authenticity of the server you're talking to. +Therefore, when in client mode, it is highly recommended to use +:const:`CERT_REQUIRED`. However, it is in itself not sufficient; you also +have to check that the server certificate (obtained with +:meth:`SSLSocket.getpeercert`) matches the desired service. The exact way +of doing so depends on the higher-level protocol used; for example, with +HTTPS, you'll check that the host name in the URL matches either the +``commonName`` field in the ``subjectName``, or one of the ``DNS`` fields +in the ``subjectAltName``. + +In server mode, if you want to authenticate your clients using the SSL layer +(rather than using a higher-level authentication mechanism), you'll also have +to specify :const:`CERT_REQUIRED` and similarly check the client certificate. + + .. note:: + + In client mode, :const:`CERT_OPTIONAL` and :const:`CERT_REQUIRED` are + equivalent unless anonymous ciphers are enabled (they are disabled + by default). .. seealso:: Modified: python/branches/py3k/Lib/ssl.py ============================================================================== --- python/branches/py3k/Lib/ssl.py (original) +++ python/branches/py3k/Lib/ssl.py Sun May 16 20:19:27 2010 @@ -59,7 +59,7 @@ import _ssl # if we can't import it, let the error propagate from _ssl import OPENSSL_VERSION_NUMBER, OPENSSL_VERSION_INFO, OPENSSL_VERSION -from _ssl import SSLError +from _ssl import _SSLContext, SSLError from _ssl import CERT_NONE, CERT_OPTIONAL, CERT_REQUIRED from _ssl import (PROTOCOL_SSLv2, PROTOCOL_SSLv3, PROTOCOL_SSLv23, PROTOCOL_TLSv1) @@ -84,8 +84,29 @@ import traceback import errno -class SSLSocket(socket): +class SSLContext(_SSLContext): + """An SSLContext holds various SSL-related configuration options and + data, such as certificates and possibly a private key.""" + + __slots__ = ('protocol',) + + def __new__(cls, protocol, *args, **kwargs): + return _SSLContext.__new__(cls, protocol) + + def __init__(self, protocol): + self.protocol = protocol + + def wrap_socket(self, sock, server_side=False, + do_handshake_on_connect=True, + suppress_ragged_eofs=True): + return SSLSocket(sock=sock, server_side=server_side, + do_handshake_on_connect=do_handshake_on_connect, + suppress_ragged_eofs=suppress_ragged_eofs, + _context=self) + + +class SSLSocket(socket): """This class implements a subtype of socket.socket that wraps the underlying OS socket in an SSL context when necessary, and provides read and write methods over that channel.""" @@ -95,8 +116,31 @@ ssl_version=PROTOCOL_SSLv23, ca_certs=None, do_handshake_on_connect=True, family=AF_INET, type=SOCK_STREAM, proto=0, fileno=None, - suppress_ragged_eofs=True, ciphers=None): + suppress_ragged_eofs=True, ciphers=None, + _context=None): + + if _context: + self.context = _context + else: + if certfile and not keyfile: + keyfile = certfile + self.context = SSLContext(ssl_version) + self.context.verify_mode = cert_reqs + if ca_certs: + self.context.load_verify_locations(ca_certs) + if certfile: + self.context.load_cert_chain(certfile, keyfile) + if ciphers: + self.context.set_ciphers(ciphers) + self.keyfile = keyfile + self.certfile = certfile + self.cert_reqs = cert_reqs + self.ssl_version = ssl_version + self.ca_certs = ca_certs + self.ciphers = ciphers + self.do_handshake_on_connect = do_handshake_on_connect + self.suppress_ragged_eofs = suppress_ragged_eofs connected = False if sock is not None: socket.__init__(self, @@ -119,18 +163,12 @@ else: socket.__init__(self, family=family, type=type, proto=proto) - if certfile and not keyfile: - keyfile = certfile - self._closed = False self._sslobj = None if connected: # create the SSL object try: - self._sslobj = _ssl.sslwrap(self, server_side, - keyfile, certfile, - cert_reqs, ssl_version, ca_certs, - ciphers) + self._sslobj = self.context._wrap_socket(self, server_side) if do_handshake_on_connect: timeout = self.gettimeout() if timeout == 0.0: @@ -142,15 +180,6 @@ self.close() raise x - self.keyfile = keyfile - self.certfile = certfile - self.cert_reqs = cert_reqs - self.ssl_version = ssl_version - self.ca_certs = ca_certs - self.ciphers = ciphers - self.do_handshake_on_connect = do_handshake_on_connect - self.suppress_ragged_eofs = suppress_ragged_eofs - def dup(self): raise NotImplemented("Can't dup() %s instances" % self.__class__.__name__) @@ -331,9 +360,7 @@ if self._sslobj: raise ValueError("attempt to connect already-connected SSLSocket!") socket.connect(self, addr) - self._sslobj = _ssl.sslwrap(self, False, self.keyfile, self.certfile, - self.cert_reqs, self.ssl_version, - self.ca_certs, self.ciphers) + self._sslobj = self.context._wrap_socket(self, False) try: if self.do_handshake_on_connect: self.do_handshake() Added: python/branches/py3k/Lib/test/capath/6e88d7b8.0 ============================================================================== --- (empty file) +++ python/branches/py3k/Lib/test/capath/6e88d7b8.0 Sun May 16 20:19:27 2010 @@ -0,0 +1,14 @@ +-----BEGIN CERTIFICATE----- +MIICLDCCAdYCAQAwDQYJKoZIhvcNAQEEBQAwgaAxCzAJBgNVBAYTAlBUMRMwEQYD +VQQIEwpRdWVlbnNsYW5kMQ8wDQYDVQQHEwZMaXNib2ExFzAVBgNVBAoTDk5ldXJv +bmlvLCBMZGEuMRgwFgYDVQQLEw9EZXNlbnZvbHZpbWVudG8xGzAZBgNVBAMTEmJy +dXR1cy5uZXVyb25pby5wdDEbMBkGCSqGSIb3DQEJARYMc2FtcG9AaWtpLmZpMB4X +DTk2MDkwNTAzNDI0M1oXDTk2MTAwNTAzNDI0M1owgaAxCzAJBgNVBAYTAlBUMRMw +EQYDVQQIEwpRdWVlbnNsYW5kMQ8wDQYDVQQHEwZMaXNib2ExFzAVBgNVBAoTDk5l +dXJvbmlvLCBMZGEuMRgwFgYDVQQLEw9EZXNlbnZvbHZpbWVudG8xGzAZBgNVBAMT +EmJydXR1cy5uZXVyb25pby5wdDEbMBkGCSqGSIb3DQEJARYMc2FtcG9AaWtpLmZp +MFwwDQYJKoZIhvcNAQEBBQADSwAwSAJBAL7+aty3S1iBA/+yxjxv4q1MUTd1kjNw +L4lYKbpzzlmC5beaQXeQ2RmGMTXU+mDvuqItjVHOK3DvPK7lTcSGftUCAwEAATAN +BgkqhkiG9w0BAQQFAANBAFqPEKFjk6T6CKTHvaQeEAsX0/8YHPHqH/9AnhSjrwuX +9EBc0n6bVGhN7XaXd6sJ7dym9sbsWxb+pJdurnkxjx4= +-----END CERTIFICATE----- Added: python/branches/py3k/Lib/test/capath/99d0fa06.0 ============================================================================== --- (empty file) +++ python/branches/py3k/Lib/test/capath/99d0fa06.0 Sun May 16 20:19:27 2010 @@ -0,0 +1,41 @@ +-----BEGIN CERTIFICATE----- +MIIHPTCCBSWgAwIBAgIBADANBgkqhkiG9w0BAQQFADB5MRAwDgYDVQQKEwdSb290 +IENBMR4wHAYDVQQLExVodHRwOi8vd3d3LmNhY2VydC5vcmcxIjAgBgNVBAMTGUNB +IENlcnQgU2lnbmluZyBBdXRob3JpdHkxITAfBgkqhkiG9w0BCQEWEnN1cHBvcnRA +Y2FjZXJ0Lm9yZzAeFw0wMzAzMzAxMjI5NDlaFw0zMzAzMjkxMjI5NDlaMHkxEDAO +BgNVBAoTB1Jvb3QgQ0ExHjAcBgNVBAsTFWh0dHA6Ly93d3cuY2FjZXJ0Lm9yZzEi +MCAGA1UEAxMZQ0EgQ2VydCBTaWduaW5nIEF1dGhvcml0eTEhMB8GCSqGSIb3DQEJ +ARYSc3VwcG9ydEBjYWNlcnQub3JnMIICIjANBgkqhkiG9w0BAQEFAAOCAg8AMIIC +CgKCAgEAziLA4kZ97DYoB1CW8qAzQIxL8TtmPzHlawI229Z89vGIj053NgVBlfkJ +8BLPRoZzYLdufujAWGSuzbCtRRcMY/pnCujW0r8+55jE8Ez64AO7NV1sId6eINm6 +zWYyN3L69wj1x81YyY7nDl7qPv4coRQKFWyGhFtkZip6qUtTefWIonvuLwphK42y +fk1WpRPs6tqSnqxEQR5YYGUFZvjARL3LlPdCfgv3ZWiYUQXw8wWRBB0bF4LsyFe7 +w2t6iPGwcswlWyCR7BYCEo8y6RcYSNDHBS4CMEK4JZwFaz+qOqfrU0j36NK2B5jc +G8Y0f3/JHIJ6BVgrCFvzOKKrF11myZjXnhCLotLddJr3cQxyYN/Nb5gznZY0dj4k +epKwDpUeb+agRThHqtdB7Uq3EvbXG4OKDy7YCbZZ16oE/9KTfWgu3YtLq1i6L43q +laegw1SJpfvbi1EinbLDvhG+LJGGi5Z4rSDTii8aP8bQUWWHIbEZAWV/RRyH9XzQ +QUxPKZgh/TMfdQwEUfoZd9vUFBzugcMd9Zi3aQaRIt0AUMyBMawSB3s42mhb5ivU +fslfrejrckzzAeVLIL+aplfKkQABi6F1ITe1Yw1nPkZPcCBnzsXWWdsC4PDSy826 +YreQQejdIOQpvGQpQsgi3Hia/0PsmBsJUUtaWsJx8cTLc6nloQsCAwEAAaOCAc4w +ggHKMB0GA1UdDgQWBBQWtTIb1Mfz4OaO873SsDrusjkY0TCBowYDVR0jBIGbMIGY +gBQWtTIb1Mfz4OaO873SsDrusjkY0aF9pHsweTEQMA4GA1UEChMHUm9vdCBDQTEe +MBwGA1UECxMVaHR0cDovL3d3dy5jYWNlcnQub3JnMSIwIAYDVQQDExlDQSBDZXJ0 +IFNpZ25pbmcgQXV0aG9yaXR5MSEwHwYJKoZIhvcNAQkBFhJzdXBwb3J0QGNhY2Vy +dC5vcmeCAQAwDwYDVR0TAQH/BAUwAwEB/zAyBgNVHR8EKzApMCegJaAjhiFodHRw +czovL3d3dy5jYWNlcnQub3JnL3Jldm9rZS5jcmwwMAYJYIZIAYb4QgEEBCMWIWh0 +dHBzOi8vd3d3LmNhY2VydC5vcmcvcmV2b2tlLmNybDA0BglghkgBhvhCAQgEJxYl +aHR0cDovL3d3dy5jYWNlcnQub3JnL2luZGV4LnBocD9pZD0xMDBWBglghkgBhvhC +AQ0ESRZHVG8gZ2V0IHlvdXIgb3duIGNlcnRpZmljYXRlIGZvciBGUkVFIGhlYWQg +b3ZlciB0byBodHRwOi8vd3d3LmNhY2VydC5vcmcwDQYJKoZIhvcNAQEEBQADggIB +ACjH7pyCArpcgBLKNQodgW+JapnM8mgPf6fhjViVPr3yBsOQWqy1YPaZQwGjiHCc +nWKdpIevZ1gNMDY75q1I08t0AoZxPuIrA2jxNGJARjtT6ij0rPtmlVOKTV39O9lg +18p5aTuxZZKmxoGCXJzN600BiqXfEVWqFcofN8CCmHBh22p8lqOOLlQ+TyGpkO/c +gr/c6EWtTZBzCDyUZbAEmXZ/4rzCahWqlwQ3JNgelE5tDlG+1sSPypZt90Pf6DBl +Jzt7u0NDY8RD97LsaMzhGY4i+5jhe1o+ATc7iwiwovOVThrLm82asduycPAtStvY +sONvRUgzEv/+PDIqVPfE94rwiCPCR/5kenHA0R6mY7AHfqQv0wGP3J8rtsYIqQ+T +SCX8Ev2fQtzzxD72V7DX3WnRBnc0CkvSyqD/HMaMyRa+xMwyN2hzXwj7UfdJUzYF +CpUCTPJ5GhD22Dp1nPMd8aINcGeGG7MW9S/lpOt5hvk9C8JzC6WZrG/8Z7jlLwum +GCSNe9FINSkYQKyTYOGWhlC0elnYjyELn8+CkcY7v2vcB5G5l1YjqrZslMZIBjzk +zk6q5PYvCdxTby78dOs6Y5nCpqyJvKeyRKANihDjbPIky/qbn3BHLt4Ui9SyIAmW +omTxJBzcoTWcFbLUvFUufQb1nA5V9FrWk9p2rSVzTMVD +-----END CERTIFICATE----- Modified: python/branches/py3k/Lib/test/test_ssl.py ============================================================================== --- python/branches/py3k/Lib/test/test_ssl.py (original) +++ python/branches/py3k/Lib/test/test_ssl.py Sun May 16 20:19:27 2010 @@ -10,6 +10,7 @@ import os import errno import pprint +import tempfile import urllib.parse, urllib.request import traceback import asyncore @@ -25,8 +26,30 @@ skip_expected = True HOST = support.HOST -CERTFILE = None -SVN_PYTHON_ORG_ROOT_CERT = None +PROTOCOLS = [ + ssl.PROTOCOL_SSLv2, ssl.PROTOCOL_SSLv3, + ssl.PROTOCOL_SSLv23, ssl.PROTOCOL_TLSv1 +] + +data_file = lambda name: os.path.join(os.path.dirname(__file__), name) +fsencode = lambda name: name.encode(sys.getfilesystemencoding(), "surrogateescape") + +CERTFILE = data_file("keycert.pem") +BYTES_CERTFILE = fsencode(CERTFILE) +ONLYCERT = data_file("ssl_cert.pem") +ONLYKEY = data_file("ssl_key.pem") +BYTES_ONLYCERT = fsencode(ONLYCERT) +BYTES_ONLYKEY = fsencode(ONLYKEY) +CAPATH = data_file("capath") +BYTES_CAPATH = fsencode(CAPATH) + +SVN_PYTHON_ORG_ROOT_CERT = data_file("https_svn_python_org_root.pem") + +EMPTYCERT = data_file("nullcert.pem") +BADCERT = data_file("badcert.pem") +WRONGCERT = data_file("XXXnonexisting.pem") +BADKEY = data_file("badkey.pem") + def handle_error(prefix): exc_format = ' '.join(traceback.format_exception(*sys.exc_info())) @@ -34,7 +57,7 @@ sys.stdout.write(prefix + exc_format) -class BasicTests(unittest.TestCase): +class BasicSocketTests(unittest.TestCase): def test_constants(self): ssl.PROTOCOL_SSLv2 @@ -116,11 +139,10 @@ s = ssl.wrap_socket(socket.socket(socket.AF_INET), cert_reqs=ssl.CERT_NONE, ciphers="DEFAULT") s.connect(remote) - # Error checking occurs when connecting, because the SSL context - # isn't created before. - s = ssl.wrap_socket(socket.socket(socket.AF_INET), - cert_reqs=ssl.CERT_NONE, ciphers="^$:,;?*'dorothyx") + # Error checking can happen at instantiation or when connecting with self.assertRaisesRegexp(ssl.SSLError, "No cipher can be selected"): + s = ssl.wrap_socket(socket.socket(socket.AF_INET), + cert_reqs=ssl.CERT_NONE, ciphers="^$:,;?*'dorothyx") s.connect(remote) @support.cpython_only @@ -143,33 +165,160 @@ self.assertEqual(timeout, ss.gettimeout()) +class ContextTests(unittest.TestCase): + + def test_constructor(self): + ctx = ssl.SSLContext(ssl.PROTOCOL_SSLv2) + ctx = ssl.SSLContext(ssl.PROTOCOL_SSLv23) + ctx = ssl.SSLContext(ssl.PROTOCOL_SSLv3) + ctx = ssl.SSLContext(ssl.PROTOCOL_TLSv1) + self.assertRaises(TypeError, ssl.SSLContext) + self.assertRaises(ValueError, ssl.SSLContext, -1) + self.assertRaises(ValueError, ssl.SSLContext, 42) + + def test_protocol(self): + for proto in PROTOCOLS: + ctx = ssl.SSLContext(proto) + self.assertEqual(ctx.protocol, proto) + + def test_ciphers(self): + ctx = ssl.SSLContext(ssl.PROTOCOL_TLSv1) + ctx.set_ciphers("ALL") + ctx.set_ciphers("DEFAULT") + with self.assertRaisesRegexp(ssl.SSLError, "No cipher can be selected"): + ctx.set_ciphers("^$:,;?*'dorothyx") + + def test_verify(self): + ctx = ssl.SSLContext(ssl.PROTOCOL_TLSv1) + # Default value + self.assertEqual(ctx.verify_mode, ssl.CERT_NONE) + ctx.verify_mode = ssl.CERT_OPTIONAL + self.assertEqual(ctx.verify_mode, ssl.CERT_OPTIONAL) + ctx.verify_mode = ssl.CERT_REQUIRED + self.assertEqual(ctx.verify_mode, ssl.CERT_REQUIRED) + ctx.verify_mode = ssl.CERT_NONE + self.assertEqual(ctx.verify_mode, ssl.CERT_NONE) + with self.assertRaises(TypeError): + ctx.verify_mode = None + with self.assertRaises(ValueError): + ctx.verify_mode = 42 + + def test_load_cert_chain(self): + ctx = ssl.SSLContext(ssl.PROTOCOL_TLSv1) + # Combined key and cert in a single file + ctx.load_cert_chain(CERTFILE) + ctx.load_cert_chain(CERTFILE, keyfile=CERTFILE) + self.assertRaises(TypeError, ctx.load_cert_chain, keyfile=CERTFILE) + with self.assertRaisesRegexp(ssl.SSLError, "system lib"): + ctx.load_cert_chain(WRONGCERT) + with self.assertRaisesRegexp(ssl.SSLError, "PEM lib"): + ctx.load_cert_chain(BADCERT) + with self.assertRaisesRegexp(ssl.SSLError, "PEM lib"): + ctx.load_cert_chain(EMPTYCERT) + # Separate key and cert + ctx.load_cert_chain(ONLYCERT, ONLYKEY) + ctx.load_cert_chain(certfile=ONLYCERT, keyfile=ONLYKEY) + ctx.load_cert_chain(certfile=BYTES_ONLYCERT, keyfile=BYTES_ONLYKEY) + with self.assertRaisesRegexp(ssl.SSLError, "PEM lib"): + ctx.load_cert_chain(ONLYCERT) + with self.assertRaisesRegexp(ssl.SSLError, "PEM lib"): + ctx.load_cert_chain(ONLYKEY) + with self.assertRaisesRegexp(ssl.SSLError, "PEM lib"): + ctx.load_cert_chain(certfile=ONLYKEY, keyfile=ONLYCERT) + # Mismatching key and cert + with self.assertRaisesRegexp(ssl.SSLError, "key values mismatch"): + ctx.load_cert_chain(CERTFILE, ONLYKEY) + + def test_load_verify_locations(self): + ctx = ssl.SSLContext(ssl.PROTOCOL_TLSv1) + ctx.load_verify_locations(CERTFILE) + ctx.load_verify_locations(cafile=CERTFILE, capath=None) + ctx.load_verify_locations(BYTES_CERTFILE) + ctx.load_verify_locations(cafile=BYTES_CERTFILE, capath=None) + self.assertRaises(TypeError, ctx.load_verify_locations) + self.assertRaises(TypeError, ctx.load_verify_locations, None, None) + with self.assertRaisesRegexp(ssl.SSLError, "system lib"): + ctx.load_verify_locations(WRONGCERT) + with self.assertRaisesRegexp(ssl.SSLError, "PEM lib"): + ctx.load_verify_locations(BADCERT) + ctx.load_verify_locations(CERTFILE, CAPATH) + ctx.load_verify_locations(CERTFILE, capath=BYTES_CAPATH) + + class NetworkedTests(unittest.TestCase): def test_connect(self): s = ssl.wrap_socket(socket.socket(socket.AF_INET), cert_reqs=ssl.CERT_NONE) - s.connect(("svn.python.org", 443)) - c = s.getpeercert() - if c: - self.fail("Peer cert %s shouldn't be here!") - s.close() - - # this should fail because we have no verification certs - s = ssl.wrap_socket(socket.socket(socket.AF_INET), - cert_reqs=ssl.CERT_REQUIRED) try: s.connect(("svn.python.org", 443)) - except ssl.SSLError: - pass + self.assertEqual({}, s.getpeercert()) finally: s.close() + # this should fail because we have no verification certs + s = ssl.wrap_socket(socket.socket(socket.AF_INET), + cert_reqs=ssl.CERT_REQUIRED) + self.assertRaisesRegexp(ssl.SSLError, "certificate verify failed", + s.connect, ("svn.python.org", 443)) + s.close() + # this should succeed because we specify the root cert s = ssl.wrap_socket(socket.socket(socket.AF_INET), cert_reqs=ssl.CERT_REQUIRED, ca_certs=SVN_PYTHON_ORG_ROOT_CERT) try: s.connect(("svn.python.org", 443)) + self.assertTrue(s.getpeercert()) + finally: + s.close() + + def test_connect_with_context(self): + # Same as test_connect, but with a separately created context + ctx = ssl.SSLContext(ssl.PROTOCOL_SSLv23) + s = ctx.wrap_socket(socket.socket(socket.AF_INET)) + s.connect(("svn.python.org", 443)) + try: + self.assertEqual({}, s.getpeercert()) + finally: + s.close() + # This should fail because we have no verification certs + ctx.verify_mode = ssl.CERT_REQUIRED + s = ctx.wrap_socket(socket.socket(socket.AF_INET)) + self.assertRaisesRegexp(ssl.SSLError, "certificate verify failed", + s.connect, ("svn.python.org", 443)) + s.close() + # This should succeed because we specify the root cert + ctx.load_verify_locations(SVN_PYTHON_ORG_ROOT_CERT) + s = ctx.wrap_socket(socket.socket(socket.AF_INET)) + s.connect(("svn.python.org", 443)) + try: + cert = s.getpeercert() + self.assertTrue(cert) + finally: + s.close() + + def test_connect_capath(self): + # Verify server certificates using the `capath` argument + ctx = ssl.SSLContext(ssl.PROTOCOL_SSLv23) + ctx.verify_mode = ssl.CERT_REQUIRED + ctx.load_verify_locations(capath=CAPATH) + s = ctx.wrap_socket(socket.socket(socket.AF_INET)) + s.connect(("svn.python.org", 443)) + try: + cert = s.getpeercert() + self.assertTrue(cert) + finally: + s.close() + # Same with a bytes `capath` argument + ctx = ssl.SSLContext(ssl.PROTOCOL_SSLv23) + ctx.verify_mode = ssl.CERT_REQUIRED + ctx.load_verify_locations(capath=BYTES_CAPATH) + s = ctx.wrap_socket(socket.socket(socket.AF_INET)) + s.connect(("svn.python.org", 443)) + try: + cert = s.getpeercert() + self.assertTrue(cert) finally: s.close() @@ -1227,18 +1376,14 @@ if skip_expected: raise unittest.SkipTest("No SSL support") - global CERTFILE, SVN_PYTHON_ORG_ROOT_CERT - CERTFILE = os.path.join(os.path.dirname(__file__) or os.curdir, - "keycert.pem") - SVN_PYTHON_ORG_ROOT_CERT = os.path.join( - os.path.dirname(__file__) or os.curdir, - "https_svn_python_org_root.pem") - - if (not os.path.exists(CERTFILE) or - not os.path.exists(SVN_PYTHON_ORG_ROOT_CERT)): - raise support.TestFailed("Can't read certificate files!") + for filename in [ + CERTFILE, SVN_PYTHON_ORG_ROOT_CERT, BYTES_CERTFILE, + ONLYCERT, ONLYKEY, BYTES_ONLYCERT, BYTES_ONLYKEY, + BADCERT, BADKEY, EMPTYCERT]: + if not os.path.exists(filename): + raise support.TestFailed("Can't read certificate file %r" % filename) - tests = [BasicTests] + tests = [ContextTests, BasicSocketTests] if support.is_resource_enabled('network'): tests.append(NetworkedTests) Modified: python/branches/py3k/Misc/NEWS ============================================================================== --- python/branches/py3k/Misc/NEWS (original) +++ python/branches/py3k/Misc/NEWS Sun May 16 20:19:27 2010 @@ -363,6 +363,8 @@ Library ------- +- Issue #8550: Add first class ``SSLContext`` objects to the ssl module. + - Issue #8681: Make the zlib module's error messages more informative when the zlib itself doesn't give any detailed explanation. Modified: python/branches/py3k/Modules/_ssl.c ============================================================================== --- python/branches/py3k/Modules/_ssl.c (original) +++ python/branches/py3k/Modules/_ssl.c Sun May 16 20:19:27 2010 @@ -115,23 +115,29 @@ typedef struct { PyObject_HEAD - PyObject *Socket; /* weakref to socket on which we're layered */ - SSL_CTX* ctx; - SSL* ssl; - X509* peer_cert; - int shutdown_seen_zero; - -} PySSLObject; - -static PyTypeObject PySSL_Type; -static PyObject *PySSL_SSLwrite(PySSLObject *self, PyObject *args); -static PyObject *PySSL_SSLread(PySSLObject *self, PyObject *args); + SSL_CTX *ctx; +} PySSLContext; + +typedef struct { + PyObject_HEAD + PyObject *Socket; /* weakref to socket on which we're layered */ + SSL *ssl; + X509 *peer_cert; + int shutdown_seen_zero; +} PySSLSocket; + +static PyTypeObject PySSLContext_Type; +static PyTypeObject PySSLSocket_Type; + +static PyObject *PySSL_SSLwrite(PySSLSocket *self, PyObject *args); +static PyObject *PySSL_SSLread(PySSLSocket *self, PyObject *args); static int check_socket_and_wait_for_timeout(PySocketSockObject *s, int writing); -static PyObject *PySSL_peercert(PySSLObject *self, PyObject *args); -static PyObject *PySSL_cipher(PySSLObject *self); +static PyObject *PySSL_peercert(PySSLSocket *self, PyObject *args); +static PyObject *PySSL_cipher(PySSLSocket *self); -#define PySSLObject_Check(v) (Py_TYPE(v) == &PySSL_Type) +#define PySSLContext_Check(v) (Py_TYPE(v) == &PySSLContext_Type) +#define PySSLSocket_Check(v) (Py_TYPE(v) == &PySSLSocket_Type) typedef enum { SOCKET_IS_NONBLOCKING, @@ -154,7 +160,7 @@ */ static PyObject * -PySSL_SetError(PySSLObject *obj, int ret, char *filename, int lineno) +PySSL_SetError(PySSLSocket *obj, int ret, char *filename, int lineno) { PyObject *v; char buf[2048]; @@ -258,126 +264,28 @@ return NULL; } -static PySSLObject * -newPySSLObject(PySocketSockObject *Sock, char *key_file, char *cert_file, - enum py_ssl_server_or_client socket_type, - enum py_ssl_cert_requirements certreq, - enum py_ssl_version proto_version, - char *cacerts_file, char *ciphers) +static PySSLSocket * +newPySSLSocket(SSL_CTX *ctx, PySocketSockObject *sock, + enum py_ssl_server_or_client socket_type) { - PySSLObject *self; - char *errstr = NULL; - int ret; - int verification_mode; + PySSLSocket *self; - self = PyObject_New(PySSLObject, &PySSL_Type); /* Create new object */ + self = PyObject_New(PySSLSocket, &PySSLSocket_Type); if (self == NULL) return NULL; + self->peer_cert = NULL; self->ssl = NULL; - self->ctx = NULL; self->Socket = NULL; /* Make sure the SSL error state is initialized */ (void) ERR_get_state(); ERR_clear_error(); - if ((key_file && !cert_file) || (!key_file && cert_file)) { - errstr = ERRSTR("Both the key & certificate files " - "must be specified"); - goto fail; - } - - if ((socket_type == PY_SSL_SERVER) && - ((key_file == NULL) || (cert_file == NULL))) { - errstr = ERRSTR("Both the key & certificate files " - "must be specified for server-side operation"); - goto fail; - } - PySSL_BEGIN_ALLOW_THREADS - if (proto_version == PY_SSL_VERSION_TLS1) - self->ctx = SSL_CTX_new(TLSv1_method()); /* Set up context */ - else if (proto_version == PY_SSL_VERSION_SSL3) - self->ctx = SSL_CTX_new(SSLv3_method()); /* Set up context */ - else if (proto_version == PY_SSL_VERSION_SSL2) - self->ctx = SSL_CTX_new(SSLv2_method()); /* Set up context */ - else if (proto_version == PY_SSL_VERSION_SSL23) - self->ctx = SSL_CTX_new(SSLv23_method()); /* Set up context */ + self->ssl = SSL_new(ctx); PySSL_END_ALLOW_THREADS - - if (self->ctx == NULL) { - errstr = ERRSTR("Invalid SSL protocol variant specified."); - goto fail; - } - - if (ciphers != NULL) { - ret = SSL_CTX_set_cipher_list(self->ctx, ciphers); - if (ret == 0) { - errstr = ERRSTR("No cipher can be selected."); - goto fail; - } - } - - if (certreq != PY_SSL_CERT_NONE) { - if (cacerts_file == NULL) { - errstr = ERRSTR("No root certificates specified for " - "verification of other-side certificates."); - goto fail; - } else { - PySSL_BEGIN_ALLOW_THREADS - ret = SSL_CTX_load_verify_locations(self->ctx, - cacerts_file, - NULL); - PySSL_END_ALLOW_THREADS - if (ret != 1) { - _setSSLError(NULL, 0, __FILE__, __LINE__); - goto fail; - } - } - } - if (key_file) { - PySSL_BEGIN_ALLOW_THREADS - ret = SSL_CTX_use_PrivateKey_file(self->ctx, key_file, - SSL_FILETYPE_PEM); - PySSL_END_ALLOW_THREADS - if (ret != 1) { - _setSSLError(NULL, ret, __FILE__, __LINE__); - goto fail; - } - - PySSL_BEGIN_ALLOW_THREADS - ret = SSL_CTX_use_certificate_chain_file(self->ctx, - cert_file); - PySSL_END_ALLOW_THREADS - if (ret != 1) { - /* - fprintf(stderr, "ret is %d, errcode is %lu, %lu, with file \"%s\"\n", - ret, ERR_peek_error(), ERR_peek_last_error(), cert_file); - */ - if (ERR_peek_last_error() != 0) { - _setSSLError(NULL, ret, __FILE__, __LINE__); - goto fail; - } - } - } - - /* ssl compatibility */ - SSL_CTX_set_options(self->ctx, SSL_OP_ALL); - - verification_mode = SSL_VERIFY_NONE; - if (certreq == PY_SSL_CERT_OPTIONAL) - verification_mode = SSL_VERIFY_PEER; - else if (certreq == PY_SSL_CERT_REQUIRED) - verification_mode = (SSL_VERIFY_PEER | - SSL_VERIFY_FAIL_IF_NO_PEER_CERT); - SSL_CTX_set_verify(self->ctx, verification_mode, - NULL); /* set verify lvl */ - - PySSL_BEGIN_ALLOW_THREADS - self->ssl = SSL_new(self->ctx); /* New ssl struct */ - PySSL_END_ALLOW_THREADS - SSL_set_fd(self->ssl, Sock->sock_fd); /* Set the socket for SSL */ + SSL_set_fd(self->ssl, sock->sock_fd); #ifdef SSL_MODE_AUTO_RETRY SSL_set_mode(self->ssl, SSL_MODE_AUTO_RETRY); #endif @@ -385,8 +293,7 @@ /* If the socket is in non-blocking mode or timeout mode, set the BIO * to non-blocking mode (blocking is the default) */ - if (Sock->sock_timeout >= 0.0) { - /* Set both the read and write BIO's to non-blocking mode */ + if (sock->sock_timeout >= 0.0) { BIO_set_nbio(SSL_get_rbio(self->ssl), 1); BIO_set_nbio(SSL_get_wbio(self->ssl), 1); } @@ -398,57 +305,13 @@ SSL_set_accept_state(self->ssl); PySSL_END_ALLOW_THREADS - self->Socket = PyWeakref_NewRef((PyObject *) Sock, Py_None); + self->Socket = PyWeakref_NewRef((PyObject *) sock, NULL); return self; - fail: - if (errstr) - PyErr_SetString(PySSLErrorObject, errstr); - Py_DECREF(self); - return NULL; -} - -static PyObject * -PySSL_sslwrap(PyObject *self, PyObject *args) -{ - PySocketSockObject *Sock; - int server_side = 0; - int verification_mode = PY_SSL_CERT_NONE; - int protocol = PY_SSL_VERSION_SSL23; - char *key_file = NULL; - char *cert_file = NULL; - char *cacerts_file = NULL; - char *ciphers = NULL; - - if (!PyArg_ParseTuple(args, "O!i|zziizz:sslwrap", - PySocketModule.Sock_Type, - &Sock, - &server_side, - &key_file, &cert_file, - &verification_mode, &protocol, - &cacerts_file, &ciphers)) - return NULL; - - /* - fprintf(stderr, - "server_side is %d, keyfile %p, certfile %p, verify_mode %d, " - "protocol %d, certs %p\n", - server_side, key_file, cert_file, verification_mode, - protocol, cacerts_file); - */ - - return (PyObject *) newPySSLObject(Sock, key_file, cert_file, - server_side, verification_mode, - protocol, cacerts_file, - ciphers); } -PyDoc_STRVAR(ssl_doc, -"sslwrap(socket, server_side, [keyfile, certfile, certs_mode, protocol,\n" -" cacertsfile, ciphers]) -> sslobject"); - /* SSL object methods */ -static PyObject *PySSL_SSLdo_handshake(PySSLObject *self) +static PyObject *PySSL_SSLdo_handshake(PySSLSocket *self) { int ret; int err; @@ -986,7 +849,7 @@ static PyObject * -PySSL_peercert(PySSLObject *self, PyObject *args) +PySSL_peercert(PySSLSocket *self, PyObject *args) { PyObject *retval = NULL; int len; @@ -1017,8 +880,7 @@ return retval; } else { - - verification = SSL_CTX_get_verify_mode(self->ctx); + verification = SSL_CTX_get_verify_mode(SSL_get_SSL_CTX(self->ssl)); if ((verification & SSL_VERIFY_PEER) == 0) return PyDict_New(); else @@ -1038,7 +900,7 @@ peer certificate, or None if no certificate was provided. This will\n\ return the certificate even if it wasn't validated."); -static PyObject *PySSL_cipher (PySSLObject *self) { +static PyObject *PySSL_cipher (PySSLSocket *self) { PyObject *retval, *v; SSL_CIPHER *current; @@ -1084,14 +946,12 @@ return NULL; } -static void PySSL_dealloc(PySSLObject *self) +static void PySSL_dealloc(PySSLSocket *self) { if (self->peer_cert) /* Possible not to have one? */ X509_free (self->peer_cert); if (self->ssl) SSL_free(self->ssl); - if (self->ctx) - SSL_CTX_free(self->ctx); Py_XDECREF(self->Socket); PyObject_Del(self); } @@ -1166,7 +1026,7 @@ return rc == 0 ? SOCKET_HAS_TIMED_OUT : SOCKET_OPERATION_OK; } -static PyObject *PySSL_SSLwrite(PySSLObject *self, PyObject *args) +static PyObject *PySSL_SSLwrite(PySSLSocket *self, PyObject *args) { Py_buffer buf; int len; @@ -1250,7 +1110,7 @@ Writes the string s into the SSL object. Returns the number\n\ of bytes written."); -static PyObject *PySSL_SSLpending(PySSLObject *self) +static PyObject *PySSL_SSLpending(PySSLSocket *self) { int count = 0; @@ -1269,7 +1129,7 @@ Returns the number of already decrypted bytes available for read,\n\ pending on the connection.\n"); -static PyObject *PySSL_SSLread(PySSLObject *self, PyObject *args) +static PyObject *PySSL_SSLread(PySSLSocket *self, PyObject *args) { PyObject *dest = NULL; Py_buffer buf; @@ -1392,7 +1252,7 @@ \n\ Read up to len bytes from the SSL socket."); -static PyObject *PySSL_SSLshutdown(PySSLObject *self) +static PyObject *PySSL_SSLshutdown(PySSLSocket *self) { int err, ssl_err, sockstate, nonblocking; int zeros = 0; @@ -1497,10 +1357,10 @@ {NULL, NULL} }; -static PyTypeObject PySSL_Type = { +static PyTypeObject PySSLSocket_Type = { PyVarObject_HEAD_INIT(NULL, 0) - "ssl.SSLContext", /*tp_name*/ - sizeof(PySSLObject), /*tp_basicsize*/ + "_ssl._SSLSocket", /*tp_name*/ + sizeof(PySSLSocket), /*tp_basicsize*/ 0, /*tp_itemsize*/ /* methods */ (destructor)PySSL_dealloc, /*tp_dealloc*/ @@ -1529,6 +1389,306 @@ PySSLMethods, /*tp_methods*/ }; + +/* + * _SSLContext objects + */ + +static PyObject * +context_new(PyTypeObject *type, PyObject *args, PyObject *kwds) +{ + char *kwlist[] = {"protocol", NULL}; + PySSLContext *self; + int proto_version = PY_SSL_VERSION_SSL23; + SSL_CTX *ctx = NULL; + + if (!PyArg_ParseTupleAndKeywords( + args, kwds, "i:_SSLContext", kwlist, + &proto_version)) + return NULL; + + PySSL_BEGIN_ALLOW_THREADS + if (proto_version == PY_SSL_VERSION_TLS1) + ctx = SSL_CTX_new(TLSv1_method()); + else if (proto_version == PY_SSL_VERSION_SSL3) + ctx = SSL_CTX_new(SSLv3_method()); + else if (proto_version == PY_SSL_VERSION_SSL2) + ctx = SSL_CTX_new(SSLv2_method()); + else if (proto_version == PY_SSL_VERSION_SSL23) + ctx = SSL_CTX_new(SSLv23_method()); + else + proto_version = -1; + PySSL_END_ALLOW_THREADS + + if (proto_version == -1) { + PyErr_SetString(PyExc_ValueError, + "invalid protocol version"); + return NULL; + } + if (ctx == NULL) { + PyErr_SetString(PySSLErrorObject, + "failed to allocate SSL context"); + return NULL; + } + + assert(type != NULL && type->tp_alloc != NULL); + self = (PySSLContext *) type->tp_alloc(type, 0); + if (self == NULL) { + SSL_CTX_free(ctx); + return NULL; + } + self->ctx = ctx; + /* Defaults */ + SSL_CTX_set_verify(self->ctx, SSL_VERIFY_NONE, NULL); + SSL_CTX_set_options(self->ctx, SSL_OP_ALL); + + return (PyObject *)self; +} + +static void +context_dealloc(PySSLContext *self) +{ + SSL_CTX_free(self->ctx); + Py_TYPE(self)->tp_free(self); +} + +static PyObject * +set_ciphers(PySSLContext *self, PyObject *args) +{ + int ret; + const char *cipherlist; + + if (!PyArg_ParseTuple(args, "s:set_ciphers", &cipherlist)) + return NULL; + ret = SSL_CTX_set_cipher_list(self->ctx, cipherlist); + if (ret == 0) { + PyErr_SetString(PySSLErrorObject, + "No cipher can be selected."); + return NULL; + } + Py_RETURN_NONE; +} + +static PyObject * +get_verify_mode(PySSLContext *self, void *c) +{ + switch (SSL_CTX_get_verify_mode(self->ctx)) { + case SSL_VERIFY_NONE: + return PyLong_FromLong(PY_SSL_CERT_NONE); + case SSL_VERIFY_PEER: + return PyLong_FromLong(PY_SSL_CERT_OPTIONAL); + case SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT: + return PyLong_FromLong(PY_SSL_CERT_REQUIRED); + } + PyErr_SetString(PySSLErrorObject, + "invalid return value from SSL_CTX_get_verify_mode"); + return NULL; +} + +static int +set_verify_mode(PySSLContext *self, PyObject *arg, void *c) +{ + int n, mode; + if (!PyArg_Parse(arg, "i", &n)) + return -1; + if (n == PY_SSL_CERT_NONE) + mode = SSL_VERIFY_NONE; + else if (n == PY_SSL_CERT_OPTIONAL) + mode = SSL_VERIFY_PEER; + else if (n == PY_SSL_CERT_REQUIRED) + mode = SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT; + else { + PyErr_SetString(PyExc_ValueError, + "invalid value for verify_mode"); + return -1; + } + SSL_CTX_set_verify(self->ctx, mode, NULL); + return 0; +} + +static PyObject * +load_cert_chain(PySSLContext *self, PyObject *args, PyObject *kwds) +{ + char *kwlist[] = {"certfile", "keyfile", NULL}; + PyObject *certfile, *keyfile = NULL; + PyObject *certfile_bytes = NULL, *keyfile_bytes = NULL; + int r; + + if (!PyArg_ParseTupleAndKeywords(args, kwds, + "O|O:load_cert_chain", kwlist, + &certfile, &keyfile)) + return NULL; + if (keyfile == Py_None) + keyfile = NULL; + if (!PyUnicode_FSConverter(certfile, &certfile_bytes)) { + PyErr_SetString(PyExc_TypeError, + "certfile should be a valid filesystem path"); + return NULL; + } + if (keyfile && !PyUnicode_FSConverter(keyfile, &keyfile_bytes)) { + PyErr_SetString(PyExc_TypeError, + "keyfile should be a valid filesystem path"); + goto error; + } + PySSL_BEGIN_ALLOW_THREADS + r = SSL_CTX_use_certificate_chain_file(self->ctx, + PyBytes_AS_STRING(certfile_bytes)); + PySSL_END_ALLOW_THREADS + if (r != 1) { + _setSSLError(NULL, 0, __FILE__, __LINE__); + goto error; + } + PySSL_BEGIN_ALLOW_THREADS + r = SSL_CTX_use_RSAPrivateKey_file(self->ctx, + PyBytes_AS_STRING(keyfile ? keyfile_bytes : certfile_bytes), + SSL_FILETYPE_PEM); + PySSL_END_ALLOW_THREADS + Py_XDECREF(keyfile_bytes); + Py_XDECREF(certfile_bytes); + if (r != 1) { + _setSSLError(NULL, 0, __FILE__, __LINE__); + return NULL; + } + PySSL_BEGIN_ALLOW_THREADS + r = SSL_CTX_check_private_key(self->ctx); + PySSL_END_ALLOW_THREADS + if (r != 1) { + _setSSLError(NULL, 0, __FILE__, __LINE__); + return NULL; + } + Py_RETURN_NONE; + +error: + Py_XDECREF(keyfile_bytes); + Py_XDECREF(certfile_bytes); + return NULL; +} + +static PyObject * +load_verify_locations(PySSLContext *self, PyObject *args, PyObject *kwds) +{ + char *kwlist[] = {"cafile", "capath", NULL}; + PyObject *cafile = NULL, *capath = NULL; + PyObject *cafile_bytes = NULL, *capath_bytes = NULL; + const char *cafile_buf = NULL, *capath_buf = NULL; + int r; + + if (!PyArg_ParseTupleAndKeywords(args, kwds, + "|OO:load_verify_locations", kwlist, + &cafile, &capath)) + return NULL; + if (cafile == Py_None) + cafile = NULL; + if (capath == Py_None) + capath = NULL; + if (cafile == NULL && capath == NULL) { + PyErr_SetString(PyExc_TypeError, + "cafile and capath cannot be both omitted"); + return NULL; + } + if (cafile && !PyUnicode_FSConverter(cafile, &cafile_bytes)) { + PyErr_SetString(PyExc_TypeError, + "cafile should be a valid filesystem path"); + return NULL; + } + if (capath && !PyUnicode_FSConverter(capath, &capath_bytes)) { + Py_DECREF(cafile_bytes); + PyErr_SetString(PyExc_TypeError, + "capath should be a valid filesystem path"); + return NULL; + } + if (cafile) + cafile_buf = PyBytes_AS_STRING(cafile_bytes); + if (capath) + capath_buf = PyBytes_AS_STRING(capath_bytes); + PySSL_BEGIN_ALLOW_THREADS + r = SSL_CTX_load_verify_locations(self->ctx, cafile_buf, capath_buf); + PySSL_END_ALLOW_THREADS + Py_XDECREF(cafile_bytes); + Py_XDECREF(capath_bytes); + if (r != 1) { + _setSSLError(NULL, 0, __FILE__, __LINE__); + return NULL; + } + Py_RETURN_NONE; +} + +static PyObject * +context_wrap_socket(PySSLContext *self, PyObject *args, PyObject *kwds) +{ + char *kwlist[] = {"sock", "server_side", NULL}; + PySocketSockObject *sock; + int server_side = 0; + + if (!PyArg_ParseTupleAndKeywords(args, kwds, "O!i:_wrap_socket", kwlist, + PySocketModule.Sock_Type, + &sock, &server_side)) + return NULL; + + return (PyObject *) newPySSLSocket(self->ctx, sock, server_side); +} + +static PyGetSetDef context_getsetlist[] = { + {"verify_mode", (getter) get_verify_mode, + (setter) set_verify_mode, NULL}, + {NULL}, /* sentinel */ +}; + +static struct PyMethodDef context_methods[] = { + {"_wrap_socket", (PyCFunction) context_wrap_socket, + METH_VARARGS | METH_KEYWORDS, NULL}, + {"set_ciphers", (PyCFunction) set_ciphers, + METH_VARARGS, NULL}, + {"load_cert_chain", (PyCFunction) load_cert_chain, + METH_VARARGS | METH_KEYWORDS, NULL}, + {"load_verify_locations", (PyCFunction) load_verify_locations, + METH_VARARGS | METH_KEYWORDS, NULL}, + {NULL, NULL} /* sentinel */ +}; + +static PyTypeObject PySSLContext_Type = { + PyVarObject_HEAD_INIT(NULL, 0) + "_ssl._SSLContext", /*tp_name*/ + sizeof(PySSLContext), /*tp_basicsize*/ + 0, /*tp_itemsize*/ + (destructor)context_dealloc, /*tp_dealloc*/ + 0, /*tp_print*/ + 0, /*tp_getattr*/ + 0, /*tp_setattr*/ + 0, /*tp_reserved*/ + 0, /*tp_repr*/ + 0, /*tp_as_number*/ + 0, /*tp_as_sequence*/ + 0, /*tp_as_mapping*/ + 0, /*tp_hash*/ + 0, /*tp_call*/ + 0, /*tp_str*/ + 0, /*tp_getattro*/ + 0, /*tp_setattro*/ + 0, /*tp_as_buffer*/ + Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /*tp_flags*/ + 0, /*tp_doc*/ + 0, /*tp_traverse*/ + 0, /*tp_clear*/ + 0, /*tp_richcompare*/ + 0, /*tp_weaklistoffset*/ + 0, /*tp_iter*/ + 0, /*tp_iternext*/ + context_methods, /*tp_methods*/ + 0, /*tp_members*/ + context_getsetlist, /*tp_getset*/ + 0, /*tp_base*/ + 0, /*tp_dict*/ + 0, /*tp_descr_get*/ + 0, /*tp_descr_set*/ + 0, /*tp_dictoffset*/ + 0, /*tp_init*/ + 0, /*tp_alloc*/ + context_new, /*tp_new*/ +}; + + + #ifdef HAVE_OPENSSL_RAND /* helper routines for seeding the SSL PRNG */ @@ -1598,8 +1758,6 @@ /* List of functions exported by this module. */ static PyMethodDef PySSL_methods[] = { - {"sslwrap", PySSL_sslwrap, - METH_VARARGS, ssl_doc}, {"_test_decode_cert", PySSL_test_decode_certificate, METH_VARARGS}, #ifdef HAVE_OPENSSL_RAND @@ -1708,7 +1866,9 @@ unsigned int major, minor, fix, patch, status; PySocketModule_APIObject *socket_api; - if (PyType_Ready(&PySSL_Type) < 0) + if (PyType_Ready(&PySSLContext_Type) < 0) + return NULL; + if (PyType_Ready(&PySSLSocket_Type) < 0) return NULL; m = PyModule_Create(&_sslmodule); @@ -1741,8 +1901,11 @@ return NULL; if (PyDict_SetItemString(d, "SSLError", PySSLErrorObject) != 0) return NULL; - if (PyDict_SetItemString(d, "SSLType", - (PyObject *)&PySSL_Type) != 0) + if (PyDict_SetItemString(d, "_SSLContext", + (PyObject *)&PySSLContext_Type) != 0) + return NULL; + if (PyDict_SetItemString(d, "_SSLSocket", + (PyObject *)&PySSLSocket_Type) != 0) return NULL; PyModule_AddIntConstant(m, "SSL_ERROR_ZERO_RETURN", PY_SSL_ERROR_ZERO_RETURN); From python-checkins at python.org Sun May 16 21:22:44 2010 From: python-checkins at python.org (antoine.pitrou) Date: Sun, 16 May 2010 21:22:44 +0200 (CEST) Subject: [Python-checkins] r81234 - in python/branches/py3k/Lib/test: capath/4e1295a3.0 capath/5ed36f99.0 test_ssl.py Message-ID: <20100516192244.4529DEEB4E@mail.python.org> Author: antoine.pitrou Date: Sun May 16 21:22:44 2010 New Revision: 81234 Log: Followup on r81233: fix test_ssl with OpenSSL < 1.0.0. Added: python/branches/py3k/Lib/test/capath/4e1295a3.0 - copied unchanged from r81233, /python/branches/py3k/Lib/test/capath/6e88d7b8.0 python/branches/py3k/Lib/test/capath/5ed36f99.0 - copied unchanged from r81233, /python/branches/py3k/Lib/test/capath/99d0fa06.0 Modified: python/branches/py3k/Lib/test/test_ssl.py Modified: python/branches/py3k/Lib/test/test_ssl.py ============================================================================== --- python/branches/py3k/Lib/test/test_ssl.py (original) +++ python/branches/py3k/Lib/test/test_ssl.py Sun May 16 21:22:44 2010 @@ -300,6 +300,10 @@ def test_connect_capath(self): # Verify server certificates using the `capath` argument + # NOTE: the subject hashing algorithm has been changed between + # OpenSSL 0.9.8n and 1.0.0, as a result the capath directory must + # contain both versions of each certificate (same content, different + # filename) for this test to be portable accross OpenSSL releases. ctx = ssl.SSLContext(ssl.PROTOCOL_SSLv23) ctx.verify_mode = ssl.CERT_REQUIRED ctx.load_verify_locations(capath=CAPATH) From python-checkins at python.org Sun May 16 21:56:32 2010 From: python-checkins at python.org (antoine.pitrou) Date: Sun, 16 May 2010 21:56:32 +0200 (CEST) Subject: [Python-checkins] r81235 - in python/branches/py3k: Lib/test/test_ssl.py Modules/_ssl.c Message-ID: <20100516195632.4D89AEEB6B@mail.python.org> Author: antoine.pitrou Date: Sun May 16 21:56:32 2010 New Revision: 81235 Log: Fix (hopefully) the remaining test_ssl buildbot failures Modified: python/branches/py3k/Lib/test/test_ssl.py python/branches/py3k/Modules/_ssl.c Modified: python/branches/py3k/Lib/test/test_ssl.py ============================================================================== --- python/branches/py3k/Lib/test/test_ssl.py (original) +++ python/branches/py3k/Lib/test/test_ssl.py Sun May 16 21:56:32 2010 @@ -142,7 +142,7 @@ # Error checking can happen at instantiation or when connecting with self.assertRaisesRegexp(ssl.SSLError, "No cipher can be selected"): s = ssl.wrap_socket(socket.socket(socket.AF_INET), - cert_reqs=ssl.CERT_NONE, ciphers="^$:,;?*'dorothyx") + cert_reqs=ssl.CERT_NONE, ciphers="xyzzy") s.connect(remote) @support.cpython_only @@ -186,7 +186,7 @@ ctx.set_ciphers("ALL") ctx.set_ciphers("DEFAULT") with self.assertRaisesRegexp(ssl.SSLError, "No cipher can be selected"): - ctx.set_ciphers("^$:,;?*'dorothyx") + ctx.set_ciphers("xyzzy") def test_verify(self): ctx = ssl.SSLContext(ssl.PROTOCOL_TLSv1) Modified: python/branches/py3k/Modules/_ssl.c ============================================================================== --- python/branches/py3k/Modules/_ssl.c (original) +++ python/branches/py3k/Modules/_ssl.c Sun May 16 21:56:32 2010 @@ -1462,6 +1462,10 @@ return NULL; ret = SSL_CTX_set_cipher_list(self->ctx, cipherlist); if (ret == 0) { + /* Clearing the error queue is necessary on some OpenSSL versions, + otherwise the error will be reported again when another SSL call + is done. */ + ERR_clear_error(); PyErr_SetString(PySSLErrorObject, "No cipher can be selected."); return NULL; From brett at python.org Sun May 16 21:59:24 2010 From: brett at python.org (Brett Cannon) Date: Sun, 16 May 2010 12:59:24 -0700 Subject: [Python-checkins] r81225 - in python/branches/release26-maint: Lib/test/list_tests.py In-Reply-To: <20100516003543.C1839EEAF1@mail.python.org> References: <20100516003543.C1839EEAF1@mail.python.org> Message-ID: Probably shouldn't backport stuff like this as it isn't a bug fix but a code cleanup. And this is especially true of tests as the last thing we want to do is break our verification that we didn't break anything. But don't back this change out as it didn't break anything. On Sat, May 15, 2010 at 17:35, victor.stinner wrote: > Author: victor.stinner > Date: Sun May 16 02:35:43 2010 > New Revision: 81225 > > Log: > Merged revisions 81224 via svnmerge from > svn+ssh://pythondev at svn.python.org/python/trunk > > ........ > ?r81224 | victor.stinner | 2010-05-16 02:34:40 +0200 (dim., 16 mai 2010) | 4 lines > > ?Use with open() as fo: ... instead of try: fo = open(...) finally: fo.close() > > ?fo is not set if the open() fails. > ........ > > > Modified: > ? python/branches/release26-maint/ ? (props changed) > ? python/branches/release26-maint/Lib/test/list_tests.py > > Modified: python/branches/release26-maint/Lib/test/list_tests.py > ============================================================================== > --- python/branches/release26-maint/Lib/test/list_tests.py ? ? ?(original) > +++ python/branches/release26-maint/Lib/test/list_tests.py ? ? ?Sun May 16 02:35:43 2010 > @@ -57,13 +57,11 @@ > ? ? ? ? d.append(d) > ? ? ? ? d.append(400) > ? ? ? ? try: > - ? ? ? ? ? ?fo = open(test_support.TESTFN, "wb") > - ? ? ? ? ? ?print >> fo, d, > - ? ? ? ? ? ?fo.close() > - ? ? ? ? ? ?fo = open(test_support.TESTFN, "rb") > - ? ? ? ? ? ?self.assertEqual(fo.read(), repr(d)) > + ? ? ? ? ? ?with open(test_support.TESTFN, "wb") as fo: > + ? ? ? ? ? ? ? ?print >> fo, d, > + ? ? ? ? ? ?with open(test_support.TESTFN, "rb") as fo: > + ? ? ? ? ? ? ? ?self.assertEqual(fo.read(), repr(d)) > ? ? ? ? finally: > - ? ? ? ? ? ?fo.close() > ? ? ? ? ? ? os.remove(test_support.TESTFN) > > ? ? def test_set_subscript(self): > _______________________________________________ > Python-checkins mailing list > Python-checkins at python.org > http://mail.python.org/mailman/listinfo/python-checkins > From python-checkins at python.org Sun May 16 22:35:03 2010 From: python-checkins at python.org (antoine.pitrou) Date: Sun, 16 May 2010 22:35:03 +0200 (CEST) Subject: [Python-checkins] r81236 - python/branches/py3k/Lib/test/test_ssl.py Message-ID: <20100516203504.0005AC8F1@mail.python.org> Author: antoine.pitrou Date: Sun May 16 22:35:03 2010 New Revision: 81236 Log: Do not fail if ssl fails to import Modified: python/branches/py3k/Lib/test/test_ssl.py Modified: python/branches/py3k/Lib/test/test_ssl.py ============================================================================== --- python/branches/py3k/Lib/test/test_ssl.py (original) +++ python/branches/py3k/Lib/test/test_ssl.py Sun May 16 22:35:03 2010 @@ -24,12 +24,13 @@ import ssl except ImportError: skip_expected = True +else: + PROTOCOLS = [ + ssl.PROTOCOL_SSLv2, ssl.PROTOCOL_SSLv3, + ssl.PROTOCOL_SSLv23, ssl.PROTOCOL_TLSv1 + ] HOST = support.HOST -PROTOCOLS = [ - ssl.PROTOCOL_SSLv2, ssl.PROTOCOL_SSLv3, - ssl.PROTOCOL_SSLv23, ssl.PROTOCOL_TLSv1 -] data_file = lambda name: os.path.join(os.path.dirname(__file__), name) fsencode = lambda name: name.encode(sys.getfilesystemencoding(), "surrogateescape") From victor.stinner at haypocalc.com Sun May 16 23:00:39 2010 From: victor.stinner at haypocalc.com (Victor Stinner) Date: Sun, 16 May 2010 23:00:39 +0200 Subject: [Python-checkins] r81225 - in python/branches/release26-maint: Lib/test/list_tests.py In-Reply-To: References: <20100516003543.C1839EEAF1@mail.python.org> Message-ID: <201005162300.39673.victor.stinner@haypocalc.com> Le dimanche 16 mai 2010 21:59:24, Brett Cannon a ?crit : > Probably shouldn't backport stuff like this as it isn't a bug fix but > a code cleanup. And this is especially true of tests as the last thing > we want to do is break our verification that we didn't break anything. I don't know if it can be called "a bug". As I wrote in my changelog: "fo is not set if the open() fails" and so fo.close() will raise a NameError in the finally block. I had the bug in 3.1 branch after the commit r81171. In 3.1 branch: r81173 reverts r81171, and r81175 fix another bug related to TESTFN ("remove TESTFN if it is a directory"). trunk and py3k add the pid to TESTFN. -- Victor Stinner http://www.haypocalc.com/ From ncoghlan at gmail.com Sun May 16 23:05:28 2010 From: ncoghlan at gmail.com (Nick Coghlan) Date: Mon, 17 May 2010 07:05:28 +1000 Subject: [Python-checkins] r81225 - in python/branches/release26-maint: Lib/test/list_tests.py In-Reply-To: References: <20100516003543.C1839EEAF1@mail.python.org> Message-ID: <4BF05E18.40307@gmail.com> Brett Cannon wrote: > Probably shouldn't backport stuff like this as it isn't a bug fix but > a code cleanup. And this is especially true of tests as the last thing > we want to do is break our verification that we didn't break anything. > > But don't back this change out as it didn't break anything. This wasn't just a cleanup - the old test was broken (it called open() inside the try block instead of before it). Cheers, Nick. -- Nick Coghlan | ncoghlan at gmail.com | Brisbane, Australia --------------------------------------------------------------- From brett at python.org Sun May 16 23:08:26 2010 From: brett at python.org (Brett Cannon) Date: Sun, 16 May 2010 14:08:26 -0700 Subject: [Python-checkins] r81225 - in python/branches/release26-maint: Lib/test/list_tests.py In-Reply-To: <4BF05E18.40307@gmail.com> References: <20100516003543.C1839EEAF1@mail.python.org> <4BF05E18.40307@gmail.com> Message-ID: My mistake. Sorry about that. Have not written that try/finally pattern in a while. =) On Sun, May 16, 2010 at 14:05, Nick Coghlan wrote: > Brett Cannon wrote: >> Probably shouldn't backport stuff like this as it isn't a bug fix but >> a code cleanup. And this is especially true of tests as the last thing >> we want to do is break our verification that we didn't break anything. >> >> But don't back this change out as it didn't break anything. > > This wasn't just a cleanup - the old test was broken (it called open() > inside the try block instead of before it). > > Cheers, > Nick. > > -- > Nick Coghlan ? | ? ncoghlan at gmail.com ? | ? Brisbane, Australia > --------------------------------------------------------------- > From python-checkins at python.org Sun May 16 23:23:48 2010 From: python-checkins at python.org (victor.stinner) Date: Sun, 16 May 2010 23:23:48 +0200 (CEST) Subject: [Python-checkins] r81237 - in python/branches/py3k: Misc/NEWS Modules/_ssl.c Message-ID: <20100516212348.36BB7C947@mail.python.org> Author: victor.stinner Date: Sun May 16 23:23:48 2010 New Revision: 81237 Log: Issue #8477: _ssl._test_decode_cert() supports str with surrogates and bytes for the filename Modified: python/branches/py3k/Misc/NEWS python/branches/py3k/Modules/_ssl.c Modified: python/branches/py3k/Misc/NEWS ============================================================================== --- python/branches/py3k/Misc/NEWS (original) +++ python/branches/py3k/Misc/NEWS Sun May 16 23:23:48 2010 @@ -363,6 +363,9 @@ Library ------- +- Issue #8477: _ssl._test_decode_cert() supports str with surrogates and bytes + for the filename + - Issue #8550: Add first class ``SSLContext`` objects to the ssl module. - Issue #8681: Make the zlib module's error messages more informative when Modified: python/branches/py3k/Modules/_ssl.c ============================================================================== --- python/branches/py3k/Modules/_ssl.c (original) +++ python/branches/py3k/Modules/_ssl.c Sun May 16 23:23:48 2010 @@ -811,13 +811,13 @@ PySSL_test_decode_certificate (PyObject *mod, PyObject *args) { PyObject *retval = NULL; - char *filename = NULL; + PyObject *filename; X509 *x=NULL; BIO *cert; int verbose = 1; - if (!PyArg_ParseTuple(args, "s|i:test_decode_certificate", - &filename, &verbose)) + if (!PyArg_ParseTuple(args, "O&|i:test_decode_certificate", + PyUnicode_FSConverter, &filename, &verbose)) return NULL; if ((cert=BIO_new(BIO_s_file())) == NULL) { @@ -826,7 +826,7 @@ goto fail0; } - if (BIO_read_filename(cert,filename) <= 0) { + if (BIO_read_filename(cert, PyBytes_AsString(filename)) <= 0) { PyErr_SetString(PySSLErrorObject, "Can't open file"); goto fail0; @@ -842,7 +842,7 @@ retval = _decode_certificate(x, verbose); fail0: - + Py_DECREF(filename); if (cert != NULL) BIO_free(cert); return retval; } From python-checkins at python.org Sun May 16 23:25:04 2010 From: python-checkins at python.org (victor.stinner) Date: Sun, 16 May 2010 23:25:04 +0200 (CEST) Subject: [Python-checkins] r81238 - python/branches/release31-maint Message-ID: <20100516212504.03C07C947@mail.python.org> Author: victor.stinner Date: Sun May 16 23:25:03 2010 New Revision: 81238 Log: Blocked revisions 81237 via svnmerge ........ r81237 | victor.stinner | 2010-05-16 23:23:48 +0200 (dim., 16 mai 2010) | 3 lines Issue #8477: _ssl._test_decode_cert() supports str with surrogates and bytes for the filename ........ Modified: python/branches/release31-maint/ (props changed) From python-checkins at python.org Sun May 16 23:36:37 2010 From: python-checkins at python.org (victor.stinner) Date: Sun, 16 May 2010 23:36:37 +0200 (CEST) Subject: [Python-checkins] r81239 - in python/branches/py3k: Misc/NEWS Modules/_ssl.c Message-ID: <20100516213637.69802E4C9@mail.python.org> Author: victor.stinner Date: Sun May 16 23:36:37 2010 New Revision: 81239 Log: Issue #8477: ssl.RAND_egd() supports str with surrogates and bytes for the path Modified: python/branches/py3k/Misc/NEWS python/branches/py3k/Modules/_ssl.c Modified: python/branches/py3k/Misc/NEWS ============================================================================== --- python/branches/py3k/Misc/NEWS (original) +++ python/branches/py3k/Misc/NEWS Sun May 16 23:36:37 2010 @@ -363,8 +363,8 @@ Library ------- -- Issue #8477: _ssl._test_decode_cert() supports str with surrogates and bytes - for the filename +- Issue #8477: ssl.RAND_egd() and ssl._test_decode_cert() support str with + surrogates and bytes for the filename - Issue #8550: Add first class ``SSLContext`` objects to the ssl module. Modified: python/branches/py3k/Modules/_ssl.c ============================================================================== --- python/branches/py3k/Modules/_ssl.c (original) +++ python/branches/py3k/Modules/_ssl.c Sun May 16 23:36:37 2010 @@ -1730,15 +1730,17 @@ using the ssl() function."); static PyObject * -PySSL_RAND_egd(PyObject *self, PyObject *arg) +PySSL_RAND_egd(PyObject *self, PyObject *args) { + PyObject *path; int bytes; - if (!PyUnicode_Check(arg)) - return PyErr_Format(PyExc_TypeError, - "RAND_egd() expected string, found %s", - Py_TYPE(arg)->tp_name); - bytes = RAND_egd(_PyUnicode_AsString(arg)); + if (!PyArg_ParseTuple(args, "O&|i:RAND_egd", + PyUnicode_FSConverter, &path)) + return NULL; + + bytes = RAND_egd(PyBytes_AsString(path)); + Py_DECREF(path); if (bytes == -1) { PyErr_SetString(PySSLErrorObject, "EGD connection failed or EGD did not return " @@ -1767,7 +1769,7 @@ #ifdef HAVE_OPENSSL_RAND {"RAND_add", PySSL_RAND_add, METH_VARARGS, PySSL_RAND_add_doc}, - {"RAND_egd", PySSL_RAND_egd, METH_O, + {"RAND_egd", PySSL_RAND_egd, METH_VARARGS, PySSL_RAND_egd_doc}, {"RAND_status", (PyCFunction)PySSL_RAND_status, METH_NOARGS, PySSL_RAND_status_doc}, From python-checkins at python.org Sun May 16 23:37:34 2010 From: python-checkins at python.org (victor.stinner) Date: Sun, 16 May 2010 23:37:34 +0200 (CEST) Subject: [Python-checkins] r81240 - python/branches/release31-maint Message-ID: <20100516213734.2AC91E4C9@mail.python.org> Author: victor.stinner Date: Sun May 16 23:37:34 2010 New Revision: 81240 Log: Blocked revisions 81239 via svnmerge ........ r81239 | victor.stinner | 2010-05-16 23:36:37 +0200 (dim., 16 mai 2010) | 2 lines Issue #8477: ssl.RAND_egd() supports str with surrogates and bytes for the path ........ Modified: python/branches/release31-maint/ (props changed) From ncoghlan at gmail.com Sun May 16 23:59:54 2010 From: ncoghlan at gmail.com (Nick Coghlan) Date: Mon, 17 May 2010 07:59:54 +1000 Subject: [Python-checkins] r81225 - in python/branches/release26-maint: Lib/test/list_tests.py In-Reply-To: References: <20100516003543.C1839EEAF1@mail.python.org> <4BF05E18.40307@gmail.com> Message-ID: <4BF06ADA.3090407@gmail.com> Brett Cannon wrote: > My mistake. Sorry about that. Have not written that try/finally > pattern in a while. =) Making it easier to avoid that particular mistake (and the equivalent for thread lock acquisition) was one of the motivations behind the with statement in the first place, so I tend to remember it :) Cheers, Nick. -- Nick Coghlan | ncoghlan at gmail.com | Brisbane, Australia --------------------------------------------------------------- From python-checkins at python.org Mon May 17 01:11:46 2010 From: python-checkins at python.org (antoine.pitrou) Date: Mon, 17 May 2010 01:11:46 +0200 (CEST) Subject: [Python-checkins] r81241 - python/trunk/Modules/_ssl.c Message-ID: <20100516231146.9511AEE9F5@mail.python.org> Author: antoine.pitrou Date: Mon May 17 01:11:46 2010 New Revision: 81241 Log: Clear the OpenSSL error queue each time an error is signalled. When the error queue is not emptied, strange things can happen on the next SSL call, depending on the OpenSSL version. Modified: python/trunk/Modules/_ssl.c Modified: python/trunk/Modules/_ssl.c ============================================================================== --- python/trunk/Modules/_ssl.c (original) +++ python/trunk/Modules/_ssl.c Mon May 17 01:11:46 2010 @@ -196,6 +196,7 @@ errstr = "EOF occurred in violation of protocol"; } else if (ret == -1) { /* underlying BIO reported an I/O error */ + ERR_clear_error(); return obj->Socket->errorhandler(); } else { /* possible? */ p = PY_SSL_ERROR_SYSCALL; @@ -228,6 +229,7 @@ errstr = ERR_error_string(ERR_peek_last_error(), NULL); } PyOS_snprintf(buf, sizeof(buf), "_ssl.c:%d: %s", lineno, errstr); + ERR_clear_error(); v = Py_BuildValue("(is)", p, buf); if (v != NULL) { PyErr_SetObject(PySSLErrorObject, v); @@ -247,6 +249,7 @@ errstr = ERR_error_string(errcode, NULL); } PyOS_snprintf(buf, sizeof(buf), "_ssl.c:%d: %s", lineno, errstr); + ERR_clear_error(); v = Py_BuildValue("(is)", errcode, buf); if (v != NULL) { PyErr_SetObject(PySSLErrorObject, v); From python-checkins at python.org Mon May 17 01:14:22 2010 From: python-checkins at python.org (antoine.pitrou) Date: Mon, 17 May 2010 01:14:22 +0200 (CEST) Subject: [Python-checkins] r81242 - in python/branches/py3k: Modules/_ssl.c Message-ID: <20100516231422.E44FFEE990@mail.python.org> Author: antoine.pitrou Date: Mon May 17 01:14:22 2010 New Revision: 81242 Log: Merged revisions 81241 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r81241 | antoine.pitrou | 2010-05-17 01:11:46 +0200 (lun., 17 mai 2010) | 4 lines Clear the OpenSSL error queue each time an error is signalled. When the error queue is not emptied, strange things can happen on the next SSL call, depending on the OpenSSL version. ........ Modified: python/branches/py3k/ (props changed) python/branches/py3k/Modules/_ssl.c Modified: python/branches/py3k/Modules/_ssl.c ============================================================================== --- python/branches/py3k/Modules/_ssl.c (original) +++ python/branches/py3k/Modules/_ssl.c Mon May 17 01:14:22 2010 @@ -205,6 +205,7 @@ errstr = "EOF occurred in violation of protocol"; } else if (ret == -1) { /* underlying BIO reported an I/O error */ + ERR_clear_error(); return s->errorhandler(); } else { /* possible? */ p = PY_SSL_ERROR_SYSCALL; @@ -237,6 +238,7 @@ errstr = ERR_error_string(ERR_peek_last_error(), NULL); } PyOS_snprintf(buf, sizeof(buf), "_ssl.c:%d: %s", lineno, errstr); + ERR_clear_error(); v = Py_BuildValue("(is)", p, buf); if (v != NULL) { PyErr_SetObject(PySSLErrorObject, v); @@ -256,6 +258,7 @@ errstr = ERR_error_string(errcode, NULL); } PyOS_snprintf(buf, sizeof(buf), "_ssl.c:%d: %s", lineno, errstr); + ERR_clear_error(); v = Py_BuildValue("(is)", errcode, buf); if (v != NULL) { PyErr_SetObject(PySSLErrorObject, v); From python-checkins at python.org Mon May 17 01:14:34 2010 From: python-checkins at python.org (antoine.pitrou) Date: Mon, 17 May 2010 01:14:34 +0200 (CEST) Subject: [Python-checkins] r81243 - in python/branches/release26-maint: Modules/_ssl.c Message-ID: <20100516231434.B7154EEACE@mail.python.org> Author: antoine.pitrou Date: Mon May 17 01:14:34 2010 New Revision: 81243 Log: Merged revisions 81241 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r81241 | antoine.pitrou | 2010-05-17 01:11:46 +0200 (lun., 17 mai 2010) | 4 lines Clear the OpenSSL error queue each time an error is signalled. When the error queue is not emptied, strange things can happen on the next SSL call, depending on the OpenSSL version. ........ Modified: python/branches/release26-maint/ (props changed) python/branches/release26-maint/Modules/_ssl.c Modified: python/branches/release26-maint/Modules/_ssl.c ============================================================================== --- python/branches/release26-maint/Modules/_ssl.c (original) +++ python/branches/release26-maint/Modules/_ssl.c Mon May 17 01:14:34 2010 @@ -196,6 +196,7 @@ errstr = "EOF occurred in violation of protocol"; } else if (ret == -1) { /* underlying BIO reported an I/O error */ + ERR_clear_error(); return obj->Socket->errorhandler(); } else { /* possible? */ p = PY_SSL_ERROR_SYSCALL; @@ -228,6 +229,7 @@ errstr = ERR_error_string(ERR_peek_last_error(), NULL); } PyOS_snprintf(buf, sizeof(buf), "_ssl.c:%d: %s", lineno, errstr); + ERR_clear_error(); v = Py_BuildValue("(is)", p, buf); if (v != NULL) { PyErr_SetObject(PySSLErrorObject, v); @@ -247,6 +249,7 @@ errstr = ERR_error_string(errcode, NULL); } PyOS_snprintf(buf, sizeof(buf), "_ssl.c:%d: %s", lineno, errstr); + ERR_clear_error(); v = Py_BuildValue("(is)", errcode, buf); if (v != NULL) { PyErr_SetObject(PySSLErrorObject, v); From python-checkins at python.org Mon May 17 01:18:00 2010 From: python-checkins at python.org (antoine.pitrou) Date: Mon, 17 May 2010 01:18:00 +0200 (CEST) Subject: [Python-checkins] r81244 - in python/branches/release31-maint: Modules/_ssl.c Message-ID: <20100516231800.86265EEAD6@mail.python.org> Author: antoine.pitrou Date: Mon May 17 01:18:00 2010 New Revision: 81244 Log: Merged revisions 81242 via svnmerge from svn+ssh://pythondev at svn.python.org/python/branches/py3k ................ r81242 | antoine.pitrou | 2010-05-17 01:14:22 +0200 (lun., 17 mai 2010) | 10 lines Merged revisions 81241 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r81241 | antoine.pitrou | 2010-05-17 01:11:46 +0200 (lun., 17 mai 2010) | 4 lines Clear the OpenSSL error queue each time an error is signalled. When the error queue is not emptied, strange things can happen on the next SSL call, depending on the OpenSSL version. ........ ................ Modified: python/branches/release31-maint/ (props changed) python/branches/release31-maint/Modules/_ssl.c Modified: python/branches/release31-maint/Modules/_ssl.c ============================================================================== --- python/branches/release31-maint/Modules/_ssl.c (original) +++ python/branches/release31-maint/Modules/_ssl.c Mon May 17 01:18:00 2010 @@ -199,6 +199,7 @@ errstr = "EOF occurred in violation of protocol"; } else if (ret == -1) { /* underlying BIO reported an I/O error */ + ERR_clear_error(); return s->errorhandler(); } else { /* possible? */ p = PY_SSL_ERROR_SYSCALL; @@ -231,6 +232,7 @@ errstr = ERR_error_string(ERR_peek_last_error(), NULL); } PyOS_snprintf(buf, sizeof(buf), "_ssl.c:%d: %s", lineno, errstr); + ERR_clear_error(); v = Py_BuildValue("(is)", p, buf); if (v != NULL) { PyErr_SetObject(PySSLErrorObject, v); @@ -250,6 +252,7 @@ errstr = ERR_error_string(errcode, NULL); } PyOS_snprintf(buf, sizeof(buf), "_ssl.c:%d: %s", lineno, errstr); + ERR_clear_error(); v = Py_BuildValue("(is)", errcode, buf); if (v != NULL) { PyErr_SetObject(PySSLErrorObject, v); From solipsis at pitrou.net Mon May 17 01:23:44 2010 From: solipsis at pitrou.net (solipsis at pitrou.net) Date: Mon, 17 May 2010 01:23:44 +0200 (CEST) Subject: [Python-checkins] Daily py3k reference leaks (r81236): sum=0 Message-ID: <20100516232344.E57461770A@ns6635.ovh.net> py3k results for svn r81236 (hg cset 6f3b2812a570) -------------------------------------------------- Command line was: ['./python', '-m', 'test.regrtest', '-uall', '-R', '3:3:/home/antoine/py3k/refleaks/reflog6lEvIZ', '-x'] From python-checkins at python.org Mon May 17 01:31:16 2010 From: python-checkins at python.org (andrew.kuchling) Date: Mon, 17 May 2010 01:31:16 +0200 (CEST) Subject: [Python-checkins] r81245 - python/trunk/Doc/library/logging.rst Message-ID: <20100516233116.44848C982@mail.python.org> Author: andrew.kuchling Date: Mon May 17 01:31:16 2010 New Revision: 81245 Log: Add cross-reference to later section Modified: python/trunk/Doc/library/logging.rst Modified: python/trunk/Doc/library/logging.rst ============================================================================== --- python/trunk/Doc/library/logging.rst (original) +++ python/trunk/Doc/library/logging.rst Mon May 17 01:31:16 2010 @@ -2733,9 +2733,9 @@ All other keys are optional, but if present they will be interpreted as described below. In all cases below where a 'configuring dict' is mentioned, it will be checked for the special ``'()'`` key to see if a -custom instantiation is required. If so, the mechanism described -above is used to instantiate; otherwise, the context is used to -determine how to instantiate. +custom instantiation is required. If so, the mechanism described in +:ref:`logging-config-dict-userdef` below is used to create an instance; +otherwise, the context is used to determine what to instantiate. * `formatters` - the corresponding value will be a dict in which each key is a formatter id and each value is a dict describing how to From python-checkins at python.org Mon May 17 01:46:27 2010 From: python-checkins at python.org (antoine.pitrou) Date: Mon, 17 May 2010 01:46:27 +0200 (CEST) Subject: [Python-checkins] r81246 - python/branches/py3k/Lib/test/test_ssl.py Message-ID: <20100516234627.138B3EE990@mail.python.org> Author: antoine.pitrou Date: Mon May 17 01:46:26 2010 New Revision: 81246 Log: "xyzzy" is not a silly enough name for some OpenSSL versions to report an error Modified: python/branches/py3k/Lib/test/test_ssl.py Modified: python/branches/py3k/Lib/test/test_ssl.py ============================================================================== --- python/branches/py3k/Lib/test/test_ssl.py (original) +++ python/branches/py3k/Lib/test/test_ssl.py Mon May 17 01:46:26 2010 @@ -143,7 +143,7 @@ # Error checking can happen at instantiation or when connecting with self.assertRaisesRegexp(ssl.SSLError, "No cipher can be selected"): s = ssl.wrap_socket(socket.socket(socket.AF_INET), - cert_reqs=ssl.CERT_NONE, ciphers="xyzzy") + cert_reqs=ssl.CERT_NONE, ciphers="^$:,;?*'dorothyx") s.connect(remote) @support.cpython_only @@ -187,7 +187,7 @@ ctx.set_ciphers("ALL") ctx.set_ciphers("DEFAULT") with self.assertRaisesRegexp(ssl.SSLError, "No cipher can be selected"): - ctx.set_ciphers("xyzzy") + ctx.set_ciphers("^$:,;?*'dorothyx") def test_verify(self): ctx = ssl.SSLContext(ssl.PROTOCOL_TLSv1) From python-checkins at python.org Mon May 17 02:14:53 2010 From: python-checkins at python.org (victor.stinner) Date: Mon, 17 May 2010 02:14:53 +0200 (CEST) Subject: [Python-checkins] r81247 - python/branches/py3k/Lib/test/test_os.py Message-ID: <20100517001453.CAC21EE990@mail.python.org> Author: victor.stinner Date: Mon May 17 02:14:53 2010 New Revision: 81247 Log: test_os: cleanup test_internal_execvpe() and os._execvpe() mockup * Replace os.defpath instead of os.get_exec_path() to test also os.get_exec_path() * Use contextlib.contextmanager, move the mockup outside the class, and the mockup returns directly the call list object * Use two different contexts for the two tests * Use more revelant values and names Modified: python/branches/py3k/Lib/test/test_os.py Modified: python/branches/py3k/Lib/test/test_os.py ============================================================================== --- python/branches/py3k/Lib/test/test_os.py (original) +++ python/branches/py3k/Lib/test/test_os.py Mon May 17 02:14:53 2010 @@ -12,6 +12,7 @@ import time import shutil from test import support +import contextlib # Detect whether we're on a Linux system that uses the (now outdated # and unmaintained) linuxthreads threading library. There's an issue @@ -623,6 +624,39 @@ except NotImplementedError: pass + at contextlib.contextmanager +def _execvpe_mockup(defpath=None): + """ + Stubs out execv and execve functions when used as context manager. + Records exec calls. The mock execv and execve functions always raise an + exception as they would normally never return. + """ + # A list of tuples containing (function name, first arg, args) + # of calls to execv or execve that have been made. + calls = [] + + def mock_execv(name, *args): + calls.append(('execv', name, args)) + raise RuntimeError("execv called") + + def mock_execve(name, *args): + calls.append(('execve', name, args)) + raise OSError(errno.ENOTDIR, "execve called") + + try: + orig_execv = os.execv + orig_execve = os.execve + orig_defpath = os.defpath + os.execv = mock_execv + os.execve = mock_execve + if defpath is not None: + os.defpath = defpath + yield calls + finally: + os.execv = orig_execv + os.execve = orig_execve + os.defpath = orig_defpath + class ExecTests(unittest.TestCase): @unittest.skipIf(USING_LINUXTHREADS, "avoid triggering a linuxthreads bug: see issue #4970") @@ -633,57 +667,28 @@ def test_execvpe_with_bad_arglist(self): self.assertRaises(ValueError, os.execvpe, 'notepad', [], None) - class _stub_out_for_execvpe_test(object): - """ - Stubs out execv, execve and get_exec_path functions when - used as context manager. Records exec calls. The mock execv - and execve functions always raise an exception as they would - normally never return. - """ - def __init__(self): - # A list of tuples containing (function name, first arg, args) - # of calls to execv or execve that have been made. - self.calls = [] - def _mock_execv(self, name, *args): - self.calls.append(('execv', name, args)) - raise RuntimeError("execv called") - - def _mock_execve(self, name, *args): - self.calls.append(('execve', name, args)) - raise OSError(errno.ENOTDIR, "execve called") - - def _mock_get_exec_path(self, env=None): - return [os.sep+'p', os.sep+'pp'] - - def __enter__(self): - self.orig_execv = os.execv - self.orig_execve = os.execve - self.orig_get_exec_path = os.get_exec_path - os.execv = self._mock_execv - os.execve = self._mock_execve - os.get_exec_path = self._mock_get_exec_path - - def __exit__(self, type, value, tb): - os.execv = self.orig_execv - os.execve = self.orig_execve - os.get_exec_path = self.orig_get_exec_path - @unittest.skipUnless(hasattr(os, '_execvpe'), "No internal os._execvpe function to test.") def test_internal_execvpe(self): - exec_stubbed = self._stub_out_for_execvpe_test() - with exec_stubbed: - self.assertRaises(RuntimeError, os._execvpe, os.sep+'f', ['-a']) - self.assertEqual([('execv', os.sep+'f', (['-a'],))], - exec_stubbed.calls) - exec_stubbed.calls = [] - self.assertRaises(OSError, os._execvpe, 'f', ['-a'], - env={'spam': 'beans'}) - self.assertEqual([('execve', os.sep+'p'+os.sep+'f', - (['-a'], {'spam': 'beans'})), - ('execve', os.sep+'pp'+os.sep+'f', - (['-a'], {'spam': 'beans'}))], - exec_stubbed.calls) + program_path = os.sep+'absolutepath' + program = 'executable' + fullpath = os.path.join(program_path, program) + arguments = ['progname', 'arg1', 'arg2'] + env = {'spam': 'beans'} + + with _execvpe_mockup() as calls: + self.assertRaises(RuntimeError, os._execvpe, fullpath, arguments) + self.assertEqual(len(calls), 1) + self.assertEqual(calls[0], ('execv', fullpath, (arguments,))) + + with _execvpe_mockup(defpath=program_path) as calls: + self.assertRaises(OSError, os._execvpe, program, arguments, env=env) + self.assertEqual(len(calls), 1) + if os.name != "nt": + self.assertEqual(calls[0], ('execve', os.fsencode(fullpath), (arguments, env))) + else: + self.assertEqual(calls[0], ('execve', fullpath, (arguments, env))) + class Win32ErrorTests(unittest.TestCase): def test_rename(self): From python-checkins at python.org Mon May 17 02:15:47 2010 From: python-checkins at python.org (victor.stinner) Date: Mon, 17 May 2010 02:15:47 +0200 (CEST) Subject: [Python-checkins] r81248 - python/branches/release31-maint Message-ID: <20100517001547.32C93EE990@mail.python.org> Author: victor.stinner Date: Mon May 17 02:15:47 2010 New Revision: 81248 Log: Blocked revisions 81247 via svnmerge ........ r81247 | victor.stinner | 2010-05-17 02:14:53 +0200 (lun., 17 mai 2010) | 9 lines test_os: cleanup test_internal_execvpe() and os._execvpe() mockup * Replace os.defpath instead of os.get_exec_path() to test also os.get_exec_path() * Use contextlib.contextmanager, move the mockup outside the class, and the mockup returns directly the call list object * Use two different contexts for the two tests * Use more revelant values and names ........ Modified: python/branches/release31-maint/ (props changed) From python-checkins at python.org Mon May 17 02:18:34 2010 From: python-checkins at python.org (victor.stinner) Date: Mon, 17 May 2010 02:18:34 +0200 (CEST) Subject: [Python-checkins] r81249 - python/branches/py3k/Lib/test/test_os.py Message-ID: <20100517001834.4BC68EE990@mail.python.org> Author: victor.stinner Date: Mon May 17 02:18:34 2010 New Revision: 81249 Log: Oops, my patch on subprocess is not merged yet: fix my previous commit on test_os Modified: python/branches/py3k/Lib/test/test_os.py Modified: python/branches/py3k/Lib/test/test_os.py ============================================================================== --- python/branches/py3k/Lib/test/test_os.py (original) +++ python/branches/py3k/Lib/test/test_os.py Mon May 17 02:18:34 2010 @@ -684,10 +684,7 @@ with _execvpe_mockup(defpath=program_path) as calls: self.assertRaises(OSError, os._execvpe, program, arguments, env=env) self.assertEqual(len(calls), 1) - if os.name != "nt": - self.assertEqual(calls[0], ('execve', os.fsencode(fullpath), (arguments, env))) - else: - self.assertEqual(calls[0], ('execve', fullpath, (arguments, env))) + self.assertEqual(calls[0], ('execve', fullpath, (arguments, env))) class Win32ErrorTests(unittest.TestCase): From python-checkins at python.org Mon May 17 03:13:37 2010 From: python-checkins at python.org (victor.stinner) Date: Mon, 17 May 2010 03:13:37 +0200 (CEST) Subject: [Python-checkins] r81250 - in python/branches/py3k: Lib/test/test_sys.py Modules/main.c Message-ID: <20100517011337.70BB6EE9EF@mail.python.org> Author: victor.stinner Date: Mon May 17 03:13:37 2010 New Revision: 81250 Log: Issue #6697: Fix a crash if code of "python -c code" contains surrogates Modified: python/branches/py3k/Lib/test/test_sys.py python/branches/py3k/Modules/main.c Modified: python/branches/py3k/Lib/test/test_sys.py ============================================================================== --- python/branches/py3k/Lib/test/test_sys.py (original) +++ python/branches/py3k/Lib/test/test_sys.py Mon May 17 03:13:37 2010 @@ -449,6 +449,24 @@ self.assertRaises(TypeError, sys.intern, S("abc")) + def test_main_invalid_unicode(self): + import locale + non_decodable = b"\xff" + encoding = locale.getpreferredencoding() + try: + non_decodable.decode(encoding) + except UnicodeDecodeError: + pass + else: + self.skipTest('%r is decodable with encoding %s' + % (non_decodable, encoding)) + code = b'print("' + non_decodable + b'")' + p = subprocess.Popen([sys.executable, "-c", code], stderr=subprocess.PIPE) + stdout, stderr = p.communicate() + self.assertEqual(p.returncode, 1) + self.assert_(stderr.startswith(b"UnicodeEncodeError: " + b"'utf-8' codec can't encode character '\\udcff' in " + b"position 7: surrogates not allowed"), stderr) def test_sys_flags(self): self.assertTrue(sys.flags) Modified: python/branches/py3k/Modules/main.c ============================================================================== --- python/branches/py3k/Modules/main.c (original) +++ python/branches/py3k/Modules/main.c Mon May 17 03:13:37 2010 @@ -563,18 +563,22 @@ } if (command) { + char *commandStr; PyObject *commandObj = PyUnicode_FromWideChar( command, wcslen(command)); free(command); - if (commandObj != NULL) { - sts = PyRun_SimpleStringFlags( - _PyUnicode_AsString(commandObj), &cf) != 0; + if (commandObj != NULL) + commandStr = _PyUnicode_AsString(commandObj); + else + commandStr = NULL; + if (commandStr != NULL) { + sts = PyRun_SimpleStringFlags(commandStr, &cf) != 0; + Py_DECREF(commandObj); } else { PyErr_Print(); sts = 1; } - Py_DECREF(commandObj); } else if (module) { sts = RunModule(module, 1); } From python-checkins at python.org Mon May 17 03:26:02 2010 From: python-checkins at python.org (victor.stinner) Date: Mon, 17 May 2010 03:26:02 +0200 (CEST) Subject: [Python-checkins] r81251 - in python/branches/py3k: Lib/test/test_sys.py Misc/NEWS Objects/object.c Message-ID: <20100517012602.14271EE9EF@mail.python.org> Author: victor.stinner Date: Mon May 17 03:26:01 2010 New Revision: 81251 Log: PyObject_Dump() encodes unicode objects to utf8 with backslashreplace (instead of strict) error handler to escape surrogates Modified: python/branches/py3k/Lib/test/test_sys.py python/branches/py3k/Misc/NEWS python/branches/py3k/Objects/object.c Modified: python/branches/py3k/Lib/test/test_sys.py ============================================================================== --- python/branches/py3k/Lib/test/test_sys.py (original) +++ python/branches/py3k/Lib/test/test_sys.py Mon May 17 03:26:01 2010 @@ -145,6 +145,16 @@ "raise SystemExit(47)"]) self.assertEqual(rc, 47) + # test that the exit message is written with backslashreplace error + # handler to stderr + import subprocess + code = r'import sys; sys.exit("surrogates:\uDCFF")' + process = subprocess.Popen([sys.executable, "-c", code], + stderr=subprocess.PIPE) + stdout, stderr = process.communicate() + self.assertEqual(process.returncode, 1) + self.assertTrue(stderr.startswith(b"surrogates:\\udcff"), stderr) + def test_getdefaultencoding(self): self.assertRaises(TypeError, sys.getdefaultencoding, 42) # can't check more than the type, as the user might have changed it Modified: python/branches/py3k/Misc/NEWS ============================================================================== --- python/branches/py3k/Misc/NEWS (original) +++ python/branches/py3k/Misc/NEWS Mon May 17 03:26:01 2010 @@ -12,6 +12,9 @@ Core and Builtins ----------------- +- PyObject_Dump() encodes unicode objects to utf8 with backslashreplace + (instead of strict) error handler to escape surrogates + - Issue #8715: Create PyUnicode_EncodeFSDefault() function: Encode a Unicode object to Py_FileSystemDefaultEncoding with the "surrogateescape" error handler, and return bytes. If Py_FileSystemDefaultEncoding is not set, fall Modified: python/branches/py3k/Objects/object.c ============================================================================== --- python/branches/py3k/Objects/object.c (original) +++ python/branches/py3k/Objects/object.c Mon May 17 03:26:01 2010 @@ -303,7 +303,9 @@ } else if (PyUnicode_Check(s)) { PyObject *t; - t = _PyUnicode_AsDefaultEncodedString(s, NULL); + t = PyUnicode_EncodeUTF8(PyUnicode_AS_UNICODE(s), + PyUnicode_GET_SIZE(s), + "backslashreplace"); if (t == NULL) ret = 0; else { From python-checkins at python.org Mon May 17 10:58:51 2010 From: python-checkins at python.org (victor.stinner) Date: Mon, 17 May 2010 10:58:51 +0200 (CEST) Subject: [Python-checkins] r81252 - in python/branches/py3k: Lib/test/test_sys.py Python/pythonrun.c Message-ID: <20100517085851.53A66C97B@mail.python.org> Author: victor.stinner Date: Mon May 17 10:58:51 2010 New Revision: 81252 Log: handle_system_exit() flushs files to warranty the output order PyObject_Print() writes into the C object stderr, whereas PySys_WriteStderr() writes into the Python object sys.stderr. Each object has its own buffer, so call sys.stderr.flush() and fflush(stderr). Modified: python/branches/py3k/Lib/test/test_sys.py python/branches/py3k/Python/pythonrun.c Modified: python/branches/py3k/Lib/test/test_sys.py ============================================================================== --- python/branches/py3k/Lib/test/test_sys.py (original) +++ python/branches/py3k/Lib/test/test_sys.py Mon May 17 10:58:51 2010 @@ -86,6 +86,8 @@ # Python/pythonrun.c::PyErr_PrintEx() is tricky. def test_exit(self): + import subprocess + self.assertRaises(TypeError, sys.exit, 42, 42) # call without argument @@ -140,20 +142,28 @@ self.fail("no exception") # test that the exit machinery handles SystemExits properly - import subprocess rc = subprocess.call([sys.executable, "-c", "raise SystemExit(47)"]) self.assertEqual(rc, 47) + def check_exit_message(code, expected): + process = subprocess.Popen([sys.executable, "-c", code], + stderr=subprocess.PIPE) + stdout, stderr = process.communicate() + self.assertEqual(process.returncode, 1) + self.assertTrue(stderr.startswith(expected), stderr) + + # test that stderr buffer if flushed before the exit message is written + # into stderr + check_exit_message( + r'import sys; sys.stderr.write("unflushed,"); sys.exit("message")', + b"unflushed,message") + # test that the exit message is written with backslashreplace error # handler to stderr - import subprocess - code = r'import sys; sys.exit("surrogates:\uDCFF")' - process = subprocess.Popen([sys.executable, "-c", code], - stderr=subprocess.PIPE) - stdout, stderr = process.communicate() - self.assertEqual(process.returncode, 1) - self.assertTrue(stderr.startswith(b"surrogates:\\udcff"), stderr) + check_exit_message( + r'import sys; sys.exit("surrogates:\uDCFF")', + b"surrogates:\\udcff") def test_getdefaultencoding(self): self.assertRaises(TypeError, sys.getdefaultencoding, 42) Modified: python/branches/py3k/Python/pythonrun.c ============================================================================== --- python/branches/py3k/Python/pythonrun.c (original) +++ python/branches/py3k/Python/pythonrun.c Mon May 17 10:58:51 2010 @@ -1367,7 +1367,11 @@ if (PyLong_Check(value)) exitcode = (int)PyLong_AsLong(value); else { + PyObject *sys_stderr = PySys_GetObject("stderr"); + if (sys_stderr != NULL) + PyObject_CallMethod(sys_stderr, "flush", NULL); PyObject_Print(value, stderr, Py_PRINT_RAW); + fflush(stderr); PySys_WriteStderr("\n"); exitcode = 1; } From python-checkins at python.org Mon May 17 11:33:43 2010 From: python-checkins at python.org (victor.stinner) Date: Mon, 17 May 2010 11:33:43 +0200 (CEST) Subject: [Python-checkins] r81253 - python/branches/py3k/Objects/object.c Message-ID: <20100517093343.04067EE9BF@mail.python.org> Author: victor.stinner Date: Mon May 17 11:33:42 2010 New Revision: 81253 Log: Fix refleak in internal_print() introduced by myself in r81251 _PyUnicode_AsDefaultEncodedString() uses a magical PyUnicode attribute to automatically destroy PyUnicode_EncodeUTF8() result when the unicode string is destroyed. Modified: python/branches/py3k/Objects/object.c Modified: python/branches/py3k/Objects/object.c ============================================================================== --- python/branches/py3k/Objects/object.c (original) +++ python/branches/py3k/Objects/object.c Mon May 17 11:33:42 2010 @@ -311,6 +311,7 @@ else { fwrite(PyBytes_AS_STRING(t), 1, PyBytes_GET_SIZE(t), fp); + Py_DECREF(t); } } else { From python-checkins at python.org Mon May 17 11:35:45 2010 From: python-checkins at python.org (victor.stinner) Date: Mon, 17 May 2010 11:35:45 +0200 (CEST) Subject: [Python-checkins] r81254 - in python/branches/release31-maint: Lib/test/test_sys.py Misc/NEWS Modules/main.c Objects/object.c Python/pythonrun.c Message-ID: <20100517093545.2A56DEEA08@mail.python.org> Author: victor.stinner Date: Mon May 17 11:35:44 2010 New Revision: 81254 Log: Merged revisions 81250-81253 via svnmerge from svn+ssh://pythondev at svn.python.org/python/branches/py3k ........ r81250 | victor.stinner | 2010-05-17 03:13:37 +0200 (lun., 17 mai 2010) | 2 lines Issue #6697: Fix a crash if code of "python -c code" contains surrogates ........ r81251 | victor.stinner | 2010-05-17 03:26:01 +0200 (lun., 17 mai 2010) | 3 lines PyObject_Dump() encodes unicode objects to utf8 with backslashreplace (instead of strict) error handler to escape surrogates ........ r81252 | victor.stinner | 2010-05-17 10:58:51 +0200 (lun., 17 mai 2010) | 6 lines handle_system_exit() flushs files to warranty the output order PyObject_Print() writes into the C object stderr, whereas PySys_WriteStderr() writes into the Python object sys.stderr. Each object has its own buffer, so call sys.stderr.flush() and fflush(stderr). ........ r81253 | victor.stinner | 2010-05-17 11:33:42 +0200 (lun., 17 mai 2010) | 6 lines Fix refleak in internal_print() introduced by myself in r81251 _PyUnicode_AsDefaultEncodedString() uses a magical PyUnicode attribute to automatically destroy PyUnicode_EncodeUTF8() result when the unicode string is destroyed. ........ Modified: python/branches/release31-maint/ (props changed) python/branches/release31-maint/Lib/test/test_sys.py python/branches/release31-maint/Misc/NEWS python/branches/release31-maint/Modules/main.c python/branches/release31-maint/Objects/object.c python/branches/release31-maint/Python/pythonrun.c Modified: python/branches/release31-maint/Lib/test/test_sys.py ============================================================================== --- python/branches/release31-maint/Lib/test/test_sys.py (original) +++ python/branches/release31-maint/Lib/test/test_sys.py Mon May 17 11:35:44 2010 @@ -79,6 +79,8 @@ # Python/pythonrun.c::PyErr_PrintEx() is tricky. def test_exit(self): + import subprocess + self.assertRaises(TypeError, sys.exit, 42, 42) # call without argument @@ -133,11 +135,29 @@ self.fail("no exception") # test that the exit machinery handles SystemExits properly - import subprocess rc = subprocess.call([sys.executable, "-c", "raise SystemExit(47)"]) self.assertEqual(rc, 47) + def check_exit_message(code, expected): + process = subprocess.Popen([sys.executable, "-c", code], + stderr=subprocess.PIPE) + stdout, stderr = process.communicate() + self.assertEqual(process.returncode, 1) + self.assertTrue(stderr.startswith(expected), stderr) + + # test that stderr buffer if flushed before the exit message is written + # into stderr + check_exit_message( + r'import sys; sys.stderr.write("unflushed,"); sys.exit("message")', + b"unflushed,message") + + # test that the exit message is written with backslashreplace error + # handler to stderr + check_exit_message( + r'import sys; sys.exit("surrogates:\uDCFF")', + b"surrogates:\\udcff") + def test_getdefaultencoding(self): self.assertRaises(TypeError, sys.getdefaultencoding, 42) # can't check more than the type, as the user might have changed it @@ -403,6 +423,24 @@ self.assertRaises(TypeError, sys.intern, S("abc")) + def test_main_invalid_unicode(self): + import locale + non_decodable = b"\xff" + encoding = locale.getpreferredencoding() + try: + non_decodable.decode(encoding) + except UnicodeDecodeError: + pass + else: + self.skipTest('%r is decodable with encoding %s' + % (non_decodable, encoding)) + code = b'print("' + non_decodable + b'")' + p = subprocess.Popen([sys.executable, "-c", code], stderr=subprocess.PIPE) + stdout, stderr = p.communicate() + self.assertEqual(p.returncode, 1) + self.assert_(stderr.startswith(b"UnicodeEncodeError: " + b"'utf-8' codec can't encode character '\\udcff' in " + b"position 7: surrogates not allowed"), stderr) def test_sys_flags(self): self.assertTrue(sys.flags) Modified: python/branches/release31-maint/Misc/NEWS ============================================================================== --- python/branches/release31-maint/Misc/NEWS (original) +++ python/branches/release31-maint/Misc/NEWS Mon May 17 11:35:44 2010 @@ -12,6 +12,9 @@ Core and Builtins ----------------- +- PyObject_Dump() encodes unicode objects to utf8 with backslashreplace + (instead of strict) error handler to escape surrogates + - Issue #8124: PySys_WriteStdout() and PySys_WriteStderr() don't execute indirectly Python signal handlers anymore because mywrite() ignores exceptions (KeyboardInterrupt) Modified: python/branches/release31-maint/Modules/main.c ============================================================================== --- python/branches/release31-maint/Modules/main.c (original) +++ python/branches/release31-maint/Modules/main.c Mon May 17 11:35:44 2010 @@ -516,18 +516,22 @@ } if (command) { + char *commandStr; PyObject *commandObj = PyUnicode_FromWideChar( command, wcslen(command)); free(command); - if (commandObj != NULL) { - sts = PyRun_SimpleStringFlags( - _PyUnicode_AsString(commandObj), &cf) != 0; + if (commandObj != NULL) + commandStr = _PyUnicode_AsString(commandObj); + else + commandStr = NULL; + if (commandStr != NULL) { + sts = PyRun_SimpleStringFlags(commandStr, &cf) != 0; + Py_DECREF(commandObj); } else { PyErr_Print(); sts = 1; } - Py_DECREF(commandObj); } else if (module) { sts = RunModule(module, 1); } Modified: python/branches/release31-maint/Objects/object.c ============================================================================== --- python/branches/release31-maint/Objects/object.c (original) +++ python/branches/release31-maint/Objects/object.c Mon May 17 11:35:44 2010 @@ -303,12 +303,15 @@ } else if (PyUnicode_Check(s)) { PyObject *t; - t = _PyUnicode_AsDefaultEncodedString(s, NULL); + t = PyUnicode_EncodeUTF8(PyUnicode_AS_UNICODE(s), + PyUnicode_GET_SIZE(s), + "backslashreplace"); if (t == NULL) ret = 0; else { fwrite(PyBytes_AS_STRING(t), 1, PyBytes_GET_SIZE(t), fp); + Py_DECREF(t); } } else { Modified: python/branches/release31-maint/Python/pythonrun.c ============================================================================== --- python/branches/release31-maint/Python/pythonrun.c (original) +++ python/branches/release31-maint/Python/pythonrun.c Mon May 17 11:35:44 2010 @@ -1353,7 +1353,11 @@ if (PyLong_Check(value)) exitcode = (int)PyLong_AsLong(value); else { + PyObject *sys_stderr = PySys_GetObject("stderr"); + if (sys_stderr != NULL) + PyObject_CallMethod(sys_stderr, "flush", NULL); PyObject_Print(value, stderr, Py_PRINT_RAW); + fflush(stderr); PySys_WriteStderr("\n"); exitcode = 1; } From python-checkins at python.org Mon May 17 12:06:21 2010 From: python-checkins at python.org (tarek.ziade) Date: Mon, 17 May 2010 12:06:21 +0200 (CEST) Subject: [Python-checkins] r81255 - in python/trunk: Lib/distutils/command/sdist.py Lib/distutils/tests/test_sdist.py Misc/NEWS Message-ID: <20100517100621.16736EE997@mail.python.org> Author: tarek.ziade Date: Mon May 17 12:06:20 2010 New Revision: 81255 Log: Fixed #8688: Distutils now recalculates MANIFEST everytime. Modified: python/trunk/Lib/distutils/command/sdist.py python/trunk/Lib/distutils/tests/test_sdist.py python/trunk/Misc/NEWS Modified: python/trunk/Lib/distutils/command/sdist.py ============================================================================== --- python/trunk/Lib/distutils/command/sdist.py (original) +++ python/trunk/Lib/distutils/command/sdist.py Mon May 17 12:06:20 2010 @@ -179,66 +179,34 @@ distribution, and put it in 'self.filelist'. This might involve reading the manifest template (and writing the manifest), or just reading the manifest, or just using the default file set -- it all - depends on the user's options and the state of the filesystem. + depends on the user's options. """ - # If we have a manifest template, see if it's newer than the - # manifest; if so, we'll regenerate the manifest. + # new behavior: + # the file list is recalculated everytime because + # even if MANIFEST.in or setup.py are not changed + # the user might have added some files in the tree that + # need to be included. + # + # This makes --force the default and only behavior. template_exists = os.path.isfile(self.template) + if not template_exists: + self.warn(("manifest template '%s' does not exist " + + "(using default file list)") % + self.template) + self.filelist.findall() + + if self.use_defaults: + self.add_defaults() + if template_exists: - template_newer = dep_util.newer(self.template, self.manifest) + self.read_template() - # The contents of the manifest file almost certainly depend on the - # setup script as well as the manifest template -- so if the setup - # script is newer than the manifest, we'll regenerate the manifest - # from the template. (Well, not quite: if we already have a - # manifest, but there's no template -- which will happen if the - # developer elects to generate a manifest some other way -- then we - # can't regenerate the manifest, so we don't.) - self.debug_print("checking if %s newer than %s" % - (self.distribution.script_name, self.manifest)) - setup_newer = dep_util.newer(self.distribution.script_name, - self.manifest) - - # cases: - # 1) no manifest, template exists: generate manifest - # (covered by 2a: no manifest == template newer) - # 2) manifest & template exist: - # 2a) template or setup script newer than manifest: - # regenerate manifest - # 2b) manifest newer than both: - # do nothing (unless --force or --manifest-only) - # 3) manifest exists, no template: - # do nothing (unless --force or --manifest-only) - # 4) no manifest, no template: generate w/ warning ("defaults only") - - manifest_outofdate = (template_exists and - (template_newer or setup_newer)) - force_regen = self.force_manifest or self.manifest_only - manifest_exists = os.path.isfile(self.manifest) - neither_exists = (not template_exists and not manifest_exists) - - # Regenerate the manifest if necessary (or if explicitly told to) - if manifest_outofdate or neither_exists or force_regen: - if not template_exists: - self.warn(("manifest template '%s' does not exist " + - "(using default file list)") % - self.template) - self.filelist.findall() - - if self.use_defaults: - self.add_defaults() - if template_exists: - self.read_template() - if self.prune: - self.prune_file_list() - - self.filelist.sort() - self.filelist.remove_duplicates() - self.write_manifest() + if self.prune: + self.prune_file_list() - # Don't regenerate the manifest, just read it in. - else: - self.read_manifest() + self.filelist.sort() + self.filelist.remove_duplicates() + self.write_manifest() def add_defaults(self): """Add all the default files to self.filelist: Modified: python/trunk/Lib/distutils/tests/test_sdist.py ============================================================================== --- python/trunk/Lib/distutils/tests/test_sdist.py (original) +++ python/trunk/Lib/distutils/tests/test_sdist.py Mon May 17 12:06:20 2010 @@ -346,6 +346,47 @@ finally: archive.close() + def test_get_file_list(self): + # make sure MANIFEST is recalculated + dist, cmd = self.get_cmd() + + # filling data_files by pointing files in package_data + dist.package_data = {'somecode': ['*.txt']} + self.write_file((self.tmp_dir, 'somecode', 'doc.txt'), '#') + cmd.ensure_finalized() + cmd.run() + + f = open(cmd.manifest) + try: + manifest = [line.strip() for line in f.read().split('\n') + if line.strip() != ''] + finally: + f.close() + + self.assertEquals(len(manifest), 4) + + # adding a file + self.write_file((self.tmp_dir, 'somecode', 'doc2.txt'), '#') + + # make sure build_py is reinitinialized, like a fresh run + build_py = dist.get_command_obj('build_py') + build_py.finalized = False + build_py.ensure_finalized() + + cmd.run() + + f = open(cmd.manifest) + try: + manifest2 = [line.strip() for line in f.read().split('\n') + if line.strip() != ''] + finally: + f.close() + + # do we have the new file in MANIFEST ? + self.assertEquals(len(manifest2), 5) + self.assertIn('doc2.txt', manifest2[-1]) + + def test_suite(): return unittest.makeSuite(SDistTestCase) Modified: python/trunk/Misc/NEWS ============================================================================== --- python/trunk/Misc/NEWS (original) +++ python/trunk/Misc/NEWS Mon May 17 12:06:20 2010 @@ -15,6 +15,8 @@ Library ------- +- Issue #8688: Distutils now recalculates MANIFEST everytime. + - Issue #5099: subprocess.Popen's __del__ method (and the methods it calls) referenced global objects, causing errors to pop up during interpreter shutdown. From python-checkins at python.org Mon May 17 12:26:15 2010 From: python-checkins at python.org (tarek.ziade) Date: Mon, 17 May 2010 12:26:15 +0200 (CEST) Subject: [Python-checkins] r81256 - in python/branches/release26-maint: Lib/distutils/command/sdist.py Lib/distutils/tests/test_sdist.py Misc/NEWS Message-ID: <20100517102615.4C8EAEE9BF@mail.python.org> Author: tarek.ziade Date: Mon May 17 12:26:15 2010 New Revision: 81256 Log: Merged revisions 81255 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r81255 | tarek.ziade | 2010-05-17 12:06:20 +0200 (Mon, 17 May 2010) | 1 line Fixed #8688: Distutils now recalculates MANIFEST everytime. ........ Modified: python/branches/release26-maint/ (props changed) python/branches/release26-maint/Lib/distutils/command/sdist.py python/branches/release26-maint/Lib/distutils/tests/test_sdist.py python/branches/release26-maint/Misc/NEWS Modified: python/branches/release26-maint/Lib/distutils/command/sdist.py ============================================================================== --- python/branches/release26-maint/Lib/distutils/command/sdist.py (original) +++ python/branches/release26-maint/Lib/distutils/command/sdist.py Mon May 17 12:26:15 2010 @@ -190,67 +190,34 @@ distribution, and put it in 'self.filelist'. This might involve reading the manifest template (and writing the manifest), or just reading the manifest, or just using the default file set -- it all - depends on the user's options and the state of the filesystem. + depends on the user's options. """ - - # If we have a manifest template, see if it's newer than the - # manifest; if so, we'll regenerate the manifest. + # new behavior: + # the file list is recalculated everytime because + # even if MANIFEST.in or setup.py are not changed + # the user might have added some files in the tree that + # need to be included. + # + # This makes --force the default and only behavior. template_exists = os.path.isfile(self.template) + if not template_exists: + self.warn(("manifest template '%s' does not exist " + + "(using default file list)") % + self.template) + self.filelist.findall() + + if self.use_defaults: + self.add_defaults() + if template_exists: - template_newer = dep_util.newer(self.template, self.manifest) + self.read_template() - # The contents of the manifest file almost certainly depend on the - # setup script as well as the manifest template -- so if the setup - # script is newer than the manifest, we'll regenerate the manifest - # from the template. (Well, not quite: if we already have a - # manifest, but there's no template -- which will happen if the - # developer elects to generate a manifest some other way -- then we - # can't regenerate the manifest, so we don't.) - self.debug_print("checking if %s newer than %s" % - (self.distribution.script_name, self.manifest)) - setup_newer = dep_util.newer(self.distribution.script_name, - self.manifest) - - # cases: - # 1) no manifest, template exists: generate manifest - # (covered by 2a: no manifest == template newer) - # 2) manifest & template exist: - # 2a) template or setup script newer than manifest: - # regenerate manifest - # 2b) manifest newer than both: - # do nothing (unless --force or --manifest-only) - # 3) manifest exists, no template: - # do nothing (unless --force or --manifest-only) - # 4) no manifest, no template: generate w/ warning ("defaults only") - - manifest_outofdate = (template_exists and - (template_newer or setup_newer)) - force_regen = self.force_manifest or self.manifest_only - manifest_exists = os.path.isfile(self.manifest) - neither_exists = (not template_exists and not manifest_exists) - - # Regenerate the manifest if necessary (or if explicitly told to) - if manifest_outofdate or neither_exists or force_regen: - if not template_exists: - self.warn(("manifest template '%s' does not exist " + - "(using default file list)") % - self.template) - self.filelist.findall() - - if self.use_defaults: - self.add_defaults() - if template_exists: - self.read_template() - if self.prune: - self.prune_file_list() - - self.filelist.sort() - self.filelist.remove_duplicates() - self.write_manifest() + if self.prune: + self.prune_file_list() - # Don't regenerate the manifest, just read it in. - else: - self.read_manifest() + self.filelist.sort() + self.filelist.remove_duplicates() + self.write_manifest() # get_file_list () Modified: python/branches/release26-maint/Lib/distutils/tests/test_sdist.py ============================================================================== --- python/branches/release26-maint/Lib/distutils/tests/test_sdist.py (original) +++ python/branches/release26-maint/Lib/distutils/tests/test_sdist.py Mon May 17 12:26:15 2010 @@ -29,6 +29,7 @@ super(sdistTestCase, self).setUp() self.old_path = os.getcwd() self.temp_pkg = os.path.join(self.mkdtemp(), 'temppkg') + self.tmp_dir = self.mkdtemp() def tearDown(self): os.chdir(self.old_path) @@ -151,6 +152,67 @@ self.assertEquals(result, ['fake-1.0.tar', 'fake-1.0.tar.gz']) + def get_cmd(self, metadata=None): + """Returns a cmd""" + if metadata is None: + metadata = {'name': 'fake', 'version': '1.0', + 'url': 'xxx', 'author': 'xxx', + 'author_email': 'xxx'} + dist = Distribution(metadata) + dist.script_name = 'setup.py' + dist.packages = ['somecode'] + dist.include_package_data = True + cmd = sdist(dist) + cmd.dist_dir = 'dist' + def _warn(*args): + pass + cmd.warn = _warn + return dist, cmd + + def test_get_file_list(self): + # make sure MANIFEST is recalculated + dist, cmd = self.get_cmd() + + os.chdir(self.tmp_dir) + + # filling data_files by pointing files in package_data + os.mkdir(os.path.join(self.tmp_dir, 'somecode')) + self.write_file((self.tmp_dir, 'somecode', '__init__.py'), '#') + self.write_file((self.tmp_dir, 'somecode', 'one.py'), '#') + cmd.ensure_finalized() + cmd.run() + + f = open(cmd.manifest) + try: + manifest = [line.strip() for line in f.read().split('\n') + if line.strip() != ''] + finally: + f.close() + + self.assertEquals(len(manifest), 2) + + # adding a file + self.write_file((self.tmp_dir, 'somecode', 'two.py'), '#') + + # make sure build_py is reinitinialized, like a fresh run + build_py = dist.get_command_obj('build_py') + build_py.finalized = False + build_py.ensure_finalized() + + cmd.run() + + f = open(cmd.manifest) + try: + manifest2 = [line.strip() for line in f.read().split('\n') + if line.strip() != ''] + finally: + f.close() + + # do we have the new file in MANIFEST ? + self.assertEquals(len(manifest2), 3) + self.assert_('two.py' in manifest2[-1]) + + def test_suite(): return unittest.makeSuite(sdistTestCase) Modified: python/branches/release26-maint/Misc/NEWS ============================================================================== --- python/branches/release26-maint/Misc/NEWS (original) +++ python/branches/release26-maint/Misc/NEWS Mon May 17 12:26:15 2010 @@ -39,6 +39,8 @@ Library ------- +- Issue #8688: Distutils now recalculates MANIFEST everytime. + - Issue #7640: In the new `io` module, fix relative seek() for buffered readable streams when the internal buffer isn't empty. Patch by Pascal Chambon. From python-checkins at python.org Mon May 17 12:30:00 2010 From: python-checkins at python.org (antoine.pitrou) Date: Mon, 17 May 2010 12:30:00 +0200 (CEST) Subject: [Python-checkins] r81257 - python/branches/py3k/Lib/test/test_ssl.py Message-ID: <20100517103000.55141EEA13@mail.python.org> Author: antoine.pitrou Date: Mon May 17 12:30:00 2010 New Revision: 81257 Log: Try to fix buildbot failures with old OpenSSLs. Modified: python/branches/py3k/Lib/test/test_ssl.py Modified: python/branches/py3k/Lib/test/test_ssl.py ============================================================================== --- python/branches/py3k/Lib/test/test_ssl.py (original) +++ python/branches/py3k/Lib/test/test_ssl.py Mon May 17 12:30:00 2010 @@ -217,6 +217,7 @@ with self.assertRaisesRegexp(ssl.SSLError, "PEM lib"): ctx.load_cert_chain(EMPTYCERT) # Separate key and cert + ctx = ssl.SSLContext(ssl.PROTOCOL_TLSv1) ctx.load_cert_chain(ONLYCERT, ONLYKEY) ctx.load_cert_chain(certfile=ONLYCERT, keyfile=ONLYKEY) ctx.load_cert_chain(certfile=BYTES_ONLYCERT, keyfile=BYTES_ONLYKEY) @@ -227,6 +228,7 @@ with self.assertRaisesRegexp(ssl.SSLError, "PEM lib"): ctx.load_cert_chain(certfile=ONLYKEY, keyfile=ONLYCERT) # Mismatching key and cert + ctx = ssl.SSLContext(ssl.PROTOCOL_TLSv1) with self.assertRaisesRegexp(ssl.SSLError, "key values mismatch"): ctx.load_cert_chain(CERTFILE, ONLYKEY) From python-checkins at python.org Mon May 17 12:38:53 2010 From: python-checkins at python.org (tarek.ziade) Date: Mon, 17 May 2010 12:38:53 +0200 (CEST) Subject: [Python-checkins] r81258 - in python/branches/py3k: Lib/distutils/command/sdist.py Lib/distutils/tests/test_sdist.py Misc/NEWS Message-ID: <20100517103853.E1080EE981@mail.python.org> Author: tarek.ziade Date: Mon May 17 12:38:53 2010 New Revision: 81258 Log: Merged revisions 81255 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r81255 | tarek.ziade | 2010-05-17 12:06:20 +0200 (Mon, 17 May 2010) | 1 line Fixed #8688: Distutils now recalculates MANIFEST everytime. ........ Modified: python/branches/py3k/ (props changed) python/branches/py3k/Lib/distutils/command/sdist.py python/branches/py3k/Lib/distutils/tests/test_sdist.py python/branches/py3k/Misc/NEWS Modified: python/branches/py3k/Lib/distutils/command/sdist.py ============================================================================== --- python/branches/py3k/Lib/distutils/command/sdist.py (original) +++ python/branches/py3k/Lib/distutils/command/sdist.py Mon May 17 12:38:53 2010 @@ -179,66 +179,34 @@ distribution, and put it in 'self.filelist'. This might involve reading the manifest template (and writing the manifest), or just reading the manifest, or just using the default file set -- it all - depends on the user's options and the state of the filesystem. + depends on the user's options. """ - # If we have a manifest template, see if it's newer than the - # manifest; if so, we'll regenerate the manifest. + # new behavior: + # the file list is recalculated everytime because + # even if MANIFEST.in or setup.py are not changed + # the user might have added some files in the tree that + # need to be included. + # + # This makes --force the default and only behavior. template_exists = os.path.isfile(self.template) + if not template_exists: + self.warn(("manifest template '%s' does not exist " + + "(using default file list)") % + self.template) + self.filelist.findall() + + if self.use_defaults: + self.add_defaults() + if template_exists: - template_newer = dep_util.newer(self.template, self.manifest) + self.read_template() - # The contents of the manifest file almost certainly depend on the - # setup script as well as the manifest template -- so if the setup - # script is newer than the manifest, we'll regenerate the manifest - # from the template. (Well, not quite: if we already have a - # manifest, but there's no template -- which will happen if the - # developer elects to generate a manifest some other way -- then we - # can't regenerate the manifest, so we don't.) - self.debug_print("checking if %s newer than %s" % - (self.distribution.script_name, self.manifest)) - setup_newer = dep_util.newer(self.distribution.script_name, - self.manifest) - - # cases: - # 1) no manifest, template exists: generate manifest - # (covered by 2a: no manifest == template newer) - # 2) manifest & template exist: - # 2a) template or setup script newer than manifest: - # regenerate manifest - # 2b) manifest newer than both: - # do nothing (unless --force or --manifest-only) - # 3) manifest exists, no template: - # do nothing (unless --force or --manifest-only) - # 4) no manifest, no template: generate w/ warning ("defaults only") - - manifest_outofdate = (template_exists and - (template_newer or setup_newer)) - force_regen = self.force_manifest or self.manifest_only - manifest_exists = os.path.isfile(self.manifest) - neither_exists = (not template_exists and not manifest_exists) - - # Regenerate the manifest if necessary (or if explicitly told to) - if manifest_outofdate or neither_exists or force_regen: - if not template_exists: - self.warn("manifest template '%s' does not exist " - "(using default file list)" - % self.template) - self.filelist.findall() - - if self.use_defaults: - self.add_defaults() - if template_exists: - self.read_template() - if self.prune: - self.prune_file_list() - - self.filelist.sort() - self.filelist.remove_duplicates() - self.write_manifest() + if self.prune: + self.prune_file_list() - # Don't regenerate the manifest, just read it in. - else: - self.read_manifest() + self.filelist.sort() + self.filelist.remove_duplicates() + self.write_manifest() def add_defaults(self): """Add all the default files to self.filelist: Modified: python/branches/py3k/Lib/distutils/tests/test_sdist.py ============================================================================== --- python/branches/py3k/Lib/distutils/tests/test_sdist.py (original) +++ python/branches/py3k/Lib/distutils/tests/test_sdist.py Mon May 17 12:38:53 2010 @@ -346,6 +346,47 @@ finally: archive.close() + def test_get_file_list(self): + # make sure MANIFEST is recalculated + dist, cmd = self.get_cmd() + + # filling data_files by pointing files in package_data + dist.package_data = {'somecode': ['*.txt']} + self.write_file((self.tmp_dir, 'somecode', 'doc.txt'), '#') + cmd.ensure_finalized() + cmd.run() + + f = open(cmd.manifest) + try: + manifest = [line.strip() for line in f.read().split('\n') + if line.strip() != ''] + finally: + f.close() + + self.assertEquals(len(manifest), 4) + + # adding a file + self.write_file((self.tmp_dir, 'somecode', 'doc2.txt'), '#') + + # make sure build_py is reinitinialized, like a fresh run + build_py = dist.get_command_obj('build_py') + build_py.finalized = False + build_py.ensure_finalized() + + cmd.run() + + f = open(cmd.manifest) + try: + manifest2 = [line.strip() for line in f.read().split('\n') + if line.strip() != ''] + finally: + f.close() + + # do we have the new file in MANIFEST ? + self.assertEquals(len(manifest2), 5) + self.assertIn('doc2.txt', manifest2[-1]) + + def test_suite(): return unittest.makeSuite(SDistTestCase) Modified: python/branches/py3k/Misc/NEWS ============================================================================== --- python/branches/py3k/Misc/NEWS (original) +++ python/branches/py3k/Misc/NEWS Mon May 17 12:38:53 2010 @@ -366,6 +366,8 @@ Library ------- +- Issue #8688: Distutils now recalculates MANIFEST everytime. + - Issue #8477: ssl.RAND_egd() and ssl._test_decode_cert() support str with surrogates and bytes for the filename From python-checkins at python.org Mon May 17 12:39:07 2010 From: python-checkins at python.org (florent.xicluna) Date: Mon, 17 May 2010 12:39:07 +0200 (CEST) Subject: [Python-checkins] r81259 - python/trunk/Lib/urllib.py Message-ID: <20100517103907.C6296EE9E6@mail.python.org> Author: florent.xicluna Date: Mon May 17 12:39:07 2010 New Revision: 81259 Log: Slight style cleanup. Modified: python/trunk/Lib/urllib.py Modified: python/trunk/Lib/urllib.py ============================================================================== --- python/trunk/Lib/urllib.py (original) +++ python/trunk/Lib/urllib.py Mon May 17 12:39:07 2010 @@ -765,7 +765,7 @@ else: return self.open(newurl, data) - def get_user_passwd(self, host, realm, clear_cache = 0): + def get_user_passwd(self, host, realm, clear_cache=0): key = realm + '@' + host.lower() if key in self.auth_cache: if clear_cache: @@ -1157,7 +1157,8 @@ return attr, None _hexdig = '0123456789ABCDEFabcdef' -_hextochr = dict((a+b, chr(int(a+b,16))) for a in _hexdig for b in _hexdig) +_hextochr = dict((a + b, chr(int(a + b, 16))) + for a in _hexdig for b in _hexdig) def unquote(s): """unquote('abc%20def') -> 'abc def'.""" @@ -1182,7 +1183,7 @@ '0123456789' '_.-') _safemaps = {} -def quote(s, safe = '/'): +def quote(s, safe='/'): """quote('abc def') -> 'abc%20def' Each part of a URL, e.g. the path info, the query, etc., has a @@ -1216,14 +1217,14 @@ res = map(safe_map.__getitem__, s) return ''.join(res) -def quote_plus(s, safe = ''): +def quote_plus(s, safe=''): """Quote the query fragment of a URL; replacing ' ' with '+'""" if ' ' in s: s = quote(s, safe + ' ') return s.replace(' ', '+') return quote(s, safe) -def urlencode(query,doseq=0): +def urlencode(query, doseq=0): """Encode a sequence of two-element tuples or dictionary into a URL query string. If any values in the query arg are sequences and doseq is true, each @@ -1380,7 +1381,6 @@ return False - def getproxies_macosx_sysconf(): """Return a dictionary of scheme -> proxy server URL mappings. @@ -1389,8 +1389,6 @@ """ return _get_proxies() - - def proxy_bypass(host): if getproxies_environment(): return proxy_bypass_environment(host) From python-checkins at python.org Mon May 17 12:48:29 2010 From: python-checkins at python.org (tarek.ziade) Date: Mon, 17 May 2010 12:48:29 +0200 (CEST) Subject: [Python-checkins] r81260 - in python/branches/release31-maint: Lib/distutils/command/sdist.py Lib/distutils/tests/test_sdist.py Misc/NEWS Message-ID: <20100517104829.9AC57EEA1D@mail.python.org> Author: tarek.ziade Date: Mon May 17 12:48:29 2010 New Revision: 81260 Log: Merged revisions 81258 via svnmerge from svn+ssh://pythondev at svn.python.org/python/branches/py3k ................ r81258 | tarek.ziade | 2010-05-17 12:38:53 +0200 (Mon, 17 May 2010) | 9 lines Merged revisions 81255 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r81255 | tarek.ziade | 2010-05-17 12:06:20 +0200 (Mon, 17 May 2010) | 1 line Fixed #8688: Distutils now recalculates MANIFEST everytime. ........ ................ Modified: python/branches/release31-maint/ (props changed) python/branches/release31-maint/Lib/distutils/command/sdist.py python/branches/release31-maint/Lib/distutils/tests/test_sdist.py python/branches/release31-maint/Misc/NEWS Modified: python/branches/release31-maint/Lib/distutils/command/sdist.py ============================================================================== --- python/branches/release31-maint/Lib/distutils/command/sdist.py (original) +++ python/branches/release31-maint/Lib/distutils/command/sdist.py Mon May 17 12:48:29 2010 @@ -173,66 +173,34 @@ distribution, and put it in 'self.filelist'. This might involve reading the manifest template (and writing the manifest), or just reading the manifest, or just using the default file set -- it all - depends on the user's options and the state of the filesystem. + depends on the user's options. """ - # If we have a manifest template, see if it's newer than the - # manifest; if so, we'll regenerate the manifest. + # new behavior: + # the file list is recalculated everytime because + # even if MANIFEST.in or setup.py are not changed + # the user might have added some files in the tree that + # need to be included. + # + # This makes --force the default and only behavior. template_exists = os.path.isfile(self.template) + if not template_exists: + self.warn(("manifest template '%s' does not exist " + + "(using default file list)") % + self.template) + self.filelist.findall() + + if self.use_defaults: + self.add_defaults() + if template_exists: - template_newer = dep_util.newer(self.template, self.manifest) + self.read_template() - # The contents of the manifest file almost certainly depend on the - # setup script as well as the manifest template -- so if the setup - # script is newer than the manifest, we'll regenerate the manifest - # from the template. (Well, not quite: if we already have a - # manifest, but there's no template -- which will happen if the - # developer elects to generate a manifest some other way -- then we - # can't regenerate the manifest, so we don't.) - self.debug_print("checking if %s newer than %s" % - (self.distribution.script_name, self.manifest)) - setup_newer = dep_util.newer(self.distribution.script_name, - self.manifest) - - # cases: - # 1) no manifest, template exists: generate manifest - # (covered by 2a: no manifest == template newer) - # 2) manifest & template exist: - # 2a) template or setup script newer than manifest: - # regenerate manifest - # 2b) manifest newer than both: - # do nothing (unless --force or --manifest-only) - # 3) manifest exists, no template: - # do nothing (unless --force or --manifest-only) - # 4) no manifest, no template: generate w/ warning ("defaults only") - - manifest_outofdate = (template_exists and - (template_newer or setup_newer)) - force_regen = self.force_manifest or self.manifest_only - manifest_exists = os.path.isfile(self.manifest) - neither_exists = (not template_exists and not manifest_exists) - - # Regenerate the manifest if necessary (or if explicitly told to) - if manifest_outofdate or neither_exists or force_regen: - if not template_exists: - self.warn("manifest template '%s' does not exist " - "(using default file list)" - % self.template) - self.filelist.findall() - - if self.use_defaults: - self.add_defaults() - if template_exists: - self.read_template() - if self.prune: - self.prune_file_list() - - self.filelist.sort() - self.filelist.remove_duplicates() - self.write_manifest() + if self.prune: + self.prune_file_list() - # Don't regenerate the manifest, just read it in. - else: - self.read_manifest() + self.filelist.sort() + self.filelist.remove_duplicates() + self.write_manifest() def add_defaults(self): """Add all the default files to self.filelist: Modified: python/branches/release31-maint/Lib/distutils/tests/test_sdist.py ============================================================================== --- python/branches/release31-maint/Lib/distutils/tests/test_sdist.py (original) +++ python/branches/release31-maint/Lib/distutils/tests/test_sdist.py Mon May 17 12:48:29 2010 @@ -277,6 +277,47 @@ self.assertRaises(DistutilsOptionError, cmd.finalize_options) + def test_get_file_list(self): + # make sure MANIFEST is recalculated + dist, cmd = self.get_cmd() + + # filling data_files by pointing files in package_data + dist.package_data = {'somecode': ['*.txt']} + self.write_file((self.tmp_dir, 'somecode', 'doc.txt'), '#') + cmd.ensure_finalized() + cmd.run() + + f = open(cmd.manifest) + try: + manifest = [line.strip() for line in f.read().split('\n') + if line.strip() != ''] + finally: + f.close() + + self.assertEquals(len(manifest), 4) + + # adding a file + self.write_file((self.tmp_dir, 'somecode', 'doc2.txt'), '#') + + # make sure build_py is reinitinialized, like a fresh run + build_py = dist.get_command_obj('build_py') + build_py.finalized = False + build_py.ensure_finalized() + + cmd.run() + + f = open(cmd.manifest) + try: + manifest2 = [line.strip() for line in f.read().split('\n') + if line.strip() != ''] + finally: + f.close() + + # do we have the new file in MANIFEST ? + self.assertEquals(len(manifest2), 5) + self.assertIn('doc2.txt', manifest2[-1]) + + def test_suite(): return unittest.makeSuite(SDistTestCase) Modified: python/branches/release31-maint/Misc/NEWS ============================================================================== --- python/branches/release31-maint/Misc/NEWS (original) +++ python/branches/release31-maint/Misc/NEWS Mon May 17 12:48:29 2010 @@ -43,6 +43,8 @@ Library ------- +- Issue #8688: Distutils now recalculates MANIFEST everytime. + - Issue #5099: subprocess.Popen.__del__ no longer references global objects to prevent issues during interpreter shutdown. From python-checkins at python.org Mon May 17 12:54:43 2010 From: python-checkins at python.org (tarek.ziade) Date: Mon, 17 May 2010 12:54:43 +0200 (CEST) Subject: [Python-checkins] r81261 - in python/trunk: Doc/distutils/sourcedist.rst Lib/distutils/command/sdist.py Message-ID: <20100517105443.6F36BEE984@mail.python.org> Author: tarek.ziade Date: Mon May 17 12:54:43 2010 New Revision: 81261 Log: upgraded distutils docs w.r.t. the manifest regeneration Modified: python/trunk/Doc/distutils/sourcedist.rst python/trunk/Lib/distutils/command/sdist.py Modified: python/trunk/Doc/distutils/sourcedist.rst ============================================================================== --- python/trunk/Doc/distutils/sourcedist.rst (original) +++ python/trunk/Doc/distutils/sourcedist.rst Mon May 17 12:54:43 2010 @@ -137,20 +137,12 @@ :option:`--no-defaults` and :option:`--no-prune` to disable the standard "include" and "exclude" sets. -Second, you might want to force the manifest to be regenerated---for example, if -you have added or removed files or directories that match an existing pattern in -the manifest template, you should regenerate the manifest:: - - python setup.py sdist --force-manifest - -Or, you might just want to (re)generate the manifest, but not create a source -distribution:: +Second, you might just want to (re)generate the manifest, but not create a +source distribution:: python setup.py sdist --manifest-only -:option:`--manifest-only` implies :option:`--force-manifest`. :option:`-o` is a -shortcut for :option:`--manifest-only`, and :option:`-f` for -:option:`--force-manifest`. +:option:`-o` is a sortcut for :option:`--manifest-only`. .. _manifest_template: Modified: python/trunk/Lib/distutils/command/sdist.py ============================================================================== --- python/trunk/Lib/distutils/command/sdist.py (original) +++ python/trunk/Lib/distutils/command/sdist.py Mon May 17 12:54:43 2010 @@ -63,7 +63,8 @@ "just regenerate the manifest and then stop " "(implies --force-manifest)"), ('force-manifest', 'f', - "forcibly regenerate the manifest and carry on as usual"), + "forcibly regenerate the manifest and carry on as usual. " + "Deprecated: now the manifest is always regenerated."), ('formats=', None, "formats for source distribution (comma-separated list)"), ('keep-temp', 'k', From python-checkins at python.org Mon May 17 13:00:17 2010 From: python-checkins at python.org (tarek.ziade) Date: Mon, 17 May 2010 13:00:17 +0200 (CEST) Subject: [Python-checkins] r81262 - in python/branches/release26-maint: Doc/distutils/sourcedist.rst Lib/distutils/command/sdist.py Message-ID: <20100517110017.3F119EF02@mail.python.org> Author: tarek.ziade Date: Mon May 17 13:00:17 2010 New Revision: 81262 Log: Merged revisions 81261 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r81261 | tarek.ziade | 2010-05-17 12:54:43 +0200 (Mon, 17 May 2010) | 1 line upgraded distutils docs w.r.t. the manifest regeneration ........ Modified: python/branches/release26-maint/ (props changed) python/branches/release26-maint/Doc/distutils/sourcedist.rst python/branches/release26-maint/Lib/distutils/command/sdist.py Modified: python/branches/release26-maint/Doc/distutils/sourcedist.rst ============================================================================== --- python/branches/release26-maint/Doc/distutils/sourcedist.rst (original) +++ python/branches/release26-maint/Doc/distutils/sourcedist.rst Mon May 17 13:00:17 2010 @@ -191,19 +191,11 @@ :option:`--no-defaults` and :option:`--no-prune` to disable the standard "include" and "exclude" sets. -Second, you might want to force the manifest to be regenerated---for example, if -you have added or removed files or directories that match an existing pattern in -the manifest template, you should regenerate the manifest:: - - python setup.py sdist --force-manifest - -Or, you might just want to (re)generate the manifest, but not create a source +Second, you might just want to (re)generate the manifest, but not create a source distribution:: python setup.py sdist --manifest-only -:option:`--manifest-only` implies :option:`--force-manifest`. :option:`-o` is a -shortcut for :option:`--manifest-only`, and :option:`-f` for -:option:`--force-manifest`. +:option:`-o` is a shortcut for :option:`--manifest-only`. Modified: python/branches/release26-maint/Lib/distutils/command/sdist.py ============================================================================== --- python/branches/release26-maint/Lib/distutils/command/sdist.py (original) +++ python/branches/release26-maint/Lib/distutils/command/sdist.py Mon May 17 13:00:17 2010 @@ -57,7 +57,8 @@ "just regenerate the manifest and then stop " "(implies --force-manifest)"), ('force-manifest', 'f', - "forcibly regenerate the manifest and carry on as usual"), + "forcibly regenerate the manifest and carry on as usual. " + "Deprecated: now the manifest is always regenerated."), ('formats=', None, "formats for source distribution (comma-separated list)"), ('keep-temp', 'k', From python-checkins at python.org Mon May 17 13:01:57 2010 From: python-checkins at python.org (tarek.ziade) Date: Mon, 17 May 2010 13:01:57 +0200 (CEST) Subject: [Python-checkins] r81263 - in python/branches/py3k: Doc/distutils/sourcedist.rst Lib/distutils/command/sdist.py Message-ID: <20100517110157.88568EF02@mail.python.org> Author: tarek.ziade Date: Mon May 17 13:01:57 2010 New Revision: 81263 Log: Merged revisions 81261 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r81261 | tarek.ziade | 2010-05-17 12:54:43 +0200 (Mon, 17 May 2010) | 1 line upgraded distutils docs w.r.t. the manifest regeneration ........ Modified: python/branches/py3k/ (props changed) python/branches/py3k/Doc/distutils/sourcedist.rst python/branches/py3k/Lib/distutils/command/sdist.py Modified: python/branches/py3k/Doc/distutils/sourcedist.rst ============================================================================== --- python/branches/py3k/Doc/distutils/sourcedist.rst (original) +++ python/branches/py3k/Doc/distutils/sourcedist.rst Mon May 17 13:01:57 2010 @@ -137,20 +137,12 @@ :option:`--no-defaults` and :option:`--no-prune` to disable the standard "include" and "exclude" sets. -Second, you might want to force the manifest to be regenerated---for example, if -you have added or removed files or directories that match an existing pattern in -the manifest template, you should regenerate the manifest:: - - python setup.py sdist --force-manifest - -Or, you might just want to (re)generate the manifest, but not create a source -distribution:: +Second, you might just want to (re)generate the manifest, but not create a +source distribution:: python setup.py sdist --manifest-only -:option:`--manifest-only` implies :option:`--force-manifest`. :option:`-o` is a -shortcut for :option:`--manifest-only`, and :option:`-f` for -:option:`--force-manifest`. +:option:`-o` is a sortcut for :option:`--manifest-only`. .. _manifest_template: Modified: python/branches/py3k/Lib/distutils/command/sdist.py ============================================================================== --- python/branches/py3k/Lib/distutils/command/sdist.py (original) +++ python/branches/py3k/Lib/distutils/command/sdist.py Mon May 17 13:01:57 2010 @@ -63,7 +63,8 @@ "just regenerate the manifest and then stop " "(implies --force-manifest)"), ('force-manifest', 'f', - "forcibly regenerate the manifest and carry on as usual"), + "forcibly regenerate the manifest and carry on as usual. " + "Deprecated: now the manifest is always regenerated."), ('formats=', None, "formats for source distribution (comma-separated list)"), ('keep-temp', 'k', From python-checkins at python.org Mon May 17 13:04:41 2010 From: python-checkins at python.org (tarek.ziade) Date: Mon, 17 May 2010 13:04:41 +0200 (CEST) Subject: [Python-checkins] r81264 - in python/branches/release31-maint: Doc/distutils/sourcedist.rst Lib/distutils/command/sdist.py Message-ID: <20100517110441.ED5CBEE984@mail.python.org> Author: tarek.ziade Date: Mon May 17 13:04:41 2010 New Revision: 81264 Log: Merged revisions 81263 via svnmerge from svn+ssh://pythondev at svn.python.org/python/branches/py3k ................ r81263 | tarek.ziade | 2010-05-17 13:01:57 +0200 (Mon, 17 May 2010) | 9 lines Merged revisions 81261 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r81261 | tarek.ziade | 2010-05-17 12:54:43 +0200 (Mon, 17 May 2010) | 1 line upgraded distutils docs w.r.t. the manifest regeneration ........ ................ Modified: python/branches/release31-maint/ (props changed) python/branches/release31-maint/Doc/distutils/sourcedist.rst python/branches/release31-maint/Lib/distutils/command/sdist.py Modified: python/branches/release31-maint/Doc/distutils/sourcedist.rst ============================================================================== --- python/branches/release31-maint/Doc/distutils/sourcedist.rst (original) +++ python/branches/release31-maint/Doc/distutils/sourcedist.rst Mon May 17 13:04:41 2010 @@ -198,19 +198,11 @@ :option:`--no-defaults` and :option:`--no-prune` to disable the standard "include" and "exclude" sets. -Second, you might want to force the manifest to be regenerated---for example, if -you have added or removed files or directories that match an existing pattern in -the manifest template, you should regenerate the manifest:: - - python setup.py sdist --force-manifest - -Or, you might just want to (re)generate the manifest, but not create a source +Second, you might just want to (re)generate the manifest, but not create a source distribution:: python setup.py sdist --manifest-only -:option:`--manifest-only` implies :option:`--force-manifest`. :option:`-o` is a -shortcut for :option:`--manifest-only`, and :option:`-f` for -:option:`--force-manifest`. +:option:`-o` is a shortcut for :option:`--manifest-only`. Modified: python/branches/release31-maint/Lib/distutils/command/sdist.py ============================================================================== --- python/branches/release31-maint/Lib/distutils/command/sdist.py (original) +++ python/branches/release31-maint/Lib/distutils/command/sdist.py Mon May 17 13:04:41 2010 @@ -63,7 +63,8 @@ "just regenerate the manifest and then stop " "(implies --force-manifest)"), ('force-manifest', 'f', - "forcibly regenerate the manifest and carry on as usual"), + "forcibly regenerate the manifest and carry on as usual. " + "Deprecated: now the manifest is always regenerated."), ('formats=', None, "formats for source distribution (comma-separated list)"), ('keep-temp', 'k', From python-checkins at python.org Mon May 17 13:08:43 2010 From: python-checkins at python.org (tarek.ziade) Date: Mon, 17 May 2010 13:08:43 +0200 Subject: [Python-checkins] distutils2: removed --force-manifest in sdist command Message-ID: tarek.ziade pushed 541f90ef0636 to distutils2: http://hg.python.org/distutils2/rev/541f90ef0636 changeset: 153:541f90ef0636 tag: tip user: Tarek Ziade date: Mon May 17 13:08:36 2010 +0200 summary: removed --force-manifest in sdist command files: src/distutils2/command/sdist.py diff --git a/src/distutils2/command/sdist.py b/src/distutils2/command/sdist.py --- a/src/distutils2/command/sdist.py +++ b/src/distutils2/command/sdist.py @@ -68,10 +68,7 @@ ('no-prune', None, "don't automatically exclude anything"), ('manifest-only', 'o', - "just regenerate the manifest and then stop " - "(implies --force-manifest)"), - ('force-manifest', 'f', - "forcibly regenerate the manifest and carry on as usual"), + "just regenerate the manifest and then stop "), ('formats=', None, "formats for source distribution (comma-separated list)"), ('keep-temp', 'k', @@ -90,8 +87,7 @@ ] boolean_options = ['use-defaults', 'prune', - 'manifest-only', 'force-manifest', - 'keep-temp', 'metadata-check'] + 'manifest-only', 'keep-temp', 'metadata-check'] help_options = [ ('help-formats', None, @@ -116,10 +112,7 @@ # in the manifest self.use_defaults = 1 self.prune = 1 - self.manifest_only = 0 - self.force_manifest = 0 - self.formats = None self.keep_temp = 0 self.dist_dir = None @@ -194,63 +187,24 @@ distribution, and put it in 'self.filelist'. This might involve reading the manifest template (and writing the manifest), or just reading the manifest, or just using the default file set -- it all - depends on the user's options and the state of the filesystem. + depends on the user's options. """ - # If we have a manifest template, see if it's newer than the - # manifest; if so, we'll regenerate the manifest. template_exists = os.path.isfile(self.template) + if not template_exists: + self.warn(("manifest template '%s' does not exist " + + "(using default file list)") % + self.template) + + self.filelist.findall() + + if self.use_defaults: + self.add_defaults() if template_exists: - template_newer = newer(self.template, self.manifest) + self.read_template() + if self.prune: + self.prune_file_list() - # The contents of the manifest file almost certainly depend on the - # setup script as well as the manifest template -- so if the setup - # script is newer than the manifest, we'll regenerate the manifest - # from the template. (Well, not quite: if we already have a - # manifest, but there's no template -- which will happen if the - # developer elects to generate a manifest some other way -- then we - # can't regenerate the manifest, so we don't.) - setup_newer = newer(self.distribution.script_name, - self.manifest) - - # cases: - # 1) no manifest, template exists: generate manifest - # (covered by 2a: no manifest == template newer) - # 2) manifest & template exist: - # 2a) template or setup script newer than manifest: - # regenerate manifest - # 2b) manifest newer than both: - # do nothing (unless --force or --manifest-only) - # 3) manifest exists, no template: - # do nothing (unless --force or --manifest-only) - # 4) no manifest, no template: generate w/ warning ("defaults only") - - - manifest_outofdate = (template_exists and - (template_newer or setup_newer)) - force_regen = self.force_manifest or self.manifest_only - manifest_exists = os.path.isfile(self.manifest) - neither_exists = (not template_exists and not manifest_exists) - - # Regenerate the manifest if necessary (or if explicitly told to) - if manifest_outofdate or neither_exists or force_regen: - if not template_exists: - self.warn(("manifest template '%s' does not exist " + - "(using default file list)") % - self.template) - self.filelist.findall() - - if self.use_defaults: - self.add_defaults() - if template_exists: - self.read_template() - if self.prune: - self.prune_file_list() - - self.filelist.write(self.manifest) - - # Don't regenerate the manifest, just read it in. - else: - self.filelist.read(self.manifest) + self.filelist.write(self.manifest) def add_defaults(self): """Add all the default files to self.filelist: -- Repository URL: http://hg.python.org/distutils2 From nnorwitz at gmail.com Mon May 17 14:25:21 2010 From: nnorwitz at gmail.com (Neal Norwitz) Date: Mon, 17 May 2010 08:25:21 -0400 Subject: [Python-checkins] Python Regression Test Failures refleak (1) Message-ID: <20100517122521.GA19377@kbk-i386-bb.psfb.org> More important issues: ---------------------- test_bz2 leaked [0, 0, 69] references, sum=69 Less important issues: ---------------------- test_threadsignals leaked [0, 0, -8] references, sum=-8 From python-checkins at python.org Mon May 17 15:35:09 2010 From: python-checkins at python.org (florent.xicluna) Date: Mon, 17 May 2010 15:35:09 +0200 (CEST) Subject: [Python-checkins] r81265 - in python/trunk: Lib/urllib.py Misc/NEWS Message-ID: <20100517133509.3B65FEE9FD@mail.python.org> Author: florent.xicluna Date: Mon May 17 15:35:09 2010 New Revision: 81265 Log: Issue #1285086: Speed up urllib.quote and urllib.unquote for simple cases. Modified: python/trunk/Lib/urllib.py python/trunk/Misc/NEWS Modified: python/trunk/Lib/urllib.py ============================================================================== --- python/trunk/Lib/urllib.py (original) +++ python/trunk/Lib/urllib.py Mon May 17 15:35:09 2010 @@ -92,7 +92,7 @@ def urlcleanup(): if _urlopener: _urlopener.cleanup() - _safemaps.clear() + _safe_quoters.clear() ftpcache.clear() # check for SSL @@ -1163,15 +1163,18 @@ def unquote(s): """unquote('abc%20def') -> 'abc def'.""" res = s.split('%') - for i in xrange(1, len(res)): - item = res[i] + # fastpath + if len(res) == 1: + return s + s = res[0] + for item in res[1:]: try: - res[i] = _hextochr[item[:2]] + item[2:] + s += _hextochr[item[:2]] + item[2:] except KeyError: - res[i] = '%' + item + s += '%' + item except UnicodeDecodeError: - res[i] = unichr(int(item[:2], 16)) + item[2:] - return "".join(res) + s += unichr(int(item[:2], 16)) + item[2:] + return s def unquote_plus(s): """unquote('%7e/abc+def') -> '~/abc def'""" @@ -1181,7 +1184,10 @@ always_safe = ('ABCDEFGHIJKLMNOPQRSTUVWXYZ' 'abcdefghijklmnopqrstuvwxyz' '0123456789' '_.-') -_safemaps = {} +_safe_map = {} +for i, c in zip(xrange(256), str(bytearray(xrange(256)))): + _safe_map[c] = c if (i < 128 and c in always_safe) else '%{:02X}'.format(i) +_safe_quoters = {} def quote(s, safe='/'): """quote('abc def') -> 'abc%20def' @@ -1204,18 +1210,21 @@ called on a path where the existing slash characters are used as reserved characters. """ + # fastpath + if not s: + return s cachekey = (safe, always_safe) try: - safe_map = _safemaps[cachekey] + (quoter, safe) = _safe_quoters[cachekey] except KeyError: - safe += always_safe - safe_map = {} - for i in range(256): - c = chr(i) - safe_map[c] = (c in safe) and c or ('%%%02X' % i) - _safemaps[cachekey] = safe_map - res = map(safe_map.__getitem__, s) - return ''.join(res) + safe_map = _safe_map.copy() + safe_map.update([(c, c) for c in safe]) + quoter = safe_map.__getitem__ + safe = always_safe + safe + _safe_quoters[cachekey] = (quoter, safe) + if not s.rstrip(safe): + return s + return ''.join(map(quoter, s)) def quote_plus(s, safe=''): """Quote the query fragment of a URL; replacing ' ' with '+'""" Modified: python/trunk/Misc/NEWS ============================================================================== --- python/trunk/Misc/NEWS (original) +++ python/trunk/Misc/NEWS Mon May 17 15:35:09 2010 @@ -15,6 +15,8 @@ Library ------- +- Issue #1285086: Speed up urllib.quote and urllib.unquote for simple cases. + - Issue #8688: Distutils now recalculates MANIFEST everytime. - Issue #5099: subprocess.Popen's __del__ method (and the methods it calls) From python-checkins at python.org Mon May 17 16:13:10 2010 From: python-checkins at python.org (antoine.pitrou) Date: Mon, 17 May 2010 16:13:10 +0200 (CEST) Subject: [Python-checkins] r81266 - python/branches/py3k/Lib/test/test_ssl.py Message-ID: <20100517141310.D8027EE9DD@mail.python.org> Author: antoine.pitrou Date: Mon May 17 16:13:10 2010 New Revision: 81266 Log: Typo (thanks Arfrever) Modified: python/branches/py3k/Lib/test/test_ssl.py Modified: python/branches/py3k/Lib/test/test_ssl.py ============================================================================== --- python/branches/py3k/Lib/test/test_ssl.py (original) +++ python/branches/py3k/Lib/test/test_ssl.py Mon May 17 16:13:10 2010 @@ -306,7 +306,7 @@ # NOTE: the subject hashing algorithm has been changed between # OpenSSL 0.9.8n and 1.0.0, as a result the capath directory must # contain both versions of each certificate (same content, different - # filename) for this test to be portable accross OpenSSL releases. + # filename) for this test to be portable across OpenSSL releases. ctx = ssl.SSLContext(ssl.PROTOCOL_SSLv23) ctx.verify_mode = ssl.CERT_REQUIRED ctx.load_verify_locations(capath=CAPATH) From python-checkins at python.org Mon May 17 16:36:43 2010 From: python-checkins at python.org (victor.stinner) Date: Mon, 17 May 2010 16:36:43 +0200 (CEST) Subject: [Python-checkins] r81267 - python/branches/py3k/Lib/test/test_sys.py Message-ID: <20100517143643.565FFEE981@mail.python.org> Author: victor.stinner Date: Mon May 17 16:36:43 2010 New Revision: 81267 Log: Improve test_exit() error message to analyze sparc failures Modified: python/branches/py3k/Lib/test/test_sys.py Modified: python/branches/py3k/Lib/test/test_sys.py ============================================================================== --- python/branches/py3k/Lib/test/test_sys.py (original) +++ python/branches/py3k/Lib/test/test_sys.py Mon May 17 16:36:43 2010 @@ -151,7 +151,8 @@ stderr=subprocess.PIPE) stdout, stderr = process.communicate() self.assertEqual(process.returncode, 1) - self.assertTrue(stderr.startswith(expected), stderr) + self.assertTrue(stderr.startswith(expected), + "%r doesn't start with %r" % (stderr, expected)) # test that stderr buffer if flushed before the exit message is written # into stderr From python-checkins at python.org Mon May 17 16:37:57 2010 From: python-checkins at python.org (victor.stinner) Date: Mon, 17 May 2010 16:37:57 +0200 (CEST) Subject: [Python-checkins] r81268 - in python/branches/release31-maint: Lib/test/test_sys.py Message-ID: <20100517143757.AFBFAEEA0A@mail.python.org> Author: victor.stinner Date: Mon May 17 16:37:57 2010 New Revision: 81268 Log: Merged revisions 81267 via svnmerge from svn+ssh://pythondev at svn.python.org/python/branches/py3k ........ r81267 | victor.stinner | 2010-05-17 16:36:43 +0200 (lun., 17 mai 2010) | 2 lines Improve test_exit() error message to analyze sparc failures ........ Modified: python/branches/release31-maint/ (props changed) python/branches/release31-maint/Lib/test/test_sys.py Modified: python/branches/release31-maint/Lib/test/test_sys.py ============================================================================== --- python/branches/release31-maint/Lib/test/test_sys.py (original) +++ python/branches/release31-maint/Lib/test/test_sys.py Mon May 17 16:37:57 2010 @@ -144,7 +144,8 @@ stderr=subprocess.PIPE) stdout, stderr = process.communicate() self.assertEqual(process.returncode, 1) - self.assertTrue(stderr.startswith(expected), stderr) + self.assertTrue(stderr.startswith(expected), + "%r doesn't start with %r" % (stderr, expected)) # test that stderr buffer if flushed before the exit message is written # into stderr From python-checkins at python.org Mon May 17 18:59:23 2010 From: python-checkins at python.org (jeffrey.yasskin) Date: Mon, 17 May 2010 18:59:23 +0200 (CEST) Subject: [Python-checkins] r81269 - python/branches/py3k/Modules/_testcapimodule.c Message-ID: <20100517165923.81339EE9DD@mail.python.org> Author: jeffrey.yasskin Date: Mon May 17 18:59:23 2010 New Revision: 81269 Log: Fix test_capi in !pydebug mode, where my original attempt segfaulted without producing the expected error message. The test only tests what it's supposed to test in pydebug mode though. Fixes issue 8726. Modified: python/branches/py3k/Modules/_testcapimodule.c Modified: python/branches/py3k/Modules/_testcapimodule.c ============================================================================== --- python/branches/py3k/Modules/_testcapimodule.c (original) +++ python/branches/py3k/Modules/_testcapimodule.c Mon May 17 18:59:23 2010 @@ -2011,7 +2011,11 @@ crash_no_current_thread(PyObject *self) { Py_BEGIN_ALLOW_THREADS - PyErr_SetString(PyExc_SystemError, "bork bork bork"); + /* Using PyThreadState_Get() directly allows the test to pass in + !pydebug mode. However, the test only actually tests anything + in pydebug mode, since that's where the infinite loop was in + the first place. */ + PyThreadState_Get(); Py_END_ALLOW_THREADS return NULL; } From python-checkins at python.org Mon May 17 19:24:07 2010 From: python-checkins at python.org (florent.xicluna) Date: Mon, 17 May 2010 19:24:07 +0200 (CEST) Subject: [Python-checkins] r81270 - in python/branches/py3k: Lib/urllib/request.py Message-ID: <20100517172407.A4EA9EEA23@mail.python.org> Author: florent.xicluna Date: Mon May 17 19:24:07 2010 New Revision: 81270 Log: Merged revision 81259 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r81259 | florent.xicluna | 2010-05-17 12:39:07 +0200 (lun, 17 mai 2010) | 2 lines Slight style cleanup. ........ Modified: python/branches/py3k/ (props changed) python/branches/py3k/Lib/urllib/request.py Modified: python/branches/py3k/Lib/urllib/request.py ============================================================================== --- python/branches/py3k/Lib/urllib/request.py (original) +++ python/branches/py3k/Lib/urllib/request.py Mon May 17 19:24:07 2010 @@ -1965,7 +1965,7 @@ else: return self.open(newurl, data) - def get_user_passwd(self, host, realm, clear_cache = 0): + def get_user_passwd(self, host, realm, clear_cache=0): key = realm + '@' + host.lower() if key in self.auth_cache: if clear_cache: From python-checkins at python.org Mon May 17 19:33:07 2010 From: python-checkins at python.org (florent.xicluna) Date: Mon, 17 May 2010 19:33:07 +0200 (CEST) Subject: [Python-checkins] r81271 - in python/branches/py3k: Lib/urllib/parse.py Misc/NEWS Message-ID: <20100517173307.9D05CEE981@mail.python.org> Author: florent.xicluna Date: Mon May 17 19:33:07 2010 New Revision: 81271 Log: Issue #1285086: Speed up urllib.parse functions: quote, quote_from_bytes, unquote, unquote_to_bytes. Recorded merge of revisions 81265 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r81265 | florent.xicluna | 2010-05-17 15:35:09 +0200 (lun, 17 mai 2010) | 2 lines Issue #1285086: Speed up urllib.quote and urllib.unquote for simple cases. ........ Modified: python/branches/py3k/ (props changed) python/branches/py3k/Lib/urllib/parse.py python/branches/py3k/Misc/NEWS Modified: python/branches/py3k/Lib/urllib/parse.py ============================================================================== --- python/branches/py3k/Lib/urllib/parse.py (original) +++ python/branches/py3k/Lib/urllib/parse.py Mon May 17 19:33:07 2010 @@ -41,7 +41,7 @@ uses_netloc = ['ftp', 'http', 'gopher', 'nntp', 'telnet', 'imap', 'wais', 'file', 'mms', 'https', 'shttp', 'snews', 'prospero', 'rtsp', 'rtspu', 'rsync', '', - 'svn', 'svn+ssh', 'sftp', 'nfs',' git', 'git+ssh'] + 'svn', 'svn+ssh', 'sftp', 'nfs', 'git', 'git+ssh'] non_hierarchical = ['gopher', 'hdl', 'mailto', 'news', 'telnet', 'wais', 'imap', 'snews', 'sip', 'sips'] uses_params = ['ftp', 'hdl', 'prospero', 'http', 'imap', @@ -307,17 +307,20 @@ """unquote_to_bytes('abc%20def') -> b'abc def'.""" # Note: strings are encoded as UTF-8. This is only an issue if it contains # unescaped non-ASCII characters, which URIs should not. + if not string: + return b'' if isinstance(string, str): string = string.encode('utf-8') res = string.split(b'%') - res[0] = res[0] - for i in range(1, len(res)): - item = res[i] + if len(res) == 1: + return string + string = res[0] + for item in res[1:]: try: - res[i] = bytes([int(item[:2], 16)]) + item[2:] + string += bytes([int(item[:2], 16)]) + item[2:] except ValueError: - res[i] = b'%' + item - return b''.join(res) + string += b'%' + item + return string def unquote(string, encoding='utf-8', errors='replace'): """Replace %xx escapes by their single-character equivalent. The optional @@ -329,36 +332,39 @@ unquote('abc%20def') -> 'abc def'. """ - if encoding is None: encoding = 'utf-8' - if errors is None: errors = 'replace' - # pct_sequence: contiguous sequence of percent-encoded bytes, decoded - # (list of single-byte bytes objects) - pct_sequence = [] + if not string: + return string res = string.split('%') - for i in range(1, len(res)): - item = res[i] + if len(res) == 1: + return string + if encoding is None: + encoding = 'utf-8' + if errors is None: + errors = 'replace' + # pct_sequence: contiguous sequence of percent-encoded bytes + pct_sequence = b'' + string = res[0] + for item in res[1:]: try: - if not item: raise ValueError - pct_sequence.append(bytes.fromhex(item[:2])) + if not item: + raise ValueError + pct_sequence += bytes.fromhex(item[:2]) rest = item[2:] + if not rest: + # This segment was just a single percent-encoded character. + # May be part of a sequence of code units, so delay decoding. + # (Stored in pct_sequence). + continue except ValueError: rest = '%' + item - if not rest: - # This segment was just a single percent-encoded character. - # May be part of a sequence of code units, so delay decoding. - # (Stored in pct_sequence). - res[i] = '' - else: - # Encountered non-percent-encoded characters. Flush the current - # pct_sequence. - res[i] = b''.join(pct_sequence).decode(encoding, errors) + rest - pct_sequence = [] + # Encountered non-percent-encoded characters. Flush the current + # pct_sequence. + string += pct_sequence.decode(encoding, errors) + rest + pct_sequence = b'' if pct_sequence: # Flush the final pct_sequence - # res[-1] will always be empty if pct_sequence != [] - assert not res[-1], "string=%r, res=%r" % (string, res) - res[-1] = b''.join(pct_sequence).decode(encoding, errors) - return ''.join(res) + string += pct_sequence.decode(encoding, errors) + return string def parse_qs(qs, keep_blank_values=False, strict_parsing=False): """Parse a query given as a string argument. @@ -439,7 +445,8 @@ b'abcdefghijklmnopqrstuvwxyz' b'0123456789' b'_.-') -_safe_quoters= {} +_ALWAYS_SAFE_BYTES = bytes(_ALWAYS_SAFE) +_safe_quoters = {} class Quoter(collections.defaultdict): """A mapping from bytes (in range(0,256)) to strings. @@ -451,7 +458,7 @@ # of cached keys don't call Python code at all). def __init__(self, safe): """safe: bytes object.""" - self.safe = _ALWAYS_SAFE.union(c for c in safe if c < 128) + self.safe = _ALWAYS_SAFE.union(safe) def __repr__(self): # Without this, will just display as a defaultdict @@ -459,7 +466,7 @@ def __missing__(self, b): # Handle a cache miss. Store quoted string in cache and return. - res = b in self.safe and chr(b) or ('%%%02X' % b) + res = chr(b) if b in self.safe else '%{:02X}'.format(b) self[b] = res return res @@ -493,6 +500,8 @@ errors='strict' (unsupported characters raise a UnicodeEncodeError). """ if isinstance(string, str): + if not string: + return string if encoding is None: encoding = 'utf-8' if errors is None: @@ -527,18 +536,22 @@ not perform string-to-bytes encoding. It always returns an ASCII string. quote_from_bytes(b'abc def\xab') -> 'abc%20def%AB' """ + if not isinstance(bs, (bytes, bytearray)): + raise TypeError("quote_from_bytes() expected bytes") + if not bs: + return '' if isinstance(safe, str): # Normalize 'safe' by converting to bytes and removing non-ASCII chars safe = safe.encode('ascii', 'ignore') - cachekey = bytes(safe) # In case it was a bytearray - if not (isinstance(bs, bytes) or isinstance(bs, bytearray)): - raise TypeError("quote_from_bytes() expected a bytes") + else: + safe = bytes([c for c in safe if c < 128]) + if not bs.rstrip(_ALWAYS_SAFE_BYTES + safe): + return bs.decode() try: - quoter = _safe_quoters[cachekey] + quoter = _safe_quoters[safe] except KeyError: - quoter = Quoter(safe) - _safe_quoters[cachekey] = quoter - return ''.join([quoter[char] for char in bs]) + _safe_quoters[safe] = quoter = Quoter(safe).__getitem__ + return ''.join([quoter(char) for char in bs]) def urlencode(query, doseq=False): """Encode a sequence of two-element tuples or dictionary into a URL query string. Modified: python/branches/py3k/Misc/NEWS ============================================================================== --- python/branches/py3k/Misc/NEWS (original) +++ python/branches/py3k/Misc/NEWS Mon May 17 19:33:07 2010 @@ -366,6 +366,9 @@ Library ------- +- Issue #1285086: Speed up urllib.parse functions: quote, quote_from_bytes, + unquote, unquote_to_bytes. + - Issue #8688: Distutils now recalculates MANIFEST everytime. - Issue #8477: ssl.RAND_egd() and ssl._test_decode_cert() support str with From python-checkins at python.org Mon May 17 20:01:22 2010 From: python-checkins at python.org (florent.xicluna) Date: Mon, 17 May 2010 20:01:22 +0200 (CEST) Subject: [Python-checkins] r81272 - python/branches/py3k/Lib/urllib/parse.py Message-ID: <20100517180122.8DEFFEEA23@mail.python.org> Author: florent.xicluna Date: Mon May 17 20:01:22 2010 New Revision: 81272 Log: Inadvertently removed part of the comment in r81271. Modified: python/branches/py3k/Lib/urllib/parse.py Modified: python/branches/py3k/Lib/urllib/parse.py ============================================================================== --- python/branches/py3k/Lib/urllib/parse.py (original) +++ python/branches/py3k/Lib/urllib/parse.py Mon May 17 20:01:22 2010 @@ -341,7 +341,7 @@ encoding = 'utf-8' if errors is None: errors = 'replace' - # pct_sequence: contiguous sequence of percent-encoded bytes + # pct_sequence: contiguous sequence of percent-encoded bytes, decoded pct_sequence = b'' string = res[0] for item in res[1:]: From python-checkins at python.org Mon May 17 20:02:51 2010 From: python-checkins at python.org (lars.gustaebel) Date: Mon, 17 May 2010 20:02:51 +0200 (CEST) Subject: [Python-checkins] r81273 - in python/branches/py3k: Doc/library/tarfile.rst Lib/tarfile.py Lib/test/test_tarfile.py Lib/test/testtar.tar Misc/NEWS Message-ID: <20100517180251.30924EE9A5@mail.python.org> Author: lars.gustaebel Date: Mon May 17 20:02:50 2010 New Revision: 81273 Log: Issue #8633: Support for POSIX.1-2008 binary pax headers. tarfile is now able to read and write pax headers with a "hdrcharset=BINARY" record. This record was introduced in POSIX.1-2008 as a method to store unencoded binary strings that cannot be translated to UTF-8. In practice, this is just a workaround that allows a tar implementation to store filenames that do not comply with the current filesystem encoding and thus cannot be decoded correctly. Additionally, tarfile works around a bug in current versions of GNU tar: undecodable filenames are stored as-is in a pax header without a "hdrcharset" record being added. Technically, these headers are invalid, but tarfile manages to read them correctly anyway. Modified: python/branches/py3k/Doc/library/tarfile.rst python/branches/py3k/Lib/tarfile.py python/branches/py3k/Lib/test/test_tarfile.py python/branches/py3k/Lib/test/testtar.tar python/branches/py3k/Misc/NEWS Modified: python/branches/py3k/Doc/library/tarfile.rst ============================================================================== --- python/branches/py3k/Doc/library/tarfile.rst (original) +++ python/branches/py3k/Doc/library/tarfile.rst Mon May 17 20:02:50 2010 @@ -711,6 +711,8 @@ The default scheme is ``'surrogateescape'`` which Python also uses for its file system calls, see :ref:`os-filenames`. -In case of writing :const:`PAX_FORMAT` archives, *encoding* is ignored because -non-ASCII metadata is stored using *UTF-8*. Storing surrogate characters is not -possible and will raise a :exc:`UnicodeEncodeError`. +In case of :const:`PAX_FORMAT` archives, *encoding* is generally not needed +because all the metadata is stored using *UTF-8*. *encoding* is only used in +the rare cases when binary pax headers are decoded or when strings with +surrogate characters are stored. + Modified: python/branches/py3k/Lib/tarfile.py ============================================================================== --- python/branches/py3k/Lib/tarfile.py (original) +++ python/branches/py3k/Lib/tarfile.py Mon May 17 20:02:50 2010 @@ -118,6 +118,9 @@ PAX_FIELDS = ("path", "linkpath", "size", "mtime", "uid", "gid", "uname", "gname") +# Fields from a pax header that are affected by hdrcharset. +PAX_NAME_FIELDS = {"path", "linkpath", "uname", "gname"} + # Fields in a pax header that are numbers, all other fields # are treated as strings. PAX_NUMBER_FIELDS = { @@ -988,7 +991,7 @@ elif format == GNU_FORMAT: return self.create_gnu_header(info, encoding, errors) elif format == PAX_FORMAT: - return self.create_pax_header(info) + return self.create_pax_header(info, encoding) else: raise ValueError("invalid format") @@ -1019,7 +1022,7 @@ return buf + self._create_header(info, GNU_FORMAT, encoding, errors) - def create_pax_header(self, info): + def create_pax_header(self, info, encoding): """Return the object as a ustar header block. If it cannot be represented this way, prepend a pax extended header sequence with supplement information. @@ -1062,7 +1065,7 @@ # Create a pax extended header if necessary. if pax_headers: - buf = self._create_pax_generic_header(pax_headers, XHDTYPE) + buf = self._create_pax_generic_header(pax_headers, XHDTYPE, encoding) else: buf = b"" @@ -1072,7 +1075,7 @@ def create_pax_global_header(cls, pax_headers): """Return the object as a pax global header block sequence. """ - return cls._create_pax_generic_header(pax_headers, XGLTYPE) + return cls._create_pax_generic_header(pax_headers, XGLTYPE, "utf8") def _posix_split_name(self, name): """Split a name longer than 100 chars into a prefix @@ -1145,15 +1148,35 @@ cls._create_payload(name) @classmethod - def _create_pax_generic_header(cls, pax_headers, type): - """Return a POSIX.1-2001 extended or global header sequence + def _create_pax_generic_header(cls, pax_headers, type, encoding): + """Return a POSIX.1-2008 extended or global header sequence that contains a list of keyword, value pairs. The values must be strings. """ + # Check if one of the fields contains surrogate characters and thereby + # forces hdrcharset=BINARY, see _proc_pax() for more information. + binary = False + for keyword, value in pax_headers.items(): + try: + value.encode("utf8", "strict") + except UnicodeEncodeError: + binary = True + break + records = b"" + if binary: + # Put the hdrcharset field at the beginning of the header. + records += b"21 hdrcharset=BINARY\n" + for keyword, value in pax_headers.items(): keyword = keyword.encode("utf8") - value = value.encode("utf8") + if binary: + # Try to restore the original byte representation of `value'. + # Needless to say, that the encoding must match the string. + value = value.encode(encoding, "surrogateescape") + else: + value = value.encode("utf8") + l = len(keyword) + len(value) + 3 # ' ' + '=' + '\n' n = p = 0 while True: @@ -1354,7 +1377,7 @@ def _proc_pax(self, tarfile): """Process an extended or global header as described in - POSIX.1-2001. + POSIX.1-2008. """ # Read the header information. buf = tarfile.fileobj.read(self._block(self.size)) @@ -1367,6 +1390,24 @@ else: pax_headers = tarfile.pax_headers.copy() + # Check if the pax header contains a hdrcharset field. This tells us + # the encoding of the path, linkpath, uname and gname fields. Normally, + # these fields are UTF-8 encoded but since POSIX.1-2008 tar + # implementations are allowed to store them as raw binary strings if + # the translation to UTF-8 fails. + match = re.search(br"\d+ hdrcharset=([^\n]+)\n", buf) + if match is not None: + pax_headers["hdrcharset"] = match.group(1).decode("utf8") + + # For the time being, we don't care about anything other than "BINARY". + # The only other value that is currently allowed by the standard is + # "ISO-IR 10646 2000 UTF-8" in other words UTF-8. + hdrcharset = pax_headers.get("hdrcharset") + if hdrcharset == "BINARY": + encoding = tarfile.encoding + else: + encoding = "utf8" + # Parse pax header information. A record looks like that: # "%d %s=%s\n" % (length, keyword, value). length is the size # of the complete record including the length field itself and @@ -1382,8 +1423,21 @@ length = int(length) value = buf[match.end(2) + 1:match.start(1) + length - 1] - keyword = keyword.decode("utf8") - value = value.decode("utf8") + # Normally, we could just use "utf8" as the encoding and "strict" + # as the error handler, but we better not take the risk. For + # example, GNU tar <= 1.23 is known to store filenames it cannot + # translate to UTF-8 as raw strings (unfortunately without a + # hdrcharset=BINARY header). + # We first try the strict standard encoding, and if that fails we + # fall back on the user's encoding and error handler. + keyword = self._decode_pax_field(keyword, "utf8", "utf8", + tarfile.errors) + if keyword in PAX_NAME_FIELDS: + value = self._decode_pax_field(value, encoding, tarfile.encoding, + tarfile.errors) + else: + value = self._decode_pax_field(value, "utf8", "utf8", + tarfile.errors) pax_headers[keyword] = value pos += length @@ -1431,6 +1485,14 @@ self.pax_headers = pax_headers.copy() + def _decode_pax_field(self, value, encoding, fallback_encoding, fallback_errors): + """Decode a single field from a pax record. + """ + try: + return value.decode(encoding, "strict") + except UnicodeDecodeError: + return value.decode(fallback_encoding, fallback_errors) + def _block(self, count): """Round up a byte count by BLOCKSIZE and return it, e.g. _block(834) => 1024. Modified: python/branches/py3k/Lib/test/test_tarfile.py ============================================================================== --- python/branches/py3k/Lib/test/test_tarfile.py (original) +++ python/branches/py3k/Lib/test/test_tarfile.py Mon May 17 20:02:50 2010 @@ -1126,11 +1126,32 @@ format = tarfile.GNU_FORMAT + def test_bad_pax_header(self): + # Test for issue #8633. GNU tar <= 1.23 creates raw binary fields + # without a hdrcharset=BINARY header. + for encoding, name in (("utf8", "pax/bad-pax-\udce4\udcf6\udcfc"), + ("iso8859-1", "pax/bad-pax-\xe4\xf6\xfc"),): + with tarfile.open(tarname, encoding=encoding, errors="surrogateescape") as tar: + try: + t = tar.getmember(name) + except KeyError: + self.fail("unable to read bad GNU tar pax header") + class PAXUnicodeTest(UstarUnicodeTest): format = tarfile.PAX_FORMAT + def test_binary_header(self): + # Test a POSIX.1-2008 compatible header with a hdrcharset=BINARY field. + for encoding, name in (("utf8", "pax/hdrcharset-\udce4\udcf6\udcfc"), + ("iso8859-1", "pax/hdrcharset-\xe4\xf6\xfc"),): + with tarfile.open(tarname, encoding=encoding, errors="surrogateescape") as tar: + try: + t = tar.getmember(name) + except KeyError: + self.fail("unable to read POSIX.1-2008 binary header") + class AppendTest(unittest.TestCase): # Test append mode (cp. patch #1652681). Modified: python/branches/py3k/Lib/test/testtar.tar ============================================================================== Binary files. No diff available. Modified: python/branches/py3k/Misc/NEWS ============================================================================== --- python/branches/py3k/Misc/NEWS (original) +++ python/branches/py3k/Misc/NEWS Mon May 17 20:02:50 2010 @@ -366,6 +366,9 @@ Library ------- +- Issue #8633: tarfile is now able to read and write archives with "raw" binary + pax headers as described in POSIX.1-2008. + - Issue #1285086: Speed up urllib.parse functions: quote, quote_from_bytes, unquote, unquote_to_bytes. From python-checkins at python.org Mon May 17 20:11:22 2010 From: python-checkins at python.org (lars.gustaebel) Date: Mon, 17 May 2010 20:11:22 +0200 (CEST) Subject: [Python-checkins] r81274 - python/branches/release31-maint Message-ID: <20100517181122.3EC35EEA1C@mail.python.org> Author: lars.gustaebel Date: Mon May 17 20:11:22 2010 New Revision: 81274 Log: Blocked revisions 81273 via svnmerge ........ r81273 | lars.gustaebel | 2010-05-17 20:02:50 +0200 (Mon, 17 May 2010) | 15 lines Issue #8633: Support for POSIX.1-2008 binary pax headers. tarfile is now able to read and write pax headers with a "hdrcharset=BINARY" record. This record was introduced in POSIX.1-2008 as a method to store unencoded binary strings that cannot be translated to UTF-8. In practice, this is just a workaround that allows a tar implementation to store filenames that do not comply with the current filesystem encoding and thus cannot be decoded correctly. Additionally, tarfile works around a bug in current versions of GNU tar: undecodable filenames are stored as-is in a pax header without a "hdrcharset" record being added. Technically, these headers are invalid, but tarfile manages to read them correctly anyway. ........ Modified: python/branches/release31-maint/ (props changed) From python-checkins at python.org Mon May 17 21:57:00 2010 From: python-checkins at python.org (antoine.pitrou) Date: Mon, 17 May 2010 21:57:00 +0200 (CEST) Subject: [Python-checkins] r81275 - in python/trunk: Lib/test/test_file2k.py Misc/NEWS Objects/fileobject.c Message-ID: <20100517195700.24A9BEE9BB@mail.python.org> Author: antoine.pitrou Date: Mon May 17 21:56:59 2010 New Revision: 81275 Log: Issue #7079: Fix a possible crash when closing a file object while using it from another thread. Patch by Daniel Stutzbach. Modified: python/trunk/Lib/test/test_file2k.py python/trunk/Misc/NEWS python/trunk/Objects/fileobject.c Modified: python/trunk/Lib/test/test_file2k.py ============================================================================== --- python/trunk/Lib/test/test_file2k.py (original) +++ python/trunk/Lib/test/test_file2k.py Mon May 17 21:56:59 2010 @@ -429,6 +429,7 @@ self._count_lock = threading.Lock() self.close_count = 0 self.close_success_count = 0 + self.use_buffering = False def tearDown(self): if self.f: @@ -443,7 +444,10 @@ test_support.threading_cleanup(*self._threads) def _create_file(self): - self.f = open(self.filename, "w+") + if self.use_buffering: + self.f = open(self.filename, "w+", buffering=1024*16) + else: + self.f = open(self.filename, "w+") def _close_file(self): with self._count_lock: @@ -530,6 +534,12 @@ print >> self.f, '' self._test_close_open_io(io_func) + def test_close_open_print_buffered(self): + self.use_buffering = True + def io_func(): + print >> self.f, '' + self._test_close_open_io(io_func) + def test_close_open_read(self): def io_func(): self.f.read(0) Modified: python/trunk/Misc/NEWS ============================================================================== --- python/trunk/Misc/NEWS (original) +++ python/trunk/Misc/NEWS Mon May 17 21:56:59 2010 @@ -12,6 +12,9 @@ Core and Builtins ----------------- +- Issue #7079: Fix a possible crash when closing a file object while using + it from another thread. Patch by Daniel Stutzbach. + Library ------- Modified: python/trunk/Objects/fileobject.c ============================================================================== --- python/trunk/Objects/fileobject.c (original) +++ python/trunk/Objects/fileobject.c Mon May 17 21:56:59 2010 @@ -649,8 +649,10 @@ file_close(PyFileObject *f) { PyObject *sts = close_the_file(f); - PyMem_Free(f->f_setbuf); - f->f_setbuf = NULL; + if (sts) { + PyMem_Free(f->f_setbuf); + f->f_setbuf = NULL; + } return sts; } From python-checkins at python.org Mon May 17 21:57:40 2010 From: python-checkins at python.org (victor.stinner) Date: Mon, 17 May 2010 21:57:40 +0200 (CEST) Subject: [Python-checkins] r81276 - python/branches/py3k/Lib/test/test_sys.py Message-ID: <20100517195740.E8A22EE9BB@mail.python.org> Author: victor.stinner Date: Mon May 17 21:57:40 2010 New Revision: 81276 Log: Fix test_main_invalid_unicode() of test_sys for ASCII locale encoding It should fix sparc 3.x and 3.1 failures. Modified: python/branches/py3k/Lib/test/test_sys.py Modified: python/branches/py3k/Lib/test/test_sys.py ============================================================================== --- python/branches/py3k/Lib/test/test_sys.py (original) +++ python/branches/py3k/Lib/test/test_sys.py Mon May 17 21:57:40 2010 @@ -152,7 +152,7 @@ stdout, stderr = process.communicate() self.assertEqual(process.returncode, 1) self.assertTrue(stderr.startswith(expected), - "%r doesn't start with %r" % (stderr, expected)) + "%s doesn't start with %s" % (ascii(stderr), ascii(expected))) # test that stderr buffer if flushed before the exit message is written # into stderr @@ -485,9 +485,8 @@ p = subprocess.Popen([sys.executable, "-c", code], stderr=subprocess.PIPE) stdout, stderr = p.communicate() self.assertEqual(p.returncode, 1) - self.assert_(stderr.startswith(b"UnicodeEncodeError: " - b"'utf-8' codec can't encode character '\\udcff' in " - b"position 7: surrogates not allowed"), stderr) + self.assert_(b"UnicodeEncodeError:" in stderr, + "%r not in %s" % (b"UniodeEncodeError:", ascii(stderr))) def test_sys_flags(self): self.assertTrue(sys.flags) From python-checkins at python.org Mon May 17 22:00:52 2010 From: python-checkins at python.org (antoine.pitrou) Date: Mon, 17 May 2010 22:00:52 +0200 (CEST) Subject: [Python-checkins] r81277 - in python/branches/release26-maint: Lib/test/test_file.py Misc/NEWS Objects/fileobject.c Message-ID: <20100517200052.52053EE9D3@mail.python.org> Author: antoine.pitrou Date: Mon May 17 22:00:52 2010 New Revision: 81277 Log: Merged revisions 81275 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r81275 | antoine.pitrou | 2010-05-17 21:56:59 +0200 (lun., 17 mai 2010) | 4 lines Issue #7079: Fix a possible crash when closing a file object while using it from another thread. Patch by Daniel Stutzbach. ........ Modified: python/branches/release26-maint/ (props changed) python/branches/release26-maint/Lib/test/test_file.py python/branches/release26-maint/Misc/NEWS python/branches/release26-maint/Objects/fileobject.c Modified: python/branches/release26-maint/Lib/test/test_file.py ============================================================================== --- python/branches/release26-maint/Lib/test/test_file.py (original) +++ python/branches/release26-maint/Lib/test/test_file.py Mon May 17 22:00:52 2010 @@ -417,6 +417,7 @@ self._count_lock = threading.Lock() self.close_count = 0 self.close_success_count = 0 + self.use_buffering = False def tearDown(self): if self.f: @@ -430,7 +431,10 @@ pass def _create_file(self): - self.f = open(self.filename, "w+") + if self.use_buffering: + self.f = open(self.filename, "w+", buffering=1024*16) + else: + self.f = open(self.filename, "w+") def _close_file(self): with self._count_lock: @@ -517,6 +521,12 @@ print >> self.f, '' self._test_close_open_io(io_func) + def test_close_open_print_buffered(self): + self.use_buffering = True + def io_func(): + print >> self.f, '' + self._test_close_open_io(io_func) + def test_close_open_read(self): def io_func(): self.f.read(0) Modified: python/branches/release26-maint/Misc/NEWS ============================================================================== --- python/branches/release26-maint/Misc/NEWS (original) +++ python/branches/release26-maint/Misc/NEWS Mon May 17 22:00:52 2010 @@ -12,6 +12,9 @@ Core and Builtins ----------------- +- Issue #7079: Fix a possible crash when closing a file object while using + it from another thread. Patch by Daniel Stutzbach. + - Issue #1533: fix inconsistency in range function argument processing: any non-float non-integer argument is now converted to an integer (if possible) using its __int__ method. Previously, only Modified: python/branches/release26-maint/Objects/fileobject.c ============================================================================== --- python/branches/release26-maint/Objects/fileobject.c (original) +++ python/branches/release26-maint/Objects/fileobject.c Mon May 17 22:00:52 2010 @@ -568,8 +568,10 @@ file_close(PyFileObject *f) { PyObject *sts = close_the_file(f); - PyMem_Free(f->f_setbuf); - f->f_setbuf = NULL; + if (sts) { + PyMem_Free(f->f_setbuf); + f->f_setbuf = NULL; + } return sts; } From python-checkins at python.org Mon May 17 22:01:55 2010 From: python-checkins at python.org (victor.stinner) Date: Mon, 17 May 2010 22:01:55 +0200 (CEST) Subject: [Python-checkins] r81278 - in python/branches/release31-maint: Lib/test/test_sys.py Message-ID: <20100517200155.4C870EE9D3@mail.python.org> Author: victor.stinner Date: Mon May 17 22:01:55 2010 New Revision: 81278 Log: Merged revisions 81276 via svnmerge from svn+ssh://pythondev at svn.python.org/python/branches/py3k ........ r81276 | victor.stinner | 2010-05-17 21:57:40 +0200 (lun., 17 mai 2010) | 4 lines Fix test_main_invalid_unicode() of test_sys for ASCII locale encoding It should fix sparc 3.x and 3.1 failures. ........ Modified: python/branches/release31-maint/ (props changed) python/branches/release31-maint/Lib/test/test_sys.py Modified: python/branches/release31-maint/Lib/test/test_sys.py ============================================================================== --- python/branches/release31-maint/Lib/test/test_sys.py (original) +++ python/branches/release31-maint/Lib/test/test_sys.py Mon May 17 22:01:55 2010 @@ -145,7 +145,7 @@ stdout, stderr = process.communicate() self.assertEqual(process.returncode, 1) self.assertTrue(stderr.startswith(expected), - "%r doesn't start with %r" % (stderr, expected)) + "%s doesn't start with %s" % (ascii(stderr), ascii(expected))) # test that stderr buffer if flushed before the exit message is written # into stderr @@ -439,9 +439,8 @@ p = subprocess.Popen([sys.executable, "-c", code], stderr=subprocess.PIPE) stdout, stderr = p.communicate() self.assertEqual(p.returncode, 1) - self.assert_(stderr.startswith(b"UnicodeEncodeError: " - b"'utf-8' codec can't encode character '\\udcff' in " - b"position 7: surrogates not allowed"), stderr) + self.assert_(b"UnicodeEncodeError:" in stderr, + "%r not in %s" % (b"UniodeEncodeError:", ascii(stderr))) def test_sys_flags(self): self.assertTrue(sys.flags) From solipsis at pitrou.net Tue May 18 01:23:18 2010 From: solipsis at pitrou.net (solipsis at pitrou.net) Date: Tue, 18 May 2010 01:23:18 +0200 (CEST) Subject: [Python-checkins] Daily py3k reference leaks (r81276): sum=0 Message-ID: <20100517232318.E78831770A@ns6635.ovh.net> py3k results for svn r81276 (hg cset b5a846514900) -------------------------------------------------- Command line was: ['./python', '-m', 'test.regrtest', '-uall', '-R', '3:3:/home/antoine/py3k/refleaks/reflogcHnpLI', '-x'] From python-checkins at python.org Tue May 18 05:20:43 2010 From: python-checkins at python.org (senthil.kumaran) Date: Tue, 18 May 2010 05:20:43 +0200 (CEST) Subject: [Python-checkins] r81279 - python/trunk/Doc/library/test.rst Message-ID: <20100518032043.5093FEE990@mail.python.org> Author: senthil.kumaran Date: Tue May 18 05:20:43 2010 New Revision: 81279 Log: Fix minor typo. Modified: python/trunk/Doc/library/test.rst Modified: python/trunk/Doc/library/test.rst ============================================================================== --- python/trunk/Doc/library/test.rst (original) +++ python/trunk/Doc/library/test.rst Tue May 18 05:20:43 2010 @@ -369,7 +369,7 @@ .. function:: captured_stdout() - This is a context manager than runs the :keyword:`with` statement body using + This is a context manager that runs the :keyword:`with` statement body using a :class:`StringIO.StringIO` object as sys.stdout. That object can be retrieved using the ``as`` clause of the :keyword:`with` statement. From python-checkins at python.org Tue May 18 05:23:44 2010 From: python-checkins at python.org (senthil.kumaran) Date: Tue, 18 May 2010 05:23:44 +0200 (CEST) Subject: [Python-checkins] r81280 - in python/branches/release26-maint: Doc/library/test.rst Message-ID: <20100518032344.16408EE981@mail.python.org> Author: senthil.kumaran Date: Tue May 18 05:23:43 2010 New Revision: 81280 Log: Merged revisions 81279 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r81279 | senthil.kumaran | 2010-05-18 08:50:43 +0530 (Tue, 18 May 2010) | 3 lines Fix minor typo. ........ Modified: python/branches/release26-maint/ (props changed) python/branches/release26-maint/Doc/library/test.rst Modified: python/branches/release26-maint/Doc/library/test.rst ============================================================================== --- python/branches/release26-maint/Doc/library/test.rst (original) +++ python/branches/release26-maint/Doc/library/test.rst Tue May 18 05:23:43 2010 @@ -326,7 +326,7 @@ .. function:: captured_stdout() - This is a context manager than runs the :keyword:`with` statement body using + This is a context manager that runs the :keyword:`with` statement body using a :class:`StringIO.StringIO` object as sys.stdout. That object can be retrieved using the ``as`` clause of the :keyword:`with` statement. From python-checkins at python.org Tue May 18 05:26:11 2010 From: python-checkins at python.org (senthil.kumaran) Date: Tue, 18 May 2010 05:26:11 +0200 (CEST) Subject: [Python-checkins] r81281 - in python/branches/py3k: Doc/library/test.rst Message-ID: <20100518032611.42EC0EE981@mail.python.org> Author: senthil.kumaran Date: Tue May 18 05:26:11 2010 New Revision: 81281 Log: Merged revisions 81279 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r81279 | senthil.kumaran | 2010-05-18 08:50:43 +0530 (Tue, 18 May 2010) | 3 lines Fix minor typo. ........ Modified: python/branches/py3k/ (props changed) python/branches/py3k/Doc/library/test.rst Modified: python/branches/py3k/Doc/library/test.rst ============================================================================== --- python/branches/py3k/Doc/library/test.rst (original) +++ python/branches/py3k/Doc/library/test.rst Tue May 18 05:26:11 2010 @@ -340,7 +340,7 @@ .. function:: captured_stdout() - This is a context manager than runs the :keyword:`with` statement body using + This is a context manager that runs the :keyword:`with` statement body using a :class:`StringIO.StringIO` object as sys.stdout. That object can be retrieved using the ``as`` clause of the :keyword:`with` statement. From python-checkins at python.org Tue May 18 05:28:45 2010 From: python-checkins at python.org (senthil.kumaran) Date: Tue, 18 May 2010 05:28:45 +0200 (CEST) Subject: [Python-checkins] r81282 - in python/branches/release31-maint: Doc/library/test.rst Message-ID: <20100518032845.243D8EE997@mail.python.org> Author: senthil.kumaran Date: Tue May 18 05:28:44 2010 New Revision: 81282 Log: Merged revisions 81281 via svnmerge from svn+ssh://pythondev at svn.python.org/python/branches/py3k ................ r81281 | senthil.kumaran | 2010-05-18 08:56:11 +0530 (Tue, 18 May 2010) | 9 lines Merged revisions 81279 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r81279 | senthil.kumaran | 2010-05-18 08:50:43 +0530 (Tue, 18 May 2010) | 3 lines Fix minor typo. ........ ................ Modified: python/branches/release31-maint/ (props changed) python/branches/release31-maint/Doc/library/test.rst Modified: python/branches/release31-maint/Doc/library/test.rst ============================================================================== --- python/branches/release31-maint/Doc/library/test.rst (original) +++ python/branches/release31-maint/Doc/library/test.rst Tue May 18 05:28:44 2010 @@ -310,7 +310,7 @@ .. function:: captured_stdout() - This is a context manager than runs the :keyword:`with` statement body using + This is a context manager that runs the :keyword:`with` statement body using a :class:`StringIO.StringIO` object as sys.stdout. That object can be retrieved using the ``as`` clause of the :keyword:`with` statement. From python-checkins at python.org Tue May 18 05:58:36 2010 From: python-checkins at python.org (senthil.kumaran) Date: Tue, 18 May 2010 05:58:36 +0200 (CEST) Subject: [Python-checkins] r81283 - python/branches/py3k/Doc/library/urllib.request.rst Message-ID: <20100518035836.D424CEEA2D@mail.python.org> Author: senthil.kumaran Date: Tue May 18 05:58:36 2010 New Revision: 81283 Log: Removing the reference in the docs for overriding _urlopener global value. See Issue8619 for details. Modified: python/branches/py3k/Doc/library/urllib.request.rst Modified: python/branches/py3k/Doc/library/urllib.request.rst ============================================================================== --- python/branches/py3k/Doc/library/urllib.request.rst (original) +++ python/branches/py3k/Doc/library/urllib.request.rst Tue May 18 05:58:36 2010 @@ -126,26 +126,6 @@ of the data it has downloaded, and just returns it. In this case you just have to assume that the download was successful. - -.. data:: _urlopener - - The public functions :func:`urlopen` and :func:`urlretrieve` create an instance - of the :class:`FancyURLopener` class and use it to perform their requested - actions. To override this functionality, programmers can create a subclass of - :class:`URLopener` or :class:`FancyURLopener`, then assign an instance of that - class to the ``urllib.request._urlopener`` variable before calling the - desired function. For example, applications may want to specify a different - :mailheader:`User-Agent` header than :class:`URLopener` defines. - This can be accomplished with the following code:: - - import urllib.request - - class AppURLopener(urllib.request.FancyURLopener): - version = "App/1.7" - - urllib.request._urlopener = AppURLopener() - - .. function:: urlcleanup() Clear the cache that may have been built up by previous calls to From python-checkins at python.org Tue May 18 06:01:11 2010 From: python-checkins at python.org (senthil.kumaran) Date: Tue, 18 May 2010 06:01:11 +0200 (CEST) Subject: [Python-checkins] r81284 - in python/branches/release31-maint: Doc/library/urllib.request.rst Message-ID: <20100518040111.86EE8C972@mail.python.org> Author: senthil.kumaran Date: Tue May 18 06:01:11 2010 New Revision: 81284 Log: Merged revisions 81283 via svnmerge from svn+ssh://pythondev at svn.python.org/python/branches/py3k ........ r81283 | senthil.kumaran | 2010-05-18 09:28:36 +0530 (Tue, 18 May 2010) | 3 lines Removing the reference in the docs for overriding _urlopener global value. See Issue8619 for details. ........ Modified: python/branches/release31-maint/ (props changed) python/branches/release31-maint/Doc/library/urllib.request.rst Modified: python/branches/release31-maint/Doc/library/urllib.request.rst ============================================================================== --- python/branches/release31-maint/Doc/library/urllib.request.rst (original) +++ python/branches/release31-maint/Doc/library/urllib.request.rst Tue May 18 06:01:11 2010 @@ -126,26 +126,6 @@ of the data it has downloaded, and just returns it. In this case you just have to assume that the download was successful. - -.. data:: _urlopener - - The public functions :func:`urlopen` and :func:`urlretrieve` create an instance - of the :class:`FancyURLopener` class and use it to perform their requested - actions. To override this functionality, programmers can create a subclass of - :class:`URLopener` or :class:`FancyURLopener`, then assign an instance of that - class to the ``urllib.request._urlopener`` variable before calling the - desired function. For example, applications may want to specify a different - :mailheader:`User-Agent` header than :class:`URLopener` defines. - This can be accomplished with the following code:: - - import urllib.request - - class AppURLopener(urllib.request.FancyURLopener): - version = "App/1.7" - - urllib.request._urlopener = AppURLopener() - - .. function:: urlcleanup() Clear the cache that may have been built up by previous calls to From python-checkins at python.org Tue May 18 10:16:27 2010 From: python-checkins at python.org (vinay.sajip) Date: Tue, 18 May 2010 10:16:27 +0200 (CEST) Subject: [Python-checkins] r81285 - python/trunk/Doc/library/logging.rst Message-ID: <20100518081627.CE8B6C95D@mail.python.org> Author: vinay.sajip Date: Tue May 18 10:16:27 2010 New Revision: 81285 Log: Fixed minor typo in ReST markup. Modified: python/trunk/Doc/library/logging.rst Modified: python/trunk/Doc/library/logging.rst ============================================================================== --- python/trunk/Doc/library/logging.rst (original) +++ python/trunk/Doc/library/logging.rst Tue May 18 10:16:27 2010 @@ -333,7 +333,7 @@ to the :func:`dictConfig` function. The following example configures a very simple logger, a console -handler, and a simple formatter using Python code: +handler, and a simple formatter using Python code:: import logging From python-checkins at python.org Tue May 18 15:40:24 2010 From: python-checkins at python.org (senthil.kumaran) Date: Tue, 18 May 2010 15:40:24 +0200 (CEST) Subject: [Python-checkins] r81286 - python/trunk/Parser/asdl.py Message-ID: <20100518134024.13A4DEF02@mail.python.org> Author: senthil.kumaran Date: Tue May 18 15:40:23 2010 New Revision: 81286 Log: Doc Fix. Correct link to Zephyr ASDL Abstract page. Modified: python/trunk/Parser/asdl.py Modified: python/trunk/Parser/asdl.py ============================================================================== --- python/trunk/Parser/asdl.py (original) +++ python/trunk/Parser/asdl.py Tue May 18 15:40:23 2010 @@ -1,7 +1,7 @@ """An implementation of the Zephyr Abstract Syntax Definition Language. See http://asdl.sourceforge.net/ and -http://www.cs.princeton.edu/~danwang/Papers/dsl97/dsl97-abstract.html. +http://www.cs.princeton.edu/research/techreps/TR-554-97 Only supports top level module decl, not view. I'm guessing that view is intended to support the browser and I'm not interested in the From python-checkins at python.org Tue May 18 15:44:50 2010 From: python-checkins at python.org (senthil.kumaran) Date: Tue, 18 May 2010 15:44:50 +0200 (CEST) Subject: [Python-checkins] r81287 - in python/branches/release26-maint: Parser/asdl.py Message-ID: <20100518134450.83A82ECCF@mail.python.org> Author: senthil.kumaran Date: Tue May 18 15:44:50 2010 New Revision: 81287 Log: Merged revisions 81286 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r81286 | senthil.kumaran | 2010-05-18 19:10:23 +0530 (Tue, 18 May 2010) | 3 lines Doc Fix. Correct link to Zephyr ASDL Abstract page. ........ Modified: python/branches/release26-maint/ (props changed) python/branches/release26-maint/Parser/asdl.py Modified: python/branches/release26-maint/Parser/asdl.py ============================================================================== --- python/branches/release26-maint/Parser/asdl.py (original) +++ python/branches/release26-maint/Parser/asdl.py Tue May 18 15:44:50 2010 @@ -1,7 +1,7 @@ """An implementation of the Zephyr Abstract Syntax Definition Language. See http://asdl.sourceforge.net/ and -http://www.cs.princeton.edu/~danwang/Papers/dsl97/dsl97-abstract.html. +http://www.cs.princeton.edu/research/techreps/TR-554-97 Only supports top level module decl, not view. I'm guessing that view is intended to support the browser and I'm not interested in the From python-checkins at python.org Tue May 18 15:48:45 2010 From: python-checkins at python.org (senthil.kumaran) Date: Tue, 18 May 2010 15:48:45 +0200 (CEST) Subject: [Python-checkins] r81288 - in python/branches/py3k: Parser/asdl.py Message-ID: <20100518134845.3D4C5ECE3@mail.python.org> Author: senthil.kumaran Date: Tue May 18 15:48:45 2010 New Revision: 81288 Log: Merged revisions 81286 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r81286 | senthil.kumaran | 2010-05-18 19:10:23 +0530 (Tue, 18 May 2010) | 3 lines Doc Fix. Correct link to Zephyr ASDL Abstract page. ........ Modified: python/branches/py3k/ (props changed) python/branches/py3k/Parser/asdl.py Modified: python/branches/py3k/Parser/asdl.py ============================================================================== --- python/branches/py3k/Parser/asdl.py (original) +++ python/branches/py3k/Parser/asdl.py Tue May 18 15:48:45 2010 @@ -1,7 +1,7 @@ """An implementation of the Zephyr Abstract Syntax Definition Language. See http://asdl.sourceforge.net/ and -http://www.cs.princeton.edu/~danwang/Papers/dsl97/dsl97-abstract.html. +http://www.cs.princeton.edu/research/techreps/TR-554-97 Only supports top level module decl, not view. I'm guessing that view is intended to support the browser and I'm not interested in the From python-checkins at python.org Tue May 18 15:51:07 2010 From: python-checkins at python.org (senthil.kumaran) Date: Tue, 18 May 2010 15:51:07 +0200 (CEST) Subject: [Python-checkins] r81289 - in python/branches/release31-maint: Parser/asdl.py Message-ID: <20100518135107.DDE19EE981@mail.python.org> Author: senthil.kumaran Date: Tue May 18 15:51:07 2010 New Revision: 81289 Log: Merged revisions 81288 via svnmerge from svn+ssh://pythondev at svn.python.org/python/branches/py3k ................ r81288 | senthil.kumaran | 2010-05-18 19:18:45 +0530 (Tue, 18 May 2010) | 9 lines Merged revisions 81286 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r81286 | senthil.kumaran | 2010-05-18 19:10:23 +0530 (Tue, 18 May 2010) | 3 lines Doc Fix. Correct link to Zephyr ASDL Abstract page. ........ ................ Modified: python/branches/release31-maint/ (props changed) python/branches/release31-maint/Parser/asdl.py Modified: python/branches/release31-maint/Parser/asdl.py ============================================================================== --- python/branches/release31-maint/Parser/asdl.py (original) +++ python/branches/release31-maint/Parser/asdl.py Tue May 18 15:51:07 2010 @@ -1,7 +1,7 @@ """An implementation of the Zephyr Abstract Syntax Definition Language. See http://asdl.sourceforge.net/ and -http://www.cs.princeton.edu/~danwang/Papers/dsl97/dsl97-abstract.html. +http://www.cs.princeton.edu/research/techreps/TR-554-97 Only supports top level module decl, not view. I'm guessing that view is intended to support the browser and I'm not interested in the From python-checkins at python.org Tue May 18 16:15:20 2010 From: python-checkins at python.org (barry.warsaw) Date: Tue, 18 May 2010 16:15:20 +0200 (CEST) Subject: [Python-checkins] r81290 - in python/branches/py3k/Lib: importlib/_bootstrap.py importlib/test/source/test_file_loader.py test/test_import.py Message-ID: <20100518141520.7934EC959@mail.python.org> Author: barry.warsaw Date: Tue May 18 16:15:20 2010 New Revision: 81290 Log: Repair test failure. Bug 8727. Modified: python/branches/py3k/Lib/importlib/_bootstrap.py python/branches/py3k/Lib/importlib/test/source/test_file_loader.py python/branches/py3k/Lib/test/test_import.py Modified: python/branches/py3k/Lib/importlib/_bootstrap.py ============================================================================== --- python/branches/py3k/Lib/importlib/_bootstrap.py (original) +++ python/branches/py3k/Lib/importlib/_bootstrap.py Tue May 18 16:15:20 2010 @@ -494,8 +494,16 @@ if ext_type == imp.PY_COMPILED: # We don't really care what the extension on self._base_path is, # as long as it has exactly one dot. - bytecode_path = imp.cache_from_source(self._base_path + '.py') - return (bytecode_path if _path_exists(bytecode_path) else None) + source_path = self._base_path + '.py' + pycache_path = imp.cache_from_source(source_path) + legacy_path = self._base_path + '.pyc' + # The rule is: if the source file exists, then Python always uses + # the __pycache__/foo..pyc file. If the source file does not + # exist, then Python uses the legacy path. + pyc_path = (pycache_path + if _path_exists(source_path) + else legacy_path) + return (pyc_path if _path_exists(pyc_path) else None) return super()._find_path(ext_type) @_check_name Modified: python/branches/py3k/Lib/importlib/test/source/test_file_loader.py ============================================================================== --- python/branches/py3k/Lib/importlib/test/source/test_file_loader.py (original) +++ python/branches/py3k/Lib/importlib/test/source/test_file_loader.py Tue May 18 16:15:20 2010 @@ -10,6 +10,8 @@ import sys import unittest +from test.support import make_legacy_pyc + class SimpleTest(unittest.TestCase): @@ -136,6 +138,7 @@ file.write(new_bc) if del_source: os.unlink(mapping[name]) + make_legacy_pyc(mapping[name]) return bytecode_path @source_util.writes_bytecode_files Modified: python/branches/py3k/Lib/test/test_import.py ============================================================================== --- python/branches/py3k/Lib/test/test_import.py (original) +++ python/branches/py3k/Lib/test/test_import.py Tue May 18 16:15:20 2010 @@ -142,7 +142,6 @@ self.assertIs(orig_path, new_os.path) self.assertIsNot(orig_getenv, new_os.getenv) - @unittest.expectedFailure # Issue 8727 is tracking the fix. def test_module_with_large_stack(self, module='longlist'): # Regression test for http://bugs.python.org/issue561858. filename = module + '.py' From python-checkins at python.org Tue May 18 19:17:24 2010 From: python-checkins at python.org (victor.stinner) Date: Tue, 18 May 2010 19:17:24 +0200 (CEST) Subject: [Python-checkins] r81291 - in python/branches/py3k: Doc/library/os.rst Lib/os.py Lib/subprocess.py Lib/test/test_os.py Lib/test/test_subprocess.py Misc/NEWS Message-ID: <20100518171724.237E4EE9AB@mail.python.org> Author: victor.stinner Date: Tue May 18 19:17:23 2010 New Revision: 81291 Log: Issue #8513: os.get_exec_path() supports b'PATH' key and bytes value. subprocess.Popen() and os._execvpe() support bytes program name. Add os.supports_bytes_environ flag: True if the native OS type of the environment is bytes (eg. False on Windows). Modified: python/branches/py3k/Doc/library/os.rst python/branches/py3k/Lib/os.py python/branches/py3k/Lib/subprocess.py python/branches/py3k/Lib/test/test_os.py python/branches/py3k/Lib/test/test_subprocess.py python/branches/py3k/Misc/NEWS Modified: python/branches/py3k/Doc/library/os.rst ============================================================================== --- python/branches/py3k/Doc/library/os.rst (original) +++ python/branches/py3k/Doc/library/os.rst Tue May 18 19:17:23 2010 @@ -142,7 +142,8 @@ synchronized (modify :data:`environb` updates :data:`environ`, and vice versa). - Availability: Unix. + :data:`environb` is only available if :data:`supports_bytes_environ` is + True. .. versionadded:: 3.2 @@ -457,6 +458,12 @@ Availability: Unix, Windows. +.. data:: supports_bytes_environ + + True if the native OS type of the environment is bytes (eg. False on + Windows). + + .. function:: umask(mask) Set the current numeric umask and return the previous umask. Modified: python/branches/py3k/Lib/os.py ============================================================================== --- python/branches/py3k/Lib/os.py (original) +++ python/branches/py3k/Lib/os.py Tue May 18 19:17:23 2010 @@ -355,7 +355,11 @@ return last_exc = saved_exc = None saved_tb = None - for dir in get_exec_path(env): + path_list = get_exec_path(env) + if name != 'nt': + file = fsencode(file) + path_list = map(fsencode, path_list) + for dir in path_list: fullname = path.join(dir, file) try: exec_func(fullname, *argrest) @@ -380,7 +384,30 @@ """ if env is None: env = environ - return env.get('PATH', defpath).split(pathsep) + + try: + path_list = env.get('PATH') + except TypeError: + path_list = None + + if supports_bytes_environ: + try: + path_listb = env[b'PATH'] + except (KeyError, TypeError): + pass + else: + if path_list is not None: + raise ValueError( + "env cannot contain 'PATH' and b'PATH' keys") + path_list = path_listb + + if path_list is not None and isinstance(path_list, bytes): + path_list = path_list.decode(sys.getfilesystemencoding(), + 'surrogateescape') + + if path_list is None: + path_list = defpath + return path_list.split(pathsep) # Change environ to automatically call putenv(), unsetenv if they exist. @@ -482,9 +509,11 @@ The optional second argument can specify an alternate default. key, default and the result are str.""" return environ.get(key, default) -__all__.append("getenv") -if name not in ('os2', 'nt'): +supports_bytes_environ = name not in ('os2', 'nt') +__all__.extend(("getenv", "supports_bytes_environ")) + +if supports_bytes_environ: def _check_bytes(value): if not isinstance(value, bytes): raise TypeError("bytes expected, not %s" % type(value).__name__) Modified: python/branches/py3k/Lib/subprocess.py ============================================================================== --- python/branches/py3k/Lib/subprocess.py (original) +++ python/branches/py3k/Lib/subprocess.py Tue May 18 19:17:23 2010 @@ -1096,15 +1096,14 @@ for k, v in env.items()] else: env_list = None # Use execv instead of execve. + executable = os.fsencode(executable) if os.path.dirname(executable): - executable_list = (os.fsencode(executable),) + executable_list = (executable,) else: # This matches the behavior of os._execvpe(). - path_list = os.get_exec_path(env) - executable_list = (os.path.join(dir, executable) - for dir in path_list) - executable_list = tuple(os.fsencode(exe) - for exe in executable_list) + executable_list = tuple( + os.path.join(os.fsencode(dir), executable) + for dir in os.get_exec_path(env)) self.pid = _posixsubprocess.fork_exec( args, executable_list, close_fds, cwd, env_list, Modified: python/branches/py3k/Lib/test/test_os.py ============================================================================== --- python/branches/py3k/Lib/test/test_os.py (original) +++ python/branches/py3k/Lib/test/test_os.py Tue May 18 19:17:23 2010 @@ -370,7 +370,7 @@ def setUp(self): self.__save = dict(os.environ) - if os.name not in ('os2', 'nt'): + if os.supports_bytes_environ: self.__saveb = dict(os.environb) for key, value in self._reference().items(): os.environ[key] = value @@ -378,7 +378,7 @@ def tearDown(self): os.environ.clear() os.environ.update(self.__save) - if os.name not in ('os2', 'nt'): + if os.supports_bytes_environ: os.environb.clear() os.environb.update(self.__saveb) @@ -445,7 +445,21 @@ # Supplied PATH environment variable self.assertSequenceEqual(test_path, os.get_exec_path(test_env)) - @unittest.skipIf(sys.platform == "win32", "POSIX specific test") + if os.supports_bytes_environ: + # env cannot contain 'PATH' and b'PATH' keys + self.assertRaises(ValueError, + os.get_exec_path, {'PATH': '1', b'PATH': b'2'}) + + # bytes key and/or value + self.assertSequenceEqual(os.get_exec_path({b'PATH': b'abc'}), + ['abc']) + self.assertSequenceEqual(os.get_exec_path({b'PATH': 'abc'}), + ['abc']) + self.assertSequenceEqual(os.get_exec_path({'PATH': b'abc'}), + ['abc']) + + @unittest.skipUnless(os.supports_bytes_environ, + "os.environb required for this test.") def test_environb(self): # os.environ -> os.environb value = 'euro\u20ac' @@ -669,22 +683,54 @@ @unittest.skipUnless(hasattr(os, '_execvpe'), "No internal os._execvpe function to test.") - def test_internal_execvpe(self): - program_path = os.sep+'absolutepath' - program = 'executable' - fullpath = os.path.join(program_path, program) - arguments = ['progname', 'arg1', 'arg2'] + def _test_internal_execvpe(self, test_type): + program_path = os.sep + 'absolutepath' + if test_type is bytes: + program = b'executable' + fullpath = os.path.join(os.fsencode(program_path), program) + native_fullpath = fullpath + arguments = [b'progname', 'arg1', 'arg2'] + else: + program = 'executable' + arguments = ['progname', 'arg1', 'arg2'] + fullpath = os.path.join(program_path, program) + if os.name != "nt": + native_fullpath = os.fsencode(fullpath) + else: + native_fullpath = fullpath env = {'spam': 'beans'} + # test os._execvpe() with an absolute path with _execvpe_mockup() as calls: - self.assertRaises(RuntimeError, os._execvpe, fullpath, arguments) + self.assertRaises(RuntimeError, + os._execvpe, fullpath, arguments) self.assertEqual(len(calls), 1) self.assertEqual(calls[0], ('execv', fullpath, (arguments,))) + # test os._execvpe() with a relative path: + # os.get_exec_path() returns defpath with _execvpe_mockup(defpath=program_path) as calls: - self.assertRaises(OSError, os._execvpe, program, arguments, env=env) + self.assertRaises(OSError, + os._execvpe, program, arguments, env=env) self.assertEqual(len(calls), 1) - self.assertEqual(calls[0], ('execve', fullpath, (arguments, env))) + self.assertSequenceEqual(calls[0], + ('execve', native_fullpath, (arguments, env))) + + # test os._execvpe() with a relative path: + # os.get_exec_path() reads the 'PATH' variable + with _execvpe_mockup() as calls: + env_path = env.copy() + env_path['PATH'] = program_path + self.assertRaises(OSError, + os._execvpe, program, arguments, env=env_path) + self.assertEqual(len(calls), 1) + self.assertSequenceEqual(calls[0], + ('execve', native_fullpath, (arguments, env_path))) + + def test_internal_execvpe_str(self): + self._test_internal_execvpe(str) + if os.name != "nt": + self._test_internal_execvpe(bytes) class Win32ErrorTests(unittest.TestCase): Modified: python/branches/py3k/Lib/test/test_subprocess.py ============================================================================== --- python/branches/py3k/Lib/test/test_subprocess.py (original) +++ python/branches/py3k/Lib/test/test_subprocess.py Tue May 18 19:17:23 2010 @@ -825,6 +825,27 @@ stdout = stdout.rstrip(b'\n\r') self.assertEquals(stdout.decode('ascii'), repr(value)) + def test_bytes_program(self): + abs_program = os.fsencode(sys.executable) + path, program = os.path.split(sys.executable) + program = os.fsencode(program) + + # absolute bytes path + exitcode = subprocess.call([abs_program, "-c", "pass"]) + self.assertEquals(exitcode, 0) + + # bytes program, unicode PATH + env = os.environ.copy() + env["PATH"] = path + exitcode = subprocess.call([program, "-c", "pass"], env=env) + self.assertEquals(exitcode, 0) + + # bytes program, bytes PATH + envb = os.environb.copy() + envb[b"PATH"] = os.fsencode(path) + exitcode = subprocess.call([program, "-c", "pass"], env=envb) + self.assertEquals(exitcode, 0) + @unittest.skipUnless(mswindows, "Windows specific tests") class Win32ProcessTestCase(BaseTestCase): Modified: python/branches/py3k/Misc/NEWS ============================================================================== --- python/branches/py3k/Misc/NEWS (original) +++ python/branches/py3k/Misc/NEWS Tue May 18 19:17:23 2010 @@ -366,6 +366,11 @@ Library ------- +- Issue #8513: os.get_exec_path() supports b'PATH' key and bytes value. + subprocess.Popen() and os._execvpe() support bytes program name. Add + os.supports_bytes_environ flag: True if the native OS type of the environment + is bytes (eg. False on Windows). + - Issue #8633: tarfile is now able to read and write archives with "raw" binary pax headers as described in POSIX.1-2008. From python-checkins at python.org Tue May 18 19:24:09 2010 From: python-checkins at python.org (victor.stinner) Date: Tue, 18 May 2010 19:24:09 +0200 (CEST) Subject: [Python-checkins] r81292 - python/branches/py3k/Doc/library/os.rst Message-ID: <20100518172409.38B5DEE9C7@mail.python.org> Author: victor.stinner Date: Tue May 18 19:24:09 2010 New Revision: 81292 Log: Add versionadded (3.2) tag to os.supports_bytes_environ documentation Modified: python/branches/py3k/Doc/library/os.rst Modified: python/branches/py3k/Doc/library/os.rst ============================================================================== --- python/branches/py3k/Doc/library/os.rst (original) +++ python/branches/py3k/Doc/library/os.rst Tue May 18 19:24:09 2010 @@ -463,6 +463,8 @@ True if the native OS type of the environment is bytes (eg. False on Windows). + .. versionadded:: 3.2 + .. function:: umask(mask) From python-checkins at python.org Tue May 18 19:58:31 2010 From: python-checkins at python.org (collin.winter) Date: Tue, 18 May 2010 19:58:31 +0200 (CEST) Subject: [Python-checkins] r81293 - in python/branches/py3k-jit: Doc/c-api/list.rst Doc/c-api/unicode.rst Doc/distutils/sourcedist.rst Doc/howto/cporting.rst Doc/library/imp.rst Doc/library/pkgutil.rst Doc/library/runpy.rst Doc/library/ssl.rst Doc/library/sys.rst Doc/library/tarfile.rst Doc/library/wsgiref.rst Doc/library/zipimport.rst Include/unicodeobject.h Lib/distutils/command/sdist.py Lib/distutils/tests/test_sdist.py Lib/ssl.py Lib/subprocess.py Lib/tarfile.py Lib/test/capath Lib/test/list_tests.py Lib/test/test_capi.py Lib/test/test_import.py Lib/test/test_math.py Lib/test/test_os.py Lib/test/test_signal.py Lib/test/test_site.py Lib/test/test_ssl.py Lib/test/test_sys.py Lib/test/test_tarfile.py Lib/test/testtar.tar Lib/urllib/parse.py Lib/urllib/request.py Makefile.pre.in Misc/NEWS Modules/_cursesmodule.c Modules/_io/fileio.c Modules/_ssl.c Modules/_testcapimodule.c Modules/_tkinter.c Modules/grpmodule.c Modules/main.c Modules/mathmodule.c Modules/posixmodule.c Modules/pwdmodule.c Modules/spwdmodule.c Objects/object.c Objects/unicodeobject.c Parser/printgrammar.c Python/bltinmodule.c Python/graminit.c Python/import.c Python/pythonrun.c Message-ID: <20100518175831.54F4AC97C@mail.python.org> Author: collin.winter Date: Tue May 18 19:58:30 2010 New Revision: 81293 Log: Merged revisions 81146,81153,81155-81156,81165,81168,81170,81181,81183,81188,81190,81192,81194,81196-81199,81201,81204,81207,81209,81211,81214-81215,81218-81219,81222,81226,81231,81233-81237,81239,81242,81246-81247,81249-81253,81257-81258,81263,81266-81267,81269-81273,81276 via svnmerge from svn+ssh://pythondev at svn.python.org/python/branches/py3k ................ r81146 | benjamin.peterson | 2010-05-13 14:16:51 -0700 (Thu, 13 May 2010) | 9 lines Merged revisions 81145 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r81145 | benjamin.peterson | 2010-05-13 16:14:10 -0500 (Thu, 13 May 2010) | 1 line rip out mention of types.ListType #8703 ........ ................ r81153 | brett.cannon | 2010-05-13 17:04:56 -0700 (Thu, 13 May 2010) | 10 lines Merged revisions 81152 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r81152 | brett.cannon | 2010-05-13 16:59:41 -0700 (Thu, 13 May 2010) | 3 lines test_site was failing under darwin for non-framework builds because a test was assuming framework-specific site-packages directories were being used. ........ ................ r81155 | brett.cannon | 2010-05-13 17:33:40 -0700 (Thu, 13 May 2010) | 22 lines Merged revisions 81154 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r81154 | brett.cannon | 2010-05-13 17:21:48 -0700 (Thu, 13 May 2010) | 15 lines subprocess.Popen.__del__ referenced global objects, which is a no-no thanks to interpreter shutdown semantics. Same issue goes for the methods that __del__ called. Now all the methods capture the global objects it needs as default values to private parameters (could have stuck them on the class object itself, but since the objects have nothing directly to do with the class that seemed wrong). There is no test as making one that works is hard. This patch was verified against a consistently failing test in Mercurial's test suite, though, so it has been tested in some regard. Closes issue #5099. Thanks to Mary Stern for the bug report and Gabriel Genellina for writing another patch for the same issue and attempting to write a test. ........ ................ r81156 | victor.stinner | 2010-05-13 17:59:09 -0700 (Thu, 13 May 2010) | 5 lines Issue #4653: fix typo in flush_std_files() Don't call sys.stderr.flush() if sys has no stderr attribute or if sys.stderr==None. ................ r81165 | victor.stinner | 2010-05-14 07:36:18 -0700 (Fri, 14 May 2010) | 9 lines Merged revisions 81163 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r81163 | victor.stinner | 2010-05-14 16:20:07 +0200 (ven., 14 mai 2010) | 2 lines Doc: replace PEP xxx by :pep:`xxx` to create a link on the PEP ........ ................ r81168 | victor.stinner | 2010-05-14 08:58:55 -0700 (Fri, 14 May 2010) | 10 lines Issue #8711: Document PyUnicode_DecodeFSDefault*() functions * Add paragraph titles to c-api/unicode.rst. * Fix PyUnicode_DecodeFSDefault*() comment: it now uses the "surrogateescape" error handler (and not "replace") * Remove "The function is intended to be used for paths and file names only during bootstrapping process where the codecs are not set up." from PyUnicode_FSConverter() comment: it is used after the bootstrapping and for other purposes than file names ................ r81170 | victor.stinner | 2010-05-14 09:35:39 -0700 (Fri, 14 May 2010) | 6 lines posix_listdir(), posix_readlink(): avoid temporary PyBytes object Use directly PyUnicode_DecodeFSDefaultAndSize() instead of PyBytes_FromStringAndSize() + PyUnicode_FromEncodedObject() if the argument is unicode. ................ r81181 | victor.stinner | 2010-05-14 14:53:45 -0700 (Fri, 14 May 2010) | 9 lines Merged revisions 81179 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r81179 | victor.stinner | 2010-05-14 23:52:26 +0200 (ven., 14 mai 2010) | 2 lines Fix regression introduced by r81154 (Issue #5099, subprocess destructor) ........ ................ r81183 | victor.stinner | 2010-05-14 18:40:41 -0700 (Fri, 14 May 2010) | 4 lines Fix test_capi for Windows: strip newline characters Fix test_no_FatalError_infinite_loop() introduced by r81142 (issue #3605). ................ r81188 | stefan.krah | 2010-05-15 02:41:27 -0700 (Sat, 15 May 2010) | 10 lines Merged revisions 81185 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r81185 | stefan.krah | 2010-05-15 11:31:08 +0200 (Sat, 15 May 2010) | 4 lines If the timeout is exceeded, count the tests as skipped instead of just issuing a warning. ........ ................ r81190 | victor.stinner | 2010-05-15 05:27:16 -0700 (Sat, 15 May 2010) | 4 lines Issue #8610: Load file system codec at startup, and display a fatal error on failure. Set the file system encoding to utf-8 (instead of None) if getting the locale encoding failed, or if nl_langinfo(CODESET) function is missing. ................ r81192 | victor.stinner | 2010-05-15 06:14:32 -0700 (Sat, 15 May 2010) | 3 lines Enable shortcuts for common encodings in PyUnicode_AsEncodedString() for any error handler, not only the default error handler (strict) ................ r81194 | victor.stinner | 2010-05-15 09:27:27 -0700 (Sat, 15 May 2010) | 5 lines Issue #8715: Create PyUnicode_EncodeFSDefault() function: Encode a Unicode object to Py_FileSystemDefaultEncoding with the "surrogateescape" error handler, return a bytes object. If Py_FileSystemDefaultEncoding is not set, fall back to UTF-8. ................ r81196 | mark.dickinson | 2010-05-15 10:02:38 -0700 (Sat, 15 May 2010) | 13 lines Issue #8692: Improve performance of math.factorial: (1) use a different algorithm that roughly halves the total number of multiplications required and results in more balanced multiplications (2) use a lookup table for small arguments (3) fast accumulation of products in C integer arithmetic rather than PyLong arithmetic when possible. Typical speedup, from unscientific testing on a 64-bit laptop, is 4.5x to 6.5x for arguments in the range 100 - 10000. Patch by Daniel Stutzbach; extensive reviews by Alexander Belopolsky. ................ r81197 | benjamin.peterson | 2010-05-15 10:42:02 -0700 (Sat, 15 May 2010) | 1 line fix run-on sentence ................ r81198 | benjamin.peterson | 2010-05-15 10:43:18 -0700 (Sat, 15 May 2010) | 1 line rephrase ................ r81199 | benjamin.peterson | 2010-05-15 10:43:57 -0700 (Sat, 15 May 2010) | 1 line fix one more runon ................ r81201 | benjamin.peterson | 2010-05-15 10:52:12 -0700 (Sat, 15 May 2010) | 9 lines Merged revisions 81200 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r81200 | benjamin.peterson | 2010-05-15 12:48:55 -0500 (Sat, 15 May 2010) | 1 line use TestCase skip method ........ ................ r81204 | amaury.forgeotdarc | 2010-05-15 13:35:12 -0700 (Sat, 15 May 2010) | 2 lines Remove unused variable, and fix a compilation warning on Windows. ................ r81207 | victor.stinner | 2010-05-15 14:04:43 -0700 (Sat, 15 May 2010) | 9 lines Recorded merge of revisions 81205 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r81205 | victor.stinner | 2010-05-15 23:00:59 +0200 (sam., 15 mai 2010) | 2 lines NEWS: strip trailing spaces ........ ................ r81209 | antoine.pitrou | 2010-05-15 14:34:27 -0700 (Sat, 15 May 2010) | 3 lines Issue #8665: Fix `make pycremoval` exiting with non-zero status. ................ r81211 | amaury.forgeotdarc | 2010-05-15 14:49:45 -0700 (Sat, 15 May 2010) | 8 lines Blocked revisions 81210 via svnmerge ........ r81210 | amaury.forgeotdarc | 2010-05-15 23:45:30 +0200 (sam., 15 mai 2010) | 2 lines Remove unused variable, and fix a compilation warning on Windows ........ ................ r81214 | brett.cannon | 2010-05-15 15:20:16 -0700 (Sat, 15 May 2010) | 2 lines A test was not guaranteeing cleanup in the face of an exception. ................ r81215 | victor.stinner | 2010-05-15 15:23:53 -0700 (Sat, 15 May 2010) | 12 lines Recorded merge of revisions 81213 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r81213 | victor.stinner | 2010-05-16 00:19:27 +0200 (dim., 16 mai 2010) | 5 lines reindent _cursesmodule.c Use untabify.py + emacs (python3 mode) + manual editions for Py_BEGIN_ALLOW_THREADS / Py_END_ALLOW_THREADS ........ ................ r81218 | brett.cannon | 2010-05-15 15:51:45 -0700 (Sat, 15 May 2010) | 1 line Fix a comment to state the right thing. ................ r81219 | brett.cannon | 2010-05-15 15:53:24 -0700 (Sat, 15 May 2010) | 4 lines Make test_module_with_large_stack as an expected failure because of a change in importlib that is causing it to fail. Work to fix it is being tracked in issue 8727. ................ r81222 | victor.stinner | 2010-05-15 16:00:51 -0700 (Sat, 15 May 2010) | 11 lines Merged revisions 81220 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r81220 | victor.stinner | 2010-05-16 00:55:28 +0200 (dim., 16 mai 2010) | 4 lines Use 4-spaces for indentation (instead of tabs) in pgen outputs Regenerate (reindent) Python/graminit.c ........ ................ r81226 | victor.stinner | 2010-05-15 17:36:38 -0700 (Sat, 15 May 2010) | 11 lines Merged revisions 81224 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r81224 | victor.stinner | 2010-05-16 02:34:40 +0200 (dim., 16 mai 2010) | 4 lines Use with open() as fo: ... instead of try: fo = open(...) finally: fo.close() fo is not set if the open() fails. ........ ................ r81231 | antoine.pitrou | 2010-05-16 07:19:41 -0700 (Sun, 16 May 2010) | 9 lines Merged revisions 81229 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r81229 | antoine.pitrou | 2010-05-16 16:16:56 +0200 (dim., 16 mai 2010) | 3 lines Document that SSL v2 is insecure. ........ ................ r81233 | antoine.pitrou | 2010-05-16 11:19:27 -0700 (Sun, 16 May 2010) | 3 lines Issue #8550: Add first class `SSLContext` objects to the ssl module. ................ r81234 | antoine.pitrou | 2010-05-16 12:22:44 -0700 (Sun, 16 May 2010) | 3 lines Followup on r81233: fix test_ssl with OpenSSL < 1.0.0. ................ r81235 | antoine.pitrou | 2010-05-16 12:56:32 -0700 (Sun, 16 May 2010) | 3 lines Fix (hopefully) the remaining test_ssl buildbot failures ................ r81236 | antoine.pitrou | 2010-05-16 13:35:03 -0700 (Sun, 16 May 2010) | 3 lines Do not fail if ssl fails to import ................ r81237 | victor.stinner | 2010-05-16 14:23:48 -0700 (Sun, 16 May 2010) | 3 lines Issue #8477: _ssl._test_decode_cert() supports str with surrogates and bytes for the filename ................ r81239 | victor.stinner | 2010-05-16 14:36:37 -0700 (Sun, 16 May 2010) | 2 lines Issue #8477: ssl.RAND_egd() supports str with surrogates and bytes for the path ................ r81242 | antoine.pitrou | 2010-05-16 16:14:22 -0700 (Sun, 16 May 2010) | 10 lines Merged revisions 81241 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r81241 | antoine.pitrou | 2010-05-17 01:11:46 +0200 (lun., 17 mai 2010) | 4 lines Clear the OpenSSL error queue each time an error is signalled. When the error queue is not emptied, strange things can happen on the next SSL call, depending on the OpenSSL version. ........ ................ r81246 | antoine.pitrou | 2010-05-16 16:46:26 -0700 (Sun, 16 May 2010) | 3 lines "xyzzy" is not a silly enough name for some OpenSSL versions to report an error ................ r81247 | victor.stinner | 2010-05-16 17:14:53 -0700 (Sun, 16 May 2010) | 9 lines test_os: cleanup test_internal_execvpe() and os._execvpe() mockup * Replace os.defpath instead of os.get_exec_path() to test also os.get_exec_path() * Use contextlib.contextmanager, move the mockup outside the class, and the mockup returns directly the call list object * Use two different contexts for the two tests * Use more revelant values and names ................ r81249 | victor.stinner | 2010-05-16 17:18:34 -0700 (Sun, 16 May 2010) | 2 lines Oops, my patch on subprocess is not merged yet: fix my previous commit on test_os ................ r81250 | victor.stinner | 2010-05-16 18:13:37 -0700 (Sun, 16 May 2010) | 2 lines Issue #6697: Fix a crash if code of "python -c code" contains surrogates ................ r81251 | victor.stinner | 2010-05-16 18:26:01 -0700 (Sun, 16 May 2010) | 3 lines PyObject_Dump() encodes unicode objects to utf8 with backslashreplace (instead of strict) error handler to escape surrogates ................ r81252 | victor.stinner | 2010-05-17 01:58:51 -0700 (Mon, 17 May 2010) | 6 lines handle_system_exit() flushs files to warranty the output order PyObject_Print() writes into the C object stderr, whereas PySys_WriteStderr() writes into the Python object sys.stderr. Each object has its own buffer, so call sys.stderr.flush() and fflush(stderr). ................ r81253 | victor.stinner | 2010-05-17 02:33:42 -0700 (Mon, 17 May 2010) | 6 lines Fix refleak in internal_print() introduced by myself in r81251 _PyUnicode_AsDefaultEncodedString() uses a magical PyUnicode attribute to automatically destroy PyUnicode_EncodeUTF8() result when the unicode string is destroyed. ................ r81257 | antoine.pitrou | 2010-05-17 03:30:00 -0700 (Mon, 17 May 2010) | 3 lines Try to fix buildbot failures with old OpenSSLs. ................ r81258 | tarek.ziade | 2010-05-17 03:38:53 -0700 (Mon, 17 May 2010) | 9 lines Merged revisions 81255 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r81255 | tarek.ziade | 2010-05-17 12:06:20 +0200 (Mon, 17 May 2010) | 1 line Fixed #8688: Distutils now recalculates MANIFEST everytime. ........ ................ r81263 | tarek.ziade | 2010-05-17 04:01:57 -0700 (Mon, 17 May 2010) | 9 lines Merged revisions 81261 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r81261 | tarek.ziade | 2010-05-17 12:54:43 +0200 (Mon, 17 May 2010) | 1 line upgraded distutils docs w.r.t. the manifest regeneration ........ ................ r81266 | antoine.pitrou | 2010-05-17 07:13:10 -0700 (Mon, 17 May 2010) | 3 lines Typo (thanks Arfrever) ................ r81267 | victor.stinner | 2010-05-17 07:36:43 -0700 (Mon, 17 May 2010) | 2 lines Improve test_exit() error message to analyze sparc failures ................ r81269 | jeffrey.yasskin | 2010-05-17 09:59:23 -0700 (Mon, 17 May 2010) | 4 lines Fix test_capi in !pydebug mode, where my original attempt segfaulted without producing the expected error message. The test only tests what it's supposed to test in pydebug mode though. Fixes issue 8726. ................ r81270 | florent.xicluna | 2010-05-17 10:24:07 -0700 (Mon, 17 May 2010) | 9 lines Merged revision 81259 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r81259 | florent.xicluna | 2010-05-17 12:39:07 +0200 (lun, 17 mai 2010) | 2 lines Slight style cleanup. ........ ................ r81271 | florent.xicluna | 2010-05-17 10:33:07 -0700 (Mon, 17 May 2010) | 11 lines Issue #1285086: Speed up urllib.parse functions: quote, quote_from_bytes, unquote, unquote_to_bytes. Recorded merge of revisions 81265 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r81265 | florent.xicluna | 2010-05-17 15:35:09 +0200 (lun, 17 mai 2010) | 2 lines Issue #1285086: Speed up urllib.quote and urllib.unquote for simple cases. ........ ................ r81272 | florent.xicluna | 2010-05-17 11:01:22 -0700 (Mon, 17 May 2010) | 2 lines Inadvertently removed part of the comment in r81271. ................ r81273 | lars.gustaebel | 2010-05-17 11:02:50 -0700 (Mon, 17 May 2010) | 15 lines Issue #8633: Support for POSIX.1-2008 binary pax headers. tarfile is now able to read and write pax headers with a "hdrcharset=BINARY" record. This record was introduced in POSIX.1-2008 as a method to store unencoded binary strings that cannot be translated to UTF-8. In practice, this is just a workaround that allows a tar implementation to store filenames that do not comply with the current filesystem encoding and thus cannot be decoded correctly. Additionally, tarfile works around a bug in current versions of GNU tar: undecodable filenames are stored as-is in a pax header without a "hdrcharset" record being added. Technically, these headers are invalid, but tarfile manages to read them correctly anyway. ................ r81276 | victor.stinner | 2010-05-17 12:57:40 -0700 (Mon, 17 May 2010) | 4 lines Fix test_main_invalid_unicode() of test_sys for ASCII locale encoding It should fix sparc 3.x and 3.1 failures. ................ Added: python/branches/py3k-jit/Lib/test/capath/ - copied from r81276, /python/branches/py3k/Lib/test/capath/ Modified: python/branches/py3k-jit/ (props changed) python/branches/py3k-jit/Doc/c-api/list.rst python/branches/py3k-jit/Doc/c-api/unicode.rst python/branches/py3k-jit/Doc/distutils/sourcedist.rst python/branches/py3k-jit/Doc/howto/cporting.rst python/branches/py3k-jit/Doc/library/imp.rst python/branches/py3k-jit/Doc/library/pkgutil.rst python/branches/py3k-jit/Doc/library/runpy.rst python/branches/py3k-jit/Doc/library/ssl.rst python/branches/py3k-jit/Doc/library/sys.rst python/branches/py3k-jit/Doc/library/tarfile.rst python/branches/py3k-jit/Doc/library/wsgiref.rst python/branches/py3k-jit/Doc/library/zipimport.rst python/branches/py3k-jit/Include/unicodeobject.h python/branches/py3k-jit/Lib/distutils/command/sdist.py python/branches/py3k-jit/Lib/distutils/tests/test_sdist.py python/branches/py3k-jit/Lib/ssl.py python/branches/py3k-jit/Lib/subprocess.py python/branches/py3k-jit/Lib/tarfile.py python/branches/py3k-jit/Lib/test/list_tests.py python/branches/py3k-jit/Lib/test/test_capi.py python/branches/py3k-jit/Lib/test/test_import.py python/branches/py3k-jit/Lib/test/test_math.py python/branches/py3k-jit/Lib/test/test_os.py python/branches/py3k-jit/Lib/test/test_signal.py python/branches/py3k-jit/Lib/test/test_site.py python/branches/py3k-jit/Lib/test/test_ssl.py python/branches/py3k-jit/Lib/test/test_sys.py python/branches/py3k-jit/Lib/test/test_tarfile.py python/branches/py3k-jit/Lib/test/testtar.tar python/branches/py3k-jit/Lib/urllib/parse.py python/branches/py3k-jit/Lib/urllib/request.py python/branches/py3k-jit/Makefile.pre.in python/branches/py3k-jit/Misc/NEWS python/branches/py3k-jit/Modules/_cursesmodule.c python/branches/py3k-jit/Modules/_io/fileio.c python/branches/py3k-jit/Modules/_ssl.c python/branches/py3k-jit/Modules/_testcapimodule.c python/branches/py3k-jit/Modules/_tkinter.c python/branches/py3k-jit/Modules/grpmodule.c python/branches/py3k-jit/Modules/main.c python/branches/py3k-jit/Modules/mathmodule.c python/branches/py3k-jit/Modules/posixmodule.c python/branches/py3k-jit/Modules/pwdmodule.c python/branches/py3k-jit/Modules/spwdmodule.c python/branches/py3k-jit/Objects/object.c python/branches/py3k-jit/Objects/unicodeobject.c python/branches/py3k-jit/Parser/printgrammar.c python/branches/py3k-jit/Python/bltinmodule.c python/branches/py3k-jit/Python/graminit.c python/branches/py3k-jit/Python/import.c python/branches/py3k-jit/Python/pythonrun.c Modified: python/branches/py3k-jit/Doc/c-api/list.rst ============================================================================== --- python/branches/py3k-jit/Doc/c-api/list.rst (original) +++ python/branches/py3k-jit/Doc/c-api/list.rst Tue May 18 19:58:30 2010 @@ -15,11 +15,8 @@ .. cvar:: PyTypeObject PyList_Type - .. index:: single: ListType (in module types) - - This instance of :ctype:`PyTypeObject` represents the Python list type. - This is the same object as ``list`` and ``types.ListType`` in the Python - layer. + This instance of :ctype:`PyTypeObject` represents the Python list type. This + is the same object as ``list`` in the Python layer. .. cfunction:: int PyList_Check(PyObject *p) Modified: python/branches/py3k-jit/Doc/c-api/unicode.rst ============================================================================== --- python/branches/py3k-jit/Doc/c-api/unicode.rst (original) +++ python/branches/py3k-jit/Doc/c-api/unicode.rst Tue May 18 19:58:30 2010 @@ -10,11 +10,12 @@ Unicode Objects ^^^^^^^^^^^^^^^ +Unicode Type +"""""""""""" + These are the basic Unicode object types used for the Unicode implementation in Python: -.. % --- Unicode Type ------------------------------------------------------- - .. ctype:: Py_UNICODE @@ -89,12 +90,13 @@ Clear the free list. Return the total number of freed items. +Unicode Character Properties +"""""""""""""""""""""""""""" + Unicode provides many different character properties. The most often needed ones are available through these macros which are mapped to C functions depending on the Python configuration. -.. % --- Unicode character properties --------------------------------------- - .. cfunction:: int Py_UNICODE_ISSPACE(Py_UNICODE ch) @@ -192,11 +194,13 @@ Return the character *ch* converted to a double. Return ``-1.0`` if this is not possible. This macro does not raise exceptions. + +Plain Py_UNICODE +"""""""""""""""" + To create Unicode objects and access their basic sequence properties, use these APIs: -.. % --- Plain Py_UNICODE --------------------------------------------------- - .. cfunction:: PyObject* PyUnicode_FromUnicode(const Py_UNICODE *u, Py_ssize_t size) @@ -364,8 +368,57 @@ Support is optimized if Python's own :ctype:`Py_UNICODE` type is identical to the system's :ctype:`wchar_t`. -.. % --- wchar_t support for platforms which support it --------------------- +File System Encoding +"""""""""""""""""""" + +To encode and decode file names and other environment strings, +:cdata:`Py_FileSystemEncoding` should be used as the encoding, and +``"surrogateescape"`` should be used as the error handler (:pep:`383`). To +encode file names during argument parsing, the ``"O&"`` converter should be +used, passsing :func:PyUnicode_FSConverter as the conversion function: + +.. cfunction:: int PyUnicode_FSConverter(PyObject* obj, void* result) + + Convert *obj* into *result*, using :cdata:`Py_FileSystemDefaultEncoding`, + and the ``"surrogateescape"`` error handler. *result* must be a + ``PyObject*``, return a :func:`bytes` object which must be released if it + is no longer used. + + .. versionadded:: 3.1 + +.. cfunction:: PyObject* PyUnicode_DecodeFSDefaultAndSize(const char *s, Py_ssize_t size) + + Decode a null-terminated string using :cdata:`Py_FileSystemDefaultEncoding` + and the ``"surrogateescape"`` error handler. + + If :cdata:`Py_FileSystemDefaultEncoding` is not set, fall back to UTF-8. + + Use :func:`PyUnicode_DecodeFSDefaultAndSize` if you know the string length. + + +.. cfunction:: PyObject* PyUnicode_DecodeFSDefault(const char *s) + + Decode a string using :cdata:`Py_FileSystemDefaultEncoding` and + the ``"surrogateescape"`` error handler. + + If :cdata:`Py_FileSystemDefaultEncoding` is not set, fall back to UTF-8. + + +.. cfunction:: PyObject* PyUnicode_EncodeFSDefault(PyObject *unicode) + + Encode a Unicode object to :cdata:`Py_FileSystemDefaultEncoding` with the + ``'surrogateescape'`` error handler, and return :class:`bytes`. + + If :cdata:`Py_FileSystemDefaultEncoding` is not set, fall back to UTF-8. + + .. versionadded:: 3.2 + + +wchar_t Support +""""""""""""""" + +wchar_t support for platforms which support it: .. cfunction:: PyObject* PyUnicode_FromWideChar(const wchar_t *w, Py_ssize_t size) @@ -413,9 +466,11 @@ The codecs all use a similar interface. Only deviation from the following generic ones are documented for simplicity. -These are the generic codec APIs: -.. % --- Generic Codecs ----------------------------------------------------- +Generic Codecs +"""""""""""""" + +These are the generic codec APIs: .. cfunction:: PyObject* PyUnicode_Decode(const char *s, Py_ssize_t size, const char *encoding, const char *errors) @@ -444,9 +499,11 @@ using the Python codec registry. Return *NULL* if an exception was raised by the codec. -These are the UTF-8 codec APIs: -.. % --- UTF-8 Codecs ------------------------------------------------------- +UTF-8 Codecs +"""""""""""" + +These are the UTF-8 codec APIs: .. cfunction:: PyObject* PyUnicode_DecodeUTF8(const char *s, Py_ssize_t size, const char *errors) @@ -476,9 +533,11 @@ object. Error handling is "strict". Return *NULL* if an exception was raised by the codec. -These are the UTF-32 codec APIs: -.. % --- UTF-32 Codecs ------------------------------------------------------ */ +UTF-32 Codecs +""""""""""""" + +These are the UTF-32 codec APIs: .. cfunction:: PyObject* PyUnicode_DecodeUTF32(const char *s, Py_ssize_t size, const char *errors, int *byteorder) @@ -543,9 +602,10 @@ Return *NULL* if an exception was raised by the codec. -These are the UTF-16 codec APIs: +UTF-16 Codecs +""""""""""""" -.. % --- UTF-16 Codecs ------------------------------------------------------ */ +These are the UTF-16 codec APIs: .. cfunction:: PyObject* PyUnicode_DecodeUTF16(const char *s, Py_ssize_t size, const char *errors, int *byteorder) @@ -609,9 +669,11 @@ order. The string always starts with a BOM mark. Error handling is "strict". Return *NULL* if an exception was raised by the codec. -These are the "Unicode Escape" codec APIs: -.. % --- Unicode-Escape Codecs ---------------------------------------------- +Unicode-Escape Codecs +""""""""""""""""""""" + +These are the "Unicode Escape" codec APIs: .. cfunction:: PyObject* PyUnicode_DecodeUnicodeEscape(const char *s, Py_ssize_t size, const char *errors) @@ -633,9 +695,11 @@ string object. Error handling is "strict". Return *NULL* if an exception was raised by the codec. -These are the "Raw Unicode Escape" codec APIs: -.. % --- Raw-Unicode-Escape Codecs ------------------------------------------ +Raw-Unicode-Escape Codecs +""""""""""""""""""""""""" + +These are the "Raw Unicode Escape" codec APIs: .. cfunction:: PyObject* PyUnicode_DecodeRawUnicodeEscape(const char *s, Py_ssize_t size, const char *errors) @@ -657,11 +721,13 @@ Python string object. Error handling is "strict". Return *NULL* if an exception was raised by the codec. + +Latin-1 Codecs +"""""""""""""" + These are the Latin-1 codec APIs: Latin-1 corresponds to the first 256 Unicode ordinals and only these are accepted by the codecs during encoding. -.. % --- Latin-1 Codecs ----------------------------------------------------- - .. cfunction:: PyObject* PyUnicode_DecodeLatin1(const char *s, Py_ssize_t size, const char *errors) @@ -682,11 +748,13 @@ object. Error handling is "strict". Return *NULL* if an exception was raised by the codec. + +ASCII Codecs +"""""""""""" + These are the ASCII codec APIs. Only 7-bit ASCII data is accepted. All other codes generate errors. -.. % --- ASCII Codecs ------------------------------------------------------- - .. cfunction:: PyObject* PyUnicode_DecodeASCII(const char *s, Py_ssize_t size, const char *errors) @@ -707,9 +775,11 @@ object. Error handling is "strict". Return *NULL* if an exception was raised by the codec. -These are the mapping codec APIs: -.. % --- Character Map Codecs ----------------------------------------------- +Character Map Codecs +"""""""""""""""""""" + +These are the mapping codec APIs: This codec is special in that it can be used to implement many different codecs (and this is in fact what was done to obtain most of the standard codecs @@ -778,7 +848,9 @@ DBCS) is a class of encodings, not just one. The target encoding is defined by the user settings on the machine running the codec. -.. % --- MBCS codecs for Windows -------------------------------------------- + +MBCS codecs for Windows +""""""""""""""""""""""" .. cfunction:: PyObject* PyUnicode_DecodeMBCS(const char *s, Py_ssize_t size, const char *errors) @@ -808,20 +880,9 @@ object. Error handling is "strict". Return *NULL* if an exception was raised by the codec. -For decoding file names and other environment strings, :cdata:`Py_FileSystemEncoding` -should be used as the encoding, and ``"surrogateescape"`` should be used as the error -handler. For encoding file names during argument parsing, the ``O&`` converter should -be used, passsing PyUnicode_FSConverter as the conversion function: - -.. cfunction:: int PyUnicode_FSConverter(PyObject* obj, void* result) - - Convert *obj* into *result*, using the file system encoding, and the ``surrogateescape`` - error handler. *result* must be a ``PyObject*``, yielding a bytes or bytearray object - which must be released if it is no longer used. - - .. versionadded:: 3.1 -.. % --- Methods & Slots ---------------------------------------------------- +Methods & Slots +""""""""""""""" .. _unicodemethodsandslots: Modified: python/branches/py3k-jit/Doc/distutils/sourcedist.rst ============================================================================== --- python/branches/py3k-jit/Doc/distutils/sourcedist.rst (original) +++ python/branches/py3k-jit/Doc/distutils/sourcedist.rst Tue May 18 19:58:30 2010 @@ -137,20 +137,12 @@ :option:`--no-defaults` and :option:`--no-prune` to disable the standard "include" and "exclude" sets. -Second, you might want to force the manifest to be regenerated---for example, if -you have added or removed files or directories that match an existing pattern in -the manifest template, you should regenerate the manifest:: - - python setup.py sdist --force-manifest - -Or, you might just want to (re)generate the manifest, but not create a source -distribution:: +Second, you might just want to (re)generate the manifest, but not create a +source distribution:: python setup.py sdist --manifest-only -:option:`--manifest-only` implies :option:`--force-manifest`. :option:`-o` is a -shortcut for :option:`--manifest-only`, and :option:`-f` for -:option:`--force-manifest`. +:option:`-o` is a sortcut for :option:`--manifest-only`. .. _manifest_template: Modified: python/branches/py3k-jit/Doc/howto/cporting.rst ============================================================================== --- python/branches/py3k-jit/Doc/howto/cporting.rst (original) +++ python/branches/py3k-jit/Doc/howto/cporting.rst Tue May 18 19:58:30 2010 @@ -120,7 +120,7 @@ Module initialization and state =============================== -Python 3.0 has a revamped extension module initialization system. (See PEP +Python 3.0 has a revamped extension module initialization system. (See :pep:`3121`.) Instead of storing module state in globals, they should be stored in an interpreter specific structure. Creating modules that act correctly in both 2.x and 3.0 is tricky. The following simple example demonstrates how. :: Modified: python/branches/py3k-jit/Doc/library/imp.rst ============================================================================== --- python/branches/py3k-jit/Doc/library/imp.rst (original) +++ python/branches/py3k-jit/Doc/library/imp.rst Tue May 18 19:58:30 2010 @@ -211,7 +211,7 @@ .. function:: cache_from_source(path, debug_override=None) - Return the PEP 3147 path to the byte-compiled file associated with the + Return the :pep:`3147` path to the byte-compiled file associated with the source *path*. For example, if *path* is ``/foo/bar/baz.py`` the return value would be ``/foo/bar/__pycache__/baz.cpython-32.pyc`` for Python 3.2. The ``cpython-32`` string comes from the current magic tag (see @@ -225,15 +225,15 @@ .. function:: source_from_cache(path) - Given the *path* to a PEP 3147 file name, return the associated source code + Given the *path* to a :pep:`3147` file name, return the associated source code file path. For example, if *path* is ``/foo/bar/__pycache__/baz.cpython-32.pyc`` the returned path would be ``/foo/bar/baz.py``. *path* need not exist, however if it does not conform - to PEP 3147 format, a ``ValueError`` is raised. + to :pep:`3147` format, a ``ValueError`` is raised. .. function:: get_tag() - Return the PEP 3147 magic tag string matching this version of Python's + Return the :pep:`3147` magic tag string matching this version of Python's magic number, as returned by :func:`get_magic`. Modified: python/branches/py3k-jit/Doc/library/pkgutil.rst ============================================================================== --- python/branches/py3k-jit/Doc/library/pkgutil.rst (original) +++ python/branches/py3k-jit/Doc/library/pkgutil.rst Tue May 18 19:58:30 2010 @@ -41,7 +41,7 @@ Get a resource from a package. - This is a wrapper for the PEP 302 loader :func:`get_data` API. The package + This is a wrapper for the :pep:`302` loader :func:`get_data` API. The package argument should be the name of a package, in standard module format (foo.bar). The resource argument should be in the form of a relative filename, using ``/`` as the path separator. The parent directory name @@ -56,5 +56,5 @@ d = os.path.dirname(sys.modules[package].__file__) data = open(os.path.join(d, resource), 'rb').read() - If the package cannot be located or loaded, or it uses a PEP 302 loader + If the package cannot be located or loaded, or it uses a :pep:`302` loader which does not support :func:`get_data`, then None is returned. Modified: python/branches/py3k-jit/Doc/library/runpy.rst ============================================================================== --- python/branches/py3k-jit/Doc/library/runpy.rst (original) +++ python/branches/py3k-jit/Doc/library/runpy.rst Tue May 18 19:58:30 2010 @@ -18,7 +18,7 @@ Execute the code of the specified module and return the resulting module globals dictionary. The module's code is first located using the standard - import mechanism (refer to PEP 302 for details) and then executed in a + import mechanism (refer to :pep:`302` for details) and then executed in a fresh module namespace. If the supplied module name refers to a package rather than a normal @@ -48,7 +48,7 @@ ``__cached__`` will be set to ``None``. - ``__loader__`` is set to the PEP 302 module loader used to retrieve the + ``__loader__`` is set to the :pep:`302` module loader used to retrieve the code for the module (This loader may be a wrapper around the standard import mechanism). @@ -106,7 +106,7 @@ loader does not make filename information available, this variable is set to :const:`None`. For a simple script, this will be set to ``file_path``. - ``__loader__`` is set to the PEP 302 module loader used to retrieve the + ``__loader__`` is set to the :pep:`302` module loader used to retrieve the code for the module (This loader may be a wrapper around the standard import mechanism). For a simple script, this will be set to :const:`None`. Modified: python/branches/py3k-jit/Doc/library/ssl.rst ============================================================================== --- python/branches/py3k-jit/Doc/library/ssl.rst (original) +++ python/branches/py3k-jit/Doc/library/ssl.rst Tue May 18 19:58:30 2010 @@ -36,6 +36,11 @@ connection, and a method, :meth:`cipher`, to retrieve the cipher being used for the secure connection. +For more sophisticated applications, the :class:`ssl.SSLContext` class +helps manage settings and certificates, which can then be inherited +by SSL sockets created through the :meth:`SSLContext.wrap_socket` method. + + Functions, Constants, and Exceptions ------------------------------------ @@ -64,19 +69,6 @@ connection. See the discussion of :ref:`ssl-certificates` for more information on how the certificate is stored in the ``certfile``. - Often the private key is stored in the same file as the certificate; in this - case, only the ``certfile`` parameter need be passed. If the private key is - stored in a separate file, both parameters must be used. If the private key - is stored in the ``certfile``, it should come before the first certificate in - the certificate chain:: - - -----BEGIN RSA PRIVATE KEY----- - ... (private key in base64 encoding) ... - -----END RSA PRIVATE KEY----- - -----BEGIN CERTIFICATE----- - ... (certificate in base64 PEM encoding) ... - -----END CERTIFICATE----- - The parameter ``server_side`` is a boolean which identifies whether server-side or client-side behavior is desired from this socket. @@ -208,29 +200,45 @@ .. data:: CERT_NONE - Value to pass to the ``cert_reqs`` parameter to :func:`sslobject` when no - certificates will be required or validated from the other side of the socket - connection. + Possible value for :attr:`SSLContext.verify_mode`, or the ``cert_reqs`` + parameter to :func:`wrap_socket`. In this mode (the default), no + certificates will be required from the other side of the socket connection. + If a certificate is received from the other end, no attempt to validate it + is made. + + See the discussion of :ref:`ssl-security` below. .. data:: CERT_OPTIONAL - Value to pass to the ``cert_reqs`` parameter to :func:`sslobject` when no - certificates will be required from the other side of the socket connection, - but if they are provided, will be validated. Note that use of this setting - requires a valid certificate validation file also be passed as a value of the - ``ca_certs`` parameter. + Possible value for :attr:`SSLContext.verify_mode`, or the ``cert_reqs`` + parameter to :func:`wrap_socket`. In this mode no certificates will be + required from the other side of the socket connection; but if they + are provided, validation will be attempted and an :class:`SSLError` + will be raised on failure. + + Use of this setting requires a valid set of CA certificates to + be passed, either to :meth:`SSLContext.load_verify_locations` or as a + value of the ``ca_certs`` parameter to :func:`wrap_socket`. .. data:: CERT_REQUIRED - Value to pass to the ``cert_reqs`` parameter to :func:`sslobject` when - certificates will be required from the other side of the socket connection. - Note that use of this setting requires a valid certificate validation file - also be passed as a value of the ``ca_certs`` parameter. + Possible value for :attr:`SSLContext.verify_mode`, or the ``cert_reqs`` + parameter to :func:`wrap_socket`. In this mode, certificates are + required from the other side of the socket connection; an :class:`SSLError` + will be raised if no certificate is provided, or if its validation fails. + + Use of this setting requires a valid set of CA certificates to + be passed, either to :meth:`SSLContext.load_verify_locations` or as a + value of the ``ca_certs`` parameter to :func:`wrap_socket`. .. data:: PROTOCOL_SSLv2 Selects SSL version 2 as the channel encryption protocol. + .. warning:: + + SSL version 2 is insecure. Its use is highly discouraged. + .. data:: PROTOCOL_SSLv23 Selects SSL version 2 or 3 as the channel encryption protocol. This is a @@ -280,8 +288,8 @@ .. versionadded:: 3.2 -SSLSocket Objects ------------------ +SSL Sockets +----------- .. method:: SSLSocket.read(nbytes=1024, buffer=None) @@ -367,6 +375,83 @@ returned socket should always be used for further communication with the other side of the connection, rather than the original socket. + +SSL Contexts +------------ + +.. class:: SSLContext(protocol) + + An object holding various data longer-lived than single SSL connections, + such as SSL configuration options, certificate(s) and private key(s). + You must pass *protocol* which must be one of the ``PROTOCOL_*`` constants + defined in this module. :data:`PROTOCOL_SSLv23` is recommended for + maximum interoperability. + +:class:`SSLContext` objects have the following methods and attributes: + +.. method:: SSLContext.load_cert_chain(certfile, keyfile=None) + + Load a private key and the corresponding certificate. The *certfile* + string must be the path to a single file in PEM format containing the + certificate as well as any number of CA certificates needed to establish + the certificate's authenticity. The *keyfile* string, if present, must + point to a file containing the private key in. Otherwise the private + key will be taken from *certfile* as well. See the discussion of + :ref:`ssl-certificates` for more information on how the certificate + is stored in the *certfile*. + + An :class:`SSLError` is raised if the private key doesn't + match with the certificate. + +.. method:: SSLContext.load_verify_locations(cafile=None, capath=None) + + Load a set of "certification authority" (CA) certificates used to validate + other peers' certificates when :data:`verify_mode` is other than + :data:`CERT_NONE`. At least one of *cafile* or *capath* must be specified. + + The *cafile* string, if present, is the path to a file of concatenated + CA certificates in PEM format. See the discussion of + :ref:`ssl-certificates` for more information about how to arrange the + certificates in this file. + + The *capath* string, if present, is + the path to a directory containing several CA certificates in PEM format, + following an `OpenSSL specific layout + `_. + +.. method:: SSLContext.set_ciphers(ciphers) + + 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. + + .. note:: + when connected, the :meth:`SSLSocket.cipher` method of SSL sockets will + give the currently selected cipher. + +.. method:: SSLContext.wrap_socket(sock, server_side=False, do_handshake_on_connect=True, suppress_ragged_eofs=True) + + Wrap an existing Python socket *sock* and return an :class:`SSLSocket` + object. The SSL socket is tied to the context, its settings and + certificates. The parameters *server_side*, *do_handshake_on_connect* + and *suppress_ragged_eofs* have the same meaning as in the top-level + :func:`wrap_socket` function. + +.. attribute:: SSLContext.protocol + + The protocol version chosen when constructing the context. This attribute + is read-only. + +.. attribute:: SSLContext.verify_mode + + Whether to try to verify other peers' certificates and how to behave + if verification fails. This attribute must be one of + :data:`CERT_NONE`, :data:`CERT_OPTIONAL` or :data:`CERT_REQUIRED`. + + .. index:: single: certificates .. index:: single: X509 certificate @@ -412,6 +497,9 @@ ... (certificate in base64 PEM encoding) ... -----END CERTIFICATE----- +Certificate chains +^^^^^^^^^^^^^^^^^^ + The Python files which contain certificates can contain a sequence of certificates, sometimes called a *certificate chain*. This chain should start with the specific certificate for the principal who "is" the client or server, @@ -435,6 +523,9 @@ ... (the root certificate for the CA's issuer)... -----END CERTIFICATE----- +CA certificates +^^^^^^^^^^^^^^^ + If you are going to require validation of the other side of the connection's certificate, you need to provide a "CA certs" file, filled with the certificate chains for each issuer you are willing to trust. Again, this file just contains @@ -454,6 +545,25 @@ certificate to a root certificate. See :rfc:`4158` for more discussion of the way in which certification chains can be built. +Combined key and certificate +^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +Often the private key is stored in the same file as the certificate; in this +case, only the ``certfile`` parameter to :meth:`SSLContext.load_cert_chain` +and :func:`wrap_socket` needs to be passed. If the private key is stored +with the certificate, it should come before the first certificate in +the certificate chain:: + + -----BEGIN RSA PRIVATE KEY----- + ... (private key in base64 encoding) ... + -----END RSA PRIVATE KEY----- + -----BEGIN CERTIFICATE----- + ... (certificate in base64 PEM encoding) ... + -----END CERTIFICATE----- + +Self-signed certificates +^^^^^^^^^^^^^^^^^^^^^^^^ + If you are going to create a server that provides SSL-encrypted connection services, you will need to acquire a certificate for that service. There are many ways of acquiring appropriate certificates, such as buying one from a @@ -526,8 +636,7 @@ print(pprint.pformat(ssl_sock.getpeercert())) # Set a simple HTTP request -- use http.client in actual code. - ssl_sock.write("""GET / HTTP/1.0\r - Host: www.verisign.com\r\n\r\n""") + ssl_sock.write(b"GET / HTTP/1.0\r\nHost: www.verisign.com\r\n\r\n") # Read a chunk of data. Will not necessarily # read all the data returned by the server. @@ -557,39 +666,91 @@ which is a fairly poorly-formed ``subject`` field. +This other example first creates an SSL context, instructs it to verify +certificates sent by peers, and feeds it a set of recognized certificate +authorities (CA):: + + >>> context = ssl.SSLContext(ssl.PROTOCOL_SSLv23) + >>> context.verify_mode = ssl.CERT_OPTIONAL + >>> context.load_verify_locations("/etc/ssl/certs/ca-bundle.crt") + +(it is assumed your operating system places a bundle of all CA certificates +in ``/etc/ssl/certs/ca-bundle.crt``; if not, you'll get an error and have +to adjust the location) + +When you use the context to connect to a server, :const:`CERT_OPTIONAL` +validates the server certificate: it ensures that the server certificate +was signed with one of the CA certificates, and checks the signature for +correctness:: + + >>> conn = context.wrap_socket(socket.socket(socket.AF_INET)) + >>> conn.connect(("linuxfr.org", 443)) + +You should then fetch the certificate and check its fields for conformity. +Here, the ``commonName`` field in the ``subject`` matches the desired HTTPS +host ``linuxfr.org``:: + + >>> pprint.pprint(conn.getpeercert()) + {'notAfter': 'Jun 26 21:41:46 2011 GMT', + 'subject': ((('commonName', 'linuxfr.org'),),), + 'subjectAltName': (('DNS', 'linuxfr.org'), ('othername', ''))} + +Now that you are assured of its authenticity, you can proceed to talk with +the server:: + + >>> conn.write(b"HEAD / HTTP/1.0\r\nHost: linuxfr.org\r\n\r\n") + 38 + >>> pprint.pprint(conn.read().split(b"\r\n")) + [b'HTTP/1.1 302 Found', + b'Date: Sun, 16 May 2010 13:43:28 GMT', + b'Server: Apache/2.2', + b'Location: https://linuxfr.org/pub/', + b'Vary: Accept-Encoding', + b'Connection: close', + b'Content-Type: text/html; charset=iso-8859-1', + b'', + b''] + + +See the discussion of :ref:`ssl-security` below. + + Server-side operation ^^^^^^^^^^^^^^^^^^^^^ -For server operation, typically you'd need to have a server certificate, and -private key, each in a file. You'd open a socket, bind it to a port, call -:meth:`listen` on it, then start waiting for clients to connect:: +For server operation, typically you'll need to have a server certificate, and +private key, each in a file. You'll first create a context holding the key +and the certificate, so that clients can check your authenticity. Then +you'll open a socket, bind it to a port, call :meth:`listen` on it, and start +waiting for clients to connect:: import socket, ssl + context = ssl.SSLContext(ssl.PROTOCOL_TLSv1) + context.load_cert_chain(certfile="mycertfile", keyfile="mykeyfile") + bindsocket = socket.socket() bindsocket.bind(('myaddr.mydomain.com', 10023)) bindsocket.listen(5) -When one did, you'd call :meth:`accept` on the socket to get the new socket from -the other end, and use :func:`wrap_socket` to create a server-side SSL context -for it:: +When a client connects, you'll call :meth:`accept` on the socket to get the +new socket from the other end, and use the context's :meth:`SSLContext.wrap_socket` +method to create a server-side SSL socket for the connection:: while True: newsocket, fromaddr = bindsocket.accept() - connstream = ssl.wrap_socket(newsocket, - server_side=True, - certfile="mycertfile", - keyfile="mykeyfile", - ssl_version=ssl.PROTOCOL_TLSv1) - deal_with_client(connstream) + connstream = context.wrap_socket(newsocket, server_side=True) + try: + deal_with_client(connstream) + finally: + connstream.close() -Then you'd read data from the ``connstream`` and do something with it till you +Then you'll read data from the ``connstream`` and do something with it till you are finished with the client (or the client is finished with you):: def deal_with_client(connstream): - data = connstream.read() - # null data means the client is finished with us + # empty data means the client is finished with us while data: if not do_something(connstream, data): # we'll assume do_something returns False @@ -597,9 +758,41 @@ break data = connstream.read() # finished with client - connstream.close() -And go back to listening for new client connections. +And go back to listening for new client connections (of course, a real server +would probably handle each client connection in a separate thread, or put +the sockets in non-blocking mode and use an event loop). + + +.. _ssl-security: + +Security considerations +----------------------- + +Verifying certificates +^^^^^^^^^^^^^^^^^^^^^^ + +:const:`CERT_NONE` is the default. Since it does not authenticate the other +peer, it can be insecure, especially in client mode where most of time you +would like to ensure the authenticity of the server you're talking to. +Therefore, when in client mode, it is highly recommended to use +:const:`CERT_REQUIRED`. However, it is in itself not sufficient; you also +have to check that the server certificate (obtained with +:meth:`SSLSocket.getpeercert`) matches the desired service. The exact way +of doing so depends on the higher-level protocol used; for example, with +HTTPS, you'll check that the host name in the URL matches either the +``commonName`` field in the ``subjectName``, or one of the ``DNS`` fields +in the ``subjectAltName``. + +In server mode, if you want to authenticate your clients using the SSL layer +(rather than using a higher-level authentication mechanism), you'll also have +to specify :const:`CERT_REQUIRED` and similarly check the client certificate. + + .. note:: + + In client mode, :const:`CERT_OPTIONAL` and :const:`CERT_REQUIRED` are + equivalent unless anonymous ciphers are enabled (they are disabled + by default). .. seealso:: Modified: python/branches/py3k-jit/Doc/library/sys.rst ============================================================================== --- python/branches/py3k-jit/Doc/library/sys.rst (original) +++ python/branches/py3k-jit/Doc/library/sys.rst Tue May 18 19:58:30 2010 @@ -298,15 +298,13 @@ .. function:: getfilesystemencoding() - Return the name of the encoding used to convert Unicode filenames into system - file names, or ``None`` if the system default encoding is used. The result value - depends on the operating system: + Return the name of the encoding used to convert Unicode filenames into + system file names. The result value depends on the operating system: * On Mac OS X, the encoding is ``'utf-8'``. * On Unix, the encoding is the user's preference according to the result of - nl_langinfo(CODESET), or ``None`` if the ``nl_langinfo(CODESET)`` - failed. + nl_langinfo(CODESET), or ``'utf-8'`` if ``nl_langinfo(CODESET)`` failed. * On Windows NT+, file names are Unicode natively, so no conversion is performed. :func:`getfilesystemencoding` still returns ``'mbcs'``, as @@ -316,6 +314,10 @@ * On Windows 9x, the encoding is ``'mbcs'``. + .. versionchanged:: 3.2 + On Unix, use ``'utf-8'`` instead of ``None`` if ``nl_langinfo(CODESET)`` + failed. :func:`getfilesystemencoding` result cannot be ``None``. + .. function:: getrefcount(object) Modified: python/branches/py3k-jit/Doc/library/tarfile.rst ============================================================================== --- python/branches/py3k-jit/Doc/library/tarfile.rst (original) +++ python/branches/py3k-jit/Doc/library/tarfile.rst Tue May 18 19:58:30 2010 @@ -711,6 +711,8 @@ The default scheme is ``'surrogateescape'`` which Python also uses for its file system calls, see :ref:`os-filenames`. -In case of writing :const:`PAX_FORMAT` archives, *encoding* is ignored because -non-ASCII metadata is stored using *UTF-8*. Storing surrogate characters is not -possible and will raise a :exc:`UnicodeEncodeError`. +In case of :const:`PAX_FORMAT` archives, *encoding* is generally not needed +because all the metadata is stored using *UTF-8*. *encoding* is only used in +the rare cases when binary pax headers are decoded or when strings with +surrogate characters are stored. + Modified: python/branches/py3k-jit/Doc/library/wsgiref.rst ============================================================================== --- python/branches/py3k-jit/Doc/library/wsgiref.rst (original) +++ python/branches/py3k-jit/Doc/library/wsgiref.rst Tue May 18 19:58:30 2010 @@ -710,7 +710,7 @@ # use a function (note that you're not limited to a function, you can # use a class for example). The first argument passed to the function # is a dictionary containing CGI-style envrironment variables and the - # second variable is the callable object (see PEP333) + # second variable is the callable object (see :pep:`333`) def hello_world_app(environ, start_response): status = b'200 OK' # HTTP Status headers = [(b'Content-type', b'text/plain; charset=utf-8')] # HTTP Headers Modified: python/branches/py3k-jit/Doc/library/zipimport.rst ============================================================================== --- python/branches/py3k-jit/Doc/library/zipimport.rst (original) +++ python/branches/py3k-jit/Doc/library/zipimport.rst Tue May 18 19:58:30 2010 @@ -34,12 +34,12 @@ Documentation on the ZIP file format by Phil Katz, the creator of the format and algorithms used. - :pep:`0273` - Import Modules from Zip Archives + :pep:`273` - Import Modules from Zip Archives Written by James C. Ahlstrom, who also provided an implementation. Python 2.3 follows the specification in PEP 273, but uses an implementation written by Just van Rossum that uses the import hooks described in PEP 302. - :pep:`0302` - New Import Hooks + :pep:`302` - New Import Hooks The PEP to add the import hooks that help this module work. Modified: python/branches/py3k-jit/Include/unicodeobject.h ============================================================================== --- python/branches/py3k-jit/Include/unicodeobject.h (original) +++ python/branches/py3k-jit/Include/unicodeobject.h Tue May 18 19:58:30 2010 @@ -1240,30 +1240,44 @@ /* --- File system encoding ---------------------------------------------- */ /* ParseTuple converter which converts a Unicode object into the file - system encoding as a bytes object, using the PEP 383 error handler; bytes - objects are output as-is. */ + system encoding as a bytes object, using the "surrogateescape" error + handler; bytes objects are output as-is. */ PyAPI_FUNC(int) PyUnicode_FSConverter(PyObject*, void*); -/* Decode a null-terminated string using Py_FileSystemDefaultEncoding. +/* Decode a null-terminated string using Py_FileSystemDefaultEncoding + and the "surrogateescape" error handler. - If the encoding is supported by one of the built-in codecs (i.e., UTF-8, - UTF-16, UTF-32, Latin-1 or MBCS), otherwise fallback to UTF-8 and replace - invalid characters with '?'. + If Py_FileSystemDefaultEncoding is not set, fall back to UTF-8. - The function is intended to be used for paths and file names only - during bootstrapping process where the codecs are not set up. + Use PyUnicode_DecodeFSDefaultAndSize() if the string length is known. */ PyAPI_FUNC(PyObject*) PyUnicode_DecodeFSDefault( const char *s /* encoded string */ ); +/* Decode a string using Py_FileSystemDefaultEncoding + and the "surrogateescape" error handler. + + If Py_FileSystemDefaultEncoding is not set, fall back to UTF-8. +*/ + PyAPI_FUNC(PyObject*) PyUnicode_DecodeFSDefaultAndSize( const char *s, /* encoded string */ Py_ssize_t size /* size */ ); +/* Encode a Unicode object to Py_FileSystemDefaultEncoding with the + "surrogateescape" error handler, and return bytes. + + If Py_FileSystemDefaultEncoding is not set, fall back to UTF-8. +*/ + +PyAPI_FUNC(PyObject*) PyUnicode_EncodeFSDefault( + PyObject *unicode + ); + /* --- Methods & Slots ---------------------------------------------------- These are capable of handling Unicode objects and strings on input Modified: python/branches/py3k-jit/Lib/distutils/command/sdist.py ============================================================================== --- python/branches/py3k-jit/Lib/distutils/command/sdist.py (original) +++ python/branches/py3k-jit/Lib/distutils/command/sdist.py Tue May 18 19:58:30 2010 @@ -63,7 +63,8 @@ "just regenerate the manifest and then stop " "(implies --force-manifest)"), ('force-manifest', 'f', - "forcibly regenerate the manifest and carry on as usual"), + "forcibly regenerate the manifest and carry on as usual. " + "Deprecated: now the manifest is always regenerated."), ('formats=', None, "formats for source distribution (comma-separated list)"), ('keep-temp', 'k', @@ -179,66 +180,34 @@ distribution, and put it in 'self.filelist'. This might involve reading the manifest template (and writing the manifest), or just reading the manifest, or just using the default file set -- it all - depends on the user's options and the state of the filesystem. + depends on the user's options. """ - # If we have a manifest template, see if it's newer than the - # manifest; if so, we'll regenerate the manifest. + # new behavior: + # the file list is recalculated everytime because + # even if MANIFEST.in or setup.py are not changed + # the user might have added some files in the tree that + # need to be included. + # + # This makes --force the default and only behavior. template_exists = os.path.isfile(self.template) + if not template_exists: + self.warn(("manifest template '%s' does not exist " + + "(using default file list)") % + self.template) + self.filelist.findall() + + if self.use_defaults: + self.add_defaults() + if template_exists: - template_newer = dep_util.newer(self.template, self.manifest) + self.read_template() - # The contents of the manifest file almost certainly depend on the - # setup script as well as the manifest template -- so if the setup - # script is newer than the manifest, we'll regenerate the manifest - # from the template. (Well, not quite: if we already have a - # manifest, but there's no template -- which will happen if the - # developer elects to generate a manifest some other way -- then we - # can't regenerate the manifest, so we don't.) - self.debug_print("checking if %s newer than %s" % - (self.distribution.script_name, self.manifest)) - setup_newer = dep_util.newer(self.distribution.script_name, - self.manifest) - - # cases: - # 1) no manifest, template exists: generate manifest - # (covered by 2a: no manifest == template newer) - # 2) manifest & template exist: - # 2a) template or setup script newer than manifest: - # regenerate manifest - # 2b) manifest newer than both: - # do nothing (unless --force or --manifest-only) - # 3) manifest exists, no template: - # do nothing (unless --force or --manifest-only) - # 4) no manifest, no template: generate w/ warning ("defaults only") - - manifest_outofdate = (template_exists and - (template_newer or setup_newer)) - force_regen = self.force_manifest or self.manifest_only - manifest_exists = os.path.isfile(self.manifest) - neither_exists = (not template_exists and not manifest_exists) - - # Regenerate the manifest if necessary (or if explicitly told to) - if manifest_outofdate or neither_exists or force_regen: - if not template_exists: - self.warn("manifest template '%s' does not exist " - "(using default file list)" - % self.template) - self.filelist.findall() - - if self.use_defaults: - self.add_defaults() - if template_exists: - self.read_template() - if self.prune: - self.prune_file_list() - - self.filelist.sort() - self.filelist.remove_duplicates() - self.write_manifest() + if self.prune: + self.prune_file_list() - # Don't regenerate the manifest, just read it in. - else: - self.read_manifest() + self.filelist.sort() + self.filelist.remove_duplicates() + self.write_manifest() def add_defaults(self): """Add all the default files to self.filelist: Modified: python/branches/py3k-jit/Lib/distutils/tests/test_sdist.py ============================================================================== --- python/branches/py3k-jit/Lib/distutils/tests/test_sdist.py (original) +++ python/branches/py3k-jit/Lib/distutils/tests/test_sdist.py Tue May 18 19:58:30 2010 @@ -346,6 +346,47 @@ finally: archive.close() + def test_get_file_list(self): + # make sure MANIFEST is recalculated + dist, cmd = self.get_cmd() + + # filling data_files by pointing files in package_data + dist.package_data = {'somecode': ['*.txt']} + self.write_file((self.tmp_dir, 'somecode', 'doc.txt'), '#') + cmd.ensure_finalized() + cmd.run() + + f = open(cmd.manifest) + try: + manifest = [line.strip() for line in f.read().split('\n') + if line.strip() != ''] + finally: + f.close() + + self.assertEquals(len(manifest), 4) + + # adding a file + self.write_file((self.tmp_dir, 'somecode', 'doc2.txt'), '#') + + # make sure build_py is reinitinialized, like a fresh run + build_py = dist.get_command_obj('build_py') + build_py.finalized = False + build_py.ensure_finalized() + + cmd.run() + + f = open(cmd.manifest) + try: + manifest2 = [line.strip() for line in f.read().split('\n') + if line.strip() != ''] + finally: + f.close() + + # do we have the new file in MANIFEST ? + self.assertEquals(len(manifest2), 5) + self.assertIn('doc2.txt', manifest2[-1]) + + def test_suite(): return unittest.makeSuite(SDistTestCase) Modified: python/branches/py3k-jit/Lib/ssl.py ============================================================================== --- python/branches/py3k-jit/Lib/ssl.py (original) +++ python/branches/py3k-jit/Lib/ssl.py Tue May 18 19:58:30 2010 @@ -59,7 +59,7 @@ import _ssl # if we can't import it, let the error propagate from _ssl import OPENSSL_VERSION_NUMBER, OPENSSL_VERSION_INFO, OPENSSL_VERSION -from _ssl import SSLError +from _ssl import _SSLContext, SSLError from _ssl import CERT_NONE, CERT_OPTIONAL, CERT_REQUIRED from _ssl import (PROTOCOL_SSLv2, PROTOCOL_SSLv3, PROTOCOL_SSLv23, PROTOCOL_TLSv1) @@ -84,8 +84,29 @@ import traceback import errno -class SSLSocket(socket): +class SSLContext(_SSLContext): + """An SSLContext holds various SSL-related configuration options and + data, such as certificates and possibly a private key.""" + + __slots__ = ('protocol',) + + def __new__(cls, protocol, *args, **kwargs): + return _SSLContext.__new__(cls, protocol) + + def __init__(self, protocol): + self.protocol = protocol + + def wrap_socket(self, sock, server_side=False, + do_handshake_on_connect=True, + suppress_ragged_eofs=True): + return SSLSocket(sock=sock, server_side=server_side, + do_handshake_on_connect=do_handshake_on_connect, + suppress_ragged_eofs=suppress_ragged_eofs, + _context=self) + + +class SSLSocket(socket): """This class implements a subtype of socket.socket that wraps the underlying OS socket in an SSL context when necessary, and provides read and write methods over that channel.""" @@ -95,8 +116,31 @@ ssl_version=PROTOCOL_SSLv23, ca_certs=None, do_handshake_on_connect=True, family=AF_INET, type=SOCK_STREAM, proto=0, fileno=None, - suppress_ragged_eofs=True, ciphers=None): + suppress_ragged_eofs=True, ciphers=None, + _context=None): + + if _context: + self.context = _context + else: + if certfile and not keyfile: + keyfile = certfile + self.context = SSLContext(ssl_version) + self.context.verify_mode = cert_reqs + if ca_certs: + self.context.load_verify_locations(ca_certs) + if certfile: + self.context.load_cert_chain(certfile, keyfile) + if ciphers: + self.context.set_ciphers(ciphers) + self.keyfile = keyfile + self.certfile = certfile + self.cert_reqs = cert_reqs + self.ssl_version = ssl_version + self.ca_certs = ca_certs + self.ciphers = ciphers + self.do_handshake_on_connect = do_handshake_on_connect + self.suppress_ragged_eofs = suppress_ragged_eofs connected = False if sock is not None: socket.__init__(self, @@ -119,18 +163,12 @@ else: socket.__init__(self, family=family, type=type, proto=proto) - if certfile and not keyfile: - keyfile = certfile - self._closed = False self._sslobj = None if connected: # create the SSL object try: - self._sslobj = _ssl.sslwrap(self, server_side, - keyfile, certfile, - cert_reqs, ssl_version, ca_certs, - ciphers) + self._sslobj = self.context._wrap_socket(self, server_side) if do_handshake_on_connect: timeout = self.gettimeout() if timeout == 0.0: @@ -142,15 +180,6 @@ self.close() raise x - self.keyfile = keyfile - self.certfile = certfile - self.cert_reqs = cert_reqs - self.ssl_version = ssl_version - self.ca_certs = ca_certs - self.ciphers = ciphers - self.do_handshake_on_connect = do_handshake_on_connect - self.suppress_ragged_eofs = suppress_ragged_eofs - def dup(self): raise NotImplemented("Can't dup() %s instances" % self.__class__.__name__) @@ -331,9 +360,7 @@ if self._sslobj: raise ValueError("attempt to connect already-connected SSLSocket!") socket.connect(self, addr) - self._sslobj = _ssl.sslwrap(self, False, self.keyfile, self.certfile, - self.cert_reqs, self.ssl_version, - self.ca_certs, self.ciphers) + self._sslobj = self.context._wrap_socket(self, False) try: if self.do_handshake_on_connect: self.do_handshake() Modified: python/branches/py3k-jit/Lib/subprocess.py ============================================================================== --- python/branches/py3k-jit/Lib/subprocess.py (original) +++ python/branches/py3k-jit/Lib/subprocess.py Tue May 18 19:58:30 2010 @@ -356,7 +356,6 @@ if mswindows: - from _subprocess import CREATE_NEW_CONSOLE, CREATE_NEW_PROCESS_GROUP import threading import msvcrt import _subprocess @@ -394,6 +393,7 @@ "getoutput", "check_output", "CalledProcessError"] if mswindows: + from _subprocess import CREATE_NEW_CONSOLE, CREATE_NEW_PROCESS_GROUP __all__.extend(["CREATE_NEW_CONSOLE", "CREATE_NEW_PROCESS_GROUP"]) try: MAXFD = os.sysconf("SC_OPEN_MAX") @@ -698,12 +698,12 @@ return data.decode(encoding) - def __del__(self, sys=sys): + def __del__(self, _maxsize=sys.maxsize, _active=_active): if not self._child_created: # We didn't get to successfully create a child process. return # In case the child hasn't been waited on, check if it's done. - self._internal_poll(_deadstate=sys.maxsize) + self._internal_poll(_deadstate=_maxsize) if self.returncode is None and _active is not None: # Child is still running, keep us alive until we can wait on it. _active.append(self) @@ -907,13 +907,20 @@ errwrite.Close() - def _internal_poll(self, _deadstate=None): + def _internal_poll(self, _deadstate=None, + _WaitForSingleObject=_subprocess.WaitForSingleObject, + _WAIT_OBJECT_0=_subprocess.WAIT_OBJECT_0, + _GetExitCodeProcess=_subprocess.GetExitCodeProcess): """Check if child process has terminated. Returns returncode - attribute.""" + attribute. + + This method is called by __del__, so it can only refer to objects + in its local scope. + + """ if self.returncode is None: - if(_subprocess.WaitForSingleObject(self._handle, 0) == - _subprocess.WAIT_OBJECT_0): - self.returncode = _subprocess.GetExitCodeProcess(self._handle) + if _WaitForSingleObject(self._handle, 0) == _WAIT_OBJECT_0: + self.returncode = _GetExitCodeProcess(self._handle) return self.returncode @@ -1252,25 +1259,35 @@ raise child_exception_type(err_msg) - def _handle_exitstatus(self, sts): - if os.WIFSIGNALED(sts): - self.returncode = -os.WTERMSIG(sts) - elif os.WIFEXITED(sts): - self.returncode = os.WEXITSTATUS(sts) + def _handle_exitstatus(self, sts, _WIFSIGNALED=os.WIFSIGNALED, + _WTERMSIG=os.WTERMSIG, _WIFEXITED=os.WIFEXITED, + _WEXITSTATUS=os.WEXITSTATUS): + # This method is called (indirectly) by __del__, so it cannot + # refer to anything outside of its local scope.""" + if _WIFSIGNALED(sts): + self.returncode = -_WTERMSIG(sts) + elif _WIFEXITED(sts): + self.returncode = _WEXITSTATUS(sts) else: # Should never happen raise RuntimeError("Unknown child exit status!") - def _internal_poll(self, _deadstate=None): + def _internal_poll(self, _deadstate=None, _waitpid=os.waitpid, + _WNOHANG=os.WNOHANG, _os_error=os.error): """Check if child process has terminated. Returns returncode - attribute.""" + attribute. + + This method is called by __del__, so it cannot reference anything + outside of the local scope (nor can any methods it calls). + + """ if self.returncode is None: try: - pid, sts = os.waitpid(self.pid, os.WNOHANG) + pid, sts = _waitpid(self.pid, _WNOHANG) if pid == self.pid: self._handle_exitstatus(sts) - except os.error: + except _os_error: if _deadstate is not None: self.returncode = _deadstate return self.returncode Modified: python/branches/py3k-jit/Lib/tarfile.py ============================================================================== --- python/branches/py3k-jit/Lib/tarfile.py (original) +++ python/branches/py3k-jit/Lib/tarfile.py Tue May 18 19:58:30 2010 @@ -118,6 +118,9 @@ PAX_FIELDS = ("path", "linkpath", "size", "mtime", "uid", "gid", "uname", "gname") +# Fields from a pax header that are affected by hdrcharset. +PAX_NAME_FIELDS = {"path", "linkpath", "uname", "gname"} + # Fields in a pax header that are numbers, all other fields # are treated as strings. PAX_NUMBER_FIELDS = { @@ -988,7 +991,7 @@ elif format == GNU_FORMAT: return self.create_gnu_header(info, encoding, errors) elif format == PAX_FORMAT: - return self.create_pax_header(info) + return self.create_pax_header(info, encoding) else: raise ValueError("invalid format") @@ -1019,7 +1022,7 @@ return buf + self._create_header(info, GNU_FORMAT, encoding, errors) - def create_pax_header(self, info): + def create_pax_header(self, info, encoding): """Return the object as a ustar header block. If it cannot be represented this way, prepend a pax extended header sequence with supplement information. @@ -1062,7 +1065,7 @@ # Create a pax extended header if necessary. if pax_headers: - buf = self._create_pax_generic_header(pax_headers, XHDTYPE) + buf = self._create_pax_generic_header(pax_headers, XHDTYPE, encoding) else: buf = b"" @@ -1072,7 +1075,7 @@ def create_pax_global_header(cls, pax_headers): """Return the object as a pax global header block sequence. """ - return cls._create_pax_generic_header(pax_headers, XGLTYPE) + return cls._create_pax_generic_header(pax_headers, XGLTYPE, "utf8") def _posix_split_name(self, name): """Split a name longer than 100 chars into a prefix @@ -1145,15 +1148,35 @@ cls._create_payload(name) @classmethod - def _create_pax_generic_header(cls, pax_headers, type): - """Return a POSIX.1-2001 extended or global header sequence + def _create_pax_generic_header(cls, pax_headers, type, encoding): + """Return a POSIX.1-2008 extended or global header sequence that contains a list of keyword, value pairs. The values must be strings. """ + # Check if one of the fields contains surrogate characters and thereby + # forces hdrcharset=BINARY, see _proc_pax() for more information. + binary = False + for keyword, value in pax_headers.items(): + try: + value.encode("utf8", "strict") + except UnicodeEncodeError: + binary = True + break + records = b"" + if binary: + # Put the hdrcharset field at the beginning of the header. + records += b"21 hdrcharset=BINARY\n" + for keyword, value in pax_headers.items(): keyword = keyword.encode("utf8") - value = value.encode("utf8") + if binary: + # Try to restore the original byte representation of `value'. + # Needless to say, that the encoding must match the string. + value = value.encode(encoding, "surrogateescape") + else: + value = value.encode("utf8") + l = len(keyword) + len(value) + 3 # ' ' + '=' + '\n' n = p = 0 while True: @@ -1354,7 +1377,7 @@ def _proc_pax(self, tarfile): """Process an extended or global header as described in - POSIX.1-2001. + POSIX.1-2008. """ # Read the header information. buf = tarfile.fileobj.read(self._block(self.size)) @@ -1367,6 +1390,24 @@ else: pax_headers = tarfile.pax_headers.copy() + # Check if the pax header contains a hdrcharset field. This tells us + # the encoding of the path, linkpath, uname and gname fields. Normally, + # these fields are UTF-8 encoded but since POSIX.1-2008 tar + # implementations are allowed to store them as raw binary strings if + # the translation to UTF-8 fails. + match = re.search(br"\d+ hdrcharset=([^\n]+)\n", buf) + if match is not None: + pax_headers["hdrcharset"] = match.group(1).decode("utf8") + + # For the time being, we don't care about anything other than "BINARY". + # The only other value that is currently allowed by the standard is + # "ISO-IR 10646 2000 UTF-8" in other words UTF-8. + hdrcharset = pax_headers.get("hdrcharset") + if hdrcharset == "BINARY": + encoding = tarfile.encoding + else: + encoding = "utf8" + # Parse pax header information. A record looks like that: # "%d %s=%s\n" % (length, keyword, value). length is the size # of the complete record including the length field itself and @@ -1382,8 +1423,21 @@ length = int(length) value = buf[match.end(2) + 1:match.start(1) + length - 1] - keyword = keyword.decode("utf8") - value = value.decode("utf8") + # Normally, we could just use "utf8" as the encoding and "strict" + # as the error handler, but we better not take the risk. For + # example, GNU tar <= 1.23 is known to store filenames it cannot + # translate to UTF-8 as raw strings (unfortunately without a + # hdrcharset=BINARY header). + # We first try the strict standard encoding, and if that fails we + # fall back on the user's encoding and error handler. + keyword = self._decode_pax_field(keyword, "utf8", "utf8", + tarfile.errors) + if keyword in PAX_NAME_FIELDS: + value = self._decode_pax_field(value, encoding, tarfile.encoding, + tarfile.errors) + else: + value = self._decode_pax_field(value, "utf8", "utf8", + tarfile.errors) pax_headers[keyword] = value pos += length @@ -1431,6 +1485,14 @@ self.pax_headers = pax_headers.copy() + def _decode_pax_field(self, value, encoding, fallback_encoding, fallback_errors): + """Decode a single field from a pax record. + """ + try: + return value.decode(encoding, "strict") + except UnicodeDecodeError: + return value.decode(fallback_encoding, fallback_errors) + def _block(self, count): """Round up a byte count by BLOCKSIZE and return it, e.g. _block(834) => 1024. Modified: python/branches/py3k-jit/Lib/test/list_tests.py ============================================================================== --- python/branches/py3k-jit/Lib/test/list_tests.py (original) +++ python/branches/py3k-jit/Lib/test/list_tests.py Tue May 18 19:58:30 2010 @@ -66,13 +66,11 @@ d.append(d) d.append(400) try: - fo = open(support.TESTFN, "w") - fo.write(str(d)) - fo.close() - fo = open(support.TESTFN, "r") - self.assertEqual(fo.read(), repr(d)) + with open(support.TESTFN, "w") as fo: + fo.write(str(d)) + with open(support.TESTFN, "r") as fo: + self.assertEqual(fo.read(), repr(d)) finally: - fo.close() os.remove(support.TESTFN) def test_set_subscript(self): Modified: python/branches/py3k-jit/Lib/test/test_capi.py ============================================================================== --- python/branches/py3k-jit/Lib/test/test_capi.py (original) +++ python/branches/py3k-jit/Lib/test/test_capi.py Tue May 18 19:58:30 2010 @@ -45,9 +45,9 @@ (out, err) = p.communicate() self.assertEqual(out, b'') # This used to cause an infinite loop. - self.assertEqual(err, + self.assertEqual(err.rstrip(), b'Fatal Python error:' - b' PyThreadState_Get: no current thread\n') + b' PyThreadState_Get: no current thread') @unittest.skipUnless(threading, 'Threading required for this test.') Modified: python/branches/py3k-jit/Lib/test/test_import.py ============================================================================== --- python/branches/py3k-jit/Lib/test/test_import.py (original) +++ python/branches/py3k-jit/Lib/test/test_import.py Tue May 18 19:58:30 2010 @@ -142,6 +142,7 @@ self.assertIs(orig_path, new_os.path) self.assertIsNot(orig_getenv, new_os.getenv) + @unittest.expectedFailure # Issue 8727 is tracking the fix. def test_module_with_large_stack(self, module='longlist'): # Regression test for http://bugs.python.org/issue561858. filename = module + '.py' @@ -153,23 +154,23 @@ f.write('"",\n') f.write(']') - # Compile & remove .py file, we only need .pyc (or .pyo), but that - # must be relocated to the PEP 3147 bytecode-only location. - with open(filename, 'r') as f: - py_compile.compile(filename) + # Compile & remove .py file; we only need .pyc (or .pyo). + # Bytecode must be relocated from the PEP 3147 bytecode-only location. + py_compile.compile(filename) unlink(filename) make_legacy_pyc(filename) # Need to be able to load from current dir. sys.path.append('') - # This used to crash. - exec('import ' + module) - - # Cleanup. - del sys.path[-1] - unlink(filename + 'c') - unlink(filename + 'o') + try: + # This used to crash. + exec('import ' + module) + finally: + # Cleanup. + del sys.path[-1] + unlink(filename + 'c') + unlink(filename + 'o') def test_failing_import_sticks(self): source = TESTFN + ".py" Modified: python/branches/py3k-jit/Lib/test/test_math.py ============================================================================== --- python/branches/py3k-jit/Lib/test/test_math.py (original) +++ python/branches/py3k-jit/Lib/test/test_math.py Tue May 18 19:58:30 2010 @@ -60,6 +60,56 @@ return "error = {} ulps; permitted error = {} ulps".format(ulps_error, ulps) +# Here's a pure Python version of the math.factorial algorithm, for +# documentation and comparison purposes. +# +# Formula: +# +# factorial(n) = factorial_odd_part(n) << (n - count_set_bits(n)) +# +# where +# +# factorial_odd_part(n) = product_{i >= 0} product_{0 < j <= n >> i; j odd} j +# +# The outer product above is an infinite product, but once i >= n.bit_length, +# (n >> i) < 1 and the corresponding term of the product is empty. So only the +# finitely many terms for 0 <= i < n.bit_length() contribute anything. +# +# We iterate downwards from i == n.bit_length() - 1 to i == 0. The inner +# product in the formula above starts at 1 for i == n.bit_length(); for each i +# < n.bit_length() we get the inner product for i from that for i + 1 by +# multiplying by all j in {n >> i+1 < j <= n >> i; j odd}. In Python terms, +# this set is range((n >> i+1) + 1 | 1, (n >> i) + 1 | 1, 2). + +def count_set_bits(n): + """Number of '1' bits in binary expansion of a nonnnegative integer.""" + return 1 + count_set_bits(n & n - 1) if n else 0 + +def partial_product(start, stop): + """Product of integers in range(start, stop, 2), computed recursively. + start and stop should both be odd, with start <= stop. + + """ + numfactors = (stop - start) >> 1 + if not numfactors: + return 1 + elif numfactors == 1: + return start + else: + mid = (start + numfactors) | 1 + return partial_product(start, mid) * partial_product(mid, stop) + +def py_factorial(n): + """Factorial of nonnegative integer n, via "Binary Split Factorial Formula" + described at http://www.luschny.de/math/factorial/binarysplitfact.html + + """ + inner = outer = 1 + for i in reversed(range(n.bit_length())): + inner *= partial_product((n >> i + 1) + 1 | 1, (n >> i) + 1 | 1) + outer *= inner + return outer << (n - count_set_bits(n)) + def acc_check(expected, got, rel_err=2e-15, abs_err = 5e-323): """Determine whether non-NaN floats a and b are equal to within a (small) rounding error. The default values for rel_err and @@ -365,18 +415,19 @@ self.ftest('fabs(1)', math.fabs(1), 1) def testFactorial(self): - def fact(n): - result = 1 - for i in range(1, int(n)+1): - result *= i - return result - values = list(range(10)) + [50, 100, 500] - random.shuffle(values) - for x in values: - for cast in (int, float): - self.assertEqual(math.factorial(cast(x)), fact(x), (x, fact(x), math.factorial(x))) + self.assertEqual(math.factorial(0), 1) + self.assertEqual(math.factorial(0.0), 1) + total = 1 + for i in range(1, 1000): + total *= i + self.assertEqual(math.factorial(i), total) + self.assertEqual(math.factorial(float(i)), total) + self.assertEqual(math.factorial(i), py_factorial(i)) self.assertRaises(ValueError, math.factorial, -1) + self.assertRaises(ValueError, math.factorial, -1.0) self.assertRaises(ValueError, math.factorial, math.pi) + self.assertRaises(OverflowError, math.factorial, sys.maxsize+1) + self.assertRaises(OverflowError, math.factorial, 10e100) def testFloor(self): self.assertRaises(TypeError, math.floor) Modified: python/branches/py3k-jit/Lib/test/test_os.py ============================================================================== --- python/branches/py3k-jit/Lib/test/test_os.py (original) +++ python/branches/py3k-jit/Lib/test/test_os.py Tue May 18 19:58:30 2010 @@ -12,6 +12,7 @@ import time import shutil from test import support +import contextlib # Detect whether we're on a Linux system that uses the (now outdated # and unmaintained) linuxthreads threading library. There's an issue @@ -623,6 +624,39 @@ except NotImplementedError: pass + at contextlib.contextmanager +def _execvpe_mockup(defpath=None): + """ + Stubs out execv and execve functions when used as context manager. + Records exec calls. The mock execv and execve functions always raise an + exception as they would normally never return. + """ + # A list of tuples containing (function name, first arg, args) + # of calls to execv or execve that have been made. + calls = [] + + def mock_execv(name, *args): + calls.append(('execv', name, args)) + raise RuntimeError("execv called") + + def mock_execve(name, *args): + calls.append(('execve', name, args)) + raise OSError(errno.ENOTDIR, "execve called") + + try: + orig_execv = os.execv + orig_execve = os.execve + orig_defpath = os.defpath + os.execv = mock_execv + os.execve = mock_execve + if defpath is not None: + os.defpath = defpath + yield calls + finally: + os.execv = orig_execv + os.execve = orig_execve + os.defpath = orig_defpath + class ExecTests(unittest.TestCase): @unittest.skipIf(USING_LINUXTHREADS, "avoid triggering a linuxthreads bug: see issue #4970") @@ -633,57 +667,25 @@ def test_execvpe_with_bad_arglist(self): self.assertRaises(ValueError, os.execvpe, 'notepad', [], None) - class _stub_out_for_execvpe_test(object): - """ - Stubs out execv, execve and get_exec_path functions when - used as context manager. Records exec calls. The mock execv - and execve functions always raise an exception as they would - normally never return. - """ - def __init__(self): - # A list of tuples containing (function name, first arg, args) - # of calls to execv or execve that have been made. - self.calls = [] - def _mock_execv(self, name, *args): - self.calls.append(('execv', name, args)) - raise RuntimeError("execv called") - - def _mock_execve(self, name, *args): - self.calls.append(('execve', name, args)) - raise OSError(errno.ENOTDIR, "execve called") - - def _mock_get_exec_path(self, env=None): - return [os.sep+'p', os.sep+'pp'] - - def __enter__(self): - self.orig_execv = os.execv - self.orig_execve = os.execve - self.orig_get_exec_path = os.get_exec_path - os.execv = self._mock_execv - os.execve = self._mock_execve - os.get_exec_path = self._mock_get_exec_path - - def __exit__(self, type, value, tb): - os.execv = self.orig_execv - os.execve = self.orig_execve - os.get_exec_path = self.orig_get_exec_path - @unittest.skipUnless(hasattr(os, '_execvpe'), "No internal os._execvpe function to test.") def test_internal_execvpe(self): - exec_stubbed = self._stub_out_for_execvpe_test() - with exec_stubbed: - self.assertRaises(RuntimeError, os._execvpe, os.sep+'f', ['-a']) - self.assertEqual([('execv', os.sep+'f', (['-a'],))], - exec_stubbed.calls) - exec_stubbed.calls = [] - self.assertRaises(OSError, os._execvpe, 'f', ['-a'], - env={'spam': 'beans'}) - self.assertEqual([('execve', os.sep+'p'+os.sep+'f', - (['-a'], {'spam': 'beans'})), - ('execve', os.sep+'pp'+os.sep+'f', - (['-a'], {'spam': 'beans'}))], - exec_stubbed.calls) + program_path = os.sep+'absolutepath' + program = 'executable' + fullpath = os.path.join(program_path, program) + arguments = ['progname', 'arg1', 'arg2'] + env = {'spam': 'beans'} + + with _execvpe_mockup() as calls: + self.assertRaises(RuntimeError, os._execvpe, fullpath, arguments) + self.assertEqual(len(calls), 1) + self.assertEqual(calls[0], ('execv', fullpath, (arguments,))) + + with _execvpe_mockup(defpath=program_path) as calls: + self.assertRaises(OSError, os._execvpe, program, arguments, env=env) + self.assertEqual(len(calls), 1) + self.assertEqual(calls[0], ('execve', fullpath, (arguments, env))) + class Win32ErrorTests(unittest.TestCase): def test_rename(self): Modified: python/branches/py3k-jit/Lib/test/test_signal.py ============================================================================== --- python/branches/py3k-jit/Lib/test/test_signal.py (original) +++ python/branches/py3k-jit/Lib/test/test_signal.py Tue May 18 19:58:30 2010 @@ -431,9 +431,8 @@ if signal.getitimer(self.itimer) == (0.0, 0.0): break # sig_vtalrm handler stopped this itimer else: # Issue 8424 - sys.stdout.write("test_itimer_virtual: timeout: likely cause: " - "machine too slow or load too high.\n") - return + self.skipTest("timeout: likely cause: machine too slow or load too " + "high") # virtual itimer should be (0.0, 0.0) now self.assertEquals(signal.getitimer(self.itimer), (0.0, 0.0)) @@ -455,9 +454,8 @@ if signal.getitimer(self.itimer) == (0.0, 0.0): break # sig_prof handler stopped this itimer else: # Issue 8424 - sys.stdout.write("test_itimer_prof: timeout: likely cause: " - "machine too slow or load too high.\n") - return + self.skipTest("timeout: likely cause: machine too slow or load too " + "high") # profiling itimer should be (0.0, 0.0) now self.assertEquals(signal.getitimer(self.itimer), (0.0, 0.0)) Modified: python/branches/py3k-jit/Lib/test/test_site.py ============================================================================== --- python/branches/py3k-jit/Lib/test/test_site.py (original) +++ python/branches/py3k-jit/Lib/test/test_site.py Tue May 18 19:58:30 2010 @@ -181,7 +181,8 @@ self.assertEquals(dirs[1], wanted) # let's try the specific Apple location - if sys.platform == "darwin": + if (sys.platform == "darwin" and + sysconfig.get_config_var("PYTHONFRAMEWORK")): site.PREFIXES = ['Python.framework'] dirs = site.getsitepackages() self.assertEqual(len(dirs), 4) Modified: python/branches/py3k-jit/Lib/test/test_ssl.py ============================================================================== --- python/branches/py3k-jit/Lib/test/test_ssl.py (original) +++ python/branches/py3k-jit/Lib/test/test_ssl.py Tue May 18 19:58:30 2010 @@ -10,6 +10,7 @@ import os import errno import pprint +import tempfile import urllib.parse, urllib.request import traceback import asyncore @@ -23,10 +24,33 @@ import ssl except ImportError: skip_expected = True +else: + PROTOCOLS = [ + ssl.PROTOCOL_SSLv2, ssl.PROTOCOL_SSLv3, + ssl.PROTOCOL_SSLv23, ssl.PROTOCOL_TLSv1 + ] HOST = support.HOST -CERTFILE = None -SVN_PYTHON_ORG_ROOT_CERT = None + +data_file = lambda name: os.path.join(os.path.dirname(__file__), name) +fsencode = lambda name: name.encode(sys.getfilesystemencoding(), "surrogateescape") + +CERTFILE = data_file("keycert.pem") +BYTES_CERTFILE = fsencode(CERTFILE) +ONLYCERT = data_file("ssl_cert.pem") +ONLYKEY = data_file("ssl_key.pem") +BYTES_ONLYCERT = fsencode(ONLYCERT) +BYTES_ONLYKEY = fsencode(ONLYKEY) +CAPATH = data_file("capath") +BYTES_CAPATH = fsencode(CAPATH) + +SVN_PYTHON_ORG_ROOT_CERT = data_file("https_svn_python_org_root.pem") + +EMPTYCERT = data_file("nullcert.pem") +BADCERT = data_file("badcert.pem") +WRONGCERT = data_file("XXXnonexisting.pem") +BADKEY = data_file("badkey.pem") + def handle_error(prefix): exc_format = ' '.join(traceback.format_exception(*sys.exc_info())) @@ -34,7 +58,7 @@ sys.stdout.write(prefix + exc_format) -class BasicTests(unittest.TestCase): +class BasicSocketTests(unittest.TestCase): def test_constants(self): ssl.PROTOCOL_SSLv2 @@ -116,11 +140,10 @@ s = ssl.wrap_socket(socket.socket(socket.AF_INET), cert_reqs=ssl.CERT_NONE, ciphers="DEFAULT") s.connect(remote) - # Error checking occurs when connecting, because the SSL context - # isn't created before. - s = ssl.wrap_socket(socket.socket(socket.AF_INET), - cert_reqs=ssl.CERT_NONE, ciphers="^$:,;?*'dorothyx") + # Error checking can happen at instantiation or when connecting with self.assertRaisesRegexp(ssl.SSLError, "No cipher can be selected"): + s = ssl.wrap_socket(socket.socket(socket.AF_INET), + cert_reqs=ssl.CERT_NONE, ciphers="^$:,;?*'dorothyx") s.connect(remote) @support.cpython_only @@ -143,33 +166,166 @@ self.assertEqual(timeout, ss.gettimeout()) +class ContextTests(unittest.TestCase): + + def test_constructor(self): + ctx = ssl.SSLContext(ssl.PROTOCOL_SSLv2) + ctx = ssl.SSLContext(ssl.PROTOCOL_SSLv23) + ctx = ssl.SSLContext(ssl.PROTOCOL_SSLv3) + ctx = ssl.SSLContext(ssl.PROTOCOL_TLSv1) + self.assertRaises(TypeError, ssl.SSLContext) + self.assertRaises(ValueError, ssl.SSLContext, -1) + self.assertRaises(ValueError, ssl.SSLContext, 42) + + def test_protocol(self): + for proto in PROTOCOLS: + ctx = ssl.SSLContext(proto) + self.assertEqual(ctx.protocol, proto) + + def test_ciphers(self): + ctx = ssl.SSLContext(ssl.PROTOCOL_TLSv1) + ctx.set_ciphers("ALL") + ctx.set_ciphers("DEFAULT") + with self.assertRaisesRegexp(ssl.SSLError, "No cipher can be selected"): + ctx.set_ciphers("^$:,;?*'dorothyx") + + def test_verify(self): + ctx = ssl.SSLContext(ssl.PROTOCOL_TLSv1) + # Default value + self.assertEqual(ctx.verify_mode, ssl.CERT_NONE) + ctx.verify_mode = ssl.CERT_OPTIONAL + self.assertEqual(ctx.verify_mode, ssl.CERT_OPTIONAL) + ctx.verify_mode = ssl.CERT_REQUIRED + self.assertEqual(ctx.verify_mode, ssl.CERT_REQUIRED) + ctx.verify_mode = ssl.CERT_NONE + self.assertEqual(ctx.verify_mode, ssl.CERT_NONE) + with self.assertRaises(TypeError): + ctx.verify_mode = None + with self.assertRaises(ValueError): + ctx.verify_mode = 42 + + def test_load_cert_chain(self): + ctx = ssl.SSLContext(ssl.PROTOCOL_TLSv1) + # Combined key and cert in a single file + ctx.load_cert_chain(CERTFILE) + ctx.load_cert_chain(CERTFILE, keyfile=CERTFILE) + self.assertRaises(TypeError, ctx.load_cert_chain, keyfile=CERTFILE) + with self.assertRaisesRegexp(ssl.SSLError, "system lib"): + ctx.load_cert_chain(WRONGCERT) + with self.assertRaisesRegexp(ssl.SSLError, "PEM lib"): + ctx.load_cert_chain(BADCERT) + with self.assertRaisesRegexp(ssl.SSLError, "PEM lib"): + ctx.load_cert_chain(EMPTYCERT) + # Separate key and cert + ctx = ssl.SSLContext(ssl.PROTOCOL_TLSv1) + ctx.load_cert_chain(ONLYCERT, ONLYKEY) + ctx.load_cert_chain(certfile=ONLYCERT, keyfile=ONLYKEY) + ctx.load_cert_chain(certfile=BYTES_ONLYCERT, keyfile=BYTES_ONLYKEY) + with self.assertRaisesRegexp(ssl.SSLError, "PEM lib"): + ctx.load_cert_chain(ONLYCERT) + with self.assertRaisesRegexp(ssl.SSLError, "PEM lib"): + ctx.load_cert_chain(ONLYKEY) + with self.assertRaisesRegexp(ssl.SSLError, "PEM lib"): + ctx.load_cert_chain(certfile=ONLYKEY, keyfile=ONLYCERT) + # Mismatching key and cert + ctx = ssl.SSLContext(ssl.PROTOCOL_TLSv1) + with self.assertRaisesRegexp(ssl.SSLError, "key values mismatch"): + ctx.load_cert_chain(CERTFILE, ONLYKEY) + + def test_load_verify_locations(self): + ctx = ssl.SSLContext(ssl.PROTOCOL_TLSv1) + ctx.load_verify_locations(CERTFILE) + ctx.load_verify_locations(cafile=CERTFILE, capath=None) + ctx.load_verify_locations(BYTES_CERTFILE) + ctx.load_verify_locations(cafile=BYTES_CERTFILE, capath=None) + self.assertRaises(TypeError, ctx.load_verify_locations) + self.assertRaises(TypeError, ctx.load_verify_locations, None, None) + with self.assertRaisesRegexp(ssl.SSLError, "system lib"): + ctx.load_verify_locations(WRONGCERT) + with self.assertRaisesRegexp(ssl.SSLError, "PEM lib"): + ctx.load_verify_locations(BADCERT) + ctx.load_verify_locations(CERTFILE, CAPATH) + ctx.load_verify_locations(CERTFILE, capath=BYTES_CAPATH) + + class NetworkedTests(unittest.TestCase): def test_connect(self): s = ssl.wrap_socket(socket.socket(socket.AF_INET), cert_reqs=ssl.CERT_NONE) - s.connect(("svn.python.org", 443)) - c = s.getpeercert() - if c: - self.fail("Peer cert %s shouldn't be here!") - s.close() - - # this should fail because we have no verification certs - s = ssl.wrap_socket(socket.socket(socket.AF_INET), - cert_reqs=ssl.CERT_REQUIRED) try: s.connect(("svn.python.org", 443)) - except ssl.SSLError: - pass + self.assertEqual({}, s.getpeercert()) finally: s.close() + # this should fail because we have no verification certs + s = ssl.wrap_socket(socket.socket(socket.AF_INET), + cert_reqs=ssl.CERT_REQUIRED) + self.assertRaisesRegexp(ssl.SSLError, "certificate verify failed", + s.connect, ("svn.python.org", 443)) + s.close() + # this should succeed because we specify the root cert s = ssl.wrap_socket(socket.socket(socket.AF_INET), cert_reqs=ssl.CERT_REQUIRED, ca_certs=SVN_PYTHON_ORG_ROOT_CERT) try: s.connect(("svn.python.org", 443)) + self.assertTrue(s.getpeercert()) + finally: + s.close() + + def test_connect_with_context(self): + # Same as test_connect, but with a separately created context + ctx = ssl.SSLContext(ssl.PROTOCOL_SSLv23) + s = ctx.wrap_socket(socket.socket(socket.AF_INET)) + s.connect(("svn.python.org", 443)) + try: + self.assertEqual({}, s.getpeercert()) + finally: + s.close() + # This should fail because we have no verification certs + ctx.verify_mode = ssl.CERT_REQUIRED + s = ctx.wrap_socket(socket.socket(socket.AF_INET)) + self.assertRaisesRegexp(ssl.SSLError, "certificate verify failed", + s.connect, ("svn.python.org", 443)) + s.close() + # This should succeed because we specify the root cert + ctx.load_verify_locations(SVN_PYTHON_ORG_ROOT_CERT) + s = ctx.wrap_socket(socket.socket(socket.AF_INET)) + s.connect(("svn.python.org", 443)) + try: + cert = s.getpeercert() + self.assertTrue(cert) + finally: + s.close() + + def test_connect_capath(self): + # Verify server certificates using the `capath` argument + # NOTE: the subject hashing algorithm has been changed between + # OpenSSL 0.9.8n and 1.0.0, as a result the capath directory must + # contain both versions of each certificate (same content, different + # filename) for this test to be portable across OpenSSL releases. + ctx = ssl.SSLContext(ssl.PROTOCOL_SSLv23) + ctx.verify_mode = ssl.CERT_REQUIRED + ctx.load_verify_locations(capath=CAPATH) + s = ctx.wrap_socket(socket.socket(socket.AF_INET)) + s.connect(("svn.python.org", 443)) + try: + cert = s.getpeercert() + self.assertTrue(cert) + finally: + s.close() + # Same with a bytes `capath` argument + ctx = ssl.SSLContext(ssl.PROTOCOL_SSLv23) + ctx.verify_mode = ssl.CERT_REQUIRED + ctx.load_verify_locations(capath=BYTES_CAPATH) + s = ctx.wrap_socket(socket.socket(socket.AF_INET)) + s.connect(("svn.python.org", 443)) + try: + cert = s.getpeercert() + self.assertTrue(cert) finally: s.close() @@ -1227,18 +1383,14 @@ if skip_expected: raise unittest.SkipTest("No SSL support") - global CERTFILE, SVN_PYTHON_ORG_ROOT_CERT - CERTFILE = os.path.join(os.path.dirname(__file__) or os.curdir, - "keycert.pem") - SVN_PYTHON_ORG_ROOT_CERT = os.path.join( - os.path.dirname(__file__) or os.curdir, - "https_svn_python_org_root.pem") - - if (not os.path.exists(CERTFILE) or - not os.path.exists(SVN_PYTHON_ORG_ROOT_CERT)): - raise support.TestFailed("Can't read certificate files!") + for filename in [ + CERTFILE, SVN_PYTHON_ORG_ROOT_CERT, BYTES_CERTFILE, + ONLYCERT, ONLYKEY, BYTES_ONLYCERT, BYTES_ONLYKEY, + BADCERT, BADKEY, EMPTYCERT]: + if not os.path.exists(filename): + raise support.TestFailed("Can't read certificate file %r" % filename) - tests = [BasicTests] + tests = [ContextTests, BasicSocketTests] if support.is_resource_enabled('network'): tests.append(NetworkedTests) Modified: python/branches/py3k-jit/Lib/test/test_sys.py ============================================================================== --- python/branches/py3k-jit/Lib/test/test_sys.py (original) +++ python/branches/py3k-jit/Lib/test/test_sys.py Tue May 18 19:58:30 2010 @@ -87,6 +87,8 @@ # Python/pythonrun.c::PyErr_PrintEx() is tricky. def test_exit(self): + import subprocess + self.assertRaises(TypeError, sys.exit, 42, 42) # call without argument @@ -141,11 +143,30 @@ self.fail("no exception") # test that the exit machinery handles SystemExits properly - import subprocess rc = subprocess.call([sys.executable, "-c", "raise SystemExit(47)"]) self.assertEqual(rc, 47) + def check_exit_message(code, expected): + process = subprocess.Popen([sys.executable, "-c", code], + stderr=subprocess.PIPE) + stdout, stderr = process.communicate() + self.assertEqual(process.returncode, 1) + self.assertTrue(stderr.startswith(expected), + "%s doesn't start with %s" % (ascii(stderr), ascii(expected))) + + # test that stderr buffer if flushed before the exit message is written + # into stderr + check_exit_message( + r'import sys; sys.stderr.write("unflushed,"); sys.exit("message")', + b"unflushed,message") + + # test that the exit message is written with backslashreplace error + # handler to stderr + check_exit_message( + r'import sys; sys.exit("surrogates:\uDCFF")', + b"surrogates:\\udcff") + def test_getdefaultencoding(self): self.assertRaises(TypeError, sys.getdefaultencoding, 42) # can't check more than the type, as the user might have changed it @@ -450,6 +471,23 @@ self.assertRaises(TypeError, sys.intern, S("abc")) + def test_main_invalid_unicode(self): + import locale + non_decodable = b"\xff" + encoding = locale.getpreferredencoding() + try: + non_decodable.decode(encoding) + except UnicodeDecodeError: + pass + else: + self.skipTest('%r is decodable with encoding %s' + % (non_decodable, encoding)) + code = b'print("' + non_decodable + b'")' + p = subprocess.Popen([sys.executable, "-c", code], stderr=subprocess.PIPE) + stdout, stderr = p.communicate() + self.assertEqual(p.returncode, 1) + self.assert_(b"UnicodeEncodeError:" in stderr, + "%r not in %s" % (b"UniodeEncodeError:", ascii(stderr))) def test_sys_flags(self): self.assertTrue(sys.flags) Modified: python/branches/py3k-jit/Lib/test/test_tarfile.py ============================================================================== --- python/branches/py3k-jit/Lib/test/test_tarfile.py (original) +++ python/branches/py3k-jit/Lib/test/test_tarfile.py Tue May 18 19:58:30 2010 @@ -1126,11 +1126,32 @@ format = tarfile.GNU_FORMAT + def test_bad_pax_header(self): + # Test for issue #8633. GNU tar <= 1.23 creates raw binary fields + # without a hdrcharset=BINARY header. + for encoding, name in (("utf8", "pax/bad-pax-\udce4\udcf6\udcfc"), + ("iso8859-1", "pax/bad-pax-\xe4\xf6\xfc"),): + with tarfile.open(tarname, encoding=encoding, errors="surrogateescape") as tar: + try: + t = tar.getmember(name) + except KeyError: + self.fail("unable to read bad GNU tar pax header") + class PAXUnicodeTest(UstarUnicodeTest): format = tarfile.PAX_FORMAT + def test_binary_header(self): + # Test a POSIX.1-2008 compatible header with a hdrcharset=BINARY field. + for encoding, name in (("utf8", "pax/hdrcharset-\udce4\udcf6\udcfc"), + ("iso8859-1", "pax/hdrcharset-\xe4\xf6\xfc"),): + with tarfile.open(tarname, encoding=encoding, errors="surrogateescape") as tar: + try: + t = tar.getmember(name) + except KeyError: + self.fail("unable to read POSIX.1-2008 binary header") + class AppendTest(unittest.TestCase): # Test append mode (cp. patch #1652681). Modified: python/branches/py3k-jit/Lib/test/testtar.tar ============================================================================== Binary files. No diff available. Modified: python/branches/py3k-jit/Lib/urllib/parse.py ============================================================================== --- python/branches/py3k-jit/Lib/urllib/parse.py (original) +++ python/branches/py3k-jit/Lib/urllib/parse.py Tue May 18 19:58:30 2010 @@ -41,7 +41,7 @@ uses_netloc = ['ftp', 'http', 'gopher', 'nntp', 'telnet', 'imap', 'wais', 'file', 'mms', 'https', 'shttp', 'snews', 'prospero', 'rtsp', 'rtspu', 'rsync', '', - 'svn', 'svn+ssh', 'sftp', 'nfs',' git', 'git+ssh'] + 'svn', 'svn+ssh', 'sftp', 'nfs', 'git', 'git+ssh'] non_hierarchical = ['gopher', 'hdl', 'mailto', 'news', 'telnet', 'wais', 'imap', 'snews', 'sip', 'sips'] uses_params = ['ftp', 'hdl', 'prospero', 'http', 'imap', @@ -307,17 +307,20 @@ """unquote_to_bytes('abc%20def') -> b'abc def'.""" # Note: strings are encoded as UTF-8. This is only an issue if it contains # unescaped non-ASCII characters, which URIs should not. + if not string: + return b'' if isinstance(string, str): string = string.encode('utf-8') res = string.split(b'%') - res[0] = res[0] - for i in range(1, len(res)): - item = res[i] + if len(res) == 1: + return string + string = res[0] + for item in res[1:]: try: - res[i] = bytes([int(item[:2], 16)]) + item[2:] + string += bytes([int(item[:2], 16)]) + item[2:] except ValueError: - res[i] = b'%' + item - return b''.join(res) + string += b'%' + item + return string def unquote(string, encoding='utf-8', errors='replace'): """Replace %xx escapes by their single-character equivalent. The optional @@ -329,36 +332,39 @@ unquote('abc%20def') -> 'abc def'. """ - if encoding is None: encoding = 'utf-8' - if errors is None: errors = 'replace' - # pct_sequence: contiguous sequence of percent-encoded bytes, decoded - # (list of single-byte bytes objects) - pct_sequence = [] + if not string: + return string res = string.split('%') - for i in range(1, len(res)): - item = res[i] + if len(res) == 1: + return string + if encoding is None: + encoding = 'utf-8' + if errors is None: + errors = 'replace' + # pct_sequence: contiguous sequence of percent-encoded bytes, decoded + pct_sequence = b'' + string = res[0] + for item in res[1:]: try: - if not item: raise ValueError - pct_sequence.append(bytes.fromhex(item[:2])) + if not item: + raise ValueError + pct_sequence += bytes.fromhex(item[:2]) rest = item[2:] + if not rest: + # This segment was just a single percent-encoded character. + # May be part of a sequence of code units, so delay decoding. + # (Stored in pct_sequence). + continue except ValueError: rest = '%' + item - if not rest: - # This segment was just a single percent-encoded character. - # May be part of a sequence of code units, so delay decoding. - # (Stored in pct_sequence). - res[i] = '' - else: - # Encountered non-percent-encoded characters. Flush the current - # pct_sequence. - res[i] = b''.join(pct_sequence).decode(encoding, errors) + rest - pct_sequence = [] + # Encountered non-percent-encoded characters. Flush the current + # pct_sequence. + string += pct_sequence.decode(encoding, errors) + rest + pct_sequence = b'' if pct_sequence: # Flush the final pct_sequence - # res[-1] will always be empty if pct_sequence != [] - assert not res[-1], "string=%r, res=%r" % (string, res) - res[-1] = b''.join(pct_sequence).decode(encoding, errors) - return ''.join(res) + string += pct_sequence.decode(encoding, errors) + return string def parse_qs(qs, keep_blank_values=False, strict_parsing=False): """Parse a query given as a string argument. @@ -439,7 +445,8 @@ b'abcdefghijklmnopqrstuvwxyz' b'0123456789' b'_.-') -_safe_quoters= {} +_ALWAYS_SAFE_BYTES = bytes(_ALWAYS_SAFE) +_safe_quoters = {} class Quoter(collections.defaultdict): """A mapping from bytes (in range(0,256)) to strings. @@ -451,7 +458,7 @@ # of cached keys don't call Python code at all). def __init__(self, safe): """safe: bytes object.""" - self.safe = _ALWAYS_SAFE.union(c for c in safe if c < 128) + self.safe = _ALWAYS_SAFE.union(safe) def __repr__(self): # Without this, will just display as a defaultdict @@ -459,7 +466,7 @@ def __missing__(self, b): # Handle a cache miss. Store quoted string in cache and return. - res = b in self.safe and chr(b) or ('%%%02X' % b) + res = chr(b) if b in self.safe else '%{:02X}'.format(b) self[b] = res return res @@ -493,6 +500,8 @@ errors='strict' (unsupported characters raise a UnicodeEncodeError). """ if isinstance(string, str): + if not string: + return string if encoding is None: encoding = 'utf-8' if errors is None: @@ -527,18 +536,22 @@ not perform string-to-bytes encoding. It always returns an ASCII string. quote_from_bytes(b'abc def\xab') -> 'abc%20def%AB' """ + if not isinstance(bs, (bytes, bytearray)): + raise TypeError("quote_from_bytes() expected bytes") + if not bs: + return '' if isinstance(safe, str): # Normalize 'safe' by converting to bytes and removing non-ASCII chars safe = safe.encode('ascii', 'ignore') - cachekey = bytes(safe) # In case it was a bytearray - if not (isinstance(bs, bytes) or isinstance(bs, bytearray)): - raise TypeError("quote_from_bytes() expected a bytes") + else: + safe = bytes([c for c in safe if c < 128]) + if not bs.rstrip(_ALWAYS_SAFE_BYTES + safe): + return bs.decode() try: - quoter = _safe_quoters[cachekey] + quoter = _safe_quoters[safe] except KeyError: - quoter = Quoter(safe) - _safe_quoters[cachekey] = quoter - return ''.join([quoter[char] for char in bs]) + _safe_quoters[safe] = quoter = Quoter(safe).__getitem__ + return ''.join([quoter(char) for char in bs]) def urlencode(query, doseq=False): """Encode a sequence of two-element tuples or dictionary into a URL query string. Modified: python/branches/py3k-jit/Lib/urllib/request.py ============================================================================== --- python/branches/py3k-jit/Lib/urllib/request.py (original) +++ python/branches/py3k-jit/Lib/urllib/request.py Tue May 18 19:58:30 2010 @@ -1965,7 +1965,7 @@ else: return self.open(newurl, data) - def get_user_passwd(self, host, realm, clear_cache = 0): + def get_user_passwd(self, host, realm, clear_cache=0): key = realm + '@' + host.lower() if key in self.auth_cache: if clear_cache: Modified: python/branches/py3k-jit/Makefile.pre.in ============================================================================== --- python/branches/py3k-jit/Makefile.pre.in (original) +++ python/branches/py3k-jit/Makefile.pre.in Tue May 18 19:58:30 2010 @@ -1233,7 +1233,7 @@ # files, which clobber removes as well pycremoval: -find $(srcdir) -name '*.py[co]' -exec rm -f {} ';' - -find $(srcdir) -name '__pycache__' -exec rmdir {} ';' + -find $(srcdir) -name '__pycache__' -exec rmdir {} '+' rmtestturds: -rm -f *BAD *GOOD *SKIPPED Modified: python/branches/py3k-jit/Misc/NEWS ============================================================================== --- python/branches/py3k-jit/Misc/NEWS (original) +++ python/branches/py3k-jit/Misc/NEWS Tue May 18 19:58:30 2010 @@ -12,6 +12,21 @@ Core and Builtins ----------------- +- PyObject_Dump() encodes unicode objects to utf8 with backslashreplace + (instead of strict) error handler to escape surrogates + +- Issue #8715: Create PyUnicode_EncodeFSDefault() function: Encode a Unicode + object to Py_FileSystemDefaultEncoding with the "surrogateescape" error + handler, and return bytes. If Py_FileSystemDefaultEncoding is not set, fall + back to UTF-8. + +- Enable shortcuts for common encodings in PyUnicode_AsEncodedString() for any + error handler, not only the default error handler (strict) + +- Issue #8610: Load file system codec at startup, and display a fatal error on + failure. Set the file system encoding to utf-8 (instead of None) if getting + the locale encoding failed, or if nl_langinfo(CODESET) function is missing. + - PyFile_FromFd() uses PyUnicode_DecodeFSDefault() instead of PyUnicode_FromString() to support surrogates in the filename and use the right encoding @@ -351,6 +366,19 @@ Library ------- +- Issue #8633: tarfile is now able to read and write archives with "raw" binary + pax headers as described in POSIX.1-2008. + +- Issue #1285086: Speed up urllib.parse functions: quote, quote_from_bytes, + unquote, unquote_to_bytes. + +- Issue #8688: Distutils now recalculates MANIFEST everytime. + +- Issue #8477: ssl.RAND_egd() and ssl._test_decode_cert() support str with + surrogates and bytes for the filename + +- Issue #8550: Add first class ``SSLContext`` objects to the ssl module. + - Issue #8681: Make the zlib module's error messages more informative when the zlib itself doesn't give any detailed explanation. @@ -377,9 +405,9 @@ - Issue #8573: asyncore _strerror() function might throw ValueError. -- Issue #8483: asyncore.dispatcher's __getattr__ method produced confusing - error messages when accessing undefined class attributes because of the cheap - inheritance with the underlying socket object. +- Issue #8483: asyncore.dispatcher's __getattr__ method produced confusing + error messages when accessing undefined class attributes because of the cheap + inheritance with the underlying socket object. The cheap inheritance has been deprecated. - Issue #4265: shutil.copyfile() was leaking file descriptors when disk fills. @@ -476,7 +504,7 @@ - Issue #6547: Added the ignore_dangling_symlinks option to shutil.copytree. -- Issue #1540112: Now allowing the choice of a copy function in +- Issue #1540112: Now allowing the choice of a copy function in shutil.copytree. - Issue #4814: timeout parameter is now applied also for connections resulting @@ -791,7 +819,7 @@ Initial patch by Brian Curtin. - Issue #7556: Make sure Distutils' msvc9compile reads and writes the - MSVC XML Manifest file in text mode so string patterns can be used + MSVC XML Manifest file in text mode so string patterns can be used in regular expressions. - Issue #7552: Removed line feed in the base64 Authorization header in @@ -822,13 +850,13 @@ - Issue #6986: Fix crash in the JSON C accelerator when called with the wrong parameter types. Patch by Victor Stinner. -- Issue #7457: added a read_pkg_file method to +- Issue #7457: added a read_pkg_file method to distutils.dist.DistributionMetadata. - logging: Added optional `secure` parameter to SMTPHandler, to enable use of TLS with authentication credentials. -- Issue #1923: Fixed the removal of meaningful spaces when PKG-INFO is +- Issue #1923: Fixed the removal of meaningful spaces when PKG-INFO is generated in Distutils. Patch by Stephen Emslie. - Issue #4120: Drop reference to CRT from manifest when building extensions with @@ -866,7 +894,7 @@ - Issue #6123: tarfile now opens empty archives correctly and consistently raises ReadError on empty files. -- Issue #7354: distutils.tests.test_msvc9compiler - dragfullwindows can +- Issue #7354: distutils.tests.test_msvc9compiler - dragfullwindows can be 2. - Issue #5037: Proxy the __bytes__ special method instead to __bytes__ instead @@ -904,12 +932,12 @@ - Issue #7893: ``unittest.TextTestResult`` is made public and a ``resultclass`` argument added to the TextTestRunner constructor allowing a different result class to be used without having to subclass. - + - Issue 7588: ``unittest.TextTestResult.getDescription`` now includes the test name in failure reports even if the test has a docstring. - Issue #3001: Add a C implementation of recursive locks which is used by - default when instantiating a `threading.RLock` object. This makes + default when instantiating a `threading.RLock` object. This makes recursive locks as fast as regular non-recursive locks (previously, they were slower by 10x to 15x). @@ -1120,6 +1148,12 @@ Extension Modules ----------------- +- Issue #8692: Optimize math.factorial: replace the previous naive + algorithm with an improved 'binary-split' algorithm that uses fewer + multiplications and allows many of the multiplications to be + performed using plain C integer arithmetic instead of PyLong + arithmetic. Also uses a lookup table for small arguments. + - Issue #8674: Fixed a number of incorrect or undefined-behaviour-inducing overflow checks in the audioop module. @@ -1349,7 +1383,7 @@ - Issue #7498: test_multiprocessing now uses test.support.find_unused_port instead of a hardcoded port number in test_rapid_restart. -- Issue #7431: use TESTFN in test_linecache instead of trying to create a +- Issue #7431: use TESTFN in test_linecache instead of trying to create a file in the Lib/test directory, which might be read-only for the user running the tests. @@ -2233,7 +2267,7 @@ - Issue #7071: byte-compilation in Distutils is now done with respect to sys.dont_write_bytecode. -- Issue #7066: archive_util.make_archive now restores the cwd if an error is +- Issue #7066: archive_util.make_archive now restores the cwd if an error is raised. Initial patch by Ezio Melotti. - Issue #6516: Added owner/group support when creating tar archives in Modified: python/branches/py3k-jit/Modules/_cursesmodule.c ============================================================================== --- python/branches/py3k-jit/Modules/_cursesmodule.c (original) +++ python/branches/py3k-jit/Modules/_cursesmodule.c Tue May 18 19:58:30 2010 @@ -33,66 +33,66 @@ /* -A number of SysV or ncurses functions don't have wrappers yet; if you -need a given function, add it and send a patch. See -http://www.python.org/dev/patches/ for instructions on how to submit -patches to Python. - -Here's a list of currently unsupported functions: - - addchnstr addchstr color_set define_key - del_curterm delscreen dupwin inchnstr inchstr innstr keyok - mcprint mvaddchnstr mvaddchstr mvcur mvinchnstr - mvinchstr mvinnstr mmvwaddchnstr mvwaddchstr - mvwinchnstr mvwinchstr mvwinnstr newterm - restartterm ripoffline scr_dump - scr_init scr_restore scr_set scrl set_curterm set_term setterm - tgetent tgetflag tgetnum tgetstr tgoto timeout tputs - vidattr vidputs waddchnstr waddchstr - wcolor_set winchnstr winchstr winnstr wmouse_trafo wscrl - -Low-priority: - slk_attr slk_attr_off slk_attr_on slk_attr_set slk_attroff - slk_attron slk_attrset slk_clear slk_color slk_init slk_label - slk_noutrefresh slk_refresh slk_restore slk_set slk_touch - -Menu extension (ncurses and probably SYSV): - current_item free_item free_menu item_count item_description - item_index item_init item_name item_opts item_opts_off - item_opts_on item_term item_userptr item_value item_visible - menu_back menu_driver menu_fore menu_format menu_grey - menu_init menu_items menu_mark menu_opts menu_opts_off - menu_opts_on menu_pad menu_pattern menu_request_by_name - menu_request_name menu_spacing menu_sub menu_term menu_userptr - menu_win new_item new_menu pos_menu_cursor post_menu - scale_menu set_current_item set_item_init set_item_opts - set_item_term set_item_userptr set_item_value set_menu_back - set_menu_fore set_menu_format set_menu_grey set_menu_init - set_menu_items set_menu_mark set_menu_opts set_menu_pad - set_menu_pattern set_menu_spacing set_menu_sub set_menu_term - set_menu_userptr set_menu_win set_top_row top_row unpost_menu - -Form extension (ncurses and probably SYSV): - current_field data_ahead data_behind dup_field - dynamic_fieldinfo field_arg field_back field_buffer - field_count field_fore field_index field_info field_init - field_just field_opts field_opts_off field_opts_on field_pad - field_status field_term field_type field_userptr form_driver - form_fields form_init form_opts form_opts_off form_opts_on - form_page form_request_by_name form_request_name form_sub - form_term form_userptr form_win free_field free_form - link_field link_fieldtype move_field new_field new_form - new_page pos_form_cursor post_form scale_form - set_current_field set_field_back set_field_buffer - set_field_fore set_field_init set_field_just set_field_opts - set_field_pad set_field_status set_field_term set_field_type - set_field_userptr set_fieldtype_arg set_fieldtype_choice - set_form_fields set_form_init set_form_opts set_form_page - set_form_sub set_form_term set_form_userptr set_form_win - set_max_field set_new_page unpost_form + A number of SysV or ncurses functions don't have wrappers yet; if you + need a given function, add it and send a patch. See + http://www.python.org/dev/patches/ for instructions on how to submit + patches to Python. + + Here's a list of currently unsupported functions: + + addchnstr addchstr color_set define_key + del_curterm delscreen dupwin inchnstr inchstr innstr keyok + mcprint mvaddchnstr mvaddchstr mvcur mvinchnstr + mvinchstr mvinnstr mmvwaddchnstr mvwaddchstr + mvwinchnstr mvwinchstr mvwinnstr newterm + restartterm ripoffline scr_dump + scr_init scr_restore scr_set scrl set_curterm set_term setterm + tgetent tgetflag tgetnum tgetstr tgoto timeout tputs + vidattr vidputs waddchnstr waddchstr + wcolor_set winchnstr winchstr winnstr wmouse_trafo wscrl + + Low-priority: + slk_attr slk_attr_off slk_attr_on slk_attr_set slk_attroff + slk_attron slk_attrset slk_clear slk_color slk_init slk_label + slk_noutrefresh slk_refresh slk_restore slk_set slk_touch + + Menu extension (ncurses and probably SYSV): + current_item free_item free_menu item_count item_description + item_index item_init item_name item_opts item_opts_off + item_opts_on item_term item_userptr item_value item_visible + menu_back menu_driver menu_fore menu_format menu_grey + menu_init menu_items menu_mark menu_opts menu_opts_off + menu_opts_on menu_pad menu_pattern menu_request_by_name + menu_request_name menu_spacing menu_sub menu_term menu_userptr + menu_win new_item new_menu pos_menu_cursor post_menu + scale_menu set_current_item set_item_init set_item_opts + set_item_term set_item_userptr set_item_value set_menu_back + set_menu_fore set_menu_format set_menu_grey set_menu_init + set_menu_items set_menu_mark set_menu_opts set_menu_pad + set_menu_pattern set_menu_spacing set_menu_sub set_menu_term + set_menu_userptr set_menu_win set_top_row top_row unpost_menu + + Form extension (ncurses and probably SYSV): + current_field data_ahead data_behind dup_field + dynamic_fieldinfo field_arg field_back field_buffer + field_count field_fore field_index field_info field_init + field_just field_opts field_opts_off field_opts_on field_pad + field_status field_term field_type field_userptr form_driver + form_fields form_init form_opts form_opts_off form_opts_on + form_page form_request_by_name form_request_name form_sub + form_term form_userptr form_win free_field free_form + link_field link_fieldtype move_field new_field new_form + new_page pos_form_cursor post_form scale_form + set_current_field set_field_back set_field_buffer + set_field_fore set_field_init set_field_just set_field_opts + set_field_pad set_field_status set_field_term set_field_type + set_field_userptr set_fieldtype_arg set_fieldtype_choice + set_form_fields set_form_init set_form_opts set_form_page + set_form_sub set_form_term set_form_userptr set_form_win + set_max_field set_new_page unpost_form - */ +*/ /* Release Number */ @@ -116,9 +116,9 @@ #define CURSES_MODULE #include "py_curses.h" -/* These prototypes are in , but including this header - #defines many common symbols (such as "lines") which breaks the - curses module in other ways. So the code will just specify +/* These prototypes are in , but including this header + #defines many common symbols (such as "lines") which breaks the + curses module in other ways. So the code will just specify explicit prototypes here. */ extern int setupterm(char *,int,int *); #ifdef __sgi @@ -148,23 +148,23 @@ static int initialisedcolors = FALSE; /* Utility Macros */ -#define PyCursesSetupTermCalled \ - if (initialised_setupterm != TRUE) { \ - PyErr_SetString(PyCursesError, \ - "must call (at least) setupterm() first"); \ - return 0; } - -#define PyCursesInitialised \ - if (initialised != TRUE) { \ - PyErr_SetString(PyCursesError, \ - "must call initscr() first"); \ - return 0; } - -#define PyCursesInitialisedColor \ - if (initialisedcolors != TRUE) { \ - PyErr_SetString(PyCursesError, \ - "must call start_color() first"); \ - return 0; } +#define PyCursesSetupTermCalled \ + if (initialised_setupterm != TRUE) { \ + PyErr_SetString(PyCursesError, \ + "must call (at least) setupterm() first"); \ + return 0; } + +#define PyCursesInitialised \ + if (initialised != TRUE) { \ + PyErr_SetString(PyCursesError, \ + "must call initscr() first"); \ + return 0; } + +#define PyCursesInitialisedColor \ + if (initialisedcolors != TRUE) { \ + PyErr_SetString(PyCursesError, \ + "must call start_color() first"); \ + return 0; } #ifndef MIN #define MIN(x,y) ((x) < (y) ? (x) : (y)) @@ -173,51 +173,51 @@ /* Utility Functions */ /* - * Check the return code from a curses function and return None + * Check the return code from a curses function and return None * or raise an exception as appropriate. These are exported using the - * capsule API. + * capsule API. */ static PyObject * PyCursesCheckERR(int code, char *fname) { - if (code != ERR) { - Py_INCREF(Py_None); - return Py_None; - } else { - if (fname == NULL) { - PyErr_SetString(PyCursesError, catchall_ERR); + if (code != ERR) { + Py_INCREF(Py_None); + return Py_None; } else { - PyErr_Format(PyCursesError, "%s() returned ERR", fname); + if (fname == NULL) { + PyErr_SetString(PyCursesError, catchall_ERR); + } else { + PyErr_Format(PyCursesError, "%s() returned ERR", fname); + } + return NULL; } - return NULL; - } } -static int +static int PyCurses_ConvertToChtype(PyObject *obj, chtype *ch) { - if (PyLong_CheckExact(obj)) { - int overflow; - /* XXX should the truncation by the cast also be reported - as an error? */ - *ch = (chtype) PyLong_AsLongAndOverflow(obj, &overflow); - if (overflow) - return 0; - } else if(PyBytes_Check(obj) - && (PyBytes_Size(obj) == 1)) { - *ch = (chtype) *PyBytes_AsString(obj); - } else if (PyUnicode_Check(obj) && PyUnicode_GetSize(obj) == 1) { - *ch = (chtype) *PyUnicode_AS_UNICODE(obj); - } else { - return 0; - } - return 1; + if (PyLong_CheckExact(obj)) { + int overflow; + /* XXX should the truncation by the cast also be reported + as an error? */ + *ch = (chtype) PyLong_AsLongAndOverflow(obj, &overflow); + if (overflow) + return 0; + } else if(PyBytes_Check(obj) + && (PyBytes_Size(obj) == 1)) { + *ch = (chtype) *PyBytes_AsString(obj); + } else if (PyUnicode_Check(obj) && PyUnicode_GetSize(obj) == 1) { + *ch = (chtype) *PyUnicode_AS_UNICODE(obj); + } else { + return 0; + } + return 1; } /* Function versions of the 3 functions for testing whether curses has been initialised or not. */ - + static int func_PyCursesSetupTermCalled(void) { PyCursesSetupTermCalled; @@ -250,56 +250,56 @@ TYPE - parameter Type ERGSTR - format string for construction of the return value PARSESTR - format string for argument parsing - */ +*/ -#define Window_NoArgNoReturnFunction(X) \ -static PyObject *PyCursesWindow_ ## X \ -(PyCursesWindowObject *self, PyObject *args) \ -{ return PyCursesCheckERR(X(self->win), # X); } - -#define Window_NoArgTrueFalseFunction(X) \ -static PyObject * PyCursesWindow_ ## X \ -(PyCursesWindowObject *self) \ -{ \ - if (X (self->win) == FALSE) { Py_INCREF(Py_False); return Py_False; } \ - else { Py_INCREF(Py_True); return Py_True; } } - -#define Window_NoArgNoReturnVoidFunction(X) \ -static PyObject * PyCursesWindow_ ## X \ -(PyCursesWindowObject *self) \ -{ \ - X(self->win); Py_INCREF(Py_None); return Py_None; } - -#define Window_NoArg2TupleReturnFunction(X, TYPE, ERGSTR) \ -static PyObject * PyCursesWindow_ ## X \ -(PyCursesWindowObject *self) \ -{ \ - TYPE arg1, arg2; \ - X(self->win,arg1,arg2); return Py_BuildValue(ERGSTR, arg1, arg2); } - -#define Window_OneArgNoReturnVoidFunction(X, TYPE, PARSESTR) \ -static PyObject * PyCursesWindow_ ## X \ -(PyCursesWindowObject *self, PyObject *args) \ -{ \ - TYPE arg1; \ - if (!PyArg_ParseTuple(args, PARSESTR, &arg1)) return NULL; \ - X(self->win,arg1); Py_INCREF(Py_None); return Py_None; } - -#define Window_OneArgNoReturnFunction(X, TYPE, PARSESTR) \ -static PyObject * PyCursesWindow_ ## X \ -(PyCursesWindowObject *self, PyObject *args) \ -{ \ - TYPE arg1; \ - if (!PyArg_ParseTuple(args,PARSESTR, &arg1)) return NULL; \ - return PyCursesCheckERR(X(self->win, arg1), # X); } - -#define Window_TwoArgNoReturnFunction(X, TYPE, PARSESTR) \ -static PyObject * PyCursesWindow_ ## X \ -(PyCursesWindowObject *self, PyObject *args) \ -{ \ - TYPE arg1, arg2; \ - if (!PyArg_ParseTuple(args,PARSESTR, &arg1, &arg2)) return NULL; \ - return PyCursesCheckERR(X(self->win, arg1, arg2), # X); } +#define Window_NoArgNoReturnFunction(X) \ + static PyObject *PyCursesWindow_ ## X \ + (PyCursesWindowObject *self, PyObject *args) \ + { return PyCursesCheckERR(X(self->win), # X); } + +#define Window_NoArgTrueFalseFunction(X) \ + static PyObject * PyCursesWindow_ ## X \ + (PyCursesWindowObject *self) \ + { \ + if (X (self->win) == FALSE) { Py_INCREF(Py_False); return Py_False; } \ + else { Py_INCREF(Py_True); return Py_True; } } + +#define Window_NoArgNoReturnVoidFunction(X) \ + static PyObject * PyCursesWindow_ ## X \ + (PyCursesWindowObject *self) \ + { \ + X(self->win); Py_INCREF(Py_None); return Py_None; } + +#define Window_NoArg2TupleReturnFunction(X, TYPE, ERGSTR) \ + static PyObject * PyCursesWindow_ ## X \ + (PyCursesWindowObject *self) \ + { \ + TYPE arg1, arg2; \ + X(self->win,arg1,arg2); return Py_BuildValue(ERGSTR, arg1, arg2); } + +#define Window_OneArgNoReturnVoidFunction(X, TYPE, PARSESTR) \ + static PyObject * PyCursesWindow_ ## X \ + (PyCursesWindowObject *self, PyObject *args) \ + { \ + TYPE arg1; \ + if (!PyArg_ParseTuple(args, PARSESTR, &arg1)) return NULL; \ + X(self->win,arg1); Py_INCREF(Py_None); return Py_None; } + +#define Window_OneArgNoReturnFunction(X, TYPE, PARSESTR) \ + static PyObject * PyCursesWindow_ ## X \ + (PyCursesWindowObject *self, PyObject *args) \ + { \ + TYPE arg1; \ + if (!PyArg_ParseTuple(args,PARSESTR, &arg1)) return NULL; \ + return PyCursesCheckERR(X(self->win, arg1), # X); } + +#define Window_TwoArgNoReturnFunction(X, TYPE, PARSESTR) \ + static PyObject * PyCursesWindow_ ## X \ + (PyCursesWindowObject *self, PyObject *args) \ + { \ + TYPE arg1, arg2; \ + if (!PyArg_ParseTuple(args,PARSESTR, &arg1, &arg2)) return NULL; \ + return PyCursesCheckERR(X(self->win, arg1, arg2), # X); } /* ------------- WINDOW routines --------------- */ @@ -360,19 +360,19 @@ static PyObject * PyCursesWindow_New(WINDOW *win) { - PyCursesWindowObject *wo; + PyCursesWindowObject *wo; - wo = PyObject_NEW(PyCursesWindowObject, &PyCursesWindow_Type); - if (wo == NULL) return NULL; - wo->win = win; - return (PyObject *)wo; + wo = PyObject_NEW(PyCursesWindowObject, &PyCursesWindow_Type); + if (wo == NULL) return NULL; + wo->win = win; + return (PyObject *)wo; } static void PyCursesWindow_Dealloc(PyCursesWindowObject *wo) { - if (wo->win != stdscr) delwin(wo->win); - PyObject_DEL(wo); + if (wo->win != stdscr) delwin(wo->win); + PyObject_DEL(wo); } /* Addch, Addstr, Addnstr */ @@ -380,287 +380,287 @@ static PyObject * PyCursesWindow_AddCh(PyCursesWindowObject *self, PyObject *args) { - int rtn, x, y, use_xy = FALSE; - PyObject *temp; - chtype ch = 0; - attr_t attr = A_NORMAL; - long lattr; - - switch (PyTuple_Size(args)) { - case 1: - if (!PyArg_ParseTuple(args, "O;ch or int", &temp)) - return NULL; - break; - case 2: - if (!PyArg_ParseTuple(args, "Ol;ch or int,attr", &temp, &lattr)) - return NULL; - attr = lattr; - break; - case 3: - if (!PyArg_ParseTuple(args,"iiO;y,x,ch or int", &y, &x, &temp)) - return NULL; - use_xy = TRUE; - break; - case 4: - if (!PyArg_ParseTuple(args,"iiOl;y,x,ch or int, attr", - &y, &x, &temp, &lattr)) - return NULL; - attr = lattr; - use_xy = TRUE; - break; - default: - PyErr_SetString(PyExc_TypeError, "addch requires 1 to 4 arguments"); - return NULL; - } - - if (!PyCurses_ConvertToChtype(temp, &ch)) { - PyErr_SetString(PyExc_TypeError, "argument 1 or 3 must be a ch or an int"); - return NULL; - } - - if (use_xy == TRUE) - rtn = mvwaddch(self->win,y,x, ch | attr); - else { - rtn = waddch(self->win, ch | attr); - } - return PyCursesCheckERR(rtn, "addch"); + int rtn, x, y, use_xy = FALSE; + PyObject *temp; + chtype ch = 0; + attr_t attr = A_NORMAL; + long lattr; + + switch (PyTuple_Size(args)) { + case 1: + if (!PyArg_ParseTuple(args, "O;ch or int", &temp)) + return NULL; + break; + case 2: + if (!PyArg_ParseTuple(args, "Ol;ch or int,attr", &temp, &lattr)) + return NULL; + attr = lattr; + break; + case 3: + if (!PyArg_ParseTuple(args,"iiO;y,x,ch or int", &y, &x, &temp)) + return NULL; + use_xy = TRUE; + break; + case 4: + if (!PyArg_ParseTuple(args,"iiOl;y,x,ch or int, attr", + &y, &x, &temp, &lattr)) + return NULL; + attr = lattr; + use_xy = TRUE; + break; + default: + PyErr_SetString(PyExc_TypeError, "addch requires 1 to 4 arguments"); + return NULL; + } + + if (!PyCurses_ConvertToChtype(temp, &ch)) { + PyErr_SetString(PyExc_TypeError, "argument 1 or 3 must be a ch or an int"); + return NULL; + } + + if (use_xy == TRUE) + rtn = mvwaddch(self->win,y,x, ch | attr); + else { + rtn = waddch(self->win, ch | attr); + } + return PyCursesCheckERR(rtn, "addch"); } static PyObject * PyCursesWindow_AddStr(PyCursesWindowObject *self, PyObject *args) { - int rtn; - int x, y; - char *str; - attr_t attr = A_NORMAL , attr_old = A_NORMAL; - long lattr; - int use_xy = FALSE, use_attr = FALSE; - - switch (PyTuple_Size(args)) { - case 1: - if (!PyArg_ParseTuple(args,"s;str", &str)) - return NULL; - break; - case 2: - if (!PyArg_ParseTuple(args,"sl;str,attr", &str, &lattr)) - return NULL; - attr = lattr; - use_attr = TRUE; - break; - case 3: - if (!PyArg_ParseTuple(args,"iis;int,int,str", &y, &x, &str)) - return NULL; - use_xy = TRUE; - break; - case 4: - if (!PyArg_ParseTuple(args,"iisl;int,int,str,attr", &y, &x, &str, &lattr)) - return NULL; - attr = lattr; - use_xy = use_attr = TRUE; - break; - default: - PyErr_SetString(PyExc_TypeError, "addstr requires 1 to 4 arguments"); - return NULL; - } - - if (use_attr == TRUE) { - attr_old = getattrs(self->win); - (void)wattrset(self->win,attr); - } - if (use_xy == TRUE) - rtn = mvwaddstr(self->win,y,x,str); - else - rtn = waddstr(self->win,str); - if (use_attr == TRUE) - (void)wattrset(self->win,attr_old); - return PyCursesCheckERR(rtn, "addstr"); + int rtn; + int x, y; + char *str; + attr_t attr = A_NORMAL , attr_old = A_NORMAL; + long lattr; + int use_xy = FALSE, use_attr = FALSE; + + switch (PyTuple_Size(args)) { + case 1: + if (!PyArg_ParseTuple(args,"s;str", &str)) + return NULL; + break; + case 2: + if (!PyArg_ParseTuple(args,"sl;str,attr", &str, &lattr)) + return NULL; + attr = lattr; + use_attr = TRUE; + break; + case 3: + if (!PyArg_ParseTuple(args,"iis;int,int,str", &y, &x, &str)) + return NULL; + use_xy = TRUE; + break; + case 4: + if (!PyArg_ParseTuple(args,"iisl;int,int,str,attr", &y, &x, &str, &lattr)) + return NULL; + attr = lattr; + use_xy = use_attr = TRUE; + break; + default: + PyErr_SetString(PyExc_TypeError, "addstr requires 1 to 4 arguments"); + return NULL; + } + + if (use_attr == TRUE) { + attr_old = getattrs(self->win); + (void)wattrset(self->win,attr); + } + if (use_xy == TRUE) + rtn = mvwaddstr(self->win,y,x,str); + else + rtn = waddstr(self->win,str); + if (use_attr == TRUE) + (void)wattrset(self->win,attr_old); + return PyCursesCheckERR(rtn, "addstr"); } static PyObject * PyCursesWindow_AddNStr(PyCursesWindowObject *self, PyObject *args) { - int rtn, x, y, n; - char *str; - attr_t attr = A_NORMAL , attr_old = A_NORMAL; - long lattr; - int use_xy = FALSE, use_attr = FALSE; - - switch (PyTuple_Size(args)) { - case 2: - if (!PyArg_ParseTuple(args,"si;str,n", &str, &n)) - return NULL; - break; - case 3: - if (!PyArg_ParseTuple(args,"sil;str,n,attr", &str, &n, &lattr)) - return NULL; - attr = lattr; - use_attr = TRUE; - break; - case 4: - if (!PyArg_ParseTuple(args,"iisi;y,x,str,n", &y, &x, &str, &n)) - return NULL; - use_xy = TRUE; - break; - case 5: - if (!PyArg_ParseTuple(args,"iisil;y,x,str,n,attr", &y, &x, &str, &n, &lattr)) - return NULL; - attr = lattr; - use_xy = use_attr = TRUE; - break; - default: - PyErr_SetString(PyExc_TypeError, "addnstr requires 2 to 5 arguments"); - return NULL; - } - - if (use_attr == TRUE) { - attr_old = getattrs(self->win); - (void)wattrset(self->win,attr); - } - if (use_xy == TRUE) - rtn = mvwaddnstr(self->win,y,x,str,n); - else - rtn = waddnstr(self->win,str,n); - if (use_attr == TRUE) - (void)wattrset(self->win,attr_old); - return PyCursesCheckERR(rtn, "addnstr"); + int rtn, x, y, n; + char *str; + attr_t attr = A_NORMAL , attr_old = A_NORMAL; + long lattr; + int use_xy = FALSE, use_attr = FALSE; + + switch (PyTuple_Size(args)) { + case 2: + if (!PyArg_ParseTuple(args,"si;str,n", &str, &n)) + return NULL; + break; + case 3: + if (!PyArg_ParseTuple(args,"sil;str,n,attr", &str, &n, &lattr)) + return NULL; + attr = lattr; + use_attr = TRUE; + break; + case 4: + if (!PyArg_ParseTuple(args,"iisi;y,x,str,n", &y, &x, &str, &n)) + return NULL; + use_xy = TRUE; + break; + case 5: + if (!PyArg_ParseTuple(args,"iisil;y,x,str,n,attr", &y, &x, &str, &n, &lattr)) + return NULL; + attr = lattr; + use_xy = use_attr = TRUE; + break; + default: + PyErr_SetString(PyExc_TypeError, "addnstr requires 2 to 5 arguments"); + return NULL; + } + + if (use_attr == TRUE) { + attr_old = getattrs(self->win); + (void)wattrset(self->win,attr); + } + if (use_xy == TRUE) + rtn = mvwaddnstr(self->win,y,x,str,n); + else + rtn = waddnstr(self->win,str,n); + if (use_attr == TRUE) + (void)wattrset(self->win,attr_old); + return PyCursesCheckERR(rtn, "addnstr"); } static PyObject * PyCursesWindow_Bkgd(PyCursesWindowObject *self, PyObject *args) { - PyObject *temp; - chtype bkgd; - attr_t attr = A_NORMAL; - long lattr; + PyObject *temp; + chtype bkgd; + attr_t attr = A_NORMAL; + long lattr; - switch (PyTuple_Size(args)) { + switch (PyTuple_Size(args)) { case 1: - if (!PyArg_ParseTuple(args, "O;ch or int", &temp)) - return NULL; - break; + if (!PyArg_ParseTuple(args, "O;ch or int", &temp)) + return NULL; + break; case 2: - if (!PyArg_ParseTuple(args,"Ol;ch or int,attr", &temp, &lattr)) - return NULL; - attr = lattr; - break; + if (!PyArg_ParseTuple(args,"Ol;ch or int,attr", &temp, &lattr)) + return NULL; + attr = lattr; + break; default: - PyErr_SetString(PyExc_TypeError, "bkgd requires 1 or 2 arguments"); - return NULL; - } + PyErr_SetString(PyExc_TypeError, "bkgd requires 1 or 2 arguments"); + return NULL; + } - if (!PyCurses_ConvertToChtype(temp, &bkgd)) { - PyErr_SetString(PyExc_TypeError, "argument 1 or 3 must be a ch or an int"); - return NULL; - } + if (!PyCurses_ConvertToChtype(temp, &bkgd)) { + PyErr_SetString(PyExc_TypeError, "argument 1 or 3 must be a ch or an int"); + return NULL; + } - return PyCursesCheckERR(wbkgd(self->win, bkgd | attr), "bkgd"); + return PyCursesCheckERR(wbkgd(self->win, bkgd | attr), "bkgd"); } static PyObject * PyCursesWindow_AttrOff(PyCursesWindowObject *self, PyObject *args) { - long lattr; - if (!PyArg_ParseTuple(args,"l;attr", &lattr)) - return NULL; - return PyCursesCheckERR(wattroff(self->win, (attr_t)lattr), "attroff"); + long lattr; + if (!PyArg_ParseTuple(args,"l;attr", &lattr)) + return NULL; + return PyCursesCheckERR(wattroff(self->win, (attr_t)lattr), "attroff"); } static PyObject * PyCursesWindow_AttrOn(PyCursesWindowObject *self, PyObject *args) { - long lattr; - if (!PyArg_ParseTuple(args,"l;attr", &lattr)) - return NULL; - return PyCursesCheckERR(wattron(self->win, (attr_t)lattr), "attron"); + long lattr; + if (!PyArg_ParseTuple(args,"l;attr", &lattr)) + return NULL; + return PyCursesCheckERR(wattron(self->win, (attr_t)lattr), "attron"); } static PyObject * PyCursesWindow_AttrSet(PyCursesWindowObject *self, PyObject *args) { - long lattr; - if (!PyArg_ParseTuple(args,"l;attr", &lattr)) - return NULL; - return PyCursesCheckERR(wattrset(self->win, (attr_t)lattr), "attrset"); + long lattr; + if (!PyArg_ParseTuple(args,"l;attr", &lattr)) + return NULL; + return PyCursesCheckERR(wattrset(self->win, (attr_t)lattr), "attrset"); } static PyObject * PyCursesWindow_BkgdSet(PyCursesWindowObject *self, PyObject *args) { - PyObject *temp; - chtype bkgd; - attr_t attr = A_NORMAL; - long lattr; + PyObject *temp; + chtype bkgd; + attr_t attr = A_NORMAL; + long lattr; - switch (PyTuple_Size(args)) { + switch (PyTuple_Size(args)) { case 1: - if (!PyArg_ParseTuple(args, "O;ch or int", &temp)) - return NULL; - break; + if (!PyArg_ParseTuple(args, "O;ch or int", &temp)) + return NULL; + break; case 2: - if (!PyArg_ParseTuple(args,"Ol;ch or int,attr", &temp, &lattr)) - return NULL; - attr = lattr; - break; + if (!PyArg_ParseTuple(args,"Ol;ch or int,attr", &temp, &lattr)) + return NULL; + attr = lattr; + break; default: - PyErr_SetString(PyExc_TypeError, "bkgdset requires 1 or 2 arguments"); - return NULL; - } + PyErr_SetString(PyExc_TypeError, "bkgdset requires 1 or 2 arguments"); + return NULL; + } - if (!PyCurses_ConvertToChtype(temp, &bkgd)) { - PyErr_SetString(PyExc_TypeError, "argument 1 must be a ch or an int"); - return NULL; - } + if (!PyCurses_ConvertToChtype(temp, &bkgd)) { + PyErr_SetString(PyExc_TypeError, "argument 1 must be a ch or an int"); + return NULL; + } - wbkgdset(self->win, bkgd | attr); - return PyCursesCheckERR(0, "bkgdset"); + wbkgdset(self->win, bkgd | attr); + return PyCursesCheckERR(0, "bkgdset"); } static PyObject * PyCursesWindow_Border(PyCursesWindowObject *self, PyObject *args) { - PyObject *temp[8]; - chtype ch[8]; - int i; - - /* Clear the array of parameters */ - for(i=0; i<8; i++) { - temp[i] = NULL; - ch[i] = 0; - } - - if (!PyArg_ParseTuple(args,"|OOOOOOOO;ls,rs,ts,bs,tl,tr,bl,br", - &temp[0], &temp[1], &temp[2], &temp[3], - &temp[4], &temp[5], &temp[6], &temp[7])) - return NULL; - - for(i=0; i<8; i++) { - if (temp[i] != NULL && !PyCurses_ConvertToChtype(temp[i], &ch[i])) { - PyErr_Format(PyExc_TypeError, - "argument %i must be a ch or an int", i+1); - return NULL; - } - } - - wborder(self->win, - ch[0], ch[1], ch[2], ch[3], - ch[4], ch[5], ch[6], ch[7]); - Py_INCREF(Py_None); - return Py_None; + PyObject *temp[8]; + chtype ch[8]; + int i; + + /* Clear the array of parameters */ + for(i=0; i<8; i++) { + temp[i] = NULL; + ch[i] = 0; + } + + if (!PyArg_ParseTuple(args,"|OOOOOOOO;ls,rs,ts,bs,tl,tr,bl,br", + &temp[0], &temp[1], &temp[2], &temp[3], + &temp[4], &temp[5], &temp[6], &temp[7])) + return NULL; + + for(i=0; i<8; i++) { + if (temp[i] != NULL && !PyCurses_ConvertToChtype(temp[i], &ch[i])) { + PyErr_Format(PyExc_TypeError, + "argument %i must be a ch or an int", i+1); + return NULL; + } + } + + wborder(self->win, + ch[0], ch[1], ch[2], ch[3], + ch[4], ch[5], ch[6], ch[7]); + Py_INCREF(Py_None); + return Py_None; } static PyObject * PyCursesWindow_Box(PyCursesWindowObject *self, PyObject *args) { - chtype ch1=0,ch2=0; - switch(PyTuple_Size(args)){ - case 0: break; - default: - if (!PyArg_ParseTuple(args,"ll;vertint,horint", &ch1, &ch2)) - return NULL; - } - box(self->win,ch1,ch2); - Py_INCREF(Py_None); - return Py_None; + chtype ch1=0,ch2=0; + switch(PyTuple_Size(args)){ + case 0: break; + default: + if (!PyArg_ParseTuple(args,"ll;vertint,horint", &ch1, &ch2)) + return NULL; + } + box(self->win,ch1,ch2); + Py_INCREF(Py_None); + return Py_None; } #if defined(HAVE_NCURSES_H) || defined(MVWDELCH_IS_EXPRESSION) @@ -668,10 +668,10 @@ #else int py_mvwdelch(WINDOW *w, int y, int x) { - mvwdelch(w,y,x); - /* On HP/UX, mvwdelch already returns. On other systems, - we may well run into this return statement. */ - return 0; + mvwdelch(w,y,x); + /* On HP/UX, mvwdelch already returns. On other systems, + we may well run into this return statement. */ + return 0; } #endif @@ -680,603 +680,603 @@ static PyObject * PyCursesWindow_ChgAt(PyCursesWindowObject *self, PyObject *args) { - int rtn; - int x, y; - int num = -1; - short color; - attr_t attr = A_NORMAL; - long lattr; - int use_xy = FALSE; + int rtn; + int x, y; + int num = -1; + short color; + attr_t attr = A_NORMAL; + long lattr; + int use_xy = FALSE; - switch (PyTuple_Size(args)) { - case 1: - if (!PyArg_ParseTuple(args,"l;attr", &lattr)) - return NULL; - attr = lattr; - break; - case 2: - if (!PyArg_ParseTuple(args,"il;n,attr", &num, &lattr)) - return NULL; - attr = lattr; - break; - case 3: - if (!PyArg_ParseTuple(args,"iil;int,int,attr", &y, &x, &lattr)) - return NULL; - attr = lattr; - use_xy = TRUE; - break; - case 4: - if (!PyArg_ParseTuple(args,"iiil;int,int,n,attr", &y, &x, &num, &lattr)) - return NULL; - attr = lattr; - use_xy = TRUE; - break; - default: - PyErr_SetString(PyExc_TypeError, "chgat requires 1 to 4 arguments"); - return NULL; - } - - color = (short)((attr >> 8) & 0xff); - attr = attr - (color << 8); - - if (use_xy == TRUE) { - rtn = mvwchgat(self->win,y,x,num,attr,color,NULL); - touchline(self->win,y,1); - } else { - getyx(self->win,y,x); - rtn = wchgat(self->win,num,attr,color,NULL); - touchline(self->win,y,1); - } - return PyCursesCheckERR(rtn, "chgat"); + switch (PyTuple_Size(args)) { + case 1: + if (!PyArg_ParseTuple(args,"l;attr", &lattr)) + return NULL; + attr = lattr; + break; + case 2: + if (!PyArg_ParseTuple(args,"il;n,attr", &num, &lattr)) + return NULL; + attr = lattr; + break; + case 3: + if (!PyArg_ParseTuple(args,"iil;int,int,attr", &y, &x, &lattr)) + return NULL; + attr = lattr; + use_xy = TRUE; + break; + case 4: + if (!PyArg_ParseTuple(args,"iiil;int,int,n,attr", &y, &x, &num, &lattr)) + return NULL; + attr = lattr; + use_xy = TRUE; + break; + default: + PyErr_SetString(PyExc_TypeError, "chgat requires 1 to 4 arguments"); + return NULL; + } + + color = (short)((attr >> 8) & 0xff); + attr = attr - (color << 8); + + if (use_xy == TRUE) { + rtn = mvwchgat(self->win,y,x,num,attr,color,NULL); + touchline(self->win,y,1); + } else { + getyx(self->win,y,x); + rtn = wchgat(self->win,num,attr,color,NULL); + touchline(self->win,y,1); + } + return PyCursesCheckERR(rtn, "chgat"); } static PyObject * PyCursesWindow_DelCh(PyCursesWindowObject *self, PyObject *args) { - int rtn; - int x, y; + int rtn; + int x, y; - switch (PyTuple_Size(args)) { - case 0: - rtn = wdelch(self->win); - break; - case 2: - if (!PyArg_ParseTuple(args,"ii;y,x", &y, &x)) - return NULL; - rtn = py_mvwdelch(self->win,y,x); - break; - default: - PyErr_SetString(PyExc_TypeError, "delch requires 0 or 2 arguments"); - return NULL; - } - return PyCursesCheckERR(rtn, "[mv]wdelch"); + switch (PyTuple_Size(args)) { + case 0: + rtn = wdelch(self->win); + break; + case 2: + if (!PyArg_ParseTuple(args,"ii;y,x", &y, &x)) + return NULL; + rtn = py_mvwdelch(self->win,y,x); + break; + default: + PyErr_SetString(PyExc_TypeError, "delch requires 0 or 2 arguments"); + return NULL; + } + return PyCursesCheckERR(rtn, "[mv]wdelch"); } static PyObject * PyCursesWindow_DerWin(PyCursesWindowObject *self, PyObject *args) { - WINDOW *win; - int nlines, ncols, begin_y, begin_x; + WINDOW *win; + int nlines, ncols, begin_y, begin_x; - nlines = 0; - ncols = 0; - switch (PyTuple_Size(args)) { - case 2: - if (!PyArg_ParseTuple(args,"ii;begin_y,begin_x",&begin_y,&begin_x)) - return NULL; - break; - case 4: - if (!PyArg_ParseTuple(args, "iiii;nlines,ncols,begin_y,begin_x", - &nlines,&ncols,&begin_y,&begin_x)) - return NULL; - break; - default: - PyErr_SetString(PyExc_TypeError, "derwin requires 2 or 4 arguments"); - return NULL; - } - - win = derwin(self->win,nlines,ncols,begin_y,begin_x); - - if (win == NULL) { - PyErr_SetString(PyCursesError, catchall_NULL); - return NULL; - } + nlines = 0; + ncols = 0; + switch (PyTuple_Size(args)) { + case 2: + if (!PyArg_ParseTuple(args,"ii;begin_y,begin_x",&begin_y,&begin_x)) + return NULL; + break; + case 4: + if (!PyArg_ParseTuple(args, "iiii;nlines,ncols,begin_y,begin_x", + &nlines,&ncols,&begin_y,&begin_x)) + return NULL; + break; + default: + PyErr_SetString(PyExc_TypeError, "derwin requires 2 or 4 arguments"); + return NULL; + } - return (PyObject *)PyCursesWindow_New(win); + win = derwin(self->win,nlines,ncols,begin_y,begin_x); + + if (win == NULL) { + PyErr_SetString(PyCursesError, catchall_NULL); + return NULL; + } + + return (PyObject *)PyCursesWindow_New(win); } static PyObject * PyCursesWindow_EchoChar(PyCursesWindowObject *self, PyObject *args) { - PyObject *temp; - chtype ch; - attr_t attr = A_NORMAL; - long lattr; - - switch (PyTuple_Size(args)) { - case 1: - if (!PyArg_ParseTuple(args,"O;ch or int", &temp)) - return NULL; - break; - case 2: - if (!PyArg_ParseTuple(args,"Ol;ch or int,attr", &temp, &lattr)) - return NULL; - attr = lattr; - break; - default: - PyErr_SetString(PyExc_TypeError, "echochar requires 1 or 2 arguments"); - - - return NULL; - } - - if (!PyCurses_ConvertToChtype(temp, &ch)) { - PyErr_SetString(PyExc_TypeError, "argument 1 must be a ch or an int"); - return NULL; - } - + PyObject *temp; + chtype ch; + attr_t attr = A_NORMAL; + long lattr; + + switch (PyTuple_Size(args)) { + case 1: + if (!PyArg_ParseTuple(args,"O;ch or int", &temp)) + return NULL; + break; + case 2: + if (!PyArg_ParseTuple(args,"Ol;ch or int,attr", &temp, &lattr)) + return NULL; + attr = lattr; + break; + default: + PyErr_SetString(PyExc_TypeError, "echochar requires 1 or 2 arguments"); + + + return NULL; + } + + if (!PyCurses_ConvertToChtype(temp, &ch)) { + PyErr_SetString(PyExc_TypeError, "argument 1 must be a ch or an int"); + return NULL; + } + #ifdef WINDOW_HAS_FLAGS - if (self->win->_flags & _ISPAD) - return PyCursesCheckERR(pechochar(self->win, ch | attr), - "echochar"); - else + if (self->win->_flags & _ISPAD) + return PyCursesCheckERR(pechochar(self->win, ch | attr), + "echochar"); + else #endif - return PyCursesCheckERR(wechochar(self->win, ch | attr), - "echochar"); + return PyCursesCheckERR(wechochar(self->win, ch | attr), + "echochar"); } #ifdef NCURSES_MOUSE_VERSION static PyObject * PyCursesWindow_Enclose(PyCursesWindowObject *self, PyObject *args) { - int x, y; - if (!PyArg_ParseTuple(args,"ii;y,x", &y, &x)) - return NULL; + int x, y; + if (!PyArg_ParseTuple(args,"ii;y,x", &y, &x)) + return NULL; - return PyLong_FromLong( wenclose(self->win,y,x) ); + return PyLong_FromLong( wenclose(self->win,y,x) ); } #endif static PyObject * PyCursesWindow_GetBkgd(PyCursesWindowObject *self) { - return PyLong_FromLong((long) getbkgd(self->win)); + return PyLong_FromLong((long) getbkgd(self->win)); } static PyObject * PyCursesWindow_GetCh(PyCursesWindowObject *self, PyObject *args) { - int x, y; - int rtn; + int x, y; + int rtn; - switch (PyTuple_Size(args)) { - case 0: - Py_BEGIN_ALLOW_THREADS - rtn = wgetch(self->win); - Py_END_ALLOW_THREADS - break; - case 2: - if (!PyArg_ParseTuple(args,"ii;y,x",&y,&x)) - return NULL; - Py_BEGIN_ALLOW_THREADS - rtn = mvwgetch(self->win,y,x); - Py_END_ALLOW_THREADS - break; - default: - PyErr_SetString(PyExc_TypeError, "getch requires 0 or 2 arguments"); - return NULL; - } - return PyLong_FromLong((long)rtn); + switch (PyTuple_Size(args)) { + case 0: + Py_BEGIN_ALLOW_THREADS + rtn = wgetch(self->win); + Py_END_ALLOW_THREADS + break; + case 2: + if (!PyArg_ParseTuple(args,"ii;y,x",&y,&x)) + return NULL; + Py_BEGIN_ALLOW_THREADS + rtn = mvwgetch(self->win,y,x); + Py_END_ALLOW_THREADS + break; + default: + PyErr_SetString(PyExc_TypeError, "getch requires 0 or 2 arguments"); + return NULL; + } + return PyLong_FromLong((long)rtn); } static PyObject * PyCursesWindow_GetKey(PyCursesWindowObject *self, PyObject *args) { - int x, y; - int rtn; + int x, y; + int rtn; - switch (PyTuple_Size(args)) { - case 0: - Py_BEGIN_ALLOW_THREADS - rtn = wgetch(self->win); - Py_END_ALLOW_THREADS - break; - case 2: - if (!PyArg_ParseTuple(args,"ii;y,x",&y,&x)) - return NULL; - Py_BEGIN_ALLOW_THREADS - rtn = mvwgetch(self->win,y,x); - Py_END_ALLOW_THREADS - break; - default: - PyErr_SetString(PyExc_TypeError, "getkey requires 0 or 2 arguments"); - return NULL; - } - if (rtn == ERR) { - /* getch() returns ERR in nodelay mode */ - PyErr_SetString(PyCursesError, "no input"); - return NULL; - } else if (rtn<=255) { - return Py_BuildValue("C", rtn); - } else { - const char *knp; + switch (PyTuple_Size(args)) { + case 0: + Py_BEGIN_ALLOW_THREADS + rtn = wgetch(self->win); + Py_END_ALLOW_THREADS + break; + case 2: + if (!PyArg_ParseTuple(args,"ii;y,x",&y,&x)) + return NULL; + Py_BEGIN_ALLOW_THREADS + rtn = mvwgetch(self->win,y,x); + Py_END_ALLOW_THREADS + break; + default: + PyErr_SetString(PyExc_TypeError, "getkey requires 0 or 2 arguments"); + return NULL; + } + if (rtn == ERR) { + /* getch() returns ERR in nodelay mode */ + PyErr_SetString(PyCursesError, "no input"); + return NULL; + } else if (rtn<=255) { + return Py_BuildValue("C", rtn); + } else { + const char *knp; #if defined(__NetBSD__) - knp = unctrl(rtn); + knp = unctrl(rtn); #else - knp = keyname(rtn); + knp = keyname(rtn); #endif - return PyUnicode_FromString((knp == NULL) ? "" : knp); - } + return PyUnicode_FromString((knp == NULL) ? "" : knp); + } } static PyObject * PyCursesWindow_GetStr(PyCursesWindowObject *self, PyObject *args) { - int x, y, n; - char rtn[1024]; /* This should be big enough.. I hope */ - int rtn2; - - switch (PyTuple_Size(args)) { - case 0: - Py_BEGIN_ALLOW_THREADS - rtn2 = wgetnstr(self->win,rtn, 1023); - Py_END_ALLOW_THREADS - break; - case 1: - if (!PyArg_ParseTuple(args,"i;n", &n)) - return NULL; - Py_BEGIN_ALLOW_THREADS - rtn2 = wgetnstr(self->win,rtn,MIN(n, 1023)); - Py_END_ALLOW_THREADS - break; - case 2: - if (!PyArg_ParseTuple(args,"ii;y,x",&y,&x)) - return NULL; - Py_BEGIN_ALLOW_THREADS + int x, y, n; + char rtn[1024]; /* This should be big enough.. I hope */ + int rtn2; + + switch (PyTuple_Size(args)) { + case 0: + Py_BEGIN_ALLOW_THREADS + rtn2 = wgetnstr(self->win,rtn, 1023); + Py_END_ALLOW_THREADS + break; + case 1: + if (!PyArg_ParseTuple(args,"i;n", &n)) + return NULL; + Py_BEGIN_ALLOW_THREADS + rtn2 = wgetnstr(self->win,rtn,MIN(n, 1023)); + Py_END_ALLOW_THREADS + break; + case 2: + if (!PyArg_ParseTuple(args,"ii;y,x",&y,&x)) + return NULL; + Py_BEGIN_ALLOW_THREADS #ifdef STRICT_SYSV_CURSES - rtn2 = wmove(self->win,y,x)==ERR ? ERR : wgetnstr(self->win, rtn, 1023); + rtn2 = wmove(self->win,y,x)==ERR ? ERR : wgetnstr(self->win, rtn, 1023); #else - rtn2 = mvwgetnstr(self->win,y,x,rtn, 1023); + rtn2 = mvwgetnstr(self->win,y,x,rtn, 1023); #endif - Py_END_ALLOW_THREADS - break; - case 3: - if (!PyArg_ParseTuple(args,"iii;y,x,n", &y, &x, &n)) - return NULL; + Py_END_ALLOW_THREADS + break; + case 3: + if (!PyArg_ParseTuple(args,"iii;y,x,n", &y, &x, &n)) + return NULL; #ifdef STRICT_SYSV_CURSES - Py_BEGIN_ALLOW_THREADS - rtn2 = wmove(self->win,y,x)==ERR ? ERR : - wgetnstr(self->win, rtn, MIN(n, 1023)); - Py_END_ALLOW_THREADS + Py_BEGIN_ALLOW_THREADS + rtn2 = wmove(self->win,y,x)==ERR ? ERR : + wgetnstr(self->win, rtn, MIN(n, 1023)); + Py_END_ALLOW_THREADS #else - Py_BEGIN_ALLOW_THREADS - rtn2 = mvwgetnstr(self->win, y, x, rtn, MIN(n, 1023)); - Py_END_ALLOW_THREADS -#endif - break; - default: - PyErr_SetString(PyExc_TypeError, "getstr requires 0 to 3 arguments"); - return NULL; - } - if (rtn2 == ERR) - rtn[0] = 0; - return PyBytes_FromString(rtn); + Py_BEGIN_ALLOW_THREADS + rtn2 = mvwgetnstr(self->win, y, x, rtn, MIN(n, 1023)); + Py_END_ALLOW_THREADS +#endif + break; + default: + PyErr_SetString(PyExc_TypeError, "getstr requires 0 to 3 arguments"); + return NULL; + } + if (rtn2 == ERR) + rtn[0] = 0; + return PyBytes_FromString(rtn); } static PyObject * PyCursesWindow_Hline(PyCursesWindowObject *self, PyObject *args) { - PyObject *temp; - chtype ch; - int n, x, y, code = OK; - attr_t attr = A_NORMAL; - long lattr; - - switch (PyTuple_Size(args)) { - case 2: - if (!PyArg_ParseTuple(args, "Oi;ch or int,n", &temp, &n)) - return NULL; - break; - case 3: - if (!PyArg_ParseTuple(args, "Oil;ch or int,n,attr", &temp, &n, &lattr)) - return NULL; - attr = lattr; - break; - case 4: - if (!PyArg_ParseTuple(args, "iiOi;y,x,ch or int,n", &y, &x, &temp, &n)) - return NULL; - code = wmove(self->win, y, x); - break; - case 5: - if (!PyArg_ParseTuple(args, "iiOil; y,x,ch or int,n,attr", - &y, &x, &temp, &n, &lattr)) - return NULL; - attr = lattr; - code = wmove(self->win, y, x); - break; - default: - PyErr_SetString(PyExc_TypeError, "hline requires 2 to 5 arguments"); - return NULL; - } + PyObject *temp; + chtype ch; + int n, x, y, code = OK; + attr_t attr = A_NORMAL; + long lattr; - if (code != ERR) { - if (!PyCurses_ConvertToChtype(temp, &ch)) { - PyErr_SetString(PyExc_TypeError, - "argument 1 or 3 must be a ch or an int"); - return NULL; - } - return PyCursesCheckERR(whline(self->win, ch | attr, n), "hline"); - } else - return PyCursesCheckERR(code, "wmove"); + switch (PyTuple_Size(args)) { + case 2: + if (!PyArg_ParseTuple(args, "Oi;ch or int,n", &temp, &n)) + return NULL; + break; + case 3: + if (!PyArg_ParseTuple(args, "Oil;ch or int,n,attr", &temp, &n, &lattr)) + return NULL; + attr = lattr; + break; + case 4: + if (!PyArg_ParseTuple(args, "iiOi;y,x,ch or int,n", &y, &x, &temp, &n)) + return NULL; + code = wmove(self->win, y, x); + break; + case 5: + if (!PyArg_ParseTuple(args, "iiOil; y,x,ch or int,n,attr", + &y, &x, &temp, &n, &lattr)) + return NULL; + attr = lattr; + code = wmove(self->win, y, x); + break; + default: + PyErr_SetString(PyExc_TypeError, "hline requires 2 to 5 arguments"); + return NULL; + } + + if (code != ERR) { + if (!PyCurses_ConvertToChtype(temp, &ch)) { + PyErr_SetString(PyExc_TypeError, + "argument 1 or 3 must be a ch or an int"); + return NULL; + } + return PyCursesCheckERR(whline(self->win, ch | attr, n), "hline"); + } else + return PyCursesCheckERR(code, "wmove"); } static PyObject * PyCursesWindow_InsCh(PyCursesWindowObject *self, PyObject *args) { - int rtn, x, y, use_xy = FALSE; - PyObject *temp; - chtype ch = 0; - attr_t attr = A_NORMAL; - long lattr; - - switch (PyTuple_Size(args)) { - case 1: - if (!PyArg_ParseTuple(args, "O;ch or int", &temp)) - return NULL; - break; - case 2: - if (!PyArg_ParseTuple(args, "Ol;ch or int,attr", &temp, &lattr)) - return NULL; - attr = lattr; - break; - case 3: - if (!PyArg_ParseTuple(args,"iiO;y,x,ch or int", &y, &x, &temp)) - return NULL; - use_xy = TRUE; - break; - case 4: - if (!PyArg_ParseTuple(args,"iiOl;y,x,ch or int, attr", &y, &x, &temp, &lattr)) - return NULL; - attr = lattr; - use_xy = TRUE; - break; - default: - PyErr_SetString(PyExc_TypeError, "insch requires 1 or 4 arguments"); - return NULL; - } - - if (!PyCurses_ConvertToChtype(temp, &ch)) { - PyErr_SetString(PyExc_TypeError, - "argument 1 or 3 must be a ch or an int"); - return NULL; - } - - if (use_xy == TRUE) - rtn = mvwinsch(self->win,y,x, ch | attr); - else { - rtn = winsch(self->win, ch | attr); - } - return PyCursesCheckERR(rtn, "insch"); + int rtn, x, y, use_xy = FALSE; + PyObject *temp; + chtype ch = 0; + attr_t attr = A_NORMAL; + long lattr; + + switch (PyTuple_Size(args)) { + case 1: + if (!PyArg_ParseTuple(args, "O;ch or int", &temp)) + return NULL; + break; + case 2: + if (!PyArg_ParseTuple(args, "Ol;ch or int,attr", &temp, &lattr)) + return NULL; + attr = lattr; + break; + case 3: + if (!PyArg_ParseTuple(args,"iiO;y,x,ch or int", &y, &x, &temp)) + return NULL; + use_xy = TRUE; + break; + case 4: + if (!PyArg_ParseTuple(args,"iiOl;y,x,ch or int, attr", &y, &x, &temp, &lattr)) + return NULL; + attr = lattr; + use_xy = TRUE; + break; + default: + PyErr_SetString(PyExc_TypeError, "insch requires 1 or 4 arguments"); + return NULL; + } + + if (!PyCurses_ConvertToChtype(temp, &ch)) { + PyErr_SetString(PyExc_TypeError, + "argument 1 or 3 must be a ch or an int"); + return NULL; + } + + if (use_xy == TRUE) + rtn = mvwinsch(self->win,y,x, ch | attr); + else { + rtn = winsch(self->win, ch | attr); + } + return PyCursesCheckERR(rtn, "insch"); } static PyObject * PyCursesWindow_InCh(PyCursesWindowObject *self, PyObject *args) { - int x, y, rtn; + int x, y, rtn; - switch (PyTuple_Size(args)) { - case 0: - rtn = winch(self->win); - break; - case 2: - if (!PyArg_ParseTuple(args,"ii;y,x",&y,&x)) - return NULL; - rtn = mvwinch(self->win,y,x); - break; - default: - PyErr_SetString(PyExc_TypeError, "inch requires 0 or 2 arguments"); - return NULL; - } - return PyLong_FromLong((long) rtn); + switch (PyTuple_Size(args)) { + case 0: + rtn = winch(self->win); + break; + case 2: + if (!PyArg_ParseTuple(args,"ii;y,x",&y,&x)) + return NULL; + rtn = mvwinch(self->win,y,x); + break; + default: + PyErr_SetString(PyExc_TypeError, "inch requires 0 or 2 arguments"); + return NULL; + } + return PyLong_FromLong((long) rtn); } static PyObject * PyCursesWindow_InStr(PyCursesWindowObject *self, PyObject *args) { - int x, y, n; - char rtn[1024]; /* This should be big enough.. I hope */ - int rtn2; - - switch (PyTuple_Size(args)) { - case 0: - rtn2 = winnstr(self->win,rtn, 1023); - break; - case 1: - if (!PyArg_ParseTuple(args,"i;n", &n)) - return NULL; - rtn2 = winnstr(self->win,rtn,MIN(n,1023)); - break; - case 2: - if (!PyArg_ParseTuple(args,"ii;y,x",&y,&x)) - return NULL; - rtn2 = mvwinnstr(self->win,y,x,rtn,1023); - break; - case 3: - if (!PyArg_ParseTuple(args, "iii;y,x,n", &y, &x, &n)) - return NULL; - rtn2 = mvwinnstr(self->win, y, x, rtn, MIN(n,1023)); - break; - default: - PyErr_SetString(PyExc_TypeError, "instr requires 0 or 3 arguments"); - return NULL; - } - if (rtn2 == ERR) - rtn[0] = 0; - return PyBytes_FromString(rtn); + int x, y, n; + char rtn[1024]; /* This should be big enough.. I hope */ + int rtn2; + + switch (PyTuple_Size(args)) { + case 0: + rtn2 = winnstr(self->win,rtn, 1023); + break; + case 1: + if (!PyArg_ParseTuple(args,"i;n", &n)) + return NULL; + rtn2 = winnstr(self->win,rtn,MIN(n,1023)); + break; + case 2: + if (!PyArg_ParseTuple(args,"ii;y,x",&y,&x)) + return NULL; + rtn2 = mvwinnstr(self->win,y,x,rtn,1023); + break; + case 3: + if (!PyArg_ParseTuple(args, "iii;y,x,n", &y, &x, &n)) + return NULL; + rtn2 = mvwinnstr(self->win, y, x, rtn, MIN(n,1023)); + break; + default: + PyErr_SetString(PyExc_TypeError, "instr requires 0 or 3 arguments"); + return NULL; + } + if (rtn2 == ERR) + rtn[0] = 0; + return PyBytes_FromString(rtn); } static PyObject * PyCursesWindow_InsStr(PyCursesWindowObject *self, PyObject *args) { - int rtn; - int x, y; - char *str; - attr_t attr = A_NORMAL , attr_old = A_NORMAL; - long lattr; - int use_xy = FALSE, use_attr = FALSE; - - switch (PyTuple_Size(args)) { - case 1: - if (!PyArg_ParseTuple(args,"s;str", &str)) - return NULL; - break; - case 2: - if (!PyArg_ParseTuple(args,"sl;str,attr", &str, &lattr)) - return NULL; - attr = lattr; - use_attr = TRUE; - break; - case 3: - if (!PyArg_ParseTuple(args,"iis;y,x,str", &y, &x, &str)) - return NULL; - use_xy = TRUE; - break; - case 4: - if (!PyArg_ParseTuple(args,"iisl;y,x,str,attr", &y, &x, &str, &lattr)) - return NULL; - attr = lattr; - use_xy = use_attr = TRUE; - break; - default: - PyErr_SetString(PyExc_TypeError, "insstr requires 1 to 4 arguments"); - return NULL; - } - - if (use_attr == TRUE) { - attr_old = getattrs(self->win); - (void)wattrset(self->win,attr); - } - if (use_xy == TRUE) - rtn = mvwinsstr(self->win,y,x,str); - else - rtn = winsstr(self->win,str); - if (use_attr == TRUE) - (void)wattrset(self->win,attr_old); - return PyCursesCheckERR(rtn, "insstr"); + int rtn; + int x, y; + char *str; + attr_t attr = A_NORMAL , attr_old = A_NORMAL; + long lattr; + int use_xy = FALSE, use_attr = FALSE; + + switch (PyTuple_Size(args)) { + case 1: + if (!PyArg_ParseTuple(args,"s;str", &str)) + return NULL; + break; + case 2: + if (!PyArg_ParseTuple(args,"sl;str,attr", &str, &lattr)) + return NULL; + attr = lattr; + use_attr = TRUE; + break; + case 3: + if (!PyArg_ParseTuple(args,"iis;y,x,str", &y, &x, &str)) + return NULL; + use_xy = TRUE; + break; + case 4: + if (!PyArg_ParseTuple(args,"iisl;y,x,str,attr", &y, &x, &str, &lattr)) + return NULL; + attr = lattr; + use_xy = use_attr = TRUE; + break; + default: + PyErr_SetString(PyExc_TypeError, "insstr requires 1 to 4 arguments"); + return NULL; + } + + if (use_attr == TRUE) { + attr_old = getattrs(self->win); + (void)wattrset(self->win,attr); + } + if (use_xy == TRUE) + rtn = mvwinsstr(self->win,y,x,str); + else + rtn = winsstr(self->win,str); + if (use_attr == TRUE) + (void)wattrset(self->win,attr_old); + return PyCursesCheckERR(rtn, "insstr"); } static PyObject * PyCursesWindow_InsNStr(PyCursesWindowObject *self, PyObject *args) { - int rtn, x, y, n; - char *str; - attr_t attr = A_NORMAL , attr_old = A_NORMAL; - long lattr; - int use_xy = FALSE, use_attr = FALSE; - - switch (PyTuple_Size(args)) { - case 2: - if (!PyArg_ParseTuple(args,"si;str,n", &str, &n)) - return NULL; - break; - case 3: - if (!PyArg_ParseTuple(args,"sil;str,n,attr", &str, &n, &lattr)) - return NULL; - attr = lattr; - use_attr = TRUE; - break; - case 4: - if (!PyArg_ParseTuple(args,"iisi;y,x,str,n", &y, &x, &str, &n)) - return NULL; - use_xy = TRUE; - break; - case 5: - if (!PyArg_ParseTuple(args,"iisil;y,x,str,n,attr", &y, &x, &str, &n, &lattr)) - return NULL; - attr = lattr; - use_xy = use_attr = TRUE; - break; - default: - PyErr_SetString(PyExc_TypeError, "insnstr requires 2 to 5 arguments"); - return NULL; - } - - if (use_attr == TRUE) { - attr_old = getattrs(self->win); - (void)wattrset(self->win,attr); - } - if (use_xy == TRUE) - rtn = mvwinsnstr(self->win,y,x,str,n); - else - rtn = winsnstr(self->win,str,n); - if (use_attr == TRUE) - (void)wattrset(self->win,attr_old); - return PyCursesCheckERR(rtn, "insnstr"); + int rtn, x, y, n; + char *str; + attr_t attr = A_NORMAL , attr_old = A_NORMAL; + long lattr; + int use_xy = FALSE, use_attr = FALSE; + + switch (PyTuple_Size(args)) { + case 2: + if (!PyArg_ParseTuple(args,"si;str,n", &str, &n)) + return NULL; + break; + case 3: + if (!PyArg_ParseTuple(args,"sil;str,n,attr", &str, &n, &lattr)) + return NULL; + attr = lattr; + use_attr = TRUE; + break; + case 4: + if (!PyArg_ParseTuple(args,"iisi;y,x,str,n", &y, &x, &str, &n)) + return NULL; + use_xy = TRUE; + break; + case 5: + if (!PyArg_ParseTuple(args,"iisil;y,x,str,n,attr", &y, &x, &str, &n, &lattr)) + return NULL; + attr = lattr; + use_xy = use_attr = TRUE; + break; + default: + PyErr_SetString(PyExc_TypeError, "insnstr requires 2 to 5 arguments"); + return NULL; + } + + if (use_attr == TRUE) { + attr_old = getattrs(self->win); + (void)wattrset(self->win,attr); + } + if (use_xy == TRUE) + rtn = mvwinsnstr(self->win,y,x,str,n); + else + rtn = winsnstr(self->win,str,n); + if (use_attr == TRUE) + (void)wattrset(self->win,attr_old); + return PyCursesCheckERR(rtn, "insnstr"); } static PyObject * PyCursesWindow_Is_LineTouched(PyCursesWindowObject *self, PyObject *args) { - int line, erg; - if (!PyArg_ParseTuple(args,"i;line", &line)) - return NULL; - erg = is_linetouched(self->win, line); - if (erg == ERR) { - PyErr_SetString(PyExc_TypeError, - "is_linetouched: line number outside of boundaries"); - return NULL; - } else - if (erg == FALSE) { - Py_INCREF(Py_False); - return Py_False; - } else { - Py_INCREF(Py_True); - return Py_True; - } + int line, erg; + if (!PyArg_ParseTuple(args,"i;line", &line)) + return NULL; + erg = is_linetouched(self->win, line); + if (erg == ERR) { + PyErr_SetString(PyExc_TypeError, + "is_linetouched: line number outside of boundaries"); + return NULL; + } else + if (erg == FALSE) { + Py_INCREF(Py_False); + return Py_False; + } else { + Py_INCREF(Py_True); + return Py_True; + } } static PyObject * PyCursesWindow_NoOutRefresh(PyCursesWindowObject *self, PyObject *args) { - int pminrow,pmincol,sminrow,smincol,smaxrow,smaxcol; - int rtn; + int pminrow,pmincol,sminrow,smincol,smaxrow,smaxcol; + int rtn; #ifndef WINDOW_HAS_FLAGS - if (0) + if (0) #else - if (self->win->_flags & _ISPAD) + if (self->win->_flags & _ISPAD) #endif - { - switch(PyTuple_Size(args)) { - case 6: - if (!PyArg_ParseTuple(args, - "iiiiii;" \ - "pminrow,pmincol,sminrow,smincol,smaxrow,smaxcol", - &pminrow, &pmincol, &sminrow, - &smincol, &smaxrow, &smaxcol)) - return NULL; - Py_BEGIN_ALLOW_THREADS - rtn = pnoutrefresh(self->win, - pminrow, pmincol, sminrow, - smincol, smaxrow, smaxcol); - Py_END_ALLOW_THREADS - return PyCursesCheckERR(rtn, "pnoutrefresh"); - default: - PyErr_SetString(PyCursesError, - "noutrefresh() called for a pad " - "requires 6 arguments"); - return NULL; - } - } else { - if (!PyArg_ParseTuple(args, ":noutrefresh")) - return NULL; - - Py_BEGIN_ALLOW_THREADS - rtn = wnoutrefresh(self->win); - Py_END_ALLOW_THREADS - return PyCursesCheckERR(rtn, "wnoutrefresh"); - } + { + switch(PyTuple_Size(args)) { + case 6: + if (!PyArg_ParseTuple(args, + "iiiiii;" \ + "pminrow,pmincol,sminrow,smincol,smaxrow,smaxcol", + &pminrow, &pmincol, &sminrow, + &smincol, &smaxrow, &smaxcol)) + return NULL; + Py_BEGIN_ALLOW_THREADS + rtn = pnoutrefresh(self->win, + pminrow, pmincol, sminrow, + smincol, smaxrow, smaxcol); + Py_END_ALLOW_THREADS + return PyCursesCheckERR(rtn, "pnoutrefresh"); + default: + PyErr_SetString(PyCursesError, + "noutrefresh() called for a pad " + "requires 6 arguments"); + return NULL; + } + } else { + if (!PyArg_ParseTuple(args, ":noutrefresh")) + return NULL; + + Py_BEGIN_ALLOW_THREADS + rtn = wnoutrefresh(self->win); + Py_END_ALLOW_THREADS + return PyCursesCheckERR(rtn, "wnoutrefresh"); + } } static PyObject * @@ -1286,34 +1286,34 @@ int use_copywin = FALSE; int sminrow, smincol, dminrow, dmincol, dmaxrow, dmaxcol; int rtn; - + switch (PyTuple_Size(args)) { case 1: - if (!PyArg_ParseTuple(args, "O!;window object", - &PyCursesWindow_Type, &temp)) - return NULL; - break; + if (!PyArg_ParseTuple(args, "O!;window object", + &PyCursesWindow_Type, &temp)) + return NULL; + break; case 7: - if (!PyArg_ParseTuple(args, "O!iiiiii;window object, int, int, int, int, int, int", - &PyCursesWindow_Type, &temp, &sminrow, &smincol, - &dminrow, &dmincol, &dmaxrow, &dmaxcol)) - return NULL; - use_copywin = TRUE; - break; - default: - PyErr_SetString(PyExc_TypeError, - "overlay requires one or seven arguments"); - return NULL; + if (!PyArg_ParseTuple(args, "O!iiiiii;window object, int, int, int, int, int, int", + &PyCursesWindow_Type, &temp, &sminrow, &smincol, + &dminrow, &dmincol, &dmaxrow, &dmaxcol)) + return NULL; + use_copywin = TRUE; + break; + default: + PyErr_SetString(PyExc_TypeError, + "overlay requires one or seven arguments"); + return NULL; } if (use_copywin == TRUE) { - rtn = copywin(self->win, temp->win, sminrow, smincol, - dminrow, dmincol, dmaxrow, dmaxcol, TRUE); - return PyCursesCheckERR(rtn, "copywin"); + rtn = copywin(self->win, temp->win, sminrow, smincol, + dminrow, dmincol, dmaxrow, dmaxcol, TRUE); + return PyCursesCheckERR(rtn, "copywin"); } else { - rtn = overlay(self->win, temp->win); - return PyCursesCheckERR(rtn, "overlay"); + rtn = overlay(self->win, temp->win); + return PyCursesCheckERR(rtn, "overlay"); } } @@ -1324,377 +1324,377 @@ int use_copywin = FALSE; int sminrow, smincol, dminrow, dmincol, dmaxrow, dmaxcol; int rtn; - + switch (PyTuple_Size(args)) { case 1: - if (!PyArg_ParseTuple(args, "O!;window object", - &PyCursesWindow_Type, &temp)) - return NULL; - break; + if (!PyArg_ParseTuple(args, "O!;window object", + &PyCursesWindow_Type, &temp)) + return NULL; + break; case 7: - if (!PyArg_ParseTuple(args, "O!iiiiii;window object, int, int, int, int, int, int", - &PyCursesWindow_Type, &temp, &sminrow, &smincol, - &dminrow, &dmincol, &dmaxrow, &dmaxcol)) - return NULL; - use_copywin = TRUE; - break; - default: - PyErr_SetString(PyExc_TypeError, - "overwrite requires one or seven arguments"); - return NULL; + if (!PyArg_ParseTuple(args, "O!iiiiii;window object, int, int, int, int, int, int", + &PyCursesWindow_Type, &temp, &sminrow, &smincol, + &dminrow, &dmincol, &dmaxrow, &dmaxcol)) + return NULL; + use_copywin = TRUE; + break; + default: + PyErr_SetString(PyExc_TypeError, + "overwrite requires one or seven arguments"); + return NULL; } if (use_copywin == TRUE) { - rtn = copywin(self->win, temp->win, sminrow, smincol, - dminrow, dmincol, dmaxrow, dmaxcol, FALSE); + rtn = copywin(self->win, temp->win, sminrow, smincol, + dminrow, dmincol, dmaxrow, dmaxcol, FALSE); return PyCursesCheckERR(rtn, "copywin"); } else { - rtn = overwrite(self->win, temp->win); - return PyCursesCheckERR(rtn, "overwrite"); + rtn = overwrite(self->win, temp->win); + return PyCursesCheckERR(rtn, "overwrite"); } } static PyObject * PyCursesWindow_PutWin(PyCursesWindowObject *self, PyObject *stream) { - /* We have to simulate this by writing to a temporary FILE*, - then reading back, then writing to the argument stream. */ - char fn[100]; - int fd; - FILE *fp; - PyObject *res; - - strcpy(fn, "/tmp/py.curses.putwin.XXXXXX"); - fd = mkstemp(fn); - if (fd < 0) - return PyErr_SetFromErrnoWithFilename(PyExc_IOError, fn); - fp = fdopen(fd, "wb+"); - if (fp == NULL) { - close(fd); - remove(fn); - return PyErr_SetFromErrnoWithFilename(PyExc_IOError, fn); - } - res = PyCursesCheckERR(putwin(self->win, fp), "putwin"); - if (res == NULL) { + /* We have to simulate this by writing to a temporary FILE*, + then reading back, then writing to the argument stream. */ + char fn[100]; + int fd; + FILE *fp; + PyObject *res; + + strcpy(fn, "/tmp/py.curses.putwin.XXXXXX"); + fd = mkstemp(fn); + if (fd < 0) + return PyErr_SetFromErrnoWithFilename(PyExc_IOError, fn); + fp = fdopen(fd, "wb+"); + if (fp == NULL) { + close(fd); + remove(fn); + return PyErr_SetFromErrnoWithFilename(PyExc_IOError, fn); + } + res = PyCursesCheckERR(putwin(self->win, fp), "putwin"); + if (res == NULL) { + fclose(fp); + remove(fn); + return res; + } + fseek(fp, 0, 0); + while (1) { + char buf[BUFSIZ]; + Py_ssize_t n = fread(buf, 1, BUFSIZ, fp); + if (n <= 0) + break; + Py_DECREF(res); + res = PyObject_CallMethod(stream, "write", "y#", buf, n); + if (res == NULL) + break; + } fclose(fp); remove(fn); return res; - } - fseek(fp, 0, 0); - while (1) { - char buf[BUFSIZ]; - Py_ssize_t n = fread(buf, 1, BUFSIZ, fp); - if (n <= 0) - break; - Py_DECREF(res); - res = PyObject_CallMethod(stream, "write", "y#", buf, n); - if (res == NULL) - break; - } - fclose(fp); - remove(fn); - return res; } static PyObject * PyCursesWindow_RedrawLine(PyCursesWindowObject *self, PyObject *args) { - int beg, num; - if (!PyArg_ParseTuple(args, "ii;beg,num", &beg, &num)) - return NULL; - return PyCursesCheckERR(wredrawln(self->win,beg,num), "redrawln"); + int beg, num; + if (!PyArg_ParseTuple(args, "ii;beg,num", &beg, &num)) + return NULL; + return PyCursesCheckERR(wredrawln(self->win,beg,num), "redrawln"); } static PyObject * PyCursesWindow_Refresh(PyCursesWindowObject *self, PyObject *args) { - int pminrow,pmincol,sminrow,smincol,smaxrow,smaxcol; - int rtn; - + int pminrow,pmincol,sminrow,smincol,smaxrow,smaxcol; + int rtn; + #ifndef WINDOW_HAS_FLAGS - if (0) + if (0) #else - if (self->win->_flags & _ISPAD) + if (self->win->_flags & _ISPAD) #endif - { - switch(PyTuple_Size(args)) { - case 6: - if (!PyArg_ParseTuple(args, - "iiiiii;" \ - "pminrow,pmincol,sminrow,smincol,smaxrow,smaxcol", - &pminrow, &pmincol, &sminrow, - &smincol, &smaxrow, &smaxcol)) - return NULL; - - Py_BEGIN_ALLOW_THREADS - rtn = prefresh(self->win, - pminrow, pmincol, sminrow, - smincol, smaxrow, smaxcol); - Py_END_ALLOW_THREADS - return PyCursesCheckERR(rtn, "prefresh"); - default: - PyErr_SetString(PyCursesError, - "refresh() for a pad requires 6 arguments"); - return NULL; - } - } else { - if (!PyArg_ParseTuple(args, ":refresh")) - return NULL; - Py_BEGIN_ALLOW_THREADS - rtn = wrefresh(self->win); - Py_END_ALLOW_THREADS - return PyCursesCheckERR(rtn, "prefresh"); - } + { + switch(PyTuple_Size(args)) { + case 6: + if (!PyArg_ParseTuple(args, + "iiiiii;" \ + "pminrow,pmincol,sminrow,smincol,smaxrow,smaxcol", + &pminrow, &pmincol, &sminrow, + &smincol, &smaxrow, &smaxcol)) + return NULL; + + Py_BEGIN_ALLOW_THREADS + rtn = prefresh(self->win, + pminrow, pmincol, sminrow, + smincol, smaxrow, smaxcol); + Py_END_ALLOW_THREADS + return PyCursesCheckERR(rtn, "prefresh"); + default: + PyErr_SetString(PyCursesError, + "refresh() for a pad requires 6 arguments"); + return NULL; + } + } else { + if (!PyArg_ParseTuple(args, ":refresh")) + return NULL; + Py_BEGIN_ALLOW_THREADS + rtn = wrefresh(self->win); + Py_END_ALLOW_THREADS + return PyCursesCheckERR(rtn, "prefresh"); + } } static PyObject * PyCursesWindow_SetScrollRegion(PyCursesWindowObject *self, PyObject *args) { - int x, y; - if (!PyArg_ParseTuple(args,"ii;top, bottom",&y,&x)) - return NULL; - return PyCursesCheckERR(wsetscrreg(self->win,y,x), "wsetscrreg"); + int x, y; + if (!PyArg_ParseTuple(args,"ii;top, bottom",&y,&x)) + return NULL; + return PyCursesCheckERR(wsetscrreg(self->win,y,x), "wsetscrreg"); } static PyObject * PyCursesWindow_SubWin(PyCursesWindowObject *self, PyObject *args) { - WINDOW *win; - int nlines, ncols, begin_y, begin_x; + WINDOW *win; + int nlines, ncols, begin_y, begin_x; - nlines = 0; - ncols = 0; - switch (PyTuple_Size(args)) { - case 2: - if (!PyArg_ParseTuple(args,"ii;begin_y,begin_x",&begin_y,&begin_x)) - return NULL; - break; - case 4: - if (!PyArg_ParseTuple(args, "iiii;nlines,ncols,begin_y,begin_x", - &nlines,&ncols,&begin_y,&begin_x)) - return NULL; - break; - default: - PyErr_SetString(PyExc_TypeError, "subwin requires 2 or 4 arguments"); - return NULL; - } + nlines = 0; + ncols = 0; + switch (PyTuple_Size(args)) { + case 2: + if (!PyArg_ParseTuple(args,"ii;begin_y,begin_x",&begin_y,&begin_x)) + return NULL; + break; + case 4: + if (!PyArg_ParseTuple(args, "iiii;nlines,ncols,begin_y,begin_x", + &nlines,&ncols,&begin_y,&begin_x)) + return NULL; + break; + default: + PyErr_SetString(PyExc_TypeError, "subwin requires 2 or 4 arguments"); + return NULL; + } - /* printf("Subwin: %i %i %i %i \n", nlines, ncols, begin_y, begin_x); */ + /* printf("Subwin: %i %i %i %i \n", nlines, ncols, begin_y, begin_x); */ #ifdef WINDOW_HAS_FLAGS - if (self->win->_flags & _ISPAD) - win = subpad(self->win, nlines, ncols, begin_y, begin_x); - else -#endif - win = subwin(self->win, nlines, ncols, begin_y, begin_x); - - if (win == NULL) { - PyErr_SetString(PyCursesError, catchall_NULL); - return NULL; - } - - return (PyObject *)PyCursesWindow_New(win); + if (self->win->_flags & _ISPAD) + win = subpad(self->win, nlines, ncols, begin_y, begin_x); + else +#endif + win = subwin(self->win, nlines, ncols, begin_y, begin_x); + + if (win == NULL) { + PyErr_SetString(PyCursesError, catchall_NULL); + return NULL; + } + + return (PyObject *)PyCursesWindow_New(win); } static PyObject * PyCursesWindow_Scroll(PyCursesWindowObject *self, PyObject *args) { - int nlines; - switch(PyTuple_Size(args)) { - case 0: - return PyCursesCheckERR(scroll(self->win), "scroll"); - case 1: - if (!PyArg_ParseTuple(args, "i;nlines", &nlines)) - return NULL; - return PyCursesCheckERR(wscrl(self->win, nlines), "scroll"); - default: - PyErr_SetString(PyExc_TypeError, "scroll requires 0 or 1 arguments"); - return NULL; - } + int nlines; + switch(PyTuple_Size(args)) { + case 0: + return PyCursesCheckERR(scroll(self->win), "scroll"); + case 1: + if (!PyArg_ParseTuple(args, "i;nlines", &nlines)) + return NULL; + return PyCursesCheckERR(wscrl(self->win, nlines), "scroll"); + default: + PyErr_SetString(PyExc_TypeError, "scroll requires 0 or 1 arguments"); + return NULL; + } } static PyObject * PyCursesWindow_TouchLine(PyCursesWindowObject *self, PyObject *args) { - int st, cnt, val; - switch (PyTuple_Size(args)) { - case 2: - if (!PyArg_ParseTuple(args,"ii;start,count",&st,&cnt)) - return NULL; - return PyCursesCheckERR(touchline(self->win,st,cnt), "touchline"); - case 3: - if (!PyArg_ParseTuple(args, "iii;start,count,val", &st, &cnt, &val)) - return NULL; - return PyCursesCheckERR(wtouchln(self->win, st, cnt, val), "touchline"); - default: - PyErr_SetString(PyExc_TypeError, "touchline requires 2 or 3 arguments"); - return NULL; - } + int st, cnt, val; + switch (PyTuple_Size(args)) { + case 2: + if (!PyArg_ParseTuple(args,"ii;start,count",&st,&cnt)) + return NULL; + return PyCursesCheckERR(touchline(self->win,st,cnt), "touchline"); + case 3: + if (!PyArg_ParseTuple(args, "iii;start,count,val", &st, &cnt, &val)) + return NULL; + return PyCursesCheckERR(wtouchln(self->win, st, cnt, val), "touchline"); + default: + PyErr_SetString(PyExc_TypeError, "touchline requires 2 or 3 arguments"); + return NULL; + } } static PyObject * PyCursesWindow_Vline(PyCursesWindowObject *self, PyObject *args) { - PyObject *temp; - chtype ch; - int n, x, y, code = OK; - attr_t attr = A_NORMAL; - long lattr; - - switch (PyTuple_Size(args)) { - case 2: - if (!PyArg_ParseTuple(args, "Oi;ch or int,n", &temp, &n)) - return NULL; - break; - case 3: - if (!PyArg_ParseTuple(args, "Oil;ch or int,n,attr", &temp, &n, &lattr)) - return NULL; - attr = lattr; - break; - case 4: - if (!PyArg_ParseTuple(args, "iiOi;y,x,ch or int,n", &y, &x, &temp, &n)) - return NULL; - code = wmove(self->win, y, x); - break; - case 5: - if (!PyArg_ParseTuple(args, "iiOil; y,x,ch or int,n,attr", - &y, &x, &temp, &n, &lattr)) - return NULL; - attr = lattr; - code = wmove(self->win, y, x); - break; - default: - PyErr_SetString(PyExc_TypeError, "vline requires 2 to 5 arguments"); - return NULL; - } + PyObject *temp; + chtype ch; + int n, x, y, code = OK; + attr_t attr = A_NORMAL; + long lattr; - if (code != ERR) { - if (!PyCurses_ConvertToChtype(temp, &ch)) { - PyErr_SetString(PyExc_TypeError, - "argument 1 or 3 must be a ch or an int"); - return NULL; - } - return PyCursesCheckERR(wvline(self->win, ch | attr, n), "vline"); - } else - return PyCursesCheckERR(code, "wmove"); + switch (PyTuple_Size(args)) { + case 2: + if (!PyArg_ParseTuple(args, "Oi;ch or int,n", &temp, &n)) + return NULL; + break; + case 3: + if (!PyArg_ParseTuple(args, "Oil;ch or int,n,attr", &temp, &n, &lattr)) + return NULL; + attr = lattr; + break; + case 4: + if (!PyArg_ParseTuple(args, "iiOi;y,x,ch or int,n", &y, &x, &temp, &n)) + return NULL; + code = wmove(self->win, y, x); + break; + case 5: + if (!PyArg_ParseTuple(args, "iiOil; y,x,ch or int,n,attr", + &y, &x, &temp, &n, &lattr)) + return NULL; + attr = lattr; + code = wmove(self->win, y, x); + break; + default: + PyErr_SetString(PyExc_TypeError, "vline requires 2 to 5 arguments"); + return NULL; + } + + if (code != ERR) { + if (!PyCurses_ConvertToChtype(temp, &ch)) { + PyErr_SetString(PyExc_TypeError, + "argument 1 or 3 must be a ch or an int"); + return NULL; + } + return PyCursesCheckERR(wvline(self->win, ch | attr, n), "vline"); + } else + return PyCursesCheckERR(code, "wmove"); } static PyMethodDef PyCursesWindow_Methods[] = { - {"addch", (PyCFunction)PyCursesWindow_AddCh, METH_VARARGS}, - {"addnstr", (PyCFunction)PyCursesWindow_AddNStr, METH_VARARGS}, - {"addstr", (PyCFunction)PyCursesWindow_AddStr, METH_VARARGS}, - {"attroff", (PyCFunction)PyCursesWindow_AttrOff, METH_VARARGS}, - {"attron", (PyCFunction)PyCursesWindow_AttrOn, METH_VARARGS}, - {"attrset", (PyCFunction)PyCursesWindow_AttrSet, METH_VARARGS}, - {"bkgd", (PyCFunction)PyCursesWindow_Bkgd, METH_VARARGS}, - {"chgat", (PyCFunction)PyCursesWindow_ChgAt, METH_VARARGS}, - {"bkgdset", (PyCFunction)PyCursesWindow_BkgdSet, METH_VARARGS}, - {"border", (PyCFunction)PyCursesWindow_Border, METH_VARARGS}, - {"box", (PyCFunction)PyCursesWindow_Box, METH_VARARGS}, - {"clear", (PyCFunction)PyCursesWindow_wclear, METH_NOARGS}, - {"clearok", (PyCFunction)PyCursesWindow_clearok, METH_VARARGS}, - {"clrtobot", (PyCFunction)PyCursesWindow_wclrtobot, METH_NOARGS}, - {"clrtoeol", (PyCFunction)PyCursesWindow_wclrtoeol, METH_NOARGS}, - {"cursyncup", (PyCFunction)PyCursesWindow_wcursyncup, METH_NOARGS}, - {"delch", (PyCFunction)PyCursesWindow_DelCh, METH_VARARGS}, - {"deleteln", (PyCFunction)PyCursesWindow_wdeleteln, METH_NOARGS}, - {"derwin", (PyCFunction)PyCursesWindow_DerWin, METH_VARARGS}, - {"echochar", (PyCFunction)PyCursesWindow_EchoChar, METH_VARARGS}, + {"addch", (PyCFunction)PyCursesWindow_AddCh, METH_VARARGS}, + {"addnstr", (PyCFunction)PyCursesWindow_AddNStr, METH_VARARGS}, + {"addstr", (PyCFunction)PyCursesWindow_AddStr, METH_VARARGS}, + {"attroff", (PyCFunction)PyCursesWindow_AttrOff, METH_VARARGS}, + {"attron", (PyCFunction)PyCursesWindow_AttrOn, METH_VARARGS}, + {"attrset", (PyCFunction)PyCursesWindow_AttrSet, METH_VARARGS}, + {"bkgd", (PyCFunction)PyCursesWindow_Bkgd, METH_VARARGS}, + {"chgat", (PyCFunction)PyCursesWindow_ChgAt, METH_VARARGS}, + {"bkgdset", (PyCFunction)PyCursesWindow_BkgdSet, METH_VARARGS}, + {"border", (PyCFunction)PyCursesWindow_Border, METH_VARARGS}, + {"box", (PyCFunction)PyCursesWindow_Box, METH_VARARGS}, + {"clear", (PyCFunction)PyCursesWindow_wclear, METH_NOARGS}, + {"clearok", (PyCFunction)PyCursesWindow_clearok, METH_VARARGS}, + {"clrtobot", (PyCFunction)PyCursesWindow_wclrtobot, METH_NOARGS}, + {"clrtoeol", (PyCFunction)PyCursesWindow_wclrtoeol, METH_NOARGS}, + {"cursyncup", (PyCFunction)PyCursesWindow_wcursyncup, METH_NOARGS}, + {"delch", (PyCFunction)PyCursesWindow_DelCh, METH_VARARGS}, + {"deleteln", (PyCFunction)PyCursesWindow_wdeleteln, METH_NOARGS}, + {"derwin", (PyCFunction)PyCursesWindow_DerWin, METH_VARARGS}, + {"echochar", (PyCFunction)PyCursesWindow_EchoChar, METH_VARARGS}, #ifdef NCURSES_MOUSE_VERSION - {"enclose", (PyCFunction)PyCursesWindow_Enclose, METH_VARARGS}, + {"enclose", (PyCFunction)PyCursesWindow_Enclose, METH_VARARGS}, #endif - {"erase", (PyCFunction)PyCursesWindow_werase, METH_NOARGS}, - {"getbegyx", (PyCFunction)PyCursesWindow_getbegyx, METH_NOARGS}, - {"getbkgd", (PyCFunction)PyCursesWindow_GetBkgd, METH_NOARGS}, - {"getch", (PyCFunction)PyCursesWindow_GetCh, METH_VARARGS}, - {"getkey", (PyCFunction)PyCursesWindow_GetKey, METH_VARARGS}, - {"getmaxyx", (PyCFunction)PyCursesWindow_getmaxyx, METH_NOARGS}, - {"getparyx", (PyCFunction)PyCursesWindow_getparyx, METH_NOARGS}, - {"getstr", (PyCFunction)PyCursesWindow_GetStr, METH_VARARGS}, - {"getyx", (PyCFunction)PyCursesWindow_getyx, METH_NOARGS}, - {"hline", (PyCFunction)PyCursesWindow_Hline, METH_VARARGS}, - {"idcok", (PyCFunction)PyCursesWindow_idcok, METH_VARARGS}, - {"idlok", (PyCFunction)PyCursesWindow_idlok, METH_VARARGS}, - {"immedok", (PyCFunction)PyCursesWindow_immedok, METH_VARARGS}, - {"inch", (PyCFunction)PyCursesWindow_InCh, METH_VARARGS}, - {"insch", (PyCFunction)PyCursesWindow_InsCh, METH_VARARGS}, - {"insdelln", (PyCFunction)PyCursesWindow_winsdelln, METH_VARARGS}, - {"insertln", (PyCFunction)PyCursesWindow_winsertln, METH_NOARGS}, - {"insnstr", (PyCFunction)PyCursesWindow_InsNStr, METH_VARARGS}, - {"insstr", (PyCFunction)PyCursesWindow_InsStr, METH_VARARGS}, - {"instr", (PyCFunction)PyCursesWindow_InStr, METH_VARARGS}, - {"is_linetouched", (PyCFunction)PyCursesWindow_Is_LineTouched, METH_VARARGS}, - {"is_wintouched", (PyCFunction)PyCursesWindow_is_wintouched, METH_NOARGS}, - {"keypad", (PyCFunction)PyCursesWindow_keypad, METH_VARARGS}, - {"leaveok", (PyCFunction)PyCursesWindow_leaveok, METH_VARARGS}, - {"move", (PyCFunction)PyCursesWindow_wmove, METH_VARARGS}, - {"mvderwin", (PyCFunction)PyCursesWindow_mvderwin, METH_VARARGS}, - {"mvwin", (PyCFunction)PyCursesWindow_mvwin, METH_VARARGS}, - {"nodelay", (PyCFunction)PyCursesWindow_nodelay, METH_VARARGS}, - {"notimeout", (PyCFunction)PyCursesWindow_notimeout, METH_VARARGS}, - {"noutrefresh", (PyCFunction)PyCursesWindow_NoOutRefresh, METH_VARARGS}, - /* Backward compatibility alias -- remove in Python 2.3 */ - {"nooutrefresh", (PyCFunction)PyCursesWindow_NoOutRefresh, METH_VARARGS}, - {"overlay", (PyCFunction)PyCursesWindow_Overlay, METH_VARARGS}, - {"overwrite", (PyCFunction)PyCursesWindow_Overwrite, - METH_VARARGS}, - {"putwin", (PyCFunction)PyCursesWindow_PutWin, METH_O}, - {"redrawln", (PyCFunction)PyCursesWindow_RedrawLine, METH_VARARGS}, - {"redrawwin", (PyCFunction)PyCursesWindow_redrawwin, METH_NOARGS}, - {"refresh", (PyCFunction)PyCursesWindow_Refresh, METH_VARARGS}, + {"erase", (PyCFunction)PyCursesWindow_werase, METH_NOARGS}, + {"getbegyx", (PyCFunction)PyCursesWindow_getbegyx, METH_NOARGS}, + {"getbkgd", (PyCFunction)PyCursesWindow_GetBkgd, METH_NOARGS}, + {"getch", (PyCFunction)PyCursesWindow_GetCh, METH_VARARGS}, + {"getkey", (PyCFunction)PyCursesWindow_GetKey, METH_VARARGS}, + {"getmaxyx", (PyCFunction)PyCursesWindow_getmaxyx, METH_NOARGS}, + {"getparyx", (PyCFunction)PyCursesWindow_getparyx, METH_NOARGS}, + {"getstr", (PyCFunction)PyCursesWindow_GetStr, METH_VARARGS}, + {"getyx", (PyCFunction)PyCursesWindow_getyx, METH_NOARGS}, + {"hline", (PyCFunction)PyCursesWindow_Hline, METH_VARARGS}, + {"idcok", (PyCFunction)PyCursesWindow_idcok, METH_VARARGS}, + {"idlok", (PyCFunction)PyCursesWindow_idlok, METH_VARARGS}, + {"immedok", (PyCFunction)PyCursesWindow_immedok, METH_VARARGS}, + {"inch", (PyCFunction)PyCursesWindow_InCh, METH_VARARGS}, + {"insch", (PyCFunction)PyCursesWindow_InsCh, METH_VARARGS}, + {"insdelln", (PyCFunction)PyCursesWindow_winsdelln, METH_VARARGS}, + {"insertln", (PyCFunction)PyCursesWindow_winsertln, METH_NOARGS}, + {"insnstr", (PyCFunction)PyCursesWindow_InsNStr, METH_VARARGS}, + {"insstr", (PyCFunction)PyCursesWindow_InsStr, METH_VARARGS}, + {"instr", (PyCFunction)PyCursesWindow_InStr, METH_VARARGS}, + {"is_linetouched", (PyCFunction)PyCursesWindow_Is_LineTouched, METH_VARARGS}, + {"is_wintouched", (PyCFunction)PyCursesWindow_is_wintouched, METH_NOARGS}, + {"keypad", (PyCFunction)PyCursesWindow_keypad, METH_VARARGS}, + {"leaveok", (PyCFunction)PyCursesWindow_leaveok, METH_VARARGS}, + {"move", (PyCFunction)PyCursesWindow_wmove, METH_VARARGS}, + {"mvderwin", (PyCFunction)PyCursesWindow_mvderwin, METH_VARARGS}, + {"mvwin", (PyCFunction)PyCursesWindow_mvwin, METH_VARARGS}, + {"nodelay", (PyCFunction)PyCursesWindow_nodelay, METH_VARARGS}, + {"notimeout", (PyCFunction)PyCursesWindow_notimeout, METH_VARARGS}, + {"noutrefresh", (PyCFunction)PyCursesWindow_NoOutRefresh, METH_VARARGS}, + /* Backward compatibility alias -- remove in Python 2.3 */ + {"nooutrefresh", (PyCFunction)PyCursesWindow_NoOutRefresh, METH_VARARGS}, + {"overlay", (PyCFunction)PyCursesWindow_Overlay, METH_VARARGS}, + {"overwrite", (PyCFunction)PyCursesWindow_Overwrite, + METH_VARARGS}, + {"putwin", (PyCFunction)PyCursesWindow_PutWin, METH_O}, + {"redrawln", (PyCFunction)PyCursesWindow_RedrawLine, METH_VARARGS}, + {"redrawwin", (PyCFunction)PyCursesWindow_redrawwin, METH_NOARGS}, + {"refresh", (PyCFunction)PyCursesWindow_Refresh, METH_VARARGS}, #ifndef STRICT_SYSV_CURSES - {"resize", (PyCFunction)PyCursesWindow_wresize, METH_VARARGS}, + {"resize", (PyCFunction)PyCursesWindow_wresize, METH_VARARGS}, #endif - {"scroll", (PyCFunction)PyCursesWindow_Scroll, METH_VARARGS}, - {"scrollok", (PyCFunction)PyCursesWindow_scrollok, METH_VARARGS}, - {"setscrreg", (PyCFunction)PyCursesWindow_SetScrollRegion, METH_VARARGS}, - {"standend", (PyCFunction)PyCursesWindow_wstandend, METH_NOARGS}, - {"standout", (PyCFunction)PyCursesWindow_wstandout, METH_NOARGS}, - {"subpad", (PyCFunction)PyCursesWindow_SubWin, METH_VARARGS}, - {"subwin", (PyCFunction)PyCursesWindow_SubWin, METH_VARARGS}, - {"syncdown", (PyCFunction)PyCursesWindow_wsyncdown, METH_NOARGS}, - {"syncok", (PyCFunction)PyCursesWindow_syncok, METH_VARARGS}, - {"syncup", (PyCFunction)PyCursesWindow_wsyncup, METH_NOARGS}, - {"timeout", (PyCFunction)PyCursesWindow_wtimeout, METH_VARARGS}, - {"touchline", (PyCFunction)PyCursesWindow_TouchLine, METH_VARARGS}, - {"touchwin", (PyCFunction)PyCursesWindow_touchwin, METH_NOARGS}, - {"untouchwin", (PyCFunction)PyCursesWindow_untouchwin, METH_NOARGS}, - {"vline", (PyCFunction)PyCursesWindow_Vline, METH_VARARGS}, - {NULL, NULL} /* sentinel */ + {"scroll", (PyCFunction)PyCursesWindow_Scroll, METH_VARARGS}, + {"scrollok", (PyCFunction)PyCursesWindow_scrollok, METH_VARARGS}, + {"setscrreg", (PyCFunction)PyCursesWindow_SetScrollRegion, METH_VARARGS}, + {"standend", (PyCFunction)PyCursesWindow_wstandend, METH_NOARGS}, + {"standout", (PyCFunction)PyCursesWindow_wstandout, METH_NOARGS}, + {"subpad", (PyCFunction)PyCursesWindow_SubWin, METH_VARARGS}, + {"subwin", (PyCFunction)PyCursesWindow_SubWin, METH_VARARGS}, + {"syncdown", (PyCFunction)PyCursesWindow_wsyncdown, METH_NOARGS}, + {"syncok", (PyCFunction)PyCursesWindow_syncok, METH_VARARGS}, + {"syncup", (PyCFunction)PyCursesWindow_wsyncup, METH_NOARGS}, + {"timeout", (PyCFunction)PyCursesWindow_wtimeout, METH_VARARGS}, + {"touchline", (PyCFunction)PyCursesWindow_TouchLine, METH_VARARGS}, + {"touchwin", (PyCFunction)PyCursesWindow_touchwin, METH_NOARGS}, + {"untouchwin", (PyCFunction)PyCursesWindow_untouchwin, METH_NOARGS}, + {"vline", (PyCFunction)PyCursesWindow_Vline, METH_VARARGS}, + {NULL, NULL} /* sentinel */ }; /* -------------------------------------------------------*/ PyTypeObject PyCursesWindow_Type = { - PyVarObject_HEAD_INIT(NULL, 0) - "_curses.curses window", /*tp_name*/ - sizeof(PyCursesWindowObject), /*tp_basicsize*/ - 0, /*tp_itemsize*/ - /* methods */ - (destructor)PyCursesWindow_Dealloc, /*tp_dealloc*/ - 0, /*tp_print*/ - (getattrfunc)0, /*tp_getattr*/ - (setattrfunc)0, /*tp_setattr*/ - 0, /*tp_reserved*/ - 0, /*tp_repr*/ - 0, /*tp_as_number*/ - 0, /*tp_as_sequence*/ - 0, /*tp_as_mapping*/ - 0, /*tp_hash*/ - 0, /*tp_call*/ - 0, /*tp_str*/ - 0, /*tp_getattro*/ - 0, /*tp_setattro*/ - 0, /*tp_as_buffer*/ - Py_TPFLAGS_DEFAULT, /*tp_flags*/ - 0, /*tp_doc*/ - 0, /*tp_traverse*/ - 0, /*tp_clear*/ - 0, /*tp_richcompare*/ - 0, /*tp_weaklistoffset*/ - 0, /*tp_iter*/ - 0, /*tp_iternext*/ - PyCursesWindow_Methods, /*tp_methods*/ + PyVarObject_HEAD_INIT(NULL, 0) + "_curses.curses window", /*tp_name*/ + sizeof(PyCursesWindowObject), /*tp_basicsize*/ + 0, /*tp_itemsize*/ + /* methods */ + (destructor)PyCursesWindow_Dealloc, /*tp_dealloc*/ + 0, /*tp_print*/ + (getattrfunc)0, /*tp_getattr*/ + (setattrfunc)0, /*tp_setattr*/ + 0, /*tp_reserved*/ + 0, /*tp_repr*/ + 0, /*tp_as_number*/ + 0, /*tp_as_sequence*/ + 0, /*tp_as_mapping*/ + 0, /*tp_hash*/ + 0, /*tp_call*/ + 0, /*tp_str*/ + 0, /*tp_getattro*/ + 0, /*tp_setattro*/ + 0, /*tp_as_buffer*/ + Py_TPFLAGS_DEFAULT, /*tp_flags*/ + 0, /*tp_doc*/ + 0, /*tp_traverse*/ + 0, /*tp_clear*/ + 0, /*tp_richcompare*/ + 0, /*tp_weaklistoffset*/ + 0, /*tp_iter*/ + 0, /*tp_iternext*/ + PyCursesWindow_Methods, /*tp_methods*/ }; /********************************************************************* @@ -1738,452 +1738,452 @@ static PyObject * PyCurses_filter(PyObject *self) { - /* not checking for PyCursesInitialised here since filter() must - be called before initscr() */ - filter(); - Py_INCREF(Py_None); - return Py_None; + /* not checking for PyCursesInitialised here since filter() must + be called before initscr() */ + filter(); + Py_INCREF(Py_None); + return Py_None; } static PyObject * PyCurses_Color_Content(PyObject *self, PyObject *args) { - short color,r,g,b; + short color,r,g,b; - PyCursesInitialised; - PyCursesInitialisedColor; + PyCursesInitialised; + PyCursesInitialisedColor; - if (!PyArg_ParseTuple(args, "h:color_content", &color)) return NULL; + if (!PyArg_ParseTuple(args, "h:color_content", &color)) return NULL; - if (color_content(color, &r, &g, &b) != ERR) - return Py_BuildValue("(iii)", r, g, b); - else { - PyErr_SetString(PyCursesError, - "Argument 1 was out of range. Check value of COLORS."); - return NULL; - } + if (color_content(color, &r, &g, &b) != ERR) + return Py_BuildValue("(iii)", r, g, b); + else { + PyErr_SetString(PyCursesError, + "Argument 1 was out of range. Check value of COLORS."); + return NULL; + } } static PyObject * PyCurses_color_pair(PyObject *self, PyObject *args) { - int n; + int n; - PyCursesInitialised; - PyCursesInitialisedColor; + PyCursesInitialised; + PyCursesInitialisedColor; - if (!PyArg_ParseTuple(args, "i:color_pair", &n)) return NULL; - return PyLong_FromLong((long) (n << 8)); + if (!PyArg_ParseTuple(args, "i:color_pair", &n)) return NULL; + return PyLong_FromLong((long) (n << 8)); } static PyObject * PyCurses_Curs_Set(PyObject *self, PyObject *args) { - int vis,erg; + int vis,erg; - PyCursesInitialised; + PyCursesInitialised; - if (!PyArg_ParseTuple(args, "i:curs_set", &vis)) return NULL; + if (!PyArg_ParseTuple(args, "i:curs_set", &vis)) return NULL; - erg = curs_set(vis); - if (erg == ERR) return PyCursesCheckERR(erg, "curs_set"); + erg = curs_set(vis); + if (erg == ERR) return PyCursesCheckERR(erg, "curs_set"); - return PyLong_FromLong((long) erg); + return PyLong_FromLong((long) erg); } static PyObject * PyCurses_Delay_Output(PyObject *self, PyObject *args) { - int ms; + int ms; - PyCursesInitialised; + PyCursesInitialised; - if (!PyArg_ParseTuple(args, "i:delay_output", &ms)) return NULL; + if (!PyArg_ParseTuple(args, "i:delay_output", &ms)) return NULL; - return PyCursesCheckERR(delay_output(ms), "delay_output"); + return PyCursesCheckERR(delay_output(ms), "delay_output"); } static PyObject * PyCurses_EraseChar(PyObject *self) { - char ch; + char ch; - PyCursesInitialised; + PyCursesInitialised; - ch = erasechar(); + ch = erasechar(); - return PyBytes_FromStringAndSize(&ch, 1); + return PyBytes_FromStringAndSize(&ch, 1); } static PyObject * PyCurses_getsyx(PyObject *self) { - int x = 0; - int y = 0; + int x = 0; + int y = 0; - PyCursesInitialised; + PyCursesInitialised; - getsyx(y, x); + getsyx(y, x); - return Py_BuildValue("(ii)", y, x); + return Py_BuildValue("(ii)", y, x); } #ifdef NCURSES_MOUSE_VERSION static PyObject * PyCurses_GetMouse(PyObject *self) { - int rtn; - MEVENT event; + int rtn; + MEVENT event; - PyCursesInitialised; + PyCursesInitialised; - rtn = getmouse( &event ); - if (rtn == ERR) { - PyErr_SetString(PyCursesError, "getmouse() returned ERR"); - return NULL; - } - return Py_BuildValue("(hiiil)", - (short)event.id, - event.x, event.y, event.z, - (long) event.bstate); + rtn = getmouse( &event ); + if (rtn == ERR) { + PyErr_SetString(PyCursesError, "getmouse() returned ERR"); + return NULL; + } + return Py_BuildValue("(hiiil)", + (short)event.id, + event.x, event.y, event.z, + (long) event.bstate); } static PyObject * PyCurses_UngetMouse(PyObject *self, PyObject *args) { - MEVENT event; + MEVENT event; - PyCursesInitialised; - if (!PyArg_ParseTuple(args, "hiiil", - &event.id, - &event.x, &event.y, &event.z, - (int *) &event.bstate)) - return NULL; + PyCursesInitialised; + if (!PyArg_ParseTuple(args, "hiiil", + &event.id, + &event.x, &event.y, &event.z, + (int *) &event.bstate)) + return NULL; - return PyCursesCheckERR(ungetmouse(&event), "ungetmouse"); + return PyCursesCheckERR(ungetmouse(&event), "ungetmouse"); } #endif static PyObject * PyCurses_GetWin(PyCursesWindowObject *self, PyObject *stream) { - char fn[100]; - int fd; - FILE *fp; - PyObject *data; - size_t datalen; - WINDOW *win; - - PyCursesInitialised; - - strcpy(fn, "/tmp/py.curses.getwin.XXXXXX"); - fd = mkstemp(fn); - if (fd < 0) - return PyErr_SetFromErrnoWithFilename(PyExc_IOError, fn); - fp = fdopen(fd, "wb+"); - if (fp == NULL) { - close(fd); - remove(fn); - return PyErr_SetFromErrnoWithFilename(PyExc_IOError, fn); - } - data = PyObject_CallMethod(stream, "read", ""); - if (data == NULL) { - fclose(fp); - remove(fn); - return NULL; - } - if (!PyBytes_Check(data)) { - PyErr_Format(PyExc_TypeError, - "f.read() returned %.100s instead of bytes", - data->ob_type->tp_name); - Py_DECREF(data); - fclose(fp); - remove(fn); - return NULL; - } - datalen = PyBytes_GET_SIZE(data); - if (fwrite(PyBytes_AS_STRING(data), 1, datalen, fp) != datalen) { + char fn[100]; + int fd; + FILE *fp; + PyObject *data; + size_t datalen; + WINDOW *win; + + PyCursesInitialised; + + strcpy(fn, "/tmp/py.curses.getwin.XXXXXX"); + fd = mkstemp(fn); + if (fd < 0) + return PyErr_SetFromErrnoWithFilename(PyExc_IOError, fn); + fp = fdopen(fd, "wb+"); + if (fp == NULL) { + close(fd); + remove(fn); + return PyErr_SetFromErrnoWithFilename(PyExc_IOError, fn); + } + data = PyObject_CallMethod(stream, "read", ""); + if (data == NULL) { + fclose(fp); + remove(fn); + return NULL; + } + if (!PyBytes_Check(data)) { + PyErr_Format(PyExc_TypeError, + "f.read() returned %.100s instead of bytes", + data->ob_type->tp_name); + Py_DECREF(data); + fclose(fp); + remove(fn); + return NULL; + } + datalen = PyBytes_GET_SIZE(data); + if (fwrite(PyBytes_AS_STRING(data), 1, datalen, fp) != datalen) { + Py_DECREF(data); + fclose(fp); + remove(fn); + return PyErr_SetFromErrnoWithFilename(PyExc_IOError, fn); + } Py_DECREF(data); + fseek(fp, 0, 0); + win = getwin(fp); fclose(fp); remove(fn); - return PyErr_SetFromErrnoWithFilename(PyExc_IOError, fn); - } - Py_DECREF(data); - fseek(fp, 0, 0); - win = getwin(fp); - fclose(fp); - remove(fn); - if (win == NULL) { - PyErr_SetString(PyCursesError, catchall_NULL); - return NULL; - } - return PyCursesWindow_New(win); + if (win == NULL) { + PyErr_SetString(PyCursesError, catchall_NULL); + return NULL; + } + return PyCursesWindow_New(win); } static PyObject * PyCurses_HalfDelay(PyObject *self, PyObject *args) { - unsigned char tenths; + unsigned char tenths; - PyCursesInitialised; + PyCursesInitialised; - if (!PyArg_ParseTuple(args, "b:halfdelay", &tenths)) return NULL; + if (!PyArg_ParseTuple(args, "b:halfdelay", &tenths)) return NULL; - return PyCursesCheckERR(halfdelay(tenths), "halfdelay"); + return PyCursesCheckERR(halfdelay(tenths), "halfdelay"); } #ifndef STRICT_SYSV_CURSES - /* No has_key! */ +/* No has_key! */ static PyObject * PyCurses_has_key(PyObject *self, PyObject *args) { - int ch; + int ch; - PyCursesInitialised; + PyCursesInitialised; - if (!PyArg_ParseTuple(args,"i",&ch)) return NULL; + if (!PyArg_ParseTuple(args,"i",&ch)) return NULL; - if (has_key(ch) == FALSE) { - Py_INCREF(Py_False); - return Py_False; - } - Py_INCREF(Py_True); - return Py_True; + if (has_key(ch) == FALSE) { + Py_INCREF(Py_False); + return Py_False; + } + Py_INCREF(Py_True); + return Py_True; } #endif /* STRICT_SYSV_CURSES */ static PyObject * PyCurses_Init_Color(PyObject *self, PyObject *args) { - short color, r, g, b; + short color, r, g, b; - PyCursesInitialised; - PyCursesInitialisedColor; + PyCursesInitialised; + PyCursesInitialisedColor; - switch(PyTuple_Size(args)) { - case 4: - if (!PyArg_ParseTuple(args, "hhhh;color,r,g,b", &color, &r, &g, &b)) return NULL; - break; - default: - PyErr_SetString(PyExc_TypeError, "init_color requires 4 arguments"); - return NULL; - } + switch(PyTuple_Size(args)) { + case 4: + if (!PyArg_ParseTuple(args, "hhhh;color,r,g,b", &color, &r, &g, &b)) return NULL; + break; + default: + PyErr_SetString(PyExc_TypeError, "init_color requires 4 arguments"); + return NULL; + } - return PyCursesCheckERR(init_color(color, r, g, b), "init_color"); + return PyCursesCheckERR(init_color(color, r, g, b), "init_color"); } static PyObject * PyCurses_Init_Pair(PyObject *self, PyObject *args) { - short pair, f, b; + short pair, f, b; - PyCursesInitialised; - PyCursesInitialisedColor; + PyCursesInitialised; + PyCursesInitialisedColor; - if (PyTuple_Size(args) != 3) { - PyErr_SetString(PyExc_TypeError, "init_pair requires 3 arguments"); - return NULL; - } + if (PyTuple_Size(args) != 3) { + PyErr_SetString(PyExc_TypeError, "init_pair requires 3 arguments"); + return NULL; + } - if (!PyArg_ParseTuple(args, "hhh;pair, f, b", &pair, &f, &b)) return NULL; + if (!PyArg_ParseTuple(args, "hhh;pair, f, b", &pair, &f, &b)) return NULL; - return PyCursesCheckERR(init_pair(pair, f, b), "init_pair"); + return PyCursesCheckERR(init_pair(pair, f, b), "init_pair"); } static PyObject *ModDict; -static PyObject * +static PyObject * PyCurses_InitScr(PyObject *self) { - WINDOW *win; + WINDOW *win; - if (initialised == TRUE) { - wrefresh(stdscr); - return (PyObject *)PyCursesWindow_New(stdscr); - } + if (initialised == TRUE) { + wrefresh(stdscr); + return (PyObject *)PyCursesWindow_New(stdscr); + } - win = initscr(); + win = initscr(); - if (win == NULL) { - PyErr_SetString(PyCursesError, catchall_NULL); - return NULL; - } + if (win == NULL) { + PyErr_SetString(PyCursesError, catchall_NULL); + return NULL; + } - initialised = initialised_setupterm = TRUE; + initialised = initialised_setupterm = TRUE; /* This was moved from initcurses() because it core dumped on SGI, where they're not defined until you've called initscr() */ -#define SetDictInt(string,ch) \ - do { \ - PyObject *o = PyLong_FromLong((long) (ch)); \ - if (o && PyDict_SetItemString(ModDict, string, o) == 0) { \ - Py_DECREF(o); \ - } \ +#define SetDictInt(string,ch) \ + do { \ + PyObject *o = PyLong_FromLong((long) (ch)); \ + if (o && PyDict_SetItemString(ModDict, string, o) == 0) { \ + Py_DECREF(o); \ + } \ } while (0) - /* Here are some graphic symbols you can use */ - SetDictInt("ACS_ULCORNER", (ACS_ULCORNER)); - SetDictInt("ACS_LLCORNER", (ACS_LLCORNER)); - SetDictInt("ACS_URCORNER", (ACS_URCORNER)); - SetDictInt("ACS_LRCORNER", (ACS_LRCORNER)); - SetDictInt("ACS_LTEE", (ACS_LTEE)); - SetDictInt("ACS_RTEE", (ACS_RTEE)); - SetDictInt("ACS_BTEE", (ACS_BTEE)); - SetDictInt("ACS_TTEE", (ACS_TTEE)); - SetDictInt("ACS_HLINE", (ACS_HLINE)); - SetDictInt("ACS_VLINE", (ACS_VLINE)); - SetDictInt("ACS_PLUS", (ACS_PLUS)); + /* Here are some graphic symbols you can use */ + SetDictInt("ACS_ULCORNER", (ACS_ULCORNER)); + SetDictInt("ACS_LLCORNER", (ACS_LLCORNER)); + SetDictInt("ACS_URCORNER", (ACS_URCORNER)); + SetDictInt("ACS_LRCORNER", (ACS_LRCORNER)); + SetDictInt("ACS_LTEE", (ACS_LTEE)); + SetDictInt("ACS_RTEE", (ACS_RTEE)); + SetDictInt("ACS_BTEE", (ACS_BTEE)); + SetDictInt("ACS_TTEE", (ACS_TTEE)); + SetDictInt("ACS_HLINE", (ACS_HLINE)); + SetDictInt("ACS_VLINE", (ACS_VLINE)); + SetDictInt("ACS_PLUS", (ACS_PLUS)); #if !defined(__hpux) || defined(HAVE_NCURSES_H) - /* On HP/UX 11, these are of type cchar_t, which is not an - integral type. If this is a problem on more platforms, a - configure test should be added to determine whether ACS_S1 - is of integral type. */ - SetDictInt("ACS_S1", (ACS_S1)); - SetDictInt("ACS_S9", (ACS_S9)); - SetDictInt("ACS_DIAMOND", (ACS_DIAMOND)); - SetDictInt("ACS_CKBOARD", (ACS_CKBOARD)); - SetDictInt("ACS_DEGREE", (ACS_DEGREE)); - SetDictInt("ACS_PLMINUS", (ACS_PLMINUS)); - SetDictInt("ACS_BULLET", (ACS_BULLET)); - SetDictInt("ACS_LARROW", (ACS_LARROW)); - SetDictInt("ACS_RARROW", (ACS_RARROW)); - SetDictInt("ACS_DARROW", (ACS_DARROW)); - SetDictInt("ACS_UARROW", (ACS_UARROW)); - SetDictInt("ACS_BOARD", (ACS_BOARD)); - SetDictInt("ACS_LANTERN", (ACS_LANTERN)); - SetDictInt("ACS_BLOCK", (ACS_BLOCK)); -#endif - SetDictInt("ACS_BSSB", (ACS_ULCORNER)); - SetDictInt("ACS_SSBB", (ACS_LLCORNER)); - SetDictInt("ACS_BBSS", (ACS_URCORNER)); - SetDictInt("ACS_SBBS", (ACS_LRCORNER)); - SetDictInt("ACS_SBSS", (ACS_RTEE)); - SetDictInt("ACS_SSSB", (ACS_LTEE)); - SetDictInt("ACS_SSBS", (ACS_BTEE)); - SetDictInt("ACS_BSSS", (ACS_TTEE)); - SetDictInt("ACS_BSBS", (ACS_HLINE)); - SetDictInt("ACS_SBSB", (ACS_VLINE)); - SetDictInt("ACS_SSSS", (ACS_PLUS)); + /* On HP/UX 11, these are of type cchar_t, which is not an + integral type. If this is a problem on more platforms, a + configure test should be added to determine whether ACS_S1 + is of integral type. */ + SetDictInt("ACS_S1", (ACS_S1)); + SetDictInt("ACS_S9", (ACS_S9)); + SetDictInt("ACS_DIAMOND", (ACS_DIAMOND)); + SetDictInt("ACS_CKBOARD", (ACS_CKBOARD)); + SetDictInt("ACS_DEGREE", (ACS_DEGREE)); + SetDictInt("ACS_PLMINUS", (ACS_PLMINUS)); + SetDictInt("ACS_BULLET", (ACS_BULLET)); + SetDictInt("ACS_LARROW", (ACS_LARROW)); + SetDictInt("ACS_RARROW", (ACS_RARROW)); + SetDictInt("ACS_DARROW", (ACS_DARROW)); + SetDictInt("ACS_UARROW", (ACS_UARROW)); + SetDictInt("ACS_BOARD", (ACS_BOARD)); + SetDictInt("ACS_LANTERN", (ACS_LANTERN)); + SetDictInt("ACS_BLOCK", (ACS_BLOCK)); +#endif + SetDictInt("ACS_BSSB", (ACS_ULCORNER)); + SetDictInt("ACS_SSBB", (ACS_LLCORNER)); + SetDictInt("ACS_BBSS", (ACS_URCORNER)); + SetDictInt("ACS_SBBS", (ACS_LRCORNER)); + SetDictInt("ACS_SBSS", (ACS_RTEE)); + SetDictInt("ACS_SSSB", (ACS_LTEE)); + SetDictInt("ACS_SSBS", (ACS_BTEE)); + SetDictInt("ACS_BSSS", (ACS_TTEE)); + SetDictInt("ACS_BSBS", (ACS_HLINE)); + SetDictInt("ACS_SBSB", (ACS_VLINE)); + SetDictInt("ACS_SSSS", (ACS_PLUS)); - /* The following are never available with strict SYSV curses */ + /* The following are never available with strict SYSV curses */ #ifdef ACS_S3 - SetDictInt("ACS_S3", (ACS_S3)); + SetDictInt("ACS_S3", (ACS_S3)); #endif #ifdef ACS_S7 - SetDictInt("ACS_S7", (ACS_S7)); + SetDictInt("ACS_S7", (ACS_S7)); #endif #ifdef ACS_LEQUAL - SetDictInt("ACS_LEQUAL", (ACS_LEQUAL)); + SetDictInt("ACS_LEQUAL", (ACS_LEQUAL)); #endif #ifdef ACS_GEQUAL - SetDictInt("ACS_GEQUAL", (ACS_GEQUAL)); + SetDictInt("ACS_GEQUAL", (ACS_GEQUAL)); #endif #ifdef ACS_PI - SetDictInt("ACS_PI", (ACS_PI)); + SetDictInt("ACS_PI", (ACS_PI)); #endif #ifdef ACS_NEQUAL - SetDictInt("ACS_NEQUAL", (ACS_NEQUAL)); + SetDictInt("ACS_NEQUAL", (ACS_NEQUAL)); #endif #ifdef ACS_STERLING - SetDictInt("ACS_STERLING", (ACS_STERLING)); + SetDictInt("ACS_STERLING", (ACS_STERLING)); #endif - SetDictInt("LINES", LINES); - SetDictInt("COLS", COLS); + SetDictInt("LINES", LINES); + SetDictInt("COLS", COLS); - return (PyObject *)PyCursesWindow_New(win); + return (PyObject *)PyCursesWindow_New(win); } static PyObject * PyCurses_setupterm(PyObject* self, PyObject *args, PyObject* keywds) { - int fd = -1; - int err; - char* termstr = NULL; - - static char *kwlist[] = {"term", "fd", NULL}; - - if (!PyArg_ParseTupleAndKeywords( - args, keywds, "|zi:setupterm", kwlist, &termstr, &fd)) { - return NULL; - } - - if (fd == -1) { - PyObject* sys_stdout; - - sys_stdout = PySys_GetObject("stdout"); - - if (sys_stdout == NULL || sys_stdout == Py_None) { - PyErr_SetString( - PyCursesError, - "lost sys.stdout"); - return NULL; - } - - fd = PyObject_AsFileDescriptor(sys_stdout); - - if (fd == -1) { - return NULL; - } - } - - if (setupterm(termstr,fd,&err) == ERR) { - char* s = "setupterm: unknown error"; - - if (err == 0) { - s = "setupterm: could not find terminal"; - } else if (err == -1) { - s = "setupterm: could not find terminfo database"; - } - - PyErr_SetString(PyCursesError,s); - return NULL; - } + int fd = -1; + int err; + char* termstr = NULL; - initialised_setupterm = TRUE; + static char *kwlist[] = {"term", "fd", NULL}; - Py_INCREF(Py_None); - return Py_None; + if (!PyArg_ParseTupleAndKeywords( + args, keywds, "|zi:setupterm", kwlist, &termstr, &fd)) { + return NULL; + } + + if (fd == -1) { + PyObject* sys_stdout; + + sys_stdout = PySys_GetObject("stdout"); + + if (sys_stdout == NULL || sys_stdout == Py_None) { + PyErr_SetString( + PyCursesError, + "lost sys.stdout"); + return NULL; + } + + fd = PyObject_AsFileDescriptor(sys_stdout); + + if (fd == -1) { + return NULL; + } + } + + if (setupterm(termstr,fd,&err) == ERR) { + char* s = "setupterm: unknown error"; + + if (err == 0) { + s = "setupterm: could not find terminal"; + } else if (err == -1) { + s = "setupterm: could not find terminfo database"; + } + + PyErr_SetString(PyCursesError,s); + return NULL; + } + + initialised_setupterm = TRUE; + + Py_INCREF(Py_None); + return Py_None; } static PyObject * PyCurses_IntrFlush(PyObject *self, PyObject *args) { - int ch; + int ch; - PyCursesInitialised; + PyCursesInitialised; - switch(PyTuple_Size(args)) { - case 1: - if (!PyArg_ParseTuple(args,"i;True(1), False(0)",&ch)) return NULL; - break; - default: - PyErr_SetString(PyExc_TypeError, "intrflush requires 1 argument"); - return NULL; - } + switch(PyTuple_Size(args)) { + case 1: + if (!PyArg_ParseTuple(args,"i;True(1), False(0)",&ch)) return NULL; + break; + default: + PyErr_SetString(PyExc_TypeError, "intrflush requires 1 argument"); + return NULL; + } - return PyCursesCheckERR(intrflush(NULL,ch), "intrflush"); + return PyCursesCheckERR(intrflush(NULL,ch), "intrflush"); } #ifdef HAVE_CURSES_IS_TERM_RESIZED static PyObject * PyCurses_Is_Term_Resized(PyObject *self, PyObject *args) { - int lines; - int columns; - int result; - - PyCursesInitialised; - - if (!PyArg_ParseTuple(args,"ii:is_term_resized", &lines, &columns)) - return NULL; - result = is_term_resized(lines, columns); - if (result == TRUE) { - Py_INCREF(Py_True); - return Py_True; - } else { - Py_INCREF(Py_False); - return Py_False; - } + int lines; + int columns; + int result; + + PyCursesInitialised; + + if (!PyArg_ParseTuple(args,"ii:is_term_resized", &lines, &columns)) + return NULL; + result = is_term_resized(lines, columns); + if (result == TRUE) { + Py_INCREF(Py_True); + return Py_True; + } else { + Py_INCREF(Py_False); + return Py_False; + } } #endif /* HAVE_CURSES_IS_TERM_RESIZED */ @@ -2191,75 +2191,75 @@ static PyObject * PyCurses_KeyName(PyObject *self, PyObject *args) { - const char *knp; - int ch; + const char *knp; + int ch; - PyCursesInitialised; + PyCursesInitialised; - if (!PyArg_ParseTuple(args,"i",&ch)) return NULL; + if (!PyArg_ParseTuple(args,"i",&ch)) return NULL; - if (ch < 0) { - PyErr_SetString(PyExc_ValueError, "invalid key number"); - return NULL; - } - knp = keyname(ch); + if (ch < 0) { + PyErr_SetString(PyExc_ValueError, "invalid key number"); + return NULL; + } + knp = keyname(ch); - return PyBytes_FromString((knp == NULL) ? "" : (char *)knp); + return PyBytes_FromString((knp == NULL) ? "" : (char *)knp); } #endif -static PyObject * -PyCurses_KillChar(PyObject *self) -{ - char ch; +static PyObject * +PyCurses_KillChar(PyObject *self) +{ + char ch; - ch = killchar(); + ch = killchar(); - return PyBytes_FromStringAndSize(&ch, 1); -} + return PyBytes_FromStringAndSize(&ch, 1); +} static PyObject * PyCurses_Meta(PyObject *self, PyObject *args) { - int ch; + int ch; - PyCursesInitialised; + PyCursesInitialised; - switch(PyTuple_Size(args)) { - case 1: - if (!PyArg_ParseTuple(args,"i;True(1), False(0)",&ch)) return NULL; - break; - default: - PyErr_SetString(PyExc_TypeError, "meta requires 1 argument"); - return NULL; - } + switch(PyTuple_Size(args)) { + case 1: + if (!PyArg_ParseTuple(args,"i;True(1), False(0)",&ch)) return NULL; + break; + default: + PyErr_SetString(PyExc_TypeError, "meta requires 1 argument"); + return NULL; + } - return PyCursesCheckERR(meta(stdscr, ch), "meta"); + return PyCursesCheckERR(meta(stdscr, ch), "meta"); } #ifdef NCURSES_MOUSE_VERSION static PyObject * PyCurses_MouseInterval(PyObject *self, PyObject *args) { - int interval; - PyCursesInitialised; + int interval; + PyCursesInitialised; - if (!PyArg_ParseTuple(args,"i;interval",&interval)) - return NULL; - return PyCursesCheckERR(mouseinterval(interval), "mouseinterval"); + if (!PyArg_ParseTuple(args,"i;interval",&interval)) + return NULL; + return PyCursesCheckERR(mouseinterval(interval), "mouseinterval"); } static PyObject * PyCurses_MouseMask(PyObject *self, PyObject *args) { - int newmask; - mmask_t oldmask, availmask; + int newmask; + mmask_t oldmask, availmask; - PyCursesInitialised; - if (!PyArg_ParseTuple(args,"i;mousemask",&newmask)) - return NULL; - availmask = mousemask(newmask, &oldmask); - return Py_BuildValue("(ll)", (long)availmask, (long)oldmask); + PyCursesInitialised; + if (!PyArg_ParseTuple(args,"i;mousemask",&newmask)) + return NULL; + availmask = mousemask(newmask, &oldmask); + return Py_BuildValue("(ll)", (long)availmask, (long)oldmask); } #endif @@ -2278,133 +2278,133 @@ static PyObject * PyCurses_NewPad(PyObject *self, PyObject *args) { - WINDOW *win; - int nlines, ncols; + WINDOW *win; + int nlines, ncols; + + PyCursesInitialised; - PyCursesInitialised; + if (!PyArg_ParseTuple(args,"ii;nlines,ncols",&nlines,&ncols)) return NULL; - if (!PyArg_ParseTuple(args,"ii;nlines,ncols",&nlines,&ncols)) return NULL; + win = newpad(nlines, ncols); - win = newpad(nlines, ncols); - - if (win == NULL) { - PyErr_SetString(PyCursesError, catchall_NULL); - return NULL; - } + if (win == NULL) { + PyErr_SetString(PyCursesError, catchall_NULL); + return NULL; + } - return (PyObject *)PyCursesWindow_New(win); + return (PyObject *)PyCursesWindow_New(win); } static PyObject * PyCurses_NewWindow(PyObject *self, PyObject *args) { - WINDOW *win; - int nlines, ncols, begin_y=0, begin_x=0; + WINDOW *win; + int nlines, ncols, begin_y=0, begin_x=0; - PyCursesInitialised; + PyCursesInitialised; - switch (PyTuple_Size(args)) { - case 2: - if (!PyArg_ParseTuple(args,"ii;nlines,ncols",&nlines,&ncols)) - return NULL; - break; - case 4: - if (!PyArg_ParseTuple(args, "iiii;nlines,ncols,begin_y,begin_x", - &nlines,&ncols,&begin_y,&begin_x)) - return NULL; - break; - default: - PyErr_SetString(PyExc_TypeError, "newwin requires 2 or 4 arguments"); - return NULL; - } - - win = newwin(nlines,ncols,begin_y,begin_x); - if (win == NULL) { - PyErr_SetString(PyCursesError, catchall_NULL); - return NULL; - } + switch (PyTuple_Size(args)) { + case 2: + if (!PyArg_ParseTuple(args,"ii;nlines,ncols",&nlines,&ncols)) + return NULL; + break; + case 4: + if (!PyArg_ParseTuple(args, "iiii;nlines,ncols,begin_y,begin_x", + &nlines,&ncols,&begin_y,&begin_x)) + return NULL; + break; + default: + PyErr_SetString(PyExc_TypeError, "newwin requires 2 or 4 arguments"); + return NULL; + } + + win = newwin(nlines,ncols,begin_y,begin_x); + if (win == NULL) { + PyErr_SetString(PyCursesError, catchall_NULL); + return NULL; + } - return (PyObject *)PyCursesWindow_New(win); + return (PyObject *)PyCursesWindow_New(win); } static PyObject * PyCurses_Pair_Content(PyObject *self, PyObject *args) { - short pair,f,b; + short pair,f,b; + + PyCursesInitialised; + PyCursesInitialisedColor; - PyCursesInitialised; - PyCursesInitialisedColor; + switch(PyTuple_Size(args)) { + case 1: + if (!PyArg_ParseTuple(args, "h;pair", &pair)) return NULL; + break; + default: + PyErr_SetString(PyExc_TypeError, "pair_content requires 1 argument"); + return NULL; + } - switch(PyTuple_Size(args)) { - case 1: - if (!PyArg_ParseTuple(args, "h;pair", &pair)) return NULL; - break; - default: - PyErr_SetString(PyExc_TypeError, "pair_content requires 1 argument"); - return NULL; - } - - if (pair_content(pair, &f, &b)==ERR) { - PyErr_SetString(PyCursesError, - "Argument 1 was out of range. (1..COLOR_PAIRS-1)"); - return NULL; - } + if (pair_content(pair, &f, &b)==ERR) { + PyErr_SetString(PyCursesError, + "Argument 1 was out of range. (1..COLOR_PAIRS-1)"); + return NULL; + } - return Py_BuildValue("(ii)", f, b); + return Py_BuildValue("(ii)", f, b); } static PyObject * PyCurses_pair_number(PyObject *self, PyObject *args) { - int n; + int n; - PyCursesInitialised; - PyCursesInitialisedColor; + PyCursesInitialised; + PyCursesInitialisedColor; - switch(PyTuple_Size(args)) { - case 1: - if (!PyArg_ParseTuple(args, "i;pairvalue", &n)) return NULL; - break; - default: - PyErr_SetString(PyExc_TypeError, - "pair_number requires 1 argument"); - return NULL; - } + switch(PyTuple_Size(args)) { + case 1: + if (!PyArg_ParseTuple(args, "i;pairvalue", &n)) return NULL; + break; + default: + PyErr_SetString(PyExc_TypeError, + "pair_number requires 1 argument"); + return NULL; + } - return PyLong_FromLong((long) ((n & A_COLOR) >> 8)); + return PyLong_FromLong((long) ((n & A_COLOR) >> 8)); } static PyObject * PyCurses_Putp(PyObject *self, PyObject *args) { - char *str; + char *str; - if (!PyArg_ParseTuple(args,"s;str", &str)) return NULL; - return PyCursesCheckERR(putp(str), "putp"); + if (!PyArg_ParseTuple(args,"s;str", &str)) return NULL; + return PyCursesCheckERR(putp(str), "putp"); } static PyObject * PyCurses_QiFlush(PyObject *self, PyObject *args) { - int flag = 0; + int flag = 0; - PyCursesInitialised; + PyCursesInitialised; - switch(PyTuple_Size(args)) { - case 0: - qiflush(); - Py_INCREF(Py_None); - return Py_None; - case 1: - if (!PyArg_ParseTuple(args, "i;True(1) or False(0)", &flag)) return NULL; - if (flag) qiflush(); - else noqiflush(); - Py_INCREF(Py_None); - return Py_None; - default: - PyErr_SetString(PyExc_TypeError, "qiflush requires 0 or 1 arguments"); - return NULL; - } + switch(PyTuple_Size(args)) { + case 0: + qiflush(); + Py_INCREF(Py_None); + return Py_None; + case 1: + if (!PyArg_ParseTuple(args, "i;True(1) or False(0)", &flag)) return NULL; + if (flag) qiflush(); + else noqiflush(); + Py_INCREF(Py_None); + return Py_None; + default: + PyErr_SetString(PyExc_TypeError, "qiflush requires 0 or 1 arguments"); + return NULL; + } } /* Internal helper used for updating curses.LINES, curses.COLS, _curses.LINES @@ -2413,46 +2413,46 @@ static int update_lines_cols(void) { - PyObject *o; - PyObject *m = PyImport_ImportModuleNoBlock("curses"); + PyObject *o; + PyObject *m = PyImport_ImportModuleNoBlock("curses"); - if (!m) - return 0; + if (!m) + return 0; - o = PyLong_FromLong(LINES); - if (!o) { - Py_DECREF(m); - return 0; - } - if (PyObject_SetAttrString(m, "LINES", o)) { - Py_DECREF(m); - Py_DECREF(o); - return 0; - } - if (PyDict_SetItemString(ModDict, "LINES", o)) { - Py_DECREF(m); + o = PyLong_FromLong(LINES); + if (!o) { + Py_DECREF(m); + return 0; + } + if (PyObject_SetAttrString(m, "LINES", o)) { + Py_DECREF(m); + Py_DECREF(o); + return 0; + } + if (PyDict_SetItemString(ModDict, "LINES", o)) { + Py_DECREF(m); + Py_DECREF(o); + return 0; + } Py_DECREF(o); - return 0; - } - Py_DECREF(o); - o = PyLong_FromLong(COLS); - if (!o) { - Py_DECREF(m); - return 0; - } - if (PyObject_SetAttrString(m, "COLS", o)) { - Py_DECREF(m); + o = PyLong_FromLong(COLS); + if (!o) { + Py_DECREF(m); + return 0; + } + if (PyObject_SetAttrString(m, "COLS", o)) { + Py_DECREF(m); + Py_DECREF(o); + return 0; + } + if (PyDict_SetItemString(ModDict, "COLS", o)) { + Py_DECREF(m); + Py_DECREF(o); + return 0; + } Py_DECREF(o); - return 0; - } - if (PyDict_SetItemString(ModDict, "COLS", o)) { Py_DECREF(m); - Py_DECREF(o); - return 0; - } - Py_DECREF(o); - Py_DECREF(m); - return 1; + return 1; } #endif @@ -2460,21 +2460,21 @@ static PyObject * PyCurses_ResizeTerm(PyObject *self, PyObject *args) { - int lines; - int columns; - PyObject *result; - - PyCursesInitialised; - - if (!PyArg_ParseTuple(args,"ii:resizeterm", &lines, &columns)) - return NULL; - - result = PyCursesCheckERR(resizeterm(lines, columns), "resizeterm"); - if (!result) - return NULL; - if (!update_lines_cols()) - return NULL; - return result; + int lines; + int columns; + PyObject *result; + + PyCursesInitialised; + + if (!PyArg_ParseTuple(args,"ii:resizeterm", &lines, &columns)) + return NULL; + + result = PyCursesCheckERR(resizeterm(lines, columns), "resizeterm"); + if (!result) + return NULL; + if (!update_lines_cols()) + return NULL; + return result; } #endif @@ -2483,496 +2483,496 @@ static PyObject * PyCurses_Resize_Term(PyObject *self, PyObject *args) { - int lines; - int columns; + int lines; + int columns; - PyObject *result; + PyObject *result; - PyCursesInitialised; + PyCursesInitialised; - if (!PyArg_ParseTuple(args,"ii:resize_term", &lines, &columns)) - return NULL; - - result = PyCursesCheckERR(resize_term(lines, columns), "resize_term"); - if (!result) - return NULL; - if (!update_lines_cols()) - return NULL; - return result; + if (!PyArg_ParseTuple(args,"ii:resize_term", &lines, &columns)) + return NULL; + + result = PyCursesCheckERR(resize_term(lines, columns), "resize_term"); + if (!result) + return NULL; + if (!update_lines_cols()) + return NULL; + return result; } #endif /* HAVE_CURSES_RESIZE_TERM */ static PyObject * PyCurses_setsyx(PyObject *self, PyObject *args) { - int y,x; + int y,x; - PyCursesInitialised; + PyCursesInitialised; - if (PyTuple_Size(args)!=2) { - PyErr_SetString(PyExc_TypeError, "setsyx requires 2 arguments"); - return NULL; - } + if (PyTuple_Size(args)!=2) { + PyErr_SetString(PyExc_TypeError, "setsyx requires 2 arguments"); + return NULL; + } - if (!PyArg_ParseTuple(args, "ii;y, x", &y, &x)) return NULL; + if (!PyArg_ParseTuple(args, "ii;y, x", &y, &x)) return NULL; - setsyx(y,x); + setsyx(y,x); - Py_INCREF(Py_None); - return Py_None; + Py_INCREF(Py_None); + return Py_None; } static PyObject * PyCurses_Start_Color(PyObject *self) { - int code; - PyObject *c, *cp; + int code; + PyObject *c, *cp; - PyCursesInitialised; + PyCursesInitialised; - code = start_color(); - if (code != ERR) { - initialisedcolors = TRUE; - c = PyLong_FromLong((long) COLORS); - PyDict_SetItemString(ModDict, "COLORS", c); - Py_DECREF(c); - cp = PyLong_FromLong((long) COLOR_PAIRS); - PyDict_SetItemString(ModDict, "COLOR_PAIRS", cp); - Py_DECREF(cp); - Py_INCREF(Py_None); - return Py_None; - } else { - PyErr_SetString(PyCursesError, "start_color() returned ERR"); - return NULL; - } + code = start_color(); + if (code != ERR) { + initialisedcolors = TRUE; + c = PyLong_FromLong((long) COLORS); + PyDict_SetItemString(ModDict, "COLORS", c); + Py_DECREF(c); + cp = PyLong_FromLong((long) COLOR_PAIRS); + PyDict_SetItemString(ModDict, "COLOR_PAIRS", cp); + Py_DECREF(cp); + Py_INCREF(Py_None); + return Py_None; + } else { + PyErr_SetString(PyCursesError, "start_color() returned ERR"); + return NULL; + } } static PyObject * PyCurses_tigetflag(PyObject *self, PyObject *args) { - char *capname; + char *capname; - PyCursesSetupTermCalled; - - if (!PyArg_ParseTuple(args, "s", &capname)) - return NULL; + PyCursesSetupTermCalled; - return PyLong_FromLong( (long) tigetflag( capname ) ); + if (!PyArg_ParseTuple(args, "s", &capname)) + return NULL; + + return PyLong_FromLong( (long) tigetflag( capname ) ); } static PyObject * PyCurses_tigetnum(PyObject *self, PyObject *args) { - char *capname; + char *capname; - PyCursesSetupTermCalled; - - if (!PyArg_ParseTuple(args, "s", &capname)) - return NULL; + PyCursesSetupTermCalled; - return PyLong_FromLong( (long) tigetnum( capname ) ); + if (!PyArg_ParseTuple(args, "s", &capname)) + return NULL; + + return PyLong_FromLong( (long) tigetnum( capname ) ); } static PyObject * PyCurses_tigetstr(PyObject *self, PyObject *args) { - char *capname; + char *capname; + + PyCursesSetupTermCalled; - PyCursesSetupTermCalled; - - if (!PyArg_ParseTuple(args, "s", &capname)) - return NULL; - - capname = tigetstr( capname ); - if (capname == 0 || capname == (char*) -1) { - Py_INCREF(Py_None); - return Py_None; - } - return PyBytes_FromString( capname ); + if (!PyArg_ParseTuple(args, "s", &capname)) + return NULL; + + capname = tigetstr( capname ); + if (capname == 0 || capname == (char*) -1) { + Py_INCREF(Py_None); + return Py_None; + } + return PyBytes_FromString( capname ); } static PyObject * PyCurses_tparm(PyObject *self, PyObject *args) { - char* fmt; - char* result = NULL; - int i1=0,i2=0,i3=0,i4=0,i5=0,i6=0,i7=0,i8=0,i9=0; - - PyCursesSetupTermCalled; - - if (!PyArg_ParseTuple(args, "s|iiiiiiiii:tparm", - &fmt, &i1, &i2, &i3, &i4, - &i5, &i6, &i7, &i8, &i9)) { - return NULL; - } - - result = tparm(fmt,i1,i2,i3,i4,i5,i6,i7,i8,i9); - if (!result) { - PyErr_SetString(PyCursesError, "tparm() returned NULL"); - return NULL; - } + char* fmt; + char* result = NULL; + int i1=0,i2=0,i3=0,i4=0,i5=0,i6=0,i7=0,i8=0,i9=0; + + PyCursesSetupTermCalled; + + if (!PyArg_ParseTuple(args, "s|iiiiiiiii:tparm", + &fmt, &i1, &i2, &i3, &i4, + &i5, &i6, &i7, &i8, &i9)) { + return NULL; + } - return PyBytes_FromString(result); + result = tparm(fmt,i1,i2,i3,i4,i5,i6,i7,i8,i9); + if (!result) { + PyErr_SetString(PyCursesError, "tparm() returned NULL"); + return NULL; + } + + return PyBytes_FromString(result); } static PyObject * PyCurses_TypeAhead(PyObject *self, PyObject *args) { - int fd; + int fd; - PyCursesInitialised; + PyCursesInitialised; - if (!PyArg_ParseTuple(args,"i;fd",&fd)) return NULL; + if (!PyArg_ParseTuple(args,"i;fd",&fd)) return NULL; - return PyCursesCheckERR(typeahead( fd ), "typeahead"); + return PyCursesCheckERR(typeahead( fd ), "typeahead"); } static PyObject * PyCurses_UnCtrl(PyObject *self, PyObject *args) { - PyObject *temp; - chtype ch; + PyObject *temp; + chtype ch; - PyCursesInitialised; + PyCursesInitialised; - if (!PyArg_ParseTuple(args,"O;ch or int",&temp)) return NULL; + if (!PyArg_ParseTuple(args,"O;ch or int",&temp)) return NULL; - if (!PyCurses_ConvertToChtype(temp, &ch)) { - PyErr_SetString(PyExc_TypeError, "argument must be a ch or an int"); - return NULL; - } + if (!PyCurses_ConvertToChtype(temp, &ch)) { + PyErr_SetString(PyExc_TypeError, "argument must be a ch or an int"); + return NULL; + } - return PyBytes_FromString(unctrl(ch)); + return PyBytes_FromString(unctrl(ch)); } static PyObject * PyCurses_UngetCh(PyObject *self, PyObject *args) { - PyObject *temp; - chtype ch; + PyObject *temp; + chtype ch; - PyCursesInitialised; + PyCursesInitialised; - if (!PyArg_ParseTuple(args,"O;ch or int",&temp)) return NULL; + if (!PyArg_ParseTuple(args,"O;ch or int",&temp)) return NULL; - if (!PyCurses_ConvertToChtype(temp, &ch)) { - PyErr_SetString(PyExc_TypeError, "argument must be a ch or an int"); - return NULL; - } + if (!PyCurses_ConvertToChtype(temp, &ch)) { + PyErr_SetString(PyExc_TypeError, "argument must be a ch or an int"); + return NULL; + } - return PyCursesCheckERR(ungetch(ch), "ungetch"); + return PyCursesCheckERR(ungetch(ch), "ungetch"); } static PyObject * PyCurses_Use_Env(PyObject *self, PyObject *args) { - int flag; + int flag; - switch(PyTuple_Size(args)) { - case 1: - if (!PyArg_ParseTuple(args,"i;True(1), False(0)",&flag)) - return NULL; - break; - default: - PyErr_SetString(PyExc_TypeError, "use_env requires 1 argument"); - return NULL; - } - use_env(flag); - Py_INCREF(Py_None); - return Py_None; + switch(PyTuple_Size(args)) { + case 1: + if (!PyArg_ParseTuple(args,"i;True(1), False(0)",&flag)) + return NULL; + break; + default: + PyErr_SetString(PyExc_TypeError, "use_env requires 1 argument"); + return NULL; + } + use_env(flag); + Py_INCREF(Py_None); + return Py_None; } #ifndef STRICT_SYSV_CURSES static PyObject * PyCurses_Use_Default_Colors(PyObject *self) { - int code; + int code; - PyCursesInitialised; - PyCursesInitialisedColor; + PyCursesInitialised; + PyCursesInitialisedColor; - code = use_default_colors(); - if (code != ERR) { - Py_INCREF(Py_None); - return Py_None; - } else { - PyErr_SetString(PyCursesError, "use_default_colors() returned ERR"); - return NULL; - } + code = use_default_colors(); + if (code != ERR) { + Py_INCREF(Py_None); + return Py_None; + } else { + PyErr_SetString(PyCursesError, "use_default_colors() returned ERR"); + return NULL; + } } #endif /* STRICT_SYSV_CURSES */ /* List of functions defined in the module */ static PyMethodDef PyCurses_methods[] = { - {"baudrate", (PyCFunction)PyCurses_baudrate, METH_NOARGS}, - {"beep", (PyCFunction)PyCurses_beep, METH_NOARGS}, - {"can_change_color", (PyCFunction)PyCurses_can_change_color, METH_NOARGS}, - {"cbreak", (PyCFunction)PyCurses_cbreak, METH_VARARGS}, - {"color_content", (PyCFunction)PyCurses_Color_Content, METH_VARARGS}, - {"color_pair", (PyCFunction)PyCurses_color_pair, METH_VARARGS}, - {"curs_set", (PyCFunction)PyCurses_Curs_Set, METH_VARARGS}, - {"def_prog_mode", (PyCFunction)PyCurses_def_prog_mode, METH_NOARGS}, - {"def_shell_mode", (PyCFunction)PyCurses_def_shell_mode, METH_NOARGS}, - {"delay_output", (PyCFunction)PyCurses_Delay_Output, METH_VARARGS}, - {"doupdate", (PyCFunction)PyCurses_doupdate, METH_NOARGS}, - {"echo", (PyCFunction)PyCurses_echo, METH_VARARGS}, - {"endwin", (PyCFunction)PyCurses_endwin, METH_NOARGS}, - {"erasechar", (PyCFunction)PyCurses_EraseChar, METH_NOARGS}, - {"filter", (PyCFunction)PyCurses_filter, METH_NOARGS}, - {"flash", (PyCFunction)PyCurses_flash, METH_NOARGS}, - {"flushinp", (PyCFunction)PyCurses_flushinp, METH_NOARGS}, + {"baudrate", (PyCFunction)PyCurses_baudrate, METH_NOARGS}, + {"beep", (PyCFunction)PyCurses_beep, METH_NOARGS}, + {"can_change_color", (PyCFunction)PyCurses_can_change_color, METH_NOARGS}, + {"cbreak", (PyCFunction)PyCurses_cbreak, METH_VARARGS}, + {"color_content", (PyCFunction)PyCurses_Color_Content, METH_VARARGS}, + {"color_pair", (PyCFunction)PyCurses_color_pair, METH_VARARGS}, + {"curs_set", (PyCFunction)PyCurses_Curs_Set, METH_VARARGS}, + {"def_prog_mode", (PyCFunction)PyCurses_def_prog_mode, METH_NOARGS}, + {"def_shell_mode", (PyCFunction)PyCurses_def_shell_mode, METH_NOARGS}, + {"delay_output", (PyCFunction)PyCurses_Delay_Output, METH_VARARGS}, + {"doupdate", (PyCFunction)PyCurses_doupdate, METH_NOARGS}, + {"echo", (PyCFunction)PyCurses_echo, METH_VARARGS}, + {"endwin", (PyCFunction)PyCurses_endwin, METH_NOARGS}, + {"erasechar", (PyCFunction)PyCurses_EraseChar, METH_NOARGS}, + {"filter", (PyCFunction)PyCurses_filter, METH_NOARGS}, + {"flash", (PyCFunction)PyCurses_flash, METH_NOARGS}, + {"flushinp", (PyCFunction)PyCurses_flushinp, METH_NOARGS}, #ifdef NCURSES_MOUSE_VERSION - {"getmouse", (PyCFunction)PyCurses_GetMouse, METH_NOARGS}, - {"ungetmouse", (PyCFunction)PyCurses_UngetMouse, METH_VARARGS}, + {"getmouse", (PyCFunction)PyCurses_GetMouse, METH_NOARGS}, + {"ungetmouse", (PyCFunction)PyCurses_UngetMouse, METH_VARARGS}, #endif - {"getsyx", (PyCFunction)PyCurses_getsyx, METH_NOARGS}, - {"getwin", (PyCFunction)PyCurses_GetWin, METH_O}, - {"has_colors", (PyCFunction)PyCurses_has_colors, METH_NOARGS}, - {"has_ic", (PyCFunction)PyCurses_has_ic, METH_NOARGS}, - {"has_il", (PyCFunction)PyCurses_has_il, METH_NOARGS}, + {"getsyx", (PyCFunction)PyCurses_getsyx, METH_NOARGS}, + {"getwin", (PyCFunction)PyCurses_GetWin, METH_O}, + {"has_colors", (PyCFunction)PyCurses_has_colors, METH_NOARGS}, + {"has_ic", (PyCFunction)PyCurses_has_ic, METH_NOARGS}, + {"has_il", (PyCFunction)PyCurses_has_il, METH_NOARGS}, #ifndef STRICT_SYSV_CURSES - {"has_key", (PyCFunction)PyCurses_has_key, METH_VARARGS}, + {"has_key", (PyCFunction)PyCurses_has_key, METH_VARARGS}, #endif - {"halfdelay", (PyCFunction)PyCurses_HalfDelay, METH_VARARGS}, - {"init_color", (PyCFunction)PyCurses_Init_Color, METH_VARARGS}, - {"init_pair", (PyCFunction)PyCurses_Init_Pair, METH_VARARGS}, - {"initscr", (PyCFunction)PyCurses_InitScr, METH_NOARGS}, - {"intrflush", (PyCFunction)PyCurses_IntrFlush, METH_VARARGS}, - {"isendwin", (PyCFunction)PyCurses_isendwin, METH_NOARGS}, + {"halfdelay", (PyCFunction)PyCurses_HalfDelay, METH_VARARGS}, + {"init_color", (PyCFunction)PyCurses_Init_Color, METH_VARARGS}, + {"init_pair", (PyCFunction)PyCurses_Init_Pair, METH_VARARGS}, + {"initscr", (PyCFunction)PyCurses_InitScr, METH_NOARGS}, + {"intrflush", (PyCFunction)PyCurses_IntrFlush, METH_VARARGS}, + {"isendwin", (PyCFunction)PyCurses_isendwin, METH_NOARGS}, #ifdef HAVE_CURSES_IS_TERM_RESIZED - {"is_term_resized", (PyCFunction)PyCurses_Is_Term_Resized, METH_VARARGS}, + {"is_term_resized", (PyCFunction)PyCurses_Is_Term_Resized, METH_VARARGS}, #endif #if !defined(__NetBSD__) - {"keyname", (PyCFunction)PyCurses_KeyName, METH_VARARGS}, + {"keyname", (PyCFunction)PyCurses_KeyName, METH_VARARGS}, #endif - {"killchar", (PyCFunction)PyCurses_KillChar, METH_NOARGS}, - {"longname", (PyCFunction)PyCurses_longname, METH_NOARGS}, - {"meta", (PyCFunction)PyCurses_Meta, METH_VARARGS}, + {"killchar", (PyCFunction)PyCurses_KillChar, METH_NOARGS}, + {"longname", (PyCFunction)PyCurses_longname, METH_NOARGS}, + {"meta", (PyCFunction)PyCurses_Meta, METH_VARARGS}, #ifdef NCURSES_MOUSE_VERSION - {"mouseinterval", (PyCFunction)PyCurses_MouseInterval, METH_VARARGS}, - {"mousemask", (PyCFunction)PyCurses_MouseMask, METH_VARARGS}, + {"mouseinterval", (PyCFunction)PyCurses_MouseInterval, METH_VARARGS}, + {"mousemask", (PyCFunction)PyCurses_MouseMask, METH_VARARGS}, #endif - {"napms", (PyCFunction)PyCurses_Napms, METH_VARARGS}, - {"newpad", (PyCFunction)PyCurses_NewPad, METH_VARARGS}, - {"newwin", (PyCFunction)PyCurses_NewWindow, METH_VARARGS}, - {"nl", (PyCFunction)PyCurses_nl, METH_VARARGS}, - {"nocbreak", (PyCFunction)PyCurses_nocbreak, METH_NOARGS}, - {"noecho", (PyCFunction)PyCurses_noecho, METH_NOARGS}, - {"nonl", (PyCFunction)PyCurses_nonl, METH_NOARGS}, - {"noqiflush", (PyCFunction)PyCurses_noqiflush, METH_NOARGS}, - {"noraw", (PyCFunction)PyCurses_noraw, METH_NOARGS}, - {"pair_content", (PyCFunction)PyCurses_Pair_Content, METH_VARARGS}, - {"pair_number", (PyCFunction)PyCurses_pair_number, METH_VARARGS}, - {"putp", (PyCFunction)PyCurses_Putp, METH_VARARGS}, - {"qiflush", (PyCFunction)PyCurses_QiFlush, METH_VARARGS}, - {"raw", (PyCFunction)PyCurses_raw, METH_VARARGS}, - {"reset_prog_mode", (PyCFunction)PyCurses_reset_prog_mode, METH_NOARGS}, - {"reset_shell_mode", (PyCFunction)PyCurses_reset_shell_mode, METH_NOARGS}, - {"resetty", (PyCFunction)PyCurses_resetty, METH_NOARGS}, + {"napms", (PyCFunction)PyCurses_Napms, METH_VARARGS}, + {"newpad", (PyCFunction)PyCurses_NewPad, METH_VARARGS}, + {"newwin", (PyCFunction)PyCurses_NewWindow, METH_VARARGS}, + {"nl", (PyCFunction)PyCurses_nl, METH_VARARGS}, + {"nocbreak", (PyCFunction)PyCurses_nocbreak, METH_NOARGS}, + {"noecho", (PyCFunction)PyCurses_noecho, METH_NOARGS}, + {"nonl", (PyCFunction)PyCurses_nonl, METH_NOARGS}, + {"noqiflush", (PyCFunction)PyCurses_noqiflush, METH_NOARGS}, + {"noraw", (PyCFunction)PyCurses_noraw, METH_NOARGS}, + {"pair_content", (PyCFunction)PyCurses_Pair_Content, METH_VARARGS}, + {"pair_number", (PyCFunction)PyCurses_pair_number, METH_VARARGS}, + {"putp", (PyCFunction)PyCurses_Putp, METH_VARARGS}, + {"qiflush", (PyCFunction)PyCurses_QiFlush, METH_VARARGS}, + {"raw", (PyCFunction)PyCurses_raw, METH_VARARGS}, + {"reset_prog_mode", (PyCFunction)PyCurses_reset_prog_mode, METH_NOARGS}, + {"reset_shell_mode", (PyCFunction)PyCurses_reset_shell_mode, METH_NOARGS}, + {"resetty", (PyCFunction)PyCurses_resetty, METH_NOARGS}, #ifdef HAVE_CURSES_RESIZETERM - {"resizeterm", (PyCFunction)PyCurses_ResizeTerm, METH_VARARGS}, + {"resizeterm", (PyCFunction)PyCurses_ResizeTerm, METH_VARARGS}, #endif #ifdef HAVE_CURSES_RESIZE_TERM - {"resize_term", (PyCFunction)PyCurses_Resize_Term, METH_VARARGS}, + {"resize_term", (PyCFunction)PyCurses_Resize_Term, METH_VARARGS}, #endif - {"savetty", (PyCFunction)PyCurses_savetty, METH_NOARGS}, - {"setsyx", (PyCFunction)PyCurses_setsyx, METH_VARARGS}, - {"setupterm", (PyCFunction)PyCurses_setupterm, - METH_VARARGS|METH_KEYWORDS}, - {"start_color", (PyCFunction)PyCurses_Start_Color, METH_NOARGS}, - {"termattrs", (PyCFunction)PyCurses_termattrs, METH_NOARGS}, - {"termname", (PyCFunction)PyCurses_termname, METH_NOARGS}, - {"tigetflag", (PyCFunction)PyCurses_tigetflag, METH_VARARGS}, - {"tigetnum", (PyCFunction)PyCurses_tigetnum, METH_VARARGS}, - {"tigetstr", (PyCFunction)PyCurses_tigetstr, METH_VARARGS}, - {"tparm", (PyCFunction)PyCurses_tparm, METH_VARARGS}, - {"typeahead", (PyCFunction)PyCurses_TypeAhead, METH_VARARGS}, - {"unctrl", (PyCFunction)PyCurses_UnCtrl, METH_VARARGS}, - {"ungetch", (PyCFunction)PyCurses_UngetCh, METH_VARARGS}, - {"use_env", (PyCFunction)PyCurses_Use_Env, METH_VARARGS}, + {"savetty", (PyCFunction)PyCurses_savetty, METH_NOARGS}, + {"setsyx", (PyCFunction)PyCurses_setsyx, METH_VARARGS}, + {"setupterm", (PyCFunction)PyCurses_setupterm, + METH_VARARGS|METH_KEYWORDS}, + {"start_color", (PyCFunction)PyCurses_Start_Color, METH_NOARGS}, + {"termattrs", (PyCFunction)PyCurses_termattrs, METH_NOARGS}, + {"termname", (PyCFunction)PyCurses_termname, METH_NOARGS}, + {"tigetflag", (PyCFunction)PyCurses_tigetflag, METH_VARARGS}, + {"tigetnum", (PyCFunction)PyCurses_tigetnum, METH_VARARGS}, + {"tigetstr", (PyCFunction)PyCurses_tigetstr, METH_VARARGS}, + {"tparm", (PyCFunction)PyCurses_tparm, METH_VARARGS}, + {"typeahead", (PyCFunction)PyCurses_TypeAhead, METH_VARARGS}, + {"unctrl", (PyCFunction)PyCurses_UnCtrl, METH_VARARGS}, + {"ungetch", (PyCFunction)PyCurses_UngetCh, METH_VARARGS}, + {"use_env", (PyCFunction)PyCurses_Use_Env, METH_VARARGS}, #ifndef STRICT_SYSV_CURSES - {"use_default_colors", (PyCFunction)PyCurses_Use_Default_Colors, METH_NOARGS}, + {"use_default_colors", (PyCFunction)PyCurses_Use_Default_Colors, METH_NOARGS}, #endif - {NULL, NULL} /* sentinel */ + {NULL, NULL} /* sentinel */ }; /* Initialization function for the module */ static struct PyModuleDef _cursesmodule = { - PyModuleDef_HEAD_INIT, - "_curses", - NULL, - -1, - PyCurses_methods, - NULL, - NULL, - NULL, - NULL + PyModuleDef_HEAD_INIT, + "_curses", + NULL, + -1, + PyCurses_methods, + NULL, + NULL, + NULL, + NULL }; PyMODINIT_FUNC PyInit__curses(void) { - PyObject *m, *d, *v, *c_api_object; - static void *PyCurses_API[PyCurses_API_pointers]; + PyObject *m, *d, *v, *c_api_object; + static void *PyCurses_API[PyCurses_API_pointers]; + + /* Initialize object type */ + if (PyType_Ready(&PyCursesWindow_Type) < 0) + return NULL; + + /* Initialize the C API pointer array */ + PyCurses_API[0] = (void *)&PyCursesWindow_Type; + PyCurses_API[1] = (void *)func_PyCursesSetupTermCalled; + PyCurses_API[2] = (void *)func_PyCursesInitialised; + PyCurses_API[3] = (void *)func_PyCursesInitialisedColor; + + /* Create the module and add the functions */ + m = PyModule_Create(&_cursesmodule); + if (m == NULL) + return NULL; - /* Initialize object type */ - if (PyType_Ready(&PyCursesWindow_Type) < 0) - return NULL; - - /* Initialize the C API pointer array */ - PyCurses_API[0] = (void *)&PyCursesWindow_Type; - PyCurses_API[1] = (void *)func_PyCursesSetupTermCalled; - PyCurses_API[2] = (void *)func_PyCursesInitialised; - PyCurses_API[3] = (void *)func_PyCursesInitialisedColor; - - /* Create the module and add the functions */ - m = PyModule_Create(&_cursesmodule); - if (m == NULL) - return NULL; - - /* Add some symbolic constants to the module */ - d = PyModule_GetDict(m); - if (d == NULL) - return NULL; - ModDict = d; /* For PyCurses_InitScr to use later */ - - /* Add a capsule for the C API */ - c_api_object = PyCapsule_New(PyCurses_API, PyCurses_CAPSULE_NAME, NULL); - PyDict_SetItemString(d, "_C_API", c_api_object); - Py_DECREF(c_api_object); - - /* For exception curses.error */ - PyCursesError = PyErr_NewException("_curses.error", NULL, NULL); - PyDict_SetItemString(d, "error", PyCursesError); - - /* Make the version available */ - v = PyBytes_FromString(PyCursesVersion); - PyDict_SetItemString(d, "version", v); - PyDict_SetItemString(d, "__version__", v); - Py_DECREF(v); - - SetDictInt("ERR", ERR); - SetDictInt("OK", OK); - - /* Here are some attributes you can add to chars to print */ - - SetDictInt("A_ATTRIBUTES", A_ATTRIBUTES); - SetDictInt("A_NORMAL", A_NORMAL); - SetDictInt("A_STANDOUT", A_STANDOUT); - SetDictInt("A_UNDERLINE", A_UNDERLINE); - SetDictInt("A_REVERSE", A_REVERSE); - SetDictInt("A_BLINK", A_BLINK); - SetDictInt("A_DIM", A_DIM); - SetDictInt("A_BOLD", A_BOLD); - SetDictInt("A_ALTCHARSET", A_ALTCHARSET); + /* Add some symbolic constants to the module */ + d = PyModule_GetDict(m); + if (d == NULL) + return NULL; + ModDict = d; /* For PyCurses_InitScr to use later */ + + /* Add a capsule for the C API */ + c_api_object = PyCapsule_New(PyCurses_API, PyCurses_CAPSULE_NAME, NULL); + PyDict_SetItemString(d, "_C_API", c_api_object); + Py_DECREF(c_api_object); + + /* For exception curses.error */ + PyCursesError = PyErr_NewException("_curses.error", NULL, NULL); + PyDict_SetItemString(d, "error", PyCursesError); + + /* Make the version available */ + v = PyBytes_FromString(PyCursesVersion); + PyDict_SetItemString(d, "version", v); + PyDict_SetItemString(d, "__version__", v); + Py_DECREF(v); + + SetDictInt("ERR", ERR); + SetDictInt("OK", OK); + + /* Here are some attributes you can add to chars to print */ + + SetDictInt("A_ATTRIBUTES", A_ATTRIBUTES); + SetDictInt("A_NORMAL", A_NORMAL); + SetDictInt("A_STANDOUT", A_STANDOUT); + SetDictInt("A_UNDERLINE", A_UNDERLINE); + SetDictInt("A_REVERSE", A_REVERSE); + SetDictInt("A_BLINK", A_BLINK); + SetDictInt("A_DIM", A_DIM); + SetDictInt("A_BOLD", A_BOLD); + SetDictInt("A_ALTCHARSET", A_ALTCHARSET); #if !defined(__NetBSD__) - SetDictInt("A_INVIS", A_INVIS); + SetDictInt("A_INVIS", A_INVIS); #endif - SetDictInt("A_PROTECT", A_PROTECT); - SetDictInt("A_CHARTEXT", A_CHARTEXT); - SetDictInt("A_COLOR", A_COLOR); + SetDictInt("A_PROTECT", A_PROTECT); + SetDictInt("A_CHARTEXT", A_CHARTEXT); + SetDictInt("A_COLOR", A_COLOR); - /* The following are never available with strict SYSV curses */ + /* The following are never available with strict SYSV curses */ #ifdef A_HORIZONTAL - SetDictInt("A_HORIZONTAL", A_HORIZONTAL); + SetDictInt("A_HORIZONTAL", A_HORIZONTAL); #endif #ifdef A_LEFT - SetDictInt("A_LEFT", A_LEFT); + SetDictInt("A_LEFT", A_LEFT); #endif #ifdef A_LOW - SetDictInt("A_LOW", A_LOW); + SetDictInt("A_LOW", A_LOW); #endif #ifdef A_RIGHT - SetDictInt("A_RIGHT", A_RIGHT); + SetDictInt("A_RIGHT", A_RIGHT); #endif #ifdef A_TOP - SetDictInt("A_TOP", A_TOP); + SetDictInt("A_TOP", A_TOP); #endif #ifdef A_VERTICAL - SetDictInt("A_VERTICAL", A_VERTICAL); + SetDictInt("A_VERTICAL", A_VERTICAL); #endif - SetDictInt("COLOR_BLACK", COLOR_BLACK); - SetDictInt("COLOR_RED", COLOR_RED); - SetDictInt("COLOR_GREEN", COLOR_GREEN); - SetDictInt("COLOR_YELLOW", COLOR_YELLOW); - SetDictInt("COLOR_BLUE", COLOR_BLUE); - SetDictInt("COLOR_MAGENTA", COLOR_MAGENTA); - SetDictInt("COLOR_CYAN", COLOR_CYAN); - SetDictInt("COLOR_WHITE", COLOR_WHITE); + SetDictInt("COLOR_BLACK", COLOR_BLACK); + SetDictInt("COLOR_RED", COLOR_RED); + SetDictInt("COLOR_GREEN", COLOR_GREEN); + SetDictInt("COLOR_YELLOW", COLOR_YELLOW); + SetDictInt("COLOR_BLUE", COLOR_BLUE); + SetDictInt("COLOR_MAGENTA", COLOR_MAGENTA); + SetDictInt("COLOR_CYAN", COLOR_CYAN); + SetDictInt("COLOR_WHITE", COLOR_WHITE); #ifdef NCURSES_MOUSE_VERSION - /* Mouse-related constants */ - SetDictInt("BUTTON1_PRESSED", BUTTON1_PRESSED); - SetDictInt("BUTTON1_RELEASED", BUTTON1_RELEASED); - SetDictInt("BUTTON1_CLICKED", BUTTON1_CLICKED); - SetDictInt("BUTTON1_DOUBLE_CLICKED", BUTTON1_DOUBLE_CLICKED); - SetDictInt("BUTTON1_TRIPLE_CLICKED", BUTTON1_TRIPLE_CLICKED); - - SetDictInt("BUTTON2_PRESSED", BUTTON2_PRESSED); - SetDictInt("BUTTON2_RELEASED", BUTTON2_RELEASED); - SetDictInt("BUTTON2_CLICKED", BUTTON2_CLICKED); - SetDictInt("BUTTON2_DOUBLE_CLICKED", BUTTON2_DOUBLE_CLICKED); - SetDictInt("BUTTON2_TRIPLE_CLICKED", BUTTON2_TRIPLE_CLICKED); - - SetDictInt("BUTTON3_PRESSED", BUTTON3_PRESSED); - SetDictInt("BUTTON3_RELEASED", BUTTON3_RELEASED); - SetDictInt("BUTTON3_CLICKED", BUTTON3_CLICKED); - SetDictInt("BUTTON3_DOUBLE_CLICKED", BUTTON3_DOUBLE_CLICKED); - SetDictInt("BUTTON3_TRIPLE_CLICKED", BUTTON3_TRIPLE_CLICKED); - - SetDictInt("BUTTON4_PRESSED", BUTTON4_PRESSED); - SetDictInt("BUTTON4_RELEASED", BUTTON4_RELEASED); - SetDictInt("BUTTON4_CLICKED", BUTTON4_CLICKED); - SetDictInt("BUTTON4_DOUBLE_CLICKED", BUTTON4_DOUBLE_CLICKED); - SetDictInt("BUTTON4_TRIPLE_CLICKED", BUTTON4_TRIPLE_CLICKED); - - SetDictInt("BUTTON_SHIFT", BUTTON_SHIFT); - SetDictInt("BUTTON_CTRL", BUTTON_CTRL); - SetDictInt("BUTTON_ALT", BUTTON_ALT); - - SetDictInt("ALL_MOUSE_EVENTS", ALL_MOUSE_EVENTS); - SetDictInt("REPORT_MOUSE_POSITION", REPORT_MOUSE_POSITION); -#endif - /* Now set everything up for KEY_ variables */ - { - int key; - char *key_n; - char *key_n2; + /* Mouse-related constants */ + SetDictInt("BUTTON1_PRESSED", BUTTON1_PRESSED); + SetDictInt("BUTTON1_RELEASED", BUTTON1_RELEASED); + SetDictInt("BUTTON1_CLICKED", BUTTON1_CLICKED); + SetDictInt("BUTTON1_DOUBLE_CLICKED", BUTTON1_DOUBLE_CLICKED); + SetDictInt("BUTTON1_TRIPLE_CLICKED", BUTTON1_TRIPLE_CLICKED); + + SetDictInt("BUTTON2_PRESSED", BUTTON2_PRESSED); + SetDictInt("BUTTON2_RELEASED", BUTTON2_RELEASED); + SetDictInt("BUTTON2_CLICKED", BUTTON2_CLICKED); + SetDictInt("BUTTON2_DOUBLE_CLICKED", BUTTON2_DOUBLE_CLICKED); + SetDictInt("BUTTON2_TRIPLE_CLICKED", BUTTON2_TRIPLE_CLICKED); + + SetDictInt("BUTTON3_PRESSED", BUTTON3_PRESSED); + SetDictInt("BUTTON3_RELEASED", BUTTON3_RELEASED); + SetDictInt("BUTTON3_CLICKED", BUTTON3_CLICKED); + SetDictInt("BUTTON3_DOUBLE_CLICKED", BUTTON3_DOUBLE_CLICKED); + SetDictInt("BUTTON3_TRIPLE_CLICKED", BUTTON3_TRIPLE_CLICKED); + + SetDictInt("BUTTON4_PRESSED", BUTTON4_PRESSED); + SetDictInt("BUTTON4_RELEASED", BUTTON4_RELEASED); + SetDictInt("BUTTON4_CLICKED", BUTTON4_CLICKED); + SetDictInt("BUTTON4_DOUBLE_CLICKED", BUTTON4_DOUBLE_CLICKED); + SetDictInt("BUTTON4_TRIPLE_CLICKED", BUTTON4_TRIPLE_CLICKED); + + SetDictInt("BUTTON_SHIFT", BUTTON_SHIFT); + SetDictInt("BUTTON_CTRL", BUTTON_CTRL); + SetDictInt("BUTTON_ALT", BUTTON_ALT); + + SetDictInt("ALL_MOUSE_EVENTS", ALL_MOUSE_EVENTS); + SetDictInt("REPORT_MOUSE_POSITION", REPORT_MOUSE_POSITION); +#endif + /* Now set everything up for KEY_ variables */ + { + int key; + char *key_n; + char *key_n2; #if !defined(__NetBSD__) - for (key=KEY_MIN;key < KEY_MAX; key++) { - key_n = (char *)keyname(key); - if (key_n == NULL || strcmp(key_n,"UNKNOWN KEY")==0) - continue; - if (strncmp(key_n,"KEY_F(",6)==0) { - char *p1, *p2; - key_n2 = malloc(strlen(key_n)+1); - if (!key_n2) { - PyErr_NoMemory(); - break; - } - p1 = key_n; - p2 = key_n2; - while (*p1) { - if (*p1 != '(' && *p1 != ')') { - *p2 = *p1; - p2++; - } - p1++; - } - *p2 = (char)0; - } else - key_n2 = key_n; - SetDictInt(key_n2,key); - if (key_n2 != key_n) - free(key_n2); - } -#endif - SetDictInt("KEY_MIN", KEY_MIN); - SetDictInt("KEY_MAX", KEY_MAX); - } - return m; + for (key=KEY_MIN;key < KEY_MAX; key++) { + key_n = (char *)keyname(key); + if (key_n == NULL || strcmp(key_n,"UNKNOWN KEY")==0) + continue; + if (strncmp(key_n,"KEY_F(",6)==0) { + char *p1, *p2; + key_n2 = malloc(strlen(key_n)+1); + if (!key_n2) { + PyErr_NoMemory(); + break; + } + p1 = key_n; + p2 = key_n2; + while (*p1) { + if (*p1 != '(' && *p1 != ')') { + *p2 = *p1; + p2++; + } + p1++; + } + *p2 = (char)0; + } else + key_n2 = key_n; + SetDictInt(key_n2,key); + if (key_n2 != key_n) + free(key_n2); + } +#endif + SetDictInt("KEY_MIN", KEY_MIN); + SetDictInt("KEY_MAX", KEY_MAX); + } + return m; } Modified: python/branches/py3k-jit/Modules/_io/fileio.c ============================================================================== --- python/branches/py3k-jit/Modules/_io/fileio.c (original) +++ python/branches/py3k-jit/Modules/_io/fileio.c Tue May 18 19:58:30 2010 @@ -247,8 +247,7 @@ if (u == NULL) return -1; - stringobj = PyUnicode_AsEncodedString( - u, Py_FileSystemDefaultEncoding, "surrogateescape"); + stringobj = PyUnicode_EncodeFSDefault(u); Py_DECREF(u); if (stringobj == NULL) return -1; Modified: python/branches/py3k-jit/Modules/_ssl.c ============================================================================== --- python/branches/py3k-jit/Modules/_ssl.c (original) +++ python/branches/py3k-jit/Modules/_ssl.c Tue May 18 19:58:30 2010 @@ -115,23 +115,29 @@ typedef struct { PyObject_HEAD - PyObject *Socket; /* weakref to socket on which we're layered */ - SSL_CTX* ctx; - SSL* ssl; - X509* peer_cert; - int shutdown_seen_zero; - -} PySSLObject; - -static PyTypeObject PySSL_Type; -static PyObject *PySSL_SSLwrite(PySSLObject *self, PyObject *args); -static PyObject *PySSL_SSLread(PySSLObject *self, PyObject *args); + SSL_CTX *ctx; +} PySSLContext; + +typedef struct { + PyObject_HEAD + PyObject *Socket; /* weakref to socket on which we're layered */ + SSL *ssl; + X509 *peer_cert; + int shutdown_seen_zero; +} PySSLSocket; + +static PyTypeObject PySSLContext_Type; +static PyTypeObject PySSLSocket_Type; + +static PyObject *PySSL_SSLwrite(PySSLSocket *self, PyObject *args); +static PyObject *PySSL_SSLread(PySSLSocket *self, PyObject *args); static int check_socket_and_wait_for_timeout(PySocketSockObject *s, int writing); -static PyObject *PySSL_peercert(PySSLObject *self, PyObject *args); -static PyObject *PySSL_cipher(PySSLObject *self); +static PyObject *PySSL_peercert(PySSLSocket *self, PyObject *args); +static PyObject *PySSL_cipher(PySSLSocket *self); -#define PySSLObject_Check(v) (Py_TYPE(v) == &PySSL_Type) +#define PySSLContext_Check(v) (Py_TYPE(v) == &PySSLContext_Type) +#define PySSLSocket_Check(v) (Py_TYPE(v) == &PySSLSocket_Type) typedef enum { SOCKET_IS_NONBLOCKING, @@ -154,7 +160,7 @@ */ static PyObject * -PySSL_SetError(PySSLObject *obj, int ret, char *filename, int lineno) +PySSL_SetError(PySSLSocket *obj, int ret, char *filename, int lineno) { PyObject *v; char buf[2048]; @@ -199,6 +205,7 @@ errstr = "EOF occurred in violation of protocol"; } else if (ret == -1) { /* underlying BIO reported an I/O error */ + ERR_clear_error(); return s->errorhandler(); } else { /* possible? */ p = PY_SSL_ERROR_SYSCALL; @@ -231,6 +238,7 @@ errstr = ERR_error_string(ERR_peek_last_error(), NULL); } PyOS_snprintf(buf, sizeof(buf), "_ssl.c:%d: %s", lineno, errstr); + ERR_clear_error(); v = Py_BuildValue("(is)", p, buf); if (v != NULL) { PyErr_SetObject(PySSLErrorObject, v); @@ -250,6 +258,7 @@ errstr = ERR_error_string(errcode, NULL); } PyOS_snprintf(buf, sizeof(buf), "_ssl.c:%d: %s", lineno, errstr); + ERR_clear_error(); v = Py_BuildValue("(is)", errcode, buf); if (v != NULL) { PyErr_SetObject(PySSLErrorObject, v); @@ -258,126 +267,28 @@ return NULL; } -static PySSLObject * -newPySSLObject(PySocketSockObject *Sock, char *key_file, char *cert_file, - enum py_ssl_server_or_client socket_type, - enum py_ssl_cert_requirements certreq, - enum py_ssl_version proto_version, - char *cacerts_file, char *ciphers) +static PySSLSocket * +newPySSLSocket(SSL_CTX *ctx, PySocketSockObject *sock, + enum py_ssl_server_or_client socket_type) { - PySSLObject *self; - char *errstr = NULL; - int ret; - int verification_mode; + PySSLSocket *self; - self = PyObject_New(PySSLObject, &PySSL_Type); /* Create new object */ + self = PyObject_New(PySSLSocket, &PySSLSocket_Type); if (self == NULL) return NULL; + self->peer_cert = NULL; self->ssl = NULL; - self->ctx = NULL; self->Socket = NULL; /* Make sure the SSL error state is initialized */ (void) ERR_get_state(); ERR_clear_error(); - if ((key_file && !cert_file) || (!key_file && cert_file)) { - errstr = ERRSTR("Both the key & certificate files " - "must be specified"); - goto fail; - } - - if ((socket_type == PY_SSL_SERVER) && - ((key_file == NULL) || (cert_file == NULL))) { - errstr = ERRSTR("Both the key & certificate files " - "must be specified for server-side operation"); - goto fail; - } - - PySSL_BEGIN_ALLOW_THREADS - if (proto_version == PY_SSL_VERSION_TLS1) - self->ctx = SSL_CTX_new(TLSv1_method()); /* Set up context */ - else if (proto_version == PY_SSL_VERSION_SSL3) - self->ctx = SSL_CTX_new(SSLv3_method()); /* Set up context */ - else if (proto_version == PY_SSL_VERSION_SSL2) - self->ctx = SSL_CTX_new(SSLv2_method()); /* Set up context */ - else if (proto_version == PY_SSL_VERSION_SSL23) - self->ctx = SSL_CTX_new(SSLv23_method()); /* Set up context */ - PySSL_END_ALLOW_THREADS - - if (self->ctx == NULL) { - errstr = ERRSTR("Invalid SSL protocol variant specified."); - goto fail; - } - - if (ciphers != NULL) { - ret = SSL_CTX_set_cipher_list(self->ctx, ciphers); - if (ret == 0) { - errstr = ERRSTR("No cipher can be selected."); - goto fail; - } - } - - if (certreq != PY_SSL_CERT_NONE) { - if (cacerts_file == NULL) { - errstr = ERRSTR("No root certificates specified for " - "verification of other-side certificates."); - goto fail; - } else { - PySSL_BEGIN_ALLOW_THREADS - ret = SSL_CTX_load_verify_locations(self->ctx, - cacerts_file, - NULL); - PySSL_END_ALLOW_THREADS - if (ret != 1) { - _setSSLError(NULL, 0, __FILE__, __LINE__); - goto fail; - } - } - } - if (key_file) { - PySSL_BEGIN_ALLOW_THREADS - ret = SSL_CTX_use_PrivateKey_file(self->ctx, key_file, - SSL_FILETYPE_PEM); - PySSL_END_ALLOW_THREADS - if (ret != 1) { - _setSSLError(NULL, ret, __FILE__, __LINE__); - goto fail; - } - - PySSL_BEGIN_ALLOW_THREADS - ret = SSL_CTX_use_certificate_chain_file(self->ctx, - cert_file); - PySSL_END_ALLOW_THREADS - if (ret != 1) { - /* - fprintf(stderr, "ret is %d, errcode is %lu, %lu, with file \"%s\"\n", - ret, ERR_peek_error(), ERR_peek_last_error(), cert_file); - */ - if (ERR_peek_last_error() != 0) { - _setSSLError(NULL, ret, __FILE__, __LINE__); - goto fail; - } - } - } - - /* ssl compatibility */ - SSL_CTX_set_options(self->ctx, SSL_OP_ALL); - - verification_mode = SSL_VERIFY_NONE; - if (certreq == PY_SSL_CERT_OPTIONAL) - verification_mode = SSL_VERIFY_PEER; - else if (certreq == PY_SSL_CERT_REQUIRED) - verification_mode = (SSL_VERIFY_PEER | - SSL_VERIFY_FAIL_IF_NO_PEER_CERT); - SSL_CTX_set_verify(self->ctx, verification_mode, - NULL); /* set verify lvl */ - PySSL_BEGIN_ALLOW_THREADS - self->ssl = SSL_new(self->ctx); /* New ssl struct */ + self->ssl = SSL_new(ctx); PySSL_END_ALLOW_THREADS - SSL_set_fd(self->ssl, Sock->sock_fd); /* Set the socket for SSL */ + SSL_set_fd(self->ssl, sock->sock_fd); #ifdef SSL_MODE_AUTO_RETRY SSL_set_mode(self->ssl, SSL_MODE_AUTO_RETRY); #endif @@ -385,8 +296,7 @@ /* If the socket is in non-blocking mode or timeout mode, set the BIO * to non-blocking mode (blocking is the default) */ - if (Sock->sock_timeout >= 0.0) { - /* Set both the read and write BIO's to non-blocking mode */ + if (sock->sock_timeout >= 0.0) { BIO_set_nbio(SSL_get_rbio(self->ssl), 1); BIO_set_nbio(SSL_get_wbio(self->ssl), 1); } @@ -398,57 +308,13 @@ SSL_set_accept_state(self->ssl); PySSL_END_ALLOW_THREADS - self->Socket = PyWeakref_NewRef((PyObject *) Sock, Py_None); + self->Socket = PyWeakref_NewRef((PyObject *) sock, NULL); return self; - fail: - if (errstr) - PyErr_SetString(PySSLErrorObject, errstr); - Py_DECREF(self); - return NULL; } -static PyObject * -PySSL_sslwrap(PyObject *self, PyObject *args) -{ - PySocketSockObject *Sock; - int server_side = 0; - int verification_mode = PY_SSL_CERT_NONE; - int protocol = PY_SSL_VERSION_SSL23; - char *key_file = NULL; - char *cert_file = NULL; - char *cacerts_file = NULL; - char *ciphers = NULL; - - if (!PyArg_ParseTuple(args, "O!i|zziizz:sslwrap", - PySocketModule.Sock_Type, - &Sock, - &server_side, - &key_file, &cert_file, - &verification_mode, &protocol, - &cacerts_file, &ciphers)) - return NULL; - - /* - fprintf(stderr, - "server_side is %d, keyfile %p, certfile %p, verify_mode %d, " - "protocol %d, certs %p\n", - server_side, key_file, cert_file, verification_mode, - protocol, cacerts_file); - */ - - return (PyObject *) newPySSLObject(Sock, key_file, cert_file, - server_side, verification_mode, - protocol, cacerts_file, - ciphers); -} - -PyDoc_STRVAR(ssl_doc, -"sslwrap(socket, server_side, [keyfile, certfile, certs_mode, protocol,\n" -" cacertsfile, ciphers]) -> sslobject"); - /* SSL object methods */ -static PyObject *PySSL_SSLdo_handshake(PySSLObject *self) +static PyObject *PySSL_SSLdo_handshake(PySSLSocket *self) { int ret; int err; @@ -948,13 +814,13 @@ PySSL_test_decode_certificate (PyObject *mod, PyObject *args) { PyObject *retval = NULL; - char *filename = NULL; + PyObject *filename; X509 *x=NULL; BIO *cert; int verbose = 1; - if (!PyArg_ParseTuple(args, "s|i:test_decode_certificate", - &filename, &verbose)) + if (!PyArg_ParseTuple(args, "O&|i:test_decode_certificate", + PyUnicode_FSConverter, &filename, &verbose)) return NULL; if ((cert=BIO_new(BIO_s_file())) == NULL) { @@ -963,7 +829,7 @@ goto fail0; } - if (BIO_read_filename(cert,filename) <= 0) { + if (BIO_read_filename(cert, PyBytes_AsString(filename)) <= 0) { PyErr_SetString(PySSLErrorObject, "Can't open file"); goto fail0; @@ -979,14 +845,14 @@ retval = _decode_certificate(x, verbose); fail0: - + Py_DECREF(filename); if (cert != NULL) BIO_free(cert); return retval; } static PyObject * -PySSL_peercert(PySSLObject *self, PyObject *args) +PySSL_peercert(PySSLSocket *self, PyObject *args) { PyObject *retval = NULL; int len; @@ -1017,8 +883,7 @@ return retval; } else { - - verification = SSL_CTX_get_verify_mode(self->ctx); + verification = SSL_CTX_get_verify_mode(SSL_get_SSL_CTX(self->ssl)); if ((verification & SSL_VERIFY_PEER) == 0) return PyDict_New(); else @@ -1038,7 +903,7 @@ peer certificate, or None if no certificate was provided. This will\n\ return the certificate even if it wasn't validated."); -static PyObject *PySSL_cipher (PySSLObject *self) { +static PyObject *PySSL_cipher (PySSLSocket *self) { PyObject *retval, *v; SSL_CIPHER *current; @@ -1084,14 +949,12 @@ return NULL; } -static void PySSL_dealloc(PySSLObject *self) +static void PySSL_dealloc(PySSLSocket *self) { if (self->peer_cert) /* Possible not to have one? */ X509_free (self->peer_cert); if (self->ssl) SSL_free(self->ssl); - if (self->ctx) - SSL_CTX_free(self->ctx); Py_XDECREF(self->Socket); PyObject_Del(self); } @@ -1166,7 +1029,7 @@ return rc == 0 ? SOCKET_HAS_TIMED_OUT : SOCKET_OPERATION_OK; } -static PyObject *PySSL_SSLwrite(PySSLObject *self, PyObject *args) +static PyObject *PySSL_SSLwrite(PySSLSocket *self, PyObject *args) { Py_buffer buf; int len; @@ -1250,7 +1113,7 @@ Writes the string s into the SSL object. Returns the number\n\ of bytes written."); -static PyObject *PySSL_SSLpending(PySSLObject *self) +static PyObject *PySSL_SSLpending(PySSLSocket *self) { int count = 0; @@ -1269,7 +1132,7 @@ Returns the number of already decrypted bytes available for read,\n\ pending on the connection.\n"); -static PyObject *PySSL_SSLread(PySSLObject *self, PyObject *args) +static PyObject *PySSL_SSLread(PySSLSocket *self, PyObject *args) { PyObject *dest = NULL; Py_buffer buf; @@ -1392,7 +1255,7 @@ \n\ Read up to len bytes from the SSL socket."); -static PyObject *PySSL_SSLshutdown(PySSLObject *self) +static PyObject *PySSL_SSLshutdown(PySSLSocket *self) { int err, ssl_err, sockstate, nonblocking; int zeros = 0; @@ -1497,10 +1360,10 @@ {NULL, NULL} }; -static PyTypeObject PySSL_Type = { +static PyTypeObject PySSLSocket_Type = { PyVarObject_HEAD_INIT(NULL, 0) - "ssl.SSLContext", /*tp_name*/ - sizeof(PySSLObject), /*tp_basicsize*/ + "_ssl._SSLSocket", /*tp_name*/ + sizeof(PySSLSocket), /*tp_basicsize*/ 0, /*tp_itemsize*/ /* methods */ (destructor)PySSL_dealloc, /*tp_dealloc*/ @@ -1529,6 +1392,310 @@ PySSLMethods, /*tp_methods*/ }; + +/* + * _SSLContext objects + */ + +static PyObject * +context_new(PyTypeObject *type, PyObject *args, PyObject *kwds) +{ + char *kwlist[] = {"protocol", NULL}; + PySSLContext *self; + int proto_version = PY_SSL_VERSION_SSL23; + SSL_CTX *ctx = NULL; + + if (!PyArg_ParseTupleAndKeywords( + args, kwds, "i:_SSLContext", kwlist, + &proto_version)) + return NULL; + + PySSL_BEGIN_ALLOW_THREADS + if (proto_version == PY_SSL_VERSION_TLS1) + ctx = SSL_CTX_new(TLSv1_method()); + else if (proto_version == PY_SSL_VERSION_SSL3) + ctx = SSL_CTX_new(SSLv3_method()); + else if (proto_version == PY_SSL_VERSION_SSL2) + ctx = SSL_CTX_new(SSLv2_method()); + else if (proto_version == PY_SSL_VERSION_SSL23) + ctx = SSL_CTX_new(SSLv23_method()); + else + proto_version = -1; + PySSL_END_ALLOW_THREADS + + if (proto_version == -1) { + PyErr_SetString(PyExc_ValueError, + "invalid protocol version"); + return NULL; + } + if (ctx == NULL) { + PyErr_SetString(PySSLErrorObject, + "failed to allocate SSL context"); + return NULL; + } + + assert(type != NULL && type->tp_alloc != NULL); + self = (PySSLContext *) type->tp_alloc(type, 0); + if (self == NULL) { + SSL_CTX_free(ctx); + return NULL; + } + self->ctx = ctx; + /* Defaults */ + SSL_CTX_set_verify(self->ctx, SSL_VERIFY_NONE, NULL); + SSL_CTX_set_options(self->ctx, SSL_OP_ALL); + + return (PyObject *)self; +} + +static void +context_dealloc(PySSLContext *self) +{ + SSL_CTX_free(self->ctx); + Py_TYPE(self)->tp_free(self); +} + +static PyObject * +set_ciphers(PySSLContext *self, PyObject *args) +{ + int ret; + const char *cipherlist; + + if (!PyArg_ParseTuple(args, "s:set_ciphers", &cipherlist)) + return NULL; + ret = SSL_CTX_set_cipher_list(self->ctx, cipherlist); + if (ret == 0) { + /* Clearing the error queue is necessary on some OpenSSL versions, + otherwise the error will be reported again when another SSL call + is done. */ + ERR_clear_error(); + PyErr_SetString(PySSLErrorObject, + "No cipher can be selected."); + return NULL; + } + Py_RETURN_NONE; +} + +static PyObject * +get_verify_mode(PySSLContext *self, void *c) +{ + switch (SSL_CTX_get_verify_mode(self->ctx)) { + case SSL_VERIFY_NONE: + return PyLong_FromLong(PY_SSL_CERT_NONE); + case SSL_VERIFY_PEER: + return PyLong_FromLong(PY_SSL_CERT_OPTIONAL); + case SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT: + return PyLong_FromLong(PY_SSL_CERT_REQUIRED); + } + PyErr_SetString(PySSLErrorObject, + "invalid return value from SSL_CTX_get_verify_mode"); + return NULL; +} + +static int +set_verify_mode(PySSLContext *self, PyObject *arg, void *c) +{ + int n, mode; + if (!PyArg_Parse(arg, "i", &n)) + return -1; + if (n == PY_SSL_CERT_NONE) + mode = SSL_VERIFY_NONE; + else if (n == PY_SSL_CERT_OPTIONAL) + mode = SSL_VERIFY_PEER; + else if (n == PY_SSL_CERT_REQUIRED) + mode = SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT; + else { + PyErr_SetString(PyExc_ValueError, + "invalid value for verify_mode"); + return -1; + } + SSL_CTX_set_verify(self->ctx, mode, NULL); + return 0; +} + +static PyObject * +load_cert_chain(PySSLContext *self, PyObject *args, PyObject *kwds) +{ + char *kwlist[] = {"certfile", "keyfile", NULL}; + PyObject *certfile, *keyfile = NULL; + PyObject *certfile_bytes = NULL, *keyfile_bytes = NULL; + int r; + + if (!PyArg_ParseTupleAndKeywords(args, kwds, + "O|O:load_cert_chain", kwlist, + &certfile, &keyfile)) + return NULL; + if (keyfile == Py_None) + keyfile = NULL; + if (!PyUnicode_FSConverter(certfile, &certfile_bytes)) { + PyErr_SetString(PyExc_TypeError, + "certfile should be a valid filesystem path"); + return NULL; + } + if (keyfile && !PyUnicode_FSConverter(keyfile, &keyfile_bytes)) { + PyErr_SetString(PyExc_TypeError, + "keyfile should be a valid filesystem path"); + goto error; + } + PySSL_BEGIN_ALLOW_THREADS + r = SSL_CTX_use_certificate_chain_file(self->ctx, + PyBytes_AS_STRING(certfile_bytes)); + PySSL_END_ALLOW_THREADS + if (r != 1) { + _setSSLError(NULL, 0, __FILE__, __LINE__); + goto error; + } + PySSL_BEGIN_ALLOW_THREADS + r = SSL_CTX_use_RSAPrivateKey_file(self->ctx, + PyBytes_AS_STRING(keyfile ? keyfile_bytes : certfile_bytes), + SSL_FILETYPE_PEM); + PySSL_END_ALLOW_THREADS + Py_XDECREF(keyfile_bytes); + Py_XDECREF(certfile_bytes); + if (r != 1) { + _setSSLError(NULL, 0, __FILE__, __LINE__); + return NULL; + } + PySSL_BEGIN_ALLOW_THREADS + r = SSL_CTX_check_private_key(self->ctx); + PySSL_END_ALLOW_THREADS + if (r != 1) { + _setSSLError(NULL, 0, __FILE__, __LINE__); + return NULL; + } + Py_RETURN_NONE; + +error: + Py_XDECREF(keyfile_bytes); + Py_XDECREF(certfile_bytes); + return NULL; +} + +static PyObject * +load_verify_locations(PySSLContext *self, PyObject *args, PyObject *kwds) +{ + char *kwlist[] = {"cafile", "capath", NULL}; + PyObject *cafile = NULL, *capath = NULL; + PyObject *cafile_bytes = NULL, *capath_bytes = NULL; + const char *cafile_buf = NULL, *capath_buf = NULL; + int r; + + if (!PyArg_ParseTupleAndKeywords(args, kwds, + "|OO:load_verify_locations", kwlist, + &cafile, &capath)) + return NULL; + if (cafile == Py_None) + cafile = NULL; + if (capath == Py_None) + capath = NULL; + if (cafile == NULL && capath == NULL) { + PyErr_SetString(PyExc_TypeError, + "cafile and capath cannot be both omitted"); + return NULL; + } + if (cafile && !PyUnicode_FSConverter(cafile, &cafile_bytes)) { + PyErr_SetString(PyExc_TypeError, + "cafile should be a valid filesystem path"); + return NULL; + } + if (capath && !PyUnicode_FSConverter(capath, &capath_bytes)) { + Py_DECREF(cafile_bytes); + PyErr_SetString(PyExc_TypeError, + "capath should be a valid filesystem path"); + return NULL; + } + if (cafile) + cafile_buf = PyBytes_AS_STRING(cafile_bytes); + if (capath) + capath_buf = PyBytes_AS_STRING(capath_bytes); + PySSL_BEGIN_ALLOW_THREADS + r = SSL_CTX_load_verify_locations(self->ctx, cafile_buf, capath_buf); + PySSL_END_ALLOW_THREADS + Py_XDECREF(cafile_bytes); + Py_XDECREF(capath_bytes); + if (r != 1) { + _setSSLError(NULL, 0, __FILE__, __LINE__); + return NULL; + } + Py_RETURN_NONE; +} + +static PyObject * +context_wrap_socket(PySSLContext *self, PyObject *args, PyObject *kwds) +{ + char *kwlist[] = {"sock", "server_side", NULL}; + PySocketSockObject *sock; + int server_side = 0; + + if (!PyArg_ParseTupleAndKeywords(args, kwds, "O!i:_wrap_socket", kwlist, + PySocketModule.Sock_Type, + &sock, &server_side)) + return NULL; + + return (PyObject *) newPySSLSocket(self->ctx, sock, server_side); +} + +static PyGetSetDef context_getsetlist[] = { + {"verify_mode", (getter) get_verify_mode, + (setter) set_verify_mode, NULL}, + {NULL}, /* sentinel */ +}; + +static struct PyMethodDef context_methods[] = { + {"_wrap_socket", (PyCFunction) context_wrap_socket, + METH_VARARGS | METH_KEYWORDS, NULL}, + {"set_ciphers", (PyCFunction) set_ciphers, + METH_VARARGS, NULL}, + {"load_cert_chain", (PyCFunction) load_cert_chain, + METH_VARARGS | METH_KEYWORDS, NULL}, + {"load_verify_locations", (PyCFunction) load_verify_locations, + METH_VARARGS | METH_KEYWORDS, NULL}, + {NULL, NULL} /* sentinel */ +}; + +static PyTypeObject PySSLContext_Type = { + PyVarObject_HEAD_INIT(NULL, 0) + "_ssl._SSLContext", /*tp_name*/ + sizeof(PySSLContext), /*tp_basicsize*/ + 0, /*tp_itemsize*/ + (destructor)context_dealloc, /*tp_dealloc*/ + 0, /*tp_print*/ + 0, /*tp_getattr*/ + 0, /*tp_setattr*/ + 0, /*tp_reserved*/ + 0, /*tp_repr*/ + 0, /*tp_as_number*/ + 0, /*tp_as_sequence*/ + 0, /*tp_as_mapping*/ + 0, /*tp_hash*/ + 0, /*tp_call*/ + 0, /*tp_str*/ + 0, /*tp_getattro*/ + 0, /*tp_setattro*/ + 0, /*tp_as_buffer*/ + Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /*tp_flags*/ + 0, /*tp_doc*/ + 0, /*tp_traverse*/ + 0, /*tp_clear*/ + 0, /*tp_richcompare*/ + 0, /*tp_weaklistoffset*/ + 0, /*tp_iter*/ + 0, /*tp_iternext*/ + context_methods, /*tp_methods*/ + 0, /*tp_members*/ + context_getsetlist, /*tp_getset*/ + 0, /*tp_base*/ + 0, /*tp_dict*/ + 0, /*tp_descr_get*/ + 0, /*tp_descr_set*/ + 0, /*tp_dictoffset*/ + 0, /*tp_init*/ + 0, /*tp_alloc*/ + context_new, /*tp_new*/ +}; + + + #ifdef HAVE_OPENSSL_RAND /* helper routines for seeding the SSL PRNG */ @@ -1566,15 +1733,17 @@ using the ssl() function."); static PyObject * -PySSL_RAND_egd(PyObject *self, PyObject *arg) +PySSL_RAND_egd(PyObject *self, PyObject *args) { + PyObject *path; int bytes; - if (!PyUnicode_Check(arg)) - return PyErr_Format(PyExc_TypeError, - "RAND_egd() expected string, found %s", - Py_TYPE(arg)->tp_name); - bytes = RAND_egd(_PyUnicode_AsString(arg)); + if (!PyArg_ParseTuple(args, "O&|i:RAND_egd", + PyUnicode_FSConverter, &path)) + return NULL; + + bytes = RAND_egd(PyBytes_AsString(path)); + Py_DECREF(path); if (bytes == -1) { PyErr_SetString(PySSLErrorObject, "EGD connection failed or EGD did not return " @@ -1598,14 +1767,12 @@ /* List of functions exported by this module. */ static PyMethodDef PySSL_methods[] = { - {"sslwrap", PySSL_sslwrap, - METH_VARARGS, ssl_doc}, {"_test_decode_cert", PySSL_test_decode_certificate, METH_VARARGS}, #ifdef HAVE_OPENSSL_RAND {"RAND_add", PySSL_RAND_add, METH_VARARGS, PySSL_RAND_add_doc}, - {"RAND_egd", PySSL_RAND_egd, METH_O, + {"RAND_egd", PySSL_RAND_egd, METH_VARARGS, PySSL_RAND_egd_doc}, {"RAND_status", (PyCFunction)PySSL_RAND_status, METH_NOARGS, PySSL_RAND_status_doc}, @@ -1708,7 +1875,9 @@ unsigned int major, minor, fix, patch, status; PySocketModule_APIObject *socket_api; - if (PyType_Ready(&PySSL_Type) < 0) + if (PyType_Ready(&PySSLContext_Type) < 0) + return NULL; + if (PyType_Ready(&PySSLSocket_Type) < 0) return NULL; m = PyModule_Create(&_sslmodule); @@ -1741,8 +1910,11 @@ return NULL; if (PyDict_SetItemString(d, "SSLError", PySSLErrorObject) != 0) return NULL; - if (PyDict_SetItemString(d, "SSLType", - (PyObject *)&PySSL_Type) != 0) + if (PyDict_SetItemString(d, "_SSLContext", + (PyObject *)&PySSLContext_Type) != 0) + return NULL; + if (PyDict_SetItemString(d, "_SSLSocket", + (PyObject *)&PySSLSocket_Type) != 0) return NULL; PyModule_AddIntConstant(m, "SSL_ERROR_ZERO_RETURN", PY_SSL_ERROR_ZERO_RETURN); Modified: python/branches/py3k-jit/Modules/_testcapimodule.c ============================================================================== --- python/branches/py3k-jit/Modules/_testcapimodule.c (original) +++ python/branches/py3k-jit/Modules/_testcapimodule.c Tue May 18 19:58:30 2010 @@ -1551,7 +1551,11 @@ crash_no_current_thread(PyObject *self) { Py_BEGIN_ALLOW_THREADS - PyErr_SetString(PyExc_SystemError, "bork bork bork"); + /* Using PyThreadState_Get() directly allows the test to pass in + !pydebug mode. However, the test only actually tests anything + in pydebug mode, since that's where the infinite loop was in + the first place. */ + PyThreadState_Get(); Py_END_ALLOW_THREADS return NULL; } Modified: python/branches/py3k-jit/Modules/_tkinter.c ============================================================================== --- python/branches/py3k-jit/Modules/_tkinter.c (original) +++ python/branches/py3k-jit/Modules/_tkinter.c Tue May 18 19:58:30 2010 @@ -3147,9 +3147,7 @@ it also helps Tcl find its encodings. */ uexe = PyUnicode_FromWideChar(Py_GetProgramName(), -1); if (uexe) { - cexe = PyUnicode_AsEncodedString(uexe, - Py_FileSystemDefaultEncoding, - NULL); + cexe = PyUnicode_EncodeFSDefault(uexe); if (cexe) Tcl_FindExecutable(PyBytes_AsString(cexe)); Py_XDECREF(cexe); Modified: python/branches/py3k-jit/Modules/grpmodule.c ============================================================================== --- python/branches/py3k-jit/Modules/grpmodule.c (original) +++ python/branches/py3k-jit/Modules/grpmodule.c Tue May 18 19:58:30 2010 @@ -111,8 +111,7 @@ if (!PyArg_ParseTuple(args, "U:getgrnam", &arg)) return NULL; - if ((bytes = PyUnicode_AsEncodedString(arg, Py_FileSystemDefaultEncoding, - "surrogateescape")) == NULL) + if ((bytes = PyUnicode_EncodeFSDefault(arg)) == NULL) return NULL; if (PyBytes_AsStringAndSize(bytes, &name, NULL) == -1) goto out; Modified: python/branches/py3k-jit/Modules/main.c ============================================================================== --- python/branches/py3k-jit/Modules/main.c (original) +++ python/branches/py3k-jit/Modules/main.c Tue May 18 19:58:30 2010 @@ -563,18 +563,22 @@ } if (command) { + char *commandStr; PyObject *commandObj = PyUnicode_FromWideChar( command, wcslen(command)); free(command); - if (commandObj != NULL) { - sts = PyRun_SimpleStringFlags( - _PyUnicode_AsString(commandObj), &cf) != 0; + if (commandObj != NULL) + commandStr = _PyUnicode_AsString(commandObj); + else + commandStr = NULL; + if (commandStr != NULL) { + sts = PyRun_SimpleStringFlags(commandStr, &cf) != 0; + Py_DECREF(commandObj); } else { PyErr_Print(); sts = 1; } - Py_DECREF(commandObj); } else if (module) { sts = RunModule(module, 1); } Modified: python/branches/py3k-jit/Modules/mathmodule.c ============================================================================== --- python/branches/py3k-jit/Modules/mathmodule.c (original) +++ python/branches/py3k-jit/Modules/mathmodule.c Tue May 18 19:58:30 2010 @@ -1129,18 +1129,239 @@ Return an accurate floating point sum of values in the iterable.\n\ Assumes IEEE-754 floating point arithmetic."); +/* Return the smallest integer k such that n < 2**k, or 0 if n == 0. + * Equivalent to floor(lg(x))+1. Also equivalent to: bitwidth_of_type - + * count_leading_zero_bits(x) + */ + +/* XXX: This routine does more or less the same thing as + * bits_in_digit() in Objects/longobject.c. Someday it would be nice to + * consolidate them. On BSD, there's a library function called fls() + * that we could use, and GCC provides __builtin_clz(). + */ + +static unsigned long +bit_length(unsigned long n) +{ + unsigned long len = 0; + while (n != 0) { + ++len; + n >>= 1; + } + return len; +} + +static unsigned long +count_set_bits(unsigned long n) +{ + unsigned long count = 0; + while (n != 0) { + ++count; + n &= n - 1; /* clear least significant bit */ + } + return count; +} + +/* Divide-and-conquer factorial algorithm + * + * Based on the formula and psuedo-code provided at: + * http://www.luschny.de/math/factorial/binarysplitfact.html + * + * Faster algorithms exist, but they're more complicated and depend on + * a fast prime factoriazation algorithm. + * + * Notes on the algorithm + * ---------------------- + * + * factorial(n) is written in the form 2**k * m, with m odd. k and m are + * computed separately, and then combined using a left shift. + * + * The function factorial_odd_part computes the odd part m (i.e., the greatest + * odd divisor) of factorial(n), using the formula: + * + * factorial_odd_part(n) = + * + * product_{i >= 0} product_{0 < j <= n / 2**i, j odd} j + * + * Example: factorial_odd_part(20) = + * + * (1) * + * (1) * + * (1 * 3 * 5) * + * (1 * 3 * 5 * 7 * 9) + * (1 * 3 * 5 * 7 * 9 * 11 * 13 * 15 * 17 * 19) + * + * Here i goes from large to small: the first term corresponds to i=4 (any + * larger i gives an empty product), and the last term corresponds to i=0. + * Each term can be computed from the last by multiplying by the extra odd + * numbers required: e.g., to get from the penultimate term to the last one, + * we multiply by (11 * 13 * 15 * 17 * 19). + * + * To see a hint of why this formula works, here are the same numbers as above + * but with the even parts (i.e., the appropriate powers of 2) included. For + * each subterm in the product for i, we multiply that subterm by 2**i: + * + * factorial(20) = + * + * (16) * + * (8) * + * (4 * 12 * 20) * + * (2 * 6 * 10 * 14 * 18) * + * (1 * 3 * 5 * 7 * 9 * 11 * 13 * 15 * 17 * 19) + * + * The factorial_partial_product function computes the product of all odd j in + * range(start, stop) for given start and stop. It's used to compute the + * partial products like (11 * 13 * 15 * 17 * 19) in the example above. It + * operates recursively, repeatedly splitting the range into two roughly equal + * pieces until the subranges are small enough to be computed using only C + * integer arithmetic. + * + * The two-valuation k (i.e., the exponent of the largest power of 2 dividing + * the factorial) is computed independently in the main math_factorial + * function. By standard results, its value is: + * + * two_valuation = n//2 + n//4 + n//8 + .... + * + * It can be shown (e.g., by complete induction on n) that two_valuation is + * equal to n - count_set_bits(n), where count_set_bits(n) gives the number of + * '1'-bits in the binary expansion of n. + */ + +/* factorial_partial_product: Compute product(range(start, stop, 2)) using + * divide and conquer. Assumes start and stop are odd and stop > start. + * max_bits must be >= bit_length(stop - 2). */ + +static PyObject * +factorial_partial_product(unsigned long start, unsigned long stop, + unsigned long max_bits) +{ + unsigned long midpoint, num_operands; + PyObject *left = NULL, *right = NULL, *result = NULL; + + /* If the return value will fit an unsigned long, then we can + * multiply in a tight, fast loop where each multiply is O(1). + * Compute an upper bound on the number of bits required to store + * the answer. + * + * Storing some integer z requires floor(lg(z))+1 bits, which is + * conveniently the value returned by bit_length(z). The + * product x*y will require at most + * bit_length(x) + bit_length(y) bits to store, based + * on the idea that lg product = lg x + lg y. + * + * We know that stop - 2 is the largest number to be multiplied. From + * there, we have: bit_length(answer) <= num_operands * + * bit_length(stop - 2) + */ + + num_operands = (stop - start) / 2; + /* The "num_operands <= 8 * SIZEOF_LONG" check guards against the + * unlikely case of an overflow in num_operands * max_bits. */ + if (num_operands <= 8 * SIZEOF_LONG && + num_operands * max_bits <= 8 * SIZEOF_LONG) { + unsigned long j, total; + for (total = start, j = start + 2; j < stop; j += 2) + total *= j; + return PyLong_FromUnsignedLong(total); + } + + /* find midpoint of range(start, stop), rounded up to next odd number. */ + midpoint = (start + num_operands) | 1; + left = factorial_partial_product(start, midpoint, + bit_length(midpoint - 2)); + if (left == NULL) + goto error; + right = factorial_partial_product(midpoint, stop, max_bits); + if (right == NULL) + goto error; + result = PyNumber_Multiply(left, right); + + error: + Py_XDECREF(left); + Py_XDECREF(right); + return result; +} + +/* factorial_odd_part: compute the odd part of factorial(n). */ + +static PyObject * +factorial_odd_part(unsigned long n) +{ + long i; + unsigned long v, lower, upper; + PyObject *partial, *tmp, *inner, *outer; + + inner = PyLong_FromLong(1); + if (inner == NULL) + return NULL; + outer = inner; + Py_INCREF(outer); + + upper = 3; + for (i = bit_length(n) - 2; i >= 0; i--) { + v = n >> i; + if (v <= 2) + continue; + lower = upper; + /* (v + 1) | 1 = least odd integer strictly larger than n / 2**i */ + upper = (v + 1) | 1; + /* Here inner is the product of all odd integers j in the range (0, + n/2**(i+1)]. The factorial_partial_product call below gives the + product of all odd integers j in the range (n/2**(i+1), n/2**i]. */ + partial = factorial_partial_product(lower, upper, bit_length(upper-2)); + /* inner *= partial */ + if (partial == NULL) + goto error; + tmp = PyNumber_Multiply(inner, partial); + Py_DECREF(partial); + if (tmp == NULL) + goto error; + Py_DECREF(inner); + inner = tmp; + /* Now inner is the product of all odd integers j in the range (0, + n/2**i], giving the inner product in the formula above. */ + + /* outer *= inner; */ + tmp = PyNumber_Multiply(outer, inner); + if (tmp == NULL) + goto error; + Py_DECREF(outer); + outer = tmp; + } + + goto done; + + error: + Py_DECREF(outer); + done: + Py_DECREF(inner); + return outer; +} + +/* Lookup table for small factorial values */ + +static const unsigned long SmallFactorials[] = { + 1, 1, 2, 6, 24, 120, 720, 5040, 40320, + 362880, 3628800, 39916800, 479001600, +#if SIZEOF_LONG >= 8 + 6227020800, 87178291200, 1307674368000, + 20922789888000, 355687428096000, 6402373705728000, + 121645100408832000, 2432902008176640000 +#endif +}; + static PyObject * math_factorial(PyObject *self, PyObject *arg) { - long i, x; - PyObject *result, *iobj, *newresult; + long x; + PyObject *result, *odd_part, *two_valuation; if (PyFloat_Check(arg)) { PyObject *lx; double dx = PyFloat_AS_DOUBLE((PyFloatObject *)arg); if (!(Py_IS_FINITE(dx) && dx == floor(dx))) { PyErr_SetString(PyExc_ValueError, - "factorial() only accepts integral values"); + "factorial() only accepts integral values"); return NULL; } lx = PyLong_FromDouble(dx); @@ -1156,29 +1377,28 @@ return NULL; if (x < 0) { PyErr_SetString(PyExc_ValueError, - "factorial() not defined for negative values"); + "factorial() not defined for negative values"); return NULL; } - result = (PyObject *)PyLong_FromLong(1); - if (result == NULL) + /* use lookup table if x is small */ + if (x < (long)(sizeof(SmallFactorials)/sizeof(SmallFactorials[0]))) + return PyLong_FromUnsignedLong(SmallFactorials[x]); + + /* else express in the form odd_part * 2**two_valuation, and compute as + odd_part << two_valuation. */ + odd_part = factorial_odd_part(x); + if (odd_part == NULL) + return NULL; + two_valuation = PyLong_FromLong(x - count_set_bits(x)); + if (two_valuation == NULL) { + Py_DECREF(odd_part); return NULL; - for (i=1 ; i<=x ; i++) { - iobj = (PyObject *)PyLong_FromLong(i); - if (iobj == NULL) - goto error; - newresult = PyNumber_Multiply(result, iobj); - Py_DECREF(iobj); - if (newresult == NULL) - goto error; - Py_DECREF(result); - result = newresult; } + result = PyNumber_Lshift(odd_part, two_valuation); + Py_DECREF(two_valuation); + Py_DECREF(odd_part); return result; - -error: - Py_DECREF(result); - return NULL; } PyDoc_STRVAR(math_factorial_doc, Modified: python/branches/py3k-jit/Modules/posixmodule.c ============================================================================== --- python/branches/py3k-jit/Modules/posixmodule.c (original) +++ python/branches/py3k-jit/Modules/posixmodule.c Tue May 18 19:58:30 2010 @@ -2364,33 +2364,17 @@ (NAMLEN(ep) == 1 || (ep->d_name[1] == '.' && NAMLEN(ep) == 2))) continue; - v = PyBytes_FromStringAndSize(ep->d_name, NAMLEN(ep)); + if (arg_is_unicode) + v = PyUnicode_DecodeFSDefaultAndSize(ep->d_name, NAMLEN(ep)); + else + v = PyBytes_FromStringAndSize(ep->d_name, NAMLEN(ep)); if (v == NULL) { - Py_DECREF(d); - d = NULL; + Py_CLEAR(d); break; } - if (arg_is_unicode) { - PyObject *w; - - w = PyUnicode_FromEncodedObject(v, - Py_FileSystemDefaultEncoding, - "surrogateescape"); - Py_DECREF(v); - if (w != NULL) - v = w; - else { - /* Encoding failed to decode ASCII bytes. - Raise exception. */ - Py_DECREF(d); - d = NULL; - break; - } - } if (PyList_Append(d, v) != 0) { Py_DECREF(v); - Py_DECREF(d); - d = NULL; + Py_CLEAR(d); break; } Py_DECREF(v); @@ -4078,7 +4062,7 @@ static PyObject * win32_kill(PyObject *self, PyObject *args) { - PyObject *result, handle_obj; + PyObject *result; DWORD pid, sig, err; HANDLE handle; @@ -4605,22 +4589,10 @@ return posix_error_with_allocated_filename(opath); Py_DECREF(opath); - v = PyBytes_FromStringAndSize(buf, n); - if (arg_is_unicode) { - PyObject *w; - - w = PyUnicode_FromEncodedObject(v, - Py_FileSystemDefaultEncoding, - "surrogateescape"); - if (w != NULL) { - Py_DECREF(v); - v = w; - } - else { - v = NULL; - } - } - return v; + if (arg_is_unicode) + return PyUnicode_DecodeFSDefaultAndSize(buf, n); + else + return PyBytes_FromStringAndSize(buf, n); } #endif /* HAVE_READLINK */ Modified: python/branches/py3k-jit/Modules/pwdmodule.c ============================================================================== --- python/branches/py3k-jit/Modules/pwdmodule.c (original) +++ python/branches/py3k-jit/Modules/pwdmodule.c Tue May 18 19:58:30 2010 @@ -132,9 +132,7 @@ if (!PyArg_ParseTuple(args, "U:getpwnam", &arg)) return NULL; - if ((bytes = PyUnicode_AsEncodedString(arg, - Py_FileSystemDefaultEncoding, - "surrogateescape")) == NULL) + if ((bytes = PyUnicode_EncodeFSDefault(arg)) == NULL) return NULL; if (PyBytes_AsStringAndSize(bytes, &name, NULL) == -1) goto out; Modified: python/branches/py3k-jit/Modules/spwdmodule.c ============================================================================== --- python/branches/py3k-jit/Modules/spwdmodule.c (original) +++ python/branches/py3k-jit/Modules/spwdmodule.c Tue May 18 19:58:30 2010 @@ -118,9 +118,7 @@ if (!PyArg_ParseTuple(args, "U:getspnam", &arg)) return NULL; - if ((bytes = PyUnicode_AsEncodedString(arg, - Py_FileSystemDefaultEncoding, - "surrogateescape")) == NULL) + if ((bytes = PyUnicode_EncodeFSDefault(arg)) == NULL) return NULL; if (PyBytes_AsStringAndSize(bytes, &name, NULL) == -1) goto out; Modified: python/branches/py3k-jit/Objects/object.c ============================================================================== --- python/branches/py3k-jit/Objects/object.c (original) +++ python/branches/py3k-jit/Objects/object.c Tue May 18 19:58:30 2010 @@ -303,12 +303,15 @@ } else if (PyUnicode_Check(s)) { PyObject *t; - t = _PyUnicode_AsDefaultEncodedString(s, NULL); + t = PyUnicode_EncodeUTF8(PyUnicode_AS_UNICODE(s), + PyUnicode_GET_SIZE(s), + "backslashreplace"); if (t == NULL) ret = 0; else { fwrite(PyBytes_AS_STRING(t), 1, PyBytes_GET_SIZE(t), fp); + Py_DECREF(t); } } else { Modified: python/branches/py3k-jit/Objects/unicodeobject.c ============================================================================== --- python/branches/py3k-jit/Objects/unicodeobject.c (original) +++ python/branches/py3k-jit/Objects/unicodeobject.c Tue May 18 19:58:30 2010 @@ -1461,6 +1461,18 @@ return NULL; } +PyObject *PyUnicode_EncodeFSDefault(PyObject *unicode) +{ + if (Py_FileSystemDefaultEncoding) + return PyUnicode_AsEncodedString(unicode, + Py_FileSystemDefaultEncoding, + "surrogateescape"); + else + return PyUnicode_EncodeUTF8(PyUnicode_AS_UNICODE(unicode), + PyUnicode_GET_SIZE(unicode), + "surrogateescape"); +} + PyObject *PyUnicode_AsEncodedString(PyObject *unicode, const char *encoding, const char *errors) @@ -1476,31 +1488,39 @@ encoding = PyUnicode_GetDefaultEncoding(); /* Shortcuts for common default encodings */ - if (errors == NULL) { - if (strcmp(encoding, "utf-8") == 0) - return PyUnicode_AsUTF8String(unicode); - else if (strcmp(encoding, "latin-1") == 0) - return PyUnicode_AsLatin1String(unicode); + if (strcmp(encoding, "utf-8") == 0) + return PyUnicode_EncodeUTF8(PyUnicode_AS_UNICODE(unicode), + PyUnicode_GET_SIZE(unicode), + errors); + else if (strcmp(encoding, "latin-1") == 0) + return PyUnicode_EncodeLatin1(PyUnicode_AS_UNICODE(unicode), + PyUnicode_GET_SIZE(unicode), + errors); #if defined(MS_WINDOWS) && defined(HAVE_USABLE_WCHAR_T) - else if (strcmp(encoding, "mbcs") == 0) - return PyUnicode_AsMBCSString(unicode); -#endif - else if (strcmp(encoding, "ascii") == 0) - return PyUnicode_AsASCIIString(unicode); - /* During bootstrap, we may need to find the encodings - package, to load the file system encoding, and require the - file system encoding in order to load the encodings - package. - - Break out of this dependency by assuming that the path to - the encodings module is ASCII-only. XXX could try wcstombs - instead, if the file system encoding is the locale's - encoding. */ - else if (Py_FileSystemDefaultEncoding && - strcmp(encoding, Py_FileSystemDefaultEncoding) == 0 && - !PyThreadState_GET()->interp->codecs_initialized) - return PyUnicode_AsASCIIString(unicode); - } + else if (strcmp(encoding, "mbcs") == 0) + return PyUnicode_EncodeMBCS(PyUnicode_AS_UNICODE(unicode), + PyUnicode_GET_SIZE(unicode), + errors); +#endif + else if (strcmp(encoding, "ascii") == 0) + return PyUnicode_EncodeASCII(PyUnicode_AS_UNICODE(unicode), + PyUnicode_GET_SIZE(unicode), + errors); + /* During bootstrap, we may need to find the encodings + package, to load the file system encoding, and require the + file system encoding in order to load the encodings + package. + + Break out of this dependency by assuming that the path to + the encodings module is ASCII-only. XXX could try wcstombs + instead, if the file system encoding is the locale's + encoding. */ + else if (Py_FileSystemDefaultEncoding && + strcmp(encoding, Py_FileSystemDefaultEncoding) == 0 && + !PyThreadState_GET()->interp->codecs_initialized) + return PyUnicode_EncodeASCII(PyUnicode_AS_UNICODE(unicode), + PyUnicode_GET_SIZE(unicode), + errors); /* Encode via the codec registry */ v = PyCodec_Encode(unicode, encoding, errors); @@ -1638,9 +1658,7 @@ arg = PyUnicode_FromObject(arg); if (!arg) return 0; - output = PyUnicode_AsEncodedObject(arg, - Py_FileSystemDefaultEncoding, - "surrogateescape"); + output = PyUnicode_EncodeFSDefault(arg); Py_DECREF(arg); if (!output) return 0; Modified: python/branches/py3k-jit/Parser/printgrammar.c ============================================================================== --- python/branches/py3k-jit/Parser/printgrammar.c (original) +++ python/branches/py3k-jit/Parser/printgrammar.c Tue May 18 19:58:30 2010 @@ -20,10 +20,10 @@ printdfas(g, fp); printlabels(g, fp); fprintf(fp, "grammar _PyParser_Grammar = {\n"); - fprintf(fp, "\t%d,\n", g->g_ndfas); - fprintf(fp, "\tdfas,\n"); - fprintf(fp, "\t{%d, labels},\n", g->g_ll.ll_nlabels); - fprintf(fp, "\t%d\n", g->g_start); + fprintf(fp, " %d,\n", g->g_ndfas); + fprintf(fp, " dfas,\n"); + fprintf(fp, " {%d, labels},\n", g->g_ll.ll_nlabels); + fprintf(fp, " %d\n", g->g_start); fprintf(fp, "};\n"); } @@ -53,7 +53,7 @@ i, j, s->s_narcs); a = s->s_arc; for (k = 0; k < s->s_narcs; k++, a++) - fprintf(fp, "\t{%d, %d},\n", a->a_lbl, a->a_arrow); + fprintf(fp, " {%d, %d},\n", a->a_lbl, a->a_arrow); fprintf(fp, "};\n"); } } @@ -72,7 +72,7 @@ i, d->d_nstates); s = d->d_state; for (j = 0; j < d->d_nstates; j++, s++) - fprintf(fp, "\t{%d, arcs_%d_%d},\n", + fprintf(fp, " {%d, arcs_%d_%d},\n", s->s_narcs, i, j); fprintf(fp, "};\n"); } @@ -88,9 +88,9 @@ fprintf(fp, "static dfa dfas[%d] = {\n", g->g_ndfas); d = g->g_dfa; for (i = 0; i < g->g_ndfas; i++, d++) { - fprintf(fp, "\t{%d, \"%s\", %d, %d, states_%d,\n", + fprintf(fp, " {%d, \"%s\", %d, %d, states_%d,\n", d->d_type, d->d_name, d->d_initial, d->d_nstates, i); - fprintf(fp, "\t \""); + fprintf(fp, " \""); for (j = 0; j < NBYTES(g->g_ll.ll_nlabels); j++) fprintf(fp, "\\%03o", d->d_first[j] & 0xff); fprintf(fp, "\"},\n"); @@ -108,9 +108,9 @@ l = g->g_ll.ll_label; for (i = g->g_ll.ll_nlabels; --i >= 0; l++) { if (l->lb_str == NULL) - fprintf(fp, "\t{%d, 0},\n", l->lb_type); + fprintf(fp, " {%d, 0},\n", l->lb_type); else - fprintf(fp, "\t{%d, \"%s\"},\n", + fprintf(fp, " {%d, \"%s\"},\n", l->lb_type, l->lb_str); } fprintf(fp, "};\n"); Modified: python/branches/py3k-jit/Python/bltinmodule.c ============================================================================== --- python/branches/py3k-jit/Python/bltinmodule.c (original) +++ python/branches/py3k-jit/Python/bltinmodule.c Tue May 18 19:58:30 2010 @@ -9,6 +9,10 @@ #include +#ifdef HAVE_LANGINFO_H +#include /* CODESET */ +#endif + /* The default encoding used by the platform file system APIs Can remain NULL for all platforms that don't have such a concept @@ -21,9 +25,12 @@ #elif defined(__APPLE__) const char *Py_FileSystemDefaultEncoding = "utf-8"; int Py_HasFileSystemDefaultEncoding = 1; -#else -const char *Py_FileSystemDefaultEncoding = NULL; /* use default */ +#elif defined(HAVE_LANGINFO_H) && defined(CODESET) +const char *Py_FileSystemDefaultEncoding = NULL; /* set by initfsencoding() */ int Py_HasFileSystemDefaultEncoding = 0; +#else +const char *Py_FileSystemDefaultEncoding = "utf-8"; +int Py_HasFileSystemDefaultEncoding = 1; #endif int Modified: python/branches/py3k-jit/Python/graminit.c ============================================================================== --- python/branches/py3k-jit/Python/graminit.c (original) +++ python/branches/py3k-jit/Python/graminit.c Tue May 18 19:58:30 2010 @@ -4,2077 +4,2077 @@ #include "grammar.h" PyAPI_DATA(grammar) _PyParser_Grammar; static arc arcs_0_0[3] = { - {2, 1}, - {3, 1}, - {4, 2}, + {2, 1}, + {3, 1}, + {4, 2}, }; static arc arcs_0_1[1] = { - {0, 1}, + {0, 1}, }; static arc arcs_0_2[1] = { - {2, 1}, + {2, 1}, }; static state states_0[3] = { - {3, arcs_0_0}, - {1, arcs_0_1}, - {1, arcs_0_2}, + {3, arcs_0_0}, + {1, arcs_0_1}, + {1, arcs_0_2}, }; static arc arcs_1_0[3] = { - {2, 0}, - {6, 0}, - {7, 1}, + {2, 0}, + {6, 0}, + {7, 1}, }; static arc arcs_1_1[1] = { - {0, 1}, + {0, 1}, }; static state states_1[2] = { - {3, arcs_1_0}, - {1, arcs_1_1}, + {3, arcs_1_0}, + {1, arcs_1_1}, }; static arc arcs_2_0[1] = { - {9, 1}, + {9, 1}, }; static arc arcs_2_1[2] = { - {2, 1}, - {7, 2}, + {2, 1}, + {7, 2}, }; static arc arcs_2_2[1] = { - {0, 2}, + {0, 2}, }; static state states_2[3] = { - {1, arcs_2_0}, - {2, arcs_2_1}, - {1, arcs_2_2}, + {1, arcs_2_0}, + {2, arcs_2_1}, + {1, arcs_2_2}, }; static arc arcs_3_0[1] = { - {11, 1}, + {11, 1}, }; static arc arcs_3_1[1] = { - {12, 2}, + {12, 2}, }; static arc arcs_3_2[2] = { - {13, 3}, - {2, 4}, + {13, 3}, + {2, 4}, }; static arc arcs_3_3[2] = { - {14, 5}, - {15, 6}, + {14, 5}, + {15, 6}, }; static arc arcs_3_4[1] = { - {0, 4}, + {0, 4}, }; static arc arcs_3_5[1] = { - {15, 6}, + {15, 6}, }; static arc arcs_3_6[1] = { - {2, 4}, + {2, 4}, }; static state states_3[7] = { - {1, arcs_3_0}, - {1, arcs_3_1}, - {2, arcs_3_2}, - {2, arcs_3_3}, - {1, arcs_3_4}, - {1, arcs_3_5}, - {1, arcs_3_6}, + {1, arcs_3_0}, + {1, arcs_3_1}, + {2, arcs_3_2}, + {2, arcs_3_3}, + {1, arcs_3_4}, + {1, arcs_3_5}, + {1, arcs_3_6}, }; static arc arcs_4_0[1] = { - {10, 1}, + {10, 1}, }; static arc arcs_4_1[2] = { - {10, 1}, - {0, 1}, + {10, 1}, + {0, 1}, }; static state states_4[2] = { - {1, arcs_4_0}, - {2, arcs_4_1}, + {1, arcs_4_0}, + {2, arcs_4_1}, }; static arc arcs_5_0[1] = { - {16, 1}, + {16, 1}, }; static arc arcs_5_1[2] = { - {18, 2}, - {19, 2}, + {18, 2}, + {19, 2}, }; static arc arcs_5_2[1] = { - {0, 2}, + {0, 2}, }; static state states_5[3] = { - {1, arcs_5_0}, - {2, arcs_5_1}, - {1, arcs_5_2}, + {1, arcs_5_0}, + {2, arcs_5_1}, + {1, arcs_5_2}, }; static arc arcs_6_0[1] = { - {20, 1}, + {20, 1}, }; static arc arcs_6_1[1] = { - {21, 2}, + {21, 2}, }; static arc arcs_6_2[1] = { - {22, 3}, + {22, 3}, }; static arc arcs_6_3[2] = { - {23, 4}, - {25, 5}, + {23, 4}, + {25, 5}, }; static arc arcs_6_4[1] = { - {24, 6}, + {24, 6}, }; static arc arcs_6_5[1] = { - {26, 7}, + {26, 7}, }; static arc arcs_6_6[1] = { - {25, 5}, + {25, 5}, }; static arc arcs_6_7[1] = { - {0, 7}, + {0, 7}, }; static state states_6[8] = { - {1, arcs_6_0}, - {1, arcs_6_1}, - {1, arcs_6_2}, - {2, arcs_6_3}, - {1, arcs_6_4}, - {1, arcs_6_5}, - {1, arcs_6_6}, - {1, arcs_6_7}, + {1, arcs_6_0}, + {1, arcs_6_1}, + {1, arcs_6_2}, + {2, arcs_6_3}, + {1, arcs_6_4}, + {1, arcs_6_5}, + {1, arcs_6_6}, + {1, arcs_6_7}, }; static arc arcs_7_0[1] = { - {13, 1}, + {13, 1}, }; static arc arcs_7_1[2] = { - {27, 2}, - {15, 3}, + {27, 2}, + {15, 3}, }; static arc arcs_7_2[1] = { - {15, 3}, + {15, 3}, }; static arc arcs_7_3[1] = { - {0, 3}, + {0, 3}, }; static state states_7[4] = { - {1, arcs_7_0}, - {2, arcs_7_1}, - {1, arcs_7_2}, - {1, arcs_7_3}, + {1, arcs_7_0}, + {2, arcs_7_1}, + {1, arcs_7_2}, + {1, arcs_7_3}, }; static arc arcs_8_0[3] = { - {28, 1}, - {31, 2}, - {32, 3}, + {28, 1}, + {31, 2}, + {32, 3}, }; static arc arcs_8_1[3] = { - {29, 4}, - {30, 5}, - {0, 1}, + {29, 4}, + {30, 5}, + {0, 1}, }; static arc arcs_8_2[3] = { - {28, 6}, - {30, 7}, - {0, 2}, + {28, 6}, + {30, 7}, + {0, 2}, }; static arc arcs_8_3[1] = { - {28, 8}, + {28, 8}, }; static arc arcs_8_4[1] = { - {24, 9}, + {24, 9}, }; static arc arcs_8_5[4] = { - {28, 1}, - {31, 2}, - {32, 3}, - {0, 5}, + {28, 1}, + {31, 2}, + {32, 3}, + {0, 5}, }; static arc arcs_8_6[2] = { - {30, 7}, - {0, 6}, + {30, 7}, + {0, 6}, }; static arc arcs_8_7[2] = { - {28, 10}, - {32, 3}, + {28, 10}, + {32, 3}, }; static arc arcs_8_8[1] = { - {0, 8}, + {0, 8}, }; static arc arcs_8_9[2] = { - {30, 5}, - {0, 9}, + {30, 5}, + {0, 9}, }; static arc arcs_8_10[3] = { - {30, 7}, - {29, 11}, - {0, 10}, + {30, 7}, + {29, 11}, + {0, 10}, }; static arc arcs_8_11[1] = { - {24, 6}, + {24, 6}, }; static state states_8[12] = { - {3, arcs_8_0}, - {3, arcs_8_1}, - {3, arcs_8_2}, - {1, arcs_8_3}, - {1, arcs_8_4}, - {4, arcs_8_5}, - {2, arcs_8_6}, - {2, arcs_8_7}, - {1, arcs_8_8}, - {2, arcs_8_9}, - {3, arcs_8_10}, - {1, arcs_8_11}, + {3, arcs_8_0}, + {3, arcs_8_1}, + {3, arcs_8_2}, + {1, arcs_8_3}, + {1, arcs_8_4}, + {4, arcs_8_5}, + {2, arcs_8_6}, + {2, arcs_8_7}, + {1, arcs_8_8}, + {2, arcs_8_9}, + {3, arcs_8_10}, + {1, arcs_8_11}, }; static arc arcs_9_0[1] = { - {21, 1}, + {21, 1}, }; static arc arcs_9_1[2] = { - {25, 2}, - {0, 1}, + {25, 2}, + {0, 1}, }; static arc arcs_9_2[1] = { - {24, 3}, + {24, 3}, }; static arc arcs_9_3[1] = { - {0, 3}, + {0, 3}, }; static state states_9[4] = { - {1, arcs_9_0}, - {2, arcs_9_1}, - {1, arcs_9_2}, - {1, arcs_9_3}, + {1, arcs_9_0}, + {2, arcs_9_1}, + {1, arcs_9_2}, + {1, arcs_9_3}, }; static arc arcs_10_0[3] = { - {34, 1}, - {31, 2}, - {32, 3}, + {34, 1}, + {31, 2}, + {32, 3}, }; static arc arcs_10_1[3] = { - {29, 4}, - {30, 5}, - {0, 1}, + {29, 4}, + {30, 5}, + {0, 1}, }; static arc arcs_10_2[3] = { - {34, 6}, - {30, 7}, - {0, 2}, + {34, 6}, + {30, 7}, + {0, 2}, }; static arc arcs_10_3[1] = { - {34, 8}, + {34, 8}, }; static arc arcs_10_4[1] = { - {24, 9}, + {24, 9}, }; static arc arcs_10_5[4] = { - {34, 1}, - {31, 2}, - {32, 3}, - {0, 5}, + {34, 1}, + {31, 2}, + {32, 3}, + {0, 5}, }; static arc arcs_10_6[2] = { - {30, 7}, - {0, 6}, + {30, 7}, + {0, 6}, }; static arc arcs_10_7[2] = { - {34, 10}, - {32, 3}, + {34, 10}, + {32, 3}, }; static arc arcs_10_8[1] = { - {0, 8}, + {0, 8}, }; static arc arcs_10_9[2] = { - {30, 5}, - {0, 9}, + {30, 5}, + {0, 9}, }; static arc arcs_10_10[3] = { - {30, 7}, - {29, 11}, - {0, 10}, + {30, 7}, + {29, 11}, + {0, 10}, }; static arc arcs_10_11[1] = { - {24, 6}, + {24, 6}, }; static state states_10[12] = { - {3, arcs_10_0}, - {3, arcs_10_1}, - {3, arcs_10_2}, - {1, arcs_10_3}, - {1, arcs_10_4}, - {4, arcs_10_5}, - {2, arcs_10_6}, - {2, arcs_10_7}, - {1, arcs_10_8}, - {2, arcs_10_9}, - {3, arcs_10_10}, - {1, arcs_10_11}, + {3, arcs_10_0}, + {3, arcs_10_1}, + {3, arcs_10_2}, + {1, arcs_10_3}, + {1, arcs_10_4}, + {4, arcs_10_5}, + {2, arcs_10_6}, + {2, arcs_10_7}, + {1, arcs_10_8}, + {2, arcs_10_9}, + {3, arcs_10_10}, + {1, arcs_10_11}, }; static arc arcs_11_0[1] = { - {21, 1}, + {21, 1}, }; static arc arcs_11_1[1] = { - {0, 1}, + {0, 1}, }; static state states_11[2] = { - {1, arcs_11_0}, - {1, arcs_11_1}, + {1, arcs_11_0}, + {1, arcs_11_1}, }; static arc arcs_12_0[2] = { - {3, 1}, - {4, 1}, + {3, 1}, + {4, 1}, }; static arc arcs_12_1[1] = { - {0, 1}, + {0, 1}, }; static state states_12[2] = { - {2, arcs_12_0}, - {1, arcs_12_1}, + {2, arcs_12_0}, + {1, arcs_12_1}, }; static arc arcs_13_0[1] = { - {35, 1}, + {35, 1}, }; static arc arcs_13_1[2] = { - {36, 2}, - {2, 3}, + {36, 2}, + {2, 3}, }; static arc arcs_13_2[2] = { - {35, 1}, - {2, 3}, + {35, 1}, + {2, 3}, }; static arc arcs_13_3[1] = { - {0, 3}, + {0, 3}, }; static state states_13[4] = { - {1, arcs_13_0}, - {2, arcs_13_1}, - {2, arcs_13_2}, - {1, arcs_13_3}, + {1, arcs_13_0}, + {2, arcs_13_1}, + {2, arcs_13_2}, + {1, arcs_13_3}, }; static arc arcs_14_0[8] = { - {37, 1}, - {38, 1}, - {39, 1}, - {40, 1}, - {41, 1}, - {42, 1}, - {43, 1}, - {44, 1}, + {37, 1}, + {38, 1}, + {39, 1}, + {40, 1}, + {41, 1}, + {42, 1}, + {43, 1}, + {44, 1}, }; static arc arcs_14_1[1] = { - {0, 1}, + {0, 1}, }; static state states_14[2] = { - {8, arcs_14_0}, - {1, arcs_14_1}, + {8, arcs_14_0}, + {1, arcs_14_1}, }; static arc arcs_15_0[1] = { - {45, 1}, + {45, 1}, }; static arc arcs_15_1[3] = { - {46, 2}, - {29, 3}, - {0, 1}, + {46, 2}, + {29, 3}, + {0, 1}, }; static arc arcs_15_2[2] = { - {47, 4}, - {9, 4}, + {47, 4}, + {9, 4}, }; static arc arcs_15_3[2] = { - {47, 5}, - {45, 5}, + {47, 5}, + {45, 5}, }; static arc arcs_15_4[1] = { - {0, 4}, + {0, 4}, }; static arc arcs_15_5[2] = { - {29, 3}, - {0, 5}, + {29, 3}, + {0, 5}, }; static state states_15[6] = { - {1, arcs_15_0}, - {3, arcs_15_1}, - {2, arcs_15_2}, - {2, arcs_15_3}, - {1, arcs_15_4}, - {2, arcs_15_5}, + {1, arcs_15_0}, + {3, arcs_15_1}, + {2, arcs_15_2}, + {2, arcs_15_3}, + {1, arcs_15_4}, + {2, arcs_15_5}, }; static arc arcs_16_0[2] = { - {24, 1}, - {48, 1}, + {24, 1}, + {48, 1}, }; static arc arcs_16_1[2] = { - {30, 2}, - {0, 1}, + {30, 2}, + {0, 1}, }; static arc arcs_16_2[3] = { - {24, 1}, - {48, 1}, - {0, 2}, + {24, 1}, + {48, 1}, + {0, 2}, }; static state states_16[3] = { - {2, arcs_16_0}, - {2, arcs_16_1}, - {3, arcs_16_2}, + {2, arcs_16_0}, + {2, arcs_16_1}, + {3, arcs_16_2}, }; static arc arcs_17_0[12] = { - {49, 1}, - {50, 1}, - {51, 1}, - {52, 1}, - {53, 1}, - {54, 1}, - {55, 1}, - {56, 1}, - {57, 1}, - {58, 1}, - {59, 1}, - {60, 1}, + {49, 1}, + {50, 1}, + {51, 1}, + {52, 1}, + {53, 1}, + {54, 1}, + {55, 1}, + {56, 1}, + {57, 1}, + {58, 1}, + {59, 1}, + {60, 1}, }; static arc arcs_17_1[1] = { - {0, 1}, + {0, 1}, }; static state states_17[2] = { - {12, arcs_17_0}, - {1, arcs_17_1}, + {12, arcs_17_0}, + {1, arcs_17_1}, }; static arc arcs_18_0[1] = { - {61, 1}, + {61, 1}, }; static arc arcs_18_1[1] = { - {62, 2}, + {62, 2}, }; static arc arcs_18_2[1] = { - {0, 2}, + {0, 2}, }; static state states_18[3] = { - {1, arcs_18_0}, - {1, arcs_18_1}, - {1, arcs_18_2}, + {1, arcs_18_0}, + {1, arcs_18_1}, + {1, arcs_18_2}, }; static arc arcs_19_0[1] = { - {63, 1}, + {63, 1}, }; static arc arcs_19_1[1] = { - {0, 1}, + {0, 1}, }; static state states_19[2] = { - {1, arcs_19_0}, - {1, arcs_19_1}, + {1, arcs_19_0}, + {1, arcs_19_1}, }; static arc arcs_20_0[5] = { - {64, 1}, - {65, 1}, - {66, 1}, - {67, 1}, - {68, 1}, + {64, 1}, + {65, 1}, + {66, 1}, + {67, 1}, + {68, 1}, }; static arc arcs_20_1[1] = { - {0, 1}, + {0, 1}, }; static state states_20[2] = { - {5, arcs_20_0}, - {1, arcs_20_1}, + {5, arcs_20_0}, + {1, arcs_20_1}, }; static arc arcs_21_0[1] = { - {69, 1}, + {69, 1}, }; static arc arcs_21_1[1] = { - {0, 1}, + {0, 1}, }; static state states_21[2] = { - {1, arcs_21_0}, - {1, arcs_21_1}, + {1, arcs_21_0}, + {1, arcs_21_1}, }; static arc arcs_22_0[1] = { - {70, 1}, + {70, 1}, }; static arc arcs_22_1[1] = { - {0, 1}, + {0, 1}, }; static state states_22[2] = { - {1, arcs_22_0}, - {1, arcs_22_1}, + {1, arcs_22_0}, + {1, arcs_22_1}, }; static arc arcs_23_0[1] = { - {71, 1}, + {71, 1}, }; static arc arcs_23_1[2] = { - {9, 2}, - {0, 1}, + {9, 2}, + {0, 1}, }; static arc arcs_23_2[1] = { - {0, 2}, + {0, 2}, }; static state states_23[3] = { - {1, arcs_23_0}, - {2, arcs_23_1}, - {1, arcs_23_2}, + {1, arcs_23_0}, + {2, arcs_23_1}, + {1, arcs_23_2}, }; static arc arcs_24_0[1] = { - {47, 1}, + {47, 1}, }; static arc arcs_24_1[1] = { - {0, 1}, + {0, 1}, }; static state states_24[2] = { - {1, arcs_24_0}, - {1, arcs_24_1}, + {1, arcs_24_0}, + {1, arcs_24_1}, }; static arc arcs_25_0[1] = { - {72, 1}, + {72, 1}, }; static arc arcs_25_1[2] = { - {24, 2}, - {0, 1}, + {24, 2}, + {0, 1}, }; static arc arcs_25_2[2] = { - {73, 3}, - {0, 2}, + {73, 3}, + {0, 2}, }; static arc arcs_25_3[1] = { - {24, 4}, + {24, 4}, }; static arc arcs_25_4[1] = { - {0, 4}, + {0, 4}, }; static state states_25[5] = { - {1, arcs_25_0}, - {2, arcs_25_1}, - {2, arcs_25_2}, - {1, arcs_25_3}, - {1, arcs_25_4}, + {1, arcs_25_0}, + {2, arcs_25_1}, + {2, arcs_25_2}, + {1, arcs_25_3}, + {1, arcs_25_4}, }; static arc arcs_26_0[2] = { - {74, 1}, - {75, 1}, + {74, 1}, + {75, 1}, }; static arc arcs_26_1[1] = { - {0, 1}, + {0, 1}, }; static state states_26[2] = { - {2, arcs_26_0}, - {1, arcs_26_1}, + {2, arcs_26_0}, + {1, arcs_26_1}, }; static arc arcs_27_0[1] = { - {76, 1}, + {76, 1}, }; static arc arcs_27_1[1] = { - {77, 2}, + {77, 2}, }; static arc arcs_27_2[1] = { - {0, 2}, + {0, 2}, }; static state states_27[3] = { - {1, arcs_27_0}, - {1, arcs_27_1}, - {1, arcs_27_2}, + {1, arcs_27_0}, + {1, arcs_27_1}, + {1, arcs_27_2}, }; static arc arcs_28_0[1] = { - {73, 1}, + {73, 1}, }; static arc arcs_28_1[3] = { - {78, 2}, - {79, 2}, - {12, 3}, + {78, 2}, + {79, 2}, + {12, 3}, }; static arc arcs_28_2[4] = { - {78, 2}, - {79, 2}, - {12, 3}, - {76, 4}, + {78, 2}, + {79, 2}, + {12, 3}, + {76, 4}, }; static arc arcs_28_3[1] = { - {76, 4}, + {76, 4}, }; static arc arcs_28_4[3] = { - {31, 5}, - {13, 6}, - {80, 5}, + {31, 5}, + {13, 6}, + {80, 5}, }; static arc arcs_28_5[1] = { - {0, 5}, + {0, 5}, }; static arc arcs_28_6[1] = { - {80, 7}, + {80, 7}, }; static arc arcs_28_7[1] = { - {15, 5}, + {15, 5}, }; static state states_28[8] = { - {1, arcs_28_0}, - {3, arcs_28_1}, - {4, arcs_28_2}, - {1, arcs_28_3}, - {3, arcs_28_4}, - {1, arcs_28_5}, - {1, arcs_28_6}, - {1, arcs_28_7}, + {1, arcs_28_0}, + {3, arcs_28_1}, + {4, arcs_28_2}, + {1, arcs_28_3}, + {3, arcs_28_4}, + {1, arcs_28_5}, + {1, arcs_28_6}, + {1, arcs_28_7}, }; static arc arcs_29_0[1] = { - {21, 1}, + {21, 1}, }; static arc arcs_29_1[2] = { - {82, 2}, - {0, 1}, + {82, 2}, + {0, 1}, }; static arc arcs_29_2[1] = { - {21, 3}, + {21, 3}, }; static arc arcs_29_3[1] = { - {0, 3}, + {0, 3}, }; static state states_29[4] = { - {1, arcs_29_0}, - {2, arcs_29_1}, - {1, arcs_29_2}, - {1, arcs_29_3}, + {1, arcs_29_0}, + {2, arcs_29_1}, + {1, arcs_29_2}, + {1, arcs_29_3}, }; static arc arcs_30_0[1] = { - {12, 1}, + {12, 1}, }; static arc arcs_30_1[2] = { - {82, 2}, - {0, 1}, + {82, 2}, + {0, 1}, }; static arc arcs_30_2[1] = { - {21, 3}, + {21, 3}, }; static arc arcs_30_3[1] = { - {0, 3}, + {0, 3}, }; static state states_30[4] = { - {1, arcs_30_0}, - {2, arcs_30_1}, - {1, arcs_30_2}, - {1, arcs_30_3}, + {1, arcs_30_0}, + {2, arcs_30_1}, + {1, arcs_30_2}, + {1, arcs_30_3}, }; static arc arcs_31_0[1] = { - {81, 1}, + {81, 1}, }; static arc arcs_31_1[2] = { - {30, 2}, - {0, 1}, + {30, 2}, + {0, 1}, }; static arc arcs_31_2[2] = { - {81, 1}, - {0, 2}, + {81, 1}, + {0, 2}, }; static state states_31[3] = { - {1, arcs_31_0}, - {2, arcs_31_1}, - {2, arcs_31_2}, + {1, arcs_31_0}, + {2, arcs_31_1}, + {2, arcs_31_2}, }; static arc arcs_32_0[1] = { - {83, 1}, + {83, 1}, }; static arc arcs_32_1[2] = { - {30, 0}, - {0, 1}, + {30, 0}, + {0, 1}, }; static state states_32[2] = { - {1, arcs_32_0}, - {2, arcs_32_1}, + {1, arcs_32_0}, + {2, arcs_32_1}, }; static arc arcs_33_0[1] = { - {21, 1}, + {21, 1}, }; static arc arcs_33_1[2] = { - {78, 0}, - {0, 1}, + {78, 0}, + {0, 1}, }; static state states_33[2] = { - {1, arcs_33_0}, - {2, arcs_33_1}, + {1, arcs_33_0}, + {2, arcs_33_1}, }; static arc arcs_34_0[1] = { - {84, 1}, + {84, 1}, }; static arc arcs_34_1[1] = { - {21, 2}, + {21, 2}, }; static arc arcs_34_2[2] = { - {30, 1}, - {0, 2}, + {30, 1}, + {0, 2}, }; static state states_34[3] = { - {1, arcs_34_0}, - {1, arcs_34_1}, - {2, arcs_34_2}, + {1, arcs_34_0}, + {1, arcs_34_1}, + {2, arcs_34_2}, }; static arc arcs_35_0[1] = { - {85, 1}, + {85, 1}, }; static arc arcs_35_1[1] = { - {21, 2}, + {21, 2}, }; static arc arcs_35_2[2] = { - {30, 1}, - {0, 2}, + {30, 1}, + {0, 2}, }; static state states_35[3] = { - {1, arcs_35_0}, - {1, arcs_35_1}, - {2, arcs_35_2}, + {1, arcs_35_0}, + {1, arcs_35_1}, + {2, arcs_35_2}, }; static arc arcs_36_0[1] = { - {86, 1}, + {86, 1}, }; static arc arcs_36_1[1] = { - {24, 2}, + {24, 2}, }; static arc arcs_36_2[2] = { - {30, 3}, - {0, 2}, + {30, 3}, + {0, 2}, }; static arc arcs_36_3[1] = { - {24, 4}, + {24, 4}, }; static arc arcs_36_4[1] = { - {0, 4}, + {0, 4}, }; static state states_36[5] = { - {1, arcs_36_0}, - {1, arcs_36_1}, - {2, arcs_36_2}, - {1, arcs_36_3}, - {1, arcs_36_4}, + {1, arcs_36_0}, + {1, arcs_36_1}, + {2, arcs_36_2}, + {1, arcs_36_3}, + {1, arcs_36_4}, }; static arc arcs_37_0[8] = { - {87, 1}, - {88, 1}, - {89, 1}, - {90, 1}, - {91, 1}, - {19, 1}, - {18, 1}, - {17, 1}, + {87, 1}, + {88, 1}, + {89, 1}, + {90, 1}, + {91, 1}, + {19, 1}, + {18, 1}, + {17, 1}, }; static arc arcs_37_1[1] = { - {0, 1}, + {0, 1}, }; static state states_37[2] = { - {8, arcs_37_0}, - {1, arcs_37_1}, + {8, arcs_37_0}, + {1, arcs_37_1}, }; static arc arcs_38_0[1] = { - {92, 1}, + {92, 1}, }; static arc arcs_38_1[1] = { - {24, 2}, + {24, 2}, }; static arc arcs_38_2[1] = { - {25, 3}, + {25, 3}, }; static arc arcs_38_3[1] = { - {26, 4}, + {26, 4}, }; static arc arcs_38_4[3] = { - {93, 1}, - {94, 5}, - {0, 4}, + {93, 1}, + {94, 5}, + {0, 4}, }; static arc arcs_38_5[1] = { - {25, 6}, + {25, 6}, }; static arc arcs_38_6[1] = { - {26, 7}, + {26, 7}, }; static arc arcs_38_7[1] = { - {0, 7}, + {0, 7}, }; static state states_38[8] = { - {1, arcs_38_0}, - {1, arcs_38_1}, - {1, arcs_38_2}, - {1, arcs_38_3}, - {3, arcs_38_4}, - {1, arcs_38_5}, - {1, arcs_38_6}, - {1, arcs_38_7}, + {1, arcs_38_0}, + {1, arcs_38_1}, + {1, arcs_38_2}, + {1, arcs_38_3}, + {3, arcs_38_4}, + {1, arcs_38_5}, + {1, arcs_38_6}, + {1, arcs_38_7}, }; static arc arcs_39_0[1] = { - {95, 1}, + {95, 1}, }; static arc arcs_39_1[1] = { - {24, 2}, + {24, 2}, }; static arc arcs_39_2[1] = { - {25, 3}, + {25, 3}, }; static arc arcs_39_3[1] = { - {26, 4}, + {26, 4}, }; static arc arcs_39_4[2] = { - {94, 5}, - {0, 4}, + {94, 5}, + {0, 4}, }; static arc arcs_39_5[1] = { - {25, 6}, + {25, 6}, }; static arc arcs_39_6[1] = { - {26, 7}, + {26, 7}, }; static arc arcs_39_7[1] = { - {0, 7}, + {0, 7}, }; static state states_39[8] = { - {1, arcs_39_0}, - {1, arcs_39_1}, - {1, arcs_39_2}, - {1, arcs_39_3}, - {2, arcs_39_4}, - {1, arcs_39_5}, - {1, arcs_39_6}, - {1, arcs_39_7}, + {1, arcs_39_0}, + {1, arcs_39_1}, + {1, arcs_39_2}, + {1, arcs_39_3}, + {2, arcs_39_4}, + {1, arcs_39_5}, + {1, arcs_39_6}, + {1, arcs_39_7}, }; static arc arcs_40_0[1] = { - {96, 1}, + {96, 1}, }; static arc arcs_40_1[1] = { - {62, 2}, + {62, 2}, }; static arc arcs_40_2[1] = { - {97, 3}, + {97, 3}, }; static arc arcs_40_3[1] = { - {9, 4}, + {9, 4}, }; static arc arcs_40_4[1] = { - {25, 5}, + {25, 5}, }; static arc arcs_40_5[1] = { - {26, 6}, + {26, 6}, }; static arc arcs_40_6[2] = { - {94, 7}, - {0, 6}, + {94, 7}, + {0, 6}, }; static arc arcs_40_7[1] = { - {25, 8}, + {25, 8}, }; static arc arcs_40_8[1] = { - {26, 9}, + {26, 9}, }; static arc arcs_40_9[1] = { - {0, 9}, + {0, 9}, }; static state states_40[10] = { - {1, arcs_40_0}, - {1, arcs_40_1}, - {1, arcs_40_2}, - {1, arcs_40_3}, - {1, arcs_40_4}, - {1, arcs_40_5}, - {2, arcs_40_6}, - {1, arcs_40_7}, - {1, arcs_40_8}, - {1, arcs_40_9}, + {1, arcs_40_0}, + {1, arcs_40_1}, + {1, arcs_40_2}, + {1, arcs_40_3}, + {1, arcs_40_4}, + {1, arcs_40_5}, + {2, arcs_40_6}, + {1, arcs_40_7}, + {1, arcs_40_8}, + {1, arcs_40_9}, }; static arc arcs_41_0[1] = { - {98, 1}, + {98, 1}, }; static arc arcs_41_1[1] = { - {25, 2}, + {25, 2}, }; static arc arcs_41_2[1] = { - {26, 3}, + {26, 3}, }; static arc arcs_41_3[2] = { - {99, 4}, - {100, 5}, + {99, 4}, + {100, 5}, }; static arc arcs_41_4[1] = { - {25, 6}, + {25, 6}, }; static arc arcs_41_5[1] = { - {25, 7}, + {25, 7}, }; static arc arcs_41_6[1] = { - {26, 8}, + {26, 8}, }; static arc arcs_41_7[1] = { - {26, 9}, + {26, 9}, }; static arc arcs_41_8[4] = { - {99, 4}, - {94, 10}, - {100, 5}, - {0, 8}, + {99, 4}, + {94, 10}, + {100, 5}, + {0, 8}, }; static arc arcs_41_9[1] = { - {0, 9}, + {0, 9}, }; static arc arcs_41_10[1] = { - {25, 11}, + {25, 11}, }; static arc arcs_41_11[1] = { - {26, 12}, + {26, 12}, }; static arc arcs_41_12[2] = { - {100, 5}, - {0, 12}, + {100, 5}, + {0, 12}, }; static state states_41[13] = { - {1, arcs_41_0}, - {1, arcs_41_1}, - {1, arcs_41_2}, - {2, arcs_41_3}, - {1, arcs_41_4}, - {1, arcs_41_5}, - {1, arcs_41_6}, - {1, arcs_41_7}, - {4, arcs_41_8}, - {1, arcs_41_9}, - {1, arcs_41_10}, - {1, arcs_41_11}, - {2, arcs_41_12}, + {1, arcs_41_0}, + {1, arcs_41_1}, + {1, arcs_41_2}, + {2, arcs_41_3}, + {1, arcs_41_4}, + {1, arcs_41_5}, + {1, arcs_41_6}, + {1, arcs_41_7}, + {4, arcs_41_8}, + {1, arcs_41_9}, + {1, arcs_41_10}, + {1, arcs_41_11}, + {2, arcs_41_12}, }; static arc arcs_42_0[1] = { - {101, 1}, + {101, 1}, }; static arc arcs_42_1[1] = { - {102, 2}, + {102, 2}, }; static arc arcs_42_2[2] = { - {30, 1}, - {25, 3}, + {30, 1}, + {25, 3}, }; static arc arcs_42_3[1] = { - {26, 4}, + {26, 4}, }; static arc arcs_42_4[1] = { - {0, 4}, + {0, 4}, }; static state states_42[5] = { - {1, arcs_42_0}, - {1, arcs_42_1}, - {2, arcs_42_2}, - {1, arcs_42_3}, - {1, arcs_42_4}, + {1, arcs_42_0}, + {1, arcs_42_1}, + {2, arcs_42_2}, + {1, arcs_42_3}, + {1, arcs_42_4}, }; static arc arcs_43_0[1] = { - {24, 1}, + {24, 1}, }; static arc arcs_43_1[2] = { - {82, 2}, - {0, 1}, + {82, 2}, + {0, 1}, }; static arc arcs_43_2[1] = { - {103, 3}, + {103, 3}, }; static arc arcs_43_3[1] = { - {0, 3}, + {0, 3}, }; static state states_43[4] = { - {1, arcs_43_0}, - {2, arcs_43_1}, - {1, arcs_43_2}, - {1, arcs_43_3}, + {1, arcs_43_0}, + {2, arcs_43_1}, + {1, arcs_43_2}, + {1, arcs_43_3}, }; static arc arcs_44_0[1] = { - {104, 1}, + {104, 1}, }; static arc arcs_44_1[2] = { - {24, 2}, - {0, 1}, + {24, 2}, + {0, 1}, }; static arc arcs_44_2[2] = { - {82, 3}, - {0, 2}, + {82, 3}, + {0, 2}, }; static arc arcs_44_3[1] = { - {21, 4}, + {21, 4}, }; static arc arcs_44_4[1] = { - {0, 4}, + {0, 4}, }; static state states_44[5] = { - {1, arcs_44_0}, - {2, arcs_44_1}, - {2, arcs_44_2}, - {1, arcs_44_3}, - {1, arcs_44_4}, + {1, arcs_44_0}, + {2, arcs_44_1}, + {2, arcs_44_2}, + {1, arcs_44_3}, + {1, arcs_44_4}, }; static arc arcs_45_0[2] = { - {3, 1}, - {2, 2}, + {3, 1}, + {2, 2}, }; static arc arcs_45_1[1] = { - {0, 1}, + {0, 1}, }; static arc arcs_45_2[1] = { - {105, 3}, + {105, 3}, }; static arc arcs_45_3[1] = { - {6, 4}, + {6, 4}, }; static arc arcs_45_4[2] = { - {6, 4}, - {106, 1}, + {6, 4}, + {106, 1}, }; static state states_45[5] = { - {2, arcs_45_0}, - {1, arcs_45_1}, - {1, arcs_45_2}, - {1, arcs_45_3}, - {2, arcs_45_4}, + {2, arcs_45_0}, + {1, arcs_45_1}, + {1, arcs_45_2}, + {1, arcs_45_3}, + {2, arcs_45_4}, }; static arc arcs_46_0[2] = { - {107, 1}, - {108, 2}, + {107, 1}, + {108, 2}, }; static arc arcs_46_1[2] = { - {92, 3}, - {0, 1}, + {92, 3}, + {0, 1}, }; static arc arcs_46_2[1] = { - {0, 2}, + {0, 2}, }; static arc arcs_46_3[1] = { - {107, 4}, + {107, 4}, }; static arc arcs_46_4[1] = { - {94, 5}, + {94, 5}, }; static arc arcs_46_5[1] = { - {24, 2}, + {24, 2}, }; static state states_46[6] = { - {2, arcs_46_0}, - {2, arcs_46_1}, - {1, arcs_46_2}, - {1, arcs_46_3}, - {1, arcs_46_4}, - {1, arcs_46_5}, + {2, arcs_46_0}, + {2, arcs_46_1}, + {1, arcs_46_2}, + {1, arcs_46_3}, + {1, arcs_46_4}, + {1, arcs_46_5}, }; static arc arcs_47_0[2] = { - {107, 1}, - {110, 1}, + {107, 1}, + {110, 1}, }; static arc arcs_47_1[1] = { - {0, 1}, + {0, 1}, }; static state states_47[2] = { - {2, arcs_47_0}, - {1, arcs_47_1}, + {2, arcs_47_0}, + {1, arcs_47_1}, }; static arc arcs_48_0[1] = { - {111, 1}, + {111, 1}, }; static arc arcs_48_1[2] = { - {33, 2}, - {25, 3}, + {33, 2}, + {25, 3}, }; static arc arcs_48_2[1] = { - {25, 3}, + {25, 3}, }; static arc arcs_48_3[1] = { - {24, 4}, + {24, 4}, }; static arc arcs_48_4[1] = { - {0, 4}, + {0, 4}, }; static state states_48[5] = { - {1, arcs_48_0}, - {2, arcs_48_1}, - {1, arcs_48_2}, - {1, arcs_48_3}, - {1, arcs_48_4}, + {1, arcs_48_0}, + {2, arcs_48_1}, + {1, arcs_48_2}, + {1, arcs_48_3}, + {1, arcs_48_4}, }; static arc arcs_49_0[1] = { - {111, 1}, + {111, 1}, }; static arc arcs_49_1[2] = { - {33, 2}, - {25, 3}, + {33, 2}, + {25, 3}, }; static arc arcs_49_2[1] = { - {25, 3}, + {25, 3}, }; static arc arcs_49_3[1] = { - {109, 4}, + {109, 4}, }; static arc arcs_49_4[1] = { - {0, 4}, + {0, 4}, }; static state states_49[5] = { - {1, arcs_49_0}, - {2, arcs_49_1}, - {1, arcs_49_2}, - {1, arcs_49_3}, - {1, arcs_49_4}, + {1, arcs_49_0}, + {2, arcs_49_1}, + {1, arcs_49_2}, + {1, arcs_49_3}, + {1, arcs_49_4}, }; static arc arcs_50_0[1] = { - {112, 1}, + {112, 1}, }; static arc arcs_50_1[2] = { - {113, 0}, - {0, 1}, + {113, 0}, + {0, 1}, }; static state states_50[2] = { - {1, arcs_50_0}, - {2, arcs_50_1}, + {1, arcs_50_0}, + {2, arcs_50_1}, }; static arc arcs_51_0[1] = { - {114, 1}, + {114, 1}, }; static arc arcs_51_1[2] = { - {115, 0}, - {0, 1}, + {115, 0}, + {0, 1}, }; static state states_51[2] = { - {1, arcs_51_0}, - {2, arcs_51_1}, + {1, arcs_51_0}, + {2, arcs_51_1}, }; static arc arcs_52_0[2] = { - {116, 1}, - {117, 2}, + {116, 1}, + {117, 2}, }; static arc arcs_52_1[1] = { - {114, 2}, + {114, 2}, }; static arc arcs_52_2[1] = { - {0, 2}, + {0, 2}, }; static state states_52[3] = { - {2, arcs_52_0}, - {1, arcs_52_1}, - {1, arcs_52_2}, + {2, arcs_52_0}, + {1, arcs_52_1}, + {1, arcs_52_2}, }; static arc arcs_53_0[1] = { - {103, 1}, + {103, 1}, }; static arc arcs_53_1[2] = { - {118, 0}, - {0, 1}, + {118, 0}, + {0, 1}, }; static state states_53[2] = { - {1, arcs_53_0}, - {2, arcs_53_1}, + {1, arcs_53_0}, + {2, arcs_53_1}, }; static arc arcs_54_0[10] = { - {119, 1}, - {120, 1}, - {121, 1}, - {122, 1}, - {123, 1}, - {124, 1}, - {125, 1}, - {97, 1}, - {116, 2}, - {126, 3}, + {119, 1}, + {120, 1}, + {121, 1}, + {122, 1}, + {123, 1}, + {124, 1}, + {125, 1}, + {97, 1}, + {116, 2}, + {126, 3}, }; static arc arcs_54_1[1] = { - {0, 1}, + {0, 1}, }; static arc arcs_54_2[1] = { - {97, 1}, + {97, 1}, }; static arc arcs_54_3[2] = { - {116, 1}, - {0, 3}, + {116, 1}, + {0, 3}, }; static state states_54[4] = { - {10, arcs_54_0}, - {1, arcs_54_1}, - {1, arcs_54_2}, - {2, arcs_54_3}, + {10, arcs_54_0}, + {1, arcs_54_1}, + {1, arcs_54_2}, + {2, arcs_54_3}, }; static arc arcs_55_0[1] = { - {31, 1}, + {31, 1}, }; static arc arcs_55_1[1] = { - {103, 2}, + {103, 2}, }; static arc arcs_55_2[1] = { - {0, 2}, + {0, 2}, }; static state states_55[3] = { - {1, arcs_55_0}, - {1, arcs_55_1}, - {1, arcs_55_2}, + {1, arcs_55_0}, + {1, arcs_55_1}, + {1, arcs_55_2}, }; static arc arcs_56_0[1] = { - {127, 1}, + {127, 1}, }; static arc arcs_56_1[2] = { - {128, 0}, - {0, 1}, + {128, 0}, + {0, 1}, }; static state states_56[2] = { - {1, arcs_56_0}, - {2, arcs_56_1}, + {1, arcs_56_0}, + {2, arcs_56_1}, }; static arc arcs_57_0[1] = { - {129, 1}, + {129, 1}, }; static arc arcs_57_1[2] = { - {130, 0}, - {0, 1}, + {130, 0}, + {0, 1}, }; static state states_57[2] = { - {1, arcs_57_0}, - {2, arcs_57_1}, + {1, arcs_57_0}, + {2, arcs_57_1}, }; static arc arcs_58_0[1] = { - {131, 1}, + {131, 1}, }; static arc arcs_58_1[2] = { - {132, 0}, - {0, 1}, + {132, 0}, + {0, 1}, }; static state states_58[2] = { - {1, arcs_58_0}, - {2, arcs_58_1}, + {1, arcs_58_0}, + {2, arcs_58_1}, }; static arc arcs_59_0[1] = { - {133, 1}, + {133, 1}, }; static arc arcs_59_1[3] = { - {134, 0}, - {135, 0}, - {0, 1}, + {134, 0}, + {135, 0}, + {0, 1}, }; static state states_59[2] = { - {1, arcs_59_0}, - {3, arcs_59_1}, + {1, arcs_59_0}, + {3, arcs_59_1}, }; static arc arcs_60_0[1] = { - {136, 1}, + {136, 1}, }; static arc arcs_60_1[3] = { - {137, 0}, - {138, 0}, - {0, 1}, + {137, 0}, + {138, 0}, + {0, 1}, }; static state states_60[2] = { - {1, arcs_60_0}, - {3, arcs_60_1}, + {1, arcs_60_0}, + {3, arcs_60_1}, }; static arc arcs_61_0[1] = { - {139, 1}, + {139, 1}, }; static arc arcs_61_1[5] = { - {31, 0}, - {140, 0}, - {141, 0}, - {142, 0}, - {0, 1}, + {31, 0}, + {140, 0}, + {141, 0}, + {142, 0}, + {0, 1}, }; static state states_61[2] = { - {1, arcs_61_0}, - {5, arcs_61_1}, + {1, arcs_61_0}, + {5, arcs_61_1}, }; static arc arcs_62_0[4] = { - {137, 1}, - {138, 1}, - {143, 1}, - {144, 2}, + {137, 1}, + {138, 1}, + {143, 1}, + {144, 2}, }; static arc arcs_62_1[1] = { - {139, 2}, + {139, 2}, }; static arc arcs_62_2[1] = { - {0, 2}, + {0, 2}, }; static state states_62[3] = { - {4, arcs_62_0}, - {1, arcs_62_1}, - {1, arcs_62_2}, + {4, arcs_62_0}, + {1, arcs_62_1}, + {1, arcs_62_2}, }; static arc arcs_63_0[1] = { - {145, 1}, + {145, 1}, }; static arc arcs_63_1[3] = { - {146, 1}, - {32, 2}, - {0, 1}, + {146, 1}, + {32, 2}, + {0, 1}, }; static arc arcs_63_2[1] = { - {139, 3}, + {139, 3}, }; static arc arcs_63_3[1] = { - {0, 3}, + {0, 3}, }; static state states_63[4] = { - {1, arcs_63_0}, - {3, arcs_63_1}, - {1, arcs_63_2}, - {1, arcs_63_3}, + {1, arcs_63_0}, + {3, arcs_63_1}, + {1, arcs_63_2}, + {1, arcs_63_3}, }; static arc arcs_64_0[10] = { - {13, 1}, - {148, 2}, - {150, 3}, - {21, 4}, - {153, 4}, - {154, 5}, - {79, 4}, - {155, 4}, - {156, 4}, - {157, 4}, + {13, 1}, + {148, 2}, + {150, 3}, + {21, 4}, + {153, 4}, + {154, 5}, + {79, 4}, + {155, 4}, + {156, 4}, + {157, 4}, }; static arc arcs_64_1[3] = { - {47, 6}, - {147, 6}, - {15, 4}, + {47, 6}, + {147, 6}, + {15, 4}, }; static arc arcs_64_2[2] = { - {147, 7}, - {149, 4}, + {147, 7}, + {149, 4}, }; static arc arcs_64_3[2] = { - {151, 8}, - {152, 4}, + {151, 8}, + {152, 4}, }; static arc arcs_64_4[1] = { - {0, 4}, + {0, 4}, }; static arc arcs_64_5[2] = { - {154, 5}, - {0, 5}, + {154, 5}, + {0, 5}, }; static arc arcs_64_6[1] = { - {15, 4}, + {15, 4}, }; static arc arcs_64_7[1] = { - {149, 4}, + {149, 4}, }; static arc arcs_64_8[1] = { - {152, 4}, + {152, 4}, }; static state states_64[9] = { - {10, arcs_64_0}, - {3, arcs_64_1}, - {2, arcs_64_2}, - {2, arcs_64_3}, - {1, arcs_64_4}, - {2, arcs_64_5}, - {1, arcs_64_6}, - {1, arcs_64_7}, - {1, arcs_64_8}, + {10, arcs_64_0}, + {3, arcs_64_1}, + {2, arcs_64_2}, + {2, arcs_64_3}, + {1, arcs_64_4}, + {2, arcs_64_5}, + {1, arcs_64_6}, + {1, arcs_64_7}, + {1, arcs_64_8}, }; static arc arcs_65_0[2] = { - {24, 1}, - {48, 1}, + {24, 1}, + {48, 1}, }; static arc arcs_65_1[3] = { - {158, 2}, - {30, 3}, - {0, 1}, + {158, 2}, + {30, 3}, + {0, 1}, }; static arc arcs_65_2[1] = { - {0, 2}, + {0, 2}, }; static arc arcs_65_3[3] = { - {24, 4}, - {48, 4}, - {0, 3}, + {24, 4}, + {48, 4}, + {0, 3}, }; static arc arcs_65_4[2] = { - {30, 3}, - {0, 4}, + {30, 3}, + {0, 4}, }; static state states_65[5] = { - {2, arcs_65_0}, - {3, arcs_65_1}, - {1, arcs_65_2}, - {3, arcs_65_3}, - {2, arcs_65_4}, + {2, arcs_65_0}, + {3, arcs_65_1}, + {1, arcs_65_2}, + {3, arcs_65_3}, + {2, arcs_65_4}, }; static arc arcs_66_0[3] = { - {13, 1}, - {148, 2}, - {78, 3}, + {13, 1}, + {148, 2}, + {78, 3}, }; static arc arcs_66_1[2] = { - {14, 4}, - {15, 5}, + {14, 4}, + {15, 5}, }; static arc arcs_66_2[1] = { - {159, 6}, + {159, 6}, }; static arc arcs_66_3[1] = { - {21, 5}, + {21, 5}, }; static arc arcs_66_4[1] = { - {15, 5}, + {15, 5}, }; static arc arcs_66_5[1] = { - {0, 5}, + {0, 5}, }; static arc arcs_66_6[1] = { - {149, 5}, + {149, 5}, }; static state states_66[7] = { - {3, arcs_66_0}, - {2, arcs_66_1}, - {1, arcs_66_2}, - {1, arcs_66_3}, - {1, arcs_66_4}, - {1, arcs_66_5}, - {1, arcs_66_6}, + {3, arcs_66_0}, + {2, arcs_66_1}, + {1, arcs_66_2}, + {1, arcs_66_3}, + {1, arcs_66_4}, + {1, arcs_66_5}, + {1, arcs_66_6}, }; static arc arcs_67_0[1] = { - {160, 1}, + {160, 1}, }; static arc arcs_67_1[2] = { - {30, 2}, - {0, 1}, + {30, 2}, + {0, 1}, }; static arc arcs_67_2[2] = { - {160, 1}, - {0, 2}, + {160, 1}, + {0, 2}, }; static state states_67[3] = { - {1, arcs_67_0}, - {2, arcs_67_1}, - {2, arcs_67_2}, + {1, arcs_67_0}, + {2, arcs_67_1}, + {2, arcs_67_2}, }; static arc arcs_68_0[2] = { - {24, 1}, - {25, 2}, + {24, 1}, + {25, 2}, }; static arc arcs_68_1[2] = { - {25, 2}, - {0, 1}, + {25, 2}, + {0, 1}, }; static arc arcs_68_2[3] = { - {24, 3}, - {161, 4}, - {0, 2}, + {24, 3}, + {161, 4}, + {0, 2}, }; static arc arcs_68_3[2] = { - {161, 4}, - {0, 3}, + {161, 4}, + {0, 3}, }; static arc arcs_68_4[1] = { - {0, 4}, + {0, 4}, }; static state states_68[5] = { - {2, arcs_68_0}, - {2, arcs_68_1}, - {3, arcs_68_2}, - {2, arcs_68_3}, - {1, arcs_68_4}, + {2, arcs_68_0}, + {2, arcs_68_1}, + {3, arcs_68_2}, + {2, arcs_68_3}, + {1, arcs_68_4}, }; static arc arcs_69_0[1] = { - {25, 1}, + {25, 1}, }; static arc arcs_69_1[2] = { - {24, 2}, - {0, 1}, + {24, 2}, + {0, 1}, }; static arc arcs_69_2[1] = { - {0, 2}, + {0, 2}, }; static state states_69[3] = { - {1, arcs_69_0}, - {2, arcs_69_1}, - {1, arcs_69_2}, + {1, arcs_69_0}, + {2, arcs_69_1}, + {1, arcs_69_2}, }; static arc arcs_70_0[2] = { - {103, 1}, - {48, 1}, + {103, 1}, + {48, 1}, }; static arc arcs_70_1[2] = { - {30, 2}, - {0, 1}, + {30, 2}, + {0, 1}, }; static arc arcs_70_2[3] = { - {103, 1}, - {48, 1}, - {0, 2}, + {103, 1}, + {48, 1}, + {0, 2}, }; static state states_70[3] = { - {2, arcs_70_0}, - {2, arcs_70_1}, - {3, arcs_70_2}, + {2, arcs_70_0}, + {2, arcs_70_1}, + {3, arcs_70_2}, }; static arc arcs_71_0[1] = { - {24, 1}, + {24, 1}, }; static arc arcs_71_1[2] = { - {30, 2}, - {0, 1}, + {30, 2}, + {0, 1}, }; static arc arcs_71_2[2] = { - {24, 1}, - {0, 2}, + {24, 1}, + {0, 2}, }; static state states_71[3] = { - {1, arcs_71_0}, - {2, arcs_71_1}, - {2, arcs_71_2}, + {1, arcs_71_0}, + {2, arcs_71_1}, + {2, arcs_71_2}, }; static arc arcs_72_0[1] = { - {24, 1}, + {24, 1}, }; static arc arcs_72_1[4] = { - {25, 2}, - {158, 3}, - {30, 4}, - {0, 1}, + {25, 2}, + {158, 3}, + {30, 4}, + {0, 1}, }; static arc arcs_72_2[1] = { - {24, 5}, + {24, 5}, }; static arc arcs_72_3[1] = { - {0, 3}, + {0, 3}, }; static arc arcs_72_4[2] = { - {24, 6}, - {0, 4}, + {24, 6}, + {0, 4}, }; static arc arcs_72_5[3] = { - {158, 3}, - {30, 7}, - {0, 5}, + {158, 3}, + {30, 7}, + {0, 5}, }; static arc arcs_72_6[2] = { - {30, 4}, - {0, 6}, + {30, 4}, + {0, 6}, }; static arc arcs_72_7[2] = { - {24, 8}, - {0, 7}, + {24, 8}, + {0, 7}, }; static arc arcs_72_8[1] = { - {25, 9}, + {25, 9}, }; static arc arcs_72_9[1] = { - {24, 10}, + {24, 10}, }; static arc arcs_72_10[2] = { - {30, 7}, - {0, 10}, + {30, 7}, + {0, 10}, }; static state states_72[11] = { - {1, arcs_72_0}, - {4, arcs_72_1}, - {1, arcs_72_2}, - {1, arcs_72_3}, - {2, arcs_72_4}, - {3, arcs_72_5}, - {2, arcs_72_6}, - {2, arcs_72_7}, - {1, arcs_72_8}, - {1, arcs_72_9}, - {2, arcs_72_10}, + {1, arcs_72_0}, + {4, arcs_72_1}, + {1, arcs_72_2}, + {1, arcs_72_3}, + {2, arcs_72_4}, + {3, arcs_72_5}, + {2, arcs_72_6}, + {2, arcs_72_7}, + {1, arcs_72_8}, + {1, arcs_72_9}, + {2, arcs_72_10}, }; static arc arcs_73_0[1] = { - {162, 1}, + {162, 1}, }; static arc arcs_73_1[1] = { - {21, 2}, + {21, 2}, }; static arc arcs_73_2[2] = { - {13, 3}, - {25, 4}, + {13, 3}, + {25, 4}, }; static arc arcs_73_3[2] = { - {14, 5}, - {15, 6}, + {14, 5}, + {15, 6}, }; static arc arcs_73_4[1] = { - {26, 7}, + {26, 7}, }; static arc arcs_73_5[1] = { - {15, 6}, + {15, 6}, }; static arc arcs_73_6[1] = { - {25, 4}, + {25, 4}, }; static arc arcs_73_7[1] = { - {0, 7}, + {0, 7}, }; static state states_73[8] = { - {1, arcs_73_0}, - {1, arcs_73_1}, - {2, arcs_73_2}, - {2, arcs_73_3}, - {1, arcs_73_4}, - {1, arcs_73_5}, - {1, arcs_73_6}, - {1, arcs_73_7}, + {1, arcs_73_0}, + {1, arcs_73_1}, + {2, arcs_73_2}, + {2, arcs_73_3}, + {1, arcs_73_4}, + {1, arcs_73_5}, + {1, arcs_73_6}, + {1, arcs_73_7}, }; static arc arcs_74_0[3] = { - {163, 1}, - {31, 2}, - {32, 3}, + {163, 1}, + {31, 2}, + {32, 3}, }; static arc arcs_74_1[2] = { - {30, 4}, - {0, 1}, + {30, 4}, + {0, 1}, }; static arc arcs_74_2[1] = { - {24, 5}, + {24, 5}, }; static arc arcs_74_3[1] = { - {24, 6}, + {24, 6}, }; static arc arcs_74_4[4] = { - {163, 1}, - {31, 2}, - {32, 3}, - {0, 4}, + {163, 1}, + {31, 2}, + {32, 3}, + {0, 4}, }; static arc arcs_74_5[2] = { - {30, 7}, - {0, 5}, + {30, 7}, + {0, 5}, }; static arc arcs_74_6[1] = { - {0, 6}, + {0, 6}, }; static arc arcs_74_7[2] = { - {163, 5}, - {32, 3}, + {163, 5}, + {32, 3}, }; static state states_74[8] = { - {3, arcs_74_0}, - {2, arcs_74_1}, - {1, arcs_74_2}, - {1, arcs_74_3}, - {4, arcs_74_4}, - {2, arcs_74_5}, - {1, arcs_74_6}, - {2, arcs_74_7}, + {3, arcs_74_0}, + {2, arcs_74_1}, + {1, arcs_74_2}, + {1, arcs_74_3}, + {4, arcs_74_4}, + {2, arcs_74_5}, + {1, arcs_74_6}, + {2, arcs_74_7}, }; static arc arcs_75_0[1] = { - {24, 1}, + {24, 1}, }; static arc arcs_75_1[3] = { - {158, 2}, - {29, 3}, - {0, 1}, + {158, 2}, + {29, 3}, + {0, 1}, }; static arc arcs_75_2[1] = { - {0, 2}, + {0, 2}, }; static arc arcs_75_3[1] = { - {24, 2}, + {24, 2}, }; static state states_75[4] = { - {1, arcs_75_0}, - {3, arcs_75_1}, - {1, arcs_75_2}, - {1, arcs_75_3}, + {1, arcs_75_0}, + {3, arcs_75_1}, + {1, arcs_75_2}, + {1, arcs_75_3}, }; static arc arcs_76_0[2] = { - {158, 1}, - {165, 1}, + {158, 1}, + {165, 1}, }; static arc arcs_76_1[1] = { - {0, 1}, + {0, 1}, }; static state states_76[2] = { - {2, arcs_76_0}, - {1, arcs_76_1}, + {2, arcs_76_0}, + {1, arcs_76_1}, }; static arc arcs_77_0[1] = { - {96, 1}, + {96, 1}, }; static arc arcs_77_1[1] = { - {62, 2}, + {62, 2}, }; static arc arcs_77_2[1] = { - {97, 3}, + {97, 3}, }; static arc arcs_77_3[1] = { - {107, 4}, + {107, 4}, }; static arc arcs_77_4[2] = { - {164, 5}, - {0, 4}, + {164, 5}, + {0, 4}, }; static arc arcs_77_5[1] = { - {0, 5}, + {0, 5}, }; static state states_77[6] = { - {1, arcs_77_0}, - {1, arcs_77_1}, - {1, arcs_77_2}, - {1, arcs_77_3}, - {2, arcs_77_4}, - {1, arcs_77_5}, + {1, arcs_77_0}, + {1, arcs_77_1}, + {1, arcs_77_2}, + {1, arcs_77_3}, + {2, arcs_77_4}, + {1, arcs_77_5}, }; static arc arcs_78_0[1] = { - {92, 1}, + {92, 1}, }; static arc arcs_78_1[1] = { - {109, 2}, + {109, 2}, }; static arc arcs_78_2[2] = { - {164, 3}, - {0, 2}, + {164, 3}, + {0, 2}, }; static arc arcs_78_3[1] = { - {0, 3}, + {0, 3}, }; static state states_78[4] = { - {1, arcs_78_0}, - {1, arcs_78_1}, - {2, arcs_78_2}, - {1, arcs_78_3}, + {1, arcs_78_0}, + {1, arcs_78_1}, + {2, arcs_78_2}, + {1, arcs_78_3}, }; static arc arcs_79_0[1] = { - {21, 1}, + {21, 1}, }; static arc arcs_79_1[1] = { - {0, 1}, + {0, 1}, }; static state states_79[2] = { - {1, arcs_79_0}, - {1, arcs_79_1}, + {1, arcs_79_0}, + {1, arcs_79_1}, }; static arc arcs_80_0[1] = { - {167, 1}, + {167, 1}, }; static arc arcs_80_1[2] = { - {9, 2}, - {0, 1}, + {9, 2}, + {0, 1}, }; static arc arcs_80_2[1] = { - {0, 2}, + {0, 2}, }; static state states_80[3] = { - {1, arcs_80_0}, - {2, arcs_80_1}, - {1, arcs_80_2}, + {1, arcs_80_0}, + {2, arcs_80_1}, + {1, arcs_80_2}, }; static dfa dfas[81] = { - {256, "single_input", 0, 3, states_0, - "\004\050\060\200\000\000\000\240\340\223\160\220\045\200\020\000\000\206\120\076\204"}, - {257, "file_input", 0, 2, states_1, - "\204\050\060\200\000\000\000\240\340\223\160\220\045\200\020\000\000\206\120\076\204"}, - {258, "eval_input", 0, 3, states_2, - "\000\040\040\000\000\000\000\000\000\200\000\000\000\200\020\000\000\206\120\076\000"}, - {259, "decorator", 0, 7, states_3, - "\000\010\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000"}, - {260, "decorators", 0, 2, states_4, - "\000\010\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000"}, - {261, "decorated", 0, 3, states_5, - "\000\010\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000"}, - {262, "funcdef", 0, 8, states_6, - "\000\000\020\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000"}, - {263, "parameters", 0, 4, states_7, - "\000\040\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000"}, - {264, "typedargslist", 0, 12, states_8, - "\000\000\040\200\001\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000"}, - {265, "tfpdef", 0, 4, states_9, - "\000\000\040\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000"}, - {266, "varargslist", 0, 12, states_10, - "\000\000\040\200\001\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000"}, - {267, "vfpdef", 0, 2, states_11, - "\000\000\040\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000"}, - {268, "stmt", 0, 2, states_12, - "\000\050\060\200\000\000\000\240\340\223\160\220\045\200\020\000\000\206\120\076\204"}, - {269, "simple_stmt", 0, 4, states_13, - "\000\040\040\200\000\000\000\240\340\223\160\000\000\200\020\000\000\206\120\076\200"}, - {270, "small_stmt", 0, 2, states_14, - "\000\040\040\200\000\000\000\240\340\223\160\000\000\200\020\000\000\206\120\076\200"}, - {271, "expr_stmt", 0, 6, states_15, - "\000\040\040\200\000\000\000\000\000\200\000\000\000\200\020\000\000\206\120\076\000"}, - {272, "testlist_star_expr", 0, 3, states_16, - "\000\040\040\200\000\000\000\000\000\200\000\000\000\200\020\000\000\206\120\076\000"}, - {273, "augassign", 0, 2, states_17, - "\000\000\000\000\000\000\376\037\000\000\000\000\000\000\000\000\000\000\000\000\000"}, - {274, "del_stmt", 0, 3, states_18, - "\000\000\000\000\000\000\000\040\000\000\000\000\000\000\000\000\000\000\000\000\000"}, - {275, "pass_stmt", 0, 2, states_19, - "\000\000\000\000\000\000\000\200\000\000\000\000\000\000\000\000\000\000\000\000\000"}, - {276, "flow_stmt", 0, 2, states_20, - "\000\000\000\000\000\000\000\000\340\001\000\000\000\000\000\000\000\000\000\000\200"}, - {277, "break_stmt", 0, 2, states_21, - "\000\000\000\000\000\000\000\000\040\000\000\000\000\000\000\000\000\000\000\000\000"}, - {278, "continue_stmt", 0, 2, states_22, - "\000\000\000\000\000\000\000\000\100\000\000\000\000\000\000\000\000\000\000\000\000"}, - {279, "return_stmt", 0, 3, states_23, - "\000\000\000\000\000\000\000\000\200\000\000\000\000\000\000\000\000\000\000\000\000"}, - {280, "yield_stmt", 0, 2, states_24, - "\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\200"}, - {281, "raise_stmt", 0, 5, states_25, - "\000\000\000\000\000\000\000\000\000\001\000\000\000\000\000\000\000\000\000\000\000"}, - {282, "import_stmt", 0, 2, states_26, - "\000\000\000\000\000\000\000\000\000\022\000\000\000\000\000\000\000\000\000\000\000"}, - {283, "import_name", 0, 3, states_27, - "\000\000\000\000\000\000\000\000\000\020\000\000\000\000\000\000\000\000\000\000\000"}, - {284, "import_from", 0, 8, states_28, - "\000\000\000\000\000\000\000\000\000\002\000\000\000\000\000\000\000\000\000\000\000"}, - {285, "import_as_name", 0, 4, states_29, - "\000\000\040\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000"}, - {286, "dotted_as_name", 0, 4, states_30, - "\000\000\040\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000"}, - {287, "import_as_names", 0, 3, states_31, - "\000\000\040\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000"}, - {288, "dotted_as_names", 0, 2, states_32, - "\000\000\040\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000"}, - {289, "dotted_name", 0, 2, states_33, - "\000\000\040\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000"}, - {290, "global_stmt", 0, 3, states_34, - "\000\000\000\000\000\000\000\000\000\000\020\000\000\000\000\000\000\000\000\000\000"}, - {291, "nonlocal_stmt", 0, 3, states_35, - "\000\000\000\000\000\000\000\000\000\000\040\000\000\000\000\000\000\000\000\000\000"}, - {292, "assert_stmt", 0, 5, states_36, - "\000\000\000\000\000\000\000\000\000\000\100\000\000\000\000\000\000\000\000\000\000"}, - {293, "compound_stmt", 0, 2, states_37, - "\000\010\020\000\000\000\000\000\000\000\000\220\045\000\000\000\000\000\000\000\004"}, - {294, "if_stmt", 0, 8, states_38, - "\000\000\000\000\000\000\000\000\000\000\000\020\000\000\000\000\000\000\000\000\000"}, - {295, "while_stmt", 0, 8, states_39, - "\000\000\000\000\000\000\000\000\000\000\000\200\000\000\000\000\000\000\000\000\000"}, - {296, "for_stmt", 0, 10, states_40, - "\000\000\000\000\000\000\000\000\000\000\000\000\001\000\000\000\000\000\000\000\000"}, - {297, "try_stmt", 0, 13, states_41, - "\000\000\000\000\000\000\000\000\000\000\000\000\004\000\000\000\000\000\000\000\000"}, - {298, "with_stmt", 0, 5, states_42, - "\000\000\000\000\000\000\000\000\000\000\000\000\040\000\000\000\000\000\000\000\000"}, - {299, "with_item", 0, 4, states_43, - "\000\040\040\000\000\000\000\000\000\200\000\000\000\200\020\000\000\206\120\076\000"}, - {300, "except_clause", 0, 5, states_44, - "\000\000\000\000\000\000\000\000\000\000\000\000\000\001\000\000\000\000\000\000\000"}, - {301, "suite", 0, 5, states_45, - "\004\040\040\200\000\000\000\240\340\223\160\000\000\200\020\000\000\206\120\076\200"}, - {302, "test", 0, 6, states_46, - "\000\040\040\000\000\000\000\000\000\200\000\000\000\200\020\000\000\206\120\076\000"}, - {303, "test_nocond", 0, 2, states_47, - "\000\040\040\000\000\000\000\000\000\200\000\000\000\200\020\000\000\206\120\076\000"}, - {304, "lambdef", 0, 5, states_48, - "\000\000\000\000\000\000\000\000\000\000\000\000\000\200\000\000\000\000\000\000\000"}, - {305, "lambdef_nocond", 0, 5, states_49, - "\000\000\000\000\000\000\000\000\000\000\000\000\000\200\000\000\000\000\000\000\000"}, - {306, "or_test", 0, 2, states_50, - "\000\040\040\000\000\000\000\000\000\200\000\000\000\000\020\000\000\206\120\076\000"}, - {307, "and_test", 0, 2, states_51, - "\000\040\040\000\000\000\000\000\000\200\000\000\000\000\020\000\000\206\120\076\000"}, - {308, "not_test", 0, 3, states_52, - "\000\040\040\000\000\000\000\000\000\200\000\000\000\000\020\000\000\206\120\076\000"}, - {309, "comparison", 0, 2, states_53, - "\000\040\040\000\000\000\000\000\000\200\000\000\000\000\000\000\000\206\120\076\000"}, - {310, "comp_op", 0, 4, states_54, - "\000\000\000\000\000\000\000\000\000\000\000\000\002\000\220\177\000\000\000\000\000"}, - {311, "star_expr", 0, 3, states_55, - "\000\000\000\200\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000"}, - {312, "expr", 0, 2, states_56, - "\000\040\040\000\000\000\000\000\000\200\000\000\000\000\000\000\000\206\120\076\000"}, - {313, "xor_expr", 0, 2, states_57, - "\000\040\040\000\000\000\000\000\000\200\000\000\000\000\000\000\000\206\120\076\000"}, - {314, "and_expr", 0, 2, states_58, - "\000\040\040\000\000\000\000\000\000\200\000\000\000\000\000\000\000\206\120\076\000"}, - {315, "shift_expr", 0, 2, states_59, - "\000\040\040\000\000\000\000\000\000\200\000\000\000\000\000\000\000\206\120\076\000"}, - {316, "arith_expr", 0, 2, states_60, - "\000\040\040\000\000\000\000\000\000\200\000\000\000\000\000\000\000\206\120\076\000"}, - {317, "term", 0, 2, states_61, - "\000\040\040\000\000\000\000\000\000\200\000\000\000\000\000\000\000\206\120\076\000"}, - {318, "factor", 0, 3, states_62, - "\000\040\040\000\000\000\000\000\000\200\000\000\000\000\000\000\000\206\120\076\000"}, - {319, "power", 0, 4, states_63, - "\000\040\040\000\000\000\000\000\000\200\000\000\000\000\000\000\000\000\120\076\000"}, - {320, "atom", 0, 9, states_64, - "\000\040\040\000\000\000\000\000\000\200\000\000\000\000\000\000\000\000\120\076\000"}, - {321, "testlist_comp", 0, 5, states_65, - "\000\040\040\200\000\000\000\000\000\200\000\000\000\200\020\000\000\206\120\076\000"}, - {322, "trailer", 0, 7, states_66, - "\000\040\000\000\000\000\000\000\000\100\000\000\000\000\000\000\000\000\020\000\000"}, - {323, "subscriptlist", 0, 3, states_67, - "\000\040\040\002\000\000\000\000\000\200\000\000\000\200\020\000\000\206\120\076\000"}, - {324, "subscript", 0, 5, states_68, - "\000\040\040\002\000\000\000\000\000\200\000\000\000\200\020\000\000\206\120\076\000"}, - {325, "sliceop", 0, 3, states_69, - "\000\000\000\002\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000"}, - {326, "exprlist", 0, 3, states_70, - "\000\040\040\200\000\000\000\000\000\200\000\000\000\000\000\000\000\206\120\076\000"}, - {327, "testlist", 0, 3, states_71, - "\000\040\040\000\000\000\000\000\000\200\000\000\000\200\020\000\000\206\120\076\000"}, - {328, "dictorsetmaker", 0, 11, states_72, - "\000\040\040\000\000\000\000\000\000\200\000\000\000\200\020\000\000\206\120\076\000"}, - {329, "classdef", 0, 8, states_73, - "\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\004"}, - {330, "arglist", 0, 8, states_74, - "\000\040\040\200\001\000\000\000\000\200\000\000\000\200\020\000\000\206\120\076\000"}, - {331, "argument", 0, 4, states_75, - "\000\040\040\000\000\000\000\000\000\200\000\000\000\200\020\000\000\206\120\076\000"}, - {332, "comp_iter", 0, 2, states_76, - "\000\000\000\000\000\000\000\000\000\000\000\020\001\000\000\000\000\000\000\000\000"}, - {333, "comp_for", 0, 6, states_77, - "\000\000\000\000\000\000\000\000\000\000\000\000\001\000\000\000\000\000\000\000\000"}, - {334, "comp_if", 0, 4, states_78, - "\000\000\000\000\000\000\000\000\000\000\000\020\000\000\000\000\000\000\000\000\000"}, - {335, "encoding_decl", 0, 2, states_79, - "\000\000\040\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000"}, - {336, "yield_expr", 0, 3, states_80, - "\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\200"}, + {256, "single_input", 0, 3, states_0, + "\004\050\060\200\000\000\000\240\340\223\160\220\045\200\020\000\000\206\120\076\204"}, + {257, "file_input", 0, 2, states_1, + "\204\050\060\200\000\000\000\240\340\223\160\220\045\200\020\000\000\206\120\076\204"}, + {258, "eval_input", 0, 3, states_2, + "\000\040\040\000\000\000\000\000\000\200\000\000\000\200\020\000\000\206\120\076\000"}, + {259, "decorator", 0, 7, states_3, + "\000\010\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000"}, + {260, "decorators", 0, 2, states_4, + "\000\010\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000"}, + {261, "decorated", 0, 3, states_5, + "\000\010\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000"}, + {262, "funcdef", 0, 8, states_6, + "\000\000\020\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000"}, + {263, "parameters", 0, 4, states_7, + "\000\040\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000"}, + {264, "typedargslist", 0, 12, states_8, + "\000\000\040\200\001\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000"}, + {265, "tfpdef", 0, 4, states_9, + "\000\000\040\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000"}, + {266, "varargslist", 0, 12, states_10, + "\000\000\040\200\001\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000"}, + {267, "vfpdef", 0, 2, states_11, + "\000\000\040\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000"}, + {268, "stmt", 0, 2, states_12, + "\000\050\060\200\000\000\000\240\340\223\160\220\045\200\020\000\000\206\120\076\204"}, + {269, "simple_stmt", 0, 4, states_13, + "\000\040\040\200\000\000\000\240\340\223\160\000\000\200\020\000\000\206\120\076\200"}, + {270, "small_stmt", 0, 2, states_14, + "\000\040\040\200\000\000\000\240\340\223\160\000\000\200\020\000\000\206\120\076\200"}, + {271, "expr_stmt", 0, 6, states_15, + "\000\040\040\200\000\000\000\000\000\200\000\000\000\200\020\000\000\206\120\076\000"}, + {272, "testlist_star_expr", 0, 3, states_16, + "\000\040\040\200\000\000\000\000\000\200\000\000\000\200\020\000\000\206\120\076\000"}, + {273, "augassign", 0, 2, states_17, + "\000\000\000\000\000\000\376\037\000\000\000\000\000\000\000\000\000\000\000\000\000"}, + {274, "del_stmt", 0, 3, states_18, + "\000\000\000\000\000\000\000\040\000\000\000\000\000\000\000\000\000\000\000\000\000"}, + {275, "pass_stmt", 0, 2, states_19, + "\000\000\000\000\000\000\000\200\000\000\000\000\000\000\000\000\000\000\000\000\000"}, + {276, "flow_stmt", 0, 2, states_20, + "\000\000\000\000\000\000\000\000\340\001\000\000\000\000\000\000\000\000\000\000\200"}, + {277, "break_stmt", 0, 2, states_21, + "\000\000\000\000\000\000\000\000\040\000\000\000\000\000\000\000\000\000\000\000\000"}, + {278, "continue_stmt", 0, 2, states_22, + "\000\000\000\000\000\000\000\000\100\000\000\000\000\000\000\000\000\000\000\000\000"}, + {279, "return_stmt", 0, 3, states_23, + "\000\000\000\000\000\000\000\000\200\000\000\000\000\000\000\000\000\000\000\000\000"}, + {280, "yield_stmt", 0, 2, states_24, + "\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\200"}, + {281, "raise_stmt", 0, 5, states_25, + "\000\000\000\000\000\000\000\000\000\001\000\000\000\000\000\000\000\000\000\000\000"}, + {282, "import_stmt", 0, 2, states_26, + "\000\000\000\000\000\000\000\000\000\022\000\000\000\000\000\000\000\000\000\000\000"}, + {283, "import_name", 0, 3, states_27, + "\000\000\000\000\000\000\000\000\000\020\000\000\000\000\000\000\000\000\000\000\000"}, + {284, "import_from", 0, 8, states_28, + "\000\000\000\000\000\000\000\000\000\002\000\000\000\000\000\000\000\000\000\000\000"}, + {285, "import_as_name", 0, 4, states_29, + "\000\000\040\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000"}, + {286, "dotted_as_name", 0, 4, states_30, + "\000\000\040\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000"}, + {287, "import_as_names", 0, 3, states_31, + "\000\000\040\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000"}, + {288, "dotted_as_names", 0, 2, states_32, + "\000\000\040\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000"}, + {289, "dotted_name", 0, 2, states_33, + "\000\000\040\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000"}, + {290, "global_stmt", 0, 3, states_34, + "\000\000\000\000\000\000\000\000\000\000\020\000\000\000\000\000\000\000\000\000\000"}, + {291, "nonlocal_stmt", 0, 3, states_35, + "\000\000\000\000\000\000\000\000\000\000\040\000\000\000\000\000\000\000\000\000\000"}, + {292, "assert_stmt", 0, 5, states_36, + "\000\000\000\000\000\000\000\000\000\000\100\000\000\000\000\000\000\000\000\000\000"}, + {293, "compound_stmt", 0, 2, states_37, + "\000\010\020\000\000\000\000\000\000\000\000\220\045\000\000\000\000\000\000\000\004"}, + {294, "if_stmt", 0, 8, states_38, + "\000\000\000\000\000\000\000\000\000\000\000\020\000\000\000\000\000\000\000\000\000"}, + {295, "while_stmt", 0, 8, states_39, + "\000\000\000\000\000\000\000\000\000\000\000\200\000\000\000\000\000\000\000\000\000"}, + {296, "for_stmt", 0, 10, states_40, + "\000\000\000\000\000\000\000\000\000\000\000\000\001\000\000\000\000\000\000\000\000"}, + {297, "try_stmt", 0, 13, states_41, + "\000\000\000\000\000\000\000\000\000\000\000\000\004\000\000\000\000\000\000\000\000"}, + {298, "with_stmt", 0, 5, states_42, + "\000\000\000\000\000\000\000\000\000\000\000\000\040\000\000\000\000\000\000\000\000"}, + {299, "with_item", 0, 4, states_43, + "\000\040\040\000\000\000\000\000\000\200\000\000\000\200\020\000\000\206\120\076\000"}, + {300, "except_clause", 0, 5, states_44, + "\000\000\000\000\000\000\000\000\000\000\000\000\000\001\000\000\000\000\000\000\000"}, + {301, "suite", 0, 5, states_45, + "\004\040\040\200\000\000\000\240\340\223\160\000\000\200\020\000\000\206\120\076\200"}, + {302, "test", 0, 6, states_46, + "\000\040\040\000\000\000\000\000\000\200\000\000\000\200\020\000\000\206\120\076\000"}, + {303, "test_nocond", 0, 2, states_47, + "\000\040\040\000\000\000\000\000\000\200\000\000\000\200\020\000\000\206\120\076\000"}, + {304, "lambdef", 0, 5, states_48, + "\000\000\000\000\000\000\000\000\000\000\000\000\000\200\000\000\000\000\000\000\000"}, + {305, "lambdef_nocond", 0, 5, states_49, + "\000\000\000\000\000\000\000\000\000\000\000\000\000\200\000\000\000\000\000\000\000"}, + {306, "or_test", 0, 2, states_50, + "\000\040\040\000\000\000\000\000\000\200\000\000\000\000\020\000\000\206\120\076\000"}, + {307, "and_test", 0, 2, states_51, + "\000\040\040\000\000\000\000\000\000\200\000\000\000\000\020\000\000\206\120\076\000"}, + {308, "not_test", 0, 3, states_52, + "\000\040\040\000\000\000\000\000\000\200\000\000\000\000\020\000\000\206\120\076\000"}, + {309, "comparison", 0, 2, states_53, + "\000\040\040\000\000\000\000\000\000\200\000\000\000\000\000\000\000\206\120\076\000"}, + {310, "comp_op", 0, 4, states_54, + "\000\000\000\000\000\000\000\000\000\000\000\000\002\000\220\177\000\000\000\000\000"}, + {311, "star_expr", 0, 3, states_55, + "\000\000\000\200\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000"}, + {312, "expr", 0, 2, states_56, + "\000\040\040\000\000\000\000\000\000\200\000\000\000\000\000\000\000\206\120\076\000"}, + {313, "xor_expr", 0, 2, states_57, + "\000\040\040\000\000\000\000\000\000\200\000\000\000\000\000\000\000\206\120\076\000"}, + {314, "and_expr", 0, 2, states_58, + "\000\040\040\000\000\000\000\000\000\200\000\000\000\000\000\000\000\206\120\076\000"}, + {315, "shift_expr", 0, 2, states_59, + "\000\040\040\000\000\000\000\000\000\200\000\000\000\000\000\000\000\206\120\076\000"}, + {316, "arith_expr", 0, 2, states_60, + "\000\040\040\000\000\000\000\000\000\200\000\000\000\000\000\000\000\206\120\076\000"}, + {317, "term", 0, 2, states_61, + "\000\040\040\000\000\000\000\000\000\200\000\000\000\000\000\000\000\206\120\076\000"}, + {318, "factor", 0, 3, states_62, + "\000\040\040\000\000\000\000\000\000\200\000\000\000\000\000\000\000\206\120\076\000"}, + {319, "power", 0, 4, states_63, + "\000\040\040\000\000\000\000\000\000\200\000\000\000\000\000\000\000\000\120\076\000"}, + {320, "atom", 0, 9, states_64, + "\000\040\040\000\000\000\000\000\000\200\000\000\000\000\000\000\000\000\120\076\000"}, + {321, "testlist_comp", 0, 5, states_65, + "\000\040\040\200\000\000\000\000\000\200\000\000\000\200\020\000\000\206\120\076\000"}, + {322, "trailer", 0, 7, states_66, + "\000\040\000\000\000\000\000\000\000\100\000\000\000\000\000\000\000\000\020\000\000"}, + {323, "subscriptlist", 0, 3, states_67, + "\000\040\040\002\000\000\000\000\000\200\000\000\000\200\020\000\000\206\120\076\000"}, + {324, "subscript", 0, 5, states_68, + "\000\040\040\002\000\000\000\000\000\200\000\000\000\200\020\000\000\206\120\076\000"}, + {325, "sliceop", 0, 3, states_69, + "\000\000\000\002\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000"}, + {326, "exprlist", 0, 3, states_70, + "\000\040\040\200\000\000\000\000\000\200\000\000\000\000\000\000\000\206\120\076\000"}, + {327, "testlist", 0, 3, states_71, + "\000\040\040\000\000\000\000\000\000\200\000\000\000\200\020\000\000\206\120\076\000"}, + {328, "dictorsetmaker", 0, 11, states_72, + "\000\040\040\000\000\000\000\000\000\200\000\000\000\200\020\000\000\206\120\076\000"}, + {329, "classdef", 0, 8, states_73, + "\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\004"}, + {330, "arglist", 0, 8, states_74, + "\000\040\040\200\001\000\000\000\000\200\000\000\000\200\020\000\000\206\120\076\000"}, + {331, "argument", 0, 4, states_75, + "\000\040\040\000\000\000\000\000\000\200\000\000\000\200\020\000\000\206\120\076\000"}, + {332, "comp_iter", 0, 2, states_76, + "\000\000\000\000\000\000\000\000\000\000\000\020\001\000\000\000\000\000\000\000\000"}, + {333, "comp_for", 0, 6, states_77, + "\000\000\000\000\000\000\000\000\000\000\000\000\001\000\000\000\000\000\000\000\000"}, + {334, "comp_if", 0, 4, states_78, + "\000\000\000\000\000\000\000\000\000\000\000\020\000\000\000\000\000\000\000\000\000"}, + {335, "encoding_decl", 0, 2, states_79, + "\000\000\040\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000"}, + {336, "yield_expr", 0, 3, states_80, + "\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\200"}, }; static label labels[168] = { - {0, "EMPTY"}, - {256, 0}, - {4, 0}, - {269, 0}, - {293, 0}, - {257, 0}, - {268, 0}, - {0, 0}, - {258, 0}, - {327, 0}, - {259, 0}, - {50, 0}, - {289, 0}, - {7, 0}, - {330, 0}, - {8, 0}, - {260, 0}, - {261, 0}, - {329, 0}, - {262, 0}, - {1, "def"}, - {1, 0}, - {263, 0}, - {51, 0}, - {302, 0}, - {11, 0}, - {301, 0}, - {264, 0}, - {265, 0}, - {22, 0}, - {12, 0}, - {16, 0}, - {36, 0}, - {266, 0}, - {267, 0}, - {270, 0}, - {13, 0}, - {271, 0}, - {274, 0}, - {275, 0}, - {276, 0}, - {282, 0}, - {290, 0}, - {291, 0}, - {292, 0}, - {272, 0}, - {273, 0}, - {336, 0}, - {311, 0}, - {37, 0}, - {38, 0}, - {39, 0}, - {40, 0}, - {41, 0}, - {42, 0}, - {43, 0}, - {44, 0}, - {45, 0}, - {46, 0}, - {47, 0}, - {49, 0}, - {1, "del"}, - {326, 0}, - {1, "pass"}, - {277, 0}, - {278, 0}, - {279, 0}, - {281, 0}, - {280, 0}, - {1, "break"}, - {1, "continue"}, - {1, "return"}, - {1, "raise"}, - {1, "from"}, - {283, 0}, - {284, 0}, - {1, "import"}, - {288, 0}, - {23, 0}, - {52, 0}, - {287, 0}, - {285, 0}, - {1, "as"}, - {286, 0}, - {1, "global"}, - {1, "nonlocal"}, - {1, "assert"}, - {294, 0}, - {295, 0}, - {296, 0}, - {297, 0}, - {298, 0}, - {1, "if"}, - {1, "elif"}, - {1, "else"}, - {1, "while"}, - {1, "for"}, - {1, "in"}, - {1, "try"}, - {300, 0}, - {1, "finally"}, - {1, "with"}, - {299, 0}, - {312, 0}, - {1, "except"}, - {5, 0}, - {6, 0}, - {306, 0}, - {304, 0}, - {303, 0}, - {305, 0}, - {1, "lambda"}, - {307, 0}, - {1, "or"}, - {308, 0}, - {1, "and"}, - {1, "not"}, - {309, 0}, - {310, 0}, - {20, 0}, - {21, 0}, - {28, 0}, - {31, 0}, - {30, 0}, - {29, 0}, - {29, 0}, - {1, "is"}, - {313, 0}, - {18, 0}, - {314, 0}, - {33, 0}, - {315, 0}, - {19, 0}, - {316, 0}, - {34, 0}, - {35, 0}, - {317, 0}, - {14, 0}, - {15, 0}, - {318, 0}, - {17, 0}, - {24, 0}, - {48, 0}, - {32, 0}, - {319, 0}, - {320, 0}, - {322, 0}, - {321, 0}, - {9, 0}, - {10, 0}, - {26, 0}, - {328, 0}, - {27, 0}, - {2, 0}, - {3, 0}, - {1, "None"}, - {1, "True"}, - {1, "False"}, - {333, 0}, - {323, 0}, - {324, 0}, - {325, 0}, - {1, "class"}, - {331, 0}, - {332, 0}, - {334, 0}, - {335, 0}, - {1, "yield"}, + {0, "EMPTY"}, + {256, 0}, + {4, 0}, + {269, 0}, + {293, 0}, + {257, 0}, + {268, 0}, + {0, 0}, + {258, 0}, + {327, 0}, + {259, 0}, + {50, 0}, + {289, 0}, + {7, 0}, + {330, 0}, + {8, 0}, + {260, 0}, + {261, 0}, + {329, 0}, + {262, 0}, + {1, "def"}, + {1, 0}, + {263, 0}, + {51, 0}, + {302, 0}, + {11, 0}, + {301, 0}, + {264, 0}, + {265, 0}, + {22, 0}, + {12, 0}, + {16, 0}, + {36, 0}, + {266, 0}, + {267, 0}, + {270, 0}, + {13, 0}, + {271, 0}, + {274, 0}, + {275, 0}, + {276, 0}, + {282, 0}, + {290, 0}, + {291, 0}, + {292, 0}, + {272, 0}, + {273, 0}, + {336, 0}, + {311, 0}, + {37, 0}, + {38, 0}, + {39, 0}, + {40, 0}, + {41, 0}, + {42, 0}, + {43, 0}, + {44, 0}, + {45, 0}, + {46, 0}, + {47, 0}, + {49, 0}, + {1, "del"}, + {326, 0}, + {1, "pass"}, + {277, 0}, + {278, 0}, + {279, 0}, + {281, 0}, + {280, 0}, + {1, "break"}, + {1, "continue"}, + {1, "return"}, + {1, "raise"}, + {1, "from"}, + {283, 0}, + {284, 0}, + {1, "import"}, + {288, 0}, + {23, 0}, + {52, 0}, + {287, 0}, + {285, 0}, + {1, "as"}, + {286, 0}, + {1, "global"}, + {1, "nonlocal"}, + {1, "assert"}, + {294, 0}, + {295, 0}, + {296, 0}, + {297, 0}, + {298, 0}, + {1, "if"}, + {1, "elif"}, + {1, "else"}, + {1, "while"}, + {1, "for"}, + {1, "in"}, + {1, "try"}, + {300, 0}, + {1, "finally"}, + {1, "with"}, + {299, 0}, + {312, 0}, + {1, "except"}, + {5, 0}, + {6, 0}, + {306, 0}, + {304, 0}, + {303, 0}, + {305, 0}, + {1, "lambda"}, + {307, 0}, + {1, "or"}, + {308, 0}, + {1, "and"}, + {1, "not"}, + {309, 0}, + {310, 0}, + {20, 0}, + {21, 0}, + {28, 0}, + {31, 0}, + {30, 0}, + {29, 0}, + {29, 0}, + {1, "is"}, + {313, 0}, + {18, 0}, + {314, 0}, + {33, 0}, + {315, 0}, + {19, 0}, + {316, 0}, + {34, 0}, + {35, 0}, + {317, 0}, + {14, 0}, + {15, 0}, + {318, 0}, + {17, 0}, + {24, 0}, + {48, 0}, + {32, 0}, + {319, 0}, + {320, 0}, + {322, 0}, + {321, 0}, + {9, 0}, + {10, 0}, + {26, 0}, + {328, 0}, + {27, 0}, + {2, 0}, + {3, 0}, + {1, "None"}, + {1, "True"}, + {1, "False"}, + {333, 0}, + {323, 0}, + {324, 0}, + {325, 0}, + {1, "class"}, + {331, 0}, + {332, 0}, + {334, 0}, + {335, 0}, + {1, "yield"}, }; grammar _PyParser_Grammar = { - 81, - dfas, - {168, labels}, - 256 + 81, + dfas, + {168, labels}, + 256 }; Modified: python/branches/py3k-jit/Python/import.c ============================================================================== --- python/branches/py3k-jit/Python/import.c (original) +++ python/branches/py3k-jit/Python/import.c Tue May 18 19:58:30 2010 @@ -1633,8 +1633,7 @@ if (!v) return NULL; if (PyUnicode_Check(v)) { - v = PyUnicode_AsEncodedString(v, - Py_FileSystemDefaultEncoding, NULL); + v = PyUnicode_EncodeFSDefault(v); if (v == NULL) return NULL; } @@ -2752,14 +2751,7 @@ char *subname; PyObject *submod; char *p; - if (!Py_FileSystemDefaultEncoding) { - item8 = PyUnicode_EncodeASCII(PyUnicode_AsUnicode(item), - PyUnicode_GetSize(item), - NULL); - } else { - item8 = PyUnicode_AsEncodedString(item, - Py_FileSystemDefaultEncoding, NULL); - } + item8 = PyUnicode_EncodeFSDefault(item); if (!item8) { PyErr_SetString(PyExc_ValueError, "Cannot encode path item"); return 0; Modified: python/branches/py3k-jit/Python/pythonrun.c ============================================================================== --- python/branches/py3k-jit/Python/pythonrun.c (original) +++ python/branches/py3k-jit/Python/pythonrun.c Tue May 18 19:58:30 2010 @@ -57,6 +57,7 @@ /* Forward */ static void initmain(void); +static void initfsencoding(void); static void initsite(void); static int initstdio(void); static void flush_io(void); @@ -159,7 +160,6 @@ error: Py_XDECREF(codec); - PyErr_Clear(); return NULL; } #endif @@ -171,9 +171,6 @@ PyThreadState *tstate; PyObject *bimod, *sysmod, *pstderr; char *p; -#if defined(HAVE_LANGINFO_H) && defined(CODESET) - char *codeset; -#endif extern void _Py_ReadyTypes(void); if (initialized) @@ -264,21 +261,7 @@ _PyImportHooks_Init(); -#if defined(HAVE_LANGINFO_H) && defined(CODESET) - /* On Unix, set the file system encoding according to the - user's preference, if the CODESET names a well-known - Python codec, and Py_FileSystemDefaultEncoding isn't - initialized by other means. Also set the encoding of - stdin and stdout if these are terminals. */ - - codeset = get_codeset(); - if (codeset) { - if (!Py_FileSystemDefaultEncoding) - Py_FileSystemDefaultEncoding = codeset; - else - free(codeset); - } -#endif + initfsencoding(); if (install_sigs) initsigs(); /* Signal handling stuff, including initintr() */ @@ -334,7 +317,7 @@ Py_DECREF(tmp); } - if (ferr != NULL || ferr != Py_None) { + if (ferr != NULL && ferr != Py_None) { tmp = PyObject_CallMethod(ferr, "flush", ""); if (tmp == NULL) PyErr_Clear(); @@ -497,7 +480,7 @@ _PyUnicode_Fini(); /* reset file system default encoding */ - if (!Py_HasFileSystemDefaultEncoding) { + if (!Py_HasFileSystemDefaultEncoding && Py_FileSystemDefaultEncoding) { free((char*)Py_FileSystemDefaultEncoding); Py_FileSystemDefaultEncoding = NULL; } @@ -708,6 +691,45 @@ } } +static void +initfsencoding(void) +{ + PyObject *codec; +#if defined(HAVE_LANGINFO_H) && defined(CODESET) + char *codeset; + + /* On Unix, set the file system encoding according to the + user's preference, if the CODESET names a well-known + Python codec, and Py_FileSystemDefaultEncoding isn't + initialized by other means. Also set the encoding of + stdin and stdout if these are terminals. */ + codeset = get_codeset(); + if (codeset != NULL) { + Py_FileSystemDefaultEncoding = codeset; + Py_HasFileSystemDefaultEncoding = 0; + return; + } + + PyErr_Clear(); + fprintf(stderr, + "Unable to get the locale encoding: " + "fallback to utf-8\n"); + Py_FileSystemDefaultEncoding = "utf-8"; + Py_HasFileSystemDefaultEncoding = 1; +#endif + + /* the encoding is mbcs, utf-8 or ascii */ + codec = _PyCodec_Lookup(Py_FileSystemDefaultEncoding); + if (!codec) { + /* Such error can only occurs in critical situations: no more + * memory, import a module of the standard library failed, + * etc. */ + Py_FatalError("Py_Initialize: unable to load the file system codec"); + } else { + Py_DECREF(codec); + } +} + /* Import the site module (not into __main__ though) */ static void @@ -1346,7 +1368,11 @@ if (PyLong_Check(value)) exitcode = (int)PyLong_AsLong(value); else { + PyObject *sys_stderr = PySys_GetObject("stderr"); + if (sys_stderr != NULL) + PyObject_CallMethod(sys_stderr, "flush", NULL); PyObject_Print(value, stderr, Py_PRINT_RAW); + fflush(stderr); PySys_WriteStderr("\n"); exitcode = 1; } From python-checkins at python.org Tue May 18 22:04:31 2010 From: python-checkins at python.org (giampaolo.rodola) Date: Tue, 18 May 2010 22:04:31 +0200 (CEST) Subject: [Python-checkins] r81294 - in python/trunk/Lib: asyncore.py test/test_asyncore.py Message-ID: <20100518200431.749FBEE996@mail.python.org> Author: giampaolo.rodola Date: Tue May 18 22:04:31 2010 New Revision: 81294 Log: Fix issue #8573 (asyncore._strerror bug): fixed os.strerror typo; included NameError in the tuple of expected exception; added test case for asyncore._strerror. Modified: python/trunk/Lib/asyncore.py python/trunk/Lib/test/test_asyncore.py Modified: python/trunk/Lib/asyncore.py ============================================================================== --- python/trunk/Lib/asyncore.py (original) +++ python/trunk/Lib/asyncore.py Tue May 18 22:04:31 2010 @@ -63,8 +63,8 @@ def _strerror(err): try: - return strerror(err) - except (ValueError, OverflowError): + return os.strerror(err) + except (ValueError, OverflowError, NameError): if err in errorcode: return errorcode[err] return "Unknown error %s" %err Modified: python/trunk/Lib/test/test_asyncore.py ============================================================================== --- python/trunk/Lib/test/test_asyncore.py (original) +++ python/trunk/Lib/test/test_asyncore.py Tue May 18 22:04:31 2010 @@ -6,6 +6,7 @@ import sys import time import warnings +import errno from test import test_support from test.test_support import TESTFN, run_unittest, unlink @@ -323,6 +324,14 @@ self.assertTrue(len(w) == 1) self.assertTrue(issubclass(w[0].category, DeprecationWarning)) + def test_strerror(self): + # refers to bug #8573 + err = asyncore._strerror(errno.EPERM) + if hasattr(os, 'strerror'): + self.assertEqual(err, os.strerror(errno.EPERM)) + err = asyncore._strerror(-1) + self.assertTrue("unknown error" in err.lower()) + class dispatcherwithsend_noread(asyncore.dispatcher_with_send): def readable(self): From python-checkins at python.org Tue May 18 22:04:31 2010 From: python-checkins at python.org (antoine.pitrou) Date: Tue, 18 May 2010 22:04:31 +0200 (CEST) Subject: [Python-checkins] r81295 - python/branches/sslopts-4870 Message-ID: <20100518200431.B83ABEE9B0@mail.python.org> Author: antoine.pitrou Date: Tue May 18 22:04:31 2010 New Revision: 81295 Log: A branch for issue 4870 (so that I can trigger a build on the buildbots) Added: python/branches/sslopts-4870/ - copied from r81293, /python/branches/py3k/ From python-checkins at python.org Tue May 18 22:07:04 2010 From: python-checkins at python.org (antoine.pitrou) Date: Tue, 18 May 2010 22:07:04 +0200 (CEST) Subject: [Python-checkins] r81296 - python/branches/sslopts-4870 Message-ID: <20100518200704.51323F750@mail.python.org> Author: antoine.pitrou Date: Tue May 18 22:07:04 2010 New Revision: 81296 Log: Initialized merge tracking via "svnmerge" with revisions "1-81293" from svn+ssh://pythondev at svn.python.org/python/branches/py3k Modified: python/branches/sslopts-4870/ (props changed) From python-checkins at python.org Tue May 18 22:09:08 2010 From: python-checkins at python.org (antoine.pitrou) Date: Tue, 18 May 2010 22:09:08 +0200 (CEST) Subject: [Python-checkins] r81297 - in python/branches/sslopts-4870: Doc/library/ssl.rst Lib/ssl.py Lib/test/test_ssl.py Modules/_ssl.c Message-ID: <20100518200908.0B001EE984@mail.python.org> Author: antoine.pitrou Date: Tue May 18 22:09:07 2010 New Revision: 81297 Log: Checkin the current patch for SSL options Modified: python/branches/sslopts-4870/Doc/library/ssl.rst python/branches/sslopts-4870/Lib/ssl.py python/branches/sslopts-4870/Lib/test/test_ssl.py python/branches/sslopts-4870/Modules/_ssl.c Modified: python/branches/sslopts-4870/Doc/library/ssl.rst ============================================================================== --- python/branches/sslopts-4870/Doc/library/ssl.rst (original) +++ python/branches/sslopts-4870/Doc/library/ssl.rst Tue May 18 22:09:07 2010 @@ -257,6 +257,37 @@ modern version, and probably the best choice for maximum protection, if both sides can speak it. +.. data:: OP_ALL + + Enables workarounds for various bugs present in other SSL implementations. + This option is set by default. + + .. versionadded:: 3.2 + +.. data:: OP_NO_SSLv2 + + Prevents an SSLv2 connection. This option is only applicable in + conjunction with :const:`PROTOCOL_SSLv23`. It prevents the peers from + choosing SSLv2 as the protocol version. + + .. versionadded:: 3.2 + +.. data:: OP_NO_SSLv3 + + Prevents an SSLv3 connection. This option is only applicable in + conjunction with :const:`PROTOCOL_SSLv23`. It prevents the peers from + choosing SSLv3 as the protocol version. + + .. versionadded:: 3.2 + +.. data:: OP_NO_TLSv1 + + Prevents a TLSv1 connection. This option is only applicable in + conjunction with :const:`PROTOCOL_SSLv23`. It prevents the peers from + choosing TLSv1 as the protocol version. + + .. versionadded:: 3.2 + .. data:: OPENSSL_VERSION The version string of the OpenSSL library loaded by the interpreter:: @@ -440,6 +471,17 @@ and *suppress_ragged_eofs* have the same meaning as in the top-level :func:`wrap_socket` function. +.. attribute:: SSLContext.options + + An integer representing the set of SSL options enabled on this context. + The default value is :data:`OP_ALL`, but you can specify other options + such as :data:`OP_NO_SSLv2` by ORing them together. + + .. note:: + With versions of OpenSSL older than 0.9.8m, it is only possible + to set options, not to clear them. Attempting to clear an option + (by resetting the corresponding bits) will raise a ``ValueError``. + .. attribute:: SSLContext.protocol The protocol version chosen when constructing the context. This attribute @@ -794,6 +836,20 @@ equivalent unless anonymous ciphers are enabled (they are disabled by default). +Protocol versions +^^^^^^^^^^^^^^^^^ + +SSL version 2 is considered insecure and is therefore dangerous to use. If +you want maximum compatibility between clients and servers, it is recommended +to use :const:`PROTOCOL_SSLv23` as the protocol version and then disable +SSLv2 explicitly using the :data:`SSLContext.options` attribute:: + + context = ssl.SSLContext(ssl.PROTOCOL_SSLv23) + context.options |= ssl.OP_NO_SSLv2 + +The SSL context created above will allow SSLv3 and TLSv1 connections, but +not SSLv2. + .. seealso:: Modified: python/branches/sslopts-4870/Lib/ssl.py ============================================================================== --- python/branches/sslopts-4870/Lib/ssl.py (original) +++ python/branches/sslopts-4870/Lib/ssl.py Tue May 18 22:09:07 2010 @@ -63,6 +63,7 @@ from _ssl import CERT_NONE, CERT_OPTIONAL, CERT_REQUIRED from _ssl import (PROTOCOL_SSLv2, PROTOCOL_SSLv3, PROTOCOL_SSLv23, PROTOCOL_TLSv1) +from _ssl import OP_ALL, OP_NO_SSLv2, OP_NO_SSLv3, OP_NO_TLSv1 from _ssl import RAND_status, RAND_egd, RAND_add from _ssl import ( SSL_ERROR_ZERO_RETURN, Modified: python/branches/sslopts-4870/Lib/test/test_ssl.py ============================================================================== --- python/branches/sslopts-4870/Lib/test/test_ssl.py (original) +++ python/branches/sslopts-4870/Lib/test/test_ssl.py Tue May 18 22:09:07 2010 @@ -57,6 +57,10 @@ if support.verbose: sys.stdout.write(prefix + exc_format) +def can_clear_options(): + # 0.9.8m or higher + return ssl.OPENSSL_VERSION_INFO >= (0, 9, 8, 13, 15) + class BasicSocketTests(unittest.TestCase): @@ -189,6 +193,26 @@ with self.assertRaisesRegexp(ssl.SSLError, "No cipher can be selected"): ctx.set_ciphers("^$:,;?*'dorothyx") + def test_options(self): + ctx = ssl.SSLContext(ssl.PROTOCOL_TLSv1) + # OP_ALL is the default value + self.assertEqual(ssl.OP_ALL, ctx.options) + ctx.options |= ssl.OP_NO_SSLv2 + self.assertEqual(ssl.OP_ALL | ssl.OP_NO_SSLv2, + ctx.options) + ctx.options |= ssl.OP_NO_SSLv3 + self.assertEqual(ssl.OP_ALL | ssl.OP_NO_SSLv2 | ssl.OP_NO_SSLv3, + ctx.options) + if can_clear_options(): + ctx.options = (ctx.options & ~ssl.OP_NO_SSLv2) | ssl.OP_NO_TLSv1 + self.assertEqual(ssl.OP_ALL | ssl.OP_NO_TLSv1 | ssl.OP_NO_SSLv3, + ctx.options) + ctx.options = 0 + self.assertEqual(0, ctx.options) + else: + with self.assertRaises(ValueError): + ctx.options = 0 + def test_verify(self): ctx = ssl.SSLContext(ssl.PROTOCOL_TLSv1) # Default value @@ -445,12 +469,8 @@ def wrap_conn(self): try: - self.sslconn = ssl.wrap_socket(self.sock, server_side=True, - certfile=self.server.certificate, - ssl_version=self.server.protocol, - ca_certs=self.server.cacerts, - cert_reqs=self.server.certreqs, - ciphers=self.server.ciphers) + self.sslconn = self.server.context.wrap_socket( + self.sock, server_side=True) except ssl.SSLError: # XXX Various errors can have happened here, for example # a mismatching protocol version, an invalid certificate, @@ -462,7 +482,7 @@ self.close() return False else: - if self.server.certreqs == ssl.CERT_REQUIRED: + if self.server.context.verify_mode == ssl.CERT_REQUIRED: cert = self.sslconn.getpeercert() if support.verbose and self.server.chatty: sys.stdout.write(" client cert is " + pprint.pformat(cert) + "\n") @@ -542,19 +562,24 @@ # harness, we want to stop the server self.server.stop() - def __init__(self, certificate, ssl_version=None, + def __init__(self, certificate=None, ssl_version=None, certreqs=None, cacerts=None, chatty=True, connectionchatty=False, starttls_server=False, - ciphers=None): - if ssl_version is None: - ssl_version = ssl.PROTOCOL_TLSv1 - if certreqs is None: - certreqs = ssl.CERT_NONE - self.certificate = certificate - self.protocol = ssl_version - self.certreqs = certreqs - self.cacerts = cacerts - self.ciphers = ciphers + ciphers=None, context=None): + if context: + self.context = context + else: + self.context = ssl.SSLContext(ssl_version + if ssl_version is not None + else ssl.PROTOCOL_TLSv1) + self.context.verify_mode = (certreqs if certreqs is not None + else ssl.CERT_NONE) + if cacerts: + self.context.load_verify_locations(cacerts) + if certificate: + self.context.load_cert_chain(certificate) + if ciphers: + self.context.set_ciphers(ciphers) self.chatty = chatty self.connectionchatty = connectionchatty self.starttls_server = starttls_server @@ -820,18 +845,13 @@ server.stop() server.join() - def server_params_test(certfile, protocol, certreqs, cacertsfile, - client_certfile, client_protocol=None, indata=b"FOO\n", - ciphers=None, chatty=True, connectionchatty=False): + def server_params_test(client_context, server_context, indata=b"FOO\n", + chatty=True, connectionchatty=False): """ Launch a server, connect a client to it and try various reads and writes. """ - server = ThreadedEchoServer(certfile, - certreqs=certreqs, - ssl_version=protocol, - cacerts=cacertsfile, - ciphers=ciphers, + server = ThreadedEchoServer(context=server_context, chatty=chatty, connectionchatty=False) flag = threading.Event() @@ -839,15 +859,8 @@ # wait for it to start flag.wait() # try to connect - if client_protocol is None: - client_protocol = protocol try: - s = ssl.wrap_socket(socket.socket(), - certfile=client_certfile, - ca_certs=cacertsfile, - ciphers=ciphers, - cert_reqs=certreqs, - ssl_version=client_protocol) + s = client_context.wrap_socket(socket.socket()) s.connect((HOST, server.port)) for arg in [indata, bytearray(indata), memoryview(indata)]: if connectionchatty: @@ -873,10 +886,8 @@ server.stop() server.join() - def try_protocol_combo(server_protocol, - client_protocol, - expect_success, - certsreqs=None): + def try_protocol_combo(server_protocol, client_protocol, expect_success, + certsreqs=None, server_options=0, client_options=0): if certsreqs is None: certsreqs = ssl.CERT_NONE certtype = { @@ -890,14 +901,21 @@ (ssl.get_protocol_name(client_protocol), ssl.get_protocol_name(server_protocol), certtype)) - try: + client_context = ssl.SSLContext(client_protocol) + client_context.options = ssl.OP_ALL | client_options + server_context = ssl.SSLContext(server_protocol) + server_context.options = ssl.OP_ALL | server_options + for ctx in (client_context, server_context): + ctx.verify_mode = certsreqs # NOTE: we must enable "ALL" ciphers, otherwise an SSLv23 client # will send an SSLv3 hello (rather than SSLv2) starting from # OpenSSL 1.0.0 (see issue #8322). - server_params_test(CERTFILE, server_protocol, certsreqs, - CERTFILE, CERTFILE, client_protocol, - ciphers="ALL", chatty=False, - connectionchatty=False) + ctx.set_ciphers("ALL") + ctx.load_cert_chain(CERTFILE) + ctx.load_verify_locations(CERTFILE) + try: + server_params_test(client_context, server_context, + chatty=False, connectionchatty=False) # Protocol mismatch can result in either an SSLError, or a # "Connection reset by peer" error. except ssl.SSLError: @@ -920,30 +938,27 @@ """Basic test of an SSL client connecting to a server""" if support.verbose: sys.stdout.write("\n") - server_params_test(CERTFILE, ssl.PROTOCOL_TLSv1, ssl.CERT_NONE, - CERTFILE, CERTFILE, ssl.PROTOCOL_TLSv1, - chatty=True, connectionchatty=True) + for protocol in PROTOCOLS: + context = ssl.SSLContext(protocol) + context.load_cert_chain(CERTFILE) + server_params_test(context, context, + chatty=True, connectionchatty=True) def test_getpeercert(self): if support.verbose: sys.stdout.write("\n") - s2 = socket.socket() - server = ThreadedEchoServer(CERTFILE, - certreqs=ssl.CERT_NONE, - ssl_version=ssl.PROTOCOL_SSLv23, - cacerts=CERTFILE, - chatty=False) + context = ssl.SSLContext(ssl.PROTOCOL_SSLv23) + context.verify_mode = ssl.CERT_REQUIRED + context.load_verify_locations(CERTFILE) + context.load_cert_chain(CERTFILE) + server = ThreadedEchoServer(context=context, chatty=False) flag = threading.Event() server.start(flag) # wait for it to start flag.wait() # try to connect try: - s = ssl.wrap_socket(socket.socket(), - certfile=CERTFILE, - ca_certs=CERTFILE, - cert_reqs=ssl.CERT_REQUIRED, - ssl_version=ssl.PROTOCOL_SSLv23) + s = context.wrap_socket(socket.socket()) s.connect((HOST, server.port)) cert = s.getpeercert() self.assertTrue(cert, "Can't get peer certificate.") @@ -1031,6 +1046,13 @@ try_protocol_combo(ssl.PROTOCOL_SSLv2, ssl.PROTOCOL_SSLv23, True) try_protocol_combo(ssl.PROTOCOL_SSLv2, ssl.PROTOCOL_SSLv3, False) try_protocol_combo(ssl.PROTOCOL_SSLv2, ssl.PROTOCOL_TLSv1, False) + # SSLv23 client with specific SSL options + try_protocol_combo(ssl.PROTOCOL_SSLv2, ssl.PROTOCOL_SSLv23, False, + client_options=ssl.OP_NO_SSLv2) + try_protocol_combo(ssl.PROTOCOL_SSLv2, ssl.PROTOCOL_SSLv23, True, + client_options=ssl.OP_NO_SSLv3) + try_protocol_combo(ssl.PROTOCOL_SSLv2, ssl.PROTOCOL_SSLv23, True, + client_options=ssl.OP_NO_TLSv1) def test_protocol_sslv23(self): """Connecting to an SSLv23 server with various client options""" @@ -1056,6 +1078,16 @@ try_protocol_combo(ssl.PROTOCOL_SSLv23, ssl.PROTOCOL_SSLv23, True, ssl.CERT_REQUIRED) try_protocol_combo(ssl.PROTOCOL_SSLv23, ssl.PROTOCOL_TLSv1, True, ssl.CERT_REQUIRED) + # Server with specific SSL options + try_protocol_combo(ssl.PROTOCOL_SSLv23, ssl.PROTOCOL_SSLv3, False, + server_options=ssl.OP_NO_SSLv3) + # Will choose TLSv1 + try_protocol_combo(ssl.PROTOCOL_SSLv23, ssl.PROTOCOL_SSLv23, True, + server_options=ssl.OP_NO_SSLv2 | ssl.OP_NO_SSLv3) + try_protocol_combo(ssl.PROTOCOL_SSLv23, ssl.PROTOCOL_TLSv1, False, + server_options=ssl.OP_NO_TLSv1) + + def test_protocol_sslv3(self): """Connecting to an SSLv3 server with various client options""" if support.verbose: @@ -1066,6 +1098,9 @@ try_protocol_combo(ssl.PROTOCOL_SSLv3, ssl.PROTOCOL_SSLv2, False) try_protocol_combo(ssl.PROTOCOL_SSLv3, ssl.PROTOCOL_SSLv23, False) try_protocol_combo(ssl.PROTOCOL_SSLv3, ssl.PROTOCOL_TLSv1, False) + # No SSLv2 => client will use an SSLv3 hello + try_protocol_combo(ssl.PROTOCOL_SSLv3, ssl.PROTOCOL_SSLv23, True, + client_options=ssl.OP_NO_SSLv2) def test_protocol_tlsv1(self): """Connecting to a TLSv1 server with various client options""" Modified: python/branches/sslopts-4870/Modules/_ssl.c ============================================================================== --- python/branches/sslopts-4870/Modules/_ssl.c (original) +++ python/branches/sslopts-4870/Modules/_ssl.c Tue May 18 22:09:07 2010 @@ -113,6 +113,13 @@ # undef HAVE_OPENSSL_RAND #endif +/* SSL_CTX_clear_options() and SSL_clear_options() were first added in OpenSSL 0.9.8m */ +#if OPENSSL_VERSION_NUMBER >= 0x009080dfL +# define HAVE_SSL_CTX_CLEAR_OPTIONS +#else +# undef HAVE_SSL_CTX_CLEAR_OPTIONS +#endif + typedef struct { PyObject_HEAD SSL_CTX *ctx; @@ -1514,6 +1521,35 @@ } static PyObject * +get_options(PySSLContext *self, void *c) +{ + return PyLong_FromLong(SSL_CTX_get_options(self->ctx)); +} + +static int +set_options(PySSLContext *self, PyObject *arg, void *c) +{ + long new_opts, opts, set, clear; + if (!PyArg_Parse(arg, "l", &new_opts)) + return -1; + opts = SSL_CTX_get_options(self->ctx); + clear = opts & ~new_opts; + set = ~opts & new_opts; + if (clear) { +#ifdef HAVE_SSL_CTX_CLEAR_OPTIONS + SSL_CTX_clear_options(self->ctx, clear); +#else + PyErr_SetString(PyExc_ValueError, + "can't clear options before OpenSSL 0.9.8m"); + return -1; +#endif + } + if (set) + SSL_CTX_set_options(self->ctx, set); + return 0; +} + +static PyObject * load_cert_chain(PySSLContext *self, PyObject *args, PyObject *kwds) { char *kwlist[] = {"certfile", "keyfile", NULL}; @@ -1636,6 +1672,8 @@ } static PyGetSetDef context_getsetlist[] = { + {"options", (getter) get_options, + (setter) set_options, NULL}, {"verify_mode", (getter) get_verify_mode, (setter) set_verify_mode, NULL}, {NULL}, /* sentinel */ @@ -1953,6 +1991,12 @@ PyModule_AddIntConstant(m, "PROTOCOL_TLSv1", PY_SSL_VERSION_TLS1); + /* protocol options */ + PyModule_AddIntConstant(m, "OP_ALL", SSL_OP_ALL); + PyModule_AddIntConstant(m, "OP_NO_SSLv2", SSL_OP_NO_SSLv2); + PyModule_AddIntConstant(m, "OP_NO_SSLv3", SSL_OP_NO_SSLv3); + PyModule_AddIntConstant(m, "OP_NO_TLSv1", SSL_OP_NO_TLSv1); + /* OpenSSL version */ /* SSLeay() gives us the version of the library linked against, which could be different from the headers version. From python-checkins at python.org Tue May 18 22:09:25 2010 From: python-checkins at python.org (giampaolo.rodola) Date: Tue, 18 May 2010 22:09:25 +0200 (CEST) Subject: [Python-checkins] r81298 - in python/branches/release26-maint: Lib/asyncore.py Lib/test/test_asyncore.py Message-ID: <20100518200925.A1A71EE993@mail.python.org> Author: giampaolo.rodola Date: Tue May 18 22:09:25 2010 New Revision: 81298 Log: Merged revisions 81294 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r81294 | giampaolo.rodola | 2010-05-18 22:04:31 +0200 (mar, 18 mag 2010) | 1 line Fix issue #8573 (asyncore._strerror bug): fixed os.strerror typo; included NameError in the tuple of expected exception; added test case for asyncore._strerror. ........ Modified: python/branches/release26-maint/ (props changed) python/branches/release26-maint/Lib/asyncore.py python/branches/release26-maint/Lib/test/test_asyncore.py Modified: python/branches/release26-maint/Lib/asyncore.py ============================================================================== --- python/branches/release26-maint/Lib/asyncore.py (original) +++ python/branches/release26-maint/Lib/asyncore.py Tue May 18 22:09:25 2010 @@ -62,8 +62,8 @@ def _strerror(err): try: - return strerror(err) - except (ValueError, OverflowError): + return os.strerror(err) + except (ValueError, OverflowError, NameError): if err in errorcode: return errorcode[err] return "Unknown error %s" %err Modified: python/branches/release26-maint/Lib/test/test_asyncore.py ============================================================================== --- python/branches/release26-maint/Lib/test/test_asyncore.py (original) +++ python/branches/release26-maint/Lib/test/test_asyncore.py Tue May 18 22:09:25 2010 @@ -6,6 +6,7 @@ import threading import sys import time +import errno from test import test_support from test.test_support import TESTFN, run_unittest, unlink @@ -314,6 +315,14 @@ # test cheap inheritance with the underlying socket self.assertEqual(d.family, socket.AF_INET) + def test_strerror(self): + # refers to bug #8573 + err = asyncore._strerror(errno.EPERM) + if hasattr(os, 'strerror'): + self.assertEqual(err, os.strerror(errno.EPERM)) + err = asyncore._strerror(-1) + self.assertTrue("unknown error" in err.lower()) + class dispatcherwithsend_noread(asyncore.dispatcher_with_send): def readable(self): From python-checkins at python.org Tue May 18 22:11:58 2010 From: python-checkins at python.org (giampaolo.rodola) Date: Tue, 18 May 2010 22:11:58 +0200 (CEST) Subject: [Python-checkins] r81299 - in python/branches/py3k: Lib/asyncore.py Lib/test/test_asyncore.py Message-ID: <20100518201158.9E9B8EE984@mail.python.org> Author: giampaolo.rodola Date: Tue May 18 22:11:58 2010 New Revision: 81299 Log: Merged revisions 81294 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r81294 | giampaolo.rodola | 2010-05-18 22:04:31 +0200 (mar, 18 mag 2010) | 1 line Fix issue #8573 (asyncore._strerror bug): fixed os.strerror typo; included NameError in the tuple of expected exception; added test case for asyncore._strerror. ........ Modified: python/branches/py3k/ (props changed) python/branches/py3k/Lib/asyncore.py python/branches/py3k/Lib/test/test_asyncore.py Modified: python/branches/py3k/Lib/asyncore.py ============================================================================== --- python/branches/py3k/Lib/asyncore.py (original) +++ python/branches/py3k/Lib/asyncore.py Tue May 18 22:11:58 2010 @@ -63,8 +63,8 @@ def _strerror(err): try: - return strerror(err) - except (ValueError, OverflowError): + return os.strerror(err) + except (ValueError, OverflowError, NameError): if err in errorcode: return errorcode[err] return "Unknown error %s" %err Modified: python/branches/py3k/Lib/test/test_asyncore.py ============================================================================== --- python/branches/py3k/Lib/test/test_asyncore.py (original) +++ python/branches/py3k/Lib/test/test_asyncore.py Tue May 18 22:11:58 2010 @@ -6,6 +6,7 @@ import sys import time import warnings +import errno from test import support from test.support import TESTFN, run_unittest, unlink @@ -324,6 +325,14 @@ self.assertTrue(len(w) == 1) self.assertTrue(issubclass(w[0].category, DeprecationWarning)) + def test_strerror(self): + # refers to bug #8573 + err = asyncore._strerror(errno.EPERM) + if hasattr(os, 'strerror'): + self.assertEqual(err, os.strerror(errno.EPERM)) + err = asyncore._strerror(-1) + self.assertTrue("unknown error" in err.lower()) + class dispatcherwithsend_noread(asyncore.dispatcher_with_send): def readable(self): From python-checkins at python.org Tue May 18 22:13:43 2010 From: python-checkins at python.org (giampaolo.rodola) Date: Tue, 18 May 2010 22:13:43 +0200 (CEST) Subject: [Python-checkins] r81300 - in python/branches/release31-maint: Lib/asyncore.py Lib/test/test_asyncore.py Message-ID: <20100518201343.40616EE984@mail.python.org> Author: giampaolo.rodola Date: Tue May 18 22:13:43 2010 New Revision: 81300 Log: Merged revisions 81299 via svnmerge from svn+ssh://pythondev at svn.python.org/python/branches/py3k ................ r81299 | giampaolo.rodola | 2010-05-18 22:11:58 +0200 (mar, 18 mag 2010) | 9 lines Merged revisions 81294 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r81294 | giampaolo.rodola | 2010-05-18 22:04:31 +0200 (mar, 18 mag 2010) | 1 line Fix issue #8573 (asyncore._strerror bug): fixed os.strerror typo; included NameError in the tuple of expected exception; added test case for asyncore._strerror. ........ ................ Modified: python/branches/release31-maint/ (props changed) python/branches/release31-maint/Lib/asyncore.py python/branches/release31-maint/Lib/test/test_asyncore.py Modified: python/branches/release31-maint/Lib/asyncore.py ============================================================================== --- python/branches/release31-maint/Lib/asyncore.py (original) +++ python/branches/release31-maint/Lib/asyncore.py Tue May 18 22:13:43 2010 @@ -61,8 +61,8 @@ def _strerror(err): try: - return strerror(err) - except (ValueError, OverflowError): + return os.strerror(err) + except (ValueError, OverflowError, NameError): if err in errorcode: return errorcode[err] return "Unknown error %s" %err Modified: python/branches/release31-maint/Lib/test/test_asyncore.py ============================================================================== --- python/branches/release31-maint/Lib/test/test_asyncore.py (original) +++ python/branches/release31-maint/Lib/test/test_asyncore.py Tue May 18 22:13:43 2010 @@ -6,6 +6,7 @@ import threading import sys import time +import errno from test import support from test.support import TESTFN, run_unittest, unlink @@ -315,6 +316,14 @@ # test cheap inheritance with the underlying socket self.assertEqual(d.family, socket.AF_INET) + def test_strerror(self): + # refers to bug #8573 + err = asyncore._strerror(errno.EPERM) + if hasattr(os, 'strerror'): + self.assertEqual(err, os.strerror(errno.EPERM)) + err = asyncore._strerror(-1) + self.assertTrue("unknown error" in err.lower()) + class dispatcherwithsend_noread(asyncore.dispatcher_with_send): def readable(self): From python-checkins at python.org Wed May 19 01:04:56 2010 From: python-checkins at python.org (antoine.pitrou) Date: Wed, 19 May 2010 01:04:56 +0200 (CEST) Subject: [Python-checkins] r81301 - python/branches/sslopts-4870/Lib/test/test_ssl.py Message-ID: <20100518230456.8E502EE994@mail.python.org> Author: antoine.pitrou Date: Wed May 19 01:04:56 2010 New Revision: 81301 Log: Fix tests on OpenSSL < 0.9.7h Modified: python/branches/sslopts-4870/Lib/test/test_ssl.py Modified: python/branches/sslopts-4870/Lib/test/test_ssl.py ============================================================================== --- python/branches/sslopts-4870/Lib/test/test_ssl.py (original) +++ python/branches/sslopts-4870/Lib/test/test_ssl.py Wed May 19 01:04:56 2010 @@ -61,6 +61,10 @@ # 0.9.8m or higher return ssl.OPENSSL_VERSION_INFO >= (0, 9, 8, 13, 15) +def no_sslv2_implies_sslv3_hello(): + # 0.9.7h or higher + return ssl.OPENSSL_VERSION_INFO >= (0, 9, 7, 8, 15) + class BasicSocketTests(unittest.TestCase): @@ -1047,8 +1051,10 @@ try_protocol_combo(ssl.PROTOCOL_SSLv2, ssl.PROTOCOL_SSLv3, False) try_protocol_combo(ssl.PROTOCOL_SSLv2, ssl.PROTOCOL_TLSv1, False) # SSLv23 client with specific SSL options - try_protocol_combo(ssl.PROTOCOL_SSLv2, ssl.PROTOCOL_SSLv23, False, - client_options=ssl.OP_NO_SSLv2) + if no_sslv2_implies_sslv3_hello(): + # No SSLv2 => client will use an SSLv3 hello on recent OpenSSLs + try_protocol_combo(ssl.PROTOCOL_SSLv2, ssl.PROTOCOL_SSLv23, False, + client_options=ssl.OP_NO_SSLv2) try_protocol_combo(ssl.PROTOCOL_SSLv2, ssl.PROTOCOL_SSLv23, True, client_options=ssl.OP_NO_SSLv3) try_protocol_combo(ssl.PROTOCOL_SSLv2, ssl.PROTOCOL_SSLv23, True, @@ -1098,9 +1104,10 @@ try_protocol_combo(ssl.PROTOCOL_SSLv3, ssl.PROTOCOL_SSLv2, False) try_protocol_combo(ssl.PROTOCOL_SSLv3, ssl.PROTOCOL_SSLv23, False) try_protocol_combo(ssl.PROTOCOL_SSLv3, ssl.PROTOCOL_TLSv1, False) - # No SSLv2 => client will use an SSLv3 hello - try_protocol_combo(ssl.PROTOCOL_SSLv3, ssl.PROTOCOL_SSLv23, True, - client_options=ssl.OP_NO_SSLv2) + if no_sslv2_implies_sslv3_hello(): + # No SSLv2 => client will use an SSLv3 hello on recent OpenSSLs + try_protocol_combo(ssl.PROTOCOL_SSLv3, ssl.PROTOCOL_SSLv23, True, + client_options=ssl.OP_NO_SSLv2) def test_protocol_tlsv1(self): """Connecting to a TLSv1 server with various client options""" From python-checkins at python.org Wed May 19 01:13:04 2010 From: python-checkins at python.org (georg.brandl) Date: Wed, 19 May 2010 01:13:04 +0200 (CEST) Subject: [Python-checkins] r81302 - in python/branches/release26-maint: Doc/c-api/import.rst Doc/data/refcounts.dat Doc/glossary.rst Doc/library/os.rst Message-ID: <20100518231304.C2190EE9D8@mail.python.org> Author: georg.brandl Date: Wed May 19 01:13:04 2010 New Revision: 81302 Log: Merged revisions 79579-79580,79585-79587 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r79579 | georg.brandl | 2010-04-02 08:34:41 +0000 (Fr, 02 Apr 2010) | 1 line Add 2.6.5. ........ r79580 | georg.brandl | 2010-04-02 08:39:09 +0000 (Fr, 02 Apr 2010) | 1 line #2768: add a note on how to get a file descriptor. ........ r79585 | georg.brandl | 2010-04-02 09:03:18 +0000 (Fr, 02 Apr 2010) | 1 line Remove col-spanning cells in logging docs. ........ r79586 | georg.brandl | 2010-04-02 09:07:42 +0000 (Fr, 02 Apr 2010) | 1 line Document PyImport_ExecCodeModuleEx(). ........ r79587 | georg.brandl | 2010-04-02 09:11:49 +0000 (Fr, 02 Apr 2010) | 1 line #8012: clarification in generator glossary entry. ........ Modified: python/branches/release26-maint/ (props changed) python/branches/release26-maint/Doc/c-api/import.rst python/branches/release26-maint/Doc/data/refcounts.dat python/branches/release26-maint/Doc/glossary.rst python/branches/release26-maint/Doc/library/os.rst Modified: python/branches/release26-maint/Doc/c-api/import.rst ============================================================================== --- python/branches/release26-maint/Doc/c-api/import.rst (original) +++ python/branches/release26-maint/Doc/c-api/import.rst Wed May 19 01:13:04 2010 @@ -138,6 +138,9 @@ such modules have no way to know that the module object is an unknown (and probably damaged with respect to the module author's intents) state. + The module's :attr:`__file__` attribute will be set to the code object's + :cmember:`co_filename`. + This function will reload the module if it was already imported. See :cfunc:`PyImport_ReloadModule` for the intended way to reload a module. @@ -148,6 +151,12 @@ *name* is removed from :attr:`sys.modules` in error cases. +.. cfunction:: PyObject* PyImport_ExecCodeModuleEx(char *name, PyObject *co, char *pathname) + + Like :cfunc:`PyImport_ExecCodeModule`, but the :attr:`__file__` attribute of + the module object is set to *pathname* if it is non-``NULL``. + + .. cfunction:: long PyImport_GetMagicNumber() Return the magic number for Python bytecode files (a.k.a. :file:`.pyc` and Modified: python/branches/release26-maint/Doc/data/refcounts.dat ============================================================================== --- python/branches/release26-maint/Doc/data/refcounts.dat (original) +++ python/branches/release26-maint/Doc/data/refcounts.dat Wed May 19 01:13:04 2010 @@ -450,6 +450,11 @@ PyImport_ExecCodeModule:char*:name:: PyImport_ExecCodeModule:PyObject*:co:0: +PyImport_ExecCodeModuleEx:PyObject*::+1: +PyImport_ExecCodeModuleEx:char*:name:: +PyImport_ExecCodeModuleEx:PyObject*:co:0: +PyImport_ExecCodeModuleEx:char*:pathname:: + PyImport_GetMagicNumber:long::: PyImport_GetModuleDict:PyObject*::0: @@ -469,6 +474,13 @@ PyImport_ImportModuleEx:PyObject*:locals:0:??? PyImport_ImportModuleEx:PyObject*:fromlist:0:??? +PyImport_ImportModuleLevel:PyObject*::+1: +PyImport_ImportModuleLevel:char*:name:: +PyImport_ImportModuleLevel:PyObject*:globals:0:??? +PyImport_ImportModuleLevel:PyObject*:locals:0:??? +PyImport_ImportModuleLevel:PyObject*:fromlist:0:??? +PyImport_ImportModuleLevel:int:level:: + PyImport_ReloadModule:PyObject*::+1: PyImport_ReloadModule:PyObject*:m:0: Modified: python/branches/release26-maint/Doc/glossary.rst ============================================================================== --- python/branches/release26-maint/Doc/glossary.rst (original) +++ python/branches/release26-maint/Doc/glossary.rst Wed May 19 01:13:04 2010 @@ -217,6 +217,8 @@ performs garbage collection via reference counting and a cyclic garbage collector that is able to detect and break reference cycles. + .. index:: single: generator + generator A function which returns an iterator. It looks like a normal function except that values are returned to the caller using a :keyword:`yield` @@ -230,7 +232,7 @@ .. index:: single: generator expression generator expression - An expression that returns a generator. It looks like a normal expression + An expression that returns an iterator. It looks like a normal expression followed by a :keyword:`for` expression defining a loop variable, range, and an optional :keyword:`if` expression. The combined expression generates values for an enclosing function:: Modified: python/branches/release26-maint/Doc/library/os.rst ============================================================================== --- python/branches/release26-maint/Doc/library/os.rst (original) +++ python/branches/release26-maint/Doc/library/os.rst Wed May 19 01:13:04 2010 @@ -525,6 +525,10 @@ is slightly deceptive; on Unix platforms, sockets and pipes are also referenced by file descriptors. +The :meth:`~file.fileno` method can be used to obtain the file descriptor +associated with a file object when required. Note that using the file +descriptor directly will bypass the file object methods, ignoring aspects such +as internal buffering of data. .. function:: close(fd) From python-checkins at python.org Wed May 19 01:19:34 2010 From: python-checkins at python.org (georg.brandl) Date: Wed, 19 May 2010 01:19:34 +0200 (CEST) Subject: [Python-checkins] r81303 - in python/branches/release26-maint: Doc/library/os.rst Doc/library/socket.rst Doc/reference/datamodel.rst Lib/pipes.py Lib/test/test_pipes.py Misc/NEWS Misc/developers.txt Message-ID: <20100518231934.61EF8EE994@mail.python.org> Author: georg.brandl Date: Wed May 19 01:19:34 2010 New Revision: 81303 Log: Merged revisions 79822,79828,79862,80067,80069,80080-80081,80084,80432-80433 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r79822 | georg.brandl | 2010-04-06 08:18:15 +0000 (Di, 06 Apr 2010) | 1 line #8320: document return value of recv_into(). ........ r79828 | georg.brandl | 2010-04-06 14:33:44 +0000 (Di, 06 Apr 2010) | 1 line Add JP. ........ r79862 | georg.brandl | 2010-04-06 20:27:59 +0000 (Di, 06 Apr 2010) | 1 line Fix syntax. ........ r80067 | georg.brandl | 2010-04-14 08:53:38 +0000 (Mi, 14 Apr 2010) | 1 line #5341: typo. ........ r80069 | georg.brandl | 2010-04-14 13:50:31 +0000 (Mi, 14 Apr 2010) | 1 line Add an x-ref to where the O_ constants are documented and move the SEEK_ constants after lseek(). ........ r80080 | georg.brandl | 2010-04-14 19:16:38 +0000 (Mi, 14 Apr 2010) | 1 line #8399: add note about Windows and O_BINARY. ........ r80081 | georg.brandl | 2010-04-14 21:34:44 +0000 (Mi, 14 Apr 2010) | 1 line #5250: document __instancecheck__ and __subclasscheck__. I hope the part about the class/metaclass distinction is understandable. ........ r80084 | georg.brandl | 2010-04-14 21:46:45 +0000 (Mi, 14 Apr 2010) | 1 line Fix missing. ........ r80432 | georg.brandl | 2010-04-24 08:56:58 +0000 (Sa, 24 Apr 2010) | 1 line Markup fixes. ........ r80433 | georg.brandl | 2010-04-24 09:08:10 +0000 (Sa, 24 Apr 2010) | 1 line #7507: quote "!" in pipes.quote(); it is a special character for some shells. ........ Modified: python/branches/release26-maint/ (props changed) python/branches/release26-maint/Doc/library/os.rst python/branches/release26-maint/Doc/library/socket.rst python/branches/release26-maint/Doc/reference/datamodel.rst python/branches/release26-maint/Lib/pipes.py python/branches/release26-maint/Lib/test/test_pipes.py python/branches/release26-maint/Misc/NEWS python/branches/release26-maint/Misc/developers.txt Modified: python/branches/release26-maint/Doc/library/os.rst ============================================================================== --- python/branches/release26-maint/Doc/library/os.rst (original) +++ python/branches/release26-maint/Doc/library/os.rst Wed May 19 01:19:34 2010 @@ -677,6 +677,16 @@ Availability: Unix, Windows. +.. data:: SEEK_SET + SEEK_CUR + SEEK_END + + Parameters to the :func:`lseek` function. Their values are 0, 1, and 2, + respectively. Availability: Windows, Unix. + + .. versionadded:: 2.5 + + .. function:: open(file, flags[, mode]) Open the file *file* and set various flags according to *flags* and possibly its @@ -686,7 +696,8 @@ For a description of the flag and mode values, see the C run-time documentation; flag constants (like :const:`O_RDONLY` and :const:`O_WRONLY`) are defined in - this module too (see below). + this module too (see :ref:`open-constants`). In particular, on Windows adding + :const:`O_BINARY` is needed to open files in binary mode. Availability: Unix, Windows. @@ -774,6 +785,12 @@ :func:`fdopen`, or :data:`sys.stdout` or :data:`sys.stderr`, use its :meth:`~file.write` method. + +.. _open-constants: + +``open()`` flag constants +~~~~~~~~~~~~~~~~~~~~~~~~~ + The following constants are options for the *flags* parameter to the :func:`~os.open` function. They can be combined using the bitwise OR operator ``|``. Some of them are not available on all platforms. For descriptions of @@ -825,16 +842,6 @@ the C library. -.. data:: SEEK_SET - SEEK_CUR - SEEK_END - - Parameters to the :func:`lseek` function. Their values are 0, 1, and 2, - respectively. Availability: Windows, Unix. - - .. versionadded:: 2.5 - - .. _os-file-dir: Files and Directories Modified: python/branches/release26-maint/Doc/library/socket.rst ============================================================================== --- python/branches/release26-maint/Doc/library/socket.rst (original) +++ python/branches/release26-maint/Doc/library/socket.rst Wed May 19 01:19:34 2010 @@ -664,10 +664,10 @@ .. method:: socket.recv_into(buffer[, nbytes[, flags]]) Receive up to *nbytes* bytes from the socket, storing the data into a buffer - rather than creating a new string. If *nbytes* is not specified (or 0), - receive up to the size available in the given buffer. See the Unix manual page - :manpage:`recv(2)` for the meaning of the optional argument *flags*; it defaults - to zero. + rather than creating a new string. If *nbytes* is not specified (or 0), + receive up to the size available in the given buffer. Returns the number of + bytes received. See the Unix manual page :manpage:`recv(2)` for the meaning + of the optional argument *flags*; it defaults to zero. .. versionadded:: 2.5 Modified: python/branches/release26-maint/Doc/reference/datamodel.rst ============================================================================== --- python/branches/release26-maint/Doc/reference/datamodel.rst (original) +++ python/branches/release26-maint/Doc/reference/datamodel.rst Wed May 19 01:19:34 2010 @@ -1757,6 +1757,48 @@ locking/synchronization. +Customizing instance and subclass checks +---------------------------------------- + +.. versionadded:: 2.6 + +The following methods are used to override the default behavior of the +:func:`isinstance` and :func:`issubclass` built-in functions. + +In particular, the metaclass :class:`abc.ABCMeta` implements these methods in +order to allow the addition of Abstract Base Classes (ABCs) as "virtual base +classes" to any class or type (including built-in types), and including to other +ABCs. + +.. method:: class.__instancecheck__(self, instance) + + Return true if *instance* should be considered a (direct or indirect) + instance of *class*. If defined, called to implement ``isinstance(instance, + class)``. + + +.. method:: class.__subclasscheck__(self, subclass) + + Return true if *subclass* should be considered a (direct or indirect) + subclass of *class*. If defined, called to implement ``issubclass(subclass, + class)``. + + +Note that these methods are looked up on the type (metaclass) of a class. They +cannot be defined as class methods in the actual class. This is consistent with +the lookup of special methods that are called on instances, only that in this +case the instance is itself a class. + +.. seealso:: + + :pep:`3119` - Introducing Abstract Base Classes + Includes the specification for customizing :func:`isinstance` and + :func:`issubclass` behavior through :meth:`__instancecheck__` and + :meth:`__subclasscheck__`, with motivation for this functionality in the + context of adding Abstract Base Classes (see the :mod:`abc` module) to the + language. + + .. _callable-types: Emulating callable objects Modified: python/branches/release26-maint/Lib/pipes.py ============================================================================== --- python/branches/release26-maint/Lib/pipes.py (original) +++ python/branches/release26-maint/Lib/pipes.py Wed May 19 01:19:34 2010 @@ -263,11 +263,11 @@ # Reliably quote a string as a single argument for /bin/sh -_safechars = string.ascii_letters + string.digits + '!@%_-+=:,./' # Safe unquoted -_funnychars = '"`$\\' # Unsafe inside "double quotes" +# Safe unquoted +_safechars = frozenset(string.ascii_letters + string.digits + '@%_-+=:,./') def quote(file): - ''' return a shell-escaped version of the file string ''' + """Return a shell-escaped version of the file string.""" for c in file: if c not in _safechars: break @@ -275,11 +275,6 @@ if not file: return "''" return file - if '\'' not in file: - return '\'' + file + '\'' - res = '' - for c in file: - if c in _funnychars: - c = '\\' + c - res = res + c - return '"' + res + '"' + # use single quotes, and put single quotes into double quotes + # the string $'b is then quoted as '$'"'"'b' + return "'" + file.replace("'", "'\"'\"'") + "'" Modified: python/branches/release26-maint/Lib/test/test_pipes.py ============================================================================== --- python/branches/release26-maint/Lib/test/test_pipes.py (original) +++ python/branches/release26-maint/Lib/test/test_pipes.py Wed May 19 01:19:34 2010 @@ -62,9 +62,10 @@ self.assertEqual(open(TESTFN).read(), d) def testQuoting(self): - safeunquoted = string.ascii_letters + string.digits + '!@%_-+=:,./' - unsafe = '"`$\\' + safeunquoted = string.ascii_letters + string.digits + '@%_-+=:,./' + unsafe = '"`$\\!' + self.assertEqual(pipes.quote(''), "''") self.assertEqual(pipes.quote(safeunquoted), safeunquoted) self.assertEqual(pipes.quote('test file name'), "'test file name'") for u in unsafe: @@ -72,9 +73,7 @@ "'test%sname'" % u) for u in unsafe: self.assertEqual(pipes.quote("test%s'name'" % u), - '"test\\%s\'name\'"' % u) - - self.assertEqual(pipes.quote(''), "''") + "'test%s'\"'\"'name'\"'\"''" % u) def testRepr(self): t = pipes.Template() Modified: python/branches/release26-maint/Misc/NEWS ============================================================================== --- python/branches/release26-maint/Misc/NEWS (original) +++ python/branches/release26-maint/Misc/NEWS Wed May 19 01:19:34 2010 @@ -29,7 +29,9 @@ - Raise a TypeError when trying to delete a T_STRING_INPLACE struct member. -- Issue #1583863: An unicode subclass can now override the __unicode__ method +- Issue #1583863: An unicode subclass can now override the __unicode__ method. + +- Issue #7507: Quote "!" in pipes.quote(); it is special to some shells. - Issue #7544: Preallocate thread memory before creating the thread to avoid a fatal error in low memory condition. Modified: python/branches/release26-maint/Misc/developers.txt ============================================================================== --- python/branches/release26-maint/Misc/developers.txt (original) +++ python/branches/release26-maint/Misc/developers.txt Wed May 19 01:19:34 2010 @@ -17,6 +17,11 @@ Permissions History ------------------- +- Jean-Paul Calderone was given commit access on April 6 2010 by + GFB, at suggestion of Michael Foord and others. + +- Brian Curtin was given commit access on March 24 2010 by MvL. + - Florent Xicluna was given commit access on February 25 2010 by MvL, based on Antoine Pitrou's recommendation. From python-checkins at python.org Wed May 19 01:20:58 2010 From: python-checkins at python.org (georg.brandl) Date: Wed, 19 May 2010 01:20:58 +0200 (CEST) Subject: [Python-checkins] r81304 - python/branches/release26-maint Message-ID: <20100518232058.F0283EE994@mail.python.org> Author: georg.brandl Date: Wed May 19 01:20:58 2010 New Revision: 81304 Log: Blocked revisions 79923-79924,80068,80460 via svnmerge ........ r79923 | georg.brandl | 2010-04-10 11:15:24 +0000 (Sa, 10 Apr 2010) | 1 line #8360: skipTest was added in 2.7. ........ r79924 | georg.brandl | 2010-04-10 11:16:59 +0000 (Sa, 10 Apr 2010) | 1 line #8346: update version. ........ r80068 | georg.brandl | 2010-04-14 08:56:01 +0000 (Mi, 14 Apr 2010) | 1 line #5341: fix typo and adapt docstring syntax. ........ r80460 | georg.brandl | 2010-04-25 10:16:00 +0000 (So, 25 Apr 2010) | 1 line #8528: fix typo. ........ Modified: python/branches/release26-maint/ (props changed) From solipsis at pitrou.net Wed May 19 01:23:01 2010 From: solipsis at pitrou.net (solipsis at pitrou.net) Date: Wed, 19 May 2010 01:23:01 +0200 (CEST) Subject: [Python-checkins] Daily py3k reference leaks (r81299): sum=0 Message-ID: <20100518232302.28FA81770A@ns6635.ovh.net> py3k results for svn r81299 (hg cset d4e47c5f0dee) -------------------------------------------------- Command line was: ['./python', '-m', 'test.regrtest', '-uall', '-R', '3:3:/home/antoine/py3k/refleaks/reflogSYiFqC', '-x'] From python-checkins at python.org Wed May 19 01:23:16 2010 From: python-checkins at python.org (georg.brandl) Date: Wed, 19 May 2010 01:23:16 +0200 (CEST) Subject: [Python-checkins] r81305 - python/branches/release26-maint Message-ID: <20100518232316.67D37EE9BE@mail.python.org> Author: georg.brandl Date: Wed May 19 01:23:16 2010 New Revision: 81305 Log: Blocked revisions 79349,79381,79412,79537,79833,79943,79945,79947,79952,79963,80024,80064,80070,80085,80088,80605,80607,80646,80652,80674 via svnmerge ........ r79349 | andrew.kuchling | 2010-03-23 18:39:24 +0000 (Di, 23 M?r 2010) | 1 line add some unittest items ........ r79381 | andrew.kuchling | 2010-03-24 18:07:43 +0000 (Mi, 24 M?r 2010) | 1 line Various edits ........ r79412 | andrew.kuchling | 2010-03-25 01:35:51 +0000 (Do, 25 M?r 2010) | 1 line Add various items ........ r79537 | florent.xicluna | 2010-03-31 21:40:32 +0000 (Mi, 31 M?r 2010) | 2 lines Fix typo ........ r79833 | eric.smith | 2010-04-06 15:17:33 +0000 (Di, 06 Apr 2010) | 1 line Note that PEP 378 also applies to int. ........ r79943 | andrew.kuchling | 2010-04-11 01:40:30 +0000 (So, 11 Apr 2010) | 1 line Add various items ........ r79945 | andrew.kuchling | 2010-04-11 01:40:49 +0000 (So, 11 Apr 2010) | 1 line name correct ........ r79947 | andrew.kuchling | 2010-04-11 01:44:13 +0000 (So, 11 Apr 2010) | 1 line Remove distutils section ........ r79952 | andrew.kuchling | 2010-04-11 12:49:37 +0000 (So, 11 Apr 2010) | 1 line Add two items ........ r79963 | andrew.kuchling | 2010-04-11 20:40:09 +0000 (So, 11 Apr 2010) | 1 line Add several items ........ r80024 | andrew.kuchling | 2010-04-13 01:32:51 +0000 (Di, 13 Apr 2010) | 1 line Add an item; stray edit ........ r80064 | andrew.kuchling | 2010-04-14 01:14:59 +0000 (Mi, 14 Apr 2010) | 1 line Add argparse example ........ r80070 | andrew.kuchling | 2010-04-14 14:28:31 +0000 (Mi, 14 Apr 2010) | 1 line Add some text ........ r80085 | andrew.kuchling | 2010-04-14 23:55:17 +0000 (Mi, 14 Apr 2010) | 1 line Add various items; correct argparse output ........ r80088 | andrew.kuchling | 2010-04-15 01:42:27 +0000 (Do, 15 Apr 2010) | 1 line Add various items ........ r80605 | andrew.kuchling | 2010-04-29 00:22:16 +0000 (Do, 29 Apr 2010) | 1 line Add various items ........ r80607 | andrew.kuchling | 2010-04-29 01:45:41 +0000 (Do, 29 Apr 2010) | 1 line Add various unittest items ........ r80646 | andrew.kuchling | 2010-04-30 01:33:40 +0000 (Fr, 30 Apr 2010) | 1 line Add various items; rearrange unittest section a bit ........ r80652 | andrew.kuchling | 2010-04-30 13:47:34 +0000 (Fr, 30 Apr 2010) | 1 line Add item ........ r80674 | andrew.kuchling | 2010-05-01 01:19:16 +0000 (Sa, 01 Mai 2010) | 1 line Add various items ........ Modified: python/branches/release26-maint/ (props changed) From python-checkins at python.org Wed May 19 01:24:41 2010 From: python-checkins at python.org (georg.brandl) Date: Wed, 19 May 2010 01:24:41 +0200 (CEST) Subject: [Python-checkins] r81306 - in python/branches/release26-maint: Misc/developers.txt Message-ID: <20100518232441.F1202EE996@mail.python.org> Author: georg.brandl Date: Wed May 19 01:24:41 2010 New Revision: 81306 Log: Merged revisions 79374,80152,80301 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r79374 | martin.v.loewis | 2010-03-24 15:05:53 +0000 (Mi, 24 M??r 2010) | 2 lines Add Brian Curtin. ........ r80152 | martin.v.loewis | 2010-04-17 17:10:55 +0000 (Sa, 17 Apr 2010) | 2 lines Add Giampaolo. ........ r80301 | martin.v.loewis | 2010-04-21 06:37:48 +0000 (Mi, 21 Apr 2010) | 2 lines Add Tim Golden. ........ Modified: python/branches/release26-maint/ (props changed) python/branches/release26-maint/Misc/developers.txt Modified: python/branches/release26-maint/Misc/developers.txt ============================================================================== --- python/branches/release26-maint/Misc/developers.txt (original) +++ python/branches/release26-maint/Misc/developers.txt Wed May 19 01:24:41 2010 @@ -17,6 +17,12 @@ Permissions History ------------------- +- Tim Golden was given commit access on April 21 2010 by MvL, + at suggestion of Michael Foord. + +- Giampaolo Rodol? was given commit access on April 17 2010 by + MvL, at suggestion of R. David Murray. + - Jean-Paul Calderone was given commit access on April 6 2010 by GFB, at suggestion of Michael Foord and others. From python-checkins at python.org Wed May 19 01:26:18 2010 From: python-checkins at python.org (georg.brandl) Date: Wed, 19 May 2010 01:26:18 +0200 (CEST) Subject: [Python-checkins] r81307 - python/branches/release26-maint Message-ID: <20100518232618.F3D9EE375@mail.python.org> Author: georg.brandl Date: Wed May 19 01:26:18 2010 New Revision: 81307 Log: Blocked revisions 78586-78594,78600-78601,78604,78606,78613-78614,78623,78634,78749,79385 via svnmerge ........ r78586 | benjamin.peterson | 2010-03-02 22:03:03 +0000 (Di, 02 M?r 2010) | 1 line remove coding cookie as mandated by PEP 8 ........ r78587 | benjamin.peterson | 2010-03-02 22:05:59 +0000 (Di, 02 M?r 2010) | 1 line set svn:eol-style ........ r78588 | benjamin.peterson | 2010-03-02 22:08:40 +0000 (Di, 02 M?r 2010) | 1 line remove another coding cookie ........ r78589 | georg.brandl | 2010-03-02 22:17:38 +0000 (Di, 02 M?r 2010) | 1 line Add some x-refs. ........ r78590 | benjamin.peterson | 2010-03-02 22:20:10 +0000 (Di, 02 M?r 2010) | 1 line enable running of argparse tests and fix two that failed in the new environment ........ r78591 | benjamin.peterson | 2010-03-02 22:23:33 +0000 (Di, 02 M?r 2010) | 1 line prevent warning filter adjustment from altering other tests ........ r78592 | benjamin.peterson | 2010-03-02 22:24:30 +0000 (Di, 02 M?r 2010) | 1 line use test_main() in __main__ section ........ r78593 | benjamin.peterson | 2010-03-02 22:26:25 +0000 (Di, 02 M?r 2010) | 1 line convert deprecated fail* methods to assert* variants ........ r78594 | florent.xicluna | 2010-03-02 22:34:11 +0000 (Di, 02 M?r 2010) | 2 lines Test test_pep277 is only relevant for Unicode-friendly filesystems. ........ r78600 | benjamin.peterson | 2010-03-02 22:58:01 +0000 (Di, 02 M?r 2010) | 1 line remove code to avoid BaseException.message bug ........ r78601 | benjamin.peterson | 2010-03-02 23:02:02 +0000 (Di, 02 M?r 2010) | 1 line remove cross-version compatibility code ........ r78604 | benjamin.peterson | 2010-03-02 23:43:47 +0000 (Di, 02 M?r 2010) | 1 line plug ref leaks ........ r78606 | florent.xicluna | 2010-03-02 23:56:38 +0000 (Di, 02 M?r 2010) | 2 lines Fix wording. ........ r78613 | benjamin.peterson | 2010-03-03 01:55:09 +0000 (Mi, 03 M?r 2010) | 1 line edit for style ........ r78614 | benjamin.peterson | 2010-03-03 02:04:24 +0000 (Mi, 03 M?r 2010) | 1 line fix Sphinx warnings ........ r78623 | lars.gustaebel | 2010-03-03 11:55:48 +0000 (Mi, 03 M?r 2010) | 3 lines Issue #7232: Add support for the context manager protocol to the TarFile class. ........ r78634 | benjamin.peterson | 2010-03-03 21:28:25 +0000 (Mi, 03 M?r 2010) | 1 line rephrase ........ r78749 | benjamin.peterson | 2010-03-07 00:29:44 +0000 (So, 07 M?r 2010) | 1 line eliminate py3k warnings in argparse ........ r79385 | benjamin.peterson | 2010-03-24 22:03:09 +0000 (Mi, 24 M?r 2010) | 1 line replace copy right notice with simple attribution ........ Modified: python/branches/release26-maint/ (props changed) From python-checkins at python.org Wed May 19 01:37:50 2010 From: python-checkins at python.org (georg.brandl) Date: Wed, 19 May 2010 01:37:50 +0200 (CEST) Subject: [Python-checkins] r81308 - in python/branches/release26-maint: Lib/distutils/command/install_lib.py Lib/heapq.py Objects/stringlib/fastsearch.h Message-ID: <20100518233750.B3A43EBE0@mail.python.org> Author: georg.brandl Date: Wed May 19 01:37:50 2010 New Revision: 81308 Log: Merged revisions 68750,68811,68945,69157 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r68750 | benjamin.peterson | 2009-01-18 22:47:04 +0000 (So, 18 Jan 2009) | 1 line fix encoding cookie case ........ r68811 | benjamin.peterson | 2009-01-20 18:58:27 +0000 (Di, 20 Jan 2009) | 1 line fix url ........ r68945 | tarek.ziade | 2009-01-25 22:11:04 +0000 (So, 25 Jan 2009) | 1 line added missing module docstring ........ r69157 | benjamin.peterson | 2009-01-31 23:43:25 +0000 (Sa, 31 Jan 2009) | 1 line add explanatory comment ........ Modified: python/branches/release26-maint/ (props changed) python/branches/release26-maint/Lib/distutils/command/install_lib.py python/branches/release26-maint/Lib/heapq.py python/branches/release26-maint/Objects/stringlib/fastsearch.h Modified: python/branches/release26-maint/Lib/distutils/command/install_lib.py ============================================================================== --- python/branches/release26-maint/Lib/distutils/command/install_lib.py (original) +++ python/branches/release26-maint/Lib/distutils/command/install_lib.py Wed May 19 01:37:50 2010 @@ -1,4 +1,8 @@ # This module should be kept compatible with Python 2.1. +"""distutils.command.install_lib + +Implements the Distutils 'install_lib' command +(install all Python modules).""" __revision__ = "$Id$" Modified: python/branches/release26-maint/Lib/heapq.py ============================================================================== --- python/branches/release26-maint/Lib/heapq.py (original) +++ python/branches/release26-maint/Lib/heapq.py Wed May 19 01:37:50 2010 @@ -1,4 +1,4 @@ -# -*- coding: Latin-1 -*- +# -*- coding: latin-1 -*- """Heap queue algorithm (a.k.a. priority queue). Modified: python/branches/release26-maint/Objects/stringlib/fastsearch.h ============================================================================== --- python/branches/release26-maint/Objects/stringlib/fastsearch.h (original) +++ python/branches/release26-maint/Objects/stringlib/fastsearch.h Wed May 19 01:37:50 2010 @@ -5,7 +5,7 @@ /* fast search/count implementation, based on a mix between boyer- moore and horspool, with a few more bells and whistles on the top. - for some more background, see: http://effbot.org/stringlib */ + for some more background, see: http://effbot.org/stringlib.htm */ /* note: fastsearch may access s[n], which isn't a problem when using Python's ordinary string types, but may cause problems if you're From python-checkins at python.org Wed May 19 01:38:50 2010 From: python-checkins at python.org (georg.brandl) Date: Wed, 19 May 2010 01:38:50 +0200 (CEST) Subject: [Python-checkins] r81309 - in python/branches/release26-maint: README Message-ID: <20100518233850.44960EE992@mail.python.org> Author: georg.brandl Date: Wed May 19 01:38:50 2010 New Revision: 81309 Log: Merged revisions 69924,69998-69999 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r69924 | benjamin.peterson | 2009-02-24 02:45:35 +0000 (Di, 24 Feb 2009) | 1 line update README on running tests ........ r69998 | benjamin.peterson | 2009-02-26 19:04:40 +0000 (Do, 26 Feb 2009) | 1 line the startship is rather outdated now ........ r69999 | benjamin.peterson | 2009-02-26 19:05:59 +0000 (Do, 26 Feb 2009) | 1 line comma ........ Modified: python/branches/release26-maint/ (props changed) python/branches/release26-maint/README Modified: python/branches/release26-maint/README ============================================================================== --- python/branches/release26-maint/README (original) +++ python/branches/release26-maint/README Wed May 19 01:38:50 2010 @@ -97,9 +97,6 @@ New Python releases and related technologies are published at http://www.python.org/. Come visit us! -There's also a Python community web site at -http://starship.python.net/. - Newsgroups and Mailing Lists ---------------------------- @@ -166,7 +163,7 @@ To build Python, you normally type "make" in the toplevel directory. If you have changed the configuration, the Makefile may have to be -rebuilt. In this case you may have to run make again to correctly +rebuilt. In this case, you may have to run make again to correctly build your desired target. The interpreter executable is built in the top level directory. @@ -880,11 +877,14 @@ non-standard implementation of strftime() in the C library. Please ignore this, or upgrade to glibc version 6. +By default, tests are prevented from overusing resources like disk space and +memory. To enable these tests, run "make testall". + IMPORTANT: If the tests fail and you decide to mail a bug report, *don't* include the output of "make test". It is useless. Run the failing test manually, as follows: - ./python ./Lib/test/test_whatever.py + ./python Lib/test/regrtest.py -v test_whatever (substituting the top of the source tree for '.' if you built in a different directory). This runs the test in verbose mode. From python-checkins at python.org Wed May 19 01:45:21 2010 From: python-checkins at python.org (georg.brandl) Date: Wed, 19 May 2010 01:45:21 +0200 (CEST) Subject: [Python-checkins] r81310 - python/branches/release26-maint Message-ID: <20100518234521.707E8EE9CA@mail.python.org> Author: georg.brandl Date: Wed May 19 01:45:21 2010 New Revision: 81310 Log: Blocked revisions 66721-66722,66744-66745,66752,66756,66763-66765,66768,66791-66792,66822-66823,66832,66836,66852,66857,66868,66878,66894,66902,66912,66989,66994,67013,67015,67049,67065,67171,67226,67234,67287,67342,67348-67349,67353,67396,67407,67411,67442,67511,67521,67536-67537,67543,67572,67584,67587,67601,67614,67628,67818,67822,67850,67857,67902,67946,67954,67976,67978-67980,67985,68089,68092,68119,68150,68153,68156,68158,68163,68167,68176,68203,68208-68209,68231,68238,68240,68243,68296,68299,68302,68304,68311,68314,68319,68381,68395,68415,68425,68432,68455,68458-68462,68476,68484-68485,68487,68496,68498,68532,68542,68544-68546,68559-68560,68562,68565-68569,68571,68592,68596-68597,68603-68604,68607,68618,68648,68665,68667,68676,68722,68739,68763-68764,68766,68772-68773,68785,68789,68792-68793,68803,68807,68826,68829,68831,68839-68840,68843,68845,68850,68853,68881,68884,68892,68925,68927,68929,68933,68941-68943,68953,68964,68985,68998,69001,69003,69010,69012,69014,69018,69023,69039,69050,69053,69060-69063,69070,69074,69080,69085,69087,69112-69113,69129-69130,69134,69139,69143,69146,69149,69154,69156,69158,69169,69195,69211-69212,69227,69237,69242,69252-69253,69257,69260,69262,69268,69285,69302-69303,69305,69315,69322,69324,69330-69332,69342,69356,69360,69364-69366,69373-69374,69377,69385,69389,69394,69404,69410,69413,69415,69419-69420,69425,69443,69447,69459-69460,69466-69467,69470,69473-69474,69480-69481,69495,69498,69516,69521-69522,69525,69528,69530,69561,69566,69578-69580,69582-69583,69591,69594,69602,69604,69609-69610,69617,69619,69634,69639,69666,69685,69688-69690,69692-69693,69700,69709-69710,69715-69716,69724,69739,69743,69748,69751,69757,69761,69765,69770,69772,69777,69795,69811,69837-69838,69855,69861,69870-69871,69874,69878,69881,69889,69901-69902,69907-69908,69937,69946-69947,69952-69953,69955,69959,69974,69976,69981,69983,69994,70000 via svnmerge ........ r66721 | barry.warsaw | 2008-10-02 03:33:51 +0000 (Do, 02 Okt 2008) | 1 line Bump to 2.7a0 ........ r66722 | martin.v.loewis | 2008-10-02 11:44:17 +0000 (Do, 02 Okt 2008) | 1 line Use CRT 9 policy files. ........ r66744 | benjamin.peterson | 2008-10-02 19:00:31 +0000 (Do, 02 Okt 2008) | 1 line we're in 2.7 now ........ r66745 | georg.brandl | 2008-10-02 19:09:47 +0000 (Do, 02 Okt 2008) | 2 lines Forward-port r66736. ........ r66752 | martin.v.loewis | 2008-10-02 20:04:47 +0000 (Do, 02 Okt 2008) | 2 lines Add UUID for 2.7. ........ r66756 | benjamin.peterson | 2008-10-02 20:46:58 +0000 (Do, 02 Okt 2008) | 1 line update pydoc topics ........ r66763 | neal.norwitz | 2008-10-03 04:13:08 +0000 (Fr, 03 Okt 2008) | 1 line Update the version to 2.7. Hopefully this fixes the test_distutils failure ........ r66764 | martin.v.loewis | 2008-10-03 08:59:41 +0000 (Fr, 03 Okt 2008) | 2 lines Bump version to 2.7. Regenerate. ........ r66765 | martin.v.loewis | 2008-10-03 10:59:55 +0000 (Fr, 03 Okt 2008) | 1 line Update version number to 2.7. ........ r66768 | hirokazu.yamamoto | 2008-10-03 16:07:28 +0000 (Fr, 03 Okt 2008) | 1 line Follows to python's version change (VC6) ........ r66791 | andrew.kuchling | 2008-10-04 16:52:31 +0000 (Sa, 04 Okt 2008) | 1 line Add What's New for 2.7 ........ r66792 | benjamin.peterson | 2008-10-04 17:10:14 +0000 (Sa, 04 Okt 2008) | 1 line silence Sphinx warning ........ r66822 | skip.montanaro | 2008-10-07 01:55:20 +0000 (Di, 07 Okt 2008) | 2 lines Simplify individual tests by defining setUp and tearDown methods. ........ r66823 | skip.montanaro | 2008-10-07 02:02:00 +0000 (Di, 07 Okt 2008) | 2 lines Pay attention to -R entries in LDFLAGS. ........ r66832 | skip.montanaro | 2008-10-07 15:03:40 +0000 (Di, 07 Okt 2008) | 1 line save/restore stdout/stderr instead of relying on __*__ versions ........ r66836 | amaury.forgeotdarc | 2008-10-07 20:32:10 +0000 (Di, 07 Okt 2008) | 5 lines #4069: aSet.remove(otherSet) would always report the empty frozenset([]) as the missing key. Now it correctly refers to the initial otherset. Reviewed by Raymond. Will backport to 2.6. ........ r66852 | andrew.kuchling | 2008-10-08 13:21:27 +0000 (Mi, 08 Okt 2008) | 1 line Note how bytes alias is expected to be used ........ r66857 | georg.brandl | 2008-10-08 18:57:13 +0000 (Mi, 08 Okt 2008) | 2 lines Make all whatsnew docs accessible. ........ r66868 | matthias.klose | 2008-10-10 07:24:20 +0000 (Fr, 10 Okt 2008) | 2 lines - Makefile.pre.in(PROFILE_TASK): search files in srcdir ........ r66878 | benjamin.peterson | 2008-10-11 17:25:36 +0000 (Sa, 11 Okt 2008) | 4 lines give poplib a real test suite #4088 from Giampaolo Rodola'x ........ r66894 | benjamin.peterson | 2008-10-14 22:37:18 +0000 (Di, 14 Okt 2008) | 1 line remove set compat cruft ........ r66902 | skip.montanaro | 2008-10-15 11:49:10 +0000 (Mi, 15 Okt 2008) | 1 line easter egg ........ r66912 | hirokazu.yamamoto | 2008-10-16 06:25:25 +0000 (Do, 16 Okt 2008) | 2 lines removed unused _PyUnicode_FromFileSystemEncodedObject. made win32_chdir, win32_wchdir static. ........ r66989 | matthias.klose | 2008-10-21 09:12:25 +0000 (Di, 21 Okt 2008) | 2 lines - install versioned manpage ........ r66994 | amaury.forgeotdarc | 2008-10-21 22:01:38 +0000 (Di, 21 Okt 2008) | 6 lines #4157 move two test functions out of platform.py. Turn them into unit tests, and correct an obvious typo: (("a", "b") ("c", "d") ("e", "f")) compiles even with the missing commas, but does not execute very well... ........ r67013 | benjamin.peterson | 2008-10-25 02:53:28 +0000 (Sa, 25 Okt 2008) | 1 line give a py3k warning when 'nonlocal' is used as a variable name ........ r67015 | georg.brandl | 2008-10-25 07:00:52 +0000 (Sa, 25 Okt 2008) | 2 lines Typo fix. ........ r67049 | amaury.forgeotdarc | 2008-10-30 21:18:34 +0000 (Do, 30 Okt 2008) | 8 lines Issue #4176: Pickle would crash the interpreter when a __reduce__ function does not return an iterator for the 4th and 5th items. (sequence-like and mapping-like state) A list is not an iterator... Will backport to 2.6 and 2.5. ........ r67065 | benjamin.peterson | 2008-10-30 23:59:18 +0000 (Do, 30 Okt 2008) | 1 line move unprefixed error into .c file ........ r67171 | benjamin.peterson | 2008-11-08 18:38:54 +0000 (Sa, 08 Nov 2008) | 4 lines check for assignment to __debug__ during AST generation Also, give assignment to None a better error message ........ r67226 | brett.cannon | 2008-11-15 22:40:44 +0000 (Sa, 15 Nov 2008) | 4 lines The docs for httplib.HTTPConnection.putheader() have claimed for quite a while that their could be an arbitrary number of values passed in. Turns out the code did not match that. The code now matches the docs. ........ r67234 | benjamin.peterson | 2008-11-16 17:54:55 +0000 (So, 16 Nov 2008) | 1 line run autoconf ........ r67287 | josiah.carlson | 2008-11-19 18:26:12 +0000 (Mi, 19 Nov 2008) | 2 lines Fix for issue 4332 in trunk. ........ r67342 | amaury.forgeotdarc | 2008-11-22 19:39:38 +0000 (Sa, 22 Nov 2008) | 3 lines yuvconvert.c is a part of the "sv" module, an old IRIX thing and certainly not useful for any Windows build. ........ r67348 | benjamin.peterson | 2008-11-23 02:09:41 +0000 (So, 23 Nov 2008) | 1 line raise a better error ........ r67349 | matthias.klose | 2008-11-23 13:37:03 +0000 (So, 23 Nov 2008) | 3 lines - Modules/Setup.dist: Mention _functools in section "Modules that should always be present (non UNIX dependent)" ........ r67353 | matthias.klose | 2008-11-23 13:54:42 +0000 (So, 23 Nov 2008) | 2 lines - Fix typo in last checkin ........ r67396 | matthias.klose | 2008-11-26 17:32:49 +0000 (Mi, 26 Nov 2008) | 2 lines - Modules/Setup.dist: Mention _elementtree and _pickle. ........ r67407 | matthias.klose | 2008-11-27 07:45:25 +0000 (Do, 27 Nov 2008) | 2 lines - Modules/Setup.dist: Update pyexpat ........ r67411 | matthias.klose | 2008-11-27 10:14:22 +0000 (Do, 27 Nov 2008) | 2 lines - Modules/Setup.dist: Update _elementtree, add _bisect, datetime ........ r67442 | jeremy.hylton | 2008-11-29 01:09:35 +0000 (Sa, 29 Nov 2008) | 18 lines Send HTTP headers and message body in a single send() call. This change addresses part of issue 4336. Change endheaders() to take an optional message_body argument that is sent along with the headers. Change xmlrpclib and httplib's other methods to use this new interface. It is more efficient to make a single send() call, which should get the entire client request into one packet (assuming it is smaller than the MTU) and will avoid the long pause for delayed ack following timeout. Also: - Add a comment about the buffer size for makefile(). - Extract _set_content_length() method and fix whitespace issues there. ........ r67511 | vinay.sajip | 2008-12-03 23:22:58 +0000 (Mi, 03 Dez 2008) | 1 line Issue #4384: Added logging integration with warnings module using captureWarnings(). This change includes a NullHandler which does nothing; it will be of use to library developers who want to avoid the "No handlers could be found for logger XXX" message which can appear if the library user doesn't configure logging. ........ r67521 | christian.heimes | 2008-12-04 14:34:40 +0000 (Do, 04 Dez 2008) | 1 line Bumped up 2.6 to 2.7 ........ r67536 | gregory.p.smith | 2008-12-04 20:21:09 +0000 (Do, 04 Dez 2008) | 3 lines Adds a subprocess.check_call_output() function to return the output from a process on success or raise an exception on error. ........ r67537 | vinay.sajip | 2008-12-04 20:32:18 +0000 (Do, 04 Dez 2008) | 1 line Took Nick Coghlan's advice about importing warnings globally in logging, to avoid the possibility of race conditions: "This could deadlock if a thread spawned as a side effect of importing a module happens to trigger a warning. warnings is pulled into sys.modules as part of the interpreter startup - having a global 'import warnings' shouldn't have any real effect on logging's import time." ........ r67543 | gregory.p.smith | 2008-12-05 02:27:01 +0000 (Fr, 05 Dez 2008) | 2 lines rename the new check_call_output to check_output. its less ugly. ........ r67572 | georg.brandl | 2008-12-05 09:23:14 +0000 (Fr, 05 Dez 2008) | 2 lines #4458: recognize "-" as an argument, not a malformed option in gnu_getopt(). ........ r67584 | fred.drake | 2008-12-05 15:52:25 +0000 (Fr, 05 Dez 2008) | 2 lines bump version number ........ r67587 | fred.drake | 2008-12-05 16:14:18 +0000 (Fr, 05 Dez 2008) | 2 lines be more specific, and parallel to the py3k branch ........ r67601 | mark.dickinson | 2008-12-05 21:55:28 +0000 (Fr, 05 Dez 2008) | 3 lines Issue #4445: save 3 bytes (on average, on a typical machine) per string allocation. ........ r67614 | skip.montanaro | 2008-12-06 17:43:30 +0000 (Sa, 06 Dez 2008) | 2 lines issue 4483 - dbm build failures on systems with gdbm_compat lib. ........ r67628 | skip.montanaro | 2008-12-07 02:16:00 +0000 (So, 07 Dez 2008) | 1 line muffed the default case ........ r67818 | antoine.pitrou | 2008-12-17 00:38:28 +0000 (Mi, 17 Dez 2008) | 3 lines Issue #2183: Simplify and optimize bytecode for list comprehensions. ........ r67822 | mark.dickinson | 2008-12-17 16:14:37 +0000 (Mi, 17 Dez 2008) | 4 lines Issue #3439: add bit_length method to int and long. Thanks Fredrik Johansson and Victor Stinner for code, Raymond Hettinger for review. ........ r67850 | raymond.hettinger | 2008-12-19 09:06:07 +0000 (Fr, 19 Dez 2008) | 9 lines Fix-up and clean-up docs for int.bit_length(). * Replace dramatic footnote with in-line comment about possible round-off errors in logarithms of large numbers. * Add comments to the pure python code equivalent. * replace floor() with int() in the mathematical equivalent so the type is correct (should be an int, not a float). * add abs() to the mathematical equivalent so that it matches the previous line that it is supposed to be equivalent to. * make one combined example with a negative input. ........ r67857 | mark.dickinson | 2008-12-19 17:46:51 +0000 (Fr, 19 Dez 2008) | 2 lines Fix typo in Python equivalent for bit_length. ........ r67902 | benjamin.peterson | 2008-12-22 20:16:25 +0000 (Mo, 22 Dez 2008) | 1 line add py3k warnings to frame.f_exc_* ........ r67946 | antoine.pitrou | 2008-12-27 15:43:12 +0000 (Sa, 27 Dez 2008) | 4 lines Issue #4756: zipfile.is_zipfile() now supports file-like objects. Patch by Gabriel Genellina. ........ r67954 | benjamin.peterson | 2008-12-27 18:24:11 +0000 (Sa, 27 Dez 2008) | 1 line #4748 lambda generators shouldn't return values ........ r67976 | georg.brandl | 2008-12-28 11:54:53 +0000 (So, 28 Dez 2008) | 7 lines Backport r67974: #4759: allow None as first argument of bytearray.translate(), for consistency with bytes.translate(). Also fix segfault for bytearray.translate(x, None) -- will backport this part to 3.0 and 2.6. ........ r67978 | georg.brandl | 2008-12-28 11:58:49 +0000 (So, 28 Dez 2008) | 2 lines #4731: clarify message about missing module prerequisites. ........ r67979 | antoine.pitrou | 2008-12-28 14:09:36 +0000 (So, 28 Dez 2008) | 3 lines Issue #4444: Allow assertRaises() to be used as a context handler. ........ r67980 | antoine.pitrou | 2008-12-28 14:24:29 +0000 (So, 28 Dez 2008) | 1 line wrong version number in doc changes committed in r67979 ........ r67985 | antoine.pitrou | 2008-12-28 16:01:11 +0000 (So, 28 Dez 2008) | 4 lines Issue #2153: modernize coding style of unittest.py, remove obsolete compatibility stuff. Patch by Virgil Dupras. ........ r68089 | benjamin.peterson | 2008-12-31 03:37:51 +0000 (Mi, 31 Dez 2008) | 1 line #4788 qualify some bare except clauses ........ r68092 | benjamin.peterson | 2008-12-31 04:08:55 +0000 (Mi, 31 Dez 2008) | 1 line fix name collision issues ........ r68119 | georg.brandl | 2009-01-01 12:09:40 +0000 (Do, 01 Jan 2009) | 3 lines #4222: document dis.findlabels() and dis.findlinestarts() and put them into dis.__all__. ........ r68150 | ronald.oussoren | 2009-01-02 11:46:05 +0000 (Fr, 02 Jan 2009) | 1 line Fix for issue 3433 ........ r68153 | ronald.oussoren | 2009-01-02 12:59:32 +0000 (Fr, 02 Jan 2009) | 10 lines Fix for issue3559: No preferences menu in IDLE on OSX 1) Add a comment to the help file to that points to the preferences menu. 2) An earlier checkin tried to detect Tk >= 8.10.14, but did this in the wrong way. The end result of this was that the IDLE->Preferences... menu got surpressed when using the system version of Tcl/Tk ........ r68156 | ronald.oussoren | 2009-01-02 14:10:20 +0000 (Fr, 02 Jan 2009) | 1 line Fix for issue1594 ........ r68158 | ronald.oussoren | 2009-01-02 14:46:19 +0000 (Fr, 02 Jan 2009) | 2 lines Fix for issue 900949 ........ r68163 | ronald.oussoren | 2009-01-02 15:25:36 +0000 (Fr, 02 Jan 2009) | 2 lines Fix for issues #841800 and #900506 ........ r68167 | vinay.sajip | 2009-01-02 18:53:04 +0000 (Fr, 02 Jan 2009) | 1 line Minor documentation changes relating to NullHandler, the module used for handlers and references to ConfigParser. ........ r68176 | andrew.kuchling | 2009-01-02 21:00:35 +0000 (Fr, 02 Jan 2009) | 1 line Add various items ........ r68203 | martin.v.loewis | 2009-01-03 17:19:26 +0000 (Sa, 03 Jan 2009) | 2 lines Issue #4817: Remove unused function PyOS_GetLastModificationTime. ........ r68208 | raymond.hettinger | 2009-01-03 19:02:23 +0000 (Sa, 03 Jan 2009) | 1 line Issue 4796: Add from_float methods to the decimal module. ........ r68209 | raymond.hettinger | 2009-01-03 19:08:10 +0000 (Sa, 03 Jan 2009) | 1 line Reapply r68191. ........ r68231 | guilherme.polo | 2009-01-03 21:51:09 +0000 (Sa, 03 Jan 2009) | 4 lines The _tkinter module functions "createfilehandler", "deletefilehandler", "createtimerhandler", "mainloop", "dooneevent" and "quit" have been deprecated for removal in 3.x (part of issue #3638). ........ r68238 | georg.brandl | 2009-01-03 22:03:11 +0000 (Sa, 03 Jan 2009) | 2 lines Manually merge r68095,68186,68187,68188,68190 from 2.6 branch. ........ r68240 | georg.brandl | 2009-01-03 22:05:22 +0000 (Sa, 03 Jan 2009) | 2 lines Manually merge r67868 from 2.6 branch. ........ r68243 | georg.brandl | 2009-01-03 22:15:42 +0000 (Sa, 03 Jan 2009) | 2 lines Add temporary code to fix the automatic doc build failure. ........ r68296 | mark.dickinson | 2009-01-04 12:29:36 +0000 (So, 04 Jan 2009) | 6 lines Add autoconf test to detect x87-style double rounding, as described in issue #2937. This information can be helpful for diagnosing platform- specific problems in math and cmath. The result of the test also serves as a fairly reliable indicator of whether the x87 floating-point instructions (as opposed to SSE2) are in use on Intel x86/x86_64 systems. ........ r68299 | mark.dickinson | 2009-01-04 13:57:26 +0000 (So, 04 Jan 2009) | 4 lines isinf and isnan are macros, not functions; fix configure script to use AC_CHECK_DECLS instead of AC_CHECK_FUNCS for these. (See discussion in issue #4506) ........ r68302 | mark.dickinson | 2009-01-04 16:06:40 +0000 (So, 04 Jan 2009) | 4 lines Oops. Need to check not only that HAVE_DECL_ISINF is defined, but also that it's equal to 1. (If isinf isn't defined, HAVE_DECL_ISINF is defined to be 0, rather than being undefined.) ........ r68304 | mark.dickinson | 2009-01-04 17:02:05 +0000 (So, 04 Jan 2009) | 2 lines Fix HAVE_DECL_ISINF/ISNAN test (again). ........ r68311 | mark.dickinson | 2009-01-04 19:53:00 +0000 (So, 04 Jan 2009) | 2 lines Use C99 'isfinite' macro in preference to BSD-derived 'finite' function. ........ r68314 | mark.dickinson | 2009-01-04 21:10:56 +0000 (So, 04 Jan 2009) | 5 lines Fix Decimal.from_float to use valid Python 2.3 syntax, as per comments at top of decimal.py. (But note that the from_float method itself with still not be usable before Python 2.7.) See issue 4796 for discussion. ........ r68319 | antoine.pitrou | 2009-01-04 21:29:23 +0000 (So, 04 Jan 2009) | 3 lines Issue #4272: Add an optional argument to the GzipFile constructor to override the timestamp in the gzip stream. ........ r68381 | martin.v.loewis | 2009-01-07 18:40:40 +0000 (Mi, 07 Jan 2009) | 2 lines Issue #4850: Change COUNT_ALLOCS variables to Py_ssize_t. ........ r68395 | raymond.hettinger | 2009-01-08 06:39:04 +0000 (Do, 08 Jan 2009) | 1 line Forward port r68394 for issue 4816. ........ r68415 | tarek.ziade | 2009-01-08 23:56:31 +0000 (Do, 08 Jan 2009) | 1 line fixed #4394 make the storage of the password optional in .pypirc ........ r68425 | benjamin.peterson | 2009-01-09 02:56:32 +0000 (Fr, 09 Jan 2009) | 1 line fix markup ........ r68432 | benjamin.peterson | 2009-01-09 03:15:00 +0000 (Fr, 09 Jan 2009) | 1 line remove temporary code now ........ r68455 | kristjan.jonsson | 2009-01-09 20:03:27 +0000 (Fr, 09 Jan 2009) | 1 line Issue 3582. Improved thread support and TLS for Windows ........ r68458 | kristjan.jonsson | 2009-01-09 20:23:16 +0000 (Fr, 09 Jan 2009) | 1 line Issue 4336: HTTPRequest._send_output() now deals with the case of the message body not being a string. This allows clients to use endheaders(message_body) instead of endheaders() + send(message_body) without making any extra checks. ........ r68459 | kristjan.jonsson | 2009-01-09 20:27:16 +0000 (Fr, 09 Jan 2009) | 1 line Issue 4336: Let users of HTTPConnection.endheaders() submit a message body to the function if required. ........ r68460 | kristjan.jonsson | 2009-01-09 20:31:26 +0000 (Fr, 09 Jan 2009) | 1 line Issue 4293: Make Py_AddPendingCall() thread safe ........ r68461 | kristjan.jonsson | 2009-01-09 21:35:16 +0000 (Fr, 09 Jan 2009) | 2 lines Issue 4293: Make Py_AddPendingCall() thread safe Add test cases and documentation ........ r68462 | antoine.pitrou | 2009-01-09 21:40:55 +0000 (Fr, 09 Jan 2009) | 6 lines Issue #4074: Change the criteria for doing a full garbage collection (i.e. collecting the oldest generation) so that allocating lots of objects without destroying them does not show quadratic performance. Based on a proposal by Martin von L?wis at http://mail.python.org/pipermail/python-dev/2008-June/080579.html. ........ r68476 | kristjan.jonsson | 2009-01-10 12:14:31 +0000 (Sa, 10 Jan 2009) | 1 line Issue 4906: Preserve windows error state across PyThread_get_key_value ........ r68484 | antoine.pitrou | 2009-01-10 16:13:45 +0000 (Sa, 10 Jan 2009) | 3 lines Issue #3860: GzipFile and BZ2File now support the context manager protocol. ........ r68485 | antoine.pitrou | 2009-01-10 16:15:24 +0000 (Sa, 10 Jan 2009) | 1 line Add NEWS entry for r68484. ........ r68487 | matthias.klose | 2009-01-10 17:00:42 +0000 (Sa, 10 Jan 2009) | 3 lines - Issue #4861: ctypes.util.find_library(): Robustify. Fix library detection on biarch systems. Try to rely on ldconfig only, without using objdump and gcc. ........ r68496 | antoine.pitrou | 2009-01-10 18:33:21 +0000 (Sa, 10 Jan 2009) | 3 lines Add ACKS entries for some of the patches I've been committing. ........ r68498 | benjamin.peterson | 2009-01-10 19:08:49 +0000 (Sa, 10 Jan 2009) | 1 line fix encoding ........ r68532 | kristjan.jonsson | 2009-01-11 16:23:37 +0000 (So, 11 Jan 2009) | 1 line Issue 4879: Allow buffering for HTTPResponse ........ r68542 | martin.v.loewis | 2009-01-12 08:11:24 +0000 (Mo, 12 Jan 2009) | 2 lines Issue #4893: Use NT threading on CE. ........ r68544 | kristjan.jonsson | 2009-01-12 09:20:34 +0000 (Mo, 12 Jan 2009) | 1 line Update Misc/NEWS for issue 3582 ........ r68545 | kristjan.jonsson | 2009-01-12 09:24:04 +0000 (Mo, 12 Jan 2009) | 1 line Misc/NEWS for issue 4293 ........ r68546 | raymond.hettinger | 2009-01-12 10:37:32 +0000 (Mo, 12 Jan 2009) | 1 line Optimize heapq.nsmallest/nlargest for cases where n==1 or n>=size. ........ r68559 | raymond.hettinger | 2009-01-12 22:58:41 +0000 (Mo, 12 Jan 2009) | 1 line Issue 1696199: Add collections.Counter(). ........ r68560 | amaury.forgeotdarc | 2009-01-12 23:36:55 +0000 (Mo, 12 Jan 2009) | 6 lines #3720: Interpreter crashes when an evil iterator removes its own next function. Now the slot is filled with a function that always raises. Will not backport: extensions compiled with 2.6.x would not run on 2.6.0. ........ r68562 | raymond.hettinger | 2009-01-13 01:05:03 +0000 (Di, 13 Jan 2009) | 7 lines Simplify Counter() API. Replace items keyword argument with a mapping. Makes Counter() idempotent, makes update() API the same as Counter.__init__(), makes a more readable repr, makes the API more dict-like, and allows Steven Bethard's update() example to work. ........ r68565 | raymond.hettinger | 2009-01-13 03:49:43 +0000 (Di, 13 Jan 2009) | 1 line Minor documentation tweaks and simpler update() example. ........ r68566 | raymond.hettinger | 2009-01-13 04:13:53 +0000 (Di, 13 Jan 2009) | 1 line Fixup and simplify docstrings and doctests. ........ r68567 | raymond.hettinger | 2009-01-13 04:50:35 +0000 (Di, 13 Jan 2009) | 1 line Speed-up __repr__. Eliminate duplicate tests. Use a from-irmport. ........ r68568 | georg.brandl | 2009-01-13 08:11:07 +0000 (Di, 13 Jan 2009) | 2 lines Fix call signature and markup. ........ r68569 | raymond.hettinger | 2009-01-13 08:38:14 +0000 (Di, 13 Jan 2009) | 7 lines Add table of idioms/patterns for using Counter objects. Improve the appearance and flow of the References section -- it used to have a box around it that wasn't distinct from the preceding code boxes and it had a weird bolding pattern and hanging indents that made the section disproportionately large. ........ r68571 | armin.ronacher | 2009-01-13 11:52:23 +0000 (Di, 13 Jan 2009) | 3 lines ast.literal_eval can properly evaluate complex numbers now. This fixes issue4907. ........ r68592 | amaury.forgeotdarc | 2009-01-13 23:19:08 +0000 (Di, 13 Jan 2009) | 5 lines #4807: Remove a wrong usage of wsprintf in the winreg module ("windows sprintf", different than swprintf) Needed for the windows CE port. ........ r68596 | amaury.forgeotdarc | 2009-01-13 23:39:22 +0000 (Di, 13 Jan 2009) | 3 lines #1162154: inspect.getmembers() now skips attributes that raise AttributeError, e.g. a __slots__ attribute which has not been set. ........ r68597 | benjamin.peterson | 2009-01-13 23:43:50 +0000 (Di, 13 Jan 2009) | 1 line fix test_xmlrpc failures #4939 ........ r68603 | raymond.hettinger | 2009-01-14 00:15:21 +0000 (Mi, 14 Jan 2009) | 1 line Minor doc tweaks. ........ r68604 | raymond.hettinger | 2009-01-14 01:15:06 +0000 (Mi, 14 Jan 2009) | 1 line Add tests for __init__() and update() with no args. ........ r68607 | kristjan.jonsson | 2009-01-14 10:50:57 +0000 (Mi, 14 Jan 2009) | 2 lines Re-enable all tests for windows platforms. Also, explicitly connect to the IPV4 address. On windows platforms supporting AF_INET6, the SocketProxy would connect using socket.create_connection('localhost', port) which would cycle through all address families and try to connect. It would try connecting using AF_INET6 first and this would cause a delay of up to a second. ........ r68618 | kristjan.jonsson | 2009-01-15 17:20:21 +0000 (Do, 15 Jan 2009) | 1 line Issue 4929: Handle socket errors when receiving ........ r68648 | benjamin.peterson | 2009-01-17 04:28:57 +0000 (Sa, 17 Jan 2009) | 1 line use enumerate ........ r68665 | amaury.forgeotdarc | 2009-01-17 17:11:50 +0000 (Sa, 17 Jan 2009) | 3 lines #4930: Slightly cleaner (and faster) code in type creation: compare slots by address, not by name. ........ r68667 | amaury.forgeotdarc | 2009-01-17 20:18:59 +0000 (Sa, 17 Jan 2009) | 3 lines #4077: No need to append \n when calling Py_FatalError + fix a declaration to make it match the one in pythonrun.h ........ r68676 | benjamin.peterson | 2009-01-17 22:27:54 +0000 (Sa, 17 Jan 2009) | 1 line fix inspect.isclass() on instances with a custom __getattr__ #1225107 ........ r68722 | kristjan.jonsson | 2009-01-18 10:58:44 +0000 (So, 18 Jan 2009) | 1 line issue 4293: make test_capi.py more robutst, it times out on some platforms, presumably waiting for threads. Lower the thread count to 16. ........ r68739 | benjamin.peterson | 2009-01-18 21:11:38 +0000 (So, 18 Jan 2009) | 1 line fix test that wasn't working as expected #4990 ........ r68763 | kristjan.jonsson | 2009-01-19 13:10:27 +0000 (Mo, 19 Jan 2009) | 2 lines Issue 4957 Let os.ftruncate raise OSError like documented. ........ r68764 | benjamin.peterson | 2009-01-19 15:04:35 +0000 (Mo, 19 Jan 2009) | 3 lines Removed merge tracking for "svnmerge" for svn+ssh://pythondev at svn.python.org/python/branches/trunk-math ........ r68766 | benjamin.peterson | 2009-01-19 15:06:33 +0000 (Mo, 19 Jan 2009) | 3 lines Removed merge tracking for "svnmerge" for svn+ssh://pythondev at svn.python.org/python/branches/tnelson-trunk-bsddb-47-upgrade ........ r68772 | benjamin.peterson | 2009-01-19 15:42:23 +0000 (Mo, 19 Jan 2009) | 1 line add a note about the ftruncate change ........ r68773 | benjamin.peterson | 2009-01-19 15:51:27 +0000 (Mo, 19 Jan 2009) | 1 line simplify code ........ r68785 | benjamin.peterson | 2009-01-19 21:08:37 +0000 (Mo, 19 Jan 2009) | 1 line I'm sick of these deprecations warnings in test_os ........ r68789 | raymond.hettinger | 2009-01-20 01:19:26 +0000 (Di, 20 Jan 2009) | 6 lines Build-outs for Counter() class: * Constructor and update() support keyword args (like their dict counterparts). * The 'del' statement no longer raises KeyError for missing values. * Add multiset operations: __add__, __sub__, __and__, __or__. ........ r68792 | raymond.hettinger | 2009-01-20 02:24:38 +0000 (Di, 20 Jan 2009) | 1 line Add Counter() to __all__. ........ r68793 | raymond.hettinger | 2009-01-20 03:36:36 +0000 (Di, 20 Jan 2009) | 1 line Make merging easier by formattng comment blocks the same in Py3.1 ........ r68803 | raymond.hettinger | 2009-01-20 12:59:36 +0000 (Di, 20 Jan 2009) | 1 line Fix typos. ........ r68807 | benjamin.peterson | 2009-01-20 14:31:08 +0000 (Di, 20 Jan 2009) | 1 line backport r68802 (bugfix) ........ r68826 | vinay.sajip | 2009-01-20 22:43:17 +0000 (Di, 20 Jan 2009) | 1 line Issue 5013: Fixed bug in FileHandler when delay was set. ........ r68829 | vinay.sajip | 2009-01-20 23:16:08 +0000 (Di, 20 Jan 2009) | 1 line Issue 5013: Fixed bug in FileHandler when delay was set - added fix for RotatingFileHandler and changed header comment slightly. ........ r68831 | raymond.hettinger | 2009-01-20 23:42:54 +0000 (Di, 20 Jan 2009) | 1 line Beautify and cleanup the references section. ........ r68839 | jesse.noller | 2009-01-21 02:08:17 +0000 (Mi, 21 Jan 2009) | 1 line Issue 5009: multiprocessing: failure in manager._debug_info() ........ r68840 | andrew.kuchling | 2009-01-21 02:15:43 +0000 (Mi, 21 Jan 2009) | 1 line Add some items ........ r68843 | raymond.hettinger | 2009-01-21 20:31:50 +0000 (Mi, 21 Jan 2009) | 1 line Simplify explanation of multiset operations by removing restrictions on negative inputs. ........ r68845 | raymond.hettinger | 2009-01-21 23:12:51 +0000 (Mi, 21 Jan 2009) | 1 line Tighten-up the docs for Counter(). ........ r68850 | raymond.hettinger | 2009-01-22 05:20:47 +0000 (Do, 22 Jan 2009) | 1 line More doc tweaks. ........ r68853 | raymond.hettinger | 2009-01-22 09:05:43 +0000 (Do, 22 Jan 2009) | 1 line Update comments and add an optimized path for Counter.update(). ........ r68881 | andrew.kuchling | 2009-01-24 03:28:18 +0000 (Sa, 24 Jan 2009) | 1 line Add various items ........ r68884 | kristjan.jonsson | 2009-01-24 10:52:26 +0000 (Sa, 24 Jan 2009) | 1 line Add a test for UNC import paths, see issue 3677 ........ r68892 | martin.v.loewis | 2009-01-24 15:45:18 +0000 (Sa, 24 Jan 2009) | 2 lines Add heading for 2.7a0. ........ r68925 | benjamin.peterson | 2009-01-25 17:15:10 +0000 (So, 25 Jan 2009) | 5 lines fix building the core with --disable-unicode I changed some bytearray methods to use strings instead of unicode like bytes_repr Also, bytearray.fromhex() can take strings as well as unicode ........ r68927 | hirokazu.yamamoto | 2009-01-25 17:46:48 +0000 (So, 25 Jan 2009) | 1 line Fixed compile error on windows. ........ r68929 | tarek.ziade | 2009-01-25 18:19:25 +0000 (So, 25 Jan 2009) | 1 line Fixed #4863: removed distutils.mwerkscompiler ........ r68933 | tarek.ziade | 2009-01-25 19:29:10 +0000 (So, 25 Jan 2009) | 1 line Issue #4863, removing remaining bits ........ r68941 | raymond.hettinger | 2009-01-25 21:04:14 +0000 (So, 25 Jan 2009) | 1 line Promote compress() from a recipe to being a regular itertool. ........ r68942 | raymond.hettinger | 2009-01-25 21:31:47 +0000 (So, 25 Jan 2009) | 1 line Improved itertools recipe for generating powerset(). ........ r68943 | tarek.ziade | 2009-01-25 22:09:10 +0000 (So, 25 Jan 2009) | 1 line Issue #5052: removed backward compatibility information (out of date) ........ r68953 | brett.cannon | 2009-01-26 01:16:50 +0000 (Mo, 26 Jan 2009) | 3 lines Backport importlib in the form of providing importlib.import_module(). This has been done purely to help transitions from 2.7 to 3.1. ........ r68964 | raymond.hettinger | 2009-01-26 16:52:22 +0000 (Mo, 26 Jan 2009) | 1 line Fix signed/unsigned mismatch. ........ r68985 | raymond.hettinger | 2009-01-26 23:29:09 +0000 (Mo, 26 Jan 2009) | 6 lines Remove startup firewall message. That is handled by an error dialog whenever a connection cannot be formed. Also, the Idle version number is already in the About Idle dialog. Now, the startup is clean looking once again. ........ r68998 | raymond.hettinger | 2009-01-27 02:36:33 +0000 (Di, 27 Jan 2009) | 3 lines Tweak column alignment for collections docs. ........ r69001 | raymond.hettinger | 2009-01-27 02:58:49 +0000 (Di, 27 Jan 2009) | 1 line Promote combinations_with_replacement() from a recipe to a regular itertool. ........ r69003 | benjamin.peterson | 2009-01-27 03:07:53 +0000 (Di, 27 Jan 2009) | 1 line excellent place to use a set() #5069 ........ r69010 | raymond.hettinger | 2009-01-27 09:33:06 +0000 (Di, 27 Jan 2009) | 1 line Add tests to verify combinatoric relationships. ........ r69012 | raymond.hettinger | 2009-01-27 09:52:35 +0000 (Di, 27 Jan 2009) | 1 line Stronger tests for combinatoric relationships. ........ r69014 | raymond.hettinger | 2009-01-27 10:03:04 +0000 (Di, 27 Jan 2009) | 1 line Issue 5021: doctest.testfile should set __name__ ........ r69018 | raymond.hettinger | 2009-01-27 10:36:14 +0000 (Di, 27 Jan 2009) | 1 line More exhaustive combinatoric checks. ........ r69023 | raymond.hettinger | 2009-01-27 13:26:35 +0000 (Di, 27 Jan 2009) | 1 line Add more tests for the powerset() recipe. ........ r69039 | benjamin.peterson | 2009-01-27 23:15:48 +0000 (Di, 27 Jan 2009) | 1 line use True and False ........ r69050 | guilherme.polo | 2009-01-28 13:09:03 +0000 (Mi, 28 Jan 2009) | 2 lines Added the ttk module. See issue #2983: Ttk support for Tkinter. ........ r69053 | guilherme.polo | 2009-01-28 15:56:01 +0000 (Mi, 28 Jan 2009) | 2 lines Demos for ttk added. ........ r69060 | guilherme.polo | 2009-01-28 19:23:28 +0000 (Mi, 28 Jan 2009) | 2 lines Added support for collecting tests only from specific packages. ........ r69061 | guilherme.polo | 2009-01-28 19:28:04 +0000 (Mi, 28 Jan 2009) | 4 lines * Renaming test_tk_* to test_ttk_* since that is what they are testing. * Added ttk tests to the expected skips mapping just like where test_tcl was expected to be skipped too. ........ r69062 | guilherme.polo | 2009-01-28 20:02:01 +0000 (Mi, 28 Jan 2009) | 1 line Make sure the root windows gets destroyed ........ r69063 | guilherme.polo | 2009-01-28 20:03:26 +0000 (Mi, 28 Jan 2009) | 2 lines Issue #5083: New 'gui' resource for regrtest. ........ r69070 | raymond.hettinger | 2009-01-28 23:02:26 +0000 (Mi, 28 Jan 2009) | 6 lines Issue 4920: Fixed next() vs __next__() issues in the ABCs for Iterator and MutableSet. Also added thorough test for required abstractmethods. ........ r69074 | raymond.hettinger | 2009-01-28 23:58:16 +0000 (Mi, 28 Jan 2009) | 1 line Correct docs for ABCs (MutableSequence was missing __setiem). Simplify the table by taking out inherited requirements for abstract methods. ........ r69080 | brett.cannon | 2009-01-29 00:55:33 +0000 (Do, 29 Jan 2009) | 2 lines Ignore .pyc and .pyo files. ........ r69085 | raymond.hettinger | 2009-01-29 03:21:42 +0000 (Do, 29 Jan 2009) | 1 line Update itertools.__doc__ to include all tools. ........ r69087 | raymond.hettinger | 2009-01-29 03:43:44 +0000 (Do, 29 Jan 2009) | 1 line Fix typo. ........ r69112 | benjamin.peterson | 2009-01-30 02:02:25 +0000 (Fr, 30 Jan 2009) | 1 line pep8tify conditionals ........ r69113 | benjamin.peterson | 2009-01-30 02:24:39 +0000 (Fr, 30 Jan 2009) | 1 line make _tkinter._flatten check the result of PySequence_Size for errors #3880 ........ r69129 | benjamin.peterson | 2009-01-31 01:42:55 +0000 (Sa, 31 Jan 2009) | 1 line check the errno in bad fd cases ........ r69130 | andrew.kuchling | 2009-01-31 02:50:09 +0000 (Sa, 31 Jan 2009) | 1 line Add a section ........ r69134 | benjamin.peterson | 2009-01-31 16:29:18 +0000 (Sa, 31 Jan 2009) | 1 line completely detabify unicodeobject.c ........ r69139 | mark.dickinson | 2009-01-31 16:44:04 +0000 (Sa, 31 Jan 2009) | 2 lines Add an extra test for long <-> float hash equivalence. ........ r69143 | benjamin.peterson | 2009-01-31 21:00:10 +0000 (Sa, 31 Jan 2009) | 1 line I believe the intention here was to avoid a global lookup ........ r69146 | benjamin.peterson | 2009-01-31 21:47:42 +0000 (Sa, 31 Jan 2009) | 1 line fix indentation ........ r69149 | benjamin.peterson | 2009-01-31 22:03:19 +0000 (Sa, 31 Jan 2009) | 1 line fix indentation; looks like all I managed to do the first time is make things uglier ........ r69154 | benjamin.peterson | 2009-01-31 22:33:02 +0000 (Sa, 31 Jan 2009) | 1 line fix indentation in comment ........ r69156 | gregory.p.smith | 2009-01-31 22:57:30 +0000 (Sa, 31 Jan 2009) | 4 lines - Issue #5104: The socket module now raises OverflowError when 16-bit port and protocol numbers are supplied outside the allowed 0-65536 range on bind() and getservbyport(). ........ r69158 | benjamin.peterson | 2009-01-31 23:54:38 +0000 (Sa, 31 Jan 2009) | 1 line more flags which only work for function blocks ........ r69169 | guilherme.polo | 2009-02-01 02:56:16 +0000 (So, 01 Feb 2009) | 3 lines Restore Tkinter.Tk._loadtk so this test doesn't fail for problems related to ttk. ........ r69195 | guilherme.polo | 2009-02-02 00:38:54 +0000 (Mo, 02 Feb 2009) | 3 lines Use a single Tcl interpreter through all these tests, this may help some failing buildbots. ........ r69211 | guilherme.polo | 2009-02-02 20:23:29 +0000 (Mo, 02 Feb 2009) | 1 line Restore the previous geometry before leaving the test ........ r69212 | guilherme.polo | 2009-02-02 20:28:59 +0000 (Mo, 02 Feb 2009) | 1 line Moving to importlib ........ r69227 | raymond.hettinger | 2009-02-02 21:50:13 +0000 (Mo, 02 Feb 2009) | 1 line Issue 1242657: list(obj) can swallow KeyboardInterrupt. ........ r69237 | raymond.hettinger | 2009-02-03 02:23:19 +0000 (Di, 03 Feb 2009) | 1 line Validate that __length_hint__ returns a usable result. ........ r69242 | raymond.hettinger | 2009-02-03 03:37:03 +0000 (Di, 03 Feb 2009) | 1 line Register decimals as numbers.Number ........ r69252 | brett.cannon | 2009-02-03 04:58:29 +0000 (Di, 03 Feb 2009) | 3 lines Make importlib a package. This allows using svn:externals in the sandbox to package up the code for separate distribution. ........ r69253 | brett.cannon | 2009-02-03 04:59:58 +0000 (Di, 03 Feb 2009) | 1 line Ignore bytecode files in importlib. ........ r69257 | brett.cannon | 2009-02-03 05:08:22 +0000 (Di, 03 Feb 2009) | 1 line Backport importlib to at least Python 2.5 by getting rid of use of str.format. ........ r69260 | thomas.heller | 2009-02-03 17:07:40 +0000 (Di, 03 Feb 2009) | 9 lines This refactoring should make it easier to add new calling conventions. Replace ffi_call_STDCALL and ffi_call_SYSV by a ffi_call_x86 function that cleans up the stack when FFI_SYSV is used, and does nothing for FFI_STDCALL. Remove libffi_msvc\win32.S, which is out of date and also unused; it was only used for building ctypes with the MingW compiler. ........ r69262 | brett.cannon | 2009-02-03 21:13:05 +0000 (Di, 03 Feb 2009) | 5 lines Make importlib backwards-compatible to Python 2.2 (but this is not promised to last; just doing it to be nice). Also fix a message for an exception. ........ r69268 | kristjan.jonsson | 2009-02-04 10:05:25 +0000 (Mi, 04 Feb 2009) | 1 line issue 4804: Provide checks for the format string of strftime, and for the "mode" string of fopen on Windows. These strings are user provided from python and so we can avoid invoking the C runtime invalid parameter handler by first checking that they are valid. ........ r69285 | tarek.ziade | 2009-02-05 09:06:23 +0000 (Do, 05 Feb 2009) | 1 line Fix comment for #1835 ........ r69302 | neil.schemenauer | 2009-02-05 16:14:39 +0000 (Do, 05 Feb 2009) | 3 lines Fix get_python_inc() to work when building in a directory separate from the source. Also, define 'srcdir' on non-posix platforms. ........ r69303 | neil.schemenauer | 2009-02-05 16:19:05 +0000 (Do, 05 Feb 2009) | 4 lines Since sysconfig.get_python_inc() now works when building in a directory other than the source directory, simplify the test code in test_sysconfig.py. ........ r69305 | neil.schemenauer | 2009-02-05 16:32:29 +0000 (Do, 05 Feb 2009) | 4 lines Make setup.py work when building in a directory other than the source directory. Mainly use 'srcdir' rather than os.getcwd() or '.'. ........ r69315 | neil.schemenauer | 2009-02-05 22:14:04 +0000 (Do, 05 Feb 2009) | 2 lines Oops, Mac build needs the 'incdirlist' variable so restore it. ........ r69322 | neil.schemenauer | 2009-02-06 00:21:55 +0000 (Fr, 06 Feb 2009) | 2 lines Distutils apparently requires an absolute path so provide one. ........ r69324 | tarek.ziade | 2009-02-06 00:31:59 +0000 (Fr, 06 Feb 2009) | 1 line Fixed #1276768: verbose option was not used in the code. ........ r69330 | tarek.ziade | 2009-02-06 00:46:57 +0000 (Fr, 06 Feb 2009) | 1 line README now reflects the current state ........ r69331 | eric.smith | 2009-02-06 00:48:26 +0000 (Fr, 06 Feb 2009) | 2 lines Implement issue #4285, convert sys.version_info to a named tuple. Patch by Ross Light. ........ r69332 | tarek.ziade | 2009-02-06 00:49:45 +0000 (Fr, 06 Feb 2009) | 1 line using >= so setting verbose to 2 will work as well ........ r69342 | tarek.ziade | 2009-02-06 01:15:51 +0000 (Fr, 06 Feb 2009) | 1 line fixed #1520877: now distutils reads Read from the environment/Makefile ........ r69356 | tarek.ziade | 2009-02-06 08:20:15 +0000 (Fr, 06 Feb 2009) | 1 line Fixed #3987 : removed unused import ........ r69360 | tarek.ziade | 2009-02-06 08:55:23 +0000 (Fr, 06 Feb 2009) | 1 line removed types usage and added test coverage (work for #3986) ........ r69364 | kristjan.jonsson | 2009-02-06 10:17:34 +0000 (Fr, 06 Feb 2009) | 1 line Fix a number of Win32ErrorTests error cases. chmod wasn't being tested. 'access' never raises an error. ........ r69365 | armin.rigo | 2009-02-06 11:46:26 +0000 (Fr, 06 Feb 2009) | 2 lines Ivan on IRC in #twisted reported this crasher. ........ r69366 | tarek.ziade | 2009-02-06 13:27:38 +0000 (Fr, 06 Feb 2009) | 1 line Fixed #5167: test_customize_compiler does not apply under non unix compilers ........ r69373 | neil.schemenauer | 2009-02-06 21:08:52 +0000 (Fr, 06 Feb 2009) | 5 lines Overhaul Lib/compiler block ordering. The previous code was filled with hacks. The new code is based on issue #2472 posted by Antoine Pitrou. I did some further cleanups of the pyassem code and optimized the block ordering pass. ........ r69374 | neil.schemenauer | 2009-02-06 21:33:45 +0000 (Fr, 06 Feb 2009) | 6 lines Convert "srcdir" into an absolute path if that seems prudent. Currrently the only user of this is Lib/distutils/tests/test_build_ext.py (in order to find the source for xxmodule.c). I'm not sure if other platforms need similar tweaks, I'm not brave enough to attempt it without being able to test. ........ r69377 | guilherme.polo | 2009-02-06 22:48:07 +0000 (Fr, 06 Feb 2009) | 5 lines Issue #1731706: Call Tcl_ConditionFinalize for Tcl_Conditions that will not be used again (this requires Tcl/Tk 8.3.1), also fix a memory leak in Tkapp_Call when calling from a thread different than the one that created the Tcl interpreter. ........ r69385 | tarek.ziade | 2009-02-07 00:05:39 +0000 (Sa, 07 Feb 2009) | 1 line #3986 replacing string and types call (like in the Py3k branch), and put exec_msg call at the right place ........ r69389 | neil.schemenauer | 2009-02-07 00:13:39 +0000 (Sa, 07 Feb 2009) | 2 lines Make names generated for 'with' variables match the built-in compiler. ........ r69394 | neil.schemenauer | 2009-02-07 00:54:41 +0000 (Sa, 07 Feb 2009) | 4 lines Issue #999042: The Python compiler now handles explict global statements correctly (should be assigned using STORE_GLOBAL opcode). This was done by having the system table differentiate between explict and implicit globals. ........ r69404 | guilherme.polo | 2009-02-07 02:20:29 +0000 (Sa, 07 Feb 2009) | 2 lines Eliminated the need to use ttk.__loadtk__ and the problems related it. ........ r69410 | neil.schemenauer | 2009-02-07 14:53:31 +0000 (Sa, 07 Feb 2009) | 4 lines Fix broken test in test_hotshot. Treating the current directory as an empty file is sloppy and non-portable. Use NamedTemporaryFile to make an empty file. ........ r69413 | neil.schemenauer | 2009-02-07 18:35:16 +0000 (Sa, 07 Feb 2009) | 2 lines Add test for issue #999042, explict global statement works. ........ r69415 | benjamin.peterson | 2009-02-07 19:08:22 +0000 (Sa, 07 Feb 2009) | 1 line make destinsrc private ........ r69419 | nick.coghlan | 2009-02-08 01:26:34 +0000 (So, 08 Feb 2009) | 1 line Issue 4195: Restore the ability to execute packages with the -m switch (but this time in a way that leaves the import machinery in a valid state). (Original patch by Andi Vajda) ........ r69420 | nick.coghlan | 2009-02-08 01:46:01 +0000 (So, 08 Feb 2009) | 1 line Mention patch submitter in NEWS entry for r69419 ........ r69425 | nick.coghlan | 2009-02-08 03:17:00 +0000 (So, 08 Feb 2009) | 1 line Issue #4512 closeout: Make ZipImport.get_filename() a public method ........ r69443 | mark.dickinson | 2009-02-08 17:33:11 +0000 (So, 08 Feb 2009) | 2 lines Silence 'arg may be used uninitialized in this function' warning from gcc. ........ r69447 | vinay.sajip | 2009-02-08 19:06:08 +0000 (So, 08 Feb 2009) | 2 lines Issue #5170: Fixed Unicode output bug in logging and added test case. This is a regression which did not occur in 2.5. ........ r69459 | mark.dickinson | 2009-02-09 14:18:43 +0000 (Mo, 09 Feb 2009) | 3 lines Issue #4575: fix Py_IS_INFINITY macro to work correctly on x87 FPUs. It now forces its argument to double before testing for infinity. ........ r69460 | guilherme.polo | 2009-02-09 16:09:17 +0000 (Mo, 09 Feb 2009) | 1 line Turned setup_master public ........ r69466 | raymond.hettinger | 2009-02-09 18:39:41 +0000 (Mo, 09 Feb 2009) | 3 lines Issue 5171: itertools.product docstring missing 'repeat' argument ........ r69467 | guilherme.polo | 2009-02-09 19:21:21 +0000 (Mo, 09 Feb 2009) | 2 lines Some tests for Tkinter.Text.search ........ r69470 | guilherme.polo | 2009-02-09 19:57:04 +0000 (Mo, 09 Feb 2009) | 1 line Checking for tk availability before continuing (basically the same that is done in test_ttk_guionly) ........ r69473 | guilherme.polo | 2009-02-09 20:50:27 +0000 (Mo, 09 Feb 2009) | 3 lines Fixed issue #5122: Synchronize tk load failure check to prevent a potential deadlock. ........ r69474 | guilherme.polo | 2009-02-09 20:57:45 +0000 (Mo, 09 Feb 2009) | 1 line Enforcing Tk 8.3.1 requirement. ........ r69480 | raymond.hettinger | 2009-02-10 01:24:05 +0000 (Di, 10 Feb 2009) | 1 line Issue 1818: collections.namedtuple() to support automatic renaming of invalid fieldnames. ........ r69481 | brett.cannon | 2009-02-10 02:07:38 +0000 (Di, 10 Feb 2009) | 4 lines compileall used the ctime of bytecode and source to determine if the bytecode should be recreated. This created a timing hole. Fixed by just doing what import does; check the mtime and magic number. ........ r69495 | kristjan.jonsson | 2009-02-10 13:32:24 +0000 (Di, 10 Feb 2009) | 1 line Issue 4804. Add a function to test the validity of file descriptors on Windows, and stop using global runtime settings to silence the warnings / assertions. ........ r69498 | mark.dickinson | 2009-02-10 15:46:50 +0000 (Di, 10 Feb 2009) | 6 lines Issue #5175: PyLong_AsUnsignedLongLong now raises OverflowError for negative arguments. Previously, it raised TypeError. Thanks Lisandro Dalcin. ........ r69516 | hirokazu.yamamoto | 2009-02-11 04:13:06 +0000 (Mi, 11 Feb 2009) | 2 lines Issue #5204: Define _PyVerify_fd on VC6 to make test_fdopen (test_os.py) pass. ........ r69521 | benjamin.peterson | 2009-02-12 04:17:04 +0000 (Do, 12 Feb 2009) | 1 line no need for this __bases__ trick anymore ........ r69522 | raymond.hettinger | 2009-02-12 05:39:46 +0000 (Do, 12 Feb 2009) | 3 lines Issue 5032: added a step argument to itertools.count() and allowed non-integer arguments. ........ r69525 | raymond.hettinger | 2009-02-12 10:16:19 +0000 (Do, 12 Feb 2009) | 1 line Fix spaces/tabs in example. ........ r69528 | raymond.hettinger | 2009-02-12 12:04:26 +0000 (Do, 12 Feb 2009) | 1 line Add an extra testcase. ........ r69530 | raymond.hettinger | 2009-02-12 12:43:01 +0000 (Do, 12 Feb 2009) | 1 line One more test. ........ r69561 | gregory.p.smith | 2009-02-13 03:00:00 +0000 (Fr, 13 Feb 2009) | 5 lines - Issue #3745: Fix hashlib to always reject unicode and non buffer-api supporting objects as input no matter how it was compiled (built in implementations or external openssl library). (backported from a py3k branch) ........ r69566 | tarek.ziade | 2009-02-13 09:12:33 +0000 (Fr, 13 Feb 2009) | 1 line #5158: added documentation on the depends option in distutils extensions ........ r69578 | georg.brandl | 2009-02-13 11:03:59 +0000 (Fr, 13 Feb 2009) | 1 line #3694: add test for fix committed in r66693. ........ r69579 | georg.brandl | 2009-02-13 11:06:59 +0000 (Fr, 13 Feb 2009) | 2 lines Fix warnings GCC emits where the argument of PyErr_Format is a single variable. ........ r69580 | georg.brandl | 2009-02-13 11:10:04 +0000 (Fr, 13 Feb 2009) | 2 lines Fix warnings GCC emits where the argument of PyErr_Format is a single variable. ........ r69582 | antoine.pitrou | 2009-02-13 13:52:33 +0000 (Fr, 13 Feb 2009) | 4 lines Issue #5186: Reduce hash collisions for objects with no __hash__ method by rotating the object pointer by 4 bits to the right. ........ r69583 | antoine.pitrou | 2009-02-13 13:57:40 +0000 (Fr, 13 Feb 2009) | 3 lines Fix compiler warning (gcc) ........ r69591 | martin.v.loewis | 2009-02-13 20:26:16 +0000 (Fr, 13 Feb 2009) | 1 line Update Tix build procedure. ........ r69594 | tarek.ziade | 2009-02-13 22:22:03 +0000 (Fr, 13 Feb 2009) | 1 line Issue #2461: added tests for distutils.util ........ r69602 | tarek.ziade | 2009-02-13 23:41:57 +0000 (Fr, 13 Feb 2009) | 1 line fix the environ for distutils test_util ........ r69604 | raymond.hettinger | 2009-02-14 00:25:51 +0000 (Sa, 14 Feb 2009) | 1 line Add keyword argument support to itertools.count(). ........ r69609 | tarek.ziade | 2009-02-14 14:10:23 +0000 (Sa, 14 Feb 2009) | 1 line Fix for #5257: refactored all tests in distutils, so they use a temporary directory. ........ r69610 | tarek.ziade | 2009-02-14 14:12:30 +0000 (Sa, 14 Feb 2009) | 1 line Replace variable ........ r69617 | benjamin.peterson | 2009-02-14 16:51:03 +0000 (Sa, 14 Feb 2009) | 1 line we're no longer using CVS, so this doesn't have to be binary ........ r69619 | benjamin.peterson | 2009-02-14 17:00:51 +0000 (Sa, 14 Feb 2009) | 1 line this needn't be a shebang line ........ r69634 | mark.dickinson | 2009-02-15 10:13:41 +0000 (So, 15 Feb 2009) | 6 lines Issue #5260: Various portability and standards compliance fixes, optimizations and cleanups in Objects/longobject.c. The most significant change is that longs now use less memory: average savings are 2 bytes per long on 32-bit systems and 6 bytes per long on 64-bit systems. (This memory saving already exists in py3k.) ........ r69639 | mark.dickinson | 2009-02-15 15:48:39 +0000 (So, 15 Feb 2009) | 2 lines A few more minor fixes in longobject.c ........ r69666 | eric.smith | 2009-02-16 09:56:39 +0000 (Mo, 16 Feb 2009) | 1 line Added Ross Light to ACKS, for bug 4285 (r69331). ........ r69685 | raymond.hettinger | 2009-02-16 20:39:12 +0000 (Mo, 16 Feb 2009) | 1 line Add GC support to count() objects. Backport candidate. ........ r69688 | benjamin.peterson | 2009-02-16 21:07:52 +0000 (Mo, 16 Feb 2009) | 1 line fix compiler warnings ........ r69689 | benjamin.peterson | 2009-02-16 21:09:09 +0000 (Mo, 16 Feb 2009) | 1 line remove some PyBytes_* aliases that are not in 3.x ........ r69690 | benjamin.peterson | 2009-02-16 21:23:04 +0000 (Mo, 16 Feb 2009) | 1 line PyList_Append() can fail ........ r69692 | tarek.ziade | 2009-02-16 21:38:01 +0000 (Mo, 16 Feb 2009) | 1 line Fixed #2279: distutils.sdist.add_defaults now add files listed in package_data and data_files ........ r69693 | tarek.ziade | 2009-02-16 21:41:54 +0000 (Mo, 16 Feb 2009) | 1 line #2279: use os.sep so the MANIFEST file test work on win32 ........ r69700 | tarek.ziade | 2009-02-16 22:38:43 +0000 (Mo, 16 Feb 2009) | 1 line note about #2279 ........ r69709 | raymond.hettinger | 2009-02-17 08:33:01 +0000 (Di, 17 Feb 2009) | 1 line Fix-up intro paragraph for collections docs. ........ r69710 | tarek.ziade | 2009-02-17 09:42:44 +0000 (Di, 17 Feb 2009) | 1 line #2279 added the plain path case for data_files ........ r69715 | raymond.hettinger | 2009-02-17 11:00:27 +0000 (Di, 17 Feb 2009) | 1 line Fixup intro paragraphs for the itertools docs. Add some tables for quick reference. ........ r69716 | ronald.oussoren | 2009-02-17 12:38:42 +0000 (Di, 17 Feb 2009) | 2 lines Fix issue776533. ........ r69724 | tarek.ziade | 2009-02-17 23:06:51 +0000 (Di, 17 Feb 2009) | 1 line fixed the data_files inclusion behavior ........ r69739 | raymond.hettinger | 2009-02-18 20:54:53 +0000 (Mi, 18 Feb 2009) | 1 line Generalize the itertools.tee() recipe. ........ r69743 | raymond.hettinger | 2009-02-18 23:10:19 +0000 (Mi, 18 Feb 2009) | 1 line Py3k warnings now automatically include -Qwarn for division. ........ r69748 | raymond.hettinger | 2009-02-19 02:15:14 +0000 (Do, 19 Feb 2009) | 1 line Add keyword arg support to itertools.compress(). ........ r69751 | raymond.hettinger | 2009-02-19 02:38:25 +0000 (Do, 19 Feb 2009) | 1 line Add keyword arg support to itertools.repeat(). ........ r69757 | raymond.hettinger | 2009-02-19 05:34:35 +0000 (Do, 19 Feb 2009) | 1 line Add some cross-references to the docs. Simplify the python code equivalent for izip(). Supply an optional argument for the nth() recipe. ........ r69761 | raymond.hettinger | 2009-02-19 05:51:41 +0000 (Do, 19 Feb 2009) | 1 line Add an example for math.fsum() and elaborate on the accurary note. ........ r69765 | raymond.hettinger | 2009-02-19 06:55:03 +0000 (Do, 19 Feb 2009) | 1 line Add links to helpful external resources. ........ r69770 | raymond.hettinger | 2009-02-19 09:50:24 +0000 (Do, 19 Feb 2009) | 1 line Inline coefficients in gamma(). Add reflection formula. Add comments. ........ r69772 | vinay.sajip | 2009-02-19 12:31:32 +0000 (Do, 19 Feb 2009) | 1 line #5287: Add exception handling around findCaller() call to help out IronPython. ........ r69777 | jeroen.ruigrok | 2009-02-19 18:52:21 +0000 (Do, 19 Feb 2009) | 3 lines Since we recommend one module per import line, reflect this also in the documentation. ........ r69795 | benjamin.peterson | 2009-02-20 03:31:23 +0000 (Fr, 20 Feb 2009) | 1 line revert r69777 since all the experts agree that extra import lines distract from the code ........ r69811 | collin.winter | 2009-02-20 19:30:41 +0000 (Fr, 20 Feb 2009) | 2 lines Issue 5176: special-case string formatting in BINARY_MODULO implementation. This shows a modest (1-3%) speed-up in templating systems, for example. ........ r69837 | raymond.hettinger | 2009-02-21 07:17:22 +0000 (Sa, 21 Feb 2009) | 4 lines Fix keyword arguments for itertools.count(). Step arg without a start arg was ignored. ........ r69838 | raymond.hettinger | 2009-02-21 08:58:42 +0000 (Sa, 21 Feb 2009) | 1 line Speedup and simplify negative counter using count's new step argument. ........ r69855 | benjamin.peterson | 2009-02-21 23:09:33 +0000 (Sa, 21 Feb 2009) | 1 line fix compiler warnings ........ r69861 | tarek.ziade | 2009-02-22 00:07:45 +0000 (So, 22 Feb 2009) | 1 line using versionchanged instead of versionadded for distutils doc on sdist default files ........ r69870 | antoine.pitrou | 2009-02-22 17:25:52 +0000 (So, 22 Feb 2009) | 3 lines Try to make sense of the test_site buildbot failures ........ r69871 | antoine.pitrou | 2009-02-22 18:20:46 +0000 (So, 22 Feb 2009) | 3 lines Revert debugging statements, culprit is possibly test_distutils (see #5316) ........ r69874 | tarek.ziade | 2009-02-22 19:58:12 +0000 (So, 22 Feb 2009) | 1 line moved distutils.text_file tests into a real unittest class ........ r69878 | tarek.ziade | 2009-02-22 20:11:46 +0000 (So, 22 Feb 2009) | 1 line removing map and lambda usage, so the test is similar to py3k's branch one ........ r69881 | tarek.ziade | 2009-02-22 20:15:41 +0000 (So, 22 Feb 2009) | 1 line Removing unused __main__ sections ........ r69889 | matthias.klose | 2009-02-22 23:14:26 +0000 (So, 22 Feb 2009) | 2 lines - Link the shared python library with $(MODLIBS). ........ r69901 | georg.brandl | 2009-02-23 11:24:46 +0000 (Mo, 23 Feb 2009) | 2 lines #5349: C++ pure virtuals can also have an implementation. ........ r69902 | tarek.ziade | 2009-02-23 12:41:29 +0000 (Mo, 23 Feb 2009) | 1 line more test coverage ........ r69907 | georg.brandl | 2009-02-23 18:33:48 +0000 (Mo, 23 Feb 2009) | 1 line Fix grammar. ........ r69908 | raymond.hettinger | 2009-02-23 19:32:55 +0000 (Mo, 23 Feb 2009) | 1 line Update itertools recipes to use next(). ........ r69937 | raymond.hettinger | 2009-02-24 12:23:23 +0000 (Di, 24 Feb 2009) | 3 lines Backport 69934: Register xrange() as a Sequence. ........ r69946 | brett.cannon | 2009-02-24 22:01:02 +0000 (Di, 24 Feb 2009) | 2 lines Expand upon test_site.test_s_option to try to debug its failure. ........ r69947 | jeffrey.yasskin | 2009-02-24 22:48:34 +0000 (Di, 24 Feb 2009) | 3 lines Tools/scripts/analyze_dxp.py, a module with some helper functions to analyze the output of sys.getdxp(). ........ r69952 | raymond.hettinger | 2009-02-25 00:37:57 +0000 (Mi, 25 Feb 2009) | 1 line Sync-up py3.1 doc updates for super(). ........ r69953 | raymond.hettinger | 2009-02-25 00:39:47 +0000 (Mi, 25 Feb 2009) | 1 line Restore Py2.x version of sample call to super(). ........ r69955 | raymond.hettinger | 2009-02-25 00:52:37 +0000 (Mi, 25 Feb 2009) | 1 line More markup and spelling fixes. ........ r69959 | raymond.hettinger | 2009-02-25 01:06:52 +0000 (Mi, 25 Feb 2009) | 1 line Remove reference to zero argument form of super() in 2.x docs. ........ r69974 | mark.dickinson | 2009-02-25 20:29:50 +0000 (Mi, 25 Feb 2009) | 3 lines Replace long with twodigits, to avoid depending on sizeof(digit) < sizeof(long) ........ r69976 | tarek.ziade | 2009-02-25 22:29:27 +0000 (Mi, 25 Feb 2009) | 1 line Fixed #5316 : test failure in test_site ........ r69981 | raymond.hettinger | 2009-02-25 22:48:24 +0000 (Mi, 25 Feb 2009) | 1 line Clarify Counter() docs. ........ r69983 | raymond.hettinger | 2009-02-26 00:05:24 +0000 (Do, 26 Feb 2009) | 1 line Fix typo. ........ r69994 | georg.brandl | 2009-02-26 17:36:26 +0000 (Do, 26 Feb 2009) | 1 line Document that setting sys.py3kwarning wont do anything. ........ r70000 | benjamin.peterson | 2009-02-26 19:07:18 +0000 (Do, 26 Feb 2009) | 1 line remove deprecated symtable.Symbol methods ........ Modified: python/branches/release26-maint/ (props changed) From python-checkins at python.org Wed May 19 01:47:48 2010 From: python-checkins at python.org (georg.brandl) Date: Wed, 19 May 2010 01:47:48 +0200 (CEST) Subject: [Python-checkins] r81311 - in python/branches/release26-maint: Lib/test/crashers/multithreaded_close.py Message-ID: <20100518234748.4DFB3EE9F0@mail.python.org> Author: georg.brandl Date: Wed May 19 01:47:48 2010 New Revision: 81311 Log: Merged revisions 70697 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r70697 | benjamin.peterson | 2009-03-29 21:22:35 +0000 (So, 29 M?r 2009) | 1 line this has been fixed since 2.6 (I love removing these) ........ Removed: python/branches/release26-maint/Lib/test/crashers/multithreaded_close.py Modified: python/branches/release26-maint/ (props changed) Deleted: python/branches/release26-maint/Lib/test/crashers/multithreaded_close.py ============================================================================== --- python/branches/release26-maint/Lib/test/crashers/multithreaded_close.py Wed May 19 01:47:48 2010 +++ (empty file) @@ -1,14 +0,0 @@ -# f.close() is not thread-safe: calling it at the same time as another -# operation (or another close) on the same file, but done from another -# thread, causes crashes. The issue is more complicated than it seems, -# witness the discussions in: -# -# http://bugs.python.org/issue595601 -# http://bugs.python.org/issue815646 - -import thread - -while 1: - f = open("multithreaded_close.tmp", "w") - thread.start_new_thread(f.close, ()) - f.close() From python-checkins at python.org Wed May 19 01:55:25 2010 From: python-checkins at python.org (georg.brandl) Date: Wed, 19 May 2010 01:55:25 +0200 (CEST) Subject: [Python-checkins] r81312 - python/branches/release26-maint Message-ID: <20100518235525.EB37BC8D1@mail.python.org> Author: georg.brandl Date: Wed May 19 01:55:25 2010 New Revision: 81312 Log: Blocked revisions 70000,70003,70007,70011,70016-70017,70022-70023,70025-70026,70049,70071,70081,70090,70094,70119-70123,70126,70131-70132,70136,70145,70149,70153,70166,70178,70188,70212,70223,70235,70261,70267,70271,70273,70275,70281,70286,70293,70295-70296,70298,70300,70305,70308,70319,70342,70364,70378,70385-70387,70389-70390,70392-70393,70395,70397,70400,70405-70406,70418,70439,70443-70444,70454,70466,70468,70470-70473,70475,70477,70479,70485,70489,70533,70538,70542,70544,70546,70550,70552-70555,70558,70561-70564,70568-70571,70574,70578,70588-70589,70598-70599,70601,70605,70611-70621,70623-70624,70626-70627,70641,70647,70651-70652,70668-70669,70671-70672,70674,70691,70698,70700-70703,70706,70711-70712,70716,70734-70735,70747,70757,70770-70772,70775,70777-70779,70788,70807,70821,70837,70844,70856,70864,70869,70872,70874,70876-70878,70883,70885-70886,70888-70892,70894,70901,70903,70910,70918,70920,70922,70930-70931,70936,70939,70951,70956,70958,70965,70968-70969,70975,70979-70981,70986,70992-70995,70997 via svnmerge ........ r70000 | benjamin.peterson | 2009-02-26 19:07:18 +0000 (Do, 26 Feb 2009) | 1 line remove deprecated symtable.Symbol methods ........ r70003 | tarek.ziade | 2009-02-26 23:44:00 +0000 (Do, 26 Feb 2009) | 1 line removed unused import ........ r70007 | tarek.ziade | 2009-02-27 02:14:35 +0000 (Fr, 27 Feb 2009) | 1 line more info on long_description ........ r70011 | brett.cannon | 2009-02-27 03:38:28 +0000 (Fr, 27 Feb 2009) | 5 lines Fix a bug where code was trying to index an int. Left over from the situation from using str.rpartition to str.rindex. Closes Issue5213. ........ r70016 | raymond.hettinger | 2009-02-27 08:09:47 +0000 (Fr, 27 Feb 2009) | 1 line Give mapping views a usable repr. ........ r70017 | tarek.ziade | 2009-02-27 12:53:34 +0000 (Fr, 27 Feb 2009) | 1 line Issue #5052: make Distutils compatible with 2.3 again. ........ r70022 | georg.brandl | 2009-02-27 16:23:18 +0000 (Fr, 27 Feb 2009) | 1 line #5361: fix typo. ........ r70023 | georg.brandl | 2009-02-27 16:39:26 +0000 (Fr, 27 Feb 2009) | 1 line #5363: fix cmpfiles() docs. Another instance where a prose description is twice as long as the code. ........ r70025 | georg.brandl | 2009-02-27 16:52:55 +0000 (Fr, 27 Feb 2009) | 1 line #5344: fix punctuation. ........ r70026 | georg.brandl | 2009-02-27 16:59:03 +0000 (Fr, 27 Feb 2009) | 1 line #5365: add quick look conversion table for different time representations. ........ r70049 | tarek.ziade | 2009-02-28 10:08:02 +0000 (Sa, 28 Feb 2009) | 1 line Issues #1533164 and #5378: Added quiet and force-optimize options to Distutils bdist_rpm command ........ r70071 | jeffrey.yasskin | 2009-02-28 19:03:21 +0000 (Sa, 28 Feb 2009) | 5 lines Backport r69961 to trunk, replacing JUMP_IF_{TRUE,FALSE} with POP_JUMP_IF_{TRUE,FALSE} and JUMP_IF_{TRUE,FALSE}_OR_POP. This avoids executing a POP_TOP on each conditional and sometimes allows the peephole optimizer to skip a JUMP_ABSOLUTE entirely. It speeds up list comprehensions significantly. ........ r70081 | raymond.hettinger | 2009-03-01 02:04:32 +0000 (So, 01 M?r 2009) | 1 line Fix docs for ConfigParser. ........ r70090 | gregory.p.smith | 2009-03-02 05:13:57 +0000 (Mo, 02 M?r 2009) | 3 lines Adds an optional flags argument to re.split, re.sub and re.subn to be consistent with the other re module functions. ........ r70094 | tarek.ziade | 2009-03-02 05:38:44 +0000 (Mo, 02 M?r 2009) | 1 line removing the force-optimized option as discussed in #1533164 ........ r70119 | kristjan.jonsson | 2009-03-03 03:20:42 +0000 (Di, 03 M?r 2009) | 1 line Fix SHA_new and MD5_new, that would crash if not given initial data ........ r70120 | raymond.hettinger | 2009-03-03 04:45:34 +0000 (Di, 03 M?r 2009) | 1 line Backport PEP 372: OrderedDict() ........ r70121 | raymond.hettinger | 2009-03-03 04:51:24 +0000 (Di, 03 M?r 2009) | 3 lines Backport 70106: Add OrderedDict support to collections.namedtuple(). ........ r70122 | raymond.hettinger | 2009-03-03 05:00:37 +0000 (Di, 03 M?r 2009) | 3 lines Backport 70111: Let configparser use ordered dicts by default. ........ r70123 | raymond.hettinger | 2009-03-03 05:11:56 +0000 (Di, 03 M?r 2009) | 1 line Fix markup. ........ r70126 | raymond.hettinger | 2009-03-03 07:12:09 +0000 (Di, 03 M?r 2009) | 1 line Beef-up tests. ........ r70131 | raymond.hettinger | 2009-03-03 20:53:51 +0000 (Di, 03 M?r 2009) | 1 line Make the underlying data structure more private. ........ r70132 | raymond.hettinger | 2009-03-03 21:13:51 +0000 (Di, 03 M?r 2009) | 1 line Minor simplification. ........ r70136 | hirokazu.yamamoto | 2009-03-03 22:05:57 +0000 (Di, 03 M?r 2009) | 1 line Fixed memory leak. ........ r70145 | benjamin.peterson | 2009-03-03 22:51:57 +0000 (Di, 03 M?r 2009) | 1 line making the writing more formal ........ r70149 | raymond.hettinger | 2009-03-03 22:59:25 +0000 (Di, 03 M?r 2009) | 5 lines Backport 70140, 70141, 70143, and 70144. Adds tests, switches from list to deque, fixes __reduce__ which was unnecessarily copying __keys. ........ r70153 | brett.cannon | 2009-03-04 01:00:53 +0000 (Mi, 04 M?r 2009) | 4 lines Fix some more bugs caused by the backport from 3.x for importlib. Do a more exact copy of the final 3.x code to resolve bugs and add appropriate tests. ........ r70166 | georg.brandl | 2009-03-04 18:24:41 +0000 (Mi, 04 M?r 2009) | 2 lines Remove obsolete stuff from string module docs. ........ r70178 | ronald.oussoren | 2009-03-04 22:49:36 +0000 (Mi, 04 M?r 2009) | 2 lines Fix for issue #1113328. ........ r70188 | hirokazu.yamamoto | 2009-03-05 09:34:14 +0000 (Do, 05 M?r 2009) | 1 line Fixed memory leak on failure. ........ r70212 | tarek.ziade | 2009-03-07 00:32:45 +0000 (Sa, 07 M?r 2009) | 1 line Issue #5394: removed > 2.3 syntax from distutils.msvc9compiler ........ r70223 | guilherme.polo | 2009-03-07 02:14:38 +0000 (Sa, 07 M?r 2009) | 4 lines Fixed issue #2638: Show a window constructed with tkSimpleDialog.Dialog only after it is has been populated and properly configured in order to prevent window flashing. ........ r70235 | benjamin.peterson | 2009-03-08 00:21:17 +0000 (So, 08 M?r 2009) | 1 line fix funky indentation ........ r70261 | raymond.hettinger | 2009-03-09 11:31:39 +0000 (Mo, 09 M?r 2009) | 1 line Issue 5443: Fix typo. ........ r70267 | raymond.hettinger | 2009-03-09 11:57:29 +0000 (Mo, 09 M?r 2009) | 1 line Add consume() recipe to itertools docs. ........ r70271 | raymond.hettinger | 2009-03-09 12:56:23 +0000 (Mo, 09 M?r 2009) | 1 line Add cross-reference to the collections docs. ........ r70273 | georg.brandl | 2009-03-09 14:25:07 +0000 (Mo, 09 M?r 2009) | 2 lines #5458: add a note when we started to raise RuntimeErrors. ........ r70275 | georg.brandl | 2009-03-09 16:35:48 +0000 (Mo, 09 M?r 2009) | 2 lines Add missing space. ........ r70281 | benjamin.peterson | 2009-03-09 20:38:56 +0000 (Mo, 09 M?r 2009) | 1 line gzip and bz2 are context managers ........ r70286 | raymond.hettinger | 2009-03-10 00:06:05 +0000 (Di, 10 M?r 2009) | 1 line Fix markup. ........ r70293 | raymond.hettinger | 2009-03-10 04:49:21 +0000 (Di, 10 M?r 2009) | 1 line Add a version tag to the decimal module. ........ r70295 | raymond.hettinger | 2009-03-10 08:16:05 +0000 (Di, 10 M?r 2009) | 1 line Update the decimal FAQ for the from_float() classmethod and improve the recipe for remove_exponent() to make it cut and pasteable. ........ r70296 | raymond.hettinger | 2009-03-10 09:31:48 +0000 (Di, 10 M?r 2009) | 1 line Small optimization for corner case where maxlen==0. ........ r70298 | raymond.hettinger | 2009-03-10 12:50:59 +0000 (Di, 10 M?r 2009) | 1 line For collections.deque() objects, expose the maxlen parameter as a read-only attribute. ........ r70300 | raymond.hettinger | 2009-03-10 13:04:30 +0000 (Di, 10 M?r 2009) | 1 line Fix typo. ........ r70305 | brett.cannon | 2009-03-11 04:51:06 +0000 (Mi, 11 M?r 2009) | 5 lines Require implementations for warnings.showwarning() support the 'line' argument. Was a DeprecationWarning for not supporting it since Python 2.6. Closes issue #3652. ........ r70308 | tarek.ziade | 2009-03-11 12:48:04 +0000 (Mi, 11 M?r 2009) | 1 line Issue #5472: Fixed distutils.test_util tear down ........ r70319 | raymond.hettinger | 2009-03-12 00:31:58 +0000 (Do, 12 M?r 2009) | 1 line Issue 5477: Fix buglet in the itertools documentation. ........ r70342 | georg.brandl | 2009-03-13 19:03:58 +0000 (Fr, 13 M?r 2009) | 1 line #5486: typos. ........ r70364 | eric.smith | 2009-03-14 11:57:26 +0000 (Sa, 14 M?r 2009) | 17 lines Issue 5237, Allow auto-numbered replacement fields in str.format() strings. For simple uses for str.format(), this makes the typing easier. Hopfully this will help in the adoption of str.format(). For example: 'The {} is {}'.format('sky', 'blue') You can mix and matcth auto-numbering and named replacement fields: 'The {} is {color}'.format('sky', color='blue') But you can't mix and match auto-numbering and specified numbering: 'The {0} is {}'.format('sky', 'blue') ValueError: cannot switch from manual field specification to automatic field numbering Will port to 3.1. ........ r70378 | nick.coghlan | 2009-03-15 03:24:46 +0000 (So, 15 M?r 2009) | 1 line Make marshalling errors a little more informative as to what went wrong ........ r70385 | benjamin.peterson | 2009-03-15 14:38:55 +0000 (So, 15 M?r 2009) | 1 line fix tuple.index() error message #5495 ........ r70386 | georg.brandl | 2009-03-15 21:32:06 +0000 (So, 15 M?r 2009) | 1 line #5496: fix docstring of lookup(). ........ r70387 | georg.brandl | 2009-03-15 21:37:16 +0000 (So, 15 M?r 2009) | 1 line #5493: clarify __nonzero__ docs. ........ r70389 | georg.brandl | 2009-03-15 21:43:38 +0000 (So, 15 M?r 2009) | 1 line Fix a small nit in the error message if bool() falls back on __len__ and it returns the wrong type: it would tell the user that __nonzero__ should return bool or int. ........ r70390 | georg.brandl | 2009-03-15 21:44:43 +0000 (So, 15 M?r 2009) | 1 line #5491: clarify nested() semantics. ........ r70392 | georg.brandl | 2009-03-15 21:46:00 +0000 (So, 15 M?r 2009) | 1 line #5488: add missing struct member. ........ r70393 | georg.brandl | 2009-03-15 21:47:42 +0000 (So, 15 M?r 2009) | 1 line #5478: fix copy-paste oversight in function signature. ........ r70395 | georg.brandl | 2009-03-15 21:51:48 +0000 (So, 15 M?r 2009) | 1 line #5276: document IDLESTARTUP and .Idle.py. ........ r70397 | georg.brandl | 2009-03-15 21:53:56 +0000 (So, 15 M?r 2009) | 1 line #5469: add with statement to list of name-binding constructs. ........ r70400 | georg.brandl | 2009-03-15 21:59:37 +0000 (So, 15 M?r 2009) | 3 lines Fix markup in re docs and give a mail address in regex howto, so that the recommendation to send suggestions to the author can be followed. ........ r70405 | georg.brandl | 2009-03-15 22:11:07 +0000 (So, 15 M?r 2009) | 7 lines Move the previously local import of threading to module level. This is cleaner and avoids lockups in obscure cases where a Queue is instantiated while the import lock is already held by another thread. OKed by Tim Peters. ........ r70406 | hirokazu.yamamoto | 2009-03-15 22:43:14 +0000 (So, 15 M?r 2009) | 1 line Added skip for old MSVC. ........ r70418 | georg.brandl | 2009-03-16 19:42:03 +0000 (Mo, 16 M?r 2009) | 1 line Add token markup. ........ r70439 | mark.dickinson | 2009-03-17 23:03:46 +0000 (Di, 17 M?r 2009) | 3 lines Issue #2110: Add support for thousands separator and 'n' format specifier to Decimal __format__ method. ........ r70443 | bob.ippolito | 2009-03-17 23:19:00 +0000 (Di, 17 M?r 2009) | 1 line merge json library with simplejson 2.0.9 (issue 4136) ........ r70444 | mark.dickinson | 2009-03-18 08:22:51 +0000 (Mi, 18 M?r 2009) | 3 lines Fix bug in _insert_thousands_sep: too much zero padding could be added for 'n' formats with non-repeating thousands-separator. ........ r70454 | mark.dickinson | 2009-03-18 16:07:26 +0000 (Mi, 18 M?r 2009) | 9 lines Issue 4474: On platforms with sizeof(wchar_t) == 4 and sizeof(Py_UNICODE) == 2, PyUnicode_FromWideChar now converts each character outside the BMP to the appropriate surrogate pair. Thanks Victor Stinner for the patch. (backport of r70452 from py3k to trunk) ........ r70466 | raymond.hettinger | 2009-03-18 22:13:20 +0000 (Mi, 18 M?r 2009) | 1 line Use mixin methods where possible. (2.7 only -- these don't all exist in 3.0) ........ r70468 | benjamin.peterson | 2009-03-19 03:04:31 +0000 (Do, 19 M?r 2009) | 1 line close files after comparing them ........ r70470 | raymond.hettinger | 2009-03-19 15:21:10 +0000 (Do, 19 M?r 2009) | 6 lines Improve implementation with better underlying data structure for O(1) deletions. Big-Oh performance now the same as regular dictionaries. Uses a doubly-linked list instead of a list/seq to track insertion order. ........ r70471 | raymond.hettinger | 2009-03-19 19:19:03 +0000 (Do, 19 M?r 2009) | 3 lines Issue 5381: Add object_pairs_hook to the json module. ........ r70472 | raymond.hettinger | 2009-03-19 19:24:43 +0000 (Do, 19 M?r 2009) | 1 line Silence a compiler warning. ........ r70473 | raymond.hettinger | 2009-03-19 19:59:58 +0000 (Do, 19 M?r 2009) | 6 lines * Add clearer comment to initialization code. * Add optional argument to popitem() -- modeled after Anthon van der Neut's C version. * Fix method markup in docs. ........ r70475 | raymond.hettinger | 2009-03-19 23:12:41 +0000 (Do, 19 M?r 2009) | 6 lines * Add implementation notes. * Re-order methods so that those touching the underlying data structure come first and the derived methods come last. ........ r70477 | raymond.hettinger | 2009-03-19 23:22:25 +0000 (Do, 19 M?r 2009) | 1 line Fix typo ........ r70479 | mark.dickinson | 2009-03-20 15:51:55 +0000 (Fr, 20 M?r 2009) | 3 lines Issue #4258: Use 30-bit digits for Python longs, on 64-bit platforms. Backport of r70459. ........ r70485 | raymond.hettinger | 2009-03-20 18:25:49 +0000 (Fr, 20 M?r 2009) | 1 line Add MutableSet example. ........ r70489 | mark.dickinson | 2009-03-20 23:16:14 +0000 (Fr, 20 M?r 2009) | 4 lines Rewrite Py_ARITHMETIC_RIGHT_SHIFT so that it's valid for all signed integer types T, not just those for which "unsigned T" is legal. ........ r70533 | raymond.hettinger | 2009-03-23 00:08:09 +0000 (Mo, 23 M?r 2009) | 6 lines Add more comments. Improve variable names. Make links clearer by using a Link object instead of a list. Use proxy links to avoid circular references. ........ r70538 | raymond.hettinger | 2009-03-23 04:42:18 +0000 (Mo, 23 M?r 2009) | 1 line Move initialization of root link to __init__. ........ r70542 | mark.dickinson | 2009-03-23 18:25:13 +0000 (Mo, 23 M?r 2009) | 14 lines Issue #5512: speed up the long division algorithm for Python longs. The basic algorithm remains the same; the most significant speedups come from the following three changes: (1) normalize by shifting instead of multiplying and dividing (2) the old algorithm usually did an unnecessary extra iteration of the outer loop; remove this. As a special case, this means that long divisions with a single-digit result run twice as fast as before. (3) make inner loop much tighter. Various benchmarks show speedups of between 50% and 150% for long integer divisions and modulo operations. ........ r70544 | raymond.hettinger | 2009-03-23 18:26:59 +0000 (Mo, 23 M?r 2009) | 1 line Make imported name private and wrap long-line. ........ r70546 | antoine.pitrou | 2009-03-23 18:41:45 +0000 (Mo, 23 M?r 2009) | 9 lines Issue #4688: Add a heuristic so that tuples and dicts containing only untrackable objects are not tracked by the garbage collector. This can reduce the size of collections and therefore the garbage collection overhead on long-running programs, depending on their particular use of datatypes. (trivia: this makes the "binary_trees" benchmark from the Computer Language Shootout 40% faster) ........ r70550 | antoine.pitrou | 2009-03-23 19:17:00 +0000 (Mo, 23 M?r 2009) | 3 lines The tracking statistics were actually too pessimistic ........ r70552 | benjamin.peterson | 2009-03-23 20:47:59 +0000 (Mo, 23 M?r 2009) | 1 line fix very old names for exception terms #5543 ........ r70553 | benjamin.peterson | 2009-03-23 21:23:30 +0000 (Mo, 23 M?r 2009) | 1 line revert r70552; wrong fix ........ r70554 | benjamin.peterson | 2009-03-23 21:25:15 +0000 (Mo, 23 M?r 2009) | 1 line complain when there's no last exception ........ r70555 | benjamin.peterson | 2009-03-23 21:50:21 +0000 (Mo, 23 M?r 2009) | 4 lines implement test skipping and expected failures patch by myself #1034053 ........ r70558 | benjamin.peterson | 2009-03-23 22:29:45 +0000 (Mo, 23 M?r 2009) | 4 lines comply with the evilJavaNamingScheme for attribute names It seems my love of PEP 8 overrode the need for consistentcy ........ r70561 | benjamin.peterson | 2009-03-23 23:10:14 +0000 (Mo, 23 M?r 2009) | 1 line refactor unittest docs ........ r70562 | benjamin.peterson | 2009-03-23 23:13:36 +0000 (Mo, 23 M?r 2009) | 1 line forgot to document that setUp can be skipped (silly me...) ........ r70563 | benjamin.peterson | 2009-03-23 23:19:03 +0000 (Mo, 23 M?r 2009) | 1 line update from CVS ........ r70564 | raymond.hettinger | 2009-03-24 00:17:11 +0000 (Di, 24 M?r 2009) | 1 line Add links to related resources. ........ r70568 | benjamin.peterson | 2009-03-24 00:35:20 +0000 (Di, 24 M?r 2009) | 1 line some cleanup and modernization ........ r70569 | benjamin.peterson | 2009-03-24 00:36:16 +0000 (Di, 24 M?r 2009) | 1 line remove special metadata ........ r70570 | benjamin.peterson | 2009-03-24 00:37:12 +0000 (Di, 24 M?r 2009) | 1 line update docstring ........ r70571 | benjamin.peterson | 2009-03-24 00:39:24 +0000 (Di, 24 M?r 2009) | 1 line add new skipping things to __all__ ........ r70574 | benjamin.peterson | 2009-03-24 01:11:37 +0000 (Di, 24 M?r 2009) | 1 line fix typo ........ r70578 | benjamin.peterson | 2009-03-24 03:24:56 +0000 (Di, 24 M?r 2009) | 1 line this is better written using assertRaises ........ r70588 | benjamin.peterson | 2009-03-24 22:56:32 +0000 (Di, 24 M?r 2009) | 1 line fix newline issue in test summary ........ r70589 | benjamin.peterson | 2009-03-24 23:07:07 +0000 (Di, 24 M?r 2009) | 1 line another style nit ........ r70598 | benjamin.peterson | 2009-03-25 21:24:04 +0000 (Mi, 25 M?r 2009) | 1 line add shorthands for expected failures and unexpected success ........ r70599 | benjamin.peterson | 2009-03-25 21:42:51 +0000 (Mi, 25 M?r 2009) | 1 line this can be slightly less ugly ........ r70601 | raymond.hettinger | 2009-03-25 22:41:32 +0000 (Mi, 25 M?r 2009) | 1 line Separate initialization from clearing. ........ r70605 | benjamin.peterson | 2009-03-26 16:32:23 +0000 (Do, 26 M?r 2009) | 1 line remove uneeded function ........ r70611 | benjamin.peterson | 2009-03-26 18:35:37 +0000 (Do, 26 M?r 2009) | 1 line add much better tests for python version information parsing ........ r70612 | benjamin.peterson | 2009-03-26 18:55:48 +0000 (Do, 26 M?r 2009) | 1 line more and more implementations now support sys.subversion ........ r70613 | benjamin.peterson | 2009-03-26 18:58:30 +0000 (Do, 26 M?r 2009) | 1 line roll old test in with new one ........ r70614 | benjamin.peterson | 2009-03-26 19:09:21 +0000 (Do, 26 M?r 2009) | 1 line add support for PyPy ........ r70615 | benjamin.peterson | 2009-03-26 19:58:18 +0000 (Do, 26 M?r 2009) | 5 lines add some useful utilities for skipping tests with unittest's new skipping ability most significantly apply a modified portion of the patch from #4242 with patches for skipping implementation details ........ r70616 | benjamin.peterson | 2009-03-26 20:05:50 +0000 (Do, 26 M?r 2009) | 1 line rename TestCase.skip() to skipTest() because it causes annoying problems with trial #5571 ........ r70617 | benjamin.peterson | 2009-03-26 20:17:27 +0000 (Do, 26 M?r 2009) | 1 line apply the second part of #4242's patch; classify all the implementation details in test_descr ........ r70618 | benjamin.peterson | 2009-03-26 20:48:25 +0000 (Do, 26 M?r 2009) | 1 line remove test_support.TestSkipped and just use unittest.SkipTest ........ r70619 | benjamin.peterson | 2009-03-26 20:49:40 +0000 (Do, 26 M?r 2009) | 1 line fix naming ........ r70620 | benjamin.peterson | 2009-03-26 21:10:30 +0000 (Do, 26 M?r 2009) | 1 line fix incorrect auto-translation of TestSkipped -> unittest.SkipTest ........ r70621 | benjamin.peterson | 2009-03-26 21:11:16 +0000 (Do, 26 M?r 2009) | 1 line must pass argument to get expected behavior ;) ........ r70623 | benjamin.peterson | 2009-03-26 21:30:10 +0000 (Do, 26 M?r 2009) | 1 line add missing import ........ r70624 | benjamin.peterson | 2009-03-26 21:30:54 +0000 (Do, 26 M?r 2009) | 1 line ** is required here ........ r70626 | benjamin.peterson | 2009-03-26 21:40:29 +0000 (Do, 26 M?r 2009) | 1 line update email tests to use SkipTest ........ r70627 | benjamin.peterson | 2009-03-26 21:44:43 +0000 (Do, 26 M?r 2009) | 1 line fix another name ........ r70641 | guilherme.polo | 2009-03-27 21:43:08 +0000 (Fr, 27 M?r 2009) | 3 lines Adjusted _tkinter to compile without warnings when WITH_THREAD is not defined (part of issue #5035) ........ r70647 | antoine.pitrou | 2009-03-28 19:10:13 +0000 (Sa, 28 M?r 2009) | 3 lines Publicize the GC untracking optimization ........ r70651 | guilherme.polo | 2009-03-28 19:17:16 +0000 (Sa, 28 M?r 2009) | 1 line Typo fix ........ r70652 | antoine.pitrou | 2009-03-28 19:17:54 +0000 (Sa, 28 M?r 2009) | 3 lines Fix a typo and be more specific ........ r70668 | benjamin.peterson | 2009-03-29 03:16:57 +0000 (So, 29 M?r 2009) | 1 line a more realistic example ........ r70669 | benjamin.peterson | 2009-03-29 03:31:40 +0000 (So, 29 M?r 2009) | 1 line stop the versionchanged directive from hiding the docs ........ r70671 | benjamin.peterson | 2009-03-29 03:39:58 +0000 (So, 29 M?r 2009) | 1 line fix consistency ........ r70672 | collin.winter | 2009-03-29 03:44:19 +0000 (So, 29 M?r 2009) | 4 lines Add the ability to control the random seed used by regrtest.py -r. This adds a --randseed option, and makes regrtest.py -r indicate what random seed it's using so that that value can later be fed back to --randseed. This option is useful for tracking down test order-related issues found by make buildbottest, for example. ........ r70674 | guilherme.polo | 2009-03-29 10:19:05 +0000 (So, 29 M?r 2009) | 1 line Typo fix. ........ r70691 | raymond.hettinger | 2009-03-29 18:51:11 +0000 (So, 29 M?r 2009) | 1 line Make life easier for non-CPython implementations. ........ r70698 | benjamin.peterson | 2009-03-29 21:31:05 +0000 (So, 29 M?r 2009) | 1 line thanks to guido's bytecode verifier, this is fixed ........ r70700 | benjamin.peterson | 2009-03-29 21:50:14 +0000 (So, 29 M?r 2009) | 1 line use the awesome new status iterator ........ r70701 | benjamin.peterson | 2009-03-29 22:27:26 +0000 (So, 29 M?r 2009) | 1 line add missing import ........ r70702 | bob.ippolito | 2009-03-29 22:33:58 +0000 (So, 29 M?r 2009) | 1 line Issue 5381: fix regression in pure python code path, Issue 5584: fix a decoder bug for unicode float literals outside of a container ........ r70703 | benjamin.peterson | 2009-03-30 02:14:21 +0000 (Mo, 30 M?r 2009) | 1 line fix import ........ r70706 | benjamin.peterson | 2009-03-30 14:42:23 +0000 (Mo, 30 M?r 2009) | 1 line add missing import ........ r70711 | r.david.murray | 2009-03-30 15:14:01 +0000 (Mo, 30 M?r 2009) | 2 lines Convert import try/except to use test_support.import_module(). ........ r70712 | benjamin.peterson | 2009-03-30 15:15:38 +0000 (Mo, 30 M?r 2009) | 1 line don't rely on the order dict repr #5605 ........ r70716 | r.david.murray | 2009-03-30 15:30:34 +0000 (Mo, 30 M?r 2009) | 2 lines Revert incorrect change. ........ r70734 | r.david.murray | 2009-03-30 19:04:00 +0000 (Mo, 30 M?r 2009) | 7 lines Add import_function method to test.test_support, and modify a number of tests that expect to be skipped if imports fail or functions don't exist to use import_function and import_module. The ultimate goal is to change regrtest to not skip automatically on ImportError. Checking in now to make sure the buldbots don't show any errors on platforms I can't direct test on. ........ r70735 | ronald.oussoren | 2009-03-30 19:22:56 +0000 (Mo, 30 M?r 2009) | 3 lines Remove usage of the deprecated '-cString' and '+stringWithCString:' API's in PythonLauncher, replacing them with the correct counterparts. ........ r70747 | r.david.murray | 2009-03-30 20:04:06 +0000 (Mo, 30 M?r 2009) | 3 lines Remove references to test_socket_ssl which was deleted in trunk in r64392 and py3k in r59038. ........ r70757 | senthil.kumaran | 2009-03-30 21:51:50 +0000 (Mo, 30 M?r 2009) | 3 lines Fix for bugs: Issue4675 and Issue4962. ........ r70770 | andrew.kuchling | 2009-03-30 22:30:20 +0000 (Mo, 30 M?r 2009) | 1 line Add several items and placeholders ........ r70771 | andrew.kuchling | 2009-03-30 22:31:11 +0000 (Mo, 30 M?r 2009) | 1 line Many edits ........ r70772 | barry.warsaw | 2009-03-30 22:42:17 +0000 (Mo, 30 M?r 2009) | 5 lines A fix for issue 1974, inspired by the patch from Andi Albrecht (aalbrecht), though with some changes by me. This patch should not be back ported or forward ported. It's a bit too risky for 2.6 and 3.x does things fairly differently. ........ r70775 | r.david.murray | 2009-03-30 23:05:48 +0000 (Mo, 30 M?r 2009) | 4 lines Change more tests to use import_module for the modules that should cause tests to be skipped. Also rename import_function to the more descriptive get_attribute and add a docstring. ........ r70777 | andrew.kuchling | 2009-03-30 23:09:46 +0000 (Mo, 30 M?r 2009) | 1 line Add more items ........ r70778 | ronald.oussoren | 2009-03-30 23:10:35 +0000 (Mo, 30 M?r 2009) | 4 lines Fix issue #4865: add /Library/Python/2.7/site-packages to sys.path on OSX, to make it easier to share (some) installed packages between the system install and a user install. ........ r70779 | r.david.murray | 2009-03-30 23:10:37 +0000 (Mo, 30 M?r 2009) | 3 lines Actually suppress warnings in test_at_least_import_untested_modules inside the catch_warnings context manager. ........ r70788 | andrew.kuchling | 2009-03-31 01:21:01 +0000 (Di, 31 M?r 2009) | 1 line Add various items ........ r70807 | jeremy.hylton | 2009-03-31 13:31:00 +0000 (Di, 31 M?r 2009) | 2 lines Update quicktest to match Python 3 branch ........ r70821 | jeremy.hylton | 2009-03-31 15:04:15 +0000 (Di, 31 M?r 2009) | 2 lines Add check for PyDict_Update() error. ........ r70837 | gregory.p.smith | 2009-03-31 16:54:10 +0000 (Di, 31 M?r 2009) | 9 lines The unittest.TestCase.assertEqual() now displays the differences in lists, tuples, dicts and sets on failure. Many new handy type and comparison specific assert* methods have been added that fail with error messages actually useful for debugging. Contributed in by Google and completed with help from mfoord and GvR at PyCon 2009 sprints. Discussion lives in http://bugs.python.org/issue2578. ........ r70844 | raymond.hettinger | 2009-03-31 17:47:06 +0000 (Di, 31 M?r 2009) | 1 line Per the language summit, the optional fastpath imports should use from-import-star. ........ r70856 | r.david.murray | 2009-03-31 18:32:17 +0000 (Di, 31 M?r 2009) | 7 lines A few more test skips via import_module, and change import_module to return the error message produced by importlib, so that if an import in the package whose import is being wrapped is what failed the skip message will contain the name of that module instead of the name of the wrapped module. Also fixed formatting of some previous comments. ........ r70864 | gregory.p.smith | 2009-03-31 19:03:28 +0000 (Di, 31 M?r 2009) | 10 lines Rename the actual method definitions to the official assertFoo names. Adds unittests to make sure the old fail* names continue to work now and adds a comment that they are pending deprecation. Also adds a test to confirm that the plural Equals method variants continue to exist even though we're unlikely to deprecate those. http://bugs.python.org/issue2578 ........ r70869 | georg.brandl | 2009-03-31 19:14:42 +0000 (Di, 31 M?r 2009) | 1 line Fix-up unwanted change. ........ r70872 | r.david.murray | 2009-03-31 19:31:17 +0000 (Di, 31 M?r 2009) | 3 lines Delete out-of-date and little-known README from the test directory by consensus of devs at pycon sprint. ........ r70874 | r.david.murray | 2009-03-31 19:33:15 +0000 (Di, 31 M?r 2009) | 5 lines Improve test_support.import_module docstring, remove deprecated flag from get_attribute since it isn't likely to do anything useful. ........ r70876 | r.david.murray | 2009-03-31 19:49:15 +0000 (Di, 31 M?r 2009) | 4 lines Remove the regrtest check that turns any ImportError into a skipped test. Hopefully all modules whose imports legitimately result in a skipped test have been properly wrapped by the previous commits. ........ r70877 | r.david.murray | 2009-03-31 19:57:24 +0000 (Di, 31 M?r 2009) | 2 lines Add NEWS entry for regrtest change. ........ r70878 | gregory.p.smith | 2009-03-31 19:59:14 +0000 (Di, 31 M?r 2009) | 3 lines Issue an actual PendingDeprecationWarning for the TestCase.fail* methods. Document the deprecation. ........ r70883 | georg.brandl | 2009-03-31 20:41:08 +0000 (Di, 31 M?r 2009) | 1 line #1674032: return value of flag from Event.wait(). OKed by Guido. ........ r70885 | tarek.ziade | 2009-03-31 20:48:31 +0000 (Di, 31 M?r 2009) | 1 line using log.warn for sys.stderr ........ r70886 | tarek.ziade | 2009-03-31 20:50:59 +0000 (Di, 31 M?r 2009) | 1 line added tests for the clean command ........ r70888 | tarek.ziade | 2009-03-31 20:53:13 +0000 (Di, 31 M?r 2009) | 1 line more tests for the register command ........ r70889 | tarek.ziade | 2009-03-31 20:53:55 +0000 (Di, 31 M?r 2009) | 1 line more tests for the upload command ........ r70890 | tarek.ziade | 2009-03-31 20:54:38 +0000 (Di, 31 M?r 2009) | 1 line added test to the install_data command ........ r70891 | tarek.ziade | 2009-03-31 20:55:21 +0000 (Di, 31 M?r 2009) | 1 line added tests to the install_headers command ........ r70892 | tarek.ziade | 2009-03-31 20:56:11 +0000 (Di, 31 M?r 2009) | 1 line making sdist and config test silents ........ r70894 | benjamin.peterson | 2009-03-31 21:06:30 +0000 (Di, 31 M?r 2009) | 1 line take the usual lock precautions around _active_limbo_lock ........ r70901 | georg.brandl | 2009-03-31 21:40:24 +0000 (Di, 31 M?r 2009) | 2 lines Remove warning about pending Win9x support removal. ........ r70903 | georg.brandl | 2009-03-31 21:45:18 +0000 (Di, 31 M?r 2009) | 1 line #1676135: remove trailing slashes from --prefix argument. ........ r70910 | tarek.ziade | 2009-03-31 22:27:23 +0000 (Di, 31 M?r 2009) | 1 line #5583 Added optional Extensions in Distutils ........ r70918 | raymond.hettinger | 2009-03-31 22:43:03 +0000 (Di, 31 M?r 2009) | 1 line Improve examples for collections.deque() ........ r70920 | tarek.ziade | 2009-03-31 22:44:10 +0000 (Di, 31 M?r 2009) | 1 line catching msvc9compiler error as well ........ r70922 | tarek.ziade | 2009-03-31 22:47:01 +0000 (Di, 31 M?r 2009) | 1 line fixed the test for win32 CompileError ........ r70930 | r.david.murray | 2009-03-31 23:45:39 +0000 (Di, 31 M?r 2009) | 3 lines Fix Windows test skip error revealed by buildbot. Also a comment spelling correction in a previously fixed test. ........ r70931 | jack.diederich | 2009-03-31 23:46:48 +0000 (Di, 31 M?r 2009) | 1 line #5228: add pickle support to functools.partial ........ r70936 | r.david.murray | 2009-04-01 03:21:43 +0000 (Mi, 01 Apr 2009) | 4 lines Fix issue 2522. locale.format now checks that it is passed exactly one pattern, which avoids mysterious errors where it had seemed to fail to do localization. ........ r70939 | jesse.noller | 2009-04-01 03:45:50 +0000 (Mi, 01 Apr 2009) | 1 line Fix multiprocessing.event to match the new threading.Event API ........ r70951 | georg.brandl | 2009-04-01 14:02:27 +0000 (Mi, 01 Apr 2009) | 1 line Add Maksim, who worked on several issues at the sprint. ........ r70956 | brett.cannon | 2009-04-01 16:00:34 +0000 (Mi, 01 Apr 2009) | 5 lines The cgitb module had imports in its functions. This can cause deadlock with the import lock if called from within a thread that was triggered by an import. Partially fixes issue #1665206. ........ r70958 | kristjan.jonsson | 2009-04-01 16:08:34 +0000 (Mi, 01 Apr 2009) | 3 lines http://bugs.python.org/issue5623 Dynamically discoverd the size of the ioinfo struct used by the crt for its file descriptors. This should work across all flavors of the CRT. Thanks to Amaury Forgeot d'Arc Needs porting to 3.1 ........ r70965 | brett.cannon | 2009-04-01 18:03:59 +0000 (Mi, 01 Apr 2009) | 5 lines _warnings was importing itself to get an attribute. That's bad if warnings gets called in a thread that was spawned by an import itself. Last part to close #1665206. ........ r70968 | michael.foord | 2009-04-01 18:25:38 +0000 (Mi, 01 Apr 2009) | 1 line Adding Wing project file ........ r70969 | raymond.hettinger | 2009-04-01 18:50:56 +0000 (Mi, 01 Apr 2009) | 1 line Issue #5647: MutableSet.__iand__() no longer mutates self during iteration. ........ r70975 | brett.cannon | 2009-04-01 19:57:10 +0000 (Mi, 01 Apr 2009) | 4 lines test_logging was blindly clearing the warnings filter. This caused PendingDeprecationWarnings to be spewed all over by unittest.failIf*(). Fix moves over to using warnings.catch_warning to protect the warnings filter. ........ r70979 | brett.cannon | 2009-04-01 20:25:48 +0000 (Mi, 01 Apr 2009) | 3 lines test_warnings ironically had a single test that was not protecting the warnings filter and was resetting it. ........ r70980 | jack.diederich | 2009-04-01 20:26:13 +0000 (Mi, 01 Apr 2009) | 3 lines bounds check arguments to mmap.move(). All of them. Really. fixes crasher on OS X 10.5 ........ r70981 | senthil.kumaran | 2009-04-01 20:26:33 +0000 (Mi, 01 Apr 2009) | 3 lines Fix for issue5040. Adding test for Content-Length ........ r70986 | raymond.hettinger | 2009-04-01 20:50:58 +0000 (Mi, 01 Apr 2009) | 1 line Add link to an alternative generator with a long-period. ........ r70992 | georg.brandl | 2009-04-01 21:00:55 +0000 (Mi, 01 Apr 2009) | 1 line #4572: add SEEK_* values as constants in io.py. ........ r70993 | georg.brandl | 2009-04-01 21:05:44 +0000 (Mi, 01 Apr 2009) | 1 line Add NEWS item. ........ r70994 | georg.brandl | 2009-04-01 21:06:30 +0000 (Mi, 01 Apr 2009) | 1 line Revert accidental checkin. ........ r70995 | benjamin.peterson | 2009-04-01 21:12:54 +0000 (Mi, 01 Apr 2009) | 1 line add seek constants to __all__ ........ r70997 | r.david.murray | 2009-04-01 21:26:18 +0000 (Mi, 01 Apr 2009) | 3 lines Add tests checking the CSV module's ability to handle embedded newlines in quoted field values. ........ Modified: python/branches/release26-maint/ (props changed) From python-checkins at python.org Wed May 19 01:58:07 2010 From: python-checkins at python.org (georg.brandl) Date: Wed, 19 May 2010 01:58:07 +0200 (CEST) Subject: [Python-checkins] r81313 - python/branches/release26-maint Message-ID: <20100518235807.02D51BF1D@mail.python.org> Author: georg.brandl Date: Wed May 19 01:58:06 2010 New Revision: 81313 Log: Blocked revisions 71004,71006,71009,71014,71019,71022-71024,71029,71031-71033,71036,71041,71043,71059,71070,71073,71075,71078,71082,71101,71119,71126-71127,71175,71206,71208,71210,71221,71229,71237,71253,71255,71263,71266,71271,71286,71291,71295,71300,71302-71303,71361,71365,71367,71370,71377,71385,71389,71392,71395-71396,71405-71406,71408,71414,71419,71430,71435,71448,71462,71465,71473,71478,71485,71492,71494,71498,71503,71507,71509,71513,71523,71528,71533,71539,71560,71569,71585,71589,71657,71662,71674,71696,71710,71715,71719,71721,71729,71740,71750,71766,71771-71772,71776,71780,71785,71788,71794,71796,71799,71802,71808,71824,71827,71832,71837-71838,71842,71853,71869,71878,71904,71906,71938,71955,71960-71961,71963,71969,71976 via svnmerge ........ r71004 | benjamin.peterson | 2009-04-01 23:15:49 +0000 (Mi, 01 Apr 2009) | 1 line remove double underscores ........ r71006 | georg.brandl | 2009-04-01 23:32:17 +0000 (Mi, 01 Apr 2009) | 1 line Cache the f_locals dict of the current frame, since every access to frame.f_locals overrides its contents with the real locals which undoes modifications made by the debugging user. ........ r71009 | jesse.noller | 2009-04-02 00:03:28 +0000 (Do, 02 Apr 2009) | 1 line issue5545: Switch to Autoconf for multiprocessing; special thanks to Martin Lowis for help ........ r71014 | benjamin.peterson | 2009-04-02 01:03:17 +0000 (Do, 02 Apr 2009) | 1 line handle SEEK_ constants in test_io ........ r71019 | georg.brandl | 2009-04-02 02:00:01 +0000 (Do, 02 Apr 2009) | 1 line Fix test_doctest, missed two assignments to curframe. ........ r71022 | jesse.noller | 2009-04-02 02:32:55 +0000 (Do, 02 Apr 2009) | 1 line Issue 3110: Additional protection for SEM_VALUE_MAX on platforms, thanks to Martin Loewis ........ r71023 | kurt.kaiser | 2009-04-02 02:44:54 +0000 (Do, 02 Apr 2009) | 3 lines Remove port spec from run.py and fix bug where subprocess fails to extract port from command line when warnings are present. ........ r71024 | georg.brandl | 2009-04-02 02:47:44 +0000 (Do, 02 Apr 2009) | 4 lines In PyErr_GivenExceptionMatches, temporarily bump the recursion limit, so that in the most common case PyObject_IsSubclass will not raise a recursion error we have to ignore anyway. ........ r71029 | senthil.kumaran | 2009-04-02 03:00:34 +0000 (Do, 02 Apr 2009) | 3 lines Fixing the issue4860. Escaping embedded '"' character in js_output() method of Morsel. ........ r71031 | brett.cannon | 2009-04-02 03:17:39 +0000 (Do, 02 Apr 2009) | 6 lines PyImport_AppendInittab() took a char * as a first argument even though that string was stored beyond the life of the call. Changed the signature to be const char * to help make this point. Closes issue #1419652. ........ r71032 | michael.foord | 2009-04-02 03:20:38 +0000 (Do, 02 Apr 2009) | 13 lines Better exception messages for unittest assert methods. - unittest.assertNotEqual() now uses the inequality operator (!=) instead of the equality operator. - Default assertTrue and assertFalse messages are now useful. - TestCase has a longMessage attribute. This defaults to False, but if set to True useful error messages are shown in addition to explicit messages passed to assert methods. Issue #5663 ........ r71033 | brett.cannon | 2009-04-02 03:34:53 +0000 (Do, 02 Apr 2009) | 3 lines Fix two issues introduced by issue #71031 by changing the signature of PyImport_AppendInittab() to take a const char *. ........ r71036 | jesse.noller | 2009-04-02 04:22:09 +0000 (Do, 02 Apr 2009) | 1 line Issue 3551: Raise ValueError if the size causes ERROR_NO_SYSTEM_RESOURCES ........ r71041 | jesse.noller | 2009-04-02 05:17:26 +0000 (Do, 02 Apr 2009) | 1 line Add custom initializer argument to multiprocess.Manager*, courtesy of lekma ........ r71043 | michael.foord | 2009-04-02 05:51:54 +0000 (Do, 02 Apr 2009) | 7 lines Store the functions in the _type_equality_funcs as wrapped objects that are deep copyable. This allows for the deep copying of TestCase instances. Issue 5660 ........ r71059 | mark.dickinson | 2009-04-02 18:39:37 +0000 (Do, 02 Apr 2009) | 2 lines sys.long_info attributes should be ints, not longs ........ r71070 | antoine.pitrou | 2009-04-02 21:18:34 +0000 (Do, 02 Apr 2009) | 3 lines Issue #2396: backport the memoryview object. ........ r71073 | raymond.hettinger | 2009-04-02 22:25:40 +0000 (Do, 02 Apr 2009) | 4 lines Have namedtuple's field renamer assign names that are consistent with the corresponding tuple index. ........ r71075 | raymond.hettinger | 2009-04-02 22:34:17 +0000 (Do, 02 Apr 2009) | 1 line Update docs for namedtuple's renaming change. ........ r71078 | raymond.hettinger | 2009-04-03 02:43:54 +0000 (Fr, 03 Apr 2009) | 4 lines Localize the function lookup in timeit. ........ r71082 | hirokazu.yamamoto | 2009-04-03 03:54:08 +0000 (Fr, 03 Apr 2009) | 1 line Fixed compile error on windows. ........ r71101 | andrew.kuchling | 2009-04-03 21:43:00 +0000 (Fr, 03 Apr 2009) | 1 line Add some items ........ r71119 | raymond.hettinger | 2009-04-04 05:37:47 +0000 (Sa, 04 Apr 2009) | 1 line Add helpful link. ........ r71126 | kurt.kaiser | 2009-04-04 07:03:48 +0000 (Sa, 04 Apr 2009) | 5 lines Allow multiple IDLE GUI/subprocess pairs to exist simultaneously. Thanks to David Scherer for suggesting the use of an ephemeral port for the GUI. Patch 1529142 Weeble. ........ r71127 | raymond.hettinger | 2009-04-04 08:46:58 +0000 (Sa, 04 Apr 2009) | 1 line Replace the localized min/max calls with normal if/else ........ r71175 | hirokazu.yamamoto | 2009-04-04 17:20:05 +0000 (Sa, 04 Apr 2009) | 1 line No behavior change. ........ r71206 | benjamin.peterson | 2009-04-05 01:04:38 +0000 (So, 05 Apr 2009) | 1 line compare types with is ........ r71208 | michael.foord | 2009-04-05 01:15:01 +0000 (So, 05 Apr 2009) | 4 lines Change the way unittest.TestSuite use their tests to always access them through iteration. Non behavior changing, this allows you to create custom subclasses that override __iter__. Issue #5693 ........ r71210 | guilherme.polo | 2009-04-05 02:11:19 +0000 (So, 05 Apr 2009) | 1 line Include tkinter.h only after including tk.h (or the equivalent for another platform). ........ r71221 | vinay.sajip | 2009-04-05 11:06:24 +0000 (So, 05 Apr 2009) | 1 line Issue #5695: Moved logging.captureWarnings() call inside with statement in WarningsTest.test_warnings. ........ r71229 | matthias.klose | 2009-04-05 12:43:08 +0000 (So, 05 Apr 2009) | 3 lines - Py_DECREF: Add `do { ... } while (0)' to avoid compiler warnings. (avoiding brown paper typo this time) ........ r71237 | georg.brandl | 2009-04-05 14:24:52 +0000 (So, 05 Apr 2009) | 1 line #1326077: fix traceback formatting of SyntaxErrors. This fixes two differences with formatting coming from Python: a) the reproduction of location details in the error message if no line text is given, b) the prefixing of the last line by one space. ........ r71253 | tarek.ziade | 2009-04-05 18:31:24 +0000 (So, 05 Apr 2009) | 1 line Fixed 5694: removed spurious test output in Distutils ........ r71255 | georg.brandl | 2009-04-05 18:34:58 +0000 (So, 05 Apr 2009) | 1 line #602893: add indicator for current line in cgitb that doesnt rely on styling alone. ........ r71263 | michael.foord | 2009-04-05 19:19:28 +0000 (So, 05 Apr 2009) | 4 lines Adding assertIs and assertIsNot methods to unittest.TestCase Issue #2578 ........ r71266 | georg.brandl | 2009-04-05 20:23:13 +0000 (So, 05 Apr 2009) | 1 line Normalize issue referencing style. ........ r71271 | matthias.klose | 2009-04-05 21:19:13 +0000 (So, 05 Apr 2009) | 3 lines Issue #1113244: Py_XINCREF, Py_DECREF, Py_XDECREF: Add `do { ... } while (0)' to avoid compiler warnings. ........ r71286 | tarek.ziade | 2009-04-05 22:04:38 +0000 (So, 05 Apr 2009) | 1 line added a simplest test to distutils.spawn._nt_quote_args ........ r71291 | tarek.ziade | 2009-04-05 22:51:09 +0000 (So, 05 Apr 2009) | 1 line Fixed #5095: msi missing from Distutils bdist formats ........ r71295 | tarek.ziade | 2009-04-05 23:03:10 +0000 (So, 05 Apr 2009) | 1 line pep8-fied method names ........ r71300 | gregory.p.smith | 2009-04-05 23:48:26 +0000 (So, 05 Apr 2009) | 2 lines news entry for r71299. ........ r71302 | jack.diederich | 2009-04-06 02:08:44 +0000 (Mo, 06 Apr 2009) | 1 line test the telnetlib.Telnet interface more thoroughly ........ r71303 | gregory.p.smith | 2009-04-06 06:33:26 +0000 (Mo, 06 Apr 2009) | 3 lines - Issue #2254: Fix CGIHTTPServer information disclosure. Relative paths are now collapsed within the url properly before looking in cgi_directories. ........ r71361 | benjamin.peterson | 2009-04-07 15:15:04 +0000 (Di, 07 Apr 2009) | 1 line fix syntax tests after formatting change ........ r71365 | benjamin.peterson | 2009-04-07 15:52:05 +0000 (Di, 07 Apr 2009) | 1 line fix since difference formating of SyntaxErrors ........ r71367 | benjamin.peterson | 2009-04-07 16:03:04 +0000 (Di, 07 Apr 2009) | 1 line revert unrelated change to test_telnetlib ........ r71370 | vinay.sajip | 2009-04-07 17:18:24 +0000 (Di, 07 Apr 2009) | 1 line Issue #5695: Minor tweak to improve the code as suggested by Brett Cannon and as implemented in the Py3K branch. ........ r71377 | jack.diederich | 2009-04-07 20:22:59 +0000 (Di, 07 Apr 2009) | 1 line eliminate more race conditions in telnetlib tests ........ r71385 | jack.diederich | 2009-04-07 23:56:57 +0000 (Di, 07 Apr 2009) | 4 lines - Make timing assertions very generous (a la test_timeout.py) - Break the gc cycle in negotiation tests - test the different guarantees of read_lazy and read_very_lazy ........ r71389 | raymond.hettinger | 2009-04-08 05:39:38 +0000 (Mi, 08 Apr 2009) | 1 line Add docstrings. ........ r71392 | raymond.hettinger | 2009-04-08 08:26:55 +0000 (Mi, 08 Apr 2009) | 1 line Minor factoring. ........ r71395 | benjamin.peterson | 2009-04-08 13:27:29 +0000 (Mi, 08 Apr 2009) | 1 line these must be installed to correctly run tests ........ r71396 | benjamin.peterson | 2009-04-08 13:29:41 +0000 (Mi, 08 Apr 2009) | 1 line fix syntax ........ r71405 | andrew.kuchling | 2009-04-09 11:22:47 +0000 (Do, 09 Apr 2009) | 1 line Add items ........ r71406 | andrew.kuchling | 2009-04-09 11:23:36 +0000 (Do, 09 Apr 2009) | 1 line Typo fixes ........ r71408 | collin.winter | 2009-04-09 16:46:46 +0000 (Do, 09 Apr 2009) | 11 lines Issue 5665: add more pickling tests. - Add tests for the module-level load() and dump() functions. - Add tests for cPickle's internal data structures, stressing workloads with many gets/puts. - Add tests for the Pickler and Unpickler classes, in particular the memo attribute. - test_xpickle is extended to test backwards compatibility with Python 2.4, 2.5 and 2.6 by round-tripping pickled objects through a worker process. This is guarded with a regrtest -u xpickle resource. ........ r71414 | r.david.murray | 2009-04-09 21:54:50 +0000 (Do, 09 Apr 2009) | 3 lines Issue #2170: refactored xml.dom.minidom.normalize, increasing both its clarity and its speed. ........ r71419 | raymond.hettinger | 2009-04-09 22:31:51 +0000 (Do, 09 Apr 2009) | 1 line Add note on using keyword arguments with OrderedDict. ........ r71430 | raymond.hettinger | 2009-04-10 04:25:45 +0000 (Fr, 10 Apr 2009) | 1 line Clarify the table entries for combinatorics. ........ r71435 | raymond.hettinger | 2009-04-10 06:38:39 +0000 (Fr, 10 Apr 2009) | 1 line Fix the count of datatypes. ........ r71448 | raymond.hettinger | 2009-04-10 13:16:50 +0000 (Fr, 10 Apr 2009) | 1 line Add examples. ........ r71462 | chris.withers | 2009-04-11 11:22:19 +0000 (Sa, 11 Apr 2009) | 2 lines remove unpleasant exec ........ r71465 | nick.coghlan | 2009-04-11 13:31:31 +0000 (Sa, 11 Apr 2009) | 1 line Issue 5354: Provide a standardised testing mechanism for doing fresh imports of modules, including the ability to block extension modules in order to test the pure Python fallbacks ........ r71473 | tarek.ziade | 2009-04-11 14:55:07 +0000 (Sa, 11 Apr 2009) | 1 line #5732: added the check command into Distutils ........ r71478 | tarek.ziade | 2009-04-11 15:14:17 +0000 (Sa, 11 Apr 2009) | 1 line testing a full check case ........ r71485 | andrew.kuchling | 2009-04-11 16:12:23 +0000 (Sa, 11 Apr 2009) | 1 line Add various items ........ r71492 | georg.brandl | 2009-04-11 18:19:27 +0000 (Sa, 11 Apr 2009) | 1 line Take credit for a patch of mine. ........ r71494 | benjamin.peterson | 2009-04-11 19:31:00 +0000 (Sa, 11 Apr 2009) | 1 line ignore py3_test_grammar when compiling the library ........ r71498 | benjamin.peterson | 2009-04-11 20:27:15 +0000 (Sa, 11 Apr 2009) | 1 line fix markup ........ r71503 | eric.smith | 2009-04-12 02:57:29 +0000 (So, 12 Apr 2009) | 1 line Take credit for my patch for issue 5237. ........ r71507 | georg.brandl | 2009-04-12 12:08:12 +0000 (So, 12 Apr 2009) | 1 line #5704: let python -3 imply -t as well. ........ r71509 | tarek.ziade | 2009-04-12 14:53:51 +0000 (So, 12 Apr 2009) | 1 line removed the print statements and added a test ........ r71513 | tarek.ziade | 2009-04-12 15:03:50 +0000 (So, 12 Apr 2009) | 1 line pep8-fied the module before adding tests ........ r71523 | tarek.ziade | 2009-04-12 16:31:24 +0000 (So, 12 Apr 2009) | 1 line added a simple test for search_cpp ........ r71528 | tarek.ziade | 2009-04-12 16:45:32 +0000 (So, 12 Apr 2009) | 1 line added a test for finalize_options ........ r71533 | tarek.ziade | 2009-04-12 17:02:08 +0000 (So, 12 Apr 2009) | 1 line removed string usage and added a test for _clean ........ r71539 | benjamin.peterson | 2009-04-12 20:24:56 +0000 (So, 12 Apr 2009) | 1 line remove useless import ........ r71560 | tarek.ziade | 2009-04-13 12:34:01 +0000 (Mo, 13 Apr 2009) | 1 line Fixed #5607: Distutils test_get_platform was failing fo Mac OS X fat binaries. ........ r71569 | tarek.ziade | 2009-04-13 12:42:26 +0000 (Mo, 13 Apr 2009) | 1 line deactivate test_search_cpp under win32 ........ r71585 | tarek.ziade | 2009-04-13 20:03:44 +0000 (Mo, 13 Apr 2009) | 1 line improved test coverage for distutils.cmd ........ r71589 | tarek.ziade | 2009-04-13 20:14:54 +0000 (Mo, 13 Apr 2009) | 1 line pep8-fied ........ r71657 | vinay.sajip | 2009-04-16 19:07:37 +0000 (Do, 16 Apr 2009) | 1 line Issue #5768: Change to Unicode output logic and test case for same. ........ r71662 | vinay.sajip | 2009-04-16 19:15:49 +0000 (Do, 16 Apr 2009) | 1 line Issue #5768: Change to Unicode output logic and test case for same. ........ r71674 | tarek.ziade | 2009-04-17 14:29:56 +0000 (Fr, 17 Apr 2009) | 1 line DistutilsSetupError was not raised when one single warning occured ........ r71696 | georg.brandl | 2009-04-18 08:26:21 +0000 (Sa, 18 Apr 2009) | 1 line "not subscriptable" should be a bit more understandable than "unsubscriptable". ........ r71710 | mark.dickinson | 2009-04-18 14:41:37 +0000 (Sa, 18 Apr 2009) | 2 lines Backport r71704 (add configure check for C99 round function) to trunk. ........ r71715 | mark.dickinson | 2009-04-18 14:59:42 +0000 (Sa, 18 Apr 2009) | 2 lines Issue #1869: Fix a couple of minor round() issues. ........ r71719 | benjamin.peterson | 2009-04-18 15:31:34 +0000 (Sa, 18 Apr 2009) | 1 line rename internal bytes_ functions to bytearray ........ r71721 | benjamin.peterson | 2009-04-18 19:26:19 +0000 (Sa, 18 Apr 2009) | 1 line fix a few nits in unittest.py #5771 ........ r71729 | benjamin.peterson | 2009-04-18 21:03:10 +0000 (Sa, 18 Apr 2009) | 1 line move test to a more appropiate one ........ r71740 | benjamin.peterson | 2009-04-19 03:02:54 +0000 (So, 19 Apr 2009) | 1 line fix typo ........ r71750 | mark.dickinson | 2009-04-19 17:10:47 +0000 (So, 19 Apr 2009) | 3 lines Automatic conversion of floats to integers for struct.pack integer codes is deprecated. Use an explicit int() instead. ........ r71766 | tarek.ziade | 2009-04-20 14:29:42 +0000 (Mo, 20 Apr 2009) | 1 line adding a NEWS note for #5795 (previously checked via the buildbot) ........ r71771 | raymond.hettinger | 2009-04-20 18:23:57 +0000 (Mo, 20 Apr 2009) | 1 line Fix typo ........ r71772 | mark.dickinson | 2009-04-20 21:13:33 +0000 (Mo, 20 Apr 2009) | 5 lines Issue #3166: Make long -> float (and int -> float) conversions correctly rounded, using round-half-to-even. This ensures that the value of float(n) doesn't depend on whether we're using 15-bit digits or 30-bit digits for Python longs. ........ r71776 | mark.dickinson | 2009-04-20 21:41:04 +0000 (Mo, 20 Apr 2009) | 2 lines Nit: integer division should use //, not / ........ r71780 | senthil.kumaran | 2009-04-21 03:24:19 +0000 (Di, 21 Apr 2009) | 3 lines Fix for the Issue918368 - urllib doesn't correct server returned urls ........ r71785 | r.david.murray | 2009-04-21 13:06:04 +0000 (Di, 21 Apr 2009) | 4 lines Restore skips of posix and pty tests on Windows by calling the test_support.import_module on the appropriate modules before any other imports. ........ r71788 | eric.smith | 2009-04-22 00:47:00 +0000 (Mi, 22 Apr 2009) | 1 line Documentation for issue 5237, auto-numbered format fields. Contributed by Terry J. Reedy. ........ r71794 | vinay.sajip | 2009-04-22 12:10:47 +0000 (Mi, 22 Apr 2009) | 2 lines Issue #5170: Fixed regression caused when fixing #5768. ........ r71796 | eric.smith | 2009-04-22 13:29:05 +0000 (Mi, 22 Apr 2009) | 20 lines Backport of some of the work in r71665 to trunk. This reworks much of int, long, and float __format__(), and it keeps their implementation in sync with py3k. Also added PyOS_double_to_string. This is the "fallback" version that's also available in trunk, and should be kept in sync with that code. I'll add an issue to document PyOS_double_to_string in the C API. There are many internal cleanups. Externally visible changes include: - Implement PEP 378, Format Specifier for Thousands Separator, for floats, ints, and longs. - Issue #5515: 'n' formatting for ints, longs, and floats handles leading zero formatting poorly. - Issue #5772: For float.__format__, don't add a trailing ".0" if we're using no type code and we have an exponent. ........ r71799 | nick.coghlan | 2009-04-22 15:26:04 +0000 (Mi, 22 Apr 2009) | 1 line Issue 5354: Change API for import_fresh_module() to better support test_warnings use case (also fixes some bugs in the original implementation) ........ r71802 | eric.smith | 2009-04-22 16:20:47 +0000 (Mi, 22 Apr 2009) | 1 line Fixed issue 5782: formatting with commas didn't work if no specifier type code was given. ........ r71808 | mark.dickinson | 2009-04-22 18:15:25 +0000 (Mi, 22 Apr 2009) | 2 lines Issue #5812: make Fraction('1e-6') valid. Backport of r71806. ........ r71824 | mark.dickinson | 2009-04-24 12:46:53 +0000 (Fr, 24 Apr 2009) | 7 lines Issue #5816: - simplify parsing and printing of complex numbers - make complex(repr(z)) round-tripping work for complex numbers involving nans, infs, or negative zeros - don't accept some of the stranger complex strings that were previously allowed---e.g., complex('1..1j') ........ r71827 | mark.dickinson | 2009-04-24 13:14:07 +0000 (Fr, 24 Apr 2009) | 2 lines Fix missing 'return NULL' ........ r71832 | mark.dickinson | 2009-04-24 13:56:07 +0000 (Fr, 24 Apr 2009) | 3 lines Issue #5812: The two-argument form of the Fraction constructor now accepts arbitrary Rational instances. ........ r71837 | mark.dickinson | 2009-04-24 16:34:14 +0000 (Fr, 24 Apr 2009) | 4 lines Issue #5593: Use more robust test for double-rounding in test_fsum. While we're at it, use new unittest.skipUnless decorator to implement skipping for that test. ........ r71838 | mark.dickinson | 2009-04-24 16:37:22 +0000 (Fr, 24 Apr 2009) | 2 lines Remove unnecessary double negative ........ r71842 | thomas.heller | 2009-04-24 18:10:46 +0000 (Fr, 24 Apr 2009) | 3 lines Issue #5161: wrong paths for ctypes cleanup when Python is built in a directory other than the source directory. ........ r71853 | thomas.heller | 2009-04-24 20:31:47 +0000 (Fr, 24 Apr 2009) | 3 lines Issue #3102: All global symbols that the _ctypes extension defines are now prefixed with 'Py' or '_ctypes'. ........ r71869 | mark.dickinson | 2009-04-25 09:47:00 +0000 (Sa, 25 Apr 2009) | 2 lines Fix typo in complex parsing code; expand tests. ........ r71878 | tarek.ziade | 2009-04-25 12:38:08 +0000 (Sa, 25 Apr 2009) | 1 line Issue #4951: Fixed failure in test_httpservers ........ r71904 | georg.brandl | 2009-04-25 15:11:29 +0000 (Sa, 25 Apr 2009) | 1 line #5841: add deprecation py3k warning and notice in the docs for commands module. ........ r71906 | thomas.heller | 2009-04-25 16:37:18 +0000 (Sa, 25 Apr 2009) | 1 line Issue #5078: Avoid redundant call to FormatError() ........ r71938 | eric.smith | 2009-04-25 21:40:15 +0000 (Sa, 25 Apr 2009) | 5 lines Issue #5835, deprecate PyOS_ascii_formatd. If anyone wants to clean up the documentation, feel free. It's my first documentation foray, and it's not that great. Will port to py3k with a different strategy. ........ r71955 | georg.brandl | 2009-04-26 06:01:04 +0000 (So, 26 Apr 2009) | 1 line Mostly formatting nits, and "and-ed together" -> "or-ed together" flags. ........ r71960 | georg.brandl | 2009-04-26 09:56:44 +0000 (So, 26 Apr 2009) | 1 line Move pydoc_topics module to its own subdirectory, so that no generated code is in Lib/. ........ r71961 | georg.brandl | 2009-04-26 09:57:29 +0000 (So, 26 Apr 2009) | 2 lines Update pydoc topics. ........ r71963 | mark.dickinson | 2009-04-26 14:00:08 +0000 (So, 26 Apr 2009) | 2 lines Reset errno before both calls to PyOS_ascii_strtod, not just one. ........ r71969 | mark.dickinson | 2009-04-26 16:04:05 +0000 (So, 26 Apr 2009) | 3 lines Backport r71967 changes from py3k to trunk. (Internal plumbing changes for float parsing.) ........ r71976 | mark.dickinson | 2009-04-26 19:54:55 +0000 (So, 26 Apr 2009) | 2 lines Fix typo in function name ........ Modified: python/branches/release26-maint/ (props changed) From python-checkins at python.org Wed May 19 02:03:09 2010 From: python-checkins at python.org (victor.stinner) Date: Wed, 19 May 2010 02:03:09 +0200 (CEST) Subject: [Python-checkins] r81314 - python/branches/py3k/Objects/moduleobject.c Message-ID: <20100519000309.BFE74BF1D@mail.python.org> Author: victor.stinner Date: Wed May 19 02:03:09 2010 New Revision: 81314 Log: Issue #6697: Fix a crash if a module attribute name contains a surrogate Modified: python/branches/py3k/Objects/moduleobject.c Modified: python/branches/py3k/Objects/moduleobject.c ============================================================================== --- python/branches/py3k/Objects/moduleobject.c (original) +++ python/branches/py3k/Objects/moduleobject.c Wed May 19 02:03:09 2010 @@ -263,10 +263,15 @@ pos = 0; while (PyDict_Next(d, &pos, &key, &value)) { if (value != Py_None && PyUnicode_Check(key)) { - const char *s = _PyUnicode_AsString(key); - if (s[0] == '_' && s[1] != '_') { - if (Py_VerboseFlag > 1) - PySys_WriteStderr("# clear[1] %s\n", s); + Py_UNICODE *u = PyUnicode_AS_UNICODE(key); + if (u[0] == '_' && u[1] != '_') { + if (Py_VerboseFlag > 1) { + const char *s = _PyUnicode_AsString(key); + if (s != NULL) + PySys_WriteStderr("# clear[1] %s\n", s); + else + PyErr_Clear(); + } PyDict_SetItem(d, key, Py_None); } } @@ -276,10 +281,17 @@ pos = 0; while (PyDict_Next(d, &pos, &key, &value)) { if (value != Py_None && PyUnicode_Check(key)) { - const char *s = _PyUnicode_AsString(key); - if (s[0] != '_' || strcmp(s, "__builtins__") != 0) { - if (Py_VerboseFlag > 1) - PySys_WriteStderr("# clear[2] %s\n", s); + Py_UNICODE *u = PyUnicode_AS_UNICODE(key); + if (u[0] != '_' + || PyUnicode_CompareWithASCIIString(key, "__builtins__") != 0) + { + if (Py_VerboseFlag > 1) { + const char *s = _PyUnicode_AsString(key); + if (s != NULL) + PySys_WriteStderr("# clear[2] %s\n", s); + else + PyErr_Clear(); + } PyDict_SetItem(d, key, Py_None); } } From python-checkins at python.org Wed May 19 02:07:48 2010 From: python-checkins at python.org (georg.brandl) Date: Wed, 19 May 2010 02:07:48 +0200 (CEST) Subject: [Python-checkins] r81315 - in python/branches/release26-maint: Misc/NEWS Modules/parsermodule.c Message-ID: <20100519000748.22C8FD9C8@mail.python.org> Author: georg.brandl Date: Wed May 19 02:07:47 2010 New Revision: 81315 Log: Merged revisions 72645 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r72645 | antoine.pitrou | 2009-05-14 21:48:09 +0000 (Do, 14 Mai 2009) | 6 lines Issue #5918: Fix a crash in the parser module. Patch by Amaury. ........ Modified: python/branches/release26-maint/ (props changed) python/branches/release26-maint/Misc/NEWS python/branches/release26-maint/Modules/parsermodule.c Modified: python/branches/release26-maint/Misc/NEWS ============================================================================== --- python/branches/release26-maint/Misc/NEWS (original) +++ python/branches/release26-maint/Misc/NEWS Wed May 19 02:07:47 2010 @@ -44,6 +44,8 @@ Library ------- +- Issue #5918: Fix a crash in the parser module. + - Issue #8688: Distutils now recalculates MANIFEST everytime. - Issue #7640: In the new `io` module, fix relative seek() for buffered Modified: python/branches/release26-maint/Modules/parsermodule.c ============================================================================== --- python/branches/release26-maint/Modules/parsermodule.c (original) +++ python/branches/release26-maint/Modules/parsermodule.c Wed May 19 02:07:47 2010 @@ -2092,14 +2092,14 @@ return (res); } /* try/except statement: skip past except_clause sections */ - while (res && (TYPE(CHILD(tree, pos)) == except_clause)) { + while (res && pos < nch && (TYPE(CHILD(tree, pos)) == except_clause)) { res = (validate_except_clause(CHILD(tree, pos)) && validate_colon(CHILD(tree, pos + 1)) && validate_suite(CHILD(tree, pos + 2))); pos += 3; } /* skip else clause */ - if (res && (TYPE(CHILD(tree, pos)) == NAME) && + if (res && pos < nch && (TYPE(CHILD(tree, pos)) == NAME) && (strcmp(STR(CHILD(tree, pos)), "else") == 0)) { res = (validate_colon(CHILD(tree, pos + 1)) && validate_suite(CHILD(tree, pos + 2))); From python-checkins at python.org Wed May 19 02:10:00 2010 From: python-checkins at python.org (georg.brandl) Date: Wed, 19 May 2010 02:10:00 +0200 (CEST) Subject: [Python-checkins] r81316 - in python/branches/release26-maint: Makefile.pre.in Message-ID: <20100519001000.C27D1DE93@mail.python.org> Author: georg.brandl Date: Wed May 19 02:10:00 2010 New Revision: 81316 Log: Merged revisions 72787 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r72787 | ronald.oussoren | 2009-05-19 19:06:38 +0000 (Di, 19 Mai 2009) | 8 lines This patch ensures that the pydoc_data package gets installed. This is needed to make it possible to use pydoc to get access to the language reference. That is, without this patch the folllowing won't work: >>> help('if') ........ Modified: python/branches/release26-maint/ (props changed) python/branches/release26-maint/Makefile.pre.in Modified: python/branches/release26-maint/Makefile.pre.in ============================================================================== --- python/branches/release26-maint/Makefile.pre.in (original) +++ python/branches/release26-maint/Makefile.pre.in Wed May 19 02:10:00 2010 @@ -829,7 +829,7 @@ distutils distutils/command distutils/tests $(XMLLIBSUBDIRS) \ multiprocessing multiprocessing/dummy \ lib-old \ - curses $(MACHDEPS) + curses pydoc_data $(MACHDEPS) libinstall: build_all $(srcdir)/Lib/$(PLATDIR) @for i in $(SCRIPTDIR) $(LIBDEST); \ do \ From python-checkins at python.org Wed May 19 02:18:20 2010 From: python-checkins at python.org (georg.brandl) Date: Wed, 19 May 2010 02:18:20 +0200 (CEST) Subject: [Python-checkins] r81317 - python/branches/release26-maint Message-ID: <20100519001820.EB0FEDF6F@mail.python.org> Author: georg.brandl Date: Wed May 19 02:18:20 2010 New Revision: 81317 Log: Blocked revisions 72004,72040,72052,72054,72056,72094,72107,72111,72114-72115,72117,72119,72126-72127,72131,72133-72135,72137,72155,72167,72173,72178,72183-72184,72189,72191,72197-72200,72202,72210,72213,72219,72223,72225-72226,72237,72241,72246,72250,72253,72257,72267,72269,72273,72283-72284,72303,72306,72314,72322,72324,72326,72328,72335,72343,72348,72361,72368,72377,72382,72388,72392,72404,72406,72443,72445,72451,72454,72461,72464,72468-72469,72474,72476,72487-72489,72494-72495,72497,72500,72506,72508-72510,72512,72516-72518,72525-72526,72535,72539,72543,72547,72551,72560,72570-72571,72582-72583,72605,72616,72618,72624,72630,72654-72655,72658,72669,72671,72681,72686,72689-72690,72692-72694,72696,72698-72699,72721,72727,72730,72736,72746,72764,72768,72774,72776-72777,72786,72789,72791,72796,72799,72805,72812-72813,72817,72823,72833,72879-72880,72890-72891,72898,72900,72903,72905,72907,72909,72912,72920-72921,72923-72924,72940,72956-72958,72972-72973,72979,72981,72986 via svnmerge ................ r72004 | vinay.sajip | 2009-04-27 13:44:27 +0000 (Mo, 27 Apr 2009) | 1 line Issue #5854: Updated __all__ to include some missing names and remove some names which should not be exported. ................ r72040 | eric.smith | 2009-04-27 19:04:37 +0000 (Mo, 27 Apr 2009) | 1 line Issue #5793: rationalize isdigit / isalpha / tolower, etc. Will port to py3k. Should fix Windows buildbot errors. ................ r72052 | raymond.hettinger | 2009-04-27 21:12:27 +0000 (Mo, 27 Apr 2009) | 1 line Update spec version number. ................ r72054 | antoine.pitrou | 2009-04-27 21:53:26 +0000 (Mo, 27 Apr 2009) | 5 lines Issue #1734234: Massively speedup `unicodedata.normalize()` when the string is already in normalized form, by performing a quick check beforehand. Original patch by Rauli Ruohonen. ................ r72056 | eric.smith | 2009-04-28 07:33:09 +0000 (Di, 28 Apr 2009) | 1 line Silence warning on Windows. ................ r72094 | tarek.ziade | 2009-04-29 08:03:46 +0000 (Mi, 29 Apr 2009) | 1 line Fixed #5874 : distutils.tests.test_config_cmd is not locale-sensitive anymore ................ r72107 | matthias.klose | 2009-04-29 17:18:19 +0000 (Mi, 29 Apr 2009) | 3 lines - Issue #4587: Add configure option --with-dbmliborder=db1:db2:... to specify the order that backends for the dbm extension are checked. ................ r72111 | matthias.klose | 2009-04-29 19:52:49 +0000 (Mi, 29 Apr 2009) | 3 lines - Issue #4587: Add configure option --with-dbmliborder=db1:db2:... to specify the order that backends for the dbm extension are checked. ................ r72114 | matthias.klose | 2009-04-29 20:09:50 +0000 (Mi, 29 Apr 2009) | 2 lines - configure.in: Don't error, when no --with-dbmliborder option is present ................ r72115 | r.david.murray | 2009-04-29 20:15:18 +0000 (Mi, 29 Apr 2009) | 2 lines More aifc tests. ................ r72117 | benjamin.peterson | 2009-04-29 20:36:25 +0000 (Mi, 29 Apr 2009) | 1 line run autoconf ................ r72119 | mark.dickinson | 2009-04-29 20:41:00 +0000 (Mi, 29 Apr 2009) | 3 lines Issue #5864: format(1234.5, '.4') gives misleading result (Backport of r72109 from py3k.) ................ r72126 | mark.dickinson | 2009-04-29 21:56:53 +0000 (Mi, 29 Apr 2009) | 2 lines Remove format_float and use _PyOS_double_to_string instead. ................ r72127 | mark.dickinson | 2009-04-29 21:57:15 +0000 (Mi, 29 Apr 2009) | 2 lines Backport some of the float formatting tests from py3k. ................ r72131 | benjamin.peterson | 2009-04-29 22:43:35 +0000 (Mi, 29 Apr 2009) | 1 line fix test_shutil on ZFS #5676 ................ r72133 | benjamin.peterson | 2009-04-29 22:44:15 +0000 (Mi, 29 Apr 2009) | 1 line make sure mode is removable while cleaning up test droppings ................ r72134 | benjamin.peterson | 2009-04-30 00:06:33 +0000 (Do, 30 Apr 2009) | 1 line make sure to close file ................ r72135 | benjamin.peterson | 2009-04-30 00:23:11 +0000 (Do, 30 Apr 2009) | 1 line prevent ref cycles by removing bound method on close() ................ r72137 | eric.smith | 2009-04-30 00:58:58 +0000 (Do, 30 Apr 2009) | 1 line Issue #1588: Add complex.__format__. ................ r72155 | senthil.kumaran | 2009-05-01 05:59:52 +0000 (Fr, 01 Mai 2009) | 4 lines Fix for Issue1648102, based on the MSDN spec: If this parameter specifies the "" macro as the only entry, this function bypasses any host name that does not contain a period. ................ r72167 | walter.doerwald | 2009-05-01 17:35:37 +0000 (Fr, 01 Mai 2009) | 5 lines Make test.test_support.EnvironmentVarGuard behave like a dictionary. All changes are mirrored to the underlying os.environ dict, but rolled back on exit from the with block. ................ r72173 | gregory.p.smith | 2009-05-01 19:59:52 +0000 (Fr, 01 Mai 2009) | 5 lines Adds the ipaddr module to the standard library. Issue #3959. Based off of subversion r69 from http://code.google.com/p/ipaddr-py/ This code is 2to3 safe, I'll merge it into py3k later this afternoon. ................ r72178 | antoine.pitrou | 2009-05-01 20:55:35 +0000 (Fr, 01 Mai 2009) | 4 lines Issue #3002: `shutil.copyfile()` and `shutil.copytree()` now raise an error when a named pipe is encountered, rather than blocking infinitely. ................ r72183 | georg.brandl | 2009-05-01 21:28:35 +0000 (Fr, 01 Mai 2009) | 2 lines Review ipaddr docs and add them in the TOC under "Internet protocols". ................ r72184 | georg.brandl | 2009-05-01 21:30:25 +0000 (Fr, 01 Mai 2009) | 1 line Fix directive name. ................ r72189 | eric.smith | 2009-05-02 09:58:09 +0000 (Sa, 02 Mai 2009) | 1 line Keep py3k and trunk code in sync. ................ r72191 | michael.foord | 2009-05-02 11:43:06 +0000 (Sa, 02 Mai 2009) | 9 lines Adds an exit parameter to unittest.main(). If False main no longer calls sys.exit. Closes issue 3379. Michael Foord ................ r72197 | benjamin.peterson | 2009-05-02 16:24:37 +0000 (Sa, 02 Mai 2009) | 1 line don't let sys.argv be used in the tests ................ r72198 | andrew.kuchling | 2009-05-02 17:12:15 +0000 (Sa, 02 Mai 2009) | 1 line Add items ................ r72199 | benjamin.peterson | 2009-05-02 17:33:01 +0000 (Sa, 02 Mai 2009) | 1 line remove py3k compat code ................ r72200 | benjamin.peterson | 2009-05-02 17:35:39 +0000 (Sa, 02 Mai 2009) | 1 line revert unrelated change ................ r72202 | mark.dickinson | 2009-05-02 17:55:01 +0000 (Sa, 02 Mai 2009) | 3 lines Remove unnecessary use of context for long getters. (Related to issue #5880). ................ r72210 | gregory.p.smith | 2009-05-02 18:58:21 +0000 (Sa, 02 Mai 2009) | 2 lines Convert test method names to PEP8 style. ................ r72213 | andrew.kuchling | 2009-05-02 19:17:28 +0000 (Sa, 02 Mai 2009) | 3 lines #1607951: Make mailbox.Maildir re-read the directories less frequently. This is done by recording the current time -1sec, and not re-reading unless the directory mod. times are >= the recorded time. ................ r72219 | michael.foord | 2009-05-02 20:15:05 +0000 (Sa, 02 Mai 2009) | 8 lines Add addCleanup and doCleanups to unittest.TestCase. Closes issue 5679. Michael Foord ................ r72223 | antoine.pitrou | 2009-05-02 21:13:23 +0000 (Sa, 02 Mai 2009) | 5 lines Isue #5084: unpickling now interns the attribute names of pickled objects, saving memory and avoiding growth in size of subsequent pickles. Proposal and original patch by Jake McGuire. ................ r72225 | michael.foord | 2009-05-02 22:43:34 +0000 (Sa, 02 Mai 2009) | 1 line ................ r72226 | kurt.kaiser | 2009-05-03 01:03:44 +0000 (So, 03 Mai 2009) | 3 lines idle.py modified and simplified to better support developing experimental versions of IDLE which are not installed in the standard location. ................ r72237 | gregory.p.smith | 2009-05-03 18:42:15 +0000 (So, 03 Mai 2009) | 3 lines Issue 5379 - applies patch supplied by philipp hagemeister to fix many problems with the ancient mcast.py demo code. ................ r72241 | gregory.p.smith | 2009-05-03 19:37:05 +0000 (So, 03 Mai 2009) | 3 lines Optimization: move RFC defined network constant construction out of the is_*() methods and into module private instances. ................ r72246 | gregory.p.smith | 2009-05-03 20:27:25 +0000 (So, 03 Mai 2009) | 2 lines docstring update. ................ r72250 | mark.dickinson | 2009-05-03 20:39:06 +0000 (So, 03 Mai 2009) | 2 lines Remove unnecessary uses of context in PyGetSetDef. See issue #5880. ................ r72253 | mark.dickinson | 2009-05-03 20:59:48 +0000 (So, 03 Mai 2009) | 2 lines Eliminate some locale-dependent calls to isspace and tolower. ................ r72257 | mark.dickinson | 2009-05-03 22:33:34 +0000 (So, 03 Mai 2009) | 2 lines Don't use PyOS_strnicmp for NaN and Inf detection: it's locale-aware. ................ r72267 | gregory.p.smith | 2009-05-04 00:16:49 +0000 (Mo, 04 Mai 2009) | 3 lines Issue #4751: For hashlib algorithms provided by OpenSSL, the Python GIL is now released during computation on data lengths >= 2048 bytes. ................ r72269 | gregory.p.smith | 2009-05-04 00:48:41 +0000 (Mo, 04 Mai 2009) | 2 lines cleanup applied patch to match style that is already in py3k branch. ................ r72273 | hirokazu.yamamoto | 2009-05-04 05:28:39 +0000 (Mo, 04 Mai 2009) | 1 line Issue #5913: os.listdir() should fail for empty path on windows. ................ r72283 | antoine.pitrou | 2009-05-04 18:32:32 +0000 (Mo, 04 Mai 2009) | 4 lines Issue #4426: The UTF-7 decoder was too strict and didn't accept some legal sequences. Patch by Nick Barnes and Victor Stinner. ................ r72284 | antoine.pitrou | 2009-05-04 18:32:50 +0000 (Mo, 04 Mai 2009) | 3 lines Add Nick Barnes to ACKS. ................ r72303 | benjamin.peterson | 2009-05-05 00:55:24 +0000 (Di, 05 Mai 2009) | 1 line using sys._getframe(x), where x > 0 doesnt' work on IronPython ................ r72306 | steven.bethard | 2009-05-05 01:31:22 +0000 (Di, 05 Mai 2009) | 1 line Update bdist_msi so that the generated MSIs for pure Python modules can install to any version of Python, like the generated EXEs from bdist_wininst. (Previously, you had to create a new MSI for each version of Python.) ................ r72314 | georg.brandl | 2009-05-05 07:48:12 +0000 (Di, 05 Mai 2009) | 1 line #5932: fix error return in _convertPyInt_AsSsize_t() conversion function. ................ r72322 | georg.brandl | 2009-05-05 08:54:11 +0000 (Di, 05 Mai 2009) | 1 line #5142: add module skipping feature to pdb. ................ r72324 | georg.brandl | 2009-05-05 09:06:02 +0000 (Di, 05 Mai 2009) | 1 line Fix overlong lines. ................ r72326 | georg.brandl | 2009-05-05 09:19:43 +0000 (Di, 05 Mai 2009) | 1 line #5929: fix signedness warning. ................ r72328 | georg.brandl | 2009-05-05 09:20:52 +0000 (Di, 05 Mai 2009) | 1 line Remove unused variable. ................ r72335 | martin.v.loewis | 2009-05-05 16:10:16 +0000 (Di, 05 Mai 2009) | 2 lines Issue #5847: Remove -n switch on "Edit with IDLE" menu item. ................ r72343 | senthil.kumaran | 2009-05-05 17:34:42 +0000 (Di, 05 Mai 2009) | 1 line Fixing issue5861 - test_urllib fails on windows. Agree to comment to have ':' in pathname2url as windows recognizes it. test_urllib passes now. ................ r72348 | eric.smith | 2009-05-05 18:26:08 +0000 (Di, 05 Mai 2009) | 1 line Issue #5920: Changed format.__float__ and complex.__float__ to use a precision of 12 when using the empty presentation type. This more closely matches str()'s behavior and reduces surprises when adding alignment flags to an empty format string. Patch by Mark Dickinson. ................ r72361 | martin.v.loewis | 2009-05-05 22:13:01 +0000 (Di, 05 Mai 2009) | 2 lines Issue #5721: don't package Lib/test/README anymore. ................ r72368 | benjamin.peterson | 2009-05-05 23:13:58 +0000 (Di, 05 Mai 2009) | 53 lines Merged revisions 68503,68507,68694,69054,69673,69679-69681,70991,70999,71003,71695 via svnmerge from svn+ssh://pythondev at svn.python.org/sandbox/trunk/2to3/lib2to3 ........ r68503 | benjamin.peterson | 2009-01-10 14:14:49 -0600 (Sat, 10 Jan 2009) | 1 line use variable ........ r68507 | benjamin.peterson | 2009-01-10 15:13:16 -0600 (Sat, 10 Jan 2009) | 1 line rewrap ........ r68694 | benjamin.peterson | 2009-01-17 17:55:59 -0600 (Sat, 17 Jan 2009) | 1 line test for specific node type ........ r69054 | guilherme.polo | 2009-01-28 10:01:54 -0600 (Wed, 28 Jan 2009) | 2 lines Added mapping for the ttk module. ........ r69673 | benjamin.peterson | 2009-02-16 09:38:22 -0600 (Mon, 16 Feb 2009) | 1 line fix handling of as imports #5279 ........ r69679 | benjamin.peterson | 2009-02-16 11:36:06 -0600 (Mon, 16 Feb 2009) | 1 line make Base.get_next_sibling() and Base.get_prev_sibling() properties ........ r69680 | benjamin.peterson | 2009-02-16 11:41:48 -0600 (Mon, 16 Feb 2009) | 1 line normalize docstrings in pytree according to PEP 11 ........ r69681 | benjamin.peterson | 2009-02-16 11:43:09 -0600 (Mon, 16 Feb 2009) | 1 line use a set ........ r70991 | benjamin.peterson | 2009-04-01 15:54:50 -0500 (Wed, 01 Apr 2009) | 1 line map urllib.urlopen to urllib.request.open #5637 ........ r70999 | benjamin.peterson | 2009-04-01 17:36:47 -0500 (Wed, 01 Apr 2009) | 1 line add very alpha support to 2to3 for running concurrently with multiprocessing ........ r71003 | benjamin.peterson | 2009-04-01 18:10:43 -0500 (Wed, 01 Apr 2009) | 1 line fix when multiprocessing is not available or used ........ r71695 | benjamin.peterson | 2009-04-17 22:21:29 -0500 (Fri, 17 Apr 2009) | 1 line refactor multiprocessing support, so it's less hacky to employ and only loads mp when needed ........ ................ r72377 | tarek.ziade | 2009-05-06 07:17:52 +0000 (Mi, 06 Mai 2009) | 1 line Added a test and cleaned check_library_list to be ready to fix #5940 ................ r72382 | tarek.ziade | 2009-05-06 07:41:53 +0000 (Mi, 06 Mai 2009) | 1 line pep8-fied build_clib module : it is now similar to the one in 3.x ................ r72388 | tarek.ziade | 2009-05-06 08:05:47 +0000 (Mi, 06 Mai 2009) | 1 line more build_clib cleanup + test coverage ................ r72392 | tarek.ziade | 2009-05-06 08:11:00 +0000 (Mi, 06 Mai 2009) | 1 line removed string.split usage ................ r72404 | walter.doerwald | 2009-05-06 14:28:24 +0000 (Mi, 06 Mai 2009) | 3 lines Issue 3739: The unicode-internal encoder now reports the number of *characters* consumed like any other encoder (instead of the number of bytes). ................ r72406 | walter.doerwald | 2009-05-06 14:32:35 +0000 (Mi, 06 Mai 2009) | 2 lines Add NEWS entry about issue #3739. ................ r72443 | tarek.ziade | 2009-05-07 21:13:02 +0000 (Do, 07 Mai 2009) | 1 line removed remaining spaces ................ r72445 | tarek.ziade | 2009-05-07 21:20:34 +0000 (Do, 07 Mai 2009) | 1 line Fixed #5941: added ARFLAGS for the archiver command. ................ r72451 | tarek.ziade | 2009-05-07 22:19:27 +0000 (Do, 07 Mai 2009) | 1 line run autoconf (step forgotten in r72445) ................ r72454 | tarek.ziade | 2009-05-07 23:01:56 +0000 (Do, 07 Mai 2009) | 1 line fixed AR/ARFLAGS values in test_sysconfig ................ r72461 | benjamin.peterson | 2009-05-08 03:06:00 +0000 (Fr, 08 Mai 2009) | 1 line add _PyObject_LookupSpecial to handle fetching special method lookup ................ r72464 | benjamin.peterson | 2009-05-08 03:29:26 +0000 (Fr, 08 Mai 2009) | 1 line this is now a bound method ................ r72468 | jeroen.ruigrok | 2009-05-08 13:07:39 +0000 (Fr, 08 Mai 2009) | 2 lines Add ISO-8859-16. ................ r72469 | jeroen.ruigrok | 2009-05-08 14:11:23 +0000 (Fr, 08 Mai 2009) | 2 lines Update the Windows locale mapping with the ones introduced with Vista. ................ r72474 | benjamin.peterson | 2009-05-08 17:59:29 +0000 (Fr, 08 Mai 2009) | 1 line fix this test ................ r72476 | thomas.heller | 2009-05-08 20:09:40 +0000 (Fr, 08 Mai 2009) | 4 lines Add a file that contains diffs between offical libffi files and the files in this repository. Should make it easier to merge new libffi versions. ................ r72487 | jeffrey.yasskin | 2009-05-08 21:51:06 +0000 (Fr, 08 Mai 2009) | 7 lines PyCode_NewEmpty: Most uses of PyCode_New found by http://www.google.com/codesearch?q=PyCode_New are trying to build an empty code object, usually to put it in a dummy frame object. This patch adds a PyCode_NewEmpty wrapper which lets the user specify just the filename, function name, and first line number, instead of also requiring lots of code internals. ................ r72488 | jeffrey.yasskin | 2009-05-08 22:23:21 +0000 (Fr, 08 Mai 2009) | 13 lines Issue 5954, PyFrame_GetLineNumber: Most uses of PyCode_Addr2Line (http://www.google.com/codesearch?q=PyCode_Addr2Line) are just trying to get the line number of a specified frame, but there's no way to do that directly. Forcing people to go through the code object makes them know more about the guts of the interpreter than they should need. The remaining uses of PyCode_Addr2Line seem to be getting the line from a traceback (for example, http://www.google.com/codesearch/p?hl=en#u_9_nDrchrw/pygame-1.7.1release/src/base.c&q=PyCode_Addr2Line), which is replaced by the tb_lineno field. So we may be able to deprecate PyCode_Addr2Line entirely for external use. ................ r72489 | gregory.p.smith | 2009-05-08 23:16:47 +0000 (Fr, 08 Mai 2009) | 3 lines Fix an off by one error on negative indexs to __getitem__ http://code.google.com/p/ipaddr-py/issues/detail?id=15 ................ r72494 | benjamin.peterson | 2009-05-09 01:01:14 +0000 (Sa, 09 Mai 2009) | 21 lines Merged revisions 72491-72493 via svnmerge from svn+ssh://pythondev at svn.python.org/sandbox/trunk/2to3/lib2to3 ........ r72491 | benjamin.peterson | 2009-05-08 19:33:27 -0500 (Fri, 08 May 2009) | 7 lines make 2to3 use unicode internally on 2.x This started out as a fix for #2660, but became this large refactoring when I realized the dire state this was in. 2to3 now uses tokenize.detect_encoding to decode the files correctly into unicode. ........ r72492 | benjamin.peterson | 2009-05-08 19:35:38 -0500 (Fri, 08 May 2009) | 1 line remove compat code ........ r72493 | benjamin.peterson | 2009-05-08 19:54:15 -0500 (Fri, 08 May 2009) | 1 line add a test for \r\n newlines ........ ................ r72495 | benjamin.peterson | 2009-05-09 02:07:04 +0000 (Sa, 09 Mai 2009) | 1 line lookup __reversed__ correctly as a special method ................ r72497 | tarek.ziade | 2009-05-09 08:28:53 +0000 (Sa, 09 Mai 2009) | 1 line Fixed Issue 5900: distutils.command.build_ext - Ensure RUNPATH is added to extension modules with RPATH if GNU ld is used ................ r72500 | tarek.ziade | 2009-05-09 10:06:00 +0000 (Sa, 09 Mai 2009) | 1 line #5976: fixed distutils test_check_environ ................ r72506 | vinay.sajip | 2009-05-09 12:07:17 +0000 (Sa, 09 Mai 2009) | 1 line Issue #5971: StreamHandler.handleError now swallows IOErrors which occur when trying to print a traceback. ................ r72508 | benjamin.peterson | 2009-05-09 16:36:39 +0000 (Sa, 09 Mai 2009) | 1 line convert some more special methods to use _PyObject_LookupSpecial ................ r72509 | benjamin.peterson | 2009-05-09 16:51:51 +0000 (Sa, 09 Mai 2009) | 1 line ignore classic classes ................ r72510 | benjamin.peterson | 2009-05-09 17:13:10 +0000 (Sa, 09 Mai 2009) | 1 line can't handle classic classes here ................ r72512 | benjamin.peterson | 2009-05-09 17:23:03 +0000 (Sa, 09 Mai 2009) | 1 line *sigh* deal with instances correctly ................ r72516 | benjamin.peterson | 2009-05-09 19:03:05 +0000 (Sa, 09 Mai 2009) | 1 line ignore AttributeErrors for classic classes ................ r72517 | benjamin.peterson | 2009-05-09 19:17:59 +0000 (Sa, 09 Mai 2009) | 1 line don't ignore exceptions from _PyObject_LengthHint ................ r72518 | benjamin.peterson | 2009-05-09 19:18:36 +0000 (Sa, 09 Mai 2009) | 1 line clear error state properly ................ r72525 | benjamin.peterson | 2009-05-10 01:38:02 +0000 (So, 10 Mai 2009) | 1 line close file explicitly ................ r72526 | benjamin.peterson | 2009-05-10 02:29:00 +0000 (So, 10 Mai 2009) | 1 line make sure files are closed using the with statement ................ r72535 | tarek.ziade | 2009-05-10 11:42:46 +0000 (So, 10 Mai 2009) | 1 line Added tests form install_lib and pep8-fied the module ................ r72539 | tarek.ziade | 2009-05-10 11:59:30 +0000 (So, 10 Mai 2009) | 1 line refactored test_sysconfig so it uses test.test_support.EnvironmentVarGuard ................ r72543 | tarek.ziade | 2009-05-10 12:17:30 +0000 (So, 10 Mai 2009) | 1 line now using EnvironGuard everywhere ................ r72547 | tarek.ziade | 2009-05-10 12:36:48 +0000 (So, 10 Mai 2009) | 1 line fixed test for all platforms ................ r72551 | benjamin.peterson | 2009-05-10 14:16:47 +0000 (So, 10 Mai 2009) | 1 line use isinstance ................ r72560 | tarek.ziade | 2009-05-11 08:45:17 +0000 (Mo, 11 Mai 2009) | 1 line distutils.test_build_clib added a new line at the end of the file, to avoid a warning with some compilers ................ r72570 | michael.foord | 2009-05-11 17:59:43 +0000 (Mo, 11 Mai 2009) | 7 lines Adds a verbosity keyword argument to unittest.main plus a minor fix allowing you to specify test modules / classes from the command line. Closes issue 5995. Michael Foord ................ r72571 | michael.foord | 2009-05-11 18:01:45 +0000 (Mo, 11 Mai 2009) | 1 line Add missing # to NEWS ................ r72582 | michael.foord | 2009-05-12 10:46:23 +0000 (Di, 12 Mai 2009) | 1 line Fix to restore command line behaviour for test modules using unittest.main(). Regression caused by issue 5995. Michael ................ r72583 | michael.foord | 2009-05-12 10:49:13 +0000 (Di, 12 Mai 2009) | 1 line Better fix for modules using unittest.main(). Fixes regression caused by commit for issue 5995. Michael Foord ................ r72605 | r.david.murray | 2009-05-13 17:14:11 +0000 (Mi, 13 Mai 2009) | 3 lines Issue #4050: inspect.findsource/getsource now raise an IOError if the 'source' file is a binary. Patch by Brodie Rao, test by Daniel Diniz. ................ r72616 | benjamin.peterson | 2009-05-14 00:33:10 +0000 (Do, 14 Mai 2009) | 1 line importlib.import_module is better these days ................ r72618 | tarek.ziade | 2009-05-14 12:40:59 +0000 (Do, 14 Mai 2009) | 1 line more test coverage for distutils sdist command ................ r72624 | tarek.ziade | 2009-05-14 14:56:14 +0000 (Do, 14 Mai 2009) | 1 line pep8-fied distutils.command.sdist + more tests ................ r72630 | r.david.murray | 2009-05-14 16:12:57 +0000 (Do, 14 Mai 2009) | 3 lines Fix test failure on Windows, and add skip check if even unicodedata turns out not to be an external module on some other platform. ................ r72654 | benjamin.peterson | 2009-05-14 22:37:49 +0000 (Do, 14 Mai 2009) | 1 line prevent refleaks from threads ................ r72655 | benjamin.peterson | 2009-05-14 22:40:34 +0000 (Do, 14 Mai 2009) | 1 line a useful decorator for cleaning up threads ................ r72658 | collin.winter | 2009-05-14 23:26:30 +0000 (Do, 14 Mai 2009) | 1 line Issue 6024: make regrtest.py promote refleaks to test failures. ................ r72669 | antoine.pitrou | 2009-05-15 16:54:52 +0000 (Fr, 15 Mai 2009) | 3 lines Issue #2116: Weak references and weak dictionaries now support copy()ing and deepcopy()ing. ................ r72671 | antoine.pitrou | 2009-05-15 17:27:30 +0000 (Fr, 15 Mai 2009) | 3 lines Fix bootstrapping by removing uses of the copy module in distutils ................ r72681 | tarek.ziade | 2009-05-16 16:37:06 +0000 (Sa, 16 Mai 2009) | 1 line #6041: sdist and register now use the check command. No more duplicate code for metadata checking ................ r72686 | tarek.ziade | 2009-05-16 18:29:40 +0000 (Sa, 16 Mai 2009) | 1 line pep8-fied distutils.dist module ................ r72689 | benjamin.peterson | 2009-05-16 18:44:34 +0000 (Sa, 16 Mai 2009) | 1 line use skipTest() ................ r72690 | benjamin.peterson | 2009-05-16 21:44:25 +0000 (Sa, 16 Mai 2009) | 1 line properly lookup __instancecheck__ and __subclasscheck__ ................ r72692 | benjamin.peterson | 2009-05-16 22:30:48 +0000 (Sa, 16 Mai 2009) | 1 line deal with old-style classes in issubclass and isinstance ................ r72693 | benjamin.peterson | 2009-05-16 22:40:56 +0000 (Sa, 16 Mai 2009) | 1 line completely ignore old-style stuff for type checking overloading ................ r72694 | benjamin.peterson | 2009-05-16 22:46:11 +0000 (Sa, 16 Mai 2009) | 1 line update ................ r72696 | benjamin.peterson | 2009-05-16 23:34:19 +0000 (Sa, 16 Mai 2009) | 1 line typo ................ r72698 | hirokazu.yamamoto | 2009-05-17 02:52:09 +0000 (So, 17 Mai 2009) | 1 line Issue #3527: Removed Py_WIN_WIDE_FILENAMES which is not used any more. ................ r72699 | hirokazu.yamamoto | 2009-05-17 02:58:36 +0000 (So, 17 Mai 2009) | 1 line Added NEWS for r72698. ................ r72721 | tarek.ziade | 2009-05-17 10:44:12 +0000 (So, 17 Mai 2009) | 1 line removed sys.platform == 'mac' support in distutils.dist.parse_command_line and improved test coverage ................ r72727 | tarek.ziade | 2009-05-17 11:11:57 +0000 (So, 17 Mai 2009) | 1 line removed sys.platform == 'mac' usage in distutils.dir_util ................ r72730 | tarek.ziade | 2009-05-17 11:22:36 +0000 (So, 17 Mai 2009) | 1 line pep8-fied distutils.dir_util ................ r72736 | tarek.ziade | 2009-05-17 12:04:57 +0000 (So, 17 Mai 2009) | 1 line pep8-fied distutils.archive_util + added minimum test coverage ................ r72746 | tarek.ziade | 2009-05-17 14:59:05 +0000 (So, 17 Mai 2009) | 1 line fixed the test name ................ r72764 | tarek.ziade | 2009-05-18 08:20:55 +0000 (Mo, 18 Mai 2009) | 1 line working with relative paths to avoid tar warnings on absolute paths ................ r72768 | tarek.ziade | 2009-05-18 12:21:26 +0000 (Mo, 18 Mai 2009) | 1 line Fixed #6053 - win32 fixes for distutils tests ................ r72774 | raymond.hettinger | 2009-05-18 15:51:59 +0000 (Mo, 18 Mai 2009) | 1 line Issue 6037: MutableSequence.__iadd__ should return self. ................ r72776 | jeffrey.yasskin | 2009-05-18 21:14:54 +0000 (Mo, 18 Mai 2009) | 6 lines While I was modifying test_trace, it threw an exception when I accidentally made it try to set the line number from the trace callback for a 'call' event. This patch makes the error message a little more helpful in that case, and makes it a little less likely that a future editor will make the same mistake in test_trace. ................ r72777 | collin.winter | 2009-05-18 21:35:40 +0000 (Mo, 18 Mai 2009) | 1 line Issue 6032: fix refleaks in test_urllib2_localnet. ................ r72786 | raymond.hettinger | 2009-05-19 17:43:59 +0000 (Di, 19 Mai 2009) | 1 line Note that ordered dictionaries work with reversed(). ................ r72789 | ronald.oussoren | 2009-05-19 19:29:24 +0000 (Di, 19 Mai 2009) | 2 lines Remove some traces of 'MacPython' ................ r72791 | ronald.oussoren | 2009-05-19 20:12:17 +0000 (Di, 19 Mai 2009) | 2 lines Remove some old MacPython files that are no longer relevant. ................ r72796 | jeffrey.yasskin | 2009-05-20 17:57:57 +0000 (Mi, 20 Mai 2009) | 3 lines Fix issue #1689458 by teaching frame_setlineno how to jump to the first line of a code object. ................ r72799 | georg.brandl | 2009-05-20 18:24:08 +0000 (Mi, 20 Mai 2009) | 1 line Update bug tracker URL. ................ r72805 | mark.dickinson | 2009-05-20 18:43:07 +0000 (Mi, 20 Mai 2009) | 1 line Issue #5829: don't raise OverflowError for complex('1e500'). Backport of r72803. ................ r72812 | michael.foord | 2009-05-21 22:57:02 +0000 (Do, 21 Mai 2009) | 1 line Rename TestCase._result to _resultForDoCleanups to avoid potential clashes in TestCase subclasses. Issue 6072. ................ r72813 | raymond.hettinger | 2009-05-22 01:06:44 +0000 (Fr, 22 Mai 2009) | 1 line Fix-up moving average example. ................ r72817 | philip.jenvey | 2009-05-22 05:35:32 +0000 (Fr, 22 Mai 2009) | 4 lines don't use subprocess.call with PIPEs as the child can fill the pipe buf and deadlock. add a warning to subprocess docs about this, similar to Popen.wait's. refs http://bugs.jython.org/issue1351 ................ r72823 | tarek.ziade | 2009-05-22 09:42:43 +0000 (Fr, 22 Mai 2009) | 1 line fixed encoding ................ r72833 | georg.brandl | 2009-05-22 17:00:17 +0000 (Fr, 22 Mai 2009) | 1 line #6078: _warnings is a builtin module and has no standard init_warnings function. ................ r72879 | jeffrey.yasskin | 2009-05-23 23:23:01 +0000 (Sa, 23 Mai 2009) | 14 lines Issue #6042: lnotab-based tracing is very complicated and isn't documented very well. There were at least 3 comment blocks purporting to document co_lnotab, and none did a very good job. This patch unifies them into Objects/lnotab_notes.txt which tries to completely capture the current state of affairs. I also discovered that we've attached 2 layers of patches to the basic tracing scheme. The first layer avoids jumping to instructions that don't start a line, to avoid problems in if statements and while loops. The second layer discovered that jumps backward do need to trace at instructions that don't start a line, so it added extra lnotab entries for 'while' and 'for' loops, and added a special case for backward jumps within the same line. I replaced these patches by just treating forward and backward jumps differently. ................ r72880 | senthil.kumaran | 2009-05-24 09:14:50 +0000 (So, 24 Mai 2009) | 3 lines Fixed Issue1424152, urllib2 fails with HTTPS over Proxy. ................ r72890 | gregory.p.smith | 2009-05-24 18:00:13 +0000 (So, 24 Mai 2009) | 2 lines add a versionadded tag for set_tunnel ................ r72891 | martin.v.loewis | 2009-05-24 19:10:52 +0000 (So, 24 Mai 2009) | 5 lines Issue #6065: Do not try to build a version-independent installer if the package has extension modules. Also add NEWS entry for #5311. ................ r72898 | antoine.pitrou | 2009-05-24 20:23:57 +0000 (So, 24 Mai 2009) | 6 lines Issue #3585: Add pkg-config support. It creates a python-2.7.pc file and a python.pc symlink in the $(LIBDIR)/pkgconfig directory. Patch by Clinton Roy. ................ r72900 | antoine.pitrou | 2009-05-24 20:46:06 +0000 (So, 24 Mai 2009) | 3 lines Add Misc/python.pc to the list of ignored files ................ r72903 | benjamin.peterson | 2009-05-24 23:13:32 +0000 (So, 24 Mai 2009) | 1 line stop using Py_FindMethod ................ r72905 | benjamin.peterson | 2009-05-25 00:48:58 +0000 (Mo, 25 Mai 2009) | 4 lines make class skipping decorators the same as skipping every test of the class This removes ClassTestSuite and a good bit of hacks. ................ r72907 | benjamin.peterson | 2009-05-25 02:40:21 +0000 (Mo, 25 Mai 2009) | 1 line handle errors from _PyObject_LookupSpecial when __get__ fails ................ r72909 | collin.winter | 2009-05-25 04:34:39 +0000 (Mo, 25 Mai 2009) | 2 lines Issue 5670: special-case pickling of dicts. This nearly doubles the performance of dict pickling in cPickle. ................ r72912 | benjamin.peterson | 2009-05-25 13:13:44 +0000 (Mo, 25 Mai 2009) | 5 lines add a SETUP_WITH opcode It speeds up the with statement and correctly looks up the special methods involved. ................ r72920 | benjamin.peterson | 2009-05-25 20:12:57 +0000 (Mo, 25 Mai 2009) | 1 line take into account the fact that SETUP_WITH pushes a finally block ................ r72921 | benjamin.peterson | 2009-05-25 20:13:36 +0000 (Mo, 25 Mai 2009) | 1 line fix error handling ................ r72923 | michael.foord | 2009-05-25 20:36:56 +0000 (Mo, 25 Mai 2009) | 1 line Make assertSequenceEqual error messages less cryptic, particularly for nested sequences. ................ r72924 | georg.brandl | 2009-05-25 21:02:56 +0000 (Mo, 25 Mai 2009) | 6 lines Allow multiple context managers in one with statement, as proposed in http://codereview.appspot.com/53094 and accepted by Guido. The construct is transformed into multiple With AST nodes so that there should be no problems with the semantics. ................ r72940 | benjamin.peterson | 2009-05-26 12:49:59 +0000 (Di, 26 Mai 2009) | 1 line teach the peepholer about SETUP_WITH ................ r72956 | raymond.hettinger | 2009-05-27 02:24:45 +0000 (Mi, 27 Mai 2009) | 3 lines Fix field name conflicts for named tuples. ................ r72957 | benjamin.peterson | 2009-05-27 02:43:46 +0000 (Mi, 27 Mai 2009) | 1 line correctly handle descrs with __missing__ ................ r72958 | benjamin.peterson | 2009-05-27 03:08:44 +0000 (Mi, 27 Mai 2009) | 1 line plug ref leak ................ r72972 | philip.jenvey | 2009-05-28 03:10:59 +0000 (Do, 28 Mai 2009) | 2 lines explicitly close the file, merged from py3k ................ r72973 | philip.jenvey | 2009-05-28 03:12:16 +0000 (Do, 28 Mai 2009) | 2 lines further hint to where the open docs really are ................ r72979 | philip.jenvey | 2009-05-28 05:58:44 +0000 (Do, 28 Mai 2009) | 2 lines explicitly close files ................ r72981 | tarek.ziade | 2009-05-28 12:53:54 +0000 (Do, 28 Mai 2009) | 1 line Fixed #6048: Distutils uses the tarfile module instead of the tar command now ................ r72986 | tarek.ziade | 2009-05-28 13:55:51 +0000 (Do, 28 Mai 2009) | 1 line using 'tar' then 'gzip' in the test, because 'tar -czf' is not supported under some platforms ................ Modified: python/branches/release26-maint/ (props changed) From python-checkins at python.org Wed May 19 02:32:52 2010 From: python-checkins at python.org (ezio.melotti) Date: Wed, 19 May 2010 02:32:52 +0200 (CEST) Subject: [Python-checkins] r81318 - python/trunk/Doc/library/argparse.rst Message-ID: <20100519003252.D91A4EB6E@mail.python.org> Author: ezio.melotti Date: Wed May 19 02:32:52 2010 New Revision: 81318 Log: Fix typo in argparse doc. Modified: python/trunk/Doc/library/argparse.rst Modified: python/trunk/Doc/library/argparse.rst ============================================================================== --- python/trunk/Doc/library/argparse.rst (original) +++ python/trunk/Doc/library/argparse.rst Wed May 19 02:32:52 2010 @@ -452,7 +452,7 @@ By default, :class:`ArgumentParser` objects uses ``sys.argv[0]`` to determine how to display the name of the program in help messages. This default is almost -always desirable because it will make the help messages match how the pgoram was +always desirable because it will make the help messages match how the program was invoked on the command line. For example, consider a file named ``myprogram.py`` with the following code:: From python-checkins at python.org Wed May 19 02:34:15 2010 From: python-checkins at python.org (victor.stinner) Date: Wed, 19 May 2010 02:34:15 +0200 (CEST) Subject: [Python-checkins] r81319 - python/branches/py3k/Python/pythonrun.c Message-ID: <20100519003415.EA96BE78E@mail.python.org> Author: victor.stinner Date: Wed May 19 02:34:15 2010 New Revision: 81319 Log: Issue #6697: Check that _PyUnicode_AsString() result is not NULL Modified: python/branches/py3k/Python/pythonrun.c Modified: python/branches/py3k/Python/pythonrun.c ============================================================================== --- python/branches/py3k/Python/pythonrun.c (original) +++ python/branches/py3k/Python/pythonrun.c Wed May 19 02:34:15 2010 @@ -138,8 +138,8 @@ static char* get_codeset(void) { - char* codeset; - PyObject *codec, *name; + char* codeset, *name_str; + PyObject *codec, *name = NULL; codeset = nl_langinfo(CODESET); if (!codeset || codeset[0] == '\0') @@ -154,12 +154,16 @@ if (!name) goto error; - codeset = strdup(_PyUnicode_AsString(name)); + name_str = _PyUnicode_AsString(name); + if (name == NULL) + goto error; + codeset = strdup(name_str); Py_DECREF(name); return codeset; error: Py_XDECREF(codec); + Py_XDECREF(name); return NULL; } #endif @@ -1060,22 +1064,34 @@ if (!oenc) return -1; enc = _PyUnicode_AsString(oenc); + if (enc == NULL) + return -1; } v = PySys_GetObject("ps1"); if (v != NULL) { v = PyObject_Str(v); if (v == NULL) PyErr_Clear(); - else if (PyUnicode_Check(v)) + else if (PyUnicode_Check(v)) { ps1 = _PyUnicode_AsString(v); + if (ps1 == NULL) { + PyErr_Clear(); + ps1 = ""; + } + } } w = PySys_GetObject("ps2"); if (w != NULL) { w = PyObject_Str(w); if (w == NULL) PyErr_Clear(); - else if (PyUnicode_Check(w)) + else if (PyUnicode_Check(w)) { ps2 = _PyUnicode_AsString(w); + if (ps2 == NULL) { + PyErr_Clear(); + ps2 = ""; + } + } } arena = PyArena_New(); if (arena == NULL) { From python-checkins at python.org Wed May 19 02:54:06 2010 From: python-checkins at python.org (victor.stinner) Date: Wed, 19 May 2010 02:54:06 +0200 (CEST) Subject: [Python-checkins] r81320 - in python/branches/py3k: Lib/test/test_getargs2.py Python/getargs.c Message-ID: <20100519005406.A04EBE532@mail.python.org> Author: victor.stinner Date: Wed May 19 02:54:06 2010 New Revision: 81320 Log: Issue #6697: Fix a crash if a keyword contains a surrogate Modified: python/branches/py3k/Lib/test/test_getargs2.py python/branches/py3k/Python/getargs.c Modified: python/branches/py3k/Lib/test/test_getargs2.py ============================================================================== --- python/branches/py3k/Lib/test/test_getargs2.py (original) +++ python/branches/py3k/Lib/test/test_getargs2.py Wed May 19 02:54:06 2010 @@ -252,24 +252,28 @@ getargs_keywords((1,2), 3, (4,(5,6)), (7,8,9), 10), (1, 2, 3, 4, 5, 6, 7, 8, 9, 10) ) + def test_mixed_args(self): # positional and keyword args self.assertEquals( getargs_keywords((1,2), 3, (4,(5,6)), arg4=(7,8,9), arg5=10), (1, 2, 3, 4, 5, 6, 7, 8, 9, 10) ) + def test_keyword_args(self): # all keywords self.assertEquals( getargs_keywords(arg1=(1,2), arg2=3, arg3=(4,(5,6)), arg4=(7,8,9), arg5=10), (1, 2, 3, 4, 5, 6, 7, 8, 9, 10) ) + def test_optional_args(self): # missing optional keyword args, skipping tuples self.assertEquals( getargs_keywords(arg1=(1,2), arg2=3, arg5=10), (1, 2, 3, -1, -1, -1, -1, -1, -1, 10) ) + def test_required_args(self): # required arg missing try: @@ -278,6 +282,7 @@ self.assertEquals(str(err), "Required argument 'arg2' (pos 2) not found") else: self.fail('TypeError should have been raised') + def test_too_many_args(self): try: getargs_keywords((1,2),3,(4,(5,6)),(7,8,9),10,111) @@ -285,6 +290,7 @@ self.assertEquals(str(err), "function takes at most 5 arguments (6 given)") else: self.fail('TypeError should have been raised') + def test_invalid_keyword(self): # extraneous keyword arg try: @@ -294,6 +300,14 @@ else: self.fail('TypeError should have been raised') + def test_surrogate_keyword(self): + try: + getargs_keywords((1,2), 3, (4,(5,6)), (7,8,9), **{'\uDC80': 10}) + except TypeError as err: + self.assertEquals(str(err), "'\udc80' is an invalid keyword argument for this function") + else: + self.fail('TypeError should have been raised') + def test_main(): tests = [Signed_TestCase, Unsigned_TestCase, Tuple_TestCase, Keywords_TestCase] try: Modified: python/branches/py3k/Python/getargs.c ============================================================================== --- python/branches/py3k/Python/getargs.c (original) +++ python/branches/py3k/Python/getargs.c Wed May 19 02:54:06 2010 @@ -1755,18 +1755,21 @@ "keywords must be strings"); return cleanreturn(0, freelist); } + /* check that _PyUnicode_AsString() result is not NULL */ ks = _PyUnicode_AsString(key); - for (i = 0; i < len; i++) { - if (!strcmp(ks, kwlist[i])) { - match = 1; - break; + if (ks != NULL) { + for (i = 0; i < len; i++) { + if (!strcmp(ks, kwlist[i])) { + match = 1; + break; + } } } if (!match) { PyErr_Format(PyExc_TypeError, - "'%s' is an invalid keyword " + "'%U' is an invalid keyword " "argument for this function", - ks); + key); return cleanreturn(0, freelist); } } From python-checkins at python.org Wed May 19 03:06:22 2010 From: python-checkins at python.org (victor.stinner) Date: Wed, 19 May 2010 03:06:22 +0200 (CEST) Subject: [Python-checkins] r81321 - python/branches/py3k/Python/bltinmodule.c Message-ID: <20100519010622.B9319C997@mail.python.org> Author: victor.stinner Date: Wed May 19 03:06:22 2010 New Revision: 81321 Log: Issue #6697: Fix a crash if sys.stdin or sys.stdout encoding contain a surrogate This is *very* unlikely :-) Modified: python/branches/py3k/Python/bltinmodule.c Modified: python/branches/py3k/Python/bltinmodule.c ============================================================================== --- python/branches/py3k/Python/bltinmodule.c (original) +++ python/branches/py3k/Python/bltinmodule.c Wed May 19 03:06:22 2010 @@ -1610,6 +1610,7 @@ char *prompt; char *s; PyObject *stdin_encoding; + char *stdin_encoding_str; PyObject *result; stdin_encoding = PyObject_GetAttrString(fin, "encoding"); @@ -1617,6 +1618,11 @@ /* stdin is a text stream, so it must have an encoding. */ return NULL; + stdin_encoding_str = _PyUnicode_AsString(stdin_encoding); + if (stdin_encoding_str == NULL) { + Py_DECREF(stdin_encoding); + return NULL; + } tmp = PyObject_CallMethod(fout, "flush", ""); if (tmp == NULL) PyErr_Clear(); @@ -1625,12 +1631,18 @@ if (promptarg != NULL) { PyObject *stringpo; PyObject *stdout_encoding; - stdout_encoding = PyObject_GetAttrString(fout, - "encoding"); + char *stdout_encoding_str; + stdout_encoding = PyObject_GetAttrString(fout, "encoding"); if (stdout_encoding == NULL) { Py_DECREF(stdin_encoding); return NULL; } + stdout_encoding_str = _PyUnicode_AsString(stdout_encoding); + if (stdout_encoding_str == NULL) { + Py_DECREF(stdin_encoding); + Py_DECREF(stdout_encoding); + return NULL; + } stringpo = PyObject_Str(promptarg); if (stringpo == NULL) { Py_DECREF(stdin_encoding); @@ -1638,7 +1650,7 @@ return NULL; } po = PyUnicode_AsEncodedString(stringpo, - _PyUnicode_AsString(stdout_encoding), NULL); + stdout_encoding_str, NULL); Py_DECREF(stdout_encoding); Py_DECREF(stringpo); if (po == NULL) { @@ -1676,10 +1688,7 @@ result = NULL; } else { - result = PyUnicode_Decode - (s, len-1, - _PyUnicode_AsString(stdin_encoding), - NULL); + result = PyUnicode_Decode(s, len-1, stdin_encoding_str, NULL); } } Py_DECREF(stdin_encoding); From python-checkins at python.org Wed May 19 03:17:03 2010 From: python-checkins at python.org (victor.stinner) Date: Wed, 19 May 2010 03:17:03 +0200 (CEST) Subject: [Python-checkins] r81322 - python/branches/py3k/Modules/_io/textio.c Message-ID: <20100519011703.1329CEA28@mail.python.org> Author: victor.stinner Date: Wed May 19 03:17:01 2010 New Revision: 81322 Log: Issue #6697: Check that _PyUnicode_AsString() result is not NULL in textio.c The bug may occurs if locale.getpreferredencoding() returns an encoding with a surrogate (very unlikely!). Modified: python/branches/py3k/Modules/_io/textio.c Modified: python/branches/py3k/Modules/_io/textio.c ============================================================================== --- python/branches/py3k/Modules/_io/textio.c (original) +++ python/branches/py3k/Modules/_io/textio.c Wed May 19 03:17:01 2010 @@ -905,8 +905,11 @@ Py_CLEAR(self->encoding); } } - if (self->encoding != NULL) + if (self->encoding != NULL) { encoding = _PyUnicode_AsString(self->encoding); + if (encoding == NULL) + goto error; + } else if (encoding != NULL) { self->encoding = PyUnicode_FromString(encoding); if (self->encoding == NULL) @@ -935,6 +938,8 @@ self->writetranslate = (newline == NULL || newline[0] != '\0'); if (!self->readuniversal && self->readnl) { self->writenl = _PyUnicode_AsString(self->readnl); + if (self->writenl == NULL) + goto error; if (!strcmp(self->writenl, "\n")) self->writenl = NULL; } @@ -2408,7 +2413,7 @@ Py_DECREF(res); if (r < 0) return NULL; - + if (r > 0) { Py_RETURN_NONE; /* stream already closed */ } From python-checkins at python.org Wed May 19 03:27:24 2010 From: python-checkins at python.org (victor.stinner) Date: Wed, 19 May 2010 03:27:24 +0200 (CEST) Subject: [Python-checkins] r81323 - in python/branches/py3k/Modules/_sqlite: connection.c cursor.c row.c statement.c Message-ID: <20100519012724.12BCFEA47@mail.python.org> Author: victor.stinner Date: Wed May 19 03:27:23 2010 New Revision: 81323 Log: Issue #6697: Check that _PyUnicode_AsString() result is not NULL in _sqlite Strip also some trailing spaces Modified: python/branches/py3k/Modules/_sqlite/connection.c python/branches/py3k/Modules/_sqlite/cursor.c python/branches/py3k/Modules/_sqlite/row.c python/branches/py3k/Modules/_sqlite/statement.c Modified: python/branches/py3k/Modules/_sqlite/connection.c ============================================================================== --- python/branches/py3k/Modules/_sqlite/connection.c (original) +++ python/branches/py3k/Modules/_sqlite/connection.c Wed May 19 03:27:23 2010 @@ -3,7 +3,7 @@ * Copyright (C) 2004-2010 Gerhard H?ring * * This file is part of pysqlite. - * + * * 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. @@ -495,7 +495,9 @@ } else if (PyFloat_Check(py_val)) { sqlite3_result_double(context, PyFloat_AsDouble(py_val)); } else if (PyUnicode_Check(py_val)) { - sqlite3_result_text(context, _PyUnicode_AsString(py_val), -1, SQLITE_TRANSIENT); + char *str = _PyUnicode_AsString(py_val); + if (str != NULL) + sqlite3_result_text(context, str, -1, SQLITE_TRANSIENT); } else if (PyObject_CheckBuffer(py_val)) { if (PyObject_AsCharBuffer(py_val, &buffer, &buflen) != 0) { PyErr_SetString(PyExc_ValueError, "could not convert BLOB to buffer"); @@ -892,7 +894,7 @@ } /* abort query if error occurred */ - rc = 1; + rc = 1; } else { rc = (int)PyObject_IsTrue(ret); Py_DECREF(ret); Modified: python/branches/py3k/Modules/_sqlite/cursor.c ============================================================================== --- python/branches/py3k/Modules/_sqlite/cursor.c (original) +++ python/branches/py3k/Modules/_sqlite/cursor.c Wed May 19 03:27:23 2010 @@ -368,7 +368,7 @@ } PyOS_snprintf(buf, sizeof(buf) - 1, "Could not decode to UTF-8 column '%s' with text '%s'", colname , val_str); - buf_bytes = PyByteArray_FromStringAndSize(buf, strlen(buf)); + buf_bytes = PyByteArray_FromStringAndSize(buf, strlen(buf)); if (!buf_bytes) { PyErr_SetString(pysqlite_OperationalError, "Could not decode to UTF-8"); } else { @@ -533,7 +533,7 @@ } operation_cstr = _PyUnicode_AsStringAndSize(operation, &operation_len); - if (operation == NULL) + if (operation_cstr == NULL) goto error; /* reset description and rowcount */ Modified: python/branches/py3k/Modules/_sqlite/row.c ============================================================================== --- python/branches/py3k/Modules/_sqlite/row.c (original) +++ python/branches/py3k/Modules/_sqlite/row.c Wed May 19 03:27:23 2010 @@ -83,6 +83,8 @@ return item; } else if (PyUnicode_Check(idx)) { key = _PyUnicode_AsString(idx); + if (key == NULL) + return NULL; nitems = PyTuple_Size(self->description); Modified: python/branches/py3k/Modules/_sqlite/statement.c ============================================================================== --- python/branches/py3k/Modules/_sqlite/statement.c (original) +++ python/branches/py3k/Modules/_sqlite/statement.c Wed May 19 03:27:23 2010 @@ -130,7 +130,10 @@ break; case TYPE_UNICODE: string = _PyUnicode_AsString(parameter); - rc = sqlite3_bind_text(self->st, pos, string, -1, SQLITE_TRANSIENT); + if (string != NULL) + rc = sqlite3_bind_text(self->st, pos, string, -1, SQLITE_TRANSIENT); + else + rc = -1; break; case TYPE_BUFFER: if (PyObject_AsCharBuffer(parameter, &buffer, &buflen) == 0) { From python-checkins at python.org Wed May 19 03:42:46 2010 From: python-checkins at python.org (victor.stinner) Date: Wed, 19 May 2010 03:42:46 +0200 (CEST) Subject: [Python-checkins] r81324 - python/branches/py3k/Objects/typeobject.c Message-ID: <20100519014246.CE92BECA3@mail.python.org> Author: victor.stinner Date: Wed May 19 03:42:46 2010 New Revision: 81324 Log: Issue #6697: Check that _PyUnicode_AsString() result is not NULL in typeobject Type name and slots are already checked for surrogates somewhere else, but it's better to ensure that the result is not NULL. Modified: python/branches/py3k/Objects/typeobject.c Modified: python/branches/py3k/Objects/typeobject.c ============================================================================== --- python/branches/py3k/Objects/typeobject.c (original) +++ python/branches/py3k/Objects/typeobject.c Wed May 19 03:42:46 2010 @@ -1347,8 +1347,14 @@ i = 0; while (PyDict_Next(set, &i, &k, &v) && (size_t)off < sizeof(buf)) { PyObject *name = class_name(k); - off += PyOS_snprintf(buf + off, sizeof(buf) - off, " %s", - name ? _PyUnicode_AsString(name) : "?"); + char *name_str; + if (name != NULL) { + name_str = _PyUnicode_AsString(name); + if (name_str == NULL) + name_str = "?" + } else + name_str = "?" + off += PyOS_snprintf(buf + off, sizeof(buf) - off, " %s", name_str); Py_XDECREF(name); if (--n && (size_t)(off+1) < sizeof(buf)) { buf[off++] = ','; @@ -2220,6 +2226,10 @@ for (i = 0; i < nslots; i++, mp++) { mp->name = _PyUnicode_AsString( PyTuple_GET_ITEM(slots, i)); + if (mp->name == NULL) { + Py_DECREF(type); + return NULL; + } mp->type = T_OBJECT_EX; mp->offset = slotoffset; From python-checkins at python.org Wed May 19 03:50:45 2010 From: python-checkins at python.org (victor.stinner) Date: Wed, 19 May 2010 03:50:45 +0200 (CEST) Subject: [Python-checkins] r81325 - python/branches/py3k/Objects/typeobject.c Message-ID: <20100519015045.79DCFEA0A@mail.python.org> Author: victor.stinner Date: Wed May 19 03:50:45 2010 New Revision: 81325 Log: Ooops, add missing ";" in my previous commit (r81324, typeobject.c) It's time to go to bed... Modified: python/branches/py3k/Objects/typeobject.c Modified: python/branches/py3k/Objects/typeobject.c ============================================================================== --- python/branches/py3k/Objects/typeobject.c (original) +++ python/branches/py3k/Objects/typeobject.c Wed May 19 03:50:45 2010 @@ -1351,9 +1351,9 @@ if (name != NULL) { name_str = _PyUnicode_AsString(name); if (name_str == NULL) - name_str = "?" + name_str = "?"; } else - name_str = "?" + name_str = "?"; off += PyOS_snprintf(buf + off, sizeof(buf) - off, " %s", name_str); Py_XDECREF(name); if (--n && (size_t)(off+1) < sizeof(buf)) { From python-checkins at python.org Wed May 19 03:55:57 2010 From: python-checkins at python.org (victor.stinner) Date: Wed, 19 May 2010 03:55:57 +0200 (CEST) Subject: [Python-checkins] r81326 - python/branches/release31-maint Message-ID: <20100519015557.18670EA0A@mail.python.org> Author: victor.stinner Date: Wed May 19 03:55:56 2010 New Revision: 81326 Log: Blocked revisions 81291-81292 via svnmerge ........ r81291 | victor.stinner | 2010-05-18 19:17:23 +0200 (mar., 18 mai 2010) | 5 lines Issue #8513: os.get_exec_path() supports b'PATH' key and bytes value. subprocess.Popen() and os._execvpe() support bytes program name. Add os.supports_bytes_environ flag: True if the native OS type of the environment is bytes (eg. False on Windows). ........ r81292 | victor.stinner | 2010-05-18 19:24:09 +0200 (mar., 18 mai 2010) | 2 lines Add versionadded (3.2) tag to os.supports_bytes_environ documentation ........ Modified: python/branches/release31-maint/ (props changed) From python-checkins at python.org Wed May 19 14:55:12 2010 From: python-checkins at python.org (georg.brandl) Date: Wed, 19 May 2010 14:55:12 +0200 (CEST) Subject: [Python-checkins] r81327 - python/branches/release26-maint Message-ID: <20100519125512.CAF0AEBB7@mail.python.org> Author: georg.brandl Date: Wed May 19 14:55:12 2010 New Revision: 81327 Log: Blocked revisions 73001-73002,73004,73006,73008,73027,73029,73031,73049,73060,73068,73071-73074,73076,73083,73109,73121,73135,73147,73151,73166,73170,73174,73182,73184,73190,73196-73197,73201,73212,73238,73240,73243,73247,73250,73252,73270,73272,73275,73278-73282,73303,73308,73312,73314,73317-73318,73321,73324-73326,73328,73331,73334-73336,73340,73345,73350,73353-73354,73361-73363,73367,73370,73372,73376,73382,73393-73398,73400-73402,73404-73405,73409,73415,73417-73423,73432-73433,73435-73436,73439,73445,73447-73448,73457,73460-73461,73465,73471-73472,73480,73485-73486,73488-73490,73495-73496,73499,73501-73502,73509,73513-73514,73518-73519,73532,73534,73536-73537,73540,73546,73563-73564,73603,73605-73606,73614-73615,73627,73638,73660,73665,73675,73679,73686,73688,73697,73701,73710,73712,73714,73717,73720,73725,73744,73750,73756-73757,73762,73767,73773,73781,73786,73801,73814-73815,73818-73819,73821-73822,73825-73827,73834,73839,73841,73846-73847,73854,73858,73863-73864,73871,73877,73884,73888,73891,73895,73901,73916,73925-73926,73930-73933,73944,73962-73963,73985-73986,73988-73991,73994-73995,73998,74000 via svnmerge ................ r73001 | raymond.hettinger | 2009-05-29 03:36:26 +0200 (Fr, 29 Mai 2009) | 1 line Issue 5150: Add rstrip() option to IDLE's format menu. ................ r73002 | raymond.hettinger | 2009-05-29 03:46:48 +0200 (Fr, 29 Mai 2009) | 3 lines Deprecate contextlib.nested(). The with-statement now provides this functionality directly. ................ r73004 | jeffrey.yasskin | 2009-05-29 05:44:31 +0200 (Fr, 29 Mai 2009) | 5 lines Fix nearly all compilation warnings under Apple gcc-4.0. Tested with OPT="-g -Wall -Wstrict-prototypes -Werror" in both --with-pydebug mode and --without. There's still a batch of non-prototype warnings in Xlib.h that I don't know how to fix. ................ r73006 | raymond.hettinger | 2009-05-29 06:58:52 +0200 (Fr, 29 Mai 2009) | 1 line Issue 5982: Classmethod and staticmethod expose wrapped function with __func__. ................ r73008 | tarek.ziade | 2009-05-29 10:08:07 +0200 (Fr, 29 Mai 2009) | 1 line Fixed #6131: test_modulefinder leaked when run after test_distutils ................ r73027 | michael.foord | 2009-05-29 22:33:46 +0200 (Fr, 29 Mai 2009) | 1 line Add test discovery to unittest. Issue 6001. ................ r73029 | raymond.hettinger | 2009-05-29 23:20:41 +0200 (Fr, 29 Mai 2009) | 1 line Move the basic examples section back to the beginning. ................ r73031 | benjamin.peterson | 2009-05-29 23:48:19 +0200 (Fr, 29 Mai 2009) | 1 line add with statements ................ r73049 | georg.brandl | 2009-05-30 12:45:40 +0200 (Sa, 30 Mai 2009) | 1 line Rewrap a few long lines. ................ r73060 | gregory.p.smith | 2009-05-30 21:58:11 +0200 (Sa, 30 Mai 2009) | 2 lines Add more examples to the ipaddr documentation. ................ r73068 | antoine.pitrou | 2009-05-30 23:45:40 +0200 (Sa, 30 Mai 2009) | 3 lines Update ACKS ................ r73071 | georg.brandl | 2009-05-31 16:15:25 +0200 (So, 31 Mai 2009) | 1 line Fix markup. ................ r73072 | antoine.pitrou | 2009-05-31 16:20:14 +0200 (So, 31 Mai 2009) | 4 lines Issue #6152: New option '-j'/'--multiprocess' for regrtest allows running regression tests in parallel, shortening the total runtime. ................ r73073 | benjamin.peterson | 2009-05-31 16:43:00 +0200 (So, 31 Mai 2009) | 1 line remove function import ................ r73074 | benjamin.peterson | 2009-05-31 17:00:27 +0200 (So, 31 Mai 2009) | 1 line __enter__ and __exit__ must be on the class ................ r73076 | antoine.pitrou | 2009-05-31 20:05:51 +0200 (So, 31 Mai 2009) | 4 lines Uninitialized file type would lead to __exit__ lookup failure when site.py tries to read *.pth files on interpreter startup. ................ r73083 | guilherme.polo | 2009-05-31 23:31:21 +0200 (So, 31 Mai 2009) | 1 line Improved PanedWindow.add's docstring. 'subcomand' is a Tcl term, and the possible options and values are the same accepted by paneconfigure (not configure). ................ r73109 | gregory.p.smith | 2009-06-01 19:40:41 +0200 (Mo, 01 Jun 2009) | 6 lines Sync up __version__ number with the version of the ipaddr-py project this library came from that it matches. Remove the former apache license text now that its been contributed to PSF to avoid confusion. ................ r73121 | tarek.ziade | 2009-06-02 00:22:13 +0200 (Di, 02 Jun 2009) | 1 line improved distutils.dist test coverage, pep-8 compliancy ................ r73135 | gregory.p.smith | 2009-06-02 07:25:34 +0200 (Di, 02 Jun 2009) | 3 lines Fixes issue6169: it was possible for two ipaddr network addresses to compare as both < and > than eachother. ................ r73147 | tarek.ziade | 2009-06-02 17:58:43 +0200 (Di, 02 Jun 2009) | 1 line improved distutils.spawn test coverage + cleaned it up ................ r73151 | michael.foord | 2009-06-02 20:08:27 +0200 (Di, 02 Jun 2009) | 1 line Restore default testRunner argument in unittest.main to None. Issue 6177 ................ r73166 | tarek.ziade | 2009-06-03 12:26:26 +0200 (Mi, 03 Jun 2009) | 1 line added some tests for distutils.extension + code cleanup ................ r73170 | tarek.ziade | 2009-06-03 13:12:08 +0200 (Mi, 03 Jun 2009) | 1 line more cleanup and test coverage for distutils.extension ................ r73174 | tarek.ziade | 2009-06-03 13:20:44 +0200 (Mi, 03 Jun 2009) | 1 line assertion message was dropped ................ r73182 | josiah.carlson | 2009-06-03 21:46:21 +0200 (Mi, 03 Jun 2009) | 4 lines This fixes bug 5798 on OS X. This should also fix disconnect behavior cross-platform. ................ r73184 | josiah.carlson | 2009-06-03 21:51:52 +0200 (Mi, 03 Jun 2009) | 2 lines Fix for line wrap ugly. ................ r73190 | georg.brandl | 2009-06-04 01:23:45 +0200 (Do, 04 Jun 2009) | 2 lines Avoid PendingDeprecationWarnings emitted by deprecated unittest methods. ................ r73196 | benjamin.peterson | 2009-06-04 03:40:29 +0200 (Do, 04 Jun 2009) | 1 line use the offical api ................ r73197 | tarek.ziade | 2009-06-04 09:31:52 +0200 (Do, 04 Jun 2009) | 1 line improved test coverage for distutils.command.install and cleaned it up ................ r73201 | georg.brandl | 2009-06-04 10:58:32 +0200 (Do, 04 Jun 2009) | 1 line #5767: remove sgmlop support from xmlrpclib; the sgmlop parser does not do much validation and is no longer much faster than e.g. the cElementTree XMLParser. ................ r73212 | georg.brandl | 2009-06-04 12:10:41 +0200 (Do, 04 Jun 2009) | 1 line Better name for "Ctor". ................ r73238 | hirokazu.yamamoto | 2009-06-05 07:15:58 +0200 (Fr, 05 Jun 2009) | 1 line Fix test__locale on windows (Backport of r72365) ................ r73240 | eric.smith | 2009-06-05 14:33:26 +0200 (Fr, 05 Jun 2009) | 1 line Removed tests so that test_float pass on Windows. See issue 6198. ................ r73243 | tarek.ziade | 2009-06-05 15:37:29 +0200 (Fr, 05 Jun 2009) | 1 line reverting r72823 : Python trunk has to use latin-1 encoding ................ r73247 | michael.foord | 2009-06-05 16:14:34 +0200 (Fr, 05 Jun 2009) | 1 line Fix unittest discovery tests for Windows. Issue 6199 ................ r73250 | benjamin.peterson | 2009-06-05 21:09:28 +0200 (Fr, 05 Jun 2009) | 1 line only test for named pipe when os.stat doesn't raise #6209 ................ r73252 | georg.brandl | 2009-06-06 07:54:34 +0200 (Sa, 06 Jun 2009) | 1 line #6206: fix test__locale. ................ r73270 | benjamin.peterson | 2009-06-07 18:24:48 +0200 (So, 07 Jun 2009) | 1 line backport r73268 ................ r73272 | kristjan.jonsson | 2009-06-07 18:43:23 +0200 (So, 07 Jun 2009) | 2 lines http://bugs.python.org/issue6192 Add a feature to disable the Nagle algorithm on sockets in TCPServer ................ r73275 | georg.brandl | 2009-06-07 22:37:52 +0200 (So, 07 Jun 2009) | 1 line Add Ezio. ................ r73278 | benjamin.peterson | 2009-06-08 00:33:11 +0200 (Mo, 08 Jun 2009) | 1 line inherit from object ................ r73279 | benjamin.peterson | 2009-06-08 00:35:00 +0200 (Mo, 08 Jun 2009) | 1 line always inherit from an appropiate base class ................ r73280 | benjamin.peterson | 2009-06-08 00:54:35 +0200 (Mo, 08 Jun 2009) | 1 line use booleans for flags ................ r73281 | benjamin.peterson | 2009-06-08 00:55:36 +0200 (Mo, 08 Jun 2009) | 1 line remove has_key ................ r73282 | benjamin.peterson | 2009-06-08 01:12:44 +0200 (Mo, 08 Jun 2009) | 1 line backport r73273 ................ r73303 | ronald.oussoren | 2009-06-08 22:54:59 +0200 (Mo, 08 Jun 2009) | 11 lines This checkin adds a symlink to the lib directory of a framework install of Python (on OSX), and the end result of that is that the combination of ``python-config --ldflags`` and ``python-config --libs`` refers to an actually existing location. I've done this in preference to changing python-config to specify '-framework Python' for linking because that doesn't work when you have multiple versions of python installed (because '-framework Python' will always link to the 'Current' version of the framework, without a possibility to specify a specific version). ................ r73308 | benjamin.peterson | 2009-06-09 00:18:32 +0200 (Di, 09 Jun 2009) | 1 line remove useless assertion ................ r73312 | benjamin.peterson | 2009-06-09 01:44:13 +0200 (Di, 09 Jun 2009) | 1 line remove error checks already done in set_context() ................ r73314 | eric.smith | 2009-06-09 14:38:08 +0200 (Di, 09 Jun 2009) | 1 line Restored a test that was erroneously removed. See issue 6198. ................ r73317 | benjamin.peterson | 2009-06-09 19:24:26 +0200 (Di, 09 Jun 2009) | 1 line make ast.c depend on the grammar ................ r73318 | benjamin.peterson | 2009-06-09 19:29:51 +0200 (Di, 09 Jun 2009) | 1 line explain why keyword names are not just NAME ................ r73321 | benjamin.peterson | 2009-06-09 23:13:43 +0200 (Di, 09 Jun 2009) | 1 line update symbol.py from with statement changes ................ r73324 | amaury.forgeotdarc | 2009-06-10 00:53:16 +0200 (Mi, 10 Jun 2009) | 2 lines Avoid invoking the parser/compiler just to test the presence of a function. ................ r73325 | amaury.forgeotdarc | 2009-06-10 01:08:13 +0200 (Mi, 10 Jun 2009) | 8 lines #6201: Fix test_winreg on Windows: since the introduction of the SETUP_WITH opcode, __enter__ and __exit__ methods must belong to the type, and are not retrieved at the instance level (__dict__ or __getattr__). Add a note in whatsnew about this incompatibility; old style classes are not affected. ................ r73326 | amaury.forgeotdarc | 2009-06-10 01:18:50 +0200 (Mi, 10 Jun 2009) | 2 lines Both kind of types are concerned. ................ r73328 | amaury.forgeotdarc | 2009-06-10 01:37:11 +0200 (Mi, 10 Jun 2009) | 3 lines Missing import in test_curses, uncovered by some buildbots. (There are still a few test files that don't use the standard layout) ................ r73331 | benjamin.peterson | 2009-06-10 15:45:31 +0200 (Mi, 10 Jun 2009) | 1 line fix spelling ................ r73334 | raymond.hettinger | 2009-06-10 18:15:02 +0200 (Mi, 10 Jun 2009) | 1 line Issue 6256: Fix stacklevel in warning message. ................ r73335 | raymond.hettinger | 2009-06-10 18:15:40 +0200 (Mi, 10 Jun 2009) | 1 line Fix signed/unsigned compiler warning. ................ r73336 | tarek.ziade | 2009-06-10 20:49:50 +0200 (Mi, 10 Jun 2009) | 1 line Distutils: started code cleanup and test coverage for cygwinccompiler ................ r73340 | amaury.forgeotdarc | 2009-06-10 22:30:19 +0200 (Mi, 10 Jun 2009) | 2 lines Fix a typo spotted by Nick Coghlan. ................ r73345 | tarek.ziade | 2009-06-11 10:43:26 +0200 (Do, 11 Jun 2009) | 1 line removed the last string.split() call ................ r73350 | vinay.sajip | 2009-06-11 11:23:41 +0200 (Do, 11 Jun 2009) | 1 line Issue #5262: Fixed bug in next roll over time computation in TimedRotatingFileHandler. ................ r73353 | vinay.sajip | 2009-06-11 11:53:35 +0200 (Do, 11 Jun 2009) | 1 line Issue #5262: Improved fix. ................ r73354 | tarek.ziade | 2009-06-11 11:55:09 +0200 (Do, 11 Jun 2009) | 1 line pep8-fied cygwinccompiler module ................ r73361 | benjamin.peterson | 2009-06-11 18:25:52 +0200 (Do, 11 Jun 2009) | 1 line remove duplicate check ................ r73362 | benjamin.peterson | 2009-06-11 19:49:38 +0200 (Do, 11 Jun 2009) | 1 line revert r73361 ................ r73363 | benjamin.peterson | 2009-06-11 19:51:17 +0200 (Do, 11 Jun 2009) | 1 line use multi-with syntax ................ r73367 | raymond.hettinger | 2009-06-12 00:04:00 +0200 (Fr, 12 Jun 2009) | 1 line Add example of how to do key lookups with bisect(). ................ r73370 | benjamin.peterson | 2009-06-12 00:06:46 +0200 (Fr, 12 Jun 2009) | 105 lines Merged revisions 72523,72950-72951,72994,73003,73033,73036-73040,73091-73093,73096,73179-73181,73192,73231,73244,73255-73256,73365 via svnmerge from svn+ssh://pythondev at svn.python.org/sandbox/trunk/2to3/lib2to3 ........ r72523 | benjamin.peterson | 2009-05-09 14:42:26 -0500 (Sat, 09 May 2009) | 1 line remove parenthesis ........ r72950 | benjamin.peterson | 2009-05-26 18:19:45 -0500 (Tue, 26 May 2009) | 1 line remove unused imports ........ r72951 | benjamin.peterson | 2009-05-26 18:27:00 -0500 (Tue, 26 May 2009) | 1 line this is no longer executable ........ r72994 | benjamin.peterson | 2009-05-28 15:32:54 -0500 (Thu, 28 May 2009) | 1 line fix test_all_fixers on Windows #6134 ........ r73003 | benjamin.peterson | 2009-05-28 21:57:28 -0500 (Thu, 28 May 2009) | 4 lines make 2to3 test utilities easier to use with other applications (3to2) Patch by Joe Amenta ........ r73033 | benjamin.peterson | 2009-05-29 16:58:32 -0500 (Fri, 29 May 2009) | 1 line update grammar for multi with statement ........ r73036 | benjamin.peterson | 2009-05-29 17:33:20 -0500 (Fri, 29 May 2009) | 1 line simplify fix_unicode ........ r73037 | benjamin.peterson | 2009-05-29 17:53:03 -0500 (Fri, 29 May 2009) | 1 line add custom error for pattern syntax errors ........ r73038 | benjamin.peterson | 2009-05-29 17:55:00 -0500 (Fri, 29 May 2009) | 1 line complain if details are attached to a token ........ r73039 | benjamin.peterson | 2009-05-29 18:00:28 -0500 (Fri, 29 May 2009) | 1 line add a test for whitespace ........ r73040 | benjamin.peterson | 2009-05-29 18:01:17 -0500 (Fri, 29 May 2009) | 1 line a fix for emacs highlighting ........ r73091 | benjamin.peterson | 2009-05-31 20:55:25 -0500 (Sun, 31 May 2009) | 1 line deprecate set_prefix() and get_prefix() in favor of a prefix property ........ r73092 | benjamin.peterson | 2009-05-31 21:00:51 -0500 (Sun, 31 May 2009) | 1 line change hideous java naming scheme ........ r73093 | benjamin.peterson | 2009-05-31 21:01:39 -0500 (Sun, 31 May 2009) | 1 line remove dated comment ........ r73096 | benjamin.peterson | 2009-05-31 21:40:53 -0500 (Sun, 31 May 2009) | 1 line group tests ........ r73179 | benjamin.peterson | 2009-06-03 13:09:53 -0500 (Wed, 03 Jun 2009) | 1 line handle the case where there's multiple trailers #6185 ........ r73180 | benjamin.peterson | 2009-06-03 13:18:05 -0500 (Wed, 03 Jun 2009) | 1 line scrap __main__ section ........ r73181 | benjamin.peterson | 2009-06-03 13:24:48 -0500 (Wed, 03 Jun 2009) | 1 line remove shebang lines and __main__ sections ........ r73192 | benjamin.peterson | 2009-06-03 19:16:30 -0500 (Wed, 03 Jun 2009) | 4 lines actually test something here Thanks to Joe Amenta for noticing.y ........ r73231 | benjamin.peterson | 2009-06-04 13:38:50 -0500 (Thu, 04 Jun 2009) | 1 line remove unused variable ........ r73244 | benjamin.peterson | 2009-06-05 08:39:25 -0500 (Fri, 05 Jun 2009) | 1 line allow fixers to give different options in setUp ........ r73255 | benjamin.peterson | 2009-06-06 11:23:46 -0500 (Sat, 06 Jun 2009) | 1 line fix the except fixer on one line suites #6222 ........ r73256 | benjamin.peterson | 2009-06-06 11:27:40 -0500 (Sat, 06 Jun 2009) | 1 line test one-line else and finally clauses ........ r73365 | benjamin.peterson | 2009-06-11 17:01:32 -0500 (Thu, 11 Jun 2009) | 1 line normalize whitespace ........ ................ r73372 | raymond.hettinger | 2009-06-12 00:08:10 +0200 (Fr, 12 Jun 2009) | 1 line Move comment to correct line. ................ r73376 | benjamin.peterson | 2009-06-12 00:29:23 +0200 (Fr, 12 Jun 2009) | 1 line remove check for case handled in sub-function ................ r73382 | raymond.hettinger | 2009-06-12 01:14:53 +0200 (Fr, 12 Jun 2009) | 1 line Issue 6261: Clarify behavior of random.uniform(). ................ r73393 | alexandre.vassalotti | 2009-06-12 20:56:57 +0200 (Fr, 12 Jun 2009) | 2 lines Clear reference to the static PyExc_RecursionErrorInst in _PyExc_Fini. ................ r73394 | antoine.pitrou | 2009-06-12 22:14:08 +0200 (Fr, 12 Jun 2009) | 3 lines Issue #6215: backport the 3.1 io lib ................ r73395 | antoine.pitrou | 2009-06-12 22:36:25 +0200 (Fr, 12 Jun 2009) | 4 lines Restore the old test_file.py (for the builtin file object) as a new file named test_file2k.py ................ r73396 | antoine.pitrou | 2009-06-12 22:41:52 +0200 (Fr, 12 Jun 2009) | 4 lines Try to restore the old test_file and test_univnewlines as new, different files (with the right revisions this time, hopefully) ................ r73397 | antoine.pitrou | 2009-06-12 22:54:21 +0200 (Fr, 12 Jun 2009) | 3 lines Re-enable testing of builtin open() in test_bufio in test_largefile ................ r73398 | alexandre.vassalotti | 2009-06-12 22:57:12 +0200 (Fr, 12 Jun 2009) | 3 lines Add const qualifier to PyErr_SetFromErrnoWithFilename and to PyErr_SetFromErrnoWithUnicodeFilename. ................ r73400 | alexandre.vassalotti | 2009-06-12 23:43:47 +0200 (Fr, 12 Jun 2009) | 2 lines Delete outdated make file for building the parser with MSVC 6. ................ r73401 | alexandre.vassalotti | 2009-06-12 23:52:14 +0200 (Fr, 12 Jun 2009) | 2 lines Make pickling of OrderedDict instances more efficient. ................ r73402 | alexandre.vassalotti | 2009-06-13 01:03:35 +0200 (Sa, 13 Jun 2009) | 6 lines Revert r73401 per Raymond Hettinger's request. The rational is the change might cause imcompatiblity problems with PyYAML. In addition, Raymond wants to kept the different versions of collections synchronized across Python versions. ................ r73404 | benjamin.peterson | 2009-06-13 03:40:00 +0200 (Sa, 13 Jun 2009) | 1 line keep the slice.step field as NULL if no step expression is given ................ r73405 | benjamin.peterson | 2009-06-13 05:46:30 +0200 (Sa, 13 Jun 2009) | 1 line prevent import statements from assigning to None ................ r73409 | benjamin.peterson | 2009-06-13 15:06:21 +0200 (Sa, 13 Jun 2009) | 1 line allow importing from a module named None if it has an 'as' clause ................ r73415 | benjamin.peterson | 2009-06-13 16:25:08 +0200 (Sa, 13 Jun 2009) | 1 line use 'rc' for release candidates for consistency ................ r73417 | benjamin.peterson | 2009-06-13 17:42:23 +0200 (Sa, 13 Jun 2009) | 1 line special case release candidates ................ r73418 | benjamin.peterson | 2009-06-13 17:48:04 +0200 (Sa, 13 Jun 2009) | 1 line handle different rc format ................ r73419 | benjamin.peterson | 2009-06-13 18:19:19 +0200 (Sa, 13 Jun 2009) | 1 line set Print.values to NULL if there are no values ................ r73420 | benjamin.peterson | 2009-06-13 19:08:53 +0200 (Sa, 13 Jun 2009) | 1 line give a better error message when deleting () ................ r73421 | benjamin.peterson | 2009-06-13 22:23:33 +0200 (Sa, 13 Jun 2009) | 1 line when no module is given in a 'from' relative import, make ImportFrom.module NULL ................ r73422 | benjamin.peterson | 2009-06-13 22:30:48 +0200 (Sa, 13 Jun 2009) | 1 line update ast version ................ r73423 | hirokazu.yamamoto | 2009-06-14 05:05:54 +0200 (So, 14 Jun 2009) | 1 line Updated MSVC files to follow r73394. ................ r73432 | amaury.forgeotdarc | 2009-06-14 23:20:40 +0200 (So, 14 Jun 2009) | 3 lines #6227: Because of a wrong indentation, the test was not testing what it should. Ensure that the snippet in doctest_aliases actually contains aliases. ................ r73433 | benjamin.peterson | 2009-06-15 00:36:48 +0200 (Mo, 15 Jun 2009) | 1 line backport r73430 ................ r73435 | tarek.ziade | 2009-06-16 01:04:29 +0200 (Di, 16 Jun 2009) | 1 line code cleanup ................ r73436 | tarek.ziade | 2009-06-16 01:30:13 +0200 (Di, 16 Jun 2009) | 1 line Issue #6286: distutils upload command now uses urllib2 ................ r73439 | benjamin.peterson | 2009-06-16 02:29:31 +0200 (Di, 16 Jun 2009) | 1 line don't mask encoding errors when decoding a string #6289 ................ r73445 | tarek.ziade | 2009-06-16 10:31:01 +0200 (Di, 16 Jun 2009) | 1 line starting distutils.ccompiler test coverage and cleanup ................ r73447 | georg.brandl | 2009-06-16 19:41:33 +0200 (Di, 16 Jun 2009) | 1 line Add tabularcolumns directive for tables with bullet lists in them. ................ r73448 | georg.brandl | 2009-06-16 19:43:44 +0200 (Di, 16 Jun 2009) | 1 line Remove unused macro. ................ r73457 | benjamin.peterson | 2009-06-17 01:13:09 +0200 (Mi, 17 Jun 2009) | 1 line add underscores ................ r73460 | benjamin.peterson | 2009-06-17 05:23:04 +0200 (Mi, 17 Jun 2009) | 1 line remove unused 'encoding' member from the compiler struct ................ r73461 | hirokazu.yamamoto | 2009-06-17 09:05:33 +0200 (Mi, 17 Jun 2009) | 1 line Issue #6215: Fixed to use self.open() instead of open() or io.open(). ................ r73465 | nick.coghlan | 2009-06-17 14:12:15 +0200 (Mi, 17 Jun 2009) | 1 line Issue 6288: update the contextlib.nested() docs to explain why it has been deprecated and should generally be avoided ................ r73471 | georg.brandl | 2009-06-19 00:24:26 +0200 (Fr, 19 Jun 2009) | 1 line #6276: Remove usage of nested() in favor of new with statement with multiple managers. ................ r73472 | amaury.forgeotdarc | 2009-06-19 00:32:50 +0200 (Fr, 19 Jun 2009) | 5 lines #6189: The subprocess.py module should be kept compatible with python 2.2 (On windows, you still have to change one line to use pywin32 instead of the _subprocess helper module) ................ r73480 | facundo.batista | 2009-06-19 20:02:28 +0200 (Fr, 19 Jun 2009) | 3 lines Issue #6274. Fixed a potential FD leak in subprocess.py. ................ r73485 | benjamin.peterson | 2009-06-20 00:07:47 +0200 (Sa, 20 Jun 2009) | 1 line remove duplicate test ................ r73486 | benjamin.peterson | 2009-06-20 00:09:17 +0200 (Sa, 20 Jun 2009) | 1 line add missing assertion #6313 ................ r73488 | benjamin.peterson | 2009-06-20 00:16:28 +0200 (Sa, 20 Jun 2009) | 1 line show that this one isn't used ................ r73489 | benjamin.peterson | 2009-06-20 00:21:12 +0200 (Sa, 20 Jun 2009) | 1 line use closures ................ r73490 | tarek.ziade | 2009-06-20 15:57:20 +0200 (Sa, 20 Jun 2009) | 1 line Fixed #6164 AIX specific linker argument in Distutils unixcompiler ................ r73495 | guilherme.polo | 2009-06-21 19:22:50 +0200 (So, 21 Jun 2009) | 4 lines Issue #5450: Moved tests involving loading tk from Lib/test/test_tcl to Lib/lib-tk/test/test_tkinter/test_loadtk in order to follow the behaviour of test_ttkguionly. ................ r73496 | vinay.sajip | 2009-06-21 19:37:27 +0200 (So, 21 Jun 2009) | 1 line Issue #6314: logging.basicConfig() performs extra checks on the "level" argument. ................ r73499 | steven.bethard | 2009-06-21 23:03:41 +0200 (So, 21 Jun 2009) | 1 line Fix memory bug in bdist_msi. (Commit okayed in issue6319.) ................ r73501 | benjamin.peterson | 2009-06-22 01:01:07 +0200 (Mo, 22 Jun 2009) | 1 line don't need to add the name 'lambda' as assigned ................ r73502 | benjamin.peterson | 2009-06-22 01:03:36 +0200 (Mo, 22 Jun 2009) | 1 line remove tmpname support since it's no longer used ................ r73509 | amaury.forgeotdarc | 2009-06-22 21:33:48 +0200 (Mo, 22 Jun 2009) | 2 lines #4490 Fix sample code run by "python -m xml.sax.xmlreader" ................ r73513 | benjamin.peterson | 2009-06-23 03:18:57 +0200 (Di, 23 Jun 2009) | 1 line fix grammar ................ r73514 | benjamin.peterson | 2009-06-23 05:01:56 +0200 (Di, 23 Jun 2009) | 1 line remove some unused symtable constants ................ r73518 | nick.coghlan | 2009-06-23 12:19:30 +0200 (Di, 23 Jun 2009) | 1 line Issue 6288: Update contextlib.nested() docstring to reflect new documentation ................ r73519 | nick.coghlan | 2009-06-23 12:51:02 +0200 (Di, 23 Jun 2009) | 1 line Remove markup from docstring ................ r73532 | raymond.hettinger | 2009-06-23 22:59:43 +0200 (Di, 23 Jun 2009) | 3 lines Issue 6329: Fix iteration for memoryviews. ................ r73534 | amaury.forgeotdarc | 2009-06-23 23:09:09 +0200 (Di, 23 Jun 2009) | 2 lines Remove the ipaddr module per discussion on python-dev ................ r73536 | raymond.hettinger | 2009-06-23 23:32:28 +0200 (Di, 23 Jun 2009) | 1 line Issue 6305: Clarify error message for large arguments to itertools.islice(). ................ r73537 | amaury.forgeotdarc | 2009-06-23 23:53:46 +0200 (Di, 23 Jun 2009) | 3 lines Remove last remnants of the ipaddr package. The changes in mcast.py come from the first version of the patch for issue5379. ................ r73540 | raymond.hettinger | 2009-06-24 00:20:04 +0200 (Mi, 24 Jun 2009) | 1 line Add procedural note. ................ r73546 | kristjan.jonsson | 2009-06-24 11:17:04 +0200 (Mi, 24 Jun 2009) | 2 lines http://bugs.python.org/issue6192 Move the newly introduced disable_nagle_algorithm flag into the StreamRequestHandler, where it is more appropriate. ................ r73563 | amaury.forgeotdarc | 2009-06-25 23:29:32 +0200 (Do, 25 Jun 2009) | 2 lines Fix a compilation warning on Windows ................ r73564 | amaury.forgeotdarc | 2009-06-26 00:29:29 +0200 (Fr, 26 Jun 2009) | 6 lines #2016 Fix a crash in function call when the **kwargs dictionary is mutated during the function call setup. This even gives a slight speedup, probably because tuple allocation is faster than PyMem_NEW. ................ r73603 | hirokazu.yamamoto | 2009-06-28 12:23:00 +0200 (So, 28 Jun 2009) | 1 line Issue #4856: Remove checks for win NT. ................ r73605 | georg.brandl | 2009-06-28 14:10:18 +0200 (So, 28 Jun 2009) | 1 line Remove stray pychecker directive. ................ r73606 | martin.v.loewis | 2009-06-28 14:24:23 +0200 (So, 28 Jun 2009) | 2 lines Fix types in logic to compute help file name. ................ r73614 | benjamin.peterson | 2009-06-28 18:08:02 +0200 (So, 28 Jun 2009) | 1 line add two generic macros for peeking and setting in the stack ................ r73615 | benjamin.peterson | 2009-06-28 18:14:07 +0200 (So, 28 Jun 2009) | 1 line use stack macros ................ r73627 | benjamin.peterson | 2009-06-28 21:27:55 +0200 (So, 28 Jun 2009) | 1 line return locals and cells in get_locals() not bound globals, though ................ r73638 | kristjan.jonsson | 2009-06-28 23:04:17 +0200 (So, 28 Jun 2009) | 2 lines http://bugs.python.org/issue6267 Cumulative patch to http and xmlrpc ................ r73660 | mark.dickinson | 2009-06-29 00:37:13 +0200 (Mo, 29 Jun 2009) | 1 line Remove unused stdint.h includes ................ r73665 | alexandre.vassalotti | 2009-06-29 03:01:51 +0200 (Mo, 29 Jun 2009) | 2 lines Update docstrings for sys.getdlopenflags() and sys.setdlopenflags(). ................ r73675 | hirokazu.yamamoto | 2009-06-29 13:27:03 +0200 (Mo, 29 Jun 2009) | 3 lines Issue #4856: Py_GetFileAttributesEx[AW] are not needed because GetFileAttributesEx[AW] won't fail with ERROR_CALL_NOT_IMPLEMENTED on win NT. Reviewed by Amaury Forgeot d'Arc. ................ r73679 | antoine.pitrou | 2009-06-29 16:14:56 +0200 (Mo, 29 Jun 2009) | 3 lines Backport fix for buglet from py3k ................ r73686 | hirokazu.yamamoto | 2009-06-29 17:52:21 +0200 (Mo, 29 Jun 2009) | 1 line Issue #6368: Fixed unused variable warning on Unix. ................ r73688 | tarek.ziade | 2009-06-29 18:13:39 +0200 (Mo, 29 Jun 2009) | 1 line Fixed 6365: wrong inplace location for build_ext if the extension had dots ................ r73697 | raymond.hettinger | 2009-06-29 21:10:29 +0200 (Mo, 29 Jun 2009) | 1 line Issue 6370: Performance issue with collections.Counter(). ................ r73701 | mark.dickinson | 2009-06-30 17:32:30 +0200 (Di, 30 Jun 2009) | 3 lines Issue #6347: Add inttypes.h to the pyport.h #includes; fixes a build failure on HP-UX 11.00. ................ r73710 | benjamin.peterson | 2009-07-01 00:14:33 +0200 (Mi, 01 Jul 2009) | 1 line provide a dummy __exit__ on windows ................ r73712 | ezio.melotti | 2009-07-01 00:51:06 +0200 (Mi, 01 Jul 2009) | 1 line Fixed defaultTestCase -> defaultTestResult ................ r73714 | benjamin.peterson | 2009-07-01 00:57:08 +0200 (Mi, 01 Jul 2009) | 1 line convert usage of fail* to assert* ................ r73717 | benjamin.peterson | 2009-07-01 01:30:12 +0200 (Mi, 01 Jul 2009) | 1 line use assert* methods in test_unittest ................ r73720 | benjamin.peterson | 2009-07-01 02:36:41 +0200 (Mi, 01 Jul 2009) | 4 lines fix a few cases where automated fail -> assert translation messed up Thanks Joe Amenta ................ r73725 | benjamin.peterson | 2009-07-01 02:49:09 +0200 (Mi, 01 Jul 2009) | 21 lines Merged revisions 73379,73388,73507,73722 via svnmerge from svn+ssh://pythondev at svn.python.org/sandbox/trunk/2to3/lib2to3 ........ r73379 | benjamin.peterson | 2009-06-11 18:06:21 -0500 (Thu, 11 Jun 2009) | 1 line use a real conditional expresion ........ r73388 | benjamin.peterson | 2009-06-12 09:44:29 -0500 (Fri, 12 Jun 2009) | 1 line fix typo in last fix ........ r73507 | benjamin.peterson | 2009-06-22 13:32:04 -0500 (Mon, 22 Jun 2009) | 1 line remove svn:executable property ........ r73722 | benjamin.peterson | 2009-06-30 19:44:30 -0500 (Tue, 30 Jun 2009) | 1 line replace fail* with assert* ........ ................ r73744 | benjamin.peterson | 2009-07-01 15:34:35 +0200 (Mi, 01 Jul 2009) | 1 line proxy the __exit__ call ................ r73750 | benjamin.peterson | 2009-07-02 01:45:19 +0200 (Do, 02 Jul 2009) | 1 line small optimization: avoid popping the current block until we have to ................ r73756 | tarek.ziade | 2009-07-02 14:47:54 +0200 (Do, 02 Jul 2009) | 1 line raising bdist_dumb test coverage ................ r73757 | tarek.ziade | 2009-07-02 14:51:56 +0200 (Do, 02 Jul 2009) | 1 line cleaned up the bdist_dumb module ................ r73762 | tarek.ziade | 2009-07-02 16:20:47 +0200 (Do, 02 Jul 2009) | 1 line pep8-fied and cleaned up distutils.util ................ r73767 | jesus.cea | 2009-07-02 16:30:18 +0200 (Do, 02 Jul 2009) | 1 line multiprocessing doesn't compile in Solaris because a typo ................ r73773 | benjamin.peterson | 2009-07-02 18:51:56 +0200 (Do, 02 Jul 2009) | 1 line remove this test; a module level warning is enough ................ r73781 | benjamin.peterson | 2009-07-02 23:38:36 +0200 (Do, 02 Jul 2009) | 1 line test that compile() accepts the future flag ................ r73786 | benjamin.peterson | 2009-07-03 00:56:16 +0200 (Fr, 03 Jul 2009) | 1 line condense with assertRaises ................ r73801 | tarek.ziade | 2009-07-03 11:01:07 +0200 (Fr, 03 Jul 2009) | 1 line cleaned up distutils.command.build_py ................ r73814 | tarek.ziade | 2009-07-03 21:01:12 +0200 (Fr, 03 Jul 2009) | 1 line basic tests to raise distutils.file_util coverage ................ r73815 | tarek.ziade | 2009-07-03 21:14:49 +0200 (Fr, 03 Jul 2009) | 1 line cleaned distutils.file_util ................ r73818 | gregory.p.smith | 2009-07-03 22:48:31 +0200 (Fr, 03 Jul 2009) | 2 lines Adds the select.PIPE_BUF attribute to expose the system constant. ................ r73819 | kristjan.jonsson | 2009-07-04 01:07:07 +0200 (Sa, 04 Jul 2009) | 2 lines http://bugs.python.org/issue6381 some platforms may raise ENOTCONN if the stack has disconnected the socket on behalf of the peer. ................ r73821 | kristjan.jonsson | 2009-07-04 01:26:02 +0200 (Sa, 04 Jul 2009) | 2 lines http://bugs.python.org/issue6267 Incorrect exception handling for xmlrp client retry ................ r73822 | kristjan.jonsson | 2009-07-04 01:29:50 +0200 (Sa, 04 Jul 2009) | 2 lines http://bugs.python.org/issue6267 Incorrect exception handling for xmlrpc client retry ................ r73825 | gregory.p.smith | 2009-07-04 03:49:29 +0200 (Sa, 04 Jul 2009) | 9 lines Use select.poll() in subprocess, when available, rather than select() so that it does not fail when file descriptors are large. Fixes issue3392. Patch largely contributed by Frank Chu (fpmc) with some improvements by me. See http://bugs.python.org/issue3392. Candidate for backporting to release26-maint as it is a bug fix and changes no public API. ................ r73826 | gregory.p.smith | 2009-07-04 03:55:11 +0200 (Sa, 04 Jul 2009) | 2 lines news entry for r73825 ................ r73827 | tarek.ziade | 2009-07-04 04:02:41 +0200 (Sa, 04 Jul 2009) | 1 line Fixed #6413: fixed log level in distutils.dist.announce ................ r73834 | tarek.ziade | 2009-07-04 04:59:19 +0200 (Sa, 04 Jul 2009) | 1 line using print statements when used for user interaction ................ r73839 | gregory.p.smith | 2009-07-04 10:42:10 +0200 (Sa, 04 Jul 2009) | 3 lines Merge r73838 from py3k branch. Use the nondeprecated unittest method names. ................ r73841 | ezio.melotti | 2009-07-04 16:58:27 +0200 (Sa, 04 Jul 2009) | 1 line if zlib -> skipUnless(zlib) and minor cleanups ................ r73846 | alexandre.vassalotti | 2009-07-05 06:22:40 +0200 (So, 05 Jul 2009) | 6 lines Issue 2370: Add Python 3 warnings for the removal of operator.isCallable and operator.sequenceIncludes. Patch contributed by Jeff Balogh (and updated slightly by me). ................ r73847 | alexandre.vassalotti | 2009-07-05 06:25:46 +0200 (So, 05 Jul 2009) | 2 lines Fix bad variable name in r73846. ................ r73854 | alexandre.vassalotti | 2009-07-05 08:33:41 +0200 (So, 05 Jul 2009) | 2 lines Backport test cases added in r73852. ................ r73858 | mark.dickinson | 2009-07-05 12:01:24 +0200 (So, 05 Jul 2009) | 3 lines Issues #1530559, #1741130: Fix various inconsistencies in struct.pack integer packing, and reenable some previously broken tests. ................ r73863 | kristjan.jonsson | 2009-07-05 22:56:57 +0200 (So, 05 Jul 2009) | 2 lines http://bugs.python.org/issue6382 close_request() (which can send a socket.shutdown()) must be called by the child process in a forking server. The parent must merely close the socket handle. ................ r73864 | tarek.ziade | 2009-07-06 14:50:46 +0200 (Mo, 06 Jul 2009) | 1 line Fixed #6377: distutils compiler switch ignored (and added a deprecation warning if compiler is not used as supposed = a string option) ................ r73871 | alexandre.vassalotti | 2009-07-07 04:17:30 +0200 (Di, 07 Jul 2009) | 7 lines Grow the allocated buffer in PyUnicode_EncodeUTF7 to avoid buffer overrun. Without this change, test_unicode.UnicodeTest.test_codecs_utf7 crashes in debug mode. What happens is the unicode string u'\U000abcde' with a length of 1 encodes to the string '+2m/c3g-' of length 8. Since only 5 bytes is reserved in the buffer, a buffer overrun occurs. ................ r73877 | kristjan.jonsson | 2009-07-07 11:01:34 +0200 (Di, 07 Jul 2009) | 2 lines http://bugs.python.org/issue6382 added the shutdown_request() which can perform shutdown before calling close. This is needed for the ForkingMixIn because different close semantics are required for child and parent process. shutdown_request(), for TCP servers, calls socket.shutdown() and then calls close_request(). Therefore, this is not an backwards incompatible change, since subclasses that continue to override close_request() continue to work. ................ r73884 | mark.dickinson | 2009-07-07 13:08:23 +0200 (Di, 07 Jul 2009) | 1 line Add skipping to struct test that only applies when overflow masking is in effect ................ r73888 | mark.dickinson | 2009-07-07 16:15:45 +0200 (Di, 07 Jul 2009) | 3 lines Expand test coverage for struct.pack with native integer packing; reorganize the test_struct module to remove duplicated code and tests. ................ r73891 | mark.dickinson | 2009-07-07 17:08:28 +0200 (Di, 07 Jul 2009) | 3 lines Issue #1523: Remove deprecated overflow masking in struct module, and make sure that out-of-range values consistently raise struct.error. ................ r73895 | tarek.ziade | 2009-07-09 00:40:51 +0200 (Do, 09 Jul 2009) | 1 line Sets the compiler attribute to keep the old behavior for third-party packages. ................ r73901 | tarek.ziade | 2009-07-09 09:42:42 +0200 (Do, 09 Jul 2009) | 1 line PendingDeprecationWarning -> DeprecationWarning in build_ext ................ r73916 | amaury.forgeotdarc | 2009-07-10 00:37:22 +0200 (Fr, 10 Jul 2009) | 5 lines #6416: Fix compilation of the select module on Windows, as well as test_subprocess: PIPE_BUF is not defined on Windows, and probably has no meaning there. Anyway the subprocess module uses another way to perform non-blocking reads (with a thread) ................ r73925 | tarek.ziade | 2009-07-10 11:57:15 +0200 (Fr, 10 Jul 2009) | 1 line Added test coverage for distutils.command.build ................ r73926 | tarek.ziade | 2009-07-10 12:00:21 +0200 (Fr, 10 Jul 2009) | 1 line cleaned up distutils.command.build ................ r73930 | amaury.forgeotdarc | 2009-07-10 18:47:42 +0200 (Fr, 10 Jul 2009) | 2 lines #6447: typo in subprocess docstring ................ r73931 | ezio.melotti | 2009-07-10 22:25:56 +0200 (Fr, 10 Jul 2009) | 1 line more cleanups and if zlib -> skipUnless(zlib) ................ r73932 | kristjan.jonsson | 2009-07-11 10:44:43 +0200 (Sa, 11 Jul 2009) | 3 lines http://bugs.python.org/issue6460 Need to be careful with thread switching when testing the xmlrpc server. The server thread may not have updated stats when the client thread tests them. ................ r73933 | amaury.forgeotdarc | 2009-07-11 11:09:59 +0200 (Sa, 11 Jul 2009) | 3 lines Add basic tests for the return value of os.popen().close(). According to #6358, python 3.0 has a different implementation that behaves differently. ................ r73944 | tarek.ziade | 2009-07-11 12:48:31 +0200 (Sa, 11 Jul 2009) | 1 line cleaned up distutils.build_ext module ................ r73962 | benjamin.peterson | 2009-07-12 00:15:13 +0200 (So, 12 Jul 2009) | 1 line put downloaded test support files in Lib/test/data instead of the cwd ................ r73963 | benjamin.peterson | 2009-07-12 00:25:24 +0200 (So, 12 Jul 2009) | 1 line ignore things in Lib/test/data/ ................ r73985 | benjamin.peterson | 2009-07-12 23:18:55 +0200 (So, 12 Jul 2009) | 1 line add Joe ................ r73986 | kristjan.jonsson | 2009-07-13 00:42:08 +0200 (Mo, 13 Jul 2009) | 2 lines http://bugs.python.org/issue6267 Add more tests for the xlmrpc.ServerProxy ................ r73988 | benjamin.peterson | 2009-07-13 01:40:33 +0200 (Mo, 13 Jul 2009) | 1 line fix Tarek's name ................ r73989 | benjamin.peterson | 2009-07-13 01:44:43 +0200 (Mo, 13 Jul 2009) | 1 line change encoding to utf-8 ................ r73990 | benjamin.peterson | 2009-07-13 01:49:23 +0200 (Mo, 13 Jul 2009) | 1 line fix another name ................ r73991 | benjamin.peterson | 2009-07-13 01:56:18 +0200 (Mo, 13 Jul 2009) | 1 line change encoding to utf-8 ................ r73994 | benjamin.peterson | 2009-07-13 02:03:20 +0200 (Mo, 13 Jul 2009) | 1 line fix umlaut ................ r73995 | vinay.sajip | 2009-07-13 13:21:05 +0200 (Mo, 13 Jul 2009) | 1 line Issue #6314: logging: Extra checks on the "level" argument in more places. ................ r73998 | amaury.forgeotdarc | 2009-07-13 21:14:17 +0200 (Mo, 13 Jul 2009) | 3 lines Set svn:eol-style=CRLF on all Visual Studio solution files. This should allow direct compilation from a downloaded source tar ball. ................ r74000 | amaury.forgeotdarc | 2009-07-13 22:01:11 +0200 (Mo, 13 Jul 2009) | 4 lines #1616979: Add the cp720 (Arabic DOS) encoding. Since there is no official mapping file from unicode.org, the codec file is generated on Windows with the new genwincodec.py script. ................ Modified: python/branches/release26-maint/ (props changed) From python-checkins at python.org Wed May 19 15:08:36 2010 From: python-checkins at python.org (georg.brandl) Date: Wed, 19 May 2010 15:08:36 +0200 (CEST) Subject: [Python-checkins] r81328 - python/branches/release26-maint Message-ID: <20100519130836.C0567EBC5@mail.python.org> Author: georg.brandl Date: Wed May 19 15:08:36 2010 New Revision: 81328 Log: Blocked revisions 74000-74002,74005-74007,74011,74014,74019,74023-74024,74028-74029,74031-74033,74038-74039,74044,74048,74051,74067,74069,74072,74080,74083,74089,74095,74098,74100,74114,74117,74119,74123,74134,74139,74147,74150,74152,74163,74173,74187,74197,74201,74216,74219,74240,74243,74265,74269,74277,74300,74312,74321,74323,74336,74355,74365,74426,74446-74449,74463-74464,74471-74472,74477,74479,74490,74493,74495,74501,74503,74507-74511,74513,74517,74519,74522-74524,74526,74537,74542-74543,74556,74558,74569-74571,74581,74604,74625,74635-74637,74640,74644,74650,74667,74699,74702,74715,74721,74723,74733-74734,74750,74754,74780,74783,74785-74786,74811-74812,74843,74849,74853,74860,74886,74901,74908,74912-74913,74925,74929,74936-74937,74954-74955,74970,74988,74992,74994,74997 via svnmerge ................ r74000 | amaury.forgeotdarc | 2009-07-13 22:01:11 +0200 (Mo, 13 Jul 2009) | 4 lines #1616979: Add the cp720 (Arabic DOS) encoding. Since there is no official mapping file from unicode.org, the codec file is generated on Windows with the new genwincodec.py script. ................ r74001 | amaury.forgeotdarc | 2009-07-13 22:03:21 +0200 (Mo, 13 Jul 2009) | 2 lines NEWS entry for r74000. ................ r74002 | marc-andre.lemburg | 2009-07-13 22:23:49 +0200 (Mo, 13 Jul 2009) | 6 lines Use a new global DEV_NULL instead of hard-coding /dev/null into the system command helper functions. See #6479 for some motivation. ................ r74005 | marc-andre.lemburg | 2009-07-13 23:28:33 +0200 (Mo, 13 Jul 2009) | 6 lines Use a different VER command output parser to address the localization issues mentioned in #3410. Prepare for Windows 7 (still commented out). ................ r74006 | amaury.forgeotdarc | 2009-07-14 01:11:54 +0200 (Di, 14 Jul 2009) | 2 lines Document the newly added codec ................ r74007 | michael.foord | 2009-07-14 19:58:12 +0200 (Di, 14 Jul 2009) | 1 line Move TestRunner initialisation into unittest.TestProgram.runTests. Fixes issue 6418. ................ r74011 | ezio.melotti | 2009-07-15 19:07:04 +0200 (Mi, 15 Jul 2009) | 1 line methods' names pep8ification ................ r74014 | alexandre.vassalotti | 2009-07-15 20:19:47 +0200 (Mi, 15 Jul 2009) | 3 lines Issue #2389: Pickle array objects using a list representation for portability across different machine architectures and compatibility with Python 3.x. ................ r74019 | amaury.forgeotdarc | 2009-07-15 23:29:27 +0200 (Mi, 15 Jul 2009) | 2 lines #6076 Add a title to the IDLE Preferences window. ................ r74023 | jesse.noller | 2009-07-16 16:23:04 +0200 (Do, 16 Jul 2009) | 1 line Issue 6433: multiprocessing.pool.map hangs on empty list ................ r74024 | tarek.ziade | 2009-07-16 17:35:45 +0200 (Do, 16 Jul 2009) | 1 line #6466 refactored distutils duplicate get_versions() functions (used to get gcc/ld/dllwrap versions) ................ r74028 | georg.brandl | 2009-07-16 21:24:48 +0200 (Do, 16 Jul 2009) | 1 line #6482: simplify "except: raise" to "finally:". ................ r74029 | georg.brandl | 2009-07-16 23:47:51 +0200 (Do, 16 Jul 2009) | 1 line Revert r74028. ................ r74031 | alexandre.vassalotti | 2009-07-17 06:24:45 +0200 (Fr, 17 Jul 2009) | 2 lines Use AC_CHECK_SIZEOF to find the size of off_t, pthread_t and time_t. ................ r74032 | alexandre.vassalotti | 2009-07-17 06:59:05 +0200 (Fr, 17 Jul 2009) | 4 lines Rename the useless AC_INCLUDES_DEFAULT and protect the includes. This is mostly an aesthetic change. ................ r74033 | alexandre.vassalotti | 2009-07-17 07:26:39 +0200 (Fr, 17 Jul 2009) | 8 lines Cache the results of all runtime checks. This will be helpful to people who want to compile Python with a cross-compiler. Now you can upload the configure script on your host machine, run it with caching enabled, and download the cached results on your build machine. ................ r74038 | alexandre.vassalotti | 2009-07-17 08:10:06 +0200 (Fr, 17 Jul 2009) | 3 lines Double-quote the test cases for chflags() and lchflags() to ensure they don't get mangled. ................ r74039 | alexandre.vassalotti | 2009-07-17 08:17:33 +0200 (Fr, 17 Jul 2009) | 2 lines Clean up the test case for broken poll(). ................ r74044 | alexandre.vassalotti | 2009-07-17 08:33:51 +0200 (Fr, 17 Jul 2009) | 3 lines Double-quote the test case for %zd printf() format support to avoid mangling the array declarations in it. ................ r74048 | alexandre.vassalotti | 2009-07-17 09:46:46 +0200 (Fr, 17 Jul 2009) | 2 lines Regenerate configure script. ................ r74051 | alexandre.vassalotti | 2009-07-17 09:54:23 +0200 (Fr, 17 Jul 2009) | 2 lines Initialize variables in PyCurses_getsyx() to avoid compiler warnings. ................ r74067 | alexandre.vassalotti | 2009-07-18 01:09:02 +0200 (Sa, 18 Jul 2009) | 2 lines Revert r74048. ................ r74069 | alexandre.vassalotti | 2009-07-18 01:17:48 +0200 (Sa, 18 Jul 2009) | 2 lines Regenerate configure script using autoconf 2.61. ................ r74072 | alexandre.vassalotti | 2009-07-18 02:31:06 +0200 (Sa, 18 Jul 2009) | 5 lines Add a check to ensure the correct autoconf version is used for generating the configure script. Original idea by Martin von L?wis. ................ r74080 | mark.dickinson | 2009-07-18 17:18:18 +0200 (Sa, 18 Jul 2009) | 3 lines Issue #6431: Fix Fraction comparisons with unknown types, and with float infinities and nans. Backport of r74078 from py3k. ................ r74083 | mark.dickinson | 2009-07-18 18:01:57 +0200 (Sa, 18 Jul 2009) | 1 line Add Case Van Horsen to Misc/ACKS, for fractions module patches and other work ................ r74089 | senthil.kumaran | 2009-07-19 04:43:43 +0200 (So, 19 Jul 2009) | 3 lines Fix for issue5102, timeout value propages between redirects, proxy, digest and auth handlers. Fixed tests to reflect the same. ................ r74095 | benjamin.peterson | 2009-07-19 22:18:21 +0200 (So, 19 Jul 2009) | 1 line split unittest.py into a package ................ r74098 | kristjan.jonsson | 2009-07-20 00:14:00 +0200 (Mo, 20 Jul 2009) | 2 lines http://bugs.python.org/issue6499 zlib/gzip may not be present for all builds. Make xmlrpclib gracefully not supporg gzip encoding in this case ................ r74100 | kristjan.jonsson | 2009-07-20 00:35:44 +0200 (Mo, 20 Jul 2009) | 2 lines http://bugs.python.org/issue6499 gzip.GzipFile may not exist as a parent class ................ r74114 | benjamin.peterson | 2009-07-20 17:33:09 +0200 (Mo, 20 Jul 2009) | 110 lines Merged revisions 73771,73811,73840,73842,73848-73849,73861,73957-73960,73964-73969,73972-73974,73977,73981,73984,74065,74113 via svnmerge from svn+ssh://pythondev at svn.python.org/sandbox/trunk/2to3/lib2to3 ........ r73771 | benjamin.peterson | 2009-07-02 10:56:55 -0500 (Thu, 02 Jul 2009) | 1 line force the imports fixer to be run after the import one #6400 ........ r73811 | benjamin.peterson | 2009-07-03 09:03:14 -0500 (Fri, 03 Jul 2009) | 1 line check for sep, not pathsep when looking for a subpackage #6408 ........ r73840 | benjamin.peterson | 2009-07-04 09:52:28 -0500 (Sat, 04 Jul 2009) | 1 line don't print diffs by default; it's annoying ........ r73842 | benjamin.peterson | 2009-07-04 09:58:46 -0500 (Sat, 04 Jul 2009) | 1 line complain when not showing diffs or writing ........ r73848 | alexandre.vassalotti | 2009-07-04 23:38:19 -0500 (Sat, 04 Jul 2009) | 2 lines Fix test_refactor_stdin to handle print_output() method with 4 arguments. ........ r73849 | alexandre.vassalotti | 2009-07-04 23:43:18 -0500 (Sat, 04 Jul 2009) | 5 lines Issue 2370: Add fixer for the removal of operator.isCallable() and operator.sequenceIncludes(). Patch contributed by Jeff Balogh (and updated by me). ........ r73861 | benjamin.peterson | 2009-07-05 09:15:53 -0500 (Sun, 05 Jul 2009) | 1 line cleanup and use unicode where appropiate ........ r73957 | benjamin.peterson | 2009-07-11 15:49:56 -0500 (Sat, 11 Jul 2009) | 1 line fix calls to str() with unicode() ........ r73958 | benjamin.peterson | 2009-07-11 15:51:51 -0500 (Sat, 11 Jul 2009) | 1 line more str() -> unicode() ........ r73959 | benjamin.peterson | 2009-07-11 16:40:08 -0500 (Sat, 11 Jul 2009) | 1 line add tests for refactor_dir() ........ r73960 | benjamin.peterson | 2009-07-11 16:44:32 -0500 (Sat, 11 Jul 2009) | 1 line don't parse files just because they end with 'py' (no dot) ........ r73964 | benjamin.peterson | 2009-07-11 17:30:15 -0500 (Sat, 11 Jul 2009) | 1 line simplify ........ r73965 | benjamin.peterson | 2009-07-11 17:31:30 -0500 (Sat, 11 Jul 2009) | 1 line remove usage of get_prefix() ........ r73966 | benjamin.peterson | 2009-07-11 17:33:35 -0500 (Sat, 11 Jul 2009) | 1 line revert unintended change in 73965 ........ r73967 | benjamin.peterson | 2009-07-11 17:34:44 -0500 (Sat, 11 Jul 2009) | 1 line avoid expensive checks and assume the node did change ........ r73968 | benjamin.peterson | 2009-07-11 20:46:46 -0500 (Sat, 11 Jul 2009) | 1 line use a regular dict for the heads to avoid adding lists in the loop ........ r73969 | benjamin.peterson | 2009-07-11 20:50:43 -0500 (Sat, 11 Jul 2009) | 1 line prefix headnode functions with '_' ........ r73972 | benjamin.peterson | 2009-07-11 21:25:45 -0500 (Sat, 11 Jul 2009) | 1 line try to make the head node dict as sparse as possible ........ r73973 | benjamin.peterson | 2009-07-11 21:59:49 -0500 (Sat, 11 Jul 2009) | 1 line a better idea; add an option to *not* print diffs ........ r73974 | benjamin.peterson | 2009-07-11 22:00:29 -0500 (Sat, 11 Jul 2009) | 1 line add space ........ r73977 | benjamin.peterson | 2009-07-12 10:16:07 -0500 (Sun, 12 Jul 2009) | 1 line update get_headnode_dict tests for recent changes ........ r73981 | benjamin.peterson | 2009-07-12 12:06:39 -0500 (Sun, 12 Jul 2009) | 4 lines detect when "from __future__ import print_function" is given Deprecate the 'print_function' option and the -p flag ........ r73984 | benjamin.peterson | 2009-07-12 16:16:37 -0500 (Sun, 12 Jul 2009) | 1 line add tests for Call; thanks Joe Amenta ........ r74065 | benjamin.peterson | 2009-07-17 12:52:49 -0500 (Fri, 17 Jul 2009) | 1 line pathname2url and url2pathname are in urllib.request not urllib.parse #6496 ........ r74113 | benjamin.peterson | 2009-07-20 08:56:57 -0500 (Mon, 20 Jul 2009) | 1 line fix deprecation warnings in tests ........ ................ r74117 | benjamin.peterson | 2009-07-20 19:24:30 +0200 (Mo, 20 Jul 2009) | 9 lines Merged revisions 74116 via svnmerge from svn+ssh://pythondev at svn.python.org/sandbox/trunk/2to3/lib2to3 ........ r74116 | benjamin.peterson | 2009-07-20 12:22:35 -0500 (Mon, 20 Jul 2009) | 1 line placate windows ........ ................ r74119 | benjamin.peterson | 2009-07-20 22:28:08 +0200 (Mo, 20 Jul 2009) | 2 lines the Slice in x[::] has to have step as None to help the interpreter ................ r74123 | benjamin.peterson | 2009-07-20 23:09:45 +0200 (Mo, 20 Jul 2009) | 13 lines Merged revisions 74121-74122 via svnmerge from svn+ssh://pythondev at svn.python.org/sandbox/trunk/2to3/lib2to3 ........ r74121 | benjamin.peterson | 2009-07-20 15:40:59 -0500 (Mon, 20 Jul 2009) | 1 line try to make warning tests more robust ........ r74122 | benjamin.peterson | 2009-07-20 15:44:14 -0500 (Mon, 20 Jul 2009) | 1 line platform compat ........ ................ r74134 | thomas.heller | 2009-07-21 08:27:14 +0200 (Di, 21 Jul 2009) | 3 lines Issue #6493: Fix a ctypes problem setting bitfields more than 31 bits wide. ................ r74139 | benjamin.peterson | 2009-07-21 16:08:40 +0200 (Di, 21 Jul 2009) | 1 line must use _PyThreadState_Current so it isn't checked for NULL #6530 ................ r74147 | thomas.heller | 2009-07-21 21:04:02 +0200 (Di, 21 Jul 2009) | 1 line Revert rev 74134, as it does not completely fixx issue #6493. ................ r74150 | benjamin.peterson | 2009-07-22 01:13:14 +0200 (Mi, 22 Jul 2009) | 1 line install unittest as a package ................ r74152 | benjamin.peterson | 2009-07-22 02:03:43 +0200 (Mi, 22 Jul 2009) | 1 line simplify ................ r74163 | tarek.ziade | 2009-07-22 10:55:19 +0200 (Mi, 22 Jul 2009) | 1 line Issue #6545: Removed assert statements in distutils.Extension, so the behavior is similar when used with -O ................ r74173 | benjamin.peterson | 2009-07-22 18:34:37 +0200 (Mi, 22 Jul 2009) | 1 line revert r74152 ................ r74187 | benjamin.peterson | 2009-07-23 16:19:08 +0200 (Do, 23 Jul 2009) | 1 line use bools for autoraise ................ r74197 | benjamin.peterson | 2009-07-25 04:03:48 +0200 (Sa, 25 Jul 2009) | 1 line clarify ................ r74201 | amaury.forgeotdarc | 2009-07-25 18:22:06 +0200 (Sa, 25 Jul 2009) | 2 lines Better name a variable: 'buf' seems to imply a mutable buffer. ................ r74216 | michael.foord | 2009-07-26 23:12:14 +0200 (So, 26 Jul 2009) | 1 line Issue 6581. Michael Foord ................ r74219 | eric.smith | 2009-07-27 03:58:25 +0200 (Mo, 27 Jul 2009) | 1 line Sync trunk and py3k versions of string formatting. Will manually merge into py3k. ................ r74240 | mark.dickinson | 2009-07-28 22:35:03 +0200 (Di, 28 Jul 2009) | 4 lines Issue #6561: '\d' regular expression should not match characters of category [No]; only those of category [Nd]. (Backport of r74237 from py3k.) ................ r74243 | amaury.forgeotdarc | 2009-07-28 22:47:55 +0200 (Di, 28 Jul 2009) | 2 lines "Fix" for the refleak report: the ABC classes are now in the _pyio module ................ r74265 | mark.dickinson | 2009-07-30 12:00:10 +0200 (Do, 30 Jul 2009) | 1 line Documentation fix for change introduced in r71832 ................ r74269 | eric.smith | 2009-07-30 15:39:44 +0200 (Do, 30 Jul 2009) | 1 line Issue 6330: Fix --enable-unicode=ucs4. ................ r74277 | sean.reifschneider | 2009-08-02 01:54:55 +0200 (So, 02 Aug 2009) | 3 lines - Issue #6624: yArg_ParseTuple with "s" format when parsing argument with NUL: Bogus TypeError detail string. ................ r74300 | raymond.hettinger | 2009-08-04 21:08:05 +0200 (Di, 04 Aug 2009) | 1 line Issue 6637: defaultdict.copy() failed with an empty factory. ................ r74312 | mark.dickinson | 2009-08-04 23:56:04 +0200 (Di, 04 Aug 2009) | 4 lines Issue #6620: Slightly safer code for _grouping_intervals in the locale module. Fixes a 'possible use before assignment' warning from pylint. Thanks Vincent Legoll. ................ r74321 | guilherme.polo | 2009-08-05 18:51:41 +0200 (Mi, 05 Aug 2009) | 1 line Easier reference to find (at least while svn continues being used). ................ r74323 | guilherme.polo | 2009-08-06 01:48:26 +0200 (Do, 06 Aug 2009) | 1 line Typo. ................ r74336 | antoine.pitrou | 2009-08-06 22:18:29 +0200 (Do, 06 Aug 2009) | 8 lines Issue #6629: Fix a data corruption issue in the new `io` package, which could occur when writing to a BufferedRandom object (e.g. a file opened in "rb+" or "wb+" mode) after having buffered a certain amount of data for reading. This bug was not present in the pure Python implementation. Yes, this is a serious issue. ................ r74355 | gregory.p.smith | 2009-08-12 19:02:37 +0200 (Mi, 12 Aug 2009) | 2 lines comment typo fix ................ r74365 | georg.brandl | 2009-08-13 09:48:05 +0200 (Do, 13 Aug 2009) | 1 line #6679: Remove mention that sub supports no flags. ................ r74426 | gregory.p.smith | 2009-08-13 20:54:50 +0200 (Do, 13 Aug 2009) | 4 lines Fix issue1628205: Socket file objects returned by socket.socket.makefile() now properly handles EINTR within the read, readline, write & flush methods. The socket.sendall() method now properly handles interrupted system calls. ................ r74446 | guilherme.polo | 2009-08-14 15:53:41 +0200 (Fr, 14 Aug 2009) | 1 line Issue #3344: Replace itertools.count by enumerate. ................ r74447 | guilherme.polo | 2009-08-14 16:03:07 +0200 (Fr, 14 Aug 2009) | 1 line Issue #3926: Fix the usage of the new showwarnings and formatwarning. ................ r74448 | guilherme.polo | 2009-08-14 16:36:45 +0200 (Fr, 14 Aug 2009) | 3 lines Issue #1135: Add the XView and YView mix-ins to avoid duplicating the xview* and yview* methods. ................ r74449 | guilherme.polo | 2009-08-14 16:43:43 +0200 (Fr, 14 Aug 2009) | 1 line Clarifying Entry.selection_present's docstring. ................ r74463 | gregory.p.smith | 2009-08-16 00:39:03 +0200 (So, 16 Aug 2009) | 6 lines Force the http connection to close after any request returned when buffering=True as our buffered data is not known to the HTTPConnection and may contain data needed by a future request if the connection were left open. See http://bugs.python.org/issue2576 and http://bugs.python.org/issue4879. ................ r74464 | benjamin.peterson | 2009-08-16 00:59:21 +0200 (So, 16 Aug 2009) | 4 lines better col_offsets for "for" statements with tuple unpacking #6704 Patch from Frank Wierzbicki. ................ r74471 | guilherme.polo | 2009-08-16 16:34:26 +0200 (So, 16 Aug 2009) | 1 line Issue #6244: Allow detect_tkinter to look for Tcl/Tk 8.6. ................ r74472 | guilherme.polo | 2009-08-16 16:38:57 +0200 (So, 16 Aug 2009) | 1 line Wrong place for issue #6244. ................ r74477 | frank.wierzbicki | 2009-08-16 22:22:51 +0200 (So, 16 Aug 2009) | 2 lines Add test of file.write(array) extracted from Jython. ................ r74479 | gregory.p.smith | 2009-08-16 23:54:45 +0200 (So, 16 Aug 2009) | 2 lines Clean up the C library import code (based on suggestions in issue6281). ................ r74490 | benjamin.peterson | 2009-08-17 15:39:41 +0200 (Mo, 17 Aug 2009) | 1 line typos ................ r74493 | tarek.ziade | 2009-08-17 23:28:34 +0200 (Mo, 17 Aug 2009) | 1 line fixed how fnmatch.translate is used (since it has changed in r74475 for #6665). Now the code is not harcoding the usage of $ anymore ................ r74495 | tarek.ziade | 2009-08-17 23:48:22 +0200 (Mo, 17 Aug 2009) | 1 line module cleanup ................ r74501 | tarek.ziade | 2009-08-18 10:16:33 +0200 (Di, 18 Aug 2009) | 1 line added more test coverage for distutils.filelist to prevent regressions when fnmatch or re are changed ................ r74503 | tarek.ziade | 2009-08-18 10:21:49 +0200 (Di, 18 Aug 2009) | 1 line fixed typo ................ r74507 | guilherme.polo | 2009-08-18 15:23:08 +0200 (Di, 18 Aug 2009) | 1 line Issue #1119673: Do not override Tkinter.Text methods when creating a ScrolledText. ................ r74508 | guilherme.polo | 2009-08-18 15:29:20 +0200 (Di, 18 Aug 2009) | 1 line Issue #1250469: Fix the return value of Tix.PanedWindow.panes. ................ r74509 | guilherme.polo | 2009-08-18 15:33:30 +0200 (Di, 18 Aug 2009) | 1 line Mark the "radio" option of Tix.CheckList as static. ................ r74510 | guilherme.polo | 2009-08-18 16:23:00 +0200 (Di, 18 Aug 2009) | 1 line Issue #1522587: New constants and methods for the Tix.Grid widget. ................ r74511 | guilherme.polo | 2009-08-18 16:34:44 +0200 (Di, 18 Aug 2009) | 1 line Fixes for Tix.Grid from issue #1522587. ................ r74513 | skip.montanaro | 2009-08-18 16:37:52 +0200 (Di, 18 Aug 2009) | 1 line missing module ref (issue6723) ................ r74517 | guilherme.polo | 2009-08-18 16:46:57 +0200 (Di, 18 Aug 2009) | 1 line Issue #1356969: Add missing info methods in Tix.HList. ................ r74519 | guilherme.polo | 2009-08-18 18:39:36 +0200 (Di, 18 Aug 2009) | 1 line Added missing static option for OptionMenu. Issue #5961. ................ r74522 | gregory.p.smith | 2009-08-19 07:33:48 +0200 (Mi, 19 Aug 2009) | 8 lines Revert the changes from r74463, they were causing test_xmlrpc to fail. We do not need to force a close when using socket buffering on a httplib.HTTPRequest as the library does not support streaming requests so there should never been extra data beyond the end of the current request to have left over in the requests socket buffer. see http://bugs.python.org/issue6724 ................ r74523 | gregory.p.smith | 2009-08-20 11:38:43 +0200 (Do, 20 Aug 2009) | 2 lines comment typo fix ................ r74524 | gregory.p.smith | 2009-08-20 11:39:38 +0200 (Do, 20 Aug 2009) | 2 lines Add weakref support to the thread.lock type. ................ r74526 | tarek.ziade | 2009-08-20 23:23:13 +0200 (Do, 20 Aug 2009) | 1 line #6693: New functions in site.py to get user/global site packages paths. ................ r74537 | tarek.ziade | 2009-08-21 16:28:38 +0200 (Fr, 21 Aug 2009) | 1 line fixed misplaced Issue line ................ r74542 | georg.brandl | 2009-08-23 23:28:56 +0200 (So, 23 Aug 2009) | 1 line Restore alphabetic order. ................ r74543 | kristjan.jonsson | 2009-08-24 13:39:31 +0200 (Mo, 24 Aug 2009) | 2 lines issue 6769 fix a mistake in instantiatiating the HTTPSConnection class. ................ r74556 | kristjan.jonsson | 2009-08-28 00:20:21 +0200 (Fr, 28 Aug 2009) | 2 lines issue 6275 Add an "exc_value" attribute to the _AssertRaisesContext context manager in the unittest package. This allows further tests on the exception that was raised after the context manager exits. ................ r74558 | kristjan.jonsson | 2009-08-28 01:13:18 +0200 (Fr, 28 Aug 2009) | 2 lines Issue 6654 Allow the XML-RPC server to use the HTTP request path when dispatching. Added a MultiPathXMLRPCServer class that uses the feature, plus unit tests. ................ r74569 | benjamin.peterson | 2009-08-28 18:48:03 +0200 (Fr, 28 Aug 2009) | 1 line restricted environments are no more ................ r74570 | benjamin.peterson | 2009-08-28 18:49:56 +0200 (Fr, 28 Aug 2009) | 1 line remove more code for restricted execution ................ r74571 | lars.gustaebel | 2009-08-28 21:23:44 +0200 (Fr, 28 Aug 2009) | 7 lines Issue #6054: Do not normalize stored pathnames. No longer use tarfile.normpath() on pathnames. Store pathnames unchanged, i.e. do not remove "./", "../" and "//" occurrences. However, still convert absolute to relative paths. ................ r74581 | amaury.forgeotdarc | 2009-08-29 20:14:40 +0200 (Sa, 29 Aug 2009) | 3 lines #6750: TextIOWrapped could duplicate output when several threads write to it. this affect text files opened with io.open(), and the print() function of py3k ................ r74604 | mark.dickinson | 2009-08-31 16:46:07 +0200 (Mo, 31 Aug 2009) | 1 line Issue #6297: Add autogenerated Misc/python.pc file to make distclean target. Thanks Jerry Chen. ................ r74625 | benjamin.peterson | 2009-09-02 00:27:57 +0200 (Mi, 02 Sep 2009) | 1 line remove the check that classmethod's argument is a callable ................ r74635 | armin.rigo | 2009-09-03 21:40:07 +0200 (Do, 03 Sep 2009) | 2 lines Found the next crasher by thinking about this logic in PyPy. ................ r74636 | armin.rigo | 2009-09-03 21:42:03 +0200 (Do, 03 Sep 2009) | 3 lines Does not terminate: consume all memory without responding to Ctrl-C. I am not too sure why, but you can surely find out by gdb'ing a bit... ................ r74637 | armin.rigo | 2009-09-03 21:45:27 +0200 (Do, 03 Sep 2009) | 4 lines Sorry, sorry! Ignore my previous two commits. I mixed up the version of python with which I tried running the crashers. They don't crash the current HEAD. ................ r74640 | brett.cannon | 2009-09-03 23:25:21 +0200 (Do, 03 Sep 2009) | 7 lines test_platform fails on OS X Snow Leopard because the UNIX command to get the canonical version, sw_vers, leaves off trailing zeros in the version number (e.g. 10.6 instead of 10.6.0). Test now compensates by tacking on extra zeros for the test comparison. Fixes issue #6806. ................ r74644 | georg.brandl | 2009-09-04 09:55:14 +0200 (Fr, 04 Sep 2009) | 1 line #5047: remove Monterey support from configure. ................ r74650 | georg.brandl | 2009-09-04 13:19:34 +0200 (Fr, 04 Sep 2009) | 1 line #5101: add back tests to test_funcattrs that were lost during unittest conversion, and make some PEP8 cleanups. ................ r74667 | mark.dickinson | 2009-09-05 12:27:00 +0200 (Sa, 05 Sep 2009) | 2 lines Add configure-time checks for gamma and error functions. ................ r74699 | benjamin.peterson | 2009-09-07 00:43:39 +0200 (Mo, 07 Sep 2009) | 1 line PyObject_GetIter can set an error for its self just fine ................ r74702 | benjamin.peterson | 2009-09-07 15:02:15 +0200 (Mo, 07 Sep 2009) | 1 line revert r74699 since it loses useful error information ................ r74715 | ronald.oussoren | 2009-09-08 09:17:10 +0200 (Di, 08 Sep 2009) | 5 lines This is an update to r74701. How hard can it be to get a configure test right. This patch has already been backported as part of the backport of r74701, which is how I found this problem. ................ r74721 | thomas.heller | 2009-09-08 21:24:36 +0200 (Di, 08 Sep 2009) | 1 line Make ctypes compile again with older Python versions. ................ r74723 | mark.dickinson | 2009-09-08 22:20:19 +0200 (Di, 08 Sep 2009) | 3 lines Issue #6857: Fix Decimal formatting to be consistent with existing float formatting: both are now right-aligned by default. ................ r74733 | benjamin.peterson | 2009-09-09 13:40:54 +0200 (Mi, 09 Sep 2009) | 1 line tabbify ................ r74734 | benjamin.peterson | 2009-09-09 13:42:57 +0200 (Mi, 09 Sep 2009) | 1 line revert unintended changes ................ r74750 | lars.gustaebel | 2009-09-12 12:28:15 +0200 (Sa, 12 Sep 2009) | 9 lines Issue #6856: Add a filter keyword argument to TarFile.add(). The filter argument must be a function that takes a TarInfo object argument, changes it and returns it again. If the function returns None the TarInfo object will be excluded from the archive. The exclude argument is deprecated from now on, because it does something similar but is not as flexible. ................ r74754 | ezio.melotti | 2009-09-12 16:43:43 +0200 (Sa, 12 Sep 2009) | 1 line #6026 - fix tests that failed without zlib ................ r74780 | michael.foord | 2009-09-13 18:40:02 +0200 (So, 13 Sep 2009) | 1 line Objects that compare equal automatically pass or fail assertAlmostEqual and assertNotAlmostEqual tests on unittest.TestCase. Issue 6567. ................ r74783 | michael.foord | 2009-09-13 19:28:35 +0200 (So, 13 Sep 2009) | 1 line unittest.TestLoader.loadTestsFromName honors the loader suiteClass attribute. Issue 6866. ................ r74785 | michael.foord | 2009-09-13 21:07:03 +0200 (So, 13 Sep 2009) | 1 line Test discovery in unittest will only attempt to import modules that are importable; i.e. their names are valid Python identifiers. If an import fails during discovery this will be recorded as an error and test discovery will continue. Issue 6568. ................ r74786 | michael.foord | 2009-09-13 21:08:18 +0200 (So, 13 Sep 2009) | 1 line Remove an extraneous space in unittest documentation. ................ r74811 | georg.brandl | 2009-09-15 22:26:59 +0200 (Di, 15 Sep 2009) | 1 line Add Armin Ronacher. ................ r74812 | ronald.oussoren | 2009-09-15 23:24:07 +0200 (Di, 15 Sep 2009) | 3 lines Update distutils.util tests after my changes to --with-universal-archs ................ r74843 | mark.dickinson | 2009-09-16 22:26:31 +0200 (Mi, 16 Sep 2009) | 4 lines Remove outdated include; this include was breaking OS X builds using non-Apple gcc4.3 and gcc4.4 (because CoreFoundation/CoreFoundation.h won't compile under non-Apple gcc). ................ r74849 | thomas.wouters | 2009-09-16 22:36:34 +0200 (Mi, 16 Sep 2009) | 4 lines Add news entry for r74841. ................ r74853 | mark.dickinson | 2009-09-17 00:10:56 +0200 (Do, 17 Sep 2009) | 5 lines Issue #6713: Improve performance of str(n) and repr(n) for integers n (up to 3.1 times faster in tests), by special-casing base 10 in _PyLong_Format. (Backport of r74851 from py3k.) ................ r74860 | benjamin.peterson | 2009-09-17 04:46:54 +0200 (Do, 17 Sep 2009) | 1 line kill bare except ................ r74886 | benjamin.peterson | 2009-09-17 23:33:46 +0200 (Do, 17 Sep 2009) | 1 line use macros ................ r74901 | georg.brandl | 2009-09-18 11:14:52 +0200 (Fr, 18 Sep 2009) | 1 line #6905: use better exception messages in inspect when the argument is of the wrong type. ................ r74908 | georg.brandl | 2009-09-18 15:57:11 +0200 (Fr, 18 Sep 2009) | 1 line Use str.format() to fix beginner's mistake with %-style string formatting. ................ r74912 | georg.brandl | 2009-09-18 18:19:56 +0200 (Fr, 18 Sep 2009) | 1 line Optimize optimization and fix method name in docstring. ................ r74913 | mark.dickinson | 2009-09-18 20:35:42 +0200 (Fr, 18 Sep 2009) | 2 lines Add Gawain Bolton to Misc/ACKS for his work on base 10 integer -> string optimizations. ................ r74925 | mark.dickinson | 2009-09-18 23:01:50 +0200 (Fr, 18 Sep 2009) | 2 lines Use skipUnless to skip math module tests on non-IEEE 754 platforms. ................ r74929 | benjamin.peterson | 2009-09-18 23:14:55 +0200 (Fr, 18 Sep 2009) | 1 line add keyword arguments support to str/unicode encode and decode #6300 ................ r74936 | benjamin.peterson | 2009-09-18 23:46:21 +0200 (Fr, 18 Sep 2009) | 1 line backport keyword argument support for bytearray.decode ................ r74937 | benjamin.peterson | 2009-09-18 23:47:27 +0200 (Fr, 18 Sep 2009) | 1 line typo ................ r74954 | georg.brandl | 2009-09-19 15:13:56 +0200 (Sa, 19 Sep 2009) | 1 line Add Doug. ................ r74955 | georg.brandl | 2009-09-19 15:20:49 +0200 (Sa, 19 Sep 2009) | 1 line Add Mark Summerfield. ................ r74970 | ronald.oussoren | 2009-09-20 16:18:15 +0200 (So, 20 Sep 2009) | 7 lines Issue 6877: this patch makes it possible to link the readline extension to the libedit emulation of the readline API on OSX 10.5 or later. This also adds a minimal testsuite for readline to check that the history manipuation functions have the same interface with both C libraries. ................ r74988 | tarek.ziade | 2009-09-21 14:19:07 +0200 (Mo, 21 Sep 2009) | 1 line improved distutils test coverage: now the DEBUG mode is covered too (will help fix the issue #6954 in py3k branch) ................ r74992 | tarek.ziade | 2009-09-21 15:23:35 +0200 (Mo, 21 Sep 2009) | 1 line improving distutils coverage ................ r74994 | tarek.ziade | 2009-09-21 15:41:08 +0200 (Mo, 21 Sep 2009) | 1 line #6954: Fixed crash when using DISTUTILS_DEBUG flag in Distutils. ................ r74997 | tarek.ziade | 2009-09-21 15:49:57 +0200 (Mo, 21 Sep 2009) | 1 line forgot to commit a file in previous commit (r74994, issue #6954) ................ Modified: python/branches/release26-maint/ (props changed) From python-checkins at python.org Wed May 19 15:52:57 2010 From: python-checkins at python.org (georg.brandl) Date: Wed, 19 May 2010 15:52:57 +0200 (CEST) Subject: [Python-checkins] r81329 - python/branches/release26-maint Message-ID: <20100519135257.5341DF822@mail.python.org> Author: georg.brandl Date: Wed May 19 15:52:57 2010 New Revision: 81329 Log: Blocked revisions 75003,75011,75020,75054,75076,75084,75091,75095,75098,75102-75104,75106,75110,75117,75139,75141,75157,75164-75166,75171,75175,75180-75181,75192,75196,75209,75223,75230,75255,75258,75264,75267-75268,75272-75273,75292-75293,75300,75304-75305,75310,75313,75315,75318,75321-75322,75325,75327,75329,75337,75339,75342,75344,75346,75348,75350-75351,75354,75356,75358,75370-75372,75391,75396,75400,75405,75407-75413,75415,75417,75419-75421,75423-75424,75429-75434,75436-75438,75445-75446,75450,75453-75454,75456-75458,75461-75463,75465-75468,75470,75481,75485-75486,75489,75499,75501,75503,75506,75510,75529,75532,75551,75586,75589,75591,75620,75640,75650-75651,75653-75655,75657-75660,75664,75666,75672,75675,75697,75711,75714,75717-75718,75720,75722,75728,75730-75731,75739,75742-75743,75745,75824,75826,75838,75842,75844,75846,75849,75851,75855,75860,75866-75868,75871,75874,75879,75883,75893,75901,75905,75909,75913,75929,75935,75939,75954,75956-75958,75960,75962-75963,75967,75969,75971,75974,75979,75991,75995,75999 via svnmerge ........ r75003 | mark.dickinson | 2009-09-21 18:16:44 +0200 (Mo, 21 Sep 2009) | 1 line Silence MSVC compiler warnings. ........ r75011 | brett.cannon | 2009-09-22 02:29:48 +0200 (Di, 22 Sep 2009) | 10 lines When range checking was added to time.strftime() a check was placed on tm_isdst to make sure it fell within [-1, 1] just in case someone implementing strftime() in libc was stupid enough to assume this. Turns out, though, some OSs (e.g. zOS) are stupid enough to use values outside of this range for time structs created by the system itself. So instead of throwing a ValueError, tm_isdst is now normalized before being passed to strftime(). Fixes issue #6823. Thanks Robert Shapiro for diagnosing the problem and contributing an initial patch. ........ r75020 | brett.cannon | 2009-09-22 21:13:27 +0200 (Di, 22 Sep 2009) | 1 line Fix whitespace. ........ r75054 | kristjan.jonsson | 2009-09-25 17:19:51 +0200 (Fr, 25 Sep 2009) | 2 lines http://bugs.python.org/issue6971 Adding the SIO_KEEPALIVE_VALS command to socket.ioctl on windows ........ r75076 | vinay.sajip | 2009-09-26 16:53:32 +0200 (Sa, 26 Sep 2009) | 1 line Tidied up name of parameter in StreamHandler ........ r75084 | mark.dickinson | 2009-09-27 18:05:21 +0200 (So, 27 Sep 2009) | 3 lines Issue #6713: Improve decimal int -> string conversions. Thanks Gawain Bolton for the suggestion and original patches. ........ r75091 | mark.dickinson | 2009-09-27 18:39:28 +0200 (So, 27 Sep 2009) | 1 line Eliminate unnecessary get_wrapped_(u)long defines in struct module. ........ r75095 | michael.foord | 2009-09-27 21:15:41 +0200 (So, 27 Sep 2009) | 1 line Test creation moved from TestProgram.parseArgs to TestProgram.createTests exclusively. Issue 6956. ........ r75098 | michael.foord | 2009-09-27 22:08:23 +0200 (So, 27 Sep 2009) | 1 line Documentation improvement for load_tests protocol in unittest. Issue 6515. ........ r75102 | skip.montanaro | 2009-09-28 04:12:27 +0200 (Mo, 28 Sep 2009) | 3 lines Patch from Thomas Barr so that csv.Sniffer will set doublequote property. Closes issue 6606. ........ r75103 | kristjan.jonsson | 2009-09-28 15:08:48 +0200 (Mo, 28 Sep 2009) | 2 lines http://bugs.python.org/issue6836 A memory block allocated with one API was being handed over to an object that used another API to release it. ........ r75104 | kristjan.jonsson | 2009-09-28 15:12:38 +0200 (Mo, 28 Sep 2009) | 2 lines http://bugs.python.org/issue6836 The debug memory api now keeps track of which external API (PyMem_* or PyObject_*) was used to allocate each block and treats any API violation as an error. Added separate _PyMem_DebugMalloc functions for the Py_Mem API instead of having it use the _PyObject_DebugMalloc functions. ........ r75106 | kristjan.jonsson | 2009-09-28 17:56:25 +0200 (Mo, 28 Sep 2009) | 2 lines http://bugs.python.org/issue6836 A missing 'const' wasn't detected by Visual Studio. ........ r75110 | mark.dickinson | 2009-09-28 18:52:40 +0200 (Mo, 28 Sep 2009) | 9 lines Style/consistency/nano-optimization nit: replace occurrences of (high_bits << PyLong_SHIFT) + low_bits with (high_bits << PyLong_SHIFT) | low_bits in Objects/longobject.c. Motivation: - shouldn't unnecessarily mix bit ops with arithmetic ops (style) - this pattern should be spelt the same way thoughout (consistency) - it's very very very slightly faster: no need to worry about carries to the high digit (nano-optimization). ........ r75117 | mark.dickinson | 2009-09-28 20:54:55 +0200 (Mo, 28 Sep 2009) | 3 lines Issue #3366: Add gamma function to math module. (lgamma, erf and erfc to follow). ........ r75139 | raymond.hettinger | 2009-09-29 20:53:24 +0200 (Di, 29 Sep 2009) | 3 lines Issue 7008: Better document str.title and show how to work around the apostrophe problem. ........ r75141 | mark.dickinson | 2009-09-29 21:01:06 +0200 (Di, 29 Sep 2009) | 3 lines Issue #7019: Unmarshalling of bad long data could produce unnormalized PyLongs. Raise ValueError instead. ........ r75157 | mark.dickinson | 2009-09-30 18:58:01 +0200 (Mi, 30 Sep 2009) | 1 line Fix buggy accuracy test ........ r75164 | senthil.kumaran | 2009-10-01 03:07:03 +0200 (Do, 01 Okt 2009) | 3 lines Fix for issue7026 test_urllib: unsetting missing 'env' variable. ........ r75165 | senthil.kumaran | 2009-10-01 03:19:18 +0200 (Do, 01 Okt 2009) | 3 lines using dict.unset(k) instead of del dict[k]. consistent with release26-maint ........ r75166 | senthil.kumaran | 2009-10-01 03:50:13 +0200 (Do, 01 Okt 2009) | 3 lines That's self.env.unset(k) and not env.unset(k) I was heading back to the problem. ........ r75171 | antoine.pitrou | 2009-10-01 19:08:03 +0200 (Do, 01 Okt 2009) | 4 lines Sync the 2.x `io` docs with py3k, with a small note as to the distinction between bytes streams and text streams. ........ r75175 | georg.brandl | 2009-10-01 22:11:14 +0200 (Do, 01 Okt 2009) | 1 line Fix some weird whitespace and two other overlong lines. ........ r75180 | georg.brandl | 2009-10-01 22:59:31 +0200 (Do, 01 Okt 2009) | 1 line #7031: Add TestCase.assertIsInstance and negated method. ........ r75181 | georg.brandl | 2009-10-01 23:02:39 +0200 (Do, 01 Okt 2009) | 1 line Add NEWS entry for r75180. ........ r75192 | tarek.ziade | 2009-10-03 01:49:48 +0200 (Sa, 03 Okt 2009) | 1 line #6516 added owner/group support for tarfiles in Distutils ........ r75196 | tarek.ziade | 2009-10-03 02:07:35 +0200 (Sa, 03 Okt 2009) | 1 line removing the last remaning apply() calls ........ r75209 | tarek.ziade | 2009-10-03 16:52:33 +0200 (Sa, 03 Okt 2009) | 1 line now uses the right exception type ........ r75223 | benjamin.peterson | 2009-10-03 22:23:24 +0200 (Sa, 03 Okt 2009) | 1 line #7050 fix a SystemError when using tuple unpacking and augmented assignment ........ r75230 | benjamin.peterson | 2009-10-04 15:38:38 +0200 (So, 04 Okt 2009) | 1 line test logging ........ r75255 | r.david.murray | 2009-10-05 19:03:09 +0200 (Mo, 05 Okt 2009) | 3 lines Issue #7058: Added save/restore for argv and os.environ to runtest_inner in regrtest, with warnings if the called test modifies them. ........ r75258 | amaury.forgeotdarc | 2009-10-05 22:18:05 +0200 (Mo, 05 Okt 2009) | 2 lines Fix compilation warning on Windows, where size_t is 32bit but file offsets are 64bit. ........ r75264 | andrew.kuchling | 2009-10-06 00:30:22 +0200 (Di, 06 Okt 2009) | 1 line Add various items ........ r75267 | andrew.kuchling | 2009-10-06 00:42:56 +0200 (Di, 06 Okt 2009) | 1 line Backport r73983: Document the thousands separator. ........ r75268 | andrew.kuchling | 2009-10-06 00:45:39 +0200 (Di, 06 Okt 2009) | 1 line Remove two notes ........ r75272 | amaury.forgeotdarc | 2009-10-06 21:56:32 +0200 (Di, 06 Okt 2009) | 5 lines #1571184: makeunicodedata.py now generates the functions _PyUnicode_ToNumeric, _PyUnicode_IsLinebreak and _PyUnicode_IsWhitespace. It now also parses the Unihan.txt for numeric values. ........ r75273 | amaury.forgeotdarc | 2009-10-06 22:02:09 +0200 (Di, 06 Okt 2009) | 2 lines Add Anders Chrigstrom to Misc/ACKS for his work on unicodedata. ........ r75292 | benjamin.peterson | 2009-10-09 05:11:36 +0200 (Fr, 09 Okt 2009) | 1 line death to old CVS keyword ........ r75293 | kristjan.jonsson | 2009-10-09 16:32:19 +0200 (Fr, 09 Okt 2009) | 2 lines http://bugs.python.org/issue7029 a non-default timer wasn't actually used by the individual Tests. ........ r75300 | benjamin.peterson | 2009-10-09 23:48:14 +0200 (Fr, 09 Okt 2009) | 1 line fix some coding style ........ r75304 | benjamin.peterson | 2009-10-10 00:05:45 +0200 (Sa, 10 Okt 2009) | 1 line replace callable() ........ r75305 | benjamin.peterson | 2009-10-10 00:15:50 +0200 (Sa, 10 Okt 2009) | 1 line replace has_key with 'in' operator ........ r75310 | vinay.sajip | 2009-10-10 22:32:36 +0200 (Sa, 10 Okt 2009) | 1 line Issue #7086: Added TCP support to SysLogHandler and tidied up some anachronisms in the code. ........ r75313 | georg.brandl | 2009-10-10 23:07:35 +0200 (Sa, 10 Okt 2009) | 1 line Bring old demo up-to-date. ........ r75315 | georg.brandl | 2009-10-10 23:10:05 +0200 (Sa, 10 Okt 2009) | 1 line Remove unneeded "L" suffixes. ........ r75318 | benjamin.peterson | 2009-10-10 23:15:58 +0200 (Sa, 10 Okt 2009) | 1 line remove script which uses long gone module ........ r75321 | georg.brandl | 2009-10-10 23:43:21 +0200 (Sa, 10 Okt 2009) | 1 line Remove outdated comment and fix a few style issues. ........ r75322 | georg.brandl | 2009-10-10 23:47:31 +0200 (Sa, 10 Okt 2009) | 1 line Show use of range() step argument nicely. ........ r75325 | georg.brandl | 2009-10-10 23:55:11 +0200 (Sa, 10 Okt 2009) | 1 line Modernize factorisation demo (mostly augassign.) ........ r75327 | georg.brandl | 2009-10-11 00:03:43 +0200 (So, 11 Okt 2009) | 1 line Style fixes. ........ r75329 | georg.brandl | 2009-10-11 00:26:45 +0200 (So, 11 Okt 2009) | 1 line Modernize all around (dont ask me how useful that script is nowadays...) ........ r75337 | georg.brandl | 2009-10-11 10:18:44 +0200 (So, 11 Okt 2009) | 1 line Update morse script, avoid globals, use iterators. ........ r75339 | georg.brandl | 2009-10-11 10:39:16 +0200 (So, 11 Okt 2009) | 1 line Update markov demo. ........ r75342 | georg.brandl | 2009-10-11 10:45:03 +0200 (So, 11 Okt 2009) | 1 line Remove useless script "mkrcs" and update README. ........ r75344 | georg.brandl | 2009-10-11 10:48:28 +0200 (So, 11 Okt 2009) | 1 line Update primes script. ........ r75346 | mark.dickinson | 2009-10-11 11:35:57 +0200 (So, 11 Okt 2009) | 1 line Fix 'primes 0 1' ........ r75348 | mark.dickinson | 2009-10-11 12:01:17 +0200 (So, 11 Okt 2009) | 1 line Set missing executable property on scripts ........ r75350 | georg.brandl | 2009-10-11 14:00:18 +0200 (So, 11 Okt 2009) | 1 line Use getopt in script.py demo. ........ r75351 | georg.brandl | 2009-10-11 14:03:01 +0200 (So, 11 Okt 2009) | 1 line Fix variable. ........ r75354 | georg.brandl | 2009-10-11 16:23:49 +0200 (So, 11 Okt 2009) | 1 line Update lpwatch script. ........ r75356 | georg.brandl | 2009-10-11 16:49:37 +0200 (So, 11 Okt 2009) | 1 line Remove ftpstats script, the daemon whose log files it reads is long gone. ........ r75358 | georg.brandl | 2009-10-11 17:06:44 +0200 (So, 11 Okt 2009) | 1 line Overhaul of Demo/xml. ........ r75370 | georg.brandl | 2009-10-11 23:10:07 +0200 (So, 11 Okt 2009) | 1 line Move find_recursionlimit.py to Tools/scripts; it is out of place in Misc. ........ r75371 | georg.brandl | 2009-10-11 23:14:37 +0200 (So, 11 Okt 2009) | 1 line Add find_recursionlimit.py to README. ........ r75372 | georg.brandl | 2009-10-11 23:17:14 +0200 (So, 11 Okt 2009) | 1 line Update Misc/README. ........ r75391 | andrew.kuchling | 2009-10-13 17:49:33 +0200 (Di, 13 Okt 2009) | 1 line Link to PEP ........ r75396 | amaury.forgeotdarc | 2009-10-13 23:29:34 +0200 (Di, 13 Okt 2009) | 3 lines #7112: Fix compilation warning in unicodetype_db.h makeunicodedata now generates double literals ........ r75400 | r.david.murray | 2009-10-14 15:58:07 +0200 (Mi, 14 Okt 2009) | 6 lines Enhanced Issue 7058 patch, which will not be backported. Refactors the code, adds checks for stdin/out/err, cwd, and sys.path, and adds a new section in the summary for tests that modify the environment (thanks to Ezio Melotti for that suggestion). ........ r75405 | neil.schemenauer | 2009-10-14 19:17:14 +0200 (Mi, 14 Okt 2009) | 4 lines Issue #1754094: Improve the stack depth calculation in the compiler. There should be no other effect than a small decrease in memory use. Patch by Christopher Tur Lesniewski-Laas. ........ r75407 | antoine.pitrou | 2009-10-14 19:30:52 +0200 (Mi, 14 Okt 2009) | 3 lines Fix py3k warnings in the aifc module ........ r75408 | antoine.pitrou | 2009-10-14 19:34:31 +0200 (Mi, 14 Okt 2009) | 3 lines Fix a test_atexit failure when run with -3 ........ r75409 | antoine.pitrou | 2009-10-14 20:01:33 +0200 (Mi, 14 Okt 2009) | 3 lines Fix py3k warnings in bsddb ........ r75410 | antoine.pitrou | 2009-10-14 20:09:45 +0200 (Mi, 14 Okt 2009) | 3 lines Silence a py3k warning claiming to affect Lib/calendar.py ........ r75411 | antoine.pitrou | 2009-10-14 20:12:54 +0200 (Mi, 14 Okt 2009) | 3 lines Fix a py3k warning in the StringIO module (exhibited in test_codecencodings_cn) ........ r75412 | antoine.pitrou | 2009-10-14 20:27:32 +0200 (Mi, 14 Okt 2009) | 3 lines Fix py3k warnings in the socket module ........ r75413 | antoine.pitrou | 2009-10-14 20:31:05 +0200 (Mi, 14 Okt 2009) | 3 lines Fix a py3k warning in the sndhdr module (found with test_email) ........ r75415 | antoine.pitrou | 2009-10-14 20:39:46 +0200 (Mi, 14 Okt 2009) | 3 lines Silence some py3k warnings claiming to affect _pyio ........ r75417 | antoine.pitrou | 2009-10-14 20:47:13 +0200 (Mi, 14 Okt 2009) | 3 lines Fix failures in test_profilehooks when run with -3 ........ r75419 | antoine.pitrou | 2009-10-14 20:56:11 +0200 (Mi, 14 Okt 2009) | 3 lines Silence py3k warning claiming to affect the random module ........ r75420 | antoine.pitrou | 2009-10-14 21:04:48 +0200 (Mi, 14 Okt 2009) | 3 lines Fix py3k warnings in httplib ........ r75421 | antoine.pitrou | 2009-10-14 21:09:48 +0200 (Mi, 14 Okt 2009) | 3 lines Fix py3k warnings in the uuid module ........ r75423 | neil.schemenauer | 2009-10-14 21:23:53 +0200 (Mi, 14 Okt 2009) | 2 lines Add support to the ihooks module for relative imports. ........ r75424 | neil.schemenauer | 2009-10-14 21:33:31 +0200 (Mi, 14 Okt 2009) | 4 lines Make cPickle.Unpickler.noload() handle dict subclasses. noload() is an obscure, undocumentated feature so no test was added. Closes issue #1101399. ........ r75429 | benjamin.peterson | 2009-10-15 03:47:28 +0200 (Do, 15 Okt 2009) | 1 line pep8ify if blocks ........ r75430 | benjamin.peterson | 2009-10-15 03:49:37 +0200 (Do, 15 Okt 2009) | 1 line use floor division and add a test that exercises the tabsize codepath ........ r75431 | benjamin.peterson | 2009-10-15 03:56:25 +0200 (Do, 15 Okt 2009) | 1 line change test to what I intended ........ r75432 | benjamin.peterson | 2009-10-15 05:05:39 +0200 (Do, 15 Okt 2009) | 1 line some cleanups ........ r75433 | benjamin.peterson | 2009-10-15 05:06:55 +0200 (Do, 15 Okt 2009) | 1 line make inspect.isabstract() always return a boolean; add a test for it, too #7069 ........ r75434 | mark.dickinson | 2009-10-15 17:18:55 +0200 (Do, 15 Okt 2009) | 1 line Fix missing semicolon ........ r75436 | benjamin.peterson | 2009-10-15 17:39:15 +0200 (Do, 15 Okt 2009) | 1 line don't need to mess up sys.path ........ r75437 | benjamin.peterson | 2009-10-15 17:44:46 +0200 (Do, 15 Okt 2009) | 1 line only clear a module's __dict__ if the module is the only one with a reference to it #7140 ........ r75438 | mark.dickinson | 2009-10-15 17:53:58 +0200 (Do, 15 Okt 2009) | 1 line Issue #7142: Fix uses of unicode in memoryview objects ........ r75445 | vinay.sajip | 2009-10-16 16:06:44 +0200 (Fr, 16 Okt 2009) | 1 line Issue #7120: logging: Removed import of multiprocessing which is causing crash in GAE. ........ r75446 | eric.smith | 2009-10-16 16:26:36 +0200 (Fr, 16 Okt 2009) | 1 line Removed usage of unsafe PyFloat_AsString. ........ r75450 | tarek.ziade | 2009-10-17 01:04:16 +0200 (Sa, 17 Okt 2009) | 1 line this test requires zlib support ........ r75453 | nick.coghlan | 2009-10-17 08:33:05 +0200 (Sa, 17 Okt 2009) | 1 line Correctly restore sys.stdout in test_descr ........ r75454 | mark.dickinson | 2009-10-17 09:06:37 +0200 (Sa, 17 Okt 2009) | 1 line test_math ulp computation was wrong on big-endian systems ........ r75456 | nick.coghlan | 2009-10-17 09:30:40 +0200 (Sa, 17 Okt 2009) | 1 line Enhancement to the new environment checking code to print the changed items under -vv. Also includes a small tweak to allow underscores in the names of resources. ........ r75457 | nick.coghlan | 2009-10-17 09:34:27 +0200 (Sa, 17 Okt 2009) | 1 line Formatting tweak so that before and after values are vertically aligned ........ r75458 | nick.coghlan | 2009-10-17 10:21:21 +0200 (Sa, 17 Okt 2009) | 1 line Check and revert expected sys.path alterations ........ r75461 | nick.coghlan | 2009-10-17 16:40:54 +0200 (Sa, 17 Okt 2009) | 1 line Restore original sys.path when running TTK tests ........ r75462 | nick.coghlan | 2009-10-17 17:09:41 +0200 (Sa, 17 Okt 2009) | 1 line Don't invoke reload(sys) and use StringIO objects instead of real files to capture stdin and stdout when needed (ensures all sys attributes remain unmodified after test_xmlrpc runs) ........ r75463 | nick.coghlan | 2009-10-17 17:23:08 +0200 (Sa, 17 Okt 2009) | 1 line Revert changes made to environment in test_httpservers ........ r75465 | nick.coghlan | 2009-10-17 17:45:52 +0200 (Sa, 17 Okt 2009) | 1 line Move restoration of the os.environ object into the context manager where it belongs ........ r75466 | nick.coghlan | 2009-10-17 17:48:16 +0200 (Sa, 17 Okt 2009) | 1 line Also check and restore identity of sys.path, sys.argv and os.environ rather than just their values (this picked up a few more misbehaving tests) ........ r75467 | nick.coghlan | 2009-10-17 17:57:42 +0200 (Sa, 17 Okt 2009) | 1 line Avoid replacing existing modules and sys.path in import tests ........ r75468 | nick.coghlan | 2009-10-17 18:19:51 +0200 (Sa, 17 Okt 2009) | 1 line Don't replace sys.path in test_site ........ r75470 | mark.dickinson | 2009-10-17 23:46:32 +0200 (Sa, 17 Okt 2009) | 1 line Protect against attempts to replace PyNumber_Add with PyNumber_InPlaceAdd in builtin sum ........ r75481 | nick.coghlan | 2009-10-18 07:38:48 +0200 (So, 18 Okt 2009) | 1 line Using CleanImport to revert a reload of the os module doesn't work due to function registrations in copy_reg. The perils of reloading modules even for tests... ........ r75485 | tarek.ziade | 2009-10-18 11:28:26 +0200 (So, 18 Okt 2009) | 1 line Changed distutils tests to avoid environment alteration ........ r75486 | nick.coghlan | 2009-10-18 12:29:10 +0200 (So, 18 Okt 2009) | 1 line Silence a deprecation warning by using the appropriate replacement construct ........ r75489 | nick.coghlan | 2009-10-18 12:56:21 +0200 (So, 18 Okt 2009) | 1 line Restore sys.path in test_tk ........ r75499 | antoine.pitrou | 2009-10-18 20:22:04 +0200 (So, 18 Okt 2009) | 3 lines Add a test for same-thread asynchronous exceptions (see #1779233). ........ r75501 | antoine.pitrou | 2009-10-18 20:37:11 +0200 (So, 18 Okt 2009) | 3 lines Add a comment about unreachable code, and fix a typo ........ r75503 | r.david.murray | 2009-10-18 23:12:37 +0200 (So, 18 Okt 2009) | 11 lines Issue #7151: regrtest would generate a JSON failure if there was output to stderr during the test run and it happened to get emitted after the worker thread emitted the result JSON. Now we capture stdout and stderr separately, which avoids that problem. It also means that _all_ stderr output is after all stdout output when we print the test results, but that seems acceptable, since output ordering is not guaranteed anyway. The patch also moves the emit of the test name into the output block generated after the test completes. Otherwise test names and test output/errors were mixed in the terminal display, making it difficult to determine which test generated the output. ........ r75506 | eric.smith | 2009-10-19 02:34:12 +0200 (Mo, 19 Okt 2009) | 7 lines Removed calls to PyFloat_AsReprString. This is in anticipation of possibly implementing issue 7117 (short float repr). This removes the last calls to PyFloat_AsString, PyFloat_AsReprString, and PyFloat_AsStringEx, which are unsafe. Also, switch to defines for error values to bring this code more in line with the py3k branch. ........ r75510 | eric.smith | 2009-10-19 16:38:14 +0200 (Mo, 19 Okt 2009) | 1 line Issue #7169: Document PyFloat_AsString and PyFloat_AsReprString, and note that they are unsafe and deprecated. ........ r75529 | antoine.pitrou | 2009-10-19 19:59:07 +0200 (Mo, 19 Okt 2009) | 5 lines Issue #7133: SSL objects now support the new buffer API. This fixes the test_ssl failure. ........ r75532 | antoine.pitrou | 2009-10-19 20:20:21 +0200 (Mo, 19 Okt 2009) | 3 lines NEWS entry for r75531. ........ r75551 | benjamin.peterson | 2009-10-20 05:14:10 +0200 (Di, 20 Okt 2009) | 1 line use property api ........ r75586 | vinay.sajip | 2009-10-21 22:22:14 +0200 (Mi, 21 Okt 2009) | 1 line Issue #7077: logging: SysLogHandler now treats Unicode as per RFC 5424. ........ r75589 | benjamin.peterson | 2009-10-22 04:26:47 +0200 (Do, 22 Okt 2009) | 1 line whitespace ........ r75591 | benjamin.peterson | 2009-10-22 04:50:38 +0200 (Do, 22 Okt 2009) | 4 lines rewrite for style, clarify, and comments Also, use the hasattr() like scheme of allowing BaseException exceptions through. ........ r75620 | eric.smith | 2009-10-22 22:13:14 +0200 (Do, 22 Okt 2009) | 1 line Per the discussion in issue6882, backport the try/finally work that was done to the py3k version (mostly in r59477, I think). ........ r75640 | neil.schemenauer | 2009-10-23 21:58:17 +0200 (Fr, 23 Okt 2009) | 2 lines Improve some docstrings in the 'warnings' module. ........ r75650 | antoine.pitrou | 2009-10-24 13:59:41 +0200 (Sa, 24 Okt 2009) | 3 lines Manual py3k backport: [svn r74155] Issue #6242: Fix deallocator of io.StringIO and io.BytesIO ........ r75651 | mark.dickinson | 2009-10-24 14:13:30 +0200 (Sa, 24 Okt 2009) | 7 lines Issue #7117: Prepare for backport of py3k float repr. Add the Python/dtoa.c file containing the main algorithms; add corresponding include file and include in Python.h; include license information for Python/dtoa.c; add dtoa.c and dtoa.h to Makefile. ........ r75653 | mark.dickinson | 2009-10-24 14:17:24 +0200 (Sa, 24 Okt 2009) | 1 line Temporary define to avoid build failure ........ r75654 | antoine.pitrou | 2009-10-24 14:23:18 +0200 (Sa, 24 Okt 2009) | 3 lines Manual py3k backport: [svn r74158] Issue #6218: Make io.BytesIO and io.StringIO picklable. ........ r75655 | antoine.pitrou | 2009-10-24 14:28:22 +0200 (Sa, 24 Okt 2009) | 3 lines Manual py3k backport: [svn r74316] Issue #5449: Fix io.BytesIO to not accept arbitrary keywords ........ r75657 | antoine.pitrou | 2009-10-24 14:41:27 +0200 (Sa, 24 Okt 2009) | 3 lines Fix compilation error in debug mode. ........ r75658 | mark.dickinson | 2009-10-24 15:28:38 +0200 (Sa, 24 Okt 2009) | 8 lines Issue #7117 (backport py3k float repr) continued: - add double endianness detection to configure script - add configure-time check to see whether we can use inline assembly to get and set x87 control word in configure script - add functions to get and set x87 control word in Python/pymath.c - add pyport.h logic to determine whether it's safe to use the short float repr or not ........ r75659 | tarek.ziade | 2009-10-24 15:29:44 +0200 (Sa, 24 Okt 2009) | 1 line #7066 - Fixed distutils.archive_util.make_archive behavior so it restores the cwd ........ r75660 | mark.dickinson | 2009-10-24 15:31:41 +0200 (Sa, 24 Okt 2009) | 1 line Remove temporary define from r75653 ........ r75664 | mark.dickinson | 2009-10-24 15:44:16 +0200 (Sa, 24 Okt 2009) | 1 line Configure check for double rounding should take BASECFLAGS into account ........ r75666 | mark.dickinson | 2009-10-24 16:01:08 +0200 (Sa, 24 Okt 2009) | 4 lines Issue #7117 (backport py3k float repr) continued: Add sys.float_repr_style attribute ('short' if short float repr is in used; 'legacy' otherwise). ........ r75672 | mark.dickinson | 2009-10-24 17:54:35 +0200 (Sa, 24 Okt 2009) | 4 lines Issue #7117: temporarily disable the short float repr while the pieces are being assembled. To re-enable, define the preprocessor symbol PY_SHORT_FLOAT_REPR ........ r75675 | eric.smith | 2009-10-24 21:50:44 +0200 (Sa, 24 Okt 2009) | 1 line Removed unused function PyFloat_AsStringEx. It is unused in floatobject.c, and it's not declared in any .h file. ........ r75697 | mark.dickinson | 2009-10-25 21:39:06 +0100 (So, 25 Okt 2009) | 3 lines Issue #1087418: Small performance boost for bitwise operations on longs. Initial patch by Gregory Smith; some tweaks added. ........ r75711 | mark.dickinson | 2009-10-26 12:59:30 +0100 (Mo, 26 Okt 2009) | 1 line Skip readline tests if readline module is not available. ........ r75714 | mark.dickinson | 2009-10-26 15:18:44 +0100 (Mo, 26 Okt 2009) | 1 line Warn against replacing PyNumber_Add with PyNumber_InPlaceAdd in sum ........ r75717 | eric.smith | 2009-10-26 15:48:55 +0100 (Mo, 26 Okt 2009) | 1 line Start to remove _PyOS_double_to_string, as mentioned in issue 7117. ........ r75718 | eric.smith | 2009-10-26 16:06:39 +0100 (Mo, 26 Okt 2009) | 1 line Continue removing _PyOS_double_to_string, as mentioned in issue 7117. ........ r75720 | mark.dickinson | 2009-10-26 16:39:50 +0100 (Mo, 26 Okt 2009) | 3 lines Issue #7117 (backport py3k float repr) continued: Backport pystrtod.c from py3k. ........ r75722 | eric.smith | 2009-10-26 18:46:17 +0100 (Mo, 26 Okt 2009) | 1 line Finished removing _PyOS_double_to_string, as mentioned in issue 7117. ........ r75728 | mark.dickinson | 2009-10-26 20:59:23 +0100 (Mo, 26 Okt 2009) | 3 lines Use correct conversion specifier and length modifier when printing an integer of type off_t. Also, don't assume that long long is available. ........ r75730 | mark.dickinson | 2009-10-26 22:09:09 +0100 (Mo, 26 Okt 2009) | 2 lines Issue #7117: Backport missing pystrtod.h declarations from py3k. ........ r75731 | mark.dickinson | 2009-10-26 22:11:20 +0100 (Mo, 26 Okt 2009) | 4 lines Issue #7117: Use PyOS_string_to_double instead of PyOS_ascii_strtod in floatobject.c. Also, remove limitation on length of unicode inputs to float(). ........ r75739 | mark.dickinson | 2009-10-26 23:28:14 +0100 (Mo, 26 Okt 2009) | 5 lines Issue #7117: Use PyOS_string_to_double instead of PyOS_ascii_strtod in complexobject.c. Also remove length restriction on unicode inputs to the complex constructor. ........ r75742 | benjamin.peterson | 2009-10-26 23:51:16 +0100 (Mo, 26 Okt 2009) | 1 line use 'is' instead of id() ........ r75743 | eric.smith | 2009-10-27 12:32:11 +0100 (Di, 27 Okt 2009) | 1 line Issue 7117: Replace PyOS_ascii_strtod with PyOS_string_to_double in cPickle as part of short float repr. ........ r75745 | eric.smith | 2009-10-27 13:12:44 +0100 (Di, 27 Okt 2009) | 1 line Issue 7117: Replace PyOS_ascii_strtod with PyOS_string_to_double in stropmodule as part of short float repr. ........ r75824 | eric.smith | 2009-10-27 19:33:14 +0100 (Di, 27 Okt 2009) | 1 line Removed PyOS_ascii_atof from ast.c, as mentioned in issue 7117. ........ r75826 | antoine.pitrou | 2009-10-27 19:36:47 +0100 (Di, 27 Okt 2009) | 3 lines Suppress transient refleaks in test_asyncore ........ r75838 | antoine.pitrou | 2009-10-27 19:50:52 +0100 (Di, 27 Okt 2009) | 3 lines (Hopefully) suppress transient refleaks in test_httpservers. ........ r75842 | antoine.pitrou | 2009-10-27 20:23:56 +0100 (Di, 27 Okt 2009) | 3 lines Fix transient refleak in test_sys. ........ r75844 | antoine.pitrou | 2009-10-27 20:36:44 +0100 (Di, 27 Okt 2009) | 3 lines Suppress transient refleaks in test_file2k. ........ r75846 | eric.smith | 2009-10-27 20:42:57 +0100 (Di, 27 Okt 2009) | 1 line Removed PyOS_ascii_atof from marshal.c, as mentioned in issue 7117. Also brings it more in line with py3k. ........ r75849 | antoine.pitrou | 2009-10-27 20:47:30 +0100 (Di, 27 Okt 2009) | 3 lines Suppress transient refleaks in test_smtplib. ........ r75851 | antoine.pitrou | 2009-10-27 21:02:23 +0100 (Di, 27 Okt 2009) | 3 lines Suppress transient refleaks in test_threading. ........ r75855 | antoine.pitrou | 2009-10-27 21:14:04 +0100 (Di, 27 Okt 2009) | 3 lines Fix transient refleaks in test_urllib2_localnet. ........ r75860 | antoine.pitrou | 2009-10-27 21:20:41 +0100 (Di, 27 Okt 2009) | 3 lines Try to fix transient refleaks in test_distutils. ........ r75866 | georg.brandl | 2009-10-27 21:52:02 +0100 (Di, 27 Okt 2009) | 1 line Add a regrtest option to re-run in verbose mode immediately after a test fails, and use that option on the buildbots. ........ r75867 | georg.brandl | 2009-10-27 21:55:44 +0100 (Di, 27 Okt 2009) | 1 line Reformat the regrtest command-line option help and group the options into sections. ........ r75868 | benjamin.peterson | 2009-10-27 21:59:18 +0100 (Di, 27 Okt 2009) | 1 line test expect base classes ........ r75871 | tarek.ziade | 2009-10-27 22:20:27 +0100 (Di, 27 Okt 2009) | 1 line Issue #7218: Fix test_site for win32 ........ r75874 | antoine.pitrou | 2009-10-27 22:27:24 +0100 (Di, 27 Okt 2009) | 4 lines Reduce the probability of refleaks in test_socketserver. Not completely suppressed though, see issue #7222. ........ r75879 | mark.dickinson | 2009-10-27 22:48:20 +0100 (Di, 27 Okt 2009) | 3 lines Silence gcc warnings when trying to print an off_t using "lld", on platforms where off_t has type long (e.g., 64-bit Linux). ........ r75883 | mark.dickinson | 2009-10-27 23:09:33 +0100 (Di, 27 Okt 2009) | 1 line Test long inputs to float ........ r75893 | tarek.ziade | 2009-10-28 00:06:10 +0100 (Mi, 28 Okt 2009) | 1 line Fixed #1180: Option to ignore ~/.pydistutils.cfg in Distutils ........ r75901 | tarek.ziade | 2009-10-28 07:45:18 +0100 (Mi, 28 Okt 2009) | 1 line removed spurious spaces ........ r75905 | mark.dickinson | 2009-10-28 08:23:49 +0100 (Mi, 28 Okt 2009) | 1 line Replace long long with PY_LONG_LONG ........ r75909 | mark.dickinson | 2009-10-28 08:47:32 +0100 (Mi, 28 Okt 2009) | 1 line Fix format specifier for MSVC ........ r75913 | eric.smith | 2009-10-28 09:44:37 +0100 (Mi, 28 Okt 2009) | 1 line Issue 7117: Replace PyOS_ascii_strtod with PyOS_string_to_double in _json.c as part of short float repr. Change made after consulting with Bob Ippolito. This completes the removal of calls to PyOS_ascii_strtod. ........ r75929 | vinay.sajip | 2009-10-29 00:28:16 +0100 (Do, 29 Okt 2009) | 1 line Issue 7199: Documentation made slightly more consistent w.r.t. logging level enumeration. ........ r75935 | lars.gustaebel | 2009-10-29 10:15:00 +0100 (Do, 29 Okt 2009) | 3 lines Issue #4750: Store the basename of the original filename in the gzip FNAME header as required by RFC 1952. ........ r75939 | mark.dickinson | 2009-10-29 10:46:04 +0100 (Do, 29 Okt 2009) | 5 lines Roll back ill-considered attempts to fix printf specifier mismatch for off_t. The sensible solution seems to be to implement %lld for PyString_FromFormat(V) and PyErr_Format. See issue #7228. ........ r75954 | georg.brandl | 2009-10-29 21:53:00 +0100 (Do, 29 Okt 2009) | 1 line Use constants instead of magic integers for test result. Do not re-run with --verbose3 for environment changing tests. ........ r75956 | georg.brandl | 2009-10-29 22:16:34 +0100 (Do, 29 Okt 2009) | 1 line I do not think the "railroad" program mentioned is still available. ........ r75957 | georg.brandl | 2009-10-29 22:44:56 +0100 (Do, 29 Okt 2009) | 1 line Fix constant name. ........ r75958 | antoine.pitrou | 2009-10-30 18:07:08 +0100 (Fr, 30 Okt 2009) | 7 lines Issue #7222: Make thread "reaping" more reliable so that reference leak-chasing test runs give sensible results. The previous method of reaping threads could return successfully while some Thread objects were still referenced. This also introduces a new private function: :func:hread._count(). ........ r75960 | antoine.pitrou | 2009-10-30 18:33:28 +0100 (Fr, 30 Okt 2009) | 3 lines Fix transient refleaks in test_docxmlrpc. ........ r75962 | antoine.pitrou | 2009-10-30 18:55:21 +0100 (Fr, 30 Okt 2009) | 3 lines Try to fix transient refleaks in test_asynchat. ........ r75963 | antoine.pitrou | 2009-10-30 18:56:00 +0100 (Fr, 30 Okt 2009) | 3 lines Try to fix transient refleaks in test_xmlrpc. ........ r75967 | antoine.pitrou | 2009-10-30 22:41:22 +0100 (Fr, 30 Okt 2009) | 3 lines Try to fix transient refleaks in test_pydoc. ........ r75969 | antoine.pitrou | 2009-10-30 23:19:09 +0100 (Fr, 30 Okt 2009) | 5 lines Remove official documentation entry for thread._count() and make the docstring more descriptive instead. ........ r75971 | benjamin.peterson | 2009-10-31 04:56:15 +0100 (Sa, 31 Okt 2009) | 1 line add some checks for evaluation order with parenthesis #7210 ........ r75974 | mark.dickinson | 2009-10-31 10:28:12 +0100 (Sa, 31 Okt 2009) | 1 line Move a Misc/NEWS entry to right section. ........ r75979 | mark.dickinson | 2009-10-31 10:42:39 +0100 (Sa, 31 Okt 2009) | 1 line Deprecate PyOS_ascii_strtod and PyOS_ascii_atof, and document the replacement function PyOS_string_to_double. ........ r75991 | mark.dickinson | 2009-10-31 13:47:47 +0100 (Sa, 31 Okt 2009) | 1 line Set retval on PyOS_string_to_double failure. ........ r75995 | eric.smith | 2009-10-31 18:07:17 +0100 (Sa, 31 Okt 2009) | 1 line Improved test for a deprecation warning. ........ r75999 | gregory.p.smith | 2009-10-31 22:23:39 +0100 (Sa, 31 Okt 2009) | 2 lines Define TCSASOFT if the flag exists. ........ Modified: python/branches/release26-maint/ (props changed) From python-checkins at python.org Wed May 19 15:53:17 2010 From: python-checkins at python.org (georg.brandl) Date: Wed, 19 May 2010 15:53:17 +0200 (CEST) Subject: [Python-checkins] r81330 - in python/branches/release26-maint: Doc/library/socketserver.rst Message-ID: <20100519135317.78B22F822@mail.python.org> Author: georg.brandl Date: Wed May 19 15:53:17 2010 New Revision: 81330 Log: Merged revisions 76430 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r76430 | r.david.murray | 2009-11-20 14:29:43 +0100 (Fr, 20 Nov 2009) | 2 lines Issue 7363: fix indentation in socketserver udpserver example. ........ Modified: python/branches/release26-maint/ (props changed) python/branches/release26-maint/Doc/library/socketserver.rst Modified: python/branches/release26-maint/Doc/library/socketserver.rst ============================================================================== --- python/branches/release26-maint/Doc/library/socketserver.rst (original) +++ python/branches/release26-maint/Doc/library/socketserver.rst Wed May 19 15:53:17 2010 @@ -456,9 +456,9 @@ socket.sendto(data.upper(), self.client_address) if __name__ == "__main__": - HOST, PORT = "localhost", 9999 - server = SocketServer.UDPServer((HOST, PORT), MyUDPHandler) - server.serve_forever() + HOST, PORT = "localhost", 9999 + server = SocketServer.UDPServer((HOST, PORT), MyUDPHandler) + server.serve_forever() This is the client side:: From python-checkins at python.org Wed May 19 16:00:57 2010 From: python-checkins at python.org (georg.brandl) Date: Wed, 19 May 2010 16:00:57 +0200 (CEST) Subject: [Python-checkins] r81331 - python/branches/release26-maint Message-ID: <20100519140057.D6557EA0A@mail.python.org> Author: georg.brandl Date: Wed May 19 16:00:57 2010 New Revision: 81331 Log: Blocked revisions 76001,76003,76007,76016,76025,76028-76029,76034,76047,76051-76054,76057-76058,76062,76064,76066-76067,76108,76126,76129,76132,76139-76141,76154,76162,76176,76194,76196,76199,76230-76231,76243,76249,76260,76286,76300,76306,76308-76309,76321-76322,76333,76337,76358,76362,76367,76373,76379-76380,76382,76392,76399,76411,76428-76429,76431-76432,76434,76438,76443,76465,76472,76483,76487,76489,76495,76498,76502,76507-76509,76517,76522,76529,76531,76534-76535,76546,76548,76550-76551,76556,76558,76561,76568,76571,76583,76588,76591,76600,76602-76603,76605,76623,76625,76628,76632,76636,76640,76642,76644,76648,76655,76668,76672-76674,76676,76679,76689-76692,76697,76701-76702,76704,76708,76712,76716,76718,76720,76733,76736-76737,76740,76746,76750,76754-76755,76763,76780,76791,76805,76807,76813,76822,76824,76826,76831,76849,76851,76856,76861,76865,76869,76878,76898,76912,76916,76930,76934-76935,76948,76956,76963,76967-76968,76973,76978,76982,76984,76989,76996,76998 via svnmerge ................ r76001 | antoine.pitrou | 2009-11-01 00:19:52 +0100 (So, 01 Nov 2009) | 3 lines Use richer assertions in test_mailbox (for better failure messages). ................ r76003 | antoine.pitrou | 2009-11-01 01:30:13 +0100 (So, 01 Nov 2009) | 6 lines Hopefully fix the buildbot problems on test_mailbox, by computing the maildir toc cache refresh date before actually refreshing the cache. (see #6896) ................ r76007 | antoine.pitrou | 2009-11-01 12:58:22 +0100 (So, 01 Nov 2009) | 3 lines Buffered I/O: optimize lock taking in the common non-contended case. ................ r76016 | gregory.p.smith | 2009-11-01 19:33:55 +0100 (So, 01 Nov 2009) | 2 lines news entry for r76000 ................ r76025 | raymond.hettinger | 2009-11-01 21:45:16 +0100 (So, 01 Nov 2009) | 1 line Fix exception handling in itertools.izip_longest(). ................ r76028 | gregory.p.smith | 2009-11-01 22:02:52 +0100 (So, 01 Nov 2009) | 2 lines issue1115: convert some AC_TRY_RUNs into AC_TRY_COMPILEs. ................ r76029 | gregory.p.smith | 2009-11-01 22:03:38 +0100 (So, 01 Nov 2009) | 2 lines configure generated from r76028 ................ r76034 | antoine.pitrou | 2009-11-01 22:29:33 +0100 (So, 01 Nov 2009) | 3 lines This should finally fix #6896. Let's watch the buildbots. ................ r76047 | antoine.pitrou | 2009-11-02 00:54:20 +0100 (Mo, 02 Nov 2009) | 3 lines Fix and improve some assertions in test_site ................ r76051 | gregory.p.smith | 2009-11-02 02:38:35 +0100 (Mo, 02 Nov 2009) | 2 lines build using r76050 ................ r76052 | gregory.p.smith | 2009-11-02 03:02:38 +0100 (Mo, 02 Nov 2009) | 5 lines see issue1006238, this merges in the following patch to ease cross compiling the printf %zd check. http://sources.gentoo.org/viewcvs.py/gentoo-x86/dev-lang/python/files/python-2.5-cross-printf.patch?rev=1.1&view=markup ................ r76053 | gregory.p.smith | 2009-11-02 03:03:16 +0100 (Mo, 02 Nov 2009) | 2 lines regenerated from r76052 ................ r76054 | antoine.pitrou | 2009-11-02 12:34:27 +0100 (Mo, 02 Nov 2009) | 3 lines Since r76034 was successful, add a NEWS entry for it. ................ r76057 | benjamin.peterson | 2009-11-02 16:06:45 +0100 (Mo, 02 Nov 2009) | 1 line prevent a rather unlikely segfault ................ r76058 | benjamin.peterson | 2009-11-02 17:14:19 +0100 (Mo, 02 Nov 2009) | 1 line grant list.index() a more informative error message #7252 ................ r76062 | benjamin.peterson | 2009-11-02 19:12:12 +0100 (Mo, 02 Nov 2009) | 70 lines Merged revisions 74359,75081,75088,75213,75278,75303,75427-75428,75734-75736,75865,76059-76061 via svnmerge from svn+ssh://pythondev at svn.python.org/sandbox/trunk/2to3/lib2to3 ........ r74359 | benjamin.peterson | 2009-08-12 17:23:13 -0500 (Wed, 12 Aug 2009) | 1 line don't pass the deprecated print_function option ........ r75081 | benjamin.peterson | 2009-09-26 22:02:57 -0500 (Sat, 26 Sep 2009) | 1 line let 2to3 work with extended iterable unpacking ........ r75088 | benjamin.peterson | 2009-09-27 11:25:21 -0500 (Sun, 27 Sep 2009) | 1 line look on the type only for __call__ ........ r75213 | benjamin.peterson | 2009-10-03 10:09:46 -0500 (Sat, 03 Oct 2009) | 5 lines revert 75212; it's not correct People can use isinstance(x, collections.Callable) if they expect objects with __call__ in their instance dictionaries. ........ r75278 | benjamin.peterson | 2009-10-07 16:25:56 -0500 (Wed, 07 Oct 2009) | 4 lines fix whitespace problems with fix_idioms #3563 Patch by Joe Amenta. ........ r75303 | benjamin.peterson | 2009-10-09 16:59:11 -0500 (Fri, 09 Oct 2009) | 1 line port latin-1 and utf-8 cookie improvements ........ r75427 | benjamin.peterson | 2009-10-14 20:35:57 -0500 (Wed, 14 Oct 2009) | 1 line force floor division ........ r75428 | benjamin.peterson | 2009-10-14 20:39:21 -0500 (Wed, 14 Oct 2009) | 1 line silence -3 warnings about __hash__ ........ r75734 | benjamin.peterson | 2009-10-26 16:25:53 -0500 (Mon, 26 Oct 2009) | 2 lines warn on map(None, ...) with more than 2 arguments #7203 ........ r75735 | benjamin.peterson | 2009-10-26 16:28:25 -0500 (Mon, 26 Oct 2009) | 1 line remove unused result ........ r75736 | benjamin.peterson | 2009-10-26 16:29:02 -0500 (Mon, 26 Oct 2009) | 1 line using get() here is a bit pointless ........ r75865 | benjamin.peterson | 2009-10-27 15:49:00 -0500 (Tue, 27 Oct 2009) | 1 line explain reason for warning ........ r76059 | benjamin.peterson | 2009-11-02 11:43:47 -0600 (Mon, 02 Nov 2009) | 1 line tuples are no longer used for children ........ r76060 | benjamin.peterson | 2009-11-02 11:55:40 -0600 (Mon, 02 Nov 2009) | 1 line revert r76059; apparently some fixers rely on Leaf no () for children ........ r76061 | benjamin.peterson | 2009-11-02 12:06:17 -0600 (Mon, 02 Nov 2009) | 1 line make fix_tuple_params keep the tree valid #7253 ........ ................ r76064 | benjamin.peterson | 2009-11-02 19:16:36 +0100 (Mo, 02 Nov 2009) | 1 line add space ................ r76066 | benjamin.peterson | 2009-11-02 19:22:53 +0100 (Mo, 02 Nov 2009) | 9 lines Merged revisions 76065 via svnmerge from svn+ssh://pythondev at svn.python.org/sandbox/trunk/2to3/lib2to3 ........ r76065 | benjamin.peterson | 2009-11-02 12:21:25 -0600 (Mon, 02 Nov 2009) | 1 line don't print stuff in tests ........ ................ r76067 | benjamin.peterson | 2009-11-02 19:24:57 +0100 (Mo, 02 Nov 2009) | 1 line enable test_parser in lib2to3 ................ r76108 | antoine.pitrou | 2009-11-04 20:25:14 +0100 (Mi, 04 Nov 2009) | 6 lines Issue #7211: Allow 64-bit values for the `ident` and `data` fields of kevent objects on 64-bit systems. Patch by Michael Broghton. I will revert this checkin if it causes problems on our BSD buildbots. ................ r76126 | benjamin.peterson | 2009-11-05 22:29:56 +0100 (Do, 05 Nov 2009) | 9 lines Merged revisions 76125 via svnmerge from svn+ssh://pythondev at svn.python.org/sandbox/trunk/2to3/lib2to3 ........ r76125 | benjamin.peterson | 2009-11-05 15:26:55 -0600 (Thu, 05 Nov 2009) | 1 line handle newline issues better for comparing files ........ ................ r76129 | benjamin.peterson | 2009-11-06 00:20:06 +0100 (Fr, 06 Nov 2009) | 13 lines Merged revisions 76127-76128 via svnmerge from svn+ssh://pythondev at svn.python.org/sandbox/trunk/2to3/lib2to3 ........ r76127 | benjamin.peterson | 2009-11-05 17:04:58 -0600 (Thu, 05 Nov 2009) | 1 line set svn:eol-style ........ r76128 | benjamin.peterson | 2009-11-05 17:07:46 -0600 (Thu, 05 Nov 2009) | 1 line skip this test on windows to avoid newline horrors ........ ................ r76132 | benjamin.peterson | 2009-11-06 00:54:42 +0100 (Fr, 06 Nov 2009) | 9 lines Merged revisions 76131 via svnmerge from svn+ssh://pythondev at svn.python.org/sandbox/trunk/2to3/lib2to3 ........ r76131 | benjamin.peterson | 2009-11-05 17:53:21 -0600 (Thu, 05 Nov 2009) | 1 line import sys ........ ................ r76139 | benjamin.peterson | 2009-11-07 02:04:38 +0100 (Sa, 07 Nov 2009) | 1 line spelling ................ r76140 | nick.coghlan | 2009-11-07 09:13:55 +0100 (Sa, 07 Nov 2009) | 1 line Add test for runpy.run_module package execution and use something other than logging as the example of a non-executable package ................ r76141 | nick.coghlan | 2009-11-07 09:15:01 +0100 (Sa, 07 Nov 2009) | 1 line Some minor cleanups to private runpy code and docstrings ................ r76154 | brett.cannon | 2009-11-08 22:35:28 +0100 (So, 08 Nov 2009) | 4 lines Properly detect whether a C file is using tabs or spaces for Vim. Closes issue #5611. Thanks Kirk McDonald and Johannes Hoff. ................ r76162 | benjamin.peterson | 2009-11-09 05:10:53 +0100 (Mo, 09 Nov 2009) | 1 line discuss how to use -p ................ r76176 | mark.dickinson | 2009-11-09 18:03:34 +0100 (Mo, 09 Nov 2009) | 7 lines Issue #7251: Break out round tests for large values into a separate test function, and skip that test on Linux/alpha systems with a broken system round function. This should turn the Debian/alpha buildbot green. ................ r76194 | raymond.hettinger | 2009-11-10 20:35:55 +0100 (Di, 10 Nov 2009) | 3 lines Show example of how to make a sorted dictionary ................ r76196 | antoine.pitrou | 2009-11-10 21:49:30 +0100 (Di, 10 Nov 2009) | 8 lines Issue #7197: Allow unittest.TextTestRunner objects to be pickled and unpickled. This fixes crashes under Windows when trying to run test_multiprocessing in verbose mode. Additionally, Test_TextTestRunner hadn't been enabled in test_unittest. ................ r76199 | antoine.pitrou | 2009-11-10 22:39:25 +0100 (Di, 10 Nov 2009) | 3 lines Backport micro-fix from the py3k svnmerge ................ r76230 | benjamin.peterson | 2009-11-13 00:39:44 +0100 (Fr, 13 Nov 2009) | 2 lines fix several compile() issues by translating newlines in the tokenizer ................ r76231 | benjamin.peterson | 2009-11-13 00:42:23 +0100 (Fr, 13 Nov 2009) | 1 line this main is much more useful ................ r76243 | benjamin.peterson | 2009-11-13 23:17:17 +0100 (Fr, 13 Nov 2009) | 1 line never mind about eval mode in this case ................ r76249 | benjamin.peterson | 2009-11-13 23:56:00 +0100 (Fr, 13 Nov 2009) | 1 line revert r76243; I was right, actually :) ................ r76260 | r.david.murray | 2009-11-14 16:18:22 +0100 (Sa, 14 Nov 2009) | 5 lines Issue #7312 (new feature): Add a -F flag to run the selected tests in a loop until a test fails. Can be combined with -j. Patch by Antoine Pitrou. ................ r76286 | nick.coghlan | 2009-11-15 08:30:34 +0100 (So, 15 Nov 2009) | 1 line Issue #6816: expose the zipfile and directory execution mechanism to Python code via the runpy module. Also consolidated some script execution functionality in the test harness into a helper module and removed some implementation details from the runpy module documentation. ................ r76300 | mark.dickinson | 2009-11-15 14:12:43 +0100 (So, 15 Nov 2009) | 3 lines Issue #5792: Extend short float repr support to x86 platforms using suncc or icc. Many thanks Stefan Krah for help and OpenSolaris testing. ................ r76306 | antoine.pitrou | 2009-11-15 15:10:48 +0100 (So, 15 Nov 2009) | 4 lines Issue #4969: The mimetypes module now reads the MIME database from the registry under Windows. Patch by Gabriel Genellina. ................ r76308 | mark.dickinson | 2009-11-15 17:18:58 +0100 (So, 15 Nov 2009) | 3 lines Issue #7228: Add '%lld' and '%llu' support to PyFormat_FromString, PyFormat_FromStringV and PyErr_Format. ................ r76309 | antoine.pitrou | 2009-11-15 18:22:09 +0100 (So, 15 Nov 2009) | 4 lines Issue #2054: ftplib now provides an FTP_TLS class to do secure FTP using TLS or SSL. Patch by Giampaolo Rodola'. ................ r76321 | nick.coghlan | 2009-11-16 04:55:51 +0100 (Mo, 16 Nov 2009) | 1 line Account for another cache when hunting ref leaks ................ r76322 | nick.coghlan | 2009-11-16 04:57:32 +0100 (Mo, 16 Nov 2009) | 1 line Allow for backslashes in file paths passed to the regex engine ................ r76333 | mark.dickinson | 2009-11-16 20:17:16 +0100 (Mo, 16 Nov 2009) | 1 line Silence another MSVC warning about unary minus. ................ r76337 | philip.jenvey | 2009-11-17 03:42:26 +0100 (Di, 17 Nov 2009) | 2 lines #1757126: fix typo with the cyrillic_asian alias ................ r76358 | tarek.ziade | 2009-11-18 09:46:56 +0100 (Mi, 18 Nov 2009) | 1 line #7293: distutils.test_msvc9compiler now uses a key that exists on any fresh windows install ................ r76362 | nick.coghlan | 2009-11-18 12:27:53 +0100 (Mi, 18 Nov 2009) | 1 line Correctly escape arbitrary error message text in the runpy unit tests ................ r76367 | georg.brandl | 2009-11-18 19:52:35 +0100 (Mi, 18 Nov 2009) | 1 line Make separate section for deprecations in 2.7 whatsnew. ................ r76373 | mark.dickinson | 2009-11-18 20:33:35 +0100 (Mi, 18 Nov 2009) | 5 lines Issue #7117, continued: Change round implementation to use the correctly-rounded string <-> float conversions; this makes sure that the result of the round operation is correctly rounded, and hence displays nicely using the new float repr. ................ r76379 | mark.dickinson | 2009-11-18 21:14:57 +0100 (Mi, 18 Nov 2009) | 1 line Enable short float repr! ................ r76380 | antoine.pitrou | 2009-11-18 21:20:46 +0100 (Mi, 18 Nov 2009) | 3 lines Mention Giampolo R's new FTP TLS support in the what's new file ................ r76382 | raymond.hettinger | 2009-11-18 21:28:22 +0100 (Mi, 18 Nov 2009) | 1 line Issue 7263: Fix set.intersection() docstring. ................ r76392 | raymond.hettinger | 2009-11-19 02:22:04 +0100 (Do, 19 Nov 2009) | 1 line Fix docstrings for itertools combinatoric functions. ................ r76399 | tarek.ziade | 2009-11-19 06:33:16 +0100 (Do, 19 Nov 2009) | 1 line dragfullwindows can have value 2 ................ r76411 | mark.dickinson | 2009-11-19 19:41:49 +0100 (Do, 19 Nov 2009) | 1 line Misc/NEWS entries for issue 7117. ................ r76428 | benjamin.peterson | 2009-11-20 03:15:50 +0100 (Fr, 20 Nov 2009) | 1 line turn goto into do while loop ................ r76429 | benjamin.peterson | 2009-11-20 03:56:43 +0100 (Fr, 20 Nov 2009) | 2 lines avoid doing an uneeded import in a function ................ r76431 | mark.dickinson | 2009-11-20 20:27:43 +0100 (Fr, 20 Nov 2009) | 1 line Regenerate configure with GNU autoconf 2.61. ................ r76432 | mark.dickinson | 2009-11-20 20:30:22 +0100 (Fr, 20 Nov 2009) | 5 lines Issue #7272: Add configure test to detect whether sem_open works properly, and use this to skip test_multiprocessing on platforms where sem_open raises a signal. This should fix some FreeBSD buildbot failures for test_multiprocessing. ................ r76434 | jesse.noller | 2009-11-21 15:06:24 +0100 (Sa, 21 Nov 2009) | 1 line revert unintended change to multiprocessing/queues.py ................ r76438 | jesse.noller | 2009-11-21 15:38:23 +0100 (Sa, 21 Nov 2009) | 1 line issue6615: Additional test for logging support in multiprocessing ................ r76443 | lars.gustaebel | 2009-11-22 19:30:53 +0100 (So, 22 Nov 2009) | 24 lines Issue #6123: Fix opening empty archives and files. (Note that an empty archive is not the same as an empty file. An empty archive contains no members and is correctly terminated with an EOF block full of zeros. An empty file contains no data at all.) The problem was that although tarfile was able to create empty archives, it failed to open them raising a ReadError. On the other hand, tarfile opened empty files without error in most read modes and presented them as empty archives. (However, some modes still raised errors: "r|gz" raised ReadError, but "r:gz" worked, "r:bz2" even raised EOFError.) In order to get a more fine-grained control over the various internal error conditions I now split up the HeaderError exception into a number of meaningful sub-exceptions. This makes it easier in the TarFile.next() method to react to the different conditions in the correct way. The visible change in its behaviour now is that tarfile will open empty archives correctly and raise ReadError consistently for empty files. ................ r76465 | mark.dickinson | 2009-11-23 19:46:41 +0100 (Mo, 23 Nov 2009) | 4 lines Remove restriction on precision when formatting floats. This is the first step towards removing the %f -> %g switch (see issues 7117, 5859). ................ r76472 | mark.dickinson | 2009-11-23 21:54:09 +0100 (Mo, 23 Nov 2009) | 4 lines Issue #7117, continued: Remove substitution of %g-style formatting for %f-style formatting, which used to occur at high precision. Float formatting should now be consistent between 2.7 and 3.1. ................ r76483 | mark.dickinson | 2009-11-24 11:54:58 +0100 (Di, 24 Nov 2009) | 2 lines round(0, "ermintrude") succeeded instead of producing a TypeError. Fix this. ................ r76487 | jesse.noller | 2009-11-24 15:17:29 +0100 (Di, 24 Nov 2009) | 1 line comment out test added in r76438, which caused refleaks ................ r76489 | mark.dickinson | 2009-11-24 15:27:02 +0100 (Di, 24 Nov 2009) | 1 line Fix some documentation examples involving the repr of a float. ................ r76495 | mark.dickinson | 2009-11-24 16:12:20 +0100 (Di, 24 Nov 2009) | 2 lines Issue #7117: Update float formatting testcases to match those in py3k. ................ r76498 | vinay.sajip | 2009-11-24 16:53:25 +0100 (Di, 24 Nov 2009) | 1 line Made logging classes new-style and added name property to handlers. ................ r76502 | mark.dickinson | 2009-11-24 21:51:48 +0100 (Di, 24 Nov 2009) | 3 lines Issue #7228: Fix format mismatch when printing something of type off_t. (Should silence some compiler warnings.) ................ r76507 | vinay.sajip | 2009-11-25 10:03:30 +0100 (Mi, 25 Nov 2009) | 1 line Issue #6615: logging: Used weak references in internal handler list. Thanks to flox (Florent Xicluna) for the patch. ................ r76508 | vinay.sajip | 2009-11-25 10:22:47 +0100 (Mi, 25 Nov 2009) | 1 line logging: made _handlers a WeakValueDictionary. ................ r76509 | vinay.sajip | 2009-11-25 15:12:03 +0100 (Mi, 25 Nov 2009) | 1 line logging: Issue 6615: Changed handler prepend to append. ................ r76517 | benjamin.peterson | 2009-11-25 19:16:46 +0100 (Mi, 25 Nov 2009) | 29 lines Merged revisions 76160-76161,76250,76252,76447,76506 via svnmerge from svn+ssh://pythondev at svn.python.org/sandbox/trunk/2to3/lib2to3 ........ r76160 | benjamin.peterson | 2009-11-08 18:53:48 -0600 (Sun, 08 Nov 2009) | 1 line undeprecate the -p option; it's useful for converting python3 sources ........ r76161 | benjamin.peterson | 2009-11-08 19:05:37 -0600 (Sun, 08 Nov 2009) | 1 line simplify condition ........ r76250 | benjamin.peterson | 2009-11-13 16:56:48 -0600 (Fri, 13 Nov 2009) | 1 line fix handling of a utf-8 bom #7313 ........ r76252 | benjamin.peterson | 2009-11-13 16:58:36 -0600 (Fri, 13 Nov 2009) | 1 line remove pdb turd ........ r76447 | benjamin.peterson | 2009-11-22 18:17:40 -0600 (Sun, 22 Nov 2009) | 1 line #7375 fix nested transformations in fix_urllib ........ r76506 | benjamin.peterson | 2009-11-24 18:34:31 -0600 (Tue, 24 Nov 2009) | 1 line use generator expressions in any() ........ ................ r76522 | barry.warsaw | 2009-11-25 19:38:32 +0100 (Mi, 25 Nov 2009) | 2 lines Add mktime_tz to __all__. It's documented as being available in email.utils. ................ r76529 | antoine.pitrou | 2009-11-25 23:59:36 +0100 (Mi, 25 Nov 2009) | 4 lines Issue #5788: `datetime.timedelta` objects get a new `total_seconds()` method returning the total number of seconds in the duration. Patch by Brian Quinlan. ................ r76531 | antoine.pitrou | 2009-11-26 00:03:22 +0100 (Do, 26 Nov 2009) | 3 lines Forgot to add a `versionadded` tag ................ r76534 | martin.v.loewis | 2009-11-26 09:42:05 +0100 (Do, 26 Nov 2009) | 2 lines Fix typo. ................ r76535 | antoine.pitrou | 2009-11-26 13:36:30 +0100 (Do, 26 Nov 2009) | 3 lines When open_urlresource() fails, HTTPException is another possible error ................ r76546 | antoine.pitrou | 2009-11-27 14:18:34 +0100 (Fr, 27 Nov 2009) | 7 lines Issue #6845: Add restart support for binary upload in ftplib. The `storbinary()` method of FTP and FTP_TLS objects gains an optional `rest` argument. Patch by Pablo Mouzo. (note: the patch also adds a test for the rest argument in retrbinary()) ................ r76548 | antoine.pitrou | 2009-11-27 14:24:29 +0100 (Fr, 27 Nov 2009) | 3 lines Add ACKS entry for Pablo Mouzo ................ r76550 | martin.v.loewis | 2009-11-27 14:56:01 +0100 (Fr, 27 Nov 2009) | 2 lines Issue #6508: Add posix.{getresuid,getresgid,setresuid,setresgid}. ................ r76551 | vinay.sajip | 2009-11-27 15:03:36 +0100 (Fr, 27 Nov 2009) | 1 line Issue #7403: Fixed possible race condition in lock creation. ................ r76556 | gregory.p.smith | 2009-11-27 18:51:12 +0100 (Fr, 27 Nov 2009) | 2 lines fix typo ................ r76558 | mark.dickinson | 2009-11-28 11:44:20 +0100 (Sa, 28 Nov 2009) | 4 lines Issue #7272, continued: don't re-use existing HAVE_BROKEN_POSIX_SEMAPHORES to indicate that semaphores aren't available; define a new variable POSIX_SEMAPHORES_NOT_ENABLED instead. ................ r76561 | mark.dickinson | 2009-11-28 13:30:36 +0100 (Sa, 28 Nov 2009) | 5 lines Include ieeefp.h (when available) in pyport.h instead of individually in Objects/floatobject.c and Objects/complexobject.c. This should silence compiler warnings about implicit declaration of the 'finite' function on Solaris. ................ r76568 | mark.dickinson | 2009-11-28 14:13:13 +0100 (Sa, 28 Nov 2009) | 1 line Multiprocessing configure checks don't need LIBM ................ r76571 | antoine.pitrou | 2009-11-28 16:55:58 +0100 (Sa, 28 Nov 2009) | 3 lines Issue #1515: Enable use of deepcopy() with instance methods. Patch by Robert Collins. ................ r76583 | eric.smith | 2009-11-29 18:40:57 +0100 (So, 29 Nov 2009) | 1 line Issue #3382: Make '%F' and float.__format__('F') convert results to upper case. Much of the patch came from Mark Dickinson. ................ r76588 | tarek.ziade | 2009-11-29 23:20:30 +0100 (So, 29 Nov 2009) | 1 line Fixed #7408: dropped group ownership checking because it relies on os-specific rules ................ r76591 | benjamin.peterson | 2009-11-29 23:26:26 +0100 (So, 29 Nov 2009) | 4 lines now that deepcopy can handle instance methods, this hack can be removed #7409 Thanks Robert Collins ................ r76600 | raymond.hettinger | 2009-11-30 20:44:40 +0100 (Mo, 30 Nov 2009) | 3 lines Issue 7410: deepcopy of itertools.count resets the count ................ r76602 | raymond.hettinger | 2009-11-30 22:13:52 +0100 (Mo, 30 Nov 2009) | 1 line Handle step values other than one. ................ r76603 | raymond.hettinger | 2009-11-30 22:14:25 +0100 (Mo, 30 Nov 2009) | 1 line Update project file for new file: dtoa.c ................ r76605 | mark.dickinson | 2009-11-30 22:51:30 +0100 (Mo, 30 Nov 2009) | 2 lines Add dtoa.c and dtoa.h to the relevant project files. ................ r76623 | ronald.oussoren | 2009-12-01 16:54:01 +0100 (Di, 01 Dez 2009) | 9 lines Fix for issue #7416: SIZEOF_UINTPTR_T can be invalid when configuring a multi-architecture build (in particular when the architectures don't share a common pointer size). Fixed the same issue for SIZEOF_PTHREAD_T. (No update to the NEWS file because this is a bugfix for an as yet unreleased feature) ................ r76625 | amaury.forgeotdarc | 2009-12-01 22:51:04 +0100 (Di, 01 Dez 2009) | 3 lines #7419: Fix a crash on Windows in locale.setlocale() when the category is outside the allowed range. ................ r76628 | andrew.kuchling | 2009-12-02 15:27:11 +0100 (Mi, 02 Dez 2009) | 1 line Markup fixes ................ r76632 | eric.smith | 2009-12-02 18:43:06 +0100 (Mi, 02 Dez 2009) | 1 line Issue #4482: Add tests for special float value formatting. ................ r76636 | antoine.pitrou | 2009-12-02 21:37:54 +0100 (Mi, 02 Dez 2009) | 5 lines Issue #7333: The `posix` module gains an `initgroups()` function providing access to the initgroups(3) C library call on Unix systems which implement it. Patch by Jean-Paul Calderone. ................ r76640 | philip.jenvey | 2009-12-03 03:25:54 +0100 (Do, 03 Dez 2009) | 2 lines #7177: clarify the potential PIPE deadlock warnings ................ r76642 | philip.jenvey | 2009-12-03 03:40:13 +0100 (Do, 03 Dez 2009) | 1 line actually close files ................ r76644 | benjamin.peterson | 2009-12-03 03:52:39 +0100 (Do, 03 Dez 2009) | 4 lines disable pymalloc tricks with the --with-valgrind option #2422 Patch from James Henstridge. ................ r76648 | mark.dickinson | 2009-12-03 13:08:56 +0100 (Do, 03 Dez 2009) | 3 lines Issue #6985: number of range() items should be constrained to lie in a Py_ssize_t, not an int. ................ r76655 | martin.v.loewis | 2009-12-03 22:01:16 +0100 (Do, 03 Dez 2009) | 2 lines Add Christoph Gohlke, for the issue 4120 work. ................ r76668 | mark.dickinson | 2009-12-04 12:30:16 +0100 (Fr, 04 Dez 2009) | 1 line Add missing issue number in Misc/NEWS entry. ................ r76672 | benjamin.peterson | 2009-12-05 18:45:40 +0100 (Sa, 05 Dez 2009) | 1 line regenerate pydoc_topics ................ r76673 | benjamin.peterson | 2009-12-05 18:46:33 +0100 (Sa, 05 Dez 2009) | 2 lines move RPM spec for 2.7 ................ r76674 | benjamin.peterson | 2009-12-05 18:47:56 +0100 (Sa, 05 Dez 2009) | 1 line bump version to 2.7a1 ................ r76676 | benjamin.peterson | 2009-12-05 19:40:02 +0100 (Sa, 05 Dez 2009) | 1 line post release version bump ................ r76679 | benjamin.peterson | 2009-12-05 19:48:13 +0100 (Sa, 05 Dez 2009) | 1 line fix date ................ r76689 | benjamin.peterson | 2009-12-06 18:37:48 +0100 (So, 06 Dez 2009) | 1 line rewrite translate_newlines for clarity ................ r76690 | vinay.sajip | 2009-12-06 18:57:11 +0100 (So, 06 Dez 2009) | 1 line logging: Added optional 'secure' parameter to SMTPHandler. ................ r76691 | vinay.sajip | 2009-12-06 19:05:04 +0100 (So, 06 Dez 2009) | 1 line logging: Improved support for SMTP over TLS. ................ r76692 | martin.v.loewis | 2009-12-06 19:27:29 +0100 (So, 06 Dez 2009) | 2 lines Add UUIDs for 2.7. Drop UUIDs for 2.4. ................ r76697 | benjamin.peterson | 2009-12-06 22:24:30 +0100 (So, 06 Dez 2009) | 2 lines fix test_parser from tokenizer tweak ................ r76701 | andrew.kuchling | 2009-12-08 03:37:05 +0100 (Di, 08 Dez 2009) | 1 line Typo fix; grammar fix ................ r76702 | tarek.ziade | 2009-12-08 09:56:49 +0100 (Di, 08 Dez 2009) | 1 line Issue #7457: added a read_pkg_file method to distutils.dist.DistributionMetadata so we can read back PKG-INFO files ................ r76704 | tarek.ziade | 2009-12-08 10:39:51 +0100 (Di, 08 Dez 2009) | 1 line removed the usage of rfc822 in favor of email.message.Message ................ r76708 | antoine.pitrou | 2009-12-08 16:40:51 +0100 (Di, 08 Dez 2009) | 4 lines Issue #6986: Fix crash in the JSON C accelerator when called with the wrong parameter types. Patch by Victor Stinner. ................ r76712 | ronald.oussoren | 2009-12-08 17:32:52 +0100 (Di, 08 Dez 2009) | 4 lines Fix for issue 7452: HAVE_GCC_ASM_FOR_X87 gets set when doing a universal build on an i386 based machine, but should only be active when compiling the x86 part of the universal binary. ................ r76716 | antoine.pitrou | 2009-12-08 20:25:51 +0100 (Di, 08 Dez 2009) | 4 lines Fix the transient refleaks in test_zipimport_support. Diagnosis and original patch by Florent Xicluna (flox). ................ r76718 | antoine.pitrou | 2009-12-08 20:35:12 +0100 (Di, 08 Dez 2009) | 3 lines Fix transient refleaks in test_urllib. Thanks to Florent Xicluna. ................ r76720 | antoine.pitrou | 2009-12-08 20:46:38 +0100 (Di, 08 Dez 2009) | 3 lines Make test_pipes a little bit more robust. ................ r76733 | benjamin.peterson | 2009-12-10 04:37:59 +0100 (Do, 10 Dez 2009) | 1 line substitute PyDict_Check() for PyObject_IsInstance ................ r76736 | raymond.hettinger | 2009-12-10 07:00:33 +0100 (Do, 10 Dez 2009) | 1 line Fix variants of deque.extend: d.extend(d) d+=d d.extendleft(d) ................ r76737 | raymond.hettinger | 2009-12-10 07:42:54 +0100 (Do, 10 Dez 2009) | 1 line Add a reverse() method to collections.deque(). ................ r76740 | mark.dickinson | 2009-12-10 11:36:32 +0100 (Do, 10 Dez 2009) | 8 lines Replace the size check for PyMem_MALLOC and PyMem_REALLOC with an almost equivalent[*] check that doesn't produce compiler warnings about a 'x < 0' check on an unsigned type. [*] it's equivalent for inputs of type size_t or Py_ssize_t, or any smaller unsigned or signed integer type. ................ r76746 | tarek.ziade | 2009-12-10 16:29:03 +0100 (Do, 10 Dez 2009) | 1 line added test coverage for distutils.dep_util, and cleaned up the module ................ r76750 | tarek.ziade | 2009-12-10 20:29:53 +0100 (Do, 10 Dez 2009) | 1 line using an existing file to avoid dealing with a sleep to test file ages ................ r76754 | vinay.sajip | 2009-12-11 10:16:01 +0100 (Fr, 11 Dez 2009) | 1 line Issue #7470: logging: fix bug in Unicode encoding fallback. ................ r76755 | mark.dickinson | 2009-12-11 18:29:33 +0100 (Fr, 11 Dez 2009) | 2 lines Issue #3366: Add lgamma function to math module. ................ r76763 | antoine.pitrou | 2009-12-12 20:13:08 +0100 (Sa, 12 Dez 2009) | 7 lines Issue #7466: segmentation fault when the garbage collector is called in the middle of populating a tuple. Patch by Florent Xicluna. (note: no NEWS entry for trunk since the bug was introduced in 2.7/3.1) ................ r76780 | lars.gustaebel | 2009-12-13 12:32:27 +0100 (So, 13 Dez 2009) | 21 lines Issue #7357: No longer suppress fatal extraction errors by default. TarFile's errorlevel argument controls how errors are handled that occur during extraction. There are three possible levels 0, 1 and 2. If errorlevel is set to 1 or 2 fatal errors (e.g. a full filesystem) are raised as exceptions. If it is set to 0, which is the default value, extraction errors are suppressed, and error messages are written to the debug log instead. But, if the debug log is not activated, which is the default as well, all these errors go unnoticed. The original intention was to imitate GNU tar which tries to extract as many members as possible instead of stopping on the first error. It turns out that this is no good default behaviour for a tar library. This patch simply changes the default value for the errorlevel argument from 0 to 1, so that fatal extraction errors are raised as EnvironmentError exceptions. ................ r76791 | antoine.pitrou | 2009-12-13 17:18:14 +0100 (So, 13 Dez 2009) | 5 lines Add NEWS entry as per RDM's suggestion (the bug was actually present in 2.7 alpha 1) ................ r76805 | benjamin.peterson | 2009-12-13 20:19:07 +0100 (So, 13 Dez 2009) | 7 lines accept None as the same as having passed no argument in file types #7349 This is for consistency with imitation file objects like StringIO and BytesIO. This commit also adds a few tests, where they were lacking for concerned methods. ................ r76807 | benjamin.peterson | 2009-12-13 20:27:02 +0100 (So, 13 Dez 2009) | 1 line remove unused variable ................ r76813 | mark.dickinson | 2009-12-13 22:06:06 +0100 (So, 13 Dez 2009) | 3 lines Issue #7492: Autoconf tests were leaving semaphore files behind. Add sem_unlink calls to delete those semaphore files. ................ r76822 | benjamin.peterson | 2009-12-13 22:21:43 +0100 (So, 13 Dez 2009) | 1 line initialize to NULL ................ r76824 | benjamin.peterson | 2009-12-13 22:27:53 +0100 (So, 13 Dez 2009) | 1 line add a test of loading the datetime capi ................ r76826 | tarek.ziade | 2009-12-14 00:24:13 +0100 (Mo, 14 Dez 2009) | 1 line reorganized the distutils doc a bit : the MANIFEST.in template system has its own section now. This is easier to find and follow ................ r76831 | r.david.murray | 2009-12-14 17:28:26 +0100 (Mo, 14 Dez 2009) | 6 lines Issue #1680159: unicode coercion during an 'in' operation was masking any errors that might occur during coercion of the left operand and turning them into a TypeError with a message text that was confusing in the given context. This patch lets any errors through, as was already done during coercion of the right hand side. ................ r76849 | tarek.ziade | 2009-12-15 07:29:19 +0100 (Di, 15 Dez 2009) | 1 line cleaned up the module (PEP 8 + old fashion test removal) ................ r76851 | benjamin.peterson | 2009-12-16 04:28:52 +0100 (Mi, 16 Dez 2009) | 1 line remove lib2to3 resource ................ r76856 | r.david.murray | 2009-12-16 12:49:46 +0100 (Mi, 16 Dez 2009) | 2 lines Issue #7396: fix -s, which was broken by the -j enhancement. ................ r76861 | mark.dickinson | 2009-12-16 21:13:40 +0100 (Mi, 16 Dez 2009) | 3 lines Issue #3366: Add expm1 function to math module. Thanks Eric Smith for testing on Windows. ................ r76865 | mark.dickinson | 2009-12-17 09:33:56 +0100 (Do, 17 Dez 2009) | 1 line Add _math.h to math module dependencies in setup.py. ................ r76869 | vinay.sajip | 2009-12-17 15:52:00 +0100 (Do, 17 Dez 2009) | 1 line Issue #7529: logging: Minor correction to documentation. ................ r76878 | mark.dickinson | 2009-12-19 12:07:23 +0100 (Sa, 19 Dez 2009) | 3 lines Issue #3366: Add error function and complementary error function to math module. ................ r76898 | antoine.pitrou | 2009-12-19 22:06:36 +0100 (Sa, 19 Dez 2009) | 3 lines Remove superfetatory paragraph (left there by mistake). ................ r76912 | senthil.kumaran | 2009-12-20 08:29:31 +0100 (So, 20 Dez 2009) | 3 lines Document the headers parameter for set_tunnel. ................ r76916 | mark.dickinson | 2009-12-20 14:58:18 +0100 (So, 20 Dez 2009) | 3 lines math.factorial depends on PyLong_AsLong correctly converting floats; rewrite it to do the conversion explicitly instead. See issue #7550. ................ r76930 | mark.dickinson | 2009-12-20 16:57:56 +0100 (So, 20 Dez 2009) | 1 line Add missing tests for PyArg_Parse* with format 'h' ................ r76934 | r.david.murray | 2009-12-20 17:24:46 +0100 (So, 20 Dez 2009) | 2 lines Fix comment typo. ................ r76935 | r.david.murray | 2009-12-20 17:46:06 +0100 (So, 20 Dez 2009) | 10 lines Issue #7376: When called with no arguments doctest was running a self-test. Because of a change to the way tracebacks are printed, this self-test was failing. The test is run (and passes) during normal regression testing. So instead of running the failing self-test this patch makes doctest emit a usage message. This is better behavior anyway since passing in arguments is the real reason to run doctest as a command. Bug discovery and initial patch by Florent Xicluna. ................ r76948 | mark.dickinson | 2009-12-20 21:34:44 +0100 (So, 20 Dez 2009) | 3 lines Issue #7554: Various fixups in test_cmath.py: remove code duplication, use new-style formatting. Thanks Florent Xicluna for the patch. ................ r76956 | tarek.ziade | 2009-12-21 02:22:46 +0100 (Mo, 21 Dez 2009) | 1 line massive import cleaning in Distutils ................ r76963 | mark.dickinson | 2009-12-21 12:21:25 +0100 (Mo, 21 Dez 2009) | 3 lines Issue #7528: Backport PyLong_AsLongAndOverflow from py3k to trunk. Thanks Case Van Horsen for the patch. ................ r76967 | mark.dickinson | 2009-12-21 12:31:54 +0100 (Mo, 21 Dez 2009) | 1 line Fix reference counts for test_long_and_overflow. ................ r76968 | mark.dickinson | 2009-12-21 13:15:48 +0100 (Mo, 21 Dez 2009) | 1 line Additional edge-case tests for test_long_and_overflow. ................ r76973 | r.david.murray | 2009-12-21 13:45:41 +0100 (Mo, 21 Dez 2009) | 2 lines Remove a leftover from a previous iteration of the issue 7376 patch. ................ r76978 | mark.dickinson | 2009-12-21 16:22:00 +0100 (Mo, 21 Dez 2009) | 3 lines Issue #7518: Move substitute definitions of C99 math functions from pymath.c to Modules/_math.c. ................ r76982 | mark.dickinson | 2009-12-21 16:40:33 +0100 (Mo, 21 Dez 2009) | 2 lines Inverse hyperbolic trigonometric functions should call m_log1p, not log1p. ................ r76984 | mark.dickinson | 2009-12-21 17:29:21 +0100 (Mo, 21 Dez 2009) | 3 lines Issue #7553: test_long_future wasn't testing properly. Thanks Florent Xicluna for bug report and patch. ................ r76989 | martin.v.loewis | 2009-12-21 20:25:56 +0100 (Mo, 21 Dez 2009) | 1 line Drop 2.4 compatibility. ................ r76996 | tarek.ziade | 2009-12-22 00:31:55 +0100 (Di, 22 Dez 2009) | 1 line backported r76993 and r76994 so the trunk behaves the same way with MSVC Manifest files editing ................ r76998 | tarek.ziade | 2009-12-22 00:37:44 +0100 (Di, 22 Dez 2009) | 1 line added a note about #7556 in Misc/NEWS ................ Modified: python/branches/release26-maint/ (props changed) From python-checkins at python.org Wed May 19 16:04:44 2010 From: python-checkins at python.org (georg.brandl) Date: Wed, 19 May 2010 16:04:44 +0200 (CEST) Subject: [Python-checkins] r81332 - in python/branches/release26-maint: Doc/reference/datamodel.rst Message-ID: <20100519140444.4F65DECE3@mail.python.org> Author: georg.brandl Date: Wed May 19 16:04:44 2010 New Revision: 81332 Log: Merged revisions 77603 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r77603 | benjamin.peterson | 2010-01-19 00:07:56 +0100 (Di, 19 Jan 2010) | 8 lines data descriptors do not override the class dictionary if __get__ is not defined Adjust documentation and add a test to verify this behavior. See http://mail.python.org/pipermail/python-dev/2010-January/095637.html for discussion. ........ Modified: python/branches/release26-maint/ (props changed) python/branches/release26-maint/Doc/reference/datamodel.rst Modified: python/branches/release26-maint/Doc/reference/datamodel.rst ============================================================================== --- python/branches/release26-maint/Doc/reference/datamodel.rst (original) +++ python/branches/release26-maint/Doc/reference/datamodel.rst Wed May 19 16:04:44 2010 @@ -1603,11 +1603,17 @@ ``A.__dict__['m'].__get__(obj, A)``. For instance bindings, the precedence of descriptor invocation depends on the -which descriptor methods are defined. Normally, data descriptors define both -:meth:`__get__` and :meth:`__set__`, while non-data descriptors have just the -:meth:`__get__` method. Data descriptors always override a redefinition in an +which descriptor methods are defined. A descriptor can define any combination +of :meth:`__get__`, :meth:`__set__` and :meth:`__delete__`. If it does not +define :meth:`__get__`, then accessing the attribute will return the descriptor +object itself unless there is a value in the object's instance dictionary. If +the descriptor defines :meth:`__set__` and/or :meth:`__delete__`, it is a data +descriptor; if it defines neither, it is a non-data descriptor. Normally, data +descriptors define both :meth:`__get__` and :meth:`__set__`, while non-data +descriptors have just the :meth:`__get__` method. Data descriptors with +:meth:`__set__` and :meth:`__get__` defined always override a redefinition in an instance dictionary. In contrast, non-data descriptors can be overridden by -instances. [#]_ +instances. Python methods (including :func:`staticmethod` and :func:`classmethod`) are implemented as non-data descriptors. Accordingly, instances can redefine and @@ -2476,13 +2482,6 @@ controlled conditions. It generally isn't a good idea though, since it can lead to some very strange behaviour if it is handled incorrectly. -.. [#] A descriptor can define any combination of :meth:`__get__`, - :meth:`__set__` and :meth:`__delete__`. If it does not define :meth:`__get__`, - then accessing the attribute even on an instance will return the descriptor - object itself. If the descriptor defines :meth:`__set__` and/or - :meth:`__delete__`, it is a data descriptor; if it defines neither, it is a - non-data descriptor. - .. [#] For operands of the same type, it is assumed that if the non-reflected method (such as :meth:`__add__`) fails the operation is not supported, which is why the reflected method is not called. From python-checkins at python.org Wed May 19 16:06:47 2010 From: python-checkins at python.org (georg.brandl) Date: Wed, 19 May 2010 16:06:47 +0200 (CEST) Subject: [Python-checkins] r81333 - in python/branches/release26-maint: Doc/library/threading.rst Message-ID: <20100519140647.646C9EE9A9@mail.python.org> Author: georg.brandl Date: Wed May 19 16:06:47 2010 New Revision: 81333 Log: Merged revisions 77741 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r77741 | facundo.batista | 2010-01-25 07:15:01 +0100 (Mo, 25 Jan 2010) | 3 lines Added a note about Event.is_set() syntax being new to 2.6 ........ Modified: python/branches/release26-maint/ (props changed) python/branches/release26-maint/Doc/library/threading.rst Modified: python/branches/release26-maint/Doc/library/threading.rst ============================================================================== --- python/branches/release26-maint/Doc/library/threading.rst (original) +++ python/branches/release26-maint/Doc/library/threading.rst Wed May 19 16:06:47 2010 @@ -667,6 +667,9 @@ Return true if and only if the internal flag is true. + .. versionchanged:: 2.6 + The ``is_set()`` syntax is new. + .. method:: set() Set the internal flag to true. All threads waiting for it to become true From python-checkins at python.org Wed May 19 16:07:38 2010 From: python-checkins at python.org (georg.brandl) Date: Wed, 19 May 2010 16:07:38 +0200 (CEST) Subject: [Python-checkins] r81334 - in python/branches/release26-maint: Doc/library/language.rst Doc/library/python.rst Message-ID: <20100519140738.EC569EE9AF@mail.python.org> Author: georg.brandl Date: Wed May 19 16:07:38 2010 New Revision: 81334 Log: Merged revisions 77886 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r77886 | benjamin.peterson | 2010-01-31 19:09:34 +0100 (So, 31 Jan 2010) | 1 line move distutils.rst to different toc ........ Modified: python/branches/release26-maint/ (props changed) python/branches/release26-maint/Doc/library/language.rst python/branches/release26-maint/Doc/library/python.rst Modified: python/branches/release26-maint/Doc/library/language.rst ============================================================================== --- python/branches/release26-maint/Doc/library/language.rst (original) +++ python/branches/release26-maint/Doc/library/language.rst Wed May 19 16:07:38 2010 @@ -27,4 +27,3 @@ compileall.rst dis.rst pickletools.rst - distutils.rst Modified: python/branches/release26-maint/Doc/library/python.rst ============================================================================== --- python/branches/release26-maint/Doc/library/python.rst (original) +++ python/branches/release26-maint/Doc/library/python.rst Wed May 19 16:07:38 2010 @@ -27,3 +27,4 @@ site.rst user.rst fpectl.rst + distutils.rst From python-checkins at python.org Wed May 19 16:11:36 2010 From: python-checkins at python.org (georg.brandl) Date: Wed, 19 May 2010 16:11:36 +0200 (CEST) Subject: [Python-checkins] r81335 - python/branches/release26-maint Message-ID: <20100519141136.C5477ECFC@mail.python.org> Author: georg.brandl Date: Wed May 19 16:11:36 2010 New Revision: 81335 Log: Blocked revisions 77001,77030-77031,77037,77062,77066,77070-77071,77088,77096,77102,77104,77115-77116,77126-77127,77136,77139-77140,77160,77169,77178,77180,77185-77189,77212-77215,77218,77226-77227,77234,77241,77247,77249,77251-77252,77254,77257,77260,77262-77264,77275,77284,77286,77288,77290,77292-77293,77302,77310-77311,77313,77332,77337-77339,77362,77368-77369,77371,77374,77384,77386,77391,77400-77402,77410,77420-77423,77426,77428,77431,77438,77445,77448,77450-77451,77461,77463,77467,77469-77470,77472-77473,77475,77477-77478,77481-77484,77486,77490-77493,77497,77505,77510-77511,77513,77515,77519,77528,77530,77533,77548,77550,77566,77575,77578,77585,77588-77589,77599-77601,77607-77609,77614-77616,77663,77667,77672,77679,77691,77698,77704,77712-77715,77727,77739-77740,77749,77752,77755-77756,77759,77761,77763,77767,77771,77775,77784,77788-77789,77794,77796,77798,77806,77809,77811-77812,77815,77828,77841-77842,77850-77851,77866-77867,77871,77885,77889-77890,77902,77910-77914,77916,77919,77921-77922,77930,77936,77942,77944,77949,77952,77956-77957,77967,77969,77973,77979-77980,77983,77985-77986,77997,77999 via svnmerge ................ r77001 | brett.cannon | 2009-12-22 03:37:37 +0100 (Di, 22 Dez 2009) | 1 line Make a word plural. ................ r77030 | ronald.oussoren | 2009-12-24 14:30:42 +0100 (Do, 24 Dez 2009) | 5 lines An update to the script that's used to build the binary installer: don't install files in /usr/local by default. Users can still choose to install files into /usr/local, but by default we'll only install files in /Library/Framework/Python.framework and /Applications/Python X.Y/ ................ r77031 | ronald.oussoren | 2009-12-24 14:30:58 +0100 (Do, 24 Dez 2009) | 15 lines Issue #6834: replace the implementation for the 'python' and 'pythonw' executables on OSX. The previous implementation used execv(2) to run the real interpreter, which means that you cannot use the arch(1) tool to select the architecture you want to use for a universal build because that only affects the python/pythonw wrapper and not the actual interpreter. The new version uses posix_spawnv with a number of OSX-specific options that ensure that the real interpreter is started using the same CPU architecture as the wrapper, and that means that 'arch -ppc python' now actually works. I've also changed the way that the wrapper looks for the framework: it is now linked to the framework rather than hardcoding the framework path. This should make it easier to provide pythonw support in tools like virtualenv. ................ r77037 | ronald.oussoren | 2009-12-24 15:50:35 +0100 (Do, 24 Dez 2009) | 2 lines Unittests and news items for the patch in r77026. ................ r77062 | mark.dickinson | 2009-12-27 15:55:57 +0100 (So, 27 Dez 2009) | 2 lines Issue #1811: Improve accuracy and consistency of true division for integers. ................ r77066 | mark.dickinson | 2009-12-27 17:16:02 +0100 (So, 27 Dez 2009) | 1 line Use ldexp(q, exp) instead of q*2.**exp in true division test, to avoid bogus failures on platforms with broken pow (e.g., Ubuntu/ia64). ................ r77070 | amaury.forgeotdarc | 2009-12-27 21:06:44 +0100 (So, 27 Dez 2009) | 2 lines Fix a typo in comment ................ r77071 | mark.dickinson | 2009-12-27 22:31:50 +0100 (So, 27 Dez 2009) | 1 line Use a more idiomatic check in check_truediv. ................ r77088 | georg.brandl | 2009-12-28 09:34:58 +0100 (Mo, 28 Dez 2009) | 1 line #7033: add new API function PyErr_NewExceptionWithDoc, for easily giving new exceptions a docstring. ................ r77096 | benjamin.peterson | 2009-12-28 21:51:17 +0100 (Mo, 28 Dez 2009) | 1 line document new fix_callable behavior ................ r77102 | benjamin.peterson | 2009-12-29 00:50:41 +0100 (Di, 29 Dez 2009) | 50 lines Merged revisions 76871-76872,77093-77095,77097-77101 via svnmerge from svn+ssh://pythondev at svn.python.org/sandbox/trunk/2to3/lib2to3 ........ r76871 | benjamin.peterson | 2009-12-17 20:49:21 -0600 (Thu, 17 Dec 2009) | 1 line handle unencodable diffs gracefully #5093 ........ r76872 | benjamin.peterson | 2009-12-17 20:51:37 -0600 (Thu, 17 Dec 2009) | 1 line fix emacs header ........ r77093 | benjamin.peterson | 2009-12-28 14:43:32 -0600 (Mon, 28 Dec 2009) | 7 lines replace callable(x) with isinstance(x, collections.Callable) #7006 This is a more accurate translation than hasattr(x, '__call__') which failed in the case that somebody had put __call__ in the instance dictionary. Patch mostly by Joe Amenta. ........ r77094 | benjamin.peterson | 2009-12-28 14:45:13 -0600 (Mon, 28 Dec 2009) | 2 lines deuglify imports ........ r77095 | benjamin.peterson | 2009-12-28 14:49:23 -0600 (Mon, 28 Dec 2009) | 1 line remove unused flag ........ r77097 | benjamin.peterson | 2009-12-28 16:12:13 -0600 (Mon, 28 Dec 2009) | 2 lines clean up imports and whitespace ........ r77098 | benjamin.peterson | 2009-12-28 16:43:35 -0600 (Mon, 28 Dec 2009) | 1 line *** empty log message *** ........ r77099 | benjamin.peterson | 2009-12-28 16:45:10 -0600 (Mon, 28 Dec 2009) | 1 line revert unintended change ........ r77100 | benjamin.peterson | 2009-12-28 16:53:21 -0600 (Mon, 28 Dec 2009) | 1 line revert unintended changes ........ r77101 | benjamin.peterson | 2009-12-28 17:46:02 -0600 (Mon, 28 Dec 2009) | 1 line normalize whitespace ........ ................ r77104 | benjamin.peterson | 2009-12-29 01:09:33 +0100 (Di, 29 Dez 2009) | 1 line enable test_main.py ................ r77115 | andrew.kuchling | 2009-12-29 21:10:16 +0100 (Di, 29 Dez 2009) | 1 line Various additions ................ r77116 | mark.dickinson | 2009-12-29 21:51:24 +0100 (Di, 29 Dez 2009) | 6 lines Issue #7575: An overflow test for math.expm1 was failing on OS X 10.4/Intel, due to a defect in the platform's implementation of expm1. Since the issue is of low severity, and appears to be fixed in OS X 10.5 and 10.6, it doesn't seem worth working around, so I'm just weakening the relevant test so that it passes on 10.4. ................ r77126 | amaury.forgeotdarc | 2009-12-30 00:06:17 +0100 (Mi, 30 Dez 2009) | 2 lines #7579: Add docstrings to the msvcrt module ................ r77127 | andrew.kuchling | 2009-12-30 00:41:04 +0100 (Mi, 30 Dez 2009) | 1 line Add various items ................ r77136 | ezio.melotti | 2009-12-30 07:14:51 +0100 (Mi, 30 Dez 2009) | 1 line #5511: Added the ability to use ZipFile as a context manager. Patch by Brian Curtin. ................ r77139 | mark.dickinson | 2009-12-30 13:12:23 +0100 (Mi, 30 Dez 2009) | 3 lines Issue #7534: Fix handling of nans, infinities, and negative zero in ** operator, on IEEE 754 platforms. Thanks Marcos Donolo for original patch. ................ r77140 | mark.dickinson | 2009-12-30 13:22:49 +0100 (Mi, 30 Dez 2009) | 1 line Add Marcos Donolo for work on issue 7534 patch. ................ r77160 | benjamin.peterson | 2009-12-30 20:44:23 +0100 (Mi, 30 Dez 2009) | 9 lines Merged revisions 77158 via svnmerge from svn+ssh://pythondev at svn.python.org/sandbox/trunk/2to3/lib2to3 ........ r77158 | benjamin.peterson | 2009-12-30 13:41:03 -0600 (Wed, 30 Dec 2009) | 1 line clean up logging's global state after the test finishes ........ ................ r77169 | benjamin.peterson | 2009-12-31 04:17:18 +0100 (Do, 31 Dez 2009) | 2 lines add a --with-system-expat option to build pyexpat against the system's lib #7609 ................ r77178 | ezio.melotti | 2009-12-31 14:00:43 +0100 (Do, 31 Dez 2009) | 1 line cleanup and refactoring ................ r77180 | ezio.melotti | 2009-12-31 14:27:41 +0100 (Do, 31 Dez 2009) | 1 line indentation and further alignment with py3k ................ r77185 | andrew.kuchling | 2009-12-31 17:17:05 +0100 (Do, 31 Dez 2009) | 1 line Add some items ................ r77186 | benjamin.peterson | 2009-12-31 17:28:24 +0100 (Do, 31 Dez 2009) | 1 line update expat comment ................ r77187 | andrew.kuchling | 2009-12-31 17:38:53 +0100 (Do, 31 Dez 2009) | 1 line Add various items ................ r77188 | benjamin.peterson | 2009-12-31 17:49:37 +0100 (Do, 31 Dez 2009) | 1 line add another advancement ................ r77189 | mark.dickinson | 2009-12-31 21:48:04 +0100 (Do, 31 Dez 2009) | 1 line Add missing quotes. ................ r77212 | benjamin.peterson | 2010-01-01 16:16:29 +0100 (Fr, 01 Jan 2010) | 1 line use pkg-config to find the libffi headers when --with-system-ffi is used #6943 ................ r77213 | benjamin.peterson | 2010-01-01 16:18:38 +0100 (Fr, 01 Jan 2010) | 1 line add note ................ r77214 | benjamin.peterson | 2010-01-01 16:20:06 +0100 (Fr, 01 Jan 2010) | 1 line fix indentation ................ r77215 | benjamin.peterson | 2010-01-01 16:21:13 +0100 (Fr, 01 Jan 2010) | 1 line allow --with-dbmliborder to specify that no dbm modules will be built #6491 ................ r77218 | mark.dickinson | 2010-01-01 18:27:30 +0100 (Fr, 01 Jan 2010) | 5 lines Issue #5080: turn the DeprecationWarning from float arguments passed to integer PyArg_Parse* format codes into a TypeError. Add a DeprecationWarning for floats passed with the 'L' format code, which didn't previously have a warning. ................ r77226 | martin.v.loewis | 2010-01-02 10:25:21 +0100 (Sa, 02 Jan 2010) | 2 lines Update Windows build to sqlite 3.6.21. ................ r77227 | martin.v.loewis | 2010-01-02 10:53:18 +0100 (Sa, 02 Jan 2010) | 1 line Make script work with 2.5. ................ r77234 | mark.dickinson | 2010-01-02 15:45:40 +0100 (Sa, 02 Jan 2010) | 7 lines Refactor some longobject internals: PyLong_AsDouble and _PyLong_AsScaledDouble (the latter renamed to _PyLong_Frexp) now use the same core code. The exponent produced by _PyLong_Frexp now has type Py_ssize_t instead of the previously used int, and no longer needs scaling by PyLong_SHIFT. This frees the math module from having to know anything about the PyLong implementation. This closes issue #5576. ................ r77241 | antoine.pitrou | 2010-01-02 22:12:58 +0100 (Sa, 02 Jan 2010) | 4 lines Issue #7462: Implement the stringlib fast search algorithm for the `rfind`, `rindex`, `rsplit` and `rpartition` methods. Patch by Florent Xicluna. ................ r77247 | antoine.pitrou | 2010-01-02 22:47:10 +0100 (Sa, 02 Jan 2010) | 5 lines Add tests for issue #7458: str.rfind() would crash when called with an invalid start value. The offending code itself was removed as part of #7462. This patch by Victor Stinner. ................ r77249 | antoine.pitrou | 2010-01-02 22:53:44 +0100 (Sa, 02 Jan 2010) | 3 lines Remove silly conditional. ................ r77251 | gregory.p.smith | 2010-01-02 23:25:29 +0100 (Sa, 02 Jan 2010) | 6 lines Always compile the all versions of the hashlib algorithm modules when Python was compiled with Py_DEBUG defined. Otherwise the builtins are not compiled by default for many developers due to OpenSSL being present, making it easier for bugs to slip by. A future commit will add test code compare the behaviors of all implementations when they are all available. ................ r77252 | gregory.p.smith | 2010-01-02 23:28:48 +0100 (Sa, 02 Jan 2010) | 5 lines Issue #3745: Undo the requirement for new buffer API only objects to be passed to hashlib functions in python 2.x. The module now uses the 's*' for argument parsing which auto encodes unicode objects to the system default encoding for us. ................ r77254 | gregory.p.smith | 2010-01-02 23:42:50 +0100 (Sa, 02 Jan 2010) | 2 lines mention the r77252 change ................ r77257 | gregory.p.smith | 2010-01-03 01:19:04 +0100 (So, 03 Jan 2010) | 8 lines Import all implementations of the hash algorithms (OpenSSL & builtin) and run the test suite across all that are available. Warns about extension modules that could not be imported when python was compiled with Py_DEBUG. That warning could be made fatal but I didn't want to do that initially as I suspect non setup.py based build processes (windows, any others?) won't compile them all conditionally based on the Py_DEBUG setting today. ................ r77260 | gregory.p.smith | 2010-01-03 01:43:02 +0100 (So, 03 Jan 2010) | 2 lines make setup.py similar to py3k's when reporting on _hashlib as missing or not. ................ r77262 | andrew.kuchling | 2010-01-03 02:15:21 +0100 (So, 03 Jan 2010) | 1 line Add a few items ................ r77263 | gregory.p.smith | 2010-01-03 02:29:44 +0100 (So, 03 Jan 2010) | 4 lines Adds an optional source_address parameter to socket.create_connection(). For use by issue3972. ................ r77264 | gregory.p.smith | 2010-01-03 03:06:07 +0100 (So, 03 Jan 2010) | 5 lines issue3972: HTTPConnection and HTTPSConnection now support a source_address parameter. Also cleans up an annotation in the socket documentation. ................ r77275 | mark.dickinson | 2010-01-03 13:03:03 +0100 (So, 03 Jan 2010) | 1 line Make use of PyLong_AsLongAndOverflow in math_ldexp. ................ r77284 | gregory.p.smith | 2010-01-03 15:56:28 +0100 (So, 03 Jan 2010) | 2 lines remove an obsolete file that should've gone with r77252 ................ r77286 | gregory.p.smith | 2010-01-03 16:05:52 +0100 (So, 03 Jan 2010) | 2 lines Fix testSourceAddress to not test the host, it wasn't passing on some platforms. ................ r77288 | antoine.pitrou | 2010-01-03 23:29:56 +0100 (So, 03 Jan 2010) | 5 lines Issue #7471: Improve the performance of GzipFile's buffering mechanism, and make it implement the `io.BufferedIOBase` ABC to allow for further speedups by wrapping it in an `io.BufferedReader`. Patch by Nir Aides. ................ r77290 | antoine.pitrou | 2010-01-03 23:38:50 +0100 (So, 03 Jan 2010) | 3 lines Credit Nir Aides for r77288 ................ r77292 | benjamin.peterson | 2010-01-04 01:43:01 +0100 (Mo, 04 Jan 2010) | 1 line do correct lookup of the __complex__ method ................ r77293 | benjamin.peterson | 2010-01-04 02:00:47 +0100 (Mo, 04 Jan 2010) | 1 line factor out __complex__ lookup code to fix another case ................ r77302 | mark.dickinson | 2010-01-04 22:32:02 +0100 (Mo, 04 Jan 2010) | 1 line Fix typo in comment. ................ r77310 | antoine.pitrou | 2010-01-05 00:22:44 +0100 (Di, 05 Jan 2010) | 4 lines Issue #7092: Fix the DeprecationWarnings emitted by the standard library when using the -3 flag. Patch by Florent Xicluna. ................ r77311 | antoine.pitrou | 2010-01-05 00:28:16 +0100 (Di, 05 Jan 2010) | 3 lines Kill a couple of "<>" ................ r77313 | benjamin.peterson | 2010-01-05 01:04:19 +0100 (Di, 05 Jan 2010) | 1 line add a test about hashing array.array ................ r77332 | georg.brandl | 2010-01-06 19:02:16 +0100 (Mi, 06 Jan 2010) | 7 lines #5991: let completion for the "help" command include help topics. This also simplifies the Cmd.get_names() method implementation; it was written at a time where dir() didn't consider base class attributes. ................ r77337 | r.david.murray | 2010-01-07 04:09:08 +0100 (Do, 07 Jan 2010) | 3 lines Add -W to the 'basics', 'opt', and 'all' test runs so that we get verbose information if a failure happens. ................ r77338 | r.david.murray | 2010-01-07 05:04:28 +0100 (Do, 07 Jan 2010) | 2 lines Fix inadvertent checkin of debug line. ................ r77339 | mark.dickinson | 2010-01-07 10:28:29 +0100 (Do, 07 Jan 2010) | 1 line Eric Smith was missing fro m the issue 7117 whatsnew attribution. ................ r77362 | mark.dickinson | 2010-01-08 17:53:56 +0100 (Fr, 08 Jan 2010) | 1 line Backport some float repr tests that were missed in issue 7117. ................ r77368 | senthil.kumaran | 2010-01-08 19:41:40 +0100 (Fr, 08 Jan 2010) | 1 line Fixing - Issue7026 - RuntimeError: dictionary changed size during iteration. Patch by flox ................ r77369 | senthil.kumaran | 2010-01-08 20:04:16 +0100 (Fr, 08 Jan 2010) | 4 lines Reverting the Revision: 77368. I committed Flox's big patch for tests by mistake. ( It may come in for sure tough) ................ r77371 | senthil.kumaran | 2010-01-08 20:20:25 +0100 (Fr, 08 Jan 2010) | 3 lines Fix for Issue7026. For the Error - RuntimeError: dictionary changed size during iteration ................ r77374 | antoine.pitrou | 2010-01-08 20:39:04 +0100 (Fr, 08 Jan 2010) | 4 lines Remove obsolete warning filters in regrtest.py (from issue #7092 -- patch by Florent Xicluna). ................ r77384 | benjamin.peterson | 2010-01-09 17:34:06 +0100 (Sa, 09 Jan 2010) | 1 line bump version to 2.7a2 ................ r77386 | benjamin.peterson | 2010-01-09 18:30:31 +0100 (Sa, 09 Jan 2010) | 1 line post release version adjustment ................ r77391 | mark.dickinson | 2010-01-09 19:50:50 +0100 (Sa, 09 Jan 2010) | 3 lines Issue #7532: Add additional slicing test cases for new- and old-style classes. Patch by Florent Xicluna. ................ r77400 | alexandre.vassalotti | 2010-01-10 00:35:54 +0100 (So, 10 Jan 2010) | 2 lines Issue #2335: Backport set literals syntax from Python 3.x. ................ r77401 | brett.cannon | 2010-01-10 03:48:50 +0100 (So, 10 Jan 2010) | 3 lines Update the version # of Python-ast.c based on the backport of set literals from r77400. ................ r77402 | brett.cannon | 2010-01-10 03:56:19 +0100 (So, 10 Jan 2010) | 12 lines DeprecationWarning is now silent by default. This was originally suggested by Guido, discussed on the stdlib-sig mailing list, and given the OK by Guido directly to me. What this change essentially means is that Python has taken a policy of silencing warnings that are only of interest to developers by default. This should prevent users from seeing warnings which are triggered by an application being run against a new interpreter before the app developer has a chance to update their code. Closes issue #7319. Thanks to Antoine Pitrou, Ezio Melotti, and Brian Curtin for helping with the issue. ................ r77410 | mark.dickinson | 2010-01-10 14:06:31 +0100 (So, 10 Jan 2010) | 1 line Remove unused BCinfo fields and an unused macro. ................ r77420 | benjamin.peterson | 2010-01-10 21:42:03 +0100 (So, 10 Jan 2010) | 1 line fix test_popen when the path to python has spaces #7671 ................ r77421 | mark.dickinson | 2010-01-11 18:15:13 +0100 (Mo, 11 Jan 2010) | 1 line Change a variable type to avoid signed overflow; replace repeated '19999' constant by a define. ................ r77422 | alexandre.vassalotti | 2010-01-11 23:36:12 +0100 (Mo, 11 Jan 2010) | 2 lines Issue #2333: Backport set and dict comprehensions syntax. ................ r77423 | alexandre.vassalotti | 2010-01-11 23:46:43 +0100 (Mo, 11 Jan 2010) | 2 lines Update version information for AST changes in r77422. ................ r77426 | alexandre.vassalotti | 2010-01-12 00:13:49 +0100 (Di, 12 Jan 2010) | 2 lines Add missing NEWS entry for r77422. ................ r77428 | alexandre.vassalotti | 2010-01-12 00:17:10 +0100 (Di, 12 Jan 2010) | 2 lines Issue #1967: Backport dictionary views. ................ r77431 | tarek.ziade | 2010-01-12 00:41:32 +0100 (Di, 12 Jan 2010) | 1 line module cleanup ................ r77438 | alexandre.vassalotti | 2010-01-12 02:34:43 +0100 (Di, 12 Jan 2010) | 2 lines Fixed repr of dictionary views. ................ r77445 | alexandre.vassalotti | 2010-01-12 19:25:33 +0100 (Di, 12 Jan 2010) | 2 lines Added documentation for dictionary views fixer. ................ r77448 | antoine.pitrou | 2010-01-12 23:02:10 +0100 (Di, 12 Jan 2010) | 3 lines Issue #7654: enable additional bytes/bytearray tests. Patch by Florent Xicluna. ................ r77450 | mark.dickinson | 2010-01-12 23:23:56 +0100 (Di, 12 Jan 2010) | 4 lines Issue #7632: Fix a problem with _Py_dg_strtod that could lead to crashes in debug builds, for certain long numeric strings corresponding to subnormal values. ................ r77451 | mark.dickinson | 2010-01-12 23:55:51 +0100 (Di, 12 Jan 2010) | 2 lines Issue #7632: Fix a bug in dtoa.c that could lead to incorrectly-rounded results. ................ r77461 | antoine.pitrou | 2010-01-13 08:55:48 +0100 (Mi, 13 Jan 2010) | 5 lines Issue #7622: Improve the split(), rsplit(), splitlines() and replace() methods of bytes, bytearray and unicode objects by using a common implementation based on stringlib's fast search. Patch by Florent Xicluna. ................ r77463 | antoine.pitrou | 2010-01-13 09:55:20 +0100 (Mi, 13 Jan 2010) | 3 lines Fix Windows build (re r77461) ................ r77467 | antoine.pitrou | 2010-01-13 12:57:42 +0100 (Mi, 13 Jan 2010) | 3 lines Use `with` ................ r77469 | antoine.pitrou | 2010-01-13 14:43:37 +0100 (Mi, 13 Jan 2010) | 3 lines Test commit to try to diagnose failures of the IA-64 buildbot ................ r77470 | antoine.pitrou | 2010-01-13 15:01:26 +0100 (Mi, 13 Jan 2010) | 3 lines Sanitize bloom filter macros ................ r77472 | antoine.pitrou | 2010-01-13 15:32:10 +0100 (Mi, 13 Jan 2010) | 5 lines Issue #2846: Add support for gzip.GzipFile reading zero-padded files. Patch by Brian Curtin. ................ r77473 | antoine.pitrou | 2010-01-13 15:32:51 +0100 (Mi, 13 Jan 2010) | 3 lines Add ACKS entry for r77472. ................ r77475 | antoine.pitrou | 2010-01-13 16:02:13 +0100 (Mi, 13 Jan 2010) | 4 lines Issue #7625: Add more tests that bytearray methods return new objects, even if identical. Patch by Florent Xicluna (again). ................ r77477 | mark.dickinson | 2010-01-13 19:21:53 +0100 (Mi, 13 Jan 2010) | 1 line Add comments explaining the role of the bigcomp function in dtoa.c. ................ r77478 | mark.dickinson | 2010-01-13 20:02:37 +0100 (Mi, 13 Jan 2010) | 1 line Clarify that sulp expects a nonnegative input, but that +0.0 is fine. ................ r77481 | mark.dickinson | 2010-01-13 21:55:03 +0100 (Mi, 13 Jan 2010) | 1 line Simplify and annotate the bigcomp function, removing unused special cases. ................ r77482 | mark.dickinson | 2010-01-13 23:15:53 +0100 (Mi, 13 Jan 2010) | 1 line Fix buggy comparison: LHS of comparison was being treated as unsigned. ................ r77483 | mark.dickinson | 2010-01-13 23:20:10 +0100 (Mi, 13 Jan 2010) | 1 line More dtoa.c cleanup; remove the need for bc.dplen, bc.dp0 and bc.dp1. ................ r77484 | skip.montanaro | 2010-01-14 02:12:34 +0100 (Do, 14 Jan 2010) | 4 lines Update PyEval_EvalFrame to PyEval_EvalFrameEx. This looks to have been done partially before. Also add a comment describing how this might have to work with different versions of the interpreter. ................ r77486 | benjamin.peterson | 2010-01-14 03:40:10 +0100 (Do, 14 Jan 2010) | 1 line use more robust quoting ................ r77490 | mark.dickinson | 2010-01-14 14:02:36 +0100 (Do, 14 Jan 2010) | 1 line Fix off-by-one error introduced in r77483. I have a test for this, but it currently fails due to a different dtoa.c bug; I'll add the test once that bug is fixed. ................ r77491 | mark.dickinson | 2010-01-14 14:14:49 +0100 (Do, 14 Jan 2010) | 1 line Issue 7632: fix a dtoa.c bug (bug 6) causing incorrect rounding. Tests to follow. ................ r77492 | mark.dickinson | 2010-01-14 15:40:20 +0100 (Do, 14 Jan 2010) | 1 line Issue 7632: fix incorrect rounding for long input strings with values very close to a power of 2. (See Bug 4 in the tracker discussion.) ................ r77493 | mark.dickinson | 2010-01-14 16:22:33 +0100 (Do, 14 Jan 2010) | 1 line Issue #7632: add tests for bugs fixed so far. ................ r77497 | antoine.pitrou | 2010-01-14 17:27:09 +0100 (Do, 14 Jan 2010) | 5 lines Issue #7703: Add support for the new buffer API to functions of the binascii module. Backported from py3k by Florent Xicluna, with some additional tests. ................ r77505 | brett.cannon | 2010-01-14 21:00:28 +0100 (Do, 14 Jan 2010) | 7 lines The silencing of DeprecationWarning was not taking -3 into consideration. Since Py3K warnings are DeprecationWarning by default this was causing -3 to essentially be a no-op. Now DeprecationWarning is only silenced if -3 is not used. Closes issue #7700. Thanks Ezio Melotti and Florent Xicluna for patch help. ................ r77510 | brett.cannon | 2010-01-15 02:31:45 +0100 (Fr, 15 Jan 2010) | 1 line Remove C++/C99-style comments. ................ r77511 | benjamin.peterson | 2010-01-15 03:26:07 +0100 (Fr, 15 Jan 2010) | 1 line try to fix for windows ................ r77513 | vinay.sajip | 2010-01-16 00:27:05 +0100 (Sa, 16 Jan 2010) | 1 line Fixed issue-number mistake in NEWS update. ................ r77515 | sean.reifschneider | 2010-01-16 05:27:58 +0100 (Sa, 16 Jan 2010) | 1 line issue5063: Fixes for building RPM on CentOS plus misc .spec file enhancements. ................ r77519 | mark.dickinson | 2010-01-16 11:44:00 +0100 (Sa, 16 Jan 2010) | 5 lines Issue #7632: Fix a serious wrong output bug for string -> float conversion. Also remove some now unused variables, and add comments clarifying the possible outputs of the parsing section of _Py_dg_strtod. Thanks Eric Smith for reviewing. ................ r77528 | antoine.pitrou | 2010-01-16 18:45:56 +0100 (Sa, 16 Jan 2010) | 4 lines Followup to #7703: a2b_hqx() didn't follow the new buffer API (neither in trunk nor in py3k). Patch by Florent Xicluna as well as additional tests. ................ r77530 | mark.dickinson | 2010-01-16 18:57:49 +0100 (Sa, 16 Jan 2010) | 3 lines Issue #7632: Fix one more case of incorrect rounding for str -> float conversion (see bug 5 in the issue tracker). ................ r77533 | mark.dickinson | 2010-01-16 19:06:17 +0100 (Sa, 16 Jan 2010) | 1 line Fix multiple uses of variable 'L' in _Py_dg_strtod, where one use requires an unsigned long and the other a signed long. See also r77421. ................ r77548 | ezio.melotti | 2010-01-16 20:36:42 +0100 (Sa, 16 Jan 2010) | 1 line remove wrong markup ................ r77550 | mark.dickinson | 2010-01-16 21:33:02 +0100 (Sa, 16 Jan 2010) | 1 line Add better error reporting for MemoryErrors caused by str->float conversions. ................ r77566 | mark.dickinson | 2010-01-17 12:10:03 +0100 (So, 17 Jan 2010) | 1 line Increase number of strtod tests slightly, to make it more likely that a memory leak is detected. ................ r77575 | ronald.oussoren | 2010-01-17 13:38:11 +0100 (So, 17 Jan 2010) | 3 lines Add text to Mac/README to warn about non-universal libraries when building a universal Python. Based on issue7679. ................ r77578 | mark.dickinson | 2010-01-17 14:37:57 +0100 (So, 17 Jan 2010) | 2 lines Issue #7632: Fix a memory leak in _Py_dg_strtod. ................ r77585 | ronald.oussoren | 2010-01-17 17:25:57 +0100 (So, 17 Jan 2010) | 12 lines - Issue #7658: Ensure that the new pythonw executable works on OSX 10.4 - Issue #7714: Use ``gcc -dumpversion`` to detect the version of GCC on MacOSX. - Make configure look for util.h as well as libutil.h. The former is the header file that on OSX contains the defition of openpty. (Needed to compile for OSX 10.4 on OSX 10.6) - Use the correct definition of CC to compile the pythonw executable ................ r77588 | ronald.oussoren | 2010-01-17 20:32:00 +0100 (So, 17 Jan 2010) | 2 lines Explicitly use /usr/bin/arch on OSX, fixes issue 7715 ................ r77589 | mark.dickinson | 2010-01-17 21:57:56 +0100 (So, 17 Jan 2010) | 7 lines Issue #7632: When Py_USING_MEMORY_DEBUGGER is defined, disable the private memory allocation scheme in dtoa.c, along with a piece of code that caches powers of 5 for future use. This makes it easier to detect dtoa.c memory leaks with Valgrind or similar tools. Patch by Stefan Krah. ................ r77599 | antoine.pitrou | 2010-01-18 22:04:00 +0100 (Mo, 18 Jan 2010) | 3 lines Add iobench to the Tools directory (see December python-dev discussion) ................ r77600 | antoine.pitrou | 2010-01-18 22:10:31 +0100 (Mo, 18 Jan 2010) | 3 lines Add ccbench to the Tools directory ................ r77601 | antoine.pitrou | 2010-01-18 22:15:21 +0100 (Mo, 18 Jan 2010) | 3 lines Add a NEWS entry for r77599 and r77600. ................ r77607 | gregory.p.smith | 2010-01-19 09:01:00 +0100 (Di, 19 Jan 2010) | 6 lines Add a pydebug mode only debug print to help debug the errors in http://www.python.org/dev/buildbot/all/builders/x86%20gentoo%20trunk/builds/5700/ Will be removed shortly. ................ r77608 | gregory.p.smith | 2010-01-19 09:19:03 +0100 (Di, 19 Jan 2010) | 6 lines Do not compile stubs for the sha2 series hashes in the openssl hashlib module when the openssl version is too old to support them. That leads both compiled code bloat and to unittests attempting to test implementations that don't exist for comparison purposes on such platforms. ................ r77609 | gregory.p.smith | 2010-01-19 09:25:26 +0100 (Di, 19 Jan 2010) | 2 lines Revert debugprint code in r77607. ................ r77614 | mark.dickinson | 2010-01-20 18:36:31 +0100 (Mi, 20 Jan 2010) | 5 lines Various dtoa.c cleanups. 1. Despagghetify _Py_dg_strtod parsing code and exit points. 2. Simplify bigcomp comparison loop. 3. Don't set ERANGE on _Py_dg_strtod underflow (it was set inconsistently anyway). 4. Remove unused dsign field from BCinfo struct. ................ r77615 | mark.dickinson | 2010-01-20 19:02:41 +0100 (Mi, 20 Jan 2010) | 1 line Don't try to put a value into a NULL pointer. ................ r77616 | mark.dickinson | 2010-01-20 22:23:25 +0100 (Mi, 20 Jan 2010) | 1 line Additional explanatory comments for _Py_dg_strtod. ................ r77663 | mark.dickinson | 2010-01-21 18:02:53 +0100 (Do, 21 Jan 2010) | 1 line Additional testcases for strtod. ................ r77667 | mark.dickinson | 2010-01-21 19:32:27 +0100 (Do, 21 Jan 2010) | 1 line Add two more test_strtod test values. ................ r77672 | mark.dickinson | 2010-01-21 20:58:41 +0100 (Do, 21 Jan 2010) | 1 line Use // for floor division. ................ r77679 | matthias.klose | 2010-01-22 01:34:48 +0100 (Fr, 22 Jan 2010) | 2 lines - Mention CVE-2009-3720 for change in r74429. ................ r77691 | mark.dickinson | 2010-01-22 17:18:09 +0100 (Fr, 22 Jan 2010) | 1 line Correct typo in comment. ................ r77698 | mark.dickinson | 2010-01-22 18:04:07 +0100 (Fr, 22 Jan 2010) | 3 lines Issue #7743: Fix a potential incorrect rounding bug in dtoa.c (2nd bug in issue 7743). ................ r77704 | tarek.ziade | 2010-01-23 10:23:15 +0100 (Sa, 23 Jan 2010) | 1 line taking sysconfig out of distutils ................ r77712 | tarek.ziade | 2010-01-23 18:52:57 +0100 (Sa, 23 Jan 2010) | 1 line fixed the 64bits tests for get_platform() - mac osx ................ r77713 | mark.dickinson | 2010-01-23 21:48:56 +0100 (Sa, 23 Jan 2010) | 3 lines Issue #7743: Add checks for zero inputs to the lshift and mult functions; this fixes the first bug described in issue #7743. ................ r77714 | mark.dickinson | 2010-01-23 22:25:53 +0100 (Sa, 23 Jan 2010) | 1 line dtoa.c fix from upstream that fixes incorrectly rounded results for certain subnormals that are also halfway cases. ................ r77715 | ezio.melotti | 2010-01-24 00:04:36 +0100 (So, 24 Jan 2010) | 1 line use assert[Not]In where appropriate ................ r77727 | ezio.melotti | 2010-01-24 17:58:36 +0100 (So, 24 Jan 2010) | 1 line use assert[Not]IsInstance where appropriate ................ r77739 | benjamin.peterson | 2010-01-25 04:52:52 +0100 (Mo, 25 Jan 2010) | 1 line mention from_float() in error message ................ r77740 | benjamin.peterson | 2010-01-25 04:58:21 +0100 (Mo, 25 Jan 2010) | 1 line compare types with is not == ................ r77749 | ezio.melotti | 2010-01-25 13:37:02 +0100 (Mo, 25 Jan 2010) | 1 line Add a news entry for the functions verify and vereq that have been removed in r77729 and r77731 ................ r77752 | tarek.ziade | 2010-01-26 00:19:56 +0100 (Di, 26 Jan 2010) | 1 line switched the call order so this call works without suffering from issue #7774 ................ r77755 | ezio.melotti | 2010-01-26 16:57:21 +0100 (Di, 26 Jan 2010) | 1 line #7092: fix DeprecationWarnings for json when the tests are run with -3 -Wd. ................ r77756 | tarek.ziade | 2010-01-26 18:20:37 +0100 (Di, 26 Jan 2010) | 1 line fixed bdist_msi imports and added a test module for distutils.command.bdist_msi ................ r77759 | tarek.ziade | 2010-01-26 22:21:54 +0100 (Di, 26 Jan 2010) | 1 line reintroduced the names in Distutils for APIs that were relocated ................ r77761 | tarek.ziade | 2010-01-26 23:46:15 +0100 (Di, 26 Jan 2010) | 1 line added local get_platform/set_platform APIs in distutils.sysconfig ................ r77763 | eric.smith | 2010-01-27 01:28:29 +0100 (Mi, 27 Jan 2010) | 1 line Issue #7766: Change sys.getwindowsversion() return value to a named tuple and add the additional members returned in an OSVERSIONINFOEX structure. The new members are service_pack_major, service_pack_minor, suite_mask, and product_type. ................ r77767 | eric.smith | 2010-01-27 01:55:16 +0100 (Mi, 27 Jan 2010) | 1 line Fix type on getwindowsversion documentation. Thanks Taggnostr. ................ r77771 | eric.smith | 2010-01-27 01:58:43 +0100 (Mi, 27 Jan 2010) | 1 line Removed unneeded test. ................ r77775 | eric.smith | 2010-01-27 02:21:15 +0100 (Mi, 27 Jan 2010) | 1 line Switch to test_support.get_attribute. ................ r77784 | eric.smith | 2010-01-27 03:06:25 +0100 (Mi, 27 Jan 2010) | 1 line Added named (but not numbered) attributes to sys.getwindowsversion() test. ................ r77788 | benjamin.peterson | 2010-01-27 03:15:28 +0100 (Mi, 27 Jan 2010) | 1 line for UserDict to be compatible with abcs, it must subclass object ................ r77789 | benjamin.peterson | 2010-01-27 03:16:42 +0100 (Mi, 27 Jan 2010) | 1 line raise a clear TypeError when trying to register a non-class ................ r77794 | jesse.noller | 2010-01-27 04:05:57 +0100 (Mi, 27 Jan 2010) | 1 line Issue #6963: Added maxtasksperchild argument to multiprocessing.Pool ................ r77796 | ezio.melotti | 2010-01-27 21:25:11 +0100 (Mi, 27 Jan 2010) | 1 line #7765: typos ................ r77798 | antoine.pitrou | 2010-01-27 21:59:50 +0100 (Mi, 27 Jan 2010) | 8 lines Issue #7610: Reworked implementation of the internal :class:`zipfile.ZipExtFile` class used to represent files stored inside an archive. The new implementation is significantly faster and can be wrapped in a :class:`io.BufferedReader` object for more speedups. It also solves an issue where interleaved calls to `read()` and `readline()` give wrong results. Patch by Nir Aides. ................ r77806 | benjamin.peterson | 2010-01-28 02:24:46 +0100 (Do, 28 Jan 2010) | 1 line add compat note ................ r77809 | ezio.melotti | 2010-01-28 02:41:30 +0100 (Do, 28 Jan 2010) | 1 line avoid to use zlib when the compress type is not ZIP_DEFLATED ................ r77811 | benjamin.peterson | 2010-01-28 03:15:02 +0100 (Do, 28 Jan 2010) | 1 line an -> a ................ r77812 | benjamin.peterson | 2010-01-28 03:18:25 +0100 (Do, 28 Jan 2010) | 1 line avoid a py3k warning from __hash__ ................ r77815 | r.david.murray | 2010-01-28 22:16:33 +0100 (Do, 28 Jan 2010) | 3 lines Change error report when the object passed to suite.addTest is not callable to include the repr of the invalid object. ................ r77828 | r.david.murray | 2010-01-29 20:35:39 +0100 (Fr, 29 Jan 2010) | 2 lines Fix typo in assertSequenceEqual docstring. ................ r77841 | ezio.melotti | 2010-01-30 08:22:54 +0100 (Sa, 30 Jan 2010) | 1 line #7092: silence py3k warnings for deprecated modules ................ r77842 | mark.dickinson | 2010-01-30 11:08:33 +0100 (Sa, 30 Jan 2010) | 4 lines Issue #7767: Add new C-API function PyLong_AsLongLongAndOverflow, a long long variant of PyLong_AsLongAndOverflow. Patch by Case Van Horsen. ................ r77850 | ezio.melotti | 2010-01-30 14:08:54 +0100 (Sa, 30 Jan 2010) | 1 line Relocate a couple of stars and remove redundant backticks ................ r77851 | ezio.melotti | 2010-01-30 14:27:05 +0100 (Sa, 30 Jan 2010) | 1 line Use the correct markup for args ................ r77866 | benjamin.peterson | 2010-01-31 00:26:05 +0100 (So, 31 Jan 2010) | 1 line move test outside WITH_THREAD section ................ r77867 | benjamin.peterson | 2010-01-31 00:28:38 +0100 (So, 31 Jan 2010) | 1 line be robust against test being run over and over (such as -R) ................ r77871 | ezio.melotti | 2010-01-31 12:46:54 +0100 (So, 31 Jan 2010) | 1 line #7092: silence more -3 and -Wd warnings ................ r77885 | benjamin.peterson | 2010-01-31 19:02:35 +0100 (So, 31 Jan 2010) | 1 line fix windows buildbot ................ r77889 | michael.foord | 2010-01-31 20:59:26 +0100 (So, 31 Jan 2010) | 1 line Minor modification to unittest documentation. ................ r77890 | antoine.pitrou | 2010-01-31 23:26:04 +0100 (So, 31 Jan 2010) | 7 lines - Issue #6939: Fix file I/O objects in the `io` module to keep the original file position when calling `truncate()`. It would previously change the file position to the given argument, which goes against the tradition of ftruncate() and other truncation APIs. Patch by Pascal Chambon. ................ r77902 | andrew.kuchling | 2010-02-01 03:04:26 +0100 (Mo, 01 Feb 2010) | 1 line Add various items ................ r77910 | ezio.melotti | 2010-02-02 09:37:35 +0100 (Di, 02 Feb 2010) | 1 line #7092: silence py3k warnings for bsddb. Patch by Florent Xicluna. ................ r77911 | ezio.melotti | 2010-02-02 16:12:42 +0100 (Di, 02 Feb 2010) | 1 line Silence a couple of -3 warnings ................ r77912 | ezio.melotti | 2010-02-02 16:57:45 +0100 (Di, 02 Feb 2010) | 1 line Fix idioms and a couple of py3k warnings. Patch by Florent Xicluna. ................ r77913 | ezio.melotti | 2010-02-02 18:34:37 +0100 (Di, 02 Feb 2010) | 1 line #7092: Silence py3k warnings in test_exceptions and test_pep352. Patch by Florent Xicluna. ................ r77914 | tarek.ziade | 2010-02-02 23:27:58 +0100 (Di, 02 Feb 2010) | 1 line first version of the sysconfig module documentation ................ r77916 | antoine.pitrou | 2010-02-02 23:36:17 +0100 (Di, 02 Feb 2010) | 4 lines Issue #7385: Fix a crash in `MemoryView_FromObject` when `PyObject_GetBuffer` fails. Patch by Florent Xicluna. ................ r77919 | tarek.ziade | 2010-02-02 23:50:23 +0100 (Di, 02 Feb 2010) | 1 line module reorganization + missing doctests ................ r77921 | tarek.ziade | 2010-02-02 23:54:28 +0100 (Di, 02 Feb 2010) | 1 line sysconfig.get_scheme_names now returns a sorted tuple ................ r77922 | tarek.ziade | 2010-02-02 23:55:00 +0100 (Di, 02 Feb 2010) | 1 line fixed a typo on distutils.sysconfig. thanks arfever ................ r77930 | tarek.ziade | 2010-02-03 00:39:40 +0100 (Mi, 03 Feb 2010) | 1 line added a note in the whatsnew file for sysconfig ................ r77936 | andrew.kuchling | 2010-02-03 03:19:14 +0100 (Mi, 03 Feb 2010) | 1 line Add various items ................ r77942 | ezio.melotti | 2010-02-03 06:37:26 +0100 (Mi, 03 Feb 2010) | 1 line #7092: Silence more py3k warnings. Patch by Florent Xicluna. ................ r77944 | eric.smith | 2010-02-03 15:17:50 +0100 (Mi, 03 Feb 2010) | 1 line Corrected list of attributes exposed by sys.getwindowsversion. ................ r77949 | tarek.ziade | 2010-02-03 16:38:12 +0100 (Mi, 03 Feb 2010) | 1 line leaving global attributes for backward compat ................ r77952 | mark.dickinson | 2010-02-03 17:50:14 +0100 (Mi, 03 Feb 2010) | 1 line Fix test_inspect.py data to match recent change to inspect_fodder.py (r77942). ................ r77956 | brett.cannon | 2010-02-03 23:11:54 +0100 (Mi, 03 Feb 2010) | 1 line Update a docstring to suggest using importlib.import_module instead of calling __import__ directly. ................ r77957 | brett.cannon | 2010-02-03 23:13:44 +0100 (Mi, 03 Feb 2010) | 1 line Fix a typo in a docstring introduced in r77956. ................ r77967 | vinay.sajip | 2010-02-04 19:48:53 +0100 (Do, 04 Feb 2010) | 1 line Logging: Implemented PEP 391. ................ r77969 | vinay.sajip | 2010-02-04 21:18:28 +0100 (Do, 04 Feb 2010) | 1 line Removed spurious print statement. ................ r77973 | vinay.sajip | 2010-02-04 21:23:45 +0100 (Do, 04 Feb 2010) | 1 line Issue #7851: logging: clarification on logging configuration files. ................ r77979 | vinay.sajip | 2010-02-04 22:40:56 +0100 (Do, 04 Feb 2010) | 1 line Added unit test for cfg:// resolution. ................ r77980 | benjamin.peterson | 2010-02-05 02:53:27 +0100 (Fr, 05 Feb 2010) | 1 line add a test for #7853; the exception must be normalized for with ................ r77983 | benjamin.peterson | 2010-02-05 03:12:14 +0100 (Fr, 05 Feb 2010) | 9 lines normalize exceptions passed to the __exit__ method #7853 In Python 2.x, exceptions in finally blocks are not normalized. Since with statements are implemented using finally blocks, ceval.c had to be tweaked to distinguish between with finally blocks and normal ones. A test for the finalization of generators containing with statements was also added. ................ r77985 | vinay.sajip | 2010-02-05 15:52:05 +0100 (Fr, 05 Feb 2010) | 1 line Issue #7857: test_logging: listener test now uses find_unused_port(). ................ r77986 | vinay.sajip | 2010-02-05 16:40:20 +0100 (Fr, 05 Feb 2010) | 1 line Issue #7857: test_logging: listener tests disabled for now. ................ r77997 | michael.foord | 2010-02-05 21:52:14 +0100 (Fr, 05 Feb 2010) | 1 line Closes issue 7030. ................ r77999 | michael.foord | 2010-02-05 22:07:38 +0100 (Fr, 05 Feb 2010) | 1 line Example of using assertRaises as a context manager in the unittest documentation. ................ Modified: python/branches/release26-maint/ (props changed) From python-checkins at python.org Wed May 19 16:11:56 2010 From: python-checkins at python.org (georg.brandl) Date: Wed, 19 May 2010 16:11:56 +0200 (CEST) Subject: [Python-checkins] r81336 - in python/branches/release26-maint: Doc/library/subprocess.rst Message-ID: <20100519141156.1D2FFEE9BE@mail.python.org> Author: georg.brandl Date: Wed May 19 16:11:55 2010 New Revision: 81336 Log: Merged revisions 78206 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r78206 | r.david.murray | 2010-02-16 18:55:26 +0100 (Di, 16 Feb 2010) | 3 lines Make the references to Popen in the description of Call and check_call into links. ........ Modified: python/branches/release26-maint/ (props changed) python/branches/release26-maint/Doc/library/subprocess.rst Modified: python/branches/release26-maint/Doc/library/subprocess.rst ============================================================================== --- python/branches/release26-maint/Doc/library/subprocess.rst (original) +++ python/branches/release26-maint/Doc/library/subprocess.rst Wed May 19 16:11:55 2010 @@ -186,7 +186,7 @@ Run command with arguments. Wait for command to complete, then return the :attr:`returncode` attribute. - The arguments are the same as for the Popen constructor. Example:: + The arguments are the same as for the :class:`Popen` constructor. Example:: >>> retcode = subprocess.call(["ls", "-l"]) @@ -198,7 +198,7 @@ :exc:`CalledProcessError` object will have the return code in the :attr:`returncode` attribute. - The arguments are the same as for the Popen constructor. Example:: + The arguments are the same as for the :class:`Popen` constructor. Example:: >>> subprocess.check_call(["ls", "-l"]) 0 From python-checkins at python.org Wed May 19 16:12:57 2010 From: python-checkins at python.org (georg.brandl) Date: Wed, 19 May 2010 16:12:57 +0200 (CEST) Subject: [Python-checkins] r81337 - in python/branches/release26-maint: Doc/library/random.rst Doc/library/struct.rst Message-ID: <20100519141257.53888FB07@mail.python.org> Author: georg.brandl Date: Wed May 19 16:12:57 2010 New Revision: 81337 Log: Merged revisions 78297,78308 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r78297 | andrew.kuchling | 2010-02-22 03:29:10 +0100 (Mo, 22 Feb 2010) | 1 line #7076: mention SystemRandom class near start of the module docs; reword change description for clarity. Noted by Shawn Ligocki. ........ r78308 | andrew.kuchling | 2010-02-22 16:13:17 +0100 (Mo, 22 Feb 2010) | 2 lines #6414: clarify description of processor endianness. Text by Alexey Shamrin; I changed 'DEC Alpha' to the more relevant 'Intel Itanium'. ........ Modified: python/branches/release26-maint/ (props changed) python/branches/release26-maint/Doc/library/random.rst python/branches/release26-maint/Doc/library/struct.rst Modified: python/branches/release26-maint/Doc/library/random.rst ============================================================================== --- python/branches/release26-maint/Doc/library/random.rst (original) +++ python/branches/release26-maint/Doc/library/random.rst Wed May 19 16:12:57 2010 @@ -52,7 +52,11 @@ recent variant that repairs these flaws. .. versionchanged:: 2.3 - Substituted MersenneTwister for Wichmann-Hill. + MersenneTwister replaced Wichmann-Hill as the default generator. + +The :mod:`random` module also provides the :class:`SystemRandom` class which +uses the system function :func:`os.urandom` to generate random numbers +from sources provided by the operating system. Bookkeeping functions: Modified: python/branches/release26-maint/Doc/library/struct.rst ============================================================================== --- python/branches/release26-maint/Doc/library/struct.rst (original) +++ python/branches/release26-maint/Doc/library/struct.rst Wed May 19 16:12:57 2010 @@ -187,9 +187,11 @@ If the first character is not one of these, ``'@'`` is assumed. -Native byte order is big-endian or little-endian, depending on the host system. -For example, Motorola and Sun processors are big-endian; Intel and DEC -processors are little-endian. +Native byte order is big-endian or little-endian, depending on the host +system. For example, Intel x86 and AMD64 (x86-64) are little-endian; +Motorola 68000 and PowerPC G5 are big-endian; ARM and Intel Itanium feature +switchable endianness (bi-endian). Use ``sys.byteorder`` to check the +endianness of your system. Native size and alignment are determined using the C compiler's ``sizeof`` expression. This is always combined with native byte order. From python-checkins at python.org Wed May 19 16:14:06 2010 From: python-checkins at python.org (georg.brandl) Date: Wed, 19 May 2010 16:14:06 +0200 (CEST) Subject: [Python-checkins] r81338 - in python/branches/release26-maint: Doc/library/multiprocessing.rst Message-ID: <20100519141406.12A3DEE994@mail.python.org> Author: georg.brandl Date: Wed May 19 16:14:05 2010 New Revision: 81338 Log: Merged revisions 78328 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r78328 | jack.diederich | 2010-02-22 19:17:16 +0100 (Mo, 22 Feb 2010) | 1 line fixes issue #7530, serve_forever() ........ Modified: python/branches/release26-maint/ (props changed) python/branches/release26-maint/Doc/library/multiprocessing.rst Modified: python/branches/release26-maint/Doc/library/multiprocessing.rst ============================================================================== --- python/branches/release26-maint/Doc/library/multiprocessing.rst (original) +++ python/branches/release26-maint/Doc/library/multiprocessing.rst Wed May 19 16:14:05 2010 @@ -1124,7 +1124,7 @@ Create a BaseManager object. - Once created one should call :meth:`start` or :meth:`serve_forever` to ensure + Once created one should call :meth:`start` or ```get_server().serve_forever()`` to ensure that the manager object refers to a started manager process. *address* is the address on which the manager process listens for new @@ -1139,10 +1139,6 @@ Start a subprocess to start the manager. - .. method:: serve_forever() - - Run the server in the current process. - .. method:: get_server() Returns a :class:`Server` object which represents the actual server under From python-checkins at python.org Wed May 19 16:14:28 2010 From: python-checkins at python.org (georg.brandl) Date: Wed, 19 May 2010 16:14:28 +0200 (CEST) Subject: [Python-checkins] r81339 - in python/branches/release26-maint: Doc/library/multiprocessing.rst Message-ID: <20100519141428.C7A03C933@mail.python.org> Author: georg.brandl Date: Wed May 19 16:14:28 2010 New Revision: 81339 Log: Merged revisions 78378 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r78378 | jack.diederich | 2010-02-23 18:23:30 +0100 (Di, 23 Feb 2010) | 1 line fixup markup error ........ Modified: python/branches/release26-maint/ (props changed) python/branches/release26-maint/Doc/library/multiprocessing.rst Modified: python/branches/release26-maint/Doc/library/multiprocessing.rst ============================================================================== --- python/branches/release26-maint/Doc/library/multiprocessing.rst (original) +++ python/branches/release26-maint/Doc/library/multiprocessing.rst Wed May 19 16:14:28 2010 @@ -1124,7 +1124,7 @@ Create a BaseManager object. - Once created one should call :meth:`start` or ```get_server().serve_forever()`` to ensure + Once created one should call :meth:`start` or ``get_server().serve_forever()`` to ensure that the manager object refers to a started manager process. *address* is the address on which the manager process listens for new From python-checkins at python.org Wed May 19 16:14:45 2010 From: python-checkins at python.org (georg.brandl) Date: Wed, 19 May 2010 16:14:45 +0200 (CEST) Subject: [Python-checkins] r81340 - in python/branches/release26-maint: Doc/library/asyncore.rst Message-ID: <20100519141445.26350EBE4@mail.python.org> Author: georg.brandl Date: Wed May 19 16:14:45 2010 New Revision: 81340 Log: Merged revisions 78415 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r78415 | dirkjan.ochtman | 2010-02-24 05:00:52 +0100 (Mi, 24 Feb 2010) | 1 line Issue #7733: add explicit reference in asyncore docs. ........ Modified: python/branches/release26-maint/ (props changed) python/branches/release26-maint/Doc/library/asyncore.rst Modified: python/branches/release26-maint/Doc/library/asyncore.rst ============================================================================== --- python/branches/release26-maint/Doc/library/asyncore.rst (original) +++ python/branches/release26-maint/Doc/library/asyncore.rst Wed May 19 16:14:45 2010 @@ -202,7 +202,8 @@ .. method:: bind(address) Bind the socket to *address*. The socket must not already be bound. (The - format of *address* depends on the address family --- see above.) To mark + format of *address* depends on the address family --- refer to the + :mod:`socket` documentation for more information.) To mark the socket as re-usable (setting the :const:`SO_REUSEADDR` option), call the :class:`dispatcher` object's :meth:`set_reuse_addr` method. From python-checkins at python.org Wed May 19 16:15:15 2010 From: python-checkins at python.org (georg.brandl) Date: Wed, 19 May 2010 16:15:15 +0200 (CEST) Subject: [Python-checkins] r81341 - in python/branches/release26-maint: Doc/library/queue.rst Message-ID: <20100519141515.E66FFFCC2@mail.python.org> Author: georg.brandl Date: Wed May 19 16:15:15 2010 New Revision: 81341 Log: Merged revisions 78463 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r78463 | andrew.kuchling | 2010-02-26 14:22:50 +0100 (Fr, 26 Feb 2010) | 1 line #7407: specify default maxsize value; patch by Floris Bruynooghe ........ Modified: python/branches/release26-maint/ (props changed) python/branches/release26-maint/Doc/library/queue.rst Modified: python/branches/release26-maint/Doc/library/queue.rst ============================================================================== --- python/branches/release26-maint/Doc/library/queue.rst (original) +++ python/branches/release26-maint/Doc/library/queue.rst Wed May 19 16:15:15 2010 @@ -26,14 +26,14 @@ The :mod:`Queue` module defines the following classes and exceptions: -.. class:: Queue(maxsize) +.. class:: Queue(maxsize=0) Constructor for a FIFO queue. *maxsize* is an integer that sets the upperbound limit on the number of items that can be placed in the queue. Insertion will block once this size has been reached, until queue items are consumed. If *maxsize* is less than or equal to zero, the queue size is infinite. -.. class:: LifoQueue(maxsize) +.. class:: LifoQueue(maxsize=0) Constructor for a LIFO queue. *maxsize* is an integer that sets the upperbound limit on the number of items that can be placed in the queue. Insertion will @@ -42,7 +42,7 @@ .. versionadded:: 2.6 -.. class:: PriorityQueue(maxsize) +.. class:: PriorityQueue(maxsize=0) Constructor for a priority queue. *maxsize* is an integer that sets the upperbound limit on the number of items that can be placed in the queue. Insertion will From python-checkins at python.org Wed May 19 16:16:14 2010 From: python-checkins at python.org (georg.brandl) Date: Wed, 19 May 2010 16:16:14 +0200 (CEST) Subject: [Python-checkins] r81342 - in python/branches/release26-maint: Doc/includes/minidom-example.py Doc/library/xml.dom.minidom.rst Doc/library/zlib.rst Message-ID: <20100519141614.5AEEAEE994@mail.python.org> Author: georg.brandl Date: Wed May 19 16:16:14 2010 New Revision: 81342 Log: Merged revisions 78559,78561-78562 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r78559 | andrew.kuchling | 2010-03-01 20:45:21 +0100 (Mo, 01 M?r 2010) | 1 line #7637: update discussion of minidom.unlink() and garbage collection ........ r78561 | andrew.kuchling | 2010-03-01 20:51:43 +0100 (Mo, 01 M?r 2010) | 1 line #7191: describe more details of wbits parameter ........ r78562 | andrew.kuchling | 2010-03-01 21:11:57 +0100 (Mo, 01 M?r 2010) | 1 line #7637: avoid repeated-concatenation antipattern in example ........ Modified: python/branches/release26-maint/ (props changed) python/branches/release26-maint/Doc/includes/minidom-example.py python/branches/release26-maint/Doc/library/xml.dom.minidom.rst python/branches/release26-maint/Doc/library/zlib.rst Modified: python/branches/release26-maint/Doc/includes/minidom-example.py ============================================================================== --- python/branches/release26-maint/Doc/includes/minidom-example.py (original) +++ python/branches/release26-maint/Doc/includes/minidom-example.py Wed May 19 16:16:14 2010 @@ -19,11 +19,11 @@ dom = xml.dom.minidom.parseString(document) def getText(nodelist): - rc = "" + rc = [] for node in nodelist: if node.nodeType == node.TEXT_NODE: - rc = rc + node.data - return rc + rc.append(node.data) + return ''.join(rc) def handleSlideshow(slideshow): print "" Modified: python/branches/release26-maint/Doc/library/xml.dom.minidom.rst ============================================================================== --- python/branches/release26-maint/Doc/library/xml.dom.minidom.rst (original) +++ python/branches/release26-maint/Doc/library/xml.dom.minidom.rst Wed May 19 16:16:14 2010 @@ -85,22 +85,12 @@ dom3 = parseString("Some data") assert dom3.documentElement.tagName == "myxml" -When you are finished with a DOM, you should clean it up. This is necessary -because some versions of Python do not support garbage collection of objects -that refer to each other in a cycle. Until this restriction is removed from all -versions of Python, it is safest to write your code as if cycles would not be -cleaned up. - -The way to clean up a DOM is to call its :meth:`unlink` method:: - - dom1.unlink() - dom2.unlink() - dom3.unlink() - -:meth:`unlink` is a :mod:`xml.dom.minidom`\ -specific extension to the DOM API. -After calling :meth:`unlink` on a node, the node and its descendants are -essentially useless. - +When you are finished with a DOM tree, you may optionally call the +:meth:`unlink` method to encourage early cleanup of the now-unneeded +objects. :meth:`unlink` is a :mod:`xml.dom.minidom`\ -specific +extension to the DOM API that renders the node and its descendants are +essentially useless. Otherwise, Python's garbage collector will +eventually take care of the objects in the tree. .. seealso:: Modified: python/branches/release26-maint/Doc/library/zlib.rst ============================================================================== --- python/branches/release26-maint/Doc/library/zlib.rst (original) +++ python/branches/release26-maint/Doc/library/zlib.rst Wed May 19 16:16:14 2010 @@ -115,14 +115,18 @@ Decompresses the data in *string*, returning a string containing the uncompressed data. The *wbits* parameter controls the size of the window - buffer. If *bufsize* is given, it is used as the initial size of the output + buffer, and is discussed further below. + If *bufsize* is given, it is used as the initial size of the output buffer. Raises the :exc:`error` exception if any error occurs. The absolute value of *wbits* is the base two logarithm of the size of the history buffer (the "window size") used when compressing data. Its absolute value should be between 8 and 15 for the most recent versions of the zlib library, larger values resulting in better compression at the expense of greater - memory usage. The default value is 15. When *wbits* is negative, the standard + memory usage. When decompressing a stream, *wbits* must not be smaller + than the size originally used to compress the stream; using a too-small + value will result in an exception. The default value is therefore the + highest value, 15. When *wbits* is negative, the standard :program:`gzip` header is suppressed. *bufsize* is the initial size of the buffer used to hold decompressed data. If From python-checkins at python.org Wed May 19 16:17:00 2010 From: python-checkins at python.org (georg.brandl) Date: Wed, 19 May 2010 16:17:00 +0200 (CEST) Subject: [Python-checkins] r81343 - in python/branches/release26-maint: Doc/library/sys.rst Message-ID: <20100519141700.96C29EE996@mail.python.org> Author: georg.brandl Date: Wed May 19 16:17:00 2010 New Revision: 81343 Log: Merged revisions 78717 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r78717 | benjamin.peterson | 2010-03-06 04:13:33 +0100 (Sa, 06 M?r 2010) | 1 line settscdump is definitely an implementation detail ........ Modified: python/branches/release26-maint/ (props changed) python/branches/release26-maint/Doc/library/sys.rst Modified: python/branches/release26-maint/Doc/library/sys.rst ============================================================================== --- python/branches/release26-maint/Doc/library/sys.rst (original) +++ python/branches/release26-maint/Doc/library/sys.rst Wed May 19 16:17:00 2010 @@ -834,6 +834,11 @@ .. versionadded:: 2.4 + .. impl-detail:: + + This function is intimately bound to CPython implementation details and + thus not likely to be implemented elsewhere. + .. data:: stdin stdout From python-checkins at python.org Wed May 19 16:23:58 2010 From: python-checkins at python.org (georg.brandl) Date: Wed, 19 May 2010 16:23:58 +0200 (CEST) Subject: [Python-checkins] r81344 - python/branches/release26-maint Message-ID: <20100519142358.045E0EE9A9@mail.python.org> Author: georg.brandl Date: Wed May 19 16:23:57 2010 New Revision: 81344 Log: Blocked revisions 78001,78003,78005,78007,78009-78010,78018-78020,78022,78028-78033,78036-78039,78042,78046,78048,78051,78055,78059,78081-78082,78085-78086,78088,78091,78093-78094,78097,78099,78102-78109,78112,78116,78119,78125,78130-78132,78136,78148,78150,78158,78166,78211,78216-78218,78227,78229,78232,78246,78249,78280,78287-78288,78296,78319,78329,78331-78332,78336,78338,78343,78345-78346,78348-78349,78351,78354,78359-78360,78364,78367,78372-78373,78377,78379,78384,78393,78403,78416-78417,78430,78468,78486,78508-78509,78528,78544,78566,78574,78576,78580,78582,78585-78594,78600-78601,78604,78606,78613-78614,78623,78634,78644,78652-78653,78656,78660-78662,78666-78667,78671,78673,78675,78678,78680,78682,78688,78690,78694,78701,78703-78704,78706,78710,78712-78713,78719-78721,78726,78728,78731-78732,78734-78736,78738,78743,78749,78751,78755,78757-78759,78761-78762,78764,78767,78769-78770,78774-78779,78787-78791,78794,78806,78810-78812,78814-78815,78819,78828,78830,78832-78833,78838-78839,78841-78842,78844,78846-78847,78853,78855,78886,78917,78919,78922,78926,78932,78934,78937,78939,78944,78949,78954,78966,78968-78972,78974,78982-78983,78985-78986,78996 via svnmerge ........ r78001 | michael.foord | 2010-02-05 22:45:12 +0100 (Fr, 05 Feb 2010) | 1 line Adding versionadded to test skipping section of unittest documentation. ........ r78003 | michael.foord | 2010-02-05 23:55:09 +0100 (Fr, 05 Feb 2010) | 1 line Improving docstrings in unittest.TestCase ........ r78005 | michael.foord | 2010-02-06 00:22:37 +0100 (Sa, 06 Feb 2010) | 1 line Correction to docstring correction. ........ r78007 | michael.foord | 2010-02-06 00:28:12 +0100 (Sa, 06 Feb 2010) | 1 line Minor doc change. ........ r78009 | vinay.sajip | 2010-02-06 00:43:11 +0100 (Sa, 06 Feb 2010) | 1 line test_logging: minor tweaks to timeouts, listening tests marked as skipped. ........ r78010 | michael.foord | 2010-02-06 01:22:26 +0100 (Sa, 06 Feb 2010) | 1 line unittest.TestLoader creates a TestSuite before calling load_tests. Issue 7799. ........ r78018 | georg.brandl | 2010-02-06 11:08:21 +0100 (Sa, 06 Feb 2010) | 1 line #7864: make deprecation notices a bit clearer. ........ r78019 | georg.brandl | 2010-02-06 11:23:16 +0100 (Sa, 06 Feb 2010) | 1 line Review sysconfig docs. ........ r78020 | benjamin.peterson | 2010-02-06 17:37:32 +0100 (Sa, 06 Feb 2010) | 1 line bump version to 2.7a3 ........ r78022 | benjamin.peterson | 2010-02-06 19:26:27 +0100 (Sa, 06 Feb 2010) | 1 line post release updates ........ r78028 | benjamin.peterson | 2010-02-06 20:40:18 +0100 (Sa, 06 Feb 2010) | 1 line remove pointless error checking ........ r78029 | vinay.sajip | 2010-02-06 21:00:43 +0100 (Sa, 06 Feb 2010) | 1 line Issue #7857: Tentatively re-enabling one test to see effect on buildbots. ........ r78030 | benjamin.peterson | 2010-02-06 21:14:10 +0100 (Sa, 06 Feb 2010) | 1 line check type_getattro for correctness in a descriptor corner case ........ r78031 | vinay.sajip | 2010-02-06 21:28:36 +0100 (Sa, 06 Feb 2010) | 1 line Issue #7857: Gave server thread more time to get ready, and re-enabled a skipped test. ........ r78032 | georg.brandl | 2010-02-06 22:54:40 +0100 (Sa, 06 Feb 2010) | 1 line Remove unused imports from test_logging. ........ r78033 | benjamin.peterson | 2010-02-06 23:08:15 +0100 (Sa, 06 Feb 2010) | 1 line make waiting for the server to start robust ........ r78036 | georg.brandl | 2010-02-06 23:49:47 +0100 (Sa, 06 Feb 2010) | 1 line Remove unused import. ........ r78037 | georg.brandl | 2010-02-06 23:59:15 +0100 (Sa, 06 Feb 2010) | 1 line No need to assign the results of expressions used only for side effects. ........ r78038 | georg.brandl | 2010-02-07 00:02:29 +0100 (So, 07 Feb 2010) | 1 line Add a missing import. ........ r78039 | georg.brandl | 2010-02-07 00:06:24 +0100 (So, 07 Feb 2010) | 1 line Add missing imports. ........ r78042 | georg.brandl | 2010-02-07 00:12:12 +0100 (So, 07 Feb 2010) | 1 line Add missing import. ........ r78046 | georg.brandl | 2010-02-07 00:18:00 +0100 (So, 07 Feb 2010) | 1 line Fix various missing import/unbound name errors. ........ r78048 | georg.brandl | 2010-02-07 00:23:45 +0100 (So, 07 Feb 2010) | 1 line We heard you like test failures so we put unbound locals in your test so that you can fail while you fail. ........ r78051 | georg.brandl | 2010-02-07 00:53:52 +0100 (So, 07 Feb 2010) | 1 line Add missing import when running these tests standalone. ........ r78055 | vinay.sajip | 2010-02-07 02:37:08 +0100 (So, 07 Feb 2010) | 1 line Issue #7868: logging: added loggerClass attribute to Manager. ........ r78059 | georg.brandl | 2010-02-07 12:34:15 +0100 (So, 07 Feb 2010) | 1 line Use "regexp" consistently. ........ r78081 | vinay.sajip | 2010-02-07 13:56:54 +0100 (So, 07 Feb 2010) | 1 line Issue #7869: logging: improved format-time diagnostics and removed some 1.5.2 support code. ........ r78082 | mark.dickinson | 2010-02-07 14:01:56 +0100 (So, 07 Feb 2010) | 1 line Add missing global declarations for 'overflowok'; remove 'overflowrequired', which is no longer needed. ........ r78085 | vinay.sajip | 2010-02-07 14:06:51 +0100 (So, 07 Feb 2010) | 1 line logging: Removed some more 1.5.2 support code. ........ r78086 | mark.dickinson | 2010-02-07 14:09:52 +0100 (So, 07 Feb 2010) | 1 line Actually raise on failure, instead of doing nothing. ........ r78088 | antoine.pitrou | 2010-02-07 17:56:23 +0100 (So, 07 Feb 2010) | 4 lines Issue #7870: Remove duplicate test methods. Reported by Georg Brandl. ........ r78091 | georg.brandl | 2010-02-07 18:02:22 +0100 (So, 07 Feb 2010) | 1 line Rename "exc_value" attribute on assertRaises context manager to "exception". ........ r78093 | georg.brandl | 2010-02-07 18:03:15 +0100 (So, 07 Feb 2010) | 1 line Remove unused imports in test modules. ........ r78094 | michael.foord | 2010-02-07 19:44:12 +0100 (So, 07 Feb 2010) | 1 line assertRaises as context manager now allows you to access exception as documented ........ r78097 | ronald.oussoren | 2010-02-07 21:18:02 +0100 (So, 07 Feb 2010) | 2 lines Issue 6003: ZipFile.writestr "compression_type" argument ........ r78099 | mark.dickinson | 2010-02-07 21:31:10 +0100 (So, 07 Feb 2010) | 1 line Skip test_strtod entirely when correctly-rounded string->float isn't implemented ........ r78102 | andrew.kuchling | 2010-02-08 02:35:35 +0100 (Mo, 08 Feb 2010) | 1 line Move distutils into its own subsection; add various items ........ r78103 | vinay.sajip | 2010-02-08 07:50:14 +0100 (Mo, 08 Feb 2010) | 1 line Removed spurious print statement in test. ........ r78104 | andrew.kuchling | 2010-02-08 14:22:24 +0100 (Mo, 08 Feb 2010) | 1 line Add two items; move a subsection ........ r78105 | vinay.sajip | 2010-02-08 16:32:08 +0100 (Mo, 08 Feb 2010) | 1 line logging: skipped listening tests because they're not working reliably. ........ r78106 | vinay.sajip | 2010-02-08 17:05:50 +0100 (Mo, 08 Feb 2010) | 1 line Issue #7857: Another attempt to keep the buildbots happy. ........ r78107 | antoine.pitrou | 2010-02-08 21:25:47 +0100 (Mo, 08 Feb 2010) | 3 lines Clarify and correct description for ccbench and iobench. ........ r78108 | vinay.sajip | 2010-02-08 22:18:15 +0100 (Mo, 08 Feb 2010) | 1 line logging: gingerly re-enabling skipped tests after improving thread sync code in configurator. ........ r78109 | ezio.melotti | 2010-02-08 22:52:08 +0100 (Mo, 08 Feb 2010) | 1 line Fix exc_value -> exception in docstring ........ r78112 | ezio.melotti | 2010-02-08 23:22:41 +0100 (Mo, 08 Feb 2010) | 1 line Fix typo ........ r78116 | michael.foord | 2010-02-08 23:41:16 +0100 (Mo, 08 Feb 2010) | 1 line Make assertMultiLineEqual the default for comparing unicode strings. ........ r78119 | michael.foord | 2010-02-09 00:15:22 +0100 (Di, 09 Feb 2010) | 1 line Doc fix for unittest. ........ r78125 | antoine.pitrou | 2010-02-09 18:08:05 +0100 (Di, 09 Feb 2010) | 7 lines Issue #2746: Don't escape ampersands and angle brackets ("&", "<", ">") in XML processing instructions and comments. These raw characters are allowed by the XML specification, and are necessary when outputting e.g. PHP code in a processing instruction. Patch by Neil Muller. ........ r78130 | michael.foord | 2010-02-10 15:25:12 +0100 (Mi, 10 Feb 2010) | 1 line Issue 7893 and Issue 7588 ........ r78131 | michael.foord | 2010-02-10 15:31:30 +0100 (Mi, 10 Feb 2010) | 1 line Remove deprecation on assert_. It is used too frequently. ........ r78132 | michael.foord | 2010-02-10 16:50:58 +0100 (Mi, 10 Feb 2010) | 1 line Fix for unittest tests, to be merged to py3k ........ r78136 | ezio.melotti | 2010-02-10 22:40:33 +0100 (Mi, 10 Feb 2010) | 1 line #7712: add a temp_cwd context manager to test_support and use it in regrtest to run all the tests in a temporary directory, saving the original CWD in test_support.SAVEDCWD. Thanks to Florent Xicluna who helped with the patch. ........ r78148 | ronald.oussoren | 2010-02-11 14:13:08 +0100 (Do, 11 Feb 2010) | 3 lines Add guard around the prototype for completion_matches to enable compilition with libedit on OSX 10.5 ........ r78150 | ronald.oussoren | 2010-02-11 14:19:34 +0100 (Do, 11 Feb 2010) | 3 lines Fix copy&paste error in the definition of ARCH_RUN_32BIT for a 3-way universal build (all other definition where correct). ........ r78158 | michael.foord | 2010-02-11 15:12:07 +0100 (Do, 11 Feb 2010) | 1 line Adding TextTestResult to unittest.__all__ ........ r78166 | mark.dickinson | 2010-02-12 22:16:38 +0100 (Fr, 12 Feb 2010) | 1 line Check that 'd' isn't allowed as an exponent specifier in inputs to the float function. ........ r78211 | ezio.melotti | 2010-02-17 00:58:49 +0100 (Mi, 17 Feb 2010) | 1 line #7941: fix error message ........ r78216 | andrew.kuchling | 2010-02-18 15:16:48 +0100 (Do, 18 Feb 2010) | 1 line Add various items ........ r78217 | mark.dickinson | 2010-02-18 15:27:02 +0100 (Do, 18 Feb 2010) | 5 lines Issue #7633: Context method in the decimal module (with the exception of the 'canonical' and 'is_canonical' methods) now consistently accept integer arguments wherever a Decimal instance is accepted. Thanks Juan Jos? Conti for the patch. ........ r78218 | mark.dickinson | 2010-02-18 15:45:33 +0100 (Do, 18 Feb 2010) | 1 line Doctest fixes for decimal.py: add an integer-argument doctest for logical_invert; don't use integer literals with a leading zero. ........ r78227 | michael.foord | 2010-02-18 21:30:09 +0100 (Do, 18 Feb 2010) | 1 line unittest.TestCase uses safe_repr for producing failure messages. Partial fix for issue 7956 ........ r78229 | michael.foord | 2010-02-18 22:37:07 +0100 (Do, 18 Feb 2010) | 1 line Fix unittest.TestCase.assertDictContainsSubset so it can't die with unicode issues when constructing failure messages. Issue 7956 ........ r78232 | fred.drake | 2010-02-19 06:24:30 +0100 (Fr, 19 Feb 2010) | 3 lines - apply patch from issue 7005 - add corresponding documentation ........ r78246 | vinay.sajip | 2010-02-20 00:53:17 +0100 (Sa, 20 Feb 2010) | 1 line logging: Documented warnings module integration. ........ r78249 | ezio.melotti | 2010-02-20 10:40:07 +0100 (Sa, 20 Feb 2010) | 1 line Remove e assertIs definitions and use correct assert* methods. ........ r78280 | mark.dickinson | 2010-02-21 13:57:35 +0100 (So, 21 Feb 2010) | 3 lines Issue #5211: Fix complex type to avoid implicit calls to complex.__coerce__. Thanks Meador Inge for the patch. ........ r78287 | mark.dickinson | 2010-02-21 15:42:27 +0100 (So, 21 Feb 2010) | 1 line Reduce number of random tests in test_strtod, to avoid hogging buildbot time. ........ r78288 | michael.foord | 2010-02-21 15:48:59 +0100 (So, 21 Feb 2010) | 1 line Silence UnicodeWarning in crazy unittest test. ........ r78296 | andrew.kuchling | 2010-02-22 03:08:45 +0100 (Mo, 22 Feb 2010) | 1 line Re-word ........ r78319 | ezio.melotti | 2010-02-22 17:30:58 +0100 (Mo, 22 Feb 2010) | 1 line #7482: clarify error message in case of division by zero of float and complex numbers. ........ r78329 | eric.smith | 2010-02-22 19:33:47 +0100 (Mo, 22 Feb 2010) | 1 line Issue #7988: Fix default alignment to be right aligned for complex.__format__. Now it matches other numeric types. ........ r78331 | andrew.kuchling | 2010-02-22 19:38:23 +0100 (Mo, 22 Feb 2010) | 1 line Fix comment typo ........ r78332 | andrew.kuchling | 2010-02-22 19:42:07 +0100 (Mo, 22 Feb 2010) | 2 lines #7627: MH.remove() would fail if the MH mailbox was locked; it would call _unlock_file() and pass it a closed file object. Noted by Rob Austein. ........ r78336 | jack.diederich | 2010-02-22 20:55:22 +0100 (Mo, 22 Feb 2010) | 1 line fixes issue #1522237, bad init check in _threading_local ........ r78338 | andrew.kuchling | 2010-02-22 22:04:02 +0100 (Mo, 22 Feb 2010) | 4 lines Remove Tools/modulator, a reference to it in the docs, and a screenshot of it. (I asked the BDFL first, and he approved removing it. The last actual bugfix to Tools/modulator was in 2001; since then all changes have been search-and-replace: string methods, whitespace fixes, etc.) ........ r78343 | andrew.kuchling | 2010-02-22 23:48:41 +0100 (Mo, 22 Feb 2010) | 10 lines #2560: remove an unnecessary 'for' loop from my_fgets() in Parser/myreadline.c. Noted by Joseph Armbruster; patch by Jessica McKellar. The original code was 'for (;;) {...}', where ... ended with a 'return -2' statement and did not contain a 'break' or 'continue' statement. Therefore, the body of the loop is always executed once. Once upon a time there was a 'continue' in the loop, but it was removed in rev36346, committed by mwh on Wed Jul 7 17:44:12 2004. ........ r78345 | andrew.kuchling | 2010-02-23 00:10:52 +0100 (Di, 23 Feb 2010) | 1 line #7706: DONT_HAVE_ERRNO_H is no longer defined by configure (after rev.46819). ........ r78346 | andrew.kuchling | 2010-02-23 00:12:00 +0100 (Di, 23 Feb 2010) | 1 line #7706: add include guards where they're missing; required for Windows CE ........ r78348 | michael.foord | 2010-02-23 00:28:32 +0100 (Di, 23 Feb 2010) | 1 line Support for old TestResult object (unittest) with warnings when using unsupported features. ........ r78349 | eric.smith | 2010-02-23 01:11:16 +0100 (Di, 23 Feb 2010) | 1 line Issue #6902: Fix problem with built-in types format incorrectly with 0 padding. ........ r78351 | r.david.murray | 2010-02-23 01:24:49 +0100 (Di, 23 Feb 2010) | 5 lines Issue 6292: for the moment at least, the test suite passes if run with -OO. Tests requiring docstrings are skipped. Patch by Brian Curtin, thanks to Matias Torchinsky for helping review and improve the patch. ........ r78354 | tarek.ziade | 2010-02-23 05:57:05 +0100 (Di, 23 Feb 2010) | 1 line removed debugging code ........ r78359 | tarek.ziade | 2010-02-23 06:16:41 +0100 (Di, 23 Feb 2010) | 1 line added make_archive (and secondary APIs) to shutil ........ r78360 | tarek.ziade | 2010-02-23 06:20:22 +0100 (Di, 23 Feb 2010) | 1 line added a note on shutil new APIs ........ r78364 | tarek.ziade | 2010-02-23 06:36:41 +0100 (Di, 23 Feb 2010) | 1 line completed the __all__ list and changed the module doctest ........ r78367 | tarek.ziade | 2010-02-23 06:53:05 +0100 (Di, 23 Feb 2010) | 1 line fixed #5801: removed spurious empty lines in wsgiref ........ r78372 | mark.dickinson | 2010-02-23 13:53:52 +0100 (Di, 23 Feb 2010) | 1 line Make global variable overflowok into a keyword argument; this fixes a failure when running ./python -m test.regrtest -R 3:2: test_format ........ r78373 | mark.dickinson | 2010-02-23 14:06:50 +0100 (Di, 23 Feb 2010) | 1 line Fix spacing nit. Thanks Eric Smith for the public humiliation. ........ r78377 | michael.foord | 2010-02-23 18:00:53 +0100 (Di, 23 Feb 2010) | 1 line unittest.TestResult can now be used with the TextTestRunner. TextTestRunner compatible with old TestResult objects. ........ r78379 | jack.diederich | 2010-02-23 20:34:06 +0100 (Di, 23 Feb 2010) | 1 line issue#6442 use in operator instead of has_key ........ r78384 | dirkjan.ochtman | 2010-02-23 22:09:52 +0100 (Di, 23 Feb 2010) | 4 lines Fix #1537721: add writeheader() method to csv.DictWriter. Reviewed by skip.montanaro and thomas.wouters. ........ r78393 | amaury.forgeotdarc | 2010-02-24 00:19:39 +0100 (Mi, 24 Feb 2010) | 2 lines #4852: Remove dead code in every thread implementation, unused for many years. ........ r78403 | r.david.murray | 2010-02-24 03:08:28 +0100 (Mi, 24 Feb 2010) | 3 lines The primary copy of lib2to3 is not trunk, so the lib2to3 change should not have been included in the -OO patch, back it out. ........ r78416 | dirkjan.ochtman | 2010-02-24 05:12:11 +0100 (Mi, 24 Feb 2010) | 1 line Issue #8004: add a serve target to the Doc Makefile. ........ r78417 | dirkjan.ochtman | 2010-02-24 05:49:00 +0100 (Mi, 24 Feb 2010) | 1 line Issue #7427: improve the representation of httplib.BadStatusLine exceptions. ........ r78430 | dirkjan.ochtman | 2010-02-24 18:06:31 +0100 (Mi, 24 Feb 2010) | 1 line Add some notes about Tools/scripts/serve.py. ........ r78468 | benjamin.peterson | 2010-02-27 01:11:42 +0100 (Sa, 27 Feb 2010) | 1 line run autoconf ........ r78486 | ezio.melotti | 2010-02-27 13:42:52 +0100 (Sa, 27 Feb 2010) | 1 line Add a test for normpath to test_macpath. ........ r78508 | florent.xicluna | 2010-02-27 20:20:50 +0100 (Sa, 27 Feb 2010) | 2 lines Clean test_subprocess: use assertRaises, skipIf, skipUnless helpers and a custom helper assertStderrEqual. ........ r78509 | florent.xicluna | 2010-02-27 22:15:27 +0100 (Sa, 27 Feb 2010) | 2 lines Fix an oversight in r78508: p.wait() should be compared to 0 ........ r78528 | gregory.p.smith | 2010-03-01 03:01:47 +0100 (Mo, 01 M?r 2010) | 2 lines Adds the hashlib.algorithms attribute. See issue7418. ........ r78544 | gregory.p.smith | 2010-03-01 05:56:12 +0100 (Mo, 01 M?r 2010) | 2 lines Adds c_ssize_t to ctypes. issue 6729. ........ r78566 | barry.warsaw | 2010-03-01 22:46:51 +0100 (Mo, 01 M?r 2010) | 4 lines Manually copy patch for bug 7250 from the release26-maint branch. I suck because I did this in the wrong order and couldn't smack svnmerge into submission. ........ r78574 | benjamin.peterson | 2010-03-02 00:25:13 +0100 (Di, 02 M?r 2010) | 1 line remove CVS id ........ r78576 | steven.bethard | 2010-03-02 09:38:09 +0100 (Di, 02 M?r 2010) | 3 lines Initial commit of the argparse library, based on argparse 1.1. Docs still need some updating to make getopt and optparse match the wording promised in the PEP. There are also probably a number of :class:ArgumentParser etc. links that could be added to the argparse documentation. ........ r78580 | andrew.kuchling | 2010-03-02 14:55:33 +0100 (Di, 02 M?r 2010) | 1 line Add an item ........ r78582 | florent.xicluna | 2010-03-02 17:00:00 +0100 (Di, 02 M?r 2010) | 2 lines Refactor test_dict using assertRaises. ........ r78585 | florent.xicluna | 2010-03-02 22:34:45 +0100 (Di, 02 M?r 2010) | 2 lines Tentatively enable test_pep277 on all platforms. ........ r78586 | benjamin.peterson | 2010-03-02 23:03:03 +0100 (Di, 02 M?r 2010) | 1 line remove coding cookie as mandated by PEP 8 ........ r78587 | benjamin.peterson | 2010-03-02 23:05:59 +0100 (Di, 02 M?r 2010) | 1 line set svn:eol-style ........ r78588 | benjamin.peterson | 2010-03-02 23:08:40 +0100 (Di, 02 M?r 2010) | 1 line remove another coding cookie ........ r78589 | georg.brandl | 2010-03-02 23:17:38 +0100 (Di, 02 M?r 2010) | 1 line Add some x-refs. ........ r78590 | benjamin.peterson | 2010-03-02 23:20:10 +0100 (Di, 02 M?r 2010) | 1 line enable running of argparse tests and fix two that failed in the new environment ........ r78591 | benjamin.peterson | 2010-03-02 23:23:33 +0100 (Di, 02 M?r 2010) | 1 line prevent warning filter adjustment from altering other tests ........ r78592 | benjamin.peterson | 2010-03-02 23:24:30 +0100 (Di, 02 M?r 2010) | 1 line use test_main() in __main__ section ........ r78593 | benjamin.peterson | 2010-03-02 23:26:25 +0100 (Di, 02 M?r 2010) | 1 line convert deprecated fail* methods to assert* variants ........ r78594 | florent.xicluna | 2010-03-02 23:34:11 +0100 (Di, 02 M?r 2010) | 2 lines Test test_pep277 is only relevant for Unicode-friendly filesystems. ........ r78600 | benjamin.peterson | 2010-03-02 23:58:01 +0100 (Di, 02 M?r 2010) | 1 line remove code to avoid BaseException.message bug ........ r78601 | benjamin.peterson | 2010-03-03 00:02:02 +0100 (Mi, 03 M?r 2010) | 1 line remove cross-version compatibility code ........ r78604 | benjamin.peterson | 2010-03-03 00:43:47 +0100 (Mi, 03 M?r 2010) | 1 line plug ref leaks ........ r78606 | florent.xicluna | 2010-03-03 00:56:38 +0100 (Mi, 03 M?r 2010) | 2 lines Fix wording. ........ r78613 | benjamin.peterson | 2010-03-03 02:55:09 +0100 (Mi, 03 M?r 2010) | 1 line edit for style ........ r78614 | benjamin.peterson | 2010-03-03 03:04:24 +0100 (Mi, 03 M?r 2010) | 1 line fix Sphinx warnings ........ r78623 | lars.gustaebel | 2010-03-03 12:55:48 +0100 (Mi, 03 M?r 2010) | 3 lines Issue #7232: Add support for the context manager protocol to the TarFile class. ........ r78634 | benjamin.peterson | 2010-03-03 22:28:25 +0100 (Mi, 03 M?r 2010) | 1 line rephrase ........ r78644 | benjamin.peterson | 2010-03-04 03:07:55 +0100 (Do, 04 M?r 2010) | 1 line set svn:executable on all regen scripts ........ r78652 | florent.xicluna | 2010-03-04 16:57:20 +0100 (Do, 04 M?r 2010) | 2 lines Fix transient refleak in test_popen2. ........ r78653 | florent.xicluna | 2010-03-04 16:58:54 +0100 (Do, 04 M?r 2010) | 2 lines #7805: wait until all workers are started before collecting their PIDs ........ r78656 | r.david.murray | 2010-03-04 18:34:05 +0100 (Do, 04 M?r 2010) | 3 lines Fix documentation of email.Message.get_filename to match the fix applied in Issue 7082. ........ r78660 | dirkjan.ochtman | 2010-03-04 20:21:53 +0100 (Do, 04 M?r 2010) | 4 lines Try to fix buildbot breakage from r78384. Thanks bitdancer and briancurtin for the help. ........ r78661 | florent.xicluna | 2010-03-04 20:40:48 +0100 (Do, 04 M?r 2010) | 2 lines Cleanup. ........ r78662 | florent.xicluna | 2010-03-04 22:31:58 +0100 (Do, 04 M?r 2010) | 2 lines #2777: Enable test_send_signal, test_kill and test_terminate on all platforms. ........ r78666 | tarek.ziade | 2010-03-05 01:16:02 +0100 (Fr, 05 M?r 2010) | 1 line reverting partially distutils to its 2.6.x state so 2.7a4 looks more like the 2.7b1 in this. the whole revert will occur after a4 is tagged ........ r78667 | tarek.ziade | 2010-03-05 01:29:38 +0100 (Fr, 05 M?r 2010) | 1 line reverted the usage of compiler_obj in Python's setup.py ........ r78671 | florent.xicluna | 2010-03-05 01:47:40 +0100 (Fr, 05 M?r 2010) | 3 lines Workaround #3137: Retry SIGINT if it is not received the first time. test_send_signal should not hang anymore on various Linux distributions. ........ r78673 | florent.xicluna | 2010-03-05 02:05:55 +0100 (Fr, 05 M?r 2010) | 2 lines Let's use assertIsNone / assertIsNotNone. It's hype. ........ r78675 | florent.xicluna | 2010-03-05 02:12:14 +0100 (Fr, 05 M?r 2010) | 2 lines These line should not be there. ........ r78678 | benjamin.peterson | 2010-03-05 04:07:59 +0100 (Fr, 05 M?r 2010) | 1 line set svn:eol-style ........ r78680 | benjamin.peterson | 2010-03-05 04:15:07 +0100 (Fr, 05 M?r 2010) | 1 line set svn:eol-style on Lib files ........ r78682 | benjamin.peterson | 2010-03-05 04:20:06 +0100 (Fr, 05 M?r 2010) | 1 line remove the svn:executable property from files that don't have shebang lines ........ r78688 | gerhard.haering | 2010-03-05 10:12:37 +0100 (Fr, 05 M?r 2010) | 2 lines Merged code from pysqlite 2.6.0. ........ r78690 | mark.dickinson | 2010-03-05 15:36:20 +0100 (Fr, 05 M?r 2010) | 3 lines Fix incorrect stacklevel for DeprecationWarnings originating from the struct module. Also clean up related tests in test_struct. The stacklevel fix should be backported to 2.6 once that branch is unfrozen. ........ r78694 | mark.dickinson | 2010-03-05 15:50:22 +0100 (Fr, 05 M?r 2010) | 1 line Remove the redundant #define: PY_STRUCT_FLOAT_COERCE ........ r78701 | florent.xicluna | 2010-03-05 20:31:21 +0100 (Fr, 05 M?r 2010) | 2 lines #2777: Handle fds more carefully to try to fix some x86-Linux failures (namely, neal bot and twisted bot). ........ r78703 | vinay.sajip | 2010-03-05 23:11:24 +0100 (Fr, 05 M?r 2010) | 1 line Factored out time usage determination into a method, to facilitate alternative formatting implementations in the future. ........ r78704 | florent.xicluna | 2010-03-06 01:16:57 +0100 (Sa, 06 M?r 2010) | 2 lines #2777: Apply same recipe for test_terminate and test_kill, i.e. close or redirect fds. ........ r78706 | tarek.ziade | 2010-03-06 02:04:14 +0100 (Sa, 06 M?r 2010) | 1 line copied back the build_ext tests from 2.6 ........ r78710 | tarek.ziade | 2010-03-06 02:27:09 +0100 (Sa, 06 M?r 2010) | 1 line files used by win32 tests ........ r78712 | tarek.ziade | 2010-03-06 03:11:14 +0100 (Sa, 06 M?r 2010) | 1 line fixed various failures and environment alterations in distutils.test_build_ext ........ r78713 | tarek.ziade | 2010-03-06 03:17:28 +0100 (Sa, 06 M?r 2010) | 1 line search in the alternative location for VCExpress ........ r78719 | florent.xicluna | 2010-03-06 09:07:44 +0100 (Sa, 06 M?r 2010) | 3 lines Keep the test files in the ./build/ subdirectory, if Python is not installed. Remove two hacks which are no longer needed after #7712, because all __file__ attributes are absolute. ........ r78720 | florent.xicluna | 2010-03-06 10:11:55 +0100 (Sa, 06 M?r 2010) | 2 lines Print platform information to stdout, to help troubleshooting platform-specific failures. ........ r78721 | florent.xicluna | 2010-03-06 10:54:14 +0100 (Sa, 06 M?r 2010) | 2 lines #2777: Apply same recipe on win32, i.e. do not inherit file handles. ........ r78726 | florent.xicluna | 2010-03-06 15:38:09 +0100 (Sa, 06 M?r 2010) | 2 lines Backport "test.regrtest -R 2:3" syntax from py3k branch, and other minor adjustments. ........ r78728 | vinay.sajip | 2010-03-06 16:12:08 +0100 (Sa, 06 M?r 2010) | 1 line Added schema version test in dictConfig. ........ r78731 | vinay.sajip | 2010-03-06 16:56:03 +0100 (Sa, 06 M?r 2010) | 1 line Added checks for tuples in dictConfig. ........ r78732 | florent.xicluna | 2010-03-06 18:24:36 +0100 (Sa, 06 M?r 2010) | 2 lines Do not print the header lines when running a single test. ........ r78734 | florent.xicluna | 2010-03-06 19:07:18 +0100 (Sa, 06 M?r 2010) | 2 lines Create test_genericpath.CommonTest and reuse it to test other path modules. ........ r78735 | florent.xicluna | 2010-03-06 19:52:52 +0100 (Sa, 06 M?r 2010) | 2 lines Minor tweaking of previous r78734, and add a NEWS entry. ........ r78736 | florent.xicluna | 2010-03-06 20:43:41 +0100 (Sa, 06 M?r 2010) | 2 lines Skip test_send_signal, test_kill, test_terminate on win32 platforms, for 2.7a4 release. ........ r78738 | benjamin.peterson | 2010-03-06 21:34:14 +0100 (Sa, 06 M?r 2010) | 1 line bump version to 2.7a4 ........ r78743 | benjamin.peterson | 2010-03-06 23:44:07 +0100 (Sa, 06 M?r 2010) | 1 line post release update ........ r78749 | benjamin.peterson | 2010-03-07 01:29:44 +0100 (So, 07 M?r 2010) | 1 line eliminate py3k warnings in argparse ........ r78751 | senthil.kumaran | 2010-03-07 05:09:30 +0100 (So, 07 M?r 2010) | 3 lines Reverting the change made in r78431. ........ r78755 | ronald.oussoren | 2010-03-07 10:04:06 +0100 (So, 07 M?r 2010) | 3 lines Fix for issue #7998: pythonw didn't work when --with-framework-name was specified ........ r78757 | florent.xicluna | 2010-03-07 13:14:25 +0100 (So, 07 M?r 2010) | 2 lines Fix some py3k warnings in the standard library. ........ r78758 | florent.xicluna | 2010-03-07 13:18:33 +0100 (So, 07 M?r 2010) | 4 lines Issue #7849: Now the utility ``check_warnings`` verifies if the warnings are effectively raised. A new utility ``check_py3k_warnings`` deals with py3k warnings. ........ r78759 | florent.xicluna | 2010-03-07 13:21:36 +0100 (So, 07 M?r 2010) | 2 lines #2777: Enable test_send_signal, test_terminate and test_kill on win32 platforms. ........ r78761 | florent.xicluna | 2010-03-07 16:27:39 +0100 (So, 07 M?r 2010) | 4 lines Do not fail if returncode is 0 on send_signal/kill/terminate, for win32 platforms. Do not hide the KeyboardInterrupt on POSIX platforms. ........ r78762 | mark.dickinson | 2010-03-07 17:24:45 +0100 (So, 07 M?r 2010) | 8 lines Issue #1530559: When packing a non-integer with any integer conversion code using struct.pack, attempt to convert to an integer first using the argument's __int__ method (if present). Also raise a DeprecationWarning for any such usage of __int__. This fixes a regression from 2.6, where some (but not all) integer conversion codes already used __int__. ........ r78764 | mark.dickinson | 2010-03-07 18:10:19 +0100 (So, 07 M?r 2010) | 1 line Silence compiler warning. ........ r78767 | florent.xicluna | 2010-03-07 18:12:23 +0100 (So, 07 M?r 2010) | 2 lines #2777: Try hard to make Win7 buildbot happy... ........ r78769 | florent.xicluna | 2010-03-07 20:14:12 +0100 (So, 07 M?r 2010) | 2 lines Refresh the documentation for the test.test_support module. ........ r78770 | michael.foord | 2010-03-07 21:22:12 +0100 (So, 07 M?r 2010) | 1 line Fix for potentials errors in constructing unittest failure messages. Plus skipped test methods no longer run setUp and tearDown (Issue 8059) ........ r78774 | michael.foord | 2010-03-07 23:04:55 +0100 (So, 07 M?r 2010) | 1 line Addition of setUpClass and setUpModule shared fixtures to unittest. ........ r78775 | michael.foord | 2010-03-08 00:10:36 +0100 (Mo, 08 M?r 2010) | 1 line Fix accidental name rebinding in unittest py3k warning filtering. ........ r78776 | michael.foord | 2010-03-08 00:16:20 +0100 (Mo, 08 M?r 2010) | 1 line Remove accidental print statement from last commit. ........ r78777 | florent.xicluna | 2010-03-08 00:49:03 +0100 (Mo, 08 M?r 2010) | 4 lines Backport the Popen.poll() protection from subprocess to multiprocessing. See #1731717. It should fix transient failures on test_multiprocessing. ........ r78778 | r.david.murray | 2010-03-08 03:04:06 +0100 (Mo, 08 M?r 2010) | 9 lines Issue #7143: get_payload used to strip any trailing newline from a base64 transfer-encoded payload *after* decoding it; it no longer does. email had a special method in utils, _bdecode, specifically to do this, so it must have served a purpose at some point, yet it is clearly wrong per RFC. Fixed with Barry's approval, but no backport. Email package minor version number is bumped, now version 4.0.1. Patch by Joaquin Cuenca Abela. ........ r78779 | benjamin.peterson | 2010-03-08 03:11:06 +0100 (Mo, 08 M?r 2010) | 1 line remove svn:executable from scripts without a shebang line ........ r78787 | florent.xicluna | 2010-03-08 08:21:16 +0100 (Mo, 08 M?r 2010) | 2 lines Don't fail on a debug() statement, if the worker PID is (still) None. ........ r78788 | florent.xicluna | 2010-03-08 11:58:12 +0100 (Mo, 08 M?r 2010) | 2 lines Fix syntax: "rc != None" -> "rc is not None" ........ r78789 | florent.xicluna | 2010-03-08 11:59:33 +0100 (Mo, 08 M?r 2010) | 2 lines Replace the stderr logging with assertNotEqual(returncode, 0). ........ r78790 | florent.xicluna | 2010-03-08 12:01:39 +0100 (Mo, 08 M?r 2010) | 2 lines On finalize, don't try to join not started process. ........ r78791 | andrew.kuchling | 2010-03-08 13:00:39 +0100 (Mo, 08 M?r 2010) | 1 line Add various items ........ r78794 | florent.xicluna | 2010-03-08 13:39:35 +0100 (Mo, 08 M?r 2010) | 2 lines Move some tests from test_macpath to test_genericpath.CommonTest ........ r78806 | benjamin.peterson | 2010-03-08 23:15:11 +0100 (Mo, 08 M?r 2010) | 1 line set svn:eol-style on various files ........ r78810 | raymond.hettinger | 2010-03-09 09:44:18 +0100 (Di, 09 M?r 2010) | 5 lines Improve the basic example. * Show both the decorator and regular form for assertRaises() * Use assertTrue() instead of assertIn() to teach useful minimal subset of the API ........ r78811 | raymond.hettinger | 2010-03-09 10:01:46 +0100 (Di, 09 M?r 2010) | 4 lines Add nicer docstrings to namedtuples(). Provides better tooltips and looks better in help(). ........ r78812 | raymond.hettinger | 2010-03-09 10:58:53 +0100 (Di, 09 M?r 2010) | 6 lines Have links in OrderedDicts be native Python lists instead of a custom class with __slots__. This simplifies the code a bit, reduces memory consumption, improves speed, and eliminates the need for weak reference proxies. ........ r78814 | raymond.hettinger | 2010-03-09 12:29:10 +0100 (Di, 09 M?r 2010) | 1 line Improve code clarity a bit. ........ r78815 | florent.xicluna | 2010-03-09 20:57:01 +0100 (Di, 09 M?r 2010) | 2 lines #7772: Fix test_py3kwarn. Now the test suite could pass with "-3" flag. ........ r78819 | benjamin.peterson | 2010-03-09 22:46:54 +0100 (Di, 09 M?r 2010) | 1 line fix ugly configure output (follow up to #6943) ........ r78828 | florent.xicluna | 2010-03-11 00:58:42 +0100 (Do, 11 M?r 2010) | 2 lines Issue #7880: Fix sysconfig when the python executable is a symbolic link. ........ r78830 | florent.xicluna | 2010-03-11 01:56:59 +0100 (Do, 11 M?r 2010) | 3 lines Fix the test_subprocess failure when sys.executable is meaningless: '' or a directory. It does not fix #7774. ........ r78832 | florent.xicluna | 2010-03-11 02:39:55 +0100 (Do, 11 M?r 2010) | 2 lines It is not optimal to test sys.stderr on a debug build. ........ r78833 | florent.xicluna | 2010-03-11 02:50:48 +0100 (Do, 11 M?r 2010) | 2 lines Revert r78830: realpath() should really be applied to sys.executable. ........ r78838 | florent.xicluna | 2010-03-11 15:36:19 +0100 (Do, 11 M?r 2010) | 2 lines Issue #6472: The xml.etree package is updated to ElementTree 1.3. The cElementTree module is updated too. ........ r78839 | florent.xicluna | 2010-03-11 16:55:11 +0100 (Do, 11 M?r 2010) | 2 lines Fix repr of tree Element on windows. ........ r78841 | benjamin.peterson | 2010-03-11 22:50:45 +0100 (Do, 11 M?r 2010) | 1 line remove executable property from doc files ........ r78842 | benjamin.peterson | 2010-03-11 22:53:25 +0100 (Do, 11 M?r 2010) | 1 line use proper shebang lines ........ r78844 | benjamin.peterson | 2010-03-11 23:03:45 +0100 (Do, 11 M?r 2010) | 1 line revert r78842 cgi.py change ........ r78846 | benjamin.peterson | 2010-03-11 23:33:25 +0100 (Do, 11 M?r 2010) | 1 line normalize shebang lines to #!/usr/bin/env python ........ r78847 | benjamin.peterson | 2010-03-11 23:34:12 +0100 (Do, 11 M?r 2010) | 1 line remove shebang line from non-executable test ........ r78853 | vinay.sajip | 2010-03-12 07:01:21 +0100 (Fr, 12 M?r 2010) | 1 line Issue #8117: logging: Improved algorithm for computing initial rollover time. ........ r78855 | vinay.sajip | 2010-03-12 10:16:10 +0100 (Fr, 12 M?r 2010) | 1 line Issue #8117: Updated NEWS entry and added to logging documentation. ........ r78886 | victor.stinner | 2010-03-13 01:13:22 +0100 (Sa, 13 M?r 2010) | 2 lines Issue #7818: set().test_c_api() doesn't expect a set('abc'), modify the set. ........ r78917 | florent.xicluna | 2010-03-13 12:18:49 +0100 (Sa, 13 M?r 2010) | 2 lines Move the xml test data to their own directory. ........ r78919 | florent.xicluna | 2010-03-13 13:41:48 +0100 (Sa, 13 M?r 2010) | 2 lines Do not chdir when running test_xml_etree, and enhance the findfile helper. ........ r78922 | georg.brandl | 2010-03-13 14:41:58 +0100 (Sa, 13 M?r 2010) | 1 line Update for new download location. ........ r78926 | mark.dickinson | 2010-03-13 15:18:34 +0100 (Sa, 13 M?r 2010) | 1 line Fix incorrect error checks in structmember.c (backport of r78920 from py3k). ........ r78932 | martin.v.loewis | 2010-03-13 18:53:02 +0100 (Sa, 13 M?r 2010) | 2 lines Add 2.6 uuids. ........ r78934 | florent.xicluna | 2010-03-13 18:56:19 +0100 (Sa, 13 M?r 2010) | 2 lines Update some parts of the xml.etree documentation. ........ r78937 | florent.xicluna | 2010-03-13 21:30:15 +0100 (Sa, 13 M?r 2010) | 3 lines Add the keyword argument "method=None" to the .write() method and the tostring/tostringlist functions. Update the function, class and method signatures, according to the new convention. ........ r78939 | antoine.pitrou | 2010-03-13 22:21:30 +0100 (Sa, 13 M?r 2010) | 5 lines Issue #7993: Add a test of IO packet processing bandwidth to ccbench. It measures the number of UDP packets processed per second depending on the number of background CPU-bound Python threads. ........ r78944 | florent.xicluna | 2010-03-14 02:22:09 +0100 (So, 14 M?r 2010) | 2 lines Minor documentation updates for xml.etree. ........ r78949 | georg.brandl | 2010-03-14 10:50:54 +0100 (So, 14 M?r 2010) | 1 line Format and rewrap 2.7 NEWS consistently. ........ r78954 | ezio.melotti | 2010-03-14 11:13:49 +0100 (So, 14 M?r 2010) | 1 line Add a link about the Public Review Issue #29 ........ r78966 | florent.xicluna | 2010-03-14 16:20:59 +0100 (So, 14 M?r 2010) | 2 lines Do not hardcode Expat version. It's possible to build Python with --with-system-expat option. ........ r78968 | matthias.klose | 2010-03-15 01:02:36 +0100 (Mo, 15 M?r 2010) | 226 lines - Issue #8142: Update libffi to the 3.0.9 release. -- Diese und die folgenden Zeilen werden ignoriert -- M Misc/NEWS A Modules/_ctypes/libffi/m4 A Modules/_ctypes/libffi/m4/ltsugar.m4 A Modules/_ctypes/libffi/m4/libtool.m4 A Modules/_ctypes/libffi/m4/ltversion.m4 A Modules/_ctypes/libffi/m4/lt~obsolete.m4 A Modules/_ctypes/libffi/m4/ltoptions.m4 A Modules/_ctypes/libffi/ChangeLog.libffi M Modules/_ctypes/libffi/configure M Modules/_ctypes/libffi/Makefile.in M Modules/_ctypes/libffi/fficonfig.h.in M Modules/_ctypes/libffi/src/arm/sysv.S M Modules/_ctypes/libffi/src/powerpc/ffitarget.h M Modules/_ctypes/libffi/src/powerpc/aix.S M Modules/_ctypes/libffi/src/powerpc/ffi.c M Modules/_ctypes/libffi/src/powerpc/sysv.S M Modules/_ctypes/libffi/src/powerpc/ffi_darwin.c M Modules/_ctypes/libffi/src/powerpc/aix_closure.S A Modules/_ctypes/libffi/src/closures.c D Modules/_ctypes/libffi/src/darwin/ffitarget.h M Modules/_ctypes/libffi/src/sh64/ffi.c M Modules/_ctypes/libffi/src/sh64/sysv.S M Modules/_ctypes/libffi/src/x86/ffi64.c M Modules/_ctypes/libffi/src/x86/ffitarget.h M Modules/_ctypes/libffi/src/x86/win32.S M Modules/_ctypes/libffi/src/x86/darwin.S M Modules/_ctypes/libffi/src/x86/ffi.c M Modules/_ctypes/libffi/src/x86/sysv.S A Modules/_ctypes/libffi/src/x86/win64.S M Modules/_ctypes/libffi/src/x86/unix64.S A Modules/_ctypes/libffi/src/types.c A Modules/_ctypes/libffi/src/avr32 A Modules/_ctypes/libffi/src/avr32/ffitarget.h A Modules/_ctypes/libffi/src/avr32/ffi.c A Modules/_ctypes/libffi/src/avr32/sysv.S M Modules/_ctypes/libffi/src/frv/ffi.c M Modules/_ctypes/libffi/src/s390/sysv.S M Modules/_ctypes/libffi/src/pa/ffi.c A Modules/_ctypes/libffi/src/raw_api.c A Modules/_ctypes/libffi/src/java_raw_api.c A Modules/_ctypes/libffi/src/debug.c M Modules/_ctypes/libffi/src/sparc/ffi.c M Modules/_ctypes/libffi/src/sparc/v8.S M Modules/_ctypes/libffi/src/mips/ffitarget.h M Modules/_ctypes/libffi/src/mips/n32.S M Modules/_ctypes/libffi/src/mips/o32.S M Modules/_ctypes/libffi/src/mips/ffi.c A Modules/_ctypes/libffi/src/dlmalloc.c M Modules/_ctypes/libffi/src/sh/ffi.c M Modules/_ctypes/libffi/src/sh/sysv.S AM Modules/_ctypes/libffi/depcomp AM Modules/_ctypes/libffi/compile M Modules/_ctypes/libffi/config.guess AM Modules/_ctypes/libffi/ltmain.sh M Modules/_ctypes/libffi/config.sub AM Modules/_ctypes/libffi/mdate-sh M Modules/_ctypes/libffi/configure.ac A Modules/_ctypes/libffi/doc A Modules/_ctypes/libffi/doc/libffi.texi A Modules/_ctypes/libffi/doc/stamp-vti A Modules/_ctypes/libffi/doc/libffi.info A Modules/_ctypes/libffi/doc/version.texi A Modules/_ctypes/libffi/texinfo.tex A Modules/_ctypes/libffi/man A Modules/_ctypes/libffi/man/ffi_call.3 A Modules/_ctypes/libffi/man/Makefile.in A Modules/_ctypes/libffi/man/ffi.3 A Modules/_ctypes/libffi/man/Makefile.am A Modules/_ctypes/libffi/man/ffi_prep_cif.3 A Modules/_ctypes/libffi/ChangeLog.libgcj M Modules/_ctypes/libffi/LICENSE M Modules/_ctypes/libffi/include/ffi.h.in M Modules/_ctypes/libffi/include/Makefile.in M Modules/_ctypes/libffi/include/ffi_common.h M Modules/_ctypes/libffi/include/Makefile.am A Modules/_ctypes/libffi/libtool-version A Modules/_ctypes/libffi/ChangeLog A Modules/_ctypes/libffi/testsuite A Modules/_ctypes/libffi/testsuite/Makefile.in A Modules/_ctypes/libffi/testsuite/libffi.call A Modules/_ctypes/libffi/testsuite/libffi.call/cls_multi_ushort.c A Modules/_ctypes/libffi/testsuite/libffi.call/stret_medium.c A Modules/_ctypes/libffi/testsuite/libffi.call/cls_align_uint16.c A Modules/_ctypes/libffi/testsuite/libffi.call/cls_align_longdouble_split2.c A Modules/_ctypes/libffi/testsuite/libffi.call/struct1.c A Modules/_ctypes/libffi/testsuite/libffi.call/return_uc.c A Modules/_ctypes/libffi/testsuite/libffi.call/struct3.c A Modules/_ctypes/libffi/testsuite/libffi.call/nested_struct1.c A Modules/_ctypes/libffi/testsuite/libffi.call/struct5.c A Modules/_ctypes/libffi/testsuite/libffi.call/err_bad_abi.c A Modules/_ctypes/libffi/testsuite/libffi.call/nested_struct3.c A Modules/_ctypes/libffi/testsuite/libffi.call/cls_7_1_byte.c A Modules/_ctypes/libffi/testsuite/libffi.call/nested_struct5.c A Modules/_ctypes/libffi/testsuite/libffi.call/cls_double.c A Modules/_ctypes/libffi/testsuite/libffi.call/struct7.c A Modules/_ctypes/libffi/testsuite/libffi.call/return_sl.c A Modules/_ctypes/libffi/testsuite/libffi.call/nested_struct7.c A Modules/_ctypes/libffi/testsuite/libffi.call/struct9.c A Modules/_ctypes/libffi/testsuite/libffi.call/cls_sint.c A Modules/_ctypes/libffi/testsuite/libffi.call/nested_struct9.c A Modules/_ctypes/libffi/testsuite/libffi.call/cls_pointer.c A Modules/_ctypes/libffi/testsuite/libffi.call/many_win32.c A Modules/_ctypes/libffi/testsuite/libffi.call/cls_20byte1.c A Modules/_ctypes/libffi/testsuite/libffi.call/cls_multi_sshortchar.c A Modules/_ctypes/libffi/testsuite/libffi.call/return_fl.c A Modules/_ctypes/libffi/testsuite/libffi.call/cls_align_sint64.c A Modules/_ctypes/libffi/testsuite/libffi.call/many.c A Modules/_ctypes/libffi/testsuite/libffi.call/strlen.c A Modules/_ctypes/libffi/testsuite/libffi.call/cls_3byte2.c A Modules/_ctypes/libffi/testsuite/libffi.call/return_ldl.c A Modules/_ctypes/libffi/testsuite/libffi.call/stret_large.c A Modules/_ctypes/libffi/testsuite/libffi.call/cls_multi_schar.c A Modules/_ctypes/libffi/testsuite/libffi.call/cls_multi_uchar.c A Modules/_ctypes/libffi/testsuite/libffi.call/cls_9byte1.c A Modules/_ctypes/libffi/testsuite/libffi.call/err_bad_typedef.c A Modules/_ctypes/libffi/testsuite/libffi.call/cls_19byte.c A Modules/_ctypes/libffi/testsuite/libffi.call/cls_align_float.c A Modules/_ctypes/libffi/testsuite/libffi.call/closure_fn1.c A Modules/_ctypes/libffi/testsuite/libffi.call/cls_align_longdouble_split.c A Modules/_ctypes/libffi/testsuite/libffi.call/problem1.c A Modules/_ctypes/libffi/testsuite/libffi.call/return_fl1.c A Modules/_ctypes/libffi/testsuite/libffi.call/closure_fn3.c A Modules/_ctypes/libffi/testsuite/libffi.call/return_dbl2.c A Modules/_ctypes/libffi/testsuite/libffi.call/cls_sshort.c A Modules/_ctypes/libffi/testsuite/libffi.call/return_fl3.c A Modules/_ctypes/libffi/testsuite/libffi.call/closure_fn5.c A Modules/_ctypes/libffi/testsuite/libffi.call/cls_align_double.c A Modules/_ctypes/libffi/testsuite/libffi.call/cls_2byte.c A Modules/_ctypes/libffi/testsuite/libffi.call/promotion.c A Modules/_ctypes/libffi/testsuite/libffi.call/nested_struct.c A Modules/_ctypes/libffi/testsuite/libffi.call/float2.c A Modules/_ctypes/libffi/testsuite/libffi.call/nested_struct10.c A Modules/_ctypes/libffi/testsuite/libffi.call/return_ll1.c A Modules/_ctypes/libffi/testsuite/libffi.call/cls_4byte.c A Modules/_ctypes/libffi/testsuite/libffi.call/float4.c A Modules/_ctypes/libffi/testsuite/libffi.call/cls_6byte.c A Modules/_ctypes/libffi/testsuite/libffi.call/cls_longdouble.c A Modules/_ctypes/libffi/testsuite/libffi.call/huge_struct.c A Modules/_ctypes/libffi/testsuite/libffi.call/cls_8byte.c A Modules/_ctypes/libffi/testsuite/libffi.call/cls_multi_sshort.c A Modules/_ctypes/libffi/testsuite/libffi.call/cls_align_uint32.c A Modules/_ctypes/libffi/testsuite/libffi.call/cls_align_sint16.c A Modules/_ctypes/libffi/testsuite/libffi.call/cls_double_va.c A Modules/_ctypes/libffi/testsuite/libffi.call/return_sc.c A Modules/_ctypes/libffi/testsuite/libffi.call/float.c A Modules/_ctypes/libffi/testsuite/libffi.call/cls_20byte.c A Modules/_ctypes/libffi/testsuite/libffi.call/cls_float.c A Modules/_ctypes/libffi/testsuite/libffi.call/struct2.c A Modules/_ctypes/libffi/testsuite/libffi.call/cls_pointer_stack.c A Modules/_ctypes/libffi/testsuite/libffi.call/cls_5_1_byte.c A Modules/_ctypes/libffi/testsuite/libffi.call/struct4.c A Modules/_ctypes/libffi/testsuite/libffi.call/nested_struct2.c A Modules/_ctypes/libffi/testsuite/libffi.call/cls_24byte.c A Modules/_ctypes/libffi/testsuite/libffi.call/struct6.c A Modules/_ctypes/libffi/testsuite/libffi.call/nested_struct4.c A Modules/_ctypes/libffi/testsuite/libffi.call/closure_loc_fn0.c A Modules/_ctypes/libffi/testsuite/libffi.call/struct8.c A Modules/_ctypes/libffi/testsuite/libffi.call/nested_struct6.c A Modules/_ctypes/libffi/testsuite/libffi.call/testclosure.c A Modules/_ctypes/libffi/testsuite/libffi.call/nested_struct8.c A Modules/_ctypes/libffi/testsuite/libffi.call/cls_64byte.c A Modules/_ctypes/libffi/testsuite/libffi.call/return_ul.c A Modules/_ctypes/libffi/testsuite/libffi.call/cls_uint.c A Modules/_ctypes/libffi/testsuite/libffi.call/cls_dbls_struct.c A Modules/_ctypes/libffi/testsuite/libffi.call/strlen_win32.c A Modules/_ctypes/libffi/testsuite/libffi.call/pyobjc-tc.c A Modules/_ctypes/libffi/testsuite/libffi.call/stret_large2.c A Modules/_ctypes/libffi/testsuite/libffi.call/cls_multi_ushortchar.c A Modules/_ctypes/libffi/testsuite/libffi.call/return_dbl.c A Modules/_ctypes/libffi/testsuite/libffi.call/cls_schar.c A Modules/_ctypes/libffi/testsuite/libffi.call/cls_uchar.c A Modules/_ctypes/libffi/testsuite/libffi.call/cls_align_uint64.c A Modules/_ctypes/libffi/testsuite/libffi.call/cls_align_longdouble.c A Modules/_ctypes/libffi/testsuite/libffi.call/cls_ulonglong.c A Modules/_ctypes/libffi/testsuite/libffi.call/cls_1_1byte.c A Modules/_ctypes/libffi/testsuite/libffi.call/return_ll.c A Modules/_ctypes/libffi/testsuite/libffi.call/cls_3_1byte.c A Modules/_ctypes/libffi/testsuite/libffi.call/cls_12byte.c A Modules/_ctypes/libffi/testsuite/libffi.call/cls_4_1byte.c A Modules/_ctypes/libffi/testsuite/libffi.call/cls_3byte1.c A Modules/_ctypes/libffi/testsuite/libffi.call/ffitest.h A Modules/_ctypes/libffi/testsuite/libffi.call/cls_6_1_byte.c A Modules/_ctypes/libffi/testsuite/libffi.call/cls_16byte.c A Modules/_ctypes/libffi/testsuite/libffi.call/cls_18byte.c A Modules/_ctypes/libffi/testsuite/libffi.call/closure_fn0.c A Modules/_ctypes/libffi/testsuite/libffi.call/cls_9byte2.c A Modules/_ctypes/libffi/testsuite/libffi.call/cls_longdouble_va.c A Modules/_ctypes/libffi/testsuite/libffi.call/return_dbl1.c A Modules/_ctypes/libffi/testsuite/libffi.call/closure_fn2.c A Modules/_ctypes/libffi/testsuite/libffi.call/closure_stdcall.c A Modules/_ctypes/libffi/testsuite/libffi.call/return_fl2.c A Modules/_ctypes/libffi/testsuite/libffi.call/stret_medium2.c A Modules/_ctypes/libffi/testsuite/libffi.call/closure_fn4.c A Modules/_ctypes/libffi/testsuite/libffi.call/negint.c A Modules/_ctypes/libffi/testsuite/libffi.call/cls_ushort.c A Modules/_ctypes/libffi/testsuite/libffi.call/call.exp A Modules/_ctypes/libffi/testsuite/libffi.call/closure_fn6.c A Modules/_ctypes/libffi/testsuite/libffi.call/float1.c A Modules/_ctypes/libffi/testsuite/libffi.call/float3.c A Modules/_ctypes/libffi/testsuite/libffi.call/cls_5byte.c A Modules/_ctypes/libffi/testsuite/libffi.call/cls_7byte.c A Modules/_ctypes/libffi/testsuite/libffi.call/cls_align_pointer.c A Modules/_ctypes/libffi/testsuite/libffi.call/cls_align_sint32.c A Modules/_ctypes/libffi/testsuite/config A Modules/_ctypes/libffi/testsuite/config/default.exp A Modules/_ctypes/libffi/testsuite/lib A Modules/_ctypes/libffi/testsuite/lib/target-libpath.exp A Modules/_ctypes/libffi/testsuite/lib/wrapper.exp A Modules/_ctypes/libffi/testsuite/lib/libffi-dg.exp A Modules/_ctypes/libffi/testsuite/Makefile.am A Modules/_ctypes/libffi/testsuite/libffi.special A Modules/_ctypes/libffi/testsuite/libffi.special/unwindtest_ffi_call.cc A Modules/_ctypes/libffi/testsuite/libffi.special/unwindtest.cc A Modules/_ctypes/libffi/testsuite/libffi.special/special.exp A Modules/_ctypes/libffi/testsuite/libffi.special/ffitestcxx.h M Modules/_ctypes/libffi/README A Modules/_ctypes/libffi/libffi.pc.in M Modules/_ctypes/libffi/Makefile.am M Modules/_ctypes/libffi/missing A Modules/_ctypes/libffi/ChangeLog.v1 M Modules/_ctypes/libffi/aclocal.m4 M Modules/_ctypes/libffi.diff ........ r78969 | matthias.klose | 2010-03-15 01:36:18 +0100 (Mo, 15 M?r 2010) | 7 lines Backport from the libffi trunk: 2010-02-15 Matthias Klose * src/arm/sysv.S (__ARM_ARCH__): Define for processor __ARM_ARCH_7EM__. ........ r78970 | benjamin.peterson | 2010-03-15 03:58:24 +0100 (Mo, 15 M?r 2010) | 1 line this little exception dance is pointless ........ r78971 | benjamin.peterson | 2010-03-15 04:00:35 +0100 (Mo, 15 M?r 2010) | 1 line remove mac 9 code ........ r78972 | benjamin.peterson | 2010-03-15 04:02:37 +0100 (Mo, 15 M?r 2010) | 1 line clean up files correctly ........ r78974 | matthias.klose | 2010-03-15 13:46:18 +0100 (Mo, 15 M?r 2010) | 2 lines - Issue #6949: Allow the _bsddb extension to be built with db-4.8.x. ........ r78982 | florent.xicluna | 2010-03-15 15:00:58 +0100 (Mo, 15 M?r 2010) | 2 lines Remove py3k deprecation warnings from these Unicode tools. ........ r78983 | matthias.klose | 2010-03-15 18:44:12 +0100 (Mo, 15 M?r 2010) | 2 lines - Issue #8140: extend compileall to compile single files. Add -i option. ........ r78985 | matthias.klose | 2010-03-15 19:00:01 +0100 (Mo, 15 M?r 2010) | 2 lines - Fix typo in Lib/compileall.py(__all__). ........ r78986 | florent.xicluna | 2010-03-15 19:08:58 +0100 (Mo, 15 M?r 2010) | 3 lines Issue #7783 and #7787: open_urlresource invalidates the outdated files from the local cache. Use this feature to fix test_normalization. ........ r78996 | martin.v.loewis | 2010-03-16 19:49:28 +0100 (Di, 16 M?r 2010) | 1 line Integrate merge.py into msi.py. ........ Modified: python/branches/release26-maint/ (props changed) From python-checkins at python.org Wed May 19 16:25:58 2010 From: python-checkins at python.org (georg.brandl) Date: Wed, 19 May 2010 16:25:58 +0200 (CEST) Subject: [Python-checkins] r81345 - in python/branches/release26-maint: Doc/library/warnings.rst Message-ID: <20100519142558.C9DB6C73B@mail.python.org> Author: georg.brandl Date: Wed May 19 16:25:58 2010 New Revision: 81345 Log: Merged revisions 79607-79608 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r79607 | andrew.kuchling | 2010-04-02 19:48:23 +0200 (Fr, 02 Apr 2010) | 1 line #6647: document that catch_warnings is not thread-safe ........ r79608 | andrew.kuchling | 2010-04-02 19:54:26 +0200 (Fr, 02 Apr 2010) | 1 line #6647: add note to two examples ........ Modified: python/branches/release26-maint/ (props changed) python/branches/release26-maint/Doc/library/warnings.rst Modified: python/branches/release26-maint/Doc/library/warnings.rst ============================================================================== --- python/branches/release26-maint/Doc/library/warnings.rst (original) +++ python/branches/release26-maint/Doc/library/warnings.rst Wed May 19 16:25:58 2010 @@ -178,7 +178,10 @@ While within the context manager all warnings will simply be ignored. This allows you to use known-deprecated code without having to see the warning while not suppressing the warning for other code that might not be aware of its use -of deprecated code. +of deprecated code. Note: this can only be guaranteed in a single-threaded +application. If two or more threads use the :class:`catch_warnings` context +manager at the same time, the behavior is undefined. + .. _warning-testing: @@ -216,7 +219,9 @@ when the context was entered. This prevents tests from changing the warnings filter in unexpected ways between tests and leading to indeterminate test results. The :func:`showwarning` function in the module is also restored to -its original value. +its original value. Note: this can only be guaranteed in a single-threaded +application. If two or more threads use the :class:`catch_warnings` context +manager at the same time, the behavior is undefined. When testing multiple operations that raise the same kind of warning, it is important to test them in a manner that confirms each operation is raising @@ -358,6 +363,14 @@ .. note:: + The :class:`catch_warnings` manager works by replacing and + then later restoring the module's + :func:`showwarning` function and internal list of filter + specifications. This means the context manager is modifying + global state and therefore is not thread-safe. + + .. note:: + In Python 3.0, the arguments to the constructor for :class:`catch_warnings` are keyword-only arguments. From python-checkins at python.org Wed May 19 17:20:36 2010 From: python-checkins at python.org (stefan.krah) Date: Wed, 19 May 2010 17:20:36 +0200 (CEST) Subject: [Python-checkins] r81346 - python/branches/py3k-cdecimal/Modules/cdecimal/cdecimal.c Message-ID: <20100519152036.4A50AC7A8@mail.python.org> Author: stefan.krah Date: Wed May 19 17:20:36 2010 New Revision: 81346 Log: Follow decimal.py: sNaN comparisons now always signal. Modified: python/branches/py3k-cdecimal/Modules/cdecimal/cdecimal.c Modified: python/branches/py3k-cdecimal/Modules/cdecimal/cdecimal.c ============================================================================== --- python/branches/py3k-cdecimal/Modules/cdecimal/cdecimal.c (original) +++ python/branches/py3k-cdecimal/Modules/cdecimal/cdecimal.c Wed May 19 17:20:36 2010 @@ -3599,20 +3599,27 @@ PyDecObject *b; uint32_t status = 0; mpd_context_t *ctx; + int a_issnan, b_issnan; int r; ctx = mpd_ctx(); CONVERT_BINOP(v, w, &a, &b, ctx); + a_issnan = mpd_issnan(a->dec); + b_issnan = mpd_issnan(b->dec); + r = mpd_qcmp(a->dec, b->dec, &status); Py_DECREF(a); Py_DECREF(b); - /* NaNs always signal, except for Py_EQ and Py_NE. */ - if (op != Py_EQ && op != Py_NE && dec_addstatus(ctx, status)) { - return NULL; - } - /* NaN comparison with Py_EQ, Py_NE, or InvalidOperation disabled. */ if (r == INT_MAX) { + /* sNaNs or op={le,ge,lt,gt} always signal. */ + if (a_issnan || b_issnan || (op != Py_EQ && op != Py_NE)) { + if (dec_addstatus(ctx, status)) { + return NULL; + } + } + /* qNaN comparison with op={eq,ne} or comparison + * with InvalidOperation disabled. */ return (op == Py_NE) ? Dec_INCREF_TRUE : Dec_INCREF_FALSE; } From python-checkins at python.org Wed May 19 17:21:39 2010 From: python-checkins at python.org (stefan.krah) Date: Wed, 19 May 2010 17:21:39 +0200 (CEST) Subject: [Python-checkins] r81347 - python/branches/py3k-cdecimal/Lib/test/decimal_tests.py Message-ID: <20100519152139.8465FC7A8@mail.python.org> Author: stefan.krah Date: Wed May 19 17:21:39 2010 New Revision: 81347 Log: Merge changes from test_decimal.py Modified: python/branches/py3k-cdecimal/Lib/test/decimal_tests.py Modified: python/branches/py3k-cdecimal/Lib/test/decimal_tests.py ============================================================================== --- python/branches/py3k-cdecimal/Lib/test/decimal_tests.py (original) +++ python/branches/py3k-cdecimal/Lib/test/decimal_tests.py Wed May 19 17:21:39 2010 @@ -24,9 +24,9 @@ with the corresponding argument. """ -import glob import math import os, sys +import operator import pickle, copy import unittest import numbers @@ -98,6 +98,12 @@ # Useful Test Constant Signals = tuple(getcontext().flags.keys()) +# Signals ordered with respect to precedence: when an operation +# produces multiple signals, signals occurring later in the list +# should be handled before those occurring earlier in the list. +OrderedSignals = (Clamped, Rounded, Inexact, Subnormal, + Underflow, Overflow, DivisionByZero, InvalidOperation) + # Tests are built around these assumed context defaults. # test_main() restores the original context. def init(): @@ -110,6 +116,11 @@ ) setcontext(DefaultTestContext) +# decorator for skipping tests on non-IEEE 754 platforms +requires_IEEE_754 = unittest.skipUnless( + float.__getformat__("double").startswith("IEEE"), + "test requires IEEE 754 doubles") + TESTDATADIR = 'decimaltestdata' if __name__ == '__main__': file = sys.argv[0] @@ -445,6 +456,24 @@ else: self.fail("Did not raise %s in %s" % (error, s)) self.context.traps[error] = 0 + + # as above, but add traps cumulatively, to check precedence + ordered_errors = [e for e in OrderedSignals if e in theirexceptions] + for error in ordered_errors: + self.context.traps[error] = 1 + try: + funct(*vals) + except error: + pass + except Signals as e: + self.fail("Raised %s in %s; expected %s" % + (type(e), s, error)) + else: + self.fail("Did not raise %s in %s" % (error, s)) + # reset traps + for error in ordered_errors: + self.context.traps[error] = 0 + if DEBUG: print("--", self.context) try: @@ -586,6 +615,12 @@ self.assertRaises(ValueError, Decimal, (1, (4, 10, 4, 9, 1), 2) ) self.assertRaises(TypeError, Decimal, (1, (4, 3, 4, 'a', 1), 2) ) + def test_explicit_from_bool(self): + self.assertIs(bool(Decimal(0)), False) + self.assertIs(bool(Decimal(1)), True) + self.assertEqual(Decimal(False), Decimal(0)) + self.assertEqual(Decimal(True), Decimal(1)) + def test_explicit_from_Decimal(self): #positive @@ -608,6 +643,28 @@ e = Decimal(d) self.assertEqual(str(e), '0') + @unittest.skipIf(HAVE_CDECIMAL, "not yet implemented") + @requires_IEEE_754 + def test_explicit_from_float(self): + r = Decimal(0.1) + self.assertEqual(type(r), Decimal) + self.assertEqual(str(r), + '0.1000000000000000055511151231257827021181583404541015625') + self.assertTrue(Decimal(float('nan')).is_qnan()) + self.assertTrue(Decimal(float('inf')).is_infinite()) + self.assertTrue(Decimal(float('-inf')).is_infinite()) + self.assertEqual(str(Decimal(float('nan'))), + str(Decimal('NaN'))) + self.assertEqual(str(Decimal(float('inf'))), + str(Decimal('Infinity'))) + self.assertEqual(str(Decimal(float('-inf'))), + str(Decimal('-Infinity'))) + self.assertEqual(str(Decimal(float('-0.0'))), + str(Decimal('-0'))) + for i in range(200): + x = random.expovariate(0.01) * (random.random() * 2.0 - 1.0) + self.assertEqual(x, float(Decimal(x))) # roundtrip + def test_explicit_context_create_decimal(self): nc = copy.copy(getcontext()) @@ -1179,18 +1236,56 @@ self.assertEqual(abs(Decimal(45)), abs(Decimal(-45))) # abs def test_nan_comparisons(self): + # comparisons involving signaling nans signal InvalidOperation + + # order comparisons (<, <=, >, >=) involving only quiet nans + # also signal InvalidOperation + + # equality comparisons (==, !=) involving only quiet nans + # don't signal, but return False or True respectively. + n = Decimal('NaN') s = Decimal('sNaN') i = Decimal('Inf') f = Decimal('2') - for x, y in [(n, n), (n, i), (i, n), (n, f), (f, n), - (s, n), (n, s), (s, i), (i, s), (s, f), (f, s), (s, s)]: - self.assertTrue(x != y) - self.assertTrue(not (x == y)) - self.assertTrue(not (x < y)) - self.assertTrue(not (x <= y)) - self.assertTrue(not (x > y)) - self.assertTrue(not (x >= y)) + + qnan_pairs = (n, n), (n, i), (i, n), (n, f), (f, n) + snan_pairs = (s, n), (n, s), (s, i), (i, s), (s, f), (f, s), (s, s) + order_ops = operator.lt, operator.le, operator.gt, operator.ge + equality_ops = operator.eq, operator.ne + + # results when InvalidOperation is not trapped + for x, y in qnan_pairs + snan_pairs: + for op in order_ops + equality_ops: + got = op(x, y) + expected = True if op is operator.ne else False + self.assertIs(expected, got, + "expected {0!r} for operator.{1}({2!r}, {3!r}); " + "got {4!r}".format( + expected, op.__name__, x, y, got)) + + # repeat the above, but this time trap the InvalidOperation + with localcontext() as ctx: + ctx.traps[InvalidOperation] = 1 + + for x, y in qnan_pairs: + for op in equality_ops: + got = op(x, y) + expected = True if op is operator.ne else False + self.assertIs(expected, got, + "expected {0!r} for " + "operator.{1}({2!r}, {3!r}); " + "got {4!r}".format( + expected, op.__name__, x, y, got)) + + for x, y in snan_pairs: + for op in equality_ops: + self.assertRaises(InvalidOperation, operator.eq, x, y) + self.assertRaises(InvalidOperation, operator.ne, x, y) + + for x, y in qnan_pairs + snan_pairs: + for op in order_ops: + self.assertRaises(InvalidOperation, op, x, y) def test_copy_sign(self): d = Decimal(1).copy_sign(Decimal(-2)) @@ -1279,18 +1374,18 @@ dc = Decimal('45') #two Decimals - self.assertTrue(dc > da) - self.assertTrue(dc >= da) - self.assertTrue(da < dc) - self.assertTrue(da <= dc) + self.assertGreater(dc, da) + self.assertGreaterEqual(dc, da) + self.assertLess(da, dc) + self.assertLessEqual(da, dc) self.assertEqual(da, db) - self.assertTrue(da != dc) - self.assertTrue(da <= db) - self.assertTrue(da >= db) + self.assertNotEqual(da, dc) + self.assertLessEqual(da, db) + self.assertGreaterEqual(da, db) #a Decimal and an int - self.assertTrue(dc > 23) - self.assertTrue(23 < dc) + self.assertGreater(dc, 23) + self.assertLess(23, dc) self.assertEqual(dc, 45) #a Decimal and uncomparable @@ -1306,6 +1401,24 @@ a.sort() self.assertEqual(a, b) + @unittest.skipIf(HAVE_CDECIMAL, "not yet implemented") + def test_decimal_float_comparison(self): + da = Decimal('0.25') + db = Decimal('3.0') + self.assertLess(da, 3.0) + self.assertLessEqual(da, 3.0) + self.assertGreater(db, 0.25) + self.assertGreaterEqual(db, 0.25) + self.assertNotEqual(da, 1.5) + self.assertEqual(da, 0.25) + self.assertGreater(3.0, da) + self.assertGreaterEqual(3.0, da) + self.assertLess(0.25, db) + self.assertLessEqual(0.25, db) + self.assertNotEqual(0.25, db) + self.assertEqual(3.0, db) + self.assertNotEqual(0.1, Decimal('0.1')) + def test_copy_and_deepcopy_methods(self): d = Decimal('43.24') c = copy.copy(d) @@ -1316,6 +1429,11 @@ def test_hash_method(self): #just that it's hashable hash(Decimal(23)) + hash(Decimal('Infinity')) + hash(Decimal('-Infinity')) + if not HAVE_CDECIMAL: # XXX not implemented + hash(Decimal('nan123')) + hash(Decimal('-NaN')) test_values = [Decimal(sign*(2**m + n)) for m in [0, 14, 15, 16, 17, 30, 31, @@ -1354,6 +1472,16 @@ self.assertTrue(hash(Decimal('Inf'))) self.assertTrue(hash(Decimal('-Inf'))) + if not HAVE_CDECIMAL: # XXX float comparisons not implemented yet. + # check that the hashes of a Decimal float match when they + # represent exactly the same values + test_strings = ['inf', '-Inf', '0.0', '-.0e1', + '34.0', '2.5', '112390.625', '-0.515625'] + for s in test_strings: + f = float(s) + d = Decimal(s) + self.assertEqual(hash(f), hash(d)) + # check that the value of the hash doesn't depend on the # current context (issue #1757) c = getcontext() @@ -1379,16 +1507,16 @@ l2 = 28 #between Decimals - self.assertTrue(min(d1,d2) is d1) - self.assertTrue(min(d2,d1) is d1) - self.assertTrue(max(d1,d2) is d2) - self.assertTrue(max(d2,d1) is d2) + self.assertIs(min(d1,d2), d1) + self.assertIs(min(d2,d1), d1) + self.assertIs(max(d1,d2), d2) + self.assertIs(max(d2,d1), d2) #between Decimal and long - self.assertTrue(min(d1,l2) is d1) - self.assertTrue(min(l2,d1) is d1) - self.assertTrue(max(l1,d2) is d2) - self.assertTrue(max(d2,l1) is d2) + self.assertIs(min(d1,l2), d1) + self.assertIs(min(l2,d1), d1) + self.assertIs(max(l1,d2), d2) + self.assertIs(max(d2,l1), d2) def test_as_nonzero(self): #as false @@ -1651,10 +1779,10 @@ d1 = MyDecimal(1) d2 = MyDecimal(2) d = d1 + d2 - self.assertTrue(type(d) is Decimal) + self.assertIs(type(d), Decimal) d = d1.max(d2) - self.assertTrue(type(d) is Decimal) + self.assertIs(type(d), Decimal) def test_implicit_context(self): # Check results when context given implicitly. (Issue 2478) @@ -2272,9 +2400,9 @@ with localcontext() as enter_ctx: set_ctx = getcontext() final_ctx = getcontext() - self.assertTrue(orig_ctx is final_ctx, 'did not restore context correctly') - self.assertTrue(orig_ctx is not set_ctx, 'did not copy the context') - self.assertTrue(set_ctx is enter_ctx, '__enter__ returned wrong context') + self.assertIs(orig_ctx, final_ctx, 'did not restore context correctly') + self.assertIsNot(orig_ctx, set_ctx, 'did not copy the context') + self.assertIs(set_ctx, enter_ctx, '__enter__ returned wrong context') def test_localcontextarg(self): # Use a copy of the supplied context in the block @@ -2283,10 +2411,10 @@ with localcontext(new_ctx) as enter_ctx: set_ctx = getcontext() final_ctx = getcontext() - self.assertTrue(orig_ctx is final_ctx, 'did not restore context correctly') - self.assertTrue(set_ctx.prec == new_ctx.prec, 'did not set correct context') - self.assertTrue(new_ctx is not set_ctx, 'did not copy the context') - self.assertTrue(set_ctx is enter_ctx, '__enter__ returned wrong context') + self.assertIs(orig_ctx, final_ctx, 'did not restore context correctly') + self.assertEqual(set_ctx.prec, new_ctx.prec, 'did not set correct context') + self.assertIsNot(new_ctx, set_ctx, 'did not copy the context') + self.assertIs(set_ctx, enter_ctx, '__enter__ returned wrong context') class ContextFlags(unittest.TestCase): def test_flags_irrelevant(self): From python-checkins at python.org Wed May 19 17:26:45 2010 From: python-checkins at python.org (stefan.krah) Date: Wed, 19 May 2010 17:26:45 +0200 (CEST) Subject: [Python-checkins] r81348 - python/branches/py3k-cdecimal/Lib/test/decimal_extended_tests/deccheck.py Message-ID: <20100519152645.D6553EC22@mail.python.org> Author: stefan.krah Date: Wed May 19 17:26:45 2010 New Revision: 81348 Log: Changes in the hash function will be implemented once the new unified hash is committed. For now, skip known differences. Modified: python/branches/py3k-cdecimal/Lib/test/decimal_extended_tests/deccheck.py Modified: python/branches/py3k-cdecimal/Lib/test/decimal_extended_tests/deccheck.py ============================================================================== --- python/branches/py3k-cdecimal/Lib/test/decimal_extended_tests/deccheck.py (original) +++ python/branches/py3k-cdecimal/Lib/test/decimal_extended_tests/deccheck.py Wed May 19 17:26:45 2010 @@ -341,6 +341,18 @@ def __init__(self): pass + if py_minor >= 2: + def __hash__(self, result, operands): + c = operands[0] + if c.mpd.is_infinite(): + # Hashing infinities changed in 3.2 + return True + # If a Decimal instance is exactly representable as a float + # then (in 3.2) its hash matches that of the float. + f = float(c.dec) + if Decimal.from_float(f) == c.dec: + return True + def default(self, result, operands): return False @@ -349,9 +361,9 @@ def cdec_known_disagreement(result, funcname, operands): return getattr(dhandler_cdec, funcname, dhandler_cdec.default)(result, operands) -#dhandler_obj = dHandlerObj() -#def obj_known_disagreement(result, funcname, operands): -# return getattr(dhandler_obj, funcname, dhandler_obj.default)(result, operands) +dhandler_obj = dHandlerObj() +def obj_known_disagreement(result, funcname, operands): + return getattr(dhandler_obj, funcname, dhandler_obj.default)(result, operands) @@ -360,8 +372,8 @@ result[0] and result[1] as well as the context flags have the same values.""" if result[0] != result[1] or not context.assert_eq_status(): - #if obj_known_disagreement(result, funcname, operands): - # return # skip known disagreements + if obj_known_disagreement(result, funcname, operands): + return # skip known disagreements raise CdecException(result, funcname, operands) From python-checkins at python.org Wed May 19 17:30:17 2010 From: python-checkins at python.org (stefan.krah) Date: Wed, 19 May 2010 17:30:17 +0200 (CEST) Subject: [Python-checkins] r81349 - in python/branches/py3k-cdecimal: Doc/distutils/sourcedist.rst Doc/library/os.rst Doc/library/ssl.rst Doc/library/tarfile.rst Doc/library/test.rst Doc/library/urllib.request.rst Lib/asyncore.py Lib/distutils/command/sdist.py Lib/distutils/tests/test_sdist.py Lib/importlib/_bootstrap.py Lib/importlib/test/source/test_file_loader.py Lib/os.py Lib/ssl.py Lib/subprocess.py Lib/tarfile.py Lib/test/capath Lib/test/list_tests.py Lib/test/test_asyncore.py Lib/test/test_getargs2.py Lib/test/test_import.py Lib/test/test_os.py Lib/test/test_ssl.py Lib/test/test_subprocess.py Lib/test/test_sys.py Lib/test/test_tarfile.py Lib/test/testtar.tar Lib/urllib/parse.py Lib/urllib/request.py Misc/NEWS Modules/_cursesmodule.c Modules/_io/textio.c Modules/_sqlite/connection.c Modules/_sqlite/cursor.c Modules/_sqlite/row.c Modules/_sqlite/statement.c Modules/_ssl.c Modules/_testcapimodule.c Modules/main.c Objects/moduleobject.c Objects/object.c Objects/typeobject.c Parser/asdl.py Parser/printgrammar.c Python/bltinmodule.c Python/getargs.c Python/graminit.c Python/pythonrun.c Message-ID: <20100519153017.64B72FCC2@mail.python.org> Author: stefan.krah Date: Wed May 19 17:30:16 2010 New Revision: 81349 Log: Merged revisions 81214-81215,81218-81219,81222,81226,81231,81233-81237,81239,81242,81246-81247,81249-81253,81257-81258,81263,81266-81267,81269-81273,81276,81281,81283,81288,81290-81292,81299,81314,81319-81325 via svnmerge from svn+ssh://pythondev at svn.python.org/python/branches/py3k ................ r81214 | brett.cannon | 2010-05-16 00:20:16 +0200 (Sun, 16 May 2010) | 2 lines A test was not guaranteeing cleanup in the face of an exception. ................ r81215 | victor.stinner | 2010-05-16 00:23:53 +0200 (Sun, 16 May 2010) | 12 lines Recorded merge of revisions 81213 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r81213 | victor.stinner | 2010-05-16 00:19:27 +0200 (dim., 16 mai 2010) | 5 lines reindent _cursesmodule.c Use untabify.py + emacs (python3 mode) + manual editions for Py_BEGIN_ALLOW_THREADS / Py_END_ALLOW_THREADS ........ ................ r81218 | brett.cannon | 2010-05-16 00:51:45 +0200 (Sun, 16 May 2010) | 1 line Fix a comment to state the right thing. ................ r81219 | brett.cannon | 2010-05-16 00:53:24 +0200 (Sun, 16 May 2010) | 4 lines Make test_module_with_large_stack as an expected failure because of a change in importlib that is causing it to fail. Work to fix it is being tracked in issue 8727. ................ r81222 | victor.stinner | 2010-05-16 01:00:51 +0200 (Sun, 16 May 2010) | 11 lines Merged revisions 81220 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r81220 | victor.stinner | 2010-05-16 00:55:28 +0200 (dim., 16 mai 2010) | 4 lines Use 4-spaces for indentation (instead of tabs) in pgen outputs Regenerate (reindent) Python/graminit.c ........ ................ r81226 | victor.stinner | 2010-05-16 02:36:38 +0200 (Sun, 16 May 2010) | 11 lines Merged revisions 81224 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r81224 | victor.stinner | 2010-05-16 02:34:40 +0200 (dim., 16 mai 2010) | 4 lines Use with open() as fo: ... instead of try: fo = open(...) finally: fo.close() fo is not set if the open() fails. ........ ................ r81231 | antoine.pitrou | 2010-05-16 16:19:41 +0200 (Sun, 16 May 2010) | 9 lines Merged revisions 81229 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r81229 | antoine.pitrou | 2010-05-16 16:16:56 +0200 (dim., 16 mai 2010) | 3 lines Document that SSL v2 is insecure. ........ ................ r81233 | antoine.pitrou | 2010-05-16 20:19:27 +0200 (Sun, 16 May 2010) | 3 lines Issue #8550: Add first class `SSLContext` objects to the ssl module. ................ r81234 | antoine.pitrou | 2010-05-16 21:22:44 +0200 (Sun, 16 May 2010) | 3 lines Followup on r81233: fix test_ssl with OpenSSL < 1.0.0. ................ r81235 | antoine.pitrou | 2010-05-16 21:56:32 +0200 (Sun, 16 May 2010) | 3 lines Fix (hopefully) the remaining test_ssl buildbot failures ................ r81236 | antoine.pitrou | 2010-05-16 22:35:03 +0200 (Sun, 16 May 2010) | 3 lines Do not fail if ssl fails to import ................ r81237 | victor.stinner | 2010-05-16 23:23:48 +0200 (Sun, 16 May 2010) | 3 lines Issue #8477: _ssl._test_decode_cert() supports str with surrogates and bytes for the filename ................ r81239 | victor.stinner | 2010-05-16 23:36:37 +0200 (Sun, 16 May 2010) | 2 lines Issue #8477: ssl.RAND_egd() supports str with surrogates and bytes for the path ................ r81242 | antoine.pitrou | 2010-05-17 01:14:22 +0200 (Mon, 17 May 2010) | 10 lines Merged revisions 81241 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r81241 | antoine.pitrou | 2010-05-17 01:11:46 +0200 (lun., 17 mai 2010) | 4 lines Clear the OpenSSL error queue each time an error is signalled. When the error queue is not emptied, strange things can happen on the next SSL call, depending on the OpenSSL version. ........ ................ r81246 | antoine.pitrou | 2010-05-17 01:46:26 +0200 (Mon, 17 May 2010) | 3 lines "xyzzy" is not a silly enough name for some OpenSSL versions to report an error ................ r81247 | victor.stinner | 2010-05-17 02:14:53 +0200 (Mon, 17 May 2010) | 9 lines test_os: cleanup test_internal_execvpe() and os._execvpe() mockup * Replace os.defpath instead of os.get_exec_path() to test also os.get_exec_path() * Use contextlib.contextmanager, move the mockup outside the class, and the mockup returns directly the call list object * Use two different contexts for the two tests * Use more revelant values and names ................ r81249 | victor.stinner | 2010-05-17 02:18:34 +0200 (Mon, 17 May 2010) | 2 lines Oops, my patch on subprocess is not merged yet: fix my previous commit on test_os ................ r81250 | victor.stinner | 2010-05-17 03:13:37 +0200 (Mon, 17 May 2010) | 2 lines Issue #6697: Fix a crash if code of "python -c code" contains surrogates ................ r81251 | victor.stinner | 2010-05-17 03:26:01 +0200 (Mon, 17 May 2010) | 3 lines PyObject_Dump() encodes unicode objects to utf8 with backslashreplace (instead of strict) error handler to escape surrogates ................ r81252 | victor.stinner | 2010-05-17 10:58:51 +0200 (Mon, 17 May 2010) | 6 lines handle_system_exit() flushs files to warranty the output order PyObject_Print() writes into the C object stderr, whereas PySys_WriteStderr() writes into the Python object sys.stderr. Each object has its own buffer, so call sys.stderr.flush() and fflush(stderr). ................ r81253 | victor.stinner | 2010-05-17 11:33:42 +0200 (Mon, 17 May 2010) | 6 lines Fix refleak in internal_print() introduced by myself in r81251 _PyUnicode_AsDefaultEncodedString() uses a magical PyUnicode attribute to automatically destroy PyUnicode_EncodeUTF8() result when the unicode string is destroyed. ................ r81257 | antoine.pitrou | 2010-05-17 12:30:00 +0200 (Mon, 17 May 2010) | 3 lines Try to fix buildbot failures with old OpenSSLs. ................ r81258 | tarek.ziade | 2010-05-17 12:38:53 +0200 (Mon, 17 May 2010) | 9 lines Merged revisions 81255 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r81255 | tarek.ziade | 2010-05-17 12:06:20 +0200 (Mon, 17 May 2010) | 1 line Fixed #8688: Distutils now recalculates MANIFEST everytime. ........ ................ r81263 | tarek.ziade | 2010-05-17 13:01:57 +0200 (Mon, 17 May 2010) | 9 lines Merged revisions 81261 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r81261 | tarek.ziade | 2010-05-17 12:54:43 +0200 (Mon, 17 May 2010) | 1 line upgraded distutils docs w.r.t. the manifest regeneration ........ ................ r81266 | antoine.pitrou | 2010-05-17 16:13:10 +0200 (Mon, 17 May 2010) | 3 lines Typo (thanks Arfrever) ................ r81267 | victor.stinner | 2010-05-17 16:36:43 +0200 (Mon, 17 May 2010) | 2 lines Improve test_exit() error message to analyze sparc failures ................ r81269 | jeffrey.yasskin | 2010-05-17 18:59:23 +0200 (Mon, 17 May 2010) | 4 lines Fix test_capi in !pydebug mode, where my original attempt segfaulted without producing the expected error message. The test only tests what it's supposed to test in pydebug mode though. Fixes issue 8726. ................ r81270 | florent.xicluna | 2010-05-17 19:24:07 +0200 (Mon, 17 May 2010) | 9 lines Merged revision 81259 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r81259 | florent.xicluna | 2010-05-17 12:39:07 +0200 (lun, 17 mai 2010) | 2 lines Slight style cleanup. ........ ................ r81271 | florent.xicluna | 2010-05-17 19:33:07 +0200 (Mon, 17 May 2010) | 11 lines Issue #1285086: Speed up urllib.parse functions: quote, quote_from_bytes, unquote, unquote_to_bytes. Recorded merge of revisions 81265 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r81265 | florent.xicluna | 2010-05-17 15:35:09 +0200 (lun, 17 mai 2010) | 2 lines Issue #1285086: Speed up urllib.quote and urllib.unquote for simple cases. ........ ................ r81272 | florent.xicluna | 2010-05-17 20:01:22 +0200 (Mon, 17 May 2010) | 2 lines Inadvertently removed part of the comment in r81271. ................ r81273 | lars.gustaebel | 2010-05-17 20:02:50 +0200 (Mon, 17 May 2010) | 15 lines Issue #8633: Support for POSIX.1-2008 binary pax headers. tarfile is now able to read and write pax headers with a "hdrcharset=BINARY" record. This record was introduced in POSIX.1-2008 as a method to store unencoded binary strings that cannot be translated to UTF-8. In practice, this is just a workaround that allows a tar implementation to store filenames that do not comply with the current filesystem encoding and thus cannot be decoded correctly. Additionally, tarfile works around a bug in current versions of GNU tar: undecodable filenames are stored as-is in a pax header without a "hdrcharset" record being added. Technically, these headers are invalid, but tarfile manages to read them correctly anyway. ................ r81276 | victor.stinner | 2010-05-17 21:57:40 +0200 (Mon, 17 May 2010) | 4 lines Fix test_main_invalid_unicode() of test_sys for ASCII locale encoding It should fix sparc 3.x and 3.1 failures. ................ r81281 | senthil.kumaran | 2010-05-18 05:26:11 +0200 (Tue, 18 May 2010) | 9 lines Merged revisions 81279 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r81279 | senthil.kumaran | 2010-05-18 08:50:43 +0530 (Tue, 18 May 2010) | 3 lines Fix minor typo. ........ ................ r81283 | senthil.kumaran | 2010-05-18 05:58:36 +0200 (Tue, 18 May 2010) | 3 lines Removing the reference in the docs for overriding _urlopener global value. See Issue8619 for details. ................ r81288 | senthil.kumaran | 2010-05-18 15:48:45 +0200 (Tue, 18 May 2010) | 9 lines Merged revisions 81286 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r81286 | senthil.kumaran | 2010-05-18 19:10:23 +0530 (Tue, 18 May 2010) | 3 lines Doc Fix. Correct link to Zephyr ASDL Abstract page. ........ ................ r81290 | barry.warsaw | 2010-05-18 16:15:20 +0200 (Tue, 18 May 2010) | 2 lines Repair test failure. Bug 8727. ................ r81291 | victor.stinner | 2010-05-18 19:17:23 +0200 (Tue, 18 May 2010) | 5 lines Issue #8513: os.get_exec_path() supports b'PATH' key and bytes value. subprocess.Popen() and os._execvpe() support bytes program name. Add os.supports_bytes_environ flag: True if the native OS type of the environment is bytes (eg. False on Windows). ................ r81292 | victor.stinner | 2010-05-18 19:24:09 +0200 (Tue, 18 May 2010) | 2 lines Add versionadded (3.2) tag to os.supports_bytes_environ documentation ................ r81299 | giampaolo.rodola | 2010-05-18 22:11:58 +0200 (Tue, 18 May 2010) | 9 lines Merged revisions 81294 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r81294 | giampaolo.rodola | 2010-05-18 22:04:31 +0200 (mar, 18 mag 2010) | 1 line Fix issue #8573 (asyncore._strerror bug): fixed os.strerror typo; included NameError in the tuple of expected exception; added test case for asyncore._strerror. ........ ................ r81314 | victor.stinner | 2010-05-19 02:03:09 +0200 (Wed, 19 May 2010) | 2 lines Issue #6697: Fix a crash if a module attribute name contains a surrogate ................ r81319 | victor.stinner | 2010-05-19 02:34:15 +0200 (Wed, 19 May 2010) | 2 lines Issue #6697: Check that _PyUnicode_AsString() result is not NULL ................ r81320 | victor.stinner | 2010-05-19 02:54:06 +0200 (Wed, 19 May 2010) | 2 lines Issue #6697: Fix a crash if a keyword contains a surrogate ................ r81321 | victor.stinner | 2010-05-19 03:06:22 +0200 (Wed, 19 May 2010) | 4 lines Issue #6697: Fix a crash if sys.stdin or sys.stdout encoding contain a surrogate This is *very* unlikely :-) ................ r81322 | victor.stinner | 2010-05-19 03:17:01 +0200 (Wed, 19 May 2010) | 5 lines Issue #6697: Check that _PyUnicode_AsString() result is not NULL in textio.c The bug may occurs if locale.getpreferredencoding() returns an encoding with a surrogate (very unlikely!). ................ r81323 | victor.stinner | 2010-05-19 03:27:23 +0200 (Wed, 19 May 2010) | 4 lines Issue #6697: Check that _PyUnicode_AsString() result is not NULL in _sqlite Strip also some trailing spaces ................ r81324 | victor.stinner | 2010-05-19 03:42:46 +0200 (Wed, 19 May 2010) | 5 lines Issue #6697: Check that _PyUnicode_AsString() result is not NULL in typeobject Type name and slots are already checked for surrogates somewhere else, but it's better to ensure that the result is not NULL. ................ r81325 | victor.stinner | 2010-05-19 03:50:45 +0200 (Wed, 19 May 2010) | 4 lines Ooops, add missing ";" in my previous commit (r81324, typeobject.c) It's time to go to bed... ................ Added: python/branches/py3k-cdecimal/Lib/test/capath/ - copied from r81325, /python/branches/py3k/Lib/test/capath/ Modified: python/branches/py3k-cdecimal/ (props changed) python/branches/py3k-cdecimal/Doc/distutils/sourcedist.rst python/branches/py3k-cdecimal/Doc/library/os.rst python/branches/py3k-cdecimal/Doc/library/ssl.rst python/branches/py3k-cdecimal/Doc/library/tarfile.rst python/branches/py3k-cdecimal/Doc/library/test.rst python/branches/py3k-cdecimal/Doc/library/urllib.request.rst python/branches/py3k-cdecimal/Lib/asyncore.py python/branches/py3k-cdecimal/Lib/distutils/command/sdist.py python/branches/py3k-cdecimal/Lib/distutils/tests/test_sdist.py python/branches/py3k-cdecimal/Lib/importlib/_bootstrap.py python/branches/py3k-cdecimal/Lib/importlib/test/source/test_file_loader.py python/branches/py3k-cdecimal/Lib/os.py python/branches/py3k-cdecimal/Lib/ssl.py python/branches/py3k-cdecimal/Lib/subprocess.py python/branches/py3k-cdecimal/Lib/tarfile.py python/branches/py3k-cdecimal/Lib/test/list_tests.py python/branches/py3k-cdecimal/Lib/test/test_asyncore.py python/branches/py3k-cdecimal/Lib/test/test_getargs2.py python/branches/py3k-cdecimal/Lib/test/test_import.py python/branches/py3k-cdecimal/Lib/test/test_os.py python/branches/py3k-cdecimal/Lib/test/test_ssl.py python/branches/py3k-cdecimal/Lib/test/test_subprocess.py python/branches/py3k-cdecimal/Lib/test/test_sys.py python/branches/py3k-cdecimal/Lib/test/test_tarfile.py python/branches/py3k-cdecimal/Lib/test/testtar.tar python/branches/py3k-cdecimal/Lib/urllib/parse.py python/branches/py3k-cdecimal/Lib/urllib/request.py python/branches/py3k-cdecimal/Misc/NEWS python/branches/py3k-cdecimal/Modules/_cursesmodule.c python/branches/py3k-cdecimal/Modules/_io/textio.c python/branches/py3k-cdecimal/Modules/_sqlite/connection.c python/branches/py3k-cdecimal/Modules/_sqlite/cursor.c python/branches/py3k-cdecimal/Modules/_sqlite/row.c python/branches/py3k-cdecimal/Modules/_sqlite/statement.c python/branches/py3k-cdecimal/Modules/_ssl.c python/branches/py3k-cdecimal/Modules/_testcapimodule.c python/branches/py3k-cdecimal/Modules/main.c python/branches/py3k-cdecimal/Objects/moduleobject.c python/branches/py3k-cdecimal/Objects/object.c python/branches/py3k-cdecimal/Objects/typeobject.c python/branches/py3k-cdecimal/Parser/asdl.py python/branches/py3k-cdecimal/Parser/printgrammar.c python/branches/py3k-cdecimal/Python/bltinmodule.c python/branches/py3k-cdecimal/Python/getargs.c python/branches/py3k-cdecimal/Python/graminit.c python/branches/py3k-cdecimal/Python/pythonrun.c Modified: python/branches/py3k-cdecimal/Doc/distutils/sourcedist.rst ============================================================================== --- python/branches/py3k-cdecimal/Doc/distutils/sourcedist.rst (original) +++ python/branches/py3k-cdecimal/Doc/distutils/sourcedist.rst Wed May 19 17:30:16 2010 @@ -137,20 +137,12 @@ :option:`--no-defaults` and :option:`--no-prune` to disable the standard "include" and "exclude" sets. -Second, you might want to force the manifest to be regenerated---for example, if -you have added or removed files or directories that match an existing pattern in -the manifest template, you should regenerate the manifest:: - - python setup.py sdist --force-manifest - -Or, you might just want to (re)generate the manifest, but not create a source -distribution:: +Second, you might just want to (re)generate the manifest, but not create a +source distribution:: python setup.py sdist --manifest-only -:option:`--manifest-only` implies :option:`--force-manifest`. :option:`-o` is a -shortcut for :option:`--manifest-only`, and :option:`-f` for -:option:`--force-manifest`. +:option:`-o` is a sortcut for :option:`--manifest-only`. .. _manifest_template: Modified: python/branches/py3k-cdecimal/Doc/library/os.rst ============================================================================== --- python/branches/py3k-cdecimal/Doc/library/os.rst (original) +++ python/branches/py3k-cdecimal/Doc/library/os.rst Wed May 19 17:30:16 2010 @@ -142,7 +142,8 @@ synchronized (modify :data:`environb` updates :data:`environ`, and vice versa). - Availability: Unix. + :data:`environb` is only available if :data:`supports_bytes_environ` is + True. .. versionadded:: 3.2 @@ -457,6 +458,14 @@ Availability: Unix, Windows. +.. data:: supports_bytes_environ + + True if the native OS type of the environment is bytes (eg. False on + Windows). + + .. versionadded:: 3.2 + + .. function:: umask(mask) Set the current numeric umask and return the previous umask. Modified: python/branches/py3k-cdecimal/Doc/library/ssl.rst ============================================================================== --- python/branches/py3k-cdecimal/Doc/library/ssl.rst (original) +++ python/branches/py3k-cdecimal/Doc/library/ssl.rst Wed May 19 17:30:16 2010 @@ -36,6 +36,11 @@ connection, and a method, :meth:`cipher`, to retrieve the cipher being used for the secure connection. +For more sophisticated applications, the :class:`ssl.SSLContext` class +helps manage settings and certificates, which can then be inherited +by SSL sockets created through the :meth:`SSLContext.wrap_socket` method. + + Functions, Constants, and Exceptions ------------------------------------ @@ -64,19 +69,6 @@ connection. See the discussion of :ref:`ssl-certificates` for more information on how the certificate is stored in the ``certfile``. - Often the private key is stored in the same file as the certificate; in this - case, only the ``certfile`` parameter need be passed. If the private key is - stored in a separate file, both parameters must be used. If the private key - is stored in the ``certfile``, it should come before the first certificate in - the certificate chain:: - - -----BEGIN RSA PRIVATE KEY----- - ... (private key in base64 encoding) ... - -----END RSA PRIVATE KEY----- - -----BEGIN CERTIFICATE----- - ... (certificate in base64 PEM encoding) ... - -----END CERTIFICATE----- - The parameter ``server_side`` is a boolean which identifies whether server-side or client-side behavior is desired from this socket. @@ -208,29 +200,45 @@ .. data:: CERT_NONE - Value to pass to the ``cert_reqs`` parameter to :func:`sslobject` when no - certificates will be required or validated from the other side of the socket - connection. + Possible value for :attr:`SSLContext.verify_mode`, or the ``cert_reqs`` + parameter to :func:`wrap_socket`. In this mode (the default), no + certificates will be required from the other side of the socket connection. + If a certificate is received from the other end, no attempt to validate it + is made. + + See the discussion of :ref:`ssl-security` below. .. data:: CERT_OPTIONAL - Value to pass to the ``cert_reqs`` parameter to :func:`sslobject` when no - certificates will be required from the other side of the socket connection, - but if they are provided, will be validated. Note that use of this setting - requires a valid certificate validation file also be passed as a value of the - ``ca_certs`` parameter. + Possible value for :attr:`SSLContext.verify_mode`, or the ``cert_reqs`` + parameter to :func:`wrap_socket`. In this mode no certificates will be + required from the other side of the socket connection; but if they + are provided, validation will be attempted and an :class:`SSLError` + will be raised on failure. + + Use of this setting requires a valid set of CA certificates to + be passed, either to :meth:`SSLContext.load_verify_locations` or as a + value of the ``ca_certs`` parameter to :func:`wrap_socket`. .. data:: CERT_REQUIRED - Value to pass to the ``cert_reqs`` parameter to :func:`sslobject` when - certificates will be required from the other side of the socket connection. - Note that use of this setting requires a valid certificate validation file - also be passed as a value of the ``ca_certs`` parameter. + Possible value for :attr:`SSLContext.verify_mode`, or the ``cert_reqs`` + parameter to :func:`wrap_socket`. In this mode, certificates are + required from the other side of the socket connection; an :class:`SSLError` + will be raised if no certificate is provided, or if its validation fails. + + Use of this setting requires a valid set of CA certificates to + be passed, either to :meth:`SSLContext.load_verify_locations` or as a + value of the ``ca_certs`` parameter to :func:`wrap_socket`. .. data:: PROTOCOL_SSLv2 Selects SSL version 2 as the channel encryption protocol. + .. warning:: + + SSL version 2 is insecure. Its use is highly discouraged. + .. data:: PROTOCOL_SSLv23 Selects SSL version 2 or 3 as the channel encryption protocol. This is a @@ -280,8 +288,8 @@ .. versionadded:: 3.2 -SSLSocket Objects ------------------ +SSL Sockets +----------- .. method:: SSLSocket.read(nbytes=1024, buffer=None) @@ -367,6 +375,83 @@ returned socket should always be used for further communication with the other side of the connection, rather than the original socket. + +SSL Contexts +------------ + +.. class:: SSLContext(protocol) + + An object holding various data longer-lived than single SSL connections, + such as SSL configuration options, certificate(s) and private key(s). + You must pass *protocol* which must be one of the ``PROTOCOL_*`` constants + defined in this module. :data:`PROTOCOL_SSLv23` is recommended for + maximum interoperability. + +:class:`SSLContext` objects have the following methods and attributes: + +.. method:: SSLContext.load_cert_chain(certfile, keyfile=None) + + Load a private key and the corresponding certificate. The *certfile* + string must be the path to a single file in PEM format containing the + certificate as well as any number of CA certificates needed to establish + the certificate's authenticity. The *keyfile* string, if present, must + point to a file containing the private key in. Otherwise the private + key will be taken from *certfile* as well. See the discussion of + :ref:`ssl-certificates` for more information on how the certificate + is stored in the *certfile*. + + An :class:`SSLError` is raised if the private key doesn't + match with the certificate. + +.. method:: SSLContext.load_verify_locations(cafile=None, capath=None) + + Load a set of "certification authority" (CA) certificates used to validate + other peers' certificates when :data:`verify_mode` is other than + :data:`CERT_NONE`. At least one of *cafile* or *capath* must be specified. + + The *cafile* string, if present, is the path to a file of concatenated + CA certificates in PEM format. See the discussion of + :ref:`ssl-certificates` for more information about how to arrange the + certificates in this file. + + The *capath* string, if present, is + the path to a directory containing several CA certificates in PEM format, + following an `OpenSSL specific layout + `_. + +.. method:: SSLContext.set_ciphers(ciphers) + + 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. + + .. note:: + when connected, the :meth:`SSLSocket.cipher` method of SSL sockets will + give the currently selected cipher. + +.. method:: SSLContext.wrap_socket(sock, server_side=False, do_handshake_on_connect=True, suppress_ragged_eofs=True) + + Wrap an existing Python socket *sock* and return an :class:`SSLSocket` + object. The SSL socket is tied to the context, its settings and + certificates. The parameters *server_side*, *do_handshake_on_connect* + and *suppress_ragged_eofs* have the same meaning as in the top-level + :func:`wrap_socket` function. + +.. attribute:: SSLContext.protocol + + The protocol version chosen when constructing the context. This attribute + is read-only. + +.. attribute:: SSLContext.verify_mode + + Whether to try to verify other peers' certificates and how to behave + if verification fails. This attribute must be one of + :data:`CERT_NONE`, :data:`CERT_OPTIONAL` or :data:`CERT_REQUIRED`. + + .. index:: single: certificates .. index:: single: X509 certificate @@ -412,6 +497,9 @@ ... (certificate in base64 PEM encoding) ... -----END CERTIFICATE----- +Certificate chains +^^^^^^^^^^^^^^^^^^ + The Python files which contain certificates can contain a sequence of certificates, sometimes called a *certificate chain*. This chain should start with the specific certificate for the principal who "is" the client or server, @@ -435,6 +523,9 @@ ... (the root certificate for the CA's issuer)... -----END CERTIFICATE----- +CA certificates +^^^^^^^^^^^^^^^ + If you are going to require validation of the other side of the connection's certificate, you need to provide a "CA certs" file, filled with the certificate chains for each issuer you are willing to trust. Again, this file just contains @@ -454,6 +545,25 @@ certificate to a root certificate. See :rfc:`4158` for more discussion of the way in which certification chains can be built. +Combined key and certificate +^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +Often the private key is stored in the same file as the certificate; in this +case, only the ``certfile`` parameter to :meth:`SSLContext.load_cert_chain` +and :func:`wrap_socket` needs to be passed. If the private key is stored +with the certificate, it should come before the first certificate in +the certificate chain:: + + -----BEGIN RSA PRIVATE KEY----- + ... (private key in base64 encoding) ... + -----END RSA PRIVATE KEY----- + -----BEGIN CERTIFICATE----- + ... (certificate in base64 PEM encoding) ... + -----END CERTIFICATE----- + +Self-signed certificates +^^^^^^^^^^^^^^^^^^^^^^^^ + If you are going to create a server that provides SSL-encrypted connection services, you will need to acquire a certificate for that service. There are many ways of acquiring appropriate certificates, such as buying one from a @@ -526,8 +636,7 @@ print(pprint.pformat(ssl_sock.getpeercert())) # Set a simple HTTP request -- use http.client in actual code. - ssl_sock.write("""GET / HTTP/1.0\r - Host: www.verisign.com\r\n\r\n""") + ssl_sock.write(b"GET / HTTP/1.0\r\nHost: www.verisign.com\r\n\r\n") # Read a chunk of data. Will not necessarily # read all the data returned by the server. @@ -557,39 +666,91 @@ which is a fairly poorly-formed ``subject`` field. +This other example first creates an SSL context, instructs it to verify +certificates sent by peers, and feeds it a set of recognized certificate +authorities (CA):: + + >>> context = ssl.SSLContext(ssl.PROTOCOL_SSLv23) + >>> context.verify_mode = ssl.CERT_OPTIONAL + >>> context.load_verify_locations("/etc/ssl/certs/ca-bundle.crt") + +(it is assumed your operating system places a bundle of all CA certificates +in ``/etc/ssl/certs/ca-bundle.crt``; if not, you'll get an error and have +to adjust the location) + +When you use the context to connect to a server, :const:`CERT_OPTIONAL` +validates the server certificate: it ensures that the server certificate +was signed with one of the CA certificates, and checks the signature for +correctness:: + + >>> conn = context.wrap_socket(socket.socket(socket.AF_INET)) + >>> conn.connect(("linuxfr.org", 443)) + +You should then fetch the certificate and check its fields for conformity. +Here, the ``commonName`` field in the ``subject`` matches the desired HTTPS +host ``linuxfr.org``:: + + >>> pprint.pprint(conn.getpeercert()) + {'notAfter': 'Jun 26 21:41:46 2011 GMT', + 'subject': ((('commonName', 'linuxfr.org'),),), + 'subjectAltName': (('DNS', 'linuxfr.org'), ('othername', ''))} + +Now that you are assured of its authenticity, you can proceed to talk with +the server:: + + >>> conn.write(b"HEAD / HTTP/1.0\r\nHost: linuxfr.org\r\n\r\n") + 38 + >>> pprint.pprint(conn.read().split(b"\r\n")) + [b'HTTP/1.1 302 Found', + b'Date: Sun, 16 May 2010 13:43:28 GMT', + b'Server: Apache/2.2', + b'Location: https://linuxfr.org/pub/', + b'Vary: Accept-Encoding', + b'Connection: close', + b'Content-Type: text/html; charset=iso-8859-1', + b'', + b''] + + +See the discussion of :ref:`ssl-security` below. + + Server-side operation ^^^^^^^^^^^^^^^^^^^^^ -For server operation, typically you'd need to have a server certificate, and -private key, each in a file. You'd open a socket, bind it to a port, call -:meth:`listen` on it, then start waiting for clients to connect:: +For server operation, typically you'll need to have a server certificate, and +private key, each in a file. You'll first create a context holding the key +and the certificate, so that clients can check your authenticity. Then +you'll open a socket, bind it to a port, call :meth:`listen` on it, and start +waiting for clients to connect:: import socket, ssl + context = ssl.SSLContext(ssl.PROTOCOL_TLSv1) + context.load_cert_chain(certfile="mycertfile", keyfile="mykeyfile") + bindsocket = socket.socket() bindsocket.bind(('myaddr.mydomain.com', 10023)) bindsocket.listen(5) -When one did, you'd call :meth:`accept` on the socket to get the new socket from -the other end, and use :func:`wrap_socket` to create a server-side SSL context -for it:: +When a client connects, you'll call :meth:`accept` on the socket to get the +new socket from the other end, and use the context's :meth:`SSLContext.wrap_socket` +method to create a server-side SSL socket for the connection:: while True: newsocket, fromaddr = bindsocket.accept() - connstream = ssl.wrap_socket(newsocket, - server_side=True, - certfile="mycertfile", - keyfile="mykeyfile", - ssl_version=ssl.PROTOCOL_TLSv1) - deal_with_client(connstream) + connstream = context.wrap_socket(newsocket, server_side=True) + try: + deal_with_client(connstream) + finally: + connstream.close() -Then you'd read data from the ``connstream`` and do something with it till you +Then you'll read data from the ``connstream`` and do something with it till you are finished with the client (or the client is finished with you):: def deal_with_client(connstream): - data = connstream.read() - # null data means the client is finished with us + # empty data means the client is finished with us while data: if not do_something(connstream, data): # we'll assume do_something returns False @@ -597,9 +758,41 @@ break data = connstream.read() # finished with client - connstream.close() -And go back to listening for new client connections. +And go back to listening for new client connections (of course, a real server +would probably handle each client connection in a separate thread, or put +the sockets in non-blocking mode and use an event loop). + + +.. _ssl-security: + +Security considerations +----------------------- + +Verifying certificates +^^^^^^^^^^^^^^^^^^^^^^ + +:const:`CERT_NONE` is the default. Since it does not authenticate the other +peer, it can be insecure, especially in client mode where most of time you +would like to ensure the authenticity of the server you're talking to. +Therefore, when in client mode, it is highly recommended to use +:const:`CERT_REQUIRED`. However, it is in itself not sufficient; you also +have to check that the server certificate (obtained with +:meth:`SSLSocket.getpeercert`) matches the desired service. The exact way +of doing so depends on the higher-level protocol used; for example, with +HTTPS, you'll check that the host name in the URL matches either the +``commonName`` field in the ``subjectName``, or one of the ``DNS`` fields +in the ``subjectAltName``. + +In server mode, if you want to authenticate your clients using the SSL layer +(rather than using a higher-level authentication mechanism), you'll also have +to specify :const:`CERT_REQUIRED` and similarly check the client certificate. + + .. note:: + + In client mode, :const:`CERT_OPTIONAL` and :const:`CERT_REQUIRED` are + equivalent unless anonymous ciphers are enabled (they are disabled + by default). .. seealso:: Modified: python/branches/py3k-cdecimal/Doc/library/tarfile.rst ============================================================================== --- python/branches/py3k-cdecimal/Doc/library/tarfile.rst (original) +++ python/branches/py3k-cdecimal/Doc/library/tarfile.rst Wed May 19 17:30:16 2010 @@ -711,6 +711,8 @@ The default scheme is ``'surrogateescape'`` which Python also uses for its file system calls, see :ref:`os-filenames`. -In case of writing :const:`PAX_FORMAT` archives, *encoding* is ignored because -non-ASCII metadata is stored using *UTF-8*. Storing surrogate characters is not -possible and will raise a :exc:`UnicodeEncodeError`. +In case of :const:`PAX_FORMAT` archives, *encoding* is generally not needed +because all the metadata is stored using *UTF-8*. *encoding* is only used in +the rare cases when binary pax headers are decoded or when strings with +surrogate characters are stored. + Modified: python/branches/py3k-cdecimal/Doc/library/test.rst ============================================================================== --- python/branches/py3k-cdecimal/Doc/library/test.rst (original) +++ python/branches/py3k-cdecimal/Doc/library/test.rst Wed May 19 17:30:16 2010 @@ -340,7 +340,7 @@ .. function:: captured_stdout() - This is a context manager than runs the :keyword:`with` statement body using + This is a context manager that runs the :keyword:`with` statement body using a :class:`StringIO.StringIO` object as sys.stdout. That object can be retrieved using the ``as`` clause of the :keyword:`with` statement. Modified: python/branches/py3k-cdecimal/Doc/library/urllib.request.rst ============================================================================== --- python/branches/py3k-cdecimal/Doc/library/urllib.request.rst (original) +++ python/branches/py3k-cdecimal/Doc/library/urllib.request.rst Wed May 19 17:30:16 2010 @@ -126,26 +126,6 @@ of the data it has downloaded, and just returns it. In this case you just have to assume that the download was successful. - -.. data:: _urlopener - - The public functions :func:`urlopen` and :func:`urlretrieve` create an instance - of the :class:`FancyURLopener` class and use it to perform their requested - actions. To override this functionality, programmers can create a subclass of - :class:`URLopener` or :class:`FancyURLopener`, then assign an instance of that - class to the ``urllib.request._urlopener`` variable before calling the - desired function. For example, applications may want to specify a different - :mailheader:`User-Agent` header than :class:`URLopener` defines. - This can be accomplished with the following code:: - - import urllib.request - - class AppURLopener(urllib.request.FancyURLopener): - version = "App/1.7" - - urllib.request._urlopener = AppURLopener() - - .. function:: urlcleanup() Clear the cache that may have been built up by previous calls to Modified: python/branches/py3k-cdecimal/Lib/asyncore.py ============================================================================== --- python/branches/py3k-cdecimal/Lib/asyncore.py (original) +++ python/branches/py3k-cdecimal/Lib/asyncore.py Wed May 19 17:30:16 2010 @@ -63,8 +63,8 @@ def _strerror(err): try: - return strerror(err) - except (ValueError, OverflowError): + return os.strerror(err) + except (ValueError, OverflowError, NameError): if err in errorcode: return errorcode[err] return "Unknown error %s" %err Modified: python/branches/py3k-cdecimal/Lib/distutils/command/sdist.py ============================================================================== --- python/branches/py3k-cdecimal/Lib/distutils/command/sdist.py (original) +++ python/branches/py3k-cdecimal/Lib/distutils/command/sdist.py Wed May 19 17:30:16 2010 @@ -63,7 +63,8 @@ "just regenerate the manifest and then stop " "(implies --force-manifest)"), ('force-manifest', 'f', - "forcibly regenerate the manifest and carry on as usual"), + "forcibly regenerate the manifest and carry on as usual. " + "Deprecated: now the manifest is always regenerated."), ('formats=', None, "formats for source distribution (comma-separated list)"), ('keep-temp', 'k', @@ -179,66 +180,34 @@ distribution, and put it in 'self.filelist'. This might involve reading the manifest template (and writing the manifest), or just reading the manifest, or just using the default file set -- it all - depends on the user's options and the state of the filesystem. + depends on the user's options. """ - # If we have a manifest template, see if it's newer than the - # manifest; if so, we'll regenerate the manifest. + # new behavior: + # the file list is recalculated everytime because + # even if MANIFEST.in or setup.py are not changed + # the user might have added some files in the tree that + # need to be included. + # + # This makes --force the default and only behavior. template_exists = os.path.isfile(self.template) + if not template_exists: + self.warn(("manifest template '%s' does not exist " + + "(using default file list)") % + self.template) + self.filelist.findall() + + if self.use_defaults: + self.add_defaults() + if template_exists: - template_newer = dep_util.newer(self.template, self.manifest) + self.read_template() - # The contents of the manifest file almost certainly depend on the - # setup script as well as the manifest template -- so if the setup - # script is newer than the manifest, we'll regenerate the manifest - # from the template. (Well, not quite: if we already have a - # manifest, but there's no template -- which will happen if the - # developer elects to generate a manifest some other way -- then we - # can't regenerate the manifest, so we don't.) - self.debug_print("checking if %s newer than %s" % - (self.distribution.script_name, self.manifest)) - setup_newer = dep_util.newer(self.distribution.script_name, - self.manifest) - - # cases: - # 1) no manifest, template exists: generate manifest - # (covered by 2a: no manifest == template newer) - # 2) manifest & template exist: - # 2a) template or setup script newer than manifest: - # regenerate manifest - # 2b) manifest newer than both: - # do nothing (unless --force or --manifest-only) - # 3) manifest exists, no template: - # do nothing (unless --force or --manifest-only) - # 4) no manifest, no template: generate w/ warning ("defaults only") - - manifest_outofdate = (template_exists and - (template_newer or setup_newer)) - force_regen = self.force_manifest or self.manifest_only - manifest_exists = os.path.isfile(self.manifest) - neither_exists = (not template_exists and not manifest_exists) - - # Regenerate the manifest if necessary (or if explicitly told to) - if manifest_outofdate or neither_exists or force_regen: - if not template_exists: - self.warn("manifest template '%s' does not exist " - "(using default file list)" - % self.template) - self.filelist.findall() - - if self.use_defaults: - self.add_defaults() - if template_exists: - self.read_template() - if self.prune: - self.prune_file_list() - - self.filelist.sort() - self.filelist.remove_duplicates() - self.write_manifest() + if self.prune: + self.prune_file_list() - # Don't regenerate the manifest, just read it in. - else: - self.read_manifest() + self.filelist.sort() + self.filelist.remove_duplicates() + self.write_manifest() def add_defaults(self): """Add all the default files to self.filelist: Modified: python/branches/py3k-cdecimal/Lib/distutils/tests/test_sdist.py ============================================================================== --- python/branches/py3k-cdecimal/Lib/distutils/tests/test_sdist.py (original) +++ python/branches/py3k-cdecimal/Lib/distutils/tests/test_sdist.py Wed May 19 17:30:16 2010 @@ -346,6 +346,47 @@ finally: archive.close() + def test_get_file_list(self): + # make sure MANIFEST is recalculated + dist, cmd = self.get_cmd() + + # filling data_files by pointing files in package_data + dist.package_data = {'somecode': ['*.txt']} + self.write_file((self.tmp_dir, 'somecode', 'doc.txt'), '#') + cmd.ensure_finalized() + cmd.run() + + f = open(cmd.manifest) + try: + manifest = [line.strip() for line in f.read().split('\n') + if line.strip() != ''] + finally: + f.close() + + self.assertEquals(len(manifest), 4) + + # adding a file + self.write_file((self.tmp_dir, 'somecode', 'doc2.txt'), '#') + + # make sure build_py is reinitinialized, like a fresh run + build_py = dist.get_command_obj('build_py') + build_py.finalized = False + build_py.ensure_finalized() + + cmd.run() + + f = open(cmd.manifest) + try: + manifest2 = [line.strip() for line in f.read().split('\n') + if line.strip() != ''] + finally: + f.close() + + # do we have the new file in MANIFEST ? + self.assertEquals(len(manifest2), 5) + self.assertIn('doc2.txt', manifest2[-1]) + + def test_suite(): return unittest.makeSuite(SDistTestCase) Modified: python/branches/py3k-cdecimal/Lib/importlib/_bootstrap.py ============================================================================== --- python/branches/py3k-cdecimal/Lib/importlib/_bootstrap.py (original) +++ python/branches/py3k-cdecimal/Lib/importlib/_bootstrap.py Wed May 19 17:30:16 2010 @@ -494,8 +494,16 @@ if ext_type == imp.PY_COMPILED: # We don't really care what the extension on self._base_path is, # as long as it has exactly one dot. - bytecode_path = imp.cache_from_source(self._base_path + '.py') - return (bytecode_path if _path_exists(bytecode_path) else None) + source_path = self._base_path + '.py' + pycache_path = imp.cache_from_source(source_path) + legacy_path = self._base_path + '.pyc' + # The rule is: if the source file exists, then Python always uses + # the __pycache__/foo..pyc file. If the source file does not + # exist, then Python uses the legacy path. + pyc_path = (pycache_path + if _path_exists(source_path) + else legacy_path) + return (pyc_path if _path_exists(pyc_path) else None) return super()._find_path(ext_type) @_check_name Modified: python/branches/py3k-cdecimal/Lib/importlib/test/source/test_file_loader.py ============================================================================== --- python/branches/py3k-cdecimal/Lib/importlib/test/source/test_file_loader.py (original) +++ python/branches/py3k-cdecimal/Lib/importlib/test/source/test_file_loader.py Wed May 19 17:30:16 2010 @@ -10,6 +10,8 @@ import sys import unittest +from test.support import make_legacy_pyc + class SimpleTest(unittest.TestCase): @@ -136,6 +138,7 @@ file.write(new_bc) if del_source: os.unlink(mapping[name]) + make_legacy_pyc(mapping[name]) return bytecode_path @source_util.writes_bytecode_files Modified: python/branches/py3k-cdecimal/Lib/os.py ============================================================================== --- python/branches/py3k-cdecimal/Lib/os.py (original) +++ python/branches/py3k-cdecimal/Lib/os.py Wed May 19 17:30:16 2010 @@ -355,7 +355,11 @@ return last_exc = saved_exc = None saved_tb = None - for dir in get_exec_path(env): + path_list = get_exec_path(env) + if name != 'nt': + file = fsencode(file) + path_list = map(fsencode, path_list) + for dir in path_list: fullname = path.join(dir, file) try: exec_func(fullname, *argrest) @@ -380,7 +384,30 @@ """ if env is None: env = environ - return env.get('PATH', defpath).split(pathsep) + + try: + path_list = env.get('PATH') + except TypeError: + path_list = None + + if supports_bytes_environ: + try: + path_listb = env[b'PATH'] + except (KeyError, TypeError): + pass + else: + if path_list is not None: + raise ValueError( + "env cannot contain 'PATH' and b'PATH' keys") + path_list = path_listb + + if path_list is not None and isinstance(path_list, bytes): + path_list = path_list.decode(sys.getfilesystemencoding(), + 'surrogateescape') + + if path_list is None: + path_list = defpath + return path_list.split(pathsep) # Change environ to automatically call putenv(), unsetenv if they exist. @@ -482,9 +509,11 @@ The optional second argument can specify an alternate default. key, default and the result are str.""" return environ.get(key, default) -__all__.append("getenv") -if name not in ('os2', 'nt'): +supports_bytes_environ = name not in ('os2', 'nt') +__all__.extend(("getenv", "supports_bytes_environ")) + +if supports_bytes_environ: def _check_bytes(value): if not isinstance(value, bytes): raise TypeError("bytes expected, not %s" % type(value).__name__) Modified: python/branches/py3k-cdecimal/Lib/ssl.py ============================================================================== --- python/branches/py3k-cdecimal/Lib/ssl.py (original) +++ python/branches/py3k-cdecimal/Lib/ssl.py Wed May 19 17:30:16 2010 @@ -59,7 +59,7 @@ import _ssl # if we can't import it, let the error propagate from _ssl import OPENSSL_VERSION_NUMBER, OPENSSL_VERSION_INFO, OPENSSL_VERSION -from _ssl import SSLError +from _ssl import _SSLContext, SSLError from _ssl import CERT_NONE, CERT_OPTIONAL, CERT_REQUIRED from _ssl import (PROTOCOL_SSLv2, PROTOCOL_SSLv3, PROTOCOL_SSLv23, PROTOCOL_TLSv1) @@ -84,8 +84,29 @@ import traceback import errno -class SSLSocket(socket): +class SSLContext(_SSLContext): + """An SSLContext holds various SSL-related configuration options and + data, such as certificates and possibly a private key.""" + + __slots__ = ('protocol',) + + def __new__(cls, protocol, *args, **kwargs): + return _SSLContext.__new__(cls, protocol) + + def __init__(self, protocol): + self.protocol = protocol + + def wrap_socket(self, sock, server_side=False, + do_handshake_on_connect=True, + suppress_ragged_eofs=True): + return SSLSocket(sock=sock, server_side=server_side, + do_handshake_on_connect=do_handshake_on_connect, + suppress_ragged_eofs=suppress_ragged_eofs, + _context=self) + + +class SSLSocket(socket): """This class implements a subtype of socket.socket that wraps the underlying OS socket in an SSL context when necessary, and provides read and write methods over that channel.""" @@ -95,8 +116,31 @@ ssl_version=PROTOCOL_SSLv23, ca_certs=None, do_handshake_on_connect=True, family=AF_INET, type=SOCK_STREAM, proto=0, fileno=None, - suppress_ragged_eofs=True, ciphers=None): + suppress_ragged_eofs=True, ciphers=None, + _context=None): + + if _context: + self.context = _context + else: + if certfile and not keyfile: + keyfile = certfile + self.context = SSLContext(ssl_version) + self.context.verify_mode = cert_reqs + if ca_certs: + self.context.load_verify_locations(ca_certs) + if certfile: + self.context.load_cert_chain(certfile, keyfile) + if ciphers: + self.context.set_ciphers(ciphers) + self.keyfile = keyfile + self.certfile = certfile + self.cert_reqs = cert_reqs + self.ssl_version = ssl_version + self.ca_certs = ca_certs + self.ciphers = ciphers + self.do_handshake_on_connect = do_handshake_on_connect + self.suppress_ragged_eofs = suppress_ragged_eofs connected = False if sock is not None: socket.__init__(self, @@ -119,18 +163,12 @@ else: socket.__init__(self, family=family, type=type, proto=proto) - if certfile and not keyfile: - keyfile = certfile - self._closed = False self._sslobj = None if connected: # create the SSL object try: - self._sslobj = _ssl.sslwrap(self, server_side, - keyfile, certfile, - cert_reqs, ssl_version, ca_certs, - ciphers) + self._sslobj = self.context._wrap_socket(self, server_side) if do_handshake_on_connect: timeout = self.gettimeout() if timeout == 0.0: @@ -142,15 +180,6 @@ self.close() raise x - self.keyfile = keyfile - self.certfile = certfile - self.cert_reqs = cert_reqs - self.ssl_version = ssl_version - self.ca_certs = ca_certs - self.ciphers = ciphers - self.do_handshake_on_connect = do_handshake_on_connect - self.suppress_ragged_eofs = suppress_ragged_eofs - def dup(self): raise NotImplemented("Can't dup() %s instances" % self.__class__.__name__) @@ -331,9 +360,7 @@ if self._sslobj: raise ValueError("attempt to connect already-connected SSLSocket!") socket.connect(self, addr) - self._sslobj = _ssl.sslwrap(self, False, self.keyfile, self.certfile, - self.cert_reqs, self.ssl_version, - self.ca_certs, self.ciphers) + self._sslobj = self.context._wrap_socket(self, False) try: if self.do_handshake_on_connect: self.do_handshake() Modified: python/branches/py3k-cdecimal/Lib/subprocess.py ============================================================================== --- python/branches/py3k-cdecimal/Lib/subprocess.py (original) +++ python/branches/py3k-cdecimal/Lib/subprocess.py Wed May 19 17:30:16 2010 @@ -1096,15 +1096,14 @@ for k, v in env.items()] else: env_list = None # Use execv instead of execve. + executable = os.fsencode(executable) if os.path.dirname(executable): - executable_list = (os.fsencode(executable),) + executable_list = (executable,) else: # This matches the behavior of os._execvpe(). - path_list = os.get_exec_path(env) - executable_list = (os.path.join(dir, executable) - for dir in path_list) - executable_list = tuple(os.fsencode(exe) - for exe in executable_list) + executable_list = tuple( + os.path.join(os.fsencode(dir), executable) + for dir in os.get_exec_path(env)) self.pid = _posixsubprocess.fork_exec( args, executable_list, close_fds, cwd, env_list, Modified: python/branches/py3k-cdecimal/Lib/tarfile.py ============================================================================== --- python/branches/py3k-cdecimal/Lib/tarfile.py (original) +++ python/branches/py3k-cdecimal/Lib/tarfile.py Wed May 19 17:30:16 2010 @@ -118,6 +118,9 @@ PAX_FIELDS = ("path", "linkpath", "size", "mtime", "uid", "gid", "uname", "gname") +# Fields from a pax header that are affected by hdrcharset. +PAX_NAME_FIELDS = {"path", "linkpath", "uname", "gname"} + # Fields in a pax header that are numbers, all other fields # are treated as strings. PAX_NUMBER_FIELDS = { @@ -988,7 +991,7 @@ elif format == GNU_FORMAT: return self.create_gnu_header(info, encoding, errors) elif format == PAX_FORMAT: - return self.create_pax_header(info) + return self.create_pax_header(info, encoding) else: raise ValueError("invalid format") @@ -1019,7 +1022,7 @@ return buf + self._create_header(info, GNU_FORMAT, encoding, errors) - def create_pax_header(self, info): + def create_pax_header(self, info, encoding): """Return the object as a ustar header block. If it cannot be represented this way, prepend a pax extended header sequence with supplement information. @@ -1062,7 +1065,7 @@ # Create a pax extended header if necessary. if pax_headers: - buf = self._create_pax_generic_header(pax_headers, XHDTYPE) + buf = self._create_pax_generic_header(pax_headers, XHDTYPE, encoding) else: buf = b"" @@ -1072,7 +1075,7 @@ def create_pax_global_header(cls, pax_headers): """Return the object as a pax global header block sequence. """ - return cls._create_pax_generic_header(pax_headers, XGLTYPE) + return cls._create_pax_generic_header(pax_headers, XGLTYPE, "utf8") def _posix_split_name(self, name): """Split a name longer than 100 chars into a prefix @@ -1145,15 +1148,35 @@ cls._create_payload(name) @classmethod - def _create_pax_generic_header(cls, pax_headers, type): - """Return a POSIX.1-2001 extended or global header sequence + def _create_pax_generic_header(cls, pax_headers, type, encoding): + """Return a POSIX.1-2008 extended or global header sequence that contains a list of keyword, value pairs. The values must be strings. """ + # Check if one of the fields contains surrogate characters and thereby + # forces hdrcharset=BINARY, see _proc_pax() for more information. + binary = False + for keyword, value in pax_headers.items(): + try: + value.encode("utf8", "strict") + except UnicodeEncodeError: + binary = True + break + records = b"" + if binary: + # Put the hdrcharset field at the beginning of the header. + records += b"21 hdrcharset=BINARY\n" + for keyword, value in pax_headers.items(): keyword = keyword.encode("utf8") - value = value.encode("utf8") + if binary: + # Try to restore the original byte representation of `value'. + # Needless to say, that the encoding must match the string. + value = value.encode(encoding, "surrogateescape") + else: + value = value.encode("utf8") + l = len(keyword) + len(value) + 3 # ' ' + '=' + '\n' n = p = 0 while True: @@ -1354,7 +1377,7 @@ def _proc_pax(self, tarfile): """Process an extended or global header as described in - POSIX.1-2001. + POSIX.1-2008. """ # Read the header information. buf = tarfile.fileobj.read(self._block(self.size)) @@ -1367,6 +1390,24 @@ else: pax_headers = tarfile.pax_headers.copy() + # Check if the pax header contains a hdrcharset field. This tells us + # the encoding of the path, linkpath, uname and gname fields. Normally, + # these fields are UTF-8 encoded but since POSIX.1-2008 tar + # implementations are allowed to store them as raw binary strings if + # the translation to UTF-8 fails. + match = re.search(br"\d+ hdrcharset=([^\n]+)\n", buf) + if match is not None: + pax_headers["hdrcharset"] = match.group(1).decode("utf8") + + # For the time being, we don't care about anything other than "BINARY". + # The only other value that is currently allowed by the standard is + # "ISO-IR 10646 2000 UTF-8" in other words UTF-8. + hdrcharset = pax_headers.get("hdrcharset") + if hdrcharset == "BINARY": + encoding = tarfile.encoding + else: + encoding = "utf8" + # Parse pax header information. A record looks like that: # "%d %s=%s\n" % (length, keyword, value). length is the size # of the complete record including the length field itself and @@ -1382,8 +1423,21 @@ length = int(length) value = buf[match.end(2) + 1:match.start(1) + length - 1] - keyword = keyword.decode("utf8") - value = value.decode("utf8") + # Normally, we could just use "utf8" as the encoding and "strict" + # as the error handler, but we better not take the risk. For + # example, GNU tar <= 1.23 is known to store filenames it cannot + # translate to UTF-8 as raw strings (unfortunately without a + # hdrcharset=BINARY header). + # We first try the strict standard encoding, and if that fails we + # fall back on the user's encoding and error handler. + keyword = self._decode_pax_field(keyword, "utf8", "utf8", + tarfile.errors) + if keyword in PAX_NAME_FIELDS: + value = self._decode_pax_field(value, encoding, tarfile.encoding, + tarfile.errors) + else: + value = self._decode_pax_field(value, "utf8", "utf8", + tarfile.errors) pax_headers[keyword] = value pos += length @@ -1431,6 +1485,14 @@ self.pax_headers = pax_headers.copy() + def _decode_pax_field(self, value, encoding, fallback_encoding, fallback_errors): + """Decode a single field from a pax record. + """ + try: + return value.decode(encoding, "strict") + except UnicodeDecodeError: + return value.decode(fallback_encoding, fallback_errors) + def _block(self, count): """Round up a byte count by BLOCKSIZE and return it, e.g. _block(834) => 1024. Modified: python/branches/py3k-cdecimal/Lib/test/list_tests.py ============================================================================== --- python/branches/py3k-cdecimal/Lib/test/list_tests.py (original) +++ python/branches/py3k-cdecimal/Lib/test/list_tests.py Wed May 19 17:30:16 2010 @@ -66,13 +66,11 @@ d.append(d) d.append(400) try: - fo = open(support.TESTFN, "w") - fo.write(str(d)) - fo.close() - fo = open(support.TESTFN, "r") - self.assertEqual(fo.read(), repr(d)) + with open(support.TESTFN, "w") as fo: + fo.write(str(d)) + with open(support.TESTFN, "r") as fo: + self.assertEqual(fo.read(), repr(d)) finally: - fo.close() os.remove(support.TESTFN) def test_set_subscript(self): Modified: python/branches/py3k-cdecimal/Lib/test/test_asyncore.py ============================================================================== --- python/branches/py3k-cdecimal/Lib/test/test_asyncore.py (original) +++ python/branches/py3k-cdecimal/Lib/test/test_asyncore.py Wed May 19 17:30:16 2010 @@ -6,6 +6,7 @@ import sys import time import warnings +import errno from test import support from test.support import TESTFN, run_unittest, unlink @@ -324,6 +325,14 @@ self.assertTrue(len(w) == 1) self.assertTrue(issubclass(w[0].category, DeprecationWarning)) + def test_strerror(self): + # refers to bug #8573 + err = asyncore._strerror(errno.EPERM) + if hasattr(os, 'strerror'): + self.assertEqual(err, os.strerror(errno.EPERM)) + err = asyncore._strerror(-1) + self.assertTrue("unknown error" in err.lower()) + class dispatcherwithsend_noread(asyncore.dispatcher_with_send): def readable(self): Modified: python/branches/py3k-cdecimal/Lib/test/test_getargs2.py ============================================================================== --- python/branches/py3k-cdecimal/Lib/test/test_getargs2.py (original) +++ python/branches/py3k-cdecimal/Lib/test/test_getargs2.py Wed May 19 17:30:16 2010 @@ -252,24 +252,28 @@ getargs_keywords((1,2), 3, (4,(5,6)), (7,8,9), 10), (1, 2, 3, 4, 5, 6, 7, 8, 9, 10) ) + def test_mixed_args(self): # positional and keyword args self.assertEquals( getargs_keywords((1,2), 3, (4,(5,6)), arg4=(7,8,9), arg5=10), (1, 2, 3, 4, 5, 6, 7, 8, 9, 10) ) + def test_keyword_args(self): # all keywords self.assertEquals( getargs_keywords(arg1=(1,2), arg2=3, arg3=(4,(5,6)), arg4=(7,8,9), arg5=10), (1, 2, 3, 4, 5, 6, 7, 8, 9, 10) ) + def test_optional_args(self): # missing optional keyword args, skipping tuples self.assertEquals( getargs_keywords(arg1=(1,2), arg2=3, arg5=10), (1, 2, 3, -1, -1, -1, -1, -1, -1, 10) ) + def test_required_args(self): # required arg missing try: @@ -278,6 +282,7 @@ self.assertEquals(str(err), "Required argument 'arg2' (pos 2) not found") else: self.fail('TypeError should have been raised') + def test_too_many_args(self): try: getargs_keywords((1,2),3,(4,(5,6)),(7,8,9),10,111) @@ -285,6 +290,7 @@ self.assertEquals(str(err), "function takes at most 5 arguments (6 given)") else: self.fail('TypeError should have been raised') + def test_invalid_keyword(self): # extraneous keyword arg try: @@ -294,6 +300,14 @@ else: self.fail('TypeError should have been raised') + def test_surrogate_keyword(self): + try: + getargs_keywords((1,2), 3, (4,(5,6)), (7,8,9), **{'\uDC80': 10}) + except TypeError as err: + self.assertEquals(str(err), "'\udc80' is an invalid keyword argument for this function") + else: + self.fail('TypeError should have been raised') + def test_main(): tests = [Signed_TestCase, Unsigned_TestCase, Tuple_TestCase, Keywords_TestCase] try: Modified: python/branches/py3k-cdecimal/Lib/test/test_import.py ============================================================================== --- python/branches/py3k-cdecimal/Lib/test/test_import.py (original) +++ python/branches/py3k-cdecimal/Lib/test/test_import.py Wed May 19 17:30:16 2010 @@ -153,23 +153,23 @@ f.write('"",\n') f.write(']') - # Compile & remove .py file, we only need .pyc (or .pyo), but that - # must be relocated to the PEP 3147 bytecode-only location. - with open(filename, 'r') as f: - py_compile.compile(filename) + # Compile & remove .py file; we only need .pyc (or .pyo). + # Bytecode must be relocated from the PEP 3147 bytecode-only location. + py_compile.compile(filename) unlink(filename) make_legacy_pyc(filename) # Need to be able to load from current dir. sys.path.append('') - # This used to crash. - exec('import ' + module) - - # Cleanup. - del sys.path[-1] - unlink(filename + 'c') - unlink(filename + 'o') + try: + # This used to crash. + exec('import ' + module) + finally: + # Cleanup. + del sys.path[-1] + unlink(filename + 'c') + unlink(filename + 'o') def test_failing_import_sticks(self): source = TESTFN + ".py" Modified: python/branches/py3k-cdecimal/Lib/test/test_os.py ============================================================================== --- python/branches/py3k-cdecimal/Lib/test/test_os.py (original) +++ python/branches/py3k-cdecimal/Lib/test/test_os.py Wed May 19 17:30:16 2010 @@ -12,6 +12,7 @@ import time import shutil from test import support +import contextlib # Detect whether we're on a Linux system that uses the (now outdated # and unmaintained) linuxthreads threading library. There's an issue @@ -369,7 +370,7 @@ def setUp(self): self.__save = dict(os.environ) - if os.name not in ('os2', 'nt'): + if os.supports_bytes_environ: self.__saveb = dict(os.environb) for key, value in self._reference().items(): os.environ[key] = value @@ -377,7 +378,7 @@ def tearDown(self): os.environ.clear() os.environ.update(self.__save) - if os.name not in ('os2', 'nt'): + if os.supports_bytes_environ: os.environb.clear() os.environb.update(self.__saveb) @@ -444,7 +445,21 @@ # Supplied PATH environment variable self.assertSequenceEqual(test_path, os.get_exec_path(test_env)) - @unittest.skipIf(sys.platform == "win32", "POSIX specific test") + if os.supports_bytes_environ: + # env cannot contain 'PATH' and b'PATH' keys + self.assertRaises(ValueError, + os.get_exec_path, {'PATH': '1', b'PATH': b'2'}) + + # bytes key and/or value + self.assertSequenceEqual(os.get_exec_path({b'PATH': b'abc'}), + ['abc']) + self.assertSequenceEqual(os.get_exec_path({b'PATH': 'abc'}), + ['abc']) + self.assertSequenceEqual(os.get_exec_path({'PATH': b'abc'}), + ['abc']) + + @unittest.skipUnless(os.supports_bytes_environ, + "os.environb required for this test.") def test_environb(self): # os.environ -> os.environb value = 'euro\u20ac' @@ -623,6 +638,39 @@ except NotImplementedError: pass + at contextlib.contextmanager +def _execvpe_mockup(defpath=None): + """ + Stubs out execv and execve functions when used as context manager. + Records exec calls. The mock execv and execve functions always raise an + exception as they would normally never return. + """ + # A list of tuples containing (function name, first arg, args) + # of calls to execv or execve that have been made. + calls = [] + + def mock_execv(name, *args): + calls.append(('execv', name, args)) + raise RuntimeError("execv called") + + def mock_execve(name, *args): + calls.append(('execve', name, args)) + raise OSError(errno.ENOTDIR, "execve called") + + try: + orig_execv = os.execv + orig_execve = os.execve + orig_defpath = os.defpath + os.execv = mock_execv + os.execve = mock_execve + if defpath is not None: + os.defpath = defpath + yield calls + finally: + os.execv = orig_execv + os.execve = orig_execve + os.defpath = orig_defpath + class ExecTests(unittest.TestCase): @unittest.skipIf(USING_LINUXTHREADS, "avoid triggering a linuxthreads bug: see issue #4970") @@ -633,57 +681,57 @@ def test_execvpe_with_bad_arglist(self): self.assertRaises(ValueError, os.execvpe, 'notepad', [], None) - class _stub_out_for_execvpe_test(object): - """ - Stubs out execv, execve and get_exec_path functions when - used as context manager. Records exec calls. The mock execv - and execve functions always raise an exception as they would - normally never return. - """ - def __init__(self): - # A list of tuples containing (function name, first arg, args) - # of calls to execv or execve that have been made. - self.calls = [] - def _mock_execv(self, name, *args): - self.calls.append(('execv', name, args)) - raise RuntimeError("execv called") - - def _mock_execve(self, name, *args): - self.calls.append(('execve', name, args)) - raise OSError(errno.ENOTDIR, "execve called") - - def _mock_get_exec_path(self, env=None): - return [os.sep+'p', os.sep+'pp'] - - def __enter__(self): - self.orig_execv = os.execv - self.orig_execve = os.execve - self.orig_get_exec_path = os.get_exec_path - os.execv = self._mock_execv - os.execve = self._mock_execve - os.get_exec_path = self._mock_get_exec_path - - def __exit__(self, type, value, tb): - os.execv = self.orig_execv - os.execve = self.orig_execve - os.get_exec_path = self.orig_get_exec_path - @unittest.skipUnless(hasattr(os, '_execvpe'), "No internal os._execvpe function to test.") - def test_internal_execvpe(self): - exec_stubbed = self._stub_out_for_execvpe_test() - with exec_stubbed: - self.assertRaises(RuntimeError, os._execvpe, os.sep+'f', ['-a']) - self.assertEqual([('execv', os.sep+'f', (['-a'],))], - exec_stubbed.calls) - exec_stubbed.calls = [] - self.assertRaises(OSError, os._execvpe, 'f', ['-a'], - env={'spam': 'beans'}) - self.assertEqual([('execve', os.sep+'p'+os.sep+'f', - (['-a'], {'spam': 'beans'})), - ('execve', os.sep+'pp'+os.sep+'f', - (['-a'], {'spam': 'beans'}))], - exec_stubbed.calls) + def _test_internal_execvpe(self, test_type): + program_path = os.sep + 'absolutepath' + if test_type is bytes: + program = b'executable' + fullpath = os.path.join(os.fsencode(program_path), program) + native_fullpath = fullpath + arguments = [b'progname', 'arg1', 'arg2'] + else: + program = 'executable' + arguments = ['progname', 'arg1', 'arg2'] + fullpath = os.path.join(program_path, program) + if os.name != "nt": + native_fullpath = os.fsencode(fullpath) + else: + native_fullpath = fullpath + env = {'spam': 'beans'} + + # test os._execvpe() with an absolute path + with _execvpe_mockup() as calls: + self.assertRaises(RuntimeError, + os._execvpe, fullpath, arguments) + self.assertEqual(len(calls), 1) + self.assertEqual(calls[0], ('execv', fullpath, (arguments,))) + + # test os._execvpe() with a relative path: + # os.get_exec_path() returns defpath + with _execvpe_mockup(defpath=program_path) as calls: + self.assertRaises(OSError, + os._execvpe, program, arguments, env=env) + self.assertEqual(len(calls), 1) + self.assertSequenceEqual(calls[0], + ('execve', native_fullpath, (arguments, env))) + + # test os._execvpe() with a relative path: + # os.get_exec_path() reads the 'PATH' variable + with _execvpe_mockup() as calls: + env_path = env.copy() + env_path['PATH'] = program_path + self.assertRaises(OSError, + os._execvpe, program, arguments, env=env_path) + self.assertEqual(len(calls), 1) + self.assertSequenceEqual(calls[0], + ('execve', native_fullpath, (arguments, env_path))) + + def test_internal_execvpe_str(self): + self._test_internal_execvpe(str) + if os.name != "nt": + self._test_internal_execvpe(bytes) + class Win32ErrorTests(unittest.TestCase): def test_rename(self): Modified: python/branches/py3k-cdecimal/Lib/test/test_ssl.py ============================================================================== --- python/branches/py3k-cdecimal/Lib/test/test_ssl.py (original) +++ python/branches/py3k-cdecimal/Lib/test/test_ssl.py Wed May 19 17:30:16 2010 @@ -10,6 +10,7 @@ import os import errno import pprint +import tempfile import urllib.parse, urllib.request import traceback import asyncore @@ -23,10 +24,33 @@ import ssl except ImportError: skip_expected = True +else: + PROTOCOLS = [ + ssl.PROTOCOL_SSLv2, ssl.PROTOCOL_SSLv3, + ssl.PROTOCOL_SSLv23, ssl.PROTOCOL_TLSv1 + ] HOST = support.HOST -CERTFILE = None -SVN_PYTHON_ORG_ROOT_CERT = None + +data_file = lambda name: os.path.join(os.path.dirname(__file__), name) +fsencode = lambda name: name.encode(sys.getfilesystemencoding(), "surrogateescape") + +CERTFILE = data_file("keycert.pem") +BYTES_CERTFILE = fsencode(CERTFILE) +ONLYCERT = data_file("ssl_cert.pem") +ONLYKEY = data_file("ssl_key.pem") +BYTES_ONLYCERT = fsencode(ONLYCERT) +BYTES_ONLYKEY = fsencode(ONLYKEY) +CAPATH = data_file("capath") +BYTES_CAPATH = fsencode(CAPATH) + +SVN_PYTHON_ORG_ROOT_CERT = data_file("https_svn_python_org_root.pem") + +EMPTYCERT = data_file("nullcert.pem") +BADCERT = data_file("badcert.pem") +WRONGCERT = data_file("XXXnonexisting.pem") +BADKEY = data_file("badkey.pem") + def handle_error(prefix): exc_format = ' '.join(traceback.format_exception(*sys.exc_info())) @@ -34,7 +58,7 @@ sys.stdout.write(prefix + exc_format) -class BasicTests(unittest.TestCase): +class BasicSocketTests(unittest.TestCase): def test_constants(self): ssl.PROTOCOL_SSLv2 @@ -116,11 +140,10 @@ s = ssl.wrap_socket(socket.socket(socket.AF_INET), cert_reqs=ssl.CERT_NONE, ciphers="DEFAULT") s.connect(remote) - # Error checking occurs when connecting, because the SSL context - # isn't created before. - s = ssl.wrap_socket(socket.socket(socket.AF_INET), - cert_reqs=ssl.CERT_NONE, ciphers="^$:,;?*'dorothyx") + # Error checking can happen at instantiation or when connecting with self.assertRaisesRegexp(ssl.SSLError, "No cipher can be selected"): + s = ssl.wrap_socket(socket.socket(socket.AF_INET), + cert_reqs=ssl.CERT_NONE, ciphers="^$:,;?*'dorothyx") s.connect(remote) @support.cpython_only @@ -143,33 +166,166 @@ self.assertEqual(timeout, ss.gettimeout()) +class ContextTests(unittest.TestCase): + + def test_constructor(self): + ctx = ssl.SSLContext(ssl.PROTOCOL_SSLv2) + ctx = ssl.SSLContext(ssl.PROTOCOL_SSLv23) + ctx = ssl.SSLContext(ssl.PROTOCOL_SSLv3) + ctx = ssl.SSLContext(ssl.PROTOCOL_TLSv1) + self.assertRaises(TypeError, ssl.SSLContext) + self.assertRaises(ValueError, ssl.SSLContext, -1) + self.assertRaises(ValueError, ssl.SSLContext, 42) + + def test_protocol(self): + for proto in PROTOCOLS: + ctx = ssl.SSLContext(proto) + self.assertEqual(ctx.protocol, proto) + + def test_ciphers(self): + ctx = ssl.SSLContext(ssl.PROTOCOL_TLSv1) + ctx.set_ciphers("ALL") + ctx.set_ciphers("DEFAULT") + with self.assertRaisesRegexp(ssl.SSLError, "No cipher can be selected"): + ctx.set_ciphers("^$:,;?*'dorothyx") + + def test_verify(self): + ctx = ssl.SSLContext(ssl.PROTOCOL_TLSv1) + # Default value + self.assertEqual(ctx.verify_mode, ssl.CERT_NONE) + ctx.verify_mode = ssl.CERT_OPTIONAL + self.assertEqual(ctx.verify_mode, ssl.CERT_OPTIONAL) + ctx.verify_mode = ssl.CERT_REQUIRED + self.assertEqual(ctx.verify_mode, ssl.CERT_REQUIRED) + ctx.verify_mode = ssl.CERT_NONE + self.assertEqual(ctx.verify_mode, ssl.CERT_NONE) + with self.assertRaises(TypeError): + ctx.verify_mode = None + with self.assertRaises(ValueError): + ctx.verify_mode = 42 + + def test_load_cert_chain(self): + ctx = ssl.SSLContext(ssl.PROTOCOL_TLSv1) + # Combined key and cert in a single file + ctx.load_cert_chain(CERTFILE) + ctx.load_cert_chain(CERTFILE, keyfile=CERTFILE) + self.assertRaises(TypeError, ctx.load_cert_chain, keyfile=CERTFILE) + with self.assertRaisesRegexp(ssl.SSLError, "system lib"): + ctx.load_cert_chain(WRONGCERT) + with self.assertRaisesRegexp(ssl.SSLError, "PEM lib"): + ctx.load_cert_chain(BADCERT) + with self.assertRaisesRegexp(ssl.SSLError, "PEM lib"): + ctx.load_cert_chain(EMPTYCERT) + # Separate key and cert + ctx = ssl.SSLContext(ssl.PROTOCOL_TLSv1) + ctx.load_cert_chain(ONLYCERT, ONLYKEY) + ctx.load_cert_chain(certfile=ONLYCERT, keyfile=ONLYKEY) + ctx.load_cert_chain(certfile=BYTES_ONLYCERT, keyfile=BYTES_ONLYKEY) + with self.assertRaisesRegexp(ssl.SSLError, "PEM lib"): + ctx.load_cert_chain(ONLYCERT) + with self.assertRaisesRegexp(ssl.SSLError, "PEM lib"): + ctx.load_cert_chain(ONLYKEY) + with self.assertRaisesRegexp(ssl.SSLError, "PEM lib"): + ctx.load_cert_chain(certfile=ONLYKEY, keyfile=ONLYCERT) + # Mismatching key and cert + ctx = ssl.SSLContext(ssl.PROTOCOL_TLSv1) + with self.assertRaisesRegexp(ssl.SSLError, "key values mismatch"): + ctx.load_cert_chain(CERTFILE, ONLYKEY) + + def test_load_verify_locations(self): + ctx = ssl.SSLContext(ssl.PROTOCOL_TLSv1) + ctx.load_verify_locations(CERTFILE) + ctx.load_verify_locations(cafile=CERTFILE, capath=None) + ctx.load_verify_locations(BYTES_CERTFILE) + ctx.load_verify_locations(cafile=BYTES_CERTFILE, capath=None) + self.assertRaises(TypeError, ctx.load_verify_locations) + self.assertRaises(TypeError, ctx.load_verify_locations, None, None) + with self.assertRaisesRegexp(ssl.SSLError, "system lib"): + ctx.load_verify_locations(WRONGCERT) + with self.assertRaisesRegexp(ssl.SSLError, "PEM lib"): + ctx.load_verify_locations(BADCERT) + ctx.load_verify_locations(CERTFILE, CAPATH) + ctx.load_verify_locations(CERTFILE, capath=BYTES_CAPATH) + + class NetworkedTests(unittest.TestCase): def test_connect(self): s = ssl.wrap_socket(socket.socket(socket.AF_INET), cert_reqs=ssl.CERT_NONE) - s.connect(("svn.python.org", 443)) - c = s.getpeercert() - if c: - self.fail("Peer cert %s shouldn't be here!") - s.close() - - # this should fail because we have no verification certs - s = ssl.wrap_socket(socket.socket(socket.AF_INET), - cert_reqs=ssl.CERT_REQUIRED) try: s.connect(("svn.python.org", 443)) - except ssl.SSLError: - pass + self.assertEqual({}, s.getpeercert()) finally: s.close() + # this should fail because we have no verification certs + s = ssl.wrap_socket(socket.socket(socket.AF_INET), + cert_reqs=ssl.CERT_REQUIRED) + self.assertRaisesRegexp(ssl.SSLError, "certificate verify failed", + s.connect, ("svn.python.org", 443)) + s.close() + # this should succeed because we specify the root cert s = ssl.wrap_socket(socket.socket(socket.AF_INET), cert_reqs=ssl.CERT_REQUIRED, ca_certs=SVN_PYTHON_ORG_ROOT_CERT) try: s.connect(("svn.python.org", 443)) + self.assertTrue(s.getpeercert()) + finally: + s.close() + + def test_connect_with_context(self): + # Same as test_connect, but with a separately created context + ctx = ssl.SSLContext(ssl.PROTOCOL_SSLv23) + s = ctx.wrap_socket(socket.socket(socket.AF_INET)) + s.connect(("svn.python.org", 443)) + try: + self.assertEqual({}, s.getpeercert()) + finally: + s.close() + # This should fail because we have no verification certs + ctx.verify_mode = ssl.CERT_REQUIRED + s = ctx.wrap_socket(socket.socket(socket.AF_INET)) + self.assertRaisesRegexp(ssl.SSLError, "certificate verify failed", + s.connect, ("svn.python.org", 443)) + s.close() + # This should succeed because we specify the root cert + ctx.load_verify_locations(SVN_PYTHON_ORG_ROOT_CERT) + s = ctx.wrap_socket(socket.socket(socket.AF_INET)) + s.connect(("svn.python.org", 443)) + try: + cert = s.getpeercert() + self.assertTrue(cert) + finally: + s.close() + + def test_connect_capath(self): + # Verify server certificates using the `capath` argument + # NOTE: the subject hashing algorithm has been changed between + # OpenSSL 0.9.8n and 1.0.0, as a result the capath directory must + # contain both versions of each certificate (same content, different + # filename) for this test to be portable across OpenSSL releases. + ctx = ssl.SSLContext(ssl.PROTOCOL_SSLv23) + ctx.verify_mode = ssl.CERT_REQUIRED + ctx.load_verify_locations(capath=CAPATH) + s = ctx.wrap_socket(socket.socket(socket.AF_INET)) + s.connect(("svn.python.org", 443)) + try: + cert = s.getpeercert() + self.assertTrue(cert) + finally: + s.close() + # Same with a bytes `capath` argument + ctx = ssl.SSLContext(ssl.PROTOCOL_SSLv23) + ctx.verify_mode = ssl.CERT_REQUIRED + ctx.load_verify_locations(capath=BYTES_CAPATH) + s = ctx.wrap_socket(socket.socket(socket.AF_INET)) + s.connect(("svn.python.org", 443)) + try: + cert = s.getpeercert() + self.assertTrue(cert) finally: s.close() @@ -1227,18 +1383,14 @@ if skip_expected: raise unittest.SkipTest("No SSL support") - global CERTFILE, SVN_PYTHON_ORG_ROOT_CERT - CERTFILE = os.path.join(os.path.dirname(__file__) or os.curdir, - "keycert.pem") - SVN_PYTHON_ORG_ROOT_CERT = os.path.join( - os.path.dirname(__file__) or os.curdir, - "https_svn_python_org_root.pem") - - if (not os.path.exists(CERTFILE) or - not os.path.exists(SVN_PYTHON_ORG_ROOT_CERT)): - raise support.TestFailed("Can't read certificate files!") + for filename in [ + CERTFILE, SVN_PYTHON_ORG_ROOT_CERT, BYTES_CERTFILE, + ONLYCERT, ONLYKEY, BYTES_ONLYCERT, BYTES_ONLYKEY, + BADCERT, BADKEY, EMPTYCERT]: + if not os.path.exists(filename): + raise support.TestFailed("Can't read certificate file %r" % filename) - tests = [BasicTests] + tests = [ContextTests, BasicSocketTests] if support.is_resource_enabled('network'): tests.append(NetworkedTests) Modified: python/branches/py3k-cdecimal/Lib/test/test_subprocess.py ============================================================================== --- python/branches/py3k-cdecimal/Lib/test/test_subprocess.py (original) +++ python/branches/py3k-cdecimal/Lib/test/test_subprocess.py Wed May 19 17:30:16 2010 @@ -825,6 +825,27 @@ stdout = stdout.rstrip(b'\n\r') self.assertEquals(stdout.decode('ascii'), repr(value)) + def test_bytes_program(self): + abs_program = os.fsencode(sys.executable) + path, program = os.path.split(sys.executable) + program = os.fsencode(program) + + # absolute bytes path + exitcode = subprocess.call([abs_program, "-c", "pass"]) + self.assertEquals(exitcode, 0) + + # bytes program, unicode PATH + env = os.environ.copy() + env["PATH"] = path + exitcode = subprocess.call([program, "-c", "pass"], env=env) + self.assertEquals(exitcode, 0) + + # bytes program, bytes PATH + envb = os.environb.copy() + envb[b"PATH"] = os.fsencode(path) + exitcode = subprocess.call([program, "-c", "pass"], env=envb) + self.assertEquals(exitcode, 0) + @unittest.skipUnless(mswindows, "Windows specific tests") class Win32ProcessTestCase(BaseTestCase): Modified: python/branches/py3k-cdecimal/Lib/test/test_sys.py ============================================================================== --- python/branches/py3k-cdecimal/Lib/test/test_sys.py (original) +++ python/branches/py3k-cdecimal/Lib/test/test_sys.py Wed May 19 17:30:16 2010 @@ -86,6 +86,8 @@ # Python/pythonrun.c::PyErr_PrintEx() is tricky. def test_exit(self): + import subprocess + self.assertRaises(TypeError, sys.exit, 42, 42) # call without argument @@ -140,11 +142,30 @@ self.fail("no exception") # test that the exit machinery handles SystemExits properly - import subprocess rc = subprocess.call([sys.executable, "-c", "raise SystemExit(47)"]) self.assertEqual(rc, 47) + def check_exit_message(code, expected): + process = subprocess.Popen([sys.executable, "-c", code], + stderr=subprocess.PIPE) + stdout, stderr = process.communicate() + self.assertEqual(process.returncode, 1) + self.assertTrue(stderr.startswith(expected), + "%s doesn't start with %s" % (ascii(stderr), ascii(expected))) + + # test that stderr buffer if flushed before the exit message is written + # into stderr + check_exit_message( + r'import sys; sys.stderr.write("unflushed,"); sys.exit("message")', + b"unflushed,message") + + # test that the exit message is written with backslashreplace error + # handler to stderr + check_exit_message( + r'import sys; sys.exit("surrogates:\uDCFF")', + b"surrogates:\\udcff") + def test_getdefaultencoding(self): self.assertRaises(TypeError, sys.getdefaultencoding, 42) # can't check more than the type, as the user might have changed it @@ -449,6 +470,23 @@ self.assertRaises(TypeError, sys.intern, S("abc")) + def test_main_invalid_unicode(self): + import locale + non_decodable = b"\xff" + encoding = locale.getpreferredencoding() + try: + non_decodable.decode(encoding) + except UnicodeDecodeError: + pass + else: + self.skipTest('%r is decodable with encoding %s' + % (non_decodable, encoding)) + code = b'print("' + non_decodable + b'")' + p = subprocess.Popen([sys.executable, "-c", code], stderr=subprocess.PIPE) + stdout, stderr = p.communicate() + self.assertEqual(p.returncode, 1) + self.assert_(b"UnicodeEncodeError:" in stderr, + "%r not in %s" % (b"UniodeEncodeError:", ascii(stderr))) def test_sys_flags(self): self.assertTrue(sys.flags) Modified: python/branches/py3k-cdecimal/Lib/test/test_tarfile.py ============================================================================== --- python/branches/py3k-cdecimal/Lib/test/test_tarfile.py (original) +++ python/branches/py3k-cdecimal/Lib/test/test_tarfile.py Wed May 19 17:30:16 2010 @@ -1126,11 +1126,32 @@ format = tarfile.GNU_FORMAT + def test_bad_pax_header(self): + # Test for issue #8633. GNU tar <= 1.23 creates raw binary fields + # without a hdrcharset=BINARY header. + for encoding, name in (("utf8", "pax/bad-pax-\udce4\udcf6\udcfc"), + ("iso8859-1", "pax/bad-pax-\xe4\xf6\xfc"),): + with tarfile.open(tarname, encoding=encoding, errors="surrogateescape") as tar: + try: + t = tar.getmember(name) + except KeyError: + self.fail("unable to read bad GNU tar pax header") + class PAXUnicodeTest(UstarUnicodeTest): format = tarfile.PAX_FORMAT + def test_binary_header(self): + # Test a POSIX.1-2008 compatible header with a hdrcharset=BINARY field. + for encoding, name in (("utf8", "pax/hdrcharset-\udce4\udcf6\udcfc"), + ("iso8859-1", "pax/hdrcharset-\xe4\xf6\xfc"),): + with tarfile.open(tarname, encoding=encoding, errors="surrogateescape") as tar: + try: + t = tar.getmember(name) + except KeyError: + self.fail("unable to read POSIX.1-2008 binary header") + class AppendTest(unittest.TestCase): # Test append mode (cp. patch #1652681). Modified: python/branches/py3k-cdecimal/Lib/test/testtar.tar ============================================================================== Binary files. No diff available. Modified: python/branches/py3k-cdecimal/Lib/urllib/parse.py ============================================================================== --- python/branches/py3k-cdecimal/Lib/urllib/parse.py (original) +++ python/branches/py3k-cdecimal/Lib/urllib/parse.py Wed May 19 17:30:16 2010 @@ -41,7 +41,7 @@ uses_netloc = ['ftp', 'http', 'gopher', 'nntp', 'telnet', 'imap', 'wais', 'file', 'mms', 'https', 'shttp', 'snews', 'prospero', 'rtsp', 'rtspu', 'rsync', '', - 'svn', 'svn+ssh', 'sftp', 'nfs',' git', 'git+ssh'] + 'svn', 'svn+ssh', 'sftp', 'nfs', 'git', 'git+ssh'] non_hierarchical = ['gopher', 'hdl', 'mailto', 'news', 'telnet', 'wais', 'imap', 'snews', 'sip', 'sips'] uses_params = ['ftp', 'hdl', 'prospero', 'http', 'imap', @@ -307,17 +307,20 @@ """unquote_to_bytes('abc%20def') -> b'abc def'.""" # Note: strings are encoded as UTF-8. This is only an issue if it contains # unescaped non-ASCII characters, which URIs should not. + if not string: + return b'' if isinstance(string, str): string = string.encode('utf-8') res = string.split(b'%') - res[0] = res[0] - for i in range(1, len(res)): - item = res[i] + if len(res) == 1: + return string + string = res[0] + for item in res[1:]: try: - res[i] = bytes([int(item[:2], 16)]) + item[2:] + string += bytes([int(item[:2], 16)]) + item[2:] except ValueError: - res[i] = b'%' + item - return b''.join(res) + string += b'%' + item + return string def unquote(string, encoding='utf-8', errors='replace'): """Replace %xx escapes by their single-character equivalent. The optional @@ -329,36 +332,39 @@ unquote('abc%20def') -> 'abc def'. """ - if encoding is None: encoding = 'utf-8' - if errors is None: errors = 'replace' - # pct_sequence: contiguous sequence of percent-encoded bytes, decoded - # (list of single-byte bytes objects) - pct_sequence = [] + if not string: + return string res = string.split('%') - for i in range(1, len(res)): - item = res[i] + if len(res) == 1: + return string + if encoding is None: + encoding = 'utf-8' + if errors is None: + errors = 'replace' + # pct_sequence: contiguous sequence of percent-encoded bytes, decoded + pct_sequence = b'' + string = res[0] + for item in res[1:]: try: - if not item: raise ValueError - pct_sequence.append(bytes.fromhex(item[:2])) + if not item: + raise ValueError + pct_sequence += bytes.fromhex(item[:2]) rest = item[2:] + if not rest: + # This segment was just a single percent-encoded character. + # May be part of a sequence of code units, so delay decoding. + # (Stored in pct_sequence). + continue except ValueError: rest = '%' + item - if not rest: - # This segment was just a single percent-encoded character. - # May be part of a sequence of code units, so delay decoding. - # (Stored in pct_sequence). - res[i] = '' - else: - # Encountered non-percent-encoded characters. Flush the current - # pct_sequence. - res[i] = b''.join(pct_sequence).decode(encoding, errors) + rest - pct_sequence = [] + # Encountered non-percent-encoded characters. Flush the current + # pct_sequence. + string += pct_sequence.decode(encoding, errors) + rest + pct_sequence = b'' if pct_sequence: # Flush the final pct_sequence - # res[-1] will always be empty if pct_sequence != [] - assert not res[-1], "string=%r, res=%r" % (string, res) - res[-1] = b''.join(pct_sequence).decode(encoding, errors) - return ''.join(res) + string += pct_sequence.decode(encoding, errors) + return string def parse_qs(qs, keep_blank_values=False, strict_parsing=False): """Parse a query given as a string argument. @@ -439,7 +445,8 @@ b'abcdefghijklmnopqrstuvwxyz' b'0123456789' b'_.-') -_safe_quoters= {} +_ALWAYS_SAFE_BYTES = bytes(_ALWAYS_SAFE) +_safe_quoters = {} class Quoter(collections.defaultdict): """A mapping from bytes (in range(0,256)) to strings. @@ -451,7 +458,7 @@ # of cached keys don't call Python code at all). def __init__(self, safe): """safe: bytes object.""" - self.safe = _ALWAYS_SAFE.union(c for c in safe if c < 128) + self.safe = _ALWAYS_SAFE.union(safe) def __repr__(self): # Without this, will just display as a defaultdict @@ -459,7 +466,7 @@ def __missing__(self, b): # Handle a cache miss. Store quoted string in cache and return. - res = b in self.safe and chr(b) or ('%%%02X' % b) + res = chr(b) if b in self.safe else '%{:02X}'.format(b) self[b] = res return res @@ -493,6 +500,8 @@ errors='strict' (unsupported characters raise a UnicodeEncodeError). """ if isinstance(string, str): + if not string: + return string if encoding is None: encoding = 'utf-8' if errors is None: @@ -527,18 +536,22 @@ not perform string-to-bytes encoding. It always returns an ASCII string. quote_from_bytes(b'abc def\xab') -> 'abc%20def%AB' """ + if not isinstance(bs, (bytes, bytearray)): + raise TypeError("quote_from_bytes() expected bytes") + if not bs: + return '' if isinstance(safe, str): # Normalize 'safe' by converting to bytes and removing non-ASCII chars safe = safe.encode('ascii', 'ignore') - cachekey = bytes(safe) # In case it was a bytearray - if not (isinstance(bs, bytes) or isinstance(bs, bytearray)): - raise TypeError("quote_from_bytes() expected a bytes") + else: + safe = bytes([c for c in safe if c < 128]) + if not bs.rstrip(_ALWAYS_SAFE_BYTES + safe): + return bs.decode() try: - quoter = _safe_quoters[cachekey] + quoter = _safe_quoters[safe] except KeyError: - quoter = Quoter(safe) - _safe_quoters[cachekey] = quoter - return ''.join([quoter[char] for char in bs]) + _safe_quoters[safe] = quoter = Quoter(safe).__getitem__ + return ''.join([quoter(char) for char in bs]) def urlencode(query, doseq=False): """Encode a sequence of two-element tuples or dictionary into a URL query string. Modified: python/branches/py3k-cdecimal/Lib/urllib/request.py ============================================================================== --- python/branches/py3k-cdecimal/Lib/urllib/request.py (original) +++ python/branches/py3k-cdecimal/Lib/urllib/request.py Wed May 19 17:30:16 2010 @@ -1965,7 +1965,7 @@ else: return self.open(newurl, data) - def get_user_passwd(self, host, realm, clear_cache = 0): + def get_user_passwd(self, host, realm, clear_cache=0): key = realm + '@' + host.lower() if key in self.auth_cache: if clear_cache: Modified: python/branches/py3k-cdecimal/Misc/NEWS ============================================================================== --- python/branches/py3k-cdecimal/Misc/NEWS (original) +++ python/branches/py3k-cdecimal/Misc/NEWS Wed May 19 17:30:16 2010 @@ -12,6 +12,9 @@ Core and Builtins ----------------- +- PyObject_Dump() encodes unicode objects to utf8 with backslashreplace + (instead of strict) error handler to escape surrogates + - Issue #8715: Create PyUnicode_EncodeFSDefault() function: Encode a Unicode object to Py_FileSystemDefaultEncoding with the "surrogateescape" error handler, and return bytes. If Py_FileSystemDefaultEncoding is not set, fall @@ -363,6 +366,24 @@ Library ------- +- Issue #8513: os.get_exec_path() supports b'PATH' key and bytes value. + subprocess.Popen() and os._execvpe() support bytes program name. Add + os.supports_bytes_environ flag: True if the native OS type of the environment + is bytes (eg. False on Windows). + +- Issue #8633: tarfile is now able to read and write archives with "raw" binary + pax headers as described in POSIX.1-2008. + +- Issue #1285086: Speed up urllib.parse functions: quote, quote_from_bytes, + unquote, unquote_to_bytes. + +- Issue #8688: Distutils now recalculates MANIFEST everytime. + +- Issue #8477: ssl.RAND_egd() and ssl._test_decode_cert() support str with + surrogates and bytes for the filename + +- Issue #8550: Add first class ``SSLContext`` objects to the ssl module. + - Issue #8681: Make the zlib module's error messages more informative when the zlib itself doesn't give any detailed explanation. Modified: python/branches/py3k-cdecimal/Modules/_cursesmodule.c ============================================================================== --- python/branches/py3k-cdecimal/Modules/_cursesmodule.c (original) +++ python/branches/py3k-cdecimal/Modules/_cursesmodule.c Wed May 19 17:30:16 2010 @@ -33,66 +33,66 @@ /* -A number of SysV or ncurses functions don't have wrappers yet; if you -need a given function, add it and send a patch. See -http://www.python.org/dev/patches/ for instructions on how to submit -patches to Python. - -Here's a list of currently unsupported functions: - - addchnstr addchstr color_set define_key - del_curterm delscreen dupwin inchnstr inchstr innstr keyok - mcprint mvaddchnstr mvaddchstr mvcur mvinchnstr - mvinchstr mvinnstr mmvwaddchnstr mvwaddchstr - mvwinchnstr mvwinchstr mvwinnstr newterm - restartterm ripoffline scr_dump - scr_init scr_restore scr_set scrl set_curterm set_term setterm - tgetent tgetflag tgetnum tgetstr tgoto timeout tputs - vidattr vidputs waddchnstr waddchstr - wcolor_set winchnstr winchstr winnstr wmouse_trafo wscrl - -Low-priority: - slk_attr slk_attr_off slk_attr_on slk_attr_set slk_attroff - slk_attron slk_attrset slk_clear slk_color slk_init slk_label - slk_noutrefresh slk_refresh slk_restore slk_set slk_touch - -Menu extension (ncurses and probably SYSV): - current_item free_item free_menu item_count item_description - item_index item_init item_name item_opts item_opts_off - item_opts_on item_term item_userptr item_value item_visible - menu_back menu_driver menu_fore menu_format menu_grey - menu_init menu_items menu_mark menu_opts menu_opts_off - menu_opts_on menu_pad menu_pattern menu_request_by_name - menu_request_name menu_spacing menu_sub menu_term menu_userptr - menu_win new_item new_menu pos_menu_cursor post_menu - scale_menu set_current_item set_item_init set_item_opts - set_item_term set_item_userptr set_item_value set_menu_back - set_menu_fore set_menu_format set_menu_grey set_menu_init - set_menu_items set_menu_mark set_menu_opts set_menu_pad - set_menu_pattern set_menu_spacing set_menu_sub set_menu_term - set_menu_userptr set_menu_win set_top_row top_row unpost_menu - -Form extension (ncurses and probably SYSV): - current_field data_ahead data_behind dup_field - dynamic_fieldinfo field_arg field_back field_buffer - field_count field_fore field_index field_info field_init - field_just field_opts field_opts_off field_opts_on field_pad - field_status field_term field_type field_userptr form_driver - form_fields form_init form_opts form_opts_off form_opts_on - form_page form_request_by_name form_request_name form_sub - form_term form_userptr form_win free_field free_form - link_field link_fieldtype move_field new_field new_form - new_page pos_form_cursor post_form scale_form - set_current_field set_field_back set_field_buffer - set_field_fore set_field_init set_field_just set_field_opts - set_field_pad set_field_status set_field_term set_field_type - set_field_userptr set_fieldtype_arg set_fieldtype_choice - set_form_fields set_form_init set_form_opts set_form_page - set_form_sub set_form_term set_form_userptr set_form_win - set_max_field set_new_page unpost_form + A number of SysV or ncurses functions don't have wrappers yet; if you + need a given function, add it and send a patch. See + http://www.python.org/dev/patches/ for instructions on how to submit + patches to Python. + + Here's a list of currently unsupported functions: + + addchnstr addchstr color_set define_key + del_curterm delscreen dupwin inchnstr inchstr innstr keyok + mcprint mvaddchnstr mvaddchstr mvcur mvinchnstr + mvinchstr mvinnstr mmvwaddchnstr mvwaddchstr + mvwinchnstr mvwinchstr mvwinnstr newterm + restartterm ripoffline scr_dump + scr_init scr_restore scr_set scrl set_curterm set_term setterm + tgetent tgetflag tgetnum tgetstr tgoto timeout tputs + vidattr vidputs waddchnstr waddchstr + wcolor_set winchnstr winchstr winnstr wmouse_trafo wscrl + + Low-priority: + slk_attr slk_attr_off slk_attr_on slk_attr_set slk_attroff + slk_attron slk_attrset slk_clear slk_color slk_init slk_label + slk_noutrefresh slk_refresh slk_restore slk_set slk_touch + + Menu extension (ncurses and probably SYSV): + current_item free_item free_menu item_count item_description + item_index item_init item_name item_opts item_opts_off + item_opts_on item_term item_userptr item_value item_visible + menu_back menu_driver menu_fore menu_format menu_grey + menu_init menu_items menu_mark menu_opts menu_opts_off + menu_opts_on menu_pad menu_pattern menu_request_by_name + menu_request_name menu_spacing menu_sub menu_term menu_userptr + menu_win new_item new_menu pos_menu_cursor post_menu + scale_menu set_current_item set_item_init set_item_opts + set_item_term set_item_userptr set_item_value set_menu_back + set_menu_fore set_menu_format set_menu_grey set_menu_init + set_menu_items set_menu_mark set_menu_opts set_menu_pad + set_menu_pattern set_menu_spacing set_menu_sub set_menu_term + set_menu_userptr set_menu_win set_top_row top_row unpost_menu + + Form extension (ncurses and probably SYSV): + current_field data_ahead data_behind dup_field + dynamic_fieldinfo field_arg field_back field_buffer + field_count field_fore field_index field_info field_init + field_just field_opts field_opts_off field_opts_on field_pad + field_status field_term field_type field_userptr form_driver + form_fields form_init form_opts form_opts_off form_opts_on + form_page form_request_by_name form_request_name form_sub + form_term form_userptr form_win free_field free_form + link_field link_fieldtype move_field new_field new_form + new_page pos_form_cursor post_form scale_form + set_current_field set_field_back set_field_buffer + set_field_fore set_field_init set_field_just set_field_opts + set_field_pad set_field_status set_field_term set_field_type + set_field_userptr set_fieldtype_arg set_fieldtype_choice + set_form_fields set_form_init set_form_opts set_form_page + set_form_sub set_form_term set_form_userptr set_form_win + set_max_field set_new_page unpost_form - */ +*/ /* Release Number */ @@ -116,9 +116,9 @@ #define CURSES_MODULE #include "py_curses.h" -/* These prototypes are in , but including this header - #defines many common symbols (such as "lines") which breaks the - curses module in other ways. So the code will just specify +/* These prototypes are in , but including this header + #defines many common symbols (such as "lines") which breaks the + curses module in other ways. So the code will just specify explicit prototypes here. */ extern int setupterm(char *,int,int *); #ifdef __sgi @@ -148,23 +148,23 @@ static int initialisedcolors = FALSE; /* Utility Macros */ -#define PyCursesSetupTermCalled \ - if (initialised_setupterm != TRUE) { \ - PyErr_SetString(PyCursesError, \ - "must call (at least) setupterm() first"); \ - return 0; } - -#define PyCursesInitialised \ - if (initialised != TRUE) { \ - PyErr_SetString(PyCursesError, \ - "must call initscr() first"); \ - return 0; } - -#define PyCursesInitialisedColor \ - if (initialisedcolors != TRUE) { \ - PyErr_SetString(PyCursesError, \ - "must call start_color() first"); \ - return 0; } +#define PyCursesSetupTermCalled \ + if (initialised_setupterm != TRUE) { \ + PyErr_SetString(PyCursesError, \ + "must call (at least) setupterm() first"); \ + return 0; } + +#define PyCursesInitialised \ + if (initialised != TRUE) { \ + PyErr_SetString(PyCursesError, \ + "must call initscr() first"); \ + return 0; } + +#define PyCursesInitialisedColor \ + if (initialisedcolors != TRUE) { \ + PyErr_SetString(PyCursesError, \ + "must call start_color() first"); \ + return 0; } #ifndef MIN #define MIN(x,y) ((x) < (y) ? (x) : (y)) @@ -173,51 +173,51 @@ /* Utility Functions */ /* - * Check the return code from a curses function and return None + * Check the return code from a curses function and return None * or raise an exception as appropriate. These are exported using the - * capsule API. + * capsule API. */ static PyObject * PyCursesCheckERR(int code, char *fname) { - if (code != ERR) { - Py_INCREF(Py_None); - return Py_None; - } else { - if (fname == NULL) { - PyErr_SetString(PyCursesError, catchall_ERR); + if (code != ERR) { + Py_INCREF(Py_None); + return Py_None; } else { - PyErr_Format(PyCursesError, "%s() returned ERR", fname); + if (fname == NULL) { + PyErr_SetString(PyCursesError, catchall_ERR); + } else { + PyErr_Format(PyCursesError, "%s() returned ERR", fname); + } + return NULL; } - return NULL; - } } -static int +static int PyCurses_ConvertToChtype(PyObject *obj, chtype *ch) { - if (PyLong_CheckExact(obj)) { - int overflow; - /* XXX should the truncation by the cast also be reported - as an error? */ - *ch = (chtype) PyLong_AsLongAndOverflow(obj, &overflow); - if (overflow) - return 0; - } else if(PyBytes_Check(obj) - && (PyBytes_Size(obj) == 1)) { - *ch = (chtype) *PyBytes_AsString(obj); - } else if (PyUnicode_Check(obj) && PyUnicode_GetSize(obj) == 1) { - *ch = (chtype) *PyUnicode_AS_UNICODE(obj); - } else { - return 0; - } - return 1; + if (PyLong_CheckExact(obj)) { + int overflow; + /* XXX should the truncation by the cast also be reported + as an error? */ + *ch = (chtype) PyLong_AsLongAndOverflow(obj, &overflow); + if (overflow) + return 0; + } else if(PyBytes_Check(obj) + && (PyBytes_Size(obj) == 1)) { + *ch = (chtype) *PyBytes_AsString(obj); + } else if (PyUnicode_Check(obj) && PyUnicode_GetSize(obj) == 1) { + *ch = (chtype) *PyUnicode_AS_UNICODE(obj); + } else { + return 0; + } + return 1; } /* Function versions of the 3 functions for testing whether curses has been initialised or not. */ - + static int func_PyCursesSetupTermCalled(void) { PyCursesSetupTermCalled; @@ -250,56 +250,56 @@ TYPE - parameter Type ERGSTR - format string for construction of the return value PARSESTR - format string for argument parsing - */ +*/ -#define Window_NoArgNoReturnFunction(X) \ -static PyObject *PyCursesWindow_ ## X \ -(PyCursesWindowObject *self, PyObject *args) \ -{ return PyCursesCheckERR(X(self->win), # X); } - -#define Window_NoArgTrueFalseFunction(X) \ -static PyObject * PyCursesWindow_ ## X \ -(PyCursesWindowObject *self) \ -{ \ - if (X (self->win) == FALSE) { Py_INCREF(Py_False); return Py_False; } \ - else { Py_INCREF(Py_True); return Py_True; } } - -#define Window_NoArgNoReturnVoidFunction(X) \ -static PyObject * PyCursesWindow_ ## X \ -(PyCursesWindowObject *self) \ -{ \ - X(self->win); Py_INCREF(Py_None); return Py_None; } - -#define Window_NoArg2TupleReturnFunction(X, TYPE, ERGSTR) \ -static PyObject * PyCursesWindow_ ## X \ -(PyCursesWindowObject *self) \ -{ \ - TYPE arg1, arg2; \ - X(self->win,arg1,arg2); return Py_BuildValue(ERGSTR, arg1, arg2); } - -#define Window_OneArgNoReturnVoidFunction(X, TYPE, PARSESTR) \ -static PyObject * PyCursesWindow_ ## X \ -(PyCursesWindowObject *self, PyObject *args) \ -{ \ - TYPE arg1; \ - if (!PyArg_ParseTuple(args, PARSESTR, &arg1)) return NULL; \ - X(self->win,arg1); Py_INCREF(Py_None); return Py_None; } - -#define Window_OneArgNoReturnFunction(X, TYPE, PARSESTR) \ -static PyObject * PyCursesWindow_ ## X \ -(PyCursesWindowObject *self, PyObject *args) \ -{ \ - TYPE arg1; \ - if (!PyArg_ParseTuple(args,PARSESTR, &arg1)) return NULL; \ - return PyCursesCheckERR(X(self->win, arg1), # X); } - -#define Window_TwoArgNoReturnFunction(X, TYPE, PARSESTR) \ -static PyObject * PyCursesWindow_ ## X \ -(PyCursesWindowObject *self, PyObject *args) \ -{ \ - TYPE arg1, arg2; \ - if (!PyArg_ParseTuple(args,PARSESTR, &arg1, &arg2)) return NULL; \ - return PyCursesCheckERR(X(self->win, arg1, arg2), # X); } +#define Window_NoArgNoReturnFunction(X) \ + static PyObject *PyCursesWindow_ ## X \ + (PyCursesWindowObject *self, PyObject *args) \ + { return PyCursesCheckERR(X(self->win), # X); } + +#define Window_NoArgTrueFalseFunction(X) \ + static PyObject * PyCursesWindow_ ## X \ + (PyCursesWindowObject *self) \ + { \ + if (X (self->win) == FALSE) { Py_INCREF(Py_False); return Py_False; } \ + else { Py_INCREF(Py_True); return Py_True; } } + +#define Window_NoArgNoReturnVoidFunction(X) \ + static PyObject * PyCursesWindow_ ## X \ + (PyCursesWindowObject *self) \ + { \ + X(self->win); Py_INCREF(Py_None); return Py_None; } + +#define Window_NoArg2TupleReturnFunction(X, TYPE, ERGSTR) \ + static PyObject * PyCursesWindow_ ## X \ + (PyCursesWindowObject *self) \ + { \ + TYPE arg1, arg2; \ + X(self->win,arg1,arg2); return Py_BuildValue(ERGSTR, arg1, arg2); } + +#define Window_OneArgNoReturnVoidFunction(X, TYPE, PARSESTR) \ + static PyObject * PyCursesWindow_ ## X \ + (PyCursesWindowObject *self, PyObject *args) \ + { \ + TYPE arg1; \ + if (!PyArg_ParseTuple(args, PARSESTR, &arg1)) return NULL; \ + X(self->win,arg1); Py_INCREF(Py_None); return Py_None; } + +#define Window_OneArgNoReturnFunction(X, TYPE, PARSESTR) \ + static PyObject * PyCursesWindow_ ## X \ + (PyCursesWindowObject *self, PyObject *args) \ + { \ + TYPE arg1; \ + if (!PyArg_ParseTuple(args,PARSESTR, &arg1)) return NULL; \ + return PyCursesCheckERR(X(self->win, arg1), # X); } + +#define Window_TwoArgNoReturnFunction(X, TYPE, PARSESTR) \ + static PyObject * PyCursesWindow_ ## X \ + (PyCursesWindowObject *self, PyObject *args) \ + { \ + TYPE arg1, arg2; \ + if (!PyArg_ParseTuple(args,PARSESTR, &arg1, &arg2)) return NULL; \ + return PyCursesCheckERR(X(self->win, arg1, arg2), # X); } /* ------------- WINDOW routines --------------- */ @@ -360,19 +360,19 @@ static PyObject * PyCursesWindow_New(WINDOW *win) { - PyCursesWindowObject *wo; + PyCursesWindowObject *wo; - wo = PyObject_NEW(PyCursesWindowObject, &PyCursesWindow_Type); - if (wo == NULL) return NULL; - wo->win = win; - return (PyObject *)wo; + wo = PyObject_NEW(PyCursesWindowObject, &PyCursesWindow_Type); + if (wo == NULL) return NULL; + wo->win = win; + return (PyObject *)wo; } static void PyCursesWindow_Dealloc(PyCursesWindowObject *wo) { - if (wo->win != stdscr) delwin(wo->win); - PyObject_DEL(wo); + if (wo->win != stdscr) delwin(wo->win); + PyObject_DEL(wo); } /* Addch, Addstr, Addnstr */ @@ -380,287 +380,287 @@ static PyObject * PyCursesWindow_AddCh(PyCursesWindowObject *self, PyObject *args) { - int rtn, x, y, use_xy = FALSE; - PyObject *temp; - chtype ch = 0; - attr_t attr = A_NORMAL; - long lattr; - - switch (PyTuple_Size(args)) { - case 1: - if (!PyArg_ParseTuple(args, "O;ch or int", &temp)) - return NULL; - break; - case 2: - if (!PyArg_ParseTuple(args, "Ol;ch or int,attr", &temp, &lattr)) - return NULL; - attr = lattr; - break; - case 3: - if (!PyArg_ParseTuple(args,"iiO;y,x,ch or int", &y, &x, &temp)) - return NULL; - use_xy = TRUE; - break; - case 4: - if (!PyArg_ParseTuple(args,"iiOl;y,x,ch or int, attr", - &y, &x, &temp, &lattr)) - return NULL; - attr = lattr; - use_xy = TRUE; - break; - default: - PyErr_SetString(PyExc_TypeError, "addch requires 1 to 4 arguments"); - return NULL; - } - - if (!PyCurses_ConvertToChtype(temp, &ch)) { - PyErr_SetString(PyExc_TypeError, "argument 1 or 3 must be a ch or an int"); - return NULL; - } - - if (use_xy == TRUE) - rtn = mvwaddch(self->win,y,x, ch | attr); - else { - rtn = waddch(self->win, ch | attr); - } - return PyCursesCheckERR(rtn, "addch"); + int rtn, x, y, use_xy = FALSE; + PyObject *temp; + chtype ch = 0; + attr_t attr = A_NORMAL; + long lattr; + + switch (PyTuple_Size(args)) { + case 1: + if (!PyArg_ParseTuple(args, "O;ch or int", &temp)) + return NULL; + break; + case 2: + if (!PyArg_ParseTuple(args, "Ol;ch or int,attr", &temp, &lattr)) + return NULL; + attr = lattr; + break; + case 3: + if (!PyArg_ParseTuple(args,"iiO;y,x,ch or int", &y, &x, &temp)) + return NULL; + use_xy = TRUE; + break; + case 4: + if (!PyArg_ParseTuple(args,"iiOl;y,x,ch or int, attr", + &y, &x, &temp, &lattr)) + return NULL; + attr = lattr; + use_xy = TRUE; + break; + default: + PyErr_SetString(PyExc_TypeError, "addch requires 1 to 4 arguments"); + return NULL; + } + + if (!PyCurses_ConvertToChtype(temp, &ch)) { + PyErr_SetString(PyExc_TypeError, "argument 1 or 3 must be a ch or an int"); + return NULL; + } + + if (use_xy == TRUE) + rtn = mvwaddch(self->win,y,x, ch | attr); + else { + rtn = waddch(self->win, ch | attr); + } + return PyCursesCheckERR(rtn, "addch"); } static PyObject * PyCursesWindow_AddStr(PyCursesWindowObject *self, PyObject *args) { - int rtn; - int x, y; - char *str; - attr_t attr = A_NORMAL , attr_old = A_NORMAL; - long lattr; - int use_xy = FALSE, use_attr = FALSE; - - switch (PyTuple_Size(args)) { - case 1: - if (!PyArg_ParseTuple(args,"s;str", &str)) - return NULL; - break; - case 2: - if (!PyArg_ParseTuple(args,"sl;str,attr", &str, &lattr)) - return NULL; - attr = lattr; - use_attr = TRUE; - break; - case 3: - if (!PyArg_ParseTuple(args,"iis;int,int,str", &y, &x, &str)) - return NULL; - use_xy = TRUE; - break; - case 4: - if (!PyArg_ParseTuple(args,"iisl;int,int,str,attr", &y, &x, &str, &lattr)) - return NULL; - attr = lattr; - use_xy = use_attr = TRUE; - break; - default: - PyErr_SetString(PyExc_TypeError, "addstr requires 1 to 4 arguments"); - return NULL; - } - - if (use_attr == TRUE) { - attr_old = getattrs(self->win); - (void)wattrset(self->win,attr); - } - if (use_xy == TRUE) - rtn = mvwaddstr(self->win,y,x,str); - else - rtn = waddstr(self->win,str); - if (use_attr == TRUE) - (void)wattrset(self->win,attr_old); - return PyCursesCheckERR(rtn, "addstr"); + int rtn; + int x, y; + char *str; + attr_t attr = A_NORMAL , attr_old = A_NORMAL; + long lattr; + int use_xy = FALSE, use_attr = FALSE; + + switch (PyTuple_Size(args)) { + case 1: + if (!PyArg_ParseTuple(args,"s;str", &str)) + return NULL; + break; + case 2: + if (!PyArg_ParseTuple(args,"sl;str,attr", &str, &lattr)) + return NULL; + attr = lattr; + use_attr = TRUE; + break; + case 3: + if (!PyArg_ParseTuple(args,"iis;int,int,str", &y, &x, &str)) + return NULL; + use_xy = TRUE; + break; + case 4: + if (!PyArg_ParseTuple(args,"iisl;int,int,str,attr", &y, &x, &str, &lattr)) + return NULL; + attr = lattr; + use_xy = use_attr = TRUE; + break; + default: + PyErr_SetString(PyExc_TypeError, "addstr requires 1 to 4 arguments"); + return NULL; + } + + if (use_attr == TRUE) { + attr_old = getattrs(self->win); + (void)wattrset(self->win,attr); + } + if (use_xy == TRUE) + rtn = mvwaddstr(self->win,y,x,str); + else + rtn = waddstr(self->win,str); + if (use_attr == TRUE) + (void)wattrset(self->win,attr_old); + return PyCursesCheckERR(rtn, "addstr"); } static PyObject * PyCursesWindow_AddNStr(PyCursesWindowObject *self, PyObject *args) { - int rtn, x, y, n; - char *str; - attr_t attr = A_NORMAL , attr_old = A_NORMAL; - long lattr; - int use_xy = FALSE, use_attr = FALSE; - - switch (PyTuple_Size(args)) { - case 2: - if (!PyArg_ParseTuple(args,"si;str,n", &str, &n)) - return NULL; - break; - case 3: - if (!PyArg_ParseTuple(args,"sil;str,n,attr", &str, &n, &lattr)) - return NULL; - attr = lattr; - use_attr = TRUE; - break; - case 4: - if (!PyArg_ParseTuple(args,"iisi;y,x,str,n", &y, &x, &str, &n)) - return NULL; - use_xy = TRUE; - break; - case 5: - if (!PyArg_ParseTuple(args,"iisil;y,x,str,n,attr", &y, &x, &str, &n, &lattr)) - return NULL; - attr = lattr; - use_xy = use_attr = TRUE; - break; - default: - PyErr_SetString(PyExc_TypeError, "addnstr requires 2 to 5 arguments"); - return NULL; - } - - if (use_attr == TRUE) { - attr_old = getattrs(self->win); - (void)wattrset(self->win,attr); - } - if (use_xy == TRUE) - rtn = mvwaddnstr(self->win,y,x,str,n); - else - rtn = waddnstr(self->win,str,n); - if (use_attr == TRUE) - (void)wattrset(self->win,attr_old); - return PyCursesCheckERR(rtn, "addnstr"); + int rtn, x, y, n; + char *str; + attr_t attr = A_NORMAL , attr_old = A_NORMAL; + long lattr; + int use_xy = FALSE, use_attr = FALSE; + + switch (PyTuple_Size(args)) { + case 2: + if (!PyArg_ParseTuple(args,"si;str,n", &str, &n)) + return NULL; + break; + case 3: + if (!PyArg_ParseTuple(args,"sil;str,n,attr", &str, &n, &lattr)) + return NULL; + attr = lattr; + use_attr = TRUE; + break; + case 4: + if (!PyArg_ParseTuple(args,"iisi;y,x,str,n", &y, &x, &str, &n)) + return NULL; + use_xy = TRUE; + break; + case 5: + if (!PyArg_ParseTuple(args,"iisil;y,x,str,n,attr", &y, &x, &str, &n, &lattr)) + return NULL; + attr = lattr; + use_xy = use_attr = TRUE; + break; + default: + PyErr_SetString(PyExc_TypeError, "addnstr requires 2 to 5 arguments"); + return NULL; + } + + if (use_attr == TRUE) { + attr_old = getattrs(self->win); + (void)wattrset(self->win,attr); + } + if (use_xy == TRUE) + rtn = mvwaddnstr(self->win,y,x,str,n); + else + rtn = waddnstr(self->win,str,n); + if (use_attr == TRUE) + (void)wattrset(self->win,attr_old); + return PyCursesCheckERR(rtn, "addnstr"); } static PyObject * PyCursesWindow_Bkgd(PyCursesWindowObject *self, PyObject *args) { - PyObject *temp; - chtype bkgd; - attr_t attr = A_NORMAL; - long lattr; + PyObject *temp; + chtype bkgd; + attr_t attr = A_NORMAL; + long lattr; - switch (PyTuple_Size(args)) { + switch (PyTuple_Size(args)) { case 1: - if (!PyArg_ParseTuple(args, "O;ch or int", &temp)) - return NULL; - break; + if (!PyArg_ParseTuple(args, "O;ch or int", &temp)) + return NULL; + break; case 2: - if (!PyArg_ParseTuple(args,"Ol;ch or int,attr", &temp, &lattr)) - return NULL; - attr = lattr; - break; + if (!PyArg_ParseTuple(args,"Ol;ch or int,attr", &temp, &lattr)) + return NULL; + attr = lattr; + break; default: - PyErr_SetString(PyExc_TypeError, "bkgd requires 1 or 2 arguments"); - return NULL; - } + PyErr_SetString(PyExc_TypeError, "bkgd requires 1 or 2 arguments"); + return NULL; + } - if (!PyCurses_ConvertToChtype(temp, &bkgd)) { - PyErr_SetString(PyExc_TypeError, "argument 1 or 3 must be a ch or an int"); - return NULL; - } + if (!PyCurses_ConvertToChtype(temp, &bkgd)) { + PyErr_SetString(PyExc_TypeError, "argument 1 or 3 must be a ch or an int"); + return NULL; + } - return PyCursesCheckERR(wbkgd(self->win, bkgd | attr), "bkgd"); + return PyCursesCheckERR(wbkgd(self->win, bkgd | attr), "bkgd"); } static PyObject * PyCursesWindow_AttrOff(PyCursesWindowObject *self, PyObject *args) { - long lattr; - if (!PyArg_ParseTuple(args,"l;attr", &lattr)) - return NULL; - return PyCursesCheckERR(wattroff(self->win, (attr_t)lattr), "attroff"); + long lattr; + if (!PyArg_ParseTuple(args,"l;attr", &lattr)) + return NULL; + return PyCursesCheckERR(wattroff(self->win, (attr_t)lattr), "attroff"); } static PyObject * PyCursesWindow_AttrOn(PyCursesWindowObject *self, PyObject *args) { - long lattr; - if (!PyArg_ParseTuple(args,"l;attr", &lattr)) - return NULL; - return PyCursesCheckERR(wattron(self->win, (attr_t)lattr), "attron"); + long lattr; + if (!PyArg_ParseTuple(args,"l;attr", &lattr)) + return NULL; + return PyCursesCheckERR(wattron(self->win, (attr_t)lattr), "attron"); } static PyObject * PyCursesWindow_AttrSet(PyCursesWindowObject *self, PyObject *args) { - long lattr; - if (!PyArg_ParseTuple(args,"l;attr", &lattr)) - return NULL; - return PyCursesCheckERR(wattrset(self->win, (attr_t)lattr), "attrset"); + long lattr; + if (!PyArg_ParseTuple(args,"l;attr", &lattr)) + return NULL; + return PyCursesCheckERR(wattrset(self->win, (attr_t)lattr), "attrset"); } static PyObject * PyCursesWindow_BkgdSet(PyCursesWindowObject *self, PyObject *args) { - PyObject *temp; - chtype bkgd; - attr_t attr = A_NORMAL; - long lattr; + PyObject *temp; + chtype bkgd; + attr_t attr = A_NORMAL; + long lattr; - switch (PyTuple_Size(args)) { + switch (PyTuple_Size(args)) { case 1: - if (!PyArg_ParseTuple(args, "O;ch or int", &temp)) - return NULL; - break; + if (!PyArg_ParseTuple(args, "O;ch or int", &temp)) + return NULL; + break; case 2: - if (!PyArg_ParseTuple(args,"Ol;ch or int,attr", &temp, &lattr)) - return NULL; - attr = lattr; - break; + if (!PyArg_ParseTuple(args,"Ol;ch or int,attr", &temp, &lattr)) + return NULL; + attr = lattr; + break; default: - PyErr_SetString(PyExc_TypeError, "bkgdset requires 1 or 2 arguments"); - return NULL; - } + PyErr_SetString(PyExc_TypeError, "bkgdset requires 1 or 2 arguments"); + return NULL; + } - if (!PyCurses_ConvertToChtype(temp, &bkgd)) { - PyErr_SetString(PyExc_TypeError, "argument 1 must be a ch or an int"); - return NULL; - } + if (!PyCurses_ConvertToChtype(temp, &bkgd)) { + PyErr_SetString(PyExc_TypeError, "argument 1 must be a ch or an int"); + return NULL; + } - wbkgdset(self->win, bkgd | attr); - return PyCursesCheckERR(0, "bkgdset"); + wbkgdset(self->win, bkgd | attr); + return PyCursesCheckERR(0, "bkgdset"); } static PyObject * PyCursesWindow_Border(PyCursesWindowObject *self, PyObject *args) { - PyObject *temp[8]; - chtype ch[8]; - int i; - - /* Clear the array of parameters */ - for(i=0; i<8; i++) { - temp[i] = NULL; - ch[i] = 0; - } - - if (!PyArg_ParseTuple(args,"|OOOOOOOO;ls,rs,ts,bs,tl,tr,bl,br", - &temp[0], &temp[1], &temp[2], &temp[3], - &temp[4], &temp[5], &temp[6], &temp[7])) - return NULL; - - for(i=0; i<8; i++) { - if (temp[i] != NULL && !PyCurses_ConvertToChtype(temp[i], &ch[i])) { - PyErr_Format(PyExc_TypeError, - "argument %i must be a ch or an int", i+1); - return NULL; - } - } - - wborder(self->win, - ch[0], ch[1], ch[2], ch[3], - ch[4], ch[5], ch[6], ch[7]); - Py_INCREF(Py_None); - return Py_None; + PyObject *temp[8]; + chtype ch[8]; + int i; + + /* Clear the array of parameters */ + for(i=0; i<8; i++) { + temp[i] = NULL; + ch[i] = 0; + } + + if (!PyArg_ParseTuple(args,"|OOOOOOOO;ls,rs,ts,bs,tl,tr,bl,br", + &temp[0], &temp[1], &temp[2], &temp[3], + &temp[4], &temp[5], &temp[6], &temp[7])) + return NULL; + + for(i=0; i<8; i++) { + if (temp[i] != NULL && !PyCurses_ConvertToChtype(temp[i], &ch[i])) { + PyErr_Format(PyExc_TypeError, + "argument %i must be a ch or an int", i+1); + return NULL; + } + } + + wborder(self->win, + ch[0], ch[1], ch[2], ch[3], + ch[4], ch[5], ch[6], ch[7]); + Py_INCREF(Py_None); + return Py_None; } static PyObject * PyCursesWindow_Box(PyCursesWindowObject *self, PyObject *args) { - chtype ch1=0,ch2=0; - switch(PyTuple_Size(args)){ - case 0: break; - default: - if (!PyArg_ParseTuple(args,"ll;vertint,horint", &ch1, &ch2)) - return NULL; - } - box(self->win,ch1,ch2); - Py_INCREF(Py_None); - return Py_None; + chtype ch1=0,ch2=0; + switch(PyTuple_Size(args)){ + case 0: break; + default: + if (!PyArg_ParseTuple(args,"ll;vertint,horint", &ch1, &ch2)) + return NULL; + } + box(self->win,ch1,ch2); + Py_INCREF(Py_None); + return Py_None; } #if defined(HAVE_NCURSES_H) || defined(MVWDELCH_IS_EXPRESSION) @@ -668,10 +668,10 @@ #else int py_mvwdelch(WINDOW *w, int y, int x) { - mvwdelch(w,y,x); - /* On HP/UX, mvwdelch already returns. On other systems, - we may well run into this return statement. */ - return 0; + mvwdelch(w,y,x); + /* On HP/UX, mvwdelch already returns. On other systems, + we may well run into this return statement. */ + return 0; } #endif @@ -680,603 +680,603 @@ static PyObject * PyCursesWindow_ChgAt(PyCursesWindowObject *self, PyObject *args) { - int rtn; - int x, y; - int num = -1; - short color; - attr_t attr = A_NORMAL; - long lattr; - int use_xy = FALSE; + int rtn; + int x, y; + int num = -1; + short color; + attr_t attr = A_NORMAL; + long lattr; + int use_xy = FALSE; - switch (PyTuple_Size(args)) { - case 1: - if (!PyArg_ParseTuple(args,"l;attr", &lattr)) - return NULL; - attr = lattr; - break; - case 2: - if (!PyArg_ParseTuple(args,"il;n,attr", &num, &lattr)) - return NULL; - attr = lattr; - break; - case 3: - if (!PyArg_ParseTuple(args,"iil;int,int,attr", &y, &x, &lattr)) - return NULL; - attr = lattr; - use_xy = TRUE; - break; - case 4: - if (!PyArg_ParseTuple(args,"iiil;int,int,n,attr", &y, &x, &num, &lattr)) - return NULL; - attr = lattr; - use_xy = TRUE; - break; - default: - PyErr_SetString(PyExc_TypeError, "chgat requires 1 to 4 arguments"); - return NULL; - } - - color = (short)((attr >> 8) & 0xff); - attr = attr - (color << 8); - - if (use_xy == TRUE) { - rtn = mvwchgat(self->win,y,x,num,attr,color,NULL); - touchline(self->win,y,1); - } else { - getyx(self->win,y,x); - rtn = wchgat(self->win,num,attr,color,NULL); - touchline(self->win,y,1); - } - return PyCursesCheckERR(rtn, "chgat"); + switch (PyTuple_Size(args)) { + case 1: + if (!PyArg_ParseTuple(args,"l;attr", &lattr)) + return NULL; + attr = lattr; + break; + case 2: + if (!PyArg_ParseTuple(args,"il;n,attr", &num, &lattr)) + return NULL; + attr = lattr; + break; + case 3: + if (!PyArg_ParseTuple(args,"iil;int,int,attr", &y, &x, &lattr)) + return NULL; + attr = lattr; + use_xy = TRUE; + break; + case 4: + if (!PyArg_ParseTuple(args,"iiil;int,int,n,attr", &y, &x, &num, &lattr)) + return NULL; + attr = lattr; + use_xy = TRUE; + break; + default: + PyErr_SetString(PyExc_TypeError, "chgat requires 1 to 4 arguments"); + return NULL; + } + + color = (short)((attr >> 8) & 0xff); + attr = attr - (color << 8); + + if (use_xy == TRUE) { + rtn = mvwchgat(self->win,y,x,num,attr,color,NULL); + touchline(self->win,y,1); + } else { + getyx(self->win,y,x); + rtn = wchgat(self->win,num,attr,color,NULL); + touchline(self->win,y,1); + } + return PyCursesCheckERR(rtn, "chgat"); } static PyObject * PyCursesWindow_DelCh(PyCursesWindowObject *self, PyObject *args) { - int rtn; - int x, y; + int rtn; + int x, y; - switch (PyTuple_Size(args)) { - case 0: - rtn = wdelch(self->win); - break; - case 2: - if (!PyArg_ParseTuple(args,"ii;y,x", &y, &x)) - return NULL; - rtn = py_mvwdelch(self->win,y,x); - break; - default: - PyErr_SetString(PyExc_TypeError, "delch requires 0 or 2 arguments"); - return NULL; - } - return PyCursesCheckERR(rtn, "[mv]wdelch"); + switch (PyTuple_Size(args)) { + case 0: + rtn = wdelch(self->win); + break; + case 2: + if (!PyArg_ParseTuple(args,"ii;y,x", &y, &x)) + return NULL; + rtn = py_mvwdelch(self->win,y,x); + break; + default: + PyErr_SetString(PyExc_TypeError, "delch requires 0 or 2 arguments"); + return NULL; + } + return PyCursesCheckERR(rtn, "[mv]wdelch"); } static PyObject * PyCursesWindow_DerWin(PyCursesWindowObject *self, PyObject *args) { - WINDOW *win; - int nlines, ncols, begin_y, begin_x; + WINDOW *win; + int nlines, ncols, begin_y, begin_x; - nlines = 0; - ncols = 0; - switch (PyTuple_Size(args)) { - case 2: - if (!PyArg_ParseTuple(args,"ii;begin_y,begin_x",&begin_y,&begin_x)) - return NULL; - break; - case 4: - if (!PyArg_ParseTuple(args, "iiii;nlines,ncols,begin_y,begin_x", - &nlines,&ncols,&begin_y,&begin_x)) - return NULL; - break; - default: - PyErr_SetString(PyExc_TypeError, "derwin requires 2 or 4 arguments"); - return NULL; - } - - win = derwin(self->win,nlines,ncols,begin_y,begin_x); - - if (win == NULL) { - PyErr_SetString(PyCursesError, catchall_NULL); - return NULL; - } + nlines = 0; + ncols = 0; + switch (PyTuple_Size(args)) { + case 2: + if (!PyArg_ParseTuple(args,"ii;begin_y,begin_x",&begin_y,&begin_x)) + return NULL; + break; + case 4: + if (!PyArg_ParseTuple(args, "iiii;nlines,ncols,begin_y,begin_x", + &nlines,&ncols,&begin_y,&begin_x)) + return NULL; + break; + default: + PyErr_SetString(PyExc_TypeError, "derwin requires 2 or 4 arguments"); + return NULL; + } - return (PyObject *)PyCursesWindow_New(win); + win = derwin(self->win,nlines,ncols,begin_y,begin_x); + + if (win == NULL) { + PyErr_SetString(PyCursesError, catchall_NULL); + return NULL; + } + + return (PyObject *)PyCursesWindow_New(win); } static PyObject * PyCursesWindow_EchoChar(PyCursesWindowObject *self, PyObject *args) { - PyObject *temp; - chtype ch; - attr_t attr = A_NORMAL; - long lattr; - - switch (PyTuple_Size(args)) { - case 1: - if (!PyArg_ParseTuple(args,"O;ch or int", &temp)) - return NULL; - break; - case 2: - if (!PyArg_ParseTuple(args,"Ol;ch or int,attr", &temp, &lattr)) - return NULL; - attr = lattr; - break; - default: - PyErr_SetString(PyExc_TypeError, "echochar requires 1 or 2 arguments"); - - - return NULL; - } - - if (!PyCurses_ConvertToChtype(temp, &ch)) { - PyErr_SetString(PyExc_TypeError, "argument 1 must be a ch or an int"); - return NULL; - } - + PyObject *temp; + chtype ch; + attr_t attr = A_NORMAL; + long lattr; + + switch (PyTuple_Size(args)) { + case 1: + if (!PyArg_ParseTuple(args,"O;ch or int", &temp)) + return NULL; + break; + case 2: + if (!PyArg_ParseTuple(args,"Ol;ch or int,attr", &temp, &lattr)) + return NULL; + attr = lattr; + break; + default: + PyErr_SetString(PyExc_TypeError, "echochar requires 1 or 2 arguments"); + + + return NULL; + } + + if (!PyCurses_ConvertToChtype(temp, &ch)) { + PyErr_SetString(PyExc_TypeError, "argument 1 must be a ch or an int"); + return NULL; + } + #ifdef WINDOW_HAS_FLAGS - if (self->win->_flags & _ISPAD) - return PyCursesCheckERR(pechochar(self->win, ch | attr), - "echochar"); - else + if (self->win->_flags & _ISPAD) + return PyCursesCheckERR(pechochar(self->win, ch | attr), + "echochar"); + else #endif - return PyCursesCheckERR(wechochar(self->win, ch | attr), - "echochar"); + return PyCursesCheckERR(wechochar(self->win, ch | attr), + "echochar"); } #ifdef NCURSES_MOUSE_VERSION static PyObject * PyCursesWindow_Enclose(PyCursesWindowObject *self, PyObject *args) { - int x, y; - if (!PyArg_ParseTuple(args,"ii;y,x", &y, &x)) - return NULL; + int x, y; + if (!PyArg_ParseTuple(args,"ii;y,x", &y, &x)) + return NULL; - return PyLong_FromLong( wenclose(self->win,y,x) ); + return PyLong_FromLong( wenclose(self->win,y,x) ); } #endif static PyObject * PyCursesWindow_GetBkgd(PyCursesWindowObject *self) { - return PyLong_FromLong((long) getbkgd(self->win)); + return PyLong_FromLong((long) getbkgd(self->win)); } static PyObject * PyCursesWindow_GetCh(PyCursesWindowObject *self, PyObject *args) { - int x, y; - int rtn; + int x, y; + int rtn; - switch (PyTuple_Size(args)) { - case 0: - Py_BEGIN_ALLOW_THREADS - rtn = wgetch(self->win); - Py_END_ALLOW_THREADS - break; - case 2: - if (!PyArg_ParseTuple(args,"ii;y,x",&y,&x)) - return NULL; - Py_BEGIN_ALLOW_THREADS - rtn = mvwgetch(self->win,y,x); - Py_END_ALLOW_THREADS - break; - default: - PyErr_SetString(PyExc_TypeError, "getch requires 0 or 2 arguments"); - return NULL; - } - return PyLong_FromLong((long)rtn); + switch (PyTuple_Size(args)) { + case 0: + Py_BEGIN_ALLOW_THREADS + rtn = wgetch(self->win); + Py_END_ALLOW_THREADS + break; + case 2: + if (!PyArg_ParseTuple(args,"ii;y,x",&y,&x)) + return NULL; + Py_BEGIN_ALLOW_THREADS + rtn = mvwgetch(self->win,y,x); + Py_END_ALLOW_THREADS + break; + default: + PyErr_SetString(PyExc_TypeError, "getch requires 0 or 2 arguments"); + return NULL; + } + return PyLong_FromLong((long)rtn); } static PyObject * PyCursesWindow_GetKey(PyCursesWindowObject *self, PyObject *args) { - int x, y; - int rtn; + int x, y; + int rtn; - switch (PyTuple_Size(args)) { - case 0: - Py_BEGIN_ALLOW_THREADS - rtn = wgetch(self->win); - Py_END_ALLOW_THREADS - break; - case 2: - if (!PyArg_ParseTuple(args,"ii;y,x",&y,&x)) - return NULL; - Py_BEGIN_ALLOW_THREADS - rtn = mvwgetch(self->win,y,x); - Py_END_ALLOW_THREADS - break; - default: - PyErr_SetString(PyExc_TypeError, "getkey requires 0 or 2 arguments"); - return NULL; - } - if (rtn == ERR) { - /* getch() returns ERR in nodelay mode */ - PyErr_SetString(PyCursesError, "no input"); - return NULL; - } else if (rtn<=255) { - return Py_BuildValue("C", rtn); - } else { - const char *knp; + switch (PyTuple_Size(args)) { + case 0: + Py_BEGIN_ALLOW_THREADS + rtn = wgetch(self->win); + Py_END_ALLOW_THREADS + break; + case 2: + if (!PyArg_ParseTuple(args,"ii;y,x",&y,&x)) + return NULL; + Py_BEGIN_ALLOW_THREADS + rtn = mvwgetch(self->win,y,x); + Py_END_ALLOW_THREADS + break; + default: + PyErr_SetString(PyExc_TypeError, "getkey requires 0 or 2 arguments"); + return NULL; + } + if (rtn == ERR) { + /* getch() returns ERR in nodelay mode */ + PyErr_SetString(PyCursesError, "no input"); + return NULL; + } else if (rtn<=255) { + return Py_BuildValue("C", rtn); + } else { + const char *knp; #if defined(__NetBSD__) - knp = unctrl(rtn); + knp = unctrl(rtn); #else - knp = keyname(rtn); + knp = keyname(rtn); #endif - return PyUnicode_FromString((knp == NULL) ? "" : knp); - } + return PyUnicode_FromString((knp == NULL) ? "" : knp); + } } static PyObject * PyCursesWindow_GetStr(PyCursesWindowObject *self, PyObject *args) { - int x, y, n; - char rtn[1024]; /* This should be big enough.. I hope */ - int rtn2; - - switch (PyTuple_Size(args)) { - case 0: - Py_BEGIN_ALLOW_THREADS - rtn2 = wgetnstr(self->win,rtn, 1023); - Py_END_ALLOW_THREADS - break; - case 1: - if (!PyArg_ParseTuple(args,"i;n", &n)) - return NULL; - Py_BEGIN_ALLOW_THREADS - rtn2 = wgetnstr(self->win,rtn,MIN(n, 1023)); - Py_END_ALLOW_THREADS - break; - case 2: - if (!PyArg_ParseTuple(args,"ii;y,x",&y,&x)) - return NULL; - Py_BEGIN_ALLOW_THREADS + int x, y, n; + char rtn[1024]; /* This should be big enough.. I hope */ + int rtn2; + + switch (PyTuple_Size(args)) { + case 0: + Py_BEGIN_ALLOW_THREADS + rtn2 = wgetnstr(self->win,rtn, 1023); + Py_END_ALLOW_THREADS + break; + case 1: + if (!PyArg_ParseTuple(args,"i;n", &n)) + return NULL; + Py_BEGIN_ALLOW_THREADS + rtn2 = wgetnstr(self->win,rtn,MIN(n, 1023)); + Py_END_ALLOW_THREADS + break; + case 2: + if (!PyArg_ParseTuple(args,"ii;y,x",&y,&x)) + return NULL; + Py_BEGIN_ALLOW_THREADS #ifdef STRICT_SYSV_CURSES - rtn2 = wmove(self->win,y,x)==ERR ? ERR : wgetnstr(self->win, rtn, 1023); + rtn2 = wmove(self->win,y,x)==ERR ? ERR : wgetnstr(self->win, rtn, 1023); #else - rtn2 = mvwgetnstr(self->win,y,x,rtn, 1023); + rtn2 = mvwgetnstr(self->win,y,x,rtn, 1023); #endif - Py_END_ALLOW_THREADS - break; - case 3: - if (!PyArg_ParseTuple(args,"iii;y,x,n", &y, &x, &n)) - return NULL; + Py_END_ALLOW_THREADS + break; + case 3: + if (!PyArg_ParseTuple(args,"iii;y,x,n", &y, &x, &n)) + return NULL; #ifdef STRICT_SYSV_CURSES - Py_BEGIN_ALLOW_THREADS - rtn2 = wmove(self->win,y,x)==ERR ? ERR : - wgetnstr(self->win, rtn, MIN(n, 1023)); - Py_END_ALLOW_THREADS + Py_BEGIN_ALLOW_THREADS + rtn2 = wmove(self->win,y,x)==ERR ? ERR : + wgetnstr(self->win, rtn, MIN(n, 1023)); + Py_END_ALLOW_THREADS #else - Py_BEGIN_ALLOW_THREADS - rtn2 = mvwgetnstr(self->win, y, x, rtn, MIN(n, 1023)); - Py_END_ALLOW_THREADS -#endif - break; - default: - PyErr_SetString(PyExc_TypeError, "getstr requires 0 to 3 arguments"); - return NULL; - } - if (rtn2 == ERR) - rtn[0] = 0; - return PyBytes_FromString(rtn); + Py_BEGIN_ALLOW_THREADS + rtn2 = mvwgetnstr(self->win, y, x, rtn, MIN(n, 1023)); + Py_END_ALLOW_THREADS +#endif + break; + default: + PyErr_SetString(PyExc_TypeError, "getstr requires 0 to 3 arguments"); + return NULL; + } + if (rtn2 == ERR) + rtn[0] = 0; + return PyBytes_FromString(rtn); } static PyObject * PyCursesWindow_Hline(PyCursesWindowObject *self, PyObject *args) { - PyObject *temp; - chtype ch; - int n, x, y, code = OK; - attr_t attr = A_NORMAL; - long lattr; - - switch (PyTuple_Size(args)) { - case 2: - if (!PyArg_ParseTuple(args, "Oi;ch or int,n", &temp, &n)) - return NULL; - break; - case 3: - if (!PyArg_ParseTuple(args, "Oil;ch or int,n,attr", &temp, &n, &lattr)) - return NULL; - attr = lattr; - break; - case 4: - if (!PyArg_ParseTuple(args, "iiOi;y,x,ch or int,n", &y, &x, &temp, &n)) - return NULL; - code = wmove(self->win, y, x); - break; - case 5: - if (!PyArg_ParseTuple(args, "iiOil; y,x,ch or int,n,attr", - &y, &x, &temp, &n, &lattr)) - return NULL; - attr = lattr; - code = wmove(self->win, y, x); - break; - default: - PyErr_SetString(PyExc_TypeError, "hline requires 2 to 5 arguments"); - return NULL; - } + PyObject *temp; + chtype ch; + int n, x, y, code = OK; + attr_t attr = A_NORMAL; + long lattr; - if (code != ERR) { - if (!PyCurses_ConvertToChtype(temp, &ch)) { - PyErr_SetString(PyExc_TypeError, - "argument 1 or 3 must be a ch or an int"); - return NULL; - } - return PyCursesCheckERR(whline(self->win, ch | attr, n), "hline"); - } else - return PyCursesCheckERR(code, "wmove"); + switch (PyTuple_Size(args)) { + case 2: + if (!PyArg_ParseTuple(args, "Oi;ch or int,n", &temp, &n)) + return NULL; + break; + case 3: + if (!PyArg_ParseTuple(args, "Oil;ch or int,n,attr", &temp, &n, &lattr)) + return NULL; + attr = lattr; + break; + case 4: + if (!PyArg_ParseTuple(args, "iiOi;y,x,ch or int,n", &y, &x, &temp, &n)) + return NULL; + code = wmove(self->win, y, x); + break; + case 5: + if (!PyArg_ParseTuple(args, "iiOil; y,x,ch or int,n,attr", + &y, &x, &temp, &n, &lattr)) + return NULL; + attr = lattr; + code = wmove(self->win, y, x); + break; + default: + PyErr_SetString(PyExc_TypeError, "hline requires 2 to 5 arguments"); + return NULL; + } + + if (code != ERR) { + if (!PyCurses_ConvertToChtype(temp, &ch)) { + PyErr_SetString(PyExc_TypeError, + "argument 1 or 3 must be a ch or an int"); + return NULL; + } + return PyCursesCheckERR(whline(self->win, ch | attr, n), "hline"); + } else + return PyCursesCheckERR(code, "wmove"); } static PyObject * PyCursesWindow_InsCh(PyCursesWindowObject *self, PyObject *args) { - int rtn, x, y, use_xy = FALSE; - PyObject *temp; - chtype ch = 0; - attr_t attr = A_NORMAL; - long lattr; - - switch (PyTuple_Size(args)) { - case 1: - if (!PyArg_ParseTuple(args, "O;ch or int", &temp)) - return NULL; - break; - case 2: - if (!PyArg_ParseTuple(args, "Ol;ch or int,attr", &temp, &lattr)) - return NULL; - attr = lattr; - break; - case 3: - if (!PyArg_ParseTuple(args,"iiO;y,x,ch or int", &y, &x, &temp)) - return NULL; - use_xy = TRUE; - break; - case 4: - if (!PyArg_ParseTuple(args,"iiOl;y,x,ch or int, attr", &y, &x, &temp, &lattr)) - return NULL; - attr = lattr; - use_xy = TRUE; - break; - default: - PyErr_SetString(PyExc_TypeError, "insch requires 1 or 4 arguments"); - return NULL; - } - - if (!PyCurses_ConvertToChtype(temp, &ch)) { - PyErr_SetString(PyExc_TypeError, - "argument 1 or 3 must be a ch or an int"); - return NULL; - } - - if (use_xy == TRUE) - rtn = mvwinsch(self->win,y,x, ch | attr); - else { - rtn = winsch(self->win, ch | attr); - } - return PyCursesCheckERR(rtn, "insch"); + int rtn, x, y, use_xy = FALSE; + PyObject *temp; + chtype ch = 0; + attr_t attr = A_NORMAL; + long lattr; + + switch (PyTuple_Size(args)) { + case 1: + if (!PyArg_ParseTuple(args, "O;ch or int", &temp)) + return NULL; + break; + case 2: + if (!PyArg_ParseTuple(args, "Ol;ch or int,attr", &temp, &lattr)) + return NULL; + attr = lattr; + break; + case 3: + if (!PyArg_ParseTuple(args,"iiO;y,x,ch or int", &y, &x, &temp)) + return NULL; + use_xy = TRUE; + break; + case 4: + if (!PyArg_ParseTuple(args,"iiOl;y,x,ch or int, attr", &y, &x, &temp, &lattr)) + return NULL; + attr = lattr; + use_xy = TRUE; + break; + default: + PyErr_SetString(PyExc_TypeError, "insch requires 1 or 4 arguments"); + return NULL; + } + + if (!PyCurses_ConvertToChtype(temp, &ch)) { + PyErr_SetString(PyExc_TypeError, + "argument 1 or 3 must be a ch or an int"); + return NULL; + } + + if (use_xy == TRUE) + rtn = mvwinsch(self->win,y,x, ch | attr); + else { + rtn = winsch(self->win, ch | attr); + } + return PyCursesCheckERR(rtn, "insch"); } static PyObject * PyCursesWindow_InCh(PyCursesWindowObject *self, PyObject *args) { - int x, y, rtn; + int x, y, rtn; - switch (PyTuple_Size(args)) { - case 0: - rtn = winch(self->win); - break; - case 2: - if (!PyArg_ParseTuple(args,"ii;y,x",&y,&x)) - return NULL; - rtn = mvwinch(self->win,y,x); - break; - default: - PyErr_SetString(PyExc_TypeError, "inch requires 0 or 2 arguments"); - return NULL; - } - return PyLong_FromLong((long) rtn); + switch (PyTuple_Size(args)) { + case 0: + rtn = winch(self->win); + break; + case 2: + if (!PyArg_ParseTuple(args,"ii;y,x",&y,&x)) + return NULL; + rtn = mvwinch(self->win,y,x); + break; + default: + PyErr_SetString(PyExc_TypeError, "inch requires 0 or 2 arguments"); + return NULL; + } + return PyLong_FromLong((long) rtn); } static PyObject * PyCursesWindow_InStr(PyCursesWindowObject *self, PyObject *args) { - int x, y, n; - char rtn[1024]; /* This should be big enough.. I hope */ - int rtn2; - - switch (PyTuple_Size(args)) { - case 0: - rtn2 = winnstr(self->win,rtn, 1023); - break; - case 1: - if (!PyArg_ParseTuple(args,"i;n", &n)) - return NULL; - rtn2 = winnstr(self->win,rtn,MIN(n,1023)); - break; - case 2: - if (!PyArg_ParseTuple(args,"ii;y,x",&y,&x)) - return NULL; - rtn2 = mvwinnstr(self->win,y,x,rtn,1023); - break; - case 3: - if (!PyArg_ParseTuple(args, "iii;y,x,n", &y, &x, &n)) - return NULL; - rtn2 = mvwinnstr(self->win, y, x, rtn, MIN(n,1023)); - break; - default: - PyErr_SetString(PyExc_TypeError, "instr requires 0 or 3 arguments"); - return NULL; - } - if (rtn2 == ERR) - rtn[0] = 0; - return PyBytes_FromString(rtn); + int x, y, n; + char rtn[1024]; /* This should be big enough.. I hope */ + int rtn2; + + switch (PyTuple_Size(args)) { + case 0: + rtn2 = winnstr(self->win,rtn, 1023); + break; + case 1: + if (!PyArg_ParseTuple(args,"i;n", &n)) + return NULL; + rtn2 = winnstr(self->win,rtn,MIN(n,1023)); + break; + case 2: + if (!PyArg_ParseTuple(args,"ii;y,x",&y,&x)) + return NULL; + rtn2 = mvwinnstr(self->win,y,x,rtn,1023); + break; + case 3: + if (!PyArg_ParseTuple(args, "iii;y,x,n", &y, &x, &n)) + return NULL; + rtn2 = mvwinnstr(self->win, y, x, rtn, MIN(n,1023)); + break; + default: + PyErr_SetString(PyExc_TypeError, "instr requires 0 or 3 arguments"); + return NULL; + } + if (rtn2 == ERR) + rtn[0] = 0; + return PyBytes_FromString(rtn); } static PyObject * PyCursesWindow_InsStr(PyCursesWindowObject *self, PyObject *args) { - int rtn; - int x, y; - char *str; - attr_t attr = A_NORMAL , attr_old = A_NORMAL; - long lattr; - int use_xy = FALSE, use_attr = FALSE; - - switch (PyTuple_Size(args)) { - case 1: - if (!PyArg_ParseTuple(args,"s;str", &str)) - return NULL; - break; - case 2: - if (!PyArg_ParseTuple(args,"sl;str,attr", &str, &lattr)) - return NULL; - attr = lattr; - use_attr = TRUE; - break; - case 3: - if (!PyArg_ParseTuple(args,"iis;y,x,str", &y, &x, &str)) - return NULL; - use_xy = TRUE; - break; - case 4: - if (!PyArg_ParseTuple(args,"iisl;y,x,str,attr", &y, &x, &str, &lattr)) - return NULL; - attr = lattr; - use_xy = use_attr = TRUE; - break; - default: - PyErr_SetString(PyExc_TypeError, "insstr requires 1 to 4 arguments"); - return NULL; - } - - if (use_attr == TRUE) { - attr_old = getattrs(self->win); - (void)wattrset(self->win,attr); - } - if (use_xy == TRUE) - rtn = mvwinsstr(self->win,y,x,str); - else - rtn = winsstr(self->win,str); - if (use_attr == TRUE) - (void)wattrset(self->win,attr_old); - return PyCursesCheckERR(rtn, "insstr"); + int rtn; + int x, y; + char *str; + attr_t attr = A_NORMAL , attr_old = A_NORMAL; + long lattr; + int use_xy = FALSE, use_attr = FALSE; + + switch (PyTuple_Size(args)) { + case 1: + if (!PyArg_ParseTuple(args,"s;str", &str)) + return NULL; + break; + case 2: + if (!PyArg_ParseTuple(args,"sl;str,attr", &str, &lattr)) + return NULL; + attr = lattr; + use_attr = TRUE; + break; + case 3: + if (!PyArg_ParseTuple(args,"iis;y,x,str", &y, &x, &str)) + return NULL; + use_xy = TRUE; + break; + case 4: + if (!PyArg_ParseTuple(args,"iisl;y,x,str,attr", &y, &x, &str, &lattr)) + return NULL; + attr = lattr; + use_xy = use_attr = TRUE; + break; + default: + PyErr_SetString(PyExc_TypeError, "insstr requires 1 to 4 arguments"); + return NULL; + } + + if (use_attr == TRUE) { + attr_old = getattrs(self->win); + (void)wattrset(self->win,attr); + } + if (use_xy == TRUE) + rtn = mvwinsstr(self->win,y,x,str); + else + rtn = winsstr(self->win,str); + if (use_attr == TRUE) + (void)wattrset(self->win,attr_old); + return PyCursesCheckERR(rtn, "insstr"); } static PyObject * PyCursesWindow_InsNStr(PyCursesWindowObject *self, PyObject *args) { - int rtn, x, y, n; - char *str; - attr_t attr = A_NORMAL , attr_old = A_NORMAL; - long lattr; - int use_xy = FALSE, use_attr = FALSE; - - switch (PyTuple_Size(args)) { - case 2: - if (!PyArg_ParseTuple(args,"si;str,n", &str, &n)) - return NULL; - break; - case 3: - if (!PyArg_ParseTuple(args,"sil;str,n,attr", &str, &n, &lattr)) - return NULL; - attr = lattr; - use_attr = TRUE; - break; - case 4: - if (!PyArg_ParseTuple(args,"iisi;y,x,str,n", &y, &x, &str, &n)) - return NULL; - use_xy = TRUE; - break; - case 5: - if (!PyArg_ParseTuple(args,"iisil;y,x,str,n,attr", &y, &x, &str, &n, &lattr)) - return NULL; - attr = lattr; - use_xy = use_attr = TRUE; - break; - default: - PyErr_SetString(PyExc_TypeError, "insnstr requires 2 to 5 arguments"); - return NULL; - } - - if (use_attr == TRUE) { - attr_old = getattrs(self->win); - (void)wattrset(self->win,attr); - } - if (use_xy == TRUE) - rtn = mvwinsnstr(self->win,y,x,str,n); - else - rtn = winsnstr(self->win,str,n); - if (use_attr == TRUE) - (void)wattrset(self->win,attr_old); - return PyCursesCheckERR(rtn, "insnstr"); + int rtn, x, y, n; + char *str; + attr_t attr = A_NORMAL , attr_old = A_NORMAL; + long lattr; + int use_xy = FALSE, use_attr = FALSE; + + switch (PyTuple_Size(args)) { + case 2: + if (!PyArg_ParseTuple(args,"si;str,n", &str, &n)) + return NULL; + break; + case 3: + if (!PyArg_ParseTuple(args,"sil;str,n,attr", &str, &n, &lattr)) + return NULL; + attr = lattr; + use_attr = TRUE; + break; + case 4: + if (!PyArg_ParseTuple(args,"iisi;y,x,str,n", &y, &x, &str, &n)) + return NULL; + use_xy = TRUE; + break; + case 5: + if (!PyArg_ParseTuple(args,"iisil;y,x,str,n,attr", &y, &x, &str, &n, &lattr)) + return NULL; + attr = lattr; + use_xy = use_attr = TRUE; + break; + default: + PyErr_SetString(PyExc_TypeError, "insnstr requires 2 to 5 arguments"); + return NULL; + } + + if (use_attr == TRUE) { + attr_old = getattrs(self->win); + (void)wattrset(self->win,attr); + } + if (use_xy == TRUE) + rtn = mvwinsnstr(self->win,y,x,str,n); + else + rtn = winsnstr(self->win,str,n); + if (use_attr == TRUE) + (void)wattrset(self->win,attr_old); + return PyCursesCheckERR(rtn, "insnstr"); } static PyObject * PyCursesWindow_Is_LineTouched(PyCursesWindowObject *self, PyObject *args) { - int line, erg; - if (!PyArg_ParseTuple(args,"i;line", &line)) - return NULL; - erg = is_linetouched(self->win, line); - if (erg == ERR) { - PyErr_SetString(PyExc_TypeError, - "is_linetouched: line number outside of boundaries"); - return NULL; - } else - if (erg == FALSE) { - Py_INCREF(Py_False); - return Py_False; - } else { - Py_INCREF(Py_True); - return Py_True; - } + int line, erg; + if (!PyArg_ParseTuple(args,"i;line", &line)) + return NULL; + erg = is_linetouched(self->win, line); + if (erg == ERR) { + PyErr_SetString(PyExc_TypeError, + "is_linetouched: line number outside of boundaries"); + return NULL; + } else + if (erg == FALSE) { + Py_INCREF(Py_False); + return Py_False; + } else { + Py_INCREF(Py_True); + return Py_True; + } } static PyObject * PyCursesWindow_NoOutRefresh(PyCursesWindowObject *self, PyObject *args) { - int pminrow,pmincol,sminrow,smincol,smaxrow,smaxcol; - int rtn; + int pminrow,pmincol,sminrow,smincol,smaxrow,smaxcol; + int rtn; #ifndef WINDOW_HAS_FLAGS - if (0) + if (0) #else - if (self->win->_flags & _ISPAD) + if (self->win->_flags & _ISPAD) #endif - { - switch(PyTuple_Size(args)) { - case 6: - if (!PyArg_ParseTuple(args, - "iiiiii;" \ - "pminrow,pmincol,sminrow,smincol,smaxrow,smaxcol", - &pminrow, &pmincol, &sminrow, - &smincol, &smaxrow, &smaxcol)) - return NULL; - Py_BEGIN_ALLOW_THREADS - rtn = pnoutrefresh(self->win, - pminrow, pmincol, sminrow, - smincol, smaxrow, smaxcol); - Py_END_ALLOW_THREADS - return PyCursesCheckERR(rtn, "pnoutrefresh"); - default: - PyErr_SetString(PyCursesError, - "noutrefresh() called for a pad " - "requires 6 arguments"); - return NULL; - } - } else { - if (!PyArg_ParseTuple(args, ":noutrefresh")) - return NULL; - - Py_BEGIN_ALLOW_THREADS - rtn = wnoutrefresh(self->win); - Py_END_ALLOW_THREADS - return PyCursesCheckERR(rtn, "wnoutrefresh"); - } + { + switch(PyTuple_Size(args)) { + case 6: + if (!PyArg_ParseTuple(args, + "iiiiii;" \ + "pminrow,pmincol,sminrow,smincol,smaxrow,smaxcol", + &pminrow, &pmincol, &sminrow, + &smincol, &smaxrow, &smaxcol)) + return NULL; + Py_BEGIN_ALLOW_THREADS + rtn = pnoutrefresh(self->win, + pminrow, pmincol, sminrow, + smincol, smaxrow, smaxcol); + Py_END_ALLOW_THREADS + return PyCursesCheckERR(rtn, "pnoutrefresh"); + default: + PyErr_SetString(PyCursesError, + "noutrefresh() called for a pad " + "requires 6 arguments"); + return NULL; + } + } else { + if (!PyArg_ParseTuple(args, ":noutrefresh")) + return NULL; + + Py_BEGIN_ALLOW_THREADS + rtn = wnoutrefresh(self->win); + Py_END_ALLOW_THREADS + return PyCursesCheckERR(rtn, "wnoutrefresh"); + } } static PyObject * @@ -1286,34 +1286,34 @@ int use_copywin = FALSE; int sminrow, smincol, dminrow, dmincol, dmaxrow, dmaxcol; int rtn; - + switch (PyTuple_Size(args)) { case 1: - if (!PyArg_ParseTuple(args, "O!;window object", - &PyCursesWindow_Type, &temp)) - return NULL; - break; + if (!PyArg_ParseTuple(args, "O!;window object", + &PyCursesWindow_Type, &temp)) + return NULL; + break; case 7: - if (!PyArg_ParseTuple(args, "O!iiiiii;window object, int, int, int, int, int, int", - &PyCursesWindow_Type, &temp, &sminrow, &smincol, - &dminrow, &dmincol, &dmaxrow, &dmaxcol)) - return NULL; - use_copywin = TRUE; - break; - default: - PyErr_SetString(PyExc_TypeError, - "overlay requires one or seven arguments"); - return NULL; + if (!PyArg_ParseTuple(args, "O!iiiiii;window object, int, int, int, int, int, int", + &PyCursesWindow_Type, &temp, &sminrow, &smincol, + &dminrow, &dmincol, &dmaxrow, &dmaxcol)) + return NULL; + use_copywin = TRUE; + break; + default: + PyErr_SetString(PyExc_TypeError, + "overlay requires one or seven arguments"); + return NULL; } if (use_copywin == TRUE) { - rtn = copywin(self->win, temp->win, sminrow, smincol, - dminrow, dmincol, dmaxrow, dmaxcol, TRUE); - return PyCursesCheckERR(rtn, "copywin"); + rtn = copywin(self->win, temp->win, sminrow, smincol, + dminrow, dmincol, dmaxrow, dmaxcol, TRUE); + return PyCursesCheckERR(rtn, "copywin"); } else { - rtn = overlay(self->win, temp->win); - return PyCursesCheckERR(rtn, "overlay"); + rtn = overlay(self->win, temp->win); + return PyCursesCheckERR(rtn, "overlay"); } } @@ -1324,377 +1324,377 @@ int use_copywin = FALSE; int sminrow, smincol, dminrow, dmincol, dmaxrow, dmaxcol; int rtn; - + switch (PyTuple_Size(args)) { case 1: - if (!PyArg_ParseTuple(args, "O!;window object", - &PyCursesWindow_Type, &temp)) - return NULL; - break; + if (!PyArg_ParseTuple(args, "O!;window object", + &PyCursesWindow_Type, &temp)) + return NULL; + break; case 7: - if (!PyArg_ParseTuple(args, "O!iiiiii;window object, int, int, int, int, int, int", - &PyCursesWindow_Type, &temp, &sminrow, &smincol, - &dminrow, &dmincol, &dmaxrow, &dmaxcol)) - return NULL; - use_copywin = TRUE; - break; - default: - PyErr_SetString(PyExc_TypeError, - "overwrite requires one or seven arguments"); - return NULL; + if (!PyArg_ParseTuple(args, "O!iiiiii;window object, int, int, int, int, int, int", + &PyCursesWindow_Type, &temp, &sminrow, &smincol, + &dminrow, &dmincol, &dmaxrow, &dmaxcol)) + return NULL; + use_copywin = TRUE; + break; + default: + PyErr_SetString(PyExc_TypeError, + "overwrite requires one or seven arguments"); + return NULL; } if (use_copywin == TRUE) { - rtn = copywin(self->win, temp->win, sminrow, smincol, - dminrow, dmincol, dmaxrow, dmaxcol, FALSE); + rtn = copywin(self->win, temp->win, sminrow, smincol, + dminrow, dmincol, dmaxrow, dmaxcol, FALSE); return PyCursesCheckERR(rtn, "copywin"); } else { - rtn = overwrite(self->win, temp->win); - return PyCursesCheckERR(rtn, "overwrite"); + rtn = overwrite(self->win, temp->win); + return PyCursesCheckERR(rtn, "overwrite"); } } static PyObject * PyCursesWindow_PutWin(PyCursesWindowObject *self, PyObject *stream) { - /* We have to simulate this by writing to a temporary FILE*, - then reading back, then writing to the argument stream. */ - char fn[100]; - int fd; - FILE *fp; - PyObject *res; - - strcpy(fn, "/tmp/py.curses.putwin.XXXXXX"); - fd = mkstemp(fn); - if (fd < 0) - return PyErr_SetFromErrnoWithFilename(PyExc_IOError, fn); - fp = fdopen(fd, "wb+"); - if (fp == NULL) { - close(fd); - remove(fn); - return PyErr_SetFromErrnoWithFilename(PyExc_IOError, fn); - } - res = PyCursesCheckERR(putwin(self->win, fp), "putwin"); - if (res == NULL) { + /* We have to simulate this by writing to a temporary FILE*, + then reading back, then writing to the argument stream. */ + char fn[100]; + int fd; + FILE *fp; + PyObject *res; + + strcpy(fn, "/tmp/py.curses.putwin.XXXXXX"); + fd = mkstemp(fn); + if (fd < 0) + return PyErr_SetFromErrnoWithFilename(PyExc_IOError, fn); + fp = fdopen(fd, "wb+"); + if (fp == NULL) { + close(fd); + remove(fn); + return PyErr_SetFromErrnoWithFilename(PyExc_IOError, fn); + } + res = PyCursesCheckERR(putwin(self->win, fp), "putwin"); + if (res == NULL) { + fclose(fp); + remove(fn); + return res; + } + fseek(fp, 0, 0); + while (1) { + char buf[BUFSIZ]; + Py_ssize_t n = fread(buf, 1, BUFSIZ, fp); + if (n <= 0) + break; + Py_DECREF(res); + res = PyObject_CallMethod(stream, "write", "y#", buf, n); + if (res == NULL) + break; + } fclose(fp); remove(fn); return res; - } - fseek(fp, 0, 0); - while (1) { - char buf[BUFSIZ]; - Py_ssize_t n = fread(buf, 1, BUFSIZ, fp); - if (n <= 0) - break; - Py_DECREF(res); - res = PyObject_CallMethod(stream, "write", "y#", buf, n); - if (res == NULL) - break; - } - fclose(fp); - remove(fn); - return res; } static PyObject * PyCursesWindow_RedrawLine(PyCursesWindowObject *self, PyObject *args) { - int beg, num; - if (!PyArg_ParseTuple(args, "ii;beg,num", &beg, &num)) - return NULL; - return PyCursesCheckERR(wredrawln(self->win,beg,num), "redrawln"); + int beg, num; + if (!PyArg_ParseTuple(args, "ii;beg,num", &beg, &num)) + return NULL; + return PyCursesCheckERR(wredrawln(self->win,beg,num), "redrawln"); } static PyObject * PyCursesWindow_Refresh(PyCursesWindowObject *self, PyObject *args) { - int pminrow,pmincol,sminrow,smincol,smaxrow,smaxcol; - int rtn; - + int pminrow,pmincol,sminrow,smincol,smaxrow,smaxcol; + int rtn; + #ifndef WINDOW_HAS_FLAGS - if (0) + if (0) #else - if (self->win->_flags & _ISPAD) + if (self->win->_flags & _ISPAD) #endif - { - switch(PyTuple_Size(args)) { - case 6: - if (!PyArg_ParseTuple(args, - "iiiiii;" \ - "pminrow,pmincol,sminrow,smincol,smaxrow,smaxcol", - &pminrow, &pmincol, &sminrow, - &smincol, &smaxrow, &smaxcol)) - return NULL; - - Py_BEGIN_ALLOW_THREADS - rtn = prefresh(self->win, - pminrow, pmincol, sminrow, - smincol, smaxrow, smaxcol); - Py_END_ALLOW_THREADS - return PyCursesCheckERR(rtn, "prefresh"); - default: - PyErr_SetString(PyCursesError, - "refresh() for a pad requires 6 arguments"); - return NULL; - } - } else { - if (!PyArg_ParseTuple(args, ":refresh")) - return NULL; - Py_BEGIN_ALLOW_THREADS - rtn = wrefresh(self->win); - Py_END_ALLOW_THREADS - return PyCursesCheckERR(rtn, "prefresh"); - } + { + switch(PyTuple_Size(args)) { + case 6: + if (!PyArg_ParseTuple(args, + "iiiiii;" \ + "pminrow,pmincol,sminrow,smincol,smaxrow,smaxcol", + &pminrow, &pmincol, &sminrow, + &smincol, &smaxrow, &smaxcol)) + return NULL; + + Py_BEGIN_ALLOW_THREADS + rtn = prefresh(self->win, + pminrow, pmincol, sminrow, + smincol, smaxrow, smaxcol); + Py_END_ALLOW_THREADS + return PyCursesCheckERR(rtn, "prefresh"); + default: + PyErr_SetString(PyCursesError, + "refresh() for a pad requires 6 arguments"); + return NULL; + } + } else { + if (!PyArg_ParseTuple(args, ":refresh")) + return NULL; + Py_BEGIN_ALLOW_THREADS + rtn = wrefresh(self->win); + Py_END_ALLOW_THREADS + return PyCursesCheckERR(rtn, "prefresh"); + } } static PyObject * PyCursesWindow_SetScrollRegion(PyCursesWindowObject *self, PyObject *args) { - int x, y; - if (!PyArg_ParseTuple(args,"ii;top, bottom",&y,&x)) - return NULL; - return PyCursesCheckERR(wsetscrreg(self->win,y,x), "wsetscrreg"); + int x, y; + if (!PyArg_ParseTuple(args,"ii;top, bottom",&y,&x)) + return NULL; + return PyCursesCheckERR(wsetscrreg(self->win,y,x), "wsetscrreg"); } static PyObject * PyCursesWindow_SubWin(PyCursesWindowObject *self, PyObject *args) { - WINDOW *win; - int nlines, ncols, begin_y, begin_x; + WINDOW *win; + int nlines, ncols, begin_y, begin_x; - nlines = 0; - ncols = 0; - switch (PyTuple_Size(args)) { - case 2: - if (!PyArg_ParseTuple(args,"ii;begin_y,begin_x",&begin_y,&begin_x)) - return NULL; - break; - case 4: - if (!PyArg_ParseTuple(args, "iiii;nlines,ncols,begin_y,begin_x", - &nlines,&ncols,&begin_y,&begin_x)) - return NULL; - break; - default: - PyErr_SetString(PyExc_TypeError, "subwin requires 2 or 4 arguments"); - return NULL; - } + nlines = 0; + ncols = 0; + switch (PyTuple_Size(args)) { + case 2: + if (!PyArg_ParseTuple(args,"ii;begin_y,begin_x",&begin_y,&begin_x)) + return NULL; + break; + case 4: + if (!PyArg_ParseTuple(args, "iiii;nlines,ncols,begin_y,begin_x", + &nlines,&ncols,&begin_y,&begin_x)) + return NULL; + break; + default: + PyErr_SetString(PyExc_TypeError, "subwin requires 2 or 4 arguments"); + return NULL; + } - /* printf("Subwin: %i %i %i %i \n", nlines, ncols, begin_y, begin_x); */ + /* printf("Subwin: %i %i %i %i \n", nlines, ncols, begin_y, begin_x); */ #ifdef WINDOW_HAS_FLAGS - if (self->win->_flags & _ISPAD) - win = subpad(self->win, nlines, ncols, begin_y, begin_x); - else -#endif - win = subwin(self->win, nlines, ncols, begin_y, begin_x); - - if (win == NULL) { - PyErr_SetString(PyCursesError, catchall_NULL); - return NULL; - } - - return (PyObject *)PyCursesWindow_New(win); + if (self->win->_flags & _ISPAD) + win = subpad(self->win, nlines, ncols, begin_y, begin_x); + else +#endif + win = subwin(self->win, nlines, ncols, begin_y, begin_x); + + if (win == NULL) { + PyErr_SetString(PyCursesError, catchall_NULL); + return NULL; + } + + return (PyObject *)PyCursesWindow_New(win); } static PyObject * PyCursesWindow_Scroll(PyCursesWindowObject *self, PyObject *args) { - int nlines; - switch(PyTuple_Size(args)) { - case 0: - return PyCursesCheckERR(scroll(self->win), "scroll"); - case 1: - if (!PyArg_ParseTuple(args, "i;nlines", &nlines)) - return NULL; - return PyCursesCheckERR(wscrl(self->win, nlines), "scroll"); - default: - PyErr_SetString(PyExc_TypeError, "scroll requires 0 or 1 arguments"); - return NULL; - } + int nlines; + switch(PyTuple_Size(args)) { + case 0: + return PyCursesCheckERR(scroll(self->win), "scroll"); + case 1: + if (!PyArg_ParseTuple(args, "i;nlines", &nlines)) + return NULL; + return PyCursesCheckERR(wscrl(self->win, nlines), "scroll"); + default: + PyErr_SetString(PyExc_TypeError, "scroll requires 0 or 1 arguments"); + return NULL; + } } static PyObject * PyCursesWindow_TouchLine(PyCursesWindowObject *self, PyObject *args) { - int st, cnt, val; - switch (PyTuple_Size(args)) { - case 2: - if (!PyArg_ParseTuple(args,"ii;start,count",&st,&cnt)) - return NULL; - return PyCursesCheckERR(touchline(self->win,st,cnt), "touchline"); - case 3: - if (!PyArg_ParseTuple(args, "iii;start,count,val", &st, &cnt, &val)) - return NULL; - return PyCursesCheckERR(wtouchln(self->win, st, cnt, val), "touchline"); - default: - PyErr_SetString(PyExc_TypeError, "touchline requires 2 or 3 arguments"); - return NULL; - } + int st, cnt, val; + switch (PyTuple_Size(args)) { + case 2: + if (!PyArg_ParseTuple(args,"ii;start,count",&st,&cnt)) + return NULL; + return PyCursesCheckERR(touchline(self->win,st,cnt), "touchline"); + case 3: + if (!PyArg_ParseTuple(args, "iii;start,count,val", &st, &cnt, &val)) + return NULL; + return PyCursesCheckERR(wtouchln(self->win, st, cnt, val), "touchline"); + default: + PyErr_SetString(PyExc_TypeError, "touchline requires 2 or 3 arguments"); + return NULL; + } } static PyObject * PyCursesWindow_Vline(PyCursesWindowObject *self, PyObject *args) { - PyObject *temp; - chtype ch; - int n, x, y, code = OK; - attr_t attr = A_NORMAL; - long lattr; - - switch (PyTuple_Size(args)) { - case 2: - if (!PyArg_ParseTuple(args, "Oi;ch or int,n", &temp, &n)) - return NULL; - break; - case 3: - if (!PyArg_ParseTuple(args, "Oil;ch or int,n,attr", &temp, &n, &lattr)) - return NULL; - attr = lattr; - break; - case 4: - if (!PyArg_ParseTuple(args, "iiOi;y,x,ch or int,n", &y, &x, &temp, &n)) - return NULL; - code = wmove(self->win, y, x); - break; - case 5: - if (!PyArg_ParseTuple(args, "iiOil; y,x,ch or int,n,attr", - &y, &x, &temp, &n, &lattr)) - return NULL; - attr = lattr; - code = wmove(self->win, y, x); - break; - default: - PyErr_SetString(PyExc_TypeError, "vline requires 2 to 5 arguments"); - return NULL; - } + PyObject *temp; + chtype ch; + int n, x, y, code = OK; + attr_t attr = A_NORMAL; + long lattr; - if (code != ERR) { - if (!PyCurses_ConvertToChtype(temp, &ch)) { - PyErr_SetString(PyExc_TypeError, - "argument 1 or 3 must be a ch or an int"); - return NULL; - } - return PyCursesCheckERR(wvline(self->win, ch | attr, n), "vline"); - } else - return PyCursesCheckERR(code, "wmove"); + switch (PyTuple_Size(args)) { + case 2: + if (!PyArg_ParseTuple(args, "Oi;ch or int,n", &temp, &n)) + return NULL; + break; + case 3: + if (!PyArg_ParseTuple(args, "Oil;ch or int,n,attr", &temp, &n, &lattr)) + return NULL; + attr = lattr; + break; + case 4: + if (!PyArg_ParseTuple(args, "iiOi;y,x,ch or int,n", &y, &x, &temp, &n)) + return NULL; + code = wmove(self->win, y, x); + break; + case 5: + if (!PyArg_ParseTuple(args, "iiOil; y,x,ch or int,n,attr", + &y, &x, &temp, &n, &lattr)) + return NULL; + attr = lattr; + code = wmove(self->win, y, x); + break; + default: + PyErr_SetString(PyExc_TypeError, "vline requires 2 to 5 arguments"); + return NULL; + } + + if (code != ERR) { + if (!PyCurses_ConvertToChtype(temp, &ch)) { + PyErr_SetString(PyExc_TypeError, + "argument 1 or 3 must be a ch or an int"); + return NULL; + } + return PyCursesCheckERR(wvline(self->win, ch | attr, n), "vline"); + } else + return PyCursesCheckERR(code, "wmove"); } static PyMethodDef PyCursesWindow_Methods[] = { - {"addch", (PyCFunction)PyCursesWindow_AddCh, METH_VARARGS}, - {"addnstr", (PyCFunction)PyCursesWindow_AddNStr, METH_VARARGS}, - {"addstr", (PyCFunction)PyCursesWindow_AddStr, METH_VARARGS}, - {"attroff", (PyCFunction)PyCursesWindow_AttrOff, METH_VARARGS}, - {"attron", (PyCFunction)PyCursesWindow_AttrOn, METH_VARARGS}, - {"attrset", (PyCFunction)PyCursesWindow_AttrSet, METH_VARARGS}, - {"bkgd", (PyCFunction)PyCursesWindow_Bkgd, METH_VARARGS}, - {"chgat", (PyCFunction)PyCursesWindow_ChgAt, METH_VARARGS}, - {"bkgdset", (PyCFunction)PyCursesWindow_BkgdSet, METH_VARARGS}, - {"border", (PyCFunction)PyCursesWindow_Border, METH_VARARGS}, - {"box", (PyCFunction)PyCursesWindow_Box, METH_VARARGS}, - {"clear", (PyCFunction)PyCursesWindow_wclear, METH_NOARGS}, - {"clearok", (PyCFunction)PyCursesWindow_clearok, METH_VARARGS}, - {"clrtobot", (PyCFunction)PyCursesWindow_wclrtobot, METH_NOARGS}, - {"clrtoeol", (PyCFunction)PyCursesWindow_wclrtoeol, METH_NOARGS}, - {"cursyncup", (PyCFunction)PyCursesWindow_wcursyncup, METH_NOARGS}, - {"delch", (PyCFunction)PyCursesWindow_DelCh, METH_VARARGS}, - {"deleteln", (PyCFunction)PyCursesWindow_wdeleteln, METH_NOARGS}, - {"derwin", (PyCFunction)PyCursesWindow_DerWin, METH_VARARGS}, - {"echochar", (PyCFunction)PyCursesWindow_EchoChar, METH_VARARGS}, + {"addch", (PyCFunction)PyCursesWindow_AddCh, METH_VARARGS}, + {"addnstr", (PyCFunction)PyCursesWindow_AddNStr, METH_VARARGS}, + {"addstr", (PyCFunction)PyCursesWindow_AddStr, METH_VARARGS}, + {"attroff", (PyCFunction)PyCursesWindow_AttrOff, METH_VARARGS}, + {"attron", (PyCFunction)PyCursesWindow_AttrOn, METH_VARARGS}, + {"attrset", (PyCFunction)PyCursesWindow_AttrSet, METH_VARARGS}, + {"bkgd", (PyCFunction)PyCursesWindow_Bkgd, METH_VARARGS}, + {"chgat", (PyCFunction)PyCursesWindow_ChgAt, METH_VARARGS}, + {"bkgdset", (PyCFunction)PyCursesWindow_BkgdSet, METH_VARARGS}, + {"border", (PyCFunction)PyCursesWindow_Border, METH_VARARGS}, + {"box", (PyCFunction)PyCursesWindow_Box, METH_VARARGS}, + {"clear", (PyCFunction)PyCursesWindow_wclear, METH_NOARGS}, + {"clearok", (PyCFunction)PyCursesWindow_clearok, METH_VARARGS}, + {"clrtobot", (PyCFunction)PyCursesWindow_wclrtobot, METH_NOARGS}, + {"clrtoeol", (PyCFunction)PyCursesWindow_wclrtoeol, METH_NOARGS}, + {"cursyncup", (PyCFunction)PyCursesWindow_wcursyncup, METH_NOARGS}, + {"delch", (PyCFunction)PyCursesWindow_DelCh, METH_VARARGS}, + {"deleteln", (PyCFunction)PyCursesWindow_wdeleteln, METH_NOARGS}, + {"derwin", (PyCFunction)PyCursesWindow_DerWin, METH_VARARGS}, + {"echochar", (PyCFunction)PyCursesWindow_EchoChar, METH_VARARGS}, #ifdef NCURSES_MOUSE_VERSION - {"enclose", (PyCFunction)PyCursesWindow_Enclose, METH_VARARGS}, + {"enclose", (PyCFunction)PyCursesWindow_Enclose, METH_VARARGS}, #endif - {"erase", (PyCFunction)PyCursesWindow_werase, METH_NOARGS}, - {"getbegyx", (PyCFunction)PyCursesWindow_getbegyx, METH_NOARGS}, - {"getbkgd", (PyCFunction)PyCursesWindow_GetBkgd, METH_NOARGS}, - {"getch", (PyCFunction)PyCursesWindow_GetCh, METH_VARARGS}, - {"getkey", (PyCFunction)PyCursesWindow_GetKey, METH_VARARGS}, - {"getmaxyx", (PyCFunction)PyCursesWindow_getmaxyx, METH_NOARGS}, - {"getparyx", (PyCFunction)PyCursesWindow_getparyx, METH_NOARGS}, - {"getstr", (PyCFunction)PyCursesWindow_GetStr, METH_VARARGS}, - {"getyx", (PyCFunction)PyCursesWindow_getyx, METH_NOARGS}, - {"hline", (PyCFunction)PyCursesWindow_Hline, METH_VARARGS}, - {"idcok", (PyCFunction)PyCursesWindow_idcok, METH_VARARGS}, - {"idlok", (PyCFunction)PyCursesWindow_idlok, METH_VARARGS}, - {"immedok", (PyCFunction)PyCursesWindow_immedok, METH_VARARGS}, - {"inch", (PyCFunction)PyCursesWindow_InCh, METH_VARARGS}, - {"insch", (PyCFunction)PyCursesWindow_InsCh, METH_VARARGS}, - {"insdelln", (PyCFunction)PyCursesWindow_winsdelln, METH_VARARGS}, - {"insertln", (PyCFunction)PyCursesWindow_winsertln, METH_NOARGS}, - {"insnstr", (PyCFunction)PyCursesWindow_InsNStr, METH_VARARGS}, - {"insstr", (PyCFunction)PyCursesWindow_InsStr, METH_VARARGS}, - {"instr", (PyCFunction)PyCursesWindow_InStr, METH_VARARGS}, - {"is_linetouched", (PyCFunction)PyCursesWindow_Is_LineTouched, METH_VARARGS}, - {"is_wintouched", (PyCFunction)PyCursesWindow_is_wintouched, METH_NOARGS}, - {"keypad", (PyCFunction)PyCursesWindow_keypad, METH_VARARGS}, - {"leaveok", (PyCFunction)PyCursesWindow_leaveok, METH_VARARGS}, - {"move", (PyCFunction)PyCursesWindow_wmove, METH_VARARGS}, - {"mvderwin", (PyCFunction)PyCursesWindow_mvderwin, METH_VARARGS}, - {"mvwin", (PyCFunction)PyCursesWindow_mvwin, METH_VARARGS}, - {"nodelay", (PyCFunction)PyCursesWindow_nodelay, METH_VARARGS}, - {"notimeout", (PyCFunction)PyCursesWindow_notimeout, METH_VARARGS}, - {"noutrefresh", (PyCFunction)PyCursesWindow_NoOutRefresh, METH_VARARGS}, - /* Backward compatibility alias -- remove in Python 2.3 */ - {"nooutrefresh", (PyCFunction)PyCursesWindow_NoOutRefresh, METH_VARARGS}, - {"overlay", (PyCFunction)PyCursesWindow_Overlay, METH_VARARGS}, - {"overwrite", (PyCFunction)PyCursesWindow_Overwrite, - METH_VARARGS}, - {"putwin", (PyCFunction)PyCursesWindow_PutWin, METH_O}, - {"redrawln", (PyCFunction)PyCursesWindow_RedrawLine, METH_VARARGS}, - {"redrawwin", (PyCFunction)PyCursesWindow_redrawwin, METH_NOARGS}, - {"refresh", (PyCFunction)PyCursesWindow_Refresh, METH_VARARGS}, + {"erase", (PyCFunction)PyCursesWindow_werase, METH_NOARGS}, + {"getbegyx", (PyCFunction)PyCursesWindow_getbegyx, METH_NOARGS}, + {"getbkgd", (PyCFunction)PyCursesWindow_GetBkgd, METH_NOARGS}, + {"getch", (PyCFunction)PyCursesWindow_GetCh, METH_VARARGS}, + {"getkey", (PyCFunction)PyCursesWindow_GetKey, METH_VARARGS}, + {"getmaxyx", (PyCFunction)PyCursesWindow_getmaxyx, METH_NOARGS}, + {"getparyx", (PyCFunction)PyCursesWindow_getparyx, METH_NOARGS}, + {"getstr", (PyCFunction)PyCursesWindow_GetStr, METH_VARARGS}, + {"getyx", (PyCFunction)PyCursesWindow_getyx, METH_NOARGS}, + {"hline", (PyCFunction)PyCursesWindow_Hline, METH_VARARGS}, + {"idcok", (PyCFunction)PyCursesWindow_idcok, METH_VARARGS}, + {"idlok", (PyCFunction)PyCursesWindow_idlok, METH_VARARGS}, + {"immedok", (PyCFunction)PyCursesWindow_immedok, METH_VARARGS}, + {"inch", (PyCFunction)PyCursesWindow_InCh, METH_VARARGS}, + {"insch", (PyCFunction)PyCursesWindow_InsCh, METH_VARARGS}, + {"insdelln", (PyCFunction)PyCursesWindow_winsdelln, METH_VARARGS}, + {"insertln", (PyCFunction)PyCursesWindow_winsertln, METH_NOARGS}, + {"insnstr", (PyCFunction)PyCursesWindow_InsNStr, METH_VARARGS}, + {"insstr", (PyCFunction)PyCursesWindow_InsStr, METH_VARARGS}, + {"instr", (PyCFunction)PyCursesWindow_InStr, METH_VARARGS}, + {"is_linetouched", (PyCFunction)PyCursesWindow_Is_LineTouched, METH_VARARGS}, + {"is_wintouched", (PyCFunction)PyCursesWindow_is_wintouched, METH_NOARGS}, + {"keypad", (PyCFunction)PyCursesWindow_keypad, METH_VARARGS}, + {"leaveok", (PyCFunction)PyCursesWindow_leaveok, METH_VARARGS}, + {"move", (PyCFunction)PyCursesWindow_wmove, METH_VARARGS}, + {"mvderwin", (PyCFunction)PyCursesWindow_mvderwin, METH_VARARGS}, + {"mvwin", (PyCFunction)PyCursesWindow_mvwin, METH_VARARGS}, + {"nodelay", (PyCFunction)PyCursesWindow_nodelay, METH_VARARGS}, + {"notimeout", (PyCFunction)PyCursesWindow_notimeout, METH_VARARGS}, + {"noutrefresh", (PyCFunction)PyCursesWindow_NoOutRefresh, METH_VARARGS}, + /* Backward compatibility alias -- remove in Python 2.3 */ + {"nooutrefresh", (PyCFunction)PyCursesWindow_NoOutRefresh, METH_VARARGS}, + {"overlay", (PyCFunction)PyCursesWindow_Overlay, METH_VARARGS}, + {"overwrite", (PyCFunction)PyCursesWindow_Overwrite, + METH_VARARGS}, + {"putwin", (PyCFunction)PyCursesWindow_PutWin, METH_O}, + {"redrawln", (PyCFunction)PyCursesWindow_RedrawLine, METH_VARARGS}, + {"redrawwin", (PyCFunction)PyCursesWindow_redrawwin, METH_NOARGS}, + {"refresh", (PyCFunction)PyCursesWindow_Refresh, METH_VARARGS}, #ifndef STRICT_SYSV_CURSES - {"resize", (PyCFunction)PyCursesWindow_wresize, METH_VARARGS}, + {"resize", (PyCFunction)PyCursesWindow_wresize, METH_VARARGS}, #endif - {"scroll", (PyCFunction)PyCursesWindow_Scroll, METH_VARARGS}, - {"scrollok", (PyCFunction)PyCursesWindow_scrollok, METH_VARARGS}, - {"setscrreg", (PyCFunction)PyCursesWindow_SetScrollRegion, METH_VARARGS}, - {"standend", (PyCFunction)PyCursesWindow_wstandend, METH_NOARGS}, - {"standout", (PyCFunction)PyCursesWindow_wstandout, METH_NOARGS}, - {"subpad", (PyCFunction)PyCursesWindow_SubWin, METH_VARARGS}, - {"subwin", (PyCFunction)PyCursesWindow_SubWin, METH_VARARGS}, - {"syncdown", (PyCFunction)PyCursesWindow_wsyncdown, METH_NOARGS}, - {"syncok", (PyCFunction)PyCursesWindow_syncok, METH_VARARGS}, - {"syncup", (PyCFunction)PyCursesWindow_wsyncup, METH_NOARGS}, - {"timeout", (PyCFunction)PyCursesWindow_wtimeout, METH_VARARGS}, - {"touchline", (PyCFunction)PyCursesWindow_TouchLine, METH_VARARGS}, - {"touchwin", (PyCFunction)PyCursesWindow_touchwin, METH_NOARGS}, - {"untouchwin", (PyCFunction)PyCursesWindow_untouchwin, METH_NOARGS}, - {"vline", (PyCFunction)PyCursesWindow_Vline, METH_VARARGS}, - {NULL, NULL} /* sentinel */ + {"scroll", (PyCFunction)PyCursesWindow_Scroll, METH_VARARGS}, + {"scrollok", (PyCFunction)PyCursesWindow_scrollok, METH_VARARGS}, + {"setscrreg", (PyCFunction)PyCursesWindow_SetScrollRegion, METH_VARARGS}, + {"standend", (PyCFunction)PyCursesWindow_wstandend, METH_NOARGS}, + {"standout", (PyCFunction)PyCursesWindow_wstandout, METH_NOARGS}, + {"subpad", (PyCFunction)PyCursesWindow_SubWin, METH_VARARGS}, + {"subwin", (PyCFunction)PyCursesWindow_SubWin, METH_VARARGS}, + {"syncdown", (PyCFunction)PyCursesWindow_wsyncdown, METH_NOARGS}, + {"syncok", (PyCFunction)PyCursesWindow_syncok, METH_VARARGS}, + {"syncup", (PyCFunction)PyCursesWindow_wsyncup, METH_NOARGS}, + {"timeout", (PyCFunction)PyCursesWindow_wtimeout, METH_VARARGS}, + {"touchline", (PyCFunction)PyCursesWindow_TouchLine, METH_VARARGS}, + {"touchwin", (PyCFunction)PyCursesWindow_touchwin, METH_NOARGS}, + {"untouchwin", (PyCFunction)PyCursesWindow_untouchwin, METH_NOARGS}, + {"vline", (PyCFunction)PyCursesWindow_Vline, METH_VARARGS}, + {NULL, NULL} /* sentinel */ }; /* -------------------------------------------------------*/ PyTypeObject PyCursesWindow_Type = { - PyVarObject_HEAD_INIT(NULL, 0) - "_curses.curses window", /*tp_name*/ - sizeof(PyCursesWindowObject), /*tp_basicsize*/ - 0, /*tp_itemsize*/ - /* methods */ - (destructor)PyCursesWindow_Dealloc, /*tp_dealloc*/ - 0, /*tp_print*/ - (getattrfunc)0, /*tp_getattr*/ - (setattrfunc)0, /*tp_setattr*/ - 0, /*tp_reserved*/ - 0, /*tp_repr*/ - 0, /*tp_as_number*/ - 0, /*tp_as_sequence*/ - 0, /*tp_as_mapping*/ - 0, /*tp_hash*/ - 0, /*tp_call*/ - 0, /*tp_str*/ - 0, /*tp_getattro*/ - 0, /*tp_setattro*/ - 0, /*tp_as_buffer*/ - Py_TPFLAGS_DEFAULT, /*tp_flags*/ - 0, /*tp_doc*/ - 0, /*tp_traverse*/ - 0, /*tp_clear*/ - 0, /*tp_richcompare*/ - 0, /*tp_weaklistoffset*/ - 0, /*tp_iter*/ - 0, /*tp_iternext*/ - PyCursesWindow_Methods, /*tp_methods*/ + PyVarObject_HEAD_INIT(NULL, 0) + "_curses.curses window", /*tp_name*/ + sizeof(PyCursesWindowObject), /*tp_basicsize*/ + 0, /*tp_itemsize*/ + /* methods */ + (destructor)PyCursesWindow_Dealloc, /*tp_dealloc*/ + 0, /*tp_print*/ + (getattrfunc)0, /*tp_getattr*/ + (setattrfunc)0, /*tp_setattr*/ + 0, /*tp_reserved*/ + 0, /*tp_repr*/ + 0, /*tp_as_number*/ + 0, /*tp_as_sequence*/ + 0, /*tp_as_mapping*/ + 0, /*tp_hash*/ + 0, /*tp_call*/ + 0, /*tp_str*/ + 0, /*tp_getattro*/ + 0, /*tp_setattro*/ + 0, /*tp_as_buffer*/ + Py_TPFLAGS_DEFAULT, /*tp_flags*/ + 0, /*tp_doc*/ + 0, /*tp_traverse*/ + 0, /*tp_clear*/ + 0, /*tp_richcompare*/ + 0, /*tp_weaklistoffset*/ + 0, /*tp_iter*/ + 0, /*tp_iternext*/ + PyCursesWindow_Methods, /*tp_methods*/ }; /********************************************************************* @@ -1738,452 +1738,452 @@ static PyObject * PyCurses_filter(PyObject *self) { - /* not checking for PyCursesInitialised here since filter() must - be called before initscr() */ - filter(); - Py_INCREF(Py_None); - return Py_None; + /* not checking for PyCursesInitialised here since filter() must + be called before initscr() */ + filter(); + Py_INCREF(Py_None); + return Py_None; } static PyObject * PyCurses_Color_Content(PyObject *self, PyObject *args) { - short color,r,g,b; + short color,r,g,b; - PyCursesInitialised; - PyCursesInitialisedColor; + PyCursesInitialised; + PyCursesInitialisedColor; - if (!PyArg_ParseTuple(args, "h:color_content", &color)) return NULL; + if (!PyArg_ParseTuple(args, "h:color_content", &color)) return NULL; - if (color_content(color, &r, &g, &b) != ERR) - return Py_BuildValue("(iii)", r, g, b); - else { - PyErr_SetString(PyCursesError, - "Argument 1 was out of range. Check value of COLORS."); - return NULL; - } + if (color_content(color, &r, &g, &b) != ERR) + return Py_BuildValue("(iii)", r, g, b); + else { + PyErr_SetString(PyCursesError, + "Argument 1 was out of range. Check value of COLORS."); + return NULL; + } } static PyObject * PyCurses_color_pair(PyObject *self, PyObject *args) { - int n; + int n; - PyCursesInitialised; - PyCursesInitialisedColor; + PyCursesInitialised; + PyCursesInitialisedColor; - if (!PyArg_ParseTuple(args, "i:color_pair", &n)) return NULL; - return PyLong_FromLong((long) (n << 8)); + if (!PyArg_ParseTuple(args, "i:color_pair", &n)) return NULL; + return PyLong_FromLong((long) (n << 8)); } static PyObject * PyCurses_Curs_Set(PyObject *self, PyObject *args) { - int vis,erg; + int vis,erg; - PyCursesInitialised; + PyCursesInitialised; - if (!PyArg_ParseTuple(args, "i:curs_set", &vis)) return NULL; + if (!PyArg_ParseTuple(args, "i:curs_set", &vis)) return NULL; - erg = curs_set(vis); - if (erg == ERR) return PyCursesCheckERR(erg, "curs_set"); + erg = curs_set(vis); + if (erg == ERR) return PyCursesCheckERR(erg, "curs_set"); - return PyLong_FromLong((long) erg); + return PyLong_FromLong((long) erg); } static PyObject * PyCurses_Delay_Output(PyObject *self, PyObject *args) { - int ms; + int ms; - PyCursesInitialised; + PyCursesInitialised; - if (!PyArg_ParseTuple(args, "i:delay_output", &ms)) return NULL; + if (!PyArg_ParseTuple(args, "i:delay_output", &ms)) return NULL; - return PyCursesCheckERR(delay_output(ms), "delay_output"); + return PyCursesCheckERR(delay_output(ms), "delay_output"); } static PyObject * PyCurses_EraseChar(PyObject *self) { - char ch; + char ch; - PyCursesInitialised; + PyCursesInitialised; - ch = erasechar(); + ch = erasechar(); - return PyBytes_FromStringAndSize(&ch, 1); + return PyBytes_FromStringAndSize(&ch, 1); } static PyObject * PyCurses_getsyx(PyObject *self) { - int x = 0; - int y = 0; + int x = 0; + int y = 0; - PyCursesInitialised; + PyCursesInitialised; - getsyx(y, x); + getsyx(y, x); - return Py_BuildValue("(ii)", y, x); + return Py_BuildValue("(ii)", y, x); } #ifdef NCURSES_MOUSE_VERSION static PyObject * PyCurses_GetMouse(PyObject *self) { - int rtn; - MEVENT event; + int rtn; + MEVENT event; - PyCursesInitialised; + PyCursesInitialised; - rtn = getmouse( &event ); - if (rtn == ERR) { - PyErr_SetString(PyCursesError, "getmouse() returned ERR"); - return NULL; - } - return Py_BuildValue("(hiiil)", - (short)event.id, - event.x, event.y, event.z, - (long) event.bstate); + rtn = getmouse( &event ); + if (rtn == ERR) { + PyErr_SetString(PyCursesError, "getmouse() returned ERR"); + return NULL; + } + return Py_BuildValue("(hiiil)", + (short)event.id, + event.x, event.y, event.z, + (long) event.bstate); } static PyObject * PyCurses_UngetMouse(PyObject *self, PyObject *args) { - MEVENT event; + MEVENT event; - PyCursesInitialised; - if (!PyArg_ParseTuple(args, "hiiil", - &event.id, - &event.x, &event.y, &event.z, - (int *) &event.bstate)) - return NULL; + PyCursesInitialised; + if (!PyArg_ParseTuple(args, "hiiil", + &event.id, + &event.x, &event.y, &event.z, + (int *) &event.bstate)) + return NULL; - return PyCursesCheckERR(ungetmouse(&event), "ungetmouse"); + return PyCursesCheckERR(ungetmouse(&event), "ungetmouse"); } #endif static PyObject * PyCurses_GetWin(PyCursesWindowObject *self, PyObject *stream) { - char fn[100]; - int fd; - FILE *fp; - PyObject *data; - size_t datalen; - WINDOW *win; - - PyCursesInitialised; - - strcpy(fn, "/tmp/py.curses.getwin.XXXXXX"); - fd = mkstemp(fn); - if (fd < 0) - return PyErr_SetFromErrnoWithFilename(PyExc_IOError, fn); - fp = fdopen(fd, "wb+"); - if (fp == NULL) { - close(fd); - remove(fn); - return PyErr_SetFromErrnoWithFilename(PyExc_IOError, fn); - } - data = PyObject_CallMethod(stream, "read", ""); - if (data == NULL) { - fclose(fp); - remove(fn); - return NULL; - } - if (!PyBytes_Check(data)) { - PyErr_Format(PyExc_TypeError, - "f.read() returned %.100s instead of bytes", - data->ob_type->tp_name); - Py_DECREF(data); - fclose(fp); - remove(fn); - return NULL; - } - datalen = PyBytes_GET_SIZE(data); - if (fwrite(PyBytes_AS_STRING(data), 1, datalen, fp) != datalen) { + char fn[100]; + int fd; + FILE *fp; + PyObject *data; + size_t datalen; + WINDOW *win; + + PyCursesInitialised; + + strcpy(fn, "/tmp/py.curses.getwin.XXXXXX"); + fd = mkstemp(fn); + if (fd < 0) + return PyErr_SetFromErrnoWithFilename(PyExc_IOError, fn); + fp = fdopen(fd, "wb+"); + if (fp == NULL) { + close(fd); + remove(fn); + return PyErr_SetFromErrnoWithFilename(PyExc_IOError, fn); + } + data = PyObject_CallMethod(stream, "read", ""); + if (data == NULL) { + fclose(fp); + remove(fn); + return NULL; + } + if (!PyBytes_Check(data)) { + PyErr_Format(PyExc_TypeError, + "f.read() returned %.100s instead of bytes", + data->ob_type->tp_name); + Py_DECREF(data); + fclose(fp); + remove(fn); + return NULL; + } + datalen = PyBytes_GET_SIZE(data); + if (fwrite(PyBytes_AS_STRING(data), 1, datalen, fp) != datalen) { + Py_DECREF(data); + fclose(fp); + remove(fn); + return PyErr_SetFromErrnoWithFilename(PyExc_IOError, fn); + } Py_DECREF(data); + fseek(fp, 0, 0); + win = getwin(fp); fclose(fp); remove(fn); - return PyErr_SetFromErrnoWithFilename(PyExc_IOError, fn); - } - Py_DECREF(data); - fseek(fp, 0, 0); - win = getwin(fp); - fclose(fp); - remove(fn); - if (win == NULL) { - PyErr_SetString(PyCursesError, catchall_NULL); - return NULL; - } - return PyCursesWindow_New(win); + if (win == NULL) { + PyErr_SetString(PyCursesError, catchall_NULL); + return NULL; + } + return PyCursesWindow_New(win); } static PyObject * PyCurses_HalfDelay(PyObject *self, PyObject *args) { - unsigned char tenths; + unsigned char tenths; - PyCursesInitialised; + PyCursesInitialised; - if (!PyArg_ParseTuple(args, "b:halfdelay", &tenths)) return NULL; + if (!PyArg_ParseTuple(args, "b:halfdelay", &tenths)) return NULL; - return PyCursesCheckERR(halfdelay(tenths), "halfdelay"); + return PyCursesCheckERR(halfdelay(tenths), "halfdelay"); } #ifndef STRICT_SYSV_CURSES - /* No has_key! */ +/* No has_key! */ static PyObject * PyCurses_has_key(PyObject *self, PyObject *args) { - int ch; + int ch; - PyCursesInitialised; + PyCursesInitialised; - if (!PyArg_ParseTuple(args,"i",&ch)) return NULL; + if (!PyArg_ParseTuple(args,"i",&ch)) return NULL; - if (has_key(ch) == FALSE) { - Py_INCREF(Py_False); - return Py_False; - } - Py_INCREF(Py_True); - return Py_True; + if (has_key(ch) == FALSE) { + Py_INCREF(Py_False); + return Py_False; + } + Py_INCREF(Py_True); + return Py_True; } #endif /* STRICT_SYSV_CURSES */ static PyObject * PyCurses_Init_Color(PyObject *self, PyObject *args) { - short color, r, g, b; + short color, r, g, b; - PyCursesInitialised; - PyCursesInitialisedColor; + PyCursesInitialised; + PyCursesInitialisedColor; - switch(PyTuple_Size(args)) { - case 4: - if (!PyArg_ParseTuple(args, "hhhh;color,r,g,b", &color, &r, &g, &b)) return NULL; - break; - default: - PyErr_SetString(PyExc_TypeError, "init_color requires 4 arguments"); - return NULL; - } + switch(PyTuple_Size(args)) { + case 4: + if (!PyArg_ParseTuple(args, "hhhh;color,r,g,b", &color, &r, &g, &b)) return NULL; + break; + default: + PyErr_SetString(PyExc_TypeError, "init_color requires 4 arguments"); + return NULL; + } - return PyCursesCheckERR(init_color(color, r, g, b), "init_color"); + return PyCursesCheckERR(init_color(color, r, g, b), "init_color"); } static PyObject * PyCurses_Init_Pair(PyObject *self, PyObject *args) { - short pair, f, b; + short pair, f, b; - PyCursesInitialised; - PyCursesInitialisedColor; + PyCursesInitialised; + PyCursesInitialisedColor; - if (PyTuple_Size(args) != 3) { - PyErr_SetString(PyExc_TypeError, "init_pair requires 3 arguments"); - return NULL; - } + if (PyTuple_Size(args) != 3) { + PyErr_SetString(PyExc_TypeError, "init_pair requires 3 arguments"); + return NULL; + } - if (!PyArg_ParseTuple(args, "hhh;pair, f, b", &pair, &f, &b)) return NULL; + if (!PyArg_ParseTuple(args, "hhh;pair, f, b", &pair, &f, &b)) return NULL; - return PyCursesCheckERR(init_pair(pair, f, b), "init_pair"); + return PyCursesCheckERR(init_pair(pair, f, b), "init_pair"); } static PyObject *ModDict; -static PyObject * +static PyObject * PyCurses_InitScr(PyObject *self) { - WINDOW *win; + WINDOW *win; - if (initialised == TRUE) { - wrefresh(stdscr); - return (PyObject *)PyCursesWindow_New(stdscr); - } + if (initialised == TRUE) { + wrefresh(stdscr); + return (PyObject *)PyCursesWindow_New(stdscr); + } - win = initscr(); + win = initscr(); - if (win == NULL) { - PyErr_SetString(PyCursesError, catchall_NULL); - return NULL; - } + if (win == NULL) { + PyErr_SetString(PyCursesError, catchall_NULL); + return NULL; + } - initialised = initialised_setupterm = TRUE; + initialised = initialised_setupterm = TRUE; /* This was moved from initcurses() because it core dumped on SGI, where they're not defined until you've called initscr() */ -#define SetDictInt(string,ch) \ - do { \ - PyObject *o = PyLong_FromLong((long) (ch)); \ - if (o && PyDict_SetItemString(ModDict, string, o) == 0) { \ - Py_DECREF(o); \ - } \ +#define SetDictInt(string,ch) \ + do { \ + PyObject *o = PyLong_FromLong((long) (ch)); \ + if (o && PyDict_SetItemString(ModDict, string, o) == 0) { \ + Py_DECREF(o); \ + } \ } while (0) - /* Here are some graphic symbols you can use */ - SetDictInt("ACS_ULCORNER", (ACS_ULCORNER)); - SetDictInt("ACS_LLCORNER", (ACS_LLCORNER)); - SetDictInt("ACS_URCORNER", (ACS_URCORNER)); - SetDictInt("ACS_LRCORNER", (ACS_LRCORNER)); - SetDictInt("ACS_LTEE", (ACS_LTEE)); - SetDictInt("ACS_RTEE", (ACS_RTEE)); - SetDictInt("ACS_BTEE", (ACS_BTEE)); - SetDictInt("ACS_TTEE", (ACS_TTEE)); - SetDictInt("ACS_HLINE", (ACS_HLINE)); - SetDictInt("ACS_VLINE", (ACS_VLINE)); - SetDictInt("ACS_PLUS", (ACS_PLUS)); + /* Here are some graphic symbols you can use */ + SetDictInt("ACS_ULCORNER", (ACS_ULCORNER)); + SetDictInt("ACS_LLCORNER", (ACS_LLCORNER)); + SetDictInt("ACS_URCORNER", (ACS_URCORNER)); + SetDictInt("ACS_LRCORNER", (ACS_LRCORNER)); + SetDictInt("ACS_LTEE", (ACS_LTEE)); + SetDictInt("ACS_RTEE", (ACS_RTEE)); + SetDictInt("ACS_BTEE", (ACS_BTEE)); + SetDictInt("ACS_TTEE", (ACS_TTEE)); + SetDictInt("ACS_HLINE", (ACS_HLINE)); + SetDictInt("ACS_VLINE", (ACS_VLINE)); + SetDictInt("ACS_PLUS", (ACS_PLUS)); #if !defined(__hpux) || defined(HAVE_NCURSES_H) - /* On HP/UX 11, these are of type cchar_t, which is not an - integral type. If this is a problem on more platforms, a - configure test should be added to determine whether ACS_S1 - is of integral type. */ - SetDictInt("ACS_S1", (ACS_S1)); - SetDictInt("ACS_S9", (ACS_S9)); - SetDictInt("ACS_DIAMOND", (ACS_DIAMOND)); - SetDictInt("ACS_CKBOARD", (ACS_CKBOARD)); - SetDictInt("ACS_DEGREE", (ACS_DEGREE)); - SetDictInt("ACS_PLMINUS", (ACS_PLMINUS)); - SetDictInt("ACS_BULLET", (ACS_BULLET)); - SetDictInt("ACS_LARROW", (ACS_LARROW)); - SetDictInt("ACS_RARROW", (ACS_RARROW)); - SetDictInt("ACS_DARROW", (ACS_DARROW)); - SetDictInt("ACS_UARROW", (ACS_UARROW)); - SetDictInt("ACS_BOARD", (ACS_BOARD)); - SetDictInt("ACS_LANTERN", (ACS_LANTERN)); - SetDictInt("ACS_BLOCK", (ACS_BLOCK)); -#endif - SetDictInt("ACS_BSSB", (ACS_ULCORNER)); - SetDictInt("ACS_SSBB", (ACS_LLCORNER)); - SetDictInt("ACS_BBSS", (ACS_URCORNER)); - SetDictInt("ACS_SBBS", (ACS_LRCORNER)); - SetDictInt("ACS_SBSS", (ACS_RTEE)); - SetDictInt("ACS_SSSB", (ACS_LTEE)); - SetDictInt("ACS_SSBS", (ACS_BTEE)); - SetDictInt("ACS_BSSS", (ACS_TTEE)); - SetDictInt("ACS_BSBS", (ACS_HLINE)); - SetDictInt("ACS_SBSB", (ACS_VLINE)); - SetDictInt("ACS_SSSS", (ACS_PLUS)); + /* On HP/UX 11, these are of type cchar_t, which is not an + integral type. If this is a problem on more platforms, a + configure test should be added to determine whether ACS_S1 + is of integral type. */ + SetDictInt("ACS_S1", (ACS_S1)); + SetDictInt("ACS_S9", (ACS_S9)); + SetDictInt("ACS_DIAMOND", (ACS_DIAMOND)); + SetDictInt("ACS_CKBOARD", (ACS_CKBOARD)); + SetDictInt("ACS_DEGREE", (ACS_DEGREE)); + SetDictInt("ACS_PLMINUS", (ACS_PLMINUS)); + SetDictInt("ACS_BULLET", (ACS_BULLET)); + SetDictInt("ACS_LARROW", (ACS_LARROW)); + SetDictInt("ACS_RARROW", (ACS_RARROW)); + SetDictInt("ACS_DARROW", (ACS_DARROW)); + SetDictInt("ACS_UARROW", (ACS_UARROW)); + SetDictInt("ACS_BOARD", (ACS_BOARD)); + SetDictInt("ACS_LANTERN", (ACS_LANTERN)); + SetDictInt("ACS_BLOCK", (ACS_BLOCK)); +#endif + SetDictInt("ACS_BSSB", (ACS_ULCORNER)); + SetDictInt("ACS_SSBB", (ACS_LLCORNER)); + SetDictInt("ACS_BBSS", (ACS_URCORNER)); + SetDictInt("ACS_SBBS", (ACS_LRCORNER)); + SetDictInt("ACS_SBSS", (ACS_RTEE)); + SetDictInt("ACS_SSSB", (ACS_LTEE)); + SetDictInt("ACS_SSBS", (ACS_BTEE)); + SetDictInt("ACS_BSSS", (ACS_TTEE)); + SetDictInt("ACS_BSBS", (ACS_HLINE)); + SetDictInt("ACS_SBSB", (ACS_VLINE)); + SetDictInt("ACS_SSSS", (ACS_PLUS)); - /* The following are never available with strict SYSV curses */ + /* The following are never available with strict SYSV curses */ #ifdef ACS_S3 - SetDictInt("ACS_S3", (ACS_S3)); + SetDictInt("ACS_S3", (ACS_S3)); #endif #ifdef ACS_S7 - SetDictInt("ACS_S7", (ACS_S7)); + SetDictInt("ACS_S7", (ACS_S7)); #endif #ifdef ACS_LEQUAL - SetDictInt("ACS_LEQUAL", (ACS_LEQUAL)); + SetDictInt("ACS_LEQUAL", (ACS_LEQUAL)); #endif #ifdef ACS_GEQUAL - SetDictInt("ACS_GEQUAL", (ACS_GEQUAL)); + SetDictInt("ACS_GEQUAL", (ACS_GEQUAL)); #endif #ifdef ACS_PI - SetDictInt("ACS_PI", (ACS_PI)); + SetDictInt("ACS_PI", (ACS_PI)); #endif #ifdef ACS_NEQUAL - SetDictInt("ACS_NEQUAL", (ACS_NEQUAL)); + SetDictInt("ACS_NEQUAL", (ACS_NEQUAL)); #endif #ifdef ACS_STERLING - SetDictInt("ACS_STERLING", (ACS_STERLING)); + SetDictInt("ACS_STERLING", (ACS_STERLING)); #endif - SetDictInt("LINES", LINES); - SetDictInt("COLS", COLS); + SetDictInt("LINES", LINES); + SetDictInt("COLS", COLS); - return (PyObject *)PyCursesWindow_New(win); + return (PyObject *)PyCursesWindow_New(win); } static PyObject * PyCurses_setupterm(PyObject* self, PyObject *args, PyObject* keywds) { - int fd = -1; - int err; - char* termstr = NULL; - - static char *kwlist[] = {"term", "fd", NULL}; - - if (!PyArg_ParseTupleAndKeywords( - args, keywds, "|zi:setupterm", kwlist, &termstr, &fd)) { - return NULL; - } - - if (fd == -1) { - PyObject* sys_stdout; - - sys_stdout = PySys_GetObject("stdout"); - - if (sys_stdout == NULL || sys_stdout == Py_None) { - PyErr_SetString( - PyCursesError, - "lost sys.stdout"); - return NULL; - } - - fd = PyObject_AsFileDescriptor(sys_stdout); - - if (fd == -1) { - return NULL; - } - } - - if (setupterm(termstr,fd,&err) == ERR) { - char* s = "setupterm: unknown error"; - - if (err == 0) { - s = "setupterm: could not find terminal"; - } else if (err == -1) { - s = "setupterm: could not find terminfo database"; - } - - PyErr_SetString(PyCursesError,s); - return NULL; - } + int fd = -1; + int err; + char* termstr = NULL; - initialised_setupterm = TRUE; + static char *kwlist[] = {"term", "fd", NULL}; - Py_INCREF(Py_None); - return Py_None; + if (!PyArg_ParseTupleAndKeywords( + args, keywds, "|zi:setupterm", kwlist, &termstr, &fd)) { + return NULL; + } + + if (fd == -1) { + PyObject* sys_stdout; + + sys_stdout = PySys_GetObject("stdout"); + + if (sys_stdout == NULL || sys_stdout == Py_None) { + PyErr_SetString( + PyCursesError, + "lost sys.stdout"); + return NULL; + } + + fd = PyObject_AsFileDescriptor(sys_stdout); + + if (fd == -1) { + return NULL; + } + } + + if (setupterm(termstr,fd,&err) == ERR) { + char* s = "setupterm: unknown error"; + + if (err == 0) { + s = "setupterm: could not find terminal"; + } else if (err == -1) { + s = "setupterm: could not find terminfo database"; + } + + PyErr_SetString(PyCursesError,s); + return NULL; + } + + initialised_setupterm = TRUE; + + Py_INCREF(Py_None); + return Py_None; } static PyObject * PyCurses_IntrFlush(PyObject *self, PyObject *args) { - int ch; + int ch; - PyCursesInitialised; + PyCursesInitialised; - switch(PyTuple_Size(args)) { - case 1: - if (!PyArg_ParseTuple(args,"i;True(1), False(0)",&ch)) return NULL; - break; - default: - PyErr_SetString(PyExc_TypeError, "intrflush requires 1 argument"); - return NULL; - } + switch(PyTuple_Size(args)) { + case 1: + if (!PyArg_ParseTuple(args,"i;True(1), False(0)",&ch)) return NULL; + break; + default: + PyErr_SetString(PyExc_TypeError, "intrflush requires 1 argument"); + return NULL; + } - return PyCursesCheckERR(intrflush(NULL,ch), "intrflush"); + return PyCursesCheckERR(intrflush(NULL,ch), "intrflush"); } #ifdef HAVE_CURSES_IS_TERM_RESIZED static PyObject * PyCurses_Is_Term_Resized(PyObject *self, PyObject *args) { - int lines; - int columns; - int result; - - PyCursesInitialised; - - if (!PyArg_ParseTuple(args,"ii:is_term_resized", &lines, &columns)) - return NULL; - result = is_term_resized(lines, columns); - if (result == TRUE) { - Py_INCREF(Py_True); - return Py_True; - } else { - Py_INCREF(Py_False); - return Py_False; - } + int lines; + int columns; + int result; + + PyCursesInitialised; + + if (!PyArg_ParseTuple(args,"ii:is_term_resized", &lines, &columns)) + return NULL; + result = is_term_resized(lines, columns); + if (result == TRUE) { + Py_INCREF(Py_True); + return Py_True; + } else { + Py_INCREF(Py_False); + return Py_False; + } } #endif /* HAVE_CURSES_IS_TERM_RESIZED */ @@ -2191,75 +2191,75 @@ static PyObject * PyCurses_KeyName(PyObject *self, PyObject *args) { - const char *knp; - int ch; + const char *knp; + int ch; - PyCursesInitialised; + PyCursesInitialised; - if (!PyArg_ParseTuple(args,"i",&ch)) return NULL; + if (!PyArg_ParseTuple(args,"i",&ch)) return NULL; - if (ch < 0) { - PyErr_SetString(PyExc_ValueError, "invalid key number"); - return NULL; - } - knp = keyname(ch); + if (ch < 0) { + PyErr_SetString(PyExc_ValueError, "invalid key number"); + return NULL; + } + knp = keyname(ch); - return PyBytes_FromString((knp == NULL) ? "" : (char *)knp); + return PyBytes_FromString((knp == NULL) ? "" : (char *)knp); } #endif -static PyObject * -PyCurses_KillChar(PyObject *self) -{ - char ch; +static PyObject * +PyCurses_KillChar(PyObject *self) +{ + char ch; - ch = killchar(); + ch = killchar(); - return PyBytes_FromStringAndSize(&ch, 1); -} + return PyBytes_FromStringAndSize(&ch, 1); +} static PyObject * PyCurses_Meta(PyObject *self, PyObject *args) { - int ch; + int ch; - PyCursesInitialised; + PyCursesInitialised; - switch(PyTuple_Size(args)) { - case 1: - if (!PyArg_ParseTuple(args,"i;True(1), False(0)",&ch)) return NULL; - break; - default: - PyErr_SetString(PyExc_TypeError, "meta requires 1 argument"); - return NULL; - } + switch(PyTuple_Size(args)) { + case 1: + if (!PyArg_ParseTuple(args,"i;True(1), False(0)",&ch)) return NULL; + break; + default: + PyErr_SetString(PyExc_TypeError, "meta requires 1 argument"); + return NULL; + } - return PyCursesCheckERR(meta(stdscr, ch), "meta"); + return PyCursesCheckERR(meta(stdscr, ch), "meta"); } #ifdef NCURSES_MOUSE_VERSION static PyObject * PyCurses_MouseInterval(PyObject *self, PyObject *args) { - int interval; - PyCursesInitialised; + int interval; + PyCursesInitialised; - if (!PyArg_ParseTuple(args,"i;interval",&interval)) - return NULL; - return PyCursesCheckERR(mouseinterval(interval), "mouseinterval"); + if (!PyArg_ParseTuple(args,"i;interval",&interval)) + return NULL; + return PyCursesCheckERR(mouseinterval(interval), "mouseinterval"); } static PyObject * PyCurses_MouseMask(PyObject *self, PyObject *args) { - int newmask; - mmask_t oldmask, availmask; + int newmask; + mmask_t oldmask, availmask; - PyCursesInitialised; - if (!PyArg_ParseTuple(args,"i;mousemask",&newmask)) - return NULL; - availmask = mousemask(newmask, &oldmask); - return Py_BuildValue("(ll)", (long)availmask, (long)oldmask); + PyCursesInitialised; + if (!PyArg_ParseTuple(args,"i;mousemask",&newmask)) + return NULL; + availmask = mousemask(newmask, &oldmask); + return Py_BuildValue("(ll)", (long)availmask, (long)oldmask); } #endif @@ -2278,133 +2278,133 @@ static PyObject * PyCurses_NewPad(PyObject *self, PyObject *args) { - WINDOW *win; - int nlines, ncols; + WINDOW *win; + int nlines, ncols; + + PyCursesInitialised; - PyCursesInitialised; + if (!PyArg_ParseTuple(args,"ii;nlines,ncols",&nlines,&ncols)) return NULL; - if (!PyArg_ParseTuple(args,"ii;nlines,ncols",&nlines,&ncols)) return NULL; + win = newpad(nlines, ncols); - win = newpad(nlines, ncols); - - if (win == NULL) { - PyErr_SetString(PyCursesError, catchall_NULL); - return NULL; - } + if (win == NULL) { + PyErr_SetString(PyCursesError, catchall_NULL); + return NULL; + } - return (PyObject *)PyCursesWindow_New(win); + return (PyObject *)PyCursesWindow_New(win); } static PyObject * PyCurses_NewWindow(PyObject *self, PyObject *args) { - WINDOW *win; - int nlines, ncols, begin_y=0, begin_x=0; + WINDOW *win; + int nlines, ncols, begin_y=0, begin_x=0; - PyCursesInitialised; + PyCursesInitialised; - switch (PyTuple_Size(args)) { - case 2: - if (!PyArg_ParseTuple(args,"ii;nlines,ncols",&nlines,&ncols)) - return NULL; - break; - case 4: - if (!PyArg_ParseTuple(args, "iiii;nlines,ncols,begin_y,begin_x", - &nlines,&ncols,&begin_y,&begin_x)) - return NULL; - break; - default: - PyErr_SetString(PyExc_TypeError, "newwin requires 2 or 4 arguments"); - return NULL; - } - - win = newwin(nlines,ncols,begin_y,begin_x); - if (win == NULL) { - PyErr_SetString(PyCursesError, catchall_NULL); - return NULL; - } + switch (PyTuple_Size(args)) { + case 2: + if (!PyArg_ParseTuple(args,"ii;nlines,ncols",&nlines,&ncols)) + return NULL; + break; + case 4: + if (!PyArg_ParseTuple(args, "iiii;nlines,ncols,begin_y,begin_x", + &nlines,&ncols,&begin_y,&begin_x)) + return NULL; + break; + default: + PyErr_SetString(PyExc_TypeError, "newwin requires 2 or 4 arguments"); + return NULL; + } + + win = newwin(nlines,ncols,begin_y,begin_x); + if (win == NULL) { + PyErr_SetString(PyCursesError, catchall_NULL); + return NULL; + } - return (PyObject *)PyCursesWindow_New(win); + return (PyObject *)PyCursesWindow_New(win); } static PyObject * PyCurses_Pair_Content(PyObject *self, PyObject *args) { - short pair,f,b; + short pair,f,b; + + PyCursesInitialised; + PyCursesInitialisedColor; - PyCursesInitialised; - PyCursesInitialisedColor; + switch(PyTuple_Size(args)) { + case 1: + if (!PyArg_ParseTuple(args, "h;pair", &pair)) return NULL; + break; + default: + PyErr_SetString(PyExc_TypeError, "pair_content requires 1 argument"); + return NULL; + } - switch(PyTuple_Size(args)) { - case 1: - if (!PyArg_ParseTuple(args, "h;pair", &pair)) return NULL; - break; - default: - PyErr_SetString(PyExc_TypeError, "pair_content requires 1 argument"); - return NULL; - } - - if (pair_content(pair, &f, &b)==ERR) { - PyErr_SetString(PyCursesError, - "Argument 1 was out of range. (1..COLOR_PAIRS-1)"); - return NULL; - } + if (pair_content(pair, &f, &b)==ERR) { + PyErr_SetString(PyCursesError, + "Argument 1 was out of range. (1..COLOR_PAIRS-1)"); + return NULL; + } - return Py_BuildValue("(ii)", f, b); + return Py_BuildValue("(ii)", f, b); } static PyObject * PyCurses_pair_number(PyObject *self, PyObject *args) { - int n; + int n; - PyCursesInitialised; - PyCursesInitialisedColor; + PyCursesInitialised; + PyCursesInitialisedColor; - switch(PyTuple_Size(args)) { - case 1: - if (!PyArg_ParseTuple(args, "i;pairvalue", &n)) return NULL; - break; - default: - PyErr_SetString(PyExc_TypeError, - "pair_number requires 1 argument"); - return NULL; - } + switch(PyTuple_Size(args)) { + case 1: + if (!PyArg_ParseTuple(args, "i;pairvalue", &n)) return NULL; + break; + default: + PyErr_SetString(PyExc_TypeError, + "pair_number requires 1 argument"); + return NULL; + } - return PyLong_FromLong((long) ((n & A_COLOR) >> 8)); + return PyLong_FromLong((long) ((n & A_COLOR) >> 8)); } static PyObject * PyCurses_Putp(PyObject *self, PyObject *args) { - char *str; + char *str; - if (!PyArg_ParseTuple(args,"s;str", &str)) return NULL; - return PyCursesCheckERR(putp(str), "putp"); + if (!PyArg_ParseTuple(args,"s;str", &str)) return NULL; + return PyCursesCheckERR(putp(str), "putp"); } static PyObject * PyCurses_QiFlush(PyObject *self, PyObject *args) { - int flag = 0; + int flag = 0; - PyCursesInitialised; + PyCursesInitialised; - switch(PyTuple_Size(args)) { - case 0: - qiflush(); - Py_INCREF(Py_None); - return Py_None; - case 1: - if (!PyArg_ParseTuple(args, "i;True(1) or False(0)", &flag)) return NULL; - if (flag) qiflush(); - else noqiflush(); - Py_INCREF(Py_None); - return Py_None; - default: - PyErr_SetString(PyExc_TypeError, "qiflush requires 0 or 1 arguments"); - return NULL; - } + switch(PyTuple_Size(args)) { + case 0: + qiflush(); + Py_INCREF(Py_None); + return Py_None; + case 1: + if (!PyArg_ParseTuple(args, "i;True(1) or False(0)", &flag)) return NULL; + if (flag) qiflush(); + else noqiflush(); + Py_INCREF(Py_None); + return Py_None; + default: + PyErr_SetString(PyExc_TypeError, "qiflush requires 0 or 1 arguments"); + return NULL; + } } /* Internal helper used for updating curses.LINES, curses.COLS, _curses.LINES @@ -2413,46 +2413,46 @@ static int update_lines_cols(void) { - PyObject *o; - PyObject *m = PyImport_ImportModuleNoBlock("curses"); + PyObject *o; + PyObject *m = PyImport_ImportModuleNoBlock("curses"); - if (!m) - return 0; + if (!m) + return 0; - o = PyLong_FromLong(LINES); - if (!o) { - Py_DECREF(m); - return 0; - } - if (PyObject_SetAttrString(m, "LINES", o)) { - Py_DECREF(m); - Py_DECREF(o); - return 0; - } - if (PyDict_SetItemString(ModDict, "LINES", o)) { - Py_DECREF(m); + o = PyLong_FromLong(LINES); + if (!o) { + Py_DECREF(m); + return 0; + } + if (PyObject_SetAttrString(m, "LINES", o)) { + Py_DECREF(m); + Py_DECREF(o); + return 0; + } + if (PyDict_SetItemString(ModDict, "LINES", o)) { + Py_DECREF(m); + Py_DECREF(o); + return 0; + } Py_DECREF(o); - return 0; - } - Py_DECREF(o); - o = PyLong_FromLong(COLS); - if (!o) { - Py_DECREF(m); - return 0; - } - if (PyObject_SetAttrString(m, "COLS", o)) { - Py_DECREF(m); + o = PyLong_FromLong(COLS); + if (!o) { + Py_DECREF(m); + return 0; + } + if (PyObject_SetAttrString(m, "COLS", o)) { + Py_DECREF(m); + Py_DECREF(o); + return 0; + } + if (PyDict_SetItemString(ModDict, "COLS", o)) { + Py_DECREF(m); + Py_DECREF(o); + return 0; + } Py_DECREF(o); - return 0; - } - if (PyDict_SetItemString(ModDict, "COLS", o)) { Py_DECREF(m); - Py_DECREF(o); - return 0; - } - Py_DECREF(o); - Py_DECREF(m); - return 1; + return 1; } #endif @@ -2460,21 +2460,21 @@ static PyObject * PyCurses_ResizeTerm(PyObject *self, PyObject *args) { - int lines; - int columns; - PyObject *result; - - PyCursesInitialised; - - if (!PyArg_ParseTuple(args,"ii:resizeterm", &lines, &columns)) - return NULL; - - result = PyCursesCheckERR(resizeterm(lines, columns), "resizeterm"); - if (!result) - return NULL; - if (!update_lines_cols()) - return NULL; - return result; + int lines; + int columns; + PyObject *result; + + PyCursesInitialised; + + if (!PyArg_ParseTuple(args,"ii:resizeterm", &lines, &columns)) + return NULL; + + result = PyCursesCheckERR(resizeterm(lines, columns), "resizeterm"); + if (!result) + return NULL; + if (!update_lines_cols()) + return NULL; + return result; } #endif @@ -2483,496 +2483,496 @@ static PyObject * PyCurses_Resize_Term(PyObject *self, PyObject *args) { - int lines; - int columns; + int lines; + int columns; - PyObject *result; + PyObject *result; - PyCursesInitialised; + PyCursesInitialised; - if (!PyArg_ParseTuple(args,"ii:resize_term", &lines, &columns)) - return NULL; - - result = PyCursesCheckERR(resize_term(lines, columns), "resize_term"); - if (!result) - return NULL; - if (!update_lines_cols()) - return NULL; - return result; + if (!PyArg_ParseTuple(args,"ii:resize_term", &lines, &columns)) + return NULL; + + result = PyCursesCheckERR(resize_term(lines, columns), "resize_term"); + if (!result) + return NULL; + if (!update_lines_cols()) + return NULL; + return result; } #endif /* HAVE_CURSES_RESIZE_TERM */ static PyObject * PyCurses_setsyx(PyObject *self, PyObject *args) { - int y,x; + int y,x; - PyCursesInitialised; + PyCursesInitialised; - if (PyTuple_Size(args)!=2) { - PyErr_SetString(PyExc_TypeError, "setsyx requires 2 arguments"); - return NULL; - } + if (PyTuple_Size(args)!=2) { + PyErr_SetString(PyExc_TypeError, "setsyx requires 2 arguments"); + return NULL; + } - if (!PyArg_ParseTuple(args, "ii;y, x", &y, &x)) return NULL; + if (!PyArg_ParseTuple(args, "ii;y, x", &y, &x)) return NULL; - setsyx(y,x); + setsyx(y,x); - Py_INCREF(Py_None); - return Py_None; + Py_INCREF(Py_None); + return Py_None; } static PyObject * PyCurses_Start_Color(PyObject *self) { - int code; - PyObject *c, *cp; + int code; + PyObject *c, *cp; - PyCursesInitialised; + PyCursesInitialised; - code = start_color(); - if (code != ERR) { - initialisedcolors = TRUE; - c = PyLong_FromLong((long) COLORS); - PyDict_SetItemString(ModDict, "COLORS", c); - Py_DECREF(c); - cp = PyLong_FromLong((long) COLOR_PAIRS); - PyDict_SetItemString(ModDict, "COLOR_PAIRS", cp); - Py_DECREF(cp); - Py_INCREF(Py_None); - return Py_None; - } else { - PyErr_SetString(PyCursesError, "start_color() returned ERR"); - return NULL; - } + code = start_color(); + if (code != ERR) { + initialisedcolors = TRUE; + c = PyLong_FromLong((long) COLORS); + PyDict_SetItemString(ModDict, "COLORS", c); + Py_DECREF(c); + cp = PyLong_FromLong((long) COLOR_PAIRS); + PyDict_SetItemString(ModDict, "COLOR_PAIRS", cp); + Py_DECREF(cp); + Py_INCREF(Py_None); + return Py_None; + } else { + PyErr_SetString(PyCursesError, "start_color() returned ERR"); + return NULL; + } } static PyObject * PyCurses_tigetflag(PyObject *self, PyObject *args) { - char *capname; + char *capname; - PyCursesSetupTermCalled; - - if (!PyArg_ParseTuple(args, "s", &capname)) - return NULL; + PyCursesSetupTermCalled; - return PyLong_FromLong( (long) tigetflag( capname ) ); + if (!PyArg_ParseTuple(args, "s", &capname)) + return NULL; + + return PyLong_FromLong( (long) tigetflag( capname ) ); } static PyObject * PyCurses_tigetnum(PyObject *self, PyObject *args) { - char *capname; + char *capname; - PyCursesSetupTermCalled; - - if (!PyArg_ParseTuple(args, "s", &capname)) - return NULL; + PyCursesSetupTermCalled; - return PyLong_FromLong( (long) tigetnum( capname ) ); + if (!PyArg_ParseTuple(args, "s", &capname)) + return NULL; + + return PyLong_FromLong( (long) tigetnum( capname ) ); } static PyObject * PyCurses_tigetstr(PyObject *self, PyObject *args) { - char *capname; + char *capname; + + PyCursesSetupTermCalled; - PyCursesSetupTermCalled; - - if (!PyArg_ParseTuple(args, "s", &capname)) - return NULL; - - capname = tigetstr( capname ); - if (capname == 0 || capname == (char*) -1) { - Py_INCREF(Py_None); - return Py_None; - } - return PyBytes_FromString( capname ); + if (!PyArg_ParseTuple(args, "s", &capname)) + return NULL; + + capname = tigetstr( capname ); + if (capname == 0 || capname == (char*) -1) { + Py_INCREF(Py_None); + return Py_None; + } + return PyBytes_FromString( capname ); } static PyObject * PyCurses_tparm(PyObject *self, PyObject *args) { - char* fmt; - char* result = NULL; - int i1=0,i2=0,i3=0,i4=0,i5=0,i6=0,i7=0,i8=0,i9=0; - - PyCursesSetupTermCalled; - - if (!PyArg_ParseTuple(args, "s|iiiiiiiii:tparm", - &fmt, &i1, &i2, &i3, &i4, - &i5, &i6, &i7, &i8, &i9)) { - return NULL; - } - - result = tparm(fmt,i1,i2,i3,i4,i5,i6,i7,i8,i9); - if (!result) { - PyErr_SetString(PyCursesError, "tparm() returned NULL"); - return NULL; - } + char* fmt; + char* result = NULL; + int i1=0,i2=0,i3=0,i4=0,i5=0,i6=0,i7=0,i8=0,i9=0; + + PyCursesSetupTermCalled; + + if (!PyArg_ParseTuple(args, "s|iiiiiiiii:tparm", + &fmt, &i1, &i2, &i3, &i4, + &i5, &i6, &i7, &i8, &i9)) { + return NULL; + } - return PyBytes_FromString(result); + result = tparm(fmt,i1,i2,i3,i4,i5,i6,i7,i8,i9); + if (!result) { + PyErr_SetString(PyCursesError, "tparm() returned NULL"); + return NULL; + } + + return PyBytes_FromString(result); } static PyObject * PyCurses_TypeAhead(PyObject *self, PyObject *args) { - int fd; + int fd; - PyCursesInitialised; + PyCursesInitialised; - if (!PyArg_ParseTuple(args,"i;fd",&fd)) return NULL; + if (!PyArg_ParseTuple(args,"i;fd",&fd)) return NULL; - return PyCursesCheckERR(typeahead( fd ), "typeahead"); + return PyCursesCheckERR(typeahead( fd ), "typeahead"); } static PyObject * PyCurses_UnCtrl(PyObject *self, PyObject *args) { - PyObject *temp; - chtype ch; + PyObject *temp; + chtype ch; - PyCursesInitialised; + PyCursesInitialised; - if (!PyArg_ParseTuple(args,"O;ch or int",&temp)) return NULL; + if (!PyArg_ParseTuple(args,"O;ch or int",&temp)) return NULL; - if (!PyCurses_ConvertToChtype(temp, &ch)) { - PyErr_SetString(PyExc_TypeError, "argument must be a ch or an int"); - return NULL; - } + if (!PyCurses_ConvertToChtype(temp, &ch)) { + PyErr_SetString(PyExc_TypeError, "argument must be a ch or an int"); + return NULL; + } - return PyBytes_FromString(unctrl(ch)); + return PyBytes_FromString(unctrl(ch)); } static PyObject * PyCurses_UngetCh(PyObject *self, PyObject *args) { - PyObject *temp; - chtype ch; + PyObject *temp; + chtype ch; - PyCursesInitialised; + PyCursesInitialised; - if (!PyArg_ParseTuple(args,"O;ch or int",&temp)) return NULL; + if (!PyArg_ParseTuple(args,"O;ch or int",&temp)) return NULL; - if (!PyCurses_ConvertToChtype(temp, &ch)) { - PyErr_SetString(PyExc_TypeError, "argument must be a ch or an int"); - return NULL; - } + if (!PyCurses_ConvertToChtype(temp, &ch)) { + PyErr_SetString(PyExc_TypeError, "argument must be a ch or an int"); + return NULL; + } - return PyCursesCheckERR(ungetch(ch), "ungetch"); + return PyCursesCheckERR(ungetch(ch), "ungetch"); } static PyObject * PyCurses_Use_Env(PyObject *self, PyObject *args) { - int flag; + int flag; - switch(PyTuple_Size(args)) { - case 1: - if (!PyArg_ParseTuple(args,"i;True(1), False(0)",&flag)) - return NULL; - break; - default: - PyErr_SetString(PyExc_TypeError, "use_env requires 1 argument"); - return NULL; - } - use_env(flag); - Py_INCREF(Py_None); - return Py_None; + switch(PyTuple_Size(args)) { + case 1: + if (!PyArg_ParseTuple(args,"i;True(1), False(0)",&flag)) + return NULL; + break; + default: + PyErr_SetString(PyExc_TypeError, "use_env requires 1 argument"); + return NULL; + } + use_env(flag); + Py_INCREF(Py_None); + return Py_None; } #ifndef STRICT_SYSV_CURSES static PyObject * PyCurses_Use_Default_Colors(PyObject *self) { - int code; + int code; - PyCursesInitialised; - PyCursesInitialisedColor; + PyCursesInitialised; + PyCursesInitialisedColor; - code = use_default_colors(); - if (code != ERR) { - Py_INCREF(Py_None); - return Py_None; - } else { - PyErr_SetString(PyCursesError, "use_default_colors() returned ERR"); - return NULL; - } + code = use_default_colors(); + if (code != ERR) { + Py_INCREF(Py_None); + return Py_None; + } else { + PyErr_SetString(PyCursesError, "use_default_colors() returned ERR"); + return NULL; + } } #endif /* STRICT_SYSV_CURSES */ /* List of functions defined in the module */ static PyMethodDef PyCurses_methods[] = { - {"baudrate", (PyCFunction)PyCurses_baudrate, METH_NOARGS}, - {"beep", (PyCFunction)PyCurses_beep, METH_NOARGS}, - {"can_change_color", (PyCFunction)PyCurses_can_change_color, METH_NOARGS}, - {"cbreak", (PyCFunction)PyCurses_cbreak, METH_VARARGS}, - {"color_content", (PyCFunction)PyCurses_Color_Content, METH_VARARGS}, - {"color_pair", (PyCFunction)PyCurses_color_pair, METH_VARARGS}, - {"curs_set", (PyCFunction)PyCurses_Curs_Set, METH_VARARGS}, - {"def_prog_mode", (PyCFunction)PyCurses_def_prog_mode, METH_NOARGS}, - {"def_shell_mode", (PyCFunction)PyCurses_def_shell_mode, METH_NOARGS}, - {"delay_output", (PyCFunction)PyCurses_Delay_Output, METH_VARARGS}, - {"doupdate", (PyCFunction)PyCurses_doupdate, METH_NOARGS}, - {"echo", (PyCFunction)PyCurses_echo, METH_VARARGS}, - {"endwin", (PyCFunction)PyCurses_endwin, METH_NOARGS}, - {"erasechar", (PyCFunction)PyCurses_EraseChar, METH_NOARGS}, - {"filter", (PyCFunction)PyCurses_filter, METH_NOARGS}, - {"flash", (PyCFunction)PyCurses_flash, METH_NOARGS}, - {"flushinp", (PyCFunction)PyCurses_flushinp, METH_NOARGS}, + {"baudrate", (PyCFunction)PyCurses_baudrate, METH_NOARGS}, + {"beep", (PyCFunction)PyCurses_beep, METH_NOARGS}, + {"can_change_color", (PyCFunction)PyCurses_can_change_color, METH_NOARGS}, + {"cbreak", (PyCFunction)PyCurses_cbreak, METH_VARARGS}, + {"color_content", (PyCFunction)PyCurses_Color_Content, METH_VARARGS}, + {"color_pair", (PyCFunction)PyCurses_color_pair, METH_VARARGS}, + {"curs_set", (PyCFunction)PyCurses_Curs_Set, METH_VARARGS}, + {"def_prog_mode", (PyCFunction)PyCurses_def_prog_mode, METH_NOARGS}, + {"def_shell_mode", (PyCFunction)PyCurses_def_shell_mode, METH_NOARGS}, + {"delay_output", (PyCFunction)PyCurses_Delay_Output, METH_VARARGS}, + {"doupdate", (PyCFunction)PyCurses_doupdate, METH_NOARGS}, + {"echo", (PyCFunction)PyCurses_echo, METH_VARARGS}, + {"endwin", (PyCFunction)PyCurses_endwin, METH_NOARGS}, + {"erasechar", (PyCFunction)PyCurses_EraseChar, METH_NOARGS}, + {"filter", (PyCFunction)PyCurses_filter, METH_NOARGS}, + {"flash", (PyCFunction)PyCurses_flash, METH_NOARGS}, + {"flushinp", (PyCFunction)PyCurses_flushinp, METH_NOARGS}, #ifdef NCURSES_MOUSE_VERSION - {"getmouse", (PyCFunction)PyCurses_GetMouse, METH_NOARGS}, - {"ungetmouse", (PyCFunction)PyCurses_UngetMouse, METH_VARARGS}, + {"getmouse", (PyCFunction)PyCurses_GetMouse, METH_NOARGS}, + {"ungetmouse", (PyCFunction)PyCurses_UngetMouse, METH_VARARGS}, #endif - {"getsyx", (PyCFunction)PyCurses_getsyx, METH_NOARGS}, - {"getwin", (PyCFunction)PyCurses_GetWin, METH_O}, - {"has_colors", (PyCFunction)PyCurses_has_colors, METH_NOARGS}, - {"has_ic", (PyCFunction)PyCurses_has_ic, METH_NOARGS}, - {"has_il", (PyCFunction)PyCurses_has_il, METH_NOARGS}, + {"getsyx", (PyCFunction)PyCurses_getsyx, METH_NOARGS}, + {"getwin", (PyCFunction)PyCurses_GetWin, METH_O}, + {"has_colors", (PyCFunction)PyCurses_has_colors, METH_NOARGS}, + {"has_ic", (PyCFunction)PyCurses_has_ic, METH_NOARGS}, + {"has_il", (PyCFunction)PyCurses_has_il, METH_NOARGS}, #ifndef STRICT_SYSV_CURSES - {"has_key", (PyCFunction)PyCurses_has_key, METH_VARARGS}, + {"has_key", (PyCFunction)PyCurses_has_key, METH_VARARGS}, #endif - {"halfdelay", (PyCFunction)PyCurses_HalfDelay, METH_VARARGS}, - {"init_color", (PyCFunction)PyCurses_Init_Color, METH_VARARGS}, - {"init_pair", (PyCFunction)PyCurses_Init_Pair, METH_VARARGS}, - {"initscr", (PyCFunction)PyCurses_InitScr, METH_NOARGS}, - {"intrflush", (PyCFunction)PyCurses_IntrFlush, METH_VARARGS}, - {"isendwin", (PyCFunction)PyCurses_isendwin, METH_NOARGS}, + {"halfdelay", (PyCFunction)PyCurses_HalfDelay, METH_VARARGS}, + {"init_color", (PyCFunction)PyCurses_Init_Color, METH_VARARGS}, + {"init_pair", (PyCFunction)PyCurses_Init_Pair, METH_VARARGS}, + {"initscr", (PyCFunction)PyCurses_InitScr, METH_NOARGS}, + {"intrflush", (PyCFunction)PyCurses_IntrFlush, METH_VARARGS}, + {"isendwin", (PyCFunction)PyCurses_isendwin, METH_NOARGS}, #ifdef HAVE_CURSES_IS_TERM_RESIZED - {"is_term_resized", (PyCFunction)PyCurses_Is_Term_Resized, METH_VARARGS}, + {"is_term_resized", (PyCFunction)PyCurses_Is_Term_Resized, METH_VARARGS}, #endif #if !defined(__NetBSD__) - {"keyname", (PyCFunction)PyCurses_KeyName, METH_VARARGS}, + {"keyname", (PyCFunction)PyCurses_KeyName, METH_VARARGS}, #endif - {"killchar", (PyCFunction)PyCurses_KillChar, METH_NOARGS}, - {"longname", (PyCFunction)PyCurses_longname, METH_NOARGS}, - {"meta", (PyCFunction)PyCurses_Meta, METH_VARARGS}, + {"killchar", (PyCFunction)PyCurses_KillChar, METH_NOARGS}, + {"longname", (PyCFunction)PyCurses_longname, METH_NOARGS}, + {"meta", (PyCFunction)PyCurses_Meta, METH_VARARGS}, #ifdef NCURSES_MOUSE_VERSION - {"mouseinterval", (PyCFunction)PyCurses_MouseInterval, METH_VARARGS}, - {"mousemask", (PyCFunction)PyCurses_MouseMask, METH_VARARGS}, + {"mouseinterval", (PyCFunction)PyCurses_MouseInterval, METH_VARARGS}, + {"mousemask", (PyCFunction)PyCurses_MouseMask, METH_VARARGS}, #endif - {"napms", (PyCFunction)PyCurses_Napms, METH_VARARGS}, - {"newpad", (PyCFunction)PyCurses_NewPad, METH_VARARGS}, - {"newwin", (PyCFunction)PyCurses_NewWindow, METH_VARARGS}, - {"nl", (PyCFunction)PyCurses_nl, METH_VARARGS}, - {"nocbreak", (PyCFunction)PyCurses_nocbreak, METH_NOARGS}, - {"noecho", (PyCFunction)PyCurses_noecho, METH_NOARGS}, - {"nonl", (PyCFunction)PyCurses_nonl, METH_NOARGS}, - {"noqiflush", (PyCFunction)PyCurses_noqiflush, METH_NOARGS}, - {"noraw", (PyCFunction)PyCurses_noraw, METH_NOARGS}, - {"pair_content", (PyCFunction)PyCurses_Pair_Content, METH_VARARGS}, - {"pair_number", (PyCFunction)PyCurses_pair_number, METH_VARARGS}, - {"putp", (PyCFunction)PyCurses_Putp, METH_VARARGS}, - {"qiflush", (PyCFunction)PyCurses_QiFlush, METH_VARARGS}, - {"raw", (PyCFunction)PyCurses_raw, METH_VARARGS}, - {"reset_prog_mode", (PyCFunction)PyCurses_reset_prog_mode, METH_NOARGS}, - {"reset_shell_mode", (PyCFunction)PyCurses_reset_shell_mode, METH_NOARGS}, - {"resetty", (PyCFunction)PyCurses_resetty, METH_NOARGS}, + {"napms", (PyCFunction)PyCurses_Napms, METH_VARARGS}, + {"newpad", (PyCFunction)PyCurses_NewPad, METH_VARARGS}, + {"newwin", (PyCFunction)PyCurses_NewWindow, METH_VARARGS}, + {"nl", (PyCFunction)PyCurses_nl, METH_VARARGS}, + {"nocbreak", (PyCFunction)PyCurses_nocbreak, METH_NOARGS}, + {"noecho", (PyCFunction)PyCurses_noecho, METH_NOARGS}, + {"nonl", (PyCFunction)PyCurses_nonl, METH_NOARGS}, + {"noqiflush", (PyCFunction)PyCurses_noqiflush, METH_NOARGS}, + {"noraw", (PyCFunction)PyCurses_noraw, METH_NOARGS}, + {"pair_content", (PyCFunction)PyCurses_Pair_Content, METH_VARARGS}, + {"pair_number", (PyCFunction)PyCurses_pair_number, METH_VARARGS}, + {"putp", (PyCFunction)PyCurses_Putp, METH_VARARGS}, + {"qiflush", (PyCFunction)PyCurses_QiFlush, METH_VARARGS}, + {"raw", (PyCFunction)PyCurses_raw, METH_VARARGS}, + {"reset_prog_mode", (PyCFunction)PyCurses_reset_prog_mode, METH_NOARGS}, + {"reset_shell_mode", (PyCFunction)PyCurses_reset_shell_mode, METH_NOARGS}, + {"resetty", (PyCFunction)PyCurses_resetty, METH_NOARGS}, #ifdef HAVE_CURSES_RESIZETERM - {"resizeterm", (PyCFunction)PyCurses_ResizeTerm, METH_VARARGS}, + {"resizeterm", (PyCFunction)PyCurses_ResizeTerm, METH_VARARGS}, #endif #ifdef HAVE_CURSES_RESIZE_TERM - {"resize_term", (PyCFunction)PyCurses_Resize_Term, METH_VARARGS}, + {"resize_term", (PyCFunction)PyCurses_Resize_Term, METH_VARARGS}, #endif - {"savetty", (PyCFunction)PyCurses_savetty, METH_NOARGS}, - {"setsyx", (PyCFunction)PyCurses_setsyx, METH_VARARGS}, - {"setupterm", (PyCFunction)PyCurses_setupterm, - METH_VARARGS|METH_KEYWORDS}, - {"start_color", (PyCFunction)PyCurses_Start_Color, METH_NOARGS}, - {"termattrs", (PyCFunction)PyCurses_termattrs, METH_NOARGS}, - {"termname", (PyCFunction)PyCurses_termname, METH_NOARGS}, - {"tigetflag", (PyCFunction)PyCurses_tigetflag, METH_VARARGS}, - {"tigetnum", (PyCFunction)PyCurses_tigetnum, METH_VARARGS}, - {"tigetstr", (PyCFunction)PyCurses_tigetstr, METH_VARARGS}, - {"tparm", (PyCFunction)PyCurses_tparm, METH_VARARGS}, - {"typeahead", (PyCFunction)PyCurses_TypeAhead, METH_VARARGS}, - {"unctrl", (PyCFunction)PyCurses_UnCtrl, METH_VARARGS}, - {"ungetch", (PyCFunction)PyCurses_UngetCh, METH_VARARGS}, - {"use_env", (PyCFunction)PyCurses_Use_Env, METH_VARARGS}, + {"savetty", (PyCFunction)PyCurses_savetty, METH_NOARGS}, + {"setsyx", (PyCFunction)PyCurses_setsyx, METH_VARARGS}, + {"setupterm", (PyCFunction)PyCurses_setupterm, + METH_VARARGS|METH_KEYWORDS}, + {"start_color", (PyCFunction)PyCurses_Start_Color, METH_NOARGS}, + {"termattrs", (PyCFunction)PyCurses_termattrs, METH_NOARGS}, + {"termname", (PyCFunction)PyCurses_termname, METH_NOARGS}, + {"tigetflag", (PyCFunction)PyCurses_tigetflag, METH_VARARGS}, + {"tigetnum", (PyCFunction)PyCurses_tigetnum, METH_VARARGS}, + {"tigetstr", (PyCFunction)PyCurses_tigetstr, METH_VARARGS}, + {"tparm", (PyCFunction)PyCurses_tparm, METH_VARARGS}, + {"typeahead", (PyCFunction)PyCurses_TypeAhead, METH_VARARGS}, + {"unctrl", (PyCFunction)PyCurses_UnCtrl, METH_VARARGS}, + {"ungetch", (PyCFunction)PyCurses_UngetCh, METH_VARARGS}, + {"use_env", (PyCFunction)PyCurses_Use_Env, METH_VARARGS}, #ifndef STRICT_SYSV_CURSES - {"use_default_colors", (PyCFunction)PyCurses_Use_Default_Colors, METH_NOARGS}, + {"use_default_colors", (PyCFunction)PyCurses_Use_Default_Colors, METH_NOARGS}, #endif - {NULL, NULL} /* sentinel */ + {NULL, NULL} /* sentinel */ }; /* Initialization function for the module */ static struct PyModuleDef _cursesmodule = { - PyModuleDef_HEAD_INIT, - "_curses", - NULL, - -1, - PyCurses_methods, - NULL, - NULL, - NULL, - NULL + PyModuleDef_HEAD_INIT, + "_curses", + NULL, + -1, + PyCurses_methods, + NULL, + NULL, + NULL, + NULL }; PyMODINIT_FUNC PyInit__curses(void) { - PyObject *m, *d, *v, *c_api_object; - static void *PyCurses_API[PyCurses_API_pointers]; + PyObject *m, *d, *v, *c_api_object; + static void *PyCurses_API[PyCurses_API_pointers]; + + /* Initialize object type */ + if (PyType_Ready(&PyCursesWindow_Type) < 0) + return NULL; + + /* Initialize the C API pointer array */ + PyCurses_API[0] = (void *)&PyCursesWindow_Type; + PyCurses_API[1] = (void *)func_PyCursesSetupTermCalled; + PyCurses_API[2] = (void *)func_PyCursesInitialised; + PyCurses_API[3] = (void *)func_PyCursesInitialisedColor; + + /* Create the module and add the functions */ + m = PyModule_Create(&_cursesmodule); + if (m == NULL) + return NULL; - /* Initialize object type */ - if (PyType_Ready(&PyCursesWindow_Type) < 0) - return NULL; - - /* Initialize the C API pointer array */ - PyCurses_API[0] = (void *)&PyCursesWindow_Type; - PyCurses_API[1] = (void *)func_PyCursesSetupTermCalled; - PyCurses_API[2] = (void *)func_PyCursesInitialised; - PyCurses_API[3] = (void *)func_PyCursesInitialisedColor; - - /* Create the module and add the functions */ - m = PyModule_Create(&_cursesmodule); - if (m == NULL) - return NULL; - - /* Add some symbolic constants to the module */ - d = PyModule_GetDict(m); - if (d == NULL) - return NULL; - ModDict = d; /* For PyCurses_InitScr to use later */ - - /* Add a capsule for the C API */ - c_api_object = PyCapsule_New(PyCurses_API, PyCurses_CAPSULE_NAME, NULL); - PyDict_SetItemString(d, "_C_API", c_api_object); - Py_DECREF(c_api_object); - - /* For exception curses.error */ - PyCursesError = PyErr_NewException("_curses.error", NULL, NULL); - PyDict_SetItemString(d, "error", PyCursesError); - - /* Make the version available */ - v = PyBytes_FromString(PyCursesVersion); - PyDict_SetItemString(d, "version", v); - PyDict_SetItemString(d, "__version__", v); - Py_DECREF(v); - - SetDictInt("ERR", ERR); - SetDictInt("OK", OK); - - /* Here are some attributes you can add to chars to print */ - - SetDictInt("A_ATTRIBUTES", A_ATTRIBUTES); - SetDictInt("A_NORMAL", A_NORMAL); - SetDictInt("A_STANDOUT", A_STANDOUT); - SetDictInt("A_UNDERLINE", A_UNDERLINE); - SetDictInt("A_REVERSE", A_REVERSE); - SetDictInt("A_BLINK", A_BLINK); - SetDictInt("A_DIM", A_DIM); - SetDictInt("A_BOLD", A_BOLD); - SetDictInt("A_ALTCHARSET", A_ALTCHARSET); + /* Add some symbolic constants to the module */ + d = PyModule_GetDict(m); + if (d == NULL) + return NULL; + ModDict = d; /* For PyCurses_InitScr to use later */ + + /* Add a capsule for the C API */ + c_api_object = PyCapsule_New(PyCurses_API, PyCurses_CAPSULE_NAME, NULL); + PyDict_SetItemString(d, "_C_API", c_api_object); + Py_DECREF(c_api_object); + + /* For exception curses.error */ + PyCursesError = PyErr_NewException("_curses.error", NULL, NULL); + PyDict_SetItemString(d, "error", PyCursesError); + + /* Make the version available */ + v = PyBytes_FromString(PyCursesVersion); + PyDict_SetItemString(d, "version", v); + PyDict_SetItemString(d, "__version__", v); + Py_DECREF(v); + + SetDictInt("ERR", ERR); + SetDictInt("OK", OK); + + /* Here are some attributes you can add to chars to print */ + + SetDictInt("A_ATTRIBUTES", A_ATTRIBUTES); + SetDictInt("A_NORMAL", A_NORMAL); + SetDictInt("A_STANDOUT", A_STANDOUT); + SetDictInt("A_UNDERLINE", A_UNDERLINE); + SetDictInt("A_REVERSE", A_REVERSE); + SetDictInt("A_BLINK", A_BLINK); + SetDictInt("A_DIM", A_DIM); + SetDictInt("A_BOLD", A_BOLD); + SetDictInt("A_ALTCHARSET", A_ALTCHARSET); #if !defined(__NetBSD__) - SetDictInt("A_INVIS", A_INVIS); + SetDictInt("A_INVIS", A_INVIS); #endif - SetDictInt("A_PROTECT", A_PROTECT); - SetDictInt("A_CHARTEXT", A_CHARTEXT); - SetDictInt("A_COLOR", A_COLOR); + SetDictInt("A_PROTECT", A_PROTECT); + SetDictInt("A_CHARTEXT", A_CHARTEXT); + SetDictInt("A_COLOR", A_COLOR); - /* The following are never available with strict SYSV curses */ + /* The following are never available with strict SYSV curses */ #ifdef A_HORIZONTAL - SetDictInt("A_HORIZONTAL", A_HORIZONTAL); + SetDictInt("A_HORIZONTAL", A_HORIZONTAL); #endif #ifdef A_LEFT - SetDictInt("A_LEFT", A_LEFT); + SetDictInt("A_LEFT", A_LEFT); #endif #ifdef A_LOW - SetDictInt("A_LOW", A_LOW); + SetDictInt("A_LOW", A_LOW); #endif #ifdef A_RIGHT - SetDictInt("A_RIGHT", A_RIGHT); + SetDictInt("A_RIGHT", A_RIGHT); #endif #ifdef A_TOP - SetDictInt("A_TOP", A_TOP); + SetDictInt("A_TOP", A_TOP); #endif #ifdef A_VERTICAL - SetDictInt("A_VERTICAL", A_VERTICAL); + SetDictInt("A_VERTICAL", A_VERTICAL); #endif - SetDictInt("COLOR_BLACK", COLOR_BLACK); - SetDictInt("COLOR_RED", COLOR_RED); - SetDictInt("COLOR_GREEN", COLOR_GREEN); - SetDictInt("COLOR_YELLOW", COLOR_YELLOW); - SetDictInt("COLOR_BLUE", COLOR_BLUE); - SetDictInt("COLOR_MAGENTA", COLOR_MAGENTA); - SetDictInt("COLOR_CYAN", COLOR_CYAN); - SetDictInt("COLOR_WHITE", COLOR_WHITE); + SetDictInt("COLOR_BLACK", COLOR_BLACK); + SetDictInt("COLOR_RED", COLOR_RED); + SetDictInt("COLOR_GREEN", COLOR_GREEN); + SetDictInt("COLOR_YELLOW", COLOR_YELLOW); + SetDictInt("COLOR_BLUE", COLOR_BLUE); + SetDictInt("COLOR_MAGENTA", COLOR_MAGENTA); + SetDictInt("COLOR_CYAN", COLOR_CYAN); + SetDictInt("COLOR_WHITE", COLOR_WHITE); #ifdef NCURSES_MOUSE_VERSION - /* Mouse-related constants */ - SetDictInt("BUTTON1_PRESSED", BUTTON1_PRESSED); - SetDictInt("BUTTON1_RELEASED", BUTTON1_RELEASED); - SetDictInt("BUTTON1_CLICKED", BUTTON1_CLICKED); - SetDictInt("BUTTON1_DOUBLE_CLICKED", BUTTON1_DOUBLE_CLICKED); - SetDictInt("BUTTON1_TRIPLE_CLICKED", BUTTON1_TRIPLE_CLICKED); - - SetDictInt("BUTTON2_PRESSED", BUTTON2_PRESSED); - SetDictInt("BUTTON2_RELEASED", BUTTON2_RELEASED); - SetDictInt("BUTTON2_CLICKED", BUTTON2_CLICKED); - SetDictInt("BUTTON2_DOUBLE_CLICKED", BUTTON2_DOUBLE_CLICKED); - SetDictInt("BUTTON2_TRIPLE_CLICKED", BUTTON2_TRIPLE_CLICKED); - - SetDictInt("BUTTON3_PRESSED", BUTTON3_PRESSED); - SetDictInt("BUTTON3_RELEASED", BUTTON3_RELEASED); - SetDictInt("BUTTON3_CLICKED", BUTTON3_CLICKED); - SetDictInt("BUTTON3_DOUBLE_CLICKED", BUTTON3_DOUBLE_CLICKED); - SetDictInt("BUTTON3_TRIPLE_CLICKED", BUTTON3_TRIPLE_CLICKED); - - SetDictInt("BUTTON4_PRESSED", BUTTON4_PRESSED); - SetDictInt("BUTTON4_RELEASED", BUTTON4_RELEASED); - SetDictInt("BUTTON4_CLICKED", BUTTON4_CLICKED); - SetDictInt("BUTTON4_DOUBLE_CLICKED", BUTTON4_DOUBLE_CLICKED); - SetDictInt("BUTTON4_TRIPLE_CLICKED", BUTTON4_TRIPLE_CLICKED); - - SetDictInt("BUTTON_SHIFT", BUTTON_SHIFT); - SetDictInt("BUTTON_CTRL", BUTTON_CTRL); - SetDictInt("BUTTON_ALT", BUTTON_ALT); - - SetDictInt("ALL_MOUSE_EVENTS", ALL_MOUSE_EVENTS); - SetDictInt("REPORT_MOUSE_POSITION", REPORT_MOUSE_POSITION); -#endif - /* Now set everything up for KEY_ variables */ - { - int key; - char *key_n; - char *key_n2; + /* Mouse-related constants */ + SetDictInt("BUTTON1_PRESSED", BUTTON1_PRESSED); + SetDictInt("BUTTON1_RELEASED", BUTTON1_RELEASED); + SetDictInt("BUTTON1_CLICKED", BUTTON1_CLICKED); + SetDictInt("BUTTON1_DOUBLE_CLICKED", BUTTON1_DOUBLE_CLICKED); + SetDictInt("BUTTON1_TRIPLE_CLICKED", BUTTON1_TRIPLE_CLICKED); + + SetDictInt("BUTTON2_PRESSED", BUTTON2_PRESSED); + SetDictInt("BUTTON2_RELEASED", BUTTON2_RELEASED); + SetDictInt("BUTTON2_CLICKED", BUTTON2_CLICKED); + SetDictInt("BUTTON2_DOUBLE_CLICKED", BUTTON2_DOUBLE_CLICKED); + SetDictInt("BUTTON2_TRIPLE_CLICKED", BUTTON2_TRIPLE_CLICKED); + + SetDictInt("BUTTON3_PRESSED", BUTTON3_PRESSED); + SetDictInt("BUTTON3_RELEASED", BUTTON3_RELEASED); + SetDictInt("BUTTON3_CLICKED", BUTTON3_CLICKED); + SetDictInt("BUTTON3_DOUBLE_CLICKED", BUTTON3_DOUBLE_CLICKED); + SetDictInt("BUTTON3_TRIPLE_CLICKED", BUTTON3_TRIPLE_CLICKED); + + SetDictInt("BUTTON4_PRESSED", BUTTON4_PRESSED); + SetDictInt("BUTTON4_RELEASED", BUTTON4_RELEASED); + SetDictInt("BUTTON4_CLICKED", BUTTON4_CLICKED); + SetDictInt("BUTTON4_DOUBLE_CLICKED", BUTTON4_DOUBLE_CLICKED); + SetDictInt("BUTTON4_TRIPLE_CLICKED", BUTTON4_TRIPLE_CLICKED); + + SetDictInt("BUTTON_SHIFT", BUTTON_SHIFT); + SetDictInt("BUTTON_CTRL", BUTTON_CTRL); + SetDictInt("BUTTON_ALT", BUTTON_ALT); + + SetDictInt("ALL_MOUSE_EVENTS", ALL_MOUSE_EVENTS); + SetDictInt("REPORT_MOUSE_POSITION", REPORT_MOUSE_POSITION); +#endif + /* Now set everything up for KEY_ variables */ + { + int key; + char *key_n; + char *key_n2; #if !defined(__NetBSD__) - for (key=KEY_MIN;key < KEY_MAX; key++) { - key_n = (char *)keyname(key); - if (key_n == NULL || strcmp(key_n,"UNKNOWN KEY")==0) - continue; - if (strncmp(key_n,"KEY_F(",6)==0) { - char *p1, *p2; - key_n2 = malloc(strlen(key_n)+1); - if (!key_n2) { - PyErr_NoMemory(); - break; - } - p1 = key_n; - p2 = key_n2; - while (*p1) { - if (*p1 != '(' && *p1 != ')') { - *p2 = *p1; - p2++; - } - p1++; - } - *p2 = (char)0; - } else - key_n2 = key_n; - SetDictInt(key_n2,key); - if (key_n2 != key_n) - free(key_n2); - } -#endif - SetDictInt("KEY_MIN", KEY_MIN); - SetDictInt("KEY_MAX", KEY_MAX); - } - return m; + for (key=KEY_MIN;key < KEY_MAX; key++) { + key_n = (char *)keyname(key); + if (key_n == NULL || strcmp(key_n,"UNKNOWN KEY")==0) + continue; + if (strncmp(key_n,"KEY_F(",6)==0) { + char *p1, *p2; + key_n2 = malloc(strlen(key_n)+1); + if (!key_n2) { + PyErr_NoMemory(); + break; + } + p1 = key_n; + p2 = key_n2; + while (*p1) { + if (*p1 != '(' && *p1 != ')') { + *p2 = *p1; + p2++; + } + p1++; + } + *p2 = (char)0; + } else + key_n2 = key_n; + SetDictInt(key_n2,key); + if (key_n2 != key_n) + free(key_n2); + } +#endif + SetDictInt("KEY_MIN", KEY_MIN); + SetDictInt("KEY_MAX", KEY_MAX); + } + return m; } Modified: python/branches/py3k-cdecimal/Modules/_io/textio.c ============================================================================== --- python/branches/py3k-cdecimal/Modules/_io/textio.c (original) +++ python/branches/py3k-cdecimal/Modules/_io/textio.c Wed May 19 17:30:16 2010 @@ -905,8 +905,11 @@ Py_CLEAR(self->encoding); } } - if (self->encoding != NULL) + if (self->encoding != NULL) { encoding = _PyUnicode_AsString(self->encoding); + if (encoding == NULL) + goto error; + } else if (encoding != NULL) { self->encoding = PyUnicode_FromString(encoding); if (self->encoding == NULL) @@ -935,6 +938,8 @@ self->writetranslate = (newline == NULL || newline[0] != '\0'); if (!self->readuniversal && self->readnl) { self->writenl = _PyUnicode_AsString(self->readnl); + if (self->writenl == NULL) + goto error; if (!strcmp(self->writenl, "\n")) self->writenl = NULL; } @@ -2408,7 +2413,7 @@ Py_DECREF(res); if (r < 0) return NULL; - + if (r > 0) { Py_RETURN_NONE; /* stream already closed */ } Modified: python/branches/py3k-cdecimal/Modules/_sqlite/connection.c ============================================================================== --- python/branches/py3k-cdecimal/Modules/_sqlite/connection.c (original) +++ python/branches/py3k-cdecimal/Modules/_sqlite/connection.c Wed May 19 17:30:16 2010 @@ -3,7 +3,7 @@ * Copyright (C) 2004-2010 Gerhard H?ring * * This file is part of pysqlite. - * + * * 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. @@ -495,7 +495,9 @@ } else if (PyFloat_Check(py_val)) { sqlite3_result_double(context, PyFloat_AsDouble(py_val)); } else if (PyUnicode_Check(py_val)) { - sqlite3_result_text(context, _PyUnicode_AsString(py_val), -1, SQLITE_TRANSIENT); + char *str = _PyUnicode_AsString(py_val); + if (str != NULL) + sqlite3_result_text(context, str, -1, SQLITE_TRANSIENT); } else if (PyObject_CheckBuffer(py_val)) { if (PyObject_AsCharBuffer(py_val, &buffer, &buflen) != 0) { PyErr_SetString(PyExc_ValueError, "could not convert BLOB to buffer"); @@ -892,7 +894,7 @@ } /* abort query if error occurred */ - rc = 1; + rc = 1; } else { rc = (int)PyObject_IsTrue(ret); Py_DECREF(ret); Modified: python/branches/py3k-cdecimal/Modules/_sqlite/cursor.c ============================================================================== --- python/branches/py3k-cdecimal/Modules/_sqlite/cursor.c (original) +++ python/branches/py3k-cdecimal/Modules/_sqlite/cursor.c Wed May 19 17:30:16 2010 @@ -368,7 +368,7 @@ } PyOS_snprintf(buf, sizeof(buf) - 1, "Could not decode to UTF-8 column '%s' with text '%s'", colname , val_str); - buf_bytes = PyByteArray_FromStringAndSize(buf, strlen(buf)); + buf_bytes = PyByteArray_FromStringAndSize(buf, strlen(buf)); if (!buf_bytes) { PyErr_SetString(pysqlite_OperationalError, "Could not decode to UTF-8"); } else { @@ -533,7 +533,7 @@ } operation_cstr = _PyUnicode_AsStringAndSize(operation, &operation_len); - if (operation == NULL) + if (operation_cstr == NULL) goto error; /* reset description and rowcount */ Modified: python/branches/py3k-cdecimal/Modules/_sqlite/row.c ============================================================================== --- python/branches/py3k-cdecimal/Modules/_sqlite/row.c (original) +++ python/branches/py3k-cdecimal/Modules/_sqlite/row.c Wed May 19 17:30:16 2010 @@ -83,6 +83,8 @@ return item; } else if (PyUnicode_Check(idx)) { key = _PyUnicode_AsString(idx); + if (key == NULL) + return NULL; nitems = PyTuple_Size(self->description); Modified: python/branches/py3k-cdecimal/Modules/_sqlite/statement.c ============================================================================== --- python/branches/py3k-cdecimal/Modules/_sqlite/statement.c (original) +++ python/branches/py3k-cdecimal/Modules/_sqlite/statement.c Wed May 19 17:30:16 2010 @@ -130,7 +130,10 @@ break; case TYPE_UNICODE: string = _PyUnicode_AsString(parameter); - rc = sqlite3_bind_text(self->st, pos, string, -1, SQLITE_TRANSIENT); + if (string != NULL) + rc = sqlite3_bind_text(self->st, pos, string, -1, SQLITE_TRANSIENT); + else + rc = -1; break; case TYPE_BUFFER: if (PyObject_AsCharBuffer(parameter, &buffer, &buflen) == 0) { Modified: python/branches/py3k-cdecimal/Modules/_ssl.c ============================================================================== --- python/branches/py3k-cdecimal/Modules/_ssl.c (original) +++ python/branches/py3k-cdecimal/Modules/_ssl.c Wed May 19 17:30:16 2010 @@ -115,23 +115,29 @@ typedef struct { PyObject_HEAD - PyObject *Socket; /* weakref to socket on which we're layered */ - SSL_CTX* ctx; - SSL* ssl; - X509* peer_cert; - int shutdown_seen_zero; - -} PySSLObject; - -static PyTypeObject PySSL_Type; -static PyObject *PySSL_SSLwrite(PySSLObject *self, PyObject *args); -static PyObject *PySSL_SSLread(PySSLObject *self, PyObject *args); + SSL_CTX *ctx; +} PySSLContext; + +typedef struct { + PyObject_HEAD + PyObject *Socket; /* weakref to socket on which we're layered */ + SSL *ssl; + X509 *peer_cert; + int shutdown_seen_zero; +} PySSLSocket; + +static PyTypeObject PySSLContext_Type; +static PyTypeObject PySSLSocket_Type; + +static PyObject *PySSL_SSLwrite(PySSLSocket *self, PyObject *args); +static PyObject *PySSL_SSLread(PySSLSocket *self, PyObject *args); static int check_socket_and_wait_for_timeout(PySocketSockObject *s, int writing); -static PyObject *PySSL_peercert(PySSLObject *self, PyObject *args); -static PyObject *PySSL_cipher(PySSLObject *self); +static PyObject *PySSL_peercert(PySSLSocket *self, PyObject *args); +static PyObject *PySSL_cipher(PySSLSocket *self); -#define PySSLObject_Check(v) (Py_TYPE(v) == &PySSL_Type) +#define PySSLContext_Check(v) (Py_TYPE(v) == &PySSLContext_Type) +#define PySSLSocket_Check(v) (Py_TYPE(v) == &PySSLSocket_Type) typedef enum { SOCKET_IS_NONBLOCKING, @@ -154,7 +160,7 @@ */ static PyObject * -PySSL_SetError(PySSLObject *obj, int ret, char *filename, int lineno) +PySSL_SetError(PySSLSocket *obj, int ret, char *filename, int lineno) { PyObject *v; char buf[2048]; @@ -199,6 +205,7 @@ errstr = "EOF occurred in violation of protocol"; } else if (ret == -1) { /* underlying BIO reported an I/O error */ + ERR_clear_error(); return s->errorhandler(); } else { /* possible? */ p = PY_SSL_ERROR_SYSCALL; @@ -231,6 +238,7 @@ errstr = ERR_error_string(ERR_peek_last_error(), NULL); } PyOS_snprintf(buf, sizeof(buf), "_ssl.c:%d: %s", lineno, errstr); + ERR_clear_error(); v = Py_BuildValue("(is)", p, buf); if (v != NULL) { PyErr_SetObject(PySSLErrorObject, v); @@ -250,6 +258,7 @@ errstr = ERR_error_string(errcode, NULL); } PyOS_snprintf(buf, sizeof(buf), "_ssl.c:%d: %s", lineno, errstr); + ERR_clear_error(); v = Py_BuildValue("(is)", errcode, buf); if (v != NULL) { PyErr_SetObject(PySSLErrorObject, v); @@ -258,126 +267,28 @@ return NULL; } -static PySSLObject * -newPySSLObject(PySocketSockObject *Sock, char *key_file, char *cert_file, - enum py_ssl_server_or_client socket_type, - enum py_ssl_cert_requirements certreq, - enum py_ssl_version proto_version, - char *cacerts_file, char *ciphers) +static PySSLSocket * +newPySSLSocket(SSL_CTX *ctx, PySocketSockObject *sock, + enum py_ssl_server_or_client socket_type) { - PySSLObject *self; - char *errstr = NULL; - int ret; - int verification_mode; + PySSLSocket *self; - self = PyObject_New(PySSLObject, &PySSL_Type); /* Create new object */ + self = PyObject_New(PySSLSocket, &PySSLSocket_Type); if (self == NULL) return NULL; + self->peer_cert = NULL; self->ssl = NULL; - self->ctx = NULL; self->Socket = NULL; /* Make sure the SSL error state is initialized */ (void) ERR_get_state(); ERR_clear_error(); - if ((key_file && !cert_file) || (!key_file && cert_file)) { - errstr = ERRSTR("Both the key & certificate files " - "must be specified"); - goto fail; - } - - if ((socket_type == PY_SSL_SERVER) && - ((key_file == NULL) || (cert_file == NULL))) { - errstr = ERRSTR("Both the key & certificate files " - "must be specified for server-side operation"); - goto fail; - } - - PySSL_BEGIN_ALLOW_THREADS - if (proto_version == PY_SSL_VERSION_TLS1) - self->ctx = SSL_CTX_new(TLSv1_method()); /* Set up context */ - else if (proto_version == PY_SSL_VERSION_SSL3) - self->ctx = SSL_CTX_new(SSLv3_method()); /* Set up context */ - else if (proto_version == PY_SSL_VERSION_SSL2) - self->ctx = SSL_CTX_new(SSLv2_method()); /* Set up context */ - else if (proto_version == PY_SSL_VERSION_SSL23) - self->ctx = SSL_CTX_new(SSLv23_method()); /* Set up context */ - PySSL_END_ALLOW_THREADS - - if (self->ctx == NULL) { - errstr = ERRSTR("Invalid SSL protocol variant specified."); - goto fail; - } - - if (ciphers != NULL) { - ret = SSL_CTX_set_cipher_list(self->ctx, ciphers); - if (ret == 0) { - errstr = ERRSTR("No cipher can be selected."); - goto fail; - } - } - - if (certreq != PY_SSL_CERT_NONE) { - if (cacerts_file == NULL) { - errstr = ERRSTR("No root certificates specified for " - "verification of other-side certificates."); - goto fail; - } else { - PySSL_BEGIN_ALLOW_THREADS - ret = SSL_CTX_load_verify_locations(self->ctx, - cacerts_file, - NULL); - PySSL_END_ALLOW_THREADS - if (ret != 1) { - _setSSLError(NULL, 0, __FILE__, __LINE__); - goto fail; - } - } - } - if (key_file) { - PySSL_BEGIN_ALLOW_THREADS - ret = SSL_CTX_use_PrivateKey_file(self->ctx, key_file, - SSL_FILETYPE_PEM); - PySSL_END_ALLOW_THREADS - if (ret != 1) { - _setSSLError(NULL, ret, __FILE__, __LINE__); - goto fail; - } - - PySSL_BEGIN_ALLOW_THREADS - ret = SSL_CTX_use_certificate_chain_file(self->ctx, - cert_file); - PySSL_END_ALLOW_THREADS - if (ret != 1) { - /* - fprintf(stderr, "ret is %d, errcode is %lu, %lu, with file \"%s\"\n", - ret, ERR_peek_error(), ERR_peek_last_error(), cert_file); - */ - if (ERR_peek_last_error() != 0) { - _setSSLError(NULL, ret, __FILE__, __LINE__); - goto fail; - } - } - } - - /* ssl compatibility */ - SSL_CTX_set_options(self->ctx, SSL_OP_ALL); - - verification_mode = SSL_VERIFY_NONE; - if (certreq == PY_SSL_CERT_OPTIONAL) - verification_mode = SSL_VERIFY_PEER; - else if (certreq == PY_SSL_CERT_REQUIRED) - verification_mode = (SSL_VERIFY_PEER | - SSL_VERIFY_FAIL_IF_NO_PEER_CERT); - SSL_CTX_set_verify(self->ctx, verification_mode, - NULL); /* set verify lvl */ - PySSL_BEGIN_ALLOW_THREADS - self->ssl = SSL_new(self->ctx); /* New ssl struct */ + self->ssl = SSL_new(ctx); PySSL_END_ALLOW_THREADS - SSL_set_fd(self->ssl, Sock->sock_fd); /* Set the socket for SSL */ + SSL_set_fd(self->ssl, sock->sock_fd); #ifdef SSL_MODE_AUTO_RETRY SSL_set_mode(self->ssl, SSL_MODE_AUTO_RETRY); #endif @@ -385,8 +296,7 @@ /* If the socket is in non-blocking mode or timeout mode, set the BIO * to non-blocking mode (blocking is the default) */ - if (Sock->sock_timeout >= 0.0) { - /* Set both the read and write BIO's to non-blocking mode */ + if (sock->sock_timeout >= 0.0) { BIO_set_nbio(SSL_get_rbio(self->ssl), 1); BIO_set_nbio(SSL_get_wbio(self->ssl), 1); } @@ -398,57 +308,13 @@ SSL_set_accept_state(self->ssl); PySSL_END_ALLOW_THREADS - self->Socket = PyWeakref_NewRef((PyObject *) Sock, Py_None); + self->Socket = PyWeakref_NewRef((PyObject *) sock, NULL); return self; - fail: - if (errstr) - PyErr_SetString(PySSLErrorObject, errstr); - Py_DECREF(self); - return NULL; } -static PyObject * -PySSL_sslwrap(PyObject *self, PyObject *args) -{ - PySocketSockObject *Sock; - int server_side = 0; - int verification_mode = PY_SSL_CERT_NONE; - int protocol = PY_SSL_VERSION_SSL23; - char *key_file = NULL; - char *cert_file = NULL; - char *cacerts_file = NULL; - char *ciphers = NULL; - - if (!PyArg_ParseTuple(args, "O!i|zziizz:sslwrap", - PySocketModule.Sock_Type, - &Sock, - &server_side, - &key_file, &cert_file, - &verification_mode, &protocol, - &cacerts_file, &ciphers)) - return NULL; - - /* - fprintf(stderr, - "server_side is %d, keyfile %p, certfile %p, verify_mode %d, " - "protocol %d, certs %p\n", - server_side, key_file, cert_file, verification_mode, - protocol, cacerts_file); - */ - - return (PyObject *) newPySSLObject(Sock, key_file, cert_file, - server_side, verification_mode, - protocol, cacerts_file, - ciphers); -} - -PyDoc_STRVAR(ssl_doc, -"sslwrap(socket, server_side, [keyfile, certfile, certs_mode, protocol,\n" -" cacertsfile, ciphers]) -> sslobject"); - /* SSL object methods */ -static PyObject *PySSL_SSLdo_handshake(PySSLObject *self) +static PyObject *PySSL_SSLdo_handshake(PySSLSocket *self) { int ret; int err; @@ -948,13 +814,13 @@ PySSL_test_decode_certificate (PyObject *mod, PyObject *args) { PyObject *retval = NULL; - char *filename = NULL; + PyObject *filename; X509 *x=NULL; BIO *cert; int verbose = 1; - if (!PyArg_ParseTuple(args, "s|i:test_decode_certificate", - &filename, &verbose)) + if (!PyArg_ParseTuple(args, "O&|i:test_decode_certificate", + PyUnicode_FSConverter, &filename, &verbose)) return NULL; if ((cert=BIO_new(BIO_s_file())) == NULL) { @@ -963,7 +829,7 @@ goto fail0; } - if (BIO_read_filename(cert,filename) <= 0) { + if (BIO_read_filename(cert, PyBytes_AsString(filename)) <= 0) { PyErr_SetString(PySSLErrorObject, "Can't open file"); goto fail0; @@ -979,14 +845,14 @@ retval = _decode_certificate(x, verbose); fail0: - + Py_DECREF(filename); if (cert != NULL) BIO_free(cert); return retval; } static PyObject * -PySSL_peercert(PySSLObject *self, PyObject *args) +PySSL_peercert(PySSLSocket *self, PyObject *args) { PyObject *retval = NULL; int len; @@ -1017,8 +883,7 @@ return retval; } else { - - verification = SSL_CTX_get_verify_mode(self->ctx); + verification = SSL_CTX_get_verify_mode(SSL_get_SSL_CTX(self->ssl)); if ((verification & SSL_VERIFY_PEER) == 0) return PyDict_New(); else @@ -1038,7 +903,7 @@ peer certificate, or None if no certificate was provided. This will\n\ return the certificate even if it wasn't validated."); -static PyObject *PySSL_cipher (PySSLObject *self) { +static PyObject *PySSL_cipher (PySSLSocket *self) { PyObject *retval, *v; SSL_CIPHER *current; @@ -1084,14 +949,12 @@ return NULL; } -static void PySSL_dealloc(PySSLObject *self) +static void PySSL_dealloc(PySSLSocket *self) { if (self->peer_cert) /* Possible not to have one? */ X509_free (self->peer_cert); if (self->ssl) SSL_free(self->ssl); - if (self->ctx) - SSL_CTX_free(self->ctx); Py_XDECREF(self->Socket); PyObject_Del(self); } @@ -1166,7 +1029,7 @@ return rc == 0 ? SOCKET_HAS_TIMED_OUT : SOCKET_OPERATION_OK; } -static PyObject *PySSL_SSLwrite(PySSLObject *self, PyObject *args) +static PyObject *PySSL_SSLwrite(PySSLSocket *self, PyObject *args) { Py_buffer buf; int len; @@ -1250,7 +1113,7 @@ Writes the string s into the SSL object. Returns the number\n\ of bytes written."); -static PyObject *PySSL_SSLpending(PySSLObject *self) +static PyObject *PySSL_SSLpending(PySSLSocket *self) { int count = 0; @@ -1269,7 +1132,7 @@ Returns the number of already decrypted bytes available for read,\n\ pending on the connection.\n"); -static PyObject *PySSL_SSLread(PySSLObject *self, PyObject *args) +static PyObject *PySSL_SSLread(PySSLSocket *self, PyObject *args) { PyObject *dest = NULL; Py_buffer buf; @@ -1392,7 +1255,7 @@ \n\ Read up to len bytes from the SSL socket."); -static PyObject *PySSL_SSLshutdown(PySSLObject *self) +static PyObject *PySSL_SSLshutdown(PySSLSocket *self) { int err, ssl_err, sockstate, nonblocking; int zeros = 0; @@ -1497,10 +1360,10 @@ {NULL, NULL} }; -static PyTypeObject PySSL_Type = { +static PyTypeObject PySSLSocket_Type = { PyVarObject_HEAD_INIT(NULL, 0) - "ssl.SSLContext", /*tp_name*/ - sizeof(PySSLObject), /*tp_basicsize*/ + "_ssl._SSLSocket", /*tp_name*/ + sizeof(PySSLSocket), /*tp_basicsize*/ 0, /*tp_itemsize*/ /* methods */ (destructor)PySSL_dealloc, /*tp_dealloc*/ @@ -1529,6 +1392,310 @@ PySSLMethods, /*tp_methods*/ }; + +/* + * _SSLContext objects + */ + +static PyObject * +context_new(PyTypeObject *type, PyObject *args, PyObject *kwds) +{ + char *kwlist[] = {"protocol", NULL}; + PySSLContext *self; + int proto_version = PY_SSL_VERSION_SSL23; + SSL_CTX *ctx = NULL; + + if (!PyArg_ParseTupleAndKeywords( + args, kwds, "i:_SSLContext", kwlist, + &proto_version)) + return NULL; + + PySSL_BEGIN_ALLOW_THREADS + if (proto_version == PY_SSL_VERSION_TLS1) + ctx = SSL_CTX_new(TLSv1_method()); + else if (proto_version == PY_SSL_VERSION_SSL3) + ctx = SSL_CTX_new(SSLv3_method()); + else if (proto_version == PY_SSL_VERSION_SSL2) + ctx = SSL_CTX_new(SSLv2_method()); + else if (proto_version == PY_SSL_VERSION_SSL23) + ctx = SSL_CTX_new(SSLv23_method()); + else + proto_version = -1; + PySSL_END_ALLOW_THREADS + + if (proto_version == -1) { + PyErr_SetString(PyExc_ValueError, + "invalid protocol version"); + return NULL; + } + if (ctx == NULL) { + PyErr_SetString(PySSLErrorObject, + "failed to allocate SSL context"); + return NULL; + } + + assert(type != NULL && type->tp_alloc != NULL); + self = (PySSLContext *) type->tp_alloc(type, 0); + if (self == NULL) { + SSL_CTX_free(ctx); + return NULL; + } + self->ctx = ctx; + /* Defaults */ + SSL_CTX_set_verify(self->ctx, SSL_VERIFY_NONE, NULL); + SSL_CTX_set_options(self->ctx, SSL_OP_ALL); + + return (PyObject *)self; +} + +static void +context_dealloc(PySSLContext *self) +{ + SSL_CTX_free(self->ctx); + Py_TYPE(self)->tp_free(self); +} + +static PyObject * +set_ciphers(PySSLContext *self, PyObject *args) +{ + int ret; + const char *cipherlist; + + if (!PyArg_ParseTuple(args, "s:set_ciphers", &cipherlist)) + return NULL; + ret = SSL_CTX_set_cipher_list(self->ctx, cipherlist); + if (ret == 0) { + /* Clearing the error queue is necessary on some OpenSSL versions, + otherwise the error will be reported again when another SSL call + is done. */ + ERR_clear_error(); + PyErr_SetString(PySSLErrorObject, + "No cipher can be selected."); + return NULL; + } + Py_RETURN_NONE; +} + +static PyObject * +get_verify_mode(PySSLContext *self, void *c) +{ + switch (SSL_CTX_get_verify_mode(self->ctx)) { + case SSL_VERIFY_NONE: + return PyLong_FromLong(PY_SSL_CERT_NONE); + case SSL_VERIFY_PEER: + return PyLong_FromLong(PY_SSL_CERT_OPTIONAL); + case SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT: + return PyLong_FromLong(PY_SSL_CERT_REQUIRED); + } + PyErr_SetString(PySSLErrorObject, + "invalid return value from SSL_CTX_get_verify_mode"); + return NULL; +} + +static int +set_verify_mode(PySSLContext *self, PyObject *arg, void *c) +{ + int n, mode; + if (!PyArg_Parse(arg, "i", &n)) + return -1; + if (n == PY_SSL_CERT_NONE) + mode = SSL_VERIFY_NONE; + else if (n == PY_SSL_CERT_OPTIONAL) + mode = SSL_VERIFY_PEER; + else if (n == PY_SSL_CERT_REQUIRED) + mode = SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT; + else { + PyErr_SetString(PyExc_ValueError, + "invalid value for verify_mode"); + return -1; + } + SSL_CTX_set_verify(self->ctx, mode, NULL); + return 0; +} + +static PyObject * +load_cert_chain(PySSLContext *self, PyObject *args, PyObject *kwds) +{ + char *kwlist[] = {"certfile", "keyfile", NULL}; + PyObject *certfile, *keyfile = NULL; + PyObject *certfile_bytes = NULL, *keyfile_bytes = NULL; + int r; + + if (!PyArg_ParseTupleAndKeywords(args, kwds, + "O|O:load_cert_chain", kwlist, + &certfile, &keyfile)) + return NULL; + if (keyfile == Py_None) + keyfile = NULL; + if (!PyUnicode_FSConverter(certfile, &certfile_bytes)) { + PyErr_SetString(PyExc_TypeError, + "certfile should be a valid filesystem path"); + return NULL; + } + if (keyfile && !PyUnicode_FSConverter(keyfile, &keyfile_bytes)) { + PyErr_SetString(PyExc_TypeError, + "keyfile should be a valid filesystem path"); + goto error; + } + PySSL_BEGIN_ALLOW_THREADS + r = SSL_CTX_use_certificate_chain_file(self->ctx, + PyBytes_AS_STRING(certfile_bytes)); + PySSL_END_ALLOW_THREADS + if (r != 1) { + _setSSLError(NULL, 0, __FILE__, __LINE__); + goto error; + } + PySSL_BEGIN_ALLOW_THREADS + r = SSL_CTX_use_RSAPrivateKey_file(self->ctx, + PyBytes_AS_STRING(keyfile ? keyfile_bytes : certfile_bytes), + SSL_FILETYPE_PEM); + PySSL_END_ALLOW_THREADS + Py_XDECREF(keyfile_bytes); + Py_XDECREF(certfile_bytes); + if (r != 1) { + _setSSLError(NULL, 0, __FILE__, __LINE__); + return NULL; + } + PySSL_BEGIN_ALLOW_THREADS + r = SSL_CTX_check_private_key(self->ctx); + PySSL_END_ALLOW_THREADS + if (r != 1) { + _setSSLError(NULL, 0, __FILE__, __LINE__); + return NULL; + } + Py_RETURN_NONE; + +error: + Py_XDECREF(keyfile_bytes); + Py_XDECREF(certfile_bytes); + return NULL; +} + +static PyObject * +load_verify_locations(PySSLContext *self, PyObject *args, PyObject *kwds) +{ + char *kwlist[] = {"cafile", "capath", NULL}; + PyObject *cafile = NULL, *capath = NULL; + PyObject *cafile_bytes = NULL, *capath_bytes = NULL; + const char *cafile_buf = NULL, *capath_buf = NULL; + int r; + + if (!PyArg_ParseTupleAndKeywords(args, kwds, + "|OO:load_verify_locations", kwlist, + &cafile, &capath)) + return NULL; + if (cafile == Py_None) + cafile = NULL; + if (capath == Py_None) + capath = NULL; + if (cafile == NULL && capath == NULL) { + PyErr_SetString(PyExc_TypeError, + "cafile and capath cannot be both omitted"); + return NULL; + } + if (cafile && !PyUnicode_FSConverter(cafile, &cafile_bytes)) { + PyErr_SetString(PyExc_TypeError, + "cafile should be a valid filesystem path"); + return NULL; + } + if (capath && !PyUnicode_FSConverter(capath, &capath_bytes)) { + Py_DECREF(cafile_bytes); + PyErr_SetString(PyExc_TypeError, + "capath should be a valid filesystem path"); + return NULL; + } + if (cafile) + cafile_buf = PyBytes_AS_STRING(cafile_bytes); + if (capath) + capath_buf = PyBytes_AS_STRING(capath_bytes); + PySSL_BEGIN_ALLOW_THREADS + r = SSL_CTX_load_verify_locations(self->ctx, cafile_buf, capath_buf); + PySSL_END_ALLOW_THREADS + Py_XDECREF(cafile_bytes); + Py_XDECREF(capath_bytes); + if (r != 1) { + _setSSLError(NULL, 0, __FILE__, __LINE__); + return NULL; + } + Py_RETURN_NONE; +} + +static PyObject * +context_wrap_socket(PySSLContext *self, PyObject *args, PyObject *kwds) +{ + char *kwlist[] = {"sock", "server_side", NULL}; + PySocketSockObject *sock; + int server_side = 0; + + if (!PyArg_ParseTupleAndKeywords(args, kwds, "O!i:_wrap_socket", kwlist, + PySocketModule.Sock_Type, + &sock, &server_side)) + return NULL; + + return (PyObject *) newPySSLSocket(self->ctx, sock, server_side); +} + +static PyGetSetDef context_getsetlist[] = { + {"verify_mode", (getter) get_verify_mode, + (setter) set_verify_mode, NULL}, + {NULL}, /* sentinel */ +}; + +static struct PyMethodDef context_methods[] = { + {"_wrap_socket", (PyCFunction) context_wrap_socket, + METH_VARARGS | METH_KEYWORDS, NULL}, + {"set_ciphers", (PyCFunction) set_ciphers, + METH_VARARGS, NULL}, + {"load_cert_chain", (PyCFunction) load_cert_chain, + METH_VARARGS | METH_KEYWORDS, NULL}, + {"load_verify_locations", (PyCFunction) load_verify_locations, + METH_VARARGS | METH_KEYWORDS, NULL}, + {NULL, NULL} /* sentinel */ +}; + +static PyTypeObject PySSLContext_Type = { + PyVarObject_HEAD_INIT(NULL, 0) + "_ssl._SSLContext", /*tp_name*/ + sizeof(PySSLContext), /*tp_basicsize*/ + 0, /*tp_itemsize*/ + (destructor)context_dealloc, /*tp_dealloc*/ + 0, /*tp_print*/ + 0, /*tp_getattr*/ + 0, /*tp_setattr*/ + 0, /*tp_reserved*/ + 0, /*tp_repr*/ + 0, /*tp_as_number*/ + 0, /*tp_as_sequence*/ + 0, /*tp_as_mapping*/ + 0, /*tp_hash*/ + 0, /*tp_call*/ + 0, /*tp_str*/ + 0, /*tp_getattro*/ + 0, /*tp_setattro*/ + 0, /*tp_as_buffer*/ + Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /*tp_flags*/ + 0, /*tp_doc*/ + 0, /*tp_traverse*/ + 0, /*tp_clear*/ + 0, /*tp_richcompare*/ + 0, /*tp_weaklistoffset*/ + 0, /*tp_iter*/ + 0, /*tp_iternext*/ + context_methods, /*tp_methods*/ + 0, /*tp_members*/ + context_getsetlist, /*tp_getset*/ + 0, /*tp_base*/ + 0, /*tp_dict*/ + 0, /*tp_descr_get*/ + 0, /*tp_descr_set*/ + 0, /*tp_dictoffset*/ + 0, /*tp_init*/ + 0, /*tp_alloc*/ + context_new, /*tp_new*/ +}; + + + #ifdef HAVE_OPENSSL_RAND /* helper routines for seeding the SSL PRNG */ @@ -1566,15 +1733,17 @@ using the ssl() function."); static PyObject * -PySSL_RAND_egd(PyObject *self, PyObject *arg) +PySSL_RAND_egd(PyObject *self, PyObject *args) { + PyObject *path; int bytes; - if (!PyUnicode_Check(arg)) - return PyErr_Format(PyExc_TypeError, - "RAND_egd() expected string, found %s", - Py_TYPE(arg)->tp_name); - bytes = RAND_egd(_PyUnicode_AsString(arg)); + if (!PyArg_ParseTuple(args, "O&|i:RAND_egd", + PyUnicode_FSConverter, &path)) + return NULL; + + bytes = RAND_egd(PyBytes_AsString(path)); + Py_DECREF(path); if (bytes == -1) { PyErr_SetString(PySSLErrorObject, "EGD connection failed or EGD did not return " @@ -1598,14 +1767,12 @@ /* List of functions exported by this module. */ static PyMethodDef PySSL_methods[] = { - {"sslwrap", PySSL_sslwrap, - METH_VARARGS, ssl_doc}, {"_test_decode_cert", PySSL_test_decode_certificate, METH_VARARGS}, #ifdef HAVE_OPENSSL_RAND {"RAND_add", PySSL_RAND_add, METH_VARARGS, PySSL_RAND_add_doc}, - {"RAND_egd", PySSL_RAND_egd, METH_O, + {"RAND_egd", PySSL_RAND_egd, METH_VARARGS, PySSL_RAND_egd_doc}, {"RAND_status", (PyCFunction)PySSL_RAND_status, METH_NOARGS, PySSL_RAND_status_doc}, @@ -1708,7 +1875,9 @@ unsigned int major, minor, fix, patch, status; PySocketModule_APIObject *socket_api; - if (PyType_Ready(&PySSL_Type) < 0) + if (PyType_Ready(&PySSLContext_Type) < 0) + return NULL; + if (PyType_Ready(&PySSLSocket_Type) < 0) return NULL; m = PyModule_Create(&_sslmodule); @@ -1741,8 +1910,11 @@ return NULL; if (PyDict_SetItemString(d, "SSLError", PySSLErrorObject) != 0) return NULL; - if (PyDict_SetItemString(d, "SSLType", - (PyObject *)&PySSL_Type) != 0) + if (PyDict_SetItemString(d, "_SSLContext", + (PyObject *)&PySSLContext_Type) != 0) + return NULL; + if (PyDict_SetItemString(d, "_SSLSocket", + (PyObject *)&PySSLSocket_Type) != 0) return NULL; PyModule_AddIntConstant(m, "SSL_ERROR_ZERO_RETURN", PY_SSL_ERROR_ZERO_RETURN); Modified: python/branches/py3k-cdecimal/Modules/_testcapimodule.c ============================================================================== --- python/branches/py3k-cdecimal/Modules/_testcapimodule.c (original) +++ python/branches/py3k-cdecimal/Modules/_testcapimodule.c Wed May 19 17:30:16 2010 @@ -2011,7 +2011,11 @@ crash_no_current_thread(PyObject *self) { Py_BEGIN_ALLOW_THREADS - PyErr_SetString(PyExc_SystemError, "bork bork bork"); + /* Using PyThreadState_Get() directly allows the test to pass in + !pydebug mode. However, the test only actually tests anything + in pydebug mode, since that's where the infinite loop was in + the first place. */ + PyThreadState_Get(); Py_END_ALLOW_THREADS return NULL; } Modified: python/branches/py3k-cdecimal/Modules/main.c ============================================================================== --- python/branches/py3k-cdecimal/Modules/main.c (original) +++ python/branches/py3k-cdecimal/Modules/main.c Wed May 19 17:30:16 2010 @@ -563,18 +563,22 @@ } if (command) { + char *commandStr; PyObject *commandObj = PyUnicode_FromWideChar( command, wcslen(command)); free(command); - if (commandObj != NULL) { - sts = PyRun_SimpleStringFlags( - _PyUnicode_AsString(commandObj), &cf) != 0; + if (commandObj != NULL) + commandStr = _PyUnicode_AsString(commandObj); + else + commandStr = NULL; + if (commandStr != NULL) { + sts = PyRun_SimpleStringFlags(commandStr, &cf) != 0; + Py_DECREF(commandObj); } else { PyErr_Print(); sts = 1; } - Py_DECREF(commandObj); } else if (module) { sts = RunModule(module, 1); } Modified: python/branches/py3k-cdecimal/Objects/moduleobject.c ============================================================================== --- python/branches/py3k-cdecimal/Objects/moduleobject.c (original) +++ python/branches/py3k-cdecimal/Objects/moduleobject.c Wed May 19 17:30:16 2010 @@ -263,10 +263,15 @@ pos = 0; while (PyDict_Next(d, &pos, &key, &value)) { if (value != Py_None && PyUnicode_Check(key)) { - const char *s = _PyUnicode_AsString(key); - if (s[0] == '_' && s[1] != '_') { - if (Py_VerboseFlag > 1) - PySys_WriteStderr("# clear[1] %s\n", s); + Py_UNICODE *u = PyUnicode_AS_UNICODE(key); + if (u[0] == '_' && u[1] != '_') { + if (Py_VerboseFlag > 1) { + const char *s = _PyUnicode_AsString(key); + if (s != NULL) + PySys_WriteStderr("# clear[1] %s\n", s); + else + PyErr_Clear(); + } PyDict_SetItem(d, key, Py_None); } } @@ -276,10 +281,17 @@ pos = 0; while (PyDict_Next(d, &pos, &key, &value)) { if (value != Py_None && PyUnicode_Check(key)) { - const char *s = _PyUnicode_AsString(key); - if (s[0] != '_' || strcmp(s, "__builtins__") != 0) { - if (Py_VerboseFlag > 1) - PySys_WriteStderr("# clear[2] %s\n", s); + Py_UNICODE *u = PyUnicode_AS_UNICODE(key); + if (u[0] != '_' + || PyUnicode_CompareWithASCIIString(key, "__builtins__") != 0) + { + if (Py_VerboseFlag > 1) { + const char *s = _PyUnicode_AsString(key); + if (s != NULL) + PySys_WriteStderr("# clear[2] %s\n", s); + else + PyErr_Clear(); + } PyDict_SetItem(d, key, Py_None); } } Modified: python/branches/py3k-cdecimal/Objects/object.c ============================================================================== --- python/branches/py3k-cdecimal/Objects/object.c (original) +++ python/branches/py3k-cdecimal/Objects/object.c Wed May 19 17:30:16 2010 @@ -303,12 +303,15 @@ } else if (PyUnicode_Check(s)) { PyObject *t; - t = _PyUnicode_AsDefaultEncodedString(s, NULL); + t = PyUnicode_EncodeUTF8(PyUnicode_AS_UNICODE(s), + PyUnicode_GET_SIZE(s), + "backslashreplace"); if (t == NULL) ret = 0; else { fwrite(PyBytes_AS_STRING(t), 1, PyBytes_GET_SIZE(t), fp); + Py_DECREF(t); } } else { Modified: python/branches/py3k-cdecimal/Objects/typeobject.c ============================================================================== --- python/branches/py3k-cdecimal/Objects/typeobject.c (original) +++ python/branches/py3k-cdecimal/Objects/typeobject.c Wed May 19 17:30:16 2010 @@ -1347,8 +1347,14 @@ i = 0; while (PyDict_Next(set, &i, &k, &v) && (size_t)off < sizeof(buf)) { PyObject *name = class_name(k); - off += PyOS_snprintf(buf + off, sizeof(buf) - off, " %s", - name ? _PyUnicode_AsString(name) : "?"); + char *name_str; + if (name != NULL) { + name_str = _PyUnicode_AsString(name); + if (name_str == NULL) + name_str = "?"; + } else + name_str = "?"; + off += PyOS_snprintf(buf + off, sizeof(buf) - off, " %s", name_str); Py_XDECREF(name); if (--n && (size_t)(off+1) < sizeof(buf)) { buf[off++] = ','; @@ -2220,6 +2226,10 @@ for (i = 0; i < nslots; i++, mp++) { mp->name = _PyUnicode_AsString( PyTuple_GET_ITEM(slots, i)); + if (mp->name == NULL) { + Py_DECREF(type); + return NULL; + } mp->type = T_OBJECT_EX; mp->offset = slotoffset; Modified: python/branches/py3k-cdecimal/Parser/asdl.py ============================================================================== --- python/branches/py3k-cdecimal/Parser/asdl.py (original) +++ python/branches/py3k-cdecimal/Parser/asdl.py Wed May 19 17:30:16 2010 @@ -1,7 +1,7 @@ """An implementation of the Zephyr Abstract Syntax Definition Language. See http://asdl.sourceforge.net/ and -http://www.cs.princeton.edu/~danwang/Papers/dsl97/dsl97-abstract.html. +http://www.cs.princeton.edu/research/techreps/TR-554-97 Only supports top level module decl, not view. I'm guessing that view is intended to support the browser and I'm not interested in the Modified: python/branches/py3k-cdecimal/Parser/printgrammar.c ============================================================================== --- python/branches/py3k-cdecimal/Parser/printgrammar.c (original) +++ python/branches/py3k-cdecimal/Parser/printgrammar.c Wed May 19 17:30:16 2010 @@ -20,10 +20,10 @@ printdfas(g, fp); printlabels(g, fp); fprintf(fp, "grammar _PyParser_Grammar = {\n"); - fprintf(fp, "\t%d,\n", g->g_ndfas); - fprintf(fp, "\tdfas,\n"); - fprintf(fp, "\t{%d, labels},\n", g->g_ll.ll_nlabels); - fprintf(fp, "\t%d\n", g->g_start); + fprintf(fp, " %d,\n", g->g_ndfas); + fprintf(fp, " dfas,\n"); + fprintf(fp, " {%d, labels},\n", g->g_ll.ll_nlabels); + fprintf(fp, " %d\n", g->g_start); fprintf(fp, "};\n"); } @@ -53,7 +53,7 @@ i, j, s->s_narcs); a = s->s_arc; for (k = 0; k < s->s_narcs; k++, a++) - fprintf(fp, "\t{%d, %d},\n", a->a_lbl, a->a_arrow); + fprintf(fp, " {%d, %d},\n", a->a_lbl, a->a_arrow); fprintf(fp, "};\n"); } } @@ -72,7 +72,7 @@ i, d->d_nstates); s = d->d_state; for (j = 0; j < d->d_nstates; j++, s++) - fprintf(fp, "\t{%d, arcs_%d_%d},\n", + fprintf(fp, " {%d, arcs_%d_%d},\n", s->s_narcs, i, j); fprintf(fp, "};\n"); } @@ -88,9 +88,9 @@ fprintf(fp, "static dfa dfas[%d] = {\n", g->g_ndfas); d = g->g_dfa; for (i = 0; i < g->g_ndfas; i++, d++) { - fprintf(fp, "\t{%d, \"%s\", %d, %d, states_%d,\n", + fprintf(fp, " {%d, \"%s\", %d, %d, states_%d,\n", d->d_type, d->d_name, d->d_initial, d->d_nstates, i); - fprintf(fp, "\t \""); + fprintf(fp, " \""); for (j = 0; j < NBYTES(g->g_ll.ll_nlabels); j++) fprintf(fp, "\\%03o", d->d_first[j] & 0xff); fprintf(fp, "\"},\n"); @@ -108,9 +108,9 @@ l = g->g_ll.ll_label; for (i = g->g_ll.ll_nlabels; --i >= 0; l++) { if (l->lb_str == NULL) - fprintf(fp, "\t{%d, 0},\n", l->lb_type); + fprintf(fp, " {%d, 0},\n", l->lb_type); else - fprintf(fp, "\t{%d, \"%s\"},\n", + fprintf(fp, " {%d, \"%s\"},\n", l->lb_type, l->lb_str); } fprintf(fp, "};\n"); Modified: python/branches/py3k-cdecimal/Python/bltinmodule.c ============================================================================== --- python/branches/py3k-cdecimal/Python/bltinmodule.c (original) +++ python/branches/py3k-cdecimal/Python/bltinmodule.c Wed May 19 17:30:16 2010 @@ -1610,6 +1610,7 @@ char *prompt; char *s; PyObject *stdin_encoding; + char *stdin_encoding_str; PyObject *result; stdin_encoding = PyObject_GetAttrString(fin, "encoding"); @@ -1617,6 +1618,11 @@ /* stdin is a text stream, so it must have an encoding. */ return NULL; + stdin_encoding_str = _PyUnicode_AsString(stdin_encoding); + if (stdin_encoding_str == NULL) { + Py_DECREF(stdin_encoding); + return NULL; + } tmp = PyObject_CallMethod(fout, "flush", ""); if (tmp == NULL) PyErr_Clear(); @@ -1625,12 +1631,18 @@ if (promptarg != NULL) { PyObject *stringpo; PyObject *stdout_encoding; - stdout_encoding = PyObject_GetAttrString(fout, - "encoding"); + char *stdout_encoding_str; + stdout_encoding = PyObject_GetAttrString(fout, "encoding"); if (stdout_encoding == NULL) { Py_DECREF(stdin_encoding); return NULL; } + stdout_encoding_str = _PyUnicode_AsString(stdout_encoding); + if (stdout_encoding_str == NULL) { + Py_DECREF(stdin_encoding); + Py_DECREF(stdout_encoding); + return NULL; + } stringpo = PyObject_Str(promptarg); if (stringpo == NULL) { Py_DECREF(stdin_encoding); @@ -1638,7 +1650,7 @@ return NULL; } po = PyUnicode_AsEncodedString(stringpo, - _PyUnicode_AsString(stdout_encoding), NULL); + stdout_encoding_str, NULL); Py_DECREF(stdout_encoding); Py_DECREF(stringpo); if (po == NULL) { @@ -1676,10 +1688,7 @@ result = NULL; } else { - result = PyUnicode_Decode - (s, len-1, - _PyUnicode_AsString(stdin_encoding), - NULL); + result = PyUnicode_Decode(s, len-1, stdin_encoding_str, NULL); } } Py_DECREF(stdin_encoding); Modified: python/branches/py3k-cdecimal/Python/getargs.c ============================================================================== --- python/branches/py3k-cdecimal/Python/getargs.c (original) +++ python/branches/py3k-cdecimal/Python/getargs.c Wed May 19 17:30:16 2010 @@ -1755,18 +1755,21 @@ "keywords must be strings"); return cleanreturn(0, freelist); } + /* check that _PyUnicode_AsString() result is not NULL */ ks = _PyUnicode_AsString(key); - for (i = 0; i < len; i++) { - if (!strcmp(ks, kwlist[i])) { - match = 1; - break; + if (ks != NULL) { + for (i = 0; i < len; i++) { + if (!strcmp(ks, kwlist[i])) { + match = 1; + break; + } } } if (!match) { PyErr_Format(PyExc_TypeError, - "'%s' is an invalid keyword " + "'%U' is an invalid keyword " "argument for this function", - ks); + key); return cleanreturn(0, freelist); } } Modified: python/branches/py3k-cdecimal/Python/graminit.c ============================================================================== --- python/branches/py3k-cdecimal/Python/graminit.c (original) +++ python/branches/py3k-cdecimal/Python/graminit.c Wed May 19 17:30:16 2010 @@ -4,2077 +4,2077 @@ #include "grammar.h" PyAPI_DATA(grammar) _PyParser_Grammar; static arc arcs_0_0[3] = { - {2, 1}, - {3, 1}, - {4, 2}, + {2, 1}, + {3, 1}, + {4, 2}, }; static arc arcs_0_1[1] = { - {0, 1}, + {0, 1}, }; static arc arcs_0_2[1] = { - {2, 1}, + {2, 1}, }; static state states_0[3] = { - {3, arcs_0_0}, - {1, arcs_0_1}, - {1, arcs_0_2}, + {3, arcs_0_0}, + {1, arcs_0_1}, + {1, arcs_0_2}, }; static arc arcs_1_0[3] = { - {2, 0}, - {6, 0}, - {7, 1}, + {2, 0}, + {6, 0}, + {7, 1}, }; static arc arcs_1_1[1] = { - {0, 1}, + {0, 1}, }; static state states_1[2] = { - {3, arcs_1_0}, - {1, arcs_1_1}, + {3, arcs_1_0}, + {1, arcs_1_1}, }; static arc arcs_2_0[1] = { - {9, 1}, + {9, 1}, }; static arc arcs_2_1[2] = { - {2, 1}, - {7, 2}, + {2, 1}, + {7, 2}, }; static arc arcs_2_2[1] = { - {0, 2}, + {0, 2}, }; static state states_2[3] = { - {1, arcs_2_0}, - {2, arcs_2_1}, - {1, arcs_2_2}, + {1, arcs_2_0}, + {2, arcs_2_1}, + {1, arcs_2_2}, }; static arc arcs_3_0[1] = { - {11, 1}, + {11, 1}, }; static arc arcs_3_1[1] = { - {12, 2}, + {12, 2}, }; static arc arcs_3_2[2] = { - {13, 3}, - {2, 4}, + {13, 3}, + {2, 4}, }; static arc arcs_3_3[2] = { - {14, 5}, - {15, 6}, + {14, 5}, + {15, 6}, }; static arc arcs_3_4[1] = { - {0, 4}, + {0, 4}, }; static arc arcs_3_5[1] = { - {15, 6}, + {15, 6}, }; static arc arcs_3_6[1] = { - {2, 4}, + {2, 4}, }; static state states_3[7] = { - {1, arcs_3_0}, - {1, arcs_3_1}, - {2, arcs_3_2}, - {2, arcs_3_3}, - {1, arcs_3_4}, - {1, arcs_3_5}, - {1, arcs_3_6}, + {1, arcs_3_0}, + {1, arcs_3_1}, + {2, arcs_3_2}, + {2, arcs_3_3}, + {1, arcs_3_4}, + {1, arcs_3_5}, + {1, arcs_3_6}, }; static arc arcs_4_0[1] = { - {10, 1}, + {10, 1}, }; static arc arcs_4_1[2] = { - {10, 1}, - {0, 1}, + {10, 1}, + {0, 1}, }; static state states_4[2] = { - {1, arcs_4_0}, - {2, arcs_4_1}, + {1, arcs_4_0}, + {2, arcs_4_1}, }; static arc arcs_5_0[1] = { - {16, 1}, + {16, 1}, }; static arc arcs_5_1[2] = { - {18, 2}, - {19, 2}, + {18, 2}, + {19, 2}, }; static arc arcs_5_2[1] = { - {0, 2}, + {0, 2}, }; static state states_5[3] = { - {1, arcs_5_0}, - {2, arcs_5_1}, - {1, arcs_5_2}, + {1, arcs_5_0}, + {2, arcs_5_1}, + {1, arcs_5_2}, }; static arc arcs_6_0[1] = { - {20, 1}, + {20, 1}, }; static arc arcs_6_1[1] = { - {21, 2}, + {21, 2}, }; static arc arcs_6_2[1] = { - {22, 3}, + {22, 3}, }; static arc arcs_6_3[2] = { - {23, 4}, - {25, 5}, + {23, 4}, + {25, 5}, }; static arc arcs_6_4[1] = { - {24, 6}, + {24, 6}, }; static arc arcs_6_5[1] = { - {26, 7}, + {26, 7}, }; static arc arcs_6_6[1] = { - {25, 5}, + {25, 5}, }; static arc arcs_6_7[1] = { - {0, 7}, + {0, 7}, }; static state states_6[8] = { - {1, arcs_6_0}, - {1, arcs_6_1}, - {1, arcs_6_2}, - {2, arcs_6_3}, - {1, arcs_6_4}, - {1, arcs_6_5}, - {1, arcs_6_6}, - {1, arcs_6_7}, + {1, arcs_6_0}, + {1, arcs_6_1}, + {1, arcs_6_2}, + {2, arcs_6_3}, + {1, arcs_6_4}, + {1, arcs_6_5}, + {1, arcs_6_6}, + {1, arcs_6_7}, }; static arc arcs_7_0[1] = { - {13, 1}, + {13, 1}, }; static arc arcs_7_1[2] = { - {27, 2}, - {15, 3}, + {27, 2}, + {15, 3}, }; static arc arcs_7_2[1] = { - {15, 3}, + {15, 3}, }; static arc arcs_7_3[1] = { - {0, 3}, + {0, 3}, }; static state states_7[4] = { - {1, arcs_7_0}, - {2, arcs_7_1}, - {1, arcs_7_2}, - {1, arcs_7_3}, + {1, arcs_7_0}, + {2, arcs_7_1}, + {1, arcs_7_2}, + {1, arcs_7_3}, }; static arc arcs_8_0[3] = { - {28, 1}, - {31, 2}, - {32, 3}, + {28, 1}, + {31, 2}, + {32, 3}, }; static arc arcs_8_1[3] = { - {29, 4}, - {30, 5}, - {0, 1}, + {29, 4}, + {30, 5}, + {0, 1}, }; static arc arcs_8_2[3] = { - {28, 6}, - {30, 7}, - {0, 2}, + {28, 6}, + {30, 7}, + {0, 2}, }; static arc arcs_8_3[1] = { - {28, 8}, + {28, 8}, }; static arc arcs_8_4[1] = { - {24, 9}, + {24, 9}, }; static arc arcs_8_5[4] = { - {28, 1}, - {31, 2}, - {32, 3}, - {0, 5}, + {28, 1}, + {31, 2}, + {32, 3}, + {0, 5}, }; static arc arcs_8_6[2] = { - {30, 7}, - {0, 6}, + {30, 7}, + {0, 6}, }; static arc arcs_8_7[2] = { - {28, 10}, - {32, 3}, + {28, 10}, + {32, 3}, }; static arc arcs_8_8[1] = { - {0, 8}, + {0, 8}, }; static arc arcs_8_9[2] = { - {30, 5}, - {0, 9}, + {30, 5}, + {0, 9}, }; static arc arcs_8_10[3] = { - {30, 7}, - {29, 11}, - {0, 10}, + {30, 7}, + {29, 11}, + {0, 10}, }; static arc arcs_8_11[1] = { - {24, 6}, + {24, 6}, }; static state states_8[12] = { - {3, arcs_8_0}, - {3, arcs_8_1}, - {3, arcs_8_2}, - {1, arcs_8_3}, - {1, arcs_8_4}, - {4, arcs_8_5}, - {2, arcs_8_6}, - {2, arcs_8_7}, - {1, arcs_8_8}, - {2, arcs_8_9}, - {3, arcs_8_10}, - {1, arcs_8_11}, + {3, arcs_8_0}, + {3, arcs_8_1}, + {3, arcs_8_2}, + {1, arcs_8_3}, + {1, arcs_8_4}, + {4, arcs_8_5}, + {2, arcs_8_6}, + {2, arcs_8_7}, + {1, arcs_8_8}, + {2, arcs_8_9}, + {3, arcs_8_10}, + {1, arcs_8_11}, }; static arc arcs_9_0[1] = { - {21, 1}, + {21, 1}, }; static arc arcs_9_1[2] = { - {25, 2}, - {0, 1}, + {25, 2}, + {0, 1}, }; static arc arcs_9_2[1] = { - {24, 3}, + {24, 3}, }; static arc arcs_9_3[1] = { - {0, 3}, + {0, 3}, }; static state states_9[4] = { - {1, arcs_9_0}, - {2, arcs_9_1}, - {1, arcs_9_2}, - {1, arcs_9_3}, + {1, arcs_9_0}, + {2, arcs_9_1}, + {1, arcs_9_2}, + {1, arcs_9_3}, }; static arc arcs_10_0[3] = { - {34, 1}, - {31, 2}, - {32, 3}, + {34, 1}, + {31, 2}, + {32, 3}, }; static arc arcs_10_1[3] = { - {29, 4}, - {30, 5}, - {0, 1}, + {29, 4}, + {30, 5}, + {0, 1}, }; static arc arcs_10_2[3] = { - {34, 6}, - {30, 7}, - {0, 2}, + {34, 6}, + {30, 7}, + {0, 2}, }; static arc arcs_10_3[1] = { - {34, 8}, + {34, 8}, }; static arc arcs_10_4[1] = { - {24, 9}, + {24, 9}, }; static arc arcs_10_5[4] = { - {34, 1}, - {31, 2}, - {32, 3}, - {0, 5}, + {34, 1}, + {31, 2}, + {32, 3}, + {0, 5}, }; static arc arcs_10_6[2] = { - {30, 7}, - {0, 6}, + {30, 7}, + {0, 6}, }; static arc arcs_10_7[2] = { - {34, 10}, - {32, 3}, + {34, 10}, + {32, 3}, }; static arc arcs_10_8[1] = { - {0, 8}, + {0, 8}, }; static arc arcs_10_9[2] = { - {30, 5}, - {0, 9}, + {30, 5}, + {0, 9}, }; static arc arcs_10_10[3] = { - {30, 7}, - {29, 11}, - {0, 10}, + {30, 7}, + {29, 11}, + {0, 10}, }; static arc arcs_10_11[1] = { - {24, 6}, + {24, 6}, }; static state states_10[12] = { - {3, arcs_10_0}, - {3, arcs_10_1}, - {3, arcs_10_2}, - {1, arcs_10_3}, - {1, arcs_10_4}, - {4, arcs_10_5}, - {2, arcs_10_6}, - {2, arcs_10_7}, - {1, arcs_10_8}, - {2, arcs_10_9}, - {3, arcs_10_10}, - {1, arcs_10_11}, + {3, arcs_10_0}, + {3, arcs_10_1}, + {3, arcs_10_2}, + {1, arcs_10_3}, + {1, arcs_10_4}, + {4, arcs_10_5}, + {2, arcs_10_6}, + {2, arcs_10_7}, + {1, arcs_10_8}, + {2, arcs_10_9}, + {3, arcs_10_10}, + {1, arcs_10_11}, }; static arc arcs_11_0[1] = { - {21, 1}, + {21, 1}, }; static arc arcs_11_1[1] = { - {0, 1}, + {0, 1}, }; static state states_11[2] = { - {1, arcs_11_0}, - {1, arcs_11_1}, + {1, arcs_11_0}, + {1, arcs_11_1}, }; static arc arcs_12_0[2] = { - {3, 1}, - {4, 1}, + {3, 1}, + {4, 1}, }; static arc arcs_12_1[1] = { - {0, 1}, + {0, 1}, }; static state states_12[2] = { - {2, arcs_12_0}, - {1, arcs_12_1}, + {2, arcs_12_0}, + {1, arcs_12_1}, }; static arc arcs_13_0[1] = { - {35, 1}, + {35, 1}, }; static arc arcs_13_1[2] = { - {36, 2}, - {2, 3}, + {36, 2}, + {2, 3}, }; static arc arcs_13_2[2] = { - {35, 1}, - {2, 3}, + {35, 1}, + {2, 3}, }; static arc arcs_13_3[1] = { - {0, 3}, + {0, 3}, }; static state states_13[4] = { - {1, arcs_13_0}, - {2, arcs_13_1}, - {2, arcs_13_2}, - {1, arcs_13_3}, + {1, arcs_13_0}, + {2, arcs_13_1}, + {2, arcs_13_2}, + {1, arcs_13_3}, }; static arc arcs_14_0[8] = { - {37, 1}, - {38, 1}, - {39, 1}, - {40, 1}, - {41, 1}, - {42, 1}, - {43, 1}, - {44, 1}, + {37, 1}, + {38, 1}, + {39, 1}, + {40, 1}, + {41, 1}, + {42, 1}, + {43, 1}, + {44, 1}, }; static arc arcs_14_1[1] = { - {0, 1}, + {0, 1}, }; static state states_14[2] = { - {8, arcs_14_0}, - {1, arcs_14_1}, + {8, arcs_14_0}, + {1, arcs_14_1}, }; static arc arcs_15_0[1] = { - {45, 1}, + {45, 1}, }; static arc arcs_15_1[3] = { - {46, 2}, - {29, 3}, - {0, 1}, + {46, 2}, + {29, 3}, + {0, 1}, }; static arc arcs_15_2[2] = { - {47, 4}, - {9, 4}, + {47, 4}, + {9, 4}, }; static arc arcs_15_3[2] = { - {47, 5}, - {45, 5}, + {47, 5}, + {45, 5}, }; static arc arcs_15_4[1] = { - {0, 4}, + {0, 4}, }; static arc arcs_15_5[2] = { - {29, 3}, - {0, 5}, + {29, 3}, + {0, 5}, }; static state states_15[6] = { - {1, arcs_15_0}, - {3, arcs_15_1}, - {2, arcs_15_2}, - {2, arcs_15_3}, - {1, arcs_15_4}, - {2, arcs_15_5}, + {1, arcs_15_0}, + {3, arcs_15_1}, + {2, arcs_15_2}, + {2, arcs_15_3}, + {1, arcs_15_4}, + {2, arcs_15_5}, }; static arc arcs_16_0[2] = { - {24, 1}, - {48, 1}, + {24, 1}, + {48, 1}, }; static arc arcs_16_1[2] = { - {30, 2}, - {0, 1}, + {30, 2}, + {0, 1}, }; static arc arcs_16_2[3] = { - {24, 1}, - {48, 1}, - {0, 2}, + {24, 1}, + {48, 1}, + {0, 2}, }; static state states_16[3] = { - {2, arcs_16_0}, - {2, arcs_16_1}, - {3, arcs_16_2}, + {2, arcs_16_0}, + {2, arcs_16_1}, + {3, arcs_16_2}, }; static arc arcs_17_0[12] = { - {49, 1}, - {50, 1}, - {51, 1}, - {52, 1}, - {53, 1}, - {54, 1}, - {55, 1}, - {56, 1}, - {57, 1}, - {58, 1}, - {59, 1}, - {60, 1}, + {49, 1}, + {50, 1}, + {51, 1}, + {52, 1}, + {53, 1}, + {54, 1}, + {55, 1}, + {56, 1}, + {57, 1}, + {58, 1}, + {59, 1}, + {60, 1}, }; static arc arcs_17_1[1] = { - {0, 1}, + {0, 1}, }; static state states_17[2] = { - {12, arcs_17_0}, - {1, arcs_17_1}, + {12, arcs_17_0}, + {1, arcs_17_1}, }; static arc arcs_18_0[1] = { - {61, 1}, + {61, 1}, }; static arc arcs_18_1[1] = { - {62, 2}, + {62, 2}, }; static arc arcs_18_2[1] = { - {0, 2}, + {0, 2}, }; static state states_18[3] = { - {1, arcs_18_0}, - {1, arcs_18_1}, - {1, arcs_18_2}, + {1, arcs_18_0}, + {1, arcs_18_1}, + {1, arcs_18_2}, }; static arc arcs_19_0[1] = { - {63, 1}, + {63, 1}, }; static arc arcs_19_1[1] = { - {0, 1}, + {0, 1}, }; static state states_19[2] = { - {1, arcs_19_0}, - {1, arcs_19_1}, + {1, arcs_19_0}, + {1, arcs_19_1}, }; static arc arcs_20_0[5] = { - {64, 1}, - {65, 1}, - {66, 1}, - {67, 1}, - {68, 1}, + {64, 1}, + {65, 1}, + {66, 1}, + {67, 1}, + {68, 1}, }; static arc arcs_20_1[1] = { - {0, 1}, + {0, 1}, }; static state states_20[2] = { - {5, arcs_20_0}, - {1, arcs_20_1}, + {5, arcs_20_0}, + {1, arcs_20_1}, }; static arc arcs_21_0[1] = { - {69, 1}, + {69, 1}, }; static arc arcs_21_1[1] = { - {0, 1}, + {0, 1}, }; static state states_21[2] = { - {1, arcs_21_0}, - {1, arcs_21_1}, + {1, arcs_21_0}, + {1, arcs_21_1}, }; static arc arcs_22_0[1] = { - {70, 1}, + {70, 1}, }; static arc arcs_22_1[1] = { - {0, 1}, + {0, 1}, }; static state states_22[2] = { - {1, arcs_22_0}, - {1, arcs_22_1}, + {1, arcs_22_0}, + {1, arcs_22_1}, }; static arc arcs_23_0[1] = { - {71, 1}, + {71, 1}, }; static arc arcs_23_1[2] = { - {9, 2}, - {0, 1}, + {9, 2}, + {0, 1}, }; static arc arcs_23_2[1] = { - {0, 2}, + {0, 2}, }; static state states_23[3] = { - {1, arcs_23_0}, - {2, arcs_23_1}, - {1, arcs_23_2}, + {1, arcs_23_0}, + {2, arcs_23_1}, + {1, arcs_23_2}, }; static arc arcs_24_0[1] = { - {47, 1}, + {47, 1}, }; static arc arcs_24_1[1] = { - {0, 1}, + {0, 1}, }; static state states_24[2] = { - {1, arcs_24_0}, - {1, arcs_24_1}, + {1, arcs_24_0}, + {1, arcs_24_1}, }; static arc arcs_25_0[1] = { - {72, 1}, + {72, 1}, }; static arc arcs_25_1[2] = { - {24, 2}, - {0, 1}, + {24, 2}, + {0, 1}, }; static arc arcs_25_2[2] = { - {73, 3}, - {0, 2}, + {73, 3}, + {0, 2}, }; static arc arcs_25_3[1] = { - {24, 4}, + {24, 4}, }; static arc arcs_25_4[1] = { - {0, 4}, + {0, 4}, }; static state states_25[5] = { - {1, arcs_25_0}, - {2, arcs_25_1}, - {2, arcs_25_2}, - {1, arcs_25_3}, - {1, arcs_25_4}, + {1, arcs_25_0}, + {2, arcs_25_1}, + {2, arcs_25_2}, + {1, arcs_25_3}, + {1, arcs_25_4}, }; static arc arcs_26_0[2] = { - {74, 1}, - {75, 1}, + {74, 1}, + {75, 1}, }; static arc arcs_26_1[1] = { - {0, 1}, + {0, 1}, }; static state states_26[2] = { - {2, arcs_26_0}, - {1, arcs_26_1}, + {2, arcs_26_0}, + {1, arcs_26_1}, }; static arc arcs_27_0[1] = { - {76, 1}, + {76, 1}, }; static arc arcs_27_1[1] = { - {77, 2}, + {77, 2}, }; static arc arcs_27_2[1] = { - {0, 2}, + {0, 2}, }; static state states_27[3] = { - {1, arcs_27_0}, - {1, arcs_27_1}, - {1, arcs_27_2}, + {1, arcs_27_0}, + {1, arcs_27_1}, + {1, arcs_27_2}, }; static arc arcs_28_0[1] = { - {73, 1}, + {73, 1}, }; static arc arcs_28_1[3] = { - {78, 2}, - {79, 2}, - {12, 3}, + {78, 2}, + {79, 2}, + {12, 3}, }; static arc arcs_28_2[4] = { - {78, 2}, - {79, 2}, - {12, 3}, - {76, 4}, + {78, 2}, + {79, 2}, + {12, 3}, + {76, 4}, }; static arc arcs_28_3[1] = { - {76, 4}, + {76, 4}, }; static arc arcs_28_4[3] = { - {31, 5}, - {13, 6}, - {80, 5}, + {31, 5}, + {13, 6}, + {80, 5}, }; static arc arcs_28_5[1] = { - {0, 5}, + {0, 5}, }; static arc arcs_28_6[1] = { - {80, 7}, + {80, 7}, }; static arc arcs_28_7[1] = { - {15, 5}, + {15, 5}, }; static state states_28[8] = { - {1, arcs_28_0}, - {3, arcs_28_1}, - {4, arcs_28_2}, - {1, arcs_28_3}, - {3, arcs_28_4}, - {1, arcs_28_5}, - {1, arcs_28_6}, - {1, arcs_28_7}, + {1, arcs_28_0}, + {3, arcs_28_1}, + {4, arcs_28_2}, + {1, arcs_28_3}, + {3, arcs_28_4}, + {1, arcs_28_5}, + {1, arcs_28_6}, + {1, arcs_28_7}, }; static arc arcs_29_0[1] = { - {21, 1}, + {21, 1}, }; static arc arcs_29_1[2] = { - {82, 2}, - {0, 1}, + {82, 2}, + {0, 1}, }; static arc arcs_29_2[1] = { - {21, 3}, + {21, 3}, }; static arc arcs_29_3[1] = { - {0, 3}, + {0, 3}, }; static state states_29[4] = { - {1, arcs_29_0}, - {2, arcs_29_1}, - {1, arcs_29_2}, - {1, arcs_29_3}, + {1, arcs_29_0}, + {2, arcs_29_1}, + {1, arcs_29_2}, + {1, arcs_29_3}, }; static arc arcs_30_0[1] = { - {12, 1}, + {12, 1}, }; static arc arcs_30_1[2] = { - {82, 2}, - {0, 1}, + {82, 2}, + {0, 1}, }; static arc arcs_30_2[1] = { - {21, 3}, + {21, 3}, }; static arc arcs_30_3[1] = { - {0, 3}, + {0, 3}, }; static state states_30[4] = { - {1, arcs_30_0}, - {2, arcs_30_1}, - {1, arcs_30_2}, - {1, arcs_30_3}, + {1, arcs_30_0}, + {2, arcs_30_1}, + {1, arcs_30_2}, + {1, arcs_30_3}, }; static arc arcs_31_0[1] = { - {81, 1}, + {81, 1}, }; static arc arcs_31_1[2] = { - {30, 2}, - {0, 1}, + {30, 2}, + {0, 1}, }; static arc arcs_31_2[2] = { - {81, 1}, - {0, 2}, + {81, 1}, + {0, 2}, }; static state states_31[3] = { - {1, arcs_31_0}, - {2, arcs_31_1}, - {2, arcs_31_2}, + {1, arcs_31_0}, + {2, arcs_31_1}, + {2, arcs_31_2}, }; static arc arcs_32_0[1] = { - {83, 1}, + {83, 1}, }; static arc arcs_32_1[2] = { - {30, 0}, - {0, 1}, + {30, 0}, + {0, 1}, }; static state states_32[2] = { - {1, arcs_32_0}, - {2, arcs_32_1}, + {1, arcs_32_0}, + {2, arcs_32_1}, }; static arc arcs_33_0[1] = { - {21, 1}, + {21, 1}, }; static arc arcs_33_1[2] = { - {78, 0}, - {0, 1}, + {78, 0}, + {0, 1}, }; static state states_33[2] = { - {1, arcs_33_0}, - {2, arcs_33_1}, + {1, arcs_33_0}, + {2, arcs_33_1}, }; static arc arcs_34_0[1] = { - {84, 1}, + {84, 1}, }; static arc arcs_34_1[1] = { - {21, 2}, + {21, 2}, }; static arc arcs_34_2[2] = { - {30, 1}, - {0, 2}, + {30, 1}, + {0, 2}, }; static state states_34[3] = { - {1, arcs_34_0}, - {1, arcs_34_1}, - {2, arcs_34_2}, + {1, arcs_34_0}, + {1, arcs_34_1}, + {2, arcs_34_2}, }; static arc arcs_35_0[1] = { - {85, 1}, + {85, 1}, }; static arc arcs_35_1[1] = { - {21, 2}, + {21, 2}, }; static arc arcs_35_2[2] = { - {30, 1}, - {0, 2}, + {30, 1}, + {0, 2}, }; static state states_35[3] = { - {1, arcs_35_0}, - {1, arcs_35_1}, - {2, arcs_35_2}, + {1, arcs_35_0}, + {1, arcs_35_1}, + {2, arcs_35_2}, }; static arc arcs_36_0[1] = { - {86, 1}, + {86, 1}, }; static arc arcs_36_1[1] = { - {24, 2}, + {24, 2}, }; static arc arcs_36_2[2] = { - {30, 3}, - {0, 2}, + {30, 3}, + {0, 2}, }; static arc arcs_36_3[1] = { - {24, 4}, + {24, 4}, }; static arc arcs_36_4[1] = { - {0, 4}, + {0, 4}, }; static state states_36[5] = { - {1, arcs_36_0}, - {1, arcs_36_1}, - {2, arcs_36_2}, - {1, arcs_36_3}, - {1, arcs_36_4}, + {1, arcs_36_0}, + {1, arcs_36_1}, + {2, arcs_36_2}, + {1, arcs_36_3}, + {1, arcs_36_4}, }; static arc arcs_37_0[8] = { - {87, 1}, - {88, 1}, - {89, 1}, - {90, 1}, - {91, 1}, - {19, 1}, - {18, 1}, - {17, 1}, + {87, 1}, + {88, 1}, + {89, 1}, + {90, 1}, + {91, 1}, + {19, 1}, + {18, 1}, + {17, 1}, }; static arc arcs_37_1[1] = { - {0, 1}, + {0, 1}, }; static state states_37[2] = { - {8, arcs_37_0}, - {1, arcs_37_1}, + {8, arcs_37_0}, + {1, arcs_37_1}, }; static arc arcs_38_0[1] = { - {92, 1}, + {92, 1}, }; static arc arcs_38_1[1] = { - {24, 2}, + {24, 2}, }; static arc arcs_38_2[1] = { - {25, 3}, + {25, 3}, }; static arc arcs_38_3[1] = { - {26, 4}, + {26, 4}, }; static arc arcs_38_4[3] = { - {93, 1}, - {94, 5}, - {0, 4}, + {93, 1}, + {94, 5}, + {0, 4}, }; static arc arcs_38_5[1] = { - {25, 6}, + {25, 6}, }; static arc arcs_38_6[1] = { - {26, 7}, + {26, 7}, }; static arc arcs_38_7[1] = { - {0, 7}, + {0, 7}, }; static state states_38[8] = { - {1, arcs_38_0}, - {1, arcs_38_1}, - {1, arcs_38_2}, - {1, arcs_38_3}, - {3, arcs_38_4}, - {1, arcs_38_5}, - {1, arcs_38_6}, - {1, arcs_38_7}, + {1, arcs_38_0}, + {1, arcs_38_1}, + {1, arcs_38_2}, + {1, arcs_38_3}, + {3, arcs_38_4}, + {1, arcs_38_5}, + {1, arcs_38_6}, + {1, arcs_38_7}, }; static arc arcs_39_0[1] = { - {95, 1}, + {95, 1}, }; static arc arcs_39_1[1] = { - {24, 2}, + {24, 2}, }; static arc arcs_39_2[1] = { - {25, 3}, + {25, 3}, }; static arc arcs_39_3[1] = { - {26, 4}, + {26, 4}, }; static arc arcs_39_4[2] = { - {94, 5}, - {0, 4}, + {94, 5}, + {0, 4}, }; static arc arcs_39_5[1] = { - {25, 6}, + {25, 6}, }; static arc arcs_39_6[1] = { - {26, 7}, + {26, 7}, }; static arc arcs_39_7[1] = { - {0, 7}, + {0, 7}, }; static state states_39[8] = { - {1, arcs_39_0}, - {1, arcs_39_1}, - {1, arcs_39_2}, - {1, arcs_39_3}, - {2, arcs_39_4}, - {1, arcs_39_5}, - {1, arcs_39_6}, - {1, arcs_39_7}, + {1, arcs_39_0}, + {1, arcs_39_1}, + {1, arcs_39_2}, + {1, arcs_39_3}, + {2, arcs_39_4}, + {1, arcs_39_5}, + {1, arcs_39_6}, + {1, arcs_39_7}, }; static arc arcs_40_0[1] = { - {96, 1}, + {96, 1}, }; static arc arcs_40_1[1] = { - {62, 2}, + {62, 2}, }; static arc arcs_40_2[1] = { - {97, 3}, + {97, 3}, }; static arc arcs_40_3[1] = { - {9, 4}, + {9, 4}, }; static arc arcs_40_4[1] = { - {25, 5}, + {25, 5}, }; static arc arcs_40_5[1] = { - {26, 6}, + {26, 6}, }; static arc arcs_40_6[2] = { - {94, 7}, - {0, 6}, + {94, 7}, + {0, 6}, }; static arc arcs_40_7[1] = { - {25, 8}, + {25, 8}, }; static arc arcs_40_8[1] = { - {26, 9}, + {26, 9}, }; static arc arcs_40_9[1] = { - {0, 9}, + {0, 9}, }; static state states_40[10] = { - {1, arcs_40_0}, - {1, arcs_40_1}, - {1, arcs_40_2}, - {1, arcs_40_3}, - {1, arcs_40_4}, - {1, arcs_40_5}, - {2, arcs_40_6}, - {1, arcs_40_7}, - {1, arcs_40_8}, - {1, arcs_40_9}, + {1, arcs_40_0}, + {1, arcs_40_1}, + {1, arcs_40_2}, + {1, arcs_40_3}, + {1, arcs_40_4}, + {1, arcs_40_5}, + {2, arcs_40_6}, + {1, arcs_40_7}, + {1, arcs_40_8}, + {1, arcs_40_9}, }; static arc arcs_41_0[1] = { - {98, 1}, + {98, 1}, }; static arc arcs_41_1[1] = { - {25, 2}, + {25, 2}, }; static arc arcs_41_2[1] = { - {26, 3}, + {26, 3}, }; static arc arcs_41_3[2] = { - {99, 4}, - {100, 5}, + {99, 4}, + {100, 5}, }; static arc arcs_41_4[1] = { - {25, 6}, + {25, 6}, }; static arc arcs_41_5[1] = { - {25, 7}, + {25, 7}, }; static arc arcs_41_6[1] = { - {26, 8}, + {26, 8}, }; static arc arcs_41_7[1] = { - {26, 9}, + {26, 9}, }; static arc arcs_41_8[4] = { - {99, 4}, - {94, 10}, - {100, 5}, - {0, 8}, + {99, 4}, + {94, 10}, + {100, 5}, + {0, 8}, }; static arc arcs_41_9[1] = { - {0, 9}, + {0, 9}, }; static arc arcs_41_10[1] = { - {25, 11}, + {25, 11}, }; static arc arcs_41_11[1] = { - {26, 12}, + {26, 12}, }; static arc arcs_41_12[2] = { - {100, 5}, - {0, 12}, + {100, 5}, + {0, 12}, }; static state states_41[13] = { - {1, arcs_41_0}, - {1, arcs_41_1}, - {1, arcs_41_2}, - {2, arcs_41_3}, - {1, arcs_41_4}, - {1, arcs_41_5}, - {1, arcs_41_6}, - {1, arcs_41_7}, - {4, arcs_41_8}, - {1, arcs_41_9}, - {1, arcs_41_10}, - {1, arcs_41_11}, - {2, arcs_41_12}, + {1, arcs_41_0}, + {1, arcs_41_1}, + {1, arcs_41_2}, + {2, arcs_41_3}, + {1, arcs_41_4}, + {1, arcs_41_5}, + {1, arcs_41_6}, + {1, arcs_41_7}, + {4, arcs_41_8}, + {1, arcs_41_9}, + {1, arcs_41_10}, + {1, arcs_41_11}, + {2, arcs_41_12}, }; static arc arcs_42_0[1] = { - {101, 1}, + {101, 1}, }; static arc arcs_42_1[1] = { - {102, 2}, + {102, 2}, }; static arc arcs_42_2[2] = { - {30, 1}, - {25, 3}, + {30, 1}, + {25, 3}, }; static arc arcs_42_3[1] = { - {26, 4}, + {26, 4}, }; static arc arcs_42_4[1] = { - {0, 4}, + {0, 4}, }; static state states_42[5] = { - {1, arcs_42_0}, - {1, arcs_42_1}, - {2, arcs_42_2}, - {1, arcs_42_3}, - {1, arcs_42_4}, + {1, arcs_42_0}, + {1, arcs_42_1}, + {2, arcs_42_2}, + {1, arcs_42_3}, + {1, arcs_42_4}, }; static arc arcs_43_0[1] = { - {24, 1}, + {24, 1}, }; static arc arcs_43_1[2] = { - {82, 2}, - {0, 1}, + {82, 2}, + {0, 1}, }; static arc arcs_43_2[1] = { - {103, 3}, + {103, 3}, }; static arc arcs_43_3[1] = { - {0, 3}, + {0, 3}, }; static state states_43[4] = { - {1, arcs_43_0}, - {2, arcs_43_1}, - {1, arcs_43_2}, - {1, arcs_43_3}, + {1, arcs_43_0}, + {2, arcs_43_1}, + {1, arcs_43_2}, + {1, arcs_43_3}, }; static arc arcs_44_0[1] = { - {104, 1}, + {104, 1}, }; static arc arcs_44_1[2] = { - {24, 2}, - {0, 1}, + {24, 2}, + {0, 1}, }; static arc arcs_44_2[2] = { - {82, 3}, - {0, 2}, + {82, 3}, + {0, 2}, }; static arc arcs_44_3[1] = { - {21, 4}, + {21, 4}, }; static arc arcs_44_4[1] = { - {0, 4}, + {0, 4}, }; static state states_44[5] = { - {1, arcs_44_0}, - {2, arcs_44_1}, - {2, arcs_44_2}, - {1, arcs_44_3}, - {1, arcs_44_4}, + {1, arcs_44_0}, + {2, arcs_44_1}, + {2, arcs_44_2}, + {1, arcs_44_3}, + {1, arcs_44_4}, }; static arc arcs_45_0[2] = { - {3, 1}, - {2, 2}, + {3, 1}, + {2, 2}, }; static arc arcs_45_1[1] = { - {0, 1}, + {0, 1}, }; static arc arcs_45_2[1] = { - {105, 3}, + {105, 3}, }; static arc arcs_45_3[1] = { - {6, 4}, + {6, 4}, }; static arc arcs_45_4[2] = { - {6, 4}, - {106, 1}, + {6, 4}, + {106, 1}, }; static state states_45[5] = { - {2, arcs_45_0}, - {1, arcs_45_1}, - {1, arcs_45_2}, - {1, arcs_45_3}, - {2, arcs_45_4}, + {2, arcs_45_0}, + {1, arcs_45_1}, + {1, arcs_45_2}, + {1, arcs_45_3}, + {2, arcs_45_4}, }; static arc arcs_46_0[2] = { - {107, 1}, - {108, 2}, + {107, 1}, + {108, 2}, }; static arc arcs_46_1[2] = { - {92, 3}, - {0, 1}, + {92, 3}, + {0, 1}, }; static arc arcs_46_2[1] = { - {0, 2}, + {0, 2}, }; static arc arcs_46_3[1] = { - {107, 4}, + {107, 4}, }; static arc arcs_46_4[1] = { - {94, 5}, + {94, 5}, }; static arc arcs_46_5[1] = { - {24, 2}, + {24, 2}, }; static state states_46[6] = { - {2, arcs_46_0}, - {2, arcs_46_1}, - {1, arcs_46_2}, - {1, arcs_46_3}, - {1, arcs_46_4}, - {1, arcs_46_5}, + {2, arcs_46_0}, + {2, arcs_46_1}, + {1, arcs_46_2}, + {1, arcs_46_3}, + {1, arcs_46_4}, + {1, arcs_46_5}, }; static arc arcs_47_0[2] = { - {107, 1}, - {110, 1}, + {107, 1}, + {110, 1}, }; static arc arcs_47_1[1] = { - {0, 1}, + {0, 1}, }; static state states_47[2] = { - {2, arcs_47_0}, - {1, arcs_47_1}, + {2, arcs_47_0}, + {1, arcs_47_1}, }; static arc arcs_48_0[1] = { - {111, 1}, + {111, 1}, }; static arc arcs_48_1[2] = { - {33, 2}, - {25, 3}, + {33, 2}, + {25, 3}, }; static arc arcs_48_2[1] = { - {25, 3}, + {25, 3}, }; static arc arcs_48_3[1] = { - {24, 4}, + {24, 4}, }; static arc arcs_48_4[1] = { - {0, 4}, + {0, 4}, }; static state states_48[5] = { - {1, arcs_48_0}, - {2, arcs_48_1}, - {1, arcs_48_2}, - {1, arcs_48_3}, - {1, arcs_48_4}, + {1, arcs_48_0}, + {2, arcs_48_1}, + {1, arcs_48_2}, + {1, arcs_48_3}, + {1, arcs_48_4}, }; static arc arcs_49_0[1] = { - {111, 1}, + {111, 1}, }; static arc arcs_49_1[2] = { - {33, 2}, - {25, 3}, + {33, 2}, + {25, 3}, }; static arc arcs_49_2[1] = { - {25, 3}, + {25, 3}, }; static arc arcs_49_3[1] = { - {109, 4}, + {109, 4}, }; static arc arcs_49_4[1] = { - {0, 4}, + {0, 4}, }; static state states_49[5] = { - {1, arcs_49_0}, - {2, arcs_49_1}, - {1, arcs_49_2}, - {1, arcs_49_3}, - {1, arcs_49_4}, + {1, arcs_49_0}, + {2, arcs_49_1}, + {1, arcs_49_2}, + {1, arcs_49_3}, + {1, arcs_49_4}, }; static arc arcs_50_0[1] = { - {112, 1}, + {112, 1}, }; static arc arcs_50_1[2] = { - {113, 0}, - {0, 1}, + {113, 0}, + {0, 1}, }; static state states_50[2] = { - {1, arcs_50_0}, - {2, arcs_50_1}, + {1, arcs_50_0}, + {2, arcs_50_1}, }; static arc arcs_51_0[1] = { - {114, 1}, + {114, 1}, }; static arc arcs_51_1[2] = { - {115, 0}, - {0, 1}, + {115, 0}, + {0, 1}, }; static state states_51[2] = { - {1, arcs_51_0}, - {2, arcs_51_1}, + {1, arcs_51_0}, + {2, arcs_51_1}, }; static arc arcs_52_0[2] = { - {116, 1}, - {117, 2}, + {116, 1}, + {117, 2}, }; static arc arcs_52_1[1] = { - {114, 2}, + {114, 2}, }; static arc arcs_52_2[1] = { - {0, 2}, + {0, 2}, }; static state states_52[3] = { - {2, arcs_52_0}, - {1, arcs_52_1}, - {1, arcs_52_2}, + {2, arcs_52_0}, + {1, arcs_52_1}, + {1, arcs_52_2}, }; static arc arcs_53_0[1] = { - {103, 1}, + {103, 1}, }; static arc arcs_53_1[2] = { - {118, 0}, - {0, 1}, + {118, 0}, + {0, 1}, }; static state states_53[2] = { - {1, arcs_53_0}, - {2, arcs_53_1}, + {1, arcs_53_0}, + {2, arcs_53_1}, }; static arc arcs_54_0[10] = { - {119, 1}, - {120, 1}, - {121, 1}, - {122, 1}, - {123, 1}, - {124, 1}, - {125, 1}, - {97, 1}, - {116, 2}, - {126, 3}, + {119, 1}, + {120, 1}, + {121, 1}, + {122, 1}, + {123, 1}, + {124, 1}, + {125, 1}, + {97, 1}, + {116, 2}, + {126, 3}, }; static arc arcs_54_1[1] = { - {0, 1}, + {0, 1}, }; static arc arcs_54_2[1] = { - {97, 1}, + {97, 1}, }; static arc arcs_54_3[2] = { - {116, 1}, - {0, 3}, + {116, 1}, + {0, 3}, }; static state states_54[4] = { - {10, arcs_54_0}, - {1, arcs_54_1}, - {1, arcs_54_2}, - {2, arcs_54_3}, + {10, arcs_54_0}, + {1, arcs_54_1}, + {1, arcs_54_2}, + {2, arcs_54_3}, }; static arc arcs_55_0[1] = { - {31, 1}, + {31, 1}, }; static arc arcs_55_1[1] = { - {103, 2}, + {103, 2}, }; static arc arcs_55_2[1] = { - {0, 2}, + {0, 2}, }; static state states_55[3] = { - {1, arcs_55_0}, - {1, arcs_55_1}, - {1, arcs_55_2}, + {1, arcs_55_0}, + {1, arcs_55_1}, + {1, arcs_55_2}, }; static arc arcs_56_0[1] = { - {127, 1}, + {127, 1}, }; static arc arcs_56_1[2] = { - {128, 0}, - {0, 1}, + {128, 0}, + {0, 1}, }; static state states_56[2] = { - {1, arcs_56_0}, - {2, arcs_56_1}, + {1, arcs_56_0}, + {2, arcs_56_1}, }; static arc arcs_57_0[1] = { - {129, 1}, + {129, 1}, }; static arc arcs_57_1[2] = { - {130, 0}, - {0, 1}, + {130, 0}, + {0, 1}, }; static state states_57[2] = { - {1, arcs_57_0}, - {2, arcs_57_1}, + {1, arcs_57_0}, + {2, arcs_57_1}, }; static arc arcs_58_0[1] = { - {131, 1}, + {131, 1}, }; static arc arcs_58_1[2] = { - {132, 0}, - {0, 1}, + {132, 0}, + {0, 1}, }; static state states_58[2] = { - {1, arcs_58_0}, - {2, arcs_58_1}, + {1, arcs_58_0}, + {2, arcs_58_1}, }; static arc arcs_59_0[1] = { - {133, 1}, + {133, 1}, }; static arc arcs_59_1[3] = { - {134, 0}, - {135, 0}, - {0, 1}, + {134, 0}, + {135, 0}, + {0, 1}, }; static state states_59[2] = { - {1, arcs_59_0}, - {3, arcs_59_1}, + {1, arcs_59_0}, + {3, arcs_59_1}, }; static arc arcs_60_0[1] = { - {136, 1}, + {136, 1}, }; static arc arcs_60_1[3] = { - {137, 0}, - {138, 0}, - {0, 1}, + {137, 0}, + {138, 0}, + {0, 1}, }; static state states_60[2] = { - {1, arcs_60_0}, - {3, arcs_60_1}, + {1, arcs_60_0}, + {3, arcs_60_1}, }; static arc arcs_61_0[1] = { - {139, 1}, + {139, 1}, }; static arc arcs_61_1[5] = { - {31, 0}, - {140, 0}, - {141, 0}, - {142, 0}, - {0, 1}, + {31, 0}, + {140, 0}, + {141, 0}, + {142, 0}, + {0, 1}, }; static state states_61[2] = { - {1, arcs_61_0}, - {5, arcs_61_1}, + {1, arcs_61_0}, + {5, arcs_61_1}, }; static arc arcs_62_0[4] = { - {137, 1}, - {138, 1}, - {143, 1}, - {144, 2}, + {137, 1}, + {138, 1}, + {143, 1}, + {144, 2}, }; static arc arcs_62_1[1] = { - {139, 2}, + {139, 2}, }; static arc arcs_62_2[1] = { - {0, 2}, + {0, 2}, }; static state states_62[3] = { - {4, arcs_62_0}, - {1, arcs_62_1}, - {1, arcs_62_2}, + {4, arcs_62_0}, + {1, arcs_62_1}, + {1, arcs_62_2}, }; static arc arcs_63_0[1] = { - {145, 1}, + {145, 1}, }; static arc arcs_63_1[3] = { - {146, 1}, - {32, 2}, - {0, 1}, + {146, 1}, + {32, 2}, + {0, 1}, }; static arc arcs_63_2[1] = { - {139, 3}, + {139, 3}, }; static arc arcs_63_3[1] = { - {0, 3}, + {0, 3}, }; static state states_63[4] = { - {1, arcs_63_0}, - {3, arcs_63_1}, - {1, arcs_63_2}, - {1, arcs_63_3}, + {1, arcs_63_0}, + {3, arcs_63_1}, + {1, arcs_63_2}, + {1, arcs_63_3}, }; static arc arcs_64_0[10] = { - {13, 1}, - {148, 2}, - {150, 3}, - {21, 4}, - {153, 4}, - {154, 5}, - {79, 4}, - {155, 4}, - {156, 4}, - {157, 4}, + {13, 1}, + {148, 2}, + {150, 3}, + {21, 4}, + {153, 4}, + {154, 5}, + {79, 4}, + {155, 4}, + {156, 4}, + {157, 4}, }; static arc arcs_64_1[3] = { - {47, 6}, - {147, 6}, - {15, 4}, + {47, 6}, + {147, 6}, + {15, 4}, }; static arc arcs_64_2[2] = { - {147, 7}, - {149, 4}, + {147, 7}, + {149, 4}, }; static arc arcs_64_3[2] = { - {151, 8}, - {152, 4}, + {151, 8}, + {152, 4}, }; static arc arcs_64_4[1] = { - {0, 4}, + {0, 4}, }; static arc arcs_64_5[2] = { - {154, 5}, - {0, 5}, + {154, 5}, + {0, 5}, }; static arc arcs_64_6[1] = { - {15, 4}, + {15, 4}, }; static arc arcs_64_7[1] = { - {149, 4}, + {149, 4}, }; static arc arcs_64_8[1] = { - {152, 4}, + {152, 4}, }; static state states_64[9] = { - {10, arcs_64_0}, - {3, arcs_64_1}, - {2, arcs_64_2}, - {2, arcs_64_3}, - {1, arcs_64_4}, - {2, arcs_64_5}, - {1, arcs_64_6}, - {1, arcs_64_7}, - {1, arcs_64_8}, + {10, arcs_64_0}, + {3, arcs_64_1}, + {2, arcs_64_2}, + {2, arcs_64_3}, + {1, arcs_64_4}, + {2, arcs_64_5}, + {1, arcs_64_6}, + {1, arcs_64_7}, + {1, arcs_64_8}, }; static arc arcs_65_0[2] = { - {24, 1}, - {48, 1}, + {24, 1}, + {48, 1}, }; static arc arcs_65_1[3] = { - {158, 2}, - {30, 3}, - {0, 1}, + {158, 2}, + {30, 3}, + {0, 1}, }; static arc arcs_65_2[1] = { - {0, 2}, + {0, 2}, }; static arc arcs_65_3[3] = { - {24, 4}, - {48, 4}, - {0, 3}, + {24, 4}, + {48, 4}, + {0, 3}, }; static arc arcs_65_4[2] = { - {30, 3}, - {0, 4}, + {30, 3}, + {0, 4}, }; static state states_65[5] = { - {2, arcs_65_0}, - {3, arcs_65_1}, - {1, arcs_65_2}, - {3, arcs_65_3}, - {2, arcs_65_4}, + {2, arcs_65_0}, + {3, arcs_65_1}, + {1, arcs_65_2}, + {3, arcs_65_3}, + {2, arcs_65_4}, }; static arc arcs_66_0[3] = { - {13, 1}, - {148, 2}, - {78, 3}, + {13, 1}, + {148, 2}, + {78, 3}, }; static arc arcs_66_1[2] = { - {14, 4}, - {15, 5}, + {14, 4}, + {15, 5}, }; static arc arcs_66_2[1] = { - {159, 6}, + {159, 6}, }; static arc arcs_66_3[1] = { - {21, 5}, + {21, 5}, }; static arc arcs_66_4[1] = { - {15, 5}, + {15, 5}, }; static arc arcs_66_5[1] = { - {0, 5}, + {0, 5}, }; static arc arcs_66_6[1] = { - {149, 5}, + {149, 5}, }; static state states_66[7] = { - {3, arcs_66_0}, - {2, arcs_66_1}, - {1, arcs_66_2}, - {1, arcs_66_3}, - {1, arcs_66_4}, - {1, arcs_66_5}, - {1, arcs_66_6}, + {3, arcs_66_0}, + {2, arcs_66_1}, + {1, arcs_66_2}, + {1, arcs_66_3}, + {1, arcs_66_4}, + {1, arcs_66_5}, + {1, arcs_66_6}, }; static arc arcs_67_0[1] = { - {160, 1}, + {160, 1}, }; static arc arcs_67_1[2] = { - {30, 2}, - {0, 1}, + {30, 2}, + {0, 1}, }; static arc arcs_67_2[2] = { - {160, 1}, - {0, 2}, + {160, 1}, + {0, 2}, }; static state states_67[3] = { - {1, arcs_67_0}, - {2, arcs_67_1}, - {2, arcs_67_2}, + {1, arcs_67_0}, + {2, arcs_67_1}, + {2, arcs_67_2}, }; static arc arcs_68_0[2] = { - {24, 1}, - {25, 2}, + {24, 1}, + {25, 2}, }; static arc arcs_68_1[2] = { - {25, 2}, - {0, 1}, + {25, 2}, + {0, 1}, }; static arc arcs_68_2[3] = { - {24, 3}, - {161, 4}, - {0, 2}, + {24, 3}, + {161, 4}, + {0, 2}, }; static arc arcs_68_3[2] = { - {161, 4}, - {0, 3}, + {161, 4}, + {0, 3}, }; static arc arcs_68_4[1] = { - {0, 4}, + {0, 4}, }; static state states_68[5] = { - {2, arcs_68_0}, - {2, arcs_68_1}, - {3, arcs_68_2}, - {2, arcs_68_3}, - {1, arcs_68_4}, + {2, arcs_68_0}, + {2, arcs_68_1}, + {3, arcs_68_2}, + {2, arcs_68_3}, + {1, arcs_68_4}, }; static arc arcs_69_0[1] = { - {25, 1}, + {25, 1}, }; static arc arcs_69_1[2] = { - {24, 2}, - {0, 1}, + {24, 2}, + {0, 1}, }; static arc arcs_69_2[1] = { - {0, 2}, + {0, 2}, }; static state states_69[3] = { - {1, arcs_69_0}, - {2, arcs_69_1}, - {1, arcs_69_2}, + {1, arcs_69_0}, + {2, arcs_69_1}, + {1, arcs_69_2}, }; static arc arcs_70_0[2] = { - {103, 1}, - {48, 1}, + {103, 1}, + {48, 1}, }; static arc arcs_70_1[2] = { - {30, 2}, - {0, 1}, + {30, 2}, + {0, 1}, }; static arc arcs_70_2[3] = { - {103, 1}, - {48, 1}, - {0, 2}, + {103, 1}, + {48, 1}, + {0, 2}, }; static state states_70[3] = { - {2, arcs_70_0}, - {2, arcs_70_1}, - {3, arcs_70_2}, + {2, arcs_70_0}, + {2, arcs_70_1}, + {3, arcs_70_2}, }; static arc arcs_71_0[1] = { - {24, 1}, + {24, 1}, }; static arc arcs_71_1[2] = { - {30, 2}, - {0, 1}, + {30, 2}, + {0, 1}, }; static arc arcs_71_2[2] = { - {24, 1}, - {0, 2}, + {24, 1}, + {0, 2}, }; static state states_71[3] = { - {1, arcs_71_0}, - {2, arcs_71_1}, - {2, arcs_71_2}, + {1, arcs_71_0}, + {2, arcs_71_1}, + {2, arcs_71_2}, }; static arc arcs_72_0[1] = { - {24, 1}, + {24, 1}, }; static arc arcs_72_1[4] = { - {25, 2}, - {158, 3}, - {30, 4}, - {0, 1}, + {25, 2}, + {158, 3}, + {30, 4}, + {0, 1}, }; static arc arcs_72_2[1] = { - {24, 5}, + {24, 5}, }; static arc arcs_72_3[1] = { - {0, 3}, + {0, 3}, }; static arc arcs_72_4[2] = { - {24, 6}, - {0, 4}, + {24, 6}, + {0, 4}, }; static arc arcs_72_5[3] = { - {158, 3}, - {30, 7}, - {0, 5}, + {158, 3}, + {30, 7}, + {0, 5}, }; static arc arcs_72_6[2] = { - {30, 4}, - {0, 6}, + {30, 4}, + {0, 6}, }; static arc arcs_72_7[2] = { - {24, 8}, - {0, 7}, + {24, 8}, + {0, 7}, }; static arc arcs_72_8[1] = { - {25, 9}, + {25, 9}, }; static arc arcs_72_9[1] = { - {24, 10}, + {24, 10}, }; static arc arcs_72_10[2] = { - {30, 7}, - {0, 10}, + {30, 7}, + {0, 10}, }; static state states_72[11] = { - {1, arcs_72_0}, - {4, arcs_72_1}, - {1, arcs_72_2}, - {1, arcs_72_3}, - {2, arcs_72_4}, - {3, arcs_72_5}, - {2, arcs_72_6}, - {2, arcs_72_7}, - {1, arcs_72_8}, - {1, arcs_72_9}, - {2, arcs_72_10}, + {1, arcs_72_0}, + {4, arcs_72_1}, + {1, arcs_72_2}, + {1, arcs_72_3}, + {2, arcs_72_4}, + {3, arcs_72_5}, + {2, arcs_72_6}, + {2, arcs_72_7}, + {1, arcs_72_8}, + {1, arcs_72_9}, + {2, arcs_72_10}, }; static arc arcs_73_0[1] = { - {162, 1}, + {162, 1}, }; static arc arcs_73_1[1] = { - {21, 2}, + {21, 2}, }; static arc arcs_73_2[2] = { - {13, 3}, - {25, 4}, + {13, 3}, + {25, 4}, }; static arc arcs_73_3[2] = { - {14, 5}, - {15, 6}, + {14, 5}, + {15, 6}, }; static arc arcs_73_4[1] = { - {26, 7}, + {26, 7}, }; static arc arcs_73_5[1] = { - {15, 6}, + {15, 6}, }; static arc arcs_73_6[1] = { - {25, 4}, + {25, 4}, }; static arc arcs_73_7[1] = { - {0, 7}, + {0, 7}, }; static state states_73[8] = { - {1, arcs_73_0}, - {1, arcs_73_1}, - {2, arcs_73_2}, - {2, arcs_73_3}, - {1, arcs_73_4}, - {1, arcs_73_5}, - {1, arcs_73_6}, - {1, arcs_73_7}, + {1, arcs_73_0}, + {1, arcs_73_1}, + {2, arcs_73_2}, + {2, arcs_73_3}, + {1, arcs_73_4}, + {1, arcs_73_5}, + {1, arcs_73_6}, + {1, arcs_73_7}, }; static arc arcs_74_0[3] = { - {163, 1}, - {31, 2}, - {32, 3}, + {163, 1}, + {31, 2}, + {32, 3}, }; static arc arcs_74_1[2] = { - {30, 4}, - {0, 1}, + {30, 4}, + {0, 1}, }; static arc arcs_74_2[1] = { - {24, 5}, + {24, 5}, }; static arc arcs_74_3[1] = { - {24, 6}, + {24, 6}, }; static arc arcs_74_4[4] = { - {163, 1}, - {31, 2}, - {32, 3}, - {0, 4}, + {163, 1}, + {31, 2}, + {32, 3}, + {0, 4}, }; static arc arcs_74_5[2] = { - {30, 7}, - {0, 5}, + {30, 7}, + {0, 5}, }; static arc arcs_74_6[1] = { - {0, 6}, + {0, 6}, }; static arc arcs_74_7[2] = { - {163, 5}, - {32, 3}, + {163, 5}, + {32, 3}, }; static state states_74[8] = { - {3, arcs_74_0}, - {2, arcs_74_1}, - {1, arcs_74_2}, - {1, arcs_74_3}, - {4, arcs_74_4}, - {2, arcs_74_5}, - {1, arcs_74_6}, - {2, arcs_74_7}, + {3, arcs_74_0}, + {2, arcs_74_1}, + {1, arcs_74_2}, + {1, arcs_74_3}, + {4, arcs_74_4}, + {2, arcs_74_5}, + {1, arcs_74_6}, + {2, arcs_74_7}, }; static arc arcs_75_0[1] = { - {24, 1}, + {24, 1}, }; static arc arcs_75_1[3] = { - {158, 2}, - {29, 3}, - {0, 1}, + {158, 2}, + {29, 3}, + {0, 1}, }; static arc arcs_75_2[1] = { - {0, 2}, + {0, 2}, }; static arc arcs_75_3[1] = { - {24, 2}, + {24, 2}, }; static state states_75[4] = { - {1, arcs_75_0}, - {3, arcs_75_1}, - {1, arcs_75_2}, - {1, arcs_75_3}, + {1, arcs_75_0}, + {3, arcs_75_1}, + {1, arcs_75_2}, + {1, arcs_75_3}, }; static arc arcs_76_0[2] = { - {158, 1}, - {165, 1}, + {158, 1}, + {165, 1}, }; static arc arcs_76_1[1] = { - {0, 1}, + {0, 1}, }; static state states_76[2] = { - {2, arcs_76_0}, - {1, arcs_76_1}, + {2, arcs_76_0}, + {1, arcs_76_1}, }; static arc arcs_77_0[1] = { - {96, 1}, + {96, 1}, }; static arc arcs_77_1[1] = { - {62, 2}, + {62, 2}, }; static arc arcs_77_2[1] = { - {97, 3}, + {97, 3}, }; static arc arcs_77_3[1] = { - {107, 4}, + {107, 4}, }; static arc arcs_77_4[2] = { - {164, 5}, - {0, 4}, + {164, 5}, + {0, 4}, }; static arc arcs_77_5[1] = { - {0, 5}, + {0, 5}, }; static state states_77[6] = { - {1, arcs_77_0}, - {1, arcs_77_1}, - {1, arcs_77_2}, - {1, arcs_77_3}, - {2, arcs_77_4}, - {1, arcs_77_5}, + {1, arcs_77_0}, + {1, arcs_77_1}, + {1, arcs_77_2}, + {1, arcs_77_3}, + {2, arcs_77_4}, + {1, arcs_77_5}, }; static arc arcs_78_0[1] = { - {92, 1}, + {92, 1}, }; static arc arcs_78_1[1] = { - {109, 2}, + {109, 2}, }; static arc arcs_78_2[2] = { - {164, 3}, - {0, 2}, + {164, 3}, + {0, 2}, }; static arc arcs_78_3[1] = { - {0, 3}, + {0, 3}, }; static state states_78[4] = { - {1, arcs_78_0}, - {1, arcs_78_1}, - {2, arcs_78_2}, - {1, arcs_78_3}, + {1, arcs_78_0}, + {1, arcs_78_1}, + {2, arcs_78_2}, + {1, arcs_78_3}, }; static arc arcs_79_0[1] = { - {21, 1}, + {21, 1}, }; static arc arcs_79_1[1] = { - {0, 1}, + {0, 1}, }; static state states_79[2] = { - {1, arcs_79_0}, - {1, arcs_79_1}, + {1, arcs_79_0}, + {1, arcs_79_1}, }; static arc arcs_80_0[1] = { - {167, 1}, + {167, 1}, }; static arc arcs_80_1[2] = { - {9, 2}, - {0, 1}, + {9, 2}, + {0, 1}, }; static arc arcs_80_2[1] = { - {0, 2}, + {0, 2}, }; static state states_80[3] = { - {1, arcs_80_0}, - {2, arcs_80_1}, - {1, arcs_80_2}, + {1, arcs_80_0}, + {2, arcs_80_1}, + {1, arcs_80_2}, }; static dfa dfas[81] = { - {256, "single_input", 0, 3, states_0, - "\004\050\060\200\000\000\000\240\340\223\160\220\045\200\020\000\000\206\120\076\204"}, - {257, "file_input", 0, 2, states_1, - "\204\050\060\200\000\000\000\240\340\223\160\220\045\200\020\000\000\206\120\076\204"}, - {258, "eval_input", 0, 3, states_2, - "\000\040\040\000\000\000\000\000\000\200\000\000\000\200\020\000\000\206\120\076\000"}, - {259, "decorator", 0, 7, states_3, - "\000\010\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000"}, - {260, "decorators", 0, 2, states_4, - "\000\010\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000"}, - {261, "decorated", 0, 3, states_5, - "\000\010\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000"}, - {262, "funcdef", 0, 8, states_6, - "\000\000\020\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000"}, - {263, "parameters", 0, 4, states_7, - "\000\040\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000"}, - {264, "typedargslist", 0, 12, states_8, - "\000\000\040\200\001\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000"}, - {265, "tfpdef", 0, 4, states_9, - "\000\000\040\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000"}, - {266, "varargslist", 0, 12, states_10, - "\000\000\040\200\001\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000"}, - {267, "vfpdef", 0, 2, states_11, - "\000\000\040\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000"}, - {268, "stmt", 0, 2, states_12, - "\000\050\060\200\000\000\000\240\340\223\160\220\045\200\020\000\000\206\120\076\204"}, - {269, "simple_stmt", 0, 4, states_13, - "\000\040\040\200\000\000\000\240\340\223\160\000\000\200\020\000\000\206\120\076\200"}, - {270, "small_stmt", 0, 2, states_14, - "\000\040\040\200\000\000\000\240\340\223\160\000\000\200\020\000\000\206\120\076\200"}, - {271, "expr_stmt", 0, 6, states_15, - "\000\040\040\200\000\000\000\000\000\200\000\000\000\200\020\000\000\206\120\076\000"}, - {272, "testlist_star_expr", 0, 3, states_16, - "\000\040\040\200\000\000\000\000\000\200\000\000\000\200\020\000\000\206\120\076\000"}, - {273, "augassign", 0, 2, states_17, - "\000\000\000\000\000\000\376\037\000\000\000\000\000\000\000\000\000\000\000\000\000"}, - {274, "del_stmt", 0, 3, states_18, - "\000\000\000\000\000\000\000\040\000\000\000\000\000\000\000\000\000\000\000\000\000"}, - {275, "pass_stmt", 0, 2, states_19, - "\000\000\000\000\000\000\000\200\000\000\000\000\000\000\000\000\000\000\000\000\000"}, - {276, "flow_stmt", 0, 2, states_20, - "\000\000\000\000\000\000\000\000\340\001\000\000\000\000\000\000\000\000\000\000\200"}, - {277, "break_stmt", 0, 2, states_21, - "\000\000\000\000\000\000\000\000\040\000\000\000\000\000\000\000\000\000\000\000\000"}, - {278, "continue_stmt", 0, 2, states_22, - "\000\000\000\000\000\000\000\000\100\000\000\000\000\000\000\000\000\000\000\000\000"}, - {279, "return_stmt", 0, 3, states_23, - "\000\000\000\000\000\000\000\000\200\000\000\000\000\000\000\000\000\000\000\000\000"}, - {280, "yield_stmt", 0, 2, states_24, - "\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\200"}, - {281, "raise_stmt", 0, 5, states_25, - "\000\000\000\000\000\000\000\000\000\001\000\000\000\000\000\000\000\000\000\000\000"}, - {282, "import_stmt", 0, 2, states_26, - "\000\000\000\000\000\000\000\000\000\022\000\000\000\000\000\000\000\000\000\000\000"}, - {283, "import_name", 0, 3, states_27, - "\000\000\000\000\000\000\000\000\000\020\000\000\000\000\000\000\000\000\000\000\000"}, - {284, "import_from", 0, 8, states_28, - "\000\000\000\000\000\000\000\000\000\002\000\000\000\000\000\000\000\000\000\000\000"}, - {285, "import_as_name", 0, 4, states_29, - "\000\000\040\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000"}, - {286, "dotted_as_name", 0, 4, states_30, - "\000\000\040\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000"}, - {287, "import_as_names", 0, 3, states_31, - "\000\000\040\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000"}, - {288, "dotted_as_names", 0, 2, states_32, - "\000\000\040\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000"}, - {289, "dotted_name", 0, 2, states_33, - "\000\000\040\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000"}, - {290, "global_stmt", 0, 3, states_34, - "\000\000\000\000\000\000\000\000\000\000\020\000\000\000\000\000\000\000\000\000\000"}, - {291, "nonlocal_stmt", 0, 3, states_35, - "\000\000\000\000\000\000\000\000\000\000\040\000\000\000\000\000\000\000\000\000\000"}, - {292, "assert_stmt", 0, 5, states_36, - "\000\000\000\000\000\000\000\000\000\000\100\000\000\000\000\000\000\000\000\000\000"}, - {293, "compound_stmt", 0, 2, states_37, - "\000\010\020\000\000\000\000\000\000\000\000\220\045\000\000\000\000\000\000\000\004"}, - {294, "if_stmt", 0, 8, states_38, - "\000\000\000\000\000\000\000\000\000\000\000\020\000\000\000\000\000\000\000\000\000"}, - {295, "while_stmt", 0, 8, states_39, - "\000\000\000\000\000\000\000\000\000\000\000\200\000\000\000\000\000\000\000\000\000"}, - {296, "for_stmt", 0, 10, states_40, - "\000\000\000\000\000\000\000\000\000\000\000\000\001\000\000\000\000\000\000\000\000"}, - {297, "try_stmt", 0, 13, states_41, - "\000\000\000\000\000\000\000\000\000\000\000\000\004\000\000\000\000\000\000\000\000"}, - {298, "with_stmt", 0, 5, states_42, - "\000\000\000\000\000\000\000\000\000\000\000\000\040\000\000\000\000\000\000\000\000"}, - {299, "with_item", 0, 4, states_43, - "\000\040\040\000\000\000\000\000\000\200\000\000\000\200\020\000\000\206\120\076\000"}, - {300, "except_clause", 0, 5, states_44, - "\000\000\000\000\000\000\000\000\000\000\000\000\000\001\000\000\000\000\000\000\000"}, - {301, "suite", 0, 5, states_45, - "\004\040\040\200\000\000\000\240\340\223\160\000\000\200\020\000\000\206\120\076\200"}, - {302, "test", 0, 6, states_46, - "\000\040\040\000\000\000\000\000\000\200\000\000\000\200\020\000\000\206\120\076\000"}, - {303, "test_nocond", 0, 2, states_47, - "\000\040\040\000\000\000\000\000\000\200\000\000\000\200\020\000\000\206\120\076\000"}, - {304, "lambdef", 0, 5, states_48, - "\000\000\000\000\000\000\000\000\000\000\000\000\000\200\000\000\000\000\000\000\000"}, - {305, "lambdef_nocond", 0, 5, states_49, - "\000\000\000\000\000\000\000\000\000\000\000\000\000\200\000\000\000\000\000\000\000"}, - {306, "or_test", 0, 2, states_50, - "\000\040\040\000\000\000\000\000\000\200\000\000\000\000\020\000\000\206\120\076\000"}, - {307, "and_test", 0, 2, states_51, - "\000\040\040\000\000\000\000\000\000\200\000\000\000\000\020\000\000\206\120\076\000"}, - {308, "not_test", 0, 3, states_52, - "\000\040\040\000\000\000\000\000\000\200\000\000\000\000\020\000\000\206\120\076\000"}, - {309, "comparison", 0, 2, states_53, - "\000\040\040\000\000\000\000\000\000\200\000\000\000\000\000\000\000\206\120\076\000"}, - {310, "comp_op", 0, 4, states_54, - "\000\000\000\000\000\000\000\000\000\000\000\000\002\000\220\177\000\000\000\000\000"}, - {311, "star_expr", 0, 3, states_55, - "\000\000\000\200\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000"}, - {312, "expr", 0, 2, states_56, - "\000\040\040\000\000\000\000\000\000\200\000\000\000\000\000\000\000\206\120\076\000"}, - {313, "xor_expr", 0, 2, states_57, - "\000\040\040\000\000\000\000\000\000\200\000\000\000\000\000\000\000\206\120\076\000"}, - {314, "and_expr", 0, 2, states_58, - "\000\040\040\000\000\000\000\000\000\200\000\000\000\000\000\000\000\206\120\076\000"}, - {315, "shift_expr", 0, 2, states_59, - "\000\040\040\000\000\000\000\000\000\200\000\000\000\000\000\000\000\206\120\076\000"}, - {316, "arith_expr", 0, 2, states_60, - "\000\040\040\000\000\000\000\000\000\200\000\000\000\000\000\000\000\206\120\076\000"}, - {317, "term", 0, 2, states_61, - "\000\040\040\000\000\000\000\000\000\200\000\000\000\000\000\000\000\206\120\076\000"}, - {318, "factor", 0, 3, states_62, - "\000\040\040\000\000\000\000\000\000\200\000\000\000\000\000\000\000\206\120\076\000"}, - {319, "power", 0, 4, states_63, - "\000\040\040\000\000\000\000\000\000\200\000\000\000\000\000\000\000\000\120\076\000"}, - {320, "atom", 0, 9, states_64, - "\000\040\040\000\000\000\000\000\000\200\000\000\000\000\000\000\000\000\120\076\000"}, - {321, "testlist_comp", 0, 5, states_65, - "\000\040\040\200\000\000\000\000\000\200\000\000\000\200\020\000\000\206\120\076\000"}, - {322, "trailer", 0, 7, states_66, - "\000\040\000\000\000\000\000\000\000\100\000\000\000\000\000\000\000\000\020\000\000"}, - {323, "subscriptlist", 0, 3, states_67, - "\000\040\040\002\000\000\000\000\000\200\000\000\000\200\020\000\000\206\120\076\000"}, - {324, "subscript", 0, 5, states_68, - "\000\040\040\002\000\000\000\000\000\200\000\000\000\200\020\000\000\206\120\076\000"}, - {325, "sliceop", 0, 3, states_69, - "\000\000\000\002\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000"}, - {326, "exprlist", 0, 3, states_70, - "\000\040\040\200\000\000\000\000\000\200\000\000\000\000\000\000\000\206\120\076\000"}, - {327, "testlist", 0, 3, states_71, - "\000\040\040\000\000\000\000\000\000\200\000\000\000\200\020\000\000\206\120\076\000"}, - {328, "dictorsetmaker", 0, 11, states_72, - "\000\040\040\000\000\000\000\000\000\200\000\000\000\200\020\000\000\206\120\076\000"}, - {329, "classdef", 0, 8, states_73, - "\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\004"}, - {330, "arglist", 0, 8, states_74, - "\000\040\040\200\001\000\000\000\000\200\000\000\000\200\020\000\000\206\120\076\000"}, - {331, "argument", 0, 4, states_75, - "\000\040\040\000\000\000\000\000\000\200\000\000\000\200\020\000\000\206\120\076\000"}, - {332, "comp_iter", 0, 2, states_76, - "\000\000\000\000\000\000\000\000\000\000\000\020\001\000\000\000\000\000\000\000\000"}, - {333, "comp_for", 0, 6, states_77, - "\000\000\000\000\000\000\000\000\000\000\000\000\001\000\000\000\000\000\000\000\000"}, - {334, "comp_if", 0, 4, states_78, - "\000\000\000\000\000\000\000\000\000\000\000\020\000\000\000\000\000\000\000\000\000"}, - {335, "encoding_decl", 0, 2, states_79, - "\000\000\040\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000"}, - {336, "yield_expr", 0, 3, states_80, - "\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\200"}, + {256, "single_input", 0, 3, states_0, + "\004\050\060\200\000\000\000\240\340\223\160\220\045\200\020\000\000\206\120\076\204"}, + {257, "file_input", 0, 2, states_1, + "\204\050\060\200\000\000\000\240\340\223\160\220\045\200\020\000\000\206\120\076\204"}, + {258, "eval_input", 0, 3, states_2, + "\000\040\040\000\000\000\000\000\000\200\000\000\000\200\020\000\000\206\120\076\000"}, + {259, "decorator", 0, 7, states_3, + "\000\010\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000"}, + {260, "decorators", 0, 2, states_4, + "\000\010\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000"}, + {261, "decorated", 0, 3, states_5, + "\000\010\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000"}, + {262, "funcdef", 0, 8, states_6, + "\000\000\020\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000"}, + {263, "parameters", 0, 4, states_7, + "\000\040\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000"}, + {264, "typedargslist", 0, 12, states_8, + "\000\000\040\200\001\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000"}, + {265, "tfpdef", 0, 4, states_9, + "\000\000\040\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000"}, + {266, "varargslist", 0, 12, states_10, + "\000\000\040\200\001\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000"}, + {267, "vfpdef", 0, 2, states_11, + "\000\000\040\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000"}, + {268, "stmt", 0, 2, states_12, + "\000\050\060\200\000\000\000\240\340\223\160\220\045\200\020\000\000\206\120\076\204"}, + {269, "simple_stmt", 0, 4, states_13, + "\000\040\040\200\000\000\000\240\340\223\160\000\000\200\020\000\000\206\120\076\200"}, + {270, "small_stmt", 0, 2, states_14, + "\000\040\040\200\000\000\000\240\340\223\160\000\000\200\020\000\000\206\120\076\200"}, + {271, "expr_stmt", 0, 6, states_15, + "\000\040\040\200\000\000\000\000\000\200\000\000\000\200\020\000\000\206\120\076\000"}, + {272, "testlist_star_expr", 0, 3, states_16, + "\000\040\040\200\000\000\000\000\000\200\000\000\000\200\020\000\000\206\120\076\000"}, + {273, "augassign", 0, 2, states_17, + "\000\000\000\000\000\000\376\037\000\000\000\000\000\000\000\000\000\000\000\000\000"}, + {274, "del_stmt", 0, 3, states_18, + "\000\000\000\000\000\000\000\040\000\000\000\000\000\000\000\000\000\000\000\000\000"}, + {275, "pass_stmt", 0, 2, states_19, + "\000\000\000\000\000\000\000\200\000\000\000\000\000\000\000\000\000\000\000\000\000"}, + {276, "flow_stmt", 0, 2, states_20, + "\000\000\000\000\000\000\000\000\340\001\000\000\000\000\000\000\000\000\000\000\200"}, + {277, "break_stmt", 0, 2, states_21, + "\000\000\000\000\000\000\000\000\040\000\000\000\000\000\000\000\000\000\000\000\000"}, + {278, "continue_stmt", 0, 2, states_22, + "\000\000\000\000\000\000\000\000\100\000\000\000\000\000\000\000\000\000\000\000\000"}, + {279, "return_stmt", 0, 3, states_23, + "\000\000\000\000\000\000\000\000\200\000\000\000\000\000\000\000\000\000\000\000\000"}, + {280, "yield_stmt", 0, 2, states_24, + "\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\200"}, + {281, "raise_stmt", 0, 5, states_25, + "\000\000\000\000\000\000\000\000\000\001\000\000\000\000\000\000\000\000\000\000\000"}, + {282, "import_stmt", 0, 2, states_26, + "\000\000\000\000\000\000\000\000\000\022\000\000\000\000\000\000\000\000\000\000\000"}, + {283, "import_name", 0, 3, states_27, + "\000\000\000\000\000\000\000\000\000\020\000\000\000\000\000\000\000\000\000\000\000"}, + {284, "import_from", 0, 8, states_28, + "\000\000\000\000\000\000\000\000\000\002\000\000\000\000\000\000\000\000\000\000\000"}, + {285, "import_as_name", 0, 4, states_29, + "\000\000\040\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000"}, + {286, "dotted_as_name", 0, 4, states_30, + "\000\000\040\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000"}, + {287, "import_as_names", 0, 3, states_31, + "\000\000\040\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000"}, + {288, "dotted_as_names", 0, 2, states_32, + "\000\000\040\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000"}, + {289, "dotted_name", 0, 2, states_33, + "\000\000\040\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000"}, + {290, "global_stmt", 0, 3, states_34, + "\000\000\000\000\000\000\000\000\000\000\020\000\000\000\000\000\000\000\000\000\000"}, + {291, "nonlocal_stmt", 0, 3, states_35, + "\000\000\000\000\000\000\000\000\000\000\040\000\000\000\000\000\000\000\000\000\000"}, + {292, "assert_stmt", 0, 5, states_36, + "\000\000\000\000\000\000\000\000\000\000\100\000\000\000\000\000\000\000\000\000\000"}, + {293, "compound_stmt", 0, 2, states_37, + "\000\010\020\000\000\000\000\000\000\000\000\220\045\000\000\000\000\000\000\000\004"}, + {294, "if_stmt", 0, 8, states_38, + "\000\000\000\000\000\000\000\000\000\000\000\020\000\000\000\000\000\000\000\000\000"}, + {295, "while_stmt", 0, 8, states_39, + "\000\000\000\000\000\000\000\000\000\000\000\200\000\000\000\000\000\000\000\000\000"}, + {296, "for_stmt", 0, 10, states_40, + "\000\000\000\000\000\000\000\000\000\000\000\000\001\000\000\000\000\000\000\000\000"}, + {297, "try_stmt", 0, 13, states_41, + "\000\000\000\000\000\000\000\000\000\000\000\000\004\000\000\000\000\000\000\000\000"}, + {298, "with_stmt", 0, 5, states_42, + "\000\000\000\000\000\000\000\000\000\000\000\000\040\000\000\000\000\000\000\000\000"}, + {299, "with_item", 0, 4, states_43, + "\000\040\040\000\000\000\000\000\000\200\000\000\000\200\020\000\000\206\120\076\000"}, + {300, "except_clause", 0, 5, states_44, + "\000\000\000\000\000\000\000\000\000\000\000\000\000\001\000\000\000\000\000\000\000"}, + {301, "suite", 0, 5, states_45, + "\004\040\040\200\000\000\000\240\340\223\160\000\000\200\020\000\000\206\120\076\200"}, + {302, "test", 0, 6, states_46, + "\000\040\040\000\000\000\000\000\000\200\000\000\000\200\020\000\000\206\120\076\000"}, + {303, "test_nocond", 0, 2, states_47, + "\000\040\040\000\000\000\000\000\000\200\000\000\000\200\020\000\000\206\120\076\000"}, + {304, "lambdef", 0, 5, states_48, + "\000\000\000\000\000\000\000\000\000\000\000\000\000\200\000\000\000\000\000\000\000"}, + {305, "lambdef_nocond", 0, 5, states_49, + "\000\000\000\000\000\000\000\000\000\000\000\000\000\200\000\000\000\000\000\000\000"}, + {306, "or_test", 0, 2, states_50, + "\000\040\040\000\000\000\000\000\000\200\000\000\000\000\020\000\000\206\120\076\000"}, + {307, "and_test", 0, 2, states_51, + "\000\040\040\000\000\000\000\000\000\200\000\000\000\000\020\000\000\206\120\076\000"}, + {308, "not_test", 0, 3, states_52, + "\000\040\040\000\000\000\000\000\000\200\000\000\000\000\020\000\000\206\120\076\000"}, + {309, "comparison", 0, 2, states_53, + "\000\040\040\000\000\000\000\000\000\200\000\000\000\000\000\000\000\206\120\076\000"}, + {310, "comp_op", 0, 4, states_54, + "\000\000\000\000\000\000\000\000\000\000\000\000\002\000\220\177\000\000\000\000\000"}, + {311, "star_expr", 0, 3, states_55, + "\000\000\000\200\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000"}, + {312, "expr", 0, 2, states_56, + "\000\040\040\000\000\000\000\000\000\200\000\000\000\000\000\000\000\206\120\076\000"}, + {313, "xor_expr", 0, 2, states_57, + "\000\040\040\000\000\000\000\000\000\200\000\000\000\000\000\000\000\206\120\076\000"}, + {314, "and_expr", 0, 2, states_58, + "\000\040\040\000\000\000\000\000\000\200\000\000\000\000\000\000\000\206\120\076\000"}, + {315, "shift_expr", 0, 2, states_59, + "\000\040\040\000\000\000\000\000\000\200\000\000\000\000\000\000\000\206\120\076\000"}, + {316, "arith_expr", 0, 2, states_60, + "\000\040\040\000\000\000\000\000\000\200\000\000\000\000\000\000\000\206\120\076\000"}, + {317, "term", 0, 2, states_61, + "\000\040\040\000\000\000\000\000\000\200\000\000\000\000\000\000\000\206\120\076\000"}, + {318, "factor", 0, 3, states_62, + "\000\040\040\000\000\000\000\000\000\200\000\000\000\000\000\000\000\206\120\076\000"}, + {319, "power", 0, 4, states_63, + "\000\040\040\000\000\000\000\000\000\200\000\000\000\000\000\000\000\000\120\076\000"}, + {320, "atom", 0, 9, states_64, + "\000\040\040\000\000\000\000\000\000\200\000\000\000\000\000\000\000\000\120\076\000"}, + {321, "testlist_comp", 0, 5, states_65, + "\000\040\040\200\000\000\000\000\000\200\000\000\000\200\020\000\000\206\120\076\000"}, + {322, "trailer", 0, 7, states_66, + "\000\040\000\000\000\000\000\000\000\100\000\000\000\000\000\000\000\000\020\000\000"}, + {323, "subscriptlist", 0, 3, states_67, + "\000\040\040\002\000\000\000\000\000\200\000\000\000\200\020\000\000\206\120\076\000"}, + {324, "subscript", 0, 5, states_68, + "\000\040\040\002\000\000\000\000\000\200\000\000\000\200\020\000\000\206\120\076\000"}, + {325, "sliceop", 0, 3, states_69, + "\000\000\000\002\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000"}, + {326, "exprlist", 0, 3, states_70, + "\000\040\040\200\000\000\000\000\000\200\000\000\000\000\000\000\000\206\120\076\000"}, + {327, "testlist", 0, 3, states_71, + "\000\040\040\000\000\000\000\000\000\200\000\000\000\200\020\000\000\206\120\076\000"}, + {328, "dictorsetmaker", 0, 11, states_72, + "\000\040\040\000\000\000\000\000\000\200\000\000\000\200\020\000\000\206\120\076\000"}, + {329, "classdef", 0, 8, states_73, + "\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\004"}, + {330, "arglist", 0, 8, states_74, + "\000\040\040\200\001\000\000\000\000\200\000\000\000\200\020\000\000\206\120\076\000"}, + {331, "argument", 0, 4, states_75, + "\000\040\040\000\000\000\000\000\000\200\000\000\000\200\020\000\000\206\120\076\000"}, + {332, "comp_iter", 0, 2, states_76, + "\000\000\000\000\000\000\000\000\000\000\000\020\001\000\000\000\000\000\000\000\000"}, + {333, "comp_for", 0, 6, states_77, + "\000\000\000\000\000\000\000\000\000\000\000\000\001\000\000\000\000\000\000\000\000"}, + {334, "comp_if", 0, 4, states_78, + "\000\000\000\000\000\000\000\000\000\000\000\020\000\000\000\000\000\000\000\000\000"}, + {335, "encoding_decl", 0, 2, states_79, + "\000\000\040\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000"}, + {336, "yield_expr", 0, 3, states_80, + "\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\200"}, }; static label labels[168] = { - {0, "EMPTY"}, - {256, 0}, - {4, 0}, - {269, 0}, - {293, 0}, - {257, 0}, - {268, 0}, - {0, 0}, - {258, 0}, - {327, 0}, - {259, 0}, - {50, 0}, - {289, 0}, - {7, 0}, - {330, 0}, - {8, 0}, - {260, 0}, - {261, 0}, - {329, 0}, - {262, 0}, - {1, "def"}, - {1, 0}, - {263, 0}, - {51, 0}, - {302, 0}, - {11, 0}, - {301, 0}, - {264, 0}, - {265, 0}, - {22, 0}, - {12, 0}, - {16, 0}, - {36, 0}, - {266, 0}, - {267, 0}, - {270, 0}, - {13, 0}, - {271, 0}, - {274, 0}, - {275, 0}, - {276, 0}, - {282, 0}, - {290, 0}, - {291, 0}, - {292, 0}, - {272, 0}, - {273, 0}, - {336, 0}, - {311, 0}, - {37, 0}, - {38, 0}, - {39, 0}, - {40, 0}, - {41, 0}, - {42, 0}, - {43, 0}, - {44, 0}, - {45, 0}, - {46, 0}, - {47, 0}, - {49, 0}, - {1, "del"}, - {326, 0}, - {1, "pass"}, - {277, 0}, - {278, 0}, - {279, 0}, - {281, 0}, - {280, 0}, - {1, "break"}, - {1, "continue"}, - {1, "return"}, - {1, "raise"}, - {1, "from"}, - {283, 0}, - {284, 0}, - {1, "import"}, - {288, 0}, - {23, 0}, - {52, 0}, - {287, 0}, - {285, 0}, - {1, "as"}, - {286, 0}, - {1, "global"}, - {1, "nonlocal"}, - {1, "assert"}, - {294, 0}, - {295, 0}, - {296, 0}, - {297, 0}, - {298, 0}, - {1, "if"}, - {1, "elif"}, - {1, "else"}, - {1, "while"}, - {1, "for"}, - {1, "in"}, - {1, "try"}, - {300, 0}, - {1, "finally"}, - {1, "with"}, - {299, 0}, - {312, 0}, - {1, "except"}, - {5, 0}, - {6, 0}, - {306, 0}, - {304, 0}, - {303, 0}, - {305, 0}, - {1, "lambda"}, - {307, 0}, - {1, "or"}, - {308, 0}, - {1, "and"}, - {1, "not"}, - {309, 0}, - {310, 0}, - {20, 0}, - {21, 0}, - {28, 0}, - {31, 0}, - {30, 0}, - {29, 0}, - {29, 0}, - {1, "is"}, - {313, 0}, - {18, 0}, - {314, 0}, - {33, 0}, - {315, 0}, - {19, 0}, - {316, 0}, - {34, 0}, - {35, 0}, - {317, 0}, - {14, 0}, - {15, 0}, - {318, 0}, - {17, 0}, - {24, 0}, - {48, 0}, - {32, 0}, - {319, 0}, - {320, 0}, - {322, 0}, - {321, 0}, - {9, 0}, - {10, 0}, - {26, 0}, - {328, 0}, - {27, 0}, - {2, 0}, - {3, 0}, - {1, "None"}, - {1, "True"}, - {1, "False"}, - {333, 0}, - {323, 0}, - {324, 0}, - {325, 0}, - {1, "class"}, - {331, 0}, - {332, 0}, - {334, 0}, - {335, 0}, - {1, "yield"}, + {0, "EMPTY"}, + {256, 0}, + {4, 0}, + {269, 0}, + {293, 0}, + {257, 0}, + {268, 0}, + {0, 0}, + {258, 0}, + {327, 0}, + {259, 0}, + {50, 0}, + {289, 0}, + {7, 0}, + {330, 0}, + {8, 0}, + {260, 0}, + {261, 0}, + {329, 0}, + {262, 0}, + {1, "def"}, + {1, 0}, + {263, 0}, + {51, 0}, + {302, 0}, + {11, 0}, + {301, 0}, + {264, 0}, + {265, 0}, + {22, 0}, + {12, 0}, + {16, 0}, + {36, 0}, + {266, 0}, + {267, 0}, + {270, 0}, + {13, 0}, + {271, 0}, + {274, 0}, + {275, 0}, + {276, 0}, + {282, 0}, + {290, 0}, + {291, 0}, + {292, 0}, + {272, 0}, + {273, 0}, + {336, 0}, + {311, 0}, + {37, 0}, + {38, 0}, + {39, 0}, + {40, 0}, + {41, 0}, + {42, 0}, + {43, 0}, + {44, 0}, + {45, 0}, + {46, 0}, + {47, 0}, + {49, 0}, + {1, "del"}, + {326, 0}, + {1, "pass"}, + {277, 0}, + {278, 0}, + {279, 0}, + {281, 0}, + {280, 0}, + {1, "break"}, + {1, "continue"}, + {1, "return"}, + {1, "raise"}, + {1, "from"}, + {283, 0}, + {284, 0}, + {1, "import"}, + {288, 0}, + {23, 0}, + {52, 0}, + {287, 0}, + {285, 0}, + {1, "as"}, + {286, 0}, + {1, "global"}, + {1, "nonlocal"}, + {1, "assert"}, + {294, 0}, + {295, 0}, + {296, 0}, + {297, 0}, + {298, 0}, + {1, "if"}, + {1, "elif"}, + {1, "else"}, + {1, "while"}, + {1, "for"}, + {1, "in"}, + {1, "try"}, + {300, 0}, + {1, "finally"}, + {1, "with"}, + {299, 0}, + {312, 0}, + {1, "except"}, + {5, 0}, + {6, 0}, + {306, 0}, + {304, 0}, + {303, 0}, + {305, 0}, + {1, "lambda"}, + {307, 0}, + {1, "or"}, + {308, 0}, + {1, "and"}, + {1, "not"}, + {309, 0}, + {310, 0}, + {20, 0}, + {21, 0}, + {28, 0}, + {31, 0}, + {30, 0}, + {29, 0}, + {29, 0}, + {1, "is"}, + {313, 0}, + {18, 0}, + {314, 0}, + {33, 0}, + {315, 0}, + {19, 0}, + {316, 0}, + {34, 0}, + {35, 0}, + {317, 0}, + {14, 0}, + {15, 0}, + {318, 0}, + {17, 0}, + {24, 0}, + {48, 0}, + {32, 0}, + {319, 0}, + {320, 0}, + {322, 0}, + {321, 0}, + {9, 0}, + {10, 0}, + {26, 0}, + {328, 0}, + {27, 0}, + {2, 0}, + {3, 0}, + {1, "None"}, + {1, "True"}, + {1, "False"}, + {333, 0}, + {323, 0}, + {324, 0}, + {325, 0}, + {1, "class"}, + {331, 0}, + {332, 0}, + {334, 0}, + {335, 0}, + {1, "yield"}, }; grammar _PyParser_Grammar = { - 81, - dfas, - {168, labels}, - 256 + 81, + dfas, + {168, labels}, + 256 }; Modified: python/branches/py3k-cdecimal/Python/pythonrun.c ============================================================================== --- python/branches/py3k-cdecimal/Python/pythonrun.c (original) +++ python/branches/py3k-cdecimal/Python/pythonrun.c Wed May 19 17:30:16 2010 @@ -138,8 +138,8 @@ static char* get_codeset(void) { - char* codeset; - PyObject *codec, *name; + char* codeset, *name_str; + PyObject *codec, *name = NULL; codeset = nl_langinfo(CODESET); if (!codeset || codeset[0] == '\0') @@ -154,12 +154,16 @@ if (!name) goto error; - codeset = strdup(_PyUnicode_AsString(name)); + name_str = _PyUnicode_AsString(name); + if (name == NULL) + goto error; + codeset = strdup(name_str); Py_DECREF(name); return codeset; error: Py_XDECREF(codec); + Py_XDECREF(name); return NULL; } #endif @@ -1060,22 +1064,34 @@ if (!oenc) return -1; enc = _PyUnicode_AsString(oenc); + if (enc == NULL) + return -1; } v = PySys_GetObject("ps1"); if (v != NULL) { v = PyObject_Str(v); if (v == NULL) PyErr_Clear(); - else if (PyUnicode_Check(v)) + else if (PyUnicode_Check(v)) { ps1 = _PyUnicode_AsString(v); + if (ps1 == NULL) { + PyErr_Clear(); + ps1 = ""; + } + } } w = PySys_GetObject("ps2"); if (w != NULL) { w = PyObject_Str(w); if (w == NULL) PyErr_Clear(); - else if (PyUnicode_Check(w)) + else if (PyUnicode_Check(w)) { ps2 = _PyUnicode_AsString(w); + if (ps2 == NULL) { + PyErr_Clear(); + ps2 = ""; + } + } } arena = PyArena_New(); if (arena == NULL) { @@ -1367,7 +1383,11 @@ if (PyLong_Check(value)) exitcode = (int)PyLong_AsLong(value); else { + PyObject *sys_stderr = PySys_GetObject("stderr"); + if (sys_stderr != NULL) + PyObject_CallMethod(sys_stderr, "flush", NULL); PyObject_Print(value, stderr, Py_PRINT_RAW); + fflush(stderr); PySys_WriteStderr("\n"); exitcode = 1; } From python-checkins at python.org Wed May 19 17:46:39 2010 From: python-checkins at python.org (stefan.krah) Date: Wed, 19 May 2010 17:46:39 +0200 (CEST) Subject: [Python-checkins] r81350 - python/trunk/Lib/decimal.py Message-ID: <20100519154639.4190DEE9CD@mail.python.org> Author: stefan.krah Date: Wed May 19 17:46:39 2010 New Revision: 81350 Log: Fix typos in docstrings. Modified: python/trunk/Lib/decimal.py Modified: python/trunk/Lib/decimal.py ============================================================================== --- python/trunk/Lib/decimal.py (original) +++ python/trunk/Lib/decimal.py Wed May 19 17:46:39 2010 @@ -168,7 +168,7 @@ anything, though. handle -- Called when context._raise_error is called and the - trap_enabler is set. First argument is self, second is the + trap_enabler is not set. First argument is self, second is the context. More arguments can be given, those being after the explanation in _raise_error (For example, context._raise_error(NewError, '(-x)!', self._sign) would @@ -3807,7 +3807,7 @@ If the flag is in _ignored_flags, returns the default response. Otherwise, it sets the flag, then, if the corresponding - trap_enabler is set, it reaises the exception. Otherwise, it returns + trap_enabler is set, it reraises the exception. Otherwise, it returns the default value after setting the flag. """ error = _condition_map.get(condition, condition) From python-checkins at python.org Wed May 19 17:50:05 2010 From: python-checkins at python.org (stefan.krah) Date: Wed, 19 May 2010 17:50:05 +0200 (CEST) Subject: [Python-checkins] r81351 - in python/branches/release26-maint: Lib/decimal.py Message-ID: <20100519155005.EDEFCC566@mail.python.org> Author: stefan.krah Date: Wed May 19 17:50:05 2010 New Revision: 81351 Log: Merged revisions 81350 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r81350 | stefan.krah | 2010-05-19 17:46:39 +0200 (Wed, 19 May 2010) | 1 line Fix typos in docstrings. ........ Modified: python/branches/release26-maint/ (props changed) python/branches/release26-maint/Lib/decimal.py Modified: python/branches/release26-maint/Lib/decimal.py ============================================================================== --- python/branches/release26-maint/Lib/decimal.py (original) +++ python/branches/release26-maint/Lib/decimal.py Wed May 19 17:50:05 2010 @@ -165,7 +165,7 @@ anything, though. handle -- Called when context._raise_error is called and the - trap_enabler is set. First argument is self, second is the + trap_enabler is not set. First argument is self, second is the context. More arguments can be given, those being after the explanation in _raise_error (For example, context._raise_error(NewError, '(-x)!', self._sign) would @@ -3741,7 +3741,7 @@ If the flag is in _ignored_flags, returns the default response. Otherwise, it sets the flag, then, if the corresponding - trap_enabler is set, it reaises the exception. Otherwise, it returns + trap_enabler is set, it reraises the exception. Otherwise, it returns the default value after setting the flag. """ error = _condition_map.get(condition, condition) From python-checkins at python.org Wed May 19 17:52:31 2010 From: python-checkins at python.org (stefan.krah) Date: Wed, 19 May 2010 17:52:31 +0200 (CEST) Subject: [Python-checkins] r81352 - in python/branches/py3k: Lib/decimal.py Message-ID: <20100519155231.61025FB07@mail.python.org> Author: stefan.krah Date: Wed May 19 17:52:31 2010 New Revision: 81352 Log: Merged revisions 81350 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r81350 | stefan.krah | 2010-05-19 17:46:39 +0200 (Wed, 19 May 2010) | 1 line Fix typos in docstrings. ........ Modified: python/branches/py3k/ (props changed) python/branches/py3k/Lib/decimal.py Modified: python/branches/py3k/Lib/decimal.py ============================================================================== --- python/branches/py3k/Lib/decimal.py (original) +++ python/branches/py3k/Lib/decimal.py Wed May 19 17:52:31 2010 @@ -164,7 +164,7 @@ anything, though. handle -- Called when context._raise_error is called and the - trap_enabler is set. First argument is self, second is the + trap_enabler is not set. First argument is self, second is the context. More arguments can be given, those being after the explanation in _raise_error (For example, context._raise_error(NewError, '(-x)!', self._sign) would @@ -3888,7 +3888,7 @@ If the flag is in _ignored_flags, returns the default response. Otherwise, it sets the flag, then, if the corresponding - trap_enabler is set, it reaises the exception. Otherwise, it returns + trap_enabler is set, it reraises the exception. Otherwise, it returns the default value after setting the flag. """ error = _condition_map.get(condition, condition) From python-checkins at python.org Wed May 19 17:54:54 2010 From: python-checkins at python.org (stefan.krah) Date: Wed, 19 May 2010 17:54:54 +0200 (CEST) Subject: [Python-checkins] r81353 - in python/branches/release31-maint: Lib/decimal.py Message-ID: <20100519155454.DE1C4EE9EA@mail.python.org> Author: stefan.krah Date: Wed May 19 17:54:54 2010 New Revision: 81353 Log: Merged revisions 81352 via svnmerge from svn+ssh://pythondev at svn.python.org/python/branches/py3k ................ r81352 | stefan.krah | 2010-05-19 17:52:31 +0200 (Wed, 19 May 2010) | 9 lines Merged revisions 81350 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r81350 | stefan.krah | 2010-05-19 17:46:39 +0200 (Wed, 19 May 2010) | 1 line Fix typos in docstrings. ........ ................ Modified: python/branches/release31-maint/ (props changed) python/branches/release31-maint/Lib/decimal.py Modified: python/branches/release31-maint/Lib/decimal.py ============================================================================== --- python/branches/release31-maint/Lib/decimal.py (original) +++ python/branches/release31-maint/Lib/decimal.py Wed May 19 17:54:54 2010 @@ -164,7 +164,7 @@ anything, though. handle -- Called when context._raise_error is called and the - trap_enabler is set. First argument is self, second is the + trap_enabler is not set. First argument is self, second is the context. More arguments can be given, those being after the explanation in _raise_error (For example, context._raise_error(NewError, '(-x)!', self._sign) would @@ -3858,7 +3858,7 @@ If the flag is in _ignored_flags, returns the default response. Otherwise, it sets the flag, then, if the corresponding - trap_enabler is set, it reaises the exception. Otherwise, it returns + trap_enabler is set, it reraises the exception. Otherwise, it returns the default value after setting the flag. """ error = _condition_map.get(condition, condition) From python-checkins at python.org Wed May 19 17:59:40 2010 From: python-checkins at python.org (stefan.krah) Date: Wed, 19 May 2010 17:59:40 +0200 (CEST) Subject: [Python-checkins] r81354 - python/trunk/Doc/library/unittest.rst Message-ID: <20100519155940.ADC3AEE9A4@mail.python.org> Author: stefan.krah Date: Wed May 19 17:59:40 2010 New Revision: 81354 Log: Fix typo. Modified: python/trunk/Doc/library/unittest.rst Modified: python/trunk/Doc/library/unittest.rst ============================================================================== --- python/trunk/Doc/library/unittest.rst (original) +++ python/trunk/Doc/library/unittest.rst Wed May 19 17:59:40 2010 @@ -752,7 +752,7 @@ .. method:: skipTest(reason) - Calling this during the a test method or :meth:`setUp` skips the current + Calling this during a test method or :meth:`setUp` skips the current test. See :ref:`unittest-skipping` for more information. .. versionadded:: 2.7 From python-checkins at python.org Wed May 19 18:08:15 2010 From: python-checkins at python.org (stefan.krah) Date: Wed, 19 May 2010 18:08:15 +0200 (CEST) Subject: [Python-checkins] r81355 - python/branches/release26-maint Message-ID: <20100519160815.237C3EEA01@mail.python.org> Author: stefan.krah Date: Wed May 19 18:08:15 2010 New Revision: 81355 Log: Blocked revisions 81354 via svnmerge ........ r81354 | stefan.krah | 2010-05-19 17:59:40 +0200 (Wed, 19 May 2010) | 3 lines Fix typo. ........ Modified: python/branches/release26-maint/ (props changed) From python-checkins at python.org Wed May 19 18:09:41 2010 From: python-checkins at python.org (stefan.krah) Date: Wed, 19 May 2010 18:09:41 +0200 (CEST) Subject: [Python-checkins] r81356 - in python/branches/py3k: Doc/library/unittest.rst Message-ID: <20100519160941.ED731EF02@mail.python.org> Author: stefan.krah Date: Wed May 19 18:09:41 2010 New Revision: 81356 Log: Merged revisions 81354 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r81354 | stefan.krah | 2010-05-19 17:59:40 +0200 (Wed, 19 May 2010) | 3 lines Fix typo. ........ Modified: python/branches/py3k/ (props changed) python/branches/py3k/Doc/library/unittest.rst Modified: python/branches/py3k/Doc/library/unittest.rst ============================================================================== --- python/branches/py3k/Doc/library/unittest.rst (original) +++ python/branches/py3k/Doc/library/unittest.rst Wed May 19 18:09:41 2010 @@ -749,7 +749,7 @@ .. method:: skipTest(reason) - Calling this during the a test method or :meth:`setUp` skips the current + Calling this during a test method or :meth:`setUp` skips the current test. See :ref:`unittest-skipping` for more information. .. versionadded:: 3.1 From python-checkins at python.org Wed May 19 18:11:36 2010 From: python-checkins at python.org (stefan.krah) Date: Wed, 19 May 2010 18:11:36 +0200 (CEST) Subject: [Python-checkins] r81357 - in python/branches/release31-maint: Doc/library/unittest.rst Message-ID: <20100519161136.EA0BDEE9DB@mail.python.org> Author: stefan.krah Date: Wed May 19 18:11:36 2010 New Revision: 81357 Log: Merged revisions 81356 via svnmerge from svn+ssh://pythondev at svn.python.org/python/branches/py3k ................ r81356 | stefan.krah | 2010-05-19 18:09:41 +0200 (Wed, 19 May 2010) | 9 lines Merged revisions 81354 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r81354 | stefan.krah | 2010-05-19 17:59:40 +0200 (Wed, 19 May 2010) | 3 lines Fix typo. ........ ................ Modified: python/branches/release31-maint/ (props changed) python/branches/release31-maint/Doc/library/unittest.rst Modified: python/branches/release31-maint/Doc/library/unittest.rst ============================================================================== --- python/branches/release31-maint/Doc/library/unittest.rst (original) +++ python/branches/release31-maint/Doc/library/unittest.rst Wed May 19 18:11:36 2010 @@ -589,7 +589,7 @@ .. method:: skipTest(reason) - Calling this during the a test method or :meth:`setUp` skips the current + Calling this during a test method or :meth:`setUp` skips the current test. See :ref:`unittest-skipping` for more information. .. versionadded:: 3.1 From python-checkins at python.org Wed May 19 18:53:30 2010 From: python-checkins at python.org (victor.stinner) Date: Wed, 19 May 2010 18:53:30 +0200 (CEST) Subject: [Python-checkins] r81358 - in python/branches/py3k: Doc/c-api/sys.rst Include/sysmodule.h Misc/NEWS Modules/main.c Python/sysmodule.c Message-ID: <20100519165330.3EF18EBB7@mail.python.org> Author: victor.stinner Date: Wed May 19 18:53:30 2010 New Revision: 81358 Log: Issue #8589: Decode PYTHONWARNINGS environment variable with the file system encoding and surrogateespace error handler instead of the locale encoding to be consistent with os.environ. Add PySys_AddWarnOptionUnicode() function. Modified: python/branches/py3k/Doc/c-api/sys.rst python/branches/py3k/Include/sysmodule.h python/branches/py3k/Misc/NEWS python/branches/py3k/Modules/main.c python/branches/py3k/Python/sysmodule.c Modified: python/branches/py3k/Doc/c-api/sys.rst ============================================================================== --- python/branches/py3k/Doc/c-api/sys.rst (original) +++ python/branches/py3k/Doc/c-api/sys.rst Wed May 19 18:53:30 2010 @@ -81,6 +81,10 @@ Append *s* to :data:`sys.warnoptions`. +.. cfunction:: void PySys_AddWarnOptionUnicode(PyObject *unicode) + + Append *unicode* to :data:`sys.warnoptions`. + .. cfunction:: void PySys_SetPath(wchar_t *path) Set :data:`sys.path` to a list object of paths found in *path* which should Modified: python/branches/py3k/Include/sysmodule.h ============================================================================== --- python/branches/py3k/Include/sysmodule.h (original) +++ python/branches/py3k/Include/sysmodule.h Wed May 19 18:53:30 2010 @@ -21,6 +21,7 @@ PyAPI_FUNC(void) PySys_ResetWarnOptions(void); PyAPI_FUNC(void) PySys_AddWarnOption(const wchar_t *); +PyAPI_FUNC(void) PySys_AddWarnOptionUnicode(PyObject *); PyAPI_FUNC(int) PySys_HasWarnOptions(void); #ifdef __cplusplus Modified: python/branches/py3k/Misc/NEWS ============================================================================== --- python/branches/py3k/Misc/NEWS (original) +++ python/branches/py3k/Misc/NEWS Wed May 19 18:53:30 2010 @@ -12,6 +12,10 @@ Core and Builtins ----------------- +- Issue #8589: Decode PYTHONWARNINGS environment variable with the file system + encoding and surrogateespace error handler instead of the locale encoding to + be consistent with os.environ. Add PySys_AddWarnOptionUnicode() function. + - PyObject_Dump() encodes unicode objects to utf8 with backslashreplace (instead of strict) error handler to escape surrogates Modified: python/branches/py3k/Modules/main.c ============================================================================== --- python/branches/py3k/Modules/main.c (original) +++ python/branches/py3k/Modules/main.c Wed May 19 18:53:30 2010 @@ -425,7 +425,7 @@ #else if ((p = Py_GETENV("PYTHONWARNINGS")) && *p != '\0') { char *buf, *oldloc; - wchar_t *warning; + PyObject *warning; /* settle for strtok here as there's no one standard C89 wcstok */ @@ -437,9 +437,10 @@ oldloc = strdup(setlocale(LC_ALL, NULL)); setlocale(LC_ALL, ""); for (p = strtok(buf, ","); p != NULL; p = strtok(NULL, ",")) { - if ((warning = _Py_char2wchar(p)) != NULL) { - PySys_AddWarnOption(warning); - PyMem_Free(warning); + warning = PyUnicode_DecodeFSDefault(p); + if (warning != NULL) { + PySys_AddWarnOptionUnicode(warning); + Py_DECREF(warning); } } setlocale(LC_ALL, oldloc); Modified: python/branches/py3k/Python/sysmodule.c ============================================================================== --- python/branches/py3k/Python/sysmodule.c (original) +++ python/branches/py3k/Python/sysmodule.c Wed May 19 18:53:30 2010 @@ -1048,21 +1048,26 @@ } void -PySys_AddWarnOption(const wchar_t *s) +PySys_AddWarnOptionUnicode(PyObject *unicode) { - PyObject *str; - if (warnoptions == NULL || !PyList_Check(warnoptions)) { Py_XDECREF(warnoptions); warnoptions = PyList_New(0); if (warnoptions == NULL) return; } - str = PyUnicode_FromWideChar(s, -1); - if (str != NULL) { - PyList_Append(warnoptions, str); - Py_DECREF(str); - } + PyList_Append(warnoptions, unicode); +} + +void +PySys_AddWarnOption(const wchar_t *s) +{ + PyObject *unicode; + unicode = PyUnicode_FromWideChar(s, -1); + if (unicode == NULL) + return; + PySys_AddWarnOptionUnicode(unicode); + Py_DECREF(unicode); } int From python-checkins at python.org Wed May 19 19:00:07 2010 From: python-checkins at python.org (victor.stinner) Date: Wed, 19 May 2010 19:00:07 +0200 (CEST) Subject: [Python-checkins] r81359 - in python/branches/py3k: Lib/distutils/log.py Misc/NEWS Message-ID: <20100519170007.72994E69E@mail.python.org> Author: victor.stinner Date: Wed May 19 19:00:07 2010 New Revision: 81359 Log: Issue #8663: distutils.log emulates backslashreplace error handler. Fix compilation in a non-ASCII directory if stdout encoding is ASCII (eg. if stdout is not a TTY). Modified: python/branches/py3k/Lib/distutils/log.py python/branches/py3k/Misc/NEWS Modified: python/branches/py3k/Lib/distutils/log.py ============================================================================== --- python/branches/py3k/Lib/distutils/log.py (original) +++ python/branches/py3k/Lib/distutils/log.py Wed May 19 19:00:07 2010 @@ -27,6 +27,10 @@ stream = sys.stderr else: stream = sys.stdout + if stream.errors == 'strict': + # emulate backslashreplace error handler + encoding = stream.encoding + msg = msg.encode(encoding, "backslashreplace").decode(encoding) stream.write('%s\n' % msg) stream.flush() Modified: python/branches/py3k/Misc/NEWS ============================================================================== --- python/branches/py3k/Misc/NEWS (original) +++ python/branches/py3k/Misc/NEWS Wed May 19 19:00:07 2010 @@ -370,6 +370,10 @@ Library ------- +- Issue #8663: distutils.log emulates backslashreplace error handler. Fix + compilation in a non-ASCII directory if stdout encoding is ASCII (eg. if + stdout is not a TTY). + - Issue #8513: os.get_exec_path() supports b'PATH' key and bytes value. subprocess.Popen() and os._execvpe() support bytes program name. Add os.supports_bytes_environ flag: True if the native OS type of the environment From python-checkins at python.org Wed May 19 19:11:19 2010 From: python-checkins at python.org (victor.stinner) Date: Wed, 19 May 2010 19:11:19 +0200 (CEST) Subject: [Python-checkins] r81360 - python/branches/py3k/Lib/test/regrtest.py Message-ID: <20100519171119.C918FEE9A3@mail.python.org> Author: victor.stinner Date: Wed May 19 19:11:19 2010 New Revision: 81360 Log: regrtest.py: call replace_stdout() before the first call to print() print("== ", os.getcwd()) fails if the current working directory is not ASCII whereas sys.stdout encoding is ASCII. Modified: python/branches/py3k/Lib/test/regrtest.py Modified: python/branches/py3k/Lib/test/regrtest.py ============================================================================== --- python/branches/py3k/Lib/test/regrtest.py (original) +++ python/branches/py3k/Lib/test/regrtest.py Wed May 19 19:11:19 2010 @@ -258,6 +258,8 @@ on the command line. """ + replace_stdout() + support.record_original_stdout(sys.stdout) try: opts, args = getopt.getopt(sys.argv[1:], 'hvqxsSrf:lu:t:TD:NLR:FwWM:nj:', @@ -376,7 +378,6 @@ elif o in ('-j', '--multiprocess'): use_mp = int(a) elif o == '--slaveargs': - replace_stdout() args, kwargs = json.loads(a) try: result = runtest(*args, **kwargs) @@ -515,8 +516,6 @@ else: tests = iter(selected) - replace_stdout() - if use_mp: try: from threading import Thread From python-checkins at python.org Wed May 19 19:15:50 2010 From: python-checkins at python.org (victor.stinner) Date: Wed, 19 May 2010 19:15:50 +0200 (CEST) Subject: [Python-checkins] r81361 - python/branches/py3k/Lib/distutils/tests/test_log.py Message-ID: <20100519171550.DF5A7EE9D0@mail.python.org> Author: victor.stinner Date: Wed May 19 19:15:50 2010 New Revision: 81361 Log: Oops, add the new test_log.py for distutils test suite (missing part of r81359) Added: python/branches/py3k/Lib/distutils/tests/test_log.py Added: python/branches/py3k/Lib/distutils/tests/test_log.py ============================================================================== --- (empty file) +++ python/branches/py3k/Lib/distutils/tests/test_log.py Wed May 19 19:15:50 2010 @@ -0,0 +1,36 @@ +"""Tests for distutils.log""" + +import sys +import unittest +from tempfile import NamedTemporaryFile + +from distutils import log + +class TestLog(unittest.TestCase): + def test_non_ascii(self): + # Issue #8663: test that non-ASCII text is escaped with + # backslashreplace error handler (stream use ASCII encoding and strict + # error handler) + old_stdout = sys.stdout + old_stderr = sys.stderr + try: + log.set_threshold(log.DEBUG) + with NamedTemporaryFile(mode="w+", encoding='ascii') as stdout, \ + NamedTemporaryFile(mode="w+", encoding='ascii') as stderr: + sys.stdout = stdout + sys.stderr = stderr + log.debug("debug:\xe9") + log.fatal("fatal:\xe9") + stdout.seek(0) + self.assertEquals(stdout.read().rstrip(), "debug:\\xe9") + stderr.seek(0) + self.assertEquals(stderr.read().rstrip(), "fatal:\\xe9") + finally: + sys.stdout = old_stdout + sys.stderr = old_stderr + +def test_suite(): + return unittest.makeSuite(TestLog) + +if __name__ == "__main__": + unittest.main(defaultTest="test_suite") From python-checkins at python.org Wed May 19 22:13:55 2010 From: python-checkins at python.org (victor.stinner) Date: Wed, 19 May 2010 22:13:55 +0200 (CEST) Subject: [Python-checkins] r81362 - python/branches/release31-maint Message-ID: <20100519201355.954CEE498@mail.python.org> Author: victor.stinner Date: Wed May 19 22:13:55 2010 New Revision: 81362 Log: Blocked revisions 81358 via svnmerge ........ r81358 | victor.stinner | 2010-05-19 18:53:30 +0200 (mer., 19 mai 2010) | 4 lines Issue #8589: Decode PYTHONWARNINGS environment variable with the file system encoding and surrogateespace error handler instead of the locale encoding to be consistent with os.environ. Add PySys_AddWarnOptionUnicode() function. ........ Modified: python/branches/release31-maint/ (props changed) From python-checkins at python.org Wed May 19 22:30:19 2010 From: python-checkins at python.org (victor.stinner) Date: Wed, 19 May 2010 22:30:19 +0200 (CEST) Subject: [Python-checkins] r81363 - in python/branches/release31-maint: Lib/distutils/log.py Lib/distutils/tests/test_log.py Lib/test/regrtest.py Misc/NEWS Message-ID: <20100519203019.B2682E592@mail.python.org> Author: victor.stinner Date: Wed May 19 22:30:19 2010 New Revision: 81363 Log: Merged revisions 81359-81361 via svnmerge from svn+ssh://pythondev at svn.python.org/python/branches/py3k ........ r81359 | victor.stinner | 2010-05-19 19:00:07 +0200 (mer., 19 mai 2010) | 4 lines Issue #8663: distutils.log emulates backslashreplace error handler. Fix compilation in a non-ASCII directory if stdout encoding is ASCII (eg. if stdout is not a TTY). ........ r81360 | victor.stinner | 2010-05-19 19:11:19 +0200 (mer., 19 mai 2010) | 5 lines regrtest.py: call replace_stdout() before the first call to print() print("== ", os.getcwd()) fails if the current working directory is not ASCII whereas sys.stdout encoding is ASCII. ........ r81361 | victor.stinner | 2010-05-19 19:15:50 +0200 (mer., 19 mai 2010) | 2 lines Oops, add the new test_log.py for distutils test suite (missing part of r81359) ........ Added: python/branches/release31-maint/Lib/distutils/tests/test_log.py Modified: python/branches/release31-maint/ (props changed) python/branches/release31-maint/Lib/distutils/log.py python/branches/release31-maint/Lib/test/regrtest.py python/branches/release31-maint/Misc/NEWS Modified: python/branches/release31-maint/Lib/distutils/log.py ============================================================================== --- python/branches/release31-maint/Lib/distutils/log.py (original) +++ python/branches/release31-maint/Lib/distutils/log.py Wed May 19 22:30:19 2010 @@ -27,6 +27,10 @@ stream = sys.stderr else: stream = sys.stdout + if stream.errors == 'strict': + # emulate backslashreplace error handler + encoding = stream.encoding + msg = msg.encode(encoding, "backslashreplace").decode(encoding) stream.write('%s\n' % msg) stream.flush() Added: python/branches/release31-maint/Lib/distutils/tests/test_log.py ============================================================================== --- (empty file) +++ python/branches/release31-maint/Lib/distutils/tests/test_log.py Wed May 19 22:30:19 2010 @@ -0,0 +1,36 @@ +"""Tests for distutils.log""" + +import sys +import unittest +from tempfile import NamedTemporaryFile + +from distutils import log + +class TestLog(unittest.TestCase): + def test_non_ascii(self): + # Issue #8663: test that non-ASCII text is escaped with + # backslashreplace error handler (stream use ASCII encoding and strict + # error handler) + old_stdout = sys.stdout + old_stderr = sys.stderr + try: + log.set_threshold(log.DEBUG) + with NamedTemporaryFile(mode="w+", encoding='ascii') as stdout, \ + NamedTemporaryFile(mode="w+", encoding='ascii') as stderr: + sys.stdout = stdout + sys.stderr = stderr + log.debug("debug:\xe9") + log.fatal("fatal:\xe9") + stdout.seek(0) + self.assertEquals(stdout.read().rstrip(), "debug:\\xe9") + stderr.seek(0) + self.assertEquals(stderr.read().rstrip(), "fatal:\\xe9") + finally: + sys.stdout = old_stdout + sys.stderr = old_stderr + +def test_suite(): + return unittest.makeSuite(TestLog) + +if __name__ == "__main__": + unittest.main(defaultTest="test_suite") Modified: python/branches/release31-maint/Lib/test/regrtest.py ============================================================================== --- python/branches/release31-maint/Lib/test/regrtest.py (original) +++ python/branches/release31-maint/Lib/test/regrtest.py Wed May 19 22:30:19 2010 @@ -215,6 +215,8 @@ on the command line. """ + replace_stdout() + support.record_original_stdout(sys.stdout) try: opts, args = getopt.getopt(sys.argv[1:], 'hvgqxsSrf:lu:t:TD:NLR:wM:n', @@ -411,7 +413,6 @@ support.verbose = verbose # Tell tests to be moderately quiet support.use_resources = use_resources save_modules = sys.modules.keys() - replace_stdout() for test in tests: if not quiet: print(test) Modified: python/branches/release31-maint/Misc/NEWS ============================================================================== --- python/branches/release31-maint/Misc/NEWS (original) +++ python/branches/release31-maint/Misc/NEWS Wed May 19 22:30:19 2010 @@ -43,6 +43,10 @@ Library ------- +- Issue #8663: distutils.log emulates backslashreplace error handler. Fix + compilation in a non-ASCII directory if stdout encoding is ASCII (eg. if + stdout is not a TTY). + - Issue #8688: Distutils now recalculates MANIFEST everytime. - Issue #5099: subprocess.Popen.__del__ no longer references global objects From python-checkins at python.org Wed May 19 22:40:51 2010 From: python-checkins at python.org (victor.stinner) Date: Wed, 19 May 2010 22:40:51 +0200 (CEST) Subject: [Python-checkins] r81364 - in python/branches/py3k: Lib/test/test_warnings.py Misc/NEWS Python/_warnings.c Python/pythonrun.c Message-ID: <20100519204051.2B7E8EE9AB@mail.python.org> Author: victor.stinner Date: Wed May 19 22:40:50 2010 New Revision: 81364 Log: Issue #8766: Initialize _warnings module before importing the first module. Fix a crash if an empty directory called "encodings" exists in sys.path. Modified: python/branches/py3k/Lib/test/test_warnings.py python/branches/py3k/Misc/NEWS python/branches/py3k/Python/_warnings.c python/branches/py3k/Python/pythonrun.c Modified: python/branches/py3k/Lib/test/test_warnings.py ============================================================================== --- python/branches/py3k/Lib/test/test_warnings.py (original) +++ python/branches/py3k/Lib/test/test_warnings.py Wed May 19 22:40:50 2010 @@ -738,20 +738,38 @@ module = py_warnings +class BootstrapTest(unittest.TestCase): + def test_issue_8766(self): + # "import encodings" emits a warning whereas the warnings is not loaded + # or not completly loaded (warnings imports indirectly encodings by + # importing linecache) yet + with support.temp_cwd() as cwd, support.temp_cwd('encodings'): + env = os.environ.copy() + env['PYTHONPATH'] = cwd + + # encodings loaded by initfsencoding() + retcode = subprocess.call([sys.executable, '-c', 'pass'], env=env) + self.assertEqual(retcode, 0) + + # Use -W to load warnings module at startup + retcode = subprocess.call( + [sys.executable, '-c', 'pass', '-W', 'always'], + env=env) + self.assertEqual(retcode, 0) + def test_main(): py_warnings.onceregistry.clear() c_warnings.onceregistry.clear() - support.run_unittest(CFilterTests, - PyFilterTests, - CWarnTests, - PyWarnTests, - CWCmdLineTests, PyWCmdLineTests, - _WarningsTests, - CWarningsDisplayTests, PyWarningsDisplayTests, - CCatchWarningTests, PyCatchWarningTests, - CEnvironmentVariableTests, - PyEnvironmentVariableTests - ) + support.run_unittest( + CFilterTests, PyFilterTests, + CWarnTests, PyWarnTests, + CWCmdLineTests, PyWCmdLineTests, + _WarningsTests, + CWarningsDisplayTests, PyWarningsDisplayTests, + CCatchWarningTests, PyCatchWarningTests, + CEnvironmentVariableTests, PyEnvironmentVariableTests, + BootstrapTest, + ) if __name__ == "__main__": Modified: python/branches/py3k/Misc/NEWS ============================================================================== --- python/branches/py3k/Misc/NEWS (original) +++ python/branches/py3k/Misc/NEWS Wed May 19 22:40:50 2010 @@ -12,6 +12,9 @@ Core and Builtins ----------------- +- Issue #8766: Initialize _warnings module before importing the first module. + Fix a crash if an empty directory called "encodings" exists in sys.path. + - Issue #8589: Decode PYTHONWARNINGS environment variable with the file system encoding and surrogateespace error handler instead of the locale encoding to be consistent with os.environ. Add PySys_AddWarnOptionUnicode() function. Modified: python/branches/py3k/Python/_warnings.c ============================================================================== --- python/branches/py3k/Python/_warnings.c (original) +++ python/branches/py3k/Python/_warnings.c Wed May 19 22:40:50 2010 @@ -116,7 +116,7 @@ _filters = warnings_filters; } - if (!PyList_Check(_filters)) { + if (_filters == NULL || !PyList_Check(_filters)) { PyErr_SetString(PyExc_ValueError, MODULE_NAME ".filters must be a list"); return NULL; Modified: python/branches/py3k/Python/pythonrun.c ============================================================================== --- python/branches/py3k/Python/pythonrun.c (original) +++ python/branches/py3k/Python/pythonrun.c Wed May 19 22:40:50 2010 @@ -265,13 +265,15 @@ _PyImportHooks_Init(); + /* Initialize _warnings. */ + _PyWarnings_Init(); + initfsencoding(); if (install_sigs) initsigs(); /* Signal handling stuff, including initintr() */ /* Initialize warnings. */ - _PyWarnings_Init(); if (PySys_HasWarnOptions()) { PyObject *warnings_module = PyImport_ImportModule("warnings"); if (!warnings_module) From python-checkins at python.org Wed May 19 22:57:08 2010 From: python-checkins at python.org (georg.brandl) Date: Wed, 19 May 2010 22:57:08 +0200 (CEST) Subject: [Python-checkins] r81365 - in python/branches/py3k: Doc/library/fcntl.rst Doc/library/ftplib.rst Doc/library/io.rst Doc/library/json.rst Doc/library/os.rst Doc/library/socket.rst Doc/library/syslog.rst Doc/library/unittest.rst Doc/reference/datamodel.rst Lib/pipes.py Lib/test/test_pipes.py Misc/NEWS Message-ID: <20100519205708.D09D3F6993@mail.python.org> Author: georg.brandl Date: Wed May 19 22:57:08 2010 New Revision: 81365 Log: Merged revisions 80030,80067,80069,80080-80081,80084,80432-80433,80465-80470,81059,81065-81067 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r80030 | georg.brandl | 2010-04-13 08:43:54 +0200 (Di, 13 Apr 2010) | 1 line Get rid of multi-row cells. ........ r80067 | georg.brandl | 2010-04-14 10:53:38 +0200 (Mi, 14 Apr 2010) | 1 line #5341: typo. ........ r80069 | georg.brandl | 2010-04-14 15:50:31 +0200 (Mi, 14 Apr 2010) | 1 line Add an x-ref to where the O_ constants are documented and move the SEEK_ constants after lseek(). ........ r80080 | georg.brandl | 2010-04-14 21:16:38 +0200 (Mi, 14 Apr 2010) | 1 line #8399: add note about Windows and O_BINARY. ........ r80081 | georg.brandl | 2010-04-14 23:34:44 +0200 (Mi, 14 Apr 2010) | 1 line #5250: document __instancecheck__ and __subclasscheck__. I hope the part about the class/metaclass distinction is understandable. ........ r80084 | georg.brandl | 2010-04-14 23:46:45 +0200 (Mi, 14 Apr 2010) | 1 line Fix missing. ........ r80432 | georg.brandl | 2010-04-24 10:56:58 +0200 (Sa, 24 Apr 2010) | 1 line Markup fixes. ........ r80433 | georg.brandl | 2010-04-24 11:08:10 +0200 (Sa, 24 Apr 2010) | 1 line #7507: quote "!" in pipes.quote(); it is a special character for some shells. ........ r80465 | georg.brandl | 2010-04-25 12:29:17 +0200 (So, 25 Apr 2010) | 1 line Remove LaTeXy index entry syntax. ........ r80466 | georg.brandl | 2010-04-25 12:54:42 +0200 (So, 25 Apr 2010) | 1 line Patch from Tim Hatch: Better cross-referencing in socket and winreg docs. ........ r80467 | georg.brandl | 2010-04-25 12:55:16 +0200 (So, 25 Apr 2010) | 1 line Patch from Tim Hatch: Remove reference to winreg being the fabled high-level registry interface. ........ r80468 | georg.brandl | 2010-04-25 12:55:58 +0200 (So, 25 Apr 2010) | 1 line Patch from Tim Hatch: Minor spelling changes to _winreg docs. ........ r80469 | georg.brandl | 2010-04-25 12:56:41 +0200 (So, 25 Apr 2010) | 1 line Fix code example to have valid syntax so that it can be highlighted. ........ r80470 | georg.brandl | 2010-04-25 12:57:15 +0200 (So, 25 Apr 2010) | 1 line Patch from Tim Hatch: Make socket setblocking <-> settimeout examples symmetric. ........ r81059 | georg.brandl | 2010-05-10 23:02:51 +0200 (Mo, 10 Mai 2010) | 1 line #8642: fix wrong function name. ........ r81065 | georg.brandl | 2010-05-10 23:46:50 +0200 (Mo, 10 Mai 2010) | 1 line Fix reference direction. ........ r81066 | georg.brandl | 2010-05-10 23:50:57 +0200 (Mo, 10 Mai 2010) | 1 line Consolidate deprecation messages. ........ r81067 | georg.brandl | 2010-05-10 23:51:33 +0200 (Mo, 10 Mai 2010) | 1 line Fix typo. ........ Modified: python/branches/py3k/Doc/library/fcntl.rst python/branches/py3k/Doc/library/ftplib.rst python/branches/py3k/Doc/library/io.rst python/branches/py3k/Doc/library/json.rst python/branches/py3k/Doc/library/os.rst python/branches/py3k/Doc/library/socket.rst python/branches/py3k/Doc/library/syslog.rst python/branches/py3k/Doc/library/unittest.rst python/branches/py3k/Doc/reference/datamodel.rst python/branches/py3k/Lib/pipes.py python/branches/py3k/Lib/test/test_pipes.py python/branches/py3k/Misc/NEWS Modified: python/branches/py3k/Doc/library/fcntl.rst ============================================================================== --- python/branches/py3k/Doc/library/fcntl.rst (original) +++ python/branches/py3k/Doc/library/fcntl.rst Wed May 19 22:57:08 2010 @@ -8,8 +8,8 @@ .. index:: - pair: UNIX at Unix; file control - pair: UNIX at Unix; I/O control + pair: UNIX; file control + pair: UNIX; I/O control This module performs file control and I/O control on file descriptors. It is an interface to the :cfunc:`fcntl` and :cfunc:`ioctl` Unix routines. Modified: python/branches/py3k/Doc/library/ftplib.rst ============================================================================== --- python/branches/py3k/Doc/library/ftplib.rst (original) +++ python/branches/py3k/Doc/library/ftplib.rst Wed May 19 22:57:08 2010 @@ -122,7 +122,7 @@ The set of all exceptions (as a tuple) that methods of :class:`FTP` instances may raise as a result of problems with the FTP connection (as opposed to programming errors made by the caller). This set includes the - four exceptions listed below as well as :exc:`socket.error` and + four exceptions listed above as well as :exc:`socket.error` and :exc:`IOError`. .. seealso:: Modified: python/branches/py3k/Doc/library/io.rst ============================================================================== --- python/branches/py3k/Doc/library/io.rst (original) +++ python/branches/py3k/Doc/library/io.rst Wed May 19 22:57:08 2010 @@ -240,7 +240,7 @@ Flush and close this stream. This method has no effect if the file is already closed. Once the file is closed, any operation on the file - (e.g. reading or writing) will raise an :exc:`ValueError`. + (e.g. reading or writing) will raise a :exc:`ValueError`. As a convenience, it is allowed to call this method more than once; only the first call, however, will have an effect. Modified: python/branches/py3k/Doc/library/json.rst ============================================================================== --- python/branches/py3k/Doc/library/json.rst (original) +++ python/branches/py3k/Doc/library/json.rst Wed May 19 22:57:08 2010 @@ -209,7 +209,7 @@ specified. Encodings that are not ASCII based (such as UCS-2) are not allowed and should be decoded to :class:`str` first. - The other arguments have the same meaning as in :func:`dump`. + The other arguments have the same meaning as in :func:`load`. Encoders and decoders Modified: python/branches/py3k/Doc/library/os.rst ============================================================================== --- python/branches/py3k/Doc/library/os.rst (original) +++ python/branches/py3k/Doc/library/os.rst Wed May 19 22:57:08 2010 @@ -697,6 +697,14 @@ Availability: Unix, Windows. +.. data:: SEEK_SET + SEEK_CUR + SEEK_END + + Parameters to the :func:`lseek` function. Their values are 0, 1, and 2, + respectively. Availability: Windows, Unix. + + .. function:: open(file, flags[, mode]) Open the file *file* and set various flags according to *flags* and possibly @@ -706,7 +714,8 @@ For a description of the flag and mode values, see the C run-time documentation; flag constants (like :const:`O_RDONLY` and :const:`O_WRONLY`) are defined in - this module too (see below). + this module too (see :ref:`open-constants`). In particular, on Windows adding + :const:`O_BINARY` is needed to open files in binary mode. Availability: Unix, Windows. @@ -794,6 +803,12 @@ :func:`fdopen`, or :data:`sys.stdout` or :data:`sys.stderr`, use its :meth:`~file.write` method. + +.. _open-constants: + +``open()`` flag constants +~~~~~~~~~~~~~~~~~~~~~~~~~ + The following constants are options for the *flags* parameter to the :func:`~os.open` function. They can be combined using the bitwise OR operator ``|``. Some of them are not available on all platforms. For descriptions of @@ -845,14 +860,6 @@ the C library. -.. data:: SEEK_SET - SEEK_CUR - SEEK_END - - Parameters to the :func:`lseek` function. Their values are 0, 1, and 2, - respectively. Availability: Windows, Unix. - - .. _os-file-dir: Files and Directories Modified: python/branches/py3k/Doc/library/socket.rst ============================================================================== --- python/branches/py3k/Doc/library/socket.rst (original) +++ python/branches/py3k/Doc/library/socket.rst Wed May 19 22:57:08 2010 @@ -89,8 +89,9 @@ and out-of-memory conditions can be raised; errors related to socket or address semantics raise the error :exc:`socket.error`. -Non-blocking mode is supported through :meth:`setblocking`. A generalization of -this based on timeouts is supported through :meth:`settimeout`. +Non-blocking mode is supported through :meth:`~socket.setblocking`. A +generalization of this based on timeouts is supported through +:meth:`~socket.settimeout`. The module :mod:`socket` exports the following constants and functions: @@ -559,7 +560,9 @@ :platform: Windows The :meth:`ioctl` method is a limited interface to the WSAIoctl system - interface. Please refer to the MSDN documentation for more information. + interface. Please refer to the `Win32 documentation + `_ for more + information. On other platforms, the generic :func:`fcntl.fcntl` and :func:`fcntl.ioctl` functions may be used; they accept a socket object as their first argument. @@ -662,7 +665,7 @@ blocking mode. In non-blocking mode, if a :meth:`recv` call doesn't find any data, or if a :meth:`send` call can't immediately dispose of the data, a :exc:`error` exception is raised; in blocking mode, the calls block until they - can proceed. ``s.setblocking(0)`` is equivalent to ``s.settimeout(0)``; + can proceed. ``s.setblocking(0)`` is equivalent to ``s.settimeout(0.0)``; ``s.setblocking(1)`` is equivalent to ``s.settimeout(None)``. @@ -691,21 +694,21 @@ non-blocking mode, operations fail (with an error that is unfortunately system-dependent) if they cannot be completed immediately. In timeout mode, operations fail if they cannot be completed within the timeout specified for the -socket or if the system returns an error. The :meth:`setblocking` method is simply -a shorthand for certain :meth:`settimeout` calls. +socket or if the system returns an error. The :meth:`~socket.setblocking` +method is simply a shorthand for certain :meth:`~socket.settimeout` calls. Timeout mode internally sets the socket in non-blocking mode. The blocking and timeout modes are shared between file descriptors and socket objects that refer to the same network endpoint. A consequence of this is that file objects -returned by the :meth:`makefile` method must only be used when the socket is in -blocking mode; in timeout or non-blocking mode file operations that cannot be -completed immediately will fail. - -Note that the :meth:`connect` operation is subject to the timeout setting, and -in general it is recommended to call :meth:`settimeout` before calling -:meth:`connect` or pass a timeout parameter to :meth:`create_connection`. -The system network stack may return a connection timeout error -of its own regardless of any Python socket timeout setting. +returned by the :meth:`~socket.makefile` method must only be used when the +socket is in blocking mode; in timeout or non-blocking mode file operations +that cannot be completed immediately will fail. + +Note that the :meth:`~socket.connect` operation is subject to the timeout +setting, and in general it is recommended to call :meth:`~socket.settimeout` +before calling :meth:`~socket.connect` or pass a timeout parameter to +:meth:`create_connection`. The system network stack may return a connection +timeout error of its own regardless of any Python socket timeout setting. .. method:: socket.setsockopt(level, optname, value) @@ -727,8 +730,8 @@ are disallowed. If *how* is :const:`SHUT_RDWR`, further sends and receives are disallowed. -Note that there are no methods :meth:`read` or :meth:`write`; use :meth:`recv` -and :meth:`send` without *flags* argument instead. +Note that there are no methods :meth:`read` or :meth:`write`; use +:meth:`~socket.recv` and :meth:`~socket.send` without *flags* argument instead. Socket objects also have these (read-only) attributes that correspond to the values given to the :class:`socket` constructor. @@ -757,11 +760,12 @@ Here are four minimal example programs using the TCP/IP protocol: a server that echoes all data that it receives back (servicing only one client), and a client using it. Note that a server must perform the sequence :func:`socket`, -:meth:`bind`, :meth:`listen`, :meth:`accept` (possibly repeating the -:meth:`accept` to service more than one client), while a client only needs the -sequence :func:`socket`, :meth:`connect`. Also note that the server does not -:meth:`send`/:meth:`recv` on the socket it is listening on but on the new -socket returned by :meth:`accept`. +:meth:`~socket.bind`, :meth:`~socket.listen`, :meth:`~socket.accept` (possibly +repeating the :meth:`~socket.accept` to service more than one client), while a +client only needs the sequence :func:`socket`, :meth:`~socket.connect`. Also +note that the server does not :meth:`~socket.send`/:meth:`~socket.recv` on the +socket it is listening on but on the new socket returned by +:meth:`~socket.accept`. The first two examples support IPv4 only. :: Modified: python/branches/py3k/Doc/library/syslog.rst ============================================================================== --- python/branches/py3k/Doc/library/syslog.rst (original) +++ python/branches/py3k/Doc/library/syslog.rst Wed May 19 22:57:08 2010 @@ -10,66 +10,63 @@ Refer to the Unix manual pages for a detailed description of the ``syslog`` facility. -This module wraps the system ``syslog`` module. A pure Python -library that can speak to a syslog server is available in -the :mod:`logging.handlers` module as :class:`SysLogHandler`. +This module wraps the system ``syslog`` family of routines. A pure Python +library that can speak to a syslog server is available in the +:mod:`logging.handlers` module as :class:`SysLogHandler`. The module defines the following functions: .. function:: syslog([priority,] message) - Send the string *message* to the system logger. A trailing newline is - added if necessary. Each message is tagged with a priority composed - of a *facility* and a *level*. The optional *priority* argument, which - defaults to :const:`LOG_INFO`, determines the message priority. If the - facility is not encoded in *priority* using logical-or (``LOG_INFO | - LOG_USER``), the value given in the :func:`openlog` call is used. + Send the string *message* to the system logger. A trailing newline is added + if necessary. Each message is tagged with a priority composed of a + *facility* and a *level*. The optional *priority* argument, which defaults + to :const:`LOG_INFO`, determines the message priority. If the facility is + not encoded in *priority* using logical-or (``LOG_INFO | LOG_USER``), the + value given in the :func:`openlog` call is used. - If :func:`openlog` has not been called prior to the call to - :func:'syslog', ``openlog()`` will be called with no arguments. + If :func:`openlog` has not been called prior to the call to :func:`syslog`, + ``openlog()`` will be called with no arguments. .. function:: openlog([ident[, logopt[, facility]]]) - Logging options of subsequent :func:`syslog` calls can be set by - calling :func:`openlog`. :func:`syslog` will call :func:`openlog` - with no arguments if the log is not currently open. - - The optional *ident* keyword argument is a string which is prepended - to every message, and defaults to ''sys.argv[0]'' with leading - path components stripped. The optional *logopt* keyword argument - (default=0) is a bit field - see below for possible values to combine. - The optional *facility* keyword argument (default=:const:`LOG_USER`) - sets the default facility for messages which do not have a facility - explicitly encoded. - - .. versionchanged::3.2 - In previous versions, keyword arguments were not allowed, and *ident* - was required. The default for *ident* was dependent on the system - libraries, and often was ''python'' instead of the name of the - python program file. + Logging options of subsequent :func:`syslog` calls can be set by calling + :func:`openlog`. :func:`syslog` will call :func:`openlog` with no arguments + if the log is not currently open. + + The optional *ident* keyword argument is a string which is prepended to every + message, and defaults to ``sys.argv[0]`` with leading path components + stripped. The optional *logopt* keyword argument (default is 0) is a bit + field -- see below for possible values to combine. The optional *facility* + keyword argument (default is :const:`LOG_USER`) sets the default facility for + messages which do not have a facility explicitly encoded. + + .. versionchanged:: 3.2 + In previous versions, keyword arguments were not allowed, and *ident* was + required. The default for *ident* was dependent on the system libraries, + and often was ``python`` instead of the name of the python program file. .. function:: closelog() - Reset the syslog module values and call the system library - ''closelog()''. + Reset the syslog module values and call the system library ``closelog()``. - This causes the module to behave as it does when initially imported. - For example, :func:'openlog' will be called on the first :func:'syslog' - call (if :func:'openlog' hasn't already been called), and *ident* - and other :func:'openlog' parameters are reset to defaults. + This causes the module to behave as it does when initially imported. For + example, :func:`openlog` will be called on the first :func:`syslog` call (if + :func:`openlog` hasn't already been called), and *ident* and other + :func:`openlog` parameters are reset to defaults. .. function:: setlogmask(maskpri) - Set the priority mask to *maskpri* and return the previous mask value. - Calls to :func:`syslog` with a priority level not set in *maskpri* - are ignored. The default is to log all priorities. The function - ``LOG_MASK(pri)`` calculates the mask for the individual priority - *pri*. The function ``LOG_UPTO(pri)`` calculates the mask for all - priorities up to and including *pri*. + Set the priority mask to *maskpri* and return the previous mask value. Calls + to :func:`syslog` with a priority level not set in *maskpri* are ignored. + The default is to log all priorities. The function ``LOG_MASK(pri)`` + calculates the mask for the individual priority *pri*. The function + ``LOG_UPTO(pri)`` calculates the mask for all priorities up to and including + *pri*. The module defines the following constants: @@ -100,11 +97,11 @@ syslog.syslog('Processing started') if error: - syslog.syslog(syslog.LOG_ERR, 'Processing started') + syslog.syslog(syslog.LOG_ERR, 'Processing started') -An example of setting some log options, these would include the process ID -in logged messages, and write the messages to the destination facility -used for mail logging:: +An example of setting some log options, these would include the process ID in +logged messages, and write the messages to the destination facility used for +mail logging:: syslog.openlog(logopt=syslog.LOG_PID, facility=syslog.LOG_MAIL) syslog.syslog('E-mail processing initiated...') Modified: python/branches/py3k/Doc/library/unittest.rst ============================================================================== --- python/branches/py3k/Doc/library/unittest.rst (original) +++ python/branches/py3k/Doc/library/unittest.rst Wed May 19 22:57:08 2010 @@ -773,8 +773,7 @@ will be *msg* if given, otherwise it will be :const:`None`. .. deprecated:: 3.1 - :meth:`failUnless`; use one of the ``assert`` variants. - :meth:`assert_`; use :meth:`assertTrue`. + :meth:`failUnless` and :meth:`assert_`; use :meth:`assertTrue`. .. method:: assertEqual(first, second, msg=None) Modified: python/branches/py3k/Doc/reference/datamodel.rst ============================================================================== --- python/branches/py3k/Doc/reference/datamodel.rst (original) +++ python/branches/py3k/Doc/reference/datamodel.rst Wed May 19 22:57:08 2010 @@ -1587,6 +1587,46 @@ called *members*. +Customizing instance and subclass checks +---------------------------------------- + +The following methods are used to override the default behavior of the +:func:`isinstance` and :func:`issubclass` built-in functions. + +In particular, the metaclass :class:`abc.ABCMeta` implements these methods in +order to allow the addition of Abstract Base Classes (ABCs) as "virtual base +classes" to any class or type (including built-in types), and including to other +ABCs. + +.. method:: class.__instancecheck__(self, instance) + + Return true if *instance* should be considered a (direct or indirect) + instance of *class*. If defined, called to implement ``isinstance(instance, + class)``. + + +.. method:: class.__subclasscheck__(self, subclass) + + Return true if *subclass* should be considered a (direct or indirect) + subclass of *class*. If defined, called to implement ``issubclass(subclass, + class)``. + + +Note that these methods are looked up on the type (metaclass) of a class. They +cannot be defined as class methods in the actual class. This is consistent with +the lookup of special methods that are called on instances, only that in this +case the instance is itself a class. + +.. seealso:: + + :pep:`3119` - Introducing Abstract Base Classes + Includes the specification for customizing :func:`isinstance` and + :func:`issubclass` behavior through :meth:`__instancecheck__` and + :meth:`__subclasscheck__`, with motivation for this functionality in the + context of adding Abstract Base Classes (see the :mod:`abc` module) to the + language. + + .. _callable-types: Emulating callable objects Modified: python/branches/py3k/Lib/pipes.py ============================================================================== --- python/branches/py3k/Lib/pipes.py (original) +++ python/branches/py3k/Lib/pipes.py Wed May 19 22:57:08 2010 @@ -249,11 +249,11 @@ # Reliably quote a string as a single argument for /bin/sh -_safechars = string.ascii_letters + string.digits + '!@%_-+=:,./' # Safe unquoted -_funnychars = '"`$\\' # Unsafe inside "double quotes" +# Safe unquoted +_safechars = frozenset(string.ascii_letters + string.digits + '@%_-+=:,./') def quote(file): - ''' return a shell-escaped version of the file string ''' + """Return a shell-escaped version of the file string.""" for c in file: if c not in _safechars: break @@ -261,11 +261,6 @@ if not file: return "''" return file - if '\'' not in file: - return '\'' + file + '\'' - res = '' - for c in file: - if c in _funnychars: - c = '\\' + c - res = res + c - return '"' + res + '"' + # use single quotes, and put single quotes into double quotes + # the string $'b is then quoted as '$'"'"'b' + return "'" + file.replace("'", "'\"'\"'") + "'" Modified: python/branches/py3k/Lib/test/test_pipes.py ============================================================================== --- python/branches/py3k/Lib/test/test_pipes.py (original) +++ python/branches/py3k/Lib/test/test_pipes.py Wed May 19 22:57:08 2010 @@ -70,9 +70,10 @@ self.assertEqual(open(TESTFN).read(), d) def testQuoting(self): - safeunquoted = string.ascii_letters + string.digits + '!@%_-+=:,./' - unsafe = '"`$\\' + safeunquoted = string.ascii_letters + string.digits + '@%_-+=:,./' + unsafe = '"`$\\!' + self.assertEqual(pipes.quote(''), "''") self.assertEqual(pipes.quote(safeunquoted), safeunquoted) self.assertEqual(pipes.quote('test file name'), "'test file name'") for u in unsafe: @@ -80,9 +81,7 @@ "'test%sname'" % u) for u in unsafe: self.assertEqual(pipes.quote("test%s'name'" % u), - '"test\\%s\'name\'"' % u) - - self.assertEqual(pipes.quote(''), "''") + "'test%s'\"'\"'name'\"'\"''" % u) def testRepr(self): t = pipes.Template() Modified: python/branches/py3k/Misc/NEWS ============================================================================== --- python/branches/py3k/Misc/NEWS (original) +++ python/branches/py3k/Misc/NEWS Wed May 19 22:57:08 2010 @@ -38,6 +38,8 @@ PyUnicode_FromString() to support surrogates in the filename and use the right encoding +- Issue #7507: Quote "!" in pipes.quote(); it is special to some shells. + - PyUnicode_DecodeFSDefaultAndSize() uses surrogateescape error handler - Issue #8419: Prevent the dict constructor from accepting non-string keyword From python-checkins at python.org Wed May 19 22:58:02 2010 From: python-checkins at python.org (georg.brandl) Date: Wed, 19 May 2010 22:58:02 +0200 (CEST) Subject: [Python-checkins] r81366 - python/branches/py3k Message-ID: <20100519205802.47030F699C@mail.python.org> Author: georg.brandl Date: Wed May 19 22:58:02 2010 New Revision: 81366 Log: Recorded merge of revisions 80030,80067,80069,80080-80081,80084,80432-80433,80465,80470,81059,81065-81067 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r80030 | georg.brandl | 2010-04-13 08:43:54 +0200 (Di, 13 Apr 2010) | 1 line Get rid of multi-row cells. ........ r80067 | georg.brandl | 2010-04-14 10:53:38 +0200 (Mi, 14 Apr 2010) | 1 line #5341: typo. ........ r80069 | georg.brandl | 2010-04-14 15:50:31 +0200 (Mi, 14 Apr 2010) | 1 line Add an x-ref to where the O_ constants are documented and move the SEEK_ constants after lseek(). ........ r80080 | georg.brandl | 2010-04-14 21:16:38 +0200 (Mi, 14 Apr 2010) | 1 line #8399: add note about Windows and O_BINARY. ........ r80081 | georg.brandl | 2010-04-14 23:34:44 +0200 (Mi, 14 Apr 2010) | 1 line #5250: document __instancecheck__ and __subclasscheck__. I hope the part about the class/metaclass distinction is understandable. ........ r80084 | georg.brandl | 2010-04-14 23:46:45 +0200 (Mi, 14 Apr 2010) | 1 line Fix missing. ........ r80432 | georg.brandl | 2010-04-24 10:56:58 +0200 (Sa, 24 Apr 2010) | 1 line Markup fixes. ........ r80433 | georg.brandl | 2010-04-24 11:08:10 +0200 (Sa, 24 Apr 2010) | 1 line #7507: quote "!" in pipes.quote(); it is a special character for some shells. ........ r80465 | georg.brandl | 2010-04-25 12:29:17 +0200 (So, 25 Apr 2010) | 1 line Remove LaTeXy index entry syntax. ........ r80470 | georg.brandl | 2010-04-25 12:57:15 +0200 (So, 25 Apr 2010) | 1 line Patch from Tim Hatch: Make socket setblocking <-> settimeout examples symmetric. ........ r81059 | georg.brandl | 2010-05-10 23:02:51 +0200 (Mo, 10 Mai 2010) | 1 line #8642: fix wrong function name. ........ r81065 | georg.brandl | 2010-05-10 23:46:50 +0200 (Mo, 10 Mai 2010) | 1 line Fix reference direction. ........ r81066 | georg.brandl | 2010-05-10 23:50:57 +0200 (Mo, 10 Mai 2010) | 1 line Consolidate deprecation messages. ........ r81067 | georg.brandl | 2010-05-10 23:51:33 +0200 (Mo, 10 Mai 2010) | 1 line Fix typo. ........ Modified: python/branches/py3k/ (props changed) From python-checkins at python.org Wed May 19 23:03:51 2010 From: python-checkins at python.org (georg.brandl) Date: Wed, 19 May 2010 23:03:51 +0200 (CEST) Subject: [Python-checkins] r81367 - in python/branches/py3k: Doc/library/winreg.rst Message-ID: <20100519210351.3B27EEEA0B@mail.python.org> Author: georg.brandl Date: Wed May 19 23:03:51 2010 New Revision: 81367 Log: Recorded merge of revisions 80466-80469 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r80466 | georg.brandl | 2010-04-25 12:54:42 +0200 (So, 25 Apr 2010) | 1 line Patch from Tim Hatch: Better cross-referencing in socket and winreg docs. ........ r80467 | georg.brandl | 2010-04-25 12:55:16 +0200 (So, 25 Apr 2010) | 1 line Patch from Tim Hatch: Remove reference to winreg being the fabled high-level registry interface. ........ r80468 | georg.brandl | 2010-04-25 12:55:58 +0200 (So, 25 Apr 2010) | 1 line Patch from Tim Hatch: Minor spelling changes to _winreg docs. ........ r80469 | georg.brandl | 2010-04-25 12:56:41 +0200 (So, 25 Apr 2010) | 1 line Fix code example to have valid syntax so that it can be highlighted. ........ Modified: python/branches/py3k/ (props changed) python/branches/py3k/Doc/library/winreg.rst Modified: python/branches/py3k/Doc/library/winreg.rst ============================================================================== --- python/branches/py3k/Doc/library/winreg.rst (original) +++ python/branches/py3k/Doc/library/winreg.rst Wed May 19 23:03:51 2010 @@ -8,21 +8,23 @@ These functions expose the Windows registry API to Python. Instead of using an -integer as the registry handle, a handle object is used to ensure that the -handles are closed correctly, even if the programmer neglects to explicitly -close them. +integer as the registry handle, a :ref:`handle object ` is used +to ensure that the handles are closed correctly, even if the programmer neglects +to explicitly close them. This module offers the following functions: .. function:: CloseKey(hkey) - Closes a previously opened registry key. The hkey argument specifies a + Closes a previously opened registry key. The *hkey* argument specifies a previously opened key. .. note:: - If *hkey* is not closed using this method (or via :meth:`hkey.Close() `), - it is closed when the *hkey* object is destroyed by Python. + + If *hkey* is not closed using this method (or via :meth:`hkey.Close() + `), it is closed when the *hkey* object is destroyed by + Python. .. function:: ConnectRegistry(computer_name, key) @@ -120,7 +122,7 @@ *res* is a reserved integer, and must be zero. The default is zero. - *sam* is an integer that specifies an access mask that describes the + *sam* is an integer that specifies an access mask that describes the desired security access for the key. Default is :const:`KEY_ALL_ACCESS`. See :ref:`Access Rights ` for other allowed values. @@ -183,13 +185,15 @@ | | registry type | +-------+--------------------------------------------+ | ``2`` | An integer that identifies the type of the | - | | value data | + | | value data (see table in docs for | + | | :meth:`SetValueEx`) | +-------+--------------------------------------------+ .. function:: ExpandEnvironmentStrings(str) - Expands environment strings %NAME% in unicode string like :const:`REG_EXPAND_SZ`:: + Expands environment variable placeholders ``%NAME%`` in strings like + :const:`REG_EXPAND_SZ`:: >>> ExpandEnvironmentStrings('%windir%') 'C:\\Windows' @@ -223,23 +227,20 @@ *key* is a handle returned by :func:`ConnectRegistry` or one of the constants :const:`HKEY_USERS` or :const:`HKEY_LOCAL_MACHINE`. - *sub_key* is a string that identifies the sub_key to load. + *sub_key* is a string that identifies the subkey to load. *file_name* is the name of the file to load registry data from. This file must have been created with the :func:`SaveKey` function. Under the file allocation table (FAT) file system, the filename may not have an extension. - A call to LoadKey() fails if the calling process does not have the - :const:`SE_RESTORE_PRIVILEGE` privilege. Note that privileges are different than + A call to :func:`LoadKey` fails if the calling process does not have the + :const:`SE_RESTORE_PRIVILEGE` privilege. Note that privileges are different from permissions -- see the `RegLoadKey documentation `__ for more details. If *key* is a handle returned by :func:`ConnectRegistry`, then the path - specified in *fileName* is relative to the remote computer. - - The Win32 documentation implies *key* must be in the :const:`HKEY_USER` or - :const:`HKEY_LOCAL_MACHINE` tree. This may or may not be true. + specified in *file_name* is relative to the remote computer. .. function:: OpenKey(key, sub_key[, res[, sam]]) @@ -254,8 +255,8 @@ *res* is a reserved integer, and must be zero. The default is zero. *sam* is an integer that specifies an access mask that describes the desired - security access for the key. Default is :const:`KEY_READ`. See - :ref:`Access Rights ` for other allowed values. + security access for the key. Default is :const:`KEY_READ`. See :ref:`Access + Rights ` for other allowed values. The result is a new handle to the specified key. @@ -327,7 +328,8 @@ | ``0`` | The value of the registry item. | +-------+-----------------------------------------+ | ``1`` | An integer giving the registry type for | - | | this value. | + | | this value (see table in docs for | + | | :meth:`SetValueEx`) | +-------+-----------------------------------------+ @@ -338,10 +340,10 @@ *key* is an already open key, or one of the predefined :ref:`HKEY_* constants `. - *file_name* is the name of the file to save registry data to. This file cannot - already exist. If this filename includes an extension, it cannot be used on file - allocation table (FAT) file systems by the :meth:`LoadKey`, :meth:`ReplaceKey` - or :meth:`RestoreKey` methods. + *file_name* is the name of the file to save registry data to. This file + cannot already exist. If this filename includes an extension, it cannot be + used on file allocation table (FAT) file systems by the :meth:`LoadKey` + method. If *key* represents a key on a remote computer, the path described by *file_name* is relative to the remote computer. The caller of this method must @@ -411,16 +413,16 @@ .. function:: DisableReflectionKey(key) Disables registry reflection for 32-bit processes running on a 64-bit - Operating System. + operating system. - *key* is an already open key, or one of the predefined - :ref:`HKEY_* constants `. + *key* is an already open key, or one of the predefined :ref:`HKEY_* constants + `. - Will generally raise :exc:`NotImplemented` if executed on a 32-bit - Operating System. + Will generally raise :exc:`NotImplemented` if executed on a 32-bit operating + system. If the key is not on the reflection list, the function succeeds but has no - effect. Disabling reflection for a key does not affect reflection of any + effect. Disabling reflection for a key does not affect reflection of any subkeys. @@ -428,11 +430,11 @@ Restores registry reflection for the specified disabled key. - *key* is an already open key, or one of the predefined - :ref:`HKEY_* constants `. + *key* is an already open key, or one of the predefined :ref:`HKEY_* constants + `. - Will generally raise :exc:`NotImplemented` if executed on a 32-bit - Operating System. + Will generally raise :exc:`NotImplemented` if executed on a 32-bit operating + system. Restoring reflection for a key does not affect reflection of any subkeys. @@ -447,7 +449,7 @@ Returns ``True`` if reflection is disabled. Will generally raise :exc:`NotImplemented` if executed on a 32-bit - Operating System. + operating system. .. _constants: @@ -646,7 +648,7 @@ This object wraps a Windows HKEY object, automatically closing it when the object is destroyed. To guarantee cleanup, you can call either the -:meth:`Close` method on the object, or the :func:`CloseKey` function. +:meth:`~PyHKEY.Close` method on the object, or the :func:`CloseKey` function. All registry functions in this module return one of these objects. @@ -666,8 +668,8 @@ Handle objects can be converted to an integer (e.g., using the built-in :func:`int` function), in which case the underlying Windows handle value is -returned. You can also use the :meth:`Detach` method to return the integer -handle, and also disconnect the Windows handle from the handle object. +returned. You can also use the :meth:`~PyHKEY.Detach` method to return the +integer handle, and also disconnect the Windows handle from the handle object. .. method:: PyHKEY.Close() @@ -692,11 +694,12 @@ .. method:: PyHKEY.__enter__() PyHKEY.__exit__(\*exc_info) - The HKEY object implements :meth:`__enter__` and :meth:`__exit__` and thus - supports the context protocol for the :keyword:`with` statement:: + The HKEY object implements :meth:`~object.__enter__` and + :meth:`~object.__exit__` and thus supports the context protocol for the + :keyword:`with` statement:: with OpenKey(HKEY_LOCAL_MACHINE, "foo") as key: - # ... work with key ... + ... # work with key will automatically close *key* when control leaves the :keyword:`with` block. From python-checkins at python.org Wed May 19 23:06:36 2010 From: python-checkins at python.org (georg.brandl) Date: Wed, 19 May 2010 23:06:36 +0200 (CEST) Subject: [Python-checkins] r81368 - in python/branches/py3k: Lib/functools.py Message-ID: <20100519210636.5D889F696A@mail.python.org> Author: georg.brandl Date: Wed May 19 23:06:36 2010 New Revision: 81368 Log: Merged revisions 80068 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r80068 | georg.brandl | 2010-04-14 10:56:01 +0200 (Mi, 14 Apr 2010) | 1 line #5341: fix typo and adapt docstring syntax. ........ Modified: python/branches/py3k/ (props changed) python/branches/py3k/Lib/functools.py Modified: python/branches/py3k/Lib/functools.py ============================================================================== --- python/branches/py3k/Lib/functools.py (original) +++ python/branches/py3k/Lib/functools.py Wed May 19 23:06:36 2010 @@ -51,7 +51,7 @@ assigned=assigned, updated=updated) def total_ordering(cls): - 'Class decorator that fills-in missing ordering methods' + """Class decorator that fills in missing ordering methods""" convert = { '__lt__': [('__gt__', lambda self, other: other < self), ('__le__', lambda self, other: not other < self), @@ -78,7 +78,7 @@ return cls def cmp_to_key(mycmp): - 'Convert a cmp= function into a key= function' + """Convert a cmp= function into a key= function""" class K(object): def __init__(self, obj, *args): self.obj = obj From python-checkins at python.org Wed May 19 23:22:59 2010 From: python-checkins at python.org (georg.brandl) Date: Wed, 19 May 2010 23:22:59 +0200 (CEST) Subject: [Python-checkins] r81369 - in python/branches/release31-maint: Doc/library/fcntl.rst Doc/library/ftplib.rst Doc/library/io.rst Doc/library/json.rst Doc/library/os.rst Doc/library/socket.rst Doc/library/winreg.rst Doc/reference/datamodel.rst Lib/pipes.py Lib/test/test_pipes.py Misc/NEWS Message-ID: <20100519212259.2A7EEEE9BF@mail.python.org> Author: georg.brandl Date: Wed May 19 23:22:58 2010 New Revision: 81369 Log: Merged revisions 81365,81367 via svnmerge from svn+ssh://svn.python.org/python/branches/py3k ................ r81365 | georg.brandl | 2010-05-19 22:57:08 +0200 (Mi, 19 Mai 2010) | 77 lines Merged revisions 80030,80067,80069,80080-80081,80084,80432-80433,80465-80470,81059,81065-81067 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r80030 | georg.brandl | 2010-04-13 08:43:54 +0200 (Di, 13 Apr 2010) | 1 line Get rid of multi-row cells. ........ r80067 | georg.brandl | 2010-04-14 10:53:38 +0200 (Mi, 14 Apr 2010) | 1 line #5341: typo. ........ r80069 | georg.brandl | 2010-04-14 15:50:31 +0200 (Mi, 14 Apr 2010) | 1 line Add an x-ref to where the O_ constants are documented and move the SEEK_ constants after lseek(). ........ r80080 | georg.brandl | 2010-04-14 21:16:38 +0200 (Mi, 14 Apr 2010) | 1 line #8399: add note about Windows and O_BINARY. ........ r80081 | georg.brandl | 2010-04-14 23:34:44 +0200 (Mi, 14 Apr 2010) | 1 line #5250: document __instancecheck__ and __subclasscheck__. I hope the part about the class/metaclass distinction is understandable. ........ r80084 | georg.brandl | 2010-04-14 23:46:45 +0200 (Mi, 14 Apr 2010) | 1 line Fix missing. ........ r80432 | georg.brandl | 2010-04-24 10:56:58 +0200 (Sa, 24 Apr 2010) | 1 line Markup fixes. ........ r80433 | georg.brandl | 2010-04-24 11:08:10 +0200 (Sa, 24 Apr 2010) | 1 line #7507: quote "!" in pipes.quote(); it is a special character for some shells. ........ r80465 | georg.brandl | 2010-04-25 12:29:17 +0200 (So, 25 Apr 2010) | 1 line Remove LaTeXy index entry syntax. ........ r80466 | georg.brandl | 2010-04-25 12:54:42 +0200 (So, 25 Apr 2010) | 1 line Patch from Tim Hatch: Better cross-referencing in socket and winreg docs. ........ r80467 | georg.brandl | 2010-04-25 12:55:16 +0200 (So, 25 Apr 2010) | 1 line Patch from Tim Hatch: Remove reference to winreg being the fabled high-level registry interface. ........ r80468 | georg.brandl | 2010-04-25 12:55:58 +0200 (So, 25 Apr 2010) | 1 line Patch from Tim Hatch: Minor spelling changes to _winreg docs. ........ r80469 | georg.brandl | 2010-04-25 12:56:41 +0200 (So, 25 Apr 2010) | 1 line Fix code example to have valid syntax so that it can be highlighted. ........ r80470 | georg.brandl | 2010-04-25 12:57:15 +0200 (So, 25 Apr 2010) | 1 line Patch from Tim Hatch: Make socket setblocking <-> settimeout examples symmetric. ........ r81059 | georg.brandl | 2010-05-10 23:02:51 +0200 (Mo, 10 Mai 2010) | 1 line #8642: fix wrong function name. ........ r81065 | georg.brandl | 2010-05-10 23:46:50 +0200 (Mo, 10 Mai 2010) | 1 line Fix reference direction. ........ r81066 | georg.brandl | 2010-05-10 23:50:57 +0200 (Mo, 10 Mai 2010) | 1 line Consolidate deprecation messages. ........ r81067 | georg.brandl | 2010-05-10 23:51:33 +0200 (Mo, 10 Mai 2010) | 1 line Fix typo. ........ ................ r81367 | georg.brandl | 2010-05-19 23:03:51 +0200 (Mi, 19 Mai 2010) | 21 lines Recorded merge of revisions 80466-80469 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r80466 | georg.brandl | 2010-04-25 12:54:42 +0200 (So, 25 Apr 2010) | 1 line Patch from Tim Hatch: Better cross-referencing in socket and winreg docs. ........ r80467 | georg.brandl | 2010-04-25 12:55:16 +0200 (So, 25 Apr 2010) | 1 line Patch from Tim Hatch: Remove reference to winreg being the fabled high-level registry interface. ........ r80468 | georg.brandl | 2010-04-25 12:55:58 +0200 (So, 25 Apr 2010) | 1 line Patch from Tim Hatch: Minor spelling changes to _winreg docs. ........ r80469 | georg.brandl | 2010-04-25 12:56:41 +0200 (So, 25 Apr 2010) | 1 line Fix code example to have valid syntax so that it can be highlighted. ........ ................ Modified: python/branches/release31-maint/ (props changed) python/branches/release31-maint/Doc/library/fcntl.rst python/branches/release31-maint/Doc/library/ftplib.rst python/branches/release31-maint/Doc/library/io.rst python/branches/release31-maint/Doc/library/json.rst python/branches/release31-maint/Doc/library/os.rst python/branches/release31-maint/Doc/library/socket.rst python/branches/release31-maint/Doc/library/winreg.rst python/branches/release31-maint/Doc/reference/datamodel.rst python/branches/release31-maint/Lib/pipes.py python/branches/release31-maint/Lib/test/test_pipes.py python/branches/release31-maint/Misc/NEWS Modified: python/branches/release31-maint/Doc/library/fcntl.rst ============================================================================== --- python/branches/release31-maint/Doc/library/fcntl.rst (original) +++ python/branches/release31-maint/Doc/library/fcntl.rst Wed May 19 23:22:58 2010 @@ -8,8 +8,8 @@ .. index:: - pair: UNIX at Unix; file control - pair: UNIX at Unix; I/O control + pair: UNIX; file control + pair: UNIX; I/O control This module performs file control and I/O control on file descriptors. It is an interface to the :cfunc:`fcntl` and :cfunc:`ioctl` Unix routines. Modified: python/branches/release31-maint/Doc/library/ftplib.rst ============================================================================== --- python/branches/release31-maint/Doc/library/ftplib.rst (original) +++ python/branches/release31-maint/Doc/library/ftplib.rst Wed May 19 23:22:58 2010 @@ -46,14 +46,6 @@ connection attempt (if is not specified, the global default timeout setting will be used). - .. attribute:: all_errors - - The set of all exceptions (as a tuple) that methods of :class:`FTP` - instances may raise as a result of problems with the FTP connection (as - opposed to programming errors made by the caller). This set includes the - four exceptions listed below as well as :exc:`socket.error` and - :exc:`IOError`. - .. exception:: error_reply @@ -76,6 +68,15 @@ with a digit in the range 1--5. +.. data:: all_errors + + The set of all exceptions (as a tuple) that methods of :class:`FTP` + instances may raise as a result of problems with the FTP connection (as + opposed to programming errors made by the caller). This set includes the + four exceptions listed above as well as :exc:`socket.error` and + :exc:`IOError`. + + .. seealso:: Module :mod:`netrc` Modified: python/branches/release31-maint/Doc/library/io.rst ============================================================================== --- python/branches/release31-maint/Doc/library/io.rst (original) +++ python/branches/release31-maint/Doc/library/io.rst Wed May 19 23:22:58 2010 @@ -235,7 +235,7 @@ Flush and close this stream. This method has no effect if the file is already closed. Once the file is closed, any operation on the file - (e.g. reading or writing) will raise an :exc:`ValueError`. + (e.g. reading or writing) will raise a :exc:`ValueError`. As a convenience, it is allowed to call this method more than once; only the first call, however, will have an effect. Modified: python/branches/release31-maint/Doc/library/json.rst ============================================================================== --- python/branches/release31-maint/Doc/library/json.rst (original) +++ python/branches/release31-maint/Doc/library/json.rst Wed May 19 23:22:58 2010 @@ -209,7 +209,7 @@ specified. Encodings that are not ASCII based (such as UCS-2) are not allowed and should be decoded to :class:`str` first. - The other arguments have the same meaning as in :func:`dump`. + The other arguments have the same meaning as in :func:`load`. Encoders and decoders Modified: python/branches/release31-maint/Doc/library/os.rst ============================================================================== --- python/branches/release31-maint/Doc/library/os.rst (original) +++ python/branches/release31-maint/Doc/library/os.rst Wed May 19 23:22:58 2010 @@ -584,6 +584,14 @@ Availability: Unix, Windows. +.. data:: SEEK_SET + SEEK_CUR + SEEK_END + + Parameters to the :func:`lseek` function. Their values are 0, 1, and 2, + respectively. Availability: Windows, Unix. + + .. function:: open(file, flags[, mode]) Open the file *file* and set various flags according to *flags* and possibly @@ -593,7 +601,8 @@ For a description of the flag and mode values, see the C run-time documentation; flag constants (like :const:`O_RDONLY` and :const:`O_WRONLY`) are defined in - this module too (see below). + this module too (see :ref:`open-constants`). In particular, on Windows adding + :const:`O_BINARY` is needed to open files in binary mode. Availability: Unix, Windows. @@ -681,6 +690,12 @@ :func:`fdopen`, or :data:`sys.stdout` or :data:`sys.stderr`, use its :meth:`~file.write` method. + +.. _open-constants: + +``open()`` flag constants +~~~~~~~~~~~~~~~~~~~~~~~~~ + The following constants are options for the *flags* parameter to the :func:`~os.open` function. They can be combined using the bitwise OR operator ``|``. Some of them are not available on all platforms. For descriptions of @@ -732,14 +747,6 @@ the C library. -.. data:: SEEK_SET - SEEK_CUR - SEEK_END - - Parameters to the :func:`lseek` function. Their values are 0, 1, and 2, - respectively. Availability: Windows, Unix. - - .. _os-file-dir: Files and Directories Modified: python/branches/release31-maint/Doc/library/socket.rst ============================================================================== --- python/branches/release31-maint/Doc/library/socket.rst (original) +++ python/branches/release31-maint/Doc/library/socket.rst Wed May 19 23:22:58 2010 @@ -90,8 +90,9 @@ and out-of-memory conditions can be raised; errors related to socket or address semantics raise the error :exc:`socket.error`. -Non-blocking mode is supported through :meth:`setblocking`. A generalization of -this based on timeouts is supported through :meth:`settimeout`. +Non-blocking mode is supported through :meth:`~socket.setblocking`. A +generalization of this based on timeouts is supported through +:meth:`~socket.settimeout`. The module :mod:`socket` exports the following constants and functions: @@ -553,7 +554,9 @@ :platform: Windows The :meth:`ioctl` method is a limited interface to the WSAIoctl system - interface. Please refer to the MSDN documentation for more information. + interface. Please refer to the `Win32 documentation + `_ for more + information. On other platforms, the generic :func:`fcntl.fcntl` and :func:`fcntl.ioctl` functions may be used; they accept a socket object as their first argument. @@ -656,7 +659,7 @@ blocking mode. In non-blocking mode, if a :meth:`recv` call doesn't find any data, or if a :meth:`send` call can't immediately dispose of the data, a :exc:`error` exception is raised; in blocking mode, the calls block until they - can proceed. ``s.setblocking(0)`` is equivalent to ``s.settimeout(0)``; + can proceed. ``s.setblocking(0)`` is equivalent to ``s.settimeout(0.0)``; ``s.setblocking(1)`` is equivalent to ``s.settimeout(None)``. @@ -685,21 +688,21 @@ non-blocking mode, operations fail (with an error that is unfortunately system-dependent) if they cannot be completed immediately. In timeout mode, operations fail if they cannot be completed within the timeout specified for the -socket or if the system returns an error. The :meth:`setblocking` method is simply -a shorthand for certain :meth:`settimeout` calls. +socket or if the system returns an error. The :meth:`~socket.setblocking` +method is simply a shorthand for certain :meth:`~socket.settimeout` calls. Timeout mode internally sets the socket in non-blocking mode. The blocking and timeout modes are shared between file descriptors and socket objects that refer to the same network endpoint. A consequence of this is that file objects -returned by the :meth:`makefile` method must only be used when the socket is in -blocking mode; in timeout or non-blocking mode file operations that cannot be -completed immediately will fail. - -Note that the :meth:`connect` operation is subject to the timeout setting, and -in general it is recommended to call :meth:`settimeout` before calling -:meth:`connect` or pass a timeout parameter to :meth:`create_connection`. -The system network stack may return a connection timeout error -of its own regardless of any Python socket timeout setting. +returned by the :meth:`~socket.makefile` method must only be used when the +socket is in blocking mode; in timeout or non-blocking mode file operations +that cannot be completed immediately will fail. + +Note that the :meth:`~socket.connect` operation is subject to the timeout +setting, and in general it is recommended to call :meth:`~socket.settimeout` +before calling :meth:`~socket.connect` or pass a timeout parameter to +:meth:`create_connection`. The system network stack may return a connection +timeout error of its own regardless of any Python socket timeout setting. .. method:: socket.setsockopt(level, optname, value) @@ -721,8 +724,8 @@ are disallowed. If *how* is :const:`SHUT_RDWR`, further sends and receives are disallowed. -Note that there are no methods :meth:`read` or :meth:`write`; use :meth:`recv` -and :meth:`send` without *flags* argument instead. +Note that there are no methods :meth:`read` or :meth:`write`; use +:meth:`~socket.recv` and :meth:`~socket.send` without *flags* argument instead. Socket objects also have these (read-only) attributes that correspond to the values given to the :class:`socket` constructor. @@ -751,11 +754,12 @@ Here are four minimal example programs using the TCP/IP protocol: a server that echoes all data that it receives back (servicing only one client), and a client using it. Note that a server must perform the sequence :func:`socket`, -:meth:`bind`, :meth:`listen`, :meth:`accept` (possibly repeating the -:meth:`accept` to service more than one client), while a client only needs the -sequence :func:`socket`, :meth:`connect`. Also note that the server does not -:meth:`send`/:meth:`recv` on the socket it is listening on but on the new -socket returned by :meth:`accept`. +:meth:`~socket.bind`, :meth:`~socket.listen`, :meth:`~socket.accept` (possibly +repeating the :meth:`~socket.accept` to service more than one client), while a +client only needs the sequence :func:`socket`, :meth:`~socket.connect`. Also +note that the server does not :meth:`~socket.send`/:meth:`~socket.recv` on the +socket it is listening on but on the new socket returned by +:meth:`~socket.accept`. The first two examples support IPv4 only. :: Modified: python/branches/release31-maint/Doc/library/winreg.rst ============================================================================== --- python/branches/release31-maint/Doc/library/winreg.rst (original) +++ python/branches/release31-maint/Doc/library/winreg.rst Wed May 19 23:22:58 2010 @@ -8,21 +8,23 @@ These functions expose the Windows registry API to Python. Instead of using an -integer as the registry handle, a handle object is used to ensure that the -handles are closed correctly, even if the programmer neglects to explicitly -close them. +integer as the registry handle, a :ref:`handle object ` is used +to ensure that the handles are closed correctly, even if the programmer neglects +to explicitly close them. This module offers the following functions: .. function:: CloseKey(hkey) - Closes a previously opened registry key. The hkey argument specifies a + Closes a previously opened registry key. The *hkey* argument specifies a previously opened key. .. note:: - If *hkey* is not closed using this method (or via :meth:`hkey.Close() `), - it is closed when the *hkey* object is destroyed by Python. + + If *hkey* is not closed using this method (or via :meth:`hkey.Close() + `), it is closed when the *hkey* object is destroyed by + Python. .. function:: ConnectRegistry(computer_name, key) @@ -123,13 +125,15 @@ | | registry type | +-------+--------------------------------------------+ | ``2`` | An integer that identifies the type of the | - | | value data | + | | value data (see table in docs for | + | | :meth:`SetValueEx`) | +-------+--------------------------------------------+ .. function:: ExpandEnvironmentStrings(str) - Expands environment strings %NAME% in unicode string like :const:`REG_EXPAND_SZ`:: + Expands environment variable placeholders ``%NAME%`` in strings like + :const:`REG_EXPAND_SZ`:: >>> ExpandEnvironmentStrings('%windir%') 'C:\\Windows' @@ -163,23 +167,20 @@ *key* is a handle returned by :func:`ConnectRegistry` or one of the constants :const:`HKEY_USERS` or :const:`HKEY_LOCAL_MACHINE`. - *sub_key* is a string that identifies the sub_key to load. + *sub_key* is a string that identifies the subkey to load. *file_name* is the name of the file to load registry data from. This file must have been created with the :func:`SaveKey` function. Under the file allocation table (FAT) file system, the filename may not have an extension. - A call to LoadKey() fails if the calling process does not have the - :const:`SE_RESTORE_PRIVILEGE` privilege. Note that privileges are different than + A call to :func:`LoadKey` fails if the calling process does not have the + :const:`SE_RESTORE_PRIVILEGE` privilege. Note that privileges are different from permissions -- see the `RegLoadKey documentation `__ for more details. If *key* is a handle returned by :func:`ConnectRegistry`, then the path - specified in *fileName* is relative to the remote computer. - - The Win32 documentation implies *key* must be in the :const:`HKEY_USER` or - :const:`HKEY_LOCAL_MACHINE` tree. This may or may not be true. + specified in *file_name* is relative to the remote computer. .. function:: OpenKey(key, sub_key[, res[, sam]]) @@ -194,8 +195,8 @@ *res* is a reserved integer, and must be zero. The default is zero. *sam* is an integer that specifies an access mask that describes the desired - security access for the key. Default is :const:`KEY_READ`. See - :ref:`Access Rights ` for other allowed values. + security access for the key. Default is :const:`KEY_READ`. See :ref:`Access + Rights ` for other allowed values. The result is a new handle to the specified key. @@ -267,7 +268,8 @@ | ``0`` | The value of the registry item. | +-------+-----------------------------------------+ | ``1`` | An integer giving the registry type for | - | | this value. | + | | this value (see table in docs for | + | | :meth:`SetValueEx`) | +-------+-----------------------------------------+ @@ -278,10 +280,10 @@ *key* is an already open key, or one of the predefined :ref:`HKEY_* constants `. - *file_name* is the name of the file to save registry data to. This file cannot - already exist. If this filename includes an extension, it cannot be used on file - allocation table (FAT) file systems by the :meth:`LoadKey`, :meth:`ReplaceKey` - or :meth:`RestoreKey` methods. + *file_name* is the name of the file to save registry data to. This file + cannot already exist. If this filename includes an extension, it cannot be + used on file allocation table (FAT) file systems by the :meth:`LoadKey` + method. If *key* represents a key on a remote computer, the path described by *file_name* is relative to the remote computer. The caller of this method must @@ -351,16 +353,16 @@ .. function:: DisableReflectionKey(key) Disables registry reflection for 32-bit processes running on a 64-bit - Operating System. + operating system. - *key* is an already open key, or one of the predefined - :ref:`HKEY_* constants `. + *key* is an already open key, or one of the predefined :ref:`HKEY_* constants + `. - Will generally raise :exc:`NotImplemented` if executed on a 32-bit - Operating System. + Will generally raise :exc:`NotImplemented` if executed on a 32-bit operating + system. If the key is not on the reflection list, the function succeeds but has no - effect. Disabling reflection for a key does not affect reflection of any + effect. Disabling reflection for a key does not affect reflection of any subkeys. @@ -368,11 +370,11 @@ Restores registry reflection for the specified disabled key. - *key* is an already open key, or one of the predefined - :ref:`HKEY_* constants `. + *key* is an already open key, or one of the predefined :ref:`HKEY_* constants + `. - Will generally raise :exc:`NotImplemented` if executed on a 32-bit - Operating System. + Will generally raise :exc:`NotImplemented` if executed on a 32-bit operating + system. Restoring reflection for a key does not affect reflection of any subkeys. @@ -387,7 +389,7 @@ Returns ``True`` if reflection is disabled. Will generally raise :exc:`NotImplemented` if executed on a 32-bit - Operating System. + operating system. .. _constants: @@ -586,7 +588,7 @@ This object wraps a Windows HKEY object, automatically closing it when the object is destroyed. To guarantee cleanup, you can call either the -:meth:`Close` method on the object, or the :func:`CloseKey` function. +:meth:`~PyHKEY.Close` method on the object, or the :func:`CloseKey` function. All registry functions in this module return one of these objects. @@ -606,8 +608,8 @@ Handle objects can be converted to an integer (e.g., using the built-in :func:`int` function), in which case the underlying Windows handle value is -returned. You can also use the :meth:`Detach` method to return the integer -handle, and also disconnect the Windows handle from the handle object. +returned. You can also use the :meth:`~PyHKEY.Detach` method to return the +integer handle, and also disconnect the Windows handle from the handle object. .. method:: PyHKEY.Close() @@ -632,11 +634,12 @@ .. method:: PyHKEY.__enter__() PyHKEY.__exit__(\*exc_info) - The HKEY object implements :meth:`__enter__` and :meth:`__exit__` and thus - supports the context protocol for the :keyword:`with` statement:: + The HKEY object implements :meth:`~object.__enter__` and + :meth:`~object.__exit__` and thus supports the context protocol for the + :keyword:`with` statement:: with OpenKey(HKEY_LOCAL_MACHINE, "foo") as key: - # ... work with key ... + ... # work with key will automatically close *key* when control leaves the :keyword:`with` block. Modified: python/branches/release31-maint/Doc/reference/datamodel.rst ============================================================================== --- python/branches/release31-maint/Doc/reference/datamodel.rst (original) +++ python/branches/release31-maint/Doc/reference/datamodel.rst Wed May 19 23:22:58 2010 @@ -1588,6 +1588,46 @@ called *members*. +Customizing instance and subclass checks +---------------------------------------- + +The following methods are used to override the default behavior of the +:func:`isinstance` and :func:`issubclass` built-in functions. + +In particular, the metaclass :class:`abc.ABCMeta` implements these methods in +order to allow the addition of Abstract Base Classes (ABCs) as "virtual base +classes" to any class or type (including built-in types), and including to other +ABCs. + +.. method:: class.__instancecheck__(self, instance) + + Return true if *instance* should be considered a (direct or indirect) + instance of *class*. If defined, called to implement ``isinstance(instance, + class)``. + + +.. method:: class.__subclasscheck__(self, subclass) + + Return true if *subclass* should be considered a (direct or indirect) + subclass of *class*. If defined, called to implement ``issubclass(subclass, + class)``. + + +Note that these methods are looked up on the type (metaclass) of a class. They +cannot be defined as class methods in the actual class. This is consistent with +the lookup of special methods that are called on instances, only that in this +case the instance is itself a class. + +.. seealso:: + + :pep:`3119` - Introducing Abstract Base Classes + Includes the specification for customizing :func:`isinstance` and + :func:`issubclass` behavior through :meth:`__instancecheck__` and + :meth:`__subclasscheck__`, with motivation for this functionality in the + context of adding Abstract Base Classes (see the :mod:`abc` module) to the + language. + + .. _callable-types: Emulating callable objects Modified: python/branches/release31-maint/Lib/pipes.py ============================================================================== --- python/branches/release31-maint/Lib/pipes.py (original) +++ python/branches/release31-maint/Lib/pipes.py Wed May 19 23:22:58 2010 @@ -249,20 +249,18 @@ # Reliably quote a string as a single argument for /bin/sh -_safechars = string.ascii_letters + string.digits + '!@%_-+=:,./' # Safe unquoted -_funnychars = '"`$\\' # Unsafe inside "double quotes" +# Safe unquoted +_safechars = frozenset(string.ascii_letters + string.digits + '@%_-+=:,./') def quote(file): + """Return a shell-escaped version of the file string.""" for c in file: if c not in _safechars: break else: + if not file: + return "''" return file - if '\'' not in file: - return '\'' + file + '\'' - res = '' - for c in file: - if c in _funnychars: - c = '\\' + c - res = res + c - return '"' + res + '"' + # use single quotes, and put single quotes into double quotes + # the string $'b is then quoted as '$'"'"'b' + return "'" + file.replace("'", "'\"'\"'") + "'" Modified: python/branches/release31-maint/Lib/test/test_pipes.py ============================================================================== --- python/branches/release31-maint/Lib/test/test_pipes.py (original) +++ python/branches/release31-maint/Lib/test/test_pipes.py Wed May 19 23:22:58 2010 @@ -62,9 +62,10 @@ self.assertEqual(open(TESTFN).read(), d) def testQuoting(self): - safeunquoted = string.ascii_letters + string.digits + '!@%_-+=:,./' - unsafe = '"`$\\' + safeunquoted = string.ascii_letters + string.digits + '@%_-+=:,./' + unsafe = '"`$\\!' + self.assertEqual(pipes.quote(''), "''") self.assertEqual(pipes.quote(safeunquoted), safeunquoted) self.assertEqual(pipes.quote('test file name'), "'test file name'") for u in unsafe: @@ -72,7 +73,7 @@ "'test%sname'" % u) for u in unsafe: self.assertEqual(pipes.quote("test%s'name'" % u), - '"test\\%s\'name\'"' % u) + "'test%s'\"'\"'name'\"'\"''" % u) def testRepr(self): t = pipes.Template() Modified: python/branches/release31-maint/Misc/NEWS ============================================================================== --- python/branches/release31-maint/Misc/NEWS (original) +++ python/branches/release31-maint/Misc/NEWS Wed May 19 23:22:58 2010 @@ -43,6 +43,8 @@ Library ------- +- Issue #7507: Quote "!" in pipes.quote(); it is special to some shells. + - Issue #8663: distutils.log emulates backslashreplace error handler. Fix compilation in a non-ASCII directory if stdout encoding is ASCII (eg. if stdout is not a TTY). From python-checkins at python.org Wed May 19 23:39:51 2010 From: python-checkins at python.org (georg.brandl) Date: Wed, 19 May 2010 23:39:51 +0200 (CEST) Subject: [Python-checkins] r81370 - in python/branches/py3k/Doc/howto: descriptor.rst index.rst Message-ID: <20100519213951.DCD6DF6979@mail.python.org> Author: georg.brandl Date: Wed May 19 23:39:51 2010 New Revision: 81370 Log: Add descriptor HOWTO to py3k docs. Added: python/branches/py3k/Doc/howto/descriptor.rst Modified: python/branches/py3k/Doc/howto/index.rst Added: python/branches/py3k/Doc/howto/descriptor.rst ============================================================================== --- (empty file) +++ python/branches/py3k/Doc/howto/descriptor.rst Wed May 19 23:39:51 2010 @@ -0,0 +1,431 @@ +====================== +Descriptor HowTo Guide +====================== + +:Author: Raymond Hettinger +:Contact: + +.. Contents:: + +Abstract +-------- + +Defines descriptors, summarizes the protocol, and shows how descriptors are +called. Examines a custom descriptor and several built-in python descriptors +including functions, properties, static methods, and class methods. Shows how +each works by giving a pure Python equivalent and a sample application. + +Learning about descriptors not only provides access to a larger toolset, it +creates a deeper understanding of how Python works and an appreciation for the +elegance of its design. + + +Definition and Introduction +--------------------------- + +In general, a descriptor is an object attribute with "binding behavior", one +whose attribute access has been overridden by methods in the descriptor +protocol. Those methods are :meth:`__get__`, :meth:`__set__`, and +:meth:`__delete__`. If any of those methods are defined for an object, it is +said to be a descriptor. + +The default behavior for attribute access is to get, set, or delete the +attribute from an object's dictionary. For instance, ``a.x`` has a lookup chain +starting with ``a.__dict__['x']``, then ``type(a).__dict__['x']``, and +continuing through the base classes of ``type(a)`` excluding metaclasses. If the +looked-up value is an object defining one of the descriptor methods, then Python +may override the default behavior and invoke the descriptor method instead. +Where this occurs in the precedence chain depends on which descriptor methods +were defined. Note that descriptors are only invoked for new style objects or +classes (a class is new style if it inherits from :class:`object` or +:class:`type`). + +Descriptors are a powerful, general purpose protocol. They are the mechanism +behind properties, methods, static methods, class methods, and :func:`super()`. +They are used used throughout Python itself to implement the new style classes +introduced in version 2.2. Descriptors simplify the underlying C-code and offer +a flexible set of new tools for everyday Python programs. + + +Descriptor Protocol +------------------- + +``descr.__get__(self, obj, type=None) --> value`` + +``descr.__set__(self, obj, value) --> None`` + +``descr.__delete__(self, obj) --> None`` + +That is all there is to it. Define any of these methods and an object is +considered a descriptor and can override default behavior upon being looked up +as an attribute. + +If an object defines both :meth:`__get__` and :meth:`__set__`, it is considered +a data descriptor. Descriptors that only define :meth:`__get__` are called +non-data descriptors (they are typically used for methods but other uses are +possible). + +Data and non-data descriptors differ in how overrides are calculated with +respect to entries in an instance's dictionary. If an instance's dictionary +has an entry with the same name as a data descriptor, the data descriptor +takes precedence. If an instance's dictionary has an entry with the same +name as a non-data descriptor, the dictionary entry takes precedence. + +To make a read-only data descriptor, define both :meth:`__get__` and +:meth:`__set__` with the :meth:`__set__` raising an :exc:`AttributeError` when +called. Defining the :meth:`__set__` method with an exception raising +placeholder is enough to make it a data descriptor. + + +Invoking Descriptors +-------------------- + +A descriptor can be called directly by its method name. For example, +``d.__get__(obj)``. + +Alternatively, it is more common for a descriptor to be invoked automatically +upon attribute access. For example, ``obj.d`` looks up ``d`` in the dictionary +of ``obj``. If ``d`` defines the method :meth:`__get__`, then ``d.__get__(obj)`` +is invoked according to the precedence rules listed below. + +The details of invocation depend on whether ``obj`` is an object or a class. +Either way, descriptors only work for new style objects and classes. A class is +new style if it is a subclass of :class:`object`. + +For objects, the machinery is in :meth:`object.__getattribute__` which +transforms ``b.x`` into ``type(b).__dict__['x'].__get__(b, type(b))``. The +implementation works through a precedence chain that gives data descriptors +priority over instance variables, instance variables priority over non-data +descriptors, and assigns lowest priority to :meth:`__getattr__` if provided. The +full C implementation can be found in :cfunc:`PyObject_GenericGetAttr()` in +`Objects/object.c `_\. + +For classes, the machinery is in :meth:`type.__getattribute__` which transforms +``B.x`` into ``B.__dict__['x'].__get__(None, B)``. In pure Python, it looks +like:: + + def __getattribute__(self, key): + "Emulate type_getattro() in Objects/typeobject.c" + v = object.__getattribute__(self, key) + if hasattr(v, '__get__'): + return v.__get__(None, self) + return v + +The important points to remember are: + +* descriptors are invoked by the :meth:`__getattribute__` method +* overriding :meth:`__getattribute__` prevents automatic descriptor calls +* :meth:`__getattribute__` is only available with new style classes and objects +* :meth:`object.__getattribute__` and :meth:`type.__getattribute__` make + different calls to :meth:`__get__`. +* data descriptors always override instance dictionaries. +* non-data descriptors may be overridden by instance dictionaries. + +The object returned by ``super()`` also has a custom :meth:`__getattribute__` +method for invoking descriptors. The call ``super(B, obj).m()`` searches +``obj.__class__.__mro__`` for the base class ``A`` immediately following ``B`` +and then returns ``A.__dict__['m'].__get__(obj, A)``. If not a descriptor, +``m`` is returned unchanged. If not in the dictionary, ``m`` reverts to a +search using :meth:`object.__getattribute__`. + +Note, in Python 2.2, ``super(B, obj).m()`` would only invoke :meth:`__get__` if +``m`` was a data descriptor. In Python 2.3, non-data descriptors also get +invoked unless an old-style class is involved. The implementation details are +in :cfunc:`super_getattro()` in +`Objects/typeobject.c `_ +and a pure Python equivalent can be found in `Guido's Tutorial`_. + +.. _`Guido's Tutorial`: http://www.python.org/2.2.3/descrintro.html#cooperation + +The details above show that the mechanism for descriptors is embedded in the +:meth:`__getattribute__()` methods for :class:`object`, :class:`type`, and +:func:`super`. Classes inherit this machinery when they derive from +:class:`object` or if they have a meta-class providing similar functionality. +Likewise, classes can turn-off descriptor invocation by overriding +:meth:`__getattribute__()`. + + +Descriptor Example +------------------ + +The following code creates a class whose objects are data descriptors which +print a message for each get or set. Overriding :meth:`__getattribute__` is +alternate approach that could do this for every attribute. However, this +descriptor is useful for monitoring just a few chosen attributes:: + + class RevealAccess(object): + """A data descriptor that sets and returns values + normally and prints a message logging their access. + """ + + def __init__(self, initval=None, name='var'): + self.val = initval + self.name = name + + def __get__(self, obj, objtype): + print('Retrieving', self.name) + return self.val + + def __set__(self, obj, val): + print('Updating', self.name) + self.val = val + + >>> class MyClass(object): + x = RevealAccess(10, 'var "x"') + y = 5 + + >>> m = MyClass() + >>> m.x + Retrieving var "x" + 10 + >>> m.x = 20 + Updating var "x" + >>> m.x + Retrieving var "x" + 20 + >>> m.y + 5 + +The protocol is simple and offers exciting possibilities. Several use cases are +so common that they have been packaged into individual function calls. +Properties, bound and unbound methods, static methods, and class methods are all +based on the descriptor protocol. + + +Properties +---------- + +Calling :func:`property` is a succinct way of building a data descriptor that +triggers function calls upon access to an attribute. Its signature is:: + + property(fget=None, fset=None, fdel=None, doc=None) -> property attribute + +The documentation shows a typical use to define a managed attribute ``x``:: + + class C(object): + def getx(self): return self.__x + def setx(self, value): self.__x = value + def delx(self): del self.__x + x = property(getx, setx, delx, "I'm the 'x' property.") + +To see how :func:`property` is implemented in terms of the descriptor protocol, +here is a pure Python equivalent:: + + class Property(object): + "Emulate PyProperty_Type() in Objects/descrobject.c" + + def __init__(self, fget=None, fset=None, fdel=None, doc=None): + self.fget = fget + self.fset = fset + self.fdel = fdel + self.__doc__ = doc + + def __get__(self, obj, objtype=None): + if obj is None: + return self + if self.fget is None: + raise AttributeError, "unreadable attribute" + return self.fget(obj) + + def __set__(self, obj, value): + if self.fset is None: + raise AttributeError, "can't set attribute" + self.fset(obj, value) + + def __delete__(self, obj): + if self.fdel is None: + raise AttributeError, "can't delete attribute" + self.fdel(obj) + +The :func:`property` builtin helps whenever a user interface has granted +attribute access and then subsequent changes require the intervention of a +method. + +For instance, a spreadsheet class may grant access to a cell value through +``Cell('b10').value``. Subsequent improvements to the program require the cell +to be recalculated on every access; however, the programmer does not want to +affect existing client code accessing the attribute directly. The solution is +to wrap access to the value attribute in a property data descriptor:: + + class Cell(object): + . . . + def getvalue(self, obj): + "Recalculate cell before returning value" + self.recalc() + return obj._value + value = property(getvalue) + + +Functions and Methods +--------------------- + +Python's object oriented features are built upon a function based environment. +Using non-data descriptors, the two are merged seamlessly. + +Class dictionaries store methods as functions. In a class definition, methods +are written using :keyword:`def` and :keyword:`lambda`, the usual tools for +creating functions. The only difference from regular functions is that the +first argument is reserved for the object instance. By Python convention, the +instance reference is called *self* but may be called *this* or any other +variable name. + +To support method calls, functions include the :meth:`__get__` method for +binding methods during attribute access. This means that all functions are +non-data descriptors which return bound or unbound methods depending whether +they are invoked from an object or a class. In pure python, it works like +this:: + + class Function(object): + . . . + def __get__(self, obj, objtype=None): + "Simulate func_descr_get() in Objects/funcobject.c" + return types.MethodType(self, obj, objtype) + +Running the interpreter shows how the function descriptor works in practice:: + + >>> class D(object): + def f(self, x): + return x + + >>> d = D() + >>> D.__dict__['f'] # Stored internally as a function + + >>> D.f # Get from a class becomes an unbound method + + >>> d.f # Get from an instance becomes a bound method + > + +The output suggests that bound and unbound methods are two different types. +While they could have been implemented that way, the actual C implemention of +:ctype:`PyMethod_Type` in +`Objects/classobject.c `_ +is a single object with two different representations depending on whether the +:attr:`im_self` field is set or is *NULL* (the C equivalent of *None*). + +Likewise, the effects of calling a method object depend on the :attr:`im_self` +field. If set (meaning bound), the original function (stored in the +:attr:`im_func` field) is called as expected with the first argument set to the +instance. If unbound, all of the arguments are passed unchanged to the original +function. The actual C implementation of :func:`instancemethod_call()` is only +slightly more complex in that it includes some type checking. + + +Static Methods and Class Methods +-------------------------------- + +Non-data descriptors provide a simple mechanism for variations on the usual +patterns of binding functions into methods. + +To recap, functions have a :meth:`__get__` method so that they can be converted +to a method when accessed as attributes. The non-data descriptor transforms a +``obj.f(*args)`` call into ``f(obj, *args)``. Calling ``klass.f(*args)`` +becomes ``f(*args)``. + +This chart summarizes the binding and its two most useful variants: + + +-----------------+----------------------+------------------+ + | Transformation | Called from an | Called from a | + | | Object | Class | + +=================+======================+==================+ + | function | f(obj, \*args) | f(\*args) | + +-----------------+----------------------+------------------+ + | staticmethod | f(\*args) | f(\*args) | + +-----------------+----------------------+------------------+ + | classmethod | f(type(obj), \*args) | f(klass, \*args) | + +-----------------+----------------------+------------------+ + +Static methods return the underlying function without changes. Calling either +``c.f`` or ``C.f`` is the equivalent of a direct lookup into +``object.__getattribute__(c, "f")`` or ``object.__getattribute__(C, "f")``. As a +result, the function becomes identically accessible from either an object or a +class. + +Good candidates for static methods are methods that do not reference the +``self`` variable. + +For instance, a statistics package may include a container class for +experimental data. The class provides normal methods for computing the average, +mean, median, and other descriptive statistics that depend on the data. However, +there may be useful functions which are conceptually related but do not depend +on the data. For instance, ``erf(x)`` is handy conversion routine that comes up +in statistical work but does not directly depend on a particular dataset. +It can be called either from an object or the class: ``s.erf(1.5) --> .9332`` or +``Sample.erf(1.5) --> .9332``. + +Since staticmethods return the underlying function with no changes, the example +calls are unexciting:: + + >>> class E(object): + def f(x): + print(x) + f = staticmethod(f) + + >>> print(E.f(3)) + 3 + >>> print(E().f(3)) + 3 + +Using the non-data descriptor protocol, a pure Python version of +:func:`staticmethod` would look like this:: + + class StaticMethod(object): + "Emulate PyStaticMethod_Type() in Objects/funcobject.c" + + def __init__(self, f): + self.f = f + + def __get__(self, obj, objtype=None): + return self.f + +Unlike static methods, class methods prepend the class reference to the +argument list before calling the function. This format is the same +for whether the caller is an object or a class:: + + >>> class E(object): + def f(klass, x): + return klass.__name__, x + f = classmethod(f) + + >>> print(E.f(3)) + ('E', 3) + >>> print(E().f(3)) + ('E', 3) + + +This behavior is useful whenever the function only needs to have a class +reference and does not care about any underlying data. One use for classmethods +is to create alternate class constructors. In Python 2.3, the classmethod +:func:`dict.fromkeys` creates a new dictionary from a list of keys. The pure +Python equivalent is:: + + class Dict: + . . . + def fromkeys(klass, iterable, value=None): + "Emulate dict_fromkeys() in Objects/dictobject.c" + d = klass() + for key in iterable: + d[key] = value + return d + fromkeys = classmethod(fromkeys) + +Now a new dictionary of unique keys can be constructed like this:: + + >>> Dict.fromkeys('abracadabra') + {'a': None, 'r': None, 'b': None, 'c': None, 'd': None} + +Using the non-data descriptor protocol, a pure Python version of +:func:`classmethod` would look like this:: + + class ClassMethod(object): + "Emulate PyClassMethod_Type() in Objects/funcobject.c" + + def __init__(self, f): + self.f = f + + def __get__(self, obj, klass=None): + if klass is None: + klass = type(obj) + def newfunc(*args): + return self.f(klass, *args) + return newfunc + Modified: python/branches/py3k/Doc/howto/index.rst ============================================================================== --- python/branches/py3k/Doc/howto/index.rst (original) +++ python/branches/py3k/Doc/howto/index.rst Wed May 19 23:39:51 2010 @@ -16,6 +16,7 @@ advocacy.rst cporting.rst curses.rst + descriptor.rst doanddont.rst functional.rst regex.rst From python-checkins at python.org Thu May 20 00:20:14 2010 From: python-checkins at python.org (tarek.ziade) Date: Thu, 20 May 2010 00:20:14 +0200 (CEST) Subject: [Python-checkins] r81371 - in python/trunk: Lib/sysconfig.py Lib/test/test_sysconfig.py Misc/NEWS Message-ID: <20100519222014.982C3EEA08@mail.python.org> Author: tarek.ziade Date: Thu May 20 00:20:14 2010 New Revision: 81371 Log: #8759: Fixed user paths in sysconfig for posix and os2 schemes Modified: python/trunk/Lib/sysconfig.py python/trunk/Lib/test/test_sysconfig.py python/trunk/Misc/NEWS Modified: python/trunk/Lib/sysconfig.py ============================================================================== --- python/trunk/Lib/sysconfig.py (original) +++ python/trunk/Lib/sysconfig.py Thu May 20 00:20:14 2010 @@ -47,10 +47,10 @@ 'data' : '{base}', }, 'os2_home': { - 'stdlib': '{userbase}/lib/python/{py_version_short}', - 'platstdlib': '{userbase}/lib/python/{py_version_short}', - 'purelib': '{userbase}/lib/python/{py_version_short}/site-packages', - 'platlib': '{userbase}/lib/python/{py_version_short}/site-packages', + 'stdlib': '{userbase}/lib/python{py_version_short}', + 'platstdlib': '{userbase}/lib/python{py_version_short}', + 'purelib': '{userbase}/lib/python{py_version_short}/site-packages', + 'platlib': '{userbase}/lib/python{py_version_short}/site-packages', 'include': '{userbase}/include/python{py_version_short}', 'scripts': '{userbase}/bin', 'data' : '{userbase}', @@ -65,10 +65,10 @@ 'data' : '{userbase}', }, 'posix_user': { - 'stdlib': '{userbase}/lib/python/{py_version_short}', - 'platstdlib': '{userbase}/lib/python/{py_version_short}', - 'purelib': '{userbase}/lib/python/{py_version_short}/site-packages', - 'platlib': '{userbase}/lib/python/{py_version_short}/site-packages', + 'stdlib': '{userbase}/lib/python{py_version_short}', + 'platstdlib': '{userbase}/lib/python{py_version_short}', + 'purelib': '{userbase}/lib/python{py_version_short}/site-packages', + 'platlib': '{userbase}/lib/python{py_version_short}/site-packages', 'include': '{userbase}/include/python{py_version_short}', 'scripts': '{userbase}/bin', 'data' : '{userbase}', Modified: python/trunk/Lib/test/test_sysconfig.py ============================================================================== --- python/trunk/Lib/test/test_sysconfig.py (original) +++ python/trunk/Lib/test/test_sysconfig.py Thu May 20 00:20:14 2010 @@ -17,7 +17,7 @@ from sysconfig import (get_paths, get_platform, get_config_vars, get_path, get_path_names, _INSTALL_SCHEMES, _get_default_scheme, _expand_vars, - get_scheme_names) + get_scheme_names, get_config_var) class TestSysConfig(unittest.TestCase): @@ -255,6 +255,15 @@ finally: unlink(link) + def test_user_similar(self): + # Issue 8759 : make sure the posix scheme for the users + # is similar to the global posix_prefix one + base = get_config_var('base') + user = get_config_var('userbase') + for name in ('stdlib', 'platstdlib', 'purelib', 'platlib'): + global_path = get_path(name, 'posix_prefix') + user_path = get_path(name, 'posix_user') + self.assertEquals(user_path, global_path.replace(base, user)) def test_main(): run_unittest(TestSysConfig) Modified: python/trunk/Misc/NEWS ============================================================================== --- python/trunk/Misc/NEWS (original) +++ python/trunk/Misc/NEWS Thu May 20 00:20:14 2010 @@ -18,6 +18,8 @@ Library ------- +- Issue #8759: Fixed user paths in sysconfig for posix and os2 schemes. + - Issue #1285086: Speed up urllib.quote and urllib.unquote for simple cases. - Issue #8688: Distutils now recalculates MANIFEST everytime. From python-checkins at python.org Thu May 20 00:25:01 2010 From: python-checkins at python.org (tarek.ziade) Date: Thu, 20 May 2010 00:25:01 +0200 (CEST) Subject: [Python-checkins] r81372 - in python/branches/py3k: Lib/sysconfig.py Lib/test/test_sysconfig.py Misc/NEWS Message-ID: <20100519222501.1F7EFEE9A2@mail.python.org> Author: tarek.ziade Date: Thu May 20 00:25:00 2010 New Revision: 81372 Log: Merged revisions 81371 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r81371 | tarek.ziade | 2010-05-20 00:20:14 +0200 (Thu, 20 May 2010) | 1 line #8759: Fixed user paths in sysconfig for posix and os2 schemes ........ Modified: python/branches/py3k/ (props changed) python/branches/py3k/Lib/sysconfig.py python/branches/py3k/Lib/test/test_sysconfig.py python/branches/py3k/Misc/NEWS Modified: python/branches/py3k/Lib/sysconfig.py ============================================================================== --- python/branches/py3k/Lib/sysconfig.py (original) +++ python/branches/py3k/Lib/sysconfig.py Thu May 20 00:25:00 2010 @@ -47,10 +47,10 @@ 'data' : '{base}', }, 'os2_home': { - 'stdlib': '{userbase}/lib/python/{py_version_short}', - 'platstdlib': '{userbase}/lib/python/{py_version_short}', - 'purelib': '{userbase}/lib/python/{py_version_short}/site-packages', - 'platlib': '{userbase}/lib/python/{py_version_short}/site-packages', + 'stdlib': '{userbase}/lib/python{py_version_short}', + 'platstdlib': '{userbase}/lib/python{py_version_short}', + 'purelib': '{userbase}/lib/python{py_version_short}/site-packages', + 'platlib': '{userbase}/lib/python{py_version_short}/site-packages', 'include': '{userbase}/include/python{py_version_short}', 'scripts': '{userbase}/bin', 'data' : '{userbase}', @@ -65,10 +65,10 @@ 'data' : '{userbase}', }, 'posix_user': { - 'stdlib': '{userbase}/lib/python/{py_version_short}', - 'platstdlib': '{userbase}/lib/python/{py_version_short}', - 'purelib': '{userbase}/lib/python/{py_version_short}/site-packages', - 'platlib': '{userbase}/lib/python/{py_version_short}/site-packages', + 'stdlib': '{userbase}/lib/python{py_version_short}', + 'platstdlib': '{userbase}/lib/python{py_version_short}', + 'purelib': '{userbase}/lib/python{py_version_short}/site-packages', + 'platlib': '{userbase}/lib/python{py_version_short}/site-packages', 'include': '{userbase}/include/python{py_version_short}', 'scripts': '{userbase}/bin', 'data' : '{userbase}', Modified: python/branches/py3k/Lib/test/test_sysconfig.py ============================================================================== --- python/branches/py3k/Lib/test/test_sysconfig.py (original) +++ python/branches/py3k/Lib/test/test_sysconfig.py Thu May 20 00:25:00 2010 @@ -17,7 +17,7 @@ from sysconfig import (get_paths, get_platform, get_config_vars, get_path, get_path_names, _INSTALL_SCHEMES, _get_default_scheme, _expand_vars, - get_scheme_names) + get_scheme_names, get_config_var) class TestSysConfig(unittest.TestCase): @@ -254,6 +254,15 @@ finally: unlink(link) + def test_user_similar(self): + # Issue 8759 : make sure the posix scheme for the users + # is similar to the global posix_prefix one + base = get_config_var('base') + user = get_config_var('userbase') + for name in ('stdlib', 'platstdlib', 'purelib', 'platlib'): + global_path = get_path(name, 'posix_prefix') + user_path = get_path(name, 'posix_user') + self.assertEquals(user_path, global_path.replace(base, user)) def test_main(): run_unittest(TestSysConfig) Modified: python/branches/py3k/Misc/NEWS ============================================================================== --- python/branches/py3k/Misc/NEWS (original) +++ python/branches/py3k/Misc/NEWS Thu May 20 00:25:00 2010 @@ -375,6 +375,8 @@ Library ------- +- Issue #8759: Fixed user paths in sysconfig for posix and os2 schemes. + - Issue #8663: distutils.log emulates backslashreplace error handler. Fix compilation in a non-ASCII directory if stdout encoding is ASCII (eg. if stdout is not a TTY). From python-checkins at python.org Thu May 20 00:26:01 2010 From: python-checkins at python.org (tarek.ziade) Date: Thu, 20 May 2010 00:26:01 +0200 (CEST) Subject: [Python-checkins] r81373 - python/branches/release31-maint Message-ID: <20100519222601.C0952EEA2F@mail.python.org> Author: tarek.ziade Date: Thu May 20 00:26:01 2010 New Revision: 81373 Log: Blocked revisions 81372 via svnmerge ................ r81372 | tarek.ziade | 2010-05-20 00:25:00 +0200 (Thu, 20 May 2010) | 9 lines Merged revisions 81371 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r81371 | tarek.ziade | 2010-05-20 00:20:14 +0200 (Thu, 20 May 2010) | 1 line #8759: Fixed user paths in sysconfig for posix and os2 schemes ........ ................ Modified: python/branches/release31-maint/ (props changed) From python-checkins at python.org Thu May 20 00:26:49 2010 From: python-checkins at python.org (tarek.ziade) Date: Thu, 20 May 2010 00:26:49 +0200 (CEST) Subject: [Python-checkins] r81374 - python/branches/release26-maint Message-ID: <20100519222649.14251EEA91@mail.python.org> Author: tarek.ziade Date: Thu May 20 00:26:48 2010 New Revision: 81374 Log: Blocked revisions 81371 via svnmerge ........ r81371 | tarek.ziade | 2010-05-20 00:20:14 +0200 (Thu, 20 May 2010) | 1 line #8759: Fixed user paths in sysconfig for posix and os2 schemes ........ Modified: python/branches/release26-maint/ (props changed) From python-checkins at python.org Thu May 20 00:47:15 2010 From: python-checkins at python.org (tarek.ziade) Date: Thu, 20 May 2010 00:47:15 +0200 Subject: [Python-checkins] distutils2: added a dev note Message-ID: tarek.ziade pushed 7eff59171017 to distutils2: http://hg.python.org/distutils2/rev/7eff59171017 changeset: 154:7eff59171017 tag: tip user: Tarek Ziade date: Thu May 20 00:47:06 2010 +0200 summary: added a dev note files: src/distutils2/mkpkg.py diff --git a/src/distutils2/mkpkg.py b/src/distutils2/mkpkg.py --- a/src/distutils2/mkpkg.py +++ b/src/distutils2/mkpkg.py @@ -72,6 +72,8 @@ ''', } +# XXX this list should be asked at PyPI (it changes) +# then cached, rather than hardcoded troveList = [ 'Development Status :: 1 - Planning', 'Development Status :: 2 - Pre-Alpha', -- Repository URL: http://hg.python.org/distutils2 From python-checkins at python.org Thu May 20 01:04:57 2010 From: python-checkins at python.org (victor.stinner) Date: Thu, 20 May 2010 01:04:57 +0200 (CEST) Subject: [Python-checkins] r81375 - in python/branches/py3k: Lib/test/test_gdb.py Tools/gdb/libpython.py Message-ID: <20100519230457.00B4EEE9C2@mail.python.org> Author: victor.stinner Date: Thu May 20 01:04:56 2010 New Revision: 81375 Log: Issue #8559: improve unicode support of (gdb) libpython.py * Escape non printable characters (use locale.getpreferredencoding()) * Fix support of surrogate pairs * test_gdb.py: use ascii() instead of repr() in gdb program arguments to avoid encoding issues * Fix test_strings() of test_gdb.py for encoding different than UTF-8 (eg. ACSII) Modified: python/branches/py3k/Lib/test/test_gdb.py python/branches/py3k/Tools/gdb/libpython.py Modified: python/branches/py3k/Lib/test/test_gdb.py ============================================================================== --- python/branches/py3k/Lib/test/test_gdb.py (original) +++ python/branches/py3k/Lib/test/test_gdb.py Thu May 20 01:04:56 2010 @@ -8,6 +8,7 @@ import subprocess import sys import unittest +import locale from test.support import run_unittest, findfile @@ -177,7 +178,7 @@ def assertGdbRepr(self, val, exp_repr=None, cmds_after_breakpoint=None): # Ensure that gdb's rendering of the value in a debugged process # matches repr(value) in this process: - gdb_repr, gdb_output = self.get_gdb_repr('id(' + repr(val) + ')', + gdb_repr, gdb_output = self.get_gdb_repr('id(' + ascii(val) + ')', cmds_after_breakpoint) if not exp_repr: exp_repr = repr(val) @@ -226,31 +227,35 @@ def test_strings(self): 'Verify the pretty-printing of unicode strings' + encoding = locale.getpreferredencoding() + def check_repr(text): + try: + text.encode(encoding) + printable = True + except UnicodeEncodeError: + self.assertGdbRepr(text, ascii(text)) + else: + self.assertGdbRepr(text) + self.assertGdbRepr('') self.assertGdbRepr('And now for something hopefully the same') self.assertGdbRepr('string with embedded NUL here \0 and then some more text') # Test printing a single character: # U+2620 SKULL AND CROSSBONES - self.assertGdbRepr('\u2620') + check_repr('\u2620') # Test printing a Japanese unicode string # (I believe this reads "mojibake", using 3 characters from the CJK # Unified Ideographs area, followed by U+3051 HIRAGANA LETTER KE) - self.assertGdbRepr('\u6587\u5b57\u5316\u3051') + check_repr('\u6587\u5b57\u5316\u3051') # Test a character outside the BMP: # U+1D121 MUSICAL SYMBOL C CLEF # This is: # UTF-8: 0xF0 0x9D 0x84 0xA1 # UTF-16: 0xD834 0xDD21 - if sys.maxunicode == 0x10FFFF: - # wide unicode: - self.assertGdbRepr(chr(0x1D121)) - else: - # narrow unicode: - self.assertGdbRepr(chr(0x1D121), - "'\\U0000d834\\U0000dd21'") + check_repr(chr(0x1D121)) def test_tuples(self): 'Verify the pretty-printing of tuples' Modified: python/branches/py3k/Tools/gdb/libpython.py ============================================================================== --- python/branches/py3k/Tools/gdb/libpython.py (original) +++ python/branches/py3k/Tools/gdb/libpython.py Thu May 20 01:04:56 2010 @@ -42,6 +42,7 @@ ''' from __future__ import with_statement import gdb +import locale # Look up the gdb.Type for some standard types: _type_char_ptr = gdb.lookup_type('char').pointer() # char* @@ -69,6 +70,7 @@ hexdigits = "0123456789abcdef" +ENCODING = locale.getpreferredencoding() class NullPyObjectPtr(RuntimeError): pass @@ -1128,53 +1130,68 @@ # Non-ASCII characters else: - ucs = ch; - - if self.char_width == 2: - ch2 = 0 + ucs = ch + orig_ucs = None + if self.char_width() == 2: # Get code point from surrogate pair - if i < len(proxy): + if (i < len(proxy) + and 0xD800 <= ord(ch) < 0xDC00 \ + and 0xDC00 <= ord(proxy[i]) <= 0xDFFF): ch2 = proxy[i] - if (ord(ch) >= 0xD800 and ord(ch) < 0xDC00 - and ord(ch2) >= 0xDC00 and ord(ch2) <= 0xDFFF): - ucs = (((ch & 0x03FF) << 10) | (ch2 & 0x03FF)) + 0x00010000; - i += 1 + code = (ord(ch) & 0x03FF) << 10 + code |= ord(ch2) & 0x03FF + code += 0x00010000 + orig_ucs = ucs + ucs = unichr(code) + i += 1 + else: + ch2 = None + + printable = _unichr_is_printable(ucs) + if printable: + try: + ucs.encode(ENCODING) + except UnicodeEncodeError: + printable = False + if orig_ucs is not None: + ucs = orig_ucs + i -= 1 # Map Unicode whitespace and control characters # (categories Z* and C* except ASCII space) - if not _unichr_is_printable(ucs): + if not printable: # Unfortuately, Python 2's unicode type doesn't seem # to expose the "isprintable" method + code = ord(ucs) # Map 8-bit characters to '\\xhh' - if ucs <= 0xff: + if code <= 0xff: out.write('\\x') - out.write(hexdigits[(ord(ucs) >> 4) & 0x000F]) - out.write(hexdigits[ord(ucs) & 0x000F]) + out.write(hexdigits[(code >> 4) & 0x000F]) + out.write(hexdigits[code & 0x000F]) # Map 21-bit characters to '\U00xxxxxx' - elif ucs >= 0x10000: + elif code >= 0x10000: out.write('\\U') - out.write(hexdigits[(ord(ucs) >> 28) & 0x0000000F]) - out.write(hexdigits[(ord(ucs) >> 24) & 0x0000000F]) - out.write(hexdigits[(ord(ucs) >> 20) & 0x0000000F]) - out.write(hexdigits[(ord(ucs) >> 16) & 0x0000000F]) - out.write(hexdigits[(ord(ucs) >> 12) & 0x0000000F]) - out.write(hexdigits[(ord(ucs) >> 8) & 0x0000000F]) - out.write(hexdigits[(ord(ucs) >> 4) & 0x0000000F]) - out.write(hexdigits[ord(ucs) & 0x0000000F]) + out.write(hexdigits[(code >> 28) & 0x0000000F]) + out.write(hexdigits[(code >> 24) & 0x0000000F]) + out.write(hexdigits[(code >> 20) & 0x0000000F]) + out.write(hexdigits[(code >> 16) & 0x0000000F]) + out.write(hexdigits[(code >> 12) & 0x0000000F]) + out.write(hexdigits[(code >> 8) & 0x0000000F]) + out.write(hexdigits[(code >> 4) & 0x0000000F]) + out.write(hexdigits[code & 0x0000000F]) # Map 16-bit characters to '\uxxxx' else: out.write('\\u') - out.write(hexdigits[(ord(ucs) >> 12) & 0x000F]) - out.write(hexdigits[(ord(ucs) >> 8) & 0x000F]) - out.write(hexdigits[(ord(ucs) >> 4) & 0x000F]) - out.write(hexdigits[ord(ucs) & 0x000F]) + out.write(hexdigits[(code >> 12) & 0x000F]) + out.write(hexdigits[(code >> 8) & 0x000F]) + out.write(hexdigits[(code >> 4) & 0x000F]) + out.write(hexdigits[code & 0x000F]) else: # Copy characters as-is out.write(ch) - if self.char_width == 2: - if ord(ucs) >= 0x10000: - out.write(ch2) + if self.char_width() == 2 and (ch2 is not None): + out.write(ch2) out.write(quote) From solipsis at pitrou.net Thu May 20 01:25:48 2010 From: solipsis at pitrou.net (solipsis at pitrou.net) Date: Thu, 20 May 2010 01:25:48 +0200 (CEST) Subject: [Python-checkins] Daily py3k reference leaks (r81368): sum=0 Message-ID: <20100519232549.043751771F@ns6635.ovh.net> py3k results for svn r81368 (hg cset d0c11ace2503) -------------------------------------------------- Command line was: ['./python', '-m', 'test.regrtest', '-uall', '-R', '3:3:/home/antoine/py3k/refleaks/reflogmQ8NEm', '-x'] From python-checkins at python.org Thu May 20 12:41:41 2010 From: python-checkins at python.org (victor.stinner) Date: Thu, 20 May 2010 12:41:41 +0200 (CEST) Subject: [Python-checkins] r81376 - python/branches/release31-maint Message-ID: <20100520104141.EAF98DD0D@mail.python.org> Author: victor.stinner Date: Thu May 20 12:41:41 2010 New Revision: 81376 Log: Blocked revisions 81375 via svnmerge ........ r81375 | victor.stinner | 2010-05-20 01:04:56 +0200 (jeu., 20 mai 2010) | 9 lines Issue #8559: improve unicode support of (gdb) libpython.py * Escape non printable characters (use locale.getpreferredencoding()) * Fix support of surrogate pairs * test_gdb.py: use ascii() instead of repr() in gdb program arguments to avoid encoding issues * Fix test_strings() of test_gdb.py for encoding different than UTF-8 (eg. ACSII) ........ Modified: python/branches/release31-maint/ (props changed) From python-checkins at python.org Thu May 20 13:29:45 2010 From: python-checkins at python.org (victor.stinner) Date: Thu, 20 May 2010 13:29:45 +0200 (CEST) Subject: [Python-checkins] r81377 - in python/trunk: Lib/test/test_gdb.py Tools/gdb/libpython.py Message-ID: <20100520112945.9B08FC918@mail.python.org> Author: victor.stinner Date: Thu May 20 13:29:45 2010 New Revision: 81377 Log: libpython.py: fix support of non-BMP unicode characters Forward port some code from Python3: * join surrogate pairs if sizeof(Py_UNICODE)==2 * Enable non-BMP test on narrow builds using u"\U0001D121" instead of unichr(0x1D121) Modified: python/trunk/Lib/test/test_gdb.py python/trunk/Tools/gdb/libpython.py Modified: python/trunk/Lib/test/test_gdb.py ============================================================================== --- python/trunk/Lib/test/test_gdb.py (original) +++ python/trunk/Lib/test/test_gdb.py Thu May 20 13:29:45 2010 @@ -243,14 +243,8 @@ # This is: # UTF-8: 0xF0 0x9D 0x84 0xA1 # UTF-16: 0xD834 0xDD21 - try: - # This will only work on wide-unicode builds: - self.assertGdbRepr(unichr(0x1D121)) - except ValueError, e: - # We're probably on a narrow-unicode build; if we're seeing a - # different problem, then re-raise it: - if e.args != ('unichr() arg not in range(0x10000) (narrow Python build)',): - raise e + # This will only work on wide-unicode builds: + self.assertGdbRepr(u"\U0001D121") def test_sets(self): 'Verify the pretty-printing of sets' Modified: python/trunk/Tools/gdb/libpython.py ============================================================================== --- python/trunk/Tools/gdb/libpython.py (original) +++ python/trunk/Tools/gdb/libpython.py Thu May 20 13:29:45 2010 @@ -1013,6 +1013,10 @@ class PyUnicodeObjectPtr(PyObjectPtr): _typename = 'PyUnicodeObject' + def char_width(self): + _type_Py_UNICODE = gdb.lookup_type('Py_UNICODE') + return _type_Py_UNICODE.sizeof + def proxyval(self, visited): # From unicodeobject.h: # Py_ssize_t length; /* Length of raw Unicode data in buffer */ @@ -1029,6 +1033,30 @@ result = u''.join([unichr(ucs) for ucs in Py_UNICODEs]) return result + def write_repr(self, out, visited): + proxy = self.proxyval(visited) + if self.char_width() == 2: + # sizeof(Py_UNICODE)==2: join surrogates + proxy2 = [] + i = 0 + while i < len(proxy): + ch = proxy[i] + i += 1 + if (i < len(proxy) + and 0xD800 <= ord(ch) < 0xDC00 \ + and 0xDC00 <= ord(proxy[i]) <= 0xDFFF): + # Get code point from surrogate pair + ch2 = proxy[i] + code = (ord(ch) & 0x03FF) << 10 + code |= ord(ch2) & 0x03FF + code += 0x00010000 + i += 1 + proxy2.append(unichr(code)) + else: + proxy2.append(ch) + proxy = u''.join(proxy2) + out.write(repr(proxy)) + def int_from_int(gdbval): return int(str(gdbval)) From python-checkins at python.org Thu May 20 13:30:37 2010 From: python-checkins at python.org (victor.stinner) Date: Thu, 20 May 2010 13:30:37 +0200 (CEST) Subject: [Python-checkins] r81378 - python/branches/py3k Message-ID: <20100520113037.DC9DDC918@mail.python.org> Author: victor.stinner Date: Thu May 20 13:30:37 2010 New Revision: 81378 Log: Blocked revisions 81377 via svnmerge ........ r81377 | victor.stinner | 2010-05-20 13:29:45 +0200 (jeu., 20 mai 2010) | 8 lines libpython.py: fix support of non-BMP unicode characters Forward port some code from Python3: * join surrogate pairs if sizeof(Py_UNICODE)==2 * Enable non-BMP test on narrow builds using u"\U0001D121" instead of unichr(0x1D121) ........ Modified: python/branches/py3k/ (props changed) From python-checkins at python.org Thu May 20 13:31:06 2010 From: python-checkins at python.org (victor.stinner) Date: Thu, 20 May 2010 13:31:06 +0200 (CEST) Subject: [Python-checkins] r81379 - python/branches/release26-maint Message-ID: <20100520113106.6F539C918@mail.python.org> Author: victor.stinner Date: Thu May 20 13:31:06 2010 New Revision: 81379 Log: Blocked revisions 81377 via svnmerge ........ r81377 | victor.stinner | 2010-05-20 13:29:45 +0200 (jeu., 20 mai 2010) | 8 lines libpython.py: fix support of non-BMP unicode characters Forward port some code from Python3: * join surrogate pairs if sizeof(Py_UNICODE)==2 * Enable non-BMP test on narrow builds using u"\U0001D121" instead of unichr(0x1D121) ........ Modified: python/branches/release26-maint/ (props changed) From nnorwitz at gmail.com Thu May 20 14:07:04 2010 From: nnorwitz at gmail.com (Neal Norwitz) Date: Thu, 20 May 2010 08:07:04 -0400 Subject: [Python-checkins] Python Regression Test Failures all (2) Message-ID: <20100520120703.GA12567@kbk-i386-bb.psfb.org> 352 tests OK. 1 test failed: test_mailbox 28 tests skipped: test_aepack test_al test_applesingle test_bsddb185 test_cd test_cl test_epoll test_gdb test_gl test_imgfile test_ioctl test_kqueue test_macos test_macostools test_multiprocessing test_pep277 test_py3kwarn test_scriptpackages test_startfile test_sunaudiodev test_tcl test_tk test_ttk_guionly test_ttk_textonly test_unicode_file test_winreg test_winsound test_zipfile64 7 skips unexpected on linux2: test_epoll test_gdb test_ioctl test_multiprocessing test_tk test_ttk_guionly test_ttk_textonly test test_mailbox crashed -- : [Errno 2] No such file or directory Re-running test 'test_mailbox' in verbose mode test test_mailbox crashed -- : [Errno 2] No such file or directory Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 861, in runtest_inner with saved_test_environment(test, verbose, quiet) as environment: File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 814, in __enter__ in self.resource_info()) File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 813, in self.saved_values = dict((name, get()) for name, get, restore File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 773, in get_cwd return os.getcwd() OSError: [Errno 2] No such file or directory test_marshal test test_marshal crashed -- : [Errno 2] No such file or directory Re-running test 'test_marshal' in verbose mode test test_marshal crashed -- : [Errno 2] No such file or directory Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 861, in runtest_inner with saved_test_environment(test, verbose, quiet) as environment: File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 814, in __enter__ in self.resource_info()) File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 813, in self.saved_values = dict((name, get()) for name, get, restore File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 773, in get_cwd return os.getcwd() OSError: [Errno 2] No such file or directory test_math test test_math crashed -- : [Errno 2] No such file or directory Re-running test 'test_math' in verbose mode test test_math crashed -- : [Errno 2] No such file or directory Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 861, in runtest_inner with saved_test_environment(test, verbose, quiet) as environment: File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 814, in __enter__ in self.resource_info()) File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 813, in self.saved_values = dict((name, get()) for name, get, restore File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 773, in get_cwd return os.getcwd() OSError: [Errno 2] No such file or directory test_md5 test test_md5 crashed -- : [Errno 2] No such file or directory Re-running test 'test_md5' in verbose mode test test_md5 crashed -- : [Errno 2] No such file or directory Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 861, in runtest_inner with saved_test_environment(test, verbose, quiet) as environment: File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 814, in __enter__ in self.resource_info()) File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 813, in self.saved_values = dict((name, get()) for name, get, restore File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 773, in get_cwd return os.getcwd() OSError: [Errno 2] No such file or directory test_memoryio test test_memoryio crashed -- : [Errno 2] No such file or directory Re-running test 'test_memoryio' in verbose mode test test_memoryio crashed -- : [Errno 2] No such file or directory Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 861, in runtest_inner with saved_test_environment(test, verbose, quiet) as environment: File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 814, in __enter__ in self.resource_info()) File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 813, in self.saved_values = dict((name, get()) for name, get, restore File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 773, in get_cwd return os.getcwd() OSError: [Errno 2] No such file or directory test_memoryview test test_memoryview crashed -- : [Errno 2] No such file or directory Re-running test 'test_memoryview' in verbose mode test test_memoryview crashed -- : [Errno 2] No such file or directory Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 861, in runtest_inner with saved_test_environment(test, verbose, quiet) as environment: File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 814, in __enter__ in self.resource_info()) File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 813, in self.saved_values = dict((name, get()) for name, get, restore File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 773, in get_cwd return os.getcwd() OSError: [Errno 2] No such file or directory test_mhlib test test_mhlib crashed -- : [Errno 2] No such file or directory Re-running test 'test_mhlib' in verbose mode test test_mhlib crashed -- : [Errno 2] No such file or directory Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 861, in runtest_inner with saved_test_environment(test, verbose, quiet) as environment: File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 814, in __enter__ in self.resource_info()) File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 813, in self.saved_values = dict((name, get()) for name, get, restore File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 773, in get_cwd return os.getcwd() OSError: [Errno 2] No such file or directory test_mimetools test test_mimetools crashed -- : [Errno 2] No such file or directory Re-running test 'test_mimetools' in verbose mode test test_mimetools crashed -- : [Errno 2] No such file or directory Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 861, in runtest_inner with saved_test_environment(test, verbose, quiet) as environment: File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 814, in __enter__ in self.resource_info()) File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 813, in self.saved_values = dict((name, get()) for name, get, restore File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 773, in get_cwd return os.getcwd() OSError: [Errno 2] No such file or directory test_mimetypes test test_mimetypes crashed -- : [Errno 2] No such file or directory Re-running test 'test_mimetypes' in verbose mode test test_mimetypes crashed -- : [Errno 2] No such file or directory Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 861, in runtest_inner with saved_test_environment(test, verbose, quiet) as environment: File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 814, in __enter__ in self.resource_info()) File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 813, in self.saved_values = dict((name, get()) for name, get, restore File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 773, in get_cwd return os.getcwd() OSError: [Errno 2] No such file or directory test_minidom test test_minidom crashed -- : [Errno 2] No such file or directory Re-running test 'test_minidom' in verbose mode test test_minidom crashed -- : [Errno 2] No such file or directory Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 861, in runtest_inner with saved_test_environment(test, verbose, quiet) as environment: File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 814, in __enter__ in self.resource_info()) File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 813, in self.saved_values = dict((name, get()) for name, get, restore File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 773, in get_cwd return os.getcwd() OSError: [Errno 2] No such file or directory test_mmap test test_mmap crashed -- : [Errno 2] No such file or directory Re-running test 'test_mmap' in verbose mode test test_mmap crashed -- : [Errno 2] No such file or directory Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 861, in runtest_inner with saved_test_environment(test, verbose, quiet) as environment: File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 814, in __enter__ in self.resource_info()) File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 813, in self.saved_values = dict((name, get()) for name, get, restore File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 773, in get_cwd return os.getcwd() OSError: [Errno 2] No such file or directory test_module test test_module crashed -- : [Errno 2] No such file or directory Re-running test 'test_module' in verbose mode test test_module crashed -- : [Errno 2] No such file or directory Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 861, in runtest_inner with saved_test_environment(test, verbose, quiet) as environment: File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 814, in __enter__ in self.resource_info()) File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 813, in self.saved_values = dict((name, get()) for name, get, restore File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 773, in get_cwd return os.getcwd() OSError: [Errno 2] No such file or directory test_modulefinder test test_modulefinder crashed -- : [Errno 2] No such file or directory Re-running test 'test_modulefinder' in verbose mode test test_modulefinder crashed -- : [Errno 2] No such file or directory Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 861, in runtest_inner with saved_test_environment(test, verbose, quiet) as environment: File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 814, in __enter__ in self.resource_info()) File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 813, in self.saved_values = dict((name, get()) for name, get, restore File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 773, in get_cwd return os.getcwd() OSError: [Errno 2] No such file or directory test_multibytecodec test test_multibytecodec crashed -- : [Errno 2] No such file or directory Re-running test 'test_multibytecodec' in verbose mode test test_multibytecodec crashed -- : [Errno 2] No such file or directory Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 861, in runtest_inner with saved_test_environment(test, verbose, quiet) as environment: File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 814, in __enter__ in self.resource_info()) File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 813, in self.saved_values = dict((name, get()) for name, get, restore File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 773, in get_cwd return os.getcwd() OSError: [Errno 2] No such file or directory test_multibytecodec_support test test_multibytecodec_support crashed -- : [Errno 2] No such file or directory Re-running test 'test_multibytecodec_support' in verbose mode test test_multibytecodec_support crashed -- : [Errno 2] No such file or directory Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 861, in runtest_inner with saved_test_environment(test, verbose, quiet) as environment: File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 814, in __enter__ in self.resource_info()) File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 813, in self.saved_values = dict((name, get()) for name, get, restore File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 773, in get_cwd return os.getcwd() OSError: [Errno 2] No such file or directory test_multifile test test_multifile crashed -- : [Errno 2] No such file or directory Re-running test 'test_multifile' in verbose mode test test_multifile crashed -- : [Errno 2] No such file or directory Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 861, in runtest_inner with saved_test_environment(test, verbose, quiet) as environment: File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 814, in __enter__ in self.resource_info()) File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 813, in self.saved_values = dict((name, get()) for name, get, restore File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 773, in get_cwd return os.getcwd() OSError: [Errno 2] No such file or directory test_multiprocessing test test_multiprocessing crashed -- : [Errno 2] No such file or directory Re-running test 'test_multiprocessing' in verbose mode test test_multiprocessing crashed -- : [Errno 2] No such file or directory Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 861, in runtest_inner with saved_test_environment(test, verbose, quiet) as environment: File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 814, in __enter__ in self.resource_info()) File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 813, in self.saved_values = dict((name, get()) for name, get, restore File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 773, in get_cwd return os.getcwd() OSError: [Errno 2] No such file or directory test_mutants test test_mutants crashed -- : [Errno 2] No such file or directory Re-running test 'test_mutants' in verbose mode test test_mutants crashed -- : [Errno 2] No such file or directory Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 861, in runtest_inner with saved_test_environment(test, verbose, quiet) as environment: File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 814, in __enter__ in self.resource_info()) File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 813, in self.saved_values = dict((name, get()) for name, get, restore File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 773, in get_cwd return os.getcwd() OSError: [Errno 2] No such file or directory test_mutex test test_mutex crashed -- : [Errno 2] No such file or directory Re-running test 'test_mutex' in verbose mode test test_mutex crashed -- : [Errno 2] No such file or directory Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 861, in runtest_inner with saved_test_environment(test, verbose, quiet) as environment: File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 814, in __enter__ in self.resource_info()) File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 813, in self.saved_values = dict((name, get()) for name, get, restore File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 773, in get_cwd return os.getcwd() OSError: [Errno 2] No such file or directory test_netrc test test_netrc crashed -- : [Errno 2] No such file or directory Re-running test 'test_netrc' in verbose mode test test_netrc crashed -- : [Errno 2] No such file or directory Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 861, in runtest_inner with saved_test_environment(test, verbose, quiet) as environment: File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 814, in __enter__ in self.resource_info()) File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 813, in self.saved_values = dict((name, get()) for name, get, restore File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 773, in get_cwd return os.getcwd() OSError: [Errno 2] No such file or directory test_new test test_new crashed -- : [Errno 2] No such file or directory Re-running test 'test_new' in verbose mode test test_new crashed -- : [Errno 2] No such file or directory Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 861, in runtest_inner with saved_test_environment(test, verbose, quiet) as environment: File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 814, in __enter__ in self.resource_info()) File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 813, in self.saved_values = dict((name, get()) for name, get, restore File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 773, in get_cwd return os.getcwd() OSError: [Errno 2] No such file or directory test_nis test test_nis crashed -- : [Errno 2] No such file or directory Re-running test 'test_nis' in verbose mode test test_nis crashed -- : [Errno 2] No such file or directory Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 861, in runtest_inner with saved_test_environment(test, verbose, quiet) as environment: File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 814, in __enter__ in self.resource_info()) File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 813, in self.saved_values = dict((name, get()) for name, get, restore File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 773, in get_cwd return os.getcwd() OSError: [Errno 2] No such file or directory test_normalization test test_normalization crashed -- : [Errno 2] No such file or directory Re-running test 'test_normalization' in verbose mode test test_normalization crashed -- : [Errno 2] No such file or directory Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 861, in runtest_inner with saved_test_environment(test, verbose, quiet) as environment: File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 814, in __enter__ in self.resource_info()) File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 813, in self.saved_values = dict((name, get()) for name, get, restore File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 773, in get_cwd return os.getcwd() OSError: [Errno 2] No such file or directory test_ntpath test test_ntpath crashed -- : [Errno 2] No such file or directory Re-running test 'test_ntpath' in verbose mode test test_ntpath crashed -- : [Errno 2] No such file or directory Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 861, in runtest_inner with saved_test_environment(test, verbose, quiet) as environment: File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 814, in __enter__ in self.resource_info()) File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 813, in self.saved_values = dict((name, get()) for name, get, restore File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 773, in get_cwd return os.getcwd() OSError: [Errno 2] No such file or directory test_old_mailbox test test_old_mailbox crashed -- : [Errno 2] No such file or directory Re-running test 'test_old_mailbox' in verbose mode test test_old_mailbox crashed -- : [Errno 2] No such file or directory Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 861, in runtest_inner with saved_test_environment(test, verbose, quiet) as environment: File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 814, in __enter__ in self.resource_info()) File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 813, in self.saved_values = dict((name, get()) for name, get, restore File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 773, in get_cwd return os.getcwd() OSError: [Errno 2] No such file or directory test_openpty test test_openpty crashed -- : [Errno 2] No such file or directory Re-running test 'test_openpty' in verbose mode test test_openpty crashed -- : [Errno 2] No such file or directory Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 861, in runtest_inner with saved_test_environment(test, verbose, quiet) as environment: File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 814, in __enter__ in self.resource_info()) File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 813, in self.saved_values = dict((name, get()) for name, get, restore File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 773, in get_cwd return os.getcwd() OSError: [Errno 2] No such file or directory test_operator test test_operator crashed -- : [Errno 2] No such file or directory Re-running test 'test_operator' in verbose mode test test_operator crashed -- : [Errno 2] No such file or directory Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 861, in runtest_inner with saved_test_environment(test, verbose, quiet) as environment: File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 814, in __enter__ in self.resource_info()) File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 813, in self.saved_values = dict((name, get()) for name, get, restore File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 773, in get_cwd return os.getcwd() OSError: [Errno 2] No such file or directory test_optparse test test_optparse crashed -- : [Errno 2] No such file or directory Re-running test 'test_optparse' in verbose mode test test_optparse crashed -- : [Errno 2] No such file or directory Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 861, in runtest_inner with saved_test_environment(test, verbose, quiet) as environment: File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 814, in __enter__ in self.resource_info()) File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 813, in self.saved_values = dict((name, get()) for name, get, restore File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 773, in get_cwd return os.getcwd() OSError: [Errno 2] No such file or directory test_os test test_os crashed -- : [Errno 2] No such file or directory Re-running test 'test_os' in verbose mode test test_os crashed -- : [Errno 2] No such file or directory Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 861, in runtest_inner with saved_test_environment(test, verbose, quiet) as environment: File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 814, in __enter__ in self.resource_info()) File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 813, in self.saved_values = dict((name, get()) for name, get, restore File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 773, in get_cwd return os.getcwd() OSError: [Errno 2] No such file or directory test_parser test test_parser crashed -- : [Errno 2] No such file or directory Re-running test 'test_parser' in verbose mode test test_parser crashed -- : [Errno 2] No such file or directory Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 861, in runtest_inner with saved_test_environment(test, verbose, quiet) as environment: File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 814, in __enter__ in self.resource_info()) File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 813, in self.saved_values = dict((name, get()) for name, get, restore File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 773, in get_cwd return os.getcwd() OSError: [Errno 2] No such file or directory test_pdb test test_pdb crashed -- : [Errno 2] No such file or directory Re-running test 'test_pdb' in verbose mode test test_pdb crashed -- : [Errno 2] No such file or directory Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 861, in runtest_inner with saved_test_environment(test, verbose, quiet) as environment: File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 814, in __enter__ in self.resource_info()) File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 813, in self.saved_values = dict((name, get()) for name, get, restore File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 773, in get_cwd return os.getcwd() OSError: [Errno 2] No such file or directory test_peepholer test test_peepholer crashed -- : [Errno 2] No such file or directory Re-running test 'test_peepholer' in verbose mode test test_peepholer crashed -- : [Errno 2] No such file or directory Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 861, in runtest_inner with saved_test_environment(test, verbose, quiet) as environment: File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 814, in __enter__ in self.resource_info()) File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 813, in self.saved_values = dict((name, get()) for name, get, restore File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 773, in get_cwd return os.getcwd() OSError: [Errno 2] No such file or directory test_pep247 test test_pep247 crashed -- : [Errno 2] No such file or directory Re-running test 'test_pep247' in verbose mode test test_pep247 crashed -- : [Errno 2] No such file or directory Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 861, in runtest_inner with saved_test_environment(test, verbose, quiet) as environment: File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 814, in __enter__ in self.resource_info()) File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 813, in self.saved_values = dict((name, get()) for name, get, restore File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 773, in get_cwd return os.getcwd() OSError: [Errno 2] No such file or directory test_pep263 test test_pep263 crashed -- : [Errno 2] No such file or directory Re-running test 'test_pep263' in verbose mode test test_pep263 crashed -- : [Errno 2] No such file or directory Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 861, in runtest_inner with saved_test_environment(test, verbose, quiet) as environment: File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 814, in __enter__ in self.resource_info()) File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 813, in self.saved_values = dict((name, get()) for name, get, restore File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 773, in get_cwd return os.getcwd() OSError: [Errno 2] No such file or directory test_pep277 test test_pep277 crashed -- : [Errno 2] No such file or directory Re-running test 'test_pep277' in verbose mode test test_pep277 crashed -- : [Errno 2] No such file or directory Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 861, in runtest_inner with saved_test_environment(test, verbose, quiet) as environment: File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 814, in __enter__ in self.resource_info()) File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 813, in self.saved_values = dict((name, get()) for name, get, restore File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 773, in get_cwd return os.getcwd() OSError: [Errno 2] No such file or directory test_pep292 test test_pep292 crashed -- : [Errno 2] No such file or directory Re-running test 'test_pep292' in verbose mode test test_pep292 crashed -- : [Errno 2] No such file or directory Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 861, in runtest_inner with saved_test_environment(test, verbose, quiet) as environment: File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 814, in __enter__ in self.resource_info()) File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 813, in self.saved_values = dict((name, get()) for name, get, restore File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 773, in get_cwd return os.getcwd() OSError: [Errno 2] No such file or directory test_pep352 test test_pep352 crashed -- : [Errno 2] No such file or directory Re-running test 'test_pep352' in verbose mode test test_pep352 crashed -- : [Errno 2] No such file or directory Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 861, in runtest_inner with saved_test_environment(test, verbose, quiet) as environment: File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 814, in __enter__ in self.resource_info()) File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 813, in self.saved_values = dict((name, get()) for name, get, restore File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 773, in get_cwd return os.getcwd() OSError: [Errno 2] No such file or directory test_pickle test test_pickle crashed -- : [Errno 2] No such file or directory Re-running test 'test_pickle' in verbose mode test test_pickle crashed -- : [Errno 2] No such file or directory Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 861, in runtest_inner with saved_test_environment(test, verbose, quiet) as environment: File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 814, in __enter__ in self.resource_info()) File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 813, in self.saved_values = dict((name, get()) for name, get, restore File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 773, in get_cwd return os.getcwd() OSError: [Errno 2] No such file or directory test_pickletools test test_pickletools crashed -- : [Errno 2] No such file or directory Re-running test 'test_pickletools' in verbose mode test test_pickletools crashed -- : [Errno 2] No such file or directory Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 861, in runtest_inner with saved_test_environment(test, verbose, quiet) as environment: File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 814, in __enter__ in self.resource_info()) File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 813, in self.saved_values = dict((name, get()) for name, get, restore File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 773, in get_cwd return os.getcwd() OSError: [Errno 2] No such file or directory test_pipes test test_pipes crashed -- : [Errno 2] No such file or directory Re-running test 'test_pipes' in verbose mode test test_pipes crashed -- : [Errno 2] No such file or directory Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 861, in runtest_inner with saved_test_environment(test, verbose, quiet) as environment: File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 814, in __enter__ in self.resource_info()) File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 813, in self.saved_values = dict((name, get()) for name, get, restore File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 773, in get_cwd return os.getcwd() OSError: [Errno 2] No such file or directory test_pkg test test_pkg crashed -- : [Errno 2] No such file or directory Re-running test 'test_pkg' in verbose mode test test_pkg crashed -- : [Errno 2] No such file or directory Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 861, in runtest_inner with saved_test_environment(test, verbose, quiet) as environment: File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 814, in __enter__ in self.resource_info()) File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 813, in self.saved_values = dict((name, get()) for name, get, restore File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 773, in get_cwd return os.getcwd() OSError: [Errno 2] No such file or directory test_pkgimport test test_pkgimport crashed -- : [Errno 2] No such file or directory Re-running test 'test_pkgimport' in verbose mode test test_pkgimport crashed -- : [Errno 2] No such file or directory Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 861, in runtest_inner with saved_test_environment(test, verbose, quiet) as environment: File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 814, in __enter__ in self.resource_info()) File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 813, in self.saved_values = dict((name, get()) for name, get, restore File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 773, in get_cwd return os.getcwd() OSError: [Errno 2] No such file or directory test_pkgutil test test_pkgutil crashed -- : [Errno 2] No such file or directory Re-running test 'test_pkgutil' in verbose mode test test_pkgutil crashed -- : [Errno 2] No such file or directory Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 861, in runtest_inner with saved_test_environment(test, verbose, quiet) as environment: File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 814, in __enter__ in self.resource_info()) File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 813, in self.saved_values = dict((name, get()) for name, get, restore File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 773, in get_cwd return os.getcwd() OSError: [Errno 2] No such file or directory test_platform test test_platform crashed -- : [Errno 2] No such file or directory Re-running test 'test_platform' in verbose mode test test_platform crashed -- : [Errno 2] No such file or directory Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 861, in runtest_inner with saved_test_environment(test, verbose, quiet) as environment: File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 814, in __enter__ in self.resource_info()) File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 813, in self.saved_values = dict((name, get()) for name, get, restore File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 773, in get_cwd return os.getcwd() OSError: [Errno 2] No such file or directory test_plistlib test test_plistlib crashed -- : [Errno 2] No such file or directory Re-running test 'test_plistlib' in verbose mode test test_plistlib crashed -- : [Errno 2] No such file or directory Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 861, in runtest_inner with saved_test_environment(test, verbose, quiet) as environment: File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 814, in __enter__ in self.resource_info()) File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 813, in self.saved_values = dict((name, get()) for name, get, restore File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 773, in get_cwd return os.getcwd() OSError: [Errno 2] No such file or directory test_poll test test_poll crashed -- : [Errno 2] No such file or directory Re-running test 'test_poll' in verbose mode test test_poll crashed -- : [Errno 2] No such file or directory Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 861, in runtest_inner with saved_test_environment(test, verbose, quiet) as environment: File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 814, in __enter__ in self.resource_info()) File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 813, in self.saved_values = dict((name, get()) for name, get, restore File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 773, in get_cwd return os.getcwd() OSError: [Errno 2] No such file or directory test_popen test test_popen crashed -- : [Errno 2] No such file or directory Re-running test 'test_popen' in verbose mode test test_popen crashed -- : [Errno 2] No such file or directory Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 861, in runtest_inner with saved_test_environment(test, verbose, quiet) as environment: File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 814, in __enter__ in self.resource_info()) File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 813, in self.saved_values = dict((name, get()) for name, get, restore File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 773, in get_cwd return os.getcwd() OSError: [Errno 2] No such file or directory test_popen2 test test_popen2 crashed -- : [Errno 2] No such file or directory Re-running test 'test_popen2' in verbose mode test test_popen2 crashed -- : [Errno 2] No such file or directory Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 861, in runtest_inner with saved_test_environment(test, verbose, quiet) as environment: File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 814, in __enter__ in self.resource_info()) File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 813, in self.saved_values = dict((name, get()) for name, get, restore File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 773, in get_cwd return os.getcwd() OSError: [Errno 2] No such file or directory test_poplib test test_poplib crashed -- : [Errno 2] No such file or directory Re-running test 'test_poplib' in verbose mode test test_poplib crashed -- : [Errno 2] No such file or directory Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 861, in runtest_inner with saved_test_environment(test, verbose, quiet) as environment: File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 814, in __enter__ in self.resource_info()) File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 813, in self.saved_values = dict((name, get()) for name, get, restore File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 773, in get_cwd return os.getcwd() OSError: [Errno 2] No such file or directory test_posix test test_posix crashed -- : [Errno 2] No such file or directory Re-running test 'test_posix' in verbose mode test test_posix crashed -- : [Errno 2] No such file or directory Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 861, in runtest_inner with saved_test_environment(test, verbose, quiet) as environment: File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 814, in __enter__ in self.resource_info()) File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 813, in self.saved_values = dict((name, get()) for name, get, restore File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 773, in get_cwd return os.getcwd() OSError: [Errno 2] No such file or directory test_posixpath test test_posixpath crashed -- : [Errno 2] No such file or directory Re-running test 'test_posixpath' in verbose mode test test_posixpath crashed -- : [Errno 2] No such file or directory Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 861, in runtest_inner with saved_test_environment(test, verbose, quiet) as environment: File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 814, in __enter__ in self.resource_info()) File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 813, in self.saved_values = dict((name, get()) for name, get, restore File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 773, in get_cwd return os.getcwd() OSError: [Errno 2] No such file or directory test_pow test test_pow crashed -- : [Errno 2] No such file or directory Re-running test 'test_pow' in verbose mode test test_pow crashed -- : [Errno 2] No such file or directory Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 861, in runtest_inner with saved_test_environment(test, verbose, quiet) as environment: File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 814, in __enter__ in self.resource_info()) File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 813, in self.saved_values = dict((name, get()) for name, get, restore File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 773, in get_cwd return os.getcwd() OSError: [Errno 2] No such file or directory test_pprint test test_pprint crashed -- : [Errno 2] No such file or directory Re-running test 'test_pprint' in verbose mode test test_pprint crashed -- : [Errno 2] No such file or directory Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 861, in runtest_inner with saved_test_environment(test, verbose, quiet) as environment: File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 814, in __enter__ in self.resource_info()) File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 813, in self.saved_values = dict((name, get()) for name, get, restore File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 773, in get_cwd return os.getcwd() OSError: [Errno 2] No such file or directory test_print test test_print crashed -- : [Errno 2] No such file or directory Re-running test 'test_print' in verbose mode test test_print crashed -- : [Errno 2] No such file or directory Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 861, in runtest_inner with saved_test_environment(test, verbose, quiet) as environment: File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 814, in __enter__ in self.resource_info()) File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 813, in self.saved_values = dict((name, get()) for name, get, restore File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 773, in get_cwd return os.getcwd() OSError: [Errno 2] No such file or directory test_profile test test_profile crashed -- : [Errno 2] No such file or directory Re-running test 'test_profile' in verbose mode test test_profile crashed -- : [Errno 2] No such file or directory Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 861, in runtest_inner with saved_test_environment(test, verbose, quiet) as environment: File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 814, in __enter__ in self.resource_info()) File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 813, in self.saved_values = dict((name, get()) for name, get, restore File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 773, in get_cwd return os.getcwd() OSError: [Errno 2] No such file or directory test_profilehooks test test_profilehooks crashed -- : [Errno 2] No such file or directory Re-running test 'test_profilehooks' in verbose mode test test_profilehooks crashed -- : [Errno 2] No such file or directory Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 861, in runtest_inner with saved_test_environment(test, verbose, quiet) as environment: File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 814, in __enter__ in self.resource_info()) File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 813, in self.saved_values = dict((name, get()) for name, get, restore File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 773, in get_cwd return os.getcwd() OSError: [Errno 2] No such file or directory test_property test test_property crashed -- : [Errno 2] No such file or directory Re-running test 'test_property' in verbose mode test test_property crashed -- : [Errno 2] No such file or directory Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 861, in runtest_inner with saved_test_environment(test, verbose, quiet) as environment: File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 814, in __enter__ in self.resource_info()) File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 813, in self.saved_values = dict((name, get()) for name, get, restore File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 773, in get_cwd return os.getcwd() OSError: [Errno 2] No such file or directory test_pstats test test_pstats crashed -- : [Errno 2] No such file or directory Re-running test 'test_pstats' in verbose mode test test_pstats crashed -- : [Errno 2] No such file or directory Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 861, in runtest_inner with saved_test_environment(test, verbose, quiet) as environment: File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 814, in __enter__ in self.resource_info()) File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 813, in self.saved_values = dict((name, get()) for name, get, restore File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 773, in get_cwd return os.getcwd() OSError: [Errno 2] No such file or directory test_pty test test_pty crashed -- : [Errno 2] No such file or directory Re-running test 'test_pty' in verbose mode test test_pty crashed -- : [Errno 2] No such file or directory Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 861, in runtest_inner with saved_test_environment(test, verbose, quiet) as environment: File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 814, in __enter__ in self.resource_info()) File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 813, in self.saved_values = dict((name, get()) for name, get, restore File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 773, in get_cwd return os.getcwd() OSError: [Errno 2] No such file or directory test_pwd test test_pwd crashed -- : [Errno 2] No such file or directory Re-running test 'test_pwd' in verbose mode test test_pwd crashed -- : [Errno 2] No such file or directory Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 861, in runtest_inner with saved_test_environment(test, verbose, quiet) as environment: File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 814, in __enter__ in self.resource_info()) File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 813, in self.saved_values = dict((name, get()) for name, get, restore File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 773, in get_cwd return os.getcwd() OSError: [Errno 2] No such file or directory test_py3kwarn test test_py3kwarn crashed -- : [Errno 2] No such file or directory Re-running test 'test_py3kwarn' in verbose mode test test_py3kwarn crashed -- : [Errno 2] No such file or directory Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 861, in runtest_inner with saved_test_environment(test, verbose, quiet) as environment: File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 814, in __enter__ in self.resource_info()) File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 813, in self.saved_values = dict((name, get()) for name, get, restore File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 773, in get_cwd return os.getcwd() OSError: [Errno 2] No such file or directory test_pyclbr test test_pyclbr crashed -- : [Errno 2] No such file or directory Re-running test 'test_pyclbr' in verbose mode test test_pyclbr crashed -- : [Errno 2] No such file or directory Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 861, in runtest_inner with saved_test_environment(test, verbose, quiet) as environment: File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 814, in __enter__ in self.resource_info()) File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 813, in self.saved_values = dict((name, get()) for name, get, restore File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 773, in get_cwd return os.getcwd() OSError: [Errno 2] No such file or directory test_pydoc test test_pydoc crashed -- : [Errno 2] No such file or directory Re-running test 'test_pydoc' in verbose mode test test_pydoc crashed -- : [Errno 2] No such file or directory Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 861, in runtest_inner with saved_test_environment(test, verbose, quiet) as environment: File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 814, in __enter__ in self.resource_info()) File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 813, in self.saved_values = dict((name, get()) for name, get, restore File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 773, in get_cwd return os.getcwd() OSError: [Errno 2] No such file or directory test_pyexpat test test_pyexpat crashed -- : [Errno 2] No such file or directory Re-running test 'test_pyexpat' in verbose mode test test_pyexpat crashed -- : [Errno 2] No such file or directory Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 861, in runtest_inner with saved_test_environment(test, verbose, quiet) as environment: File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 814, in __enter__ in self.resource_info()) File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 813, in self.saved_values = dict((name, get()) for name, get, restore File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 773, in get_cwd return os.getcwd() OSError: [Errno 2] No such file or directory test_queue test test_queue crashed -- : [Errno 2] No such file or directory Re-running test 'test_queue' in verbose mode test test_queue crashed -- : [Errno 2] No such file or directory Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 861, in runtest_inner with saved_test_environment(test, verbose, quiet) as environment: File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 814, in __enter__ in self.resource_info()) File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 813, in self.saved_values = dict((name, get()) for name, get, restore File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 773, in get_cwd return os.getcwd() OSError: [Errno 2] No such file or directory test_quopri test test_quopri crashed -- : [Errno 2] No such file or directory Re-running test 'test_quopri' in verbose mode test test_quopri crashed -- : [Errno 2] No such file or directory Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 861, in runtest_inner with saved_test_environment(test, verbose, quiet) as environment: File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 814, in __enter__ in self.resource_info()) File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 813, in self.saved_values = dict((name, get()) for name, get, restore File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 773, in get_cwd return os.getcwd() OSError: [Errno 2] No such file or directory test_random test test_random crashed -- : [Errno 2] No such file or directory Re-running test 'test_random' in verbose mode test test_random crashed -- : [Errno 2] No such file or directory Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 861, in runtest_inner with saved_test_environment(test, verbose, quiet) as environment: File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 814, in __enter__ in self.resource_info()) File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 813, in self.saved_values = dict((name, get()) for name, get, restore File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 773, in get_cwd return os.getcwd() OSError: [Errno 2] No such file or directory test_re test test_re crashed -- : [Errno 2] No such file or directory Re-running test 'test_re' in verbose mode test test_re crashed -- : [Errno 2] No such file or directory Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 861, in runtest_inner with saved_test_environment(test, verbose, quiet) as environment: File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 814, in __enter__ in self.resource_info()) File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 813, in self.saved_values = dict((name, get()) for name, get, restore File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 773, in get_cwd return os.getcwd() OSError: [Errno 2] No such file or directory test_readline test test_readline crashed -- : [Errno 2] No such file or directory Re-running test 'test_readline' in verbose mode test test_readline crashed -- : [Errno 2] No such file or directory Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 861, in runtest_inner with saved_test_environment(test, verbose, quiet) as environment: File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 814, in __enter__ in self.resource_info()) File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 813, in self.saved_values = dict((name, get()) for name, get, restore File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 773, in get_cwd return os.getcwd() OSError: [Errno 2] No such file or directory test_repr test test_repr crashed -- : [Errno 2] No such file or directory Re-running test 'test_repr' in verbose mode test test_repr crashed -- : [Errno 2] No such file or directory Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 861, in runtest_inner with saved_test_environment(test, verbose, quiet) as environment: File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 814, in __enter__ in self.resource_info()) File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 813, in self.saved_values = dict((name, get()) for name, get, restore File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 773, in get_cwd return os.getcwd() OSError: [Errno 2] No such file or directory test_resource test test_resource crashed -- : [Errno 2] No such file or directory Re-running test 'test_resource' in verbose mode test test_resource crashed -- : [Errno 2] No such file or directory Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 861, in runtest_inner with saved_test_environment(test, verbose, quiet) as environment: File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 814, in __enter__ in self.resource_info()) File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 813, in self.saved_values = dict((name, get()) for name, get, restore File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 773, in get_cwd return os.getcwd() OSError: [Errno 2] No such file or directory test_rfc822 test test_rfc822 crashed -- : [Errno 2] No such file or directory Re-running test 'test_rfc822' in verbose mode test test_rfc822 crashed -- : [Errno 2] No such file or directory Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 861, in runtest_inner with saved_test_environment(test, verbose, quiet) as environment: File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 814, in __enter__ in self.resource_info()) File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 813, in self.saved_values = dict((name, get()) for name, get, restore File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 773, in get_cwd return os.getcwd() OSError: [Errno 2] No such file or directory test_richcmp test test_richcmp crashed -- : [Errno 2] No such file or directory Re-running test 'test_richcmp' in verbose mode test test_richcmp crashed -- : [Errno 2] No such file or directory Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 861, in runtest_inner with saved_test_environment(test, verbose, quiet) as environment: File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 814, in __enter__ in self.resource_info()) File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 813, in self.saved_values = dict((name, get()) for name, get, restore File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 773, in get_cwd return os.getcwd() OSError: [Errno 2] No such file or directory test_robotparser test test_robotparser crashed -- : [Errno 2] No such file or directory Re-running test 'test_robotparser' in verbose mode test test_robotparser crashed -- : [Errno 2] No such file or directory Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 861, in runtest_inner with saved_test_environment(test, verbose, quiet) as environment: File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 814, in __enter__ in self.resource_info()) File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 813, in self.saved_values = dict((name, get()) for name, get, restore File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 773, in get_cwd return os.getcwd() OSError: [Errno 2] No such file or directory test_runpy test test_runpy crashed -- : [Errno 2] No such file or directory Re-running test 'test_runpy' in verbose mode test test_runpy crashed -- : [Errno 2] No such file or directory Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 861, in runtest_inner with saved_test_environment(test, verbose, quiet) as environment: File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 814, in __enter__ in self.resource_info()) File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 813, in self.saved_values = dict((name, get()) for name, get, restore File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 773, in get_cwd return os.getcwd() OSError: [Errno 2] No such file or directory test_sax test test_sax crashed -- : [Errno 2] No such file or directory Re-running test 'test_sax' in verbose mode test test_sax crashed -- : [Errno 2] No such file or directory Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 861, in runtest_inner with saved_test_environment(test, verbose, quiet) as environment: File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 814, in __enter__ in self.resource_info()) File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 813, in self.saved_values = dict((name, get()) for name, get, restore File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 773, in get_cwd return os.getcwd() OSError: [Errno 2] No such file or directory test_scope test test_scope crashed -- : [Errno 2] No such file or directory Re-running test 'test_scope' in verbose mode test test_scope crashed -- : [Errno 2] No such file or directory Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 861, in runtest_inner with saved_test_environment(test, verbose, quiet) as environment: File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 814, in __enter__ in self.resource_info()) File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 813, in self.saved_values = dict((name, get()) for name, get, restore File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 773, in get_cwd return os.getcwd() OSError: [Errno 2] No such file or directory test_scriptpackages test test_scriptpackages crashed -- : [Errno 2] No such file or directory Re-running test 'test_scriptpackages' in verbose mode test test_scriptpackages crashed -- : [Errno 2] No such file or directory Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 861, in runtest_inner with saved_test_environment(test, verbose, quiet) as environment: File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 814, in __enter__ in self.resource_info()) File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 813, in self.saved_values = dict((name, get()) for name, get, restore File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 773, in get_cwd return os.getcwd() OSError: [Errno 2] No such file or directory test_select test test_select crashed -- : [Errno 2] No such file or directory Re-running test 'test_select' in verbose mode test test_select crashed -- : [Errno 2] No such file or directory Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 861, in runtest_inner with saved_test_environment(test, verbose, quiet) as environment: File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 814, in __enter__ in self.resource_info()) File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 813, in self.saved_values = dict((name, get()) for name, get, restore File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 773, in get_cwd return os.getcwd() OSError: [Errno 2] No such file or directory test_set test test_set crashed -- : [Errno 2] No such file or directory Re-running test 'test_set' in verbose mode test test_set crashed -- : [Errno 2] No such file or directory Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 861, in runtest_inner with saved_test_environment(test, verbose, quiet) as environment: File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 814, in __enter__ in self.resource_info()) File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 813, in self.saved_values = dict((name, get()) for name, get, restore File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 773, in get_cwd return os.getcwd() OSError: [Errno 2] No such file or directory test_setcomps test test_setcomps crashed -- : [Errno 2] No such file or directory Re-running test 'test_setcomps' in verbose mode test test_setcomps crashed -- : [Errno 2] No such file or directory Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 861, in runtest_inner with saved_test_environment(test, verbose, quiet) as environment: File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 814, in __enter__ in self.resource_info()) File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 813, in self.saved_values = dict((name, get()) for name, get, restore File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 773, in get_cwd return os.getcwd() OSError: [Errno 2] No such file or directory test_sets test test_sets crashed -- : [Errno 2] No such file or directory Re-running test 'test_sets' in verbose mode test test_sets crashed -- : [Errno 2] No such file or directory Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 861, in runtest_inner with saved_test_environment(test, verbose, quiet) as environment: File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 814, in __enter__ in self.resource_info()) File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 813, in self.saved_values = dict((name, get()) for name, get, restore File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 773, in get_cwd return os.getcwd() OSError: [Errno 2] No such file or directory test_sgmllib test test_sgmllib crashed -- : [Errno 2] No such file or directory Re-running test 'test_sgmllib' in verbose mode test test_sgmllib crashed -- : [Errno 2] No such file or directory Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 861, in runtest_inner with saved_test_environment(test, verbose, quiet) as environment: File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 814, in __enter__ in self.resource_info()) File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 813, in self.saved_values = dict((name, get()) for name, get, restore File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 773, in get_cwd return os.getcwd() OSError: [Errno 2] No such file or directory test_sha test test_sha crashed -- : [Errno 2] No such file or directory Re-running test 'test_sha' in verbose mode test test_sha crashed -- : [Errno 2] No such file or directory Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 861, in runtest_inner with saved_test_environment(test, verbose, quiet) as environment: File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 814, in __enter__ in self.resource_info()) File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 813, in self.saved_values = dict((name, get()) for name, get, restore File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 773, in get_cwd return os.getcwd() OSError: [Errno 2] No such file or directory test_shelve test test_shelve crashed -- : [Errno 2] No such file or directory Re-running test 'test_shelve' in verbose mode test test_shelve crashed -- : [Errno 2] No such file or directory Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 861, in runtest_inner with saved_test_environment(test, verbose, quiet) as environment: File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 814, in __enter__ in self.resource_info()) File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 813, in self.saved_values = dict((name, get()) for name, get, restore File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 773, in get_cwd return os.getcwd() OSError: [Errno 2] No such file or directory test_shlex test test_shlex crashed -- : [Errno 2] No such file or directory Re-running test 'test_shlex' in verbose mode test test_shlex crashed -- : [Errno 2] No such file or directory Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 861, in runtest_inner with saved_test_environment(test, verbose, quiet) as environment: File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 814, in __enter__ in self.resource_info()) File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 813, in self.saved_values = dict((name, get()) for name, get, restore File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 773, in get_cwd return os.getcwd() OSError: [Errno 2] No such file or directory test_shutil test test_shutil crashed -- : [Errno 2] No such file or directory Re-running test 'test_shutil' in verbose mode test test_shutil crashed -- : [Errno 2] No such file or directory Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 861, in runtest_inner with saved_test_environment(test, verbose, quiet) as environment: File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 814, in __enter__ in self.resource_info()) File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 813, in self.saved_values = dict((name, get()) for name, get, restore File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 773, in get_cwd return os.getcwd() OSError: [Errno 2] No such file or directory test_signal test test_signal crashed -- : [Errno 2] No such file or directory Re-running test 'test_signal' in verbose mode test test_signal crashed -- : [Errno 2] No such file or directory Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 861, in runtest_inner with saved_test_environment(test, verbose, quiet) as environment: File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 814, in __enter__ in self.resource_info()) File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 813, in self.saved_values = dict((name, get()) for name, get, restore File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 773, in get_cwd return os.getcwd() OSError: [Errno 2] No such file or directory test_site test test_site crashed -- : [Errno 2] No such file or directory Re-running test 'test_site' in verbose mode test test_site crashed -- : [Errno 2] No such file or directory Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 861, in runtest_inner with saved_test_environment(test, verbose, quiet) as environment: File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 814, in __enter__ in self.resource_info()) File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 813, in self.saved_values = dict((name, get()) for name, get, restore File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 773, in get_cwd return os.getcwd() OSError: [Errno 2] No such file or directory test_slice test test_slice crashed -- : [Errno 2] No such file or directory Re-running test 'test_slice' in verbose mode test test_slice crashed -- : [Errno 2] No such file or directory Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 861, in runtest_inner with saved_test_environment(test, verbose, quiet) as environment: File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 814, in __enter__ in self.resource_info()) File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 813, in self.saved_values = dict((name, get()) for name, get, restore File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 773, in get_cwd return os.getcwd() OSError: [Errno 2] No such file or directory test_smtplib test test_smtplib crashed -- : [Errno 2] No such file or directory Re-running test 'test_smtplib' in verbose mode test test_smtplib crashed -- : [Errno 2] No such file or directory Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 861, in runtest_inner with saved_test_environment(test, verbose, quiet) as environment: File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 814, in __enter__ in self.resource_info()) File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 813, in self.saved_values = dict((name, get()) for name, get, restore File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 773, in get_cwd return os.getcwd() OSError: [Errno 2] No such file or directory test_smtpnet test test_smtpnet crashed -- : [Errno 2] No such file or directory Re-running test 'test_smtpnet' in verbose mode test test_smtpnet crashed -- : [Errno 2] No such file or directory Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 861, in runtest_inner with saved_test_environment(test, verbose, quiet) as environment: File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 814, in __enter__ in self.resource_info()) File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 813, in self.saved_values = dict((name, get()) for name, get, restore File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 773, in get_cwd return os.getcwd() OSError: [Errno 2] No such file or directory test_socket test test_socket crashed -- : [Errno 2] No such file or directory Re-running test 'test_socket' in verbose mode test test_socket crashed -- : [Errno 2] No such file or directory Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 861, in runtest_inner with saved_test_environment(test, verbose, quiet) as environment: File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 814, in __enter__ in self.resource_info()) File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 813, in self.saved_values = dict((name, get()) for name, get, restore File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 773, in get_cwd return os.getcwd() OSError: [Errno 2] No such file or directory test_socketserver test test_socketserver crashed -- : [Errno 2] No such file or directory Re-running test 'test_socketserver' in verbose mode test test_socketserver crashed -- : [Errno 2] No such file or directory Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 861, in runtest_inner with saved_test_environment(test, verbose, quiet) as environment: File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 814, in __enter__ in self.resource_info()) File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 813, in self.saved_values = dict((name, get()) for name, get, restore File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 773, in get_cwd return os.getcwd() OSError: [Errno 2] No such file or directory test_softspace test test_softspace crashed -- : [Errno 2] No such file or directory Re-running test 'test_softspace' in verbose mode test test_softspace crashed -- : [Errno 2] No such file or directory Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 861, in runtest_inner with saved_test_environment(test, verbose, quiet) as environment: File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 814, in __enter__ in self.resource_info()) File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 813, in self.saved_values = dict((name, get()) for name, get, restore File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 773, in get_cwd return os.getcwd() OSError: [Errno 2] No such file or directory test_sort test test_sort crashed -- : [Errno 2] No such file or directory Re-running test 'test_sort' in verbose mode test test_sort crashed -- : [Errno 2] No such file or directory Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 861, in runtest_inner with saved_test_environment(test, verbose, quiet) as environment: File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 814, in __enter__ in self.resource_info()) File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 813, in self.saved_values = dict((name, get()) for name, get, restore File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 773, in get_cwd return os.getcwd() OSError: [Errno 2] No such file or directory test_sqlite test test_sqlite crashed -- : [Errno 2] No such file or directory Re-running test 'test_sqlite' in verbose mode test test_sqlite crashed -- : [Errno 2] No such file or directory Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 861, in runtest_inner with saved_test_environment(test, verbose, quiet) as environment: File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 814, in __enter__ in self.resource_info()) File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 813, in self.saved_values = dict((name, get()) for name, get, restore File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 773, in get_cwd return os.getcwd() OSError: [Errno 2] No such file or directory test_ssl test test_ssl crashed -- : [Errno 2] No such file or directory Re-running test 'test_ssl' in verbose mode test test_ssl crashed -- : [Errno 2] No such file or directory Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 861, in runtest_inner with saved_test_environment(test, verbose, quiet) as environment: File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 814, in __enter__ in self.resource_info()) File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 813, in self.saved_values = dict((name, get()) for name, get, restore File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 773, in get_cwd return os.getcwd() OSError: [Errno 2] No such file or directory test_startfile test test_startfile crashed -- : [Errno 2] No such file or directory Re-running test 'test_startfile' in verbose mode test test_startfile crashed -- : [Errno 2] No such file or directory Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 861, in runtest_inner with saved_test_environment(test, verbose, quiet) as environment: File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 814, in __enter__ in self.resource_info()) File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 813, in self.saved_values = dict((name, get()) for name, get, restore File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 773, in get_cwd return os.getcwd() OSError: [Errno 2] No such file or directory test_str test test_str crashed -- : [Errno 2] No such file or directory Re-running test 'test_str' in verbose mode test test_str crashed -- : [Errno 2] No such file or directory Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 861, in runtest_inner with saved_test_environment(test, verbose, quiet) as environment: File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 814, in __enter__ in self.resource_info()) File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 813, in self.saved_values = dict((name, get()) for name, get, restore File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 773, in get_cwd return os.getcwd() OSError: [Errno 2] No such file or directory test_strftime test test_strftime crashed -- : [Errno 2] No such file or directory Re-running test 'test_strftime' in verbose mode test test_strftime crashed -- : [Errno 2] No such file or directory Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 861, in runtest_inner with saved_test_environment(test, verbose, quiet) as environment: File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 814, in __enter__ in self.resource_info()) File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 813, in self.saved_values = dict((name, get()) for name, get, restore File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 773, in get_cwd return os.getcwd() OSError: [Errno 2] No such file or directory test_string test test_string crashed -- : [Errno 2] No such file or directory Re-running test 'test_string' in verbose mode test test_string crashed -- : [Errno 2] No such file or directory Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 861, in runtest_inner with saved_test_environment(test, verbose, quiet) as environment: File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 814, in __enter__ in self.resource_info()) File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 813, in self.saved_values = dict((name, get()) for name, get, restore File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 773, in get_cwd return os.getcwd() OSError: [Errno 2] No such file or directory test_stringprep test test_stringprep crashed -- : [Errno 2] No such file or directory Re-running test 'test_stringprep' in verbose mode test test_stringprep crashed -- : [Errno 2] No such file or directory Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 861, in runtest_inner with saved_test_environment(test, verbose, quiet) as environment: File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 814, in __enter__ in self.resource_info()) File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 813, in self.saved_values = dict((name, get()) for name, get, restore File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 773, in get_cwd return os.getcwd() OSError: [Errno 2] No such file or directory test_strop test test_strop crashed -- : [Errno 2] No such file or directory Re-running test 'test_strop' in verbose mode test test_strop crashed -- : [Errno 2] No such file or directory Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 861, in runtest_inner with saved_test_environment(test, verbose, quiet) as environment: File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 814, in __enter__ in self.resource_info()) File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 813, in self.saved_values = dict((name, get()) for name, get, restore File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 773, in get_cwd return os.getcwd() OSError: [Errno 2] No such file or directory test_strptime test test_strptime crashed -- : [Errno 2] No such file or directory Re-running test 'test_strptime' in verbose mode test test_strptime crashed -- : [Errno 2] No such file or directory Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 861, in runtest_inner with saved_test_environment(test, verbose, quiet) as environment: File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 814, in __enter__ in self.resource_info()) File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 813, in self.saved_values = dict((name, get()) for name, get, restore File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 773, in get_cwd return os.getcwd() OSError: [Errno 2] No such file or directory test_strtod test test_strtod crashed -- : [Errno 2] No such file or directory Re-running test 'test_strtod' in verbose mode test test_strtod crashed -- : [Errno 2] No such file or directory Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 861, in runtest_inner with saved_test_environment(test, verbose, quiet) as environment: File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 814, in __enter__ in self.resource_info()) File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 813, in self.saved_values = dict((name, get()) for name, get, restore File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 773, in get_cwd return os.getcwd() OSError: [Errno 2] No such file or directory test_struct test test_struct crashed -- : [Errno 2] No such file or directory Re-running test 'test_struct' in verbose mode test test_struct crashed -- : [Errno 2] No such file or directory Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 861, in runtest_inner with saved_test_environment(test, verbose, quiet) as environment: File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 814, in __enter__ in self.resource_info()) File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 813, in self.saved_values = dict((name, get()) for name, get, restore File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 773, in get_cwd return os.getcwd() OSError: [Errno 2] No such file or directory test_structmembers test test_structmembers crashed -- : [Errno 2] No such file or directory Re-running test 'test_structmembers' in verbose mode test test_structmembers crashed -- : [Errno 2] No such file or directory Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 861, in runtest_inner with saved_test_environment(test, verbose, quiet) as environment: File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 814, in __enter__ in self.resource_info()) File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 813, in self.saved_values = dict((name, get()) for name, get, restore File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 773, in get_cwd return os.getcwd() OSError: [Errno 2] No such file or directory test_structseq test test_structseq crashed -- : [Errno 2] No such file or directory Re-running test 'test_structseq' in verbose mode test test_structseq crashed -- : [Errno 2] No such file or directory Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 861, in runtest_inner with saved_test_environment(test, verbose, quiet) as environment: File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 814, in __enter__ in self.resource_info()) File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 813, in self.saved_values = dict((name, get()) for name, get, restore File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 773, in get_cwd return os.getcwd() OSError: [Errno 2] No such file or directory test_subprocess test test_subprocess crashed -- : [Errno 2] No such file or directory Re-running test 'test_subprocess' in verbose mode test test_subprocess crashed -- : [Errno 2] No such file or directory Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 861, in runtest_inner with saved_test_environment(test, verbose, quiet) as environment: File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 814, in __enter__ in self.resource_info()) File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 813, in self.saved_values = dict((name, get()) for name, get, restore File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 773, in get_cwd return os.getcwd() OSError: [Errno 2] No such file or directory test_sunaudiodev test test_sunaudiodev crashed -- : [Errno 2] No such file or directory Re-running test 'test_sunaudiodev' in verbose mode test test_sunaudiodev crashed -- : [Errno 2] No such file or directory Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 861, in runtest_inner with saved_test_environment(test, verbose, quiet) as environment: File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 814, in __enter__ in self.resource_info()) File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 813, in self.saved_values = dict((name, get()) for name, get, restore File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 773, in get_cwd return os.getcwd() OSError: [Errno 2] No such file or directory test_sundry test test_sundry crashed -- : [Errno 2] No such file or directory Re-running test 'test_sundry' in verbose mode test test_sundry crashed -- : [Errno 2] No such file or directory Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 861, in runtest_inner with saved_test_environment(test, verbose, quiet) as environment: File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 814, in __enter__ in self.resource_info()) File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 813, in self.saved_values = dict((name, get()) for name, get, restore File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 773, in get_cwd return os.getcwd() OSError: [Errno 2] No such file or directory test_symtable test test_symtable crashed -- : [Errno 2] No such file or directory Re-running test 'test_symtable' in verbose mode test test_symtable crashed -- : [Errno 2] No such file or directory Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 861, in runtest_inner with saved_test_environment(test, verbose, quiet) as environment: File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 814, in __enter__ in self.resource_info()) File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 813, in self.saved_values = dict((name, get()) for name, get, restore File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 773, in get_cwd return os.getcwd() OSError: [Errno 2] No such file or directory test_syntax test test_syntax crashed -- : [Errno 2] No such file or directory Re-running test 'test_syntax' in verbose mode test test_syntax crashed -- : [Errno 2] No such file or directory Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 861, in runtest_inner with saved_test_environment(test, verbose, quiet) as environment: File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 814, in __enter__ in self.resource_info()) File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 813, in self.saved_values = dict((name, get()) for name, get, restore File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 773, in get_cwd return os.getcwd() OSError: [Errno 2] No such file or directory test_sys test test_sys crashed -- : [Errno 2] No such file or directory Re-running test 'test_sys' in verbose mode test test_sys crashed -- : [Errno 2] No such file or directory Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 861, in runtest_inner with saved_test_environment(test, verbose, quiet) as environment: File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 814, in __enter__ in self.resource_info()) File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 813, in self.saved_values = dict((name, get()) for name, get, restore File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 773, in get_cwd return os.getcwd() OSError: [Errno 2] No such file or directory test_sysconfig test test_sysconfig crashed -- : [Errno 2] No such file or directory Re-running test 'test_sysconfig' in verbose mode test test_sysconfig crashed -- : [Errno 2] No such file or directory Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 861, in runtest_inner with saved_test_environment(test, verbose, quiet) as environment: File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 814, in __enter__ in self.resource_info()) File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 813, in self.saved_values = dict((name, get()) for name, get, restore File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 773, in get_cwd return os.getcwd() OSError: [Errno 2] No such file or directory test_tarfile test test_tarfile crashed -- : [Errno 2] No such file or directory Re-running test 'test_tarfile' in verbose mode test test_tarfile crashed -- : [Errno 2] No such file or directory Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 861, in runtest_inner with saved_test_environment(test, verbose, quiet) as environment: File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 814, in __enter__ in self.resource_info()) File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 813, in self.saved_values = dict((name, get()) for name, get, restore File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 773, in get_cwd return os.getcwd() OSError: [Errno 2] No such file or directory test_tcl test test_tcl crashed -- : [Errno 2] No such file or directory Re-running test 'test_tcl' in verbose mode test test_tcl crashed -- : [Errno 2] No such file or directory Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 861, in runtest_inner with saved_test_environment(test, verbose, quiet) as environment: File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 814, in __enter__ in self.resource_info()) File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 813, in self.saved_values = dict((name, get()) for name, get, restore File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 773, in get_cwd return os.getcwd() OSError: [Errno 2] No such file or directory test_telnetlib test test_telnetlib crashed -- : [Errno 2] No such file or directory Re-running test 'test_telnetlib' in verbose mode test test_telnetlib crashed -- : [Errno 2] No such file or directory Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 861, in runtest_inner with saved_test_environment(test, verbose, quiet) as environment: File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 814, in __enter__ in self.resource_info()) File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 813, in self.saved_values = dict((name, get()) for name, get, restore File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 773, in get_cwd return os.getcwd() OSError: [Errno 2] No such file or directory test_tempfile test test_tempfile crashed -- : [Errno 2] No such file or directory Re-running test 'test_tempfile' in verbose mode test test_tempfile crashed -- : [Errno 2] No such file or directory Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 861, in runtest_inner with saved_test_environment(test, verbose, quiet) as environment: File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 814, in __enter__ in self.resource_info()) File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 813, in self.saved_values = dict((name, get()) for name, get, restore File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 773, in get_cwd return os.getcwd() OSError: [Errno 2] No such file or directory test_textwrap test test_textwrap crashed -- : [Errno 2] No such file or directory Re-running test 'test_textwrap' in verbose mode test test_textwrap crashed -- : [Errno 2] No such file or directory Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 861, in runtest_inner with saved_test_environment(test, verbose, quiet) as environment: File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 814, in __enter__ in self.resource_info()) File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 813, in self.saved_values = dict((name, get()) for name, get, restore File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 773, in get_cwd return os.getcwd() OSError: [Errno 2] No such file or directory test_thread test test_thread crashed -- : [Errno 2] No such file or directory Re-running test 'test_thread' in verbose mode test test_thread crashed -- : [Errno 2] No such file or directory Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 861, in runtest_inner with saved_test_environment(test, verbose, quiet) as environment: File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 814, in __enter__ in self.resource_info()) File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 813, in self.saved_values = dict((name, get()) for name, get, restore File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 773, in get_cwd return os.getcwd() OSError: [Errno 2] No such file or directory test_threaded_import test test_threaded_import crashed -- : [Errno 2] No such file or directory Re-running test 'test_threaded_import' in verbose mode test test_threaded_import crashed -- : [Errno 2] No such file or directory Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 861, in runtest_inner with saved_test_environment(test, verbose, quiet) as environment: File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 814, in __enter__ in self.resource_info()) File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 813, in self.saved_values = dict((name, get()) for name, get, restore File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 773, in get_cwd return os.getcwd() OSError: [Errno 2] No such file or directory test_threadedtempfile test test_threadedtempfile crashed -- : [Errno 2] No such file or directory Re-running test 'test_threadedtempfile' in verbose mode test test_threadedtempfile crashed -- : [Errno 2] No such file or directory Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 861, in runtest_inner with saved_test_environment(test, verbose, quiet) as environment: File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 814, in __enter__ in self.resource_info()) File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 813, in self.saved_values = dict((name, get()) for name, get, restore File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 773, in get_cwd return os.getcwd() OSError: [Errno 2] No such file or directory test_threading test test_threading crashed -- : [Errno 2] No such file or directory Re-running test 'test_threading' in verbose mode test test_threading crashed -- : [Errno 2] No such file or directory Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 861, in runtest_inner with saved_test_environment(test, verbose, quiet) as environment: File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 814, in __enter__ in self.resource_info()) File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 813, in self.saved_values = dict((name, get()) for name, get, restore File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 773, in get_cwd return os.getcwd() OSError: [Errno 2] No such file or directory test_threading_local test test_threading_local crashed -- : [Errno 2] No such file or directory Re-running test 'test_threading_local' in verbose mode test test_threading_local crashed -- : [Errno 2] No such file or directory Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 861, in runtest_inner with saved_test_environment(test, verbose, quiet) as environment: File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 814, in __enter__ in self.resource_info()) File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 813, in self.saved_values = dict((name, get()) for name, get, restore File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 773, in get_cwd return os.getcwd() OSError: [Errno 2] No such file or directory test_threadsignals test test_threadsignals crashed -- : [Errno 2] No such file or directory Re-running test 'test_threadsignals' in verbose mode test test_threadsignals crashed -- : [Errno 2] No such file or directory Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 861, in runtest_inner with saved_test_environment(test, verbose, quiet) as environment: File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 814, in __enter__ in self.resource_info()) File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 813, in self.saved_values = dict((name, get()) for name, get, restore File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 773, in get_cwd return os.getcwd() OSError: [Errno 2] No such file or directory test_time test test_time crashed -- : [Errno 2] No such file or directory Re-running test 'test_time' in verbose mode test test_time crashed -- : [Errno 2] No such file or directory Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 861, in runtest_inner with saved_test_environment(test, verbose, quiet) as environment: File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 814, in __enter__ in self.resource_info()) File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 813, in self.saved_values = dict((name, get()) for name, get, restore File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 773, in get_cwd return os.getcwd() OSError: [Errno 2] No such file or directory test_timeout test test_timeout crashed -- : [Errno 2] No such file or directory Re-running test 'test_timeout' in verbose mode test test_timeout crashed -- : [Errno 2] No such file or directory Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 861, in runtest_inner with saved_test_environment(test, verbose, quiet) as environment: File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 814, in __enter__ in self.resource_info()) File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 813, in self.saved_values = dict((name, get()) for name, get, restore File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 773, in get_cwd return os.getcwd() OSError: [Errno 2] No such file or directory test_tk test test_tk crashed -- : [Errno 2] No such file or directory Re-running test 'test_tk' in verbose mode test test_tk crashed -- : [Errno 2] No such file or directory Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 861, in runtest_inner with saved_test_environment(test, verbose, quiet) as environment: File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 814, in __enter__ in self.resource_info()) File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 813, in self.saved_values = dict((name, get()) for name, get, restore File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 773, in get_cwd return os.getcwd() OSError: [Errno 2] No such file or directory test_tokenize test test_tokenize crashed -- : [Errno 2] No such file or directory Re-running test 'test_tokenize' in verbose mode test test_tokenize crashed -- : [Errno 2] No such file or directory Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 861, in runtest_inner with saved_test_environment(test, verbose, quiet) as environment: File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 814, in __enter__ in self.resource_info()) File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 813, in self.saved_values = dict((name, get()) for name, get, restore File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 773, in get_cwd return os.getcwd() OSError: [Errno 2] No such file or directory test_trace test test_trace crashed -- : [Errno 2] No such file or directory Re-running test 'test_trace' in verbose mode test test_trace crashed -- : [Errno 2] No such file or directory Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 861, in runtest_inner with saved_test_environment(test, verbose, quiet) as environment: File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 814, in __enter__ in self.resource_info()) File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 813, in self.saved_values = dict((name, get()) for name, get, restore File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 773, in get_cwd return os.getcwd() OSError: [Errno 2] No such file or directory test_traceback test test_traceback crashed -- : [Errno 2] No such file or directory Re-running test 'test_traceback' in verbose mode test test_traceback crashed -- : [Errno 2] No such file or directory Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 861, in runtest_inner with saved_test_environment(test, verbose, quiet) as environment: File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 814, in __enter__ in self.resource_info()) File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 813, in self.saved_values = dict((name, get()) for name, get, restore File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 773, in get_cwd return os.getcwd() OSError: [Errno 2] No such file or directory test_transformer test test_transformer crashed -- : [Errno 2] No such file or directory Re-running test 'test_transformer' in verbose mode test test_transformer crashed -- : [Errno 2] No such file or directory Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 861, in runtest_inner with saved_test_environment(test, verbose, quiet) as environment: File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 814, in __enter__ in self.resource_info()) File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 813, in self.saved_values = dict((name, get()) for name, get, restore File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 773, in get_cwd return os.getcwd() OSError: [Errno 2] No such file or directory test_ttk_guionly test test_ttk_guionly crashed -- : [Errno 2] No such file or directory Re-running test 'test_ttk_guionly' in verbose mode test test_ttk_guionly crashed -- : [Errno 2] No such file or directory Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 861, in runtest_inner with saved_test_environment(test, verbose, quiet) as environment: File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 814, in __enter__ in self.resource_info()) File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 813, in self.saved_values = dict((name, get()) for name, get, restore File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 773, in get_cwd return os.getcwd() OSError: [Errno 2] No such file or directory test_ttk_textonly test test_ttk_textonly crashed -- : [Errno 2] No such file or directory Re-running test 'test_ttk_textonly' in verbose mode test test_ttk_textonly crashed -- : [Errno 2] No such file or directory Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 861, in runtest_inner with saved_test_environment(test, verbose, quiet) as environment: File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 814, in __enter__ in self.resource_info()) File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 813, in self.saved_values = dict((name, get()) for name, get, restore File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 773, in get_cwd return os.getcwd() OSError: [Errno 2] No such file or directory test_tuple test test_tuple crashed -- : [Errno 2] No such file or directory Re-running test 'test_tuple' in verbose mode test test_tuple crashed -- : [Errno 2] No such file or directory Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 861, in runtest_inner with saved_test_environment(test, verbose, quiet) as environment: File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 814, in __enter__ in self.resource_info()) File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 813, in self.saved_values = dict((name, get()) for name, get, restore File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 773, in get_cwd return os.getcwd() OSError: [Errno 2] No such file or directory test_typechecks test test_typechecks crashed -- : [Errno 2] No such file or directory Re-running test 'test_typechecks' in verbose mode test test_typechecks crashed -- : [Errno 2] No such file or directory Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 861, in runtest_inner with saved_test_environment(test, verbose, quiet) as environment: File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 814, in __enter__ in self.resource_info()) File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 813, in self.saved_values = dict((name, get()) for name, get, restore File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 773, in get_cwd return os.getcwd() OSError: [Errno 2] No such file or directory test_ucn test test_ucn crashed -- : [Errno 2] No such file or directory Re-running test 'test_ucn' in verbose mode test test_ucn crashed -- : [Errno 2] No such file or directory Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 861, in runtest_inner with saved_test_environment(test, verbose, quiet) as environment: File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 814, in __enter__ in self.resource_info()) File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 813, in self.saved_values = dict((name, get()) for name, get, restore File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 773, in get_cwd return os.getcwd() OSError: [Errno 2] No such file or directory test_unary test test_unary crashed -- : [Errno 2] No such file or directory Re-running test 'test_unary' in verbose mode test test_unary crashed -- : [Errno 2] No such file or directory Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 861, in runtest_inner with saved_test_environment(test, verbose, quiet) as environment: File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 814, in __enter__ in self.resource_info()) File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 813, in self.saved_values = dict((name, get()) for name, get, restore File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 773, in get_cwd return os.getcwd() OSError: [Errno 2] No such file or directory test_undocumented_details test test_undocumented_details crashed -- : [Errno 2] No such file or directory Re-running test 'test_undocumented_details' in verbose mode test test_undocumented_details crashed -- : [Errno 2] No such file or directory Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 861, in runtest_inner with saved_test_environment(test, verbose, quiet) as environment: File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 814, in __enter__ in self.resource_info()) File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 813, in self.saved_values = dict((name, get()) for name, get, restore File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 773, in get_cwd return os.getcwd() OSError: [Errno 2] No such file or directory test_unicode test test_unicode crashed -- : [Errno 2] No such file or directory Re-running test 'test_unicode' in verbose mode test test_unicode crashed -- : [Errno 2] No such file or directory Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 861, in runtest_inner with saved_test_environment(test, verbose, quiet) as environment: File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 814, in __enter__ in self.resource_info()) File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 813, in self.saved_values = dict((name, get()) for name, get, restore File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 773, in get_cwd return os.getcwd() OSError: [Errno 2] No such file or directory test_unicode_file test test_unicode_file crashed -- : [Errno 2] No such file or directory Re-running test 'test_unicode_file' in verbose mode test test_unicode_file crashed -- : [Errno 2] No such file or directory Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 861, in runtest_inner with saved_test_environment(test, verbose, quiet) as environment: File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 814, in __enter__ in self.resource_info()) File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 813, in self.saved_values = dict((name, get()) for name, get, restore File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 773, in get_cwd return os.getcwd() OSError: [Errno 2] No such file or directory test_unicodedata test test_unicodedata crashed -- : [Errno 2] No such file or directory Re-running test 'test_unicodedata' in verbose mode test test_unicodedata crashed -- : [Errno 2] No such file or directory Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 861, in runtest_inner with saved_test_environment(test, verbose, quiet) as environment: File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 814, in __enter__ in self.resource_info()) File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 813, in self.saved_values = dict((name, get()) for name, get, restore File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 773, in get_cwd return os.getcwd() OSError: [Errno 2] No such file or directory test_univnewlines test test_univnewlines crashed -- : [Errno 2] No such file or directory Re-running test 'test_univnewlines' in verbose mode test test_univnewlines crashed -- : [Errno 2] No such file or directory Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 861, in runtest_inner with saved_test_environment(test, verbose, quiet) as environment: File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 814, in __enter__ in self.resource_info()) File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 813, in self.saved_values = dict((name, get()) for name, get, restore File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 773, in get_cwd return os.getcwd() OSError: [Errno 2] No such file or directory test_univnewlines2k test test_univnewlines2k crashed -- : [Errno 2] No such file or directory Re-running test 'test_univnewlines2k' in verbose mode test test_univnewlines2k crashed -- : [Errno 2] No such file or directory Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 861, in runtest_inner with saved_test_environment(test, verbose, quiet) as environment: File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 814, in __enter__ in self.resource_info()) File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 813, in self.saved_values = dict((name, get()) for name, get, restore File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 773, in get_cwd return os.getcwd() OSError: [Errno 2] No such file or directory test_unpack test test_unpack crashed -- : [Errno 2] No such file or directory Re-running test 'test_unpack' in verbose mode test test_unpack crashed -- : [Errno 2] No such file or directory Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 861, in runtest_inner with saved_test_environment(test, verbose, quiet) as environment: File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 814, in __enter__ in self.resource_info()) File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 813, in self.saved_values = dict((name, get()) for name, get, restore File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 773, in get_cwd return os.getcwd() OSError: [Errno 2] No such file or directory test_urllib test test_urllib crashed -- : [Errno 2] No such file or directory Re-running test 'test_urllib' in verbose mode test test_urllib crashed -- : [Errno 2] No such file or directory Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 861, in runtest_inner with saved_test_environment(test, verbose, quiet) as environment: File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 814, in __enter__ in self.resource_info()) File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 813, in self.saved_values = dict((name, get()) for name, get, restore File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 773, in get_cwd return os.getcwd() OSError: [Errno 2] No such file or directory test_urllib2 test test_urllib2 crashed -- : [Errno 2] No such file or directory Re-running test 'test_urllib2' in verbose mode test test_urllib2 crashed -- : [Errno 2] No such file or directory Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 861, in runtest_inner with saved_test_environment(test, verbose, quiet) as environment: File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 814, in __enter__ in self.resource_info()) File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 813, in self.saved_values = dict((name, get()) for name, get, restore File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 773, in get_cwd return os.getcwd() OSError: [Errno 2] No such file or directory test_urllib2_localnet test test_urllib2_localnet crashed -- : [Errno 2] No such file or directory Re-running test 'test_urllib2_localnet' in verbose mode test test_urllib2_localnet crashed -- : [Errno 2] No such file or directory Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 861, in runtest_inner with saved_test_environment(test, verbose, quiet) as environment: File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 814, in __enter__ in self.resource_info()) File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 813, in self.saved_values = dict((name, get()) for name, get, restore File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 773, in get_cwd return os.getcwd() OSError: [Errno 2] No such file or directory test_urllib2net test test_urllib2net crashed -- : [Errno 2] No such file or directory Re-running test 'test_urllib2net' in verbose mode test test_urllib2net crashed -- : [Errno 2] No such file or directory Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 861, in runtest_inner with saved_test_environment(test, verbose, quiet) as environment: File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 814, in __enter__ in self.resource_info()) File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 813, in self.saved_values = dict((name, get()) for name, get, restore File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 773, in get_cwd return os.getcwd() OSError: [Errno 2] No such file or directory test_urllibnet test test_urllibnet crashed -- : [Errno 2] No such file or directory Re-running test 'test_urllibnet' in verbose mode test test_urllibnet crashed -- : [Errno 2] No such file or directory Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 861, in runtest_inner with saved_test_environment(test, verbose, quiet) as environment: File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 814, in __enter__ in self.resource_info()) File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 813, in self.saved_values = dict((name, get()) for name, get, restore File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 773, in get_cwd return os.getcwd() OSError: [Errno 2] No such file or directory test_urlparse test test_urlparse crashed -- : [Errno 2] No such file or directory Re-running test 'test_urlparse' in verbose mode test test_urlparse crashed -- : [Errno 2] No such file or directory Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 861, in runtest_inner with saved_test_environment(test, verbose, quiet) as environment: File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 814, in __enter__ in self.resource_info()) File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 813, in self.saved_values = dict((name, get()) for name, get, restore File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 773, in get_cwd return os.getcwd() OSError: [Errno 2] No such file or directory test_userdict test test_userdict crashed -- : [Errno 2] No such file or directory Re-running test 'test_userdict' in verbose mode test test_userdict crashed -- : [Errno 2] No such file or directory Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 861, in runtest_inner with saved_test_environment(test, verbose, quiet) as environment: File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 814, in __enter__ in self.resource_info()) File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 813, in self.saved_values = dict((name, get()) for name, get, restore File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 773, in get_cwd return os.getcwd() OSError: [Errno 2] No such file or directory test_userlist test test_userlist crashed -- : [Errno 2] No such file or directory Re-running test 'test_userlist' in verbose mode test test_userlist crashed -- : [Errno 2] No such file or directory Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 861, in runtest_inner with saved_test_environment(test, verbose, quiet) as environment: File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 814, in __enter__ in self.resource_info()) File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 813, in self.saved_values = dict((name, get()) for name, get, restore File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 773, in get_cwd return os.getcwd() OSError: [Errno 2] No such file or directory test_userstring test test_userstring crashed -- : [Errno 2] No such file or directory Re-running test 'test_userstring' in verbose mode test test_userstring crashed -- : [Errno 2] No such file or directory Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 861, in runtest_inner with saved_test_environment(test, verbose, quiet) as environment: File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 814, in __enter__ in self.resource_info()) File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 813, in self.saved_values = dict((name, get()) for name, get, restore File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 773, in get_cwd return os.getcwd() OSError: [Errno 2] No such file or directory test_uu test test_uu crashed -- : [Errno 2] No such file or directory Re-running test 'test_uu' in verbose mode test test_uu crashed -- : [Errno 2] No such file or directory Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 861, in runtest_inner with saved_test_environment(test, verbose, quiet) as environment: File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 814, in __enter__ in self.resource_info()) File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 813, in self.saved_values = dict((name, get()) for name, get, restore File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 773, in get_cwd return os.getcwd() OSError: [Errno 2] No such file or directory test_uuid test test_uuid crashed -- : [Errno 2] No such file or directory Re-running test 'test_uuid' in verbose mode test test_uuid crashed -- : [Errno 2] No such file or directory Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 861, in runtest_inner with saved_test_environment(test, verbose, quiet) as environment: File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 814, in __enter__ in self.resource_info()) File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 813, in self.saved_values = dict((name, get()) for name, get, restore File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 773, in get_cwd return os.getcwd() OSError: [Errno 2] No such file or directory test_wait3 test test_wait3 crashed -- : [Errno 2] No such file or directory Re-running test 'test_wait3' in verbose mode test test_wait3 crashed -- : [Errno 2] No such file or directory Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 861, in runtest_inner with saved_test_environment(test, verbose, quiet) as environment: File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 814, in __enter__ in self.resource_info()) File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 813, in self.saved_values = dict((name, get()) for name, get, restore File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 773, in get_cwd return os.getcwd() OSError: [Errno 2] No such file or directory test_wait4 test test_wait4 crashed -- : [Errno 2] No such file or directory Re-running test 'test_wait4' in verbose mode test test_wait4 crashed -- : [Errno 2] No such file or directory Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 861, in runtest_inner with saved_test_environment(test, verbose, quiet) as environment: File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 814, in __enter__ in self.resource_info()) File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 813, in self.saved_values = dict((name, get()) for name, get, restore File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 773, in get_cwd return os.getcwd() OSError: [Errno 2] No such file or directory test_warnings test test_warnings crashed -- : [Errno 2] No such file or directory Re-running test 'test_warnings' in verbose mode test test_warnings crashed -- : [Errno 2] No such file or directory Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 861, in runtest_inner with saved_test_environment(test, verbose, quiet) as environment: File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 814, in __enter__ in self.resource_info()) File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 813, in self.saved_values = dict((name, get()) for name, get, restore File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 773, in get_cwd return os.getcwd() OSError: [Errno 2] No such file or directory test_wave test test_wave crashed -- : [Errno 2] No such file or directory Re-running test 'test_wave' in verbose mode test test_wave crashed -- : [Errno 2] No such file or directory Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 861, in runtest_inner with saved_test_environment(test, verbose, quiet) as environment: File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 814, in __enter__ in self.resource_info()) File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 813, in self.saved_values = dict((name, get()) for name, get, restore File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 773, in get_cwd return os.getcwd() OSError: [Errno 2] No such file or directory test_weakref test test_weakref crashed -- : [Errno 2] No such file or directory Re-running test 'test_weakref' in verbose mode test test_weakref crashed -- : [Errno 2] No such file or directory Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 861, in runtest_inner with saved_test_environment(test, verbose, quiet) as environment: File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 814, in __enter__ in self.resource_info()) File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 813, in self.saved_values = dict((name, get()) for name, get, restore File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 773, in get_cwd return os.getcwd() OSError: [Errno 2] No such file or directory test_weakset test test_weakset crashed -- : [Errno 2] No such file or directory Re-running test 'test_weakset' in verbose mode test test_weakset crashed -- : [Errno 2] No such file or directory Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 861, in runtest_inner with saved_test_environment(test, verbose, quiet) as environment: File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 814, in __enter__ in self.resource_info()) File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 813, in self.saved_values = dict((name, get()) for name, get, restore File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 773, in get_cwd return os.getcwd() OSError: [Errno 2] No such file or directory test_whichdb test test_whichdb crashed -- : [Errno 2] No such file or directory Re-running test 'test_whichdb' in verbose mode test test_whichdb crashed -- : [Errno 2] No such file or directory Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 861, in runtest_inner with saved_test_environment(test, verbose, quiet) as environment: File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 814, in __enter__ in self.resource_info()) File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 813, in self.saved_values = dict((name, get()) for name, get, restore File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 773, in get_cwd return os.getcwd() OSError: [Errno 2] No such file or directory test_winreg test test_winreg crashed -- : [Errno 2] No such file or directory Re-running test 'test_winreg' in verbose mode test test_winreg crashed -- : [Errno 2] No such file or directory Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 861, in runtest_inner with saved_test_environment(test, verbose, quiet) as environment: File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 814, in __enter__ in self.resource_info()) File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 813, in self.saved_values = dict((name, get()) for name, get, restore File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 773, in get_cwd return os.getcwd() OSError: [Errno 2] No such file or directory test_winsound test test_winsound crashed -- : [Errno 2] No such file or directory Re-running test 'test_winsound' in verbose mode test test_winsound crashed -- : [Errno 2] No such file or directory Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 861, in runtest_inner with saved_test_environment(test, verbose, quiet) as environment: File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 814, in __enter__ in self.resource_info()) File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 813, in self.saved_values = dict((name, get()) for name, get, restore File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 773, in get_cwd return os.getcwd() OSError: [Errno 2] No such file or directory test_with test test_with crashed -- : [Errno 2] No such file or directory Re-running test 'test_with' in verbose mode test test_with crashed -- : [Errno 2] No such file or directory Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 861, in runtest_inner with saved_test_environment(test, verbose, quiet) as environment: File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 814, in __enter__ in self.resource_info()) File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 813, in self.saved_values = dict((name, get()) for name, get, restore File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 773, in get_cwd return os.getcwd() OSError: [Errno 2] No such file or directory test_wsgiref test test_wsgiref crashed -- : [Errno 2] No such file or directory Re-running test 'test_wsgiref' in verbose mode test test_wsgiref crashed -- : [Errno 2] No such file or directory Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 861, in runtest_inner with saved_test_environment(test, verbose, quiet) as environment: File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 814, in __enter__ in self.resource_info()) File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 813, in self.saved_values = dict((name, get()) for name, get, restore File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 773, in get_cwd return os.getcwd() OSError: [Errno 2] No such file or directory test_xdrlib test test_xdrlib crashed -- : [Errno 2] No such file or directory Re-running test 'test_xdrlib' in verbose mode test test_xdrlib crashed -- : [Errno 2] No such file or directory Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 861, in runtest_inner with saved_test_environment(test, verbose, quiet) as environment: File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 814, in __enter__ in self.resource_info()) File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 813, in self.saved_values = dict((name, get()) for name, get, restore File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 773, in get_cwd return os.getcwd() OSError: [Errno 2] No such file or directory test_xml_etree test test_xml_etree crashed -- : [Errno 2] No such file or directory Re-running test 'test_xml_etree' in verbose mode test test_xml_etree crashed -- : [Errno 2] No such file or directory Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 861, in runtest_inner with saved_test_environment(test, verbose, quiet) as environment: File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 814, in __enter__ in self.resource_info()) File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 813, in self.saved_values = dict((name, get()) for name, get, restore File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 773, in get_cwd return os.getcwd() OSError: [Errno 2] No such file or directory test_xml_etree_c test test_xml_etree_c crashed -- : [Errno 2] No such file or directory Re-running test 'test_xml_etree_c' in verbose mode test test_xml_etree_c crashed -- : [Errno 2] No such file or directory Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 861, in runtest_inner with saved_test_environment(test, verbose, quiet) as environment: File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 814, in __enter__ in self.resource_info()) File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 813, in self.saved_values = dict((name, get()) for name, get, restore File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 773, in get_cwd return os.getcwd() OSError: [Errno 2] No such file or directory test_xmllib test test_xmllib crashed -- : [Errno 2] No such file or directory Re-running test 'test_xmllib' in verbose mode test test_xmllib crashed -- : [Errno 2] No such file or directory Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 861, in runtest_inner with saved_test_environment(test, verbose, quiet) as environment: File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 814, in __enter__ in self.resource_info()) File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 813, in self.saved_values = dict((name, get()) for name, get, restore File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 773, in get_cwd return os.getcwd() OSError: [Errno 2] No such file or directory test_xmlrpc test test_xmlrpc crashed -- : [Errno 2] No such file or directory Re-running test 'test_xmlrpc' in verbose mode test test_xmlrpc crashed -- : [Errno 2] No such file or directory Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 861, in runtest_inner with saved_test_environment(test, verbose, quiet) as environment: File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 814, in __enter__ in self.resource_info()) File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 813, in self.saved_values = dict((name, get()) for name, get, restore File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 773, in get_cwd return os.getcwd() OSError: [Errno 2] No such file or directory test_xpickle test test_xpickle crashed -- : [Errno 2] No such file or directory Re-running test 'test_xpickle' in verbose mode test test_xpickle crashed -- : [Errno 2] No such file or directory Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 861, in runtest_inner with saved_test_environment(test, verbose, quiet) as environment: File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 814, in __enter__ in self.resource_info()) File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 813, in self.saved_values = dict((name, get()) for name, get, restore File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 773, in get_cwd return os.getcwd() OSError: [Errno 2] No such file or directory test_xrange test test_xrange crashed -- : [Errno 2] No such file or directory Re-running test 'test_xrange' in verbose mode test test_xrange crashed -- : [Errno 2] No such file or directory Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 861, in runtest_inner with saved_test_environment(test, verbose, quiet) as environment: File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 814, in __enter__ in self.resource_info()) File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 813, in self.saved_values = dict((name, get()) for name, get, restore File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 773, in get_cwd return os.getcwd() OSError: [Errno 2] No such file or directory test_zipfile test test_zipfile crashed -- : [Errno 2] No such file or directory Re-running test 'test_zipfile' in verbose mode test test_zipfile crashed -- : [Errno 2] No such file or directory Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 861, in runtest_inner with saved_test_environment(test, verbose, quiet) as environment: File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 814, in __enter__ in self.resource_info()) File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 813, in self.saved_values = dict((name, get()) for name, get, restore File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 773, in get_cwd return os.getcwd() OSError: [Errno 2] No such file or directory test_zipfile64 test test_zipfile64 crashed -- : [Errno 2] No such file or directory Re-running test 'test_zipfile64' in verbose mode test test_zipfile64 crashed -- : [Errno 2] No such file or directory Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 861, in runtest_inner with saved_test_environment(test, verbose, quiet) as environment: File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 814, in __enter__ in self.resource_info()) File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 813, in self.saved_values = dict((name, get()) for name, get, restore File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 773, in get_cwd return os.getcwd() OSError: [Errno 2] No such file or directory test_zipimport test test_zipimport crashed -- : [Errno 2] No such file or directory Re-running test 'test_zipimport' in verbose mode test test_zipimport crashed -- : [Errno 2] No such file or directory Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 861, in runtest_inner with saved_test_environment(test, verbose, quiet) as environment: File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 814, in __enter__ in self.resource_info()) File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 813, in self.saved_values = dict((name, get()) for name, get, restore File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 773, in get_cwd return os.getcwd() OSError: [Errno 2] No such file or directory test_zipimport_support test test_zipimport_support crashed -- : [Errno 2] No such file or directory Re-running test 'test_zipimport_support' in verbose mode test test_zipimport_support crashed -- : [Errno 2] No such file or directory Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 861, in runtest_inner with saved_test_environment(test, verbose, quiet) as environment: File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 814, in __enter__ in self.resource_info()) File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 813, in self.saved_values = dict((name, get()) for name, get, restore File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 773, in get_cwd return os.getcwd() OSError: [Errno 2] No such file or directory test_zlib test test_zlib crashed -- : [Errno 2] No such file or directory Re-running test 'test_zlib' in verbose mode test test_zlib crashed -- : [Errno 2] No such file or directory Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 861, in runtest_inner with saved_test_environment(test, verbose, quiet) as environment: File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 814, in __enter__ in self.resource_info()) File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 813, in self.saved_values = dict((name, get()) for name, get, restore File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 773, in get_cwd return os.getcwd() OSError: [Errno 2] No such file or directory 186 tests OK. 181 tests failed: test_mailbox test_marshal test_math test_md5 test_memoryio test_memoryview test_mhlib test_mimetools test_mimetypes test_minidom test_mmap test_module test_modulefinder test_multibytecodec test_multibytecodec_support test_multifile test_multiprocessing test_mutants test_mutex test_netrc test_new test_nis test_normalization test_ntpath test_old_mailbox test_openpty test_operator test_optparse test_os test_parser test_pdb test_peepholer test_pep247 test_pep263 test_pep277 test_pep292 test_pep352 test_pickle test_pickletools test_pipes test_pkg test_pkgimport test_pkgutil test_platform test_plistlib test_poll test_popen test_popen2 test_poplib test_posix test_posixpath test_pow test_pprint test_print test_profile test_profilehooks test_property test_pstats test_pty test_pwd test_py3kwarn test_pyclbr test_pydoc test_pyexpat test_queue test_quopri test_random test_re test_readline test_repr test_resource test_rfc822 test_richcmp test_robotparser test_runpy test_sax test_scope test_scriptpackages test_select test_set test_setcomps test_sets test_sgmllib test_sha test_shelve test_shlex test_shutil test_signal test_site test_slice test_smtplib test_smtpnet test_socket test_socketserver test_softspace test_sort test_sqlite test_ssl test_startfile test_str test_strftime test_string test_stringprep test_strop test_strptime test_strtod test_struct test_structmembers test_structseq test_subprocess test_sunaudiodev test_sundry test_symtable test_syntax test_sys test_sysconfig test_tarfile test_tcl test_telnetlib test_tempfile test_textwrap test_thread test_threaded_import test_threadedtempfile test_threading test_threading_local test_threadsignals test_time test_timeout test_tk test_tokenize test_trace test_traceback test_transformer test_ttk_guionly test_ttk_textonly test_tuple test_typechecks test_ucn test_unary test_undocumented_details test_unicode test_unicode_file test_unicodedata test_univnewlines test_univnewlines2k test_unpack test_urllib test_urllib2 test_urllib2_localnet test_urllib2net test_urllibnet test_urlparse test_userdict test_userlist test_userstring test_uu test_uuid test_wait3 test_wait4 test_warnings test_wave test_weakref test_weakset test_whichdb test_winreg test_winsound test_with test_wsgiref test_xdrlib test_xml_etree test_xml_etree_c test_xmllib test_xmlrpc test_xpickle test_xrange test_zipfile test_zipfile64 test_zipimport test_zipimport_support test_zlib 14 tests skipped: test_aepack test_al test_applesingle test_bsddb185 test_cd test_cl test_epoll test_gdb test_gl test_imgfile test_ioctl test_kqueue test_macos test_macostools 3 skips unexpected on linux2: test_epoll test_gdb test_ioctl == CPython 2.7b2+ (trunk:81375M, May 20 2010, 04:01:38) [GCC 3.3.4 20040623 (Gentoo Linux 3.3.4-r1, ssp-3.3.2-2, pie-8.7.6)] == Linux-2.6.9-gentoo-r1-i686-AMD_Athlon-tm-_XP_3000+-with-gentoo-1.4.16 little-endian == /tmp/test_python_24606 test_grammar test_opcodes test_dict test_builtin test_exceptions test_types test_unittest test_doctest test_doctest2 test_MimeWriter test_SimpleHTTPServer test_StringIO test___all__ test___future__ test__locale test_abc test_abstract_numbers test_aepack test_aepack skipped -- No module named aetypes test_aifc test_al test_al skipped -- No module named al test_anydbm test_applesingle test_applesingle skipped -- No module named MacOS test_argparse test_array test_ascii_formatd test_ast test_asynchat test_asyncore test_atexit test_audioop test_augassign test_base64 test_bastion test_bigaddrspace test_bigmem test_binascii test_binhex test_binop test_bisect test_bool test_bsddb test_bsddb185 test_bsddb185 skipped -- No module named bsddb185 test_bsddb3 Sleepycat Software: Berkeley DB 4.1.25: (December 19, 2002) Test path prefix: /tmp/z-test_bsddb3-24606 test_buffer test_bufio test_bytes test_bz2 test_calendar test_call test_capi test_cd test_cd skipped -- No module named cd test_cfgparser test_cgi test_charmapcodec test_cl test_cl skipped -- No module named cl test_class test_cmath test_cmd test_cmd_line test_cmd_line_script test_code test_codeccallbacks test_codecencodings_cn test_codecencodings_hk test_codecencodings_jp test_codecencodings_kr test_codecencodings_tw test_codecmaps_cn test_codecmaps_hk test_codecmaps_jp test_codecmaps_kr test_codecmaps_tw test_codecs test_codeop test_coding test_coercion test_collections test_colorsys test_commands test_compare test_compile test_compileall test_compiler testCompileLibrary still working, be patient... test_complex test_complex_args test_contains test_contextlib test_cookie test_cookielib test_copy test_copy_reg test_cpickle test_cprofile test_crypt test_csv test_ctypes test_datetime test_dbm test_decimal test_decorators test_defaultdict test_deque test_descr test_descrtut test_dictcomps test_dictviews test_difflib test_dircache test_dis test_distutils [20646 refs] test_dl test_docxmlrpc test_dumbdbm test_dummy_thread test_dummy_threading test_email test_email_codecs test_email_renamed test_enumerate test_eof test_epoll test_epoll skipped -- kernel doesn't support epoll() test_errno test_exception_variations test_extcall test_fcntl test_file test_file2k test_filecmp test_fileinput test_fileio test_float test_fnmatch test_fork1 test_format test_fpformat test_fractions test_frozen test_ftplib test_funcattrs test_functools test_future test_future3 test_future4 test_future5 test_future_builtins test_gc test_gdb test_gdb skipped -- gdb versions before 7.0 didn't support python embedding Saw: GNU gdb 6.2.1 Copyright 2004 Free Software Foundation, Inc. GDB is free software, covered by the GNU General Public License, and you are welcome to change it and/or distribute copies of it under certain conditions. Type "show copying" to see the conditions. There is absolutely no warranty for GDB. Type "show warranty" for details. This GDB was configured as "i386-pc-linux-gnu". test_gdbm test_generators test_genericpath test_genexps test_getargs test_getargs2 test_getopt test_gettext test_gl test_gl skipped -- No module named gl test_glob test_global test_grp test_gzip test_hash test_hashlib test_heapq test_hmac test_hotshot test_htmllib test_htmlparser test_httplib test_httpservers [16651 refs] [16651 refs] [16651 refs] [26939 refs] test_imageop test_imaplib test_imgfile test_imgfile skipped -- No module named imgfile test_imp test_import test_importhooks test_importlib test_index test_inspect test_int test_int_literal test_io test_ioctl test_ioctl skipped -- Unable to open /dev/tty test_isinstance test_iter test_iterlen test_itertools test_json test_kqueue test_kqueue skipped -- test works only on BSD test_largefile test_lib2to3 test_linecache test_list test_locale test_logging test_long test_long_future test_longexp test_macos test_macos skipped -- No module named MacOS test_macostools test_macostools skipped -- No module named MacOS test_macpath test_mailbox test test_mailbox failed -- Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/test_mailbox.py", line 843, in test_lock_conflict self._box.lock() File "/tmp/python-test/local/lib/python2.7/mailbox.py", line 604, in lock _lock_file(self._file) File "/tmp/python-test/local/lib/python2.7/mailbox.py", line 1891, in _lock_file f.name) ExternalClashError: lockf: lock unavailable: /tmp/test_python_24606/@test_24606_tmp Re-running test 'test_mailbox' in verbose mode test_notimplemented (test.test_mailbox.TestMailboxSuperclass) ... ok test_add (test.test_mailbox.TestMaildir) ... ok test_add_MM (test.test_mailbox.TestMaildir) ... ok test_add_and_remove_folders (test.test_mailbox.TestMaildir) ... ok test_clean (test.test_mailbox.TestMaildir) ... ok test_clear (test.test_mailbox.TestMaildir) ... ok test_close (test.test_mailbox.TestMaildir) ... ok test_consistent_factory (test.test_mailbox.TestMaildir) ... ok test_contains (test.test_mailbox.TestMaildir) ... ok test_create_tmp (test.test_mailbox.TestMaildir) ... ok test_delitem (test.test_mailbox.TestMaildir) ... ok test_directory_in_folder (test.test_mailbox.TestMaildir) ... ok test_discard (test.test_mailbox.TestMaildir) ... ok test_dump_message (test.test_mailbox.TestMaildir) ... ok test_file_permissions (test.test_mailbox.TestMaildir) ... ok test_flush (test.test_mailbox.TestMaildir) ... ok test_folder (test.test_mailbox.TestMaildir) ... ok test_folder_file_perms (test.test_mailbox.TestMaildir) ... ok test_get (test.test_mailbox.TestMaildir) ... ok test_get_MM (test.test_mailbox.TestMaildir) ... ok test_get_file (test.test_mailbox.TestMaildir) ... ok test_get_folder (test.test_mailbox.TestMaildir) ... ok test_get_message (test.test_mailbox.TestMaildir) ... ok test_get_string (test.test_mailbox.TestMaildir) ... ok test_getitem (test.test_mailbox.TestMaildir) ... ok test_has_key (test.test_mailbox.TestMaildir) ... ok test_initialize_existing (test.test_mailbox.TestMaildir) ... ok test_initialize_new (test.test_mailbox.TestMaildir) ... ok test_items (test.test_mailbox.TestMaildir) ... ok test_iter (test.test_mailbox.TestMaildir) ... ok test_iteritems (test.test_mailbox.TestMaildir) ... ok test_iterkeys (test.test_mailbox.TestMaildir) ... ok test_itervalues (test.test_mailbox.TestMaildir) ... ok test_keys (test.test_mailbox.TestMaildir) ... ok test_len (test.test_mailbox.TestMaildir) ... ok test_list_folders (test.test_mailbox.TestMaildir) ... ok test_lock_unlock (test.test_mailbox.TestMaildir) ... ok test_lookup (test.test_mailbox.TestMaildir) ... ok test_pop (test.test_mailbox.TestMaildir) ... ok test_popitem (test.test_mailbox.TestMaildir) ... ok test_refresh (test.test_mailbox.TestMaildir) ... ok test_remove (test.test_mailbox.TestMaildir) ... ok test_reread (test.test_mailbox.TestMaildir) ... ok test_set_MM (test.test_mailbox.TestMaildir) ... ok test_set_item (test.test_mailbox.TestMaildir) ... ok test_update (test.test_mailbox.TestMaildir) ... ok test_values (test.test_mailbox.TestMaildir) ... ok test_add (test.test_mailbox.TestMbox) ... ok test_add_and_close (test.test_mailbox.TestMbox) ... ok test_add_from_string (test.test_mailbox.TestMbox) ... ok test_add_mbox_or_mmdf_message (test.test_mailbox.TestMbox) ... ok test_clear (test.test_mailbox.TestMbox) ... ok test_close (test.test_mailbox.TestMbox) ... ok test_contains (test.test_mailbox.TestMbox) ... ok test_delitem (test.test_mailbox.TestMbox) ... ok test_discard (test.test_mailbox.TestMbox) ... ok test_dump_message (test.test_mailbox.TestMbox) ... ok test_file_perms (test.test_mailbox.TestMbox) ... ok test_flush (test.test_mailbox.TestMbox) ... ok test_get (test.test_mailbox.TestMbox) ... ok test_get_file (test.test_mailbox.TestMbox) ... ok test_get_message (test.test_mailbox.TestMbox) ... ok test_get_string (test.test_mailbox.TestMbox) ... ok test_getitem (test.test_mailbox.TestMbox) ... ok test_has_key (test.test_mailbox.TestMbox) ... ok test_items (test.test_mailbox.TestMbox) ... ok test_iter (test.test_mailbox.TestMbox) ... ok test_iteritems (test.test_mailbox.TestMbox) ... ok test_iterkeys (test.test_mailbox.TestMbox) ... ok test_itervalues (test.test_mailbox.TestMbox) ... ok test_keys (test.test_mailbox.TestMbox) ... ok test_len (test.test_mailbox.TestMbox) ... ok test_lock_conflict (test.test_mailbox.TestMbox) ... ok test_lock_unlock (test.test_mailbox.TestMbox) ... ok test_open_close_open (test.test_mailbox.TestMbox) ... ok test_pop (test.test_mailbox.TestMbox) ... ok test_popitem (test.test_mailbox.TestMbox) ... ok test_relock (test.test_mailbox.TestMbox) ... ok test_remove (test.test_mailbox.TestMbox) ... ok test_set_item (test.test_mailbox.TestMbox) ... ok test_update (test.test_mailbox.TestMbox) ... ok test_values (test.test_mailbox.TestMbox) ... ok test_add (test.test_mailbox.TestMMDF) ... ok test_add_and_close (test.test_mailbox.TestMMDF) ... ok test_add_from_string (test.test_mailbox.TestMMDF) ... ok test_add_mbox_or_mmdf_message (test.test_mailbox.TestMMDF) ... ok test_clear (test.test_mailbox.TestMMDF) ... ok test_close (test.test_mailbox.TestMMDF) ... ok test_contains (test.test_mailbox.TestMMDF) ... ok test_delitem (test.test_mailbox.TestMMDF) ... ok test_discard (test.test_mailbox.TestMMDF) ... ok test_dump_message (test.test_mailbox.TestMMDF) ... ok test_flush (test.test_mailbox.TestMMDF) ... ok test_get (test.test_mailbox.TestMMDF) ... ok test_get_file (test.test_mailbox.TestMMDF) ... ok test_get_message (test.test_mailbox.TestMMDF) ... ok test_get_string (test.test_mailbox.TestMMDF) ... ok test_getitem (test.test_mailbox.TestMMDF) ... ok test_has_key (test.test_mailbox.TestMMDF) ... ok test_items (test.test_mailbox.TestMMDF) ... ok test_iter (test.test_mailbox.TestMMDF) ... ok test_iteritems (test.test_mailbox.TestMMDF) ... ok test_iterkeys (test.test_mailbox.TestMMDF) ... ok test_itervalues (test.test_mailbox.TestMMDF) ... ok test_keys (test.test_mailbox.TestMMDF) ... ok test_len (test.test_mailbox.TestMMDF) ... ok test_lock_conflict (test.test_mailbox.TestMMDF) ... ok test_lock_unlock (test.test_mailbox.TestMMDF) ... ok test_open_close_open (test.test_mailbox.TestMMDF) ... ok test_pop (test.test_mailbox.TestMMDF) ... ok test_popitem (test.test_mailbox.TestMMDF) ... ok test_relock (test.test_mailbox.TestMMDF) ... ok test_remove (test.test_mailbox.TestMMDF) ... ok test_set_item (test.test_mailbox.TestMMDF) ... ok test_update (test.test_mailbox.TestMMDF) ... ok test_values (test.test_mailbox.TestMMDF) ... ok test_add (test.test_mailbox.TestMH) ... ok test_add_and_remove_folders (test.test_mailbox.TestMH) ... ok test_clear (test.test_mailbox.TestMH) ... ok test_close (test.test_mailbox.TestMH) ... ok test_contains (test.test_mailbox.TestMH) ... ok test_delitem (test.test_mailbox.TestMH) ... ok test_discard (test.test_mailbox.TestMH) ... ok test_dump_message (test.test_mailbox.TestMH) ... ok test_flush (test.test_mailbox.TestMH) ... ok test_get (test.test_mailbox.TestMH) ... ok test_get_file (test.test_mailbox.TestMH) ... ok test_get_folder (test.test_mailbox.TestMH) ... ok test_get_message (test.test_mailbox.TestMH) ... ok test_get_string (test.test_mailbox.TestMH) ... ok test_getitem (test.test_mailbox.TestMH) ... ok test_has_key (test.test_mailbox.TestMH) ... ok test_issue2625 (test.test_mailbox.TestMH) ... ok test_issue7627 (test.test_mailbox.TestMH) ... ok test_items (test.test_mailbox.TestMH) ... ok test_iter (test.test_mailbox.TestMH) ... ok test_iteritems (test.test_mailbox.TestMH) ... ok test_iterkeys (test.test_mailbox.TestMH) ... ok test_itervalues (test.test_mailbox.TestMH) ... ok test_keys (test.test_mailbox.TestMH) ... ok test_len (test.test_mailbox.TestMH) ... ok test_list_folders (test.test_mailbox.TestMH) ... ok test_lock_unlock (test.test_mailbox.TestMH) ... ok test_pack (test.test_mailbox.TestMH) ... ok test_pop (test.test_mailbox.TestMH) ... ok test_popitem (test.test_mailbox.TestMH) ... ok test_remove (test.test_mailbox.TestMH) ... ok test_sequences (test.test_mailbox.TestMH) ... ok test_set_item (test.test_mailbox.TestMH) ... ok test_update (test.test_mailbox.TestMH) ... ok test_values (test.test_mailbox.TestMH) ... ok test_add (test.test_mailbox.TestBabyl) ... ok test_clear (test.test_mailbox.TestBabyl) ... ok test_close (test.test_mailbox.TestBabyl) ... ok test_contains (test.test_mailbox.TestBabyl) ... ok test_delitem (test.test_mailbox.TestBabyl) ... ok test_discard (test.test_mailbox.TestBabyl) ... ok test_dump_message (test.test_mailbox.TestBabyl) ... ok test_flush (test.test_mailbox.TestBabyl) ... ok test_get (test.test_mailbox.TestBabyl) ... ok test_get_file (test.test_mailbox.TestBabyl) ... ok test_get_message (test.test_mailbox.TestBabyl) ... ok test_get_string (test.test_mailbox.TestBabyl) ... ok test_getitem (test.test_mailbox.TestBabyl) ... ok test_has_key (test.test_mailbox.TestBabyl) ... ok test_items (test.test_mailbox.TestBabyl) ... ok test_iter (test.test_mailbox.TestBabyl) ... ok test_iteritems (test.test_mailbox.TestBabyl) ... ok test_iterkeys (test.test_mailbox.TestBabyl) ... ok test_itervalues (test.test_mailbox.TestBabyl) ... ok test_keys (test.test_mailbox.TestBabyl) ... ok test_labels (test.test_mailbox.TestBabyl) ... ok test_len (test.test_mailbox.TestBabyl) ... ok test_lock_unlock (test.test_mailbox.TestBabyl) ... ok test_pop (test.test_mailbox.TestBabyl) ... ok test_popitem (test.test_mailbox.TestBabyl) ... ok test_remove (test.test_mailbox.TestBabyl) ... ok test_set_item (test.test_mailbox.TestBabyl) ... ok test_update (test.test_mailbox.TestBabyl) ... ok test_values (test.test_mailbox.TestBabyl) ... ok test_become_message (test.test_mailbox.TestMessage) ... ok test_explain_to (test.test_mailbox.TestMessage) ... ok test_initialize_incorrectly (test.test_mailbox.TestMessage) ... ok test_initialize_with_eMM (test.test_mailbox.TestMessage) ... ok test_initialize_with_file (test.test_mailbox.TestMessage) ... ok test_initialize_with_nothing (test.test_mailbox.TestMessage) ... ok test_initialize_with_string (test.test_mailbox.TestMessage) ... ok test_become_message (test.test_mailbox.TestMaildirMessage) ... ok test_date (test.test_mailbox.TestMaildirMessage) ... ok test_explain_to (test.test_mailbox.TestMaildirMessage) ... ok test_flags (test.test_mailbox.TestMaildirMessage) ... ok test_info (test.test_mailbox.TestMaildirMessage) ... ok test_info_and_flags (test.test_mailbox.TestMaildirMessage) ... ok test_initialize_incorrectly (test.test_mailbox.TestMaildirMessage) ... ok test_initialize_with_eMM (test.test_mailbox.TestMaildirMessage) ... ok test_initialize_with_file (test.test_mailbox.TestMaildirMessage) ... ok test_initialize_with_nothing (test.test_mailbox.TestMaildirMessage) ... ok test_initialize_with_string (test.test_mailbox.TestMaildirMessage) ... ok test_subdir (test.test_mailbox.TestMaildirMessage) ... ok test_become_message (test.test_mailbox.TestMboxMessage) ... ok test_explain_to (test.test_mailbox.TestMboxMessage) ... ok test_flags (test.test_mailbox.TestMboxMessage) ... ok test_from (test.test_mailbox.TestMboxMessage) ... ok test_initialize_incorrectly (test.test_mailbox.TestMboxMessage) ... ok test_initialize_with_eMM (test.test_mailbox.TestMboxMessage) ... ok test_initialize_with_file (test.test_mailbox.TestMboxMessage) ... ok test_initialize_with_nothing (test.test_mailbox.TestMboxMessage) ... ok test_initialize_with_string (test.test_mailbox.TestMboxMessage) ... ok test_initialize_with_unixfrom (test.test_mailbox.TestMboxMessage) ... ok test_become_message (test.test_mailbox.TestMHMessage) ... ok test_explain_to (test.test_mailbox.TestMHMessage) ... ok test_initialize_incorrectly (test.test_mailbox.TestMHMessage) ... ok test_initialize_with_eMM (test.test_mailbox.TestMHMessage) ... ok test_initialize_with_file (test.test_mailbox.TestMHMessage) ... ok test_initialize_with_nothing (test.test_mailbox.TestMHMessage) ... ok test_initialize_with_string (test.test_mailbox.TestMHMessage) ... ok test_sequences (test.test_mailbox.TestMHMessage) ... ok test_become_message (test.test_mailbox.TestBabylMessage) ... ok test_explain_to (test.test_mailbox.TestBabylMessage) ... ok test_initialize_incorrectly (test.test_mailbox.TestBabylMessage) ... ok test_initialize_with_eMM (test.test_mailbox.TestBabylMessage) ... ok test_initialize_with_file (test.test_mailbox.TestBabylMessage) ... ok test_initialize_with_nothing (test.test_mailbox.TestBabylMessage) ... ok test_initialize_with_string (test.test_mailbox.TestBabylMessage) ... ok test_labels (test.test_mailbox.TestBabylMessage) ... ok test_visible (test.test_mailbox.TestBabylMessage) ... ok test_become_message (test.test_mailbox.TestMMDFMessage) ... ok test_explain_to (test.test_mailbox.TestMMDFMessage) ... ok test_flags (test.test_mailbox.TestMMDFMessage) ... ok test_from (test.test_mailbox.TestMMDFMessage) ... ok test_initialize_incorrectly (test.test_mailbox.TestMMDFMessage) ... ok test_initialize_with_eMM (test.test_mailbox.TestMMDFMessage) ... ok test_initialize_with_file (test.test_mailbox.TestMMDFMessage) ... ok test_initialize_with_nothing (test.test_mailbox.TestMMDFMessage) ... ok test_initialize_with_string (test.test_mailbox.TestMMDFMessage) ... ok test_initialize_with_unixfrom (test.test_mailbox.TestMMDFMessage) ... ok test_babyl_to_babyl (test.test_mailbox.TestMessageConversion) ... ok test_babyl_to_maildir (test.test_mailbox.TestMessageConversion) ... ok test_babyl_to_mboxmmdf (test.test_mailbox.TestMessageConversion) ... ok test_babyl_to_mh (test.test_mailbox.TestMessageConversion) ... ok test_maildir_to_babyl (test.test_mailbox.TestMessageConversion) ... ok test_maildir_to_maildir (test.test_mailbox.TestMessageConversion) ... ok test_maildir_to_mboxmmdf (test.test_mailbox.TestMessageConversion) ... ok test_maildir_to_mh (test.test_mailbox.TestMessageConversion) ... ok test_mboxmmdf_to_babyl (test.test_mailbox.TestMessageConversion) ... ok test_mboxmmdf_to_maildir (test.test_mailbox.TestMessageConversion) ... ok test_mboxmmdf_to_mboxmmdf (test.test_mailbox.TestMessageConversion) ... ok test_mboxmmdf_to_mh (test.test_mailbox.TestMessageConversion) ... ok test_mh_to_babyl (test.test_mailbox.TestMessageConversion) ... ok test_mh_to_maildir (test.test_mailbox.TestMessageConversion) ... ok test_mh_to_mboxmmdf (test.test_mailbox.TestMessageConversion) ... ok test_mh_to_mh (test.test_mailbox.TestMessageConversion) ... ok test_plain_to_x (test.test_mailbox.TestMessageConversion) ... ok test_x_to_invalid (test.test_mailbox.TestMessageConversion) ... ok test_x_to_plain (test.test_mailbox.TestMessageConversion) ... ok test_close (test.test_mailbox.TestProxyFile) ... ok test_initialize (test.test_mailbox.TestProxyFile) ... ok test_iteration (test.test_mailbox.TestProxyFile) ... ok test_read (test.test_mailbox.TestProxyFile) ... ok test_readline (test.test_mailbox.TestProxyFile) ... ok test_readlines (test.test_mailbox.TestProxyFile) ... ok test_seek_and_tell (test.test_mailbox.TestProxyFile) ... ok test_close (test.test_mailbox.TestPartialFile) ... ok test_initialize (test.test_mailbox.TestPartialFile) ... ok test_iteration (test.test_mailbox.TestPartialFile) ... ok test_read (test.test_mailbox.TestPartialFile) ... ok test_readline (test.test_mailbox.TestPartialFile) ... ok test_readlines (test.test_mailbox.TestPartialFile) ... ok test_seek_and_tell (test.test_mailbox.TestPartialFile) ... ok test_empty_maildir (test.test_mailbox.MaildirTestCase) Test an empty maildir mailbox ... ok test_nonempty_maildir_both (test.test_mailbox.MaildirTestCase) ... ok test_nonempty_maildir_cur (test.test_mailbox.MaildirTestCase) ... ok test_nonempty_maildir_new (test.test_mailbox.MaildirTestCase) ... ok test_unix_mbox (test.test_mailbox.MaildirTestCase) ... ok ---------------------------------------------------------------------- Ran 274 tests in 12.434s OK test_marshal test_math test_md5 test_memoryio test_memoryview test_mhlib test_mimetools test_mimetypes test_minidom test_mmap test_module test_modulefinder test_multibytecodec test_multibytecodec_support test_multifile test_multiprocessing test_multiprocessing skipped -- This platform lacks a functioning sem_open implementation, therefore, the required synchronization primitives needed will not function, see issue 3770. test_mutants test_mutex test_netrc test_new test_nis test_normalization test_ntpath test_old_mailbox test_openpty test_operator test_optparse test_os [16651 refs] [16651 refs] test_parser Expecting 's_push: parser stack overflow' in next line s_push: parser stack overflow test_pdb test_peepholer test_pep247 test_pep263 test_pep277 test_pep277 skipped -- only NT+ and systems with Unicode-friendly filesystem encoding test_pep292 test_pep352 test_pickle test_pickletools test_pipes test_pkg test_pkgimport test_pkgutil test_platform [18047 refs] [18047 refs] test_plistlib test_poll test_popen [16656 refs] [16656 refs] [16656 refs] test_popen2 test_poplib test_posix test_posixpath test_pow test_pprint test_print test_profile test_profilehooks test_property test_pstats test_pty test_pwd test_py3kwarn test_py3kwarn skipped -- test.test_py3kwarn must be run with the -3 flag test_pyclbr test_pydoc [21863 refs] [21863 refs] [21863 refs] [21863 refs] [21863 refs] [21862 refs] [21862 refs] test_pyexpat test_queue test_quopri [19480 refs] [19480 refs] test_random test_re test_readline test_repr test_resource test_rfc822 test_richcmp test_robotparser test_runpy test_sax test_scope test_scriptpackages test_scriptpackages skipped -- No module named aetools test_select test_set test_setcomps test_sets test_sgmllib test_sha test_shelve test_shlex test_shutil test_signal test_site [16651 refs] [16651 refs] [16651 refs] [16651 refs] test_slice test_smtplib test_smtpnet test_socket test_socketserver test_softspace test_sort test_sqlite test_ssl test_startfile test_startfile skipped -- module os has no attribute startfile test_str test_strftime test_string test_stringprep test_strop test_strptime test_strtod test_struct test_structmembers test_structseq test_subprocess [16651 refs] [16651 refs] [16651 refs] [16651 refs] [16651 refs] [16651 refs] [16651 refs] [16651 refs] [16651 refs] [16651 refs] [16651 refs] [16651 refs] [16651 refs] [16651 refs] [16866 refs] [16651 refs] [16651 refs] [16651 refs] [16651 refs] [16651 refs] . [16651 refs] [16651 refs] this bit of output is from a test of stdout in a different process ... [16651 refs] [16651 refs] [16866 refs] [16651 refs] [16651 refs] [16651 refs] [16651 refs] [16651 refs] [16651 refs] [16651 refs] [16651 refs] [16651 refs] [16651 refs] [16651 refs] [16651 refs] [16651 refs] [16651 refs] [16651 refs] [16651 refs] [16651 refs] [16866 refs] [16651 refs] [16651 refs] [16651 refs] [16651 refs] [16651 refs] . [16651 refs] [16651 refs] this bit of output is from a test of stdout in a different process ... [16651 refs] [16651 refs] [16866 refs] test_sunaudiodev test_sunaudiodev skipped -- No module named sunaudiodev test_sundry test_symtable test_syntax test_sys [16651 refs] [16651 refs] [16651 refs] [16880 refs] [16674 refs] test_sysconfig [16651 refs] [16651 refs] test_tarfile test_tcl test_tcl skipped -- No module named _tkinter test_telnetlib test_tempfile [16651 refs] test_textwrap test_thread test_threaded_import test_threadedtempfile test_threading [19951 refs] [22122 refs] [21034 refs] [21034 refs] [21034 refs] [21034 refs] test_threading_local test_threadsignals test_time test_timeout test_tk test_tk skipped -- No module named _tkinter test_tokenize test_trace test_traceback test_transformer test_ttk_guionly test_ttk_guionly skipped -- No module named _tkinter test_ttk_textonly test_ttk_textonly skipped -- No module named _tkinter test_tuple test_typechecks test_ucn test_unary test_undocumented_details test_unicode test_unicode_file test_unicode_file skipped -- No Unicode filesystem semantics on this platform. test_unicodedata test_univnewlines test_univnewlines2k test_unpack test_urllib test_urllib2 test_urllib2_localnet test_urllib2net test_urllibnet test_urlparse test_userdict test_userlist test_userstring test_uu test_uuid test_wait3 test_wait4 test_warnings [16682 refs] [16682 refs] [16675 refs] [16682 refs] [16682 refs] [16675 refs] test_wave test_weakref test_weakset test_whichdb test_winreg test_winreg skipped -- No module named _winreg test_winsound test_winsound skipped -- No module named winsound test_with test_wsgiref test_xdrlib test_xml_etree test_xml_etree_c test_xmllib test_xmlrpc test_xpickle sh: line 1: python2.4: command not found sh: line 1: python2.6: command not found test_xrange test_zipfile test_zipfile64 test_zipfile64 skipped -- test requires loads of disk-space bytes and a long time to run test_zipimport test_zipimport_support test_zlib 352 tests OK. 1 test failed: test_mailbox 28 tests skipped: test_aepack test_al test_applesingle test_bsddb185 test_cd test_cl test_epoll test_gdb test_gl test_imgfile test_ioctl test_kqueue test_macos test_macostools test_multiprocessing test_pep277 test_py3kwarn test_scriptpackages test_startfile test_sunaudiodev test_tcl test_tk test_ttk_guionly test_ttk_textonly test_unicode_file test_winreg test_winsound test_zipfile64 7 skips unexpected on linux2: test_epoll test_gdb test_ioctl test_multiprocessing test_tk test_ttk_guionly test_ttk_textonly [981797 refs] test test_mailbox crashed -- : [Errno 2] No such file or directory Re-running test 'test_mailbox' in verbose mode test test_mailbox crashed -- : [Errno 2] No such file or directory Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 861, in runtest_inner with saved_test_environment(test, verbose, quiet) as environment: File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 814, in __enter__ in self.resource_info()) File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 813, in self.saved_values = dict((name, get()) for name, get, restore File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 773, in get_cwd return os.getcwd() OSError: [Errno 2] No such file or directory test_marshal test test_marshal crashed -- : [Errno 2] No such file or directory Re-running test 'test_marshal' in verbose mode test test_marshal crashed -- : [Errno 2] No such file or directory Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 861, in runtest_inner with saved_test_environment(test, verbose, quiet) as environment: File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 814, in __enter__ in self.resource_info()) File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 813, in self.saved_values = dict((name, get()) for name, get, restore File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 773, in get_cwd return os.getcwd() OSError: [Errno 2] No such file or directory test_math test test_math crashed -- : [Errno 2] No such file or directory Re-running test 'test_math' in verbose mode test test_math crashed -- : [Errno 2] No such file or directory Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 861, in runtest_inner with saved_test_environment(test, verbose, quiet) as environment: File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 814, in __enter__ in self.resource_info()) File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 813, in self.saved_values = dict((name, get()) for name, get, restore File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 773, in get_cwd return os.getcwd() OSError: [Errno 2] No such file or directory test_md5 test test_md5 crashed -- : [Errno 2] No such file or directory Re-running test 'test_md5' in verbose mode test test_md5 crashed -- : [Errno 2] No such file or directory Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 861, in runtest_inner with saved_test_environment(test, verbose, quiet) as environment: File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 814, in __enter__ in self.resource_info()) File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 813, in self.saved_values = dict((name, get()) for name, get, restore File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 773, in get_cwd return os.getcwd() OSError: [Errno 2] No such file or directory test_memoryio test test_memoryio crashed -- : [Errno 2] No such file or directory Re-running test 'test_memoryio' in verbose mode test test_memoryio crashed -- : [Errno 2] No such file or directory Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 861, in runtest_inner with saved_test_environment(test, verbose, quiet) as environment: File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 814, in __enter__ in self.resource_info()) File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 813, in self.saved_values = dict((name, get()) for name, get, restore File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 773, in get_cwd return os.getcwd() OSError: [Errno 2] No such file or directory test_memoryview test test_memoryview crashed -- : [Errno 2] No such file or directory Re-running test 'test_memoryview' in verbose mode test test_memoryview crashed -- : [Errno 2] No such file or directory Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 861, in runtest_inner with saved_test_environment(test, verbose, quiet) as environment: File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 814, in __enter__ in self.resource_info()) File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 813, in self.saved_values = dict((name, get()) for name, get, restore File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 773, in get_cwd return os.getcwd() OSError: [Errno 2] No such file or directory test_mhlib test test_mhlib crashed -- : [Errno 2] No such file or directory Re-running test 'test_mhlib' in verbose mode test test_mhlib crashed -- : [Errno 2] No such file or directory Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 861, in runtest_inner with saved_test_environment(test, verbose, quiet) as environment: File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 814, in __enter__ in self.resource_info()) File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 813, in self.saved_values = dict((name, get()) for name, get, restore File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 773, in get_cwd return os.getcwd() OSError: [Errno 2] No such file or directory test_mimetools test test_mimetools crashed -- : [Errno 2] No such file or directory Re-running test 'test_mimetools' in verbose mode test test_mimetools crashed -- : [Errno 2] No such file or directory Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 861, in runtest_inner with saved_test_environment(test, verbose, quiet) as environment: File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 814, in __enter__ in self.resource_info()) File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 813, in self.saved_values = dict((name, get()) for name, get, restore File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 773, in get_cwd return os.getcwd() OSError: [Errno 2] No such file or directory test_mimetypes test test_mimetypes crashed -- : [Errno 2] No such file or directory Re-running test 'test_mimetypes' in verbose mode test test_mimetypes crashed -- : [Errno 2] No such file or directory Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 861, in runtest_inner with saved_test_environment(test, verbose, quiet) as environment: File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 814, in __enter__ in self.resource_info()) File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 813, in self.saved_values = dict((name, get()) for name, get, restore File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 773, in get_cwd return os.getcwd() OSError: [Errno 2] No such file or directory test_minidom test test_minidom crashed -- : [Errno 2] No such file or directory Re-running test 'test_minidom' in verbose mode test test_minidom crashed -- : [Errno 2] No such file or directory Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 861, in runtest_inner with saved_test_environment(test, verbose, quiet) as environment: File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 814, in __enter__ in self.resource_info()) File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 813, in self.saved_values = dict((name, get()) for name, get, restore File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 773, in get_cwd return os.getcwd() OSError: [Errno 2] No such file or directory test_mmap test test_mmap crashed -- : [Errno 2] No such file or directory Re-running test 'test_mmap' in verbose mode test test_mmap crashed -- : [Errno 2] No such file or directory Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 861, in runtest_inner with saved_test_environment(test, verbose, quiet) as environment: File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 814, in __enter__ in self.resource_info()) File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 813, in self.saved_values = dict((name, get()) for name, get, restore File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 773, in get_cwd return os.getcwd() OSError: [Errno 2] No such file or directory test_module test test_module crashed -- : [Errno 2] No such file or directory Re-running test 'test_module' in verbose mode test test_module crashed -- : [Errno 2] No such file or directory Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 861, in runtest_inner with saved_test_environment(test, verbose, quiet) as environment: File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 814, in __enter__ in self.resource_info()) File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 813, in self.saved_values = dict((name, get()) for name, get, restore File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 773, in get_cwd return os.getcwd() OSError: [Errno 2] No such file or directory test_modulefinder test test_modulefinder crashed -- : [Errno 2] No such file or directory Re-running test 'test_modulefinder' in verbose mode test test_modulefinder crashed -- : [Errno 2] No such file or directory Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 861, in runtest_inner with saved_test_environment(test, verbose, quiet) as environment: File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 814, in __enter__ in self.resource_info()) File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 813, in self.saved_values = dict((name, get()) for name, get, restore File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 773, in get_cwd return os.getcwd() OSError: [Errno 2] No such file or directory test_multibytecodec test test_multibytecodec crashed -- : [Errno 2] No such file or directory Re-running test 'test_multibytecodec' in verbose mode test test_multibytecodec crashed -- : [Errno 2] No such file or directory Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 861, in runtest_inner with saved_test_environment(test, verbose, quiet) as environment: File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 814, in __enter__ in self.resource_info()) File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 813, in self.saved_values = dict((name, get()) for name, get, restore File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 773, in get_cwd return os.getcwd() OSError: [Errno 2] No such file or directory test_multibytecodec_support test test_multibytecodec_support crashed -- : [Errno 2] No such file or directory Re-running test 'test_multibytecodec_support' in verbose mode test test_multibytecodec_support crashed -- : [Errno 2] No such file or directory Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 861, in runtest_inner with saved_test_environment(test, verbose, quiet) as environment: File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 814, in __enter__ in self.resource_info()) File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 813, in self.saved_values = dict((name, get()) for name, get, restore File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 773, in get_cwd return os.getcwd() OSError: [Errno 2] No such file or directory test_multifile test test_multifile crashed -- : [Errno 2] No such file or directory Re-running test 'test_multifile' in verbose mode test test_multifile crashed -- : [Errno 2] No such file or directory Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 861, in runtest_inner with saved_test_environment(test, verbose, quiet) as environment: File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 814, in __enter__ in self.resource_info()) File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 813, in self.saved_values = dict((name, get()) for name, get, restore File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 773, in get_cwd return os.getcwd() OSError: [Errno 2] No such file or directory test_multiprocessing test test_multiprocessing crashed -- : [Errno 2] No such file or directory Re-running test 'test_multiprocessing' in verbose mode test test_multiprocessing crashed -- : [Errno 2] No such file or directory Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 861, in runtest_inner with saved_test_environment(test, verbose, quiet) as environment: File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 814, in __enter__ in self.resource_info()) File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 813, in self.saved_values = dict((name, get()) for name, get, restore File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 773, in get_cwd return os.getcwd() OSError: [Errno 2] No such file or directory test_mutants test test_mutants crashed -- : [Errno 2] No such file or directory Re-running test 'test_mutants' in verbose mode test test_mutants crashed -- : [Errno 2] No such file or directory Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 861, in runtest_inner with saved_test_environment(test, verbose, quiet) as environment: File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 814, in __enter__ in self.resource_info()) File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 813, in self.saved_values = dict((name, get()) for name, get, restore File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 773, in get_cwd return os.getcwd() OSError: [Errno 2] No such file or directory test_mutex test test_mutex crashed -- : [Errno 2] No such file or directory Re-running test 'test_mutex' in verbose mode test test_mutex crashed -- : [Errno 2] No such file or directory Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 861, in runtest_inner with saved_test_environment(test, verbose, quiet) as environment: File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 814, in __enter__ in self.resource_info()) File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 813, in self.saved_values = dict((name, get()) for name, get, restore File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 773, in get_cwd return os.getcwd() OSError: [Errno 2] No such file or directory test_netrc test test_netrc crashed -- : [Errno 2] No such file or directory Re-running test 'test_netrc' in verbose mode test test_netrc crashed -- : [Errno 2] No such file or directory Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 861, in runtest_inner with saved_test_environment(test, verbose, quiet) as environment: File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 814, in __enter__ in self.resource_info()) File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 813, in self.saved_values = dict((name, get()) for name, get, restore File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 773, in get_cwd return os.getcwd() OSError: [Errno 2] No such file or directory test_new test test_new crashed -- : [Errno 2] No such file or directory Re-running test 'test_new' in verbose mode test test_new crashed -- : [Errno 2] No such file or directory Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 861, in runtest_inner with saved_test_environment(test, verbose, quiet) as environment: File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 814, in __enter__ in self.resource_info()) File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 813, in self.saved_values = dict((name, get()) for name, get, restore File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 773, in get_cwd return os.getcwd() OSError: [Errno 2] No such file or directory test_nis test test_nis crashed -- : [Errno 2] No such file or directory Re-running test 'test_nis' in verbose mode test test_nis crashed -- : [Errno 2] No such file or directory Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 861, in runtest_inner with saved_test_environment(test, verbose, quiet) as environment: File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 814, in __enter__ in self.resource_info()) File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 813, in self.saved_values = dict((name, get()) for name, get, restore File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 773, in get_cwd return os.getcwd() OSError: [Errno 2] No such file or directory test_normalization test test_normalization crashed -- : [Errno 2] No such file or directory Re-running test 'test_normalization' in verbose mode test test_normalization crashed -- : [Errno 2] No such file or directory Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 861, in runtest_inner with saved_test_environment(test, verbose, quiet) as environment: File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 814, in __enter__ in self.resource_info()) File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 813, in self.saved_values = dict((name, get()) for name, get, restore File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 773, in get_cwd return os.getcwd() OSError: [Errno 2] No such file or directory test_ntpath test test_ntpath crashed -- : [Errno 2] No such file or directory Re-running test 'test_ntpath' in verbose mode test test_ntpath crashed -- : [Errno 2] No such file or directory Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 861, in runtest_inner with saved_test_environment(test, verbose, quiet) as environment: File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 814, in __enter__ in self.resource_info()) File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 813, in self.saved_values = dict((name, get()) for name, get, restore File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 773, in get_cwd return os.getcwd() OSError: [Errno 2] No such file or directory test_old_mailbox test test_old_mailbox crashed -- : [Errno 2] No such file or directory Re-running test 'test_old_mailbox' in verbose mode test test_old_mailbox crashed -- : [Errno 2] No such file or directory Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 861, in runtest_inner with saved_test_environment(test, verbose, quiet) as environment: File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 814, in __enter__ in self.resource_info()) File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 813, in self.saved_values = dict((name, get()) for name, get, restore File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 773, in get_cwd return os.getcwd() OSError: [Errno 2] No such file or directory test_openpty test test_openpty crashed -- : [Errno 2] No such file or directory Re-running test 'test_openpty' in verbose mode test test_openpty crashed -- : [Errno 2] No such file or directory Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 861, in runtest_inner with saved_test_environment(test, verbose, quiet) as environment: File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 814, in __enter__ in self.resource_info()) File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 813, in self.saved_values = dict((name, get()) for name, get, restore File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 773, in get_cwd return os.getcwd() OSError: [Errno 2] No such file or directory test_operator test test_operator crashed -- : [Errno 2] No such file or directory Re-running test 'test_operator' in verbose mode test test_operator crashed -- : [Errno 2] No such file or directory Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 861, in runtest_inner with saved_test_environment(test, verbose, quiet) as environment: File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 814, in __enter__ in self.resource_info()) File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 813, in self.saved_values = dict((name, get()) for name, get, restore File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 773, in get_cwd return os.getcwd() OSError: [Errno 2] No such file or directory test_optparse test test_optparse crashed -- : [Errno 2] No such file or directory Re-running test 'test_optparse' in verbose mode test test_optparse crashed -- : [Errno 2] No such file or directory Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 861, in runtest_inner with saved_test_environment(test, verbose, quiet) as environment: File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 814, in __enter__ in self.resource_info()) File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 813, in self.saved_values = dict((name, get()) for name, get, restore File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 773, in get_cwd return os.getcwd() OSError: [Errno 2] No such file or directory test_os test test_os crashed -- : [Errno 2] No such file or directory Re-running test 'test_os' in verbose mode test test_os crashed -- : [Errno 2] No such file or directory Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 861, in runtest_inner with saved_test_environment(test, verbose, quiet) as environment: File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 814, in __enter__ in self.resource_info()) File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 813, in self.saved_values = dict((name, get()) for name, get, restore File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 773, in get_cwd return os.getcwd() OSError: [Errno 2] No such file or directory test_parser test test_parser crashed -- : [Errno 2] No such file or directory Re-running test 'test_parser' in verbose mode test test_parser crashed -- : [Errno 2] No such file or directory Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 861, in runtest_inner with saved_test_environment(test, verbose, quiet) as environment: File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 814, in __enter__ in self.resource_info()) File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 813, in self.saved_values = dict((name, get()) for name, get, restore File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 773, in get_cwd return os.getcwd() OSError: [Errno 2] No such file or directory test_pdb test test_pdb crashed -- : [Errno 2] No such file or directory Re-running test 'test_pdb' in verbose mode test test_pdb crashed -- : [Errno 2] No such file or directory Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 861, in runtest_inner with saved_test_environment(test, verbose, quiet) as environment: File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 814, in __enter__ in self.resource_info()) File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 813, in self.saved_values = dict((name, get()) for name, get, restore File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 773, in get_cwd return os.getcwd() OSError: [Errno 2] No such file or directory test_peepholer test test_peepholer crashed -- : [Errno 2] No such file or directory Re-running test 'test_peepholer' in verbose mode test test_peepholer crashed -- : [Errno 2] No such file or directory Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 861, in runtest_inner with saved_test_environment(test, verbose, quiet) as environment: File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 814, in __enter__ in self.resource_info()) File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 813, in self.saved_values = dict((name, get()) for name, get, restore File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 773, in get_cwd return os.getcwd() OSError: [Errno 2] No such file or directory test_pep247 test test_pep247 crashed -- : [Errno 2] No such file or directory Re-running test 'test_pep247' in verbose mode test test_pep247 crashed -- : [Errno 2] No such file or directory Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 861, in runtest_inner with saved_test_environment(test, verbose, quiet) as environment: File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 814, in __enter__ in self.resource_info()) File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 813, in self.saved_values = dict((name, get()) for name, get, restore File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 773, in get_cwd return os.getcwd() OSError: [Errno 2] No such file or directory test_pep263 test test_pep263 crashed -- : [Errno 2] No such file or directory Re-running test 'test_pep263' in verbose mode test test_pep263 crashed -- : [Errno 2] No such file or directory Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 861, in runtest_inner with saved_test_environment(test, verbose, quiet) as environment: File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 814, in __enter__ in self.resource_info()) File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 813, in self.saved_values = dict((name, get()) for name, get, restore File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 773, in get_cwd return os.getcwd() OSError: [Errno 2] No such file or directory test_pep277 test test_pep277 crashed -- : [Errno 2] No such file or directory Re-running test 'test_pep277' in verbose mode test test_pep277 crashed -- : [Errno 2] No such file or directory Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 861, in runtest_inner with saved_test_environment(test, verbose, quiet) as environment: File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 814, in __enter__ in self.resource_info()) File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 813, in self.saved_values = dict((name, get()) for name, get, restore File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 773, in get_cwd return os.getcwd() OSError: [Errno 2] No such file or directory test_pep292 test test_pep292 crashed -- : [Errno 2] No such file or directory Re-running test 'test_pep292' in verbose mode test test_pep292 crashed -- : [Errno 2] No such file or directory Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 861, in runtest_inner with saved_test_environment(test, verbose, quiet) as environment: File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 814, in __enter__ in self.resource_info()) File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 813, in self.saved_values = dict((name, get()) for name, get, restore File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 773, in get_cwd return os.getcwd() OSError: [Errno 2] No such file or directory test_pep352 test test_pep352 crashed -- : [Errno 2] No such file or directory Re-running test 'test_pep352' in verbose mode test test_pep352 crashed -- : [Errno 2] No such file or directory Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 861, in runtest_inner with saved_test_environment(test, verbose, quiet) as environment: File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 814, in __enter__ in self.resource_info()) File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 813, in self.saved_values = dict((name, get()) for name, get, restore File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 773, in get_cwd return os.getcwd() OSError: [Errno 2] No such file or directory test_pickle test test_pickle crashed -- : [Errno 2] No such file or directory Re-running test 'test_pickle' in verbose mode test test_pickle crashed -- : [Errno 2] No such file or directory Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 861, in runtest_inner with saved_test_environment(test, verbose, quiet) as environment: File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 814, in __enter__ in self.resource_info()) File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 813, in self.saved_values = dict((name, get()) for name, get, restore File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 773, in get_cwd return os.getcwd() OSError: [Errno 2] No such file or directory test_pickletools test test_pickletools crashed -- : [Errno 2] No such file or directory Re-running test 'test_pickletools' in verbose mode test test_pickletools crashed -- : [Errno 2] No such file or directory Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 861, in runtest_inner with saved_test_environment(test, verbose, quiet) as environment: File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 814, in __enter__ in self.resource_info()) File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 813, in self.saved_values = dict((name, get()) for name, get, restore File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 773, in get_cwd return os.getcwd() OSError: [Errno 2] No such file or directory test_pipes test test_pipes crashed -- : [Errno 2] No such file or directory Re-running test 'test_pipes' in verbose mode test test_pipes crashed -- : [Errno 2] No such file or directory Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 861, in runtest_inner with saved_test_environment(test, verbose, quiet) as environment: File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 814, in __enter__ in self.resource_info()) File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 813, in self.saved_values = dict((name, get()) for name, get, restore File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 773, in get_cwd return os.getcwd() OSError: [Errno 2] No such file or directory test_pkg test test_pkg crashed -- : [Errno 2] No such file or directory Re-running test 'test_pkg' in verbose mode test test_pkg crashed -- : [Errno 2] No such file or directory Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 861, in runtest_inner with saved_test_environment(test, verbose, quiet) as environment: File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 814, in __enter__ in self.resource_info()) File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 813, in self.saved_values = dict((name, get()) for name, get, restore File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 773, in get_cwd return os.getcwd() OSError: [Errno 2] No such file or directory test_pkgimport test test_pkgimport crashed -- : [Errno 2] No such file or directory Re-running test 'test_pkgimport' in verbose mode test test_pkgimport crashed -- : [Errno 2] No such file or directory Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 861, in runtest_inner with saved_test_environment(test, verbose, quiet) as environment: File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 814, in __enter__ in self.resource_info()) File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 813, in self.saved_values = dict((name, get()) for name, get, restore File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 773, in get_cwd return os.getcwd() OSError: [Errno 2] No such file or directory test_pkgutil test test_pkgutil crashed -- : [Errno 2] No such file or directory Re-running test 'test_pkgutil' in verbose mode test test_pkgutil crashed -- : [Errno 2] No such file or directory Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 861, in runtest_inner with saved_test_environment(test, verbose, quiet) as environment: File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 814, in __enter__ in self.resource_info()) File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 813, in self.saved_values = dict((name, get()) for name, get, restore File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 773, in get_cwd return os.getcwd() OSError: [Errno 2] No such file or directory test_platform test test_platform crashed -- : [Errno 2] No such file or directory Re-running test 'test_platform' in verbose mode test test_platform crashed -- : [Errno 2] No such file or directory Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 861, in runtest_inner with saved_test_environment(test, verbose, quiet) as environment: File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 814, in __enter__ in self.resource_info()) File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 813, in self.saved_values = dict((name, get()) for name, get, restore File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 773, in get_cwd return os.getcwd() OSError: [Errno 2] No such file or directory test_plistlib test test_plistlib crashed -- : [Errno 2] No such file or directory Re-running test 'test_plistlib' in verbose mode test test_plistlib crashed -- : [Errno 2] No such file or directory Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 861, in runtest_inner with saved_test_environment(test, verbose, quiet) as environment: File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 814, in __enter__ in self.resource_info()) File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 813, in self.saved_values = dict((name, get()) for name, get, restore File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 773, in get_cwd return os.getcwd() OSError: [Errno 2] No such file or directory test_poll test test_poll crashed -- : [Errno 2] No such file or directory Re-running test 'test_poll' in verbose mode test test_poll crashed -- : [Errno 2] No such file or directory Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 861, in runtest_inner with saved_test_environment(test, verbose, quiet) as environment: File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 814, in __enter__ in self.resource_info()) File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 813, in self.saved_values = dict((name, get()) for name, get, restore File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 773, in get_cwd return os.getcwd() OSError: [Errno 2] No such file or directory test_popen test test_popen crashed -- : [Errno 2] No such file or directory Re-running test 'test_popen' in verbose mode test test_popen crashed -- : [Errno 2] No such file or directory Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 861, in runtest_inner with saved_test_environment(test, verbose, quiet) as environment: File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 814, in __enter__ in self.resource_info()) File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 813, in self.saved_values = dict((name, get()) for name, get, restore File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 773, in get_cwd return os.getcwd() OSError: [Errno 2] No such file or directory test_popen2 test test_popen2 crashed -- : [Errno 2] No such file or directory Re-running test 'test_popen2' in verbose mode test test_popen2 crashed -- : [Errno 2] No such file or directory Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 861, in runtest_inner with saved_test_environment(test, verbose, quiet) as environment: File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 814, in __enter__ in self.resource_info()) File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 813, in self.saved_values = dict((name, get()) for name, get, restore File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 773, in get_cwd return os.getcwd() OSError: [Errno 2] No such file or directory test_poplib test test_poplib crashed -- : [Errno 2] No such file or directory Re-running test 'test_poplib' in verbose mode test test_poplib crashed -- : [Errno 2] No such file or directory Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 861, in runtest_inner with saved_test_environment(test, verbose, quiet) as environment: File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 814, in __enter__ in self.resource_info()) File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 813, in self.saved_values = dict((name, get()) for name, get, restore File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 773, in get_cwd return os.getcwd() OSError: [Errno 2] No such file or directory test_posix test test_posix crashed -- : [Errno 2] No such file or directory Re-running test 'test_posix' in verbose mode test test_posix crashed -- : [Errno 2] No such file or directory Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 861, in runtest_inner with saved_test_environment(test, verbose, quiet) as environment: File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 814, in __enter__ in self.resource_info()) File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 813, in self.saved_values = dict((name, get()) for name, get, restore File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 773, in get_cwd return os.getcwd() OSError: [Errno 2] No such file or directory test_posixpath test test_posixpath crashed -- : [Errno 2] No such file or directory Re-running test 'test_posixpath' in verbose mode test test_posixpath crashed -- : [Errno 2] No such file or directory Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 861, in runtest_inner with saved_test_environment(test, verbose, quiet) as environment: File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 814, in __enter__ in self.resource_info()) File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 813, in self.saved_values = dict((name, get()) for name, get, restore File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 773, in get_cwd return os.getcwd() OSError: [Errno 2] No such file or directory test_pow test test_pow crashed -- : [Errno 2] No such file or directory Re-running test 'test_pow' in verbose mode test test_pow crashed -- : [Errno 2] No such file or directory Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 861, in runtest_inner with saved_test_environment(test, verbose, quiet) as environment: File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 814, in __enter__ in self.resource_info()) File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 813, in self.saved_values = dict((name, get()) for name, get, restore File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 773, in get_cwd return os.getcwd() OSError: [Errno 2] No such file or directory test_pprint test test_pprint crashed -- : [Errno 2] No such file or directory Re-running test 'test_pprint' in verbose mode test test_pprint crashed -- : [Errno 2] No such file or directory Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 861, in runtest_inner with saved_test_environment(test, verbose, quiet) as environment: File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 814, in __enter__ in self.resource_info()) File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 813, in self.saved_values = dict((name, get()) for name, get, restore File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 773, in get_cwd return os.getcwd() OSError: [Errno 2] No such file or directory test_print test test_print crashed -- : [Errno 2] No such file or directory Re-running test 'test_print' in verbose mode test test_print crashed -- : [Errno 2] No such file or directory Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 861, in runtest_inner with saved_test_environment(test, verbose, quiet) as environment: File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 814, in __enter__ in self.resource_info()) File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 813, in self.saved_values = dict((name, get()) for name, get, restore File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 773, in get_cwd return os.getcwd() OSError: [Errno 2] No such file or directory test_profile test test_profile crashed -- : [Errno 2] No such file or directory Re-running test 'test_profile' in verbose mode test test_profile crashed -- : [Errno 2] No such file or directory Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 861, in runtest_inner with saved_test_environment(test, verbose, quiet) as environment: File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 814, in __enter__ in self.resource_info()) File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 813, in self.saved_values = dict((name, get()) for name, get, restore File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 773, in get_cwd return os.getcwd() OSError: [Errno 2] No such file or directory test_profilehooks test test_profilehooks crashed -- : [Errno 2] No such file or directory Re-running test 'test_profilehooks' in verbose mode test test_profilehooks crashed -- : [Errno 2] No such file or directory Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 861, in runtest_inner with saved_test_environment(test, verbose, quiet) as environment: File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 814, in __enter__ in self.resource_info()) File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 813, in self.saved_values = dict((name, get()) for name, get, restore File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 773, in get_cwd return os.getcwd() OSError: [Errno 2] No such file or directory test_property test test_property crashed -- : [Errno 2] No such file or directory Re-running test 'test_property' in verbose mode test test_property crashed -- : [Errno 2] No such file or directory Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 861, in runtest_inner with saved_test_environment(test, verbose, quiet) as environment: File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 814, in __enter__ in self.resource_info()) File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 813, in self.saved_values = dict((name, get()) for name, get, restore File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 773, in get_cwd return os.getcwd() OSError: [Errno 2] No such file or directory test_pstats test test_pstats crashed -- : [Errno 2] No such file or directory Re-running test 'test_pstats' in verbose mode test test_pstats crashed -- : [Errno 2] No such file or directory Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 861, in runtest_inner with saved_test_environment(test, verbose, quiet) as environment: File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 814, in __enter__ in self.resource_info()) File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 813, in self.saved_values = dict((name, get()) for name, get, restore File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 773, in get_cwd return os.getcwd() OSError: [Errno 2] No such file or directory test_pty test test_pty crashed -- : [Errno 2] No such file or directory Re-running test 'test_pty' in verbose mode test test_pty crashed -- : [Errno 2] No such file or directory Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 861, in runtest_inner with saved_test_environment(test, verbose, quiet) as environment: File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 814, in __enter__ in self.resource_info()) File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 813, in self.saved_values = dict((name, get()) for name, get, restore File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 773, in get_cwd return os.getcwd() OSError: [Errno 2] No such file or directory test_pwd test test_pwd crashed -- : [Errno 2] No such file or directory Re-running test 'test_pwd' in verbose mode test test_pwd crashed -- : [Errno 2] No such file or directory Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 861, in runtest_inner with saved_test_environment(test, verbose, quiet) as environment: File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 814, in __enter__ in self.resource_info()) File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 813, in self.saved_values = dict((name, get()) for name, get, restore File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 773, in get_cwd return os.getcwd() OSError: [Errno 2] No such file or directory test_py3kwarn test test_py3kwarn crashed -- : [Errno 2] No such file or directory Re-running test 'test_py3kwarn' in verbose mode test test_py3kwarn crashed -- : [Errno 2] No such file or directory Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 861, in runtest_inner with saved_test_environment(test, verbose, quiet) as environment: File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 814, in __enter__ in self.resource_info()) File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 813, in self.saved_values = dict((name, get()) for name, get, restore File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 773, in get_cwd return os.getcwd() OSError: [Errno 2] No such file or directory test_pyclbr test test_pyclbr crashed -- : [Errno 2] No such file or directory Re-running test 'test_pyclbr' in verbose mode test test_pyclbr crashed -- : [Errno 2] No such file or directory Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 861, in runtest_inner with saved_test_environment(test, verbose, quiet) as environment: File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 814, in __enter__ in self.resource_info()) File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 813, in self.saved_values = dict((name, get()) for name, get, restore File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 773, in get_cwd return os.getcwd() OSError: [Errno 2] No such file or directory test_pydoc test test_pydoc crashed -- : [Errno 2] No such file or directory Re-running test 'test_pydoc' in verbose mode test test_pydoc crashed -- : [Errno 2] No such file or directory Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 861, in runtest_inner with saved_test_environment(test, verbose, quiet) as environment: File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 814, in __enter__ in self.resource_info()) File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 813, in self.saved_values = dict((name, get()) for name, get, restore File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 773, in get_cwd return os.getcwd() OSError: [Errno 2] No such file or directory test_pyexpat test test_pyexpat crashed -- : [Errno 2] No such file or directory Re-running test 'test_pyexpat' in verbose mode test test_pyexpat crashed -- : [Errno 2] No such file or directory Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 861, in runtest_inner with saved_test_environment(test, verbose, quiet) as environment: File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 814, in __enter__ in self.resource_info()) File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 813, in self.saved_values = dict((name, get()) for name, get, restore File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 773, in get_cwd return os.getcwd() OSError: [Errno 2] No such file or directory test_queue test test_queue crashed -- : [Errno 2] No such file or directory Re-running test 'test_queue' in verbose mode test test_queue crashed -- : [Errno 2] No such file or directory Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 861, in runtest_inner with saved_test_environment(test, verbose, quiet) as environment: File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 814, in __enter__ in self.resource_info()) File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 813, in self.saved_values = dict((name, get()) for name, get, restore File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 773, in get_cwd return os.getcwd() OSError: [Errno 2] No such file or directory test_quopri test test_quopri crashed -- : [Errno 2] No such file or directory Re-running test 'test_quopri' in verbose mode test test_quopri crashed -- : [Errno 2] No such file or directory Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 861, in runtest_inner with saved_test_environment(test, verbose, quiet) as environment: File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 814, in __enter__ in self.resource_info()) File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 813, in self.saved_values = dict((name, get()) for name, get, restore File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 773, in get_cwd return os.getcwd() OSError: [Errno 2] No such file or directory test_random test test_random crashed -- : [Errno 2] No such file or directory Re-running test 'test_random' in verbose mode test test_random crashed -- : [Errno 2] No such file or directory Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 861, in runtest_inner with saved_test_environment(test, verbose, quiet) as environment: File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 814, in __enter__ in self.resource_info()) File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 813, in self.saved_values = dict((name, get()) for name, get, restore File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 773, in get_cwd return os.getcwd() OSError: [Errno 2] No such file or directory test_re test test_re crashed -- : [Errno 2] No such file or directory Re-running test 'test_re' in verbose mode test test_re crashed -- : [Errno 2] No such file or directory Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 861, in runtest_inner with saved_test_environment(test, verbose, quiet) as environment: File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 814, in __enter__ in self.resource_info()) File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 813, in self.saved_values = dict((name, get()) for name, get, restore File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 773, in get_cwd return os.getcwd() OSError: [Errno 2] No such file or directory test_readline test test_readline crashed -- : [Errno 2] No such file or directory Re-running test 'test_readline' in verbose mode test test_readline crashed -- : [Errno 2] No such file or directory Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 861, in runtest_inner with saved_test_environment(test, verbose, quiet) as environment: File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 814, in __enter__ in self.resource_info()) File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 813, in self.saved_values = dict((name, get()) for name, get, restore File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 773, in get_cwd return os.getcwd() OSError: [Errno 2] No such file or directory test_repr test test_repr crashed -- : [Errno 2] No such file or directory Re-running test 'test_repr' in verbose mode test test_repr crashed -- : [Errno 2] No such file or directory Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 861, in runtest_inner with saved_test_environment(test, verbose, quiet) as environment: File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 814, in __enter__ in self.resource_info()) File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 813, in self.saved_values = dict((name, get()) for name, get, restore File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 773, in get_cwd return os.getcwd() OSError: [Errno 2] No such file or directory test_resource test test_resource crashed -- : [Errno 2] No such file or directory Re-running test 'test_resource' in verbose mode test test_resource crashed -- : [Errno 2] No such file or directory Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 861, in runtest_inner with saved_test_environment(test, verbose, quiet) as environment: File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 814, in __enter__ in self.resource_info()) File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 813, in self.saved_values = dict((name, get()) for name, get, restore File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 773, in get_cwd return os.getcwd() OSError: [Errno 2] No such file or directory test_rfc822 test test_rfc822 crashed -- : [Errno 2] No such file or directory Re-running test 'test_rfc822' in verbose mode test test_rfc822 crashed -- : [Errno 2] No such file or directory Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 861, in runtest_inner with saved_test_environment(test, verbose, quiet) as environment: File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 814, in __enter__ in self.resource_info()) File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 813, in self.saved_values = dict((name, get()) for name, get, restore File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 773, in get_cwd return os.getcwd() OSError: [Errno 2] No such file or directory test_richcmp test test_richcmp crashed -- : [Errno 2] No such file or directory Re-running test 'test_richcmp' in verbose mode test test_richcmp crashed -- : [Errno 2] No such file or directory Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 861, in runtest_inner with saved_test_environment(test, verbose, quiet) as environment: File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 814, in __enter__ in self.resource_info()) File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 813, in self.saved_values = dict((name, get()) for name, get, restore File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 773, in get_cwd return os.getcwd() OSError: [Errno 2] No such file or directory test_robotparser test test_robotparser crashed -- : [Errno 2] No such file or directory Re-running test 'test_robotparser' in verbose mode test test_robotparser crashed -- : [Errno 2] No such file or directory Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 861, in runtest_inner with saved_test_environment(test, verbose, quiet) as environment: File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 814, in __enter__ in self.resource_info()) File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 813, in self.saved_values = dict((name, get()) for name, get, restore File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 773, in get_cwd return os.getcwd() OSError: [Errno 2] No such file or directory test_runpy test test_runpy crashed -- : [Errno 2] No such file or directory Re-running test 'test_runpy' in verbose mode test test_runpy crashed -- : [Errno 2] No such file or directory Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 861, in runtest_inner with saved_test_environment(test, verbose, quiet) as environment: File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 814, in __enter__ in self.resource_info()) File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 813, in self.saved_values = dict((name, get()) for name, get, restore File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 773, in get_cwd return os.getcwd() OSError: [Errno 2] No such file or directory test_sax test test_sax crashed -- : [Errno 2] No such file or directory Re-running test 'test_sax' in verbose mode test test_sax crashed -- : [Errno 2] No such file or directory Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 861, in runtest_inner with saved_test_environment(test, verbose, quiet) as environment: File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 814, in __enter__ in self.resource_info()) File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 813, in self.saved_values = dict((name, get()) for name, get, restore File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 773, in get_cwd return os.getcwd() OSError: [Errno 2] No such file or directory test_scope test test_scope crashed -- : [Errno 2] No such file or directory Re-running test 'test_scope' in verbose mode test test_scope crashed -- : [Errno 2] No such file or directory Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 861, in runtest_inner with saved_test_environment(test, verbose, quiet) as environment: File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 814, in __enter__ in self.resource_info()) File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 813, in self.saved_values = dict((name, get()) for name, get, restore File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 773, in get_cwd return os.getcwd() OSError: [Errno 2] No such file or directory test_scriptpackages test test_scriptpackages crashed -- : [Errno 2] No such file or directory Re-running test 'test_scriptpackages' in verbose mode test test_scriptpackages crashed -- : [Errno 2] No such file or directory Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 861, in runtest_inner with saved_test_environment(test, verbose, quiet) as environment: File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 814, in __enter__ in self.resource_info()) File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 813, in self.saved_values = dict((name, get()) for name, get, restore File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 773, in get_cwd return os.getcwd() OSError: [Errno 2] No such file or directory test_select test test_select crashed -- : [Errno 2] No such file or directory Re-running test 'test_select' in verbose mode test test_select crashed -- : [Errno 2] No such file or directory Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 861, in runtest_inner with saved_test_environment(test, verbose, quiet) as environment: File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 814, in __enter__ in self.resource_info()) File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 813, in self.saved_values = dict((name, get()) for name, get, restore File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 773, in get_cwd return os.getcwd() OSError: [Errno 2] No such file or directory test_set test test_set crashed -- : [Errno 2] No such file or directory Re-running test 'test_set' in verbose mode test test_set crashed -- : [Errno 2] No such file or directory Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 861, in runtest_inner with saved_test_environment(test, verbose, quiet) as environment: File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 814, in __enter__ in self.resource_info()) File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 813, in self.saved_values = dict((name, get()) for name, get, restore File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 773, in get_cwd return os.getcwd() OSError: [Errno 2] No such file or directory test_setcomps test test_setcomps crashed -- : [Errno 2] No such file or directory Re-running test 'test_setcomps' in verbose mode test test_setcomps crashed -- : [Errno 2] No such file or directory Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 861, in runtest_inner with saved_test_environment(test, verbose, quiet) as environment: File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 814, in __enter__ in self.resource_info()) File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 813, in self.saved_values = dict((name, get()) for name, get, restore File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 773, in get_cwd return os.getcwd() OSError: [Errno 2] No such file or directory test_sets test test_sets crashed -- : [Errno 2] No such file or directory Re-running test 'test_sets' in verbose mode test test_sets crashed -- : [Errno 2] No such file or directory Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 861, in runtest_inner with saved_test_environment(test, verbose, quiet) as environment: File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 814, in __enter__ in self.resource_info()) File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 813, in self.saved_values = dict((name, get()) for name, get, restore File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 773, in get_cwd return os.getcwd() OSError: [Errno 2] No such file or directory test_sgmllib test test_sgmllib crashed -- : [Errno 2] No such file or directory Re-running test 'test_sgmllib' in verbose mode test test_sgmllib crashed -- : [Errno 2] No such file or directory Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 861, in runtest_inner with saved_test_environment(test, verbose, quiet) as environment: File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 814, in __enter__ in self.resource_info()) File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 813, in self.saved_values = dict((name, get()) for name, get, restore File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 773, in get_cwd return os.getcwd() OSError: [Errno 2] No such file or directory test_sha test test_sha crashed -- : [Errno 2] No such file or directory Re-running test 'test_sha' in verbose mode test test_sha crashed -- : [Errno 2] No such file or directory Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 861, in runtest_inner with saved_test_environment(test, verbose, quiet) as environment: File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 814, in __enter__ in self.resource_info()) File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 813, in self.saved_values = dict((name, get()) for name, get, restore File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 773, in get_cwd return os.getcwd() OSError: [Errno 2] No such file or directory test_shelve test test_shelve crashed -- : [Errno 2] No such file or directory Re-running test 'test_shelve' in verbose mode test test_shelve crashed -- : [Errno 2] No such file or directory Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 861, in runtest_inner with saved_test_environment(test, verbose, quiet) as environment: File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 814, in __enter__ in self.resource_info()) File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 813, in self.saved_values = dict((name, get()) for name, get, restore File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 773, in get_cwd return os.getcwd() OSError: [Errno 2] No such file or directory test_shlex test test_shlex crashed -- : [Errno 2] No such file or directory Re-running test 'test_shlex' in verbose mode test test_shlex crashed -- : [Errno 2] No such file or directory Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 861, in runtest_inner with saved_test_environment(test, verbose, quiet) as environment: File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 814, in __enter__ in self.resource_info()) File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 813, in self.saved_values = dict((name, get()) for name, get, restore File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 773, in get_cwd return os.getcwd() OSError: [Errno 2] No such file or directory test_shutil test test_shutil crashed -- : [Errno 2] No such file or directory Re-running test 'test_shutil' in verbose mode test test_shutil crashed -- : [Errno 2] No such file or directory Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 861, in runtest_inner with saved_test_environment(test, verbose, quiet) as environment: File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 814, in __enter__ in self.resource_info()) File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 813, in self.saved_values = dict((name, get()) for name, get, restore File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 773, in get_cwd return os.getcwd() OSError: [Errno 2] No such file or directory test_signal test test_signal crashed -- : [Errno 2] No such file or directory Re-running test 'test_signal' in verbose mode test test_signal crashed -- : [Errno 2] No such file or directory Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 861, in runtest_inner with saved_test_environment(test, verbose, quiet) as environment: File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 814, in __enter__ in self.resource_info()) File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 813, in self.saved_values = dict((name, get()) for name, get, restore File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 773, in get_cwd return os.getcwd() OSError: [Errno 2] No such file or directory test_site test test_site crashed -- : [Errno 2] No such file or directory Re-running test 'test_site' in verbose mode test test_site crashed -- : [Errno 2] No such file or directory Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 861, in runtest_inner with saved_test_environment(test, verbose, quiet) as environment: File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 814, in __enter__ in self.resource_info()) File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 813, in self.saved_values = dict((name, get()) for name, get, restore File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 773, in get_cwd return os.getcwd() OSError: [Errno 2] No such file or directory test_slice test test_slice crashed -- : [Errno 2] No such file or directory Re-running test 'test_slice' in verbose mode test test_slice crashed -- : [Errno 2] No such file or directory Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 861, in runtest_inner with saved_test_environment(test, verbose, quiet) as environment: File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 814, in __enter__ in self.resource_info()) File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 813, in self.saved_values = dict((name, get()) for name, get, restore File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 773, in get_cwd return os.getcwd() OSError: [Errno 2] No such file or directory test_smtplib test test_smtplib crashed -- : [Errno 2] No such file or directory Re-running test 'test_smtplib' in verbose mode test test_smtplib crashed -- : [Errno 2] No such file or directory Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 861, in runtest_inner with saved_test_environment(test, verbose, quiet) as environment: File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 814, in __enter__ in self.resource_info()) File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 813, in self.saved_values = dict((name, get()) for name, get, restore File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 773, in get_cwd return os.getcwd() OSError: [Errno 2] No such file or directory test_smtpnet test test_smtpnet crashed -- : [Errno 2] No such file or directory Re-running test 'test_smtpnet' in verbose mode test test_smtpnet crashed -- : [Errno 2] No such file or directory Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 861, in runtest_inner with saved_test_environment(test, verbose, quiet) as environment: File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 814, in __enter__ in self.resource_info()) File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 813, in self.saved_values = dict((name, get()) for name, get, restore File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 773, in get_cwd return os.getcwd() OSError: [Errno 2] No such file or directory test_socket test test_socket crashed -- : [Errno 2] No such file or directory Re-running test 'test_socket' in verbose mode test test_socket crashed -- : [Errno 2] No such file or directory Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 861, in runtest_inner with saved_test_environment(test, verbose, quiet) as environment: File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 814, in __enter__ in self.resource_info()) File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 813, in self.saved_values = dict((name, get()) for name, get, restore File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 773, in get_cwd return os.getcwd() OSError: [Errno 2] No such file or directory test_socketserver test test_socketserver crashed -- : [Errno 2] No such file or directory Re-running test 'test_socketserver' in verbose mode test test_socketserver crashed -- : [Errno 2] No such file or directory Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 861, in runtest_inner with saved_test_environment(test, verbose, quiet) as environment: File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 814, in __enter__ in self.resource_info()) File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 813, in self.saved_values = dict((name, get()) for name, get, restore File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 773, in get_cwd return os.getcwd() OSError: [Errno 2] No such file or directory test_softspace test test_softspace crashed -- : [Errno 2] No such file or directory Re-running test 'test_softspace' in verbose mode test test_softspace crashed -- : [Errno 2] No such file or directory Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 861, in runtest_inner with saved_test_environment(test, verbose, quiet) as environment: File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 814, in __enter__ in self.resource_info()) File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 813, in self.saved_values = dict((name, get()) for name, get, restore File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 773, in get_cwd return os.getcwd() OSError: [Errno 2] No such file or directory test_sort test test_sort crashed -- : [Errno 2] No such file or directory Re-running test 'test_sort' in verbose mode test test_sort crashed -- : [Errno 2] No such file or directory Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 861, in runtest_inner with saved_test_environment(test, verbose, quiet) as environment: File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 814, in __enter__ in self.resource_info()) File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 813, in self.saved_values = dict((name, get()) for name, get, restore File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 773, in get_cwd return os.getcwd() OSError: [Errno 2] No such file or directory test_sqlite test test_sqlite crashed -- : [Errno 2] No such file or directory Re-running test 'test_sqlite' in verbose mode test test_sqlite crashed -- : [Errno 2] No such file or directory Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 861, in runtest_inner with saved_test_environment(test, verbose, quiet) as environment: File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 814, in __enter__ in self.resource_info()) File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 813, in self.saved_values = dict((name, get()) for name, get, restore File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 773, in get_cwd return os.getcwd() OSError: [Errno 2] No such file or directory test_ssl test test_ssl crashed -- : [Errno 2] No such file or directory Re-running test 'test_ssl' in verbose mode test test_ssl crashed -- : [Errno 2] No such file or directory Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 861, in runtest_inner with saved_test_environment(test, verbose, quiet) as environment: File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 814, in __enter__ in self.resource_info()) File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 813, in self.saved_values = dict((name, get()) for name, get, restore File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 773, in get_cwd return os.getcwd() OSError: [Errno 2] No such file or directory test_startfile test test_startfile crashed -- : [Errno 2] No such file or directory Re-running test 'test_startfile' in verbose mode test test_startfile crashed -- : [Errno 2] No such file or directory Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 861, in runtest_inner with saved_test_environment(test, verbose, quiet) as environment: File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 814, in __enter__ in self.resource_info()) File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 813, in self.saved_values = dict((name, get()) for name, get, restore File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 773, in get_cwd return os.getcwd() OSError: [Errno 2] No such file or directory test_str test test_str crashed -- : [Errno 2] No such file or directory Re-running test 'test_str' in verbose mode test test_str crashed -- : [Errno 2] No such file or directory Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 861, in runtest_inner with saved_test_environment(test, verbose, quiet) as environment: File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 814, in __enter__ in self.resource_info()) File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 813, in self.saved_values = dict((name, get()) for name, get, restore File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 773, in get_cwd return os.getcwd() OSError: [Errno 2] No such file or directory test_strftime test test_strftime crashed -- : [Errno 2] No such file or directory Re-running test 'test_strftime' in verbose mode test test_strftime crashed -- : [Errno 2] No such file or directory Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 861, in runtest_inner with saved_test_environment(test, verbose, quiet) as environment: File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 814, in __enter__ in self.resource_info()) File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 813, in self.saved_values = dict((name, get()) for name, get, restore File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 773, in get_cwd return os.getcwd() OSError: [Errno 2] No such file or directory test_string test test_string crashed -- : [Errno 2] No such file or directory Re-running test 'test_string' in verbose mode test test_string crashed -- : [Errno 2] No such file or directory Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 861, in runtest_inner with saved_test_environment(test, verbose, quiet) as environment: File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 814, in __enter__ in self.resource_info()) File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 813, in self.saved_values = dict((name, get()) for name, get, restore File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 773, in get_cwd return os.getcwd() OSError: [Errno 2] No such file or directory test_stringprep test test_stringprep crashed -- : [Errno 2] No such file or directory Re-running test 'test_stringprep' in verbose mode test test_stringprep crashed -- : [Errno 2] No such file or directory Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 861, in runtest_inner with saved_test_environment(test, verbose, quiet) as environment: File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 814, in __enter__ in self.resource_info()) File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 813, in self.saved_values = dict((name, get()) for name, get, restore File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 773, in get_cwd return os.getcwd() OSError: [Errno 2] No such file or directory test_strop test test_strop crashed -- : [Errno 2] No such file or directory Re-running test 'test_strop' in verbose mode test test_strop crashed -- : [Errno 2] No such file or directory Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 861, in runtest_inner with saved_test_environment(test, verbose, quiet) as environment: File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 814, in __enter__ in self.resource_info()) File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 813, in self.saved_values = dict((name, get()) for name, get, restore File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 773, in get_cwd return os.getcwd() OSError: [Errno 2] No such file or directory test_strptime test test_strptime crashed -- : [Errno 2] No such file or directory Re-running test 'test_strptime' in verbose mode test test_strptime crashed -- : [Errno 2] No such file or directory Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 861, in runtest_inner with saved_test_environment(test, verbose, quiet) as environment: File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 814, in __enter__ in self.resource_info()) File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 813, in self.saved_values = dict((name, get()) for name, get, restore File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 773, in get_cwd return os.getcwd() OSError: [Errno 2] No such file or directory test_strtod test test_strtod crashed -- : [Errno 2] No such file or directory Re-running test 'test_strtod' in verbose mode test test_strtod crashed -- : [Errno 2] No such file or directory Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 861, in runtest_inner with saved_test_environment(test, verbose, quiet) as environment: File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 814, in __enter__ in self.resource_info()) File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 813, in self.saved_values = dict((name, get()) for name, get, restore File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 773, in get_cwd return os.getcwd() OSError: [Errno 2] No such file or directory test_struct test test_struct crashed -- : [Errno 2] No such file or directory Re-running test 'test_struct' in verbose mode test test_struct crashed -- : [Errno 2] No such file or directory Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 861, in runtest_inner with saved_test_environment(test, verbose, quiet) as environment: File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 814, in __enter__ in self.resource_info()) File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 813, in self.saved_values = dict((name, get()) for name, get, restore File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 773, in get_cwd return os.getcwd() OSError: [Errno 2] No such file or directory test_structmembers test test_structmembers crashed -- : [Errno 2] No such file or directory Re-running test 'test_structmembers' in verbose mode test test_structmembers crashed -- : [Errno 2] No such file or directory Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 861, in runtest_inner with saved_test_environment(test, verbose, quiet) as environment: File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 814, in __enter__ in self.resource_info()) File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 813, in self.saved_values = dict((name, get()) for name, get, restore File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 773, in get_cwd return os.getcwd() OSError: [Errno 2] No such file or directory test_structseq test test_structseq crashed -- : [Errno 2] No such file or directory Re-running test 'test_structseq' in verbose mode test test_structseq crashed -- : [Errno 2] No such file or directory Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 861, in runtest_inner with saved_test_environment(test, verbose, quiet) as environment: File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 814, in __enter__ in self.resource_info()) File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 813, in self.saved_values = dict((name, get()) for name, get, restore File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 773, in get_cwd return os.getcwd() OSError: [Errno 2] No such file or directory test_subprocess test test_subprocess crashed -- : [Errno 2] No such file or directory Re-running test 'test_subprocess' in verbose mode test test_subprocess crashed -- : [Errno 2] No such file or directory Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 861, in runtest_inner with saved_test_environment(test, verbose, quiet) as environment: File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 814, in __enter__ in self.resource_info()) File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 813, in self.saved_values = dict((name, get()) for name, get, restore File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 773, in get_cwd return os.getcwd() OSError: [Errno 2] No such file or directory test_sunaudiodev test test_sunaudiodev crashed -- : [Errno 2] No such file or directory Re-running test 'test_sunaudiodev' in verbose mode test test_sunaudiodev crashed -- : [Errno 2] No such file or directory Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 861, in runtest_inner with saved_test_environment(test, verbose, quiet) as environment: File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 814, in __enter__ in self.resource_info()) File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 813, in self.saved_values = dict((name, get()) for name, get, restore File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 773, in get_cwd return os.getcwd() OSError: [Errno 2] No such file or directory test_sundry test test_sundry crashed -- : [Errno 2] No such file or directory Re-running test 'test_sundry' in verbose mode test test_sundry crashed -- : [Errno 2] No such file or directory Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 861, in runtest_inner with saved_test_environment(test, verbose, quiet) as environment: File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 814, in __enter__ in self.resource_info()) File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 813, in self.saved_values = dict((name, get()) for name, get, restore File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 773, in get_cwd return os.getcwd() OSError: [Errno 2] No such file or directory test_symtable test test_symtable crashed -- : [Errno 2] No such file or directory Re-running test 'test_symtable' in verbose mode test test_symtable crashed -- : [Errno 2] No such file or directory Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 861, in runtest_inner with saved_test_environment(test, verbose, quiet) as environment: File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 814, in __enter__ in self.resource_info()) File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 813, in self.saved_values = dict((name, get()) for name, get, restore File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 773, in get_cwd return os.getcwd() OSError: [Errno 2] No such file or directory test_syntax test test_syntax crashed -- : [Errno 2] No such file or directory Re-running test 'test_syntax' in verbose mode test test_syntax crashed -- : [Errno 2] No such file or directory Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 861, in runtest_inner with saved_test_environment(test, verbose, quiet) as environment: File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 814, in __enter__ in self.resource_info()) File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 813, in self.saved_values = dict((name, get()) for name, get, restore File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 773, in get_cwd return os.getcwd() OSError: [Errno 2] No such file or directory test_sys test test_sys crashed -- : [Errno 2] No such file or directory Re-running test 'test_sys' in verbose mode test test_sys crashed -- : [Errno 2] No such file or directory Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 861, in runtest_inner with saved_test_environment(test, verbose, quiet) as environment: File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 814, in __enter__ in self.resource_info()) File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 813, in self.saved_values = dict((name, get()) for name, get, restore File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 773, in get_cwd return os.getcwd() OSError: [Errno 2] No such file or directory test_sysconfig test test_sysconfig crashed -- : [Errno 2] No such file or directory Re-running test 'test_sysconfig' in verbose mode test test_sysconfig crashed -- : [Errno 2] No such file or directory Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 861, in runtest_inner with saved_test_environment(test, verbose, quiet) as environment: File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 814, in __enter__ in self.resource_info()) File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 813, in self.saved_values = dict((name, get()) for name, get, restore File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 773, in get_cwd return os.getcwd() OSError: [Errno 2] No such file or directory test_tarfile test test_tarfile crashed -- : [Errno 2] No such file or directory Re-running test 'test_tarfile' in verbose mode test test_tarfile crashed -- : [Errno 2] No such file or directory Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 861, in runtest_inner with saved_test_environment(test, verbose, quiet) as environment: File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 814, in __enter__ in self.resource_info()) File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 813, in self.saved_values = dict((name, get()) for name, get, restore File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 773, in get_cwd return os.getcwd() OSError: [Errno 2] No such file or directory test_tcl test test_tcl crashed -- : [Errno 2] No such file or directory Re-running test 'test_tcl' in verbose mode test test_tcl crashed -- : [Errno 2] No such file or directory Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 861, in runtest_inner with saved_test_environment(test, verbose, quiet) as environment: File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 814, in __enter__ in self.resource_info()) File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 813, in self.saved_values = dict((name, get()) for name, get, restore File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 773, in get_cwd return os.getcwd() OSError: [Errno 2] No such file or directory test_telnetlib test test_telnetlib crashed -- : [Errno 2] No such file or directory Re-running test 'test_telnetlib' in verbose mode test test_telnetlib crashed -- : [Errno 2] No such file or directory Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 861, in runtest_inner with saved_test_environment(test, verbose, quiet) as environment: File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 814, in __enter__ in self.resource_info()) File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 813, in self.saved_values = dict((name, get()) for name, get, restore File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 773, in get_cwd return os.getcwd() OSError: [Errno 2] No such file or directory test_tempfile test test_tempfile crashed -- : [Errno 2] No such file or directory Re-running test 'test_tempfile' in verbose mode test test_tempfile crashed -- : [Errno 2] No such file or directory Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 861, in runtest_inner with saved_test_environment(test, verbose, quiet) as environment: File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 814, in __enter__ in self.resource_info()) File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 813, in self.saved_values = dict((name, get()) for name, get, restore File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 773, in get_cwd return os.getcwd() OSError: [Errno 2] No such file or directory test_textwrap test test_textwrap crashed -- : [Errno 2] No such file or directory Re-running test 'test_textwrap' in verbose mode test test_textwrap crashed -- : [Errno 2] No such file or directory Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 861, in runtest_inner with saved_test_environment(test, verbose, quiet) as environment: File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 814, in __enter__ in self.resource_info()) File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 813, in self.saved_values = dict((name, get()) for name, get, restore File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 773, in get_cwd return os.getcwd() OSError: [Errno 2] No such file or directory test_thread test test_thread crashed -- : [Errno 2] No such file or directory Re-running test 'test_thread' in verbose mode test test_thread crashed -- : [Errno 2] No such file or directory Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 861, in runtest_inner with saved_test_environment(test, verbose, quiet) as environment: File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 814, in __enter__ in self.resource_info()) File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 813, in self.saved_values = dict((name, get()) for name, get, restore File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 773, in get_cwd return os.getcwd() OSError: [Errno 2] No such file or directory test_threaded_import test test_threaded_import crashed -- : [Errno 2] No such file or directory Re-running test 'test_threaded_import' in verbose mode test test_threaded_import crashed -- : [Errno 2] No such file or directory Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 861, in runtest_inner with saved_test_environment(test, verbose, quiet) as environment: File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 814, in __enter__ in self.resource_info()) File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 813, in self.saved_values = dict((name, get()) for name, get, restore File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 773, in get_cwd return os.getcwd() OSError: [Errno 2] No such file or directory test_threadedtempfile test test_threadedtempfile crashed -- : [Errno 2] No such file or directory Re-running test 'test_threadedtempfile' in verbose mode test test_threadedtempfile crashed -- : [Errno 2] No such file or directory Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 861, in runtest_inner with saved_test_environment(test, verbose, quiet) as environment: File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 814, in __enter__ in self.resource_info()) File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 813, in self.saved_values = dict((name, get()) for name, get, restore File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 773, in get_cwd return os.getcwd() OSError: [Errno 2] No such file or directory test_threading test test_threading crashed -- : [Errno 2] No such file or directory Re-running test 'test_threading' in verbose mode test test_threading crashed -- : [Errno 2] No such file or directory Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 861, in runtest_inner with saved_test_environment(test, verbose, quiet) as environment: File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 814, in __enter__ in self.resource_info()) File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 813, in self.saved_values = dict((name, get()) for name, get, restore File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 773, in get_cwd return os.getcwd() OSError: [Errno 2] No such file or directory test_threading_local test test_threading_local crashed -- : [Errno 2] No such file or directory Re-running test 'test_threading_local' in verbose mode test test_threading_local crashed -- : [Errno 2] No such file or directory Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 861, in runtest_inner with saved_test_environment(test, verbose, quiet) as environment: File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 814, in __enter__ in self.resource_info()) File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 813, in self.saved_values = dict((name, get()) for name, get, restore File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 773, in get_cwd return os.getcwd() OSError: [Errno 2] No such file or directory test_threadsignals test test_threadsignals crashed -- : [Errno 2] No such file or directory Re-running test 'test_threadsignals' in verbose mode test test_threadsignals crashed -- : [Errno 2] No such file or directory Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 861, in runtest_inner with saved_test_environment(test, verbose, quiet) as environment: File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 814, in __enter__ in self.resource_info()) File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 813, in self.saved_values = dict((name, get()) for name, get, restore File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 773, in get_cwd return os.getcwd() OSError: [Errno 2] No such file or directory test_time test test_time crashed -- : [Errno 2] No such file or directory Re-running test 'test_time' in verbose mode test test_time crashed -- : [Errno 2] No such file or directory Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 861, in runtest_inner with saved_test_environment(test, verbose, quiet) as environment: File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 814, in __enter__ in self.resource_info()) File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 813, in self.saved_values = dict((name, get()) for name, get, restore File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 773, in get_cwd return os.getcwd() OSError: [Errno 2] No such file or directory test_timeout test test_timeout crashed -- : [Errno 2] No such file or directory Re-running test 'test_timeout' in verbose mode test test_timeout crashed -- : [Errno 2] No such file or directory Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 861, in runtest_inner with saved_test_environment(test, verbose, quiet) as environment: File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 814, in __enter__ in self.resource_info()) File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 813, in self.saved_values = dict((name, get()) for name, get, restore File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 773, in get_cwd return os.getcwd() OSError: [Errno 2] No such file or directory test_tk test test_tk crashed -- : [Errno 2] No such file or directory Re-running test 'test_tk' in verbose mode test test_tk crashed -- : [Errno 2] No such file or directory Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 861, in runtest_inner with saved_test_environment(test, verbose, quiet) as environment: File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 814, in __enter__ in self.resource_info()) File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 813, in self.saved_values = dict((name, get()) for name, get, restore File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 773, in get_cwd return os.getcwd() OSError: [Errno 2] No such file or directory test_tokenize test test_tokenize crashed -- : [Errno 2] No such file or directory Re-running test 'test_tokenize' in verbose mode test test_tokenize crashed -- : [Errno 2] No such file or directory Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 861, in runtest_inner with saved_test_environment(test, verbose, quiet) as environment: File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 814, in __enter__ in self.resource_info()) File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 813, in self.saved_values = dict((name, get()) for name, get, restore File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 773, in get_cwd return os.getcwd() OSError: [Errno 2] No such file or directory test_trace test test_trace crashed -- : [Errno 2] No such file or directory Re-running test 'test_trace' in verbose mode test test_trace crashed -- : [Errno 2] No such file or directory Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 861, in runtest_inner with saved_test_environment(test, verbose, quiet) as environment: File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 814, in __enter__ in self.resource_info()) File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 813, in self.saved_values = dict((name, get()) for name, get, restore File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 773, in get_cwd return os.getcwd() OSError: [Errno 2] No such file or directory test_traceback test test_traceback crashed -- : [Errno 2] No such file or directory Re-running test 'test_traceback' in verbose mode test test_traceback crashed -- : [Errno 2] No such file or directory Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 861, in runtest_inner with saved_test_environment(test, verbose, quiet) as environment: File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 814, in __enter__ in self.resource_info()) File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 813, in self.saved_values = dict((name, get()) for name, get, restore File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 773, in get_cwd return os.getcwd() OSError: [Errno 2] No such file or directory test_transformer test test_transformer crashed -- : [Errno 2] No such file or directory Re-running test 'test_transformer' in verbose mode test test_transformer crashed -- : [Errno 2] No such file or directory Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 861, in runtest_inner with saved_test_environment(test, verbose, quiet) as environment: File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 814, in __enter__ in self.resource_info()) File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 813, in self.saved_values = dict((name, get()) for name, get, restore File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 773, in get_cwd return os.getcwd() OSError: [Errno 2] No such file or directory test_ttk_guionly test test_ttk_guionly crashed -- : [Errno 2] No such file or directory Re-running test 'test_ttk_guionly' in verbose mode test test_ttk_guionly crashed -- : [Errno 2] No such file or directory Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 861, in runtest_inner with saved_test_environment(test, verbose, quiet) as environment: File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 814, in __enter__ in self.resource_info()) File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 813, in self.saved_values = dict((name, get()) for name, get, restore File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 773, in get_cwd return os.getcwd() OSError: [Errno 2] No such file or directory test_ttk_textonly test test_ttk_textonly crashed -- : [Errno 2] No such file or directory Re-running test 'test_ttk_textonly' in verbose mode test test_ttk_textonly crashed -- : [Errno 2] No such file or directory Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 861, in runtest_inner with saved_test_environment(test, verbose, quiet) as environment: File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 814, in __enter__ in self.resource_info()) File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 813, in self.saved_values = dict((name, get()) for name, get, restore File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 773, in get_cwd return os.getcwd() OSError: [Errno 2] No such file or directory test_tuple test test_tuple crashed -- : [Errno 2] No such file or directory Re-running test 'test_tuple' in verbose mode test test_tuple crashed -- : [Errno 2] No such file or directory Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 861, in runtest_inner with saved_test_environment(test, verbose, quiet) as environment: File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 814, in __enter__ in self.resource_info()) File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 813, in self.saved_values = dict((name, get()) for name, get, restore File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 773, in get_cwd return os.getcwd() OSError: [Errno 2] No such file or directory test_typechecks test test_typechecks crashed -- : [Errno 2] No such file or directory Re-running test 'test_typechecks' in verbose mode test test_typechecks crashed -- : [Errno 2] No such file or directory Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 861, in runtest_inner with saved_test_environment(test, verbose, quiet) as environment: File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 814, in __enter__ in self.resource_info()) File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 813, in self.saved_values = dict((name, get()) for name, get, restore File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 773, in get_cwd return os.getcwd() OSError: [Errno 2] No such file or directory test_ucn test test_ucn crashed -- : [Errno 2] No such file or directory Re-running test 'test_ucn' in verbose mode test test_ucn crashed -- : [Errno 2] No such file or directory Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 861, in runtest_inner with saved_test_environment(test, verbose, quiet) as environment: File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 814, in __enter__ in self.resource_info()) File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 813, in self.saved_values = dict((name, get()) for name, get, restore File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 773, in get_cwd return os.getcwd() OSError: [Errno 2] No such file or directory test_unary test test_unary crashed -- : [Errno 2] No such file or directory Re-running test 'test_unary' in verbose mode test test_unary crashed -- : [Errno 2] No such file or directory Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 861, in runtest_inner with saved_test_environment(test, verbose, quiet) as environment: File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 814, in __enter__ in self.resource_info()) File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 813, in self.saved_values = dict((name, get()) for name, get, restore File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 773, in get_cwd return os.getcwd() OSError: [Errno 2] No such file or directory test_undocumented_details test test_undocumented_details crashed -- : [Errno 2] No such file or directory Re-running test 'test_undocumented_details' in verbose mode test test_undocumented_details crashed -- : [Errno 2] No such file or directory Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 861, in runtest_inner with saved_test_environment(test, verbose, quiet) as environment: File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 814, in __enter__ in self.resource_info()) File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 813, in self.saved_values = dict((name, get()) for name, get, restore File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 773, in get_cwd return os.getcwd() OSError: [Errno 2] No such file or directory test_unicode test test_unicode crashed -- : [Errno 2] No such file or directory Re-running test 'test_unicode' in verbose mode test test_unicode crashed -- : [Errno 2] No such file or directory Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 861, in runtest_inner with saved_test_environment(test, verbose, quiet) as environment: File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 814, in __enter__ in self.resource_info()) File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 813, in self.saved_values = dict((name, get()) for name, get, restore File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 773, in get_cwd return os.getcwd() OSError: [Errno 2] No such file or directory test_unicode_file test test_unicode_file crashed -- : [Errno 2] No such file or directory Re-running test 'test_unicode_file' in verbose mode test test_unicode_file crashed -- : [Errno 2] No such file or directory Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 861, in runtest_inner with saved_test_environment(test, verbose, quiet) as environment: File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 814, in __enter__ in self.resource_info()) File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 813, in self.saved_values = dict((name, get()) for name, get, restore File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 773, in get_cwd return os.getcwd() OSError: [Errno 2] No such file or directory test_unicodedata test test_unicodedata crashed -- : [Errno 2] No such file or directory Re-running test 'test_unicodedata' in verbose mode test test_unicodedata crashed -- : [Errno 2] No such file or directory Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 861, in runtest_inner with saved_test_environment(test, verbose, quiet) as environment: File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 814, in __enter__ in self.resource_info()) File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 813, in self.saved_values = dict((name, get()) for name, get, restore File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 773, in get_cwd return os.getcwd() OSError: [Errno 2] No such file or directory test_univnewlines test test_univnewlines crashed -- : [Errno 2] No such file or directory Re-running test 'test_univnewlines' in verbose mode test test_univnewlines crashed -- : [Errno 2] No such file or directory Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 861, in runtest_inner with saved_test_environment(test, verbose, quiet) as environment: File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 814, in __enter__ in self.resource_info()) File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 813, in self.saved_values = dict((name, get()) for name, get, restore File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 773, in get_cwd return os.getcwd() OSError: [Errno 2] No such file or directory test_univnewlines2k test test_univnewlines2k crashed -- : [Errno 2] No such file or directory Re-running test 'test_univnewlines2k' in verbose mode test test_univnewlines2k crashed -- : [Errno 2] No such file or directory Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 861, in runtest_inner with saved_test_environment(test, verbose, quiet) as environment: File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 814, in __enter__ in self.resource_info()) File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 813, in self.saved_values = dict((name, get()) for name, get, restore File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 773, in get_cwd return os.getcwd() OSError: [Errno 2] No such file or directory test_unpack test test_unpack crashed -- : [Errno 2] No such file or directory Re-running test 'test_unpack' in verbose mode test test_unpack crashed -- : [Errno 2] No such file or directory Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 861, in runtest_inner with saved_test_environment(test, verbose, quiet) as environment: File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 814, in __enter__ in self.resource_info()) File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 813, in self.saved_values = dict((name, get()) for name, get, restore File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 773, in get_cwd return os.getcwd() OSError: [Errno 2] No such file or directory test_urllib test test_urllib crashed -- : [Errno 2] No such file or directory Re-running test 'test_urllib' in verbose mode test test_urllib crashed -- : [Errno 2] No such file or directory Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 861, in runtest_inner with saved_test_environment(test, verbose, quiet) as environment: File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 814, in __enter__ in self.resource_info()) File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 813, in self.saved_values = dict((name, get()) for name, get, restore File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 773, in get_cwd return os.getcwd() OSError: [Errno 2] No such file or directory test_urllib2 test test_urllib2 crashed -- : [Errno 2] No such file or directory Re-running test 'test_urllib2' in verbose mode test test_urllib2 crashed -- : [Errno 2] No such file or directory Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 861, in runtest_inner with saved_test_environment(test, verbose, quiet) as environment: File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 814, in __enter__ in self.resource_info()) File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 813, in self.saved_values = dict((name, get()) for name, get, restore File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 773, in get_cwd return os.getcwd() OSError: [Errno 2] No such file or directory test_urllib2_localnet test test_urllib2_localnet crashed -- : [Errno 2] No such file or directory Re-running test 'test_urllib2_localnet' in verbose mode test test_urllib2_localnet crashed -- : [Errno 2] No such file or directory Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 861, in runtest_inner with saved_test_environment(test, verbose, quiet) as environment: File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 814, in __enter__ in self.resource_info()) File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 813, in self.saved_values = dict((name, get()) for name, get, restore File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 773, in get_cwd return os.getcwd() OSError: [Errno 2] No such file or directory test_urllib2net test test_urllib2net crashed -- : [Errno 2] No such file or directory Re-running test 'test_urllib2net' in verbose mode test test_urllib2net crashed -- : [Errno 2] No such file or directory Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 861, in runtest_inner with saved_test_environment(test, verbose, quiet) as environment: File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 814, in __enter__ in self.resource_info()) File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 813, in self.saved_values = dict((name, get()) for name, get, restore File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 773, in get_cwd return os.getcwd() OSError: [Errno 2] No such file or directory test_urllibnet test test_urllibnet crashed -- : [Errno 2] No such file or directory Re-running test 'test_urllibnet' in verbose mode test test_urllibnet crashed -- : [Errno 2] No such file or directory Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 861, in runtest_inner with saved_test_environment(test, verbose, quiet) as environment: File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 814, in __enter__ in self.resource_info()) File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 813, in self.saved_values = dict((name, get()) for name, get, restore File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 773, in get_cwd return os.getcwd() OSError: [Errno 2] No such file or directory test_urlparse test test_urlparse crashed -- : [Errno 2] No such file or directory Re-running test 'test_urlparse' in verbose mode test test_urlparse crashed -- : [Errno 2] No such file or directory Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 861, in runtest_inner with saved_test_environment(test, verbose, quiet) as environment: File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 814, in __enter__ in self.resource_info()) File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 813, in self.saved_values = dict((name, get()) for name, get, restore File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 773, in get_cwd return os.getcwd() OSError: [Errno 2] No such file or directory test_userdict test test_userdict crashed -- : [Errno 2] No such file or directory Re-running test 'test_userdict' in verbose mode test test_userdict crashed -- : [Errno 2] No such file or directory Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 861, in runtest_inner with saved_test_environment(test, verbose, quiet) as environment: File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 814, in __enter__ in self.resource_info()) File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 813, in self.saved_values = dict((name, get()) for name, get, restore File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 773, in get_cwd return os.getcwd() OSError: [Errno 2] No such file or directory test_userlist test test_userlist crashed -- : [Errno 2] No such file or directory Re-running test 'test_userlist' in verbose mode test test_userlist crashed -- : [Errno 2] No such file or directory Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 861, in runtest_inner with saved_test_environment(test, verbose, quiet) as environment: File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 814, in __enter__ in self.resource_info()) File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 813, in self.saved_values = dict((name, get()) for name, get, restore File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 773, in get_cwd return os.getcwd() OSError: [Errno 2] No such file or directory test_userstring test test_userstring crashed -- : [Errno 2] No such file or directory Re-running test 'test_userstring' in verbose mode test test_userstring crashed -- : [Errno 2] No such file or directory Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 861, in runtest_inner with saved_test_environment(test, verbose, quiet) as environment: File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 814, in __enter__ in self.resource_info()) File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 813, in self.saved_values = dict((name, get()) for name, get, restore File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 773, in get_cwd return os.getcwd() OSError: [Errno 2] No such file or directory test_uu test test_uu crashed -- : [Errno 2] No such file or directory Re-running test 'test_uu' in verbose mode test test_uu crashed -- : [Errno 2] No such file or directory Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 861, in runtest_inner with saved_test_environment(test, verbose, quiet) as environment: File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 814, in __enter__ in self.resource_info()) File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 813, in self.saved_values = dict((name, get()) for name, get, restore File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 773, in get_cwd return os.getcwd() OSError: [Errno 2] No such file or directory test_uuid test test_uuid crashed -- : [Errno 2] No such file or directory Re-running test 'test_uuid' in verbose mode test test_uuid crashed -- : [Errno 2] No such file or directory Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 861, in runtest_inner with saved_test_environment(test, verbose, quiet) as environment: File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 814, in __enter__ in self.resource_info()) File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 813, in self.saved_values = dict((name, get()) for name, get, restore File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 773, in get_cwd return os.getcwd() OSError: [Errno 2] No such file or directory test_wait3 test test_wait3 crashed -- : [Errno 2] No such file or directory Re-running test 'test_wait3' in verbose mode test test_wait3 crashed -- : [Errno 2] No such file or directory Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 861, in runtest_inner with saved_test_environment(test, verbose, quiet) as environment: File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 814, in __enter__ in self.resource_info()) File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 813, in self.saved_values = dict((name, get()) for name, get, restore File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 773, in get_cwd return os.getcwd() OSError: [Errno 2] No such file or directory test_wait4 test test_wait4 crashed -- : [Errno 2] No such file or directory Re-running test 'test_wait4' in verbose mode test test_wait4 crashed -- : [Errno 2] No such file or directory Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 861, in runtest_inner with saved_test_environment(test, verbose, quiet) as environment: File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 814, in __enter__ in self.resource_info()) File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 813, in self.saved_values = dict((name, get()) for name, get, restore File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 773, in get_cwd return os.getcwd() OSError: [Errno 2] No such file or directory test_warnings test test_warnings crashed -- : [Errno 2] No such file or directory Re-running test 'test_warnings' in verbose mode test test_warnings crashed -- : [Errno 2] No such file or directory Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 861, in runtest_inner with saved_test_environment(test, verbose, quiet) as environment: File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 814, in __enter__ in self.resource_info()) File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 813, in self.saved_values = dict((name, get()) for name, get, restore File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 773, in get_cwd return os.getcwd() OSError: [Errno 2] No such file or directory test_wave test test_wave crashed -- : [Errno 2] No such file or directory Re-running test 'test_wave' in verbose mode test test_wave crashed -- : [Errno 2] No such file or directory Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 861, in runtest_inner with saved_test_environment(test, verbose, quiet) as environment: File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 814, in __enter__ in self.resource_info()) File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 813, in self.saved_values = dict((name, get()) for name, get, restore File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 773, in get_cwd return os.getcwd() OSError: [Errno 2] No such file or directory test_weakref test test_weakref crashed -- : [Errno 2] No such file or directory Re-running test 'test_weakref' in verbose mode test test_weakref crashed -- : [Errno 2] No such file or directory Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 861, in runtest_inner with saved_test_environment(test, verbose, quiet) as environment: File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 814, in __enter__ in self.resource_info()) File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 813, in self.saved_values = dict((name, get()) for name, get, restore File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 773, in get_cwd return os.getcwd() OSError: [Errno 2] No such file or directory test_weakset test test_weakset crashed -- : [Errno 2] No such file or directory Re-running test 'test_weakset' in verbose mode test test_weakset crashed -- : [Errno 2] No such file or directory Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 861, in runtest_inner with saved_test_environment(test, verbose, quiet) as environment: File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 814, in __enter__ in self.resource_info()) File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 813, in self.saved_values = dict((name, get()) for name, get, restore File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 773, in get_cwd return os.getcwd() OSError: [Errno 2] No such file or directory test_whichdb test test_whichdb crashed -- : [Errno 2] No such file or directory Re-running test 'test_whichdb' in verbose mode test test_whichdb crashed -- : [Errno 2] No such file or directory Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 861, in runtest_inner with saved_test_environment(test, verbose, quiet) as environment: File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 814, in __enter__ in self.resource_info()) File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 813, in self.saved_values = dict((name, get()) for name, get, restore File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 773, in get_cwd return os.getcwd() OSError: [Errno 2] No such file or directory test_winreg test test_winreg crashed -- : [Errno 2] No such file or directory Re-running test 'test_winreg' in verbose mode test test_winreg crashed -- : [Errno 2] No such file or directory Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 861, in runtest_inner with saved_test_environment(test, verbose, quiet) as environment: File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 814, in __enter__ in self.resource_info()) File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 813, in self.saved_values = dict((name, get()) for name, get, restore File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 773, in get_cwd return os.getcwd() OSError: [Errno 2] No such file or directory test_winsound test test_winsound crashed -- : [Errno 2] No such file or directory Re-running test 'test_winsound' in verbose mode test test_winsound crashed -- : [Errno 2] No such file or directory Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 861, in runtest_inner with saved_test_environment(test, verbose, quiet) as environment: File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 814, in __enter__ in self.resource_info()) File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 813, in self.saved_values = dict((name, get()) for name, get, restore File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 773, in get_cwd return os.getcwd() OSError: [Errno 2] No such file or directory test_with test test_with crashed -- : [Errno 2] No such file or directory Re-running test 'test_with' in verbose mode test test_with crashed -- : [Errno 2] No such file or directory Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 861, in runtest_inner with saved_test_environment(test, verbose, quiet) as environment: File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 814, in __enter__ in self.resource_info()) File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 813, in self.saved_values = dict((name, get()) for name, get, restore File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 773, in get_cwd return os.getcwd() OSError: [Errno 2] No such file or directory test_wsgiref test test_wsgiref crashed -- : [Errno 2] No such file or directory Re-running test 'test_wsgiref' in verbose mode test test_wsgiref crashed -- : [Errno 2] No such file or directory Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 861, in runtest_inner with saved_test_environment(test, verbose, quiet) as environment: File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 814, in __enter__ in self.resource_info()) File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 813, in self.saved_values = dict((name, get()) for name, get, restore File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 773, in get_cwd return os.getcwd() OSError: [Errno 2] No such file or directory test_xdrlib test test_xdrlib crashed -- : [Errno 2] No such file or directory Re-running test 'test_xdrlib' in verbose mode test test_xdrlib crashed -- : [Errno 2] No such file or directory Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 861, in runtest_inner with saved_test_environment(test, verbose, quiet) as environment: File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 814, in __enter__ in self.resource_info()) File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 813, in self.saved_values = dict((name, get()) for name, get, restore File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 773, in get_cwd return os.getcwd() OSError: [Errno 2] No such file or directory test_xml_etree test test_xml_etree crashed -- : [Errno 2] No such file or directory Re-running test 'test_xml_etree' in verbose mode test test_xml_etree crashed -- : [Errno 2] No such file or directory Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 861, in runtest_inner with saved_test_environment(test, verbose, quiet) as environment: File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 814, in __enter__ in self.resource_info()) File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 813, in self.saved_values = dict((name, get()) for name, get, restore File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 773, in get_cwd return os.getcwd() OSError: [Errno 2] No such file or directory test_xml_etree_c test test_xml_etree_c crashed -- : [Errno 2] No such file or directory Re-running test 'test_xml_etree_c' in verbose mode test test_xml_etree_c crashed -- : [Errno 2] No such file or directory Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 861, in runtest_inner with saved_test_environment(test, verbose, quiet) as environment: File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 814, in __enter__ in self.resource_info()) File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 813, in self.saved_values = dict((name, get()) for name, get, restore File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 773, in get_cwd return os.getcwd() OSError: [Errno 2] No such file or directory test_xmllib test test_xmllib crashed -- : [Errno 2] No such file or directory Re-running test 'test_xmllib' in verbose mode test test_xmllib crashed -- : [Errno 2] No such file or directory Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 861, in runtest_inner with saved_test_environment(test, verbose, quiet) as environment: File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 814, in __enter__ in self.resource_info()) File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 813, in self.saved_values = dict((name, get()) for name, get, restore File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 773, in get_cwd return os.getcwd() OSError: [Errno 2] No such file or directory test_xmlrpc test test_xmlrpc crashed -- : [Errno 2] No such file or directory Re-running test 'test_xmlrpc' in verbose mode test test_xmlrpc crashed -- : [Errno 2] No such file or directory Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 861, in runtest_inner with saved_test_environment(test, verbose, quiet) as environment: File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 814, in __enter__ in self.resource_info()) File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 813, in self.saved_values = dict((name, get()) for name, get, restore File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 773, in get_cwd return os.getcwd() OSError: [Errno 2] No such file or directory test_xpickle test test_xpickle crashed -- : [Errno 2] No such file or directory Re-running test 'test_xpickle' in verbose mode test test_xpickle crashed -- : [Errno 2] No such file or directory Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 861, in runtest_inner with saved_test_environment(test, verbose, quiet) as environment: File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 814, in __enter__ in self.resource_info()) File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 813, in self.saved_values = dict((name, get()) for name, get, restore File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 773, in get_cwd return os.getcwd() OSError: [Errno 2] No such file or directory test_xrange test test_xrange crashed -- : [Errno 2] No such file or directory Re-running test 'test_xrange' in verbose mode test test_xrange crashed -- : [Errno 2] No such file or directory Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 861, in runtest_inner with saved_test_environment(test, verbose, quiet) as environment: File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 814, in __enter__ in self.resource_info()) File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 813, in self.saved_values = dict((name, get()) for name, get, restore File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 773, in get_cwd return os.getcwd() OSError: [Errno 2] No such file or directory test_zipfile test test_zipfile crashed -- : [Errno 2] No such file or directory Re-running test 'test_zipfile' in verbose mode test test_zipfile crashed -- : [Errno 2] No such file or directory Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 861, in runtest_inner with saved_test_environment(test, verbose, quiet) as environment: File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 814, in __enter__ in self.resource_info()) File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 813, in self.saved_values = dict((name, get()) for name, get, restore File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 773, in get_cwd return os.getcwd() OSError: [Errno 2] No such file or directory test_zipfile64 test test_zipfile64 crashed -- : [Errno 2] No such file or directory Re-running test 'test_zipfile64' in verbose mode test test_zipfile64 crashed -- : [Errno 2] No such file or directory Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 861, in runtest_inner with saved_test_environment(test, verbose, quiet) as environment: File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 814, in __enter__ in self.resource_info()) File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 813, in self.saved_values = dict((name, get()) for name, get, restore File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 773, in get_cwd return os.getcwd() OSError: [Errno 2] No such file or directory test_zipimport test test_zipimport crashed -- : [Errno 2] No such file or directory Re-running test 'test_zipimport' in verbose mode test test_zipimport crashed -- : [Errno 2] No such file or directory Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 861, in runtest_inner with saved_test_environment(test, verbose, quiet) as environment: File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 814, in __enter__ in self.resource_info()) File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 813, in self.saved_values = dict((name, get()) for name, get, restore File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 773, in get_cwd return os.getcwd() OSError: [Errno 2] No such file or directory test_zipimport_support test test_zipimport_support crashed -- : [Errno 2] No such file or directory Re-running test 'test_zipimport_support' in verbose mode test test_zipimport_support crashed -- : [Errno 2] No such file or directory Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 861, in runtest_inner with saved_test_environment(test, verbose, quiet) as environment: File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 814, in __enter__ in self.resource_info()) File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 813, in self.saved_values = dict((name, get()) for name, get, restore File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 773, in get_cwd return os.getcwd() OSError: [Errno 2] No such file or directory test_zlib test test_zlib crashed -- : [Errno 2] No such file or directory Re-running test 'test_zlib' in verbose mode test test_zlib crashed -- : [Errno 2] No such file or directory Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 861, in runtest_inner with saved_test_environment(test, verbose, quiet) as environment: File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 814, in __enter__ in self.resource_info()) File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 813, in self.saved_values = dict((name, get()) for name, get, restore File "/tmp/python-test/local/lib/python2.7/test/regrtest.py", line 773, in get_cwd return os.getcwd() OSError: [Errno 2] No such file or directory 186 tests OK. 181 tests failed: test_mailbox test_marshal test_math test_md5 test_memoryio test_memoryview test_mhlib test_mimetools test_mimetypes test_minidom test_mmap test_module test_modulefinder test_multibytecodec test_multibytecodec_support test_multifile test_multiprocessing test_mutants test_mutex test_netrc test_new test_nis test_normalization test_ntpath test_old_mailbox test_openpty test_operator test_optparse test_os test_parser test_pdb test_peepholer test_pep247 test_pep263 test_pep277 test_pep292 test_pep352 test_pickle test_pickletools test_pipes test_pkg test_pkgimport test_pkgutil test_platform test_plistlib test_poll test_popen test_popen2 test_poplib test_posix test_posixpath test_pow test_pprint test_print test_profile test_profilehooks test_property test_pstats test_pty test_pwd test_py3kwarn test_pyclbr test_pydoc test_pyexpat test_queue test_quopri test_random test_re test_readline test_repr test_resource test_rfc822 test_richcmp test_robotparser test_runpy test_sax test_scope test_scriptpackages test_select test_set test_setcomps test_sets test_sgmllib test_sha test_shelve test_shlex test_shutil test_signal test_site test_slice test_smtplib test_smtpnet test_socket test_socketserver test_softspace test_sort test_sqlite test_ssl test_startfile test_str test_strftime test_string test_stringprep test_strop test_strptime test_strtod test_struct test_structmembers test_structseq test_subprocess test_sunaudiodev test_sundry test_symtable test_syntax test_sys test_sysconfig test_tarfile test_tcl test_telnetlib test_tempfile test_textwrap test_thread test_threaded_import test_threadedtempfile test_threading test_threading_local test_threadsignals test_time test_timeout test_tk test_tokenize test_trace test_traceback test_transformer test_ttk_guionly test_ttk_textonly test_tuple test_typechecks test_ucn test_unary test_undocumented_details test_unicode test_unicode_file test_unicodedata test_univnewlines test_univnewlines2k test_unpack test_urllib test_urllib2 test_urllib2_localnet test_urllib2net test_urllibnet test_urlparse test_userdict test_userlist test_userstring test_uu test_uuid test_wait3 test_wait4 test_warnings test_wave test_weakref test_weakset test_whichdb test_winreg test_winsound test_with test_wsgiref test_xdrlib test_xml_etree test_xml_etree_c test_xmllib test_xmlrpc test_xpickle test_xrange test_zipfile test_zipfile64 test_zipimport test_zipimport_support test_zlib 14 tests skipped: test_aepack test_al test_applesingle test_bsddb185 test_cd test_cl test_epoll test_gdb test_gl test_imgfile test_ioctl test_kqueue test_macos test_macostools 3 skips unexpected on linux2: test_epoll test_gdb test_ioctl [727762 refs] From python-checkins at python.org Thu May 20 20:37:55 2010 From: python-checkins at python.org (brett.cannon) Date: Thu, 20 May 2010 20:37:55 +0200 (CEST) Subject: [Python-checkins] r81380 - in python/trunk: Lib/test/test_import.py Misc/NEWS Python/import.c Message-ID: <20100520183755.EF012C797@mail.python.org> Author: brett.cannon Date: Thu May 20 20:37:55 2010 New Revision: 81380 Log: Turned out that if you used explicit relative import syntax (e.g. from .os import sep) and it failed, import would still try the implicit relative import semantics of an absolute import (from os import sep). That's not right, so when level is negative, only do explicit relative import semantics. Fixes issue #7902. Thanks to Meador Inge for the patch. Modified: python/trunk/Lib/test/test_import.py python/trunk/Misc/NEWS python/trunk/Python/import.c Modified: python/trunk/Lib/test/test_import.py ============================================================================== --- python/trunk/Lib/test/test_import.py (original) +++ python/trunk/Lib/test/test_import.py Thu May 20 20:37:55 2010 @@ -431,6 +431,18 @@ self.assertRaises(ValueError, check_absolute) self.assertRaises(ValueError, check_relative) + def test_absolute_import_without_future(self): + # If absolute import syntax is used, then do not try to perform + # a relative import in the face of failure. + # Issue #7902. + try: + from .os import sep + except ImportError: + pass + else: + self.fail("explicit relative import triggered an " + "implicit relative import") + def test_main(verbose=None): run_unittest(ImportTests, PycRewritingTests, PathsTests, RelativeImportTests) Modified: python/trunk/Misc/NEWS ============================================================================== --- python/trunk/Misc/NEWS (original) +++ python/trunk/Misc/NEWS Thu May 20 20:37:55 2010 @@ -12,6 +12,9 @@ Core and Builtins ----------------- +- Issue #7902: When using explicit relative import syntax, don't try + implicit relative import semantics. + - Issue #7079: Fix a possible crash when closing a file object while using it from another thread. Patch by Daniel Stutzbach. Modified: python/trunk/Python/import.c ============================================================================== --- python/trunk/Python/import.c (original) +++ python/trunk/Python/import.c Thu May 20 20:37:55 2010 @@ -2134,7 +2134,8 @@ if (parent == NULL) return NULL; - head = load_next(parent, Py_None, &name, buf, &buflen); + head = load_next(parent, level < 0 ? Py_None : parent, &name, buf, + &buflen); if (head == NULL) return NULL; From python-checkins at python.org Thu May 20 20:41:08 2010 From: python-checkins at python.org (brett.cannon) Date: Thu, 20 May 2010 20:41:08 +0200 (CEST) Subject: [Python-checkins] r81381 - in python/branches/release26-maint: Lib/test/test_import.py Misc/NEWS Python/import.c Message-ID: <20100520184108.848B0C874@mail.python.org> Author: brett.cannon Date: Thu May 20 20:41:08 2010 New Revision: 81381 Log: Merged revisions 81380 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r81380 | brett.cannon | 2010-05-20 11:37:55 -0700 (Thu, 20 May 2010) | 8 lines Turned out that if you used explicit relative import syntax (e.g. from .os import sep) and it failed, import would still try the implicit relative import semantics of an absolute import (from os import sep). That's not right, so when level is negative, only do explicit relative import semantics. Fixes issue #7902. Thanks to Meador Inge for the patch. ........ Modified: python/branches/release26-maint/ (props changed) python/branches/release26-maint/Lib/test/test_import.py python/branches/release26-maint/Misc/NEWS python/branches/release26-maint/Python/import.c Modified: python/branches/release26-maint/Lib/test/test_import.py ============================================================================== --- python/branches/release26-maint/Lib/test/test_import.py (original) +++ python/branches/release26-maint/Lib/test/test_import.py Thu May 20 20:41:08 2010 @@ -417,6 +417,19 @@ self.assertRaises(ValueError, check_absolute) self.assertRaises(ValueError, check_relative) + def test_absolute_import_without_future(self): + # If absolute import syntax is used, then do not try to perform + # a relative import in the face of failure. + # Issue #7902. + try: + from .os import sep + except ImportError: + pass + else: + self.fail("explicit relative import triggered an " + "implicit relative import") + + def test_main(verbose=None): run_unittest(ImportTest, TestPycRewriting, PathsTests, RelativeImport) Modified: python/branches/release26-maint/Misc/NEWS ============================================================================== --- python/branches/release26-maint/Misc/NEWS (original) +++ python/branches/release26-maint/Misc/NEWS Thu May 20 20:41:08 2010 @@ -12,6 +12,9 @@ Core and Builtins ----------------- +- Issue #7902: When using explicit relative import syntax, don't try + implicit relative import semantics. + - Issue #7079: Fix a possible crash when closing a file object while using it from another thread. Patch by Daniel Stutzbach. Modified: python/branches/release26-maint/Python/import.c ============================================================================== --- python/branches/release26-maint/Python/import.c (original) +++ python/branches/release26-maint/Python/import.c Thu May 20 20:41:08 2010 @@ -2130,7 +2130,8 @@ if (parent == NULL) return NULL; - head = load_next(parent, Py_None, &name, buf, &buflen); + head = load_next(parent, level < 0 ? Py_None : parent, &name, buf, + &buflen); if (head == NULL) return NULL; From python-checkins at python.org Thu May 20 22:53:34 2010 From: python-checkins at python.org (r.david.murray) Date: Thu, 20 May 2010 22:53:34 +0200 (CEST) Subject: [Python-checkins] r81382 - in python/branches/release26-maint: Lib/test/test_csv.py Message-ID: <20100520205334.ECC25E8C1@mail.python.org> Author: r.david.murray Date: Thu May 20 22:53:34 2010 New Revision: 81382 Log: Unblocked and Merged revisions 70997 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r70997 | r.david.murray | 2009-04-01 17:26:18 -0400 (Wed, 01 Apr 2009) | 3 lines Add tests checking the CSV module's ability to handle embedded newlines in quoted field values. ........ Modified: python/branches/release26-maint/ (props changed) python/branches/release26-maint/Lib/test/test_csv.py Modified: python/branches/release26-maint/Lib/test/test_csv.py ============================================================================== --- python/branches/release26-maint/Lib/test/test_csv.py (original) +++ python/branches/release26-maint/Lib/test/test_csv.py Thu May 20 22:53:34 2010 @@ -166,6 +166,8 @@ quoting = csv.QUOTE_NONNUMERIC) self._write_test(['a',1,'p,q'], '"a","1","p,q"', quoting = csv.QUOTE_ALL) + self._write_test(['a\nb',1], '"a\nb","1"', + quoting = csv.QUOTE_ALL) def test_write_escape(self): self._write_test(['a',1,'p,q'], 'a,1,"p,q"', @@ -245,6 +247,7 @@ # will this fail where locale uses comma for decimals? self._read_test([',3,"5",7.3, 9'], [['', 3, '5', 7.3, 9]], quoting=csv.QUOTE_NONNUMERIC) + self._read_test(['"a\nb", 7'], [['a\nb', ' 7']]) self.assertRaises(ValueError, self._read_test, ['abc,3'], [[]], quoting=csv.QUOTE_NONNUMERIC) @@ -282,6 +285,21 @@ self.assertRaises(StopIteration, r.next) self.assertEqual(r.line_num, 3) + def test_roundtrip_quoteed_newlines(self): + fd, name = tempfile.mkstemp() + fileobj = os.fdopen(fd, "w+b") + try: + writer = csv.writer(fileobj) + self.assertRaises(TypeError, writer.writerows, None) + rows = [['a\nb','b'],['c','x\r\nd']] + writer.writerows(rows) + fileobj.seek(0) + for i, row in enumerate(csv.reader(fileobj)): + self.assertEqual(row, rows[i]) + finally: + fileobj.close() + os.unlink(name) + class TestDialectRegistry(unittest.TestCase): def test_registry_badargs(self): self.assertRaises(TypeError, csv.list_dialects, None) From python-checkins at python.org Thu May 20 23:00:34 2010 From: python-checkins at python.org (victor.stinner) Date: Thu, 20 May 2010 23:00:34 +0200 (CEST) Subject: [Python-checkins] r81383 - in python/branches/release31-maint: Lib/test/test_warnings.py Misc/NEWS Python/_warnings.c Python/pythonrun.c Message-ID: <20100520210034.6F2EAEB06@mail.python.org> Author: victor.stinner Date: Thu May 20 23:00:34 2010 New Revision: 81383 Log: Recorded merge of revisions 81364 via svnmerge from svn+ssh://pythondev at svn.python.org/python/branches/py3k ........ r81364 | victor.stinner | 2010-05-19 22:40:50 +0200 (mer., 19 mai 2010) | 3 lines Issue #8766: Initialize _warnings module before importing the first module. Fix a crash if an empty directory called "encodings" exists in sys.path. ........ Modified: python/branches/release31-maint/ (props changed) python/branches/release31-maint/Lib/test/test_warnings.py python/branches/release31-maint/Misc/NEWS python/branches/release31-maint/Python/_warnings.c python/branches/release31-maint/Python/pythonrun.c Modified: python/branches/release31-maint/Lib/test/test_warnings.py ============================================================================== --- python/branches/release31-maint/Lib/test/test_warnings.py (original) +++ python/branches/release31-maint/Lib/test/test_warnings.py Thu May 20 23:00:34 2010 @@ -4,6 +4,9 @@ from io import StringIO import sys import unittest +import shutil +import tempfile +import subprocess from test import support from test import warning_tests @@ -670,18 +673,46 @@ module = py_warnings +class BootstrapTest(unittest.TestCase): + def test_issue_8766(self): + # "import encodings" emits a warning whereas the warnings is not loaded + # or not completly loaded (warnings imports indirectly encodings by + # importing linecache) yet + old_cwd = os.getcwd() + try: + cwd = tempfile.mkdtemp() + try: + os.chdir(cwd) + os.mkdir('encodings') + env = os.environ.copy() + env['PYTHONPATH'] = cwd + + # encodings loaded by initfsencoding() + retcode = subprocess.call([sys.executable, '-c', 'pass'], env=env) + self.assertEqual(retcode, 0) + + # Use -W to load warnings module at startup + retcode = subprocess.call( + [sys.executable, '-c', 'pass', '-W', 'always'], + env=env) + self.assertEqual(retcode, 0) + finally: + shutil.rmtree(cwd) + finally: + os.chdir(old_cwd) + def test_main(): py_warnings.onceregistry.clear() c_warnings.onceregistry.clear() - support.run_unittest(CFilterTests, - PyFilterTests, - CWarnTests, - PyWarnTests, - CWCmdLineTests, PyWCmdLineTests, - _WarningsTests, - CWarningsDisplayTests, PyWarningsDisplayTests, - CCatchWarningTests, PyCatchWarningTests, - ) + support.run_unittest( + CFilterTests, PyFilterTests, + CWarnTests, PyWarnTests, + CWCmdLineTests, PyWCmdLineTests, + _WarningsTests, + CWarningsDisplayTests, PyWarningsDisplayTests, + CCatchWarningTests, PyCatchWarningTests, + BootstrapTest, + ) if __name__ == "__main__": Modified: python/branches/release31-maint/Misc/NEWS ============================================================================== --- python/branches/release31-maint/Misc/NEWS (original) +++ python/branches/release31-maint/Misc/NEWS Thu May 20 23:00:34 2010 @@ -12,6 +12,9 @@ Core and Builtins ----------------- +- Issue #8766: Initialize _warnings module before importing the first module. + Fix a crash if an empty directory called "encodings" exists in sys.path. + - PyObject_Dump() encodes unicode objects to utf8 with backslashreplace (instead of strict) error handler to escape surrogates Modified: python/branches/release31-maint/Python/_warnings.c ============================================================================== --- python/branches/release31-maint/Python/_warnings.c (original) +++ python/branches/release31-maint/Python/_warnings.c Thu May 20 23:00:34 2010 @@ -116,7 +116,7 @@ _filters = warnings_filters; } - if (!PyList_Check(_filters)) { + if (_filters == NULL || !PyList_Check(_filters)) { PyErr_SetString(PyExc_ValueError, MODULE_NAME ".filters must be a list"); return NULL; Modified: python/branches/release31-maint/Python/pythonrun.c ============================================================================== --- python/branches/release31-maint/Python/pythonrun.c (original) +++ python/branches/release31-maint/Python/pythonrun.c Thu May 20 23:00:34 2010 @@ -264,6 +264,9 @@ _PyImportHooks_Init(); + /* Initialize _warnings. */ + _PyWarnings_Init(); + #if defined(HAVE_LANGINFO_H) && defined(CODESET) /* On Unix, set the file system encoding according to the user's preference, if the CODESET names a well-known @@ -284,7 +287,6 @@ initsigs(); /* Signal handling stuff, including initintr() */ /* Initialize warnings. */ - _PyWarnings_Init(); if (PySys_HasWarnOptions()) { PyObject *warnings_module = PyImport_ImportModule("warnings"); if (!warnings_module) From python-checkins at python.org Thu May 20 23:42:00 2010 From: python-checkins at python.org (victor.stinner) Date: Thu, 20 May 2010 23:42:00 +0200 (CEST) Subject: [Python-checkins] r81384 - python/branches/release31-maint/Lib/test/test_warnings.py Message-ID: <20100520214200.BBC19C8E3@mail.python.org> Author: victor.stinner Date: Thu May 20 23:42:00 2010 New Revision: 81384 Log: Fix test_warnings on Windows (don't change current directory) Modified: python/branches/release31-maint/Lib/test/test_warnings.py Modified: python/branches/release31-maint/Lib/test/test_warnings.py ============================================================================== --- python/branches/release31-maint/Lib/test/test_warnings.py (original) +++ python/branches/release31-maint/Lib/test/test_warnings.py Thu May 20 23:42:00 2010 @@ -4,7 +4,6 @@ from io import StringIO import sys import unittest -import shutil import tempfile import subprocess from test import support @@ -678,12 +677,11 @@ # "import encodings" emits a warning whereas the warnings is not loaded # or not completly loaded (warnings imports indirectly encodings by # importing linecache) yet - old_cwd = os.getcwd() + cwd = tempfile.mkdtemp() try: - cwd = tempfile.mkdtemp() + encodings = os.path.join(cwd, 'encodings') + os.mkdir(encodings) try: - os.chdir(cwd) - os.mkdir('encodings') env = os.environ.copy() env['PYTHONPATH'] = cwd @@ -697,9 +695,9 @@ env=env) self.assertEqual(retcode, 0) finally: - shutil.rmtree(cwd) + os.rmdir(encodings) finally: - os.chdir(old_cwd) + os.rmdir(cwd) def test_main(): py_warnings.onceregistry.clear() From python-checkins at python.org Fri May 21 00:23:37 2010 From: python-checkins at python.org (benjamin.peterson) Date: Fri, 21 May 2010 00:23:37 +0200 (CEST) Subject: [Python-checkins] r81385 - python/trunk/Doc/library/symtable.rst Message-ID: <20100520222337.30B35C874@mail.python.org> Author: benjamin.peterson Date: Fri May 21 00:23:37 2010 New Revision: 81385 Log: fix extra 't' #8778 Modified: python/trunk/Doc/library/symtable.rst Modified: python/trunk/Doc/library/symtable.rst ============================================================================== --- python/trunk/Doc/library/symtable.rst (original) +++ python/trunk/Doc/library/symtable.rst Fri May 21 00:23:37 2010 @@ -67,7 +67,7 @@ Return ``True`` if the block uses ``exec``. - .. method:: has_import_start() + .. method:: has_import_star() Return ``True`` if the block uses a starred from-import. From python-checkins at python.org Fri May 21 00:27:10 2010 From: python-checkins at python.org (benjamin.peterson) Date: Fri, 21 May 2010 00:27:10 +0200 (CEST) Subject: [Python-checkins] r81386 - in python/branches/release26-maint: Doc/library/symtable.rst Message-ID: <20100520222710.A7DA1E340@mail.python.org> Author: benjamin.peterson Date: Fri May 21 00:27:10 2010 New Revision: 81386 Log: Merged revisions 81385 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r81385 | benjamin.peterson | 2010-05-20 17:23:37 -0500 (Thu, 20 May 2010) | 1 line fix extra 't' #8778 ........ Modified: python/branches/release26-maint/ (props changed) python/branches/release26-maint/Doc/library/symtable.rst Modified: python/branches/release26-maint/Doc/library/symtable.rst ============================================================================== --- python/branches/release26-maint/Doc/library/symtable.rst (original) +++ python/branches/release26-maint/Doc/library/symtable.rst Fri May 21 00:27:10 2010 @@ -67,7 +67,7 @@ Return ``True`` if the block uses ``exec``. - .. method:: has_import_start() + .. method:: has_import_star() Return ``True`` if the block uses a starred from-import. From python-checkins at python.org Fri May 21 00:29:43 2010 From: python-checkins at python.org (benjamin.peterson) Date: Fri, 21 May 2010 00:29:43 +0200 (CEST) Subject: [Python-checkins] r81387 - in python/branches/py3k: Doc/library/symtable.rst Message-ID: <20100520222943.705D6C874@mail.python.org> Author: benjamin.peterson Date: Fri May 21 00:29:43 2010 New Revision: 81387 Log: Merged revisions 81385 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r81385 | benjamin.peterson | 2010-05-20 17:23:37 -0500 (Thu, 20 May 2010) | 1 line fix extra 't' #8778 ........ Modified: python/branches/py3k/ (props changed) python/branches/py3k/Doc/library/symtable.rst Modified: python/branches/py3k/Doc/library/symtable.rst ============================================================================== --- python/branches/py3k/Doc/library/symtable.rst (original) +++ python/branches/py3k/Doc/library/symtable.rst Fri May 21 00:29:43 2010 @@ -67,7 +67,7 @@ Return ``True`` if the block uses ``exec``. - .. method:: has_import_start() + .. method:: has_import_star() Return ``True`` if the block uses a starred from-import. From python-checkins at python.org Fri May 21 00:34:01 2010 From: python-checkins at python.org (benjamin.peterson) Date: Fri, 21 May 2010 00:34:01 +0200 (CEST) Subject: [Python-checkins] r81388 - in python/branches/release31-maint: Doc/library/symtable.rst Message-ID: <20100520223401.0EC1EC8BE@mail.python.org> Author: benjamin.peterson Date: Fri May 21 00:34:00 2010 New Revision: 81388 Log: Merged revisions 81387 via svnmerge from svn+ssh://pythondev at svn.python.org/python/branches/py3k ................ r81387 | benjamin.peterson | 2010-05-20 17:29:43 -0500 (Thu, 20 May 2010) | 9 lines Merged revisions 81385 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r81385 | benjamin.peterson | 2010-05-20 17:23:37 -0500 (Thu, 20 May 2010) | 1 line fix extra 't' #8778 ........ ................ Modified: python/branches/release31-maint/ (props changed) python/branches/release31-maint/Doc/library/symtable.rst Modified: python/branches/release31-maint/Doc/library/symtable.rst ============================================================================== --- python/branches/release31-maint/Doc/library/symtable.rst (original) +++ python/branches/release31-maint/Doc/library/symtable.rst Fri May 21 00:34:00 2010 @@ -67,7 +67,7 @@ Return ``True`` if the block uses ``exec``. - .. method:: has_import_start() + .. method:: has_import_star() Return ``True`` if the block uses a starred from-import. From solipsis at pitrou.net Fri May 21 01:25:10 2010 From: solipsis at pitrou.net (solipsis at pitrou.net) Date: Fri, 21 May 2010 01:25:10 +0200 (CEST) Subject: [Python-checkins] Daily py3k reference leaks (r81375): sum=0 Message-ID: <20100520232510.BF86F1771F@ns6635.ovh.net> py3k results for svn r81375 (hg cset 68c84a6a6b0d) -------------------------------------------------- Command line was: ['./python', '-m', 'test.regrtest', '-uall', '-R', '3:3:/home/antoine/py3k/refleaks/reflog-jEhhg', '-x'] From python-checkins at python.org Fri May 21 03:40:36 2010 From: python-checkins at python.org (brett.cannon) Date: Fri, 21 May 2010 03:40:36 +0200 (CEST) Subject: [Python-checkins] r81389 - peps/trunk/pep-3148.txt Message-ID: <20100521014036.7DB53EE98A@mail.python.org> Author: brett.cannon Date: Fri May 21 03:40:36 2010 New Revision: 81389 Log: Specify the package name. Update from Brian Quinlan. Modified: peps/trunk/pep-3148.txt Modified: peps/trunk/pep-3148.txt ============================================================================== --- peps/trunk/pep-3148.txt (original) +++ peps/trunk/pep-3148.txt Fri May 21 03:40:36 2010 @@ -38,7 +38,7 @@ :: - import futures + from concurrent import futures import math PRIMES = [ @@ -68,7 +68,7 @@ :: - import futures + from concurrent import futures import urllib.request URLS = ['http://www.foxnews.com/', @@ -95,10 +95,11 @@ Interface --------- -The proposed package provides two core classes: `Executor` and -`Future`. An `Executor` receives asynchronous work requests (in terms -of a callable and its arguments) and returns a `Future` to represent -the execution of that work request. +The proposed package would be called "futures" and would live in a new +"concurrent" top-level package. It provides two core classes: `Executor` and +`Future`. An `Executor` receives asynchronous work requests (in terms of a +callable and its arguments) and returns a `Future` to represent the execution +of that work request. Executor '''''''' From python-checkins at python.org Fri May 21 10:34:08 2010 From: python-checkins at python.org (stefan.krah) Date: Fri, 21 May 2010 10:34:08 +0200 (CEST) Subject: [Python-checkins] r81390 - python/branches/py3k-cdecimal/Lib/test/decimal_extended_tests/deccheck.py Message-ID: <20100521083408.39FAAEE990@mail.python.org> Author: stefan.krah Date: Fri May 21 10:34:08 2010 New Revision: 81390 Log: 1) deccheck.py uses absolute imports. 2) Existing methods of the disagreement-handler object must be overridden. 3) Fix stale comment. Modified: python/branches/py3k-cdecimal/Lib/test/decimal_extended_tests/deccheck.py Modified: python/branches/py3k-cdecimal/Lib/test/decimal_extended_tests/deccheck.py ============================================================================== --- python/branches/py3k-cdecimal/Lib/test/decimal_extended_tests/deccheck.py (original) +++ python/branches/py3k-cdecimal/Lib/test/decimal_extended_tests/deccheck.py Fri May 21 10:34:08 2010 @@ -335,12 +335,16 @@ class dHandlerObj(): """For non-decimal return values: - Handle known disagreements between decimal.py and cdecimal.so. - Currently there are none.""" + Handle known disagreements between decimal.py and cdecimal.so.""" def __init__(self): pass + def default(self, result, operands): + return False + __ge__ = __gt__ = __le__ = __lt__ = __repr__ = __str__ = \ + __ne__ = __eq__ = default + if py_minor >= 2: def __hash__(self, result, operands): c = operands[0] @@ -350,12 +354,9 @@ # If a Decimal instance is exactly representable as a float # then (in 3.2) its hash matches that of the float. f = float(c.dec) - if Decimal.from_float(f) == c.dec: + if decimal.Decimal.from_float(f) == c.dec: return True - def default(self, result, operands): - return False - dhandler_cdec = dHandlerCdec() def cdec_known_disagreement(result, funcname, operands): @@ -366,7 +367,6 @@ return getattr(dhandler_obj, funcname, dhandler_obj.default)(result, operands) - def verify(result, funcname, operands): """Verifies that after operation 'funcname' with operand(s) 'operands' result[0] and result[1] as well as the context flags have the same From python-checkins at python.org Fri May 21 10:35:21 2010 From: python-checkins at python.org (stefan.krah) Date: Fri, 21 May 2010 10:35:21 +0200 (CEST) Subject: [Python-checkins] r81391 - python/branches/py3k-cdecimal/Lib/test/decimal_extended_tests/ctx-deccheck.py Message-ID: <20100521083521.60DE8EE990@mail.python.org> Author: stefan.krah Date: Fri May 21 10:35:21 2010 New Revision: 81391 Log: Existing methods of the disagreement-handler object must be overridden. Modified: python/branches/py3k-cdecimal/Lib/test/decimal_extended_tests/ctx-deccheck.py Modified: python/branches/py3k-cdecimal/Lib/test/decimal_extended_tests/ctx-deccheck.py ============================================================================== --- python/branches/py3k-cdecimal/Lib/test/decimal_extended_tests/ctx-deccheck.py (original) +++ python/branches/py3k-cdecimal/Lib/test/decimal_extended_tests/ctx-deccheck.py Fri May 21 10:35:21 2010 @@ -303,6 +303,8 @@ def default(self, result, operands): return False + __eq__ = __ne__ = __ge__ = __gt__ = __le__ = __lt__ = \ + __repr__ = __str__ = default dhandler_cdec = dHandlerCdec() @@ -314,7 +316,6 @@ # return getattr(dhandler_obj, funcname, dhandler_obj.default)(result, operands) - def verify(result, funcname, operands): """Verifies that after operation 'funcname' with operand(s) 'operands' result[0] and result[1] as well as the context flags have the same From python-checkins at python.org Fri May 21 11:56:06 2010 From: python-checkins at python.org (antoine.pitrou) Date: Fri, 21 May 2010 11:56:06 +0200 (CEST) Subject: [Python-checkins] r81392 - in python/branches/py3k: Doc/library/ssl.rst Lib/ssl.py Lib/test/test_ssl.py Misc/NEWS Modules/_ssl.c Message-ID: <20100521095606.5266BEE9B2@mail.python.org> Author: antoine.pitrou Date: Fri May 21 11:56:06 2010 New Revision: 81392 Log: Issue #4870: Add an `options` attribute to SSL contexts, as well as several ``OP_*`` constants to the `ssl` module. This allows to selectively disable protocol versions, when used in combination with `PROTOCOL_SSLv23`. Modified: python/branches/py3k/Doc/library/ssl.rst python/branches/py3k/Lib/ssl.py python/branches/py3k/Lib/test/test_ssl.py python/branches/py3k/Misc/NEWS python/branches/py3k/Modules/_ssl.c Modified: python/branches/py3k/Doc/library/ssl.rst ============================================================================== --- python/branches/py3k/Doc/library/ssl.rst (original) +++ python/branches/py3k/Doc/library/ssl.rst Fri May 21 11:56:06 2010 @@ -257,6 +257,37 @@ modern version, and probably the best choice for maximum protection, if both sides can speak it. +.. data:: OP_ALL + + Enables workarounds for various bugs present in other SSL implementations. + This option is set by default. + + .. versionadded:: 3.2 + +.. data:: OP_NO_SSLv2 + + Prevents an SSLv2 connection. This option is only applicable in + conjunction with :const:`PROTOCOL_SSLv23`. It prevents the peers from + choosing SSLv2 as the protocol version. + + .. versionadded:: 3.2 + +.. data:: OP_NO_SSLv3 + + Prevents an SSLv3 connection. This option is only applicable in + conjunction with :const:`PROTOCOL_SSLv23`. It prevents the peers from + choosing SSLv3 as the protocol version. + + .. versionadded:: 3.2 + +.. data:: OP_NO_TLSv1 + + Prevents a TLSv1 connection. This option is only applicable in + conjunction with :const:`PROTOCOL_SSLv23`. It prevents the peers from + choosing TLSv1 as the protocol version. + + .. versionadded:: 3.2 + .. data:: OPENSSL_VERSION The version string of the OpenSSL library loaded by the interpreter:: @@ -440,6 +471,17 @@ and *suppress_ragged_eofs* have the same meaning as in the top-level :func:`wrap_socket` function. +.. attribute:: SSLContext.options + + An integer representing the set of SSL options enabled on this context. + The default value is :data:`OP_ALL`, but you can specify other options + such as :data:`OP_NO_SSLv2` by ORing them together. + + .. note:: + With versions of OpenSSL older than 0.9.8m, it is only possible + to set options, not to clear them. Attempting to clear an option + (by resetting the corresponding bits) will raise a ``ValueError``. + .. attribute:: SSLContext.protocol The protocol version chosen when constructing the context. This attribute @@ -794,6 +836,20 @@ equivalent unless anonymous ciphers are enabled (they are disabled by default). +Protocol versions +^^^^^^^^^^^^^^^^^ + +SSL version 2 is considered insecure and is therefore dangerous to use. If +you want maximum compatibility between clients and servers, it is recommended +to use :const:`PROTOCOL_SSLv23` as the protocol version and then disable +SSLv2 explicitly using the :data:`SSLContext.options` attribute:: + + context = ssl.SSLContext(ssl.PROTOCOL_SSLv23) + context.options |= ssl.OP_NO_SSLv2 + +The SSL context created above will allow SSLv3 and TLSv1 connections, but +not SSLv2. + .. seealso:: Modified: python/branches/py3k/Lib/ssl.py ============================================================================== --- python/branches/py3k/Lib/ssl.py (original) +++ python/branches/py3k/Lib/ssl.py Fri May 21 11:56:06 2010 @@ -63,6 +63,7 @@ from _ssl import CERT_NONE, CERT_OPTIONAL, CERT_REQUIRED from _ssl import (PROTOCOL_SSLv2, PROTOCOL_SSLv3, PROTOCOL_SSLv23, PROTOCOL_TLSv1) +from _ssl import OP_ALL, OP_NO_SSLv2, OP_NO_SSLv3, OP_NO_TLSv1 from _ssl import RAND_status, RAND_egd, RAND_add from _ssl import ( SSL_ERROR_ZERO_RETURN, Modified: python/branches/py3k/Lib/test/test_ssl.py ============================================================================== --- python/branches/py3k/Lib/test/test_ssl.py (original) +++ python/branches/py3k/Lib/test/test_ssl.py Fri May 21 11:56:06 2010 @@ -57,6 +57,14 @@ if support.verbose: sys.stdout.write(prefix + exc_format) +def can_clear_options(): + # 0.9.8m or higher + return ssl.OPENSSL_VERSION_INFO >= (0, 9, 8, 13, 15) + +def no_sslv2_implies_sslv3_hello(): + # 0.9.7h or higher + return ssl.OPENSSL_VERSION_INFO >= (0, 9, 7, 8, 15) + class BasicSocketTests(unittest.TestCase): @@ -189,6 +197,26 @@ with self.assertRaisesRegexp(ssl.SSLError, "No cipher can be selected"): ctx.set_ciphers("^$:,;?*'dorothyx") + def test_options(self): + ctx = ssl.SSLContext(ssl.PROTOCOL_TLSv1) + # OP_ALL is the default value + self.assertEqual(ssl.OP_ALL, ctx.options) + ctx.options |= ssl.OP_NO_SSLv2 + self.assertEqual(ssl.OP_ALL | ssl.OP_NO_SSLv2, + ctx.options) + ctx.options |= ssl.OP_NO_SSLv3 + self.assertEqual(ssl.OP_ALL | ssl.OP_NO_SSLv2 | ssl.OP_NO_SSLv3, + ctx.options) + if can_clear_options(): + ctx.options = (ctx.options & ~ssl.OP_NO_SSLv2) | ssl.OP_NO_TLSv1 + self.assertEqual(ssl.OP_ALL | ssl.OP_NO_TLSv1 | ssl.OP_NO_SSLv3, + ctx.options) + ctx.options = 0 + self.assertEqual(0, ctx.options) + else: + with self.assertRaises(ValueError): + ctx.options = 0 + def test_verify(self): ctx = ssl.SSLContext(ssl.PROTOCOL_TLSv1) # Default value @@ -445,12 +473,8 @@ def wrap_conn(self): try: - self.sslconn = ssl.wrap_socket(self.sock, server_side=True, - certfile=self.server.certificate, - ssl_version=self.server.protocol, - ca_certs=self.server.cacerts, - cert_reqs=self.server.certreqs, - ciphers=self.server.ciphers) + self.sslconn = self.server.context.wrap_socket( + self.sock, server_side=True) except ssl.SSLError: # XXX Various errors can have happened here, for example # a mismatching protocol version, an invalid certificate, @@ -462,7 +486,7 @@ self.close() return False else: - if self.server.certreqs == ssl.CERT_REQUIRED: + if self.server.context.verify_mode == ssl.CERT_REQUIRED: cert = self.sslconn.getpeercert() if support.verbose and self.server.chatty: sys.stdout.write(" client cert is " + pprint.pformat(cert) + "\n") @@ -542,19 +566,24 @@ # harness, we want to stop the server self.server.stop() - def __init__(self, certificate, ssl_version=None, + def __init__(self, certificate=None, ssl_version=None, certreqs=None, cacerts=None, chatty=True, connectionchatty=False, starttls_server=False, - ciphers=None): - if ssl_version is None: - ssl_version = ssl.PROTOCOL_TLSv1 - if certreqs is None: - certreqs = ssl.CERT_NONE - self.certificate = certificate - self.protocol = ssl_version - self.certreqs = certreqs - self.cacerts = cacerts - self.ciphers = ciphers + ciphers=None, context=None): + if context: + self.context = context + else: + self.context = ssl.SSLContext(ssl_version + if ssl_version is not None + else ssl.PROTOCOL_TLSv1) + self.context.verify_mode = (certreqs if certreqs is not None + else ssl.CERT_NONE) + if cacerts: + self.context.load_verify_locations(cacerts) + if certificate: + self.context.load_cert_chain(certificate) + if ciphers: + self.context.set_ciphers(ciphers) self.chatty = chatty self.connectionchatty = connectionchatty self.starttls_server = starttls_server @@ -820,18 +849,13 @@ server.stop() server.join() - def server_params_test(certfile, protocol, certreqs, cacertsfile, - client_certfile, client_protocol=None, indata=b"FOO\n", - ciphers=None, chatty=True, connectionchatty=False): + def server_params_test(client_context, server_context, indata=b"FOO\n", + chatty=True, connectionchatty=False): """ Launch a server, connect a client to it and try various reads and writes. """ - server = ThreadedEchoServer(certfile, - certreqs=certreqs, - ssl_version=protocol, - cacerts=cacertsfile, - ciphers=ciphers, + server = ThreadedEchoServer(context=server_context, chatty=chatty, connectionchatty=False) flag = threading.Event() @@ -839,15 +863,8 @@ # wait for it to start flag.wait() # try to connect - if client_protocol is None: - client_protocol = protocol try: - s = ssl.wrap_socket(socket.socket(), - certfile=client_certfile, - ca_certs=cacertsfile, - ciphers=ciphers, - cert_reqs=certreqs, - ssl_version=client_protocol) + s = client_context.wrap_socket(socket.socket()) s.connect((HOST, server.port)) for arg in [indata, bytearray(indata), memoryview(indata)]: if connectionchatty: @@ -873,10 +890,8 @@ server.stop() server.join() - def try_protocol_combo(server_protocol, - client_protocol, - expect_success, - certsreqs=None): + def try_protocol_combo(server_protocol, client_protocol, expect_success, + certsreqs=None, server_options=0, client_options=0): if certsreqs is None: certsreqs = ssl.CERT_NONE certtype = { @@ -890,14 +905,21 @@ (ssl.get_protocol_name(client_protocol), ssl.get_protocol_name(server_protocol), certtype)) - try: + client_context = ssl.SSLContext(client_protocol) + client_context.options = ssl.OP_ALL | client_options + server_context = ssl.SSLContext(server_protocol) + server_context.options = ssl.OP_ALL | server_options + for ctx in (client_context, server_context): + ctx.verify_mode = certsreqs # NOTE: we must enable "ALL" ciphers, otherwise an SSLv23 client # will send an SSLv3 hello (rather than SSLv2) starting from # OpenSSL 1.0.0 (see issue #8322). - server_params_test(CERTFILE, server_protocol, certsreqs, - CERTFILE, CERTFILE, client_protocol, - ciphers="ALL", chatty=False, - connectionchatty=False) + ctx.set_ciphers("ALL") + ctx.load_cert_chain(CERTFILE) + ctx.load_verify_locations(CERTFILE) + try: + server_params_test(client_context, server_context, + chatty=False, connectionchatty=False) # Protocol mismatch can result in either an SSLError, or a # "Connection reset by peer" error. except ssl.SSLError: @@ -920,30 +942,27 @@ """Basic test of an SSL client connecting to a server""" if support.verbose: sys.stdout.write("\n") - server_params_test(CERTFILE, ssl.PROTOCOL_TLSv1, ssl.CERT_NONE, - CERTFILE, CERTFILE, ssl.PROTOCOL_TLSv1, - chatty=True, connectionchatty=True) + for protocol in PROTOCOLS: + context = ssl.SSLContext(protocol) + context.load_cert_chain(CERTFILE) + server_params_test(context, context, + chatty=True, connectionchatty=True) def test_getpeercert(self): if support.verbose: sys.stdout.write("\n") - s2 = socket.socket() - server = ThreadedEchoServer(CERTFILE, - certreqs=ssl.CERT_NONE, - ssl_version=ssl.PROTOCOL_SSLv23, - cacerts=CERTFILE, - chatty=False) + context = ssl.SSLContext(ssl.PROTOCOL_SSLv23) + context.verify_mode = ssl.CERT_REQUIRED + context.load_verify_locations(CERTFILE) + context.load_cert_chain(CERTFILE) + server = ThreadedEchoServer(context=context, chatty=False) flag = threading.Event() server.start(flag) # wait for it to start flag.wait() # try to connect try: - s = ssl.wrap_socket(socket.socket(), - certfile=CERTFILE, - ca_certs=CERTFILE, - cert_reqs=ssl.CERT_REQUIRED, - ssl_version=ssl.PROTOCOL_SSLv23) + s = context.wrap_socket(socket.socket()) s.connect((HOST, server.port)) cert = s.getpeercert() self.assertTrue(cert, "Can't get peer certificate.") @@ -1031,6 +1050,15 @@ try_protocol_combo(ssl.PROTOCOL_SSLv2, ssl.PROTOCOL_SSLv23, True) try_protocol_combo(ssl.PROTOCOL_SSLv2, ssl.PROTOCOL_SSLv3, False) try_protocol_combo(ssl.PROTOCOL_SSLv2, ssl.PROTOCOL_TLSv1, False) + # SSLv23 client with specific SSL options + if no_sslv2_implies_sslv3_hello(): + # No SSLv2 => client will use an SSLv3 hello on recent OpenSSLs + try_protocol_combo(ssl.PROTOCOL_SSLv2, ssl.PROTOCOL_SSLv23, False, + client_options=ssl.OP_NO_SSLv2) + try_protocol_combo(ssl.PROTOCOL_SSLv2, ssl.PROTOCOL_SSLv23, True, + client_options=ssl.OP_NO_SSLv3) + try_protocol_combo(ssl.PROTOCOL_SSLv2, ssl.PROTOCOL_SSLv23, True, + client_options=ssl.OP_NO_TLSv1) def test_protocol_sslv23(self): """Connecting to an SSLv23 server with various client options""" @@ -1056,6 +1084,16 @@ try_protocol_combo(ssl.PROTOCOL_SSLv23, ssl.PROTOCOL_SSLv23, True, ssl.CERT_REQUIRED) try_protocol_combo(ssl.PROTOCOL_SSLv23, ssl.PROTOCOL_TLSv1, True, ssl.CERT_REQUIRED) + # Server with specific SSL options + try_protocol_combo(ssl.PROTOCOL_SSLv23, ssl.PROTOCOL_SSLv3, False, + server_options=ssl.OP_NO_SSLv3) + # Will choose TLSv1 + try_protocol_combo(ssl.PROTOCOL_SSLv23, ssl.PROTOCOL_SSLv23, True, + server_options=ssl.OP_NO_SSLv2 | ssl.OP_NO_SSLv3) + try_protocol_combo(ssl.PROTOCOL_SSLv23, ssl.PROTOCOL_TLSv1, False, + server_options=ssl.OP_NO_TLSv1) + + def test_protocol_sslv3(self): """Connecting to an SSLv3 server with various client options""" if support.verbose: @@ -1066,6 +1104,10 @@ try_protocol_combo(ssl.PROTOCOL_SSLv3, ssl.PROTOCOL_SSLv2, False) try_protocol_combo(ssl.PROTOCOL_SSLv3, ssl.PROTOCOL_SSLv23, False) try_protocol_combo(ssl.PROTOCOL_SSLv3, ssl.PROTOCOL_TLSv1, False) + if no_sslv2_implies_sslv3_hello(): + # No SSLv2 => client will use an SSLv3 hello on recent OpenSSLs + try_protocol_combo(ssl.PROTOCOL_SSLv3, ssl.PROTOCOL_SSLv23, True, + client_options=ssl.OP_NO_SSLv2) def test_protocol_tlsv1(self): """Connecting to a TLSv1 server with various client options""" Modified: python/branches/py3k/Misc/NEWS ============================================================================== --- python/branches/py3k/Misc/NEWS (original) +++ python/branches/py3k/Misc/NEWS Fri May 21 11:56:06 2010 @@ -375,6 +375,10 @@ Library ------- +- Issue #4870: Add an `options` attribute to SSL contexts, as well as + several ``OP_*`` constants to the `ssl` module. This allows to selectively + disable protocol versions, when used in combination with `PROTOCOL_SSLv23`. + - Issue #8759: Fixed user paths in sysconfig for posix and os2 schemes. - Issue #8663: distutils.log emulates backslashreplace error handler. Fix Modified: python/branches/py3k/Modules/_ssl.c ============================================================================== --- python/branches/py3k/Modules/_ssl.c (original) +++ python/branches/py3k/Modules/_ssl.c Fri May 21 11:56:06 2010 @@ -113,6 +113,13 @@ # undef HAVE_OPENSSL_RAND #endif +/* SSL_CTX_clear_options() and SSL_clear_options() were first added in OpenSSL 0.9.8m */ +#if OPENSSL_VERSION_NUMBER >= 0x009080dfL +# define HAVE_SSL_CTX_CLEAR_OPTIONS +#else +# undef HAVE_SSL_CTX_CLEAR_OPTIONS +#endif + typedef struct { PyObject_HEAD SSL_CTX *ctx; @@ -1514,6 +1521,35 @@ } static PyObject * +get_options(PySSLContext *self, void *c) +{ + return PyLong_FromLong(SSL_CTX_get_options(self->ctx)); +} + +static int +set_options(PySSLContext *self, PyObject *arg, void *c) +{ + long new_opts, opts, set, clear; + if (!PyArg_Parse(arg, "l", &new_opts)) + return -1; + opts = SSL_CTX_get_options(self->ctx); + clear = opts & ~new_opts; + set = ~opts & new_opts; + if (clear) { +#ifdef HAVE_SSL_CTX_CLEAR_OPTIONS + SSL_CTX_clear_options(self->ctx, clear); +#else + PyErr_SetString(PyExc_ValueError, + "can't clear options before OpenSSL 0.9.8m"); + return -1; +#endif + } + if (set) + SSL_CTX_set_options(self->ctx, set); + return 0; +} + +static PyObject * load_cert_chain(PySSLContext *self, PyObject *args, PyObject *kwds) { char *kwlist[] = {"certfile", "keyfile", NULL}; @@ -1636,6 +1672,8 @@ } static PyGetSetDef context_getsetlist[] = { + {"options", (getter) get_options, + (setter) set_options, NULL}, {"verify_mode", (getter) get_verify_mode, (setter) set_verify_mode, NULL}, {NULL}, /* sentinel */ @@ -1953,6 +1991,12 @@ PyModule_AddIntConstant(m, "PROTOCOL_TLSv1", PY_SSL_VERSION_TLS1); + /* protocol options */ + PyModule_AddIntConstant(m, "OP_ALL", SSL_OP_ALL); + PyModule_AddIntConstant(m, "OP_NO_SSLv2", SSL_OP_NO_SSLv2); + PyModule_AddIntConstant(m, "OP_NO_SSLv3", SSL_OP_NO_SSLv3); + PyModule_AddIntConstant(m, "OP_NO_TLSv1", SSL_OP_NO_TLSv1); + /* OpenSSL version */ /* SSLeay() gives us the version of the library linked against, which could be different from the headers version. From python-checkins at python.org Fri May 21 12:52:08 2010 From: python-checkins at python.org (victor.stinner) Date: Fri, 21 May 2010 12:52:08 +0200 (CEST) Subject: [Python-checkins] r81393 - in python/branches/py3k: Lib/tabnanny.py Misc/NEWS Message-ID: <20100521105208.D7161EE9B3@mail.python.org> Author: victor.stinner Date: Fri May 21 12:52:08 2010 New Revision: 81393 Log: Issue #8774: tabnanny uses the encoding cookie (#coding:...) to use the correct encoding Modified: python/branches/py3k/Lib/tabnanny.py python/branches/py3k/Misc/NEWS Modified: python/branches/py3k/Lib/tabnanny.py ============================================================================== --- python/branches/py3k/Lib/tabnanny.py (original) +++ python/branches/py3k/Lib/tabnanny.py Fri May 21 12:52:08 2010 @@ -93,8 +93,11 @@ check(fullname) return + with open(file, 'rb') as f: + encoding, lines = tokenize.detect_encoding(f.readline) + try: - f = open(file) + f = open(file, encoding=encoding) except IOError as msg: errprint("%r: I/O Error: %s" % (file, msg)) return Modified: python/branches/py3k/Misc/NEWS ============================================================================== --- python/branches/py3k/Misc/NEWS (original) +++ python/branches/py3k/Misc/NEWS Fri May 21 12:52:08 2010 @@ -375,7 +375,10 @@ Library ------- -- Issue #4870: Add an `options` attribute to SSL contexts, as well as +- Issue #8774: tabnanny uses the encoding cookie (#coding:...) to use the + correct encoding + +- Issue #4870: Add an `options` attribute to SSL contexts, as well as several ``OP_*`` constants to the `ssl` module. This allows to selectively disable protocol versions, when used in combination with `PROTOCOL_SSLv23`. From python-checkins at python.org Fri May 21 12:53:33 2010 From: python-checkins at python.org (victor.stinner) Date: Fri, 21 May 2010 12:53:33 +0200 (CEST) Subject: [Python-checkins] r81394 - in python/branches/release31-maint: Lib/tabnanny.py Misc/NEWS Message-ID: <20100521105333.05F9DEE9B8@mail.python.org> Author: victor.stinner Date: Fri May 21 12:53:32 2010 New Revision: 81394 Log: Merged revisions 81393 via svnmerge from svn+ssh://pythondev at svn.python.org/python/branches/py3k ........ r81393 | victor.stinner | 2010-05-21 12:52:08 +0200 (ven., 21 mai 2010) | 3 lines Issue #8774: tabnanny uses the encoding cookie (#coding:...) to use the correct encoding ........ Modified: python/branches/release31-maint/ (props changed) python/branches/release31-maint/Lib/tabnanny.py python/branches/release31-maint/Misc/NEWS Modified: python/branches/release31-maint/Lib/tabnanny.py ============================================================================== --- python/branches/release31-maint/Lib/tabnanny.py (original) +++ python/branches/release31-maint/Lib/tabnanny.py Fri May 21 12:53:32 2010 @@ -93,8 +93,11 @@ check(fullname) return + with open(file, 'rb') as f: + encoding, lines = tokenize.detect_encoding(f.readline) + try: - f = open(file) + f = open(file, encoding=encoding) except IOError as msg: errprint("%r: I/O Error: %s" % (file, msg)) return Modified: python/branches/release31-maint/Misc/NEWS ============================================================================== --- python/branches/release31-maint/Misc/NEWS (original) +++ python/branches/release31-maint/Misc/NEWS Fri May 21 12:53:32 2010 @@ -46,6 +46,9 @@ Library ------- +- Issue #8774: tabnanny uses the encoding cookie (#coding:...) to use the + correct encoding + - Issue #7507: Quote "!" in pipes.quote(); it is special to some shells. - Issue #8663: distutils.log emulates backslashreplace error handler. Fix From nnorwitz at gmail.com Fri May 21 14:01:40 2010 From: nnorwitz at gmail.com (Neal Norwitz) Date: Fri, 21 May 2010 08:01:40 -0400 Subject: [Python-checkins] Python Regression Test Failures all (1) Message-ID: <20100521120140.GA1773@kbk-i386-bb.psfb.org> 352 tests OK. 1 test failed: test_subprocess 28 tests skipped: test_aepack test_al test_applesingle test_bsddb185 test_cd test_cl test_epoll test_gdb test_gl test_imgfile test_ioctl test_kqueue test_macos test_macostools test_multiprocessing test_pep277 test_py3kwarn test_scriptpackages test_startfile test_sunaudiodev test_tcl test_tk test_ttk_guionly test_ttk_textonly test_unicode_file test_winreg test_winsound test_zipfile64 7 skips unexpected on linux2: test_epoll test_gdb test_ioctl test_multiprocessing test_tk test_ttk_guionly test_ttk_textonly == CPython 2.7b2+ (trunk:81389M, May 21 2010, 04:01:39) [GCC 3.3.4 20040623 (Gentoo Linux 3.3.4-r1, ssp-3.3.2-2, pie-8.7.6)] == Linux-2.6.9-gentoo-r1-i686-AMD_Athlon-tm-_XP_3000+-with-gentoo-1.4.16 little-endian == /tmp/test_python_2792 test_grammar test_opcodes test_dict test_builtin test_exceptions test_types test_unittest test_doctest test_doctest2 test_MimeWriter test_SimpleHTTPServer test_StringIO test___all__ test___future__ test__locale test_abc test_abstract_numbers test_aepack test_aepack skipped -- No module named aetypes test_aifc test_al test_al skipped -- No module named al test_anydbm test_applesingle test_applesingle skipped -- No module named MacOS test_argparse test_array test_ascii_formatd test_ast test_asynchat test_asyncore test_atexit test_audioop test_augassign test_base64 test_bastion test_bigaddrspace test_bigmem test_binascii test_binhex test_binop test_bisect test_bool test_bsddb test_bsddb185 test_bsddb185 skipped -- No module named bsddb185 test_bsddb3 Sleepycat Software: Berkeley DB 4.1.25: (December 19, 2002) Test path prefix: /tmp/z-test_bsddb3-2792 test_buffer test_bufio test_bytes test_bz2 test_calendar test_call test_capi test_cd test_cd skipped -- No module named cd test_cfgparser test_cgi test_charmapcodec test_cl test_cl skipped -- No module named cl test_class test_cmath test_cmd test_cmd_line test_cmd_line_script test_code test_codeccallbacks test_codecencodings_cn test_codecencodings_hk test_codecencodings_jp test_codecencodings_kr test_codecencodings_tw test_codecmaps_cn test_codecmaps_hk test_codecmaps_jp test_codecmaps_kr test_codecmaps_tw test_codecs test_codeop test_coding test_coercion test_collections test_colorsys test_commands test_compare test_compile test_compileall test_compiler testCompileLibrary still working, be patient... testCompileLibrary still working, be patient... test_complex test_complex_args test_contains test_contextlib test_cookie test_cookielib test_copy test_copy_reg test_cpickle test_cprofile test_crypt test_csv test_ctypes test_datetime test_dbm test_decimal test_decorators test_defaultdict test_deque test_descr test_descrtut test_dictcomps test_dictviews test_difflib test_dircache test_dis test_distutils [20646 refs] test_dl test_docxmlrpc test_dumbdbm test_dummy_thread test_dummy_threading test_email test_email_codecs test_email_renamed test_enumerate test_eof test_epoll test_epoll skipped -- kernel doesn't support epoll() test_errno test_exception_variations test_extcall test_fcntl test_file test_file2k test_filecmp test_fileinput test_fileio test_float test_fnmatch test_fork1 test_format test_fpformat test_fractions test_frozen test_ftplib test_funcattrs test_functools test_future test_future3 test_future4 test_future5 test_future_builtins test_gc test_gdb test_gdb skipped -- gdb versions before 7.0 didn't support python embedding Saw: GNU gdb 6.2.1 Copyright 2004 Free Software Foundation, Inc. GDB is free software, covered by the GNU General Public License, and you are welcome to change it and/or distribute copies of it under certain conditions. Type "show copying" to see the conditions. There is absolutely no warranty for GDB. Type "show warranty" for details. This GDB was configured as "i386-pc-linux-gnu". test_gdbm test_generators test_genericpath test_genexps test_getargs test_getargs2 test_getopt test_gettext test_gl test_gl skipped -- No module named gl test_glob test_global test_grp test_gzip test_hash test_hashlib test_heapq test_hmac test_hotshot test_htmllib test_htmlparser test_httplib test_httpservers [16651 refs] [16651 refs] [16651 refs] [26939 refs] test_imageop test_imaplib test_imgfile test_imgfile skipped -- No module named imgfile test_imp test_import test_importhooks test_importlib test_index test_inspect test_int test_int_literal test_io test_ioctl test_ioctl skipped -- Unable to open /dev/tty test_isinstance test_iter test_iterlen test_itertools test_json test_kqueue test_kqueue skipped -- test works only on BSD test_largefile test_lib2to3 test_linecache test_list test_locale test_logging test_long test_long_future test_longexp test_macos test_macos skipped -- No module named MacOS test_macostools test_macostools skipped -- No module named MacOS test_macpath test_mailbox test_marshal test_math test_md5 test_memoryio test_memoryview test_mhlib test_mimetools test_mimetypes test_minidom test_mmap test_module test_modulefinder test_multibytecodec test_multibytecodec_support test_multifile test_multiprocessing test_multiprocessing skipped -- This platform lacks a functioning sem_open implementation, therefore, the required synchronization primitives needed will not function, see issue 3770. test_mutants test_mutex test_netrc test_new test_nis test_normalization test_ntpath test_old_mailbox test_openpty test_operator test_optparse test_os [16651 refs] [16651 refs] test_parser Expecting 's_push: parser stack overflow' in next line s_push: parser stack overflow test_pdb test_peepholer test_pep247 test_pep263 test_pep277 test_pep277 skipped -- only NT+ and systems with Unicode-friendly filesystem encoding test_pep292 test_pep352 test_pickle test_pickletools test_pipes test_pkg test_pkgimport test_pkgutil test_platform [18047 refs] [18047 refs] test_plistlib test_poll test_popen [16656 refs] [16656 refs] [16656 refs] test_popen2 test_poplib test_posix test_posixpath test_pow test_pprint test_print test_profile test_profilehooks test_property test_pstats test_pty test_pwd test_py3kwarn test_py3kwarn skipped -- test.test_py3kwarn must be run with the -3 flag test_pyclbr test_pydoc [21863 refs] [21863 refs] [21863 refs] [21863 refs] [21863 refs] [21862 refs] [21862 refs] test_pyexpat test_queue test_quopri [19480 refs] [19480 refs] test_random test_re test_readline test_repr test_resource test_rfc822 test_richcmp test_robotparser test_runpy test_sax test_scope test_scriptpackages test_scriptpackages skipped -- No module named aetools test_select test_set test_setcomps test_sets test_sgmllib test_sha test_shelve test_shlex test_shutil test_signal test_site [16651 refs] [16651 refs] [16651 refs] [16651 refs] test_slice test_smtplib test_smtpnet test_socket test_socketserver test_softspace test_sort test_sqlite test_ssl test_startfile test_startfile skipped -- module os has no attribute startfile test_str test_strftime test_string test_stringprep test_strop test_strptime test_strtod test_struct test_structmembers test_structseq test_subprocess [16651 refs] [16651 refs] [16651 refs] [16651 refs] [16651 refs] [16651 refs] [16651 refs] [16651 refs] [16651 refs] [16651 refs] [16651 refs] [16651 refs] [16651 refs] [16651 refs] [16866 refs] [16651 refs] [16651 refs] [16651 refs] [16651 refs] [16651 refs] . [16651 refs] [16651 refs] this bit of output is from a test of stdout in a different process ... [16651 refs] [16651 refs] [16866 refs] [16651 refs] [16651 refs] [16651 refs] p.send_signal(2,) succeeded after 3 attempts [16651 refs] [16651 refs] [16651 refs] [16651 refs] [16651 refs] [16651 refs] [16651 refs] [16651 refs] [16651 refs] [16651 refs] [16651 refs] [16651 refs] [16651 refs] [16651 refs] [16866 refs] [16651 refs] [16651 refs] [16651 refs] [16651 refs] [16651 refs] . [16651 refs] [16651 refs] this bit of output is from a test of stdout in a different process ... [16651 refs] [16651 refs] [16866 refs] test test_subprocess failed -- multiple errors occurred; run in verbose mode for details Re-running test 'test_subprocess' in verbose mode test_call_kwargs (test.test_subprocess.ProcessTestCase) ... [16651 refs] ERROR test_call_seq (test.test_subprocess.ProcessTestCase) ... [16651 refs] ERROR test_check_call_nonzero (test.test_subprocess.ProcessTestCase) ... [16651 refs] ERROR test_check_call_zero (test.test_subprocess.ProcessTestCase) ... [16651 refs] ERROR test_check_output (test.test_subprocess.ProcessTestCase) ... [16651 refs] ERROR test_check_output_nonzero (test.test_subprocess.ProcessTestCase) ... [16651 refs] ERROR test_check_output_stderr (test.test_subprocess.ProcessTestCase) ... ERROR test_check_output_stdout_arg (test.test_subprocess.ProcessTestCase) ... ERROR test_communicate (test.test_subprocess.ProcessTestCase) ... ERROR test_communicate_pipe_buf (test.test_subprocess.ProcessTestCase) ... ERROR test_communicate_pipe_fd_leak (test.test_subprocess.ProcessTestCase) ... [16651 refs] ERROR test_communicate_returns (test.test_subprocess.ProcessTestCase) ... [16651 refs] ERROR test_communicate_stderr (test.test_subprocess.ProcessTestCase) ... ERROR test_communicate_stdin (test.test_subprocess.ProcessTestCase) ... [16651 refs] ERROR test_communicate_stdout (test.test_subprocess.ProcessTestCase) ... [16651 refs] ERROR test_cwd (test.test_subprocess.ProcessTestCase) ... [16651 refs] ERROR test_env (test.test_subprocess.ProcessTestCase) ... [16651 refs] ERROR test_executable_with_cwd (test.test_subprocess.ProcessTestCase) ... [16651 refs] ERROR test_executable_without_cwd (test.test_subprocess.ProcessTestCase) ... [16651 refs] ERROR test_invalid_bufsize (test.test_subprocess.ProcessTestCase) ... ERROR test_leaking_fds_on_error (test.test_subprocess.ProcessTestCase) ... ERROR test_list2cmdline (test.test_subprocess.ProcessTestCase) ... ERROR test_no_leaking (test.test_subprocess.ProcessTestCase) ... ERROR test_poll (test.test_subprocess.ProcessTestCase) ... [16866 refs] ERROR test_stderr_filedes (test.test_subprocess.ProcessTestCase) ... ERROR test_stderr_fileobj (test.test_subprocess.ProcessTestCase) ... ERROR test_stderr_none (test.test_subprocess.ProcessTestCase) ... [16651 refs] ERROR test_stderr_pipe (test.test_subprocess.ProcessTestCase) ... ERROR test_stdin_filedes (test.test_subprocess.ProcessTestCase) ... [16651 refs] ERROR test_stdin_fileobj (test.test_subprocess.ProcessTestCase) ... [16651 refs] ERROR test_stdin_none (test.test_subprocess.ProcessTestCase) ... ERROR test_stdin_pipe (test.test_subprocess.ProcessTestCase) ... [16651 refs] ERROR test_stdout_filedes (test.test_subprocess.ProcessTestCase) ... [16651 refs] ERROR test_stdout_filedes_of_stdout (test.test_subprocess.ProcessTestCase) ... . [16651 refs] ERROR test_stdout_fileobj (test.test_subprocess.ProcessTestCase) ... [16651 refs] ERROR test_stdout_none (test.test_subprocess.ProcessTestCase) ... this bit of output is from a test of stdout in a different process ... ERROR test_stdout_pipe (test.test_subprocess.ProcessTestCase) ... [16651 refs] ERROR test_stdout_stderr_file (test.test_subprocess.ProcessTestCase) ... ERROR test_stdout_stderr_pipe (test.test_subprocess.ProcessTestCase) ... ERROR test_universal_newlines (test.test_subprocess.ProcessTestCase) ... [16651 refs] ERROR test_universal_newlines_communicate (test.test_subprocess.ProcessTestCase) ... ERROR test_wait (test.test_subprocess.ProcessTestCase) ... [16866 refs] ERROR test_writes_before_communicate (test.test_subprocess.ProcessTestCase) ... ERROR test_args_string (test.test_subprocess.POSIXProcessTestCase) ... [16651 refs] ERROR test_call_string (test.test_subprocess.POSIXProcessTestCase) ... [16651 refs] ERROR test_exceptions (test.test_subprocess.POSIXProcessTestCase) ... ERROR test_invalid_args (test.test_subprocess.POSIXProcessTestCase) ... ERROR test_kill (test.test_subprocess.POSIXProcessTestCase) ... ERROR test_preexec (test.test_subprocess.POSIXProcessTestCase) ... [16651 refs] ERROR test_run_abort (test.test_subprocess.POSIXProcessTestCase) ... ERROR test_send_signal (test.test_subprocess.POSIXProcessTestCase) ... ERROR test_shell_sequence (test.test_subprocess.POSIXProcessTestCase) ... ERROR test_shell_string (test.test_subprocess.POSIXProcessTestCase) ... ERROR test_terminate (test.test_subprocess.POSIXProcessTestCase) ... ERROR test_call_string (test.test_subprocess.Win32ProcessTestCase) ... skipped 'Windows specific tests' test_close_fds (test.test_subprocess.Win32ProcessTestCase) ... skipped 'Windows specific tests' test_creationflags (test.test_subprocess.Win32ProcessTestCase) ... skipped 'Windows specific tests' test_invalid_args (test.test_subprocess.Win32ProcessTestCase) ... skipped 'Windows specific tests' test_kill (test.test_subprocess.Win32ProcessTestCase) ... skipped 'Windows specific tests' test_send_signal (test.test_subprocess.Win32ProcessTestCase) ... skipped 'Windows specific tests' test_shell_sequence (test.test_subprocess.Win32ProcessTestCase) ... skipped 'Windows specific tests' test_shell_string (test.test_subprocess.Win32ProcessTestCase) ... skipped 'Windows specific tests' test_startupinfo (test.test_subprocess.Win32ProcessTestCase) ... skipped 'Windows specific tests' test_terminate (test.test_subprocess.Win32ProcessTestCase) ... skipped 'Windows specific tests' test_call_kwargs (test.test_subprocess.ProcessTestCaseNoPoll) ... [16651 refs] ERROR test_call_seq (test.test_subprocess.ProcessTestCaseNoPoll) ... [16651 refs] ERROR test_check_call_nonzero (test.test_subprocess.ProcessTestCaseNoPoll) ... [16651 refs] ERROR test_check_call_zero (test.test_subprocess.ProcessTestCaseNoPoll) ... [16651 refs] ERROR test_check_output (test.test_subprocess.ProcessTestCaseNoPoll) ... [16651 refs] ERROR test_check_output_nonzero (test.test_subprocess.ProcessTestCaseNoPoll) ... [16651 refs] ERROR test_check_output_stderr (test.test_subprocess.ProcessTestCaseNoPoll) ... ERROR test_check_output_stdout_arg (test.test_subprocess.ProcessTestCaseNoPoll) ... ERROR test_communicate (test.test_subprocess.ProcessTestCaseNoPoll) ... ERROR test_communicate_pipe_buf (test.test_subprocess.ProcessTestCaseNoPoll) ... ERROR test_communicate_pipe_fd_leak (test.test_subprocess.ProcessTestCaseNoPoll) ... [16651 refs] ERROR test_communicate_returns (test.test_subprocess.ProcessTestCaseNoPoll) ... [16651 refs] ERROR test_communicate_stderr (test.test_subprocess.ProcessTestCaseNoPoll) ... ERROR test_communicate_stdin (test.test_subprocess.ProcessTestCaseNoPoll) ... [16651 refs] ERROR test_communicate_stdout (test.test_subprocess.ProcessTestCaseNoPoll) ... [16651 refs] ERROR test_cwd (test.test_subprocess.ProcessTestCaseNoPoll) ... [16651 refs] ERROR test_env (test.test_subprocess.ProcessTestCaseNoPoll) ... [16651 refs] ERROR test_executable_with_cwd (test.test_subprocess.ProcessTestCaseNoPoll) ... [16651 refs] ERROR test_executable_without_cwd (test.test_subprocess.ProcessTestCaseNoPoll) ... [16651 refs] ERROR test_invalid_bufsize (test.test_subprocess.ProcessTestCaseNoPoll) ... ERROR test_leaking_fds_on_error (test.test_subprocess.ProcessTestCaseNoPoll) ... ERROR test_list2cmdline (test.test_subprocess.ProcessTestCaseNoPoll) ... ERROR test_no_leaking (test.test_subprocess.ProcessTestCaseNoPoll) ... ERROR test_poll (test.test_subprocess.ProcessTestCaseNoPoll) ... [16866 refs] ERROR test_stderr_filedes (test.test_subprocess.ProcessTestCaseNoPoll) ... ERROR test_stderr_fileobj (test.test_subprocess.ProcessTestCaseNoPoll) ... ERROR test_stderr_none (test.test_subprocess.ProcessTestCaseNoPoll) ... [16651 refs] ERROR test_stderr_pipe (test.test_subprocess.ProcessTestCaseNoPoll) ... ERROR test_stdin_filedes (test.test_subprocess.ProcessTestCaseNoPoll) ... [16651 refs] ERROR test_stdin_fileobj (test.test_subprocess.ProcessTestCaseNoPoll) ... [16651 refs] ERROR test_stdin_none (test.test_subprocess.ProcessTestCaseNoPoll) ... ERROR test_stdin_pipe (test.test_subprocess.ProcessTestCaseNoPoll) ... [16651 refs] ERROR test_stdout_filedes (test.test_subprocess.ProcessTestCaseNoPoll) ... [16651 refs] ERROR test_stdout_filedes_of_stdout (test.test_subprocess.ProcessTestCaseNoPoll) ... . [16651 refs] ERROR test_stdout_fileobj (test.test_subprocess.ProcessTestCaseNoPoll) ... [16651 refs] ERROR test_stdout_none (test.test_subprocess.ProcessTestCaseNoPoll) ... this bit of output is from a test of stdout in a different process ... ERROR test_stdout_pipe (test.test_subprocess.ProcessTestCaseNoPoll) ... [16651 refs] ERROR test_stdout_stderr_file (test.test_subprocess.ProcessTestCaseNoPoll) ... ERROR test_stdout_stderr_pipe (test.test_subprocess.ProcessTestCaseNoPoll) ... ERROR test_universal_newlines (test.test_subprocess.ProcessTestCaseNoPoll) ... [16651 refs] ERROR test_universal_newlines_communicate (test.test_subprocess.ProcessTestCaseNoPoll) ... ERROR test_wait (test.test_subprocess.ProcessTestCaseNoPoll) ... [16866 refs] ERROR test_writes_before_communicate (test.test_subprocess.ProcessTestCaseNoPoll) ... ERROR test_eintr_retry_call (test.test_subprocess.HelperFunctionTests) ... ok ====================================================================== ERROR: test_call_kwargs (test.test_subprocess.ProcessTestCase) ---------------------------------------------------------------------- Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/test_subprocess.py", line 46, in tearDown self.assertFalse(subprocess._active, "subprocess._active not empty") AssertionError: subprocess._active not empty ====================================================================== ERROR: test_call_seq (test.test_subprocess.ProcessTestCase) ---------------------------------------------------------------------- Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/test_subprocess.py", line 46, in tearDown self.assertFalse(subprocess._active, "subprocess._active not empty") AssertionError: subprocess._active not empty ====================================================================== ERROR: test_check_call_nonzero (test.test_subprocess.ProcessTestCase) ---------------------------------------------------------------------- Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/test_subprocess.py", line 46, in tearDown self.assertFalse(subprocess._active, "subprocess._active not empty") AssertionError: subprocess._active not empty ====================================================================== ERROR: test_check_call_zero (test.test_subprocess.ProcessTestCase) ---------------------------------------------------------------------- Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/test_subprocess.py", line 46, in tearDown self.assertFalse(subprocess._active, "subprocess._active not empty") AssertionError: subprocess._active not empty ====================================================================== ERROR: test_check_output (test.test_subprocess.ProcessTestCase) ---------------------------------------------------------------------- Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/test_subprocess.py", line 46, in tearDown self.assertFalse(subprocess._active, "subprocess._active not empty") AssertionError: subprocess._active not empty ====================================================================== ERROR: test_check_output_nonzero (test.test_subprocess.ProcessTestCase) ---------------------------------------------------------------------- Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/test_subprocess.py", line 46, in tearDown self.assertFalse(subprocess._active, "subprocess._active not empty") AssertionError: subprocess._active not empty ====================================================================== ERROR: test_check_output_stderr (test.test_subprocess.ProcessTestCase) ---------------------------------------------------------------------- Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/test_subprocess.py", line 46, in tearDown self.assertFalse(subprocess._active, "subprocess._active not empty") AssertionError: subprocess._active not empty ====================================================================== ERROR: test_check_output_stdout_arg (test.test_subprocess.ProcessTestCase) ---------------------------------------------------------------------- Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/test_subprocess.py", line 46, in tearDown self.assertFalse(subprocess._active, "subprocess._active not empty") AssertionError: subprocess._active not empty ====================================================================== ERROR: test_communicate (test.test_subprocess.ProcessTestCase) ---------------------------------------------------------------------- Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/test_subprocess.py", line 46, in tearDown self.assertFalse(subprocess._active, "subprocess._active not empty") AssertionError: subprocess._active not empty ====================================================================== ERROR: test_communicate_pipe_buf (test.test_subprocess.ProcessTestCase) ---------------------------------------------------------------------- Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/test_subprocess.py", line 46, in tearDown self.assertFalse(subprocess._active, "subprocess._active not empty") AssertionError: subprocess._active not empty ====================================================================== ERROR: test_communicate_pipe_fd_leak (test.test_subprocess.ProcessTestCase) ---------------------------------------------------------------------- Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/test_subprocess.py", line 46, in tearDown self.assertFalse(subprocess._active, "subprocess._active not empty") AssertionError: subprocess._active not empty ====================================================================== ERROR: test_communicate_returns (test.test_subprocess.ProcessTestCase) ---------------------------------------------------------------------- Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/test_subprocess.py", line 46, in tearDown self.assertFalse(subprocess._active, "subprocess._active not empty") AssertionError: subprocess._active not empty ====================================================================== ERROR: test_communicate_stderr (test.test_subprocess.ProcessTestCase) ---------------------------------------------------------------------- Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/test_subprocess.py", line 46, in tearDown self.assertFalse(subprocess._active, "subprocess._active not empty") AssertionError: subprocess._active not empty ====================================================================== ERROR: test_communicate_stdin (test.test_subprocess.ProcessTestCase) ---------------------------------------------------------------------- Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/test_subprocess.py", line 46, in tearDown self.assertFalse(subprocess._active, "subprocess._active not empty") AssertionError: subprocess._active not empty ====================================================================== ERROR: test_communicate_stdout (test.test_subprocess.ProcessTestCase) ---------------------------------------------------------------------- Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/test_subprocess.py", line 46, in tearDown self.assertFalse(subprocess._active, "subprocess._active not empty") AssertionError: subprocess._active not empty ====================================================================== ERROR: test_cwd (test.test_subprocess.ProcessTestCase) ---------------------------------------------------------------------- Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/test_subprocess.py", line 46, in tearDown self.assertFalse(subprocess._active, "subprocess._active not empty") AssertionError: subprocess._active not empty ====================================================================== ERROR: test_env (test.test_subprocess.ProcessTestCase) ---------------------------------------------------------------------- Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/test_subprocess.py", line 46, in tearDown self.assertFalse(subprocess._active, "subprocess._active not empty") AssertionError: subprocess._active not empty ====================================================================== ERROR: test_executable_with_cwd (test.test_subprocess.ProcessTestCase) ---------------------------------------------------------------------- Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/test_subprocess.py", line 46, in tearDown self.assertFalse(subprocess._active, "subprocess._active not empty") AssertionError: subprocess._active not empty ====================================================================== ERROR: test_executable_without_cwd (test.test_subprocess.ProcessTestCase) ---------------------------------------------------------------------- Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/test_subprocess.py", line 46, in tearDown self.assertFalse(subprocess._active, "subprocess._active not empty") AssertionError: subprocess._active not empty ====================================================================== ERROR: test_invalid_bufsize (test.test_subprocess.ProcessTestCase) ---------------------------------------------------------------------- Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/test_subprocess.py", line 46, in tearDown self.assertFalse(subprocess._active, "subprocess._active not empty") AssertionError: subprocess._active not empty ====================================================================== ERROR: test_leaking_fds_on_error (test.test_subprocess.ProcessTestCase) ---------------------------------------------------------------------- Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/test_subprocess.py", line 46, in tearDown self.assertFalse(subprocess._active, "subprocess._active not empty") AssertionError: subprocess._active not empty ====================================================================== ERROR: test_list2cmdline (test.test_subprocess.ProcessTestCase) ---------------------------------------------------------------------- Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/test_subprocess.py", line 46, in tearDown self.assertFalse(subprocess._active, "subprocess._active not empty") AssertionError: subprocess._active not empty ====================================================================== ERROR: test_no_leaking (test.test_subprocess.ProcessTestCase) ---------------------------------------------------------------------- Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/test_subprocess.py", line 46, in tearDown self.assertFalse(subprocess._active, "subprocess._active not empty") AssertionError: subprocess._active not empty ====================================================================== ERROR: test_poll (test.test_subprocess.ProcessTestCase) ---------------------------------------------------------------------- Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/test_subprocess.py", line 46, in tearDown self.assertFalse(subprocess._active, "subprocess._active not empty") AssertionError: subprocess._active not empty ====================================================================== ERROR: test_stderr_filedes (test.test_subprocess.ProcessTestCase) ---------------------------------------------------------------------- Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/test_subprocess.py", line 46, in tearDown self.assertFalse(subprocess._active, "subprocess._active not empty") AssertionError: subprocess._active not empty ====================================================================== ERROR: test_stderr_fileobj (test.test_subprocess.ProcessTestCase) ---------------------------------------------------------------------- Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/test_subprocess.py", line 46, in tearDown self.assertFalse(subprocess._active, "subprocess._active not empty") AssertionError: subprocess._active not empty ====================================================================== ERROR: test_stderr_none (test.test_subprocess.ProcessTestCase) ---------------------------------------------------------------------- Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/test_subprocess.py", line 46, in tearDown self.assertFalse(subprocess._active, "subprocess._active not empty") AssertionError: subprocess._active not empty ====================================================================== ERROR: test_stderr_pipe (test.test_subprocess.ProcessTestCase) ---------------------------------------------------------------------- Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/test_subprocess.py", line 46, in tearDown self.assertFalse(subprocess._active, "subprocess._active not empty") AssertionError: subprocess._active not empty ====================================================================== ERROR: test_stdin_filedes (test.test_subprocess.ProcessTestCase) ---------------------------------------------------------------------- Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/test_subprocess.py", line 46, in tearDown self.assertFalse(subprocess._active, "subprocess._active not empty") AssertionError: subprocess._active not empty ====================================================================== ERROR: test_stdin_fileobj (test.test_subprocess.ProcessTestCase) ---------------------------------------------------------------------- Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/test_subprocess.py", line 46, in tearDown self.assertFalse(subprocess._active, "subprocess._active not empty") AssertionError: subprocess._active not empty ====================================================================== ERROR: test_stdin_none (test.test_subprocess.ProcessTestCase) ---------------------------------------------------------------------- Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/test_subprocess.py", line 46, in tearDown self.assertFalse(subprocess._active, "subprocess._active not empty") AssertionError: subprocess._active not empty ====================================================================== ERROR: test_stdin_pipe (test.test_subprocess.ProcessTestCase) ---------------------------------------------------------------------- Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/test_subprocess.py", line 46, in tearDown self.assertFalse(subprocess._active, "subprocess._active not empty") AssertionError: subprocess._active not empty ====================================================================== ERROR: test_stdout_filedes (test.test_subprocess.ProcessTestCase) ---------------------------------------------------------------------- Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/test_subprocess.py", line 46, in tearDown self.assertFalse(subprocess._active, "subprocess._active not empty") AssertionError: subprocess._active not empty ====================================================================== ERROR: test_stdout_filedes_of_stdout (test.test_subprocess.ProcessTestCase) ---------------------------------------------------------------------- Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/test_subprocess.py", line 46, in tearDown self.assertFalse(subprocess._active, "subprocess._active not empty") AssertionError: subprocess._active not empty ====================================================================== ERROR: test_stdout_fileobj (test.test_subprocess.ProcessTestCase) ---------------------------------------------------------------------- Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/test_subprocess.py", line 46, in tearDown self.assertFalse(subprocess._active, "subprocess._active not empty") AssertionError: subprocess._active not empty ====================================================================== ERROR: test_stdout_none (test.test_subprocess.ProcessTestCase) ---------------------------------------------------------------------- Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/test_subprocess.py", line 46, in tearDown self.assertFalse(subprocess._active, "subprocess._active not empty") AssertionError: subprocess._active not empty ====================================================================== ERROR: test_stdout_pipe (test.test_subprocess.ProcessTestCase) ---------------------------------------------------------------------- Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/test_subprocess.py", line 46, in tearDown self.assertFalse(subprocess._active, "subprocess._active not empty") AssertionError: subprocess._active not empty ====================================================================== ERROR: test_stdout_stderr_file (test.test_subprocess.ProcessTestCase) ---------------------------------------------------------------------- Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/test_subprocess.py", line 46, in tearDown self.assertFalse(subprocess._active, "subprocess._active not empty") AssertionError: subprocess._active not empty ====================================================================== ERROR: test_stdout_stderr_pipe (test.test_subprocess.ProcessTestCase) ---------------------------------------------------------------------- Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/test_subprocess.py", line 46, in tearDown self.assertFalse(subprocess._active, "subprocess._active not empty") AssertionError: subprocess._active not empty ====================================================================== ERROR: test_universal_newlines (test.test_subprocess.ProcessTestCase) ---------------------------------------------------------------------- Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/test_subprocess.py", line 46, in tearDown self.assertFalse(subprocess._active, "subprocess._active not empty") AssertionError: subprocess._active not empty ====================================================================== ERROR: test_universal_newlines_communicate (test.test_subprocess.ProcessTestCase) ---------------------------------------------------------------------- Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/test_subprocess.py", line 46, in tearDown self.assertFalse(subprocess._active, "subprocess._active not empty") AssertionError: subprocess._active not empty ====================================================================== ERROR: test_wait (test.test_subprocess.ProcessTestCase) ---------------------------------------------------------------------- Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/test_subprocess.py", line 46, in tearDown self.assertFalse(subprocess._active, "subprocess._active not empty") AssertionError: subprocess._active not empty ====================================================================== ERROR: test_writes_before_communicate (test.test_subprocess.ProcessTestCase) ---------------------------------------------------------------------- Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/test_subprocess.py", line 46, in tearDown self.assertFalse(subprocess._active, "subprocess._active not empty") AssertionError: subprocess._active not empty ====================================================================== ERROR: test_args_string (test.test_subprocess.POSIXProcessTestCase) ---------------------------------------------------------------------- Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/test_subprocess.py", line 46, in tearDown self.assertFalse(subprocess._active, "subprocess._active not empty") AssertionError: subprocess._active not empty ====================================================================== ERROR: test_call_string (test.test_subprocess.POSIXProcessTestCase) ---------------------------------------------------------------------- Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/test_subprocess.py", line 46, in tearDown self.assertFalse(subprocess._active, "subprocess._active not empty") AssertionError: subprocess._active not empty ====================================================================== ERROR: test_exceptions (test.test_subprocess.POSIXProcessTestCase) ---------------------------------------------------------------------- Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/test_subprocess.py", line 46, in tearDown self.assertFalse(subprocess._active, "subprocess._active not empty") AssertionError: subprocess._active not empty ====================================================================== ERROR: test_invalid_args (test.test_subprocess.POSIXProcessTestCase) ---------------------------------------------------------------------- Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/test_subprocess.py", line 46, in tearDown self.assertFalse(subprocess._active, "subprocess._active not empty") AssertionError: subprocess._active not empty ====================================================================== ERROR: test_kill (test.test_subprocess.POSIXProcessTestCase) ---------------------------------------------------------------------- Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/test_subprocess.py", line 46, in tearDown self.assertFalse(subprocess._active, "subprocess._active not empty") AssertionError: subprocess._active not empty ====================================================================== ERROR: test_preexec (test.test_subprocess.POSIXProcessTestCase) ---------------------------------------------------------------------- Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/test_subprocess.py", line 46, in tearDown self.assertFalse(subprocess._active, "subprocess._active not empty") AssertionError: subprocess._active not empty ====================================================================== ERROR: test_run_abort (test.test_subprocess.POSIXProcessTestCase) ---------------------------------------------------------------------- Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/test_subprocess.py", line 46, in tearDown self.assertFalse(subprocess._active, "subprocess._active not empty") AssertionError: subprocess._active not empty ====================================================================== ERROR: test_send_signal (test.test_subprocess.POSIXProcessTestCase) ---------------------------------------------------------------------- Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/test_subprocess.py", line 46, in tearDown self.assertFalse(subprocess._active, "subprocess._active not empty") AssertionError: subprocess._active not empty ====================================================================== ERROR: test_shell_sequence (test.test_subprocess.POSIXProcessTestCase) ---------------------------------------------------------------------- Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/test_subprocess.py", line 46, in tearDown self.assertFalse(subprocess._active, "subprocess._active not empty") AssertionError: subprocess._active not empty ====================================================================== ERROR: test_shell_string (test.test_subprocess.POSIXProcessTestCase) ---------------------------------------------------------------------- Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/test_subprocess.py", line 46, in tearDown self.assertFalse(subprocess._active, "subprocess._active not empty") AssertionError: subprocess._active not empty ====================================================================== ERROR: test_terminate (test.test_subprocess.POSIXProcessTestCase) ---------------------------------------------------------------------- Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/test_subprocess.py", line 46, in tearDown self.assertFalse(subprocess._active, "subprocess._active not empty") AssertionError: subprocess._active not empty ====================================================================== ERROR: test_call_kwargs (test.test_subprocess.ProcessTestCaseNoPoll) ---------------------------------------------------------------------- Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/test_subprocess.py", line 802, in tearDown ProcessTestCase.tearDown(self) File "/tmp/python-test/local/lib/python2.7/test/test_subprocess.py", line 46, in tearDown self.assertFalse(subprocess._active, "subprocess._active not empty") AssertionError: subprocess._active not empty ====================================================================== ERROR: test_call_seq (test.test_subprocess.ProcessTestCaseNoPoll) ---------------------------------------------------------------------- Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/test_subprocess.py", line 802, in tearDown ProcessTestCase.tearDown(self) File "/tmp/python-test/local/lib/python2.7/test/test_subprocess.py", line 46, in tearDown self.assertFalse(subprocess._active, "subprocess._active not empty") AssertionError: subprocess._active not empty ====================================================================== ERROR: test_check_call_nonzero (test.test_subprocess.ProcessTestCaseNoPoll) ---------------------------------------------------------------------- Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/test_subprocess.py", line 802, in tearDown ProcessTestCase.tearDown(self) File "/tmp/python-test/local/lib/python2.7/test/test_subprocess.py", line 46, in tearDown self.assertFalse(subprocess._active, "subprocess._active not empty") AssertionError: subprocess._active not empty ====================================================================== ERROR: test_check_call_zero (test.test_subprocess.ProcessTestCaseNoPoll) ---------------------------------------------------------------------- Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/test_subprocess.py", line 802, in tearDown ProcessTestCase.tearDown(self) File "/tmp/python-test/local/lib/python2.7/test/test_subprocess.py", line 46, in tearDown self.assertFalse(subprocess._active, "subprocess._active not empty") AssertionError: subprocess._active not empty ====================================================================== ERROR: test_check_output (test.test_subprocess.ProcessTestCaseNoPoll) ---------------------------------------------------------------------- Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/test_subprocess.py", line 802, in tearDown ProcessTestCase.tearDown(self) File "/tmp/python-test/local/lib/python2.7/test/test_subprocess.py", line 46, in tearDown self.assertFalse(subprocess._active, "subprocess._active not empty") AssertionError: subprocess._active not empty ====================================================================== ERROR: test_check_output_nonzero (test.test_subprocess.ProcessTestCaseNoPoll) ---------------------------------------------------------------------- Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/test_subprocess.py", line 802, in tearDown ProcessTestCase.tearDown(self) File "/tmp/python-test/local/lib/python2.7/test/test_subprocess.py", line 46, in tearDown self.assertFalse(subprocess._active, "subprocess._active not empty") AssertionError: subprocess._active not empty ====================================================================== ERROR: test_check_output_stderr (test.test_subprocess.ProcessTestCaseNoPoll) ---------------------------------------------------------------------- Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/test_subprocess.py", line 802, in tearDown ProcessTestCase.tearDown(self) File "/tmp/python-test/local/lib/python2.7/test/test_subprocess.py", line 46, in tearDown self.assertFalse(subprocess._active, "subprocess._active not empty") AssertionError: subprocess._active not empty ====================================================================== ERROR: test_check_output_stdout_arg (test.test_subprocess.ProcessTestCaseNoPoll) ---------------------------------------------------------------------- Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/test_subprocess.py", line 802, in tearDown ProcessTestCase.tearDown(self) File "/tmp/python-test/local/lib/python2.7/test/test_subprocess.py", line 46, in tearDown self.assertFalse(subprocess._active, "subprocess._active not empty") AssertionError: subprocess._active not empty ====================================================================== ERROR: test_communicate (test.test_subprocess.ProcessTestCaseNoPoll) ---------------------------------------------------------------------- Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/test_subprocess.py", line 802, in tearDown ProcessTestCase.tearDown(self) File "/tmp/python-test/local/lib/python2.7/test/test_subprocess.py", line 46, in tearDown self.assertFalse(subprocess._active, "subprocess._active not empty") AssertionError: subprocess._active not empty ====================================================================== ERROR: test_communicate_pipe_buf (test.test_subprocess.ProcessTestCaseNoPoll) ---------------------------------------------------------------------- Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/test_subprocess.py", line 802, in tearDown ProcessTestCase.tearDown(self) File "/tmp/python-test/local/lib/python2.7/test/test_subprocess.py", line 46, in tearDown self.assertFalse(subprocess._active, "subprocess._active not empty") AssertionError: subprocess._active not empty ====================================================================== ERROR: test_communicate_pipe_fd_leak (test.test_subprocess.ProcessTestCaseNoPoll) ---------------------------------------------------------------------- Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/test_subprocess.py", line 802, in tearDown ProcessTestCase.tearDown(self) File "/tmp/python-test/local/lib/python2.7/test/test_subprocess.py", line 46, in tearDown self.assertFalse(subprocess._active, "subprocess._active not empty") AssertionError: subprocess._active not empty ====================================================================== ERROR: test_communicate_returns (test.test_subprocess.ProcessTestCaseNoPoll) ---------------------------------------------------------------------- Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/test_subprocess.py", line 802, in tearDown ProcessTestCase.tearDown(self) File "/tmp/python-test/local/lib/python2.7/test/test_subprocess.py", line 46, in tearDown self.assertFalse(subprocess._active, "subprocess._active not empty") AssertionError: subprocess._active not empty ====================================================================== ERROR: test_communicate_stderr (test.test_subprocess.ProcessTestCaseNoPoll) ---------------------------------------------------------------------- Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/test_subprocess.py", line 802, in tearDown ProcessTestCase.tearDown(self) File "/tmp/python-test/local/lib/python2.7/test/test_subprocess.py", line 46, in tearDown self.assertFalse(subprocess._active, "subprocess._active not empty") AssertionError: subprocess._active not empty ====================================================================== ERROR: test_communicate_stdin (test.test_subprocess.ProcessTestCaseNoPoll) ---------------------------------------------------------------------- Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/test_subprocess.py", line 802, in tearDown ProcessTestCase.tearDown(self) File "/tmp/python-test/local/lib/python2.7/test/test_subprocess.py", line 46, in tearDown self.assertFalse(subprocess._active, "subprocess._active not empty") AssertionError: subprocess._active not empty ====================================================================== ERROR: test_communicate_stdout (test.test_subprocess.ProcessTestCaseNoPoll) ---------------------------------------------------------------------- Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/test_subprocess.py", line 802, in tearDown ProcessTestCase.tearDown(self) File "/tmp/python-test/local/lib/python2.7/test/test_subprocess.py", line 46, in tearDown self.assertFalse(subprocess._active, "subprocess._active not empty") AssertionError: subprocess._active not empty ====================================================================== ERROR: test_cwd (test.test_subprocess.ProcessTestCaseNoPoll) ---------------------------------------------------------------------- Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/test_subprocess.py", line 802, in tearDown ProcessTestCase.tearDown(self) File "/tmp/python-test/local/lib/python2.7/test/test_subprocess.py", line 46, in tearDown self.assertFalse(subprocess._active, "subprocess._active not empty") AssertionError: subprocess._active not empty ====================================================================== ERROR: test_env (test.test_subprocess.ProcessTestCaseNoPoll) ---------------------------------------------------------------------- Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/test_subprocess.py", line 802, in tearDown ProcessTestCase.tearDown(self) File "/tmp/python-test/local/lib/python2.7/test/test_subprocess.py", line 46, in tearDown self.assertFalse(subprocess._active, "subprocess._active not empty") AssertionError: subprocess._active not empty ====================================================================== ERROR: test_executable_with_cwd (test.test_subprocess.ProcessTestCaseNoPoll) ---------------------------------------------------------------------- Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/test_subprocess.py", line 802, in tearDown ProcessTestCase.tearDown(self) File "/tmp/python-test/local/lib/python2.7/test/test_subprocess.py", line 46, in tearDown self.assertFalse(subprocess._active, "subprocess._active not empty") AssertionError: subprocess._active not empty ====================================================================== ERROR: test_executable_without_cwd (test.test_subprocess.ProcessTestCaseNoPoll) ---------------------------------------------------------------------- Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/test_subprocess.py", line 802, in tearDown ProcessTestCase.tearDown(self) File "/tmp/python-test/local/lib/python2.7/test/test_subprocess.py", line 46, in tearDown self.assertFalse(subprocess._active, "subprocess._active not empty") AssertionError: subprocess._active not empty ====================================================================== ERROR: test_invalid_bufsize (test.test_subprocess.ProcessTestCaseNoPoll) ---------------------------------------------------------------------- Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/test_subprocess.py", line 802, in tearDown ProcessTestCase.tearDown(self) File "/tmp/python-test/local/lib/python2.7/test/test_subprocess.py", line 46, in tearDown self.assertFalse(subprocess._active, "subprocess._active not empty") AssertionError: subprocess._active not empty ====================================================================== ERROR: test_leaking_fds_on_error (test.test_subprocess.ProcessTestCaseNoPoll) ---------------------------------------------------------------------- Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/test_subprocess.py", line 802, in tearDown ProcessTestCase.tearDown(self) File "/tmp/python-test/local/lib/python2.7/test/test_subprocess.py", line 46, in tearDown self.assertFalse(subprocess._active, "subprocess._active not empty") AssertionError: subprocess._active not empty ====================================================================== ERROR: test_list2cmdline (test.test_subprocess.ProcessTestCaseNoPoll) ---------------------------------------------------------------------- Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/test_subprocess.py", line 802, in tearDown ProcessTestCase.tearDown(self) File "/tmp/python-test/local/lib/python2.7/test/test_subprocess.py", line 46, in tearDown self.assertFalse(subprocess._active, "subprocess._active not empty") AssertionError: subprocess._active not empty ====================================================================== ERROR: test_no_leaking (test.test_subprocess.ProcessTestCaseNoPoll) ---------------------------------------------------------------------- Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/test_subprocess.py", line 802, in tearDown ProcessTestCase.tearDown(self) File "/tmp/python-test/local/lib/python2.7/test/test_subprocess.py", line 46, in tearDown self.assertFalse(subprocess._active, "subprocess._active not empty") AssertionError: subprocess._active not empty ====================================================================== ERROR: test_poll (test.test_subprocess.ProcessTestCaseNoPoll) ---------------------------------------------------------------------- Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/test_subprocess.py", line 802, in tearDown ProcessTestCase.tearDown(self) File "/tmp/python-test/local/lib/python2.7/test/test_subprocess.py", line 46, in tearDown self.assertFalse(subprocess._active, "subprocess._active not empty") AssertionError: subprocess._active not empty ====================================================================== ERROR: test_stderr_filedes (test.test_subprocess.ProcessTestCaseNoPoll) ---------------------------------------------------------------------- Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/test_subprocess.py", line 802, in tearDown ProcessTestCase.tearDown(self) File "/tmp/python-test/local/lib/python2.7/test/test_subprocess.py", line 46, in tearDown self.assertFalse(subprocess._active, "subprocess._active not empty") AssertionError: subprocess._active not empty ====================================================================== ERROR: test_stderr_fileobj (test.test_subprocess.ProcessTestCaseNoPoll) ---------------------------------------------------------------------- Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/test_subprocess.py", line 802, in tearDown ProcessTestCase.tearDown(self) File "/tmp/python-test/local/lib/python2.7/test/test_subprocess.py", line 46, in tearDown self.assertFalse(subprocess._active, "subprocess._active not empty") AssertionError: subprocess._active not empty ====================================================================== ERROR: test_stderr_none (test.test_subprocess.ProcessTestCaseNoPoll) ---------------------------------------------------------------------- Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/test_subprocess.py", line 802, in tearDown ProcessTestCase.tearDown(self) File "/tmp/python-test/local/lib/python2.7/test/test_subprocess.py", line 46, in tearDown self.assertFalse(subprocess._active, "subprocess._active not empty") AssertionError: subprocess._active not empty ====================================================================== ERROR: test_stderr_pipe (test.test_subprocess.ProcessTestCaseNoPoll) ---------------------------------------------------------------------- Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/test_subprocess.py", line 802, in tearDown ProcessTestCase.tearDown(self) File "/tmp/python-test/local/lib/python2.7/test/test_subprocess.py", line 46, in tearDown self.assertFalse(subprocess._active, "subprocess._active not empty") AssertionError: subprocess._active not empty ====================================================================== ERROR: test_stdin_filedes (test.test_subprocess.ProcessTestCaseNoPoll) ---------------------------------------------------------------------- Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/test_subprocess.py", line 802, in tearDown ProcessTestCase.tearDown(self) File "/tmp/python-test/local/lib/python2.7/test/test_subprocess.py", line 46, in tearDown self.assertFalse(subprocess._active, "subprocess._active not empty") AssertionError: subprocess._active not empty ====================================================================== ERROR: test_stdin_fileobj (test.test_subprocess.ProcessTestCaseNoPoll) ---------------------------------------------------------------------- Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/test_subprocess.py", line 802, in tearDown ProcessTestCase.tearDown(self) File "/tmp/python-test/local/lib/python2.7/test/test_subprocess.py", line 46, in tearDown self.assertFalse(subprocess._active, "subprocess._active not empty") AssertionError: subprocess._active not empty ====================================================================== ERROR: test_stdin_none (test.test_subprocess.ProcessTestCaseNoPoll) ---------------------------------------------------------------------- Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/test_subprocess.py", line 802, in tearDown ProcessTestCase.tearDown(self) File "/tmp/python-test/local/lib/python2.7/test/test_subprocess.py", line 46, in tearDown self.assertFalse(subprocess._active, "subprocess._active not empty") AssertionError: subprocess._active not empty ====================================================================== ERROR: test_stdin_pipe (test.test_subprocess.ProcessTestCaseNoPoll) ---------------------------------------------------------------------- Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/test_subprocess.py", line 802, in tearDown ProcessTestCase.tearDown(self) File "/tmp/python-test/local/lib/python2.7/test/test_subprocess.py", line 46, in tearDown self.assertFalse(subprocess._active, "subprocess._active not empty") AssertionError: subprocess._active not empty ====================================================================== ERROR: test_stdout_filedes (test.test_subprocess.ProcessTestCaseNoPoll) ---------------------------------------------------------------------- Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/test_subprocess.py", line 802, in tearDown ProcessTestCase.tearDown(self) File "/tmp/python-test/local/lib/python2.7/test/test_subprocess.py", line 46, in tearDown self.assertFalse(subprocess._active, "subprocess._active not empty") AssertionError: subprocess._active not empty ====================================================================== ERROR: test_stdout_filedes_of_stdout (test.test_subprocess.ProcessTestCaseNoPoll) ---------------------------------------------------------------------- Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/test_subprocess.py", line 802, in tearDown ProcessTestCase.tearDown(self) File "/tmp/python-test/local/lib/python2.7/test/test_subprocess.py", line 46, in tearDown self.assertFalse(subprocess._active, "subprocess._active not empty") AssertionError: subprocess._active not empty ====================================================================== ERROR: test_stdout_fileobj (test.test_subprocess.ProcessTestCaseNoPoll) ---------------------------------------------------------------------- Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/test_subprocess.py", line 802, in tearDown ProcessTestCase.tearDown(self) File "/tmp/python-test/local/lib/python2.7/test/test_subprocess.py", line 46, in tearDown self.assertFalse(subprocess._active, "subprocess._active not empty") AssertionError: subprocess._active not empty ====================================================================== ERROR: test_stdout_none (test.test_subprocess.ProcessTestCaseNoPoll) ---------------------------------------------------------------------- Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/test_subprocess.py", line 802, in tearDown ProcessTestCase.tearDown(self) File "/tmp/python-test/local/lib/python2.7/test/test_subprocess.py", line 46, in tearDown self.assertFalse(subprocess._active, "subprocess._active not empty") AssertionError: subprocess._active not empty ====================================================================== ERROR: test_stdout_pipe (test.test_subprocess.ProcessTestCaseNoPoll) ---------------------------------------------------------------------- Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/test_subprocess.py", line 802, in tearDown ProcessTestCase.tearDown(self) File "/tmp/python-test/local/lib/python2.7/test/test_subprocess.py", line 46, in tearDown self.assertFalse(subprocess._active, "subprocess._active not empty") AssertionError: subprocess._active not empty ====================================================================== ERROR: test_stdout_stderr_file (test.test_subprocess.ProcessTestCaseNoPoll) ---------------------------------------------------------------------- Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/test_subprocess.py", line 802, in tearDown ProcessTestCase.tearDown(self) File "/tmp/python-test/local/lib/python2.7/test/test_subprocess.py", line 46, in tearDown self.assertFalse(subprocess._active, "subprocess._active not empty") AssertionError: subprocess._active not empty ====================================================================== ERROR: test_stdout_stderr_pipe (test.test_subprocess.ProcessTestCaseNoPoll) ---------------------------------------------------------------------- Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/test_subprocess.py", line 802, in tearDown ProcessTestCase.tearDown(self) File "/tmp/python-test/local/lib/python2.7/test/test_subprocess.py", line 46, in tearDown self.assertFalse(subprocess._active, "subprocess._active not empty") AssertionError: subprocess._active not empty ====================================================================== ERROR: test_universal_newlines (test.test_subprocess.ProcessTestCaseNoPoll) ---------------------------------------------------------------------- Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/test_subprocess.py", line 802, in tearDown ProcessTestCase.tearDown(self) File "/tmp/python-test/local/lib/python2.7/test/test_subprocess.py", line 46, in tearDown self.assertFalse(subprocess._active, "subprocess._active not empty") AssertionError: subprocess._active not empty ====================================================================== ERROR: test_universal_newlines_communicate (test.test_subprocess.ProcessTestCaseNoPoll) ---------------------------------------------------------------------- Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/test_subprocess.py", line 802, in tearDown ProcessTestCase.tearDown(self) File "/tmp/python-test/local/lib/python2.7/test/test_subprocess.py", line 46, in tearDown self.assertFalse(subprocess._active, "subprocess._active not empty") AssertionError: subprocess._active not empty ====================================================================== ERROR: test_wait (test.test_subprocess.ProcessTestCaseNoPoll) ---------------------------------------------------------------------- Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/test_subprocess.py", line 802, in tearDown ProcessTestCase.tearDown(self) File "/tmp/python-test/local/lib/python2.7/test/test_subprocess.py", line 46, in tearDown self.assertFalse(subprocess._active, "subprocess._active not empty") AssertionError: subprocess._active not empty ====================================================================== ERROR: test_writes_before_communicate (test.test_subprocess.ProcessTestCaseNoPoll) ---------------------------------------------------------------------- Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/test_subprocess.py", line 802, in tearDown ProcessTestCase.tearDown(self) File "/tmp/python-test/local/lib/python2.7/test/test_subprocess.py", line 46, in tearDown self.assertFalse(subprocess._active, "subprocess._active not empty") AssertionError: subprocess._active not empty ---------------------------------------------------------------------- Ran 108 tests in 296.598s FAILED (errors=97, skipped=10) test test_subprocess failed -- multiple errors occurred test_sunaudiodev test_sunaudiodev skipped -- No module named sunaudiodev test_sundry test_symtable test_syntax test_sys [16651 refs] [16651 refs] [16651 refs] [16880 refs] [16674 refs] test_sysconfig [16651 refs] [16651 refs] test_tarfile test_tcl test_tcl skipped -- No module named _tkinter test_telnetlib test_tempfile [16651 refs] test_textwrap test_thread test_threaded_import test_threadedtempfile test_threading [19951 refs] [22122 refs] [21034 refs] [21034 refs] [21034 refs] [21034 refs] test_threading_local test_threadsignals test_time test_timeout test_tk test_tk skipped -- No module named _tkinter test_tokenize test_trace test_traceback test_transformer test_ttk_guionly test_ttk_guionly skipped -- No module named _tkinter test_ttk_textonly test_ttk_textonly skipped -- No module named _tkinter test_tuple test_typechecks test_ucn test_unary test_undocumented_details test_unicode test_unicode_file test_unicode_file skipped -- No Unicode filesystem semantics on this platform. test_unicodedata test_univnewlines test_univnewlines2k test_unpack test_urllib test_urllib2 test_urllib2_localnet test_urllib2net test_urllibnet test_urlparse test_userdict test_userlist test_userstring test_uu test_uuid test_wait3 test_wait4 test_warnings [16682 refs] [16682 refs] [16675 refs] [16682 refs] [16682 refs] [16675 refs] test_wave test_weakref test_weakset test_whichdb test_winreg test_winreg skipped -- No module named _winreg test_winsound test_winsound skipped -- No module named winsound test_with test_wsgiref test_xdrlib test_xml_etree test_xml_etree_c test_xmllib test_xmlrpc test_xpickle sh: line 1: python2.4: command not found sh: line 1: python2.6: command not found test_xrange test_zipfile test_zipfile64 test_zipfile64 skipped -- test requires loads of disk-space bytes and a long time to run test_zipimport test_zipimport_support test_zlib 352 tests OK. 1 test failed: test_subprocess 28 tests skipped: test_aepack test_al test_applesingle test_bsddb185 test_cd test_cl test_epoll test_gdb test_gl test_imgfile test_ioctl test_kqueue test_macos test_macostools test_multiprocessing test_pep277 test_py3kwarn test_scriptpackages test_startfile test_sunaudiodev test_tcl test_tk test_ttk_guionly test_ttk_textonly test_unicode_file test_winreg test_winsound test_zipfile64 7 skips unexpected on linux2: test_epoll test_gdb test_ioctl test_multiprocessing test_tk test_ttk_guionly test_ttk_textonly [981844 refs] From python-checkins at python.org Fri May 21 15:08:21 2010 From: python-checkins at python.org (matthias.klose) Date: Fri, 21 May 2010 15:08:21 +0200 (CEST) Subject: [Python-checkins] r81395 - in python/branches/release26-maint: Lib/email/test/data/audiotest.au Lib/test/audiotest.au Lib/test/test_ossaudiodev.py Message-ID: <20100521130821.37FF4EE99D@mail.python.org> Author: matthias.klose Date: Fri May 21 15:08:20 2010 New Revision: 81395 Log: Merged revisions 80793 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r80793 | barry.warsaw | 2010-05-05 18:15:09 +0200 (Mi, 05 Mai 2010) | 5 lines Bug 7755: audiotest.au is arguably copyrighted material, but definitely makes Debian unhappy. The actual contents of the audio clip are unimportant, so replace it with something that we know is okay. Guido likes woodpeckers. ........ Modified: python/branches/release26-maint/ (props changed) python/branches/release26-maint/Lib/email/test/data/audiotest.au python/branches/release26-maint/Lib/test/audiotest.au python/branches/release26-maint/Lib/test/test_ossaudiodev.py Modified: python/branches/release26-maint/Lib/email/test/data/audiotest.au ============================================================================== Binary files. No diff available. Modified: python/branches/release26-maint/Lib/test/audiotest.au ============================================================================== Binary files. No diff available. Modified: python/branches/release26-maint/Lib/test/test_ossaudiodev.py ============================================================================== --- python/branches/release26-maint/Lib/test/test_ossaudiodev.py (original) +++ python/branches/release26-maint/Lib/test/test_ossaudiodev.py Fri May 21 15:08:20 2010 @@ -74,7 +74,7 @@ # set parameters based on .au file headers dsp.setparameters(AFMT_S16_NE, nchannels, rate) - self.assertTrue(abs(expected_time - 2.94) < 1e-2, expected_time) + self.assertTrue(abs(expected_time - 3.51) < 1e-2, expected_time) t1 = time.time() dsp.write(data) dsp.close() From python-checkins at python.org Fri May 21 15:11:01 2010 From: python-checkins at python.org (matthias.klose) Date: Fri, 21 May 2010 15:11:01 +0200 (CEST) Subject: [Python-checkins] r81396 - in python/branches/release31-maint: Lib/email/test/data/audiotest.au Lib/test/audiotest.au Lib/test/test_ossaudiodev.py Misc/NEWS Message-ID: <20100521131101.0776FEEAE1@mail.python.org> Author: matthias.klose Date: Fri May 21 15:11:00 2010 New Revision: 81396 Log: Merged revisions 80795 via svnmerge from svn+ssh://pythondev at svn.python.org/python/branches/py3k ........ r80795 | barry.warsaw | 2010-05-05 18:18:31 +0200 (Mi, 05 Mai 2010) | 5 lines Bug 7755: audiotest.au is arguably copyrighted material, but definitely makes Debian unhappy. The actual contents of the audio clip are unimportant, so replace it with something that we know is okay. Guido likes woodpeckers. ........ Modified: python/branches/release31-maint/Lib/email/test/data/audiotest.au python/branches/release31-maint/Lib/test/audiotest.au python/branches/release31-maint/Lib/test/test_ossaudiodev.py python/branches/release31-maint/Misc/NEWS Modified: python/branches/release31-maint/Lib/email/test/data/audiotest.au ============================================================================== Binary files. No diff available. Modified: python/branches/release31-maint/Lib/test/audiotest.au ============================================================================== Binary files. No diff available. Modified: python/branches/release31-maint/Lib/test/test_ossaudiodev.py ============================================================================== --- python/branches/release31-maint/Lib/test/test_ossaudiodev.py (original) +++ python/branches/release31-maint/Lib/test/test_ossaudiodev.py Fri May 21 15:11:00 2010 @@ -76,7 +76,7 @@ # set parameters based on .au file headers dsp.setparameters(AFMT_S16_NE, nchannels, rate) - self.assertTrue(abs(expected_time - 2.94) < 1e-2, expected_time) + self.assertTrue(abs(expected_time - 3.51) < 1e-2, expected_time) t1 = time.time() dsp.write(data) dsp.close() Modified: python/branches/release31-maint/Misc/NEWS ============================================================================== --- python/branches/release31-maint/Misc/NEWS (original) +++ python/branches/release31-maint/Misc/NEWS Fri May 21 15:11:00 2010 @@ -83,6 +83,8 @@ - Issue #4265: shutil.copyfile() was leaking file descriptors when disk fills. Patch by Tres Seaver. +- Issue #7755: Use an unencumbered audio file for tests. + - Issue #8621: uuid.uuid4() returned the same sequence of values in the parent and any children created using ``os.fork`` on MacOS X 10.6. From python-checkins at python.org Fri May 21 16:55:26 2010 From: python-checkins at python.org (mark.dickinson) Date: Fri, 21 May 2010 16:55:26 +0200 (CEST) Subject: [Python-checkins] r81397 - in python/branches/py3k: Lib/test/test_complex.py Misc/NEWS Objects/complexobject.c Message-ID: <20100521145526.3D8F8EE999@mail.python.org> Author: mark.dickinson Date: Fri May 21 16:55:26 2010 New Revision: 81397 Log: Issue #8748: Fix two issues with comparisons between complex and integer objects. (1) The comparison could incorrectly return True in some cases (2**53+1 == complex(2**53) == 2**53), breaking transivity of equality. (2) The comparison raised an OverflowError for large integers, leading to unpredictable exceptions when combining integers and complex objects in sets or dicts. Patch by Meador Inge. Modified: python/branches/py3k/Lib/test/test_complex.py python/branches/py3k/Misc/NEWS python/branches/py3k/Objects/complexobject.c Modified: python/branches/py3k/Lib/test/test_complex.py ============================================================================== --- python/branches/py3k/Lib/test/test_complex.py (original) +++ python/branches/py3k/Lib/test/test_complex.py Fri May 21 16:55:26 2010 @@ -110,12 +110,18 @@ self.assertRaises(TypeError, complex.__floordiv__, 3+0j, 0+0j) def test_richcompare(self): - self.assertRaises(OverflowError, complex.__eq__, 1+1j, 1<<10000) + self.assertIs(complex.__eq__(1+1j, 1<<10000), False) self.assertIs(complex.__lt__(1+1j, None), NotImplemented) self.assertIs(complex.__eq__(1+1j, 1+1j), True) self.assertIs(complex.__eq__(1+1j, 2+2j), False) self.assertIs(complex.__ne__(1+1j, 1+1j), False) self.assertIs(complex.__ne__(1+1j, 2+2j), True) + for i in range(1, 100): + f = i / 100.0 + self.assertIs(complex.__eq__(f+0j, f), True) + self.assertIs(complex.__ne__(f+0j, f), False) + self.assertIs(complex.__eq__(complex(f, f), f), False) + self.assertIs(complex.__ne__(complex(f, f), f), True) self.assertIs(complex.__lt__(1+1j, 2+2j), NotImplemented) self.assertIs(complex.__le__(1+1j, 2+2j), NotImplemented) self.assertIs(complex.__gt__(1+1j, 2+2j), NotImplemented) @@ -129,6 +135,23 @@ self.assertIs(operator.ne(1+1j, 1+1j), False) self.assertIs(operator.ne(1+1j, 2+2j), True) + def test_richcompare_boundaries(self): + def check(n, deltas, is_equal, imag = 0.0): + for delta in deltas: + i = n + delta + z = complex(i, imag) + self.assertIs(complex.__eq__(z, i), is_equal(delta)) + self.assertIs(complex.__ne__(z, i), not is_equal(delta)) + # For IEEE-754 doubles the following should hold: + # x in [2 ** (52 + i), 2 ** (53 + i + 1)] -> x mod 2 ** i == 0 + # where the interval is representable, of course. + for i in range(1, 10): + pow = 52 + i + mult = 2 ** i + check(2 ** pow, range(1, 101), lambda delta: delta % mult == 0) + check(2 ** pow, range(1, 101), lambda delta: False, float(i)) + check(2 ** 53, range(-100, 0), lambda delta: True) + def test_mod(self): # % is no longer supported on complex numbers self.assertRaises(TypeError, (1+1j).__mod__, 0+0j) Modified: python/branches/py3k/Misc/NEWS ============================================================================== --- python/branches/py3k/Misc/NEWS (original) +++ python/branches/py3k/Misc/NEWS Fri May 21 16:55:26 2010 @@ -12,6 +12,19 @@ Core and Builtins ----------------- +- Issue #8748: Fix two issues with comparisons between complex and integer + objects. (1) The comparison could incorrectly return True in some cases + (2**53+1 == complex(2**53) == 2**53), breaking transivity of equality. + (2) The comparison raised an OverflowError for large integers, leading + to unpredictable exceptions when combining integers and complex objects + in sets or dicts. + +- Issue #8748: Fix comparisons between complex and integer objects. + These used to convert the integer object to a complex number before + doing the comparison, giving a potentially incorrect result when + that conversion involved precision loss. (Ex: 2**53+1 == + complex(2**53) returned True; now returns False.) + - Issue #8766: Initialize _warnings module before importing the first module. Fix a crash if an empty directory called "encodings" exists in sys.path. Modified: python/branches/py3k/Objects/complexobject.c ============================================================================== --- python/branches/py3k/Objects/complexobject.c (original) +++ python/branches/py3k/Objects/complexobject.c Fri May 21 16:55:26 2010 @@ -620,22 +620,58 @@ complex_richcompare(PyObject *v, PyObject *w, int op) { PyObject *res; - Py_complex i, j; - TO_COMPLEX(v, i); - TO_COMPLEX(w, j); + Py_complex i; + int equal; if (op != Py_EQ && op != Py_NE) { - Py_INCREF(Py_NotImplemented); - return Py_NotImplemented; + goto Unimplemented; } - if ((i.real == j.real && i.imag == j.imag) == (op == Py_EQ)) - res = Py_True; + assert(PyComplex_Check(v)); + TO_COMPLEX(v, i); + + if (PyLong_Check(w)) { + /* Check for 0.0 imaginary part first to avoid the rich + * comparison when possible. + */ + if (i.imag == 0.0) { + PyObject *j, *sub_res; + j = PyFloat_FromDouble(i.real); + if (j == NULL) + return NULL; + + sub_res = PyObject_RichCompare(j, w, op); + Py_DECREF(j); + return sub_res; + } + else { + equal = 0; + } + } + else if (PyFloat_Check(w)) { + equal = (i.real == PyFloat_AsDouble(w) && i.imag == 0.0); + } + else if (PyComplex_Check(w)) { + Py_complex j; + + TO_COMPLEX(w, j); + equal = (i.real == j.real && i.imag == j.imag); + } + else { + goto Unimplemented; + } + + if (equal == (op == Py_EQ)) + res = Py_True; else - res = Py_False; + res = Py_False; Py_INCREF(res); return res; + +Unimplemented: + Py_INCREF(Py_NotImplemented); + return Py_NotImplemented; } static PyObject * From python-checkins at python.org Fri May 21 19:12:38 2010 From: python-checkins at python.org (antoine.pitrou) Date: Fri, 21 May 2010 19:12:38 +0200 (CEST) Subject: [Python-checkins] r81398 - in python/trunk: Doc/c-api/init.rst Include/sysmodule.h Misc/NEWS Python/sysmodule.c Message-ID: <20100521171238.ED323EE9B7@mail.python.org> Author: antoine.pitrou Date: Fri May 21 19:12:38 2010 New Revision: 81398 Log: Issue #5753: A new C API function, :cfunc:`PySys_SetArgvEx`, allows embedders of the interpreter to set sys.argv without also modifying sys.path. This helps fix `CVE-2008-5983 `_. Modified: python/trunk/Doc/c-api/init.rst python/trunk/Include/sysmodule.h python/trunk/Misc/NEWS python/trunk/Python/sysmodule.c Modified: python/trunk/Doc/c-api/init.rst ============================================================================== --- python/trunk/Doc/c-api/init.rst (original) +++ python/trunk/Doc/c-api/init.rst Fri May 21 19:12:38 2010 @@ -22,6 +22,7 @@ module: sys triple: module; search; path single: PySys_SetArgv() + single: PySys_SetArgvEx() single: Py_Finalize() Initialize the Python interpreter. In an application embedding Python, this @@ -31,7 +32,7 @@ the table of loaded modules (``sys.modules``), and creates the fundamental modules :mod:`__builtin__`, :mod:`__main__` and :mod:`sys`. It also initializes the module search path (``sys.path``). It does not set ``sys.argv``; use - :cfunc:`PySys_SetArgv` for that. This is a no-op when called for a second time + :cfunc:`PySys_SetArgvEx` for that. This is a no-op when called for a second time (without calling :cfunc:`Py_Finalize` first). There is no return value; it is a fatal error if the initialization fails. @@ -338,7 +339,7 @@ ``sys.version``. -.. cfunction:: void PySys_SetArgv(int argc, char **argv) +.. cfunction:: void PySys_SetArgvEx(int argc, char **argv, int updatepath) .. index:: single: main() @@ -353,14 +354,41 @@ string. If this function fails to initialize :data:`sys.argv`, a fatal condition is signalled using :cfunc:`Py_FatalError`. - This function also prepends the executed script's path to :data:`sys.path`. - If no script is executed (in the case of calling ``python -c`` or just the - interactive interpreter), the empty string is used instead. + If *updatepath* is zero, this is all the function does. If *updatepath* + is non-zero, the function also modifies :data:`sys.path` according to the + following algorithm: + + - If the name of an existing script is passed in ``argv[0]``, the absolute + path of the directory where the script is located is prepended to + :data:`sys.path`. + - Otherwise (that is, if *argc* is 0 or ``argv[0]`` doesn't point + to an existing file name), an empty string is prepended to + :data:`sys.path`, which is the same as prepending the current working + directory (``"."``). + + .. note:: + It is recommended that applications embedding the Python interpreter + for purposes other than executing a single script pass 0 as *updatepath*, + and update :data:`sys.path` themselves if desired. + See `CVE-2008-5983 `_. + + On versions before 2.6.6, you can achieve the same effect by manually + popping the first :data:`sys.path` element after having called + :cfunc:`PySys_SetArgv`, for example using:: + + PyRun_SimpleString("import sys; sys.path.pop(0)\n"); + + .. versionadded:: 2.6.6 .. XXX impl. doesn't seem consistent in allowing 0/NULL for the params; check w/ Guido. +.. cfunction:: void PySys_SetArgv(int argc, char **argv) + + This function works like :cfunc:`PySys_SetArgv` with *updatepath* set to 1. + + .. cfunction:: void Py_SetPythonHome(char *home) Set the default "home" directory, that is, the location of the standard Modified: python/trunk/Include/sysmodule.h ============================================================================== --- python/trunk/Include/sysmodule.h (original) +++ python/trunk/Include/sysmodule.h Fri May 21 19:12:38 2010 @@ -11,6 +11,7 @@ PyAPI_FUNC(int) PySys_SetObject(char *, PyObject *); PyAPI_FUNC(FILE *) PySys_GetFile(char *, FILE *); PyAPI_FUNC(void) PySys_SetArgv(int, char **); +PyAPI_FUNC(void) PySys_SetArgvEx(int, char **, int); PyAPI_FUNC(void) PySys_SetPath(char *); PyAPI_FUNC(void) PySys_WriteStdout(const char *format, ...) Modified: python/trunk/Misc/NEWS ============================================================================== --- python/trunk/Misc/NEWS (original) +++ python/trunk/Misc/NEWS Fri May 21 19:12:38 2010 @@ -18,6 +18,14 @@ - Issue #7079: Fix a possible crash when closing a file object while using it from another thread. Patch by Daniel Stutzbach. +C-API +----- + +- Issue #5753: A new C API function, :cfunc:`PySys_SetArgvEx`, allows + embedders of the interpreter to set sys.argv without also modifying + sys.path. This helps fix `CVE-2008-5983 + `_. + Library ------- Modified: python/trunk/Python/sysmodule.c ============================================================================== --- python/trunk/Python/sysmodule.c (original) +++ python/trunk/Python/sysmodule.c Fri May 21 19:12:38 2010 @@ -1649,7 +1649,7 @@ } void -PySys_SetArgv(int argc, char **argv) +PySys_SetArgvEx(int argc, char **argv, int updatepath) { #if defined(HAVE_REALPATH) char fullpath[MAXPATHLEN]; @@ -1662,7 +1662,7 @@ Py_FatalError("no mem for sys.argv"); if (PySys_SetObject("argv", av) != 0) Py_FatalError("can't assign sys.argv"); - if (path != NULL) { + if (updatepath && path != NULL) { char *argv0 = argv[0]; char *p = NULL; Py_ssize_t n = 0; @@ -1752,6 +1752,12 @@ Py_DECREF(av); } +void +PySys_SetArgv(int argc, char **argv) +{ + PySys_SetArgvEx(argc, argv, 1); +} + /* APIs to write to sys.stdout or sys.stderr using a printf-like interface. Adapted from code submitted by Just van Rossum. From python-checkins at python.org Fri May 21 19:22:44 2010 From: python-checkins at python.org (antoine.pitrou) Date: Fri, 21 May 2010 19:22:44 +0200 (CEST) Subject: [Python-checkins] r81399 - in python/branches/release26-maint: Doc/c-api/init.rst Include/sysmodule.h Misc/NEWS Python/sysmodule.c Message-ID: <20100521172244.378B9EE981@mail.python.org> Author: antoine.pitrou Date: Fri May 21 19:22:43 2010 New Revision: 81399 Log: Merged revisions 81398 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r81398 | antoine.pitrou | 2010-05-21 19:12:38 +0200 (ven., 21 mai 2010) | 6 lines Issue #5753: A new C API function, :cfunc:`PySys_SetArgvEx`, allows embedders of the interpreter to set sys.argv without also modifying sys.path. This helps fix `CVE-2008-5983 `_. ........ Modified: python/branches/release26-maint/ (props changed) python/branches/release26-maint/Doc/c-api/init.rst python/branches/release26-maint/Include/sysmodule.h python/branches/release26-maint/Misc/NEWS python/branches/release26-maint/Python/sysmodule.c Modified: python/branches/release26-maint/Doc/c-api/init.rst ============================================================================== --- python/branches/release26-maint/Doc/c-api/init.rst (original) +++ python/branches/release26-maint/Doc/c-api/init.rst Fri May 21 19:22:43 2010 @@ -22,6 +22,7 @@ module: sys triple: module; search; path single: PySys_SetArgv() + single: PySys_SetArgvEx() single: Py_Finalize() Initialize the Python interpreter. In an application embedding Python, this @@ -31,7 +32,7 @@ the table of loaded modules (``sys.modules``), and creates the fundamental modules :mod:`__builtin__`, :mod:`__main__` and :mod:`sys`. It also initializes the module search path (``sys.path``). It does not set ``sys.argv``; use - :cfunc:`PySys_SetArgv` for that. This is a no-op when called for a second time + :cfunc:`PySys_SetArgvEx` for that. This is a no-op when called for a second time (without calling :cfunc:`Py_Finalize` first). There is no return value; it is a fatal error if the initialization fails. @@ -338,7 +339,7 @@ ``sys.version``. -.. cfunction:: void PySys_SetArgv(int argc, char **argv) +.. cfunction:: void PySys_SetArgvEx(int argc, char **argv, int updatepath) .. index:: single: main() @@ -353,14 +354,41 @@ string. If this function fails to initialize :data:`sys.argv`, a fatal condition is signalled using :cfunc:`Py_FatalError`. - This function also prepends the executed script's path to :data:`sys.path`. - If no script is executed (in the case of calling ``python -c`` or just the - interactive interpreter), the empty string is used instead. + If *updatepath* is zero, this is all the function does. If *updatepath* + is non-zero, the function also modifies :data:`sys.path` according to the + following algorithm: + + - If the name of an existing script is passed in ``argv[0]``, the absolute + path of the directory where the script is located is prepended to + :data:`sys.path`. + - Otherwise (that is, if *argc* is 0 or ``argv[0]`` doesn't point + to an existing file name), an empty string is prepended to + :data:`sys.path`, which is the same as prepending the current working + directory (``"."``). + + .. note:: + It is recommended that applications embedding the Python interpreter + for purposes other than executing a single script pass 0 as *updatepath*, + and update :data:`sys.path` themselves if desired. + See `CVE-2008-5983 `_. + + On versions before 2.6.6, you can achieve the same effect by manually + popping the first :data:`sys.path` element after having called + :cfunc:`PySys_SetArgv`, for example using:: + + PyRun_SimpleString("import sys; sys.path.pop(0)\n"); + + .. versionadded:: 2.6.6 .. XXX impl. doesn't seem consistent in allowing 0/NULL for the params; check w/ Guido. +.. cfunction:: void PySys_SetArgv(int argc, char **argv) + + This function works like :cfunc:`PySys_SetArgv` with *updatepath* set to 1. + + .. cfunction:: void Py_SetPythonHome(char *home) Set the default "home" directory, that is, the location of the standard Modified: python/branches/release26-maint/Include/sysmodule.h ============================================================================== --- python/branches/release26-maint/Include/sysmodule.h (original) +++ python/branches/release26-maint/Include/sysmodule.h Fri May 21 19:22:43 2010 @@ -11,6 +11,7 @@ PyAPI_FUNC(int) PySys_SetObject(char *, PyObject *); PyAPI_FUNC(FILE *) PySys_GetFile(char *, FILE *); PyAPI_FUNC(void) PySys_SetArgv(int, char **); +PyAPI_FUNC(void) PySys_SetArgvEx(int, char **, int); PyAPI_FUNC(void) PySys_SetPath(char *); PyAPI_FUNC(void) PySys_WriteStdout(const char *format, ...) Modified: python/branches/release26-maint/Misc/NEWS ============================================================================== --- python/branches/release26-maint/Misc/NEWS (original) +++ python/branches/release26-maint/Misc/NEWS Fri May 21 19:22:43 2010 @@ -44,6 +44,14 @@ - Issue #7072: isspace(0xa0) is true on Mac OS X +C-API +----- + +- Issue #5753: A new C API function, :cfunc:`PySys_SetArgvEx`, allows + embedders of the interpreter to set sys.argv without also modifying + sys.path. This helps fix `CVE-2008-5983 + `_. + Library ------- Modified: python/branches/release26-maint/Python/sysmodule.c ============================================================================== --- python/branches/release26-maint/Python/sysmodule.c (original) +++ python/branches/release26-maint/Python/sysmodule.c Fri May 21 19:22:43 2010 @@ -1528,7 +1528,7 @@ } void -PySys_SetArgv(int argc, char **argv) +PySys_SetArgvEx(int argc, char **argv, int updatepath) { #if defined(HAVE_REALPATH) char fullpath[MAXPATHLEN]; @@ -1541,7 +1541,7 @@ Py_FatalError("no mem for sys.argv"); if (PySys_SetObject("argv", av) != 0) Py_FatalError("can't assign sys.argv"); - if (path != NULL) { + if (updatepath && path != NULL) { char *argv0 = argv[0]; char *p = NULL; Py_ssize_t n = 0; @@ -1631,6 +1631,12 @@ Py_DECREF(av); } +void +PySys_SetArgv(int argc, char **argv) +{ + PySys_SetArgvEx(argc, argv, 1); +} + /* APIs to write to sys.stdout or sys.stderr using a printf-like interface. Adapted from code submitted by Just van Rossum. From python-checkins at python.org Fri May 21 19:25:34 2010 From: python-checkins at python.org (antoine.pitrou) Date: Fri, 21 May 2010 19:25:34 +0200 (CEST) Subject: [Python-checkins] r81400 - in python/branches/py3k: Doc/c-api/init.rst Include/sysmodule.h Misc/NEWS Python/sysmodule.c Message-ID: <20100521172534.7BD51EE9BB@mail.python.org> Author: antoine.pitrou Date: Fri May 21 19:25:34 2010 New Revision: 81400 Log: Merged revisions 81398 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r81398 | antoine.pitrou | 2010-05-21 19:12:38 +0200 (ven., 21 mai 2010) | 6 lines Issue #5753: A new C API function, :cfunc:`PySys_SetArgvEx`, allows embedders of the interpreter to set sys.argv without also modifying sys.path. This helps fix `CVE-2008-5983 `_. ........ Modified: python/branches/py3k/ (props changed) python/branches/py3k/Doc/c-api/init.rst python/branches/py3k/Include/sysmodule.h python/branches/py3k/Misc/NEWS python/branches/py3k/Python/sysmodule.c Modified: python/branches/py3k/Doc/c-api/init.rst ============================================================================== --- python/branches/py3k/Doc/c-api/init.rst (original) +++ python/branches/py3k/Doc/c-api/init.rst Fri May 21 19:25:34 2010 @@ -22,6 +22,7 @@ module: sys triple: module; search; path single: PySys_SetArgv() + single: PySys_SetArgvEx() single: Py_Finalize() Initialize the Python interpreter. In an application embedding Python, this @@ -31,7 +32,7 @@ the table of loaded modules (``sys.modules``), and creates the fundamental modules :mod:`builtins`, :mod:`__main__` and :mod:`sys`. It also initializes the module search path (``sys.path``). It does not set ``sys.argv``; use - :cfunc:`PySys_SetArgv` for that. This is a no-op when called for a second time + :cfunc:`PySys_SetArgvEx` for that. This is a no-op when called for a second time (without calling :cfunc:`Py_Finalize` first). There is no return value; it is a fatal error if the initialization fails. @@ -337,7 +338,7 @@ ``sys.version``. -.. cfunction:: void PySys_SetArgv(int argc, wchar_t **argv) +.. cfunction:: void PySys_SetArgvEx(int argc, wchar_t **argv, int updatepath) .. index:: single: main() @@ -352,14 +353,41 @@ string. If this function fails to initialize :data:`sys.argv`, a fatal condition is signalled using :cfunc:`Py_FatalError`. - This function also prepends the executed script's path to :data:`sys.path`. - If no script is executed (in the case of calling ``python -c`` or just the - interactive interpreter), the empty string is used instead. + If *updatepath* is zero, this is all the function does. If *updatepath* + is non-zero, the function also modifies :data:`sys.path` according to the + following algorithm: + + - If the name of an existing script is passed in ``argv[0]``, the absolute + path of the directory where the script is located is prepended to + :data:`sys.path`. + - Otherwise (that is, if *argc* is 0 or ``argv[0]`` doesn't point + to an existing file name), an empty string is prepended to + :data:`sys.path`, which is the same as prepending the current working + directory (``"."``). + + .. note:: + It is recommended that applications embedding the Python interpreter + for purposes other than executing a single script pass 0 as *updatepath*, + and update :data:`sys.path` themselves if desired. + See `CVE-2008-5983 `_. + + On versions before 3.1.3, you can achieve the same effect by manually + popping the first :data:`sys.path` element after having called + :cfunc:`PySys_SetArgv`, for example using:: + + PyRun_SimpleString("import sys; sys.path.pop(0)\n"); + + .. versionadded:: 3.1.3 .. XXX impl. doesn't seem consistent in allowing 0/NULL for the params; check w/ Guido. +.. cfunction:: void PySys_SetArgv(int argc, wchar_t **argv) + + This function works like :cfunc:`PySys_SetArgv` with *updatepath* set to 1. + + .. cfunction:: void Py_SetPythonHome(wchar_t *home) Set the default "home" directory, that is, the location of the standard Modified: python/branches/py3k/Include/sysmodule.h ============================================================================== --- python/branches/py3k/Include/sysmodule.h (original) +++ python/branches/py3k/Include/sysmodule.h Fri May 21 19:25:34 2010 @@ -10,6 +10,7 @@ PyAPI_FUNC(PyObject *) PySys_GetObject(const char *); PyAPI_FUNC(int) PySys_SetObject(const char *, PyObject *); PyAPI_FUNC(void) PySys_SetArgv(int, wchar_t **); +PyAPI_FUNC(void) PySys_SetArgvEx(int, wchar_t **, int); PyAPI_FUNC(void) PySys_SetPath(const wchar_t *); PyAPI_FUNC(void) PySys_WriteStdout(const char *format, ...) Modified: python/branches/py3k/Misc/NEWS ============================================================================== --- python/branches/py3k/Misc/NEWS (original) +++ python/branches/py3k/Misc/NEWS Fri May 21 19:25:34 2010 @@ -334,6 +334,11 @@ C-API ----- +- Issue #5753: A new C API function, :cfunc:`PySys_SetArgvEx`, allows + embedders of the interpreter to set sys.argv without also modifying + sys.path. This helps fix `CVE-2008-5983 + `_. + - Add PyArg_ValidateKeywordArguments, which checks if all keyword arguments are strings in an efficient manner. Modified: python/branches/py3k/Python/sysmodule.c ============================================================================== --- python/branches/py3k/Python/sysmodule.c (original) +++ python/branches/py3k/Python/sysmodule.c Fri May 21 19:25:34 2010 @@ -1668,7 +1668,7 @@ #endif void -PySys_SetArgv(int argc, wchar_t **argv) +PySys_SetArgvEx(int argc, wchar_t **argv, int updatepath) { #if defined(HAVE_REALPATH) wchar_t fullpath[MAXPATHLEN]; @@ -1681,7 +1681,7 @@ Py_FatalError("no mem for sys.argv"); if (PySys_SetObject("argv", av) != 0) Py_FatalError("can't assign sys.argv"); - if (path != NULL) { + if (updatepath && path != NULL) { wchar_t *argv0 = argv[0]; wchar_t *p = NULL; Py_ssize_t n = 0; @@ -1768,6 +1768,12 @@ Py_DECREF(av); } +void +PySys_SetArgv(int argc, wchar_t **argv) +{ + PySys_SetArgvEx(argc, argv, 1); +} + /* Reimplementation of PyFile_WriteString() no calling indirectly PyErr_CheckSignals(): avoid the call to PyObject_Str(). */ From python-checkins at python.org Fri May 21 19:33:14 2010 From: python-checkins at python.org (antoine.pitrou) Date: Fri, 21 May 2010 19:33:14 +0200 (CEST) Subject: [Python-checkins] r81401 - in python/branches/release31-maint: Doc/c-api/init.rst Include/sysmodule.h Misc/NEWS Python/sysmodule.c Message-ID: <20100521173314.AC626EE998@mail.python.org> Author: antoine.pitrou Date: Fri May 21 19:33:14 2010 New Revision: 81401 Log: Merged revisions 81400 via svnmerge from svn+ssh://pythondev at svn.python.org/python/branches/py3k ................ r81400 | antoine.pitrou | 2010-05-21 19:25:34 +0200 (ven., 21 mai 2010) | 12 lines Merged revisions 81398 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r81398 | antoine.pitrou | 2010-05-21 19:12:38 +0200 (ven., 21 mai 2010) | 6 lines Issue #5753: A new C API function, :cfunc:`PySys_SetArgvEx`, allows embedders of the interpreter to set sys.argv without also modifying sys.path. This helps fix `CVE-2008-5983 `_. ........ ................ Modified: python/branches/release31-maint/ (props changed) python/branches/release31-maint/Doc/c-api/init.rst python/branches/release31-maint/Include/sysmodule.h python/branches/release31-maint/Misc/NEWS python/branches/release31-maint/Python/sysmodule.c Modified: python/branches/release31-maint/Doc/c-api/init.rst ============================================================================== --- python/branches/release31-maint/Doc/c-api/init.rst (original) +++ python/branches/release31-maint/Doc/c-api/init.rst Fri May 21 19:33:14 2010 @@ -22,6 +22,7 @@ module: sys triple: module; search; path single: PySys_SetArgv() + single: PySys_SetArgvEx() single: Py_Finalize() Initialize the Python interpreter. In an application embedding Python, this @@ -31,7 +32,7 @@ the table of loaded modules (``sys.modules``), and creates the fundamental modules :mod:`builtins`, :mod:`__main__` and :mod:`sys`. It also initializes the module search path (``sys.path``). It does not set ``sys.argv``; use - :cfunc:`PySys_SetArgv` for that. This is a no-op when called for a second time + :cfunc:`PySys_SetArgvEx` for that. This is a no-op when called for a second time (without calling :cfunc:`Py_Finalize` first). There is no return value; it is a fatal error if the initialization fails. @@ -344,7 +345,7 @@ ``sys.version``. -.. cfunction:: void PySys_SetArgv(int argc, wchar_t **argv) +.. cfunction:: void PySys_SetArgvEx(int argc, wchar_t **argv, int updatepath) .. index:: single: main() @@ -359,14 +360,41 @@ string. If this function fails to initialize :data:`sys.argv`, a fatal condition is signalled using :cfunc:`Py_FatalError`. - This function also prepends the executed script's path to :data:`sys.path`. - If no script is executed (in the case of calling ``python -c`` or just the - interactive interpreter), the empty string is used instead. + If *updatepath* is zero, this is all the function does. If *updatepath* + is non-zero, the function also modifies :data:`sys.path` according to the + following algorithm: + + - If the name of an existing script is passed in ``argv[0]``, the absolute + path of the directory where the script is located is prepended to + :data:`sys.path`. + - Otherwise (that is, if *argc* is 0 or ``argv[0]`` doesn't point + to an existing file name), an empty string is prepended to + :data:`sys.path`, which is the same as prepending the current working + directory (``"."``). + + .. note:: + It is recommended that applications embedding the Python interpreter + for purposes other than executing a single script pass 0 as *updatepath*, + and update :data:`sys.path` themselves if desired. + See `CVE-2008-5983 `_. + + On versions before 3.1.3, you can achieve the same effect by manually + popping the first :data:`sys.path` element after having called + :cfunc:`PySys_SetArgv`, for example using:: + + PyRun_SimpleString("import sys; sys.path.pop(0)\n"); + + .. versionadded:: 3.1.3 .. XXX impl. doesn't seem consistent in allowing 0/NULL for the params; check w/ Guido. +.. cfunction:: void PySys_SetArgv(int argc, wchar_t **argv) + + This function works like :cfunc:`PySys_SetArgv` with *updatepath* set to 1. + + .. cfunction:: void Py_SetPythonHome(wchar_t *home) Set the default "home" directory, that is, the location of the standard Modified: python/branches/release31-maint/Include/sysmodule.h ============================================================================== --- python/branches/release31-maint/Include/sysmodule.h (original) +++ python/branches/release31-maint/Include/sysmodule.h Fri May 21 19:33:14 2010 @@ -10,6 +10,7 @@ PyAPI_FUNC(PyObject *) PySys_GetObject(const char *); PyAPI_FUNC(int) PySys_SetObject(const char *, PyObject *); PyAPI_FUNC(void) PySys_SetArgv(int, wchar_t **); +PyAPI_FUNC(void) PySys_SetArgvEx(int, wchar_t **, int); PyAPI_FUNC(void) PySys_SetPath(const wchar_t *); PyAPI_FUNC(void) PySys_WriteStdout(const char *format, ...) Modified: python/branches/release31-maint/Misc/NEWS ============================================================================== --- python/branches/release31-maint/Misc/NEWS (original) +++ python/branches/release31-maint/Misc/NEWS Fri May 21 19:33:14 2010 @@ -43,6 +43,14 @@ - Issue #7072: isspace(0xa0) is true on Mac OS X +C-API +----- + +- Issue #5753: A new C API function, :cfunc:`PySys_SetArgvEx`, allows + embedders of the interpreter to set sys.argv without also modifying + sys.path. This helps fix `CVE-2008-5983 + `_. + Library ------- Modified: python/branches/release31-maint/Python/sysmodule.c ============================================================================== --- python/branches/release31-maint/Python/sysmodule.c (original) +++ python/branches/release31-maint/Python/sysmodule.c Fri May 21 19:33:14 2010 @@ -1555,7 +1555,7 @@ #endif void -PySys_SetArgv(int argc, wchar_t **argv) +PySys_SetArgvEx(int argc, wchar_t **argv, int updatepath) { #if defined(HAVE_REALPATH) wchar_t fullpath[MAXPATHLEN]; @@ -1568,7 +1568,7 @@ Py_FatalError("no mem for sys.argv"); if (PySys_SetObject("argv", av) != 0) Py_FatalError("can't assign sys.argv"); - if (path != NULL) { + if (updatepath && path != NULL) { wchar_t *argv0 = argv[0]; wchar_t *p = NULL; Py_ssize_t n = 0; @@ -1655,6 +1655,12 @@ Py_DECREF(av); } +void +PySys_SetArgv(int argc, wchar_t **argv) +{ + PySys_SetArgvEx(argc, argv, 1); +} + /* Reimplementation of PyFile_WriteString() no calling indirectly PyErr_CheckSignals(): avoid the call to PyObject_Str(). */ From python-checkins at python.org Fri May 21 19:41:34 2010 From: python-checkins at python.org (vinay.sajip) Date: Fri, 21 May 2010 19:41:34 +0200 (CEST) Subject: [Python-checkins] r81402 - python/trunk/Doc/library/logging.rst Message-ID: <20100521174134.6548EEE989@mail.python.org> Author: vinay.sajip Date: Fri May 21 19:41:34 2010 New Revision: 81402 Log: Updated logging documentation with more dictConfig information. Modified: python/trunk/Doc/library/logging.rst Modified: python/trunk/Doc/library/logging.rst ============================================================================== --- python/trunk/Doc/library/logging.rst (original) +++ python/trunk/Doc/library/logging.rst Fri May 21 19:41:34 2010 @@ -440,6 +440,45 @@ class defined in package :mod:`mypackage` and module :mod:`mymodule`, where :mod:`mypackage` is available on the Python import path). +.. versionchanged:: 2.7 + +In Python 2.7, a new means of configuring logging has been introduced, using +dictionaries to hold configuration information. This provides a superset of the +functionality of the config-file-based approach outlined above, and is the +recommended configuration method for new applications and deployments. Because +a Python dictionary is used to hold configuration information, and since you +can populate that dictionary using different means, you have more options for +configuration. For example, you can use a configuration file in JSON format, +or, if you have access to YAML processing functionality, a file in YAML +format, to populate the configuration dictionary. Or, of course, you can +construct the dictionary in Python code, receive it in pickled form over a +socket, or use whatever approach makes sense for your application. + +Here's an example of the same configuration as above, in YAML format for +the new dictionary-based approach:: + + version: 1 + formatters: + simple: + format: format=%(asctime)s - %(name)s - %(levelname)s - %(message)s + handlers: + console: + class: logging.StreamHandler + level: DEBUG + formatter: simple + stream: ext://sys.stdout + loggers: + simpleExample: + level: DEBUG + handlers: [console] + propagate: no + root: + level: DEBUG + handlers: [console] + +For more information about logging using a dictionary, see +:ref:`logging-config-api`. + .. _library-config: Configuring Logging for a Library From python-checkins at python.org Fri May 21 22:13:12 2010 From: python-checkins at python.org (victor.stinner) Date: Fri, 21 May 2010 22:13:12 +0200 (CEST) Subject: [Python-checkins] r81403 - in python/branches/py3k/Lib: subprocess.py test/test_subprocess.py Message-ID: <20100521201312.ECB2BEE9BE@mail.python.org> Author: victor.stinner Date: Fri May 21 22:13:12 2010 New Revision: 81403 Log: Issue #8780: Fix a regression introduced by r78946 in subprocess on Windows Ensure that stdout / stderr is inherited from the parent if stdout=PIPE / stderr=PIPE is not used. Modified: python/branches/py3k/Lib/subprocess.py python/branches/py3k/Lib/test/test_subprocess.py Modified: python/branches/py3k/Lib/subprocess.py ============================================================================== --- python/branches/py3k/Lib/subprocess.py (original) +++ python/branches/py3k/Lib/subprocess.py Fri May 21 22:13:12 2010 @@ -843,7 +843,7 @@ # Process startup details if startupinfo is None: startupinfo = STARTUPINFO() - if None not in (p2cread, c2pwrite, errwrite): + if -1 not in (p2cread, c2pwrite, errwrite): startupinfo.dwFlags |= _subprocess.STARTF_USESTDHANDLES startupinfo.hStdInput = p2cread startupinfo.hStdOutput = c2pwrite Modified: python/branches/py3k/Lib/test/test_subprocess.py ============================================================================== --- python/branches/py3k/Lib/test/test_subprocess.py (original) +++ python/branches/py3k/Lib/test/test_subprocess.py Fri May 21 22:13:12 2010 @@ -535,6 +535,17 @@ if c.exception.errno != 2: # ignore "no such file" raise c.exception + def test_issue8780(self): + # Ensure that stdout is inherited from the parent + # if stdout=PIPE is not used + code = ';'.join(( + 'import subprocess, sys', + 'retcode = subprocess.call(' + "[sys.executable, '-c', 'print(\"Hello World!\")'])", + 'assert retcode == 0')) + output = subprocess.check_output([sys.executable, '-c', code]) + self.assert_(output.startswith(b'Hello World!'), ascii(output)) + # context manager class _SuppressCoreFiles(object): From python-checkins at python.org Fri May 21 22:24:45 2010 From: python-checkins at python.org (georg.brandl) Date: Fri, 21 May 2010 22:24:45 +0200 (CEST) Subject: [Python-checkins] r81404 - python/trunk/Doc/library/hashlib.rst Message-ID: <20100521202445.A84DDEE989@mail.python.org> Author: georg.brandl Date: Fri May 21 22:24:45 2010 New Revision: 81404 Log: #8783: replace link to now dead hash collision FAQ. Modified: python/trunk/Doc/library/hashlib.rst Modified: python/trunk/Doc/library/hashlib.rst ============================================================================== --- python/trunk/Doc/library/hashlib.rst (original) +++ python/trunk/Doc/library/hashlib.rst Fri May 21 22:24:45 2010 @@ -142,7 +142,7 @@ http://csrc.nist.gov/publications/fips/fips180-2/fips180-2.pdf The FIPS 180-2 publication on Secure Hash Algorithms. - http://www.cryptography.com/cnews/hash.html - Hash Collision FAQ with information on which algorithms have known issues and + http://en.wikipedia.org/wiki/Cryptographic_hash_function#Cryptographic_hash_algorithms + Wikipedia article with information on which algorithms have known issues and what that means regarding their use. From python-checkins at python.org Fri May 21 22:28:10 2010 From: python-checkins at python.org (georg.brandl) Date: Fri, 21 May 2010 22:28:10 +0200 (CEST) Subject: [Python-checkins] r81405 - in python/branches/release26-maint: Doc/library/hashlib.rst Message-ID: <20100521202810.8B8E0EE989@mail.python.org> Author: georg.brandl Date: Fri May 21 22:28:10 2010 New Revision: 81405 Log: Merged revisions 81404 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r81404 | georg.brandl | 2010-05-21 22:24:45 +0200 (Fr, 21 Mai 2010) | 1 line #8783: replace link to now dead hash collision FAQ. ........ Modified: python/branches/release26-maint/ (props changed) python/branches/release26-maint/Doc/library/hashlib.rst Modified: python/branches/release26-maint/Doc/library/hashlib.rst ============================================================================== --- python/branches/release26-maint/Doc/library/hashlib.rst (original) +++ python/branches/release26-maint/Doc/library/hashlib.rst Fri May 21 22:28:10 2010 @@ -127,7 +127,7 @@ http://csrc.nist.gov/publications/fips/fips180-2/fips180-2.pdf The FIPS 180-2 publication on Secure Hash Algorithms. - http://www.cryptography.com/cnews/hash.html - Hash Collision FAQ with information on which algorithms have known issues and + http://en.wikipedia.org/wiki/Cryptographic_hash_function#Cryptographic_hash_algorithms + Wikipedia article with information on which algorithms have known issues and what that means regarding their use. From python-checkins at python.org Fri May 21 22:28:13 2010 From: python-checkins at python.org (georg.brandl) Date: Fri, 21 May 2010 22:28:13 +0200 (CEST) Subject: [Python-checkins] r81406 - in python/branches/py3k: Doc/library/hashlib.rst Message-ID: <20100521202813.9C402EE99C@mail.python.org> Author: georg.brandl Date: Fri May 21 22:28:13 2010 New Revision: 81406 Log: Merged revisions 81404 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r81404 | georg.brandl | 2010-05-21 22:24:45 +0200 (Fr, 21 Mai 2010) | 1 line #8783: replace link to now dead hash collision FAQ. ........ Modified: python/branches/py3k/ (props changed) python/branches/py3k/Doc/library/hashlib.rst Modified: python/branches/py3k/Doc/library/hashlib.rst ============================================================================== --- python/branches/py3k/Doc/library/hashlib.rst (original) +++ python/branches/py3k/Doc/library/hashlib.rst Fri May 21 22:28:13 2010 @@ -151,7 +151,7 @@ http://csrc.nist.gov/publications/fips/fips180-2/fips180-2.pdf The FIPS 180-2 publication on Secure Hash Algorithms. - http://www.cryptography.com/cnews/hash.html - Hash Collision FAQ with information on which algorithms have known issues and + http://en.wikipedia.org/wiki/Cryptographic_hash_function#Cryptographic_hash_algorithms + Wikipedia article with information on which algorithms have known issues and what that means regarding their use. From python-checkins at python.org Fri May 21 22:36:04 2010 From: python-checkins at python.org (georg.brandl) Date: Fri, 21 May 2010 22:36:04 +0200 (CEST) Subject: [Python-checkins] r81407 - in python/branches/release31-maint: Doc/faq/programming.rst Doc/library/hashlib.rst Message-ID: <20100521203604.137B0EE981@mail.python.org> Author: georg.brandl Date: Fri May 21 22:36:03 2010 New Revision: 81407 Log: Merged revisions 76888,76922,81406 via svnmerge from svn+ssh://svn.python.org/python/branches/py3k ................ r76888 | georg.brandl | 2009-12-19 18:51:41 +0100 (Sa, 19 Dez 2009) | 1 line #7495: Review of Programming FAQ by Florent Xicluna. ................ r76922 | georg.brandl | 2009-12-20 15:21:27 +0100 (So, 20 Dez 2009) | 1 line #7495: more review fixes. ................ r81406 | georg.brandl | 2010-05-21 22:28:13 +0200 (Fr, 21 Mai 2010) | 9 lines Merged revisions 81404 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r81404 | georg.brandl | 2010-05-21 22:24:45 +0200 (Fr, 21 Mai 2010) | 1 line #8783: replace link to now dead hash collision FAQ. ........ ................ Modified: python/branches/release31-maint/ (props changed) python/branches/release31-maint/Doc/faq/programming.rst python/branches/release31-maint/Doc/library/hashlib.rst Modified: python/branches/release31-maint/Doc/faq/programming.rst ============================================================================== --- python/branches/release31-maint/Doc/faq/programming.rst (original) +++ python/branches/release31-maint/Doc/faq/programming.rst Fri May 21 22:36:03 2010 @@ -176,31 +176,32 @@ it is much shorter and far faster to use :: - L2 = list(L1[:3]) # "list" is redundant if L1 is a list. + L2 = list(L1[:3]) # "list" is redundant if L1 is a list. Note that the functionally-oriented builtins such as :func:`map`, :func:`zip`, and friends can be a convenient accelerator for loops that perform a single task. For example to pair the elements of two lists together:: - >>> zip([1,2,3], [4,5,6]) + >>> list(zip([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] + >>> list(map(math.sin, (1, 2, 3, 4))) + [0.841470984808, 0.909297426826, 0.14112000806, -0.756802495308] The operation completes very quickly in such cases. -Other examples include the ``join()`` and ``split()`` methods of string objects. +Other examples include the ``join()`` and ``split()`` :ref:`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 the copying in one pass. For -manipulating strings, use the ``replace()`` method on string objects. Use -regular expressions only when you're not dealing with constant string patterns. -Consider using the string formatting operations ``string % tuple`` and ``string -% dictionary``. +manipulating strings, use the ``replace()`` and the ``format()`` :ref:`methods +on string objects `. Use regular expressions only when you're +not dealing with constant string patterns. Be sure to use the :meth:`list.sort` builtin method to do sorting, and see the `sorting mini-HOWTO `_ for examples @@ -210,7 +211,7 @@ 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 to determine that a Python function ``ff()`` is being called lots of times. If you -notice that ``ff ()``:: +notice that ``ff()``:: def ff(x): ... # do something with x computing result... @@ -387,7 +388,7 @@ import config import mod - print config.x + print(config.x) Note that using a module is also the basis for implementing the Singleton design pattern, for the same reason. @@ -408,16 +409,15 @@ It's good practice if you import modules in the following order: -1. standard library modules -- e.g. ``sys``, ``os``, ``getopt``, ``re``) +1. standard library modules -- e.g. ``sys``, ``os``, ``getopt``, ``re`` 2. third-party library modules (anything installed in Python's site-packages directory) -- e.g. mx.DateTime, ZODB, PIL.Image, etc. 3. locally-developed modules Never use relative package imports. If you're writing code that's in the ``package.sub.m1`` module and want to import ``package.sub.m2``, do not just -write ``import m2``, even though it's legal. Write ``from package.sub import -m2`` instead. Relative imports can lead to a module being initialized twice, -leading to confusing bugs. +write ``from . import m2``, even though it's legal. Write ``from package.sub +import m2`` instead. See :pep:`328` for details. It is sometimes necessary to move imports to a function or class to avoid problems with circular imports. Gordon McMillan says: @@ -499,7 +499,7 @@ x, y = 'old-value', 99 x, y = func2(x, y) - print x, y # output: new-value 100 + print(x, y) # output: new-value 100 This is almost always the clearest solution. @@ -513,7 +513,7 @@ args = ['old-value', 99] func1(args) - print args[0], args[1] # output: new-value 100 + print(args[0], args[1]) # output: new-value 100 4) By passing in a dictionary that gets mutated:: @@ -523,7 +523,7 @@ args = {'a':' old-value', 'b': 99} func3(args) - print args['a'], args['b'] + print(args['a'], args['b']) 5) Or bundle up values in a class instance:: @@ -538,7 +538,7 @@ args = callByRef(a='old-value', b=99) func4(args) - print args.a, args.b + print(args.a, args.b) There's almost never a good reason to get this complicated. @@ -644,10 +644,10 @@ a = B() b = a - print b - <__main__.A instance at 016D07CC> - print a - <__main__.A instance at 016D07CC> + print(b) + <__main__.A object at 0x16D07CC> + print(a) + <__main__.A object at 0x16D07CC> 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 @@ -677,7 +677,7 @@ Comma is not an operator in Python. Consider this session:: >>> "a" in "b", "a" - (False, '1') + (False, 'a') Since the comma is not an operator, but a separator between expressions the above is evaluated as if you had entered:: @@ -686,7 +686,7 @@ not:: - >>> "a" in ("5", "a") + >>> "a" in ("b", "a") The same is true of the various assignment operators (``=``, ``+=`` etc). They are not truly operators but syntactic delimiters in assignment statements. @@ -728,12 +728,12 @@ if not isfunction(on_true): return on_true else: - return apply(on_true) + return on_true() else: if not isfunction(on_false): return on_false else: - return apply(on_false) + return 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.: @@ -758,22 +758,24 @@ Yes. Usually this is done by nesting :keyword:`lambda` within :keyword:`lambda`. See the following three examples, due to Ulf Bartelt:: + from functools import reduce + # 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))) + print(list(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)) + print(list(map(lambda x,f=lambda x,f:(f(x-1,f)+f(x-2,f)) if x>1 else 1: + 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, + 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) + ))))(-2.1, 0.7, -1.2, 1.2, 30, 80, 24)) # \___ ___/ \___ ___/ | | |__ lines on screen # V V | |______ columns on screen # | | |__________ maximum of "iterations" @@ -789,10 +791,11 @@ 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:: +To specify an octal digit, precede the octal value with a zero, and then a lower +or uppercase "o". For example, to set the variable "a" to the octal value "10" +(8 in decimal), type:: - >>> a = 010 + >>> a = 0o10 >>> a 8 @@ -808,17 +811,17 @@ 178 -Why does -22 / 10 return -3? ----------------------------- +Why does -22 // 10 return -3? +----------------------------- It's primarily driven by the desire that ``i % j`` have the same sign as ``j``. If you want that, and also want:: - i == (i / j) * j + (i % j) + i == (i // j) * j + (i % j) then integer division has to return the floor. C also requires that identity to -hold, and then compilers that truncate ``i / j`` need to make ``i % j`` have the -same sign as ``i``. +hold, and then compilers that truncate ``i // j`` need to make ``i % j`` have +the same sign as ``i``. There are few real use cases for ``i % j`` when ``j`` is negative. When ``j`` is positive, there are many, and in virtually all of them it's more useful for @@ -848,8 +851,8 @@ directory. :func:`eval` also has the effect of interpreting numbers as Python expressions, -so that e.g. ``eval('09')`` gives a syntax error because Python regards numbers -starting with '0' as octal (base 8). +so that e.g. ``eval('09')`` gives a syntax error because Python does not allow +leading '0' in a decimal number (except '0'). How do I convert a number to a string? @@ -857,10 +860,9 @@ To convert, e.g., the number 144 to the string '144', use the built-in type constructor :func:`str`. If you want a hexadecimal or octal representation, use -the built-in functions ``hex()`` or ``oct()``. For fancy formatting, use -:ref:`the % operator ` on strings, e.g. ``"%04d" % 144`` -yields ``'0144'`` and ``"%.3f" % (1/3.0)`` yields ``'0.333'``. See the library -reference manual for details. +the built-in functions :func:`hex` or :func:`oct`. For fancy formatting, see +the :ref:`string-formatting` section, e.g. ``"{:04d}".format(144)`` yields +``'0144'`` and ``"{:.3f}".format(1/3)`` yields ``'0.333'``. How do I modify a string in place? @@ -871,19 +873,20 @@ >>> s = "Hello, world" >>> a = list(s) - >>> print a + >>> print(a) ['H', 'e', 'l', 'l', 'o', ',', ' ', 'w', 'o', 'r', 'l', 'd'] >>> a[7:] = list("there!") >>> ''.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() + >>> a = array.array('u', s) + >>> print(a) + array('u', 'Hello, world') + >>> a[0] = 'y' + >>> print(a) + array('u', 'yello world') + >>> a.tounicode() 'yello, world' @@ -931,7 +934,7 @@ * Use :func:`locals` or :func:`eval` to resolve the function name:: def myFunc(): - print "hello" + print("hello") fname = "myFunc" @@ -958,12 +961,12 @@ ... "\r\n" ... "\r\n") >>> lines.rstrip("\n\r") - "line 1 " + 'line 1 ' Since this is typically only desired when reading text one line at a time, using ``S.rstrip()`` this way works well. -For older versions of Python, There are two partial substitutes: +For older versions of Python, there are two partial substitutes: - If you want to remove all trailing whitespace, use the ``rstrip()`` method of string objects. This removes all trailing whitespace, not just a single @@ -988,45 +991,10 @@ :cfunc:`sscanf` and better suited for the task. -What does 'UnicodeError: ASCII [decoding,encoding] error: ordinal not in range(128)' mean? ------------------------------------------------------------------------------------------- +What does 'UnicodeDecodeError' or 'UnicodeEncodeError' error mean? +------------------------------------------------------------------- -This error indicates that your Python installation can handle only 7-bit ASCII -strings. There are a couple ways to fix or work around the problem. - -If your programs must handle data in arbitrary 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 example, 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 :exc:`UnicodeError` exception. - -If you only want strings converted 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 - -It's possible to set a default encoding in a file called ``sitecustomize.py`` -that's part of the Python library. However, this isn't recommended because -changing the Python-wide default encoding may cause third-party extension -modules to fail. - -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. +See the :ref:`unicode-howto`. Sequences (Tuples/Lists) @@ -1089,26 +1057,26 @@ If you don't mind reordering the list, sort it and then scan from the end of the list, deleting duplicates as you go:: - if List: - List.sort() - last = List[-1] - for i in range(len(List)-2, -1, -1): - if last == List[i]: - del List[i] + if mylist: + mylist.sort() + last = mylist[-1] + for i in range(len(mylist)-2, -1, -1): + if last == mylist[i]: + del mylist[i] else: - last = List[i] + last = mylist[i] If all elements of the list may be used as dictionary keys (i.e. they are all hashable) this is often faster :: d = {} - for x in List: - d[x] = x - List = d.values() + for x in mylist: + d[x] = 1 + mylist = list(d.keys()) In Python 2.5 and later, the following is possible instead:: - List = list(set(List)) + mylist = list(set(mylist)) This converts the list into a set, thereby removing duplicates, and then back into a list. @@ -1184,15 +1152,7 @@ Use a list comprehension:: - result = [obj.method() for obj in List] - -More generically, you can try the following function:: - - def method_map(objects, method, arguments): - """method_map([a,b], "meth", (1,2)) gives [a.meth(1,2), b.meth(1,2)]""" - nobjects = len(objects) - methods = map(getattr, objects, [method]*nobjects) - return map(apply, methods, [arguments]*nobjects) + result = [obj.method() for obj in mylist] Dictionaries @@ -1209,23 +1169,17 @@ case, use the ``pprint`` module to pretty-print the dictionary; the items will be presented in order sorted by the key. -A more complicated solution is to subclass ``UserDict.UserDict`` to create a +A more complicated solution is to subclass ``dict`` 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): + class SortedDict(dict): 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, ", ") + keys = sorted(self.keys()) + result = ("{!r}: {!r}".format(k, self[k]) for k in keys) + return "{{{}}}".format(", ".join(result)) - __str__ = __repr__ + __str__ = __repr__ This will work for many common situations you might encounter, though it's far from a perfect solution. The largest flaw is that if some values in the @@ -1247,18 +1201,18 @@ sorting is quite simple to do with list comprehensions. To sort a list of strings by their uppercase values:: - tmp1 = [(x.upper(), x) for x in L] # Schwartzian transform + tmp1 = [(x.upper(), x) for x in L] # Schwartzian transform tmp1.sort() Usorted = [x[1] for x in tmp1] To sort by the integer value of a subfield extending from positions 10-15 in each string:: - tmp2 = [(int(s[10:15]), s) for s in L] # Schwartzian transform + 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 :: +For versions prior to 3.0, Isorted may also be computed by :: def intfield(s): return int(s[10:15]) @@ -1276,23 +1230,24 @@ How can I sort one list by values from another list? ---------------------------------------------------- -Merge them into a single list of tuples, sort the resulting list, and then pick +Merge them into an iterator of tuples, sort the resulting list, and then pick out the element you want. :: >>> list1 = ["what", "I'm", "sorting", "by"] >>> list2 = ["something", "else", "to", "sort"] >>> pairs = zip(list1, list2) + >>> pairs = sorted(pairs) >>> pairs - [('what', 'something'), ("I'm", 'else'), ('sorting', 'to'), ('by', 'sort')] - >>> pairs.sort() - >>> result = [ x[1] for x in pairs ] + [("I'm", 'else'), ('by', 'sort'), ('sorting', 'to'), ('what', 'something')] + >>> result = [x[1] for x in pairs] >>> result ['else', 'sort', 'to', 'something'] + An alternative for the last step is:: - result = [] - for p in pairs: result.append(p[1]) + >>> result = [] + >>> for p in pairs: result.append(p[1]) If you find this more legible, you might prefer to use this instead of the final list comprehension. However, it is almost twice as slow for long lists. Why? @@ -1351,7 +1306,7 @@ is an instance of any of a number of classes by providing a tuple instead of a single class, e.g. ``isinstance(obj, (class1, class2, ...))``, and can also check whether an object is one of Python's built-in types, e.g. -``isinstance(obj, str)`` or ``isinstance(obj, (int, long, float, complex))``. +``isinstance(obj, str)`` or ``isinstance(obj, (int, float, complex))``. Note that most programs do not use :func:`isinstance` on user-defined classes very often. If you are developing the classes yourself, a more proper @@ -1360,7 +1315,7 @@ different thing based on what class it is. For example, if you have a function that does something:: - def search (obj): + def search(obj): if isinstance(obj, Mailbox): # ... code to search a mailbox elif isinstance(obj, Document): @@ -1430,17 +1385,17 @@ How do I call a method defined in a base class from a derived class that overrides it? -------------------------------------------------------------------------------------- -If you're using new-style classes, use the built-in :func:`super` function:: +Use the built-in :func:`super` function:: class Derived(Base): def meth (self): super(Derived, self).meth() -If you're using classic classes: For a class definition such as ``class -Derived(Base): ...`` 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, so you need to provide the ``self`` -argument. +For version prior to 3.0, you may be using classic classes: For a class +definition such as ``class Derived(Base): ...`` 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, so you need to +provide the ``self`` argument. How can I organize my code to make it easier to change the base class? @@ -1463,8 +1418,8 @@ How do I create static class data and static class methods? ----------------------------------------------------------- -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. +Both static data and static methods (in the sense of C++ or Java) are supported +in Python. For static data, simply define a class attribute. To assign a new value to the attribute, you have to explicitly use the class name in the assignment:: @@ -1483,9 +1438,9 @@ search path from ``c.__class__`` back to ``C``. Caution: within a method of C, an assignment like ``self.count = 42`` creates a -new and unrelated instance vrbl named "count" in ``self``'s own dict. Rebinding -of a class-static data name must always specify the class whether inside a -method or not:: +new and unrelated instance named "count" in ``self``'s own dict. Rebinding of a +class-static data name must always specify the class whether inside a method or +not:: C.count = 314 @@ -1536,9 +1491,9 @@ class C: def __init__(self, i=None): if i is None: - print "No arguments" + print("No arguments") else: - print "Argument is", i + print("Argument is", i) This is not entirely equivalent, but close enough in practice. @@ -1597,11 +1552,13 @@ Tree data structures, for instance, should use weak references for their parent and sibling references (if they need them!). -If the object has ever been a local variable in 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, calling :func:`sys.exc_clear` will take care of this by clearing the -last recorded exception. +.. XXX relevant for Python 3? + + If the object has ever been a local variable in 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, calling :func:`sys.exc_clear` will take care of this by clearing + the last recorded exception. Finally, if your :meth:`__del__` method raises an exception, a warning message is printed to :data:`sys.stderr`. @@ -1669,7 +1626,7 @@ after checking ``__name__``:: def main(): - print 'Running test...' + print('Running test...') ... if __name__ == '__main__': @@ -1758,8 +1715,9 @@ basic module would be parsed and re-parsed many times. To force rereading of a changed module, do this:: + import imp import modname - reload(modname) + imp.reload(modname) Warning: this technique is not 100% fool-proof. In particular, modules containing statements like :: @@ -1771,17 +1729,18 @@ updated to use the new class definition. This can result in the following paradoxical behaviour: + >>> import imp >>> import cls >>> c = cls.C() # Create an instance of C - >>> reload(cls) - + >>> imp.reload(cls) + >>> isinstance(c, cls.C) # isinstance is false?!? False -The nature of the problem is made clear if you print out the class objects: - - >>> c.__class__ - - >>> cls.C - +The nature of the problem is made clear if you print out the "identity" of the +class objects: + >>> hex(id(c.__class__)) + '0x7352a0' + >>> hex(id(cls.C)) + '0x4198d0' Modified: python/branches/release31-maint/Doc/library/hashlib.rst ============================================================================== --- python/branches/release31-maint/Doc/library/hashlib.rst (original) +++ python/branches/release31-maint/Doc/library/hashlib.rst Fri May 21 22:36:03 2010 @@ -142,7 +142,7 @@ http://csrc.nist.gov/publications/fips/fips180-2/fips180-2.pdf The FIPS 180-2 publication on Secure Hash Algorithms. - http://www.cryptography.com/cnews/hash.html - Hash Collision FAQ with information on which algorithms have known issues and + http://en.wikipedia.org/wiki/Cryptographic_hash_function#Cryptographic_hash_algorithms + Wikipedia article with information on which algorithms have known issues and what that means regarding their use. From python-checkins at python.org Fri May 21 22:39:17 2010 From: python-checkins at python.org (victor.stinner) Date: Fri, 21 May 2010 22:39:17 +0200 (CEST) Subject: [Python-checkins] r81408 - in python/branches/release31-maint: Lib/test/test_subprocess.py Message-ID: <20100521203917.B8F47EE989@mail.python.org> Author: victor.stinner Date: Fri May 21 22:39:17 2010 New Revision: 81408 Log: Issue #8780: Only backport the new test, the fix is not needed Recorded merge of revisions 81403 via svnmerge from svn+ssh://pythondev at svn.python.org/python/branches/py3k ........ r81403 | victor.stinner | 2010-05-21 22:13:12 +0200 (ven., 21 mai 2010) | 5 lines Issue #8780: Fix a regression introduced by r78946 in subprocess on Windows Ensure that stdout / stderr is inherited from the parent if stdout=PIPE / stderr=PIPE is not used. ........ Modified: python/branches/release31-maint/ (props changed) python/branches/release31-maint/Lib/test/test_subprocess.py Modified: python/branches/release31-maint/Lib/test/test_subprocess.py ============================================================================== --- python/branches/release31-maint/Lib/test/test_subprocess.py (original) +++ python/branches/release31-maint/Lib/test/test_subprocess.py Fri May 21 22:39:17 2010 @@ -539,6 +539,17 @@ if err.errno != 2: # ignore "no such file" raise + def test_issue8780(self): + # Ensure that stdout is inherited from the parent + # if stdout=PIPE is not used + code = ';'.join(( + 'import subprocess, sys', + 'retcode = subprocess.call(' + "[sys.executable, '-c', 'print(\"Hello World!\")'])", + 'assert retcode == 0')) + output = subprocess.check_output([sys.executable, '-c', code]) + self.assert_(output.startswith(b'Hello World!'), ascii(output)) + # # POSIX tests # From python-checkins at python.org Fri May 21 22:42:22 2010 From: python-checkins at python.org (georg.brandl) Date: Fri, 21 May 2010 22:42:22 +0200 (CEST) Subject: [Python-checkins] r81409 - python/branches/release26-maint/Doc/library/2to3.rst Message-ID: <20100521204222.52D87EE981@mail.python.org> Author: georg.brandl Date: Fri May 21 22:42:22 2010 New Revision: 81409 Log: typo Modified: python/branches/release26-maint/Doc/library/2to3.rst Modified: python/branches/release26-maint/Doc/library/2to3.rst ============================================================================== --- python/branches/release26-maint/Doc/library/2to3.rst (original) +++ python/branches/release26-maint/Doc/library/2to3.rst Fri May 21 22:42:22 2010 @@ -114,7 +114,7 @@ .. 2to3fixer:: callable - Converts ``callable(x)`` to ``hasattr(x, "__call_")``. + Converts ``callable(x)`` to ``hasattr(x, "__call__")``. .. 2to3fixer:: dict From python-checkins at python.org Fri May 21 22:45:13 2010 From: python-checkins at python.org (georg.brandl) Date: Fri, 21 May 2010 22:45:13 +0200 (CEST) Subject: [Python-checkins] r81410 - python/branches/py3k/Doc/tutorial/datastructures.rst Message-ID: <20100521204513.033A6EE989@mail.python.org> Author: georg.brandl Date: Fri May 21 22:45:12 2010 New Revision: 81410 Log: Remove redundant example. Modified: python/branches/py3k/Doc/tutorial/datastructures.rst Modified: python/branches/py3k/Doc/tutorial/datastructures.rst ============================================================================== --- python/branches/py3k/Doc/tutorial/datastructures.rst (original) +++ python/branches/py3k/Doc/tutorial/datastructures.rst Fri May 21 22:45:12 2010 @@ -377,10 +377,7 @@ Here is a brief demonstration:: - >>> basket = {'apple', 'orange', 'apple', 'pear', 'orange', 'banana'} - >>> print(basket) - {'orange', 'banana', 'pear', 'apple'} - >>> fruit = ['apple', 'orange', 'apple', 'pear', 'orange', 'banana'] + >>> basket = ['apple', 'orange', 'apple', 'pear', 'orange', 'banana'] >>> fruit = set(basket) # create a set without duplicates >>> fruit {'orange', 'pear', 'apple', 'banana'} From python-checkins at python.org Fri May 21 22:46:53 2010 From: python-checkins at python.org (benjamin.peterson) Date: Fri, 21 May 2010 22:46:53 +0200 (CEST) Subject: [Python-checkins] r81411 - python/branches/release26-maint/Doc/library/2to3.rst Message-ID: <20100521204653.BE3DEEE989@mail.python.org> Author: benjamin.peterson Date: Fri May 21 22:46:53 2010 New Revision: 81411 Log: update 2to3 docs Modified: python/branches/release26-maint/Doc/library/2to3.rst Modified: python/branches/release26-maint/Doc/library/2to3.rst ============================================================================== --- python/branches/release26-maint/Doc/library/2to3.rst (original) +++ python/branches/release26-maint/Doc/library/2to3.rst Fri May 21 22:46:53 2010 @@ -86,13 +86,21 @@ The :option:`-v` option enables output of more information on the translation process. +Since some print statements can be parsed as function calls or statements, 2to3 +cannot always read files containing the print function. When 2to3 detects the +presence of the ``from __future__ import print_function`` compiler directive, it +modifies its internal grammar to interpert :func:`print` as a function. This +change can also be enabled manually with the :option:`-p` flag. Use +:option:`-p` to run fixers on code that already has had its print statements +converted. + .. _2to3-fixers: Fixers ------ -Each step of tranforming code is encapsulated in a fixer. The command ``2to3 +Each step of transforming code is encapsulated in a fixer. The command ``2to3 -l`` lists them. As :ref:`documented above <2to3-using>`, each can be turned on and off individually. They are described here in more detail. @@ -114,7 +122,8 @@ .. 2to3fixer:: callable - Converts ``callable(x)`` to ``hasattr(x, "__call__")``. + Converts ``callable(x)`` to ``isinstance(x, collections.Callable)``, adding + an import to :mod:`collections` if needed. .. 2to3fixer:: dict @@ -167,11 +176,11 @@ .. 2to3fixer:: idioms - This optional fixer preforms several transformations that make Python code - more idiomatic. Type comparisions like ``type(x) is SomeClass`` and + This optional fixer performs several transformations that make Python code + more idiomatic. Type comparisons like ``type(x) is SomeClass`` and ``type(x) == SomeClass`` are converted to ``isinstance(x, SomeClass)``. ``while 1`` becomes ``while True``. This fixer also tries to make use of - :func:`sorted` in appropiate places. For example, this block :: + :func:`sorted` in appropriate places. For example, this block :: L = list(some_iterable) L.sort() From python-checkins at python.org Fri May 21 22:47:30 2010 From: python-checkins at python.org (georg.brandl) Date: Fri, 21 May 2010 22:47:30 +0200 (CEST) Subject: [Python-checkins] r81412 - in python/branches/release31-maint: Doc/tutorial/datastructures.rst Message-ID: <20100521204730.E5A50EE989@mail.python.org> Author: georg.brandl Date: Fri May 21 22:47:30 2010 New Revision: 81412 Log: Recorded merge of revisions 81410 via svnmerge from svn+ssh://svn.python.org/python/branches/py3k ........ r81410 | georg.brandl | 2010-05-21 22:45:12 +0200 (Fr, 21 Mai 2010) | 1 line Remove redundant example. ........ Modified: python/branches/release31-maint/ (props changed) python/branches/release31-maint/Doc/tutorial/datastructures.rst Modified: python/branches/release31-maint/Doc/tutorial/datastructures.rst ============================================================================== --- python/branches/release31-maint/Doc/tutorial/datastructures.rst (original) +++ python/branches/release31-maint/Doc/tutorial/datastructures.rst Fri May 21 22:47:30 2010 @@ -377,10 +377,7 @@ Here is a brief demonstration:: - >>> basket = {'apple', 'orange', 'apple', 'pear', 'orange', 'banana'} - >>> print(basket) - {'orange', 'banana', 'pear', 'apple'} - >>> fruit = ['apple', 'orange', 'apple', 'pear', 'orange', 'banana'] + >>> basket = ['apple', 'orange', 'apple', 'pear', 'orange', 'banana'] >>> fruit = set(basket) # create a set without duplicates >>> fruit {'orange', 'pear', 'apple', 'banana'} From python-checkins at python.org Fri May 21 22:48:49 2010 From: python-checkins at python.org (georg.brandl) Date: Fri, 21 May 2010 22:48:49 +0200 (CEST) Subject: [Python-checkins] r81413 - python/branches/release26-maint/Doc/library/threading.rst Message-ID: <20100521204849.1A701EE989@mail.python.org> Author: georg.brandl Date: Fri May 21 22:48:48 2010 New Revision: 81413 Log: Do not mention 2.7+ behavior in the 2.6 docs. Modified: python/branches/release26-maint/Doc/library/threading.rst Modified: python/branches/release26-maint/Doc/library/threading.rst ============================================================================== --- python/branches/release26-maint/Doc/library/threading.rst (original) +++ python/branches/release26-maint/Doc/library/threading.rst Fri May 21 22:48:48 2010 @@ -693,11 +693,7 @@ floating point number specifying a timeout for the operation in seconds (or fractions thereof). - This method returns the internal flag on exit, so it will always return - ``True`` except if a timeout is given and the operation times out. - - .. versionchanged:: 2.7 - Previously, the method always returned ``None``. + This method always returns ``None``. .. _timer-objects: From python-checkins at python.org Fri May 21 22:51:45 2010 From: python-checkins at python.org (benjamin.peterson) Date: Fri, 21 May 2010 22:51:45 +0200 (CEST) Subject: [Python-checkins] r81414 - in python/trunk: Lib/_abcoll.py Lib/test/test_collections.py Misc/NEWS Message-ID: <20100521205145.91E63EE989@mail.python.org> Author: benjamin.peterson Date: Fri May 21 22:51:45 2010 New Revision: 81414 Log: return NotImplemented from Mapping when comparing to a non-mapping #8729 Modified: python/trunk/Lib/_abcoll.py python/trunk/Lib/test/test_collections.py python/trunk/Misc/NEWS Modified: python/trunk/Lib/_abcoll.py ============================================================================== --- python/trunk/Lib/_abcoll.py (original) +++ python/trunk/Lib/_abcoll.py Fri May 21 22:51:45 2010 @@ -369,8 +369,9 @@ __hash__ = None def __eq__(self, other): - return isinstance(other, Mapping) and \ - dict(self.items()) == dict(other.items()) + if not isinstance(other, Mapping): + return NotImplemented + return dict(self.items()) == dict(other.items()) def __ne__(self, other): return not (self == other) Modified: python/trunk/Lib/test/test_collections.py ============================================================================== --- python/trunk/Lib/test/test_collections.py (original) +++ python/trunk/Lib/test/test_collections.py Fri May 21 22:51:45 2010 @@ -1,5 +1,5 @@ -import unittest, doctest +import unittest, doctest, operator import inspect from test import test_support from collections import namedtuple, Counter, OrderedDict @@ -253,6 +253,37 @@ self.assertNotIsInstance(C(), abc) self.assertFalse(issubclass(C, abc)) + def validate_comparison(self, instance): + ops = ['lt', 'gt', 'le', 'ge', 'ne', 'or', 'and', 'xor', 'sub'] + operators = {} + for op in ops: + name = '__' + op + '__' + operators[name] = getattr(operator, name) + + class Other: + def __init__(self): + self.right_side = False + def __eq__(self, other): + self.right_side = True + return True + __lt__ = __eq__ + __gt__ = __eq__ + __le__ = __eq__ + __ge__ = __eq__ + __ne__ = __eq__ + __ror__ = __eq__ + __rand__ = __eq__ + __rxor__ = __eq__ + __rsub__ = __eq__ + + for name, op in operators.items(): + if not hasattr(instance, name): + continue + other = Other() + op(instance, other) + self.assertTrue(other.right_side,'Right side not called for %s.%s' + % (type(instance), name)) + class TestOneTrickPonyABCs(ABCTestCase): def test_Hashable(self): @@ -430,6 +461,14 @@ self.assertIsInstance(sample(), Set) self.assertTrue(issubclass(sample, Set)) self.validate_abstract_methods(Set, '__contains__', '__iter__', '__len__') + class MySet(Set): + def __contains__(self, x): + return False + def __len__(self): + return 0 + def __iter__(self): + return iter([]) + self.validate_comparison(MySet()) def test_hash_Set(self): class OneTwoThreeSet(Set): @@ -493,6 +532,14 @@ self.assertTrue(issubclass(sample, Mapping)) self.validate_abstract_methods(Mapping, '__contains__', '__iter__', '__len__', '__getitem__') + class MyMapping(collections.Mapping): + def __len__(self): + return 0 + def __getitem__(self, i): + raise IndexError + def __iter__(self): + return iter(()) + self.validate_comparison(MyMapping()) def test_MutableMapping(self): for sample in [dict]: Modified: python/trunk/Misc/NEWS ============================================================================== --- python/trunk/Misc/NEWS (original) +++ python/trunk/Misc/NEWS Fri May 21 22:51:45 2010 @@ -29,6 +29,9 @@ Library ------- +- Issue #8729: Return NotImplemented from collections.Mapping.__eq__ when + comparing to a non-mapping. + - Issue #8759: Fixed user paths in sysconfig for posix and os2 schemes. - Issue #1285086: Speed up urllib.quote and urllib.unquote for simple cases. From python-checkins at python.org Fri May 21 22:52:46 2010 From: python-checkins at python.org (georg.brandl) Date: Fri, 21 May 2010 22:52:46 +0200 (CEST) Subject: [Python-checkins] r81415 - python/trunk/Doc/library/urllib2.rst Message-ID: <20100521205246.9031CEE9A2@mail.python.org> Author: georg.brandl Date: Fri May 21 22:52:46 2010 New Revision: 81415 Log: typo Modified: python/trunk/Doc/library/urllib2.rst Modified: python/trunk/Doc/library/urllib2.rst ============================================================================== --- python/trunk/Doc/library/urllib2.rst (original) +++ python/trunk/Doc/library/urllib2.rst Fri May 21 22:52:46 2010 @@ -427,7 +427,7 @@ method on the currently installed global :class:`OpenerDirector`). The optional *timeout* parameter specifies a timeout in seconds for blocking operations like the connection attempt (if not specified, the global default - timeout setting will be usedi). The timeout feature actually works only for + timeout setting will be used). The timeout feature actually works only for HTTP, HTTPS, FTP and FTPS connections). .. versionchanged:: 2.6 From python-checkins at python.org Fri May 21 22:54:17 2010 From: python-checkins at python.org (georg.brandl) Date: Fri, 21 May 2010 22:54:17 +0200 (CEST) Subject: [Python-checkins] r81416 - in python/branches/release26-maint: Doc/library/urllib2.rst Message-ID: <20100521205417.785F5EE983@mail.python.org> Author: georg.brandl Date: Fri May 21 22:54:17 2010 New Revision: 81416 Log: Merged revisions 81415 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r81415 | georg.brandl | 2010-05-21 22:52:46 +0200 (Fr, 21 Mai 2010) | 1 line typo ........ Modified: python/branches/release26-maint/ (props changed) python/branches/release26-maint/Doc/library/urllib2.rst Modified: python/branches/release26-maint/Doc/library/urllib2.rst ============================================================================== --- python/branches/release26-maint/Doc/library/urllib2.rst (original) +++ python/branches/release26-maint/Doc/library/urllib2.rst Fri May 21 22:54:17 2010 @@ -427,7 +427,7 @@ method on the currently installed global :class:`OpenerDirector`). The optional *timeout* parameter specifies a timeout in seconds for blocking operations like the connection attempt (if not specified, the global default - timeout setting will be usedi). The timeout feature actually works only for + timeout setting will be used). The timeout feature actually works only for HTTP, HTTPS, FTP and FTPS connections). .. versionchanged:: 2.6 From python-checkins at python.org Fri May 21 22:55:22 2010 From: python-checkins at python.org (benjamin.peterson) Date: Fri, 21 May 2010 22:55:22 +0200 (CEST) Subject: [Python-checkins] r81417 - in python/branches/py3k: Lib/_abcoll.py Lib/test/test_collections.py Misc/NEWS Message-ID: <20100521205522.507D4EE983@mail.python.org> Author: benjamin.peterson Date: Fri May 21 22:55:22 2010 New Revision: 81417 Log: Merged revisions 81414 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r81414 | benjamin.peterson | 2010-05-21 15:51:45 -0500 (Fri, 21 May 2010) | 1 line return NotImplemented from Mapping when comparing to a non-mapping #8729 ........ Modified: python/branches/py3k/ (props changed) python/branches/py3k/Lib/_abcoll.py python/branches/py3k/Lib/test/test_collections.py python/branches/py3k/Misc/NEWS Modified: python/branches/py3k/Lib/_abcoll.py ============================================================================== --- python/branches/py3k/Lib/_abcoll.py (original) +++ python/branches/py3k/Lib/_abcoll.py Fri May 21 22:55:22 2010 @@ -376,8 +376,9 @@ return ValuesView(self) def __eq__(self, other): - return isinstance(other, Mapping) and \ - dict(self.items()) == dict(other.items()) + if not isinstance(other, Mapping): + return NotImplemented + return dict(self.items()) == dict(other.items()) def __ne__(self, other): return not (self == other) Modified: python/branches/py3k/Lib/test/test_collections.py ============================================================================== --- python/branches/py3k/Lib/test/test_collections.py (original) +++ python/branches/py3k/Lib/test/test_collections.py Fri May 21 22:55:22 2010 @@ -1,6 +1,6 @@ """Unit tests for collections.py.""" -import unittest, doctest +import unittest, doctest, operator import inspect from test import support from collections import namedtuple, Counter, OrderedDict @@ -246,6 +246,37 @@ self.assertNotIsInstance(C(), abc) self.assertFalse(issubclass(C, abc)) + def validate_comparison(self, instance): + ops = ['lt', 'gt', 'le', 'ge', 'ne', 'or', 'and', 'xor', 'sub'] + operators = {} + for op in ops: + name = '__' + op + '__' + operators[name] = getattr(operator, name) + + class Other: + def __init__(self): + self.right_side = False + def __eq__(self, other): + self.right_side = True + return True + __lt__ = __eq__ + __gt__ = __eq__ + __le__ = __eq__ + __ge__ = __eq__ + __ne__ = __eq__ + __ror__ = __eq__ + __rand__ = __eq__ + __rxor__ = __eq__ + __rsub__ = __eq__ + + for name, op in operators.items(): + if not hasattr(instance, name): + continue + other = Other() + op(instance, other) + self.assertTrue(other.right_side,'Right side not called for %s.%s' + % (type(instance), name)) + class TestOneTrickPonyABCs(ABCTestCase): def test_Hashable(self): @@ -420,6 +451,14 @@ self.assertIsInstance(sample(), Set) self.assertTrue(issubclass(sample, Set)) self.validate_abstract_methods(Set, '__contains__', '__iter__', '__len__') + class MySet(Set): + def __contains__(self, x): + return False + def __len__(self): + return 0 + def __iter__(self): + return iter([]) + self.validate_comparison(MySet()) def test_hash_Set(self): class OneTwoThreeSet(Set): @@ -483,6 +522,14 @@ self.assertTrue(issubclass(sample, Mapping)) self.validate_abstract_methods(Mapping, '__contains__', '__iter__', '__len__', '__getitem__') + class MyMapping(collections.Mapping): + def __len__(self): + return 0 + def __getitem__(self, i): + raise IndexError + def __iter__(self): + return iter(()) + self.validate_comparison(MyMapping()) def test_MutableMapping(self): for sample in [dict]: Modified: python/branches/py3k/Misc/NEWS ============================================================================== --- python/branches/py3k/Misc/NEWS (original) +++ python/branches/py3k/Misc/NEWS Fri May 21 22:55:22 2010 @@ -393,6 +393,9 @@ Library ------- +- Issue #8729: Return NotImplemented from collections.Mapping.__eq__ when + comparing to a non-mapping. + - Issue #8774: tabnanny uses the encoding cookie (#coding:...) to use the correct encoding From python-checkins at python.org Fri May 21 22:57:33 2010 From: python-checkins at python.org (georg.brandl) Date: Fri, 21 May 2010 22:57:33 +0200 (CEST) Subject: [Python-checkins] r81418 - in python/branches/py3k: Doc/library/urllib.request.rst Message-ID: <20100521205733.571E5EE983@mail.python.org> Author: georg.brandl Date: Fri May 21 22:57:33 2010 New Revision: 81418 Log: Recorded merge of revisions 81415 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r81415 | georg.brandl | 2010-05-21 22:52:46 +0200 (Fr, 21 Mai 2010) | 1 line typo ........ Modified: python/branches/py3k/ (props changed) python/branches/py3k/Doc/library/urllib.request.rst Modified: python/branches/py3k/Doc/library/urllib.request.rst ============================================================================== --- python/branches/py3k/Doc/library/urllib.request.rst (original) +++ python/branches/py3k/Doc/library/urllib.request.rst Fri May 21 22:57:33 2010 @@ -604,7 +604,7 @@ method on the currently installed global :class:`OpenerDirector`). The optional *timeout* parameter specifies a timeout in seconds for blocking operations like the connection attempt (if not specified, the global default - timeout setting will be usedi). The timeout feature actually works only for + timeout setting will be used). The timeout feature actually works only for HTTP, HTTPS, FTP and FTPS connections). From python-checkins at python.org Fri May 21 22:58:12 2010 From: python-checkins at python.org (georg.brandl) Date: Fri, 21 May 2010 22:58:12 +0200 (CEST) Subject: [Python-checkins] r81419 - python/trunk/Doc/library/simplexmlrpcserver.rst Message-ID: <20100521205812.977B9EE983@mail.python.org> Author: georg.brandl Date: Fri May 21 22:58:12 2010 New Revision: 81419 Log: Add missing parameter in SimpleXMLRPCServer signature. Modified: python/trunk/Doc/library/simplexmlrpcserver.rst Modified: python/trunk/Doc/library/simplexmlrpcserver.rst ============================================================================== --- python/trunk/Doc/library/simplexmlrpcserver.rst (original) +++ python/trunk/Doc/library/simplexmlrpcserver.rst Fri May 21 22:58:12 2010 @@ -20,7 +20,7 @@ :class:`CGIXMLRPCRequestHandler`. -.. class:: SimpleXMLRPCServer(addr[, requestHandler[, logRequests[, allow_none[, encoding]]]]) +.. class:: SimpleXMLRPCServer(addr[, requestHandler[, logRequests[, allow_none[, encoding[, bind_and_activate]]]]) Create a new server instance. This class provides methods for registration of functions that can be called by the XML-RPC protocol. The *requestHandler* From python-checkins at python.org Fri May 21 22:59:29 2010 From: python-checkins at python.org (georg.brandl) Date: Fri, 21 May 2010 22:59:29 +0200 (CEST) Subject: [Python-checkins] r81420 - in python/branches/release26-maint: Doc/library/simplexmlrpcserver.rst Message-ID: <20100521205929.02318EE98A@mail.python.org> Author: georg.brandl Date: Fri May 21 22:59:28 2010 New Revision: 81420 Log: Merged revisions 81419 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r81419 | georg.brandl | 2010-05-21 22:58:12 +0200 (Fr, 21 Mai 2010) | 1 line Add missing parameter in SimpleXMLRPCServer signature. ........ Modified: python/branches/release26-maint/ (props changed) python/branches/release26-maint/Doc/library/simplexmlrpcserver.rst Modified: python/branches/release26-maint/Doc/library/simplexmlrpcserver.rst ============================================================================== --- python/branches/release26-maint/Doc/library/simplexmlrpcserver.rst (original) +++ python/branches/release26-maint/Doc/library/simplexmlrpcserver.rst Fri May 21 22:59:28 2010 @@ -20,7 +20,7 @@ :class:`CGIXMLRPCRequestHandler`. -.. class:: SimpleXMLRPCServer(addr[, requestHandler[, logRequests[, allow_none[, encoding]]]]) +.. class:: SimpleXMLRPCServer(addr[, requestHandler[, logRequests[, allow_none[, encoding[, bind_and_activate]]]]) Create a new server instance. This class provides methods for registration of functions that can be called by the XML-RPC protocol. The *requestHandler* From python-checkins at python.org Fri May 21 23:01:32 2010 From: python-checkins at python.org (georg.brandl) Date: Fri, 21 May 2010 23:01:32 +0200 (CEST) Subject: [Python-checkins] r81421 - python/branches/py3k/Doc/library/urllib.request.rst Message-ID: <20100521210132.8B2ACEE987@mail.python.org> Author: georg.brandl Date: Fri May 21 23:01:32 2010 New Revision: 81421 Log: Fix variable name in example. Modified: python/branches/py3k/Doc/library/urllib.request.rst Modified: python/branches/py3k/Doc/library/urllib.request.rst ============================================================================== --- python/branches/py3k/Doc/library/urllib.request.rst (original) +++ python/branches/py3k/Doc/library/urllib.request.rst Fri May 21 23:01:32 2010 @@ -1079,7 +1079,7 @@ >>> import urllib.request >>> f = urllib.request.urlopen('http://www.python.org/') - >>> print(fp.read(100).decode('utf-8')) + >>> print(f.read(100).decode('utf-8')) Author: georg.brandl Date: Fri May 21 23:01:43 2010 New Revision: 81422 Log: Merged revisions 81418 via svnmerge from svn+ssh://svn.python.org/python/branches/py3k ................ r81418 | georg.brandl | 2010-05-21 22:57:33 +0200 (Fr, 21 Mai 2010) | 9 lines Recorded merge of revisions 81415 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r81415 | georg.brandl | 2010-05-21 22:52:46 +0200 (Fr, 21 Mai 2010) | 1 line typo ........ ................ Modified: python/branches/release31-maint/ (props changed) python/branches/release31-maint/Doc/library/urllib.request.rst Modified: python/branches/release31-maint/Doc/library/urllib.request.rst ============================================================================== --- python/branches/release31-maint/Doc/library/urllib.request.rst (original) +++ python/branches/release31-maint/Doc/library/urllib.request.rst Fri May 21 23:01:43 2010 @@ -604,7 +604,7 @@ method on the currently installed global :class:`OpenerDirector`). The optional *timeout* parameter specifies a timeout in seconds for blocking operations like the connection attempt (if not specified, the global default - timeout setting will be usedi). The timeout feature actually works only for + timeout setting will be used). The timeout feature actually works only for HTTP, HTTPS, FTP and FTPS connections). From python-checkins at python.org Fri May 21 23:02:56 2010 From: python-checkins at python.org (georg.brandl) Date: Fri, 21 May 2010 23:02:56 +0200 (CEST) Subject: [Python-checkins] r81423 - in python/branches/release31-maint: Doc/library/urllib.request.rst Message-ID: <20100521210256.8815DEE987@mail.python.org> Author: georg.brandl Date: Fri May 21 23:02:56 2010 New Revision: 81423 Log: Merged revisions 81421 via svnmerge from svn+ssh://svn.python.org/python/branches/py3k ........ r81421 | georg.brandl | 2010-05-21 23:01:32 +0200 (Fr, 21 Mai 2010) | 1 line Fix variable name in example. ........ Modified: python/branches/release31-maint/ (props changed) python/branches/release31-maint/Doc/library/urllib.request.rst Modified: python/branches/release31-maint/Doc/library/urllib.request.rst ============================================================================== --- python/branches/release31-maint/Doc/library/urllib.request.rst (original) +++ python/branches/release31-maint/Doc/library/urllib.request.rst Fri May 21 23:02:56 2010 @@ -1079,7 +1079,7 @@ >>> import urllib.request >>> f = urllib.request.urlopen('http://www.python.org/') - >>> print(fp.read(100).decode('utf-8')) + >>> print(f.read(100).decode('utf-8')) Author: georg.brandl Date: Fri May 21 23:03:02 2010 New Revision: 81424 Log: Blocked revisions 81419 via svnmerge ........ r81419 | georg.brandl | 2010-05-21 22:58:12 +0200 (Fr, 21 Mai 2010) | 1 line Add missing parameter in SimpleXMLRPCServer signature. ........ Modified: python/branches/py3k/ (props changed) From python-checkins at python.org Fri May 21 23:03:02 2010 From: python-checkins at python.org (benjamin.peterson) Date: Fri, 21 May 2010 23:03:02 +0200 (CEST) Subject: [Python-checkins] r81425 - in python/branches/release26-maint: Lib/_abcoll.py Lib/test/test_collections.py Misc/NEWS Message-ID: <20100521210302.E5D4BEE99B@mail.python.org> Author: benjamin.peterson Date: Fri May 21 23:03:02 2010 New Revision: 81425 Log: Merged revisions 81414 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r81414 | benjamin.peterson | 2010-05-21 15:51:45 -0500 (Fri, 21 May 2010) | 1 line return NotImplemented from Mapping when comparing to a non-mapping #8729 ........ Modified: python/branches/release26-maint/ (props changed) python/branches/release26-maint/Lib/_abcoll.py python/branches/release26-maint/Lib/test/test_collections.py python/branches/release26-maint/Misc/NEWS Modified: python/branches/release26-maint/Lib/_abcoll.py ============================================================================== --- python/branches/release26-maint/Lib/_abcoll.py (original) +++ python/branches/release26-maint/Lib/_abcoll.py Fri May 21 23:03:02 2010 @@ -369,8 +369,9 @@ __hash__ = None def __eq__(self, other): - return isinstance(other, Mapping) and \ - dict(self.items()) == dict(other.items()) + if not isinstance(other, Mapping): + return NotImplemented + return dict(self.items()) == dict(other.items()) def __ne__(self, other): return not (self == other) Modified: python/branches/release26-maint/Lib/test/test_collections.py ============================================================================== --- python/branches/release26-maint/Lib/test/test_collections.py (original) +++ python/branches/release26-maint/Lib/test/test_collections.py Fri May 21 23:03:02 2010 @@ -1,4 +1,4 @@ -import unittest, doctest +import unittest, doctest, operator from test import test_support from collections import namedtuple import pickle, cPickle, copy @@ -232,6 +232,37 @@ self.assertFalse(isinstance(C(), abc)) self.assertFalse(issubclass(C, abc)) + def validate_comparison(self, instance): + ops = ['lt', 'gt', 'le', 'ge', 'ne', 'or', 'and', 'xor', 'sub'] + operators = {} + for op in ops: + name = '__' + op + '__' + operators[name] = getattr(operator, name) + + class Other: + def __init__(self): + self.right_side = False + def __eq__(self, other): + self.right_side = True + return True + __lt__ = __eq__ + __gt__ = __eq__ + __le__ = __eq__ + __ge__ = __eq__ + __ne__ = __eq__ + __ror__ = __eq__ + __rand__ = __eq__ + __rxor__ = __eq__ + __rsub__ = __eq__ + + for name, op in operators.items(): + if not hasattr(instance, name): + continue + other = Other() + op(instance, other) + self.assertTrue(other.right_side,'Right side not called for %s.%s' + % (type(instance), name)) + class TestOneTrickPonyABCs(ABCTestCase): def test_Hashable(self): @@ -409,6 +440,14 @@ self.failUnless(isinstance(sample(), Set)) self.failUnless(issubclass(sample, Set)) self.validate_abstract_methods(Set, '__contains__', '__iter__', '__len__') + class MySet(Set): + def __contains__(self, x): + return False + def __len__(self): + return 0 + def __iter__(self): + return iter([]) + self.validate_comparison(MySet()) def test_hash_Set(self): class OneTwoThreeSet(Set): @@ -472,6 +511,14 @@ self.failUnless(issubclass(sample, Mapping)) self.validate_abstract_methods(Mapping, '__contains__', '__iter__', '__len__', '__getitem__') + class MyMapping(collections.Mapping): + def __len__(self): + return 0 + def __getitem__(self, i): + raise IndexError + def __iter__(self): + return iter(()) + self.validate_comparison(MyMapping()) def test_MutableMapping(self): for sample in [dict]: Modified: python/branches/release26-maint/Misc/NEWS ============================================================================== --- python/branches/release26-maint/Misc/NEWS (original) +++ python/branches/release26-maint/Misc/NEWS Fri May 21 23:03:02 2010 @@ -55,6 +55,9 @@ Library ------- +- Issue #8729: Return NotImplemented from collections.Mapping.__eq__ when + comparing to a non-mapping. + - Issue #5918: Fix a crash in the parser module. - Issue #8688: Distutils now recalculates MANIFEST everytime. From python-checkins at python.org Fri May 21 23:05:45 2010 From: python-checkins at python.org (benjamin.peterson) Date: Fri, 21 May 2010 23:05:45 +0200 (CEST) Subject: [Python-checkins] r81426 - in python/branches/release31-maint: Lib/_abcoll.py Lib/test/test_collections.py Misc/NEWS Message-ID: <20100521210545.7D844EE99B@mail.python.org> Author: benjamin.peterson Date: Fri May 21 23:05:45 2010 New Revision: 81426 Log: Merged revisions 81417 via svnmerge from svn+ssh://pythondev at svn.python.org/python/branches/py3k ................ r81417 | benjamin.peterson | 2010-05-21 15:55:22 -0500 (Fri, 21 May 2010) | 9 lines Merged revisions 81414 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r81414 | benjamin.peterson | 2010-05-21 15:51:45 -0500 (Fri, 21 May 2010) | 1 line return NotImplemented from Mapping when comparing to a non-mapping #8729 ........ ................ Modified: python/branches/release31-maint/ (props changed) python/branches/release31-maint/Lib/_abcoll.py python/branches/release31-maint/Lib/test/test_collections.py python/branches/release31-maint/Misc/NEWS Modified: python/branches/release31-maint/Lib/_abcoll.py ============================================================================== --- python/branches/release31-maint/Lib/_abcoll.py (original) +++ python/branches/release31-maint/Lib/_abcoll.py Fri May 21 23:05:45 2010 @@ -376,8 +376,9 @@ return ValuesView(self) def __eq__(self, other): - return isinstance(other, Mapping) and \ - dict(self.items()) == dict(other.items()) + if not isinstance(other, Mapping): + return NotImplemented + return dict(self.items()) == dict(other.items()) def __ne__(self, other): return not (self == other) Modified: python/branches/release31-maint/Lib/test/test_collections.py ============================================================================== --- python/branches/release31-maint/Lib/test/test_collections.py (original) +++ python/branches/release31-maint/Lib/test/test_collections.py Fri May 21 23:05:45 2010 @@ -1,6 +1,6 @@ """Unit tests for collections.py.""" -import unittest, doctest +import unittest, doctest, operator import inspect from test import support from collections import namedtuple, Counter, OrderedDict @@ -230,6 +230,37 @@ self.assertRaises(TypeError, C, name) + def validate_comparison(self, instance): + ops = ['lt', 'gt', 'le', 'ge', 'ne', 'or', 'and', 'xor', 'sub'] + operators = {} + for op in ops: + name = '__' + op + '__' + operators[name] = getattr(operator, name) + + class Other: + def __init__(self): + self.right_side = False + def __eq__(self, other): + self.right_side = True + return True + __lt__ = __eq__ + __gt__ = __eq__ + __le__ = __eq__ + __ge__ = __eq__ + __ne__ = __eq__ + __ror__ = __eq__ + __rand__ = __eq__ + __rxor__ = __eq__ + __rsub__ = __eq__ + + for name, op in operators.items(): + if not hasattr(instance, name): + continue + other = Other() + op(instance, other) + self.assertTrue(other.right_side,'Right side not called for %s.%s' + % (type(instance), name)) + class TestOneTrickPonyABCs(ABCTestCase): def test_Hashable(self): @@ -398,6 +429,14 @@ self.assertTrue(isinstance(sample(), Set)) self.assertTrue(issubclass(sample, Set)) self.validate_abstract_methods(Set, '__contains__', '__iter__', '__len__') + class MySet(Set): + def __contains__(self, x): + return False + def __len__(self): + return 0 + def __iter__(self): + return iter([]) + self.validate_comparison(MySet()) def test_hash_Set(self): class OneTwoThreeSet(Set): @@ -461,6 +500,14 @@ self.assertTrue(issubclass(sample, Mapping)) self.validate_abstract_methods(Mapping, '__contains__', '__iter__', '__len__', '__getitem__') + class MyMapping(collections.Mapping): + def __len__(self): + return 0 + def __getitem__(self, i): + raise IndexError + def __iter__(self): + return iter(()) + self.validate_comparison(MyMapping()) def test_MutableMapping(self): for sample in [dict]: Modified: python/branches/release31-maint/Misc/NEWS ============================================================================== --- python/branches/release31-maint/Misc/NEWS (original) +++ python/branches/release31-maint/Misc/NEWS Fri May 21 23:05:45 2010 @@ -54,6 +54,9 @@ Library ------- +- Issue #8729: Return NotImplemented from collections.Mapping.__eq__ when + comparing to a non-mapping. + - Issue #8774: tabnanny uses the encoding cookie (#coding:...) to use the correct encoding From python-checkins at python.org Fri May 21 23:12:07 2010 From: python-checkins at python.org (georg.brandl) Date: Fri, 21 May 2010 23:12:07 +0200 (CEST) Subject: [Python-checkins] r81427 - python/branches/py3k/Doc/library/tempfile.rst Message-ID: <20100521211207.37651EE9A2@mail.python.org> Author: georg.brandl Date: Fri May 21 23:12:07 2010 New Revision: 81427 Log: Fix signatures for the various TemporaryFile class^Wfunctions. Modified: python/branches/py3k/Doc/library/tempfile.rst Modified: python/branches/py3k/Doc/library/tempfile.rst ============================================================================== --- python/branches/py3k/Doc/library/tempfile.rst (original) +++ python/branches/py3k/Doc/library/tempfile.rst Fri May 21 23:12:07 2010 @@ -27,8 +27,7 @@ The module defines the following user-callable functions: - -.. function:: TemporaryFile(mode='w+b', bufsize=-1, suffix='', prefix='tmp', dir=None) +.. function:: TemporaryFile(mode='w+b', buffering=None, encoding=None, newline=None, suffix='', prefix='tmp', dir=None) Return a file-like object that can be used as a temporary storage area. The file is created using :func:`mkstemp`. It will be destroyed as soon @@ -41,8 +40,8 @@ The *mode* parameter defaults to ``'w+b'`` so that the file created can be read and written without being closed. Binary mode is used so that it behaves consistently on all platforms without regard for the data that is - stored. *bufsize* defaults to ``-1``, meaning that the operating system - default is used. + stored. *buffering*, *encoding* and *newline* are interpreted as for + :func:`open`. The *dir*, *prefix* and *suffix* parameters are passed to :func:`mkstemp`. @@ -52,7 +51,7 @@ :keyword:`with` statement, just like a normal file. -.. function:: NamedTemporaryFile(mode='w+b', bufsize=-1, suffix='', prefix='tmp', dir=None, delete=True) +.. function:: NamedTemporaryFile(mode='w+b', buffering=None, encoding=None, newline=None, suffix='', prefix='tmp', dir=None, delete=True) This function operates exactly as :func:`TemporaryFile` does, except that the file is guaranteed to have a visible name in the file system (on @@ -67,7 +66,7 @@ be used in a :keyword:`with` statement, just like a normal file. -.. function:: SpooledTemporaryFile(max_size=0, mode='w+b', bufsize=-1, suffix='', prefix='tmp', dir=None) +.. function:: SpooledTemporaryFile(max_size=0, mode='w+b', buffering=None, encoding=None, newline=None, suffix='', prefix='tmp', dir=None) This function operates exactly as :func:`TemporaryFile` does, except that data is spooled in memory until the file size exceeds *max_size*, or From python-checkins at python.org Fri May 21 23:16:12 2010 From: python-checkins at python.org (benjamin.peterson) Date: Fri, 21 May 2010 23:16:12 +0200 (CEST) Subject: [Python-checkins] r81428 - python/trunk/Lib/test/test_linecache.py Message-ID: <20100521211612.E30C7ECBC@mail.python.org> Author: benjamin.peterson Date: Fri May 21 23:16:12 2010 New Revision: 81428 Log: use addCleanup Modified: python/trunk/Lib/test/test_linecache.py Modified: python/trunk/Lib/test/test_linecache.py ============================================================================== --- python/trunk/Lib/test/test_linecache.py (original) +++ python/trunk/Lib/test/test_linecache.py Fri May 21 23:16:12 2010 @@ -81,39 +81,36 @@ def test_checkcache(self): getline = linecache.getline - try: - # Create a source file and cache its contents - source_name = support.TESTFN + '.py' - with open(source_name, 'w') as source: - source.write(SOURCE_1) - getline(source_name, 1) - - # Keep a copy of the old contents - source_list = [] - with open(source_name) as source: - for index, line in enumerate(source): - self.assertEquals(line, getline(source_name, index + 1)) - source_list.append(line) + # Create a source file and cache its contents + source_name = support.TESTFN + '.py' + self.addCleanup(test_support.unlink, source_name) + with open(source_name, 'w') as source: + source.write(SOURCE_1) + getline(source_name, 1) + + # Keep a copy of the old contents + source_list = [] + with open(source_name) as source: + for index, line in enumerate(source): + self.assertEquals(line, getline(source_name, index + 1)) + source_list.append(line) - with open(source_name, 'w') as source: - source.write(SOURCE_2) + with open(source_name, 'w') as source: + source.write(SOURCE_2) - # Try to update a bogus cache entry - linecache.checkcache('dummy') + # Try to update a bogus cache entry + linecache.checkcache('dummy') - # Check that the cache matches the old contents - for index, line in enumerate(source_list): + # Check that the cache matches the old contents + for index, line in enumerate(source_list): + self.assertEquals(line, getline(source_name, index + 1)) + + # Update the cache and check whether it matches the new source file + linecache.checkcache(source_name) + with open(source_name) as source: + for index, line in enumerate(source): self.assertEquals(line, getline(source_name, index + 1)) - - # Update the cache and check whether it matches the new source file - linecache.checkcache(source_name) - with open(source_name) as source: - for index, line in enumerate(source): - self.assertEquals(line, getline(source_name, index + 1)) - source_list.append(line) - - finally: - support.unlink(source_name) + source_list.append(line) def test_main(): support.run_unittest(LineCacheTests) From python-checkins at python.org Fri May 21 23:17:22 2010 From: python-checkins at python.org (benjamin.peterson) Date: Fri, 21 May 2010 23:17:22 +0200 (CEST) Subject: [Python-checkins] r81429 - python/trunk/Lib/test/test_linecache.py Message-ID: <20100521211722.BC78BEE9A8@mail.python.org> Author: benjamin.peterson Date: Fri May 21 23:17:22 2010 New Revision: 81429 Log: fix name Modified: python/trunk/Lib/test/test_linecache.py Modified: python/trunk/Lib/test/test_linecache.py ============================================================================== --- python/trunk/Lib/test/test_linecache.py (original) +++ python/trunk/Lib/test/test_linecache.py Fri May 21 23:17:22 2010 @@ -83,7 +83,7 @@ getline = linecache.getline # Create a source file and cache its contents source_name = support.TESTFN + '.py' - self.addCleanup(test_support.unlink, source_name) + self.addCleanup(support.unlink, source_name) with open(source_name, 'w') as source: source.write(SOURCE_1) getline(source_name, 1) From python-checkins at python.org Fri May 21 23:28:17 2010 From: python-checkins at python.org (georg.brandl) Date: Fri, 21 May 2010 23:28:17 +0200 (CEST) Subject: [Python-checkins] r81430 - in python/branches/release31-maint: Doc/library/tempfile.rst Message-ID: <20100521212817.5D346EE9DF@mail.python.org> Author: georg.brandl Date: Fri May 21 23:28:17 2010 New Revision: 81430 Log: Recorded merge of revisions 81427 via svnmerge from svn+ssh://svn.python.org/python/branches/py3k ........ r81427 | georg.brandl | 2010-05-21 23:12:07 +0200 (Fr, 21 Mai 2010) | 1 line Fix signatures for the various TemporaryFile class^Wfunctions. ........ Modified: python/branches/release31-maint/ (props changed) python/branches/release31-maint/Doc/library/tempfile.rst Modified: python/branches/release31-maint/Doc/library/tempfile.rst ============================================================================== --- python/branches/release31-maint/Doc/library/tempfile.rst (original) +++ python/branches/release31-maint/Doc/library/tempfile.rst Fri May 21 23:28:17 2010 @@ -27,8 +27,7 @@ The module defines the following user-callable functions: - -.. function:: TemporaryFile(mode='w+b', bufsize=-1, suffix='', prefix='tmp', dir=None) +.. function:: TemporaryFile(mode='w+b', buffering=None, encoding=None, newline=None, suffix='', prefix='tmp', dir=None) Return a file-like object that can be used as a temporary storage area. The file is created using :func:`mkstemp`. It will be destroyed as soon @@ -41,8 +40,8 @@ The *mode* parameter defaults to ``'w+b'`` so that the file created can be read and written without being closed. Binary mode is used so that it behaves consistently on all platforms without regard for the data that is - stored. *bufsize* defaults to ``-1``, meaning that the operating system - default is used. + stored. *buffering*, *encoding* and *newline* are interpreted as for + :func:`open`. The *dir*, *prefix* and *suffix* parameters are passed to :func:`mkstemp`. @@ -52,7 +51,7 @@ :keyword:`with` statement, just like a normal file. -.. function:: NamedTemporaryFile(mode='w+b', bufsize=-1, suffix='', prefix='tmp', dir=None, delete=True) +.. function:: NamedTemporaryFile(mode='w+b', buffering=None, encoding=None, newline=None, suffix='', prefix='tmp', dir=None, delete=True) This function operates exactly as :func:`TemporaryFile` does, except that the file is guaranteed to have a visible name in the file system (on @@ -67,7 +66,7 @@ be used in a :keyword:`with` statement, just like a normal file. -.. function:: SpooledTemporaryFile(max_size=0, mode='w+b', bufsize=-1, suffix='', prefix='tmp', dir=None) +.. function:: SpooledTemporaryFile(max_size=0, mode='w+b', buffering=None, encoding=None, newline=None, suffix='', prefix='tmp', dir=None) This function operates exactly as :func:`TemporaryFile` does, except that data is spooled in memory until the file size exceeds *max_size*, or From python-checkins at python.org Fri May 21 23:30:47 2010 From: python-checkins at python.org (georg.brandl) Date: Fri, 21 May 2010 23:30:47 +0200 (CEST) Subject: [Python-checkins] r81431 - python/trunk/Doc/library/telnetlib.rst Message-ID: <20100521213047.612B1EE9D9@mail.python.org> Author: georg.brandl Date: Fri May 21 23:30:47 2010 New Revision: 81431 Log: #8707: remove duplicate paragraph part. Modified: python/trunk/Doc/library/telnetlib.rst Modified: python/trunk/Doc/library/telnetlib.rst ============================================================================== --- python/trunk/Doc/library/telnetlib.rst (original) +++ python/trunk/Doc/library/telnetlib.rst Fri May 21 23:30:47 2010 @@ -28,16 +28,11 @@ :class:`Telnet` represents a connection to a Telnet server. The instance is initially not connected by default; the :meth:`open` method must be used to establish a connection. Alternatively, the host name and optional port - and timeout can be passed to the constructor, in which case the connection to - the server will be established before the constructor returns. The optional - *timeout* parameter specifies a timeout in seconds for the connection attempt (if - not specified, the global default timeout setting will be used). - number can be passed to the constructor, to, in which case the connection to - the server will be established before the constructor returns. The optional + the server will be established before the constructor returns. The optional *timeout* parameter specifies a timeout in seconds for blocking operations - like the connection attempt (if not specified, or passed as None, the global - default timeout setting will be used). + like the connection attempt (if not specified, the global default timeout + setting will be used). Do not reopen an already connected instance. From python-checkins at python.org Fri May 21 23:31:24 2010 From: python-checkins at python.org (benjamin.peterson) Date: Fri, 21 May 2010 23:31:24 +0200 (CEST) Subject: [Python-checkins] r81432 - in python/trunk: Lib/linecache.py Lib/test/test_linecache.py Misc/NEWS Message-ID: <20100521213124.D372EEE9C7@mail.python.org> Author: benjamin.peterson Date: Fri May 21 23:31:24 2010 New Revision: 81432 Log: ensure the last line has a trailing newline #8782 Modified: python/trunk/Lib/linecache.py python/trunk/Lib/test/test_linecache.py python/trunk/Misc/NEWS Modified: python/trunk/Lib/linecache.py ============================================================================== --- python/trunk/Lib/linecache.py (original) +++ python/trunk/Lib/linecache.py Fri May 21 23:31:24 2010 @@ -133,6 +133,8 @@ except IOError, msg: ## print '*** Cannot open', fullname, ':', msg return [] + if lines and not lines[-1].endswith('\n'): + lines[-1] += '\n' size, mtime = stat.st_size, stat.st_mtime cache[filename] = size, mtime, lines, fullname return lines Modified: python/trunk/Lib/test/test_linecache.py ============================================================================== --- python/trunk/Lib/test/test_linecache.py (original) +++ python/trunk/Lib/test/test_linecache.py Fri May 21 23:31:24 2010 @@ -31,6 +31,11 @@ ''' +SOURCE_3 = ''' +def f(): + return 3''' # No ending newline + + class LineCacheTests(unittest.TestCase): def test_getline(self): @@ -63,6 +68,13 @@ empty = linecache.getlines('a/b/c/__init__.py') self.assertEquals(empty, []) + def test_no_ending_newline(self): + self.addCleanup(support.unlink, support.TESTFN) + with open(support.TESTFN, "w") as fp: + fp.write(SOURCE_3) + lines = linecache.getlines(support.TESTFN) + self.assertEqual(lines, ["\n", "def f():\n", " return 3\n"]) + def test_clearcache(self): cached = [] for entry in TESTS: Modified: python/trunk/Misc/NEWS ============================================================================== --- python/trunk/Misc/NEWS (original) +++ python/trunk/Misc/NEWS Fri May 21 23:31:24 2010 @@ -29,6 +29,9 @@ Library ------- +- Issue #8782: Add a trailing newline in linecache.updatecache to the last line + of files without one. + - Issue #8729: Return NotImplemented from collections.Mapping.__eq__ when comparing to a non-mapping. From python-checkins at python.org Fri May 21 23:32:50 2010 From: python-checkins at python.org (benjamin.peterson) Date: Fri, 21 May 2010 23:32:50 +0200 (CEST) Subject: [Python-checkins] r81433 - python/trunk/Lib/linecache.py Message-ID: <20100521213250.043BCEE9BD@mail.python.org> Author: benjamin.peterson Date: Fri May 21 23:32:49 2010 New Revision: 81433 Log: remove debugging rubish Modified: python/trunk/Lib/linecache.py Modified: python/trunk/Lib/linecache.py ============================================================================== --- python/trunk/Lib/linecache.py (original) +++ python/trunk/Lib/linecache.py Fri May 21 23:32:49 2010 @@ -123,15 +123,12 @@ except os.error: pass else: - # No luck -## print '*** Cannot stat', filename, ':', msg return [] try: fp = open(fullname, 'rU') lines = fp.readlines() fp.close() except IOError, msg: -## print '*** Cannot open', fullname, ':', msg return [] if lines and not lines[-1].endswith('\n'): lines[-1] += '\n' From python-checkins at python.org Fri May 21 23:33:16 2010 From: python-checkins at python.org (georg.brandl) Date: Fri, 21 May 2010 23:33:16 +0200 (CEST) Subject: [Python-checkins] r81434 - in python/branches/release26-maint: Doc/library/telnetlib.rst Message-ID: <20100521213316.7B6D9EE9EC@mail.python.org> Author: georg.brandl Date: Fri May 21 23:33:16 2010 New Revision: 81434 Log: Merged revisions 81431 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r81431 | georg.brandl | 2010-05-21 23:30:47 +0200 (Fr, 21 Mai 2010) | 1 line #8707: remove duplicate paragraph part. ........ Modified: python/branches/release26-maint/ (props changed) python/branches/release26-maint/Doc/library/telnetlib.rst Modified: python/branches/release26-maint/Doc/library/telnetlib.rst ============================================================================== --- python/branches/release26-maint/Doc/library/telnetlib.rst (original) +++ python/branches/release26-maint/Doc/library/telnetlib.rst Fri May 21 23:33:16 2010 @@ -28,16 +28,11 @@ :class:`Telnet` represents a connection to a Telnet server. The instance is initially not connected by default; the :meth:`open` method must be used to establish a connection. Alternatively, the host name and optional port - and timeout can be passed to the constructor, in which case the connection to - the server will be established before the constructor returns. The optional - *timeout* parameter specifies a timeout in seconds for the connection attempt (if - not specified, the global default timeout setting will be used). - number can be passed to the constructor, to, in which case the connection to - the server will be established before the constructor returns. The optional + the server will be established before the constructor returns. The optional *timeout* parameter specifies a timeout in seconds for blocking operations - like the connection attempt (if not specified, or passed as None, the global - default timeout setting will be used). + like the connection attempt (if not specified, the global default timeout + setting will be used). Do not reopen an already connected instance. From python-checkins at python.org Fri May 21 23:33:23 2010 From: python-checkins at python.org (georg.brandl) Date: Fri, 21 May 2010 23:33:23 +0200 (CEST) Subject: [Python-checkins] r81435 - in python/branches/py3k: Doc/library/telnetlib.rst Message-ID: <20100521213323.D6045EE9E6@mail.python.org> Author: georg.brandl Date: Fri May 21 23:33:23 2010 New Revision: 81435 Log: Merged revisions 81431 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r81431 | georg.brandl | 2010-05-21 23:30:47 +0200 (Fr, 21 Mai 2010) | 1 line #8707: remove duplicate paragraph part. ........ Modified: python/branches/py3k/ (props changed) python/branches/py3k/Doc/library/telnetlib.rst Modified: python/branches/py3k/Doc/library/telnetlib.rst ============================================================================== --- python/branches/py3k/Doc/library/telnetlib.rst (original) +++ python/branches/py3k/Doc/library/telnetlib.rst Fri May 21 23:33:23 2010 @@ -27,16 +27,11 @@ :class:`Telnet` represents a connection to a Telnet server. The instance is initially not connected by default; the :meth:`open` method must be used to establish a connection. Alternatively, the host name and optional port - and timeout can be passed to the constructor, in which case the connection to - the server will be established before the constructor returns. The optional - *timeout* parameter specifies a timeout in seconds for the connection attempt (if - not specified, the global default timeout setting will be used). - number can be passed to the constructor, to, in which case the connection to - the server will be established before the constructor returns. The optional + the server will be established before the constructor returns. The optional *timeout* parameter specifies a timeout in seconds for blocking operations - like the connection attempt (if not specified, or passed as None, the global - default timeout setting will be used). + like the connection attempt (if not specified, the global default timeout + setting will be used). Do not reopen an already connected instance. From python-checkins at python.org Fri May 21 23:33:56 2010 From: python-checkins at python.org (georg.brandl) Date: Fri, 21 May 2010 23:33:56 +0200 (CEST) Subject: [Python-checkins] r81436 - in python/branches/release31-maint: Doc/library/telnetlib.rst Message-ID: <20100521213356.2C8AFEE9C4@mail.python.org> Author: georg.brandl Date: Fri May 21 23:33:56 2010 New Revision: 81436 Log: Merged revisions 81435 via svnmerge from svn+ssh://svn.python.org/python/branches/py3k ................ r81435 | georg.brandl | 2010-05-21 23:33:23 +0200 (Fr, 21 Mai 2010) | 9 lines Merged revisions 81431 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r81431 | georg.brandl | 2010-05-21 23:30:47 +0200 (Fr, 21 Mai 2010) | 1 line #8707: remove duplicate paragraph part. ........ ................ Modified: python/branches/release31-maint/ (props changed) python/branches/release31-maint/Doc/library/telnetlib.rst Modified: python/branches/release31-maint/Doc/library/telnetlib.rst ============================================================================== --- python/branches/release31-maint/Doc/library/telnetlib.rst (original) +++ python/branches/release31-maint/Doc/library/telnetlib.rst Fri May 21 23:33:56 2010 @@ -27,16 +27,11 @@ :class:`Telnet` represents a connection to a Telnet server. The instance is initially not connected by default; the :meth:`open` method must be used to establish a connection. Alternatively, the host name and optional port - and timeout can be passed to the constructor, in which case the connection to - the server will be established before the constructor returns. The optional - *timeout* parameter specifies a timeout in seconds for the connection attempt (if - not specified, the global default timeout setting will be used). - number can be passed to the constructor, to, in which case the connection to - the server will be established before the constructor returns. The optional + the server will be established before the constructor returns. The optional *timeout* parameter specifies a timeout in seconds for blocking operations - like the connection attempt (if not specified, or passed as None, the global - default timeout setting will be used). + like the connection attempt (if not specified, the global default timeout + setting will be used). Do not reopen an already connected instance. From python-checkins at python.org Fri May 21 23:35:44 2010 From: python-checkins at python.org (benjamin.peterson) Date: Fri, 21 May 2010 23:35:44 +0200 (CEST) Subject: [Python-checkins] r81437 - python/trunk/Lib/linecache.py Message-ID: <20100521213544.BCDCAEE9D6@mail.python.org> Author: benjamin.peterson Date: Fri May 21 23:35:44 2010 New Revision: 81437 Log: simplify and modernize updatecache() Modified: python/trunk/Lib/linecache.py Modified: python/trunk/Lib/linecache.py ============================================================================== --- python/trunk/Lib/linecache.py (original) +++ python/trunk/Lib/linecache.py Fri May 21 23:35:44 2010 @@ -72,13 +72,13 @@ if filename in cache: del cache[filename] - if not filename or filename[0] + filename[-1] == '<>': + if not filename or (filename.startswith('<') and filename.endswith('>')): return [] fullname = filename try: stat = os.stat(fullname) - except os.error, msg: + except OSError: basename = filename # Try for a __loader__, if available @@ -115,20 +115,18 @@ fullname = os.path.join(dirname, basename) except (TypeError, AttributeError): # Not sufficiently string-like to do anything useful with. + continue + try: + stat = os.stat(fullname) + break + except os.error: pass - else: - try: - stat = os.stat(fullname) - break - except os.error: - pass else: return [] try: - fp = open(fullname, 'rU') - lines = fp.readlines() - fp.close() - except IOError, msg: + with open(fullname, 'rU') as fp: + lines = fp.readlines() + except IOError: return [] if lines and not lines[-1].endswith('\n'): lines[-1] += '\n' From python-checkins at python.org Fri May 21 23:45:06 2010 From: python-checkins at python.org (benjamin.peterson) Date: Fri, 21 May 2010 23:45:06 +0200 (CEST) Subject: [Python-checkins] r81438 - in python/branches/py3k: Lib/linecache.py Lib/test/test_linecache.py Misc/NEWS Message-ID: <20100521214506.B1C14EE981@mail.python.org> Author: benjamin.peterson Date: Fri May 21 23:45:06 2010 New Revision: 81438 Log: Merged revisions 81428-81429,81432-81433,81437 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r81428 | benjamin.peterson | 2010-05-21 16:16:12 -0500 (Fri, 21 May 2010) | 1 line use addCleanup ........ r81429 | benjamin.peterson | 2010-05-21 16:17:22 -0500 (Fri, 21 May 2010) | 1 line fix name ........ r81432 | benjamin.peterson | 2010-05-21 16:31:24 -0500 (Fri, 21 May 2010) | 1 line ensure the last line has a trailing newline #8782 ........ r81433 | benjamin.peterson | 2010-05-21 16:32:49 -0500 (Fri, 21 May 2010) | 1 line remove debugging rubish ........ r81437 | benjamin.peterson | 2010-05-21 16:35:44 -0500 (Fri, 21 May 2010) | 1 line simplify and modernize updatecache() ........ Modified: python/branches/py3k/ (props changed) python/branches/py3k/Lib/linecache.py python/branches/py3k/Lib/test/test_linecache.py python/branches/py3k/Misc/NEWS Modified: python/branches/py3k/Lib/linecache.py ============================================================================== --- python/branches/py3k/Lib/linecache.py (original) +++ python/branches/py3k/Lib/linecache.py Fri May 21 23:45:06 2010 @@ -73,13 +73,13 @@ if filename in cache: del cache[filename] - if not filename or filename[0] + filename[-1] == '<>': + if not filename or (filename.startswith('<') and filename.endswith('>')): return [] fullname = filename try: stat = os.stat(fullname) - except os.error as msg: + except OSError: basename = filename # Try for a __loader__, if available @@ -114,20 +114,23 @@ fullname = os.path.join(dirname, basename) except (TypeError, AttributeError): # Not sufficiently string-like to do anything useful with. + continue + try: + stat = os.stat(fullname) + break + except os.error: pass - else: - try: - stat = os.stat(fullname) - break - except os.error: - pass else: - # No luck return [] - with open(fullname, 'rb') as fp: - coding, line = tokenize.detect_encoding(fp.readline) - with open(fullname, 'r', encoding=coding) as fp: - lines = fp.readlines() + try: + with open(fullname, 'rb') as fp: + coding, line = tokenize.detect_encoding(fp.readline) + with open(fullname, 'r', encoding=coding) as fp: + lines = fp.readlines() + except IOError: + pass + if lines and not lines[-1].endswith('\n'): + lines[-1] += '\n' size, mtime = stat.st_size, stat.st_mtime cache[filename] = size, mtime, lines, fullname return lines Modified: python/branches/py3k/Lib/test/test_linecache.py ============================================================================== --- python/branches/py3k/Lib/test/test_linecache.py (original) +++ python/branches/py3k/Lib/test/test_linecache.py Fri May 21 23:45:06 2010 @@ -31,6 +31,11 @@ ''' +SOURCE_3 = ''' +def f(): + return 3''' # No ending newline + + class LineCacheTests(unittest.TestCase): def test_getline(self): @@ -63,6 +68,13 @@ empty = linecache.getlines('a/b/c/__init__.py') self.assertEquals(empty, []) + def test_no_ending_newline(self): + self.addCleanup(support.unlink, support.TESTFN) + with open(support.TESTFN, "w") as fp: + fp.write(SOURCE_3) + lines = linecache.getlines(support.TESTFN) + self.assertEqual(lines, ["\n", "def f():\n", " return 3\n"]) + def test_clearcache(self): cached = [] for entry in TESTS: @@ -81,39 +93,36 @@ def test_checkcache(self): getline = linecache.getline - try: - # Create a source file and cache its contents - source_name = support.TESTFN + '.py' - with open(source_name, 'w') as source: - source.write(SOURCE_1) - getline(source_name, 1) - - # Keep a copy of the old contents - source_list = [] - with open(source_name) as source: - for index, line in enumerate(source): - self.assertEquals(line, getline(source_name, index + 1)) - source_list.append(line) + # Create a source file and cache its contents + source_name = support.TESTFN + '.py' + self.addCleanup(support.unlink, source_name) + with open(source_name, 'w') as source: + source.write(SOURCE_1) + getline(source_name, 1) + + # Keep a copy of the old contents + source_list = [] + with open(source_name) as source: + for index, line in enumerate(source): + self.assertEquals(line, getline(source_name, index + 1)) + source_list.append(line) - with open(source_name, 'w') as source: - source.write(SOURCE_2) + with open(source_name, 'w') as source: + source.write(SOURCE_2) - # Try to update a bogus cache entry - linecache.checkcache('dummy') + # Try to update a bogus cache entry + linecache.checkcache('dummy') - # Check that the cache matches the old contents - for index, line in enumerate(source_list): + # Check that the cache matches the old contents + for index, line in enumerate(source_list): + self.assertEquals(line, getline(source_name, index + 1)) + + # Update the cache and check whether it matches the new source file + linecache.checkcache(source_name) + with open(source_name) as source: + for index, line in enumerate(source): self.assertEquals(line, getline(source_name, index + 1)) - - # Update the cache and check whether it matches the new source file - linecache.checkcache(source_name) - with open(source_name) as source: - for index, line in enumerate(source): - self.assertEquals(line, getline(source_name, index + 1)) - source_list.append(line) - - finally: - support.unlink(source_name) + source_list.append(line) def test_main(): support.run_unittest(LineCacheTests) Modified: python/branches/py3k/Misc/NEWS ============================================================================== --- python/branches/py3k/Misc/NEWS (original) +++ python/branches/py3k/Misc/NEWS Fri May 21 23:45:06 2010 @@ -393,6 +393,9 @@ Library ------- +- Issue #8782: Add a trailing newline in linecache.updatecache to the last line + of files without one. + - Issue #8729: Return NotImplemented from collections.Mapping.__eq__ when comparing to a non-mapping. From python-checkins at python.org Fri May 21 23:45:16 2010 From: python-checkins at python.org (benjamin.peterson) Date: Fri, 21 May 2010 23:45:16 +0200 (CEST) Subject: [Python-checkins] r81439 - in python/branches/release26-maint: Lib/linecache.py Lib/test/test_linecache.py Misc/NEWS Message-ID: <20100521214516.45F16EE9BC@mail.python.org> Author: benjamin.peterson Date: Fri May 21 23:45:16 2010 New Revision: 81439 Log: Merged revisions 81432 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r81432 | benjamin.peterson | 2010-05-21 16:31:24 -0500 (Fri, 21 May 2010) | 1 line ensure the last line has a trailing newline #8782 ........ Modified: python/branches/release26-maint/ (props changed) python/branches/release26-maint/Lib/linecache.py python/branches/release26-maint/Lib/test/test_linecache.py python/branches/release26-maint/Misc/NEWS Modified: python/branches/release26-maint/Lib/linecache.py ============================================================================== --- python/branches/release26-maint/Lib/linecache.py (original) +++ python/branches/release26-maint/Lib/linecache.py Fri May 21 23:45:16 2010 @@ -133,6 +133,8 @@ except IOError, msg: ## print '*** Cannot open', fullname, ':', msg return [] + if lines and not lines[-1].endswith('\n'): + lines[-1] += '\n' size, mtime = stat.st_size, stat.st_mtime cache[filename] = size, mtime, lines, fullname return lines Modified: python/branches/release26-maint/Lib/test/test_linecache.py ============================================================================== --- python/branches/release26-maint/Lib/test/test_linecache.py (original) +++ python/branches/release26-maint/Lib/test/test_linecache.py Fri May 21 23:45:16 2010 @@ -31,6 +31,11 @@ ''' +SOURCE_3 = ''' +def f(): + return 3''' # No ending newline + + class LineCacheTests(unittest.TestCase): def test_getline(self): @@ -63,6 +68,15 @@ empty = linecache.getlines('a/b/c/__init__.py') self.assertEquals(empty, []) + def test_no_ending_newline(self): + try: + with open(support.TESTFN, "w") as fp: + fp.write(SOURCE_3) + lines = linecache.getlines(support.TESTFN) + self.assertEqual(lines, ["\n", "def f():\n", " return 3\n"]) + finally: + support.unlink(support.TESTFN) + def test_clearcache(self): cached = [] for entry in TESTS: Modified: python/branches/release26-maint/Misc/NEWS ============================================================================== --- python/branches/release26-maint/Misc/NEWS (original) +++ python/branches/release26-maint/Misc/NEWS Fri May 21 23:45:16 2010 @@ -55,6 +55,9 @@ Library ------- +- Issue #8782: Add a trailing newline in linecache.updatecache to the last line + of files without one. + - Issue #8729: Return NotImplemented from collections.Mapping.__eq__ when comparing to a non-mapping. From python-checkins at python.org Fri May 21 23:47:07 2010 From: python-checkins at python.org (georg.brandl) Date: Fri, 21 May 2010 23:47:07 +0200 (CEST) Subject: [Python-checkins] r81440 - python/trunk/Doc/library/multiprocessing.rst Message-ID: <20100521214707.10014EE981@mail.python.org> Author: georg.brandl Date: Fri May 21 23:47:05 2010 New Revision: 81440 Log: Correct info for Semaphore.acquire() semantics under OSX. Modified: python/trunk/Doc/library/multiprocessing.rst Modified: python/trunk/Doc/library/multiprocessing.rst ============================================================================== --- python/trunk/Doc/library/multiprocessing.rst (original) +++ python/trunk/Doc/library/multiprocessing.rst Fri May 21 23:47:05 2010 @@ -839,7 +839,7 @@ A bounded semaphore object: a clone of :class:`threading.BoundedSemaphore`. - (On Mac OS X this is indistinguishable from :class:`Semaphore` because + (On Mac OS X, this is indistinguishable from :class:`Semaphore` because ``sem_getvalue()`` is not implemented on that platform). .. class:: Condition([lock]) @@ -881,9 +881,8 @@ specifies a timeout in seconds. If *block* is ``False`` then *timeout* is ignored. -.. note:: - On OS/X ``sem_timedwait`` is unsupported, so timeout arguments for the - aforementioned :meth:`acquire` methods will be ignored on OS/X. + On Mac OS X, ``sem_timedwait`` is unsupported, so calling ``acquire()`` with + a timeout will emulate that function's behavior using a sleeping loop. .. note:: From python-checkins at python.org Fri May 21 23:48:11 2010 From: python-checkins at python.org (georg.brandl) Date: Fri, 21 May 2010 23:48:11 +0200 (CEST) Subject: [Python-checkins] r81441 - in python/branches/release26-maint: Doc/library/multiprocessing.rst Message-ID: <20100521214811.05192EE981@mail.python.org> Author: georg.brandl Date: Fri May 21 23:48:10 2010 New Revision: 81441 Log: Merged revisions 81440 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r81440 | georg.brandl | 2010-05-21 23:47:05 +0200 (Fr, 21 Mai 2010) | 1 line Correct info for Semaphore.acquire() semantics under OSX. ........ Modified: python/branches/release26-maint/ (props changed) python/branches/release26-maint/Doc/library/multiprocessing.rst Modified: python/branches/release26-maint/Doc/library/multiprocessing.rst ============================================================================== --- python/branches/release26-maint/Doc/library/multiprocessing.rst (original) +++ python/branches/release26-maint/Doc/library/multiprocessing.rst Fri May 21 23:48:10 2010 @@ -836,7 +836,7 @@ A bounded semaphore object: a clone of :class:`threading.BoundedSemaphore`. - (On Mac OS X this is indistinguishable from :class:`Semaphore` because + (On Mac OS X, this is indistinguishable from :class:`Semaphore` because ``sem_getvalue()`` is not implemented on that platform). .. class:: Condition([lock]) @@ -872,9 +872,8 @@ specifies a timeout in seconds. If *block* is ``False`` then *timeout* is ignored. -.. note:: - On OS/X ``sem_timedwait`` is unsupported, so timeout arguments for the - aforementioned :meth:`acquire` methods will be ignored on OS/X. + On Mac OS X, ``sem_timedwait`` is unsupported, so calling ``acquire()`` with + a timeout will emulate that function's behavior using a sleeping loop. .. note:: From python-checkins at python.org Fri May 21 23:48:27 2010 From: python-checkins at python.org (georg.brandl) Date: Fri, 21 May 2010 23:48:27 +0200 (CEST) Subject: [Python-checkins] r81442 - in python/branches/py3k: Doc/library/multiprocessing.rst Message-ID: <20100521214827.EE8FFEE989@mail.python.org> Author: georg.brandl Date: Fri May 21 23:48:27 2010 New Revision: 81442 Log: Merged revisions 81440 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r81440 | georg.brandl | 2010-05-21 23:47:05 +0200 (Fr, 21 Mai 2010) | 1 line Correct info for Semaphore.acquire() semantics under OSX. ........ Modified: python/branches/py3k/ (props changed) python/branches/py3k/Doc/library/multiprocessing.rst Modified: python/branches/py3k/Doc/library/multiprocessing.rst ============================================================================== --- python/branches/py3k/Doc/library/multiprocessing.rst (original) +++ python/branches/py3k/Doc/library/multiprocessing.rst Fri May 21 23:48:27 2010 @@ -837,7 +837,7 @@ A bounded semaphore object: a clone of :class:`threading.BoundedSemaphore`. - (On Mac OS X this is indistinguishable from :class:`Semaphore` because + (On Mac OS X, this is indistinguishable from :class:`Semaphore` because ``sem_getvalue()`` is not implemented on that platform). .. class:: Condition([lock]) @@ -879,9 +879,8 @@ specifies a timeout in seconds. If *block* is ``False`` then *timeout* is ignored. -.. note:: - On OS/X ``sem_timedwait`` is unsupported, so timeout arguments for the - aforementioned :meth:`acquire` methods will be ignored on OS/X. + On Mac OS X, ``sem_timedwait`` is unsupported, so calling ``acquire()`` with + a timeout will emulate that function's behavior using a sleeping loop. .. note:: From python-checkins at python.org Fri May 21 23:48:58 2010 From: python-checkins at python.org (georg.brandl) Date: Fri, 21 May 2010 23:48:58 +0200 (CEST) Subject: [Python-checkins] r81443 - python/trunk/Misc/NEWS Message-ID: <20100521214858.24FC5EFE5@mail.python.org> Author: georg.brandl Date: Fri May 21 23:48:57 2010 New Revision: 81443 Log: typo Modified: python/trunk/Misc/NEWS Modified: python/trunk/Misc/NEWS ============================================================================== --- python/trunk/Misc/NEWS (original) +++ python/trunk/Misc/NEWS Fri May 21 23:48:57 2010 @@ -143,7 +143,7 @@ - Issue #8354: The siginterrupt setting is now preserved for all signals, not just SIGCHLD. -- Issue #7192: webbrowser.get("firefox") now wors on Mac OS X, as does +- Issue #7192: webbrowser.get("firefox") now works on Mac OS X, as does webbrowser.get("safari"). - Issue #8577: distutils.sysconfig.get_python_inc() now makes a difference From python-checkins at python.org Fri May 21 23:49:24 2010 From: python-checkins at python.org (benjamin.peterson) Date: Fri, 21 May 2010 23:49:24 +0200 (CEST) Subject: [Python-checkins] r81444 - in python/branches/release31-maint: Lib/linecache.py Lib/test/test_linecache.py Misc/NEWS Message-ID: <20100521214924.85009EE981@mail.python.org> Author: benjamin.peterson Date: Fri May 21 23:49:24 2010 New Revision: 81444 Log: Merged revisions 81438 via svnmerge from svn+ssh://pythondev at svn.python.org/python/branches/py3k ................ r81438 | benjamin.peterson | 2010-05-21 16:45:06 -0500 (Fri, 21 May 2010) | 25 lines Merged revisions 81428-81429,81432-81433,81437 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r81428 | benjamin.peterson | 2010-05-21 16:16:12 -0500 (Fri, 21 May 2010) | 1 line use addCleanup ........ r81429 | benjamin.peterson | 2010-05-21 16:17:22 -0500 (Fri, 21 May 2010) | 1 line fix name ........ r81432 | benjamin.peterson | 2010-05-21 16:31:24 -0500 (Fri, 21 May 2010) | 1 line ensure the last line has a trailing newline #8782 ........ r81433 | benjamin.peterson | 2010-05-21 16:32:49 -0500 (Fri, 21 May 2010) | 1 line remove debugging rubish ........ r81437 | benjamin.peterson | 2010-05-21 16:35:44 -0500 (Fri, 21 May 2010) | 1 line simplify and modernize updatecache() ........ ................ Modified: python/branches/release31-maint/ (props changed) python/branches/release31-maint/Lib/linecache.py python/branches/release31-maint/Lib/test/test_linecache.py python/branches/release31-maint/Misc/NEWS Modified: python/branches/release31-maint/Lib/linecache.py ============================================================================== --- python/branches/release31-maint/Lib/linecache.py (original) +++ python/branches/release31-maint/Lib/linecache.py Fri May 21 23:49:24 2010 @@ -73,13 +73,13 @@ if filename in cache: del cache[filename] - if not filename or filename[0] + filename[-1] == '<>': + if not filename or (filename.startswith('<') and filename.endswith('>')): return [] fullname = filename try: stat = os.stat(fullname) - except os.error as msg: + except OSError: basename = filename # Try for a __loader__, if available @@ -114,20 +114,23 @@ fullname = os.path.join(dirname, basename) except (TypeError, AttributeError): # Not sufficiently string-like to do anything useful with. + continue + try: + stat = os.stat(fullname) + break + except os.error: pass - else: - try: - stat = os.stat(fullname) - break - except os.error: - pass else: - # No luck return [] - with open(fullname, 'rb') as fp: - coding, line = tokenize.detect_encoding(fp.readline) - with open(fullname, 'r', encoding=coding) as fp: - lines = fp.readlines() + try: + with open(fullname, 'rb') as fp: + coding, line = tokenize.detect_encoding(fp.readline) + with open(fullname, 'r', encoding=coding) as fp: + lines = fp.readlines() + except IOError: + pass + if lines and not lines[-1].endswith('\n'): + lines[-1] += '\n' size, mtime = stat.st_size, stat.st_mtime cache[filename] = size, mtime, lines, fullname return lines Modified: python/branches/release31-maint/Lib/test/test_linecache.py ============================================================================== --- python/branches/release31-maint/Lib/test/test_linecache.py (original) +++ python/branches/release31-maint/Lib/test/test_linecache.py Fri May 21 23:49:24 2010 @@ -31,6 +31,11 @@ ''' +SOURCE_3 = ''' +def f(): + return 3''' # No ending newline + + class LineCacheTests(unittest.TestCase): def test_getline(self): @@ -63,6 +68,13 @@ empty = linecache.getlines('a/b/c/__init__.py') self.assertEquals(empty, []) + def test_no_ending_newline(self): + self.addCleanup(support.unlink, support.TESTFN) + with open(support.TESTFN, "w") as fp: + fp.write(SOURCE_3) + lines = linecache.getlines(support.TESTFN) + self.assertEqual(lines, ["\n", "def f():\n", " return 3\n"]) + def test_clearcache(self): cached = [] for entry in TESTS: @@ -81,42 +93,36 @@ def test_checkcache(self): getline = linecache.getline - try: - # Create a source file and cache its contents - source_name = support.TESTFN + '.py' - with open(source_name, 'w') as source: - source.write(SOURCE_1) - source.close() - getline(source_name, 1) - - # Keep a copy of the old contents - source_list = [] - source = open(source_name) - for index, line in enumerate(source): - self.assertEquals(line, getline(source_name, index + 1)) - source_list.append(line) - source.close() - - source = open(source_name, 'w') - source.write(SOURCE_2) - source.close() - - # Try to update a bogus cache entry - linecache.checkcache('dummy') - - # Check that the cache matches the old contents - for index, line in enumerate(source_list): - self.assertEquals(line, getline(source_name, index + 1)) - - # Update the cache and check whether it matches the new source file - linecache.checkcache(source_name) - source = open(source_name) - for index, line in enumerate(source): - self.assertEquals(line, getline(source_name, index + 1)) - source_list.append(line) + # Create a source file and cache its contents + source_name = support.TESTFN + '.py' + self.addCleanup(support.unlink, source_name) + with open(source_name, 'w') as source: + source.write(SOURCE_1) + getline(source_name, 1) + # Keep a copy of the old contents + source_list = [] + with open(source_name) as source: + for index, line in enumerate(source): + self.assertEquals(line, getline(source_name, index + 1)) + source_list.append(line) + + with open(source_name, 'w') as source: + source.write(SOURCE_2) + + # Try to update a bogus cache entry + linecache.checkcache('dummy') + + # Check that the cache matches the old contents + for index, line in enumerate(source_list): + self.assertEquals(line, getline(source_name, index + 1)) + + # Update the cache and check whether it matches the new source file + linecache.checkcache(source_name) + with open(source_name) as source: + for index, line in enumerate(source): + self.assertEquals(line, getline(source_name, index + 1)) + source_list.append(line) - finally: - support.unlink(source_name) def test_main(): support.run_unittest(LineCacheTests) Modified: python/branches/release31-maint/Misc/NEWS ============================================================================== --- python/branches/release31-maint/Misc/NEWS (original) +++ python/branches/release31-maint/Misc/NEWS Fri May 21 23:49:24 2010 @@ -54,6 +54,9 @@ Library ------- +- Issue #8782: Add a trailing newline in linecache.updatecache to the last line + of files without one. + - Issue #8729: Return NotImplemented from collections.Mapping.__eq__ when comparing to a non-mapping. From python-checkins at python.org Fri May 21 23:49:31 2010 From: python-checkins at python.org (georg.brandl) Date: Fri, 21 May 2010 23:49:31 +0200 (CEST) Subject: [Python-checkins] r81445 - python/branches/release26-maint Message-ID: <20100521214931.527D0EE9C0@mail.python.org> Author: georg.brandl Date: Fri May 21 23:49:31 2010 New Revision: 81445 Log: Blocked revisions 81443 via svnmerge ........ r81443 | georg.brandl | 2010-05-21 23:48:57 +0200 (Fr, 21 Mai 2010) | 1 line typo ........ Modified: python/branches/release26-maint/ (props changed) From python-checkins at python.org Fri May 21 23:49:47 2010 From: python-checkins at python.org (georg.brandl) Date: Fri, 21 May 2010 23:49:47 +0200 (CEST) Subject: [Python-checkins] r81446 - in python/branches/py3k: Misc/NEWS Message-ID: <20100521214947.92614EE9BD@mail.python.org> Author: georg.brandl Date: Fri May 21 23:49:47 2010 New Revision: 81446 Log: Merged revisions 81443 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r81443 | georg.brandl | 2010-05-21 23:48:57 +0200 (Fr, 21 Mai 2010) | 1 line typo ........ Modified: python/branches/py3k/ (props changed) python/branches/py3k/Misc/NEWS Modified: python/branches/py3k/Misc/NEWS ============================================================================== --- python/branches/py3k/Misc/NEWS (original) +++ python/branches/py3k/Misc/NEWS Fri May 21 23:49:47 2010 @@ -488,7 +488,7 @@ - Issue #8354: The siginterrupt setting is now preserved for all signals, not just SIGCHLD. -- Issue #7192: webbrowser.get("firefox") now wors on Mac OS X, as does +- Issue #7192: webbrowser.get("firefox") now works on Mac OS X, as does webbrowser.get("safari"). - Issue #8464: tarfile no longer creates files with execute permissions set From python-checkins at python.org Fri May 21 23:49:56 2010 From: python-checkins at python.org (georg.brandl) Date: Fri, 21 May 2010 23:49:56 +0200 (CEST) Subject: [Python-checkins] r81447 - in python/branches/release31-maint: Doc/library/multiprocessing.rst Message-ID: <20100521214956.EC268EE98A@mail.python.org> Author: georg.brandl Date: Fri May 21 23:49:56 2010 New Revision: 81447 Log: Recorded merge of revisions 81442 via svnmerge from svn+ssh://svn.python.org/python/branches/py3k ................ r81442 | georg.brandl | 2010-05-21 23:48:27 +0200 (Fr, 21 Mai 2010) | 9 lines Merged revisions 81440 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r81440 | georg.brandl | 2010-05-21 23:47:05 +0200 (Fr, 21 Mai 2010) | 1 line Correct info for Semaphore.acquire() semantics under OSX. ........ ................ Modified: python/branches/release31-maint/ (props changed) python/branches/release31-maint/Doc/library/multiprocessing.rst Modified: python/branches/release31-maint/Doc/library/multiprocessing.rst ============================================================================== --- python/branches/release31-maint/Doc/library/multiprocessing.rst (original) +++ python/branches/release31-maint/Doc/library/multiprocessing.rst Fri May 21 23:49:56 2010 @@ -837,7 +837,7 @@ A bounded semaphore object: a clone of :class:`threading.BoundedSemaphore`. - (On Mac OS X this is indistinguishable from :class:`Semaphore` because + (On Mac OS X, this is indistinguishable from :class:`Semaphore` because ``sem_getvalue()`` is not implemented on that platform). .. class:: Condition([lock]) @@ -879,9 +879,8 @@ specifies a timeout in seconds. If *block* is ``False`` then *timeout* is ignored. -.. note:: - On OS/X ``sem_timedwait`` is unsupported, so timeout arguments for the - aforementioned :meth:`acquire` methods will be ignored on OS/X. + On Mac OS X, ``sem_timedwait`` is unsupported, so calling ``acquire()`` with + a timeout will emulate that function's behavior using a sleeping loop. .. note:: From python-checkins at python.org Fri May 21 23:50:17 2010 From: python-checkins at python.org (georg.brandl) Date: Fri, 21 May 2010 23:50:17 +0200 (CEST) Subject: [Python-checkins] r81448 - python/branches/release31-maint Message-ID: <20100521215017.2394CEE9E0@mail.python.org> Author: georg.brandl Date: Fri May 21 23:50:17 2010 New Revision: 81448 Log: Blocked revisions 81446 via svnmerge ................ r81446 | georg.brandl | 2010-05-21 23:49:47 +0200 (Fr, 21 Mai 2010) | 9 lines Merged revisions 81443 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r81443 | georg.brandl | 2010-05-21 23:48:57 +0200 (Fr, 21 Mai 2010) | 1 line typo ........ ................ Modified: python/branches/release31-maint/ (props changed) From python-checkins at python.org Sat May 22 00:00:25 2010 From: python-checkins at python.org (georg.brandl) Date: Sat, 22 May 2010 00:00:25 +0200 (CEST) Subject: [Python-checkins] r81449 - peps/trunk/pep-3148.txt Message-ID: <20100521220025.69AE7EE9B6@mail.python.org> Author: georg.brandl Date: Sat May 22 00:00:25 2010 New Revision: 81449 Log: Update from Brian. Modified: peps/trunk/pep-3148.txt Modified: peps/trunk/pep-3148.txt ============================================================================== --- peps/trunk/pep-3148.txt (original) +++ peps/trunk/pep-3148.txt Sat May 22 00:00:25 2010 @@ -118,14 +118,14 @@ ``map(func, *iterables, timeout=None)`` - Equivalent to ``map(func, *iterables)`` but executed - asynchronously and possibly out-of-order. The returned iterator - raises a `TimeoutError` if `__next__()` is called and the result - isn't available after *timeout* seconds from the original call to - `map()`. If *timeout* is not specified or `None` then there is no - limit to the wait time. If a call raises an exception then that - exception will be raised when its value is retrieved from the - iterator. + Equivalent to ``map(func, *iterables)`` but func is executed + asynchronously and several calls to func may be made concurrently. + The returned iterator raises a `TimeoutError` if `__next__()` is + called and the result isn't available after *timeout* seconds from + the original call to `map()`. If *timeout* is not specified or + `None` then there is no limit to the wait time. If a call raises + an exception then that exception will be raised when its value is + retrieved from the iterator. ``shutdown(wait=True)`` @@ -364,7 +364,7 @@ Futures are created by concrete implementations of the Executor class (called ExecutorService in Java). The reference implementation -provides classes that use either a process a thread pool to eagerly +provides classes that use either a process or a thread pool to eagerly evaluate computations. Futures have already been seen in Python as part of a popular Python From python-checkins at python.org Sat May 22 00:03:29 2010 From: python-checkins at python.org (georg.brandl) Date: Sat, 22 May 2010 00:03:29 +0200 (CEST) Subject: [Python-checkins] r81450 - python/trunk/Doc/library/os.rst Message-ID: <20100521220329.A5DFAEE989@mail.python.org> Author: georg.brandl Date: Sat May 22 00:03:29 2010 New Revision: 81450 Log: #8709: mention Windows support for os.devnull. Modified: python/trunk/Doc/library/os.rst Modified: python/trunk/Doc/library/os.rst ============================================================================== --- python/trunk/Doc/library/os.rst (original) +++ python/trunk/Doc/library/os.rst Sat May 22 00:03:29 2010 @@ -2410,8 +2410,8 @@ .. data:: devnull - The file path of the null device. For example: ``'/dev/null'`` for POSIX. - Also available via :mod:`os.path`. + The file path of the null device. For example: ``'/dev/null'`` for + POSIX, ``'nul'`` for Windows. Also available via :mod:`os.path`. .. versionadded:: 2.4 From python-checkins at python.org Sat May 22 00:04:28 2010 From: python-checkins at python.org (georg.brandl) Date: Sat, 22 May 2010 00:04:28 +0200 (CEST) Subject: [Python-checkins] r81451 - in python/branches/release26-maint: Doc/library/os.rst Message-ID: <20100521220428.4FBBAEE9D9@mail.python.org> Author: georg.brandl Date: Sat May 22 00:04:28 2010 New Revision: 81451 Log: Merged revisions 81450 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r81450 | georg.brandl | 2010-05-22 00:03:29 +0200 (Sa, 22 Mai 2010) | 1 line #8709: mention Windows support for os.devnull. ........ Modified: python/branches/release26-maint/ (props changed) python/branches/release26-maint/Doc/library/os.rst Modified: python/branches/release26-maint/Doc/library/os.rst ============================================================================== --- python/branches/release26-maint/Doc/library/os.rst (original) +++ python/branches/release26-maint/Doc/library/os.rst Sat May 22 00:04:28 2010 @@ -2350,8 +2350,8 @@ .. data:: devnull - The file path of the null device. For example: ``'/dev/null'`` for POSIX. - Also available via :mod:`os.path`. + The file path of the null device. For example: ``'/dev/null'`` for + POSIX, ``'nul'`` for Windows. Also available via :mod:`os.path`. .. versionadded:: 2.4 From python-checkins at python.org Sat May 22 00:04:32 2010 From: python-checkins at python.org (georg.brandl) Date: Sat, 22 May 2010 00:04:32 +0200 (CEST) Subject: [Python-checkins] r81452 - in python/branches/py3k: Doc/library/os.rst Message-ID: <20100521220432.6E0C1EE9E0@mail.python.org> Author: georg.brandl Date: Sat May 22 00:04:32 2010 New Revision: 81452 Log: Merged revisions 81450 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r81450 | georg.brandl | 2010-05-22 00:03:29 +0200 (Sa, 22 Mai 2010) | 1 line #8709: mention Windows support for os.devnull. ........ Modified: python/branches/py3k/ (props changed) python/branches/py3k/Doc/library/os.rst Modified: python/branches/py3k/Doc/library/os.rst ============================================================================== --- python/branches/py3k/Doc/library/os.rst (original) +++ python/branches/py3k/Doc/library/os.rst Sat May 22 00:04:32 2010 @@ -2194,8 +2194,8 @@ .. data:: devnull - The file path of the null device. For example: ``'/dev/null'`` for POSIX. - Also available via :mod:`os.path`. + The file path of the null device. For example: ``'/dev/null'`` for + POSIX, ``'nul'`` for Windows. Also available via :mod:`os.path`. .. _os-miscfunc: From python-checkins at python.org Sat May 22 00:05:15 2010 From: python-checkins at python.org (georg.brandl) Date: Sat, 22 May 2010 00:05:15 +0200 (CEST) Subject: [Python-checkins] r81453 - in python/branches/release31-maint: Doc/library/os.rst Message-ID: <20100521220515.D1B81EE9DE@mail.python.org> Author: georg.brandl Date: Sat May 22 00:05:15 2010 New Revision: 81453 Log: Merged revisions 81452 via svnmerge from svn+ssh://svn.python.org/python/branches/py3k ................ r81452 | georg.brandl | 2010-05-22 00:04:32 +0200 (Sa, 22 Mai 2010) | 9 lines Merged revisions 81450 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r81450 | georg.brandl | 2010-05-22 00:03:29 +0200 (Sa, 22 Mai 2010) | 1 line #8709: mention Windows support for os.devnull. ........ ................ Modified: python/branches/release31-maint/ (props changed) python/branches/release31-maint/Doc/library/os.rst Modified: python/branches/release31-maint/Doc/library/os.rst ============================================================================== --- python/branches/release31-maint/Doc/library/os.rst (original) +++ python/branches/release31-maint/Doc/library/os.rst Sat May 22 00:05:15 2010 @@ -2073,8 +2073,8 @@ .. data:: devnull - The file path of the null device. For example: ``'/dev/null'`` for POSIX. - Also available via :mod:`os.path`. + The file path of the null device. For example: ``'/dev/null'`` for + POSIX, ``'nul'`` for Windows. Also available via :mod:`os.path`. .. _os-miscfunc: From python-checkins at python.org Sat May 22 00:50:29 2010 From: python-checkins at python.org (victor.stinner) Date: Sat, 22 May 2010 00:50:29 +0200 (CEST) Subject: [Python-checkins] r81454 - in python/trunk: Lib/test/test_multibytecodec.py Misc/NEWS Modules/cjkcodecs/multibytecodec.c Message-ID: <20100521225029.31ABEEE987@mail.python.org> Author: victor.stinner Date: Sat May 22 00:50:28 2010 New Revision: 81454 Log: Issue #5640: Fix Shift-JIS incremental encoder for error handlers different than strict Modified: python/trunk/Lib/test/test_multibytecodec.py python/trunk/Misc/NEWS python/trunk/Modules/cjkcodecs/multibytecodec.c Modified: python/trunk/Lib/test/test_multibytecodec.py ============================================================================== --- python/trunk/Lib/test/test_multibytecodec.py (original) +++ python/trunk/Lib/test/test_multibytecodec.py Sat May 22 00:50:28 2010 @@ -107,6 +107,10 @@ self.assertRaises(UnicodeEncodeError, encoder.encode, u'\u0123') self.assertEqual(encoder.encode(u'', True), '\xa9\xdc') + def test_issue5640(self): + encoder = codecs.getincrementalencoder('shift-jis')('backslashreplace') + self.assertEqual(encoder.encode(u'\xff'), b'\\xff') + self.assertEqual(encoder.encode(u'\n'), b'\n') class Test_IncrementalDecoder(unittest.TestCase): Modified: python/trunk/Misc/NEWS ============================================================================== --- python/trunk/Misc/NEWS (original) +++ python/trunk/Misc/NEWS Sat May 22 00:50:28 2010 @@ -29,6 +29,9 @@ Library ------- +- Issue #5640: Fix Shift-JIS incremental encoder for error handlers different + than strict + - Issue #8782: Add a trailing newline in linecache.updatecache to the last line of files without one. Modified: python/trunk/Modules/cjkcodecs/multibytecodec.c ============================================================================== --- python/trunk/Modules/cjkcodecs/multibytecodec.c (original) +++ python/trunk/Modules/cjkcodecs/multibytecodec.c Sat May 22 00:50:28 2010 @@ -498,7 +498,6 @@ outleft = (Py_ssize_t)(buf.outbuf_end - buf.outbuf); r = codec->encode(state, codec->config, &buf.inbuf, inleft, &buf.outbuf, outleft, flags); - *data = buf.inbuf; if ((r == 0) || (r == MBERR_TOOFEW && !(flags & MBENC_FLUSH))) break; else if (multibytecodec_encerror(codec, state, &buf, errors,r)) @@ -528,6 +527,7 @@ if (_PyString_Resize(&buf.outobj, finalsize) == -1) goto errorexit; + *data = buf.inbuf; Py_XDECREF(buf.excobj); return buf.outobj; From python-checkins at python.org Sat May 22 00:52:10 2010 From: python-checkins at python.org (victor.stinner) Date: Sat, 22 May 2010 00:52:10 +0200 (CEST) Subject: [Python-checkins] r81455 - python/branches/py3k Message-ID: <20100521225210.58B7FEE989@mail.python.org> Author: victor.stinner Date: Sat May 22 00:52:10 2010 New Revision: 81455 Log: Blocked revisions 81454 via svnmerge ........ r81454 | victor.stinner | 2010-05-22 00:50:28 +0200 (sam., 22 mai 2010) | 3 lines Issue #5640: Fix Shift-JIS incremental encoder for error handlers different than strict ........ Modified: python/branches/py3k/ (props changed) From python-checkins at python.org Sat May 22 00:55:31 2010 From: python-checkins at python.org (victor.stinner) Date: Sat, 22 May 2010 00:55:31 +0200 (CEST) Subject: [Python-checkins] r81456 - in python/branches/release26-maint: Lib/test/test_multibytecodec.py Misc/NEWS Modules/cjkcodecs/multibytecodec.c Message-ID: <20100521225531.E2A67EE989@mail.python.org> Author: victor.stinner Date: Sat May 22 00:55:31 2010 New Revision: 81456 Log: Merged revisions 81454 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r81454 | victor.stinner | 2010-05-22 00:50:28 +0200 (sam., 22 mai 2010) | 3 lines Issue #5640: Fix Shift-JIS incremental encoder for error handlers different than strict ........ Modified: python/branches/release26-maint/ (props changed) python/branches/release26-maint/Lib/test/test_multibytecodec.py python/branches/release26-maint/Misc/NEWS python/branches/release26-maint/Modules/cjkcodecs/multibytecodec.c Modified: python/branches/release26-maint/Lib/test/test_multibytecodec.py ============================================================================== --- python/branches/release26-maint/Lib/test/test_multibytecodec.py (original) +++ python/branches/release26-maint/Lib/test/test_multibytecodec.py Sat May 22 00:55:31 2010 @@ -108,6 +108,10 @@ self.assertRaises(UnicodeEncodeError, encoder.encode, u'\u0123') self.assertEqual(encoder.encode(u'', True), '\xa9\xdc') + def test_issue5640(self): + encoder = codecs.getincrementalencoder('shift-jis')('backslashreplace') + self.assertEqual(encoder.encode(u'\xff'), b'\\xff') + self.assertEqual(encoder.encode(u'\n'), b'\n') class Test_IncrementalDecoder(unittest.TestCase): Modified: python/branches/release26-maint/Misc/NEWS ============================================================================== --- python/branches/release26-maint/Misc/NEWS (original) +++ python/branches/release26-maint/Misc/NEWS Sat May 22 00:55:31 2010 @@ -55,6 +55,9 @@ Library ------- +- Issue #5640: Fix Shift-JIS incremental encoder for error handlers different + than strict + - Issue #8782: Add a trailing newline in linecache.updatecache to the last line of files without one. Modified: python/branches/release26-maint/Modules/cjkcodecs/multibytecodec.c ============================================================================== --- python/branches/release26-maint/Modules/cjkcodecs/multibytecodec.c (original) +++ python/branches/release26-maint/Modules/cjkcodecs/multibytecodec.c Sat May 22 00:55:31 2010 @@ -498,7 +498,6 @@ outleft = (Py_ssize_t)(buf.outbuf_end - buf.outbuf); r = codec->encode(state, codec->config, &buf.inbuf, inleft, &buf.outbuf, outleft, flags); - *data = buf.inbuf; if ((r == 0) || (r == MBERR_TOOFEW && !(flags & MBENC_FLUSH))) break; else if (multibytecodec_encerror(codec, state, &buf, errors,r)) @@ -528,6 +527,7 @@ if (_PyString_Resize(&buf.outobj, finalsize) == -1) goto errorexit; + *data = buf.inbuf; Py_XDECREF(buf.excobj); return buf.outobj; From solipsis at pitrou.net Sat May 22 01:25:30 2010 From: solipsis at pitrou.net (solipsis at pitrou.net) Date: Sat, 22 May 2010 01:25:30 +0200 (CEST) Subject: [Python-checkins] Daily py3k reference leaks (r81421): sum=0 Message-ID: <20100521232530.2B0B81771F@ns6635.ovh.net> py3k results for svn r81421 (hg cset 9b5334abee7f) -------------------------------------------------- Command line was: ['./python', '-m', 'test.regrtest', '-uall', '-R', '3:3:/home/antoine/py3k/refleaks/reflogSjvPUq', '-x'] From python-checkins at python.org Sat May 22 01:45:42 2010 From: python-checkins at python.org (victor.stinner) Date: Sat, 22 May 2010 01:45:42 +0200 (CEST) Subject: [Python-checkins] r81457 - in python/branches/py3k: Lib/test/test_sys.py Misc/NEWS Python/pythonrun.c Message-ID: <20100521234542.EA05AEE9C7@mail.python.org> Author: victor.stinner Date: Sat May 22 01:45:42 2010 New Revision: 81457 Log: Issue #3798: sys.exit(message) writes the message to sys.stderr file, instead of the C file stderr, to use stderr encoding and error handler Modified: python/branches/py3k/Lib/test/test_sys.py python/branches/py3k/Misc/NEWS python/branches/py3k/Python/pythonrun.c Modified: python/branches/py3k/Lib/test/test_sys.py ============================================================================== --- python/branches/py3k/Lib/test/test_sys.py (original) +++ python/branches/py3k/Lib/test/test_sys.py Sat May 22 01:45:42 2010 @@ -146,9 +146,9 @@ "raise SystemExit(47)"]) self.assertEqual(rc, 47) - def check_exit_message(code, expected): + def check_exit_message(code, expected, env=None): process = subprocess.Popen([sys.executable, "-c", code], - stderr=subprocess.PIPE) + stderr=subprocess.PIPE, env=env) stdout, stderr = process.communicate() self.assertEqual(process.returncode, 1) self.assertTrue(stderr.startswith(expected), @@ -166,6 +166,14 @@ r'import sys; sys.exit("surrogates:\uDCFF")', b"surrogates:\\udcff") + # test that the unicode message is encoded to the stderr encoding + # instead of the default encoding (utf8) + env = os.environ.copy() + env['PYTHONIOENCODING'] = 'latin-1' + check_exit_message( + r'import sys; sys.exit("h\xe9")', + b"h\xe9", env=env) + def test_getdefaultencoding(self): self.assertRaises(TypeError, sys.getdefaultencoding, 42) # can't check more than the type, as the user might have changed it Modified: python/branches/py3k/Misc/NEWS ============================================================================== --- python/branches/py3k/Misc/NEWS (original) +++ python/branches/py3k/Misc/NEWS Sat May 22 01:45:42 2010 @@ -393,6 +393,9 @@ Library ------- +- Issue #3798: sys.exit(message) writes the message to sys.stderr file, instead + of the C file stderr, to use stderr encoding and error handler + - Issue #8782: Add a trailing newline in linecache.updatecache to the last line of files without one. Modified: python/branches/py3k/Python/pythonrun.c ============================================================================== --- python/branches/py3k/Python/pythonrun.c (original) +++ python/branches/py3k/Python/pythonrun.c Sat May 22 01:45:42 2010 @@ -1386,10 +1386,12 @@ exitcode = (int)PyLong_AsLong(value); else { PyObject *sys_stderr = PySys_GetObject("stderr"); - if (sys_stderr != NULL) - PyObject_CallMethod(sys_stderr, "flush", NULL); - PyObject_Print(value, stderr, Py_PRINT_RAW); - fflush(stderr); + if (sys_stderr != NULL && sys_stderr != Py_None) { + PyFile_WriteObject(value, sys_stderr, Py_PRINT_RAW); + } else { + PyObject_Print(value, stderr, Py_PRINT_RAW); + fflush(stderr); + } PySys_WriteStderr("\n"); exitcode = 1; } From python-checkins at python.org Sat May 22 01:46:06 2010 From: python-checkins at python.org (jeffrey.yasskin) Date: Sat, 22 May 2010 01:46:06 +0200 (CEST) Subject: [Python-checkins] r81458 - in python/branches/py3k-jit: Include/bg_thread.h Include/ceval.h Include/code.h Include/intrcheck.h Include/pystate.h Lib/test/test_sys.py Makefile.pre.in Misc/NEWS Modules/_posixsubprocess.c Modules/posixmodule.c Modules/signalmodule.c Objects/codeobject.c Python/bg_thread.cc Python/ceval.c Python/pystate.c Unittests/BgThreadTest.cc Message-ID: <20100521234606.AFEBEEE9A3@mail.python.org> Author: jeffrey.yasskin Date: Sat May 22 01:46:06 2010 New Revision: 81458 Log: This patch adds a background thread that starts when a function becomes hot, but only runs dummy jobs in the background. The idea is that this will smoke out problems with forking, etc. and will make it easier to introduce compilation later. The concepts all come from Reid Kleckner's background compilation thread, but I've changed them around a bit. In particular, the background thread is now independent of the fact that we plan to do compilation in it; it should work for other kinds of jobs too. ### 2to3 ### 18.861179 -> 19.893243: 1.0547x slower ### slowpickle ### Min: 0.052314 -> 0.053090: 1.0148x slower Avg: 0.053037 -> 0.054663: 1.0306x slower Significant (t=-2.916043) Stddev: 0.00226 -> 0.00323: 1.4302x larger Timeline: b'http://tinyurl.com/32uk99v' ### slowunpickle ### Min: 0.089470 -> 0.088268: 1.0136x faster Avg: 0.089903 -> 0.089005: 1.0101x faster Not significant Stddev: 0.00214 -> 0.00276: 1.2912x larger Timeline: b'http://tinyurl.com/2urke56' I believe the slowdown is due to allocating inside PyCondition::Wait. I'll send another patch to fix that. Added: python/branches/py3k-jit/Include/bg_thread.h python/branches/py3k-jit/Python/bg_thread.cc python/branches/py3k-jit/Unittests/BgThreadTest.cc Modified: python/branches/py3k-jit/Include/ceval.h python/branches/py3k-jit/Include/code.h python/branches/py3k-jit/Include/intrcheck.h python/branches/py3k-jit/Include/pystate.h python/branches/py3k-jit/Lib/test/test_sys.py python/branches/py3k-jit/Makefile.pre.in python/branches/py3k-jit/Misc/NEWS python/branches/py3k-jit/Modules/_posixsubprocess.c python/branches/py3k-jit/Modules/posixmodule.c python/branches/py3k-jit/Modules/signalmodule.c python/branches/py3k-jit/Objects/codeobject.c python/branches/py3k-jit/Python/ceval.c python/branches/py3k-jit/Python/pystate.c Added: python/branches/py3k-jit/Include/bg_thread.h ============================================================================== --- (empty file) +++ python/branches/py3k-jit/Include/bg_thread.h Sat May 22 01:46:06 2010 @@ -0,0 +1,283 @@ +/* -*- C++ -*- */ +#ifndef Py_BG_THREAD_H +#define Py_BG_THREAD_H + +/* This header defines a class used to run jobs in a background + thread, with the GIL unlocked. The thread is accessible from + either C or C++, but it is implemented in C++. The interface and + implementation assume a single background thread (and, of course, + one thread at a time on the GIL end). */ + +typedef struct PyBackgroundThread PyBackgroundThread; +typedef struct PyBackgroundJob PyBackgroundJob; + +#ifdef __cplusplus +extern "C" { +#endif /* __cplusplus */ + +/* Whether or not we should block until a background job is finished. */ +typedef enum { + Py_NO_BLOCK, + Py_BLOCK +} Py_ShouldBlock; + +/* Creates and starts a background thread if none was running and + saves it into the PyInterpreterState. Then hands it a job to + run. */ +PyAPI_FUNC(int) PyBackgroundThread_RunJob( + PyInterpreterState*, PyBackgroundJob*); + +/* Returns true if the background thread has been disabled after + * forking. This function must be false to call the other functions + * here. */ +#define PyBackgroundThread_Disabled(thread) ((uintptr_t)(thread) & 1) + +/* Simple extern "C" wrappers for the compile thread methods. */ +PyAPI_FUNC(PyBackgroundThread*) PyBackgroundThread_New(void); +PyAPI_FUNC(void) PyBackgroundThread_Free(PyBackgroundThread*); +PyAPI_FUNC(void) PyBackgroundThread_Pause(PyBackgroundThread*); +PyAPI_FUNC(void) PyBackgroundThread_Unpause(PyBackgroundThread*); +PyAPI_FUNC(void) PyBackgroundThread_DisableAfterFork(PyInterpreterState*); +PyAPI_FUNC(int) PyBackgroundThread_ApplyFinishedJobs( + PyBackgroundThread*, Py_ShouldBlock); + +/* Returns a PyBackgroundJob that does nothing. */ +PyAPI_FUNC(PyBackgroundJob*) PyBackgroundThread_NewDummyJob(void); + +#ifdef __cplusplus +} + +#include "pythread.h" +#include + +// Acquires its lock argument within a scope. +struct PyLockGuard { + PyLockGuard(PyThread_type_lock lock) : lock_(lock) + { + PyThread_acquire_lock(this->lock_, WAIT_LOCK); + } + ~PyLockGuard() + { + PyThread_release_lock(this->lock_); + } +private: + const PyThread_type_lock lock_; +}; + +// Releases its lock argument within a scope. The lock must be held when the +// scope is entered, of course. +struct PyUnlockGuard { + PyUnlockGuard(PyThread_type_lock lock) : lock_(lock) + { + PyThread_release_lock(this->lock_); + } + ~PyUnlockGuard() + { + PyThread_acquire_lock(this->lock_, WAIT_LOCK); + } +private: + const PyThread_type_lock lock_; +}; + +// Acts roughly like a posix condition variable. This class takes the lock as a +// constructor argument and requires that it be held on entry to Wait(), +// Notify(), and NotifyAll(). +struct PyCondition { + PyCondition(PyThread_type_lock lock); + // All threads blocked in this->Wait() must have been notified by the time + // 'this' is destroyed. + ~PyCondition(); + + // Blocks until another thread calls Notify or NotifyAll. The associated + // lock must be held on entry and will be released and reacquired. + void Wait(); + + // Wakes up 'to_notify' threads blocked in this->Wait(). If less than that + // many threads are blocked, wakes all blocked threads. Unlike Posix + // condition variables, the associated lock must be held. + void Notify(size_t to_notify = 1); + + // Wakes up all threads blocked in this->Wait(). Unlike Posix condition + // variables, the associated lock must be held. + void NotifyAll(); + +private: + const PyThread_type_lock lock_; + std::deque waiters_; +}; + +// Provides a boolean variable 'was_set' that can transition from false to true +// at most one time, and a way to wait until it turns true. There is no way to +// change 'was_set' back to false because most uses would require extra locking +// around the reset to make sure notifications aren't lost. +struct PyMonotonicEvent { + PyMonotonicEvent(); + ~PyMonotonicEvent(); + + // Waits for 'was_set' to become true. + void Wait(); + // Sets 'was_set' to true. + void Set(); + +private: + const PyThread_type_lock lock_; + PyCondition cond_; + bool was_set_; +}; + +// This is the interface for background jobs. Each job has two virtual methods: +// a Run method, and an Apply method. +// +// The Run method runs on the background thread, with the GIL unlocked. It may +// acquire the GIL, but that kinda defeats the point. All Run methods execute +// serially, in the same order they were submitted to the background thread. +// +// The Apply method will called from some foreground thread that holds the GIL. +// The eval loop applies jobs periodically, and Python code waiting for a +// particular job to finish may apply other jobs too. When a Job's Apply method +// returns, the system deletes the job. +struct PyBackgroundJob { + PyBackgroundJob() : ready_to_apply_(NULL) {} + virtual ~PyBackgroundJob() {} + + // This method is called in the background thread. It must be careful not + // to access Python data structures since it doesn't hold the GIL, and to + // lock any data it needs to share. 'shutting_down' is true if Terminate + // has been called. + virtual void Run(bool shutting_down) = 0; + + // This method applies the result of the background job in a foreground + // thread. It's called while holding the GIL. If any Python exceptions are + // set when Apply returns, they'll be printed as if they escaped a Python + // thread. + virtual void Apply() = 0; + +private: + friend struct PyBackgroundThread; + // If ready_to_apply_ is not null, the background thread will Set it when a + // subsequent ApplyFinishedJobs will apply it. This is only set by + // PyBackgroundThread::RunJobAndWait(); users don't have access. + PyMonotonicEvent *ready_to_apply_; +}; + +// This class encapsulates all state required by the background thread. +// Instances must be created and all public methods must be called while holding +// the GIL. +struct PyBackgroundThread { +public: + PyBackgroundThread(); + ~PyBackgroundThread(); + + // This method starts the background thread. Calling it multiple times has + // no effect. + void Start(); + + // Terminate the background thread. This will block until it terminates, + // which may be after it finishes a single compile job. After the thread + // has has stopped, all of the public methods below will run the job in the + // foreground or do nothing. This method must be called before destroying + // the thread object or the PyGlobalLlvmData object. Calling this method + // when the thread is already stopped has no effect. + void Terminate(); + + // Pause the background thread. Puts a job on the queue that will cause the + // background thread to acquire the unpause event lock twice. This call + // must be paired with an Unpause call from the same thread. + // + // While the background thread is paused, it will run new jobs in the + // foreground, as if it had been terminated. This means that if we fork + // while paused, the child process won't send jobs off to nowhere allows us + // to fork while paused and avoid creating a new thread in the child process + // or depending on state + void Pause(); + + // Unpause the background thread. This releases the unpause_event_ lock, + // allowing the background thread to proceed. This call must be paired with + // a Pause call from the same thread. + void Unpause(); + + // Helper method that puts a job on the queue. If the queue is closed, it + // calls the RunAfterShutdown method of the job and returns -1. This + // method takes ownership of the job. + int RunJob(PyBackgroundJob *job); + + // Helper method that puts a job on the queue and waits for it to be + // finished. This method takes ownership of the job. + void RunJobAndWait(PyBackgroundJob *job); + + // Helper method that calls RunJobAndWait and then applies all finished + // jobs. This method takes ownership of the job. + void RunJobAndApply(PyBackgroundJob *job); + + // Apply the results of any JIT compilation done in the background thread. + // If block is PY_NO_BLOCK, then this function returns non-zero immediately + // if it cannot acquire the lock on the output job queue. Otherwise it + // returns 0. The thread that calls this must hold the GIL. + int ApplyFinishedJobs(Py_ShouldBlock block); + + PyThreadState *getThreadState() { return this->tstate_; } + +private: + // Guards member variables. + const PyThread_type_lock lock_; + // Lets the background thread wait for something to do. Guarded by + // this->lock_. + PyCondition cond_; + + // This is the queue transferring jobs that need to be Run from the + // foreground (GIL-holding threads) to the background thread. Guarded by + // this->lock_. + std::deque fore2back_queue_; + + // This is the queue transferring finished jobs that need to be Applied from + // the background thread to the foreground. It is read periodically when + // the Python ticker expires, or when a thread waits for a job to complete. + // Guarded by this->lock_. + std::deque back2fore_queue_; + + // Indicates whether the thread is running. Guarded by this->lock_. + bool running_; + + // True if a thread has called Terminate(). Guarded by this->lock_. + bool exiting_; + + // The thread state for the background thread. We don't use any of this + // information, but we have to have an interpreter state to swap in when we + // acquire the GIL. Many Python calls assume that there is always a valid + // thread state from which to get the interpreter state, so we must provide + // one. Set once at the beginning of Run + PyThreadState *tstate_; + + // The interpreter state corresponding to this background thread. We cache + // this value because it is not safe to call PyThreadState_GET() from a + // background thread. + PyInterpreterState *const interpreter_state_; + + // A lock that allows us to pause and unpause the background thread without + // destroying and recreating the underlying OS-level thread. + PyThread_type_lock unpause_event_; + + + // -- Functions called by the background thread -- + + // This static method is the background compilation thread entry point. It + // simply wraps calling ((PyBackgroundThread*)thread)->Run() so we can pass + // it as a function pointer to PyThread_start_new_thread. + static void Bootstrap(void *thread); + + // This method reads jobs from the queue and runs them in a loop. It + // terminates when it reads a JIT_EXIT job from the queue. This method + // must be called from the background thread, and the caller should not + // hold the GIL. + void Run(); + + // Puts a finished job on the output queue and notifies anyone waiting for + // it that it is now on the output queue. This method takes ownership of + // the job. This method must be called from the background thread, and the + // caller should not hold the GIL. + void OutputFinishedJob(PyBackgroundJob *job); +}; + +#endif /* __cplusplus */ + +#endif /* Py_BG_THREAD_H */ Modified: python/branches/py3k-jit/Include/ceval.h ============================================================================== --- python/branches/py3k-jit/Include/ceval.h (original) +++ python/branches/py3k-jit/Include/ceval.h Sat May 22 01:46:06 2010 @@ -170,6 +170,16 @@ PyAPI_FUNC(void) _PyEval_SetSwitchInterval(unsigned long microseconds); PyAPI_FUNC(unsigned long) _PyEval_GetSwitchInterval(void); +PyAPI_FUNC(void) _PyEval_AssertLockHeld(void); + +// Hide this assertion function behind a macro to avoid extra calls in release +// builds. +#ifndef NDEBUG +#define PyEval_AssertLockHeld() _PyEval_AssertLockHeld() +#else +#define PyEval_AssertLockHeld() +#endif /* NDEBUG */ + #define Py_BEGIN_ALLOW_THREADS { \ PyThreadState *_save; \ _save = PyEval_SaveThread(); @@ -189,7 +199,7 @@ PyAPI_FUNC(int) _PyEval_SliceIndex(PyObject *, Py_ssize_t *); PyAPI_FUNC(void) _PyEval_SignalAsyncExc(void); - +PyAPI_FUNC(void) _PyEval_SetBackgroundJobAvailable(int); #ifdef __cplusplus } Modified: python/branches/py3k-jit/Include/code.h ============================================================================== --- python/branches/py3k-jit/Include/code.h (original) +++ python/branches/py3k-jit/Include/code.h Sat May 22 01:46:06 2010 @@ -32,9 +32,14 @@ /* Measure of how hot this code object is. This will be used to decide which code objects are worth sending through LLVM. */ long co_hotness; + /* True if the code object is being compiled by the background thread. */ + char co_being_compiled; #endif /* WITH_LLVM */ } PyCodeObject; +/* The threshold for co_hotness before the code object is considered "hot". */ +#define PY_HOTNESS_THRESHOLD 100000 + /* Masks for co_flags above */ #define CO_OPTIMIZED 0x0001 #define CO_NEWLOCALS 0x0002 Modified: python/branches/py3k-jit/Include/intrcheck.h ============================================================================== --- python/branches/py3k-jit/Include/intrcheck.h (original) +++ python/branches/py3k-jit/Include/intrcheck.h Sat May 22 01:46:06 2010 @@ -7,7 +7,8 @@ PyAPI_FUNC(int) PyOS_InterruptOccurred(void); PyAPI_FUNC(void) PyOS_InitInterrupts(void); -PyAPI_FUNC(void) PyOS_AfterFork(void); +PyAPI_FUNC(void) PyOS_BeforeFork(void); +PyAPI_FUNC(int) PyOS_AfterFork(int); /* Preserves errno. */ #ifdef __cplusplus } Modified: python/branches/py3k-jit/Include/pystate.h ============================================================================== --- python/branches/py3k-jit/Include/pystate.h (original) +++ python/branches/py3k-jit/Include/pystate.h Sat May 22 01:46:06 2010 @@ -27,6 +27,13 @@ PyObject *codec_search_path; PyObject *codec_search_cache; PyObject *codec_error_registry; +#ifdef WITH_LLVM + /* NULL if no thread has been started yet. The low bit is set to + 1 after a fork to mark the thread as disabled until the user + explicitly re-enables it with + PyBackgroundThread_ReenableAfterFork(). */ + struct PyBackgroundThread *background_thread; +#endif int codecs_initialized; #ifdef HAVE_DLOPEN Modified: python/branches/py3k-jit/Lib/test/test_sys.py ============================================================================== --- python/branches/py3k-jit/Lib/test/test_sys.py (original) +++ python/branches/py3k-jit/Lib/test/test_sys.py Sat May 22 01:46:06 2010 @@ -633,7 +633,7 @@ check(get_cell().__closure__[0], size(h + 'P')) # code if WITH_LLVM: - check(get_cell().__code__, size(h + '5i8Pi3Pl')) + check(get_cell().__code__, size(h + '5i8Pi3Plc')) else: check(get_cell().__code__, size(h + '5i8Pi3P')) # complex Modified: python/branches/py3k-jit/Makefile.pre.in ============================================================================== --- python/branches/py3k-jit/Makefile.pre.in (original) +++ python/branches/py3k-jit/Makefile.pre.in Sat May 22 01:46:06 2010 @@ -292,6 +292,7 @@ Python/Python-ast.o \ Python/asdl.o \ Python/ast.o \ + Python/bg_thread.o \ Python/bltinmodule.o \ Python/ceval.o \ Python/compile.o \ @@ -654,11 +655,12 @@ Include/abstract.h \ Include/asdl.h \ Include/ast.h \ - Include/bltinmodule.h \ + Include/bg_thread.h \ Include/bitset.h \ + Include/bltinmodule.h \ Include/boolobject.h \ - Include/bytes_methods.h \ Include/bytearrayobject.h \ + Include/bytes_methods.h \ Include/bytesobject.h \ Include/cellobject.h \ Include/ceval.h \ @@ -746,6 +748,7 @@ $(srcdir)/Unittests/StatsTest.cc UNITTEST_SRCS := $(LIBRARY) \ + $(srcdir)/Unittests/BgThreadTest.cc \ $(srcdir)/Unittests/DatetimeTest.cc \ $(srcdir)/Unittests/DictTest.cc \ $(srcdir)/Unittests/GetArgsTest.cc \ Modified: python/branches/py3k-jit/Misc/NEWS ============================================================================== --- python/branches/py3k-jit/Misc/NEWS (original) +++ python/branches/py3k-jit/Misc/NEWS Sat May 22 01:46:06 2010 @@ -4,6 +4,25 @@ (editors: check NEWS.help for information about editing NEWS using ReST.) +What's New in Python 3.3 Alpha 1? +================================= + +*Release date: XX-XXX-XXX* + +Core and Builtins +----------------- + +C-API +----- + +- Previously, if extension modules forked, they were supposed to call + PyOS_AfterFork from the child process. Now they are required to call + PyOS_BeforeFork and PyOS_AfterFork in both the child and the parent and pass a + new boolean parameter to PyOS_AfterFork specifying whether the current process + is the child or the parent. To be specific, you should change "if (pid == 0) + PyOS_AfterFork()" to "PyOS_AfterFork(pid == 0)". + + What's New in Python 3.2 Alpha 1? ================================= Modified: python/branches/py3k-jit/Modules/_posixsubprocess.c ============================================================================== --- python/branches/py3k-jit/Modules/_posixsubprocess.c (original) +++ python/branches/py3k-jit/Modules/_posixsubprocess.c Sat May 22 01:46:06 2010 @@ -265,7 +265,7 @@ preexec_fn_args_tuple = PyTuple_New(0); if (!preexec_fn_args_tuple) goto cleanup; - _PyImport_AcquireLock(); + PyOS_BeforeFork(); } if (cwd_obj != Py_None) { @@ -291,7 +291,7 @@ * This call may not be async-signal-safe but neither is calling * back into Python. The user asked us to use hope as a strategy * to avoid deadlock... */ - PyOS_AfterFork(); + PyOS_AfterFork(/*is_child=*/1); } child_exec(exec_array, argv, envp, cwd, @@ -308,11 +308,9 @@ /* Capture the errno exception before errno can be clobbered. */ PyErr_SetFromErrno(PyExc_OSError); } - if (preexec_fn != Py_None && - _PyImport_ReleaseLock() < 0 && !PyErr_Occurred()) { - PyErr_SetString(PyExc_RuntimeError, - "not holding the import lock"); - } + + if (preexec_fn != Py_None) + PyOS_AfterFork(/*is_child=*/0); /* Parent process */ if (envp) Modified: python/branches/py3k-jit/Modules/posixmodule.c ============================================================================== --- python/branches/py3k-jit/Modules/posixmodule.c (original) +++ python/branches/py3k-jit/Modules/posixmodule.c Sat May 22 01:46:06 2010 @@ -3590,21 +3590,12 @@ { pid_t pid; int result = 0; - _PyImport_AcquireLock(); + PyOS_BeforeFork(); pid = fork1(); - if (pid == 0) { - /* child: this clobbers and resets the import lock. */ - PyOS_AfterFork(); - } else { - /* parent: release the import lock. */ - result = _PyImport_ReleaseLock(); - } + result = PyOS_AfterFork(pid == 0); if (pid == -1) return posix_error(); if (result < 0) { - /* Don't clobber the OSError if the fork failed. */ - PyErr_SetString(PyExc_RuntimeError, - "not holding the import lock"); return NULL; } return PyLong_FromPid(pid); @@ -3623,21 +3614,12 @@ { pid_t pid; int result = 0; - _PyImport_AcquireLock(); + PyOS_BeforeFork(); pid = fork(); - if (pid == 0) { - /* child: this clobbers and resets the import lock. */ - PyOS_AfterFork(); - } else { - /* parent: release the import lock. */ - result = _PyImport_ReleaseLock(); - } + result = PyOS_AfterFork(pid == 0); if (pid == -1) return posix_error(); if (result < 0) { - /* Don't clobber the OSError if the fork failed. */ - PyErr_SetString(PyExc_RuntimeError, - "not holding the import lock"); return NULL; } return PyLong_FromPid(pid); @@ -3749,21 +3731,12 @@ int master_fd = -1, result = 0; pid_t pid; - _PyImport_AcquireLock(); + PyOS_BeforeFork(); pid = forkpty(&master_fd, NULL, NULL, NULL); - if (pid == 0) { - /* child: this clobbers and resets the import lock. */ - PyOS_AfterFork(); - } else { - /* parent: release the import lock. */ - result = _PyImport_ReleaseLock(); - } + result = PyOS_AfterFork(pid == 0); if (pid == -1) return posix_error(); if (result < 0) { - /* Don't clobber the OSError if the fork failed. */ - PyErr_SetString(PyExc_RuntimeError, - "not holding the import lock"); return NULL; } return Py_BuildValue("(Ni)", PyLong_FromPid(pid), master_fd); Modified: python/branches/py3k-jit/Modules/signalmodule.c ============================================================================== --- python/branches/py3k-jit/Modules/signalmodule.c (original) +++ python/branches/py3k-jit/Modules/signalmodule.c Sat May 22 01:46:06 2010 @@ -5,6 +5,7 @@ #include "Python.h" #include "intrcheck.h" +#include "bg_thread.h" #ifdef MS_WINDOWS #include @@ -957,14 +958,51 @@ return 0; } +/* TODO: Move these other PyOS functions to a better place. */ + void -PyOS_AfterFork(void) +PyOS_BeforeFork(void) { + _PyImport_AcquireLock(); #ifdef WITH_THREAD - PyEval_ReInitThreads(); - main_thread = PyThread_get_thread_ident(); - main_pid = getpid(); - _PyImport_ReInitLock(); - PyThread_ReInitTLS(); +#ifdef WITH_LLVM + PyBackgroundThread_Pause(PyThreadState_GET()->interp->background_thread); +#endif +#endif +} + +/* Returns -1 if there was an error. Preserves errno. */ +int +PyOS_AfterFork(int is_child) +{ + int result = 0; + int saved_errno = errno; +#ifdef WITH_THREAD + PyInterpreterState *interp = PyThreadState_GET()->interp; + if (is_child) { +#ifdef WITH_LLVM + PyBackgroundThread_DisableAfterFork(interp); +#endif + PyEval_ReInitThreads(); + main_thread = PyThread_get_thread_ident(); + main_pid = getpid(); + _PyImport_ReInitLock(); + PyThread_ReInitTLS(); + } else { +#ifdef WITH_LLVM + PyBackgroundThread_Unpause(interp->background_thread); #endif + } +#endif + if (!is_child) { + /* parent-only: release the import lock. */ + result = _PyImport_ReleaseLock(); + if (result < 0 && !PyErr_Occurred()) { + /* Don't clobber any other errors someone set. */ + PyErr_SetString(PyExc_RuntimeError, + "not holding the import lock"); + } + } + errno = saved_errno; + return result; } Modified: python/branches/py3k-jit/Objects/codeobject.c ============================================================================== --- python/branches/py3k-jit/Objects/codeobject.c (original) +++ python/branches/py3k-jit/Objects/codeobject.c Sat May 22 01:46:06 2010 @@ -111,6 +111,7 @@ co->co_weakreflist = NULL; #ifdef WITH_LLVM co->co_hotness = 0; + co->co_being_compiled = 0; #endif /* WITH_LLVM */ } return co; Added: python/branches/py3k-jit/Python/bg_thread.cc ============================================================================== --- (empty file) +++ python/branches/py3k-jit/Python/bg_thread.cc Sat May 22 01:46:06 2010 @@ -0,0 +1,438 @@ +#include "Python.h" + +#include "bg_thread.h" +#include "pythread.h" + +#ifdef WITH_LLVM + +// Support structs: + +PyCondition::PyCondition(PyThread_type_lock lock) + : lock_(lock) +{} +PyCondition::~PyCondition() +{ + assert(this->waiters_.empty() && + "Destroyed condition variable with waiting threads"); +} + +void PyCondition::Wait() +{ + // TODO: Allocating a new python-lock on every wait is moderately + // expensive. We should add a real condition variable to + // pythreads or create a freelist for these python-locks. + const PyThread_type_lock semaphore = PyThread_allocate_lock(); + PyThread_acquire_lock(semaphore, WAIT_LOCK); + this->waiters_.push_back(semaphore); + const PyThread_type_lock this_lock = this->lock_; + PyThread_release_lock(this_lock); + // After here, 'this' may have been destroyed. + // Block until another thread notifies us. + PyThread_acquire_lock(semaphore, WAIT_LOCK); + PyThread_free_lock(semaphore); + PyThread_acquire_lock(this_lock, WAIT_LOCK); +} + +void PyCondition::Notify(size_t to_notify) +{ + to_notify = std::min(to_notify, waiters_.size()); + for (size_t i = 0; i < to_notify; ++i) { + PyThread_type_lock waiter_semaphore = waiters_.front(); + waiters_.pop_front(); + PyThread_release_lock(waiter_semaphore); + } +} + +void PyCondition::NotifyAll() +{ + Notify(waiters_.size()); +} + +PyMonotonicEvent::PyMonotonicEvent() + : lock_(PyThread_allocate_lock()), + cond_(lock_), + was_set_(false) +{} +PyMonotonicEvent::~PyMonotonicEvent() +{ + PyThread_free_lock(lock_); +} + +void PyMonotonicEvent::Wait() +{ + PyLockGuard g(this->lock_); + while (!this->was_set_) { + this->cond_.Wait(); + } +} + +void PyMonotonicEvent::Set() +{ + PyLockGuard g(this->lock_); + this->was_set_ = true; + this->cond_.NotifyAll(); +} + + +// Actual background thread code: + +PyBackgroundThread::PyBackgroundThread() + : lock_(PyThread_allocate_lock()), cond_(lock_), + running_(false), exiting_(false), tstate_(NULL), + interpreter_state_(PyThreadState_GET()->interp), + unpause_event_(PyThread_allocate_lock()) +{ +} + +PyBackgroundThread::~PyBackgroundThread() +{ + this->Terminate(); + PyThread_free_lock(this->unpause_event_); +#ifdef Py_WITH_INSTRUMENTATION + fprintf(stderr, "Compilation thread statistics:\n"); + fprintf(stderr, "compile jobs completed: %d\n", CompileJob::compile_count); + fprintf(stderr, "compile jobs skipped at thread termination: %d\n", + CompileJob::skipped_compile_count); +#endif +} + +// Assumes this->lock_ is held. +void +PyBackgroundThread::OutputFinishedJob(PyBackgroundJob *job) +{ + // Put the result of the action on the output queue. This takes + // ownership of the job. + this->back2fore_queue_.push_back(job); + + // Alert anybody who might be blocked waiting for this job to finish. This + // is done under the same lock as the output queue, so that anyone waiting + // can call this->ApplyFinishedJobs(Py_BLOCK) to make the job take effect. + if (job->ready_to_apply_) { + job->ready_to_apply_->Set(); + } + + // Tell the eval loop too. + _PyEval_SetBackgroundJobAvailable(true); +} + +void +PyBackgroundThread::Run() +{ + // Create a new thread state. + assert(this->tstate_ == NULL); + this->tstate_ = PyThreadState_New(this->interpreter_state_); + + PyLockGuard lg(this->lock_); + // Consume and run jobs from the input queue until Terminate is called. + // Then consume jobs until there aren't any left and exit. + while (true) { + while (!this->exiting_ && this->fore2back_queue_.empty()) { + this->cond_.Wait(); + } + const bool exiting = this->exiting_; + if (exiting && this->fore2back_queue_.empty()) { + break; + } + PyBackgroundJob *job = this->fore2back_queue_.front(); + this->fore2back_queue_.pop_front(); + + { + PyUnlockGuard ug(this->lock_); + // Don't hold the lock while running the job, so other jobs can be + // submitted without blocking. + job->Run(exiting); + } + this->OutputFinishedJob(job); + } + PyThreadState_Clear(this->tstate_); + PyThreadState_Delete(this->tstate_); + this->tstate_ = NULL; + this->running_ = false; + this->cond_.NotifyAll(); +} + +int +PyBackgroundThread::RunJob(PyBackgroundJob *job) +{ + PyEval_AssertLockHeld(); + + { + PyLockGuard g(this->lock_); + if (this->running_) { + this->fore2back_queue_.push_back(job); + this->cond_.NotifyAll(); + return 0; + } + } + + // If the background thread has terminated, it can't race with the code in + // any job that expects to run there. So we just do exactly what the + // background thread would have done. + job->Run(/*shutting_down=*/true); + + // Rather than pushing it on to the output queue, since we already hold + // the GIL, we apply the job and delete it here. + job->Apply(); + delete job; + return -1; +} + +void +PyBackgroundThread::RunJobAndWait(PyBackgroundJob *job) +{ + // Create a lock for the job, acquire it, and put the job on the queue. + assert(job->ready_to_apply_ == NULL && "Job is already being waited for?"); + PyMonotonicEvent ready; + job->ready_to_apply_ = &ready; + if (this->RunJob(job) < 0) { + // If we couldn't put it on the queue, don't wait for it, because it's + // already done. + return; + } + + // Try to acquire the lock again to wait until the lock is released by the + // background thread. This may take awhile, so we release the GIL while we + // wait. + Py_BEGIN_ALLOW_THREADS; + ready.Wait(); + job->ready_to_apply_ = NULL; + // When we get control back, reacquire the GIL. + Py_END_ALLOW_THREADS; +} + +void +PyBackgroundThread::RunJobAndApply(PyBackgroundJob *job) +{ + this->RunJobAndWait(job); + // Call this to make sure all compilations take effect before we return. + this->ApplyFinishedJobs(Py_BLOCK); +} + +int +PyBackgroundThread::ApplyFinishedJobs(Py_ShouldBlock block) +{ + if (!PyThread_acquire_lock(this->lock_, block == Py_BLOCK)) { + assert(block == Py_NO_BLOCK && + "We should only fail to acquire the lock " + "in a non-blocking application attempt."); + return -1; // We couldn't acquire the lock, so we'll try again later. + } + std::deque queue; + // Take all of the elements out of the background->foreground queue. + queue.swap(this->back2fore_queue_); + // Tell the eval loop that the jobs are taken care of. We have to + // do this under the lock so we don't clobber any new jobs that + // finish after we release the lock. + _PyEval_SetBackgroundJobAvailable(false); + // Then release the lock so Apply doesn't deadlock, and the background + // thread can keep running jobs. + PyThread_release_lock(this->lock_); + + for (std::deque::const_iterator + it = queue.begin(), end = queue.end(); it != end; ++it) { + PyBackgroundJob *job = *it; + job->Apply(); + delete job; + } + return 0; +} + +void +PyBackgroundThread::Terminate() +{ + Py_BEGIN_ALLOW_THREADS; + { + PyLockGuard g(this->lock_); + this->exiting_ = true; + this->cond_.NotifyAll(); + while (this->running_) { + this->cond_.Wait(); + } + } + Py_END_ALLOW_THREADS; + this->ApplyFinishedJobs(Py_BLOCK); +} + +void +PyBackgroundThread::Bootstrap(void *thread) +{ + ((PyBackgroundThread*)thread)->Run(); +} + +void +PyBackgroundThread::Start() +{ + if (this->running_) { + return; + } + this->running_ = true; + + PyEval_InitThreads(); /* Start the interpreter's thread-awareness */ + PyThread_start_new_thread(Bootstrap, this); +} + +// A PyBackgroundJob that pauses the background thread in preparation for +// forking. This works by acquiring the PyBackgroundThread::unpause_event_ lock +// twice. +struct PauseJob : public PyBackgroundJob { + PauseJob(PyThread_type_lock bg_thread_lock, + PyThread_type_lock unpause_event, + PyMonotonicEvent &paused) + : bg_thread_lock_(bg_thread_lock), + unpause_event_(unpause_event), + paused_(&paused) + {} + + // Acquire the unpause event lock so that we wait for it. + virtual void Run(bool shut_down) { + if (shut_down) { + // If we try to pause the thread after its stopped, acquire the lock once, + // so that it can be properly released later. + PyThread_acquire_lock(this->unpause_event_, WAIT_LOCK); + return; + } + + // Prepare to block by acquiring the unpause event lock twice. + assert(PyThread_acquire_lock(this->unpause_event_, NOWAIT_LOCK) && + "Unpause event lock was already acquired!"); + + // Acquire the lock on the whole background thread so that no one can + // use it while we're paused. + PyThread_acquire_lock(this->bg_thread_lock_, WAIT_LOCK); + + // We need to notify whoever is waiting on this job before we block. + this->paused_->Set(); + // The foreground thread may fork at any point after this. + this->paused_ = NULL; + + // At this point, there is sort of a race between the thread that paused + // the compilation thread and this next acquire. In either case, after + // the acquire we will hold the lock because only one pause job can be + // processed at a time. + + // Block until we are unpaused. + PyThread_acquire_lock(this->unpause_event_, WAIT_LOCK); + + // Leave the unpause event lock in the released state. + PyThread_release_lock(this->unpause_event_); + + // Release the locks on the background thread. + PyThread_release_lock(this->bg_thread_lock_); + } + + virtual void Apply() {} + +private: + const PyThread_type_lock bg_thread_lock_; + const PyThread_type_lock unpause_event_; + PyMonotonicEvent *paused_; +}; + +void +PyBackgroundThread::Pause() +{ + PyMonotonicEvent paused; + { + PyLockGuard g(this->lock_); + if (!this->running_) + return; + + // Put the pause job at the front of the queue so we don't wait for the + // other jobs to finish before pausing. + this->fore2back_queue_.push_front( + new PauseJob(this->lock_, this->unpause_event_, paused)); + this->cond_.NotifyAll(); + } + + // Wait for the pause job to actually start and acquire the locks it needs + // to acquire. + paused.Wait(); + + // Note that we leak the pause job in the child process during a fork. This + // is OK because we leak all kinds of other things, like locks and objects + // owned by other threads. +} + +void +PyBackgroundThread::Unpause() +{ + PyThread_release_lock(this->unpause_event_); +} + +extern "C" { + void + PyBackgroundThread_DisableAfterFork(PyInterpreterState *interp) + { + interp->background_thread = + reinterpret_cast( + reinterpret_cast(interp->background_thread) | 1); + } + + void + PyBackgroundThread_ReenableAfterFork(PyInterpreterState *interp) + { + // After forking, most of the data in the background thread is + // in an unknown state. We do, however, know that the thread + // isn't actually running. So we leak any memory owned by the + // background thread, and reset the interpreter's pointer to + // NULL, so anyone trying to use it will restart the thread. + interp->background_thread = NULL; + } + + PyBackgroundThread * + PyBackgroundThread_New() + { + return new PyBackgroundThread; + } + + void + PyBackgroundThread_Free(PyBackgroundThread *bg_thread) + { + delete bg_thread; + } + + void + PyBackgroundThread_Pause(PyBackgroundThread *thread) + { + if (thread != NULL && !PyBackgroundThread_Disabled(thread)) + thread->Pause(); + } + + void + PyBackgroundThread_Unpause(PyBackgroundThread *thread) + { + if (thread != NULL && !PyBackgroundThread_Disabled(thread)) + thread->Unpause(); + } + + int PyBackgroundThread_RunJob(PyInterpreterState *interp, + PyBackgroundJob *job) + { + if (interp->background_thread == NULL) { + interp->background_thread = new PyBackgroundThread; + interp->background_thread->Start(); + } + return interp->background_thread->RunJob(job); + } + + int + PyBackgroundThread_ApplyFinishedJobs( + PyBackgroundThread *thread, Py_ShouldBlock block) + { + return thread->ApplyFinishedJobs(block); + } + + PyBackgroundJob* + PyBackgroundThread_NewDummyJob() + { + struct DummyJob : PyBackgroundJob { + virtual void Run(bool shutting_down) + {} + virtual void Apply() + {} + }; + return new DummyJob; + } +} + +#endif // WITH_LLVM Modified: python/branches/py3k-jit/Python/ceval.c ============================================================================== --- python/branches/py3k-jit/Python/ceval.c (original) +++ python/branches/py3k-jit/Python/ceval.c Sat May 22 01:46:06 2010 @@ -11,6 +11,7 @@ #include "Python.h" +#include "bg_thread.h" #include "code.h" #include "frameobject.h" #include "eval.h" @@ -119,6 +120,8 @@ #ifdef WITH_LLVM static inline void mark_called(PyCodeObject *co); +static inline void maybe_compile(PyInterpreterState *interp, + PyCodeObject *co, PyFrameObject *f); #endif /* WITH_LLVM */ #define CALL_FLAG_VAR 1 @@ -229,6 +232,7 @@ &eval_breaker, \ _Py_atomic_load_relaxed(&gil_drop_request) | \ _Py_atomic_load_relaxed(&pendingcalls_to_do) | \ + _Py_atomic_load_relaxed(&background_job_ready) | \ pending_async_exc) #define SET_GIL_DROP_REQUEST() \ @@ -265,6 +269,18 @@ #define UNSIGNAL_ASYNC_EXC() \ do { pending_async_exc = 0; COMPUTE_EVAL_BREAKER(); } while (0) +#define SIGNAL_BACKGROUND_JOB_READY() \ + do { \ + _Py_atomic_store_relaxed(&background_job_ready, 1); \ + _Py_atomic_store_relaxed(&eval_breaker, 1); \ + } while (0) + +#define UNSIGNAL_BACKGROUND_JOB_READY() \ + do { \ + _Py_atomic_store_relaxed(&background_job_ready, 0); \ + COMPUTE_EVAL_BREAKER(); \ + } while (0) + #ifdef WITH_THREAD @@ -285,6 +301,8 @@ /* Request for looking at the `async_exc` field of the current thread state. Guarded by the GIL. */ static int pending_async_exc = 0; +/* Request for applying background jobs. */ +static _Py_atomic_int background_job_ready = {0}; #include "ceval_gil.h" @@ -326,6 +344,18 @@ &_PyThreadState_Current)); } +#ifndef NDEBUG +// Assert that the calling thread holds the GIL. To do this we ask Python what +// thread it thinks is currently running and compare its identity with our own. +void +_PyEval_AssertLockHeld() +{ + PyThreadState *tstate = PyThreadState_GET(); + assert(tstate && tstate->thread_id == PyThread_get_thread_ident() && + "Caller must hold the GIL!"); +} +#endif // NDEBUG + void PyEval_AcquireThread(PyThreadState *tstate) { @@ -403,6 +433,7 @@ static _Py_atomic_int eval_breaker = {0}; static _Py_atomic_int gil_drop_request = {0}; static int pending_async_exc = 0; +static _Py_atomic_int background_job_ready = {0}; #endif /* WITH_THREAD */ /* This function is used to signal that async exceptions are waiting to be @@ -414,6 +445,17 @@ SIGNAL_ASYNC_EXC(); } +/* Lets the eval loop know that a background job is or isn't ready to + apply. */ +void +_PyEval_SetBackgroundJobAvailable(int available) +{ + if (available) + SIGNAL_BACKGROUND_JOB_READY(); + else + UNSIGNAL_BACKGROUND_JOB_READY(); +} + /* Functions save_thread and restore_thread are always defined so dynamically loaded modules needn't be compiled separately for use with and without threads: */ @@ -1144,6 +1186,11 @@ return NULL; tstate->frame = f; + co = f->f_code; + +#ifdef WITH_LLVM + maybe_compile(tstate->interp, co, f); +#endif /* WITH_LLVM */ if (tstate->use_tracing) { if (tstate->c_tracefunc != NULL) { @@ -1179,7 +1226,6 @@ } } - co = f->f_code; names = co->co_names; consts = co->co_consts; fastlocals = f->f_localsplus; @@ -1281,6 +1327,28 @@ goto on_error; } } + if (_Py_atomic_load_relaxed(&background_job_ready)) { +#ifdef WITH_LLVM + if (tstate->interp->background_thread == NULL || + PyBackgroundThread_Disabled( + tstate->interp->background_thread)) { + /* No interpreter background thread, so it can't + have a job ready, but there could be other + instances that signal the interpreter + spuriously. */ + UNSIGNAL_BACKGROUND_JOB_READY(); + } + else { + /* No need to block. If we can't acquire the lock, + we'll try again on the next iteration. */ + PyBackgroundThread_ApplyFinishedJobs( + tstate->interp->background_thread, + Py_NO_BLOCK); + } +#else /* !WITH_LLVM */ + UNSIGNAL_BACKGROUND_JOB_READY(); +#endif /* WITH_LLVM */ + } if (_Py_atomic_load_relaxed(&gil_drop_request)) { #ifdef WITH_THREAD /* Give another thread a chance */ @@ -3843,6 +3911,28 @@ { co->co_hotness += 10; } + +/* For now, if the code object is hot, starts the background thread if + necessary and sends a dummy job to it. TODO: flesh this out to + actually compile. */ +static inline void +maybe_compile(PyInterpreterState *interp, PyCodeObject *co, PyFrameObject *f) +{ + int is_hot = 0, should_compile; + if (co->co_hotness > PY_HOTNESS_THRESHOLD) + is_hot = 1; + should_compile = is_hot; + if (PyBackgroundThread_Disabled(interp->background_thread)) + should_compile = 0; + if (co->co_being_compiled) + should_compile = 0; + if (should_compile) { + co->co_being_compiled = 1; + PyBackgroundThread_RunJob(PyThreadState_GET()->interp, + PyBackgroundThread_NewDummyJob()); + } +} + #endif /* WITH_LLVM */ #define C_TRACE(x, call) \ Modified: python/branches/py3k-jit/Python/pystate.c ============================================================================== --- python/branches/py3k-jit/Python/pystate.c (original) +++ python/branches/py3k-jit/Python/pystate.c Sat May 22 01:46:06 2010 @@ -25,6 +25,7 @@ #ifdef WITH_THREAD #include "pythread.h" +#include "bg_thread.h" static PyThread_type_lock head_mutex = NULL; /* Protects interp->tstate_head */ #define HEAD_INIT() (void)(head_mutex || (head_mutex = PyThread_allocate_lock())) #define HEAD_LOCK() PyThread_acquire_lock(head_mutex, WAIT_LOCK) @@ -79,6 +80,9 @@ interp->codec_search_cache = NULL; interp->codec_error_registry = NULL; interp->codecs_initialized = 0; +#ifdef WITH_LLVM + interp->background_thread = NULL; +#endif /* WITH_LLVM */ #ifdef HAVE_DLOPEN #ifdef RTLD_NOW interp->dlopenflags = RTLD_NOW; @@ -116,6 +120,10 @@ Py_CLEAR(interp->modules_reloading); Py_CLEAR(interp->sysdict); Py_CLEAR(interp->builtins); +#ifdef WITH_LLVM + PyBackgroundThread_Free(interp->background_thread); + interp->background_thread = NULL; +#endif /* WITH_LLVM */ } Added: python/branches/py3k-jit/Unittests/BgThreadTest.cc ============================================================================== --- (empty file) +++ python/branches/py3k-jit/Unittests/BgThreadTest.cc Sat May 22 01:46:06 2010 @@ -0,0 +1,112 @@ +#include "Python.h" +#include "pythread.h" +#include "bg_thread.h" + +#include "gtest/gtest.h" +#include "pytest.h" + +#include + +namespace { + +class BgThreadTest : public ::testing::Test { + PythonSetupTeardown setup_teardown_; +}; + +TEST_F(BgThreadTest, StartStop) +{ + PyThreadState *tstate = PyThreadState_GET(); + PyBackgroundThread thread; + EXPECT_EQ(tstate, PyThreadState_GET()); + thread.Start(); + EXPECT_EQ(tstate, PyThreadState_GET()); + thread.Terminate(); + EXPECT_EQ(tstate, PyThreadState_GET()); +} + +struct TestJob : public PyBackgroundJob { + TestJob(int &phases_run) + : phases_run_(phases_run) + { + } + + virtual void Run(bool shutdown) + { + phases_run_++; + } + + virtual void Apply() + { + phases_run_++; + } + +private: + int &phases_run_; +}; + +TEST_F(BgThreadTest, PhasesRun) +{ + PyBackgroundThread thread; + thread.Start(); + int phases_run = 0; + thread.RunJobAndWait(new TestJob(phases_run)); + EXPECT_EQ(1, phases_run); + thread.ApplyFinishedJobs(Py_BLOCK); + EXPECT_EQ(2, phases_run); + thread.Terminate(); +} + +TEST_F(BgThreadTest, EvalLoopAppliesJobs) +{ + PyBackgroundThread thread; + // Tell the eval loop which PyBackgroundThread to listen to. + PyThreadState_GET()->interp->background_thread = &thread; + thread.Start(); + int phases_run = 0; + thread.RunJobAndWait(new TestJob(phases_run)); + EXPECT_EQ(1, phases_run); + PyRun_SimpleString("for i in range(3): i += 1"); + EXPECT_EQ(2, phases_run); + thread.Terminate(); + // Don't free the background thread in PyInterpreterState + // destruction though. + PyThreadState_GET()->interp->background_thread = NULL; +} + +TEST_F(BgThreadTest, RunAndApplyAppliesJobs) +{ + PyBackgroundThread thread; + thread.Start(); + int phases_run = 0; + thread.RunJobAndApply(new TestJob(phases_run)); + EXPECT_EQ(2, phases_run); + thread.Terminate(); +} + +TEST_F(BgThreadTest, TerminationWaitsForAndAppliesActiveJobs) +{ + PyBackgroundThread thread; + thread.Start(); + int phases_run = 0; + thread.RunJob(new TestJob(phases_run)); + thread.Terminate(); + EXPECT_EQ(2, phases_run); +} + +TEST_F(BgThreadTest, AfterTerminationJobsRunImmediately) +{ + PyBackgroundThread thread; + thread.Start(); + thread.Terminate(); + int phases_run = 0; + thread.RunJob(new TestJob(phases_run)); + EXPECT_EQ(2, phases_run); +} + +TEST_F(BgThreadTest, HotFunctionStartsThread) +{ + PyRun_SimpleString("def hot(): pass\nfor _ in range(10**4 + 1): hot()"); + EXPECT_TRUE(NULL != PyThreadState_GET()->interp->background_thread); +} + +} // anonymous namespace From python-checkins at python.org Sat May 22 04:11:07 2010 From: python-checkins at python.org (victor.stinner) Date: Sat, 22 May 2010 04:11:07 +0200 (CEST) Subject: [Python-checkins] r81459 - in python/trunk: Lib/codecs.py Lib/test/test_codecs.py Misc/NEWS Message-ID: <20100522021107.D05F4EE984@mail.python.org> Author: victor.stinner Date: Sat May 22 04:11:07 2010 New Revision: 81459 Log: Issue #6268: Fix seek() method of codecs.open(), don't read the BOM twice after seek(0) Modified: python/trunk/Lib/codecs.py python/trunk/Lib/test/test_codecs.py python/trunk/Misc/NEWS Modified: python/trunk/Lib/codecs.py ============================================================================== --- python/trunk/Lib/codecs.py (original) +++ python/trunk/Lib/codecs.py Sat May 22 04:11:07 2010 @@ -694,6 +694,10 @@ self.reader.reset() self.writer.reset() + def seek(self, offset, whence=0): + self.reader.seek(offset, whence) + self.writer.seek(offset, whence) + def __getattr__(self, name, getattr=getattr): Modified: python/trunk/Lib/test/test_codecs.py ============================================================================== --- python/trunk/Lib/test/test_codecs.py (original) +++ python/trunk/Lib/test/test_codecs.py Sat May 22 04:11:07 2010 @@ -1496,6 +1496,26 @@ self.assertEquals(srw.read(), u"\xfc") +class BomTest(unittest.TestCase): + def test_seek0(self): + data = "1234567890" + tests = ("utf-16", + "utf-16-le", + "utf-16-be", + "utf-32", + "utf-32-le", + "utf-32-be") + for encoding in tests: + with codecs.open('foo', 'wt+', encoding=encoding) as f: + # Check if the BOM is written only once + f.write(data) + f.write(data) + f.seek(0) + self.assertEquals(f.read(), data * 2) + f.seek(0) + self.assertEquals(f.read(), data * 2) + + def test_main(): test_support.run_unittest( UTF32Test, @@ -1524,6 +1544,7 @@ BasicStrTest, CharmapTest, WithStmtTest, + BomTest, ) Modified: python/trunk/Misc/NEWS ============================================================================== --- python/trunk/Misc/NEWS (original) +++ python/trunk/Misc/NEWS Sat May 22 04:11:07 2010 @@ -29,6 +29,9 @@ Library ------- +- Issue #6268: Fix seek() method of codecs.open(), don't read the BOM twice + after seek(0) + - Issue #5640: Fix Shift-JIS incremental encoder for error handlers different than strict From python-checkins at python.org Sat May 22 04:12:29 2010 From: python-checkins at python.org (victor.stinner) Date: Sat, 22 May 2010 04:12:29 +0200 (CEST) Subject: [Python-checkins] r81460 - in python/branches/release26-maint: Lib/codecs.py Lib/test/test_codecs.py Misc/NEWS Message-ID: <20100522021229.206C3EE984@mail.python.org> Author: victor.stinner Date: Sat May 22 04:12:28 2010 New Revision: 81460 Log: Merged revisions 81459 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r81459 | victor.stinner | 2010-05-22 04:11:07 +0200 (sam., 22 mai 2010) | 3 lines Issue #6268: Fix seek() method of codecs.open(), don't read the BOM twice after seek(0) ........ Modified: python/branches/release26-maint/ (props changed) python/branches/release26-maint/Lib/codecs.py python/branches/release26-maint/Lib/test/test_codecs.py python/branches/release26-maint/Misc/NEWS Modified: python/branches/release26-maint/Lib/codecs.py ============================================================================== --- python/branches/release26-maint/Lib/codecs.py (original) +++ python/branches/release26-maint/Lib/codecs.py Sat May 22 04:12:28 2010 @@ -694,6 +694,10 @@ self.reader.reset() self.writer.reset() + def seek(self, offset, whence=0): + self.reader.seek(offset, whence) + self.writer.seek(offset, whence) + def __getattr__(self, name, getattr=getattr): Modified: python/branches/release26-maint/Lib/test/test_codecs.py ============================================================================== --- python/branches/release26-maint/Lib/test/test_codecs.py (original) +++ python/branches/release26-maint/Lib/test/test_codecs.py Sat May 22 04:12:28 2010 @@ -1488,6 +1488,26 @@ self.assertEquals(srw.read(), u"\xfc") +class BomTest(unittest.TestCase): + def test_seek0(self): + data = "1234567890" + tests = ("utf-16", + "utf-16-le", + "utf-16-be", + "utf-32", + "utf-32-le", + "utf-32-be") + for encoding in tests: + with codecs.open('foo', 'wt+', encoding=encoding) as f: + # Check if the BOM is written only once + f.write(data) + f.write(data) + f.seek(0) + self.assertEquals(f.read(), data * 2) + f.seek(0) + self.assertEquals(f.read(), data * 2) + + def test_main(): test_support.run_unittest( UTF32Test, @@ -1516,6 +1536,7 @@ BasicStrTest, CharmapTest, WithStmtTest, + BomTest, ) Modified: python/branches/release26-maint/Misc/NEWS ============================================================================== --- python/branches/release26-maint/Misc/NEWS (original) +++ python/branches/release26-maint/Misc/NEWS Sat May 22 04:12:28 2010 @@ -55,6 +55,9 @@ Library ------- +- Issue #6268: Fix seek() method of codecs.open(), don't read the BOM twice + after seek(0) + - Issue #5640: Fix Shift-JIS incremental encoder for error handlers different than strict From python-checkins at python.org Sat May 22 04:16:27 2010 From: python-checkins at python.org (victor.stinner) Date: Sat, 22 May 2010 04:16:27 +0200 (CEST) Subject: [Python-checkins] r81461 - in python/branches/py3k: Lib/codecs.py Lib/test/test_codecs.py Misc/NEWS Message-ID: <20100522021627.8E2E4EE9BC@mail.python.org> Author: victor.stinner Date: Sat May 22 04:16:27 2010 New Revision: 81461 Log: Merged revisions 81459 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r81459 | victor.stinner | 2010-05-22 04:11:07 +0200 (sam., 22 mai 2010) | 3 lines Issue #6268: Fix seek() method of codecs.open(), don't read the BOM twice after seek(0) ........ Modified: python/branches/py3k/ (props changed) python/branches/py3k/Lib/codecs.py python/branches/py3k/Lib/test/test_codecs.py python/branches/py3k/Misc/NEWS Modified: python/branches/py3k/Lib/codecs.py ============================================================================== --- python/branches/py3k/Lib/codecs.py (original) +++ python/branches/py3k/Lib/codecs.py Sat May 22 04:16:27 2010 @@ -699,6 +699,10 @@ self.reader.reset() self.writer.reset() + def seek(self, offset, whence=0): + self.reader.seek(offset, whence) + self.writer.seek(offset, whence) + def __getattr__(self, name, getattr=getattr): Modified: python/branches/py3k/Lib/test/test_codecs.py ============================================================================== --- python/branches/py3k/Lib/test/test_codecs.py (original) +++ python/branches/py3k/Lib/test/test_codecs.py Sat May 22 04:16:27 2010 @@ -1594,6 +1594,26 @@ b"\xe4\xeb\xef\xf6\xfc") +class BomTest(unittest.TestCase): + def test_seek0(self): + data = "1234567890" + tests = ("utf-16", + "utf-16-le", + "utf-16-be", + "utf-32", + "utf-32-le", + "utf-32-be") + for encoding in tests: + with codecs.open('foo', 'w+', encoding=encoding) as f: + # Check if the BOM is written only once + f.write(data) + f.write(data) + f.seek(0) + self.assertEquals(f.read(), data * 2) + f.seek(0) + self.assertEquals(f.read(), data * 2) + + def test_main(): support.run_unittest( UTF32Test, @@ -1621,6 +1641,7 @@ WithStmtTest, TypesTest, SurrogateEscapeTest, + BomTest, ) Modified: python/branches/py3k/Misc/NEWS ============================================================================== --- python/branches/py3k/Misc/NEWS (original) +++ python/branches/py3k/Misc/NEWS Sat May 22 04:16:27 2010 @@ -393,6 +393,9 @@ Library ------- +- Issue #6268: Fix seek() method of codecs.open(), don't read the BOM twice + after seek(0) + - Issue #3798: sys.exit(message) writes the message to sys.stderr file, instead of the C file stderr, to use stderr encoding and error handler From python-checkins at python.org Sat May 22 04:17:42 2010 From: python-checkins at python.org (victor.stinner) Date: Sat, 22 May 2010 04:17:42 +0200 (CEST) Subject: [Python-checkins] r81462 - in python/branches/release31-maint: Lib/codecs.py Lib/test/test_codecs.py Misc/NEWS Message-ID: <20100522021742.498CCEE988@mail.python.org> Author: victor.stinner Date: Sat May 22 04:17:42 2010 New Revision: 81462 Log: Merged revisions 81461 via svnmerge from svn+ssh://pythondev at svn.python.org/python/branches/py3k ................ r81461 | victor.stinner | 2010-05-22 04:16:27 +0200 (sam., 22 mai 2010) | 10 lines Merged revisions 81459 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r81459 | victor.stinner | 2010-05-22 04:11:07 +0200 (sam., 22 mai 2010) | 3 lines Issue #6268: Fix seek() method of codecs.open(), don't read the BOM twice after seek(0) ........ ................ Modified: python/branches/release31-maint/ (props changed) python/branches/release31-maint/Lib/codecs.py python/branches/release31-maint/Lib/test/test_codecs.py python/branches/release31-maint/Misc/NEWS Modified: python/branches/release31-maint/Lib/codecs.py ============================================================================== --- python/branches/release31-maint/Lib/codecs.py (original) +++ python/branches/release31-maint/Lib/codecs.py Sat May 22 04:17:42 2010 @@ -699,6 +699,10 @@ self.reader.reset() self.writer.reset() + def seek(self, offset, whence=0): + self.reader.seek(offset, whence) + self.writer.seek(offset, whence) + def __getattr__(self, name, getattr=getattr): Modified: python/branches/release31-maint/Lib/test/test_codecs.py ============================================================================== --- python/branches/release31-maint/Lib/test/test_codecs.py (original) +++ python/branches/release31-maint/Lib/test/test_codecs.py Sat May 22 04:17:42 2010 @@ -1592,6 +1592,26 @@ b"\xe4\xeb\xef\xf6\xfc") +class BomTest(unittest.TestCase): + def test_seek0(self): + data = "1234567890" + tests = ("utf-16", + "utf-16-le", + "utf-16-be", + "utf-32", + "utf-32-le", + "utf-32-be") + for encoding in tests: + with codecs.open('foo', 'w+', encoding=encoding) as f: + # Check if the BOM is written only once + f.write(data) + f.write(data) + f.seek(0) + self.assertEquals(f.read(), data * 2) + f.seek(0) + self.assertEquals(f.read(), data * 2) + + def test_main(): support.run_unittest( UTF32Test, @@ -1619,6 +1639,7 @@ WithStmtTest, TypesTest, SurrogateEscapeTest, + BomTest, ) Modified: python/branches/release31-maint/Misc/NEWS ============================================================================== --- python/branches/release31-maint/Misc/NEWS (original) +++ python/branches/release31-maint/Misc/NEWS Sat May 22 04:17:42 2010 @@ -54,6 +54,9 @@ Library ------- +- Issue #6268: Fix seek() method of codecs.open(), don't read the BOM twice + after seek(0) + - Issue #8782: Add a trailing newline in linecache.updatecache to the last line of files without one. From python-checkins at python.org Sat May 22 10:17:23 2010 From: python-checkins at python.org (georg.brandl) Date: Sat, 22 May 2010 10:17:23 +0200 (CEST) Subject: [Python-checkins] r81463 - python/trunk/Doc/library/re.rst Message-ID: <20100522081723.F1E52EE99F@mail.python.org> Author: georg.brandl Date: Sat May 22 10:17:23 2010 New Revision: 81463 Log: #8785: less confusing description of regex.find*. Modified: python/trunk/Doc/library/re.rst Modified: python/trunk/Doc/library/re.rst ============================================================================== --- python/trunk/Doc/library/re.rst (original) +++ python/trunk/Doc/library/re.rst Sat May 22 10:17:23 2010 @@ -739,12 +739,16 @@ .. method:: RegexObject.findall(string[, pos[, endpos]]) - Identical to the :func:`findall` function, using the compiled pattern. + Similar to the :func:`findall` function, using the compiled pattern, but + also accepts optional *pos* and *endpos* parameters that limit the search + region like for :meth:`match`. .. method:: RegexObject.finditer(string[, pos[, endpos]]) - Identical to the :func:`finditer` function, using the compiled pattern. + Similar to the :func:`finditer` function, using the compiled pattern, but + also accepts optional *pos* and *endpos* parameters that limit the search + region like for :meth:`match`. .. method:: RegexObject.sub(repl, string[, count=0]) From python-checkins at python.org Sat May 22 10:21:45 2010 From: python-checkins at python.org (georg.brandl) Date: Sat, 22 May 2010 10:21:45 +0200 (CEST) Subject: [Python-checkins] r81464 - in python/branches/release26-maint: Doc/library/re.rst Message-ID: <20100522082145.86BF6EE9A9@mail.python.org> Author: georg.brandl Date: Sat May 22 10:21:45 2010 New Revision: 81464 Log: Merged revisions 81463 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r81463 | georg.brandl | 2010-05-22 10:17:23 +0200 (Sa, 22 Mai 2010) | 1 line #8785: less confusing description of regex.find*. ........ Modified: python/branches/release26-maint/ (props changed) python/branches/release26-maint/Doc/library/re.rst Modified: python/branches/release26-maint/Doc/library/re.rst ============================================================================== --- python/branches/release26-maint/Doc/library/re.rst (original) +++ python/branches/release26-maint/Doc/library/re.rst Sat May 22 10:21:45 2010 @@ -727,12 +727,16 @@ .. method:: RegexObject.findall(string[, pos[, endpos]]) - Identical to the :func:`findall` function, using the compiled pattern. + Similar to the :func:`findall` function, using the compiled pattern, but + also accepts optional *pos* and *endpos* parameters that limit the search + region like for :meth:`match`. .. method:: RegexObject.finditer(string[, pos[, endpos]]) - Identical to the :func:`finditer` function, using the compiled pattern. + Similar to the :func:`finditer` function, using the compiled pattern, but + also accepts optional *pos* and *endpos* parameters that limit the search + region like for :meth:`match`. .. method:: RegexObject.sub(repl, string[, count=0]) From python-checkins at python.org Sat May 22 13:29:19 2010 From: python-checkins at python.org (georg.brandl) Date: Sat, 22 May 2010 13:29:19 +0200 (CEST) Subject: [Python-checkins] r81465 - in python/trunk: Lib/cookielib.py Lib/test/test_cookielib.py Misc/NEWS Message-ID: <20100522112919.749A2EEA00@mail.python.org> Author: georg.brandl Date: Sat May 22 13:29:19 2010 New Revision: 81465 Log: Issue #3924: Ignore cookies with invalid "version" field in cookielib. Modified: python/trunk/Lib/cookielib.py python/trunk/Lib/test/test_cookielib.py python/trunk/Misc/NEWS Modified: python/trunk/Lib/cookielib.py ============================================================================== --- python/trunk/Lib/cookielib.py (original) +++ python/trunk/Lib/cookielib.py Sat May 22 13:29:19 2010 @@ -434,6 +434,13 @@ if attr: headers.append("; ".join(attr)) return ", ".join(headers) +def strip_quotes(text): + if text.startswith('"'): + text = text[1:] + if text.endswith('"'): + text = text[:-1] + return text + def parse_ns_headers(ns_headers): """Ad-hoc parser for Netscape protocol cookie-attributes. @@ -451,7 +458,7 @@ """ known_attrs = ("expires", "domain", "path", "secure", # RFC 2109 attrs (may turn up in Netscape cookies, too) - "port", "max-age") + "version", "port", "max-age") result = [] for ns_header in ns_headers: @@ -471,12 +478,11 @@ k = lc if k == "version": # This is an RFC 2109 cookie. + v = strip_quotes(v) version_set = True if k == "expires": # convert expires date to seconds since epoch - if v.startswith('"'): v = v[1:] - if v.endswith('"'): v = v[:-1] - v = http2time(v) # None if invalid + v = http2time(strip_quotes(v)) # None if invalid pairs.append((k, v)) if pairs: @@ -1450,7 +1456,11 @@ # set the easy defaults version = standard.get("version", None) - if version is not None: version = int(version) + if version is not None: + try: + version = int(version) + except ValueError: + return None # invalid version, ignore cookie secure = standard.get("secure", False) # (discard is also set if expires is Absent) discard = standard.get("discard", False) Modified: python/trunk/Lib/test/test_cookielib.py ============================================================================== --- python/trunk/Lib/test/test_cookielib.py (original) +++ python/trunk/Lib/test/test_cookielib.py Sat May 22 13:29:19 2010 @@ -99,7 +99,8 @@ class HeaderTests(TestCase): - def test_parse_ns_headers(self): + + def test_parse_ns_headers_expires(self): from cookielib import parse_ns_headers # quotes should be stripped @@ -110,6 +111,17 @@ ]: self.assertEquals(parse_ns_headers([hdr]), expected) + def test_parse_ns_headers_version(self): + from cookielib import parse_ns_headers + + # quotes should be stripped + expected = [[('foo', 'bar'), ('version', '1')]] + for hdr in [ + 'foo=bar; version="1"', + 'foo=bar; Version="1"', + ]: + self.assertEquals(parse_ns_headers([hdr]), expected) + def test_parse_ns_headers_special_names(self): # names such as 'expires' are not special in first name=value pair # of Set-Cookie: header @@ -1091,6 +1103,8 @@ ["Set-Cookie2: a=foo; path=/; Version=1; domain"], # bad max-age ["Set-Cookie: b=foo; max-age=oops"], + # bad version + ["Set-Cookie: b=foo; version=spam"], ]: c = cookiejar_from_cookie_headers(headers) # these bad cookies shouldn't be set Modified: python/trunk/Misc/NEWS ============================================================================== --- python/trunk/Misc/NEWS (original) +++ python/trunk/Misc/NEWS Sat May 22 13:29:19 2010 @@ -29,6 +29,8 @@ Library ------- +- Issue #3924: Ignore cookies with invalid "version" field in cookielib. + - Issue #6268: Fix seek() method of codecs.open(), don't read the BOM twice after seek(0) From python-checkins at python.org Sat May 22 13:31:16 2010 From: python-checkins at python.org (georg.brandl) Date: Sat, 22 May 2010 13:31:16 +0200 (CEST) Subject: [Python-checkins] r81466 - python/trunk/Lib/cookielib.py Message-ID: <20100522113116.A4C8EEE9FA@mail.python.org> Author: georg.brandl Date: Sat May 22 13:31:16 2010 New Revision: 81466 Log: Underscore the name of an internal utility function. Modified: python/trunk/Lib/cookielib.py Modified: python/trunk/Lib/cookielib.py ============================================================================== --- python/trunk/Lib/cookielib.py (original) +++ python/trunk/Lib/cookielib.py Sat May 22 13:31:16 2010 @@ -434,7 +434,7 @@ if attr: headers.append("; ".join(attr)) return ", ".join(headers) -def strip_quotes(text): +def _strip_quotes(text): if text.startswith('"'): text = text[1:] if text.endswith('"'): @@ -478,11 +478,11 @@ k = lc if k == "version": # This is an RFC 2109 cookie. - v = strip_quotes(v) + v = _strip_quotes(v) version_set = True if k == "expires": # convert expires date to seconds since epoch - v = http2time(strip_quotes(v)) # None if invalid + v = http2time(_strip_quotes(v)) # None if invalid pairs.append((k, v)) if pairs: From python-checkins at python.org Sat May 22 13:32:59 2010 From: python-checkins at python.org (georg.brandl) Date: Sat, 22 May 2010 13:32:59 +0200 (CEST) Subject: [Python-checkins] r81467 - in python/branches/release26-maint: Lib/cookielib.py Lib/test/test_cookielib.py Misc/NEWS Message-ID: <20100522113259.B403AEEA02@mail.python.org> Author: georg.brandl Date: Sat May 22 13:32:59 2010 New Revision: 81467 Log: Merged revisions 81465-81466 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r81465 | georg.brandl | 2010-05-22 13:29:19 +0200 (Sa, 22 Mai 2010) | 2 lines Issue #3924: Ignore cookies with invalid "version" field in cookielib. ........ r81466 | georg.brandl | 2010-05-22 13:31:16 +0200 (Sa, 22 Mai 2010) | 1 line Underscore the name of an internal utility function. ........ Modified: python/branches/release26-maint/ (props changed) python/branches/release26-maint/Lib/cookielib.py python/branches/release26-maint/Lib/test/test_cookielib.py python/branches/release26-maint/Misc/NEWS Modified: python/branches/release26-maint/Lib/cookielib.py ============================================================================== --- python/branches/release26-maint/Lib/cookielib.py (original) +++ python/branches/release26-maint/Lib/cookielib.py Sat May 22 13:32:59 2010 @@ -434,6 +434,13 @@ if attr: headers.append("; ".join(attr)) return ", ".join(headers) +def _strip_quotes(text): + if text.startswith('"'): + text = text[1:] + if text.endswith('"'): + text = text[:-1] + return text + def parse_ns_headers(ns_headers): """Ad-hoc parser for Netscape protocol cookie-attributes. @@ -451,7 +458,7 @@ """ known_attrs = ("expires", "domain", "path", "secure", # RFC 2109 attrs (may turn up in Netscape cookies, too) - "port", "max-age") + "version", "port", "max-age") result = [] for ns_header in ns_headers: @@ -471,12 +478,11 @@ k = lc if k == "version": # This is an RFC 2109 cookie. + v = _strip_quotes(v) version_set = True if k == "expires": # convert expires date to seconds since epoch - if v.startswith('"'): v = v[1:] - if v.endswith('"'): v = v[:-1] - v = http2time(v) # None if invalid + v = http2time(_strip_quotes(v)) # None if invalid pairs.append((k, v)) if pairs: @@ -1450,7 +1456,11 @@ # set the easy defaults version = standard.get("version", None) - if version is not None: version = int(version) + if version is not None: + try: + version = int(version) + except ValueError: + return None # invalid version, ignore cookie secure = standard.get("secure", False) # (discard is also set if expires is Absent) discard = standard.get("discard", False) Modified: python/branches/release26-maint/Lib/test/test_cookielib.py ============================================================================== --- python/branches/release26-maint/Lib/test/test_cookielib.py (original) +++ python/branches/release26-maint/Lib/test/test_cookielib.py Sat May 22 13:32:59 2010 @@ -99,7 +99,8 @@ class HeaderTests(TestCase): - def test_parse_ns_headers(self): + + def test_parse_ns_headers_expires(self): from cookielib import parse_ns_headers # quotes should be stripped @@ -110,6 +111,17 @@ ]: self.assertEquals(parse_ns_headers([hdr]), expected) + def test_parse_ns_headers_version(self): + from cookielib import parse_ns_headers + + # quotes should be stripped + expected = [[('foo', 'bar'), ('version', '1')]] + for hdr in [ + 'foo=bar; version="1"', + 'foo=bar; Version="1"', + ]: + self.assertEquals(parse_ns_headers([hdr]), expected) + def test_parse_ns_headers_special_names(self): # names such as 'expires' are not special in first name=value pair # of Set-Cookie: header @@ -1093,6 +1105,8 @@ ["Set-Cookie2: a=foo; path=/; Version=1; domain"], # bad max-age ["Set-Cookie: b=foo; max-age=oops"], + # bad version + ["Set-Cookie: b=foo; version=spam"], ]: c = cookiejar_from_cookie_headers(headers) # these bad cookies shouldn't be set Modified: python/branches/release26-maint/Misc/NEWS ============================================================================== --- python/branches/release26-maint/Misc/NEWS (original) +++ python/branches/release26-maint/Misc/NEWS Sat May 22 13:32:59 2010 @@ -55,6 +55,8 @@ Library ------- +- Issue #3924: Ignore cookies with invalid "version" field in cookielib. + - Issue #6268: Fix seek() method of codecs.open(), don't read the BOM twice after seek(0) From python-checkins at python.org Sat May 22 13:43:25 2010 From: python-checkins at python.org (georg.brandl) Date: Sat, 22 May 2010 13:43:25 +0200 (CEST) Subject: [Python-checkins] r81468 - python/trunk/Objects/enumobject.c Message-ID: <20100522114325.26102EE983@mail.python.org> Author: georg.brandl Date: Sat May 22 13:43:25 2010 New Revision: 81468 Log: #8635: document enumerate() start parameter in docstring. Modified: python/trunk/Objects/enumobject.c Modified: python/trunk/Objects/enumobject.c ============================================================================== --- python/trunk/Objects/enumobject.c (original) +++ python/trunk/Objects/enumobject.c Sat May 22 13:43:25 2010 @@ -159,12 +159,13 @@ } PyDoc_STRVAR(enum_doc, -"enumerate(iterable) -> iterator for index, value of iterable\n" +"enumerate(iterable[, start]) -> iterator for index, value of iterable\n" "\n" "Return an enumerate object. iterable must be another object that supports\n" "iteration. The enumerate object yields pairs containing a count (from\n" -"zero) and a value yielded by the iterable argument. enumerate is useful\n" -"for obtaining an indexed list: (0, seq[0]), (1, seq[1]), (2, seq[2]), ..."); +"start, which defaults to zero) and a value yielded by the iterable argument.\n" +"enumerate is useful for obtaining an indexed list:\n" +" (0, seq[0]), (1, seq[1]), (2, seq[2]), ..."); PyTypeObject PyEnum_Type = { PyVarObject_HEAD_INIT(&PyType_Type, 0) From python-checkins at python.org Sat May 22 13:44:31 2010 From: python-checkins at python.org (georg.brandl) Date: Sat, 22 May 2010 13:44:31 +0200 (CEST) Subject: [Python-checkins] r81469 - in python/branches/release26-maint: Objects/enumobject.c Message-ID: <20100522114431.0B438E917@mail.python.org> Author: georg.brandl Date: Sat May 22 13:44:30 2010 New Revision: 81469 Log: Merged revisions 81468 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r81468 | georg.brandl | 2010-05-22 13:43:25 +0200 (Sa, 22 Mai 2010) | 1 line #8635: document enumerate() start parameter in docstring. ........ Modified: python/branches/release26-maint/ (props changed) python/branches/release26-maint/Objects/enumobject.c Modified: python/branches/release26-maint/Objects/enumobject.c ============================================================================== --- python/branches/release26-maint/Objects/enumobject.c (original) +++ python/branches/release26-maint/Objects/enumobject.c Sat May 22 13:44:30 2010 @@ -159,12 +159,13 @@ } PyDoc_STRVAR(enum_doc, -"enumerate(iterable) -> iterator for index, value of iterable\n" +"enumerate(iterable[, start]) -> iterator for index, value of iterable\n" "\n" "Return an enumerate object. iterable must be another object that supports\n" "iteration. The enumerate object yields pairs containing a count (from\n" -"zero) and a value yielded by the iterable argument. enumerate is useful\n" -"for obtaining an indexed list: (0, seq[0]), (1, seq[1]), (2, seq[2]), ..."); +"start, which defaults to zero) and a value yielded by the iterable argument.\n" +"enumerate is useful for obtaining an indexed list:\n" +" (0, seq[0]), (1, seq[1]), (2, seq[2]), ..."); PyTypeObject PyEnum_Type = { PyVarObject_HEAD_INIT(&PyType_Type, 0) From python-checkins at python.org Sat May 22 14:02:35 2010 From: python-checkins at python.org (mark.dickinson) Date: Sat, 22 May 2010 14:02:35 +0200 (CEST) Subject: [Python-checkins] r81470 - python/branches/py3k/Objects/object.c Message-ID: <20100522120235.B3DA9EE983@mail.python.org> Author: mark.dickinson Date: Sat May 22 14:02:35 2010 New Revision: 81470 Log: Issue #8749: remove unused code in Objects/object.c. Thanks Yaniv Aknin. Modified: python/branches/py3k/Objects/object.c Modified: python/branches/py3k/Objects/object.c ============================================================================== --- python/branches/py3k/Objects/object.c (original) +++ python/branches/py3k/Objects/object.c Sat May 22 14:02:35 2010 @@ -950,31 +950,7 @@ goto done; } -#if 0 /* XXX this is not quite _PyType_Lookup anymore */ - /* Inline _PyType_Lookup */ - { - Py_ssize_t i, n; - PyObject *mro, *base, *dict; - - /* Look in tp_dict of types in MRO */ - mro = tp->tp_mro; - assert(mro != NULL); - assert(PyTuple_Check(mro)); - n = PyTuple_GET_SIZE(mro); - for (i = 0; i < n; i++) { - base = PyTuple_GET_ITEM(mro, i); - assert(PyType_Check(base)); - dict = ((PyTypeObject *)base)->tp_dict; - assert(dict && PyDict_Check(dict)); - descr = PyDict_GetItem(dict, name); - if (descr != NULL) - break; - } - } -#else descr = _PyType_Lookup(tp, name); -#endif - Py_XINCREF(descr); f = NULL; From python-checkins at python.org Sat May 22 15:37:57 2010 From: python-checkins at python.org (victor.stinner) Date: Sat, 22 May 2010 15:37:57 +0200 (CEST) Subject: [Python-checkins] r81471 - in python/trunk: Lib/codecs.py Lib/encodings/utf_16.py Lib/encodings/utf_32.py Lib/test/test_codecs.py Misc/NEWS Message-ID: <20100522133757.0C223EE982@mail.python.org> Author: victor.stinner Date: Sat May 22 15:37:56 2010 New Revision: 81471 Log: Issue #6268: More bugfixes about BOM, UTF-16 and UTF-32 * Fix seek() method of codecs.open(), don't write the BOM twice after seek(0) * Fix reset() method of codecs, UTF-16, UTF-32 and StreamWriter classes * test_codecs: use "w+" mode instead of "wt+". "t" mode is not supported by Solaris or Windows, but does it really exist? I found it the in the issue. Modified: python/trunk/Lib/codecs.py python/trunk/Lib/encodings/utf_16.py python/trunk/Lib/encodings/utf_32.py python/trunk/Lib/test/test_codecs.py python/trunk/Misc/NEWS Modified: python/trunk/Lib/codecs.py ============================================================================== --- python/trunk/Lib/codecs.py (original) +++ python/trunk/Lib/codecs.py Sat May 22 15:37:56 2010 @@ -370,6 +370,11 @@ """ pass + def seek(self, offset, whence=0): + self.stream.seek(offset, whence) + if whence == 0 and offset == 0: + self.reset() + def __getattr__(self, name, getattr=getattr): @@ -601,8 +606,8 @@ Resets the codec buffers used for keeping state. """ - self.reset() self.stream.seek(offset, whence) + self.reset() def next(self): @@ -695,8 +700,10 @@ self.writer.reset() def seek(self, offset, whence=0): - self.reader.seek(offset, whence) - self.writer.seek(offset, whence) + self.stream.seek(offset, whence) + self.reader.reset() + if whence == 0 and offset == 0: + self.writer.reset() def __getattr__(self, name, getattr=getattr): Modified: python/trunk/Lib/encodings/utf_16.py ============================================================================== --- python/trunk/Lib/encodings/utf_16.py (original) +++ python/trunk/Lib/encodings/utf_16.py Sat May 22 15:37:56 2010 @@ -58,17 +58,23 @@ class StreamWriter(codecs.StreamWriter): def __init__(self, stream, errors='strict'): - self.bom_written = False codecs.StreamWriter.__init__(self, stream, errors) + self.encoder = None + + def reset(self): + codecs.StreamWriter.reset(self) + self.encoder = None def encode(self, input, errors='strict'): - self.bom_written = True - result = codecs.utf_16_encode(input, errors) - if sys.byteorder == 'little': - self.encode = codecs.utf_16_le_encode + if self.encoder is None: + result = codecs.utf_16encoder(input, errors) + if sys.byteorder == 'little': + self.encoder = codecs.utf_16_leencoder + else: + self.encoder = codecs.utf_16_beencoder + return result else: - self.encode = codecs.utf_16_be_encode - return result + return self.encoder(input, errors) class StreamReader(codecs.StreamReader): Modified: python/trunk/Lib/encodings/utf_32.py ============================================================================== --- python/trunk/Lib/encodings/utf_32.py (original) +++ python/trunk/Lib/encodings/utf_32.py Sat May 22 15:37:56 2010 @@ -98,17 +98,23 @@ class StreamWriter(codecs.StreamWriter): def __init__(self, stream, errors='strict'): - self.bom_written = False + self.encoder = None codecs.StreamWriter.__init__(self, stream, errors) + def reset(self): + codecs.StreamWriter.reset(self) + self.encoder = None + def encode(self, input, errors='strict'): - self.bom_written = True - result = codecs.utf_32_encode(input, errors) - if sys.byteorder == 'little': - self.encode = codecs.utf_32_le_encode + if self.encoder is None: + result = codecs.utf_32encoder(input, errors) + if sys.byteorder == 'little': + self.encoder = codecs.utf_32_leencoder + else: + self.encoder = codecs.utf_32_beencoder + return result else: - self.encode = codecs.utf_32_be_encode - return result + return self.encoder(input, errors) class StreamReader(codecs.StreamReader): Modified: python/trunk/Lib/test/test_codecs.py ============================================================================== --- python/trunk/Lib/test/test_codecs.py (original) +++ python/trunk/Lib/test/test_codecs.py Sat May 22 15:37:56 2010 @@ -1498,7 +1498,7 @@ class BomTest(unittest.TestCase): def test_seek0(self): - data = "1234567890" + data = u"1234567890" tests = ("utf-16", "utf-16-le", "utf-16-be", @@ -1506,8 +1506,8 @@ "utf-32-le", "utf-32-be") for encoding in tests: - with codecs.open('foo', 'wt+', encoding=encoding) as f: - # Check if the BOM is written only once + # Check if the BOM is written only once + with codecs.open(test_support.TESTFN, 'w+', encoding=encoding) as f: f.write(data) f.write(data) f.seek(0) @@ -1515,6 +1515,42 @@ f.seek(0) self.assertEquals(f.read(), data * 2) + # Check that the BOM is written after a seek(0) + with codecs.open(test_support.TESTFN, 'w+', encoding=encoding) as f: + f.write(data[0]) + self.assertNotEquals(f.tell(), 0) + f.seek(0) + f.write(data) + f.seek(0) + self.assertEquals(f.read(), data) + + # (StreamWriter) Check that the BOM is written after a seek(0) + with codecs.open(test_support.TESTFN, 'w+', encoding=encoding) as f: + f.writer.write(data[0]) + self.assertNotEquals(f.writer.tell(), 0) + f.writer.seek(0) + f.writer.write(data) + f.seek(0) + self.assertEquals(f.read(), data) + + # Check that the BOM is not written after a seek() at a position + # different than the start + with codecs.open(test_support.TESTFN, 'w+', encoding=encoding) as f: + f.write(data) + f.seek(f.tell()) + f.write(data) + f.seek(0) + self.assertEquals(f.read(), data * 2) + + # (StreamWriter) Check that the BOM is not written after a seek() + # at a position different than the start + with codecs.open(test_support.TESTFN, 'w+', encoding=encoding) as f: + f.writer.write(data) + f.writer.seek(f.writer.tell()) + f.writer.write(data) + f.seek(0) + self.assertEquals(f.read(), data * 2) + def test_main(): test_support.run_unittest( Modified: python/trunk/Misc/NEWS ============================================================================== --- python/trunk/Misc/NEWS (original) +++ python/trunk/Misc/NEWS Sat May 22 15:37:56 2010 @@ -31,8 +31,9 @@ - Issue #3924: Ignore cookies with invalid "version" field in cookielib. -- Issue #6268: Fix seek() method of codecs.open(), don't read the BOM twice - after seek(0) +- Issue #6268: Fix seek() method of codecs.open(), don't read or write the BOM + twice after seek(0). Fix also reset() method of codecs, UTF-16, UTF-32 and + StreamWriter classes. - Issue #5640: Fix Shift-JIS incremental encoder for error handlers different than strict From python-checkins at python.org Sat May 22 15:44:25 2010 From: python-checkins at python.org (victor.stinner) Date: Sat, 22 May 2010 15:44:25 +0200 (CEST) Subject: [Python-checkins] r81472 - in python/trunk/Lib/encodings: utf_16.py utf_32.py Message-ID: <20100522134425.B9C9AEE983@mail.python.org> Author: victor.stinner Date: Sat May 22 15:44:25 2010 New Revision: 81472 Log: Fix my last commit (r81471) about codecs Rememder: don't touch the code just before a commit Modified: python/trunk/Lib/encodings/utf_16.py python/trunk/Lib/encodings/utf_32.py Modified: python/trunk/Lib/encodings/utf_16.py ============================================================================== --- python/trunk/Lib/encodings/utf_16.py (original) +++ python/trunk/Lib/encodings/utf_16.py Sat May 22 15:44:25 2010 @@ -67,11 +67,11 @@ def encode(self, input, errors='strict'): if self.encoder is None: - result = codecs.utf_16encoder(input, errors) + result = codecs.utf_16_encode(input, errors) if sys.byteorder == 'little': - self.encoder = codecs.utf_16_leencoder + self.encoder = codecs.utf_16_le_encode else: - self.encoder = codecs.utf_16_beencoder + self.encoder = codecs.utf_16_be_encode return result else: return self.encoder(input, errors) Modified: python/trunk/Lib/encodings/utf_32.py ============================================================================== --- python/trunk/Lib/encodings/utf_32.py (original) +++ python/trunk/Lib/encodings/utf_32.py Sat May 22 15:44:25 2010 @@ -107,11 +107,11 @@ def encode(self, input, errors='strict'): if self.encoder is None: - result = codecs.utf_32encoder(input, errors) + result = codecs.utf_32_encode(input, errors) if sys.byteorder == 'little': - self.encoder = codecs.utf_32_leencoder + self.encoder = codecs.utf_32_le_encode else: - self.encoder = codecs.utf_32_beencoder + self.encoder = codecs.utf_32_be_encode return result else: return self.encoder(input, errors) From python-checkins at python.org Sat May 22 18:52:13 2010 From: python-checkins at python.org (victor.stinner) Date: Sat, 22 May 2010 18:52:13 +0200 (CEST) Subject: [Python-checkins] r81473 - in python/branches/release26-maint: Lib/codecs.py Lib/encodings/utf_16.py Lib/encodings/utf_32.py Lib/test/test_codecs.py Misc/NEWS Message-ID: <20100522165213.82DD4EE988@mail.python.org> Author: victor.stinner Date: Sat May 22 18:52:13 2010 New Revision: 81473 Log: Merged revisions 81471-81472 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r81471 | victor.stinner | 2010-05-22 15:37:56 +0200 (sam., 22 mai 2010) | 7 lines Issue #6268: More bugfixes about BOM, UTF-16 and UTF-32 * Fix seek() method of codecs.open(), don't write the BOM twice after seek(0) * Fix reset() method of codecs, UTF-16, UTF-32 and StreamWriter classes * test_codecs: use "w+" mode instead of "wt+". "t" mode is not supported by Solaris or Windows, but does it really exist? I found it the in the issue. ........ r81472 | victor.stinner | 2010-05-22 15:44:25 +0200 (sam., 22 mai 2010) | 4 lines Fix my last commit (r81471) about codecs Rememder: don't touch the code just before a commit ........ Modified: python/branches/release26-maint/ (props changed) python/branches/release26-maint/Lib/codecs.py python/branches/release26-maint/Lib/encodings/utf_16.py python/branches/release26-maint/Lib/encodings/utf_32.py python/branches/release26-maint/Lib/test/test_codecs.py python/branches/release26-maint/Misc/NEWS Modified: python/branches/release26-maint/Lib/codecs.py ============================================================================== --- python/branches/release26-maint/Lib/codecs.py (original) +++ python/branches/release26-maint/Lib/codecs.py Sat May 22 18:52:13 2010 @@ -370,6 +370,11 @@ """ pass + def seek(self, offset, whence=0): + self.stream.seek(offset, whence) + if whence == 0 and offset == 0: + self.reset() + def __getattr__(self, name, getattr=getattr): @@ -601,8 +606,8 @@ Resets the codec buffers used for keeping state. """ - self.reset() self.stream.seek(offset, whence) + self.reset() def next(self): @@ -695,8 +700,10 @@ self.writer.reset() def seek(self, offset, whence=0): - self.reader.seek(offset, whence) - self.writer.seek(offset, whence) + self.stream.seek(offset, whence) + self.reader.reset() + if whence == 0 and offset == 0: + self.writer.reset() def __getattr__(self, name, getattr=getattr): Modified: python/branches/release26-maint/Lib/encodings/utf_16.py ============================================================================== --- python/branches/release26-maint/Lib/encodings/utf_16.py (original) +++ python/branches/release26-maint/Lib/encodings/utf_16.py Sat May 22 18:52:13 2010 @@ -58,17 +58,23 @@ class StreamWriter(codecs.StreamWriter): def __init__(self, stream, errors='strict'): - self.bom_written = False codecs.StreamWriter.__init__(self, stream, errors) + self.encoder = None + + def reset(self): + codecs.StreamWriter.reset(self) + self.encoder = None def encode(self, input, errors='strict'): - self.bom_written = True - result = codecs.utf_16_encode(input, errors) - if sys.byteorder == 'little': - self.encode = codecs.utf_16_le_encode + if self.encoder is None: + result = codecs.utf_16_encode(input, errors) + if sys.byteorder == 'little': + self.encoder = codecs.utf_16_le_encode + else: + self.encoder = codecs.utf_16_be_encode + return result else: - self.encode = codecs.utf_16_be_encode - return result + return self.encoder(input, errors) class StreamReader(codecs.StreamReader): Modified: python/branches/release26-maint/Lib/encodings/utf_32.py ============================================================================== --- python/branches/release26-maint/Lib/encodings/utf_32.py (original) +++ python/branches/release26-maint/Lib/encodings/utf_32.py Sat May 22 18:52:13 2010 @@ -98,17 +98,23 @@ class StreamWriter(codecs.StreamWriter): def __init__(self, stream, errors='strict'): - self.bom_written = False + self.encoder = None codecs.StreamWriter.__init__(self, stream, errors) + def reset(self): + codecs.StreamWriter.reset(self) + self.encoder = None + def encode(self, input, errors='strict'): - self.bom_written = True - result = codecs.utf_32_encode(input, errors) - if sys.byteorder == 'little': - self.encode = codecs.utf_32_le_encode + if self.encoder is None: + result = codecs.utf_32_encode(input, errors) + if sys.byteorder == 'little': + self.encoder = codecs.utf_32_le_encode + else: + self.encoder = codecs.utf_32_be_encode + return result else: - self.encode = codecs.utf_32_be_encode - return result + return self.encoder(input, errors) class StreamReader(codecs.StreamReader): Modified: python/branches/release26-maint/Lib/test/test_codecs.py ============================================================================== --- python/branches/release26-maint/Lib/test/test_codecs.py (original) +++ python/branches/release26-maint/Lib/test/test_codecs.py Sat May 22 18:52:13 2010 @@ -1490,7 +1490,7 @@ class BomTest(unittest.TestCase): def test_seek0(self): - data = "1234567890" + data = u"1234567890" tests = ("utf-16", "utf-16-le", "utf-16-be", @@ -1498,8 +1498,8 @@ "utf-32-le", "utf-32-be") for encoding in tests: - with codecs.open('foo', 'wt+', encoding=encoding) as f: - # Check if the BOM is written only once + # Check if the BOM is written only once + with codecs.open(test_support.TESTFN, 'w+', encoding=encoding) as f: f.write(data) f.write(data) f.seek(0) @@ -1507,6 +1507,42 @@ f.seek(0) self.assertEquals(f.read(), data * 2) + # Check that the BOM is written after a seek(0) + with codecs.open(test_support.TESTFN, 'w+', encoding=encoding) as f: + f.write(data[0]) + self.assertNotEquals(f.tell(), 0) + f.seek(0) + f.write(data) + f.seek(0) + self.assertEquals(f.read(), data) + + # (StreamWriter) Check that the BOM is written after a seek(0) + with codecs.open(test_support.TESTFN, 'w+', encoding=encoding) as f: + f.writer.write(data[0]) + self.assertNotEquals(f.writer.tell(), 0) + f.writer.seek(0) + f.writer.write(data) + f.seek(0) + self.assertEquals(f.read(), data) + + # Check that the BOM is not written after a seek() at a position + # different than the start + with codecs.open(test_support.TESTFN, 'w+', encoding=encoding) as f: + f.write(data) + f.seek(f.tell()) + f.write(data) + f.seek(0) + self.assertEquals(f.read(), data * 2) + + # (StreamWriter) Check that the BOM is not written after a seek() + # at a position different than the start + with codecs.open(test_support.TESTFN, 'w+', encoding=encoding) as f: + f.writer.write(data) + f.writer.seek(f.writer.tell()) + f.writer.write(data) + f.seek(0) + self.assertEquals(f.read(), data * 2) + def test_main(): test_support.run_unittest( Modified: python/branches/release26-maint/Misc/NEWS ============================================================================== --- python/branches/release26-maint/Misc/NEWS (original) +++ python/branches/release26-maint/Misc/NEWS Sat May 22 18:52:13 2010 @@ -57,8 +57,9 @@ - Issue #3924: Ignore cookies with invalid "version" field in cookielib. -- Issue #6268: Fix seek() method of codecs.open(), don't read the BOM twice - after seek(0) +- Issue #6268: Fix seek() method of codecs.open(), don't read or write the BOM + twice after seek(0). Fix also reset() method of codecs, UTF-16, UTF-32 and + StreamWriter classes. - Issue #5640: Fix Shift-JIS incremental encoder for error handlers different than strict From python-checkins at python.org Sat May 22 18:59:09 2010 From: python-checkins at python.org (victor.stinner) Date: Sat, 22 May 2010 18:59:09 +0200 (CEST) Subject: [Python-checkins] r81474 - in python/branches/py3k: Lib/codecs.py Lib/encodings/utf_16.py Lib/encodings/utf_32.py Lib/test/test_codecs.py Misc/NEWS Message-ID: <20100522165909.71099EE9BB@mail.python.org> Author: victor.stinner Date: Sat May 22 18:59:09 2010 New Revision: 81474 Log: Merged revisions 81471-81472 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r81471 | victor.stinner | 2010-05-22 15:37:56 +0200 (sam., 22 mai 2010) | 7 lines Issue #6268: More bugfixes about BOM, UTF-16 and UTF-32 * Fix seek() method of codecs.open(), don't write the BOM twice after seek(0) * Fix reset() method of codecs, UTF-16, UTF-32 and StreamWriter classes * test_codecs: use "w+" mode instead of "wt+". "t" mode is not supported by Solaris or Windows, but does it really exist? I found it the in the issue. ........ r81472 | victor.stinner | 2010-05-22 15:44:25 +0200 (sam., 22 mai 2010) | 4 lines Fix my last commit (r81471) about codecs Rememder: don't touch the code just before a commit ........ Modified: python/branches/py3k/ (props changed) python/branches/py3k/Lib/codecs.py python/branches/py3k/Lib/encodings/utf_16.py python/branches/py3k/Lib/encodings/utf_32.py python/branches/py3k/Lib/test/test_codecs.py python/branches/py3k/Misc/NEWS Modified: python/branches/py3k/Lib/codecs.py ============================================================================== --- python/branches/py3k/Lib/codecs.py (original) +++ python/branches/py3k/Lib/codecs.py Sat May 22 18:59:09 2010 @@ -374,6 +374,11 @@ """ pass + def seek(self, offset, whence=0): + self.stream.seek(offset, whence) + if whence == 0 and offset == 0: + self.reset() + def __getattr__(self, name, getattr=getattr): @@ -606,8 +611,8 @@ Resets the codec buffers used for keeping state. """ - self.reset() self.stream.seek(offset, whence) + self.reset() def __next__(self): @@ -700,8 +705,10 @@ self.writer.reset() def seek(self, offset, whence=0): - self.reader.seek(offset, whence) - self.writer.seek(offset, whence) + self.stream.seek(offset, whence) + self.reader.reset() + if whence == 0 and offset == 0: + self.writer.reset() def __getattr__(self, name, getattr=getattr): Modified: python/branches/py3k/Lib/encodings/utf_16.py ============================================================================== --- python/branches/py3k/Lib/encodings/utf_16.py (original) +++ python/branches/py3k/Lib/encodings/utf_16.py Sat May 22 18:59:09 2010 @@ -103,17 +103,23 @@ class StreamWriter(codecs.StreamWriter): def __init__(self, stream, errors='strict'): - self.bom_written = False codecs.StreamWriter.__init__(self, stream, errors) + self.encoder = None + + def reset(self): + codecs.StreamWriter.reset(self) + self.encoder = None def encode(self, input, errors='strict'): - self.bom_written = True - result = codecs.utf_16_encode(input, errors) - if sys.byteorder == 'little': - self.encode = codecs.utf_16_le_encode + if self.encoder is None: + result = codecs.utf_16_encode(input, errors) + if sys.byteorder == 'little': + self.encoder = codecs.utf_16_le_encode + else: + self.encoder = codecs.utf_16_be_encode + return result else: - self.encode = codecs.utf_16_be_encode - return result + return self.encoder(input, errors) class StreamReader(codecs.StreamReader): Modified: python/branches/py3k/Lib/encodings/utf_32.py ============================================================================== --- python/branches/py3k/Lib/encodings/utf_32.py (original) +++ python/branches/py3k/Lib/encodings/utf_32.py Sat May 22 18:59:09 2010 @@ -98,17 +98,23 @@ class StreamWriter(codecs.StreamWriter): def __init__(self, stream, errors='strict'): - self.bom_written = False + self.encoder = None codecs.StreamWriter.__init__(self, stream, errors) + def reset(self): + codecs.StreamWriter.reset(self) + self.encoder = None + def encode(self, input, errors='strict'): - self.bom_written = True - result = codecs.utf_32_encode(input, errors) - if sys.byteorder == 'little': - self.encode = codecs.utf_32_le_encode + if self.encoder is None: + result = codecs.utf_32_encode(input, errors) + if sys.byteorder == 'little': + self.encoder = codecs.utf_32_le_encode + else: + self.encoder = codecs.utf_32_be_encode + return result else: - self.encode = codecs.utf_32_be_encode - return result + return self.encoder(input, errors) class StreamReader(codecs.StreamReader): Modified: python/branches/py3k/Lib/test/test_codecs.py ============================================================================== --- python/branches/py3k/Lib/test/test_codecs.py (original) +++ python/branches/py3k/Lib/test/test_codecs.py Sat May 22 18:59:09 2010 @@ -1604,8 +1604,8 @@ "utf-32-le", "utf-32-be") for encoding in tests: - with codecs.open('foo', 'w+', encoding=encoding) as f: - # Check if the BOM is written only once + # Check if the BOM is written only once + with codecs.open(support.TESTFN, 'w+', encoding=encoding) as f: f.write(data) f.write(data) f.seek(0) @@ -1613,6 +1613,42 @@ f.seek(0) self.assertEquals(f.read(), data * 2) + # Check that the BOM is written after a seek(0) + with codecs.open(support.TESTFN, 'w+', encoding=encoding) as f: + f.write(data[0]) + self.assertNotEquals(f.tell(), 0) + f.seek(0) + f.write(data) + f.seek(0) + self.assertEquals(f.read(), data) + + # (StreamWriter) Check that the BOM is written after a seek(0) + with codecs.open(support.TESTFN, 'w+', encoding=encoding) as f: + f.writer.write(data[0]) + self.assertNotEquals(f.writer.tell(), 0) + f.writer.seek(0) + f.writer.write(data) + f.seek(0) + self.assertEquals(f.read(), data) + + # Check that the BOM is not written after a seek() at a position + # different than the start + with codecs.open(support.TESTFN, 'w+', encoding=encoding) as f: + f.write(data) + f.seek(f.tell()) + f.write(data) + f.seek(0) + self.assertEquals(f.read(), data * 2) + + # (StreamWriter) Check that the BOM is not written after a seek() + # at a position different than the start + with codecs.open(support.TESTFN, 'w+', encoding=encoding) as f: + f.writer.write(data) + f.writer.seek(f.writer.tell()) + f.writer.write(data) + f.seek(0) + self.assertEquals(f.read(), data * 2) + def test_main(): support.run_unittest( Modified: python/branches/py3k/Misc/NEWS ============================================================================== --- python/branches/py3k/Misc/NEWS (original) +++ python/branches/py3k/Misc/NEWS Sat May 22 18:59:09 2010 @@ -393,8 +393,9 @@ Library ------- -- Issue #6268: Fix seek() method of codecs.open(), don't read the BOM twice - after seek(0) +- Issue #6268: Fix seek() method of codecs.open(), don't read or write the BOM + twice after seek(0). Fix also reset() method of codecs, UTF-16, UTF-32 and + StreamWriter classes. - Issue #3798: sys.exit(message) writes the message to sys.stderr file, instead of the C file stderr, to use stderr encoding and error handler From python-checkins at python.org Sat May 22 19:01:13 2010 From: python-checkins at python.org (victor.stinner) Date: Sat, 22 May 2010 19:01:13 +0200 (CEST) Subject: [Python-checkins] r81475 - in python/branches/release31-maint: Lib/codecs.py Lib/encodings/utf_16.py Lib/encodings/utf_32.py Lib/test/test_codecs.py Misc/NEWS Message-ID: <20100522170113.8306AEE9D3@mail.python.org> Author: victor.stinner Date: Sat May 22 19:01:13 2010 New Revision: 81475 Log: Merged revisions 81474 via svnmerge from svn+ssh://pythondev at svn.python.org/python/branches/py3k ................ r81474 | victor.stinner | 2010-05-22 18:59:09 +0200 (sam., 22 mai 2010) | 20 lines Merged revisions 81471-81472 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r81471 | victor.stinner | 2010-05-22 15:37:56 +0200 (sam., 22 mai 2010) | 7 lines Issue #6268: More bugfixes about BOM, UTF-16 and UTF-32 * Fix seek() method of codecs.open(), don't write the BOM twice after seek(0) * Fix reset() method of codecs, UTF-16, UTF-32 and StreamWriter classes * test_codecs: use "w+" mode instead of "wt+". "t" mode is not supported by Solaris or Windows, but does it really exist? I found it the in the issue. ........ r81472 | victor.stinner | 2010-05-22 15:44:25 +0200 (sam., 22 mai 2010) | 4 lines Fix my last commit (r81471) about codecs Rememder: don't touch the code just before a commit ........ ................ Modified: python/branches/release31-maint/ (props changed) python/branches/release31-maint/Lib/codecs.py python/branches/release31-maint/Lib/encodings/utf_16.py python/branches/release31-maint/Lib/encodings/utf_32.py python/branches/release31-maint/Lib/test/test_codecs.py python/branches/release31-maint/Misc/NEWS Modified: python/branches/release31-maint/Lib/codecs.py ============================================================================== --- python/branches/release31-maint/Lib/codecs.py (original) +++ python/branches/release31-maint/Lib/codecs.py Sat May 22 19:01:13 2010 @@ -374,6 +374,11 @@ """ pass + def seek(self, offset, whence=0): + self.stream.seek(offset, whence) + if whence == 0 and offset == 0: + self.reset() + def __getattr__(self, name, getattr=getattr): @@ -606,8 +611,8 @@ Resets the codec buffers used for keeping state. """ - self.reset() self.stream.seek(offset, whence) + self.reset() def __next__(self): @@ -700,8 +705,10 @@ self.writer.reset() def seek(self, offset, whence=0): - self.reader.seek(offset, whence) - self.writer.seek(offset, whence) + self.stream.seek(offset, whence) + self.reader.reset() + if whence == 0 and offset == 0: + self.writer.reset() def __getattr__(self, name, getattr=getattr): Modified: python/branches/release31-maint/Lib/encodings/utf_16.py ============================================================================== --- python/branches/release31-maint/Lib/encodings/utf_16.py (original) +++ python/branches/release31-maint/Lib/encodings/utf_16.py Sat May 22 19:01:13 2010 @@ -103,17 +103,23 @@ class StreamWriter(codecs.StreamWriter): def __init__(self, stream, errors='strict'): - self.bom_written = False codecs.StreamWriter.__init__(self, stream, errors) + self.encoder = None + + def reset(self): + codecs.StreamWriter.reset(self) + self.encoder = None def encode(self, input, errors='strict'): - self.bom_written = True - result = codecs.utf_16_encode(input, errors) - if sys.byteorder == 'little': - self.encode = codecs.utf_16_le_encode + if self.encoder is None: + result = codecs.utf_16_encode(input, errors) + if sys.byteorder == 'little': + self.encoder = codecs.utf_16_le_encode + else: + self.encoder = codecs.utf_16_be_encode + return result else: - self.encode = codecs.utf_16_be_encode - return result + return self.encoder(input, errors) class StreamReader(codecs.StreamReader): Modified: python/branches/release31-maint/Lib/encodings/utf_32.py ============================================================================== --- python/branches/release31-maint/Lib/encodings/utf_32.py (original) +++ python/branches/release31-maint/Lib/encodings/utf_32.py Sat May 22 19:01:13 2010 @@ -98,17 +98,23 @@ class StreamWriter(codecs.StreamWriter): def __init__(self, stream, errors='strict'): - self.bom_written = False + self.encoder = None codecs.StreamWriter.__init__(self, stream, errors) + def reset(self): + codecs.StreamWriter.reset(self) + self.encoder = None + def encode(self, input, errors='strict'): - self.bom_written = True - result = codecs.utf_32_encode(input, errors) - if sys.byteorder == 'little': - self.encode = codecs.utf_32_le_encode + if self.encoder is None: + result = codecs.utf_32_encode(input, errors) + if sys.byteorder == 'little': + self.encoder = codecs.utf_32_le_encode + else: + self.encoder = codecs.utf_32_be_encode + return result else: - self.encode = codecs.utf_32_be_encode - return result + return self.encoder(input, errors) class StreamReader(codecs.StreamReader): Modified: python/branches/release31-maint/Lib/test/test_codecs.py ============================================================================== --- python/branches/release31-maint/Lib/test/test_codecs.py (original) +++ python/branches/release31-maint/Lib/test/test_codecs.py Sat May 22 19:01:13 2010 @@ -1602,8 +1602,8 @@ "utf-32-le", "utf-32-be") for encoding in tests: - with codecs.open('foo', 'w+', encoding=encoding) as f: - # Check if the BOM is written only once + # Check if the BOM is written only once + with codecs.open(support.TESTFN, 'w+', encoding=encoding) as f: f.write(data) f.write(data) f.seek(0) @@ -1611,6 +1611,42 @@ f.seek(0) self.assertEquals(f.read(), data * 2) + # Check that the BOM is written after a seek(0) + with codecs.open(support.TESTFN, 'w+', encoding=encoding) as f: + f.write(data[0]) + self.assertNotEquals(f.tell(), 0) + f.seek(0) + f.write(data) + f.seek(0) + self.assertEquals(f.read(), data) + + # (StreamWriter) Check that the BOM is written after a seek(0) + with codecs.open(support.TESTFN, 'w+', encoding=encoding) as f: + f.writer.write(data[0]) + self.assertNotEquals(f.writer.tell(), 0) + f.writer.seek(0) + f.writer.write(data) + f.seek(0) + self.assertEquals(f.read(), data) + + # Check that the BOM is not written after a seek() at a position + # different than the start + with codecs.open(support.TESTFN, 'w+', encoding=encoding) as f: + f.write(data) + f.seek(f.tell()) + f.write(data) + f.seek(0) + self.assertEquals(f.read(), data * 2) + + # (StreamWriter) Check that the BOM is not written after a seek() + # at a position different than the start + with codecs.open(support.TESTFN, 'w+', encoding=encoding) as f: + f.writer.write(data) + f.writer.seek(f.writer.tell()) + f.writer.write(data) + f.seek(0) + self.assertEquals(f.read(), data * 2) + def test_main(): support.run_unittest( Modified: python/branches/release31-maint/Misc/NEWS ============================================================================== --- python/branches/release31-maint/Misc/NEWS (original) +++ python/branches/release31-maint/Misc/NEWS Sat May 22 19:01:13 2010 @@ -54,8 +54,9 @@ Library ------- -- Issue #6268: Fix seek() method of codecs.open(), don't read the BOM twice - after seek(0) +- Issue #6268: Fix seek() method of codecs.open(), don't read or write the BOM + twice after seek(0). Fix also reset() method of codecs, UTF-16, UTF-32 and + StreamWriter classes. - Issue #8782: Add a trailing newline in linecache.updatecache to the last line of files without one. From python-checkins at python.org Sat May 22 20:35:36 2010 From: python-checkins at python.org (mark.dickinson) Date: Sat, 22 May 2010 20:35:36 +0200 (CEST) Subject: [Python-checkins] r81476 - in python/branches/py3k: Doc/library/decimal.rst Lib/decimal.py Lib/test/test_decimal.py Misc/NEWS Message-ID: <20100522183536.87730EE99A@mail.python.org> Author: mark.dickinson Date: Sat May 22 20:35:36 2010 New Revision: 81476 Log: #Issue 8540: Make Context._clamp attribute public in decimal module. Modified: python/branches/py3k/Doc/library/decimal.rst python/branches/py3k/Lib/decimal.py python/branches/py3k/Lib/test/test_decimal.py python/branches/py3k/Misc/NEWS Modified: python/branches/py3k/Doc/library/decimal.rst ============================================================================== --- python/branches/py3k/Doc/library/decimal.rst (original) +++ python/branches/py3k/Doc/library/decimal.rst Sat May 22 20:35:36 2010 @@ -122,7 +122,7 @@ >>> from decimal import * >>> getcontext() Context(prec=28, rounding=ROUND_HALF_EVEN, Emin=-999999999, Emax=999999999, - capitals=1, flags=[], traps=[Overflow, DivisionByZero, + capitals=1, clamp=0, flags=[], traps=[Overflow, DivisionByZero, InvalidOperation]) >>> getcontext().prec = 7 # Set a new precision @@ -244,7 +244,7 @@ >>> ExtendedContext Context(prec=9, rounding=ROUND_HALF_EVEN, Emin=-999999999, Emax=999999999, - capitals=1, flags=[], traps=[]) + capitals=1, clamp=0, flags=[], traps=[]) >>> setcontext(ExtendedContext) >>> Decimal(1) / Decimal(7) Decimal('0.142857143') @@ -269,7 +269,7 @@ Decimal('3.14159292') >>> getcontext() Context(prec=9, rounding=ROUND_HALF_EVEN, Emin=-999999999, Emax=999999999, - capitals=1, flags=[Inexact, Rounded], traps=[]) + capitals=1, clamp=0, flags=[Inexact, Rounded], traps=[]) The *flags* entry shows that the rational approximation to :const:`Pi` was rounded (digits beyond the context precision were thrown away) and that the @@ -891,7 +891,7 @@ :class:`Context` constructor. -.. class:: Context(prec=None, rounding=None, traps=None, flags=None, Emin=None, Emax=None, capitals=1) +.. class:: Context(prec=None, rounding=None, traps=None, flags=None, Emin=None, Emax=None, capitals=None, clamp=None) Creates a new context. If a field is not specified or is :const:`None`, the default values are copied from the :const:`DefaultContext`. If the *flags* @@ -922,6 +922,23 @@ :const:`1`, exponents are printed with a capital :const:`E`; otherwise, a lowercase :const:`e` is used: :const:`Decimal('6.02e+23')`. + The *clamp* field is either :const:`0` (the default) or :const:`1`. + If set to :const:`1`, the exponent ``e`` of a :class:`Decimal` + instance representable in this context is strictly limited to the + range ``Emin - prec + 1 <= e <= Emax - prec + 1``. If *clamp* is + :const:`0` then a weaker condition holds: the adjusted exponent of + the :class:`Decimal` instance is at most ``Emax``. When *clamp* is + :const:`1`, a large normal number will, where possible, have its + exponent reduced and a corresponding number of zeros added to its + coefficient, in order to fit the exponent constraints; this + preserves the value of the number but loses information about + significant trailing zeros. For example:: + + >>> Context(prec=6, Emax=999, clamp=1).create_decimal('1.23e999') + Decimal('1.23000E+999') + + A *clamp* value of :const:`1` allows compatibility with the + fixed-width decimal interchange formats specified in IEEE 754. The :class:`Context` class defines several general purpose methods as well as a large number of methods for doing arithmetic directly in a given context. Modified: python/branches/py3k/Lib/decimal.py ============================================================================== --- python/branches/py3k/Lib/decimal.py (original) +++ python/branches/py3k/Lib/decimal.py Sat May 22 20:35:36 2010 @@ -1611,9 +1611,9 @@ """Decapitate the payload of a NaN to fit the context""" payload = self._int - # maximum length of payload is precision if _clamp=0, - # precision-1 if _clamp=1. - max_payload_len = context.prec - context._clamp + # maximum length of payload is precision if clamp=0, + # precision-1 if clamp=1. + max_payload_len = context.prec - context.clamp if len(payload) > max_payload_len: payload = payload[len(payload)-max_payload_len:].lstrip('0') return _dec_from_triple(self._sign, payload, self._exp, True) @@ -1638,11 +1638,11 @@ return Decimal(self) # if self is zero then exponent should be between Etiny and - # Emax if _clamp==0, and between Etiny and Etop if _clamp==1. + # Emax if clamp==0, and between Etiny and Etop if clamp==1. Etiny = context.Etiny() Etop = context.Etop() if not self: - exp_max = [context.Emax, Etop][context._clamp] + exp_max = [context.Emax, Etop][context.clamp] new_exp = min(max(self._exp, Etiny), exp_max) if new_exp != self._exp: context._raise_error(Clamped) @@ -1702,8 +1702,8 @@ if self_is_subnormal: context._raise_error(Subnormal) - # fold down if _clamp == 1 and self has too few digits - if context._clamp == 1 and self._exp > Etop: + # fold down if clamp == 1 and self has too few digits + if context.clamp == 1 and self._exp > Etop: context._raise_error(Clamped) self_padded = self._int + '0'*(self._exp - Etop) return _dec_from_triple(self._sign, self_padded, Etop) @@ -2451,7 +2451,7 @@ if not dup: return _dec_from_triple(dup._sign, '0', 0) - exp_max = [context.Emax, context.Etop()][context._clamp] + exp_max = [context.Emax, context.Etop()][context.clamp] end = len(dup._int) exp = dup._exp while dup._int[end-1] == '0' and exp < exp_max: @@ -3828,13 +3828,13 @@ Emax - Maximum exponent capitals - If 1, 1*10^1 is printed as 1E+1. If 0, printed as 1e1 - _clamp - If 1, change exponents if too high (Default 0) + clamp - If 1, change exponents if too high (Default 0) """ def __init__(self, prec=None, rounding=None, traps=None, flags=None, Emin=None, Emax=None, - capitals=None, _clamp=0, + capitals=None, clamp=None, _ignored_flags=None): if flags is None: flags = [] @@ -3855,7 +3855,8 @@ """Show the current context.""" s = [] s.append('Context(prec=%(prec)d, rounding=%(rounding)s, ' - 'Emin=%(Emin)d, Emax=%(Emax)d, capitals=%(capitals)d' + 'Emin=%(Emin)d, Emax=%(Emax)d, capitals=%(capitals)d, ' + 'clamp=%(clamp)d' % vars(self)) names = [f.__name__ for f, v in self.flags.items() if v] s.append('flags=[' + ', '.join(names) + ']') @@ -3872,17 +3873,39 @@ """Returns a shallow copy from self.""" nc = Context(self.prec, self.rounding, self.traps, self.flags, self.Emin, self.Emax, - self.capitals, self._clamp, self._ignored_flags) + self.capitals, self.clamp, self._ignored_flags) return nc def copy(self): """Returns a deep copy from self.""" nc = Context(self.prec, self.rounding, self.traps.copy(), self.flags.copy(), self.Emin, self.Emax, - self.capitals, self._clamp, self._ignored_flags) + self.capitals, self.clamp, self._ignored_flags) return nc __copy__ = copy + # _clamp is provided for backwards compatibility with third-party + # code. May be removed in Python >= 3.3. + def _get_clamp(self): + "_clamp mirrors the clamp attribute. Its use is deprecated." + import warnings + warnings.warn('Use of the _clamp attribute is deprecated. ' + 'Please use clamp instead.', + DeprecationWarning) + return self.clamp + + def _set_clamp(self, clamp): + "_clamp mirrors the clamp attribute. Its use is deprecated." + import warnings + warnings.warn('Use of the _clamp attribute is deprecated. ' + 'Please use clamp instead.', + DeprecationWarning) + self.clamp = clamp + + # don't bother with _del_clamp; no sane 3rd party code should + # be deleting the _clamp attribute + _clamp = property(_get_clamp, _set_clamp) + def _raise_error(self, condition, explanation = None, *args): """Handles an error @@ -3965,7 +3988,7 @@ "permitted.") d = Decimal(num, context=self) - if d._isnan() and len(d._int) > self.prec - self._clamp: + if d._isnan() and len(d._int) > self.prec - self.clamp: return self._raise_error(ConversionSyntax, "diagnostic info too long in NaN") return d._fix(self) @@ -5875,7 +5898,8 @@ flags=[], Emax=999999999, Emin=-999999999, - capitals=1 + capitals=1, + clamp=0 ) # Pre-made alternate contexts offered by the specification Modified: python/branches/py3k/Lib/test/test_decimal.py ============================================================================== --- python/branches/py3k/Lib/test/test_decimal.py (original) +++ python/branches/py3k/Lib/test/test_decimal.py Sat May 22 20:35:36 2010 @@ -27,11 +27,13 @@ import math import os, sys import operator +import warnings import pickle, copy import unittest from decimal import * import numbers from test.support import run_unittest, run_doctest, is_resource_enabled +from test.support import check_warnings import random try: import threading @@ -412,7 +414,7 @@ def change_max_exponent(self, exp): self.context.Emax = exp def change_clamp(self, clamp): - self.context._clamp = clamp + self.context.clamp = clamp @@ -1815,6 +1817,26 @@ self.assertNotEqual(id(c.flags), id(d.flags)) self.assertNotEqual(id(c.traps), id(d.traps)) + def test__clamp(self): + # In Python 3.2, the private attribute `_clamp` was made + # public (issue 8540), with the old `_clamp` becoming a + # property wrapping `clamp`. For the duration of Python 3.2 + # only, the attribute should be gettable/settable via both + # `clamp` and `_clamp`; in Python 3.3, `_clamp` should be + # removed. + c = Context(clamp = 0) + self.assertEqual(c.clamp, 0) + + with check_warnings(("", DeprecationWarning)): + c._clamp = 1 + self.assertEqual(c.clamp, 1) + with check_warnings(("", DeprecationWarning)): + self.assertEqual(c._clamp, 1) + c.clamp = 0 + self.assertEqual(c.clamp, 0) + with check_warnings(("", DeprecationWarning)): + self.assertEqual(c._clamp, 0) + def test_abs(self): c = Context() d = c.abs(Decimal(-1)) Modified: python/branches/py3k/Misc/NEWS ============================================================================== --- python/branches/py3k/Misc/NEWS (original) +++ python/branches/py3k/Misc/NEWS Sat May 22 20:35:36 2010 @@ -393,6 +393,11 @@ Library ------- +- Issue #8540: Decimal module: rename the Context._clamp attribute to + Context.clamp and make it public. This is useful in creating + contexts that correspond to the decimal interchange formats + specified in IEEE 754. + - Issue #6268: Fix seek() method of codecs.open(), don't read or write the BOM twice after seek(0). Fix also reset() method of codecs, UTF-16, UTF-32 and StreamWriter classes. From python-checkins at python.org Sat May 22 20:47:23 2010 From: python-checkins at python.org (mark.dickinson) Date: Sat, 22 May 2010 20:47:23 +0200 (CEST) Subject: [Python-checkins] r81477 - in python/branches/release26-maint: Doc/library/struct.rst Message-ID: <20100522184723.DFE25EE991@mail.python.org> Author: mark.dickinson Date: Sat May 22 20:47:23 2010 New Revision: 81477 Log: Merged revisions 80013-80015 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r80013 | mark.dickinson | 2010-04-12 20:25:32 +0100 (Mon, 12 Apr 2010) | 14 lines Issue #7355: Various improvements to struct module documentation. - note early on that the result of struct.pack includes padding bytes by default - add examples showing how order of struct fields can affect size (due to padding) - better headers and references; introduction to format strings - integrate packing notes into table Many thanks to Meador Inge for the patch. ........ r80014 | mark.dickinson | 2010-04-12 20:46:20 +0100 (Mon, 12 Apr 2010) | 1 line Rewrap some long lines in struct module doc source. ........ r80015 | mark.dickinson | 2010-04-12 21:38:36 +0100 (Mon, 12 Apr 2010) | 1 line More struct doc tweaks. ........ Modified: python/branches/release26-maint/ (props changed) python/branches/release26-maint/Doc/library/struct.rst Modified: python/branches/release26-maint/Doc/library/struct.rst ============================================================================== --- python/branches/release26-maint/Doc/library/struct.rst (original) +++ python/branches/release26-maint/Doc/library/struct.rst Sat May 22 20:47:23 2010 @@ -10,18 +10,31 @@ triple: packing; binary; data This module performs conversions between Python values and C structs represented -as Python strings. It uses :dfn:`format strings` (explained below) as compact -descriptions of the lay-out of the C structs and the intended conversion to/from -Python values. This can be used in handling binary data stored in files or from -network connections, among other sources. +as Python strings. This can be used in handling binary data stored in files or +from network connections, among other sources. It uses +:ref:`struct-format-strings` as compact descriptions of the layout of the C +structs and the intended conversion to/from Python values. + +.. note:: + + By default, the result of packing a given C struct includes pad bytes in + order to maintain proper alignment for the C types involved; similarly, + alignment is taken into account when unpacking. This behavior is chosen so + that the bytes of a packed struct correspond exactly to the layout in memory + of the corresponding C struct. To omit pad bytes, use `standard` size and + alignment instead of `native` size and alignment: see :ref:`struct-alignment` + for details. + +Functions and Exceptions +------------------------ The module defines the following exception and functions: .. exception:: error - Exception raised on various occasions; argument is a string describing what is - wrong. + Exception raised on various occasions; argument is a string describing what + is wrong. .. function:: pack(fmt, v1, v2, ...) @@ -33,9 +46,9 @@ .. function:: pack_into(fmt, buffer, offset, v1, v2, ...) - Pack the values ``v1, v2, ...`` according to the given format, write the packed - bytes into the writable *buffer* starting at *offset*. Note that the offset is - a required argument. + Pack the values ``v1, v2, ...`` according to the given format, write the + packed bytes into the writable *buffer* starting at *offset*. Note that the + offset is a required argument. .. versionadded:: 2.5 @@ -43,17 +56,17 @@ .. function:: unpack(fmt, string) Unpack the string (presumably packed by ``pack(fmt, ...)``) according to the - given format. The result is a tuple even if it contains exactly one item. The - string must contain exactly the amount of data required by the format + given format. The result is a tuple even if it contains exactly one item. + The string must contain exactly the amount of data required by the format (``len(string)`` must equal ``calcsize(fmt)``). .. function:: unpack_from(fmt, buffer[,offset=0]) Unpack the *buffer* according to the given format. The result is a tuple even - if it contains exactly one item. The *buffer* must contain at least the amount - of data required by the format (``len(buffer[offset:])`` must be at least - ``calcsize(fmt)``). + if it contains exactly one item. The *buffer* must contain at least the + amount of data required by the format (``len(buffer[offset:])`` must be at + least ``calcsize(fmt)``). .. versionadded:: 2.5 @@ -63,49 +76,62 @@ Return the size of the struct (and hence of the string) corresponding to the given format. +.. _struct-format-strings: + +Format Strings +-------------- + +Format strings are the mechanism used to specify the expected layout when +packing and unpacking data. They are built up from format characters, which +specify the type of data being packed/unpacked. In addition, there are +special characters for controlling the byte order, size, and alignment. + +Format Characters +^^^^^^^^^^^^^^^^^ + Format characters have the following meaning; the conversion between C and Python values should be obvious given their types: -+--------+-------------------------+--------------------+-------+ -| Format | C Type | Python | Notes | -+========+=========================+====================+=======+ -| ``x`` | pad byte | no value | | -+--------+-------------------------+--------------------+-------+ -| ``c`` | :ctype:`char` | string of length 1 | | -+--------+-------------------------+--------------------+-------+ -| ``b`` | :ctype:`signed char` | integer | | -+--------+-------------------------+--------------------+-------+ -| ``B`` | :ctype:`unsigned char` | integer | | -+--------+-------------------------+--------------------+-------+ -| ``?`` | :ctype:`_Bool` | bool | \(1) | -+--------+-------------------------+--------------------+-------+ -| ``h`` | :ctype:`short` | integer | | -+--------+-------------------------+--------------------+-------+ -| ``H`` | :ctype:`unsigned short` | integer | | -+--------+-------------------------+--------------------+-------+ -| ``i`` | :ctype:`int` | integer | | -+--------+-------------------------+--------------------+-------+ -| ``I`` | :ctype:`unsigned int` | integer or long | | -+--------+-------------------------+--------------------+-------+ -| ``l`` | :ctype:`long` | integer | | -+--------+-------------------------+--------------------+-------+ -| ``L`` | :ctype:`unsigned long` | long | | -+--------+-------------------------+--------------------+-------+ -| ``q`` | :ctype:`long long` | long | \(2) | -+--------+-------------------------+--------------------+-------+ -| ``Q`` | :ctype:`unsigned long | long | \(2) | -| | long` | | | -+--------+-------------------------+--------------------+-------+ -| ``f`` | :ctype:`float` | float | | -+--------+-------------------------+--------------------+-------+ -| ``d`` | :ctype:`double` | float | | -+--------+-------------------------+--------------------+-------+ -| ``s`` | :ctype:`char[]` | string | | -+--------+-------------------------+--------------------+-------+ -| ``p`` | :ctype:`char[]` | string | | -+--------+-------------------------+--------------------+-------+ -| ``P`` | :ctype:`void \*` | long | | -+--------+-------------------------+--------------------+-------+ ++--------+-------------------------+--------------------+------------+ +| Format | C Type | Python | Notes | ++========+=========================+====================+============+ +| ``x`` | pad byte | no value | | ++--------+-------------------------+--------------------+------------+ +| ``c`` | :ctype:`char` | string of length 1 | | ++--------+-------------------------+--------------------+------------+ +| ``b`` | :ctype:`signed char` | integer | \(3) | ++--------+-------------------------+--------------------+------------+ +| ``B`` | :ctype:`unsigned char` | integer | \(3) | ++--------+-------------------------+--------------------+------------+ +| ``?`` | :ctype:`_Bool` | bool | \(1) | ++--------+-------------------------+--------------------+------------+ +| ``h`` | :ctype:`short` | integer | \(3) | ++--------+-------------------------+--------------------+------------+ +| ``H`` | :ctype:`unsigned short` | integer | \(3) | ++--------+-------------------------+--------------------+------------+ +| ``i`` | :ctype:`int` | integer | \(3) | ++--------+-------------------------+--------------------+------------+ +| ``I`` | :ctype:`unsigned int` | integer or long | \(3) | ++--------+-------------------------+--------------------+------------+ +| ``l`` | :ctype:`long` | integer | \(3) | ++--------+-------------------------+--------------------+------------+ +| ``L`` | :ctype:`unsigned long` | long | \(3) | ++--------+-------------------------+--------------------+------------+ +| ``q`` | :ctype:`long long` | long | \(2),\(3) | ++--------+-------------------------+--------------------+------------+ +| ``Q`` | :ctype:`unsigned long | long | \(2),\(3) | +| | long` | | | ++--------+-------------------------+--------------------+------------+ +| ``f`` | :ctype:`float` | float | | ++--------+-------------------------+--------------------+------------+ +| ``d`` | :ctype:`double` | float | | ++--------+-------------------------+--------------------+------------+ +| ``s`` | :ctype:`char[]` | string | | ++--------+-------------------------+--------------------+------------+ +| ``p`` | :ctype:`char[]` | string | | ++--------+-------------------------+--------------------+------------+ +| ``P`` | :ctype:`void \*` | long | \(3) | ++--------+-------------------------+--------------------+------------+ Notes: @@ -163,7 +189,13 @@ Either 0 or 1 in the native or standard bool representation will be packed, and any non-zero value will be True when unpacking. -By default, C numbers are represented in the machine's native format and byte + +.. _struct-alignment: + +Byte Order, Size, and Alignment +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +By default, C types are represented in the machine's native format and byte order, and properly aligned by skipping pad bytes if necessary (according to the rules used by the C compiler). @@ -217,8 +249,29 @@ the host system. The struct module does not interpret this as native ordering, so the ``'P'`` format is not available. -Examples (all using native byte order, size and alignment, on a big-endian -machine):: +Notes: + +(1) Padding is only automatically added between successive structure members. + No padding is added at the beginning or the end of the encoded struct. + +(2) No padding is added when using non-native size and alignment, e.g. + with '<', '>', '=', and '!'. + +(3) To align the end of a structure to the alignment requirement of a + particular type, end the format with the code for that type with a repeat + count of zero. See :ref:`struct-examples`. + + +.. _struct-examples: + +Examples +^^^^^^^^ + +.. note:: + All examples assume a native byte order, size, and alignment with a + big-endian machine. + +A basic example of packing/unpacking three integers:: >>> from struct import * >>> pack('hhl', 1, 2, 3) @@ -228,13 +281,6 @@ >>> calcsize('hhl') 8 -Hint: to align the end of a structure to the alignment requirement of a -particular type, end the format with the code for that type with a repeat count -of zero. For example, the format ``'llh0l'`` specifies two pad bytes at the -end, assuming longs are aligned on 4-byte boundaries. This only works when -native size and alignment are in effect; standard size and alignment does not -enforce any alignment. - Unpacked fields can be named by assigning them to variables or by wrapping the result in a named tuple:: @@ -246,6 +292,28 @@ >>> Student._make(unpack('<10sHHb', s)) Student(name='raymond ', serialnum=4658, school=264, gradelevel=8) +The ordering of format characters may have an impact on size since the padding +needed to satisfy alignment requirements is different:: + + >>> pack('ci', '*', 0x12131415) + '*\x00\x00\x00\x12\x13\x14\x15' + >>> pack('ic', 0x12131415, '*') + '\x12\x13\x14\x15*' + >>> calcsize('ci') + 8 + >>> calcsize('ic') + 5 + +The following format ``'llh0l'`` specifies two pad bytes at the end, assuming +longs are aligned on 4-byte boundaries:: + + >>> pack('llh0l', 1, 2, 3) + '\x00\x00\x00\x01\x00\x00\x00\x02\x00\x03\x00\x00' + +This only works when native size and alignment are in effect; standard size and +alignment does not enforce any alignment. + + .. seealso:: Module :mod:`array` @@ -257,18 +325,18 @@ .. _struct-objects: -Struct Objects --------------- +Objects +------- The :mod:`struct` module also defines the following type: .. class:: Struct(format) - Return a new Struct object which writes and reads binary data according to the - format string *format*. Creating a Struct object once and calling its methods - is more efficient than calling the :mod:`struct` functions with the same format - since the format string only needs to be compiled once. + Return a new Struct object which writes and reads binary data according to + the format string *format*. Creating a Struct object once and calling its + methods is more efficient than calling the :mod:`struct` functions with the + same format since the format string only needs to be compiled once. .. versionadded:: 2.5 From python-checkins at python.org Sat May 22 20:47:40 2010 From: python-checkins at python.org (benjamin.peterson) Date: Sat, 22 May 2010 20:47:40 +0200 (CEST) Subject: [Python-checkins] r81478 - sandbox/trunk/2to3/lib2to3/refactor.py Message-ID: <20100522184740.04167EE9B0@mail.python.org> Author: benjamin.peterson Date: Sat May 22 20:47:39 2010 New Revision: 81478 Log: ensure doctests have some future_features Modified: sandbox/trunk/2to3/lib2to3/refactor.py Modified: sandbox/trunk/2to3/lib2to3/refactor.py ============================================================================== --- sandbox/trunk/2to3/lib2to3/refactor.py (original) +++ sandbox/trunk/2to3/lib2to3/refactor.py Sat May 22 20:47:39 2010 @@ -564,7 +564,9 @@ This is necessary to get correct line number / offset information in the parser diagnostics and embedded into the parse tree. """ - return self.driver.parse_tokens(self.wrap_toks(block, lineno, indent)) + tree = self.driver.parse_tokens(self.wrap_toks(block, lineno, indent)) + tree.future_features = frozenset() + return tree def wrap_toks(self, block, lineno, indent): """Wraps a tokenize stream to systematically modify start/end.""" From python-checkins at python.org Sat May 22 20:52:22 2010 From: python-checkins at python.org (benjamin.peterson) Date: Sat, 22 May 2010 20:52:22 +0200 (CEST) Subject: [Python-checkins] r81479 - in python/trunk/Lib/lib2to3: fixes/fix_sys_exc.py refactor.py Message-ID: <20100522185222.0DB46EE9DE@mail.python.org> Author: benjamin.peterson Date: Sat May 22 20:52:21 2010 New Revision: 81479 Log: Merged revisions 80937,81478 via svnmerge from svn+ssh://pythondev at svn.python.org/sandbox/trunk/2to3/lib2to3 ........ r80937 | benjamin.peterson | 2010-05-07 14:10:58 -0500 (Fri, 07 May 2010) | 1 line remove redundant unicode call ........ r81478 | benjamin.peterson | 2010-05-22 13:47:39 -0500 (Sat, 22 May 2010) | 1 line ensure doctests have some future_features ........ Modified: python/trunk/Lib/lib2to3/ (props changed) python/trunk/Lib/lib2to3/fixes/fix_sys_exc.py python/trunk/Lib/lib2to3/refactor.py Modified: python/trunk/Lib/lib2to3/fixes/fix_sys_exc.py ============================================================================== --- python/trunk/Lib/lib2to3/fixes/fix_sys_exc.py (original) +++ python/trunk/Lib/lib2to3/fixes/fix_sys_exc.py Sat May 22 20:52:21 2010 @@ -20,7 +20,7 @@ def transform(self, node, results): sys_attr = results["attribute"][0] - index = Number(unicode(self.exc_info.index(sys_attr.value))) + index = Number(self.exc_info.index(sys_attr.value)) call = Call(Name(u"exc_info"), prefix=sys_attr.prefix) attr = Attr(Name(u"sys"), call) Modified: python/trunk/Lib/lib2to3/refactor.py ============================================================================== --- python/trunk/Lib/lib2to3/refactor.py (original) +++ python/trunk/Lib/lib2to3/refactor.py Sat May 22 20:52:21 2010 @@ -564,7 +564,9 @@ This is necessary to get correct line number / offset information in the parser diagnostics and embedded into the parse tree. """ - return self.driver.parse_tokens(self.wrap_toks(block, lineno, indent)) + tree = self.driver.parse_tokens(self.wrap_toks(block, lineno, indent)) + tree.future_features = frozenset() + return tree def wrap_toks(self, block, lineno, indent): """Wraps a tokenize stream to systematically modify start/end.""" From python-checkins at python.org Sat May 22 20:58:40 2010 From: python-checkins at python.org (mark.dickinson) Date: Sat, 22 May 2010 20:58:40 +0200 (CEST) Subject: [Python-checkins] r81480 - in python/branches/release31-maint: Doc/library/struct.rst Message-ID: <20100522185840.16AE3EE9D5@mail.python.org> Author: mark.dickinson Date: Sat May 22 20:58:39 2010 New Revision: 81480 Log: Merged revisions 80016 via svnmerge from svn+ssh://pythondev at svn.python.org/python/branches/py3k ................ r80016 | mark.dickinson | 2010-04-12 22:00:59 +0100 (Mon, 12 Apr 2010) | 29 lines Merged revisions 80013-80015 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r80013 | mark.dickinson | 2010-04-12 20:25:32 +0100 (Mon, 12 Apr 2010) | 14 lines Issue #7355: Various improvements to struct module documentation. - note early on that the result of struct.pack includes padding bytes by default - add examples showing how order of struct fields can affect size (due to padding) - better headers and references; introduction to format strings - integrate packing notes into table Many thanks to Meador Inge for the patch. ........ r80014 | mark.dickinson | 2010-04-12 20:46:20 +0100 (Mon, 12 Apr 2010) | 1 line Rewrap some long lines in struct module doc source. ........ r80015 | mark.dickinson | 2010-04-12 21:38:36 +0100 (Mon, 12 Apr 2010) | 1 line More struct doc tweaks. ........ ................ Modified: python/branches/release31-maint/ (props changed) python/branches/release31-maint/Doc/library/struct.rst Modified: python/branches/release31-maint/Doc/library/struct.rst ============================================================================== --- python/branches/release31-maint/Doc/library/struct.rst (original) +++ python/branches/release31-maint/Doc/library/struct.rst Sat May 22 20:58:39 2010 @@ -9,18 +9,31 @@ triple: packing; binary; data This module performs conversions between Python values and C structs represented -as Python :class:`bytes` objects. It uses :dfn:`format strings` (explained -below) as compact descriptions of the lay-out of the C structs and the -intended conversion to/from Python values. This can be used in handling -binary data stored in files or from network connections, among other sources. +as Python :class:`bytes` objects. This can be used in handling binary data +stored in files or from network connections, among other sources. It uses +:ref:`struct-format-strings` as compact descriptions of the layout of the C +structs and the intended conversion to/from Python values. + +.. note:: + + By default, the result of packing a given C struct includes pad bytes in + order to maintain proper alignment for the C types involved; similarly, + alignment is taken into account when unpacking. This behavior is chosen so + that the bytes of a packed struct correspond exactly to the layout in memory + of the corresponding C struct. To omit pad bytes, use `standard` size and + alignment instead of `native` size and alignment: see :ref:`struct-alignment` + for details. + +Functions and Exceptions +------------------------ The module defines the following exception and functions: .. exception:: error - Exception raised on various occasions; argument is a string describing what is - wrong. + Exception raised on various occasions; argument is a string describing what + is wrong. .. function:: pack(fmt, v1, v2, ...) @@ -32,25 +45,25 @@ .. function:: pack_into(fmt, buffer, offset, v1, v2, ...) - Pack the values ``v1, v2, ...`` according to the given format, write the packed - bytes into the writable *buffer* starting at *offset*. Note that the offset is - a required argument. + Pack the values ``v1, v2, ...`` according to the given format, write the + packed bytes into the writable *buffer* starting at *offset*. Note that the + offset is a required argument. .. function:: unpack(fmt, bytes) Unpack the bytes (presumably packed by ``pack(fmt, ...)``) according to the - given format. The result is a tuple even if it contains exactly one item. The - bytes must contain exactly the amount of data required by the format + given format. The result is a tuple even if it contains exactly one item. + The bytes must contain exactly the amount of data required by the format (``len(bytes)`` must equal ``calcsize(fmt)``). .. function:: unpack_from(fmt, buffer, offset=0) Unpack the *buffer* according to the given format. The result is a tuple even - if it contains exactly one item. The *buffer* must contain at least the amount - of data required by the format (``len(buffer[offset:])`` must be at least - ``calcsize(fmt)``). + if it contains exactly one item. The *buffer* must contain at least the + amount of data required by the format (``len(buffer[offset:])`` must be at + least ``calcsize(fmt)``). .. function:: calcsize(fmt) @@ -58,49 +71,62 @@ Return the size of the struct (and hence of the bytes) corresponding to the given format. +.. _struct-format-strings: + +Format Strings +-------------- + +Format strings are the mechanism used to specify the expected layout when +packing and unpacking data. They are built up from format characters, which +specify the type of data being packed/unpacked. In addition, there are +special characters for controlling the byte order, size, and alignment. + +Format Characters +^^^^^^^^^^^^^^^^^ + Format characters have the following meaning; the conversion between C and Python values should be obvious given their types: -+--------+-------------------------+--------------------+-------+ -| Format | C Type | Python | Notes | -+========+=========================+====================+=======+ -| ``x`` | pad byte | no value | | -+--------+-------------------------+--------------------+-------+ -| ``c`` | :ctype:`char` | bytes of length 1 | | -+--------+-------------------------+--------------------+-------+ -| ``b`` | :ctype:`signed char` | integer | \(1) | -+--------+-------------------------+--------------------+-------+ -| ``B`` | :ctype:`unsigned char` | integer | | -+--------+-------------------------+--------------------+-------+ -| ``?`` | :ctype:`_Bool` | bool | \(2) | -+--------+-------------------------+--------------------+-------+ -| ``h`` | :ctype:`short` | integer | | -+--------+-------------------------+--------------------+-------+ -| ``H`` | :ctype:`unsigned short` | integer | | -+--------+-------------------------+--------------------+-------+ -| ``i`` | :ctype:`int` | integer | | -+--------+-------------------------+--------------------+-------+ -| ``I`` | :ctype:`unsigned int` | integer | | -+--------+-------------------------+--------------------+-------+ -| ``l`` | :ctype:`long` | integer | | -+--------+-------------------------+--------------------+-------+ -| ``L`` | :ctype:`unsigned long` | integer | | -+--------+-------------------------+--------------------+-------+ -| ``q`` | :ctype:`long long` | integer | \(3) | -+--------+-------------------------+--------------------+-------+ -| ``Q`` | :ctype:`unsigned long | integer | \(3) | -| | long` | | | -+--------+-------------------------+--------------------+-------+ -| ``f`` | :ctype:`float` | float | | -+--------+-------------------------+--------------------+-------+ -| ``d`` | :ctype:`double` | float | | -+--------+-------------------------+--------------------+-------+ -| ``s`` | :ctype:`char[]` | bytes | \(1) | -+--------+-------------------------+--------------------+-------+ -| ``p`` | :ctype:`char[]` | bytes | \(1) | -+--------+-------------------------+--------------------+-------+ -| ``P`` | :ctype:`void \*` | integer | | -+--------+-------------------------+--------------------+-------+ ++--------+-------------------------+--------------------+------------+ +| Format | C Type | Python | Notes | ++========+=========================+====================+============+ +| ``x`` | pad byte | no value | | ++--------+-------------------------+--------------------+------------+ +| ``c`` | :ctype:`char` | bytes of length 1 | | ++--------+-------------------------+--------------------+------------+ +| ``b`` | :ctype:`signed char` | integer | \(1),\(4) | ++--------+-------------------------+--------------------+------------+ +| ``B`` | :ctype:`unsigned char` | integer | \(4) | ++--------+-------------------------+--------------------+------------+ +| ``?`` | :ctype:`_Bool` | bool | \(2) | ++--------+-------------------------+--------------------+------------+ +| ``h`` | :ctype:`short` | integer | \(4) | ++--------+-------------------------+--------------------+------------+ +| ``H`` | :ctype:`unsigned short` | integer | \(4) | ++--------+-------------------------+--------------------+------------+ +| ``i`` | :ctype:`int` | integer | \(4) | ++--------+-------------------------+--------------------+------------+ +| ``I`` | :ctype:`unsigned int` | integer | \(4) | ++--------+-------------------------+--------------------+------------+ +| ``l`` | :ctype:`long` | integer | \(4) | ++--------+-------------------------+--------------------+------------+ +| ``L`` | :ctype:`unsigned long` | integer | \(4) | ++--------+-------------------------+--------------------+------------+ +| ``q`` | :ctype:`long long` | integer | \(3), \(4) | ++--------+-------------------------+--------------------+------------+ +| ``Q`` | :ctype:`unsigned long | integer | \(3), \(4) | +| | long` | | | ++--------+-------------------------+--------------------+------------+ +| ``f`` | :ctype:`float` | float | | ++--------+-------------------------+--------------------+------------+ +| ``d`` | :ctype:`double` | float | | ++--------+-------------------------+--------------------+------------+ +| ``s`` | :ctype:`char[]` | bytes | \(1) | ++--------+-------------------------+--------------------+------------+ +| ``p`` | :ctype:`char[]` | bytes | \(1) | ++--------+-------------------------+--------------------+------------+ +| ``P`` | :ctype:`void \*` | integer | | ++--------+-------------------------+--------------------+------------+ Notes: @@ -160,7 +186,13 @@ Either 0 or 1 in the native or standard bool representation will be packed, and any non-zero value will be True when unpacking. -By default, C numbers are represented in the machine's native format and byte + +.. _struct-alignment: + +Byte Order, Size, and Alignment +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +By default, C types are represented in the machine's native format and byte order, and properly aligned by skipping pad bytes if necessary (according to the rules used by the C compiler). @@ -212,8 +244,29 @@ the host system. The struct module does not interpret this as native ordering, so the ``'P'`` format is not available. -Examples (all using native byte order, size and alignment, on a big-endian -machine):: +Notes: + +(1) Padding is only automatically added between successive structure members. + No padding is added at the beginning or the end of the encoded struct. + +(2) No padding is added when using non-native size and alignment, e.g. + with '<', '>', '=', and '!'. + +(3) To align the end of a structure to the alignment requirement of a + particular type, end the format with the code for that type with a repeat + count of zero. See :ref:`struct-examples`. + + +.. _struct-examples: + +Examples +^^^^^^^^ + +.. note:: + All examples assume a native byte order, size, and alignment with a + big-endian machine. + +A basic example of packing/unpacking three integers:: >>> from struct import * >>> pack('hhl', 1, 2, 3) @@ -223,13 +276,6 @@ >>> calcsize('hhl') 8 -Hint: to align the end of a structure to the alignment requirement of a -particular type, end the format with the code for that type with a repeat count -of zero. For example, the format ``'llh0l'`` specifies two pad bytes at the -end, assuming longs are aligned on 4-byte boundaries. This only works when -native size and alignment are in effect; standard size and alignment does not -enforce any alignment. - Unpacked fields can be named by assigning them to variables or by wrapping the result in a named tuple:: @@ -241,6 +287,28 @@ >>> Student._make(unpack('<10sHHb', record)) Student(name=b'raymond ', serialnum=4658, school=264, gradelevel=8) +The ordering of format characters may have an impact on size since the padding +needed to satisfy alignment requirements is different:: + + >>> pack('ci', '*', 0x12131415) + b'*\x00\x00\x00\x12\x13\x14\x15' + >>> pack('ic', 0x12131415, '*') + b'\x12\x13\x14\x15*' + >>> calcsize('ci') + 8 + >>> calcsize('ic') + 5 + +The following format ``'llh0l'`` specifies two pad bytes at the end, assuming +longs are aligned on 4-byte boundaries:: + + >>> pack('llh0l', 1, 2, 3) + b'\x00\x00\x00\x01\x00\x00\x00\x02\x00\x03\x00\x00' + +This only works when native size and alignment are in effect; standard size and +alignment does not enforce any alignment. + + .. seealso:: Module :mod:`array` @@ -252,18 +320,18 @@ .. _struct-objects: -Struct Objects --------------- +Objects +------- The :mod:`struct` module also defines the following type: .. class:: Struct(format) - Return a new Struct object which writes and reads binary data according to the - format string *format*. Creating a Struct object once and calling its methods - is more efficient than calling the :mod:`struct` functions with the same format - since the format string only needs to be compiled once. + Return a new Struct object which writes and reads binary data according to + the format string *format*. Creating a Struct object once and calling its + methods is more efficient than calling the :mod:`struct` functions with the + same format since the format string only needs to be compiled once. Compiled Struct objects support the following methods and attributes: From python-checkins at python.org Sat May 22 20:59:24 2010 From: python-checkins at python.org (benjamin.peterson) Date: Sat, 22 May 2010 20:59:24 +0200 (CEST) Subject: [Python-checkins] r81481 - in python/branches/py3k: Lib/lib2to3/refactor.py Message-ID: <20100522185924.B3300EE9DB@mail.python.org> Author: benjamin.peterson Date: Sat May 22 20:59:24 2010 New Revision: 81481 Log: Merged revisions 81479 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ................ r81479 | benjamin.peterson | 2010-05-22 13:52:21 -0500 (Sat, 22 May 2010) | 13 lines Merged revisions 80937,81478 via svnmerge from svn+ssh://pythondev at svn.python.org/sandbox/trunk/2to3/lib2to3 ........ r80937 | benjamin.peterson | 2010-05-07 14:10:58 -0500 (Fri, 07 May 2010) | 1 line remove redundant unicode call ........ r81478 | benjamin.peterson | 2010-05-22 13:47:39 -0500 (Sat, 22 May 2010) | 1 line ensure doctests have some future_features ........ ................ Modified: python/branches/py3k/ (props changed) python/branches/py3k/Lib/lib2to3/refactor.py Modified: python/branches/py3k/Lib/lib2to3/refactor.py ============================================================================== --- python/branches/py3k/Lib/lib2to3/refactor.py (original) +++ python/branches/py3k/Lib/lib2to3/refactor.py Sat May 22 20:59:24 2010 @@ -564,7 +564,9 @@ This is necessary to get correct line number / offset information in the parser diagnostics and embedded into the parse tree. """ - return self.driver.parse_tokens(self.wrap_toks(block, lineno, indent)) + tree = self.driver.parse_tokens(self.wrap_toks(block, lineno, indent)) + tree.future_features = frozenset() + return tree def wrap_toks(self, block, lineno, indent): """Wraps a tokenize stream to systematically modify start/end.""" From python-checkins at python.org Sat May 22 20:59:39 2010 From: python-checkins at python.org (benjamin.peterson) Date: Sat, 22 May 2010 20:59:39 +0200 (CEST) Subject: [Python-checkins] r81482 - in python/branches/release26-maint: Lib/lib2to3 Lib/lib2to3/fixes/fix_sys_exc.py Lib/lib2to3/refactor.py Message-ID: <20100522185939.152F4EE9CA@mail.python.org> Author: benjamin.peterson Date: Sat May 22 20:59:38 2010 New Revision: 81482 Log: Merged revisions 81479 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ................ r81479 | benjamin.peterson | 2010-05-22 13:52:21 -0500 (Sat, 22 May 2010) | 13 lines Merged revisions 80937,81478 via svnmerge from svn+ssh://pythondev at svn.python.org/sandbox/trunk/2to3/lib2to3 ........ r80937 | benjamin.peterson | 2010-05-07 14:10:58 -0500 (Fri, 07 May 2010) | 1 line remove redundant unicode call ........ r81478 | benjamin.peterson | 2010-05-22 13:47:39 -0500 (Sat, 22 May 2010) | 1 line ensure doctests have some future_features ........ ................ Modified: python/branches/release26-maint/ (props changed) python/branches/release26-maint/Lib/lib2to3/ (props changed) python/branches/release26-maint/Lib/lib2to3/fixes/fix_sys_exc.py python/branches/release26-maint/Lib/lib2to3/refactor.py Modified: python/branches/release26-maint/Lib/lib2to3/fixes/fix_sys_exc.py ============================================================================== --- python/branches/release26-maint/Lib/lib2to3/fixes/fix_sys_exc.py (original) +++ python/branches/release26-maint/Lib/lib2to3/fixes/fix_sys_exc.py Sat May 22 20:59:38 2010 @@ -20,7 +20,7 @@ def transform(self, node, results): sys_attr = results["attribute"][0] - index = Number(unicode(self.exc_info.index(sys_attr.value))) + index = Number(self.exc_info.index(sys_attr.value)) call = Call(Name(u"exc_info"), prefix=sys_attr.prefix) attr = Attr(Name(u"sys"), call) Modified: python/branches/release26-maint/Lib/lib2to3/refactor.py ============================================================================== --- python/branches/release26-maint/Lib/lib2to3/refactor.py (original) +++ python/branches/release26-maint/Lib/lib2to3/refactor.py Sat May 22 20:59:38 2010 @@ -564,7 +564,9 @@ This is necessary to get correct line number / offset information in the parser diagnostics and embedded into the parse tree. """ - return self.driver.parse_tokens(self.wrap_toks(block, lineno, indent)) + tree = self.driver.parse_tokens(self.wrap_toks(block, lineno, indent)) + tree.future_features = frozenset() + return tree def wrap_toks(self, block, lineno, indent): """Wraps a tokenize stream to systematically modify start/end.""" From python-checkins at python.org Sat May 22 21:40:31 2010 From: python-checkins at python.org (benjamin.peterson) Date: Sat, 22 May 2010 21:40:31 +0200 (CEST) Subject: [Python-checkins] r81483 - in python/branches/release31-maint: Lib/lib2to3/refactor.py Message-ID: <20100522194031.76B2AEE9AD@mail.python.org> Author: benjamin.peterson Date: Sat May 22 21:40:31 2010 New Revision: 81483 Log: Merged revisions 81481 via svnmerge from svn+ssh://pythondev at svn.python.org/python/branches/py3k ................ r81481 | benjamin.peterson | 2010-05-22 13:59:24 -0500 (Sat, 22 May 2010) | 20 lines Merged revisions 81479 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ................ r81479 | benjamin.peterson | 2010-05-22 13:52:21 -0500 (Sat, 22 May 2010) | 13 lines Merged revisions 80937,81478 via svnmerge from svn+ssh://pythondev at svn.python.org/sandbox/trunk/2to3/lib2to3 ........ r80937 | benjamin.peterson | 2010-05-07 14:10:58 -0500 (Fri, 07 May 2010) | 1 line remove redundant unicode call ........ r81478 | benjamin.peterson | 2010-05-22 13:47:39 -0500 (Sat, 22 May 2010) | 1 line ensure doctests have some future_features ........ ................ ................ Modified: python/branches/release31-maint/ (props changed) python/branches/release31-maint/Lib/lib2to3/refactor.py Modified: python/branches/release31-maint/Lib/lib2to3/refactor.py ============================================================================== --- python/branches/release31-maint/Lib/lib2to3/refactor.py (original) +++ python/branches/release31-maint/Lib/lib2to3/refactor.py Sat May 22 21:40:31 2010 @@ -564,7 +564,9 @@ This is necessary to get correct line number / offset information in the parser diagnostics and embedded into the parse tree. """ - return self.driver.parse_tokens(self.wrap_toks(block, lineno, indent)) + tree = self.driver.parse_tokens(self.wrap_toks(block, lineno, indent)) + tree.future_features = frozenset() + return tree def wrap_toks(self, block, lineno, indent): """Wraps a tokenize stream to systematically modify start/end.""" From python-checkins at python.org Sat May 22 23:26:21 2010 From: python-checkins at python.org (georg.brandl) Date: Sat, 22 May 2010 23:26:21 +0200 (CEST) Subject: [Python-checkins] r81484 - python/trunk/Misc/NEWS Message-ID: <20100522212621.DDEDEEE982@mail.python.org> Author: georg.brandl Date: Sat May 22 23:26:21 2010 New Revision: 81484 Log: NEWS rewrap and punctuation consistency. Modified: python/trunk/Misc/NEWS Modified: python/trunk/Misc/NEWS ============================================================================== --- python/trunk/Misc/NEWS (original) +++ python/trunk/Misc/NEWS Sat May 22 23:26:21 2010 @@ -12,18 +12,18 @@ Core and Builtins ----------------- -- Issue #7902: When using explicit relative import syntax, don't try - implicit relative import semantics. +- Issue #7902: When using explicit relative import syntax, don't try implicit + relative import semantics. -- Issue #7079: Fix a possible crash when closing a file object while using - it from another thread. Patch by Daniel Stutzbach. +- Issue #7079: Fix a possible crash when closing a file object while using it + from another thread. Patch by Daniel Stutzbach. C-API ----- -- Issue #5753: A new C API function, :cfunc:`PySys_SetArgvEx`, allows - embedders of the interpreter to set sys.argv without also modifying - sys.path. This helps fix `CVE-2008-5983 +- Issue #5753: A new C API function, :cfunc:`PySys_SetArgvEx`, allows embedders + of the interpreter to set sys.argv without also modifying sys.path. This + helps fix `CVE-2008-5983 `_. Library @@ -36,36 +36,37 @@ StreamWriter classes. - Issue #5640: Fix Shift-JIS incremental encoder for error handlers different - than strict + than 'strict'. - Issue #8782: Add a trailing newline in linecache.updatecache to the last line of files without one. -- Issue #8729: Return NotImplemented from collections.Mapping.__eq__ when +- Issue #8729: Return NotImplemented from ``collections.Mapping.__eq__()`` when comparing to a non-mapping. -- Issue #8759: Fixed user paths in sysconfig for posix and os2 schemes. +- Issue #8759: Fix user paths in sysconfig for posix and os2 schemes. -- Issue #1285086: Speed up urllib.quote and urllib.unquote for simple cases. +- Issue #1285086: Speed up ``urllib.quote()`` and urllib.unquote for simple + cases. - Issue #8688: Distutils now recalculates MANIFEST everytime. -- Issue #5099: subprocess.Popen's __del__ method (and the methods it calls) - referenced global objects, causing errors to pop up during interpreter - shutdown. +- Issue #5099: The ``__del__()`` method of ``subprocess.Popen`` (and the methods + it calls) referenced global objects, causing errors to pop up during + interpreter shutdown. Extension Modules ----------------- - Issue #8674: Fixed a number of incorrect or undefined-behaviour-inducing - overflow checks in the audioop module. + overflow checks in the ``audioop`` module. Tests ----- -- On darwin, test_site assumed that a framework build was being used, leading - to a failure where four directories were expected for site-packages instead - of two in a non-framework build. +- On darwin, ``test_site`` assumed that a framework build was being used, + leading to a failure where four directories were expected for site-packages + instead of two in a non-framework build. What's New in Python 2.7 beta 2? @@ -76,226 +77,221 @@ Core and Builtins ----------------- -- Run Clang 2.7's static analyzer for Objects/ and Python/ . +- Run Clang 2.7's static analyzer for ``Objects/`` and ``Python/``. + +- Issue #1533: Fix inconsistency in range function argument processing: any + non-float non-integer argument is now converted to an integer (if possible) + using its __int__ method. Previously, only small arguments were treated this + way; larger arguments (those whose __int__ was outside the range of a C long) + would produce a TypeError. -- Issue #1533: fix inconsistency in range function argument - processing: any non-float non-integer argument is now converted to - an integer (if possible) using its __int__ method. Previously, only - small arguments were treated this way; larger arguments (those whose - __int__ was outside the range of a C long) would produce a TypeError. - -- Issue #8202: sys.argv[0] is now set to '-m' instead of '-c' when - searching for the module file to be executed with the -m command - line option +- Issue #8202: ``sys.argv[0]`` is now set to '-m' instead of '-c' when searching + for the module file to be executed with the -m command line option. - Issue #7319: When -Q is used, do not silence DeprecationWarning. - Issue #7332: Remove the 16KB stack-based buffer in - PyMarshal_ReadLastObjectFromFile, which doesn't bring any noticeable + ``PyMarshal_ReadLastObjectFromFile``, which doesn't bring any noticeable benefit compared to the dynamic memory allocation fallback. Patch by Charles-Fran?ois Natali. - Issue #8417: Raise an OverflowError when an integer larger than sys.maxsize is passed to bytearray. -- Issue #7072: isspace(0xa0) is true on Mac OS X +- Issue #7072: ``isspace(0xa0)`` is true on Mac OS X. -- Issue #8404: Fixed set operations on dictionary views. +- Issue #8404: Fix set operations on dictionary views. -- Issue #8084: PEP 370 now conforms to system conventions for framework - builds on MacOS X. That is, "python setup.py install --user" will install - into "~/Library/Python/2.7" instead of "~/.local". +- Issue #8084: PEP 370 now conforms to system conventions for framework builds + on MacOS X. That is, ``python setup.py install --user`` will install into + ``~/Library/Python/2.7`` instead of ``~/.local``. Library ------- -- Issue #8681: Make the zlib module's error messages more informative when - the zlib itself doesn't give any detailed explanation. +- Issue #8681: Make the zlib module's error messages more informative when the + zlib itself doesn't give any detailed explanation. -- Issue #8571: Fix an internal error when compressing or decompressing a - chunk larger than 1GB with the zlib module's compressor and decompressor - objects. +- Issue #8571: Fix an internal error when compressing or decompressing a chunk + larger than 1GB with the zlib module's compressor and decompressor objects. -- Issue #8573: asyncore _strerror() function might throw ValueError. +- Issue #8573: asyncore ``_strerror()`` function might throw ValueError. -- Issue #8483: asyncore.dispatcher's __getattr__ method produced confusing - error messages when accessing undefined class attributes because of the cheap - inheritance with the underlying socket object. - The cheap inheritance has been deprecated. +- Issue #8483: asyncore.dispatcher's __getattr__ method produced confusing error + messages when accessing undefined class attributes because of the cheap + inheritance with the underlying socket object. The cheap inheritance has been + deprecated. -- Issue #4265: shutil.copyfile() was leaking file descriptors when disk fills. - Patch by Tres Seaver. +- Issue #4265: ``shutil.copyfile()`` was leaking file descriptors when disk + fills. Patch by Tres Seaver. - Issue #7755: Use an unencumbered audio file for tests. -- Issue #8621: uuid.uuid4() returned the same sequence of values in the - parent and any children created using ``os.fork`` on MacOS X 10.6. +- Issue #8621: ``uuid.uuid4()`` returned the same sequence of values in the + parent and any children created using ``os.fork`` on Mac OS X 10.6. -- Issue #8313: traceback.format_exception_only() encodes unicode message to - ASCII with backslashreplace error handler if str(value) failed +- Issue #8313: ``traceback.format_exception_only()`` encodes unicode message to + ASCII with backslashreplace error handler if ``str(value)`` failed. -- Issue #8567: Fix precedence of signals in Decimal module: when a - Decimal operation raises multiple signals and more than one of those - signals is trapped, the specification determines the order in which - the signals should be handled. In many cases this order wasn't - being followed, leading to the wrong Python exception being raised. +- Issue #8567: Fix precedence of signals in Decimal module: when a Decimal + operation raises multiple signals and more than one of those signals is + trapped, the specification determines the order in which the signals should be + handled. In many cases this order wasn't being followed, leading to the wrong + Python exception being raised. - Issue #7865: The close() method of :mod:`io` objects should not swallow - exceptions raised by the implicit flush(). Also ensure that calling - close() several times is supported. Patch by Pascal Chambon. + exceptions raised by the implicit flush(). Also ensure that calling close() + several times is supported. Patch by Pascal Chambon. - Issue #8576: logging updated to remove usage of find_unused_port(). - Issue #4687: Fix accuracy of garbage collection runtimes displayed with gc.DEBUG_STATS. -- Issue #8354: The siginterrupt setting is now preserved for all signals, - not just SIGCHLD. +- Issue #8354: The siginterrupt setting is now preserved for all signals, not + just SIGCHLD. -- Issue #7192: webbrowser.get("firefox") now works on Mac OS X, as does - webbrowser.get("safari"). +- Issue #7192: ``webbrowser.get("firefox")`` now works on Mac OS X, as does + ``webbrowser.get("safari")``. -- Issue #8577: distutils.sysconfig.get_python_inc() now makes a difference +- Issue #8577: ``distutils.sysconfig.get_python_inc()`` now makes a difference between the build dir and the source dir when looking for "python.h" or "Include". -- Issue #8464: tarfile no longer creates files with execute permissions set - when mode="w|" is used. +- Issue #8464: tarfile no longer creates files with execute permissions set when + mode="w|" is used. -- Issue #7834: Fix connect() of Bluetooth L2CAP sockets with recent versions - of the Linux kernel. Patch by Yaniv Aknin. +- Issue #7834: Fix connect() of Bluetooth L2CAP sockets with recent versions of + the Linux kernel. Patch by Yaniv Aknin. -- Issue #6312: Fixed http HEAD request when the transfer encoding is chunked. - It should correctly return an empty response now. +- Issue #6312: Fix http HEAD request when the transfer encoding is chunked. It + should correctly return an empty response now. -- Issue #7490: to facilitate sharing of doctests between 2.x and 3.x test - suites, the IGNORE_EXCEPTION_DETAIL directive now also ignores the module - location of the raised exception. Based on initial patch by Lennart - Regebro. +- Issue #7490: To facilitate sharing of doctests between 2.x and 3.x test + suites, the ``IGNORE_EXCEPTION_DETAIL`` directive now also ignores the module + location of the raised exception. Based on initial patch by Lennart Regebro. -- Issue #8086: In :func:`ssl.DER_cert_to_PEM_cert()`, fix missing newline - before the certificate footer. Patch by Kyle VanderBeek. +- Issue #8086: In :func:`ssl.DER_cert_to_PEM_cert()`, fix missing newline before + the certificate footer. Patch by Kyle VanderBeek. -- Issue #8546: Reject None given as the buffering argument to _pyio.open. +- Issue #8546: Reject None given as the buffering argument to ``_pyio.open()``. -- Issue #8549: Fix compiling the _ssl extension under AIX. Patch by - Sridhar Ratnakumar. +- Issue #8549: Fix compiling the _ssl extension under AIX. Patch by Sridhar + Ratnakumar. -- Issue #6656: fix locale.format_string to handle escaped percents - and mappings. +- Issue #6656: Fix locale.format_string to handle escaped percents and mappings. -- Issue #2302: Fix a race condition in SocketServer.BaseServer.shutdown, - where the method could block indefinitely if called just before the - event loop started running. This also fixes the occasional freezes - witnessed in test_httpservers. +- Issue #2302: Fix a race condition in SocketServer.BaseServer.shutdown, where + the method could block indefinitely if called just before the event loop + started running. This also fixes the occasional freezes witnessed in + test_httpservers. - Issue #5103: SSL handshake would ignore the socket timeout and block indefinitely if the other end didn't respond. -- The do_handshake() method of SSL objects now adjusts the blocking mode of - the SSL structure if necessary (as other methods already do). +- The do_handshake() method of SSL objects now adjusts the blocking mode of the + SSL structure if necessary (as other methods already do). - Issue #7507: Quote "!" in pipes.quote(); it is special to some shells. -- Issue #5238: Calling makefile() on an SSL object would prevent the - underlying socket from being closed until all objects get truely destroyed. +- Issue #5238: Calling makefile() on an SSL object would prevent the underlying + socket from being closed until all objects get truely destroyed. -- Issue #7943: Fix circular reference created when instantiating an SSL - socket. Initial patch by P?ter Szab?. +- Issue #7943: Fix circular reference created when instantiating an SSL socket. + Initial patch by P?ter Szab?. -- Issue #8451: Syslog module now uses basename(sys.argv[0]) instead of - the string "python" as the *ident*. openlog() arguments are all optional - and keywords. +- Issue #8451: Syslog module now uses basename(sys.argv[0]) instead of the + string "python" as the *ident*. openlog() arguments are all optional and + keywords. -- Issue #8108: Fix the unwrap() method of SSL objects when the socket has - a non-infinite timeout. Also make that method friendlier with applications +- Issue #8108: Fix the unwrap() method of SSL objects when the socket has a + non-infinite timeout. Also make that method friendlier with applications wanting to continue using the socket in clear-text mode, by disabling OpenSSL's internal readahead. Thanks to Darryl Miles for guidance. -- Issue #8484: Load all ciphers and digest algorithms when initializing - the _ssl extension, such that verification of some SSL certificates - doesn't fail because of an "unknown algorithm". +- Issue #8484: Load all ciphers and digest algorithms when initializing the _ssl + extension, such that verification of some SSL certificates doesn't fail + because of an "unknown algorithm". - Issue #8437: Fix test_gdb failures, patch written by Dave Malcolm -- Issue #4814: timeout parameter is now applied also for connections resulting - from PORT/EPRT commands. +- Issue #4814: The timeout parameter is now applied also for connections + resulting from PORT/EPRT commands. -- Issue #8463: added missing reference to bztar in shutil's documentation. +- Issue #8463: Add missing reference to bztar in shutil's documentation. -- Issue #8438: Remove reference to the missing "surrogateescape" encoding - error handler from the new IO library. +- Issue #8438: Remove reference to the missing "surrogateescape" encoding error + handler from the new IO library. -- Issue #3817: ftplib.FTP.abort() method now considers 225 a valid response - code as stated in RFC-959 at chapter 5.4. +- Issue #3817: ftplib.FTP.abort() method now considers 225 a valid response code + as stated in RFC-959 at chapter 5.4. - Issue #8279: Fix test_gdb failures. - Issue #8322: Add a *ciphers* argument to SSL sockets, so as to change the available cipher list. Helps fix test_ssl with OpenSSL 1.0.0. -- Issue #2987: RFC2732 support for urlparse (IPv6 addresses). Patch by Tony +- Issue #2987: RFC 2732 support for urlparse (IPv6 addresses). Patch by Tony Locke and Hans Ulrich Niedermann. - Issue #7585: difflib context and unified diffs now place a tab between - filename and date, conforming to the 'standards' they were originally - designed to follow. This improves compatibility with patch tools. + filename and date, conforming to the 'standards' they were originally designed + to follow. This improves compatibility with patch tools. - Issue #7472: Fixed typo in email.encoders module; messages using ISO-2022 - character sets will now consistently use a Content-Transfer-Encoding of - 7bit rather than sometimes being marked as 8bit. + character sets will now consistently use a Content-Transfer-Encoding of 7bit + rather than sometimes being marked as 8bit. - Issue #8330: Fix expected output in test_gdb. -- Issue #8374: Update the internal alias table in the :mod:`locale` module - to cover recent locale changes and additions. +- Issue #8374: Update the internal alias table in the :mod:`locale` module to + cover recent locale changes and additions. Extension Modules ----------------- -- Issue #8644: Improved accuracy of timedelta.total_seconds(). +- Issue #8644: Improved accuracy of ``timedelta.total_seconds()``. - Use Clang 2.7's static analyzer to find places to clean up some code. - Build the ossaudio extension on GNU/kFreeBSD. -- On Windows, ctypes does no longer check the stack before and after - calling a foreign function. This allows to use the unmodified - libffi library. +- On Windows, ctypes does no longer check the stack before and after calling a + foreign function. This allows to use the unmodified libffi library. Tests ----- -- Issue #8672: Add a zlib test ensuring that an incomplete stream can be - handled by a decompressor object without errors (it returns incomplete - uncompressed data). +- Issue #8672: Add a zlib test ensuring that an incomplete stream can be handled + by a decompressor object without errors (it returns incomplete uncompressed + data). -- Issue #8490: asyncore now has a more solid test suite which actually tests - its API. +- Issue #8490: asyncore now has a more solid test suite which actually tests its + API. - Issue #8576: Remove use of find_unused_port() in test_smtplib and test_multiprocessing. Patch by Paul Moore. -- Issue #7449: Fix many tests to support Python compiled without thread - support. Patches written by Jerry Seutter. +- Issue #7449: Fix many tests to support Python compiled without thread support. + Patches written by Jerry Seutter. -- Issue #8108: test_ftplib's non-blocking SSL server now has proper handling - of SSL shutdowns. +- Issue #8108: test_ftplib's non-blocking SSL server now has proper handling of + SSL shutdowns. Build ----- -- Issue #8625: Turn off optimization in --with-pydebug builds with gcc. +- Issue #8625: Turn off optimization in ``--with-pydebug`` builds with gcc. (Optimization was unintentionally turned on in gcc --with-pydebug builds in 2.7 beta1 as a result of the issue #1628484 fix, combined with autoconf's strange choice of default CFLAGS produced by AC_PROG_CC for gcc.) - Issue #8509: Fix quoting in help strings and code snippets in configure.in. -- Issue #3646: It is now easily possible to install a Python framework into - your home directory on MacOSX, see Mac/README for more information. +- Issue #3646: It is now easily possible to install a Python framework into your + home directory on Mac OS X, see Mac/README for more information. -- Issue #8510: Update to autoconf2.65. +- Issue #8510: Update to autoconf 2.65. Misc ---- @@ -316,29 +312,28 @@ - Issue #8329: Don't return the same lists from select.select when no fds are changed. -- Issue #8259: 1L << (2**31) no longer produces an 'outrageous shift error' +- Issue #8259: ``1L << (2**31)`` no longer produces an 'outrageous shift error' on 64-bit machines. The shift count for either left or right shift is permitted to be up to sys.maxsize. - Ensure that tokenization of identifiers is not affected by locale. -- Issue #1222585: Added LDCXXSHARED for C++ support. Patch by Arfrever. +- Issue #1222585: Added LDCXXSHARED for C++ support. Patch by Arfrever. - Raise a TypeError when trying to delete a T_STRING_INPLACE struct member. -- Issue #7994: Issue a PendingDeprecationWarning if object.__format__ - is called with a non-empty format string. This is an effort to - future-proof user code. If a derived class does not currently - implement __format__ but later adds its own __format__, it would - most likely break user code that had supplied a format string. This - will be changed to a DeprecationWaring in Python 3.3 and it will be - an error in Python 3.4. +- Issue #7994: Issue a PendingDeprecationWarning if object.__format__ is called + with a non-empty format string. This is an effort to future-proof user + code. If a derived class does not currently implement __format__ but later + adds its own __format__, it would most likely break user code that had + supplied a format string. This will be changed to a DeprecationWaring in + Python 3.3 and it will be an error in Python 3.4. - Issue #8268: Old-style classes (not just instances) now support weak references. -- Issue #8211: Save/restore CFLAGS around AC_PROG_CC in configure.in, in - case it is set. +- Issue #8211: Save/restore CFLAGS around AC_PROG_CC in configure.in, in case it + is set. - Issue #1583863: An unicode subclass can now override the __unicode__ method @@ -360,55 +355,54 @@ - Issue #5277: Fix quote counting when parsing RFC 2231 encoded parameters. - Issue #8321: Give access to OpenSSL version numbers from the `ssl` module, - using the new attributes `ssl.OPENSSL_VERSION`, `ssl.OPENSSL_VERSION_INFO` - and `ssl.OPENSSL_VERSION_NUMBER`. + using the new attributes `ssl.OPENSSL_VERSION`, `ssl.OPENSSL_VERSION_INFO` and + `ssl.OPENSSL_VERSION_NUMBER`. - Issue #8310: Allow dis to examine new style classes. -- Issue #8257: The Decimal construct now accepts a float instance - directly, converting that float to a Decimal of equal value: +- Issue #8257: The Decimal construct now accepts a float instance directly, + converting that float to a Decimal of equal value: >>> Decimal(1.1) Decimal('1.100000000000000088817841970012523233890533447265625') - collections.Counter() now supports a subtract() method. -- the functools module now has a total_ordering() class decorator - to simplify the specification of rich comparisons. +- The functools module now has a total_ordering() class decorator to simplify + the specification of rich comparisons. -- The functools module also adds cmp_to_key() as a tool to transition - old-style comparison functions to new-style key-functions. +- The functools module also adds cmp_to_key() as a tool to transition old-style + comparison functions to new-style key-functions. -- Issue #8294: The Fraction constructor now accepts Decimal and float - instances directly. +- Issue #8294: The Fraction constructor now accepts Decimal and float instances + directly. -- Issue #7279: Comparisons involving a Decimal signaling NaN now - signal InvalidOperation instead of returning False. (Comparisons - involving a quiet NaN are unchanged.) Also, Decimal quiet NaNs - are now hashable; Decimal signaling NaNs remain unhashable. - -- Issue #2531: Comparison operations between floats and Decimal - instances now return a result based on the numeric values of the - operands; previously they returned an arbitrary result based on - the relative ordering of id(float) and id(Decimal). +- Issue #7279: Comparisons involving a Decimal signaling NaN now signal + InvalidOperation instead of returning False. (Comparisons involving a quiet + NaN are unchanged.) Also, Decimal quiet NaNs are now hashable; Decimal + signaling NaNs remain unhashable. + +- Issue #2531: Comparison operations between floats and Decimal instances now + return a result based on the numeric values of the operands; previously they + returned an arbitrary result based on the relative ordering of id(float) and + id(Decimal). - Issue #8233: When run as a script, py_compile.py optionally takes a single - argument `-` which tells it to read files to compile from stdin. Each line - is read on demand and the named file is compiled immediately. (Original - patch by Piotr O?arowski). + argument `-` which tells it to read files to compile from stdin. Each line is + read on demand and the named file is compiled immediately. (Original patch by + Piotr O?arowski). -- Issue #3135: Add inspect.getcallargs, which binds arguments to a function - like a normal call. +- Issue #3135: Add ``inspect.getcallargs()``, which binds arguments to a + function like a normal call. - Backwards incompatible change: Unicode codepoints line tabulation (0x0B) and form feed (0x0C) are now considered linebreaks, as specified in Unicode - Standard Annex #14. See issue #7643. - http://www.unicode.org/reports/tr14/ + Standard Annex #14. See issue #7643. http://www.unicode.org/reports/tr14/ -- Comparisons using one of <, <=, >, >= between a complex instance and - a Fractions instance now raise TypeError instead of returning - True/False. This makes Fraction <=> complex comparisons consistent with - int <=> complex, float <=> complex, and complex <=> complex comparisons. +- Comparisons using one of <, <=, >, >= between a complex instance and a + Fractions instance now raise TypeError instead of returning True/False. This + makes Fraction <=> complex comparisons consistent with int <=> complex, float + <=> complex, and complex <=> complex comparisons. - Addition of ``WeakSet`` to the ``weakref`` module. @@ -420,24 +414,24 @@ - Issue #7667: Fix doctest failures with non-ASCII paths. - Issue #7512: shutil.copystat() could raise an OSError when the filesystem - didn't support chflags() (for example ZFS under FreeBSD). The error is - now silenced. + didn't support chflags() (for example ZFS under FreeBSD). The error is now + silenced. - Issue #7703: ctypes supports both buffer() and memoryview(). The former is deprecated. -- Issue #7860: platform.uname now reports the correct 'machine' type - when Python is running in WOW64 mode on 64 bit Windows. +- Issue #7860: platform.uname now reports the correct 'machine' type when Python + is running in WOW64 mode on 64 bit Windows. -- logging: Added getChild utility method to Logger and added isEnabledFor - method to LoggerAdapter. +- logging: Added getChild utility method to Logger and added isEnabledFor method + to LoggerAdapter. -- Issue #8201: logging: Handle situation of non-ASCII and Unicode - logger names existing at the same time, causing a Unicode error - when configuration code attempted to sort the existing loggers. +- Issue #8201: logging: Handle situation of non-ASCII and Unicode logger names + existing at the same time, causing a Unicode error when configuration code + attempted to sort the existing loggers. -- Issue #8200: logging: Handle errors when multiprocessing is not - fully loaded when logging occurs. +- Issue #8200: logging: Handle errors when multiprocessing is not fully loaded + when logging occurs. - Issue #3890, #8222: Fix recv() and recv_into() on non-blocking SSL sockets. Also, enable the SSL_MODE_AUTO_RETRY flag on SSL sockets, so that blocking @@ -447,26 +441,26 @@ - Issue #8024: Update the Unicode database to 5.2. -- Issue #8104: socket.recv_into() and socket.recvfrom_into() now support - writing into objects supporting the new buffer API, for example bytearrays - or memoryviews. +- Issue #8104: socket.recv_into() and socket.recvfrom_into() now support writing + into objects supporting the new buffer API, for example bytearrays or + memoryviews. - Issue #4961: Inconsistent/wrong result of askyesno function in tkMessageBox with Tcl/Tk-8.5. -- Issue #8140: extend compileall to compile single files. Add -i option. +- Issue #8140: Extend compileall to compile single files. Add -i option. -- Issue #7356: ctypes.util: Make parsing of ldconfig output independent of - the locale. +- Issue #7356: ctypes.util: Make parsing of ldconfig output independent of the + locale. -- Issue #7774: Set sys.executable to an empty string if ``argv[0]`` has been - set to an non existent program name and Python is unable to retrieve the real +- Issue #7774: Set sys.executable to an empty string if ``argv[0]`` has been set + to an non existent program name and Python is unable to retrieve the real program name. - Issue #8117: logging: Improved algorithm for computing initial rollover time - for ``TimedRotatingFileHandler`` by using the modification time of an - existing log file to compute the next rollover time. If the log file does - not exist, the current time is used as the basis for the computation. + for ``TimedRotatingFileHandler`` by using the modification time of an existing + log file to compute the next rollover time. If the log file does not exist, + the current time is used as the basis for the computation. - Issue #6472: The ``xml.etree`` package is updated to ElementTree 1.3. The cElementTree module is updated too. @@ -500,8 +494,8 @@ - Issue #1039, #8154: Fix os.execlp() crash with missing 2nd argument. - Issue #8156: bsddb module updated to version 4.8.4. - http://www.jcea.es/programacion/pybsddb.htm#bsddb3-4.8.4. - This update drops support for Berkeley DB 4.0, and adds support for 4.8. + http://www.jcea.es/programacion/pybsddb.htm#bsddb3-4.8.4. This update drops + support for Berkeley DB 4.0, and adds support for 4.8. - Issue #3928: os.mknod() now available in Solaris, also. @@ -515,13 +509,13 @@ - Issue #1530559: When passing a non-integer argument to struct.pack with *any* integer format code (one of 'bBhHiIlLqQ'), struct.pack attempts to use the argument's __int__ method to convert to an integer before packing. It also - produces a DeprecationWarning in this case. (In Python 2.6, the behaviour - was inconsistent: __int__ was used for some integer codes but not for others, - and the set of integer codes for which it was used differed between native - packing and standard packing.) + produces a DeprecationWarning in this case. (In Python 2.6, the behaviour was + inconsistent: __int__ was used for some integer codes but not for others, and + the set of integer codes for which it was used differed between native packing + and standard packing.) -- Issue #7347: _winreg: Add CreateKeyEx and DeleteKeyEx, as well as fix a - bug in the return value of QueryReflectionKey. +- Issue #7347: _winreg: Add CreateKeyEx and DeleteKeyEx, as well as fix a bug in + the return value of QueryReflectionKey. Tools/Demos ----------- @@ -535,12 +529,12 @@ Build ----- -- Issue #8032: For gdb7, a python-gdb.py file is added to the build, - allowing to use advanced gdb features when debugging Python. +- Issue #8032: For gdb7, a python-gdb.py file is added to the build, allowing to + use advanced gdb features when debugging Python. -- Issue #1628484: The Makefile doesn't ignore the CFLAGS environment - variable anymore. It also forwards the LDFLAGS settings to the linker - when building a shared library. +- Issue #1628484: The Makefile doesn't ignore the CFLAGS environment variable + anymore. It also forwards the LDFLAGS settings to the linker when building a + shared library. - Issue #6716: Quote -x arguments of compileall in MSI installer. @@ -553,19 +547,19 @@ ----- - Issue #8276: PyEval_CallObject() is now only available in macro form. The - function declaration, which was kept for backwards compatibility reasons, - is now removed (the macro was introduced in 1997!). + function declaration, which was kept for backwards compatibility reasons, is + now removed (the macro was introduced in 1997!). -- Issue #7992: A replacement PyCObject API, PyCapsule, has been backported - from Python 3.1. All existing Python CObjects in the main distribution - have been converted to capsules. To address backwards-compatibility - concerns, PyCObject_AsVoidPtr() was changed to understand capsules. +- Issue #7992: A replacement PyCObject API, PyCapsule, has been backported from + Python 3.1. All existing Python CObjects in the main distribution have been + converted to capsules. To address backwards-compatibility concerns, + PyCObject_AsVoidPtr() was changed to understand capsules. Tests ----- -- Issue #3864: Skip three test_signal tests on freebsd6 because they fail - if any thread was previously started, most likely due to a platform bug. +- Issue #3864: Skip three test_signal tests on freebsd6 because they fail if any + thread was previously started, most likely due to a platform bug. - Issue #8348: Fix test ftp url in test_urllib2net. @@ -583,8 +577,8 @@ - Issue #8180 and #8207: Fix test_pep277 on OS X and add more tests for special Unicode normalization cases. -- Issue #7783: test.test_support.open_urlresource invalidates the outdated - files from the local cache. +- Issue #7783: test.test_support.open_urlresource invalidates the outdated files + from the local cache. What's New in Python 2.7 alpha 4? From python-checkins at python.org Sat May 22 23:28:59 2010 From: python-checkins at python.org (tarek.ziade) Date: Sat, 22 May 2010 23:28:59 +0200 Subject: [Python-checkins] distutils2: replaced get_next_sibling() calls by next_sibling (>=2.6.5rc2) Message-ID: tarek.ziade pushed 105229c23a6a to distutils2: http://hg.python.org/distutils2/rev/105229c23a6a changeset: 155:105229c23a6a tag: tip user: Tarek Ziade date: Sat May 22 23:28:50 2010 +0200 summary: replaced get_next_sibling() calls by next_sibling (>=2.6.5rc2) files: src/distutils2/converter/fixers/fix_imports.py, src/distutils2/converter/fixers/fix_setup_options.py diff --git a/src/distutils2/converter/fixers/fix_imports.py b/src/distutils2/converter/fixers/fix_imports.py --- a/src/distutils2/converter/fixers/fix_imports.py +++ b/src/distutils2/converter/fixers/fix_imports.py @@ -31,10 +31,10 @@ if imp.value == 'setuptools': # catching "from setuptools import setup" pattern = [] - next = imp.get_next_sibling() + next = imp.next_sibling while next is not None: pattern.append(next.value) - next = next.get_next_sibling() + next = next.next_sibling if pattern == ['import', 'setup']: imp.value = 'distutils2.core' imp.changed() diff --git a/src/distutils2/converter/fixers/fix_setup_options.py b/src/distutils2/converter/fixers/fix_setup_options.py --- a/src/distutils2/converter/fixers/fix_setup_options.py +++ b/src/distutils2/converter/fixers/fix_setup_options.py @@ -41,15 +41,14 @@ def _fix_name(self, argument, remove_list): name = argument.children[0] - next = name.get_next_sibling - sibling = next() + sibling = name.next_sibling if sibling is None or sibling.type != token.EQUAL: return False if name.value in _OLD_NAMES: name.value = _OLD_NAMES[name.value] if name.value in _SEQUENCE_NAMES: - right_operand = next().get_next_sibling() + right_operand = sibling.next_sibling # replacing string -> list[string] if right_operand.type == token.STRING: # we want this to be a list now -- Repository URL: http://hg.python.org/distutils2 From python-checkins at python.org Sat May 22 23:39:46 2010 From: python-checkins at python.org (tarek.ziade) Date: Sat, 22 May 2010 23:39:46 +0200 Subject: [Python-checkins] distutils2: removed more dead code related to RPMs Message-ID: tarek.ziade pushed 4310eca1971e to distutils2: http://hg.python.org/distutils2/rev/4310eca1971e changeset: 158:4310eca1971e user: Yannick Gingras date: Sat May 22 17:37:17 2010 -0400 summary: removed more dead code related to RPMs files: src/distutils2/command/bdist.py diff --git a/src/distutils2/command/bdist.py b/src/distutils2/command/bdist.py --- a/src/distutils2/command/bdist.py +++ b/src/distutils2/command/bdist.py @@ -127,8 +127,6 @@ for i in range(len(self.formats)): cmd_name = commands[i] sub_cmd = self.reinitialize_command(cmd_name) - if cmd_name not in self.no_format_option: - sub_cmd.format = self.formats[i] # passing the owner and group names for tar archiving if cmd_name == 'bdist_dumb': -- Repository URL: http://hg.python.org/distutils2 From python-checkins at python.org Sat May 22 23:39:45 2010 From: python-checkins at python.org (tarek.ziade) Date: Sat, 22 May 2010 23:39:45 +0200 Subject: [Python-checkins] distutils2: fixed test for the removal of the rpm support Message-ID: tarek.ziade pushed f07ceccc1055 to distutils2: http://hg.python.org/distutils2/rev/f07ceccc1055 changeset: 157:f07ceccc1055 user: Yannick Gingras date: Sat May 22 17:21:56 2010 -0400 summary: fixed test for the removal of the rpm support files: src/distutils2/tests/test_bdist.py diff --git a/src/distutils2/tests/test_bdist.py b/src/distutils2/tests/test_bdist.py --- a/src/distutils2/tests/test_bdist.py +++ b/src/distutils2/tests/test_bdist.py @@ -31,8 +31,7 @@ # XXX an explicit list in bdist is # not the best way to bdist_* commands # we should add a registry - formats = ['rpm', 'zip', 'gztar', 'bztar', 'ztar', - 'tar', 'wininst', 'msi'] + formats = ['zip', 'gztar', 'bztar', 'ztar', 'tar', 'wininst', 'msi'] formats.sort() founded = cmd.format_command.keys() founded.sort() -- Repository URL: http://hg.python.org/distutils2 From python-checkins at python.org Sat May 22 23:39:45 2010 From: python-checkins at python.org (tarek.ziade) Date: Sat, 22 May 2010 23:39:45 +0200 Subject: [Python-checkins] distutils2: removed remaining bits from 'bdist_rpm' Message-ID: tarek.ziade pushed 19f1965a304d to distutils2: http://hg.python.org/distutils2/rev/19f1965a304d changeset: 156:19f1965a304d parent: 154:7eff59171017 user: Yannick Gingras date: Sat May 22 17:17:54 2010 -0400 summary: removed remaining bits from 'bdist_rpm' files: src/distutils2/command/__init__.py, src/distutils2/command/bdist.py, src/distutils2/command/upload.py diff --git a/src/distutils2/command/__init__.py b/src/distutils2/command/__init__.py --- a/src/distutils2/command/__init__.py +++ b/src/distutils2/command/__init__.py @@ -20,7 +20,6 @@ 'register', 'bdist', 'bdist_dumb', - 'bdist_rpm', 'bdist_wininst', 'upload', 'check', diff --git a/src/distutils2/command/bdist.py b/src/distutils2/command/bdist.py --- a/src/distutils2/command/bdist.py +++ b/src/distutils2/command/bdist.py @@ -55,9 +55,6 @@ "lists available distribution formats", show_formats), ] - # The following commands do not take a format option from bdist - no_format_option = ('bdist_rpm',) - # This won't do in reality: will need to distinguish RPM-ish Linux, # Debian-ish Linux, Solaris, FreeBSD, ..., Windows, Mac OS. default_format = {'posix': 'gztar', @@ -69,8 +66,7 @@ 'wininst', 'zip', 'msi'] # And the real information. - format_command = {'rpm': ('bdist_rpm', "RPM distribution"), - 'gztar': ('bdist_dumb', "gzip'ed tar file"), + format_command = {'gztar': ('bdist_dumb', "gzip'ed tar file"), 'bztar': ('bdist_dumb', "bzip2'ed tar file"), 'ztar': ('bdist_dumb', "compressed tar file"), 'tar': ('bdist_dumb', "tar file"), diff --git a/src/distutils2/command/upload.py b/src/distutils2/command/upload.py --- a/src/distutils2/command/upload.py +++ b/src/distutils2/command/upload.py @@ -96,11 +96,7 @@ data['md5_digest'] = md5(content).hexdigest() comment = '' - if command == 'bdist_rpm': - dist, version, id = platform.dist() - if dist: - comment = 'built for %s %s' % (dist, version) - elif command == 'bdist_dumb': + if command == 'bdist_dumb': comment = 'built for %s' % platform.platform(terse=1) data['comment'] = comment -- Repository URL: http://hg.python.org/distutils2 From python-checkins at python.org Sat May 22 23:39:46 2010 From: python-checkins at python.org (tarek.ziade) Date: Sat, 22 May 2010 23:39:46 +0200 Subject: [Python-checkins] distutils2: merged Yannick work Message-ID: tarek.ziade pushed ddb6eda2abd7 to distutils2: http://hg.python.org/distutils2/rev/ddb6eda2abd7 changeset: 159:ddb6eda2abd7 tag: tip parent: 155:105229c23a6a parent: 158:4310eca1971e user: Tarek Ziade date: Sat May 22 23:39:02 2010 +0200 summary: merged Yannick work files: diff --git a/src/distutils2/command/__init__.py b/src/distutils2/command/__init__.py --- a/src/distutils2/command/__init__.py +++ b/src/distutils2/command/__init__.py @@ -20,7 +20,6 @@ 'register', 'bdist', 'bdist_dumb', - 'bdist_rpm', 'bdist_wininst', 'upload', 'check', diff --git a/src/distutils2/command/bdist.py b/src/distutils2/command/bdist.py --- a/src/distutils2/command/bdist.py +++ b/src/distutils2/command/bdist.py @@ -55,9 +55,6 @@ "lists available distribution formats", show_formats), ] - # The following commands do not take a format option from bdist - no_format_option = ('bdist_rpm',) - # This won't do in reality: will need to distinguish RPM-ish Linux, # Debian-ish Linux, Solaris, FreeBSD, ..., Windows, Mac OS. default_format = {'posix': 'gztar', @@ -69,8 +66,7 @@ 'wininst', 'zip', 'msi'] # And the real information. - format_command = {'rpm': ('bdist_rpm', "RPM distribution"), - 'gztar': ('bdist_dumb', "gzip'ed tar file"), + format_command = {'gztar': ('bdist_dumb', "gzip'ed tar file"), 'bztar': ('bdist_dumb', "bzip2'ed tar file"), 'ztar': ('bdist_dumb', "compressed tar file"), 'tar': ('bdist_dumb', "tar file"), @@ -131,8 +127,6 @@ for i in range(len(self.formats)): cmd_name = commands[i] sub_cmd = self.reinitialize_command(cmd_name) - if cmd_name not in self.no_format_option: - sub_cmd.format = self.formats[i] # passing the owner and group names for tar archiving if cmd_name == 'bdist_dumb': diff --git a/src/distutils2/command/upload.py b/src/distutils2/command/upload.py --- a/src/distutils2/command/upload.py +++ b/src/distutils2/command/upload.py @@ -96,11 +96,7 @@ data['md5_digest'] = md5(content).hexdigest() comment = '' - if command == 'bdist_rpm': - dist, version, id = platform.dist() - if dist: - comment = 'built for %s %s' % (dist, version) - elif command == 'bdist_dumb': + if command == 'bdist_dumb': comment = 'built for %s' % platform.platform(terse=1) data['comment'] = comment diff --git a/src/distutils2/tests/test_bdist.py b/src/distutils2/tests/test_bdist.py --- a/src/distutils2/tests/test_bdist.py +++ b/src/distutils2/tests/test_bdist.py @@ -31,8 +31,7 @@ # XXX an explicit list in bdist is # not the best way to bdist_* commands # we should add a registry - formats = ['rpm', 'zip', 'gztar', 'bztar', 'ztar', - 'tar', 'wininst', 'msi'] + formats = ['zip', 'gztar', 'bztar', 'ztar', 'tar', 'wininst', 'msi'] formats.sort() founded = cmd.format_command.keys() founded.sort() -- Repository URL: http://hg.python.org/distutils2 From solipsis at pitrou.net Sun May 23 01:23:34 2010 From: solipsis at pitrou.net (solipsis at pitrou.net) Date: Sun, 23 May 2010 01:23:34 +0200 (CEST) Subject: [Python-checkins] Daily py3k reference leaks (r81481): sum=0 Message-ID: <20100522232334.A97461771F@ns6635.ovh.net> py3k results for svn r81481 (hg cset 5c9709acc7c4) -------------------------------------------------- Command line was: ['./python', '-m', 'test.regrtest', '-uall', '-R', '3:3:/home/antoine/py3k/refleaks/refloguFqTUF', '-x'] From python-checkins at python.org Sun May 23 15:26:49 2010 From: python-checkins at python.org (mark.dickinson) Date: Sun, 23 May 2010 15:26:49 +0200 (CEST) Subject: [Python-checkins] r81485 - python/branches/py3k/Misc/NEWS Message-ID: <20100523132649.5F078EE983@mail.python.org> Author: mark.dickinson Date: Sun May 23 15:26:48 2010 New Revision: 81485 Log: Remove duplicate NEWS entry. Modified: python/branches/py3k/Misc/NEWS Modified: python/branches/py3k/Misc/NEWS ============================================================================== --- python/branches/py3k/Misc/NEWS (original) +++ python/branches/py3k/Misc/NEWS Sun May 23 15:26:48 2010 @@ -19,12 +19,6 @@ to unpredictable exceptions when combining integers and complex objects in sets or dicts. -- Issue #8748: Fix comparisons between complex and integer objects. - These used to convert the integer object to a complex number before - doing the comparison, giving a potentially incorrect result when - that conversion involved precision loss. (Ex: 2**53+1 == - complex(2**53) returned True; now returns False.) - - Issue #8766: Initialize _warnings module before importing the first module. Fix a crash if an empty directory called "encodings" exists in sys.path. From python-checkins at python.org Sun May 23 15:33:13 2010 From: python-checkins at python.org (mark.dickinson) Date: Sun, 23 May 2010 15:33:13 +0200 (CEST) Subject: [Python-checkins] r81486 - in python/branches/py3k: Doc/library/stdtypes.rst Doc/library/sys.rst Include/pyport.h Lib/decimal.py Lib/fractions.py Lib/test/test_float.py Lib/test/test_numeric_tower.py Lib/test/test_sys.py Misc/NEWS Objects/complexobject.c Objects/longobject.c Objects/object.c Objects/typeobject.c Python/sysmodule.c Message-ID: <20100523133313.6C109EE984@mail.python.org> Author: mark.dickinson Date: Sun May 23 15:33:13 2010 New Revision: 81486 Log: Issue #8188: Introduce a new scheme for computing hashes of numbers (instances of int, float, complex, decimal.Decimal and fractions.Fraction) that makes it easy to maintain the invariant that hash(x) == hash(y) whenever x and y have equal value. Added: python/branches/py3k/Lib/test/test_numeric_tower.py Modified: python/branches/py3k/Doc/library/stdtypes.rst python/branches/py3k/Doc/library/sys.rst python/branches/py3k/Include/pyport.h python/branches/py3k/Lib/decimal.py python/branches/py3k/Lib/fractions.py python/branches/py3k/Lib/test/test_float.py python/branches/py3k/Lib/test/test_sys.py python/branches/py3k/Misc/NEWS python/branches/py3k/Objects/complexobject.c python/branches/py3k/Objects/longobject.c python/branches/py3k/Objects/object.c python/branches/py3k/Objects/typeobject.c python/branches/py3k/Python/sysmodule.c Modified: python/branches/py3k/Doc/library/stdtypes.rst ============================================================================== --- python/branches/py3k/Doc/library/stdtypes.rst (original) +++ python/branches/py3k/Doc/library/stdtypes.rst Sun May 23 15:33:13 2010 @@ -595,6 +595,109 @@ '0x1.d380000000000p+11' +.. _numeric-hash: + +Hashing of numeric types +------------------------ + +For numbers ``x`` and ``y``, possibly of different types, it's a requirement +that ``hash(x) == hash(y)`` whenever ``x == y`` (see the :meth:`__hash__` +method documentation for more details). For ease of implementation and +efficiency across a variety of numeric types (including :class:`int`, +:class:`float`, :class:`decimal.Decimal` and :class:`fractions.Fraction`) +Python's hash for numeric types is based on a single mathematical function +that's defined for any rational number, and hence applies to all instances of +:class:`int` and :class:`fraction.Fraction`, and all finite instances of +:class:`float` and :class:`decimal.Decimal`. Essentially, this function is +given by reduction modulo ``P`` for a fixed prime ``P``. The value of ``P`` is +made available to Python as the :attr:`modulus` attribute of +:data:`sys.hash_info`. + +.. impl-detail:: + + Currently, the prime used is ``P = 2**31 - 1`` on machines with 32-bit C + longs and ``P = 2**61 - 1`` on machines with 64-bit C longs. + +Here are the rules in detail: + + - If ``x = m / n`` is a nonnegative rational number and ``n`` is not divisible + by ``P``, define ``hash(x)`` as ``m * invmod(n, P) % P``, where ``invmod(n, + P)`` gives the inverse of ``n`` modulo ``P``. + + - If ``x = m / n`` is a nonnegative rational number and ``n`` is + divisible by ``P`` (but ``m`` is not) then ``n`` has no inverse + modulo ``P`` and the rule above doesn't apply; in this case define + ``hash(x)`` to be the constant value ``sys.hash_info.inf``. + + - If ``x = m / n`` is a negative rational number define ``hash(x)`` + as ``-hash(-x)``. If the resulting hash is ``-1``, replace it with + ``-2``. + + - The particular values ``sys.hash_info.inf``, ``-sys.hash_info.inf`` + and ``sys.hash_info.nan`` are used as hash values for positive + infinity, negative infinity, or nans (respectively). (All hashable + nans have the same hash value.) + + - For a :class:`complex` number ``z``, the hash values of the real + and imaginary parts are combined by computing ``hash(z.real) + + sys.hash_info.imag * hash(z.imag)``, reduced modulo + ``2**sys.hash_info.width`` so that it lies in + ``range(-2**(sys.hash_info.width - 1), 2**(sys.hash_info.width - + 1))``. Again, if the result is ``-1``, it's replaced with ``-2``. + + +To clarify the above rules, here's some example Python code, +equivalent to the builtin hash, for computing the hash of a rational +number, :class:`float`, or :class:`complex`:: + + + import sys, math + + def hash_fraction(m, n): + """Compute the hash of a rational number m / n. + + Assumes m and n are integers, with n positive. + Equivalent to hash(fractions.Fraction(m, n)). + + """ + P = sys.hash_info.modulus + # Remove common factors of P. (Unnecessary if m and n already coprime.) + while m % P == n % P == 0: + m, n = m // P, n // P + + if n % P == 0: + hash_ = sys.hash_info.inf + else: + # Fermat's Little Theorem: pow(n, P-1, P) is 1, so + # pow(n, P-2, P) gives the inverse of n modulo P. + hash_ = (abs(m) % P) * pow(n, P - 2, P) % P + if m < 0: + hash_ = -hash_ + if hash_ == -1: + hash_ = -2 + return hash_ + + def hash_float(x): + """Compute the hash of a float x.""" + + if math.isnan(x): + return sys.hash_info.nan + elif math.isinf(x): + return sys.hash_info.inf if x > 0 else -sys.hash_info.inf + else: + return hash_fraction(*x.as_integer_ratio()) + + def hash_complex(z): + """Compute the hash of a complex number z.""" + + hash_ = hash_float(z.real) + sys.hash_info.imag * hash_float(z.imag) + # do a signed reduction modulo 2**sys.hash_info.width + M = 2**(sys.hash_info.width - 1) + hash_ = (hash_ & (M - 1)) - (hash & M) + if hash_ == -1: + hash_ == -2 + return hash_ + .. _typeiter: Iterator Types Modified: python/branches/py3k/Doc/library/sys.rst ============================================================================== --- python/branches/py3k/Doc/library/sys.rst (original) +++ python/branches/py3k/Doc/library/sys.rst Sun May 23 15:33:13 2010 @@ -446,6 +446,30 @@ Changed to a named tuple and added *service_pack_minor*, *service_pack_major*, *suite_mask*, and *product_type*. + +.. data:: hash_info + + A structseq giving parameters of the numeric hash implementation. For + more details about hashing of numeric types, see :ref:`numeric-hash`. + + +---------------------+--------------------------------------------------+ + | attribute | explanation | + +=====================+==================================================+ + | :const:`width` | width in bits used for hash values | + +---------------------+--------------------------------------------------+ + | :const:`modulus` | prime modulus P used for numeric hash scheme | + +---------------------+--------------------------------------------------+ + | :const:`inf` | hash value returned for a positive infinity | + +---------------------+--------------------------------------------------+ + | :const:`nan` | hash value returned for a nan | + +---------------------+--------------------------------------------------+ + | :const:`imag` | multiplier used for the imaginary part of a | + | | complex number | + +---------------------+--------------------------------------------------+ + + .. versionadded:: 3.2 + + .. data:: hexversion The version number encoded as a single integer. This is guaranteed to increase Modified: python/branches/py3k/Include/pyport.h ============================================================================== --- python/branches/py3k/Include/pyport.h (original) +++ python/branches/py3k/Include/pyport.h Sun May 23 15:33:13 2010 @@ -126,6 +126,20 @@ #endif #endif +/* Parameters used for the numeric hash implementation. See notes for + _PyHash_Double in Objects/object.c. Numeric hashes are based on + reduction modulo the prime 2**_PyHASH_BITS - 1. */ + +#if SIZEOF_LONG >= 8 +#define _PyHASH_BITS 61 +#else +#define _PyHASH_BITS 31 +#endif +#define _PyHASH_MODULUS ((1UL << _PyHASH_BITS) - 1) +#define _PyHASH_INF 314159 +#define _PyHASH_NAN 0 +#define _PyHASH_IMAG 1000003UL + /* uintptr_t is the C9X name for an unsigned integral type such that a * legitimate void* can be cast to uintptr_t and then back to void* again * without loss of information. Similarly for intptr_t, wrt a signed Modified: python/branches/py3k/Lib/decimal.py ============================================================================== --- python/branches/py3k/Lib/decimal.py (original) +++ python/branches/py3k/Lib/decimal.py Sun May 23 15:33:13 2010 @@ -862,7 +862,7 @@ # that specified by IEEE 754. def __eq__(self, other, context=None): - other = _convert_other(other, allow_float=True) + other = _convert_other(other, allow_float = True) if other is NotImplemented: return other if self._check_nans(other, context): @@ -870,7 +870,7 @@ return self._cmp(other) == 0 def __ne__(self, other, context=None): - other = _convert_other(other, allow_float=True) + other = _convert_other(other, allow_float = True) if other is NotImplemented: return other if self._check_nans(other, context): @@ -879,7 +879,7 @@ def __lt__(self, other, context=None): - other = _convert_other(other, allow_float=True) + other = _convert_other(other, allow_float = True) if other is NotImplemented: return other ans = self._compare_check_nans(other, context) @@ -888,7 +888,7 @@ return self._cmp(other) < 0 def __le__(self, other, context=None): - other = _convert_other(other, allow_float=True) + other = _convert_other(other, allow_float = True) if other is NotImplemented: return other ans = self._compare_check_nans(other, context) @@ -897,7 +897,7 @@ return self._cmp(other) <= 0 def __gt__(self, other, context=None): - other = _convert_other(other, allow_float=True) + other = _convert_other(other, allow_float = True) if other is NotImplemented: return other ans = self._compare_check_nans(other, context) @@ -906,7 +906,7 @@ return self._cmp(other) > 0 def __ge__(self, other, context=None): - other = _convert_other(other, allow_float=True) + other = _convert_other(other, allow_float = True) if other is NotImplemented: return other ans = self._compare_check_nans(other, context) @@ -935,55 +935,28 @@ def __hash__(self): """x.__hash__() <==> hash(x)""" - # Decimal integers must hash the same as the ints - # - # The hash of a nonspecial noninteger Decimal must depend only - # on the value of that Decimal, and not on its representation. - # For example: hash(Decimal('100E-1')) == hash(Decimal('10')). - - # Equality comparisons involving signaling nans can raise an - # exception; since equality checks are implicitly and - # unpredictably used when checking set and dict membership, we - # prevent signaling nans from being used as set elements or - # dict keys by making __hash__ raise an exception. + + # In order to make sure that the hash of a Decimal instance + # agrees with the hash of a numerically equal integer, float + # or Fraction, we follow the rules for numeric hashes outlined + # in the documentation. (See library docs, 'Built-in Types'). if self._is_special: if self.is_snan(): raise TypeError('Cannot hash a signaling NaN value.') elif self.is_nan(): - # 0 to match hash(float('nan')) - return 0 + return _PyHASH_NAN else: - # values chosen to match hash(float('inf')) and - # hash(float('-inf')). if self._sign: - return -271828 + return -_PyHASH_INF else: - return 314159 + return _PyHASH_INF - # In Python 2.7, we're allowing comparisons (but not - # arithmetic operations) between floats and Decimals; so if - # a Decimal instance is exactly representable as a float then - # its hash should match that of the float. - self_as_float = float(self) - if Decimal.from_float(self_as_float) == self: - return hash(self_as_float) - - if self._isinteger(): - op = _WorkRep(self.to_integral_value()) - # to make computation feasible for Decimals with large - # exponent, we use the fact that hash(n) == hash(m) for - # any two nonzero integers n and m such that (i) n and m - # have the same sign, and (ii) n is congruent to m modulo - # 2**64-1. So we can replace hash((-1)**s*c*10**e) with - # hash((-1)**s*c*pow(10, e, 2**64-1). - return hash((-1)**op.sign*op.int*pow(10, op.exp, 2**64-1)) - # The value of a nonzero nonspecial Decimal instance is - # faithfully represented by the triple consisting of its sign, - # its adjusted exponent, and its coefficient with trailing - # zeros removed. - return hash((self._sign, - self._exp+len(self._int), - self._int.rstrip('0'))) + if self._exp >= 0: + exp_hash = pow(10, self._exp, _PyHASH_MODULUS) + else: + exp_hash = pow(_PyHASH_10INV, -self._exp, _PyHASH_MODULUS) + hash_ = int(self._int) * exp_hash % _PyHASH_MODULUS + return hash_ if self >= 0 else -hash_ def as_tuple(self): """Represents the number as a triple tuple. @@ -6218,6 +6191,17 @@ # _SignedInfinity[sign] is infinity w/ that sign _SignedInfinity = (_Infinity, _NegativeInfinity) +# Constants related to the hash implementation; hash(x) is based +# on the reduction of x modulo _PyHASH_MODULUS +import sys +_PyHASH_MODULUS = sys.hash_info.modulus +# hash values to use for positive and negative infinities, and nans +_PyHASH_INF = sys.hash_info.inf +_PyHASH_NAN = sys.hash_info.nan +del sys + +# _PyHASH_10INV is the inverse of 10 modulo the prime _PyHASH_MODULUS +_PyHASH_10INV = pow(10, _PyHASH_MODULUS - 2, _PyHASH_MODULUS) if __name__ == '__main__': Modified: python/branches/py3k/Lib/fractions.py ============================================================================== --- python/branches/py3k/Lib/fractions.py (original) +++ python/branches/py3k/Lib/fractions.py Sun May 23 15:33:13 2010 @@ -8,6 +8,7 @@ import numbers import operator import re +import sys __all__ = ['Fraction', 'gcd'] @@ -23,6 +24,12 @@ a, b = b, a%b return a +# Constants related to the hash implementation; hash(x) is based +# on the reduction of x modulo the prime _PyHASH_MODULUS. +_PyHASH_MODULUS = sys.hash_info.modulus +# Value to be used for rationals that reduce to infinity modulo +# _PyHASH_MODULUS. +_PyHASH_INF = sys.hash_info.inf _RATIONAL_FORMAT = re.compile(r""" \A\s* # optional whitespace at the start, then @@ -528,16 +535,22 @@ """ # XXX since this method is expensive, consider caching the result - if self._denominator == 1: - # Get integers right. - return hash(self._numerator) - # Expensive check, but definitely correct. - if self == float(self): - return hash(float(self)) + + # In order to make sure that the hash of a Fraction agrees + # with the hash of a numerically equal integer, float or + # Decimal instance, we follow the rules for numeric hashes + # outlined in the documentation. (See library docs, 'Built-in + # Types'). + + # dinv is the inverse of self._denominator modulo the prime + # _PyHASH_MODULUS, or 0 if self._denominator is divisible by + # _PyHASH_MODULUS. + dinv = pow(self._denominator, _PyHASH_MODULUS - 2, _PyHASH_MODULUS) + if not dinv: + hash_ = _PyHASH_INF else: - # Use tuple's hash to avoid a high collision rate on - # simple fractions. - return hash((self._numerator, self._denominator)) + hash_ = abs(self._numerator) * dinv % _PyHASH_MODULUS + return hash_ if self >= 0 else -hash_ def __eq__(a, b): """a == b""" Modified: python/branches/py3k/Lib/test/test_float.py ============================================================================== --- python/branches/py3k/Lib/test/test_float.py (original) +++ python/branches/py3k/Lib/test/test_float.py Sun May 23 15:33:13 2010 @@ -914,15 +914,6 @@ self.assertFalse(NAN.is_inf()) self.assertFalse((0.).is_inf()) - def test_hash_inf(self): - # the actual values here should be regarded as an - # implementation detail, but they need to be - # identical to those used in the Decimal module. - self.assertEqual(hash(float('inf')), 314159) - self.assertEqual(hash(float('-inf')), -271828) - self.assertEqual(hash(float('nan')), 0) - - fromHex = float.fromhex toHex = float.hex class HexFloatTestCase(unittest.TestCase): Added: python/branches/py3k/Lib/test/test_numeric_tower.py ============================================================================== --- (empty file) +++ python/branches/py3k/Lib/test/test_numeric_tower.py Sun May 23 15:33:13 2010 @@ -0,0 +1,151 @@ +# test interactions betwen int, float, Decimal and Fraction + +import unittest +import random +import math +import sys +import operator +from test.support import run_unittest + +from decimal import Decimal as D +from fractions import Fraction as F + +# Constants related to the hash implementation; hash(x) is based +# on the reduction of x modulo the prime _PyHASH_MODULUS. +_PyHASH_MODULUS = sys.hash_info.modulus +_PyHASH_INF = sys.hash_info.inf + +class HashTest(unittest.TestCase): + def check_equal_hash(self, x, y): + # check both that x and y are equal and that their hashes are equal + self.assertEqual(hash(x), hash(y), + "got different hashes for {!r} and {!r}".format(x, y)) + self.assertEqual(x, y) + + def test_bools(self): + self.check_equal_hash(False, 0) + self.check_equal_hash(True, 1) + + def test_integers(self): + # check that equal values hash equal + + # exact integers + for i in range(-1000, 1000): + self.check_equal_hash(i, float(i)) + self.check_equal_hash(i, D(i)) + self.check_equal_hash(i, F(i)) + + # the current hash is based on reduction modulo 2**n-1 for some + # n, so pay special attention to numbers of the form 2**n and 2**n-1. + for i in range(100): + n = 2**i - 1 + if n == int(float(n)): + self.check_equal_hash(n, float(n)) + self.check_equal_hash(-n, -float(n)) + self.check_equal_hash(n, D(n)) + self.check_equal_hash(n, F(n)) + self.check_equal_hash(-n, D(-n)) + self.check_equal_hash(-n, F(-n)) + + n = 2**i + self.check_equal_hash(n, float(n)) + self.check_equal_hash(-n, -float(n)) + self.check_equal_hash(n, D(n)) + self.check_equal_hash(n, F(n)) + self.check_equal_hash(-n, D(-n)) + self.check_equal_hash(-n, F(-n)) + + # random values of various sizes + for _ in range(1000): + e = random.randrange(300) + n = random.randrange(-10**e, 10**e) + self.check_equal_hash(n, D(n)) + self.check_equal_hash(n, F(n)) + if n == int(float(n)): + self.check_equal_hash(n, float(n)) + + def test_binary_floats(self): + # check that floats hash equal to corresponding Fractions and Decimals + + # floats that are distinct but numerically equal should hash the same + self.check_equal_hash(0.0, -0.0) + + # zeros + self.check_equal_hash(0.0, D(0)) + self.check_equal_hash(-0.0, D(0)) + self.check_equal_hash(-0.0, D('-0.0')) + self.check_equal_hash(0.0, F(0)) + + # infinities and nans + self.check_equal_hash(float('inf'), D('inf')) + self.check_equal_hash(float('-inf'), D('-inf')) + + for _ in range(1000): + x = random.random() * math.exp(random.random()*200.0 - 100.0) + self.check_equal_hash(x, D.from_float(x)) + self.check_equal_hash(x, F.from_float(x)) + + def test_complex(self): + # complex numbers with zero imaginary part should hash equal to + # the corresponding float + + test_values = [0.0, -0.0, 1.0, -1.0, 0.40625, -5136.5, + float('inf'), float('-inf')] + + for zero in -0.0, 0.0: + for value in test_values: + self.check_equal_hash(value, complex(value, zero)) + + def test_decimals(self): + # check that Decimal instances that have different representations + # but equal values give the same hash + zeros = ['0', '-0', '0.0', '-0.0e10', '000e-10'] + for zero in zeros: + self.check_equal_hash(D(zero), D(0)) + + self.check_equal_hash(D('1.00'), D(1)) + self.check_equal_hash(D('1.00000'), D(1)) + self.check_equal_hash(D('-1.00'), D(-1)) + self.check_equal_hash(D('-1.00000'), D(-1)) + self.check_equal_hash(D('123e2'), D(12300)) + self.check_equal_hash(D('1230e1'), D(12300)) + self.check_equal_hash(D('12300'), D(12300)) + self.check_equal_hash(D('12300.0'), D(12300)) + self.check_equal_hash(D('12300.00'), D(12300)) + self.check_equal_hash(D('12300.000'), D(12300)) + + def test_fractions(self): + # check special case for fractions where either the numerator + # or the denominator is a multiple of _PyHASH_MODULUS + self.assertEqual(hash(F(1, _PyHASH_MODULUS)), _PyHASH_INF) + self.assertEqual(hash(F(-1, 3*_PyHASH_MODULUS)), -_PyHASH_INF) + self.assertEqual(hash(F(7*_PyHASH_MODULUS, 1)), 0) + self.assertEqual(hash(F(-_PyHASH_MODULUS, 1)), 0) + + def test_hash_normalization(self): + # Test for a bug encountered while changing long_hash. + # + # Given objects x and y, it should be possible for y's + # __hash__ method to return hash(x) in order to ensure that + # hash(x) == hash(y). But hash(x) is not exactly equal to the + # result of x.__hash__(): there's some internal normalization + # to make sure that the result fits in a C long, and is not + # equal to the invalid hash value -1. This internal + # normalization must therefore not change the result of + # hash(x) for any x. + + class HalibutProxy: + def __hash__(self): + return hash('halibut') + def __eq__(self, other): + return other == 'halibut' + + x = {'halibut', HalibutProxy()} + self.assertEqual(len(x), 1) + + +def test_main(): + run_unittest(HashTest) + +if __name__ == '__main__': + test_main() Modified: python/branches/py3k/Lib/test/test_sys.py ============================================================================== --- python/branches/py3k/Lib/test/test_sys.py (original) +++ python/branches/py3k/Lib/test/test_sys.py Sun May 23 15:33:13 2010 @@ -426,6 +426,23 @@ self.assertEqual(type(sys.int_info.bits_per_digit), int) self.assertEqual(type(sys.int_info.sizeof_digit), int) self.assertIsInstance(sys.hexversion, int) + + self.assertEqual(len(sys.hash_info), 5) + self.assertLess(sys.hash_info.modulus, 2**sys.hash_info.width) + # sys.hash_info.modulus should be a prime; we do a quick + # probable primality test (doesn't exclude the possibility of + # a Carmichael number) + for x in range(1, 100): + self.assertEqual( + pow(x, sys.hash_info.modulus-1, sys.hash_info.modulus), + 1, + "sys.hash_info.modulus {} is a non-prime".format( + sys.hash_info.modulus) + ) + self.assertIsInstance(sys.hash_info.inf, int) + self.assertIsInstance(sys.hash_info.nan, int) + self.assertIsInstance(sys.hash_info.imag, int) + self.assertIsInstance(sys.maxsize, int) self.assertIsInstance(sys.maxunicode, int) self.assertIsInstance(sys.platform, str) Modified: python/branches/py3k/Misc/NEWS ============================================================================== --- python/branches/py3k/Misc/NEWS (original) +++ python/branches/py3k/Misc/NEWS Sun May 23 15:33:13 2010 @@ -12,6 +12,11 @@ Core and Builtins ----------------- +- Issue #8188: Introduce a new scheme for computing hashes of numbers + (instances of int, float, complex, decimal.Decimal and + fractions.Fraction) that makes it easy to maintain the invariant + that hash(x) == hash(y) whenever x and y have equal value. + - Issue #8748: Fix two issues with comparisons between complex and integer objects. (1) The comparison could incorrectly return True in some cases (2**53+1 == complex(2**53) == 2**53), breaking transivity of equality. Modified: python/branches/py3k/Objects/complexobject.c ============================================================================== --- python/branches/py3k/Objects/complexobject.c (original) +++ python/branches/py3k/Objects/complexobject.c Sun May 23 15:33:13 2010 @@ -403,12 +403,12 @@ static long complex_hash(PyComplexObject *v) { - long hashreal, hashimag, combined; - hashreal = _Py_HashDouble(v->cval.real); - if (hashreal == -1) + unsigned long hashreal, hashimag, combined; + hashreal = (unsigned long)_Py_HashDouble(v->cval.real); + if (hashreal == (unsigned long)-1) return -1; - hashimag = _Py_HashDouble(v->cval.imag); - if (hashimag == -1) + hashimag = (unsigned long)_Py_HashDouble(v->cval.imag); + if (hashimag == (unsigned long)-1) return -1; /* Note: if the imaginary part is 0, hashimag is 0 now, * so the following returns hashreal unchanged. This is @@ -416,10 +416,10 @@ * compare equal must have the same hash value, so that * hash(x + 0*j) must equal hash(x). */ - combined = hashreal + 1000003 * hashimag; - if (combined == -1) - combined = -2; - return combined; + combined = hashreal + _PyHASH_IMAG * hashimag; + if (combined == (unsigned long)-1) + combined = (unsigned long)-2; + return (long)combined; } /* This macro may return! */ Modified: python/branches/py3k/Objects/longobject.c ============================================================================== --- python/branches/py3k/Objects/longobject.c (original) +++ python/branches/py3k/Objects/longobject.c Sun May 23 15:33:13 2010 @@ -2571,18 +2571,37 @@ sign = -1; i = -(i); } - /* The following loop produces a C unsigned long x such that x is - congruent to the absolute value of v modulo ULONG_MAX. The - resulting x is nonzero if and only if v is. */ while (--i >= 0) { - /* Force a native long #-bits (32 or 64) circular shift */ - x = (x >> (8*SIZEOF_LONG-PyLong_SHIFT)) | (x << PyLong_SHIFT); + /* Here x is a quantity in the range [0, _PyHASH_MODULUS); we + want to compute x * 2**PyLong_SHIFT + v->ob_digit[i] modulo + _PyHASH_MODULUS. + + The computation of x * 2**PyLong_SHIFT % _PyHASH_MODULUS + amounts to a rotation of the bits of x. To see this, write + + x * 2**PyLong_SHIFT = y * 2**_PyHASH_BITS + z + + where y = x >> (_PyHASH_BITS - PyLong_SHIFT) gives the top + PyLong_SHIFT bits of x (those that are shifted out of the + original _PyHASH_BITS bits, and z = (x << PyLong_SHIFT) & + _PyHASH_MODULUS gives the bottom _PyHASH_BITS - PyLong_SHIFT + bits of x, shifted up. Then since 2**_PyHASH_BITS is + congruent to 1 modulo _PyHASH_MODULUS, y*2**_PyHASH_BITS is + congruent to y modulo _PyHASH_MODULUS. So + + x * 2**PyLong_SHIFT = y + z (mod _PyHASH_MODULUS). + + The right-hand side is just the result of rotating the + _PyHASH_BITS bits of x left by PyLong_SHIFT places; since + not all _PyHASH_BITS bits of x are 1s, the same is true + after rotation, so 0 <= y+z < _PyHASH_MODULUS and y + z is + the reduction of x*2**PyLong_SHIFT modulo + _PyHASH_MODULUS. */ + x = ((x << PyLong_SHIFT) & _PyHASH_MODULUS) | + (x >> (_PyHASH_BITS - PyLong_SHIFT)); x += v->ob_digit[i]; - /* If the addition above overflowed we compensate by - incrementing. This preserves the value modulo - ULONG_MAX. */ - if (x < v->ob_digit[i]) - x++; + if (x >= _PyHASH_MODULUS) + x -= _PyHASH_MODULUS; } x = x * sign; if (x == (unsigned long)-1) Modified: python/branches/py3k/Objects/object.c ============================================================================== --- python/branches/py3k/Objects/object.c (original) +++ python/branches/py3k/Objects/object.c Sun May 23 15:33:13 2010 @@ -647,63 +647,101 @@ All the utility functions (_Py_Hash*()) return "-1" to signify an error. */ +/* For numeric types, the hash of a number x is based on the reduction + of x modulo the prime P = 2**_PyHASH_BITS - 1. It's designed so that + hash(x) == hash(y) whenever x and y are numerically equal, even if + x and y have different types. + + A quick summary of the hashing strategy: + + (1) First define the 'reduction of x modulo P' for any rational + number x; this is a standard extension of the usual notion of + reduction modulo P for integers. If x == p/q (written in lowest + terms), the reduction is interpreted as the reduction of p times + the inverse of the reduction of q, all modulo P; if q is exactly + divisible by P then define the reduction to be infinity. So we've + got a well-defined map + + reduce : { rational numbers } -> { 0, 1, 2, ..., P-1, infinity }. + + (2) Now for a rational number x, define hash(x) by: + + reduce(x) if x >= 0 + -reduce(-x) if x < 0 + + If the result of the reduction is infinity (this is impossible for + integers, floats and Decimals) then use the predefined hash value + _PyHASH_INF for x >= 0, or -_PyHASH_INF for x < 0, instead. + _PyHASH_INF, -_PyHASH_INF and _PyHASH_NAN are also used for the + hashes of float and Decimal infinities and nans. + + A selling point for the above strategy is that it makes it possible + to compute hashes of decimal and binary floating-point numbers + efficiently, even if the exponent of the binary or decimal number + is large. The key point is that + + reduce(x * y) == reduce(x) * reduce(y) (modulo _PyHASH_MODULUS) + + provided that {reduce(x), reduce(y)} != {0, infinity}. The reduction of a + binary or decimal float is never infinity, since the denominator is a power + of 2 (for binary) or a divisor of a power of 10 (for decimal). So we have, + for nonnegative x, + + reduce(x * 2**e) == reduce(x) * reduce(2**e) % _PyHASH_MODULUS + + reduce(x * 10**e) == reduce(x) * reduce(10**e) % _PyHASH_MODULUS + + and reduce(10**e) can be computed efficiently by the usual modular + exponentiation algorithm. For reduce(2**e) it's even better: since + P is of the form 2**n-1, reduce(2**e) is 2**(e mod n), and multiplication + by 2**(e mod n) modulo 2**n-1 just amounts to a rotation of bits. + + */ + long _Py_HashDouble(double v) { - double intpart, fractpart; - int expo; - long hipart; - long x; /* the final hash value */ - /* This is designed so that Python numbers of different types - * that compare equal hash to the same value; otherwise comparisons - * of mapping keys will turn out weird. - */ + int e, sign; + double m; + unsigned long x, y; if (!Py_IS_FINITE(v)) { if (Py_IS_INFINITY(v)) - return v < 0 ? -271828 : 314159; + return v > 0 ? _PyHASH_INF : -_PyHASH_INF; else - return 0; + return _PyHASH_NAN; } - fractpart = modf(v, &intpart); - if (fractpart == 0.0) { - /* This must return the same hash as an equal int or long. */ - if (intpart > LONG_MAX/2 || -intpart > LONG_MAX/2) { - /* Convert to long and use its hash. */ - PyObject *plong; /* converted to Python long */ - plong = PyLong_FromDouble(v); - if (plong == NULL) - return -1; - x = PyObject_Hash(plong); - Py_DECREF(plong); - return x; - } - /* Fits in a C long == a Python int, so is its own hash. */ - x = (long)intpart; - if (x == -1) - x = -2; - return x; - } - /* The fractional part is non-zero, so we don't have to worry about - * making this match the hash of some other type. - * Use frexp to get at the bits in the double. - * Since the VAX D double format has 56 mantissa bits, which is the - * most of any double format in use, each of these parts may have as - * many as (but no more than) 56 significant bits. - * So, assuming sizeof(long) >= 4, each part can be broken into two - * longs; frexp and multiplication are used to do that. - * Also, since the Cray double format has 15 exponent bits, which is - * the most of any double format in use, shifting the exponent field - * left by 15 won't overflow a long (again assuming sizeof(long) >= 4). - */ - v = frexp(v, &expo); - v *= 2147483648.0; /* 2**31 */ - hipart = (long)v; /* take the top 32 bits */ - v = (v - (double)hipart) * 2147483648.0; /* get the next 32 bits */ - x = hipart + (long)v + (expo << 15); - if (x == -1) - x = -2; - return x; + + m = frexp(v, &e); + + sign = 1; + if (m < 0) { + sign = -1; + m = -m; + } + + /* process 28 bits at a time; this should work well both for binary + and hexadecimal floating point. */ + x = 0; + while (m) { + x = ((x << 28) & _PyHASH_MODULUS) | x >> (_PyHASH_BITS - 28); + m *= 268435456.0; /* 2**28 */ + e -= 28; + y = (unsigned long)m; /* pull out integer part */ + m -= y; + x += y; + if (x >= _PyHASH_MODULUS) + x -= _PyHASH_MODULUS; + } + + /* adjust for the exponent; first reduce it modulo _PyHASH_BITS */ + e = e >= 0 ? e % _PyHASH_BITS : _PyHASH_BITS-1-((-1-e) % _PyHASH_BITS); + x = ((x << e) & _PyHASH_MODULUS) | x >> (_PyHASH_BITS - e); + + x = x * sign; + if (x == (unsigned long)-1) + x = (unsigned long)-2; + return (long)x; } long Modified: python/branches/py3k/Objects/typeobject.c ============================================================================== --- python/branches/py3k/Objects/typeobject.c (original) +++ python/branches/py3k/Objects/typeobject.c Sun May 23 15:33:13 2010 @@ -4921,6 +4921,7 @@ PyObject *func, *res; static PyObject *hash_str; long h; + int overflow; func = lookup_method(self, "__hash__", &hash_str); @@ -4937,14 +4938,27 @@ Py_DECREF(func); if (res == NULL) return -1; - if (PyLong_Check(res)) + + if (!PyLong_Check(res)) { + PyErr_SetString(PyExc_TypeError, + "__hash__ method should return an integer"); + return -1; + } + /* Transform the PyLong `res` to a C long `h`. For an existing + hashable Python object x, hash(x) will always lie within the range + of a C long. Therefore our transformation must preserve values + that already lie within this range, to ensure that if x.__hash__() + returns hash(y) then hash(x) == hash(y). */ + h = PyLong_AsLongAndOverflow(res, &overflow); + if (overflow) + /* res was not within the range of a C long, so we're free to + use any sufficiently bit-mixing transformation; + long.__hash__ will do nicely. */ h = PyLong_Type.tp_hash(res); - else - h = PyLong_AsLong(res); Py_DECREF(res); - if (h == -1 && !PyErr_Occurred()) - h = -2; - return h; + if (h == -1 && !PyErr_Occurred()) + h = -2; + return h; } static PyObject * Modified: python/branches/py3k/Python/sysmodule.c ============================================================================== --- python/branches/py3k/Python/sysmodule.c (original) +++ python/branches/py3k/Python/sysmodule.c Sun May 23 15:33:13 2010 @@ -570,6 +570,57 @@ return Py_None; } +static PyTypeObject Hash_InfoType; + +PyDoc_STRVAR(hash_info_doc, +"hash_info\n\ +\n\ +A struct sequence providing parameters used for computing\n\ +numeric hashes. The attributes are read only."); + +static PyStructSequence_Field hash_info_fields[] = { + {"width", "width of the type used for hashing, in bits"}, + {"modulus", "prime number giving the modulus on which the hash " + "function is based"}, + {"inf", "value to be used for hash of a positive infinity"}, + {"nan", "value to be used for hash of a nan"}, + {"imag", "multiplier used for the imaginary part of a complex number"}, + {NULL, NULL} +}; + +static PyStructSequence_Desc hash_info_desc = { + "sys.hash_info", + hash_info_doc, + hash_info_fields, + 5, +}; + +PyObject * +get_hash_info(void) +{ + PyObject *hash_info; + int field = 0; + hash_info = PyStructSequence_New(&Hash_InfoType); + if (hash_info == NULL) + return NULL; + PyStructSequence_SET_ITEM(hash_info, field++, + PyLong_FromLong(8*sizeof(long))); + PyStructSequence_SET_ITEM(hash_info, field++, + PyLong_FromLong(_PyHASH_MODULUS)); + PyStructSequence_SET_ITEM(hash_info, field++, + PyLong_FromLong(_PyHASH_INF)); + PyStructSequence_SET_ITEM(hash_info, field++, + PyLong_FromLong(_PyHASH_NAN)); + PyStructSequence_SET_ITEM(hash_info, field++, + PyLong_FromLong(_PyHASH_IMAG)); + if (PyErr_Occurred()) { + Py_CLEAR(hash_info); + return NULL; + } + return hash_info; +} + + PyDoc_STRVAR(setrecursionlimit_doc, "setrecursionlimit(n)\n\ \n\ @@ -1482,6 +1533,11 @@ PyFloat_GetInfo()); SET_SYS_FROM_STRING("int_info", PyLong_GetInfo()); + /* initialize hash_info */ + if (Hash_InfoType.tp_name == 0) + PyStructSequence_InitType(&Hash_InfoType, &hash_info_desc); + SET_SYS_FROM_STRING("hash_info", + get_hash_info()); SET_SYS_FROM_STRING("maxunicode", PyLong_FromLong(PyUnicode_GetMax())); SET_SYS_FROM_STRING("builtin_module_names", From python-checkins at python.org Sun May 23 16:58:05 2010 From: python-checkins at python.org (jean-paul.calderone) Date: Sun, 23 May 2010 16:58:05 +0200 (CEST) Subject: [Python-checkins] r81487 - python/branches/release26-maint Message-ID: <20100523145805.D65E5EA43@mail.python.org> Author: jean-paul.calderone Date: Sun May 23 16:58:05 2010 New Revision: 81487 Log: Unblocked revisions 74426 via svnmerge ........ r74426 | gregory.p.smith | 2009-08-13 14:54:50 -0400 (Thu, 13 Aug 2009) | 4 lines Fix issue1628205: Socket file objects returned by socket.socket.makefile() now properly handles EINTR within the read, readline, write & flush methods. The socket.sendall() method now properly handles interrupted system calls. ........ Modified: python/branches/release26-maint/ (props changed) From python-checkins at python.org Sun May 23 17:22:08 2010 From: python-checkins at python.org (jean-paul.calderone) Date: Sun, 23 May 2010 17:22:08 +0200 (CEST) Subject: [Python-checkins] r81488 - in python/branches/release26-maint: Lib/socket.py Lib/test/test_socket.py Misc/NEWS Modules/socketmodule.c Message-ID: <20100523152208.525A3EE982@mail.python.org> Author: jean-paul.calderone Date: Sun May 23 17:22:08 2010 New Revision: 81488 Log: Merged revisions 74426 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r74426 | gregory.p.smith | 2009-08-13 14:54:50 -0400 (Thu, 13 Aug 2009) | 4 lines Fix issue1628205: Socket file objects returned by socket.socket.makefile() now properly handles EINTR within the read, readline, write & flush methods. The socket.sendall() method now properly handles interrupted system calls. ........ Modified: python/branches/release26-maint/ (props changed) python/branches/release26-maint/Lib/socket.py python/branches/release26-maint/Lib/test/test_socket.py python/branches/release26-maint/Misc/NEWS python/branches/release26-maint/Modules/socketmodule.c Modified: python/branches/release26-maint/Lib/socket.py ============================================================================== --- python/branches/release26-maint/Lib/socket.py (original) +++ python/branches/release26-maint/Lib/socket.py Sun May 23 17:22:08 2010 @@ -84,9 +84,11 @@ from StringIO import StringIO try: - from errno import EBADF + import errno except ImportError: - EBADF = 9 + errno = None +EBADF = getattr(errno, 'EBADF', 9) +EINTR = getattr(errno, 'EINTR', 4) __all__ = ["getfqdn", "create_connection"] __all__.extend(os._get_exports_list(_socket)) @@ -280,10 +282,22 @@ def flush(self): if self._wbuf: - buffer = "".join(self._wbuf) + data = "".join(self._wbuf) self._wbuf = [] self._wbuf_len = 0 - self._sock.sendall(buffer) + buffer_size = max(self._rbufsize, self.default_bufsize) + data_size = len(data) + write_offset = 0 + try: + while write_offset < data_size: + self._sock.sendall(buffer(data, write_offset, buffer_size)) + write_offset += buffer_size + finally: + if write_offset < data_size: + remainder = data[write_offset:] + del data # explicit free + self._wbuf.append(remainder) + self._wbuf_len = len(remainder) def fileno(self): return self._sock.fileno() @@ -326,7 +340,12 @@ # Read until EOF self._rbuf = StringIO() # reset _rbuf. we consume it via buf. while True: - data = self._sock.recv(rbufsize) + try: + data = self._sock.recv(rbufsize) + except error, e: + if e[0] == EINTR: + continue + raise if not data: break buf.write(data) @@ -350,7 +369,12 @@ # than that. The returned data string is short lived # as we copy it into a StringIO and free it. This avoids # fragmentation issues on many platforms. - data = self._sock.recv(left) + try: + data = self._sock.recv(left) + except error, e: + if e[0] == EINTR: + continue + raise if not data: break n = len(data) @@ -393,17 +417,31 @@ self._rbuf = StringIO() # reset _rbuf. we consume it via buf. data = None recv = self._sock.recv - while data != "\n": - data = recv(1) - if not data: - break - buffers.append(data) + while True: + try: + while data != "\n": + data = recv(1) + if not data: + break + buffers.append(data) + except error, e: + # The try..except to catch EINTR was moved outside the + # recv loop to avoid the per byte overhead. + if e[0] == EINTR: + continue + raise + break return "".join(buffers) buf.seek(0, 2) # seek end self._rbuf = StringIO() # reset _rbuf. we consume it via buf. while True: - data = self._sock.recv(self._rbufsize) + try: + data = self._sock.recv(self._rbufsize) + except error, e: + if e[0] == EINTR: + continue + raise if not data: break nl = data.find('\n') @@ -427,7 +465,12 @@ return rv self._rbuf = StringIO() # reset _rbuf. we consume it via buf. while True: - data = self._sock.recv(self._rbufsize) + try: + data = self._sock.recv(self._rbufsize) + except error, e: + if e[0] == EINTR: + continue + raise if not data: break left = size - buf_len Modified: python/branches/release26-maint/Lib/test/test_socket.py ============================================================================== --- python/branches/release26-maint/Lib/test/test_socket.py (original) +++ python/branches/release26-maint/Lib/test/test_socket.py Sun May 23 17:22:08 2010 @@ -834,6 +834,77 @@ def _testClosedAttr(self): self.assert_(not self.cli_file.closed) + +class FileObjectInterruptedTestCase(unittest.TestCase): + """Test that the file object correctly handles EINTR internally.""" + + class MockSocket(object): + def __init__(self, recv_funcs=()): + # A generator that returns callables that we'll call for each + # call to recv(). + self._recv_step = iter(recv_funcs) + + def recv(self, size): + return self._recv_step.next()() + + @staticmethod + def _raise_eintr(): + raise socket.error(errno.EINTR) + + def _test_readline(self, size=-1, **kwargs): + mock_sock = self.MockSocket(recv_funcs=[ + lambda : "This is the first line\nAnd the sec", + self._raise_eintr, + lambda : "ond line is here\n", + lambda : "", + ]) + fo = socket._fileobject(mock_sock, **kwargs) + self.assertEquals(fo.readline(size), "This is the first line\n") + self.assertEquals(fo.readline(size), "And the second line is here\n") + + def _test_read(self, size=-1, **kwargs): + mock_sock = self.MockSocket(recv_funcs=[ + lambda : "This is the first line\nAnd the sec", + self._raise_eintr, + lambda : "ond line is here\n", + lambda : "", + ]) + fo = socket._fileobject(mock_sock, **kwargs) + self.assertEquals(fo.read(size), "This is the first line\n" + "And the second line is here\n") + + def test_default(self): + self._test_readline() + self._test_readline(size=100) + self._test_read() + self._test_read(size=100) + + def test_with_1k_buffer(self): + self._test_readline(bufsize=1024) + self._test_readline(size=100, bufsize=1024) + self._test_read(bufsize=1024) + self._test_read(size=100, bufsize=1024) + + def _test_readline_no_buffer(self, size=-1): + mock_sock = self.MockSocket(recv_funcs=[ + lambda : "aa", + lambda : "\n", + lambda : "BB", + self._raise_eintr, + lambda : "bb", + lambda : "", + ]) + fo = socket._fileobject(mock_sock, bufsize=0) + self.assertEquals(fo.readline(size), "aa\n") + self.assertEquals(fo.readline(size), "BBbb") + + def test_no_buffer(self): + self._test_readline_no_buffer() + self._test_readline_no_buffer(size=4) + self._test_read(bufsize=0) + self._test_read(size=100, bufsize=0) + + class UnbufferedFileObjectClassTestCase(FileObjectClassTestCase): """Repeat the tests from FileObjectClassTestCase with bufsize==0. @@ -1229,6 +1300,7 @@ tests.extend([ NonBlockingTCPTests, FileObjectClassTestCase, + FileObjectInterruptedTestCase, UnbufferedFileObjectClassTestCase, LineBufferedFileObjectClassTestCase, SmallBufferedFileObjectClassTestCase, Modified: python/branches/release26-maint/Misc/NEWS ============================================================================== --- python/branches/release26-maint/Misc/NEWS (original) +++ python/branches/release26-maint/Misc/NEWS Sun May 23 17:22:08 2010 @@ -55,6 +55,10 @@ Library ------- +- Issue #1628205: Socket file objects returned by socket.socket.makefile() now + properly handles EINTR within the read, readline, write & flush methods. + The socket.sendall() method now properly handles interrupted system calls. + - Issue #3924: Ignore cookies with invalid "version" field in cookielib. - Issue #6268: Fix seek() method of codecs.open(), don't read or write the BOM Modified: python/branches/release26-maint/Modules/socketmodule.c ============================================================================== --- python/branches/release26-maint/Modules/socketmodule.c (original) +++ python/branches/release26-maint/Modules/socketmodule.c Sun May 23 17:22:08 2010 @@ -2723,8 +2723,21 @@ #else n = send(s->sock_fd, buf, len, flags); #endif - if (n < 0) + if (n < 0) { +#ifdef EINTR + /* We must handle EINTR here as there is no way for + * the caller to know how much was sent otherwise. */ + if (errno == EINTR) { + /* Run signal handlers. If an exception was + * raised, abort and leave this socket in + * an unknown state. */ + if (PyErr_CheckSignals()) + return NULL; + continue; + } +#endif break; + } buf += n; len -= n; } while (len > 0); From python-checkins at python.org Sun May 23 23:29:29 2010 From: python-checkins at python.org (georg.brandl) Date: Sun, 23 May 2010 23:29:29 +0200 (CEST) Subject: [Python-checkins] r81489 - python/trunk/Doc/library/datetime.rst Message-ID: <20100523212929.9352FEE982@mail.python.org> Author: georg.brandl Date: Sun May 23 23:29:29 2010 New Revision: 81489 Log: #1436346: make it more obvious that timetuple[7] is yday. Modified: python/trunk/Doc/library/datetime.rst Modified: python/trunk/Doc/library/datetime.rst ============================================================================== --- python/trunk/Doc/library/datetime.rst (original) +++ python/trunk/Doc/library/datetime.rst Sun May 23 23:29:29 2010 @@ -455,7 +455,9 @@ Return a :class:`time.struct_time` such as returned by :func:`time.localtime`. The hours, minutes and seconds are 0, and the DST flag is -1. ``d.timetuple()`` is equivalent to ``time.struct_time((d.year, d.month, d.day, 0, 0, 0, - d.weekday(), d.toordinal() - date(d.year, 1, 1).toordinal() + 1, -1))`` + d.weekday(), yday, -1))``, where ``yday = d.toordinal() - date(d.year, 1, + 1).toordinal() + 1`` is the day number within the current year starting with + ``1`` for January 1st. .. method:: date.toordinal() @@ -920,12 +922,13 @@ Return a :class:`time.struct_time` such as returned by :func:`time.localtime`. ``d.timetuple()`` is equivalent to ``time.struct_time((d.year, d.month, d.day, - d.hour, d.minute, d.second, d.weekday(), d.toordinal() - date(d.year, 1, - 1).toordinal() + 1, dst))`` The :attr:`tm_isdst` flag of the result is set - according to the :meth:`dst` method: :attr:`tzinfo` is ``None`` or :meth:`dst` - returns ``None``, :attr:`tm_isdst` is set to ``-1``; else if :meth:`dst` - returns a non-zero value, :attr:`tm_isdst` is set to ``1``; else ``tm_isdst`` is - set to ``0``. + d.hour, d.minute, d.second, d.weekday(), yday, dst))``, where ``yday = + d.toordinal() - date(d.year, 1, 1).toordinal() + 1`` is the day number within + the current year starting with ``1`` for January 1st. The :attr:`tm_isdst` flag + of the result is set according to the :meth:`dst` method: :attr:`tzinfo` is + ``None`` or :meth:`dst`` returns ``None``, :attr:`tm_isdst` is set to ``-1``; + else if :meth:`dst` returns a non-zero value, :attr:`tm_isdst` is set to ``1``; + else ``tm_isdst`` is set to ``0``. .. method:: datetime.utctimetuple() From solipsis at pitrou.net Mon May 24 01:22:45 2010 From: solipsis at pitrou.net (solipsis at pitrou.net) Date: Mon, 24 May 2010 01:22:45 +0200 (CEST) Subject: [Python-checkins] Daily py3k reference leaks (r81486): sum=0 Message-ID: <20100523232245.203981770A@ns6635.ovh.net> py3k results for svn r81486 (hg cset 0b4610178d62) -------------------------------------------------- Command line was: ['./python', '-m', 'test.regrtest', '-uall', '-R', '3:3:/home/antoine/py3k/refleaks/reflogCkUdAW', '-x'] From python-checkins at python.org Mon May 24 04:38:01 2010 From: python-checkins at python.org (steven.bethard) Date: Mon, 24 May 2010 04:38:01 +0200 (CEST) Subject: [Python-checkins] r81490 - in python/trunk/Doc/library: argparse.rst getopt.rst optparse.rst Message-ID: <20100524023801.1F8C0EE983@mail.python.org> Author: steven.bethard Date: Mon May 24 04:38:00 2010 New Revision: 81490 Log: argparse documentation updates (including updates to optparse and getopt documentation that were promised in the PEP) Modified: python/trunk/Doc/library/argparse.rst python/trunk/Doc/library/getopt.rst python/trunk/Doc/library/optparse.rst Modified: python/trunk/Doc/library/argparse.rst ============================================================================== --- python/trunk/Doc/library/argparse.rst (original) +++ python/trunk/Doc/library/argparse.rst Mon May 24 04:38:00 2010 @@ -672,8 +672,8 @@ >>> import argparse >>> parser = argparse.ArgumentParser(prog='PROG') - >>> parser.add_argument('-v', '--version', action='version', version='%(prog)s 2.0') - >>> parser.parse_args(['-v']) + >>> parser.add_argument('--version', action='version', version='%(prog)s 2.0') + >>> parser.parse_args(['--version']) PROG 2.0 You can also specify an arbitrary action by passing an object that implements @@ -1725,3 +1725,6 @@ * Replace strings with implicit arguments such as ``%default`` or ``%prog`` with the standard python syntax to use dictionaries to format strings, that is, ``%(default)s`` and ``%(prog)s``. + +* Replace the OptionParser constructor ``version`` argument with a call to + ``parser.add_argument('--version', action='version', version='')`` Modified: python/trunk/Doc/library/getopt.rst ============================================================================== --- python/trunk/Doc/library/getopt.rst (original) +++ python/trunk/Doc/library/getopt.rst Mon May 24 04:38:00 2010 @@ -6,6 +6,12 @@ :synopsis: Portable parser for command line options; support both short and long option names. +.. note:: + The :mod:`getopt` module is a parser for command line options whose API is + designed to be familiar to users of the C :cfunc:`getopt` function. Users who + are unfamiliar with the C :cfunc:`getopt` function or who would like to write + less code and get better help and error messages should consider using the + :mod:`argparse` module instead. This module helps scripts to parse the command line arguments in ``sys.argv``. It supports the same conventions as the Unix :cfunc:`getopt` function (including @@ -142,9 +148,21 @@ if __name__ == "__main__": main() +Note that an equivalent command line interface could be produced with less code +and more informative help and error messages by using the :mod:`argparse` module:: + + import argparse + + if __name__ == '__main__': + parser = argparse.ArgumentParser() + parser.add_argument('-o', '--output') + parser.add_argument('-v', dest='verbose', action='store_true') + args = parser.parse_args() + # ... do something with args.output ... + # ... do something with args.verbose .. .. seealso:: - Module :mod:`optparse` - More object-oriented command line option parsing. + Module :mod:`argparse` + Alternative command line option and argument parsing library. Modified: python/trunk/Doc/library/optparse.rst ============================================================================== --- python/trunk/Doc/library/optparse.rst (original) +++ python/trunk/Doc/library/optparse.rst Mon May 24 04:38:00 2010 @@ -3,8 +3,13 @@ .. module:: optparse :synopsis: Command-line option parsing library. -.. moduleauthor:: Greg Ward + :deprecated: + +.. deprecated:: 2.7 + The :mod:`optparse` module is deprecated and will not be developed further; + development will continue with the :mod:`argparse` module. +.. moduleauthor:: Greg Ward .. versionadded:: 2.3 From python-checkins at python.org Mon May 24 05:21:08 2010 From: python-checkins at python.org (steven.bethard) Date: Mon, 24 May 2010 05:21:08 +0200 (CEST) Subject: [Python-checkins] r81491 - in python/branches/py3k: Doc/library/argparse.rst Doc/library/getopt.rst Doc/library/optparse.rst Message-ID: <20100524032108.45999EE984@mail.python.org> Author: steven.bethard Date: Mon May 24 05:21:08 2010 New Revision: 81491 Log: Merged revisions 81490 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r81490 | steven.bethard | 2010-05-23 19:38:00 -0700 (Sun, 23 May 2010) | 1 line argparse documentation updates (including updates to optparse and getopt documentation that were promised in the PEP) ........ Modified: python/branches/py3k/ (props changed) python/branches/py3k/Doc/library/argparse.rst python/branches/py3k/Doc/library/getopt.rst python/branches/py3k/Doc/library/optparse.rst Modified: python/branches/py3k/Doc/library/argparse.rst ============================================================================== --- python/branches/py3k/Doc/library/argparse.rst (original) +++ python/branches/py3k/Doc/library/argparse.rst Mon May 24 05:21:08 2010 @@ -672,8 +672,8 @@ >>> import argparse >>> parser = argparse.ArgumentParser(prog='PROG') - >>> parser.add_argument('-v', '--version', action='version', version='%(prog)s 2.0') - >>> parser.parse_args(['-v']) + >>> parser.add_argument('--version', action='version', version='%(prog)s 2.0') + >>> parser.parse_args(['--version']) PROG 2.0 You can also specify an arbitrary action by passing an object that implements @@ -1725,3 +1725,6 @@ * Replace strings with implicit arguments such as ``%default`` or ``%prog`` with the standard python syntax to use dictionaries to format strings, that is, ``%(default)s`` and ``%(prog)s``. + +* Replace the OptionParser constructor ``version`` argument with a call to + ``parser.add_argument('--version', action='version', version='')`` Modified: python/branches/py3k/Doc/library/getopt.rst ============================================================================== --- python/branches/py3k/Doc/library/getopt.rst (original) +++ python/branches/py3k/Doc/library/getopt.rst Mon May 24 05:21:08 2010 @@ -5,6 +5,12 @@ :synopsis: Portable parser for command line options; support both short and long option names. +.. note:: + The :mod:`getopt` module is a parser for command line options whose API is + designed to be familiar to users of the C :cfunc:`getopt` function. Users who + are unfamiliar with the C :cfunc:`getopt` function or who would like to write + less code and get better help and error messages should consider using the + :mod:`argparse` module instead. This module helps scripts to parse the command line arguments in ``sys.argv``. It supports the same conventions as the Unix :cfunc:`getopt` function (including @@ -136,9 +142,21 @@ if __name__ == "__main__": main() +Note that an equivalent command line interface could be produced with less code +and more informative help and error messages by using the :mod:`argparse` module:: + + import argparse + + if __name__ == '__main__': + parser = argparse.ArgumentParser() + parser.add_argument('-o', '--output') + parser.add_argument('-v', dest='verbose', action='store_true') + args = parser.parse_args() + # ... do something with args.output ... + # ... do something with args.verbose .. .. seealso:: - Module :mod:`optparse` - More object-oriented command line option parsing. + Module :mod:`argparse` + Alternative command line option and argument parsing library. Modified: python/branches/py3k/Doc/library/optparse.rst ============================================================================== --- python/branches/py3k/Doc/library/optparse.rst (original) +++ python/branches/py3k/Doc/library/optparse.rst Mon May 24 05:21:08 2010 @@ -3,6 +3,12 @@ .. module:: optparse :synopsis: Command-line option parsing library. + :deprecated: + +.. deprecated:: 2.7 + The :mod:`optparse` module is deprecated and will not be developed further; + development will continue with the :mod:`argparse` module. + .. moduleauthor:: Greg Ward .. sectionauthor:: Greg Ward From python-checkins at python.org Mon May 24 05:45:26 2010 From: python-checkins at python.org (steven.bethard) Date: Mon, 24 May 2010 05:45:26 +0200 (CEST) Subject: [Python-checkins] r81492 - in python/trunk/Lib: argparse.py test/test_argparse.py Message-ID: <20100524034526.9CDB9EC9E@mail.python.org> Author: steven.bethard Date: Mon May 24 05:45:26 2010 New Revision: 81492 Log: Fix default value for version help. Approved by Benjamin on python-dev: http://mail.python.org/pipermail/python-dev/2010-May/100231.html Modified: python/trunk/Lib/argparse.py python/trunk/Lib/test/test_argparse.py Modified: python/trunk/Lib/argparse.py ============================================================================== --- python/trunk/Lib/argparse.py (original) +++ python/trunk/Lib/argparse.py Mon May 24 05:45:26 2010 @@ -987,7 +987,7 @@ version=None, dest=SUPPRESS, default=SUPPRESS, - help=None): + help="show program's version number and exit"): super(_VersionAction, self).__init__( option_strings=option_strings, dest=dest, Modified: python/trunk/Lib/test/test_argparse.py ============================================================================== --- python/trunk/Lib/test/test_argparse.py (original) +++ python/trunk/Lib/test/test_argparse.py Mon May 24 05:45:26 2010 @@ -3699,6 +3699,25 @@ ''' version = '' +class TestHelpVersionAction(HelpTestCase): + """Test the default help for the version action""" + + parser_signature = Sig(prog='PROG', description='description') + argument_signatures = [Sig('-V', '--version', action='version', version='3.6')] + argument_group_signatures = [] + usage = '''\ + usage: PROG [-h] [-V] + ''' + help = usage + '''\ + + description + + optional arguments: + -h, --help show this help message and exit + -V, --version show program's version number and exit + ''' + version = '' + # ===================================== # Optional/Positional constructor tests # ===================================== From python-checkins at python.org Mon May 24 05:47:39 2010 From: python-checkins at python.org (steven.bethard) Date: Mon, 24 May 2010 05:47:39 +0200 (CEST) Subject: [Python-checkins] r81493 - in python/branches/py3k: Lib/argparse.py Lib/test/test_argparse.py Message-ID: <20100524034739.135BBEC9E@mail.python.org> Author: steven.bethard Date: Mon May 24 05:47:38 2010 New Revision: 81493 Log: Merged revisions 81492 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r81492 | steven.bethard | 2010-05-23 20:45:26 -0700 (Sun, 23 May 2010) | 1 line Fix default value for version help. Approved by Benjamin on python-dev: http://mail.python.org/pipermail/python-dev/2010-May/100231.html ........ Modified: python/branches/py3k/ (props changed) python/branches/py3k/Lib/argparse.py python/branches/py3k/Lib/test/test_argparse.py Modified: python/branches/py3k/Lib/argparse.py ============================================================================== --- python/branches/py3k/Lib/argparse.py (original) +++ python/branches/py3k/Lib/argparse.py Mon May 24 05:47:38 2010 @@ -987,7 +987,7 @@ version=None, dest=SUPPRESS, default=SUPPRESS, - help=None): + help="show program's version number and exit"): super(_VersionAction, self).__init__( option_strings=option_strings, dest=dest, Modified: python/branches/py3k/Lib/test/test_argparse.py ============================================================================== --- python/branches/py3k/Lib/test/test_argparse.py (original) +++ python/branches/py3k/Lib/test/test_argparse.py Mon May 24 05:47:38 2010 @@ -3688,6 +3688,25 @@ ''' version = '' +class TestHelpVersionAction(HelpTestCase): + """Test the default help for the version action""" + + parser_signature = Sig(prog='PROG', description='description') + argument_signatures = [Sig('-V', '--version', action='version', version='3.6')] + argument_group_signatures = [] + usage = '''\ + usage: PROG [-h] [-V] + ''' + help = usage + '''\ + + description + + optional arguments: + -h, --help show this help message and exit + -V, --version show program's version number and exit + ''' + version = '' + # ===================================== # Optional/Positional constructor tests # ===================================== From python-checkins at python.org Mon May 24 11:43:14 2010 From: python-checkins at python.org (vinay.sajip) Date: Mon, 24 May 2010 11:43:14 +0200 (CEST) Subject: [Python-checkins] r81494 - python/branches/release26-maint/Lib/logging/handlers.py Message-ID: <20100524094314.2C32BEA43@mail.python.org> Author: vinay.sajip Date: Mon May 24 11:43:13 2010 New Revision: 81494 Log: Issue #8795: logging: Backported trunk fix for SysLogHandler and Unicode. Modified: python/branches/release26-maint/Lib/logging/handlers.py Modified: python/branches/release26-maint/Lib/logging/handlers.py ============================================================================== --- python/branches/release26-maint/Lib/logging/handlers.py (original) +++ python/branches/release26-maint/Lib/logging/handlers.py Mon May 24 11:43:13 2010 @@ -31,6 +31,11 @@ import codecs except ImportError: codecs = None +try: + unicode + _unicode = True +except NameError: + _unicode = False # # Some constants... @@ -777,6 +782,11 @@ self.encodePriority(self.facility, self.mapPriority(record.levelname)), msg) + # Treat unicode messages as required by RFC 5424 + if _unicode and type(msg) is unicode: + msg = msg.encode('utf-8') + if codecs: + msg = codecs.BOM_UTF8 + msg try: if self.unixsocket: try: From python-checkins at python.org Mon May 24 17:58:43 2010 From: python-checkins at python.org (antoine.pitrou) Date: Mon, 24 May 2010 17:58:43 +0200 (CEST) Subject: [Python-checkins] r81495 - python/branches/py3k/Doc/library/ssl.rst Message-ID: <20100524155843.648F9EEF9@mail.python.org> Author: antoine.pitrou Date: Mon May 24 17:58:43 2010 New Revision: 81495 Log: Add a versionadded tag for SSL contexts. Modified: python/branches/py3k/Doc/library/ssl.rst Modified: python/branches/py3k/Doc/library/ssl.rst ============================================================================== --- python/branches/py3k/Doc/library/ssl.rst (original) +++ python/branches/py3k/Doc/library/ssl.rst Mon May 24 17:58:43 2010 @@ -410,6 +410,8 @@ SSL Contexts ------------ +.. versionadded:: 3.2 + .. class:: SSLContext(protocol) An object holding various data longer-lived than single SSL connections, From python-checkins at python.org Mon May 24 23:20:20 2010 From: python-checkins at python.org (antoine.pitrou) Date: Mon, 24 May 2010 23:20:20 +0200 (CEST) Subject: [Python-checkins] r81498 - python/branches/py3k/Doc/library/ssl.rst Message-ID: <20100524212020.7CBC4EE983@mail.python.org> Author: antoine.pitrou Date: Mon May 24 23:20:20 2010 New Revision: 81498 Log: Document the context attribute of SSL sockets Modified: python/branches/py3k/Doc/library/ssl.rst Modified: python/branches/py3k/Doc/library/ssl.rst ============================================================================== --- python/branches/py3k/Doc/library/ssl.rst (original) +++ python/branches/py3k/Doc/library/ssl.rst Mon May 24 23:20:20 2010 @@ -407,6 +407,16 @@ other side of the connection, rather than the original socket. +.. attribute:: SSLSocket.context + + The :class:`SSLContext` object this SSL socket is tied to. If the SSL + socket was created using the top-level :func:`wrap_socket` function + (rather than :meth:`SSLContext.wrap_socket`), this is a custom context + object created for this SSL socket. + + .. versionadded:: 3.2 + + SSL Contexts ------------ From python-checkins at python.org Mon May 24 23:29:07 2010 From: python-checkins at python.org (georg.brandl) Date: Mon, 24 May 2010 23:29:07 +0200 (CEST) Subject: [Python-checkins] r81499 - in python/trunk: Doc/library/codecs.rst Lib/encodings/aliases.py Lib/encodings/cp858.py Lib/test/test_codecs.py Lib/test/test_unicode.py Misc/NEWS Message-ID: <20100524212907.AAECBEE984@mail.python.org> Author: georg.brandl Date: Mon May 24 23:29:07 2010 New Revision: 81499 Log: #8016: add the CP858 codec (approved by Benjamin). (Also add CP720 to the tests, it was missing there.) Added: python/trunk/Lib/encodings/cp858.py (contents, props changed) Modified: python/trunk/Doc/library/codecs.rst python/trunk/Lib/encodings/aliases.py python/trunk/Lib/test/test_codecs.py python/trunk/Lib/test/test_unicode.py python/trunk/Misc/NEWS Modified: python/trunk/Doc/library/codecs.rst ============================================================================== --- python/trunk/Doc/library/codecs.rst (original) +++ python/trunk/Doc/library/codecs.rst Mon May 24 23:29:07 2010 @@ -925,6 +925,8 @@ +-----------------+--------------------------------+--------------------------------+ | cp857 | 857, IBM857 | Turkish | +-----------------+--------------------------------+--------------------------------+ +| cp858 | 858, IBM858 | Western Europe | ++-----------------+--------------------------------+--------------------------------+ | cp860 | 860, IBM860 | Portuguese | +-----------------+--------------------------------+--------------------------------+ | cp861 | 861, CP-IS, IBM861 | Icelandic | Modified: python/trunk/Lib/encodings/aliases.py ============================================================================== --- python/trunk/Lib/encodings/aliases.py (original) +++ python/trunk/Lib/encodings/aliases.py Mon May 24 23:29:07 2010 @@ -146,6 +146,11 @@ 'csibm857' : 'cp857', 'ibm857' : 'cp857', + # cp858 codec + '858' : 'cp858', + 'csibm858' : 'cp858', + 'ibm858' : 'cp858', + # cp860 codec '860' : 'cp860', 'csibm860' : 'cp860', Added: python/trunk/Lib/encodings/cp858.py ============================================================================== --- (empty file) +++ python/trunk/Lib/encodings/cp858.py Mon May 24 23:29:07 2010 @@ -0,0 +1,698 @@ +""" Python Character Mapping Codec for CP858, modified from cp850. + +""" + +import codecs + +### Codec APIs + +class Codec(codecs.Codec): + + def encode(self,input,errors='strict'): + return codecs.charmap_encode(input,errors,encoding_map) + + def decode(self,input,errors='strict'): + return codecs.charmap_decode(input,errors,decoding_table) + +class IncrementalEncoder(codecs.IncrementalEncoder): + def encode(self, input, final=False): + return codecs.charmap_encode(input,self.errors,encoding_map)[0] + +class IncrementalDecoder(codecs.IncrementalDecoder): + def decode(self, input, final=False): + return codecs.charmap_decode(input,self.errors,decoding_table)[0] + +class StreamWriter(Codec,codecs.StreamWriter): + pass + +class StreamReader(Codec,codecs.StreamReader): + pass + +### encodings module API + +def getregentry(): + return codecs.CodecInfo( + name='cp858', + encode=Codec().encode, + decode=Codec().decode, + incrementalencoder=IncrementalEncoder, + incrementaldecoder=IncrementalDecoder, + streamreader=StreamReader, + streamwriter=StreamWriter, + ) + +### Decoding Map + +decoding_map = codecs.make_identity_dict(range(256)) +decoding_map.update({ + 0x0080: 0x00c7, # LATIN CAPITAL LETTER C WITH CEDILLA + 0x0081: 0x00fc, # LATIN SMALL LETTER U WITH DIAERESIS + 0x0082: 0x00e9, # LATIN SMALL LETTER E WITH ACUTE + 0x0083: 0x00e2, # LATIN SMALL LETTER A WITH CIRCUMFLEX + 0x0084: 0x00e4, # LATIN SMALL LETTER A WITH DIAERESIS + 0x0085: 0x00e0, # LATIN SMALL LETTER A WITH GRAVE + 0x0086: 0x00e5, # LATIN SMALL LETTER A WITH RING ABOVE + 0x0087: 0x00e7, # LATIN SMALL LETTER C WITH CEDILLA + 0x0088: 0x00ea, # LATIN SMALL LETTER E WITH CIRCUMFLEX + 0x0089: 0x00eb, # LATIN SMALL LETTER E WITH DIAERESIS + 0x008a: 0x00e8, # LATIN SMALL LETTER E WITH GRAVE + 0x008b: 0x00ef, # LATIN SMALL LETTER I WITH DIAERESIS + 0x008c: 0x00ee, # LATIN SMALL LETTER I WITH CIRCUMFLEX + 0x008d: 0x00ec, # LATIN SMALL LETTER I WITH GRAVE + 0x008e: 0x00c4, # LATIN CAPITAL LETTER A WITH DIAERESIS + 0x008f: 0x00c5, # LATIN CAPITAL LETTER A WITH RING ABOVE + 0x0090: 0x00c9, # LATIN CAPITAL LETTER E WITH ACUTE + 0x0091: 0x00e6, # LATIN SMALL LIGATURE AE + 0x0092: 0x00c6, # LATIN CAPITAL LIGATURE AE + 0x0093: 0x00f4, # LATIN SMALL LETTER O WITH CIRCUMFLEX + 0x0094: 0x00f6, # LATIN SMALL LETTER O WITH DIAERESIS + 0x0095: 0x00f2, # LATIN SMALL LETTER O WITH GRAVE + 0x0096: 0x00fb, # LATIN SMALL LETTER U WITH CIRCUMFLEX + 0x0097: 0x00f9, # LATIN SMALL LETTER U WITH GRAVE + 0x0098: 0x00ff, # LATIN SMALL LETTER Y WITH DIAERESIS + 0x0099: 0x00d6, # LATIN CAPITAL LETTER O WITH DIAERESIS + 0x009a: 0x00dc, # LATIN CAPITAL LETTER U WITH DIAERESIS + 0x009b: 0x00f8, # LATIN SMALL LETTER O WITH STROKE + 0x009c: 0x00a3, # POUND SIGN + 0x009d: 0x00d8, # LATIN CAPITAL LETTER O WITH STROKE + 0x009e: 0x00d7, # MULTIPLICATION SIGN + 0x009f: 0x0192, # LATIN SMALL LETTER F WITH HOOK + 0x00a0: 0x00e1, # LATIN SMALL LETTER A WITH ACUTE + 0x00a1: 0x00ed, # LATIN SMALL LETTER I WITH ACUTE + 0x00a2: 0x00f3, # LATIN SMALL LETTER O WITH ACUTE + 0x00a3: 0x00fa, # LATIN SMALL LETTER U WITH ACUTE + 0x00a4: 0x00f1, # LATIN SMALL LETTER N WITH TILDE + 0x00a5: 0x00d1, # LATIN CAPITAL LETTER N WITH TILDE + 0x00a6: 0x00aa, # FEMININE ORDINAL INDICATOR + 0x00a7: 0x00ba, # MASCULINE ORDINAL INDICATOR + 0x00a8: 0x00bf, # INVERTED QUESTION MARK + 0x00a9: 0x00ae, # REGISTERED SIGN + 0x00aa: 0x00ac, # NOT SIGN + 0x00ab: 0x00bd, # VULGAR FRACTION ONE HALF + 0x00ac: 0x00bc, # VULGAR FRACTION ONE QUARTER + 0x00ad: 0x00a1, # INVERTED EXCLAMATION MARK + 0x00ae: 0x00ab, # LEFT-POINTING DOUBLE ANGLE QUOTATION MARK + 0x00af: 0x00bb, # RIGHT-POINTING DOUBLE ANGLE QUOTATION MARK + 0x00b0: 0x2591, # LIGHT SHADE + 0x00b1: 0x2592, # MEDIUM SHADE + 0x00b2: 0x2593, # DARK SHADE + 0x00b3: 0x2502, # BOX DRAWINGS LIGHT VERTICAL + 0x00b4: 0x2524, # BOX DRAWINGS LIGHT VERTICAL AND LEFT + 0x00b5: 0x00c1, # LATIN CAPITAL LETTER A WITH ACUTE + 0x00b6: 0x00c2, # LATIN CAPITAL LETTER A WITH CIRCUMFLEX + 0x00b7: 0x00c0, # LATIN CAPITAL LETTER A WITH GRAVE + 0x00b8: 0x00a9, # COPYRIGHT SIGN + 0x00b9: 0x2563, # BOX DRAWINGS DOUBLE VERTICAL AND LEFT + 0x00ba: 0x2551, # BOX DRAWINGS DOUBLE VERTICAL + 0x00bb: 0x2557, # BOX DRAWINGS DOUBLE DOWN AND LEFT + 0x00bc: 0x255d, # BOX DRAWINGS DOUBLE UP AND LEFT + 0x00bd: 0x00a2, # CENT SIGN + 0x00be: 0x00a5, # YEN SIGN + 0x00bf: 0x2510, # BOX DRAWINGS LIGHT DOWN AND LEFT + 0x00c0: 0x2514, # BOX DRAWINGS LIGHT UP AND RIGHT + 0x00c1: 0x2534, # BOX DRAWINGS LIGHT UP AND HORIZONTAL + 0x00c2: 0x252c, # BOX DRAWINGS LIGHT DOWN AND HORIZONTAL + 0x00c3: 0x251c, # BOX DRAWINGS LIGHT VERTICAL AND RIGHT + 0x00c4: 0x2500, # BOX DRAWINGS LIGHT HORIZONTAL + 0x00c5: 0x253c, # BOX DRAWINGS LIGHT VERTICAL AND HORIZONTAL + 0x00c6: 0x00e3, # LATIN SMALL LETTER A WITH TILDE + 0x00c7: 0x00c3, # LATIN CAPITAL LETTER A WITH TILDE + 0x00c8: 0x255a, # BOX DRAWINGS DOUBLE UP AND RIGHT + 0x00c9: 0x2554, # BOX DRAWINGS DOUBLE DOWN AND RIGHT + 0x00ca: 0x2569, # BOX DRAWINGS DOUBLE UP AND HORIZONTAL + 0x00cb: 0x2566, # BOX DRAWINGS DOUBLE DOWN AND HORIZONTAL + 0x00cc: 0x2560, # BOX DRAWINGS DOUBLE VERTICAL AND RIGHT + 0x00cd: 0x2550, # BOX DRAWINGS DOUBLE HORIZONTAL + 0x00ce: 0x256c, # BOX DRAWINGS DOUBLE VERTICAL AND HORIZONTAL + 0x00cf: 0x00a4, # CURRENCY SIGN + 0x00d0: 0x00f0, # LATIN SMALL LETTER ETH + 0x00d1: 0x00d0, # LATIN CAPITAL LETTER ETH + 0x00d2: 0x00ca, # LATIN CAPITAL LETTER E WITH CIRCUMFLEX + 0x00d3: 0x00cb, # LATIN CAPITAL LETTER E WITH DIAERESIS + 0x00d4: 0x00c8, # LATIN CAPITAL LETTER E WITH GRAVE + 0x00d5: 0x20ac, # EURO SIGN + 0x00d6: 0x00cd, # LATIN CAPITAL LETTER I WITH ACUTE + 0x00d7: 0x00ce, # LATIN CAPITAL LETTER I WITH CIRCUMFLEX + 0x00d8: 0x00cf, # LATIN CAPITAL LETTER I WITH DIAERESIS + 0x00d9: 0x2518, # BOX DRAWINGS LIGHT UP AND LEFT + 0x00da: 0x250c, # BOX DRAWINGS LIGHT DOWN AND RIGHT + 0x00db: 0x2588, # FULL BLOCK + 0x00dc: 0x2584, # LOWER HALF BLOCK + 0x00dd: 0x00a6, # BROKEN BAR + 0x00de: 0x00cc, # LATIN CAPITAL LETTER I WITH GRAVE + 0x00df: 0x2580, # UPPER HALF BLOCK + 0x00e0: 0x00d3, # LATIN CAPITAL LETTER O WITH ACUTE + 0x00e1: 0x00df, # LATIN SMALL LETTER SHARP S + 0x00e2: 0x00d4, # LATIN CAPITAL LETTER O WITH CIRCUMFLEX + 0x00e3: 0x00d2, # LATIN CAPITAL LETTER O WITH GRAVE + 0x00e4: 0x00f5, # LATIN SMALL LETTER O WITH TILDE + 0x00e5: 0x00d5, # LATIN CAPITAL LETTER O WITH TILDE + 0x00e6: 0x00b5, # MICRO SIGN + 0x00e7: 0x00fe, # LATIN SMALL LETTER THORN + 0x00e8: 0x00de, # LATIN CAPITAL LETTER THORN + 0x00e9: 0x00da, # LATIN CAPITAL LETTER U WITH ACUTE + 0x00ea: 0x00db, # LATIN CAPITAL LETTER U WITH CIRCUMFLEX + 0x00eb: 0x00d9, # LATIN CAPITAL LETTER U WITH GRAVE + 0x00ec: 0x00fd, # LATIN SMALL LETTER Y WITH ACUTE + 0x00ed: 0x00dd, # LATIN CAPITAL LETTER Y WITH ACUTE + 0x00ee: 0x00af, # MACRON + 0x00ef: 0x00b4, # ACUTE ACCENT + 0x00f0: 0x00ad, # SOFT HYPHEN + 0x00f1: 0x00b1, # PLUS-MINUS SIGN + 0x00f2: 0x2017, # DOUBLE LOW LINE + 0x00f3: 0x00be, # VULGAR FRACTION THREE QUARTERS + 0x00f4: 0x00b6, # PILCROW SIGN + 0x00f5: 0x00a7, # SECTION SIGN + 0x00f6: 0x00f7, # DIVISION SIGN + 0x00f7: 0x00b8, # CEDILLA + 0x00f8: 0x00b0, # DEGREE SIGN + 0x00f9: 0x00a8, # DIAERESIS + 0x00fa: 0x00b7, # MIDDLE DOT + 0x00fb: 0x00b9, # SUPERSCRIPT ONE + 0x00fc: 0x00b3, # SUPERSCRIPT THREE + 0x00fd: 0x00b2, # SUPERSCRIPT TWO + 0x00fe: 0x25a0, # BLACK SQUARE + 0x00ff: 0x00a0, # NO-BREAK SPACE +}) + +### Decoding Table + +decoding_table = ( + u'\x00' # 0x0000 -> NULL + u'\x01' # 0x0001 -> START OF HEADING + u'\x02' # 0x0002 -> START OF TEXT + u'\x03' # 0x0003 -> END OF TEXT + u'\x04' # 0x0004 -> END OF TRANSMISSION + u'\x05' # 0x0005 -> ENQUIRY + u'\x06' # 0x0006 -> ACKNOWLEDGE + u'\x07' # 0x0007 -> BELL + u'\x08' # 0x0008 -> BACKSPACE + u'\t' # 0x0009 -> HORIZONTAL TABULATION + u'\n' # 0x000a -> LINE FEED + u'\x0b' # 0x000b -> VERTICAL TABULATION + u'\x0c' # 0x000c -> FORM FEED + u'\r' # 0x000d -> CARRIAGE RETURN + u'\x0e' # 0x000e -> SHIFT OUT + u'\x0f' # 0x000f -> SHIFT IN + u'\x10' # 0x0010 -> DATA LINK ESCAPE + u'\x11' # 0x0011 -> DEVICE CONTROL ONE + u'\x12' # 0x0012 -> DEVICE CONTROL TWO + u'\x13' # 0x0013 -> DEVICE CONTROL THREE + u'\x14' # 0x0014 -> DEVICE CONTROL FOUR + u'\x15' # 0x0015 -> NEGATIVE ACKNOWLEDGE + u'\x16' # 0x0016 -> SYNCHRONOUS IDLE + u'\x17' # 0x0017 -> END OF TRANSMISSION BLOCK + u'\x18' # 0x0018 -> CANCEL + u'\x19' # 0x0019 -> END OF MEDIUM + u'\x1a' # 0x001a -> SUBSTITUTE + u'\x1b' # 0x001b -> ESCAPE + u'\x1c' # 0x001c -> FILE SEPARATOR + u'\x1d' # 0x001d -> GROUP SEPARATOR + u'\x1e' # 0x001e -> RECORD SEPARATOR + u'\x1f' # 0x001f -> UNIT SEPARATOR + u' ' # 0x0020 -> SPACE + u'!' # 0x0021 -> EXCLAMATION MARK + u'"' # 0x0022 -> QUOTATION MARK + u'#' # 0x0023 -> NUMBER SIGN + u'$' # 0x0024 -> DOLLAR SIGN + u'%' # 0x0025 -> PERCENT SIGN + u'&' # 0x0026 -> AMPERSAND + u"'" # 0x0027 -> APOSTROPHE + u'(' # 0x0028 -> LEFT PARENTHESIS + u')' # 0x0029 -> RIGHT PARENTHESIS + u'*' # 0x002a -> ASTERISK + u'+' # 0x002b -> PLUS SIGN + u',' # 0x002c -> COMMA + u'-' # 0x002d -> HYPHEN-MINUS + u'.' # 0x002e -> FULL STOP + u'/' # 0x002f -> SOLIDUS + u'0' # 0x0030 -> DIGIT ZERO + u'1' # 0x0031 -> DIGIT ONE + u'2' # 0x0032 -> DIGIT TWO + u'3' # 0x0033 -> DIGIT THREE + u'4' # 0x0034 -> DIGIT FOUR + u'5' # 0x0035 -> DIGIT FIVE + u'6' # 0x0036 -> DIGIT SIX + u'7' # 0x0037 -> DIGIT SEVEN + u'8' # 0x0038 -> DIGIT EIGHT + u'9' # 0x0039 -> DIGIT NINE + u':' # 0x003a -> COLON + u';' # 0x003b -> SEMICOLON + u'<' # 0x003c -> LESS-THAN SIGN + u'=' # 0x003d -> EQUALS SIGN + u'>' # 0x003e -> GREATER-THAN SIGN + u'?' # 0x003f -> QUESTION MARK + u'@' # 0x0040 -> COMMERCIAL AT + u'A' # 0x0041 -> LATIN CAPITAL LETTER A + u'B' # 0x0042 -> LATIN CAPITAL LETTER B + u'C' # 0x0043 -> LATIN CAPITAL LETTER C + u'D' # 0x0044 -> LATIN CAPITAL LETTER D + u'E' # 0x0045 -> LATIN CAPITAL LETTER E + u'F' # 0x0046 -> LATIN CAPITAL LETTER F + u'G' # 0x0047 -> LATIN CAPITAL LETTER G + u'H' # 0x0048 -> LATIN CAPITAL LETTER H + u'I' # 0x0049 -> LATIN CAPITAL LETTER I + u'J' # 0x004a -> LATIN CAPITAL LETTER J + u'K' # 0x004b -> LATIN CAPITAL LETTER K + u'L' # 0x004c -> LATIN CAPITAL LETTER L + u'M' # 0x004d -> LATIN CAPITAL LETTER M + u'N' # 0x004e -> LATIN CAPITAL LETTER N + u'O' # 0x004f -> LATIN CAPITAL LETTER O + u'P' # 0x0050 -> LATIN CAPITAL LETTER P + u'Q' # 0x0051 -> LATIN CAPITAL LETTER Q + u'R' # 0x0052 -> LATIN CAPITAL LETTER R + u'S' # 0x0053 -> LATIN CAPITAL LETTER S + u'T' # 0x0054 -> LATIN CAPITAL LETTER T + u'U' # 0x0055 -> LATIN CAPITAL LETTER U + u'V' # 0x0056 -> LATIN CAPITAL LETTER V + u'W' # 0x0057 -> LATIN CAPITAL LETTER W + u'X' # 0x0058 -> LATIN CAPITAL LETTER X + u'Y' # 0x0059 -> LATIN CAPITAL LETTER Y + u'Z' # 0x005a -> LATIN CAPITAL LETTER Z + u'[' # 0x005b -> LEFT SQUARE BRACKET + u'\\' # 0x005c -> REVERSE SOLIDUS + u']' # 0x005d -> RIGHT SQUARE BRACKET + u'^' # 0x005e -> CIRCUMFLEX ACCENT + u'_' # 0x005f -> LOW LINE + u'`' # 0x0060 -> GRAVE ACCENT + u'a' # 0x0061 -> LATIN SMALL LETTER A + u'b' # 0x0062 -> LATIN SMALL LETTER B + u'c' # 0x0063 -> LATIN SMALL LETTER C + u'd' # 0x0064 -> LATIN SMALL LETTER D + u'e' # 0x0065 -> LATIN SMALL LETTER E + u'f' # 0x0066 -> LATIN SMALL LETTER F + u'g' # 0x0067 -> LATIN SMALL LETTER G + u'h' # 0x0068 -> LATIN SMALL LETTER H + u'i' # 0x0069 -> LATIN SMALL LETTER I + u'j' # 0x006a -> LATIN SMALL LETTER J + u'k' # 0x006b -> LATIN SMALL LETTER K + u'l' # 0x006c -> LATIN SMALL LETTER L + u'm' # 0x006d -> LATIN SMALL LETTER M + u'n' # 0x006e -> LATIN SMALL LETTER N + u'o' # 0x006f -> LATIN SMALL LETTER O + u'p' # 0x0070 -> LATIN SMALL LETTER P + u'q' # 0x0071 -> LATIN SMALL LETTER Q + u'r' # 0x0072 -> LATIN SMALL LETTER R + u's' # 0x0073 -> LATIN SMALL LETTER S + u't' # 0x0074 -> LATIN SMALL LETTER T + u'u' # 0x0075 -> LATIN SMALL LETTER U + u'v' # 0x0076 -> LATIN SMALL LETTER V + u'w' # 0x0077 -> LATIN SMALL LETTER W + u'x' # 0x0078 -> LATIN SMALL LETTER X + u'y' # 0x0079 -> LATIN SMALL LETTER Y + u'z' # 0x007a -> LATIN SMALL LETTER Z + u'{' # 0x007b -> LEFT CURLY BRACKET + u'|' # 0x007c -> VERTICAL LINE + u'}' # 0x007d -> RIGHT CURLY BRACKET + u'~' # 0x007e -> TILDE + u'\x7f' # 0x007f -> DELETE + u'\xc7' # 0x0080 -> LATIN CAPITAL LETTER C WITH CEDILLA + u'\xfc' # 0x0081 -> LATIN SMALL LETTER U WITH DIAERESIS + u'\xe9' # 0x0082 -> LATIN SMALL LETTER E WITH ACUTE + u'\xe2' # 0x0083 -> LATIN SMALL LETTER A WITH CIRCUMFLEX + u'\xe4' # 0x0084 -> LATIN SMALL LETTER A WITH DIAERESIS + u'\xe0' # 0x0085 -> LATIN SMALL LETTER A WITH GRAVE + u'\xe5' # 0x0086 -> LATIN SMALL LETTER A WITH RING ABOVE + u'\xe7' # 0x0087 -> LATIN SMALL LETTER C WITH CEDILLA + u'\xea' # 0x0088 -> LATIN SMALL LETTER E WITH CIRCUMFLEX + u'\xeb' # 0x0089 -> LATIN SMALL LETTER E WITH DIAERESIS + u'\xe8' # 0x008a -> LATIN SMALL LETTER E WITH GRAVE + u'\xef' # 0x008b -> LATIN SMALL LETTER I WITH DIAERESIS + u'\xee' # 0x008c -> LATIN SMALL LETTER I WITH CIRCUMFLEX + u'\xec' # 0x008d -> LATIN SMALL LETTER I WITH GRAVE + u'\xc4' # 0x008e -> LATIN CAPITAL LETTER A WITH DIAERESIS + u'\xc5' # 0x008f -> LATIN CAPITAL LETTER A WITH RING ABOVE + u'\xc9' # 0x0090 -> LATIN CAPITAL LETTER E WITH ACUTE + u'\xe6' # 0x0091 -> LATIN SMALL LIGATURE AE + u'\xc6' # 0x0092 -> LATIN CAPITAL LIGATURE AE + u'\xf4' # 0x0093 -> LATIN SMALL LETTER O WITH CIRCUMFLEX + u'\xf6' # 0x0094 -> LATIN SMALL LETTER O WITH DIAERESIS + u'\xf2' # 0x0095 -> LATIN SMALL LETTER O WITH GRAVE + u'\xfb' # 0x0096 -> LATIN SMALL LETTER U WITH CIRCUMFLEX + u'\xf9' # 0x0097 -> LATIN SMALL LETTER U WITH GRAVE + u'\xff' # 0x0098 -> LATIN SMALL LETTER Y WITH DIAERESIS + u'\xd6' # 0x0099 -> LATIN CAPITAL LETTER O WITH DIAERESIS + u'\xdc' # 0x009a -> LATIN CAPITAL LETTER U WITH DIAERESIS + u'\xf8' # 0x009b -> LATIN SMALL LETTER O WITH STROKE + u'\xa3' # 0x009c -> POUND SIGN + u'\xd8' # 0x009d -> LATIN CAPITAL LETTER O WITH STROKE + u'\xd7' # 0x009e -> MULTIPLICATION SIGN + u'\u0192' # 0x009f -> LATIN SMALL LETTER F WITH HOOK + u'\xe1' # 0x00a0 -> LATIN SMALL LETTER A WITH ACUTE + u'\xed' # 0x00a1 -> LATIN SMALL LETTER I WITH ACUTE + u'\xf3' # 0x00a2 -> LATIN SMALL LETTER O WITH ACUTE + u'\xfa' # 0x00a3 -> LATIN SMALL LETTER U WITH ACUTE + u'\xf1' # 0x00a4 -> LATIN SMALL LETTER N WITH TILDE + u'\xd1' # 0x00a5 -> LATIN CAPITAL LETTER N WITH TILDE + u'\xaa' # 0x00a6 -> FEMININE ORDINAL INDICATOR + u'\xba' # 0x00a7 -> MASCULINE ORDINAL INDICATOR + u'\xbf' # 0x00a8 -> INVERTED QUESTION MARK + u'\xae' # 0x00a9 -> REGISTERED SIGN + u'\xac' # 0x00aa -> NOT SIGN + u'\xbd' # 0x00ab -> VULGAR FRACTION ONE HALF + u'\xbc' # 0x00ac -> VULGAR FRACTION ONE QUARTER + u'\xa1' # 0x00ad -> INVERTED EXCLAMATION MARK + u'\xab' # 0x00ae -> LEFT-POINTING DOUBLE ANGLE QUOTATION MARK + u'\xbb' # 0x00af -> RIGHT-POINTING DOUBLE ANGLE QUOTATION MARK + u'\u2591' # 0x00b0 -> LIGHT SHADE + u'\u2592' # 0x00b1 -> MEDIUM SHADE + u'\u2593' # 0x00b2 -> DARK SHADE + u'\u2502' # 0x00b3 -> BOX DRAWINGS LIGHT VERTICAL + u'\u2524' # 0x00b4 -> BOX DRAWINGS LIGHT VERTICAL AND LEFT + u'\xc1' # 0x00b5 -> LATIN CAPITAL LETTER A WITH ACUTE + u'\xc2' # 0x00b6 -> LATIN CAPITAL LETTER A WITH CIRCUMFLEX + u'\xc0' # 0x00b7 -> LATIN CAPITAL LETTER A WITH GRAVE + u'\xa9' # 0x00b8 -> COPYRIGHT SIGN + u'\u2563' # 0x00b9 -> BOX DRAWINGS DOUBLE VERTICAL AND LEFT + u'\u2551' # 0x00ba -> BOX DRAWINGS DOUBLE VERTICAL + u'\u2557' # 0x00bb -> BOX DRAWINGS DOUBLE DOWN AND LEFT + u'\u255d' # 0x00bc -> BOX DRAWINGS DOUBLE UP AND LEFT + u'\xa2' # 0x00bd -> CENT SIGN + u'\xa5' # 0x00be -> YEN SIGN + u'\u2510' # 0x00bf -> BOX DRAWINGS LIGHT DOWN AND LEFT + u'\u2514' # 0x00c0 -> BOX DRAWINGS LIGHT UP AND RIGHT + u'\u2534' # 0x00c1 -> BOX DRAWINGS LIGHT UP AND HORIZONTAL + u'\u252c' # 0x00c2 -> BOX DRAWINGS LIGHT DOWN AND HORIZONTAL + u'\u251c' # 0x00c3 -> BOX DRAWINGS LIGHT VERTICAL AND RIGHT + u'\u2500' # 0x00c4 -> BOX DRAWINGS LIGHT HORIZONTAL + u'\u253c' # 0x00c5 -> BOX DRAWINGS LIGHT VERTICAL AND HORIZONTAL + u'\xe3' # 0x00c6 -> LATIN SMALL LETTER A WITH TILDE + u'\xc3' # 0x00c7 -> LATIN CAPITAL LETTER A WITH TILDE + u'\u255a' # 0x00c8 -> BOX DRAWINGS DOUBLE UP AND RIGHT + u'\u2554' # 0x00c9 -> BOX DRAWINGS DOUBLE DOWN AND RIGHT + u'\u2569' # 0x00ca -> BOX DRAWINGS DOUBLE UP AND HORIZONTAL + u'\u2566' # 0x00cb -> BOX DRAWINGS DOUBLE DOWN AND HORIZONTAL + u'\u2560' # 0x00cc -> BOX DRAWINGS DOUBLE VERTICAL AND RIGHT + u'\u2550' # 0x00cd -> BOX DRAWINGS DOUBLE HORIZONTAL + u'\u256c' # 0x00ce -> BOX DRAWINGS DOUBLE VERTICAL AND HORIZONTAL + u'\xa4' # 0x00cf -> CURRENCY SIGN + u'\xf0' # 0x00d0 -> LATIN SMALL LETTER ETH + u'\xd0' # 0x00d1 -> LATIN CAPITAL LETTER ETH + u'\xca' # 0x00d2 -> LATIN CAPITAL LETTER E WITH CIRCUMFLEX + u'\xcb' # 0x00d3 -> LATIN CAPITAL LETTER E WITH DIAERESIS + u'\xc8' # 0x00d4 -> LATIN CAPITAL LETTER E WITH GRAVE + u'\u20ac' # 0x00d5 -> EURO SIGN + u'\xcd' # 0x00d6 -> LATIN CAPITAL LETTER I WITH ACUTE + u'\xce' # 0x00d7 -> LATIN CAPITAL LETTER I WITH CIRCUMFLEX + u'\xcf' # 0x00d8 -> LATIN CAPITAL LETTER I WITH DIAERESIS + u'\u2518' # 0x00d9 -> BOX DRAWINGS LIGHT UP AND LEFT + u'\u250c' # 0x00da -> BOX DRAWINGS LIGHT DOWN AND RIGHT + u'\u2588' # 0x00db -> FULL BLOCK + u'\u2584' # 0x00dc -> LOWER HALF BLOCK + u'\xa6' # 0x00dd -> BROKEN BAR + u'\xcc' # 0x00de -> LATIN CAPITAL LETTER I WITH GRAVE + u'\u2580' # 0x00df -> UPPER HALF BLOCK + u'\xd3' # 0x00e0 -> LATIN CAPITAL LETTER O WITH ACUTE + u'\xdf' # 0x00e1 -> LATIN SMALL LETTER SHARP S + u'\xd4' # 0x00e2 -> LATIN CAPITAL LETTER O WITH CIRCUMFLEX + u'\xd2' # 0x00e3 -> LATIN CAPITAL LETTER O WITH GRAVE + u'\xf5' # 0x00e4 -> LATIN SMALL LETTER O WITH TILDE + u'\xd5' # 0x00e5 -> LATIN CAPITAL LETTER O WITH TILDE + u'\xb5' # 0x00e6 -> MICRO SIGN + u'\xfe' # 0x00e7 -> LATIN SMALL LETTER THORN + u'\xde' # 0x00e8 -> LATIN CAPITAL LETTER THORN + u'\xda' # 0x00e9 -> LATIN CAPITAL LETTER U WITH ACUTE + u'\xdb' # 0x00ea -> LATIN CAPITAL LETTER U WITH CIRCUMFLEX + u'\xd9' # 0x00eb -> LATIN CAPITAL LETTER U WITH GRAVE + u'\xfd' # 0x00ec -> LATIN SMALL LETTER Y WITH ACUTE + u'\xdd' # 0x00ed -> LATIN CAPITAL LETTER Y WITH ACUTE + u'\xaf' # 0x00ee -> MACRON + u'\xb4' # 0x00ef -> ACUTE ACCENT + u'\xad' # 0x00f0 -> SOFT HYPHEN + u'\xb1' # 0x00f1 -> PLUS-MINUS SIGN + u'\u2017' # 0x00f2 -> DOUBLE LOW LINE + u'\xbe' # 0x00f3 -> VULGAR FRACTION THREE QUARTERS + u'\xb6' # 0x00f4 -> PILCROW SIGN + u'\xa7' # 0x00f5 -> SECTION SIGN + u'\xf7' # 0x00f6 -> DIVISION SIGN + u'\xb8' # 0x00f7 -> CEDILLA + u'\xb0' # 0x00f8 -> DEGREE SIGN + u'\xa8' # 0x00f9 -> DIAERESIS + u'\xb7' # 0x00fa -> MIDDLE DOT + u'\xb9' # 0x00fb -> SUPERSCRIPT ONE + u'\xb3' # 0x00fc -> SUPERSCRIPT THREE + u'\xb2' # 0x00fd -> SUPERSCRIPT TWO + u'\u25a0' # 0x00fe -> BLACK SQUARE + u'\xa0' # 0x00ff -> NO-BREAK SPACE +) + +### Encoding Map + +encoding_map = { + 0x0000: 0x0000, # NULL + 0x0001: 0x0001, # START OF HEADING + 0x0002: 0x0002, # START OF TEXT + 0x0003: 0x0003, # END OF TEXT + 0x0004: 0x0004, # END OF TRANSMISSION + 0x0005: 0x0005, # ENQUIRY + 0x0006: 0x0006, # ACKNOWLEDGE + 0x0007: 0x0007, # BELL + 0x0008: 0x0008, # BACKSPACE + 0x0009: 0x0009, # HORIZONTAL TABULATION + 0x000a: 0x000a, # LINE FEED + 0x000b: 0x000b, # VERTICAL TABULATION + 0x000c: 0x000c, # FORM FEED + 0x000d: 0x000d, # CARRIAGE RETURN + 0x000e: 0x000e, # SHIFT OUT + 0x000f: 0x000f, # SHIFT IN + 0x0010: 0x0010, # DATA LINK ESCAPE + 0x0011: 0x0011, # DEVICE CONTROL ONE + 0x0012: 0x0012, # DEVICE CONTROL TWO + 0x0013: 0x0013, # DEVICE CONTROL THREE + 0x0014: 0x0014, # DEVICE CONTROL FOUR + 0x0015: 0x0015, # NEGATIVE ACKNOWLEDGE + 0x0016: 0x0016, # SYNCHRONOUS IDLE + 0x0017: 0x0017, # END OF TRANSMISSION BLOCK + 0x0018: 0x0018, # CANCEL + 0x0019: 0x0019, # END OF MEDIUM + 0x001a: 0x001a, # SUBSTITUTE + 0x001b: 0x001b, # ESCAPE + 0x001c: 0x001c, # FILE SEPARATOR + 0x001d: 0x001d, # GROUP SEPARATOR + 0x001e: 0x001e, # RECORD SEPARATOR + 0x001f: 0x001f, # UNIT SEPARATOR + 0x0020: 0x0020, # SPACE + 0x0021: 0x0021, # EXCLAMATION MARK + 0x0022: 0x0022, # QUOTATION MARK + 0x0023: 0x0023, # NUMBER SIGN + 0x0024: 0x0024, # DOLLAR SIGN + 0x0025: 0x0025, # PERCENT SIGN + 0x0026: 0x0026, # AMPERSAND + 0x0027: 0x0027, # APOSTROPHE + 0x0028: 0x0028, # LEFT PARENTHESIS + 0x0029: 0x0029, # RIGHT PARENTHESIS + 0x002a: 0x002a, # ASTERISK + 0x002b: 0x002b, # PLUS SIGN + 0x002c: 0x002c, # COMMA + 0x002d: 0x002d, # HYPHEN-MINUS + 0x002e: 0x002e, # FULL STOP + 0x002f: 0x002f, # SOLIDUS + 0x0030: 0x0030, # DIGIT ZERO + 0x0031: 0x0031, # DIGIT ONE + 0x0032: 0x0032, # DIGIT TWO + 0x0033: 0x0033, # DIGIT THREE + 0x0034: 0x0034, # DIGIT FOUR + 0x0035: 0x0035, # DIGIT FIVE + 0x0036: 0x0036, # DIGIT SIX + 0x0037: 0x0037, # DIGIT SEVEN + 0x0038: 0x0038, # DIGIT EIGHT + 0x0039: 0x0039, # DIGIT NINE + 0x003a: 0x003a, # COLON + 0x003b: 0x003b, # SEMICOLON + 0x003c: 0x003c, # LESS-THAN SIGN + 0x003d: 0x003d, # EQUALS SIGN + 0x003e: 0x003e, # GREATER-THAN SIGN + 0x003f: 0x003f, # QUESTION MARK + 0x0040: 0x0040, # COMMERCIAL AT + 0x0041: 0x0041, # LATIN CAPITAL LETTER A + 0x0042: 0x0042, # LATIN CAPITAL LETTER B + 0x0043: 0x0043, # LATIN CAPITAL LETTER C + 0x0044: 0x0044, # LATIN CAPITAL LETTER D + 0x0045: 0x0045, # LATIN CAPITAL LETTER E + 0x0046: 0x0046, # LATIN CAPITAL LETTER F + 0x0047: 0x0047, # LATIN CAPITAL LETTER G + 0x0048: 0x0048, # LATIN CAPITAL LETTER H + 0x0049: 0x0049, # LATIN CAPITAL LETTER I + 0x004a: 0x004a, # LATIN CAPITAL LETTER J + 0x004b: 0x004b, # LATIN CAPITAL LETTER K + 0x004c: 0x004c, # LATIN CAPITAL LETTER L + 0x004d: 0x004d, # LATIN CAPITAL LETTER M + 0x004e: 0x004e, # LATIN CAPITAL LETTER N + 0x004f: 0x004f, # LATIN CAPITAL LETTER O + 0x0050: 0x0050, # LATIN CAPITAL LETTER P + 0x0051: 0x0051, # LATIN CAPITAL LETTER Q + 0x0052: 0x0052, # LATIN CAPITAL LETTER R + 0x0053: 0x0053, # LATIN CAPITAL LETTER S + 0x0054: 0x0054, # LATIN CAPITAL LETTER T + 0x0055: 0x0055, # LATIN CAPITAL LETTER U + 0x0056: 0x0056, # LATIN CAPITAL LETTER V + 0x0057: 0x0057, # LATIN CAPITAL LETTER W + 0x0058: 0x0058, # LATIN CAPITAL LETTER X + 0x0059: 0x0059, # LATIN CAPITAL LETTER Y + 0x005a: 0x005a, # LATIN CAPITAL LETTER Z + 0x005b: 0x005b, # LEFT SQUARE BRACKET + 0x005c: 0x005c, # REVERSE SOLIDUS + 0x005d: 0x005d, # RIGHT SQUARE BRACKET + 0x005e: 0x005e, # CIRCUMFLEX ACCENT + 0x005f: 0x005f, # LOW LINE + 0x0060: 0x0060, # GRAVE ACCENT + 0x0061: 0x0061, # LATIN SMALL LETTER A + 0x0062: 0x0062, # LATIN SMALL LETTER B + 0x0063: 0x0063, # LATIN SMALL LETTER C + 0x0064: 0x0064, # LATIN SMALL LETTER D + 0x0065: 0x0065, # LATIN SMALL LETTER E + 0x0066: 0x0066, # LATIN SMALL LETTER F + 0x0067: 0x0067, # LATIN SMALL LETTER G + 0x0068: 0x0068, # LATIN SMALL LETTER H + 0x0069: 0x0069, # LATIN SMALL LETTER I + 0x006a: 0x006a, # LATIN SMALL LETTER J + 0x006b: 0x006b, # LATIN SMALL LETTER K + 0x006c: 0x006c, # LATIN SMALL LETTER L + 0x006d: 0x006d, # LATIN SMALL LETTER M + 0x006e: 0x006e, # LATIN SMALL LETTER N + 0x006f: 0x006f, # LATIN SMALL LETTER O + 0x0070: 0x0070, # LATIN SMALL LETTER P + 0x0071: 0x0071, # LATIN SMALL LETTER Q + 0x0072: 0x0072, # LATIN SMALL LETTER R + 0x0073: 0x0073, # LATIN SMALL LETTER S + 0x0074: 0x0074, # LATIN SMALL LETTER T + 0x0075: 0x0075, # LATIN SMALL LETTER U + 0x0076: 0x0076, # LATIN SMALL LETTER V + 0x0077: 0x0077, # LATIN SMALL LETTER W + 0x0078: 0x0078, # LATIN SMALL LETTER X + 0x0079: 0x0079, # LATIN SMALL LETTER Y + 0x007a: 0x007a, # LATIN SMALL LETTER Z + 0x007b: 0x007b, # LEFT CURLY BRACKET + 0x007c: 0x007c, # VERTICAL LINE + 0x007d: 0x007d, # RIGHT CURLY BRACKET + 0x007e: 0x007e, # TILDE + 0x007f: 0x007f, # DELETE + 0x00a0: 0x00ff, # NO-BREAK SPACE + 0x00a1: 0x00ad, # INVERTED EXCLAMATION MARK + 0x00a2: 0x00bd, # CENT SIGN + 0x00a3: 0x009c, # POUND SIGN + 0x00a4: 0x00cf, # CURRENCY SIGN + 0x00a5: 0x00be, # YEN SIGN + 0x00a6: 0x00dd, # BROKEN BAR + 0x00a7: 0x00f5, # SECTION SIGN + 0x00a8: 0x00f9, # DIAERESIS + 0x00a9: 0x00b8, # COPYRIGHT SIGN + 0x00aa: 0x00a6, # FEMININE ORDINAL INDICATOR + 0x00ab: 0x00ae, # LEFT-POINTING DOUBLE ANGLE QUOTATION MARK + 0x00ac: 0x00aa, # NOT SIGN + 0x00ad: 0x00f0, # SOFT HYPHEN + 0x00ae: 0x00a9, # REGISTERED SIGN + 0x00af: 0x00ee, # MACRON + 0x00b0: 0x00f8, # DEGREE SIGN + 0x00b1: 0x00f1, # PLUS-MINUS SIGN + 0x00b2: 0x00fd, # SUPERSCRIPT TWO + 0x00b3: 0x00fc, # SUPERSCRIPT THREE + 0x00b4: 0x00ef, # ACUTE ACCENT + 0x00b5: 0x00e6, # MICRO SIGN + 0x00b6: 0x00f4, # PILCROW SIGN + 0x00b7: 0x00fa, # MIDDLE DOT + 0x00b8: 0x00f7, # CEDILLA + 0x00b9: 0x00fb, # SUPERSCRIPT ONE + 0x00ba: 0x00a7, # MASCULINE ORDINAL INDICATOR + 0x00bb: 0x00af, # RIGHT-POINTING DOUBLE ANGLE QUOTATION MARK + 0x00bc: 0x00ac, # VULGAR FRACTION ONE QUARTER + 0x00bd: 0x00ab, # VULGAR FRACTION ONE HALF + 0x00be: 0x00f3, # VULGAR FRACTION THREE QUARTERS + 0x00bf: 0x00a8, # INVERTED QUESTION MARK + 0x00c0: 0x00b7, # LATIN CAPITAL LETTER A WITH GRAVE + 0x00c1: 0x00b5, # LATIN CAPITAL LETTER A WITH ACUTE + 0x00c2: 0x00b6, # LATIN CAPITAL LETTER A WITH CIRCUMFLEX + 0x00c3: 0x00c7, # LATIN CAPITAL LETTER A WITH TILDE + 0x00c4: 0x008e, # LATIN CAPITAL LETTER A WITH DIAERESIS + 0x00c5: 0x008f, # LATIN CAPITAL LETTER A WITH RING ABOVE + 0x00c6: 0x0092, # LATIN CAPITAL LIGATURE AE + 0x00c7: 0x0080, # LATIN CAPITAL LETTER C WITH CEDILLA + 0x00c8: 0x00d4, # LATIN CAPITAL LETTER E WITH GRAVE + 0x00c9: 0x0090, # LATIN CAPITAL LETTER E WITH ACUTE + 0x00ca: 0x00d2, # LATIN CAPITAL LETTER E WITH CIRCUMFLEX + 0x00cb: 0x00d3, # LATIN CAPITAL LETTER E WITH DIAERESIS + 0x00cc: 0x00de, # LATIN CAPITAL LETTER I WITH GRAVE + 0x00cd: 0x00d6, # LATIN CAPITAL LETTER I WITH ACUTE + 0x00ce: 0x00d7, # LATIN CAPITAL LETTER I WITH CIRCUMFLEX + 0x00cf: 0x00d8, # LATIN CAPITAL LETTER I WITH DIAERESIS + 0x00d0: 0x00d1, # LATIN CAPITAL LETTER ETH + 0x00d1: 0x00a5, # LATIN CAPITAL LETTER N WITH TILDE + 0x00d2: 0x00e3, # LATIN CAPITAL LETTER O WITH GRAVE + 0x00d3: 0x00e0, # LATIN CAPITAL LETTER O WITH ACUTE + 0x00d4: 0x00e2, # LATIN CAPITAL LETTER O WITH CIRCUMFLEX + 0x00d5: 0x00e5, # LATIN CAPITAL LETTER O WITH TILDE + 0x00d6: 0x0099, # LATIN CAPITAL LETTER O WITH DIAERESIS + 0x00d7: 0x009e, # MULTIPLICATION SIGN + 0x00d8: 0x009d, # LATIN CAPITAL LETTER O WITH STROKE + 0x00d9: 0x00eb, # LATIN CAPITAL LETTER U WITH GRAVE + 0x00da: 0x00e9, # LATIN CAPITAL LETTER U WITH ACUTE + 0x00db: 0x00ea, # LATIN CAPITAL LETTER U WITH CIRCUMFLEX + 0x00dc: 0x009a, # LATIN CAPITAL LETTER U WITH DIAERESIS + 0x00dd: 0x00ed, # LATIN CAPITAL LETTER Y WITH ACUTE + 0x00de: 0x00e8, # LATIN CAPITAL LETTER THORN + 0x00df: 0x00e1, # LATIN SMALL LETTER SHARP S + 0x00e0: 0x0085, # LATIN SMALL LETTER A WITH GRAVE + 0x00e1: 0x00a0, # LATIN SMALL LETTER A WITH ACUTE + 0x00e2: 0x0083, # LATIN SMALL LETTER A WITH CIRCUMFLEX + 0x00e3: 0x00c6, # LATIN SMALL LETTER A WITH TILDE + 0x00e4: 0x0084, # LATIN SMALL LETTER A WITH DIAERESIS + 0x00e5: 0x0086, # LATIN SMALL LETTER A WITH RING ABOVE + 0x00e6: 0x0091, # LATIN SMALL LIGATURE AE + 0x00e7: 0x0087, # LATIN SMALL LETTER C WITH CEDILLA + 0x00e8: 0x008a, # LATIN SMALL LETTER E WITH GRAVE + 0x00e9: 0x0082, # LATIN SMALL LETTER E WITH ACUTE + 0x00ea: 0x0088, # LATIN SMALL LETTER E WITH CIRCUMFLEX + 0x00eb: 0x0089, # LATIN SMALL LETTER E WITH DIAERESIS + 0x00ec: 0x008d, # LATIN SMALL LETTER I WITH GRAVE + 0x00ed: 0x00a1, # LATIN SMALL LETTER I WITH ACUTE + 0x00ee: 0x008c, # LATIN SMALL LETTER I WITH CIRCUMFLEX + 0x00ef: 0x008b, # LATIN SMALL LETTER I WITH DIAERESIS + 0x00f0: 0x00d0, # LATIN SMALL LETTER ETH + 0x00f1: 0x00a4, # LATIN SMALL LETTER N WITH TILDE + 0x00f2: 0x0095, # LATIN SMALL LETTER O WITH GRAVE + 0x00f3: 0x00a2, # LATIN SMALL LETTER O WITH ACUTE + 0x00f4: 0x0093, # LATIN SMALL LETTER O WITH CIRCUMFLEX + 0x00f5: 0x00e4, # LATIN SMALL LETTER O WITH TILDE + 0x00f6: 0x0094, # LATIN SMALL LETTER O WITH DIAERESIS + 0x00f7: 0x00f6, # DIVISION SIGN + 0x00f8: 0x009b, # LATIN SMALL LETTER O WITH STROKE + 0x00f9: 0x0097, # LATIN SMALL LETTER U WITH GRAVE + 0x00fa: 0x00a3, # LATIN SMALL LETTER U WITH ACUTE + 0x00fb: 0x0096, # LATIN SMALL LETTER U WITH CIRCUMFLEX + 0x00fc: 0x0081, # LATIN SMALL LETTER U WITH DIAERESIS + 0x00fd: 0x00ec, # LATIN SMALL LETTER Y WITH ACUTE + 0x00fe: 0x00e7, # LATIN SMALL LETTER THORN + 0x00ff: 0x0098, # LATIN SMALL LETTER Y WITH DIAERESIS + 0x20ac: 0x00d5, # EURO SIGN + 0x0192: 0x009f, # LATIN SMALL LETTER F WITH HOOK + 0x2017: 0x00f2, # DOUBLE LOW LINE + 0x2500: 0x00c4, # BOX DRAWINGS LIGHT HORIZONTAL + 0x2502: 0x00b3, # BOX DRAWINGS LIGHT VERTICAL + 0x250c: 0x00da, # BOX DRAWINGS LIGHT DOWN AND RIGHT + 0x2510: 0x00bf, # BOX DRAWINGS LIGHT DOWN AND LEFT + 0x2514: 0x00c0, # BOX DRAWINGS LIGHT UP AND RIGHT + 0x2518: 0x00d9, # BOX DRAWINGS LIGHT UP AND LEFT + 0x251c: 0x00c3, # BOX DRAWINGS LIGHT VERTICAL AND RIGHT + 0x2524: 0x00b4, # BOX DRAWINGS LIGHT VERTICAL AND LEFT + 0x252c: 0x00c2, # BOX DRAWINGS LIGHT DOWN AND HORIZONTAL + 0x2534: 0x00c1, # BOX DRAWINGS LIGHT UP AND HORIZONTAL + 0x253c: 0x00c5, # BOX DRAWINGS LIGHT VERTICAL AND HORIZONTAL + 0x2550: 0x00cd, # BOX DRAWINGS DOUBLE HORIZONTAL + 0x2551: 0x00ba, # BOX DRAWINGS DOUBLE VERTICAL + 0x2554: 0x00c9, # BOX DRAWINGS DOUBLE DOWN AND RIGHT + 0x2557: 0x00bb, # BOX DRAWINGS DOUBLE DOWN AND LEFT + 0x255a: 0x00c8, # BOX DRAWINGS DOUBLE UP AND RIGHT + 0x255d: 0x00bc, # BOX DRAWINGS DOUBLE UP AND LEFT + 0x2560: 0x00cc, # BOX DRAWINGS DOUBLE VERTICAL AND RIGHT + 0x2563: 0x00b9, # BOX DRAWINGS DOUBLE VERTICAL AND LEFT + 0x2566: 0x00cb, # BOX DRAWINGS DOUBLE DOWN AND HORIZONTAL + 0x2569: 0x00ca, # BOX DRAWINGS DOUBLE UP AND HORIZONTAL + 0x256c: 0x00ce, # BOX DRAWINGS DOUBLE VERTICAL AND HORIZONTAL + 0x2580: 0x00df, # UPPER HALF BLOCK + 0x2584: 0x00dc, # LOWER HALF BLOCK + 0x2588: 0x00db, # FULL BLOCK + 0x2591: 0x00b0, # LIGHT SHADE + 0x2592: 0x00b1, # MEDIUM SHADE + 0x2593: 0x00b2, # DARK SHADE + 0x25a0: 0x00fe, # BLACK SQUARE +} Modified: python/trunk/Lib/test/test_codecs.py ============================================================================== --- python/trunk/Lib/test/test_codecs.py (original) +++ python/trunk/Lib/test/test_codecs.py Mon May 24 23:29:07 2010 @@ -1190,6 +1190,7 @@ "cp424", "cp437", "cp500", + "cp720", "cp737", "cp775", "cp850", @@ -1197,6 +1198,7 @@ "cp855", "cp856", "cp857", + "cp858", "cp860", "cp861", "cp862", Modified: python/trunk/Lib/test/test_unicode.py ============================================================================== --- python/trunk/Lib/test/test_unicode.py (original) +++ python/trunk/Lib/test/test_unicode.py Mon May 24 23:29:07 2010 @@ -700,8 +700,8 @@ s = ''.join(map(chr, xrange(128))) for encoding in ( 'cp037', 'cp1026', - 'cp437', 'cp500', 'cp737', 'cp775', 'cp850', - 'cp852', 'cp855', 'cp860', 'cp861', 'cp862', + 'cp437', 'cp500', 'cp720', 'cp737', 'cp775', 'cp850', + 'cp852', 'cp855', 'cp858', 'cp860', 'cp861', 'cp862', 'cp863', 'cp865', 'cp866', 'iso8859_10', 'iso8859_13', 'iso8859_14', 'iso8859_15', 'iso8859_2', 'iso8859_3', 'iso8859_4', 'iso8859_5', 'iso8859_6', @@ -728,8 +728,8 @@ s = ''.join(map(chr, xrange(128, 256))) for encoding in ( 'cp037', 'cp1026', - 'cp437', 'cp500', 'cp737', 'cp775', 'cp850', - 'cp852', 'cp855', 'cp860', 'cp861', 'cp862', + 'cp437', 'cp500', 'cp720', 'cp737', 'cp775', 'cp850', + 'cp852', 'cp855', 'cp858', 'cp860', 'cp861', 'cp862', 'cp863', 'cp865', 'cp866', 'iso8859_10', 'iso8859_13', 'iso8859_14', 'iso8859_15', 'iso8859_2', 'iso8859_4', 'iso8859_5', Modified: python/trunk/Misc/NEWS ============================================================================== --- python/trunk/Misc/NEWS (original) +++ python/trunk/Misc/NEWS Mon May 24 23:29:07 2010 @@ -29,6 +29,8 @@ Library ------- +- Issue #8016: Add the CP858 codec. + - Issue #3924: Ignore cookies with invalid "version" field in cookielib. - Issue #6268: Fix seek() method of codecs.open(), don't read or write the BOM From python-checkins at python.org Mon May 24 23:33:24 2010 From: python-checkins at python.org (victor.stinner) Date: Mon, 24 May 2010 23:33:24 +0200 (CEST) Subject: [Python-checkins] r81500 - in python/trunk: Lib/HTMLParser.py Lib/test/test_htmlparser.py Misc/NEWS Message-ID: <20100524213324.C5AC0EE984@mail.python.org> Author: victor.stinner Date: Mon May 24 23:33:24 2010 New Revision: 81500 Log: Issue #6662: Fix parsing of malformatted charref (&#bad;) Modified: python/trunk/Lib/HTMLParser.py python/trunk/Lib/test/test_htmlparser.py python/trunk/Misc/NEWS Modified: python/trunk/Lib/HTMLParser.py ============================================================================== --- python/trunk/Lib/HTMLParser.py (original) +++ python/trunk/Lib/HTMLParser.py Mon May 24 23:33:24 2010 @@ -175,6 +175,9 @@ i = self.updatepos(i, k) continue else: + if ";" in rawdata[i:]: #bail by consuming &# + self.handle_data(rawdata[0:2]) + i = self.updatepos(i, 2) break elif startswith('&', i): match = entityref.match(rawdata, i) Modified: python/trunk/Lib/test/test_htmlparser.py ============================================================================== --- python/trunk/Lib/test/test_htmlparser.py (original) +++ python/trunk/Lib/test/test_htmlparser.py Mon May 24 23:33:24 2010 @@ -313,6 +313,13 @@ ("starttag", "html", [("foo", u"\u20AC&aa&unsupported;")]) ]) + def test_malformatted_charref(self): + self._run_check("

    &#bad;

    ", [ + ("starttag", "p", []), + ("data", "&#bad;"), + ("endtag", "p"), + ]) + def test_main(): test_support.run_unittest(HTMLParserTestCase) Modified: python/trunk/Misc/NEWS ============================================================================== --- python/trunk/Misc/NEWS (original) +++ python/trunk/Misc/NEWS Mon May 24 23:33:24 2010 @@ -29,6 +29,8 @@ Library ------- +- Issue #6662: Fix parsing of malformatted charref (&#bad;) + - Issue #8016: Add the CP858 codec. - Issue #3924: Ignore cookies with invalid "version" field in cookielib. From python-checkins at python.org Mon May 24 23:37:28 2010 From: python-checkins at python.org (victor.stinner) Date: Mon, 24 May 2010 23:37:28 +0200 (CEST) Subject: [Python-checkins] r81501 - in python/trunk/Misc: ACKS NEWS Message-ID: <20100524213728.B7B0AEE984@mail.python.org> Author: victor.stinner Date: Mon May 24 23:37:28 2010 New Revision: 81501 Log: Add the author of the last fix (Issue #6662) Modified: python/trunk/Misc/ACKS python/trunk/Misc/NEWS Modified: python/trunk/Misc/ACKS ============================================================================== --- python/trunk/Misc/ACKS (original) +++ python/trunk/Misc/ACKS Mon May 24 23:37:28 2010 @@ -860,3 +860,4 @@ Uwe Zessin Tarek Ziad? Peter ?strand +Fredrik H??rd Modified: python/trunk/Misc/NEWS ============================================================================== --- python/trunk/Misc/NEWS (original) +++ python/trunk/Misc/NEWS Mon May 24 23:37:28 2010 @@ -29,7 +29,8 @@ Library ------- -- Issue #6662: Fix parsing of malformatted charref (&#bad;) +- Issue #6662: Fix parsing of malformatted charref (&#bad;), patch written by + Fredrik H??rd - Issue #8016: Add the CP858 codec. From python-checkins at python.org Mon May 24 23:37:54 2010 From: python-checkins at python.org (georg.brandl) Date: Mon, 24 May 2010 23:37:54 +0200 (CEST) Subject: [Python-checkins] r81502 - python/trunk/Demo/turtle/turtleDemo.py Message-ID: <20100524213754.C877EEE984@mail.python.org> Author: georg.brandl Date: Mon May 24 23:37:54 2010 New Revision: 81502 Log: #8616: update module name Modified: python/trunk/Demo/turtle/turtleDemo.py Modified: python/trunk/Demo/turtle/turtleDemo.py ============================================================================== --- python/trunk/Demo/turtle/turtleDemo.py (original) +++ python/trunk/Demo/turtle/turtleDemo.py Mon May 24 23:37:54 2010 @@ -212,7 +212,7 @@ self.text.delete("1.0", "end") self.text.insert("1.0",chars) direc, fname = os.path.split(filename) - self.root.title(fname[6:-3]+" - an xturtle example") + self.root.title(fname[6:-3]+" - a Python turtle graphics example") self.module = __import__(fname[:-3]) reload(self.module) self.configGUI(NORMAL, NORMAL, DISABLED, DISABLED, From python-checkins at python.org Mon May 24 23:42:59 2010 From: python-checkins at python.org (victor.stinner) Date: Mon, 24 May 2010 23:42:59 +0200 (CEST) Subject: [Python-checkins] r81503 - in python/branches/release26-maint: Lib/HTMLParser.py Lib/test/test_htmlparser.py Misc/ACKS Misc/NEWS Message-ID: <20100524214259.DAFA0EE9B7@mail.python.org> Author: victor.stinner Date: Mon May 24 23:42:59 2010 New Revision: 81503 Log: Merged revisions 81500-81501 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r81500 | victor.stinner | 2010-05-24 23:33:24 +0200 (lun., 24 mai 2010) | 2 lines Issue #6662: Fix parsing of malformatted charref (&#bad;) ........ r81501 | victor.stinner | 2010-05-24 23:37:28 +0200 (lun., 24 mai 2010) | 2 lines Add the author of the last fix (Issue #6662) ........ Modified: python/branches/release26-maint/ (props changed) python/branches/release26-maint/Lib/HTMLParser.py python/branches/release26-maint/Lib/test/test_htmlparser.py python/branches/release26-maint/Misc/ACKS python/branches/release26-maint/Misc/NEWS Modified: python/branches/release26-maint/Lib/HTMLParser.py ============================================================================== --- python/branches/release26-maint/Lib/HTMLParser.py (original) +++ python/branches/release26-maint/Lib/HTMLParser.py Mon May 24 23:42:59 2010 @@ -175,6 +175,9 @@ i = self.updatepos(i, k) continue else: + if ";" in rawdata[i:]: #bail by consuming &# + self.handle_data(rawdata[0:2]) + i = self.updatepos(i, 2) break elif startswith('&', i): match = entityref.match(rawdata, i) Modified: python/branches/release26-maint/Lib/test/test_htmlparser.py ============================================================================== --- python/branches/release26-maint/Lib/test/test_htmlparser.py (original) +++ python/branches/release26-maint/Lib/test/test_htmlparser.py Mon May 24 23:42:59 2010 @@ -313,6 +313,13 @@ ("starttag", "html", [("foo", u"\u20AC&aa&unsupported;")]) ]) + def test_malformatted_charref(self): + self._run_check("

    &#bad;

    ", [ + ("starttag", "p", []), + ("data", "&#bad;"), + ("endtag", "p"), + ]) + def test_main(): test_support.run_unittest(HTMLParserTestCase) Modified: python/branches/release26-maint/Misc/ACKS ============================================================================== --- python/branches/release26-maint/Misc/ACKS (original) +++ python/branches/release26-maint/Misc/ACKS Mon May 24 23:42:59 2010 @@ -191,7 +191,7 @@ Andy Dustman Gary Duzan Eugene Dvurechenski -Josip Dzolonga +Josip Dzolonga Maxim Dzumanenko Walter D?rwald Hans Eckardt @@ -812,3 +812,4 @@ Tarek Ziad? Peter ?strand Jesse Noller +Fredrik H??rd Modified: python/branches/release26-maint/Misc/NEWS ============================================================================== --- python/branches/release26-maint/Misc/NEWS (original) +++ python/branches/release26-maint/Misc/NEWS Mon May 24 23:42:59 2010 @@ -55,6 +55,9 @@ Library ------- +- Issue #6662: Fix parsing of malformatted charref (&#bad;), patch written by + Fredrik H????rd + - Issue #1628205: Socket file objects returned by socket.socket.makefile() now properly handles EINTR within the read, readline, write & flush methods. The socket.sendall() method now properly handles interrupted system calls. From python-checkins at python.org Mon May 24 23:46:26 2010 From: python-checkins at python.org (victor.stinner) Date: Mon, 24 May 2010 23:46:26 +0200 (CEST) Subject: [Python-checkins] r81504 - in python/branches/py3k: Lib/html/parser.py Lib/test/test_htmlparser.py Misc/ACKS Misc/NEWS Message-ID: <20100524214626.1D1F8EB74@mail.python.org> Author: victor.stinner Date: Mon May 24 23:46:25 2010 New Revision: 81504 Log: Recorded merge of revisions 81500-81501 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r81500 | victor.stinner | 2010-05-24 23:33:24 +0200 (lun., 24 mai 2010) | 2 lines Issue #6662: Fix parsing of malformatted charref (&#bad;) ........ r81501 | victor.stinner | 2010-05-24 23:37:28 +0200 (lun., 24 mai 2010) | 2 lines Add the author of the last fix (Issue #6662) ........ Modified: python/branches/py3k/ (props changed) python/branches/py3k/Lib/html/parser.py python/branches/py3k/Lib/test/test_htmlparser.py python/branches/py3k/Misc/ACKS python/branches/py3k/Misc/NEWS Modified: python/branches/py3k/Lib/html/parser.py ============================================================================== --- python/branches/py3k/Lib/html/parser.py (original) +++ python/branches/py3k/Lib/html/parser.py Mon May 24 23:46:25 2010 @@ -175,6 +175,9 @@ i = self.updatepos(i, k) continue else: + if ";" in rawdata[i:]: #bail by consuming &# + self.handle_data(rawdata[0:2]) + i = self.updatepos(i, 2) break elif startswith('&', i): match = entityref.match(rawdata, i) Modified: python/branches/py3k/Lib/test/test_htmlparser.py ============================================================================== --- python/branches/py3k/Lib/test/test_htmlparser.py (original) +++ python/branches/py3k/Lib/test/test_htmlparser.py Mon May 24 23:46:25 2010 @@ -136,6 +136,13 @@ ("data", "\n"), ]) + def test_malformatted_charref(self): + self._run_check("

    &#bad;

    ", [ + ("starttag", "p", []), + ("data", "&#bad;"), + ("endtag", "p"), + ]) + def test_unclosed_entityref(self): self._run_check("&entityref foo", [ ("entityref", "entityref"), Modified: python/branches/py3k/Misc/ACKS ============================================================================== --- python/branches/py3k/Misc/ACKS (original) +++ python/branches/py3k/Misc/ACKS Mon May 24 23:46:25 2010 @@ -871,3 +871,4 @@ Uwe Zessin Tarek Ziad? Peter ?strand +Fredrik H??rd Modified: python/branches/py3k/Misc/NEWS ============================================================================== --- python/branches/py3k/Misc/NEWS (original) +++ python/branches/py3k/Misc/NEWS Mon May 24 23:46:25 2010 @@ -392,6 +392,9 @@ Library ------- +- Issue #6662: Fix parsing of malformatted charref (&#bad;), patch written by + Fredrik H??rd + - Issue #8540: Decimal module: rename the Context._clamp attribute to Context.clamp and make it public. This is useful in creating contexts that correspond to the decimal interchange formats From python-checkins at python.org Mon May 24 23:48:07 2010 From: python-checkins at python.org (victor.stinner) Date: Mon, 24 May 2010 23:48:07 +0200 (CEST) Subject: [Python-checkins] r81505 - in python/branches/release31-maint: Lib/html/parser.py Lib/test/test_htmlparser.py Misc/ACKS Misc/NEWS Message-ID: <20100524214807.9F20BEB74@mail.python.org> Author: victor.stinner Date: Mon May 24 23:48:07 2010 New Revision: 81505 Log: Merged revisions 81504 via svnmerge from svn+ssh://pythondev at svn.python.org/python/branches/py3k ................ r81504 | victor.stinner | 2010-05-24 23:46:25 +0200 (lun., 24 mai 2010) | 13 lines Recorded merge of revisions 81500-81501 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r81500 | victor.stinner | 2010-05-24 23:33:24 +0200 (lun., 24 mai 2010) | 2 lines Issue #6662: Fix parsing of malformatted charref (&#bad;) ........ r81501 | victor.stinner | 2010-05-24 23:37:28 +0200 (lun., 24 mai 2010) | 2 lines Add the author of the last fix (Issue #6662) ........ ................ Modified: python/branches/release31-maint/ (props changed) python/branches/release31-maint/Lib/html/parser.py python/branches/release31-maint/Lib/test/test_htmlparser.py python/branches/release31-maint/Misc/ACKS python/branches/release31-maint/Misc/NEWS Modified: python/branches/release31-maint/Lib/html/parser.py ============================================================================== --- python/branches/release31-maint/Lib/html/parser.py (original) +++ python/branches/release31-maint/Lib/html/parser.py Mon May 24 23:48:07 2010 @@ -175,6 +175,9 @@ i = self.updatepos(i, k) continue else: + if ";" in rawdata[i:]: #bail by consuming &# + self.handle_data(rawdata[0:2]) + i = self.updatepos(i, 2) break elif startswith('&', i): match = entityref.match(rawdata, i) Modified: python/branches/release31-maint/Lib/test/test_htmlparser.py ============================================================================== --- python/branches/release31-maint/Lib/test/test_htmlparser.py (original) +++ python/branches/release31-maint/Lib/test/test_htmlparser.py Mon May 24 23:48:07 2010 @@ -136,6 +136,13 @@ ("data", "\n"), ]) + def test_malformatted_charref(self): + self._run_check("

    &#bad;

    ", [ + ("starttag", "p", []), + ("data", "&#bad;"), + ("endtag", "p"), + ]) + def test_unclosed_entityref(self): self._run_check("&entityref foo", [ ("entityref", "entityref"), Modified: python/branches/release31-maint/Misc/ACKS ============================================================================== --- python/branches/release31-maint/Misc/ACKS (original) +++ python/branches/release31-maint/Misc/ACKS Mon May 24 23:48:07 2010 @@ -846,3 +846,4 @@ Uwe Zessin Tarek Ziad? Peter ?strand +Fredrik H??rd Modified: python/branches/release31-maint/Misc/NEWS ============================================================================== --- python/branches/release31-maint/Misc/NEWS (original) +++ python/branches/release31-maint/Misc/NEWS Mon May 24 23:48:07 2010 @@ -54,6 +54,9 @@ Library ------- +- Issue #6662: Fix parsing of malformatted charref (&#bad;), patch written by + Fredrik H??rd + - Issue #6268: Fix seek() method of codecs.open(), don't read or write the BOM twice after seek(0). Fix also reset() method of codecs, UTF-16, UTF-32 and StreamWriter classes. From python-checkins at python.org Tue May 25 00:04:53 2010 From: python-checkins at python.org (benjamin.peterson) Date: Tue, 25 May 2010 00:04:53 +0200 (CEST) Subject: [Python-checkins] r81506 - python/trunk/Lib/encodings/cp858.py Message-ID: <20100524220453.EC91BEB64@mail.python.org> Author: benjamin.peterson Date: Tue May 25 00:04:53 2010 New Revision: 81506 Log: set svn:eol-style Modified: python/trunk/Lib/encodings/cp858.py (props changed) From solipsis at pitrou.net Tue May 25 01:24:52 2010 From: solipsis at pitrou.net (solipsis at pitrou.net) Date: Tue, 25 May 2010 01:24:52 +0200 (CEST) Subject: [Python-checkins] Daily py3k reference leaks (r81495): sum=0 Message-ID: <20100524232452.0D87A1770A@ns6635.ovh.net> py3k results for svn r81495 (hg cset 3d40c3b24885) -------------------------------------------------- Command line was: ['./python', '-m', 'test.regrtest', '-uall', '-R', '3:3:/home/antoine/py3k/refleaks/reflogDgkj_Z', '-x'] From python-checkins at python.org Tue May 25 03:17:50 2010 From: python-checkins at python.org (collin.winter) Date: Tue, 25 May 2010 03:17:50 +0200 (CEST) Subject: [Python-checkins] r81508 - in python/branches/py3k-jit: Doc/c-api/init.rst Doc/c-api/sys.rst Doc/howto/descriptor.rst Doc/howto/index.rst Doc/library/argparse.rst Doc/library/decimal.rst Doc/library/fcntl.rst Doc/library/ftplib.rst Doc/library/getopt.rst Doc/library/hashlib.rst Doc/library/io.rst Doc/library/json.rst Doc/library/multiprocessing.rst Doc/library/optparse.rst Doc/library/os.rst Doc/library/socket.rst Doc/library/ssl.rst Doc/library/stdtypes.rst Doc/library/symtable.rst Doc/library/sys.rst Doc/library/syslog.rst Doc/library/telnetlib.rst Doc/library/tempfile.rst Doc/library/test.rst Doc/library/unittest.rst Doc/library/urllib.request.rst Doc/library/winreg.rst Doc/reference/datamodel.rst Doc/tutorial/datastructures.rst Include/pyport.h Include/sysmodule.h Lib/_abcoll.py Lib/argparse.py Lib/asyncore.py Lib/codecs.py Lib/decimal.py Lib/distutils/log.py Lib/distutils/tests/test_log.py Lib/encodings/utf_16.py Lib/encodings/utf_32.py Lib/fractions.py Lib/functools.py Lib/importlib/_bootstrap.py Lib/importlib/test/source/test_file_loader.py Lib/lib2to3/refactor.py Lib/linecache.py Lib/os.py Lib/pipes.py Lib/ssl.py Lib/subprocess.py Lib/sysconfig.py Lib/tabnanny.py Lib/test/regrtest.py Lib/test/test_argparse.py Lib/test/test_asyncore.py Lib/test/test_codecs.py Lib/test/test_collections.py Lib/test/test_complex.py Lib/test/test_decimal.py Lib/test/test_float.py Lib/test/test_gdb.py Lib/test/test_getargs2.py Lib/test/test_import.py Lib/test/test_linecache.py Lib/test/test_numeric_tower.py Lib/test/test_os.py Lib/test/test_pipes.py Lib/test/test_ssl.py Lib/test/test_subprocess.py Lib/test/test_sys.py Lib/test/test_sysconfig.py Lib/test/test_warnings.py Misc/NEWS Modules/_io/textio.c Modules/_sqlite/connection.c Modules/_sqlite/cursor.c Modules/_sqlite/row.c Modules/_sqlite/statement.c Modules/_ssl.c Modules/main.c Objects/complexobject.c Objects/longobject.c Objects/moduleobject.c Objects/object.c Objects/typeobject.c Parser/asdl.py Python/_warnings.c Python/bltinmodule.c Python/getargs.c Python/pythonrun.c Python/sysmodule.c Tools/gdb/libpython.py Message-ID: <20100525011750.BD1BAEE984@mail.python.org> Author: collin.winter Date: Tue May 25 03:17:49 2010 New Revision: 81508 Log: Merged revisions 81281,81283,81288,81290-81292,81299,81314,81319-81325,81352,81356,81358-81361,81364-81368,81370,81372,81375,81378,81387,81392-81393,81397,81400,81403,81406,81410,81417-81418,81421,81424,81427,81435,81438,81442,81446,81452,81455,81457,81461,81470,81474,81476,81481,81485-81486,81491,81493,81495 via svnmerge from svn+ssh://pythondev at svn.python.org/python/branches/py3k ................ r81281 | senthil.kumaran | 2010-05-17 20:26:11 -0700 (Mon, 17 May 2010) | 9 lines Merged revisions 81279 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r81279 | senthil.kumaran | 2010-05-18 08:50:43 +0530 (Tue, 18 May 2010) | 3 lines Fix minor typo. ........ ................ r81283 | senthil.kumaran | 2010-05-17 20:58:36 -0700 (Mon, 17 May 2010) | 3 lines Removing the reference in the docs for overriding _urlopener global value. See Issue8619 for details. ................ r81288 | senthil.kumaran | 2010-05-18 06:48:45 -0700 (Tue, 18 May 2010) | 9 lines Merged revisions 81286 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r81286 | senthil.kumaran | 2010-05-18 19:10:23 +0530 (Tue, 18 May 2010) | 3 lines Doc Fix. Correct link to Zephyr ASDL Abstract page. ........ ................ r81290 | barry.warsaw | 2010-05-18 07:15:20 -0700 (Tue, 18 May 2010) | 2 lines Repair test failure. Bug 8727. ................ r81291 | victor.stinner | 2010-05-18 10:17:23 -0700 (Tue, 18 May 2010) | 5 lines Issue #8513: os.get_exec_path() supports b'PATH' key and bytes value. subprocess.Popen() and os._execvpe() support bytes program name. Add os.supports_bytes_environ flag: True if the native OS type of the environment is bytes (eg. False on Windows). ................ r81292 | victor.stinner | 2010-05-18 10:24:09 -0700 (Tue, 18 May 2010) | 2 lines Add versionadded (3.2) tag to os.supports_bytes_environ documentation ................ r81299 | giampaolo.rodola | 2010-05-18 13:11:58 -0700 (Tue, 18 May 2010) | 9 lines Merged revisions 81294 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r81294 | giampaolo.rodola | 2010-05-18 22:04:31 +0200 (mar, 18 mag 2010) | 1 line Fix issue #8573 (asyncore._strerror bug): fixed os.strerror typo; included NameError in the tuple of expected exception; added test case for asyncore._strerror. ........ ................ r81314 | victor.stinner | 2010-05-18 17:03:09 -0700 (Tue, 18 May 2010) | 2 lines Issue #6697: Fix a crash if a module attribute name contains a surrogate ................ r81319 | victor.stinner | 2010-05-18 17:34:15 -0700 (Tue, 18 May 2010) | 2 lines Issue #6697: Check that _PyUnicode_AsString() result is not NULL ................ r81320 | victor.stinner | 2010-05-18 17:54:06 -0700 (Tue, 18 May 2010) | 2 lines Issue #6697: Fix a crash if a keyword contains a surrogate ................ r81321 | victor.stinner | 2010-05-18 18:06:22 -0700 (Tue, 18 May 2010) | 4 lines Issue #6697: Fix a crash if sys.stdin or sys.stdout encoding contain a surrogate This is *very* unlikely :-) ................ r81322 | victor.stinner | 2010-05-18 18:17:01 -0700 (Tue, 18 May 2010) | 5 lines Issue #6697: Check that _PyUnicode_AsString() result is not NULL in textio.c The bug may occurs if locale.getpreferredencoding() returns an encoding with a surrogate (very unlikely!). ................ r81323 | victor.stinner | 2010-05-18 18:27:23 -0700 (Tue, 18 May 2010) | 4 lines Issue #6697: Check that _PyUnicode_AsString() result is not NULL in _sqlite Strip also some trailing spaces ................ r81324 | victor.stinner | 2010-05-18 18:42:46 -0700 (Tue, 18 May 2010) | 5 lines Issue #6697: Check that _PyUnicode_AsString() result is not NULL in typeobject Type name and slots are already checked for surrogates somewhere else, but it's better to ensure that the result is not NULL. ................ r81325 | victor.stinner | 2010-05-18 18:50:45 -0700 (Tue, 18 May 2010) | 4 lines Ooops, add missing ";" in my previous commit (r81324, typeobject.c) It's time to go to bed... ................ r81352 | stefan.krah | 2010-05-19 08:52:31 -0700 (Wed, 19 May 2010) | 9 lines Merged revisions 81350 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r81350 | stefan.krah | 2010-05-19 17:46:39 +0200 (Wed, 19 May 2010) | 1 line Fix typos in docstrings. ........ ................ r81356 | stefan.krah | 2010-05-19 09:09:41 -0700 (Wed, 19 May 2010) | 9 lines Merged revisions 81354 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r81354 | stefan.krah | 2010-05-19 17:59:40 +0200 (Wed, 19 May 2010) | 3 lines Fix typo. ........ ................ r81358 | victor.stinner | 2010-05-19 09:53:30 -0700 (Wed, 19 May 2010) | 4 lines Issue #8589: Decode PYTHONWARNINGS environment variable with the file system encoding and surrogateespace error handler instead of the locale encoding to be consistent with os.environ. Add PySys_AddWarnOptionUnicode() function. ................ r81359 | victor.stinner | 2010-05-19 10:00:07 -0700 (Wed, 19 May 2010) | 4 lines Issue #8663: distutils.log emulates backslashreplace error handler. Fix compilation in a non-ASCII directory if stdout encoding is ASCII (eg. if stdout is not a TTY). ................ r81360 | victor.stinner | 2010-05-19 10:11:19 -0700 (Wed, 19 May 2010) | 5 lines regrtest.py: call replace_stdout() before the first call to print() print("== ", os.getcwd()) fails if the current working directory is not ASCII whereas sys.stdout encoding is ASCII. ................ r81361 | victor.stinner | 2010-05-19 10:15:50 -0700 (Wed, 19 May 2010) | 2 lines Oops, add the new test_log.py for distutils test suite (missing part of r81359) ................ r81364 | victor.stinner | 2010-05-19 13:40:50 -0700 (Wed, 19 May 2010) | 3 lines Issue #8766: Initialize _warnings module before importing the first module. Fix a crash if an empty directory called "encodings" exists in sys.path. ................ r81365 | georg.brandl | 2010-05-19 13:57:08 -0700 (Wed, 19 May 2010) | 77 lines Merged revisions 80030,80067,80069,80080-80081,80084,80432-80433,80465-80470,81059,81065-81067 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r80030 | georg.brandl | 2010-04-13 08:43:54 +0200 (Di, 13 Apr 2010) | 1 line Get rid of multi-row cells. ........ r80067 | georg.brandl | 2010-04-14 10:53:38 +0200 (Mi, 14 Apr 2010) | 1 line #5341: typo. ........ r80069 | georg.brandl | 2010-04-14 15:50:31 +0200 (Mi, 14 Apr 2010) | 1 line Add an x-ref to where the O_ constants are documented and move the SEEK_ constants after lseek(). ........ r80080 | georg.brandl | 2010-04-14 21:16:38 +0200 (Mi, 14 Apr 2010) | 1 line #8399: add note about Windows and O_BINARY. ........ r80081 | georg.brandl | 2010-04-14 23:34:44 +0200 (Mi, 14 Apr 2010) | 1 line #5250: document __instancecheck__ and __subclasscheck__. I hope the part about the class/metaclass distinction is understandable. ........ r80084 | georg.brandl | 2010-04-14 23:46:45 +0200 (Mi, 14 Apr 2010) | 1 line Fix missing. ........ r80432 | georg.brandl | 2010-04-24 10:56:58 +0200 (Sa, 24 Apr 2010) | 1 line Markup fixes. ........ r80433 | georg.brandl | 2010-04-24 11:08:10 +0200 (Sa, 24 Apr 2010) | 1 line #7507: quote "!" in pipes.quote(); it is a special character for some shells. ........ r80465 | georg.brandl | 2010-04-25 12:29:17 +0200 (So, 25 Apr 2010) | 1 line Remove LaTeXy index entry syntax. ........ r80466 | georg.brandl | 2010-04-25 12:54:42 +0200 (So, 25 Apr 2010) | 1 line Patch from Tim Hatch: Better cross-referencing in socket and winreg docs. ........ r80467 | georg.brandl | 2010-04-25 12:55:16 +0200 (So, 25 Apr 2010) | 1 line Patch from Tim Hatch: Remove reference to winreg being the fabled high-level registry interface. ........ r80468 | georg.brandl | 2010-04-25 12:55:58 +0200 (So, 25 Apr 2010) | 1 line Patch from Tim Hatch: Minor spelling changes to _winreg docs. ........ r80469 | georg.brandl | 2010-04-25 12:56:41 +0200 (So, 25 Apr 2010) | 1 line Fix code example to have valid syntax so that it can be highlighted. ........ r80470 | georg.brandl | 2010-04-25 12:57:15 +0200 (So, 25 Apr 2010) | 1 line Patch from Tim Hatch: Make socket setblocking <-> settimeout examples symmetric. ........ r81059 | georg.brandl | 2010-05-10 23:02:51 +0200 (Mo, 10 Mai 2010) | 1 line #8642: fix wrong function name. ........ r81065 | georg.brandl | 2010-05-10 23:46:50 +0200 (Mo, 10 Mai 2010) | 1 line Fix reference direction. ........ r81066 | georg.brandl | 2010-05-10 23:50:57 +0200 (Mo, 10 Mai 2010) | 1 line Consolidate deprecation messages. ........ r81067 | georg.brandl | 2010-05-10 23:51:33 +0200 (Mo, 10 Mai 2010) | 1 line Fix typo. ........ ................ r81366 | georg.brandl | 2010-05-19 13:58:02 -0700 (Wed, 19 May 2010) | 61 lines Recorded merge of revisions 80030,80067,80069,80080-80081,80084,80432-80433,80465,80470,81059,81065-81067 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r80030 | georg.brandl | 2010-04-13 08:43:54 +0200 (Di, 13 Apr 2010) | 1 line Get rid of multi-row cells. ........ r80067 | georg.brandl | 2010-04-14 10:53:38 +0200 (Mi, 14 Apr 2010) | 1 line #5341: typo. ........ r80069 | georg.brandl | 2010-04-14 15:50:31 +0200 (Mi, 14 Apr 2010) | 1 line Add an x-ref to where the O_ constants are documented and move the SEEK_ constants after lseek(). ........ r80080 | georg.brandl | 2010-04-14 21:16:38 +0200 (Mi, 14 Apr 2010) | 1 line #8399: add note about Windows and O_BINARY. ........ r80081 | georg.brandl | 2010-04-14 23:34:44 +0200 (Mi, 14 Apr 2010) | 1 line #5250: document __instancecheck__ and __subclasscheck__. I hope the part about the class/metaclass distinction is understandable. ........ r80084 | georg.brandl | 2010-04-14 23:46:45 +0200 (Mi, 14 Apr 2010) | 1 line Fix missing. ........ r80432 | georg.brandl | 2010-04-24 10:56:58 +0200 (Sa, 24 Apr 2010) | 1 line Markup fixes. ........ r80433 | georg.brandl | 2010-04-24 11:08:10 +0200 (Sa, 24 Apr 2010) | 1 line #7507: quote "!" in pipes.quote(); it is a special character for some shells. ........ r80465 | georg.brandl | 2010-04-25 12:29:17 +0200 (So, 25 Apr 2010) | 1 line Remove LaTeXy index entry syntax. ........ r80470 | georg.brandl | 2010-04-25 12:57:15 +0200 (So, 25 Apr 2010) | 1 line Patch from Tim Hatch: Make socket setblocking <-> settimeout examples symmetric. ........ r81059 | georg.brandl | 2010-05-10 23:02:51 +0200 (Mo, 10 Mai 2010) | 1 line #8642: fix wrong function name. ........ r81065 | georg.brandl | 2010-05-10 23:46:50 +0200 (Mo, 10 Mai 2010) | 1 line Fix reference direction. ........ r81066 | georg.brandl | 2010-05-10 23:50:57 +0200 (Mo, 10 Mai 2010) | 1 line Consolidate deprecation messages. ........ r81067 | georg.brandl | 2010-05-10 23:51:33 +0200 (Mo, 10 Mai 2010) | 1 line Fix typo. ........ ................ r81367 | georg.brandl | 2010-05-19 14:03:51 -0700 (Wed, 19 May 2010) | 21 lines Recorded merge of revisions 80466-80469 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r80466 | georg.brandl | 2010-04-25 12:54:42 +0200 (So, 25 Apr 2010) | 1 line Patch from Tim Hatch: Better cross-referencing in socket and winreg docs. ........ r80467 | georg.brandl | 2010-04-25 12:55:16 +0200 (So, 25 Apr 2010) | 1 line Patch from Tim Hatch: Remove reference to winreg being the fabled high-level registry interface. ........ r80468 | georg.brandl | 2010-04-25 12:55:58 +0200 (So, 25 Apr 2010) | 1 line Patch from Tim Hatch: Minor spelling changes to _winreg docs. ........ r80469 | georg.brandl | 2010-04-25 12:56:41 +0200 (So, 25 Apr 2010) | 1 line Fix code example to have valid syntax so that it can be highlighted. ........ ................ r81368 | georg.brandl | 2010-05-19 14:06:36 -0700 (Wed, 19 May 2010) | 9 lines Merged revisions 80068 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r80068 | georg.brandl | 2010-04-14 10:56:01 +0200 (Mi, 14 Apr 2010) | 1 line #5341: fix typo and adapt docstring syntax. ........ ................ r81370 | georg.brandl | 2010-05-19 14:39:51 -0700 (Wed, 19 May 2010) | 1 line Add descriptor HOWTO to py3k docs. ................ r81372 | tarek.ziade | 2010-05-19 15:25:00 -0700 (Wed, 19 May 2010) | 9 lines Merged revisions 81371 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r81371 | tarek.ziade | 2010-05-20 00:20:14 +0200 (Thu, 20 May 2010) | 1 line #8759: Fixed user paths in sysconfig for posix and os2 schemes ........ ................ r81375 | victor.stinner | 2010-05-19 16:04:56 -0700 (Wed, 19 May 2010) | 9 lines Issue #8559: improve unicode support of (gdb) libpython.py * Escape non printable characters (use locale.getpreferredencoding()) * Fix support of surrogate pairs * test_gdb.py: use ascii() instead of repr() in gdb program arguments to avoid encoding issues * Fix test_strings() of test_gdb.py for encoding different than UTF-8 (eg. ACSII) ................ r81378 | victor.stinner | 2010-05-20 04:30:37 -0700 (Thu, 20 May 2010) | 14 lines Blocked revisions 81377 via svnmerge ........ r81377 | victor.stinner | 2010-05-20 13:29:45 +0200 (jeu., 20 mai 2010) | 8 lines libpython.py: fix support of non-BMP unicode characters Forward port some code from Python3: * join surrogate pairs if sizeof(Py_UNICODE)==2 * Enable non-BMP test on narrow builds using u"\U0001D121" instead of unichr(0x1D121) ........ ................ r81387 | benjamin.peterson | 2010-05-20 15:29:43 -0700 (Thu, 20 May 2010) | 9 lines Merged revisions 81385 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r81385 | benjamin.peterson | 2010-05-20 17:23:37 -0500 (Thu, 20 May 2010) | 1 line fix extra 't' #8778 ........ ................ r81392 | antoine.pitrou | 2010-05-21 02:56:06 -0700 (Fri, 21 May 2010) | 5 lines Issue #4870: Add an `options` attribute to SSL contexts, as well as several ``OP_*`` constants to the `ssl` module. This allows to selectively disable protocol versions, when used in combination with `PROTOCOL_SSLv23`. ................ r81393 | victor.stinner | 2010-05-21 03:52:08 -0700 (Fri, 21 May 2010) | 3 lines Issue #8774: tabnanny uses the encoding cookie (#coding:...) to use the correct encoding ................ r81397 | mark.dickinson | 2010-05-21 07:55:26 -0700 (Fri, 21 May 2010) | 10 lines Issue #8748: Fix two issues with comparisons between complex and integer objects. (1) The comparison could incorrectly return True in some cases (2**53+1 == complex(2**53) == 2**53), breaking transivity of equality. (2) The comparison raised an OverflowError for large integers, leading to unpredictable exceptions when combining integers and complex objects in sets or dicts. Patch by Meador Inge. ................ r81400 | antoine.pitrou | 2010-05-21 10:25:34 -0700 (Fri, 21 May 2010) | 12 lines Merged revisions 81398 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r81398 | antoine.pitrou | 2010-05-21 19:12:38 +0200 (ven., 21 mai 2010) | 6 lines Issue #5753: A new C API function, :cfunc:`PySys_SetArgvEx`, allows embedders of the interpreter to set sys.argv without also modifying sys.path. This helps fix `CVE-2008-5983 `_. ........ ................ r81403 | victor.stinner | 2010-05-21 13:13:12 -0700 (Fri, 21 May 2010) | 5 lines Issue #8780: Fix a regression introduced by r78946 in subprocess on Windows Ensure that stdout / stderr is inherited from the parent if stdout=PIPE / stderr=PIPE is not used. ................ r81406 | georg.brandl | 2010-05-21 13:28:13 -0700 (Fri, 21 May 2010) | 9 lines Merged revisions 81404 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r81404 | georg.brandl | 2010-05-21 22:24:45 +0200 (Fr, 21 Mai 2010) | 1 line #8783: replace link to now dead hash collision FAQ. ........ ................ r81410 | georg.brandl | 2010-05-21 13:45:12 -0700 (Fri, 21 May 2010) | 1 line Remove redundant example. ................ r81417 | benjamin.peterson | 2010-05-21 13:55:22 -0700 (Fri, 21 May 2010) | 9 lines Merged revisions 81414 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r81414 | benjamin.peterson | 2010-05-21 15:51:45 -0500 (Fri, 21 May 2010) | 1 line return NotImplemented from Mapping when comparing to a non-mapping #8729 ........ ................ r81418 | georg.brandl | 2010-05-21 13:57:33 -0700 (Fri, 21 May 2010) | 9 lines Recorded merge of revisions 81415 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r81415 | georg.brandl | 2010-05-21 22:52:46 +0200 (Fr, 21 Mai 2010) | 1 line typo ........ ................ r81421 | georg.brandl | 2010-05-21 14:01:32 -0700 (Fri, 21 May 2010) | 1 line Fix variable name in example. ................ r81424 | georg.brandl | 2010-05-21 14:03:02 -0700 (Fri, 21 May 2010) | 8 lines Blocked revisions 81419 via svnmerge ........ r81419 | georg.brandl | 2010-05-21 22:58:12 +0200 (Fr, 21 Mai 2010) | 1 line Add missing parameter in SimpleXMLRPCServer signature. ........ ................ r81427 | georg.brandl | 2010-05-21 14:12:07 -0700 (Fri, 21 May 2010) | 1 line Fix signatures for the various TemporaryFile class^Wfunctions. ................ r81435 | georg.brandl | 2010-05-21 14:33:23 -0700 (Fri, 21 May 2010) | 9 lines Merged revisions 81431 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r81431 | georg.brandl | 2010-05-21 23:30:47 +0200 (Fr, 21 Mai 2010) | 1 line #8707: remove duplicate paragraph part. ........ ................ r81438 | benjamin.peterson | 2010-05-21 14:45:06 -0700 (Fri, 21 May 2010) | 25 lines Merged revisions 81428-81429,81432-81433,81437 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r81428 | benjamin.peterson | 2010-05-21 16:16:12 -0500 (Fri, 21 May 2010) | 1 line use addCleanup ........ r81429 | benjamin.peterson | 2010-05-21 16:17:22 -0500 (Fri, 21 May 2010) | 1 line fix name ........ r81432 | benjamin.peterson | 2010-05-21 16:31:24 -0500 (Fri, 21 May 2010) | 1 line ensure the last line has a trailing newline #8782 ........ r81433 | benjamin.peterson | 2010-05-21 16:32:49 -0500 (Fri, 21 May 2010) | 1 line remove debugging rubish ........ r81437 | benjamin.peterson | 2010-05-21 16:35:44 -0500 (Fri, 21 May 2010) | 1 line simplify and modernize updatecache() ........ ................ r81442 | georg.brandl | 2010-05-21 14:48:27 -0700 (Fri, 21 May 2010) | 9 lines Merged revisions 81440 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r81440 | georg.brandl | 2010-05-21 23:47:05 +0200 (Fr, 21 Mai 2010) | 1 line Correct info for Semaphore.acquire() semantics under OSX. ........ ................ r81446 | georg.brandl | 2010-05-21 14:49:47 -0700 (Fri, 21 May 2010) | 9 lines Merged revisions 81443 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r81443 | georg.brandl | 2010-05-21 23:48:57 +0200 (Fr, 21 Mai 2010) | 1 line typo ........ ................ r81452 | georg.brandl | 2010-05-21 15:04:32 -0700 (Fri, 21 May 2010) | 9 lines Merged revisions 81450 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r81450 | georg.brandl | 2010-05-22 00:03:29 +0200 (Sa, 22 Mai 2010) | 1 line #8709: mention Windows support for os.devnull. ........ ................ r81455 | victor.stinner | 2010-05-21 15:52:10 -0700 (Fri, 21 May 2010) | 9 lines Blocked revisions 81454 via svnmerge ........ r81454 | victor.stinner | 2010-05-22 00:50:28 +0200 (sam., 22 mai 2010) | 3 lines Issue #5640: Fix Shift-JIS incremental encoder for error handlers different than strict ........ ................ r81457 | victor.stinner | 2010-05-21 16:45:42 -0700 (Fri, 21 May 2010) | 3 lines Issue #3798: sys.exit(message) writes the message to sys.stderr file, instead of the C file stderr, to use stderr encoding and error handler ................ r81461 | victor.stinner | 2010-05-21 19:16:27 -0700 (Fri, 21 May 2010) | 10 lines Merged revisions 81459 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r81459 | victor.stinner | 2010-05-22 04:11:07 +0200 (sam., 22 mai 2010) | 3 lines Issue #6268: Fix seek() method of codecs.open(), don't read the BOM twice after seek(0) ........ ................ r81470 | mark.dickinson | 2010-05-22 05:02:35 -0700 (Sat, 22 May 2010) | 1 line Issue #8749: remove unused code in Objects/object.c. Thanks Yaniv Aknin. ................ r81474 | victor.stinner | 2010-05-22 09:59:09 -0700 (Sat, 22 May 2010) | 20 lines Merged revisions 81471-81472 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r81471 | victor.stinner | 2010-05-22 15:37:56 +0200 (sam., 22 mai 2010) | 7 lines Issue #6268: More bugfixes about BOM, UTF-16 and UTF-32 * Fix seek() method of codecs.open(), don't write the BOM twice after seek(0) * Fix reset() method of codecs, UTF-16, UTF-32 and StreamWriter classes * test_codecs: use "w+" mode instead of "wt+". "t" mode is not supported by Solaris or Windows, but does it really exist? I found it the in the issue. ........ r81472 | victor.stinner | 2010-05-22 15:44:25 +0200 (sam., 22 mai 2010) | 4 lines Fix my last commit (r81471) about codecs Rememder: don't touch the code just before a commit ........ ................ r81476 | mark.dickinson | 2010-05-22 11:35:36 -0700 (Sat, 22 May 2010) | 2 lines #Issue 8540: Make Context._clamp attribute public in decimal module. ................ r81481 | benjamin.peterson | 2010-05-22 11:59:24 -0700 (Sat, 22 May 2010) | 20 lines Merged revisions 81479 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ................ r81479 | benjamin.peterson | 2010-05-22 13:52:21 -0500 (Sat, 22 May 2010) | 13 lines Merged revisions 80937,81478 via svnmerge from svn+ssh://pythondev at svn.python.org/sandbox/trunk/2to3/lib2to3 ........ r80937 | benjamin.peterson | 2010-05-07 14:10:58 -0500 (Fri, 07 May 2010) | 1 line remove redundant unicode call ........ r81478 | benjamin.peterson | 2010-05-22 13:47:39 -0500 (Sat, 22 May 2010) | 1 line ensure doctests have some future_features ........ ................ ................ r81485 | mark.dickinson | 2010-05-23 06:26:48 -0700 (Sun, 23 May 2010) | 1 line Remove duplicate NEWS entry. ................ r81486 | mark.dickinson | 2010-05-23 06:33:13 -0700 (Sun, 23 May 2010) | 6 lines Issue #8188: Introduce a new scheme for computing hashes of numbers (instances of int, float, complex, decimal.Decimal and fractions.Fraction) that makes it easy to maintain the invariant that hash(x) == hash(y) whenever x and y have equal value. ................ r81491 | steven.bethard | 2010-05-23 20:21:08 -0700 (Sun, 23 May 2010) | 9 lines Merged revisions 81490 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r81490 | steven.bethard | 2010-05-23 19:38:00 -0700 (Sun, 23 May 2010) | 1 line argparse documentation updates (including updates to optparse and getopt documentation that were promised in the PEP) ........ ................ r81493 | steven.bethard | 2010-05-23 20:47:38 -0700 (Sun, 23 May 2010) | 9 lines Merged revisions 81492 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r81492 | steven.bethard | 2010-05-23 20:45:26 -0700 (Sun, 23 May 2010) | 1 line Fix default value for version help. Approved by Benjamin on python-dev: http://mail.python.org/pipermail/python-dev/2010-May/100231.html ........ ................ r81495 | antoine.pitrou | 2010-05-24 08:58:43 -0700 (Mon, 24 May 2010) | 3 lines Add a versionadded tag for SSL contexts. ................ Added: python/branches/py3k-jit/Doc/howto/descriptor.rst - copied unchanged from r81495, /python/branches/py3k/Doc/howto/descriptor.rst python/branches/py3k-jit/Lib/distutils/tests/test_log.py - copied unchanged from r81495, /python/branches/py3k/Lib/distutils/tests/test_log.py python/branches/py3k-jit/Lib/test/test_numeric_tower.py - copied unchanged from r81495, /python/branches/py3k/Lib/test/test_numeric_tower.py Modified: python/branches/py3k-jit/ (props changed) python/branches/py3k-jit/Doc/c-api/init.rst python/branches/py3k-jit/Doc/c-api/sys.rst python/branches/py3k-jit/Doc/howto/index.rst python/branches/py3k-jit/Doc/library/argparse.rst python/branches/py3k-jit/Doc/library/decimal.rst python/branches/py3k-jit/Doc/library/fcntl.rst python/branches/py3k-jit/Doc/library/ftplib.rst python/branches/py3k-jit/Doc/library/getopt.rst python/branches/py3k-jit/Doc/library/hashlib.rst python/branches/py3k-jit/Doc/library/io.rst python/branches/py3k-jit/Doc/library/json.rst python/branches/py3k-jit/Doc/library/multiprocessing.rst python/branches/py3k-jit/Doc/library/optparse.rst python/branches/py3k-jit/Doc/library/os.rst python/branches/py3k-jit/Doc/library/socket.rst python/branches/py3k-jit/Doc/library/ssl.rst python/branches/py3k-jit/Doc/library/stdtypes.rst python/branches/py3k-jit/Doc/library/symtable.rst python/branches/py3k-jit/Doc/library/sys.rst python/branches/py3k-jit/Doc/library/syslog.rst python/branches/py3k-jit/Doc/library/telnetlib.rst python/branches/py3k-jit/Doc/library/tempfile.rst python/branches/py3k-jit/Doc/library/test.rst python/branches/py3k-jit/Doc/library/unittest.rst python/branches/py3k-jit/Doc/library/urllib.request.rst python/branches/py3k-jit/Doc/library/winreg.rst python/branches/py3k-jit/Doc/reference/datamodel.rst python/branches/py3k-jit/Doc/tutorial/datastructures.rst python/branches/py3k-jit/Include/pyport.h python/branches/py3k-jit/Include/sysmodule.h python/branches/py3k-jit/Lib/_abcoll.py python/branches/py3k-jit/Lib/argparse.py python/branches/py3k-jit/Lib/asyncore.py python/branches/py3k-jit/Lib/codecs.py python/branches/py3k-jit/Lib/decimal.py python/branches/py3k-jit/Lib/distutils/log.py python/branches/py3k-jit/Lib/encodings/utf_16.py python/branches/py3k-jit/Lib/encodings/utf_32.py python/branches/py3k-jit/Lib/fractions.py python/branches/py3k-jit/Lib/functools.py python/branches/py3k-jit/Lib/importlib/_bootstrap.py python/branches/py3k-jit/Lib/importlib/test/source/test_file_loader.py python/branches/py3k-jit/Lib/lib2to3/refactor.py python/branches/py3k-jit/Lib/linecache.py python/branches/py3k-jit/Lib/os.py python/branches/py3k-jit/Lib/pipes.py python/branches/py3k-jit/Lib/ssl.py python/branches/py3k-jit/Lib/subprocess.py python/branches/py3k-jit/Lib/sysconfig.py python/branches/py3k-jit/Lib/tabnanny.py python/branches/py3k-jit/Lib/test/regrtest.py python/branches/py3k-jit/Lib/test/test_argparse.py python/branches/py3k-jit/Lib/test/test_asyncore.py python/branches/py3k-jit/Lib/test/test_codecs.py python/branches/py3k-jit/Lib/test/test_collections.py python/branches/py3k-jit/Lib/test/test_complex.py python/branches/py3k-jit/Lib/test/test_decimal.py python/branches/py3k-jit/Lib/test/test_float.py python/branches/py3k-jit/Lib/test/test_gdb.py python/branches/py3k-jit/Lib/test/test_getargs2.py python/branches/py3k-jit/Lib/test/test_import.py python/branches/py3k-jit/Lib/test/test_linecache.py python/branches/py3k-jit/Lib/test/test_os.py python/branches/py3k-jit/Lib/test/test_pipes.py python/branches/py3k-jit/Lib/test/test_ssl.py python/branches/py3k-jit/Lib/test/test_subprocess.py python/branches/py3k-jit/Lib/test/test_sys.py python/branches/py3k-jit/Lib/test/test_sysconfig.py python/branches/py3k-jit/Lib/test/test_warnings.py python/branches/py3k-jit/Misc/NEWS python/branches/py3k-jit/Modules/_io/textio.c python/branches/py3k-jit/Modules/_sqlite/connection.c python/branches/py3k-jit/Modules/_sqlite/cursor.c python/branches/py3k-jit/Modules/_sqlite/row.c python/branches/py3k-jit/Modules/_sqlite/statement.c python/branches/py3k-jit/Modules/_ssl.c python/branches/py3k-jit/Modules/main.c python/branches/py3k-jit/Objects/complexobject.c python/branches/py3k-jit/Objects/longobject.c python/branches/py3k-jit/Objects/moduleobject.c python/branches/py3k-jit/Objects/object.c python/branches/py3k-jit/Objects/typeobject.c python/branches/py3k-jit/Parser/asdl.py python/branches/py3k-jit/Python/_warnings.c python/branches/py3k-jit/Python/bltinmodule.c python/branches/py3k-jit/Python/getargs.c python/branches/py3k-jit/Python/pythonrun.c python/branches/py3k-jit/Python/sysmodule.c python/branches/py3k-jit/Tools/gdb/libpython.py Modified: python/branches/py3k-jit/Doc/c-api/init.rst ============================================================================== --- python/branches/py3k-jit/Doc/c-api/init.rst (original) +++ python/branches/py3k-jit/Doc/c-api/init.rst Tue May 25 03:17:49 2010 @@ -22,6 +22,7 @@ module: sys triple: module; search; path single: PySys_SetArgv() + single: PySys_SetArgvEx() single: Py_Finalize() Initialize the Python interpreter. In an application embedding Python, this @@ -31,7 +32,7 @@ the table of loaded modules (``sys.modules``), and creates the fundamental modules :mod:`builtins`, :mod:`__main__` and :mod:`sys`. It also initializes the module search path (``sys.path``). It does not set ``sys.argv``; use - :cfunc:`PySys_SetArgv` for that. This is a no-op when called for a second time + :cfunc:`PySys_SetArgvEx` for that. This is a no-op when called for a second time (without calling :cfunc:`Py_Finalize` first). There is no return value; it is a fatal error if the initialization fails. @@ -337,7 +338,7 @@ ``sys.version``. -.. cfunction:: void PySys_SetArgv(int argc, wchar_t **argv) +.. cfunction:: void PySys_SetArgvEx(int argc, wchar_t **argv, int updatepath) .. index:: single: main() @@ -352,14 +353,41 @@ string. If this function fails to initialize :data:`sys.argv`, a fatal condition is signalled using :cfunc:`Py_FatalError`. - This function also prepends the executed script's path to :data:`sys.path`. - If no script is executed (in the case of calling ``python -c`` or just the - interactive interpreter), the empty string is used instead. + If *updatepath* is zero, this is all the function does. If *updatepath* + is non-zero, the function also modifies :data:`sys.path` according to the + following algorithm: + + - If the name of an existing script is passed in ``argv[0]``, the absolute + path of the directory where the script is located is prepended to + :data:`sys.path`. + - Otherwise (that is, if *argc* is 0 or ``argv[0]`` doesn't point + to an existing file name), an empty string is prepended to + :data:`sys.path`, which is the same as prepending the current working + directory (``"."``). + + .. note:: + It is recommended that applications embedding the Python interpreter + for purposes other than executing a single script pass 0 as *updatepath*, + and update :data:`sys.path` themselves if desired. + See `CVE-2008-5983 `_. + + On versions before 3.1.3, you can achieve the same effect by manually + popping the first :data:`sys.path` element after having called + :cfunc:`PySys_SetArgv`, for example using:: + + PyRun_SimpleString("import sys; sys.path.pop(0)\n"); + + .. versionadded:: 3.1.3 .. XXX impl. doesn't seem consistent in allowing 0/NULL for the params; check w/ Guido. +.. cfunction:: void PySys_SetArgv(int argc, wchar_t **argv) + + This function works like :cfunc:`PySys_SetArgv` with *updatepath* set to 1. + + .. cfunction:: void Py_SetPythonHome(wchar_t *home) Set the default "home" directory, that is, the location of the standard Modified: python/branches/py3k-jit/Doc/c-api/sys.rst ============================================================================== --- python/branches/py3k-jit/Doc/c-api/sys.rst (original) +++ python/branches/py3k-jit/Doc/c-api/sys.rst Tue May 25 03:17:49 2010 @@ -81,6 +81,10 @@ Append *s* to :data:`sys.warnoptions`. +.. cfunction:: void PySys_AddWarnOptionUnicode(PyObject *unicode) + + Append *unicode* to :data:`sys.warnoptions`. + .. cfunction:: void PySys_SetPath(wchar_t *path) Set :data:`sys.path` to a list object of paths found in *path* which should Modified: python/branches/py3k-jit/Doc/howto/index.rst ============================================================================== --- python/branches/py3k-jit/Doc/howto/index.rst (original) +++ python/branches/py3k-jit/Doc/howto/index.rst Tue May 25 03:17:49 2010 @@ -16,6 +16,7 @@ advocacy.rst cporting.rst curses.rst + descriptor.rst doanddont.rst functional.rst regex.rst Modified: python/branches/py3k-jit/Doc/library/argparse.rst ============================================================================== --- python/branches/py3k-jit/Doc/library/argparse.rst (original) +++ python/branches/py3k-jit/Doc/library/argparse.rst Tue May 25 03:17:49 2010 @@ -672,8 +672,8 @@ >>> import argparse >>> parser = argparse.ArgumentParser(prog='PROG') - >>> parser.add_argument('-v', '--version', action='version', version='%(prog)s 2.0') - >>> parser.parse_args(['-v']) + >>> parser.add_argument('--version', action='version', version='%(prog)s 2.0') + >>> parser.parse_args(['--version']) PROG 2.0 You can also specify an arbitrary action by passing an object that implements @@ -1725,3 +1725,6 @@ * Replace strings with implicit arguments such as ``%default`` or ``%prog`` with the standard python syntax to use dictionaries to format strings, that is, ``%(default)s`` and ``%(prog)s``. + +* Replace the OptionParser constructor ``version`` argument with a call to + ``parser.add_argument('--version', action='version', version='')`` Modified: python/branches/py3k-jit/Doc/library/decimal.rst ============================================================================== --- python/branches/py3k-jit/Doc/library/decimal.rst (original) +++ python/branches/py3k-jit/Doc/library/decimal.rst Tue May 25 03:17:49 2010 @@ -122,7 +122,7 @@ >>> from decimal import * >>> getcontext() Context(prec=28, rounding=ROUND_HALF_EVEN, Emin=-999999999, Emax=999999999, - capitals=1, flags=[], traps=[Overflow, DivisionByZero, + capitals=1, clamp=0, flags=[], traps=[Overflow, DivisionByZero, InvalidOperation]) >>> getcontext().prec = 7 # Set a new precision @@ -244,7 +244,7 @@ >>> ExtendedContext Context(prec=9, rounding=ROUND_HALF_EVEN, Emin=-999999999, Emax=999999999, - capitals=1, flags=[], traps=[]) + capitals=1, clamp=0, flags=[], traps=[]) >>> setcontext(ExtendedContext) >>> Decimal(1) / Decimal(7) Decimal('0.142857143') @@ -269,7 +269,7 @@ Decimal('3.14159292') >>> getcontext() Context(prec=9, rounding=ROUND_HALF_EVEN, Emin=-999999999, Emax=999999999, - capitals=1, flags=[Inexact, Rounded], traps=[]) + capitals=1, clamp=0, flags=[Inexact, Rounded], traps=[]) The *flags* entry shows that the rational approximation to :const:`Pi` was rounded (digits beyond the context precision were thrown away) and that the @@ -891,7 +891,7 @@ :class:`Context` constructor. -.. class:: Context(prec=None, rounding=None, traps=None, flags=None, Emin=None, Emax=None, capitals=1) +.. class:: Context(prec=None, rounding=None, traps=None, flags=None, Emin=None, Emax=None, capitals=None, clamp=None) Creates a new context. If a field is not specified or is :const:`None`, the default values are copied from the :const:`DefaultContext`. If the *flags* @@ -922,6 +922,23 @@ :const:`1`, exponents are printed with a capital :const:`E`; otherwise, a lowercase :const:`e` is used: :const:`Decimal('6.02e+23')`. + The *clamp* field is either :const:`0` (the default) or :const:`1`. + If set to :const:`1`, the exponent ``e`` of a :class:`Decimal` + instance representable in this context is strictly limited to the + range ``Emin - prec + 1 <= e <= Emax - prec + 1``. If *clamp* is + :const:`0` then a weaker condition holds: the adjusted exponent of + the :class:`Decimal` instance is at most ``Emax``. When *clamp* is + :const:`1`, a large normal number will, where possible, have its + exponent reduced and a corresponding number of zeros added to its + coefficient, in order to fit the exponent constraints; this + preserves the value of the number but loses information about + significant trailing zeros. For example:: + + >>> Context(prec=6, Emax=999, clamp=1).create_decimal('1.23e999') + Decimal('1.23000E+999') + + A *clamp* value of :const:`1` allows compatibility with the + fixed-width decimal interchange formats specified in IEEE 754. The :class:`Context` class defines several general purpose methods as well as a large number of methods for doing arithmetic directly in a given context. Modified: python/branches/py3k-jit/Doc/library/fcntl.rst ============================================================================== --- python/branches/py3k-jit/Doc/library/fcntl.rst (original) +++ python/branches/py3k-jit/Doc/library/fcntl.rst Tue May 25 03:17:49 2010 @@ -8,8 +8,8 @@ .. index:: - pair: UNIX at Unix; file control - pair: UNIX at Unix; I/O control + pair: UNIX; file control + pair: UNIX; I/O control This module performs file control and I/O control on file descriptors. It is an interface to the :cfunc:`fcntl` and :cfunc:`ioctl` Unix routines. Modified: python/branches/py3k-jit/Doc/library/ftplib.rst ============================================================================== --- python/branches/py3k-jit/Doc/library/ftplib.rst (original) +++ python/branches/py3k-jit/Doc/library/ftplib.rst Tue May 25 03:17:49 2010 @@ -122,7 +122,7 @@ The set of all exceptions (as a tuple) that methods of :class:`FTP` instances may raise as a result of problems with the FTP connection (as opposed to programming errors made by the caller). This set includes the - four exceptions listed below as well as :exc:`socket.error` and + four exceptions listed above as well as :exc:`socket.error` and :exc:`IOError`. .. seealso:: Modified: python/branches/py3k-jit/Doc/library/getopt.rst ============================================================================== --- python/branches/py3k-jit/Doc/library/getopt.rst (original) +++ python/branches/py3k-jit/Doc/library/getopt.rst Tue May 25 03:17:49 2010 @@ -5,6 +5,12 @@ :synopsis: Portable parser for command line options; support both short and long option names. +.. note:: + The :mod:`getopt` module is a parser for command line options whose API is + designed to be familiar to users of the C :cfunc:`getopt` function. Users who + are unfamiliar with the C :cfunc:`getopt` function or who would like to write + less code and get better help and error messages should consider using the + :mod:`argparse` module instead. This module helps scripts to parse the command line arguments in ``sys.argv``. It supports the same conventions as the Unix :cfunc:`getopt` function (including @@ -136,9 +142,21 @@ if __name__ == "__main__": main() +Note that an equivalent command line interface could be produced with less code +and more informative help and error messages by using the :mod:`argparse` module:: + + import argparse + + if __name__ == '__main__': + parser = argparse.ArgumentParser() + parser.add_argument('-o', '--output') + parser.add_argument('-v', dest='verbose', action='store_true') + args = parser.parse_args() + # ... do something with args.output ... + # ... do something with args.verbose .. .. seealso:: - Module :mod:`optparse` - More object-oriented command line option parsing. + Module :mod:`argparse` + Alternative command line option and argument parsing library. Modified: python/branches/py3k-jit/Doc/library/hashlib.rst ============================================================================== --- python/branches/py3k-jit/Doc/library/hashlib.rst (original) +++ python/branches/py3k-jit/Doc/library/hashlib.rst Tue May 25 03:17:49 2010 @@ -151,7 +151,7 @@ http://csrc.nist.gov/publications/fips/fips180-2/fips180-2.pdf The FIPS 180-2 publication on Secure Hash Algorithms. - http://www.cryptography.com/cnews/hash.html - Hash Collision FAQ with information on which algorithms have known issues and + http://en.wikipedia.org/wiki/Cryptographic_hash_function#Cryptographic_hash_algorithms + Wikipedia article with information on which algorithms have known issues and what that means regarding their use. Modified: python/branches/py3k-jit/Doc/library/io.rst ============================================================================== --- python/branches/py3k-jit/Doc/library/io.rst (original) +++ python/branches/py3k-jit/Doc/library/io.rst Tue May 25 03:17:49 2010 @@ -240,7 +240,7 @@ Flush and close this stream. This method has no effect if the file is already closed. Once the file is closed, any operation on the file - (e.g. reading or writing) will raise an :exc:`ValueError`. + (e.g. reading or writing) will raise a :exc:`ValueError`. As a convenience, it is allowed to call this method more than once; only the first call, however, will have an effect. Modified: python/branches/py3k-jit/Doc/library/json.rst ============================================================================== --- python/branches/py3k-jit/Doc/library/json.rst (original) +++ python/branches/py3k-jit/Doc/library/json.rst Tue May 25 03:17:49 2010 @@ -209,7 +209,7 @@ specified. Encodings that are not ASCII based (such as UCS-2) are not allowed and should be decoded to :class:`str` first. - The other arguments have the same meaning as in :func:`dump`. + The other arguments have the same meaning as in :func:`load`. Encoders and decoders Modified: python/branches/py3k-jit/Doc/library/multiprocessing.rst ============================================================================== --- python/branches/py3k-jit/Doc/library/multiprocessing.rst (original) +++ python/branches/py3k-jit/Doc/library/multiprocessing.rst Tue May 25 03:17:49 2010 @@ -837,7 +837,7 @@ A bounded semaphore object: a clone of :class:`threading.BoundedSemaphore`. - (On Mac OS X this is indistinguishable from :class:`Semaphore` because + (On Mac OS X, this is indistinguishable from :class:`Semaphore` because ``sem_getvalue()`` is not implemented on that platform). .. class:: Condition([lock]) @@ -879,9 +879,8 @@ specifies a timeout in seconds. If *block* is ``False`` then *timeout* is ignored. -.. note:: - On OS/X ``sem_timedwait`` is unsupported, so timeout arguments for the - aforementioned :meth:`acquire` methods will be ignored on OS/X. + On Mac OS X, ``sem_timedwait`` is unsupported, so calling ``acquire()`` with + a timeout will emulate that function's behavior using a sleeping loop. .. note:: Modified: python/branches/py3k-jit/Doc/library/optparse.rst ============================================================================== --- python/branches/py3k-jit/Doc/library/optparse.rst (original) +++ python/branches/py3k-jit/Doc/library/optparse.rst Tue May 25 03:17:49 2010 @@ -3,6 +3,12 @@ .. module:: optparse :synopsis: Command-line option parsing library. + :deprecated: + +.. deprecated:: 2.7 + The :mod:`optparse` module is deprecated and will not be developed further; + development will continue with the :mod:`argparse` module. + .. moduleauthor:: Greg Ward .. sectionauthor:: Greg Ward Modified: python/branches/py3k-jit/Doc/library/os.rst ============================================================================== --- python/branches/py3k-jit/Doc/library/os.rst (original) +++ python/branches/py3k-jit/Doc/library/os.rst Tue May 25 03:17:49 2010 @@ -142,7 +142,8 @@ synchronized (modify :data:`environb` updates :data:`environ`, and vice versa). - Availability: Unix. + :data:`environb` is only available if :data:`supports_bytes_environ` is + True. .. versionadded:: 3.2 @@ -457,6 +458,14 @@ Availability: Unix, Windows. +.. data:: supports_bytes_environ + + True if the native OS type of the environment is bytes (eg. False on + Windows). + + .. versionadded:: 3.2 + + .. function:: umask(mask) Set the current numeric umask and return the previous umask. @@ -688,6 +697,14 @@ Availability: Unix, Windows. +.. data:: SEEK_SET + SEEK_CUR + SEEK_END + + Parameters to the :func:`lseek` function. Their values are 0, 1, and 2, + respectively. Availability: Windows, Unix. + + .. function:: open(file, flags[, mode]) Open the file *file* and set various flags according to *flags* and possibly @@ -697,7 +714,8 @@ For a description of the flag and mode values, see the C run-time documentation; flag constants (like :const:`O_RDONLY` and :const:`O_WRONLY`) are defined in - this module too (see below). + this module too (see :ref:`open-constants`). In particular, on Windows adding + :const:`O_BINARY` is needed to open files in binary mode. Availability: Unix, Windows. @@ -785,6 +803,12 @@ :func:`fdopen`, or :data:`sys.stdout` or :data:`sys.stderr`, use its :meth:`~file.write` method. + +.. _open-constants: + +``open()`` flag constants +~~~~~~~~~~~~~~~~~~~~~~~~~ + The following constants are options for the *flags* parameter to the :func:`~os.open` function. They can be combined using the bitwise OR operator ``|``. Some of them are not available on all platforms. For descriptions of @@ -836,14 +860,6 @@ the C library. -.. data:: SEEK_SET - SEEK_CUR - SEEK_END - - Parameters to the :func:`lseek` function. Their values are 0, 1, and 2, - respectively. Availability: Windows, Unix. - - .. _os-file-dir: Files and Directories @@ -2178,8 +2194,8 @@ .. data:: devnull - The file path of the null device. For example: ``'/dev/null'`` for POSIX. - Also available via :mod:`os.path`. + The file path of the null device. For example: ``'/dev/null'`` for + POSIX, ``'nul'`` for Windows. Also available via :mod:`os.path`. .. _os-miscfunc: Modified: python/branches/py3k-jit/Doc/library/socket.rst ============================================================================== --- python/branches/py3k-jit/Doc/library/socket.rst (original) +++ python/branches/py3k-jit/Doc/library/socket.rst Tue May 25 03:17:49 2010 @@ -89,8 +89,9 @@ and out-of-memory conditions can be raised; errors related to socket or address semantics raise the error :exc:`socket.error`. -Non-blocking mode is supported through :meth:`setblocking`. A generalization of -this based on timeouts is supported through :meth:`settimeout`. +Non-blocking mode is supported through :meth:`~socket.setblocking`. A +generalization of this based on timeouts is supported through +:meth:`~socket.settimeout`. The module :mod:`socket` exports the following constants and functions: @@ -559,7 +560,9 @@ :platform: Windows The :meth:`ioctl` method is a limited interface to the WSAIoctl system - interface. Please refer to the MSDN documentation for more information. + interface. Please refer to the `Win32 documentation + `_ for more + information. On other platforms, the generic :func:`fcntl.fcntl` and :func:`fcntl.ioctl` functions may be used; they accept a socket object as their first argument. @@ -662,7 +665,7 @@ blocking mode. In non-blocking mode, if a :meth:`recv` call doesn't find any data, or if a :meth:`send` call can't immediately dispose of the data, a :exc:`error` exception is raised; in blocking mode, the calls block until they - can proceed. ``s.setblocking(0)`` is equivalent to ``s.settimeout(0)``; + can proceed. ``s.setblocking(0)`` is equivalent to ``s.settimeout(0.0)``; ``s.setblocking(1)`` is equivalent to ``s.settimeout(None)``. @@ -691,21 +694,21 @@ non-blocking mode, operations fail (with an error that is unfortunately system-dependent) if they cannot be completed immediately. In timeout mode, operations fail if they cannot be completed within the timeout specified for the -socket or if the system returns an error. The :meth:`setblocking` method is simply -a shorthand for certain :meth:`settimeout` calls. +socket or if the system returns an error. The :meth:`~socket.setblocking` +method is simply a shorthand for certain :meth:`~socket.settimeout` calls. Timeout mode internally sets the socket in non-blocking mode. The blocking and timeout modes are shared between file descriptors and socket objects that refer to the same network endpoint. A consequence of this is that file objects -returned by the :meth:`makefile` method must only be used when the socket is in -blocking mode; in timeout or non-blocking mode file operations that cannot be -completed immediately will fail. - -Note that the :meth:`connect` operation is subject to the timeout setting, and -in general it is recommended to call :meth:`settimeout` before calling -:meth:`connect` or pass a timeout parameter to :meth:`create_connection`. -The system network stack may return a connection timeout error -of its own regardless of any Python socket timeout setting. +returned by the :meth:`~socket.makefile` method must only be used when the +socket is in blocking mode; in timeout or non-blocking mode file operations +that cannot be completed immediately will fail. + +Note that the :meth:`~socket.connect` operation is subject to the timeout +setting, and in general it is recommended to call :meth:`~socket.settimeout` +before calling :meth:`~socket.connect` or pass a timeout parameter to +:meth:`create_connection`. The system network stack may return a connection +timeout error of its own regardless of any Python socket timeout setting. .. method:: socket.setsockopt(level, optname, value) @@ -727,8 +730,8 @@ are disallowed. If *how* is :const:`SHUT_RDWR`, further sends and receives are disallowed. -Note that there are no methods :meth:`read` or :meth:`write`; use :meth:`recv` -and :meth:`send` without *flags* argument instead. +Note that there are no methods :meth:`read` or :meth:`write`; use +:meth:`~socket.recv` and :meth:`~socket.send` without *flags* argument instead. Socket objects also have these (read-only) attributes that correspond to the values given to the :class:`socket` constructor. @@ -757,11 +760,12 @@ Here are four minimal example programs using the TCP/IP protocol: a server that echoes all data that it receives back (servicing only one client), and a client using it. Note that a server must perform the sequence :func:`socket`, -:meth:`bind`, :meth:`listen`, :meth:`accept` (possibly repeating the -:meth:`accept` to service more than one client), while a client only needs the -sequence :func:`socket`, :meth:`connect`. Also note that the server does not -:meth:`send`/:meth:`recv` on the socket it is listening on but on the new -socket returned by :meth:`accept`. +:meth:`~socket.bind`, :meth:`~socket.listen`, :meth:`~socket.accept` (possibly +repeating the :meth:`~socket.accept` to service more than one client), while a +client only needs the sequence :func:`socket`, :meth:`~socket.connect`. Also +note that the server does not :meth:`~socket.send`/:meth:`~socket.recv` on the +socket it is listening on but on the new socket returned by +:meth:`~socket.accept`. The first two examples support IPv4 only. :: Modified: python/branches/py3k-jit/Doc/library/ssl.rst ============================================================================== --- python/branches/py3k-jit/Doc/library/ssl.rst (original) +++ python/branches/py3k-jit/Doc/library/ssl.rst Tue May 25 03:17:49 2010 @@ -257,6 +257,37 @@ modern version, and probably the best choice for maximum protection, if both sides can speak it. +.. data:: OP_ALL + + Enables workarounds for various bugs present in other SSL implementations. + This option is set by default. + + .. versionadded:: 3.2 + +.. data:: OP_NO_SSLv2 + + Prevents an SSLv2 connection. This option is only applicable in + conjunction with :const:`PROTOCOL_SSLv23`. It prevents the peers from + choosing SSLv2 as the protocol version. + + .. versionadded:: 3.2 + +.. data:: OP_NO_SSLv3 + + Prevents an SSLv3 connection. This option is only applicable in + conjunction with :const:`PROTOCOL_SSLv23`. It prevents the peers from + choosing SSLv3 as the protocol version. + + .. versionadded:: 3.2 + +.. data:: OP_NO_TLSv1 + + Prevents a TLSv1 connection. This option is only applicable in + conjunction with :const:`PROTOCOL_SSLv23`. It prevents the peers from + choosing TLSv1 as the protocol version. + + .. versionadded:: 3.2 + .. data:: OPENSSL_VERSION The version string of the OpenSSL library loaded by the interpreter:: @@ -379,6 +410,8 @@ SSL Contexts ------------ +.. versionadded:: 3.2 + .. class:: SSLContext(protocol) An object holding various data longer-lived than single SSL connections, @@ -440,6 +473,17 @@ and *suppress_ragged_eofs* have the same meaning as in the top-level :func:`wrap_socket` function. +.. attribute:: SSLContext.options + + An integer representing the set of SSL options enabled on this context. + The default value is :data:`OP_ALL`, but you can specify other options + such as :data:`OP_NO_SSLv2` by ORing them together. + + .. note:: + With versions of OpenSSL older than 0.9.8m, it is only possible + to set options, not to clear them. Attempting to clear an option + (by resetting the corresponding bits) will raise a ``ValueError``. + .. attribute:: SSLContext.protocol The protocol version chosen when constructing the context. This attribute @@ -794,6 +838,20 @@ equivalent unless anonymous ciphers are enabled (they are disabled by default). +Protocol versions +^^^^^^^^^^^^^^^^^ + +SSL version 2 is considered insecure and is therefore dangerous to use. If +you want maximum compatibility between clients and servers, it is recommended +to use :const:`PROTOCOL_SSLv23` as the protocol version and then disable +SSLv2 explicitly using the :data:`SSLContext.options` attribute:: + + context = ssl.SSLContext(ssl.PROTOCOL_SSLv23) + context.options |= ssl.OP_NO_SSLv2 + +The SSL context created above will allow SSLv3 and TLSv1 connections, but +not SSLv2. + .. seealso:: Modified: python/branches/py3k-jit/Doc/library/stdtypes.rst ============================================================================== --- python/branches/py3k-jit/Doc/library/stdtypes.rst (original) +++ python/branches/py3k-jit/Doc/library/stdtypes.rst Tue May 25 03:17:49 2010 @@ -595,6 +595,109 @@ '0x1.d380000000000p+11' +.. _numeric-hash: + +Hashing of numeric types +------------------------ + +For numbers ``x`` and ``y``, possibly of different types, it's a requirement +that ``hash(x) == hash(y)`` whenever ``x == y`` (see the :meth:`__hash__` +method documentation for more details). For ease of implementation and +efficiency across a variety of numeric types (including :class:`int`, +:class:`float`, :class:`decimal.Decimal` and :class:`fractions.Fraction`) +Python's hash for numeric types is based on a single mathematical function +that's defined for any rational number, and hence applies to all instances of +:class:`int` and :class:`fraction.Fraction`, and all finite instances of +:class:`float` and :class:`decimal.Decimal`. Essentially, this function is +given by reduction modulo ``P`` for a fixed prime ``P``. The value of ``P`` is +made available to Python as the :attr:`modulus` attribute of +:data:`sys.hash_info`. + +.. impl-detail:: + + Currently, the prime used is ``P = 2**31 - 1`` on machines with 32-bit C + longs and ``P = 2**61 - 1`` on machines with 64-bit C longs. + +Here are the rules in detail: + + - If ``x = m / n`` is a nonnegative rational number and ``n`` is not divisible + by ``P``, define ``hash(x)`` as ``m * invmod(n, P) % P``, where ``invmod(n, + P)`` gives the inverse of ``n`` modulo ``P``. + + - If ``x = m / n`` is a nonnegative rational number and ``n`` is + divisible by ``P`` (but ``m`` is not) then ``n`` has no inverse + modulo ``P`` and the rule above doesn't apply; in this case define + ``hash(x)`` to be the constant value ``sys.hash_info.inf``. + + - If ``x = m / n`` is a negative rational number define ``hash(x)`` + as ``-hash(-x)``. If the resulting hash is ``-1``, replace it with + ``-2``. + + - The particular values ``sys.hash_info.inf``, ``-sys.hash_info.inf`` + and ``sys.hash_info.nan`` are used as hash values for positive + infinity, negative infinity, or nans (respectively). (All hashable + nans have the same hash value.) + + - For a :class:`complex` number ``z``, the hash values of the real + and imaginary parts are combined by computing ``hash(z.real) + + sys.hash_info.imag * hash(z.imag)``, reduced modulo + ``2**sys.hash_info.width`` so that it lies in + ``range(-2**(sys.hash_info.width - 1), 2**(sys.hash_info.width - + 1))``. Again, if the result is ``-1``, it's replaced with ``-2``. + + +To clarify the above rules, here's some example Python code, +equivalent to the builtin hash, for computing the hash of a rational +number, :class:`float`, or :class:`complex`:: + + + import sys, math + + def hash_fraction(m, n): + """Compute the hash of a rational number m / n. + + Assumes m and n are integers, with n positive. + Equivalent to hash(fractions.Fraction(m, n)). + + """ + P = sys.hash_info.modulus + # Remove common factors of P. (Unnecessary if m and n already coprime.) + while m % P == n % P == 0: + m, n = m // P, n // P + + if n % P == 0: + hash_ = sys.hash_info.inf + else: + # Fermat's Little Theorem: pow(n, P-1, P) is 1, so + # pow(n, P-2, P) gives the inverse of n modulo P. + hash_ = (abs(m) % P) * pow(n, P - 2, P) % P + if m < 0: + hash_ = -hash_ + if hash_ == -1: + hash_ = -2 + return hash_ + + def hash_float(x): + """Compute the hash of a float x.""" + + if math.isnan(x): + return sys.hash_info.nan + elif math.isinf(x): + return sys.hash_info.inf if x > 0 else -sys.hash_info.inf + else: + return hash_fraction(*x.as_integer_ratio()) + + def hash_complex(z): + """Compute the hash of a complex number z.""" + + hash_ = hash_float(z.real) + sys.hash_info.imag * hash_float(z.imag) + # do a signed reduction modulo 2**sys.hash_info.width + M = 2**(sys.hash_info.width - 1) + hash_ = (hash_ & (M - 1)) - (hash & M) + if hash_ == -1: + hash_ == -2 + return hash_ + .. _typeiter: Iterator Types Modified: python/branches/py3k-jit/Doc/library/symtable.rst ============================================================================== --- python/branches/py3k-jit/Doc/library/symtable.rst (original) +++ python/branches/py3k-jit/Doc/library/symtable.rst Tue May 25 03:17:49 2010 @@ -67,7 +67,7 @@ Return ``True`` if the block uses ``exec``. - .. method:: has_import_start() + .. method:: has_import_star() Return ``True`` if the block uses a starred from-import. Modified: python/branches/py3k-jit/Doc/library/sys.rst ============================================================================== --- python/branches/py3k-jit/Doc/library/sys.rst (original) +++ python/branches/py3k-jit/Doc/library/sys.rst Tue May 25 03:17:49 2010 @@ -446,6 +446,30 @@ Changed to a named tuple and added *service_pack_minor*, *service_pack_major*, *suite_mask*, and *product_type*. + +.. data:: hash_info + + A structseq giving parameters of the numeric hash implementation. For + more details about hashing of numeric types, see :ref:`numeric-hash`. + + +---------------------+--------------------------------------------------+ + | attribute | explanation | + +=====================+==================================================+ + | :const:`width` | width in bits used for hash values | + +---------------------+--------------------------------------------------+ + | :const:`modulus` | prime modulus P used for numeric hash scheme | + +---------------------+--------------------------------------------------+ + | :const:`inf` | hash value returned for a positive infinity | + +---------------------+--------------------------------------------------+ + | :const:`nan` | hash value returned for a nan | + +---------------------+--------------------------------------------------+ + | :const:`imag` | multiplier used for the imaginary part of a | + | | complex number | + +---------------------+--------------------------------------------------+ + + .. versionadded:: 3.2 + + .. data:: hexversion The version number encoded as a single integer. This is guaranteed to increase Modified: python/branches/py3k-jit/Doc/library/syslog.rst ============================================================================== --- python/branches/py3k-jit/Doc/library/syslog.rst (original) +++ python/branches/py3k-jit/Doc/library/syslog.rst Tue May 25 03:17:49 2010 @@ -10,66 +10,63 @@ Refer to the Unix manual pages for a detailed description of the ``syslog`` facility. -This module wraps the system ``syslog`` module. A pure Python -library that can speak to a syslog server is available in -the :mod:`logging.handlers` module as :class:`SysLogHandler`. +This module wraps the system ``syslog`` family of routines. A pure Python +library that can speak to a syslog server is available in the +:mod:`logging.handlers` module as :class:`SysLogHandler`. The module defines the following functions: .. function:: syslog([priority,] message) - Send the string *message* to the system logger. A trailing newline is - added if necessary. Each message is tagged with a priority composed - of a *facility* and a *level*. The optional *priority* argument, which - defaults to :const:`LOG_INFO`, determines the message priority. If the - facility is not encoded in *priority* using logical-or (``LOG_INFO | - LOG_USER``), the value given in the :func:`openlog` call is used. + Send the string *message* to the system logger. A trailing newline is added + if necessary. Each message is tagged with a priority composed of a + *facility* and a *level*. The optional *priority* argument, which defaults + to :const:`LOG_INFO`, determines the message priority. If the facility is + not encoded in *priority* using logical-or (``LOG_INFO | LOG_USER``), the + value given in the :func:`openlog` call is used. - If :func:`openlog` has not been called prior to the call to - :func:'syslog', ``openlog()`` will be called with no arguments. + If :func:`openlog` has not been called prior to the call to :func:`syslog`, + ``openlog()`` will be called with no arguments. .. function:: openlog([ident[, logopt[, facility]]]) - Logging options of subsequent :func:`syslog` calls can be set by - calling :func:`openlog`. :func:`syslog` will call :func:`openlog` - with no arguments if the log is not currently open. - - The optional *ident* keyword argument is a string which is prepended - to every message, and defaults to ''sys.argv[0]'' with leading - path components stripped. The optional *logopt* keyword argument - (default=0) is a bit field - see below for possible values to combine. - The optional *facility* keyword argument (default=:const:`LOG_USER`) - sets the default facility for messages which do not have a facility - explicitly encoded. - - .. versionchanged::3.2 - In previous versions, keyword arguments were not allowed, and *ident* - was required. The default for *ident* was dependent on the system - libraries, and often was ''python'' instead of the name of the - python program file. + Logging options of subsequent :func:`syslog` calls can be set by calling + :func:`openlog`. :func:`syslog` will call :func:`openlog` with no arguments + if the log is not currently open. + + The optional *ident* keyword argument is a string which is prepended to every + message, and defaults to ``sys.argv[0]`` with leading path components + stripped. The optional *logopt* keyword argument (default is 0) is a bit + field -- see below for possible values to combine. The optional *facility* + keyword argument (default is :const:`LOG_USER`) sets the default facility for + messages which do not have a facility explicitly encoded. + + .. versionchanged:: 3.2 + In previous versions, keyword arguments were not allowed, and *ident* was + required. The default for *ident* was dependent on the system libraries, + and often was ``python`` instead of the name of the python program file. .. function:: closelog() - Reset the syslog module values and call the system library - ''closelog()''. + Reset the syslog module values and call the system library ``closelog()``. - This causes the module to behave as it does when initially imported. - For example, :func:'openlog' will be called on the first :func:'syslog' - call (if :func:'openlog' hasn't already been called), and *ident* - and other :func:'openlog' parameters are reset to defaults. + This causes the module to behave as it does when initially imported. For + example, :func:`openlog` will be called on the first :func:`syslog` call (if + :func:`openlog` hasn't already been called), and *ident* and other + :func:`openlog` parameters are reset to defaults. .. function:: setlogmask(maskpri) - Set the priority mask to *maskpri* and return the previous mask value. - Calls to :func:`syslog` with a priority level not set in *maskpri* - are ignored. The default is to log all priorities. The function - ``LOG_MASK(pri)`` calculates the mask for the individual priority - *pri*. The function ``LOG_UPTO(pri)`` calculates the mask for all - priorities up to and including *pri*. + Set the priority mask to *maskpri* and return the previous mask value. Calls + to :func:`syslog` with a priority level not set in *maskpri* are ignored. + The default is to log all priorities. The function ``LOG_MASK(pri)`` + calculates the mask for the individual priority *pri*. The function + ``LOG_UPTO(pri)`` calculates the mask for all priorities up to and including + *pri*. The module defines the following constants: @@ -100,11 +97,11 @@ syslog.syslog('Processing started') if error: - syslog.syslog(syslog.LOG_ERR, 'Processing started') + syslog.syslog(syslog.LOG_ERR, 'Processing started') -An example of setting some log options, these would include the process ID -in logged messages, and write the messages to the destination facility -used for mail logging:: +An example of setting some log options, these would include the process ID in +logged messages, and write the messages to the destination facility used for +mail logging:: syslog.openlog(logopt=syslog.LOG_PID, facility=syslog.LOG_MAIL) syslog.syslog('E-mail processing initiated...') Modified: python/branches/py3k-jit/Doc/library/telnetlib.rst ============================================================================== --- python/branches/py3k-jit/Doc/library/telnetlib.rst (original) +++ python/branches/py3k-jit/Doc/library/telnetlib.rst Tue May 25 03:17:49 2010 @@ -27,16 +27,11 @@ :class:`Telnet` represents a connection to a Telnet server. The instance is initially not connected by default; the :meth:`open` method must be used to establish a connection. Alternatively, the host name and optional port - and timeout can be passed to the constructor, in which case the connection to - the server will be established before the constructor returns. The optional - *timeout* parameter specifies a timeout in seconds for the connection attempt (if - not specified, the global default timeout setting will be used). - number can be passed to the constructor, to, in which case the connection to - the server will be established before the constructor returns. The optional + the server will be established before the constructor returns. The optional *timeout* parameter specifies a timeout in seconds for blocking operations - like the connection attempt (if not specified, or passed as None, the global - default timeout setting will be used). + like the connection attempt (if not specified, the global default timeout + setting will be used). Do not reopen an already connected instance. Modified: python/branches/py3k-jit/Doc/library/tempfile.rst ============================================================================== --- python/branches/py3k-jit/Doc/library/tempfile.rst (original) +++ python/branches/py3k-jit/Doc/library/tempfile.rst Tue May 25 03:17:49 2010 @@ -27,8 +27,7 @@ The module defines the following user-callable functions: - -.. function:: TemporaryFile(mode='w+b', bufsize=-1, suffix='', prefix='tmp', dir=None) +.. function:: TemporaryFile(mode='w+b', buffering=None, encoding=None, newline=None, suffix='', prefix='tmp', dir=None) Return a file-like object that can be used as a temporary storage area. The file is created using :func:`mkstemp`. It will be destroyed as soon @@ -41,8 +40,8 @@ The *mode* parameter defaults to ``'w+b'`` so that the file created can be read and written without being closed. Binary mode is used so that it behaves consistently on all platforms without regard for the data that is - stored. *bufsize* defaults to ``-1``, meaning that the operating system - default is used. + stored. *buffering*, *encoding* and *newline* are interpreted as for + :func:`open`. The *dir*, *prefix* and *suffix* parameters are passed to :func:`mkstemp`. @@ -52,7 +51,7 @@ :keyword:`with` statement, just like a normal file. -.. function:: NamedTemporaryFile(mode='w+b', bufsize=-1, suffix='', prefix='tmp', dir=None, delete=True) +.. function:: NamedTemporaryFile(mode='w+b', buffering=None, encoding=None, newline=None, suffix='', prefix='tmp', dir=None, delete=True) This function operates exactly as :func:`TemporaryFile` does, except that the file is guaranteed to have a visible name in the file system (on @@ -67,7 +66,7 @@ be used in a :keyword:`with` statement, just like a normal file. -.. function:: SpooledTemporaryFile(max_size=0, mode='w+b', bufsize=-1, suffix='', prefix='tmp', dir=None) +.. function:: SpooledTemporaryFile(max_size=0, mode='w+b', buffering=None, encoding=None, newline=None, suffix='', prefix='tmp', dir=None) This function operates exactly as :func:`TemporaryFile` does, except that data is spooled in memory until the file size exceeds *max_size*, or Modified: python/branches/py3k-jit/Doc/library/test.rst ============================================================================== --- python/branches/py3k-jit/Doc/library/test.rst (original) +++ python/branches/py3k-jit/Doc/library/test.rst Tue May 25 03:17:49 2010 @@ -340,7 +340,7 @@ .. function:: captured_stdout() - This is a context manager than runs the :keyword:`with` statement body using + This is a context manager that runs the :keyword:`with` statement body using a :class:`StringIO.StringIO` object as sys.stdout. That object can be retrieved using the ``as`` clause of the :keyword:`with` statement. Modified: python/branches/py3k-jit/Doc/library/unittest.rst ============================================================================== --- python/branches/py3k-jit/Doc/library/unittest.rst (original) +++ python/branches/py3k-jit/Doc/library/unittest.rst Tue May 25 03:17:49 2010 @@ -749,7 +749,7 @@ .. method:: skipTest(reason) - Calling this during the a test method or :meth:`setUp` skips the current + Calling this during a test method or :meth:`setUp` skips the current test. See :ref:`unittest-skipping` for more information. .. versionadded:: 3.1 @@ -773,8 +773,7 @@ will be *msg* if given, otherwise it will be :const:`None`. .. deprecated:: 3.1 - :meth:`failUnless`; use one of the ``assert`` variants. - :meth:`assert_`; use :meth:`assertTrue`. + :meth:`failUnless` and :meth:`assert_`; use :meth:`assertTrue`. .. method:: assertEqual(first, second, msg=None) Modified: python/branches/py3k-jit/Doc/library/urllib.request.rst ============================================================================== --- python/branches/py3k-jit/Doc/library/urllib.request.rst (original) +++ python/branches/py3k-jit/Doc/library/urllib.request.rst Tue May 25 03:17:49 2010 @@ -126,26 +126,6 @@ of the data it has downloaded, and just returns it. In this case you just have to assume that the download was successful. - -.. data:: _urlopener - - The public functions :func:`urlopen` and :func:`urlretrieve` create an instance - of the :class:`FancyURLopener` class and use it to perform their requested - actions. To override this functionality, programmers can create a subclass of - :class:`URLopener` or :class:`FancyURLopener`, then assign an instance of that - class to the ``urllib.request._urlopener`` variable before calling the - desired function. For example, applications may want to specify a different - :mailheader:`User-Agent` header than :class:`URLopener` defines. - This can be accomplished with the following code:: - - import urllib.request - - class AppURLopener(urllib.request.FancyURLopener): - version = "App/1.7" - - urllib.request._urlopener = AppURLopener() - - .. function:: urlcleanup() Clear the cache that may have been built up by previous calls to @@ -624,7 +604,7 @@ method on the currently installed global :class:`OpenerDirector`). The optional *timeout* parameter specifies a timeout in seconds for blocking operations like the connection attempt (if not specified, the global default - timeout setting will be usedi). The timeout feature actually works only for + timeout setting will be used). The timeout feature actually works only for HTTP, HTTPS, FTP and FTPS connections). @@ -1099,7 +1079,7 @@ >>> import urllib.request >>> f = urllib.request.urlopen('http://www.python.org/') - >>> print(fp.read(100).decode('utf-8')) + >>> print(f.read(100).decode('utf-8')) ` is used +to ensure that the handles are closed correctly, even if the programmer neglects +to explicitly close them. This module offers the following functions: .. function:: CloseKey(hkey) - Closes a previously opened registry key. The hkey argument specifies a + Closes a previously opened registry key. The *hkey* argument specifies a previously opened key. .. note:: - If *hkey* is not closed using this method (or via :meth:`hkey.Close() `), - it is closed when the *hkey* object is destroyed by Python. + + If *hkey* is not closed using this method (or via :meth:`hkey.Close() + `), it is closed when the *hkey* object is destroyed by + Python. .. function:: ConnectRegistry(computer_name, key) @@ -120,7 +122,7 @@ *res* is a reserved integer, and must be zero. The default is zero. - *sam* is an integer that specifies an access mask that describes the + *sam* is an integer that specifies an access mask that describes the desired security access for the key. Default is :const:`KEY_ALL_ACCESS`. See :ref:`Access Rights ` for other allowed values. @@ -183,13 +185,15 @@ | | registry type | +-------+--------------------------------------------+ | ``2`` | An integer that identifies the type of the | - | | value data | + | | value data (see table in docs for | + | | :meth:`SetValueEx`) | +-------+--------------------------------------------+ .. function:: ExpandEnvironmentStrings(str) - Expands environment strings %NAME% in unicode string like :const:`REG_EXPAND_SZ`:: + Expands environment variable placeholders ``%NAME%`` in strings like + :const:`REG_EXPAND_SZ`:: >>> ExpandEnvironmentStrings('%windir%') 'C:\\Windows' @@ -223,23 +227,20 @@ *key* is a handle returned by :func:`ConnectRegistry` or one of the constants :const:`HKEY_USERS` or :const:`HKEY_LOCAL_MACHINE`. - *sub_key* is a string that identifies the sub_key to load. + *sub_key* is a string that identifies the subkey to load. *file_name* is the name of the file to load registry data from. This file must have been created with the :func:`SaveKey` function. Under the file allocation table (FAT) file system, the filename may not have an extension. - A call to LoadKey() fails if the calling process does not have the - :const:`SE_RESTORE_PRIVILEGE` privilege. Note that privileges are different than + A call to :func:`LoadKey` fails if the calling process does not have the + :const:`SE_RESTORE_PRIVILEGE` privilege. Note that privileges are different from permissions -- see the `RegLoadKey documentation `__ for more details. If *key* is a handle returned by :func:`ConnectRegistry`, then the path - specified in *fileName* is relative to the remote computer. - - The Win32 documentation implies *key* must be in the :const:`HKEY_USER` or - :const:`HKEY_LOCAL_MACHINE` tree. This may or may not be true. + specified in *file_name* is relative to the remote computer. .. function:: OpenKey(key, sub_key[, res[, sam]]) @@ -254,8 +255,8 @@ *res* is a reserved integer, and must be zero. The default is zero. *sam* is an integer that specifies an access mask that describes the desired - security access for the key. Default is :const:`KEY_READ`. See - :ref:`Access Rights ` for other allowed values. + security access for the key. Default is :const:`KEY_READ`. See :ref:`Access + Rights ` for other allowed values. The result is a new handle to the specified key. @@ -327,7 +328,8 @@ | ``0`` | The value of the registry item. | +-------+-----------------------------------------+ | ``1`` | An integer giving the registry type for | - | | this value. | + | | this value (see table in docs for | + | | :meth:`SetValueEx`) | +-------+-----------------------------------------+ @@ -338,10 +340,10 @@ *key* is an already open key, or one of the predefined :ref:`HKEY_* constants `. - *file_name* is the name of the file to save registry data to. This file cannot - already exist. If this filename includes an extension, it cannot be used on file - allocation table (FAT) file systems by the :meth:`LoadKey`, :meth:`ReplaceKey` - or :meth:`RestoreKey` methods. + *file_name* is the name of the file to save registry data to. This file + cannot already exist. If this filename includes an extension, it cannot be + used on file allocation table (FAT) file systems by the :meth:`LoadKey` + method. If *key* represents a key on a remote computer, the path described by *file_name* is relative to the remote computer. The caller of this method must @@ -411,16 +413,16 @@ .. function:: DisableReflectionKey(key) Disables registry reflection for 32-bit processes running on a 64-bit - Operating System. + operating system. - *key* is an already open key, or one of the predefined - :ref:`HKEY_* constants `. + *key* is an already open key, or one of the predefined :ref:`HKEY_* constants + `. - Will generally raise :exc:`NotImplemented` if executed on a 32-bit - Operating System. + Will generally raise :exc:`NotImplemented` if executed on a 32-bit operating + system. If the key is not on the reflection list, the function succeeds but has no - effect. Disabling reflection for a key does not affect reflection of any + effect. Disabling reflection for a key does not affect reflection of any subkeys. @@ -428,11 +430,11 @@ Restores registry reflection for the specified disabled key. - *key* is an already open key, or one of the predefined - :ref:`HKEY_* constants `. + *key* is an already open key, or one of the predefined :ref:`HKEY_* constants + `. - Will generally raise :exc:`NotImplemented` if executed on a 32-bit - Operating System. + Will generally raise :exc:`NotImplemented` if executed on a 32-bit operating + system. Restoring reflection for a key does not affect reflection of any subkeys. @@ -447,7 +449,7 @@ Returns ``True`` if reflection is disabled. Will generally raise :exc:`NotImplemented` if executed on a 32-bit - Operating System. + operating system. .. _constants: @@ -646,7 +648,7 @@ This object wraps a Windows HKEY object, automatically closing it when the object is destroyed. To guarantee cleanup, you can call either the -:meth:`Close` method on the object, or the :func:`CloseKey` function. +:meth:`~PyHKEY.Close` method on the object, or the :func:`CloseKey` function. All registry functions in this module return one of these objects. @@ -666,8 +668,8 @@ Handle objects can be converted to an integer (e.g., using the built-in :func:`int` function), in which case the underlying Windows handle value is -returned. You can also use the :meth:`Detach` method to return the integer -handle, and also disconnect the Windows handle from the handle object. +returned. You can also use the :meth:`~PyHKEY.Detach` method to return the +integer handle, and also disconnect the Windows handle from the handle object. .. method:: PyHKEY.Close() @@ -692,11 +694,12 @@ .. method:: PyHKEY.__enter__() PyHKEY.__exit__(\*exc_info) - The HKEY object implements :meth:`__enter__` and :meth:`__exit__` and thus - supports the context protocol for the :keyword:`with` statement:: + The HKEY object implements :meth:`~object.__enter__` and + :meth:`~object.__exit__` and thus supports the context protocol for the + :keyword:`with` statement:: with OpenKey(HKEY_LOCAL_MACHINE, "foo") as key: - # ... work with key ... + ... # work with key will automatically close *key* when control leaves the :keyword:`with` block. Modified: python/branches/py3k-jit/Doc/reference/datamodel.rst ============================================================================== --- python/branches/py3k-jit/Doc/reference/datamodel.rst (original) +++ python/branches/py3k-jit/Doc/reference/datamodel.rst Tue May 25 03:17:49 2010 @@ -1587,6 +1587,46 @@ called *members*. +Customizing instance and subclass checks +---------------------------------------- + +The following methods are used to override the default behavior of the +:func:`isinstance` and :func:`issubclass` built-in functions. + +In particular, the metaclass :class:`abc.ABCMeta` implements these methods in +order to allow the addition of Abstract Base Classes (ABCs) as "virtual base +classes" to any class or type (including built-in types), and including to other +ABCs. + +.. method:: class.__instancecheck__(self, instance) + + Return true if *instance* should be considered a (direct or indirect) + instance of *class*. If defined, called to implement ``isinstance(instance, + class)``. + + +.. method:: class.__subclasscheck__(self, subclass) + + Return true if *subclass* should be considered a (direct or indirect) + subclass of *class*. If defined, called to implement ``issubclass(subclass, + class)``. + + +Note that these methods are looked up on the type (metaclass) of a class. They +cannot be defined as class methods in the actual class. This is consistent with +the lookup of special methods that are called on instances, only that in this +case the instance is itself a class. + +.. seealso:: + + :pep:`3119` - Introducing Abstract Base Classes + Includes the specification for customizing :func:`isinstance` and + :func:`issubclass` behavior through :meth:`__instancecheck__` and + :meth:`__subclasscheck__`, with motivation for this functionality in the + context of adding Abstract Base Classes (see the :mod:`abc` module) to the + language. + + .. _callable-types: Emulating callable objects Modified: python/branches/py3k-jit/Doc/tutorial/datastructures.rst ============================================================================== --- python/branches/py3k-jit/Doc/tutorial/datastructures.rst (original) +++ python/branches/py3k-jit/Doc/tutorial/datastructures.rst Tue May 25 03:17:49 2010 @@ -377,10 +377,7 @@ Here is a brief demonstration:: - >>> basket = {'apple', 'orange', 'apple', 'pear', 'orange', 'banana'} - >>> print(basket) - {'orange', 'banana', 'pear', 'apple'} - >>> fruit = ['apple', 'orange', 'apple', 'pear', 'orange', 'banana'] + >>> basket = ['apple', 'orange', 'apple', 'pear', 'orange', 'banana'] >>> fruit = set(basket) # create a set without duplicates >>> fruit {'orange', 'pear', 'apple', 'banana'} Modified: python/branches/py3k-jit/Include/pyport.h ============================================================================== --- python/branches/py3k-jit/Include/pyport.h (original) +++ python/branches/py3k-jit/Include/pyport.h Tue May 25 03:17:49 2010 @@ -126,6 +126,20 @@ #endif #endif +/* Parameters used for the numeric hash implementation. See notes for + _PyHash_Double in Objects/object.c. Numeric hashes are based on + reduction modulo the prime 2**_PyHASH_BITS - 1. */ + +#if SIZEOF_LONG >= 8 +#define _PyHASH_BITS 61 +#else +#define _PyHASH_BITS 31 +#endif +#define _PyHASH_MODULUS ((1UL << _PyHASH_BITS) - 1) +#define _PyHASH_INF 314159 +#define _PyHASH_NAN 0 +#define _PyHASH_IMAG 1000003UL + /* uintptr_t is the C9X name for an unsigned integral type such that a * legitimate void* can be cast to uintptr_t and then back to void* again * without loss of information. Similarly for intptr_t, wrt a signed Modified: python/branches/py3k-jit/Include/sysmodule.h ============================================================================== --- python/branches/py3k-jit/Include/sysmodule.h (original) +++ python/branches/py3k-jit/Include/sysmodule.h Tue May 25 03:17:49 2010 @@ -10,6 +10,7 @@ PyAPI_FUNC(PyObject *) PySys_GetObject(const char *); PyAPI_FUNC(int) PySys_SetObject(const char *, PyObject *); PyAPI_FUNC(void) PySys_SetArgv(int, wchar_t **); +PyAPI_FUNC(void) PySys_SetArgvEx(int, wchar_t **, int); PyAPI_FUNC(void) PySys_SetPath(const wchar_t *); PyAPI_FUNC(void) PySys_WriteStdout(const char *format, ...) @@ -21,6 +22,7 @@ PyAPI_FUNC(void) PySys_ResetWarnOptions(void); PyAPI_FUNC(void) PySys_AddWarnOption(const wchar_t *); +PyAPI_FUNC(void) PySys_AddWarnOptionUnicode(PyObject *); PyAPI_FUNC(int) PySys_HasWarnOptions(void); #ifdef __cplusplus Modified: python/branches/py3k-jit/Lib/_abcoll.py ============================================================================== --- python/branches/py3k-jit/Lib/_abcoll.py (original) +++ python/branches/py3k-jit/Lib/_abcoll.py Tue May 25 03:17:49 2010 @@ -376,8 +376,9 @@ return ValuesView(self) def __eq__(self, other): - return isinstance(other, Mapping) and \ - dict(self.items()) == dict(other.items()) + if not isinstance(other, Mapping): + return NotImplemented + return dict(self.items()) == dict(other.items()) def __ne__(self, other): return not (self == other) Modified: python/branches/py3k-jit/Lib/argparse.py ============================================================================== --- python/branches/py3k-jit/Lib/argparse.py (original) +++ python/branches/py3k-jit/Lib/argparse.py Tue May 25 03:17:49 2010 @@ -987,7 +987,7 @@ version=None, dest=SUPPRESS, default=SUPPRESS, - help=None): + help="show program's version number and exit"): super(_VersionAction, self).__init__( option_strings=option_strings, dest=dest, Modified: python/branches/py3k-jit/Lib/asyncore.py ============================================================================== --- python/branches/py3k-jit/Lib/asyncore.py (original) +++ python/branches/py3k-jit/Lib/asyncore.py Tue May 25 03:17:49 2010 @@ -63,8 +63,8 @@ def _strerror(err): try: - return strerror(err) - except (ValueError, OverflowError): + return os.strerror(err) + except (ValueError, OverflowError, NameError): if err in errorcode: return errorcode[err] return "Unknown error %s" %err Modified: python/branches/py3k-jit/Lib/codecs.py ============================================================================== --- python/branches/py3k-jit/Lib/codecs.py (original) +++ python/branches/py3k-jit/Lib/codecs.py Tue May 25 03:17:49 2010 @@ -374,6 +374,11 @@ """ pass + def seek(self, offset, whence=0): + self.stream.seek(offset, whence) + if whence == 0 and offset == 0: + self.reset() + def __getattr__(self, name, getattr=getattr): @@ -606,8 +611,8 @@ Resets the codec buffers used for keeping state. """ - self.reset() self.stream.seek(offset, whence) + self.reset() def __next__(self): @@ -699,6 +704,12 @@ self.reader.reset() self.writer.reset() + def seek(self, offset, whence=0): + self.stream.seek(offset, whence) + self.reader.reset() + if whence == 0 and offset == 0: + self.writer.reset() + def __getattr__(self, name, getattr=getattr): Modified: python/branches/py3k-jit/Lib/decimal.py ============================================================================== --- python/branches/py3k-jit/Lib/decimal.py (original) +++ python/branches/py3k-jit/Lib/decimal.py Tue May 25 03:17:49 2010 @@ -164,7 +164,7 @@ anything, though. handle -- Called when context._raise_error is called and the - trap_enabler is set. First argument is self, second is the + trap_enabler is not set. First argument is self, second is the context. More arguments can be given, those being after the explanation in _raise_error (For example, context._raise_error(NewError, '(-x)!', self._sign) would @@ -862,7 +862,7 @@ # that specified by IEEE 754. def __eq__(self, other, context=None): - other = _convert_other(other, allow_float=True) + other = _convert_other(other, allow_float = True) if other is NotImplemented: return other if self._check_nans(other, context): @@ -870,7 +870,7 @@ return self._cmp(other) == 0 def __ne__(self, other, context=None): - other = _convert_other(other, allow_float=True) + other = _convert_other(other, allow_float = True) if other is NotImplemented: return other if self._check_nans(other, context): @@ -879,7 +879,7 @@ def __lt__(self, other, context=None): - other = _convert_other(other, allow_float=True) + other = _convert_other(other, allow_float = True) if other is NotImplemented: return other ans = self._compare_check_nans(other, context) @@ -888,7 +888,7 @@ return self._cmp(other) < 0 def __le__(self, other, context=None): - other = _convert_other(other, allow_float=True) + other = _convert_other(other, allow_float = True) if other is NotImplemented: return other ans = self._compare_check_nans(other, context) @@ -897,7 +897,7 @@ return self._cmp(other) <= 0 def __gt__(self, other, context=None): - other = _convert_other(other, allow_float=True) + other = _convert_other(other, allow_float = True) if other is NotImplemented: return other ans = self._compare_check_nans(other, context) @@ -906,7 +906,7 @@ return self._cmp(other) > 0 def __ge__(self, other, context=None): - other = _convert_other(other, allow_float=True) + other = _convert_other(other, allow_float = True) if other is NotImplemented: return other ans = self._compare_check_nans(other, context) @@ -935,55 +935,28 @@ def __hash__(self): """x.__hash__() <==> hash(x)""" - # Decimal integers must hash the same as the ints - # - # The hash of a nonspecial noninteger Decimal must depend only - # on the value of that Decimal, and not on its representation. - # For example: hash(Decimal('100E-1')) == hash(Decimal('10')). - - # Equality comparisons involving signaling nans can raise an - # exception; since equality checks are implicitly and - # unpredictably used when checking set and dict membership, we - # prevent signaling nans from being used as set elements or - # dict keys by making __hash__ raise an exception. + + # In order to make sure that the hash of a Decimal instance + # agrees with the hash of a numerically equal integer, float + # or Fraction, we follow the rules for numeric hashes outlined + # in the documentation. (See library docs, 'Built-in Types'). if self._is_special: if self.is_snan(): raise TypeError('Cannot hash a signaling NaN value.') elif self.is_nan(): - # 0 to match hash(float('nan')) - return 0 + return _PyHASH_NAN else: - # values chosen to match hash(float('inf')) and - # hash(float('-inf')). if self._sign: - return -271828 + return -_PyHASH_INF else: - return 314159 + return _PyHASH_INF - # In Python 2.7, we're allowing comparisons (but not - # arithmetic operations) between floats and Decimals; so if - # a Decimal instance is exactly representable as a float then - # its hash should match that of the float. - self_as_float = float(self) - if Decimal.from_float(self_as_float) == self: - return hash(self_as_float) - - if self._isinteger(): - op = _WorkRep(self.to_integral_value()) - # to make computation feasible for Decimals with large - # exponent, we use the fact that hash(n) == hash(m) for - # any two nonzero integers n and m such that (i) n and m - # have the same sign, and (ii) n is congruent to m modulo - # 2**64-1. So we can replace hash((-1)**s*c*10**e) with - # hash((-1)**s*c*pow(10, e, 2**64-1). - return hash((-1)**op.sign*op.int*pow(10, op.exp, 2**64-1)) - # The value of a nonzero nonspecial Decimal instance is - # faithfully represented by the triple consisting of its sign, - # its adjusted exponent, and its coefficient with trailing - # zeros removed. - return hash((self._sign, - self._exp+len(self._int), - self._int.rstrip('0'))) + if self._exp >= 0: + exp_hash = pow(10, self._exp, _PyHASH_MODULUS) + else: + exp_hash = pow(_PyHASH_10INV, -self._exp, _PyHASH_MODULUS) + hash_ = int(self._int) * exp_hash % _PyHASH_MODULUS + return hash_ if self >= 0 else -hash_ def as_tuple(self): """Represents the number as a triple tuple. @@ -1611,9 +1584,9 @@ """Decapitate the payload of a NaN to fit the context""" payload = self._int - # maximum length of payload is precision if _clamp=0, - # precision-1 if _clamp=1. - max_payload_len = context.prec - context._clamp + # maximum length of payload is precision if clamp=0, + # precision-1 if clamp=1. + max_payload_len = context.prec - context.clamp if len(payload) > max_payload_len: payload = payload[len(payload)-max_payload_len:].lstrip('0') return _dec_from_triple(self._sign, payload, self._exp, True) @@ -1638,11 +1611,11 @@ return Decimal(self) # if self is zero then exponent should be between Etiny and - # Emax if _clamp==0, and between Etiny and Etop if _clamp==1. + # Emax if clamp==0, and between Etiny and Etop if clamp==1. Etiny = context.Etiny() Etop = context.Etop() if not self: - exp_max = [context.Emax, Etop][context._clamp] + exp_max = [context.Emax, Etop][context.clamp] new_exp = min(max(self._exp, Etiny), exp_max) if new_exp != self._exp: context._raise_error(Clamped) @@ -1702,8 +1675,8 @@ if self_is_subnormal: context._raise_error(Subnormal) - # fold down if _clamp == 1 and self has too few digits - if context._clamp == 1 and self._exp > Etop: + # fold down if clamp == 1 and self has too few digits + if context.clamp == 1 and self._exp > Etop: context._raise_error(Clamped) self_padded = self._int + '0'*(self._exp - Etop) return _dec_from_triple(self._sign, self_padded, Etop) @@ -2451,7 +2424,7 @@ if not dup: return _dec_from_triple(dup._sign, '0', 0) - exp_max = [context.Emax, context.Etop()][context._clamp] + exp_max = [context.Emax, context.Etop()][context.clamp] end = len(dup._int) exp = dup._exp while dup._int[end-1] == '0' and exp < exp_max: @@ -3828,13 +3801,13 @@ Emax - Maximum exponent capitals - If 1, 1*10^1 is printed as 1E+1. If 0, printed as 1e1 - _clamp - If 1, change exponents if too high (Default 0) + clamp - If 1, change exponents if too high (Default 0) """ def __init__(self, prec=None, rounding=None, traps=None, flags=None, Emin=None, Emax=None, - capitals=None, _clamp=0, + capitals=None, clamp=None, _ignored_flags=None): if flags is None: flags = [] @@ -3855,7 +3828,8 @@ """Show the current context.""" s = [] s.append('Context(prec=%(prec)d, rounding=%(rounding)s, ' - 'Emin=%(Emin)d, Emax=%(Emax)d, capitals=%(capitals)d' + 'Emin=%(Emin)d, Emax=%(Emax)d, capitals=%(capitals)d, ' + 'clamp=%(clamp)d' % vars(self)) names = [f.__name__ for f, v in self.flags.items() if v] s.append('flags=[' + ', '.join(names) + ']') @@ -3872,23 +3846,45 @@ """Returns a shallow copy from self.""" nc = Context(self.prec, self.rounding, self.traps, self.flags, self.Emin, self.Emax, - self.capitals, self._clamp, self._ignored_flags) + self.capitals, self.clamp, self._ignored_flags) return nc def copy(self): """Returns a deep copy from self.""" nc = Context(self.prec, self.rounding, self.traps.copy(), self.flags.copy(), self.Emin, self.Emax, - self.capitals, self._clamp, self._ignored_flags) + self.capitals, self.clamp, self._ignored_flags) return nc __copy__ = copy + # _clamp is provided for backwards compatibility with third-party + # code. May be removed in Python >= 3.3. + def _get_clamp(self): + "_clamp mirrors the clamp attribute. Its use is deprecated." + import warnings + warnings.warn('Use of the _clamp attribute is deprecated. ' + 'Please use clamp instead.', + DeprecationWarning) + return self.clamp + + def _set_clamp(self, clamp): + "_clamp mirrors the clamp attribute. Its use is deprecated." + import warnings + warnings.warn('Use of the _clamp attribute is deprecated. ' + 'Please use clamp instead.', + DeprecationWarning) + self.clamp = clamp + + # don't bother with _del_clamp; no sane 3rd party code should + # be deleting the _clamp attribute + _clamp = property(_get_clamp, _set_clamp) + def _raise_error(self, condition, explanation = None, *args): """Handles an error If the flag is in _ignored_flags, returns the default response. Otherwise, it sets the flag, then, if the corresponding - trap_enabler is set, it reaises the exception. Otherwise, it returns + trap_enabler is set, it reraises the exception. Otherwise, it returns the default value after setting the flag. """ error = _condition_map.get(condition, condition) @@ -3965,7 +3961,7 @@ "permitted.") d = Decimal(num, context=self) - if d._isnan() and len(d._int) > self.prec - self._clamp: + if d._isnan() and len(d._int) > self.prec - self.clamp: return self._raise_error(ConversionSyntax, "diagnostic info too long in NaN") return d._fix(self) @@ -5875,7 +5871,8 @@ flags=[], Emax=999999999, Emin=-999999999, - capitals=1 + capitals=1, + clamp=0 ) # Pre-made alternate contexts offered by the specification @@ -6194,6 +6191,17 @@ # _SignedInfinity[sign] is infinity w/ that sign _SignedInfinity = (_Infinity, _NegativeInfinity) +# Constants related to the hash implementation; hash(x) is based +# on the reduction of x modulo _PyHASH_MODULUS +import sys +_PyHASH_MODULUS = sys.hash_info.modulus +# hash values to use for positive and negative infinities, and nans +_PyHASH_INF = sys.hash_info.inf +_PyHASH_NAN = sys.hash_info.nan +del sys + +# _PyHASH_10INV is the inverse of 10 modulo the prime _PyHASH_MODULUS +_PyHASH_10INV = pow(10, _PyHASH_MODULUS - 2, _PyHASH_MODULUS) if __name__ == '__main__': Modified: python/branches/py3k-jit/Lib/distutils/log.py ============================================================================== --- python/branches/py3k-jit/Lib/distutils/log.py (original) +++ python/branches/py3k-jit/Lib/distutils/log.py Tue May 25 03:17:49 2010 @@ -27,6 +27,10 @@ stream = sys.stderr else: stream = sys.stdout + if stream.errors == 'strict': + # emulate backslashreplace error handler + encoding = stream.encoding + msg = msg.encode(encoding, "backslashreplace").decode(encoding) stream.write('%s\n' % msg) stream.flush() Modified: python/branches/py3k-jit/Lib/encodings/utf_16.py ============================================================================== --- python/branches/py3k-jit/Lib/encodings/utf_16.py (original) +++ python/branches/py3k-jit/Lib/encodings/utf_16.py Tue May 25 03:17:49 2010 @@ -103,17 +103,23 @@ class StreamWriter(codecs.StreamWriter): def __init__(self, stream, errors='strict'): - self.bom_written = False codecs.StreamWriter.__init__(self, stream, errors) + self.encoder = None + + def reset(self): + codecs.StreamWriter.reset(self) + self.encoder = None def encode(self, input, errors='strict'): - self.bom_written = True - result = codecs.utf_16_encode(input, errors) - if sys.byteorder == 'little': - self.encode = codecs.utf_16_le_encode + if self.encoder is None: + result = codecs.utf_16_encode(input, errors) + if sys.byteorder == 'little': + self.encoder = codecs.utf_16_le_encode + else: + self.encoder = codecs.utf_16_be_encode + return result else: - self.encode = codecs.utf_16_be_encode - return result + return self.encoder(input, errors) class StreamReader(codecs.StreamReader): Modified: python/branches/py3k-jit/Lib/encodings/utf_32.py ============================================================================== --- python/branches/py3k-jit/Lib/encodings/utf_32.py (original) +++ python/branches/py3k-jit/Lib/encodings/utf_32.py Tue May 25 03:17:49 2010 @@ -98,17 +98,23 @@ class StreamWriter(codecs.StreamWriter): def __init__(self, stream, errors='strict'): - self.bom_written = False + self.encoder = None codecs.StreamWriter.__init__(self, stream, errors) + def reset(self): + codecs.StreamWriter.reset(self) + self.encoder = None + def encode(self, input, errors='strict'): - self.bom_written = True - result = codecs.utf_32_encode(input, errors) - if sys.byteorder == 'little': - self.encode = codecs.utf_32_le_encode + if self.encoder is None: + result = codecs.utf_32_encode(input, errors) + if sys.byteorder == 'little': + self.encoder = codecs.utf_32_le_encode + else: + self.encoder = codecs.utf_32_be_encode + return result else: - self.encode = codecs.utf_32_be_encode - return result + return self.encoder(input, errors) class StreamReader(codecs.StreamReader): Modified: python/branches/py3k-jit/Lib/fractions.py ============================================================================== --- python/branches/py3k-jit/Lib/fractions.py (original) +++ python/branches/py3k-jit/Lib/fractions.py Tue May 25 03:17:49 2010 @@ -8,6 +8,7 @@ import numbers import operator import re +import sys __all__ = ['Fraction', 'gcd'] @@ -23,6 +24,12 @@ a, b = b, a%b return a +# Constants related to the hash implementation; hash(x) is based +# on the reduction of x modulo the prime _PyHASH_MODULUS. +_PyHASH_MODULUS = sys.hash_info.modulus +# Value to be used for rationals that reduce to infinity modulo +# _PyHASH_MODULUS. +_PyHASH_INF = sys.hash_info.inf _RATIONAL_FORMAT = re.compile(r""" \A\s* # optional whitespace at the start, then @@ -528,16 +535,22 @@ """ # XXX since this method is expensive, consider caching the result - if self._denominator == 1: - # Get integers right. - return hash(self._numerator) - # Expensive check, but definitely correct. - if self == float(self): - return hash(float(self)) + + # In order to make sure that the hash of a Fraction agrees + # with the hash of a numerically equal integer, float or + # Decimal instance, we follow the rules for numeric hashes + # outlined in the documentation. (See library docs, 'Built-in + # Types'). + + # dinv is the inverse of self._denominator modulo the prime + # _PyHASH_MODULUS, or 0 if self._denominator is divisible by + # _PyHASH_MODULUS. + dinv = pow(self._denominator, _PyHASH_MODULUS - 2, _PyHASH_MODULUS) + if not dinv: + hash_ = _PyHASH_INF else: - # Use tuple's hash to avoid a high collision rate on - # simple fractions. - return hash((self._numerator, self._denominator)) + hash_ = abs(self._numerator) * dinv % _PyHASH_MODULUS + return hash_ if self >= 0 else -hash_ def __eq__(a, b): """a == b""" Modified: python/branches/py3k-jit/Lib/functools.py ============================================================================== --- python/branches/py3k-jit/Lib/functools.py (original) +++ python/branches/py3k-jit/Lib/functools.py Tue May 25 03:17:49 2010 @@ -51,7 +51,7 @@ assigned=assigned, updated=updated) def total_ordering(cls): - 'Class decorator that fills-in missing ordering methods' + """Class decorator that fills in missing ordering methods""" convert = { '__lt__': [('__gt__', lambda self, other: other < self), ('__le__', lambda self, other: not other < self), @@ -78,7 +78,7 @@ return cls def cmp_to_key(mycmp): - 'Convert a cmp= function into a key= function' + """Convert a cmp= function into a key= function""" class K(object): def __init__(self, obj, *args): self.obj = obj Modified: python/branches/py3k-jit/Lib/importlib/_bootstrap.py ============================================================================== --- python/branches/py3k-jit/Lib/importlib/_bootstrap.py (original) +++ python/branches/py3k-jit/Lib/importlib/_bootstrap.py Tue May 25 03:17:49 2010 @@ -494,8 +494,16 @@ if ext_type == imp.PY_COMPILED: # We don't really care what the extension on self._base_path is, # as long as it has exactly one dot. - bytecode_path = imp.cache_from_source(self._base_path + '.py') - return (bytecode_path if _path_exists(bytecode_path) else None) + source_path = self._base_path + '.py' + pycache_path = imp.cache_from_source(source_path) + legacy_path = self._base_path + '.pyc' + # The rule is: if the source file exists, then Python always uses + # the __pycache__/foo..pyc file. If the source file does not + # exist, then Python uses the legacy path. + pyc_path = (pycache_path + if _path_exists(source_path) + else legacy_path) + return (pyc_path if _path_exists(pyc_path) else None) return super()._find_path(ext_type) @_check_name Modified: python/branches/py3k-jit/Lib/importlib/test/source/test_file_loader.py ============================================================================== --- python/branches/py3k-jit/Lib/importlib/test/source/test_file_loader.py (original) +++ python/branches/py3k-jit/Lib/importlib/test/source/test_file_loader.py Tue May 25 03:17:49 2010 @@ -10,6 +10,8 @@ import sys import unittest +from test.support import make_legacy_pyc + class SimpleTest(unittest.TestCase): @@ -136,6 +138,7 @@ file.write(new_bc) if del_source: os.unlink(mapping[name]) + make_legacy_pyc(mapping[name]) return bytecode_path @source_util.writes_bytecode_files Modified: python/branches/py3k-jit/Lib/lib2to3/refactor.py ============================================================================== --- python/branches/py3k-jit/Lib/lib2to3/refactor.py (original) +++ python/branches/py3k-jit/Lib/lib2to3/refactor.py Tue May 25 03:17:49 2010 @@ -564,7 +564,9 @@ This is necessary to get correct line number / offset information in the parser diagnostics and embedded into the parse tree. """ - return self.driver.parse_tokens(self.wrap_toks(block, lineno, indent)) + tree = self.driver.parse_tokens(self.wrap_toks(block, lineno, indent)) + tree.future_features = frozenset() + return tree def wrap_toks(self, block, lineno, indent): """Wraps a tokenize stream to systematically modify start/end.""" Modified: python/branches/py3k-jit/Lib/linecache.py ============================================================================== --- python/branches/py3k-jit/Lib/linecache.py (original) +++ python/branches/py3k-jit/Lib/linecache.py Tue May 25 03:17:49 2010 @@ -73,13 +73,13 @@ if filename in cache: del cache[filename] - if not filename or filename[0] + filename[-1] == '<>': + if not filename or (filename.startswith('<') and filename.endswith('>')): return [] fullname = filename try: stat = os.stat(fullname) - except os.error as msg: + except OSError: basename = filename # Try for a __loader__, if available @@ -114,20 +114,23 @@ fullname = os.path.join(dirname, basename) except (TypeError, AttributeError): # Not sufficiently string-like to do anything useful with. + continue + try: + stat = os.stat(fullname) + break + except os.error: pass - else: - try: - stat = os.stat(fullname) - break - except os.error: - pass else: - # No luck return [] - with open(fullname, 'rb') as fp: - coding, line = tokenize.detect_encoding(fp.readline) - with open(fullname, 'r', encoding=coding) as fp: - lines = fp.readlines() + try: + with open(fullname, 'rb') as fp: + coding, line = tokenize.detect_encoding(fp.readline) + with open(fullname, 'r', encoding=coding) as fp: + lines = fp.readlines() + except IOError: + pass + if lines and not lines[-1].endswith('\n'): + lines[-1] += '\n' size, mtime = stat.st_size, stat.st_mtime cache[filename] = size, mtime, lines, fullname return lines Modified: python/branches/py3k-jit/Lib/os.py ============================================================================== --- python/branches/py3k-jit/Lib/os.py (original) +++ python/branches/py3k-jit/Lib/os.py Tue May 25 03:17:49 2010 @@ -355,7 +355,11 @@ return last_exc = saved_exc = None saved_tb = None - for dir in get_exec_path(env): + path_list = get_exec_path(env) + if name != 'nt': + file = fsencode(file) + path_list = map(fsencode, path_list) + for dir in path_list: fullname = path.join(dir, file) try: exec_func(fullname, *argrest) @@ -380,7 +384,30 @@ """ if env is None: env = environ - return env.get('PATH', defpath).split(pathsep) + + try: + path_list = env.get('PATH') + except TypeError: + path_list = None + + if supports_bytes_environ: + try: + path_listb = env[b'PATH'] + except (KeyError, TypeError): + pass + else: + if path_list is not None: + raise ValueError( + "env cannot contain 'PATH' and b'PATH' keys") + path_list = path_listb + + if path_list is not None and isinstance(path_list, bytes): + path_list = path_list.decode(sys.getfilesystemencoding(), + 'surrogateescape') + + if path_list is None: + path_list = defpath + return path_list.split(pathsep) # Change environ to automatically call putenv(), unsetenv if they exist. @@ -482,9 +509,11 @@ The optional second argument can specify an alternate default. key, default and the result are str.""" return environ.get(key, default) -__all__.append("getenv") -if name not in ('os2', 'nt'): +supports_bytes_environ = name not in ('os2', 'nt') +__all__.extend(("getenv", "supports_bytes_environ")) + +if supports_bytes_environ: def _check_bytes(value): if not isinstance(value, bytes): raise TypeError("bytes expected, not %s" % type(value).__name__) Modified: python/branches/py3k-jit/Lib/pipes.py ============================================================================== --- python/branches/py3k-jit/Lib/pipes.py (original) +++ python/branches/py3k-jit/Lib/pipes.py Tue May 25 03:17:49 2010 @@ -249,11 +249,11 @@ # Reliably quote a string as a single argument for /bin/sh -_safechars = string.ascii_letters + string.digits + '!@%_-+=:,./' # Safe unquoted -_funnychars = '"`$\\' # Unsafe inside "double quotes" +# Safe unquoted +_safechars = frozenset(string.ascii_letters + string.digits + '@%_-+=:,./') def quote(file): - ''' return a shell-escaped version of the file string ''' + """Return a shell-escaped version of the file string.""" for c in file: if c not in _safechars: break @@ -261,11 +261,6 @@ if not file: return "''" return file - if '\'' not in file: - return '\'' + file + '\'' - res = '' - for c in file: - if c in _funnychars: - c = '\\' + c - res = res + c - return '"' + res + '"' + # use single quotes, and put single quotes into double quotes + # the string $'b is then quoted as '$'"'"'b' + return "'" + file.replace("'", "'\"'\"'") + "'" Modified: python/branches/py3k-jit/Lib/ssl.py ============================================================================== --- python/branches/py3k-jit/Lib/ssl.py (original) +++ python/branches/py3k-jit/Lib/ssl.py Tue May 25 03:17:49 2010 @@ -63,6 +63,7 @@ from _ssl import CERT_NONE, CERT_OPTIONAL, CERT_REQUIRED from _ssl import (PROTOCOL_SSLv2, PROTOCOL_SSLv3, PROTOCOL_SSLv23, PROTOCOL_TLSv1) +from _ssl import OP_ALL, OP_NO_SSLv2, OP_NO_SSLv3, OP_NO_TLSv1 from _ssl import RAND_status, RAND_egd, RAND_add from _ssl import ( SSL_ERROR_ZERO_RETURN, Modified: python/branches/py3k-jit/Lib/subprocess.py ============================================================================== --- python/branches/py3k-jit/Lib/subprocess.py (original) +++ python/branches/py3k-jit/Lib/subprocess.py Tue May 25 03:17:49 2010 @@ -843,7 +843,7 @@ # Process startup details if startupinfo is None: startupinfo = STARTUPINFO() - if None not in (p2cread, c2pwrite, errwrite): + if -1 not in (p2cread, c2pwrite, errwrite): startupinfo.dwFlags |= _subprocess.STARTF_USESTDHANDLES startupinfo.hStdInput = p2cread startupinfo.hStdOutput = c2pwrite @@ -1096,15 +1096,14 @@ for k, v in env.items()] else: env_list = None # Use execv instead of execve. + executable = os.fsencode(executable) if os.path.dirname(executable): - executable_list = (os.fsencode(executable),) + executable_list = (executable,) else: # This matches the behavior of os._execvpe(). - path_list = os.get_exec_path(env) - executable_list = (os.path.join(dir, executable) - for dir in path_list) - executable_list = tuple(os.fsencode(exe) - for exe in executable_list) + executable_list = tuple( + os.path.join(os.fsencode(dir), executable) + for dir in os.get_exec_path(env)) self.pid = _posixsubprocess.fork_exec( args, executable_list, close_fds, cwd, env_list, Modified: python/branches/py3k-jit/Lib/sysconfig.py ============================================================================== --- python/branches/py3k-jit/Lib/sysconfig.py (original) +++ python/branches/py3k-jit/Lib/sysconfig.py Tue May 25 03:17:49 2010 @@ -47,10 +47,10 @@ 'data' : '{base}', }, 'os2_home': { - 'stdlib': '{userbase}/lib/python/{py_version_short}', - 'platstdlib': '{userbase}/lib/python/{py_version_short}', - 'purelib': '{userbase}/lib/python/{py_version_short}/site-packages', - 'platlib': '{userbase}/lib/python/{py_version_short}/site-packages', + 'stdlib': '{userbase}/lib/python{py_version_short}', + 'platstdlib': '{userbase}/lib/python{py_version_short}', + 'purelib': '{userbase}/lib/python{py_version_short}/site-packages', + 'platlib': '{userbase}/lib/python{py_version_short}/site-packages', 'include': '{userbase}/include/python{py_version_short}', 'scripts': '{userbase}/bin', 'data' : '{userbase}', @@ -65,10 +65,10 @@ 'data' : '{userbase}', }, 'posix_user': { - 'stdlib': '{userbase}/lib/python/{py_version_short}', - 'platstdlib': '{userbase}/lib/python/{py_version_short}', - 'purelib': '{userbase}/lib/python/{py_version_short}/site-packages', - 'platlib': '{userbase}/lib/python/{py_version_short}/site-packages', + 'stdlib': '{userbase}/lib/python{py_version_short}', + 'platstdlib': '{userbase}/lib/python{py_version_short}', + 'purelib': '{userbase}/lib/python{py_version_short}/site-packages', + 'platlib': '{userbase}/lib/python{py_version_short}/site-packages', 'include': '{userbase}/include/python{py_version_short}', 'scripts': '{userbase}/bin', 'data' : '{userbase}', Modified: python/branches/py3k-jit/Lib/tabnanny.py ============================================================================== --- python/branches/py3k-jit/Lib/tabnanny.py (original) +++ python/branches/py3k-jit/Lib/tabnanny.py Tue May 25 03:17:49 2010 @@ -93,8 +93,11 @@ check(fullname) return + with open(file, 'rb') as f: + encoding, lines = tokenize.detect_encoding(f.readline) + try: - f = open(file) + f = open(file, encoding=encoding) except IOError as msg: errprint("%r: I/O Error: %s" % (file, msg)) return Modified: python/branches/py3k-jit/Lib/test/regrtest.py ============================================================================== --- python/branches/py3k-jit/Lib/test/regrtest.py (original) +++ python/branches/py3k-jit/Lib/test/regrtest.py Tue May 25 03:17:49 2010 @@ -258,6 +258,8 @@ on the command line. """ + replace_stdout() + support.record_original_stdout(sys.stdout) try: opts, args = getopt.getopt(sys.argv[1:], 'hvqxsSrf:lu:t:TD:NLR:FwWM:nj:', @@ -376,7 +378,6 @@ elif o in ('-j', '--multiprocess'): use_mp = int(a) elif o == '--slaveargs': - replace_stdout() args, kwargs = json.loads(a) try: result = runtest(*args, **kwargs) @@ -515,8 +516,6 @@ else: tests = iter(selected) - replace_stdout() - if use_mp: try: from threading import Thread Modified: python/branches/py3k-jit/Lib/test/test_argparse.py ============================================================================== --- python/branches/py3k-jit/Lib/test/test_argparse.py (original) +++ python/branches/py3k-jit/Lib/test/test_argparse.py Tue May 25 03:17:49 2010 @@ -3688,6 +3688,25 @@ ''' version = '' +class TestHelpVersionAction(HelpTestCase): + """Test the default help for the version action""" + + parser_signature = Sig(prog='PROG', description='description') + argument_signatures = [Sig('-V', '--version', action='version', version='3.6')] + argument_group_signatures = [] + usage = '''\ + usage: PROG [-h] [-V] + ''' + help = usage + '''\ + + description + + optional arguments: + -h, --help show this help message and exit + -V, --version show program's version number and exit + ''' + version = '' + # ===================================== # Optional/Positional constructor tests # ===================================== Modified: python/branches/py3k-jit/Lib/test/test_asyncore.py ============================================================================== --- python/branches/py3k-jit/Lib/test/test_asyncore.py (original) +++ python/branches/py3k-jit/Lib/test/test_asyncore.py Tue May 25 03:17:49 2010 @@ -6,6 +6,7 @@ import sys import time import warnings +import errno from test import support from test.support import TESTFN, run_unittest, unlink @@ -324,6 +325,14 @@ self.assertTrue(len(w) == 1) self.assertTrue(issubclass(w[0].category, DeprecationWarning)) + def test_strerror(self): + # refers to bug #8573 + err = asyncore._strerror(errno.EPERM) + if hasattr(os, 'strerror'): + self.assertEqual(err, os.strerror(errno.EPERM)) + err = asyncore._strerror(-1) + self.assertTrue("unknown error" in err.lower()) + class dispatcherwithsend_noread(asyncore.dispatcher_with_send): def readable(self): Modified: python/branches/py3k-jit/Lib/test/test_codecs.py ============================================================================== --- python/branches/py3k-jit/Lib/test/test_codecs.py (original) +++ python/branches/py3k-jit/Lib/test/test_codecs.py Tue May 25 03:17:49 2010 @@ -1594,6 +1594,62 @@ b"\xe4\xeb\xef\xf6\xfc") +class BomTest(unittest.TestCase): + def test_seek0(self): + data = "1234567890" + tests = ("utf-16", + "utf-16-le", + "utf-16-be", + "utf-32", + "utf-32-le", + "utf-32-be") + for encoding in tests: + # Check if the BOM is written only once + with codecs.open(support.TESTFN, 'w+', encoding=encoding) as f: + f.write(data) + f.write(data) + f.seek(0) + self.assertEquals(f.read(), data * 2) + f.seek(0) + self.assertEquals(f.read(), data * 2) + + # Check that the BOM is written after a seek(0) + with codecs.open(support.TESTFN, 'w+', encoding=encoding) as f: + f.write(data[0]) + self.assertNotEquals(f.tell(), 0) + f.seek(0) + f.write(data) + f.seek(0) + self.assertEquals(f.read(), data) + + # (StreamWriter) Check that the BOM is written after a seek(0) + with codecs.open(support.TESTFN, 'w+', encoding=encoding) as f: + f.writer.write(data[0]) + self.assertNotEquals(f.writer.tell(), 0) + f.writer.seek(0) + f.writer.write(data) + f.seek(0) + self.assertEquals(f.read(), data) + + # Check that the BOM is not written after a seek() at a position + # different than the start + with codecs.open(support.TESTFN, 'w+', encoding=encoding) as f: + f.write(data) + f.seek(f.tell()) + f.write(data) + f.seek(0) + self.assertEquals(f.read(), data * 2) + + # (StreamWriter) Check that the BOM is not written after a seek() + # at a position different than the start + with codecs.open(support.TESTFN, 'w+', encoding=encoding) as f: + f.writer.write(data) + f.writer.seek(f.writer.tell()) + f.writer.write(data) + f.seek(0) + self.assertEquals(f.read(), data * 2) + + def test_main(): support.run_unittest( UTF32Test, @@ -1621,6 +1677,7 @@ WithStmtTest, TypesTest, SurrogateEscapeTest, + BomTest, ) Modified: python/branches/py3k-jit/Lib/test/test_collections.py ============================================================================== --- python/branches/py3k-jit/Lib/test/test_collections.py (original) +++ python/branches/py3k-jit/Lib/test/test_collections.py Tue May 25 03:17:49 2010 @@ -1,6 +1,6 @@ """Unit tests for collections.py.""" -import unittest, doctest +import unittest, doctest, operator import inspect from test import support from collections import namedtuple, Counter, OrderedDict @@ -246,6 +246,37 @@ self.assertNotIsInstance(C(), abc) self.assertFalse(issubclass(C, abc)) + def validate_comparison(self, instance): + ops = ['lt', 'gt', 'le', 'ge', 'ne', 'or', 'and', 'xor', 'sub'] + operators = {} + for op in ops: + name = '__' + op + '__' + operators[name] = getattr(operator, name) + + class Other: + def __init__(self): + self.right_side = False + def __eq__(self, other): + self.right_side = True + return True + __lt__ = __eq__ + __gt__ = __eq__ + __le__ = __eq__ + __ge__ = __eq__ + __ne__ = __eq__ + __ror__ = __eq__ + __rand__ = __eq__ + __rxor__ = __eq__ + __rsub__ = __eq__ + + for name, op in operators.items(): + if not hasattr(instance, name): + continue + other = Other() + op(instance, other) + self.assertTrue(other.right_side,'Right side not called for %s.%s' + % (type(instance), name)) + class TestOneTrickPonyABCs(ABCTestCase): def test_Hashable(self): @@ -420,6 +451,14 @@ self.assertIsInstance(sample(), Set) self.assertTrue(issubclass(sample, Set)) self.validate_abstract_methods(Set, '__contains__', '__iter__', '__len__') + class MySet(Set): + def __contains__(self, x): + return False + def __len__(self): + return 0 + def __iter__(self): + return iter([]) + self.validate_comparison(MySet()) def test_hash_Set(self): class OneTwoThreeSet(Set): @@ -483,6 +522,14 @@ self.assertTrue(issubclass(sample, Mapping)) self.validate_abstract_methods(Mapping, '__contains__', '__iter__', '__len__', '__getitem__') + class MyMapping(collections.Mapping): + def __len__(self): + return 0 + def __getitem__(self, i): + raise IndexError + def __iter__(self): + return iter(()) + self.validate_comparison(MyMapping()) def test_MutableMapping(self): for sample in [dict]: Modified: python/branches/py3k-jit/Lib/test/test_complex.py ============================================================================== --- python/branches/py3k-jit/Lib/test/test_complex.py (original) +++ python/branches/py3k-jit/Lib/test/test_complex.py Tue May 25 03:17:49 2010 @@ -110,12 +110,18 @@ self.assertRaises(TypeError, complex.__floordiv__, 3+0j, 0+0j) def test_richcompare(self): - self.assertRaises(OverflowError, complex.__eq__, 1+1j, 1<<10000) + self.assertIs(complex.__eq__(1+1j, 1<<10000), False) self.assertIs(complex.__lt__(1+1j, None), NotImplemented) self.assertIs(complex.__eq__(1+1j, 1+1j), True) self.assertIs(complex.__eq__(1+1j, 2+2j), False) self.assertIs(complex.__ne__(1+1j, 1+1j), False) self.assertIs(complex.__ne__(1+1j, 2+2j), True) + for i in range(1, 100): + f = i / 100.0 + self.assertIs(complex.__eq__(f+0j, f), True) + self.assertIs(complex.__ne__(f+0j, f), False) + self.assertIs(complex.__eq__(complex(f, f), f), False) + self.assertIs(complex.__ne__(complex(f, f), f), True) self.assertIs(complex.__lt__(1+1j, 2+2j), NotImplemented) self.assertIs(complex.__le__(1+1j, 2+2j), NotImplemented) self.assertIs(complex.__gt__(1+1j, 2+2j), NotImplemented) @@ -129,6 +135,23 @@ self.assertIs(operator.ne(1+1j, 1+1j), False) self.assertIs(operator.ne(1+1j, 2+2j), True) + def test_richcompare_boundaries(self): + def check(n, deltas, is_equal, imag = 0.0): + for delta in deltas: + i = n + delta + z = complex(i, imag) + self.assertIs(complex.__eq__(z, i), is_equal(delta)) + self.assertIs(complex.__ne__(z, i), not is_equal(delta)) + # For IEEE-754 doubles the following should hold: + # x in [2 ** (52 + i), 2 ** (53 + i + 1)] -> x mod 2 ** i == 0 + # where the interval is representable, of course. + for i in range(1, 10): + pow = 52 + i + mult = 2 ** i + check(2 ** pow, range(1, 101), lambda delta: delta % mult == 0) + check(2 ** pow, range(1, 101), lambda delta: False, float(i)) + check(2 ** 53, range(-100, 0), lambda delta: True) + def test_mod(self): # % is no longer supported on complex numbers self.assertRaises(TypeError, (1+1j).__mod__, 0+0j) Modified: python/branches/py3k-jit/Lib/test/test_decimal.py ============================================================================== --- python/branches/py3k-jit/Lib/test/test_decimal.py (original) +++ python/branches/py3k-jit/Lib/test/test_decimal.py Tue May 25 03:17:49 2010 @@ -27,11 +27,13 @@ import math import os, sys import operator +import warnings import pickle, copy import unittest from decimal import * import numbers from test.support import run_unittest, run_doctest, is_resource_enabled +from test.support import check_warnings import random try: import threading @@ -412,7 +414,7 @@ def change_max_exponent(self, exp): self.context.Emax = exp def change_clamp(self, clamp): - self.context._clamp = clamp + self.context.clamp = clamp @@ -1815,6 +1817,26 @@ self.assertNotEqual(id(c.flags), id(d.flags)) self.assertNotEqual(id(c.traps), id(d.traps)) + def test__clamp(self): + # In Python 3.2, the private attribute `_clamp` was made + # public (issue 8540), with the old `_clamp` becoming a + # property wrapping `clamp`. For the duration of Python 3.2 + # only, the attribute should be gettable/settable via both + # `clamp` and `_clamp`; in Python 3.3, `_clamp` should be + # removed. + c = Context(clamp = 0) + self.assertEqual(c.clamp, 0) + + with check_warnings(("", DeprecationWarning)): + c._clamp = 1 + self.assertEqual(c.clamp, 1) + with check_warnings(("", DeprecationWarning)): + self.assertEqual(c._clamp, 1) + c.clamp = 0 + self.assertEqual(c.clamp, 0) + with check_warnings(("", DeprecationWarning)): + self.assertEqual(c._clamp, 0) + def test_abs(self): c = Context() d = c.abs(Decimal(-1)) Modified: python/branches/py3k-jit/Lib/test/test_float.py ============================================================================== --- python/branches/py3k-jit/Lib/test/test_float.py (original) +++ python/branches/py3k-jit/Lib/test/test_float.py Tue May 25 03:17:49 2010 @@ -914,15 +914,6 @@ self.assertFalse(NAN.is_inf()) self.assertFalse((0.).is_inf()) - def test_hash_inf(self): - # the actual values here should be regarded as an - # implementation detail, but they need to be - # identical to those used in the Decimal module. - self.assertEqual(hash(float('inf')), 314159) - self.assertEqual(hash(float('-inf')), -271828) - self.assertEqual(hash(float('nan')), 0) - - fromHex = float.fromhex toHex = float.hex class HexFloatTestCase(unittest.TestCase): Modified: python/branches/py3k-jit/Lib/test/test_gdb.py ============================================================================== --- python/branches/py3k-jit/Lib/test/test_gdb.py (original) +++ python/branches/py3k-jit/Lib/test/test_gdb.py Tue May 25 03:17:49 2010 @@ -8,6 +8,7 @@ import subprocess import sys import unittest +import locale from test.support import run_unittest, findfile @@ -177,7 +178,7 @@ def assertGdbRepr(self, val, exp_repr=None, cmds_after_breakpoint=None): # Ensure that gdb's rendering of the value in a debugged process # matches repr(value) in this process: - gdb_repr, gdb_output = self.get_gdb_repr('id(' + repr(val) + ')', + gdb_repr, gdb_output = self.get_gdb_repr('id(' + ascii(val) + ')', cmds_after_breakpoint) if not exp_repr: exp_repr = repr(val) @@ -226,31 +227,35 @@ def test_strings(self): 'Verify the pretty-printing of unicode strings' + encoding = locale.getpreferredencoding() + def check_repr(text): + try: + text.encode(encoding) + printable = True + except UnicodeEncodeError: + self.assertGdbRepr(text, ascii(text)) + else: + self.assertGdbRepr(text) + self.assertGdbRepr('') self.assertGdbRepr('And now for something hopefully the same') self.assertGdbRepr('string with embedded NUL here \0 and then some more text') # Test printing a single character: # U+2620 SKULL AND CROSSBONES - self.assertGdbRepr('\u2620') + check_repr('\u2620') # Test printing a Japanese unicode string # (I believe this reads "mojibake", using 3 characters from the CJK # Unified Ideographs area, followed by U+3051 HIRAGANA LETTER KE) - self.assertGdbRepr('\u6587\u5b57\u5316\u3051') + check_repr('\u6587\u5b57\u5316\u3051') # Test a character outside the BMP: # U+1D121 MUSICAL SYMBOL C CLEF # This is: # UTF-8: 0xF0 0x9D 0x84 0xA1 # UTF-16: 0xD834 0xDD21 - if sys.maxunicode == 0x10FFFF: - # wide unicode: - self.assertGdbRepr(chr(0x1D121)) - else: - # narrow unicode: - self.assertGdbRepr(chr(0x1D121), - "'\\U0000d834\\U0000dd21'") + check_repr(chr(0x1D121)) def test_tuples(self): 'Verify the pretty-printing of tuples' Modified: python/branches/py3k-jit/Lib/test/test_getargs2.py ============================================================================== --- python/branches/py3k-jit/Lib/test/test_getargs2.py (original) +++ python/branches/py3k-jit/Lib/test/test_getargs2.py Tue May 25 03:17:49 2010 @@ -252,24 +252,28 @@ getargs_keywords((1,2), 3, (4,(5,6)), (7,8,9), 10), (1, 2, 3, 4, 5, 6, 7, 8, 9, 10) ) + def test_mixed_args(self): # positional and keyword args self.assertEquals( getargs_keywords((1,2), 3, (4,(5,6)), arg4=(7,8,9), arg5=10), (1, 2, 3, 4, 5, 6, 7, 8, 9, 10) ) + def test_keyword_args(self): # all keywords self.assertEquals( getargs_keywords(arg1=(1,2), arg2=3, arg3=(4,(5,6)), arg4=(7,8,9), arg5=10), (1, 2, 3, 4, 5, 6, 7, 8, 9, 10) ) + def test_optional_args(self): # missing optional keyword args, skipping tuples self.assertEquals( getargs_keywords(arg1=(1,2), arg2=3, arg5=10), (1, 2, 3, -1, -1, -1, -1, -1, -1, 10) ) + def test_required_args(self): # required arg missing try: @@ -278,6 +282,7 @@ self.assertEquals(str(err), "Required argument 'arg2' (pos 2) not found") else: self.fail('TypeError should have been raised') + def test_too_many_args(self): try: getargs_keywords((1,2),3,(4,(5,6)),(7,8,9),10,111) @@ -285,6 +290,7 @@ self.assertEquals(str(err), "function takes at most 5 arguments (6 given)") else: self.fail('TypeError should have been raised') + def test_invalid_keyword(self): # extraneous keyword arg try: @@ -294,6 +300,14 @@ else: self.fail('TypeError should have been raised') + def test_surrogate_keyword(self): + try: + getargs_keywords((1,2), 3, (4,(5,6)), (7,8,9), **{'\uDC80': 10}) + except TypeError as err: + self.assertEquals(str(err), "'\udc80' is an invalid keyword argument for this function") + else: + self.fail('TypeError should have been raised') + def test_main(): tests = [Signed_TestCase, Unsigned_TestCase, Tuple_TestCase, Keywords_TestCase] try: Modified: python/branches/py3k-jit/Lib/test/test_import.py ============================================================================== --- python/branches/py3k-jit/Lib/test/test_import.py (original) +++ python/branches/py3k-jit/Lib/test/test_import.py Tue May 25 03:17:49 2010 @@ -142,7 +142,6 @@ self.assertIs(orig_path, new_os.path) self.assertIsNot(orig_getenv, new_os.getenv) - @unittest.expectedFailure # Issue 8727 is tracking the fix. def test_module_with_large_stack(self, module='longlist'): # Regression test for http://bugs.python.org/issue561858. filename = module + '.py' Modified: python/branches/py3k-jit/Lib/test/test_linecache.py ============================================================================== --- python/branches/py3k-jit/Lib/test/test_linecache.py (original) +++ python/branches/py3k-jit/Lib/test/test_linecache.py Tue May 25 03:17:49 2010 @@ -31,6 +31,11 @@ ''' +SOURCE_3 = ''' +def f(): + return 3''' # No ending newline + + class LineCacheTests(unittest.TestCase): def test_getline(self): @@ -63,6 +68,13 @@ empty = linecache.getlines('a/b/c/__init__.py') self.assertEquals(empty, []) + def test_no_ending_newline(self): + self.addCleanup(support.unlink, support.TESTFN) + with open(support.TESTFN, "w") as fp: + fp.write(SOURCE_3) + lines = linecache.getlines(support.TESTFN) + self.assertEqual(lines, ["\n", "def f():\n", " return 3\n"]) + def test_clearcache(self): cached = [] for entry in TESTS: @@ -81,39 +93,36 @@ def test_checkcache(self): getline = linecache.getline - try: - # Create a source file and cache its contents - source_name = support.TESTFN + '.py' - with open(source_name, 'w') as source: - source.write(SOURCE_1) - getline(source_name, 1) - - # Keep a copy of the old contents - source_list = [] - with open(source_name) as source: - for index, line in enumerate(source): - self.assertEquals(line, getline(source_name, index + 1)) - source_list.append(line) + # Create a source file and cache its contents + source_name = support.TESTFN + '.py' + self.addCleanup(support.unlink, source_name) + with open(source_name, 'w') as source: + source.write(SOURCE_1) + getline(source_name, 1) + + # Keep a copy of the old contents + source_list = [] + with open(source_name) as source: + for index, line in enumerate(source): + self.assertEquals(line, getline(source_name, index + 1)) + source_list.append(line) - with open(source_name, 'w') as source: - source.write(SOURCE_2) + with open(source_name, 'w') as source: + source.write(SOURCE_2) - # Try to update a bogus cache entry - linecache.checkcache('dummy') + # Try to update a bogus cache entry + linecache.checkcache('dummy') - # Check that the cache matches the old contents - for index, line in enumerate(source_list): + # Check that the cache matches the old contents + for index, line in enumerate(source_list): + self.assertEquals(line, getline(source_name, index + 1)) + + # Update the cache and check whether it matches the new source file + linecache.checkcache(source_name) + with open(source_name) as source: + for index, line in enumerate(source): self.assertEquals(line, getline(source_name, index + 1)) - - # Update the cache and check whether it matches the new source file - linecache.checkcache(source_name) - with open(source_name) as source: - for index, line in enumerate(source): - self.assertEquals(line, getline(source_name, index + 1)) - source_list.append(line) - - finally: - support.unlink(source_name) + source_list.append(line) def test_main(): support.run_unittest(LineCacheTests) Modified: python/branches/py3k-jit/Lib/test/test_os.py ============================================================================== --- python/branches/py3k-jit/Lib/test/test_os.py (original) +++ python/branches/py3k-jit/Lib/test/test_os.py Tue May 25 03:17:49 2010 @@ -370,7 +370,7 @@ def setUp(self): self.__save = dict(os.environ) - if os.name not in ('os2', 'nt'): + if os.supports_bytes_environ: self.__saveb = dict(os.environb) for key, value in self._reference().items(): os.environ[key] = value @@ -378,7 +378,7 @@ def tearDown(self): os.environ.clear() os.environ.update(self.__save) - if os.name not in ('os2', 'nt'): + if os.supports_bytes_environ: os.environb.clear() os.environb.update(self.__saveb) @@ -445,7 +445,21 @@ # Supplied PATH environment variable self.assertSequenceEqual(test_path, os.get_exec_path(test_env)) - @unittest.skipIf(sys.platform == "win32", "POSIX specific test") + if os.supports_bytes_environ: + # env cannot contain 'PATH' and b'PATH' keys + self.assertRaises(ValueError, + os.get_exec_path, {'PATH': '1', b'PATH': b'2'}) + + # bytes key and/or value + self.assertSequenceEqual(os.get_exec_path({b'PATH': b'abc'}), + ['abc']) + self.assertSequenceEqual(os.get_exec_path({b'PATH': 'abc'}), + ['abc']) + self.assertSequenceEqual(os.get_exec_path({'PATH': b'abc'}), + ['abc']) + + @unittest.skipUnless(os.supports_bytes_environ, + "os.environb required for this test.") def test_environb(self): # os.environ -> os.environb value = 'euro\u20ac' @@ -669,22 +683,54 @@ @unittest.skipUnless(hasattr(os, '_execvpe'), "No internal os._execvpe function to test.") - def test_internal_execvpe(self): - program_path = os.sep+'absolutepath' - program = 'executable' - fullpath = os.path.join(program_path, program) - arguments = ['progname', 'arg1', 'arg2'] + def _test_internal_execvpe(self, test_type): + program_path = os.sep + 'absolutepath' + if test_type is bytes: + program = b'executable' + fullpath = os.path.join(os.fsencode(program_path), program) + native_fullpath = fullpath + arguments = [b'progname', 'arg1', 'arg2'] + else: + program = 'executable' + arguments = ['progname', 'arg1', 'arg2'] + fullpath = os.path.join(program_path, program) + if os.name != "nt": + native_fullpath = os.fsencode(fullpath) + else: + native_fullpath = fullpath env = {'spam': 'beans'} + # test os._execvpe() with an absolute path with _execvpe_mockup() as calls: - self.assertRaises(RuntimeError, os._execvpe, fullpath, arguments) + self.assertRaises(RuntimeError, + os._execvpe, fullpath, arguments) self.assertEqual(len(calls), 1) self.assertEqual(calls[0], ('execv', fullpath, (arguments,))) + # test os._execvpe() with a relative path: + # os.get_exec_path() returns defpath with _execvpe_mockup(defpath=program_path) as calls: - self.assertRaises(OSError, os._execvpe, program, arguments, env=env) + self.assertRaises(OSError, + os._execvpe, program, arguments, env=env) self.assertEqual(len(calls), 1) - self.assertEqual(calls[0], ('execve', fullpath, (arguments, env))) + self.assertSequenceEqual(calls[0], + ('execve', native_fullpath, (arguments, env))) + + # test os._execvpe() with a relative path: + # os.get_exec_path() reads the 'PATH' variable + with _execvpe_mockup() as calls: + env_path = env.copy() + env_path['PATH'] = program_path + self.assertRaises(OSError, + os._execvpe, program, arguments, env=env_path) + self.assertEqual(len(calls), 1) + self.assertSequenceEqual(calls[0], + ('execve', native_fullpath, (arguments, env_path))) + + def test_internal_execvpe_str(self): + self._test_internal_execvpe(str) + if os.name != "nt": + self._test_internal_execvpe(bytes) class Win32ErrorTests(unittest.TestCase): Modified: python/branches/py3k-jit/Lib/test/test_pipes.py ============================================================================== --- python/branches/py3k-jit/Lib/test/test_pipes.py (original) +++ python/branches/py3k-jit/Lib/test/test_pipes.py Tue May 25 03:17:49 2010 @@ -70,9 +70,10 @@ self.assertEqual(open(TESTFN).read(), d) def testQuoting(self): - safeunquoted = string.ascii_letters + string.digits + '!@%_-+=:,./' - unsafe = '"`$\\' + safeunquoted = string.ascii_letters + string.digits + '@%_-+=:,./' + unsafe = '"`$\\!' + self.assertEqual(pipes.quote(''), "''") self.assertEqual(pipes.quote(safeunquoted), safeunquoted) self.assertEqual(pipes.quote('test file name'), "'test file name'") for u in unsafe: @@ -80,9 +81,7 @@ "'test%sname'" % u) for u in unsafe: self.assertEqual(pipes.quote("test%s'name'" % u), - '"test\\%s\'name\'"' % u) - - self.assertEqual(pipes.quote(''), "''") + "'test%s'\"'\"'name'\"'\"''" % u) def testRepr(self): t = pipes.Template() Modified: python/branches/py3k-jit/Lib/test/test_ssl.py ============================================================================== --- python/branches/py3k-jit/Lib/test/test_ssl.py (original) +++ python/branches/py3k-jit/Lib/test/test_ssl.py Tue May 25 03:17:49 2010 @@ -57,6 +57,14 @@ if support.verbose: sys.stdout.write(prefix + exc_format) +def can_clear_options(): + # 0.9.8m or higher + return ssl.OPENSSL_VERSION_INFO >= (0, 9, 8, 13, 15) + +def no_sslv2_implies_sslv3_hello(): + # 0.9.7h or higher + return ssl.OPENSSL_VERSION_INFO >= (0, 9, 7, 8, 15) + class BasicSocketTests(unittest.TestCase): @@ -189,6 +197,26 @@ with self.assertRaisesRegexp(ssl.SSLError, "No cipher can be selected"): ctx.set_ciphers("^$:,;?*'dorothyx") + def test_options(self): + ctx = ssl.SSLContext(ssl.PROTOCOL_TLSv1) + # OP_ALL is the default value + self.assertEqual(ssl.OP_ALL, ctx.options) + ctx.options |= ssl.OP_NO_SSLv2 + self.assertEqual(ssl.OP_ALL | ssl.OP_NO_SSLv2, + ctx.options) + ctx.options |= ssl.OP_NO_SSLv3 + self.assertEqual(ssl.OP_ALL | ssl.OP_NO_SSLv2 | ssl.OP_NO_SSLv3, + ctx.options) + if can_clear_options(): + ctx.options = (ctx.options & ~ssl.OP_NO_SSLv2) | ssl.OP_NO_TLSv1 + self.assertEqual(ssl.OP_ALL | ssl.OP_NO_TLSv1 | ssl.OP_NO_SSLv3, + ctx.options) + ctx.options = 0 + self.assertEqual(0, ctx.options) + else: + with self.assertRaises(ValueError): + ctx.options = 0 + def test_verify(self): ctx = ssl.SSLContext(ssl.PROTOCOL_TLSv1) # Default value @@ -445,12 +473,8 @@ def wrap_conn(self): try: - self.sslconn = ssl.wrap_socket(self.sock, server_side=True, - certfile=self.server.certificate, - ssl_version=self.server.protocol, - ca_certs=self.server.cacerts, - cert_reqs=self.server.certreqs, - ciphers=self.server.ciphers) + self.sslconn = self.server.context.wrap_socket( + self.sock, server_side=True) except ssl.SSLError: # XXX Various errors can have happened here, for example # a mismatching protocol version, an invalid certificate, @@ -462,7 +486,7 @@ self.close() return False else: - if self.server.certreqs == ssl.CERT_REQUIRED: + if self.server.context.verify_mode == ssl.CERT_REQUIRED: cert = self.sslconn.getpeercert() if support.verbose and self.server.chatty: sys.stdout.write(" client cert is " + pprint.pformat(cert) + "\n") @@ -542,19 +566,24 @@ # harness, we want to stop the server self.server.stop() - def __init__(self, certificate, ssl_version=None, + def __init__(self, certificate=None, ssl_version=None, certreqs=None, cacerts=None, chatty=True, connectionchatty=False, starttls_server=False, - ciphers=None): - if ssl_version is None: - ssl_version = ssl.PROTOCOL_TLSv1 - if certreqs is None: - certreqs = ssl.CERT_NONE - self.certificate = certificate - self.protocol = ssl_version - self.certreqs = certreqs - self.cacerts = cacerts - self.ciphers = ciphers + ciphers=None, context=None): + if context: + self.context = context + else: + self.context = ssl.SSLContext(ssl_version + if ssl_version is not None + else ssl.PROTOCOL_TLSv1) + self.context.verify_mode = (certreqs if certreqs is not None + else ssl.CERT_NONE) + if cacerts: + self.context.load_verify_locations(cacerts) + if certificate: + self.context.load_cert_chain(certificate) + if ciphers: + self.context.set_ciphers(ciphers) self.chatty = chatty self.connectionchatty = connectionchatty self.starttls_server = starttls_server @@ -820,18 +849,13 @@ server.stop() server.join() - def server_params_test(certfile, protocol, certreqs, cacertsfile, - client_certfile, client_protocol=None, indata=b"FOO\n", - ciphers=None, chatty=True, connectionchatty=False): + def server_params_test(client_context, server_context, indata=b"FOO\n", + chatty=True, connectionchatty=False): """ Launch a server, connect a client to it and try various reads and writes. """ - server = ThreadedEchoServer(certfile, - certreqs=certreqs, - ssl_version=protocol, - cacerts=cacertsfile, - ciphers=ciphers, + server = ThreadedEchoServer(context=server_context, chatty=chatty, connectionchatty=False) flag = threading.Event() @@ -839,15 +863,8 @@ # wait for it to start flag.wait() # try to connect - if client_protocol is None: - client_protocol = protocol try: - s = ssl.wrap_socket(socket.socket(), - certfile=client_certfile, - ca_certs=cacertsfile, - ciphers=ciphers, - cert_reqs=certreqs, - ssl_version=client_protocol) + s = client_context.wrap_socket(socket.socket()) s.connect((HOST, server.port)) for arg in [indata, bytearray(indata), memoryview(indata)]: if connectionchatty: @@ -873,10 +890,8 @@ server.stop() server.join() - def try_protocol_combo(server_protocol, - client_protocol, - expect_success, - certsreqs=None): + def try_protocol_combo(server_protocol, client_protocol, expect_success, + certsreqs=None, server_options=0, client_options=0): if certsreqs is None: certsreqs = ssl.CERT_NONE certtype = { @@ -890,14 +905,21 @@ (ssl.get_protocol_name(client_protocol), ssl.get_protocol_name(server_protocol), certtype)) - try: + client_context = ssl.SSLContext(client_protocol) + client_context.options = ssl.OP_ALL | client_options + server_context = ssl.SSLContext(server_protocol) + server_context.options = ssl.OP_ALL | server_options + for ctx in (client_context, server_context): + ctx.verify_mode = certsreqs # NOTE: we must enable "ALL" ciphers, otherwise an SSLv23 client # will send an SSLv3 hello (rather than SSLv2) starting from # OpenSSL 1.0.0 (see issue #8322). - server_params_test(CERTFILE, server_protocol, certsreqs, - CERTFILE, CERTFILE, client_protocol, - ciphers="ALL", chatty=False, - connectionchatty=False) + ctx.set_ciphers("ALL") + ctx.load_cert_chain(CERTFILE) + ctx.load_verify_locations(CERTFILE) + try: + server_params_test(client_context, server_context, + chatty=False, connectionchatty=False) # Protocol mismatch can result in either an SSLError, or a # "Connection reset by peer" error. except ssl.SSLError: @@ -920,30 +942,27 @@ """Basic test of an SSL client connecting to a server""" if support.verbose: sys.stdout.write("\n") - server_params_test(CERTFILE, ssl.PROTOCOL_TLSv1, ssl.CERT_NONE, - CERTFILE, CERTFILE, ssl.PROTOCOL_TLSv1, - chatty=True, connectionchatty=True) + for protocol in PROTOCOLS: + context = ssl.SSLContext(protocol) + context.load_cert_chain(CERTFILE) + server_params_test(context, context, + chatty=True, connectionchatty=True) def test_getpeercert(self): if support.verbose: sys.stdout.write("\n") - s2 = socket.socket() - server = ThreadedEchoServer(CERTFILE, - certreqs=ssl.CERT_NONE, - ssl_version=ssl.PROTOCOL_SSLv23, - cacerts=CERTFILE, - chatty=False) + context = ssl.SSLContext(ssl.PROTOCOL_SSLv23) + context.verify_mode = ssl.CERT_REQUIRED + context.load_verify_locations(CERTFILE) + context.load_cert_chain(CERTFILE) + server = ThreadedEchoServer(context=context, chatty=False) flag = threading.Event() server.start(flag) # wait for it to start flag.wait() # try to connect try: - s = ssl.wrap_socket(socket.socket(), - certfile=CERTFILE, - ca_certs=CERTFILE, - cert_reqs=ssl.CERT_REQUIRED, - ssl_version=ssl.PROTOCOL_SSLv23) + s = context.wrap_socket(socket.socket()) s.connect((HOST, server.port)) cert = s.getpeercert() self.assertTrue(cert, "Can't get peer certificate.") @@ -1031,6 +1050,15 @@ try_protocol_combo(ssl.PROTOCOL_SSLv2, ssl.PROTOCOL_SSLv23, True) try_protocol_combo(ssl.PROTOCOL_SSLv2, ssl.PROTOCOL_SSLv3, False) try_protocol_combo(ssl.PROTOCOL_SSLv2, ssl.PROTOCOL_TLSv1, False) + # SSLv23 client with specific SSL options + if no_sslv2_implies_sslv3_hello(): + # No SSLv2 => client will use an SSLv3 hello on recent OpenSSLs + try_protocol_combo(ssl.PROTOCOL_SSLv2, ssl.PROTOCOL_SSLv23, False, + client_options=ssl.OP_NO_SSLv2) + try_protocol_combo(ssl.PROTOCOL_SSLv2, ssl.PROTOCOL_SSLv23, True, + client_options=ssl.OP_NO_SSLv3) + try_protocol_combo(ssl.PROTOCOL_SSLv2, ssl.PROTOCOL_SSLv23, True, + client_options=ssl.OP_NO_TLSv1) def test_protocol_sslv23(self): """Connecting to an SSLv23 server with various client options""" @@ -1056,6 +1084,16 @@ try_protocol_combo(ssl.PROTOCOL_SSLv23, ssl.PROTOCOL_SSLv23, True, ssl.CERT_REQUIRED) try_protocol_combo(ssl.PROTOCOL_SSLv23, ssl.PROTOCOL_TLSv1, True, ssl.CERT_REQUIRED) + # Server with specific SSL options + try_protocol_combo(ssl.PROTOCOL_SSLv23, ssl.PROTOCOL_SSLv3, False, + server_options=ssl.OP_NO_SSLv3) + # Will choose TLSv1 + try_protocol_combo(ssl.PROTOCOL_SSLv23, ssl.PROTOCOL_SSLv23, True, + server_options=ssl.OP_NO_SSLv2 | ssl.OP_NO_SSLv3) + try_protocol_combo(ssl.PROTOCOL_SSLv23, ssl.PROTOCOL_TLSv1, False, + server_options=ssl.OP_NO_TLSv1) + + def test_protocol_sslv3(self): """Connecting to an SSLv3 server with various client options""" if support.verbose: @@ -1066,6 +1104,10 @@ try_protocol_combo(ssl.PROTOCOL_SSLv3, ssl.PROTOCOL_SSLv2, False) try_protocol_combo(ssl.PROTOCOL_SSLv3, ssl.PROTOCOL_SSLv23, False) try_protocol_combo(ssl.PROTOCOL_SSLv3, ssl.PROTOCOL_TLSv1, False) + if no_sslv2_implies_sslv3_hello(): + # No SSLv2 => client will use an SSLv3 hello on recent OpenSSLs + try_protocol_combo(ssl.PROTOCOL_SSLv3, ssl.PROTOCOL_SSLv23, True, + client_options=ssl.OP_NO_SSLv2) def test_protocol_tlsv1(self): """Connecting to a TLSv1 server with various client options""" Modified: python/branches/py3k-jit/Lib/test/test_subprocess.py ============================================================================== --- python/branches/py3k-jit/Lib/test/test_subprocess.py (original) +++ python/branches/py3k-jit/Lib/test/test_subprocess.py Tue May 25 03:17:49 2010 @@ -535,6 +535,17 @@ if c.exception.errno != 2: # ignore "no such file" raise c.exception + def test_issue8780(self): + # Ensure that stdout is inherited from the parent + # if stdout=PIPE is not used + code = ';'.join(( + 'import subprocess, sys', + 'retcode = subprocess.call(' + "[sys.executable, '-c', 'print(\"Hello World!\")'])", + 'assert retcode == 0')) + output = subprocess.check_output([sys.executable, '-c', code]) + self.assert_(output.startswith(b'Hello World!'), ascii(output)) + # context manager class _SuppressCoreFiles(object): @@ -825,6 +836,27 @@ stdout = stdout.rstrip(b'\n\r') self.assertEquals(stdout.decode('ascii'), repr(value)) + def test_bytes_program(self): + abs_program = os.fsencode(sys.executable) + path, program = os.path.split(sys.executable) + program = os.fsencode(program) + + # absolute bytes path + exitcode = subprocess.call([abs_program, "-c", "pass"]) + self.assertEquals(exitcode, 0) + + # bytes program, unicode PATH + env = os.environ.copy() + env["PATH"] = path + exitcode = subprocess.call([program, "-c", "pass"], env=env) + self.assertEquals(exitcode, 0) + + # bytes program, bytes PATH + envb = os.environb.copy() + envb[b"PATH"] = os.fsencode(path) + exitcode = subprocess.call([program, "-c", "pass"], env=envb) + self.assertEquals(exitcode, 0) + @unittest.skipUnless(mswindows, "Windows specific tests") class Win32ProcessTestCase(BaseTestCase): Modified: python/branches/py3k-jit/Lib/test/test_sys.py ============================================================================== --- python/branches/py3k-jit/Lib/test/test_sys.py (original) +++ python/branches/py3k-jit/Lib/test/test_sys.py Tue May 25 03:17:49 2010 @@ -147,9 +147,9 @@ "raise SystemExit(47)"]) self.assertEqual(rc, 47) - def check_exit_message(code, expected): + def check_exit_message(code, expected, env=None): process = subprocess.Popen([sys.executable, "-c", code], - stderr=subprocess.PIPE) + stderr=subprocess.PIPE, env=env) stdout, stderr = process.communicate() self.assertEqual(process.returncode, 1) self.assertTrue(stderr.startswith(expected), @@ -167,6 +167,14 @@ r'import sys; sys.exit("surrogates:\uDCFF")', b"surrogates:\\udcff") + # test that the unicode message is encoded to the stderr encoding + # instead of the default encoding (utf8) + env = os.environ.copy() + env['PYTHONIOENCODING'] = 'latin-1' + check_exit_message( + r'import sys; sys.exit("h\xe9")', + b"h\xe9", env=env) + def test_getdefaultencoding(self): self.assertRaises(TypeError, sys.getdefaultencoding, 42) # can't check more than the type, as the user might have changed it @@ -419,6 +427,23 @@ self.assertEqual(type(sys.int_info.bits_per_digit), int) self.assertEqual(type(sys.int_info.sizeof_digit), int) self.assertIsInstance(sys.hexversion, int) + + self.assertEqual(len(sys.hash_info), 5) + self.assertLess(sys.hash_info.modulus, 2**sys.hash_info.width) + # sys.hash_info.modulus should be a prime; we do a quick + # probable primality test (doesn't exclude the possibility of + # a Carmichael number) + for x in range(1, 100): + self.assertEqual( + pow(x, sys.hash_info.modulus-1, sys.hash_info.modulus), + 1, + "sys.hash_info.modulus {} is a non-prime".format( + sys.hash_info.modulus) + ) + self.assertIsInstance(sys.hash_info.inf, int) + self.assertIsInstance(sys.hash_info.nan, int) + self.assertIsInstance(sys.hash_info.imag, int) + self.assertIsInstance(sys.maxsize, int) self.assertIsInstance(sys.maxunicode, int) self.assertIsInstance(sys.platform, str) Modified: python/branches/py3k-jit/Lib/test/test_sysconfig.py ============================================================================== --- python/branches/py3k-jit/Lib/test/test_sysconfig.py (original) +++ python/branches/py3k-jit/Lib/test/test_sysconfig.py Tue May 25 03:17:49 2010 @@ -17,7 +17,7 @@ from sysconfig import (get_paths, get_platform, get_config_vars, get_path, get_path_names, _INSTALL_SCHEMES, _get_default_scheme, _expand_vars, - get_scheme_names) + get_scheme_names, get_config_var) class TestSysConfig(unittest.TestCase): @@ -254,6 +254,15 @@ finally: unlink(link) + def test_user_similar(self): + # Issue 8759 : make sure the posix scheme for the users + # is similar to the global posix_prefix one + base = get_config_var('base') + user = get_config_var('userbase') + for name in ('stdlib', 'platstdlib', 'purelib', 'platlib'): + global_path = get_path(name, 'posix_prefix') + user_path = get_path(name, 'posix_user') + self.assertEquals(user_path, global_path.replace(base, user)) def test_main(): run_unittest(TestSysConfig) Modified: python/branches/py3k-jit/Lib/test/test_warnings.py ============================================================================== --- python/branches/py3k-jit/Lib/test/test_warnings.py (original) +++ python/branches/py3k-jit/Lib/test/test_warnings.py Tue May 25 03:17:49 2010 @@ -738,20 +738,38 @@ module = py_warnings +class BootstrapTest(unittest.TestCase): + def test_issue_8766(self): + # "import encodings" emits a warning whereas the warnings is not loaded + # or not completly loaded (warnings imports indirectly encodings by + # importing linecache) yet + with support.temp_cwd() as cwd, support.temp_cwd('encodings'): + env = os.environ.copy() + env['PYTHONPATH'] = cwd + + # encodings loaded by initfsencoding() + retcode = subprocess.call([sys.executable, '-c', 'pass'], env=env) + self.assertEqual(retcode, 0) + + # Use -W to load warnings module at startup + retcode = subprocess.call( + [sys.executable, '-c', 'pass', '-W', 'always'], + env=env) + self.assertEqual(retcode, 0) + def test_main(): py_warnings.onceregistry.clear() c_warnings.onceregistry.clear() - support.run_unittest(CFilterTests, - PyFilterTests, - CWarnTests, - PyWarnTests, - CWCmdLineTests, PyWCmdLineTests, - _WarningsTests, - CWarningsDisplayTests, PyWarningsDisplayTests, - CCatchWarningTests, PyCatchWarningTests, - CEnvironmentVariableTests, - PyEnvironmentVariableTests - ) + support.run_unittest( + CFilterTests, PyFilterTests, + CWarnTests, PyWarnTests, + CWCmdLineTests, PyWCmdLineTests, + _WarningsTests, + CWarningsDisplayTests, PyWarningsDisplayTests, + CCatchWarningTests, PyCatchWarningTests, + CEnvironmentVariableTests, PyEnvironmentVariableTests, + BootstrapTest, + ) if __name__ == "__main__": Modified: python/branches/py3k-jit/Misc/NEWS ============================================================================== --- python/branches/py3k-jit/Misc/NEWS (original) +++ python/branches/py3k-jit/Misc/NEWS Tue May 25 03:17:49 2010 @@ -31,6 +31,25 @@ Core and Builtins ----------------- +- Issue #8188: Introduce a new scheme for computing hashes of numbers + (instances of int, float, complex, decimal.Decimal and + fractions.Fraction) that makes it easy to maintain the invariant + that hash(x) == hash(y) whenever x and y have equal value. + +- Issue #8748: Fix two issues with comparisons between complex and integer + objects. (1) The comparison could incorrectly return True in some cases + (2**53+1 == complex(2**53) == 2**53), breaking transivity of equality. + (2) The comparison raised an OverflowError for large integers, leading + to unpredictable exceptions when combining integers and complex objects + in sets or dicts. + +- Issue #8766: Initialize _warnings module before importing the first module. + Fix a crash if an empty directory called "encodings" exists in sys.path. + +- Issue #8589: Decode PYTHONWARNINGS environment variable with the file system + encoding and surrogateespace error handler instead of the locale encoding to + be consistent with os.environ. Add PySys_AddWarnOptionUnicode() function. + - PyObject_Dump() encodes unicode objects to utf8 with backslashreplace (instead of strict) error handler to escape surrogates @@ -50,6 +69,8 @@ PyUnicode_FromString() to support surrogates in the filename and use the right encoding +- Issue #7507: Quote "!" in pipes.quote(); it is special to some shells. + - PyUnicode_DecodeFSDefaultAndSize() uses surrogateescape error handler - Issue #8419: Prevent the dict constructor from accepting non-string keyword @@ -331,6 +352,11 @@ C-API ----- +- Issue #5753: A new C API function, :cfunc:`PySys_SetArgvEx`, allows + embedders of the interpreter to set sys.argv without also modifying + sys.path. This helps fix `CVE-2008-5983 + `_. + - Add PyArg_ValidateKeywordArguments, which checks if all keyword arguments are strings in an efficient manner. @@ -385,6 +411,42 @@ Library ------- +- Issue #8540: Decimal module: rename the Context._clamp attribute to + Context.clamp and make it public. This is useful in creating + contexts that correspond to the decimal interchange formats + specified in IEEE 754. + +- Issue #6268: Fix seek() method of codecs.open(), don't read or write the BOM + twice after seek(0). Fix also reset() method of codecs, UTF-16, UTF-32 and + StreamWriter classes. + +- Issue #3798: sys.exit(message) writes the message to sys.stderr file, instead + of the C file stderr, to use stderr encoding and error handler + +- Issue #8782: Add a trailing newline in linecache.updatecache to the last line + of files without one. + +- Issue #8729: Return NotImplemented from collections.Mapping.__eq__ when + comparing to a non-mapping. + +- Issue #8774: tabnanny uses the encoding cookie (#coding:...) to use the + correct encoding + +- Issue #4870: Add an `options` attribute to SSL contexts, as well as + several ``OP_*`` constants to the `ssl` module. This allows to selectively + disable protocol versions, when used in combination with `PROTOCOL_SSLv23`. + +- Issue #8759: Fixed user paths in sysconfig for posix and os2 schemes. + +- Issue #8663: distutils.log emulates backslashreplace error handler. Fix + compilation in a non-ASCII directory if stdout encoding is ASCII (eg. if + stdout is not a TTY). + +- Issue #8513: os.get_exec_path() supports b'PATH' key and bytes value. + subprocess.Popen() and os._execvpe() support bytes program name. Add + os.supports_bytes_environ flag: True if the native OS type of the environment + is bytes (eg. False on Windows). + - Issue #8633: tarfile is now able to read and write archives with "raw" binary pax headers as described in POSIX.1-2008. @@ -456,7 +518,7 @@ - Issue #8354: The siginterrupt setting is now preserved for all signals, not just SIGCHLD. -- Issue #7192: webbrowser.get("firefox") now wors on Mac OS X, as does +- Issue #7192: webbrowser.get("firefox") now works on Mac OS X, as does webbrowser.get("safari"). - Issue #8464: tarfile no longer creates files with execute permissions set Modified: python/branches/py3k-jit/Modules/_io/textio.c ============================================================================== --- python/branches/py3k-jit/Modules/_io/textio.c (original) +++ python/branches/py3k-jit/Modules/_io/textio.c Tue May 25 03:17:49 2010 @@ -905,8 +905,11 @@ Py_CLEAR(self->encoding); } } - if (self->encoding != NULL) + if (self->encoding != NULL) { encoding = _PyUnicode_AsString(self->encoding); + if (encoding == NULL) + goto error; + } else if (encoding != NULL) { self->encoding = PyUnicode_FromString(encoding); if (self->encoding == NULL) @@ -935,6 +938,8 @@ self->writetranslate = (newline == NULL || newline[0] != '\0'); if (!self->readuniversal && self->readnl) { self->writenl = _PyUnicode_AsString(self->readnl); + if (self->writenl == NULL) + goto error; if (!strcmp(self->writenl, "\n")) self->writenl = NULL; } @@ -2408,7 +2413,7 @@ Py_DECREF(res); if (r < 0) return NULL; - + if (r > 0) { Py_RETURN_NONE; /* stream already closed */ } Modified: python/branches/py3k-jit/Modules/_sqlite/connection.c ============================================================================== --- python/branches/py3k-jit/Modules/_sqlite/connection.c (original) +++ python/branches/py3k-jit/Modules/_sqlite/connection.c Tue May 25 03:17:49 2010 @@ -3,7 +3,7 @@ * Copyright (C) 2004-2010 Gerhard H?ring * * This file is part of pysqlite. - * + * * 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. @@ -495,7 +495,9 @@ } else if (PyFloat_Check(py_val)) { sqlite3_result_double(context, PyFloat_AsDouble(py_val)); } else if (PyUnicode_Check(py_val)) { - sqlite3_result_text(context, _PyUnicode_AsString(py_val), -1, SQLITE_TRANSIENT); + char *str = _PyUnicode_AsString(py_val); + if (str != NULL) + sqlite3_result_text(context, str, -1, SQLITE_TRANSIENT); } else if (PyObject_CheckBuffer(py_val)) { if (PyObject_AsCharBuffer(py_val, &buffer, &buflen) != 0) { PyErr_SetString(PyExc_ValueError, "could not convert BLOB to buffer"); @@ -892,7 +894,7 @@ } /* abort query if error occurred */ - rc = 1; + rc = 1; } else { rc = (int)PyObject_IsTrue(ret); Py_DECREF(ret); Modified: python/branches/py3k-jit/Modules/_sqlite/cursor.c ============================================================================== --- python/branches/py3k-jit/Modules/_sqlite/cursor.c (original) +++ python/branches/py3k-jit/Modules/_sqlite/cursor.c Tue May 25 03:17:49 2010 @@ -368,7 +368,7 @@ } PyOS_snprintf(buf, sizeof(buf) - 1, "Could not decode to UTF-8 column '%s' with text '%s'", colname , val_str); - buf_bytes = PyByteArray_FromStringAndSize(buf, strlen(buf)); + buf_bytes = PyByteArray_FromStringAndSize(buf, strlen(buf)); if (!buf_bytes) { PyErr_SetString(pysqlite_OperationalError, "Could not decode to UTF-8"); } else { @@ -533,7 +533,7 @@ } operation_cstr = _PyUnicode_AsStringAndSize(operation, &operation_len); - if (operation == NULL) + if (operation_cstr == NULL) goto error; /* reset description and rowcount */ Modified: python/branches/py3k-jit/Modules/_sqlite/row.c ============================================================================== --- python/branches/py3k-jit/Modules/_sqlite/row.c (original) +++ python/branches/py3k-jit/Modules/_sqlite/row.c Tue May 25 03:17:49 2010 @@ -83,6 +83,8 @@ return item; } else if (PyUnicode_Check(idx)) { key = _PyUnicode_AsString(idx); + if (key == NULL) + return NULL; nitems = PyTuple_Size(self->description); Modified: python/branches/py3k-jit/Modules/_sqlite/statement.c ============================================================================== --- python/branches/py3k-jit/Modules/_sqlite/statement.c (original) +++ python/branches/py3k-jit/Modules/_sqlite/statement.c Tue May 25 03:17:49 2010 @@ -130,7 +130,10 @@ break; case TYPE_UNICODE: string = _PyUnicode_AsString(parameter); - rc = sqlite3_bind_text(self->st, pos, string, -1, SQLITE_TRANSIENT); + if (string != NULL) + rc = sqlite3_bind_text(self->st, pos, string, -1, SQLITE_TRANSIENT); + else + rc = -1; break; case TYPE_BUFFER: if (PyObject_AsCharBuffer(parameter, &buffer, &buflen) == 0) { Modified: python/branches/py3k-jit/Modules/_ssl.c ============================================================================== --- python/branches/py3k-jit/Modules/_ssl.c (original) +++ python/branches/py3k-jit/Modules/_ssl.c Tue May 25 03:17:49 2010 @@ -113,6 +113,13 @@ # undef HAVE_OPENSSL_RAND #endif +/* SSL_CTX_clear_options() and SSL_clear_options() were first added in OpenSSL 0.9.8m */ +#if OPENSSL_VERSION_NUMBER >= 0x009080dfL +# define HAVE_SSL_CTX_CLEAR_OPTIONS +#else +# undef HAVE_SSL_CTX_CLEAR_OPTIONS +#endif + typedef struct { PyObject_HEAD SSL_CTX *ctx; @@ -1514,6 +1521,35 @@ } static PyObject * +get_options(PySSLContext *self, void *c) +{ + return PyLong_FromLong(SSL_CTX_get_options(self->ctx)); +} + +static int +set_options(PySSLContext *self, PyObject *arg, void *c) +{ + long new_opts, opts, set, clear; + if (!PyArg_Parse(arg, "l", &new_opts)) + return -1; + opts = SSL_CTX_get_options(self->ctx); + clear = opts & ~new_opts; + set = ~opts & new_opts; + if (clear) { +#ifdef HAVE_SSL_CTX_CLEAR_OPTIONS + SSL_CTX_clear_options(self->ctx, clear); +#else + PyErr_SetString(PyExc_ValueError, + "can't clear options before OpenSSL 0.9.8m"); + return -1; +#endif + } + if (set) + SSL_CTX_set_options(self->ctx, set); + return 0; +} + +static PyObject * load_cert_chain(PySSLContext *self, PyObject *args, PyObject *kwds) { char *kwlist[] = {"certfile", "keyfile", NULL}; @@ -1636,6 +1672,8 @@ } static PyGetSetDef context_getsetlist[] = { + {"options", (getter) get_options, + (setter) set_options, NULL}, {"verify_mode", (getter) get_verify_mode, (setter) set_verify_mode, NULL}, {NULL}, /* sentinel */ @@ -1953,6 +1991,12 @@ PyModule_AddIntConstant(m, "PROTOCOL_TLSv1", PY_SSL_VERSION_TLS1); + /* protocol options */ + PyModule_AddIntConstant(m, "OP_ALL", SSL_OP_ALL); + PyModule_AddIntConstant(m, "OP_NO_SSLv2", SSL_OP_NO_SSLv2); + PyModule_AddIntConstant(m, "OP_NO_SSLv3", SSL_OP_NO_SSLv3); + PyModule_AddIntConstant(m, "OP_NO_TLSv1", SSL_OP_NO_TLSv1); + /* OpenSSL version */ /* SSLeay() gives us the version of the library linked against, which could be different from the headers version. Modified: python/branches/py3k-jit/Modules/main.c ============================================================================== --- python/branches/py3k-jit/Modules/main.c (original) +++ python/branches/py3k-jit/Modules/main.c Tue May 25 03:17:49 2010 @@ -425,7 +425,7 @@ #else if ((p = Py_GETENV("PYTHONWARNINGS")) && *p != '\0') { char *buf, *oldloc; - wchar_t *warning; + PyObject *warning; /* settle for strtok here as there's no one standard C89 wcstok */ @@ -437,9 +437,10 @@ oldloc = strdup(setlocale(LC_ALL, NULL)); setlocale(LC_ALL, ""); for (p = strtok(buf, ","); p != NULL; p = strtok(NULL, ",")) { - if ((warning = _Py_char2wchar(p)) != NULL) { - PySys_AddWarnOption(warning); - PyMem_Free(warning); + warning = PyUnicode_DecodeFSDefault(p); + if (warning != NULL) { + PySys_AddWarnOptionUnicode(warning); + Py_DECREF(warning); } } setlocale(LC_ALL, oldloc); Modified: python/branches/py3k-jit/Objects/complexobject.c ============================================================================== --- python/branches/py3k-jit/Objects/complexobject.c (original) +++ python/branches/py3k-jit/Objects/complexobject.c Tue May 25 03:17:49 2010 @@ -403,12 +403,12 @@ static long complex_hash(PyComplexObject *v) { - long hashreal, hashimag, combined; - hashreal = _Py_HashDouble(v->cval.real); - if (hashreal == -1) + unsigned long hashreal, hashimag, combined; + hashreal = (unsigned long)_Py_HashDouble(v->cval.real); + if (hashreal == (unsigned long)-1) return -1; - hashimag = _Py_HashDouble(v->cval.imag); - if (hashimag == -1) + hashimag = (unsigned long)_Py_HashDouble(v->cval.imag); + if (hashimag == (unsigned long)-1) return -1; /* Note: if the imaginary part is 0, hashimag is 0 now, * so the following returns hashreal unchanged. This is @@ -416,10 +416,10 @@ * compare equal must have the same hash value, so that * hash(x + 0*j) must equal hash(x). */ - combined = hashreal + 1000003 * hashimag; - if (combined == -1) - combined = -2; - return combined; + combined = hashreal + _PyHASH_IMAG * hashimag; + if (combined == (unsigned long)-1) + combined = (unsigned long)-2; + return (long)combined; } /* This macro may return! */ @@ -620,22 +620,58 @@ complex_richcompare(PyObject *v, PyObject *w, int op) { PyObject *res; - Py_complex i, j; - TO_COMPLEX(v, i); - TO_COMPLEX(w, j); + Py_complex i; + int equal; if (op != Py_EQ && op != Py_NE) { - Py_INCREF(Py_NotImplemented); - return Py_NotImplemented; + goto Unimplemented; + } + + assert(PyComplex_Check(v)); + TO_COMPLEX(v, i); + + if (PyLong_Check(w)) { + /* Check for 0.0 imaginary part first to avoid the rich + * comparison when possible. + */ + if (i.imag == 0.0) { + PyObject *j, *sub_res; + j = PyFloat_FromDouble(i.real); + if (j == NULL) + return NULL; + + sub_res = PyObject_RichCompare(j, w, op); + Py_DECREF(j); + return sub_res; + } + else { + equal = 0; + } } + else if (PyFloat_Check(w)) { + equal = (i.real == PyFloat_AsDouble(w) && i.imag == 0.0); + } + else if (PyComplex_Check(w)) { + Py_complex j; - if ((i.real == j.real && i.imag == j.imag) == (op == Py_EQ)) - res = Py_True; + TO_COMPLEX(w, j); + equal = (i.real == j.real && i.imag == j.imag); + } + else { + goto Unimplemented; + } + + if (equal == (op == Py_EQ)) + res = Py_True; else - res = Py_False; + res = Py_False; Py_INCREF(res); return res; + +Unimplemented: + Py_INCREF(Py_NotImplemented); + return Py_NotImplemented; } static PyObject * Modified: python/branches/py3k-jit/Objects/longobject.c ============================================================================== --- python/branches/py3k-jit/Objects/longobject.c (original) +++ python/branches/py3k-jit/Objects/longobject.c Tue May 25 03:17:49 2010 @@ -2571,18 +2571,37 @@ sign = -1; i = -(i); } - /* The following loop produces a C unsigned long x such that x is - congruent to the absolute value of v modulo ULONG_MAX. The - resulting x is nonzero if and only if v is. */ while (--i >= 0) { - /* Force a native long #-bits (32 or 64) circular shift */ - x = (x >> (8*SIZEOF_LONG-PyLong_SHIFT)) | (x << PyLong_SHIFT); + /* Here x is a quantity in the range [0, _PyHASH_MODULUS); we + want to compute x * 2**PyLong_SHIFT + v->ob_digit[i] modulo + _PyHASH_MODULUS. + + The computation of x * 2**PyLong_SHIFT % _PyHASH_MODULUS + amounts to a rotation of the bits of x. To see this, write + + x * 2**PyLong_SHIFT = y * 2**_PyHASH_BITS + z + + where y = x >> (_PyHASH_BITS - PyLong_SHIFT) gives the top + PyLong_SHIFT bits of x (those that are shifted out of the + original _PyHASH_BITS bits, and z = (x << PyLong_SHIFT) & + _PyHASH_MODULUS gives the bottom _PyHASH_BITS - PyLong_SHIFT + bits of x, shifted up. Then since 2**_PyHASH_BITS is + congruent to 1 modulo _PyHASH_MODULUS, y*2**_PyHASH_BITS is + congruent to y modulo _PyHASH_MODULUS. So + + x * 2**PyLong_SHIFT = y + z (mod _PyHASH_MODULUS). + + The right-hand side is just the result of rotating the + _PyHASH_BITS bits of x left by PyLong_SHIFT places; since + not all _PyHASH_BITS bits of x are 1s, the same is true + after rotation, so 0 <= y+z < _PyHASH_MODULUS and y + z is + the reduction of x*2**PyLong_SHIFT modulo + _PyHASH_MODULUS. */ + x = ((x << PyLong_SHIFT) & _PyHASH_MODULUS) | + (x >> (_PyHASH_BITS - PyLong_SHIFT)); x += v->ob_digit[i]; - /* If the addition above overflowed we compensate by - incrementing. This preserves the value modulo - ULONG_MAX. */ - if (x < v->ob_digit[i]) - x++; + if (x >= _PyHASH_MODULUS) + x -= _PyHASH_MODULUS; } x = x * sign; if (x == (unsigned long)-1) Modified: python/branches/py3k-jit/Objects/moduleobject.c ============================================================================== --- python/branches/py3k-jit/Objects/moduleobject.c (original) +++ python/branches/py3k-jit/Objects/moduleobject.c Tue May 25 03:17:49 2010 @@ -263,10 +263,15 @@ pos = 0; while (PyDict_Next(d, &pos, &key, &value)) { if (value != Py_None && PyUnicode_Check(key)) { - const char *s = _PyUnicode_AsString(key); - if (s[0] == '_' && s[1] != '_') { - if (Py_VerboseFlag > 1) - PySys_WriteStderr("# clear[1] %s\n", s); + Py_UNICODE *u = PyUnicode_AS_UNICODE(key); + if (u[0] == '_' && u[1] != '_') { + if (Py_VerboseFlag > 1) { + const char *s = _PyUnicode_AsString(key); + if (s != NULL) + PySys_WriteStderr("# clear[1] %s\n", s); + else + PyErr_Clear(); + } PyDict_SetItem(d, key, Py_None); } } @@ -276,10 +281,17 @@ pos = 0; while (PyDict_Next(d, &pos, &key, &value)) { if (value != Py_None && PyUnicode_Check(key)) { - const char *s = _PyUnicode_AsString(key); - if (s[0] != '_' || strcmp(s, "__builtins__") != 0) { - if (Py_VerboseFlag > 1) - PySys_WriteStderr("# clear[2] %s\n", s); + Py_UNICODE *u = PyUnicode_AS_UNICODE(key); + if (u[0] != '_' + || PyUnicode_CompareWithASCIIString(key, "__builtins__") != 0) + { + if (Py_VerboseFlag > 1) { + const char *s = _PyUnicode_AsString(key); + if (s != NULL) + PySys_WriteStderr("# clear[2] %s\n", s); + else + PyErr_Clear(); + } PyDict_SetItem(d, key, Py_None); } } Modified: python/branches/py3k-jit/Objects/object.c ============================================================================== --- python/branches/py3k-jit/Objects/object.c (original) +++ python/branches/py3k-jit/Objects/object.c Tue May 25 03:17:49 2010 @@ -647,63 +647,101 @@ All the utility functions (_Py_Hash*()) return "-1" to signify an error. */ +/* For numeric types, the hash of a number x is based on the reduction + of x modulo the prime P = 2**_PyHASH_BITS - 1. It's designed so that + hash(x) == hash(y) whenever x and y are numerically equal, even if + x and y have different types. + + A quick summary of the hashing strategy: + + (1) First define the 'reduction of x modulo P' for any rational + number x; this is a standard extension of the usual notion of + reduction modulo P for integers. If x == p/q (written in lowest + terms), the reduction is interpreted as the reduction of p times + the inverse of the reduction of q, all modulo P; if q is exactly + divisible by P then define the reduction to be infinity. So we've + got a well-defined map + + reduce : { rational numbers } -> { 0, 1, 2, ..., P-1, infinity }. + + (2) Now for a rational number x, define hash(x) by: + + reduce(x) if x >= 0 + -reduce(-x) if x < 0 + + If the result of the reduction is infinity (this is impossible for + integers, floats and Decimals) then use the predefined hash value + _PyHASH_INF for x >= 0, or -_PyHASH_INF for x < 0, instead. + _PyHASH_INF, -_PyHASH_INF and _PyHASH_NAN are also used for the + hashes of float and Decimal infinities and nans. + + A selling point for the above strategy is that it makes it possible + to compute hashes of decimal and binary floating-point numbers + efficiently, even if the exponent of the binary or decimal number + is large. The key point is that + + reduce(x * y) == reduce(x) * reduce(y) (modulo _PyHASH_MODULUS) + + provided that {reduce(x), reduce(y)} != {0, infinity}. The reduction of a + binary or decimal float is never infinity, since the denominator is a power + of 2 (for binary) or a divisor of a power of 10 (for decimal). So we have, + for nonnegative x, + + reduce(x * 2**e) == reduce(x) * reduce(2**e) % _PyHASH_MODULUS + + reduce(x * 10**e) == reduce(x) * reduce(10**e) % _PyHASH_MODULUS + + and reduce(10**e) can be computed efficiently by the usual modular + exponentiation algorithm. For reduce(2**e) it's even better: since + P is of the form 2**n-1, reduce(2**e) is 2**(e mod n), and multiplication + by 2**(e mod n) modulo 2**n-1 just amounts to a rotation of bits. + + */ + long _Py_HashDouble(double v) { - double intpart, fractpart; - int expo; - long hipart; - long x; /* the final hash value */ - /* This is designed so that Python numbers of different types - * that compare equal hash to the same value; otherwise comparisons - * of mapping keys will turn out weird. - */ + int e, sign; + double m; + unsigned long x, y; if (!Py_IS_FINITE(v)) { if (Py_IS_INFINITY(v)) - return v < 0 ? -271828 : 314159; + return v > 0 ? _PyHASH_INF : -_PyHASH_INF; else - return 0; + return _PyHASH_NAN; } - fractpart = modf(v, &intpart); - if (fractpart == 0.0) { - /* This must return the same hash as an equal int or long. */ - if (intpart > LONG_MAX/2 || -intpart > LONG_MAX/2) { - /* Convert to long and use its hash. */ - PyObject *plong; /* converted to Python long */ - plong = PyLong_FromDouble(v); - if (plong == NULL) - return -1; - x = PyObject_Hash(plong); - Py_DECREF(plong); - return x; - } - /* Fits in a C long == a Python int, so is its own hash. */ - x = (long)intpart; - if (x == -1) - x = -2; - return x; - } - /* The fractional part is non-zero, so we don't have to worry about - * making this match the hash of some other type. - * Use frexp to get at the bits in the double. - * Since the VAX D double format has 56 mantissa bits, which is the - * most of any double format in use, each of these parts may have as - * many as (but no more than) 56 significant bits. - * So, assuming sizeof(long) >= 4, each part can be broken into two - * longs; frexp and multiplication are used to do that. - * Also, since the Cray double format has 15 exponent bits, which is - * the most of any double format in use, shifting the exponent field - * left by 15 won't overflow a long (again assuming sizeof(long) >= 4). - */ - v = frexp(v, &expo); - v *= 2147483648.0; /* 2**31 */ - hipart = (long)v; /* take the top 32 bits */ - v = (v - (double)hipart) * 2147483648.0; /* get the next 32 bits */ - x = hipart + (long)v + (expo << 15); - if (x == -1) - x = -2; - return x; + + m = frexp(v, &e); + + sign = 1; + if (m < 0) { + sign = -1; + m = -m; + } + + /* process 28 bits at a time; this should work well both for binary + and hexadecimal floating point. */ + x = 0; + while (m) { + x = ((x << 28) & _PyHASH_MODULUS) | x >> (_PyHASH_BITS - 28); + m *= 268435456.0; /* 2**28 */ + e -= 28; + y = (unsigned long)m; /* pull out integer part */ + m -= y; + x += y; + if (x >= _PyHASH_MODULUS) + x -= _PyHASH_MODULUS; + } + + /* adjust for the exponent; first reduce it modulo _PyHASH_BITS */ + e = e >= 0 ? e % _PyHASH_BITS : _PyHASH_BITS-1-((-1-e) % _PyHASH_BITS); + x = ((x << e) & _PyHASH_MODULUS) | x >> (_PyHASH_BITS - e); + + x = x * sign; + if (x == (unsigned long)-1) + x = (unsigned long)-2; + return (long)x; } long @@ -950,31 +988,7 @@ goto done; } -#if 0 /* XXX this is not quite _PyType_Lookup anymore */ - /* Inline _PyType_Lookup */ - { - Py_ssize_t i, n; - PyObject *mro, *base, *dict; - - /* Look in tp_dict of types in MRO */ - mro = tp->tp_mro; - assert(mro != NULL); - assert(PyTuple_Check(mro)); - n = PyTuple_GET_SIZE(mro); - for (i = 0; i < n; i++) { - base = PyTuple_GET_ITEM(mro, i); - assert(PyType_Check(base)); - dict = ((PyTypeObject *)base)->tp_dict; - assert(dict && PyDict_Check(dict)); - descr = PyDict_GetItem(dict, name); - if (descr != NULL) - break; - } - } -#else descr = _PyType_Lookup(tp, name); -#endif - Py_XINCREF(descr); f = NULL; Modified: python/branches/py3k-jit/Objects/typeobject.c ============================================================================== --- python/branches/py3k-jit/Objects/typeobject.c (original) +++ python/branches/py3k-jit/Objects/typeobject.c Tue May 25 03:17:49 2010 @@ -1347,8 +1347,14 @@ i = 0; while (PyDict_Next(set, &i, &k, &v) && (size_t)off < sizeof(buf)) { PyObject *name = class_name(k); - off += PyOS_snprintf(buf + off, sizeof(buf) - off, " %s", - name ? _PyUnicode_AsString(name) : "?"); + char *name_str; + if (name != NULL) { + name_str = _PyUnicode_AsString(name); + if (name_str == NULL) + name_str = "?"; + } else + name_str = "?"; + off += PyOS_snprintf(buf + off, sizeof(buf) - off, " %s", name_str); Py_XDECREF(name); if (--n && (size_t)(off+1) < sizeof(buf)) { buf[off++] = ','; @@ -2220,6 +2226,10 @@ for (i = 0; i < nslots; i++, mp++) { mp->name = _PyUnicode_AsString( PyTuple_GET_ITEM(slots, i)); + if (mp->name == NULL) { + Py_DECREF(type); + return NULL; + } mp->type = T_OBJECT_EX; mp->offset = slotoffset; @@ -4911,6 +4921,7 @@ PyObject *func, *res; static PyObject *hash_str; long h; + int overflow; func = lookup_method(self, "__hash__", &hash_str); @@ -4927,14 +4938,27 @@ Py_DECREF(func); if (res == NULL) return -1; - if (PyLong_Check(res)) + + if (!PyLong_Check(res)) { + PyErr_SetString(PyExc_TypeError, + "__hash__ method should return an integer"); + return -1; + } + /* Transform the PyLong `res` to a C long `h`. For an existing + hashable Python object x, hash(x) will always lie within the range + of a C long. Therefore our transformation must preserve values + that already lie within this range, to ensure that if x.__hash__() + returns hash(y) then hash(x) == hash(y). */ + h = PyLong_AsLongAndOverflow(res, &overflow); + if (overflow) + /* res was not within the range of a C long, so we're free to + use any sufficiently bit-mixing transformation; + long.__hash__ will do nicely. */ h = PyLong_Type.tp_hash(res); - else - h = PyLong_AsLong(res); Py_DECREF(res); - if (h == -1 && !PyErr_Occurred()) - h = -2; - return h; + if (h == -1 && !PyErr_Occurred()) + h = -2; + return h; } static PyObject * Modified: python/branches/py3k-jit/Parser/asdl.py ============================================================================== --- python/branches/py3k-jit/Parser/asdl.py (original) +++ python/branches/py3k-jit/Parser/asdl.py Tue May 25 03:17:49 2010 @@ -1,7 +1,7 @@ """An implementation of the Zephyr Abstract Syntax Definition Language. See http://asdl.sourceforge.net/ and -http://www.cs.princeton.edu/~danwang/Papers/dsl97/dsl97-abstract.html. +http://www.cs.princeton.edu/research/techreps/TR-554-97 Only supports top level module decl, not view. I'm guessing that view is intended to support the browser and I'm not interested in the Modified: python/branches/py3k-jit/Python/_warnings.c ============================================================================== --- python/branches/py3k-jit/Python/_warnings.c (original) +++ python/branches/py3k-jit/Python/_warnings.c Tue May 25 03:17:49 2010 @@ -116,7 +116,7 @@ _filters = warnings_filters; } - if (!PyList_Check(_filters)) { + if (_filters == NULL || !PyList_Check(_filters)) { PyErr_SetString(PyExc_ValueError, MODULE_NAME ".filters must be a list"); return NULL; Modified: python/branches/py3k-jit/Python/bltinmodule.c ============================================================================== --- python/branches/py3k-jit/Python/bltinmodule.c (original) +++ python/branches/py3k-jit/Python/bltinmodule.c Tue May 25 03:17:49 2010 @@ -1610,6 +1610,7 @@ char *prompt; char *s; PyObject *stdin_encoding; + char *stdin_encoding_str; PyObject *result; stdin_encoding = PyObject_GetAttrString(fin, "encoding"); @@ -1617,6 +1618,11 @@ /* stdin is a text stream, so it must have an encoding. */ return NULL; + stdin_encoding_str = _PyUnicode_AsString(stdin_encoding); + if (stdin_encoding_str == NULL) { + Py_DECREF(stdin_encoding); + return NULL; + } tmp = PyObject_CallMethod(fout, "flush", ""); if (tmp == NULL) PyErr_Clear(); @@ -1625,12 +1631,18 @@ if (promptarg != NULL) { PyObject *stringpo; PyObject *stdout_encoding; - stdout_encoding = PyObject_GetAttrString(fout, - "encoding"); + char *stdout_encoding_str; + stdout_encoding = PyObject_GetAttrString(fout, "encoding"); if (stdout_encoding == NULL) { Py_DECREF(stdin_encoding); return NULL; } + stdout_encoding_str = _PyUnicode_AsString(stdout_encoding); + if (stdout_encoding_str == NULL) { + Py_DECREF(stdin_encoding); + Py_DECREF(stdout_encoding); + return NULL; + } stringpo = PyObject_Str(promptarg); if (stringpo == NULL) { Py_DECREF(stdin_encoding); @@ -1638,7 +1650,7 @@ return NULL; } po = PyUnicode_AsEncodedString(stringpo, - _PyUnicode_AsString(stdout_encoding), NULL); + stdout_encoding_str, NULL); Py_DECREF(stdout_encoding); Py_DECREF(stringpo); if (po == NULL) { @@ -1676,10 +1688,7 @@ result = NULL; } else { - result = PyUnicode_Decode - (s, len-1, - _PyUnicode_AsString(stdin_encoding), - NULL); + result = PyUnicode_Decode(s, len-1, stdin_encoding_str, NULL); } } Py_DECREF(stdin_encoding); Modified: python/branches/py3k-jit/Python/getargs.c ============================================================================== --- python/branches/py3k-jit/Python/getargs.c (original) +++ python/branches/py3k-jit/Python/getargs.c Tue May 25 03:17:49 2010 @@ -1755,18 +1755,21 @@ "keywords must be strings"); return cleanreturn(0, freelist); } + /* check that _PyUnicode_AsString() result is not NULL */ ks = _PyUnicode_AsString(key); - for (i = 0; i < len; i++) { - if (!strcmp(ks, kwlist[i])) { - match = 1; - break; + if (ks != NULL) { + for (i = 0; i < len; i++) { + if (!strcmp(ks, kwlist[i])) { + match = 1; + break; + } } } if (!match) { PyErr_Format(PyExc_TypeError, - "'%s' is an invalid keyword " + "'%U' is an invalid keyword " "argument for this function", - ks); + key); return cleanreturn(0, freelist); } } Modified: python/branches/py3k-jit/Python/pythonrun.c ============================================================================== --- python/branches/py3k-jit/Python/pythonrun.c (original) +++ python/branches/py3k-jit/Python/pythonrun.c Tue May 25 03:17:49 2010 @@ -138,8 +138,8 @@ static char* get_codeset(void) { - char* codeset; - PyObject *codec, *name; + char* codeset, *name_str; + PyObject *codec, *name = NULL; codeset = nl_langinfo(CODESET); if (!codeset || codeset[0] == '\0') @@ -154,12 +154,16 @@ if (!name) goto error; - codeset = strdup(_PyUnicode_AsString(name)); + name_str = _PyUnicode_AsString(name); + if (name == NULL) + goto error; + codeset = strdup(name_str); Py_DECREF(name); return codeset; error: Py_XDECREF(codec); + Py_XDECREF(name); return NULL; } #endif @@ -261,13 +265,15 @@ _PyImportHooks_Init(); + /* Initialize _warnings. */ + _PyWarnings_Init(); + initfsencoding(); if (install_sigs) initsigs(); /* Signal handling stuff, including initintr() */ /* Initialize warnings. */ - _PyWarnings_Init(); if (PySys_HasWarnOptions()) { PyObject *warnings_module = PyImport_ImportModule("warnings"); if (!warnings_module) @@ -1061,22 +1067,34 @@ if (!oenc) return -1; enc = _PyUnicode_AsString(oenc); + if (enc == NULL) + return -1; } v = PySys_GetObject("ps1"); if (v != NULL) { v = PyObject_Str(v); if (v == NULL) PyErr_Clear(); - else if (PyUnicode_Check(v)) + else if (PyUnicode_Check(v)) { ps1 = _PyUnicode_AsString(v); + if (ps1 == NULL) { + PyErr_Clear(); + ps1 = ""; + } + } } w = PySys_GetObject("ps2"); if (w != NULL) { w = PyObject_Str(w); if (w == NULL) PyErr_Clear(); - else if (PyUnicode_Check(w)) + else if (PyUnicode_Check(w)) { ps2 = _PyUnicode_AsString(w); + if (ps2 == NULL) { + PyErr_Clear(); + ps2 = ""; + } + } } arena = PyArena_New(); if (arena == NULL) { @@ -1369,10 +1387,12 @@ exitcode = (int)PyLong_AsLong(value); else { PyObject *sys_stderr = PySys_GetObject("stderr"); - if (sys_stderr != NULL) - PyObject_CallMethod(sys_stderr, "flush", NULL); - PyObject_Print(value, stderr, Py_PRINT_RAW); - fflush(stderr); + if (sys_stderr != NULL && sys_stderr != Py_None) { + PyFile_WriteObject(value, sys_stderr, Py_PRINT_RAW); + } else { + PyObject_Print(value, stderr, Py_PRINT_RAW); + fflush(stderr); + } PySys_WriteStderr("\n"); exitcode = 1; } Modified: python/branches/py3k-jit/Python/sysmodule.c ============================================================================== --- python/branches/py3k-jit/Python/sysmodule.c (original) +++ python/branches/py3k-jit/Python/sysmodule.c Tue May 25 03:17:49 2010 @@ -570,6 +570,57 @@ return Py_None; } +static PyTypeObject Hash_InfoType; + +PyDoc_STRVAR(hash_info_doc, +"hash_info\n\ +\n\ +A struct sequence providing parameters used for computing\n\ +numeric hashes. The attributes are read only."); + +static PyStructSequence_Field hash_info_fields[] = { + {"width", "width of the type used for hashing, in bits"}, + {"modulus", "prime number giving the modulus on which the hash " + "function is based"}, + {"inf", "value to be used for hash of a positive infinity"}, + {"nan", "value to be used for hash of a nan"}, + {"imag", "multiplier used for the imaginary part of a complex number"}, + {NULL, NULL} +}; + +static PyStructSequence_Desc hash_info_desc = { + "sys.hash_info", + hash_info_doc, + hash_info_fields, + 5, +}; + +PyObject * +get_hash_info(void) +{ + PyObject *hash_info; + int field = 0; + hash_info = PyStructSequence_New(&Hash_InfoType); + if (hash_info == NULL) + return NULL; + PyStructSequence_SET_ITEM(hash_info, field++, + PyLong_FromLong(8*sizeof(long))); + PyStructSequence_SET_ITEM(hash_info, field++, + PyLong_FromLong(_PyHASH_MODULUS)); + PyStructSequence_SET_ITEM(hash_info, field++, + PyLong_FromLong(_PyHASH_INF)); + PyStructSequence_SET_ITEM(hash_info, field++, + PyLong_FromLong(_PyHASH_NAN)); + PyStructSequence_SET_ITEM(hash_info, field++, + PyLong_FromLong(_PyHASH_IMAG)); + if (PyErr_Occurred()) { + Py_CLEAR(hash_info); + return NULL; + } + return hash_info; +} + + PyDoc_STRVAR(setrecursionlimit_doc, "setrecursionlimit(n)\n\ \n\ @@ -1048,21 +1099,26 @@ } void -PySys_AddWarnOption(const wchar_t *s) +PySys_AddWarnOptionUnicode(PyObject *unicode) { - PyObject *str; - if (warnoptions == NULL || !PyList_Check(warnoptions)) { Py_XDECREF(warnoptions); warnoptions = PyList_New(0); if (warnoptions == NULL) return; } - str = PyUnicode_FromWideChar(s, -1); - if (str != NULL) { - PyList_Append(warnoptions, str); - Py_DECREF(str); - } + PyList_Append(warnoptions, unicode); +} + +void +PySys_AddWarnOption(const wchar_t *s) +{ + PyObject *unicode; + unicode = PyUnicode_FromWideChar(s, -1); + if (unicode == NULL) + return; + PySys_AddWarnOptionUnicode(unicode); + Py_DECREF(unicode); } int @@ -1477,6 +1533,11 @@ PyFloat_GetInfo()); SET_SYS_FROM_STRING("int_info", PyLong_GetInfo()); + /* initialize hash_info */ + if (Hash_InfoType.tp_name == 0) + PyStructSequence_InitType(&Hash_InfoType, &hash_info_desc); + SET_SYS_FROM_STRING("hash_info", + get_hash_info()); SET_SYS_FROM_STRING("maxunicode", PyLong_FromLong(PyUnicode_GetMax())); SET_SYS_FROM_STRING("builtin_module_names", @@ -1663,7 +1724,7 @@ #endif void -PySys_SetArgv(int argc, wchar_t **argv) +PySys_SetArgvEx(int argc, wchar_t **argv, int updatepath) { #if defined(HAVE_REALPATH) wchar_t fullpath[MAXPATHLEN]; @@ -1676,7 +1737,7 @@ Py_FatalError("no mem for sys.argv"); if (PySys_SetObject("argv", av) != 0) Py_FatalError("can't assign sys.argv"); - if (path != NULL) { + if (updatepath && path != NULL) { wchar_t *argv0 = argv[0]; wchar_t *p = NULL; Py_ssize_t n = 0; @@ -1763,6 +1824,12 @@ Py_DECREF(av); } +void +PySys_SetArgv(int argc, wchar_t **argv) +{ + PySys_SetArgvEx(argc, argv, 1); +} + /* Reimplementation of PyFile_WriteString() no calling indirectly PyErr_CheckSignals(): avoid the call to PyObject_Str(). */ Modified: python/branches/py3k-jit/Tools/gdb/libpython.py ============================================================================== --- python/branches/py3k-jit/Tools/gdb/libpython.py (original) +++ python/branches/py3k-jit/Tools/gdb/libpython.py Tue May 25 03:17:49 2010 @@ -42,6 +42,7 @@ ''' from __future__ import with_statement import gdb +import locale # Look up the gdb.Type for some standard types: _type_char_ptr = gdb.lookup_type('char').pointer() # char* @@ -69,6 +70,7 @@ hexdigits = "0123456789abcdef" +ENCODING = locale.getpreferredencoding() class NullPyObjectPtr(RuntimeError): pass @@ -1128,53 +1130,68 @@ # Non-ASCII characters else: - ucs = ch; - - if self.char_width == 2: - ch2 = 0 + ucs = ch + orig_ucs = None + if self.char_width() == 2: # Get code point from surrogate pair - if i < len(proxy): + if (i < len(proxy) + and 0xD800 <= ord(ch) < 0xDC00 \ + and 0xDC00 <= ord(proxy[i]) <= 0xDFFF): ch2 = proxy[i] - if (ord(ch) >= 0xD800 and ord(ch) < 0xDC00 - and ord(ch2) >= 0xDC00 and ord(ch2) <= 0xDFFF): - ucs = (((ch & 0x03FF) << 10) | (ch2 & 0x03FF)) + 0x00010000; - i += 1 + code = (ord(ch) & 0x03FF) << 10 + code |= ord(ch2) & 0x03FF + code += 0x00010000 + orig_ucs = ucs + ucs = unichr(code) + i += 1 + else: + ch2 = None + + printable = _unichr_is_printable(ucs) + if printable: + try: + ucs.encode(ENCODING) + except UnicodeEncodeError: + printable = False + if orig_ucs is not None: + ucs = orig_ucs + i -= 1 # Map Unicode whitespace and control characters # (categories Z* and C* except ASCII space) - if not _unichr_is_printable(ucs): + if not printable: # Unfortuately, Python 2's unicode type doesn't seem # to expose the "isprintable" method + code = ord(ucs) # Map 8-bit characters to '\\xhh' - if ucs <= 0xff: + if code <= 0xff: out.write('\\x') - out.write(hexdigits[(ord(ucs) >> 4) & 0x000F]) - out.write(hexdigits[ord(ucs) & 0x000F]) + out.write(hexdigits[(code >> 4) & 0x000F]) + out.write(hexdigits[code & 0x000F]) # Map 21-bit characters to '\U00xxxxxx' - elif ucs >= 0x10000: + elif code >= 0x10000: out.write('\\U') - out.write(hexdigits[(ord(ucs) >> 28) & 0x0000000F]) - out.write(hexdigits[(ord(ucs) >> 24) & 0x0000000F]) - out.write(hexdigits[(ord(ucs) >> 20) & 0x0000000F]) - out.write(hexdigits[(ord(ucs) >> 16) & 0x0000000F]) - out.write(hexdigits[(ord(ucs) >> 12) & 0x0000000F]) - out.write(hexdigits[(ord(ucs) >> 8) & 0x0000000F]) - out.write(hexdigits[(ord(ucs) >> 4) & 0x0000000F]) - out.write(hexdigits[ord(ucs) & 0x0000000F]) + out.write(hexdigits[(code >> 28) & 0x0000000F]) + out.write(hexdigits[(code >> 24) & 0x0000000F]) + out.write(hexdigits[(code >> 20) & 0x0000000F]) + out.write(hexdigits[(code >> 16) & 0x0000000F]) + out.write(hexdigits[(code >> 12) & 0x0000000F]) + out.write(hexdigits[(code >> 8) & 0x0000000F]) + out.write(hexdigits[(code >> 4) & 0x0000000F]) + out.write(hexdigits[code & 0x0000000F]) # Map 16-bit characters to '\uxxxx' else: out.write('\\u') - out.write(hexdigits[(ord(ucs) >> 12) & 0x000F]) - out.write(hexdigits[(ord(ucs) >> 8) & 0x000F]) - out.write(hexdigits[(ord(ucs) >> 4) & 0x000F]) - out.write(hexdigits[ord(ucs) & 0x000F]) + out.write(hexdigits[(code >> 12) & 0x000F]) + out.write(hexdigits[(code >> 8) & 0x000F]) + out.write(hexdigits[(code >> 4) & 0x000F]) + out.write(hexdigits[code & 0x000F]) else: # Copy characters as-is out.write(ch) - if self.char_width == 2: - if ord(ucs) >= 0x10000: - out.write(ch2) + if self.char_width() == 2 and (ch2 is not None): + out.write(ch2) out.write(quote) From python-checkins at python.org Tue May 25 04:23:32 2010 From: python-checkins at python.org (benjamin.peterson) Date: Tue, 25 May 2010 04:23:32 +0200 (CEST) Subject: [Python-checkins] r81509 - in python/trunk: configure configure.in Message-ID: <20100525022332.8D8E5EA93@mail.python.org> Author: benjamin.peterson Date: Tue May 25 04:23:32 2010 New Revision: 81509 Log: correct default docs Modified: python/trunk/configure python/trunk/configure.in Modified: python/trunk/configure ============================================================================== --- python/trunk/configure (original) +++ python/trunk/configure Tue May 25 04:23:32 2010 @@ -1,5 +1,5 @@ #! /bin/sh -# From configure.in Revision: 81004 . +# From configure.in Revision: 81077 . # Guess values for system-dependent variables and create Makefiles. # Generated by GNU Autoconf 2.65 for python 2.7. # @@ -1388,7 +1388,7 @@ --enable-big-digits[=BITS] use big digits for Python longs [[BITS=30]] --enable-unicode[=ucs[24]] - Enable Unicode strings (default is yes) + Enable Unicode strings (default is ucs2) Optional Packages: --with-PACKAGE[=ARG] use PACKAGE [ARG=yes] @@ -1934,11 +1934,11 @@ cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ $ac_includes_default - enum { N = $2 / 2 - 1 }; int main () { -static int test_array [1 - 2 * !(0 < ($ac_type) ((((($ac_type) 1 << N) << N) - 1) * 2 + 1))]; +static int test_array [1 - 2 * !(enum { N = $2 / 2 - 1 }; + 0 < ($ac_type) ((((($ac_type) 1 << N) << N) - 1) * 2 + 1))]; test_array [0] = 0 ; @@ -1949,11 +1949,11 @@ cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ $ac_includes_default - enum { N = $2 / 2 - 1 }; int main () { -static int test_array [1 - 2 * !(($ac_type) ((((($ac_type) 1 << N) << N) - 1) * 2 + 1) +static int test_array [1 - 2 * !(enum { N = $2 / 2 - 1 }; + ($ac_type) ((((($ac_type) 1 << N) << N) - 1) * 2 + 1) < ($ac_type) ((((($ac_type) 1 << N) << N) - 1) * 2 + 2))]; test_array [0] = 0 Modified: python/trunk/configure.in ============================================================================== --- python/trunk/configure.in (original) +++ python/trunk/configure.in Tue May 25 04:23:32 2010 @@ -3714,7 +3714,7 @@ AC_MSG_CHECKING(what type to use for unicode) dnl quadrigraphs "@<:@" and "@:>@" produce "[" and "]" in the output AC_ARG_ENABLE(unicode, - AS_HELP_STRING([--enable-unicode@<:@=ucs@<:@24@:>@@:>@], [Enable Unicode strings (default is yes)]), + AS_HELP_STRING([--enable-unicode@<:@=ucs@<:@24@:>@@:>@], [Enable Unicode strings (default is ucs2)]), [], [enable_unicode=yes]) From python-checkins at python.org Tue May 25 04:27:05 2010 From: python-checkins at python.org (benjamin.peterson) Date: Tue, 25 May 2010 04:27:05 +0200 (CEST) Subject: [Python-checkins] r81510 - in python/branches/release26-maint: configure configure.in Message-ID: <20100525022705.01503EE988@mail.python.org> Author: benjamin.peterson Date: Tue May 25 04:27:03 2010 New Revision: 81510 Log: Merged revisions 81509 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r81509 | benjamin.peterson | 2010-05-24 21:23:32 -0500 (Mon, 24 May 2010) | 1 line correct default docs ........ Modified: python/branches/release26-maint/ (props changed) python/branches/release26-maint/configure python/branches/release26-maint/configure.in Modified: python/branches/release26-maint/configure ============================================================================== --- python/branches/release26-maint/configure (original) +++ python/branches/release26-maint/configure Tue May 25 04:27:03 2010 @@ -1,21 +1,25 @@ #! /bin/sh -# From configure.in Revision: 80575 . +# From configure.in Revision: 80701 . # Guess values for system-dependent variables and create Makefiles. -# Generated by GNU Autoconf 2.63 for python 2.6. +# Generated by GNU Autoconf 2.65 for python 2.6. # # Report bugs to . # +# # Copyright (C) 1992, 1993, 1994, 1995, 1996, 1998, 1999, 2000, 2001, -# 2002, 2003, 2004, 2005, 2006, 2007, 2008 Free Software Foundation, Inc. +# 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009 Free Software Foundation, +# Inc. +# +# # This configure script is free software; the Free Software Foundation # gives unlimited permission to copy, distribute and modify it. -## --------------------- ## -## M4sh Initialization. ## -## --------------------- ## +## -------------------- ## +## M4sh Initialization. ## +## -------------------- ## # Be more Bourne compatible DUALCASE=1; export DUALCASE # for MKS sh -if test -n "${ZSH_VERSION+set}" && (emulate sh) >/dev/null 2>&1; then +if test -n "${ZSH_VERSION+set}" && (emulate sh) >/dev/null 2>&1; then : emulate sh NULLCMD=: # Pre-4.2 versions of Zsh do word splitting on ${1+"$@"}, which @@ -23,23 +27,15 @@ alias -g '${1+"$@"}'='"$@"' setopt NO_GLOB_SUBST else - case `(set -o) 2>/dev/null` in - *posix*) set -o posix ;; + case `(set -o) 2>/dev/null` in #( + *posix*) : + set -o posix ;; #( + *) : + ;; esac - fi - - -# PATH needs CR -# Avoid depending upon Character Ranges. -as_cr_letters='abcdefghijklmnopqrstuvwxyz' -as_cr_LETTERS='ABCDEFGHIJKLMNOPQRSTUVWXYZ' -as_cr_Letters=$as_cr_letters$as_cr_LETTERS -as_cr_digits='0123456789' -as_cr_alnum=$as_cr_Letters$as_cr_digits - as_nl=' ' export as_nl @@ -47,7 +43,13 @@ as_echo='\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\' as_echo=$as_echo$as_echo$as_echo$as_echo$as_echo as_echo=$as_echo$as_echo$as_echo$as_echo$as_echo$as_echo -if (test "X`printf %s $as_echo`" = "X$as_echo") 2>/dev/null; then +# Prefer a ksh shell builtin over an external printf program on Solaris, +# but without wasting forks for bash or zsh. +if test -z "$BASH_VERSION$ZSH_VERSION" \ + && (test "X`print -r -- $as_echo`" = "X$as_echo") 2>/dev/null; then + as_echo='print -r --' + as_echo_n='print -rn --' +elif (test "X`printf %s $as_echo`" = "X$as_echo") 2>/dev/null; then as_echo='printf %s\n' as_echo_n='printf %s' else @@ -58,7 +60,7 @@ as_echo_body='eval expr "X$1" : "X\\(.*\\)"' as_echo_n_body='eval arg=$1; - case $arg in + case $arg in #( *"$as_nl"*) expr "X$arg" : "X\\(.*\\)$as_nl"; arg=`expr "X$arg" : ".*$as_nl\\(.*\\)"`;; @@ -81,13 +83,6 @@ } fi -# Support unset when possible. -if ( (MAIL=60; unset MAIL) || exit) >/dev/null 2>&1; then - as_unset=unset -else - as_unset=false -fi - # IFS # We need space, tab and new line, in precisely that order. Quoting is @@ -97,15 +92,15 @@ IFS=" "" $as_nl" # Find who we are. Look in the path if we contain no directory separator. -case $0 in +case $0 in #(( *[\\/]* ) as_myself=$0 ;; *) as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $PATH do IFS=$as_save_IFS test -z "$as_dir" && as_dir=. - test -r "$as_dir/$0" && as_myself=$as_dir/$0 && break -done + test -r "$as_dir/$0" && as_myself=$as_dir/$0 && break + done IFS=$as_save_IFS ;; @@ -117,12 +112,16 @@ fi if test ! -f "$as_myself"; then $as_echo "$as_myself: error: cannot find myself; rerun with an absolute file name" >&2 - { (exit 1); exit 1; } + exit 1 fi -# Work around bugs in pre-3.0 UWIN ksh. -for as_var in ENV MAIL MAILPATH -do ($as_unset $as_var) >/dev/null 2>&1 && $as_unset $as_var +# Unset variables that we do not need and which cause bugs (e.g. in +# pre-3.0 UWIN ksh). But do not cause bugs in bash 2.01; the "|| exit 1" +# suppresses any "Segmentation fault" message there. '((' could +# trigger a bug in pdksh 5.2.14. +for as_var in BASH_ENV ENV MAIL MAILPATH +do eval test x\${$as_var+set} = xset \ + && ( (unset $as_var) || exit 1) >/dev/null 2>&1 && unset $as_var || : done PS1='$ ' PS2='> ' @@ -134,330 +133,300 @@ LANGUAGE=C export LANGUAGE -# Required to use basename. -if expr a : '\(a\)' >/dev/null 2>&1 && - test "X`expr 00001 : '.*\(...\)'`" = X001; then - as_expr=expr -else - as_expr=false -fi - -if (basename -- /) >/dev/null 2>&1 && test "X`basename -- / 2>&1`" = "X/"; then - as_basename=basename -else - as_basename=false -fi - - -# Name of the executable. -as_me=`$as_basename -- "$0" || -$as_expr X/"$0" : '.*/\([^/][^/]*\)/*$' \| \ - X"$0" : 'X\(//\)$' \| \ - X"$0" : 'X\(/\)' \| . 2>/dev/null || -$as_echo X/"$0" | - sed '/^.*\/\([^/][^/]*\)\/*$/{ - s//\1/ - q - } - /^X\/\(\/\/\)$/{ - s//\1/ - q - } - /^X\/\(\/\).*/{ - s//\1/ - q - } - s/.*/./; q'` - # CDPATH. -$as_unset CDPATH - +(unset CDPATH) >/dev/null 2>&1 && unset CDPATH if test "x$CONFIG_SHELL" = x; then - if (eval ":") 2>/dev/null; then - as_have_required=yes + as_bourne_compatible="if test -n \"\${ZSH_VERSION+set}\" && (emulate sh) >/dev/null 2>&1; then : + emulate sh + NULLCMD=: + # Pre-4.2 versions of Zsh do word splitting on \${1+\"\$@\"}, which + # is contrary to our usage. Disable this feature. + alias -g '\${1+\"\$@\"}'='\"\$@\"' + setopt NO_GLOB_SUBST else - as_have_required=no + case \`(set -o) 2>/dev/null\` in #( + *posix*) : + set -o posix ;; #( + *) : + ;; +esac fi - - if test $as_have_required = yes && (eval ": -(as_func_return () { - (exit \$1) -} -as_func_success () { - as_func_return 0 -} -as_func_failure () { - as_func_return 1 -} -as_func_ret_success () { - return 0 -} -as_func_ret_failure () { - return 1 -} +" + as_required="as_fn_return () { (exit \$1); } +as_fn_success () { as_fn_return 0; } +as_fn_failure () { as_fn_return 1; } +as_fn_ret_success () { return 0; } +as_fn_ret_failure () { return 1; } exitcode=0 -if as_func_success; then - : -else - exitcode=1 - echo as_func_success failed. -fi - -if as_func_failure; then - exitcode=1 - echo as_func_failure succeeded. -fi - -if as_func_ret_success; then - : -else - exitcode=1 - echo as_func_ret_success failed. -fi - -if as_func_ret_failure; then - exitcode=1 - echo as_func_ret_failure succeeded. -fi - -if ( set x; as_func_ret_success y && test x = \"\$1\" ); then - : +as_fn_success || { exitcode=1; echo as_fn_success failed.; } +as_fn_failure && { exitcode=1; echo as_fn_failure succeeded.; } +as_fn_ret_success || { exitcode=1; echo as_fn_ret_success failed.; } +as_fn_ret_failure && { exitcode=1; echo as_fn_ret_failure succeeded.; } +if ( set x; as_fn_ret_success y && test x = \"\$1\" ); then : + +else + exitcode=1; echo positional parameters were not saved. +fi +test x\$exitcode = x0 || exit 1" + as_suggested=" as_lineno_1=";as_suggested=$as_suggested$LINENO;as_suggested=$as_suggested" as_lineno_1a=\$LINENO + as_lineno_2=";as_suggested=$as_suggested$LINENO;as_suggested=$as_suggested" as_lineno_2a=\$LINENO + eval 'test \"x\$as_lineno_1'\$as_run'\" != \"x\$as_lineno_2'\$as_run'\" && + test \"x\`expr \$as_lineno_1'\$as_run' + 1\`\" = \"x\$as_lineno_2'\$as_run'\"' || exit 1 +test \$(( 1 + 1 )) = 2 || exit 1" + if (eval "$as_required") 2>/dev/null; then : + as_have_required=yes else - exitcode=1 - echo positional parameters were not saved. + as_have_required=no fi + if test x$as_have_required = xyes && (eval "$as_suggested") 2>/dev/null; then : -test \$exitcode = 0) || { (exit 1); exit 1; } - -( - as_lineno_1=\$LINENO - as_lineno_2=\$LINENO - test \"x\$as_lineno_1\" != \"x\$as_lineno_2\" && - test \"x\`expr \$as_lineno_1 + 1\`\" = \"x\$as_lineno_2\") || { (exit 1); exit 1; } -") 2> /dev/null; then - : else - as_candidate_shells= - as_save_IFS=$IFS; IFS=$PATH_SEPARATOR + as_save_IFS=$IFS; IFS=$PATH_SEPARATOR +as_found=false for as_dir in /bin$PATH_SEPARATOR/usr/bin$PATH_SEPARATOR$PATH do IFS=$as_save_IFS test -z "$as_dir" && as_dir=. - case $as_dir in + as_found=: + case $as_dir in #( /*) for as_base in sh bash ksh sh5; do - as_candidate_shells="$as_candidate_shells $as_dir/$as_base" + # Try only shells that exist, to save several forks. + as_shell=$as_dir/$as_base + if { test -f "$as_shell" || test -f "$as_shell.exe"; } && + { $as_echo "$as_bourne_compatible""$as_required" | as_run=a "$as_shell"; } 2>/dev/null; then : + CONFIG_SHELL=$as_shell as_have_required=yes + if { $as_echo "$as_bourne_compatible""$as_suggested" | as_run=a "$as_shell"; } 2>/dev/null; then : + break 2 +fi +fi done;; esac + as_found=false done +$as_found || { if { test -f "$SHELL" || test -f "$SHELL.exe"; } && + { $as_echo "$as_bourne_compatible""$as_required" | as_run=a "$SHELL"; } 2>/dev/null; then : + CONFIG_SHELL=$SHELL as_have_required=yes +fi; } IFS=$as_save_IFS - for as_shell in $as_candidate_shells $SHELL; do - # Try only shells that exist, to save several forks. - if { test -f "$as_shell" || test -f "$as_shell.exe"; } && - { ("$as_shell") 2> /dev/null <<\_ASEOF -if test -n "${ZSH_VERSION+set}" && (emulate sh) >/dev/null 2>&1; then - emulate sh - NULLCMD=: - # Pre-4.2 versions of Zsh do word splitting on ${1+"$@"}, which - # is contrary to our usage. Disable this feature. - alias -g '${1+"$@"}'='"$@"' - setopt NO_GLOB_SUBST -else - case `(set -o) 2>/dev/null` in - *posix*) set -o posix ;; -esac - -fi - - -: -_ASEOF -}; then - CONFIG_SHELL=$as_shell - as_have_required=yes - if { "$as_shell" 2> /dev/null <<\_ASEOF -if test -n "${ZSH_VERSION+set}" && (emulate sh) >/dev/null 2>&1; then - emulate sh - NULLCMD=: - # Pre-4.2 versions of Zsh do word splitting on ${1+"$@"}, which - # is contrary to our usage. Disable this feature. - alias -g '${1+"$@"}'='"$@"' - setopt NO_GLOB_SUBST -else - case `(set -o) 2>/dev/null` in - *posix*) set -o posix ;; -esac - -fi - - -: -(as_func_return () { - (exit $1) -} -as_func_success () { - as_func_return 0 -} -as_func_failure () { - as_func_return 1 -} -as_func_ret_success () { - return 0 -} -as_func_ret_failure () { - return 1 -} - -exitcode=0 -if as_func_success; then - : -else - exitcode=1 - echo as_func_success failed. -fi - -if as_func_failure; then - exitcode=1 - echo as_func_failure succeeded. -fi - -if as_func_ret_success; then - : -else - exitcode=1 - echo as_func_ret_success failed. -fi - -if as_func_ret_failure; then - exitcode=1 - echo as_func_ret_failure succeeded. -fi - -if ( set x; as_func_ret_success y && test x = "$1" ); then - : -else - exitcode=1 - echo positional parameters were not saved. -fi - -test $exitcode = 0) || { (exit 1); exit 1; } - -( - as_lineno_1=$LINENO - as_lineno_2=$LINENO - test "x$as_lineno_1" != "x$as_lineno_2" && - test "x`expr $as_lineno_1 + 1`" = "x$as_lineno_2") || { (exit 1); exit 1; } - -_ASEOF -}; then - break -fi - -fi - - done - - if test "x$CONFIG_SHELL" != x; then - for as_var in BASH_ENV ENV - do ($as_unset $as_var) >/dev/null 2>&1 && $as_unset $as_var - done + if test "x$CONFIG_SHELL" != x; then : + # We cannot yet assume a decent shell, so we have to provide a + # neutralization value for shells without unset; and this also + # works around shells that cannot unset nonexistent variables. + BASH_ENV=/dev/null + ENV=/dev/null + (unset BASH_ENV) >/dev/null 2>&1 && unset BASH_ENV ENV export CONFIG_SHELL exec "$CONFIG_SHELL" "$as_myself" ${1+"$@"} fi - - if test $as_have_required = no; then - echo This script requires a shell more modern than all the - echo shells that I found on your system. Please install a - echo modern shell, or manually run the script under such a - echo shell if you do have one. - { (exit 1); exit 1; } + if test x$as_have_required = xno; then : + $as_echo "$0: This script requires a shell more modern than all" + $as_echo "$0: the shells that I found on your system." + if test x${ZSH_VERSION+set} = xset ; then + $as_echo "$0: In particular, zsh $ZSH_VERSION has bugs and should" + $as_echo "$0: be upgraded to zsh 4.3.4 or later." + else + $as_echo "$0: Please tell bug-autoconf at gnu.org and +$0: http://www.python.org/python-bugs about your system, +$0: including any error possibly output before this +$0: message. Then install a modern shell, or manually run +$0: the script under such a shell if you do have one." + fi + exit 1 fi - - fi - fi +SHELL=${CONFIG_SHELL-/bin/sh} +export SHELL +# Unset more variables known to interfere with behavior of common tools. +CLICOLOR_FORCE= GREP_OPTIONS= +unset CLICOLOR_FORCE GREP_OPTIONS + +## --------------------- ## +## M4sh Shell Functions. ## +## --------------------- ## +# as_fn_unset VAR +# --------------- +# Portably unset VAR. +as_fn_unset () +{ + { eval $1=; unset $1;} +} +as_unset=as_fn_unset + +# as_fn_set_status STATUS +# ----------------------- +# Set $? to STATUS, without forking. +as_fn_set_status () +{ + return $1 +} # as_fn_set_status + +# as_fn_exit STATUS +# ----------------- +# Exit the shell with STATUS, even in a "trap 0" or "set -e" context. +as_fn_exit () +{ + set +e + as_fn_set_status $1 + exit $1 +} # as_fn_exit + +# as_fn_mkdir_p +# ------------- +# Create "$as_dir" as a directory, including parents if necessary. +as_fn_mkdir_p () +{ + case $as_dir in #( + -*) as_dir=./$as_dir;; + esac + test -d "$as_dir" || eval $as_mkdir_p || { + as_dirs= + while :; do + case $as_dir in #( + *\'*) as_qdir=`$as_echo "$as_dir" | sed "s/'/'\\\\\\\\''/g"`;; #'( + *) as_qdir=$as_dir;; + esac + as_dirs="'$as_qdir' $as_dirs" + as_dir=`$as_dirname -- "$as_dir" || +$as_expr X"$as_dir" : 'X\(.*[^/]\)//*[^/][^/]*/*$' \| \ + X"$as_dir" : 'X\(//\)[^/]' \| \ + X"$as_dir" : 'X\(//\)$' \| \ + X"$as_dir" : 'X\(/\)' \| . 2>/dev/null || +$as_echo X"$as_dir" | + sed '/^X\(.*[^/]\)\/\/*[^/][^/]*\/*$/{ + s//\1/ + q + } + /^X\(\/\/\)[^/].*/{ + s//\1/ + q + } + /^X\(\/\/\)$/{ + s//\1/ + q + } + /^X\(\/\).*/{ + s//\1/ + q + } + s/.*/./; q'` + test -d "$as_dir" && break + done + test -z "$as_dirs" || eval "mkdir $as_dirs" + } || test -d "$as_dir" || as_fn_error "cannot create directory $as_dir" -(eval "as_func_return () { - (exit \$1) -} -as_func_success () { - as_func_return 0 -} -as_func_failure () { - as_func_return 1 -} -as_func_ret_success () { - return 0 -} -as_func_ret_failure () { - return 1 -} +} # as_fn_mkdir_p +# as_fn_append VAR VALUE +# ---------------------- +# Append the text in VALUE to the end of the definition contained in VAR. Take +# advantage of any shell optimizations that allow amortized linear growth over +# repeated appends, instead of the typical quadratic growth present in naive +# implementations. +if (eval "as_var=1; as_var+=2; test x\$as_var = x12") 2>/dev/null; then : + eval 'as_fn_append () + { + eval $1+=\$2 + }' +else + as_fn_append () + { + eval $1=\$$1\$2 + } +fi # as_fn_append -exitcode=0 -if as_func_success; then - : +# as_fn_arith ARG... +# ------------------ +# Perform arithmetic evaluation on the ARGs, and store the result in the +# global $as_val. Take advantage of shells that can avoid forks. The arguments +# must be portable across $(()) and expr. +if (eval "test \$(( 1 + 1 )) = 2") 2>/dev/null; then : + eval 'as_fn_arith () + { + as_val=$(( $* )) + }' else - exitcode=1 - echo as_func_success failed. -fi + as_fn_arith () + { + as_val=`expr "$@" || test $? -eq 1` + } +fi # as_fn_arith -if as_func_failure; then - exitcode=1 - echo as_func_failure succeeded. -fi -if as_func_ret_success; then - : +# as_fn_error ERROR [LINENO LOG_FD] +# --------------------------------- +# Output "`basename $0`: error: ERROR" to stderr. If LINENO and LOG_FD are +# provided, also output the error to LOG_FD, referencing LINENO. Then exit the +# script with status $?, using 1 if that was 0. +as_fn_error () +{ + as_status=$?; test $as_status -eq 0 && as_status=1 + if test "$3"; then + as_lineno=${as_lineno-"$2"} as_lineno_stack=as_lineno_stack=$as_lineno_stack + $as_echo "$as_me:${as_lineno-$LINENO}: error: $1" >&$3 + fi + $as_echo "$as_me: error: $1" >&2 + as_fn_exit $as_status +} # as_fn_error + +if expr a : '\(a\)' >/dev/null 2>&1 && + test "X`expr 00001 : '.*\(...\)'`" = X001; then + as_expr=expr else - exitcode=1 - echo as_func_ret_success failed. + as_expr=false fi -if as_func_ret_failure; then - exitcode=1 - echo as_func_ret_failure succeeded. +if (basename -- /) >/dev/null 2>&1 && test "X`basename -- / 2>&1`" = "X/"; then + as_basename=basename +else + as_basename=false fi -if ( set x; as_func_ret_success y && test x = \"\$1\" ); then - : +if (as_dir=`dirname -- /` && test "X$as_dir" = X/) >/dev/null 2>&1; then + as_dirname=dirname else - exitcode=1 - echo positional parameters were not saved. + as_dirname=false fi -test \$exitcode = 0") || { - echo No shell found that supports shell functions. - echo Please tell bug-autoconf at gnu.org about your system, - echo including any error possibly output before this message. - echo This can help us improve future autoconf versions. - echo Configuration will now proceed without shell functions. -} +as_me=`$as_basename -- "$0" || +$as_expr X/"$0" : '.*/\([^/][^/]*\)/*$' \| \ + X"$0" : 'X\(//\)$' \| \ + X"$0" : 'X\(/\)' \| . 2>/dev/null || +$as_echo X/"$0" | + sed '/^.*\/\([^/][^/]*\)\/*$/{ + s//\1/ + q + } + /^X\/\(\/\/\)$/{ + s//\1/ + q + } + /^X\/\(\/\).*/{ + s//\1/ + q + } + s/.*/./; q'` +# Avoid depending upon Character Ranges. +as_cr_letters='abcdefghijklmnopqrstuvwxyz' +as_cr_LETTERS='ABCDEFGHIJKLMNOPQRSTUVWXYZ' +as_cr_Letters=$as_cr_letters$as_cr_LETTERS +as_cr_digits='0123456789' +as_cr_alnum=$as_cr_Letters$as_cr_digits - as_lineno_1=$LINENO - as_lineno_2=$LINENO - test "x$as_lineno_1" != "x$as_lineno_2" && - test "x`expr $as_lineno_1 + 1`" = "x$as_lineno_2" || { - - # Create $as_me.lineno as a copy of $as_myself, but with $LINENO - # uniformly replaced by the line number. The first 'sed' inserts a - # line-number line after each line using $LINENO; the second 'sed' - # does the real work. The second script uses 'N' to pair each - # line-number line with the line containing $LINENO, and appends - # trailing '-' during substitution so that $LINENO is not a special - # case at line end. - # (Raja R Harinath suggested sed '=', and Paul Eggert wrote the - # scripts with optimization help from Paolo Bonzini. Blame Lee - # E. McMahon (1931-1989) for sed's syntax. :-) + as_lineno_1=$LINENO as_lineno_1a=$LINENO + as_lineno_2=$LINENO as_lineno_2a=$LINENO + eval 'test "x$as_lineno_1'$as_run'" != "x$as_lineno_2'$as_run'" && + test "x`expr $as_lineno_1'$as_run' + 1`" = "x$as_lineno_2'$as_run'"' || { + # Blame Lee E. McMahon (1931-1989) for sed's syntax. :-) sed -n ' p /[$]LINENO/= @@ -474,8 +443,7 @@ s/-\n.*// ' >$as_me.lineno && chmod +x "$as_me.lineno" || - { $as_echo "$as_me: error: cannot create $as_me.lineno; rerun with a POSIX shell" >&2 - { (exit 1); exit 1; }; } + { $as_echo "$as_me: error: cannot create $as_me.lineno; rerun with a POSIX shell" >&2; as_fn_exit 1; } # Don't try to exec as it changes $[0], causing all sort of problems # (the dirname of $[0] is not the place where we might find the @@ -485,29 +453,18 @@ exit } - -if (as_dir=`dirname -- /` && test "X$as_dir" = X/) >/dev/null 2>&1; then - as_dirname=dirname -else - as_dirname=false -fi - ECHO_C= ECHO_N= ECHO_T= -case `echo -n x` in +case `echo -n x` in #((((( -n*) - case `echo 'x\c'` in + case `echo 'xy\c'` in *c*) ECHO_T=' ';; # ECHO_T is single tab character. - *) ECHO_C='\c';; + xy) ECHO_C='\c';; + *) echo `echo ksh88 bug on AIX 6.1` > /dev/null + ECHO_T=' ';; esac;; *) ECHO_N='-n';; esac -if expr a : '\(a\)' >/dev/null 2>&1 && - test "X`expr 00001 : '.*\(...\)'`" = X001; then - as_expr=expr -else - as_expr=false -fi rm -f conf$$ conf$$.exe conf$$.file if test -d conf$$.dir; then @@ -537,7 +494,7 @@ rmdir conf$$.dir 2>/dev/null if mkdir -p . 2>/dev/null; then - as_mkdir_p=: + as_mkdir_p='mkdir -p "$as_dir"' else test -d ./-p && rmdir ./-p as_mkdir_p=false @@ -556,10 +513,10 @@ if test -d "$1"; then test -d "$1/."; else - case $1 in + case $1 in #( -*)set "./$1";; esac; - case `ls -ld'$as_ls_L_option' "$1" 2>/dev/null` in + case `ls -ld'$as_ls_L_option' "$1" 2>/dev/null` in #(( ???[sx]*):;;*)false;;esac;fi '\'' sh ' @@ -573,8 +530,8 @@ as_tr_sh="eval sed 'y%*+%pp%;s%[^_$as_cr_alnum]%_%g'" - -exec 7<&0 &1 +test -n "$DJDIR" || exec 7<&0 &1 # Name of the host. # hostname on some systems (SVR3.2, Linux) returns a bogus exit status, @@ -592,7 +549,6 @@ subdirs= MFLAGS= MAKEFLAGS= -SHELL=${CONFIG_SHELL-/bin/sh} # Identity of this package. PACKAGE_NAME='python' @@ -600,6 +556,7 @@ PACKAGE_VERSION='2.6' PACKAGE_STRING='python 2.6' PACKAGE_BUGREPORT='http://www.python.org/python-bugs' +PACKAGE_URL='' ac_unique_file="Include/object.h" # Factoring default headers for most tests. @@ -752,6 +709,7 @@ program_transform_name prefix exec_prefix +PACKAGE_URL PACKAGE_BUGREPORT PACKAGE_STRING PACKAGE_VERSION @@ -907,8 +865,7 @@ ac_useropt=`expr "x$ac_option" : 'x-*disable-\(.*\)'` # Reject names that are not valid shell variable names. expr "x$ac_useropt" : ".*[^-+._$as_cr_alnum]" >/dev/null && - { $as_echo "$as_me: error: invalid feature name: $ac_useropt" >&2 - { (exit 1); exit 1; }; } + as_fn_error "invalid feature name: $ac_useropt" ac_useropt_orig=$ac_useropt ac_useropt=`$as_echo "$ac_useropt" | sed 's/[-+.]/_/g'` case $ac_user_opts in @@ -934,8 +891,7 @@ ac_useropt=`expr "x$ac_option" : 'x-*enable-\([^=]*\)'` # Reject names that are not valid shell variable names. expr "x$ac_useropt" : ".*[^-+._$as_cr_alnum]" >/dev/null && - { $as_echo "$as_me: error: invalid feature name: $ac_useropt" >&2 - { (exit 1); exit 1; }; } + as_fn_error "invalid feature name: $ac_useropt" ac_useropt_orig=$ac_useropt ac_useropt=`$as_echo "$ac_useropt" | sed 's/[-+.]/_/g'` case $ac_user_opts in @@ -1139,8 +1095,7 @@ ac_useropt=`expr "x$ac_option" : 'x-*with-\([^=]*\)'` # Reject names that are not valid shell variable names. expr "x$ac_useropt" : ".*[^-+._$as_cr_alnum]" >/dev/null && - { $as_echo "$as_me: error: invalid package name: $ac_useropt" >&2 - { (exit 1); exit 1; }; } + as_fn_error "invalid package name: $ac_useropt" ac_useropt_orig=$ac_useropt ac_useropt=`$as_echo "$ac_useropt" | sed 's/[-+.]/_/g'` case $ac_user_opts in @@ -1156,8 +1111,7 @@ ac_useropt=`expr "x$ac_option" : 'x-*without-\(.*\)'` # Reject names that are not valid shell variable names. expr "x$ac_useropt" : ".*[^-+._$as_cr_alnum]" >/dev/null && - { $as_echo "$as_me: error: invalid package name: $ac_useropt" >&2 - { (exit 1); exit 1; }; } + as_fn_error "invalid package name: $ac_useropt" ac_useropt_orig=$ac_useropt ac_useropt=`$as_echo "$ac_useropt" | sed 's/[-+.]/_/g'` case $ac_user_opts in @@ -1187,17 +1141,17 @@ | --x-librar=* | --x-libra=* | --x-libr=* | --x-lib=* | --x-li=* | --x-l=*) x_libraries=$ac_optarg ;; - -*) { $as_echo "$as_me: error: unrecognized option: $ac_option -Try \`$0 --help' for more information." >&2 - { (exit 1); exit 1; }; } + -*) as_fn_error "unrecognized option: \`$ac_option' +Try \`$0 --help' for more information." ;; *=*) ac_envvar=`expr "x$ac_option" : 'x\([^=]*\)='` # Reject names that are not valid shell variable names. - expr "x$ac_envvar" : ".*[^_$as_cr_alnum]" >/dev/null && - { $as_echo "$as_me: error: invalid variable name: $ac_envvar" >&2 - { (exit 1); exit 1; }; } + case $ac_envvar in #( + '' | [0-9]* | *[!_$as_cr_alnum]* ) + as_fn_error "invalid variable name: \`$ac_envvar'" ;; + esac eval $ac_envvar=\$ac_optarg export $ac_envvar ;; @@ -1214,15 +1168,13 @@ if test -n "$ac_prev"; then ac_option=--`echo $ac_prev | sed 's/_/-/g'` - { $as_echo "$as_me: error: missing argument to $ac_option" >&2 - { (exit 1); exit 1; }; } + as_fn_error "missing argument to $ac_option" fi if test -n "$ac_unrecognized_opts"; then case $enable_option_checking in no) ;; - fatal) { $as_echo "$as_me: error: unrecognized options: $ac_unrecognized_opts" >&2 - { (exit 1); exit 1; }; } ;; + fatal) as_fn_error "unrecognized options: $ac_unrecognized_opts" ;; *) $as_echo "$as_me: WARNING: unrecognized options: $ac_unrecognized_opts" >&2 ;; esac fi @@ -1245,8 +1197,7 @@ [\\/$]* | ?:[\\/]* ) continue;; NONE | '' ) case $ac_var in *prefix ) continue;; esac;; esac - { $as_echo "$as_me: error: expected an absolute directory name for --$ac_var: $ac_val" >&2 - { (exit 1); exit 1; }; } + as_fn_error "expected an absolute directory name for --$ac_var: $ac_val" done # There might be people who depend on the old broken behavior: `$host' @@ -1276,11 +1227,9 @@ ac_pwd=`pwd` && test -n "$ac_pwd" && ac_ls_di=`ls -di .` && ac_pwd_ls_di=`cd "$ac_pwd" && ls -di .` || - { $as_echo "$as_me: error: working directory cannot be determined" >&2 - { (exit 1); exit 1; }; } + as_fn_error "working directory cannot be determined" test "X$ac_ls_di" = "X$ac_pwd_ls_di" || - { $as_echo "$as_me: error: pwd does not report name of working directory" >&2 - { (exit 1); exit 1; }; } + as_fn_error "pwd does not report name of working directory" # Find the source files, if location was not specified. @@ -1319,13 +1268,11 @@ fi if test ! -r "$srcdir/$ac_unique_file"; then test "$ac_srcdir_defaulted" = yes && srcdir="$ac_confdir or .." - { $as_echo "$as_me: error: cannot find sources ($ac_unique_file) in $srcdir" >&2 - { (exit 1); exit 1; }; } + as_fn_error "cannot find sources ($ac_unique_file) in $srcdir" fi ac_msg="sources are in $srcdir, but \`cd $srcdir' does not work" ac_abs_confdir=`( - cd "$srcdir" && test -r "./$ac_unique_file" || { $as_echo "$as_me: error: $ac_msg" >&2 - { (exit 1); exit 1; }; } + cd "$srcdir" && test -r "./$ac_unique_file" || as_fn_error "$ac_msg" pwd)` # When building in place, set srcdir=. if test "$ac_abs_confdir" = "$ac_pwd"; then @@ -1430,7 +1377,7 @@ --enable-ipv6 Enable ipv6 (with ipv4) support --disable-ipv6 Disable ipv6 support --enable-unicode[=ucs[24]] - Enable Unicode strings (default is yes) + Enable Unicode strings (default is ucs2) Optional Packages: --with-PACKAGE[=ARG] use PACKAGE [ARG=yes] @@ -1470,7 +1417,7 @@ LDFLAGS linker flags, e.g. -L if you have libraries in a nonstandard directory LIBS libraries to pass to the linker, e.g. -l - CPPFLAGS C/C++/Objective C preprocessor flags, e.g. -I if + CPPFLAGS (Objective) C/C++ preprocessor flags, e.g. -I if you have headers in a nonstandard directory CPP C preprocessor @@ -1541,2462 +1488,2116 @@ if $ac_init_version; then cat <<\_ACEOF python configure 2.6 -generated by GNU Autoconf 2.63 +generated by GNU Autoconf 2.65 -Copyright (C) 1992, 1993, 1994, 1995, 1996, 1998, 1999, 2000, 2001, -2002, 2003, 2004, 2005, 2006, 2007, 2008 Free Software Foundation, Inc. +Copyright (C) 2009 Free Software Foundation, Inc. This configure script is free software; the Free Software Foundation gives unlimited permission to copy, distribute and modify it. _ACEOF exit fi -cat >config.log <<_ACEOF -This file contains any messages produced by compilers while -running configure, to aid debugging if configure makes a mistake. -It was created by python $as_me 2.6, which was -generated by GNU Autoconf 2.63. Invocation command line was +## ------------------------ ## +## Autoconf initialization. ## +## ------------------------ ## + +# ac_fn_c_try_compile LINENO +# -------------------------- +# Try to compile conftest.$ac_ext, and return whether this succeeded. +ac_fn_c_try_compile () +{ + as_lineno=${as_lineno-"$1"} as_lineno_stack=as_lineno_stack=$as_lineno_stack + rm -f conftest.$ac_objext + if { { ac_try="$ac_compile" +case "(($ac_try" in + *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; + *) ac_try_echo=$ac_try;; +esac +eval ac_try_echo="\"\$as_me:${as_lineno-$LINENO}: $ac_try_echo\"" +$as_echo "$ac_try_echo"; } >&5 + (eval "$ac_compile") 2>conftest.err + ac_status=$? + if test -s conftest.err; then + grep -v '^ *+' conftest.err >conftest.er1 + cat conftest.er1 >&5 + mv -f conftest.er1 conftest.err + fi + $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 + test $ac_status = 0; } && { + test -z "$ac_c_werror_flag" || + test ! -s conftest.err + } && test -s conftest.$ac_objext; then : + ac_retval=0 +else + $as_echo "$as_me: failed program was:" >&5 +sed 's/^/| /' conftest.$ac_ext >&5 - $ $0 $@ + ac_retval=1 +fi + eval $as_lineno_stack; test "x$as_lineno_stack" = x && { as_lineno=; unset as_lineno;} + as_fn_set_status $ac_retval -_ACEOF -exec 5>>config.log +} # ac_fn_c_try_compile + +# ac_fn_c_try_cpp LINENO +# ---------------------- +# Try to preprocess conftest.$ac_ext, and return whether this succeeded. +ac_fn_c_try_cpp () { -cat <<_ASUNAME -## --------- ## -## Platform. ## -## --------- ## + as_lineno=${as_lineno-"$1"} as_lineno_stack=as_lineno_stack=$as_lineno_stack + if { { ac_try="$ac_cpp conftest.$ac_ext" +case "(($ac_try" in + *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; + *) ac_try_echo=$ac_try;; +esac +eval ac_try_echo="\"\$as_me:${as_lineno-$LINENO}: $ac_try_echo\"" +$as_echo "$ac_try_echo"; } >&5 + (eval "$ac_cpp conftest.$ac_ext") 2>conftest.err + ac_status=$? + if test -s conftest.err; then + grep -v '^ *+' conftest.err >conftest.er1 + cat conftest.er1 >&5 + mv -f conftest.er1 conftest.err + fi + $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 + test $ac_status = 0; } >/dev/null && { + test -z "$ac_c_preproc_warn_flag$ac_c_werror_flag" || + test ! -s conftest.err + }; then : + ac_retval=0 +else + $as_echo "$as_me: failed program was:" >&5 +sed 's/^/| /' conftest.$ac_ext >&5 -hostname = `(hostname || uname -n) 2>/dev/null | sed 1q` -uname -m = `(uname -m) 2>/dev/null || echo unknown` -uname -r = `(uname -r) 2>/dev/null || echo unknown` -uname -s = `(uname -s) 2>/dev/null || echo unknown` -uname -v = `(uname -v) 2>/dev/null || echo unknown` + ac_retval=1 +fi + eval $as_lineno_stack; test "x$as_lineno_stack" = x && { as_lineno=; unset as_lineno;} + as_fn_set_status $ac_retval -/usr/bin/uname -p = `(/usr/bin/uname -p) 2>/dev/null || echo unknown` -/bin/uname -X = `(/bin/uname -X) 2>/dev/null || echo unknown` +} # ac_fn_c_try_cpp -/bin/arch = `(/bin/arch) 2>/dev/null || echo unknown` -/usr/bin/arch -k = `(/usr/bin/arch -k) 2>/dev/null || echo unknown` -/usr/convex/getsysinfo = `(/usr/convex/getsysinfo) 2>/dev/null || echo unknown` -/usr/bin/hostinfo = `(/usr/bin/hostinfo) 2>/dev/null || echo unknown` -/bin/machine = `(/bin/machine) 2>/dev/null || echo unknown` -/usr/bin/oslevel = `(/usr/bin/oslevel) 2>/dev/null || echo unknown` -/bin/universe = `(/bin/universe) 2>/dev/null || echo unknown` +# ac_fn_c_check_header_mongrel LINENO HEADER VAR INCLUDES +# ------------------------------------------------------- +# Tests whether HEADER exists, giving a warning if it cannot be compiled using +# the include files in INCLUDES and setting the cache variable VAR +# accordingly. +ac_fn_c_check_header_mongrel () +{ + as_lineno=${as_lineno-"$1"} as_lineno_stack=as_lineno_stack=$as_lineno_stack + if { as_var=$3; eval "test \"\${$as_var+set}\" = set"; }; then : + { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $2" >&5 +$as_echo_n "checking for $2... " >&6; } +if { as_var=$3; eval "test \"\${$as_var+set}\" = set"; }; then : + $as_echo_n "(cached) " >&6 +fi +eval ac_res=\$$3 + { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_res" >&5 +$as_echo "$ac_res" >&6; } +else + # Is the header compilable? +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking $2 usability" >&5 +$as_echo_n "checking $2 usability... " >&6; } +cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ +$4 +#include <$2> +_ACEOF +if ac_fn_c_try_compile "$LINENO"; then : + ac_header_compiler=yes +else + ac_header_compiler=no +fi +rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_header_compiler" >&5 +$as_echo "$ac_header_compiler" >&6; } -_ASUNAME +# Is the header present? +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking $2 presence" >&5 +$as_echo_n "checking $2 presence... " >&6; } +cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ +#include <$2> +_ACEOF +if ac_fn_c_try_cpp "$LINENO"; then : + ac_header_preproc=yes +else + ac_header_preproc=no +fi +rm -f conftest.err conftest.$ac_ext +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_header_preproc" >&5 +$as_echo "$ac_header_preproc" >&6; } -as_save_IFS=$IFS; IFS=$PATH_SEPARATOR -for as_dir in $PATH -do - IFS=$as_save_IFS - test -z "$as_dir" && as_dir=. - $as_echo "PATH: $as_dir" -done -IFS=$as_save_IFS +# So? What about this header? +case $ac_header_compiler:$ac_header_preproc:$ac_c_preproc_warn_flag in #(( + yes:no: ) + { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: $2: accepted by the compiler, rejected by the preprocessor!" >&5 +$as_echo "$as_me: WARNING: $2: accepted by the compiler, rejected by the preprocessor!" >&2;} + { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: $2: proceeding with the compiler's result" >&5 +$as_echo "$as_me: WARNING: $2: proceeding with the compiler's result" >&2;} + ;; + no:yes:* ) + { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: $2: present but cannot be compiled" >&5 +$as_echo "$as_me: WARNING: $2: present but cannot be compiled" >&2;} + { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: $2: check for missing prerequisite headers?" >&5 +$as_echo "$as_me: WARNING: $2: check for missing prerequisite headers?" >&2;} + { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: $2: see the Autoconf documentation" >&5 +$as_echo "$as_me: WARNING: $2: see the Autoconf documentation" >&2;} + { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: $2: section \"Present But Cannot Be Compiled\"" >&5 +$as_echo "$as_me: WARNING: $2: section \"Present But Cannot Be Compiled\"" >&2;} + { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: $2: proceeding with the compiler's result" >&5 +$as_echo "$as_me: WARNING: $2: proceeding with the compiler's result" >&2;} +( cat <<\_ASBOX +## ------------------------------------------------ ## +## Report this to http://www.python.org/python-bugs ## +## ------------------------------------------------ ## +_ASBOX + ) | sed "s/^/$as_me: WARNING: /" >&2 + ;; +esac + { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $2" >&5 +$as_echo_n "checking for $2... " >&6; } +if { as_var=$3; eval "test \"\${$as_var+set}\" = set"; }; then : + $as_echo_n "(cached) " >&6 +else + eval "$3=\$ac_header_compiler" +fi +eval ac_res=\$$3 + { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_res" >&5 +$as_echo "$ac_res" >&6; } +fi + eval $as_lineno_stack; test "x$as_lineno_stack" = x && { as_lineno=; unset as_lineno;} -} >&5 +} # ac_fn_c_check_header_mongrel -cat >&5 <<_ACEOF +# ac_fn_c_try_run LINENO +# ---------------------- +# Try to link conftest.$ac_ext, and return whether this succeeded. Assumes +# that executables *can* be run. +ac_fn_c_try_run () +{ + as_lineno=${as_lineno-"$1"} as_lineno_stack=as_lineno_stack=$as_lineno_stack + if { { ac_try="$ac_link" +case "(($ac_try" in + *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; + *) ac_try_echo=$ac_try;; +esac +eval ac_try_echo="\"\$as_me:${as_lineno-$LINENO}: $ac_try_echo\"" +$as_echo "$ac_try_echo"; } >&5 + (eval "$ac_link") 2>&5 + ac_status=$? + $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 + test $ac_status = 0; } && { ac_try='./conftest$ac_exeext' + { { case "(($ac_try" in + *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; + *) ac_try_echo=$ac_try;; +esac +eval ac_try_echo="\"\$as_me:${as_lineno-$LINENO}: $ac_try_echo\"" +$as_echo "$ac_try_echo"; } >&5 + (eval "$ac_try") 2>&5 + ac_status=$? + $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 + test $ac_status = 0; }; }; then : + ac_retval=0 +else + $as_echo "$as_me: program exited with status $ac_status" >&5 + $as_echo "$as_me: failed program was:" >&5 +sed 's/^/| /' conftest.$ac_ext >&5 + ac_retval=$ac_status +fi + rm -rf conftest.dSYM conftest_ipa8_conftest.oo + eval $as_lineno_stack; test "x$as_lineno_stack" = x && { as_lineno=; unset as_lineno;} + as_fn_set_status $ac_retval -## ----------- ## -## Core tests. ## -## ----------- ## +} # ac_fn_c_try_run +# ac_fn_c_check_header_compile LINENO HEADER VAR INCLUDES +# ------------------------------------------------------- +# Tests whether HEADER exists and can be compiled using the include files in +# INCLUDES, setting the cache variable VAR accordingly. +ac_fn_c_check_header_compile () +{ + as_lineno=${as_lineno-"$1"} as_lineno_stack=as_lineno_stack=$as_lineno_stack + { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $2" >&5 +$as_echo_n "checking for $2... " >&6; } +if { as_var=$3; eval "test \"\${$as_var+set}\" = set"; }; then : + $as_echo_n "(cached) " >&6 +else + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ +$4 +#include <$2> _ACEOF +if ac_fn_c_try_compile "$LINENO"; then : + eval "$3=yes" +else + eval "$3=no" +fi +rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext +fi +eval ac_res=\$$3 + { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_res" >&5 +$as_echo "$ac_res" >&6; } + eval $as_lineno_stack; test "x$as_lineno_stack" = x && { as_lineno=; unset as_lineno;} +} # ac_fn_c_check_header_compile -# Keep a trace of the command line. -# Strip out --no-create and --no-recursion so they do not pile up. -# Strip out --silent because we don't want to record it for future runs. -# Also quote any args containing shell meta-characters. -# Make two passes to allow for proper duplicate-argument suppression. -ac_configure_args= -ac_configure_args0= -ac_configure_args1= -ac_must_keep_next=false -for ac_pass in 1 2 -do - for ac_arg - do - case $ac_arg in - -no-create | --no-c* | -n | -no-recursion | --no-r*) continue ;; - -q | -quiet | --quiet | --quie | --qui | --qu | --q \ - | -silent | --silent | --silen | --sile | --sil) - continue ;; - *\'*) - ac_arg=`$as_echo "$ac_arg" | sed "s/'/'\\\\\\\\''/g"` ;; - esac - case $ac_pass in - 1) ac_configure_args0="$ac_configure_args0 '$ac_arg'" ;; - 2) - ac_configure_args1="$ac_configure_args1 '$ac_arg'" - if test $ac_must_keep_next = true; then - ac_must_keep_next=false # Got value, back to normal. - else - case $ac_arg in - *=* | --config-cache | -C | -disable-* | --disable-* \ - | -enable-* | --enable-* | -gas | --g* | -nfp | --nf* \ - | -q | -quiet | --q* | -silent | --sil* | -v | -verb* \ - | -with-* | --with-* | -without-* | --without-* | --x) - case "$ac_configure_args0 " in - "$ac_configure_args1"*" '$ac_arg' "* ) continue ;; - esac - ;; - -* ) ac_must_keep_next=true ;; - esac - fi - ac_configure_args="$ac_configure_args '$ac_arg'" - ;; - esac - done -done -$as_unset ac_configure_args0 || test "${ac_configure_args0+set}" != set || { ac_configure_args0=; export ac_configure_args0; } -$as_unset ac_configure_args1 || test "${ac_configure_args1+set}" != set || { ac_configure_args1=; export ac_configure_args1; } +# ac_fn_c_try_link LINENO +# ----------------------- +# Try to link conftest.$ac_ext, and return whether this succeeded. +ac_fn_c_try_link () +{ + as_lineno=${as_lineno-"$1"} as_lineno_stack=as_lineno_stack=$as_lineno_stack + rm -f conftest.$ac_objext conftest$ac_exeext + if { { ac_try="$ac_link" +case "(($ac_try" in + *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; + *) ac_try_echo=$ac_try;; +esac +eval ac_try_echo="\"\$as_me:${as_lineno-$LINENO}: $ac_try_echo\"" +$as_echo "$ac_try_echo"; } >&5 + (eval "$ac_link") 2>conftest.err + ac_status=$? + if test -s conftest.err; then + grep -v '^ *+' conftest.err >conftest.er1 + cat conftest.er1 >&5 + mv -f conftest.er1 conftest.err + fi + $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 + test $ac_status = 0; } && { + test -z "$ac_c_werror_flag" || + test ! -s conftest.err + } && test -s conftest$ac_exeext && { + test "$cross_compiling" = yes || + $as_test_x conftest$ac_exeext + }; then : + ac_retval=0 +else + $as_echo "$as_me: failed program was:" >&5 +sed 's/^/| /' conftest.$ac_ext >&5 -# When interrupted or exit'd, cleanup temporary files, and complete -# config.log. We remove comments because anyway the quotes in there -# would cause problems or look ugly. -# WARNING: Use '\'' to represent an apostrophe within the trap. -# WARNING: Do not start the trap code with a newline, due to a FreeBSD 4.0 bug. -trap 'exit_status=$? - # Save into config.log some information that might help in debugging. - { - echo + ac_retval=1 +fi + # Delete the IPA/IPO (Inter Procedural Analysis/Optimization) information + # created by the PGI compiler (conftest_ipa8_conftest.oo), as it would + # interfere with the next link command; also delete a directory that is + # left behind by Apple's compiler. We do this before executing the actions. + rm -rf conftest.dSYM conftest_ipa8_conftest.oo + eval $as_lineno_stack; test "x$as_lineno_stack" = x && { as_lineno=; unset as_lineno;} + as_fn_set_status $ac_retval - cat <<\_ASBOX -## ---------------- ## -## Cache variables. ## -## ---------------- ## -_ASBOX - echo - # The following way of writing the cache mishandles newlines in values, -( - for ac_var in `(set) 2>&1 | sed -n '\''s/^\([a-zA-Z_][a-zA-Z0-9_]*\)=.*/\1/p'\''`; do - eval ac_val=\$$ac_var - case $ac_val in #( - *${as_nl}*) - case $ac_var in #( - *_cv_*) { $as_echo "$as_me:$LINENO: WARNING: cache variable $ac_var contains a newline" >&5 -$as_echo "$as_me: WARNING: cache variable $ac_var contains a newline" >&2;} ;; - esac - case $ac_var in #( - _ | IFS | as_nl) ;; #( - BASH_ARGV | BASH_SOURCE) eval $ac_var= ;; #( - *) $as_unset $ac_var ;; - esac ;; - esac - done - (set) 2>&1 | - case $as_nl`(ac_space='\'' '\''; set) 2>&1` in #( - *${as_nl}ac_space=\ *) - sed -n \ - "s/'\''/'\''\\\\'\'''\''/g; - s/^\\([_$as_cr_alnum]*_cv_[_$as_cr_alnum]*\\)=\\(.*\\)/\\1='\''\\2'\''/p" - ;; #( - *) - sed -n "/^[_$as_cr_alnum]*_cv_[_$as_cr_alnum]*=/p" - ;; - esac | - sort -) - echo +} # ac_fn_c_try_link - cat <<\_ASBOX -## ----------------- ## -## Output variables. ## -## ----------------- ## -_ASBOX - echo - for ac_var in $ac_subst_vars - do - eval ac_val=\$$ac_var - case $ac_val in - *\'\''*) ac_val=`$as_echo "$ac_val" | sed "s/'\''/'\''\\\\\\\\'\'''\''/g"`;; - esac - $as_echo "$ac_var='\''$ac_val'\''" - done | sort - echo - - if test -n "$ac_subst_files"; then - cat <<\_ASBOX -## ------------------- ## -## File substitutions. ## -## ------------------- ## -_ASBOX - echo - for ac_var in $ac_subst_files - do - eval ac_val=\$$ac_var - case $ac_val in - *\'\''*) ac_val=`$as_echo "$ac_val" | sed "s/'\''/'\''\\\\\\\\'\'''\''/g"`;; - esac - $as_echo "$ac_var='\''$ac_val'\''" - done | sort - echo - fi +# ac_fn_c_check_type LINENO TYPE VAR INCLUDES +# ------------------------------------------- +# Tests whether TYPE exists after having included INCLUDES, setting cache +# variable VAR accordingly. +ac_fn_c_check_type () +{ + as_lineno=${as_lineno-"$1"} as_lineno_stack=as_lineno_stack=$as_lineno_stack + { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $2" >&5 +$as_echo_n "checking for $2... " >&6; } +if { as_var=$3; eval "test \"\${$as_var+set}\" = set"; }; then : + $as_echo_n "(cached) " >&6 +else + eval "$3=no" + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ +$4 +int +main () +{ +if (sizeof ($2)) + return 0; + ; + return 0; +} +_ACEOF +if ac_fn_c_try_compile "$LINENO"; then : + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ +$4 +int +main () +{ +if (sizeof (($2))) + return 0; + ; + return 0; +} +_ACEOF +if ac_fn_c_try_compile "$LINENO"; then : - if test -s confdefs.h; then - cat <<\_ASBOX -## ----------- ## -## confdefs.h. ## -## ----------- ## -_ASBOX - echo - cat confdefs.h - echo - fi - test "$ac_signal" != 0 && - $as_echo "$as_me: caught signal $ac_signal" - $as_echo "$as_me: exit $exit_status" - } >&5 - rm -f core *.core core.conftest.* && - rm -f -r conftest* confdefs* conf$$* $ac_clean_files && - exit $exit_status -' 0 -for ac_signal in 1 2 13 15; do - trap 'ac_signal='$ac_signal'; { (exit 1); exit 1; }' $ac_signal -done -ac_signal=0 +else + eval "$3=yes" +fi +rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext +fi +rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext +fi +eval ac_res=\$$3 + { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_res" >&5 +$as_echo "$ac_res" >&6; } + eval $as_lineno_stack; test "x$as_lineno_stack" = x && { as_lineno=; unset as_lineno;} -# confdefs.h avoids OS command line length limits that DEFS can exceed. -rm -f -r conftest* confdefs.h +} # ac_fn_c_check_type -# Predefined preprocessor variables. +# ac_fn_c_compute_int LINENO EXPR VAR INCLUDES +# -------------------------------------------- +# Tries to find the compile-time value of EXPR in a program that includes +# INCLUDES, setting VAR accordingly. Returns whether the value could be +# computed +ac_fn_c_compute_int () +{ + as_lineno=${as_lineno-"$1"} as_lineno_stack=as_lineno_stack=$as_lineno_stack + if test "$cross_compiling" = yes; then + # Depending upon the size, compute the lo and hi bounds. +cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ +$4 +int +main () +{ +static int test_array [1 - 2 * !(($2) >= 0)]; +test_array [0] = 0 -cat >>confdefs.h <<_ACEOF -#define PACKAGE_NAME "$PACKAGE_NAME" + ; + return 0; +} _ACEOF +if ac_fn_c_try_compile "$LINENO"; then : + ac_lo=0 ac_mid=0 + while :; do + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ +$4 +int +main () +{ +static int test_array [1 - 2 * !(($2) <= $ac_mid)]; +test_array [0] = 0 - -cat >>confdefs.h <<_ACEOF -#define PACKAGE_TARNAME "$PACKAGE_TARNAME" + ; + return 0; +} _ACEOF +if ac_fn_c_try_compile "$LINENO"; then : + ac_hi=$ac_mid; break +else + as_fn_arith $ac_mid + 1 && ac_lo=$as_val + if test $ac_lo -le $ac_mid; then + ac_lo= ac_hi= + break + fi + as_fn_arith 2 '*' $ac_mid + 1 && ac_mid=$as_val +fi +rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext + done +else + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ +$4 +int +main () +{ +static int test_array [1 - 2 * !(($2) < 0)]; +test_array [0] = 0 - -cat >>confdefs.h <<_ACEOF -#define PACKAGE_VERSION "$PACKAGE_VERSION" + ; + return 0; +} _ACEOF +if ac_fn_c_try_compile "$LINENO"; then : + ac_hi=-1 ac_mid=-1 + while :; do + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ +$4 +int +main () +{ +static int test_array [1 - 2 * !(($2) >= $ac_mid)]; +test_array [0] = 0 - -cat >>confdefs.h <<_ACEOF -#define PACKAGE_STRING "$PACKAGE_STRING" + ; + return 0; +} _ACEOF +if ac_fn_c_try_compile "$LINENO"; then : + ac_lo=$ac_mid; break +else + as_fn_arith '(' $ac_mid ')' - 1 && ac_hi=$as_val + if test $ac_mid -le $ac_hi; then + ac_lo= ac_hi= + break + fi + as_fn_arith 2 '*' $ac_mid && ac_mid=$as_val +fi +rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext + done +else + ac_lo= ac_hi= +fi +rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext +fi +rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext +# Binary search between lo and hi bounds. +while test "x$ac_lo" != "x$ac_hi"; do + as_fn_arith '(' $ac_hi - $ac_lo ')' / 2 + $ac_lo && ac_mid=$as_val + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ +$4 +int +main () +{ +static int test_array [1 - 2 * !(($2) <= $ac_mid)]; +test_array [0] = 0 - -cat >>confdefs.h <<_ACEOF -#define PACKAGE_BUGREPORT "$PACKAGE_BUGREPORT" + ; + return 0; +} _ACEOF +if ac_fn_c_try_compile "$LINENO"; then : + ac_hi=$ac_mid +else + as_fn_arith '(' $ac_mid ')' + 1 && ac_lo=$as_val +fi +rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext +done +case $ac_lo in #(( +?*) eval "$3=\$ac_lo"; ac_retval=0 ;; +'') ac_retval=1 ;; +esac + else + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ +$4 +static long int longval () { return $2; } +static unsigned long int ulongval () { return $2; } +#include +#include +int +main () +{ + FILE *f = fopen ("conftest.val", "w"); + if (! f) + return 1; + if (($2) < 0) + { + long int i = longval (); + if (i != ($2)) + return 1; + fprintf (f, "%ld", i); + } + else + { + unsigned long int i = ulongval (); + if (i != ($2)) + return 1; + fprintf (f, "%lu", i); + } + /* Do not output a trailing newline, as this causes \r\n confusion + on some platforms. */ + return ferror (f) || fclose (f) != 0; -# Let the site file select an alternate cache file if it wants to. -# Prefer an explicitly selected file to automatically selected ones. -ac_site_file1=NONE -ac_site_file2=NONE -if test -n "$CONFIG_SITE"; then - ac_site_file1=$CONFIG_SITE -elif test "x$prefix" != xNONE; then - ac_site_file1=$prefix/share/config.site - ac_site_file2=$prefix/etc/config.site + ; + return 0; +} +_ACEOF +if ac_fn_c_try_run "$LINENO"; then : + echo >>conftest.val; read $3 &5 -$as_echo "$as_me: loading site script $ac_site_file" >&6;} - sed 's/^/| /' "$ac_site_file" >&5 - . "$ac_site_file" - fi -done +rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext \ + conftest.$ac_objext conftest.beam conftest.$ac_ext +rm -f conftest.val -if test -r "$cache_file"; then - # Some versions of bash will fail to source /dev/null (special - # files actually), so we avoid doing that. - if test -f "$cache_file"; then - { $as_echo "$as_me:$LINENO: loading cache $cache_file" >&5 -$as_echo "$as_me: loading cache $cache_file" >&6;} - case $cache_file in - [\\/]* | ?:[\\/]* ) . "$cache_file";; - *) . "./$cache_file";; - esac fi + eval $as_lineno_stack; test "x$as_lineno_stack" = x && { as_lineno=; unset as_lineno;} + as_fn_set_status $ac_retval + +} # ac_fn_c_compute_int + +# ac_fn_c_check_func LINENO FUNC VAR +# ---------------------------------- +# Tests whether FUNC exists, setting the cache variable VAR accordingly +ac_fn_c_check_func () +{ + as_lineno=${as_lineno-"$1"} as_lineno_stack=as_lineno_stack=$as_lineno_stack + { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $2" >&5 +$as_echo_n "checking for $2... " >&6; } +if { as_var=$3; eval "test \"\${$as_var+set}\" = set"; }; then : + $as_echo_n "(cached) " >&6 else - { $as_echo "$as_me:$LINENO: creating cache $cache_file" >&5 -$as_echo "$as_me: creating cache $cache_file" >&6;} - >$cache_file -fi + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ +/* Define $2 to an innocuous variant, in case declares $2. + For example, HP-UX 11i declares gettimeofday. */ +#define $2 innocuous_$2 -# Check that the precious variables saved in the cache have kept the same -# value. -ac_cache_corrupted=false -for ac_var in $ac_precious_vars; do - eval ac_old_set=\$ac_cv_env_${ac_var}_set - eval ac_new_set=\$ac_env_${ac_var}_set - eval ac_old_val=\$ac_cv_env_${ac_var}_value - eval ac_new_val=\$ac_env_${ac_var}_value - case $ac_old_set,$ac_new_set in - set,) - { $as_echo "$as_me:$LINENO: error: \`$ac_var' was set to \`$ac_old_val' in the previous run" >&5 -$as_echo "$as_me: error: \`$ac_var' was set to \`$ac_old_val' in the previous run" >&2;} - ac_cache_corrupted=: ;; - ,set) - { $as_echo "$as_me:$LINENO: error: \`$ac_var' was not set in the previous run" >&5 -$as_echo "$as_me: error: \`$ac_var' was not set in the previous run" >&2;} - ac_cache_corrupted=: ;; - ,);; - *) - if test "x$ac_old_val" != "x$ac_new_val"; then - # differences in whitespace do not lead to failure. - ac_old_val_w=`echo x $ac_old_val` - ac_new_val_w=`echo x $ac_new_val` - if test "$ac_old_val_w" != "$ac_new_val_w"; then - { $as_echo "$as_me:$LINENO: error: \`$ac_var' has changed since the previous run:" >&5 -$as_echo "$as_me: error: \`$ac_var' has changed since the previous run:" >&2;} - ac_cache_corrupted=: - else - { $as_echo "$as_me:$LINENO: warning: ignoring whitespace changes in \`$ac_var' since the previous run:" >&5 -$as_echo "$as_me: warning: ignoring whitespace changes in \`$ac_var' since the previous run:" >&2;} - eval $ac_var=\$ac_old_val - fi - { $as_echo "$as_me:$LINENO: former value: \`$ac_old_val'" >&5 -$as_echo "$as_me: former value: \`$ac_old_val'" >&2;} - { $as_echo "$as_me:$LINENO: current value: \`$ac_new_val'" >&5 -$as_echo "$as_me: current value: \`$ac_new_val'" >&2;} - fi;; - esac - # Pass precious variables to config.status. - if test "$ac_new_set" = set; then - case $ac_new_val in - *\'*) ac_arg=$ac_var=`$as_echo "$ac_new_val" | sed "s/'/'\\\\\\\\''/g"` ;; - *) ac_arg=$ac_var=$ac_new_val ;; - esac - case " $ac_configure_args " in - *" '$ac_arg' "*) ;; # Avoid dups. Use of quotes ensures accuracy. - *) ac_configure_args="$ac_configure_args '$ac_arg'" ;; - esac - fi -done -if $ac_cache_corrupted; then - { $as_echo "$as_me:$LINENO: error: in \`$ac_pwd':" >&5 -$as_echo "$as_me: error: in \`$ac_pwd':" >&2;} - { $as_echo "$as_me:$LINENO: error: changes in the environment can compromise the build" >&5 -$as_echo "$as_me: error: changes in the environment can compromise the build" >&2;} - { { $as_echo "$as_me:$LINENO: error: run \`make distclean' and/or \`rm $cache_file' and start over" >&5 -$as_echo "$as_me: error: run \`make distclean' and/or \`rm $cache_file' and start over" >&2;} - { (exit 1); exit 1; }; } -fi - - - - - - - - - - - - - - - - - - - - - - - - - -ac_ext=c -ac_cpp='$CPP $CPPFLAGS' -ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5' -ac_link='$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5' -ac_compiler_gnu=$ac_cv_c_compiler_gnu - - - -ac_config_headers="$ac_config_headers pyconfig.h" - - - - - - - -# We don't use PACKAGE_ variables, and they cause conflicts -# with other autoconf-based packages that include Python.h -grep -v 'define PACKAGE_' confdefs.h.new -rm confdefs.h -mv confdefs.h.new confdefs.h - - -VERSION=2.6 - - -SOVERSION=1.0 - -# The later defininition of _XOPEN_SOURCE disables certain features -# on Linux, so we need _GNU_SOURCE to re-enable them (makedev, tm_zone). +/* System header to define __stub macros and hopefully few prototypes, + which can conflict with char $2 (); below. + Prefer to if __STDC__ is defined, since + exists even on freestanding compilers. */ -cat >>confdefs.h <<\_ACEOF -#define _GNU_SOURCE 1 -_ACEOF +#ifdef __STDC__ +# include +#else +# include +#endif +#undef $2 -# The later defininition of _XOPEN_SOURCE and _POSIX_C_SOURCE disables -# certain features on NetBSD, so we need _NETBSD_SOURCE to re-enable -# them. +/* Override any GCC internal prototype to avoid an error. + Use char because int might match the return type of a GCC + builtin and then its argument prototype would still apply. */ +#ifdef __cplusplus +extern "C" +#endif +char $2 (); +/* The GNU C library defines this for functions which it implements + to always fail with ENOSYS. Some functions are actually named + something starting with __ and the normal name is an alias. */ +#if defined __stub_$2 || defined __stub___$2 +choke me +#endif -cat >>confdefs.h <<\_ACEOF -#define _NETBSD_SOURCE 1 +int +main () +{ +return $2 (); + ; + return 0; +} _ACEOF +if ac_fn_c_try_link "$LINENO"; then : + eval "$3=yes" +else + eval "$3=no" +fi +rm -f core conftest.err conftest.$ac_objext \ + conftest$ac_exeext conftest.$ac_ext +fi +eval ac_res=\$$3 + { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_res" >&5 +$as_echo "$ac_res" >&6; } + eval $as_lineno_stack; test "x$as_lineno_stack" = x && { as_lineno=; unset as_lineno;} +} # ac_fn_c_check_func -# The later defininition of _XOPEN_SOURCE and _POSIX_C_SOURCE disables -# certain features on FreeBSD, so we need __BSD_VISIBLE to re-enable -# them. - -cat >>confdefs.h <<\_ACEOF -#define __BSD_VISIBLE 1 +# ac_fn_c_check_member LINENO AGGR MEMBER VAR INCLUDES +# ---------------------------------------------------- +# Tries to find if the field MEMBER exists in type AGGR, after including +# INCLUDES, setting cache variable VAR accordingly. +ac_fn_c_check_member () +{ + as_lineno=${as_lineno-"$1"} as_lineno_stack=as_lineno_stack=$as_lineno_stack + { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $2.$3" >&5 +$as_echo_n "checking for $2.$3... " >&6; } +if { as_var=$4; eval "test \"\${$as_var+set}\" = set"; }; then : + $as_echo_n "(cached) " >&6 +else + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ +$5 +int +main () +{ +static $2 ac_aggr; +if (ac_aggr.$3) +return 0; + ; + return 0; +} _ACEOF - - -# The later defininition of _XOPEN_SOURCE and _POSIX_C_SOURCE disables -# u_int on Irix 5.3. Defining _BSD_TYPES brings it back. - -cat >>confdefs.h <<\_ACEOF -#define _BSD_TYPES 1 +if ac_fn_c_try_compile "$LINENO"; then : + eval "$4=yes" +else + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ +$5 +int +main () +{ +static $2 ac_aggr; +if (sizeof ac_aggr.$3) +return 0; + ; + return 0; +} _ACEOF +if ac_fn_c_try_compile "$LINENO"; then : + eval "$4=yes" +else + eval "$4=no" +fi +rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext +fi +rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext +fi +eval ac_res=\$$4 + { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_res" >&5 +$as_echo "$ac_res" >&6; } + eval $as_lineno_stack; test "x$as_lineno_stack" = x && { as_lineno=; unset as_lineno;} +} # ac_fn_c_check_member -# The later defininition of _XOPEN_SOURCE and _POSIX_C_SOURCE disables -# certain features on Mac OS X, so we need _DARWIN_C_SOURCE to re-enable -# them. +# ac_fn_c_check_decl LINENO SYMBOL VAR +# ------------------------------------ +# Tests whether SYMBOL is declared, setting cache variable VAR accordingly. +ac_fn_c_check_decl () +{ + as_lineno=${as_lineno-"$1"} as_lineno_stack=as_lineno_stack=$as_lineno_stack + { $as_echo "$as_me:${as_lineno-$LINENO}: checking whether $2 is declared" >&5 +$as_echo_n "checking whether $2 is declared... " >&6; } +if { as_var=$3; eval "test \"\${$as_var+set}\" = set"; }; then : + $as_echo_n "(cached) " >&6 +else + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ +$4 +int +main () +{ +#ifndef $2 + (void) $2; +#endif -cat >>confdefs.h <<\_ACEOF -#define _DARWIN_C_SOURCE 1 + ; + return 0; +} _ACEOF - - - -define_xopen_source=yes - -# Arguments passed to configure. - -CONFIG_ARGS="$ac_configure_args" - -{ $as_echo "$as_me:$LINENO: checking for --enable-universalsdk" >&5 -$as_echo_n "checking for --enable-universalsdk... " >&6; } -# Check whether --enable-universalsdk was given. -if test "${enable_universalsdk+set}" = set; then - enableval=$enable_universalsdk; - case $enableval in - yes) - enableval=/Developer/SDKs/MacOSX10.4u.sdk - if test ! -d "${enableval}" - then - enableval=/ - fi - ;; - esac - case $enableval in - no) - UNIVERSALSDK= - enable_universalsdk= - ;; - *) - UNIVERSALSDK=$enableval - if test ! -d "${UNIVERSALSDK}" - then - { { $as_echo "$as_me:$LINENO: error: --enable-universalsdk specifies non-existing SDK: ${UNIVERSALSDK}" >&5 -$as_echo "$as_me: error: --enable-universalsdk specifies non-existing SDK: ${UNIVERSALSDK}" >&2;} - { (exit 1); exit 1; }; } - fi - ;; - esac - - +if ac_fn_c_try_compile "$LINENO"; then : + eval "$3=yes" else - - UNIVERSALSDK= - enable_universalsdk= - + eval "$3=no" fi - -if test -n "${UNIVERSALSDK}" -then - { $as_echo "$as_me:$LINENO: result: ${UNIVERSALSDK}" >&5 -$as_echo "${UNIVERSALSDK}" >&6; } -else - { $as_echo "$as_me:$LINENO: result: no" >&5 -$as_echo "no" >&6; } +rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext fi +eval ac_res=\$$3 + { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_res" >&5 +$as_echo "$ac_res" >&6; } + eval $as_lineno_stack; test "x$as_lineno_stack" = x && { as_lineno=; unset as_lineno;} +} # ac_fn_c_check_decl +cat >config.log <<_ACEOF +This file contains any messages produced by compilers while +running configure, to aid debugging if configure makes a mistake. +It was created by python $as_me 2.6, which was +generated by GNU Autoconf 2.65. Invocation command line was + $ $0 $@ -UNIVERSAL_ARCHS="32-bit" +_ACEOF +exec 5>>config.log +{ +cat <<_ASUNAME +## --------- ## +## Platform. ## +## --------- ## +hostname = `(hostname || uname -n) 2>/dev/null | sed 1q` +uname -m = `(uname -m) 2>/dev/null || echo unknown` +uname -r = `(uname -r) 2>/dev/null || echo unknown` +uname -s = `(uname -s) 2>/dev/null || echo unknown` +uname -v = `(uname -v) 2>/dev/null || echo unknown` -{ $as_echo "$as_me:$LINENO: checking for --with-universal-archs" >&5 -$as_echo_n "checking for --with-universal-archs... " >&6; } +/usr/bin/uname -p = `(/usr/bin/uname -p) 2>/dev/null || echo unknown` +/bin/uname -X = `(/bin/uname -X) 2>/dev/null || echo unknown` -# Check whether --with-universal-archs was given. -if test "${with_universal_archs+set}" = set; then - withval=$with_universal_archs; - { $as_echo "$as_me:$LINENO: result: $withval" >&5 -$as_echo "$withval" >&6; } - UNIVERSAL_ARCHS="$withval" - if test "${enable_universalsdk}" ; then - : - else - { { $as_echo "$as_me:$LINENO: error: --with-universal-archs without --enable-universalsdk. See Mac/README" >&5 -$as_echo "$as_me: error: --with-universal-archs without --enable-universalsdk. See Mac/README" >&2;} - { (exit 1); exit 1; }; } - fi +/bin/arch = `(/bin/arch) 2>/dev/null || echo unknown` +/usr/bin/arch -k = `(/usr/bin/arch -k) 2>/dev/null || echo unknown` +/usr/convex/getsysinfo = `(/usr/convex/getsysinfo) 2>/dev/null || echo unknown` +/usr/bin/hostinfo = `(/usr/bin/hostinfo) 2>/dev/null || echo unknown` +/bin/machine = `(/bin/machine) 2>/dev/null || echo unknown` +/usr/bin/oslevel = `(/usr/bin/oslevel) 2>/dev/null || echo unknown` +/bin/universe = `(/bin/universe) 2>/dev/null || echo unknown` -else +_ASUNAME - { $as_echo "$as_me:$LINENO: result: 32-bit" >&5 -$as_echo "32-bit" >&6; } +as_save_IFS=$IFS; IFS=$PATH_SEPARATOR +for as_dir in $PATH +do + IFS=$as_save_IFS + test -z "$as_dir" && as_dir=. + $as_echo "PATH: $as_dir" + done +IFS=$as_save_IFS -fi +} >&5 +cat >&5 <<_ACEOF +## ----------- ## +## Core tests. ## +## ----------- ## +_ACEOF -# Check whether --with-framework-name was given. -if test "${with_framework_name+set}" = set; then - withval=$with_framework_name; - if test "${enable_framework}"; then - : - else - { { $as_echo "$as_me:$LINENO: error: --with-framework-name without --enable-framework. See Mac/README" >&5 -$as_echo "$as_me: error: --with-framework-name without --enable-framework. See Mac/README" >&2;} - { (exit 1); exit 1; }; } - fi - PYTHONFRAMEWORK=${withval} - PYTHONFRAMEWORKDIR=${withval}.framework - PYTHONFRAMEWORKIDENTIFIER=org.python.`echo $withval | tr 'A-Z' 'a-z'` - -else - - PYTHONFRAMEWORK=Python - PYTHONFRAMEWORKDIR=Python.framework - PYTHONFRAMEWORKIDENTIFIER=org.python.python - -fi -# Check whether --enable-framework was given. -if test "${enable_framework+set}" = set; then - enableval=$enable_framework; - case $enableval in - yes) - enableval=/Library/Frameworks +# Keep a trace of the command line. +# Strip out --no-create and --no-recursion so they do not pile up. +# Strip out --silent because we don't want to record it for future runs. +# Also quote any args containing shell meta-characters. +# Make two passes to allow for proper duplicate-argument suppression. +ac_configure_args= +ac_configure_args0= +ac_configure_args1= +ac_must_keep_next=false +for ac_pass in 1 2 +do + for ac_arg + do + case $ac_arg in + -no-create | --no-c* | -n | -no-recursion | --no-r*) continue ;; + -q | -quiet | --quiet | --quie | --qui | --qu | --q \ + | -silent | --silent | --silen | --sile | --sil) + continue ;; + *\'*) + ac_arg=`$as_echo "$ac_arg" | sed "s/'/'\\\\\\\\''/g"` ;; + esac + case $ac_pass in + 1) as_fn_append ac_configure_args0 " '$ac_arg'" ;; + 2) + as_fn_append ac_configure_args1 " '$ac_arg'" + if test $ac_must_keep_next = true; then + ac_must_keep_next=false # Got value, back to normal. + else + case $ac_arg in + *=* | --config-cache | -C | -disable-* | --disable-* \ + | -enable-* | --enable-* | -gas | --g* | -nfp | --nf* \ + | -q | -quiet | --q* | -silent | --sil* | -v | -verb* \ + | -with-* | --with-* | -without-* | --without-* | --x) + case "$ac_configure_args0 " in + "$ac_configure_args1"*" '$ac_arg' "* ) continue ;; + esac + ;; + -* ) ac_must_keep_next=true ;; esac - case $enableval in - no) - PYTHONFRAMEWORK= - PYTHONFRAMEWORKDIR=no-framework - PYTHONFRAMEWORKPREFIX= - PYTHONFRAMEWORKINSTALLDIR= - FRAMEWORKINSTALLFIRST= - FRAMEWORKINSTALLLAST= - FRAMEWORKALTINSTALLFIRST= - FRAMEWORKALTINSTALLLAST= - if test "x${prefix}" = "xNONE"; then - FRAMEWORKUNIXTOOLSPREFIX="${ac_default_prefix}" - else - FRAMEWORKUNIXTOOLSPREFIX="${prefix}" - fi - enable_framework= - ;; - *) - PYTHONFRAMEWORKPREFIX=$enableval - PYTHONFRAMEWORKINSTALLDIR=$PYTHONFRAMEWORKPREFIX/$PYTHONFRAMEWORKDIR - FRAMEWORKINSTALLFIRST="frameworkinstallstructure" - FRAMEWORKALTINSTALLFIRST="frameworkinstallstructure bininstall maninstall" - case "${UNIVERSAL_ARCHS}" in - all|3-way|intel) - FRAMEWORKINSTALLLAST="frameworkinstallmaclib frameworkinstallapps4way frameworkinstallunixtools4way" - FRAMEWORKALTINSTALLLAST="frameworkinstallmaclib frameworkinstallapps4way frameworkaltinstallunixtools4way" - ;; - *) - FRAMEWORKINSTALLLAST="frameworkinstallmaclib frameworkinstallapps frameworkinstallunixtools" - FRAMEWORKALTINSTALLLAST="frameworkinstallmaclib frameworkinstallapps frameworkaltinstallunixtools" - ;; - esac - - if test "x${prefix}" = "xNONE" ; then - FRAMEWORKUNIXTOOLSPREFIX="${ac_default_prefix}" - else - FRAMEWORKUNIXTOOLSPREFIX="${prefix}" - fi - prefix=$PYTHONFRAMEWORKINSTALLDIR/Versions/$VERSION - - # Add files for Mac specific code to the list of output - # files: - ac_config_files="$ac_config_files Mac/Makefile" - - ac_config_files="$ac_config_files Mac/PythonLauncher/Makefile" + fi + as_fn_append ac_configure_args " '$ac_arg'" + ;; + esac + done +done +{ ac_configure_args0=; unset ac_configure_args0;} +{ ac_configure_args1=; unset ac_configure_args1;} - ac_config_files="$ac_config_files Mac/IDLE/Makefile" +# When interrupted or exit'd, cleanup temporary files, and complete +# config.log. We remove comments because anyway the quotes in there +# would cause problems or look ugly. +# WARNING: Use '\'' to represent an apostrophe within the trap. +# WARNING: Do not start the trap code with a newline, due to a FreeBSD 4.0 bug. +trap 'exit_status=$? + # Save into config.log some information that might help in debugging. + { + echo - ac_config_files="$ac_config_files Mac/Resources/framework/Info.plist" + cat <<\_ASBOX +## ---------------- ## +## Cache variables. ## +## ---------------- ## +_ASBOX + echo + # The following way of writing the cache mishandles newlines in values, +( + for ac_var in `(set) 2>&1 | sed -n '\''s/^\([a-zA-Z_][a-zA-Z0-9_]*\)=.*/\1/p'\''`; do + eval ac_val=\$$ac_var + case $ac_val in #( + *${as_nl}*) + case $ac_var in #( + *_cv_*) { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: cache variable $ac_var contains a newline" >&5 +$as_echo "$as_me: WARNING: cache variable $ac_var contains a newline" >&2;} ;; + esac + case $ac_var in #( + _ | IFS | as_nl) ;; #( + BASH_ARGV | BASH_SOURCE) eval $ac_var= ;; #( + *) { eval $ac_var=; unset $ac_var;} ;; + esac ;; + esac + done + (set) 2>&1 | + case $as_nl`(ac_space='\'' '\''; set) 2>&1` in #( + *${as_nl}ac_space=\ *) + sed -n \ + "s/'\''/'\''\\\\'\'''\''/g; + s/^\\([_$as_cr_alnum]*_cv_[_$as_cr_alnum]*\\)=\\(.*\\)/\\1='\''\\2'\''/p" + ;; #( + *) + sed -n "/^[_$as_cr_alnum]*_cv_[_$as_cr_alnum]*=/p" + ;; + esac | + sort +) + echo - ac_config_files="$ac_config_files Mac/Resources/app/Info.plist" + cat <<\_ASBOX +## ----------------- ## +## Output variables. ## +## ----------------- ## +_ASBOX + echo + for ac_var in $ac_subst_vars + do + eval ac_val=\$$ac_var + case $ac_val in + *\'\''*) ac_val=`$as_echo "$ac_val" | sed "s/'\''/'\''\\\\\\\\'\'''\''/g"`;; + esac + $as_echo "$ac_var='\''$ac_val'\''" + done | sort + echo + if test -n "$ac_subst_files"; then + cat <<\_ASBOX +## ------------------- ## +## File substitutions. ## +## ------------------- ## +_ASBOX + echo + for ac_var in $ac_subst_files + do + eval ac_val=\$$ac_var + case $ac_val in + *\'\''*) ac_val=`$as_echo "$ac_val" | sed "s/'\''/'\''\\\\\\\\'\'''\''/g"`;; esac + $as_echo "$ac_var='\''$ac_val'\''" + done | sort + echo + fi -else - - PYTHONFRAMEWORK= - PYTHONFRAMEWORKDIR=no-framework - PYTHONFRAMEWORKPREFIX= - PYTHONFRAMEWORKINSTALLDIR= - FRAMEWORKINSTALLFIRST= - FRAMEWORKINSTALLLAST= - FRAMEWORKALTINSTALLFIRST= - FRAMEWORKALTINSTALLLAST= - if test "x${prefix}" = "xNONE" ; then - FRAMEWORKUNIXTOOLSPREFIX="${ac_default_prefix}" - else - FRAMEWORKUNIXTOOLSPREFIX="${prefix}" - fi - enable_framework= - - if test "$UNIVERSAL_ARCHS" = "all" - then - FRAMEWORKINSTALLLAST=update4wayuniversal - FRAMEWORKALTINSTALLLAST=update4wayuniversal - fi - -fi - + if test -s confdefs.h; then + cat <<\_ASBOX +## ----------- ## +## confdefs.h. ## +## ----------- ## +_ASBOX + echo + cat confdefs.h + echo + fi + test "$ac_signal" != 0 && + $as_echo "$as_me: caught signal $ac_signal" + $as_echo "$as_me: exit $exit_status" + } >&5 + rm -f core *.core core.conftest.* && + rm -f -r conftest* confdefs* conf$$* $ac_clean_files && + exit $exit_status +' 0 +for ac_signal in 1 2 13 15; do + trap 'ac_signal='$ac_signal'; as_fn_exit 1' $ac_signal +done +ac_signal=0 +# confdefs.h avoids OS command line length limits that DEFS can exceed. +rm -f -r conftest* confdefs.h +$as_echo "/* confdefs.h */" > confdefs.h +# Predefined preprocessor variables. +cat >>confdefs.h <<_ACEOF +#define PACKAGE_NAME "$PACKAGE_NAME" +_ACEOF +cat >>confdefs.h <<_ACEOF +#define PACKAGE_TARNAME "$PACKAGE_TARNAME" +_ACEOF +cat >>confdefs.h <<_ACEOF +#define PACKAGE_VERSION "$PACKAGE_VERSION" +_ACEOF +cat >>confdefs.h <<_ACEOF +#define PACKAGE_STRING "$PACKAGE_STRING" +_ACEOF +cat >>confdefs.h <<_ACEOF +#define PACKAGE_BUGREPORT "$PACKAGE_BUGREPORT" +_ACEOF +cat >>confdefs.h <<_ACEOF +#define PACKAGE_URL "$PACKAGE_URL" +_ACEOF -##AC_ARG_WITH(dyld, -## AC_HELP_STRING(--with-dyld, -## Use (OpenStep|Rhapsody) dynamic linker)) -## -# Set name for machine-dependent library files +# Let the site file select an alternate cache file if it wants to. +# Prefer an explicitly selected file to automatically selected ones. +ac_site_file1=NONE +ac_site_file2=NONE +if test -n "$CONFIG_SITE"; then + ac_site_file1=$CONFIG_SITE +elif test "x$prefix" != xNONE; then + ac_site_file1=$prefix/share/config.site + ac_site_file2=$prefix/etc/config.site +else + ac_site_file1=$ac_default_prefix/share/config.site + ac_site_file2=$ac_default_prefix/etc/config.site +fi +for ac_site_file in "$ac_site_file1" "$ac_site_file2" +do + test "x$ac_site_file" = xNONE && continue + if test /dev/null != "$ac_site_file" && test -r "$ac_site_file"; then + { $as_echo "$as_me:${as_lineno-$LINENO}: loading site script $ac_site_file" >&5 +$as_echo "$as_me: loading site script $ac_site_file" >&6;} + sed 's/^/| /' "$ac_site_file" >&5 + . "$ac_site_file" + fi +done -{ $as_echo "$as_me:$LINENO: checking MACHDEP" >&5 -$as_echo_n "checking MACHDEP... " >&6; } -if test -z "$MACHDEP" -then - ac_sys_system=`uname -s` - if test "$ac_sys_system" = "AIX" -o "$ac_sys_system" = "Monterey64" \ - -o "$ac_sys_system" = "UnixWare" -o "$ac_sys_system" = "OpenUNIX"; then - ac_sys_release=`uname -v` +if test -r "$cache_file"; then + # Some versions of bash will fail to source /dev/null (special files + # actually), so we avoid doing that. DJGPP emulates it as a regular file. + if test /dev/null != "$cache_file" && test -f "$cache_file"; then + { $as_echo "$as_me:${as_lineno-$LINENO}: loading cache $cache_file" >&5 +$as_echo "$as_me: loading cache $cache_file" >&6;} + case $cache_file in + [\\/]* | ?:[\\/]* ) . "$cache_file";; + *) . "./$cache_file";; + esac + fi +else + { $as_echo "$as_me:${as_lineno-$LINENO}: creating cache $cache_file" >&5 +$as_echo "$as_me: creating cache $cache_file" >&6;} + >$cache_file +fi + +# Check that the precious variables saved in the cache have kept the same +# value. +ac_cache_corrupted=false +for ac_var in $ac_precious_vars; do + eval ac_old_set=\$ac_cv_env_${ac_var}_set + eval ac_new_set=\$ac_env_${ac_var}_set + eval ac_old_val=\$ac_cv_env_${ac_var}_value + eval ac_new_val=\$ac_env_${ac_var}_value + case $ac_old_set,$ac_new_set in + set,) + { $as_echo "$as_me:${as_lineno-$LINENO}: error: \`$ac_var' was set to \`$ac_old_val' in the previous run" >&5 +$as_echo "$as_me: error: \`$ac_var' was set to \`$ac_old_val' in the previous run" >&2;} + ac_cache_corrupted=: ;; + ,set) + { $as_echo "$as_me:${as_lineno-$LINENO}: error: \`$ac_var' was not set in the previous run" >&5 +$as_echo "$as_me: error: \`$ac_var' was not set in the previous run" >&2;} + ac_cache_corrupted=: ;; + ,);; + *) + if test "x$ac_old_val" != "x$ac_new_val"; then + # differences in whitespace do not lead to failure. + ac_old_val_w=`echo x $ac_old_val` + ac_new_val_w=`echo x $ac_new_val` + if test "$ac_old_val_w" != "$ac_new_val_w"; then + { $as_echo "$as_me:${as_lineno-$LINENO}: error: \`$ac_var' has changed since the previous run:" >&5 +$as_echo "$as_me: error: \`$ac_var' has changed since the previous run:" >&2;} + ac_cache_corrupted=: else - ac_sys_release=`uname -r` + { $as_echo "$as_me:${as_lineno-$LINENO}: warning: ignoring whitespace changes in \`$ac_var' since the previous run:" >&5 +$as_echo "$as_me: warning: ignoring whitespace changes in \`$ac_var' since the previous run:" >&2;} + eval $ac_var=\$ac_old_val fi - ac_md_system=`echo $ac_sys_system | - tr -d '/ ' | tr '[A-Z]' '[a-z]'` - ac_md_release=`echo $ac_sys_release | - tr -d '/ ' | sed 's/^[A-Z]\.//' | sed 's/\..*//'` - MACHDEP="$ac_md_system$ac_md_release" - - case $MACHDEP in - cygwin*) MACHDEP="cygwin";; - darwin*) MACHDEP="darwin";; - atheos*) MACHDEP="atheos";; - irix646) MACHDEP="irix6";; - '') MACHDEP="unknown";; - esac + { $as_echo "$as_me:${as_lineno-$LINENO}: former value: \`$ac_old_val'" >&5 +$as_echo "$as_me: former value: \`$ac_old_val'" >&2;} + { $as_echo "$as_me:${as_lineno-$LINENO}: current value: \`$ac_new_val'" >&5 +$as_echo "$as_me: current value: \`$ac_new_val'" >&2;} + fi;; + esac + # Pass precious variables to config.status. + if test "$ac_new_set" = set; then + case $ac_new_val in + *\'*) ac_arg=$ac_var=`$as_echo "$ac_new_val" | sed "s/'/'\\\\\\\\''/g"` ;; + *) ac_arg=$ac_var=$ac_new_val ;; + esac + case " $ac_configure_args " in + *" '$ac_arg' "*) ;; # Avoid dups. Use of quotes ensures accuracy. + *) as_fn_append ac_configure_args " '$ac_arg'" ;; + esac + fi +done +if $ac_cache_corrupted; then + { $as_echo "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5 +$as_echo "$as_me: error: in \`$ac_pwd':" >&2;} + { $as_echo "$as_me:${as_lineno-$LINENO}: error: changes in the environment can compromise the build" >&5 +$as_echo "$as_me: error: changes in the environment can compromise the build" >&2;} + as_fn_error "run \`make distclean' and/or \`rm $cache_file' and start over" "$LINENO" 5 fi +## -------------------- ## +## Main body of script. ## +## -------------------- ## -# Some systems cannot stand _XOPEN_SOURCE being defined at all; they -# disable features if it is defined, without any means to access these -# features as extensions. For these systems, we skip the definition of -# _XOPEN_SOURCE. Before adding a system to the list to gain access to -# some feature, make sure there is no alternative way to access this -# feature. Also, when using wildcards, make sure you have verified the -# need for not defining _XOPEN_SOURCE on all systems matching the -# wildcard, and that the wildcard does not include future systems -# (which may remove their limitations). -case $ac_sys_system/$ac_sys_release in - # On OpenBSD, select(2) is not available if _XOPEN_SOURCE is defined, - # even though select is a POSIX function. Reported by J. Ribbens. - # Reconfirmed for OpenBSD 3.3 by Zachary Hamm, for 3.4 by Jason Ish. - # In addition, Stefan Krah confirms that issue #1244610 exists through - # OpenBSD 4.6, but is fixed in 4.7. - OpenBSD/2.* | OpenBSD/3.[0123456789] | OpenBSD/4.[0123456]) - define_xopen_source=no - # OpenBSD undoes our definition of __BSD_VISIBLE if _XOPEN_SOURCE is - # also defined. This can be overridden by defining _BSD_SOURCE - # As this has a different meaning on Linux, only define it on OpenBSD +ac_ext=c +ac_cpp='$CPP $CPPFLAGS' +ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5' +ac_link='$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5' +ac_compiler_gnu=$ac_cv_c_compiler_gnu -cat >>confdefs.h <<\_ACEOF -#define _BSD_SOURCE 1 -_ACEOF - ;; - OpenBSD/4.[789]) - # OpenBSD undoes our definition of __BSD_VISIBLE if _XOPEN_SOURCE is - # also defined. This can be overridden by defining _BSD_SOURCE - # As this has a different meaning on Linux, only define it on OpenBSD -cat >>confdefs.h <<\_ACEOF -#define _BSD_SOURCE 1 -_ACEOF +ac_config_headers="$ac_config_headers pyconfig.h" - ;; - # Defining _XOPEN_SOURCE on NetBSD version prior to the introduction of - # _NETBSD_SOURCE disables certain features (eg. setgroups). Reported by - # Marc Recht - NetBSD/1.5 | NetBSD/1.5.* | NetBSD/1.6 | NetBSD/1.6.* | NetBSD/1.6[A-S]) - define_xopen_source=no;; - # On Solaris 2.6, sys/wait.h is inconsistent in the usage - # of union __?sigval. Reported by Stuart Bishop. - SunOS/5.6) - define_xopen_source=no;; - # On UnixWare 7, u_long is never defined with _XOPEN_SOURCE, - # but used in /usr/include/netinet/tcp.h. Reported by Tim Rice. - # Reconfirmed for 7.1.4 by Martin v. Loewis. - OpenUNIX/8.0.0| UnixWare/7.1.[0-4]) - define_xopen_source=no;; - # On OpenServer 5, u_short is never defined with _XOPEN_SOURCE, - # but used in struct sockaddr.sa_family. Reported by Tim Rice. - SCO_SV/3.2) - define_xopen_source=no;; - # On FreeBSD 4, the math functions C89 does not cover are never defined - # with _XOPEN_SOURCE and __BSD_VISIBLE does not re-enable them. - FreeBSD/4.*) - define_xopen_source=no;; - # On MacOS X 10.2, a bug in ncurses.h means that it craps out if - # _XOPEN_EXTENDED_SOURCE is defined. Apparently, this is fixed in 10.3, which - # identifies itself as Darwin/7.* - # On Mac OS X 10.4, defining _POSIX_C_SOURCE or _XOPEN_SOURCE - # disables platform specific features beyond repair. - # On Mac OS X 10.3, defining _POSIX_C_SOURCE or _XOPEN_SOURCE - # has no effect, don't bother defining them - Darwin/[6789].*) - define_xopen_source=no;; - Darwin/1[0-9].*) - define_xopen_source=no;; - # On AIX 4 and 5.1, mbstate_t is defined only when _XOPEN_SOURCE == 500 but - # used in wcsnrtombs() and mbsnrtowcs() even if _XOPEN_SOURCE is not defined - # or has another value. By not (re)defining it, the defaults come in place. - AIX/4) - define_xopen_source=no;; - AIX/5) - if test `uname -r` -eq 1; then - define_xopen_source=no - fi - ;; - # On QNX 6.3.2, defining _XOPEN_SOURCE prevents netdb.h from - # defining NI_NUMERICHOST. - QNX/6.3.2) - define_xopen_source=no - ;; -esac -if test $define_xopen_source = yes -then - # On Solaris w/ g++ it appears that _XOPEN_SOURCE has to be - # defined precisely as g++ defines it - # Furthermore, on Solaris 10, XPG6 requires the use of a C99 - # compiler - case $ac_sys_system/$ac_sys_release in - SunOS/5.8|SunOS/5.9|SunOS/5.10) -cat >>confdefs.h <<\_ACEOF -#define _XOPEN_SOURCE 500 -_ACEOF - ;; - *) +# We don't use PACKAGE_ variables, and they cause conflicts +# with other autoconf-based packages that include Python.h +grep -v 'define PACKAGE_' confdefs.h.new +rm confdefs.h +mv confdefs.h.new confdefs.h -cat >>confdefs.h <<\_ACEOF -#define _XOPEN_SOURCE 600 -_ACEOF - ;; - esac +VERSION=2.6 - # On Tru64 Unix 4.0F, defining _XOPEN_SOURCE also requires - # definition of _XOPEN_SOURCE_EXTENDED and _POSIX_C_SOURCE, or else - # several APIs are not declared. Since this is also needed in some - # cases for HP-UX, we define it globally. - # except for Solaris 10, where it must not be defined, - # as it implies XPG4.2 - case $ac_sys_system/$ac_sys_release in - SunOS/5.10) - ;; - *) -cat >>confdefs.h <<\_ACEOF -#define _XOPEN_SOURCE_EXTENDED 1 -_ACEOF +SOVERSION=1.0 - ;; - esac +# The later defininition of _XOPEN_SOURCE disables certain features +# on Linux, so we need _GNU_SOURCE to re-enable them (makedev, tm_zone). +$as_echo "#define _GNU_SOURCE 1" >>confdefs.h -cat >>confdefs.h <<\_ACEOF -#define _POSIX_C_SOURCE 200112L -_ACEOF +# The later defininition of _XOPEN_SOURCE and _POSIX_C_SOURCE disables +# certain features on NetBSD, so we need _NETBSD_SOURCE to re-enable +# them. -fi +$as_echo "#define _NETBSD_SOURCE 1" >>confdefs.h -# -# SGI compilers allow the specification of the both the ABI and the -# ISA on the command line. Depending on the values of these switches, -# different and often incompatable code will be generated. -# -# The SGI_ABI variable can be used to modify the CC and LDFLAGS and -# thus supply support for various ABI/ISA combinations. The MACHDEP -# variable is also adjusted. -# -if test ! -z "$SGI_ABI" -then - CC="cc $SGI_ABI" - LDFLAGS="$SGI_ABI $LDFLAGS" - MACHDEP=`echo "${MACHDEP}${SGI_ABI}" | sed 's/ *//g'` -fi -{ $as_echo "$as_me:$LINENO: result: $MACHDEP" >&5 -$as_echo "$MACHDEP" >&6; } +# The later defininition of _XOPEN_SOURCE and _POSIX_C_SOURCE disables +# certain features on FreeBSD, so we need __BSD_VISIBLE to re-enable +# them. -# And add extra plat-mac for darwin +$as_echo "#define __BSD_VISIBLE 1" >>confdefs.h -{ $as_echo "$as_me:$LINENO: checking EXTRAPLATDIR" >&5 -$as_echo_n "checking EXTRAPLATDIR... " >&6; } -if test -z "$EXTRAPLATDIR" -then - case $MACHDEP in - darwin) - EXTRAPLATDIR="\$(PLATMACDIRS)" - EXTRAMACHDEPPATH="\$(PLATMACPATH)" - ;; - *) - EXTRAPLATDIR="" - EXTRAMACHDEPPATH="" - ;; - esac -fi -{ $as_echo "$as_me:$LINENO: result: $EXTRAPLATDIR" >&5 -$as_echo "$EXTRAPLATDIR" >&6; } +# The later defininition of _XOPEN_SOURCE and _POSIX_C_SOURCE disables +# u_int on Irix 5.3. Defining _BSD_TYPES brings it back. -# Record the configure-time value of MACOSX_DEPLOYMENT_TARGET, -# it may influence the way we can build extensions, so distutils -# needs to check it +$as_echo "#define _BSD_TYPES 1" >>confdefs.h -CONFIGURE_MACOSX_DEPLOYMENT_TARGET= -EXPORT_MACOSX_DEPLOYMENT_TARGET='#' +# The later defininition of _XOPEN_SOURCE and _POSIX_C_SOURCE disables +# certain features on Mac OS X, so we need _DARWIN_C_SOURCE to re-enable +# them. -{ $as_echo "$as_me:$LINENO: checking machine type as reported by uname -m" >&5 -$as_echo_n "checking machine type as reported by uname -m... " >&6; } -ac_sys_machine=`uname -m` -{ $as_echo "$as_me:$LINENO: result: $ac_sys_machine" >&5 -$as_echo "$ac_sys_machine" >&6; } +$as_echo "#define _DARWIN_C_SOURCE 1" >>confdefs.h -# checks for alternative programs -# compiler flags are generated in two sets, BASECFLAGS and OPT. OPT is just -# for debug/optimization stuff. BASECFLAGS is for flags that are required -# just to get things to compile and link. Users are free to override OPT -# when running configure or make. The build should not break if they do. -# BASECFLAGS should generally not be messed with, however. -# XXX shouldn't some/most/all of this code be merged with the stuff later -# on that fiddles with OPT and BASECFLAGS? -{ $as_echo "$as_me:$LINENO: checking for --without-gcc" >&5 -$as_echo_n "checking for --without-gcc... " >&6; } +define_xopen_source=yes -# Check whether --with-gcc was given. -if test "${with_gcc+set}" = set; then - withval=$with_gcc; - case $withval in - no) CC=${CC:-cc} - without_gcc=yes;; - yes) CC=gcc - without_gcc=no;; - *) CC=$withval - without_gcc=$withval;; - esac -else +# Arguments passed to configure. - case $ac_sys_system in - AIX*) CC=cc_r - without_gcc=;; - BeOS*) - case $BE_HOST_CPU in - ppc) - CC=mwcc - without_gcc=yes - BASECFLAGS="$BASECFLAGS -export pragma" - OPT="$OPT -O" - LDFLAGS="$LDFLAGS -nodup" - ;; - x86) - CC=gcc - without_gcc=no - OPT="$OPT -O" - ;; - *) - { { $as_echo "$as_me:$LINENO: error: Unknown BeOS platform \"$BE_HOST_CPU\"" >&5 -$as_echo "$as_me: error: Unknown BeOS platform \"$BE_HOST_CPU\"" >&2;} - { (exit 1); exit 1; }; } - ;; - esac - AR="\$(srcdir)/Modules/ar_beos" - RANLIB=: +CONFIG_ARGS="$ac_configure_args" + +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for --enable-universalsdk" >&5 +$as_echo_n "checking for --enable-universalsdk... " >&6; } +# Check whether --enable-universalsdk was given. +if test "${enable_universalsdk+set}" = set; then : + enableval=$enable_universalsdk; + case $enableval in + yes) + enableval=/Developer/SDKs/MacOSX10.4u.sdk + if test ! -d "${enableval}" + then + enableval=/ + fi + ;; + esac + case $enableval in + no) + UNIVERSALSDK= + enable_universalsdk= + ;; + *) + UNIVERSALSDK=$enableval + if test ! -d "${UNIVERSALSDK}" + then + as_fn_error "--enable-universalsdk specifies non-existing SDK: ${UNIVERSALSDK}" "$LINENO" 5 + fi ;; - Monterey*) - RANLIB=: - without_gcc=;; - *) without_gcc=no;; esac -fi - -{ $as_echo "$as_me:$LINENO: result: $without_gcc" >&5 -$as_echo "$without_gcc" >&6; } -# If the user switches compilers, we can't believe the cache -if test ! -z "$ac_cv_prog_CC" -a ! -z "$CC" -a "$CC" != "$ac_cv_prog_CC" -then - { { $as_echo "$as_me:$LINENO: error: cached CC is different -- throw away $cache_file -(it is also a good idea to do 'make clean' before compiling)" >&5 -$as_echo "$as_me: error: cached CC is different -- throw away $cache_file -(it is also a good idea to do 'make clean' before compiling)" >&2;} - { (exit 1); exit 1; }; } -fi -ac_ext=c -ac_cpp='$CPP $CPPFLAGS' -ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5' -ac_link='$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5' -ac_compiler_gnu=$ac_cv_c_compiler_gnu -if test -n "$ac_tool_prefix"; then - # Extract the first word of "${ac_tool_prefix}gcc", so it can be a program name with args. -set dummy ${ac_tool_prefix}gcc; ac_word=$2 -{ $as_echo "$as_me:$LINENO: checking for $ac_word" >&5 -$as_echo_n "checking for $ac_word... " >&6; } -if test "${ac_cv_prog_CC+set}" = set; then - $as_echo_n "(cached) " >&6 -else - if test -n "$CC"; then - ac_cv_prog_CC="$CC" # Let the user override the test. else -as_save_IFS=$IFS; IFS=$PATH_SEPARATOR -for as_dir in $PATH -do - IFS=$as_save_IFS - test -z "$as_dir" && as_dir=. - for ac_exec_ext in '' $ac_executable_extensions; do - if { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_test_x "$as_dir/$ac_word$ac_exec_ext"; }; then - ac_cv_prog_CC="${ac_tool_prefix}gcc" - $as_echo "$as_me:$LINENO: found $as_dir/$ac_word$ac_exec_ext" >&5 - break 2 - fi -done -done -IFS=$as_save_IFS + + UNIVERSALSDK= + enable_universalsdk= fi -fi -CC=$ac_cv_prog_CC -if test -n "$CC"; then - { $as_echo "$as_me:$LINENO: result: $CC" >&5 -$as_echo "$CC" >&6; } + +if test -n "${UNIVERSALSDK}" +then + { $as_echo "$as_me:${as_lineno-$LINENO}: result: ${UNIVERSALSDK}" >&5 +$as_echo "${UNIVERSALSDK}" >&6; } else - { $as_echo "$as_me:$LINENO: result: no" >&5 + { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 $as_echo "no" >&6; } fi -fi -if test -z "$ac_cv_prog_CC"; then - ac_ct_CC=$CC - # Extract the first word of "gcc", so it can be a program name with args. -set dummy gcc; ac_word=$2 -{ $as_echo "$as_me:$LINENO: checking for $ac_word" >&5 -$as_echo_n "checking for $ac_word... " >&6; } -if test "${ac_cv_prog_ac_ct_CC+set}" = set; then - $as_echo_n "(cached) " >&6 -else - if test -n "$ac_ct_CC"; then - ac_cv_prog_ac_ct_CC="$ac_ct_CC" # Let the user override the test. -else -as_save_IFS=$IFS; IFS=$PATH_SEPARATOR -for as_dir in $PATH -do - IFS=$as_save_IFS - test -z "$as_dir" && as_dir=. - for ac_exec_ext in '' $ac_executable_extensions; do - if { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_test_x "$as_dir/$ac_word$ac_exec_ext"; }; then - ac_cv_prog_ac_ct_CC="gcc" - $as_echo "$as_me:$LINENO: found $as_dir/$ac_word$ac_exec_ext" >&5 - break 2 - fi -done -done -IFS=$as_save_IFS -fi -fi -ac_ct_CC=$ac_cv_prog_ac_ct_CC -if test -n "$ac_ct_CC"; then - { $as_echo "$as_me:$LINENO: result: $ac_ct_CC" >&5 -$as_echo "$ac_ct_CC" >&6; } -else - { $as_echo "$as_me:$LINENO: result: no" >&5 -$as_echo "no" >&6; } -fi - if test "x$ac_ct_CC" = x; then - CC="" - else - case $cross_compiling:$ac_tool_warned in -yes:) -{ $as_echo "$as_me:$LINENO: WARNING: using cross tools not prefixed with host triplet" >&5 -$as_echo "$as_me: WARNING: using cross tools not prefixed with host triplet" >&2;} -ac_tool_warned=yes ;; -esac - CC=$ac_ct_CC - fi -else - CC="$ac_cv_prog_CC" -fi +UNIVERSAL_ARCHS="32-bit" + + +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for --with-universal-archs" >&5 +$as_echo_n "checking for --with-universal-archs... " >&6; } + +# Check whether --with-universal-archs was given. +if test "${with_universal_archs+set}" = set; then : + withval=$with_universal_archs; + { $as_echo "$as_me:${as_lineno-$LINENO}: result: $withval" >&5 +$as_echo "$withval" >&6; } + UNIVERSAL_ARCHS="$withval" + if test "${enable_universalsdk}" ; then + : + else + as_fn_error "--with-universal-archs without --enable-universalsdk. See Mac/README" "$LINENO" 5 + fi -if test -z "$CC"; then - if test -n "$ac_tool_prefix"; then - # Extract the first word of "${ac_tool_prefix}cc", so it can be a program name with args. -set dummy ${ac_tool_prefix}cc; ac_word=$2 -{ $as_echo "$as_me:$LINENO: checking for $ac_word" >&5 -$as_echo_n "checking for $ac_word... " >&6; } -if test "${ac_cv_prog_CC+set}" = set; then - $as_echo_n "(cached) " >&6 -else - if test -n "$CC"; then - ac_cv_prog_CC="$CC" # Let the user override the test. else -as_save_IFS=$IFS; IFS=$PATH_SEPARATOR -for as_dir in $PATH -do - IFS=$as_save_IFS - test -z "$as_dir" && as_dir=. - for ac_exec_ext in '' $ac_executable_extensions; do - if { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_test_x "$as_dir/$ac_word$ac_exec_ext"; }; then - ac_cv_prog_CC="${ac_tool_prefix}cc" - $as_echo "$as_me:$LINENO: found $as_dir/$ac_word$ac_exec_ext" >&5 - break 2 - fi -done -done -IFS=$as_save_IFS + + { $as_echo "$as_me:${as_lineno-$LINENO}: result: 32-bit" >&5 +$as_echo "32-bit" >&6; } fi -fi -CC=$ac_cv_prog_CC -if test -n "$CC"; then - { $as_echo "$as_me:$LINENO: result: $CC" >&5 -$as_echo "$CC" >&6; } + + + + + +# Check whether --with-framework-name was given. +if test "${with_framework_name+set}" = set; then : + withval=$with_framework_name; + if test "${enable_framework}"; then + : + else + as_fn_error "--with-framework-name without --enable-framework. See Mac/README" "$LINENO" 5 + fi + PYTHONFRAMEWORK=${withval} + PYTHONFRAMEWORKDIR=${withval}.framework + PYTHONFRAMEWORKIDENTIFIER=org.python.`echo $withval | tr 'A-Z' 'a-z'` + else - { $as_echo "$as_me:$LINENO: result: no" >&5 -$as_echo "no" >&6; } -fi + PYTHONFRAMEWORK=Python + PYTHONFRAMEWORKDIR=Python.framework + PYTHONFRAMEWORKIDENTIFIER=org.python.python - fi fi -if test -z "$CC"; then - # Extract the first word of "cc", so it can be a program name with args. -set dummy cc; ac_word=$2 -{ $as_echo "$as_me:$LINENO: checking for $ac_word" >&5 -$as_echo_n "checking for $ac_word... " >&6; } -if test "${ac_cv_prog_CC+set}" = set; then - $as_echo_n "(cached) " >&6 -else - if test -n "$CC"; then - ac_cv_prog_CC="$CC" # Let the user override the test. -else - ac_prog_rejected=no -as_save_IFS=$IFS; IFS=$PATH_SEPARATOR -for as_dir in $PATH -do - IFS=$as_save_IFS - test -z "$as_dir" && as_dir=. - for ac_exec_ext in '' $ac_executable_extensions; do - if { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_test_x "$as_dir/$ac_word$ac_exec_ext"; }; then - if test "$as_dir/$ac_word$ac_exec_ext" = "/usr/ucb/cc"; then - ac_prog_rejected=yes - continue - fi - ac_cv_prog_CC="cc" - $as_echo "$as_me:$LINENO: found $as_dir/$ac_word$ac_exec_ext" >&5 - break 2 - fi -done -done -IFS=$as_save_IFS -if test $ac_prog_rejected = yes; then - # We found a bogon in the path, so make sure we never use it. - set dummy $ac_cv_prog_CC - shift - if test $# != 0; then - # We chose a different compiler from the bogus one. - # However, it has the same basename, so the bogon will be chosen - # first if we set CC to just the basename; use the full file name. - shift - ac_cv_prog_CC="$as_dir/$ac_word${1+' '}$@" - fi -fi -fi -fi -CC=$ac_cv_prog_CC -if test -n "$CC"; then - { $as_echo "$as_me:$LINENO: result: $CC" >&5 -$as_echo "$CC" >&6; } -else - { $as_echo "$as_me:$LINENO: result: no" >&5 -$as_echo "no" >&6; } -fi +# Check whether --enable-framework was given. +if test "${enable_framework+set}" = set; then : + enableval=$enable_framework; + case $enableval in + yes) + enableval=/Library/Frameworks + esac + case $enableval in + no) + PYTHONFRAMEWORK= + PYTHONFRAMEWORKDIR=no-framework + PYTHONFRAMEWORKPREFIX= + PYTHONFRAMEWORKINSTALLDIR= + FRAMEWORKINSTALLFIRST= + FRAMEWORKINSTALLLAST= + FRAMEWORKALTINSTALLFIRST= + FRAMEWORKALTINSTALLLAST= + if test "x${prefix}" = "xNONE"; then + FRAMEWORKUNIXTOOLSPREFIX="${ac_default_prefix}" + else + FRAMEWORKUNIXTOOLSPREFIX="${prefix}" + fi + enable_framework= + ;; + *) + PYTHONFRAMEWORKPREFIX=$enableval + PYTHONFRAMEWORKINSTALLDIR=$PYTHONFRAMEWORKPREFIX/$PYTHONFRAMEWORKDIR + FRAMEWORKINSTALLFIRST="frameworkinstallstructure" + FRAMEWORKALTINSTALLFIRST="frameworkinstallstructure bininstall maninstall" + case "${UNIVERSAL_ARCHS}" in + all|3-way|intel) + FRAMEWORKINSTALLLAST="frameworkinstallmaclib frameworkinstallapps4way frameworkinstallunixtools4way" + FRAMEWORKALTINSTALLLAST="frameworkinstallmaclib frameworkinstallapps4way frameworkaltinstallunixtools4way" + ;; + *) + FRAMEWORKINSTALLLAST="frameworkinstallmaclib frameworkinstallapps frameworkinstallunixtools" + FRAMEWORKALTINSTALLLAST="frameworkinstallmaclib frameworkinstallapps frameworkaltinstallunixtools" + ;; + esac + if test "x${prefix}" = "xNONE" ; then + FRAMEWORKUNIXTOOLSPREFIX="${ac_default_prefix}" + else + FRAMEWORKUNIXTOOLSPREFIX="${prefix}" + fi + prefix=$PYTHONFRAMEWORKINSTALLDIR/Versions/$VERSION -fi -if test -z "$CC"; then - if test -n "$ac_tool_prefix"; then - for ac_prog in cl.exe - do - # Extract the first word of "$ac_tool_prefix$ac_prog", so it can be a program name with args. -set dummy $ac_tool_prefix$ac_prog; ac_word=$2 -{ $as_echo "$as_me:$LINENO: checking for $ac_word" >&5 -$as_echo_n "checking for $ac_word... " >&6; } -if test "${ac_cv_prog_CC+set}" = set; then - $as_echo_n "(cached) " >&6 -else - if test -n "$CC"; then - ac_cv_prog_CC="$CC" # Let the user override the test. -else -as_save_IFS=$IFS; IFS=$PATH_SEPARATOR -for as_dir in $PATH -do - IFS=$as_save_IFS - test -z "$as_dir" && as_dir=. - for ac_exec_ext in '' $ac_executable_extensions; do - if { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_test_x "$as_dir/$ac_word$ac_exec_ext"; }; then - ac_cv_prog_CC="$ac_tool_prefix$ac_prog" - $as_echo "$as_me:$LINENO: found $as_dir/$ac_word$ac_exec_ext" >&5 - break 2 - fi -done -done -IFS=$as_save_IFS + # Add files for Mac specific code to the list of output + # files: + ac_config_files="$ac_config_files Mac/Makefile" -fi -fi -CC=$ac_cv_prog_CC -if test -n "$CC"; then - { $as_echo "$as_me:$LINENO: result: $CC" >&5 -$as_echo "$CC" >&6; } -else - { $as_echo "$as_me:$LINENO: result: no" >&5 -$as_echo "no" >&6; } -fi + ac_config_files="$ac_config_files Mac/PythonLauncher/Makefile" + ac_config_files="$ac_config_files Mac/IDLE/Makefile" - test -n "$CC" && break - done -fi -if test -z "$CC"; then - ac_ct_CC=$CC - for ac_prog in cl.exe -do - # Extract the first word of "$ac_prog", so it can be a program name with args. -set dummy $ac_prog; ac_word=$2 -{ $as_echo "$as_me:$LINENO: checking for $ac_word" >&5 -$as_echo_n "checking for $ac_word... " >&6; } -if test "${ac_cv_prog_ac_ct_CC+set}" = set; then - $as_echo_n "(cached) " >&6 -else - if test -n "$ac_ct_CC"; then - ac_cv_prog_ac_ct_CC="$ac_ct_CC" # Let the user override the test. -else -as_save_IFS=$IFS; IFS=$PATH_SEPARATOR -for as_dir in $PATH -do - IFS=$as_save_IFS - test -z "$as_dir" && as_dir=. - for ac_exec_ext in '' $ac_executable_extensions; do - if { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_test_x "$as_dir/$ac_word$ac_exec_ext"; }; then - ac_cv_prog_ac_ct_CC="$ac_prog" - $as_echo "$as_me:$LINENO: found $as_dir/$ac_word$ac_exec_ext" >&5 - break 2 - fi -done -done -IFS=$as_save_IFS + ac_config_files="$ac_config_files Mac/Resources/framework/Info.plist" + + ac_config_files="$ac_config_files Mac/Resources/app/Info.plist" + + esac -fi -fi -ac_ct_CC=$ac_cv_prog_ac_ct_CC -if test -n "$ac_ct_CC"; then - { $as_echo "$as_me:$LINENO: result: $ac_ct_CC" >&5 -$as_echo "$ac_ct_CC" >&6; } else - { $as_echo "$as_me:$LINENO: result: no" >&5 -$as_echo "no" >&6; } -fi + PYTHONFRAMEWORK= + PYTHONFRAMEWORKDIR=no-framework + PYTHONFRAMEWORKPREFIX= + PYTHONFRAMEWORKINSTALLDIR= + FRAMEWORKINSTALLFIRST= + FRAMEWORKINSTALLLAST= + FRAMEWORKALTINSTALLFIRST= + FRAMEWORKALTINSTALLLAST= + if test "x${prefix}" = "xNONE" ; then + FRAMEWORKUNIXTOOLSPREFIX="${ac_default_prefix}" + else + FRAMEWORKUNIXTOOLSPREFIX="${prefix}" + fi + enable_framework= - test -n "$ac_ct_CC" && break -done + if test "$UNIVERSAL_ARCHS" = "all" + then + FRAMEWORKINSTALLLAST=update4wayuniversal + FRAMEWORKALTINSTALLLAST=update4wayuniversal + fi - if test "x$ac_ct_CC" = x; then - CC="" - else - case $cross_compiling:$ac_tool_warned in -yes:) -{ $as_echo "$as_me:$LINENO: WARNING: using cross tools not prefixed with host triplet" >&5 -$as_echo "$as_me: WARNING: using cross tools not prefixed with host triplet" >&2;} -ac_tool_warned=yes ;; -esac - CC=$ac_ct_CC - fi fi -fi -test -z "$CC" && { { $as_echo "$as_me:$LINENO: error: in \`$ac_pwd':" >&5 -$as_echo "$as_me: error: in \`$ac_pwd':" >&2;} -{ { $as_echo "$as_me:$LINENO: error: no acceptable C compiler found in \$PATH -See \`config.log' for more details." >&5 -$as_echo "$as_me: error: no acceptable C compiler found in \$PATH -See \`config.log' for more details." >&2;} - { (exit 1); exit 1; }; }; } -# Provide some information about the compiler. -$as_echo "$as_me:$LINENO: checking for C compiler version" >&5 -set X $ac_compile -ac_compiler=$2 -{ (ac_try="$ac_compiler --version >&5" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" -$as_echo "$ac_try_echo") >&5 - (eval "$ac_compiler --version >&5") 2>&5 - ac_status=$? - $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } -{ (ac_try="$ac_compiler -v >&5" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" -$as_echo "$ac_try_echo") >&5 - (eval "$ac_compiler -v >&5") 2>&5 - ac_status=$? - $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } -{ (ac_try="$ac_compiler -V >&5" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" -$as_echo "$ac_try_echo") >&5 - (eval "$ac_compiler -V >&5") 2>&5 - ac_status=$? - $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } -cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -int -main () -{ - ; - return 0; -} -_ACEOF -ac_clean_files_save=$ac_clean_files -ac_clean_files="$ac_clean_files a.out a.out.dSYM a.exe b.out" -# Try to create an executable without -o first, disregard a.out. -# It will help us diagnose broken compilers, and finding out an intuition -# of exeext. -{ $as_echo "$as_me:$LINENO: checking for C compiler default output file name" >&5 -$as_echo_n "checking for C compiler default output file name... " >&6; } -ac_link_default=`$as_echo "$ac_link" | sed 's/ -o *conftest[^ ]*//'` -# The possible output files: -ac_files="a.out conftest.exe conftest a.exe a_out.exe b.out conftest.*" -ac_rmfiles= -for ac_file in $ac_files -do - case $ac_file in - *.$ac_ext | *.xcoff | *.tds | *.d | *.pdb | *.xSYM | *.bb | *.bbg | *.map | *.inf | *.dSYM | *.o | *.obj ) ;; - * ) ac_rmfiles="$ac_rmfiles $ac_file";; - esac -done -rm -f $ac_rmfiles -if { (ac_try="$ac_link_default" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" -$as_echo "$ac_try_echo") >&5 - (eval "$ac_link_default") 2>&5 - ac_status=$? - $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); }; then - # Autoconf-2.13 could set the ac_cv_exeext variable to `no'. -# So ignore a value of `no', otherwise this would lead to `EXEEXT = no' -# in a Makefile. We should not override ac_cv_exeext if it was cached, -# so that the user can short-circuit this test for compilers unknown to -# Autoconf. -for ac_file in $ac_files '' -do - test -f "$ac_file" || continue - case $ac_file in - *.$ac_ext | *.xcoff | *.tds | *.d | *.pdb | *.xSYM | *.bb | *.bbg | *.map | *.inf | *.dSYM | *.o | *.obj ) - ;; - [ab].out ) - # We found the default executable, but exeext='' is most - # certainly right. - break;; - *.* ) - if test "${ac_cv_exeext+set}" = set && test "$ac_cv_exeext" != no; - then :; else - ac_cv_exeext=`expr "$ac_file" : '[^.]*\(\..*\)'` - fi - # We set ac_cv_exeext here because the later test for it is not - # safe: cross compilers may not add the suffix if given an `-o' - # argument, so we may need to know it at that point already. - # Even if this section looks crufty: it has the advantage of - # actually working. - break;; - * ) - break;; - esac -done -test "$ac_cv_exeext" = no && ac_cv_exeext= - -else - ac_file='' -fi -{ $as_echo "$as_me:$LINENO: result: $ac_file" >&5 -$as_echo "$ac_file" >&6; } -if test -z "$ac_file"; then - $as_echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 -{ { $as_echo "$as_me:$LINENO: error: in \`$ac_pwd':" >&5 -$as_echo "$as_me: error: in \`$ac_pwd':" >&2;} -{ { $as_echo "$as_me:$LINENO: error: C compiler cannot create executables -See \`config.log' for more details." >&5 -$as_echo "$as_me: error: C compiler cannot create executables -See \`config.log' for more details." >&2;} - { (exit 77); exit 77; }; }; } -fi +##AC_ARG_WITH(dyld, +## AC_HELP_STRING(--with-dyld, +## Use (OpenStep|Rhapsody) dynamic linker)) +## +# Set name for machine-dependent library files -ac_exeext=$ac_cv_exeext +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking MACHDEP" >&5 +$as_echo_n "checking MACHDEP... " >&6; } +if test -z "$MACHDEP" +then + ac_sys_system=`uname -s` + if test "$ac_sys_system" = "AIX" -o "$ac_sys_system" = "Monterey64" \ + -o "$ac_sys_system" = "UnixWare" -o "$ac_sys_system" = "OpenUNIX"; then + ac_sys_release=`uname -v` + else + ac_sys_release=`uname -r` + fi + ac_md_system=`echo $ac_sys_system | + tr -d '/ ' | tr '[A-Z]' '[a-z]'` + ac_md_release=`echo $ac_sys_release | + tr -d '/ ' | sed 's/^[A-Z]\.//' | sed 's/\..*//'` + MACHDEP="$ac_md_system$ac_md_release" -# Check that the compiler produces executables we can run. If not, either -# the compiler is broken, or we cross compile. -{ $as_echo "$as_me:$LINENO: checking whether the C compiler works" >&5 -$as_echo_n "checking whether the C compiler works... " >&6; } -# FIXME: These cross compiler hacks should be removed for Autoconf 3.0 -# If not cross compiling, check that we can run a simple program. -if test "$cross_compiling" != yes; then - if { ac_try='./$ac_file' - { (case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" -$as_echo "$ac_try_echo") >&5 - (eval "$ac_try") 2>&5 - ac_status=$? - $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); }; }; then - cross_compiling=no - else - if test "$cross_compiling" = maybe; then - cross_compiling=yes - else - { { $as_echo "$as_me:$LINENO: error: in \`$ac_pwd':" >&5 -$as_echo "$as_me: error: in \`$ac_pwd':" >&2;} -{ { $as_echo "$as_me:$LINENO: error: cannot run C compiled programs. -If you meant to cross compile, use \`--host'. -See \`config.log' for more details." >&5 -$as_echo "$as_me: error: cannot run C compiled programs. -If you meant to cross compile, use \`--host'. -See \`config.log' for more details." >&2;} - { (exit 1); exit 1; }; }; } - fi - fi + case $MACHDEP in + cygwin*) MACHDEP="cygwin";; + darwin*) MACHDEP="darwin";; + atheos*) MACHDEP="atheos";; + irix646) MACHDEP="irix6";; + '') MACHDEP="unknown";; + esac fi -{ $as_echo "$as_me:$LINENO: result: yes" >&5 -$as_echo "yes" >&6; } -rm -f -r a.out a.out.dSYM a.exe conftest$ac_cv_exeext b.out -ac_clean_files=$ac_clean_files_save -# Check that the compiler produces executables we can run. If not, either -# the compiler is broken, or we cross compile. -{ $as_echo "$as_me:$LINENO: checking whether we are cross compiling" >&5 -$as_echo_n "checking whether we are cross compiling... " >&6; } -{ $as_echo "$as_me:$LINENO: result: $cross_compiling" >&5 -$as_echo "$cross_compiling" >&6; } +# Some systems cannot stand _XOPEN_SOURCE being defined at all; they +# disable features if it is defined, without any means to access these +# features as extensions. For these systems, we skip the definition of +# _XOPEN_SOURCE. Before adding a system to the list to gain access to +# some feature, make sure there is no alternative way to access this +# feature. Also, when using wildcards, make sure you have verified the +# need for not defining _XOPEN_SOURCE on all systems matching the +# wildcard, and that the wildcard does not include future systems +# (which may remove their limitations). +case $ac_sys_system/$ac_sys_release in + # On OpenBSD, select(2) is not available if _XOPEN_SOURCE is defined, + # even though select is a POSIX function. Reported by J. Ribbens. + # Reconfirmed for OpenBSD 3.3 by Zachary Hamm, for 3.4 by Jason Ish. + # In addition, Stefan Krah confirms that issue #1244610 exists through + # OpenBSD 4.6, but is fixed in 4.7. + OpenBSD/2.* | OpenBSD/3.[0123456789] | OpenBSD/4.[0123456]) + define_xopen_source=no + # OpenBSD undoes our definition of __BSD_VISIBLE if _XOPEN_SOURCE is + # also defined. This can be overridden by defining _BSD_SOURCE + # As this has a different meaning on Linux, only define it on OpenBSD -{ $as_echo "$as_me:$LINENO: checking for suffix of executables" >&5 -$as_echo_n "checking for suffix of executables... " >&6; } -if { (ac_try="$ac_link" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" -$as_echo "$ac_try_echo") >&5 - (eval "$ac_link") 2>&5 - ac_status=$? - $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); }; then - # If both `conftest.exe' and `conftest' are `present' (well, observable) -# catch `conftest.exe'. For instance with Cygwin, `ls conftest' will -# work properly (i.e., refer to `conftest.exe'), while it won't with -# `rm'. -for ac_file in conftest.exe conftest conftest.*; do - test -f "$ac_file" || continue - case $ac_file in - *.$ac_ext | *.xcoff | *.tds | *.d | *.pdb | *.xSYM | *.bb | *.bbg | *.map | *.inf | *.dSYM | *.o | *.obj ) ;; - *.* ) ac_cv_exeext=`expr "$ac_file" : '[^.]*\(\..*\)'` - break;; - * ) break;; - esac -done -else - { { $as_echo "$as_me:$LINENO: error: in \`$ac_pwd':" >&5 -$as_echo "$as_me: error: in \`$ac_pwd':" >&2;} -{ { $as_echo "$as_me:$LINENO: error: cannot compute suffix of executables: cannot compile and link -See \`config.log' for more details." >&5 -$as_echo "$as_me: error: cannot compute suffix of executables: cannot compile and link -See \`config.log' for more details." >&2;} - { (exit 1); exit 1; }; }; } -fi +$as_echo "#define _BSD_SOURCE 1" >>confdefs.h -rm -f conftest$ac_cv_exeext -{ $as_echo "$as_me:$LINENO: result: $ac_cv_exeext" >&5 -$as_echo "$ac_cv_exeext" >&6; } + ;; + OpenBSD/4.[789]) + # OpenBSD undoes our definition of __BSD_VISIBLE if _XOPEN_SOURCE is + # also defined. This can be overridden by defining _BSD_SOURCE + # As this has a different meaning on Linux, only define it on OpenBSD -rm -f conftest.$ac_ext -EXEEXT=$ac_cv_exeext -ac_exeext=$EXEEXT -{ $as_echo "$as_me:$LINENO: checking for suffix of object files" >&5 -$as_echo_n "checking for suffix of object files... " >&6; } -if test "${ac_cv_objext+set}" = set; then - $as_echo_n "(cached) " >&6 -else - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ +$as_echo "#define _BSD_SOURCE 1" >>confdefs.h -int -main () -{ + ;; + # Defining _XOPEN_SOURCE on NetBSD version prior to the introduction of + # _NETBSD_SOURCE disables certain features (eg. setgroups). Reported by + # Marc Recht + NetBSD/1.5 | NetBSD/1.5.* | NetBSD/1.6 | NetBSD/1.6.* | NetBSD/1.6[A-S]) + define_xopen_source=no;; + # On Solaris 2.6, sys/wait.h is inconsistent in the usage + # of union __?sigval. Reported by Stuart Bishop. + SunOS/5.6) + define_xopen_source=no;; + # On UnixWare 7, u_long is never defined with _XOPEN_SOURCE, + # but used in /usr/include/netinet/tcp.h. Reported by Tim Rice. + # Reconfirmed for 7.1.4 by Martin v. Loewis. + OpenUNIX/8.0.0| UnixWare/7.1.[0-4]) + define_xopen_source=no;; + # On OpenServer 5, u_short is never defined with _XOPEN_SOURCE, + # but used in struct sockaddr.sa_family. Reported by Tim Rice. + SCO_SV/3.2) + define_xopen_source=no;; + # On FreeBSD 4, the math functions C89 does not cover are never defined + # with _XOPEN_SOURCE and __BSD_VISIBLE does not re-enable them. + FreeBSD/4.*) + define_xopen_source=no;; + # On MacOS X 10.2, a bug in ncurses.h means that it craps out if + # _XOPEN_EXTENDED_SOURCE is defined. Apparently, this is fixed in 10.3, which + # identifies itself as Darwin/7.* + # On Mac OS X 10.4, defining _POSIX_C_SOURCE or _XOPEN_SOURCE + # disables platform specific features beyond repair. + # On Mac OS X 10.3, defining _POSIX_C_SOURCE or _XOPEN_SOURCE + # has no effect, don't bother defining them + Darwin/[6789].*) + define_xopen_source=no;; + Darwin/1[0-9].*) + define_xopen_source=no;; + # On AIX 4 and 5.1, mbstate_t is defined only when _XOPEN_SOURCE == 500 but + # used in wcsnrtombs() and mbsnrtowcs() even if _XOPEN_SOURCE is not defined + # or has another value. By not (re)defining it, the defaults come in place. + AIX/4) + define_xopen_source=no;; + AIX/5) + if test `uname -r` -eq 1; then + define_xopen_source=no + fi + ;; + # On QNX 6.3.2, defining _XOPEN_SOURCE prevents netdb.h from + # defining NI_NUMERICHOST. + QNX/6.3.2) + define_xopen_source=no + ;; - ; - return 0; -} -_ACEOF -rm -f conftest.o conftest.obj -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; esac -eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" -$as_echo "$ac_try_echo") >&5 - (eval "$ac_compile") 2>&5 - ac_status=$? - $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); }; then - for ac_file in conftest.o conftest.obj conftest.*; do - test -f "$ac_file" || continue; - case $ac_file in - *.$ac_ext | *.xcoff | *.tds | *.d | *.pdb | *.xSYM | *.bb | *.bbg | *.map | *.inf | *.dSYM ) ;; - *) ac_cv_objext=`expr "$ac_file" : '.*\.\(.*\)'` - break;; - esac -done -else - $as_echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 -{ { $as_echo "$as_me:$LINENO: error: in \`$ac_pwd':" >&5 -$as_echo "$as_me: error: in \`$ac_pwd':" >&2;} -{ { $as_echo "$as_me:$LINENO: error: cannot compute suffix of object files: cannot compile -See \`config.log' for more details." >&5 -$as_echo "$as_me: error: cannot compute suffix of object files: cannot compile -See \`config.log' for more details." >&2;} - { (exit 1); exit 1; }; }; } -fi +if test $define_xopen_source = yes +then + # On Solaris w/ g++ it appears that _XOPEN_SOURCE has to be + # defined precisely as g++ defines it + # Furthermore, on Solaris 10, XPG6 requires the use of a C99 + # compiler + case $ac_sys_system/$ac_sys_release in + SunOS/5.8|SunOS/5.9|SunOS/5.10) -rm -f conftest.$ac_cv_objext conftest.$ac_ext -fi -{ $as_echo "$as_me:$LINENO: result: $ac_cv_objext" >&5 -$as_echo "$ac_cv_objext" >&6; } -OBJEXT=$ac_cv_objext -ac_objext=$OBJEXT -{ $as_echo "$as_me:$LINENO: checking whether we are using the GNU C compiler" >&5 -$as_echo_n "checking whether we are using the GNU C compiler... " >&6; } -if test "${ac_cv_c_compiler_gnu+set}" = set; then - $as_echo_n "(cached) " >&6 -else - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ +$as_echo "#define _XOPEN_SOURCE 500" >>confdefs.h -int -main () -{ -#ifndef __GNUC__ - choke me -#endif + ;; + *) - ; - return 0; -} -_ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" -$as_echo "$ac_try_echo") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - ac_compiler_gnu=yes -else - $as_echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 +$as_echo "#define _XOPEN_SOURCE 600" >>confdefs.h - ac_compiler_gnu=no -fi + ;; + esac -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext -ac_cv_c_compiler_gnu=$ac_compiler_gnu + # On Tru64 Unix 4.0F, defining _XOPEN_SOURCE also requires + # definition of _XOPEN_SOURCE_EXTENDED and _POSIX_C_SOURCE, or else + # several APIs are not declared. Since this is also needed in some + # cases for HP-UX, we define it globally. + # except for Solaris 10, where it must not be defined, + # as it implies XPG4.2 + case $ac_sys_system/$ac_sys_release in + SunOS/5.10) + ;; + *) -fi -{ $as_echo "$as_me:$LINENO: result: $ac_cv_c_compiler_gnu" >&5 -$as_echo "$ac_cv_c_compiler_gnu" >&6; } -if test $ac_compiler_gnu = yes; then - GCC=yes -else - GCC= -fi -ac_test_CFLAGS=${CFLAGS+set} -ac_save_CFLAGS=$CFLAGS -{ $as_echo "$as_me:$LINENO: checking whether $CC accepts -g" >&5 -$as_echo_n "checking whether $CC accepts -g... " >&6; } -if test "${ac_cv_prog_cc_g+set}" = set; then - $as_echo_n "(cached) " >&6 -else - ac_save_c_werror_flag=$ac_c_werror_flag - ac_c_werror_flag=yes - ac_cv_prog_cc_g=no - CFLAGS="-g" - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ - -int -main () -{ - - ; - return 0; -} -_ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" -$as_echo "$ac_try_echo") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - ac_cv_prog_cc_g=yes -else - $as_echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - CFLAGS="" - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ - -int -main () -{ - - ; - return 0; -} -_ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" -$as_echo "$ac_try_echo") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - : -else - $as_echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - ac_c_werror_flag=$ac_save_c_werror_flag - CFLAGS="-g" - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ +$as_echo "#define _XOPEN_SOURCE_EXTENDED 1" >>confdefs.h -int -main () -{ + ;; + esac - ; - return 0; -} -_ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" -$as_echo "$ac_try_echo") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - ac_cv_prog_cc_g=yes -else - $as_echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 +$as_echo "#define _POSIX_C_SOURCE 200112L" >>confdefs.h -fi -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext fi -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext -fi +# +# SGI compilers allow the specification of the both the ABI and the +# ISA on the command line. Depending on the values of these switches, +# different and often incompatable code will be generated. +# +# The SGI_ABI variable can be used to modify the CC and LDFLAGS and +# thus supply support for various ABI/ISA combinations. The MACHDEP +# variable is also adjusted. +# -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext - ac_c_werror_flag=$ac_save_c_werror_flag -fi -{ $as_echo "$as_me:$LINENO: result: $ac_cv_prog_cc_g" >&5 -$as_echo "$ac_cv_prog_cc_g" >&6; } -if test "$ac_test_CFLAGS" = set; then - CFLAGS=$ac_save_CFLAGS -elif test $ac_cv_prog_cc_g = yes; then - if test "$GCC" = yes; then - CFLAGS="-g -O2" - else - CFLAGS="-g" - fi -else - if test "$GCC" = yes; then - CFLAGS="-O2" - else - CFLAGS= - fi +if test ! -z "$SGI_ABI" +then + CC="cc $SGI_ABI" + LDFLAGS="$SGI_ABI $LDFLAGS" + MACHDEP=`echo "${MACHDEP}${SGI_ABI}" | sed 's/ *//g'` fi -{ $as_echo "$as_me:$LINENO: checking for $CC option to accept ISO C89" >&5 -$as_echo_n "checking for $CC option to accept ISO C89... " >&6; } -if test "${ac_cv_prog_cc_c89+set}" = set; then - $as_echo_n "(cached) " >&6 -else - ac_cv_prog_cc_c89=no -ac_save_CC=$CC -cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -#include -#include -#include -#include -/* Most of the following tests are stolen from RCS 5.7's src/conf.sh. */ -struct buf { int x; }; -FILE * (*rcsopen) (struct buf *, struct stat *, int); -static char *e (p, i) - char **p; - int i; -{ - return p[i]; -} -static char *f (char * (*g) (char **, int), char **p, ...) -{ - char *s; - va_list v; - va_start (v,p); - s = g (p, va_arg (v,int)); - va_end (v); - return s; -} - -/* OSF 4.0 Compaq cc is some sort of almost-ANSI by default. It has - function prototypes and stuff, but not '\xHH' hex character constants. - These don't provoke an error unfortunately, instead are silently treated - as 'x'. The following induces an error, until -std is added to get - proper ANSI mode. Curiously '\x00'!='x' always comes out true, for an - array size at least. It's necessary to write '\x00'==0 to get something - that's true only with -std. */ -int osf4_cc_array ['\x00' == 0 ? 1 : -1]; - -/* IBM C 6 for AIX is almost-ANSI by default, but it replaces macro parameters - inside strings and character constants. */ -#define FOO(x) 'x' -int xlc6_cc_array[FOO(a) == 'x' ? 1 : -1]; - -int test (int i, double x); -struct s1 {int (*f) (int a);}; -struct s2 {int (*f) (double a);}; -int pairnames (int, char **, FILE *(*)(struct buf *, struct stat *, int), int, int); -int argc; -char **argv; -int -main () -{ -return f (e, argv, 0) != argv[0] || f (e, argv, 1) != argv[1]; - ; - return 0; -} -_ACEOF -for ac_arg in '' -qlanglvl=extc89 -qlanglvl=ansi -std \ - -Ae "-Aa -D_HPUX_SOURCE" "-Xc -D__EXTENSIONS__" -do - CC="$ac_save_CC $ac_arg" - rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" -$as_echo "$ac_try_echo") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - ac_cv_prog_cc_c89=$ac_arg -else - $as_echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $MACHDEP" >&5 +$as_echo "$MACHDEP" >&6; } -fi +# And add extra plat-mac for darwin -rm -f core conftest.err conftest.$ac_objext - test "x$ac_cv_prog_cc_c89" != "xno" && break -done -rm -f conftest.$ac_ext -CC=$ac_save_CC +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking EXTRAPLATDIR" >&5 +$as_echo_n "checking EXTRAPLATDIR... " >&6; } +if test -z "$EXTRAPLATDIR" +then + case $MACHDEP in + darwin) + EXTRAPLATDIR="\$(PLATMACDIRS)" + EXTRAMACHDEPPATH="\$(PLATMACPATH)" + ;; + *) + EXTRAPLATDIR="" + EXTRAMACHDEPPATH="" + ;; + esac fi -# AC_CACHE_VAL -case "x$ac_cv_prog_cc_c89" in - x) - { $as_echo "$as_me:$LINENO: result: none needed" >&5 -$as_echo "none needed" >&6; } ;; - xno) - { $as_echo "$as_me:$LINENO: result: unsupported" >&5 -$as_echo "unsupported" >&6; } ;; - *) - CC="$CC $ac_cv_prog_cc_c89" - { $as_echo "$as_me:$LINENO: result: $ac_cv_prog_cc_c89" >&5 -$as_echo "$ac_cv_prog_cc_c89" >&6; } ;; -esac +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $EXTRAPLATDIR" >&5 +$as_echo "$EXTRAPLATDIR" >&6; } +# Record the configure-time value of MACOSX_DEPLOYMENT_TARGET, +# it may influence the way we can build extensions, so distutils +# needs to check it -ac_ext=c -ac_cpp='$CPP $CPPFLAGS' -ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5' -ac_link='$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5' -ac_compiler_gnu=$ac_cv_c_compiler_gnu +CONFIGURE_MACOSX_DEPLOYMENT_TARGET= +EXPORT_MACOSX_DEPLOYMENT_TARGET='#' +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking machine type as reported by uname -m" >&5 +$as_echo_n "checking machine type as reported by uname -m... " >&6; } +ac_sys_machine=`uname -m` +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_sys_machine" >&5 +$as_echo "$ac_sys_machine" >&6; } +# checks for alternative programs -{ $as_echo "$as_me:$LINENO: checking for --with-cxx-main=" >&5 -$as_echo_n "checking for --with-cxx-main=... " >&6; } +# compiler flags are generated in two sets, BASECFLAGS and OPT. OPT is just +# for debug/optimization stuff. BASECFLAGS is for flags that are required +# just to get things to compile and link. Users are free to override OPT +# when running configure or make. The build should not break if they do. +# BASECFLAGS should generally not be messed with, however. -# Check whether --with-cxx_main was given. -if test "${with_cxx_main+set}" = set; then - withval=$with_cxx_main; +# XXX shouldn't some/most/all of this code be merged with the stuff later +# on that fiddles with OPT and BASECFLAGS? +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for --without-gcc" >&5 +$as_echo_n "checking for --without-gcc... " >&6; } +# Check whether --with-gcc was given. +if test "${with_gcc+set}" = set; then : + withval=$with_gcc; case $withval in - no) with_cxx_main=no - MAINCC='$(CC)';; - yes) with_cxx_main=yes - MAINCC='$(CXX)';; - *) with_cxx_main=yes - MAINCC=$withval - if test -z "$CXX" - then - CXX=$withval - fi;; + no) CC=${CC:-cc} + without_gcc=yes;; + yes) CC=gcc + without_gcc=no;; + *) CC=$withval + without_gcc=$withval;; esac else - with_cxx_main=no - MAINCC='$(CC)' - + case $ac_sys_system in + AIX*) CC=cc_r + without_gcc=;; + BeOS*) + case $BE_HOST_CPU in + ppc) + CC=mwcc + without_gcc=yes + BASECFLAGS="$BASECFLAGS -export pragma" + OPT="$OPT -O" + LDFLAGS="$LDFLAGS -nodup" + ;; + x86) + CC=gcc + without_gcc=no + OPT="$OPT -O" + ;; + *) + as_fn_error "Unknown BeOS platform \"$BE_HOST_CPU\"" "$LINENO" 5 + ;; + esac + AR="\$(srcdir)/Modules/ar_beos" + RANLIB=: + ;; + Monterey*) + RANLIB=: + without_gcc=;; + *) without_gcc=no;; + esac fi -{ $as_echo "$as_me:$LINENO: result: $with_cxx_main" >&5 -$as_echo "$with_cxx_main" >&6; } +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $without_gcc" >&5 +$as_echo "$without_gcc" >&6; } -preset_cxx="$CXX" -if test -z "$CXX" +# If the user switches compilers, we can't believe the cache +if test ! -z "$ac_cv_prog_CC" -a ! -z "$CC" -a "$CC" != "$ac_cv_prog_CC" then - case "$CC" in - gcc) # Extract the first word of "g++", so it can be a program name with args. -set dummy g++; ac_word=$2 -{ $as_echo "$as_me:$LINENO: checking for $ac_word" >&5 + as_fn_error "cached CC is different -- throw away $cache_file +(it is also a good idea to do 'make clean' before compiling)" "$LINENO" 5 +fi + +ac_ext=c +ac_cpp='$CPP $CPPFLAGS' +ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5' +ac_link='$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5' +ac_compiler_gnu=$ac_cv_c_compiler_gnu +if test -n "$ac_tool_prefix"; then + # Extract the first word of "${ac_tool_prefix}gcc", so it can be a program name with args. +set dummy ${ac_tool_prefix}gcc; ac_word=$2 +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 $as_echo_n "checking for $ac_word... " >&6; } -if test "${ac_cv_path_CXX+set}" = set; then +if test "${ac_cv_prog_CC+set}" = set; then : $as_echo_n "(cached) " >&6 else - case $CXX in - [\\/]* | ?:[\\/]*) - ac_cv_path_CXX="$CXX" # Let the user override the test with a path. - ;; - *) - as_save_IFS=$IFS; IFS=$PATH_SEPARATOR -for as_dir in notfound + if test -n "$CC"; then + ac_cv_prog_CC="$CC" # Let the user override the test. +else +as_save_IFS=$IFS; IFS=$PATH_SEPARATOR +for as_dir in $PATH do IFS=$as_save_IFS test -z "$as_dir" && as_dir=. - for ac_exec_ext in '' $ac_executable_extensions; do + for ac_exec_ext in '' $ac_executable_extensions; do if { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_test_x "$as_dir/$ac_word$ac_exec_ext"; }; then - ac_cv_path_CXX="$as_dir/$ac_word$ac_exec_ext" - $as_echo "$as_me:$LINENO: found $as_dir/$ac_word$ac_exec_ext" >&5 + ac_cv_prog_CC="${ac_tool_prefix}gcc" + $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 break 2 fi done -done + done IFS=$as_save_IFS - test -z "$ac_cv_path_CXX" && ac_cv_path_CXX="g++" - ;; -esac fi -CXX=$ac_cv_path_CXX -if test -n "$CXX"; then - { $as_echo "$as_me:$LINENO: result: $CXX" >&5 -$as_echo "$CXX" >&6; } +fi +CC=$ac_cv_prog_CC +if test -n "$CC"; then + { $as_echo "$as_me:${as_lineno-$LINENO}: result: $CC" >&5 +$as_echo "$CC" >&6; } else - { $as_echo "$as_me:$LINENO: result: no" >&5 + { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 $as_echo "no" >&6; } fi - ;; - cc) # Extract the first word of "c++", so it can be a program name with args. -set dummy c++; ac_word=$2 -{ $as_echo "$as_me:$LINENO: checking for $ac_word" >&5 + +fi +if test -z "$ac_cv_prog_CC"; then + ac_ct_CC=$CC + # Extract the first word of "gcc", so it can be a program name with args. +set dummy gcc; ac_word=$2 +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 $as_echo_n "checking for $ac_word... " >&6; } -if test "${ac_cv_path_CXX+set}" = set; then +if test "${ac_cv_prog_ac_ct_CC+set}" = set; then : $as_echo_n "(cached) " >&6 else - case $CXX in - [\\/]* | ?:[\\/]*) - ac_cv_path_CXX="$CXX" # Let the user override the test with a path. - ;; - *) - as_save_IFS=$IFS; IFS=$PATH_SEPARATOR -for as_dir in notfound + if test -n "$ac_ct_CC"; then + ac_cv_prog_ac_ct_CC="$ac_ct_CC" # Let the user override the test. +else +as_save_IFS=$IFS; IFS=$PATH_SEPARATOR +for as_dir in $PATH do IFS=$as_save_IFS test -z "$as_dir" && as_dir=. - for ac_exec_ext in '' $ac_executable_extensions; do + for ac_exec_ext in '' $ac_executable_extensions; do if { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_test_x "$as_dir/$ac_word$ac_exec_ext"; }; then - ac_cv_path_CXX="$as_dir/$ac_word$ac_exec_ext" - $as_echo "$as_me:$LINENO: found $as_dir/$ac_word$ac_exec_ext" >&5 + ac_cv_prog_ac_ct_CC="gcc" + $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 break 2 fi done -done + done IFS=$as_save_IFS - test -z "$ac_cv_path_CXX" && ac_cv_path_CXX="c++" - ;; -esac fi -CXX=$ac_cv_path_CXX -if test -n "$CXX"; then - { $as_echo "$as_me:$LINENO: result: $CXX" >&5 -$as_echo "$CXX" >&6; } +fi +ac_ct_CC=$ac_cv_prog_ac_ct_CC +if test -n "$ac_ct_CC"; then + { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_ct_CC" >&5 +$as_echo "$ac_ct_CC" >&6; } else - { $as_echo "$as_me:$LINENO: result: no" >&5 + { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 $as_echo "no" >&6; } fi - ;; - esac - if test "$CXX" = "notfound" - then - CXX="" - fi + if test "x$ac_ct_CC" = x; then + CC="" + else + case $cross_compiling:$ac_tool_warned in +yes:) +{ $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: using cross tools not prefixed with host triplet" >&5 +$as_echo "$as_me: WARNING: using cross tools not prefixed with host triplet" >&2;} +ac_tool_warned=yes ;; +esac + CC=$ac_ct_CC + fi +else + CC="$ac_cv_prog_CC" fi -if test -z "$CXX" -then - for ac_prog in $CCC c++ g++ gcc CC cxx cc++ cl -do - # Extract the first word of "$ac_prog", so it can be a program name with args. -set dummy $ac_prog; ac_word=$2 -{ $as_echo "$as_me:$LINENO: checking for $ac_word" >&5 + +if test -z "$CC"; then + if test -n "$ac_tool_prefix"; then + # Extract the first word of "${ac_tool_prefix}cc", so it can be a program name with args. +set dummy ${ac_tool_prefix}cc; ac_word=$2 +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 $as_echo_n "checking for $ac_word... " >&6; } -if test "${ac_cv_prog_CXX+set}" = set; then +if test "${ac_cv_prog_CC+set}" = set; then : $as_echo_n "(cached) " >&6 else - if test -n "$CXX"; then - ac_cv_prog_CXX="$CXX" # Let the user override the test. + if test -n "$CC"; then + ac_cv_prog_CC="$CC" # Let the user override the test. else as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $PATH do IFS=$as_save_IFS test -z "$as_dir" && as_dir=. - for ac_exec_ext in '' $ac_executable_extensions; do + for ac_exec_ext in '' $ac_executable_extensions; do if { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_test_x "$as_dir/$ac_word$ac_exec_ext"; }; then - ac_cv_prog_CXX="$ac_prog" - $as_echo "$as_me:$LINENO: found $as_dir/$ac_word$ac_exec_ext" >&5 + ac_cv_prog_CC="${ac_tool_prefix}cc" + $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 break 2 fi done -done + done IFS=$as_save_IFS fi fi -CXX=$ac_cv_prog_CXX -if test -n "$CXX"; then - { $as_echo "$as_me:$LINENO: result: $CXX" >&5 -$as_echo "$CXX" >&6; } +CC=$ac_cv_prog_CC +if test -n "$CC"; then + { $as_echo "$as_me:${as_lineno-$LINENO}: result: $CC" >&5 +$as_echo "$CC" >&6; } else - { $as_echo "$as_me:$LINENO: result: no" >&5 + { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 $as_echo "no" >&6; } fi - test -n "$CXX" && break + fi +fi +if test -z "$CC"; then + # Extract the first word of "cc", so it can be a program name with args. +set dummy cc; ac_word=$2 +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 +$as_echo_n "checking for $ac_word... " >&6; } +if test "${ac_cv_prog_CC+set}" = set; then : + $as_echo_n "(cached) " >&6 +else + if test -n "$CC"; then + ac_cv_prog_CC="$CC" # Let the user override the test. +else + ac_prog_rejected=no +as_save_IFS=$IFS; IFS=$PATH_SEPARATOR +for as_dir in $PATH +do + IFS=$as_save_IFS + test -z "$as_dir" && as_dir=. + for ac_exec_ext in '' $ac_executable_extensions; do + if { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_test_x "$as_dir/$ac_word$ac_exec_ext"; }; then + if test "$as_dir/$ac_word$ac_exec_ext" = "/usr/ucb/cc"; then + ac_prog_rejected=yes + continue + fi + ac_cv_prog_CC="cc" + $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 + break 2 + fi done -test -n "$CXX" || CXX="notfound" + done +IFS=$as_save_IFS - if test "$CXX" = "notfound" - then - CXX="" - fi +if test $ac_prog_rejected = yes; then + # We found a bogon in the path, so make sure we never use it. + set dummy $ac_cv_prog_CC + shift + if test $# != 0; then + # We chose a different compiler from the bogus one. + # However, it has the same basename, so the bogon will be chosen + # first if we set CC to just the basename; use the full file name. + shift + ac_cv_prog_CC="$as_dir/$ac_word${1+' '}$@" + fi fi -if test "$preset_cxx" != "$CXX" -then - { $as_echo "$as_me:$LINENO: WARNING: - - By default, distutils will build C++ extension modules with \"$CXX\". - If this is not intended, then set CXX on the configure command line. - " >&5 -$as_echo "$as_me: WARNING: - - By default, distutils will build C++ extension modules with \"$CXX\". - If this is not intended, then set CXX on the configure command line. - " >&2;} +fi +fi +CC=$ac_cv_prog_CC +if test -n "$CC"; then + { $as_echo "$as_me:${as_lineno-$LINENO}: result: $CC" >&5 +$as_echo "$CC" >&6; } +else + { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 +$as_echo "no" >&6; } fi -# checks for UNIX variants that set C preprocessor variables - -ac_ext=c -ac_cpp='$CPP $CPPFLAGS' -ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5' -ac_link='$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5' -ac_compiler_gnu=$ac_cv_c_compiler_gnu -{ $as_echo "$as_me:$LINENO: checking how to run the C preprocessor" >&5 -$as_echo_n "checking how to run the C preprocessor... " >&6; } -# On Suns, sometimes $CPP names a directory. -if test -n "$CPP" && test -d "$CPP"; then - CPP= fi -if test -z "$CPP"; then - if test "${ac_cv_prog_CPP+set}" = set; then +if test -z "$CC"; then + if test -n "$ac_tool_prefix"; then + for ac_prog in cl.exe + do + # Extract the first word of "$ac_tool_prefix$ac_prog", so it can be a program name with args. +set dummy $ac_tool_prefix$ac_prog; ac_word=$2 +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 +$as_echo_n "checking for $ac_word... " >&6; } +if test "${ac_cv_prog_CC+set}" = set; then : $as_echo_n "(cached) " >&6 else - # Double quotes because CPP needs to be expanded - for CPP in "$CC -E" "$CC -E -traditional-cpp" "/lib/cpp" - do - ac_preproc_ok=false -for ac_c_preproc_warn_flag in '' yes -do - # Use a header file that comes with gcc, so configuring glibc - # with a fresh cross-compiler works. - # Prefer to if __STDC__ is defined, since - # exists even on freestanding compilers. - # On the NeXT, cc -E runs the code through the compiler's parser, - # not just through cpp. "Syntax error" is here to catch this case. - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -#ifdef __STDC__ -# include -#else -# include -#endif - Syntax error -_ACEOF -if { (ac_try="$ac_cpp conftest.$ac_ext" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" -$as_echo "$ac_try_echo") >&5 - (eval "$ac_cpp conftest.$ac_ext") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } >/dev/null && { - test -z "$ac_c_preproc_warn_flag$ac_c_werror_flag" || - test ! -s conftest.err - }; then - : + if test -n "$CC"; then + ac_cv_prog_CC="$CC" # Let the user override the test. else - $as_echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 +as_save_IFS=$IFS; IFS=$PATH_SEPARATOR +for as_dir in $PATH +do + IFS=$as_save_IFS + test -z "$as_dir" && as_dir=. + for ac_exec_ext in '' $ac_executable_extensions; do + if { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_test_x "$as_dir/$ac_word$ac_exec_ext"; }; then + ac_cv_prog_CC="$ac_tool_prefix$ac_prog" + $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 + break 2 + fi +done + done +IFS=$as_save_IFS - # Broken: fails on valid input. -continue +fi +fi +CC=$ac_cv_prog_CC +if test -n "$CC"; then + { $as_echo "$as_me:${as_lineno-$LINENO}: result: $CC" >&5 +$as_echo "$CC" >&6; } +else + { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 +$as_echo "no" >&6; } fi -rm -f conftest.err conftest.$ac_ext - # OK, works on sane cases. Now check whether nonexistent headers - # can be detected and how. - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -#include -_ACEOF -if { (ac_try="$ac_cpp conftest.$ac_ext" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" -$as_echo "$ac_try_echo") >&5 - (eval "$ac_cpp conftest.$ac_ext") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } >/dev/null && { - test -z "$ac_c_preproc_warn_flag$ac_c_werror_flag" || - test ! -s conftest.err - }; then - # Broken: success on invalid input. -continue + test -n "$CC" && break + done +fi +if test -z "$CC"; then + ac_ct_CC=$CC + for ac_prog in cl.exe +do + # Extract the first word of "$ac_prog", so it can be a program name with args. +set dummy $ac_prog; ac_word=$2 +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 +$as_echo_n "checking for $ac_word... " >&6; } +if test "${ac_cv_prog_ac_ct_CC+set}" = set; then : + $as_echo_n "(cached) " >&6 else - $as_echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 + if test -n "$ac_ct_CC"; then + ac_cv_prog_ac_ct_CC="$ac_ct_CC" # Let the user override the test. +else +as_save_IFS=$IFS; IFS=$PATH_SEPARATOR +for as_dir in $PATH +do + IFS=$as_save_IFS + test -z "$as_dir" && as_dir=. + for ac_exec_ext in '' $ac_executable_extensions; do + if { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_test_x "$as_dir/$ac_word$ac_exec_ext"; }; then + ac_cv_prog_ac_ct_CC="$ac_prog" + $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 + break 2 + fi +done + done +IFS=$as_save_IFS - # Passes both tests. -ac_preproc_ok=: -break +fi +fi +ac_ct_CC=$ac_cv_prog_ac_ct_CC +if test -n "$ac_ct_CC"; then + { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_ct_CC" >&5 +$as_echo "$ac_ct_CC" >&6; } +else + { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 +$as_echo "no" >&6; } fi -rm -f conftest.err conftest.$ac_ext + test -n "$ac_ct_CC" && break done -# Because of `break', _AC_PREPROC_IFELSE's cleaning code was skipped. -rm -f conftest.err conftest.$ac_ext -if $ac_preproc_ok; then - break -fi - - done - ac_cv_prog_CPP=$CPP + if test "x$ac_ct_CC" = x; then + CC="" + else + case $cross_compiling:$ac_tool_warned in +yes:) +{ $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: using cross tools not prefixed with host triplet" >&5 +$as_echo "$as_me: WARNING: using cross tools not prefixed with host triplet" >&2;} +ac_tool_warned=yes ;; +esac + CC=$ac_ct_CC + fi fi - CPP=$ac_cv_prog_CPP -else - ac_cv_prog_CPP=$CPP + fi -{ $as_echo "$as_me:$LINENO: result: $CPP" >&5 -$as_echo "$CPP" >&6; } -ac_preproc_ok=false -for ac_c_preproc_warn_flag in '' yes -do - # Use a header file that comes with gcc, so configuring glibc - # with a fresh cross-compiler works. - # Prefer to if __STDC__ is defined, since - # exists even on freestanding compilers. - # On the NeXT, cc -E runs the code through the compiler's parser, - # not just through cpp. "Syntax error" is here to catch this case. - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -#ifdef __STDC__ -# include -#else -# include -#endif - Syntax error -_ACEOF -if { (ac_try="$ac_cpp conftest.$ac_ext" + + +test -z "$CC" && { { $as_echo "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5 +$as_echo "$as_me: error: in \`$ac_pwd':" >&2;} +as_fn_error "no acceptable C compiler found in \$PATH +See \`config.log' for more details." "$LINENO" 5; } + +# Provide some information about the compiler. +$as_echo "$as_me:${as_lineno-$LINENO}: checking for C compiler version" >&5 +set X $ac_compile +ac_compiler=$2 +for ac_option in --version -v -V -qversion; do + { { ac_try="$ac_compiler $ac_option >&5" case "(($ac_try" in *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" -$as_echo "$ac_try_echo") >&5 - (eval "$ac_cpp conftest.$ac_ext") 2>conftest.er1 +eval ac_try_echo="\"\$as_me:${as_lineno-$LINENO}: $ac_try_echo\"" +$as_echo "$ac_try_echo"; } >&5 + (eval "$ac_compiler $ac_option >&5") 2>conftest.err ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } >/dev/null && { - test -z "$ac_c_preproc_warn_flag$ac_c_werror_flag" || - test ! -s conftest.err - }; then - : -else - $as_echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 + if test -s conftest.err; then + sed '10a\ +... rest of stderr output deleted ... + 10q' conftest.err >conftest.er1 + cat conftest.er1 >&5 + fi + rm -f conftest.er1 conftest.err + $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 + test $ac_status = 0; } +done - # Broken: fails on valid input. -continue -fi +cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ -rm -f conftest.err conftest.$ac_ext +int +main () +{ - # OK, works on sane cases. Now check whether nonexistent headers - # can be detected and how. - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -#include + ; + return 0; +} _ACEOF -if { (ac_try="$ac_cpp conftest.$ac_ext" +ac_clean_files_save=$ac_clean_files +ac_clean_files="$ac_clean_files a.out a.out.dSYM a.exe b.out" +# Try to create an executable without -o first, disregard a.out. +# It will help us diagnose broken compilers, and finding out an intuition +# of exeext. +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking whether the C compiler works" >&5 +$as_echo_n "checking whether the C compiler works... " >&6; } +ac_link_default=`$as_echo "$ac_link" | sed 's/ -o *conftest[^ ]*//'` + +# The possible output files: +ac_files="a.out conftest.exe conftest a.exe a_out.exe b.out conftest.*" + +ac_rmfiles= +for ac_file in $ac_files +do + case $ac_file in + *.$ac_ext | *.xcoff | *.tds | *.d | *.pdb | *.xSYM | *.bb | *.bbg | *.map | *.inf | *.dSYM | *.o | *.obj ) ;; + * ) ac_rmfiles="$ac_rmfiles $ac_file";; + esac +done +rm -f $ac_rmfiles + +if { { ac_try="$ac_link_default" case "(($ac_try" in *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" -$as_echo "$ac_try_echo") >&5 - (eval "$ac_cpp conftest.$ac_ext") 2>conftest.er1 +eval ac_try_echo="\"\$as_me:${as_lineno-$LINENO}: $ac_try_echo\"" +$as_echo "$ac_try_echo"; } >&5 + (eval "$ac_link_default") 2>&5 ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } >/dev/null && { - test -z "$ac_c_preproc_warn_flag$ac_c_werror_flag" || - test ! -s conftest.err - }; then - # Broken: success on invalid input. -continue + $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 + test $ac_status = 0; }; then : + # Autoconf-2.13 could set the ac_cv_exeext variable to `no'. +# So ignore a value of `no', otherwise this would lead to `EXEEXT = no' +# in a Makefile. We should not override ac_cv_exeext if it was cached, +# so that the user can short-circuit this test for compilers unknown to +# Autoconf. +for ac_file in $ac_files '' +do + test -f "$ac_file" || continue + case $ac_file in + *.$ac_ext | *.xcoff | *.tds | *.d | *.pdb | *.xSYM | *.bb | *.bbg | *.map | *.inf | *.dSYM | *.o | *.obj ) + ;; + [ab].out ) + # We found the default executable, but exeext='' is most + # certainly right. + break;; + *.* ) + if test "${ac_cv_exeext+set}" = set && test "$ac_cv_exeext" != no; + then :; else + ac_cv_exeext=`expr "$ac_file" : '[^.]*\(\..*\)'` + fi + # We set ac_cv_exeext here because the later test for it is not + # safe: cross compilers may not add the suffix if given an `-o' + # argument, so we may need to know it at that point already. + # Even if this section looks crufty: it has the advantage of + # actually working. + break;; + * ) + break;; + esac +done +test "$ac_cv_exeext" = no && ac_cv_exeext= + else - $as_echo "$as_me: failed program was:" >&5 + ac_file='' +fi +if test -z "$ac_file"; then : + { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 +$as_echo "no" >&6; } +$as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 - # Passes both tests. -ac_preproc_ok=: -break +{ { $as_echo "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5 +$as_echo "$as_me: error: in \`$ac_pwd':" >&2;} +{ as_fn_set_status 77 +as_fn_error "C compiler cannot create executables +See \`config.log' for more details." "$LINENO" 5; }; } +else + { $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +$as_echo "yes" >&6; } fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for C compiler default output file name" >&5 +$as_echo_n "checking for C compiler default output file name... " >&6; } +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_file" >&5 +$as_echo "$ac_file" >&6; } +ac_exeext=$ac_cv_exeext -rm -f conftest.err conftest.$ac_ext - -done -# Because of `break', _AC_PREPROC_IFELSE's cleaning code was skipped. -rm -f conftest.err conftest.$ac_ext -if $ac_preproc_ok; then - : -else - { { $as_echo "$as_me:$LINENO: error: in \`$ac_pwd':" >&5 -$as_echo "$as_me: error: in \`$ac_pwd':" >&2;} -{ { $as_echo "$as_me:$LINENO: error: C preprocessor \"$CPP\" fails sanity check -See \`config.log' for more details." >&5 -$as_echo "$as_me: error: C preprocessor \"$CPP\" fails sanity check -See \`config.log' for more details." >&2;} - { (exit 1); exit 1; }; }; } -fi - -ac_ext=c -ac_cpp='$CPP $CPPFLAGS' -ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5' -ac_link='$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5' -ac_compiler_gnu=$ac_cv_c_compiler_gnu - - -{ $as_echo "$as_me:$LINENO: checking for grep that handles long lines and -e" >&5 -$as_echo_n "checking for grep that handles long lines and -e... " >&6; } -if test "${ac_cv_path_GREP+set}" = set; then - $as_echo_n "(cached) " >&6 -else - if test -z "$GREP"; then - ac_path_GREP_found=false - # Loop through the user's path and test for each of PROGNAME-LIST - as_save_IFS=$IFS; IFS=$PATH_SEPARATOR -for as_dir in $PATH$PATH_SEPARATOR/usr/xpg4/bin -do - IFS=$as_save_IFS - test -z "$as_dir" && as_dir=. - for ac_prog in grep ggrep; do - for ac_exec_ext in '' $ac_executable_extensions; do - ac_path_GREP="$as_dir/$ac_prog$ac_exec_ext" - { test -f "$ac_path_GREP" && $as_test_x "$ac_path_GREP"; } || continue -# Check for GNU ac_path_GREP and select it if it is found. - # Check for GNU $ac_path_GREP -case `"$ac_path_GREP" --version 2>&1` in -*GNU*) - ac_cv_path_GREP="$ac_path_GREP" ac_path_GREP_found=:;; -*) - ac_count=0 - $as_echo_n 0123456789 >"conftest.in" - while : - do - cat "conftest.in" "conftest.in" >"conftest.tmp" - mv "conftest.tmp" "conftest.in" - cp "conftest.in" "conftest.nl" - $as_echo 'GREP' >> "conftest.nl" - "$ac_path_GREP" -e 'GREP$' -e '-(cannot match)-' < "conftest.nl" >"conftest.out" 2>/dev/null || break - diff "conftest.out" "conftest.nl" >/dev/null 2>&1 || break - ac_count=`expr $ac_count + 1` - if test $ac_count -gt ${ac_path_GREP_max-0}; then - # Best one so far, save it but keep looking for a better one - ac_cv_path_GREP="$ac_path_GREP" - ac_path_GREP_max=$ac_count - fi - # 10*(2^10) chars as input seems more than enough - test $ac_count -gt 10 && break - done - rm -f conftest.in conftest.tmp conftest.nl conftest.out;; +rm -f -r a.out a.out.dSYM a.exe conftest$ac_cv_exeext b.out +ac_clean_files=$ac_clean_files_save +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for suffix of executables" >&5 +$as_echo_n "checking for suffix of executables... " >&6; } +if { { ac_try="$ac_link" +case "(($ac_try" in + *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; + *) ac_try_echo=$ac_try;; esac - - $ac_path_GREP_found && break 3 - done - done +eval ac_try_echo="\"\$as_me:${as_lineno-$LINENO}: $ac_try_echo\"" +$as_echo "$ac_try_echo"; } >&5 + (eval "$ac_link") 2>&5 + ac_status=$? + $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 + test $ac_status = 0; }; then : + # If both `conftest.exe' and `conftest' are `present' (well, observable) +# catch `conftest.exe'. For instance with Cygwin, `ls conftest' will +# work properly (i.e., refer to `conftest.exe'), while it won't with +# `rm'. +for ac_file in conftest.exe conftest conftest.*; do + test -f "$ac_file" || continue + case $ac_file in + *.$ac_ext | *.xcoff | *.tds | *.d | *.pdb | *.xSYM | *.bb | *.bbg | *.map | *.inf | *.dSYM | *.o | *.obj ) ;; + *.* ) ac_cv_exeext=`expr "$ac_file" : '[^.]*\(\..*\)'` + break;; + * ) break;; + esac done -IFS=$as_save_IFS - if test -z "$ac_cv_path_GREP"; then - { { $as_echo "$as_me:$LINENO: error: no acceptable grep could be found in $PATH$PATH_SEPARATOR/usr/xpg4/bin" >&5 -$as_echo "$as_me: error: no acceptable grep could be found in $PATH$PATH_SEPARATOR/usr/xpg4/bin" >&2;} - { (exit 1); exit 1; }; } - fi else - ac_cv_path_GREP=$GREP -fi - + { { $as_echo "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5 +$as_echo "$as_me: error: in \`$ac_pwd':" >&2;} +as_fn_error "cannot compute suffix of executables: cannot compile and link +See \`config.log' for more details." "$LINENO" 5; } fi -{ $as_echo "$as_me:$LINENO: result: $ac_cv_path_GREP" >&5 -$as_echo "$ac_cv_path_GREP" >&6; } - GREP="$ac_cv_path_GREP" +rm -f conftest conftest$ac_cv_exeext +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_exeext" >&5 +$as_echo "$ac_cv_exeext" >&6; } +rm -f conftest.$ac_ext +EXEEXT=$ac_cv_exeext +ac_exeext=$EXEEXT +cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ +#include +int +main () +{ +FILE *f = fopen ("conftest.out", "w"); + return ferror (f) || fclose (f) != 0; -{ $as_echo "$as_me:$LINENO: checking for egrep" >&5 -$as_echo_n "checking for egrep... " >&6; } -if test "${ac_cv_path_EGREP+set}" = set; then - $as_echo_n "(cached) " >&6 -else - if echo a | $GREP -E '(a|b)' >/dev/null 2>&1 - then ac_cv_path_EGREP="$GREP -E" - else - if test -z "$EGREP"; then - ac_path_EGREP_found=false - # Loop through the user's path and test for each of PROGNAME-LIST - as_save_IFS=$IFS; IFS=$PATH_SEPARATOR -for as_dir in $PATH$PATH_SEPARATOR/usr/xpg4/bin -do - IFS=$as_save_IFS - test -z "$as_dir" && as_dir=. - for ac_prog in egrep; do - for ac_exec_ext in '' $ac_executable_extensions; do - ac_path_EGREP="$as_dir/$ac_prog$ac_exec_ext" - { test -f "$ac_path_EGREP" && $as_test_x "$ac_path_EGREP"; } || continue -# Check for GNU ac_path_EGREP and select it if it is found. - # Check for GNU $ac_path_EGREP -case `"$ac_path_EGREP" --version 2>&1` in -*GNU*) - ac_cv_path_EGREP="$ac_path_EGREP" ac_path_EGREP_found=:;; -*) - ac_count=0 - $as_echo_n 0123456789 >"conftest.in" - while : - do - cat "conftest.in" "conftest.in" >"conftest.tmp" - mv "conftest.tmp" "conftest.in" - cp "conftest.in" "conftest.nl" - $as_echo 'EGREP' >> "conftest.nl" - "$ac_path_EGREP" 'EGREP$' < "conftest.nl" >"conftest.out" 2>/dev/null || break - diff "conftest.out" "conftest.nl" >/dev/null 2>&1 || break - ac_count=`expr $ac_count + 1` - if test $ac_count -gt ${ac_path_EGREP_max-0}; then - # Best one so far, save it but keep looking for a better one - ac_cv_path_EGREP="$ac_path_EGREP" - ac_path_EGREP_max=$ac_count - fi - # 10*(2^10) chars as input seems more than enough - test $ac_count -gt 10 && break - done - rm -f conftest.in conftest.tmp conftest.nl conftest.out;; + ; + return 0; +} +_ACEOF +ac_clean_files="$ac_clean_files conftest.out" +# Check that the compiler produces executables we can run. If not, either +# the compiler is broken, or we cross compile. +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking whether we are cross compiling" >&5 +$as_echo_n "checking whether we are cross compiling... " >&6; } +if test "$cross_compiling" != yes; then + { { ac_try="$ac_link" +case "(($ac_try" in + *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; + *) ac_try_echo=$ac_try;; esac - - $ac_path_EGREP_found && break 3 - done - done -done -IFS=$as_save_IFS - if test -z "$ac_cv_path_EGREP"; then - { { $as_echo "$as_me:$LINENO: error: no acceptable egrep could be found in $PATH$PATH_SEPARATOR/usr/xpg4/bin" >&5 -$as_echo "$as_me: error: no acceptable egrep could be found in $PATH$PATH_SEPARATOR/usr/xpg4/bin" >&2;} - { (exit 1); exit 1; }; } +eval ac_try_echo="\"\$as_me:${as_lineno-$LINENO}: $ac_try_echo\"" +$as_echo "$ac_try_echo"; } >&5 + (eval "$ac_link") 2>&5 + ac_status=$? + $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 + test $ac_status = 0; } + if { ac_try='./conftest$ac_cv_exeext' + { { case "(($ac_try" in + *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; + *) ac_try_echo=$ac_try;; +esac +eval ac_try_echo="\"\$as_me:${as_lineno-$LINENO}: $ac_try_echo\"" +$as_echo "$ac_try_echo"; } >&5 + (eval "$ac_try") 2>&5 + ac_status=$? + $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 + test $ac_status = 0; }; }; then + cross_compiling=no + else + if test "$cross_compiling" = maybe; then + cross_compiling=yes + else + { { $as_echo "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5 +$as_echo "$as_me: error: in \`$ac_pwd':" >&2;} +as_fn_error "cannot run C compiled programs. +If you meant to cross compile, use \`--host'. +See \`config.log' for more details." "$LINENO" 5; } + fi fi -else - ac_cv_path_EGREP=$EGREP -fi - - fi fi -{ $as_echo "$as_me:$LINENO: result: $ac_cv_path_EGREP" >&5 -$as_echo "$ac_cv_path_EGREP" >&6; } - EGREP="$ac_cv_path_EGREP" - +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $cross_compiling" >&5 +$as_echo "$cross_compiling" >&6; } -{ $as_echo "$as_me:$LINENO: checking for ANSI C header files" >&5 -$as_echo_n "checking for ANSI C header files... " >&6; } -if test "${ac_cv_header_stdc+set}" = set; then +rm -f conftest.$ac_ext conftest$ac_cv_exeext conftest.out +ac_clean_files=$ac_clean_files_save +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for suffix of object files" >&5 +$as_echo_n "checking for suffix of object files... " >&6; } +if test "${ac_cv_objext+set}" = set; then : $as_echo_n "(cached) " >&6 else - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF + cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ -#include -#include -#include -#include int main () @@ -4006,589 +3607,1024 @@ return 0; } _ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" +rm -f conftest.o conftest.obj +if { { ac_try="$ac_compile" case "(($ac_try" in *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac -eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" -$as_echo "$ac_try_echo") >&5 - (eval "$ac_compile") 2>conftest.er1 +eval ac_try_echo="\"\$as_me:${as_lineno-$LINENO}: $ac_try_echo\"" +$as_echo "$ac_try_echo"; } >&5 + (eval "$ac_compile") 2>&5 ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - ac_cv_header_stdc=yes + $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 + test $ac_status = 0; }; then : + for ac_file in conftest.o conftest.obj conftest.*; do + test -f "$ac_file" || continue; + case $ac_file in + *.$ac_ext | *.xcoff | *.tds | *.d | *.pdb | *.xSYM | *.bb | *.bbg | *.map | *.inf | *.dSYM ) ;; + *) ac_cv_objext=`expr "$ac_file" : '.*\.\(.*\)'` + break;; + esac +done else $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 - ac_cv_header_stdc=no -fi - -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext - -if test $ac_cv_header_stdc = yes; then - # SunOS 4.x string.h does not declare mem*, contrary to ANSI. - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -#include - -_ACEOF -if (eval "$ac_cpp conftest.$ac_ext") 2>&5 | - $EGREP "memchr" >/dev/null 2>&1; then - : -else - ac_cv_header_stdc=no +{ { $as_echo "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5 +$as_echo "$as_me: error: in \`$ac_pwd':" >&2;} +as_fn_error "cannot compute suffix of object files: cannot compile +See \`config.log' for more details." "$LINENO" 5; } fi -rm -f conftest* - +rm -f conftest.$ac_cv_objext conftest.$ac_ext fi - -if test $ac_cv_header_stdc = yes; then - # ISC 2.0.2 stdlib.h does not declare free, contrary to ANSI. - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_objext" >&5 +$as_echo "$ac_cv_objext" >&6; } +OBJEXT=$ac_cv_objext +ac_objext=$OBJEXT +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking whether we are using the GNU C compiler" >&5 +$as_echo_n "checking whether we are using the GNU C compiler... " >&6; } +if test "${ac_cv_c_compiler_gnu+set}" = set; then : + $as_echo_n "(cached) " >&6 +else + cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ -#include +int +main () +{ +#ifndef __GNUC__ + choke me +#endif + + ; + return 0; +} _ACEOF -if (eval "$ac_cpp conftest.$ac_ext") 2>&5 | - $EGREP "free" >/dev/null 2>&1; then - : +if ac_fn_c_try_compile "$LINENO"; then : + ac_compiler_gnu=yes else - ac_cv_header_stdc=no + ac_compiler_gnu=no fi -rm -f conftest* +rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext +ac_cv_c_compiler_gnu=$ac_compiler_gnu fi - -if test $ac_cv_header_stdc = yes; then - # /bin/cc in Irix-4.0.5 gets non-ANSI ctype macros unless using -ansi. - if test "$cross_compiling" = yes; then - : +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_c_compiler_gnu" >&5 +$as_echo "$ac_cv_c_compiler_gnu" >&6; } +if test $ac_compiler_gnu = yes; then + GCC=yes else - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -#include -#include -#if ((' ' & 0x0FF) == 0x020) -# define ISLOWER(c) ('a' <= (c) && (c) <= 'z') -# define TOUPPER(c) (ISLOWER(c) ? 'A' + ((c) - 'a') : (c)) -#else -# define ISLOWER(c) \ - (('a' <= (c) && (c) <= 'i') \ - || ('j' <= (c) && (c) <= 'r') \ - || ('s' <= (c) && (c) <= 'z')) -# define TOUPPER(c) (ISLOWER(c) ? ((c) | 0x40) : (c)) -#endif + GCC= +fi +ac_test_CFLAGS=${CFLAGS+set} +ac_save_CFLAGS=$CFLAGS +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking whether $CC accepts -g" >&5 +$as_echo_n "checking whether $CC accepts -g... " >&6; } +if test "${ac_cv_prog_cc_g+set}" = set; then : + $as_echo_n "(cached) " >&6 +else + ac_save_c_werror_flag=$ac_c_werror_flag + ac_c_werror_flag=yes + ac_cv_prog_cc_g=no + CFLAGS="-g" + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ -#define XOR(e, f) (((e) && !(f)) || (!(e) && (f))) int main () { - int i; - for (i = 0; i < 256; i++) - if (XOR (islower (i), ISLOWER (i)) - || toupper (i) != TOUPPER (i)) - return 2; + + ; return 0; } _ACEOF -rm -f conftest$ac_exeext -if { (ac_try="$ac_link" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" -$as_echo "$ac_try_echo") >&5 - (eval "$ac_link") 2>&5 - ac_status=$? - $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { ac_try='./conftest$ac_exeext' - { (case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" -$as_echo "$ac_try_echo") >&5 - (eval "$ac_try") 2>&5 - ac_status=$? - $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); }; }; then - : +if ac_fn_c_try_compile "$LINENO"; then : + ac_cv_prog_cc_g=yes else - $as_echo "$as_me: program exited with status $ac_status" >&5 -$as_echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 + CFLAGS="" + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ -( exit $ac_status ) -ac_cv_header_stdc=no -fi -rm -rf conftest.dSYM -rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext conftest.$ac_objext conftest.$ac_ext -fi +int +main () +{ + + ; + return 0; +} +_ACEOF +if ac_fn_c_try_compile "$LINENO"; then : + +else + ac_c_werror_flag=$ac_save_c_werror_flag + CFLAGS="-g" + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ +int +main () +{ + ; + return 0; +} +_ACEOF +if ac_fn_c_try_compile "$LINENO"; then : + ac_cv_prog_cc_g=yes +fi +rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext fi +rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext fi -{ $as_echo "$as_me:$LINENO: result: $ac_cv_header_stdc" >&5 -$as_echo "$ac_cv_header_stdc" >&6; } -if test $ac_cv_header_stdc = yes; then +rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext + ac_c_werror_flag=$ac_save_c_werror_flag +fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_prog_cc_g" >&5 +$as_echo "$ac_cv_prog_cc_g" >&6; } +if test "$ac_test_CFLAGS" = set; then + CFLAGS=$ac_save_CFLAGS +elif test $ac_cv_prog_cc_g = yes; then + if test "$GCC" = yes; then + CFLAGS="-g -O2" + else + CFLAGS="-g" + fi +else + if test "$GCC" = yes; then + CFLAGS="-O2" + else + CFLAGS= + fi +fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $CC option to accept ISO C89" >&5 +$as_echo_n "checking for $CC option to accept ISO C89... " >&6; } +if test "${ac_cv_prog_cc_c89+set}" = set; then : + $as_echo_n "(cached) " >&6 +else + ac_cv_prog_cc_c89=no +ac_save_CC=$CC +cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ +#include +#include +#include +#include +/* Most of the following tests are stolen from RCS 5.7's src/conf.sh. */ +struct buf { int x; }; +FILE * (*rcsopen) (struct buf *, struct stat *, int); +static char *e (p, i) + char **p; + int i; +{ + return p[i]; +} +static char *f (char * (*g) (char **, int), char **p, ...) +{ + char *s; + va_list v; + va_start (v,p); + s = g (p, va_arg (v,int)); + va_end (v); + return s; +} + +/* OSF 4.0 Compaq cc is some sort of almost-ANSI by default. It has + function prototypes and stuff, but not '\xHH' hex character constants. + These don't provoke an error unfortunately, instead are silently treated + as 'x'. The following induces an error, until -std is added to get + proper ANSI mode. Curiously '\x00'!='x' always comes out true, for an + array size at least. It's necessary to write '\x00'==0 to get something + that's true only with -std. */ +int osf4_cc_array ['\x00' == 0 ? 1 : -1]; + +/* IBM C 6 for AIX is almost-ANSI by default, but it replaces macro parameters + inside strings and character constants. */ +#define FOO(x) 'x' +int xlc6_cc_array[FOO(a) == 'x' ? 1 : -1]; -cat >>confdefs.h <<\_ACEOF -#define STDC_HEADERS 1 +int test (int i, double x); +struct s1 {int (*f) (int a);}; +struct s2 {int (*f) (double a);}; +int pairnames (int, char **, FILE *(*)(struct buf *, struct stat *, int), int, int); +int argc; +char **argv; +int +main () +{ +return f (e, argv, 0) != argv[0] || f (e, argv, 1) != argv[1]; + ; + return 0; +} _ACEOF +for ac_arg in '' -qlanglvl=extc89 -qlanglvl=ansi -std \ + -Ae "-Aa -D_HPUX_SOURCE" "-Xc -D__EXTENSIONS__" +do + CC="$ac_save_CC $ac_arg" + if ac_fn_c_try_compile "$LINENO"; then : + ac_cv_prog_cc_c89=$ac_arg +fi +rm -f core conftest.err conftest.$ac_objext + test "x$ac_cv_prog_cc_c89" != "xno" && break +done +rm -f conftest.$ac_ext +CC=$ac_save_CC + +fi +# AC_CACHE_VAL +case "x$ac_cv_prog_cc_c89" in + x) + { $as_echo "$as_me:${as_lineno-$LINENO}: result: none needed" >&5 +$as_echo "none needed" >&6; } ;; + xno) + { $as_echo "$as_me:${as_lineno-$LINENO}: result: unsupported" >&5 +$as_echo "unsupported" >&6; } ;; + *) + CC="$CC $ac_cv_prog_cc_c89" + { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_prog_cc_c89" >&5 +$as_echo "$ac_cv_prog_cc_c89" >&6; } ;; +esac +if test "x$ac_cv_prog_cc_c89" != xno; then : fi -# On IRIX 5.3, sys/types and inttypes.h are conflicting. +ac_ext=c +ac_cpp='$CPP $CPPFLAGS' +ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5' +ac_link='$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5' +ac_compiler_gnu=$ac_cv_c_compiler_gnu + +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for --with-cxx-main=" >&5 +$as_echo_n "checking for --with-cxx-main=... " >&6; } +# Check whether --with-cxx_main was given. +if test "${with_cxx_main+set}" = set; then : + withval=$with_cxx_main; + case $withval in + no) with_cxx_main=no + MAINCC='$(CC)';; + yes) with_cxx_main=yes + MAINCC='$(CXX)';; + *) with_cxx_main=yes + MAINCC=$withval + if test -z "$CXX" + then + CXX=$withval + fi;; + esac +else + with_cxx_main=no + MAINCC='$(CC)' +fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $with_cxx_main" >&5 +$as_echo "$with_cxx_main" >&6; } -for ac_header in sys/types.h sys/stat.h stdlib.h string.h memory.h strings.h \ - inttypes.h stdint.h unistd.h -do -as_ac_Header=`$as_echo "ac_cv_header_$ac_header" | $as_tr_sh` -{ $as_echo "$as_me:$LINENO: checking for $ac_header" >&5 -$as_echo_n "checking for $ac_header... " >&6; } -if { as_var=$as_ac_Header; eval "test \"\${$as_var+set}\" = set"; }; then +preset_cxx="$CXX" +if test -z "$CXX" +then + case "$CC" in + gcc) # Extract the first word of "g++", so it can be a program name with args. +set dummy g++; ac_word=$2 +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 +$as_echo_n "checking for $ac_word... " >&6; } +if test "${ac_cv_path_CXX+set}" = set; then : $as_echo_n "(cached) " >&6 else - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -$ac_includes_default + case $CXX in + [\\/]* | ?:[\\/]*) + ac_cv_path_CXX="$CXX" # Let the user override the test with a path. + ;; + *) + as_save_IFS=$IFS; IFS=$PATH_SEPARATOR +for as_dir in notfound +do + IFS=$as_save_IFS + test -z "$as_dir" && as_dir=. + for ac_exec_ext in '' $ac_executable_extensions; do + if { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_test_x "$as_dir/$ac_word$ac_exec_ext"; }; then + ac_cv_path_CXX="$as_dir/$ac_word$ac_exec_ext" + $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 + break 2 + fi +done + done +IFS=$as_save_IFS -#include <$ac_header> -_ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; + test -z "$ac_cv_path_CXX" && ac_cv_path_CXX="g++" + ;; esac -eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" -$as_echo "$ac_try_echo") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - eval "$as_ac_Header=yes" -else - $as_echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - eval "$as_ac_Header=no" fi - -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext +CXX=$ac_cv_path_CXX +if test -n "$CXX"; then + { $as_echo "$as_me:${as_lineno-$LINENO}: result: $CXX" >&5 +$as_echo "$CXX" >&6; } +else + { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 +$as_echo "no" >&6; } fi -ac_res=`eval 'as_val=${'$as_ac_Header'} - $as_echo "$as_val"'` - { $as_echo "$as_me:$LINENO: result: $ac_res" >&5 -$as_echo "$ac_res" >&6; } -as_val=`eval 'as_val=${'$as_ac_Header'} - $as_echo "$as_val"'` - if test "x$as_val" = x""yes; then - cat >>confdefs.h <<_ACEOF -#define `$as_echo "HAVE_$ac_header" | $as_tr_cpp` 1 -_ACEOF -fi - -done - - - - if test "${ac_cv_header_minix_config_h+set}" = set; then - { $as_echo "$as_me:$LINENO: checking for minix/config.h" >&5 -$as_echo_n "checking for minix/config.h... " >&6; } -if test "${ac_cv_header_minix_config_h+set}" = set; then + ;; + cc) # Extract the first word of "c++", so it can be a program name with args. +set dummy c++; ac_word=$2 +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 +$as_echo_n "checking for $ac_word... " >&6; } +if test "${ac_cv_path_CXX+set}" = set; then : $as_echo_n "(cached) " >&6 -fi -{ $as_echo "$as_me:$LINENO: result: $ac_cv_header_minix_config_h" >&5 -$as_echo "$ac_cv_header_minix_config_h" >&6; } -else - # Is the header compilable? -{ $as_echo "$as_me:$LINENO: checking minix/config.h usability" >&5 -$as_echo_n "checking minix/config.h usability... " >&6; } -cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -$ac_includes_default -#include -_ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" -$as_echo "$ac_try_echo") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - ac_header_compiler=yes else - $as_echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - ac_header_compiler=no -fi - -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext -{ $as_echo "$as_me:$LINENO: result: $ac_header_compiler" >&5 -$as_echo "$ac_header_compiler" >&6; } + case $CXX in + [\\/]* | ?:[\\/]*) + ac_cv_path_CXX="$CXX" # Let the user override the test with a path. + ;; + *) + as_save_IFS=$IFS; IFS=$PATH_SEPARATOR +for as_dir in notfound +do + IFS=$as_save_IFS + test -z "$as_dir" && as_dir=. + for ac_exec_ext in '' $ac_executable_extensions; do + if { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_test_x "$as_dir/$ac_word$ac_exec_ext"; }; then + ac_cv_path_CXX="$as_dir/$ac_word$ac_exec_ext" + $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 + break 2 + fi +done + done +IFS=$as_save_IFS -# Is the header present? -{ $as_echo "$as_me:$LINENO: checking minix/config.h presence" >&5 -$as_echo_n "checking minix/config.h presence... " >&6; } -cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -#include -_ACEOF -if { (ac_try="$ac_cpp conftest.$ac_ext" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; + test -z "$ac_cv_path_CXX" && ac_cv_path_CXX="c++" + ;; esac -eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" -$as_echo "$ac_try_echo") >&5 - (eval "$ac_cpp conftest.$ac_ext") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } >/dev/null && { - test -z "$ac_c_preproc_warn_flag$ac_c_werror_flag" || - test ! -s conftest.err - }; then - ac_header_preproc=yes +fi +CXX=$ac_cv_path_CXX +if test -n "$CXX"; then + { $as_echo "$as_me:${as_lineno-$LINENO}: result: $CXX" >&5 +$as_echo "$CXX" >&6; } else - $as_echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - ac_header_preproc=no + { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 +$as_echo "no" >&6; } fi -rm -f conftest.err conftest.$ac_ext -{ $as_echo "$as_me:$LINENO: result: $ac_header_preproc" >&5 -$as_echo "$ac_header_preproc" >&6; } - -# So? What about this header? -case $ac_header_compiler:$ac_header_preproc:$ac_c_preproc_warn_flag in - yes:no: ) - { $as_echo "$as_me:$LINENO: WARNING: minix/config.h: accepted by the compiler, rejected by the preprocessor!" >&5 -$as_echo "$as_me: WARNING: minix/config.h: accepted by the compiler, rejected by the preprocessor!" >&2;} - { $as_echo "$as_me:$LINENO: WARNING: minix/config.h: proceeding with the compiler's result" >&5 -$as_echo "$as_me: WARNING: minix/config.h: proceeding with the compiler's result" >&2;} - ac_header_preproc=yes - ;; - no:yes:* ) - { $as_echo "$as_me:$LINENO: WARNING: minix/config.h: present but cannot be compiled" >&5 -$as_echo "$as_me: WARNING: minix/config.h: present but cannot be compiled" >&2;} - { $as_echo "$as_me:$LINENO: WARNING: minix/config.h: check for missing prerequisite headers?" >&5 -$as_echo "$as_me: WARNING: minix/config.h: check for missing prerequisite headers?" >&2;} - { $as_echo "$as_me:$LINENO: WARNING: minix/config.h: see the Autoconf documentation" >&5 -$as_echo "$as_me: WARNING: minix/config.h: see the Autoconf documentation" >&2;} - { $as_echo "$as_me:$LINENO: WARNING: minix/config.h: section \"Present But Cannot Be Compiled\"" >&5 -$as_echo "$as_me: WARNING: minix/config.h: section \"Present But Cannot Be Compiled\"" >&2;} - { $as_echo "$as_me:$LINENO: WARNING: minix/config.h: proceeding with the preprocessor's result" >&5 -$as_echo "$as_me: WARNING: minix/config.h: proceeding with the preprocessor's result" >&2;} - { $as_echo "$as_me:$LINENO: WARNING: minix/config.h: in the future, the compiler will take precedence" >&5 -$as_echo "$as_me: WARNING: minix/config.h: in the future, the compiler will take precedence" >&2;} - ( cat <<\_ASBOX -## ------------------------------------------------ ## -## Report this to http://www.python.org/python-bugs ## -## ------------------------------------------------ ## -_ASBOX - ) | sed "s/^/$as_me: WARNING: /" >&2 - ;; -esac -{ $as_echo "$as_me:$LINENO: checking for minix/config.h" >&5 -$as_echo_n "checking for minix/config.h... " >&6; } -if test "${ac_cv_header_minix_config_h+set}" = set; then + ;; + esac + if test "$CXX" = "notfound" + then + CXX="" + fi +fi +if test -z "$CXX" +then + for ac_prog in $CCC c++ g++ gcc CC cxx cc++ cl +do + # Extract the first word of "$ac_prog", so it can be a program name with args. +set dummy $ac_prog; ac_word=$2 +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 +$as_echo_n "checking for $ac_word... " >&6; } +if test "${ac_cv_prog_CXX+set}" = set; then : $as_echo_n "(cached) " >&6 else - ac_cv_header_minix_config_h=$ac_header_preproc -fi -{ $as_echo "$as_me:$LINENO: result: $ac_cv_header_minix_config_h" >&5 -$as_echo "$ac_cv_header_minix_config_h" >&6; } + if test -n "$CXX"; then + ac_cv_prog_CXX="$CXX" # Let the user override the test. +else +as_save_IFS=$IFS; IFS=$PATH_SEPARATOR +for as_dir in $PATH +do + IFS=$as_save_IFS + test -z "$as_dir" && as_dir=. + for ac_exec_ext in '' $ac_executable_extensions; do + if { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_test_x "$as_dir/$ac_word$ac_exec_ext"; }; then + ac_cv_prog_CXX="$ac_prog" + $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 + break 2 + fi +done + done +IFS=$as_save_IFS fi -if test "x$ac_cv_header_minix_config_h" = x""yes; then - MINIX=yes +fi +CXX=$ac_cv_prog_CXX +if test -n "$CXX"; then + { $as_echo "$as_me:${as_lineno-$LINENO}: result: $CXX" >&5 +$as_echo "$CXX" >&6; } else - MINIX= + { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 +$as_echo "no" >&6; } fi - if test "$MINIX" = yes; then - -cat >>confdefs.h <<\_ACEOF -#define _POSIX_SOURCE 1 -_ACEOF - - -cat >>confdefs.h <<\_ACEOF -#define _POSIX_1_SOURCE 2 -_ACEOF + test -n "$CXX" && break +done +test -n "$CXX" || CXX="notfound" + if test "$CXX" = "notfound" + then + CXX="" + fi +fi +if test "$preset_cxx" != "$CXX" +then + { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: -cat >>confdefs.h <<\_ACEOF -#define _MINIX 1 -_ACEOF + By default, distutils will build C++ extension modules with \"$CXX\". + If this is not intended, then set CXX on the configure command line. + " >&5 +$as_echo "$as_me: WARNING: - fi + By default, distutils will build C++ extension modules with \"$CXX\". + If this is not intended, then set CXX on the configure command line. + " >&2;} +fi +# checks for UNIX variants that set C preprocessor variables - { $as_echo "$as_me:$LINENO: checking whether it is safe to define __EXTENSIONS__" >&5 -$as_echo_n "checking whether it is safe to define __EXTENSIONS__... " >&6; } -if test "${ac_cv_safe_to_define___extensions__+set}" = set; then +ac_ext=c +ac_cpp='$CPP $CPPFLAGS' +ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5' +ac_link='$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5' +ac_compiler_gnu=$ac_cv_c_compiler_gnu +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking how to run the C preprocessor" >&5 +$as_echo_n "checking how to run the C preprocessor... " >&6; } +# On Suns, sometimes $CPP names a directory. +if test -n "$CPP" && test -d "$CPP"; then + CPP= +fi +if test -z "$CPP"; then + if test "${ac_cv_prog_CPP+set}" = set; then : $as_echo_n "(cached) " >&6 else - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF + # Double quotes because CPP needs to be expanded + for CPP in "$CC -E" "$CC -E -traditional-cpp" "/lib/cpp" + do + ac_preproc_ok=false +for ac_c_preproc_warn_flag in '' yes +do + # Use a header file that comes with gcc, so configuring glibc + # with a fresh cross-compiler works. + # Prefer to if __STDC__ is defined, since + # exists even on freestanding compilers. + # On the NeXT, cc -E runs the code through the compiler's parser, + # not just through cpp. "Syntax error" is here to catch this case. + cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ +#ifdef __STDC__ +# include +#else +# include +#endif + Syntax error +_ACEOF +if ac_fn_c_try_cpp "$LINENO"; then : -# define __EXTENSIONS__ 1 - $ac_includes_default -int -main () -{ +else + # Broken: fails on valid input. +continue +fi +rm -f conftest.err conftest.$ac_ext - ; - return 0; -} + # OK, works on sane cases. Now check whether nonexistent headers + # can be detected and how. + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ +#include _ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" -$as_echo "$ac_try_echo") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - ac_cv_safe_to_define___extensions__=yes +if ac_fn_c_try_cpp "$LINENO"; then : + # Broken: success on invalid input. +continue else - $as_echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - ac_cv_safe_to_define___extensions__=no + # Passes both tests. +ac_preproc_ok=: +break fi +rm -f conftest.err conftest.$ac_ext -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext +done +# Because of `break', _AC_PREPROC_IFELSE's cleaning code was skipped. +rm -f conftest.err conftest.$ac_ext +if $ac_preproc_ok; then : + break fi -{ $as_echo "$as_me:$LINENO: result: $ac_cv_safe_to_define___extensions__" >&5 -$as_echo "$ac_cv_safe_to_define___extensions__" >&6; } - test $ac_cv_safe_to_define___extensions__ = yes && - cat >>confdefs.h <<\_ACEOF -#define __EXTENSIONS__ 1 -_ACEOF - cat >>confdefs.h <<\_ACEOF -#define _ALL_SOURCE 1 -_ACEOF + done + ac_cv_prog_CPP=$CPP - cat >>confdefs.h <<\_ACEOF -#define _GNU_SOURCE 1 +fi + CPP=$ac_cv_prog_CPP +else + ac_cv_prog_CPP=$CPP +fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $CPP" >&5 +$as_echo "$CPP" >&6; } +ac_preproc_ok=false +for ac_c_preproc_warn_flag in '' yes +do + # Use a header file that comes with gcc, so configuring glibc + # with a fresh cross-compiler works. + # Prefer to if __STDC__ is defined, since + # exists even on freestanding compilers. + # On the NeXT, cc -E runs the code through the compiler's parser, + # not just through cpp. "Syntax error" is here to catch this case. + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ +#ifdef __STDC__ +# include +#else +# include +#endif + Syntax error _ACEOF +if ac_fn_c_try_cpp "$LINENO"; then : - cat >>confdefs.h <<\_ACEOF -#define _POSIX_PTHREAD_SEMANTICS 1 -_ACEOF +else + # Broken: fails on valid input. +continue +fi +rm -f conftest.err conftest.$ac_ext - cat >>confdefs.h <<\_ACEOF -#define _TANDEM_SOURCE 1 + # OK, works on sane cases. Now check whether nonexistent headers + # can be detected and how. + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ +#include _ACEOF +if ac_fn_c_try_cpp "$LINENO"; then : + # Broken: success on invalid input. +continue +else + # Passes both tests. +ac_preproc_ok=: +break +fi +rm -f conftest.err conftest.$ac_ext +done +# Because of `break', _AC_PREPROC_IFELSE's cleaning code was skipped. +rm -f conftest.err conftest.$ac_ext +if $ac_preproc_ok; then : +else + { { $as_echo "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5 +$as_echo "$as_me: error: in \`$ac_pwd':" >&2;} +as_fn_error "C preprocessor \"$CPP\" fails sanity check +See \`config.log' for more details." "$LINENO" 5; } +fi -# Check for unsupported systems -case $ac_sys_system/$ac_sys_release in -atheos*|Linux*/1*) - echo This system \($ac_sys_system/$ac_sys_release\) is no longer supported. - echo See README for details. - exit 1;; -esac +ac_ext=c +ac_cpp='$CPP $CPPFLAGS' +ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5' +ac_link='$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5' +ac_compiler_gnu=$ac_cv_c_compiler_gnu -{ $as_echo "$as_me:$LINENO: checking for --with-suffix" >&5 -$as_echo_n "checking for --with-suffix... " >&6; } +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for grep that handles long lines and -e" >&5 +$as_echo_n "checking for grep that handles long lines and -e... " >&6; } +if test "${ac_cv_path_GREP+set}" = set; then : + $as_echo_n "(cached) " >&6 +else + if test -z "$GREP"; then + ac_path_GREP_found=false + # Loop through the user's path and test for each of PROGNAME-LIST + as_save_IFS=$IFS; IFS=$PATH_SEPARATOR +for as_dir in $PATH$PATH_SEPARATOR/usr/xpg4/bin +do + IFS=$as_save_IFS + test -z "$as_dir" && as_dir=. + for ac_prog in grep ggrep; do + for ac_exec_ext in '' $ac_executable_extensions; do + ac_path_GREP="$as_dir/$ac_prog$ac_exec_ext" + { test -f "$ac_path_GREP" && $as_test_x "$ac_path_GREP"; } || continue +# Check for GNU ac_path_GREP and select it if it is found. + # Check for GNU $ac_path_GREP +case `"$ac_path_GREP" --version 2>&1` in +*GNU*) + ac_cv_path_GREP="$ac_path_GREP" ac_path_GREP_found=:;; +*) + ac_count=0 + $as_echo_n 0123456789 >"conftest.in" + while : + do + cat "conftest.in" "conftest.in" >"conftest.tmp" + mv "conftest.tmp" "conftest.in" + cp "conftest.in" "conftest.nl" + $as_echo 'GREP' >> "conftest.nl" + "$ac_path_GREP" -e 'GREP$' -e '-(cannot match)-' < "conftest.nl" >"conftest.out" 2>/dev/null || break + diff "conftest.out" "conftest.nl" >/dev/null 2>&1 || break + as_fn_arith $ac_count + 1 && ac_count=$as_val + if test $ac_count -gt ${ac_path_GREP_max-0}; then + # Best one so far, save it but keep looking for a better one + ac_cv_path_GREP="$ac_path_GREP" + ac_path_GREP_max=$ac_count + fi + # 10*(2^10) chars as input seems more than enough + test $ac_count -gt 10 && break + done + rm -f conftest.in conftest.tmp conftest.nl conftest.out;; +esac -# Check whether --with-suffix was given. -if test "${with_suffix+set}" = set; then - withval=$with_suffix; - case $withval in - no) EXEEXT=;; - yes) EXEEXT=.exe;; - *) EXEEXT=$withval;; - esac + $ac_path_GREP_found && break 3 + done + done + done +IFS=$as_save_IFS + if test -z "$ac_cv_path_GREP"; then + as_fn_error "no acceptable grep could be found in $PATH$PATH_SEPARATOR/usr/xpg4/bin" "$LINENO" 5 + fi +else + ac_cv_path_GREP=$GREP fi -{ $as_echo "$as_me:$LINENO: result: $EXEEXT" >&5 -$as_echo "$EXEEXT" >&6; } - -# Test whether we're running on a non-case-sensitive system, in which -# case we give a warning if no ext is given - -{ $as_echo "$as_me:$LINENO: checking for case-insensitive build directory" >&5 -$as_echo_n "checking for case-insensitive build directory... " >&6; } -if test ! -d CaseSensitiveTestDir; then -mkdir CaseSensitiveTestDir fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_path_GREP" >&5 +$as_echo "$ac_cv_path_GREP" >&6; } + GREP="$ac_cv_path_GREP" -if test -d casesensitivetestdir -then - { $as_echo "$as_me:$LINENO: result: yes" >&5 -$as_echo "yes" >&6; } - BUILDEXEEXT=.exe -else - { $as_echo "$as_me:$LINENO: result: no" >&5 -$as_echo "no" >&6; } - BUILDEXEEXT=$EXEEXT -fi -rmdir CaseSensitiveTestDir -case $MACHDEP in -bsdos*) - case $CC in - gcc) CC="$CC -D_HAVE_BSDI";; - esac;; +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for egrep" >&5 +$as_echo_n "checking for egrep... " >&6; } +if test "${ac_cv_path_EGREP+set}" = set; then : + $as_echo_n "(cached) " >&6 +else + if echo a | $GREP -E '(a|b)' >/dev/null 2>&1 + then ac_cv_path_EGREP="$GREP -E" + else + if test -z "$EGREP"; then + ac_path_EGREP_found=false + # Loop through the user's path and test for each of PROGNAME-LIST + as_save_IFS=$IFS; IFS=$PATH_SEPARATOR +for as_dir in $PATH$PATH_SEPARATOR/usr/xpg4/bin +do + IFS=$as_save_IFS + test -z "$as_dir" && as_dir=. + for ac_prog in egrep; do + for ac_exec_ext in '' $ac_executable_extensions; do + ac_path_EGREP="$as_dir/$ac_prog$ac_exec_ext" + { test -f "$ac_path_EGREP" && $as_test_x "$ac_path_EGREP"; } || continue +# Check for GNU ac_path_EGREP and select it if it is found. + # Check for GNU $ac_path_EGREP +case `"$ac_path_EGREP" --version 2>&1` in +*GNU*) + ac_cv_path_EGREP="$ac_path_EGREP" ac_path_EGREP_found=:;; +*) + ac_count=0 + $as_echo_n 0123456789 >"conftest.in" + while : + do + cat "conftest.in" "conftest.in" >"conftest.tmp" + mv "conftest.tmp" "conftest.in" + cp "conftest.in" "conftest.nl" + $as_echo 'EGREP' >> "conftest.nl" + "$ac_path_EGREP" 'EGREP$' < "conftest.nl" >"conftest.out" 2>/dev/null || break + diff "conftest.out" "conftest.nl" >/dev/null 2>&1 || break + as_fn_arith $ac_count + 1 && ac_count=$as_val + if test $ac_count -gt ${ac_path_EGREP_max-0}; then + # Best one so far, save it but keep looking for a better one + ac_cv_path_EGREP="$ac_path_EGREP" + ac_path_EGREP_max=$ac_count + fi + # 10*(2^10) chars as input seems more than enough + test $ac_count -gt 10 && break + done + rm -f conftest.in conftest.tmp conftest.nl conftest.out;; esac -case $ac_sys_system in -hp*|HP*) - case $CC in - cc|*/cc) CC="$CC -Ae";; - esac;; -Monterey*) - case $CC in - cc) CC="$CC -Wl,-Bexport";; - esac;; -SunOS*) - # Some functions have a prototype only with that define, e.g. confstr + $ac_path_EGREP_found && break 3 + done + done + done +IFS=$as_save_IFS + if test -z "$ac_cv_path_EGREP"; then + as_fn_error "no acceptable egrep could be found in $PATH$PATH_SEPARATOR/usr/xpg4/bin" "$LINENO" 5 + fi +else + ac_cv_path_EGREP=$EGREP +fi -cat >>confdefs.h <<\_ACEOF -#define __EXTENSIONS__ 1 -_ACEOF + fi +fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_path_EGREP" >&5 +$as_echo "$ac_cv_path_EGREP" >&6; } + EGREP="$ac_cv_path_EGREP" - ;; -esac +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for ANSI C header files" >&5 +$as_echo_n "checking for ANSI C header files... " >&6; } +if test "${ac_cv_header_stdc+set}" = set; then : + $as_echo_n "(cached) " >&6 +else + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ +#include +#include +#include +#include +int +main () +{ -{ $as_echo "$as_me:$LINENO: checking LIBRARY" >&5 -$as_echo_n "checking LIBRARY... " >&6; } -if test -z "$LIBRARY" -then - LIBRARY='libpython$(VERSION).a' + ; + return 0; +} +_ACEOF +if ac_fn_c_try_compile "$LINENO"; then : + ac_cv_header_stdc=yes +else + ac_cv_header_stdc=no fi -{ $as_echo "$as_me:$LINENO: result: $LIBRARY" >&5 -$as_echo "$LIBRARY" >&6; } +rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext -# LDLIBRARY is the name of the library to link against (as opposed to the -# name of the library into which to insert object files). BLDLIBRARY is also -# the library to link against, usually. On Mac OS X frameworks, BLDLIBRARY -# is blank as the main program is not linked directly against LDLIBRARY. -# LDLIBRARYDIR is the path to LDLIBRARY, which is made in a subdirectory. On -# systems without shared libraries, LDLIBRARY is the same as LIBRARY -# (defined in the Makefiles). On Cygwin LDLIBRARY is the import library, -# DLLLIBRARY is the shared (i.e., DLL) library. -# -# RUNSHARED is used to run shared python without installed libraries -# -# INSTSONAME is the name of the shared library that will be use to install -# on the system - some systems like version suffix, others don't +if test $ac_cv_header_stdc = yes; then + # SunOS 4.x string.h does not declare mem*, contrary to ANSI. + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ +#include +_ACEOF +if (eval "$ac_cpp conftest.$ac_ext") 2>&5 | + $EGREP "memchr" >/dev/null 2>&1; then : +else + ac_cv_header_stdc=no +fi +rm -f conftest* +fi +if test $ac_cv_header_stdc = yes; then + # ISC 2.0.2 stdlib.h does not declare free, contrary to ANSI. + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ +#include +_ACEOF +if (eval "$ac_cpp conftest.$ac_ext") 2>&5 | + $EGREP "free" >/dev/null 2>&1; then : -LDLIBRARY="$LIBRARY" -BLDLIBRARY='$(LDLIBRARY)' -INSTSONAME='$(LDLIBRARY)' -DLLLIBRARY='' -LDLIBRARYDIR='' -RUNSHARED='' +else + ac_cv_header_stdc=no +fi +rm -f conftest* -# LINKCC is the command that links the python executable -- default is $(CC). -# If CXX is set, and if it is needed to link a main function that was -# compiled with CXX, LINKCC is CXX instead. Always using CXX is undesirable: -# python might then depend on the C++ runtime -# This is altered for AIX in order to build the export list before -# linking. +fi -{ $as_echo "$as_me:$LINENO: checking LINKCC" >&5 -$as_echo_n "checking LINKCC... " >&6; } -if test -z "$LINKCC" -then - LINKCC='$(PURIFY) $(MAINCC)' +if test $ac_cv_header_stdc = yes; then + # /bin/cc in Irix-4.0.5 gets non-ANSI ctype macros unless using -ansi. + if test "$cross_compiling" = yes; then : + : +else + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ +#include +#include +#if ((' ' & 0x0FF) == 0x020) +# define ISLOWER(c) ('a' <= (c) && (c) <= 'z') +# define TOUPPER(c) (ISLOWER(c) ? 'A' + ((c) - 'a') : (c)) +#else +# define ISLOWER(c) \ + (('a' <= (c) && (c) <= 'i') \ + || ('j' <= (c) && (c) <= 'r') \ + || ('s' <= (c) && (c) <= 'z')) +# define TOUPPER(c) (ISLOWER(c) ? ((c) | 0x40) : (c)) +#endif + +#define XOR(e, f) (((e) && !(f)) || (!(e) && (f))) +int +main () +{ + int i; + for (i = 0; i < 256; i++) + if (XOR (islower (i), ISLOWER (i)) + || toupper (i) != TOUPPER (i)) + return 2; + return 0; +} +_ACEOF +if ac_fn_c_try_run "$LINENO"; then : + +else + ac_cv_header_stdc=no +fi +rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext \ + conftest.$ac_objext conftest.beam conftest.$ac_ext +fi + +fi +fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_header_stdc" >&5 +$as_echo "$ac_cv_header_stdc" >&6; } +if test $ac_cv_header_stdc = yes; then + +$as_echo "#define STDC_HEADERS 1" >>confdefs.h + +fi + +# On IRIX 5.3, sys/types and inttypes.h are conflicting. +for ac_header in sys/types.h sys/stat.h stdlib.h string.h memory.h strings.h \ + inttypes.h stdint.h unistd.h +do : + as_ac_Header=`$as_echo "ac_cv_header_$ac_header" | $as_tr_sh` +ac_fn_c_check_header_compile "$LINENO" "$ac_header" "$as_ac_Header" "$ac_includes_default +" +eval as_val=\$$as_ac_Header + if test "x$as_val" = x""yes; then : + cat >>confdefs.h <<_ACEOF +#define `$as_echo "HAVE_$ac_header" | $as_tr_cpp` 1 +_ACEOF + +fi + +done + + + + ac_fn_c_check_header_mongrel "$LINENO" "minix/config.h" "ac_cv_header_minix_config_h" "$ac_includes_default" +if test "x$ac_cv_header_minix_config_h" = x""yes; then : + MINIX=yes +else + MINIX= +fi + + + if test "$MINIX" = yes; then + +$as_echo "#define _POSIX_SOURCE 1" >>confdefs.h + + +$as_echo "#define _POSIX_1_SOURCE 2" >>confdefs.h + + +$as_echo "#define _MINIX 1" >>confdefs.h + + fi + + + { $as_echo "$as_me:${as_lineno-$LINENO}: checking whether it is safe to define __EXTENSIONS__" >&5 +$as_echo_n "checking whether it is safe to define __EXTENSIONS__... " >&6; } +if test "${ac_cv_safe_to_define___extensions__+set}" = set; then : + $as_echo_n "(cached) " >&6 +else + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + +# define __EXTENSIONS__ 1 + $ac_includes_default +int +main () +{ + + ; + return 0; +} +_ACEOF +if ac_fn_c_try_compile "$LINENO"; then : + ac_cv_safe_to_define___extensions__=yes +else + ac_cv_safe_to_define___extensions__=no +fi +rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext +fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_safe_to_define___extensions__" >&5 +$as_echo "$ac_cv_safe_to_define___extensions__" >&6; } + test $ac_cv_safe_to_define___extensions__ = yes && + $as_echo "#define __EXTENSIONS__ 1" >>confdefs.h + + $as_echo "#define _ALL_SOURCE 1" >>confdefs.h + + $as_echo "#define _GNU_SOURCE 1" >>confdefs.h + + $as_echo "#define _POSIX_PTHREAD_SEMANTICS 1" >>confdefs.h + + $as_echo "#define _TANDEM_SOURCE 1" >>confdefs.h + + + + +# Check for unsupported systems +case $ac_sys_system/$ac_sys_release in +atheos*|Linux*/1*) + echo This system \($ac_sys_system/$ac_sys_release\) is no longer supported. + echo See README for details. + exit 1;; +esac + + +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for --with-suffix" >&5 +$as_echo_n "checking for --with-suffix... " >&6; } + +# Check whether --with-suffix was given. +if test "${with_suffix+set}" = set; then : + withval=$with_suffix; + case $withval in + no) EXEEXT=;; + yes) EXEEXT=.exe;; + *) EXEEXT=$withval;; + esac +fi + +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $EXEEXT" >&5 +$as_echo "$EXEEXT" >&6; } + +# Test whether we're running on a non-case-sensitive system, in which +# case we give a warning if no ext is given + +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for case-insensitive build directory" >&5 +$as_echo_n "checking for case-insensitive build directory... " >&6; } +if test ! -d CaseSensitiveTestDir; then +mkdir CaseSensitiveTestDir +fi + +if test -d casesensitivetestdir +then + { $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +$as_echo "yes" >&6; } + BUILDEXEEXT=.exe +else + { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 +$as_echo "no" >&6; } + BUILDEXEEXT=$EXEEXT +fi +rmdir CaseSensitiveTestDir + +case $MACHDEP in +bsdos*) + case $CC in + gcc) CC="$CC -D_HAVE_BSDI";; + esac;; +esac + +case $ac_sys_system in +hp*|HP*) + case $CC in + cc|*/cc) CC="$CC -Ae";; + esac;; +Monterey*) + case $CC in + cc) CC="$CC -Wl,-Bexport";; + esac;; +SunOS*) + # Some functions have a prototype only with that define, e.g. confstr + +$as_echo "#define __EXTENSIONS__ 1" >>confdefs.h + + ;; +esac + + + +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking LIBRARY" >&5 +$as_echo_n "checking LIBRARY... " >&6; } +if test -z "$LIBRARY" +then + LIBRARY='libpython$(VERSION).a' +fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $LIBRARY" >&5 +$as_echo "$LIBRARY" >&6; } + +# LDLIBRARY is the name of the library to link against (as opposed to the +# name of the library into which to insert object files). BLDLIBRARY is also +# the library to link against, usually. On Mac OS X frameworks, BLDLIBRARY +# is blank as the main program is not linked directly against LDLIBRARY. +# LDLIBRARYDIR is the path to LDLIBRARY, which is made in a subdirectory. On +# systems without shared libraries, LDLIBRARY is the same as LIBRARY +# (defined in the Makefiles). On Cygwin LDLIBRARY is the import library, +# DLLLIBRARY is the shared (i.e., DLL) library. +# +# RUNSHARED is used to run shared python without installed libraries +# +# INSTSONAME is the name of the shared library that will be use to install +# on the system - some systems like version suffix, others don't + + + + + + +LDLIBRARY="$LIBRARY" +BLDLIBRARY='$(LDLIBRARY)' +INSTSONAME='$(LDLIBRARY)' +DLLLIBRARY='' +LDLIBRARYDIR='' +RUNSHARED='' + +# LINKCC is the command that links the python executable -- default is $(CC). +# If CXX is set, and if it is needed to link a main function that was +# compiled with CXX, LINKCC is CXX instead. Always using CXX is undesirable: +# python might then depend on the C++ runtime +# This is altered for AIX in order to build the export list before +# linking. + +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking LINKCC" >&5 +$as_echo_n "checking LINKCC... " >&6; } +if test -z "$LINKCC" +then + LINKCC='$(PURIFY) $(MAINCC)' case $ac_sys_system in AIX*) exp_extra="\"\"" @@ -4605,13 +4641,13 @@ LINKCC=qcc;; esac fi -{ $as_echo "$as_me:$LINENO: result: $LINKCC" >&5 +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $LINKCC" >&5 $as_echo "$LINKCC" >&6; } -{ $as_echo "$as_me:$LINENO: checking for --enable-shared" >&5 +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for --enable-shared" >&5 $as_echo_n "checking for --enable-shared... " >&6; } # Check whether --enable-shared was given. -if test "${enable_shared+set}" = set; then +if test "${enable_shared+set}" = set; then : enableval=$enable_shared; fi @@ -4625,66 +4661,35 @@ enable_shared="no";; esac fi -{ $as_echo "$as_me:$LINENO: result: $enable_shared" >&5 +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $enable_shared" >&5 $as_echo "$enable_shared" >&6; } -{ $as_echo "$as_me:$LINENO: checking for --enable-profiling" >&5 +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for --enable-profiling" >&5 $as_echo_n "checking for --enable-profiling... " >&6; } # Check whether --enable-profiling was given. -if test "${enable_profiling+set}" = set; then +if test "${enable_profiling+set}" = set; then : enableval=$enable_profiling; ac_save_cc="$CC" CC="$CC -pg" - if test "$cross_compiling" = yes; then + if test "$cross_compiling" = yes; then : ac_enable_profiling="no" else - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF + cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ int main() { return 0; } _ACEOF -rm -f conftest$ac_exeext -if { (ac_try="$ac_link" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" -$as_echo "$ac_try_echo") >&5 - (eval "$ac_link") 2>&5 - ac_status=$? - $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { ac_try='./conftest$ac_exeext' - { (case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" -$as_echo "$ac_try_echo") >&5 - (eval "$ac_try") 2>&5 - ac_status=$? - $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); }; }; then +if ac_fn_c_try_run "$LINENO"; then : ac_enable_profiling="yes" else - $as_echo "$as_me: program exited with status $ac_status" >&5 -$as_echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - -( exit $ac_status ) -ac_enable_profiling="no" + ac_enable_profiling="no" fi -rm -rf conftest.dSYM -rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext conftest.$ac_objext conftest.$ac_ext +rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext \ + conftest.$ac_objext conftest.beam conftest.$ac_ext fi - CC="$ac_save_cc" fi -{ $as_echo "$as_me:$LINENO: result: $ac_enable_profiling" >&5 +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_enable_profiling" >&5 $as_echo "$ac_enable_profiling" >&6; } case "$ac_enable_profiling" in @@ -4694,7 +4699,7 @@ ;; esac -{ $as_echo "$as_me:$LINENO: checking LDLIBRARY" >&5 +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking LDLIBRARY" >&5 $as_echo_n "checking LDLIBRARY... " >&6; } # MacOSX framework builds need more magic. LDLIBRARY is the dynamic @@ -4715,9 +4720,7 @@ # Other platforms follow if test $enable_shared = "yes"; then -cat >>confdefs.h <<\_ACEOF -#define Py_ENABLE_SHARED 1 -_ACEOF +$as_echo "#define Py_ENABLE_SHARED 1" >>confdefs.h case $ac_sys_system in BeOS*) @@ -4782,15 +4785,15 @@ esac fi -{ $as_echo "$as_me:$LINENO: result: $LDLIBRARY" >&5 +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $LDLIBRARY" >&5 $as_echo "$LDLIBRARY" >&6; } if test -n "$ac_tool_prefix"; then # Extract the first word of "${ac_tool_prefix}ranlib", so it can be a program name with args. set dummy ${ac_tool_prefix}ranlib; ac_word=$2 -{ $as_echo "$as_me:$LINENO: checking for $ac_word" >&5 +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 $as_echo_n "checking for $ac_word... " >&6; } -if test "${ac_cv_prog_RANLIB+set}" = set; then +if test "${ac_cv_prog_RANLIB+set}" = set; then : $as_echo_n "(cached) " >&6 else if test -n "$RANLIB"; then @@ -4801,24 +4804,24 @@ do IFS=$as_save_IFS test -z "$as_dir" && as_dir=. - for ac_exec_ext in '' $ac_executable_extensions; do + for ac_exec_ext in '' $ac_executable_extensions; do if { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_test_x "$as_dir/$ac_word$ac_exec_ext"; }; then ac_cv_prog_RANLIB="${ac_tool_prefix}ranlib" - $as_echo "$as_me:$LINENO: found $as_dir/$ac_word$ac_exec_ext" >&5 + $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 break 2 fi done -done + done IFS=$as_save_IFS fi fi RANLIB=$ac_cv_prog_RANLIB if test -n "$RANLIB"; then - { $as_echo "$as_me:$LINENO: result: $RANLIB" >&5 + { $as_echo "$as_me:${as_lineno-$LINENO}: result: $RANLIB" >&5 $as_echo "$RANLIB" >&6; } else - { $as_echo "$as_me:$LINENO: result: no" >&5 + { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 $as_echo "no" >&6; } fi @@ -4828,9 +4831,9 @@ ac_ct_RANLIB=$RANLIB # Extract the first word of "ranlib", so it can be a program name with args. set dummy ranlib; ac_word=$2 -{ $as_echo "$as_me:$LINENO: checking for $ac_word" >&5 +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 $as_echo_n "checking for $ac_word... " >&6; } -if test "${ac_cv_prog_ac_ct_RANLIB+set}" = set; then +if test "${ac_cv_prog_ac_ct_RANLIB+set}" = set; then : $as_echo_n "(cached) " >&6 else if test -n "$ac_ct_RANLIB"; then @@ -4841,24 +4844,24 @@ do IFS=$as_save_IFS test -z "$as_dir" && as_dir=. - for ac_exec_ext in '' $ac_executable_extensions; do + for ac_exec_ext in '' $ac_executable_extensions; do if { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_test_x "$as_dir/$ac_word$ac_exec_ext"; }; then ac_cv_prog_ac_ct_RANLIB="ranlib" - $as_echo "$as_me:$LINENO: found $as_dir/$ac_word$ac_exec_ext" >&5 + $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 break 2 fi done -done + done IFS=$as_save_IFS fi fi ac_ct_RANLIB=$ac_cv_prog_ac_ct_RANLIB if test -n "$ac_ct_RANLIB"; then - { $as_echo "$as_me:$LINENO: result: $ac_ct_RANLIB" >&5 + { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_ct_RANLIB" >&5 $as_echo "$ac_ct_RANLIB" >&6; } else - { $as_echo "$as_me:$LINENO: result: no" >&5 + { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 $as_echo "no" >&6; } fi @@ -4867,7 +4870,7 @@ else case $cross_compiling:$ac_tool_warned in yes:) -{ $as_echo "$as_me:$LINENO: WARNING: using cross tools not prefixed with host triplet" >&5 +{ $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: using cross tools not prefixed with host triplet" >&5 $as_echo "$as_me: WARNING: using cross tools not prefixed with host triplet" >&2;} ac_tool_warned=yes ;; esac @@ -4882,9 +4885,9 @@ do # Extract the first word of "$ac_prog", so it can be a program name with args. set dummy $ac_prog; ac_word=$2 -{ $as_echo "$as_me:$LINENO: checking for $ac_word" >&5 +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 $as_echo_n "checking for $ac_word... " >&6; } -if test "${ac_cv_prog_AR+set}" = set; then +if test "${ac_cv_prog_AR+set}" = set; then : $as_echo_n "(cached) " >&6 else if test -n "$AR"; then @@ -4895,24 +4898,24 @@ do IFS=$as_save_IFS test -z "$as_dir" && as_dir=. - for ac_exec_ext in '' $ac_executable_extensions; do + for ac_exec_ext in '' $ac_executable_extensions; do if { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_test_x "$as_dir/$ac_word$ac_exec_ext"; }; then ac_cv_prog_AR="$ac_prog" - $as_echo "$as_me:$LINENO: found $as_dir/$ac_word$ac_exec_ext" >&5 + $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 break 2 fi done -done + done IFS=$as_save_IFS fi fi AR=$ac_cv_prog_AR if test -n "$AR"; then - { $as_echo "$as_me:$LINENO: result: $AR" >&5 + { $as_echo "$as_me:${as_lineno-$LINENO}: result: $AR" >&5 $as_echo "$AR" >&6; } else - { $as_echo "$as_me:$LINENO: result: no" >&5 + { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 $as_echo "no" >&6; } fi @@ -4925,9 +4928,9 @@ # Extract the first word of "svnversion", so it can be a program name with args. set dummy svnversion; ac_word=$2 -{ $as_echo "$as_me:$LINENO: checking for $ac_word" >&5 +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 $as_echo_n "checking for $ac_word... " >&6; } -if test "${ac_cv_prog_SVNVERSION+set}" = set; then +if test "${ac_cv_prog_SVNVERSION+set}" = set; then : $as_echo_n "(cached) " >&6 else if test -n "$SVNVERSION"; then @@ -4938,14 +4941,14 @@ do IFS=$as_save_IFS test -z "$as_dir" && as_dir=. - for ac_exec_ext in '' $ac_executable_extensions; do + for ac_exec_ext in '' $ac_executable_extensions; do if { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_test_x "$as_dir/$ac_word$ac_exec_ext"; }; then ac_cv_prog_SVNVERSION="found" - $as_echo "$as_me:$LINENO: found $as_dir/$ac_word$ac_exec_ext" >&5 + $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 break 2 fi done -done + done IFS=$as_save_IFS test -z "$ac_cv_prog_SVNVERSION" && ac_cv_prog_SVNVERSION="not-found" @@ -4953,10 +4956,10 @@ fi SVNVERSION=$ac_cv_prog_SVNVERSION if test -n "$SVNVERSION"; then - { $as_echo "$as_me:$LINENO: result: $SVNVERSION" >&5 + { $as_echo "$as_me:${as_lineno-$LINENO}: result: $SVNVERSION" >&5 $as_echo "$SVNVERSION" >&6; } else - { $as_echo "$as_me:$LINENO: result: no" >&5 + { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 $as_echo "no" >&6; } fi @@ -4978,24 +4981,16 @@ esac ac_aux_dir= for ac_dir in "$srcdir" "$srcdir/.." "$srcdir/../.."; do - if test -f "$ac_dir/install-sh"; then - ac_aux_dir=$ac_dir - ac_install_sh="$ac_aux_dir/install-sh -c" - break - elif test -f "$ac_dir/install.sh"; then - ac_aux_dir=$ac_dir - ac_install_sh="$ac_aux_dir/install.sh -c" - break - elif test -f "$ac_dir/shtool"; then - ac_aux_dir=$ac_dir - ac_install_sh="$ac_aux_dir/shtool install -c" - break - fi + for ac_t in install-sh install.sh shtool; do + if test -f "$ac_dir/$ac_t"; then + ac_aux_dir=$ac_dir + ac_install_sh="$ac_aux_dir/$ac_t -c" + break 2 + fi + done done if test -z "$ac_aux_dir"; then - { { $as_echo "$as_me:$LINENO: error: cannot find install-sh or install.sh in \"$srcdir\" \"$srcdir/..\" \"$srcdir/../..\"" >&5 -$as_echo "$as_me: error: cannot find install-sh or install.sh in \"$srcdir\" \"$srcdir/..\" \"$srcdir/../..\"" >&2;} - { (exit 1); exit 1; }; } + as_fn_error "cannot find install-sh, install.sh, or shtool in \"$srcdir\" \"$srcdir/..\" \"$srcdir/../..\"" "$LINENO" 5 fi # These three variables are undocumented and unsupported, @@ -5021,10 +5016,10 @@ # OS/2's system install, which has a completely different semantic # ./install, which can be erroneously created by make from ./install.sh. # Reject install programs that cannot install multiple files. -{ $as_echo "$as_me:$LINENO: checking for a BSD-compatible install" >&5 +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for a BSD-compatible install" >&5 $as_echo_n "checking for a BSD-compatible install... " >&6; } if test -z "$INSTALL"; then -if test "${ac_cv_path_install+set}" = set; then +if test "${ac_cv_path_install+set}" = set; then : $as_echo_n "(cached) " >&6 else as_save_IFS=$IFS; IFS=$PATH_SEPARATOR @@ -5032,11 +5027,11 @@ do IFS=$as_save_IFS test -z "$as_dir" && as_dir=. - # Account for people who put trailing slashes in PATH elements. -case $as_dir/ in - ./ | .// | /cC/* | \ + # Account for people who put trailing slashes in PATH elements. +case $as_dir/ in #(( + ./ | .// | /[cC]/* | \ /etc/* | /usr/sbin/* | /usr/etc/* | /sbin/* | /usr/afsws/bin/* | \ - ?:\\/os2\\/install\\/* | ?:\\/OS2\\/INSTALL\\/* | \ + ?:[\\/]os2[\\/]install[\\/]* | ?:[\\/]OS2[\\/]INSTALL[\\/]* | \ /usr/ucb/* ) ;; *) # OSF1 and SCO ODT 3.0 have their own names for install. @@ -5073,7 +5068,7 @@ ;; esac -done + done IFS=$as_save_IFS rm -rf conftest.one conftest.two conftest.dir @@ -5089,7 +5084,7 @@ INSTALL=$ac_install_sh fi fi -{ $as_echo "$as_me:$LINENO: result: $INSTALL" >&5 +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $INSTALL" >&5 $as_echo "$INSTALL" >&6; } # Use test -z because SunOS4 sh mishandles braces in ${var-val}. @@ -5113,27 +5108,25 @@ fi # Check for --with-pydebug -{ $as_echo "$as_me:$LINENO: checking for --with-pydebug" >&5 +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for --with-pydebug" >&5 $as_echo_n "checking for --with-pydebug... " >&6; } # Check whether --with-pydebug was given. -if test "${with_pydebug+set}" = set; then +if test "${with_pydebug+set}" = set; then : withval=$with_pydebug; if test "$withval" != no then -cat >>confdefs.h <<\_ACEOF -#define Py_DEBUG 1 -_ACEOF +$as_echo "#define Py_DEBUG 1" >>confdefs.h - { $as_echo "$as_me:$LINENO: result: yes" >&5 + { $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5 $as_echo "yes" >&6; }; Py_DEBUG='true' -else { $as_echo "$as_me:$LINENO: result: no" >&5 +else { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 $as_echo "no" >&6; }; Py_DEBUG='false' fi else - { $as_echo "$as_me:$LINENO: result: no" >&5 + { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 $as_echo "no" >&6; } fi @@ -5212,59 +5205,28 @@ # Python violates C99 rules, by casting between incompatible # pointer types. GCC may generate bad code as a result of that, # so use -fno-strict-aliasing if supported. - { $as_echo "$as_me:$LINENO: checking whether $CC accepts -fno-strict-aliasing" >&5 + { $as_echo "$as_me:${as_lineno-$LINENO}: checking whether $CC accepts -fno-strict-aliasing" >&5 $as_echo_n "checking whether $CC accepts -fno-strict-aliasing... " >&6; } ac_save_cc="$CC" CC="$CC -fno-strict-aliasing" - if test "$cross_compiling" = yes; then + if test "$cross_compiling" = yes; then : ac_cv_no_strict_aliasing_ok=no else - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF + cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ int main() { return 0; } _ACEOF -rm -f conftest$ac_exeext -if { (ac_try="$ac_link" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" -$as_echo "$ac_try_echo") >&5 - (eval "$ac_link") 2>&5 - ac_status=$? - $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { ac_try='./conftest$ac_exeext' - { (case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" -$as_echo "$ac_try_echo") >&5 - (eval "$ac_try") 2>&5 - ac_status=$? - $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); }; }; then +if ac_fn_c_try_run "$LINENO"; then : ac_cv_no_strict_aliasing_ok=yes else - $as_echo "$as_me: program exited with status $ac_status" >&5 -$as_echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - -( exit $ac_status ) -ac_cv_no_strict_aliasing_ok=no + ac_cv_no_strict_aliasing_ok=no fi -rm -rf conftest.dSYM -rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext conftest.$ac_objext conftest.$ac_ext +rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext \ + conftest.$ac_objext conftest.beam conftest.$ac_ext fi - CC="$ac_save_cc" - { $as_echo "$as_me:$LINENO: result: $ac_cv_no_strict_aliasing_ok" >&5 + { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_no_strict_aliasing_ok" >&5 $as_echo "$ac_cv_no_strict_aliasing_ok" >&6; } if test $ac_cv_no_strict_aliasing_ok = yes then @@ -5291,7 +5253,7 @@ if test "${CC}" = gcc then - { $as_echo "$as_me:$LINENO: checking which compiler should be used" >&5 + { $as_echo "$as_me:${as_lineno-$LINENO}: checking which compiler should be used" >&5 $as_echo_n "checking which compiler should be used... " >&6; } case "${UNIVERSALSDK}" in */MacOSX10.4u.sdk) @@ -5302,7 +5264,7 @@ CPP=cpp-4.0 ;; esac - { $as_echo "$as_me:$LINENO: result: $CC" >&5 + { $as_echo "$as_me:${as_lineno-$LINENO}: result: $CC" >&5 $as_echo "$CC" >&6; } fi @@ -5336,9 +5298,7 @@ LIPO_64BIT_FLAGS="-extract x86_64" else - { { $as_echo "$as_me:$LINENO: error: proper usage is --with-universal-arch=32-bit|64-bit|all|intel|3-way" >&5 -$as_echo "$as_me: error: proper usage is --with-universal-arch=32-bit|64-bit|all|intel|3-way" >&2;} - { (exit 1); exit 1; }; } + as_fn_error "proper usage is --with-universal-arch=32-bit|64-bit|all|intel|3-way" "$LINENO" 5 fi @@ -5431,64 +5391,33 @@ ac_cv_opt_olimit_ok=no fi -{ $as_echo "$as_me:$LINENO: checking whether $CC accepts -OPT:Olimit=0" >&5 +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking whether $CC accepts -OPT:Olimit=0" >&5 $as_echo_n "checking whether $CC accepts -OPT:Olimit=0... " >&6; } -if test "${ac_cv_opt_olimit_ok+set}" = set; then +if test "${ac_cv_opt_olimit_ok+set}" = set; then : $as_echo_n "(cached) " >&6 else ac_save_cc="$CC" CC="$CC -OPT:Olimit=0" -if test "$cross_compiling" = yes; then +if test "$cross_compiling" = yes; then : ac_cv_opt_olimit_ok=no else - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF + cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ int main() { return 0; } _ACEOF -rm -f conftest$ac_exeext -if { (ac_try="$ac_link" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" -$as_echo "$ac_try_echo") >&5 - (eval "$ac_link") 2>&5 - ac_status=$? - $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { ac_try='./conftest$ac_exeext' - { (case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" -$as_echo "$ac_try_echo") >&5 - (eval "$ac_try") 2>&5 - ac_status=$? - $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); }; }; then +if ac_fn_c_try_run "$LINENO"; then : ac_cv_opt_olimit_ok=yes else - $as_echo "$as_me: program exited with status $ac_status" >&5 -$as_echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - -( exit $ac_status ) -ac_cv_opt_olimit_ok=no + ac_cv_opt_olimit_ok=no fi -rm -rf conftest.dSYM -rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext conftest.$ac_objext conftest.$ac_ext +rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext \ + conftest.$ac_objext conftest.beam conftest.$ac_ext fi - CC="$ac_save_cc" fi -{ $as_echo "$as_me:$LINENO: result: $ac_cv_opt_olimit_ok" >&5 +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_opt_olimit_ok" >&5 $as_echo "$ac_cv_opt_olimit_ok" >&6; } if test $ac_cv_opt_olimit_ok = yes; then case $ac_sys_system in @@ -5502,64 +5431,33 @@ ;; esac else - { $as_echo "$as_me:$LINENO: checking whether $CC accepts -Olimit 1500" >&5 + { $as_echo "$as_me:${as_lineno-$LINENO}: checking whether $CC accepts -Olimit 1500" >&5 $as_echo_n "checking whether $CC accepts -Olimit 1500... " >&6; } - if test "${ac_cv_olimit_ok+set}" = set; then + if test "${ac_cv_olimit_ok+set}" = set; then : $as_echo_n "(cached) " >&6 else ac_save_cc="$CC" CC="$CC -Olimit 1500" - if test "$cross_compiling" = yes; then + if test "$cross_compiling" = yes; then : ac_cv_olimit_ok=no else - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF + cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ int main() { return 0; } _ACEOF -rm -f conftest$ac_exeext -if { (ac_try="$ac_link" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" -$as_echo "$ac_try_echo") >&5 - (eval "$ac_link") 2>&5 - ac_status=$? - $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { ac_try='./conftest$ac_exeext' - { (case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" -$as_echo "$ac_try_echo") >&5 - (eval "$ac_try") 2>&5 - ac_status=$? - $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); }; }; then +if ac_fn_c_try_run "$LINENO"; then : ac_cv_olimit_ok=yes else - $as_echo "$as_me: program exited with status $ac_status" >&5 -$as_echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - -( exit $ac_status ) -ac_cv_olimit_ok=no + ac_cv_olimit_ok=no fi -rm -rf conftest.dSYM -rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext conftest.$ac_objext conftest.$ac_ext +rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext \ + conftest.$ac_objext conftest.beam conftest.$ac_ext fi - CC="$ac_save_cc" fi - { $as_echo "$as_me:$LINENO: result: $ac_cv_olimit_ok" >&5 + { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_olimit_ok" >&5 $as_echo "$ac_cv_olimit_ok" >&6; } if test $ac_cv_olimit_ok = yes; then BASECFLAGS="$BASECFLAGS -Olimit 1500" @@ -5569,15 +5467,11 @@ # Check whether GCC supports PyArg_ParseTuple format if test "$GCC" = "yes" then - { $as_echo "$as_me:$LINENO: checking whether gcc supports ParseTuple __format__" >&5 + { $as_echo "$as_me:${as_lineno-$LINENO}: checking whether gcc supports ParseTuple __format__" >&5 $as_echo_n "checking whether gcc supports ParseTuple __format__... " >&6; } save_CFLAGS=$CFLAGS CFLAGS="$CFLAGS -Werror" - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF + cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ void f(char*,...)__attribute((format(PyArg_ParseTuple, 1, 2))); @@ -5590,40 +5484,17 @@ return 0; } _ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" -$as_echo "$ac_try_echo") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then +if ac_fn_c_try_compile "$LINENO"; then : -cat >>confdefs.h <<\_ACEOF -#define HAVE_ATTRIBUTE_FORMAT_PARSETUPLE 1 -_ACEOF +$as_echo "#define HAVE_ATTRIBUTE_FORMAT_PARSETUPLE 1" >>confdefs.h - { $as_echo "$as_me:$LINENO: result: yes" >&5 + { $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5 $as_echo "yes" >&6; } else - $as_echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - { $as_echo "$as_me:$LINENO: result: no" >&5 + { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 $as_echo "no" >&6; } fi - rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext CFLAGS=$save_CFLAGS fi @@ -5633,19 +5504,15 @@ # complain if unaccepted options are passed (e.g. gcc on Mac OS X). # So we have to see first whether pthreads are available without # options before we can check whether -Kpthread improves anything. -{ $as_echo "$as_me:$LINENO: checking whether pthreads are available without options" >&5 +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking whether pthreads are available without options" >&5 $as_echo_n "checking whether pthreads are available without options... " >&6; } -if test "${ac_cv_pthread_is_default+set}" = set; then +if test "${ac_cv_pthread_is_default+set}" = set; then : $as_echo_n "(cached) " >&6 else - if test "$cross_compiling" = yes; then + if test "$cross_compiling" = yes; then : ac_cv_pthread_is_default=no else - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF + cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ #include @@ -5661,50 +5528,23 @@ } _ACEOF -rm -f conftest$ac_exeext -if { (ac_try="$ac_link" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" -$as_echo "$ac_try_echo") >&5 - (eval "$ac_link") 2>&5 - ac_status=$? - $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { ac_try='./conftest$ac_exeext' - { (case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" -$as_echo "$ac_try_echo") >&5 - (eval "$ac_try") 2>&5 - ac_status=$? - $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); }; }; then +if ac_fn_c_try_run "$LINENO"; then : ac_cv_pthread_is_default=yes ac_cv_kthread=no ac_cv_pthread=no else - $as_echo "$as_me: program exited with status $ac_status" >&5 -$as_echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - -( exit $ac_status ) -ac_cv_pthread_is_default=no + ac_cv_pthread_is_default=no fi -rm -rf conftest.dSYM -rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext conftest.$ac_objext conftest.$ac_ext +rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext \ + conftest.$ac_objext conftest.beam conftest.$ac_ext fi - fi -{ $as_echo "$as_me:$LINENO: result: $ac_cv_pthread_is_default" >&5 +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_pthread_is_default" >&5 $as_echo "$ac_cv_pthread_is_default" >&6; } @@ -5717,21 +5557,17 @@ # Some compilers won't report that they do not support -Kpthread, # so we need to run a program to see whether it really made the # function available. -{ $as_echo "$as_me:$LINENO: checking whether $CC accepts -Kpthread" >&5 +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking whether $CC accepts -Kpthread" >&5 $as_echo_n "checking whether $CC accepts -Kpthread... " >&6; } -if test "${ac_cv_kpthread+set}" = set; then +if test "${ac_cv_kpthread+set}" = set; then : $as_echo_n "(cached) " >&6 else ac_save_cc="$CC" CC="$CC -Kpthread" -if test "$cross_compiling" = yes; then +if test "$cross_compiling" = yes; then : ac_cv_kpthread=no else - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF + cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ #include @@ -5747,46 +5583,19 @@ } _ACEOF -rm -f conftest$ac_exeext -if { (ac_try="$ac_link" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" -$as_echo "$ac_try_echo") >&5 - (eval "$ac_link") 2>&5 - ac_status=$? - $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { ac_try='./conftest$ac_exeext' - { (case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" -$as_echo "$ac_try_echo") >&5 - (eval "$ac_try") 2>&5 - ac_status=$? - $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); }; }; then +if ac_fn_c_try_run "$LINENO"; then : ac_cv_kpthread=yes else - $as_echo "$as_me: program exited with status $ac_status" >&5 -$as_echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - -( exit $ac_status ) -ac_cv_kpthread=no + ac_cv_kpthread=no fi -rm -rf conftest.dSYM -rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext conftest.$ac_objext conftest.$ac_ext +rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext \ + conftest.$ac_objext conftest.beam conftest.$ac_ext fi - CC="$ac_save_cc" fi -{ $as_echo "$as_me:$LINENO: result: $ac_cv_kpthread" >&5 +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_kpthread" >&5 $as_echo "$ac_cv_kpthread" >&6; } fi @@ -5797,21 +5606,17 @@ # Some compilers won't report that they do not support -Kthread, # so we need to run a program to see whether it really made the # function available. -{ $as_echo "$as_me:$LINENO: checking whether $CC accepts -Kthread" >&5 +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking whether $CC accepts -Kthread" >&5 $as_echo_n "checking whether $CC accepts -Kthread... " >&6; } -if test "${ac_cv_kthread+set}" = set; then +if test "${ac_cv_kthread+set}" = set; then : $as_echo_n "(cached) " >&6 else ac_save_cc="$CC" CC="$CC -Kthread" -if test "$cross_compiling" = yes; then +if test "$cross_compiling" = yes; then : ac_cv_kthread=no else - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF + cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ #include @@ -5827,46 +5632,19 @@ } _ACEOF -rm -f conftest$ac_exeext -if { (ac_try="$ac_link" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" -$as_echo "$ac_try_echo") >&5 - (eval "$ac_link") 2>&5 - ac_status=$? - $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { ac_try='./conftest$ac_exeext' - { (case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" -$as_echo "$ac_try_echo") >&5 - (eval "$ac_try") 2>&5 - ac_status=$? - $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); }; }; then +if ac_fn_c_try_run "$LINENO"; then : ac_cv_kthread=yes else - $as_echo "$as_me: program exited with status $ac_status" >&5 -$as_echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - -( exit $ac_status ) -ac_cv_kthread=no + ac_cv_kthread=no fi -rm -rf conftest.dSYM -rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext conftest.$ac_objext conftest.$ac_ext +rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext \ + conftest.$ac_objext conftest.beam conftest.$ac_ext fi - CC="$ac_save_cc" fi -{ $as_echo "$as_me:$LINENO: result: $ac_cv_kthread" >&5 +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_kthread" >&5 $as_echo "$ac_cv_kthread" >&6; } fi @@ -5877,21 +5655,17 @@ # Some compilers won't report that they do not support -pthread, # so we need to run a program to see whether it really made the # function available. -{ $as_echo "$as_me:$LINENO: checking whether $CC accepts -pthread" >&5 +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking whether $CC accepts -pthread" >&5 $as_echo_n "checking whether $CC accepts -pthread... " >&6; } -if test "${ac_cv_thread+set}" = set; then +if test "${ac_cv_thread+set}" = set; then : $as_echo_n "(cached) " >&6 else ac_save_cc="$CC" CC="$CC -pthread" -if test "$cross_compiling" = yes; then +if test "$cross_compiling" = yes; then : ac_cv_pthread=no else - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF + cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ #include @@ -5907,46 +5681,19 @@ } _ACEOF -rm -f conftest$ac_exeext -if { (ac_try="$ac_link" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" -$as_echo "$ac_try_echo") >&5 - (eval "$ac_link") 2>&5 - ac_status=$? - $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { ac_try='./conftest$ac_exeext' - { (case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" -$as_echo "$ac_try_echo") >&5 - (eval "$ac_try") 2>&5 - ac_status=$? - $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); }; }; then +if ac_fn_c_try_run "$LINENO"; then : ac_cv_pthread=yes else - $as_echo "$as_me: program exited with status $ac_status" >&5 -$as_echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - -( exit $ac_status ) -ac_cv_pthread=no + ac_cv_pthread=no fi -rm -rf conftest.dSYM -rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext conftest.$ac_objext conftest.$ac_ext +rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext \ + conftest.$ac_objext conftest.beam conftest.$ac_ext fi - CC="$ac_save_cc" fi -{ $as_echo "$as_me:$LINENO: result: $ac_cv_pthread" >&5 +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_pthread" >&5 $as_echo "$ac_cv_pthread" >&6; } fi @@ -5955,7 +5702,7 @@ ac_cv_cxx_thread=no if test ! -z "$CXX" then -{ $as_echo "$as_me:$LINENO: checking whether $CXX also accepts flags for thread support" >&5 +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking whether $CXX also accepts flags for thread support" >&5 $as_echo_n "checking whether $CXX also accepts flags for thread support... " >&6; } ac_save_cxx="$CXX" @@ -5986,23 +5733,19 @@ fi rm -fr conftest* fi -{ $as_echo "$as_me:$LINENO: result: $ac_cv_cxx_thread" >&5 +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_cxx_thread" >&5 $as_echo "$ac_cv_cxx_thread" >&6; } fi CXX="$ac_save_cxx" # checks for header files -{ $as_echo "$as_me:$LINENO: checking for ANSI C header files" >&5 +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for ANSI C header files" >&5 $as_echo_n "checking for ANSI C header files... " >&6; } -if test "${ac_cv_header_stdc+set}" = set; then +if test "${ac_cv_header_stdc+set}" = set; then : $as_echo_n "(cached) " >&6 else - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF + cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ #include #include @@ -6017,48 +5760,23 @@ return 0; } _ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" -$as_echo "$ac_try_echo") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then +if ac_fn_c_try_compile "$LINENO"; then : ac_cv_header_stdc=yes else - $as_echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - ac_cv_header_stdc=no + ac_cv_header_stdc=no fi - rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext if test $ac_cv_header_stdc = yes; then # SunOS 4.x string.h does not declare mem*, contrary to ANSI. - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF + cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ #include _ACEOF if (eval "$ac_cpp conftest.$ac_ext") 2>&5 | - $EGREP "memchr" >/dev/null 2>&1; then - : + $EGREP "memchr" >/dev/null 2>&1; then : + else ac_cv_header_stdc=no fi @@ -6068,18 +5786,14 @@ if test $ac_cv_header_stdc = yes; then # ISC 2.0.2 stdlib.h does not declare free, contrary to ANSI. - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF + cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ #include _ACEOF if (eval "$ac_cpp conftest.$ac_ext") 2>&5 | - $EGREP "free" >/dev/null 2>&1; then - : + $EGREP "free" >/dev/null 2>&1; then : + else ac_cv_header_stdc=no fi @@ -6089,14 +5803,10 @@ if test $ac_cv_header_stdc = yes; then # /bin/cc in Irix-4.0.5 gets non-ANSI ctype macros unless using -ansi. - if test "$cross_compiling" = yes; then + if test "$cross_compiling" = yes; then : : else - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF + cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ #include #include @@ -6123,108 +5833,25 @@ return 0; } _ACEOF -rm -f conftest$ac_exeext -if { (ac_try="$ac_link" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" -$as_echo "$ac_try_echo") >&5 - (eval "$ac_link") 2>&5 - ac_status=$? - $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { ac_try='./conftest$ac_exeext' - { (case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" -$as_echo "$ac_try_echo") >&5 - (eval "$ac_try") 2>&5 - ac_status=$? - $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); }; }; then - : -else - $as_echo "$as_me: program exited with status $ac_status" >&5 -$as_echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 +if ac_fn_c_try_run "$LINENO"; then : -( exit $ac_status ) -ac_cv_header_stdc=no +else + ac_cv_header_stdc=no fi -rm -rf conftest.dSYM -rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext conftest.$ac_objext conftest.$ac_ext +rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext \ + conftest.$ac_objext conftest.beam conftest.$ac_ext fi - fi fi -{ $as_echo "$as_me:$LINENO: result: $ac_cv_header_stdc" >&5 +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_header_stdc" >&5 $as_echo "$ac_cv_header_stdc" >&6; } if test $ac_cv_header_stdc = yes; then -cat >>confdefs.h <<\_ACEOF -#define STDC_HEADERS 1 -_ACEOF +$as_echo "#define STDC_HEADERS 1" >>confdefs.h fi - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - for ac_header in asm/types.h conio.h curses.h direct.h dlfcn.h errno.h \ fcntl.h grp.h \ ieeefp.h io.h langinfo.h libintl.h ncurses.h poll.h process.h pthread.h \ @@ -6237,173 +5864,28 @@ sys/times.h sys/types.h sys/un.h sys/utsname.h sys/wait.h pty.h libutil.h \ sys/resource.h netpacket/packet.h sysexits.h bluetooth.h \ bluetooth/bluetooth.h linux/tipc.h -do -as_ac_Header=`$as_echo "ac_cv_header_$ac_header" | $as_tr_sh` -if { as_var=$as_ac_Header; eval "test \"\${$as_var+set}\" = set"; }; then - { $as_echo "$as_me:$LINENO: checking for $ac_header" >&5 -$as_echo_n "checking for $ac_header... " >&6; } -if { as_var=$as_ac_Header; eval "test \"\${$as_var+set}\" = set"; }; then - $as_echo_n "(cached) " >&6 -fi -ac_res=`eval 'as_val=${'$as_ac_Header'} - $as_echo "$as_val"'` - { $as_echo "$as_me:$LINENO: result: $ac_res" >&5 -$as_echo "$ac_res" >&6; } -else - # Is the header compilable? -{ $as_echo "$as_me:$LINENO: checking $ac_header usability" >&5 -$as_echo_n "checking $ac_header usability... " >&6; } -cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -$ac_includes_default -#include <$ac_header> -_ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" -$as_echo "$ac_try_echo") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - ac_header_compiler=yes -else - $as_echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - ac_header_compiler=no -fi - -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext -{ $as_echo "$as_me:$LINENO: result: $ac_header_compiler" >&5 -$as_echo "$ac_header_compiler" >&6; } - -# Is the header present? -{ $as_echo "$as_me:$LINENO: checking $ac_header presence" >&5 -$as_echo_n "checking $ac_header presence... " >&6; } -cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -#include <$ac_header> -_ACEOF -if { (ac_try="$ac_cpp conftest.$ac_ext" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" -$as_echo "$ac_try_echo") >&5 - (eval "$ac_cpp conftest.$ac_ext") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } >/dev/null && { - test -z "$ac_c_preproc_warn_flag$ac_c_werror_flag" || - test ! -s conftest.err - }; then - ac_header_preproc=yes -else - $as_echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - ac_header_preproc=no -fi - -rm -f conftest.err conftest.$ac_ext -{ $as_echo "$as_me:$LINENO: result: $ac_header_preproc" >&5 -$as_echo "$ac_header_preproc" >&6; } - -# So? What about this header? -case $ac_header_compiler:$ac_header_preproc:$ac_c_preproc_warn_flag in - yes:no: ) - { $as_echo "$as_me:$LINENO: WARNING: $ac_header: accepted by the compiler, rejected by the preprocessor!" >&5 -$as_echo "$as_me: WARNING: $ac_header: accepted by the compiler, rejected by the preprocessor!" >&2;} - { $as_echo "$as_me:$LINENO: WARNING: $ac_header: proceeding with the compiler's result" >&5 -$as_echo "$as_me: WARNING: $ac_header: proceeding with the compiler's result" >&2;} - ac_header_preproc=yes - ;; - no:yes:* ) - { $as_echo "$as_me:$LINENO: WARNING: $ac_header: present but cannot be compiled" >&5 -$as_echo "$as_me: WARNING: $ac_header: present but cannot be compiled" >&2;} - { $as_echo "$as_me:$LINENO: WARNING: $ac_header: check for missing prerequisite headers?" >&5 -$as_echo "$as_me: WARNING: $ac_header: check for missing prerequisite headers?" >&2;} - { $as_echo "$as_me:$LINENO: WARNING: $ac_header: see the Autoconf documentation" >&5 -$as_echo "$as_me: WARNING: $ac_header: see the Autoconf documentation" >&2;} - { $as_echo "$as_me:$LINENO: WARNING: $ac_header: section \"Present But Cannot Be Compiled\"" >&5 -$as_echo "$as_me: WARNING: $ac_header: section \"Present But Cannot Be Compiled\"" >&2;} - { $as_echo "$as_me:$LINENO: WARNING: $ac_header: proceeding with the preprocessor's result" >&5 -$as_echo "$as_me: WARNING: $ac_header: proceeding with the preprocessor's result" >&2;} - { $as_echo "$as_me:$LINENO: WARNING: $ac_header: in the future, the compiler will take precedence" >&5 -$as_echo "$as_me: WARNING: $ac_header: in the future, the compiler will take precedence" >&2;} - ( cat <<\_ASBOX -## ------------------------------------------------ ## -## Report this to http://www.python.org/python-bugs ## -## ------------------------------------------------ ## -_ASBOX - ) | sed "s/^/$as_me: WARNING: /" >&2 - ;; -esac -{ $as_echo "$as_me:$LINENO: checking for $ac_header" >&5 -$as_echo_n "checking for $ac_header... " >&6; } -if { as_var=$as_ac_Header; eval "test \"\${$as_var+set}\" = set"; }; then - $as_echo_n "(cached) " >&6 -else - eval "$as_ac_Header=\$ac_header_preproc" -fi -ac_res=`eval 'as_val=${'$as_ac_Header'} - $as_echo "$as_val"'` - { $as_echo "$as_me:$LINENO: result: $ac_res" >&5 -$as_echo "$ac_res" >&6; } - -fi -as_val=`eval 'as_val=${'$as_ac_Header'} - $as_echo "$as_val"'` - if test "x$as_val" = x""yes; then - cat >>confdefs.h <<_ACEOF -#define `$as_echo "HAVE_$ac_header" | $as_tr_cpp` 1 +do : + as_ac_Header=`$as_echo "ac_cv_header_$ac_header" | $as_tr_sh` +ac_fn_c_check_header_mongrel "$LINENO" "$ac_header" "$as_ac_Header" "$ac_includes_default" +eval as_val=\$$as_ac_Header + if test "x$as_val" = x""yes; then : + cat >>confdefs.h <<_ACEOF +#define `$as_echo "HAVE_$ac_header" | $as_tr_cpp` 1 _ACEOF fi done - - - - - ac_header_dirent=no for ac_hdr in dirent.h sys/ndir.h sys/dir.h ndir.h; do as_ac_Header=`$as_echo "ac_cv_header_dirent_$ac_hdr" | $as_tr_sh` -{ $as_echo "$as_me:$LINENO: checking for $ac_hdr that defines DIR" >&5 +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_hdr that defines DIR" >&5 $as_echo_n "checking for $ac_hdr that defines DIR... " >&6; } -if { as_var=$as_ac_Header; eval "test \"\${$as_var+set}\" = set"; }; then +if { as_var=$as_ac_Header; eval "test \"\${$as_var+set}\" = set"; }; then : $as_echo_n "(cached) " >&6 else - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF + cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ #include #include <$ac_hdr> @@ -6417,41 +5899,18 @@ return 0; } _ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" -$as_echo "$ac_try_echo") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then +if ac_fn_c_try_compile "$LINENO"; then : eval "$as_ac_Header=yes" else - $as_echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - eval "$as_ac_Header=no" + eval "$as_ac_Header=no" fi - rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext fi -ac_res=`eval 'as_val=${'$as_ac_Header'} - $as_echo "$as_val"'` - { $as_echo "$as_me:$LINENO: result: $ac_res" >&5 +eval ac_res=\$$as_ac_Header + { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_res" >&5 $as_echo "$ac_res" >&6; } -as_val=`eval 'as_val=${'$as_ac_Header'} - $as_echo "$as_val"'` - if test "x$as_val" = x""yes; then +eval as_val=\$$as_ac_Header + if test "x$as_val" = x""yes; then : cat >>confdefs.h <<_ACEOF #define `$as_echo "HAVE_$ac_hdr" | $as_tr_cpp` 1 _ACEOF @@ -6462,17 +5921,13 @@ done # Two versions of opendir et al. are in -ldir and -lx on SCO Xenix. if test $ac_header_dirent = dirent.h; then - { $as_echo "$as_me:$LINENO: checking for library containing opendir" >&5 + { $as_echo "$as_me:${as_lineno-$LINENO}: checking for library containing opendir" >&5 $as_echo_n "checking for library containing opendir... " >&6; } -if test "${ac_cv_search_opendir+set}" = set; then +if test "${ac_cv_search_opendir+set}" = set; then : $as_echo_n "(cached) " >&6 else ac_func_search_save_LIBS=$LIBS -cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF +cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ /* Override any GCC internal prototype to avoid an error. @@ -6497,70 +5952,39 @@ ac_res=-l$ac_lib LIBS="-l$ac_lib $ac_func_search_save_LIBS" fi - rm -f conftest.$ac_objext conftest$ac_exeext -if { (ac_try="$ac_link" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" -$as_echo "$ac_try_echo") >&5 - (eval "$ac_link") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest$ac_exeext && { - test "$cross_compiling" = yes || - $as_test_x conftest$ac_exeext - }; then + if ac_fn_c_try_link "$LINENO"; then : ac_cv_search_opendir=$ac_res -else - $as_echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - fi - -rm -rf conftest.dSYM -rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \ - conftest$ac_exeext - if test "${ac_cv_search_opendir+set}" = set; then +rm -f core conftest.err conftest.$ac_objext \ + conftest$ac_exeext + if test "${ac_cv_search_opendir+set}" = set; then : break fi done -if test "${ac_cv_search_opendir+set}" = set; then - : +if test "${ac_cv_search_opendir+set}" = set; then : + else ac_cv_search_opendir=no fi rm conftest.$ac_ext LIBS=$ac_func_search_save_LIBS fi -{ $as_echo "$as_me:$LINENO: result: $ac_cv_search_opendir" >&5 +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_search_opendir" >&5 $as_echo "$ac_cv_search_opendir" >&6; } ac_res=$ac_cv_search_opendir -if test "$ac_res" != no; then +if test "$ac_res" != no; then : test "$ac_res" = "none required" || LIBS="$ac_res $LIBS" fi else - { $as_echo "$as_me:$LINENO: checking for library containing opendir" >&5 + { $as_echo "$as_me:${as_lineno-$LINENO}: checking for library containing opendir" >&5 $as_echo_n "checking for library containing opendir... " >&6; } -if test "${ac_cv_search_opendir+set}" = set; then +if test "${ac_cv_search_opendir+set}" = set; then : $as_echo_n "(cached) " >&6 else ac_func_search_save_LIBS=$LIBS -cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF +cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ /* Override any GCC internal prototype to avoid an error. @@ -6585,70 +6009,39 @@ ac_res=-l$ac_lib LIBS="-l$ac_lib $ac_func_search_save_LIBS" fi - rm -f conftest.$ac_objext conftest$ac_exeext -if { (ac_try="$ac_link" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" -$as_echo "$ac_try_echo") >&5 - (eval "$ac_link") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest$ac_exeext && { - test "$cross_compiling" = yes || - $as_test_x conftest$ac_exeext - }; then + if ac_fn_c_try_link "$LINENO"; then : ac_cv_search_opendir=$ac_res -else - $as_echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - fi - -rm -rf conftest.dSYM -rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \ - conftest$ac_exeext - if test "${ac_cv_search_opendir+set}" = set; then +rm -f core conftest.err conftest.$ac_objext \ + conftest$ac_exeext + if test "${ac_cv_search_opendir+set}" = set; then : break fi done -if test "${ac_cv_search_opendir+set}" = set; then - : +if test "${ac_cv_search_opendir+set}" = set; then : + else ac_cv_search_opendir=no fi rm conftest.$ac_ext LIBS=$ac_func_search_save_LIBS fi -{ $as_echo "$as_me:$LINENO: result: $ac_cv_search_opendir" >&5 +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_search_opendir" >&5 $as_echo "$ac_cv_search_opendir" >&6; } ac_res=$ac_cv_search_opendir -if test "$ac_res" != no; then +if test "$ac_res" != no; then : test "$ac_res" = "none required" || LIBS="$ac_res $LIBS" fi fi -{ $as_echo "$as_me:$LINENO: checking whether sys/types.h defines makedev" >&5 +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking whether sys/types.h defines makedev" >&5 $as_echo_n "checking whether sys/types.h defines makedev... " >&6; } -if test "${ac_cv_header_sys_types_h_makedev+set}" = set; then +if test "${ac_cv_header_sys_types_h_makedev+set}" = set; then : $as_echo_n "(cached) " >&6 else - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF + cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ #include int @@ -6659,509 +6052,110 @@ return 0; } _ACEOF -rm -f conftest.$ac_objext conftest$ac_exeext -if { (ac_try="$ac_link" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" -$as_echo "$ac_try_echo") >&5 - (eval "$ac_link") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest$ac_exeext && { - test "$cross_compiling" = yes || - $as_test_x conftest$ac_exeext - }; then +if ac_fn_c_try_link "$LINENO"; then : ac_cv_header_sys_types_h_makedev=yes else - $as_echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - ac_cv_header_sys_types_h_makedev=no + ac_cv_header_sys_types_h_makedev=no fi - -rm -rf conftest.dSYM -rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \ - conftest$ac_exeext conftest.$ac_ext +rm -f core conftest.err conftest.$ac_objext \ + conftest$ac_exeext conftest.$ac_ext fi -{ $as_echo "$as_me:$LINENO: result: $ac_cv_header_sys_types_h_makedev" >&5 +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_header_sys_types_h_makedev" >&5 $as_echo "$ac_cv_header_sys_types_h_makedev" >&6; } if test $ac_cv_header_sys_types_h_makedev = no; then -if test "${ac_cv_header_sys_mkdev_h+set}" = set; then - { $as_echo "$as_me:$LINENO: checking for sys/mkdev.h" >&5 -$as_echo_n "checking for sys/mkdev.h... " >&6; } -if test "${ac_cv_header_sys_mkdev_h+set}" = set; then - $as_echo_n "(cached) " >&6 -fi -{ $as_echo "$as_me:$LINENO: result: $ac_cv_header_sys_mkdev_h" >&5 -$as_echo "$ac_cv_header_sys_mkdev_h" >&6; } -else - # Is the header compilable? -{ $as_echo "$as_me:$LINENO: checking sys/mkdev.h usability" >&5 -$as_echo_n "checking sys/mkdev.h usability... " >&6; } -cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -$ac_includes_default -#include -_ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" -$as_echo "$ac_try_echo") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - ac_header_compiler=yes -else - $as_echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 +ac_fn_c_check_header_mongrel "$LINENO" "sys/mkdev.h" "ac_cv_header_sys_mkdev_h" "$ac_includes_default" +if test "x$ac_cv_header_sys_mkdev_h" = x""yes; then : + +$as_echo "#define MAJOR_IN_MKDEV 1" >>confdefs.h - ac_header_compiler=no fi -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext -{ $as_echo "$as_me:$LINENO: result: $ac_header_compiler" >&5 -$as_echo "$ac_header_compiler" >&6; } -# Is the header present? -{ $as_echo "$as_me:$LINENO: checking sys/mkdev.h presence" >&5 -$as_echo_n "checking sys/mkdev.h presence... " >&6; } -cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -#include -_ACEOF -if { (ac_try="$ac_cpp conftest.$ac_ext" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" -$as_echo "$ac_try_echo") >&5 - (eval "$ac_cpp conftest.$ac_ext") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } >/dev/null && { - test -z "$ac_c_preproc_warn_flag$ac_c_werror_flag" || - test ! -s conftest.err - }; then - ac_header_preproc=yes -else - $as_echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - ac_header_preproc=no -fi + if test $ac_cv_header_sys_mkdev_h = no; then + ac_fn_c_check_header_mongrel "$LINENO" "sys/sysmacros.h" "ac_cv_header_sys_sysmacros_h" "$ac_includes_default" +if test "x$ac_cv_header_sys_sysmacros_h" = x""yes; then : -rm -f conftest.err conftest.$ac_ext -{ $as_echo "$as_me:$LINENO: result: $ac_header_preproc" >&5 -$as_echo "$ac_header_preproc" >&6; } +$as_echo "#define MAJOR_IN_SYSMACROS 1" >>confdefs.h -# So? What about this header? -case $ac_header_compiler:$ac_header_preproc:$ac_c_preproc_warn_flag in - yes:no: ) - { $as_echo "$as_me:$LINENO: WARNING: sys/mkdev.h: accepted by the compiler, rejected by the preprocessor!" >&5 -$as_echo "$as_me: WARNING: sys/mkdev.h: accepted by the compiler, rejected by the preprocessor!" >&2;} - { $as_echo "$as_me:$LINENO: WARNING: sys/mkdev.h: proceeding with the compiler's result" >&5 -$as_echo "$as_me: WARNING: sys/mkdev.h: proceeding with the compiler's result" >&2;} - ac_header_preproc=yes - ;; - no:yes:* ) - { $as_echo "$as_me:$LINENO: WARNING: sys/mkdev.h: present but cannot be compiled" >&5 -$as_echo "$as_me: WARNING: sys/mkdev.h: present but cannot be compiled" >&2;} - { $as_echo "$as_me:$LINENO: WARNING: sys/mkdev.h: check for missing prerequisite headers?" >&5 -$as_echo "$as_me: WARNING: sys/mkdev.h: check for missing prerequisite headers?" >&2;} - { $as_echo "$as_me:$LINENO: WARNING: sys/mkdev.h: see the Autoconf documentation" >&5 -$as_echo "$as_me: WARNING: sys/mkdev.h: see the Autoconf documentation" >&2;} - { $as_echo "$as_me:$LINENO: WARNING: sys/mkdev.h: section \"Present But Cannot Be Compiled\"" >&5 -$as_echo "$as_me: WARNING: sys/mkdev.h: section \"Present But Cannot Be Compiled\"" >&2;} - { $as_echo "$as_me:$LINENO: WARNING: sys/mkdev.h: proceeding with the preprocessor's result" >&5 -$as_echo "$as_me: WARNING: sys/mkdev.h: proceeding with the preprocessor's result" >&2;} - { $as_echo "$as_me:$LINENO: WARNING: sys/mkdev.h: in the future, the compiler will take precedence" >&5 -$as_echo "$as_me: WARNING: sys/mkdev.h: in the future, the compiler will take precedence" >&2;} - ( cat <<\_ASBOX -## ------------------------------------------------ ## -## Report this to http://www.python.org/python-bugs ## -## ------------------------------------------------ ## -_ASBOX - ) | sed "s/^/$as_me: WARNING: /" >&2 - ;; -esac -{ $as_echo "$as_me:$LINENO: checking for sys/mkdev.h" >&5 -$as_echo_n "checking for sys/mkdev.h... " >&6; } -if test "${ac_cv_header_sys_mkdev_h+set}" = set; then - $as_echo_n "(cached) " >&6 -else - ac_cv_header_sys_mkdev_h=$ac_header_preproc fi -{ $as_echo "$as_me:$LINENO: result: $ac_cv_header_sys_mkdev_h" >&5 -$as_echo "$ac_cv_header_sys_mkdev_h" >&6; } + + fi fi -if test "x$ac_cv_header_sys_mkdev_h" = x""yes; then -cat >>confdefs.h <<\_ACEOF -#define MAJOR_IN_MKDEV 1 + +# On Solaris, term.h requires curses.h +for ac_header in term.h +do : + ac_fn_c_check_header_compile "$LINENO" "term.h" "ac_cv_header_term_h" " +#ifdef HAVE_CURSES_H +#include +#endif + +" +if test "x$ac_cv_header_term_h" = x""yes; then : + cat >>confdefs.h <<_ACEOF +#define HAVE_TERM_H 1 _ACEOF fi +done - if test $ac_cv_header_sys_mkdev_h = no; then - if test "${ac_cv_header_sys_sysmacros_h+set}" = set; then - { $as_echo "$as_me:$LINENO: checking for sys/sysmacros.h" >&5 -$as_echo_n "checking for sys/sysmacros.h... " >&6; } -if test "${ac_cv_header_sys_sysmacros_h+set}" = set; then - $as_echo_n "(cached) " >&6 -fi -{ $as_echo "$as_me:$LINENO: result: $ac_cv_header_sys_sysmacros_h" >&5 -$as_echo "$ac_cv_header_sys_sysmacros_h" >&6; } -else - # Is the header compilable? -{ $as_echo "$as_me:$LINENO: checking sys/sysmacros.h usability" >&5 -$as_echo_n "checking sys/sysmacros.h usability... " >&6; } -cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -$ac_includes_default -#include +# On Linux, netlink.h requires asm/types.h +for ac_header in linux/netlink.h +do : + ac_fn_c_check_header_compile "$LINENO" "linux/netlink.h" "ac_cv_header_linux_netlink_h" " +#ifdef HAVE_ASM_TYPES_H +#include +#endif +#ifdef HAVE_SYS_SOCKET_H +#include +#endif + +" +if test "x$ac_cv_header_linux_netlink_h" = x""yes; then : + cat >>confdefs.h <<_ACEOF +#define HAVE_LINUX_NETLINK_H 1 _ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" -$as_echo "$ac_try_echo") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - ac_header_compiler=yes -else - $as_echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - ac_header_compiler=no fi -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext -{ $as_echo "$as_me:$LINENO: result: $ac_header_compiler" >&5 -$as_echo "$ac_header_compiler" >&6; } +done -# Is the header present? -{ $as_echo "$as_me:$LINENO: checking sys/sysmacros.h presence" >&5 -$as_echo_n "checking sys/sysmacros.h presence... " >&6; } -cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF + +# checks for typedefs +was_it_defined=no +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for clock_t in time.h" >&5 +$as_echo_n "checking for clock_t in time.h... " >&6; } +cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ -#include +#include + _ACEOF -if { (ac_try="$ac_cpp conftest.$ac_ext" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" -$as_echo "$ac_try_echo") >&5 - (eval "$ac_cpp conftest.$ac_ext") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } >/dev/null && { - test -z "$ac_c_preproc_warn_flag$ac_c_werror_flag" || - test ! -s conftest.err - }; then - ac_header_preproc=yes +if (eval "$ac_cpp conftest.$ac_ext") 2>&5 | + $EGREP "clock_t" >/dev/null 2>&1; then : + was_it_defined=yes else - $as_echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - ac_header_preproc=no + +$as_echo "#define clock_t long" >>confdefs.h + + fi +rm -f conftest* -rm -f conftest.err conftest.$ac_ext -{ $as_echo "$as_me:$LINENO: result: $ac_header_preproc" >&5 -$as_echo "$ac_header_preproc" >&6; } - -# So? What about this header? -case $ac_header_compiler:$ac_header_preproc:$ac_c_preproc_warn_flag in - yes:no: ) - { $as_echo "$as_me:$LINENO: WARNING: sys/sysmacros.h: accepted by the compiler, rejected by the preprocessor!" >&5 -$as_echo "$as_me: WARNING: sys/sysmacros.h: accepted by the compiler, rejected by the preprocessor!" >&2;} - { $as_echo "$as_me:$LINENO: WARNING: sys/sysmacros.h: proceeding with the compiler's result" >&5 -$as_echo "$as_me: WARNING: sys/sysmacros.h: proceeding with the compiler's result" >&2;} - ac_header_preproc=yes - ;; - no:yes:* ) - { $as_echo "$as_me:$LINENO: WARNING: sys/sysmacros.h: present but cannot be compiled" >&5 -$as_echo "$as_me: WARNING: sys/sysmacros.h: present but cannot be compiled" >&2;} - { $as_echo "$as_me:$LINENO: WARNING: sys/sysmacros.h: check for missing prerequisite headers?" >&5 -$as_echo "$as_me: WARNING: sys/sysmacros.h: check for missing prerequisite headers?" >&2;} - { $as_echo "$as_me:$LINENO: WARNING: sys/sysmacros.h: see the Autoconf documentation" >&5 -$as_echo "$as_me: WARNING: sys/sysmacros.h: see the Autoconf documentation" >&2;} - { $as_echo "$as_me:$LINENO: WARNING: sys/sysmacros.h: section \"Present But Cannot Be Compiled\"" >&5 -$as_echo "$as_me: WARNING: sys/sysmacros.h: section \"Present But Cannot Be Compiled\"" >&2;} - { $as_echo "$as_me:$LINENO: WARNING: sys/sysmacros.h: proceeding with the preprocessor's result" >&5 -$as_echo "$as_me: WARNING: sys/sysmacros.h: proceeding with the preprocessor's result" >&2;} - { $as_echo "$as_me:$LINENO: WARNING: sys/sysmacros.h: in the future, the compiler will take precedence" >&5 -$as_echo "$as_me: WARNING: sys/sysmacros.h: in the future, the compiler will take precedence" >&2;} - ( cat <<\_ASBOX -## ------------------------------------------------ ## -## Report this to http://www.python.org/python-bugs ## -## ------------------------------------------------ ## -_ASBOX - ) | sed "s/^/$as_me: WARNING: /" >&2 - ;; -esac -{ $as_echo "$as_me:$LINENO: checking for sys/sysmacros.h" >&5 -$as_echo_n "checking for sys/sysmacros.h... " >&6; } -if test "${ac_cv_header_sys_sysmacros_h+set}" = set; then - $as_echo_n "(cached) " >&6 -else - ac_cv_header_sys_sysmacros_h=$ac_header_preproc -fi -{ $as_echo "$as_me:$LINENO: result: $ac_cv_header_sys_sysmacros_h" >&5 -$as_echo "$ac_cv_header_sys_sysmacros_h" >&6; } - -fi -if test "x$ac_cv_header_sys_sysmacros_h" = x""yes; then - -cat >>confdefs.h <<\_ACEOF -#define MAJOR_IN_SYSMACROS 1 -_ACEOF - -fi - - - fi -fi - - -# On Solaris, term.h requires curses.h - -for ac_header in term.h -do -as_ac_Header=`$as_echo "ac_cv_header_$ac_header" | $as_tr_sh` -{ $as_echo "$as_me:$LINENO: checking for $ac_header" >&5 -$as_echo_n "checking for $ac_header... " >&6; } -if { as_var=$as_ac_Header; eval "test \"\${$as_var+set}\" = set"; }; then - $as_echo_n "(cached) " >&6 -else - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ - -#ifdef HAVE_CURSES_H -#include -#endif - - -#include <$ac_header> -_ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" -$as_echo "$ac_try_echo") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - eval "$as_ac_Header=yes" -else - $as_echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - eval "$as_ac_Header=no" -fi - -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext -fi -ac_res=`eval 'as_val=${'$as_ac_Header'} - $as_echo "$as_val"'` - { $as_echo "$as_me:$LINENO: result: $ac_res" >&5 -$as_echo "$ac_res" >&6; } -as_val=`eval 'as_val=${'$as_ac_Header'} - $as_echo "$as_val"'` - if test "x$as_val" = x""yes; then - cat >>confdefs.h <<_ACEOF -#define `$as_echo "HAVE_$ac_header" | $as_tr_cpp` 1 -_ACEOF - -fi - -done - - -# On Linux, netlink.h requires asm/types.h - -for ac_header in linux/netlink.h -do -as_ac_Header=`$as_echo "ac_cv_header_$ac_header" | $as_tr_sh` -{ $as_echo "$as_me:$LINENO: checking for $ac_header" >&5 -$as_echo_n "checking for $ac_header... " >&6; } -if { as_var=$as_ac_Header; eval "test \"\${$as_var+set}\" = set"; }; then - $as_echo_n "(cached) " >&6 -else - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ - -#ifdef HAVE_ASM_TYPES_H -#include -#endif -#ifdef HAVE_SYS_SOCKET_H -#include -#endif - - -#include <$ac_header> -_ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" -$as_echo "$ac_try_echo") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - eval "$as_ac_Header=yes" -else - $as_echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - eval "$as_ac_Header=no" -fi - -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext -fi -ac_res=`eval 'as_val=${'$as_ac_Header'} - $as_echo "$as_val"'` - { $as_echo "$as_me:$LINENO: result: $ac_res" >&5 -$as_echo "$ac_res" >&6; } -as_val=`eval 'as_val=${'$as_ac_Header'} - $as_echo "$as_val"'` - if test "x$as_val" = x""yes; then - cat >>confdefs.h <<_ACEOF -#define `$as_echo "HAVE_$ac_header" | $as_tr_cpp` 1 -_ACEOF - -fi - -done - - -# checks for typedefs -was_it_defined=no -{ $as_echo "$as_me:$LINENO: checking for clock_t in time.h" >&5 -$as_echo_n "checking for clock_t in time.h... " >&6; } -cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -#include - -_ACEOF -if (eval "$ac_cpp conftest.$ac_ext") 2>&5 | - $EGREP "clock_t" >/dev/null 2>&1; then - was_it_defined=yes -else - - -cat >>confdefs.h <<\_ACEOF -#define clock_t long -_ACEOF - - -fi -rm -f conftest* - -{ $as_echo "$as_me:$LINENO: result: $was_it_defined" >&5 -$as_echo "$was_it_defined" >&6; } +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $was_it_defined" >&5 +$as_echo "$was_it_defined" >&6; } # Check whether using makedev requires defining _OSF_SOURCE -{ $as_echo "$as_me:$LINENO: checking for makedev" >&5 +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for makedev" >&5 $as_echo_n "checking for makedev... " >&6; } -cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF +cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ #if defined(MAJOR_IN_MKDEV) @@ -7179,45 +6173,16 @@ return 0; } _ACEOF -rm -f conftest.$ac_objext conftest$ac_exeext -if { (ac_try="$ac_link" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" -$as_echo "$ac_try_echo") >&5 - (eval "$ac_link") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest$ac_exeext && { - test "$cross_compiling" = yes || - $as_test_x conftest$ac_exeext - }; then +if ac_fn_c_try_link "$LINENO"; then : ac_cv_has_makedev=yes else - $as_echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - ac_cv_has_makedev=no + ac_cv_has_makedev=no fi - -rm -rf conftest.dSYM -rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \ - conftest$ac_exeext conftest.$ac_ext +rm -f core conftest.err conftest.$ac_objext \ + conftest$ac_exeext conftest.$ac_ext if test "$ac_cv_has_makedev" = "no"; then # we didn't link, try if _OSF_SOURCE will allow us to link - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF + cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ #define _OSF_SOURCE 1 @@ -7231,53 +6196,24 @@ return 0; } _ACEOF -rm -f conftest.$ac_objext conftest$ac_exeext -if { (ac_try="$ac_link" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" -$as_echo "$ac_try_echo") >&5 - (eval "$ac_link") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest$ac_exeext && { - test "$cross_compiling" = yes || - $as_test_x conftest$ac_exeext - }; then +if ac_fn_c_try_link "$LINENO"; then : ac_cv_has_makedev=yes else - $as_echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - ac_cv_has_makedev=no + ac_cv_has_makedev=no fi - -rm -rf conftest.dSYM -rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \ - conftest$ac_exeext conftest.$ac_ext +rm -f core conftest.err conftest.$ac_objext \ + conftest$ac_exeext conftest.$ac_ext if test "$ac_cv_has_makedev" = "yes"; then -cat >>confdefs.h <<\_ACEOF -#define _OSF_SOURCE 1 -_ACEOF +$as_echo "#define _OSF_SOURCE 1" >>confdefs.h fi fi -{ $as_echo "$as_me:$LINENO: result: $ac_cv_has_makedev" >&5 +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_has_makedev" >&5 $as_echo "$ac_cv_has_makedev" >&6; } if test "$ac_cv_has_makedev" = "yes"; then -cat >>confdefs.h <<\_ACEOF -#define HAVE_MAKEDEV 1 -_ACEOF +$as_echo "#define HAVE_MAKEDEV 1" >>confdefs.h fi @@ -7289,13 +6225,9 @@ # work-around, disable LFS on such configurations use_lfs=yes -{ $as_echo "$as_me:$LINENO: checking Solaris LFS bug" >&5 +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking Solaris LFS bug" >&5 $as_echo_n "checking Solaris LFS bug... " >&6; } -cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF +cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ #define _LARGEFILE_SOURCE 1 @@ -7310,34 +6242,13 @@ return 0; } _ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" -$as_echo "$ac_try_echo") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then +if ac_fn_c_try_compile "$LINENO"; then : sol_lfs_bug=no else - $as_echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - sol_lfs_bug=yes + sol_lfs_bug=yes fi - rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext -{ $as_echo "$as_me:$LINENO: result: $sol_lfs_bug" >&5 +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $sol_lfs_bug" >&5 $as_echo "$sol_lfs_bug" >&6; } if test "$sol_lfs_bug" = "yes"; then use_lfs=no @@ -7347,14 +6258,10 @@ # Two defines needed to enable largefile support on various platforms # These may affect some typedefs -cat >>confdefs.h <<\_ACEOF -#define _LARGEFILE_SOURCE 1 -_ACEOF +$as_echo "#define _LARGEFILE_SOURCE 1" >>confdefs.h -cat >>confdefs.h <<\_ACEOF -#define _FILE_OFFSET_BITS 64 -_ACEOF +$as_echo "#define _FILE_OFFSET_BITS 64" >>confdefs.h fi @@ -7366,10977 +6273,1351 @@ EOF # Type availability checks -{ $as_echo "$as_me:$LINENO: checking for mode_t" >&5 -$as_echo_n "checking for mode_t... " >&6; } -if test "${ac_cv_type_mode_t+set}" = set; then - $as_echo_n "(cached) " >&6 +ac_fn_c_check_type "$LINENO" "mode_t" "ac_cv_type_mode_t" "$ac_includes_default" +if test "x$ac_cv_type_mode_t" = x""yes; then : + else - ac_cv_type_mode_t=no -cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -$ac_includes_default -int -main () -{ -if (sizeof (mode_t)) - return 0; - ; - return 0; -} -_ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" -$as_echo "$ac_try_echo") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -$ac_includes_default -int -main () -{ -if (sizeof ((mode_t))) - return 0; - ; - return 0; -} + +cat >>confdefs.h <<_ACEOF +#define mode_t int _ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" -$as_echo "$ac_try_echo") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - : -else - $as_echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - ac_cv_type_mode_t=yes fi -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext +ac_fn_c_check_type "$LINENO" "off_t" "ac_cv_type_off_t" "$ac_includes_default" +if test "x$ac_cv_type_off_t" = x""yes; then : + else - $as_echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 +cat >>confdefs.h <<_ACEOF +#define off_t long int +_ACEOF fi -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext -fi -{ $as_echo "$as_me:$LINENO: result: $ac_cv_type_mode_t" >&5 -$as_echo "$ac_cv_type_mode_t" >&6; } -if test "x$ac_cv_type_mode_t" = x""yes; then - : +ac_fn_c_check_type "$LINENO" "pid_t" "ac_cv_type_pid_t" "$ac_includes_default" +if test "x$ac_cv_type_pid_t" = x""yes; then : + else cat >>confdefs.h <<_ACEOF -#define mode_t int +#define pid_t int _ACEOF fi -{ $as_echo "$as_me:$LINENO: checking for off_t" >&5 -$as_echo_n "checking for off_t... " >&6; } -if test "${ac_cv_type_off_t+set}" = set; then +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking return type of signal handlers" >&5 +$as_echo_n "checking return type of signal handlers... " >&6; } +if test "${ac_cv_type_signal+set}" = set; then : $as_echo_n "(cached) " >&6 else - ac_cv_type_off_t=no -cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF + cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ -$ac_includes_default +#include +#include + int main () { -if (sizeof (off_t)) - return 0; +return *(signal (0, 0)) (0) == 1; ; return 0; } _ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" -$as_echo "$ac_try_echo") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ +if ac_fn_c_try_compile "$LINENO"; then : + ac_cv_type_signal=int +else + ac_cv_type_signal=void +fi +rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext +fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_type_signal" >&5 +$as_echo "$ac_cv_type_signal" >&6; } + +cat >>confdefs.h <<_ACEOF +#define RETSIGTYPE $ac_cv_type_signal _ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -$ac_includes_default -int -main () -{ -if (sizeof ((off_t))) - return 0; - ; - return 0; -} -_ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" -$as_echo "$ac_try_echo") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - : -else - $as_echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - ac_cv_type_off_t=yes -fi - -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext -else - $as_echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 -fi +ac_fn_c_check_type "$LINENO" "size_t" "ac_cv_type_size_t" "$ac_includes_default" +if test "x$ac_cv_type_size_t" = x""yes; then : -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext -fi -{ $as_echo "$as_me:$LINENO: result: $ac_cv_type_off_t" >&5 -$as_echo "$ac_cv_type_off_t" >&6; } -if test "x$ac_cv_type_off_t" = x""yes; then - : else cat >>confdefs.h <<_ACEOF -#define off_t long int +#define size_t unsigned int _ACEOF fi -{ $as_echo "$as_me:$LINENO: checking for pid_t" >&5 -$as_echo_n "checking for pid_t... " >&6; } -if test "${ac_cv_type_pid_t+set}" = set; then +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for uid_t in sys/types.h" >&5 +$as_echo_n "checking for uid_t in sys/types.h... " >&6; } +if test "${ac_cv_type_uid_t+set}" = set; then : $as_echo_n "(cached) " >&6 else - ac_cv_type_pid_t=no -cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -$ac_includes_default -int -main () -{ -if (sizeof (pid_t)) - return 0; - ; - return 0; -} -_ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" -$as_echo "$ac_try_echo") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF + cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ -$ac_includes_default -int -main () -{ -if (sizeof ((pid_t))) - return 0; - ; - return 0; -} +#include + _ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" -$as_echo "$ac_try_echo") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - : +if (eval "$ac_cpp conftest.$ac_ext") 2>&5 | + $EGREP "uid_t" >/dev/null 2>&1; then : + ac_cv_type_uid_t=yes else - $as_echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 + ac_cv_type_uid_t=no +fi +rm -f conftest* - ac_cv_type_pid_t=yes fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_type_uid_t" >&5 +$as_echo "$ac_cv_type_uid_t" >&6; } +if test $ac_cv_type_uid_t = no; then -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext -else - $as_echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 +$as_echo "#define uid_t int" >>confdefs.h -fi +$as_echo "#define gid_t int" >>confdefs.h -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext fi -{ $as_echo "$as_me:$LINENO: result: $ac_cv_type_pid_t" >&5 -$as_echo "$ac_cv_type_pid_t" >&6; } -if test "x$ac_cv_type_pid_t" = x""yes; then - : -else -cat >>confdefs.h <<_ACEOF -#define pid_t int -_ACEOF +ac_fn_c_check_type "$LINENO" "ssize_t" "ac_cv_type_ssize_t" "$ac_includes_default" +if test "x$ac_cv_type_ssize_t" = x""yes; then : + +$as_echo "#define HAVE_SSIZE_T 1" >>confdefs.h fi -{ $as_echo "$as_me:$LINENO: checking return type of signal handlers" >&5 -$as_echo_n "checking return type of signal handlers... " >&6; } -if test "${ac_cv_type_signal+set}" = set; then + +# Sizes of various common basic types +# ANSI C requires sizeof(char) == 1, so no need to check it +# The cast to long int works around a bug in the HP C Compiler +# version HP92453-01 B.11.11.23709.GP, which incorrectly rejects +# declarations like `int a3[[(sizeof (unsigned char)) >= 0]];'. +# This bug is HP SR number 8606223364. +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking size of int" >&5 +$as_echo_n "checking size of int... " >&6; } +if test "${ac_cv_sizeof_int+set}" = set; then : $as_echo_n "(cached) " >&6 else - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -#include -#include + if ac_fn_c_compute_int "$LINENO" "(long int) (sizeof (int))" "ac_cv_sizeof_int" "$ac_includes_default"; then : -int -main () -{ -return *(signal (0, 0)) (0) == 1; - ; - return 0; -} -_ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" -$as_echo "$ac_try_echo") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - ac_cv_type_signal=int else - $as_echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - ac_cv_type_signal=void + if test "$ac_cv_type_int" = yes; then + { { $as_echo "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5 +$as_echo "$as_me: error: in \`$ac_pwd':" >&2;} +{ as_fn_set_status 77 +as_fn_error "cannot compute sizeof (int) +See \`config.log' for more details." "$LINENO" 5; }; } + else + ac_cv_sizeof_int=0 + fi fi -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext fi -{ $as_echo "$as_me:$LINENO: result: $ac_cv_type_signal" >&5 -$as_echo "$ac_cv_type_signal" >&6; } +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_sizeof_int" >&5 +$as_echo "$ac_cv_sizeof_int" >&6; } + + cat >>confdefs.h <<_ACEOF -#define RETSIGTYPE $ac_cv_type_signal +#define SIZEOF_INT $ac_cv_sizeof_int _ACEOF -{ $as_echo "$as_me:$LINENO: checking for size_t" >&5 -$as_echo_n "checking for size_t... " >&6; } -if test "${ac_cv_type_size_t+set}" = set; then +# The cast to long int works around a bug in the HP C Compiler +# version HP92453-01 B.11.11.23709.GP, which incorrectly rejects +# declarations like `int a3[[(sizeof (unsigned char)) >= 0]];'. +# This bug is HP SR number 8606223364. +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking size of long" >&5 +$as_echo_n "checking size of long... " >&6; } +if test "${ac_cv_sizeof_long+set}" = set; then : $as_echo_n "(cached) " >&6 else - ac_cv_type_size_t=no -cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -$ac_includes_default -int -main () -{ -if (sizeof (size_t)) - return 0; - ; - return 0; -} -_ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" -$as_echo "$ac_try_echo") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -$ac_includes_default -int -main () -{ -if (sizeof ((size_t))) - return 0; - ; - return 0; -} -_ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" -$as_echo "$ac_try_echo") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - : + if ac_fn_c_compute_int "$LINENO" "(long int) (sizeof (long))" "ac_cv_sizeof_long" "$ac_includes_default"; then : + else - $as_echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 + if test "$ac_cv_type_long" = yes; then + { { $as_echo "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5 +$as_echo "$as_me: error: in \`$ac_pwd':" >&2;} +{ as_fn_set_status 77 +as_fn_error "cannot compute sizeof (long) +See \`config.log' for more details." "$LINENO" 5; }; } + else + ac_cv_sizeof_long=0 + fi +fi - ac_cv_type_size_t=yes fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_sizeof_long" >&5 +$as_echo "$ac_cv_sizeof_long" >&6; } -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext -else - $as_echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 +cat >>confdefs.h <<_ACEOF +#define SIZEOF_LONG $ac_cv_sizeof_long +_ACEOF + + +# The cast to long int works around a bug in the HP C Compiler +# version HP92453-01 B.11.11.23709.GP, which incorrectly rejects +# declarations like `int a3[[(sizeof (unsigned char)) >= 0]];'. +# This bug is HP SR number 8606223364. +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking size of void *" >&5 +$as_echo_n "checking size of void *... " >&6; } +if test "${ac_cv_sizeof_void_p+set}" = set; then : + $as_echo_n "(cached) " >&6 +else + if ac_fn_c_compute_int "$LINENO" "(long int) (sizeof (void *))" "ac_cv_sizeof_void_p" "$ac_includes_default"; then : + +else + if test "$ac_cv_type_void_p" = yes; then + { { $as_echo "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5 +$as_echo "$as_me: error: in \`$ac_pwd':" >&2;} +{ as_fn_set_status 77 +as_fn_error "cannot compute sizeof (void *) +See \`config.log' for more details." "$LINENO" 5; }; } + else + ac_cv_sizeof_void_p=0 + fi fi -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext fi -{ $as_echo "$as_me:$LINENO: result: $ac_cv_type_size_t" >&5 -$as_echo "$ac_cv_type_size_t" >&6; } -if test "x$ac_cv_type_size_t" = x""yes; then - : -else +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_sizeof_void_p" >&5 +$as_echo "$ac_cv_sizeof_void_p" >&6; } + + cat >>confdefs.h <<_ACEOF -#define size_t unsigned int +#define SIZEOF_VOID_P $ac_cv_sizeof_void_p _ACEOF -fi -{ $as_echo "$as_me:$LINENO: checking for uid_t in sys/types.h" >&5 -$as_echo_n "checking for uid_t in sys/types.h... " >&6; } -if test "${ac_cv_type_uid_t+set}" = set; then +# The cast to long int works around a bug in the HP C Compiler +# version HP92453-01 B.11.11.23709.GP, which incorrectly rejects +# declarations like `int a3[[(sizeof (unsigned char)) >= 0]];'. +# This bug is HP SR number 8606223364. +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking size of short" >&5 +$as_echo_n "checking size of short... " >&6; } +if test "${ac_cv_sizeof_short+set}" = set; then : $as_echo_n "(cached) " >&6 else - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -#include + if ac_fn_c_compute_int "$LINENO" "(long int) (sizeof (short))" "ac_cv_sizeof_short" "$ac_includes_default"; then : -_ACEOF -if (eval "$ac_cpp conftest.$ac_ext") 2>&5 | - $EGREP "uid_t" >/dev/null 2>&1; then - ac_cv_type_uid_t=yes else - ac_cv_type_uid_t=no + if test "$ac_cv_type_short" = yes; then + { { $as_echo "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5 +$as_echo "$as_me: error: in \`$ac_pwd':" >&2;} +{ as_fn_set_status 77 +as_fn_error "cannot compute sizeof (short) +See \`config.log' for more details." "$LINENO" 5; }; } + else + ac_cv_sizeof_short=0 + fi fi -rm -f conftest* fi -{ $as_echo "$as_me:$LINENO: result: $ac_cv_type_uid_t" >&5 -$as_echo "$ac_cv_type_uid_t" >&6; } -if test $ac_cv_type_uid_t = no; then +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_sizeof_short" >&5 +$as_echo "$ac_cv_sizeof_short" >&6; } -cat >>confdefs.h <<\_ACEOF -#define uid_t int -_ACEOF -cat >>confdefs.h <<\_ACEOF -#define gid_t int +cat >>confdefs.h <<_ACEOF +#define SIZEOF_SHORT $ac_cv_sizeof_short _ACEOF -fi -{ $as_echo "$as_me:$LINENO: checking for ssize_t" >&5 -$as_echo_n "checking for ssize_t... " >&6; } -if test "${ac_cv_type_ssize_t+set}" = set; then +# The cast to long int works around a bug in the HP C Compiler +# version HP92453-01 B.11.11.23709.GP, which incorrectly rejects +# declarations like `int a3[[(sizeof (unsigned char)) >= 0]];'. +# This bug is HP SR number 8606223364. +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking size of float" >&5 +$as_echo_n "checking size of float... " >&6; } +if test "${ac_cv_sizeof_float+set}" = set; then : $as_echo_n "(cached) " >&6 else - ac_cv_type_ssize_t=no -cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ + if ac_fn_c_compute_int "$LINENO" "(long int) (sizeof (float))" "ac_cv_sizeof_float" "$ac_includes_default"; then : + +else + if test "$ac_cv_type_float" = yes; then + { { $as_echo "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5 +$as_echo "$as_me: error: in \`$ac_pwd':" >&2;} +{ as_fn_set_status 77 +as_fn_error "cannot compute sizeof (float) +See \`config.log' for more details." "$LINENO" 5; }; } + else + ac_cv_sizeof_float=0 + fi +fi + +fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_sizeof_float" >&5 +$as_echo "$ac_cv_sizeof_float" >&6; } + + + +cat >>confdefs.h <<_ACEOF +#define SIZEOF_FLOAT $ac_cv_sizeof_float _ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -$ac_includes_default -int -main () -{ -if (sizeof (ssize_t)) - return 0; - ; - return 0; -} -_ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" -$as_echo "$ac_try_echo") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -$ac_includes_default -int -main () -{ -if (sizeof ((ssize_t))) - return 0; - ; - return 0; -} -_ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" -$as_echo "$ac_try_echo") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - : -else - $as_echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - ac_cv_type_ssize_t=yes -fi -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext +# The cast to long int works around a bug in the HP C Compiler +# version HP92453-01 B.11.11.23709.GP, which incorrectly rejects +# declarations like `int a3[[(sizeof (unsigned char)) >= 0]];'. +# This bug is HP SR number 8606223364. +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking size of double" >&5 +$as_echo_n "checking size of double... " >&6; } +if test "${ac_cv_sizeof_double+set}" = set; then : + $as_echo_n "(cached) " >&6 else - $as_echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - + if ac_fn_c_compute_int "$LINENO" "(long int) (sizeof (double))" "ac_cv_sizeof_double" "$ac_includes_default"; then : +else + if test "$ac_cv_type_double" = yes; then + { { $as_echo "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5 +$as_echo "$as_me: error: in \`$ac_pwd':" >&2;} +{ as_fn_set_status 77 +as_fn_error "cannot compute sizeof (double) +See \`config.log' for more details." "$LINENO" 5; }; } + else + ac_cv_sizeof_double=0 + fi fi -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext fi -{ $as_echo "$as_me:$LINENO: result: $ac_cv_type_ssize_t" >&5 -$as_echo "$ac_cv_type_ssize_t" >&6; } -if test "x$ac_cv_type_ssize_t" = x""yes; then +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_sizeof_double" >&5 +$as_echo "$ac_cv_sizeof_double" >&6; } + -cat >>confdefs.h <<\_ACEOF -#define HAVE_SSIZE_T 1 + +cat >>confdefs.h <<_ACEOF +#define SIZEOF_DOUBLE $ac_cv_sizeof_double _ACEOF + +# The cast to long int works around a bug in the HP C Compiler +# version HP92453-01 B.11.11.23709.GP, which incorrectly rejects +# declarations like `int a3[[(sizeof (unsigned char)) >= 0]];'. +# This bug is HP SR number 8606223364. +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking size of fpos_t" >&5 +$as_echo_n "checking size of fpos_t... " >&6; } +if test "${ac_cv_sizeof_fpos_t+set}" = set; then : + $as_echo_n "(cached) " >&6 +else + if ac_fn_c_compute_int "$LINENO" "(long int) (sizeof (fpos_t))" "ac_cv_sizeof_fpos_t" "$ac_includes_default"; then : + +else + if test "$ac_cv_type_fpos_t" = yes; then + { { $as_echo "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5 +$as_echo "$as_me: error: in \`$ac_pwd':" >&2;} +{ as_fn_set_status 77 +as_fn_error "cannot compute sizeof (fpos_t) +See \`config.log' for more details." "$LINENO" 5; }; } + else + ac_cv_sizeof_fpos_t=0 + fi +fi + fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_sizeof_fpos_t" >&5 +$as_echo "$ac_cv_sizeof_fpos_t" >&6; } + + + +cat >>confdefs.h <<_ACEOF +#define SIZEOF_FPOS_T $ac_cv_sizeof_fpos_t +_ACEOF -# Sizes of various common basic types -# ANSI C requires sizeof(char) == 1, so no need to check it # The cast to long int works around a bug in the HP C Compiler # version HP92453-01 B.11.11.23709.GP, which incorrectly rejects # declarations like `int a3[[(sizeof (unsigned char)) >= 0]];'. # This bug is HP SR number 8606223364. -{ $as_echo "$as_me:$LINENO: checking size of int" >&5 -$as_echo_n "checking size of int... " >&6; } -if test "${ac_cv_sizeof_int+set}" = set; then +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking size of size_t" >&5 +$as_echo_n "checking size of size_t... " >&6; } +if test "${ac_cv_sizeof_size_t+set}" = set; then : $as_echo_n "(cached) " >&6 else - if test "$cross_compiling" = yes; then - # Depending upon the size, compute the lo and hi bounds. -cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -$ac_includes_default -int -main () -{ -static int test_array [1 - 2 * !(((long int) (sizeof (int))) >= 0)]; -test_array [0] = 0 + if ac_fn_c_compute_int "$LINENO" "(long int) (sizeof (size_t))" "ac_cv_sizeof_size_t" "$ac_includes_default"; then : - ; - return 0; -} -_ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" -$as_echo "$ac_try_echo") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - ac_lo=0 ac_mid=0 - while :; do - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -$ac_includes_default -int -main () -{ -static int test_array [1 - 2 * !(((long int) (sizeof (int))) <= $ac_mid)]; -test_array [0] = 0 +else + if test "$ac_cv_type_size_t" = yes; then + { { $as_echo "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5 +$as_echo "$as_me: error: in \`$ac_pwd':" >&2;} +{ as_fn_set_status 77 +as_fn_error "cannot compute sizeof (size_t) +See \`config.log' for more details." "$LINENO" 5; }; } + else + ac_cv_sizeof_size_t=0 + fi +fi - ; - return 0; -} +fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_sizeof_size_t" >&5 +$as_echo "$ac_cv_sizeof_size_t" >&6; } + + + +cat >>confdefs.h <<_ACEOF +#define SIZEOF_SIZE_T $ac_cv_sizeof_size_t _ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" -$as_echo "$ac_try_echo") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - ac_hi=$ac_mid; break + + +# The cast to long int works around a bug in the HP C Compiler +# version HP92453-01 B.11.11.23709.GP, which incorrectly rejects +# declarations like `int a3[[(sizeof (unsigned char)) >= 0]];'. +# This bug is HP SR number 8606223364. +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking size of pid_t" >&5 +$as_echo_n "checking size of pid_t... " >&6; } +if test "${ac_cv_sizeof_pid_t+set}" = set; then : + $as_echo_n "(cached) " >&6 else - $as_echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 + if ac_fn_c_compute_int "$LINENO" "(long int) (sizeof (pid_t))" "ac_cv_sizeof_pid_t" "$ac_includes_default"; then : - ac_lo=`expr $ac_mid + 1` - if test $ac_lo -le $ac_mid; then - ac_lo= ac_hi= - break - fi - ac_mid=`expr 2 '*' $ac_mid + 1` +else + if test "$ac_cv_type_pid_t" = yes; then + { { $as_echo "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5 +$as_echo "$as_me: error: in \`$ac_pwd':" >&2;} +{ as_fn_set_status 77 +as_fn_error "cannot compute sizeof (pid_t) +See \`config.log' for more details." "$LINENO" 5; }; } + else + ac_cv_sizeof_pid_t=0 + fi fi -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext - done -else - $as_echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 +fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_sizeof_pid_t" >&5 +$as_echo "$ac_cv_sizeof_pid_t" >&6; } - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -$ac_includes_default -int -main () -{ -static int test_array [1 - 2 * !(((long int) (sizeof (int))) < 0)]; -test_array [0] = 0 - ; - return 0; -} -_ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" -$as_echo "$ac_try_echo") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - ac_hi=-1 ac_mid=-1 - while :; do - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ + +cat >>confdefs.h <<_ACEOF +#define SIZEOF_PID_T $ac_cv_sizeof_pid_t _ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF + + + +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for long long support" >&5 +$as_echo_n "checking for long long support... " >&6; } +have_long_long=no +cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ -$ac_includes_default + int main () { -static int test_array [1 - 2 * !(((long int) (sizeof (int))) >= $ac_mid)]; -test_array [0] = 0 - +long long x; x = (long long)0; ; return 0; } _ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" -$as_echo "$ac_try_echo") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - ac_lo=$ac_mid; break -else - $as_echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 +if ac_fn_c_try_compile "$LINENO"; then : - ac_hi=`expr '(' $ac_mid ')' - 1` - if test $ac_mid -le $ac_hi; then - ac_lo= ac_hi= - break - fi - ac_mid=`expr 2 '*' $ac_mid` -fi +$as_echo "#define HAVE_LONG_LONG 1" >>confdefs.h + + have_long_long=yes + +fi rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext - done +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $have_long_long" >&5 +$as_echo "$have_long_long" >&6; } +if test "$have_long_long" = yes ; then +# The cast to long int works around a bug in the HP C Compiler +# version HP92453-01 B.11.11.23709.GP, which incorrectly rejects +# declarations like `int a3[[(sizeof (unsigned char)) >= 0]];'. +# This bug is HP SR number 8606223364. +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking size of long long" >&5 +$as_echo_n "checking size of long long... " >&6; } +if test "${ac_cv_sizeof_long_long+set}" = set; then : + $as_echo_n "(cached) " >&6 else - $as_echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 + if ac_fn_c_compute_int "$LINENO" "(long int) (sizeof (long long))" "ac_cv_sizeof_long_long" "$ac_includes_default"; then : - ac_lo= ac_hi= +else + if test "$ac_cv_type_long_long" = yes; then + { { $as_echo "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5 +$as_echo "$as_me: error: in \`$ac_pwd':" >&2;} +{ as_fn_set_status 77 +as_fn_error "cannot compute sizeof (long long) +See \`config.log' for more details." "$LINENO" 5; }; } + else + ac_cv_sizeof_long_long=0 + fi fi -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_sizeof_long_long" >&5 +$as_echo "$ac_cv_sizeof_long_long" >&6; } -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext -# Binary search between lo and hi bounds. -while test "x$ac_lo" != "x$ac_hi"; do - ac_mid=`expr '(' $ac_hi - $ac_lo ')' / 2 + $ac_lo` - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ + + +cat >>confdefs.h <<_ACEOF +#define SIZEOF_LONG_LONG $ac_cv_sizeof_long_long _ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF + + +fi + +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for long double support" >&5 +$as_echo_n "checking for long double support... " >&6; } +have_long_double=no +cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ -$ac_includes_default + int main () { -static int test_array [1 - 2 * !(((long int) (sizeof (int))) <= $ac_mid)]; -test_array [0] = 0 - +long double x; x = (long double)0.; ; return 0; } _ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" -$as_echo "$ac_try_echo") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - ac_hi=$ac_mid -else - $as_echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 +if ac_fn_c_try_compile "$LINENO"; then : - ac_lo=`expr '(' $ac_mid ')' + 1` -fi +$as_echo "#define HAVE_LONG_DOUBLE 1" >>confdefs.h + + have_long_double=yes + +fi rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext -done -case $ac_lo in -?*) ac_cv_sizeof_int=$ac_lo;; -'') if test "$ac_cv_type_int" = yes; then - { { $as_echo "$as_me:$LINENO: error: in \`$ac_pwd':" >&5 +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $have_long_double" >&5 +$as_echo "$have_long_double" >&6; } +if test "$have_long_double" = yes ; then +# The cast to long int works around a bug in the HP C Compiler +# version HP92453-01 B.11.11.23709.GP, which incorrectly rejects +# declarations like `int a3[[(sizeof (unsigned char)) >= 0]];'. +# This bug is HP SR number 8606223364. +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking size of long double" >&5 +$as_echo_n "checking size of long double... " >&6; } +if test "${ac_cv_sizeof_long_double+set}" = set; then : + $as_echo_n "(cached) " >&6 +else + if ac_fn_c_compute_int "$LINENO" "(long int) (sizeof (long double))" "ac_cv_sizeof_long_double" "$ac_includes_default"; then : + +else + if test "$ac_cv_type_long_double" = yes; then + { { $as_echo "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5 $as_echo "$as_me: error: in \`$ac_pwd':" >&2;} -{ { $as_echo "$as_me:$LINENO: error: cannot compute sizeof (int) -See \`config.log' for more details." >&5 -$as_echo "$as_me: error: cannot compute sizeof (int) -See \`config.log' for more details." >&2;} - { (exit 77); exit 77; }; }; } +{ as_fn_set_status 77 +as_fn_error "cannot compute sizeof (long double) +See \`config.log' for more details." "$LINENO" 5; }; } else - ac_cv_sizeof_int=0 - fi ;; -esac -else - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ + ac_cv_sizeof_long_double=0 + fi +fi + +fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_sizeof_long_double" >&5 +$as_echo "$ac_cv_sizeof_long_double" >&6; } + + + +cat >>confdefs.h <<_ACEOF +#define SIZEOF_LONG_DOUBLE $ac_cv_sizeof_long_double _ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF + + +fi + +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for _Bool support" >&5 +$as_echo_n "checking for _Bool support... " >&6; } +have_c99_bool=no +cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ -$ac_includes_default -static long int longval () { return (long int) (sizeof (int)); } -static unsigned long int ulongval () { return (long int) (sizeof (int)); } -#include -#include + int main () { - - FILE *f = fopen ("conftest.val", "w"); - if (! f) - return 1; - if (((long int) (sizeof (int))) < 0) - { - long int i = longval (); - if (i != ((long int) (sizeof (int)))) - return 1; - fprintf (f, "%ld", i); - } - else - { - unsigned long int i = ulongval (); - if (i != ((long int) (sizeof (int)))) - return 1; - fprintf (f, "%lu", i); - } - /* Do not output a trailing newline, as this causes \r\n confusion - on some platforms. */ - return ferror (f) || fclose (f) != 0; - +_Bool x; x = (_Bool)0; ; return 0; } _ACEOF -rm -f conftest$ac_exeext -if { (ac_try="$ac_link" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" -$as_echo "$ac_try_echo") >&5 - (eval "$ac_link") 2>&5 - ac_status=$? - $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { ac_try='./conftest$ac_exeext' - { (case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" -$as_echo "$ac_try_echo") >&5 - (eval "$ac_try") 2>&5 - ac_status=$? - $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); }; }; then - ac_cv_sizeof_int=`cat conftest.val` +if ac_fn_c_try_compile "$LINENO"; then : + + +$as_echo "#define HAVE_C99_BOOL 1" >>confdefs.h + + have_c99_bool=yes + +fi +rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $have_c99_bool" >&5 +$as_echo "$have_c99_bool" >&6; } +if test "$have_c99_bool" = yes ; then +# The cast to long int works around a bug in the HP C Compiler +# version HP92453-01 B.11.11.23709.GP, which incorrectly rejects +# declarations like `int a3[[(sizeof (unsigned char)) >= 0]];'. +# This bug is HP SR number 8606223364. +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking size of _Bool" >&5 +$as_echo_n "checking size of _Bool... " >&6; } +if test "${ac_cv_sizeof__Bool+set}" = set; then : + $as_echo_n "(cached) " >&6 else - $as_echo "$as_me: program exited with status $ac_status" >&5 -$as_echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 + if ac_fn_c_compute_int "$LINENO" "(long int) (sizeof (_Bool))" "ac_cv_sizeof__Bool" "$ac_includes_default"; then : -( exit $ac_status ) -if test "$ac_cv_type_int" = yes; then - { { $as_echo "$as_me:$LINENO: error: in \`$ac_pwd':" >&5 +else + if test "$ac_cv_type__Bool" = yes; then + { { $as_echo "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5 $as_echo "$as_me: error: in \`$ac_pwd':" >&2;} -{ { $as_echo "$as_me:$LINENO: error: cannot compute sizeof (int) -See \`config.log' for more details." >&5 -$as_echo "$as_me: error: cannot compute sizeof (int) -See \`config.log' for more details." >&2;} - { (exit 77); exit 77; }; }; } +{ as_fn_set_status 77 +as_fn_error "cannot compute sizeof (_Bool) +See \`config.log' for more details." "$LINENO" 5; }; } else - ac_cv_sizeof_int=0 + ac_cv_sizeof__Bool=0 fi fi -rm -rf conftest.dSYM -rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext conftest.$ac_objext conftest.$ac_ext -fi -rm -f conftest.val + fi -{ $as_echo "$as_me:$LINENO: result: $ac_cv_sizeof_int" >&5 -$as_echo "$ac_cv_sizeof_int" >&6; } +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_sizeof__Bool" >&5 +$as_echo "$ac_cv_sizeof__Bool" >&6; } cat >>confdefs.h <<_ACEOF -#define SIZEOF_INT $ac_cv_sizeof_int +#define SIZEOF__BOOL $ac_cv_sizeof__Bool _ACEOF +fi + +ac_fn_c_check_type "$LINENO" "uintptr_t" "ac_cv_type_uintptr_t" "#ifdef HAVE_STDINT_H + #include + #endif +" +if test "x$ac_cv_type_uintptr_t" = x""yes; then : + +cat >>confdefs.h <<_ACEOF +#define HAVE_UINTPTR_T 1 +_ACEOF + # The cast to long int works around a bug in the HP C Compiler # version HP92453-01 B.11.11.23709.GP, which incorrectly rejects # declarations like `int a3[[(sizeof (unsigned char)) >= 0]];'. # This bug is HP SR number 8606223364. -{ $as_echo "$as_me:$LINENO: checking size of long" >&5 -$as_echo_n "checking size of long... " >&6; } -if test "${ac_cv_sizeof_long+set}" = set; then +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking size of uintptr_t" >&5 +$as_echo_n "checking size of uintptr_t... " >&6; } +if test "${ac_cv_sizeof_uintptr_t+set}" = set; then : $as_echo_n "(cached) " >&6 else - if test "$cross_compiling" = yes; then - # Depending upon the size, compute the lo and hi bounds. -cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -$ac_includes_default -int -main () -{ -static int test_array [1 - 2 * !(((long int) (sizeof (long))) >= 0)]; -test_array [0] = 0 + if ac_fn_c_compute_int "$LINENO" "(long int) (sizeof (uintptr_t))" "ac_cv_sizeof_uintptr_t" "$ac_includes_default"; then : - ; - return 0; -} -_ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" -$as_echo "$ac_try_echo") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - ac_lo=0 ac_mid=0 - while :; do - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -$ac_includes_default -int -main () -{ -static int test_array [1 - 2 * !(((long int) (sizeof (long))) <= $ac_mid)]; -test_array [0] = 0 - - ; - return 0; -} -_ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" -$as_echo "$ac_try_echo") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - ac_hi=$ac_mid; break else - $as_echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 + if test "$ac_cv_type_uintptr_t" = yes; then + { { $as_echo "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5 +$as_echo "$as_me: error: in \`$ac_pwd':" >&2;} +{ as_fn_set_status 77 +as_fn_error "cannot compute sizeof (uintptr_t) +See \`config.log' for more details." "$LINENO" 5; }; } + else + ac_cv_sizeof_uintptr_t=0 + fi +fi - ac_lo=`expr $ac_mid + 1` - if test $ac_lo -le $ac_mid; then - ac_lo= ac_hi= - break - fi - ac_mid=`expr 2 '*' $ac_mid + 1` fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_sizeof_uintptr_t" >&5 +$as_echo "$ac_cv_sizeof_uintptr_t" >&6; } -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext - done -else - $as_echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -$ac_includes_default -int -main () -{ -static int test_array [1 - 2 * !(((long int) (sizeof (long))) < 0)]; -test_array [0] = 0 - ; - return 0; -} -_ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" -$as_echo "$ac_try_echo") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - ac_hi=-1 ac_mid=-1 - while :; do - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ +cat >>confdefs.h <<_ACEOF +#define SIZEOF_UINTPTR_T $ac_cv_sizeof_uintptr_t _ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF + + +fi + + + +# Hmph. AC_CHECK_SIZEOF() doesn't include . +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking size of off_t" >&5 +$as_echo_n "checking size of off_t... " >&6; } +if test "${ac_cv_sizeof_off_t+set}" = set; then : + $as_echo_n "(cached) " >&6 +else + if test "$cross_compiling" = yes; then : + ac_cv_sizeof_off_t=4 +else + cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ -$ac_includes_default -int -main () +#include +#include +main() { -static int test_array [1 - 2 * !(((long int) (sizeof (long))) >= $ac_mid)]; -test_array [0] = 0 - - ; - return 0; + FILE *f=fopen("conftestval", "w"); + if (!f) exit(1); + fprintf(f, "%d\n", sizeof(off_t)); + exit(0); } _ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" -$as_echo "$ac_try_echo") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - ac_lo=$ac_mid; break +if ac_fn_c_try_run "$LINENO"; then : + ac_cv_sizeof_off_t=`cat conftestval` else - $as_echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - ac_hi=`expr '(' $ac_mid ')' - 1` - if test $ac_mid -le $ac_hi; then - ac_lo= ac_hi= - break - fi - ac_mid=`expr 2 '*' $ac_mid` + ac_cv_sizeof_off_t=0 +fi +rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext \ + conftest.$ac_objext conftest.beam conftest.$ac_ext fi -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext - done -else - $as_echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - ac_lo= ac_hi= fi -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext -fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_sizeof_off_t" >&5 +$as_echo "$ac_cv_sizeof_off_t" >&6; } -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext -# Binary search between lo and hi bounds. -while test "x$ac_lo" != "x$ac_hi"; do - ac_mid=`expr '(' $ac_hi - $ac_lo ')' / 2 + $ac_lo` - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ +cat >>confdefs.h <<_ACEOF +#define SIZEOF_OFF_T $ac_cv_sizeof_off_t _ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -$ac_includes_default -int -main () -{ -static int test_array [1 - 2 * !(((long int) (sizeof (long))) <= $ac_mid)]; -test_array [0] = 0 - ; - return 0; -} -_ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" -$as_echo "$ac_try_echo") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - ac_hi=$ac_mid -else - $as_echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - ac_lo=`expr '(' $ac_mid ')' + 1` +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking whether to enable large file support" >&5 +$as_echo_n "checking whether to enable large file support... " >&6; } +if test "$have_long_long" = yes +then +if test "$ac_cv_sizeof_off_t" -gt "$ac_cv_sizeof_long" -a \ + "$ac_cv_sizeof_long_long" -ge "$ac_cv_sizeof_off_t"; then + +$as_echo "#define HAVE_LARGEFILE_SUPPORT 1" >>confdefs.h + + { $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +$as_echo "yes" >&6; } +else + { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 +$as_echo "no" >&6; } +fi +else + { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 +$as_echo "no" >&6; } fi -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext -done -case $ac_lo in -?*) ac_cv_sizeof_long=$ac_lo;; -'') if test "$ac_cv_type_long" = yes; then - { { $as_echo "$as_me:$LINENO: error: in \`$ac_pwd':" >&5 -$as_echo "$as_me: error: in \`$ac_pwd':" >&2;} -{ { $as_echo "$as_me:$LINENO: error: cannot compute sizeof (long) -See \`config.log' for more details." >&5 -$as_echo "$as_me: error: cannot compute sizeof (long) -See \`config.log' for more details." >&2;} - { (exit 77); exit 77; }; }; } - else - ac_cv_sizeof_long=0 - fi ;; -esac +# AC_CHECK_SIZEOF() doesn't include . +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking size of time_t" >&5 +$as_echo_n "checking size of time_t... " >&6; } +if test "${ac_cv_sizeof_time_t+set}" = set; then : + $as_echo_n "(cached) " >&6 else - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF + if test "$cross_compiling" = yes; then : + ac_cv_sizeof_time_t=4 +else + cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ -$ac_includes_default -static long int longval () { return (long int) (sizeof (long)); } -static unsigned long int ulongval () { return (long int) (sizeof (long)); } #include -#include -int -main () +#include +main() { - - FILE *f = fopen ("conftest.val", "w"); - if (! f) - return 1; - if (((long int) (sizeof (long))) < 0) - { - long int i = longval (); - if (i != ((long int) (sizeof (long)))) - return 1; - fprintf (f, "%ld", i); - } - else - { - unsigned long int i = ulongval (); - if (i != ((long int) (sizeof (long)))) - return 1; - fprintf (f, "%lu", i); - } - /* Do not output a trailing newline, as this causes \r\n confusion - on some platforms. */ - return ferror (f) || fclose (f) != 0; - - ; - return 0; + FILE *f=fopen("conftestval", "w"); + if (!f) exit(1); + fprintf(f, "%d\n", sizeof(time_t)); + exit(0); } _ACEOF -rm -f conftest$ac_exeext -if { (ac_try="$ac_link" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" -$as_echo "$ac_try_echo") >&5 - (eval "$ac_link") 2>&5 - ac_status=$? - $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { ac_try='./conftest$ac_exeext' - { (case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" -$as_echo "$ac_try_echo") >&5 - (eval "$ac_try") 2>&5 - ac_status=$? - $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); }; }; then - ac_cv_sizeof_long=`cat conftest.val` +if ac_fn_c_try_run "$LINENO"; then : + ac_cv_sizeof_time_t=`cat conftestval` else - $as_echo "$as_me: program exited with status $ac_status" >&5 -$as_echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - -( exit $ac_status ) -if test "$ac_cv_type_long" = yes; then - { { $as_echo "$as_me:$LINENO: error: in \`$ac_pwd':" >&5 -$as_echo "$as_me: error: in \`$ac_pwd':" >&2;} -{ { $as_echo "$as_me:$LINENO: error: cannot compute sizeof (long) -See \`config.log' for more details." >&5 -$as_echo "$as_me: error: cannot compute sizeof (long) -See \`config.log' for more details." >&2;} - { (exit 77); exit 77; }; }; } - else - ac_cv_sizeof_long=0 - fi -fi -rm -rf conftest.dSYM -rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext conftest.$ac_objext conftest.$ac_ext + ac_cv_sizeof_time_t=0 fi -rm -f conftest.val +rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext \ + conftest.$ac_objext conftest.beam conftest.$ac_ext fi -{ $as_echo "$as_me:$LINENO: result: $ac_cv_sizeof_long" >&5 -$as_echo "$ac_cv_sizeof_long" >&6; } +fi + +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_sizeof_time_t" >&5 +$as_echo "$ac_cv_sizeof_time_t" >&6; } cat >>confdefs.h <<_ACEOF -#define SIZEOF_LONG $ac_cv_sizeof_long +#define SIZEOF_TIME_T $ac_cv_sizeof_time_t _ACEOF -# The cast to long int works around a bug in the HP C Compiler -# version HP92453-01 B.11.11.23709.GP, which incorrectly rejects -# declarations like `int a3[[(sizeof (unsigned char)) >= 0]];'. -# This bug is HP SR number 8606223364. -{ $as_echo "$as_me:$LINENO: checking size of void *" >&5 -$as_echo_n "checking size of void *... " >&6; } -if test "${ac_cv_sizeof_void_p+set}" = set; then - $as_echo_n "(cached) " >&6 -else - if test "$cross_compiling" = yes; then - # Depending upon the size, compute the lo and hi bounds. -cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -$ac_includes_default -int -main () -{ -static int test_array [1 - 2 * !(((long int) (sizeof (void *))) >= 0)]; -test_array [0] = 0 - ; - return 0; -} -_ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" -$as_echo "$ac_try_echo") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - ac_lo=0 ac_mid=0 - while :; do - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF +# if have pthread_t then define SIZEOF_PTHREAD_T +ac_save_cc="$CC" +if test "$ac_cv_kpthread" = "yes" +then CC="$CC -Kpthread" +elif test "$ac_cv_kthread" = "yes" +then CC="$CC -Kthread" +elif test "$ac_cv_pthread" = "yes" +then CC="$CC -pthread" +fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for pthread_t" >&5 +$as_echo_n "checking for pthread_t... " >&6; } +have_pthread_t=no +cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ -$ac_includes_default +#include int main () { -static int test_array [1 - 2 * !(((long int) (sizeof (void *))) <= $ac_mid)]; -test_array [0] = 0 - +pthread_t x; x = *(pthread_t*)0; ; return 0; } _ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" -$as_echo "$ac_try_echo") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - ac_hi=$ac_mid; break -else - $as_echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - ac_lo=`expr $ac_mid + 1` - if test $ac_lo -le $ac_mid; then - ac_lo= ac_hi= - break - fi - ac_mid=`expr 2 '*' $ac_mid + 1` +if ac_fn_c_try_compile "$LINENO"; then : + have_pthread_t=yes fi - rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext - done +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $have_pthread_t" >&5 +$as_echo "$have_pthread_t" >&6; } +if test "$have_pthread_t" = yes ; then + # AC_CHECK_SIZEOF() doesn't include . + { $as_echo "$as_me:${as_lineno-$LINENO}: checking size of pthread_t" >&5 +$as_echo_n "checking size of pthread_t... " >&6; } + if test "${ac_cv_sizeof_pthread_t+set}" = set; then : + $as_echo_n "(cached) " >&6 else - $as_echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -$ac_includes_default -int -main () -{ -static int test_array [1 - 2 * !(((long int) (sizeof (void *))) < 0)]; -test_array [0] = 0 - - ; - return 0; -} -_ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" -$as_echo "$ac_try_echo") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - ac_hi=-1 ac_mid=-1 - while :; do - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF + if test "$cross_compiling" = yes; then : + ac_cv_sizeof_pthread_t=4 +else + cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ -$ac_includes_default -int -main () -{ -static int test_array [1 - 2 * !(((long int) (sizeof (void *))) >= $ac_mid)]; -test_array [0] = 0 - - ; - return 0; -} +#include +#include + main() + { + FILE *f=fopen("conftestval", "w"); + if (!f) exit(1); + fprintf(f, "%d\n", sizeof(pthread_t)); + exit(0); + } _ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" -$as_echo "$ac_try_echo") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - ac_lo=$ac_mid; break +if ac_fn_c_try_run "$LINENO"; then : + ac_cv_sizeof_pthread_t=`cat conftestval` else - $as_echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - ac_hi=`expr '(' $ac_mid ')' - 1` - if test $ac_mid -le $ac_hi; then - ac_lo= ac_hi= - break - fi - ac_mid=`expr 2 '*' $ac_mid` + ac_cv_sizeof_pthread_t=0 +fi +rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext \ + conftest.$ac_objext conftest.beam conftest.$ac_ext fi -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext - done -else - $as_echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - ac_lo= ac_hi= fi -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext -fi + { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_sizeof_pthread_t" >&5 +$as_echo "$ac_cv_sizeof_pthread_t" >&6; } -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext -# Binary search between lo and hi bounds. -while test "x$ac_lo" != "x$ac_hi"; do - ac_mid=`expr '(' $ac_hi - $ac_lo ')' / 2 + $ac_lo` - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ +cat >>confdefs.h <<_ACEOF +#define SIZEOF_PTHREAD_T $ac_cv_sizeof_pthread_t _ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -$ac_includes_default -int -main () -{ -static int test_array [1 - 2 * !(((long int) (sizeof (void *))) <= $ac_mid)]; -test_array [0] = 0 - ; - return 0; -} -_ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" -$as_echo "$ac_try_echo") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - ac_hi=$ac_mid -else - $as_echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 +fi +CC="$ac_save_cc" - ac_lo=`expr '(' $ac_mid ')' + 1` +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for --enable-toolbox-glue" >&5 +$as_echo_n "checking for --enable-toolbox-glue... " >&6; } +# Check whether --enable-toolbox-glue was given. +if test "${enable_toolbox_glue+set}" = set; then : + enableval=$enable_toolbox_glue; fi -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext -done -case $ac_lo in -?*) ac_cv_sizeof_void_p=$ac_lo;; -'') if test "$ac_cv_type_void_p" = yes; then - { { $as_echo "$as_me:$LINENO: error: in \`$ac_pwd':" >&5 -$as_echo "$as_me: error: in \`$ac_pwd':" >&2;} -{ { $as_echo "$as_me:$LINENO: error: cannot compute sizeof (void *) -See \`config.log' for more details." >&5 -$as_echo "$as_me: error: cannot compute sizeof (void *) -See \`config.log' for more details." >&2;} - { (exit 77); exit 77; }; }; } - else - ac_cv_sizeof_void_p=0 - fi ;; + +if test -z "$enable_toolbox_glue" +then + case $ac_sys_system/$ac_sys_release in + Darwin/*) + enable_toolbox_glue="yes";; + *) + enable_toolbox_glue="no";; + esac +fi +case "$enable_toolbox_glue" in +yes) + extra_machdep_objs="Python/mactoolboxglue.o" + extra_undefs="-u _PyMac_Error" + +$as_echo "#define USE_TOOLBOX_OBJECT_GLUE 1" >>confdefs.h + + ;; +*) + extra_machdep_objs="" + extra_undefs="" + ;; +esac +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $enable_toolbox_glue" >&5 +$as_echo "$enable_toolbox_glue" >&6; } + + + +case $ac_sys_system/$ac_sys_release in + Darwin/[01567]\..*) + OTHER_LIBTOOL_OPT="-prebind -seg1addr 0x10000000" + ;; + Darwin/*) + OTHER_LIBTOOL_OPT="" + ;; esac + + +ARCH_RUN_32BIT="" + +case $ac_sys_system/$ac_sys_release in + Darwin/[01567]\..*) + LIBTOOL_CRUFT="-framework System -lcc_dynamic" + if test "${enable_universalsdk}"; then + : + else + LIBTOOL_CRUFT="${LIBTOOL_CRUFT} -arch_only `/usr/bin/arch`" + fi + LIBTOOL_CRUFT=$LIBTOOL_CRUFT' -install_name $(PYTHONFRAMEWORKINSTALLDIR)/Versions/$(VERSION)/$(PYTHONFRAMEWORK)' + LIBTOOL_CRUFT=$LIBTOOL_CRUFT' -compatibility_version $(VERSION) -current_version $(VERSION)';; + Darwin/*) + gcc_version=`gcc -dumpversion` + if test ${gcc_version} '<' 4.0 + then + LIBTOOL_CRUFT="-lcc_dynamic" + else + LIBTOOL_CRUFT="" + fi + if test "$cross_compiling" = yes; then : + ac_osx_32bit=yes else - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF + cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ -$ac_includes_default -static long int longval () { return (long int) (sizeof (void *)); } -static unsigned long int ulongval () { return (long int) (sizeof (void *)); } -#include -#include -int -main () -{ - FILE *f = fopen ("conftest.val", "w"); - if (! f) - return 1; - if (((long int) (sizeof (void *))) < 0) - { - long int i = longval (); - if (i != ((long int) (sizeof (void *)))) - return 1; - fprintf (f, "%ld", i); - } - else + #include + int main(int argc, char*argv[]) { - unsigned long int i = ulongval (); - if (i != ((long int) (sizeof (void *)))) - return 1; - fprintf (f, "%lu", i); + if (sizeof(long) == 4) { + return 0; + } else { + return 1; + } } - /* Do not output a trailing newline, as this causes \r\n confusion - on some platforms. */ - return ferror (f) || fclose (f) != 0; - ; - return 0; -} _ACEOF -rm -f conftest$ac_exeext -if { (ac_try="$ac_link" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" -$as_echo "$ac_try_echo") >&5 - (eval "$ac_link") 2>&5 - ac_status=$? - $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { ac_try='./conftest$ac_exeext' - { (case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" -$as_echo "$ac_try_echo") >&5 - (eval "$ac_try") 2>&5 - ac_status=$? - $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); }; }; then - ac_cv_sizeof_void_p=`cat conftest.val` +if ac_fn_c_try_run "$LINENO"; then : + ac_osx_32bit=yes else - $as_echo "$as_me: program exited with status $ac_status" >&5 -$as_echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - -( exit $ac_status ) -if test "$ac_cv_type_void_p" = yes; then - { { $as_echo "$as_me:$LINENO: error: in \`$ac_pwd':" >&5 -$as_echo "$as_me: error: in \`$ac_pwd':" >&2;} -{ { $as_echo "$as_me:$LINENO: error: cannot compute sizeof (void *) -See \`config.log' for more details." >&5 -$as_echo "$as_me: error: cannot compute sizeof (void *) -See \`config.log' for more details." >&2;} - { (exit 77); exit 77; }; }; } - else - ac_cv_sizeof_void_p=0 - fi + ac_osx_32bit=no fi -rm -rf conftest.dSYM -rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext conftest.$ac_objext conftest.$ac_ext +rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext \ + conftest.$ac_objext conftest.beam conftest.$ac_ext fi -rm -f conftest.val -fi -{ $as_echo "$as_me:$LINENO: result: $ac_cv_sizeof_void_p" >&5 -$as_echo "$ac_cv_sizeof_void_p" >&6; } + if test "${ac_osx_32bit}" = "yes"; then + case `/usr/bin/arch` in + i386) + MACOSX_DEFAULT_ARCH="i386" + ;; + ppc) + MACOSX_DEFAULT_ARCH="ppc" + ;; + *) + as_fn_error "Unexpected output of 'arch' on OSX" "$LINENO" 5 + ;; + esac + else + case `/usr/bin/arch` in + i386) + MACOSX_DEFAULT_ARCH="x86_64" + ;; + ppc) + MACOSX_DEFAULT_ARCH="ppc64" + ;; + *) + as_fn_error "Unexpected output of 'arch' on OSX" "$LINENO" 5 + ;; + esac -cat >>confdefs.h <<_ACEOF -#define SIZEOF_VOID_P $ac_cv_sizeof_void_p -_ACEOF + #ARCH_RUN_32BIT="true" + fi + LIBTOOL_CRUFT=$LIBTOOL_CRUFT" -lSystem -lSystemStubs -arch_only ${MACOSX_DEFAULT_ARCH}" + LIBTOOL_CRUFT=$LIBTOOL_CRUFT' -install_name $(PYTHONFRAMEWORKINSTALLDIR)/Versions/$(VERSION)/$(PYTHONFRAMEWORK)' + LIBTOOL_CRUFT=$LIBTOOL_CRUFT' -compatibility_version $(VERSION) -current_version $(VERSION)';; +esac -# The cast to long int works around a bug in the HP C Compiler -# version HP92453-01 B.11.11.23709.GP, which incorrectly rejects -# declarations like `int a3[[(sizeof (unsigned char)) >= 0]];'. -# This bug is HP SR number 8606223364. -{ $as_echo "$as_me:$LINENO: checking size of short" >&5 -$as_echo_n "checking size of short... " >&6; } -if test "${ac_cv_sizeof_short+set}" = set; then - $as_echo_n "(cached) " >&6 +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for --enable-framework" >&5 +$as_echo_n "checking for --enable-framework... " >&6; } +if test "$enable_framework" +then + BASECFLAGS="$BASECFLAGS -fno-common -dynamic" + # -F. is needed to allow linking to the framework while + # in the build location. + +$as_echo "#define WITH_NEXT_FRAMEWORK 1" >>confdefs.h + + { $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +$as_echo "yes" >&6; } + if test $enable_shared = "yes" + then + as_fn_error "Specifying both --enable-shared and --enable-framework is not supported, use only --enable-framework instead. See Mac/README." "$LINENO" 5 + fi else - if test "$cross_compiling" = yes; then - # Depending upon the size, compute the lo and hi bounds. -cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -$ac_includes_default -int -main () -{ -static int test_array [1 - 2 * !(((long int) (sizeof (short))) >= 0)]; -test_array [0] = 0 + { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 +$as_echo "no" >&6; } +fi - ; - return 0; -} -_ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" -$as_echo "$ac_try_echo") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - ac_lo=0 ac_mid=0 - while :; do - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -$ac_includes_default -int -main () -{ -static int test_array [1 - 2 * !(((long int) (sizeof (short))) <= $ac_mid)]; -test_array [0] = 0 +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for dyld" >&5 +$as_echo_n "checking for dyld... " >&6; } +case $ac_sys_system/$ac_sys_release in + Darwin/*) - ; - return 0; -} -_ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; +$as_echo "#define WITH_DYLD 1" >>confdefs.h + + { $as_echo "$as_me:${as_lineno-$LINENO}: result: always on for Darwin" >&5 +$as_echo "always on for Darwin" >&6; } + ;; + *) + { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 +$as_echo "no" >&6; } + ;; esac -eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" -$as_echo "$ac_try_echo") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - ac_hi=$ac_mid; break -else - $as_echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - ac_lo=`expr $ac_mid + 1` - if test $ac_lo -le $ac_mid; then - ac_lo= ac_hi= - break - fi - ac_mid=`expr 2 '*' $ac_mid + 1` -fi +# Set info about shared libraries. -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext - done -else - $as_echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -$ac_includes_default -int -main () -{ -static int test_array [1 - 2 * !(((long int) (sizeof (short))) < 0)]; -test_array [0] = 0 - ; - return 0; -} -_ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" -$as_echo "$ac_try_echo") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - ac_hi=-1 ac_mid=-1 - while :; do - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -$ac_includes_default -int -main () -{ -static int test_array [1 - 2 * !(((long int) (sizeof (short))) >= $ac_mid)]; -test_array [0] = 0 - - ; - return 0; -} -_ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" -$as_echo "$ac_try_echo") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - ac_lo=$ac_mid; break -else - $as_echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - ac_hi=`expr '(' $ac_mid ')' - 1` - if test $ac_mid -le $ac_hi; then - ac_lo= ac_hi= - break - fi - ac_mid=`expr 2 '*' $ac_mid` -fi - -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext - done -else - $as_echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - ac_lo= ac_hi= -fi - -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext -fi - -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext -# Binary search between lo and hi bounds. -while test "x$ac_lo" != "x$ac_hi"; do - ac_mid=`expr '(' $ac_hi - $ac_lo ')' / 2 + $ac_lo` - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -$ac_includes_default -int -main () -{ -static int test_array [1 - 2 * !(((long int) (sizeof (short))) <= $ac_mid)]; -test_array [0] = 0 - - ; - return 0; -} -_ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" -$as_echo "$ac_try_echo") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - ac_hi=$ac_mid -else - $as_echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - ac_lo=`expr '(' $ac_mid ')' + 1` -fi - -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext -done -case $ac_lo in -?*) ac_cv_sizeof_short=$ac_lo;; -'') if test "$ac_cv_type_short" = yes; then - { { $as_echo "$as_me:$LINENO: error: in \`$ac_pwd':" >&5 -$as_echo "$as_me: error: in \`$ac_pwd':" >&2;} -{ { $as_echo "$as_me:$LINENO: error: cannot compute sizeof (short) -See \`config.log' for more details." >&5 -$as_echo "$as_me: error: cannot compute sizeof (short) -See \`config.log' for more details." >&2;} - { (exit 77); exit 77; }; }; } - else - ac_cv_sizeof_short=0 - fi ;; -esac -else - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -$ac_includes_default -static long int longval () { return (long int) (sizeof (short)); } -static unsigned long int ulongval () { return (long int) (sizeof (short)); } -#include -#include -int -main () -{ - - FILE *f = fopen ("conftest.val", "w"); - if (! f) - return 1; - if (((long int) (sizeof (short))) < 0) - { - long int i = longval (); - if (i != ((long int) (sizeof (short)))) - return 1; - fprintf (f, "%ld", i); - } - else - { - unsigned long int i = ulongval (); - if (i != ((long int) (sizeof (short)))) - return 1; - fprintf (f, "%lu", i); - } - /* Do not output a trailing newline, as this causes \r\n confusion - on some platforms. */ - return ferror (f) || fclose (f) != 0; - - ; - return 0; -} -_ACEOF -rm -f conftest$ac_exeext -if { (ac_try="$ac_link" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" -$as_echo "$ac_try_echo") >&5 - (eval "$ac_link") 2>&5 - ac_status=$? - $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { ac_try='./conftest$ac_exeext' - { (case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" -$as_echo "$ac_try_echo") >&5 - (eval "$ac_try") 2>&5 - ac_status=$? - $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); }; }; then - ac_cv_sizeof_short=`cat conftest.val` -else - $as_echo "$as_me: program exited with status $ac_status" >&5 -$as_echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - -( exit $ac_status ) -if test "$ac_cv_type_short" = yes; then - { { $as_echo "$as_me:$LINENO: error: in \`$ac_pwd':" >&5 -$as_echo "$as_me: error: in \`$ac_pwd':" >&2;} -{ { $as_echo "$as_me:$LINENO: error: cannot compute sizeof (short) -See \`config.log' for more details." >&5 -$as_echo "$as_me: error: cannot compute sizeof (short) -See \`config.log' for more details." >&2;} - { (exit 77); exit 77; }; }; } - else - ac_cv_sizeof_short=0 - fi -fi -rm -rf conftest.dSYM -rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext conftest.$ac_objext conftest.$ac_ext -fi -rm -f conftest.val -fi -{ $as_echo "$as_me:$LINENO: result: $ac_cv_sizeof_short" >&5 -$as_echo "$ac_cv_sizeof_short" >&6; } - - - -cat >>confdefs.h <<_ACEOF -#define SIZEOF_SHORT $ac_cv_sizeof_short -_ACEOF - - -# The cast to long int works around a bug in the HP C Compiler -# version HP92453-01 B.11.11.23709.GP, which incorrectly rejects -# declarations like `int a3[[(sizeof (unsigned char)) >= 0]];'. -# This bug is HP SR number 8606223364. -{ $as_echo "$as_me:$LINENO: checking size of float" >&5 -$as_echo_n "checking size of float... " >&6; } -if test "${ac_cv_sizeof_float+set}" = set; then - $as_echo_n "(cached) " >&6 -else - if test "$cross_compiling" = yes; then - # Depending upon the size, compute the lo and hi bounds. -cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -$ac_includes_default -int -main () -{ -static int test_array [1 - 2 * !(((long int) (sizeof (float))) >= 0)]; -test_array [0] = 0 - - ; - return 0; -} -_ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" -$as_echo "$ac_try_echo") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - ac_lo=0 ac_mid=0 - while :; do - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -$ac_includes_default -int -main () -{ -static int test_array [1 - 2 * !(((long int) (sizeof (float))) <= $ac_mid)]; -test_array [0] = 0 - - ; - return 0; -} -_ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" -$as_echo "$ac_try_echo") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - ac_hi=$ac_mid; break -else - $as_echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - ac_lo=`expr $ac_mid + 1` - if test $ac_lo -le $ac_mid; then - ac_lo= ac_hi= - break - fi - ac_mid=`expr 2 '*' $ac_mid + 1` -fi - -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext - done -else - $as_echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -$ac_includes_default -int -main () -{ -static int test_array [1 - 2 * !(((long int) (sizeof (float))) < 0)]; -test_array [0] = 0 - - ; - return 0; -} -_ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" -$as_echo "$ac_try_echo") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - ac_hi=-1 ac_mid=-1 - while :; do - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -$ac_includes_default -int -main () -{ -static int test_array [1 - 2 * !(((long int) (sizeof (float))) >= $ac_mid)]; -test_array [0] = 0 - - ; - return 0; -} -_ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" -$as_echo "$ac_try_echo") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - ac_lo=$ac_mid; break -else - $as_echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - ac_hi=`expr '(' $ac_mid ')' - 1` - if test $ac_mid -le $ac_hi; then - ac_lo= ac_hi= - break - fi - ac_mid=`expr 2 '*' $ac_mid` -fi - -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext - done -else - $as_echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - ac_lo= ac_hi= -fi - -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext -fi - -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext -# Binary search between lo and hi bounds. -while test "x$ac_lo" != "x$ac_hi"; do - ac_mid=`expr '(' $ac_hi - $ac_lo ')' / 2 + $ac_lo` - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -$ac_includes_default -int -main () -{ -static int test_array [1 - 2 * !(((long int) (sizeof (float))) <= $ac_mid)]; -test_array [0] = 0 - - ; - return 0; -} -_ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" -$as_echo "$ac_try_echo") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - ac_hi=$ac_mid -else - $as_echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - ac_lo=`expr '(' $ac_mid ')' + 1` -fi - -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext -done -case $ac_lo in -?*) ac_cv_sizeof_float=$ac_lo;; -'') if test "$ac_cv_type_float" = yes; then - { { $as_echo "$as_me:$LINENO: error: in \`$ac_pwd':" >&5 -$as_echo "$as_me: error: in \`$ac_pwd':" >&2;} -{ { $as_echo "$as_me:$LINENO: error: cannot compute sizeof (float) -See \`config.log' for more details." >&5 -$as_echo "$as_me: error: cannot compute sizeof (float) -See \`config.log' for more details." >&2;} - { (exit 77); exit 77; }; }; } - else - ac_cv_sizeof_float=0 - fi ;; -esac -else - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -$ac_includes_default -static long int longval () { return (long int) (sizeof (float)); } -static unsigned long int ulongval () { return (long int) (sizeof (float)); } -#include -#include -int -main () -{ - - FILE *f = fopen ("conftest.val", "w"); - if (! f) - return 1; - if (((long int) (sizeof (float))) < 0) - { - long int i = longval (); - if (i != ((long int) (sizeof (float)))) - return 1; - fprintf (f, "%ld", i); - } - else - { - unsigned long int i = ulongval (); - if (i != ((long int) (sizeof (float)))) - return 1; - fprintf (f, "%lu", i); - } - /* Do not output a trailing newline, as this causes \r\n confusion - on some platforms. */ - return ferror (f) || fclose (f) != 0; - - ; - return 0; -} -_ACEOF -rm -f conftest$ac_exeext -if { (ac_try="$ac_link" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" -$as_echo "$ac_try_echo") >&5 - (eval "$ac_link") 2>&5 - ac_status=$? - $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { ac_try='./conftest$ac_exeext' - { (case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" -$as_echo "$ac_try_echo") >&5 - (eval "$ac_try") 2>&5 - ac_status=$? - $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); }; }; then - ac_cv_sizeof_float=`cat conftest.val` -else - $as_echo "$as_me: program exited with status $ac_status" >&5 -$as_echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - -( exit $ac_status ) -if test "$ac_cv_type_float" = yes; then - { { $as_echo "$as_me:$LINENO: error: in \`$ac_pwd':" >&5 -$as_echo "$as_me: error: in \`$ac_pwd':" >&2;} -{ { $as_echo "$as_me:$LINENO: error: cannot compute sizeof (float) -See \`config.log' for more details." >&5 -$as_echo "$as_me: error: cannot compute sizeof (float) -See \`config.log' for more details." >&2;} - { (exit 77); exit 77; }; }; } - else - ac_cv_sizeof_float=0 - fi -fi -rm -rf conftest.dSYM -rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext conftest.$ac_objext conftest.$ac_ext -fi -rm -f conftest.val -fi -{ $as_echo "$as_me:$LINENO: result: $ac_cv_sizeof_float" >&5 -$as_echo "$ac_cv_sizeof_float" >&6; } - - - -cat >>confdefs.h <<_ACEOF -#define SIZEOF_FLOAT $ac_cv_sizeof_float -_ACEOF - - -# The cast to long int works around a bug in the HP C Compiler -# version HP92453-01 B.11.11.23709.GP, which incorrectly rejects -# declarations like `int a3[[(sizeof (unsigned char)) >= 0]];'. -# This bug is HP SR number 8606223364. -{ $as_echo "$as_me:$LINENO: checking size of double" >&5 -$as_echo_n "checking size of double... " >&6; } -if test "${ac_cv_sizeof_double+set}" = set; then - $as_echo_n "(cached) " >&6 -else - if test "$cross_compiling" = yes; then - # Depending upon the size, compute the lo and hi bounds. -cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -$ac_includes_default -int -main () -{ -static int test_array [1 - 2 * !(((long int) (sizeof (double))) >= 0)]; -test_array [0] = 0 - - ; - return 0; -} -_ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" -$as_echo "$ac_try_echo") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - ac_lo=0 ac_mid=0 - while :; do - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -$ac_includes_default -int -main () -{ -static int test_array [1 - 2 * !(((long int) (sizeof (double))) <= $ac_mid)]; -test_array [0] = 0 - - ; - return 0; -} -_ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" -$as_echo "$ac_try_echo") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - ac_hi=$ac_mid; break -else - $as_echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - ac_lo=`expr $ac_mid + 1` - if test $ac_lo -le $ac_mid; then - ac_lo= ac_hi= - break - fi - ac_mid=`expr 2 '*' $ac_mid + 1` -fi - -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext - done -else - $as_echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -$ac_includes_default -int -main () -{ -static int test_array [1 - 2 * !(((long int) (sizeof (double))) < 0)]; -test_array [0] = 0 - - ; - return 0; -} -_ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" -$as_echo "$ac_try_echo") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - ac_hi=-1 ac_mid=-1 - while :; do - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -$ac_includes_default -int -main () -{ -static int test_array [1 - 2 * !(((long int) (sizeof (double))) >= $ac_mid)]; -test_array [0] = 0 - - ; - return 0; -} -_ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" -$as_echo "$ac_try_echo") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - ac_lo=$ac_mid; break -else - $as_echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - ac_hi=`expr '(' $ac_mid ')' - 1` - if test $ac_mid -le $ac_hi; then - ac_lo= ac_hi= - break - fi - ac_mid=`expr 2 '*' $ac_mid` -fi - -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext - done -else - $as_echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - ac_lo= ac_hi= -fi - -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext -fi - -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext -# Binary search between lo and hi bounds. -while test "x$ac_lo" != "x$ac_hi"; do - ac_mid=`expr '(' $ac_hi - $ac_lo ')' / 2 + $ac_lo` - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -$ac_includes_default -int -main () -{ -static int test_array [1 - 2 * !(((long int) (sizeof (double))) <= $ac_mid)]; -test_array [0] = 0 - - ; - return 0; -} -_ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" -$as_echo "$ac_try_echo") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - ac_hi=$ac_mid -else - $as_echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - ac_lo=`expr '(' $ac_mid ')' + 1` -fi - -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext -done -case $ac_lo in -?*) ac_cv_sizeof_double=$ac_lo;; -'') if test "$ac_cv_type_double" = yes; then - { { $as_echo "$as_me:$LINENO: error: in \`$ac_pwd':" >&5 -$as_echo "$as_me: error: in \`$ac_pwd':" >&2;} -{ { $as_echo "$as_me:$LINENO: error: cannot compute sizeof (double) -See \`config.log' for more details." >&5 -$as_echo "$as_me: error: cannot compute sizeof (double) -See \`config.log' for more details." >&2;} - { (exit 77); exit 77; }; }; } - else - ac_cv_sizeof_double=0 - fi ;; -esac -else - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -$ac_includes_default -static long int longval () { return (long int) (sizeof (double)); } -static unsigned long int ulongval () { return (long int) (sizeof (double)); } -#include -#include -int -main () -{ - - FILE *f = fopen ("conftest.val", "w"); - if (! f) - return 1; - if (((long int) (sizeof (double))) < 0) - { - long int i = longval (); - if (i != ((long int) (sizeof (double)))) - return 1; - fprintf (f, "%ld", i); - } - else - { - unsigned long int i = ulongval (); - if (i != ((long int) (sizeof (double)))) - return 1; - fprintf (f, "%lu", i); - } - /* Do not output a trailing newline, as this causes \r\n confusion - on some platforms. */ - return ferror (f) || fclose (f) != 0; - - ; - return 0; -} -_ACEOF -rm -f conftest$ac_exeext -if { (ac_try="$ac_link" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" -$as_echo "$ac_try_echo") >&5 - (eval "$ac_link") 2>&5 - ac_status=$? - $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { ac_try='./conftest$ac_exeext' - { (case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" -$as_echo "$ac_try_echo") >&5 - (eval "$ac_try") 2>&5 - ac_status=$? - $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); }; }; then - ac_cv_sizeof_double=`cat conftest.val` -else - $as_echo "$as_me: program exited with status $ac_status" >&5 -$as_echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - -( exit $ac_status ) -if test "$ac_cv_type_double" = yes; then - { { $as_echo "$as_me:$LINENO: error: in \`$ac_pwd':" >&5 -$as_echo "$as_me: error: in \`$ac_pwd':" >&2;} -{ { $as_echo "$as_me:$LINENO: error: cannot compute sizeof (double) -See \`config.log' for more details." >&5 -$as_echo "$as_me: error: cannot compute sizeof (double) -See \`config.log' for more details." >&2;} - { (exit 77); exit 77; }; }; } - else - ac_cv_sizeof_double=0 - fi -fi -rm -rf conftest.dSYM -rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext conftest.$ac_objext conftest.$ac_ext -fi -rm -f conftest.val -fi -{ $as_echo "$as_me:$LINENO: result: $ac_cv_sizeof_double" >&5 -$as_echo "$ac_cv_sizeof_double" >&6; } - - - -cat >>confdefs.h <<_ACEOF -#define SIZEOF_DOUBLE $ac_cv_sizeof_double -_ACEOF - - -# The cast to long int works around a bug in the HP C Compiler -# version HP92453-01 B.11.11.23709.GP, which incorrectly rejects -# declarations like `int a3[[(sizeof (unsigned char)) >= 0]];'. -# This bug is HP SR number 8606223364. -{ $as_echo "$as_me:$LINENO: checking size of fpos_t" >&5 -$as_echo_n "checking size of fpos_t... " >&6; } -if test "${ac_cv_sizeof_fpos_t+set}" = set; then - $as_echo_n "(cached) " >&6 -else - if test "$cross_compiling" = yes; then - # Depending upon the size, compute the lo and hi bounds. -cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -$ac_includes_default -int -main () -{ -static int test_array [1 - 2 * !(((long int) (sizeof (fpos_t))) >= 0)]; -test_array [0] = 0 - - ; - return 0; -} -_ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" -$as_echo "$ac_try_echo") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - ac_lo=0 ac_mid=0 - while :; do - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -$ac_includes_default -int -main () -{ -static int test_array [1 - 2 * !(((long int) (sizeof (fpos_t))) <= $ac_mid)]; -test_array [0] = 0 - - ; - return 0; -} -_ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" -$as_echo "$ac_try_echo") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - ac_hi=$ac_mid; break -else - $as_echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - ac_lo=`expr $ac_mid + 1` - if test $ac_lo -le $ac_mid; then - ac_lo= ac_hi= - break - fi - ac_mid=`expr 2 '*' $ac_mid + 1` -fi - -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext - done -else - $as_echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -$ac_includes_default -int -main () -{ -static int test_array [1 - 2 * !(((long int) (sizeof (fpos_t))) < 0)]; -test_array [0] = 0 - - ; - return 0; -} -_ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" -$as_echo "$ac_try_echo") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - ac_hi=-1 ac_mid=-1 - while :; do - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -$ac_includes_default -int -main () -{ -static int test_array [1 - 2 * !(((long int) (sizeof (fpos_t))) >= $ac_mid)]; -test_array [0] = 0 - - ; - return 0; -} -_ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" -$as_echo "$ac_try_echo") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - ac_lo=$ac_mid; break -else - $as_echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - ac_hi=`expr '(' $ac_mid ')' - 1` - if test $ac_mid -le $ac_hi; then - ac_lo= ac_hi= - break - fi - ac_mid=`expr 2 '*' $ac_mid` -fi - -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext - done -else - $as_echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - ac_lo= ac_hi= -fi - -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext -fi - -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext -# Binary search between lo and hi bounds. -while test "x$ac_lo" != "x$ac_hi"; do - ac_mid=`expr '(' $ac_hi - $ac_lo ')' / 2 + $ac_lo` - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -$ac_includes_default -int -main () -{ -static int test_array [1 - 2 * !(((long int) (sizeof (fpos_t))) <= $ac_mid)]; -test_array [0] = 0 - - ; - return 0; -} -_ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" -$as_echo "$ac_try_echo") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - ac_hi=$ac_mid -else - $as_echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - ac_lo=`expr '(' $ac_mid ')' + 1` -fi - -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext -done -case $ac_lo in -?*) ac_cv_sizeof_fpos_t=$ac_lo;; -'') if test "$ac_cv_type_fpos_t" = yes; then - { { $as_echo "$as_me:$LINENO: error: in \`$ac_pwd':" >&5 -$as_echo "$as_me: error: in \`$ac_pwd':" >&2;} -{ { $as_echo "$as_me:$LINENO: error: cannot compute sizeof (fpos_t) -See \`config.log' for more details." >&5 -$as_echo "$as_me: error: cannot compute sizeof (fpos_t) -See \`config.log' for more details." >&2;} - { (exit 77); exit 77; }; }; } - else - ac_cv_sizeof_fpos_t=0 - fi ;; -esac -else - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -$ac_includes_default -static long int longval () { return (long int) (sizeof (fpos_t)); } -static unsigned long int ulongval () { return (long int) (sizeof (fpos_t)); } -#include -#include -int -main () -{ - - FILE *f = fopen ("conftest.val", "w"); - if (! f) - return 1; - if (((long int) (sizeof (fpos_t))) < 0) - { - long int i = longval (); - if (i != ((long int) (sizeof (fpos_t)))) - return 1; - fprintf (f, "%ld", i); - } - else - { - unsigned long int i = ulongval (); - if (i != ((long int) (sizeof (fpos_t)))) - return 1; - fprintf (f, "%lu", i); - } - /* Do not output a trailing newline, as this causes \r\n confusion - on some platforms. */ - return ferror (f) || fclose (f) != 0; - - ; - return 0; -} -_ACEOF -rm -f conftest$ac_exeext -if { (ac_try="$ac_link" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" -$as_echo "$ac_try_echo") >&5 - (eval "$ac_link") 2>&5 - ac_status=$? - $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { ac_try='./conftest$ac_exeext' - { (case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" -$as_echo "$ac_try_echo") >&5 - (eval "$ac_try") 2>&5 - ac_status=$? - $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); }; }; then - ac_cv_sizeof_fpos_t=`cat conftest.val` -else - $as_echo "$as_me: program exited with status $ac_status" >&5 -$as_echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - -( exit $ac_status ) -if test "$ac_cv_type_fpos_t" = yes; then - { { $as_echo "$as_me:$LINENO: error: in \`$ac_pwd':" >&5 -$as_echo "$as_me: error: in \`$ac_pwd':" >&2;} -{ { $as_echo "$as_me:$LINENO: error: cannot compute sizeof (fpos_t) -See \`config.log' for more details." >&5 -$as_echo "$as_me: error: cannot compute sizeof (fpos_t) -See \`config.log' for more details." >&2;} - { (exit 77); exit 77; }; }; } - else - ac_cv_sizeof_fpos_t=0 - fi -fi -rm -rf conftest.dSYM -rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext conftest.$ac_objext conftest.$ac_ext -fi -rm -f conftest.val -fi -{ $as_echo "$as_me:$LINENO: result: $ac_cv_sizeof_fpos_t" >&5 -$as_echo "$ac_cv_sizeof_fpos_t" >&6; } - - - -cat >>confdefs.h <<_ACEOF -#define SIZEOF_FPOS_T $ac_cv_sizeof_fpos_t -_ACEOF - - -# The cast to long int works around a bug in the HP C Compiler -# version HP92453-01 B.11.11.23709.GP, which incorrectly rejects -# declarations like `int a3[[(sizeof (unsigned char)) >= 0]];'. -# This bug is HP SR number 8606223364. -{ $as_echo "$as_me:$LINENO: checking size of size_t" >&5 -$as_echo_n "checking size of size_t... " >&6; } -if test "${ac_cv_sizeof_size_t+set}" = set; then - $as_echo_n "(cached) " >&6 -else - if test "$cross_compiling" = yes; then - # Depending upon the size, compute the lo and hi bounds. -cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -$ac_includes_default -int -main () -{ -static int test_array [1 - 2 * !(((long int) (sizeof (size_t))) >= 0)]; -test_array [0] = 0 - - ; - return 0; -} -_ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" -$as_echo "$ac_try_echo") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - ac_lo=0 ac_mid=0 - while :; do - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -$ac_includes_default -int -main () -{ -static int test_array [1 - 2 * !(((long int) (sizeof (size_t))) <= $ac_mid)]; -test_array [0] = 0 - - ; - return 0; -} -_ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" -$as_echo "$ac_try_echo") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - ac_hi=$ac_mid; break -else - $as_echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - ac_lo=`expr $ac_mid + 1` - if test $ac_lo -le $ac_mid; then - ac_lo= ac_hi= - break - fi - ac_mid=`expr 2 '*' $ac_mid + 1` -fi - -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext - done -else - $as_echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -$ac_includes_default -int -main () -{ -static int test_array [1 - 2 * !(((long int) (sizeof (size_t))) < 0)]; -test_array [0] = 0 - - ; - return 0; -} -_ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" -$as_echo "$ac_try_echo") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - ac_hi=-1 ac_mid=-1 - while :; do - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -$ac_includes_default -int -main () -{ -static int test_array [1 - 2 * !(((long int) (sizeof (size_t))) >= $ac_mid)]; -test_array [0] = 0 - - ; - return 0; -} -_ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" -$as_echo "$ac_try_echo") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - ac_lo=$ac_mid; break -else - $as_echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - ac_hi=`expr '(' $ac_mid ')' - 1` - if test $ac_mid -le $ac_hi; then - ac_lo= ac_hi= - break - fi - ac_mid=`expr 2 '*' $ac_mid` -fi - -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext - done -else - $as_echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - ac_lo= ac_hi= -fi - -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext -fi - -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext -# Binary search between lo and hi bounds. -while test "x$ac_lo" != "x$ac_hi"; do - ac_mid=`expr '(' $ac_hi - $ac_lo ')' / 2 + $ac_lo` - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -$ac_includes_default -int -main () -{ -static int test_array [1 - 2 * !(((long int) (sizeof (size_t))) <= $ac_mid)]; -test_array [0] = 0 - - ; - return 0; -} -_ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" -$as_echo "$ac_try_echo") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - ac_hi=$ac_mid -else - $as_echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - ac_lo=`expr '(' $ac_mid ')' + 1` -fi - -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext -done -case $ac_lo in -?*) ac_cv_sizeof_size_t=$ac_lo;; -'') if test "$ac_cv_type_size_t" = yes; then - { { $as_echo "$as_me:$LINENO: error: in \`$ac_pwd':" >&5 -$as_echo "$as_me: error: in \`$ac_pwd':" >&2;} -{ { $as_echo "$as_me:$LINENO: error: cannot compute sizeof (size_t) -See \`config.log' for more details." >&5 -$as_echo "$as_me: error: cannot compute sizeof (size_t) -See \`config.log' for more details." >&2;} - { (exit 77); exit 77; }; }; } - else - ac_cv_sizeof_size_t=0 - fi ;; -esac -else - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -$ac_includes_default -static long int longval () { return (long int) (sizeof (size_t)); } -static unsigned long int ulongval () { return (long int) (sizeof (size_t)); } -#include -#include -int -main () -{ - - FILE *f = fopen ("conftest.val", "w"); - if (! f) - return 1; - if (((long int) (sizeof (size_t))) < 0) - { - long int i = longval (); - if (i != ((long int) (sizeof (size_t)))) - return 1; - fprintf (f, "%ld", i); - } - else - { - unsigned long int i = ulongval (); - if (i != ((long int) (sizeof (size_t)))) - return 1; - fprintf (f, "%lu", i); - } - /* Do not output a trailing newline, as this causes \r\n confusion - on some platforms. */ - return ferror (f) || fclose (f) != 0; - - ; - return 0; -} -_ACEOF -rm -f conftest$ac_exeext -if { (ac_try="$ac_link" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" -$as_echo "$ac_try_echo") >&5 - (eval "$ac_link") 2>&5 - ac_status=$? - $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { ac_try='./conftest$ac_exeext' - { (case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" -$as_echo "$ac_try_echo") >&5 - (eval "$ac_try") 2>&5 - ac_status=$? - $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); }; }; then - ac_cv_sizeof_size_t=`cat conftest.val` -else - $as_echo "$as_me: program exited with status $ac_status" >&5 -$as_echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - -( exit $ac_status ) -if test "$ac_cv_type_size_t" = yes; then - { { $as_echo "$as_me:$LINENO: error: in \`$ac_pwd':" >&5 -$as_echo "$as_me: error: in \`$ac_pwd':" >&2;} -{ { $as_echo "$as_me:$LINENO: error: cannot compute sizeof (size_t) -See \`config.log' for more details." >&5 -$as_echo "$as_me: error: cannot compute sizeof (size_t) -See \`config.log' for more details." >&2;} - { (exit 77); exit 77; }; }; } - else - ac_cv_sizeof_size_t=0 - fi -fi -rm -rf conftest.dSYM -rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext conftest.$ac_objext conftest.$ac_ext -fi -rm -f conftest.val -fi -{ $as_echo "$as_me:$LINENO: result: $ac_cv_sizeof_size_t" >&5 -$as_echo "$ac_cv_sizeof_size_t" >&6; } - - - -cat >>confdefs.h <<_ACEOF -#define SIZEOF_SIZE_T $ac_cv_sizeof_size_t -_ACEOF - - -# The cast to long int works around a bug in the HP C Compiler -# version HP92453-01 B.11.11.23709.GP, which incorrectly rejects -# declarations like `int a3[[(sizeof (unsigned char)) >= 0]];'. -# This bug is HP SR number 8606223364. -{ $as_echo "$as_me:$LINENO: checking size of pid_t" >&5 -$as_echo_n "checking size of pid_t... " >&6; } -if test "${ac_cv_sizeof_pid_t+set}" = set; then - $as_echo_n "(cached) " >&6 -else - if test "$cross_compiling" = yes; then - # Depending upon the size, compute the lo and hi bounds. -cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -$ac_includes_default -int -main () -{ -static int test_array [1 - 2 * !(((long int) (sizeof (pid_t))) >= 0)]; -test_array [0] = 0 - - ; - return 0; -} -_ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" -$as_echo "$ac_try_echo") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - ac_lo=0 ac_mid=0 - while :; do - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -$ac_includes_default -int -main () -{ -static int test_array [1 - 2 * !(((long int) (sizeof (pid_t))) <= $ac_mid)]; -test_array [0] = 0 - - ; - return 0; -} -_ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" -$as_echo "$ac_try_echo") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - ac_hi=$ac_mid; break -else - $as_echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - ac_lo=`expr $ac_mid + 1` - if test $ac_lo -le $ac_mid; then - ac_lo= ac_hi= - break - fi - ac_mid=`expr 2 '*' $ac_mid + 1` -fi - -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext - done -else - $as_echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -$ac_includes_default -int -main () -{ -static int test_array [1 - 2 * !(((long int) (sizeof (pid_t))) < 0)]; -test_array [0] = 0 - - ; - return 0; -} -_ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" -$as_echo "$ac_try_echo") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - ac_hi=-1 ac_mid=-1 - while :; do - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -$ac_includes_default -int -main () -{ -static int test_array [1 - 2 * !(((long int) (sizeof (pid_t))) >= $ac_mid)]; -test_array [0] = 0 - - ; - return 0; -} -_ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" -$as_echo "$ac_try_echo") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - ac_lo=$ac_mid; break -else - $as_echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - ac_hi=`expr '(' $ac_mid ')' - 1` - if test $ac_mid -le $ac_hi; then - ac_lo= ac_hi= - break - fi - ac_mid=`expr 2 '*' $ac_mid` -fi - -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext - done -else - $as_echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - ac_lo= ac_hi= -fi - -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext -fi - -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext -# Binary search between lo and hi bounds. -while test "x$ac_lo" != "x$ac_hi"; do - ac_mid=`expr '(' $ac_hi - $ac_lo ')' / 2 + $ac_lo` - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -$ac_includes_default -int -main () -{ -static int test_array [1 - 2 * !(((long int) (sizeof (pid_t))) <= $ac_mid)]; -test_array [0] = 0 - - ; - return 0; -} -_ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" -$as_echo "$ac_try_echo") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - ac_hi=$ac_mid -else - $as_echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - ac_lo=`expr '(' $ac_mid ')' + 1` -fi - -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext -done -case $ac_lo in -?*) ac_cv_sizeof_pid_t=$ac_lo;; -'') if test "$ac_cv_type_pid_t" = yes; then - { { $as_echo "$as_me:$LINENO: error: in \`$ac_pwd':" >&5 -$as_echo "$as_me: error: in \`$ac_pwd':" >&2;} -{ { $as_echo "$as_me:$LINENO: error: cannot compute sizeof (pid_t) -See \`config.log' for more details." >&5 -$as_echo "$as_me: error: cannot compute sizeof (pid_t) -See \`config.log' for more details." >&2;} - { (exit 77); exit 77; }; }; } - else - ac_cv_sizeof_pid_t=0 - fi ;; -esac -else - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -$ac_includes_default -static long int longval () { return (long int) (sizeof (pid_t)); } -static unsigned long int ulongval () { return (long int) (sizeof (pid_t)); } -#include -#include -int -main () -{ - - FILE *f = fopen ("conftest.val", "w"); - if (! f) - return 1; - if (((long int) (sizeof (pid_t))) < 0) - { - long int i = longval (); - if (i != ((long int) (sizeof (pid_t)))) - return 1; - fprintf (f, "%ld", i); - } - else - { - unsigned long int i = ulongval (); - if (i != ((long int) (sizeof (pid_t)))) - return 1; - fprintf (f, "%lu", i); - } - /* Do not output a trailing newline, as this causes \r\n confusion - on some platforms. */ - return ferror (f) || fclose (f) != 0; - - ; - return 0; -} -_ACEOF -rm -f conftest$ac_exeext -if { (ac_try="$ac_link" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" -$as_echo "$ac_try_echo") >&5 - (eval "$ac_link") 2>&5 - ac_status=$? - $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { ac_try='./conftest$ac_exeext' - { (case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" -$as_echo "$ac_try_echo") >&5 - (eval "$ac_try") 2>&5 - ac_status=$? - $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); }; }; then - ac_cv_sizeof_pid_t=`cat conftest.val` -else - $as_echo "$as_me: program exited with status $ac_status" >&5 -$as_echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - -( exit $ac_status ) -if test "$ac_cv_type_pid_t" = yes; then - { { $as_echo "$as_me:$LINENO: error: in \`$ac_pwd':" >&5 -$as_echo "$as_me: error: in \`$ac_pwd':" >&2;} -{ { $as_echo "$as_me:$LINENO: error: cannot compute sizeof (pid_t) -See \`config.log' for more details." >&5 -$as_echo "$as_me: error: cannot compute sizeof (pid_t) -See \`config.log' for more details." >&2;} - { (exit 77); exit 77; }; }; } - else - ac_cv_sizeof_pid_t=0 - fi -fi -rm -rf conftest.dSYM -rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext conftest.$ac_objext conftest.$ac_ext -fi -rm -f conftest.val -fi -{ $as_echo "$as_me:$LINENO: result: $ac_cv_sizeof_pid_t" >&5 -$as_echo "$ac_cv_sizeof_pid_t" >&6; } - - - -cat >>confdefs.h <<_ACEOF -#define SIZEOF_PID_T $ac_cv_sizeof_pid_t -_ACEOF - - - -{ $as_echo "$as_me:$LINENO: checking for long long support" >&5 -$as_echo_n "checking for long long support... " >&6; } -have_long_long=no -cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ - -int -main () -{ -long long x; x = (long long)0; - ; - return 0; -} -_ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" -$as_echo "$ac_try_echo") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - - -cat >>confdefs.h <<\_ACEOF -#define HAVE_LONG_LONG 1 -_ACEOF - - have_long_long=yes - -else - $as_echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - -fi - -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext -{ $as_echo "$as_me:$LINENO: result: $have_long_long" >&5 -$as_echo "$have_long_long" >&6; } -if test "$have_long_long" = yes ; then -# The cast to long int works around a bug in the HP C Compiler -# version HP92453-01 B.11.11.23709.GP, which incorrectly rejects -# declarations like `int a3[[(sizeof (unsigned char)) >= 0]];'. -# This bug is HP SR number 8606223364. -{ $as_echo "$as_me:$LINENO: checking size of long long" >&5 -$as_echo_n "checking size of long long... " >&6; } -if test "${ac_cv_sizeof_long_long+set}" = set; then - $as_echo_n "(cached) " >&6 -else - if test "$cross_compiling" = yes; then - # Depending upon the size, compute the lo and hi bounds. -cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -$ac_includes_default -int -main () -{ -static int test_array [1 - 2 * !(((long int) (sizeof (long long))) >= 0)]; -test_array [0] = 0 - - ; - return 0; -} -_ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" -$as_echo "$ac_try_echo") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - ac_lo=0 ac_mid=0 - while :; do - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -$ac_includes_default -int -main () -{ -static int test_array [1 - 2 * !(((long int) (sizeof (long long))) <= $ac_mid)]; -test_array [0] = 0 - - ; - return 0; -} -_ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" -$as_echo "$ac_try_echo") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - ac_hi=$ac_mid; break -else - $as_echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - ac_lo=`expr $ac_mid + 1` - if test $ac_lo -le $ac_mid; then - ac_lo= ac_hi= - break - fi - ac_mid=`expr 2 '*' $ac_mid + 1` -fi - -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext - done -else - $as_echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -$ac_includes_default -int -main () -{ -static int test_array [1 - 2 * !(((long int) (sizeof (long long))) < 0)]; -test_array [0] = 0 - - ; - return 0; -} -_ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" -$as_echo "$ac_try_echo") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - ac_hi=-1 ac_mid=-1 - while :; do - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -$ac_includes_default -int -main () -{ -static int test_array [1 - 2 * !(((long int) (sizeof (long long))) >= $ac_mid)]; -test_array [0] = 0 - - ; - return 0; -} -_ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" -$as_echo "$ac_try_echo") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - ac_lo=$ac_mid; break -else - $as_echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - ac_hi=`expr '(' $ac_mid ')' - 1` - if test $ac_mid -le $ac_hi; then - ac_lo= ac_hi= - break - fi - ac_mid=`expr 2 '*' $ac_mid` -fi - -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext - done -else - $as_echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - ac_lo= ac_hi= -fi - -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext -fi - -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext -# Binary search between lo and hi bounds. -while test "x$ac_lo" != "x$ac_hi"; do - ac_mid=`expr '(' $ac_hi - $ac_lo ')' / 2 + $ac_lo` - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -$ac_includes_default -int -main () -{ -static int test_array [1 - 2 * !(((long int) (sizeof (long long))) <= $ac_mid)]; -test_array [0] = 0 - - ; - return 0; -} -_ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" -$as_echo "$ac_try_echo") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - ac_hi=$ac_mid -else - $as_echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - ac_lo=`expr '(' $ac_mid ')' + 1` -fi - -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext -done -case $ac_lo in -?*) ac_cv_sizeof_long_long=$ac_lo;; -'') if test "$ac_cv_type_long_long" = yes; then - { { $as_echo "$as_me:$LINENO: error: in \`$ac_pwd':" >&5 -$as_echo "$as_me: error: in \`$ac_pwd':" >&2;} -{ { $as_echo "$as_me:$LINENO: error: cannot compute sizeof (long long) -See \`config.log' for more details." >&5 -$as_echo "$as_me: error: cannot compute sizeof (long long) -See \`config.log' for more details." >&2;} - { (exit 77); exit 77; }; }; } - else - ac_cv_sizeof_long_long=0 - fi ;; -esac -else - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -$ac_includes_default -static long int longval () { return (long int) (sizeof (long long)); } -static unsigned long int ulongval () { return (long int) (sizeof (long long)); } -#include -#include -int -main () -{ - - FILE *f = fopen ("conftest.val", "w"); - if (! f) - return 1; - if (((long int) (sizeof (long long))) < 0) - { - long int i = longval (); - if (i != ((long int) (sizeof (long long)))) - return 1; - fprintf (f, "%ld", i); - } - else - { - unsigned long int i = ulongval (); - if (i != ((long int) (sizeof (long long)))) - return 1; - fprintf (f, "%lu", i); - } - /* Do not output a trailing newline, as this causes \r\n confusion - on some platforms. */ - return ferror (f) || fclose (f) != 0; - - ; - return 0; -} -_ACEOF -rm -f conftest$ac_exeext -if { (ac_try="$ac_link" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" -$as_echo "$ac_try_echo") >&5 - (eval "$ac_link") 2>&5 - ac_status=$? - $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { ac_try='./conftest$ac_exeext' - { (case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" -$as_echo "$ac_try_echo") >&5 - (eval "$ac_try") 2>&5 - ac_status=$? - $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); }; }; then - ac_cv_sizeof_long_long=`cat conftest.val` -else - $as_echo "$as_me: program exited with status $ac_status" >&5 -$as_echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - -( exit $ac_status ) -if test "$ac_cv_type_long_long" = yes; then - { { $as_echo "$as_me:$LINENO: error: in \`$ac_pwd':" >&5 -$as_echo "$as_me: error: in \`$ac_pwd':" >&2;} -{ { $as_echo "$as_me:$LINENO: error: cannot compute sizeof (long long) -See \`config.log' for more details." >&5 -$as_echo "$as_me: error: cannot compute sizeof (long long) -See \`config.log' for more details." >&2;} - { (exit 77); exit 77; }; }; } - else - ac_cv_sizeof_long_long=0 - fi -fi -rm -rf conftest.dSYM -rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext conftest.$ac_objext conftest.$ac_ext -fi -rm -f conftest.val -fi -{ $as_echo "$as_me:$LINENO: result: $ac_cv_sizeof_long_long" >&5 -$as_echo "$ac_cv_sizeof_long_long" >&6; } - - - -cat >>confdefs.h <<_ACEOF -#define SIZEOF_LONG_LONG $ac_cv_sizeof_long_long -_ACEOF - - -fi - -{ $as_echo "$as_me:$LINENO: checking for long double support" >&5 -$as_echo_n "checking for long double support... " >&6; } -have_long_double=no -cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ - -int -main () -{ -long double x; x = (long double)0.; - ; - return 0; -} -_ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" -$as_echo "$ac_try_echo") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - - -cat >>confdefs.h <<\_ACEOF -#define HAVE_LONG_DOUBLE 1 -_ACEOF - - have_long_double=yes - -else - $as_echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - -fi - -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext -{ $as_echo "$as_me:$LINENO: result: $have_long_double" >&5 -$as_echo "$have_long_double" >&6; } -if test "$have_long_double" = yes ; then -# The cast to long int works around a bug in the HP C Compiler -# version HP92453-01 B.11.11.23709.GP, which incorrectly rejects -# declarations like `int a3[[(sizeof (unsigned char)) >= 0]];'. -# This bug is HP SR number 8606223364. -{ $as_echo "$as_me:$LINENO: checking size of long double" >&5 -$as_echo_n "checking size of long double... " >&6; } -if test "${ac_cv_sizeof_long_double+set}" = set; then - $as_echo_n "(cached) " >&6 -else - if test "$cross_compiling" = yes; then - # Depending upon the size, compute the lo and hi bounds. -cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -$ac_includes_default -int -main () -{ -static int test_array [1 - 2 * !(((long int) (sizeof (long double))) >= 0)]; -test_array [0] = 0 - - ; - return 0; -} -_ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" -$as_echo "$ac_try_echo") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - ac_lo=0 ac_mid=0 - while :; do - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -$ac_includes_default -int -main () -{ -static int test_array [1 - 2 * !(((long int) (sizeof (long double))) <= $ac_mid)]; -test_array [0] = 0 - - ; - return 0; -} -_ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" -$as_echo "$ac_try_echo") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - ac_hi=$ac_mid; break -else - $as_echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - ac_lo=`expr $ac_mid + 1` - if test $ac_lo -le $ac_mid; then - ac_lo= ac_hi= - break - fi - ac_mid=`expr 2 '*' $ac_mid + 1` -fi - -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext - done -else - $as_echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -$ac_includes_default -int -main () -{ -static int test_array [1 - 2 * !(((long int) (sizeof (long double))) < 0)]; -test_array [0] = 0 - - ; - return 0; -} -_ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" -$as_echo "$ac_try_echo") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - ac_hi=-1 ac_mid=-1 - while :; do - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -$ac_includes_default -int -main () -{ -static int test_array [1 - 2 * !(((long int) (sizeof (long double))) >= $ac_mid)]; -test_array [0] = 0 - - ; - return 0; -} -_ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" -$as_echo "$ac_try_echo") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - ac_lo=$ac_mid; break -else - $as_echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - ac_hi=`expr '(' $ac_mid ')' - 1` - if test $ac_mid -le $ac_hi; then - ac_lo= ac_hi= - break - fi - ac_mid=`expr 2 '*' $ac_mid` -fi - -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext - done -else - $as_echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - ac_lo= ac_hi= -fi - -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext -fi - -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext -# Binary search between lo and hi bounds. -while test "x$ac_lo" != "x$ac_hi"; do - ac_mid=`expr '(' $ac_hi - $ac_lo ')' / 2 + $ac_lo` - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -$ac_includes_default -int -main () -{ -static int test_array [1 - 2 * !(((long int) (sizeof (long double))) <= $ac_mid)]; -test_array [0] = 0 - - ; - return 0; -} -_ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" -$as_echo "$ac_try_echo") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - ac_hi=$ac_mid -else - $as_echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - ac_lo=`expr '(' $ac_mid ')' + 1` -fi - -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext -done -case $ac_lo in -?*) ac_cv_sizeof_long_double=$ac_lo;; -'') if test "$ac_cv_type_long_double" = yes; then - { { $as_echo "$as_me:$LINENO: error: in \`$ac_pwd':" >&5 -$as_echo "$as_me: error: in \`$ac_pwd':" >&2;} -{ { $as_echo "$as_me:$LINENO: error: cannot compute sizeof (long double) -See \`config.log' for more details." >&5 -$as_echo "$as_me: error: cannot compute sizeof (long double) -See \`config.log' for more details." >&2;} - { (exit 77); exit 77; }; }; } - else - ac_cv_sizeof_long_double=0 - fi ;; -esac -else - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -$ac_includes_default -static long int longval () { return (long int) (sizeof (long double)); } -static unsigned long int ulongval () { return (long int) (sizeof (long double)); } -#include -#include -int -main () -{ - - FILE *f = fopen ("conftest.val", "w"); - if (! f) - return 1; - if (((long int) (sizeof (long double))) < 0) - { - long int i = longval (); - if (i != ((long int) (sizeof (long double)))) - return 1; - fprintf (f, "%ld", i); - } - else - { - unsigned long int i = ulongval (); - if (i != ((long int) (sizeof (long double)))) - return 1; - fprintf (f, "%lu", i); - } - /* Do not output a trailing newline, as this causes \r\n confusion - on some platforms. */ - return ferror (f) || fclose (f) != 0; - - ; - return 0; -} -_ACEOF -rm -f conftest$ac_exeext -if { (ac_try="$ac_link" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" -$as_echo "$ac_try_echo") >&5 - (eval "$ac_link") 2>&5 - ac_status=$? - $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { ac_try='./conftest$ac_exeext' - { (case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" -$as_echo "$ac_try_echo") >&5 - (eval "$ac_try") 2>&5 - ac_status=$? - $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); }; }; then - ac_cv_sizeof_long_double=`cat conftest.val` -else - $as_echo "$as_me: program exited with status $ac_status" >&5 -$as_echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - -( exit $ac_status ) -if test "$ac_cv_type_long_double" = yes; then - { { $as_echo "$as_me:$LINENO: error: in \`$ac_pwd':" >&5 -$as_echo "$as_me: error: in \`$ac_pwd':" >&2;} -{ { $as_echo "$as_me:$LINENO: error: cannot compute sizeof (long double) -See \`config.log' for more details." >&5 -$as_echo "$as_me: error: cannot compute sizeof (long double) -See \`config.log' for more details." >&2;} - { (exit 77); exit 77; }; }; } - else - ac_cv_sizeof_long_double=0 - fi -fi -rm -rf conftest.dSYM -rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext conftest.$ac_objext conftest.$ac_ext -fi -rm -f conftest.val -fi -{ $as_echo "$as_me:$LINENO: result: $ac_cv_sizeof_long_double" >&5 -$as_echo "$ac_cv_sizeof_long_double" >&6; } - - - -cat >>confdefs.h <<_ACEOF -#define SIZEOF_LONG_DOUBLE $ac_cv_sizeof_long_double -_ACEOF - - -fi - -{ $as_echo "$as_me:$LINENO: checking for _Bool support" >&5 -$as_echo_n "checking for _Bool support... " >&6; } -have_c99_bool=no -cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ - -int -main () -{ -_Bool x; x = (_Bool)0; - ; - return 0; -} -_ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" -$as_echo "$ac_try_echo") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - - -cat >>confdefs.h <<\_ACEOF -#define HAVE_C99_BOOL 1 -_ACEOF - - have_c99_bool=yes - -else - $as_echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - -fi - -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext -{ $as_echo "$as_me:$LINENO: result: $have_c99_bool" >&5 -$as_echo "$have_c99_bool" >&6; } -if test "$have_c99_bool" = yes ; then -# The cast to long int works around a bug in the HP C Compiler -# version HP92453-01 B.11.11.23709.GP, which incorrectly rejects -# declarations like `int a3[[(sizeof (unsigned char)) >= 0]];'. -# This bug is HP SR number 8606223364. -{ $as_echo "$as_me:$LINENO: checking size of _Bool" >&5 -$as_echo_n "checking size of _Bool... " >&6; } -if test "${ac_cv_sizeof__Bool+set}" = set; then - $as_echo_n "(cached) " >&6 -else - if test "$cross_compiling" = yes; then - # Depending upon the size, compute the lo and hi bounds. -cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -$ac_includes_default -int -main () -{ -static int test_array [1 - 2 * !(((long int) (sizeof (_Bool))) >= 0)]; -test_array [0] = 0 - - ; - return 0; -} -_ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" -$as_echo "$ac_try_echo") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - ac_lo=0 ac_mid=0 - while :; do - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -$ac_includes_default -int -main () -{ -static int test_array [1 - 2 * !(((long int) (sizeof (_Bool))) <= $ac_mid)]; -test_array [0] = 0 - - ; - return 0; -} -_ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" -$as_echo "$ac_try_echo") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - ac_hi=$ac_mid; break -else - $as_echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - ac_lo=`expr $ac_mid + 1` - if test $ac_lo -le $ac_mid; then - ac_lo= ac_hi= - break - fi - ac_mid=`expr 2 '*' $ac_mid + 1` -fi - -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext - done -else - $as_echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -$ac_includes_default -int -main () -{ -static int test_array [1 - 2 * !(((long int) (sizeof (_Bool))) < 0)]; -test_array [0] = 0 - - ; - return 0; -} -_ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" -$as_echo "$ac_try_echo") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - ac_hi=-1 ac_mid=-1 - while :; do - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -$ac_includes_default -int -main () -{ -static int test_array [1 - 2 * !(((long int) (sizeof (_Bool))) >= $ac_mid)]; -test_array [0] = 0 - - ; - return 0; -} -_ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" -$as_echo "$ac_try_echo") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - ac_lo=$ac_mid; break -else - $as_echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - ac_hi=`expr '(' $ac_mid ')' - 1` - if test $ac_mid -le $ac_hi; then - ac_lo= ac_hi= - break - fi - ac_mid=`expr 2 '*' $ac_mid` -fi - -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext - done -else - $as_echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - ac_lo= ac_hi= -fi - -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext -fi - -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext -# Binary search between lo and hi bounds. -while test "x$ac_lo" != "x$ac_hi"; do - ac_mid=`expr '(' $ac_hi - $ac_lo ')' / 2 + $ac_lo` - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -$ac_includes_default -int -main () -{ -static int test_array [1 - 2 * !(((long int) (sizeof (_Bool))) <= $ac_mid)]; -test_array [0] = 0 - - ; - return 0; -} -_ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" -$as_echo "$ac_try_echo") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - ac_hi=$ac_mid -else - $as_echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - ac_lo=`expr '(' $ac_mid ')' + 1` -fi - -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext -done -case $ac_lo in -?*) ac_cv_sizeof__Bool=$ac_lo;; -'') if test "$ac_cv_type__Bool" = yes; then - { { $as_echo "$as_me:$LINENO: error: in \`$ac_pwd':" >&5 -$as_echo "$as_me: error: in \`$ac_pwd':" >&2;} -{ { $as_echo "$as_me:$LINENO: error: cannot compute sizeof (_Bool) -See \`config.log' for more details." >&5 -$as_echo "$as_me: error: cannot compute sizeof (_Bool) -See \`config.log' for more details." >&2;} - { (exit 77); exit 77; }; }; } - else - ac_cv_sizeof__Bool=0 - fi ;; -esac -else - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -$ac_includes_default -static long int longval () { return (long int) (sizeof (_Bool)); } -static unsigned long int ulongval () { return (long int) (sizeof (_Bool)); } -#include -#include -int -main () -{ - - FILE *f = fopen ("conftest.val", "w"); - if (! f) - return 1; - if (((long int) (sizeof (_Bool))) < 0) - { - long int i = longval (); - if (i != ((long int) (sizeof (_Bool)))) - return 1; - fprintf (f, "%ld", i); - } - else - { - unsigned long int i = ulongval (); - if (i != ((long int) (sizeof (_Bool)))) - return 1; - fprintf (f, "%lu", i); - } - /* Do not output a trailing newline, as this causes \r\n confusion - on some platforms. */ - return ferror (f) || fclose (f) != 0; - - ; - return 0; -} -_ACEOF -rm -f conftest$ac_exeext -if { (ac_try="$ac_link" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" -$as_echo "$ac_try_echo") >&5 - (eval "$ac_link") 2>&5 - ac_status=$? - $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { ac_try='./conftest$ac_exeext' - { (case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" -$as_echo "$ac_try_echo") >&5 - (eval "$ac_try") 2>&5 - ac_status=$? - $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); }; }; then - ac_cv_sizeof__Bool=`cat conftest.val` -else - $as_echo "$as_me: program exited with status $ac_status" >&5 -$as_echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - -( exit $ac_status ) -if test "$ac_cv_type__Bool" = yes; then - { { $as_echo "$as_me:$LINENO: error: in \`$ac_pwd':" >&5 -$as_echo "$as_me: error: in \`$ac_pwd':" >&2;} -{ { $as_echo "$as_me:$LINENO: error: cannot compute sizeof (_Bool) -See \`config.log' for more details." >&5 -$as_echo "$as_me: error: cannot compute sizeof (_Bool) -See \`config.log' for more details." >&2;} - { (exit 77); exit 77; }; }; } - else - ac_cv_sizeof__Bool=0 - fi -fi -rm -rf conftest.dSYM -rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext conftest.$ac_objext conftest.$ac_ext -fi -rm -f conftest.val -fi -{ $as_echo "$as_me:$LINENO: result: $ac_cv_sizeof__Bool" >&5 -$as_echo "$ac_cv_sizeof__Bool" >&6; } - - - -cat >>confdefs.h <<_ACEOF -#define SIZEOF__BOOL $ac_cv_sizeof__Bool -_ACEOF - - -fi - -{ $as_echo "$as_me:$LINENO: checking for uintptr_t" >&5 -$as_echo_n "checking for uintptr_t... " >&6; } -if test "${ac_cv_type_uintptr_t+set}" = set; then - $as_echo_n "(cached) " >&6 -else - ac_cv_type_uintptr_t=no -cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -#ifdef HAVE_STDINT_H - #include - #endif - -int -main () -{ -if (sizeof (uintptr_t)) - return 0; - ; - return 0; -} -_ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" -$as_echo "$ac_try_echo") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -#ifdef HAVE_STDINT_H - #include - #endif - -int -main () -{ -if (sizeof ((uintptr_t))) - return 0; - ; - return 0; -} -_ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" -$as_echo "$ac_try_echo") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - : -else - $as_echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - ac_cv_type_uintptr_t=yes -fi - -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext -else - $as_echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - -fi - -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext -fi -{ $as_echo "$as_me:$LINENO: result: $ac_cv_type_uintptr_t" >&5 -$as_echo "$ac_cv_type_uintptr_t" >&6; } -if test "x$ac_cv_type_uintptr_t" = x""yes; then - -cat >>confdefs.h <<_ACEOF -#define HAVE_UINTPTR_T 1 -_ACEOF - -# The cast to long int works around a bug in the HP C Compiler -# version HP92453-01 B.11.11.23709.GP, which incorrectly rejects -# declarations like `int a3[[(sizeof (unsigned char)) >= 0]];'. -# This bug is HP SR number 8606223364. -{ $as_echo "$as_me:$LINENO: checking size of uintptr_t" >&5 -$as_echo_n "checking size of uintptr_t... " >&6; } -if test "${ac_cv_sizeof_uintptr_t+set}" = set; then - $as_echo_n "(cached) " >&6 -else - if test "$cross_compiling" = yes; then - # Depending upon the size, compute the lo and hi bounds. -cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -$ac_includes_default -int -main () -{ -static int test_array [1 - 2 * !(((long int) (sizeof (uintptr_t))) >= 0)]; -test_array [0] = 0 - - ; - return 0; -} -_ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" -$as_echo "$ac_try_echo") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - ac_lo=0 ac_mid=0 - while :; do - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -$ac_includes_default -int -main () -{ -static int test_array [1 - 2 * !(((long int) (sizeof (uintptr_t))) <= $ac_mid)]; -test_array [0] = 0 - - ; - return 0; -} -_ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" -$as_echo "$ac_try_echo") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - ac_hi=$ac_mid; break -else - $as_echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - ac_lo=`expr $ac_mid + 1` - if test $ac_lo -le $ac_mid; then - ac_lo= ac_hi= - break - fi - ac_mid=`expr 2 '*' $ac_mid + 1` -fi - -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext - done -else - $as_echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -$ac_includes_default -int -main () -{ -static int test_array [1 - 2 * !(((long int) (sizeof (uintptr_t))) < 0)]; -test_array [0] = 0 - - ; - return 0; -} -_ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" -$as_echo "$ac_try_echo") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - ac_hi=-1 ac_mid=-1 - while :; do - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -$ac_includes_default -int -main () -{ -static int test_array [1 - 2 * !(((long int) (sizeof (uintptr_t))) >= $ac_mid)]; -test_array [0] = 0 - - ; - return 0; -} -_ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" -$as_echo "$ac_try_echo") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - ac_lo=$ac_mid; break -else - $as_echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - ac_hi=`expr '(' $ac_mid ')' - 1` - if test $ac_mid -le $ac_hi; then - ac_lo= ac_hi= - break - fi - ac_mid=`expr 2 '*' $ac_mid` -fi - -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext - done -else - $as_echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - ac_lo= ac_hi= -fi - -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext -fi - -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext -# Binary search between lo and hi bounds. -while test "x$ac_lo" != "x$ac_hi"; do - ac_mid=`expr '(' $ac_hi - $ac_lo ')' / 2 + $ac_lo` - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -$ac_includes_default -int -main () -{ -static int test_array [1 - 2 * !(((long int) (sizeof (uintptr_t))) <= $ac_mid)]; -test_array [0] = 0 - - ; - return 0; -} -_ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" -$as_echo "$ac_try_echo") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - ac_hi=$ac_mid -else - $as_echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - ac_lo=`expr '(' $ac_mid ')' + 1` -fi - -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext -done -case $ac_lo in -?*) ac_cv_sizeof_uintptr_t=$ac_lo;; -'') if test "$ac_cv_type_uintptr_t" = yes; then - { { $as_echo "$as_me:$LINENO: error: in \`$ac_pwd':" >&5 -$as_echo "$as_me: error: in \`$ac_pwd':" >&2;} -{ { $as_echo "$as_me:$LINENO: error: cannot compute sizeof (uintptr_t) -See \`config.log' for more details." >&5 -$as_echo "$as_me: error: cannot compute sizeof (uintptr_t) -See \`config.log' for more details." >&2;} - { (exit 77); exit 77; }; }; } - else - ac_cv_sizeof_uintptr_t=0 - fi ;; -esac -else - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -$ac_includes_default -static long int longval () { return (long int) (sizeof (uintptr_t)); } -static unsigned long int ulongval () { return (long int) (sizeof (uintptr_t)); } -#include -#include -int -main () -{ - - FILE *f = fopen ("conftest.val", "w"); - if (! f) - return 1; - if (((long int) (sizeof (uintptr_t))) < 0) - { - long int i = longval (); - if (i != ((long int) (sizeof (uintptr_t)))) - return 1; - fprintf (f, "%ld", i); - } - else - { - unsigned long int i = ulongval (); - if (i != ((long int) (sizeof (uintptr_t)))) - return 1; - fprintf (f, "%lu", i); - } - /* Do not output a trailing newline, as this causes \r\n confusion - on some platforms. */ - return ferror (f) || fclose (f) != 0; - - ; - return 0; -} -_ACEOF -rm -f conftest$ac_exeext -if { (ac_try="$ac_link" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" -$as_echo "$ac_try_echo") >&5 - (eval "$ac_link") 2>&5 - ac_status=$? - $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { ac_try='./conftest$ac_exeext' - { (case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" -$as_echo "$ac_try_echo") >&5 - (eval "$ac_try") 2>&5 - ac_status=$? - $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); }; }; then - ac_cv_sizeof_uintptr_t=`cat conftest.val` -else - $as_echo "$as_me: program exited with status $ac_status" >&5 -$as_echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - -( exit $ac_status ) -if test "$ac_cv_type_uintptr_t" = yes; then - { { $as_echo "$as_me:$LINENO: error: in \`$ac_pwd':" >&5 -$as_echo "$as_me: error: in \`$ac_pwd':" >&2;} -{ { $as_echo "$as_me:$LINENO: error: cannot compute sizeof (uintptr_t) -See \`config.log' for more details." >&5 -$as_echo "$as_me: error: cannot compute sizeof (uintptr_t) -See \`config.log' for more details." >&2;} - { (exit 77); exit 77; }; }; } - else - ac_cv_sizeof_uintptr_t=0 - fi -fi -rm -rf conftest.dSYM -rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext conftest.$ac_objext conftest.$ac_ext -fi -rm -f conftest.val -fi -{ $as_echo "$as_me:$LINENO: result: $ac_cv_sizeof_uintptr_t" >&5 -$as_echo "$ac_cv_sizeof_uintptr_t" >&6; } - - - -cat >>confdefs.h <<_ACEOF -#define SIZEOF_UINTPTR_T $ac_cv_sizeof_uintptr_t -_ACEOF - - -fi - - - -# Hmph. AC_CHECK_SIZEOF() doesn't include . -{ $as_echo "$as_me:$LINENO: checking size of off_t" >&5 -$as_echo_n "checking size of off_t... " >&6; } -if test "${ac_cv_sizeof_off_t+set}" = set; then - $as_echo_n "(cached) " >&6 -else - if test "$cross_compiling" = yes; then - ac_cv_sizeof_off_t=4 -else - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -#include -#include -main() -{ - FILE *f=fopen("conftestval", "w"); - if (!f) exit(1); - fprintf(f, "%d\n", sizeof(off_t)); - exit(0); -} -_ACEOF -rm -f conftest$ac_exeext -if { (ac_try="$ac_link" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" -$as_echo "$ac_try_echo") >&5 - (eval "$ac_link") 2>&5 - ac_status=$? - $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { ac_try='./conftest$ac_exeext' - { (case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" -$as_echo "$ac_try_echo") >&5 - (eval "$ac_try") 2>&5 - ac_status=$? - $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); }; }; then - ac_cv_sizeof_off_t=`cat conftestval` -else - $as_echo "$as_me: program exited with status $ac_status" >&5 -$as_echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - -( exit $ac_status ) -ac_cv_sizeof_off_t=0 -fi -rm -rf conftest.dSYM -rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext conftest.$ac_objext conftest.$ac_ext -fi - - - -fi - -{ $as_echo "$as_me:$LINENO: result: $ac_cv_sizeof_off_t" >&5 -$as_echo "$ac_cv_sizeof_off_t" >&6; } - -cat >>confdefs.h <<_ACEOF -#define SIZEOF_OFF_T $ac_cv_sizeof_off_t -_ACEOF - - -{ $as_echo "$as_me:$LINENO: checking whether to enable large file support" >&5 -$as_echo_n "checking whether to enable large file support... " >&6; } -if test "$have_long_long" = yes -then -if test "$ac_cv_sizeof_off_t" -gt "$ac_cv_sizeof_long" -a \ - "$ac_cv_sizeof_long_long" -ge "$ac_cv_sizeof_off_t"; then - -cat >>confdefs.h <<\_ACEOF -#define HAVE_LARGEFILE_SUPPORT 1 -_ACEOF - - { $as_echo "$as_me:$LINENO: result: yes" >&5 -$as_echo "yes" >&6; } -else - { $as_echo "$as_me:$LINENO: result: no" >&5 -$as_echo "no" >&6; } -fi -else - { $as_echo "$as_me:$LINENO: result: no" >&5 -$as_echo "no" >&6; } -fi - -# AC_CHECK_SIZEOF() doesn't include . -{ $as_echo "$as_me:$LINENO: checking size of time_t" >&5 -$as_echo_n "checking size of time_t... " >&6; } -if test "${ac_cv_sizeof_time_t+set}" = set; then - $as_echo_n "(cached) " >&6 -else - if test "$cross_compiling" = yes; then - ac_cv_sizeof_time_t=4 -else - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -#include -#include -main() -{ - FILE *f=fopen("conftestval", "w"); - if (!f) exit(1); - fprintf(f, "%d\n", sizeof(time_t)); - exit(0); -} -_ACEOF -rm -f conftest$ac_exeext -if { (ac_try="$ac_link" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" -$as_echo "$ac_try_echo") >&5 - (eval "$ac_link") 2>&5 - ac_status=$? - $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { ac_try='./conftest$ac_exeext' - { (case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" -$as_echo "$ac_try_echo") >&5 - (eval "$ac_try") 2>&5 - ac_status=$? - $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); }; }; then - ac_cv_sizeof_time_t=`cat conftestval` -else - $as_echo "$as_me: program exited with status $ac_status" >&5 -$as_echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - -( exit $ac_status ) -ac_cv_sizeof_time_t=0 -fi -rm -rf conftest.dSYM -rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext conftest.$ac_objext conftest.$ac_ext -fi - - - -fi - -{ $as_echo "$as_me:$LINENO: result: $ac_cv_sizeof_time_t" >&5 -$as_echo "$ac_cv_sizeof_time_t" >&6; } - -cat >>confdefs.h <<_ACEOF -#define SIZEOF_TIME_T $ac_cv_sizeof_time_t -_ACEOF - - - -# if have pthread_t then define SIZEOF_PTHREAD_T -ac_save_cc="$CC" -if test "$ac_cv_kpthread" = "yes" -then CC="$CC -Kpthread" -elif test "$ac_cv_kthread" = "yes" -then CC="$CC -Kthread" -elif test "$ac_cv_pthread" = "yes" -then CC="$CC -pthread" -fi -{ $as_echo "$as_me:$LINENO: checking for pthread_t" >&5 -$as_echo_n "checking for pthread_t... " >&6; } -have_pthread_t=no -cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -#include -int -main () -{ -pthread_t x; x = *(pthread_t*)0; - ; - return 0; -} -_ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" -$as_echo "$ac_try_echo") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - have_pthread_t=yes -else - $as_echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - -fi - -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext -{ $as_echo "$as_me:$LINENO: result: $have_pthread_t" >&5 -$as_echo "$have_pthread_t" >&6; } -if test "$have_pthread_t" = yes ; then - # AC_CHECK_SIZEOF() doesn't include . - { $as_echo "$as_me:$LINENO: checking size of pthread_t" >&5 -$as_echo_n "checking size of pthread_t... " >&6; } - if test "${ac_cv_sizeof_pthread_t+set}" = set; then - $as_echo_n "(cached) " >&6 -else - if test "$cross_compiling" = yes; then - ac_cv_sizeof_pthread_t=4 -else - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -#include -#include - main() - { - FILE *f=fopen("conftestval", "w"); - if (!f) exit(1); - fprintf(f, "%d\n", sizeof(pthread_t)); - exit(0); - } -_ACEOF -rm -f conftest$ac_exeext -if { (ac_try="$ac_link" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" -$as_echo "$ac_try_echo") >&5 - (eval "$ac_link") 2>&5 - ac_status=$? - $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { ac_try='./conftest$ac_exeext' - { (case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" -$as_echo "$ac_try_echo") >&5 - (eval "$ac_try") 2>&5 - ac_status=$? - $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); }; }; then - ac_cv_sizeof_pthread_t=`cat conftestval` -else - $as_echo "$as_me: program exited with status $ac_status" >&5 -$as_echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - -( exit $ac_status ) -ac_cv_sizeof_pthread_t=0 -fi -rm -rf conftest.dSYM -rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext conftest.$ac_objext conftest.$ac_ext -fi - - - -fi - - { $as_echo "$as_me:$LINENO: result: $ac_cv_sizeof_pthread_t" >&5 -$as_echo "$ac_cv_sizeof_pthread_t" >&6; } - -cat >>confdefs.h <<_ACEOF -#define SIZEOF_PTHREAD_T $ac_cv_sizeof_pthread_t -_ACEOF - -fi -CC="$ac_save_cc" - -{ $as_echo "$as_me:$LINENO: checking for --enable-toolbox-glue" >&5 -$as_echo_n "checking for --enable-toolbox-glue... " >&6; } -# Check whether --enable-toolbox-glue was given. -if test "${enable_toolbox_glue+set}" = set; then - enableval=$enable_toolbox_glue; -fi - - -if test -z "$enable_toolbox_glue" -then - case $ac_sys_system/$ac_sys_release in - Darwin/*) - enable_toolbox_glue="yes";; - *) - enable_toolbox_glue="no";; - esac -fi -case "$enable_toolbox_glue" in -yes) - extra_machdep_objs="Python/mactoolboxglue.o" - extra_undefs="-u _PyMac_Error" - -cat >>confdefs.h <<\_ACEOF -#define USE_TOOLBOX_OBJECT_GLUE 1 -_ACEOF - - ;; -*) - extra_machdep_objs="" - extra_undefs="" - ;; -esac -{ $as_echo "$as_me:$LINENO: result: $enable_toolbox_glue" >&5 -$as_echo "$enable_toolbox_glue" >&6; } - - - -case $ac_sys_system/$ac_sys_release in - Darwin/[01567]\..*) - OTHER_LIBTOOL_OPT="-prebind -seg1addr 0x10000000" - ;; - Darwin/*) - OTHER_LIBTOOL_OPT="" - ;; -esac - - -ARCH_RUN_32BIT="" - -case $ac_sys_system/$ac_sys_release in - Darwin/[01567]\..*) - LIBTOOL_CRUFT="-framework System -lcc_dynamic" - if test "${enable_universalsdk}"; then - : - else - LIBTOOL_CRUFT="${LIBTOOL_CRUFT} -arch_only `/usr/bin/arch`" - fi - LIBTOOL_CRUFT=$LIBTOOL_CRUFT' -install_name $(PYTHONFRAMEWORKINSTALLDIR)/Versions/$(VERSION)/$(PYTHONFRAMEWORK)' - LIBTOOL_CRUFT=$LIBTOOL_CRUFT' -compatibility_version $(VERSION) -current_version $(VERSION)';; - Darwin/*) - gcc_version=`gcc -dumpversion` - if test ${gcc_version} '<' 4.0 - then - LIBTOOL_CRUFT="-lcc_dynamic" - else - LIBTOOL_CRUFT="" - fi - if test "$cross_compiling" = yes; then - ac_osx_32bit=yes -else - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ - - #include - int main(int argc, char*argv[]) - { - if (sizeof(long) == 4) { - return 0; - } else { - return 1; - } - } - -_ACEOF -rm -f conftest$ac_exeext -if { (ac_try="$ac_link" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" -$as_echo "$ac_try_echo") >&5 - (eval "$ac_link") 2>&5 - ac_status=$? - $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { ac_try='./conftest$ac_exeext' - { (case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" -$as_echo "$ac_try_echo") >&5 - (eval "$ac_try") 2>&5 - ac_status=$? - $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); }; }; then - ac_osx_32bit=yes -else - $as_echo "$as_me: program exited with status $ac_status" >&5 -$as_echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - -( exit $ac_status ) -ac_osx_32bit=no -fi -rm -rf conftest.dSYM -rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext conftest.$ac_objext conftest.$ac_ext -fi - - - - if test "${ac_osx_32bit}" = "yes"; then - case `/usr/bin/arch` in - i386) - MACOSX_DEFAULT_ARCH="i386" - ;; - ppc) - MACOSX_DEFAULT_ARCH="ppc" - ;; - *) - { { $as_echo "$as_me:$LINENO: error: Unexpected output of 'arch' on OSX" >&5 -$as_echo "$as_me: error: Unexpected output of 'arch' on OSX" >&2;} - { (exit 1); exit 1; }; } - ;; - esac - else - case `/usr/bin/arch` in - i386) - MACOSX_DEFAULT_ARCH="x86_64" - ;; - ppc) - MACOSX_DEFAULT_ARCH="ppc64" - ;; - *) - { { $as_echo "$as_me:$LINENO: error: Unexpected output of 'arch' on OSX" >&5 -$as_echo "$as_me: error: Unexpected output of 'arch' on OSX" >&2;} - { (exit 1); exit 1; }; } - ;; - esac - - #ARCH_RUN_32BIT="true" - fi - - LIBTOOL_CRUFT=$LIBTOOL_CRUFT" -lSystem -lSystemStubs -arch_only ${MACOSX_DEFAULT_ARCH}" - LIBTOOL_CRUFT=$LIBTOOL_CRUFT' -install_name $(PYTHONFRAMEWORKINSTALLDIR)/Versions/$(VERSION)/$(PYTHONFRAMEWORK)' - LIBTOOL_CRUFT=$LIBTOOL_CRUFT' -compatibility_version $(VERSION) -current_version $(VERSION)';; -esac - -{ $as_echo "$as_me:$LINENO: checking for --enable-framework" >&5 -$as_echo_n "checking for --enable-framework... " >&6; } -if test "$enable_framework" -then - BASECFLAGS="$BASECFLAGS -fno-common -dynamic" - # -F. is needed to allow linking to the framework while - # in the build location. - -cat >>confdefs.h <<\_ACEOF -#define WITH_NEXT_FRAMEWORK 1 -_ACEOF - - { $as_echo "$as_me:$LINENO: result: yes" >&5 -$as_echo "yes" >&6; } - if test $enable_shared = "yes" - then - { { $as_echo "$as_me:$LINENO: error: Specifying both --enable-shared and --enable-framework is not supported, use only --enable-framework instead. See Mac/README." >&5 -$as_echo "$as_me: error: Specifying both --enable-shared and --enable-framework is not supported, use only --enable-framework instead. See Mac/README." >&2;} - { (exit 1); exit 1; }; } - fi -else - { $as_echo "$as_me:$LINENO: result: no" >&5 -$as_echo "no" >&6; } -fi - -{ $as_echo "$as_me:$LINENO: checking for dyld" >&5 -$as_echo_n "checking for dyld... " >&6; } -case $ac_sys_system/$ac_sys_release in - Darwin/*) - -cat >>confdefs.h <<\_ACEOF -#define WITH_DYLD 1 -_ACEOF - - { $as_echo "$as_me:$LINENO: result: always on for Darwin" >&5 -$as_echo "always on for Darwin" >&6; } - ;; - *) - { $as_echo "$as_me:$LINENO: result: no" >&5 -$as_echo "no" >&6; } - ;; -esac - -# Set info about shared libraries. - - - - - -# SO is the extension of shared libraries `(including the dot!) -# -- usually .so, .sl on HP-UX, .dll on Cygwin -{ $as_echo "$as_me:$LINENO: checking SO" >&5 -$as_echo_n "checking SO... " >&6; } -if test -z "$SO" -then - case $ac_sys_system in - hp*|HP*) - case `uname -m` in - ia64) SO=.so;; - *) SO=.sl;; - esac - ;; - CYGWIN*) SO=.dll;; - *) SO=.so;; - esac -else - # this might also be a termcap variable, see #610332 - echo - echo '=====================================================================' - echo '+ +' - echo '+ WARNING: You have set SO in your environment. +' - echo '+ Do you really mean to change the extension for shared libraries? +' - echo '+ Continuing in 10 seconds to let you to ponder. +' - echo '+ +' - echo '=====================================================================' - sleep 10 -fi -{ $as_echo "$as_me:$LINENO: result: $SO" >&5 -$as_echo "$SO" >&6; } - - -cat >>confdefs.h <<_ACEOF -#define SHLIB_EXT "$SO" -_ACEOF - -# LDSHARED is the ld *command* used to create shared library -# -- "cc -G" on SunOS 5.x, "ld -shared" on IRIX 5 -# (Shared libraries in this instance are shared modules to be loaded into -# Python, as opposed to building Python itself as a shared library.) -{ $as_echo "$as_me:$LINENO: checking LDSHARED" >&5 -$as_echo_n "checking LDSHARED... " >&6; } -if test -z "$LDSHARED" -then - case $ac_sys_system/$ac_sys_release in - AIX*) - BLDSHARED="\$(srcdir)/Modules/ld_so_aix \$(CC) -bI:Modules/python.exp" - LDSHARED="\$(BINLIBDEST)/config/ld_so_aix \$(CC) -bI:\$(BINLIBDEST)/config/python.exp" - ;; - BeOS*) - BLDSHARED="\$(srcdir)/Modules/ld_so_beos $LDLIBRARY" - LDSHARED="\$(BINLIBDEST)/config/ld_so_beos \$(LIBDIR)/$LDLIBRARY" - ;; - IRIX/5*) LDSHARED="ld -shared";; - IRIX*/6*) LDSHARED="ld ${SGI_ABI} -shared -all";; - SunOS/5*) - if test "$GCC" = "yes" - then LDSHARED='$(CC) -shared' - else LDSHARED='$(CC) -G'; - fi ;; - hp*|HP*) - if test "$GCC" = "yes" - then LDSHARED='$(CC) -shared' - else LDSHARED='ld -b'; - fi ;; - OSF*) LDSHARED="ld -shared -expect_unresolved \"*\"";; - Darwin/1.3*) - LDSHARED='$(CC) $(LDFLAGS) -bundle' - if test "$enable_framework" ; then - # Link against the framework. All externals should be defined. - BLDSHARED="$LDSHARED "'$(PYTHONFRAMEWORKDIR)/Versions/$(VERSION)/$(PYTHONFRAMEWORK)' - LDSHARED="$LDSHARED "'$(PYTHONFRAMEWORKPREFIX)/$(PYTHONFRAMEWORKDIR)/Versions/$(VERSION)/$(PYTHONFRAMEWORK)' - else - # No framework. Ignore undefined symbols, assuming they come from Python - LDSHARED="$LDSHARED -undefined suppress" - fi ;; - Darwin/1.4*|Darwin/5.*|Darwin/6.*) - LDSHARED='$(CC) $(LDFLAGS) -bundle' - if test "$enable_framework" ; then - # Link against the framework. All externals should be defined. - BLDSHARED="$LDSHARED "'$(PYTHONFRAMEWORKDIR)/Versions/$(VERSION)/$(PYTHONFRAMEWORK)' - LDSHARED="$LDSHARED "'$(PYTHONFRAMEWORKPREFIX)/$(PYTHONFRAMEWORKDIR)/Versions/$(VERSION)/$(PYTHONFRAMEWORK)' - else - # No framework, use the Python app as bundle-loader - BLDSHARED="$LDSHARED "'-bundle_loader $(BUILDPYTHON)' - LDSHARED="$LDSHARED "'-bundle_loader $(BINDIR)/python$(VERSION)$(EXE)' - fi ;; - Darwin/*) - # Use -undefined dynamic_lookup whenever possible (10.3 and later). - # This allows an extension to be used in any Python - - if test ${MACOSX_DEPLOYMENT_TARGET} '>' 10.2 - then - if test "${enable_universalsdk}"; then - LDFLAGS="${UNIVERSAL_ARCH_FLAGS} -isysroot ${UNIVERSALSDK} ${LDFLAGS}" - fi - LDSHARED='$(CC) $(LDFLAGS) -bundle -undefined dynamic_lookup' - BLDSHARED="$LDSHARED" - else - LDSHARED='$(CC) $(LDFLAGS) -bundle' - if test "$enable_framework" ; then - # Link against the framework. All externals should be defined. - BLDSHARED="$LDSHARED "'$(PYTHONFRAMEWORKDIR)/Versions/$(VERSION)/$(PYTHONFRAMEWORK)' - LDSHARED="$LDSHARED "'$(PYTHONFRAMEWORKPREFIX)/$(PYTHONFRAMEWORKDIR)/Versions/$(VERSION)/$(PYTHONFRAMEWORK)' - else - # No framework, use the Python app as bundle-loader - BLDSHARED="$LDSHARED "'-bundle_loader $(BUILDPYTHON)' - LDSHARED="$LDSHARED "'-bundle_loader $(BINDIR)/python$(VERSION)$(EXE)' - fi - fi - ;; - Linux*|GNU*|QNX*) LDSHARED='$(CC) -shared';; - BSD/OS*/4*) LDSHARED="gcc -shared";; - FreeBSD*) - if [ "`$CC -dM -E - &5 -$as_echo "$LDSHARED" >&6; } -BLDSHARED=${BLDSHARED-$LDSHARED} -# CCSHARED are the C *flags* used to create objects to go into a shared -# library (module) -- this is only needed for a few systems -{ $as_echo "$as_me:$LINENO: checking CCSHARED" >&5 -$as_echo_n "checking CCSHARED... " >&6; } -if test -z "$CCSHARED" -then - case $ac_sys_system/$ac_sys_release in - SunOS*) if test "$GCC" = yes; - then CCSHARED="-fPIC"; - elif test `uname -p` = sparc; - then CCSHARED="-xcode=pic32"; - else CCSHARED="-Kpic"; - fi;; - hp*|HP*) if test "$GCC" = yes; - then CCSHARED="-fPIC"; - else CCSHARED="+z"; - fi;; - Linux*|GNU*) CCSHARED="-fPIC";; - BSD/OS*/4*) CCSHARED="-fpic";; - FreeBSD*|NetBSD*|OpenBSD*|DragonFly*) CCSHARED="-fPIC";; - OpenUNIX*|UnixWare*) - if test "$GCC" = "yes" - then CCSHARED="-fPIC" - else CCSHARED="-KPIC" - fi;; - SCO_SV*) - if test "$GCC" = "yes" - then CCSHARED="-fPIC" - else CCSHARED="-Kpic -belf" - fi;; - Monterey*) CCSHARED="-G";; - IRIX*/6*) case $CC in - *gcc*) CCSHARED="-shared";; - *) CCSHARED="";; - esac;; - atheos*) CCSHARED="-fPIC";; - esac -fi -{ $as_echo "$as_me:$LINENO: result: $CCSHARED" >&5 -$as_echo "$CCSHARED" >&6; } -# LINKFORSHARED are the flags passed to the $(CC) command that links -# the python executable -- this is only needed for a few systems -{ $as_echo "$as_me:$LINENO: checking LINKFORSHARED" >&5 -$as_echo_n "checking LINKFORSHARED... " >&6; } -if test -z "$LINKFORSHARED" -then - case $ac_sys_system/$ac_sys_release in - AIX*) LINKFORSHARED='-Wl,-bE:Modules/python.exp -lld';; - hp*|HP*) - 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";; - # -u libsys_s pulls in all symbols in libsys - Darwin/*) - # -u _PyMac_Error is needed to pull in the mac toolbox glue, - # which is - # not used by the core itself but which needs to be in the core so - # that dynamically loaded extension modules have access to it. - # -prebind is no longer used, because it actually seems to give a - # slowdown in stead of a speedup, maybe due to the large number of - # dynamic loads Python does. - - LINKFORSHARED="$extra_undefs" - if test "$enable_framework" - then - LINKFORSHARED="$LINKFORSHARED "'$(PYTHONFRAMEWORKDIR)/Versions/$(VERSION)/$(PYTHONFRAMEWORK)' - fi - LINKFORSHARED="$LINKFORSHARED";; - OpenUNIX*|UnixWare*) LINKFORSHARED="-Wl,-Bexport";; - SCO_SV*) LINKFORSHARED="-Wl,-Bexport";; - ReliantUNIX*) LINKFORSHARED="-W1 -Blargedynsym";; - FreeBSD*|NetBSD*|OpenBSD*|DragonFly*) - if [ "`$CC -dM -E - &1 | grep export-dynamic >/dev/null - then - LINKFORSHARED="-Xlinker --export-dynamic" - fi;; - esac;; - CYGWIN*) - if test $enable_shared = "no" - then - LINKFORSHARED='-Wl,--out-implib=$(LDLIBRARY)' - fi;; - QNX*) - # -Wl,-E causes the symbols to be added to the dynamic - # symbol table so that they can be found when a module - # is loaded. -N 2048K causes the stack size to be set - # to 2048 kilobytes so that the stack doesn't overflow - # when running test_compile.py. - LINKFORSHARED='-Wl,-E -N 2048K';; - esac -fi -{ $as_echo "$as_me:$LINENO: result: $LINKFORSHARED" >&5 -$as_echo "$LINKFORSHARED" >&6; } - - - -{ $as_echo "$as_me:$LINENO: checking CFLAGSFORSHARED" >&5 -$as_echo_n "checking CFLAGSFORSHARED... " >&6; } -if test ! "$LIBRARY" = "$LDLIBRARY" -then - case $ac_sys_system in - CYGWIN*) - # Cygwin needs CCSHARED when building extension DLLs - # but not when building the interpreter DLL. - CFLAGSFORSHARED='';; - *) - CFLAGSFORSHARED='$(CCSHARED)' - esac -fi -{ $as_echo "$as_me:$LINENO: result: $CFLAGSFORSHARED" >&5 -$as_echo "$CFLAGSFORSHARED" >&6; } - -# SHLIBS are libraries (except -lc and -lm) to link to the python shared -# library (with --enable-shared). -# For platforms on which shared libraries are not allowed to have unresolved -# symbols, this must be set to $(LIBS) (expanded by make). We do this even -# if it is not required, since it creates a dependency of the shared library -# to LIBS. This, in turn, means that applications linking the shared libpython -# don't need to link LIBS explicitly. The default should be only changed -# on systems where this approach causes problems. - -{ $as_echo "$as_me:$LINENO: checking SHLIBS" >&5 -$as_echo_n "checking SHLIBS... " >&6; } -case "$ac_sys_system" in - *) - SHLIBS='$(LIBS)';; -esac -{ $as_echo "$as_me:$LINENO: result: $SHLIBS" >&5 -$as_echo "$SHLIBS" >&6; } - - -# checks for libraries - -{ $as_echo "$as_me:$LINENO: checking for dlopen in -ldl" >&5 -$as_echo_n "checking for dlopen in -ldl... " >&6; } -if test "${ac_cv_lib_dl_dlopen+set}" = set; then - $as_echo_n "(cached) " >&6 -else - ac_check_lib_save_LIBS=$LIBS -LIBS="-ldl $LIBS" -cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ - -/* Override any GCC internal prototype to avoid an error. - Use char because int might match the return type of a GCC - builtin and then its argument prototype would still apply. */ -#ifdef __cplusplus -extern "C" -#endif -char dlopen (); -int -main () -{ -return dlopen (); - ; - return 0; -} -_ACEOF -rm -f conftest.$ac_objext conftest$ac_exeext -if { (ac_try="$ac_link" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" -$as_echo "$ac_try_echo") >&5 - (eval "$ac_link") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest$ac_exeext && { - test "$cross_compiling" = yes || - $as_test_x conftest$ac_exeext - }; then - ac_cv_lib_dl_dlopen=yes -else - $as_echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - ac_cv_lib_dl_dlopen=no -fi - -rm -rf conftest.dSYM -rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \ - conftest$ac_exeext conftest.$ac_ext -LIBS=$ac_check_lib_save_LIBS -fi -{ $as_echo "$as_me:$LINENO: result: $ac_cv_lib_dl_dlopen" >&5 -$as_echo "$ac_cv_lib_dl_dlopen" >&6; } -if test "x$ac_cv_lib_dl_dlopen" = x""yes; then - cat >>confdefs.h <<_ACEOF -#define HAVE_LIBDL 1 -_ACEOF - - LIBS="-ldl $LIBS" - -fi - # Dynamic linking for SunOS/Solaris and SYSV - -{ $as_echo "$as_me:$LINENO: checking for shl_load in -ldld" >&5 -$as_echo_n "checking for shl_load in -ldld... " >&6; } -if test "${ac_cv_lib_dld_shl_load+set}" = set; then - $as_echo_n "(cached) " >&6 -else - ac_check_lib_save_LIBS=$LIBS -LIBS="-ldld $LIBS" -cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ - -/* Override any GCC internal prototype to avoid an error. - Use char because int might match the return type of a GCC - builtin and then its argument prototype would still apply. */ -#ifdef __cplusplus -extern "C" -#endif -char shl_load (); -int -main () -{ -return shl_load (); - ; - return 0; -} -_ACEOF -rm -f conftest.$ac_objext conftest$ac_exeext -if { (ac_try="$ac_link" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" -$as_echo "$ac_try_echo") >&5 - (eval "$ac_link") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest$ac_exeext && { - test "$cross_compiling" = yes || - $as_test_x conftest$ac_exeext - }; then - ac_cv_lib_dld_shl_load=yes -else - $as_echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - ac_cv_lib_dld_shl_load=no -fi - -rm -rf conftest.dSYM -rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \ - conftest$ac_exeext conftest.$ac_ext -LIBS=$ac_check_lib_save_LIBS -fi -{ $as_echo "$as_me:$LINENO: result: $ac_cv_lib_dld_shl_load" >&5 -$as_echo "$ac_cv_lib_dld_shl_load" >&6; } -if test "x$ac_cv_lib_dld_shl_load" = x""yes; then - cat >>confdefs.h <<_ACEOF -#define HAVE_LIBDLD 1 -_ACEOF - - LIBS="-ldld $LIBS" - -fi - # Dynamic linking for HP-UX - -# only check for sem_init if thread support is requested -if test "$with_threads" = "yes" -o -z "$with_threads"; then - { $as_echo "$as_me:$LINENO: checking for library containing sem_init" >&5 -$as_echo_n "checking for library containing sem_init... " >&6; } -if test "${ac_cv_search_sem_init+set}" = set; then - $as_echo_n "(cached) " >&6 -else - ac_func_search_save_LIBS=$LIBS -cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ - -/* Override any GCC internal prototype to avoid an error. - Use char because int might match the return type of a GCC - builtin and then its argument prototype would still apply. */ -#ifdef __cplusplus -extern "C" -#endif -char sem_init (); -int -main () -{ -return sem_init (); - ; - return 0; -} -_ACEOF -for ac_lib in '' pthread rt posix4; do - if test -z "$ac_lib"; then - ac_res="none required" - else - ac_res=-l$ac_lib - LIBS="-l$ac_lib $ac_func_search_save_LIBS" - fi - rm -f conftest.$ac_objext conftest$ac_exeext -if { (ac_try="$ac_link" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" -$as_echo "$ac_try_echo") >&5 - (eval "$ac_link") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest$ac_exeext && { - test "$cross_compiling" = yes || - $as_test_x conftest$ac_exeext - }; then - ac_cv_search_sem_init=$ac_res -else - $as_echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - -fi - -rm -rf conftest.dSYM -rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \ - conftest$ac_exeext - if test "${ac_cv_search_sem_init+set}" = set; then - break -fi -done -if test "${ac_cv_search_sem_init+set}" = set; then - : -else - ac_cv_search_sem_init=no -fi -rm conftest.$ac_ext -LIBS=$ac_func_search_save_LIBS -fi -{ $as_echo "$as_me:$LINENO: result: $ac_cv_search_sem_init" >&5 -$as_echo "$ac_cv_search_sem_init" >&6; } -ac_res=$ac_cv_search_sem_init -if test "$ac_res" != no; then - test "$ac_res" = "none required" || LIBS="$ac_res $LIBS" - -fi - # 'Real Time' functions on Solaris - # posix4 on Solaris 2.6 - # pthread (first!) on Linux -fi - -# check if we need libintl for locale functions -{ $as_echo "$as_me:$LINENO: checking for textdomain in -lintl" >&5 -$as_echo_n "checking for textdomain in -lintl... " >&6; } -if test "${ac_cv_lib_intl_textdomain+set}" = set; then - $as_echo_n "(cached) " >&6 -else - ac_check_lib_save_LIBS=$LIBS -LIBS="-lintl $LIBS" -cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ - -/* Override any GCC internal prototype to avoid an error. - Use char because int might match the return type of a GCC - builtin and then its argument prototype would still apply. */ -#ifdef __cplusplus -extern "C" -#endif -char textdomain (); -int -main () -{ -return textdomain (); - ; - return 0; -} -_ACEOF -rm -f conftest.$ac_objext conftest$ac_exeext -if { (ac_try="$ac_link" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" -$as_echo "$ac_try_echo") >&5 - (eval "$ac_link") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest$ac_exeext && { - test "$cross_compiling" = yes || - $as_test_x conftest$ac_exeext - }; then - ac_cv_lib_intl_textdomain=yes -else - $as_echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - ac_cv_lib_intl_textdomain=no -fi - -rm -rf conftest.dSYM -rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \ - conftest$ac_exeext conftest.$ac_ext -LIBS=$ac_check_lib_save_LIBS -fi -{ $as_echo "$as_me:$LINENO: result: $ac_cv_lib_intl_textdomain" >&5 -$as_echo "$ac_cv_lib_intl_textdomain" >&6; } -if test "x$ac_cv_lib_intl_textdomain" = x""yes; then - -cat >>confdefs.h <<\_ACEOF -#define WITH_LIBINTL 1 -_ACEOF - -fi - - -# checks for system dependent C++ extensions support -case "$ac_sys_system" in - AIX*) { $as_echo "$as_me:$LINENO: checking for genuine AIX C++ extensions support" >&5 -$as_echo_n "checking for genuine AIX C++ extensions support... " >&6; } - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -#include "/usr/lpp/xlC/include/load.h" -int -main () -{ -loadAndInit("", 0, "") - ; - return 0; -} -_ACEOF -rm -f conftest.$ac_objext conftest$ac_exeext -if { (ac_try="$ac_link" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" -$as_echo "$ac_try_echo") >&5 - (eval "$ac_link") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest$ac_exeext && { - test "$cross_compiling" = yes || - $as_test_x conftest$ac_exeext - }; then - -cat >>confdefs.h <<\_ACEOF -#define AIX_GENUINE_CPLUSPLUS 1 -_ACEOF - - { $as_echo "$as_me:$LINENO: result: yes" >&5 -$as_echo "yes" >&6; } -else - $as_echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - { $as_echo "$as_me:$LINENO: result: no" >&5 -$as_echo "no" >&6; } -fi - -rm -rf conftest.dSYM -rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \ - conftest$ac_exeext conftest.$ac_ext;; - *) ;; -esac - -# Most SVR4 platforms (e.g. Solaris) need -lsocket and -lnsl. -# BeOS' sockets are stashed in libnet. -{ $as_echo "$as_me:$LINENO: checking for t_open in -lnsl" >&5 -$as_echo_n "checking for t_open in -lnsl... " >&6; } -if test "${ac_cv_lib_nsl_t_open+set}" = set; then - $as_echo_n "(cached) " >&6 -else - ac_check_lib_save_LIBS=$LIBS -LIBS="-lnsl $LIBS" -cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ - -/* Override any GCC internal prototype to avoid an error. - Use char because int might match the return type of a GCC - builtin and then its argument prototype would still apply. */ -#ifdef __cplusplus -extern "C" -#endif -char t_open (); -int -main () -{ -return t_open (); - ; - return 0; -} -_ACEOF -rm -f conftest.$ac_objext conftest$ac_exeext -if { (ac_try="$ac_link" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" -$as_echo "$ac_try_echo") >&5 - (eval "$ac_link") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest$ac_exeext && { - test "$cross_compiling" = yes || - $as_test_x conftest$ac_exeext - }; then - ac_cv_lib_nsl_t_open=yes -else - $as_echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - ac_cv_lib_nsl_t_open=no -fi - -rm -rf conftest.dSYM -rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \ - conftest$ac_exeext conftest.$ac_ext -LIBS=$ac_check_lib_save_LIBS -fi -{ $as_echo "$as_me:$LINENO: result: $ac_cv_lib_nsl_t_open" >&5 -$as_echo "$ac_cv_lib_nsl_t_open" >&6; } -if test "x$ac_cv_lib_nsl_t_open" = x""yes; then - LIBS="-lnsl $LIBS" -fi - # SVR4 -{ $as_echo "$as_me:$LINENO: checking for socket in -lsocket" >&5 -$as_echo_n "checking for socket in -lsocket... " >&6; } -if test "${ac_cv_lib_socket_socket+set}" = set; then - $as_echo_n "(cached) " >&6 -else - ac_check_lib_save_LIBS=$LIBS -LIBS="-lsocket $LIBS $LIBS" -cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ - -/* Override any GCC internal prototype to avoid an error. - Use char because int might match the return type of a GCC - builtin and then its argument prototype would still apply. */ -#ifdef __cplusplus -extern "C" -#endif -char socket (); -int -main () -{ -return socket (); - ; - return 0; -} -_ACEOF -rm -f conftest.$ac_objext conftest$ac_exeext -if { (ac_try="$ac_link" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" -$as_echo "$ac_try_echo") >&5 - (eval "$ac_link") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest$ac_exeext && { - test "$cross_compiling" = yes || - $as_test_x conftest$ac_exeext - }; then - ac_cv_lib_socket_socket=yes -else - $as_echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - ac_cv_lib_socket_socket=no -fi - -rm -rf conftest.dSYM -rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \ - conftest$ac_exeext conftest.$ac_ext -LIBS=$ac_check_lib_save_LIBS -fi -{ $as_echo "$as_me:$LINENO: result: $ac_cv_lib_socket_socket" >&5 -$as_echo "$ac_cv_lib_socket_socket" >&6; } -if test "x$ac_cv_lib_socket_socket" = x""yes; then - LIBS="-lsocket $LIBS" -fi - # SVR4 sockets - -case "$ac_sys_system" in -BeOS*) -{ $as_echo "$as_me:$LINENO: checking for socket in -lnet" >&5 -$as_echo_n "checking for socket in -lnet... " >&6; } -if test "${ac_cv_lib_net_socket+set}" = set; then - $as_echo_n "(cached) " >&6 -else - ac_check_lib_save_LIBS=$LIBS -LIBS="-lnet $LIBS $LIBS" -cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ - -/* Override any GCC internal prototype to avoid an error. - Use char because int might match the return type of a GCC - builtin and then its argument prototype would still apply. */ -#ifdef __cplusplus -extern "C" -#endif -char socket (); -int -main () -{ -return socket (); - ; - return 0; -} -_ACEOF -rm -f conftest.$ac_objext conftest$ac_exeext -if { (ac_try="$ac_link" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" -$as_echo "$ac_try_echo") >&5 - (eval "$ac_link") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest$ac_exeext && { - test "$cross_compiling" = yes || - $as_test_x conftest$ac_exeext - }; then - ac_cv_lib_net_socket=yes -else - $as_echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - ac_cv_lib_net_socket=no -fi - -rm -rf conftest.dSYM -rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \ - conftest$ac_exeext conftest.$ac_ext -LIBS=$ac_check_lib_save_LIBS -fi -{ $as_echo "$as_me:$LINENO: result: $ac_cv_lib_net_socket" >&5 -$as_echo "$ac_cv_lib_net_socket" >&6; } -if test "x$ac_cv_lib_net_socket" = x""yes; then - LIBS="-lnet $LIBS" -fi - # BeOS -;; -esac - -{ $as_echo "$as_me:$LINENO: checking for --with-libs" >&5 -$as_echo_n "checking for --with-libs... " >&6; } - -# Check whether --with-libs was given. -if test "${with_libs+set}" = set; then - withval=$with_libs; -{ $as_echo "$as_me:$LINENO: result: $withval" >&5 -$as_echo "$withval" >&6; } -LIBS="$withval $LIBS" - -else - { $as_echo "$as_me:$LINENO: result: no" >&5 -$as_echo "no" >&6; } -fi - - -# Check for use of the system libffi library -{ $as_echo "$as_me:$LINENO: checking for --with-system-ffi" >&5 -$as_echo_n "checking for --with-system-ffi... " >&6; } - -# Check whether --with-system_ffi was given. -if test "${with_system_ffi+set}" = set; then - withval=$with_system_ffi; -fi - - -{ $as_echo "$as_me:$LINENO: result: $with_system_ffi" >&5 -$as_echo "$with_system_ffi" >&6; } - -# Determine if signalmodule should be used. - - -{ $as_echo "$as_me:$LINENO: checking for --with-signal-module" >&5 -$as_echo_n "checking for --with-signal-module... " >&6; } - -# Check whether --with-signal-module was given. -if test "${with_signal_module+set}" = set; then - withval=$with_signal_module; -fi - - -if test -z "$with_signal_module" -then with_signal_module="yes" -fi -{ $as_echo "$as_me:$LINENO: result: $with_signal_module" >&5 -$as_echo "$with_signal_module" >&6; } - -if test "${with_signal_module}" = "yes"; then - USE_SIGNAL_MODULE="" - SIGNAL_OBJS="" -else - USE_SIGNAL_MODULE="#" - SIGNAL_OBJS="Parser/intrcheck.o Python/sigcheck.o" -fi - -# This is used to generate Setup.config - -USE_THREAD_MODULE="" - -{ $as_echo "$as_me:$LINENO: checking for --with-dec-threads" >&5 -$as_echo_n "checking for --with-dec-threads... " >&6; } - - -# Check whether --with-dec-threads was given. -if test "${with_dec_threads+set}" = set; then - withval=$with_dec_threads; -{ $as_echo "$as_me:$LINENO: result: $withval" >&5 -$as_echo "$withval" >&6; } -LDLAST=-threads -if test "${with_thread+set}" != set; then - with_thread="$withval"; -fi -else - { $as_echo "$as_me:$LINENO: result: no" >&5 -$as_echo "no" >&6; } -fi - - -# Templates for things AC_DEFINEd more than once. -# For a single AC_DEFINE, no template is needed. - - - - - - - -{ $as_echo "$as_me:$LINENO: checking for --with-threads" >&5 -$as_echo_n "checking for --with-threads... " >&6; } - -# Check whether --with-threads was given. -if test "${with_threads+set}" = set; then - withval=$with_threads; -fi - - -# --with-thread is deprecated, but check for it anyway - -# Check whether --with-thread was given. -if test "${with_thread+set}" = set; then - withval=$with_thread; with_threads=$with_thread -fi - - -if test -z "$with_threads" -then with_threads="yes" -fi -{ $as_echo "$as_me:$LINENO: result: $with_threads" >&5 -$as_echo "$with_threads" >&6; } - - -if test "$with_threads" = "no" -then - USE_THREAD_MODULE="#" -elif test "$ac_cv_pthread_is_default" = yes -then - cat >>confdefs.h <<\_ACEOF -#define WITH_THREAD 1 -_ACEOF - - # Defining _REENTRANT on system with POSIX threads should not hurt. - cat >>confdefs.h <<\_ACEOF -#define _REENTRANT 1 -_ACEOF - - posix_threads=yes - THREADOBJ="Python/thread.o" -elif test "$ac_cv_kpthread" = "yes" -then - CC="$CC -Kpthread" - if test "$ac_cv_cxx_thread" = "yes"; then - CXX="$CXX -Kpthread" - fi - cat >>confdefs.h <<\_ACEOF -#define WITH_THREAD 1 -_ACEOF - - posix_threads=yes - THREADOBJ="Python/thread.o" -elif test "$ac_cv_kthread" = "yes" -then - CC="$CC -Kthread" - if test "$ac_cv_cxx_thread" = "yes"; then - CXX="$CXX -Kthread" - fi - cat >>confdefs.h <<\_ACEOF -#define WITH_THREAD 1 -_ACEOF - - posix_threads=yes - THREADOBJ="Python/thread.o" -elif test "$ac_cv_pthread" = "yes" -then - CC="$CC -pthread" - if test "$ac_cv_cxx_thread" = "yes"; then - CXX="$CXX -pthread" - fi - cat >>confdefs.h <<\_ACEOF -#define WITH_THREAD 1 -_ACEOF - - posix_threads=yes - THREADOBJ="Python/thread.o" -else - if test ! -z "$with_threads" -a -d "$with_threads" - then LDFLAGS="$LDFLAGS -L$with_threads" - fi - if test ! -z "$withval" -a -d "$withval" - then LDFLAGS="$LDFLAGS -L$withval" - fi - - # According to the POSIX spec, a pthreads implementation must - # define _POSIX_THREADS in unistd.h. Some apparently don't - # (e.g. gnu pth with pthread emulation) - { $as_echo "$as_me:$LINENO: checking for _POSIX_THREADS in unistd.h" >&5 -$as_echo_n "checking for _POSIX_THREADS in unistd.h... " >&6; } - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ - -#include -#ifdef _POSIX_THREADS -yes -#endif - -_ACEOF -if (eval "$ac_cpp conftest.$ac_ext") 2>&5 | - $EGREP "yes" >/dev/null 2>&1; then - unistd_defines_pthreads=yes -else - unistd_defines_pthreads=no -fi -rm -f conftest* - - { $as_echo "$as_me:$LINENO: result: $unistd_defines_pthreads" >&5 -$as_echo "$unistd_defines_pthreads" >&6; } - - cat >>confdefs.h <<\_ACEOF -#define _REENTRANT 1 -_ACEOF - - if test "${ac_cv_header_cthreads_h+set}" = set; then - { $as_echo "$as_me:$LINENO: checking for cthreads.h" >&5 -$as_echo_n "checking for cthreads.h... " >&6; } -if test "${ac_cv_header_cthreads_h+set}" = set; then - $as_echo_n "(cached) " >&6 -fi -{ $as_echo "$as_me:$LINENO: result: $ac_cv_header_cthreads_h" >&5 -$as_echo "$ac_cv_header_cthreads_h" >&6; } -else - # Is the header compilable? -{ $as_echo "$as_me:$LINENO: checking cthreads.h usability" >&5 -$as_echo_n "checking cthreads.h usability... " >&6; } -cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -$ac_includes_default -#include -_ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" -$as_echo "$ac_try_echo") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - ac_header_compiler=yes -else - $as_echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - ac_header_compiler=no -fi - -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext -{ $as_echo "$as_me:$LINENO: result: $ac_header_compiler" >&5 -$as_echo "$ac_header_compiler" >&6; } - -# Is the header present? -{ $as_echo "$as_me:$LINENO: checking cthreads.h presence" >&5 -$as_echo_n "checking cthreads.h presence... " >&6; } -cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -#include -_ACEOF -if { (ac_try="$ac_cpp conftest.$ac_ext" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" -$as_echo "$ac_try_echo") >&5 - (eval "$ac_cpp conftest.$ac_ext") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } >/dev/null && { - test -z "$ac_c_preproc_warn_flag$ac_c_werror_flag" || - test ! -s conftest.err - }; then - ac_header_preproc=yes -else - $as_echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - ac_header_preproc=no -fi - -rm -f conftest.err conftest.$ac_ext -{ $as_echo "$as_me:$LINENO: result: $ac_header_preproc" >&5 -$as_echo "$ac_header_preproc" >&6; } - -# So? What about this header? -case $ac_header_compiler:$ac_header_preproc:$ac_c_preproc_warn_flag in - yes:no: ) - { $as_echo "$as_me:$LINENO: WARNING: cthreads.h: accepted by the compiler, rejected by the preprocessor!" >&5 -$as_echo "$as_me: WARNING: cthreads.h: accepted by the compiler, rejected by the preprocessor!" >&2;} - { $as_echo "$as_me:$LINENO: WARNING: cthreads.h: proceeding with the compiler's result" >&5 -$as_echo "$as_me: WARNING: cthreads.h: proceeding with the compiler's result" >&2;} - ac_header_preproc=yes - ;; - no:yes:* ) - { $as_echo "$as_me:$LINENO: WARNING: cthreads.h: present but cannot be compiled" >&5 -$as_echo "$as_me: WARNING: cthreads.h: present but cannot be compiled" >&2;} - { $as_echo "$as_me:$LINENO: WARNING: cthreads.h: check for missing prerequisite headers?" >&5 -$as_echo "$as_me: WARNING: cthreads.h: check for missing prerequisite headers?" >&2;} - { $as_echo "$as_me:$LINENO: WARNING: cthreads.h: see the Autoconf documentation" >&5 -$as_echo "$as_me: WARNING: cthreads.h: see the Autoconf documentation" >&2;} - { $as_echo "$as_me:$LINENO: WARNING: cthreads.h: section \"Present But Cannot Be Compiled\"" >&5 -$as_echo "$as_me: WARNING: cthreads.h: section \"Present But Cannot Be Compiled\"" >&2;} - { $as_echo "$as_me:$LINENO: WARNING: cthreads.h: proceeding with the preprocessor's result" >&5 -$as_echo "$as_me: WARNING: cthreads.h: proceeding with the preprocessor's result" >&2;} - { $as_echo "$as_me:$LINENO: WARNING: cthreads.h: in the future, the compiler will take precedence" >&5 -$as_echo "$as_me: WARNING: cthreads.h: in the future, the compiler will take precedence" >&2;} - ( cat <<\_ASBOX -## ------------------------------------------------ ## -## Report this to http://www.python.org/python-bugs ## -## ------------------------------------------------ ## -_ASBOX - ) | sed "s/^/$as_me: WARNING: /" >&2 - ;; -esac -{ $as_echo "$as_me:$LINENO: checking for cthreads.h" >&5 -$as_echo_n "checking for cthreads.h... " >&6; } -if test "${ac_cv_header_cthreads_h+set}" = set; then - $as_echo_n "(cached) " >&6 -else - ac_cv_header_cthreads_h=$ac_header_preproc -fi -{ $as_echo "$as_me:$LINENO: result: $ac_cv_header_cthreads_h" >&5 -$as_echo "$ac_cv_header_cthreads_h" >&6; } - -fi -if test "x$ac_cv_header_cthreads_h" = x""yes; then - cat >>confdefs.h <<\_ACEOF -#define WITH_THREAD 1 -_ACEOF - - cat >>confdefs.h <<\_ACEOF -#define C_THREADS 1 -_ACEOF - - -cat >>confdefs.h <<\_ACEOF -#define HURD_C_THREADS 1 -_ACEOF - - LIBS="$LIBS -lthreads" - THREADOBJ="Python/thread.o" -else - - if test "${ac_cv_header_mach_cthreads_h+set}" = set; then - { $as_echo "$as_me:$LINENO: checking for mach/cthreads.h" >&5 -$as_echo_n "checking for mach/cthreads.h... " >&6; } -if test "${ac_cv_header_mach_cthreads_h+set}" = set; then - $as_echo_n "(cached) " >&6 -fi -{ $as_echo "$as_me:$LINENO: result: $ac_cv_header_mach_cthreads_h" >&5 -$as_echo "$ac_cv_header_mach_cthreads_h" >&6; } -else - # Is the header compilable? -{ $as_echo "$as_me:$LINENO: checking mach/cthreads.h usability" >&5 -$as_echo_n "checking mach/cthreads.h usability... " >&6; } -cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -$ac_includes_default -#include -_ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" -$as_echo "$ac_try_echo") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - ac_header_compiler=yes -else - $as_echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - ac_header_compiler=no -fi - -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext -{ $as_echo "$as_me:$LINENO: result: $ac_header_compiler" >&5 -$as_echo "$ac_header_compiler" >&6; } - -# Is the header present? -{ $as_echo "$as_me:$LINENO: checking mach/cthreads.h presence" >&5 -$as_echo_n "checking mach/cthreads.h presence... " >&6; } -cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -#include -_ACEOF -if { (ac_try="$ac_cpp conftest.$ac_ext" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" -$as_echo "$ac_try_echo") >&5 - (eval "$ac_cpp conftest.$ac_ext") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } >/dev/null && { - test -z "$ac_c_preproc_warn_flag$ac_c_werror_flag" || - test ! -s conftest.err - }; then - ac_header_preproc=yes -else - $as_echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - ac_header_preproc=no -fi - -rm -f conftest.err conftest.$ac_ext -{ $as_echo "$as_me:$LINENO: result: $ac_header_preproc" >&5 -$as_echo "$ac_header_preproc" >&6; } - -# So? What about this header? -case $ac_header_compiler:$ac_header_preproc:$ac_c_preproc_warn_flag in - yes:no: ) - { $as_echo "$as_me:$LINENO: WARNING: mach/cthreads.h: accepted by the compiler, rejected by the preprocessor!" >&5 -$as_echo "$as_me: WARNING: mach/cthreads.h: accepted by the compiler, rejected by the preprocessor!" >&2;} - { $as_echo "$as_me:$LINENO: WARNING: mach/cthreads.h: proceeding with the compiler's result" >&5 -$as_echo "$as_me: WARNING: mach/cthreads.h: proceeding with the compiler's result" >&2;} - ac_header_preproc=yes - ;; - no:yes:* ) - { $as_echo "$as_me:$LINENO: WARNING: mach/cthreads.h: present but cannot be compiled" >&5 -$as_echo "$as_me: WARNING: mach/cthreads.h: present but cannot be compiled" >&2;} - { $as_echo "$as_me:$LINENO: WARNING: mach/cthreads.h: check for missing prerequisite headers?" >&5 -$as_echo "$as_me: WARNING: mach/cthreads.h: check for missing prerequisite headers?" >&2;} - { $as_echo "$as_me:$LINENO: WARNING: mach/cthreads.h: see the Autoconf documentation" >&5 -$as_echo "$as_me: WARNING: mach/cthreads.h: see the Autoconf documentation" >&2;} - { $as_echo "$as_me:$LINENO: WARNING: mach/cthreads.h: section \"Present But Cannot Be Compiled\"" >&5 -$as_echo "$as_me: WARNING: mach/cthreads.h: section \"Present But Cannot Be Compiled\"" >&2;} - { $as_echo "$as_me:$LINENO: WARNING: mach/cthreads.h: proceeding with the preprocessor's result" >&5 -$as_echo "$as_me: WARNING: mach/cthreads.h: proceeding with the preprocessor's result" >&2;} - { $as_echo "$as_me:$LINENO: WARNING: mach/cthreads.h: in the future, the compiler will take precedence" >&5 -$as_echo "$as_me: WARNING: mach/cthreads.h: in the future, the compiler will take precedence" >&2;} - ( cat <<\_ASBOX -## ------------------------------------------------ ## -## Report this to http://www.python.org/python-bugs ## -## ------------------------------------------------ ## -_ASBOX - ) | sed "s/^/$as_me: WARNING: /" >&2 - ;; -esac -{ $as_echo "$as_me:$LINENO: checking for mach/cthreads.h" >&5 -$as_echo_n "checking for mach/cthreads.h... " >&6; } -if test "${ac_cv_header_mach_cthreads_h+set}" = set; then - $as_echo_n "(cached) " >&6 -else - ac_cv_header_mach_cthreads_h=$ac_header_preproc -fi -{ $as_echo "$as_me:$LINENO: result: $ac_cv_header_mach_cthreads_h" >&5 -$as_echo "$ac_cv_header_mach_cthreads_h" >&6; } - -fi -if test "x$ac_cv_header_mach_cthreads_h" = x""yes; then - cat >>confdefs.h <<\_ACEOF -#define WITH_THREAD 1 -_ACEOF - - cat >>confdefs.h <<\_ACEOF -#define C_THREADS 1 -_ACEOF - - -cat >>confdefs.h <<\_ACEOF -#define MACH_C_THREADS 1 -_ACEOF - - THREADOBJ="Python/thread.o" -else - - { $as_echo "$as_me:$LINENO: checking for --with-pth" >&5 -$as_echo_n "checking for --with-pth... " >&6; } - -# Check whether --with-pth was given. -if test "${with_pth+set}" = set; then - withval=$with_pth; { $as_echo "$as_me:$LINENO: result: $withval" >&5 -$as_echo "$withval" >&6; } - cat >>confdefs.h <<\_ACEOF -#define WITH_THREAD 1 -_ACEOF - - -cat >>confdefs.h <<\_ACEOF -#define HAVE_PTH 1 -_ACEOF - - LIBS="-lpth $LIBS" - THREADOBJ="Python/thread.o" -else - { $as_echo "$as_me:$LINENO: result: no" >&5 -$as_echo "no" >&6; } - - # Just looking for pthread_create in libpthread is not enough: - # on HP/UX, pthread.h renames pthread_create to a different symbol name. - # So we really have to include pthread.h, and then link. - _libs=$LIBS - LIBS="$LIBS -lpthread" - { $as_echo "$as_me:$LINENO: checking for pthread_create in -lpthread" >&5 -$as_echo_n "checking for pthread_create in -lpthread... " >&6; } - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -#include - -void * start_routine (void *arg) { exit (0); } -int -main () -{ - -pthread_create (NULL, NULL, start_routine, NULL) - ; - return 0; -} -_ACEOF -rm -f conftest.$ac_objext conftest$ac_exeext -if { (ac_try="$ac_link" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" -$as_echo "$ac_try_echo") >&5 - (eval "$ac_link") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest$ac_exeext && { - test "$cross_compiling" = yes || - $as_test_x conftest$ac_exeext - }; then - - { $as_echo "$as_me:$LINENO: result: yes" >&5 -$as_echo "yes" >&6; } - cat >>confdefs.h <<\_ACEOF -#define WITH_THREAD 1 -_ACEOF - - posix_threads=yes - THREADOBJ="Python/thread.o" -else - $as_echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - - LIBS=$_libs - { $as_echo "$as_me:$LINENO: checking for pthread_detach" >&5 -$as_echo_n "checking for pthread_detach... " >&6; } -if test "${ac_cv_func_pthread_detach+set}" = set; then - $as_echo_n "(cached) " >&6 -else - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -/* Define pthread_detach to an innocuous variant, in case declares pthread_detach. - For example, HP-UX 11i declares gettimeofday. */ -#define pthread_detach innocuous_pthread_detach - -/* System header to define __stub macros and hopefully few prototypes, - which can conflict with char pthread_detach (); below. - Prefer to if __STDC__ is defined, since - exists even on freestanding compilers. */ - -#ifdef __STDC__ -# include -#else -# include -#endif - -#undef pthread_detach - -/* Override any GCC internal prototype to avoid an error. - Use char because int might match the return type of a GCC - builtin and then its argument prototype would still apply. */ -#ifdef __cplusplus -extern "C" -#endif -char pthread_detach (); -/* The GNU C library defines this for functions which it implements - to always fail with ENOSYS. Some functions are actually named - something starting with __ and the normal name is an alias. */ -#if defined __stub_pthread_detach || defined __stub___pthread_detach -choke me -#endif - -int -main () -{ -return pthread_detach (); - ; - return 0; -} -_ACEOF -rm -f conftest.$ac_objext conftest$ac_exeext -if { (ac_try="$ac_link" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" -$as_echo "$ac_try_echo") >&5 - (eval "$ac_link") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest$ac_exeext && { - test "$cross_compiling" = yes || - $as_test_x conftest$ac_exeext - }; then - ac_cv_func_pthread_detach=yes -else - $as_echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - ac_cv_func_pthread_detach=no -fi - -rm -rf conftest.dSYM -rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \ - conftest$ac_exeext conftest.$ac_ext -fi -{ $as_echo "$as_me:$LINENO: result: $ac_cv_func_pthread_detach" >&5 -$as_echo "$ac_cv_func_pthread_detach" >&6; } -if test "x$ac_cv_func_pthread_detach" = x""yes; then - cat >>confdefs.h <<\_ACEOF -#define WITH_THREAD 1 -_ACEOF - - posix_threads=yes - THREADOBJ="Python/thread.o" -else - - if test "${ac_cv_header_atheos_threads_h+set}" = set; then - { $as_echo "$as_me:$LINENO: checking for atheos/threads.h" >&5 -$as_echo_n "checking for atheos/threads.h... " >&6; } -if test "${ac_cv_header_atheos_threads_h+set}" = set; then - $as_echo_n "(cached) " >&6 -fi -{ $as_echo "$as_me:$LINENO: result: $ac_cv_header_atheos_threads_h" >&5 -$as_echo "$ac_cv_header_atheos_threads_h" >&6; } -else - # Is the header compilable? -{ $as_echo "$as_me:$LINENO: checking atheos/threads.h usability" >&5 -$as_echo_n "checking atheos/threads.h usability... " >&6; } -cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -$ac_includes_default -#include -_ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" -$as_echo "$ac_try_echo") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - ac_header_compiler=yes -else - $as_echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - ac_header_compiler=no -fi - -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext -{ $as_echo "$as_me:$LINENO: result: $ac_header_compiler" >&5 -$as_echo "$ac_header_compiler" >&6; } - -# Is the header present? -{ $as_echo "$as_me:$LINENO: checking atheos/threads.h presence" >&5 -$as_echo_n "checking atheos/threads.h presence... " >&6; } -cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -#include -_ACEOF -if { (ac_try="$ac_cpp conftest.$ac_ext" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" -$as_echo "$ac_try_echo") >&5 - (eval "$ac_cpp conftest.$ac_ext") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } >/dev/null && { - test -z "$ac_c_preproc_warn_flag$ac_c_werror_flag" || - test ! -s conftest.err - }; then - ac_header_preproc=yes -else - $as_echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - ac_header_preproc=no -fi - -rm -f conftest.err conftest.$ac_ext -{ $as_echo "$as_me:$LINENO: result: $ac_header_preproc" >&5 -$as_echo "$ac_header_preproc" >&6; } - -# So? What about this header? -case $ac_header_compiler:$ac_header_preproc:$ac_c_preproc_warn_flag in - yes:no: ) - { $as_echo "$as_me:$LINENO: WARNING: atheos/threads.h: accepted by the compiler, rejected by the preprocessor!" >&5 -$as_echo "$as_me: WARNING: atheos/threads.h: accepted by the compiler, rejected by the preprocessor!" >&2;} - { $as_echo "$as_me:$LINENO: WARNING: atheos/threads.h: proceeding with the compiler's result" >&5 -$as_echo "$as_me: WARNING: atheos/threads.h: proceeding with the compiler's result" >&2;} - ac_header_preproc=yes - ;; - no:yes:* ) - { $as_echo "$as_me:$LINENO: WARNING: atheos/threads.h: present but cannot be compiled" >&5 -$as_echo "$as_me: WARNING: atheos/threads.h: present but cannot be compiled" >&2;} - { $as_echo "$as_me:$LINENO: WARNING: atheos/threads.h: check for missing prerequisite headers?" >&5 -$as_echo "$as_me: WARNING: atheos/threads.h: check for missing prerequisite headers?" >&2;} - { $as_echo "$as_me:$LINENO: WARNING: atheos/threads.h: see the Autoconf documentation" >&5 -$as_echo "$as_me: WARNING: atheos/threads.h: see the Autoconf documentation" >&2;} - { $as_echo "$as_me:$LINENO: WARNING: atheos/threads.h: section \"Present But Cannot Be Compiled\"" >&5 -$as_echo "$as_me: WARNING: atheos/threads.h: section \"Present But Cannot Be Compiled\"" >&2;} - { $as_echo "$as_me:$LINENO: WARNING: atheos/threads.h: proceeding with the preprocessor's result" >&5 -$as_echo "$as_me: WARNING: atheos/threads.h: proceeding with the preprocessor's result" >&2;} - { $as_echo "$as_me:$LINENO: WARNING: atheos/threads.h: in the future, the compiler will take precedence" >&5 -$as_echo "$as_me: WARNING: atheos/threads.h: in the future, the compiler will take precedence" >&2;} - ( cat <<\_ASBOX -## ------------------------------------------------ ## -## Report this to http://www.python.org/python-bugs ## -## ------------------------------------------------ ## -_ASBOX - ) | sed "s/^/$as_me: WARNING: /" >&2 - ;; -esac -{ $as_echo "$as_me:$LINENO: checking for atheos/threads.h" >&5 -$as_echo_n "checking for atheos/threads.h... " >&6; } -if test "${ac_cv_header_atheos_threads_h+set}" = set; then - $as_echo_n "(cached) " >&6 -else - ac_cv_header_atheos_threads_h=$ac_header_preproc -fi -{ $as_echo "$as_me:$LINENO: result: $ac_cv_header_atheos_threads_h" >&5 -$as_echo "$ac_cv_header_atheos_threads_h" >&6; } - -fi -if test "x$ac_cv_header_atheos_threads_h" = x""yes; then - cat >>confdefs.h <<\_ACEOF -#define WITH_THREAD 1 -_ACEOF - - -cat >>confdefs.h <<\_ACEOF -#define ATHEOS_THREADS 1 -_ACEOF - - THREADOBJ="Python/thread.o" -else - - if test "${ac_cv_header_kernel_OS_h+set}" = set; then - { $as_echo "$as_me:$LINENO: checking for kernel/OS.h" >&5 -$as_echo_n "checking for kernel/OS.h... " >&6; } -if test "${ac_cv_header_kernel_OS_h+set}" = set; then - $as_echo_n "(cached) " >&6 -fi -{ $as_echo "$as_me:$LINENO: result: $ac_cv_header_kernel_OS_h" >&5 -$as_echo "$ac_cv_header_kernel_OS_h" >&6; } -else - # Is the header compilable? -{ $as_echo "$as_me:$LINENO: checking kernel/OS.h usability" >&5 -$as_echo_n "checking kernel/OS.h usability... " >&6; } -cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -$ac_includes_default -#include -_ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" -$as_echo "$ac_try_echo") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - ac_header_compiler=yes -else - $as_echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - ac_header_compiler=no -fi - -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext -{ $as_echo "$as_me:$LINENO: result: $ac_header_compiler" >&5 -$as_echo "$ac_header_compiler" >&6; } - -# Is the header present? -{ $as_echo "$as_me:$LINENO: checking kernel/OS.h presence" >&5 -$as_echo_n "checking kernel/OS.h presence... " >&6; } -cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -#include -_ACEOF -if { (ac_try="$ac_cpp conftest.$ac_ext" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" -$as_echo "$ac_try_echo") >&5 - (eval "$ac_cpp conftest.$ac_ext") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } >/dev/null && { - test -z "$ac_c_preproc_warn_flag$ac_c_werror_flag" || - test ! -s conftest.err - }; then - ac_header_preproc=yes -else - $as_echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - ac_header_preproc=no -fi - -rm -f conftest.err conftest.$ac_ext -{ $as_echo "$as_me:$LINENO: result: $ac_header_preproc" >&5 -$as_echo "$ac_header_preproc" >&6; } - -# So? What about this header? -case $ac_header_compiler:$ac_header_preproc:$ac_c_preproc_warn_flag in - yes:no: ) - { $as_echo "$as_me:$LINENO: WARNING: kernel/OS.h: accepted by the compiler, rejected by the preprocessor!" >&5 -$as_echo "$as_me: WARNING: kernel/OS.h: accepted by the compiler, rejected by the preprocessor!" >&2;} - { $as_echo "$as_me:$LINENO: WARNING: kernel/OS.h: proceeding with the compiler's result" >&5 -$as_echo "$as_me: WARNING: kernel/OS.h: proceeding with the compiler's result" >&2;} - ac_header_preproc=yes - ;; - no:yes:* ) - { $as_echo "$as_me:$LINENO: WARNING: kernel/OS.h: present but cannot be compiled" >&5 -$as_echo "$as_me: WARNING: kernel/OS.h: present but cannot be compiled" >&2;} - { $as_echo "$as_me:$LINENO: WARNING: kernel/OS.h: check for missing prerequisite headers?" >&5 -$as_echo "$as_me: WARNING: kernel/OS.h: check for missing prerequisite headers?" >&2;} - { $as_echo "$as_me:$LINENO: WARNING: kernel/OS.h: see the Autoconf documentation" >&5 -$as_echo "$as_me: WARNING: kernel/OS.h: see the Autoconf documentation" >&2;} - { $as_echo "$as_me:$LINENO: WARNING: kernel/OS.h: section \"Present But Cannot Be Compiled\"" >&5 -$as_echo "$as_me: WARNING: kernel/OS.h: section \"Present But Cannot Be Compiled\"" >&2;} - { $as_echo "$as_me:$LINENO: WARNING: kernel/OS.h: proceeding with the preprocessor's result" >&5 -$as_echo "$as_me: WARNING: kernel/OS.h: proceeding with the preprocessor's result" >&2;} - { $as_echo "$as_me:$LINENO: WARNING: kernel/OS.h: in the future, the compiler will take precedence" >&5 -$as_echo "$as_me: WARNING: kernel/OS.h: in the future, the compiler will take precedence" >&2;} - ( cat <<\_ASBOX -## ------------------------------------------------ ## -## Report this to http://www.python.org/python-bugs ## -## ------------------------------------------------ ## -_ASBOX - ) | sed "s/^/$as_me: WARNING: /" >&2 - ;; -esac -{ $as_echo "$as_me:$LINENO: checking for kernel/OS.h" >&5 -$as_echo_n "checking for kernel/OS.h... " >&6; } -if test "${ac_cv_header_kernel_OS_h+set}" = set; then - $as_echo_n "(cached) " >&6 -else - ac_cv_header_kernel_OS_h=$ac_header_preproc -fi -{ $as_echo "$as_me:$LINENO: result: $ac_cv_header_kernel_OS_h" >&5 -$as_echo "$ac_cv_header_kernel_OS_h" >&6; } - -fi -if test "x$ac_cv_header_kernel_OS_h" = x""yes; then - cat >>confdefs.h <<\_ACEOF -#define WITH_THREAD 1 -_ACEOF - - -cat >>confdefs.h <<\_ACEOF -#define BEOS_THREADS 1 -_ACEOF - - THREADOBJ="Python/thread.o" -else - - { $as_echo "$as_me:$LINENO: checking for pthread_create in -lpthreads" >&5 -$as_echo_n "checking for pthread_create in -lpthreads... " >&6; } -if test "${ac_cv_lib_pthreads_pthread_create+set}" = set; then - $as_echo_n "(cached) " >&6 -else - ac_check_lib_save_LIBS=$LIBS -LIBS="-lpthreads $LIBS" -cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ - -/* Override any GCC internal prototype to avoid an error. - Use char because int might match the return type of a GCC - builtin and then its argument prototype would still apply. */ -#ifdef __cplusplus -extern "C" -#endif -char pthread_create (); -int -main () -{ -return pthread_create (); - ; - return 0; -} -_ACEOF -rm -f conftest.$ac_objext conftest$ac_exeext -if { (ac_try="$ac_link" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" -$as_echo "$ac_try_echo") >&5 - (eval "$ac_link") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest$ac_exeext && { - test "$cross_compiling" = yes || - $as_test_x conftest$ac_exeext - }; then - ac_cv_lib_pthreads_pthread_create=yes -else - $as_echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - ac_cv_lib_pthreads_pthread_create=no -fi - -rm -rf conftest.dSYM -rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \ - conftest$ac_exeext conftest.$ac_ext -LIBS=$ac_check_lib_save_LIBS -fi -{ $as_echo "$as_me:$LINENO: result: $ac_cv_lib_pthreads_pthread_create" >&5 -$as_echo "$ac_cv_lib_pthreads_pthread_create" >&6; } -if test "x$ac_cv_lib_pthreads_pthread_create" = x""yes; then - cat >>confdefs.h <<\_ACEOF -#define WITH_THREAD 1 -_ACEOF - - posix_threads=yes - LIBS="$LIBS -lpthreads" - THREADOBJ="Python/thread.o" -else - - { $as_echo "$as_me:$LINENO: checking for pthread_create in -lc_r" >&5 -$as_echo_n "checking for pthread_create in -lc_r... " >&6; } -if test "${ac_cv_lib_c_r_pthread_create+set}" = set; then - $as_echo_n "(cached) " >&6 -else - ac_check_lib_save_LIBS=$LIBS -LIBS="-lc_r $LIBS" -cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ - -/* Override any GCC internal prototype to avoid an error. - Use char because int might match the return type of a GCC - builtin and then its argument prototype would still apply. */ -#ifdef __cplusplus -extern "C" -#endif -char pthread_create (); -int -main () -{ -return pthread_create (); - ; - return 0; -} -_ACEOF -rm -f conftest.$ac_objext conftest$ac_exeext -if { (ac_try="$ac_link" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" -$as_echo "$ac_try_echo") >&5 - (eval "$ac_link") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest$ac_exeext && { - test "$cross_compiling" = yes || - $as_test_x conftest$ac_exeext - }; then - ac_cv_lib_c_r_pthread_create=yes -else - $as_echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - ac_cv_lib_c_r_pthread_create=no -fi - -rm -rf conftest.dSYM -rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \ - conftest$ac_exeext conftest.$ac_ext -LIBS=$ac_check_lib_save_LIBS -fi -{ $as_echo "$as_me:$LINENO: result: $ac_cv_lib_c_r_pthread_create" >&5 -$as_echo "$ac_cv_lib_c_r_pthread_create" >&6; } -if test "x$ac_cv_lib_c_r_pthread_create" = x""yes; then - cat >>confdefs.h <<\_ACEOF -#define WITH_THREAD 1 -_ACEOF - - posix_threads=yes - LIBS="$LIBS -lc_r" - THREADOBJ="Python/thread.o" -else - - { $as_echo "$as_me:$LINENO: checking for __pthread_create_system in -lpthread" >&5 -$as_echo_n "checking for __pthread_create_system in -lpthread... " >&6; } -if test "${ac_cv_lib_pthread___pthread_create_system+set}" = set; then - $as_echo_n "(cached) " >&6 -else - ac_check_lib_save_LIBS=$LIBS -LIBS="-lpthread $LIBS" -cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ - -/* Override any GCC internal prototype to avoid an error. - Use char because int might match the return type of a GCC - builtin and then its argument prototype would still apply. */ -#ifdef __cplusplus -extern "C" -#endif -char __pthread_create_system (); -int -main () -{ -return __pthread_create_system (); - ; - return 0; -} -_ACEOF -rm -f conftest.$ac_objext conftest$ac_exeext -if { (ac_try="$ac_link" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" -$as_echo "$ac_try_echo") >&5 - (eval "$ac_link") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest$ac_exeext && { - test "$cross_compiling" = yes || - $as_test_x conftest$ac_exeext - }; then - ac_cv_lib_pthread___pthread_create_system=yes -else - $as_echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - ac_cv_lib_pthread___pthread_create_system=no -fi - -rm -rf conftest.dSYM -rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \ - conftest$ac_exeext conftest.$ac_ext -LIBS=$ac_check_lib_save_LIBS -fi -{ $as_echo "$as_me:$LINENO: result: $ac_cv_lib_pthread___pthread_create_system" >&5 -$as_echo "$ac_cv_lib_pthread___pthread_create_system" >&6; } -if test "x$ac_cv_lib_pthread___pthread_create_system" = x""yes; then - cat >>confdefs.h <<\_ACEOF -#define WITH_THREAD 1 -_ACEOF - - posix_threads=yes - LIBS="$LIBS -lpthread" - THREADOBJ="Python/thread.o" -else - - { $as_echo "$as_me:$LINENO: checking for pthread_create in -lcma" >&5 -$as_echo_n "checking for pthread_create in -lcma... " >&6; } -if test "${ac_cv_lib_cma_pthread_create+set}" = set; then - $as_echo_n "(cached) " >&6 -else - ac_check_lib_save_LIBS=$LIBS -LIBS="-lcma $LIBS" -cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ - -/* Override any GCC internal prototype to avoid an error. - Use char because int might match the return type of a GCC - builtin and then its argument prototype would still apply. */ -#ifdef __cplusplus -extern "C" -#endif -char pthread_create (); -int -main () -{ -return pthread_create (); - ; - return 0; -} -_ACEOF -rm -f conftest.$ac_objext conftest$ac_exeext -if { (ac_try="$ac_link" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" -$as_echo "$ac_try_echo") >&5 - (eval "$ac_link") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest$ac_exeext && { - test "$cross_compiling" = yes || - $as_test_x conftest$ac_exeext - }; then - ac_cv_lib_cma_pthread_create=yes -else - $as_echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - ac_cv_lib_cma_pthread_create=no -fi - -rm -rf conftest.dSYM -rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \ - conftest$ac_exeext conftest.$ac_ext -LIBS=$ac_check_lib_save_LIBS -fi -{ $as_echo "$as_me:$LINENO: result: $ac_cv_lib_cma_pthread_create" >&5 -$as_echo "$ac_cv_lib_cma_pthread_create" >&6; } -if test "x$ac_cv_lib_cma_pthread_create" = x""yes; then - cat >>confdefs.h <<\_ACEOF -#define WITH_THREAD 1 -_ACEOF - - posix_threads=yes - LIBS="$LIBS -lcma" - THREADOBJ="Python/thread.o" -else - - USE_THREAD_MODULE="#" -fi - - -fi - -fi - -fi - -fi - - -fi - - -fi - -fi - -rm -rf conftest.dSYM -rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \ - conftest$ac_exeext conftest.$ac_ext -fi - -fi - - -fi - - - - { $as_echo "$as_me:$LINENO: checking for usconfig in -lmpc" >&5 -$as_echo_n "checking for usconfig in -lmpc... " >&6; } -if test "${ac_cv_lib_mpc_usconfig+set}" = set; then - $as_echo_n "(cached) " >&6 -else - ac_check_lib_save_LIBS=$LIBS -LIBS="-lmpc $LIBS" -cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ - -/* Override any GCC internal prototype to avoid an error. - Use char because int might match the return type of a GCC - builtin and then its argument prototype would still apply. */ -#ifdef __cplusplus -extern "C" -#endif -char usconfig (); -int -main () -{ -return usconfig (); - ; - return 0; -} -_ACEOF -rm -f conftest.$ac_objext conftest$ac_exeext -if { (ac_try="$ac_link" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" -$as_echo "$ac_try_echo") >&5 - (eval "$ac_link") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest$ac_exeext && { - test "$cross_compiling" = yes || - $as_test_x conftest$ac_exeext - }; then - ac_cv_lib_mpc_usconfig=yes -else - $as_echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - ac_cv_lib_mpc_usconfig=no -fi - -rm -rf conftest.dSYM -rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \ - conftest$ac_exeext conftest.$ac_ext -LIBS=$ac_check_lib_save_LIBS -fi -{ $as_echo "$as_me:$LINENO: result: $ac_cv_lib_mpc_usconfig" >&5 -$as_echo "$ac_cv_lib_mpc_usconfig" >&6; } -if test "x$ac_cv_lib_mpc_usconfig" = x""yes; then - cat >>confdefs.h <<\_ACEOF -#define WITH_THREAD 1 -_ACEOF - - LIBS="$LIBS -lmpc" - THREADOBJ="Python/thread.o" - USE_THREAD_MODULE="" -fi - - - if test "$posix_threads" != "yes"; then - { $as_echo "$as_me:$LINENO: checking for thr_create in -lthread" >&5 -$as_echo_n "checking for thr_create in -lthread... " >&6; } -if test "${ac_cv_lib_thread_thr_create+set}" = set; then - $as_echo_n "(cached) " >&6 -else - ac_check_lib_save_LIBS=$LIBS -LIBS="-lthread $LIBS" -cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ - -/* Override any GCC internal prototype to avoid an error. - Use char because int might match the return type of a GCC - builtin and then its argument prototype would still apply. */ -#ifdef __cplusplus -extern "C" -#endif -char thr_create (); -int -main () -{ -return thr_create (); - ; - return 0; -} -_ACEOF -rm -f conftest.$ac_objext conftest$ac_exeext -if { (ac_try="$ac_link" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" -$as_echo "$ac_try_echo") >&5 - (eval "$ac_link") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest$ac_exeext && { - test "$cross_compiling" = yes || - $as_test_x conftest$ac_exeext - }; then - ac_cv_lib_thread_thr_create=yes -else - $as_echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - ac_cv_lib_thread_thr_create=no -fi - -rm -rf conftest.dSYM -rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \ - conftest$ac_exeext conftest.$ac_ext -LIBS=$ac_check_lib_save_LIBS -fi -{ $as_echo "$as_me:$LINENO: result: $ac_cv_lib_thread_thr_create" >&5 -$as_echo "$ac_cv_lib_thread_thr_create" >&6; } -if test "x$ac_cv_lib_thread_thr_create" = x""yes; then - cat >>confdefs.h <<\_ACEOF -#define WITH_THREAD 1 -_ACEOF - - LIBS="$LIBS -lthread" - THREADOBJ="Python/thread.o" - USE_THREAD_MODULE="" -fi - - fi - - if test "$USE_THREAD_MODULE" != "#" - then - # If the above checks didn't disable threads, (at least) OSF1 - # needs this '-threads' argument during linking. - case $ac_sys_system in - OSF1) LDLAST=-threads;; - esac - fi -fi - -if test "$posix_threads" = "yes"; then - if test "$unistd_defines_pthreads" = "no"; then - -cat >>confdefs.h <<\_ACEOF -#define _POSIX_THREADS 1 -_ACEOF - - fi - - # Bug 662787: Using semaphores causes unexplicable hangs on Solaris 8. - case $ac_sys_system/$ac_sys_release in - SunOS/5.6) -cat >>confdefs.h <<\_ACEOF -#define HAVE_PTHREAD_DESTRUCTOR 1 -_ACEOF - - ;; - SunOS/5.8) -cat >>confdefs.h <<\_ACEOF -#define HAVE_BROKEN_POSIX_SEMAPHORES 1 -_ACEOF - - ;; - AIX/5) -cat >>confdefs.h <<\_ACEOF -#define HAVE_BROKEN_POSIX_SEMAPHORES 1 -_ACEOF - - ;; - esac - - { $as_echo "$as_me:$LINENO: checking if PTHREAD_SCOPE_SYSTEM is supported" >&5 -$as_echo_n "checking if PTHREAD_SCOPE_SYSTEM is supported... " >&6; } - if test "${ac_cv_pthread_system_supported+set}" = set; then - $as_echo_n "(cached) " >&6 -else - if test "$cross_compiling" = yes; then - ac_cv_pthread_system_supported=no -else - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -#include - void *foo(void *parm) { - return NULL; - } - main() { - pthread_attr_t attr; - pthread_t id; - if (pthread_attr_init(&attr)) exit(-1); - if (pthread_attr_setscope(&attr, PTHREAD_SCOPE_SYSTEM)) exit(-1); - if (pthread_create(&id, &attr, foo, NULL)) exit(-1); - exit(0); - } -_ACEOF -rm -f conftest$ac_exeext -if { (ac_try="$ac_link" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" -$as_echo "$ac_try_echo") >&5 - (eval "$ac_link") 2>&5 - ac_status=$? - $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { ac_try='./conftest$ac_exeext' - { (case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" -$as_echo "$ac_try_echo") >&5 - (eval "$ac_try") 2>&5 - ac_status=$? - $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); }; }; then - ac_cv_pthread_system_supported=yes -else - $as_echo "$as_me: program exited with status $ac_status" >&5 -$as_echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - -( exit $ac_status ) -ac_cv_pthread_system_supported=no -fi -rm -rf conftest.dSYM -rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext conftest.$ac_objext conftest.$ac_ext -fi - - - -fi - - { $as_echo "$as_me:$LINENO: result: $ac_cv_pthread_system_supported" >&5 -$as_echo "$ac_cv_pthread_system_supported" >&6; } - if test "$ac_cv_pthread_system_supported" = "yes"; then - -cat >>confdefs.h <<\_ACEOF -#define PTHREAD_SYSTEM_SCHED_SUPPORTED 1 -_ACEOF - - fi - -for ac_func in pthread_sigmask -do -as_ac_var=`$as_echo "ac_cv_func_$ac_func" | $as_tr_sh` -{ $as_echo "$as_me:$LINENO: checking for $ac_func" >&5 -$as_echo_n "checking for $ac_func... " >&6; } -if { as_var=$as_ac_var; eval "test \"\${$as_var+set}\" = set"; }; then - $as_echo_n "(cached) " >&6 -else - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -/* Define $ac_func to an innocuous variant, in case declares $ac_func. - For example, HP-UX 11i declares gettimeofday. */ -#define $ac_func innocuous_$ac_func - -/* System header to define __stub macros and hopefully few prototypes, - which can conflict with char $ac_func (); below. - Prefer to if __STDC__ is defined, since - exists even on freestanding compilers. */ - -#ifdef __STDC__ -# include -#else -# include -#endif - -#undef $ac_func - -/* Override any GCC internal prototype to avoid an error. - Use char because int might match the return type of a GCC - builtin and then its argument prototype would still apply. */ -#ifdef __cplusplus -extern "C" -#endif -char $ac_func (); -/* The GNU C library defines this for functions which it implements - to always fail with ENOSYS. Some functions are actually named - something starting with __ and the normal name is an alias. */ -#if defined __stub_$ac_func || defined __stub___$ac_func -choke me -#endif - -int -main () -{ -return $ac_func (); - ; - return 0; -} -_ACEOF -rm -f conftest.$ac_objext conftest$ac_exeext -if { (ac_try="$ac_link" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" -$as_echo "$ac_try_echo") >&5 - (eval "$ac_link") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest$ac_exeext && { - test "$cross_compiling" = yes || - $as_test_x conftest$ac_exeext - }; then - eval "$as_ac_var=yes" -else - $as_echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - eval "$as_ac_var=no" -fi - -rm -rf conftest.dSYM -rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \ - conftest$ac_exeext conftest.$ac_ext -fi -ac_res=`eval 'as_val=${'$as_ac_var'} - $as_echo "$as_val"'` - { $as_echo "$as_me:$LINENO: result: $ac_res" >&5 -$as_echo "$ac_res" >&6; } -as_val=`eval 'as_val=${'$as_ac_var'} - $as_echo "$as_val"'` - if test "x$as_val" = x""yes; then - cat >>confdefs.h <<_ACEOF -#define `$as_echo "HAVE_$ac_func" | $as_tr_cpp` 1 -_ACEOF - case $ac_sys_system in - CYGWIN*) - -cat >>confdefs.h <<\_ACEOF -#define HAVE_BROKEN_PTHREAD_SIGMASK 1 -_ACEOF - - ;; - esac -fi -done - -fi - - -# Check for enable-ipv6 - - -{ $as_echo "$as_me:$LINENO: checking if --enable-ipv6 is specified" >&5 -$as_echo_n "checking if --enable-ipv6 is specified... " >&6; } -# Check whether --enable-ipv6 was given. -if test "${enable_ipv6+set}" = set; then - enableval=$enable_ipv6; case "$enableval" in - no) - { $as_echo "$as_me:$LINENO: result: no" >&5 -$as_echo "no" >&6; } - ipv6=no - ;; - *) { $as_echo "$as_me:$LINENO: result: yes" >&5 -$as_echo "yes" >&6; } - cat >>confdefs.h <<\_ACEOF -#define ENABLE_IPV6 1 -_ACEOF - - ipv6=yes - ;; - esac -else - - if test "$cross_compiling" = yes; then - { $as_echo "$as_me:$LINENO: result: no" >&5 -$as_echo "no" >&6; } - ipv6=no - -else - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ - /* AF_INET6 available check */ -#include -#include -main() -{ - if (socket(AF_INET6, SOCK_STREAM, 0) < 0) - exit(1); - else - exit(0); -} - -_ACEOF -rm -f conftest$ac_exeext -if { (ac_try="$ac_link" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" -$as_echo "$ac_try_echo") >&5 - (eval "$ac_link") 2>&5 - ac_status=$? - $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { ac_try='./conftest$ac_exeext' - { (case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" -$as_echo "$ac_try_echo") >&5 - (eval "$ac_try") 2>&5 - ac_status=$? - $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); }; }; then - { $as_echo "$as_me:$LINENO: result: yes" >&5 -$as_echo "yes" >&6; } - ipv6=yes -else - $as_echo "$as_me: program exited with status $ac_status" >&5 -$as_echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - -( exit $ac_status ) -{ $as_echo "$as_me:$LINENO: result: no" >&5 -$as_echo "no" >&6; } - ipv6=no -fi -rm -rf conftest.dSYM -rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext conftest.$ac_objext conftest.$ac_ext -fi - - - -if test "$ipv6" = "yes"; then - { $as_echo "$as_me:$LINENO: checking if RFC2553 API is available" >&5 -$as_echo_n "checking if RFC2553 API is available... " >&6; } - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -#include -#include -int -main () -{ -struct sockaddr_in6 x; -x.sin6_scope_id; - ; - return 0; -} -_ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" -$as_echo "$ac_try_echo") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - { $as_echo "$as_me:$LINENO: result: yes" >&5 -$as_echo "yes" >&6; } - ipv6=yes -else - $as_echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - { $as_echo "$as_me:$LINENO: result: no" >&5 -$as_echo "no" >&6; } - ipv6=no -fi - -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext -fi - -if test "$ipv6" = "yes"; then - cat >>confdefs.h <<\_ACEOF -#define ENABLE_IPV6 1 -_ACEOF - -fi - -fi - - -ipv6type=unknown -ipv6lib=none -ipv6trylibc=no - -if test "$ipv6" = "yes"; then - { $as_echo "$as_me:$LINENO: checking ipv6 stack type" >&5 -$as_echo_n "checking ipv6 stack type... " >&6; } - for i in inria kame linux-glibc linux-inet6 solaris toshiba v6d zeta; - do - case $i in - inria) - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ - -#include -#ifdef IPV6_INRIA_VERSION -yes -#endif -_ACEOF -if (eval "$ac_cpp conftest.$ac_ext") 2>&5 | - $EGREP "yes" >/dev/null 2>&1; then - ipv6type=$i -fi -rm -f conftest* - - ;; - kame) - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ - -#include -#ifdef __KAME__ -yes -#endif -_ACEOF -if (eval "$ac_cpp conftest.$ac_ext") 2>&5 | - $EGREP "yes" >/dev/null 2>&1; then - ipv6type=$i; - ipv6lib=inet6 - ipv6libdir=/usr/local/v6/lib - ipv6trylibc=yes -fi -rm -f conftest* - - ;; - linux-glibc) - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ - -#include -#if defined(__GLIBC__) && ((__GLIBC__ == 2 && __GLIBC_MINOR__ >= 1) || (__GLIBC__ > 2)) -yes -#endif -_ACEOF -if (eval "$ac_cpp conftest.$ac_ext") 2>&5 | - $EGREP "yes" >/dev/null 2>&1; then - ipv6type=$i; - ipv6trylibc=yes -fi -rm -f conftest* - - ;; - linux-inet6) - if test -d /usr/inet6; then - ipv6type=$i - ipv6lib=inet6 - ipv6libdir=/usr/inet6/lib - BASECFLAGS="-I/usr/inet6/include $BASECFLAGS" - fi - ;; - solaris) - if test -f /etc/netconfig; then - if /usr/xpg4/bin/grep -q tcp6 /etc/netconfig; then - ipv6type=$i - ipv6trylibc=yes - fi - fi - ;; - toshiba) - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ - -#include -#ifdef _TOSHIBA_INET6 -yes -#endif -_ACEOF -if (eval "$ac_cpp conftest.$ac_ext") 2>&5 | - $EGREP "yes" >/dev/null 2>&1; then - ipv6type=$i; - ipv6lib=inet6; - ipv6libdir=/usr/local/v6/lib -fi -rm -f conftest* - - ;; - v6d) - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ - -#include -#ifdef __V6D__ -yes -#endif -_ACEOF -if (eval "$ac_cpp conftest.$ac_ext") 2>&5 | - $EGREP "yes" >/dev/null 2>&1; then - ipv6type=$i; - ipv6lib=v6; - ipv6libdir=/usr/local/v6/lib; - BASECFLAGS="-I/usr/local/v6/include $BASECFLAGS" -fi -rm -f conftest* - - ;; - zeta) - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ - -#include -#ifdef _ZETA_MINAMI_INET6 -yes -#endif -_ACEOF -if (eval "$ac_cpp conftest.$ac_ext") 2>&5 | - $EGREP "yes" >/dev/null 2>&1; then - ipv6type=$i; - ipv6lib=inet6; - ipv6libdir=/usr/local/v6/lib -fi -rm -f conftest* - - ;; - esac - if test "$ipv6type" != "unknown"; then - break - fi - done - { $as_echo "$as_me:$LINENO: result: $ipv6type" >&5 -$as_echo "$ipv6type" >&6; } -fi - -if test "$ipv6" = "yes" -a "$ipv6lib" != "none"; then - if test -d $ipv6libdir -a -f $ipv6libdir/lib$ipv6lib.a; then - LIBS="-L$ipv6libdir -l$ipv6lib $LIBS" - echo "using lib$ipv6lib" - else - if test $ipv6trylibc = "yes"; then - echo "using libc" - else - echo 'Fatal: no $ipv6lib library found. cannot continue.' - echo "You need to fetch lib$ipv6lib.a from appropriate" - echo 'ipv6 kit and compile beforehand.' - exit 1 - fi - fi -fi - -{ $as_echo "$as_me:$LINENO: checking for OSX 10.5 SDK or later" >&5 -$as_echo_n "checking for OSX 10.5 SDK or later... " >&6; } -cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -#include -int -main () -{ -FSIORefNum fRef = 0 - ; - return 0; -} -_ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" -$as_echo "$ac_try_echo") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - -cat >>confdefs.h <<\_ACEOF -#define HAVE_OSX105_SDK 1 -_ACEOF - - { $as_echo "$as_me:$LINENO: result: yes" >&5 -$as_echo "yes" >&6; } -else - $as_echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - { $as_echo "$as_me:$LINENO: result: no" >&5 -$as_echo "no" >&6; } - -fi - -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext - -# Check for --with-doc-strings -{ $as_echo "$as_me:$LINENO: checking for --with-doc-strings" >&5 -$as_echo_n "checking for --with-doc-strings... " >&6; } - -# Check whether --with-doc-strings was given. -if test "${with_doc_strings+set}" = set; then - withval=$with_doc_strings; -fi - - -if test -z "$with_doc_strings" -then with_doc_strings="yes" -fi -if test "$with_doc_strings" != "no" -then - -cat >>confdefs.h <<\_ACEOF -#define WITH_DOC_STRINGS 1 -_ACEOF - -fi -{ $as_echo "$as_me:$LINENO: result: $with_doc_strings" >&5 -$as_echo "$with_doc_strings" >&6; } - -# Check for Python-specific malloc support -{ $as_echo "$as_me:$LINENO: checking for --with-tsc" >&5 -$as_echo_n "checking for --with-tsc... " >&6; } - -# Check whether --with-tsc was given. -if test "${with_tsc+set}" = set; then - withval=$with_tsc; -if test "$withval" != no -then - -cat >>confdefs.h <<\_ACEOF -#define WITH_TSC 1 -_ACEOF - - { $as_echo "$as_me:$LINENO: result: yes" >&5 -$as_echo "yes" >&6; } -else { $as_echo "$as_me:$LINENO: result: no" >&5 -$as_echo "no" >&6; } -fi -else - { $as_echo "$as_me:$LINENO: result: no" >&5 -$as_echo "no" >&6; } -fi - - -# Check for Python-specific malloc support -{ $as_echo "$as_me:$LINENO: checking for --with-pymalloc" >&5 -$as_echo_n "checking for --with-pymalloc... " >&6; } - -# Check whether --with-pymalloc was given. -if test "${with_pymalloc+set}" = set; then - withval=$with_pymalloc; -fi - - -if test -z "$with_pymalloc" -then with_pymalloc="yes" -fi -if test "$with_pymalloc" != "no" -then - -cat >>confdefs.h <<\_ACEOF -#define WITH_PYMALLOC 1 -_ACEOF - -fi -{ $as_echo "$as_me:$LINENO: result: $with_pymalloc" >&5 -$as_echo "$with_pymalloc" >&6; } - -# Check for --with-wctype-functions -{ $as_echo "$as_me:$LINENO: checking for --with-wctype-functions" >&5 -$as_echo_n "checking for --with-wctype-functions... " >&6; } - -# Check whether --with-wctype-functions was given. -if test "${with_wctype_functions+set}" = set; then - withval=$with_wctype_functions; -if test "$withval" != no -then - -cat >>confdefs.h <<\_ACEOF -#define WANT_WCTYPE_FUNCTIONS 1 -_ACEOF - - { $as_echo "$as_me:$LINENO: result: yes" >&5 -$as_echo "yes" >&6; } -else { $as_echo "$as_me:$LINENO: result: no" >&5 -$as_echo "no" >&6; } -fi -else - { $as_echo "$as_me:$LINENO: result: no" >&5 -$as_echo "no" >&6; } -fi - - -# -I${DLINCLDIR} is added to the compile rule for importdl.o - -DLINCLDIR=. - -# the dlopen() function means we might want to use dynload_shlib.o. some -# platforms, such as AIX, have dlopen(), but don't want to use it. - -for ac_func in dlopen -do -as_ac_var=`$as_echo "ac_cv_func_$ac_func" | $as_tr_sh` -{ $as_echo "$as_me:$LINENO: checking for $ac_func" >&5 -$as_echo_n "checking for $ac_func... " >&6; } -if { as_var=$as_ac_var; eval "test \"\${$as_var+set}\" = set"; }; then - $as_echo_n "(cached) " >&6 -else - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -/* Define $ac_func to an innocuous variant, in case declares $ac_func. - For example, HP-UX 11i declares gettimeofday. */ -#define $ac_func innocuous_$ac_func - -/* System header to define __stub macros and hopefully few prototypes, - which can conflict with char $ac_func (); below. - Prefer to if __STDC__ is defined, since - exists even on freestanding compilers. */ - -#ifdef __STDC__ -# include -#else -# include -#endif - -#undef $ac_func - -/* Override any GCC internal prototype to avoid an error. - Use char because int might match the return type of a GCC - builtin and then its argument prototype would still apply. */ -#ifdef __cplusplus -extern "C" -#endif -char $ac_func (); -/* The GNU C library defines this for functions which it implements - to always fail with ENOSYS. Some functions are actually named - something starting with __ and the normal name is an alias. */ -#if defined __stub_$ac_func || defined __stub___$ac_func -choke me -#endif - -int -main () -{ -return $ac_func (); - ; - return 0; -} -_ACEOF -rm -f conftest.$ac_objext conftest$ac_exeext -if { (ac_try="$ac_link" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" -$as_echo "$ac_try_echo") >&5 - (eval "$ac_link") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest$ac_exeext && { - test "$cross_compiling" = yes || - $as_test_x conftest$ac_exeext - }; then - eval "$as_ac_var=yes" -else - $as_echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - eval "$as_ac_var=no" -fi - -rm -rf conftest.dSYM -rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \ - conftest$ac_exeext conftest.$ac_ext -fi -ac_res=`eval 'as_val=${'$as_ac_var'} - $as_echo "$as_val"'` - { $as_echo "$as_me:$LINENO: result: $ac_res" >&5 -$as_echo "$ac_res" >&6; } -as_val=`eval 'as_val=${'$as_ac_var'} - $as_echo "$as_val"'` - if test "x$as_val" = x""yes; then - cat >>confdefs.h <<_ACEOF -#define `$as_echo "HAVE_$ac_func" | $as_tr_cpp` 1 -_ACEOF - -fi -done - - -# DYNLOADFILE specifies which dynload_*.o file we will use for dynamic -# loading of modules. - -{ $as_echo "$as_me:$LINENO: checking DYNLOADFILE" >&5 -$as_echo_n "checking DYNLOADFILE... " >&6; } -if test -z "$DYNLOADFILE" -then - case $ac_sys_system/$ac_sys_release in - AIX*) # Use dynload_shlib.c and dlopen() if we have it; otherwise dynload_aix.c - if test "$ac_cv_func_dlopen" = yes - then DYNLOADFILE="dynload_shlib.o" - else DYNLOADFILE="dynload_aix.o" - fi - ;; - BeOS*) DYNLOADFILE="dynload_beos.o";; - hp*|HP*) DYNLOADFILE="dynload_hpux.o";; - # Use dynload_next.c only on 10.2 and below, which don't have native dlopen() - Darwin/[0156]\..*) DYNLOADFILE="dynload_next.o";; - atheos*) DYNLOADFILE="dynload_atheos.o";; - *) - # use dynload_shlib.c and dlopen() if we have it; otherwise stub - # out any dynamic loading - if test "$ac_cv_func_dlopen" = yes - then DYNLOADFILE="dynload_shlib.o" - else DYNLOADFILE="dynload_stub.o" - fi - ;; - esac -fi -{ $as_echo "$as_me:$LINENO: result: $DYNLOADFILE" >&5 -$as_echo "$DYNLOADFILE" >&6; } -if test "$DYNLOADFILE" != "dynload_stub.o" -then - -cat >>confdefs.h <<\_ACEOF -#define HAVE_DYNAMIC_LOADING 1 -_ACEOF - -fi - -# MACHDEP_OBJS can be set to platform-specific object files needed by Python - - -{ $as_echo "$as_me:$LINENO: checking MACHDEP_OBJS" >&5 -$as_echo_n "checking MACHDEP_OBJS... " >&6; } -if test -z "$MACHDEP_OBJS" -then - MACHDEP_OBJS=$extra_machdep_objs -else - MACHDEP_OBJS="$MACHDEP_OBJS $extra_machdep_objs" -fi -{ $as_echo "$as_me:$LINENO: result: MACHDEP_OBJS" >&5 -$as_echo "MACHDEP_OBJS" >&6; } - -# checks for library functions - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -for ac_func in alarm setitimer getitimer bind_textdomain_codeset chown \ - clock confstr ctermid execv fchmod fchown fork fpathconf ftime ftruncate \ - gai_strerror getgroups getlogin getloadavg getpeername getpgid getpid \ - getpriority getpwent getspnam getspent getsid getwd \ - kill killpg lchmod lchown lstat mkfifo mknod mktime \ - mremap nice pathconf pause plock poll pthread_init \ - putenv readlink realpath \ - select setegid seteuid setgid \ - setlocale setregid setreuid 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 -do -as_ac_var=`$as_echo "ac_cv_func_$ac_func" | $as_tr_sh` -{ $as_echo "$as_me:$LINENO: checking for $ac_func" >&5 -$as_echo_n "checking for $ac_func... " >&6; } -if { as_var=$as_ac_var; eval "test \"\${$as_var+set}\" = set"; }; then - $as_echo_n "(cached) " >&6 -else - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -/* Define $ac_func to an innocuous variant, in case declares $ac_func. - For example, HP-UX 11i declares gettimeofday. */ -#define $ac_func innocuous_$ac_func - -/* System header to define __stub macros and hopefully few prototypes, - which can conflict with char $ac_func (); below. - Prefer to if __STDC__ is defined, since - exists even on freestanding compilers. */ - -#ifdef __STDC__ -# include -#else -# include -#endif - -#undef $ac_func - -/* Override any GCC internal prototype to avoid an error. - Use char because int might match the return type of a GCC - builtin and then its argument prototype would still apply. */ -#ifdef __cplusplus -extern "C" -#endif -char $ac_func (); -/* The GNU C library defines this for functions which it implements - to always fail with ENOSYS. Some functions are actually named - something starting with __ and the normal name is an alias. */ -#if defined __stub_$ac_func || defined __stub___$ac_func -choke me -#endif - -int -main () -{ -return $ac_func (); - ; - return 0; -} -_ACEOF -rm -f conftest.$ac_objext conftest$ac_exeext -if { (ac_try="$ac_link" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" -$as_echo "$ac_try_echo") >&5 - (eval "$ac_link") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest$ac_exeext && { - test "$cross_compiling" = yes || - $as_test_x conftest$ac_exeext - }; then - eval "$as_ac_var=yes" -else - $as_echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - eval "$as_ac_var=no" -fi - -rm -rf conftest.dSYM -rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \ - conftest$ac_exeext conftest.$ac_ext -fi -ac_res=`eval 'as_val=${'$as_ac_var'} - $as_echo "$as_val"'` - { $as_echo "$as_me:$LINENO: result: $ac_res" >&5 -$as_echo "$ac_res" >&6; } -as_val=`eval 'as_val=${'$as_ac_var'} - $as_echo "$as_val"'` - if test "x$as_val" = x""yes; then - cat >>confdefs.h <<_ACEOF -#define `$as_echo "HAVE_$ac_func" | $as_tr_cpp` 1 -_ACEOF - -fi -done - - -# For some functions, having a definition is not sufficient, since -# we want to take their address. -{ $as_echo "$as_me:$LINENO: checking for chroot" >&5 -$as_echo_n "checking for chroot... " >&6; } -cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -#include -int -main () -{ -void *x=chroot - ; - return 0; -} -_ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" -$as_echo "$ac_try_echo") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - -cat >>confdefs.h <<\_ACEOF -#define HAVE_CHROOT 1 -_ACEOF - - { $as_echo "$as_me:$LINENO: result: yes" >&5 -$as_echo "yes" >&6; } -else - $as_echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - { $as_echo "$as_me:$LINENO: result: no" >&5 -$as_echo "no" >&6; } - -fi - -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext -{ $as_echo "$as_me:$LINENO: checking for link" >&5 -$as_echo_n "checking for link... " >&6; } -cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -#include -int -main () -{ -void *x=link - ; - return 0; -} -_ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" -$as_echo "$ac_try_echo") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - -cat >>confdefs.h <<\_ACEOF -#define HAVE_LINK 1 -_ACEOF - - { $as_echo "$as_me:$LINENO: result: yes" >&5 -$as_echo "yes" >&6; } -else - $as_echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - { $as_echo "$as_me:$LINENO: result: no" >&5 -$as_echo "no" >&6; } - -fi - -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext -{ $as_echo "$as_me:$LINENO: checking for symlink" >&5 -$as_echo_n "checking for symlink... " >&6; } -cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -#include -int -main () -{ -void *x=symlink - ; - return 0; -} -_ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" -$as_echo "$ac_try_echo") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - -cat >>confdefs.h <<\_ACEOF -#define HAVE_SYMLINK 1 -_ACEOF - - { $as_echo "$as_me:$LINENO: result: yes" >&5 -$as_echo "yes" >&6; } -else - $as_echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - { $as_echo "$as_me:$LINENO: result: no" >&5 -$as_echo "no" >&6; } - -fi - -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext -{ $as_echo "$as_me:$LINENO: checking for fchdir" >&5 -$as_echo_n "checking for fchdir... " >&6; } -cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -#include -int -main () -{ -void *x=fchdir - ; - return 0; -} -_ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" -$as_echo "$ac_try_echo") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - -cat >>confdefs.h <<\_ACEOF -#define HAVE_FCHDIR 1 -_ACEOF - - { $as_echo "$as_me:$LINENO: result: yes" >&5 -$as_echo "yes" >&6; } -else - $as_echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - { $as_echo "$as_me:$LINENO: result: no" >&5 -$as_echo "no" >&6; } - -fi - -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext -{ $as_echo "$as_me:$LINENO: checking for fsync" >&5 -$as_echo_n "checking for fsync... " >&6; } -cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -#include -int -main () -{ -void *x=fsync - ; - return 0; -} -_ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" -$as_echo "$ac_try_echo") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - -cat >>confdefs.h <<\_ACEOF -#define HAVE_FSYNC 1 -_ACEOF - - { $as_echo "$as_me:$LINENO: result: yes" >&5 -$as_echo "yes" >&6; } -else - $as_echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - { $as_echo "$as_me:$LINENO: result: no" >&5 -$as_echo "no" >&6; } - -fi - -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext -{ $as_echo "$as_me:$LINENO: checking for fdatasync" >&5 -$as_echo_n "checking for fdatasync... " >&6; } -cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -#include -int -main () -{ -void *x=fdatasync - ; - return 0; -} -_ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" -$as_echo "$ac_try_echo") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - -cat >>confdefs.h <<\_ACEOF -#define HAVE_FDATASYNC 1 -_ACEOF - - { $as_echo "$as_me:$LINENO: result: yes" >&5 -$as_echo "yes" >&6; } -else - $as_echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - { $as_echo "$as_me:$LINENO: result: no" >&5 -$as_echo "no" >&6; } - -fi - -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext -{ $as_echo "$as_me:$LINENO: checking for epoll" >&5 -$as_echo_n "checking for epoll... " >&6; } -cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -#include -int -main () -{ -void *x=epoll_create - ; - return 0; -} -_ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" -$as_echo "$ac_try_echo") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - -cat >>confdefs.h <<\_ACEOF -#define HAVE_EPOLL 1 -_ACEOF - - { $as_echo "$as_me:$LINENO: result: yes" >&5 -$as_echo "yes" >&6; } -else - $as_echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - { $as_echo "$as_me:$LINENO: result: no" >&5 -$as_echo "no" >&6; } - -fi - -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext -{ $as_echo "$as_me:$LINENO: checking for kqueue" >&5 -$as_echo_n "checking for kqueue... " >&6; } -cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ - -#include -#include - -int -main () -{ -int x=kqueue() - ; - return 0; -} -_ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" -$as_echo "$ac_try_echo") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - -cat >>confdefs.h <<\_ACEOF -#define HAVE_KQUEUE 1 -_ACEOF - - { $as_echo "$as_me:$LINENO: result: yes" >&5 -$as_echo "yes" >&6; } -else - $as_echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - { $as_echo "$as_me:$LINENO: result: no" >&5 -$as_echo "no" >&6; } - -fi - -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext -# On some systems (eg. FreeBSD 5), we would find a definition of the -# functions ctermid_r, setgroups in the library, but no prototype -# (e.g. because we use _XOPEN_SOURCE). See whether we can take their -# address to avoid compiler warnings and potential miscompilations -# because of the missing prototypes. - -{ $as_echo "$as_me:$LINENO: checking for ctermid_r" >&5 -$as_echo_n "checking for ctermid_r... " >&6; } -cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ - -#include "confdefs.h" -#include - -int -main () -{ -void* p = ctermid_r - ; - return 0; -} -_ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" -$as_echo "$ac_try_echo") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - -cat >>confdefs.h <<\_ACEOF -#define HAVE_CTERMID_R 1 -_ACEOF - - { $as_echo "$as_me:$LINENO: result: yes" >&5 -$as_echo "yes" >&6; } -else - $as_echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - { $as_echo "$as_me:$LINENO: result: no" >&5 -$as_echo "no" >&6; } - -fi - -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext - -{ $as_echo "$as_me:$LINENO: checking for flock" >&5 -$as_echo_n "checking for flock... " >&6; } -cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ - -#include "confdefs.h" -#include - -int -main () -{ -void* p = flock - ; - return 0; -} -_ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" -$as_echo "$ac_try_echo") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - -cat >>confdefs.h <<\_ACEOF -#define HAVE_FLOCK 1 -_ACEOF - - { $as_echo "$as_me:$LINENO: result: yes" >&5 -$as_echo "yes" >&6; } -else - $as_echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - { $as_echo "$as_me:$LINENO: result: no" >&5 -$as_echo "no" >&6; } - -fi - -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext - -{ $as_echo "$as_me:$LINENO: checking for getpagesize" >&5 -$as_echo_n "checking for getpagesize... " >&6; } -cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ - -#include "confdefs.h" -#include - -int -main () -{ -void* p = getpagesize - ; - return 0; -} -_ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" -$as_echo "$ac_try_echo") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - -cat >>confdefs.h <<\_ACEOF -#define HAVE_GETPAGESIZE 1 -_ACEOF - - { $as_echo "$as_me:$LINENO: result: yes" >&5 -$as_echo "yes" >&6; } -else - $as_echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - { $as_echo "$as_me:$LINENO: result: no" >&5 -$as_echo "no" >&6; } - -fi - -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext - -for ac_prog in true -do - # Extract the first word of "$ac_prog", so it can be a program name with args. -set dummy $ac_prog; ac_word=$2 -{ $as_echo "$as_me:$LINENO: checking for $ac_word" >&5 -$as_echo_n "checking for $ac_word... " >&6; } -if test "${ac_cv_prog_TRUE+set}" = set; then - $as_echo_n "(cached) " >&6 -else - if test -n "$TRUE"; then - ac_cv_prog_TRUE="$TRUE" # Let the user override the test. -else -as_save_IFS=$IFS; IFS=$PATH_SEPARATOR -for as_dir in $PATH -do - IFS=$as_save_IFS - test -z "$as_dir" && as_dir=. - for ac_exec_ext in '' $ac_executable_extensions; do - if { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_test_x "$as_dir/$ac_word$ac_exec_ext"; }; then - ac_cv_prog_TRUE="$ac_prog" - $as_echo "$as_me:$LINENO: found $as_dir/$ac_word$ac_exec_ext" >&5 - break 2 - fi -done -done -IFS=$as_save_IFS - -fi -fi -TRUE=$ac_cv_prog_TRUE -if test -n "$TRUE"; then - { $as_echo "$as_me:$LINENO: result: $TRUE" >&5 -$as_echo "$TRUE" >&6; } -else - { $as_echo "$as_me:$LINENO: result: no" >&5 -$as_echo "no" >&6; } -fi - - - test -n "$TRUE" && break -done -test -n "$TRUE" || TRUE="/bin/true" - - -{ $as_echo "$as_me:$LINENO: checking for inet_aton in -lc" >&5 -$as_echo_n "checking for inet_aton in -lc... " >&6; } -if test "${ac_cv_lib_c_inet_aton+set}" = set; then - $as_echo_n "(cached) " >&6 -else - ac_check_lib_save_LIBS=$LIBS -LIBS="-lc $LIBS" -cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ - -/* Override any GCC internal prototype to avoid an error. - Use char because int might match the return type of a GCC - builtin and then its argument prototype would still apply. */ -#ifdef __cplusplus -extern "C" -#endif -char inet_aton (); -int -main () -{ -return inet_aton (); - ; - return 0; -} -_ACEOF -rm -f conftest.$ac_objext conftest$ac_exeext -if { (ac_try="$ac_link" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" -$as_echo "$ac_try_echo") >&5 - (eval "$ac_link") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest$ac_exeext && { - test "$cross_compiling" = yes || - $as_test_x conftest$ac_exeext - }; then - ac_cv_lib_c_inet_aton=yes -else - $as_echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - ac_cv_lib_c_inet_aton=no -fi - -rm -rf conftest.dSYM -rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \ - conftest$ac_exeext conftest.$ac_ext -LIBS=$ac_check_lib_save_LIBS -fi -{ $as_echo "$as_me:$LINENO: result: $ac_cv_lib_c_inet_aton" >&5 -$as_echo "$ac_cv_lib_c_inet_aton" >&6; } -if test "x$ac_cv_lib_c_inet_aton" = x""yes; then - $ac_cv_prog_TRUE -else - -{ $as_echo "$as_me:$LINENO: checking for inet_aton in -lresolv" >&5 -$as_echo_n "checking for inet_aton in -lresolv... " >&6; } -if test "${ac_cv_lib_resolv_inet_aton+set}" = set; then - $as_echo_n "(cached) " >&6 -else - ac_check_lib_save_LIBS=$LIBS -LIBS="-lresolv $LIBS" -cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ - -/* Override any GCC internal prototype to avoid an error. - Use char because int might match the return type of a GCC - builtin and then its argument prototype would still apply. */ -#ifdef __cplusplus -extern "C" -#endif -char inet_aton (); -int -main () -{ -return inet_aton (); - ; - return 0; -} -_ACEOF -rm -f conftest.$ac_objext conftest$ac_exeext -if { (ac_try="$ac_link" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" -$as_echo "$ac_try_echo") >&5 - (eval "$ac_link") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest$ac_exeext && { - test "$cross_compiling" = yes || - $as_test_x conftest$ac_exeext - }; then - ac_cv_lib_resolv_inet_aton=yes -else - $as_echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - ac_cv_lib_resolv_inet_aton=no -fi - -rm -rf conftest.dSYM -rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \ - conftest$ac_exeext conftest.$ac_ext -LIBS=$ac_check_lib_save_LIBS -fi -{ $as_echo "$as_me:$LINENO: result: $ac_cv_lib_resolv_inet_aton" >&5 -$as_echo "$ac_cv_lib_resolv_inet_aton" >&6; } -if test "x$ac_cv_lib_resolv_inet_aton" = x""yes; then - cat >>confdefs.h <<_ACEOF -#define HAVE_LIBRESOLV 1 -_ACEOF - - LIBS="-lresolv $LIBS" - -fi - - -fi - - -# On Tru64, chflags seems to be present, but calling it will -# exit Python -{ $as_echo "$as_me:$LINENO: checking for chflags" >&5 -$as_echo_n "checking for chflags... " >&6; } -if test "${ac_cv_have_chflags+set}" = set; then - $as_echo_n "(cached) " >&6 -else - if test "$cross_compiling" = yes; then - ac_cv_have_chflags=cross -else - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -[ -#include -#include -int main(int argc, char*argv[]) -{ - if(chflags(argv[0], 0) != 0) - return 1; - return 0; -} -] -_ACEOF -rm -f conftest$ac_exeext -if { (ac_try="$ac_link" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" -$as_echo "$ac_try_echo") >&5 - (eval "$ac_link") 2>&5 - ac_status=$? - $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { ac_try='./conftest$ac_exeext' - { (case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" -$as_echo "$ac_try_echo") >&5 - (eval "$ac_try") 2>&5 - ac_status=$? - $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); }; }; then - ac_cv_have_chflags=yes -else - $as_echo "$as_me: program exited with status $ac_status" >&5 -$as_echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - -( exit $ac_status ) -ac_cv_have_chflags=no -fi -rm -rf conftest.dSYM -rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext conftest.$ac_objext conftest.$ac_ext -fi - - - -fi -{ $as_echo "$as_me:$LINENO: result: $ac_cv_have_chflags" >&5 -$as_echo "$ac_cv_have_chflags" >&6; } -if test "$ac_cv_have_chflags" = cross ; then - { $as_echo "$as_me:$LINENO: checking for chflags" >&5 -$as_echo_n "checking for chflags... " >&6; } -if test "${ac_cv_func_chflags+set}" = set; then - $as_echo_n "(cached) " >&6 -else - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -/* Define chflags to an innocuous variant, in case declares chflags. - For example, HP-UX 11i declares gettimeofday. */ -#define chflags innocuous_chflags - -/* System header to define __stub macros and hopefully few prototypes, - which can conflict with char chflags (); below. - Prefer to if __STDC__ is defined, since - exists even on freestanding compilers. */ - -#ifdef __STDC__ -# include -#else -# include -#endif - -#undef chflags - -/* Override any GCC internal prototype to avoid an error. - Use char because int might match the return type of a GCC - builtin and then its argument prototype would still apply. */ -#ifdef __cplusplus -extern "C" -#endif -char chflags (); -/* The GNU C library defines this for functions which it implements - to always fail with ENOSYS. Some functions are actually named - something starting with __ and the normal name is an alias. */ -#if defined __stub_chflags || defined __stub___chflags -choke me -#endif - -int -main () -{ -return chflags (); - ; - return 0; -} -_ACEOF -rm -f conftest.$ac_objext conftest$ac_exeext -if { (ac_try="$ac_link" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" -$as_echo "$ac_try_echo") >&5 - (eval "$ac_link") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest$ac_exeext && { - test "$cross_compiling" = yes || - $as_test_x conftest$ac_exeext - }; then - ac_cv_func_chflags=yes -else - $as_echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - ac_cv_func_chflags=no -fi - -rm -rf conftest.dSYM -rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \ - conftest$ac_exeext conftest.$ac_ext -fi -{ $as_echo "$as_me:$LINENO: result: $ac_cv_func_chflags" >&5 -$as_echo "$ac_cv_func_chflags" >&6; } -if test "x$ac_cv_func_chflags" = x""yes; then - ac_cv_have_chflags="yes" -else - ac_cv_have_chflags="no" -fi - -fi -if test "$ac_cv_have_chflags" = yes ; then - -cat >>confdefs.h <<\_ACEOF -#define HAVE_CHFLAGS 1 -_ACEOF - -fi - -{ $as_echo "$as_me:$LINENO: checking for lchflags" >&5 -$as_echo_n "checking for lchflags... " >&6; } -if test "${ac_cv_have_lchflags+set}" = set; then - $as_echo_n "(cached) " >&6 -else - if test "$cross_compiling" = yes; then - ac_cv_have_lchflags=cross -else - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -[ -#include -#include -int main(int argc, char*argv[]) -{ - if(lchflags(argv[0], 0) != 0) - return 1; - return 0; -} -] -_ACEOF -rm -f conftest$ac_exeext -if { (ac_try="$ac_link" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" -$as_echo "$ac_try_echo") >&5 - (eval "$ac_link") 2>&5 - ac_status=$? - $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { ac_try='./conftest$ac_exeext' - { (case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" -$as_echo "$ac_try_echo") >&5 - (eval "$ac_try") 2>&5 - ac_status=$? - $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); }; }; then - ac_cv_have_lchflags=yes -else - $as_echo "$as_me: program exited with status $ac_status" >&5 -$as_echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - -( exit $ac_status ) -ac_cv_have_lchflags=no -fi -rm -rf conftest.dSYM -rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext conftest.$ac_objext conftest.$ac_ext -fi - - - -fi -{ $as_echo "$as_me:$LINENO: result: $ac_cv_have_lchflags" >&5 -$as_echo "$ac_cv_have_lchflags" >&6; } -if test "$ac_cv_have_lchflags" = cross ; then - { $as_echo "$as_me:$LINENO: checking for lchflags" >&5 -$as_echo_n "checking for lchflags... " >&6; } -if test "${ac_cv_func_lchflags+set}" = set; then - $as_echo_n "(cached) " >&6 -else - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -/* Define lchflags to an innocuous variant, in case declares lchflags. - For example, HP-UX 11i declares gettimeofday. */ -#define lchflags innocuous_lchflags - -/* System header to define __stub macros and hopefully few prototypes, - which can conflict with char lchflags (); below. - Prefer to if __STDC__ is defined, since - exists even on freestanding compilers. */ - -#ifdef __STDC__ -# include -#else -# include -#endif - -#undef lchflags - -/* Override any GCC internal prototype to avoid an error. - Use char because int might match the return type of a GCC - builtin and then its argument prototype would still apply. */ -#ifdef __cplusplus -extern "C" -#endif -char lchflags (); -/* The GNU C library defines this for functions which it implements - to always fail with ENOSYS. Some functions are actually named - something starting with __ and the normal name is an alias. */ -#if defined __stub_lchflags || defined __stub___lchflags -choke me -#endif - -int -main () -{ -return lchflags (); - ; - return 0; -} -_ACEOF -rm -f conftest.$ac_objext conftest$ac_exeext -if { (ac_try="$ac_link" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" -$as_echo "$ac_try_echo") >&5 - (eval "$ac_link") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest$ac_exeext && { - test "$cross_compiling" = yes || - $as_test_x conftest$ac_exeext - }; then - ac_cv_func_lchflags=yes -else - $as_echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - ac_cv_func_lchflags=no -fi - -rm -rf conftest.dSYM -rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \ - conftest$ac_exeext conftest.$ac_ext -fi -{ $as_echo "$as_me:$LINENO: result: $ac_cv_func_lchflags" >&5 -$as_echo "$ac_cv_func_lchflags" >&6; } -if test "x$ac_cv_func_lchflags" = x""yes; then - ac_cv_have_lchflags="yes" -else - ac_cv_have_lchflags="no" -fi - -fi -if test "$ac_cv_have_lchflags" = yes ; then - -cat >>confdefs.h <<\_ACEOF -#define HAVE_LCHFLAGS 1 -_ACEOF - -fi - -case $ac_sys_system/$ac_sys_release in -Darwin/*) - _CUR_CFLAGS="${CFLAGS}" - _CUR_LDFLAGS="${LDFLAGS}" - CFLAGS="${CFLAGS} -Wl,-search_paths_first" - LDFLAGS="${LDFLAGS} -Wl,-search_paths_first -L/usr/local/lib" - ;; -esac - -{ $as_echo "$as_me:$LINENO: checking for inflateCopy in -lz" >&5 -$as_echo_n "checking for inflateCopy in -lz... " >&6; } -if test "${ac_cv_lib_z_inflateCopy+set}" = set; then - $as_echo_n "(cached) " >&6 -else - ac_check_lib_save_LIBS=$LIBS -LIBS="-lz $LIBS" -cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ - -/* Override any GCC internal prototype to avoid an error. - Use char because int might match the return type of a GCC - builtin and then its argument prototype would still apply. */ -#ifdef __cplusplus -extern "C" -#endif -char inflateCopy (); -int -main () -{ -return inflateCopy (); - ; - return 0; -} -_ACEOF -rm -f conftest.$ac_objext conftest$ac_exeext -if { (ac_try="$ac_link" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" -$as_echo "$ac_try_echo") >&5 - (eval "$ac_link") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest$ac_exeext && { - test "$cross_compiling" = yes || - $as_test_x conftest$ac_exeext - }; then - ac_cv_lib_z_inflateCopy=yes -else - $as_echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - ac_cv_lib_z_inflateCopy=no -fi - -rm -rf conftest.dSYM -rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \ - conftest$ac_exeext conftest.$ac_ext -LIBS=$ac_check_lib_save_LIBS -fi -{ $as_echo "$as_me:$LINENO: result: $ac_cv_lib_z_inflateCopy" >&5 -$as_echo "$ac_cv_lib_z_inflateCopy" >&6; } -if test "x$ac_cv_lib_z_inflateCopy" = x""yes; then - -cat >>confdefs.h <<\_ACEOF -#define HAVE_ZLIB_COPY 1 -_ACEOF - -fi - - -case $ac_sys_system/$ac_sys_release in -Darwin/*) - CFLAGS="${_CUR_CFLAGS}" - LDFLAGS="${_CUR_LDFLAGS}" - ;; -esac - -{ $as_echo "$as_me:$LINENO: checking for hstrerror" >&5 -$as_echo_n "checking for hstrerror... " >&6; } -cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ - -#include "confdefs.h" -#include - -int -main () -{ -void* p = hstrerror; hstrerror(0) - ; - return 0; -} -_ACEOF -rm -f conftest.$ac_objext conftest$ac_exeext -if { (ac_try="$ac_link" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" -$as_echo "$ac_try_echo") >&5 - (eval "$ac_link") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest$ac_exeext && { - test "$cross_compiling" = yes || - $as_test_x conftest$ac_exeext - }; then -cat >>confdefs.h <<\_ACEOF -#define HAVE_HSTRERROR 1 -_ACEOF - { $as_echo "$as_me:$LINENO: result: yes" >&5 -$as_echo "yes" >&6; } +# SO is the extension of shared libraries `(including the dot!) +# -- usually .so, .sl on HP-UX, .dll on Cygwin +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking SO" >&5 +$as_echo_n "checking SO... " >&6; } +if test -z "$SO" +then + case $ac_sys_system in + hp*|HP*) + case `uname -m` in + ia64) SO=.so;; + *) SO=.sl;; + esac + ;; + CYGWIN*) SO=.dll;; + *) SO=.so;; + esac else - $as_echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - { $as_echo "$as_me:$LINENO: result: no" >&5 -$as_echo "no" >&6; } - + # this might also be a termcap variable, see #610332 + echo + echo '=====================================================================' + echo '+ +' + echo '+ WARNING: You have set SO in your environment. +' + echo '+ Do you really mean to change the extension for shared libraries? +' + echo '+ Continuing in 10 seconds to let you to ponder. +' + echo '+ +' + echo '=====================================================================' + sleep 10 fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $SO" >&5 +$as_echo "$SO" >&6; } -rm -rf conftest.dSYM -rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \ - conftest$ac_exeext conftest.$ac_ext -{ $as_echo "$as_me:$LINENO: checking for inet_aton" >&5 -$as_echo_n "checking for inet_aton... " >&6; } -cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ +cat >>confdefs.h <<_ACEOF +#define SHLIB_EXT "$SO" _ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -#include "confdefs.h" -#include -#include -#include -#include +# LDSHARED is the ld *command* used to create shared library +# -- "cc -G" on SunOS 5.x, "ld -shared" on IRIX 5 +# (Shared libraries in this instance are shared modules to be loaded into +# Python, as opposed to building Python itself as a shared library.) +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking LDSHARED" >&5 +$as_echo_n "checking LDSHARED... " >&6; } +if test -z "$LDSHARED" +then + case $ac_sys_system/$ac_sys_release in + AIX*) + BLDSHARED="\$(srcdir)/Modules/ld_so_aix \$(CC) -bI:Modules/python.exp" + LDSHARED="\$(BINLIBDEST)/config/ld_so_aix \$(CC) -bI:\$(BINLIBDEST)/config/python.exp" + ;; + BeOS*) + BLDSHARED="\$(srcdir)/Modules/ld_so_beos $LDLIBRARY" + LDSHARED="\$(BINLIBDEST)/config/ld_so_beos \$(LIBDIR)/$LDLIBRARY" + ;; + IRIX/5*) LDSHARED="ld -shared";; + IRIX*/6*) LDSHARED="ld ${SGI_ABI} -shared -all";; + SunOS/5*) + if test "$GCC" = "yes" + then LDSHARED='$(CC) -shared' + else LDSHARED='$(CC) -G'; + fi ;; + hp*|HP*) + if test "$GCC" = "yes" + then LDSHARED='$(CC) -shared' + else LDSHARED='ld -b'; + fi ;; + OSF*) LDSHARED="ld -shared -expect_unresolved \"*\"";; + Darwin/1.3*) + LDSHARED='$(CC) $(LDFLAGS) -bundle' + if test "$enable_framework" ; then + # Link against the framework. All externals should be defined. + BLDSHARED="$LDSHARED "'$(PYTHONFRAMEWORKDIR)/Versions/$(VERSION)/$(PYTHONFRAMEWORK)' + LDSHARED="$LDSHARED "'$(PYTHONFRAMEWORKPREFIX)/$(PYTHONFRAMEWORKDIR)/Versions/$(VERSION)/$(PYTHONFRAMEWORK)' + else + # No framework. Ignore undefined symbols, assuming they come from Python + LDSHARED="$LDSHARED -undefined suppress" + fi ;; + Darwin/1.4*|Darwin/5.*|Darwin/6.*) + LDSHARED='$(CC) $(LDFLAGS) -bundle' + if test "$enable_framework" ; then + # Link against the framework. All externals should be defined. + BLDSHARED="$LDSHARED "'$(PYTHONFRAMEWORKDIR)/Versions/$(VERSION)/$(PYTHONFRAMEWORK)' + LDSHARED="$LDSHARED "'$(PYTHONFRAMEWORKPREFIX)/$(PYTHONFRAMEWORKDIR)/Versions/$(VERSION)/$(PYTHONFRAMEWORK)' + else + # No framework, use the Python app as bundle-loader + BLDSHARED="$LDSHARED "'-bundle_loader $(BUILDPYTHON)' + LDSHARED="$LDSHARED "'-bundle_loader $(BINDIR)/python$(VERSION)$(EXE)' + fi ;; + Darwin/*) + # Use -undefined dynamic_lookup whenever possible (10.3 and later). + # This allows an extension to be used in any Python -int -main () -{ -void* p = inet_aton;inet_aton(0,0) - ; - return 0; -} -_ACEOF -rm -f conftest.$ac_objext conftest$ac_exeext -if { (ac_try="$ac_link" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" -$as_echo "$ac_try_echo") >&5 - (eval "$ac_link") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest$ac_exeext && { - test "$cross_compiling" = yes || - $as_test_x conftest$ac_exeext - }; then + if test ${MACOSX_DEPLOYMENT_TARGET} '>' 10.2 + then + if test "${enable_universalsdk}"; then + LDFLAGS="${UNIVERSAL_ARCH_FLAGS} -isysroot ${UNIVERSALSDK} ${LDFLAGS}" + fi + LDSHARED='$(CC) $(LDFLAGS) -bundle -undefined dynamic_lookup' + BLDSHARED="$LDSHARED" + else + LDSHARED='$(CC) $(LDFLAGS) -bundle' + if test "$enable_framework" ; then + # Link against the framework. All externals should be defined. + BLDSHARED="$LDSHARED "'$(PYTHONFRAMEWORKDIR)/Versions/$(VERSION)/$(PYTHONFRAMEWORK)' + LDSHARED="$LDSHARED "'$(PYTHONFRAMEWORKPREFIX)/$(PYTHONFRAMEWORKDIR)/Versions/$(VERSION)/$(PYTHONFRAMEWORK)' + else + # No framework, use the Python app as bundle-loader + BLDSHARED="$LDSHARED "'-bundle_loader $(BUILDPYTHON)' + LDSHARED="$LDSHARED "'-bundle_loader $(BINDIR)/python$(VERSION)$(EXE)' + fi + fi + ;; + Linux*|GNU*|QNX*) LDSHARED='$(CC) -shared';; + BSD/OS*/4*) LDSHARED="gcc -shared";; + FreeBSD*) + if [ "`$CC -dM -E - &5 +$as_echo "$LDSHARED" >&6; } +BLDSHARED=${BLDSHARED-$LDSHARED} +# CCSHARED are the C *flags* used to create objects to go into a shared +# library (module) -- this is only needed for a few systems +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking CCSHARED" >&5 +$as_echo_n "checking CCSHARED... " >&6; } +if test -z "$CCSHARED" +then + case $ac_sys_system/$ac_sys_release in + SunOS*) if test "$GCC" = yes; + then CCSHARED="-fPIC"; + elif test `uname -p` = sparc; + then CCSHARED="-xcode=pic32"; + else CCSHARED="-Kpic"; + fi;; + hp*|HP*) if test "$GCC" = yes; + then CCSHARED="-fPIC"; + else CCSHARED="+z"; + fi;; + Linux*|GNU*) CCSHARED="-fPIC";; + BSD/OS*/4*) CCSHARED="-fpic";; + FreeBSD*|NetBSD*|OpenBSD*|DragonFly*) CCSHARED="-fPIC";; + OpenUNIX*|UnixWare*) + if test "$GCC" = "yes" + then CCSHARED="-fPIC" + else CCSHARED="-KPIC" + fi;; + SCO_SV*) + if test "$GCC" = "yes" + then CCSHARED="-fPIC" + else CCSHARED="-Kpic -belf" + fi;; + Monterey*) CCSHARED="-G";; + IRIX*/6*) case $CC in + *gcc*) CCSHARED="-shared";; + *) CCSHARED="";; + esac;; + atheos*) CCSHARED="-fPIC";; + esac +fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $CCSHARED" >&5 +$as_echo "$CCSHARED" >&6; } +# LINKFORSHARED are the flags passed to the $(CC) command that links +# the python executable -- this is only needed for a few systems +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking LINKFORSHARED" >&5 +$as_echo_n "checking LINKFORSHARED... " >&6; } +if test -z "$LINKFORSHARED" +then + case $ac_sys_system/$ac_sys_release in + AIX*) LINKFORSHARED='-Wl,-bE:Modules/python.exp -lld';; + hp*|HP*) + 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";; + # -u libsys_s pulls in all symbols in libsys + Darwin/*) + # -u _PyMac_Error is needed to pull in the mac toolbox glue, + # which is + # not used by the core itself but which needs to be in the core so + # that dynamically loaded extension modules have access to it. + # -prebind is no longer used, because it actually seems to give a + # slowdown in stead of a speedup, maybe due to the large number of + # dynamic loads Python does. -cat >>confdefs.h <<\_ACEOF -#define HAVE_INET_ATON 1 -_ACEOF + LINKFORSHARED="$extra_undefs" + if test "$enable_framework" + then + LINKFORSHARED="$LINKFORSHARED "'$(PYTHONFRAMEWORKDIR)/Versions/$(VERSION)/$(PYTHONFRAMEWORK)' + fi + LINKFORSHARED="$LINKFORSHARED";; + OpenUNIX*|UnixWare*) LINKFORSHARED="-Wl,-Bexport";; + SCO_SV*) LINKFORSHARED="-Wl,-Bexport";; + ReliantUNIX*) LINKFORSHARED="-W1 -Blargedynsym";; + FreeBSD*|NetBSD*|OpenBSD*|DragonFly*) + if [ "`$CC -dM -E - &1 | grep export-dynamic >/dev/null + then + LINKFORSHARED="-Xlinker --export-dynamic" + fi;; + esac;; + CYGWIN*) + if test $enable_shared = "no" + then + LINKFORSHARED='-Wl,--out-implib=$(LDLIBRARY)' + fi;; + QNX*) + # -Wl,-E causes the symbols to be added to the dynamic + # symbol table so that they can be found when a module + # is loaded. -N 2048K causes the stack size to be set + # to 2048 kilobytes so that the stack doesn't overflow + # when running test_compile.py. + LINKFORSHARED='-Wl,-E -N 2048K';; + esac +fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $LINKFORSHARED" >&5 +$as_echo "$LINKFORSHARED" >&6; } - { $as_echo "$as_me:$LINENO: result: yes" >&5 -$as_echo "yes" >&6; } -else - $as_echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - { $as_echo "$as_me:$LINENO: result: no" >&5 -$as_echo "no" >&6; } +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking CFLAGSFORSHARED" >&5 +$as_echo_n "checking CFLAGSFORSHARED... " >&6; } +if test ! "$LIBRARY" = "$LDLIBRARY" +then + case $ac_sys_system in + CYGWIN*) + # Cygwin needs CCSHARED when building extension DLLs + # but not when building the interpreter DLL. + CFLAGSFORSHARED='';; + *) + CFLAGSFORSHARED='$(CCSHARED)' + esac fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $CFLAGSFORSHARED" >&5 +$as_echo "$CFLAGSFORSHARED" >&6; } -rm -rf conftest.dSYM -rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \ - conftest$ac_exeext conftest.$ac_ext - -{ $as_echo "$as_me:$LINENO: checking for inet_pton" >&5 -$as_echo_n "checking for inet_pton... " >&6; } -cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ - -#include "confdefs.h" -#include -#include -#include -#include +# SHLIBS are libraries (except -lc and -lm) to link to the python shared +# library (with --enable-shared). +# For platforms on which shared libraries are not allowed to have unresolved +# symbols, this must be set to $(LIBS) (expanded by make). We do this even +# if it is not required, since it creates a dependency of the shared library +# to LIBS. This, in turn, means that applications linking the shared libpython +# don't need to link LIBS explicitly. The default should be only changed +# on systems where this approach causes problems. -int -main () -{ -void* p = inet_pton - ; - return 0; -} -_ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking SHLIBS" >&5 +$as_echo_n "checking SHLIBS... " >&6; } +case "$ac_sys_system" in + *) + SHLIBS='$(LIBS)';; esac -eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" -$as_echo "$ac_try_echo") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $SHLIBS" >&5 +$as_echo "$SHLIBS" >&6; } -cat >>confdefs.h <<\_ACEOF -#define HAVE_INET_PTON 1 -_ACEOF - { $as_echo "$as_me:$LINENO: result: yes" >&5 -$as_echo "yes" >&6; } +# checks for libraries +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for dlopen in -ldl" >&5 +$as_echo_n "checking for dlopen in -ldl... " >&6; } +if test "${ac_cv_lib_dl_dlopen+set}" = set; then : + $as_echo_n "(cached) " >&6 else - $as_echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - { $as_echo "$as_me:$LINENO: result: no" >&5 -$as_echo "no" >&6; } - -fi - -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext - -# On some systems, setgroups is in unistd.h, on others, in grp.h -{ $as_echo "$as_me:$LINENO: checking for setgroups" >&5 -$as_echo_n "checking for setgroups... " >&6; } -cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF + ac_check_lib_save_LIBS=$LIBS +LIBS="-ldl $LIBS" +cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ -#include "confdefs.h" -#include -#ifdef HAVE_GRP_H -#include +/* Override any GCC internal prototype to avoid an error. + Use char because int might match the return type of a GCC + builtin and then its argument prototype would still apply. */ +#ifdef __cplusplus +extern "C" #endif - +char dlopen (); int main () { -void* p = setgroups +return dlopen (); ; return 0; } _ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" -$as_echo "$ac_try_echo") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - -cat >>confdefs.h <<\_ACEOF -#define HAVE_SETGROUPS 1 -_ACEOF - - { $as_echo "$as_me:$LINENO: result: yes" >&5 -$as_echo "yes" >&6; } +if ac_fn_c_try_link "$LINENO"; then : + ac_cv_lib_dl_dlopen=yes else - $as_echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - { $as_echo "$as_me:$LINENO: result: no" >&5 -$as_echo "no" >&6; } - + ac_cv_lib_dl_dlopen=no fi +rm -f core conftest.err conftest.$ac_objext \ + conftest$ac_exeext conftest.$ac_ext +LIBS=$ac_check_lib_save_LIBS +fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_lib_dl_dlopen" >&5 +$as_echo "$ac_cv_lib_dl_dlopen" >&6; } +if test "x$ac_cv_lib_dl_dlopen" = x""yes; then : + cat >>confdefs.h <<_ACEOF +#define HAVE_LIBDL 1 +_ACEOF -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext - -# check for openpty and forkpty - + LIBS="-ldl $LIBS" -for ac_func in openpty -do -as_ac_var=`$as_echo "ac_cv_func_$ac_func" | $as_tr_sh` -{ $as_echo "$as_me:$LINENO: checking for $ac_func" >&5 -$as_echo_n "checking for $ac_func... " >&6; } -if { as_var=$as_ac_var; eval "test \"\${$as_var+set}\" = set"; }; then +fi + # Dynamic linking for SunOS/Solaris and SYSV +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for shl_load in -ldld" >&5 +$as_echo_n "checking for shl_load in -ldld... " >&6; } +if test "${ac_cv_lib_dld_shl_load+set}" = set; then : $as_echo_n "(cached) " >&6 else - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF + ac_check_lib_save_LIBS=$LIBS +LIBS="-ldld $LIBS" +cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ -/* Define $ac_func to an innocuous variant, in case declares $ac_func. - For example, HP-UX 11i declares gettimeofday. */ -#define $ac_func innocuous_$ac_func - -/* System header to define __stub macros and hopefully few prototypes, - which can conflict with char $ac_func (); below. - Prefer to if __STDC__ is defined, since - exists even on freestanding compilers. */ - -#ifdef __STDC__ -# include -#else -# include -#endif - -#undef $ac_func /* Override any GCC internal prototype to avoid an error. Use char because int might match the return type of a GCC @@ -18344,79 +7625,45 @@ #ifdef __cplusplus extern "C" #endif -char $ac_func (); -/* The GNU C library defines this for functions which it implements - to always fail with ENOSYS. Some functions are actually named - something starting with __ and the normal name is an alias. */ -#if defined __stub_$ac_func || defined __stub___$ac_func -choke me -#endif - +char shl_load (); int main () { -return $ac_func (); +return shl_load (); ; return 0; } _ACEOF -rm -f conftest.$ac_objext conftest$ac_exeext -if { (ac_try="$ac_link" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" -$as_echo "$ac_try_echo") >&5 - (eval "$ac_link") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest$ac_exeext && { - test "$cross_compiling" = yes || - $as_test_x conftest$ac_exeext - }; then - eval "$as_ac_var=yes" +if ac_fn_c_try_link "$LINENO"; then : + ac_cv_lib_dld_shl_load=yes else - $as_echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - eval "$as_ac_var=no" + ac_cv_lib_dld_shl_load=no fi - -rm -rf conftest.dSYM -rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \ - conftest$ac_exeext conftest.$ac_ext +rm -f core conftest.err conftest.$ac_objext \ + conftest$ac_exeext conftest.$ac_ext +LIBS=$ac_check_lib_save_LIBS fi -ac_res=`eval 'as_val=${'$as_ac_var'} - $as_echo "$as_val"'` - { $as_echo "$as_me:$LINENO: result: $ac_res" >&5 -$as_echo "$ac_res" >&6; } -as_val=`eval 'as_val=${'$as_ac_var'} - $as_echo "$as_val"'` - if test "x$as_val" = x""yes; then +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_lib_dld_shl_load" >&5 +$as_echo "$ac_cv_lib_dld_shl_load" >&6; } +if test "x$ac_cv_lib_dld_shl_load" = x""yes; then : cat >>confdefs.h <<_ACEOF -#define `$as_echo "HAVE_$ac_func" | $as_tr_cpp` 1 +#define HAVE_LIBDLD 1 _ACEOF -else - { $as_echo "$as_me:$LINENO: checking for openpty in -lutil" >&5 -$as_echo_n "checking for openpty in -lutil... " >&6; } -if test "${ac_cv_lib_util_openpty+set}" = set; then + LIBS="-ldld $LIBS" + +fi + # Dynamic linking for HP-UX + +# only check for sem_init if thread support is requested +if test "$with_threads" = "yes" -o -z "$with_threads"; then + { $as_echo "$as_me:${as_lineno-$LINENO}: checking for library containing sem_init" >&5 +$as_echo_n "checking for library containing sem_init... " >&6; } +if test "${ac_cv_search_sem_init+set}" = set; then : $as_echo_n "(cached) " >&6 else - ac_check_lib_save_LIBS=$LIBS -LIBS="-lutil $LIBS" -cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF + ac_func_search_save_LIBS=$LIBS +cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ /* Override any GCC internal prototype to avoid an error. @@ -18425,69 +7672,60 @@ #ifdef __cplusplus extern "C" #endif -char openpty (); +char sem_init (); int main () { -return openpty (); +return sem_init (); ; return 0; } _ACEOF -rm -f conftest.$ac_objext conftest$ac_exeext -if { (ac_try="$ac_link" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" -$as_echo "$ac_try_echo") >&5 - (eval "$ac_link") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest$ac_exeext && { - test "$cross_compiling" = yes || - $as_test_x conftest$ac_exeext - }; then - ac_cv_lib_util_openpty=yes -else - $as_echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 +for ac_lib in '' pthread rt posix4; do + if test -z "$ac_lib"; then + ac_res="none required" + else + ac_res=-l$ac_lib + LIBS="-l$ac_lib $ac_func_search_save_LIBS" + fi + if ac_fn_c_try_link "$LINENO"; then : + ac_cv_search_sem_init=$ac_res +fi +rm -f core conftest.err conftest.$ac_objext \ + conftest$ac_exeext + if test "${ac_cv_search_sem_init+set}" = set; then : + break +fi +done +if test "${ac_cv_search_sem_init+set}" = set; then : - ac_cv_lib_util_openpty=no +else + ac_cv_search_sem_init=no fi +rm conftest.$ac_ext +LIBS=$ac_func_search_save_LIBS +fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_search_sem_init" >&5 +$as_echo "$ac_cv_search_sem_init" >&6; } +ac_res=$ac_cv_search_sem_init +if test "$ac_res" != no; then : + test "$ac_res" = "none required" || LIBS="$ac_res $LIBS" -rm -rf conftest.dSYM -rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \ - conftest$ac_exeext conftest.$ac_ext -LIBS=$ac_check_lib_save_LIBS fi -{ $as_echo "$as_me:$LINENO: result: $ac_cv_lib_util_openpty" >&5 -$as_echo "$ac_cv_lib_util_openpty" >&6; } -if test "x$ac_cv_lib_util_openpty" = x""yes; then - cat >>confdefs.h <<\_ACEOF -#define HAVE_OPENPTY 1 -_ACEOF - LIBS="$LIBS -lutil" -else - { $as_echo "$as_me:$LINENO: checking for openpty in -lbsd" >&5 -$as_echo_n "checking for openpty in -lbsd... " >&6; } -if test "${ac_cv_lib_bsd_openpty+set}" = set; then + # 'Real Time' functions on Solaris + # posix4 on Solaris 2.6 + # pthread (first!) on Linux +fi + +# check if we need libintl for locale functions +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for textdomain in -lintl" >&5 +$as_echo_n "checking for textdomain in -lintl... " >&6; } +if test "${ac_cv_lib_intl_textdomain+set}" = set; then : $as_echo_n "(cached) " >&6 else ac_check_lib_save_LIBS=$LIBS -LIBS="-lbsd $LIBS" -cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF +LIBS="-lintl $LIBS" +cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ /* Override any GCC internal prototype to avoid an error. @@ -18496,96 +7734,74 @@ #ifdef __cplusplus extern "C" #endif -char openpty (); +char textdomain (); int main () { -return openpty (); +return textdomain (); ; return 0; } _ACEOF -rm -f conftest.$ac_objext conftest$ac_exeext -if { (ac_try="$ac_link" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" -$as_echo "$ac_try_echo") >&5 - (eval "$ac_link") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest$ac_exeext && { - test "$cross_compiling" = yes || - $as_test_x conftest$ac_exeext - }; then - ac_cv_lib_bsd_openpty=yes +if ac_fn_c_try_link "$LINENO"; then : + ac_cv_lib_intl_textdomain=yes else - $as_echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - ac_cv_lib_bsd_openpty=no + ac_cv_lib_intl_textdomain=no fi - -rm -rf conftest.dSYM -rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \ - conftest$ac_exeext conftest.$ac_ext +rm -f core conftest.err conftest.$ac_objext \ + conftest$ac_exeext conftest.$ac_ext LIBS=$ac_check_lib_save_LIBS fi -{ $as_echo "$as_me:$LINENO: result: $ac_cv_lib_bsd_openpty" >&5 -$as_echo "$ac_cv_lib_bsd_openpty" >&6; } -if test "x$ac_cv_lib_bsd_openpty" = x""yes; then - cat >>confdefs.h <<\_ACEOF -#define HAVE_OPENPTY 1 -_ACEOF - LIBS="$LIBS -lbsd" -fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_lib_intl_textdomain" >&5 +$as_echo "$ac_cv_lib_intl_textdomain" >&6; } +if test "x$ac_cv_lib_intl_textdomain" = x""yes; then : +$as_echo "#define WITH_LIBINTL 1" >>confdefs.h fi +# checks for system dependent C++ extensions support +case "$ac_sys_system" in + AIX*) { $as_echo "$as_me:${as_lineno-$LINENO}: checking for genuine AIX C++ extensions support" >&5 +$as_echo_n "checking for genuine AIX C++ extensions support... " >&6; } + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ +#include "/usr/lpp/xlC/include/load.h" +int +main () +{ +loadAndInit("", 0, "") + ; + return 0; +} +_ACEOF +if ac_fn_c_try_link "$LINENO"; then : + +$as_echo "#define AIX_GENUINE_CPLUSPLUS 1" >>confdefs.h + + { $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +$as_echo "yes" >&6; } +else + { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 +$as_echo "no" >&6; } fi -done - +rm -f core conftest.err conftest.$ac_objext \ + conftest$ac_exeext conftest.$ac_ext;; + *) ;; +esac -for ac_func in forkpty -do -as_ac_var=`$as_echo "ac_cv_func_$ac_func" | $as_tr_sh` -{ $as_echo "$as_me:$LINENO: checking for $ac_func" >&5 -$as_echo_n "checking for $ac_func... " >&6; } -if { as_var=$as_ac_var; eval "test \"\${$as_var+set}\" = set"; }; then +# Most SVR4 platforms (e.g. Solaris) need -lsocket and -lnsl. +# BeOS' sockets are stashed in libnet. +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for t_open in -lnsl" >&5 +$as_echo_n "checking for t_open in -lnsl... " >&6; } +if test "${ac_cv_lib_nsl_t_open+set}" = set; then : $as_echo_n "(cached) " >&6 else - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF + ac_check_lib_save_LIBS=$LIBS +LIBS="-lnsl $LIBS" +cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ -/* Define $ac_func to an innocuous variant, in case declares $ac_func. - For example, HP-UX 11i declares gettimeofday. */ -#define $ac_func innocuous_$ac_func - -/* System header to define __stub macros and hopefully few prototypes, - which can conflict with char $ac_func (); below. - Prefer to if __STDC__ is defined, since - exists even on freestanding compilers. */ - -#ifdef __STDC__ -# include -#else -# include -#endif - -#undef $ac_func /* Override any GCC internal prototype to avoid an error. Use char because int might match the return type of a GCC @@ -18593,79 +7809,38 @@ #ifdef __cplusplus extern "C" #endif -char $ac_func (); -/* The GNU C library defines this for functions which it implements - to always fail with ENOSYS. Some functions are actually named - something starting with __ and the normal name is an alias. */ -#if defined __stub_$ac_func || defined __stub___$ac_func -choke me -#endif - +char t_open (); int main () { -return $ac_func (); +return t_open (); ; return 0; } _ACEOF -rm -f conftest.$ac_objext conftest$ac_exeext -if { (ac_try="$ac_link" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" -$as_echo "$ac_try_echo") >&5 - (eval "$ac_link") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest$ac_exeext && { - test "$cross_compiling" = yes || - $as_test_x conftest$ac_exeext - }; then - eval "$as_ac_var=yes" +if ac_fn_c_try_link "$LINENO"; then : + ac_cv_lib_nsl_t_open=yes else - $as_echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - eval "$as_ac_var=no" + ac_cv_lib_nsl_t_open=no fi - -rm -rf conftest.dSYM -rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \ - conftest$ac_exeext conftest.$ac_ext +rm -f core conftest.err conftest.$ac_objext \ + conftest$ac_exeext conftest.$ac_ext +LIBS=$ac_check_lib_save_LIBS fi -ac_res=`eval 'as_val=${'$as_ac_var'} - $as_echo "$as_val"'` - { $as_echo "$as_me:$LINENO: result: $ac_res" >&5 -$as_echo "$ac_res" >&6; } -as_val=`eval 'as_val=${'$as_ac_var'} - $as_echo "$as_val"'` - if test "x$as_val" = x""yes; then - cat >>confdefs.h <<_ACEOF -#define `$as_echo "HAVE_$ac_func" | $as_tr_cpp` 1 -_ACEOF - -else - { $as_echo "$as_me:$LINENO: checking for forkpty in -lutil" >&5 -$as_echo_n "checking for forkpty in -lutil... " >&6; } -if test "${ac_cv_lib_util_forkpty+set}" = set; then +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_lib_nsl_t_open" >&5 +$as_echo "$ac_cv_lib_nsl_t_open" >&6; } +if test "x$ac_cv_lib_nsl_t_open" = x""yes; then : + LIBS="-lnsl $LIBS" +fi + # SVR4 +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for socket in -lsocket" >&5 +$as_echo_n "checking for socket in -lsocket... " >&6; } +if test "${ac_cv_lib_socket_socket+set}" = set; then : $as_echo_n "(cached) " >&6 else ac_check_lib_save_LIBS=$LIBS -LIBS="-lutil $LIBS" -cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF +LIBS="-lsocket $LIBS $LIBS" +cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ /* Override any GCC internal prototype to avoid an error. @@ -18674,69 +7849,41 @@ #ifdef __cplusplus extern "C" #endif -char forkpty (); +char socket (); int main () { -return forkpty (); +return socket (); ; return 0; } _ACEOF -rm -f conftest.$ac_objext conftest$ac_exeext -if { (ac_try="$ac_link" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" -$as_echo "$ac_try_echo") >&5 - (eval "$ac_link") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest$ac_exeext && { - test "$cross_compiling" = yes || - $as_test_x conftest$ac_exeext - }; then - ac_cv_lib_util_forkpty=yes +if ac_fn_c_try_link "$LINENO"; then : + ac_cv_lib_socket_socket=yes else - $as_echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - ac_cv_lib_util_forkpty=no + ac_cv_lib_socket_socket=no fi - -rm -rf conftest.dSYM -rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \ - conftest$ac_exeext conftest.$ac_ext +rm -f core conftest.err conftest.$ac_objext \ + conftest$ac_exeext conftest.$ac_ext LIBS=$ac_check_lib_save_LIBS fi -{ $as_echo "$as_me:$LINENO: result: $ac_cv_lib_util_forkpty" >&5 -$as_echo "$ac_cv_lib_util_forkpty" >&6; } -if test "x$ac_cv_lib_util_forkpty" = x""yes; then - cat >>confdefs.h <<\_ACEOF -#define HAVE_FORKPTY 1 -_ACEOF - LIBS="$LIBS -lutil" -else - { $as_echo "$as_me:$LINENO: checking for forkpty in -lbsd" >&5 -$as_echo_n "checking for forkpty in -lbsd... " >&6; } -if test "${ac_cv_lib_bsd_forkpty+set}" = set; then +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_lib_socket_socket" >&5 +$as_echo "$ac_cv_lib_socket_socket" >&6; } +if test "x$ac_cv_lib_socket_socket" = x""yes; then : + LIBS="-lsocket $LIBS" +fi + # SVR4 sockets + +case "$ac_sys_system" in +BeOS*) +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for socket in -lnet" >&5 +$as_echo_n "checking for socket in -lnet... " >&6; } +if test "${ac_cv_lib_net_socket+set}" = set; then : $as_echo_n "(cached) " >&6 else ac_check_lib_save_LIBS=$LIBS -LIBS="-lbsd $LIBS" -cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF +LIBS="-lnet $LIBS $LIBS" +cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ /* Override any GCC internal prototype to avoid an error. @@ -18745,206 +7892,330 @@ #ifdef __cplusplus extern "C" #endif -char forkpty (); +char socket (); int main () { -return forkpty (); +return socket (); ; return 0; } _ACEOF -rm -f conftest.$ac_objext conftest$ac_exeext -if { (ac_try="$ac_link" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; +if ac_fn_c_try_link "$LINENO"; then : + ac_cv_lib_net_socket=yes +else + ac_cv_lib_net_socket=no +fi +rm -f core conftest.err conftest.$ac_objext \ + conftest$ac_exeext conftest.$ac_ext +LIBS=$ac_check_lib_save_LIBS +fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_lib_net_socket" >&5 +$as_echo "$ac_cv_lib_net_socket" >&6; } +if test "x$ac_cv_lib_net_socket" = x""yes; then : + LIBS="-lnet $LIBS" +fi + # BeOS +;; esac -eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" -$as_echo "$ac_try_echo") >&5 - (eval "$ac_link") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest$ac_exeext && { - test "$cross_compiling" = yes || - $as_test_x conftest$ac_exeext - }; then - ac_cv_lib_bsd_forkpty=yes + +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for --with-libs" >&5 +$as_echo_n "checking for --with-libs... " >&6; } + +# Check whether --with-libs was given. +if test "${with_libs+set}" = set; then : + withval=$with_libs; +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $withval" >&5 +$as_echo "$withval" >&6; } +LIBS="$withval $LIBS" + else - $as_echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 + { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 +$as_echo "no" >&6; } +fi + + +# Check for use of the system libffi library +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for --with-system-ffi" >&5 +$as_echo_n "checking for --with-system-ffi... " >&6; } + +# Check whether --with-system_ffi was given. +if test "${with_system_ffi+set}" = set; then : + withval=$with_system_ffi; +fi + + +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $with_system_ffi" >&5 +$as_echo "$with_system_ffi" >&6; } + +# Determine if signalmodule should be used. + + +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for --with-signal-module" >&5 +$as_echo_n "checking for --with-signal-module... " >&6; } + +# Check whether --with-signal-module was given. +if test "${with_signal_module+set}" = set; then : + withval=$with_signal_module; +fi + + +if test -z "$with_signal_module" +then with_signal_module="yes" +fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $with_signal_module" >&5 +$as_echo "$with_signal_module" >&6; } + +if test "${with_signal_module}" = "yes"; then + USE_SIGNAL_MODULE="" + SIGNAL_OBJS="" +else + USE_SIGNAL_MODULE="#" + SIGNAL_OBJS="Parser/intrcheck.o Python/sigcheck.o" +fi + +# This is used to generate Setup.config + +USE_THREAD_MODULE="" + +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for --with-dec-threads" >&5 +$as_echo_n "checking for --with-dec-threads... " >&6; } + + +# Check whether --with-dec-threads was given. +if test "${with_dec_threads+set}" = set; then : + withval=$with_dec_threads; +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $withval" >&5 +$as_echo "$withval" >&6; } +LDLAST=-threads +if test "${with_thread+set}" != set; then + with_thread="$withval"; +fi +else + { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 +$as_echo "no" >&6; } +fi + + +# Templates for things AC_DEFINEd more than once. +# For a single AC_DEFINE, no template is needed. + + + + +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for --with-threads" >&5 +$as_echo_n "checking for --with-threads... " >&6; } + +# Check whether --with-threads was given. +if test "${with_threads+set}" = set; then : + withval=$with_threads; +fi + + +# --with-thread is deprecated, but check for it anyway + +# Check whether --with-thread was given. +if test "${with_thread+set}" = set; then : + withval=$with_thread; with_threads=$with_thread +fi + + +if test -z "$with_threads" +then with_threads="yes" +fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $with_threads" >&5 +$as_echo "$with_threads" >&6; } + + +if test "$with_threads" = "no" +then + USE_THREAD_MODULE="#" +elif test "$ac_cv_pthread_is_default" = yes +then + $as_echo "#define WITH_THREAD 1" >>confdefs.h + + # Defining _REENTRANT on system with POSIX threads should not hurt. + $as_echo "#define _REENTRANT 1" >>confdefs.h + + posix_threads=yes + THREADOBJ="Python/thread.o" +elif test "$ac_cv_kpthread" = "yes" +then + CC="$CC -Kpthread" + if test "$ac_cv_cxx_thread" = "yes"; then + CXX="$CXX -Kpthread" + fi + $as_echo "#define WITH_THREAD 1" >>confdefs.h + + posix_threads=yes + THREADOBJ="Python/thread.o" +elif test "$ac_cv_kthread" = "yes" +then + CC="$CC -Kthread" + if test "$ac_cv_cxx_thread" = "yes"; then + CXX="$CXX -Kthread" + fi + $as_echo "#define WITH_THREAD 1" >>confdefs.h + + posix_threads=yes + THREADOBJ="Python/thread.o" +elif test "$ac_cv_pthread" = "yes" +then + CC="$CC -pthread" + if test "$ac_cv_cxx_thread" = "yes"; then + CXX="$CXX -pthread" + fi + $as_echo "#define WITH_THREAD 1" >>confdefs.h + + posix_threads=yes + THREADOBJ="Python/thread.o" +else + if test ! -z "$with_threads" -a -d "$with_threads" + then LDFLAGS="$LDFLAGS -L$with_threads" + fi + if test ! -z "$withval" -a -d "$withval" + then LDFLAGS="$LDFLAGS -L$withval" + fi - ac_cv_lib_bsd_forkpty=no -fi + # According to the POSIX spec, a pthreads implementation must + # define _POSIX_THREADS in unistd.h. Some apparently don't + # (e.g. gnu pth with pthread emulation) + { $as_echo "$as_me:${as_lineno-$LINENO}: checking for _POSIX_THREADS in unistd.h" >&5 +$as_echo_n "checking for _POSIX_THREADS in unistd.h... " >&6; } + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + +#include +#ifdef _POSIX_THREADS +yes +#endif -rm -rf conftest.dSYM -rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \ - conftest$ac_exeext conftest.$ac_ext -LIBS=$ac_check_lib_save_LIBS -fi -{ $as_echo "$as_me:$LINENO: result: $ac_cv_lib_bsd_forkpty" >&5 -$as_echo "$ac_cv_lib_bsd_forkpty" >&6; } -if test "x$ac_cv_lib_bsd_forkpty" = x""yes; then - cat >>confdefs.h <<\_ACEOF -#define HAVE_FORKPTY 1 _ACEOF - LIBS="$LIBS -lbsd" +if (eval "$ac_cpp conftest.$ac_ext") 2>&5 | + $EGREP "yes" >/dev/null 2>&1; then : + unistd_defines_pthreads=yes +else + unistd_defines_pthreads=no fi +rm -f conftest* + { $as_echo "$as_me:${as_lineno-$LINENO}: result: $unistd_defines_pthreads" >&5 +$as_echo "$unistd_defines_pthreads" >&6; } -fi + $as_echo "#define _REENTRANT 1" >>confdefs.h + ac_fn_c_check_header_mongrel "$LINENO" "cthreads.h" "ac_cv_header_cthreads_h" "$ac_includes_default" +if test "x$ac_cv_header_cthreads_h" = x""yes; then : + $as_echo "#define WITH_THREAD 1" >>confdefs.h -fi -done + $as_echo "#define C_THREADS 1" >>confdefs.h -# Stuff for expat. +$as_echo "#define HURD_C_THREADS 1" >>confdefs.h -for ac_func in memmove -do -as_ac_var=`$as_echo "ac_cv_func_$ac_func" | $as_tr_sh` -{ $as_echo "$as_me:$LINENO: checking for $ac_func" >&5 -$as_echo_n "checking for $ac_func... " >&6; } -if { as_var=$as_ac_var; eval "test \"\${$as_var+set}\" = set"; }; then - $as_echo_n "(cached) " >&6 + LIBS="$LIBS -lthreads" + THREADOBJ="Python/thread.o" else - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -/* Define $ac_func to an innocuous variant, in case declares $ac_func. - For example, HP-UX 11i declares gettimeofday. */ -#define $ac_func innocuous_$ac_func -/* System header to define __stub macros and hopefully few prototypes, - which can conflict with char $ac_func (); below. - Prefer to if __STDC__ is defined, since - exists even on freestanding compilers. */ + ac_fn_c_check_header_mongrel "$LINENO" "mach/cthreads.h" "ac_cv_header_mach_cthreads_h" "$ac_includes_default" +if test "x$ac_cv_header_mach_cthreads_h" = x""yes; then : + $as_echo "#define WITH_THREAD 1" >>confdefs.h -#ifdef __STDC__ -# include -#else -# include -#endif + $as_echo "#define C_THREADS 1" >>confdefs.h -#undef $ac_func -/* Override any GCC internal prototype to avoid an error. - Use char because int might match the return type of a GCC - builtin and then its argument prototype would still apply. */ -#ifdef __cplusplus -extern "C" -#endif -char $ac_func (); -/* The GNU C library defines this for functions which it implements - to always fail with ENOSYS. Some functions are actually named - something starting with __ and the normal name is an alias. */ -#if defined __stub_$ac_func || defined __stub___$ac_func -choke me -#endif +$as_echo "#define MACH_C_THREADS 1" >>confdefs.h + + THREADOBJ="Python/thread.o" +else + + { $as_echo "$as_me:${as_lineno-$LINENO}: checking for --with-pth" >&5 +$as_echo_n "checking for --with-pth... " >&6; } + +# Check whether --with-pth was given. +if test "${with_pth+set}" = set; then : + withval=$with_pth; { $as_echo "$as_me:${as_lineno-$LINENO}: result: $withval" >&5 +$as_echo "$withval" >&6; } + $as_echo "#define WITH_THREAD 1" >>confdefs.h + + +$as_echo "#define HAVE_PTH 1" >>confdefs.h + + LIBS="-lpth $LIBS" + THREADOBJ="Python/thread.o" +else + { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 +$as_echo "no" >&6; } + + # Just looking for pthread_create in libpthread is not enough: + # on HP/UX, pthread.h renames pthread_create to a different symbol name. + # So we really have to include pthread.h, and then link. + _libs=$LIBS + LIBS="$LIBS -lpthread" + { $as_echo "$as_me:${as_lineno-$LINENO}: checking for pthread_create in -lpthread" >&5 +$as_echo_n "checking for pthread_create in -lpthread... " >&6; } + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ +#include +void * start_routine (void *arg) { exit (0); } int main () { -return $ac_func (); + +pthread_create (NULL, NULL, start_routine, NULL) ; return 0; } _ACEOF -rm -f conftest.$ac_objext conftest$ac_exeext -if { (ac_try="$ac_link" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" -$as_echo "$ac_try_echo") >&5 - (eval "$ac_link") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest$ac_exeext && { - test "$cross_compiling" = yes || - $as_test_x conftest$ac_exeext - }; then - eval "$as_ac_var=yes" +if ac_fn_c_try_link "$LINENO"; then : + + { $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +$as_echo "yes" >&6; } + $as_echo "#define WITH_THREAD 1" >>confdefs.h + + posix_threads=yes + THREADOBJ="Python/thread.o" else - $as_echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - eval "$as_ac_var=no" -fi + LIBS=$_libs + ac_fn_c_check_func "$LINENO" "pthread_detach" "ac_cv_func_pthread_detach" +if test "x$ac_cv_func_pthread_detach" = x""yes; then : + $as_echo "#define WITH_THREAD 1" >>confdefs.h -rm -rf conftest.dSYM -rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \ - conftest$ac_exeext conftest.$ac_ext -fi -ac_res=`eval 'as_val=${'$as_ac_var'} - $as_echo "$as_val"'` - { $as_echo "$as_me:$LINENO: result: $ac_res" >&5 -$as_echo "$ac_res" >&6; } -as_val=`eval 'as_val=${'$as_ac_var'} - $as_echo "$as_val"'` - if test "x$as_val" = x""yes; then - cat >>confdefs.h <<_ACEOF -#define `$as_echo "HAVE_$ac_func" | $as_tr_cpp` 1 -_ACEOF + posix_threads=yes + THREADOBJ="Python/thread.o" +else -fi -done + ac_fn_c_check_header_mongrel "$LINENO" "atheos/threads.h" "ac_cv_header_atheos_threads_h" "$ac_includes_default" +if test "x$ac_cv_header_atheos_threads_h" = x""yes; then : + $as_echo "#define WITH_THREAD 1" >>confdefs.h -# check for long file support functions +$as_echo "#define ATHEOS_THREADS 1" >>confdefs.h + THREADOBJ="Python/thread.o" +else + ac_fn_c_check_header_mongrel "$LINENO" "kernel/OS.h" "ac_cv_header_kernel_OS_h" "$ac_includes_default" +if test "x$ac_cv_header_kernel_OS_h" = x""yes; then : + $as_echo "#define WITH_THREAD 1" >>confdefs.h +$as_echo "#define BEOS_THREADS 1" >>confdefs.h + THREADOBJ="Python/thread.o" +else -for ac_func in fseek64 fseeko fstatvfs ftell64 ftello statvfs -do -as_ac_var=`$as_echo "ac_cv_func_$ac_func" | $as_tr_sh` -{ $as_echo "$as_me:$LINENO: checking for $ac_func" >&5 -$as_echo_n "checking for $ac_func... " >&6; } -if { as_var=$as_ac_var; eval "test \"\${$as_var+set}\" = set"; }; then + { $as_echo "$as_me:${as_lineno-$LINENO}: checking for pthread_create in -lpthreads" >&5 +$as_echo_n "checking for pthread_create in -lpthreads... " >&6; } +if test "${ac_cv_lib_pthreads_pthread_create+set}" = set; then : $as_echo_n "(cached) " >&6 else - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF + ac_check_lib_save_LIBS=$LIBS +LIBS="-lpthreads $LIBS" +cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ -/* Define $ac_func to an innocuous variant, in case declares $ac_func. - For example, HP-UX 11i declares gettimeofday. */ -#define $ac_func innocuous_$ac_func - -/* System header to define __stub macros and hopefully few prototypes, - which can conflict with char $ac_func (); below. - Prefer to if __STDC__ is defined, since - exists even on freestanding compilers. */ - -#ifdef __STDC__ -# include -#else -# include -#endif - -#undef $ac_func /* Override any GCC internal prototype to avoid an error. Use char because int might match the return type of a GCC @@ -18952,103 +8223,43 @@ #ifdef __cplusplus extern "C" #endif -char $ac_func (); -/* The GNU C library defines this for functions which it implements - to always fail with ENOSYS. Some functions are actually named - something starting with __ and the normal name is an alias. */ -#if defined __stub_$ac_func || defined __stub___$ac_func -choke me -#endif - +char pthread_create (); int main () { -return $ac_func (); +return pthread_create (); ; return 0; } _ACEOF -rm -f conftest.$ac_objext conftest$ac_exeext -if { (ac_try="$ac_link" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" -$as_echo "$ac_try_echo") >&5 - (eval "$ac_link") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest$ac_exeext && { - test "$cross_compiling" = yes || - $as_test_x conftest$ac_exeext - }; then - eval "$as_ac_var=yes" +if ac_fn_c_try_link "$LINENO"; then : + ac_cv_lib_pthreads_pthread_create=yes else - $as_echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - eval "$as_ac_var=no" -fi - -rm -rf conftest.dSYM -rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \ - conftest$ac_exeext conftest.$ac_ext + ac_cv_lib_pthreads_pthread_create=no fi -ac_res=`eval 'as_val=${'$as_ac_var'} - $as_echo "$as_val"'` - { $as_echo "$as_me:$LINENO: result: $ac_res" >&5 -$as_echo "$ac_res" >&6; } -as_val=`eval 'as_val=${'$as_ac_var'} - $as_echo "$as_val"'` - if test "x$as_val" = x""yes; then - cat >>confdefs.h <<_ACEOF -#define `$as_echo "HAVE_$ac_func" | $as_tr_cpp` 1 -_ACEOF - +rm -f core conftest.err conftest.$ac_objext \ + conftest$ac_exeext conftest.$ac_ext +LIBS=$ac_check_lib_save_LIBS fi -done - - - +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_lib_pthreads_pthread_create" >&5 +$as_echo "$ac_cv_lib_pthreads_pthread_create" >&6; } +if test "x$ac_cv_lib_pthreads_pthread_create" = x""yes; then : + $as_echo "#define WITH_THREAD 1" >>confdefs.h + posix_threads=yes + LIBS="$LIBS -lpthreads" + THREADOBJ="Python/thread.o" +else -for ac_func in dup2 getcwd strdup -do -as_ac_var=`$as_echo "ac_cv_func_$ac_func" | $as_tr_sh` -{ $as_echo "$as_me:$LINENO: checking for $ac_func" >&5 -$as_echo_n "checking for $ac_func... " >&6; } -if { as_var=$as_ac_var; eval "test \"\${$as_var+set}\" = set"; }; then + { $as_echo "$as_me:${as_lineno-$LINENO}: checking for pthread_create in -lc_r" >&5 +$as_echo_n "checking for pthread_create in -lc_r... " >&6; } +if test "${ac_cv_lib_c_r_pthread_create+set}" = set; then : $as_echo_n "(cached) " >&6 else - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF + ac_check_lib_save_LIBS=$LIBS +LIBS="-lc_r $LIBS" +cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ -/* Define $ac_func to an innocuous variant, in case declares $ac_func. - For example, HP-UX 11i declares gettimeofday. */ -#define $ac_func innocuous_$ac_func - -/* System header to define __stub macros and hopefully few prototypes, - which can conflict with char $ac_func (); below. - Prefer to if __STDC__ is defined, since - exists even on freestanding compilers. */ - -#ifdef __STDC__ -# include -#else -# include -#endif - -#undef $ac_func /* Override any GCC internal prototype to avoid an error. Use char because int might match the return type of a GCC @@ -19056,108 +8267,43 @@ #ifdef __cplusplus extern "C" #endif -char $ac_func (); -/* The GNU C library defines this for functions which it implements - to always fail with ENOSYS. Some functions are actually named - something starting with __ and the normal name is an alias. */ -#if defined __stub_$ac_func || defined __stub___$ac_func -choke me -#endif - +char pthread_create (); int main () { -return $ac_func (); +return pthread_create (); ; return 0; } _ACEOF -rm -f conftest.$ac_objext conftest$ac_exeext -if { (ac_try="$ac_link" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" -$as_echo "$ac_try_echo") >&5 - (eval "$ac_link") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest$ac_exeext && { - test "$cross_compiling" = yes || - $as_test_x conftest$ac_exeext - }; then - eval "$as_ac_var=yes" +if ac_fn_c_try_link "$LINENO"; then : + ac_cv_lib_c_r_pthread_create=yes else - $as_echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - eval "$as_ac_var=no" -fi - -rm -rf conftest.dSYM -rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \ - conftest$ac_exeext conftest.$ac_ext + ac_cv_lib_c_r_pthread_create=no fi -ac_res=`eval 'as_val=${'$as_ac_var'} - $as_echo "$as_val"'` - { $as_echo "$as_me:$LINENO: result: $ac_res" >&5 -$as_echo "$ac_res" >&6; } -as_val=`eval 'as_val=${'$as_ac_var'} - $as_echo "$as_val"'` - if test "x$as_val" = x""yes; then - cat >>confdefs.h <<_ACEOF -#define `$as_echo "HAVE_$ac_func" | $as_tr_cpp` 1 -_ACEOF - -else - case " $LIBOBJS " in - *" $ac_func.$ac_objext "* ) ;; - *) LIBOBJS="$LIBOBJS $ac_func.$ac_objext" - ;; -esac - +rm -f core conftest.err conftest.$ac_objext \ + conftest$ac_exeext conftest.$ac_ext +LIBS=$ac_check_lib_save_LIBS fi -done - - +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_lib_c_r_pthread_create" >&5 +$as_echo "$ac_cv_lib_c_r_pthread_create" >&6; } +if test "x$ac_cv_lib_c_r_pthread_create" = x""yes; then : + $as_echo "#define WITH_THREAD 1" >>confdefs.h -for ac_func in getpgrp -do -as_ac_var=`$as_echo "ac_cv_func_$ac_func" | $as_tr_sh` -{ $as_echo "$as_me:$LINENO: checking for $ac_func" >&5 -$as_echo_n "checking for $ac_func... " >&6; } -if { as_var=$as_ac_var; eval "test \"\${$as_var+set}\" = set"; }; then - $as_echo_n "(cached) " >&6 + posix_threads=yes + LIBS="$LIBS -lc_r" + THREADOBJ="Python/thread.o" else - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -/* Define $ac_func to an innocuous variant, in case declares $ac_func. - For example, HP-UX 11i declares gettimeofday. */ -#define $ac_func innocuous_$ac_func - -/* System header to define __stub macros and hopefully few prototypes, - which can conflict with char $ac_func (); below. - Prefer to if __STDC__ is defined, since - exists even on freestanding compilers. */ - -#ifdef __STDC__ -# include -#else -# include -#endif -#undef $ac_func + { $as_echo "$as_me:${as_lineno-$LINENO}: checking for __pthread_create_system in -lpthread" >&5 +$as_echo_n "checking for __pthread_create_system in -lpthread... " >&6; } +if test "${ac_cv_lib_pthread___pthread_create_system+set}" = set; then : + $as_echo_n "(cached) " >&6 +else + ac_check_lib_save_LIBS=$LIBS +LIBS="-lpthread $LIBS" +cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ /* Override any GCC internal prototype to avoid an error. Use char because int might match the return type of a GCC @@ -19165,147 +8311,117 @@ #ifdef __cplusplus extern "C" #endif -char $ac_func (); -/* The GNU C library defines this for functions which it implements - to always fail with ENOSYS. Some functions are actually named - something starting with __ and the normal name is an alias. */ -#if defined __stub_$ac_func || defined __stub___$ac_func -choke me -#endif - +char __pthread_create_system (); int main () { -return $ac_func (); +return __pthread_create_system (); ; return 0; } _ACEOF -rm -f conftest.$ac_objext conftest$ac_exeext -if { (ac_try="$ac_link" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" -$as_echo "$ac_try_echo") >&5 - (eval "$ac_link") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest$ac_exeext && { - test "$cross_compiling" = yes || - $as_test_x conftest$ac_exeext - }; then - eval "$as_ac_var=yes" +if ac_fn_c_try_link "$LINENO"; then : + ac_cv_lib_pthread___pthread_create_system=yes else - $as_echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - eval "$as_ac_var=no" + ac_cv_lib_pthread___pthread_create_system=no fi - -rm -rf conftest.dSYM -rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \ - conftest$ac_exeext conftest.$ac_ext +rm -f core conftest.err conftest.$ac_objext \ + conftest$ac_exeext conftest.$ac_ext +LIBS=$ac_check_lib_save_LIBS fi -ac_res=`eval 'as_val=${'$as_ac_var'} - $as_echo "$as_val"'` - { $as_echo "$as_me:$LINENO: result: $ac_res" >&5 -$as_echo "$ac_res" >&6; } -as_val=`eval 'as_val=${'$as_ac_var'} - $as_echo "$as_val"'` - if test "x$as_val" = x""yes; then - cat >>confdefs.h <<_ACEOF -#define `$as_echo "HAVE_$ac_func" | $as_tr_cpp` 1 -_ACEOF - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_lib_pthread___pthread_create_system" >&5 +$as_echo "$ac_cv_lib_pthread___pthread_create_system" >&6; } +if test "x$ac_cv_lib_pthread___pthread_create_system" = x""yes; then : + $as_echo "#define WITH_THREAD 1" >>confdefs.h + + posix_threads=yes + LIBS="$LIBS -lpthread" + THREADOBJ="Python/thread.o" +else + + { $as_echo "$as_me:${as_lineno-$LINENO}: checking for pthread_create in -lcma" >&5 +$as_echo_n "checking for pthread_create in -lcma... " >&6; } +if test "${ac_cv_lib_cma_pthread_create+set}" = set; then : + $as_echo_n "(cached) " >&6 +else + ac_check_lib_save_LIBS=$LIBS +LIBS="-lcma $LIBS" +cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ -#include + +/* Override any GCC internal prototype to avoid an error. + Use char because int might match the return type of a GCC + builtin and then its argument prototype would still apply. */ +#ifdef __cplusplus +extern "C" +#endif +char pthread_create (); int main () { -getpgrp(0); +return pthread_create (); ; return 0; } _ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" -$as_echo "$ac_try_echo") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then +if ac_fn_c_try_link "$LINENO"; then : + ac_cv_lib_cma_pthread_create=yes +else + ac_cv_lib_cma_pthread_create=no +fi +rm -f core conftest.err conftest.$ac_objext \ + conftest$ac_exeext conftest.$ac_ext +LIBS=$ac_check_lib_save_LIBS +fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_lib_cma_pthread_create" >&5 +$as_echo "$ac_cv_lib_cma_pthread_create" >&6; } +if test "x$ac_cv_lib_cma_pthread_create" = x""yes; then : + $as_echo "#define WITH_THREAD 1" >>confdefs.h -cat >>confdefs.h <<\_ACEOF -#define GETPGRP_HAVE_ARG 1 -_ACEOF + posix_threads=yes + LIBS="$LIBS -lcma" + THREADOBJ="Python/thread.o" +else + USE_THREAD_MODULE="#" +fi -else - $as_echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 +fi fi -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext +fi fi -done -for ac_func in setpgrp -do -as_ac_var=`$as_echo "ac_cv_func_$ac_func" | $as_tr_sh` -{ $as_echo "$as_me:$LINENO: checking for $ac_func" >&5 -$as_echo_n "checking for $ac_func... " >&6; } -if { as_var=$as_ac_var; eval "test \"\${$as_var+set}\" = set"; }; then - $as_echo_n "(cached) " >&6 -else - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -/* Define $ac_func to an innocuous variant, in case declares $ac_func. - For example, HP-UX 11i declares gettimeofday. */ -#define $ac_func innocuous_$ac_func +fi + + +fi + +fi +rm -f core conftest.err conftest.$ac_objext \ + conftest$ac_exeext conftest.$ac_ext +fi + +fi + + +fi -/* System header to define __stub macros and hopefully few prototypes, - which can conflict with char $ac_func (); below. - Prefer to if __STDC__ is defined, since - exists even on freestanding compilers. */ -#ifdef __STDC__ -# include -#else -# include -#endif -#undef $ac_func + { $as_echo "$as_me:${as_lineno-$LINENO}: checking for usconfig in -lmpc" >&5 +$as_echo_n "checking for usconfig in -lmpc... " >&6; } +if test "${ac_cv_lib_mpc_usconfig+set}" = set; then : + $as_echo_n "(cached) " >&6 +else + ac_check_lib_save_LIBS=$LIBS +LIBS="-lmpc $LIBS" +cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ /* Override any GCC internal prototype to avoid an error. Use char because int might match the return type of a GCC @@ -19313,649 +8429,630 @@ #ifdef __cplusplus extern "C" #endif -char $ac_func (); -/* The GNU C library defines this for functions which it implements - to always fail with ENOSYS. Some functions are actually named - something starting with __ and the normal name is an alias. */ -#if defined __stub_$ac_func || defined __stub___$ac_func -choke me -#endif - +char usconfig (); int main () { -return $ac_func (); +return usconfig (); ; return 0; } _ACEOF -rm -f conftest.$ac_objext conftest$ac_exeext -if { (ac_try="$ac_link" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" -$as_echo "$ac_try_echo") >&5 - (eval "$ac_link") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest$ac_exeext && { - test "$cross_compiling" = yes || - $as_test_x conftest$ac_exeext - }; then - eval "$as_ac_var=yes" +if ac_fn_c_try_link "$LINENO"; then : + ac_cv_lib_mpc_usconfig=yes else - $as_echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - eval "$as_ac_var=no" + ac_cv_lib_mpc_usconfig=no fi +rm -f core conftest.err conftest.$ac_objext \ + conftest$ac_exeext conftest.$ac_ext +LIBS=$ac_check_lib_save_LIBS +fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_lib_mpc_usconfig" >&5 +$as_echo "$ac_cv_lib_mpc_usconfig" >&6; } +if test "x$ac_cv_lib_mpc_usconfig" = x""yes; then : + $as_echo "#define WITH_THREAD 1" >>confdefs.h -rm -rf conftest.dSYM -rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \ - conftest$ac_exeext conftest.$ac_ext + LIBS="$LIBS -lmpc" + THREADOBJ="Python/thread.o" + USE_THREAD_MODULE="" fi -ac_res=`eval 'as_val=${'$as_ac_var'} - $as_echo "$as_val"'` - { $as_echo "$as_me:$LINENO: result: $ac_res" >&5 -$as_echo "$ac_res" >&6; } -as_val=`eval 'as_val=${'$as_ac_var'} - $as_echo "$as_val"'` - if test "x$as_val" = x""yes; then - cat >>confdefs.h <<_ACEOF -#define `$as_echo "HAVE_$ac_func" | $as_tr_cpp` 1 -_ACEOF - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF + + + if test "$posix_threads" != "yes"; then + { $as_echo "$as_me:${as_lineno-$LINENO}: checking for thr_create in -lthread" >&5 +$as_echo_n "checking for thr_create in -lthread... " >&6; } +if test "${ac_cv_lib_thread_thr_create+set}" = set; then : + $as_echo_n "(cached) " >&6 +else + ac_check_lib_save_LIBS=$LIBS +LIBS="-lthread $LIBS" +cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ -#include + +/* Override any GCC internal prototype to avoid an error. + Use char because int might match the return type of a GCC + builtin and then its argument prototype would still apply. */ +#ifdef __cplusplus +extern "C" +#endif +char thr_create (); int main () { -setpgrp(0,0); +return thr_create (); ; return 0; } _ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" -$as_echo "$ac_try_echo") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then +if ac_fn_c_try_link "$LINENO"; then : + ac_cv_lib_thread_thr_create=yes +else + ac_cv_lib_thread_thr_create=no +fi +rm -f core conftest.err conftest.$ac_objext \ + conftest$ac_exeext conftest.$ac_ext +LIBS=$ac_check_lib_save_LIBS +fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_lib_thread_thr_create" >&5 +$as_echo "$ac_cv_lib_thread_thr_create" >&6; } +if test "x$ac_cv_lib_thread_thr_create" = x""yes; then : + $as_echo "#define WITH_THREAD 1" >>confdefs.h -cat >>confdefs.h <<\_ACEOF -#define SETPGRP_HAVE_ARG 1 -_ACEOF + LIBS="$LIBS -lthread" + THREADOBJ="Python/thread.o" + USE_THREAD_MODULE="" +fi + + fi + + if test "$USE_THREAD_MODULE" != "#" + then + # If the above checks didn't disable threads, (at least) OSF1 + # needs this '-threads' argument during linking. + case $ac_sys_system in + OSF1) LDLAST=-threads;; + esac + fi +fi + +if test "$posix_threads" = "yes"; then + if test "$unistd_defines_pthreads" = "no"; then + +$as_echo "#define _POSIX_THREADS 1" >>confdefs.h + + fi + + # Bug 662787: Using semaphores causes unexplicable hangs on Solaris 8. + case $ac_sys_system/$ac_sys_release in + SunOS/5.6) +$as_echo "#define HAVE_PTHREAD_DESTRUCTOR 1" >>confdefs.h + + ;; + SunOS/5.8) +$as_echo "#define HAVE_BROKEN_POSIX_SEMAPHORES 1" >>confdefs.h + + ;; + AIX/5) +$as_echo "#define HAVE_BROKEN_POSIX_SEMAPHORES 1" >>confdefs.h + ;; + esac + { $as_echo "$as_me:${as_lineno-$LINENO}: checking if PTHREAD_SCOPE_SYSTEM is supported" >&5 +$as_echo_n "checking if PTHREAD_SCOPE_SYSTEM is supported... " >&6; } + if test "${ac_cv_pthread_system_supported+set}" = set; then : + $as_echo_n "(cached) " >&6 else - $as_echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 + if test "$cross_compiling" = yes; then : + ac_cv_pthread_system_supported=no +else + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ +#include + void *foo(void *parm) { + return NULL; + } + main() { + pthread_attr_t attr; + pthread_t id; + if (pthread_attr_init(&attr)) exit(-1); + if (pthread_attr_setscope(&attr, PTHREAD_SCOPE_SYSTEM)) exit(-1); + if (pthread_create(&id, &attr, foo, NULL)) exit(-1); + exit(0); + } +_ACEOF +if ac_fn_c_try_run "$LINENO"; then : + ac_cv_pthread_system_supported=yes +else + ac_cv_pthread_system_supported=no +fi +rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext \ + conftest.$ac_objext conftest.beam conftest.$ac_ext +fi + + +fi + + { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_pthread_system_supported" >&5 +$as_echo "$ac_cv_pthread_system_supported" >&6; } + if test "$ac_cv_pthread_system_supported" = "yes"; then + +$as_echo "#define PTHREAD_SYSTEM_SCHED_SUPPORTED 1" >>confdefs.h + + fi + for ac_func in pthread_sigmask +do : + ac_fn_c_check_func "$LINENO" "pthread_sigmask" "ac_cv_func_pthread_sigmask" +if test "x$ac_cv_func_pthread_sigmask" = x""yes; then : + cat >>confdefs.h <<_ACEOF +#define HAVE_PTHREAD_SIGMASK 1 +_ACEOF + case $ac_sys_system in + CYGWIN*) +$as_echo "#define HAVE_BROKEN_PTHREAD_SIGMASK 1" >>confdefs.h + ;; + esac fi - -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext +done fi -done -for ac_func in gettimeofday -do -as_ac_var=`$as_echo "ac_cv_func_$ac_func" | $as_tr_sh` -{ $as_echo "$as_me:$LINENO: checking for $ac_func" >&5 -$as_echo_n "checking for $ac_func... " >&6; } -if { as_var=$as_ac_var; eval "test \"\${$as_var+set}\" = set"; }; then - $as_echo_n "(cached) " >&6 +# Check for enable-ipv6 + +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking if --enable-ipv6 is specified" >&5 +$as_echo_n "checking if --enable-ipv6 is specified... " >&6; } +# Check whether --enable-ipv6 was given. +if test "${enable_ipv6+set}" = set; then : + enableval=$enable_ipv6; case "$enableval" in + no) + { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 +$as_echo "no" >&6; } + ipv6=no + ;; + *) { $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +$as_echo "yes" >&6; } + $as_echo "#define ENABLE_IPV6 1" >>confdefs.h + + ipv6=yes + ;; + esac else - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -/* Define $ac_func to an innocuous variant, in case declares $ac_func. - For example, HP-UX 11i declares gettimeofday. */ -#define $ac_func innocuous_$ac_func -/* System header to define __stub macros and hopefully few prototypes, - which can conflict with char $ac_func (); below. - Prefer to if __STDC__ is defined, since - exists even on freestanding compilers. */ + if test "$cross_compiling" = yes; then : + { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 +$as_echo "no" >&6; } + ipv6=no -#ifdef __STDC__ -# include -#else -# include -#endif +else + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + /* AF_INET6 available check */ +#include +#include +main() +{ + if (socket(AF_INET6, SOCK_STREAM, 0) < 0) + exit(1); + else + exit(0); +} -#undef $ac_func +_ACEOF +if ac_fn_c_try_run "$LINENO"; then : + { $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +$as_echo "yes" >&6; } + ipv6=yes +else + { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 +$as_echo "no" >&6; } + ipv6=no +fi +rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext \ + conftest.$ac_objext conftest.beam conftest.$ac_ext +fi -/* Override any GCC internal prototype to avoid an error. - Use char because int might match the return type of a GCC - builtin and then its argument prototype would still apply. */ -#ifdef __cplusplus -extern "C" -#endif -char $ac_func (); -/* The GNU C library defines this for functions which it implements - to always fail with ENOSYS. Some functions are actually named - something starting with __ and the normal name is an alias. */ -#if defined __stub_$ac_func || defined __stub___$ac_func -choke me -#endif +if test "$ipv6" = "yes"; then + { $as_echo "$as_me:${as_lineno-$LINENO}: checking if RFC2553 API is available" >&5 +$as_echo_n "checking if RFC2553 API is available... " >&6; } + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ +#include +#include int main () { -return $ac_func (); +struct sockaddr_in6 x; +x.sin6_scope_id; ; return 0; } _ACEOF -rm -f conftest.$ac_objext conftest$ac_exeext -if { (ac_try="$ac_link" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" -$as_echo "$ac_try_echo") >&5 - (eval "$ac_link") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest$ac_exeext && { - test "$cross_compiling" = yes || - $as_test_x conftest$ac_exeext - }; then - eval "$as_ac_var=yes" +if ac_fn_c_try_compile "$LINENO"; then : + { $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +$as_echo "yes" >&6; } + ipv6=yes else - $as_echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 + { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 +$as_echo "no" >&6; } + ipv6=no +fi +rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext +fi + +if test "$ipv6" = "yes"; then + $as_echo "#define ENABLE_IPV6 1" >>confdefs.h - eval "$as_ac_var=no" fi -rm -rf conftest.dSYM -rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \ - conftest$ac_exeext conftest.$ac_ext fi -ac_res=`eval 'as_val=${'$as_ac_var'} - $as_echo "$as_val"'` - { $as_echo "$as_me:$LINENO: result: $ac_res" >&5 -$as_echo "$ac_res" >&6; } -as_val=`eval 'as_val=${'$as_ac_var'} - $as_echo "$as_val"'` - if test "x$as_val" = x""yes; then - cat >>confdefs.h <<_ACEOF -#define `$as_echo "HAVE_$ac_func" | $as_tr_cpp` 1 -_ACEOF - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF + + +ipv6type=unknown +ipv6lib=none +ipv6trylibc=no + +if test "$ipv6" = "yes"; then + { $as_echo "$as_me:${as_lineno-$LINENO}: checking ipv6 stack type" >&5 +$as_echo_n "checking ipv6 stack type... " >&6; } + for i in inria kame linux-glibc linux-inet6 solaris toshiba v6d zeta; + do + case $i in + inria) + cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ -#include -int -main () -{ -gettimeofday((struct timeval*)0,(struct timezone*)0); - ; - return 0; -} + +#include +#ifdef IPV6_INRIA_VERSION +yes +#endif _ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" -$as_echo "$ac_try_echo") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - : -else - $as_echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 +if (eval "$ac_cpp conftest.$ac_ext") 2>&5 | + $EGREP "yes" >/dev/null 2>&1; then : + ipv6type=$i +fi +rm -f conftest* + ;; + kame) + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ -cat >>confdefs.h <<\_ACEOF -#define GETTIMEOFDAY_NO_TZ 1 +#include +#ifdef __KAME__ +yes +#endif _ACEOF +if (eval "$ac_cpp conftest.$ac_ext") 2>&5 | + $EGREP "yes" >/dev/null 2>&1; then : + ipv6type=$i; + ipv6lib=inet6 + ipv6libdir=/usr/local/v6/lib + ipv6trylibc=yes +fi +rm -f conftest* + ;; + linux-glibc) + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ +#include +#if defined(__GLIBC__) && ((__GLIBC__ == 2 && __GLIBC_MINOR__ >= 1) || (__GLIBC__ > 2)) +yes +#endif +_ACEOF +if (eval "$ac_cpp conftest.$ac_ext") 2>&5 | + $EGREP "yes" >/dev/null 2>&1; then : + ipv6type=$i; + ipv6trylibc=yes fi +rm -f conftest* -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext + ;; + linux-inet6) + if test -d /usr/inet6; then + ipv6type=$i + ipv6lib=inet6 + ipv6libdir=/usr/inet6/lib + BASECFLAGS="-I/usr/inet6/include $BASECFLAGS" + fi + ;; + solaris) + if test -f /etc/netconfig; then + if /usr/xpg4/bin/grep -q tcp6 /etc/netconfig; then + ipv6type=$i + ipv6trylibc=yes + fi + fi + ;; + toshiba) + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ +#include +#ifdef _TOSHIBA_INET6 +yes +#endif +_ACEOF +if (eval "$ac_cpp conftest.$ac_ext") 2>&5 | + $EGREP "yes" >/dev/null 2>&1; then : + ipv6type=$i; + ipv6lib=inet6; + ipv6libdir=/usr/local/v6/lib fi -done +rm -f conftest* + ;; + v6d) + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ -{ $as_echo "$as_me:$LINENO: checking for major" >&5 -$as_echo_n "checking for major... " >&6; } -cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ +#include +#ifdef __V6D__ +yes +#endif _ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF +if (eval "$ac_cpp conftest.$ac_ext") 2>&5 | + $EGREP "yes" >/dev/null 2>&1; then : + ipv6type=$i; + ipv6lib=v6; + ipv6libdir=/usr/local/v6/lib; + BASECFLAGS="-I/usr/local/v6/include $BASECFLAGS" +fi +rm -f conftest* + + ;; + zeta) + cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ -#if defined(MAJOR_IN_MKDEV) -#include -#elif defined(MAJOR_IN_SYSMACROS) -#include -#else -#include +#include +#ifdef _ZETA_MINAMI_INET6 +yes #endif +_ACEOF +if (eval "$ac_cpp conftest.$ac_ext") 2>&5 | + $EGREP "yes" >/dev/null 2>&1; then : + ipv6type=$i; + ipv6lib=inet6; + ipv6libdir=/usr/local/v6/lib +fi +rm -f conftest* + + ;; + esac + if test "$ipv6type" != "unknown"; then + break + fi + done + { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ipv6type" >&5 +$as_echo "$ipv6type" >&6; } +fi + +if test "$ipv6" = "yes" -a "$ipv6lib" != "none"; then + if test -d $ipv6libdir -a -f $ipv6libdir/lib$ipv6lib.a; then + LIBS="-L$ipv6libdir -l$ipv6lib $LIBS" + echo "using lib$ipv6lib" + else + if test $ipv6trylibc = "yes"; then + echo "using libc" + else + echo 'Fatal: no $ipv6lib library found. cannot continue.' + echo "You need to fetch lib$ipv6lib.a from appropriate" + echo 'ipv6 kit and compile beforehand.' + exit 1 + fi + fi +fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for OSX 10.5 SDK or later" >&5 +$as_echo_n "checking for OSX 10.5 SDK or later... " >&6; } +cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ +#include int main () { - - makedev(major(0),minor(0)); - +FSIORefNum fRef = 0 ; return 0; } _ACEOF -rm -f conftest.$ac_objext conftest$ac_exeext -if { (ac_try="$ac_link" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" -$as_echo "$ac_try_echo") >&5 - (eval "$ac_link") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest$ac_exeext && { - test "$cross_compiling" = yes || - $as_test_x conftest$ac_exeext - }; then - +if ac_fn_c_try_compile "$LINENO"; then : -cat >>confdefs.h <<\_ACEOF -#define HAVE_DEVICE_MACROS 1 -_ACEOF +$as_echo "#define HAVE_OSX105_SDK 1" >>confdefs.h - { $as_echo "$as_me:$LINENO: result: yes" >&5 + { $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5 $as_echo "yes" >&6; } - else - $as_echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 + { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 +$as_echo "no" >&6; } +fi +rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext - { $as_echo "$as_me:$LINENO: result: no" >&5 -$as_echo "no" >&6; } +# Check for --with-doc-strings +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for --with-doc-strings" >&5 +$as_echo_n "checking for --with-doc-strings... " >&6; } +# Check whether --with-doc-strings was given. +if test "${with_doc_strings+set}" = set; then : + withval=$with_doc_strings; fi -rm -rf conftest.dSYM -rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \ - conftest$ac_exeext conftest.$ac_ext -# On OSF/1 V5.1, getaddrinfo is available, but a define -# for [no]getaddrinfo in netdb.h. -{ $as_echo "$as_me:$LINENO: checking for getaddrinfo" >&5 -$as_echo_n "checking for getaddrinfo... " >&6; } -cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ +if test -z "$with_doc_strings" +then with_doc_strings="yes" +fi +if test "$with_doc_strings" != "no" +then -#include -#include -#include -#include +$as_echo "#define WITH_DOC_STRINGS 1" >>confdefs.h -int -main () -{ +fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $with_doc_strings" >&5 +$as_echo "$with_doc_strings" >&6; } -getaddrinfo(NULL, NULL, NULL, NULL); +# Check for Python-specific malloc support +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for --with-tsc" >&5 +$as_echo_n "checking for --with-tsc... " >&6; } - ; - return 0; -} -_ACEOF -rm -f conftest.$ac_objext conftest$ac_exeext -if { (ac_try="$ac_link" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" -$as_echo "$ac_try_echo") >&5 - (eval "$ac_link") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest$ac_exeext && { - test "$cross_compiling" = yes || - $as_test_x conftest$ac_exeext - }; then +# Check whether --with-tsc was given. +if test "${with_tsc+set}" = set; then : + withval=$with_tsc; +if test "$withval" != no +then -{ $as_echo "$as_me:$LINENO: result: yes" >&5 +$as_echo "#define WITH_TSC 1" >>confdefs.h + + { $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5 $as_echo "yes" >&6; } -{ $as_echo "$as_me:$LINENO: checking getaddrinfo bug" >&5 -$as_echo_n "checking getaddrinfo bug... " >&6; } -if test "$cross_compiling" = yes; then - { $as_echo "$as_me:$LINENO: result: buggy" >&5 -$as_echo "buggy" >&6; } -buggygetaddrinfo=yes +else { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 +$as_echo "no" >&6; } +fi else - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ - -#include -#include -#include -#include -#include + { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 +$as_echo "no" >&6; } +fi -main() -{ - int passive, gaierr, inet4 = 0, inet6 = 0; - struct addrinfo hints, *ai, *aitop; - char straddr[INET6_ADDRSTRLEN], strport[16]; - for (passive = 0; passive <= 1; passive++) { - memset(&hints, 0, sizeof(hints)); - hints.ai_family = AF_UNSPEC; - hints.ai_flags = passive ? AI_PASSIVE : 0; - hints.ai_socktype = SOCK_STREAM; - hints.ai_protocol = IPPROTO_TCP; - if ((gaierr = getaddrinfo(NULL, "54321", &hints, &aitop)) != 0) { - (void)gai_strerror(gaierr); - goto bad; - } - for (ai = aitop; ai; ai = ai->ai_next) { - if (ai->ai_addr == NULL || - ai->ai_addrlen == 0 || - getnameinfo(ai->ai_addr, ai->ai_addrlen, - straddr, sizeof(straddr), strport, sizeof(strport), - NI_NUMERICHOST|NI_NUMERICSERV) != 0) { - goto bad; - } - switch (ai->ai_family) { - case AF_INET: - if (strcmp(strport, "54321") != 0) { - goto bad; - } - if (passive) { - if (strcmp(straddr, "0.0.0.0") != 0) { - goto bad; - } - } else { - if (strcmp(straddr, "127.0.0.1") != 0) { - goto bad; - } - } - inet4++; - break; - case AF_INET6: - if (strcmp(strport, "54321") != 0) { - goto bad; - } - if (passive) { - if (strcmp(straddr, "::") != 0) { - goto bad; - } - } else { - if (strcmp(straddr, "::1") != 0) { - goto bad; - } - } - inet6++; - break; - case AF_UNSPEC: - goto bad; - break; - default: - /* another family support? */ - break; - } - } - } +# Check for Python-specific malloc support +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for --with-pymalloc" >&5 +$as_echo_n "checking for --with-pymalloc... " >&6; } - if (!(inet4 == 0 || inet4 == 2)) - goto bad; - if (!(inet6 == 0 || inet6 == 2)) - goto bad; +# Check whether --with-pymalloc was given. +if test "${with_pymalloc+set}" = set; then : + withval=$with_pymalloc; +fi - if (aitop) - freeaddrinfo(aitop); - exit(0); - bad: - if (aitop) - freeaddrinfo(aitop); - exit(1); -} +if test -z "$with_pymalloc" +then with_pymalloc="yes" +fi +if test "$with_pymalloc" != "no" +then -_ACEOF -rm -f conftest$ac_exeext -if { (ac_try="$ac_link" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" -$as_echo "$ac_try_echo") >&5 - (eval "$ac_link") 2>&5 - ac_status=$? - $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { ac_try='./conftest$ac_exeext' - { (case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" -$as_echo "$ac_try_echo") >&5 - (eval "$ac_try") 2>&5 - ac_status=$? - $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); }; }; then - { $as_echo "$as_me:$LINENO: result: good" >&5 -$as_echo "good" >&6; } -buggygetaddrinfo=no -else - $as_echo "$as_me: program exited with status $ac_status" >&5 -$as_echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 +$as_echo "#define WITH_PYMALLOC 1" >>confdefs.h -( exit $ac_status ) -{ $as_echo "$as_me:$LINENO: result: buggy" >&5 -$as_echo "buggy" >&6; } -buggygetaddrinfo=yes -fi -rm -rf conftest.dSYM -rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext conftest.$ac_objext conftest.$ac_ext fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $with_pymalloc" >&5 +$as_echo "$with_pymalloc" >&6; } +# Check for --with-wctype-functions +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for --with-wctype-functions" >&5 +$as_echo_n "checking for --with-wctype-functions... " >&6; } -else - $as_echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 +# Check whether --with-wctype-functions was given. +if test "${with_wctype_functions+set}" = set; then : + withval=$with_wctype_functions; +if test "$withval" != no +then +$as_echo "#define WANT_WCTYPE_FUNCTIONS 1" >>confdefs.h -{ $as_echo "$as_me:$LINENO: result: no" >&5 + { $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +$as_echo "yes" >&6; } +else { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 +$as_echo "no" >&6; } +fi +else + { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 $as_echo "no" >&6; } -buggygetaddrinfo=yes - fi -rm -rf conftest.dSYM -rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \ - conftest$ac_exeext conftest.$ac_ext -if test "$buggygetaddrinfo" = "yes"; then - if test "$ipv6" = "yes"; then - echo 'Fatal: You must get working getaddrinfo() function.' - echo ' or you can specify "--disable-ipv6"'. - exit 1 - fi -else +# -I${DLINCLDIR} is added to the compile rule for importdl.o -cat >>confdefs.h <<\_ACEOF -#define HAVE_GETADDRINFO 1 +DLINCLDIR=. + +# the dlopen() function means we might want to use dynload_shlib.o. some +# platforms, such as AIX, have dlopen(), but don't want to use it. +for ac_func in dlopen +do : + ac_fn_c_check_func "$LINENO" "dlopen" "ac_cv_func_dlopen" +if test "x$ac_cv_func_dlopen" = x""yes; then : + cat >>confdefs.h <<_ACEOF +#define HAVE_DLOPEN 1 _ACEOF fi +done -for ac_func in getnameinfo -do -as_ac_var=`$as_echo "ac_cv_func_$ac_func" | $as_tr_sh` -{ $as_echo "$as_me:$LINENO: checking for $ac_func" >&5 -$as_echo_n "checking for $ac_func... " >&6; } -if { as_var=$as_ac_var; eval "test \"\${$as_var+set}\" = set"; }; then - $as_echo_n "(cached) " >&6 -else - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -/* Define $ac_func to an innocuous variant, in case declares $ac_func. - For example, HP-UX 11i declares gettimeofday. */ -#define $ac_func innocuous_$ac_func -/* System header to define __stub macros and hopefully few prototypes, - which can conflict with char $ac_func (); below. - Prefer to if __STDC__ is defined, since - exists even on freestanding compilers. */ +# DYNLOADFILE specifies which dynload_*.o file we will use for dynamic +# loading of modules. + +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking DYNLOADFILE" >&5 +$as_echo_n "checking DYNLOADFILE... " >&6; } +if test -z "$DYNLOADFILE" +then + case $ac_sys_system/$ac_sys_release in + AIX*) # Use dynload_shlib.c and dlopen() if we have it; otherwise dynload_aix.c + if test "$ac_cv_func_dlopen" = yes + then DYNLOADFILE="dynload_shlib.o" + else DYNLOADFILE="dynload_aix.o" + fi + ;; + BeOS*) DYNLOADFILE="dynload_beos.o";; + hp*|HP*) DYNLOADFILE="dynload_hpux.o";; + # Use dynload_next.c only on 10.2 and below, which don't have native dlopen() + Darwin/[0156]\..*) DYNLOADFILE="dynload_next.o";; + atheos*) DYNLOADFILE="dynload_atheos.o";; + *) + # use dynload_shlib.c and dlopen() if we have it; otherwise stub + # out any dynamic loading + if test "$ac_cv_func_dlopen" = yes + then DYNLOADFILE="dynload_shlib.o" + else DYNLOADFILE="dynload_stub.o" + fi + ;; + esac +fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $DYNLOADFILE" >&5 +$as_echo "$DYNLOADFILE" >&6; } +if test "$DYNLOADFILE" != "dynload_stub.o" +then + +$as_echo "#define HAVE_DYNAMIC_LOADING 1" >>confdefs.h -#ifdef __STDC__ -# include -#else -# include -#endif +fi -#undef $ac_func +# MACHDEP_OBJS can be set to platform-specific object files needed by Python -/* Override any GCC internal prototype to avoid an error. - Use char because int might match the return type of a GCC - builtin and then its argument prototype would still apply. */ -#ifdef __cplusplus -extern "C" -#endif -char $ac_func (); -/* The GNU C library defines this for functions which it implements - to always fail with ENOSYS. Some functions are actually named - something starting with __ and the normal name is an alias. */ -#if defined __stub_$ac_func || defined __stub___$ac_func -choke me -#endif -int -main () -{ -return $ac_func (); - ; - return 0; -} -_ACEOF -rm -f conftest.$ac_objext conftest$ac_exeext -if { (ac_try="$ac_link" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" -$as_echo "$ac_try_echo") >&5 - (eval "$ac_link") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest$ac_exeext && { - test "$cross_compiling" = yes || - $as_test_x conftest$ac_exeext - }; then - eval "$as_ac_var=yes" +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking MACHDEP_OBJS" >&5 +$as_echo_n "checking MACHDEP_OBJS... " >&6; } +if test -z "$MACHDEP_OBJS" +then + MACHDEP_OBJS=$extra_machdep_objs else - $as_echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - eval "$as_ac_var=no" + MACHDEP_OBJS="$MACHDEP_OBJS $extra_machdep_objs" fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: MACHDEP_OBJS" >&5 +$as_echo "MACHDEP_OBJS" >&6; } -rm -rf conftest.dSYM -rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \ - conftest$ac_exeext conftest.$ac_ext -fi -ac_res=`eval 'as_val=${'$as_ac_var'} - $as_echo "$as_val"'` - { $as_echo "$as_me:$LINENO: result: $ac_res" >&5 -$as_echo "$ac_res" >&6; } -as_val=`eval 'as_val=${'$as_ac_var'} - $as_echo "$as_val"'` - if test "x$as_val" = x""yes; then +# checks for library functions +for ac_func in alarm setitimer getitimer bind_textdomain_codeset chown \ + clock confstr ctermid execv fchmod fchown fork fpathconf ftime ftruncate \ + gai_strerror getgroups getlogin getloadavg getpeername getpgid getpid \ + getpriority getpwent getspnam getspent getsid getwd \ + kill killpg lchmod lchown lstat mkfifo mknod mktime \ + mremap nice pathconf pause plock poll pthread_init \ + putenv readlink realpath \ + select setegid seteuid setgid \ + setlocale setregid setreuid 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 +do : + as_ac_var=`$as_echo "ac_cv_func_$ac_func" | $as_tr_sh` +ac_fn_c_check_func "$LINENO" "$ac_func" "$as_ac_var" +eval as_val=\$$as_ac_var + if test "x$as_val" = x""yes; then : cat >>confdefs.h <<_ACEOF #define `$as_echo "HAVE_$ac_func" | $as_tr_cpp` 1 _ACEOF @@ -19964,3502 +9061,2418 @@ done -# checks for structures -{ $as_echo "$as_me:$LINENO: checking whether time.h and sys/time.h may both be included" >&5 -$as_echo_n "checking whether time.h and sys/time.h may both be included... " >&6; } -if test "${ac_cv_header_time+set}" = set; then - $as_echo_n "(cached) " >&6 -else - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF +# For some functions, having a definition is not sufficient, since +# we want to take their address. +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for chroot" >&5 +$as_echo_n "checking for chroot... " >&6; } +cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ -#include -#include -#include - +#include int main () { -if ((struct tm *) 0) -return 0; +void *x=chroot ; return 0; } _ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" -$as_echo "$ac_try_echo") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - ac_cv_header_time=yes -else - $as_echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - ac_cv_header_time=no -fi +if ac_fn_c_try_compile "$LINENO"; then : -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext -fi -{ $as_echo "$as_me:$LINENO: result: $ac_cv_header_time" >&5 -$as_echo "$ac_cv_header_time" >&6; } -if test $ac_cv_header_time = yes; then +$as_echo "#define HAVE_CHROOT 1" >>confdefs.h -cat >>confdefs.h <<\_ACEOF -#define TIME_WITH_SYS_TIME 1 -_ACEOF + { $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +$as_echo "yes" >&6; } +else + { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 +$as_echo "no" >&6; } fi - -{ $as_echo "$as_me:$LINENO: checking whether struct tm is in sys/time.h or time.h" >&5 -$as_echo_n "checking whether struct tm is in sys/time.h or time.h... " >&6; } -if test "${ac_cv_struct_tm+set}" = set; then - $as_echo_n "(cached) " >&6 -else - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF +rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for link" >&5 +$as_echo_n "checking for link... " >&6; } +cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ -#include -#include - +#include int main () { -struct tm tm; - int *p = &tm.tm_sec; - return !p; +void *x=link ; return 0; } _ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" -$as_echo "$ac_try_echo") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - ac_cv_struct_tm=time.h -else - $as_echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - ac_cv_struct_tm=sys/time.h -fi +if ac_fn_c_try_compile "$LINENO"; then : -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext -fi -{ $as_echo "$as_me:$LINENO: result: $ac_cv_struct_tm" >&5 -$as_echo "$ac_cv_struct_tm" >&6; } -if test $ac_cv_struct_tm = sys/time.h; then +$as_echo "#define HAVE_LINK 1" >>confdefs.h -cat >>confdefs.h <<\_ACEOF -#define TM_IN_SYS_TIME 1 -_ACEOF + { $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +$as_echo "yes" >&6; } +else + { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 +$as_echo "no" >&6; } fi - -{ $as_echo "$as_me:$LINENO: checking for struct tm.tm_zone" >&5 -$as_echo_n "checking for struct tm.tm_zone... " >&6; } -if test "${ac_cv_member_struct_tm_tm_zone+set}" = set; then - $as_echo_n "(cached) " >&6 -else - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF +rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for symlink" >&5 +$as_echo_n "checking for symlink... " >&6; } +cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ -#include -#include <$ac_cv_struct_tm> - - +#include int main () { -static struct tm ac_aggr; -if (ac_aggr.tm_zone) -return 0; +void *x=symlink ; return 0; } _ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" -$as_echo "$ac_try_echo") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - ac_cv_member_struct_tm_tm_zone=yes -else - $as_echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 +if ac_fn_c_try_compile "$LINENO"; then : - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -#include -#include <$ac_cv_struct_tm> +$as_echo "#define HAVE_SYMLINK 1" >>confdefs.h + { $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +$as_echo "yes" >&6; } +else + { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 +$as_echo "no" >&6; } +fi +rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for fchdir" >&5 +$as_echo_n "checking for fchdir... " >&6; } +cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ +#include int main () { -static struct tm ac_aggr; -if (sizeof ac_aggr.tm_zone) -return 0; +void *x=fchdir ; return 0; } _ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" -$as_echo "$ac_try_echo") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - ac_cv_member_struct_tm_tm_zone=yes -else - $as_echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - ac_cv_member_struct_tm_tm_zone=no -fi - -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext -fi - -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext -fi -{ $as_echo "$as_me:$LINENO: result: $ac_cv_member_struct_tm_tm_zone" >&5 -$as_echo "$ac_cv_member_struct_tm_tm_zone" >&6; } -if test "x$ac_cv_member_struct_tm_tm_zone" = x""yes; then +if ac_fn_c_try_compile "$LINENO"; then : -cat >>confdefs.h <<_ACEOF -#define HAVE_STRUCT_TM_TM_ZONE 1 -_ACEOF +$as_echo "#define HAVE_FCHDIR 1" >>confdefs.h + { $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +$as_echo "yes" >&6; } +else + { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 +$as_echo "no" >&6; } fi - -if test "$ac_cv_member_struct_tm_tm_zone" = yes; then - -cat >>confdefs.h <<\_ACEOF -#define HAVE_TM_ZONE 1 -_ACEOF - -else - { $as_echo "$as_me:$LINENO: checking whether tzname is declared" >&5 -$as_echo_n "checking whether tzname is declared... " >&6; } -if test "${ac_cv_have_decl_tzname+set}" = set; then - $as_echo_n "(cached) " >&6 -else - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF +rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for fsync" >&5 +$as_echo_n "checking for fsync... " >&6; } +cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ -#include - +#include int main () { -#ifndef tzname - (void) tzname; -#endif - +void *x=fsync ; return 0; } _ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" -$as_echo "$ac_try_echo") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - ac_cv_have_decl_tzname=yes -else - $as_echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - ac_cv_have_decl_tzname=no -fi - -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext -fi -{ $as_echo "$as_me:$LINENO: result: $ac_cv_have_decl_tzname" >&5 -$as_echo "$ac_cv_have_decl_tzname" >&6; } -if test "x$ac_cv_have_decl_tzname" = x""yes; then - -cat >>confdefs.h <<_ACEOF -#define HAVE_DECL_TZNAME 1 -_ACEOF +if ac_fn_c_try_compile "$LINENO"; then : +$as_echo "#define HAVE_FSYNC 1" >>confdefs.h + { $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +$as_echo "yes" >&6; } else - cat >>confdefs.h <<_ACEOF -#define HAVE_DECL_TZNAME 0 -_ACEOF - + { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 +$as_echo "no" >&6; } fi - - - { $as_echo "$as_me:$LINENO: checking for tzname" >&5 -$as_echo_n "checking for tzname... " >&6; } -if test "${ac_cv_var_tzname+set}" = set; then - $as_echo_n "(cached) " >&6 -else - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF +rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for fdatasync" >&5 +$as_echo_n "checking for fdatasync... " >&6; } +cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ -#include -#if !HAVE_DECL_TZNAME -extern char *tzname[]; -#endif - +#include int main () { -return tzname[0][0]; +void *x=fdatasync ; return 0; } _ACEOF -rm -f conftest.$ac_objext conftest$ac_exeext -if { (ac_try="$ac_link" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" -$as_echo "$ac_try_echo") >&5 - (eval "$ac_link") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest$ac_exeext && { - test "$cross_compiling" = yes || - $as_test_x conftest$ac_exeext - }; then - ac_cv_var_tzname=yes -else - $as_echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 +if ac_fn_c_try_compile "$LINENO"; then : - ac_cv_var_tzname=no -fi - -rm -rf conftest.dSYM -rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \ - conftest$ac_exeext conftest.$ac_ext -fi -{ $as_echo "$as_me:$LINENO: result: $ac_cv_var_tzname" >&5 -$as_echo "$ac_cv_var_tzname" >&6; } - if test $ac_cv_var_tzname = yes; then +$as_echo "#define HAVE_FDATASYNC 1" >>confdefs.h -cat >>confdefs.h <<\_ACEOF -#define HAVE_TZNAME 1 -_ACEOF + { $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +$as_echo "yes" >&6; } +else + { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 +$as_echo "no" >&6; } - fi fi - -{ $as_echo "$as_me:$LINENO: checking for struct stat.st_rdev" >&5 -$as_echo_n "checking for struct stat.st_rdev... " >&6; } -if test "${ac_cv_member_struct_stat_st_rdev+set}" = set; then - $as_echo_n "(cached) " >&6 -else - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF +rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for epoll" >&5 +$as_echo_n "checking for epoll... " >&6; } +cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ -$ac_includes_default +#include int main () { -static struct stat ac_aggr; -if (ac_aggr.st_rdev) -return 0; +void *x=epoll_create ; return 0; } _ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" -$as_echo "$ac_try_echo") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - ac_cv_member_struct_stat_st_rdev=yes +if ac_fn_c_try_compile "$LINENO"; then : + +$as_echo "#define HAVE_EPOLL 1" >>confdefs.h + + { $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +$as_echo "yes" >&6; } else - $as_echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 + { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 +$as_echo "no" >&6; } - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF +fi +rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for kqueue" >&5 +$as_echo_n "checking for kqueue... " >&6; } +cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ -$ac_includes_default + +#include +#include + int main () { -static struct stat ac_aggr; -if (sizeof ac_aggr.st_rdev) -return 0; +int x=kqueue() ; return 0; } _ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" -$as_echo "$ac_try_echo") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - ac_cv_member_struct_stat_st_rdev=yes +if ac_fn_c_try_compile "$LINENO"; then : + +$as_echo "#define HAVE_KQUEUE 1" >>confdefs.h + + { $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +$as_echo "yes" >&6; } else - $as_echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 + { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 +$as_echo "no" >&6; } - ac_cv_member_struct_stat_st_rdev=no fi - rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext -fi +# On some systems (eg. FreeBSD 5), we would find a definition of the +# functions ctermid_r, setgroups in the library, but no prototype +# (e.g. because we use _XOPEN_SOURCE). See whether we can take their +# address to avoid compiler warnings and potential miscompilations +# because of the missing prototypes. -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext -fi -{ $as_echo "$as_me:$LINENO: result: $ac_cv_member_struct_stat_st_rdev" >&5 -$as_echo "$ac_cv_member_struct_stat_st_rdev" >&6; } -if test "x$ac_cv_member_struct_stat_st_rdev" = x""yes; then +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for ctermid_r" >&5 +$as_echo_n "checking for ctermid_r... " >&6; } +cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ -cat >>confdefs.h <<_ACEOF -#define HAVE_STRUCT_STAT_ST_RDEV 1 +#include "confdefs.h" +#include + +int +main () +{ +void* p = ctermid_r + ; + return 0; +} _ACEOF +if ac_fn_c_try_compile "$LINENO"; then : +$as_echo "#define HAVE_CTERMID_R 1" >>confdefs.h + + { $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +$as_echo "yes" >&6; } +else + { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 +$as_echo "no" >&6; } fi +rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext -{ $as_echo "$as_me:$LINENO: checking for struct stat.st_blksize" >&5 -$as_echo_n "checking for struct stat.st_blksize... " >&6; } -if test "${ac_cv_member_struct_stat_st_blksize+set}" = set; then - $as_echo_n "(cached) " >&6 -else - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for flock" >&5 +$as_echo_n "checking for flock... " >&6; } +cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ -$ac_includes_default + +#include "confdefs.h" +#include + int main () { -static struct stat ac_aggr; -if (ac_aggr.st_blksize) -return 0; +void* p = flock ; return 0; } _ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" -$as_echo "$ac_try_echo") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - ac_cv_member_struct_stat_st_blksize=yes +if ac_fn_c_try_compile "$LINENO"; then : + +$as_echo "#define HAVE_FLOCK 1" >>confdefs.h + + { $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +$as_echo "yes" >&6; } else - $as_echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 + { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 +$as_echo "no" >&6; } - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF +fi +rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext + +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for getpagesize" >&5 +$as_echo_n "checking for getpagesize... " >&6; } +cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ -$ac_includes_default + +#include "confdefs.h" +#include + int main () { -static struct stat ac_aggr; -if (sizeof ac_aggr.st_blksize) -return 0; +void* p = getpagesize ; return 0; } _ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" -$as_echo "$ac_try_echo") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - ac_cv_member_struct_stat_st_blksize=yes +if ac_fn_c_try_compile "$LINENO"; then : + +$as_echo "#define HAVE_GETPAGESIZE 1" >>confdefs.h + + { $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +$as_echo "yes" >&6; } else - $as_echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 + { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 +$as_echo "no" >&6; } - ac_cv_member_struct_stat_st_blksize=no fi - rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext -fi -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext +for ac_prog in true +do + # Extract the first word of "$ac_prog", so it can be a program name with args. +set dummy $ac_prog; ac_word=$2 +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 +$as_echo_n "checking for $ac_word... " >&6; } +if test "${ac_cv_prog_TRUE+set}" = set; then : + $as_echo_n "(cached) " >&6 +else + if test -n "$TRUE"; then + ac_cv_prog_TRUE="$TRUE" # Let the user override the test. +else +as_save_IFS=$IFS; IFS=$PATH_SEPARATOR +for as_dir in $PATH +do + IFS=$as_save_IFS + test -z "$as_dir" && as_dir=. + for ac_exec_ext in '' $ac_executable_extensions; do + if { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_test_x "$as_dir/$ac_word$ac_exec_ext"; }; then + ac_cv_prog_TRUE="$ac_prog" + $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 + break 2 + fi +done + done +IFS=$as_save_IFS + +fi +fi +TRUE=$ac_cv_prog_TRUE +if test -n "$TRUE"; then + { $as_echo "$as_me:${as_lineno-$LINENO}: result: $TRUE" >&5 +$as_echo "$TRUE" >&6; } +else + { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 +$as_echo "no" >&6; } fi -{ $as_echo "$as_me:$LINENO: result: $ac_cv_member_struct_stat_st_blksize" >&5 -$as_echo "$ac_cv_member_struct_stat_st_blksize" >&6; } -if test "x$ac_cv_member_struct_stat_st_blksize" = x""yes; then -cat >>confdefs.h <<_ACEOF -#define HAVE_STRUCT_STAT_ST_BLKSIZE 1 -_ACEOF + test -n "$TRUE" && break +done +test -n "$TRUE" || TRUE="/bin/true" -fi -{ $as_echo "$as_me:$LINENO: checking for struct stat.st_flags" >&5 -$as_echo_n "checking for struct stat.st_flags... " >&6; } -if test "${ac_cv_member_struct_stat_st_flags+set}" = set; then +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for inet_aton in -lc" >&5 +$as_echo_n "checking for inet_aton in -lc... " >&6; } +if test "${ac_cv_lib_c_inet_aton+set}" = set; then : $as_echo_n "(cached) " >&6 else - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF + ac_check_lib_save_LIBS=$LIBS +LIBS="-lc $LIBS" +cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ -$ac_includes_default + +/* Override any GCC internal prototype to avoid an error. + Use char because int might match the return type of a GCC + builtin and then its argument prototype would still apply. */ +#ifdef __cplusplus +extern "C" +#endif +char inet_aton (); int main () { -static struct stat ac_aggr; -if (ac_aggr.st_flags) -return 0; +return inet_aton (); ; return 0; } _ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" -$as_echo "$ac_try_echo") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - ac_cv_member_struct_stat_st_flags=yes +if ac_fn_c_try_link "$LINENO"; then : + ac_cv_lib_c_inet_aton=yes else - $as_echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF + ac_cv_lib_c_inet_aton=no +fi +rm -f core conftest.err conftest.$ac_objext \ + conftest$ac_exeext conftest.$ac_ext +LIBS=$ac_check_lib_save_LIBS +fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_lib_c_inet_aton" >&5 +$as_echo "$ac_cv_lib_c_inet_aton" >&6; } +if test "x$ac_cv_lib_c_inet_aton" = x""yes; then : + $ac_cv_prog_TRUE +else + { $as_echo "$as_me:${as_lineno-$LINENO}: checking for inet_aton in -lresolv" >&5 +$as_echo_n "checking for inet_aton in -lresolv... " >&6; } +if test "${ac_cv_lib_resolv_inet_aton+set}" = set; then : + $as_echo_n "(cached) " >&6 +else + ac_check_lib_save_LIBS=$LIBS +LIBS="-lresolv $LIBS" +cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ -$ac_includes_default + +/* Override any GCC internal prototype to avoid an error. + Use char because int might match the return type of a GCC + builtin and then its argument prototype would still apply. */ +#ifdef __cplusplus +extern "C" +#endif +char inet_aton (); int main () { -static struct stat ac_aggr; -if (sizeof ac_aggr.st_flags) -return 0; +return inet_aton (); ; return 0; } _ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" -$as_echo "$ac_try_echo") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - ac_cv_member_struct_stat_st_flags=yes +if ac_fn_c_try_link "$LINENO"; then : + ac_cv_lib_resolv_inet_aton=yes else - $as_echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - ac_cv_member_struct_stat_st_flags=no + ac_cv_lib_resolv_inet_aton=no +fi +rm -f core conftest.err conftest.$ac_objext \ + conftest$ac_exeext conftest.$ac_ext +LIBS=$ac_check_lib_save_LIBS fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_lib_resolv_inet_aton" >&5 +$as_echo "$ac_cv_lib_resolv_inet_aton" >&6; } +if test "x$ac_cv_lib_resolv_inet_aton" = x""yes; then : + cat >>confdefs.h <<_ACEOF +#define HAVE_LIBRESOLV 1 +_ACEOF -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext -fi + LIBS="-lresolv $LIBS" -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext fi -{ $as_echo "$as_me:$LINENO: result: $ac_cv_member_struct_stat_st_flags" >&5 -$as_echo "$ac_cv_member_struct_stat_st_flags" >&6; } -if test "x$ac_cv_member_struct_stat_st_flags" = x""yes; then - -cat >>confdefs.h <<_ACEOF -#define HAVE_STRUCT_STAT_ST_FLAGS 1 -_ACEOF fi -{ $as_echo "$as_me:$LINENO: checking for struct stat.st_gen" >&5 -$as_echo_n "checking for struct stat.st_gen... " >&6; } -if test "${ac_cv_member_struct_stat_st_gen+set}" = set; then + +# On Tru64, chflags seems to be present, but calling it will +# exit Python +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for chflags" >&5 +$as_echo_n "checking for chflags... " >&6; } +if test "${ac_cv_have_chflags+set}" = set; then : $as_echo_n "(cached) " >&6 else - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -$ac_includes_default -int -main () -{ -static struct stat ac_aggr; -if (ac_aggr.st_gen) -return 0; - ; - return 0; -} -_ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" -$as_echo "$ac_try_echo") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - ac_cv_member_struct_stat_st_gen=yes + if test "$cross_compiling" = yes; then : + ac_cv_have_chflags=cross else - $as_echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF + cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ -$ac_includes_default -int -main () +[ +#include +#include +int main(int argc, char*argv[]) { -static struct stat ac_aggr; -if (sizeof ac_aggr.st_gen) -return 0; - ; + if(chflags(argv[0], 0) != 0) + return 1; return 0; } +] _ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" -$as_echo "$ac_try_echo") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - ac_cv_member_struct_stat_st_gen=yes +if ac_fn_c_try_run "$LINENO"; then : + ac_cv_have_chflags=yes else - $as_echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - ac_cv_member_struct_stat_st_gen=no + ac_cv_have_chflags=no fi - -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext +rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext \ + conftest.$ac_objext conftest.beam conftest.$ac_ext fi -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext + +fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_have_chflags" >&5 +$as_echo "$ac_cv_have_chflags" >&6; } +if test "$ac_cv_have_chflags" = cross ; then + ac_fn_c_check_func "$LINENO" "chflags" "ac_cv_func_chflags" +if test "x$ac_cv_func_chflags" = x""yes; then : + ac_cv_have_chflags="yes" +else + ac_cv_have_chflags="no" fi -{ $as_echo "$as_me:$LINENO: result: $ac_cv_member_struct_stat_st_gen" >&5 -$as_echo "$ac_cv_member_struct_stat_st_gen" >&6; } -if test "x$ac_cv_member_struct_stat_st_gen" = x""yes; then -cat >>confdefs.h <<_ACEOF -#define HAVE_STRUCT_STAT_ST_GEN 1 -_ACEOF +fi +if test "$ac_cv_have_chflags" = yes ; then +$as_echo "#define HAVE_CHFLAGS 1" >>confdefs.h fi -{ $as_echo "$as_me:$LINENO: checking for struct stat.st_birthtime" >&5 -$as_echo_n "checking for struct stat.st_birthtime... " >&6; } -if test "${ac_cv_member_struct_stat_st_birthtime+set}" = set; then +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for lchflags" >&5 +$as_echo_n "checking for lchflags... " >&6; } +if test "${ac_cv_have_lchflags+set}" = set; then : $as_echo_n "(cached) " >&6 else - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -$ac_includes_default -int -main () -{ -static struct stat ac_aggr; -if (ac_aggr.st_birthtime) -return 0; - ; - return 0; -} -_ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" -$as_echo "$ac_try_echo") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - ac_cv_member_struct_stat_st_birthtime=yes + if test "$cross_compiling" = yes; then : + ac_cv_have_lchflags=cross else - $as_echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF + cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ -$ac_includes_default -int -main () +[ +#include +#include +int main(int argc, char*argv[]) { -static struct stat ac_aggr; -if (sizeof ac_aggr.st_birthtime) -return 0; - ; + if(lchflags(argv[0], 0) != 0) + return 1; return 0; } +] _ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" -$as_echo "$ac_try_echo") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - ac_cv_member_struct_stat_st_birthtime=yes +if ac_fn_c_try_run "$LINENO"; then : + ac_cv_have_lchflags=yes else - $as_echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - ac_cv_member_struct_stat_st_birthtime=no + ac_cv_have_lchflags=no fi - -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext +rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext \ + conftest.$ac_objext conftest.beam conftest.$ac_ext fi -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext + +fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_have_lchflags" >&5 +$as_echo "$ac_cv_have_lchflags" >&6; } +if test "$ac_cv_have_lchflags" = cross ; then + ac_fn_c_check_func "$LINENO" "lchflags" "ac_cv_func_lchflags" +if test "x$ac_cv_func_lchflags" = x""yes; then : + ac_cv_have_lchflags="yes" +else + ac_cv_have_lchflags="no" fi -{ $as_echo "$as_me:$LINENO: result: $ac_cv_member_struct_stat_st_birthtime" >&5 -$as_echo "$ac_cv_member_struct_stat_st_birthtime" >&6; } -if test "x$ac_cv_member_struct_stat_st_birthtime" = x""yes; then -cat >>confdefs.h <<_ACEOF -#define HAVE_STRUCT_STAT_ST_BIRTHTIME 1 -_ACEOF +fi +if test "$ac_cv_have_lchflags" = yes ; then +$as_echo "#define HAVE_LCHFLAGS 1" >>confdefs.h fi -{ $as_echo "$as_me:$LINENO: checking for struct stat.st_blocks" >&5 -$as_echo_n "checking for struct stat.st_blocks... " >&6; } -if test "${ac_cv_member_struct_stat_st_blocks+set}" = set; then +case $ac_sys_system/$ac_sys_release in +Darwin/*) + _CUR_CFLAGS="${CFLAGS}" + _CUR_LDFLAGS="${LDFLAGS}" + CFLAGS="${CFLAGS} -Wl,-search_paths_first" + LDFLAGS="${LDFLAGS} -Wl,-search_paths_first -L/usr/local/lib" + ;; +esac + +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for inflateCopy in -lz" >&5 +$as_echo_n "checking for inflateCopy in -lz... " >&6; } +if test "${ac_cv_lib_z_inflateCopy+set}" = set; then : $as_echo_n "(cached) " >&6 else - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF + ac_check_lib_save_LIBS=$LIBS +LIBS="-lz $LIBS" +cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ -$ac_includes_default + +/* Override any GCC internal prototype to avoid an error. + Use char because int might match the return type of a GCC + builtin and then its argument prototype would still apply. */ +#ifdef __cplusplus +extern "C" +#endif +char inflateCopy (); int main () { -static struct stat ac_aggr; -if (ac_aggr.st_blocks) -return 0; +return inflateCopy (); ; return 0; } _ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" -$as_echo "$ac_try_echo") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - ac_cv_member_struct_stat_st_blocks=yes +if ac_fn_c_try_link "$LINENO"; then : + ac_cv_lib_z_inflateCopy=yes else - $as_echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 + ac_cv_lib_z_inflateCopy=no +fi +rm -f core conftest.err conftest.$ac_objext \ + conftest$ac_exeext conftest.$ac_ext +LIBS=$ac_check_lib_save_LIBS +fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_lib_z_inflateCopy" >&5 +$as_echo "$ac_cv_lib_z_inflateCopy" >&6; } +if test "x$ac_cv_lib_z_inflateCopy" = x""yes; then : - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF +$as_echo "#define HAVE_ZLIB_COPY 1" >>confdefs.h + +fi + + +case $ac_sys_system/$ac_sys_release in +Darwin/*) + CFLAGS="${_CUR_CFLAGS}" + LDFLAGS="${_CUR_LDFLAGS}" + ;; +esac + +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for hstrerror" >&5 +$as_echo_n "checking for hstrerror... " >&6; } +cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ -$ac_includes_default + +#include "confdefs.h" +#include + int main () { -static struct stat ac_aggr; -if (sizeof ac_aggr.st_blocks) -return 0; +void* p = hstrerror; hstrerror(0) ; return 0; } _ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" -$as_echo "$ac_try_echo") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - ac_cv_member_struct_stat_st_blocks=yes -else - $as_echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - ac_cv_member_struct_stat_st_blocks=no -fi - -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext -fi - -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext -fi -{ $as_echo "$as_me:$LINENO: result: $ac_cv_member_struct_stat_st_blocks" >&5 -$as_echo "$ac_cv_member_struct_stat_st_blocks" >&6; } -if test "x$ac_cv_member_struct_stat_st_blocks" = x""yes; then - -cat >>confdefs.h <<_ACEOF -#define HAVE_STRUCT_STAT_ST_BLOCKS 1 -_ACEOF +if ac_fn_c_try_link "$LINENO"; then : +$as_echo "#define HAVE_HSTRERROR 1" >>confdefs.h -cat >>confdefs.h <<\_ACEOF -#define HAVE_ST_BLOCKS 1 -_ACEOF - + { $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +$as_echo "yes" >&6; } else - case " $LIBOBJS " in - *" fileblocks.$ac_objext "* ) ;; - *) LIBOBJS="$LIBOBJS fileblocks.$ac_objext" - ;; -esac + { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 +$as_echo "no" >&6; } fi +rm -f core conftest.err conftest.$ac_objext \ + conftest$ac_exeext conftest.$ac_ext +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for inet_aton" >&5 +$as_echo_n "checking for inet_aton... " >&6; } +cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ +#include "confdefs.h" +#include +#include +#include +#include -{ $as_echo "$as_me:$LINENO: checking for time.h that defines altzone" >&5 -$as_echo_n "checking for time.h that defines altzone... " >&6; } -if test "${ac_cv_header_time_altzone+set}" = set; then - $as_echo_n "(cached) " >&6 -else - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -#include int main () { -return altzone; +void* p = inet_aton;inet_aton(0,0) ; return 0; } _ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" -$as_echo "$ac_try_echo") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - ac_cv_header_time_altzone=yes -else - $as_echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - ac_cv_header_time_altzone=no -fi - -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext -fi +if ac_fn_c_try_link "$LINENO"; then : -{ $as_echo "$as_me:$LINENO: result: $ac_cv_header_time_altzone" >&5 -$as_echo "$ac_cv_header_time_altzone" >&6; } -if test $ac_cv_header_time_altzone = yes; then +$as_echo "#define HAVE_INET_ATON 1" >>confdefs.h -cat >>confdefs.h <<\_ACEOF -#define HAVE_ALTZONE 1 -_ACEOF + { $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +$as_echo "yes" >&6; } +else + { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 +$as_echo "no" >&6; } fi +rm -f core conftest.err conftest.$ac_objext \ + conftest$ac_exeext conftest.$ac_ext -was_it_defined=no -{ $as_echo "$as_me:$LINENO: checking whether sys/select.h and sys/time.h may both be included" >&5 -$as_echo_n "checking whether sys/select.h and sys/time.h may both be included... " >&6; } -cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for inet_pton" >&5 +$as_echo_n "checking for inet_pton... " >&6; } +cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ +#include "confdefs.h" #include -#include -#include +#include +#include +#include int main () { -; +void* p = inet_pton ; return 0; } _ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" -$as_echo "$ac_try_echo") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - - -cat >>confdefs.h <<\_ACEOF -#define SYS_SELECT_WITH_SYS_TIME 1 -_ACEOF +if ac_fn_c_try_compile "$LINENO"; then : - was_it_defined=yes +$as_echo "#define HAVE_INET_PTON 1" >>confdefs.h + { $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +$as_echo "yes" >&6; } else - $as_echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - + { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 +$as_echo "no" >&6; } fi - rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext -{ $as_echo "$as_me:$LINENO: result: $was_it_defined" >&5 -$as_echo "$was_it_defined" >&6; } -{ $as_echo "$as_me:$LINENO: checking for addrinfo" >&5 -$as_echo_n "checking for addrinfo... " >&6; } -if test "${ac_cv_struct_addrinfo+set}" = set; then - $as_echo_n "(cached) " >&6 -else - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF +# On some systems, setgroups is in unistd.h, on others, in grp.h +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for setgroups" >&5 +$as_echo_n "checking for setgroups... " >&6; } +cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ -# include +#include "confdefs.h" +#include +#ifdef HAVE_GRP_H +#include +#endif + int main () { -struct addrinfo a +void* p = setgroups ; return 0; } _ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" -$as_echo "$ac_try_echo") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - ac_cv_struct_addrinfo=yes +if ac_fn_c_try_compile "$LINENO"; then : + +$as_echo "#define HAVE_SETGROUPS 1" >>confdefs.h + + { $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +$as_echo "yes" >&6; } else - $as_echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 + { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 +$as_echo "no" >&6; } - ac_cv_struct_addrinfo=no fi - rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext -fi -{ $as_echo "$as_me:$LINENO: result: $ac_cv_struct_addrinfo" >&5 -$as_echo "$ac_cv_struct_addrinfo" >&6; } -if test $ac_cv_struct_addrinfo = yes; then +# check for openpty and forkpty -cat >>confdefs.h <<\_ACEOF -#define HAVE_ADDRINFO 1 +for ac_func in openpty +do : + ac_fn_c_check_func "$LINENO" "openpty" "ac_cv_func_openpty" +if test "x$ac_cv_func_openpty" = x""yes; then : + cat >>confdefs.h <<_ACEOF +#define HAVE_OPENPTY 1 _ACEOF -fi - -{ $as_echo "$as_me:$LINENO: checking for sockaddr_storage" >&5 -$as_echo_n "checking for sockaddr_storage... " >&6; } -if test "${ac_cv_struct_sockaddr_storage+set}" = set; then +else + { $as_echo "$as_me:${as_lineno-$LINENO}: checking for openpty in -lutil" >&5 +$as_echo_n "checking for openpty in -lutil... " >&6; } +if test "${ac_cv_lib_util_openpty+set}" = set; then : $as_echo_n "(cached) " >&6 else - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF + ac_check_lib_save_LIBS=$LIBS +LIBS="-lutil $LIBS" +cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ -# include -# include +/* Override any GCC internal prototype to avoid an error. + Use char because int might match the return type of a GCC + builtin and then its argument prototype would still apply. */ +#ifdef __cplusplus +extern "C" +#endif +char openpty (); int main () { -struct sockaddr_storage s +return openpty (); ; return 0; } _ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" -$as_echo "$ac_try_echo") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - ac_cv_struct_sockaddr_storage=yes +if ac_fn_c_try_link "$LINENO"; then : + ac_cv_lib_util_openpty=yes else - $as_echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - ac_cv_struct_sockaddr_storage=no + ac_cv_lib_util_openpty=no fi - -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext -fi - -{ $as_echo "$as_me:$LINENO: result: $ac_cv_struct_sockaddr_storage" >&5 -$as_echo "$ac_cv_struct_sockaddr_storage" >&6; } -if test $ac_cv_struct_sockaddr_storage = yes; then - -cat >>confdefs.h <<\_ACEOF -#define HAVE_SOCKADDR_STORAGE 1 -_ACEOF - +rm -f core conftest.err conftest.$ac_objext \ + conftest$ac_exeext conftest.$ac_ext +LIBS=$ac_check_lib_save_LIBS fi - -# checks for compiler characteristics - - -{ $as_echo "$as_me:$LINENO: checking whether char is unsigned" >&5 -$as_echo_n "checking whether char is unsigned... " >&6; } -if test "${ac_cv_c_char_unsigned+set}" = set; then +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_lib_util_openpty" >&5 +$as_echo "$ac_cv_lib_util_openpty" >&6; } +if test "x$ac_cv_lib_util_openpty" = x""yes; then : + $as_echo "#define HAVE_OPENPTY 1" >>confdefs.h + LIBS="$LIBS -lutil" +else + { $as_echo "$as_me:${as_lineno-$LINENO}: checking for openpty in -lbsd" >&5 +$as_echo_n "checking for openpty in -lbsd... " >&6; } +if test "${ac_cv_lib_bsd_openpty+set}" = set; then : $as_echo_n "(cached) " >&6 else - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF + ac_check_lib_save_LIBS=$LIBS +LIBS="-lbsd $LIBS" +cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ -$ac_includes_default + +/* Override any GCC internal prototype to avoid an error. + Use char because int might match the return type of a GCC + builtin and then its argument prototype would still apply. */ +#ifdef __cplusplus +extern "C" +#endif +char openpty (); int main () { -static int test_array [1 - 2 * !(((char) -1) < 0)]; -test_array [0] = 0 - +return openpty (); ; return 0; } _ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" -$as_echo "$ac_try_echo") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - ac_cv_c_char_unsigned=no +if ac_fn_c_try_link "$LINENO"; then : + ac_cv_lib_bsd_openpty=yes else - $as_echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - ac_cv_c_char_unsigned=yes + ac_cv_lib_bsd_openpty=no +fi +rm -f core conftest.err conftest.$ac_objext \ + conftest$ac_exeext conftest.$ac_ext +LIBS=$ac_check_lib_save_LIBS +fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_lib_bsd_openpty" >&5 +$as_echo "$ac_cv_lib_bsd_openpty" >&6; } +if test "x$ac_cv_lib_bsd_openpty" = x""yes; then : + $as_echo "#define HAVE_OPENPTY 1" >>confdefs.h + LIBS="$LIBS -lbsd" fi -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext + fi -{ $as_echo "$as_me:$LINENO: result: $ac_cv_c_char_unsigned" >&5 -$as_echo "$ac_cv_c_char_unsigned" >&6; } -if test $ac_cv_c_char_unsigned = yes && test "$GCC" != yes; then - cat >>confdefs.h <<\_ACEOF -#define __CHAR_UNSIGNED__ 1 -_ACEOF + fi +done -{ $as_echo "$as_me:$LINENO: checking for an ANSI C-conforming const" >&5 -$as_echo_n "checking for an ANSI C-conforming const... " >&6; } -if test "${ac_cv_c_const+set}" = set; then +for ac_func in forkpty +do : + ac_fn_c_check_func "$LINENO" "forkpty" "ac_cv_func_forkpty" +if test "x$ac_cv_func_forkpty" = x""yes; then : + cat >>confdefs.h <<_ACEOF +#define HAVE_FORKPTY 1 +_ACEOF + +else + { $as_echo "$as_me:${as_lineno-$LINENO}: checking for forkpty in -lutil" >&5 +$as_echo_n "checking for forkpty in -lutil... " >&6; } +if test "${ac_cv_lib_util_forkpty+set}" = set; then : $as_echo_n "(cached) " >&6 else - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF + ac_check_lib_save_LIBS=$LIBS +LIBS="-lutil $LIBS" +cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ +/* Override any GCC internal prototype to avoid an error. + Use char because int might match the return type of a GCC + builtin and then its argument prototype would still apply. */ +#ifdef __cplusplus +extern "C" +#endif +char forkpty (); int main () { -/* FIXME: Include the comments suggested by Paul. */ -#ifndef __cplusplus - /* Ultrix mips cc rejects this. */ - typedef int charset[2]; - const charset cs; - /* SunOS 4.1.1 cc rejects this. */ - char const *const *pcpcc; - char **ppc; - /* NEC SVR4.0.2 mips cc rejects this. */ - struct point {int x, y;}; - static struct point const zero = {0,0}; - /* AIX XL C 1.02.0.0 rejects this. - It does not let you subtract one const X* pointer from another in - an arm of an if-expression whose if-part is not a constant - expression */ - const char *g = "string"; - pcpcc = &g + (g ? g-g : 0); - /* HPUX 7.0 cc rejects these. */ - ++pcpcc; - ppc = (char**) pcpcc; - pcpcc = (char const *const *) ppc; - { /* SCO 3.2v4 cc rejects this. */ - char *t; - char const *s = 0 ? (char *) 0 : (char const *) 0; +return forkpty (); + ; + return 0; +} +_ACEOF +if ac_fn_c_try_link "$LINENO"; then : + ac_cv_lib_util_forkpty=yes +else + ac_cv_lib_util_forkpty=no +fi +rm -f core conftest.err conftest.$ac_objext \ + conftest$ac_exeext conftest.$ac_ext +LIBS=$ac_check_lib_save_LIBS +fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_lib_util_forkpty" >&5 +$as_echo "$ac_cv_lib_util_forkpty" >&6; } +if test "x$ac_cv_lib_util_forkpty" = x""yes; then : + $as_echo "#define HAVE_FORKPTY 1" >>confdefs.h + LIBS="$LIBS -lutil" +else + { $as_echo "$as_me:${as_lineno-$LINENO}: checking for forkpty in -lbsd" >&5 +$as_echo_n "checking for forkpty in -lbsd... " >&6; } +if test "${ac_cv_lib_bsd_forkpty+set}" = set; then : + $as_echo_n "(cached) " >&6 +else + ac_check_lib_save_LIBS=$LIBS +LIBS="-lbsd $LIBS" +cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ - *t++ = 0; - if (s) return 0; - } - { /* Someone thinks the Sun supposedly-ANSI compiler will reject this. */ - int x[] = {25, 17}; - const int *foo = &x[0]; - ++foo; - } - { /* Sun SC1.0 ANSI compiler rejects this -- but not the above. */ - typedef const int *iptr; - iptr p = 0; - ++p; - } - { /* AIX XL C 1.02.0.0 rejects this saying - "k.c", line 2.27: 1506-025 (S) Operand must be a modifiable lvalue. */ - struct s { int j; const int *ap[3]; }; - struct s *b; b->j = 5; - } - { /* ULTRIX-32 V3.1 (Rev 9) vcc rejects this */ - const int foo = 10; - if (!foo) return 0; - } - return !cs[0] && !zero.x; +/* Override any GCC internal prototype to avoid an error. + Use char because int might match the return type of a GCC + builtin and then its argument prototype would still apply. */ +#ifdef __cplusplus +extern "C" #endif - +char forkpty (); +int +main () +{ +return forkpty (); ; return 0; } _ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" -$as_echo "$ac_try_echo") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - ac_cv_c_const=yes +if ac_fn_c_try_link "$LINENO"; then : + ac_cv_lib_bsd_forkpty=yes else - $as_echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 + ac_cv_lib_bsd_forkpty=no +fi +rm -f core conftest.err conftest.$ac_objext \ + conftest$ac_exeext conftest.$ac_ext +LIBS=$ac_check_lib_save_LIBS +fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_lib_bsd_forkpty" >&5 +$as_echo "$ac_cv_lib_bsd_forkpty" >&6; } +if test "x$ac_cv_lib_bsd_forkpty" = x""yes; then : + $as_echo "#define HAVE_FORKPTY 1" >>confdefs.h + LIBS="$LIBS -lbsd" +fi + - ac_cv_c_const=no fi -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext + fi -{ $as_echo "$as_me:$LINENO: result: $ac_cv_c_const" >&5 -$as_echo "$ac_cv_c_const" >&6; } -if test $ac_cv_c_const = no; then +done + -cat >>confdefs.h <<\_ACEOF -#define const /**/ +# Stuff for expat. +for ac_func in memmove +do : + ac_fn_c_check_func "$LINENO" "memmove" "ac_cv_func_memmove" +if test "x$ac_cv_func_memmove" = x""yes; then : + cat >>confdefs.h <<_ACEOF +#define HAVE_MEMMOVE 1 _ACEOF fi +done -works=no -{ $as_echo "$as_me:$LINENO: checking for working volatile" >&5 -$as_echo_n "checking for working volatile... " >&6; } -cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ +# check for long file support functions +for ac_func in fseek64 fseeko fstatvfs ftell64 ftello statvfs +do : + as_ac_var=`$as_echo "ac_cv_func_$ac_func" | $as_tr_sh` +ac_fn_c_check_func "$LINENO" "$ac_func" "$as_ac_var" +eval as_val=\$$as_ac_var + if test "x$as_val" = x""yes; then : + cat >>confdefs.h <<_ACEOF +#define `$as_echo "HAVE_$ac_func" | $as_tr_cpp` 1 _ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ +fi +done + + +for ac_func in dup2 getcwd strdup +do : + as_ac_var=`$as_echo "ac_cv_func_$ac_func" | $as_tr_sh` +ac_fn_c_check_func "$LINENO" "$ac_func" "$as_ac_var" +eval as_val=\$$as_ac_var + if test "x$as_val" = x""yes; then : + cat >>confdefs.h <<_ACEOF +#define `$as_echo "HAVE_$ac_func" | $as_tr_cpp` 1 +_ACEOF + +else + case " $LIBOBJS " in + *" $ac_func.$ac_objext "* ) ;; + *) LIBOBJS="$LIBOBJS $ac_func.$ac_objext" + ;; +esac + +fi +done + + +for ac_func in getpgrp +do : + ac_fn_c_check_func "$LINENO" "getpgrp" "ac_cv_func_getpgrp" +if test "x$ac_cv_func_getpgrp" = x""yes; then : + cat >>confdefs.h <<_ACEOF +#define HAVE_GETPGRP 1 +_ACEOF + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ +#include int main () { -volatile int x; x = 0; +getpgrp(0); ; return 0; } _ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" -$as_echo "$ac_try_echo") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - works=yes -else - $as_echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 +if ac_fn_c_try_compile "$LINENO"; then : +$as_echo "#define GETPGRP_HAVE_ARG 1" >>confdefs.h -cat >>confdefs.h <<\_ACEOF -#define volatile /**/ -_ACEOF +fi +rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext fi +done + +for ac_func in setpgrp +do : + ac_fn_c_check_func "$LINENO" "setpgrp" "ac_cv_func_setpgrp" +if test "x$ac_cv_func_setpgrp" = x""yes; then : + cat >>confdefs.h <<_ACEOF +#define HAVE_SETPGRP 1 +_ACEOF + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ +#include +int +main () +{ +setpgrp(0,0); + ; + return 0; +} +_ACEOF +if ac_fn_c_try_compile "$LINENO"; then : + +$as_echo "#define SETPGRP_HAVE_ARG 1" >>confdefs.h + +fi rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext -{ $as_echo "$as_me:$LINENO: result: $works" >&5 -$as_echo "$works" >&6; } -works=no -{ $as_echo "$as_me:$LINENO: checking for working signed char" >&5 -$as_echo_n "checking for working signed char... " >&6; } -cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ +fi +done + +for ac_func in gettimeofday +do : + ac_fn_c_check_func "$LINENO" "gettimeofday" "ac_cv_func_gettimeofday" +if test "x$ac_cv_func_gettimeofday" = x""yes; then : + cat >>confdefs.h <<_ACEOF +#define HAVE_GETTIMEOFDAY 1 _ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF + cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ - +#include int main () { -signed char c; +gettimeofday((struct timeval*)0,(struct timezone*)0); ; return 0; } _ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" -$as_echo "$ac_try_echo") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - works=yes +if ac_fn_c_try_compile "$LINENO"; then : + else - $as_echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 +$as_echo "#define GETTIMEOFDAY_NO_TZ 1" >>confdefs.h -cat >>confdefs.h <<\_ACEOF -#define signed /**/ -_ACEOF +fi +rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext fi +done -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext -{ $as_echo "$as_me:$LINENO: result: $works" >&5 -$as_echo "$works" >&6; } -have_prototypes=no -{ $as_echo "$as_me:$LINENO: checking for prototypes" >&5 -$as_echo_n "checking for prototypes... " >&6; } -cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for major" >&5 +$as_echo_n "checking for major... " >&6; } +cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ -int foo(int x) { return 0; } + +#if defined(MAJOR_IN_MKDEV) +#include +#elif defined(MAJOR_IN_SYSMACROS) +#include +#else +#include +#endif + int main () { -return foo(10); + + makedev(major(0),minor(0)); + ; return 0; } _ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" -$as_echo "$ac_try_echo") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then +if ac_fn_c_try_link "$LINENO"; then : -cat >>confdefs.h <<\_ACEOF -#define HAVE_PROTOTYPES 1 -_ACEOF +$as_echo "#define HAVE_DEVICE_MACROS 1" >>confdefs.h - have_prototypes=yes + { $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +$as_echo "yes" >&6; } else - $as_echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 + { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 +$as_echo "no" >&6; } fi +rm -f core conftest.err conftest.$ac_objext \ + conftest$ac_exeext conftest.$ac_ext -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext -{ $as_echo "$as_me:$LINENO: result: $have_prototypes" >&5 -$as_echo "$have_prototypes" >&6; } +# On OSF/1 V5.1, getaddrinfo is available, but a define +# for [no]getaddrinfo in netdb.h. +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for getaddrinfo" >&5 +$as_echo_n "checking for getaddrinfo... " >&6; } +cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + +#include +#include +#include +#include + +int +main () +{ + +getaddrinfo(NULL, NULL, NULL, NULL); + + ; + return 0; +} +_ACEOF +if ac_fn_c_try_link "$LINENO"; then : + +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +$as_echo "yes" >&6; } +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking getaddrinfo bug" >&5 +$as_echo_n "checking getaddrinfo bug... " >&6; } +if test "$cross_compiling" = yes; then : + { $as_echo "$as_me:${as_lineno-$LINENO}: result: buggy" >&5 +$as_echo "buggy" >&6; } +buggygetaddrinfo=yes +else + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + +#include +#include +#include +#include +#include + +main() +{ + int passive, gaierr, inet4 = 0, inet6 = 0; + struct addrinfo hints, *ai, *aitop; + char straddr[INET6_ADDRSTRLEN], strport[16]; + + for (passive = 0; passive <= 1; passive++) { + memset(&hints, 0, sizeof(hints)); + hints.ai_family = AF_UNSPEC; + hints.ai_flags = passive ? AI_PASSIVE : 0; + hints.ai_socktype = SOCK_STREAM; + hints.ai_protocol = IPPROTO_TCP; + if ((gaierr = getaddrinfo(NULL, "54321", &hints, &aitop)) != 0) { + (void)gai_strerror(gaierr); + goto bad; + } + for (ai = aitop; ai; ai = ai->ai_next) { + if (ai->ai_addr == NULL || + ai->ai_addrlen == 0 || + getnameinfo(ai->ai_addr, ai->ai_addrlen, + straddr, sizeof(straddr), strport, sizeof(strport), + NI_NUMERICHOST|NI_NUMERICSERV) != 0) { + goto bad; + } + switch (ai->ai_family) { + case AF_INET: + if (strcmp(strport, "54321") != 0) { + goto bad; + } + if (passive) { + if (strcmp(straddr, "0.0.0.0") != 0) { + goto bad; + } + } else { + if (strcmp(straddr, "127.0.0.1") != 0) { + goto bad; + } + } + inet4++; + break; + case AF_INET6: + if (strcmp(strport, "54321") != 0) { + goto bad; + } + if (passive) { + if (strcmp(straddr, "::") != 0) { + goto bad; + } + } else { + if (strcmp(straddr, "::1") != 0) { + goto bad; + } + } + inet6++; + break; + case AF_UNSPEC: + goto bad; + break; + default: + /* another family support? */ + break; + } + } + } -works=no -{ $as_echo "$as_me:$LINENO: checking for variable length prototypes and stdarg.h" >&5 -$as_echo_n "checking for variable length prototypes and stdarg.h... " >&6; } -cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ + if (!(inet4 == 0 || inet4 == 2)) + goto bad; + if (!(inet6 == 0 || inet6 == 2)) + goto bad; -#include -int foo(int x, ...) { - va_list va; - va_start(va, x); - va_arg(va, int); - va_arg(va, char *); - va_arg(va, double); - return 0; -} + if (aitop) + freeaddrinfo(aitop); + exit(0); -int -main () -{ -return foo(10, "", 3.14); - ; - return 0; + bad: + if (aitop) + freeaddrinfo(aitop); + exit(1); } -_ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" -$as_echo "$ac_try_echo") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - -cat >>confdefs.h <<\_ACEOF -#define HAVE_STDARG_PROTOTYPES 1 _ACEOF - - works=yes - +if ac_fn_c_try_run "$LINENO"; then : + { $as_echo "$as_me:${as_lineno-$LINENO}: result: good" >&5 +$as_echo "good" >&6; } +buggygetaddrinfo=no else - $as_echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - + { $as_echo "$as_me:${as_lineno-$LINENO}: result: buggy" >&5 +$as_echo "buggy" >&6; } +buggygetaddrinfo=yes +fi +rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext \ + conftest.$ac_objext conftest.beam conftest.$ac_ext fi -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext -{ $as_echo "$as_me:$LINENO: result: $works" >&5 -$as_echo "$works" >&6; } - -# check for socketpair -{ $as_echo "$as_me:$LINENO: checking for socketpair" >&5 -$as_echo_n "checking for socketpair... " >&6; } -cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ - -#include -#include - -int -main () -{ -void *x=socketpair - ; - return 0; -} -_ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" -$as_echo "$ac_try_echo") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - -cat >>confdefs.h <<\_ACEOF -#define HAVE_SOCKETPAIR 1 -_ACEOF - - { $as_echo "$as_me:$LINENO: result: yes" >&5 -$as_echo "yes" >&6; } else - $as_echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - { $as_echo "$as_me:$LINENO: result: no" >&5 +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 $as_echo "no" >&6; } +buggygetaddrinfo=yes fi +rm -f core conftest.err conftest.$ac_objext \ + conftest$ac_exeext conftest.$ac_ext -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext +if test "$buggygetaddrinfo" = "yes"; then + if test "$ipv6" = "yes"; then + echo 'Fatal: You must get working getaddrinfo() function.' + echo ' or you can specify "--disable-ipv6"'. + exit 1 + fi +else -# check if sockaddr has sa_len member -{ $as_echo "$as_me:$LINENO: checking if sockaddr has sa_len member" >&5 -$as_echo_n "checking if sockaddr has sa_len member... " >&6; } -cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -#include -#include -int -main () -{ -struct sockaddr x; -x.sa_len = 0; - ; - return 0; -} -_ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" -$as_echo "$ac_try_echo") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - { $as_echo "$as_me:$LINENO: result: yes" >&5 -$as_echo "yes" >&6; } +$as_echo "#define HAVE_GETADDRINFO 1" >>confdefs.h -cat >>confdefs.h <<\_ACEOF -#define HAVE_SOCKADDR_SA_LEN 1 +fi +for ac_func in getnameinfo +do : + ac_fn_c_check_func "$LINENO" "getnameinfo" "ac_cv_func_getnameinfo" +if test "x$ac_cv_func_getnameinfo" = x""yes; then : + cat >>confdefs.h <<_ACEOF +#define HAVE_GETNAMEINFO 1 _ACEOF -else - $as_echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - { $as_echo "$as_me:$LINENO: result: no" >&5 -$as_echo "no" >&6; } fi +done -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext -va_list_is_array=no -{ $as_echo "$as_me:$LINENO: checking whether va_list is an array" >&5 -$as_echo_n "checking whether va_list is an array... " >&6; } -cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF +# checks for structures +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking whether time.h and sys/time.h may both be included" >&5 +$as_echo_n "checking whether time.h and sys/time.h may both be included... " >&6; } +if test "${ac_cv_header_time+set}" = set; then : + $as_echo_n "(cached) " >&6 +else + cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ - -#ifdef HAVE_STDARG_PROTOTYPES -#include -#else -#include -#endif +#include +#include +#include int main () { -va_list list1, list2; list1 = list2; +if ((struct tm *) 0) +return 0; ; return 0; } _ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" -$as_echo "$ac_try_echo") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - : +if ac_fn_c_try_compile "$LINENO"; then : + ac_cv_header_time=yes else - $as_echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - - -cat >>confdefs.h <<\_ACEOF -#define VA_LIST_IS_ARRAY 1 -_ACEOF - - va_list_is_array=yes - + ac_cv_header_time=no fi - rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext -{ $as_echo "$as_me:$LINENO: result: $va_list_is_array" >&5 -$as_echo "$va_list_is_array" >&6; } - -# sigh -- gethostbyname_r is a mess; it can have 3, 5 or 6 arguments :-( +fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_header_time" >&5 +$as_echo "$ac_cv_header_time" >&6; } +if test $ac_cv_header_time = yes; then +$as_echo "#define TIME_WITH_SYS_TIME 1" >>confdefs.h +fi -{ $as_echo "$as_me:$LINENO: checking for gethostbyname_r" >&5 -$as_echo_n "checking for gethostbyname_r... " >&6; } -if test "${ac_cv_func_gethostbyname_r+set}" = set; then +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking whether struct tm is in sys/time.h or time.h" >&5 +$as_echo_n "checking whether struct tm is in sys/time.h or time.h... " >&6; } +if test "${ac_cv_struct_tm+set}" = set; then : $as_echo_n "(cached) " >&6 else - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF + cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ -/* Define gethostbyname_r to an innocuous variant, in case declares gethostbyname_r. - For example, HP-UX 11i declares gettimeofday. */ -#define gethostbyname_r innocuous_gethostbyname_r - -/* System header to define __stub macros and hopefully few prototypes, - which can conflict with char gethostbyname_r (); below. - Prefer to if __STDC__ is defined, since - exists even on freestanding compilers. */ - -#ifdef __STDC__ -# include -#else -# include -#endif - -#undef gethostbyname_r - -/* Override any GCC internal prototype to avoid an error. - Use char because int might match the return type of a GCC - builtin and then its argument prototype would still apply. */ -#ifdef __cplusplus -extern "C" -#endif -char gethostbyname_r (); -/* The GNU C library defines this for functions which it implements - to always fail with ENOSYS. Some functions are actually named - something starting with __ and the normal name is an alias. */ -#if defined __stub_gethostbyname_r || defined __stub___gethostbyname_r -choke me -#endif +#include +#include int main () { -return gethostbyname_r (); +struct tm tm; + int *p = &tm.tm_sec; + return !p; ; return 0; } _ACEOF -rm -f conftest.$ac_objext conftest$ac_exeext -if { (ac_try="$ac_link" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" -$as_echo "$ac_try_echo") >&5 - (eval "$ac_link") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest$ac_exeext && { - test "$cross_compiling" = yes || - $as_test_x conftest$ac_exeext - }; then - ac_cv_func_gethostbyname_r=yes +if ac_fn_c_try_compile "$LINENO"; then : + ac_cv_struct_tm=time.h else - $as_echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - ac_cv_func_gethostbyname_r=no + ac_cv_struct_tm=sys/time.h fi - -rm -rf conftest.dSYM -rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \ - conftest$ac_exeext conftest.$ac_ext +rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext fi -{ $as_echo "$as_me:$LINENO: result: $ac_cv_func_gethostbyname_r" >&5 -$as_echo "$ac_cv_func_gethostbyname_r" >&6; } -if test "x$ac_cv_func_gethostbyname_r" = x""yes; then - - cat >>confdefs.h <<\_ACEOF -#define HAVE_GETHOSTBYNAME_R 1 -_ACEOF - - { $as_echo "$as_me:$LINENO: checking gethostbyname_r with 6 args" >&5 -$as_echo_n "checking gethostbyname_r with 6 args... " >&6; } - OLD_CFLAGS=$CFLAGS - CFLAGS="$CFLAGS $MY_CPPFLAGS $MY_THREAD_CPPFLAGS $MY_CFLAGS" - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_struct_tm" >&5 +$as_echo "$ac_cv_struct_tm" >&6; } +if test $ac_cv_struct_tm = sys/time.h; then -# include +$as_echo "#define TM_IN_SYS_TIME 1" >>confdefs.h -int -main () -{ +fi - char *name; - struct hostent *he, *res; - char buffer[2048]; - int buflen = 2048; - int h_errnop; +ac_fn_c_check_member "$LINENO" "struct tm" "tm_zone" "ac_cv_member_struct_tm_tm_zone" "#include +#include <$ac_cv_struct_tm> - (void) gethostbyname_r(name, he, buffer, buflen, &res, &h_errnop) +" +if test "x$ac_cv_member_struct_tm_tm_zone" = x""yes; then : - ; - return 0; -} +cat >>confdefs.h <<_ACEOF +#define HAVE_STRUCT_TM_TM_ZONE 1 _ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" -$as_echo "$ac_try_echo") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - cat >>confdefs.h <<\_ACEOF -#define HAVE_GETHOSTBYNAME_R 1 -_ACEOF +fi -cat >>confdefs.h <<\_ACEOF -#define HAVE_GETHOSTBYNAME_R_6_ARG 1 -_ACEOF +if test "$ac_cv_member_struct_tm_tm_zone" = yes; then - { $as_echo "$as_me:$LINENO: result: yes" >&5 -$as_echo "yes" >&6; } +$as_echo "#define HAVE_TM_ZONE 1" >>confdefs.h else - $as_echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - + ac_fn_c_check_decl "$LINENO" "tzname" "ac_cv_have_decl_tzname" "#include +" +if test "x$ac_cv_have_decl_tzname" = x""yes; then : + ac_have_decl=1 +else + ac_have_decl=0 +fi - { $as_echo "$as_me:$LINENO: result: no" >&5 -$as_echo "no" >&6; } - { $as_echo "$as_me:$LINENO: checking gethostbyname_r with 5 args" >&5 -$as_echo_n "checking gethostbyname_r with 5 args... " >&6; } - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ +cat >>confdefs.h <<_ACEOF +#define HAVE_DECL_TZNAME $ac_have_decl _ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -# include + { $as_echo "$as_me:${as_lineno-$LINENO}: checking for tzname" >&5 +$as_echo_n "checking for tzname... " >&6; } +if test "${ac_cv_var_tzname+set}" = set; then : + $as_echo_n "(cached) " >&6 +else + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ +#include +#if !HAVE_DECL_TZNAME +extern char *tzname[]; +#endif int main () { - - char *name; - struct hostent *he; - char buffer[2048]; - int buflen = 2048; - int h_errnop; - - (void) gethostbyname_r(name, he, buffer, buflen, &h_errnop) - +return tzname[0][0]; ; return 0; } _ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" -$as_echo "$ac_try_echo") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then +if ac_fn_c_try_link "$LINENO"; then : + ac_cv_var_tzname=yes +else + ac_cv_var_tzname=no +fi +rm -f core conftest.err conftest.$ac_objext \ + conftest$ac_exeext conftest.$ac_ext +fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_var_tzname" >&5 +$as_echo "$ac_cv_var_tzname" >&6; } + if test $ac_cv_var_tzname = yes; then - cat >>confdefs.h <<\_ACEOF -#define HAVE_GETHOSTBYNAME_R 1 -_ACEOF +$as_echo "#define HAVE_TZNAME 1" >>confdefs.h + fi +fi -cat >>confdefs.h <<\_ACEOF -#define HAVE_GETHOSTBYNAME_R_5_ARG 1 +ac_fn_c_check_member "$LINENO" "struct stat" "st_rdev" "ac_cv_member_struct_stat_st_rdev" "$ac_includes_default" +if test "x$ac_cv_member_struct_stat_st_rdev" = x""yes; then : + +cat >>confdefs.h <<_ACEOF +#define HAVE_STRUCT_STAT_ST_RDEV 1 _ACEOF - { $as_echo "$as_me:$LINENO: result: yes" >&5 -$as_echo "yes" >&6; } -else - $as_echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 +fi +ac_fn_c_check_member "$LINENO" "struct stat" "st_blksize" "ac_cv_member_struct_stat_st_blksize" "$ac_includes_default" +if test "x$ac_cv_member_struct_stat_st_blksize" = x""yes; then : - { $as_echo "$as_me:$LINENO: result: no" >&5 -$as_echo "no" >&6; } - { $as_echo "$as_me:$LINENO: checking gethostbyname_r with 3 args" >&5 -$as_echo_n "checking gethostbyname_r with 3 args... " >&6; } - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ +cat >>confdefs.h <<_ACEOF +#define HAVE_STRUCT_STAT_ST_BLKSIZE 1 _ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ - -# include - -int -main () -{ - char *name; - struct hostent *he; - struct hostent_data data; - (void) gethostbyname_r(name, he, &data); +fi - ; - return 0; -} -_ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" -$as_echo "$ac_try_echo") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then +ac_fn_c_check_member "$LINENO" "struct stat" "st_flags" "ac_cv_member_struct_stat_st_flags" "$ac_includes_default" +if test "x$ac_cv_member_struct_stat_st_flags" = x""yes; then : - cat >>confdefs.h <<\_ACEOF -#define HAVE_GETHOSTBYNAME_R 1 +cat >>confdefs.h <<_ACEOF +#define HAVE_STRUCT_STAT_ST_FLAGS 1 _ACEOF -cat >>confdefs.h <<\_ACEOF -#define HAVE_GETHOSTBYNAME_R_3_ARG 1 -_ACEOF - - { $as_echo "$as_me:$LINENO: result: yes" >&5 -$as_echo "yes" >&6; } +fi -else - $as_echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 +ac_fn_c_check_member "$LINENO" "struct stat" "st_gen" "ac_cv_member_struct_stat_st_gen" "$ac_includes_default" +if test "x$ac_cv_member_struct_stat_st_gen" = x""yes; then : +cat >>confdefs.h <<_ACEOF +#define HAVE_STRUCT_STAT_ST_GEN 1 +_ACEOF - { $as_echo "$as_me:$LINENO: result: no" >&5 -$as_echo "no" >&6; } fi -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext +ac_fn_c_check_member "$LINENO" "struct stat" "st_birthtime" "ac_cv_member_struct_stat_st_birthtime" "$ac_includes_default" +if test "x$ac_cv_member_struct_stat_st_birthtime" = x""yes; then : -fi +cat >>confdefs.h <<_ACEOF +#define HAVE_STRUCT_STAT_ST_BIRTHTIME 1 +_ACEOF -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext fi -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext - CFLAGS=$OLD_CFLAGS +ac_fn_c_check_member "$LINENO" "struct stat" "st_blocks" "ac_cv_member_struct_stat_st_blocks" "$ac_includes_default" +if test "x$ac_cv_member_struct_stat_st_blocks" = x""yes; then : -else +cat >>confdefs.h <<_ACEOF +#define HAVE_STRUCT_STAT_ST_BLOCKS 1 +_ACEOF -for ac_func in gethostbyname -do -as_ac_var=`$as_echo "ac_cv_func_$ac_func" | $as_tr_sh` -{ $as_echo "$as_me:$LINENO: checking for $ac_func" >&5 -$as_echo_n "checking for $ac_func... " >&6; } -if { as_var=$as_ac_var; eval "test \"\${$as_var+set}\" = set"; }; then - $as_echo_n "(cached) " >&6 -else - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -/* Define $ac_func to an innocuous variant, in case declares $ac_func. - For example, HP-UX 11i declares gettimeofday. */ -#define $ac_func innocuous_$ac_func +$as_echo "#define HAVE_ST_BLOCKS 1" >>confdefs.h -/* System header to define __stub macros and hopefully few prototypes, - which can conflict with char $ac_func (); below. - Prefer to if __STDC__ is defined, since - exists even on freestanding compilers. */ +else + case " $LIBOBJS " in + *" fileblocks.$ac_objext "* ) ;; + *) LIBOBJS="$LIBOBJS fileblocks.$ac_objext" + ;; +esac -#ifdef __STDC__ -# include -#else -# include -#endif +fi -#undef $ac_func -/* Override any GCC internal prototype to avoid an error. - Use char because int might match the return type of a GCC - builtin and then its argument prototype would still apply. */ -#ifdef __cplusplus -extern "C" -#endif -char $ac_func (); -/* The GNU C library defines this for functions which it implements - to always fail with ENOSYS. Some functions are actually named - something starting with __ and the normal name is an alias. */ -#if defined __stub_$ac_func || defined __stub___$ac_func -choke me -#endif +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for time.h that defines altzone" >&5 +$as_echo_n "checking for time.h that defines altzone... " >&6; } +if test "${ac_cv_header_time_altzone+set}" = set; then : + $as_echo_n "(cached) " >&6 +else + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ +#include int main () { -return $ac_func (); +return altzone; ; return 0; } _ACEOF -rm -f conftest.$ac_objext conftest$ac_exeext -if { (ac_try="$ac_link" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" -$as_echo "$ac_try_echo") >&5 - (eval "$ac_link") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest$ac_exeext && { - test "$cross_compiling" = yes || - $as_test_x conftest$ac_exeext - }; then - eval "$as_ac_var=yes" +if ac_fn_c_try_compile "$LINENO"; then : + ac_cv_header_time_altzone=yes else - $as_echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - eval "$as_ac_var=no" + ac_cv_header_time_altzone=no fi - -rm -rf conftest.dSYM -rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \ - conftest$ac_exeext conftest.$ac_ext +rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext fi -ac_res=`eval 'as_val=${'$as_ac_var'} - $as_echo "$as_val"'` - { $as_echo "$as_me:$LINENO: result: $ac_res" >&5 -$as_echo "$ac_res" >&6; } -as_val=`eval 'as_val=${'$as_ac_var'} - $as_echo "$as_val"'` - if test "x$as_val" = x""yes; then - cat >>confdefs.h <<_ACEOF -#define `$as_echo "HAVE_$ac_func" | $as_tr_cpp` 1 -_ACEOF -fi -done +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_header_time_altzone" >&5 +$as_echo "$ac_cv_header_time_altzone" >&6; } +if test $ac_cv_header_time_altzone = yes; then +$as_echo "#define HAVE_ALTZONE 1" >>confdefs.h fi +was_it_defined=no +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking whether sys/select.h and sys/time.h may both be included" >&5 +$as_echo_n "checking whether sys/select.h and sys/time.h may both be included... " >&6; } +cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ +#include +#include +#include +int +main () +{ +; + ; + return 0; +} +_ACEOF +if ac_fn_c_try_compile "$LINENO"; then : +$as_echo "#define SYS_SELECT_WITH_SYS_TIME 1" >>confdefs.h + was_it_defined=yes -# checks for system services -# (none yet) +fi +rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $was_it_defined" >&5 +$as_echo "$was_it_defined" >&6; } -# Linux requires this for correct f.p. operations -{ $as_echo "$as_me:$LINENO: checking for __fpu_control" >&5 -$as_echo_n "checking for __fpu_control... " >&6; } -if test "${ac_cv_func___fpu_control+set}" = set; then +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for addrinfo" >&5 +$as_echo_n "checking for addrinfo... " >&6; } +if test "${ac_cv_struct_addrinfo+set}" = set; then : $as_echo_n "(cached) " >&6 else - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + +# include +int +main () +{ +struct addrinfo a + ; + return 0; +} _ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF +if ac_fn_c_try_compile "$LINENO"; then : + ac_cv_struct_addrinfo=yes +else + ac_cv_struct_addrinfo=no +fi +rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext +fi + +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_struct_addrinfo" >&5 +$as_echo "$ac_cv_struct_addrinfo" >&6; } +if test $ac_cv_struct_addrinfo = yes; then + +$as_echo "#define HAVE_ADDRINFO 1" >>confdefs.h + +fi + +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for sockaddr_storage" >&5 +$as_echo_n "checking for sockaddr_storage... " >&6; } +if test "${ac_cv_struct_sockaddr_storage+set}" = set; then : + $as_echo_n "(cached) " >&6 +else + cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ -/* Define __fpu_control to an innocuous variant, in case declares __fpu_control. - For example, HP-UX 11i declares gettimeofday. */ -#define __fpu_control innocuous___fpu_control -/* System header to define __stub macros and hopefully few prototypes, - which can conflict with char __fpu_control (); below. - Prefer to if __STDC__ is defined, since - exists even on freestanding compilers. */ +# include +# include +int +main () +{ +struct sockaddr_storage s + ; + return 0; +} +_ACEOF +if ac_fn_c_try_compile "$LINENO"; then : + ac_cv_struct_sockaddr_storage=yes +else + ac_cv_struct_sockaddr_storage=no +fi +rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext +fi -#ifdef __STDC__ -# include -#else -# include -#endif +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_struct_sockaddr_storage" >&5 +$as_echo "$ac_cv_struct_sockaddr_storage" >&6; } +if test $ac_cv_struct_sockaddr_storage = yes; then -#undef __fpu_control +$as_echo "#define HAVE_SOCKADDR_STORAGE 1" >>confdefs.h -/* Override any GCC internal prototype to avoid an error. - Use char because int might match the return type of a GCC - builtin and then its argument prototype would still apply. */ -#ifdef __cplusplus -extern "C" -#endif -char __fpu_control (); -/* The GNU C library defines this for functions which it implements - to always fail with ENOSYS. Some functions are actually named - something starting with __ and the normal name is an alias. */ -#if defined __stub___fpu_control || defined __stub_____fpu_control -choke me -#endif +fi + +# checks for compiler characteristics +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking whether char is unsigned" >&5 +$as_echo_n "checking whether char is unsigned... " >&6; } +if test "${ac_cv_c_char_unsigned+set}" = set; then : + $as_echo_n "(cached) " >&6 +else + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ +$ac_includes_default int main () { -return __fpu_control (); +static int test_array [1 - 2 * !(((char) -1) < 0)]; +test_array [0] = 0 + ; return 0; } _ACEOF -rm -f conftest.$ac_objext conftest$ac_exeext -if { (ac_try="$ac_link" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" -$as_echo "$ac_try_echo") >&5 - (eval "$ac_link") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest$ac_exeext && { - test "$cross_compiling" = yes || - $as_test_x conftest$ac_exeext - }; then - ac_cv_func___fpu_control=yes +if ac_fn_c_try_compile "$LINENO"; then : + ac_cv_c_char_unsigned=no else - $as_echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - ac_cv_func___fpu_control=no + ac_cv_c_char_unsigned=yes +fi +rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_c_char_unsigned" >&5 +$as_echo "$ac_cv_c_char_unsigned" >&6; } +if test $ac_cv_c_char_unsigned = yes && test "$GCC" != yes; then + $as_echo "#define __CHAR_UNSIGNED__ 1" >>confdefs.h -rm -rf conftest.dSYM -rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \ - conftest$ac_exeext conftest.$ac_ext fi -{ $as_echo "$as_me:$LINENO: result: $ac_cv_func___fpu_control" >&5 -$as_echo "$ac_cv_func___fpu_control" >&6; } -if test "x$ac_cv_func___fpu_control" = x""yes; then - : -else -{ $as_echo "$as_me:$LINENO: checking for __fpu_control in -lieee" >&5 -$as_echo_n "checking for __fpu_control in -lieee... " >&6; } -if test "${ac_cv_lib_ieee___fpu_control+set}" = set; then +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for an ANSI C-conforming const" >&5 +$as_echo_n "checking for an ANSI C-conforming const... " >&6; } +if test "${ac_cv_c_const+set}" = set; then : $as_echo_n "(cached) " >&6 else - ac_check_lib_save_LIBS=$LIBS -LIBS="-lieee $LIBS" -cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF + cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ -/* Override any GCC internal prototype to avoid an error. - Use char because int might match the return type of a GCC - builtin and then its argument prototype would still apply. */ -#ifdef __cplusplus -extern "C" -#endif -char __fpu_control (); int main () { -return __fpu_control (); +/* FIXME: Include the comments suggested by Paul. */ +#ifndef __cplusplus + /* Ultrix mips cc rejects this. */ + typedef int charset[2]; + const charset cs; + /* SunOS 4.1.1 cc rejects this. */ + char const *const *pcpcc; + char **ppc; + /* NEC SVR4.0.2 mips cc rejects this. */ + struct point {int x, y;}; + static struct point const zero = {0,0}; + /* AIX XL C 1.02.0.0 rejects this. + It does not let you subtract one const X* pointer from another in + an arm of an if-expression whose if-part is not a constant + expression */ + const char *g = "string"; + pcpcc = &g + (g ? g-g : 0); + /* HPUX 7.0 cc rejects these. */ + ++pcpcc; + ppc = (char**) pcpcc; + pcpcc = (char const *const *) ppc; + { /* SCO 3.2v4 cc rejects this. */ + char *t; + char const *s = 0 ? (char *) 0 : (char const *) 0; + + *t++ = 0; + if (s) return 0; + } + { /* Someone thinks the Sun supposedly-ANSI compiler will reject this. */ + int x[] = {25, 17}; + const int *foo = &x[0]; + ++foo; + } + { /* Sun SC1.0 ANSI compiler rejects this -- but not the above. */ + typedef const int *iptr; + iptr p = 0; + ++p; + } + { /* AIX XL C 1.02.0.0 rejects this saying + "k.c", line 2.27: 1506-025 (S) Operand must be a modifiable lvalue. */ + struct s { int j; const int *ap[3]; }; + struct s *b; b->j = 5; + } + { /* ULTRIX-32 V3.1 (Rev 9) vcc rejects this */ + const int foo = 10; + if (!foo) return 0; + } + return !cs[0] && !zero.x; +#endif + ; return 0; } _ACEOF -rm -f conftest.$ac_objext conftest$ac_exeext -if { (ac_try="$ac_link" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" -$as_echo "$ac_try_echo") >&5 - (eval "$ac_link") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest$ac_exeext && { - test "$cross_compiling" = yes || - $as_test_x conftest$ac_exeext - }; then - ac_cv_lib_ieee___fpu_control=yes +if ac_fn_c_try_compile "$LINENO"; then : + ac_cv_c_const=yes else - $as_echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - ac_cv_lib_ieee___fpu_control=no -fi - -rm -rf conftest.dSYM -rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \ - conftest$ac_exeext conftest.$ac_ext -LIBS=$ac_check_lib_save_LIBS + ac_cv_c_const=no fi -{ $as_echo "$as_me:$LINENO: result: $ac_cv_lib_ieee___fpu_control" >&5 -$as_echo "$ac_cv_lib_ieee___fpu_control" >&6; } -if test "x$ac_cv_lib_ieee___fpu_control" = x""yes; then - cat >>confdefs.h <<_ACEOF -#define HAVE_LIBIEEE 1 -_ACEOF - - LIBS="-lieee $LIBS" - +rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_c_const" >&5 +$as_echo "$ac_cv_c_const" >&6; } +if test $ac_cv_c_const = no; then +$as_echo "#define const /**/" >>confdefs.h fi -# Check for --with-fpectl -{ $as_echo "$as_me:$LINENO: checking for --with-fpectl" >&5 -$as_echo_n "checking for --with-fpectl... " >&6; } - -# Check whether --with-fpectl was given. -if test "${with_fpectl+set}" = set; then - withval=$with_fpectl; -if test "$withval" != no -then +works=no +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for working volatile" >&5 +$as_echo_n "checking for working volatile... " >&6; } +cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ -cat >>confdefs.h <<\_ACEOF -#define WANT_SIGFPE_HANDLER 1 +int +main () +{ +volatile int x; x = 0; + ; + return 0; +} _ACEOF - - { $as_echo "$as_me:$LINENO: result: yes" >&5 -$as_echo "yes" >&6; } -else { $as_echo "$as_me:$LINENO: result: no" >&5 -$as_echo "no" >&6; } -fi +if ac_fn_c_try_compile "$LINENO"; then : + works=yes else - { $as_echo "$as_me:$LINENO: result: no" >&5 -$as_echo "no" >&6; } -fi +$as_echo "#define volatile /**/" >>confdefs.h -# check for --with-libm=... - -case $ac_sys_system in -Darwin) ;; -BeOS) ;; -*) LIBM=-lm -esac -{ $as_echo "$as_me:$LINENO: checking for --with-libm=STRING" >&5 -$as_echo_n "checking for --with-libm=STRING... " >&6; } -# Check whether --with-libm was given. -if test "${with_libm+set}" = set; then - withval=$with_libm; -if test "$withval" = no -then LIBM= - { $as_echo "$as_me:$LINENO: result: force LIBM empty" >&5 -$as_echo "force LIBM empty" >&6; } -elif test "$withval" != yes -then LIBM=$withval - { $as_echo "$as_me:$LINENO: result: set LIBM=\"$withval\"" >&5 -$as_echo "set LIBM=\"$withval\"" >&6; } -else { { $as_echo "$as_me:$LINENO: error: proper usage is --with-libm=STRING" >&5 -$as_echo "$as_me: error: proper usage is --with-libm=STRING" >&2;} - { (exit 1); exit 1; }; } fi -else - { $as_echo "$as_me:$LINENO: result: default LIBM=\"$LIBM\"" >&5 -$as_echo "default LIBM=\"$LIBM\"" >&6; } -fi - - -# check for --with-libc=... +rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $works" >&5 +$as_echo "$works" >&6; } -{ $as_echo "$as_me:$LINENO: checking for --with-libc=STRING" >&5 -$as_echo_n "checking for --with-libc=STRING... " >&6; } +works=no +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for working signed char" >&5 +$as_echo_n "checking for working signed char... " >&6; } +cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ -# Check whether --with-libc was given. -if test "${with_libc+set}" = set; then - withval=$with_libc; -if test "$withval" = no -then LIBC= - { $as_echo "$as_me:$LINENO: result: force LIBC empty" >&5 -$as_echo "force LIBC empty" >&6; } -elif test "$withval" != yes -then LIBC=$withval - { $as_echo "$as_me:$LINENO: result: set LIBC=\"$withval\"" >&5 -$as_echo "set LIBC=\"$withval\"" >&6; } -else { { $as_echo "$as_me:$LINENO: error: proper usage is --with-libc=STRING" >&5 -$as_echo "$as_me: error: proper usage is --with-libc=STRING" >&2;} - { (exit 1); exit 1; }; } -fi +int +main () +{ +signed char c; + ; + return 0; +} +_ACEOF +if ac_fn_c_try_compile "$LINENO"; then : + works=yes else - { $as_echo "$as_me:$LINENO: result: default LIBC=\"$LIBC\"" >&5 -$as_echo "default LIBC=\"$LIBC\"" >&6; } -fi +$as_echo "#define signed /**/" >>confdefs.h -# ************************************ -# * Check for mathematical functions * -# ************************************ - -LIBS_SAVE=$LIBS -LIBS="$LIBS $LIBM" -# Detect whether system arithmetic is subject to x87-style double -# rounding issues. The result of this test has little meaning on non -# IEEE 754 platforms. On IEEE 754, test should return 1 if rounding -# mode is round-to-nearest and double rounding issues are present, and -# 0 otherwise. See http://bugs.python.org/issue2937 for more info. -{ $as_echo "$as_me:$LINENO: checking for x87-style double rounding" >&5 -$as_echo_n "checking for x87-style double rounding... " >&6; } -if test "${ac_cv_x87_double_rounding+set}" = set; then - $as_echo_n "(cached) " >&6 -else +fi +rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $works" >&5 +$as_echo "$works" >&6; } -if test "$cross_compiling" = yes; then - ac_cv_x87_double_rounding=no -else - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF +have_prototypes=no +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for prototypes" >&5 +$as_echo_n "checking for prototypes... " >&6; } +cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ - -#include -#include -int main() { - volatile double x, y, z; - /* 1./(1-2**-53) -> 1+2**-52 (correct), 1.0 (double rounding) */ - x = 0.99999999999999989; /* 1-2**-53 */ - y = 1./x; - if (y != 1.) - exit(0); - /* 1e16+2.99999 -> 1e16+2. (correct), 1e16+4. (double rounding) */ - x = 1e16; - y = 2.99999; - z = x + y; - if (z != 1e16+4.) - exit(0); - /* both tests show evidence of double rounding */ - exit(1); +int foo(int x) { return 0; } +int +main () +{ +return foo(10); + ; + return 0; } - _ACEOF -rm -f conftest$ac_exeext -if { (ac_try="$ac_link" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" -$as_echo "$ac_try_echo") >&5 - (eval "$ac_link") 2>&5 - ac_status=$? - $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { ac_try='./conftest$ac_exeext' - { (case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" -$as_echo "$ac_try_echo") >&5 - (eval "$ac_try") 2>&5 - ac_status=$? - $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); }; }; then - ac_cv_x87_double_rounding=no -else - $as_echo "$as_me: program exited with status $ac_status" >&5 -$as_echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 +if ac_fn_c_try_compile "$LINENO"; then : -( exit $ac_status ) -ac_cv_x87_double_rounding=yes -fi -rm -rf conftest.dSYM -rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext conftest.$ac_objext conftest.$ac_ext -fi +$as_echo "#define HAVE_PROTOTYPES 1" >>confdefs.h + + have_prototypes=yes fi +rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $have_prototypes" >&5 +$as_echo "$have_prototypes" >&6; } -{ $as_echo "$as_me:$LINENO: result: $ac_cv_x87_double_rounding" >&5 -$as_echo "$ac_cv_x87_double_rounding" >&6; } -if test "$ac_cv_x87_double_rounding" = yes -then +works=no +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for variable length prototypes and stdarg.h" >&5 +$as_echo_n "checking for variable length prototypes and stdarg.h... " >&6; } +cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + +#include +int foo(int x, ...) { + va_list va; + va_start(va, x); + va_arg(va, int); + va_arg(va, char *); + va_arg(va, double); + return 0; +} -cat >>confdefs.h <<\_ACEOF -#define X87_DOUBLE_ROUNDING 1 +int +main () +{ +return foo(10, "", 3.14); + ; + return 0; +} _ACEOF +if ac_fn_c_try_compile "$LINENO"; then : -fi +$as_echo "#define HAVE_STDARG_PROTOTYPES 1" >>confdefs.h -# On FreeBSD 6.2, it appears that tanh(-0.) returns 0. instead of -# -0. on some architectures. -{ $as_echo "$as_me:$LINENO: checking whether tanh preserves the sign of zero" >&5 -$as_echo_n "checking whether tanh preserves the sign of zero... " >&6; } -if test "${ac_cv_tanh_preserves_zero_sign+set}" = set; then - $as_echo_n "(cached) " >&6 -else + works=yes -if test "$cross_compiling" = yes; then - ac_cv_tanh_preserves_zero_sign=no -else - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF +fi +rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $works" >&5 +$as_echo "$works" >&6; } + +# check for socketpair +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for socketpair" >&5 +$as_echo_n "checking for socketpair... " >&6; } +cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ -#include -#include -int main() { - /* return 0 if either negative zeros don't exist - on this platform or if negative zeros exist - and tanh(-0.) == -0. */ - if (atan2(0., -1.) == atan2(-0., -1.) || - atan2(tanh(-0.), -1.) == atan2(-0., -1.)) exit(0); - else exit(1); -} +#include +#include +int +main () +{ +void *x=socketpair + ; + return 0; +} _ACEOF -rm -f conftest$ac_exeext -if { (ac_try="$ac_link" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" -$as_echo "$ac_try_echo") >&5 - (eval "$ac_link") 2>&5 - ac_status=$? - $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { ac_try='./conftest$ac_exeext' - { (case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" -$as_echo "$ac_try_echo") >&5 - (eval "$ac_try") 2>&5 - ac_status=$? - $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); }; }; then - ac_cv_tanh_preserves_zero_sign=yes -else - $as_echo "$as_me: program exited with status $ac_status" >&5 -$as_echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 +if ac_fn_c_try_compile "$LINENO"; then : -( exit $ac_status ) -ac_cv_tanh_preserves_zero_sign=no -fi -rm -rf conftest.dSYM -rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext conftest.$ac_objext conftest.$ac_ext -fi +$as_echo "#define HAVE_SOCKETPAIR 1" >>confdefs.h + { $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +$as_echo "yes" >&6; } +else + { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 +$as_echo "no" >&6; } fi +rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext -{ $as_echo "$as_me:$LINENO: result: $ac_cv_tanh_preserves_zero_sign" >&5 -$as_echo "$ac_cv_tanh_preserves_zero_sign" >&6; } -if test "$ac_cv_tanh_preserves_zero_sign" = yes -then - -cat >>confdefs.h <<\_ACEOF -#define TANH_PRESERVES_ZERO_SIGN 1 +# check if sockaddr has sa_len member +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking if sockaddr has sa_len member" >&5 +$as_echo_n "checking if sockaddr has sa_len member... " >&6; } +cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ +#include +#include +int +main () +{ +struct sockaddr x; +x.sa_len = 0; + ; + return 0; +} _ACEOF +if ac_fn_c_try_compile "$LINENO"; then : + { $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +$as_echo "yes" >&6; } +$as_echo "#define HAVE_SOCKADDR_SA_LEN 1" >>confdefs.h + +else + { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 +$as_echo "no" >&6; } fi +rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext + +va_list_is_array=no +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking whether va_list is an array" >&5 +$as_echo_n "checking whether va_list is an array... " >&6; } +cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ +#ifdef HAVE_STDARG_PROTOTYPES +#include +#else +#include +#endif +int +main () +{ +va_list list1, list2; list1 = list2; + ; + return 0; +} +_ACEOF +if ac_fn_c_try_compile "$LINENO"; then : +else +$as_echo "#define VA_LIST_IS_ARRAY 1" >>confdefs.h + va_list_is_array=yes +fi +rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $va_list_is_array" >&5 +$as_echo "$va_list_is_array" >&6; } +# sigh -- gethostbyname_r is a mess; it can have 3, 5 or 6 arguments :-( -for ac_func in acosh asinh atanh copysign expm1 finite hypot log1p -do -as_ac_var=`$as_echo "ac_cv_func_$ac_func" | $as_tr_sh` -{ $as_echo "$as_me:$LINENO: checking for $ac_func" >&5 -$as_echo_n "checking for $ac_func... " >&6; } -if { as_var=$as_ac_var; eval "test \"\${$as_var+set}\" = set"; }; then - $as_echo_n "(cached) " >&6 -else - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -/* Define $ac_func to an innocuous variant, in case declares $ac_func. - For example, HP-UX 11i declares gettimeofday. */ -#define $ac_func innocuous_$ac_func -/* System header to define __stub macros and hopefully few prototypes, - which can conflict with char $ac_func (); below. - Prefer to if __STDC__ is defined, since - exists even on freestanding compilers. */ +ac_fn_c_check_func "$LINENO" "gethostbyname_r" "ac_cv_func_gethostbyname_r" +if test "x$ac_cv_func_gethostbyname_r" = x""yes; then : -#ifdef __STDC__ -# include -#else -# include -#endif + $as_echo "#define HAVE_GETHOSTBYNAME_R 1" >>confdefs.h -#undef $ac_func + { $as_echo "$as_me:${as_lineno-$LINENO}: checking gethostbyname_r with 6 args" >&5 +$as_echo_n "checking gethostbyname_r with 6 args... " >&6; } + OLD_CFLAGS=$CFLAGS + CFLAGS="$CFLAGS $MY_CPPFLAGS $MY_THREAD_CPPFLAGS $MY_CFLAGS" + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ -/* Override any GCC internal prototype to avoid an error. - Use char because int might match the return type of a GCC - builtin and then its argument prototype would still apply. */ -#ifdef __cplusplus -extern "C" -#endif -char $ac_func (); -/* The GNU C library defines this for functions which it implements - to always fail with ENOSYS. Some functions are actually named - something starting with __ and the normal name is an alias. */ -#if defined __stub_$ac_func || defined __stub___$ac_func -choke me -#endif +# include int main () { -return $ac_func (); + + char *name; + struct hostent *he, *res; + char buffer[2048]; + int buflen = 2048; + int h_errnop; + + (void) gethostbyname_r(name, he, buffer, buflen, &res, &h_errnop) + ; return 0; } _ACEOF -rm -f conftest.$ac_objext conftest$ac_exeext -if { (ac_try="$ac_link" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" -$as_echo "$ac_try_echo") >&5 - (eval "$ac_link") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest$ac_exeext && { - test "$cross_compiling" = yes || - $as_test_x conftest$ac_exeext - }; then - eval "$as_ac_var=yes" -else - $as_echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 +if ac_fn_c_try_compile "$LINENO"; then : - eval "$as_ac_var=no" -fi + $as_echo "#define HAVE_GETHOSTBYNAME_R 1" >>confdefs.h -rm -rf conftest.dSYM -rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \ - conftest$ac_exeext conftest.$ac_ext -fi -ac_res=`eval 'as_val=${'$as_ac_var'} - $as_echo "$as_val"'` - { $as_echo "$as_me:$LINENO: result: $ac_res" >&5 -$as_echo "$ac_res" >&6; } -as_val=`eval 'as_val=${'$as_ac_var'} - $as_echo "$as_val"'` - if test "x$as_val" = x""yes; then - cat >>confdefs.h <<_ACEOF -#define `$as_echo "HAVE_$ac_func" | $as_tr_cpp` 1 -_ACEOF -fi -done +$as_echo "#define HAVE_GETHOSTBYNAME_R_6_ARG 1" >>confdefs.h + + { $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +$as_echo "yes" >&6; } -{ $as_echo "$as_me:$LINENO: checking whether isinf is declared" >&5 -$as_echo_n "checking whether isinf is declared... " >&6; } -if test "${ac_cv_have_decl_isinf+set}" = set; then - $as_echo_n "(cached) " >&6 else - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF + + { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 +$as_echo "no" >&6; } + { $as_echo "$as_me:${as_lineno-$LINENO}: checking gethostbyname_r with 5 args" >&5 +$as_echo_n "checking gethostbyname_r with 5 args... " >&6; } + cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ -#include + +# include int main () { -#ifndef isinf - (void) isinf; -#endif + + char *name; + struct hostent *he; + char buffer[2048]; + int buflen = 2048; + int h_errnop; + + (void) gethostbyname_r(name, he, buffer, buflen, &h_errnop) ; return 0; } _ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" -$as_echo "$ac_try_echo") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - ac_cv_have_decl_isinf=yes -else - $as_echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 +if ac_fn_c_try_compile "$LINENO"; then : - ac_cv_have_decl_isinf=no -fi + $as_echo "#define HAVE_GETHOSTBYNAME_R 1" >>confdefs.h -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext -fi -{ $as_echo "$as_me:$LINENO: result: $ac_cv_have_decl_isinf" >&5 -$as_echo "$ac_cv_have_decl_isinf" >&6; } -if test "x$ac_cv_have_decl_isinf" = x""yes; then -cat >>confdefs.h <<_ACEOF -#define HAVE_DECL_ISINF 1 -_ACEOF +$as_echo "#define HAVE_GETHOSTBYNAME_R_5_ARG 1" >>confdefs.h + { $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +$as_echo "yes" >&6; } else - cat >>confdefs.h <<_ACEOF -#define HAVE_DECL_ISINF 0 -_ACEOF - -fi -{ $as_echo "$as_me:$LINENO: checking whether isnan is declared" >&5 -$as_echo_n "checking whether isnan is declared... " >&6; } -if test "${ac_cv_have_decl_isnan+set}" = set; then - $as_echo_n "(cached) " >&6 -else - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF + { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 +$as_echo "no" >&6; } + { $as_echo "$as_me:${as_lineno-$LINENO}: checking gethostbyname_r with 3 args" >&5 +$as_echo_n "checking gethostbyname_r with 3 args... " >&6; } + cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ -#include + +# include int main () { -#ifndef isnan - (void) isnan; -#endif + + char *name; + struct hostent *he; + struct hostent_data data; + + (void) gethostbyname_r(name, he, &data); ; return 0; } _ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" -$as_echo "$ac_try_echo") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - ac_cv_have_decl_isnan=yes +if ac_fn_c_try_compile "$LINENO"; then : + + $as_echo "#define HAVE_GETHOSTBYNAME_R 1" >>confdefs.h + + +$as_echo "#define HAVE_GETHOSTBYNAME_R_3_ARG 1" >>confdefs.h + + { $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +$as_echo "yes" >&6; } + else - $as_echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - ac_cv_have_decl_isnan=no -fi + { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 +$as_echo "no" >&6; } -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext fi -{ $as_echo "$as_me:$LINENO: result: $ac_cv_have_decl_isnan" >&5 -$as_echo "$ac_cv_have_decl_isnan" >&6; } -if test "x$ac_cv_have_decl_isnan" = x""yes; then +rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext -cat >>confdefs.h <<_ACEOF -#define HAVE_DECL_ISNAN 1 -_ACEOF +fi +rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext +fi +rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext + CFLAGS=$OLD_CFLAGS else + + for ac_func in gethostbyname +do : + ac_fn_c_check_func "$LINENO" "gethostbyname" "ac_cv_func_gethostbyname" +if test "x$ac_cv_func_gethostbyname" = x""yes; then : cat >>confdefs.h <<_ACEOF -#define HAVE_DECL_ISNAN 0 +#define HAVE_GETHOSTBYNAME 1 _ACEOF +fi +done + fi -{ $as_echo "$as_me:$LINENO: checking whether isfinite is declared" >&5 -$as_echo_n "checking whether isfinite is declared... " >&6; } -if test "${ac_cv_have_decl_isfinite+set}" = set; then + + + + + + + +# checks for system services +# (none yet) + +# Linux requires this for correct f.p. operations +ac_fn_c_check_func "$LINENO" "__fpu_control" "ac_cv_func___fpu_control" +if test "x$ac_cv_func___fpu_control" = x""yes; then : + +else + { $as_echo "$as_me:${as_lineno-$LINENO}: checking for __fpu_control in -lieee" >&5 +$as_echo_n "checking for __fpu_control in -lieee... " >&6; } +if test "${ac_cv_lib_ieee___fpu_control+set}" = set; then : $as_echo_n "(cached) " >&6 else - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF + ac_check_lib_save_LIBS=$LIBS +LIBS="-lieee $LIBS" +cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ -#include +/* Override any GCC internal prototype to avoid an error. + Use char because int might match the return type of a GCC + builtin and then its argument prototype would still apply. */ +#ifdef __cplusplus +extern "C" +#endif +char __fpu_control (); int main () { -#ifndef isfinite - (void) isfinite; -#endif - +return __fpu_control (); ; return 0; } _ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" -$as_echo "$ac_try_echo") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - ac_cv_have_decl_isfinite=yes +if ac_fn_c_try_link "$LINENO"; then : + ac_cv_lib_ieee___fpu_control=yes else - $as_echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - ac_cv_have_decl_isfinite=no + ac_cv_lib_ieee___fpu_control=no fi - -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext +rm -f core conftest.err conftest.$ac_objext \ + conftest$ac_exeext conftest.$ac_ext +LIBS=$ac_check_lib_save_LIBS fi -{ $as_echo "$as_me:$LINENO: result: $ac_cv_have_decl_isfinite" >&5 -$as_echo "$ac_cv_have_decl_isfinite" >&6; } -if test "x$ac_cv_have_decl_isfinite" = x""yes; then - -cat >>confdefs.h <<_ACEOF -#define HAVE_DECL_ISFINITE 1 +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_lib_ieee___fpu_control" >&5 +$as_echo "$ac_cv_lib_ieee___fpu_control" >&6; } +if test "x$ac_cv_lib_ieee___fpu_control" = x""yes; then : + cat >>confdefs.h <<_ACEOF +#define HAVE_LIBIEEE 1 _ACEOF + LIBS="-lieee $LIBS" -else - cat >>confdefs.h <<_ACEOF -#define HAVE_DECL_ISFINITE 0 -_ACEOF +fi fi +# Check for --with-fpectl +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for --with-fpectl" >&5 +$as_echo_n "checking for --with-fpectl... " >&6; } -LIBS=$LIBS_SAVE +# Check whether --with-fpectl was given. +if test "${with_fpectl+set}" = set; then : + withval=$with_fpectl; +if test "$withval" != no +then -# check for wchar.h -if test "${ac_cv_header_wchar_h+set}" = set; then - { $as_echo "$as_me:$LINENO: checking for wchar.h" >&5 -$as_echo_n "checking for wchar.h... " >&6; } -if test "${ac_cv_header_wchar_h+set}" = set; then - $as_echo_n "(cached) " >&6 +$as_echo "#define WANT_SIGFPE_HANDLER 1" >>confdefs.h + + { $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +$as_echo "yes" >&6; } +else { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 +$as_echo "no" >&6; } fi -{ $as_echo "$as_me:$LINENO: result: $ac_cv_header_wchar_h" >&5 -$as_echo "$ac_cv_header_wchar_h" >&6; } -else - # Is the header compilable? -{ $as_echo "$as_me:$LINENO: checking wchar.h usability" >&5 -$as_echo_n "checking wchar.h usability... " >&6; } -cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -$ac_includes_default -#include -_ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" -$as_echo "$ac_try_echo") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - ac_header_compiler=yes else - $as_echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - ac_header_compiler=no + { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 +$as_echo "no" >&6; } fi -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext -{ $as_echo "$as_me:$LINENO: result: $ac_header_compiler" >&5 -$as_echo "$ac_header_compiler" >&6; } -# Is the header present? -{ $as_echo "$as_me:$LINENO: checking wchar.h presence" >&5 -$as_echo_n "checking wchar.h presence... " >&6; } -cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -#include -_ACEOF -if { (ac_try="$ac_cpp conftest.$ac_ext" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; +# check for --with-libm=... + +case $ac_sys_system in +Darwin) ;; +BeOS) ;; +*) LIBM=-lm esac -eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" -$as_echo "$ac_try_echo") >&5 - (eval "$ac_cpp conftest.$ac_ext") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } >/dev/null && { - test -z "$ac_c_preproc_warn_flag$ac_c_werror_flag" || - test ! -s conftest.err - }; then - ac_header_preproc=yes -else - $as_echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for --with-libm=STRING" >&5 +$as_echo_n "checking for --with-libm=STRING... " >&6; } - ac_header_preproc=no +# Check whether --with-libm was given. +if test "${with_libm+set}" = set; then : + withval=$with_libm; +if test "$withval" = no +then LIBM= + { $as_echo "$as_me:${as_lineno-$LINENO}: result: force LIBM empty" >&5 +$as_echo "force LIBM empty" >&6; } +elif test "$withval" != yes +then LIBM=$withval + { $as_echo "$as_me:${as_lineno-$LINENO}: result: set LIBM=\"$withval\"" >&5 +$as_echo "set LIBM=\"$withval\"" >&6; } +else as_fn_error "proper usage is --with-libm=STRING" "$LINENO" 5 fi - -rm -f conftest.err conftest.$ac_ext -{ $as_echo "$as_me:$LINENO: result: $ac_header_preproc" >&5 -$as_echo "$ac_header_preproc" >&6; } - -# So? What about this header? -case $ac_header_compiler:$ac_header_preproc:$ac_c_preproc_warn_flag in - yes:no: ) - { $as_echo "$as_me:$LINENO: WARNING: wchar.h: accepted by the compiler, rejected by the preprocessor!" >&5 -$as_echo "$as_me: WARNING: wchar.h: accepted by the compiler, rejected by the preprocessor!" >&2;} - { $as_echo "$as_me:$LINENO: WARNING: wchar.h: proceeding with the compiler's result" >&5 -$as_echo "$as_me: WARNING: wchar.h: proceeding with the compiler's result" >&2;} - ac_header_preproc=yes - ;; - no:yes:* ) - { $as_echo "$as_me:$LINENO: WARNING: wchar.h: present but cannot be compiled" >&5 -$as_echo "$as_me: WARNING: wchar.h: present but cannot be compiled" >&2;} - { $as_echo "$as_me:$LINENO: WARNING: wchar.h: check for missing prerequisite headers?" >&5 -$as_echo "$as_me: WARNING: wchar.h: check for missing prerequisite headers?" >&2;} - { $as_echo "$as_me:$LINENO: WARNING: wchar.h: see the Autoconf documentation" >&5 -$as_echo "$as_me: WARNING: wchar.h: see the Autoconf documentation" >&2;} - { $as_echo "$as_me:$LINENO: WARNING: wchar.h: section \"Present But Cannot Be Compiled\"" >&5 -$as_echo "$as_me: WARNING: wchar.h: section \"Present But Cannot Be Compiled\"" >&2;} - { $as_echo "$as_me:$LINENO: WARNING: wchar.h: proceeding with the preprocessor's result" >&5 -$as_echo "$as_me: WARNING: wchar.h: proceeding with the preprocessor's result" >&2;} - { $as_echo "$as_me:$LINENO: WARNING: wchar.h: in the future, the compiler will take precedence" >&5 -$as_echo "$as_me: WARNING: wchar.h: in the future, the compiler will take precedence" >&2;} - ( cat <<\_ASBOX -## ------------------------------------------------ ## -## Report this to http://www.python.org/python-bugs ## -## ------------------------------------------------ ## -_ASBOX - ) | sed "s/^/$as_me: WARNING: /" >&2 - ;; -esac -{ $as_echo "$as_me:$LINENO: checking for wchar.h" >&5 -$as_echo_n "checking for wchar.h... " >&6; } -if test "${ac_cv_header_wchar_h+set}" = set; then - $as_echo_n "(cached) " >&6 else - ac_cv_header_wchar_h=$ac_header_preproc -fi -{ $as_echo "$as_me:$LINENO: result: $ac_cv_header_wchar_h" >&5 -$as_echo "$ac_cv_header_wchar_h" >&6; } - + { $as_echo "$as_me:${as_lineno-$LINENO}: result: default LIBM=\"$LIBM\"" >&5 +$as_echo "default LIBM=\"$LIBM\"" >&6; } fi -if test "x$ac_cv_header_wchar_h" = x""yes; then -cat >>confdefs.h <<\_ACEOF -#define HAVE_WCHAR_H 1 -_ACEOF +# check for --with-libc=... - wchar_h="yes" +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for --with-libc=STRING" >&5 +$as_echo_n "checking for --with-libc=STRING... " >&6; } +# Check whether --with-libc was given. +if test "${with_libc+set}" = set; then : + withval=$with_libc; +if test "$withval" = no +then LIBC= + { $as_echo "$as_me:${as_lineno-$LINENO}: result: force LIBC empty" >&5 +$as_echo "force LIBC empty" >&6; } +elif test "$withval" != yes +then LIBC=$withval + { $as_echo "$as_me:${as_lineno-$LINENO}: result: set LIBC=\"$withval\"" >&5 +$as_echo "set LIBC=\"$withval\"" >&6; } +else as_fn_error "proper usage is --with-libc=STRING" "$LINENO" 5 +fi else - wchar_h="no" - + { $as_echo "$as_me:${as_lineno-$LINENO}: result: default LIBC=\"$LIBC\"" >&5 +$as_echo "default LIBC=\"$LIBC\"" >&6; } fi +# ************************************ +# * Check for mathematical functions * +# ************************************ -# determine wchar_t size -if test "$wchar_h" = yes -then - # The cast to long int works around a bug in the HP C Compiler -# version HP92453-01 B.11.11.23709.GP, which incorrectly rejects -# declarations like `int a3[[(sizeof (unsigned char)) >= 0]];'. -# This bug is HP SR number 8606223364. -{ $as_echo "$as_me:$LINENO: checking size of wchar_t" >&5 -$as_echo_n "checking size of wchar_t... " >&6; } -if test "${ac_cv_sizeof_wchar_t+set}" = set; then +LIBS_SAVE=$LIBS +LIBS="$LIBS $LIBM" + +# Detect whether system arithmetic is subject to x87-style double +# rounding issues. The result of this test has little meaning on non +# IEEE 754 platforms. On IEEE 754, test should return 1 if rounding +# mode is round-to-nearest and double rounding issues are present, and +# 0 otherwise. See http://bugs.python.org/issue2937 for more info. +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for x87-style double rounding" >&5 +$as_echo_n "checking for x87-style double rounding... " >&6; } +if test "${ac_cv_x87_double_rounding+set}" = set; then : $as_echo_n "(cached) " >&6 else - if test "$cross_compiling" = yes; then - # Depending upon the size, compute the lo and hi bounds. -cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -#include -int -main () -{ -static int test_array [1 - 2 * !(((long int) (sizeof (wchar_t))) >= 0)]; -test_array [0] = 0 - - ; - return 0; -} -_ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" -$as_echo "$ac_try_echo") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - ac_lo=0 ac_mid=0 - while :; do - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF +if test "$cross_compiling" = yes; then : + ac_cv_x87_double_rounding=no +else + cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ -#include - -int -main () -{ -static int test_array [1 - 2 * !(((long int) (sizeof (wchar_t))) <= $ac_mid)]; -test_array [0] = 0 - ; - return 0; +#include +#include +int main() { + volatile double x, y, z; + /* 1./(1-2**-53) -> 1+2**-52 (correct), 1.0 (double rounding) */ + x = 0.99999999999999989; /* 1-2**-53 */ + y = 1./x; + if (y != 1.) + exit(0); + /* 1e16+2.99999 -> 1e16+2. (correct), 1e16+4. (double rounding) */ + x = 1e16; + y = 2.99999; + z = x + y; + if (z != 1e16+4.) + exit(0); + /* both tests show evidence of double rounding */ + exit(1); } + _ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" -$as_echo "$ac_try_echo") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - ac_hi=$ac_mid; break +if ac_fn_c_try_run "$LINENO"; then : + ac_cv_x87_double_rounding=no else - $as_echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 + ac_cv_x87_double_rounding=yes +fi +rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext \ + conftest.$ac_objext conftest.beam conftest.$ac_ext +fi + +fi + +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_x87_double_rounding" >&5 +$as_echo "$ac_cv_x87_double_rounding" >&6; } +if test "$ac_cv_x87_double_rounding" = yes +then + +$as_echo "#define X87_DOUBLE_ROUNDING 1" >>confdefs.h - ac_lo=`expr $ac_mid + 1` - if test $ac_lo -le $ac_mid; then - ac_lo= ac_hi= - break - fi - ac_mid=`expr 2 '*' $ac_mid + 1` fi -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext - done + +# On FreeBSD 6.2, it appears that tanh(-0.) returns 0. instead of +# -0. on some architectures. +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking whether tanh preserves the sign of zero" >&5 +$as_echo_n "checking whether tanh preserves the sign of zero... " >&6; } +if test "${ac_cv_tanh_preserves_zero_sign+set}" = set; then : + $as_echo_n "(cached) " >&6 else - $as_echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF +if test "$cross_compiling" = yes; then : + ac_cv_tanh_preserves_zero_sign=no +else + cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ -#include - -int -main () -{ -static int test_array [1 - 2 * !(((long int) (sizeof (wchar_t))) < 0)]; -test_array [0] = 0 - ; - return 0; +#include +#include +int main() { + /* return 0 if either negative zeros don't exist + on this platform or if negative zeros exist + and tanh(-0.) == -0. */ + if (atan2(0., -1.) == atan2(-0., -1.) || + atan2(tanh(-0.), -1.) == atan2(-0., -1.)) exit(0); + else exit(1); } -_ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" -$as_echo "$ac_try_echo") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - ac_hi=-1 ac_mid=-1 - while :; do - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -#include - -int -main () -{ -static int test_array [1 - 2 * !(((long int) (sizeof (wchar_t))) >= $ac_mid)]; -test_array [0] = 0 - ; - return 0; -} _ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" -$as_echo "$ac_try_echo") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - ac_lo=$ac_mid; break +if ac_fn_c_try_run "$LINENO"; then : + ac_cv_tanh_preserves_zero_sign=yes else - $as_echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 + ac_cv_tanh_preserves_zero_sign=no +fi +rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext \ + conftest.$ac_objext conftest.beam conftest.$ac_ext +fi - ac_hi=`expr '(' $ac_mid ')' - 1` - if test $ac_mid -le $ac_hi; then - ac_lo= ac_hi= - break - fi - ac_mid=`expr 2 '*' $ac_mid` fi -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext - done -else - $as_echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_tanh_preserves_zero_sign" >&5 +$as_echo "$ac_cv_tanh_preserves_zero_sign" >&6; } +if test "$ac_cv_tanh_preserves_zero_sign" = yes +then - ac_lo= ac_hi= -fi +$as_echo "#define TANH_PRESERVES_ZERO_SIGN 1" >>confdefs.h -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext fi -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext -# Binary search between lo and hi bounds. -while test "x$ac_lo" != "x$ac_hi"; do - ac_mid=`expr '(' $ac_hi - $ac_lo ')' / 2 + $ac_lo` - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ +for ac_func in acosh asinh atanh copysign expm1 finite hypot log1p +do : + as_ac_var=`$as_echo "ac_cv_func_$ac_func" | $as_tr_sh` +ac_fn_c_check_func "$LINENO" "$ac_func" "$as_ac_var" +eval as_val=\$$as_ac_var + if test "x$as_val" = x""yes; then : + cat >>confdefs.h <<_ACEOF +#define `$as_echo "HAVE_$ac_func" | $as_tr_cpp` 1 _ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -#include -int -main () -{ -static int test_array [1 - 2 * !(((long int) (sizeof (wchar_t))) <= $ac_mid)]; -test_array [0] = 0 +fi +done - ; - return 0; -} -_ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" -$as_echo "$ac_try_echo") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - ac_hi=$ac_mid +ac_fn_c_check_decl "$LINENO" "isinf" "ac_cv_have_decl_isinf" "#include +" +if test "x$ac_cv_have_decl_isinf" = x""yes; then : + ac_have_decl=1 else - $as_echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 + ac_have_decl=0 +fi - ac_lo=`expr '(' $ac_mid ')' + 1` +cat >>confdefs.h <<_ACEOF +#define HAVE_DECL_ISINF $ac_have_decl +_ACEOF +ac_fn_c_check_decl "$LINENO" "isnan" "ac_cv_have_decl_isnan" "#include +" +if test "x$ac_cv_have_decl_isnan" = x""yes; then : + ac_have_decl=1 +else + ac_have_decl=0 fi -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext -done -case $ac_lo in -?*) ac_cv_sizeof_wchar_t=$ac_lo;; -'') if test "$ac_cv_type_wchar_t" = yes; then - { { $as_echo "$as_me:$LINENO: error: in \`$ac_pwd':" >&5 -$as_echo "$as_me: error: in \`$ac_pwd':" >&2;} -{ { $as_echo "$as_me:$LINENO: error: cannot compute sizeof (wchar_t) -See \`config.log' for more details." >&5 -$as_echo "$as_me: error: cannot compute sizeof (wchar_t) -See \`config.log' for more details." >&2;} - { (exit 77); exit 77; }; }; } - else - ac_cv_sizeof_wchar_t=0 - fi ;; -esac +cat >>confdefs.h <<_ACEOF +#define HAVE_DECL_ISNAN $ac_have_decl +_ACEOF +ac_fn_c_check_decl "$LINENO" "isfinite" "ac_cv_have_decl_isfinite" "#include +" +if test "x$ac_cv_have_decl_isfinite" = x""yes; then : + ac_have_decl=1 else - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ + ac_have_decl=0 +fi + +cat >>confdefs.h <<_ACEOF +#define HAVE_DECL_ISFINITE $ac_have_decl _ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -#include -static long int longval () { return (long int) (sizeof (wchar_t)); } -static unsigned long int ulongval () { return (long int) (sizeof (wchar_t)); } -#include -#include -int -main () -{ - FILE *f = fopen ("conftest.val", "w"); - if (! f) - return 1; - if (((long int) (sizeof (wchar_t))) < 0) - { - long int i = longval (); - if (i != ((long int) (sizeof (wchar_t)))) - return 1; - fprintf (f, "%ld", i); - } - else - { - unsigned long int i = ulongval (); - if (i != ((long int) (sizeof (wchar_t)))) - return 1; - fprintf (f, "%lu", i); - } - /* Do not output a trailing newline, as this causes \r\n confusion - on some platforms. */ - return ferror (f) || fclose (f) != 0; +LIBS=$LIBS_SAVE + +# check for wchar.h +ac_fn_c_check_header_mongrel "$LINENO" "wchar.h" "ac_cv_header_wchar_h" "$ac_includes_default" +if test "x$ac_cv_header_wchar_h" = x""yes; then : + + +$as_echo "#define HAVE_WCHAR_H 1" >>confdefs.h + + wchar_h="yes" - ; - return 0; -} -_ACEOF -rm -f conftest$ac_exeext -if { (ac_try="$ac_link" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" -$as_echo "$ac_try_echo") >&5 - (eval "$ac_link") 2>&5 - ac_status=$? - $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { ac_try='./conftest$ac_exeext' - { (case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" -$as_echo "$ac_try_echo") >&5 - (eval "$ac_try") 2>&5 - ac_status=$? - $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); }; }; then - ac_cv_sizeof_wchar_t=`cat conftest.val` else - $as_echo "$as_me: program exited with status $ac_status" >&5 -$as_echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 + wchar_h="no" -( exit $ac_status ) -if test "$ac_cv_type_wchar_t" = yes; then - { { $as_echo "$as_me:$LINENO: error: in \`$ac_pwd':" >&5 +fi + + + +# determine wchar_t size +if test "$wchar_h" = yes +then + # The cast to long int works around a bug in the HP C Compiler +# version HP92453-01 B.11.11.23709.GP, which incorrectly rejects +# declarations like `int a3[[(sizeof (unsigned char)) >= 0]];'. +# This bug is HP SR number 8606223364. +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking size of wchar_t" >&5 +$as_echo_n "checking size of wchar_t... " >&6; } +if test "${ac_cv_sizeof_wchar_t+set}" = set; then : + $as_echo_n "(cached) " >&6 +else + if ac_fn_c_compute_int "$LINENO" "(long int) (sizeof (wchar_t))" "ac_cv_sizeof_wchar_t" "#include +"; then : + +else + if test "$ac_cv_type_wchar_t" = yes; then + { { $as_echo "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5 $as_echo "$as_me: error: in \`$ac_pwd':" >&2;} -{ { $as_echo "$as_me:$LINENO: error: cannot compute sizeof (wchar_t) -See \`config.log' for more details." >&5 -$as_echo "$as_me: error: cannot compute sizeof (wchar_t) -See \`config.log' for more details." >&2;} - { (exit 77); exit 77; }; }; } +{ as_fn_set_status 77 +as_fn_error "cannot compute sizeof (wchar_t) +See \`config.log' for more details." "$LINENO" 5; }; } else ac_cv_sizeof_wchar_t=0 fi fi -rm -rf conftest.dSYM -rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext conftest.$ac_objext conftest.$ac_ext -fi -rm -f conftest.val + fi -{ $as_echo "$as_me:$LINENO: result: $ac_cv_sizeof_wchar_t" >&5 +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_sizeof_wchar_t" >&5 $as_echo "$ac_cv_sizeof_wchar_t" >&6; } @@ -23471,14 +11484,10 @@ fi -{ $as_echo "$as_me:$LINENO: checking for UCS-4 tcl" >&5 +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for UCS-4 tcl" >&5 $as_echo_n "checking for UCS-4 tcl... " >&6; } have_ucs4_tcl=no -cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF +cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ #include @@ -23493,61 +11502,32 @@ return 0; } _ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" -$as_echo "$ac_try_echo") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then +if ac_fn_c_try_compile "$LINENO"; then : -cat >>confdefs.h <<\_ACEOF -#define HAVE_UCS4_TCL 1 -_ACEOF +$as_echo "#define HAVE_UCS4_TCL 1" >>confdefs.h have_ucs4_tcl=yes -else - $as_echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - fi - rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext -{ $as_echo "$as_me:$LINENO: result: $have_ucs4_tcl" >&5 +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $have_ucs4_tcl" >&5 $as_echo "$have_ucs4_tcl" >&6; } # check whether wchar_t is signed or not if test "$wchar_h" = yes then # check whether wchar_t is signed or not - { $as_echo "$as_me:$LINENO: checking whether wchar_t is signed" >&5 + { $as_echo "$as_me:${as_lineno-$LINENO}: checking whether wchar_t is signed" >&5 $as_echo_n "checking whether wchar_t is signed... " >&6; } - if test "${ac_cv_wchar_t_signed+set}" = set; then + if test "${ac_cv_wchar_t_signed+set}" = set; then : $as_echo_n "(cached) " >&6 else - if test "$cross_compiling" = yes; then + if test "$cross_compiling" = yes; then : ac_cv_wchar_t_signed=yes else - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF + cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ #include @@ -23558,52 +11538,25 @@ } _ACEOF -rm -f conftest$ac_exeext -if { (ac_try="$ac_link" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" -$as_echo "$ac_try_echo") >&5 - (eval "$ac_link") 2>&5 - ac_status=$? - $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { ac_try='./conftest$ac_exeext' - { (case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" -$as_echo "$ac_try_echo") >&5 - (eval "$ac_try") 2>&5 - ac_status=$? - $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); }; }; then +if ac_fn_c_try_run "$LINENO"; then : ac_cv_wchar_t_signed=yes else - $as_echo "$as_me: program exited with status $ac_status" >&5 -$as_echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - -( exit $ac_status ) -ac_cv_wchar_t_signed=no + ac_cv_wchar_t_signed=no fi -rm -rf conftest.dSYM -rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext conftest.$ac_objext conftest.$ac_ext +rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext \ + conftest.$ac_objext conftest.beam conftest.$ac_ext fi - fi - { $as_echo "$as_me:$LINENO: result: $ac_cv_wchar_t_signed" >&5 + { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_wchar_t_signed" >&5 $as_echo "$ac_cv_wchar_t_signed" >&6; } fi -{ $as_echo "$as_me:$LINENO: checking what type to use for unicode" >&5 +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking what type to use for unicode" >&5 $as_echo_n "checking what type to use for unicode... " >&6; } # Check whether --enable-unicode was given. -if test "${enable_unicode+set}" = set; then +if test "${enable_unicode+set}" = set; then : enableval=$enable_unicode; else enable_unicode=yes @@ -23622,40 +11575,30 @@ fi - case "$enable_unicode" in ucs2) unicode_size="2" - cat >>confdefs.h <<\_ACEOF -#define Py_UNICODE_SIZE 2 -_ACEOF + $as_echo "#define Py_UNICODE_SIZE 2" >>confdefs.h ;; ucs4) unicode_size="4" - cat >>confdefs.h <<\_ACEOF -#define Py_UNICODE_SIZE 4 -_ACEOF + $as_echo "#define Py_UNICODE_SIZE 4" >>confdefs.h ;; -*) { { $as_echo "$as_me:$LINENO: error: invalid value for --enable-unicode. Use either ucs2 or ucs4 (lowercase)." >&5 -$as_echo "$as_me: error: invalid value for --enable-unicode. Use either ucs2 or ucs4 (lowercase)." >&2;} - { (exit 1); exit 1; }; } ;; +*) as_fn_error "invalid value for --enable-unicode. Use either ucs2 or ucs4 (lowercase)." "$LINENO" 5 ;; esac - if test "$enable_unicode" = "no" then UNICODE_OBJS="" - { $as_echo "$as_me:$LINENO: result: not used" >&5 + { $as_echo "$as_me:${as_lineno-$LINENO}: result: not used" >&5 $as_echo "not used" >&6; } else UNICODE_OBJS="Objects/unicodeobject.o Objects/unicodectype.o" -cat >>confdefs.h <<\_ACEOF -#define Py_USING_UNICODE 1 -_ACEOF +$as_echo "#define Py_USING_UNICODE 1" >>confdefs.h # wchar_t is only usable if it maps to an unsigned type @@ -23664,96 +11607,71 @@ then PY_UNICODE_TYPE="wchar_t" -cat >>confdefs.h <<\_ACEOF -#define HAVE_USABLE_WCHAR_T 1 -_ACEOF +$as_echo "#define HAVE_USABLE_WCHAR_T 1" >>confdefs.h - cat >>confdefs.h <<\_ACEOF -#define PY_UNICODE_TYPE wchar_t -_ACEOF + $as_echo "#define PY_UNICODE_TYPE wchar_t" >>confdefs.h elif test "$ac_cv_sizeof_short" = "$unicode_size" then PY_UNICODE_TYPE="unsigned short" - cat >>confdefs.h <<\_ACEOF -#define PY_UNICODE_TYPE unsigned short -_ACEOF + $as_echo "#define PY_UNICODE_TYPE unsigned short" >>confdefs.h elif test "$ac_cv_sizeof_long" = "$unicode_size" then PY_UNICODE_TYPE="unsigned long" - cat >>confdefs.h <<\_ACEOF -#define PY_UNICODE_TYPE unsigned long -_ACEOF + $as_echo "#define PY_UNICODE_TYPE unsigned long" >>confdefs.h else PY_UNICODE_TYPE="no type found" fi - { $as_echo "$as_me:$LINENO: result: $PY_UNICODE_TYPE" >&5 + { $as_echo "$as_me:${as_lineno-$LINENO}: result: $PY_UNICODE_TYPE" >&5 $as_echo "$PY_UNICODE_TYPE" >&6; } fi # check for endianness - - { $as_echo "$as_me:$LINENO: checking whether byte ordering is bigendian" >&5 + { $as_echo "$as_me:${as_lineno-$LINENO}: checking whether byte ordering is bigendian" >&5 $as_echo_n "checking whether byte ordering is bigendian... " >&6; } -if test "${ac_cv_c_bigendian+set}" = set; then +if test "${ac_cv_c_bigendian+set}" = set; then : $as_echo_n "(cached) " >&6 else ac_cv_c_bigendian=unknown # See if we're dealing with a universal compiler. - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF + cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ #ifndef __APPLE_CC__ not a universal capable compiler - #endif - typedef int dummy; - -_ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" -$as_echo "$ac_try_echo") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - - # Check for potential -arch flags. It is not universal unless - # there are some -arch flags. Note that *ppc* also matches - # ppc64. This check is also rather less than ideal. - case "${CC} ${CFLAGS} ${CPPFLAGS} ${LDFLAGS}" in #( - *-arch*ppc*|*-arch*i386*|*-arch*x86_64*) ac_cv_c_bigendian=universal;; - esac -else - $as_echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 + #endif + typedef int dummy; +_ACEOF +if ac_fn_c_try_compile "$LINENO"; then : + # Check for potential -arch flags. It is not universal unless + # there are at least two -arch flags with different values. + ac_arch= + ac_prev= + for ac_word in $CC $CFLAGS $CPPFLAGS $LDFLAGS; do + if test -n "$ac_prev"; then + case $ac_word in + i?86 | x86_64 | ppc | ppc64) + if test -z "$ac_arch" || test "$ac_arch" = "$ac_word"; then + ac_arch=$ac_word + else + ac_cv_c_bigendian=universal + break + fi + ;; + esac + ac_prev= + elif test "x$ac_word" = "x-arch"; then + ac_prev=arch + fi + done fi - rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext if test $ac_cv_c_bigendian = unknown; then # See if sys/param.h defines the BYTE_ORDER macro. - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF + cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ #include #include @@ -23771,30 +11689,9 @@ return 0; } _ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" -$as_echo "$ac_try_echo") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then +if ac_fn_c_try_compile "$LINENO"; then : # It does; now see whether it defined to BIG_ENDIAN or not. - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF + cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ #include #include @@ -23810,49 +11707,18 @@ return 0; } _ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" -$as_echo "$ac_try_echo") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then +if ac_fn_c_try_compile "$LINENO"; then : ac_cv_c_bigendian=yes else - $as_echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - ac_cv_c_bigendian=no + ac_cv_c_bigendian=no fi - rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext -else - $as_echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - fi - rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext fi if test $ac_cv_c_bigendian = unknown; then # See if defines _LITTLE_ENDIAN or _BIG_ENDIAN (e.g., Solaris). - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF + cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ #include @@ -23867,30 +11733,9 @@ return 0; } _ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" -$as_echo "$ac_try_echo") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then +if ac_fn_c_try_compile "$LINENO"; then : # It does; now see whether it defined to _BIG_ENDIAN or not. - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF + cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ #include @@ -23905,51 +11750,20 @@ return 0; } _ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" -$as_echo "$ac_try_echo") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then +if ac_fn_c_try_compile "$LINENO"; then : ac_cv_c_bigendian=yes else - $as_echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - ac_cv_c_bigendian=no + ac_cv_c_bigendian=no fi - rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext -else - $as_echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - fi - rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext fi if test $ac_cv_c_bigendian = unknown; then # Compile a test program. - if test "$cross_compiling" = yes; then + if test "$cross_compiling" = yes; then : # Try to guess by grepping values from an object file. - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF + cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ short int ascii_mm[] = { 0x4249, 0x4765, 0x6E44, 0x6961, 0x6E53, 0x7953, 0 }; @@ -23975,24 +11789,7 @@ return 0; } _ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" -$as_echo "$ac_try_echo") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then +if ac_fn_c_try_compile "$LINENO"; then : if grep BIGenDianSyS conftest.$ac_objext >/dev/null; then ac_cv_c_bigendian=yes fi @@ -24004,20 +11801,10 @@ ac_cv_c_bigendian=unknown fi fi -else - $as_echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - fi - rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext else - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF + cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ $ac_includes_default int @@ -24037,86 +11824,48 @@ return 0; } _ACEOF -rm -f conftest$ac_exeext -if { (ac_try="$ac_link" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" -$as_echo "$ac_try_echo") >&5 - (eval "$ac_link") 2>&5 - ac_status=$? - $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { ac_try='./conftest$ac_exeext' - { (case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" -$as_echo "$ac_try_echo") >&5 - (eval "$ac_try") 2>&5 - ac_status=$? - $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); }; }; then +if ac_fn_c_try_run "$LINENO"; then : ac_cv_c_bigendian=no else - $as_echo "$as_me: program exited with status $ac_status" >&5 -$as_echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - -( exit $ac_status ) -ac_cv_c_bigendian=yes + ac_cv_c_bigendian=yes fi -rm -rf conftest.dSYM -rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext conftest.$ac_objext conftest.$ac_ext +rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext \ + conftest.$ac_objext conftest.beam conftest.$ac_ext fi - fi fi -{ $as_echo "$as_me:$LINENO: result: $ac_cv_c_bigendian" >&5 +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_c_bigendian" >&5 $as_echo "$ac_cv_c_bigendian" >&6; } case $ac_cv_c_bigendian in #( yes) - cat >>confdefs.h <<\_ACEOF -#define WORDS_BIGENDIAN 1 -_ACEOF + $as_echo "#define WORDS_BIGENDIAN 1" >>confdefs.h ;; #( no) ;; #( universal) -cat >>confdefs.h <<\_ACEOF -#define AC_APPLE_UNIVERSAL_BUILD 1 -_ACEOF +$as_echo "#define AC_APPLE_UNIVERSAL_BUILD 1" >>confdefs.h ;; #( *) - { { $as_echo "$as_me:$LINENO: error: unknown endianness - presetting ac_cv_c_bigendian=no (or yes) will help" >&5 -$as_echo "$as_me: error: unknown endianness - presetting ac_cv_c_bigendian=no (or yes) will help" >&2;} - { (exit 1); exit 1; }; } ;; + as_fn_error "unknown endianness + presetting ac_cv_c_bigendian=no (or yes) will help" "$LINENO" 5 ;; esac # Check whether right shifting a negative integer extends the sign bit # or fills with zeros (like the Cray J90, according to Tim Peters). -{ $as_echo "$as_me:$LINENO: checking whether right shift extends the sign bit" >&5 +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking whether right shift extends the sign bit" >&5 $as_echo_n "checking whether right shift extends the sign bit... " >&6; } -if test "${ac_cv_rshift_extends_sign+set}" = set; then +if test "${ac_cv_rshift_extends_sign+set}" = set; then : $as_echo_n "(cached) " >&6 else -if test "$cross_compiling" = yes; then +if test "$cross_compiling" = yes; then : ac_cv_rshift_extends_sign=yes else - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF + cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ int main() @@ -24125,67 +11874,34 @@ } _ACEOF -rm -f conftest$ac_exeext -if { (ac_try="$ac_link" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" -$as_echo "$ac_try_echo") >&5 - (eval "$ac_link") 2>&5 - ac_status=$? - $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { ac_try='./conftest$ac_exeext' - { (case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" -$as_echo "$ac_try_echo") >&5 - (eval "$ac_try") 2>&5 - ac_status=$? - $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); }; }; then +if ac_fn_c_try_run "$LINENO"; then : ac_cv_rshift_extends_sign=yes else - $as_echo "$as_me: program exited with status $ac_status" >&5 -$as_echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - -( exit $ac_status ) -ac_cv_rshift_extends_sign=no + ac_cv_rshift_extends_sign=no fi -rm -rf conftest.dSYM -rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext conftest.$ac_objext conftest.$ac_ext +rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext \ + conftest.$ac_objext conftest.beam conftest.$ac_ext fi - fi -{ $as_echo "$as_me:$LINENO: result: $ac_cv_rshift_extends_sign" >&5 +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_rshift_extends_sign" >&5 $as_echo "$ac_cv_rshift_extends_sign" >&6; } if test "$ac_cv_rshift_extends_sign" = no then -cat >>confdefs.h <<\_ACEOF -#define SIGNED_RIGHT_SHIFT_ZERO_FILLS 1 -_ACEOF +$as_echo "#define SIGNED_RIGHT_SHIFT_ZERO_FILLS 1" >>confdefs.h fi # check for getc_unlocked and related locking functions -{ $as_echo "$as_me:$LINENO: checking for getc_unlocked() and friends" >&5 +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for getc_unlocked() and friends" >&5 $as_echo_n "checking for getc_unlocked() and friends... " >&6; } -if test "${ac_cv_have_getc_unlocked+set}" = set; then +if test "${ac_cv_have_getc_unlocked+set}" = set; then : $as_echo_n "(cached) " >&6 else -cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF +cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ #include int @@ -24201,48 +11917,21 @@ return 0; } _ACEOF -rm -f conftest.$ac_objext conftest$ac_exeext -if { (ac_try="$ac_link" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" -$as_echo "$ac_try_echo") >&5 - (eval "$ac_link") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest$ac_exeext && { - test "$cross_compiling" = yes || - $as_test_x conftest$ac_exeext - }; then +if ac_fn_c_try_link "$LINENO"; then : ac_cv_have_getc_unlocked=yes else - $as_echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - ac_cv_have_getc_unlocked=no + ac_cv_have_getc_unlocked=no fi - -rm -rf conftest.dSYM -rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \ - conftest$ac_exeext conftest.$ac_ext +rm -f core conftest.err conftest.$ac_objext \ + conftest$ac_exeext conftest.$ac_ext fi -{ $as_echo "$as_me:$LINENO: result: $ac_cv_have_getc_unlocked" >&5 +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_have_getc_unlocked" >&5 $as_echo "$ac_cv_have_getc_unlocked" >&6; } if test "$ac_cv_have_getc_unlocked" = yes then -cat >>confdefs.h <<\_ACEOF -#define HAVE_GETC_UNLOCKED 1 -_ACEOF +$as_echo "#define HAVE_GETC_UNLOCKED 1" >>confdefs.h fi @@ -24254,7 +11943,7 @@ # library. NOTE: Keep the precedence of listed libraries synchronised # with setup.py. py_cv_lib_readline=no -{ $as_echo "$as_me:$LINENO: checking how to link readline libs" >&5 +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking how to link readline libs" >&5 $as_echo_n "checking how to link readline libs... " >&6; } for py_libtermcap in "" ncursesw ncurses curses termcap; do if test -z "$py_libtermcap"; then @@ -24263,11 +11952,7 @@ READLINE_LIBS="-lreadline -l$py_libtermcap" fi LIBS="$READLINE_LIBS $LIBS_no_readline" - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF + cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ /* Override any GCC internal prototype to avoid an error. @@ -24285,38 +11970,11 @@ return 0; } _ACEOF -rm -f conftest.$ac_objext conftest$ac_exeext -if { (ac_try="$ac_link" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" -$as_echo "$ac_try_echo") >&5 - (eval "$ac_link") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest$ac_exeext && { - test "$cross_compiling" = yes || - $as_test_x conftest$ac_exeext - }; then +if ac_fn_c_try_link "$LINENO"; then : py_cv_lib_readline=yes -else - $as_echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - fi - -rm -rf conftest.dSYM -rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \ - conftest$ac_exeext conftest.$ac_ext +rm -f core conftest.err conftest.$ac_objext \ + conftest$ac_exeext conftest.$ac_ext if test $py_cv_lib_readline = yes; then break fi @@ -24324,31 +11982,25 @@ # Uncomment this line if you want to use READINE_LIBS in Makefile or scripts #AC_SUBST([READLINE_LIBS]) if test $py_cv_lib_readline = no; then - { $as_echo "$as_me:$LINENO: result: none" >&5 + { $as_echo "$as_me:${as_lineno-$LINENO}: result: none" >&5 $as_echo "none" >&6; } else - { $as_echo "$as_me:$LINENO: result: $READLINE_LIBS" >&5 + { $as_echo "$as_me:${as_lineno-$LINENO}: result: $READLINE_LIBS" >&5 $as_echo "$READLINE_LIBS" >&6; } -cat >>confdefs.h <<\_ACEOF -#define HAVE_LIBREADLINE 1 -_ACEOF +$as_echo "#define HAVE_LIBREADLINE 1" >>confdefs.h fi # check for readline 2.1 -{ $as_echo "$as_me:$LINENO: checking for rl_callback_handler_install in -lreadline" >&5 +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for rl_callback_handler_install in -lreadline" >&5 $as_echo_n "checking for rl_callback_handler_install in -lreadline... " >&6; } -if test "${ac_cv_lib_readline_rl_callback_handler_install+set}" = set; then +if test "${ac_cv_lib_readline_rl_callback_handler_install+set}" = set; then : $as_echo_n "(cached) " >&6 else ac_check_lib_save_LIBS=$LIBS LIBS="-lreadline $READLINE_LIBS $LIBS" -cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF +cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ /* Override any GCC internal prototype to avoid an error. @@ -24366,122 +12018,59 @@ return 0; } _ACEOF -rm -f conftest.$ac_objext conftest$ac_exeext -if { (ac_try="$ac_link" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" -$as_echo "$ac_try_echo") >&5 - (eval "$ac_link") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest$ac_exeext && { - test "$cross_compiling" = yes || - $as_test_x conftest$ac_exeext - }; then +if ac_fn_c_try_link "$LINENO"; then : ac_cv_lib_readline_rl_callback_handler_install=yes else - $as_echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - ac_cv_lib_readline_rl_callback_handler_install=no + ac_cv_lib_readline_rl_callback_handler_install=no fi - -rm -rf conftest.dSYM -rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \ - conftest$ac_exeext conftest.$ac_ext +rm -f core conftest.err conftest.$ac_objext \ + conftest$ac_exeext conftest.$ac_ext LIBS=$ac_check_lib_save_LIBS fi -{ $as_echo "$as_me:$LINENO: result: $ac_cv_lib_readline_rl_callback_handler_install" >&5 +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_lib_readline_rl_callback_handler_install" >&5 $as_echo "$ac_cv_lib_readline_rl_callback_handler_install" >&6; } -if test "x$ac_cv_lib_readline_rl_callback_handler_install" = x""yes; then +if test "x$ac_cv_lib_readline_rl_callback_handler_install" = x""yes; then : -cat >>confdefs.h <<\_ACEOF -#define HAVE_RL_CALLBACK 1 -_ACEOF +$as_echo "#define HAVE_RL_CALLBACK 1" >>confdefs.h fi # check for readline 2.2 -cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF +cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ #include _ACEOF -if { (ac_try="$ac_cpp conftest.$ac_ext" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" -$as_echo "$ac_try_echo") >&5 - (eval "$ac_cpp conftest.$ac_ext") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } >/dev/null && { - test -z "$ac_c_preproc_warn_flag$ac_c_werror_flag" || - test ! -s conftest.err - }; then +if ac_fn_c_try_cpp "$LINENO"; then : have_readline=yes else - $as_echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - have_readline=no fi - rm -f conftest.err conftest.$ac_ext if test $have_readline = yes then - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF + cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ #include _ACEOF if (eval "$ac_cpp conftest.$ac_ext") 2>&5 | - $EGREP "extern int rl_completion_append_character;" >/dev/null 2>&1; then + $EGREP "extern int rl_completion_append_character;" >/dev/null 2>&1; then : -cat >>confdefs.h <<\_ACEOF -#define HAVE_RL_COMPLETION_APPEND_CHARACTER 1 -_ACEOF +$as_echo "#define HAVE_RL_COMPLETION_APPEND_CHARACTER 1" >>confdefs.h fi rm -f conftest* - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF + cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ #include _ACEOF if (eval "$ac_cpp conftest.$ac_ext") 2>&5 | - $EGREP "extern int rl_completion_suppress_append;" >/dev/null 2>&1; then + $EGREP "extern int rl_completion_suppress_append;" >/dev/null 2>&1; then : -cat >>confdefs.h <<\_ACEOF -#define HAVE_RL_COMPLETION_SUPPRESS_APPEND 1 -_ACEOF +$as_echo "#define HAVE_RL_COMPLETION_SUPPRESS_APPEND 1" >>confdefs.h fi rm -f conftest* @@ -24489,18 +12078,14 @@ fi # check for readline 4.0 -{ $as_echo "$as_me:$LINENO: checking for rl_pre_input_hook in -lreadline" >&5 +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for rl_pre_input_hook in -lreadline" >&5 $as_echo_n "checking for rl_pre_input_hook in -lreadline... " >&6; } -if test "${ac_cv_lib_readline_rl_pre_input_hook+set}" = set; then +if test "${ac_cv_lib_readline_rl_pre_input_hook+set}" = set; then : $as_echo_n "(cached) " >&6 else ac_check_lib_save_LIBS=$LIBS LIBS="-lreadline $READLINE_LIBS $LIBS" -cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF +cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ /* Override any GCC internal prototype to avoid an error. @@ -24518,64 +12103,33 @@ return 0; } _ACEOF -rm -f conftest.$ac_objext conftest$ac_exeext -if { (ac_try="$ac_link" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" -$as_echo "$ac_try_echo") >&5 - (eval "$ac_link") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest$ac_exeext && { - test "$cross_compiling" = yes || - $as_test_x conftest$ac_exeext - }; then +if ac_fn_c_try_link "$LINENO"; then : ac_cv_lib_readline_rl_pre_input_hook=yes else - $as_echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - ac_cv_lib_readline_rl_pre_input_hook=no + ac_cv_lib_readline_rl_pre_input_hook=no fi - -rm -rf conftest.dSYM -rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \ - conftest$ac_exeext conftest.$ac_ext +rm -f core conftest.err conftest.$ac_objext \ + conftest$ac_exeext conftest.$ac_ext LIBS=$ac_check_lib_save_LIBS fi -{ $as_echo "$as_me:$LINENO: result: $ac_cv_lib_readline_rl_pre_input_hook" >&5 +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_lib_readline_rl_pre_input_hook" >&5 $as_echo "$ac_cv_lib_readline_rl_pre_input_hook" >&6; } -if test "x$ac_cv_lib_readline_rl_pre_input_hook" = x""yes; then +if test "x$ac_cv_lib_readline_rl_pre_input_hook" = x""yes; then : -cat >>confdefs.h <<\_ACEOF -#define HAVE_RL_PRE_INPUT_HOOK 1 -_ACEOF +$as_echo "#define HAVE_RL_PRE_INPUT_HOOK 1" >>confdefs.h fi # also in 4.0 -{ $as_echo "$as_me:$LINENO: checking for rl_completion_display_matches_hook in -lreadline" >&5 +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for rl_completion_display_matches_hook in -lreadline" >&5 $as_echo_n "checking for rl_completion_display_matches_hook in -lreadline... " >&6; } -if test "${ac_cv_lib_readline_rl_completion_display_matches_hook+set}" = set; then +if test "${ac_cv_lib_readline_rl_completion_display_matches_hook+set}" = set; then : $as_echo_n "(cached) " >&6 else ac_check_lib_save_LIBS=$LIBS LIBS="-lreadline $READLINE_LIBS $LIBS" -cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF +cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ /* Override any GCC internal prototype to avoid an error. @@ -24593,64 +12147,33 @@ return 0; } _ACEOF -rm -f conftest.$ac_objext conftest$ac_exeext -if { (ac_try="$ac_link" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" -$as_echo "$ac_try_echo") >&5 - (eval "$ac_link") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest$ac_exeext && { - test "$cross_compiling" = yes || - $as_test_x conftest$ac_exeext - }; then +if ac_fn_c_try_link "$LINENO"; then : ac_cv_lib_readline_rl_completion_display_matches_hook=yes else - $as_echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - ac_cv_lib_readline_rl_completion_display_matches_hook=no + ac_cv_lib_readline_rl_completion_display_matches_hook=no fi - -rm -rf conftest.dSYM -rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \ - conftest$ac_exeext conftest.$ac_ext +rm -f core conftest.err conftest.$ac_objext \ + conftest$ac_exeext conftest.$ac_ext LIBS=$ac_check_lib_save_LIBS fi -{ $as_echo "$as_me:$LINENO: result: $ac_cv_lib_readline_rl_completion_display_matches_hook" >&5 +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_lib_readline_rl_completion_display_matches_hook" >&5 $as_echo "$ac_cv_lib_readline_rl_completion_display_matches_hook" >&6; } -if test "x$ac_cv_lib_readline_rl_completion_display_matches_hook" = x""yes; then +if test "x$ac_cv_lib_readline_rl_completion_display_matches_hook" = x""yes; then : -cat >>confdefs.h <<\_ACEOF -#define HAVE_RL_COMPLETION_DISPLAY_MATCHES_HOOK 1 -_ACEOF +$as_echo "#define HAVE_RL_COMPLETION_DISPLAY_MATCHES_HOOK 1" >>confdefs.h fi # check for readline 4.2 -{ $as_echo "$as_me:$LINENO: checking for rl_completion_matches in -lreadline" >&5 +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for rl_completion_matches in -lreadline" >&5 $as_echo_n "checking for rl_completion_matches in -lreadline... " >&6; } -if test "${ac_cv_lib_readline_rl_completion_matches+set}" = set; then +if test "${ac_cv_lib_readline_rl_completion_matches+set}" = set; then : $as_echo_n "(cached) " >&6 else ac_check_lib_save_LIBS=$LIBS LIBS="-lreadline $READLINE_LIBS $LIBS" -cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF +cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ /* Override any GCC internal prototype to avoid an error. @@ -24668,103 +12191,46 @@ return 0; } _ACEOF -rm -f conftest.$ac_objext conftest$ac_exeext -if { (ac_try="$ac_link" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" -$as_echo "$ac_try_echo") >&5 - (eval "$ac_link") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest$ac_exeext && { - test "$cross_compiling" = yes || - $as_test_x conftest$ac_exeext - }; then +if ac_fn_c_try_link "$LINENO"; then : ac_cv_lib_readline_rl_completion_matches=yes else - $as_echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - ac_cv_lib_readline_rl_completion_matches=no + ac_cv_lib_readline_rl_completion_matches=no fi - -rm -rf conftest.dSYM -rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \ - conftest$ac_exeext conftest.$ac_ext +rm -f core conftest.err conftest.$ac_objext \ + conftest$ac_exeext conftest.$ac_ext LIBS=$ac_check_lib_save_LIBS fi -{ $as_echo "$as_me:$LINENO: result: $ac_cv_lib_readline_rl_completion_matches" >&5 +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_lib_readline_rl_completion_matches" >&5 $as_echo "$ac_cv_lib_readline_rl_completion_matches" >&6; } -if test "x$ac_cv_lib_readline_rl_completion_matches" = x""yes; then +if test "x$ac_cv_lib_readline_rl_completion_matches" = x""yes; then : -cat >>confdefs.h <<\_ACEOF -#define HAVE_RL_COMPLETION_MATCHES 1 -_ACEOF +$as_echo "#define HAVE_RL_COMPLETION_MATCHES 1" >>confdefs.h fi # also in readline 4.2 -cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF +cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ #include _ACEOF -if { (ac_try="$ac_cpp conftest.$ac_ext" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" -$as_echo "$ac_try_echo") >&5 - (eval "$ac_cpp conftest.$ac_ext") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } >/dev/null && { - test -z "$ac_c_preproc_warn_flag$ac_c_werror_flag" || - test ! -s conftest.err - }; then +if ac_fn_c_try_cpp "$LINENO"; then : have_readline=yes else - $as_echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - have_readline=no fi - rm -f conftest.err conftest.$ac_ext if test $have_readline = yes then - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF + cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ #include _ACEOF if (eval "$ac_cpp conftest.$ac_ext") 2>&5 | - $EGREP "extern int rl_catch_signals;" >/dev/null 2>&1; then + $EGREP "extern int rl_catch_signals;" >/dev/null 2>&1; then : -cat >>confdefs.h <<\_ACEOF -#define HAVE_RL_CATCH_SIGNAL 1 -_ACEOF +$as_echo "#define HAVE_RL_CATCH_SIGNAL 1" >>confdefs.h fi rm -f conftest* @@ -24774,90 +12240,53 @@ # End of readline checks: restore LIBS LIBS=$LIBS_no_readline -{ $as_echo "$as_me:$LINENO: checking for broken nice()" >&5 +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for broken nice()" >&5 $as_echo_n "checking for broken nice()... " >&6; } -if test "${ac_cv_broken_nice+set}" = set; then +if test "${ac_cv_broken_nice+set}" = set; then : $as_echo_n "(cached) " >&6 else -if test "$cross_compiling" = yes; then +if test "$cross_compiling" = yes; then : ac_cv_broken_nice=no else - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF + cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ int main() { int val1 = nice(1); if (val1 != -1 && val1 == nice(2)) - exit(0); - exit(1); -} - -_ACEOF -rm -f conftest$ac_exeext -if { (ac_try="$ac_link" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" -$as_echo "$ac_try_echo") >&5 - (eval "$ac_link") 2>&5 - ac_status=$? - $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { ac_try='./conftest$ac_exeext' - { (case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" -$as_echo "$ac_try_echo") >&5 - (eval "$ac_try") 2>&5 - ac_status=$? - $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); }; }; then + exit(0); + exit(1); +} + +_ACEOF +if ac_fn_c_try_run "$LINENO"; then : ac_cv_broken_nice=yes else - $as_echo "$as_me: program exited with status $ac_status" >&5 -$as_echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - -( exit $ac_status ) -ac_cv_broken_nice=no + ac_cv_broken_nice=no fi -rm -rf conftest.dSYM -rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext conftest.$ac_objext conftest.$ac_ext +rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext \ + conftest.$ac_objext conftest.beam conftest.$ac_ext fi - fi -{ $as_echo "$as_me:$LINENO: result: $ac_cv_broken_nice" >&5 +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_broken_nice" >&5 $as_echo "$ac_cv_broken_nice" >&6; } if test "$ac_cv_broken_nice" = yes then -cat >>confdefs.h <<\_ACEOF -#define HAVE_BROKEN_NICE 1 -_ACEOF +$as_echo "#define HAVE_BROKEN_NICE 1" >>confdefs.h fi -{ $as_echo "$as_me:$LINENO: checking for broken poll()" >&5 +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for broken poll()" >&5 $as_echo_n "checking for broken poll()... " >&6; } -if test "$cross_compiling" = yes; then +if test "$cross_compiling" = yes; then : ac_cv_broken_poll=no else - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF + cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ #include @@ -24885,158 +12314,32 @@ } _ACEOF -rm -f conftest$ac_exeext -if { (ac_try="$ac_link" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" -$as_echo "$ac_try_echo") >&5 - (eval "$ac_link") 2>&5 - ac_status=$? - $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { ac_try='./conftest$ac_exeext' - { (case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" -$as_echo "$ac_try_echo") >&5 - (eval "$ac_try") 2>&5 - ac_status=$? - $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); }; }; then +if ac_fn_c_try_run "$LINENO"; then : ac_cv_broken_poll=yes else - $as_echo "$as_me: program exited with status $ac_status" >&5 -$as_echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - -( exit $ac_status ) -ac_cv_broken_poll=no + ac_cv_broken_poll=no fi -rm -rf conftest.dSYM -rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext conftest.$ac_objext conftest.$ac_ext +rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext \ + conftest.$ac_objext conftest.beam conftest.$ac_ext fi - -{ $as_echo "$as_me:$LINENO: result: $ac_cv_broken_poll" >&5 +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_broken_poll" >&5 $as_echo "$ac_cv_broken_poll" >&6; } if test "$ac_cv_broken_poll" = yes then -cat >>confdefs.h <<\_ACEOF -#define HAVE_BROKEN_POLL 1 -_ACEOF +$as_echo "#define HAVE_BROKEN_POLL 1" >>confdefs.h 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[] -{ $as_echo "$as_me:$LINENO: checking for struct tm.tm_zone" >&5 -$as_echo_n "checking for struct tm.tm_zone... " >&6; } -if test "${ac_cv_member_struct_tm_tm_zone+set}" = set; then - $as_echo_n "(cached) " >&6 -else - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -#include -#include <$ac_cv_struct_tm> - - -int -main () -{ -static struct tm ac_aggr; -if (ac_aggr.tm_zone) -return 0; - ; - return 0; -} -_ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" -$as_echo "$ac_try_echo") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - ac_cv_member_struct_tm_tm_zone=yes -else - $as_echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -#include +ac_fn_c_check_member "$LINENO" "struct tm" "tm_zone" "ac_cv_member_struct_tm_tm_zone" "#include #include <$ac_cv_struct_tm> - -int -main () -{ -static struct tm ac_aggr; -if (sizeof ac_aggr.tm_zone) -return 0; - ; - return 0; -} -_ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" -$as_echo "$ac_try_echo") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - ac_cv_member_struct_tm_tm_zone=yes -else - $as_echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - ac_cv_member_struct_tm_tm_zone=no -fi - -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext -fi - -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext -fi -{ $as_echo "$as_me:$LINENO: result: $ac_cv_member_struct_tm_tm_zone" >&5 -$as_echo "$ac_cv_member_struct_tm_tm_zone" >&6; } -if test "x$ac_cv_member_struct_tm_tm_zone" = x""yes; then +" +if test "x$ac_cv_member_struct_tm_tm_zone" = x""yes; then : cat >>confdefs.h <<_ACEOF #define HAVE_STRUCT_TM_TM_ZONE 1 @@ -25047,91 +12350,27 @@ if test "$ac_cv_member_struct_tm_tm_zone" = yes; then -cat >>confdefs.h <<\_ACEOF -#define HAVE_TM_ZONE 1 -_ACEOF +$as_echo "#define HAVE_TM_ZONE 1" >>confdefs.h else - { $as_echo "$as_me:$LINENO: checking whether tzname is declared" >&5 -$as_echo_n "checking whether tzname is declared... " >&6; } -if test "${ac_cv_have_decl_tzname+set}" = set; then - $as_echo_n "(cached) " >&6 -else - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -#include - -int -main () -{ -#ifndef tzname - (void) tzname; -#endif - - ; - return 0; -} -_ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" -$as_echo "$ac_try_echo") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - ac_cv_have_decl_tzname=yes + ac_fn_c_check_decl "$LINENO" "tzname" "ac_cv_have_decl_tzname" "#include +" +if test "x$ac_cv_have_decl_tzname" = x""yes; then : + ac_have_decl=1 else - $as_echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - ac_cv_have_decl_tzname=no + ac_have_decl=0 fi -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext -fi -{ $as_echo "$as_me:$LINENO: result: $ac_cv_have_decl_tzname" >&5 -$as_echo "$ac_cv_have_decl_tzname" >&6; } -if test "x$ac_cv_have_decl_tzname" = x""yes; then - cat >>confdefs.h <<_ACEOF -#define HAVE_DECL_TZNAME 1 -_ACEOF - - -else - cat >>confdefs.h <<_ACEOF -#define HAVE_DECL_TZNAME 0 +#define HAVE_DECL_TZNAME $ac_have_decl _ACEOF - -fi - - - { $as_echo "$as_me:$LINENO: checking for tzname" >&5 + { $as_echo "$as_me:${as_lineno-$LINENO}: checking for tzname" >&5 $as_echo_n "checking for tzname... " >&6; } -if test "${ac_cv_var_tzname+set}" = set; then +if test "${ac_cv_var_tzname+set}" = set; then : $as_echo_n "(cached) " >&6 else - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF + cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ #include #if !HAVE_DECL_TZNAME @@ -25146,66 +12385,35 @@ return 0; } _ACEOF -rm -f conftest.$ac_objext conftest$ac_exeext -if { (ac_try="$ac_link" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" -$as_echo "$ac_try_echo") >&5 - (eval "$ac_link") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest$ac_exeext && { - test "$cross_compiling" = yes || - $as_test_x conftest$ac_exeext - }; then +if ac_fn_c_try_link "$LINENO"; then : ac_cv_var_tzname=yes else - $as_echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - ac_cv_var_tzname=no + ac_cv_var_tzname=no fi - -rm -rf conftest.dSYM -rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \ - conftest$ac_exeext conftest.$ac_ext +rm -f core conftest.err conftest.$ac_objext \ + conftest$ac_exeext conftest.$ac_ext fi -{ $as_echo "$as_me:$LINENO: result: $ac_cv_var_tzname" >&5 +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_var_tzname" >&5 $as_echo "$ac_cv_var_tzname" >&6; } if test $ac_cv_var_tzname = yes; then -cat >>confdefs.h <<\_ACEOF -#define HAVE_TZNAME 1 -_ACEOF +$as_echo "#define HAVE_TZNAME 1" >>confdefs.h fi fi # check tzset(3) exists and works like we expect it to -{ $as_echo "$as_me:$LINENO: checking for working tzset()" >&5 +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for working tzset()" >&5 $as_echo_n "checking for working tzset()... " >&6; } -if test "${ac_cv_working_tzset+set}" = set; then +if test "${ac_cv_working_tzset+set}" = set; then : $as_echo_n "(cached) " >&6 else -if test "$cross_compiling" = yes; then +if test "$cross_compiling" = yes; then : ac_cv_working_tzset=no else - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF + cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ #include @@ -25272,66 +12480,33 @@ } _ACEOF -rm -f conftest$ac_exeext -if { (ac_try="$ac_link" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" -$as_echo "$ac_try_echo") >&5 - (eval "$ac_link") 2>&5 - ac_status=$? - $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { ac_try='./conftest$ac_exeext' - { (case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" -$as_echo "$ac_try_echo") >&5 - (eval "$ac_try") 2>&5 - ac_status=$? - $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); }; }; then +if ac_fn_c_try_run "$LINENO"; then : ac_cv_working_tzset=yes else - $as_echo "$as_me: program exited with status $ac_status" >&5 -$as_echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - -( exit $ac_status ) -ac_cv_working_tzset=no + ac_cv_working_tzset=no fi -rm -rf conftest.dSYM -rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext conftest.$ac_objext conftest.$ac_ext +rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext \ + conftest.$ac_objext conftest.beam conftest.$ac_ext fi - fi -{ $as_echo "$as_me:$LINENO: result: $ac_cv_working_tzset" >&5 +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_working_tzset" >&5 $as_echo "$ac_cv_working_tzset" >&6; } if test "$ac_cv_working_tzset" = yes then -cat >>confdefs.h <<\_ACEOF -#define HAVE_WORKING_TZSET 1 -_ACEOF +$as_echo "#define HAVE_WORKING_TZSET 1" >>confdefs.h fi # Look for subsecond timestamps in struct stat -{ $as_echo "$as_me:$LINENO: checking for tv_nsec in struct stat" >&5 +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for tv_nsec in struct stat" >&5 $as_echo_n "checking for tv_nsec in struct stat... " >&6; } -if test "${ac_cv_stat_tv_nsec+set}" = set; then +if test "${ac_cv_stat_tv_nsec+set}" = set; then : $as_echo_n "(cached) " >&6 else - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF + cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ #include int @@ -25345,57 +12520,30 @@ return 0; } _ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" -$as_echo "$ac_try_echo") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then +if ac_fn_c_try_compile "$LINENO"; then : ac_cv_stat_tv_nsec=yes else - $as_echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - ac_cv_stat_tv_nsec=no + ac_cv_stat_tv_nsec=no fi - rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext fi -{ $as_echo "$as_me:$LINENO: result: $ac_cv_stat_tv_nsec" >&5 +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_stat_tv_nsec" >&5 $as_echo "$ac_cv_stat_tv_nsec" >&6; } if test "$ac_cv_stat_tv_nsec" = yes then -cat >>confdefs.h <<\_ACEOF -#define HAVE_STAT_TV_NSEC 1 -_ACEOF +$as_echo "#define HAVE_STAT_TV_NSEC 1" >>confdefs.h fi # Look for BSD style subsecond timestamps in struct stat -{ $as_echo "$as_me:$LINENO: checking for tv_nsec2 in struct stat" >&5 +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for tv_nsec2 in struct stat" >&5 $as_echo_n "checking for tv_nsec2 in struct stat... " >&6; } -if test "${ac_cv_stat_tv_nsec2+set}" = set; then +if test "${ac_cv_stat_tv_nsec2+set}" = set; then : $as_echo_n "(cached) " >&6 else - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF + cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ #include int @@ -25409,57 +12557,30 @@ return 0; } _ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" -$as_echo "$ac_try_echo") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then +if ac_fn_c_try_compile "$LINENO"; then : ac_cv_stat_tv_nsec2=yes else - $as_echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - ac_cv_stat_tv_nsec2=no + ac_cv_stat_tv_nsec2=no fi - rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext fi -{ $as_echo "$as_me:$LINENO: result: $ac_cv_stat_tv_nsec2" >&5 +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_stat_tv_nsec2" >&5 $as_echo "$ac_cv_stat_tv_nsec2" >&6; } if test "$ac_cv_stat_tv_nsec2" = yes then -cat >>confdefs.h <<\_ACEOF -#define HAVE_STAT_TV_NSEC2 1 -_ACEOF +$as_echo "#define HAVE_STAT_TV_NSEC2 1" >>confdefs.h fi # On HP/UX 11.0, mvwdelch is a block with a return statement -{ $as_echo "$as_me:$LINENO: checking whether mvwdelch is an expression" >&5 +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking whether mvwdelch is an expression" >&5 $as_echo_n "checking whether mvwdelch is an expression... " >&6; } -if test "${ac_cv_mvwdelch_is_expression+set}" = set; then +if test "${ac_cv_mvwdelch_is_expression+set}" = set; then : $as_echo_n "(cached) " >&6 else - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF + cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ #include int @@ -25473,57 +12594,30 @@ return 0; } _ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" -$as_echo "$ac_try_echo") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then +if ac_fn_c_try_compile "$LINENO"; then : ac_cv_mvwdelch_is_expression=yes else - $as_echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - ac_cv_mvwdelch_is_expression=no + ac_cv_mvwdelch_is_expression=no fi - rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext fi -{ $as_echo "$as_me:$LINENO: result: $ac_cv_mvwdelch_is_expression" >&5 +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_mvwdelch_is_expression" >&5 $as_echo "$ac_cv_mvwdelch_is_expression" >&6; } if test "$ac_cv_mvwdelch_is_expression" = yes then -cat >>confdefs.h <<\_ACEOF -#define MVWDELCH_IS_EXPRESSION 1 -_ACEOF +$as_echo "#define MVWDELCH_IS_EXPRESSION 1" >>confdefs.h fi -{ $as_echo "$as_me:$LINENO: checking whether WINDOW has _flags" >&5 +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking whether WINDOW has _flags" >&5 $as_echo_n "checking whether WINDOW has _flags... " >&6; } -if test "${ac_cv_window_has_flags+set}" = set; then +if test "${ac_cv_window_has_flags+set}" = set; then : $as_echo_n "(cached) " >&6 else - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF + cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ #include int @@ -25537,55 +12631,28 @@ return 0; } _ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" -$as_echo "$ac_try_echo") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then +if ac_fn_c_try_compile "$LINENO"; then : ac_cv_window_has_flags=yes else - $as_echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - ac_cv_window_has_flags=no + ac_cv_window_has_flags=no fi - rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext fi -{ $as_echo "$as_me:$LINENO: result: $ac_cv_window_has_flags" >&5 +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_window_has_flags" >&5 $as_echo "$ac_cv_window_has_flags" >&6; } if test "$ac_cv_window_has_flags" = yes then -cat >>confdefs.h <<\_ACEOF -#define WINDOW_HAS_FLAGS 1 -_ACEOF +$as_echo "#define WINDOW_HAS_FLAGS 1" >>confdefs.h fi -{ $as_echo "$as_me:$LINENO: checking for is_term_resized" >&5 +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for is_term_resized" >&5 $as_echo_n "checking for is_term_resized... " >&6; } -cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF +cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ #include int @@ -25596,49 +12663,22 @@ return 0; } _ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" -$as_echo "$ac_try_echo") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then +if ac_fn_c_try_compile "$LINENO"; then : -cat >>confdefs.h <<\_ACEOF -#define HAVE_CURSES_IS_TERM_RESIZED 1 -_ACEOF +$as_echo "#define HAVE_CURSES_IS_TERM_RESIZED 1" >>confdefs.h - { $as_echo "$as_me:$LINENO: result: yes" >&5 + { $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5 $as_echo "yes" >&6; } else - $as_echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - { $as_echo "$as_me:$LINENO: result: no" >&5 + { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 $as_echo "no" >&6; } fi - rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext -{ $as_echo "$as_me:$LINENO: checking for resize_term" >&5 +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for resize_term" >&5 $as_echo_n "checking for resize_term... " >&6; } -cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF +cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ #include int @@ -25649,49 +12689,22 @@ return 0; } _ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" -$as_echo "$ac_try_echo") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then +if ac_fn_c_try_compile "$LINENO"; then : -cat >>confdefs.h <<\_ACEOF -#define HAVE_CURSES_RESIZE_TERM 1 -_ACEOF +$as_echo "#define HAVE_CURSES_RESIZE_TERM 1" >>confdefs.h - { $as_echo "$as_me:$LINENO: result: yes" >&5 + { $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5 $as_echo "yes" >&6; } else - $as_echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - { $as_echo "$as_me:$LINENO: result: no" >&5 + { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 $as_echo "no" >&6; } fi - rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext -{ $as_echo "$as_me:$LINENO: checking for resizeterm" >&5 +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for resizeterm" >&5 $as_echo_n "checking for resizeterm... " >&6; } -cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF +cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ #include int @@ -25702,92 +12715,58 @@ return 0; } _ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" -$as_echo "$ac_try_echo") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then +if ac_fn_c_try_compile "$LINENO"; then : -cat >>confdefs.h <<\_ACEOF -#define HAVE_CURSES_RESIZETERM 1 -_ACEOF +$as_echo "#define HAVE_CURSES_RESIZETERM 1" >>confdefs.h - { $as_echo "$as_me:$LINENO: result: yes" >&5 + { $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5 $as_echo "yes" >&6; } else - $as_echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - { $as_echo "$as_me:$LINENO: result: no" >&5 + { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 $as_echo "no" >&6; } fi - rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext -{ $as_echo "$as_me:$LINENO: checking for /dev/ptmx" >&5 +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for /dev/ptmx" >&5 $as_echo_n "checking for /dev/ptmx... " >&6; } if test -r /dev/ptmx then - { $as_echo "$as_me:$LINENO: result: yes" >&5 + { $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5 $as_echo "yes" >&6; } -cat >>confdefs.h <<\_ACEOF -#define HAVE_DEV_PTMX 1 -_ACEOF +$as_echo "#define HAVE_DEV_PTMX 1" >>confdefs.h else - { $as_echo "$as_me:$LINENO: result: no" >&5 + { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 $as_echo "no" >&6; } fi -{ $as_echo "$as_me:$LINENO: checking for /dev/ptc" >&5 +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for /dev/ptc" >&5 $as_echo_n "checking for /dev/ptc... " >&6; } if test -r /dev/ptc then - { $as_echo "$as_me:$LINENO: result: yes" >&5 + { $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5 $as_echo "yes" >&6; } -cat >>confdefs.h <<\_ACEOF -#define HAVE_DEV_PTC 1 -_ACEOF +$as_echo "#define HAVE_DEV_PTC 1" >>confdefs.h else - { $as_echo "$as_me:$LINENO: result: no" >&5 + { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 $as_echo "no" >&6; } fi -{ $as_echo "$as_me:$LINENO: checking for %zd printf() format support" >&5 +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for %zd printf() format support" >&5 $as_echo_n "checking for %zd printf() format support... " >&6; } -if test "$cross_compiling" = yes; then - { { $as_echo "$as_me:$LINENO: error: in \`$ac_pwd':" >&5 +if test "$cross_compiling" = yes; then : + { { $as_echo "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5 $as_echo "$as_me: error: in \`$ac_pwd':" >&2;} -{ { $as_echo "$as_me:$LINENO: error: cannot run test program while cross compiling -See \`config.log' for more details." >&5 -$as_echo "$as_me: error: cannot run test program while cross compiling -See \`config.log' for more details." >&2;} - { (exit 1); exit 1; }; }; } +as_fn_error "cannot run test program while cross compiling +See \`config.log' for more details." "$LINENO" 5; } else - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF + cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ #include #include @@ -25824,105 +12803,22 @@ return 0; } _ACEOF -rm -f conftest$ac_exeext -if { (ac_try="$ac_link" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" -$as_echo "$ac_try_echo") >&5 - (eval "$ac_link") 2>&5 - ac_status=$? - $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { ac_try='./conftest$ac_exeext' - { (case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" -$as_echo "$ac_try_echo") >&5 - (eval "$ac_try") 2>&5 - ac_status=$? - $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); }; }; then - { $as_echo "$as_me:$LINENO: result: yes" >&5 +if ac_fn_c_try_run "$LINENO"; then : + { $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5 $as_echo "yes" >&6; } -cat >>confdefs.h <<\_ACEOF -#define PY_FORMAT_SIZE_T "z" -_ACEOF +$as_echo "#define PY_FORMAT_SIZE_T \"z\"" >>confdefs.h else - $as_echo "$as_me: program exited with status $ac_status" >&5 -$as_echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - -( exit $ac_status ) -{ $as_echo "$as_me:$LINENO: result: no" >&5 + { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 $as_echo "no" >&6; } fi -rm -rf conftest.dSYM -rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext conftest.$ac_objext conftest.$ac_ext +rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext \ + conftest.$ac_objext conftest.beam conftest.$ac_ext fi - -{ $as_echo "$as_me:$LINENO: checking for socklen_t" >&5 -$as_echo_n "checking for socklen_t... " >&6; } -if test "${ac_cv_type_socklen_t+set}" = set; then - $as_echo_n "(cached) " >&6 -else - ac_cv_type_socklen_t=no -cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ - -#ifdef HAVE_SYS_TYPES_H -#include -#endif -#ifdef HAVE_SYS_SOCKET_H -#include -#endif - - -int -main () -{ -if (sizeof (socklen_t)) - return 0; - ; - return 0; -} -_ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" -$as_echo "$ac_try_echo") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ - +ac_fn_c_check_type "$LINENO" "socklen_t" "ac_cv_type_socklen_t" " #ifdef HAVE_SYS_TYPES_H #include #endif @@ -25930,61 +12826,12 @@ #include #endif +" +if test "x$ac_cv_type_socklen_t" = x""yes; then : -int -main () -{ -if (sizeof ((socklen_t))) - return 0; - ; - return 0; -} -_ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" -$as_echo "$ac_try_echo") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - : -else - $as_echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - ac_cv_type_socklen_t=yes -fi - -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext -else - $as_echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - -fi - -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext -fi -{ $as_echo "$as_me:$LINENO: result: $ac_cv_type_socklen_t" >&5 -$as_echo "$ac_cv_type_socklen_t" >&6; } -if test "x$ac_cv_type_socklen_t" = x""yes; then - : else -cat >>confdefs.h <<\_ACEOF -#define socklen_t int -_ACEOF +$as_echo "#define socklen_t int" >>confdefs.h fi @@ -26005,14 +12852,14 @@ SRCDIRS="Parser Grammar Objects Python Modules Mac" -{ $as_echo "$as_me:$LINENO: checking for build directories" >&5 +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for build directories" >&5 $as_echo_n "checking for build directories... " >&6; } for dir in $SRCDIRS; do if test ! -d $dir; then mkdir $dir fi done -{ $as_echo "$as_me:$LINENO: result: done" >&5 +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: done" >&5 $as_echo "done" >&6; } # generate output files @@ -26045,13 +12892,13 @@ case $ac_val in #( *${as_nl}*) case $ac_var in #( - *_cv_*) { $as_echo "$as_me:$LINENO: WARNING: cache variable $ac_var contains a newline" >&5 + *_cv_*) { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: cache variable $ac_var contains a newline" >&5 $as_echo "$as_me: WARNING: cache variable $ac_var contains a newline" >&2;} ;; esac case $ac_var in #( _ | IFS | as_nl) ;; #( BASH_ARGV | BASH_SOURCE) eval $ac_var= ;; #( - *) $as_unset $ac_var ;; + *) { eval $ac_var=; unset $ac_var;} ;; esac ;; esac done @@ -26059,8 +12906,8 @@ (set) 2>&1 | case $as_nl`(ac_space=' '; set) 2>&1` in #( *${as_nl}ac_space=\ *) - # `set' does not quote correctly, so add quotes (double-quote - # substitution turns \\\\ into \\, and sed turns \\ into \). + # `set' does not quote correctly, so add quotes: double-quote + # substitution turns \\\\ into \\, and sed turns \\ into \. sed -n \ "s/'/'\\\\''/g; s/^\\([_$as_cr_alnum]*_cv_[_$as_cr_alnum]*\\)=\\(.*\\)/\\1='\\2'/p" @@ -26083,11 +12930,11 @@ if diff "$cache_file" confcache >/dev/null 2>&1; then :; else if test -w "$cache_file"; then test "x$cache_file" != "x/dev/null" && - { $as_echo "$as_me:$LINENO: updating cache $cache_file" >&5 + { $as_echo "$as_me:${as_lineno-$LINENO}: updating cache $cache_file" >&5 $as_echo "$as_me: updating cache $cache_file" >&6;} cat confcache >$cache_file else - { $as_echo "$as_me:$LINENO: not updating unwritable cache $cache_file" >&5 + { $as_echo "$as_me:${as_lineno-$LINENO}: not updating unwritable cache $cache_file" >&5 $as_echo "$as_me: not updating unwritable cache $cache_file" >&6;} fi fi @@ -26107,8 +12954,8 @@ ac_i=`$as_echo "$ac_i" | sed "$ac_script"` # 2. Prepend LIBOBJDIR. When used with automake>=1.10 LIBOBJDIR # will be set to the directory where LIBOBJS objects are built. - ac_libobjs="$ac_libobjs \${LIBOBJDIR}$ac_i\$U.$ac_objext" - ac_ltlibobjs="$ac_ltlibobjs \${LIBOBJDIR}$ac_i"'$U.lo' + as_fn_append ac_libobjs " \${LIBOBJDIR}$ac_i\$U.$ac_objext" + as_fn_append ac_ltlibobjs " \${LIBOBJDIR}$ac_i"'$U.lo' done LIBOBJS=$ac_libobjs @@ -26121,9 +12968,10 @@ ac_write_fail=0 ac_clean_files_save=$ac_clean_files ac_clean_files="$ac_clean_files $CONFIG_STATUS" -{ $as_echo "$as_me:$LINENO: creating $CONFIG_STATUS" >&5 +{ $as_echo "$as_me:${as_lineno-$LINENO}: creating $CONFIG_STATUS" >&5 $as_echo "$as_me: creating $CONFIG_STATUS" >&6;} -cat >$CONFIG_STATUS <<_ACEOF || ac_write_fail=1 +as_write_fail=0 +cat >$CONFIG_STATUS <<_ASEOF || as_write_fail=1 #! $SHELL # Generated by $as_me. # Run this file to recreate the current configuration. @@ -26133,17 +12981,18 @@ debug=false ac_cs_recheck=false ac_cs_silent=false -SHELL=\${CONFIG_SHELL-$SHELL} -_ACEOF -cat >>$CONFIG_STATUS <<\_ACEOF || ac_write_fail=1 -## --------------------- ## -## M4sh Initialization. ## -## --------------------- ## +SHELL=\${CONFIG_SHELL-$SHELL} +export SHELL +_ASEOF +cat >>$CONFIG_STATUS <<\_ASEOF || as_write_fail=1 +## -------------------- ## +## M4sh Initialization. ## +## -------------------- ## # Be more Bourne compatible DUALCASE=1; export DUALCASE # for MKS sh -if test -n "${ZSH_VERSION+set}" && (emulate sh) >/dev/null 2>&1; then +if test -n "${ZSH_VERSION+set}" && (emulate sh) >/dev/null 2>&1; then : emulate sh NULLCMD=: # Pre-4.2 versions of Zsh do word splitting on ${1+"$@"}, which @@ -26151,23 +13000,15 @@ alias -g '${1+"$@"}'='"$@"' setopt NO_GLOB_SUBST else - case `(set -o) 2>/dev/null` in - *posix*) set -o posix ;; + case `(set -o) 2>/dev/null` in #( + *posix*) : + set -o posix ;; #( + *) : + ;; esac - fi - - -# PATH needs CR -# Avoid depending upon Character Ranges. -as_cr_letters='abcdefghijklmnopqrstuvwxyz' -as_cr_LETTERS='ABCDEFGHIJKLMNOPQRSTUVWXYZ' -as_cr_Letters=$as_cr_letters$as_cr_LETTERS -as_cr_digits='0123456789' -as_cr_alnum=$as_cr_Letters$as_cr_digits - as_nl=' ' export as_nl @@ -26175,7 +13016,13 @@ as_echo='\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\' as_echo=$as_echo$as_echo$as_echo$as_echo$as_echo as_echo=$as_echo$as_echo$as_echo$as_echo$as_echo$as_echo -if (test "X`printf %s $as_echo`" = "X$as_echo") 2>/dev/null; then +# Prefer a ksh shell builtin over an external printf program on Solaris, +# but without wasting forks for bash or zsh. +if test -z "$BASH_VERSION$ZSH_VERSION" \ + && (test "X`print -r -- $as_echo`" = "X$as_echo") 2>/dev/null; then + as_echo='print -r --' + as_echo_n='print -rn --' +elif (test "X`printf %s $as_echo`" = "X$as_echo") 2>/dev/null; then as_echo='printf %s\n' as_echo_n='printf %s' else @@ -26186,7 +13033,7 @@ as_echo_body='eval expr "X$1" : "X\\(.*\\)"' as_echo_n_body='eval arg=$1; - case $arg in + case $arg in #( *"$as_nl"*) expr "X$arg" : "X\\(.*\\)$as_nl"; arg=`expr "X$arg" : ".*$as_nl\\(.*\\)"`;; @@ -26209,13 +13056,6 @@ } fi -# Support unset when possible. -if ( (MAIL=60; unset MAIL) || exit) >/dev/null 2>&1; then - as_unset=unset -else - as_unset=false -fi - # IFS # We need space, tab and new line, in precisely that order. Quoting is @@ -26225,15 +13065,15 @@ IFS=" "" $as_nl" # Find who we are. Look in the path if we contain no directory separator. -case $0 in +case $0 in #(( *[\\/]* ) as_myself=$0 ;; *) as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $PATH do IFS=$as_save_IFS test -z "$as_dir" && as_dir=. - test -r "$as_dir/$0" && as_myself=$as_dir/$0 && break -done + test -r "$as_dir/$0" && as_myself=$as_dir/$0 && break + done IFS=$as_save_IFS ;; @@ -26245,12 +13085,16 @@ fi if test ! -f "$as_myself"; then $as_echo "$as_myself: error: cannot find myself; rerun with an absolute file name" >&2 - { (exit 1); exit 1; } + exit 1 fi -# Work around bugs in pre-3.0 UWIN ksh. -for as_var in ENV MAIL MAILPATH -do ($as_unset $as_var) >/dev/null 2>&1 && $as_unset $as_var +# Unset variables that we do not need and which cause bugs (e.g. in +# pre-3.0 UWIN ksh). But do not cause bugs in bash 2.01; the "|| exit 1" +# suppresses any "Segmentation fault" message there. '((' could +# trigger a bug in pdksh 5.2.14. +for as_var in BASH_ENV ENV MAIL MAILPATH +do eval test x\${$as_var+set} = xset \ + && ( (unset $as_var) || exit 1) >/dev/null 2>&1 && unset $as_var || : done PS1='$ ' PS2='> ' @@ -26262,7 +13106,89 @@ LANGUAGE=C export LANGUAGE -# Required to use basename. +# CDPATH. +(unset CDPATH) >/dev/null 2>&1 && unset CDPATH + + +# as_fn_error ERROR [LINENO LOG_FD] +# --------------------------------- +# Output "`basename $0`: error: ERROR" to stderr. If LINENO and LOG_FD are +# provided, also output the error to LOG_FD, referencing LINENO. Then exit the +# script with status $?, using 1 if that was 0. +as_fn_error () +{ + as_status=$?; test $as_status -eq 0 && as_status=1 + if test "$3"; then + as_lineno=${as_lineno-"$2"} as_lineno_stack=as_lineno_stack=$as_lineno_stack + $as_echo "$as_me:${as_lineno-$LINENO}: error: $1" >&$3 + fi + $as_echo "$as_me: error: $1" >&2 + as_fn_exit $as_status +} # as_fn_error + + +# as_fn_set_status STATUS +# ----------------------- +# Set $? to STATUS, without forking. +as_fn_set_status () +{ + return $1 +} # as_fn_set_status + +# as_fn_exit STATUS +# ----------------- +# Exit the shell with STATUS, even in a "trap 0" or "set -e" context. +as_fn_exit () +{ + set +e + as_fn_set_status $1 + exit $1 +} # as_fn_exit + +# as_fn_unset VAR +# --------------- +# Portably unset VAR. +as_fn_unset () +{ + { eval $1=; unset $1;} +} +as_unset=as_fn_unset +# as_fn_append VAR VALUE +# ---------------------- +# Append the text in VALUE to the end of the definition contained in VAR. Take +# advantage of any shell optimizations that allow amortized linear growth over +# repeated appends, instead of the typical quadratic growth present in naive +# implementations. +if (eval "as_var=1; as_var+=2; test x\$as_var = x12") 2>/dev/null; then : + eval 'as_fn_append () + { + eval $1+=\$2 + }' +else + as_fn_append () + { + eval $1=\$$1\$2 + } +fi # as_fn_append + +# as_fn_arith ARG... +# ------------------ +# Perform arithmetic evaluation on the ARGs, and store the result in the +# global $as_val. Take advantage of shells that can avoid forks. The arguments +# must be portable across $(()) and expr. +if (eval "test \$(( 1 + 1 )) = 2") 2>/dev/null; then : + eval 'as_fn_arith () + { + as_val=$(( $* )) + }' +else + as_fn_arith () + { + as_val=`expr "$@" || test $? -eq 1` + } +fi # as_fn_arith + + if expr a : '\(a\)' >/dev/null 2>&1 && test "X`expr 00001 : '.*\(...\)'`" = X001; then as_expr=expr @@ -26276,8 +13202,12 @@ as_basename=false fi +if (as_dir=`dirname -- /` && test "X$as_dir" = X/) >/dev/null 2>&1; then + as_dirname=dirname +else + as_dirname=false +fi -# Name of the executable. as_me=`$as_basename -- "$0" || $as_expr X/"$0" : '.*/\([^/][^/]*\)/*$' \| \ X"$0" : 'X\(//\)$' \| \ @@ -26297,76 +13227,25 @@ } s/.*/./; q'` -# CDPATH. -$as_unset CDPATH - - - - as_lineno_1=$LINENO - as_lineno_2=$LINENO - test "x$as_lineno_1" != "x$as_lineno_2" && - test "x`expr $as_lineno_1 + 1`" = "x$as_lineno_2" || { - - # Create $as_me.lineno as a copy of $as_myself, but with $LINENO - # uniformly replaced by the line number. The first 'sed' inserts a - # line-number line after each line using $LINENO; the second 'sed' - # does the real work. The second script uses 'N' to pair each - # line-number line with the line containing $LINENO, and appends - # trailing '-' during substitution so that $LINENO is not a special - # case at line end. - # (Raja R Harinath suggested sed '=', and Paul Eggert wrote the - # scripts with optimization help from Paolo Bonzini. Blame Lee - # E. McMahon (1931-1989) for sed's syntax. :-) - sed -n ' - p - /[$]LINENO/= - ' <$as_myself | - sed ' - s/[$]LINENO.*/&-/ - t lineno - b - :lineno - N - :loop - s/[$]LINENO\([^'$as_cr_alnum'_].*\n\)\(.*\)/\2\1\2/ - t loop - s/-\n.*// - ' >$as_me.lineno && - chmod +x "$as_me.lineno" || - { $as_echo "$as_me: error: cannot create $as_me.lineno; rerun with a POSIX shell" >&2 - { (exit 1); exit 1; }; } - - # Don't try to exec as it changes $[0], causing all sort of problems - # (the dirname of $[0] is not the place where we might find the - # original and so on. Autoconf is especially sensitive to this). - . "./$as_me.lineno" - # Exit status is that of the last command. - exit -} - - -if (as_dir=`dirname -- /` && test "X$as_dir" = X/) >/dev/null 2>&1; then - as_dirname=dirname -else - as_dirname=false -fi +# Avoid depending upon Character Ranges. +as_cr_letters='abcdefghijklmnopqrstuvwxyz' +as_cr_LETTERS='ABCDEFGHIJKLMNOPQRSTUVWXYZ' +as_cr_Letters=$as_cr_letters$as_cr_LETTERS +as_cr_digits='0123456789' +as_cr_alnum=$as_cr_Letters$as_cr_digits ECHO_C= ECHO_N= ECHO_T= -case `echo -n x` in +case `echo -n x` in #((((( -n*) - case `echo 'x\c'` in + case `echo 'xy\c'` in *c*) ECHO_T=' ';; # ECHO_T is single tab character. - *) ECHO_C='\c';; + xy) ECHO_C='\c';; + *) echo `echo ksh88 bug on AIX 6.1` > /dev/null + ECHO_T=' ';; esac;; *) ECHO_N='-n';; esac -if expr a : '\(a\)' >/dev/null 2>&1 && - test "X`expr 00001 : '.*\(...\)'`" = X001; then - as_expr=expr -else - as_expr=false -fi rm -f conf$$ conf$$.exe conf$$.file if test -d conf$$.dir; then @@ -26395,8 +13274,56 @@ rm -f conf$$ conf$$.exe conf$$.dir/conf$$.file conf$$.file rmdir conf$$.dir 2>/dev/null + +# as_fn_mkdir_p +# ------------- +# Create "$as_dir" as a directory, including parents if necessary. +as_fn_mkdir_p () +{ + + case $as_dir in #( + -*) as_dir=./$as_dir;; + esac + test -d "$as_dir" || eval $as_mkdir_p || { + as_dirs= + while :; do + case $as_dir in #( + *\'*) as_qdir=`$as_echo "$as_dir" | sed "s/'/'\\\\\\\\''/g"`;; #'( + *) as_qdir=$as_dir;; + esac + as_dirs="'$as_qdir' $as_dirs" + as_dir=`$as_dirname -- "$as_dir" || +$as_expr X"$as_dir" : 'X\(.*[^/]\)//*[^/][^/]*/*$' \| \ + X"$as_dir" : 'X\(//\)[^/]' \| \ + X"$as_dir" : 'X\(//\)$' \| \ + X"$as_dir" : 'X\(/\)' \| . 2>/dev/null || +$as_echo X"$as_dir" | + sed '/^X\(.*[^/]\)\/\/*[^/][^/]*\/*$/{ + s//\1/ + q + } + /^X\(\/\/\)[^/].*/{ + s//\1/ + q + } + /^X\(\/\/\)$/{ + s//\1/ + q + } + /^X\(\/\).*/{ + s//\1/ + q + } + s/.*/./; q'` + test -d "$as_dir" && break + done + test -z "$as_dirs" || eval "mkdir $as_dirs" + } || test -d "$as_dir" || as_fn_error "cannot create directory $as_dir" + + +} # as_fn_mkdir_p if mkdir -p . 2>/dev/null; then - as_mkdir_p=: + as_mkdir_p='mkdir -p "$as_dir"' else test -d ./-p && rmdir ./-p as_mkdir_p=false @@ -26415,10 +13342,10 @@ if test -d "$1"; then test -d "$1/."; else - case $1 in + case $1 in #( -*)set "./$1";; esac; - case `ls -ld'$as_ls_L_option' "$1" 2>/dev/null` in + case `ls -ld'$as_ls_L_option' "$1" 2>/dev/null` in #(( ???[sx]*):;;*)false;;esac;fi '\'' sh ' @@ -26433,13 +13360,19 @@ exec 6>&1 +## ----------------------------------- ## +## Main body of $CONFIG_STATUS script. ## +## ----------------------------------- ## +_ASEOF +test $as_write_fail = 0 && chmod +x $CONFIG_STATUS || ac_write_fail=1 -# Save the log message, to keep $[0] and so on meaningful, and to +cat >>$CONFIG_STATUS <<\_ACEOF || ac_write_fail=1 +# Save the log message, to keep $0 and so on meaningful, and to # report actual input values of CONFIG_FILES etc. instead of their # values after options handling. ac_log=" This file was extended by python $as_me 2.6, which was -generated by GNU Autoconf 2.63. Invocation command line was +generated by GNU Autoconf 2.65. Invocation command line was CONFIG_FILES = $CONFIG_FILES CONFIG_HEADERS = $CONFIG_HEADERS @@ -26470,13 +13403,15 @@ cat >>$CONFIG_STATUS <<\_ACEOF || ac_write_fail=1 ac_cs_usage="\ -\`$as_me' instantiates files from templates according to the -current configuration. +\`$as_me' instantiates files and other configuration actions +from templates according to the current configuration. Unless the files +and actions are specified as TAGs, all are instantiated by default. -Usage: $0 [OPTION]... [FILE]... +Usage: $0 [OPTION]... [TAG]... -h, --help print this help, then exit -V, --version print version number and configuration settings, then exit + --config print configuration, then exit -q, --quiet, --silent do not print progress messages -d, --debug don't remove temporary files @@ -26492,16 +13427,17 @@ Configuration headers: $config_headers -Report bugs to ." +Report bugs to ." _ACEOF cat >>$CONFIG_STATUS <<_ACEOF || ac_write_fail=1 +ac_cs_config="`$as_echo "$ac_configure_args" | sed 's/^ //; s/[\\""\`\$]/\\\\&/g'`" ac_cs_version="\\ python config.status 2.6 -configured by $0, generated by GNU Autoconf 2.63, - with options \\"`$as_echo "$ac_configure_args" | sed 's/^ //; s/[\\""\`\$]/\\\\&/g'`\\" +configured by $0, generated by GNU Autoconf 2.65, + with options \\"\$ac_cs_config\\" -Copyright (C) 2008 Free Software Foundation, Inc. +Copyright (C) 2009 Free Software Foundation, Inc. This config.status script is free software; the Free Software Foundation gives unlimited permission to copy, distribute and modify it." @@ -26535,6 +13471,8 @@ ac_cs_recheck=: ;; --version | --versio | --versi | --vers | --ver | --ve | --v | -V ) $as_echo "$ac_cs_version"; exit ;; + --config | --confi | --conf | --con | --co | --c ) + $as_echo "$ac_cs_config"; exit ;; --debug | --debu | --deb | --de | --d | -d ) debug=: ;; --file | --fil | --fi | --f ) @@ -26542,20 +13480,19 @@ case $ac_optarg in *\'*) ac_optarg=`$as_echo "$ac_optarg" | sed "s/'/'\\\\\\\\''/g"` ;; esac - CONFIG_FILES="$CONFIG_FILES '$ac_optarg'" + as_fn_append CONFIG_FILES " '$ac_optarg'" ac_need_defaults=false;; --header | --heade | --head | --hea ) $ac_shift case $ac_optarg in *\'*) ac_optarg=`$as_echo "$ac_optarg" | sed "s/'/'\\\\\\\\''/g"` ;; esac - CONFIG_HEADERS="$CONFIG_HEADERS '$ac_optarg'" + as_fn_append CONFIG_HEADERS " '$ac_optarg'" ac_need_defaults=false;; --he | --h) # Conflict between --help and --header - { $as_echo "$as_me: error: ambiguous option: $1 -Try \`$0 --help' for more information." >&2 - { (exit 1); exit 1; }; };; + as_fn_error "ambiguous option: \`$1' +Try \`$0 --help' for more information.";; --help | --hel | -h ) $as_echo "$ac_cs_usage"; exit ;; -q | -quiet | --quiet | --quie | --qui | --qu | --q \ @@ -26563,11 +13500,10 @@ ac_cs_silent=: ;; # This is an error. - -*) { $as_echo "$as_me: error: unrecognized option: $1 -Try \`$0 --help' for more information." >&2 - { (exit 1); exit 1; }; } ;; + -*) as_fn_error "unrecognized option: \`$1' +Try \`$0 --help' for more information." ;; - *) ac_config_targets="$ac_config_targets $1" + *) as_fn_append ac_config_targets " $1" ac_need_defaults=false ;; esac @@ -26622,9 +13558,7 @@ "Makefile.pre") CONFIG_FILES="$CONFIG_FILES Makefile.pre" ;; "Modules/Setup.config") CONFIG_FILES="$CONFIG_FILES Modules/Setup.config" ;; - *) { { $as_echo "$as_me:$LINENO: error: invalid argument: $ac_config_target" >&5 -$as_echo "$as_me: error: invalid argument: $ac_config_target" >&2;} - { (exit 1); exit 1; }; };; + *) as_fn_error "invalid argument: \`$ac_config_target'" "$LINENO" 5;; esac done @@ -26650,7 +13584,7 @@ trap 'exit_status=$? { test -z "$tmp" || test ! -d "$tmp" || rm -fr "$tmp"; } && exit $exit_status ' 0 - trap '{ (exit 1); exit 1; }' 1 2 13 15 + trap 'as_fn_exit 1' 1 2 13 15 } # Create a (secure) tmp directory for tmp files. @@ -26661,11 +13595,7 @@ { tmp=./conf$$-$RANDOM (umask 077 && mkdir "$tmp") -} || -{ - $as_echo "$as_me: cannot create a temporary directory in ." >&2 - { (exit 1); exit 1; } -} +} || as_fn_error "cannot create a temporary directory in ." "$LINENO" 5 # Set up the scripts for CONFIG_FILES section. # No need to generate them if there are no CONFIG_FILES. @@ -26673,11 +13603,16 @@ if test -n "$CONFIG_FILES"; then -ac_cr=' -' +ac_cr=`echo X | tr X '\015'` +# On cygwin, bash can eat \r inside `` if the user requested igncr. +# But we know of no other shell where ac_cr would be empty at this +# point, so we can use a bashism as a fallback. +if test "x$ac_cr" = x; then + eval ac_cr=\$\'\\r\' +fi ac_cs_awk_cr=`$AWK 'BEGIN { print "a\rb" }' /dev/null` if test "$ac_cs_awk_cr" = "a${ac_cr}b"; then - ac_cs_awk_cr='\\r' + ac_cs_awk_cr='\r' else ac_cs_awk_cr=$ac_cr fi @@ -26691,24 +13626,18 @@ echo "$ac_subst_vars" | sed 's/.*/&!$&$ac_delim/' && echo "_ACEOF" } >conf$$subs.sh || - { { $as_echo "$as_me:$LINENO: error: could not make $CONFIG_STATUS" >&5 -$as_echo "$as_me: error: could not make $CONFIG_STATUS" >&2;} - { (exit 1); exit 1; }; } + as_fn_error "could not make $CONFIG_STATUS" "$LINENO" 5 ac_delim_num=`echo "$ac_subst_vars" | grep -c '$'` ac_delim='%!_!# ' for ac_last_try in false false false false false :; do . ./conf$$subs.sh || - { { $as_echo "$as_me:$LINENO: error: could not make $CONFIG_STATUS" >&5 -$as_echo "$as_me: error: could not make $CONFIG_STATUS" >&2;} - { (exit 1); exit 1; }; } + as_fn_error "could not make $CONFIG_STATUS" "$LINENO" 5 ac_delim_n=`sed -n "s/.*$ac_delim\$/X/p" conf$$subs.awk | grep -c X` if test $ac_delim_n = $ac_delim_num; then break elif $ac_last_try; then - { { $as_echo "$as_me:$LINENO: error: could not make $CONFIG_STATUS" >&5 -$as_echo "$as_me: error: could not make $CONFIG_STATUS" >&2;} - { (exit 1); exit 1; }; } + as_fn_error "could not make $CONFIG_STATUS" "$LINENO" 5 else ac_delim="$ac_delim!$ac_delim _$ac_delim!! " fi @@ -26730,7 +13659,7 @@ t delim :nl h -s/\(.\{148\}\).*/\1/ +s/\(.\{148\}\)..*/\1/ t more1 s/["\\]/\\&/g; s/^/"/; s/$/\\n"\\/ p @@ -26744,7 +13673,7 @@ t nl :delim h -s/\(.\{148\}\).*/\1/ +s/\(.\{148\}\)..*/\1/ t more2 s/["\\]/\\&/g; s/^/"/; s/$/"/ p @@ -26797,9 +13726,7 @@ else cat fi < "$tmp/subs1.awk" > "$tmp/subs.awk" \ - || { { $as_echo "$as_me:$LINENO: error: could not setup config files machinery" >&5 -$as_echo "$as_me: error: could not setup config files machinery" >&2;} - { (exit 1); exit 1; }; } + || as_fn_error "could not setup config files machinery" "$LINENO" 5 _ACEOF # VPATH may cause trouble with some makes, so we remove $(srcdir), @@ -26840,9 +13767,7 @@ if test -z "$ac_t"; then break elif $ac_last_try; then - { { $as_echo "$as_me:$LINENO: error: could not make $CONFIG_HEADERS" >&5 -$as_echo "$as_me: error: could not make $CONFIG_HEADERS" >&2;} - { (exit 1); exit 1; }; } + as_fn_error "could not make $CONFIG_HEADERS" "$LINENO" 5 else ac_delim="$ac_delim!$ac_delim _$ac_delim!! " fi @@ -26927,9 +13852,7 @@ _ACAWK _ACEOF cat >>$CONFIG_STATUS <<\_ACEOF || ac_write_fail=1 - { { $as_echo "$as_me:$LINENO: error: could not setup config headers machinery" >&5 -$as_echo "$as_me: error: could not setup config headers machinery" >&2;} - { (exit 1); exit 1; }; } + as_fn_error "could not setup config headers machinery" "$LINENO" 5 fi # test -n "$CONFIG_HEADERS" @@ -26942,9 +13865,7 @@ esac case $ac_mode$ac_tag in :[FHL]*:*);; - :L* | :C*:*) { { $as_echo "$as_me:$LINENO: error: invalid tag $ac_tag" >&5 -$as_echo "$as_me: error: invalid tag $ac_tag" >&2;} - { (exit 1); exit 1; }; };; + :L* | :C*:*) as_fn_error "invalid tag \`$ac_tag'" "$LINENO" 5;; :[FH]-) ac_tag=-:-;; :[FH]*) ac_tag=$ac_tag:$ac_tag.in;; esac @@ -26972,12 +13893,10 @@ [\\/$]*) false;; *) test -f "$srcdir/$ac_f" && ac_f="$srcdir/$ac_f";; esac || - { { $as_echo "$as_me:$LINENO: error: cannot find input file: $ac_f" >&5 -$as_echo "$as_me: error: cannot find input file: $ac_f" >&2;} - { (exit 1); exit 1; }; };; + as_fn_error "cannot find input file: \`$ac_f'" "$LINENO" 5;; esac case $ac_f in *\'*) ac_f=`$as_echo "$ac_f" | sed "s/'/'\\\\\\\\''/g"`;; esac - ac_file_inputs="$ac_file_inputs '$ac_f'" + as_fn_append ac_file_inputs " '$ac_f'" done # Let's still pretend it is `configure' which instantiates (i.e., don't @@ -26988,7 +13907,7 @@ `' by configure.' if test x"$ac_file" != x-; then configure_input="$ac_file. $configure_input" - { $as_echo "$as_me:$LINENO: creating $ac_file" >&5 + { $as_echo "$as_me:${as_lineno-$LINENO}: creating $ac_file" >&5 $as_echo "$as_me: creating $ac_file" >&6;} fi # Neutralize special characters interpreted by sed in replacement strings. @@ -27001,9 +13920,7 @@ case $ac_tag in *:-:* | *:-) cat >"$tmp/stdin" \ - || { { $as_echo "$as_me:$LINENO: error: could not create $ac_file" >&5 -$as_echo "$as_me: error: could not create $ac_file" >&2;} - { (exit 1); exit 1; }; } ;; + || as_fn_error "could not create $ac_file" "$LINENO" 5 ;; esac ;; esac @@ -27031,47 +13948,7 @@ q } s/.*/./; q'` - { as_dir="$ac_dir" - case $as_dir in #( - -*) as_dir=./$as_dir;; - esac - test -d "$as_dir" || { $as_mkdir_p && mkdir -p "$as_dir"; } || { - as_dirs= - while :; do - case $as_dir in #( - *\'*) as_qdir=`$as_echo "$as_dir" | sed "s/'/'\\\\\\\\''/g"`;; #'( - *) as_qdir=$as_dir;; - esac - as_dirs="'$as_qdir' $as_dirs" - as_dir=`$as_dirname -- "$as_dir" || -$as_expr X"$as_dir" : 'X\(.*[^/]\)//*[^/][^/]*/*$' \| \ - X"$as_dir" : 'X\(//\)[^/]' \| \ - X"$as_dir" : 'X\(//\)$' \| \ - X"$as_dir" : 'X\(/\)' \| . 2>/dev/null || -$as_echo X"$as_dir" | - sed '/^X\(.*[^/]\)\/\/*[^/][^/]*\/*$/{ - s//\1/ - q - } - /^X\(\/\/\)[^/].*/{ - s//\1/ - q - } - /^X\(\/\/\)$/{ - s//\1/ - q - } - /^X\(\/\).*/{ - s//\1/ - q - } - s/.*/./; q'` - test -d "$as_dir" && break - done - test -z "$as_dirs" || eval "mkdir $as_dirs" - } || test -d "$as_dir" || { { $as_echo "$as_me:$LINENO: error: cannot create directory $as_dir" >&5 -$as_echo "$as_me: error: cannot create directory $as_dir" >&2;} - { (exit 1); exit 1; }; }; } + as_dir="$ac_dir"; as_fn_mkdir_p ac_builddir=. case "$ac_dir" in @@ -27123,7 +14000,6 @@ # If the template does not know about datarootdir, expand it. # FIXME: This hack should be removed a few years after 2.60. ac_datarootdir_hack=; ac_datarootdir_seen= - ac_sed_dataroot=' /datarootdir/ { p @@ -27133,12 +14009,11 @@ /@docdir@/p /@infodir@/p /@localedir@/p -/@mandir@/p -' +/@mandir@/p' case `eval "sed -n \"\$ac_sed_dataroot\" $ac_file_inputs"` in *datarootdir*) ac_datarootdir_seen=yes;; *@datadir@*|*@docdir@*|*@infodir@*|*@localedir@*|*@mandir@*) - { $as_echo "$as_me:$LINENO: WARNING: $ac_file_inputs seems to ignore the --datarootdir setting" >&5 + { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: $ac_file_inputs seems to ignore the --datarootdir setting" >&5 $as_echo "$as_me: WARNING: $ac_file_inputs seems to ignore the --datarootdir setting" >&2;} _ACEOF cat >>$CONFIG_STATUS <<_ACEOF || ac_write_fail=1 @@ -27148,7 +14023,7 @@ s&@infodir@&$infodir&g s&@localedir@&$localedir&g s&@mandir@&$mandir&g - s&\\\${datarootdir}&$datarootdir&g' ;; + s&\\\${datarootdir}&$datarootdir&g' ;; esac _ACEOF @@ -27176,14 +14051,12 @@ $ac_datarootdir_hack " eval sed \"\$ac_sed_extra\" "$ac_file_inputs" | $AWK -f "$tmp/subs.awk" >$tmp/out \ - || { { $as_echo "$as_me:$LINENO: error: could not create $ac_file" >&5 -$as_echo "$as_me: error: could not create $ac_file" >&2;} - { (exit 1); exit 1; }; } + || as_fn_error "could not create $ac_file" "$LINENO" 5 test -z "$ac_datarootdir_hack$ac_datarootdir_seen" && { ac_out=`sed -n '/\${datarootdir}/p' "$tmp/out"`; test -n "$ac_out"; } && { ac_out=`sed -n '/^[ ]*datarootdir[ ]*:*=/p' "$tmp/out"`; test -z "$ac_out"; } && - { $as_echo "$as_me:$LINENO: WARNING: $ac_file contains a reference to the variable \`datarootdir' + { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: $ac_file contains a reference to the variable \`datarootdir' which seems to be undefined. Please make sure it is defined." >&5 $as_echo "$as_me: WARNING: $ac_file contains a reference to the variable \`datarootdir' which seems to be undefined. Please make sure it is defined." >&2;} @@ -27193,9 +14066,7 @@ -) cat "$tmp/out" && rm -f "$tmp/out";; *) rm -f "$ac_file" && mv "$tmp/out" "$ac_file";; esac \ - || { { $as_echo "$as_me:$LINENO: error: could not create $ac_file" >&5 -$as_echo "$as_me: error: could not create $ac_file" >&2;} - { (exit 1); exit 1; }; } + || as_fn_error "could not create $ac_file" "$LINENO" 5 ;; :H) # @@ -27206,25 +14077,19 @@ $as_echo "/* $configure_input */" \ && eval '$AWK -f "$tmp/defines.awk"' "$ac_file_inputs" } >"$tmp/config.h" \ - || { { $as_echo "$as_me:$LINENO: error: could not create $ac_file" >&5 -$as_echo "$as_me: error: could not create $ac_file" >&2;} - { (exit 1); exit 1; }; } + || as_fn_error "could not create $ac_file" "$LINENO" 5 if diff "$ac_file" "$tmp/config.h" >/dev/null 2>&1; then - { $as_echo "$as_me:$LINENO: $ac_file is unchanged" >&5 + { $as_echo "$as_me:${as_lineno-$LINENO}: $ac_file is unchanged" >&5 $as_echo "$as_me: $ac_file is unchanged" >&6;} else rm -f "$ac_file" mv "$tmp/config.h" "$ac_file" \ - || { { $as_echo "$as_me:$LINENO: error: could not create $ac_file" >&5 -$as_echo "$as_me: error: could not create $ac_file" >&2;} - { (exit 1); exit 1; }; } + || as_fn_error "could not create $ac_file" "$LINENO" 5 fi else $as_echo "/* $configure_input */" \ && eval '$AWK -f "$tmp/defines.awk"' "$ac_file_inputs" \ - || { { $as_echo "$as_me:$LINENO: error: could not create -" >&5 -$as_echo "$as_me: error: could not create -" >&2;} - { (exit 1); exit 1; }; } + || as_fn_error "could not create -" "$LINENO" 5 fi ;; @@ -27234,15 +14099,12 @@ done # for ac_tag -{ (exit 0); exit 0; } +as_fn_exit 0 _ACEOF -chmod +x $CONFIG_STATUS ac_clean_files=$ac_clean_files_save test $ac_write_fail = 0 || - { { $as_echo "$as_me:$LINENO: error: write failure creating $CONFIG_STATUS" >&5 -$as_echo "$as_me: error: write failure creating $CONFIG_STATUS" >&2;} - { (exit 1); exit 1; }; } + as_fn_error "write failure creating $CONFIG_STATUS" "$LINENO" 5 # configure is writing to config.log, and then calls config.status. @@ -27263,10 +14125,10 @@ exec 5>>config.log # Use ||, not &&, to avoid exiting from the if with $? = 1, which # would make configure fail if this is the last instruction. - $ac_cs_success || { (exit 1); exit 1; } + $ac_cs_success || as_fn_exit $? fi if test -n "$ac_unrecognized_opts" && test "$enable_option_checking" != no; then - { $as_echo "$as_me:$LINENO: WARNING: unrecognized options: $ac_unrecognized_opts" >&5 + { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: unrecognized options: $ac_unrecognized_opts" >&5 $as_echo "$as_me: WARNING: unrecognized options: $ac_unrecognized_opts" >&2;} fi @@ -27290,7 +14152,7 @@ case $ac_sys_system in BeOS) - { $as_echo "$as_me:$LINENO: WARNING: + { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: Support for BeOS is deprecated as of Python 2.6. See PEP 11 for the gory details. Modified: python/branches/release26-maint/configure.in ============================================================================== --- python/branches/release26-maint/configure.in (original) +++ python/branches/release26-maint/configure.in Tue May 25 04:27:03 2010 @@ -3424,7 +3424,7 @@ AC_MSG_CHECKING(what type to use for unicode) dnl quadrigraphs "@<:@" and "@:>@" produce "[" and "]" in the output AC_ARG_ENABLE(unicode, - AC_HELP_STRING(--enable-unicode@<:@=ucs@<:@24@:>@@:>@, Enable Unicode strings (default is yes)), + AC_HELP_STRING(--enable-unicode@<:@=ucs@<:@24@:>@@:>@, Enable Unicode strings (default is ucs2)), [], [enable_unicode=yes]) From python-checkins at python.org Tue May 25 04:27:55 2010 From: python-checkins at python.org (benjamin.peterson) Date: Tue, 25 May 2010 04:27:55 +0200 (CEST) Subject: [Python-checkins] r81511 - python/branches/py3k Message-ID: <20100525022755.928F3EE988@mail.python.org> Author: benjamin.peterson Date: Tue May 25 04:27:55 2010 New Revision: 81511 Log: Blocked revisions 81509 via svnmerge ........ r81509 | benjamin.peterson | 2010-05-24 21:23:32 -0500 (Mon, 24 May 2010) | 1 line correct default docs ........ Modified: python/branches/py3k/ (props changed) From python-checkins at python.org Tue May 25 04:53:04 2010 From: python-checkins at python.org (brett.cannon) Date: Tue, 25 May 2010 04:53:04 +0200 (CEST) Subject: [Python-checkins] r81512 - python/trunk/Misc/ACKS Message-ID: <20100525025304.D5DB6EE986@mail.python.org> Author: brett.cannon Date: Tue May 25 04:53:04 2010 New Revision: 81512 Log: Make the contributor list alphabetical again. Modified: python/trunk/Misc/ACKS Modified: python/trunk/Misc/ACKS ============================================================================== --- python/trunk/Misc/ACKS (original) +++ python/trunk/Misc/ACKS Tue May 25 04:53:04 2010 @@ -362,6 +362,7 @@ Eric Huss Jeremy Hylton Gerhard H?ring +Fredrik H??rd Mihai Ibanescu Lars Immisch Meador Inge @@ -860,4 +861,3 @@ Uwe Zessin Tarek Ziad? Peter ?strand -Fredrik H??rd From python-checkins at python.org Tue May 25 11:44:37 2010 From: python-checkins at python.org (tarek.ziade) Date: Tue, 25 May 2010 11:44:37 +0200 (CEST) Subject: [Python-checkins] r81513 - in python/branches/py3k: Doc/library/sysconfig.rst Lib/sysconfig.py Lib/test/test_sysconfig.py Misc/NEWS Message-ID: <20100525094437.2315DEE986@mail.python.org> Author: tarek.ziade Date: Tue May 25 11:44:36 2010 New Revision: 81513 Log: Made sysconfig a script that displays useful information - #8770 Modified: python/branches/py3k/Doc/library/sysconfig.rst python/branches/py3k/Lib/sysconfig.py python/branches/py3k/Lib/test/test_sysconfig.py python/branches/py3k/Misc/NEWS Modified: python/branches/py3k/Doc/library/sysconfig.rst ============================================================================== --- python/branches/py3k/Doc/library/sysconfig.rst (original) +++ python/branches/py3k/Doc/library/sysconfig.rst Tue May 25 11:44:36 2010 @@ -216,3 +216,35 @@ .. function:: get_config_h_filename() Return the path of :file:`pyconfig.h`. + +Using :mod:`sysconfig` as a script +---------------------------------- + +You can use :mod:`sysconfig` as a script with Python's *-m* option:: + + $ python -m sysconfig + Platform: "macosx-10.4-i386" + Python version: "3.2" + Current installation scheme: "posix_prefix" + + Paths: + data = "/usr/local" + include = "/Users/tarek/Dev/svn.python.org/py3k/Include" + platinclude = "." + platlib = "/usr/local/lib/python3.2/site-packages" + platstdlib = "/usr/local/lib/python3.2" + purelib = "/usr/local/lib/python3.2/site-packages" + scripts = "/usr/local/bin" + stdlib = "/usr/local/lib/python3.2" + + Variables: + AC_APPLE_UNIVERSAL_BUILD = "0" + AIX_GENUINE_CPLUSPLUS = "0" + AR = "ar" + ARFLAGS = "rc" + ASDLGEN = "./Parser/asdl_c.py" + ... + +This call will print in the standard output the information returned by +:func:`get_platform`, :func:`get_python_version`, :func:`get_path` and +:func:`get_config_vars`. Modified: python/branches/py3k/Lib/sysconfig.py ============================================================================== --- python/branches/py3k/Lib/sysconfig.py (original) +++ python/branches/py3k/Lib/sysconfig.py Tue May 25 11:44:36 2010 @@ -686,3 +686,22 @@ def get_python_version(): return _PY_VERSION_SHORT + +def _print_dict(title, data): + for index, (key, value) in enumerate(sorted(data.items())): + if index == 0: + print('{0}: '.format(title)) + print('\t{0} = "{1}"'.format(key, value)) + +def _main(): + """Displays all information sysconfig detains.""" + print('Platform: "{0}"'.format(get_platform())) + print('Python version: "{0}"'.format(get_python_version())) + print('Current installation scheme: "{0}"'.format(_get_default_scheme())) + print('') + _print_dict('Paths', get_paths()) + print('') + _print_dict('Variables', get_config_vars()) + +if __name__ == '__main__': + _main() Modified: python/branches/py3k/Lib/test/test_sysconfig.py ============================================================================== --- python/branches/py3k/Lib/test/test_sysconfig.py (original) +++ python/branches/py3k/Lib/test/test_sysconfig.py Tue May 25 11:44:36 2010 @@ -11,13 +11,14 @@ import shutil from copy import copy, deepcopy -from test.support import run_unittest, TESTFN, unlink, get_attribute +from test.support import (run_unittest, TESTFN, unlink, get_attribute, + captured_stdout) import sysconfig from sysconfig import (get_paths, get_platform, get_config_vars, get_path, get_path_names, _INSTALL_SCHEMES, _get_default_scheme, _expand_vars, - get_scheme_names, get_config_var) + get_scheme_names, get_config_var, _main) class TestSysConfig(unittest.TestCase): @@ -264,6 +265,13 @@ user_path = get_path(name, 'posix_user') self.assertEquals(user_path, global_path.replace(base, user)) + def test_main(self): + # just making sure _main() runs and returns things in the stdout + with captured_stdout() as output: + _main() + self.assertTrue(len(output.getvalue().split('\n')) > 0) + + def test_main(): run_unittest(TestSysConfig) Modified: python/branches/py3k/Misc/NEWS ============================================================================== --- python/branches/py3k/Misc/NEWS (original) +++ python/branches/py3k/Misc/NEWS Tue May 25 11:44:36 2010 @@ -392,6 +392,9 @@ Library ------- +- Issue #8770: now sysconfig displays information when it's called as + a script. Initial idea by Sridhar Ratnakumar. + - Issue #6662: Fix parsing of malformatted charref (&#bad;), patch written by Fredrik H??rd From python-checkins at python.org Tue May 25 11:47:06 2010 From: python-checkins at python.org (tarek.ziade) Date: Tue, 25 May 2010 11:47:06 +0200 (CEST) Subject: [Python-checkins] r81514 - python/branches/py3k/Lib/sysconfig.py Message-ID: <20100525094706.88BC4EE986@mail.python.org> Author: tarek.ziade Date: Tue May 25 11:47:06 2010 New Revision: 81514 Log: added the list of public APIs in sysconfig Modified: python/branches/py3k/Lib/sysconfig.py Modified: python/branches/py3k/Lib/sysconfig.py ============================================================================== --- python/branches/py3k/Lib/sysconfig.py (original) +++ python/branches/py3k/Lib/sysconfig.py Tue May 25 11:47:06 2010 @@ -5,6 +5,10 @@ import os from os.path import pardir, realpath +__all__ = ['parse_config_h', 'get_config_h_filename', 'get_scheme_names', + 'get_path_names', 'get_paths', 'get_path', 'get_config_vars', + 'get_config_var', 'get_platform', 'get_python_version'] + _INSTALL_SCHEMES = { 'posix_prefix': { 'stdlib': '{base}/lib/python{py_version_short}', From python-checkins at python.org Tue May 25 11:48:08 2010 From: python-checkins at python.org (tarek.ziade) Date: Tue, 25 May 2010 11:48:08 +0200 (CEST) Subject: [Python-checkins] r81515 - python/branches/release31-maint Message-ID: <20100525094808.015FAEE986@mail.python.org> Author: tarek.ziade Date: Tue May 25 11:48:07 2010 New Revision: 81515 Log: Blocked revisions 81513-81514 via svnmerge ........ r81513 | tarek.ziade | 2010-05-25 11:44:36 +0200 (Tue, 25 May 2010) | 1 line Made sysconfig a script that displays useful information - #8770 ........ r81514 | tarek.ziade | 2010-05-25 11:47:06 +0200 (Tue, 25 May 2010) | 1 line added the list of public APIs in sysconfig ........ Modified: python/branches/release31-maint/ (props changed) From python-checkins at python.org Tue May 25 15:34:09 2010 From: python-checkins at python.org (andrew.kuchling) Date: Tue, 25 May 2010 15:34:09 +0200 (CEST) Subject: [Python-checkins] r81516 - python/trunk/Doc/whatsnew/2.7.rst Message-ID: <20100525133409.152BAEE9C3@mail.python.org> Author: andrew.kuchling Date: Tue May 25 15:34:08 2010 New Revision: 81516 Log: Add three items Modified: python/trunk/Doc/whatsnew/2.7.rst Modified: python/trunk/Doc/whatsnew/2.7.rst ============================================================================== --- python/trunk/Doc/whatsnew/2.7.rst (original) +++ python/trunk/Doc/whatsnew/2.7.rst Tue May 25 15:34:08 2010 @@ -796,9 +796,11 @@ deleting an unset attribute would not raise :exc:`AttributeError` as you would expect. Fixed by Benjamin Peterson; :issue:`7604`.) -* A new encoding named "cp720", used primarily for Arabic text, is now - supported. (Contributed by Alexander Belchenko and Amaury Forgeot - d'Arc; :issue:`1616979`.) +* Two new encodings are now supported: "cp720", used primarily for + Arabic text; and "cp858", a variant of CP 850 that adds the euro + symbol. (CP720 contributed by Alexander Belchenko and Amaury + Forgeot d'Arc in :issue:`1616979`; CP858 contributed by Tim Hatch in + :issue:`8016`.) * The :class:`file` object will now set the :attr:`filename` attribute on the :exc:`IOError` exception when trying to open a directory @@ -1066,6 +1068,11 @@ (Added by Raymond Hettinger; :issue:`1818`.) + Finally, the :class:`~collections.Mapping` abstract base class now + raises a :exc:`NotImplemented` exception if a mapping is compared to + another type that isn't a :class:`Mapping`. + (Fixed by Daniel Stutzbach; :issue:`8729`.) + * Constructors for the parsing classes in the :mod:`ConfigParser` module now take a *allow_no_value* parameter, defaulting to false; if true, options without values will be allowed. For example:: @@ -1158,6 +1165,12 @@ a separator in the header giving the filename. (Fixed by Anatoly Techtonik; :issue:`7585`.) +* The Distutils ``sdist`` command now always regenerates the + :file:`MANIFEST` file, since even if the :file:`MANIFEST.in` or + :file:`setup.py` files haven't been modified, the user might have + created some new files that should be included. + (Fixed by Tarek Ziad?; :issue:`8688`.) + * 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`.) From python-checkins at python.org Tue May 25 17:06:15 2010 From: python-checkins at python.org (brian.curtin) Date: Tue, 25 May 2010 17:06:15 +0200 (CEST) Subject: [Python-checkins] r81517 - in python/trunk: Lib/test/test_winreg.py Misc/NEWS PC/_winreg.c Message-ID: <20100525150615.59B91EE982@mail.python.org> Author: brian.curtin Date: Tue May 25 17:06:15 2010 New Revision: 81517 Log: Fix #2810 - handle the case where some registry calls return ERROR_MORE_DATA, requiring another call to get the remaining data. Patch by Daniel Stutzbach Modified: python/trunk/Lib/test/test_winreg.py python/trunk/Misc/NEWS python/trunk/PC/_winreg.c Modified: python/trunk/Lib/test/test_winreg.py ============================================================================== --- python/trunk/Lib/test/test_winreg.py (original) +++ python/trunk/Lib/test/test_winreg.py Tue May 25 17:06:15 2010 @@ -4,6 +4,7 @@ import os, sys import unittest from test import test_support +threading = test_support.import_module("threading") from platform import machine # Do this first so test will be skipped if module doesn't exist @@ -231,6 +232,58 @@ except WindowsError: self.assertEqual(h.handle, 0) + def test_changing_value(self): + # Issue2810: A race condition in 2.6 and 3.1 may cause + # EnumValue or QueryValue to throw "WindowsError: More data is + # available" + done = False + + class VeryActiveThread(threading.Thread): + def run(self): + with CreateKey(HKEY_CURRENT_USER, test_key_name) as key: + use_short = True + long_string = 'x'*2000 + while not done: + s = 'x' if use_short else long_string + use_short = not use_short + SetValue(key, 'changing_value', REG_SZ, s) + + thread = VeryActiveThread() + thread.start() + try: + with CreateKey(HKEY_CURRENT_USER, + test_key_name+'\\changing_value') as key: + for _ in range(1000): + num_subkeys, num_values, t = QueryInfoKey(key) + for i in range(num_values): + name = EnumValue(key, i) + QueryValue(key, name[0]) + finally: + done = True + thread.join() + DeleteKey(HKEY_CURRENT_USER, test_key_name+'\\changing_value') + DeleteKey(HKEY_CURRENT_USER, test_key_name) + + def test_long_key(self): + # Issue2810, in 2.6 and 3.1 when the key name was exactly 256 + # characters, EnumKey threw "WindowsError: More data is + # available" + name = 'x'*256 + try: + with CreateKey(HKEY_CURRENT_USER, test_key_name) as key: + SetValue(key, name, REG_SZ, 'x') + num_subkeys, num_values, t = QueryInfoKey(key) + EnumKey(key, 0) + finally: + DeleteKey(HKEY_CURRENT_USER, '\\'.join((test_key_name, name))) + DeleteKey(HKEY_CURRENT_USER, test_key_name) + + def test_dynamic_key(self): + # Issue2810, when the value is dynamically generated, these + # throw "WindowsError: More data is available" in 2.6 and 3.1 + EnumValue(HKEY_PERFORMANCE_DATA, 0) + QueryValueEx(HKEY_PERFORMANCE_DATA, None) + # Reflection requires XP x64/Vista at a minimum. XP doesn't have this stuff # or DeleteKeyEx so make sure their use raises NotImplementedError @unittest.skipUnless(WIN_VER < (5, 2), "Requires Windows XP") Modified: python/trunk/Misc/NEWS ============================================================================== --- python/trunk/Misc/NEWS (original) +++ python/trunk/Misc/NEWS Tue May 25 17:06:15 2010 @@ -63,6 +63,9 @@ Extension Modules ----------------- +- Issue #2810: Fix cases where the Windows registry API returns + ERROR_MORE_DATA, requiring a re-try in order to get the complete result. + - Issue #8674: Fixed a number of incorrect or undefined-behaviour-inducing overflow checks in the ``audioop`` module. Modified: python/trunk/PC/_winreg.c ============================================================================== --- python/trunk/PC/_winreg.c (original) +++ python/trunk/PC/_winreg.c Tue May 25 17:06:15 2010 @@ -1153,7 +1153,14 @@ int index; long rc; PyObject *retStr; - char tmpbuf[256]; /* max key name length is 255 */ + + /* The Windows docs claim that the max key name length is 255 + * characters, plus a terminating nul character. However, + * empirical testing demonstrates that it is possible to + * create a 256 character key that is missing the terminating + * nul. RegEnumKeyEx requires a 257 character buffer to + * retrieve such a key name. */ + char tmpbuf[257]; DWORD len = sizeof(tmpbuf); /* includes NULL terminator */ if (!PyArg_ParseTuple(args, "Oi:EnumKey", &obKey, &index)) @@ -1180,8 +1187,8 @@ long rc; char *retValueBuf; char *retDataBuf; - DWORD retValueSize; - DWORD retDataSize; + DWORD retValueSize, bufValueSize; + DWORD retDataSize, bufDataSize; DWORD typ; PyObject *obData; PyObject *retVal; @@ -1199,6 +1206,8 @@ "RegQueryInfoKey"); ++retValueSize; /* include null terminators */ ++retDataSize; + bufDataSize = retDataSize; + bufValueSize = retValueSize; retValueBuf = (char *)PyMem_Malloc(retValueSize); if (retValueBuf == NULL) return PyErr_NoMemory(); @@ -1208,16 +1217,33 @@ return PyErr_NoMemory(); } - Py_BEGIN_ALLOW_THREADS - rc = RegEnumValue(hKey, - index, - retValueBuf, - &retValueSize, - NULL, - &typ, - (BYTE *)retDataBuf, - &retDataSize); - Py_END_ALLOW_THREADS + while (1) { + char *tmp; + Py_BEGIN_ALLOW_THREADS + rc = RegEnumValue(hKey, + index, + retValueBuf, + &retValueSize, + NULL, + &typ, + (BYTE *)retDataBuf, + &retDataSize); + Py_END_ALLOW_THREADS + + if (rc != ERROR_MORE_DATA) + break; + + bufDataSize *= 2; + tmp = (char *)PyMem_Realloc(retDataBuf, bufDataSize); + if (tmp == NULL) { + PyErr_NoMemory(); + retVal = NULL; + goto fail; + } + retDataBuf = tmp; + retDataSize = bufDataSize; + retValueSize = bufValueSize; + } if (rc != ERROR_SUCCESS) { retVal = PyErr_SetFromWindowsErrWithFunction(rc, @@ -1374,28 +1400,56 @@ long rc; PyObject *retStr; char *retBuf; - long bufSize = 0; + DWORD bufSize = 0; + DWORD retSize = 0; + char *tmp; if (!PyArg_ParseTuple(args, "Oz:QueryValue", &obKey, &subKey)) return NULL; if (!PyHKEY_AsHKEY(obKey, &hKey, FALSE)) return NULL; - if ((rc = RegQueryValue(hKey, subKey, NULL, &bufSize)) - != ERROR_SUCCESS) + + rc = RegQueryValue(hKey, subKey, NULL, &retSize); + if (rc == ERROR_MORE_DATA) + retSize = 256; + else if (rc != ERROR_SUCCESS) return PyErr_SetFromWindowsErrWithFunction(rc, "RegQueryValue"); - retStr = PyString_FromStringAndSize(NULL, bufSize); - if (retStr == NULL) - return NULL; - retBuf = PyString_AS_STRING(retStr); - if ((rc = RegQueryValue(hKey, subKey, retBuf, &bufSize)) - != ERROR_SUCCESS) { - Py_DECREF(retStr); + + bufSize = retSize; + retBuf = (char *) PyMem_Malloc(bufSize); + if (retBuf == NULL) + return PyErr_NoMemory(); + + while (1) { + retSize = bufSize; + rc = RegQueryValue(hKey, subKey, retBuf, &retSize); + if (rc != ERROR_MORE_DATA) + break; + + bufSize *= 2; + tmp = (char *) PyMem_Realloc(retBuf, bufSize); + if (tmp == NULL) { + PyMem_Free(retBuf); + return PyErr_NoMemory(); + } + retBuf = tmp; + } + + if (rc != ERROR_SUCCESS) { + PyMem_Free(retBuf); return PyErr_SetFromWindowsErrWithFunction(rc, "RegQueryValue"); } - _PyString_Resize(&retStr, strlen(retBuf)); + + if (retBuf[retSize-1] == '\x00') + retSize--; + retStr = PyString_FromStringAndSize(retBuf, retSize); + if (retStr == NULL) { + PyMem_Free(retBuf); + return NULL; + } return retStr; } @@ -1407,8 +1461,8 @@ char *valueName; long rc; - char *retBuf; - DWORD bufSize = 0; + char *retBuf, *tmp; + DWORD bufSize = 0, retSize; DWORD typ; PyObject *obData; PyObject *result; @@ -1418,18 +1472,34 @@ if (!PyHKEY_AsHKEY(obKey, &hKey, FALSE)) return NULL; - if ((rc = RegQueryValueEx(hKey, valueName, - NULL, NULL, NULL, - &bufSize)) - != ERROR_SUCCESS) + + rc = RegQueryValueEx(hKey, valueName, NULL, NULL, NULL, &bufSize); + if (rc == ERROR_MORE_DATA) + bufSize = 256; + else if (rc != ERROR_SUCCESS) return PyErr_SetFromWindowsErrWithFunction(rc, "RegQueryValueEx"); retBuf = (char *)PyMem_Malloc(bufSize); if (retBuf == NULL) return PyErr_NoMemory(); - if ((rc = RegQueryValueEx(hKey, valueName, NULL, - &typ, (BYTE *)retBuf, &bufSize)) - != ERROR_SUCCESS) { + + while (1) { + retSize = bufSize; + rc = RegQueryValueEx(hKey, valueName, NULL, &typ, + (BYTE *)retBuf, &retSize); + if (rc != ERROR_MORE_DATA) + break; + + bufSize *= 2; + tmp = (char *) PyMem_Realloc(retBuf, bufSize); + if (tmp == NULL) { + PyMem_Free(retBuf); + return PyErr_NoMemory(); + } + retBuf = tmp; + } + + if (rc != ERROR_SUCCESS) { PyMem_Free(retBuf); return PyErr_SetFromWindowsErrWithFunction(rc, "RegQueryValueEx"); From python-checkins at python.org Tue May 25 17:20:47 2010 From: python-checkins at python.org (r.david.murray) Date: Tue, 25 May 2010 17:20:47 +0200 (CEST) Subject: [Python-checkins] r81518 - in python/trunk/Lib: urllib.py urlparse.py Message-ID: <20100525152047.14D51EE9A0@mail.python.org> Author: r.david.murray Date: Tue May 25 17:20:46 2010 New Revision: 81518 Log: Issue 8143: sync unquote in urlparse with urllib; add comment about doing so. unquote is duplicated in the two files to avoid a circular reference. (This is fixed in Python3.) Updates keep getting made to the public unquote without fixing the urlparse one, however, so this fix syncs the two and adds a comment to both to make sure changes are applied to both. Modified: python/trunk/Lib/urllib.py python/trunk/Lib/urlparse.py Modified: python/trunk/Lib/urllib.py ============================================================================== --- python/trunk/Lib/urllib.py (original) +++ python/trunk/Lib/urllib.py Tue May 25 17:20:46 2010 @@ -1156,6 +1156,10 @@ if match: return match.group(1, 2) return attr, None +# urlparse contains a duplicate of this method to avoid a circular import. If +# you update this method, also update the copy in urlparse. This code +# duplication does not exist in Python3. + _hexdig = '0123456789ABCDEFabcdef' _hextochr = dict((a + b, chr(int(a + b, 16))) for a in _hexdig for b in _hexdig) Modified: python/trunk/Lib/urlparse.py ============================================================================== --- python/trunk/Lib/urlparse.py (original) +++ python/trunk/Lib/urlparse.py Tue May 25 17:20:46 2010 @@ -301,25 +301,29 @@ return url, '' # unquote method for parse_qs and parse_qsl -# Cannot use directly from urllib as it would create circular reference. -# urllib uses urlparse methods ( urljoin) - +# Cannot use directly from urllib as it would create a circular reference +# because urllib uses urlparse methods (urljoin). If you update this function, +# update it also in urllib. This code duplication does not existin in Python3. _hexdig = '0123456789ABCDEFabcdef' -_hextochr = dict((a+b, chr(int(a+b,16))) for a in _hexdig for b in _hexdig) +_hextochr = dict((a+b, chr(int(a+b,16))) + for a in _hexdig for b in _hexdig) def unquote(s): """unquote('abc%20def') -> 'abc def'.""" res = s.split('%') - for i in xrange(1, len(res)): - item = res[i] + # fastpath + if len(res) == 1: + return s + s = res[0] + for item in res[1:]: try: - res[i] = _hextochr[item[:2]] + item[2:] + s += _hextochr[item[:2]] + item[2:] except KeyError: - res[i] = '%' + item + s += '%' + item except UnicodeDecodeError: - res[i] = unichr(int(item[:2], 16)) + item[2:] - return "".join(res) + s += unichr(int(item[:2], 16)) + item[2:] + return s def parse_qs(qs, keep_blank_values=0, strict_parsing=0): """Parse a query given as a string argument. From python-checkins at python.org Tue May 25 17:26:22 2010 From: python-checkins at python.org (r.david.murray) Date: Tue, 25 May 2010 17:26:22 +0200 (CEST) Subject: [Python-checkins] r81519 - python/branches/py3k Message-ID: <20100525152622.03125EE982@mail.python.org> Author: r.david.murray Date: Tue May 25 17:26:21 2010 New Revision: 81519 Log: Blocked revisions 81518 via svnmerge ........ r81518 | r.david.murray | 2010-05-25 11:20:46 -0400 (Tue, 25 May 2010) | 8 lines Issue 8143: sync unquote in urlparse with urllib; add comment about doing so. unquote is duplicated in the two files to avoid a circular reference. (This is fixed in Python3.) Updates keep getting made to the public unquote without fixing the urlparse one, however, so this fix syncs the two and adds a comment to both to make sure changes are applied to both. ........ Modified: python/branches/py3k/ (props changed) From python-checkins at python.org Tue May 25 17:28:16 2010 From: python-checkins at python.org (r.david.murray) Date: Tue, 25 May 2010 17:28:16 +0200 (CEST) Subject: [Python-checkins] r81520 - python/branches/release26-maint Message-ID: <20100525152816.1A6D6EE982@mail.python.org> Author: r.david.murray Date: Tue May 25 17:28:15 2010 New Revision: 81520 Log: Blocked revisions 81518 via svnmerge ........ r81518 | r.david.murray | 2010-05-25 11:20:46 -0400 (Tue, 25 May 2010) | 8 lines Issue 8143: sync unquote in urlparse with urllib; add comment about doing so. unquote is duplicated in the two files to avoid a circular reference. (This is fixed in Python3.) Updates keep getting made to the public unquote without fixing the urlparse one, however, so this fix syncs the two and adds a comment to both to make sure changes are applied to both. ........ Modified: python/branches/release26-maint/ (props changed) From python-checkins at python.org Tue May 25 17:32:06 2010 From: python-checkins at python.org (r.david.murray) Date: Tue, 25 May 2010 17:32:06 +0200 (CEST) Subject: [Python-checkins] r81521 - python/trunk/Doc/library/urlparse.rst Message-ID: <20100525153206.4BD71EE982@mail.python.org> Author: r.david.murray Date: Tue May 25 17:32:06 2010 New Revision: 81521 Log: Issue 8818: urlparse/urlsplit keyword is 'scheme', not 'default_scheme'. Modified: python/trunk/Doc/library/urlparse.rst Modified: python/trunk/Doc/library/urlparse.rst ============================================================================== --- python/trunk/Doc/library/urlparse.rst (original) +++ python/trunk/Doc/library/urlparse.rst Tue May 25 17:32:06 2010 @@ -36,7 +36,7 @@ The :mod:`urlparse` module defines the following functions: -.. function:: urlparse(urlstring[, default_scheme[, allow_fragments]]) +.. function:: urlparse(urlstring[, scheme[, allow_fragments]]) Parse a URL into six components, returning a 6-tuple. This corresponds to the general structure of a URL: ``scheme://netloc/path;parameters?query#fragment``. @@ -58,7 +58,7 @@ >>> o.geturl() 'http://www.cwi.nl:80/%7Eguido/Python.html' - If the *default_scheme* argument is specified, it gives the default addressing + If the *scheme* argument is specified, it gives the default addressing scheme, to be used only if the URL does not specify one. The default value for this argument is the empty string. @@ -161,7 +161,7 @@ equivalent). -.. function:: urlsplit(urlstring[, default_scheme[, allow_fragments]]) +.. function:: urlsplit(urlstring[, scheme[, allow_fragments]]) This is similar to :func:`urlparse`, but does not split the params from the URL. This should generally be used instead of :func:`urlparse` if the more recent URL From python-checkins at python.org Tue May 25 17:36:46 2010 From: python-checkins at python.org (r.david.murray) Date: Tue, 25 May 2010 17:36:46 +0200 (CEST) Subject: [Python-checkins] r81522 - in python/branches/py3k: Doc/library/urllib.parse.rst Message-ID: <20100525153646.936D9EE983@mail.python.org> Author: r.david.murray Date: Tue May 25 17:36:46 2010 New Revision: 81522 Log: Recorded merge of revisions 81521 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r81521 | r.david.murray | 2010-05-25 11:32:06 -0400 (Tue, 25 May 2010) | 2 lines Issue 8818: urlparse/urlsplit keyword is 'scheme', not 'default_scheme'. ........ Modified: python/branches/py3k/ (props changed) python/branches/py3k/Doc/library/urllib.parse.rst Modified: python/branches/py3k/Doc/library/urllib.parse.rst ============================================================================== --- python/branches/py3k/Doc/library/urllib.parse.rst (original) +++ python/branches/py3k/Doc/library/urllib.parse.rst Tue May 25 17:36:46 2010 @@ -26,7 +26,7 @@ The :mod:`urllib.parse` module defines the following functions: -.. function:: urlparse(urlstring, default_scheme='', allow_fragments=True) +.. function:: urlparse(urlstring, scheme='', allow_fragments=True) Parse a URL into six components, returning a 6-tuple. This corresponds to the general structure of a URL: ``scheme://netloc/path;parameters?query#fragment``. @@ -48,7 +48,7 @@ >>> o.geturl() 'http://www.cwi.nl:80/%7Eguido/Python.html' - If the *default_scheme* argument is specified, it gives the default addressing + If the *scheme* argument is specified, it gives the default addressing scheme, to be used only if the URL does not specify one. The default value for this argument is the empty string. @@ -142,7 +142,7 @@ states that these are equivalent). -.. function:: urlsplit(urlstring, default_scheme='', allow_fragments=True) +.. function:: urlsplit(urlstring, scheme='', allow_fragments=True) This is similar to :func:`urlparse`, but does not split the params from the URL. This should generally be used instead of :func:`urlparse` if the more recent URL From python-checkins at python.org Tue May 25 17:49:57 2010 From: python-checkins at python.org (r.david.murray) Date: Tue, 25 May 2010 17:49:57 +0200 (CEST) Subject: [Python-checkins] r81523 - in python/branches/release26-maint: Doc/library/urlparse.rst Message-ID: <20100525154957.7CECCEE985@mail.python.org> Author: r.david.murray Date: Tue May 25 17:49:57 2010 New Revision: 81523 Log: Merged revisions 81521 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r81521 | r.david.murray | 2010-05-25 11:32:06 -0400 (Tue, 25 May 2010) | 2 lines Issue 8818: urlparse/urlsplit keyword is 'scheme', not 'default_scheme'. ........ Modified: python/branches/release26-maint/ (props changed) python/branches/release26-maint/Doc/library/urlparse.rst Modified: python/branches/release26-maint/Doc/library/urlparse.rst ============================================================================== --- python/branches/release26-maint/Doc/library/urlparse.rst (original) +++ python/branches/release26-maint/Doc/library/urlparse.rst Tue May 25 17:49:57 2010 @@ -36,7 +36,7 @@ The :mod:`urlparse` module defines the following functions: -.. function:: urlparse(urlstring[, default_scheme[, allow_fragments]]) +.. function:: urlparse(urlstring[, scheme[, allow_fragments]]) Parse a URL into six components, returning a 6-tuple. This corresponds to the general structure of a URL: ``scheme://netloc/path;parameters?query#fragment``. @@ -58,7 +58,7 @@ >>> o.geturl() 'http://www.cwi.nl:80/%7Eguido/Python.html' - If the *default_scheme* argument is specified, it gives the default addressing + If the *scheme* argument is specified, it gives the default addressing scheme, to be used only if the URL does not specify one. The default value for this argument is the empty string. @@ -157,7 +157,7 @@ equivalent). -.. function:: urlsplit(urlstring[, default_scheme[, allow_fragments]]) +.. function:: urlsplit(urlstring[, scheme[, allow_fragments]]) This is similar to :func:`urlparse`, but does not split the params from the URL. This should generally be used instead of :func:`urlparse` if the more recent URL From python-checkins at python.org Tue May 25 17:54:24 2010 From: python-checkins at python.org (r.david.murray) Date: Tue, 25 May 2010 17:54:24 +0200 (CEST) Subject: [Python-checkins] r81524 - in python/branches/release31-maint: Doc/library/urllib.parse.rst Message-ID: <20100525155424.6C6CCEE986@mail.python.org> Author: r.david.murray Date: Tue May 25 17:54:24 2010 New Revision: 81524 Log: Merged revisions 81522 via svnmerge from svn+ssh://pythondev at svn.python.org/python/branches/py3k ................ r81522 | r.david.murray | 2010-05-25 11:36:46 -0400 (Tue, 25 May 2010) | 9 lines Recorded merge of revisions 81521 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r81521 | r.david.murray | 2010-05-25 11:32:06 -0400 (Tue, 25 May 2010) | 2 lines Issue 8818: urlparse/urlsplit keyword is 'scheme', not 'default_scheme'. ........ ................ Modified: python/branches/release31-maint/ (props changed) python/branches/release31-maint/Doc/library/urllib.parse.rst Modified: python/branches/release31-maint/Doc/library/urllib.parse.rst ============================================================================== --- python/branches/release31-maint/Doc/library/urllib.parse.rst (original) +++ python/branches/release31-maint/Doc/library/urllib.parse.rst Tue May 25 17:54:24 2010 @@ -26,7 +26,7 @@ The :mod:`urllib.parse` module defines the following functions: -.. function:: urlparse(urlstring, default_scheme='', allow_fragments=True) +.. function:: urlparse(urlstring, scheme='', allow_fragments=True) Parse a URL into six components, returning a 6-tuple. This corresponds to the general structure of a URL: ``scheme://netloc/path;parameters?query#fragment``. @@ -48,7 +48,7 @@ >>> o.geturl() 'http://www.cwi.nl:80/%7Eguido/Python.html' - If the *default_scheme* argument is specified, it gives the default addressing + If the *scheme* argument is specified, it gives the default addressing scheme, to be used only if the URL does not specify one. The default value for this argument is the empty string. @@ -139,7 +139,7 @@ states that these are equivalent). -.. function:: urlsplit(urlstring, default_scheme='', allow_fragments=True) +.. function:: urlsplit(urlstring, scheme='', allow_fragments=True) This is similar to :func:`urlparse`, but does not split the params from the URL. This should generally be used instead of :func:`urlparse` if the more recent URL From python-checkins at python.org Tue May 25 21:01:09 2010 From: python-checkins at python.org (mark.dickinson) Date: Tue, 25 May 2010 21:01:09 +0200 (CEST) Subject: [Python-checkins] r81525 - in python/trunk/Lib/test: test_builtin.py test_enumerate.py test_long.py Message-ID: <20100525190109.19299EE985@mail.python.org> Author: mark.dickinson Date: Tue May 25 21:01:08 2010 New Revision: 81525 Log: Issue #8816: Extra tests for some built-in functions. These tests are ports of IronPython tests. Thanks Gregory Nofi. Modified: python/trunk/Lib/test/test_builtin.py python/trunk/Lib/test/test_enumerate.py python/trunk/Lib/test/test_long.py Modified: python/trunk/Lib/test/test_builtin.py ============================================================================== --- python/trunk/Lib/test/test_builtin.py (original) +++ python/trunk/Lib/test/test_builtin.py Tue May 25 21:01:08 2010 @@ -90,6 +90,16 @@ self.assertEqual(abs(-1234L), 1234L) # str self.assertRaises(TypeError, abs, 'a') + # bool + self.assertEqual(abs(True), 1) + self.assertEqual(abs(False), 0) + # other + self.assertRaises(TypeError, abs) + self.assertRaises(TypeError, abs, None) + class AbsClass(object): + def __abs__(self): + return -5 + self.assertEqual(abs(AbsClass()), -5) def test_all(self): self.assertEqual(all([2, 4, 6]), True) @@ -152,19 +162,44 @@ def test_callable(self): self.assertTrue(callable(len)) + self.assertFalse(callable("a")) + self.assertTrue(callable(callable)) + self.assertTrue(callable(lambda x, y: x + y)) + self.assertFalse(callable(__builtins__)) def f(): pass self.assertTrue(callable(f)) - class C: + + class Classic: def meth(self): pass - self.assertTrue(callable(C)) - x = C() - self.assertTrue(callable(x.meth)) - self.assertTrue(not callable(x)) - class D(C): + self.assertTrue(callable(Classic)) + c = Classic() + self.assertTrue(callable(c.meth)) + self.assertFalse(callable(c)) + + class NewStyle(object): + def meth(self): pass + self.assertTrue(callable(NewStyle)) + n = NewStyle() + self.assertTrue(callable(n.meth)) + self.assertFalse(callable(n)) + + # Classic and new-style classes evaluate __call__() differently + c.__call__ = None + self.assertTrue(callable(c)) + del c.__call__ + self.assertFalse(callable(c)) + n.__call__ = None + self.assertFalse(callable(n)) + del n.__call__ + self.assertFalse(callable(n)) + + class N2(object): def __call__(self): pass - y = D() - self.assertTrue(callable(y)) - y() + n2 = N2() + self.assertTrue(callable(n2)) + class N3(N2): pass + n3 = N3() + self.assertTrue(callable(n3)) def test_chr(self): self.assertEqual(chr(32), ' ') @@ -729,6 +764,11 @@ def __len__(self): raise ValueError self.assertRaises(ValueError, len, BadSeq()) + self.assertRaises(TypeError, len, 2) + class ClassicStyle: pass + class NewStyle(object): pass + self.assertRaises(AttributeError, len, ClassicStyle()) + self.assertRaises(TypeError, len, NewStyle()) def test_map(self): self.assertEqual( @@ -1188,9 +1228,10 @@ unlink(TESTFN) def test_reduce(self): - self.assertEqual(reduce(lambda x, y: x+y, ['a', 'b', 'c'], ''), 'abc') + add = lambda x, y: x+y + self.assertEqual(reduce(add, ['a', 'b', 'c'], ''), 'abc') self.assertEqual( - reduce(lambda x, y: x+y, [['a', 'c'], [], ['d', 'w']], []), + reduce(add, [['a', 'c'], [], ['d', 'w']], []), ['a','c','d','w'] ) self.assertEqual(reduce(lambda x, y: x*y, range(2,8), 1), 5040) @@ -1198,15 +1239,23 @@ reduce(lambda x, y: x*y, range(2,21), 1L), 2432902008176640000L ) - self.assertEqual(reduce(lambda x, y: x+y, Squares(10)), 285) - self.assertEqual(reduce(lambda x, y: x+y, Squares(10), 0), 285) - self.assertEqual(reduce(lambda x, y: x+y, Squares(0), 0), 0) + self.assertEqual(reduce(add, Squares(10)), 285) + self.assertEqual(reduce(add, Squares(10), 0), 285) + self.assertEqual(reduce(add, Squares(0), 0), 0) self.assertRaises(TypeError, reduce) + self.assertRaises(TypeError, reduce, 42) self.assertRaises(TypeError, reduce, 42, 42) self.assertRaises(TypeError, reduce, 42, 42, 42) + self.assertRaises(TypeError, reduce, None, range(5)) + self.assertRaises(TypeError, reduce, add, 42) self.assertEqual(reduce(42, "1"), "1") # func is never called with one item self.assertEqual(reduce(42, "", "1"), "1") # func is never called with one item self.assertRaises(TypeError, reduce, 42, (42, 42)) + self.assertRaises(TypeError, reduce, add, []) # arg 2 must not be empty sequence with no initial value + self.assertRaises(TypeError, reduce, add, "") + self.assertRaises(TypeError, reduce, add, ()) + self.assertEqual(reduce(add, [], None), None) + self.assertEqual(reduce(add, [], 42), 42) class BadSeq: def __getitem__(self, index): @@ -1391,6 +1440,11 @@ b = 2 return vars() + class C_get_vars(object): + def getDict(self): + return {'a':2} + __dict__ = property(fget=getDict) + def test_vars(self): self.assertEqual(set(vars()), set(dir())) import sys @@ -1399,6 +1453,7 @@ self.assertEqual(self.get_vars_f2(), {'a': 1, 'b': 2}) self.assertRaises(TypeError, vars, 42, 42) self.assertRaises(TypeError, vars, 42) + self.assertEqual(vars(self.C_get_vars()), {'a':2}) def test_zip(self): a = (1, 2, 3) Modified: python/trunk/Lib/test/test_enumerate.py ============================================================================== --- python/trunk/Lib/test/test_enumerate.py (original) +++ python/trunk/Lib/test/test_enumerate.py Tue May 25 21:01:08 2010 @@ -204,6 +204,18 @@ self.fail("non-callable __reversed__ didn't raise!") self.assertEqual(rc, sys.getrefcount(r)) + def test_objmethods(self): + # Objects must have __len__() and __getitem__() implemented. + class NoLen(object): + def __getitem__(self): return 1 + nl = NoLen() + self.assertRaises(TypeError, reversed, nl) + + class NoGetItem(object): + def __len__(self): return 2 + ngi = NoGetItem() + self.assertRaises(TypeError, reversed, ngi) + class EnumerateStartTestCase(EnumerateTestCase): Modified: python/trunk/Lib/test/test_long.py ============================================================================== --- python/trunk/Lib/test/test_long.py (original) +++ python/trunk/Lib/test/test_long.py Tue May 25 21:01:08 2010 @@ -320,6 +320,9 @@ self.assertEqual(long(3.5), 3L) self.assertEqual(long(-3.5), -3L) self.assertEqual(long("-3"), -3L) + self.assertEqual(long("0b10", 2), 2L) + self.assertEqual(long("0o10", 8), 8L) + self.assertEqual(long("0x10", 16), 16L) if test_support.have_unicode: self.assertEqual(long(unicode("-3")), -3L) # Different base: From python-checkins at python.org Tue May 25 21:06:24 2010 From: python-checkins at python.org (mark.dickinson) Date: Tue, 25 May 2010 21:06:24 +0200 (CEST) Subject: [Python-checkins] r81526 - in python/branches/py3k: Lib/test/test_builtin.py Lib/test/test_enumerate.py Message-ID: <20100525190624.5A5A7EE9E2@mail.python.org> Author: mark.dickinson Date: Tue May 25 21:06:24 2010 New Revision: 81526 Log: Merged revisions 81525 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r81525 | mark.dickinson | 2010-05-25 20:01:08 +0100 (Tue, 25 May 2010) | 3 lines Issue #8816: Extra tests for some built-in functions. These tests are ports of IronPython tests. Thanks Gregory Nofi. ........ Modified: python/branches/py3k/ (props changed) python/branches/py3k/Lib/test/test_builtin.py python/branches/py3k/Lib/test/test_enumerate.py Modified: python/branches/py3k/Lib/test/test_builtin.py ============================================================================== --- python/branches/py3k/Lib/test/test_builtin.py (original) +++ python/branches/py3k/Lib/test/test_builtin.py Tue May 25 21:06:24 2010 @@ -124,6 +124,16 @@ self.assertEqual(abs(-3.14), 3.14) # str self.assertRaises(TypeError, abs, 'a') + # bool + self.assertEqual(abs(True), 1) + self.assertEqual(abs(False), 0) + # other + self.assertRaises(TypeError, abs) + self.assertRaises(TypeError, abs, None) + class AbsClass(object): + def __abs__(self): + return -5 + self.assertEqual(abs(AbsClass()), -5) def test_all(self): self.assertEqual(all([2, 4, 6]), True) @@ -600,6 +610,8 @@ def __len__(self): return sys.maxsize + 1 self.assertRaises(OverflowError, len, HugeLen()) + class NoLenMethod(object): pass + self.assertRaises(TypeError, len, NoLenMethod()) def test_map(self): self.assertEqual( @@ -1187,6 +1199,11 @@ b = 2 return vars() + class C_get_vars(object): + def getDict(self): + return {'a':2} + __dict__ = property(fget=getDict) + def test_vars(self): self.assertEqual(set(vars()), set(dir())) import sys @@ -1195,6 +1212,7 @@ self.assertEqual(self.get_vars_f2(), {'a': 1, 'b': 2}) self.assertRaises(TypeError, vars, 42, 42) self.assertRaises(TypeError, vars, 42) + self.assertEqual(vars(self.C_get_vars()), {'a':2}) def test_zip(self): a = (1, 2, 3) Modified: python/branches/py3k/Lib/test/test_enumerate.py ============================================================================== --- python/branches/py3k/Lib/test/test_enumerate.py (original) +++ python/branches/py3k/Lib/test/test_enumerate.py Tue May 25 21:06:24 2010 @@ -198,6 +198,18 @@ self.fail("non-callable __reversed__ didn't raise!") self.assertEqual(rc, sys.getrefcount(r)) + def test_objmethods(self): + # Objects must have __len__() and __getitem__() implemented. + class NoLen(object): + def __getitem__(self): return 1 + nl = NoLen() + self.assertRaises(TypeError, reversed, nl) + + class NoGetItem(object): + def __len__(self): return 2 + ngi = NoGetItem() + self.assertRaises(TypeError, reversed, ngi) + class EnumerateStartTestCase(EnumerateTestCase): From python-checkins at python.org Tue May 25 21:44:50 2010 From: python-checkins at python.org (mark.dickinson) Date: Tue, 25 May 2010 21:44:50 +0200 (CEST) Subject: [Python-checkins] r81527 - python/trunk/Lib/test/test_enumerate.py Message-ID: <20100525194450.00FCEEE983@mail.python.org> Author: mark.dickinson Date: Tue May 25 21:44:49 2010 New Revision: 81527 Log: Fix a NameError in test_enumerate. Modified: python/trunk/Lib/test/test_enumerate.py Modified: python/trunk/Lib/test/test_enumerate.py ============================================================================== --- python/trunk/Lib/test/test_enumerate.py (original) +++ python/trunk/Lib/test/test_enumerate.py Tue May 25 21:44:49 2010 @@ -245,7 +245,7 @@ if verbose and hasattr(sys, "gettotalrefcount"): counts = [None] * 5 for i in xrange(len(counts)): - test_support.run_unittest(*testclasses) + test_support.run_unittest(__name__) counts[i] = sys.gettotalrefcount() print counts From python-checkins at python.org Tue May 25 21:46:20 2010 From: python-checkins at python.org (mark.dickinson) Date: Tue, 25 May 2010 21:46:20 +0200 (CEST) Subject: [Python-checkins] r81528 - in python/branches/py3k: Lib/test/test_enumerate.py Message-ID: <20100525194620.68AB2E89C@mail.python.org> Author: mark.dickinson Date: Tue May 25 21:46:20 2010 New Revision: 81528 Log: Merged revisions 81527 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r81527 | mark.dickinson | 2010-05-25 20:44:49 +0100 (Tue, 25 May 2010) | 1 line Fix a NameError in test_enumerate. ........ Modified: python/branches/py3k/ (props changed) python/branches/py3k/Lib/test/test_enumerate.py Modified: python/branches/py3k/Lib/test/test_enumerate.py ============================================================================== --- python/branches/py3k/Lib/test/test_enumerate.py (original) +++ python/branches/py3k/Lib/test/test_enumerate.py Tue May 25 21:46:20 2010 @@ -239,7 +239,7 @@ if verbose and hasattr(sys, "gettotalrefcount"): counts = [None] * 5 for i in range(len(counts)): - support.run_unittest(*testclasses) + support.run_unittest(__name__) counts[i] = sys.gettotalrefcount() print(counts) From python-checkins at python.org Tue May 25 21:47:22 2010 From: python-checkins at python.org (mark.dickinson) Date: Tue, 25 May 2010 21:47:22 +0200 (CEST) Subject: [Python-checkins] r81529 - in python/branches/release26-maint: Lib/test/test_enumerate.py Message-ID: <20100525194722.CA807E89C@mail.python.org> Author: mark.dickinson Date: Tue May 25 21:47:22 2010 New Revision: 81529 Log: Merged revisions 81527 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r81527 | mark.dickinson | 2010-05-25 20:44:49 +0100 (Tue, 25 May 2010) | 1 line Fix a NameError in test_enumerate. ........ Modified: python/branches/release26-maint/ (props changed) python/branches/release26-maint/Lib/test/test_enumerate.py Modified: python/branches/release26-maint/Lib/test/test_enumerate.py ============================================================================== --- python/branches/release26-maint/Lib/test/test_enumerate.py (original) +++ python/branches/release26-maint/Lib/test/test_enumerate.py Tue May 25 21:47:22 2010 @@ -227,7 +227,7 @@ if verbose and hasattr(sys, "gettotalrefcount"): counts = [None] * 5 for i in xrange(len(counts)): - test_support.run_unittest(*testclasses) + test_support.run_unittest(__name__) counts[i] = sys.gettotalrefcount() print counts From python-checkins at python.org Tue May 25 21:48:15 2010 From: python-checkins at python.org (mark.dickinson) Date: Tue, 25 May 2010 21:48:15 +0200 (CEST) Subject: [Python-checkins] r81530 - in python/branches/release31-maint: Lib/test/test_enumerate.py Message-ID: <20100525194815.5433CE89C@mail.python.org> Author: mark.dickinson Date: Tue May 25 21:48:15 2010 New Revision: 81530 Log: Merged revisions 81528 via svnmerge from svn+ssh://pythondev at svn.python.org/python/branches/py3k ................ r81528 | mark.dickinson | 2010-05-25 20:46:20 +0100 (Tue, 25 May 2010) | 9 lines Merged revisions 81527 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r81527 | mark.dickinson | 2010-05-25 20:44:49 +0100 (Tue, 25 May 2010) | 1 line Fix a NameError in test_enumerate. ........ ................ Modified: python/branches/release31-maint/ (props changed) python/branches/release31-maint/Lib/test/test_enumerate.py Modified: python/branches/release31-maint/Lib/test/test_enumerate.py ============================================================================== --- python/branches/release31-maint/Lib/test/test_enumerate.py (original) +++ python/branches/release31-maint/Lib/test/test_enumerate.py Tue May 25 21:48:15 2010 @@ -227,7 +227,7 @@ if verbose and hasattr(sys, "gettotalrefcount"): counts = [None] * 5 for i in range(len(counts)): - support.run_unittest(*testclasses) + support.run_unittest(__name__) counts[i] = sys.gettotalrefcount() print(counts) From python-checkins at python.org Tue May 25 22:06:02 2010 From: python-checkins at python.org (martin.v.loewis) Date: Tue, 25 May 2010 22:06:02 +0200 (CEST) Subject: [Python-checkins] r81531 - python/trunk/Misc/developers.txt Message-ID: <20100525200602.401DCEE9E6@mail.python.org> Author: martin.v.loewis Date: Tue May 25 22:06:02 2010 New Revision: 81531 Log: Add Alexander Belopolsky. Modified: python/trunk/Misc/developers.txt Modified: python/trunk/Misc/developers.txt ============================================================================== --- python/trunk/Misc/developers.txt (original) +++ python/trunk/Misc/developers.txt Tue May 25 22:06:02 2010 @@ -20,6 +20,9 @@ Permissions History ------------------- +- Alexander Belopolsky was given commit access on May 25 2010 + by MvL at suggestion of Mark Dickinson. + - Tim Golden was given commit access on April 21 2010 by MvL, at suggestion of Michael Foord. From python-checkins at python.org Tue May 25 22:07:11 2010 From: python-checkins at python.org (martin.v.loewis) Date: Tue, 25 May 2010 22:07:11 +0200 (CEST) Subject: [Python-checkins] r81532 - in python/branches/py3k: Misc/developers.txt Message-ID: <20100525200711.A2002EE9F5@mail.python.org> Author: martin.v.loewis Date: Tue May 25 22:07:11 2010 New Revision: 81532 Log: Merged revisions 81531 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r81531 | martin.v.loewis | 2010-05-25 22:06:02 +0200 (Di, 25 Mai 2010) | 2 lines Add Alexander Belopolsky. ........ Modified: python/branches/py3k/ (props changed) python/branches/py3k/Misc/developers.txt Modified: python/branches/py3k/Misc/developers.txt ============================================================================== --- python/branches/py3k/Misc/developers.txt (original) +++ python/branches/py3k/Misc/developers.txt Tue May 25 22:07:11 2010 @@ -20,6 +20,9 @@ Permissions History ------------------- +- Alexander Belopolsky was given commit access on May 25 2010 + by MvL at suggestion of Mark Dickinson. + - Tim Golden was given commit access on April 21 2010 by MvL, at suggestion of Michael Foord. From python-checkins at python.org Tue May 25 23:12:34 2010 From: python-checkins at python.org (victor.stinner) Date: Tue, 25 May 2010 23:12:34 +0200 (CEST) Subject: [Python-checkins] r81533 - in python/branches/py3k: Lib/base64.py Lib/test/test_base64.py Misc/NEWS Message-ID: <20100525211234.EF2B0EE9F7@mail.python.org> Author: victor.stinner Date: Tue May 25 23:12:34 2010 New Revision: 81533 Log: Issue #4769: Fix main() function of the base64 module, use sys.stdin.buffer and sys.stdout.buffer (instead of sys.stdin and sys.stdout) to use the bytes API Modified: python/branches/py3k/Lib/base64.py python/branches/py3k/Lib/test/test_base64.py python/branches/py3k/Misc/NEWS Modified: python/branches/py3k/Lib/base64.py ============================================================================== --- python/branches/py3k/Lib/base64.py (original) +++ python/branches/py3k/Lib/base64.py Tue May 25 23:12:34 2010 @@ -383,9 +383,9 @@ if o == '-u': func = decode if o == '-t': test(); return if args and args[0] != '-': - func(open(args[0], 'rb'), sys.stdout) + func(open(args[0], 'rb'), sys.stdout.buffer) else: - func(sys.stdin, sys.stdout) + func(sys.stdin.buffer, sys.stdout.buffer) def test(): Modified: python/branches/py3k/Lib/test/test_base64.py ============================================================================== --- python/branches/py3k/Lib/test/test_base64.py (original) +++ python/branches/py3k/Lib/test/test_base64.py Tue May 25 23:12:34 2010 @@ -2,6 +2,8 @@ from test import support import base64 import binascii +import sys +import subprocess @@ -208,6 +210,38 @@ +class TestMain(unittest.TestCase): + def get_output(self, *args, **options): + args = (sys.executable, '-m', 'base64') + args + return subprocess.check_output(args, **options) + + def test_encode_decode(self): + output = self.get_output('-t') + self.assertSequenceEqual(output.splitlines(), ( + b"b'Aladdin:open sesame'", + br"b'QWxhZGRpbjpvcGVuIHNlc2FtZQ==\n'", + b"b'Aladdin:open sesame'", + )) + + def test_encode_file(self): + with open(support.TESTFN, 'wb') as fp: + fp.write(b'a\xffb\n') + + output = self.get_output('-e', support.TESTFN) + self.assertEquals(output.rstrip(), b'Yf9iCg==') + + with open(support.TESTFN, 'rb') as fp: + output = self.get_output('-e', stdin=fp) + self.assertEquals(output.rstrip(), b'Yf9iCg==') + + def test_decode(self): + with open(support.TESTFN, 'wb') as fp: + fp.write(b'Yf9iCg==') + output = self.get_output('-d', support.TESTFN) + self.assertEquals(output, b'a\xffb\n') + + + def test_main(): support.run_unittest(__name__) Modified: python/branches/py3k/Misc/NEWS ============================================================================== --- python/branches/py3k/Misc/NEWS (original) +++ python/branches/py3k/Misc/NEWS Tue May 25 23:12:34 2010 @@ -392,6 +392,10 @@ Library ------- +- Issue #4769: Fix main() function of the base64 module, use sys.stdin.buffer + and sys.stdout.buffer (instead of sys.stdin and sys.stdout) to use the bytes + API + - Issue #8770: now sysconfig displays information when it's called as a script. Initial idea by Sridhar Ratnakumar. From python-checkins at python.org Tue May 25 23:32:42 2010 From: python-checkins at python.org (victor.stinner) Date: Tue, 25 May 2010 23:32:42 +0200 (CEST) Subject: [Python-checkins] r81534 - in python/branches/release31-maint: Lib/base64.py Lib/test/test_base64.py Misc/NEWS Message-ID: <20100525213242.3DE11EE98F@mail.python.org> Author: victor.stinner Date: Tue May 25 23:32:42 2010 New Revision: 81534 Log: Merged revisions 81533 via svnmerge from svn+ssh://pythondev at svn.python.org/python/branches/py3k ........ r81533 | victor.stinner | 2010-05-25 23:12:34 +0200 (mar., 25 mai 2010) | 3 lines Issue #4769: Fix main() function of the base64 module, use sys.stdin.buffer and sys.stdout.buffer (instead of sys.stdin and sys.stdout) to use the bytes API ........ Modified: python/branches/release31-maint/ (props changed) python/branches/release31-maint/Lib/base64.py python/branches/release31-maint/Lib/test/test_base64.py python/branches/release31-maint/Misc/NEWS Modified: python/branches/release31-maint/Lib/base64.py ============================================================================== --- python/branches/release31-maint/Lib/base64.py (original) +++ python/branches/release31-maint/Lib/base64.py Tue May 25 23:32:42 2010 @@ -383,9 +383,9 @@ if o == '-u': func = decode if o == '-t': test(); return if args and args[0] != '-': - func(open(args[0], 'rb'), sys.stdout) + func(open(args[0], 'rb'), sys.stdout.buffer) else: - func(sys.stdin, sys.stdout) + func(sys.stdin.buffer, sys.stdout.buffer) def test(): Modified: python/branches/release31-maint/Lib/test/test_base64.py ============================================================================== --- python/branches/release31-maint/Lib/test/test_base64.py (original) +++ python/branches/release31-maint/Lib/test/test_base64.py Tue May 25 23:32:42 2010 @@ -2,6 +2,8 @@ from test import support import base64 import binascii +import sys +import subprocess @@ -208,6 +210,38 @@ +class TestMain(unittest.TestCase): + def get_output(self, *args, **options): + args = (sys.executable, '-m', 'base64') + args + return subprocess.check_output(args, **options) + + def test_encode_decode(self): + output = self.get_output('-t') + self.assertSequenceEqual(output.splitlines(), ( + b"b'Aladdin:open sesame'", + br"b'QWxhZGRpbjpvcGVuIHNlc2FtZQ==\n'", + b"b'Aladdin:open sesame'", + )) + + def test_encode_file(self): + with open(support.TESTFN, 'wb') as fp: + fp.write(b'a\xffb\n') + + output = self.get_output('-e', support.TESTFN) + self.assertEquals(output.rstrip(), b'Yf9iCg==') + + with open(support.TESTFN, 'rb') as fp: + output = self.get_output('-e', stdin=fp) + self.assertEquals(output.rstrip(), b'Yf9iCg==') + + def test_decode(self): + with open(support.TESTFN, 'wb') as fp: + fp.write(b'Yf9iCg==') + output = self.get_output('-d', support.TESTFN) + self.assertEquals(output, b'a\xffb\n') + + + def test_main(): support.run_unittest(__name__) Modified: python/branches/release31-maint/Misc/NEWS ============================================================================== --- python/branches/release31-maint/Misc/NEWS (original) +++ python/branches/release31-maint/Misc/NEWS Tue May 25 23:32:42 2010 @@ -54,6 +54,10 @@ Library ------- +- Issue #4769: Fix main() function of the base64 module, use sys.stdin.buffer + and sys.stdout.buffer (instead of sys.stdin and sys.stdout) to use the bytes + API + - Issue #6662: Fix parsing of malformatted charref (&#bad;), patch written by Fredrik H??rd From python-checkins at python.org Wed May 26 00:17:22 2010 From: python-checkins at python.org (victor.stinner) Date: Wed, 26 May 2010 00:17:22 +0200 (CEST) Subject: [Python-checkins] r81535 - python/branches/py3k/Lib/test/test_base64.py Message-ID: <20100525221722.9BA58EEA04@mail.python.org> Author: victor.stinner Date: Wed May 26 00:17:22 2010 New Revision: 81535 Log: Fix the new TestMain.test_decode() of test_base64 for Windows Modified: python/branches/py3k/Lib/test/test_base64.py Modified: python/branches/py3k/Lib/test/test_base64.py ============================================================================== --- python/branches/py3k/Lib/test/test_base64.py (original) +++ python/branches/py3k/Lib/test/test_base64.py Wed May 26 00:17:22 2010 @@ -238,7 +238,7 @@ with open(support.TESTFN, 'wb') as fp: fp.write(b'Yf9iCg==') output = self.get_output('-d', support.TESTFN) - self.assertEquals(output, b'a\xffb\n') + self.assertEquals(output.rstrip(), b'a\xffb') From python-checkins at python.org Wed May 26 00:18:30 2010 From: python-checkins at python.org (victor.stinner) Date: Wed, 26 May 2010 00:18:30 +0200 (CEST) Subject: [Python-checkins] r81536 - in python/branches/release31-maint: Lib/test/test_base64.py Message-ID: <20100525221830.68853EEA03@mail.python.org> Author: victor.stinner Date: Wed May 26 00:18:30 2010 New Revision: 81536 Log: Merged revisions 81535 via svnmerge from svn+ssh://pythondev at svn.python.org/python/branches/py3k ........ r81535 | victor.stinner | 2010-05-26 00:17:22 +0200 (mer., 26 mai 2010) | 2 lines Fix the new TestMain.test_decode() of test_base64 for Windows ........ Modified: python/branches/release31-maint/ (props changed) python/branches/release31-maint/Lib/test/test_base64.py Modified: python/branches/release31-maint/Lib/test/test_base64.py ============================================================================== --- python/branches/release31-maint/Lib/test/test_base64.py (original) +++ python/branches/release31-maint/Lib/test/test_base64.py Wed May 26 00:18:30 2010 @@ -238,7 +238,7 @@ with open(support.TESTFN, 'wb') as fp: fp.write(b'Yf9iCg==') output = self.get_output('-d', support.TESTFN) - self.assertEquals(output, b'a\xffb\n') + self.assertEquals(output.rstrip(), b'a\xffb') From python-checkins at python.org Wed May 26 00:30:33 2010 From: python-checkins at python.org (victor.stinner) Date: Wed, 26 May 2010 00:30:33 +0200 (CEST) Subject: [Python-checkins] r81537 - in python/trunk: Lib/test/test_sys.py Misc/NEWS Python/pythonrun.c Message-ID: <20100525223033.2F14FEE9A2@mail.python.org> Author: victor.stinner Date: Wed May 26 00:30:32 2010 New Revision: 81537 Log: Issue #3798: Write sys.exit() message to sys.stderr to use stderr encoding and error handler, instead of writing to the C stderr file in utf-8 Modified: python/trunk/Lib/test/test_sys.py python/trunk/Misc/NEWS python/trunk/Python/pythonrun.c Modified: python/trunk/Lib/test/test_sys.py ============================================================================== --- python/trunk/Lib/test/test_sys.py (original) +++ python/trunk/Lib/test/test_sys.py Wed May 26 00:30:32 2010 @@ -178,6 +178,26 @@ "raise SystemExit(47)"]) self.assertEqual(rc, 47) + def check_exit_message(code, expected, env=None): + process = subprocess.Popen([sys.executable, "-c", code], + stderr=subprocess.PIPE, env=env) + stdout, stderr = process.communicate() + self.assertEqual(process.returncode, 1) + self.assertTrue(stderr.startswith(expected), + "%s doesn't start with %s" % (repr(stderr), repr(expected))) + + # test that stderr buffer if flushed before the exit message is written + # into stderr + check_exit_message( + r'import sys; sys.stderr.write("unflushed,"); sys.exit("message")', + b"unflushed,message") + + # test that the unicode message is encoded to the stderr encoding + env = os.environ.copy() + env['PYTHONIOENCODING'] = 'latin-1' + check_exit_message( + r'import sys; sys.exit(u"h\xe9")', + b"h\xe9", env=env) def test_getdefaultencoding(self): if test.test_support.have_unicode: Modified: python/trunk/Misc/NEWS ============================================================================== --- python/trunk/Misc/NEWS (original) +++ python/trunk/Misc/NEWS Wed May 26 00:30:32 2010 @@ -12,6 +12,9 @@ Core and Builtins ----------------- +- Issue #3798: Write sys.exit() message to sys.stderr to use stderr encoding + and error handler, instead of writing to the C stderr file in utf-8 + - Issue #7902: When using explicit relative import syntax, don't try implicit relative import semantics. Modified: python/trunk/Python/pythonrun.c ============================================================================== --- python/trunk/Python/pythonrun.c (original) +++ python/trunk/Python/pythonrun.c Wed May 26 00:30:32 2010 @@ -1106,7 +1106,13 @@ if (PyInt_Check(value)) exitcode = (int)PyInt_AsLong(value); else { - PyObject_Print(value, stderr, Py_PRINT_RAW); + PyObject *sys_stderr = PySys_GetObject("stderr"); + if (sys_stderr != NULL && sys_stderr != Py_None) { + PyFile_WriteObject(value, sys_stderr, Py_PRINT_RAW); + } else { + PyObject_Print(value, stderr, Py_PRINT_RAW); + fflush(stderr); + } PySys_WriteStderr("\n"); exitcode = 1; } From python-checkins at python.org Wed May 26 00:35:40 2010 From: python-checkins at python.org (victor.stinner) Date: Wed, 26 May 2010 00:35:40 +0200 (CEST) Subject: [Python-checkins] r81538 - python/branches/py3k Message-ID: <20100525223540.D31E7EE99C@mail.python.org> Author: victor.stinner Date: Wed May 26 00:35:40 2010 New Revision: 81538 Log: Blocked revisions 81537 via svnmerge ........ r81537 | victor.stinner | 2010-05-26 00:30:32 +0200 (mer., 26 mai 2010) | 3 lines Issue #3798: Write sys.exit() message to sys.stderr to use stderr encoding and error handler, instead of writing to the C stderr file in utf-8 ........ py3k was already fixed by r81252. Modified: python/branches/py3k/ (props changed) From python-checkins at python.org Wed May 26 00:40:38 2010 From: python-checkins at python.org (victor.stinner) Date: Wed, 26 May 2010 00:40:38 +0200 (CEST) Subject: [Python-checkins] r81539 - in python/branches/release26-maint: Lib/test/test_sys.py Misc/NEWS Python/pythonrun.c Message-ID: <20100525224038.F31DEEE983@mail.python.org> Author: victor.stinner Date: Wed May 26 00:40:38 2010 New Revision: 81539 Log: Merged revisions 81537 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r81537 | victor.stinner | 2010-05-26 00:30:32 +0200 (mer., 26 mai 2010) | 3 lines Issue #3798: Write sys.exit() message to sys.stderr to use stderr encoding and error handler, instead of writing to the C stderr file in utf-8 ........ Modified: python/branches/release26-maint/ (props changed) python/branches/release26-maint/Lib/test/test_sys.py python/branches/release26-maint/Misc/NEWS python/branches/release26-maint/Python/pythonrun.c Modified: python/branches/release26-maint/Lib/test/test_sys.py ============================================================================== --- python/branches/release26-maint/Lib/test/test_sys.py (original) +++ python/branches/release26-maint/Lib/test/test_sys.py Wed May 26 00:40:38 2010 @@ -173,6 +173,26 @@ "raise SystemExit(47)"]) self.assertEqual(rc, 47) + def check_exit_message(code, expected, env=None): + process = subprocess.Popen([sys.executable, "-c", code], + stderr=subprocess.PIPE, env=env) + stdout, stderr = process.communicate() + self.assertEqual(process.returncode, 1) + self.assertTrue(stderr.startswith(expected), + "%s doesn't start with %s" % (repr(stderr), repr(expected))) + + # test that stderr buffer if flushed before the exit message is written + # into stderr + check_exit_message( + r'import sys; sys.stderr.write("unflushed,"); sys.exit("message")', + b"unflushed,message") + + # test that the unicode message is encoded to the stderr encoding + env = os.environ.copy() + env['PYTHONIOENCODING'] = 'latin-1' + check_exit_message( + r'import sys; sys.exit(u"h\xe9")', + b"h\xe9", env=env) def test_getdefaultencoding(self): if test.test_support.have_unicode: Modified: python/branches/release26-maint/Misc/NEWS ============================================================================== --- python/branches/release26-maint/Misc/NEWS (original) +++ python/branches/release26-maint/Misc/NEWS Wed May 26 00:40:38 2010 @@ -12,6 +12,9 @@ Core and Builtins ----------------- +- Issue #3798: Write sys.exit() message to sys.stderr to use stderr encoding + and error handler, instead of writing to the C stderr file in utf-8 + - Issue #7902: When using explicit relative import syntax, don't try implicit relative import semantics. Modified: python/branches/release26-maint/Python/pythonrun.c ============================================================================== --- python/branches/release26-maint/Python/pythonrun.c (original) +++ python/branches/release26-maint/Python/pythonrun.c Wed May 26 00:40:38 2010 @@ -1111,7 +1111,13 @@ if (PyInt_Check(value)) exitcode = (int)PyInt_AsLong(value); else { - PyObject_Print(value, stderr, Py_PRINT_RAW); + PyObject *sys_stderr = PySys_GetObject("stderr"); + if (sys_stderr != NULL && sys_stderr != Py_None) { + PyFile_WriteObject(value, sys_stderr, Py_PRINT_RAW); + } else { + PyObject_Print(value, stderr, Py_PRINT_RAW); + fflush(stderr); + } PySys_WriteStderr("\n"); exitcode = 1; } From solipsis at pitrou.net Wed May 26 01:24:33 2010 From: solipsis at pitrou.net (solipsis at pitrou.net) Date: Wed, 26 May 2010 01:24:33 +0200 (CEST) Subject: [Python-checkins] Daily py3k reference leaks (r81532): sum=0 Message-ID: <20100525232433.9F57E1770A@ns6635.ovh.net> py3k results for svn r81532 (hg cset 8701f8c20862) -------------------------------------------------- Command line was: ['./python', '-m', 'test.regrtest', '-uall', '-R', '3:3:/home/antoine/py3k/refleaks/reflogSseHHM', '-x'] From nnorwitz at gmail.com Wed May 26 02:16:03 2010 From: nnorwitz at gmail.com (Neal Norwitz) Date: Tue, 25 May 2010 20:16:03 -0400 Subject: [Python-checkins] Python Regression Test Failures refleak (1) Message-ID: <20100526001603.GA4729@kbk-i386-bb.psfb.org> More important issues: ---------------------- test_bz2 leaked [0, 0, 80] references, sum=80 Less important issues: ---------------------- test_threadsignals leaked [0, 0, -8] references, sum=-8 From python-checkins at python.org Wed May 26 15:24:57 2010 From: python-checkins at python.org (brian.curtin) Date: Wed, 26 May 2010 15:24:57 +0200 (CEST) Subject: [Python-checkins] r81540 - in python/branches/release26-maint: Lib/test/test_winreg.py Misc/NEWS PC/_winreg.c Message-ID: <20100526132457.7B6C8F037@mail.python.org> Author: brian.curtin Date: Wed May 26 15:24:57 2010 New Revision: 81540 Log: Merged revisions 81517 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r81517 | brian.curtin | 2010-05-25 10:06:15 -0500 (Tue, 25 May 2010) | 5 lines Fix #2810 - handle the case where some registry calls return ERROR_MORE_DATA, requiring another call to get the remaining data. Patch by Daniel Stutzbach ........ Modified: python/branches/release26-maint/Lib/test/test_winreg.py python/branches/release26-maint/Misc/NEWS python/branches/release26-maint/PC/_winreg.c Modified: python/branches/release26-maint/Lib/test/test_winreg.py ============================================================================== --- python/branches/release26-maint/Lib/test/test_winreg.py (original) +++ python/branches/release26-maint/Lib/test/test_winreg.py Wed May 26 15:24:57 2010 @@ -6,6 +6,8 @@ import unittest from test import test_support +threading = test_support.import_module("threading") +from platform import machine test_key_name = "SOFTWARE\\Python Registry Test Key - Delete Me" @@ -166,6 +168,58 @@ self.assertEqual(type(r), unicode) self.assertEqual(r, os.environ["windir"] + "\\test") + def test_changing_value(self): + # Issue2810: A race condition in 2.6 and 3.1 may cause + # EnumValue or QueryValue to throw "WindowsError: More data is + # available" + done = False + + class VeryActiveThread(threading.Thread): + def run(self): + with CreateKey(HKEY_CURRENT_USER, test_key_name) as key: + use_short = True + long_string = 'x'*2000 + while not done: + s = 'x' if use_short else long_string + use_short = not use_short + SetValue(key, 'changing_value', REG_SZ, s) + + thread = VeryActiveThread() + thread.start() + try: + with CreateKey(HKEY_CURRENT_USER, + test_key_name+'\\changing_value') as key: + for _ in range(1000): + num_subkeys, num_values, t = QueryInfoKey(key) + for i in range(num_values): + name = EnumValue(key, i) + QueryValue(key, name[0]) + finally: + done = True + thread.join() + DeleteKey(HKEY_CURRENT_USER, test_key_name+'\\changing_value') + DeleteKey(HKEY_CURRENT_USER, test_key_name) + + def test_long_key(self): + # Issue2810, in 2.6 and 3.1 when the key name was exactly 256 + # characters, EnumKey threw "WindowsError: More data is + # available" + name = 'x'*256 + try: + with CreateKey(HKEY_CURRENT_USER, test_key_name) as key: + SetValue(key, name, REG_SZ, 'x') + num_subkeys, num_values, t = QueryInfoKey(key) + EnumKey(key, 0) + finally: + DeleteKey(HKEY_CURRENT_USER, '\\'.join((test_key_name, name))) + DeleteKey(HKEY_CURRENT_USER, test_key_name) + + def test_dynamic_key(self): + # Issue2810, when the value is dynamically generated, these + # throw "WindowsError: More data is available" in 2.6 and 3.1 + EnumValue(HKEY_PERFORMANCE_DATA, 0) + QueryValueEx(HKEY_PERFORMANCE_DATA, None) + def test_main(): test_support.run_unittest(WinregTests) Modified: python/branches/release26-maint/Misc/NEWS ============================================================================== --- python/branches/release26-maint/Misc/NEWS (original) +++ python/branches/release26-maint/Misc/NEWS Wed May 26 15:24:57 2010 @@ -225,6 +225,12 @@ - Issue #7356: ctypes.util: Make parsing of ldconfig output independent of the locale. +Extension Modules +----------------- + +- Issue #2810: Fix cases where the Windows registry API returns + ERROR_MORE_DATA, requiring a re-try in order to get the complete result. + Build ----- Modified: python/branches/release26-maint/PC/_winreg.c ============================================================================== --- python/branches/release26-maint/PC/_winreg.c (original) +++ python/branches/release26-maint/PC/_winreg.c Wed May 26 15:24:57 2010 @@ -1071,7 +1071,14 @@ int index; long rc; PyObject *retStr; - char tmpbuf[256]; /* max key name length is 255 */ + + /* The Windows docs claim that the max key name length is 255 + * characters, plus a terminating nul character. However, + * empirical testing demonstrates that it is possible to + * create a 256 character key that is missing the terminating + * nul. RegEnumKeyEx requires a 257 character buffer to + * retrieve such a key name. */ + char tmpbuf[257]; DWORD len = sizeof(tmpbuf); /* includes NULL terminator */ if (!PyArg_ParseTuple(args, "Oi:EnumKey", &obKey, &index)) @@ -1098,8 +1105,8 @@ long rc; char *retValueBuf; char *retDataBuf; - DWORD retValueSize; - DWORD retDataSize; + DWORD retValueSize, bufValueSize; + DWORD retDataSize, bufDataSize; DWORD typ; PyObject *obData; PyObject *retVal; @@ -1117,6 +1124,8 @@ "RegQueryInfoKey"); ++retValueSize; /* include null terminators */ ++retDataSize; + bufDataSize = retDataSize; + bufValueSize = retValueSize; retValueBuf = (char *)PyMem_Malloc(retValueSize); if (retValueBuf == NULL) return PyErr_NoMemory(); @@ -1126,16 +1135,33 @@ return PyErr_NoMemory(); } - Py_BEGIN_ALLOW_THREADS - rc = RegEnumValue(hKey, - index, - retValueBuf, - &retValueSize, - NULL, - &typ, - (BYTE *)retDataBuf, - &retDataSize); - Py_END_ALLOW_THREADS + while (1) { + char *tmp; + Py_BEGIN_ALLOW_THREADS + rc = RegEnumValue(hKey, + index, + retValueBuf, + &retValueSize, + NULL, + &typ, + (BYTE *)retDataBuf, + &retDataSize); + Py_END_ALLOW_THREADS + + if (rc != ERROR_MORE_DATA) + break; + + bufDataSize *= 2; + tmp = (char *)PyMem_Realloc(retDataBuf, bufDataSize); + if (tmp == NULL) { + PyErr_NoMemory(); + retVal = NULL; + goto fail; + } + retDataBuf = tmp; + retDataSize = bufDataSize; + retValueSize = bufValueSize; + } if (rc != ERROR_SUCCESS) { retVal = PyErr_SetFromWindowsErrWithFunction(rc, @@ -1292,28 +1318,56 @@ long rc; PyObject *retStr; char *retBuf; - long bufSize = 0; + DWORD bufSize = 0; + DWORD retSize = 0; + char *tmp; if (!PyArg_ParseTuple(args, "Oz:QueryValue", &obKey, &subKey)) return NULL; if (!PyHKEY_AsHKEY(obKey, &hKey, FALSE)) return NULL; - if ((rc = RegQueryValue(hKey, subKey, NULL, &bufSize)) - != ERROR_SUCCESS) + + rc = RegQueryValue(hKey, subKey, NULL, &retSize); + if (rc == ERROR_MORE_DATA) + retSize = 256; + else if (rc != ERROR_SUCCESS) return PyErr_SetFromWindowsErrWithFunction(rc, "RegQueryValue"); - retStr = PyString_FromStringAndSize(NULL, bufSize); - if (retStr == NULL) - return NULL; - retBuf = PyString_AS_STRING(retStr); - if ((rc = RegQueryValue(hKey, subKey, retBuf, &bufSize)) - != ERROR_SUCCESS) { - Py_DECREF(retStr); + + bufSize = retSize; + retBuf = (char *) PyMem_Malloc(bufSize); + if (retBuf == NULL) + return PyErr_NoMemory(); + + while (1) { + retSize = bufSize; + rc = RegQueryValue(hKey, subKey, retBuf, &retSize); + if (rc != ERROR_MORE_DATA) + break; + + bufSize *= 2; + tmp = (char *) PyMem_Realloc(retBuf, bufSize); + if (tmp == NULL) { + PyMem_Free(retBuf); + return PyErr_NoMemory(); + } + retBuf = tmp; + } + + if (rc != ERROR_SUCCESS) { + PyMem_Free(retBuf); return PyErr_SetFromWindowsErrWithFunction(rc, "RegQueryValue"); } - _PyString_Resize(&retStr, strlen(retBuf)); + + if (retBuf[retSize-1] == '\x00') + retSize--; + retStr = PyString_FromStringAndSize(retBuf, retSize); + if (retStr == NULL) { + PyMem_Free(retBuf); + return NULL; + } return retStr; } @@ -1325,8 +1379,8 @@ char *valueName; long rc; - char *retBuf; - DWORD bufSize = 0; + char *retBuf, *tmp; + DWORD bufSize = 0, retSize; DWORD typ; PyObject *obData; PyObject *result; @@ -1336,18 +1390,34 @@ if (!PyHKEY_AsHKEY(obKey, &hKey, FALSE)) return NULL; - if ((rc = RegQueryValueEx(hKey, valueName, - NULL, NULL, NULL, - &bufSize)) - != ERROR_SUCCESS) + + rc = RegQueryValueEx(hKey, valueName, NULL, NULL, NULL, &bufSize); + if (rc == ERROR_MORE_DATA) + bufSize = 256; + else if (rc != ERROR_SUCCESS) return PyErr_SetFromWindowsErrWithFunction(rc, "RegQueryValueEx"); retBuf = (char *)PyMem_Malloc(bufSize); if (retBuf == NULL) return PyErr_NoMemory(); - if ((rc = RegQueryValueEx(hKey, valueName, NULL, - &typ, (BYTE *)retBuf, &bufSize)) - != ERROR_SUCCESS) { + + while (1) { + retSize = bufSize; + rc = RegQueryValueEx(hKey, valueName, NULL, &typ, + (BYTE *)retBuf, &retSize); + if (rc != ERROR_MORE_DATA) + break; + + bufSize *= 2; + tmp = (char *) PyMem_Realloc(retBuf, bufSize); + if (tmp == NULL) { + PyMem_Free(retBuf); + return PyErr_NoMemory(); + } + retBuf = tmp; + } + + if (rc != ERROR_SUCCESS) { PyMem_Free(retBuf); return PyErr_SetFromWindowsErrWithFunction(rc, "RegQueryValueEx"); From python-checkins at python.org Wed May 26 18:02:59 2010 From: python-checkins at python.org (mark.dickinson) Date: Wed, 26 May 2010 18:02:59 +0200 (CEST) Subject: [Python-checkins] r81541 - in python/branches/py3k: Include/longobject.h Objects/longobject.c Message-ID: <20100526160259.C17B0EE9E0@mail.python.org> Author: mark.dickinson Date: Wed May 26 18:02:59 2010 New Revision: 81541 Log: Issue #8817: Expose round-to-nearest variant of divmod in _PyLong_Divmod_Near for use by the datetime module; also refactor long_round to use this function. Modified: python/branches/py3k/Include/longobject.h python/branches/py3k/Objects/longobject.c Modified: python/branches/py3k/Include/longobject.h ============================================================================== --- python/branches/py3k/Include/longobject.h (original) +++ python/branches/py3k/Include/longobject.h Wed May 26 18:02:59 2010 @@ -101,6 +101,14 @@ */ PyAPI_FUNC(size_t) _PyLong_NumBits(PyObject *v); +/* _PyLong_Divmod_Near. Given integers a and b, compute the nearest + integer q to the exact quotient a / b, rounding to the nearest even integer + in the case of a tie. Return (q, r), where r = a - q*b. The remainder r + will satisfy abs(r) <= abs(b)/2, with equality possible only if q is + even. +*/ +PyAPI_FUNC(PyObject *) _PyLong_Divmod_Near(PyObject *, PyObject *); + /* _PyLong_FromByteArray: View the n unsigned bytes as a binary integer in base 256, and return a Python long with the same numeric value. If n is 0, the integer is 0. Else: Modified: python/branches/py3k/Objects/longobject.c ============================================================================== --- python/branches/py3k/Objects/longobject.c (original) +++ python/branches/py3k/Objects/longobject.c Wed May 26 18:02:59 2010 @@ -4201,140 +4201,169 @@ PyUnicode_GET_SIZE(format_spec)); } +/* Return a pair (q, r) such that a = b * q + r, and + abs(r) <= abs(b)/2, with equality possible only if q is even. + In other words, q == a / b, rounded to the nearest integer using + round-half-to-even. */ + +PyObject * +_PyLong_Divmod_Near(PyObject *a, PyObject *b) +{ + PyLongObject *quo = NULL, *rem = NULL; + PyObject *one = NULL, *twice_rem, *result, *temp; + int cmp, quo_is_odd, quo_is_neg; + + /* Equivalent Python code: + + def divmod_near(a, b): + q, r = divmod(a, b) + # round up if either r / b > 0.5, or r / b == 0.5 and q is odd. + # The expression r / b > 0.5 is equivalent to 2 * r > b if b is + # positive, 2 * r < b if b negative. + greater_than_half = 2*r > b if b > 0 else 2*r < b + exactly_half = 2*r == b + if greater_than_half or exactly_half and q % 2 == 1: + q += 1 + r -= b + return q, r + + */ + if (!PyLong_Check(a) || !PyLong_Check(b)) { + PyErr_SetString(PyExc_TypeError, + "non-integer arguments in division"); + return NULL; + } + + /* Do a and b have different signs? If so, quotient is negative. */ + quo_is_neg = (Py_SIZE(a) < 0) != (Py_SIZE(b) < 0); + + one = PyLong_FromLong(1L); + if (one == NULL) + return NULL; + + if (long_divrem((PyLongObject*)a, (PyLongObject*)b, &quo, &rem) < 0) + goto error; + + /* compare twice the remainder with the divisor, to see + if we need to adjust the quotient and remainder */ + twice_rem = long_lshift((PyObject *)rem, one); + if (twice_rem == NULL) + goto error; + if (quo_is_neg) { + temp = long_neg((PyLongObject*)twice_rem); + Py_DECREF(twice_rem); + twice_rem = temp; + if (twice_rem == NULL) + goto error; + } + cmp = long_compare((PyLongObject *)twice_rem, (PyLongObject *)b); + Py_DECREF(twice_rem); + + quo_is_odd = Py_SIZE(quo) != 0 && ((quo->ob_digit[0] & 1) != 0); + if ((Py_SIZE(b) < 0 ? cmp < 0 : cmp > 0) || (cmp == 0 && quo_is_odd)) { + /* fix up quotient */ + if (quo_is_neg) + temp = long_sub(quo, (PyLongObject *)one); + else + temp = long_add(quo, (PyLongObject *)one); + Py_DECREF(quo); + quo = (PyLongObject *)temp; + if (quo == NULL) + goto error; + /* and remainder */ + if (quo_is_neg) + temp = long_add(rem, (PyLongObject *)b); + else + temp = long_sub(rem, (PyLongObject *)b); + Py_DECREF(rem); + rem = (PyLongObject *)temp; + if (rem == NULL) + goto error; + } + + result = PyTuple_New(2); + if (result == NULL) + goto error; + + /* PyTuple_SET_ITEM steals references */ + PyTuple_SET_ITEM(result, 0, (PyObject *)quo); + PyTuple_SET_ITEM(result, 1, (PyObject *)rem); + Py_DECREF(one); + return result; + + error: + Py_XDECREF(quo); + Py_XDECREF(rem); + Py_XDECREF(one); + return NULL; +} + static PyObject * long_round(PyObject *self, PyObject *args) { - PyObject *o_ndigits=NULL, *temp; - PyLongObject *pow=NULL, *q=NULL, *r=NULL, *ndigits=NULL, *one; - int errcode; - digit q_mod_4; - - /* Notes on the algorithm: to round to the nearest 10**n (n positive), - the straightforward method is: - - (1) divide by 10**n - (2) round to nearest integer (round to even in case of tie) - (3) multiply result by 10**n. - - But the rounding step involves examining the fractional part of the - quotient to see whether it's greater than 0.5 or not. Since we - want to do the whole calculation in integer arithmetic, it's - simpler to do: - - (1) divide by (10**n)/2 - (2) round to nearest multiple of 2 (multiple of 4 in case of tie) - (3) multiply result by (10**n)/2. - - Then all we need to know about the fractional part of the quotient - arising in step (2) is whether it's zero or not. - - Doing both a multiplication and division is wasteful, and is easily - avoided if we just figure out how much to adjust the original input - by to do the rounding. - - Here's the whole algorithm expressed in Python. - - def round(self, ndigits = None): - """round(int, int) -> int""" - if ndigits is None or ndigits >= 0: - return self - pow = 10**-ndigits >> 1 - q, r = divmod(self, pow) - self -= r - if (q & 1 != 0): - if (q & 2 == r == 0): - self -= pow - else: - self += pow - return self + PyObject *o_ndigits=NULL, *temp, *result, *ndigits; - */ + /* To round an integer m to the nearest 10**n (n positive), we make use of + * the divmod_near operation, defined by: + * + * divmod_near(a, b) = (q, r) + * + * where q is the nearest integer to the quotient a / b (the + * nearest even integer in the case of a tie) and r == a - q * b. + * Hence q * b = a - r is the nearest multiple of b to a, + * preferring even multiples in the case of a tie. + * + * So the nearest multiple of 10**n to m is: + * + * m - divmod_near(m, 10**n)[1]. + */ if (!PyArg_ParseTuple(args, "|O", &o_ndigits)) return NULL; if (o_ndigits == NULL) return long_long(self); - ndigits = (PyLongObject *)PyNumber_Index(o_ndigits); + ndigits = PyNumber_Index(o_ndigits); if (ndigits == NULL) return NULL; + /* if ndigits >= 0 then no rounding is necessary; return self unchanged */ if (Py_SIZE(ndigits) >= 0) { Py_DECREF(ndigits); return long_long(self); } - Py_INCREF(self); /* to keep refcounting simple */ - /* we now own references to self, ndigits */ - - /* pow = 10 ** -ndigits >> 1 */ - pow = (PyLongObject *)PyLong_FromLong(10L); - if (pow == NULL) - goto error; - temp = long_neg(ndigits); + /* result = self - divmod_near(self, 10 ** -ndigits)[1] */ + temp = long_neg((PyLongObject*)ndigits); Py_DECREF(ndigits); - ndigits = (PyLongObject *)temp; + ndigits = temp; if (ndigits == NULL) - goto error; - temp = long_pow((PyObject *)pow, (PyObject *)ndigits, Py_None); - Py_DECREF(pow); - pow = (PyLongObject *)temp; - if (pow == NULL) - goto error; - assert(PyLong_Check(pow)); /* check long_pow returned a long */ - one = (PyLongObject *)PyLong_FromLong(1L); - if (one == NULL) - goto error; - temp = long_rshift(pow, one); - Py_DECREF(one); - Py_DECREF(pow); - pow = (PyLongObject *)temp; - if (pow == NULL) - goto error; - - /* q, r = divmod(self, pow) */ - errcode = l_divmod((PyLongObject *)self, pow, &q, &r); - if (errcode == -1) - goto error; - - /* self -= r */ - temp = long_sub((PyLongObject *)self, r); - Py_DECREF(self); - self = temp; - if (self == NULL) - goto error; + return NULL; - /* get value of quotient modulo 4 */ - if (Py_SIZE(q) == 0) - q_mod_4 = 0; - else if (Py_SIZE(q) > 0) - q_mod_4 = q->ob_digit[0] & 3; - else - q_mod_4 = (PyLong_BASE-q->ob_digit[0]) & 3; - - if ((q_mod_4 & 1) == 1) { - /* q is odd; round self up or down by adding or subtracting pow */ - if (q_mod_4 == 1 && Py_SIZE(r) == 0) - temp = (PyObject *)long_sub((PyLongObject *)self, pow); - else - temp = (PyObject *)long_add((PyLongObject *)self, pow); - Py_DECREF(self); - self = temp; - if (self == NULL) - goto error; + result = PyLong_FromLong(10L); + if (result == NULL) { + Py_DECREF(ndigits); + return NULL; } - Py_DECREF(q); - Py_DECREF(r); - Py_DECREF(pow); + + temp = long_pow(result, ndigits, Py_None); Py_DECREF(ndigits); - return self; + Py_DECREF(result); + result = temp; + if (result == NULL) + return NULL; - error: - Py_XDECREF(q); - Py_XDECREF(r); - Py_XDECREF(pow); - Py_XDECREF(self); - Py_XDECREF(ndigits); - return NULL; + temp = _PyLong_Divmod_Near(self, result); + Py_DECREF(result); + result = temp; + if (result == NULL) + return NULL; + + temp = long_sub((PyLongObject *)self, + (PyLongObject *)PyTuple_GET_ITEM(result, 1)); + Py_DECREF(result); + result = temp; + + return result; } static PyObject * From python-checkins at python.org Wed May 26 18:06:11 2010 From: python-checkins at python.org (mark.dickinson) Date: Wed, 26 May 2010 18:06:11 +0200 (CEST) Subject: [Python-checkins] r81542 - python/branches/release31-maint Message-ID: <20100526160611.C4424EEA07@mail.python.org> Author: mark.dickinson Date: Wed May 26 18:06:11 2010 New Revision: 81542 Log: Blocked revisions 81541 via svnmerge ........ r81541 | mark.dickinson | 2010-05-26 17:02:59 +0100 (Wed, 26 May 2010) | 4 lines Issue #8817: Expose round-to-nearest variant of divmod in _PyLong_Divmod_Near for use by the datetime module; also refactor long_round to use this function. ........ Modified: python/branches/release31-maint/ (props changed) From python-checkins at python.org Wed May 26 19:25:28 2010 From: python-checkins at python.org (victor.stinner) Date: Wed, 26 May 2010 19:25:28 +0200 (CEST) Subject: [Python-checkins] r81543 - in python/trunk: Lib/test/test_socketserver.py Misc/NEWS Message-ID: <20100526172528.EA9F0EEA2A@mail.python.org> Author: victor.stinner Date: Wed May 26 19:25:28 2010 New Revision: 81543 Log: Issue #7449: Skip test_socketserver if threading support is disabled Modified: python/trunk/Lib/test/test_socketserver.py python/trunk/Misc/NEWS Modified: python/trunk/Lib/test/test_socketserver.py ============================================================================== --- python/trunk/Lib/test/test_socketserver.py (original) +++ python/trunk/Lib/test/test_socketserver.py Wed May 26 19:25:28 2010 @@ -61,6 +61,7 @@ testcase.assertEquals(72 << 8, status) + at unittest.skipUnless(threading, 'Threading required for this test.') class SocketServerTest(unittest.TestCase): """Test all socket servers.""" Modified: python/trunk/Misc/NEWS ============================================================================== --- python/trunk/Misc/NEWS (original) +++ python/trunk/Misc/NEWS Wed May 26 19:25:28 2010 @@ -75,6 +75,8 @@ Tests ----- +- Issue #7449: Skip test_socketserver if threading support is disabled + - On darwin, ``test_site`` assumed that a framework build was being used, leading to a failure where four directories were expected for site-packages instead of two in a non-framework build. From python-checkins at python.org Wed May 26 19:31:46 2010 From: python-checkins at python.org (victor.stinner) Date: Wed, 26 May 2010 19:31:46 +0200 (CEST) Subject: [Python-checkins] r81544 - python/branches/release26-maint Message-ID: <20100526173146.44E94EEA04@mail.python.org> Author: victor.stinner Date: Wed May 26 19:31:46 2010 New Revision: 81544 Log: Blocked revisions 81543 via svnmerge ........ r81543 | victor.stinner | 2010-05-26 19:25:28 +0200 (mer., 26 mai 2010) | 2 lines Issue #7449: Skip test_socketserver if threading support is disabled ........ Modified: python/branches/release26-maint/ (props changed) From python-checkins at python.org Wed May 26 19:33:03 2010 From: python-checkins at python.org (victor.stinner) Date: Wed, 26 May 2010 19:33:03 +0200 (CEST) Subject: [Python-checkins] r81545 - in python/branches/py3k: Lib/test/test_socketserver.py Misc/NEWS Message-ID: <20100526173303.B22F7EEA19@mail.python.org> Author: victor.stinner Date: Wed May 26 19:33:03 2010 New Revision: 81545 Log: Merged revisions 81543 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r81543 | victor.stinner | 2010-05-26 19:25:28 +0200 (mer., 26 mai 2010) | 2 lines Issue #7449: Skip test_socketserver if threading support is disabled ........ Modified: python/branches/py3k/ (props changed) python/branches/py3k/Lib/test/test_socketserver.py python/branches/py3k/Misc/NEWS Modified: python/branches/py3k/Lib/test/test_socketserver.py ============================================================================== --- python/branches/py3k/Lib/test/test_socketserver.py (original) +++ python/branches/py3k/Lib/test/test_socketserver.py Wed May 26 19:33:03 2010 @@ -61,6 +61,7 @@ testcase.assertEquals(72 << 8, status) + at unittest.skipUnless(threading, 'Threading required for this test.') class SocketServerTest(unittest.TestCase): """Test all socket servers.""" Modified: python/branches/py3k/Misc/NEWS ============================================================================== --- python/branches/py3k/Misc/NEWS (original) +++ python/branches/py3k/Misc/NEWS Wed May 26 19:33:03 2010 @@ -1385,6 +1385,8 @@ Tests ----- +- Issue #7449: Skip test_socketserver if threading support is disabled + - Issue #8672: Add a zlib test ensuring that an incomplete stream can be handled by a decompressor object without errors (it returns incomplete uncompressed data). From python-checkins at python.org Wed May 26 19:35:09 2010 From: python-checkins at python.org (victor.stinner) Date: Wed, 26 May 2010 19:35:09 +0200 (CEST) Subject: [Python-checkins] r81546 - in python/branches/release31-maint: Lib/test/test_socketserver.py Misc/NEWS Message-ID: <20100526173509.338B4EEA11@mail.python.org> Author: victor.stinner Date: Wed May 26 19:35:09 2010 New Revision: 81546 Log: Merged revisions 81545 via svnmerge from svn+ssh://pythondev at svn.python.org/python/branches/py3k ................ r81545 | victor.stinner | 2010-05-26 19:33:03 +0200 (mer., 26 mai 2010) | 9 lines Merged revisions 81543 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r81543 | victor.stinner | 2010-05-26 19:25:28 +0200 (mer., 26 mai 2010) | 2 lines Issue #7449: Skip test_socketserver if threading support is disabled ........ ................ Modified: python/branches/release31-maint/ (props changed) python/branches/release31-maint/Lib/test/test_socketserver.py python/branches/release31-maint/Misc/NEWS Modified: python/branches/release31-maint/Lib/test/test_socketserver.py ============================================================================== --- python/branches/release31-maint/Lib/test/test_socketserver.py (original) +++ python/branches/release31-maint/Lib/test/test_socketserver.py Wed May 26 19:35:09 2010 @@ -61,6 +61,7 @@ testcase.assertEquals(72 << 8, status) + at unittest.skipUnless(threading, 'Threading required for this test.') class SocketServerTest(unittest.TestCase): """Test all socket servers.""" Modified: python/branches/release31-maint/Misc/NEWS ============================================================================== --- python/branches/release31-maint/Misc/NEWS (original) +++ python/branches/release31-maint/Misc/NEWS Wed May 26 19:35:09 2010 @@ -226,6 +226,8 @@ Tests ----- +- Issue #7449: Skip test_socketserver if threading support is disabled + - Issue #8672: Add a zlib test ensuring that an incomplete stream can be handled by a decompressor object without errors (it returns incomplete uncompressed data). From python-checkins at python.org Wed May 26 19:43:50 2010 From: python-checkins at python.org (brian.curtin) Date: Wed, 26 May 2010 19:43:50 +0200 (CEST) Subject: [Python-checkins] r81547 - in python/branches/py3k: Lib/test/test_winreg.py Misc/NEWS PC/winreg.c Message-ID: <20100526174350.CE7B6EEA11@mail.python.org> Author: brian.curtin Date: Wed May 26 19:43:50 2010 New Revision: 81547 Log: Fix #2810 - handle the case where some registry calls return ERROR_MORE_DATA, requiring another call to get the remaining data. Patch by Daniel Stutzbach Modified: python/branches/py3k/Lib/test/test_winreg.py python/branches/py3k/Misc/NEWS python/branches/py3k/PC/winreg.c Modified: python/branches/py3k/Lib/test/test_winreg.py ============================================================================== --- python/branches/py3k/Lib/test/test_winreg.py (original) +++ python/branches/py3k/Lib/test/test_winreg.py Wed May 26 19:43:50 2010 @@ -5,6 +5,7 @@ import os, sys import unittest from test import support +threading = support.import_module("threading") from platform import machine # Do this first so test will be skipped if module doesn't exist @@ -227,6 +228,58 @@ except WindowsError: self.assertEqual(h.handle, 0) + def test_changing_value(self): + # Issue2810: A race condition in 2.6 and 3.1 may cause + # EnumValue or QueryValue to throw "WindowsError: More data is + # available" + done = False + + class VeryActiveThread(threading.Thread): + def run(self): + with CreateKey(HKEY_CURRENT_USER, test_key_name) as key: + use_short = True + long_string = 'x'*2000 + while not done: + s = 'x' if use_short else long_string + use_short = not use_short + SetValue(key, 'changing_value', REG_SZ, s) + + thread = VeryActiveThread() + thread.start() + try: + with CreateKey(HKEY_CURRENT_USER, + test_key_name+'\\changing_value') as key: + for _ in range(1000): + num_subkeys, num_values, t = QueryInfoKey(key) + for i in range(num_values): + name = EnumValue(key, i) + QueryValue(key, name[0]) + finally: + done = True + thread.join() + DeleteKey(HKEY_CURRENT_USER, test_key_name+'\\changing_value') + DeleteKey(HKEY_CURRENT_USER, test_key_name) + + def test_long_key(self): + # Issue2810, in 2.6 and 3.1 when the key name was exactly 256 + # characters, EnumKey threw "WindowsError: More data is + # available" + name = 'x'*256 + try: + with CreateKey(HKEY_CURRENT_USER, test_key_name) as key: + SetValue(key, name, REG_SZ, 'x') + num_subkeys, num_values, t = QueryInfoKey(key) + EnumKey(key, 0) + finally: + DeleteKey(HKEY_CURRENT_USER, '\\'.join((test_key_name, name))) + DeleteKey(HKEY_CURRENT_USER, test_key_name) + + def test_dynamic_key(self): + # Issue2810, when the value is dynamically generated, these + # throw "WindowsError: More data is available" in 2.6 and 3.1 + EnumValue(HKEY_PERFORMANCE_DATA, 0) + QueryValueEx(HKEY_PERFORMANCE_DATA, "") + # Reflection requires XP x64/Vista at a minimum. XP doesn't have this stuff # or DeleteKeyEx so make sure their use raises NotImplementedError @unittest.skipUnless(WIN_VER < (5, 2), "Requires Windows XP") Modified: python/branches/py3k/Misc/NEWS ============================================================================== --- python/branches/py3k/Misc/NEWS (original) +++ python/branches/py3k/Misc/NEWS Wed May 26 19:43:50 2010 @@ -1220,6 +1220,9 @@ Extension Modules ----------------- +- Issue #2810: Fix cases where the Windows registry API returns + ERROR_MORE_DATA, requiring a re-try in order to get the complete result. + - Issue #8692: Optimize math.factorial: replace the previous naive algorithm with an improved 'binary-split' algorithm that uses fewer multiplications and allows many of the multiplications to be Modified: python/branches/py3k/PC/winreg.c ============================================================================== --- python/branches/py3k/PC/winreg.c (original) +++ python/branches/py3k/PC/winreg.c Wed May 26 19:43:50 2010 @@ -1096,7 +1096,14 @@ int index; long rc; PyObject *retStr; - wchar_t tmpbuf[256]; /* max key name length is 255 */ + + /* The Windows docs claim that the max key name length is 255 + * characters, plus a terminating nul character. However, + * empirical testing demonstrates that it is possible to + * create a 256 character key that is missing the terminating + * nul. RegEnumKeyEx requires a 257 character buffer to + * retrieve such a key name. */ + wchar_t tmpbuf[257]; DWORD len = sizeof(tmpbuf); /* includes NULL terminator */ if (!PyArg_ParseTuple(args, "Oi:EnumKey", &obKey, &index)) @@ -1123,8 +1130,8 @@ long rc; wchar_t *retValueBuf; BYTE *retDataBuf; - DWORD retValueSize; - DWORD retDataSize; + DWORD retValueSize, bufValueSize; + DWORD retDataSize, bufDataSize; DWORD typ; PyObject *obData; PyObject *retVal; @@ -1142,6 +1149,8 @@ "RegQueryInfoKey"); ++retValueSize; /* include null terminators */ ++retDataSize; + bufDataSize = retDataSize; + bufValueSize = retValueSize; retValueBuf = (wchar_t *)PyMem_Malloc(sizeof(wchar_t) * retValueSize); if (retValueBuf == NULL) return PyErr_NoMemory(); @@ -1151,16 +1160,33 @@ return PyErr_NoMemory(); } - Py_BEGIN_ALLOW_THREADS - rc = RegEnumValueW(hKey, - index, - retValueBuf, - &retValueSize, - NULL, - &typ, - retDataBuf, - &retDataSize); - Py_END_ALLOW_THREADS + while (1) { + wchar_t *tmp; + Py_BEGIN_ALLOW_THREADS + rc = RegEnumValueW(hKey, + index, + retValueBuf, + &retValueSize, + NULL, + &typ, + (BYTE *)retDataBuf, + &retDataSize); + Py_END_ALLOW_THREADS + + if (rc != ERROR_MORE_DATA) + break; + + bufDataSize *= 2; + tmp = (char *)PyMem_Realloc(retDataBuf, bufDataSize); + if (tmp == NULL) { + PyErr_NoMemory(); + retVal = NULL; + goto fail; + } + retDataBuf = tmp; + retDataSize = bufDataSize; + retValueSize = bufValueSize; + } if (rc != ERROR_SUCCESS) { retVal = PyErr_SetFromWindowsErrWithFunction(rc, @@ -1317,23 +1343,44 @@ long rc; PyObject *retStr; wchar_t *retBuf; - long bufSize = 0; + DWORD bufSize = 0; + DWORD retSize = 0; + wchar_t *tmp; if (!PyArg_ParseTuple(args, "OZ:QueryValue", &obKey, &subKey)) return NULL; if (!PyHKEY_AsHKEY(obKey, &hKey, FALSE)) return NULL; - if ((rc = RegQueryValueW(hKey, subKey, NULL, &bufSize)) - != ERROR_SUCCESS) + + rc = RegQueryValueW(hKey, subKey, NULL, &retSize); + if (rc == ERROR_MORE_DATA) + retSize = 256; + else if (rc != ERROR_SUCCESS) return PyErr_SetFromWindowsErrWithFunction(rc, "RegQueryValue"); - retBuf = (wchar_t *)PyMem_Malloc(bufSize); + + bufSize = retSize; + retBuf = (wchar_t *) PyMem_Malloc(bufSize); if (retBuf == NULL) return PyErr_NoMemory(); - if ((rc = RegQueryValueW(hKey, subKey, retBuf, &bufSize)) - != ERROR_SUCCESS) { + while (1) { + retSize = bufSize; + rc = RegQueryValueW(hKey, subKey, retBuf, &retSize); + if (rc != ERROR_MORE_DATA) + break; + + bufSize *= 2; + tmp = (wchar_t *) PyMem_Realloc(retBuf, bufSize); + if (tmp == NULL) { + PyMem_Free(retBuf); + return PyErr_NoMemory(); + } + retBuf = tmp; + } + + if (rc != ERROR_SUCCESS) { PyMem_Free(retBuf); return PyErr_SetFromWindowsErrWithFunction(rc, "RegQueryValue"); @@ -1352,8 +1399,8 @@ wchar_t *valueName; long rc; - BYTE *retBuf; - DWORD bufSize = 0; + BYTE *retBuf, *tmp; + DWORD bufSize = 0, retSize; DWORD typ; PyObject *obData; PyObject *result; @@ -1363,18 +1410,34 @@ if (!PyHKEY_AsHKEY(obKey, &hKey, FALSE)) return NULL; - if ((rc = RegQueryValueExW(hKey, valueName, - NULL, NULL, NULL, - &bufSize)) - != ERROR_SUCCESS) + + rc = RegQueryValueExW(hKey, valueName, NULL, NULL, NULL, &bufSize); + if (rc == ERROR_MORE_DATA) + bufSize = 256; + else if (rc != ERROR_SUCCESS) return PyErr_SetFromWindowsErrWithFunction(rc, "RegQueryValueEx"); retBuf = (BYTE *)PyMem_Malloc(bufSize); if (retBuf == NULL) return PyErr_NoMemory(); - if ((rc = RegQueryValueExW(hKey, valueName, NULL, - &typ, retBuf, &bufSize)) - != ERROR_SUCCESS) { + + while (1) { + retSize = bufSize; + rc = RegQueryValueExW(hKey, valueName, NULL, &typ, + (BYTE *)retBuf, &retSize); + if (rc != ERROR_MORE_DATA) + break; + + bufSize *= 2; + tmp = (char *) PyMem_Realloc(retBuf, bufSize); + if (tmp == NULL) { + PyMem_Free(retBuf); + return PyErr_NoMemory(); + } + retBuf = tmp; + } + + if (rc != ERROR_SUCCESS) { PyMem_Free(retBuf); return PyErr_SetFromWindowsErrWithFunction(rc, "RegQueryValueEx"); From python-checkins at python.org Wed May 26 20:06:04 2010 From: python-checkins at python.org (giampaolo.rodola) Date: Wed, 26 May 2010 20:06:04 +0200 (CEST) Subject: [Python-checkins] r81548 - in python/branches/py3k: Doc/library/ftplib.rst Lib/ftplib.py Lib/test/test_ftplib.py Misc/NEWS Message-ID: <20100526180604.86C75EEA3F@mail.python.org> Author: giampaolo.rodola Date: Wed May 26 20:06:04 2010 New Revision: 81548 Log: Fix issue #8806: add SSL contexts support to ftplib Modified: python/branches/py3k/Doc/library/ftplib.rst python/branches/py3k/Lib/ftplib.py python/branches/py3k/Lib/test/test_ftplib.py python/branches/py3k/Misc/NEWS Modified: python/branches/py3k/Doc/library/ftplib.rst ============================================================================== --- python/branches/py3k/Doc/library/ftplib.rst (original) +++ python/branches/py3k/Doc/library/ftplib.rst Wed May 26 20:06:04 2010 @@ -65,7 +65,7 @@ Support for the :keyword:`with` statement was added. -.. class:: FTP_TLS(host='', user='', passwd='', acct='', [keyfile[, certfile[, timeout]]]) +.. class:: FTP_TLS(host='', user='', passwd='', acct='', [keyfile[, certfile[, context[, timeout]]]]) A :class:`FTP` subclass which adds TLS support to FTP as described in :rfc:`4217`. @@ -74,6 +74,9 @@ explicitly ask for it by calling the :meth:`prot_p` method. *keyfile* and *certfile* are optional -- they can contain a PEM formatted private key and certificate chain file name for the SSL connection. + *context* parameter is a :class:`ssl.SSLContext` object which allows + bundling SSL configuration options, certificates and private keys into a + single (potentially long-lived) structure. .. versionadded:: 3.2 Modified: python/branches/py3k/Lib/ftplib.py ============================================================================== --- python/branches/py3k/Lib/ftplib.py (original) +++ python/branches/py3k/Lib/ftplib.py Wed May 26 20:06:04 2010 @@ -638,9 +638,17 @@ ssl_version = ssl.PROTOCOL_TLSv1 def __init__(self, host='', user='', passwd='', acct='', keyfile=None, - certfile=None, timeout=_GLOBAL_DEFAULT_TIMEOUT): + certfile=None, context=None, + timeout=_GLOBAL_DEFAULT_TIMEOUT): + if context is not None and keyfile is not None: + raise ValueError("context and keyfile arguments are mutually " + "exclusive") + if context is not None and certfile is not None: + raise ValueError("context and certfile arguments are mutually " + "exclusive") self.keyfile = keyfile self.certfile = certfile + self.context = context self._prot_p = False FTP.__init__(self, host, user, passwd, acct, timeout) @@ -657,8 +665,12 @@ resp = self.voidcmd('AUTH TLS') else: resp = self.voidcmd('AUTH SSL') - self.sock = ssl.wrap_socket(self.sock, self.keyfile, self.certfile, - ssl_version=self.ssl_version) + if self.context is not None: + self.sock = self.context.wrap_socket(self.sock) + else: + self.sock = ssl.wrap_socket(self.sock, self.keyfile, + self.certfile, + ssl_version=self.ssl_version) self.file = self.sock.makefile(mode='r', encoding=self.encoding) return resp @@ -689,8 +701,11 @@ def ntransfercmd(self, cmd, rest=None): conn, size = FTP.ntransfercmd(self, cmd, rest) if self._prot_p: - conn = ssl.wrap_socket(conn, self.keyfile, self.certfile, - ssl_version=self.ssl_version) + if self.context is not None: + conn = self.context.wrap_socket(conn) + else: + conn = ssl.wrap_socket(conn, self.keyfile, self.certfile, + ssl_version=self.ssl_version) return conn, size def retrbinary(self, cmd, callback, blocksize=8192, rest=None): Modified: python/branches/py3k/Lib/test/test_ftplib.py ============================================================================== --- python/branches/py3k/Lib/test/test_ftplib.py (original) +++ python/branches/py3k/Lib/test/test_ftplib.py Wed May 26 20:06:04 2010 @@ -719,6 +719,29 @@ finally: self.client.ssl_version = ssl.PROTOCOL_TLSv1 + def test_context(self): + self.client.quit() + ctx = ssl.SSLContext(ssl.PROTOCOL_TLSv1) + self.assertRaises(ValueError, ftplib.FTP_TLS, keyfile=CERTFILE, + context=ctx) + self.assertRaises(ValueError, ftplib.FTP_TLS, certfile=CERTFILE, + context=ctx) + self.assertRaises(ValueError, ftplib.FTP_TLS, certfile=CERTFILE, + keyfile=CERTFILE, context=ctx) + + self.client = ftplib.FTP_TLS(context=ctx, timeout=2) + self.client.connect(self.server.host, self.server.port) + self.assertNotIsInstance(self.client.sock, ssl.SSLSocket) + self.client.auth() + self.assertIs(self.client.sock.context, ctx) + self.assertIsInstance(self.client.sock, ssl.SSLSocket) + + self.client.prot_p() + sock = self.client.transfercmd('list') + self.assertIs(self.client.sock.context, ctx) + self.assertIsInstance(sock, ssl.SSLSocket) + sock.close() + class TestTimeouts(TestCase): Modified: python/branches/py3k/Misc/NEWS ============================================================================== --- python/branches/py3k/Misc/NEWS (original) +++ python/branches/py3k/Misc/NEWS Wed May 26 20:06:04 2010 @@ -392,6 +392,8 @@ Library ------- +- Issue #8806: add SSL contexts support to ftplib. + - Issue #4769: Fix main() function of the base64 module, use sys.stdin.buffer and sys.stdout.buffer (instead of sys.stdin and sys.stdout) to use the bytes API From python-checkins at python.org Wed May 26 20:09:33 2010 From: python-checkins at python.org (brian.curtin) Date: Wed, 26 May 2010 20:09:33 +0200 (CEST) Subject: [Python-checkins] r81549 - in python/branches/release31-maint: Lib/test/test_winreg.py Misc/NEWS PC/winreg.c Message-ID: <20100526180933.369C9EE9F7@mail.python.org> Author: brian.curtin Date: Wed May 26 20:09:32 2010 New Revision: 81549 Log: Merged revisions 81547 via svnmerge from svn+ssh://pythondev at svn.python.org/python/branches/py3k ........ r81547 | brian.curtin | 2010-05-26 12:43:50 -0500 (Wed, 26 May 2010) | 6 lines Fix #2810 - handle the case where some registry calls return ERROR_MORE_DATA, requiring another call to get the remaining data. Patch by Daniel Stutzbach ........ Modified: python/branches/release31-maint/ (props changed) python/branches/release31-maint/Lib/test/test_winreg.py python/branches/release31-maint/Misc/NEWS python/branches/release31-maint/PC/winreg.c Modified: python/branches/release31-maint/Lib/test/test_winreg.py ============================================================================== --- python/branches/release31-maint/Lib/test/test_winreg.py (original) +++ python/branches/release31-maint/Lib/test/test_winreg.py Wed May 26 20:09:32 2010 @@ -5,6 +5,7 @@ import os, sys import unittest from test import support +threading = support.import_module("threading") # Do this first so test will be skipped if module doesn't exist support.import_module('winreg') @@ -185,6 +186,59 @@ self.assertEqual(type(r), str) self.assertEqual(r, os.environ["windir"] + "\\test") + def test_changing_value(self): + # Issue2810: A race condition in 2.6 and 3.1 may cause + # EnumValue or QueryValue to throw "WindowsError: More data is + # available" + done = False + + class VeryActiveThread(threading.Thread): + def run(self): + with CreateKey(HKEY_CURRENT_USER, test_key_name) as key: + use_short = True + long_string = 'x'*2000 + while not done: + s = 'x' if use_short else long_string + use_short = not use_short + SetValue(key, 'changing_value', REG_SZ, s) + + thread = VeryActiveThread() + thread.start() + try: + with CreateKey(HKEY_CURRENT_USER, + test_key_name+'\\changing_value') as key: + for _ in range(1000): + num_subkeys, num_values, t = QueryInfoKey(key) + for i in range(num_values): + name = EnumValue(key, i) + QueryValue(key, name[0]) + finally: + done = True + thread.join() + DeleteKey(HKEY_CURRENT_USER, test_key_name+'\\changing_value') + DeleteKey(HKEY_CURRENT_USER, test_key_name) + + def test_long_key(self): + # Issue2810, in 2.6 and 3.1 when the key name was exactly 256 + # characters, EnumKey threw "WindowsError: More data is + # available" + name = 'x'*256 + try: + with CreateKey(HKEY_CURRENT_USER, test_key_name) as key: + SetValue(key, name, REG_SZ, 'x') + num_subkeys, num_values, t = QueryInfoKey(key) + EnumKey(key, 0) + finally: + DeleteKey(HKEY_CURRENT_USER, '\\'.join((test_key_name, name))) + DeleteKey(HKEY_CURRENT_USER, test_key_name) + + def test_dynamic_key(self): + # Issue2810, when the value is dynamically generated, these + # throw "WindowsError: More data is available" in 2.6 and 3.1 + EnumValue(HKEY_PERFORMANCE_DATA, 0) + QueryValueEx(HKEY_PERFORMANCE_DATA, "") + + def test_main(): support.run_unittest(WinregTests) Modified: python/branches/release31-maint/Misc/NEWS ============================================================================== --- python/branches/release31-maint/Misc/NEWS (original) +++ python/branches/release31-maint/Misc/NEWS Wed May 26 20:09:32 2010 @@ -211,6 +211,12 @@ - Issue #6716/2: Backslash-replace error output in compilall. +Extension Modules +----------------- + +- Issue #2810: Fix cases where the Windows registry API returns + ERROR_MORE_DATA, requiring a re-try in order to get the complete result. + Build ----- Modified: python/branches/release31-maint/PC/winreg.c ============================================================================== --- python/branches/release31-maint/PC/winreg.c (original) +++ python/branches/release31-maint/PC/winreg.c Wed May 26 20:09:32 2010 @@ -1003,7 +1003,14 @@ int index; long rc; PyObject *retStr; - wchar_t tmpbuf[256]; /* max key name length is 255 */ + + /* The Windows docs claim that the max key name length is 255 + * characters, plus a terminating nul character. However, + * empirical testing demonstrates that it is possible to + * create a 256 character key that is missing the terminating + * nul. RegEnumKeyEx requires a 257 character buffer to + * retrieve such a key name. */ + wchar_t tmpbuf[257]; DWORD len = sizeof(tmpbuf); /* includes NULL terminator */ if (!PyArg_ParseTuple(args, "Oi:EnumKey", &obKey, &index)) @@ -1030,8 +1037,8 @@ long rc; wchar_t *retValueBuf; BYTE *retDataBuf; - DWORD retValueSize; - DWORD retDataSize; + DWORD retValueSize, bufValueSize; + DWORD retDataSize, bufDataSize; DWORD typ; PyObject *obData; PyObject *retVal; @@ -1049,6 +1056,8 @@ "RegQueryInfoKey"); ++retValueSize; /* include null terminators */ ++retDataSize; + bufDataSize = retDataSize; + bufValueSize = retValueSize; retValueBuf = (wchar_t *)PyMem_Malloc(sizeof(wchar_t) * retValueSize); if (retValueBuf == NULL) return PyErr_NoMemory(); @@ -1058,16 +1067,33 @@ return PyErr_NoMemory(); } - Py_BEGIN_ALLOW_THREADS - rc = RegEnumValueW(hKey, - index, - retValueBuf, - &retValueSize, - NULL, - &typ, - retDataBuf, - &retDataSize); - Py_END_ALLOW_THREADS + while (1) { + wchar_t *tmp; + Py_BEGIN_ALLOW_THREADS + rc = RegEnumValueW(hKey, + index, + retValueBuf, + &retValueSize, + NULL, + &typ, + (BYTE *)retDataBuf, + &retDataSize); + Py_END_ALLOW_THREADS + + if (rc != ERROR_MORE_DATA) + break; + + bufDataSize *= 2; + tmp = (char *)PyMem_Realloc(retDataBuf, bufDataSize); + if (tmp == NULL) { + PyErr_NoMemory(); + retVal = NULL; + goto fail; + } + retDataBuf = tmp; + retDataSize = bufDataSize; + retValueSize = bufValueSize; + } if (rc != ERROR_SUCCESS) { retVal = PyErr_SetFromWindowsErrWithFunction(rc, @@ -1224,23 +1250,44 @@ long rc; PyObject *retStr; wchar_t *retBuf; - long bufSize = 0; + DWORD bufSize = 0; + DWORD retSize = 0; + wchar_t *tmp; if (!PyArg_ParseTuple(args, "OZ:QueryValue", &obKey, &subKey)) return NULL; if (!PyHKEY_AsHKEY(obKey, &hKey, FALSE)) return NULL; - if ((rc = RegQueryValueW(hKey, subKey, NULL, &bufSize)) - != ERROR_SUCCESS) + + rc = RegQueryValueW(hKey, subKey, NULL, &retSize); + if (rc == ERROR_MORE_DATA) + retSize = 256; + else if (rc != ERROR_SUCCESS) return PyErr_SetFromWindowsErrWithFunction(rc, "RegQueryValue"); - retBuf = (wchar_t *)PyMem_Malloc(bufSize); + + bufSize = retSize; + retBuf = (wchar_t *) PyMem_Malloc(bufSize); if (retBuf == NULL) return PyErr_NoMemory(); - if ((rc = RegQueryValueW(hKey, subKey, retBuf, &bufSize)) - != ERROR_SUCCESS) { + while (1) { + retSize = bufSize; + rc = RegQueryValueW(hKey, subKey, retBuf, &retSize); + if (rc != ERROR_MORE_DATA) + break; + + bufSize *= 2; + tmp = (wchar_t *) PyMem_Realloc(retBuf, bufSize); + if (tmp == NULL) { + PyMem_Free(retBuf); + return PyErr_NoMemory(); + } + retBuf = tmp; + } + + if (rc != ERROR_SUCCESS) { PyMem_Free(retBuf); return PyErr_SetFromWindowsErrWithFunction(rc, "RegQueryValue"); @@ -1259,8 +1306,8 @@ wchar_t *valueName; long rc; - BYTE *retBuf; - DWORD bufSize = 0; + BYTE *retBuf, *tmp; + DWORD bufSize = 0, retSize; DWORD typ; PyObject *obData; PyObject *result; @@ -1270,18 +1317,34 @@ if (!PyHKEY_AsHKEY(obKey, &hKey, FALSE)) return NULL; - if ((rc = RegQueryValueExW(hKey, valueName, - NULL, NULL, NULL, - &bufSize)) - != ERROR_SUCCESS) + + rc = RegQueryValueExW(hKey, valueName, NULL, NULL, NULL, &bufSize); + if (rc == ERROR_MORE_DATA) + bufSize = 256; + else if (rc != ERROR_SUCCESS) return PyErr_SetFromWindowsErrWithFunction(rc, "RegQueryValueEx"); retBuf = (BYTE *)PyMem_Malloc(bufSize); if (retBuf == NULL) return PyErr_NoMemory(); - if ((rc = RegQueryValueExW(hKey, valueName, NULL, - &typ, retBuf, &bufSize)) - != ERROR_SUCCESS) { + + while (1) { + retSize = bufSize; + rc = RegQueryValueExW(hKey, valueName, NULL, &typ, + (BYTE *)retBuf, &retSize); + if (rc != ERROR_MORE_DATA) + break; + + bufSize *= 2; + tmp = (char *) PyMem_Realloc(retBuf, bufSize); + if (tmp == NULL) { + PyMem_Free(retBuf); + return PyErr_NoMemory(); + } + retBuf = tmp; + } + + if (rc != ERROR_SUCCESS) { PyMem_Free(retBuf); return PyErr_SetFromWindowsErrWithFunction(rc, "RegQueryValueEx"); From python-checkins at python.org Wed May 26 20:21:26 2010 From: python-checkins at python.org (giampaolo.rodola) Date: Wed, 26 May 2010 20:21:26 +0200 (CEST) Subject: [Python-checkins] r81550 - python/branches/py3k/Lib/test/test_ftplib.py Message-ID: <20100526182126.B616CEEA11@mail.python.org> Author: giampaolo.rodola Date: Wed May 26 20:21:26 2010 New Revision: 81550 Log: fix wrong assertIs context Modified: python/branches/py3k/Lib/test/test_ftplib.py Modified: python/branches/py3k/Lib/test/test_ftplib.py ============================================================================== --- python/branches/py3k/Lib/test/test_ftplib.py (original) +++ python/branches/py3k/Lib/test/test_ftplib.py Wed May 26 20:21:26 2010 @@ -738,7 +738,7 @@ self.client.prot_p() sock = self.client.transfercmd('list') - self.assertIs(self.client.sock.context, ctx) + self.assertIs(sock.context, ctx) self.assertIsInstance(sock, ssl.SSLSocket) sock.close() From python-checkins at python.org Wed May 26 21:06:33 2010 From: python-checkins at python.org (mark.dickinson) Date: Wed, 26 May 2010 21:06:33 +0200 (CEST) Subject: [Python-checkins] r81551 - in python/trunk/Lib/test: test_int.py test_long.py Message-ID: <20100526190633.C1452EEA2F@mail.python.org> Author: mark.dickinson Date: Wed May 26 21:06:33 2010 New Revision: 81551 Log: Issue #8825: additional testcases for int(string, 0) and long(string, 0). Modified: python/trunk/Lib/test/test_int.py python/trunk/Lib/test/test_long.py Modified: python/trunk/Lib/test/test_int.py ============================================================================== --- python/trunk/Lib/test/test_int.py (original) +++ python/trunk/Lib/test/test_int.py Wed May 26 21:06:33 2010 @@ -175,6 +175,12 @@ self.assertEqual(int(' 0O123 ', 0), 83) self.assertEqual(int(' 0X123 ', 0), 291) self.assertEqual(int(' 0B100 ', 0), 4) + self.assertEqual(int('0', 0), 0) + self.assertEqual(int('+0', 0), 0) + self.assertEqual(int('-0', 0), 0) + self.assertEqual(int('00', 0), 0) + self.assertRaises(ValueError, int, '08', 0) + self.assertRaises(ValueError, int, '-012395', 0) # without base still base 10 self.assertEqual(int('0123'), 123) Modified: python/trunk/Lib/test/test_long.py ============================================================================== --- python/trunk/Lib/test/test_long.py (original) +++ python/trunk/Lib/test/test_long.py Wed May 26 21:06:33 2010 @@ -356,6 +356,23 @@ self.assertRaises(ValueError, long, '53', 40) self.assertRaises(TypeError, long, 1, 12) + # tests with base 0 + self.assertEqual(long(' 0123 ', 0), 83) + self.assertEqual(long(' 0123 ', 0), 83) + self.assertEqual(long('000', 0), 0) + self.assertEqual(long('0o123', 0), 83) + self.assertEqual(long('0x123', 0), 291) + self.assertEqual(long('0b100', 0), 4) + self.assertEqual(long(' 0O123 ', 0), 83) + self.assertEqual(long(' 0X123 ', 0), 291) + self.assertEqual(long(' 0B100 ', 0), 4) + self.assertEqual(long('0', 0), 0) + self.assertEqual(long('+0', 0), 0) + self.assertEqual(long('-0', 0), 0) + self.assertEqual(long('00', 0), 0) + self.assertRaises(ValueError, long, '08', 0) + self.assertRaises(ValueError, long, '-012395', 0) + # SF patch #1638879: embedded NULs were not detected with # explicit base self.assertRaises(ValueError, long, '123\0', 10) From python-checkins at python.org Wed May 26 21:07:12 2010 From: python-checkins at python.org (mark.dickinson) Date: Wed, 26 May 2010 21:07:12 +0200 (CEST) Subject: [Python-checkins] r81552 - in python/branches/release26-maint: Lib/test/test_int.py Lib/test/test_long.py Message-ID: <20100526190712.8FB1AEEA0C@mail.python.org> Author: mark.dickinson Date: Wed May 26 21:07:12 2010 New Revision: 81552 Log: Merged revisions 81551 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r81551 | mark.dickinson | 2010-05-26 20:06:33 +0100 (Wed, 26 May 2010) | 1 line Issue #8825: additional testcases for int(string, 0) and long(string, 0). ........ Modified: python/branches/release26-maint/ (props changed) python/branches/release26-maint/Lib/test/test_int.py python/branches/release26-maint/Lib/test/test_long.py Modified: python/branches/release26-maint/Lib/test/test_int.py ============================================================================== --- python/branches/release26-maint/Lib/test/test_int.py (original) +++ python/branches/release26-maint/Lib/test/test_int.py Wed May 26 21:07:12 2010 @@ -174,6 +174,12 @@ self.assertEqual(int(' 0O123 ', 0), 83) self.assertEqual(int(' 0X123 ', 0), 291) self.assertEqual(int(' 0B100 ', 0), 4) + self.assertEqual(int('0', 0), 0) + self.assertEqual(int('+0', 0), 0) + self.assertEqual(int('-0', 0), 0) + self.assertEqual(int('00', 0), 0) + self.assertRaises(ValueError, int, '08', 0) + self.assertRaises(ValueError, int, '-012395', 0) # without base still base 10 self.assertEqual(int('0123'), 123) Modified: python/branches/release26-maint/Lib/test/test_long.py ============================================================================== --- python/branches/release26-maint/Lib/test/test_long.py (original) +++ python/branches/release26-maint/Lib/test/test_long.py Wed May 26 21:07:12 2010 @@ -323,6 +323,23 @@ self.assertRaises(ValueError, long, '53', 40) self.assertRaises(TypeError, long, 1, 12) + # tests with base 0 + self.assertEqual(long(' 0123 ', 0), 83) + self.assertEqual(long(' 0123 ', 0), 83) + self.assertEqual(long('000', 0), 0) + self.assertEqual(long('0o123', 0), 83) + self.assertEqual(long('0x123', 0), 291) + self.assertEqual(long('0b100', 0), 4) + self.assertEqual(long(' 0O123 ', 0), 83) + self.assertEqual(long(' 0X123 ', 0), 291) + self.assertEqual(long(' 0B100 ', 0), 4) + self.assertEqual(long('0', 0), 0) + self.assertEqual(long('+0', 0), 0) + self.assertEqual(long('-0', 0), 0) + self.assertEqual(long('00', 0), 0) + self.assertRaises(ValueError, long, '08', 0) + self.assertRaises(ValueError, long, '-012395', 0) + # SF patch #1638879: embedded NULs were not detected with # explicit base self.assertRaises(ValueError, long, '123\0', 10) From python-checkins at python.org Wed May 26 21:14:01 2010 From: python-checkins at python.org (mark.dickinson) Date: Wed, 26 May 2010 21:14:01 +0200 (CEST) Subject: [Python-checkins] r81553 - in python/branches/py3k: Lib/test/test_long.py Message-ID: <20100526191401.25B09EE9AC@mail.python.org> Author: mark.dickinson Date: Wed May 26 21:14:01 2010 New Revision: 81553 Log: Merged revisions 81551 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r81551 | mark.dickinson | 2010-05-26 20:06:33 +0100 (Wed, 26 May 2010) | 1 line Issue #8825: additional testcases for int(string, 0) and long(string, 0). ........ Modified: python/branches/py3k/ (props changed) python/branches/py3k/Lib/test/test_long.py Modified: python/branches/py3k/Lib/test/test_long.py ============================================================================== --- python/branches/py3k/Lib/test/test_long.py (original) +++ python/branches/py3k/Lib/test/test_long.py Wed May 26 21:14:01 2010 @@ -330,6 +330,21 @@ # ... but it's just a normal digit if base >= 22 self.assertEqual(int('1L', 22), 43) + # tests with base 0 + self.assertEqual(int('000', 0), 0) + self.assertEqual(int('0o123', 0), 83) + self.assertEqual(int('0x123', 0), 291) + self.assertEqual(int('0b100', 0), 4) + self.assertEqual(int(' 0O123 ', 0), 83) + self.assertEqual(int(' 0X123 ', 0), 291) + self.assertEqual(int(' 0B100 ', 0), 4) + self.assertEqual(int('0', 0), 0) + self.assertEqual(int('+0', 0), 0) + self.assertEqual(int('-0', 0), 0) + self.assertEqual(int('00', 0), 0) + self.assertRaises(ValueError, int, '08', 0) + self.assertRaises(ValueError, int, '-012395', 0) + def test_conversion(self): class JustLong: From python-checkins at python.org Wed May 26 21:18:29 2010 From: python-checkins at python.org (mark.dickinson) Date: Wed, 26 May 2010 21:18:29 +0200 (CEST) Subject: [Python-checkins] r81554 - in python/branches/release31-maint: Lib/test/test_long.py Message-ID: <20100526191829.213ABEEA2A@mail.python.org> Author: mark.dickinson Date: Wed May 26 21:18:28 2010 New Revision: 81554 Log: Merged revisions 81553 via svnmerge from svn+ssh://pythondev at svn.python.org/python/branches/py3k ................ r81553 | mark.dickinson | 2010-05-26 20:14:01 +0100 (Wed, 26 May 2010) | 9 lines Merged revisions 81551 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r81551 | mark.dickinson | 2010-05-26 20:06:33 +0100 (Wed, 26 May 2010) | 1 line Issue #8825: additional testcases for int(string, 0) and long(string, 0). ........ ................ Modified: python/branches/release31-maint/ (props changed) python/branches/release31-maint/Lib/test/test_long.py Modified: python/branches/release31-maint/Lib/test/test_long.py ============================================================================== --- python/branches/release31-maint/Lib/test/test_long.py (original) +++ python/branches/release31-maint/Lib/test/test_long.py Wed May 26 21:18:28 2010 @@ -404,6 +404,20 @@ self.assertEqual(int('2br45qc', 35), 4294967297) self.assertEqual(int('1z141z5', 36), 4294967297) + # tests with base 0 + self.assertEqual(int('000', 0), 0) + self.assertEqual(int('0o123', 0), 83) + self.assertEqual(int('0x123', 0), 291) + self.assertEqual(int('0b100', 0), 4) + self.assertEqual(int(' 0O123 ', 0), 83) + self.assertEqual(int(' 0X123 ', 0), 291) + self.assertEqual(int(' 0B100 ', 0), 4) + self.assertEqual(int('0', 0), 0) + self.assertEqual(int('+0', 0), 0) + self.assertEqual(int('-0', 0), 0) + self.assertEqual(int('00', 0), 0) + self.assertRaises(ValueError, int, '08', 0) + self.assertRaises(ValueError, int, '-012395', 0) def test_conversion(self): # Test __int__() From python-checkins at python.org Wed May 26 21:43:16 2010 From: python-checkins at python.org (alexander.belopolsky) Date: Wed, 26 May 2010 21:43:16 +0200 (CEST) Subject: [Python-checkins] r81555 - python/trunk/Lib/test/test_datetime.py Message-ID: <20100526194316.A8082EE9B2@mail.python.org> Author: alexander.belopolsky Date: Wed May 26 21:43:16 2010 New Revision: 81555 Log: Issue #7879: Do not test negative timestamps on any Windows platform including Windows CE. Modified: python/trunk/Lib/test/test_datetime.py Modified: python/trunk/Lib/test/test_datetime.py ============================================================================== --- python/trunk/Lib/test/test_datetime.py (original) +++ python/trunk/Lib/test/test_datetime.py Wed May 26 21:43:16 2010 @@ -3,7 +3,7 @@ See http://www.zope.org/Members/fdrake/DateTimeWiki/TestCases """ from __future__ import division -import os +import sys import pickle import cPickle import unittest @@ -1513,7 +1513,7 @@ def test_negative_float_fromtimestamp(self): # Windows doesn't accept negative timestamps - if os.name == "nt": + if sys.platform == "win32": return # The result is tz-dependent; at least test that this doesn't # fail (like it did before bug 1646728 was fixed). @@ -1521,7 +1521,7 @@ def test_negative_float_utcfromtimestamp(self): # Windows doesn't accept negative timestamps - if os.name == "nt": + if sys.platform == "win32": return d = self.theclass.utcfromtimestamp(-1.05) self.assertEquals(d, self.theclass(1969, 12, 31, 23, 59, 58, 950000)) From python-checkins at python.org Wed May 26 22:00:12 2010 From: python-checkins at python.org (alexander.belopolsky) Date: Wed, 26 May 2010 22:00:12 +0200 (CEST) Subject: [Python-checkins] r81556 - in python/branches/py3k: Lib/test/test_datetime.py Message-ID: <20100526200012.D8FA9EE9CE@mail.python.org> Author: alexander.belopolsky Date: Wed May 26 22:00:12 2010 New Revision: 81556 Log: Merged revisions 81555 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r81555 | alexander.belopolsky | 2010-05-26 15:43:16 -0400 (Wed, 26 May 2010) | 3 lines Issue #7879: Do not test negative timestamps on any Windows platform including Windows CE. ........ Modified: python/branches/py3k/ (props changed) python/branches/py3k/Lib/test/test_datetime.py Modified: python/branches/py3k/Lib/test/test_datetime.py ============================================================================== --- python/branches/py3k/Lib/test/test_datetime.py (original) +++ python/branches/py3k/Lib/test/test_datetime.py Wed May 26 22:00:12 2010 @@ -3,7 +3,7 @@ See http://www.zope.org/Members/fdrake/DateTimeWiki/TestCases """ -import os +import sys import pickle import unittest @@ -1557,7 +1557,7 @@ def test_negative_float_fromtimestamp(self): # Windows doesn't accept negative timestamps - if os.name == "nt": + if sys.platform == "win32": return # The result is tz-dependent; at least test that this doesn't # fail (like it did before bug 1646728 was fixed). @@ -1565,7 +1565,7 @@ def test_negative_float_utcfromtimestamp(self): # Windows doesn't accept negative timestamps - if os.name == "nt": + if sys.platform == "win32": return d = self.theclass.utcfromtimestamp(-1.05) self.assertEquals(d, self.theclass(1969, 12, 31, 23, 59, 58, 950000)) From python-checkins at python.org Wed May 26 22:07:58 2010 From: python-checkins at python.org (mark.dickinson) Date: Wed, 26 May 2010 22:07:58 +0200 (CEST) Subject: [Python-checkins] r81557 - in python/branches/py3k: Lib/test/test_long.py Misc/NEWS Objects/longobject.c Message-ID: <20100526200758.9BD55C769@mail.python.org> Author: mark.dickinson Date: Wed May 26 22:07:58 2010 New Revision: 81557 Log: Issue #2844: Make int('42', n) consistently raise ValueError for invalid integers n (including n = -909). Modified: python/branches/py3k/Lib/test/test_long.py python/branches/py3k/Misc/NEWS python/branches/py3k/Objects/longobject.c Modified: python/branches/py3k/Lib/test/test_long.py ============================================================================== --- python/branches/py3k/Lib/test/test_long.py (original) +++ python/branches/py3k/Lib/test/test_long.py Wed May 26 22:07:58 2010 @@ -345,6 +345,16 @@ self.assertRaises(ValueError, int, '08', 0) self.assertRaises(ValueError, int, '-012395', 0) + # invalid bases + invalid_bases = [-909, + 2**31-1, 2**31, -2**31, -2**31-1, + 2**63-1, 2**63, -2**63, -2**63-1, + 2**100, -2**100, + ] + for base in invalid_bases: + self.assertRaises(ValueError, int, '42', base) + + def test_conversion(self): class JustLong: Modified: python/branches/py3k/Misc/NEWS ============================================================================== --- python/branches/py3k/Misc/NEWS (original) +++ python/branches/py3k/Misc/NEWS Wed May 26 22:07:58 2010 @@ -12,6 +12,9 @@ Core and Builtins ----------------- +- Issue #2844: Make int('42', n) consistently raise ValueError for + invalid integers n (including n = -909). + - Issue #8188: Introduce a new scheme for computing hashes of numbers (instances of int, float, complex, decimal.Decimal and fractions.Fraction) that makes it easy to maintain the invariant Modified: python/branches/py3k/Objects/longobject.c ============================================================================== --- python/branches/py3k/Objects/longobject.c (original) +++ python/branches/py3k/Objects/longobject.c Wed May 26 22:07:58 2010 @@ -4098,23 +4098,34 @@ static PyObject * long_new(PyTypeObject *type, PyObject *args, PyObject *kwds) { - PyObject *x = NULL; - int base = -909; /* unlikely! */ + PyObject *obase = NULL, *x = NULL; + long base; + int overflow; static char *kwlist[] = {"x", "base", 0}; if (type != &PyLong_Type) return long_subtype_new(type, args, kwds); /* Wimp out */ - if (!PyArg_ParseTupleAndKeywords(args, kwds, "|Oi:int", kwlist, - &x, &base)) + if (!PyArg_ParseTupleAndKeywords(args, kwds, "|OO:int", kwlist, + &x, &obase)) return NULL; if (x == NULL) return PyLong_FromLong(0L); - if (base == -909) + if (obase == NULL) return PyNumber_Long(x); - else if (PyUnicode_Check(x)) + + base = PyLong_AsLongAndOverflow(obase, &overflow); + if (base == -1 && PyErr_Occurred()) + return NULL; + if (overflow || (base != 0 && base < 2) || base > 36) { + PyErr_SetString(PyExc_ValueError, + "int() arg 2 must be >= 2 and <= 36"); + return NULL; + } + + if (PyUnicode_Check(x)) return PyLong_FromUnicode(PyUnicode_AS_UNICODE(x), PyUnicode_GET_SIZE(x), - base); + (int)base); else if (PyByteArray_Check(x) || PyBytes_Check(x)) { /* Since PyLong_FromString doesn't have a length parameter, * check here for possible NULs in the string. */ @@ -4129,10 +4140,10 @@ x is a bytes or buffer, *and* a base is given. */ PyErr_Format(PyExc_ValueError, "invalid literal for int() with base %d: %R", - base, x); + (int)base, x); return NULL; } - return PyLong_FromString(string, NULL, base); + return PyLong_FromString(string, NULL, (int)base); } else { PyErr_SetString(PyExc_TypeError, From python-checkins at python.org Wed May 26 22:31:07 2010 From: python-checkins at python.org (mark.dickinson) Date: Wed, 26 May 2010 22:31:07 +0200 (CEST) Subject: [Python-checkins] r81558 - python/branches/release31-maint Message-ID: <20100526203107.59C57EEA41@mail.python.org> Author: mark.dickinson Date: Wed May 26 22:31:07 2010 New Revision: 81558 Log: Blocked revisions 81557 via svnmerge ........ r81557 | mark.dickinson | 2010-05-26 21:07:58 +0100 (Wed, 26 May 2010) | 4 lines Issue #2844: Make int('42', n) consistently raise ValueError for invalid integers n (including n = -909). ........ Modified: python/branches/release31-maint/ (props changed) From nnorwitz at gmail.com Wed May 26 22:32:23 2010 From: nnorwitz at gmail.com (Neal Norwitz) Date: Wed, 26 May 2010 16:32:23 -0400 Subject: [Python-checkins] Python Regression Test Failures basics (1) Message-ID: <20100526203223.GA16756@kbk-i386-bb.psfb.org> 346 tests OK. 1 test failed: test_ftplib 37 tests skipped: test_aepack test_al test_applesingle test_bsddb185 test_bsddb3 test_cd test_cl test_curses test_epoll test_gdb test_gl test_imgfile test_ioctl test_kqueue test_linuxaudiodev test_macos test_macostools test_multiprocessing test_ossaudiodev test_pep277 test_py3kwarn test_scriptpackages test_smtpnet test_socketserver test_startfile test_sunaudiodev test_tcl test_timeout test_tk test_ttk_guionly test_ttk_textonly test_unicode_file test_urllib2net test_urllibnet test_winreg test_winsound test_zipfile64 7 skips unexpected on linux2: test_epoll test_gdb test_ioctl test_multiprocessing test_tk test_ttk_guionly test_ttk_textonly == CPython 2.7b2+ (trunk:81555M, May 26 2010, 16:02:47) [GCC 3.3.4 20040623 (Gentoo Linux 3.3.4-r1, ssp-3.3.2-2, pie-8.7.6)] == Linux-2.6.9-gentoo-r1-i686-AMD_Athlon-tm-_XP_3000+-with-gentoo-1.4.16 little-endian == /tmp/test_python_31114 test_grammar test_opcodes test_dict test_builtin test_exceptions test_types test_unittest test_doctest test_doctest2 test_MimeWriter test_SimpleHTTPServer test_StringIO test___all__ test___future__ test__locale test_abc test_abstract_numbers test_aepack test_aepack skipped -- No module named aetypes test_aifc test_al test_al skipped -- No module named al test_anydbm test_applesingle test_applesingle skipped -- No module named MacOS test_argparse test_array test_ascii_formatd test_ast test_asynchat test_asyncore test_atexit test_audioop test_augassign test_base64 test_bastion test_bigaddrspace test_bigmem test_binascii test_binhex test_binop test_bisect test_bool test_bsddb test_bsddb185 test_bsddb185 skipped -- No module named bsddb185 test_bsddb3 test_bsddb3 skipped -- Use of the `bsddb' resource not enabled test_buffer test_bufio test_bytes test_bz2 test_calendar test_call test_capi test_cd test_cd skipped -- No module named cd test_cfgparser test_cgi test_charmapcodec test_cl test_cl skipped -- No module named cl test_class test_cmath test_cmd test_cmd_line test_cmd_line_script test_code test_codeccallbacks test_codecencodings_cn test_codecencodings_hk test_codecencodings_jp test_codecencodings_kr test_codecencodings_tw test_codecmaps_cn fetching http://source.icu-project.org/repos/icu/data/trunk/charset/data/xml/gb-18030-2000.xml ... fetching http://people.freebsd.org/~perky/i18n/EUC-CN.TXT ... fetching http://www.unicode.org/Public/MAPPINGS/VENDORS/MICSFT/WINDOWS/CP936.TXT ... test_codecmaps_hk fetching http://people.freebsd.org/~perky/i18n/BIG5HKSCS-2004.TXT ... test_codecmaps_jp fetching http://www.unicode.org/Public/MAPPINGS/VENDORS/MICSFT/WINDOWS/CP932.TXT ... fetching http://people.freebsd.org/~perky/i18n/EUC-JISX0213.TXT ... fetching http://people.freebsd.org/~perky/i18n/EUC-JP.TXT ... fetching http://www.unicode.org/Public/MAPPINGS/OBSOLETE/EASTASIA/JIS/SHIFTJIS.TXT ... fetching http://people.freebsd.org/~perky/i18n/SHIFT_JISX0213.TXT ... test_codecmaps_kr fetching http://www.unicode.org/Public/MAPPINGS/VENDORS/MICSFT/WINDOWS/CP949.TXT ... fetching http://people.freebsd.org/~perky/i18n/EUC-KR.TXT ... fetching http://www.unicode.org/Public/MAPPINGS/OBSOLETE/EASTASIA/KSC/JOHAB.TXT ... test_codecmaps_tw fetching http://www.unicode.org/Public/MAPPINGS/OBSOLETE/EASTASIA/OTHER/BIG5.TXT ... fetching http://www.unicode.org/Public/MAPPINGS/VENDORS/MICSFT/WINDOWS/CP950.TXT ... test_codecs test_codeop test_coding test_coercion test_collections test_colorsys test_commands test_compare test_compile test_compileall test_compiler test_complex test_complex_args test_contains test_contextlib test_cookie test_cookielib test_copy test_copy_reg test_cpickle test_cprofile test_crypt test_csv test_ctypes test_curses test_curses skipped -- Use of the `curses' resource not enabled test_datetime test_dbm test_decimal test_decorators test_defaultdict test_deque test_descr test_descrtut test_dictcomps test_dictviews test_difflib test_dircache test_dis test_distutils [20673 refs] test_dl test_docxmlrpc test_dumbdbm test_dummy_thread test_dummy_threading test_email test_email_codecs test_email_renamed test_enumerate test_eof test_epoll test_epoll skipped -- kernel doesn't support epoll() test_errno test_exception_variations test_extcall test_fcntl test_file test_file2k test_filecmp test_fileinput test_fileio test_float test_fnmatch test_fork1 test_format test_fpformat test_fractions test_frozen test_ftplib test test_ftplib failed -- multiple errors occurred; run in verbose mode for details Re-running test 'test_ftplib' in verbose mode test_acct (test.test_ftplib.TestFTPClass) ... ok test_all_errors (test.test_ftplib.TestFTPClass) ... ok test_delete (test.test_ftplib.TestFTPClass) ... ok test_dir (test.test_ftplib.TestFTPClass) ... ok test_exceptions (test.test_ftplib.TestFTPClass) ... ok test_getwelcome (test.test_ftplib.TestFTPClass) ... ok test_login (test.test_ftplib.TestFTPClass) ... ok test_makepasv (test.test_ftplib.TestFTPClass) ... ok test_makeport (test.test_ftplib.TestFTPClass) ... ok test_mkd (test.test_ftplib.TestFTPClass) ... ok test_nlst (test.test_ftplib.TestFTPClass) ... ok test_pwd (test.test_ftplib.TestFTPClass) ... ok test_quit (test.test_ftplib.TestFTPClass) ... ok test_rename (test.test_ftplib.TestFTPClass) ... ok test_retrbinary (test.test_ftplib.TestFTPClass) ... ok test_retrbinary_rest (test.test_ftplib.TestFTPClass) ... ok test_retrlines (test.test_ftplib.TestFTPClass) ... ok test_rmd (test.test_ftplib.TestFTPClass) ... ok test_sanitize (test.test_ftplib.TestFTPClass) ... ok test_set_pasv (test.test_ftplib.TestFTPClass) ... ok test_size (test.test_ftplib.TestFTPClass) ... ok test_storbinary (test.test_ftplib.TestFTPClass) ... ok test_storbinary_rest (test.test_ftplib.TestFTPClass) ... ok test_storlines (test.test_ftplib.TestFTPClass) ... ok test_voidcmd (test.test_ftplib.TestFTPClass) ... ok testTimeoutConnect (test.test_ftplib.TestTimeouts) ... ok testTimeoutDefault (test.test_ftplib.TestTimeouts) ... ok testTimeoutDifferentOrder (test.test_ftplib.TestTimeouts) ... ok testTimeoutDirectAccess (test.test_ftplib.TestTimeouts) ... ok testTimeoutNone (test.test_ftplib.TestTimeouts) ... ok testTimeoutValue (test.test_ftplib.TestTimeouts) ... ok test_acct (test.test_ftplib.TestTLS_FTPClassMixin) ... ok test_all_errors (test.test_ftplib.TestTLS_FTPClassMixin) ... ok test_delete (test.test_ftplib.TestTLS_FTPClassMixin) ... ok test_dir (test.test_ftplib.TestTLS_FTPClassMixin) ... ERROR test_exceptions (test.test_ftplib.TestTLS_FTPClassMixin) ... Exception in thread Thread-244: Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/threading.py", line 530, in __bootstrap_inner self.run() File "/tmp/python-test/local/lib/python2.7/test/test_ftplib.py", line 232, in run asyncore.loop(timeout=0.1, count=1) File "/tmp/python-test/local/lib/python2.7/asyncore.py", line 214, in loop poll_fun(timeout, map) File "/tmp/python-test/local/lib/python2.7/asyncore.py", line 151, in poll read(obj) File "/tmp/python-test/local/lib/python2.7/asyncore.py", line 83, in read obj.handle_error() File "/tmp/python-test/local/lib/python2.7/asyncore.py", line 79, in read obj.handle_read_event() File "/tmp/python-test/local/lib/python2.7/test/test_ftplib.py", line 313, in handle_read_event super(SSLConnection, self).handle_read_event() File "/tmp/python-test/local/lib/python2.7/asyncore.py", line 435, in handle_read_event self.handle_read() File "/tmp/python-test/local/lib/python2.7/asynchat.py", line 158, in handle_read self.found_terminator() File "/tmp/python-test/local/lib/python2.7/test/test_ftplib.py", line 88, in found_terminator method(arg) File "/tmp/python-test/local/lib/python2.7/test/test_ftplib.py", line 391, in cmd_prot self.push('200 Protection set to Private') File "/tmp/python-test/local/lib/python2.7/test/test_ftplib.py", line 96, in push asynchat.async_chat.push(self, data + '\r\n') File "/tmp/python-test/local/lib/python2.7/asynchat.py", line 186, in push self.initiate_send() File "/tmp/python-test/local/lib/python2.7/asynchat.py", line 244, in initiate_send del self.producer_fifo[0] IndexError: deque index out of range ok test_getwelcome (test.test_ftplib.TestTLS_FTPClassMixin) ... ok test_login (test.test_ftplib.TestTLS_FTPClassMixin) ... ok test_makepasv (test.test_ftplib.TestTLS_FTPClassMixin) ... ok test_makeport (test.test_ftplib.TestTLS_FTPClassMixin) ... ok test_mkd (test.test_ftplib.TestTLS_FTPClassMixin) ... ok test_nlst (test.test_ftplib.TestTLS_FTPClassMixin) ... ok test_pwd (test.test_ftplib.TestTLS_FTPClassMixin) ... ok test_quit (test.test_ftplib.TestTLS_FTPClassMixin) ... ok test_rename (test.test_ftplib.TestTLS_FTPClassMixin) ... ok test_retrbinary (test.test_ftplib.TestTLS_FTPClassMixin) ... ok test_retrbinary_rest (test.test_ftplib.TestTLS_FTPClassMixin) ... ok test_retrlines (test.test_ftplib.TestTLS_FTPClassMixin) ... ok test_rmd (test.test_ftplib.TestTLS_FTPClassMixin) ... ok test_sanitize (test.test_ftplib.TestTLS_FTPClassMixin) ... ok test_set_pasv (test.test_ftplib.TestTLS_FTPClassMixin) ... ok test_size (test.test_ftplib.TestTLS_FTPClassMixin) ... ok test_storbinary (test.test_ftplib.TestTLS_FTPClassMixin) ... ok test_storbinary_rest (test.test_ftplib.TestTLS_FTPClassMixin) ... ok test_storlines (test.test_ftplib.TestTLS_FTPClassMixin) ... ok test_voidcmd (test.test_ftplib.TestTLS_FTPClassMixin) ... ok test_auth_issued_twice (test.test_ftplib.TestTLS_FTPClass) ... ok test_auth_ssl (test.test_ftplib.TestTLS_FTPClass) ... ok test_control_connection (test.test_ftplib.TestTLS_FTPClass) ... ok test_data_connection (test.test_ftplib.TestTLS_FTPClass) ... ok test_login (test.test_ftplib.TestTLS_FTPClass) ... ok ====================================================================== ERROR: test_dir (test.test_ftplib.TestTLS_FTPClassMixin) ---------------------------------------------------------------------- Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/test_ftplib.py", line 602, in setUp self.client.prot_p() File "/tmp/python-test/local/lib/python2.7/ftplib.py", line 661, in prot_p resp = self.voidcmd('PROT P') File "/tmp/python-test/local/lib/python2.7/ftplib.py", line 249, in voidcmd return self.voidresp() File "/tmp/python-test/local/lib/python2.7/ftplib.py", line 224, in voidresp resp = self.getresp() File "/tmp/python-test/local/lib/python2.7/ftplib.py", line 210, in getresp resp = self.getmultiline() File "/tmp/python-test/local/lib/python2.7/ftplib.py", line 196, in getmultiline line = self.getline() File "/tmp/python-test/local/lib/python2.7/ftplib.py", line 183, in getline line = self.file.readline() File "/tmp/python-test/local/lib/python2.7/socket.py", line 445, in readline data = self._sock.recv(self._rbufsize) File "/tmp/python-test/local/lib/python2.7/ssl.py", line 217, in recv return self.read(buflen) File "/tmp/python-test/local/lib/python2.7/ssl.py", line 138, in read return self._sslobj.read(len) SSLError: The read operation timed out ---------------------------------------------------------------------- Ran 61 tests in 28.391s FAILED (errors=1) test test_ftplib failed -- Traceback (most recent call last): File "/tmp/python-test/local/lib/python2.7/test/test_ftplib.py", line 602, in setUp self.client.prot_p() File "/tmp/python-test/local/lib/python2.7/ftplib.py", line 661, in prot_p resp = self.voidcmd('PROT P') File "/tmp/python-test/local/lib/python2.7/ftplib.py", line 249, in voidcmd return self.voidresp() File "/tmp/python-test/local/lib/python2.7/ftplib.py", line 224, in voidresp resp = self.getresp() File "/tmp/python-test/local/lib/python2.7/ftplib.py", line 210, in getresp resp = self.getmultiline() File "/tmp/python-test/local/lib/python2.7/ftplib.py", line 196, in getmultiline line = self.getline() File "/tmp/python-test/local/lib/python2.7/ftplib.py", line 183, in getline line = self.file.readline() File "/tmp/python-test/local/lib/python2.7/socket.py", line 445, in readline data = self._sock.recv(self._rbufsize) File "/tmp/python-test/local/lib/python2.7/ssl.py", line 217, in recv return self.read(buflen) File "/tmp/python-test/local/lib/python2.7/ssl.py", line 138, in read return self._sslobj.read(len) SSLError: The read operation timed out test_funcattrs test_functools test_future test_future3 test_future4 test_future5 test_future_builtins test_gc test_gdb test_gdb skipped -- gdb versions before 7.0 didn't support python embedding Saw: GNU gdb 6.2.1 Copyright 2004 Free Software Foundation, Inc. GDB is free software, covered by the GNU General Public License, and you are welcome to change it and/or distribute copies of it under certain conditions. Type "show copying" to see the conditions. There is absolutely no warranty for GDB. Type "show warranty" for details. This GDB was configured as "i386-pc-linux-gnu". test_gdbm test_generators test_genericpath test_genexps test_getargs test_getargs2 test_getopt test_gettext test_gl test_gl skipped -- No module named gl test_glob test_global test_grp test_gzip test_hash test_hashlib test_heapq test_hmac test_hotshot test_htmllib test_htmlparser test_httplib test_httpservers [16678 refs] [16678 refs] [16678 refs] [26966 refs] test_imageop test_imaplib test_imgfile test_imgfile skipped -- No module named imgfile test_imp test_import test_importhooks test_importlib test_index test_inspect test_int test_int_literal test_io test_ioctl test_ioctl skipped -- Unable to open /dev/tty test_isinstance test_iter test_iterlen test_itertools test_json test_kqueue test_kqueue skipped -- test works only on BSD test_largefile test_lib2to3 test_linecache test_linuxaudiodev test_linuxaudiodev skipped -- Use of the `audio' resource not enabled test_list test_locale test_logging test_long test_long_future test_longexp test_macos test_macos skipped -- No module named MacOS test_macostools test_macostools skipped -- No module named MacOS test_macpath test_mailbox test_marshal test_math test_md5 test_memoryio test_memoryview test_mhlib test_mimetools test_mimetypes test_minidom test_mmap test_module test_modulefinder test_multibytecodec test_multibytecodec_support test_multifile test_multiprocessing test_multiprocessing skipped -- This platform lacks a functioning sem_open implementation, therefore, the required synchronization primitives needed will not function, see issue 3770. test_mutants test_mutex test_netrc test_new test_nis test_normalization fetching http://www.unicode.org/Public/5.2.0/ucd/NormalizationTest.txt ... test_ntpath test_old_mailbox test_openpty test_operator test_optparse test_os [16678 refs] [16678 refs] test_ossaudiodev test_ossaudiodev skipped -- Use of the `audio' resource not enabled test_parser Expecting 's_push: parser stack overflow' in next line s_push: parser stack overflow test_pdb test_peepholer test_pep247 test_pep263 test_pep277 test_pep277 skipped -- only NT+ and systems with Unicode-friendly filesystem encoding test_pep292 test_pep352 test_pickle test_pickletools test_pipes test_pkg test_pkgimport test_pkgutil test_platform [18074 refs] [18074 refs] test_plistlib test_poll test_popen [16683 refs] [16683 refs] [16683 refs] test_popen2 test_poplib test_posix test_posixpath test_pow test_pprint test_print test_profile test_profilehooks test_property test_pstats test_pty test_pwd test_py3kwarn test_py3kwarn skipped -- test.test_py3kwarn must be run with the -3 flag test_pyclbr test_pydoc [21890 refs] [21890 refs] [21890 refs] [21890 refs] [21890 refs] [21889 refs] [21889 refs] test_pyexpat test_queue test_quopri [19507 refs] [19507 refs] test_random test_re test_readline test_repr test_resource test_rfc822 test_richcmp test_robotparser test_runpy test_sax test_scope test_scriptpackages test_scriptpackages skipped -- No module named aetools test_select test_set test_setcomps test_sets test_sgmllib test_sha test_shelve test_shlex test_shutil test_signal test_site [16678 refs] [16678 refs] [16678 refs] [16678 refs] test_slice test_smtplib test_smtpnet test_smtpnet skipped -- Use of the `network' resource not enabled test_socket test_socketserver test_socketserver skipped -- Use of the `network' resource not enabled test_softspace test_sort test_sqlite test_ssl test_startfile test_startfile skipped -- module os has no attribute startfile test_str test_strftime test_string test_stringprep test_strop test_strptime test_strtod test_struct test_structmembers test_structseq test_subprocess [16678 refs] [16678 refs] [16678 refs] [16678 refs] [16678 refs] [16678 refs] [16678 refs] [16678 refs] [16678 refs] [16678 refs] [16678 refs] [16678 refs] [16678 refs] [16678 refs] [16893 refs] [16678 refs] [16678 refs] [16678 refs] [16678 refs] [16678 refs] . [16678 refs] [16678 refs] this bit of output is from a test of stdout in a different process ... [16678 refs] [16678 refs] [16893 refs] [16678 refs] [16678 refs] [16678 refs] [16678 refs] [16678 refs] [16678 refs] [16678 refs] [16678 refs] [16678 refs] [16678 refs] [16678 refs] [16678 refs] [16678 refs] [16678 refs] [16678 refs] [16678 refs] [16678 refs] [16893 refs] [16678 refs] [16678 refs] [16678 refs] [16678 refs] [16678 refs] . [16678 refs] [16678 refs] this bit of output is from a test of stdout in a different process ... [16678 refs] [16678 refs] [16893 refs] test_sunaudiodev test_sunaudiodev skipped -- No module named sunaudiodev test_sundry test_symtable test_syntax test_sys [16678 refs] [16678 refs] [16678 refs] [16907 refs] [16701 refs] test_sysconfig [16678 refs] [16678 refs] test_tarfile test_tcl test_tcl skipped -- No module named _tkinter test_telnetlib test_tempfile [16678 refs] test_textwrap test_thread test_threaded_import test_threadedtempfile test_threading [19978 refs] [21247 refs] [21061 refs] [21061 refs] [21061 refs] [21061 refs] test_threading_local test_threadsignals test_time test_timeout test_timeout skipped -- Use of the `network' resource not enabled test_tk test_tk skipped -- No module named _tkinter test_tokenize test_trace test_traceback test_transformer test_ttk_guionly test_ttk_guionly skipped -- No module named _tkinter test_ttk_textonly test_ttk_textonly skipped -- No module named _tkinter test_tuple test_typechecks test_ucn test_unary test_undocumented_details test_unicode test_unicode_file test_unicode_file skipped -- No Unicode filesystem semantics on this platform. test_unicodedata test_univnewlines test_univnewlines2k test_unpack test_urllib test_urllib2 test_urllib2_localnet test_urllib2net test_urllib2net skipped -- Use of the `network' resource not enabled test_urllibnet test_urllibnet skipped -- Use of the `network' resource not enabled test_urlparse test_userdict test_userlist test_userstring test_uu test_uuid test_wait3 test_wait4 test_warnings [16709 refs] [16709 refs] [16702 refs] [16709 refs] [16709 refs] [16702 refs] test_wave test_weakref test_weakset test_whichdb test_winreg test_winreg skipped -- No module named _winreg test_winsound test_winsound skipped -- No module named winsound test_with test_wsgiref test_xdrlib test_xml_etree test_xml_etree_c test_xmllib test_xmlrpc test_xpickle test_xpickle -- skipping backwards compat tests. Use 'regrtest.py -u xpickle' to run them. test_xrange test_zipfile test_zipfile64 test_zipfile64 skipped -- test requires loads of disk-space bytes and a long time to run test_zipimport test_zipimport_support test_zlib 346 tests OK. 1 test failed: test_ftplib 37 tests skipped: test_aepack test_al test_applesingle test_bsddb185 test_bsddb3 test_cd test_cl test_curses test_epoll test_gdb test_gl test_imgfile test_ioctl test_kqueue test_linuxaudiodev test_macos test_macostools test_multiprocessing test_ossaudiodev test_pep277 test_py3kwarn test_scriptpackages test_smtpnet test_socketserver test_startfile test_sunaudiodev test_tcl test_timeout test_tk test_ttk_guionly test_ttk_textonly test_unicode_file test_urllib2net test_urllibnet test_winreg test_winsound test_zipfile64 7 skips unexpected on linux2: test_epoll test_gdb test_ioctl test_multiprocessing test_tk test_ttk_guionly test_ttk_textonly [965248 refs] From python-checkins at python.org Wed May 26 22:45:37 2010 From: python-checkins at python.org (alexander.belopolsky) Date: Wed, 26 May 2010 22:45:37 +0200 (CEST) Subject: [Python-checkins] r81559 - python/trunk/Lib/test/test_datetime.py Message-ID: <20100526204537.6A66AEEA17@mail.python.org> Author: alexander.belopolsky Date: Wed May 26 22:45:37 2010 New Revision: 81559 Log: Issue #7879: Skip negative timestamps test on any Windows platform using unittest.skipIf decorator. Modified: python/trunk/Lib/test/test_datetime.py Modified: python/trunk/Lib/test/test_datetime.py ============================================================================== --- python/trunk/Lib/test/test_datetime.py (original) +++ python/trunk/Lib/test/test_datetime.py Wed May 26 22:45:37 2010 @@ -1510,19 +1510,14 @@ for insane in -1e200, 1e200: self.assertRaises(ValueError, self.theclass.utcfromtimestamp, insane) - + @unittest.skipIf(sys.platform == "win32", "Windows doesn't accept negative timestamps") def test_negative_float_fromtimestamp(self): - # Windows doesn't accept negative timestamps - if sys.platform == "win32": - return # The result is tz-dependent; at least test that this doesn't # fail (like it did before bug 1646728 was fixed). self.theclass.fromtimestamp(-1.05) + @unittest.skipIf(sys.platform == "win32", "Windows doesn't accept negative timestamps") def test_negative_float_utcfromtimestamp(self): - # Windows doesn't accept negative timestamps - if sys.platform == "win32": - return d = self.theclass.utcfromtimestamp(-1.05) self.assertEquals(d, self.theclass(1969, 12, 31, 23, 59, 58, 950000)) From python-checkins at python.org Wed May 26 22:48:30 2010 From: python-checkins at python.org (alexander.belopolsky) Date: Wed, 26 May 2010 22:48:30 +0200 (CEST) Subject: [Python-checkins] r81560 - in python/branches/py3k: Lib/test/test_datetime.py Message-ID: <20100526204830.99D25EE988@mail.python.org> Author: alexander.belopolsky Date: Wed May 26 22:48:30 2010 New Revision: 81560 Log: Merged revisions 81559 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r81559 | alexander.belopolsky | 2010-05-26 16:45:37 -0400 (Wed, 26 May 2010) | 3 lines Issue #7879: Skip negative timestamps test on any Windows platform using unittest.skipIf decorator. ........ Modified: python/branches/py3k/ (props changed) python/branches/py3k/Lib/test/test_datetime.py Modified: python/branches/py3k/Lib/test/test_datetime.py ============================================================================== --- python/branches/py3k/Lib/test/test_datetime.py (original) +++ python/branches/py3k/Lib/test/test_datetime.py Wed May 26 22:48:30 2010 @@ -1554,19 +1554,14 @@ for insane in -1e200, 1e200: self.assertRaises(ValueError, self.theclass.utcfromtimestamp, insane) - + @unittest.skipIf(sys.platform == "win32", "Windows doesn't accept negative timestamps") def test_negative_float_fromtimestamp(self): - # Windows doesn't accept negative timestamps - if sys.platform == "win32": - return # The result is tz-dependent; at least test that this doesn't # fail (like it did before bug 1646728 was fixed). self.theclass.fromtimestamp(-1.05) + @unittest.skipIf(sys.platform == "win32", "Windows doesn't accept negative timestamps") def test_negative_float_utcfromtimestamp(self): - # Windows doesn't accept negative timestamps - if sys.platform == "win32": - return d = self.theclass.utcfromtimestamp(-1.05) self.assertEquals(d, self.theclass(1969, 12, 31, 23, 59, 58, 950000)) From python-checkins at python.org Wed May 26 22:57:04 2010 From: python-checkins at python.org (alexander.belopolsky) Date: Wed, 26 May 2010 22:57:04 +0200 (CEST) Subject: [Python-checkins] r81561 - python/trunk/Misc/ACKS Message-ID: <20100526205704.F0374EE9BD@mail.python.org> Author: alexander.belopolsky Date: Wed May 26 22:57:04 2010 New Revision: 81561 Log: Added Andrej Krpic. (Thanks for issue #7879 patch.) Modified: python/trunk/Misc/ACKS Modified: python/trunk/Misc/ACKS ============================================================================== --- python/trunk/Misc/ACKS (original) +++ python/trunk/Misc/ACKS Wed May 26 22:57:04 2010 @@ -861,3 +861,4 @@ Uwe Zessin Tarek Ziad? Peter ?strand +Andrej Krpic From solipsis at pitrou.net Thu May 27 01:24:30 2010 From: solipsis at pitrou.net (solipsis at pitrou.net) Date: Thu, 27 May 2010 01:24:30 +0200 (CEST) Subject: [Python-checkins] Daily py3k reference leaks (r81560): sum=0 Message-ID: <20100526232430.9CB211770A@ns6635.ovh.net> py3k results for svn r81560 (hg cset 4e8f8d83957d) -------------------------------------------------- Command line was: ['./python', '-m', 'test.regrtest', '-uall', '-R', '3:3:/home/antoine/py3k/refleaks/reflogpSIE3m', '-x'] From ezio.melotti at gmail.com Thu May 27 01:40:12 2010 From: ezio.melotti at gmail.com (Ezio Melotti) Date: Thu, 27 May 2010 02:40:12 +0300 Subject: [Python-checkins] r81548 - in python/branches/py3k: Doc/library/ftplib.rst Lib/ftplib.py Lib/test/test_ftplib.py Misc/NEWS In-Reply-To: <20100526180604.86C75EEA3F@mail.python.org> References: <20100526180604.86C75EEA3F@mail.python.org> Message-ID: <4BFDB15C.7040901@gmail.com> Hi, On 26/05/2010 21.06, giampaolo.rodola wrote: > Author: giampaolo.rodola > Date: Wed May 26 20:06:04 2010 > New Revision: 81548 > > Log: > Fix issue #8806: add SSL contexts support to ftplib > > Modified: > python/branches/py3k/Doc/library/ftplib.rst > python/branches/py3k/Lib/ftplib.py > python/branches/py3k/Lib/test/test_ftplib.py > python/branches/py3k/Misc/NEWS > > Modified: python/branches/py3k/Doc/library/ftplib.rst > ============================================================================== > --- python/branches/py3k/Doc/library/ftplib.rst (original) > +++ python/branches/py3k/Doc/library/ftplib.rst Wed May 26 20:06:04 2010 > @@ -65,7 +65,7 @@ > Support for the :keyword:`with` statement was added. > > > -.. class:: FTP_TLS(host='', user='', passwd='', acct='', [keyfile[, certfile[, timeout]]]) > +.. class:: FTP_TLS(host='', user='', passwd='', acct='', [keyfile[, certfile[, context[, timeout]]]]) > > A :class:`FTP` subclass which adds TLS support to FTP as described in > :rfc:`4217`. > @@ -74,6 +74,9 @@ > explicitly ask for it by calling the :meth:`prot_p` method. > *keyfile* and *certfile* are optional -- they can contain a PEM formatted > private key and certificate chain file name for the SSL connection. > + *context* parameter is a :class:`ssl.SSLContext` object which allows > + bundling SSL configuration options, certificates and private keys into a > + single (potentially long-lived) structure. > > .. versionadded:: 3.2 > > > Modified: python/branches/py3k/Lib/ftplib.py > ============================================================================== > --- python/branches/py3k/Lib/ftplib.py (original) > +++ python/branches/py3k/Lib/ftplib.py Wed May 26 20:06:04 2010 > @@ -638,9 +638,17 @@ > ssl_version = ssl.PROTOCOL_TLSv1 > > def __init__(self, host='', user='', passwd='', acct='', keyfile=None, > - certfile=None, timeout=_GLOBAL_DEFAULT_TIMEOUT): > + certfile=None, context=None, > + timeout=_GLOBAL_DEFAULT_TIMEOUT): The new context arg has been added in the second last position, isn't this not backward compatible in the (maybe unlikely) case that someone was creating an instance of FTP_TLS using only positional args? > + if context is not None and keyfile is not None: > + raise ValueError("context and keyfile arguments are mutually " > + "exclusive") > + if context is not None and certfile is not None: > + raise ValueError("context and certfile arguments are mutually " > + "exclusive") > self.keyfile = keyfile > self.certfile = certfile > + self.context = context > self._prot_p = False > FTP.__init__(self, host, user, passwd, acct, timeout) > > @@ -657,8 +665,12 @@ > resp = self.voidcmd('AUTH TLS') > else: > resp = self.voidcmd('AUTH SSL') > - self.sock = ssl.wrap_socket(self.sock, self.keyfile, self.certfile, > - ssl_version=self.ssl_version) > + if self.context is not None: > + self.sock = self.context.wrap_socket(self.sock) > + else: > + self.sock = ssl.wrap_socket(self.sock, self.keyfile, > + self.certfile, > + ssl_version=self.ssl_version) > self.file = self.sock.makefile(mode='r', encoding=self.encoding) > return resp > > @@ -689,8 +701,11 @@ > def ntransfercmd(self, cmd, rest=None): > conn, size = FTP.ntransfercmd(self, cmd, rest) > if self._prot_p: > - conn = ssl.wrap_socket(conn, self.keyfile, self.certfile, > - ssl_version=self.ssl_version) > + if self.context is not None: > + conn = self.context.wrap_socket(conn) > + else: > + conn = ssl.wrap_socket(conn, self.keyfile, self.certfile, > + ssl_version=self.ssl_version) > return conn, size > > def retrbinary(self, cmd, callback, blocksize=8192, rest=None): > > Modified: python/branches/py3k/Lib/test/test_ftplib.py > ============================================================================== > --- python/branches/py3k/Lib/test/test_ftplib.py (original) > +++ python/branches/py3k/Lib/test/test_ftplib.py Wed May 26 20:06:04 2010 > @@ -719,6 +719,29 @@ > finally: > self.client.ssl_version = ssl.PROTOCOL_TLSv1 > > + def test_context(self): > + self.client.quit() > + ctx = ssl.SSLContext(ssl.PROTOCOL_TLSv1) > + self.assertRaises(ValueError, ftplib.FTP_TLS, keyfile=CERTFILE, > + context=ctx) > + self.assertRaises(ValueError, ftplib.FTP_TLS, certfile=CERTFILE, > + context=ctx) > + self.assertRaises(ValueError, ftplib.FTP_TLS, certfile=CERTFILE, > + keyfile=CERTFILE, context=ctx) > + > + self.client = ftplib.FTP_TLS(context=ctx, timeout=2) > + self.client.connect(self.server.host, self.server.port) > + self.assertNotIsInstance(self.client.sock, ssl.SSLSocket) > + self.client.auth() > + self.assertIs(self.client.sock.context, ctx) > + self.assertIsInstance(self.client.sock, ssl.SSLSocket) > + > + self.client.prot_p() > + sock = self.client.transfercmd('list') > + self.assertIs(self.client.sock.context, ctx) > + self.assertIsInstance(sock, ssl.SSLSocket) > + sock.close() > + > > class TestTimeouts(TestCase): > > > Modified: python/branches/py3k/Misc/NEWS > ============================================================================== > --- python/branches/py3k/Misc/NEWS (original) > +++ python/branches/py3k/Misc/NEWS Wed May 26 20:06:04 2010 > @@ -392,6 +392,8 @@ > Library > ------- > > +- Issue #8806: add SSL contexts support to ftplib. > + > - Issue #4769: Fix main() function of the base64 module, use sys.stdin.buffer > and sys.stdout.buffer (instead of sys.stdin and sys.stdout) to use the bytes > API > _______________________________________________ > Python-checkins mailing list > Python-checkins at python.org > http://mail.python.org/mailman/listinfo/python-checkins > From g.rodola at gmail.com Thu May 27 13:01:31 2010 From: g.rodola at gmail.com (=?ISO-8859-1?Q?Giampaolo_Rodol=E0?=) Date: Thu, 27 May 2010 13:01:31 +0200 Subject: [Python-checkins] r81548 - in python/branches/py3k: Doc/library/ftplib.rst Lib/ftplib.py Lib/test/test_ftplib.py Misc/NEWS In-Reply-To: <4BFDB15C.7040901@gmail.com> References: <20100526180604.86C75EEA3F@mail.python.org> <4BFDB15C.7040901@gmail.com> Message-ID: That's fine since FTP_TLS class has been added in Python 3.2. 2010/5/27 Ezio Melotti : > Hi, > > On 26/05/2010 21.06, giampaolo.rodola wrote: >> >> Author: giampaolo.rodola >> Date: Wed May 26 20:06:04 2010 >> New Revision: 81548 >> >> Log: >> Fix issue #8806: add SSL contexts support to ftplib >> >> Modified: >> python/branches/py3k/Doc/library/ftplib.rst >> python/branches/py3k/Lib/ftplib.py >> python/branches/py3k/Lib/test/test_ftplib.py >> python/branches/py3k/Misc/NEWS >> >> Modified: python/branches/py3k/Doc/library/ftplib.rst >> >> ============================================================================== >> --- python/branches/py3k/Doc/library/ftplib.rst (original) >> +++ python/branches/py3k/Doc/library/ftplib.rst Wed May 26 20:06:04 2010 >> @@ -65,7 +65,7 @@ >> Support for the :keyword:`with` statement was added. >> >> >> -.. class:: FTP_TLS(host='', user='', passwd='', acct='', [keyfile[, >> certfile[, timeout]]]) >> +.. class:: FTP_TLS(host='', user='', passwd='', acct='', [keyfile[, >> certfile[, context[, timeout]]]]) >> >> A :class:`FTP` subclass which adds TLS support to FTP as described in >> :rfc:`4217`. >> @@ -74,6 +74,9 @@ >> explicitly ask for it by calling the :meth:`prot_p` method. >> *keyfile* and *certfile* are optional -- they can contain a PEM >> formatted >> private key and certificate chain file name for the SSL connection. >> + *context* parameter is a :class:`ssl.SSLContext` object which allows >> + bundling SSL configuration options, certificates and private keys into >> a >> + single (potentially long-lived) structure. >> >> .. versionadded:: 3.2 >> >> >> Modified: python/branches/py3k/Lib/ftplib.py >> >> ============================================================================== >> --- python/branches/py3k/Lib/ftplib.py (original) >> +++ python/branches/py3k/Lib/ftplib.py Wed May 26 20:06:04 2010 >> @@ -638,9 +638,17 @@ >> ssl_version = ssl.PROTOCOL_TLSv1 >> >> def __init__(self, host='', user='', passwd='', acct='', >> keyfile=None, >> - certfile=None, timeout=_GLOBAL_DEFAULT_TIMEOUT): >> + certfile=None, context=None, >> + timeout=_GLOBAL_DEFAULT_TIMEOUT): > > The new context arg has been added in the second last position, isn't this > not backward compatible in the (maybe unlikely) case that someone was > creating an instance of FTP_TLS using only positional args? > > >> + if context is not None and keyfile is not None: >> + raise ValueError("context and keyfile arguments are >> mutually " >> + "exclusive") >> + if context is not None and certfile is not None: >> + raise ValueError("context and certfile arguments are >> mutually " >> + "exclusive") >> self.keyfile = keyfile >> self.certfile = certfile >> + self.context = context >> self._prot_p = False >> FTP.__init__(self, host, user, passwd, acct, timeout) >> >> @@ -657,8 +665,12 @@ >> resp = self.voidcmd('AUTH TLS') >> else: >> resp = self.voidcmd('AUTH SSL') >> - self.sock = ssl.wrap_socket(self.sock, self.keyfile, >> self.certfile, >> - ssl_version=self.ssl_version) >> + if self.context is not None: >> + self.sock = self.context.wrap_socket(self.sock) >> + else: >> + self.sock = ssl.wrap_socket(self.sock, self.keyfile, >> + self.certfile, >> + ssl_version=self.ssl_version) >> self.file = self.sock.makefile(mode='r', >> encoding=self.encoding) >> return resp >> >> @@ -689,8 +701,11 @@ >> def ntransfercmd(self, cmd, rest=None): >> conn, size = FTP.ntransfercmd(self, cmd, rest) >> if self._prot_p: >> - conn = ssl.wrap_socket(conn, self.keyfile, self.certfile, >> - ssl_version=self.ssl_version) >> + if self.context is not None: >> + conn = self.context.wrap_socket(conn) >> + else: >> + conn = ssl.wrap_socket(conn, self.keyfile, >> self.certfile, >> + ssl_version=self.ssl_version) >> return conn, size >> >> def retrbinary(self, cmd, callback, blocksize=8192, rest=None): >> >> Modified: python/branches/py3k/Lib/test/test_ftplib.py >> >> ============================================================================== >> --- python/branches/py3k/Lib/test/test_ftplib.py (original) >> +++ python/branches/py3k/Lib/test/test_ftplib.py Wed May 26 >> 20:06:04 2010 >> @@ -719,6 +719,29 @@ >> finally: >> self.client.ssl_version = ssl.PROTOCOL_TLSv1 >> >> + def test_context(self): >> + self.client.quit() >> + ctx = ssl.SSLContext(ssl.PROTOCOL_TLSv1) >> + self.assertRaises(ValueError, ftplib.FTP_TLS, keyfile=CERTFILE, >> + context=ctx) >> + self.assertRaises(ValueError, ftplib.FTP_TLS, certfile=CERTFILE, >> + context=ctx) >> + self.assertRaises(ValueError, ftplib.FTP_TLS, certfile=CERTFILE, >> + keyfile=CERTFILE, context=ctx) >> + >> + self.client = ftplib.FTP_TLS(context=ctx, timeout=2) >> + self.client.connect(self.server.host, self.server.port) >> + self.assertNotIsInstance(self.client.sock, ssl.SSLSocket) >> + self.client.auth() >> + self.assertIs(self.client.sock.context, ctx) >> + self.assertIsInstance(self.client.sock, ssl.SSLSocket) >> + >> + self.client.prot_p() >> + sock = self.client.transfercmd('list') >> + self.assertIs(self.client.sock.context, ctx) >> + self.assertIsInstance(sock, ssl.SSLSocket) >> + sock.close() >> + >> >> class TestTimeouts(TestCase): >> >> >> Modified: python/branches/py3k/Misc/NEWS >> >> ============================================================================== >> --- python/branches/py3k/Misc/NEWS (original) >> +++ python/branches/py3k/Misc/NEWS Wed May 26 20:06:04 2010 >> @@ -392,6 +392,8 @@ >> Library >> ------- >> >> +- Issue #8806: add SSL contexts support to ftplib. >> + >> - Issue #4769: Fix main() function of the base64 module, use >> sys.stdin.buffer >> and sys.stdout.buffer (instead of sys.stdin and sys.stdout) to use the >> bytes >> API >> _______________________________________________ >> Python-checkins mailing list >> Python-checkins at python.org >> http://mail.python.org/mailman/listinfo/python-checkins >> > > _______________________________________________ > Python-checkins mailing list > Python-checkins at python.org > http://mail.python.org/mailman/listinfo/python-checkins > From python-checkins at python.org Thu May 27 15:22:53 2010 From: python-checkins at python.org (andrew.kuchling) Date: Thu, 27 May 2010 15:22:53 +0200 (CEST) Subject: [Python-checkins] r81562 - python/trunk/Doc/faq/gui.rst Message-ID: <20100527132253.CEF50EEA03@mail.python.org> Author: andrew.kuchling Date: Thu May 27 15:22:53 2010 New Revision: 81562 Log: Rewrite wxWidgets section Modified: python/trunk/Doc/faq/gui.rst Modified: python/trunk/Doc/faq/gui.rst ============================================================================== --- python/trunk/Doc/faq/gui.rst (original) +++ python/trunk/Doc/faq/gui.rst Thu May 27 15:22:53 2010 @@ -28,17 +28,22 @@ wxWidgets ''''''''' -wxWidgets is a GUI class library written in C++ that's a portable -interface to various platform-specific libraries, and that has a -Python interface called `wxPython `__. - -wxWidgets preserves the look and feel of the -underlying graphics toolkit, and has a large set of widgets and -collection of GDI classes. See `the wxWidgets page -`_ for more details. +wxWidgets (http://www.wxwidgets.org) is a free, portable GUI class +library written in C++ that provides a native look and feel on a +number of platforms, with Windows, MacOS X, GTK, X11, all listed as +current stable targets. Language bindings are available for a number +of languages including Python, Perl, Ruby, etc. + +wxPython (http://www.wxpython.org) is the Python binding for +wxwidgets. While it often lags slightly behind the official wxWidgets +releases, it also offers a number of features via pure Python +extensions that are not available in other language bindings. There +is an active wxPython user and developer community. + +Both wxWidgets and wxPython are free, open source, software with +permissive licences that allow their use in commercial products as +well as in freeware or shareware. -wxWidgets supports Windows and MacOS; on Unix variants, -it supports both GTk+ and Motif toolkits. Qt ''' From python-checkins at python.org Thu May 27 15:30:09 2010 From: python-checkins at python.org (andrew.kuchling) Date: Thu, 27 May 2010 15:30:09 +0200 (CEST) Subject: [Python-checkins] r81563 - python/trunk/Doc/faq/gui.rst Message-ID: <20100527133009.DE32FEEA4D@mail.python.org> Author: andrew.kuchling Date: Thu May 27 15:30:09 2010 New Revision: 81563 Log: Remove top-level 'General Questions' section, pushing up the questions it contains Modified: python/trunk/Doc/faq/gui.rst Modified: python/trunk/Doc/faq/gui.rst ============================================================================== --- python/trunk/Doc/faq/gui.rst (original) +++ python/trunk/Doc/faq/gui.rst Thu May 27 15:30:09 2010 @@ -6,18 +6,15 @@ .. contents:: -General GUI Questions -===================== - What platform-independent GUI toolkits exist for Python? --------------------------------------------------------- +======================================================== Depending on what platform(s) you are aiming at, there are several. .. XXX check links Tkinter -''''''' +------- Standard builds of Python include an object-oriented interface to the Tcl/Tk widget set, called Tkinter. This is probably the easiest to install and use. @@ -26,7 +23,7 @@ Unix platforms. wxWidgets -''''''''' +--------- wxWidgets (http://www.wxwidgets.org) is a free, portable GUI class library written in C++ that provides a native look and feel on a @@ -46,7 +43,7 @@ Qt -''' +--- There are bindings available for the Qt toolkit (`PyQt `_) and for KDE (`PyKDE `__). If @@ -57,13 +54,13 @@ `_. Gtk+ -'''' +---- PyGtk bindings for the `Gtk+ toolkit `_ have been implemented by James Henstridge; see . FLTK -'''' +---- Python bindings for `the FLTK toolkit `_, a simple yet powerful and mature cross-platform windowing system, are available from `the @@ -71,7 +68,7 @@ FOX -''' +---- A wrapper for `the FOX toolkit `_ called `FXpy `_ is available. FOX supports both Unix variants @@ -79,13 +76,13 @@ OpenGL -'''''' +------ For OpenGL bindings, see `PyOpenGL `_. What platform-specific GUI toolkits exist for Python? ------------------------------------------------------ +======================================================== `The Mac port `_ by Jack Jansen has a rich and ever-growing set of modules that support the native Mac toolbox calls. The port From brett at python.org Thu May 27 20:36:56 2010 From: brett at python.org (Brett Cannon) Date: Thu, 27 May 2010 11:36:56 -0700 Subject: [Python-checkins] r81561 - python/trunk/Misc/ACKS In-Reply-To: <20100526205704.F0374EE9BD@mail.python.org> References: <20100526205704.F0374EE9BD@mail.python.org> Message-ID: We try to keep the ACKS file alphabetized, so Andrej's entry should go in the K section (Peter's is down at the end simply because he has an accented A which doesn't really sort well). On Wed, May 26, 2010 at 13:57, alexander.belopolsky wrote: > Author: alexander.belopolsky > Date: Wed May 26 22:57:04 2010 > New Revision: 81561 > > Log: > Added Andrej Krpic. (Thanks for issue #7879 patch.) > > Modified: > ? python/trunk/Misc/ACKS > > Modified: python/trunk/Misc/ACKS > ============================================================================== > --- python/trunk/Misc/ACKS ? ? ?(original) > +++ python/trunk/Misc/ACKS ? ? ?Wed May 26 22:57:04 2010 > @@ -861,3 +861,4 @@ > ?Uwe Zessin > ?Tarek Ziad? > ?Peter ?strand > +Andrej Krpic > _______________________________________________ > Python-checkins mailing list > Python-checkins at python.org > http://mail.python.org/mailman/listinfo/python-checkins > From python-checkins at python.org Thu May 27 21:45:50 2010 From: python-checkins at python.org (mark.dickinson) Date: Thu, 27 May 2010 21:45:50 +0200 (CEST) Subject: [Python-checkins] r81564 - in python/branches/py3k: Misc/ACKS Message-ID: <20100527194550.6432DF037@mail.python.org> Author: mark.dickinson Date: Thu May 27 21:45:50 2010 New Revision: 81564 Log: Merged revisions 81512 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r81512 | brett.cannon | 2010-05-25 03:53:04 +0100 (Tue, 25 May 2010) | 1 line Make the contributor list alphabetical again. ........ Modified: python/branches/py3k/ (props changed) python/branches/py3k/Misc/ACKS Modified: python/branches/py3k/Misc/ACKS ============================================================================== --- python/branches/py3k/Misc/ACKS (original) +++ python/branches/py3k/Misc/ACKS Thu May 27 21:45:50 2010 @@ -363,6 +363,7 @@ Eric Huss Jeremy Hylton Gerhard H?ring +Fredrik H??rd Mihai Ibanescu Lars Immisch Meador Inge @@ -871,4 +872,3 @@ Uwe Zessin Tarek Ziad? Peter ?strand -Fredrik H??rd From python-checkins at python.org Thu May 27 21:47:53 2010 From: python-checkins at python.org (mark.dickinson) Date: Thu, 27 May 2010 21:47:53 +0200 (CEST) Subject: [Python-checkins] r81565 - python/branches/py3k/Misc/ACKS Message-ID: <20100527194753.34B44EEA01@mail.python.org> Author: mark.dickinson Date: Thu May 27 21:47:53 2010 New Revision: 81565 Log: Stefan Krah was missing from Misc/ACKS in the py3k branch. Modified: python/branches/py3k/Misc/ACKS Modified: python/branches/py3k/Misc/ACKS ============================================================================== --- python/branches/py3k/Misc/ACKS (original) +++ python/branches/py3k/Misc/ACKS Thu May 27 21:47:53 2010 @@ -425,6 +425,7 @@ Damon Kohler Joseph Koshy Maksim Kozyarchuk +Stefan Krah Bob Kras Holger Krekel Michael Kremer From python-checkins at python.org Thu May 27 22:55:27 2010 From: python-checkins at python.org (alexander.belopolsky) Date: Thu, 27 May 2010 22:55:27 +0200 (CEST) Subject: [Python-checkins] r81566 - in python/trunk: Lib/test/test_datetime.py Misc/NEWS Modules/datetimemodule.c Message-ID: <20100527205527.D1E82EEA56@mail.python.org> Author: alexander.belopolsky Date: Thu May 27 22:55:27 2010 New Revision: 81566 Log: Issue #7150: Raise OverflowError if the result of adding or subtracting timedelta from date or datetime falls outside of the MINYEAR:MAXYEAR range. Modified: python/trunk/Lib/test/test_datetime.py python/trunk/Misc/NEWS python/trunk/Modules/datetimemodule.c Modified: python/trunk/Lib/test/test_datetime.py ============================================================================== --- python/trunk/Lib/test/test_datetime.py (original) +++ python/trunk/Lib/test/test_datetime.py Thu May 27 22:55:27 2010 @@ -720,15 +720,16 @@ def test_overflow(self): tiny = self.theclass.resolution - dt = self.theclass.min + tiny - dt -= tiny # no problem - self.assertRaises(OverflowError, dt.__sub__, tiny) - self.assertRaises(OverflowError, dt.__add__, -tiny) - - dt = self.theclass.max - tiny - dt += tiny # no problem - self.assertRaises(OverflowError, dt.__add__, tiny) - self.assertRaises(OverflowError, dt.__sub__, -tiny) + for delta in [tiny, timedelta(1), timedelta(2)]: + dt = self.theclass.min + delta + dt -= delta # no problem + self.assertRaises(OverflowError, dt.__sub__, delta) + self.assertRaises(OverflowError, dt.__add__, -delta) + + dt = self.theclass.max - delta + dt += delta # no problem + self.assertRaises(OverflowError, dt.__add__, delta) + self.assertRaises(OverflowError, dt.__sub__, -delta) def test_fromtimestamp(self): import time Modified: python/trunk/Misc/NEWS ============================================================================== --- python/trunk/Misc/NEWS (original) +++ python/trunk/Misc/NEWS Thu May 27 22:55:27 2010 @@ -32,6 +32,9 @@ Library ------- +- Issue #7150: Raise OverflowError if the result of adding or subtracting + timedelta from date or datetime falls outside of the MINYEAR:MAXYEAR range. + - Issue #6662: Fix parsing of malformatted charref (&#bad;), patch written by Fredrik H??rd Modified: python/trunk/Modules/datetimemodule.c ============================================================================== --- python/trunk/Modules/datetimemodule.c (original) +++ python/trunk/Modules/datetimemodule.c Thu May 27 22:55:27 2010 @@ -32,6 +32,7 @@ #define MINYEAR 1 #define MAXYEAR 9999 +#define MAXORDINAL 3652059 /* date(9999,12,31).toordinal() */ /* Nine decimal digits is easy to communicate, and leaves enough room * so that two delta days can be added w/o fear of overflowing a signed @@ -482,7 +483,7 @@ * The input values must be such that the internals don't overflow. * The way this routine is used, we don't get close. */ -static void +static int normalize_y_m_d(int *y, int *m, int *d) { int dim; /* # of days in month */ @@ -536,11 +537,23 @@ else { int ordinal = ymd_to_ord(*y, *m, 1) + *d - 1; - ord_to_ymd(ordinal, y, m, d); + if (ordinal < 1 || ordinal > MAXORDINAL) { + goto error; + } else { + ord_to_ymd(ordinal, y, m, d); + return 0; + } } } assert(*m > 0); assert(*d > 0); + if (MINYEAR <= *y && *y <= MAXYEAR) + return 0; + error: + PyErr_SetString(PyExc_OverflowError, + "date value out of range"); + return -1; + } /* Fiddle out-of-bounds months and days so that the result makes some kind @@ -550,17 +563,7 @@ static int normalize_date(int *year, int *month, int *day) { - int result; - - normalize_y_m_d(year, month, day); - if (MINYEAR <= *year && *year <= MAXYEAR) - result = 0; - else { - PyErr_SetString(PyExc_OverflowError, - "date value out of range"); - result = -1; - } - return result; + return normalize_y_m_d(year, month, day); } /* Force all the datetime fields into range. The parameters are both From python-checkins at python.org Thu May 27 23:29:59 2010 From: python-checkins at python.org (andrew.kuchling) Date: Thu, 27 May 2010 23:29:59 +0200 (CEST) Subject: [Python-checkins] r81567 - python/trunk/Doc/whatsnew/2.7.rst Message-ID: <20100527212959.C0A8BEE992@mail.python.org> Author: andrew.kuchling Date: Thu May 27 23:29:59 2010 New Revision: 81567 Log: Add item Modified: python/trunk/Doc/whatsnew/2.7.rst Modified: python/trunk/Doc/whatsnew/2.7.rst ============================================================================== --- python/trunk/Doc/whatsnew/2.7.rst (original) +++ python/trunk/Doc/whatsnew/2.7.rst Thu May 27 23:29:59 2010 @@ -2354,6 +2354,12 @@ In the standard library: +* Operations with :class:`datetime` instances that resulted in a year + falling outside the supported range didn't always raise + :exc:`OverflowError`. Such errors are now checked more carefully + and will now raise the exception. (Reported by Mark Leander, patch + by Anand B. Pillai and Alexander Belopolsky; :issue:`7150`.) + * When using :class:`Decimal` instances with a string's :meth:`format` method, the default alignment was previously left-alignment. This has been changed to right-alignment, which might From python-checkins at python.org Thu May 27 23:42:58 2010 From: python-checkins at python.org (alexander.belopolsky) Date: Thu, 27 May 2010 23:42:58 +0200 (CEST) Subject: [Python-checkins] r81568 - in python/branches/py3k: Lib/test/test_datetime.py Misc/NEWS Modules/datetimemodule.c Message-ID: <20100527214258.E1338EEAC8@mail.python.org> Author: alexander.belopolsky Date: Thu May 27 23:42:58 2010 New Revision: 81568 Log: Merged revisions 81566 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r81566 | alexander.belopolsky | 2010-05-27 16:55:27 -0400 (Thu, 27 May 2010) | 3 lines Issue #7150: Raise OverflowError if the result of adding or subtracting timedelta from date or datetime falls outside of the MINYEAR:MAXYEAR range. ........ Modified: python/branches/py3k/ (props changed) python/branches/py3k/Lib/test/test_datetime.py python/branches/py3k/Misc/NEWS python/branches/py3k/Modules/datetimemodule.c Modified: python/branches/py3k/Lib/test/test_datetime.py ============================================================================== --- python/branches/py3k/Lib/test/test_datetime.py (original) +++ python/branches/py3k/Lib/test/test_datetime.py Thu May 27 23:42:58 2010 @@ -761,15 +761,16 @@ def test_overflow(self): tiny = self.theclass.resolution - dt = self.theclass.min + tiny - dt -= tiny # no problem - self.assertRaises(OverflowError, dt.__sub__, tiny) - self.assertRaises(OverflowError, dt.__add__, -tiny) - - dt = self.theclass.max - tiny - dt += tiny # no problem - self.assertRaises(OverflowError, dt.__add__, tiny) - self.assertRaises(OverflowError, dt.__sub__, -tiny) + for delta in [tiny, timedelta(1), timedelta(2)]: + dt = self.theclass.min + delta + dt -= delta # no problem + self.assertRaises(OverflowError, dt.__sub__, delta) + self.assertRaises(OverflowError, dt.__add__, -delta) + + dt = self.theclass.max - delta + dt += delta # no problem + self.assertRaises(OverflowError, dt.__add__, delta) + self.assertRaises(OverflowError, dt.__sub__, -delta) def test_fromtimestamp(self): import time Modified: python/branches/py3k/Misc/NEWS ============================================================================== --- python/branches/py3k/Misc/NEWS (original) +++ python/branches/py3k/Misc/NEWS Thu May 27 23:42:58 2010 @@ -395,6 +395,9 @@ Library ------- +- Issue #7150: Raise OverflowError if the result of adding or subtracting + timedelta from date or datetime falls outside of the MINYEAR:MAXYEAR range. + - Issue #8806: add SSL contexts support to ftplib. - Issue #4769: Fix main() function of the base64 module, use sys.stdin.buffer Modified: python/branches/py3k/Modules/datetimemodule.c ============================================================================== --- python/branches/py3k/Modules/datetimemodule.c (original) +++ python/branches/py3k/Modules/datetimemodule.c Thu May 27 23:42:58 2010 @@ -30,6 +30,7 @@ #define MINYEAR 1 #define MAXYEAR 9999 +#define MAXORDINAL 3652059 /* date(9999,12,31).toordinal() */ /* Nine decimal digits is easy to communicate, and leaves enough room * so that two delta days can be added w/o fear of overflowing a signed @@ -480,7 +481,7 @@ * The input values must be such that the internals don't overflow. * The way this routine is used, we don't get close. */ -static void +static int normalize_y_m_d(int *y, int *m, int *d) { int dim; /* # of days in month */ @@ -534,11 +535,23 @@ else { int ordinal = ymd_to_ord(*y, *m, 1) + *d - 1; - ord_to_ymd(ordinal, y, m, d); + if (ordinal < 1 || ordinal > MAXORDINAL) { + goto error; + } else { + ord_to_ymd(ordinal, y, m, d); + return 0; + } } } assert(*m > 0); assert(*d > 0); + if (MINYEAR <= *y && *y <= MAXYEAR) + return 0; + error: + PyErr_SetString(PyExc_OverflowError, + "date value out of range"); + return -1; + } /* Fiddle out-of-bounds months and days so that the result makes some kind @@ -548,17 +561,7 @@ static int normalize_date(int *year, int *month, int *day) { - int result; - - normalize_y_m_d(year, month, day); - if (MINYEAR <= *year && *year <= MAXYEAR) - result = 0; - else { - PyErr_SetString(PyExc_OverflowError, - "date value out of range"); - result = -1; - } - return result; + return normalize_y_m_d(year, month, day); } /* Force all the datetime fields into range. The parameters are both From python-checkins at python.org Thu May 27 23:53:17 2010 From: python-checkins at python.org (alexander.belopolsky) Date: Thu, 27 May 2010 23:53:17 +0200 (CEST) Subject: [Python-checkins] r81569 - in python/branches/release26-maint: Lib/test/test_datetime.py Misc/NEWS Modules/datetimemodule.c Message-ID: <20100527215317.28685EE9AD@mail.python.org> Author: alexander.belopolsky Date: Thu May 27 23:53:16 2010 New Revision: 81569 Log: Merged revisions 81566 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r81566 | alexander.belopolsky | 2010-05-27 16:55:27 -0400 (Thu, 27 May 2010) | 3 lines Issue #7150: Raise OverflowError if the result of adding or subtracting timedelta from date or datetime falls outside of the MINYEAR:MAXYEAR range. ........ Modified: python/branches/release26-maint/ (props changed) python/branches/release26-maint/Lib/test/test_datetime.py python/branches/release26-maint/Misc/NEWS python/branches/release26-maint/Modules/datetimemodule.c Modified: python/branches/release26-maint/Lib/test/test_datetime.py ============================================================================== --- python/branches/release26-maint/Lib/test/test_datetime.py (original) +++ python/branches/release26-maint/Lib/test/test_datetime.py Thu May 27 23:53:16 2010 @@ -709,15 +709,16 @@ def test_overflow(self): tiny = self.theclass.resolution - dt = self.theclass.min + tiny - dt -= tiny # no problem - self.assertRaises(OverflowError, dt.__sub__, tiny) - self.assertRaises(OverflowError, dt.__add__, -tiny) - - dt = self.theclass.max - tiny - dt += tiny # no problem - self.assertRaises(OverflowError, dt.__add__, tiny) - self.assertRaises(OverflowError, dt.__sub__, -tiny) + for delta in [tiny, timedelta(1), timedelta(2)]: + dt = self.theclass.min + delta + dt -= delta # no problem + self.assertRaises(OverflowError, dt.__sub__, delta) + self.assertRaises(OverflowError, dt.__add__, -delta) + + dt = self.theclass.max - delta + dt += delta # no problem + self.assertRaises(OverflowError, dt.__add__, delta) + self.assertRaises(OverflowError, dt.__sub__, -delta) def test_fromtimestamp(self): import time Modified: python/branches/release26-maint/Misc/NEWS ============================================================================== --- python/branches/release26-maint/Misc/NEWS (original) +++ python/branches/release26-maint/Misc/NEWS Thu May 27 23:53:16 2010 @@ -58,6 +58,9 @@ Library ------- +- Issue #7150: Raise OverflowError if the result of adding or subtracting + timedelta from date or datetime falls outside of the MINYEAR:MAXYEAR range. + - Issue #6662: Fix parsing of malformatted charref (&#bad;), patch written by Fredrik H??rd Modified: python/branches/release26-maint/Modules/datetimemodule.c ============================================================================== --- python/branches/release26-maint/Modules/datetimemodule.c (original) +++ python/branches/release26-maint/Modules/datetimemodule.c Thu May 27 23:53:16 2010 @@ -32,6 +32,7 @@ #define MINYEAR 1 #define MAXYEAR 9999 +#define MAXORDINAL 3652059 /* date(9999,12,31).toordinal() */ /* Nine decimal digits is easy to communicate, and leaves enough room * so that two delta days can be added w/o fear of overflowing a signed @@ -482,7 +483,7 @@ * The input values must be such that the internals don't overflow. * The way this routine is used, we don't get close. */ -static void +static int normalize_y_m_d(int *y, int *m, int *d) { int dim; /* # of days in month */ @@ -536,11 +537,23 @@ else { int ordinal = ymd_to_ord(*y, *m, 1) + *d - 1; - ord_to_ymd(ordinal, y, m, d); + if (ordinal < 1 || ordinal > MAXORDINAL) { + goto error; + } else { + ord_to_ymd(ordinal, y, m, d); + return 0; + } } } assert(*m > 0); assert(*d > 0); + if (MINYEAR <= *y && *y <= MAXYEAR) + return 0; + error: + PyErr_SetString(PyExc_OverflowError, + "date value out of range"); + return -1; + } /* Fiddle out-of-bounds months and days so that the result makes some kind @@ -550,17 +563,7 @@ static int normalize_date(int *year, int *month, int *day) { - int result; - - normalize_y_m_d(year, month, day); - if (MINYEAR <= *year && *year <= MAXYEAR) - result = 0; - else { - PyErr_SetString(PyExc_OverflowError, - "date value out of range"); - result = -1; - } - return result; + return normalize_y_m_d(year, month, day); } /* Force all the datetime fields into range. The parameters are both From python-checkins at python.org Fri May 28 00:03:53 2010 From: python-checkins at python.org (alexander.belopolsky) Date: Fri, 28 May 2010 00:03:53 +0200 (CEST) Subject: [Python-checkins] r81570 - in python/branches/release31-maint: Lib/test/test_datetime.py Misc/NEWS Modules/datetimemodule.c Message-ID: <20100527220353.E380BEE9AD@mail.python.org> Author: alexander.belopolsky Date: Fri May 28 00:03:53 2010 New Revision: 81570 Log: Merged revisions 81568 via svnmerge from svn+ssh://pythondev at svn.python.org/python/branches/py3k ................ r81568 | alexander.belopolsky | 2010-05-27 17:42:58 -0400 (Thu, 27 May 2010) | 10 lines Merged revisions 81566 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r81566 | alexander.belopolsky | 2010-05-27 16:55:27 -0400 (Thu, 27 May 2010) | 3 lines Issue #7150: Raise OverflowError if the result of adding or subtracting timedelta from date or datetime falls outside of the MINYEAR:MAXYEAR range. ........ ................ Modified: python/branches/release31-maint/ (props changed) python/branches/release31-maint/Lib/test/test_datetime.py python/branches/release31-maint/Misc/NEWS python/branches/release31-maint/Modules/datetimemodule.c Modified: python/branches/release31-maint/Lib/test/test_datetime.py ============================================================================== --- python/branches/release31-maint/Lib/test/test_datetime.py (original) +++ python/branches/release31-maint/Lib/test/test_datetime.py Fri May 28 00:03:53 2010 @@ -700,15 +700,16 @@ def test_overflow(self): tiny = self.theclass.resolution - dt = self.theclass.min + tiny - dt -= tiny # no problem - self.assertRaises(OverflowError, dt.__sub__, tiny) - self.assertRaises(OverflowError, dt.__add__, -tiny) - - dt = self.theclass.max - tiny - dt += tiny # no problem - self.assertRaises(OverflowError, dt.__add__, tiny) - self.assertRaises(OverflowError, dt.__sub__, -tiny) + for delta in [tiny, timedelta(1), timedelta(2)]: + dt = self.theclass.min + delta + dt -= delta # no problem + self.assertRaises(OverflowError, dt.__sub__, delta) + self.assertRaises(OverflowError, dt.__add__, -delta) + + dt = self.theclass.max - delta + dt += delta # no problem + self.assertRaises(OverflowError, dt.__add__, delta) + self.assertRaises(OverflowError, dt.__sub__, -delta) def test_fromtimestamp(self): import time Modified: python/branches/release31-maint/Misc/NEWS ============================================================================== --- python/branches/release31-maint/Misc/NEWS (original) +++ python/branches/release31-maint/Misc/NEWS Fri May 28 00:03:53 2010 @@ -54,6 +54,9 @@ Library ------- +- Issue #7150: Raise OverflowError if the result of adding or subtracting + timedelta from date or datetime falls outside of the MINYEAR:MAXYEAR range. + - Issue #4769: Fix main() function of the base64 module, use sys.stdin.buffer and sys.stdout.buffer (instead of sys.stdin and sys.stdout) to use the bytes API Modified: python/branches/release31-maint/Modules/datetimemodule.c ============================================================================== --- python/branches/release31-maint/Modules/datetimemodule.c (original) +++ python/branches/release31-maint/Modules/datetimemodule.c Fri May 28 00:03:53 2010 @@ -30,6 +30,7 @@ #define MINYEAR 1 #define MAXYEAR 9999 +#define MAXORDINAL 3652059 /* date(9999,12,31).toordinal() */ /* Nine decimal digits is easy to communicate, and leaves enough room * so that two delta days can be added w/o fear of overflowing a signed @@ -480,7 +481,7 @@ * The input values must be such that the internals don't overflow. * The way this routine is used, we don't get close. */ -static void +static int normalize_y_m_d(int *y, int *m, int *d) { int dim; /* # of days in month */ @@ -534,11 +535,23 @@ else { int ordinal = ymd_to_ord(*y, *m, 1) + *d - 1; - ord_to_ymd(ordinal, y, m, d); + if (ordinal < 1 || ordinal > MAXORDINAL) { + goto error; + } else { + ord_to_ymd(ordinal, y, m, d); + return 0; + } } } assert(*m > 0); assert(*d > 0); + if (MINYEAR <= *y && *y <= MAXYEAR) + return 0; + error: + PyErr_SetString(PyExc_OverflowError, + "date value out of range"); + return -1; + } /* Fiddle out-of-bounds months and days so that the result makes some kind @@ -548,17 +561,7 @@ static int normalize_date(int *year, int *month, int *day) { - int result; - - normalize_y_m_d(year, month, day); - if (MINYEAR <= *year && *year <= MAXYEAR) - result = 0; - else { - PyErr_SetString(PyExc_OverflowError, - "date value out of range"); - result = -1; - } - return result; + return normalize_y_m_d(year, month, day); } /* Force all the datetime fields into range. The parameters are both From python-checkins at python.org Fri May 28 00:29:48 2010 From: python-checkins at python.org (victor.stinner) Date: Fri, 28 May 2010 00:29:48 +0200 (CEST) Subject: [Python-checkins] r81571 - in python/trunk: Lib/test/test_support.py Misc/NEWS Message-ID: <20100527222948.67605C963@mail.python.org> Author: victor.stinner Date: Fri May 28 00:29:48 2010 New Revision: 81571 Log: Issue #8835: test_support.transient_internet() catchs gaierror(EAI_NONAME) and gaierror(EAI_NODATA) Modified: python/trunk/Lib/test/test_support.py python/trunk/Misc/NEWS Modified: python/trunk/Lib/test/test_support.py ============================================================================== --- python/trunk/Lib/test/test_support.py (original) +++ python/trunk/Lib/test/test_support.py Fri May 28 00:29:48 2010 @@ -757,7 +757,9 @@ time_out = TransientResource(IOError, errno=errno.ETIMEDOUT) socket_peer_reset = TransientResource(socket.error, errno=errno.ECONNRESET) ioerror_peer_reset = TransientResource(IOError, errno=errno.ECONNRESET) - with time_out, socket_peer_reset, ioerror_peer_reset: + dns_nodata = TransientResource(socket.gaierror, errno=socket.EAI_NODATA) + dns_noname = TransientResource(socket.gaierror, errno=socket.EAI_NONAME) + with time_out, socket_peer_reset, ioerror_peer_reset, dns_nodata, dns_noname: yield Modified: python/trunk/Misc/NEWS ============================================================================== --- python/trunk/Misc/NEWS (original) +++ python/trunk/Misc/NEWS Fri May 28 00:29:48 2010 @@ -78,6 +78,9 @@ Tests ----- +- Issue #8835: test_support.transient_internet() catchs gaierror(EAI_NONAME) + and gaierror(EAI_NODATA) + - Issue #7449: Skip test_socketserver if threading support is disabled - On darwin, ``test_site`` assumed that a framework build was being used, From python-checkins at python.org Fri May 28 00:32:22 2010 From: python-checkins at python.org (benjamin.peterson) Date: Fri, 28 May 2010 00:32:22 +0200 (CEST) Subject: [Python-checkins] r81572 - python/branches/py3k/Doc/library/functions.rst Message-ID: <20100527223222.72595EE981@mail.python.org> Author: benjamin.peterson Date: Fri May 28 00:32:22 2010 New Revision: 81572 Log: correct default value in signature Modified: python/branches/py3k/Doc/library/functions.rst Modified: python/branches/py3k/Doc/library/functions.rst ============================================================================== --- python/branches/py3k/Doc/library/functions.rst (original) +++ python/branches/py3k/Doc/library/functions.rst Fri May 28 00:32:22 2010 @@ -1227,7 +1227,7 @@ True -.. function:: __import__(name, globals={}, locals={}, fromlist=[], level=-1) +.. function:: __import__(name, globals={}, locals={}, fromlist=[], level=0) .. index:: statement: import From python-checkins at python.org Fri May 28 00:33:18 2010 From: python-checkins at python.org (ezio.melotti) Date: Fri, 28 May 2010 00:33:18 +0200 (CEST) Subject: [Python-checkins] r81573 - python/branches/release26-maint Message-ID: <20100527223318.116E6EE981@mail.python.org> Author: ezio.melotti Date: Fri May 28 00:33:17 2010 New Revision: 81573 Log: Blocked revisions 81318 via svnmerge ........ r81318 | ezio.melotti | 2010-05-19 03:32:52 +0300 (Wed, 19 May 2010) | 1 line Fix typo in argparse doc. ........ Modified: python/branches/release26-maint/ (props changed) From python-checkins at python.org Fri May 28 00:36:14 2010 From: python-checkins at python.org (benjamin.peterson) Date: Fri, 28 May 2010 00:36:14 +0200 (CEST) Subject: [Python-checkins] r81574 - in python/branches/release31-maint: Doc/library/functions.rst Message-ID: <20100527223614.512EAEE982@mail.python.org> Author: benjamin.peterson Date: Fri May 28 00:36:14 2010 New Revision: 81574 Log: Merged revisions 81572 via svnmerge from svn+ssh://pythondev at svn.python.org/python/branches/py3k ........ r81572 | benjamin.peterson | 2010-05-27 17:32:22 -0500 (Thu, 27 May 2010) | 1 line correct default value in signature ........ Modified: python/branches/release31-maint/ (props changed) python/branches/release31-maint/Doc/library/functions.rst Modified: python/branches/release31-maint/Doc/library/functions.rst ============================================================================== --- python/branches/release31-maint/Doc/library/functions.rst (original) +++ python/branches/release31-maint/Doc/library/functions.rst Fri May 28 00:36:14 2010 @@ -1219,7 +1219,7 @@ True -.. function:: __import__(name, globals={}, locals={}, fromlist=[], level=-1) +.. function:: __import__(name, globals={}, locals={}, fromlist=[], level=0) .. index:: statement: import From python-checkins at python.org Fri May 28 00:38:16 2010 From: python-checkins at python.org (ezio.melotti) Date: Fri, 28 May 2010 00:38:16 +0200 (CEST) Subject: [Python-checkins] r81575 - in python/branches/py3k: Doc/library/argparse.rst Message-ID: <20100527223816.79956EE9A0@mail.python.org> Author: ezio.melotti Date: Fri May 28 00:38:16 2010 New Revision: 81575 Log: Merged revisions 81318 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r81318 | ezio.melotti | 2010-05-19 03:32:52 +0300 (Wed, 19 May 2010) | 1 line Fix typo in argparse doc. ........ Modified: python/branches/py3k/ (props changed) python/branches/py3k/Doc/library/argparse.rst Modified: python/branches/py3k/Doc/library/argparse.rst ============================================================================== --- python/branches/py3k/Doc/library/argparse.rst (original) +++ python/branches/py3k/Doc/library/argparse.rst Fri May 28 00:38:16 2010 @@ -452,7 +452,7 @@ By default, :class:`ArgumentParser` objects uses ``sys.argv[0]`` to determine how to display the name of the program in help messages. This default is almost -always desirable because it will make the help messages match how the pgoram was +always desirable because it will make the help messages match how the program was invoked on the command line. For example, consider a file named ``myprogram.py`` with the following code:: From python-checkins at python.org Fri May 28 00:44:00 2010 From: python-checkins at python.org (ezio.melotti) Date: Fri, 28 May 2010 00:44:00 +0200 (CEST) Subject: [Python-checkins] r81576 - python/branches/release31-maint Message-ID: <20100527224400.C62DCEE9BF@mail.python.org> Author: ezio.melotti Date: Fri May 28 00:44:00 2010 New Revision: 81576 Log: Blocked revisions 81575 via svnmerge ................ r81575 | ezio.melotti | 2010-05-28 01:38:16 +0300 (Fri, 28 May 2010) | 9 lines Merged revisions 81318 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r81318 | ezio.melotti | 2010-05-19 03:32:52 +0300 (Wed, 19 May 2010) | 1 line Fix typo in argparse doc. ........ ................ Modified: python/branches/release31-maint/ (props changed) From solipsis at pitrou.net Fri May 28 01:25:56 2010 From: solipsis at pitrou.net (solipsis at pitrou.net) Date: Fri, 28 May 2010 01:25:56 +0200 (CEST) Subject: [Python-checkins] Daily py3k reference leaks (r81565): sum=0 Message-ID: <20100527232556.6E8F31771F@ns6635.ovh.net> py3k results for svn r81565 (hg cset 2aa866396a6a) -------------------------------------------------- Command line was: ['./python', '-m', 'test.regrtest', '-uall', '-R', '3:3:/home/antoine/py3k/refleaks/reflog6SuNF6', '-x'] From python-checkins at python.org Fri May 28 01:54:25 2010 From: python-checkins at python.org (barry.warsaw) Date: Fri, 28 May 2010 01:54:25 +0200 (CEST) Subject: [Python-checkins] r81577 - peps/trunk/pep-3147.txt Message-ID: <20100527235425.F17B0EE9EF@mail.python.org> Author: barry.warsaw Date: Fri May 28 01:54:25 2010 New Revision: 81577 Log: Add good suggestion on how to tell if you have PEP 3147 support. Modified: peps/trunk/pep-3147.txt Modified: peps/trunk/pep-3147.txt ============================================================================== --- peps/trunk/pep-3147.txt (original) +++ peps/trunk/pep-3147.txt Fri May 28 01:54:25 2010 @@ -348,6 +348,16 @@ Python and outside. This section enumerates some of these effects. +Detecting PEP 3147 availability +------------------------------- + +The easiest way to detect whether your version of Python provides PEP +3147 functionality is to do the following check:: + + >>> import imp + >>> has3147 = hasattr(imp, 'get_tag') + + __file__ --------- From python-checkins at python.org Fri May 28 04:12:37 2010 From: python-checkins at python.org (benjamin.peterson) Date: Fri, 28 May 2010 04:12:37 +0200 (CEST) Subject: [Python-checkins] r81578 - python/trunk/Lib/getopt.py Message-ID: <20100528021237.05802EE98B@mail.python.org> Author: benjamin.peterson Date: Fri May 28 04:12:36 2010 New Revision: 81578 Log: remove non-ascii coding per PEP 8 Modified: python/trunk/Lib/getopt.py Modified: python/trunk/Lib/getopt.py ============================================================================== --- python/trunk/Lib/getopt.py (original) +++ python/trunk/Lib/getopt.py Fri May 28 04:12:36 2010 @@ -1,4 +1,3 @@ -# -*- coding: iso-8859-1 -*- """Parser for command line options. This module helps scripts to parse the command line arguments in @@ -20,7 +19,7 @@ # Gerrit Holl moved the string-based exceptions # to class-based exceptions. # -# Peter ?strand added gnu_getopt(). +# Peter Astrand added gnu_getopt(). # # TODO for gnu_getopt(): # From python-checkins at python.org Fri May 28 05:10:31 2010 From: python-checkins at python.org (benjamin.peterson) Date: Fri, 28 May 2010 05:10:31 +0200 (CEST) Subject: [Python-checkins] r81579 - python/trunk/Doc/library/test.rst Message-ID: <20100528031031.2D928EE9B1@mail.python.org> Author: benjamin.peterson Date: Fri May 28 05:10:31 2010 New Revision: 81579 Log: 2to3 doesn't fix test_support #6583 Modified: python/trunk/Doc/library/test.rst Modified: python/trunk/Doc/library/test.rst ============================================================================== --- python/trunk/Doc/library/test.rst (original) +++ python/trunk/Doc/library/test.rst Fri May 28 05:10:31 2010 @@ -188,11 +188,7 @@ .. note:: The :mod:`test.test_support` module has been renamed to :mod:`test.support` - in Python 3.0. The :term:`2to3` tool will automatically adapt imports when - converting your sources to 3.0. - - - + in Python 3.x. The :mod:`test.test_support` module provides support for Python's regression tests. From python-checkins at python.org Fri May 28 05:23:52 2010 From: python-checkins at python.org (benjamin.peterson) Date: Fri, 28 May 2010 05:23:52 +0200 (CEST) Subject: [Python-checkins] r81580 - in python/branches/release26-maint: Doc/library/test.rst Message-ID: <20100528032352.412EAEE992@mail.python.org> Author: benjamin.peterson Date: Fri May 28 05:23:52 2010 New Revision: 81580 Log: Merged revisions 81579 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r81579 | benjamin.peterson | 2010-05-27 22:10:31 -0500 (Thu, 27 May 2010) | 1 line 2to3 doesn't fix test_support #6583 ........ Modified: python/branches/release26-maint/ (props changed) python/branches/release26-maint/Doc/library/test.rst Modified: python/branches/release26-maint/Doc/library/test.rst ============================================================================== --- python/branches/release26-maint/Doc/library/test.rst (original) +++ python/branches/release26-maint/Doc/library/test.rst Fri May 28 05:23:52 2010 @@ -188,11 +188,7 @@ .. note:: The :mod:`test.test_support` module has been renamed to :mod:`test.support` - in Python 3.0. The :term:`2to3` tool will automatically adapt imports when - converting your sources to 3.0. - - - + in Python 3.x. The :mod:`test.test_support` module provides support for Python's regression tests. From python-checkins at python.org Fri May 28 05:23:57 2010 From: python-checkins at python.org (benjamin.peterson) Date: Fri, 28 May 2010 05:23:57 +0200 (CEST) Subject: [Python-checkins] r81581 - python/branches/py3k Message-ID: <20100528032357.BAF6AEEA2E@mail.python.org> Author: benjamin.peterson Date: Fri May 28 05:23:57 2010 New Revision: 81581 Log: Blocked revisions 81578-81579 via svnmerge ........ r81578 | benjamin.peterson | 2010-05-27 21:12:36 -0500 (Thu, 27 May 2010) | 1 line remove non-ascii coding per PEP 8 ........ r81579 | benjamin.peterson | 2010-05-27 22:10:31 -0500 (Thu, 27 May 2010) | 1 line 2to3 doesn't fix test_support #6583 ........ Modified: python/branches/py3k/ (props changed) From python-checkins at python.org Fri May 28 17:28:48 2010 From: python-checkins at python.org (martin.v.loewis) Date: Fri, 28 May 2010 17:28:48 +0200 (CEST) Subject: [Python-checkins] r81582 - in python/trunk: Misc/NEWS configure configure.in Message-ID: <20100528152848.2D983EEA45@mail.python.org> Author: martin.v.loewis Date: Fri May 28 17:28:47 2010 New Revision: 81582 Log: Issue #1759169: Drop _XOPEN_SOURCE on Solaris. Modified: python/trunk/Misc/NEWS python/trunk/configure python/trunk/configure.in Modified: python/trunk/Misc/NEWS ============================================================================== --- python/trunk/Misc/NEWS (original) +++ python/trunk/Misc/NEWS Fri May 28 17:28:47 2010 @@ -87,6 +87,10 @@ leading to a failure where four directories were expected for site-packages instead of two in a non-framework build. +Build +----- + +- Issue #1759169: Drop _XOPEN_SOURCE on Solaris. What's New in Python 2.7 beta 2? ================================ Modified: python/trunk/configure ============================================================================== --- python/trunk/configure (original) +++ python/trunk/configure Fri May 28 17:28:47 2010 @@ -1,5 +1,5 @@ #! /bin/sh -# From configure.in Revision: 81077 . +# From configure.in Revision: 81509 . # Guess values for system-dependent variables and create Makefiles. # Generated by GNU Autoconf 2.65 for python 2.7. # @@ -3031,9 +3031,12 @@ # Marc Recht NetBSD/1.5 | NetBSD/1.5.* | NetBSD/1.6 | NetBSD/1.6.* | NetBSD/1.6[A-S]) define_xopen_source=no;; - # On Solaris 2.6, sys/wait.h is inconsistent in the usage - # of union __?sigval. Reported by Stuart Bishop. - SunOS/5.6) + # From the perspective of Solaris, _XOPEN_SOURCE is not so much a + # request to enable features supported by the standard as a request + # to disable features not supported by the standard. The best way + # for Python to use Solaris is simply to leave _XOPEN_SOURCE out + # entirely and define __EXTENSIONS__ instead. + SunOS/*) define_xopen_source=no;; # On UnixWare 7, u_long is never defined with _XOPEN_SOURCE, # but used in /usr/include/netinet/tcp.h. Reported by Tim Rice. @@ -3079,38 +3082,17 @@ if test $define_xopen_source = yes then - # On Solaris w/ g++ it appears that _XOPEN_SOURCE has to be - # defined precisely as g++ defines it - # Furthermore, on Solaris 10, XPG6 requires the use of a C99 - # compiler - case $ac_sys_system/$ac_sys_release in - SunOS/5.8|SunOS/5.9|SunOS/5.10) - -$as_echo "#define _XOPEN_SOURCE 500" >>confdefs.h - - ;; - *) $as_echo "#define _XOPEN_SOURCE 600" >>confdefs.h - ;; - esac # On Tru64 Unix 4.0F, defining _XOPEN_SOURCE also requires # definition of _XOPEN_SOURCE_EXTENDED and _POSIX_C_SOURCE, or else # several APIs are not declared. Since this is also needed in some # cases for HP-UX, we define it globally. - # except for Solaris 10, where it must not be defined, - # as it implies XPG4.2 - case $ac_sys_system/$ac_sys_release in - SunOS/5.10) - ;; - *) $as_echo "#define _XOPEN_SOURCE_EXTENDED 1" >>confdefs.h - ;; - esac $as_echo "#define _POSIX_C_SOURCE 200112L" >>confdefs.h Modified: python/trunk/configure.in ============================================================================== --- python/trunk/configure.in (original) +++ python/trunk/configure.in Fri May 28 17:28:47 2010 @@ -342,9 +342,12 @@ # Marc Recht NetBSD/1.5 | NetBSD/1.5.* | NetBSD/1.6 | NetBSD/1.6.* | NetBSD/1.6@<:@A-S@:>@) define_xopen_source=no;; - # On Solaris 2.6, sys/wait.h is inconsistent in the usage - # of union __?sigval. Reported by Stuart Bishop. - SunOS/5.6) + # From the perspective of Solaris, _XOPEN_SOURCE is not so much a + # request to enable features supported by the standard as a request + # to disable features not supported by the standard. The best way + # for Python to use Solaris is simply to leave _XOPEN_SOURCE out + # entirely and define __EXTENSIONS__ instead. + SunOS/*) define_xopen_source=no;; # On UnixWare 7, u_long is never defined with _XOPEN_SOURCE, # but used in /usr/include/netinet/tcp.h. Reported by Tim Rice. @@ -390,35 +393,15 @@ if test $define_xopen_source = yes then - # On Solaris w/ g++ it appears that _XOPEN_SOURCE has to be - # defined precisely as g++ defines it - # Furthermore, on Solaris 10, XPG6 requires the use of a C99 - # compiler - case $ac_sys_system/$ac_sys_release in - SunOS/5.8|SunOS/5.9|SunOS/5.10) - AC_DEFINE(_XOPEN_SOURCE, 500, - Define to the level of X/Open that your system supports) - ;; - *) - AC_DEFINE(_XOPEN_SOURCE, 600, - Define to the level of X/Open that your system supports) - ;; - esac + AC_DEFINE(_XOPEN_SOURCE, 600, + Define to the level of X/Open that your system supports) # On Tru64 Unix 4.0F, defining _XOPEN_SOURCE also requires # definition of _XOPEN_SOURCE_EXTENDED and _POSIX_C_SOURCE, or else # several APIs are not declared. Since this is also needed in some # cases for HP-UX, we define it globally. - # except for Solaris 10, where it must not be defined, - # as it implies XPG4.2 - case $ac_sys_system/$ac_sys_release in - SunOS/5.10) - ;; - *) - AC_DEFINE(_XOPEN_SOURCE_EXTENDED, 1, - Define to activate Unix95-and-earlier features) - ;; - esac + AC_DEFINE(_XOPEN_SOURCE_EXTENDED, 1, + Define to activate Unix95-and-earlier features) AC_DEFINE(_POSIX_C_SOURCE, 200112L, Define to activate features from IEEE Stds 1003.1-2001) From python-checkins at python.org Fri May 28 17:44:20 2010 From: python-checkins at python.org (martin.v.loewis) Date: Fri, 28 May 2010 17:44:20 +0200 (CEST) Subject: [Python-checkins] r81583 - in python/branches/py3k: Misc/NEWS configure configure.in Message-ID: <20100528154420.D500CEEA62@mail.python.org> Author: martin.v.loewis Date: Fri May 28 17:44:20 2010 New Revision: 81583 Log: Merged revisions 81582 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r81582 | martin.v.loewis | 2010-05-28 17:28:47 +0200 (Fr, 28 Mai 2010) | 2 lines Issue #1759169: Drop _XOPEN_SOURCE on Solaris. ........ Modified: python/branches/py3k/ (props changed) python/branches/py3k/Misc/NEWS python/branches/py3k/configure python/branches/py3k/configure.in Modified: python/branches/py3k/Misc/NEWS ============================================================================== --- python/branches/py3k/Misc/NEWS (original) +++ python/branches/py3k/Misc/NEWS Fri May 28 17:44:20 2010 @@ -1307,6 +1307,8 @@ Build ----- +- Issue #1759169: Drop _XOPEN_SOURCE on Solaris. + - Issue #8625: Turn off optimization in --with-pydebug builds with gcc. (Optimization was unintentionally turned on in gcc --with-pydebug builds as a result of the issue #1628484 fix, Modified: python/branches/py3k/configure ============================================================================== --- python/branches/py3k/configure (original) +++ python/branches/py3k/configure Fri May 28 17:44:20 2010 @@ -1,5 +1,5 @@ #! /bin/sh -# From configure.in Revision: 80834 . +# From configure.in Revision: 81078 . # Guess values for system-dependent variables and create Makefiles. # Generated by GNU Autoconf 2.65 for python 3.2. # @@ -1929,11 +1929,11 @@ cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ $ac_includes_default - enum { N = $2 / 2 - 1 }; int main () { -static int test_array [1 - 2 * !(0 < ($ac_type) ((((($ac_type) 1 << N) << N) - 1) * 2 + 1))]; +static int test_array [1 - 2 * !(enum { N = $2 / 2 - 1 }; + 0 < ($ac_type) ((((($ac_type) 1 << N) << N) - 1) * 2 + 1))]; test_array [0] = 0 ; @@ -1944,11 +1944,11 @@ cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ $ac_includes_default - enum { N = $2 / 2 - 1 }; int main () { -static int test_array [1 - 2 * !(($ac_type) ((((($ac_type) 1 << N) << N) - 1) * 2 + 1) +static int test_array [1 - 2 * !(enum { N = $2 / 2 - 1 }; + ($ac_type) ((((($ac_type) 1 << N) << N) - 1) * 2 + 1) < ($ac_type) ((((($ac_type) 1 << N) << N) - 1) * 2 + 2))]; test_array [0] = 0 @@ -3013,9 +3013,12 @@ # Marc Recht NetBSD/1.5 | NetBSD/1.5.* | NetBSD/1.6 | NetBSD/1.6.* | NetBSD/1.6[A-S]) define_xopen_source=no;; - # On Solaris 2.6, sys/wait.h is inconsistent in the usage - # of union __?sigval. Reported by Stuart Bishop. - SunOS/5.6) + # From the perspective of Solaris, _XOPEN_SOURCE is not so much a + # request to enable features supported by the standard as a request + # to disable features not supported by the standard. The best way + # for Python to use Solaris is simply to leave _XOPEN_SOURCE out + # entirely and define __EXTENSIONS__ instead. + SunOS/*) define_xopen_source=no;; # On UnixWare 7, u_long is never defined with _XOPEN_SOURCE, # but used in /usr/include/netinet/tcp.h. Reported by Tim Rice. @@ -3061,38 +3064,17 @@ if test $define_xopen_source = yes then - # On Solaris w/ g++ it appears that _XOPEN_SOURCE has to be - # defined precisely as g++ defines it - # Furthermore, on Solaris 10, XPG6 requires the use of a C99 - # compiler - case $ac_sys_system/$ac_sys_release in - SunOS/5.8|SunOS/5.9|SunOS/5.10) - -$as_echo "#define _XOPEN_SOURCE 500" >>confdefs.h - - ;; - *) $as_echo "#define _XOPEN_SOURCE 600" >>confdefs.h - ;; - esac # On Tru64 Unix 4.0F, defining _XOPEN_SOURCE also requires # definition of _XOPEN_SOURCE_EXTENDED and _POSIX_C_SOURCE, or else # several APIs are not declared. Since this is also needed in some # cases for HP-UX, we define it globally. - # except for Solaris 10, where it must not be defined, - # as it implies XPG4.2 - case $ac_sys_system/$ac_sys_release in - SunOS/5.10) - ;; - *) $as_echo "#define _XOPEN_SOURCE_EXTENDED 1" >>confdefs.h - ;; - esac $as_echo "#define _POSIX_C_SOURCE 200112L" >>confdefs.h Modified: python/branches/py3k/configure.in ============================================================================== --- python/branches/py3k/configure.in (original) +++ python/branches/py3k/configure.in Fri May 28 17:44:20 2010 @@ -330,9 +330,12 @@ # Marc Recht NetBSD/1.5 | NetBSD/1.5.* | NetBSD/1.6 | NetBSD/1.6.* | NetBSD/1.6@<:@A-S@:>@) define_xopen_source=no;; - # On Solaris 2.6, sys/wait.h is inconsistent in the usage - # of union __?sigval. Reported by Stuart Bishop. - SunOS/5.6) + # From the perspective of Solaris, _XOPEN_SOURCE is not so much a + # request to enable features supported by the standard as a request + # to disable features not supported by the standard. The best way + # for Python to use Solaris is simply to leave _XOPEN_SOURCE out + # entirely and define __EXTENSIONS__ instead. + SunOS/*) define_xopen_source=no;; # On UnixWare 7, u_long is never defined with _XOPEN_SOURCE, # but used in /usr/include/netinet/tcp.h. Reported by Tim Rice. @@ -378,35 +381,15 @@ if test $define_xopen_source = yes then - # On Solaris w/ g++ it appears that _XOPEN_SOURCE has to be - # defined precisely as g++ defines it - # Furthermore, on Solaris 10, XPG6 requires the use of a C99 - # compiler - case $ac_sys_system/$ac_sys_release in - SunOS/5.8|SunOS/5.9|SunOS/5.10) - AC_DEFINE(_XOPEN_SOURCE, 500, - Define to the level of X/Open that your system supports) - ;; - *) - AC_DEFINE(_XOPEN_SOURCE, 600, - Define to the level of X/Open that your system supports) - ;; - esac + AC_DEFINE(_XOPEN_SOURCE, 600, + Define to the level of X/Open that your system supports) # On Tru64 Unix 4.0F, defining _XOPEN_SOURCE also requires # definition of _XOPEN_SOURCE_EXTENDED and _POSIX_C_SOURCE, or else # several APIs are not declared. Since this is also needed in some # cases for HP-UX, we define it globally. - # except for Solaris 10, where it must not be defined, - # as it implies XPG4.2 - case $ac_sys_system/$ac_sys_release in - SunOS/5.10) - ;; - *) - AC_DEFINE(_XOPEN_SOURCE_EXTENDED, 1, - Define to activate Unix95-and-earlier features) - ;; - esac + AC_DEFINE(_XOPEN_SOURCE_EXTENDED, 1, + Define to activate Unix95-and-earlier features) AC_DEFINE(_POSIX_C_SOURCE, 200112L, Define to activate features from IEEE Stds 1003.1-2001) From python-checkins at python.org Fri May 28 17:49:21 2010 From: python-checkins at python.org (brian.curtin) Date: Fri, 28 May 2010 17:49:21 +0200 (CEST) Subject: [Python-checkins] r81584 - python/trunk/Lib/test/test_os.py Message-ID: <20100528154921.30F38EEA2F@mail.python.org> Author: brian.curtin Date: Fri May 28 17:49:21 2010 New Revision: 81584 Log: Fix #8405 for slow buildbots. Remove the sleep on startup and move the pipe communication into a loop to retry in case a buildbot gets even slower. Modified: python/trunk/Lib/test/test_os.py Modified: python/trunk/Lib/test/test_os.py ============================================================================== --- python/trunk/Lib/test/test_os.py (original) +++ python/trunk/Lib/test/test_os.py Fri May 28 17:49:21 2010 @@ -706,17 +706,22 @@ stderr=subprocess.PIPE, stdin=subprocess.PIPE) - # Let the process start up (See #3137) - time.sleep(0.5) - - # Create a string buffer to store the result of stdout from the pipe - buf = ctypes.create_string_buffer(len(msg)) - # Obtain the text currently in proc.stdout - # Bytes read/avail/left are left as NULL and unused - rslt = PeekNamedPipe(msvcrt.get_osfhandle(proc.stdout.fileno()), buf, - ctypes.sizeof(buf), None, None, None) - self.assertNotEqual(rslt, 0, "PeekNamedPipe failed") - self.assertEqual(msg, buf.value) + count, max = 0, 100 + while count < max and proc.poll() is None: + # Create a string buffer to store the result of stdout from the pipe + buf = ctypes.create_string_buffer(len(msg)) + # Obtain the text currently in proc.stdout + # Bytes read/avail/left are left as NULL and unused + rslt = PeekNamedPipe(msvcrt.get_osfhandle(proc.stdout.fileno()), + buf, ctypes.sizeof(buf), None, None, None) + self.assertNotEqual(rslt, 0, "PeekNamedPipe failed") + if buf.value: + self.assertEqual(msg, buf.value) + break + time.sleep(0.1) + count += 1 + else: + self.fail("Did not receive communication from the subprocess") os.kill(proc.pid, sig) self.assertEqual(proc.wait(), sig) From python-checkins at python.org Fri May 28 18:08:40 2010 From: python-checkins at python.org (brian.curtin) Date: Fri, 28 May 2010 18:08:40 +0200 (CEST) Subject: [Python-checkins] r81585 - in python/branches/py3k: Lib/test/test_os.py Message-ID: <20100528160840.3F583EEA89@mail.python.org> Author: brian.curtin Date: Fri May 28 18:08:40 2010 New Revision: 81585 Log: Merged revisions 81584 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r81584 | brian.curtin | 2010-05-28 10:49:21 -0500 (Fri, 28 May 2010) | 3 lines Fix #8405 for slow buildbots. Remove the sleep on startup and move the pipe communication into a loop to retry in case a buildbot gets even slower. ........ Modified: python/branches/py3k/ (props changed) python/branches/py3k/Lib/test/test_os.py Modified: python/branches/py3k/Lib/test/test_os.py ============================================================================== --- python/branches/py3k/Lib/test/test_os.py (original) +++ python/branches/py3k/Lib/test/test_os.py Fri May 28 18:08:40 2010 @@ -933,20 +933,64 @@ @unittest.skipUnless(sys.platform == "win32", "Win32 specific tests") class Win32KillTests(unittest.TestCase): - def _kill(self, sig, *args): - # Send a subprocess a signal (or in some cases, just an int to be - # the return value) - proc = subprocess.Popen(*args) + def _kill(self, sig): + # Start sys.executable as a subprocess and communicate from the + # subprocess to the parent that the interpreter is ready. When it + # becomes ready, send *sig* via os.kill to the subprocess and check + # that the return code is equal to *sig*. + import ctypes + from ctypes import wintypes + import msvcrt + + # Since we can't access the contents of the process' stdout until the + # process has exited, use PeekNamedPipe to see what's inside stdout + # without waiting. This is done so we can tell that the interpreter + # is started and running at a point where it could handle a signal. + PeekNamedPipe = ctypes.windll.kernel32.PeekNamedPipe + PeekNamedPipe.restype = wintypes.BOOL + PeekNamedPipe.argtypes = (wintypes.HANDLE, # Pipe handle + ctypes.POINTER(ctypes.c_char), # stdout buf + wintypes.DWORD, # Buffer size + ctypes.POINTER(wintypes.DWORD), # bytes read + ctypes.POINTER(wintypes.DWORD), # bytes avail + ctypes.POINTER(wintypes.DWORD)) # bytes left + msg = "running" + proc = subprocess.Popen([sys.executable, "-c", + "import sys;" + "sys.stdout.write('{}');" + "sys.stdout.flush();" + "input()".format(msg)], + stdout=subprocess.PIPE, + stderr=subprocess.PIPE, + stdin=subprocess.PIPE) + + count, max = 0, 100 + while count < max and proc.poll() is None: + # Create a string buffer to store the result of stdout from the pipe + buf = ctypes.create_string_buffer(len(msg)) + # Obtain the text currently in proc.stdout + # Bytes read/avail/left are left as NULL and unused + rslt = PeekNamedPipe(msvcrt.get_osfhandle(proc.stdout.fileno()), + buf, ctypes.sizeof(buf), None, None, None) + self.assertNotEqual(rslt, 0, "PeekNamedPipe failed") + if buf.value: + self.assertEqual(msg, buf.value.decode()) + break + time.sleep(0.1) + count += 1 + else: + self.fail("Did not receive communication from the subprocess") + os.kill(proc.pid, sig) self.assertEqual(proc.wait(), sig) def test_kill_sigterm(self): # SIGTERM doesn't mean anything special, but make sure it works - self._kill(signal.SIGTERM, [sys.executable]) + self._kill(signal.SIGTERM) def test_kill_int(self): # os.kill on Windows can take an int which gets set as the exit code - self._kill(100, [sys.executable]) + self._kill(100) def _kill_with_event(self, event, name): # Run a script which has console control handling enabled. From python-checkins at python.org Fri May 28 20:08:11 2010 From: python-checkins at python.org (r.david.murray) Date: Fri, 28 May 2010 20:08:11 +0200 (CEST) Subject: [Python-checkins] r81586 - python/trunk/Doc/extending/newtypes.rst Message-ID: <20100528180811.710CFEE9CB@mail.python.org> Author: r.david.murray Date: Fri May 28 20:08:11 2010 New Revision: 81586 Log: Make reference to Generic Attribute Management a hyperlink. Modified: python/trunk/Doc/extending/newtypes.rst Modified: python/trunk/Doc/extending/newtypes.rst ============================================================================== --- python/trunk/Doc/extending/newtypes.rst (original) +++ python/trunk/Doc/extending/newtypes.rst Fri May 28 20:08:11 2010 @@ -446,7 +446,7 @@ Noddy_members, /* tp_members */ Each member definition has a member name, type, offset, access flags and -documentation string. See the "Generic Attribute Management" section below for +documentation string. See the :ref:`Generic-Attribute-Management` section below for details. A disadvantage of this approach is that it doesn't provide a way to restrict the @@ -1129,6 +1129,8 @@ not been updated to use some of the new generic mechanism that is available. +.. _generic-attribute-management: + Generic Attribute Management ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ From python-checkins at python.org Fri May 28 20:17:20 2010 From: python-checkins at python.org (r.david.murray) Date: Fri, 28 May 2010 20:17:20 +0200 (CEST) Subject: [Python-checkins] r81587 - python/trunk/Tools/scripts/serve.py Message-ID: <20100528181720.E8788EE984@mail.python.org> Author: r.david.murray Date: Fri May 28 20:17:20 2010 New Revision: 81587 Log: Make the ctl-C shutdown of serve.py prettier. Modified: python/trunk/Tools/scripts/serve.py Modified: python/trunk/Tools/scripts/serve.py ============================================================================== --- python/trunk/Tools/scripts/serve.py (original) +++ python/trunk/Tools/scripts/serve.py Fri May 28 20:17:20 2010 @@ -28,5 +28,8 @@ path = sys.argv[1] port = int(sys.argv[2]) if len(sys.argv) > 2 else 8000 httpd = simple_server.make_server('', port, app) - print "Serving %s on port %s" % (path, port) - httpd.serve_forever() + print "Serving %s on port %s, control-C to stop" % (path, port) + try: + httpd.serve_forever() + except KeyboardInterrupt: + print "\b\bShutting down." From python-checkins at python.org Fri May 28 23:55:10 2010 From: python-checkins at python.org (victor.stinner) Date: Fri, 28 May 2010 23:55:10 +0200 (CEST) Subject: [Python-checkins] r81588 - in python/branches/py3k: Misc/NEWS Python/getargs.c Message-ID: <20100528215510.672F5EE987@mail.python.org> Author: victor.stinner Date: Fri May 28 23:55:10 2010 New Revision: 81588 Log: Issue #8837: Remove "O?" format of PyArg_Parse*() functions. The format is no used anymore and it was never documented. Modified: python/branches/py3k/Misc/NEWS python/branches/py3k/Python/getargs.c Modified: python/branches/py3k/Misc/NEWS ============================================================================== --- python/branches/py3k/Misc/NEWS (original) +++ python/branches/py3k/Misc/NEWS Fri May 28 23:55:10 2010 @@ -12,6 +12,9 @@ Core and Builtins ----------------- +- Issue #8837: Remove "O?" format of PyArg_Parse*() functions. The format is no + used anymore and it was never documented. + - Issue #2844: Make int('42', n) consistently raise ValueError for invalid integers n (including n = -909). Modified: python/branches/py3k/Python/getargs.c ============================================================================== --- python/branches/py3k/Python/getargs.c (original) +++ python/branches/py3k/Python/getargs.c Fri May 28 23:55:10 2010 @@ -1293,17 +1293,6 @@ return converterr(type->tp_name, arg, msgbuf, bufsize); } - else if (*format == '?') { - inquiry pred = va_arg(*p_va, inquiry); - p = va_arg(*p_va, PyObject **); - format++; - if ((*pred)(arg)) - *p = arg; - else - return converterr("(unspecified)", - arg, msgbuf, bufsize); - - } else if (*format == '&') { typedef int (*converter)(PyObject *, void *); converter convert = va_arg(*p_va, converter); From python-checkins at python.org Fri May 28 23:55:42 2010 From: python-checkins at python.org (victor.stinner) Date: Fri, 28 May 2010 23:55:42 +0200 (CEST) Subject: [Python-checkins] r81589 - python/branches/release31-maint Message-ID: <20100528215542.ADCB0EE987@mail.python.org> Author: victor.stinner Date: Fri May 28 23:55:42 2010 New Revision: 81589 Log: Blocked revisions 81588 via svnmerge ........ r81588 | victor.stinner | 2010-05-28 23:55:10 +0200 (ven., 28 mai 2010) | 3 lines Issue #8837: Remove "O?" format of PyArg_Parse*() functions. The format is no used anymore and it was never documented. ........ Modified: python/branches/release31-maint/ (props changed) From solipsis at pitrou.net Sat May 29 01:23:49 2010 From: solipsis at pitrou.net (solipsis at pitrou.net) Date: Sat, 29 May 2010 01:23:49 +0200 (CEST) Subject: [Python-checkins] Daily py3k reference leaks (r81585): sum=0 Message-ID: <20100528232349.3D76B1770A@ns6635.ovh.net> py3k results for svn r81585 (hg cset 798d7e23ca12) -------------------------------------------------- Command line was: ['./python', '-m', 'test.regrtest', '-uall', '-R', '3:3:/home/antoine/py3k/refleaks/reflog74K_r6', '-x'] From python-checkins at python.org Sat May 29 02:13:06 2010 From: python-checkins at python.org (victor.stinner) Date: Sat, 29 May 2010 02:13:06 +0200 (CEST) Subject: [Python-checkins] r81590 - python/branches/py3k/Python/getargs.c Message-ID: <20100529001306.4B4E1EEA01@mail.python.org> Author: victor.stinner Date: Sat May 29 02:13:06 2010 New Revision: 81590 Log: Remove dead code Modified: python/branches/py3k/Python/getargs.c Modified: python/branches/py3k/Python/getargs.c ============================================================================== --- python/branches/py3k/Python/getargs.c (original) +++ python/branches/py3k/Python/getargs.c Sat May 29 02:13:06 2010 @@ -1029,18 +1029,7 @@ else return converterr("string or None", arg, msgbuf, bufsize); - if (*format == '#') { - FETCH_SIZE; - assert(0); /* XXX redundant with if-case */ - if (arg == Py_None) { - STORE_SIZE(0); - } - else { - STORE_SIZE(PyBytes_Size(arg)); - } - format++; - } - else if (*p != NULL && uarg != NULL && + if (*p != NULL && uarg != NULL && (Py_ssize_t) strlen(*p) != PyBytes_GET_SIZE(uarg)) return converterr( "string without null bytes or None", From python-checkins at python.org Sat May 29 02:13:47 2010 From: python-checkins at python.org (victor.stinner) Date: Sat, 29 May 2010 02:13:47 +0200 (CEST) Subject: [Python-checkins] r81591 - python/branches/release31-maint Message-ID: <20100529001347.660ECEEA1C@mail.python.org> Author: victor.stinner Date: Sat May 29 02:13:47 2010 New Revision: 81591 Log: Blocked revisions 81590 via svnmerge ........ r81590 | victor.stinner | 2010-05-29 02:13:06 +0200 (sam., 29 mai 2010) | 2 lines Remove dead code ........ Modified: python/branches/release31-maint/ (props changed) From python-checkins at python.org Sat May 29 03:55:07 2010 From: python-checkins at python.org (ezio.melotti) Date: Sat, 29 May 2010 03:55:07 +0200 (CEST) Subject: [Python-checkins] r81592 - in tracker/roundup-src/test: test_cgi.py test_mailgw.py Message-ID: <20100529015507.6B7C2EE984@mail.python.org> Author: ezio.melotti Date: Sat May 29 03:55:07 2010 New Revision: 81592 Log: fix a couple of tests that were failing Modified: tracker/roundup-src/test/test_cgi.py tracker/roundup-src/test/test_mailgw.py Modified: tracker/roundup-src/test/test_cgi.py ============================================================================== --- tracker/roundup-src/test/test_cgi.py (original) +++ tracker/roundup-src/test/test_cgi.py Sat May 29 03:55:07 2010 @@ -668,7 +668,7 @@ output = StringIO.StringIO() cl.request = MockNull() cl.request.wfile = output - self.assertRaises(exceptions.Unauthorised, + self.assertRaises(exceptions.SeriousError, actions.ExportCSVAction(cl).handle) Modified: tracker/roundup-src/test/test_mailgw.py ============================================================================== --- tracker/roundup-src/test/test_mailgw.py (original) +++ tracker/roundup-src/test/test_mailgw.py Sat May 29 03:55:07 2010 @@ -595,7 +595,7 @@ Content-Transfer-Encoding: quoted-printable -Change by Bork, Chef : +Changes by Bork, Chef : ---------- From g.brandl at gmx.net Sat May 29 10:20:05 2010 From: g.brandl at gmx.net (Georg Brandl) Date: Sat, 29 May 2010 10:20:05 +0200 Subject: [Python-checkins] r81561 - python/trunk/Misc/ACKS In-Reply-To: References: <20100526205704.F0374EE9BD@mail.python.org> Message-ID: Am 27.05.2010 20:36, schrieb Brett Cannon: > We try to keep the ACKS file alphabetized, so Andrej's entry should go > in the K section (Peter's is down at the end simply because he has an > accented A which doesn't really sort well). IIRC, ? is indeed sorted after Z in Sweden. Georg -- Thus spake the Lord: Thou shalt indent with four spaces. No more, no less. Four shall be the number of spaces thou shalt indent, and the number of thy indenting shall be four. Eight shalt thou not indent, nor either indent thou two, excepting that thou then proceed to four. Tabs are right out. From python-checkins at python.org Sat May 29 10:46:18 2010 From: python-checkins at python.org (georg.brandl) Date: Sat, 29 May 2010 10:46:18 +0200 (CEST) Subject: [Python-checkins] r81593 - python/trunk/Demo/turtle/tdemo_nim.py Message-ID: <20100529084618.9F199C9D7@mail.python.org> Author: georg.brandl Date: Sat May 29 10:46:18 2010 New Revision: 81593 Log: #8616: add new turtle demo "nim". Added: python/trunk/Demo/turtle/tdemo_nim.py (contents, props changed) Added: python/trunk/Demo/turtle/tdemo_nim.py ============================================================================== --- (empty file) +++ python/trunk/Demo/turtle/tdemo_nim.py Sat May 29 10:46:18 2010 @@ -0,0 +1,227 @@ +""" turtle-example-suite: + + tdemo_nim.py + +Play nim against the computer. The player +who takes the last stick is the winner. + +Implements the model-view-controller +design pattern. +""" + + +import turtle +import random +import time + +SCREENWIDTH = 640 +SCREENHEIGHT = 480 + +MINSTICKS = 7 +MAXSTICKS = 31 + +HUNIT = SCREENHEIGHT // 12 +WUNIT = SCREENWIDTH // ((MAXSTICKS // 5) * 11 + (MAXSTICKS % 5) * 2) + +SCOLOR = (63, 63, 31) +HCOLOR = (255, 204, 204) +COLOR = (204, 204, 255) + +def randomrow(): + return random.randint(MINSTICKS, MAXSTICKS) + +def computerzug(state): + xored = state[0] ^ state[1] ^ state[2] + if xored == 0: + return randommove(state) + for z in range(3): + s = state[z] ^ xored + if s <= state[z]: + move = (z, s) + return move + +def randommove(state): + m = max(state) + while True: + z = random.randint(0,2) + if state[z] > (m > 1): + break + rand = random.randint(m > 1, state[z]-1) + return z, rand + + +class NimModel(object): + def __init__(self, game): + self.game = game + + def setup(self): + if self.game.state not in [Nim.CREATED, Nim.OVER]: + return + self.sticks = [randomrow(), randomrow(), randomrow()] + self.player = 0 + self.winner = None + self.game.view.setup() + self.game.state = Nim.RUNNING + + def move(self, row, col): + maxspalte = self.sticks[row] + self.sticks[row] = col + self.game.view.notify_move(row, col, maxspalte, self.player) + if self.game_over(): + self.game.state = Nim.OVER + self.winner = self.player + self.game.view.notify_over() + elif self.player == 0: + self.player = 1 + row, col = computerzug(self.sticks) + self.move(row, col) + self.player = 0 + + def game_over(self): + return self.sticks == [0, 0, 0] + + def notify_move(self, row, col): + if self.sticks[row] <= col: + return + self.move(row, col) + + +class Stick(turtle.Turtle): + def __init__(self, row, col, game): + turtle.Turtle.__init__(self, visible=False) + self.row = row + self.col = col + self.game = game + x, y = self.coords(row, col) + self.shape("square") + self.shapesize(HUNIT/10.0, WUNIT/20.0) + self.speed(0) + self.pu() + self.goto(x,y) + self.color("white") + self.showturtle() + + def coords(self, row, col): + packet, remainder = divmod(col, 5) + x = (3 + 11 * packet + 2 * remainder) * WUNIT + y = (2 + 3 * row) * HUNIT + return x - SCREENWIDTH // 2 + WUNIT // 2, SCREENHEIGHT // 2 - y - HUNIT // 2 + + def makemove(self, x, y): + if self.game.state != Nim.RUNNING: + return + self.game.controller.notify_move(self.row, self.col) + + +class NimView(object): + def __init__(self, game): + self.game = game + self.screen = game.screen + self.model = game.model + self.screen.colormode(255) + self.screen.tracer(False) + self.screen.bgcolor((240, 240, 255)) + self.writer = turtle.Turtle(visible=False) + self.writer.pu() + self.writer.speed(0) + self.sticks = {} + for row in range(3): + for col in range(MAXSTICKS): + self.sticks[(row, col)] = Stick(row, col, game) + self.display("... a moment please ...") + self.screen.tracer(True) + + def display(self, msg1, msg2=None): + self.screen.tracer(False) + self.writer.clear() + if msg2 is not None: + self.writer.goto(0, - SCREENHEIGHT // 2 + 48) + self.writer.pencolor("red") + self.writer.write(msg2, align="center", font=("Courier",18,"bold")) + self.writer.goto(0, - SCREENHEIGHT // 2 + 20) + self.writer.pencolor("black") + self.writer.write(msg1, align="center", font=("Courier",14,"bold")) + self.screen.tracer(True) + + + def setup(self): + self.screen.tracer(False) + for row in range(3): + for col in range(self.model.sticks[row]): + self.sticks[(row, col)].color(SCOLOR) + for row in range(3): + for col in range(self.model.sticks[row], MAXSTICKS): + self.sticks[(row, col)].color("white") + self.display("Your turn! Click leftmost stick to remove.") + self.screen.tracer(True) + + def notify_move(self, row, col, maxspalte, player): + if player == 0: + farbe = HCOLOR + for s in range(col, maxspalte): + self.sticks[(row, s)].color(farbe) + else: + self.display(" ... thinking ... ") + time.sleep(0.5) + self.display(" ... thinking ... aaah ...") + farbe = COLOR + for s in range(maxspalte-1, col-1, -1): + time.sleep(0.2) + self.sticks[(row, s)].color(farbe) + self.display("Your turn! Click leftmost stick to remove.") + + def notify_over(self): + if self.game.model.winner == 0: + msg2 = "Congrats. You're the winner!!!" + else: + msg2 = "Sorry, the computer is the winner." + self.display("To play again press space bar. To leave press ESC.", msg2) + + def clear(self): + if self.game.state == Nim.OVER: + self.screen.clear() + +class NimController(object): + + def __init__(self, game): + self.game = game + self.sticks = game.view.sticks + self.BUSY = False + for stick in self.sticks.values(): + stick.onclick(stick.makemove) + self.game.screen.onkey(self.game.model.setup, "space") + self.game.screen.onkey(self.game.view.clear, "Escape") + self.game.view.display("Press space bar to start game") + self.game.screen.listen() + + def notify_move(self, row, col): + if self.BUSY: + return + self.BUSY = True + self.game.model.notify_move(row, col) + self.BUSY = False + +class Nim(object): + CREATED = 0 + RUNNING = 1 + OVER = 2 + def __init__(self, screen): + self.state = Nim.CREATED + self.screen = screen + self.model = NimModel(self) + self.view = NimView(self) + self.controller = NimController(self) + + +mainscreen = turtle.Screen() +mainscreen.mode("standard") +mainscreen.setup(SCREENWIDTH, SCREENHEIGHT) + +def main(): + nim = Nim(mainscreen) + return "EVENTLOOP!" + +if __name__ == "__main__": + main() + turtle.mainloop() + From python-checkins at python.org Sat May 29 14:06:13 2010 From: python-checkins at python.org (antoine.pitrou) Date: Sat, 29 May 2010 14:06:13 +0200 (CEST) Subject: [Python-checkins] r81594 - python/trunk/Doc/library/io.rst Message-ID: <20100529120613.82B4DEE995@mail.python.org> Author: antoine.pitrou Date: Sat May 29 14:06:13 2010 New Revision: 81594 Log: Issue #8840: Make documentation for truncate() clearer Modified: python/trunk/Doc/library/io.rst Modified: python/trunk/Doc/library/io.rst ============================================================================== --- python/trunk/Doc/library/io.rst (original) +++ python/trunk/Doc/library/io.rst Sat May 29 14:06:13 2010 @@ -320,10 +320,12 @@ .. method:: truncate(size=None) - Truncate the file to at most *size* bytes. *size* defaults to the current - file position, as returned by :meth:`tell`. Note that the current file - position isn't changed; if you want to change it to the new end of - file, you have to :meth:`seek()` explicitly. + Resize the stream to the given *size* in bytes (or the current position + if *size* is not specified). The current stream position isn't changed. + This resizing can extend or reduce the current file size. In case of + extension, the contents of the new file area depend on the platform + (on most systems, additional bytes are zero-filled, on Windows they're + undetermined). The new file size is returned. .. method:: writable() From python-checkins at python.org Sat May 29 14:08:25 2010 From: python-checkins at python.org (antoine.pitrou) Date: Sat, 29 May 2010 14:08:25 +0200 (CEST) Subject: [Python-checkins] r81595 - in python/branches/py3k: Doc/library/io.rst Message-ID: <20100529120825.EA744EE995@mail.python.org> Author: antoine.pitrou Date: Sat May 29 14:08:25 2010 New Revision: 81595 Log: Merged revisions 81594 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r81594 | antoine.pitrou | 2010-05-29 14:06:13 +0200 (sam., 29 mai 2010) | 3 lines Issue #8840: Make documentation for truncate() clearer ........ Modified: python/branches/py3k/ (props changed) python/branches/py3k/Doc/library/io.rst Modified: python/branches/py3k/Doc/library/io.rst ============================================================================== --- python/branches/py3k/Doc/library/io.rst (original) +++ python/branches/py3k/Doc/library/io.rst Sat May 29 14:08:25 2010 @@ -314,10 +314,12 @@ .. method:: truncate(size=None) - Truncate the file to at most *size* bytes. *size* defaults to the current - file position, as returned by :meth:`tell`. Note that the current file - position isn't changed; if you want to change it to the new end of - file, you have to :meth:`seek()` explicitly. + Resize the stream to the given *size* in bytes (or the current position + if *size* is not specified). The current stream position isn't changed. + This resizing can extend or reduce the current file size. In case of + extension, the contents of the new file area depend on the platform + (on most systems, additional bytes are zero-filled, on Windows they're + undetermined). The new file size is returned. .. method:: writable() From python-checkins at python.org Sat May 29 14:08:32 2010 From: python-checkins at python.org (antoine.pitrou) Date: Sat, 29 May 2010 14:08:32 +0200 (CEST) Subject: [Python-checkins] r81596 - in python/branches/release26-maint: Doc/library/io.rst Message-ID: <20100529120832.23A6CEEA2B@mail.python.org> Author: antoine.pitrou Date: Sat May 29 14:08:31 2010 New Revision: 81596 Log: Merged revisions 81594 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r81594 | antoine.pitrou | 2010-05-29 14:06:13 +0200 (sam., 29 mai 2010) | 3 lines Issue #8840: Make documentation for truncate() clearer ........ Modified: python/branches/release26-maint/ (props changed) python/branches/release26-maint/Doc/library/io.rst Modified: python/branches/release26-maint/Doc/library/io.rst ============================================================================== --- python/branches/release26-maint/Doc/library/io.rst (original) +++ python/branches/release26-maint/Doc/library/io.rst Sat May 29 14:08:31 2010 @@ -294,10 +294,12 @@ .. method:: truncate([size]) - Truncate the file to at most *size* bytes. *size* defaults to the current - file position, as returned by :meth:`tell`. Note that the current file - position isn't changed; if you want to change it to the new end of - file, you have to :meth:`seek()` explicitly. + Resize the stream to the given *size* in bytes (or the current position + if *size* is not specified). The current stream position isn't changed. + This resizing can extend or reduce the current file size. In case of + extension, the contents of the new file area depend on the platform + (on most systems, additional bytes are zero-filled, on Windows they're + undetermined). The new file size is returned. .. method:: writable() From python-checkins at python.org Sat May 29 14:10:15 2010 From: python-checkins at python.org (antoine.pitrou) Date: Sat, 29 May 2010 14:10:15 +0200 (CEST) Subject: [Python-checkins] r81597 - in python/branches/release31-maint: Doc/library/io.rst Message-ID: <20100529121015.D4963EE9A9@mail.python.org> Author: antoine.pitrou Date: Sat May 29 14:10:15 2010 New Revision: 81597 Log: Merged revisions 81595 via svnmerge from svn+ssh://pythondev at svn.python.org/python/branches/py3k ................ r81595 | antoine.pitrou | 2010-05-29 14:08:25 +0200 (sam., 29 mai 2010) | 9 lines Merged revisions 81594 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r81594 | antoine.pitrou | 2010-05-29 14:06:13 +0200 (sam., 29 mai 2010) | 3 lines Issue #8840: Make documentation for truncate() clearer ........ ................ Modified: python/branches/release31-maint/ (props changed) python/branches/release31-maint/Doc/library/io.rst Modified: python/branches/release31-maint/Doc/library/io.rst ============================================================================== --- python/branches/release31-maint/Doc/library/io.rst (original) +++ python/branches/release31-maint/Doc/library/io.rst Sat May 29 14:10:15 2010 @@ -309,10 +309,12 @@ .. method:: truncate(size=None) - Truncate the file to at most *size* bytes. *size* defaults to the current - file position, as returned by :meth:`tell`. Note that the current file - position isn't changed; if you want to change it to the new end of - file, you have to :meth:`seek()` explicitly. + Resize the stream to the given *size* in bytes (or the current position + if *size* is not specified). The current stream position isn't changed. + This resizing can extend or reduce the current file size. In case of + extension, the contents of the new file area depend on the platform + (on most systems, additional bytes are zero-filled, on Windows they're + undetermined). The new file size is returned. .. method:: writable() From python-checkins at python.org Sat May 29 14:54:35 2010 From: python-checkins at python.org (stefan.krah) Date: Sat, 29 May 2010 14:54:35 +0200 (CEST) Subject: [Python-checkins] r81598 - python/trunk/Doc/library/decimal.rst Message-ID: <20100529125435.EB81CEE984@mail.python.org> Author: stefan.krah Date: Sat May 29 14:54:35 2010 New Revision: 81598 Log: Fix typo Modified: python/trunk/Doc/library/decimal.rst Modified: python/trunk/Doc/library/decimal.rst ============================================================================== --- python/trunk/Doc/library/decimal.rst (original) +++ python/trunk/Doc/library/decimal.rst Sat May 29 14:54:35 2010 @@ -975,7 +975,7 @@ This context is used by the :class:`Context` constructor as a prototype for new contexts. Changing a field (such a precision) has the effect of changing the - default for new contexts creating by the :class:`Context` constructor. + default for new contexts created by the :class:`Context` constructor. This context is most useful in multi-threaded environments. Changing one of the fields before threads are started has the effect of setting system-wide From python-checkins at python.org Sat May 29 14:57:00 2010 From: python-checkins at python.org (stefan.krah) Date: Sat, 29 May 2010 14:57:00 +0200 (CEST) Subject: [Python-checkins] r81599 - in python/branches/release26-maint: Doc/library/decimal.rst Message-ID: <20100529125700.BDED2EE986@mail.python.org> Author: stefan.krah Date: Sat May 29 14:57:00 2010 New Revision: 81599 Log: Merged revisions 81598 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r81598 | stefan.krah | 2010-05-29 14:54:35 +0200 (Sat, 29 May 2010) | 1 line Fix typo ........ Modified: python/branches/release26-maint/ (props changed) python/branches/release26-maint/Doc/library/decimal.rst Modified: python/branches/release26-maint/Doc/library/decimal.rst ============================================================================== --- python/branches/release26-maint/Doc/library/decimal.rst (original) +++ python/branches/release26-maint/Doc/library/decimal.rst Sat May 29 14:57:00 2010 @@ -921,7 +921,7 @@ This context is used by the :class:`Context` constructor as a prototype for new contexts. Changing a field (such a precision) has the effect of changing the - default for new contexts creating by the :class:`Context` constructor. + default for new contexts created by the :class:`Context` constructor. This context is most useful in multi-threaded environments. Changing one of the fields before threads are started has the effect of setting system-wide From python-checkins at python.org Sat May 29 14:59:18 2010 From: python-checkins at python.org (stefan.krah) Date: Sat, 29 May 2010 14:59:18 +0200 (CEST) Subject: [Python-checkins] r81600 - in python/branches/py3k: Doc/library/decimal.rst Message-ID: <20100529125918.BCCFCEE9A9@mail.python.org> Author: stefan.krah Date: Sat May 29 14:59:18 2010 New Revision: 81600 Log: Merged revisions 81598 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r81598 | stefan.krah | 2010-05-29 14:54:35 +0200 (Sat, 29 May 2010) | 1 line Fix typo ........ Modified: python/branches/py3k/ (props changed) python/branches/py3k/Doc/library/decimal.rst Modified: python/branches/py3k/Doc/library/decimal.rst ============================================================================== --- python/branches/py3k/Doc/library/decimal.rst (original) +++ python/branches/py3k/Doc/library/decimal.rst Sat May 29 14:59:18 2010 @@ -874,7 +874,7 @@ This context is used by the :class:`Context` constructor as a prototype for new contexts. Changing a field (such a precision) has the effect of changing the - default for new contexts creating by the :class:`Context` constructor. + default for new contexts created by the :class:`Context` constructor. This context is most useful in multi-threaded environments. Changing one of the fields before threads are started has the effect of setting system-wide From python-checkins at python.org Sat May 29 15:01:02 2010 From: python-checkins at python.org (stefan.krah) Date: Sat, 29 May 2010 15:01:02 +0200 (CEST) Subject: [Python-checkins] r81601 - in python/branches/release31-maint: Doc/library/decimal.rst Message-ID: <20100529130102.277B3EE9A9@mail.python.org> Author: stefan.krah Date: Sat May 29 15:01:02 2010 New Revision: 81601 Log: Merged revisions 81600 via svnmerge from svn+ssh://pythondev at svn.python.org/python/branches/py3k ................ r81600 | stefan.krah | 2010-05-29 14:59:18 +0200 (Sat, 29 May 2010) | 9 lines Merged revisions 81598 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r81598 | stefan.krah | 2010-05-29 14:54:35 +0200 (Sat, 29 May 2010) | 1 line Fix typo ........ ................ Modified: python/branches/release31-maint/ (props changed) python/branches/release31-maint/Doc/library/decimal.rst Modified: python/branches/release31-maint/Doc/library/decimal.rst ============================================================================== --- python/branches/release31-maint/Doc/library/decimal.rst (original) +++ python/branches/release31-maint/Doc/library/decimal.rst Sat May 29 15:01:02 2010 @@ -843,7 +843,7 @@ This context is used by the :class:`Context` constructor as a prototype for new contexts. Changing a field (such a precision) has the effect of changing the - default for new contexts creating by the :class:`Context` constructor. + default for new contexts created by the :class:`Context` constructor. This context is most useful in multi-threaded environments. Changing one of the fields before threads are started has the effect of setting system-wide From python-checkins at python.org Sat May 29 23:00:52 2010 From: python-checkins at python.org (mark.dickinson) Date: Sat, 29 May 2010 23:00:52 +0200 (CEST) Subject: [Python-checkins] r81602 - python/trunk/Modules/config.c.in Message-ID: <20100529210052.DDC18EE991@mail.python.org> Author: mark.dickinson Date: Sat May 29 23:00:52 2010 New Revision: 81602 Log: Untabify Modules/config.c.in. Modified: python/trunk/Modules/config.c.in Modified: python/trunk/Modules/config.c.in ============================================================================== --- python/trunk/Modules/config.c.in (original) +++ python/trunk/Modules/config.c.in Sat May 29 23:00:52 2010 @@ -34,33 +34,32 @@ /* -- ADDMODULE MARKER 2 -- */ - /* This module lives in marshal.c */ - {"marshal", PyMarshal_Init}, + /* This module lives in marshal.c */ + {"marshal", PyMarshal_Init}, - /* This lives in import.c */ - {"imp", initimp}, + /* This lives in import.c */ + {"imp", initimp}, - /* This lives in Python/Python-ast.c */ - {"_ast", init_ast}, + /* This lives in Python/Python-ast.c */ + {"_ast", init_ast}, - /* These entries are here for sys.builtin_module_names */ - {"__main__", NULL}, - {"__builtin__", NULL}, - {"sys", NULL}, - {"exceptions", NULL}, + /* These entries are here for sys.builtin_module_names */ + {"__main__", NULL}, + {"__builtin__", NULL}, + {"sys", NULL}, + {"exceptions", NULL}, - /* This lives in gcmodule.c */ - {"gc", initgc}, + /* This lives in gcmodule.c */ + {"gc", initgc}, - /* This lives in _warnings.c */ - {"_warnings", _PyWarnings_Init}, + /* This lives in _warnings.c */ + {"_warnings", _PyWarnings_Init}, - /* Sentinel */ - {0, 0} + /* Sentinel */ + {0, 0} }; #ifdef __cplusplus } #endif - From python-checkins at python.org Sat May 29 23:03:14 2010 From: python-checkins at python.org (mark.dickinson) Date: Sat, 29 May 2010 23:03:14 +0200 (CEST) Subject: [Python-checkins] r81603 - in python/branches/release26-maint: Modules/config.c.in Message-ID: <20100529210314.1E07EEE9BE@mail.python.org> Author: mark.dickinson Date: Sat May 29 23:03:13 2010 New Revision: 81603 Log: Merged revisions 81602 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r81602 | mark.dickinson | 2010-05-29 22:00:52 +0100 (Sat, 29 May 2010) | 1 line Untabify Modules/config.c.in. ........ Modified: python/branches/release26-maint/ (props changed) python/branches/release26-maint/Modules/config.c.in Modified: python/branches/release26-maint/Modules/config.c.in ============================================================================== --- python/branches/release26-maint/Modules/config.c.in (original) +++ python/branches/release26-maint/Modules/config.c.in Sat May 29 23:03:13 2010 @@ -34,33 +34,32 @@ /* -- ADDMODULE MARKER 2 -- */ - /* This module lives in marshal.c */ - {"marshal", PyMarshal_Init}, + /* This module lives in marshal.c */ + {"marshal", PyMarshal_Init}, - /* This lives in import.c */ - {"imp", initimp}, + /* This lives in import.c */ + {"imp", initimp}, - /* This lives in Python/Python-ast.c */ - {"_ast", init_ast}, + /* This lives in Python/Python-ast.c */ + {"_ast", init_ast}, - /* These entries are here for sys.builtin_module_names */ - {"__main__", NULL}, - {"__builtin__", NULL}, - {"sys", NULL}, - {"exceptions", NULL}, + /* These entries are here for sys.builtin_module_names */ + {"__main__", NULL}, + {"__builtin__", NULL}, + {"sys", NULL}, + {"exceptions", NULL}, - /* This lives in gcmodule.c */ - {"gc", initgc}, + /* This lives in gcmodule.c */ + {"gc", initgc}, - /* This lives in _warnings.c */ - {"_warnings", _PyWarnings_Init}, + /* This lives in _warnings.c */ + {"_warnings", _PyWarnings_Init}, - /* Sentinel */ - {0, 0} + /* Sentinel */ + {0, 0} }; #ifdef __cplusplus } #endif - From python-checkins at python.org Sat May 29 23:05:27 2010 From: python-checkins at python.org (mark.dickinson) Date: Sat, 29 May 2010 23:05:27 +0200 (CEST) Subject: [Python-checkins] r81604 - in python/branches/py3k: Modules/config.c.in Message-ID: <20100529210527.D73A8EE9BE@mail.python.org> Author: mark.dickinson Date: Sat May 29 23:05:27 2010 New Revision: 81604 Log: Merged revisions 81602 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r81602 | mark.dickinson | 2010-05-29 22:00:52 +0100 (Sat, 29 May 2010) | 1 line Untabify Modules/config.c.in. ........ Modified: python/branches/py3k/ (props changed) python/branches/py3k/Modules/config.c.in Modified: python/branches/py3k/Modules/config.c.in ============================================================================== --- python/branches/py3k/Modules/config.c.in (original) +++ python/branches/py3k/Modules/config.c.in Sat May 29 23:05:27 2010 @@ -34,28 +34,28 @@ /* -- ADDMODULE MARKER 2 -- */ - /* This module lives in marshal.c */ - {"marshal", PyMarshal_Init}, + /* This module lives in marshal.c */ + {"marshal", PyMarshal_Init}, - /* This lives in import.c */ - {"imp", PyInit_imp}, + /* This lives in import.c */ + {"imp", PyInit_imp}, - /* This lives in Python/Python-ast.c */ - {"_ast", PyInit__ast}, + /* This lives in Python/Python-ast.c */ + {"_ast", PyInit__ast}, - /* These entries are here for sys.builtin_module_names */ - {"__main__", NULL}, - {"builtins", NULL}, - {"sys", NULL}, + /* These entries are here for sys.builtin_module_names */ + {"__main__", NULL}, + {"builtins", NULL}, + {"sys", NULL}, - /* This lives in gcmodule.c */ - {"gc", PyInit_gc}, + /* This lives in gcmodule.c */ + {"gc", PyInit_gc}, - /* This lives in _warnings.c */ - {"_warnings", _PyWarnings_Init}, + /* This lives in _warnings.c */ + {"_warnings", _PyWarnings_Init}, - /* Sentinel */ - {0, 0} + /* Sentinel */ + {0, 0} }; From python-checkins at python.org Sat May 29 23:11:05 2010 From: python-checkins at python.org (mark.dickinson) Date: Sat, 29 May 2010 23:11:05 +0200 (CEST) Subject: [Python-checkins] r81605 - in python/branches/release31-maint: Modules/config.c.in Message-ID: <20100529211105.ED491EE9C6@mail.python.org> Author: mark.dickinson Date: Sat May 29 23:11:05 2010 New Revision: 81605 Log: Merged revisions 81604 via svnmerge from svn+ssh://pythondev at svn.python.org/python/branches/py3k ................ r81604 | mark.dickinson | 2010-05-29 22:05:27 +0100 (Sat, 29 May 2010) | 9 lines Merged revisions 81602 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r81602 | mark.dickinson | 2010-05-29 22:00:52 +0100 (Sat, 29 May 2010) | 1 line Untabify Modules/config.c.in. ........ ................ Modified: python/branches/release31-maint/ (props changed) python/branches/release31-maint/Modules/config.c.in Modified: python/branches/release31-maint/Modules/config.c.in ============================================================================== --- python/branches/release31-maint/Modules/config.c.in (original) +++ python/branches/release31-maint/Modules/config.c.in Sat May 29 23:11:05 2010 @@ -34,28 +34,28 @@ /* -- ADDMODULE MARKER 2 -- */ - /* This module lives in marshal.c */ - {"marshal", PyMarshal_Init}, + /* This module lives in marshal.c */ + {"marshal", PyMarshal_Init}, - /* This lives in import.c */ - {"imp", PyInit_imp}, + /* This lives in import.c */ + {"imp", PyInit_imp}, - /* This lives in Python/Python-ast.c */ - {"_ast", PyInit__ast}, + /* This lives in Python/Python-ast.c */ + {"_ast", PyInit__ast}, - /* These entries are here for sys.builtin_module_names */ - {"__main__", NULL}, - {"builtins", NULL}, - {"sys", NULL}, + /* These entries are here for sys.builtin_module_names */ + {"__main__", NULL}, + {"builtins", NULL}, + {"sys", NULL}, - /* This lives in gcmodule.c */ - {"gc", PyInit_gc}, + /* This lives in gcmodule.c */ + {"gc", PyInit_gc}, - /* This lives in _warnings.c */ - {"_warnings", _PyWarnings_Init}, + /* This lives in _warnings.c */ + {"_warnings", _PyWarnings_Init}, - /* Sentinel */ - {0, 0} + /* Sentinel */ + {0, 0} }; From python-checkins at python.org Sun May 30 00:05:49 2010 From: python-checkins at python.org (tarek.ziade) Date: Sun, 30 May 2010 00:05:49 +0200 Subject: [Python-checkins] distutils2: Merged with Nicolas Cadou Message-ID: tarek.ziade pushed 9bc41f8a5c20 to distutils2: http://hg.python.org/distutils2/rev/9bc41f8a5c20 changeset: 162:9bc41f8a5c20 parent: 161:807e6867e133 parent: 160:30ad3af43b5f user: Pior Bastida date: Sat May 22 20:04:32 2010 -0400 summary: Merged with Nicolas Cadou files: diff --git a/src/distutils2/tests/test_util.py b/src/distutils2/tests/test_util.py --- a/src/distutils2/tests/test_util.py +++ b/src/distutils2/tests/test_util.py @@ -294,7 +294,7 @@ self.write_file(os.path.join(pkg5, '__init__.py')) res = find_packages([root], ['pkg1.pkg2']) - self.assertEquals(res, ['pkg1', 'pkg5', 'pkg1.pkg3', 'pkg1.pkg3.pkg6']) + self.assertEquals(set(res), set(['pkg1', 'pkg5', 'pkg1.pkg3', 'pkg1.pkg3.pkg6'])) def test_suite(): -- Repository URL: http://hg.python.org/distutils2 From python-checkins at python.org Sun May 30 00:05:49 2010 From: python-checkins at python.org (tarek.ziade) Date: Sun, 30 May 2010 00:05:49 +0200 Subject: [Python-checkins] distutils2: Fix uncompatibility with lib2to3 pytree.Base.next_sibling() changed in python Message-ID: tarek.ziade pushed 807e6867e133 to distutils2: http://hg.python.org/distutils2/rev/807e6867e133 changeset: 161:807e6867e133 parent: 159:ddb6eda2abd7 user: Pior Bastida date: Sat May 22 20:03:16 2010 -0400 summary: Fix uncompatibility with lib2to3 pytree.Base.next_sibling() changed in python 2.6.5 files: src/distutils2/converter/fixers/fix_imports.py, src/distutils2/converter/fixers/fix_setup_options.py diff --git a/src/distutils2/converter/fixers/fix_imports.py b/src/distutils2/converter/fixers/fix_imports.py --- a/src/distutils2/converter/fixers/fix_imports.py +++ b/src/distutils2/converter/fixers/fix_imports.py @@ -20,6 +20,9 @@ if node.type != syms.import_from: return + if not hasattr(imp, "next_sibling"): + imp.next_sibling = imp.get_next_sibling + while not hasattr(imp, 'value'): imp = imp.children[0] diff --git a/src/distutils2/converter/fixers/fix_setup_options.py b/src/distutils2/converter/fixers/fix_setup_options.py --- a/src/distutils2/converter/fixers/fix_setup_options.py +++ b/src/distutils2/converter/fixers/fix_setup_options.py @@ -41,6 +41,10 @@ def _fix_name(self, argument, remove_list): name = argument.children[0] + + if not hasattr(name, "next_sibling"): + name.next_sibling = name.get_next_sibling + sibling = name.next_sibling if sibling is None or sibling.type != token.EQUAL: return False -- Repository URL: http://hg.python.org/distutils2 From python-checkins at python.org Sun May 30 00:05:49 2010 From: python-checkins at python.org (tarek.ziade) Date: Sun, 30 May 2010 00:05:49 +0200 Subject: [Python-checkins] distutils2: more pytree.Base.next_sibling() lib2to3 compatibility fixes Message-ID: tarek.ziade pushed 21e3531cc3ed to distutils2: http://hg.python.org/distutils2/rev/21e3531cc3ed changeset: 164:21e3531cc3ed user: Nicolas Cadou date: Sat May 22 20:32:21 2010 -0400 summary: more pytree.Base.next_sibling() lib2to3 compatibility fixes files: src/distutils2/converter/fixers/fix_imports.py, src/distutils2/converter/fixers/fix_setup_options.py diff --git a/src/distutils2/converter/fixers/fix_imports.py b/src/distutils2/converter/fixers/fix_imports.py --- a/src/distutils2/converter/fixers/fix_imports.py +++ b/src/distutils2/converter/fixers/fix_imports.py @@ -21,7 +21,7 @@ return if not hasattr(imp, "next_sibling"): - imp.next_sibling = imp.get_next_sibling + imp.next_sibling = imp.get_next_sibling() while not hasattr(imp, 'value'): imp = imp.children[0] @@ -37,6 +37,8 @@ next = imp.next_sibling while next is not None: pattern.append(next.value) + if not hasattr(next, "next_sibling"): + next.next_sibling = next.get_next_sibling() next = next.next_sibling if pattern == ['import', 'setup']: imp.value = 'distutils2.core' diff --git a/src/distutils2/converter/fixers/fix_setup_options.py b/src/distutils2/converter/fixers/fix_setup_options.py --- a/src/distutils2/converter/fixers/fix_setup_options.py +++ b/src/distutils2/converter/fixers/fix_setup_options.py @@ -52,6 +52,8 @@ if name.value in _OLD_NAMES: name.value = _OLD_NAMES[name.value] if name.value in _SEQUENCE_NAMES: + if not hasattr(sibling, "next_sibling"): + sibling.next_sibling = sibling.get_next_sibling() right_operand = sibling.next_sibling # replacing string -> list[string] if right_operand.type == token.STRING: -- Repository URL: http://hg.python.org/distutils2 From python-checkins at python.org Sun May 30 00:05:49 2010 From: python-checkins at python.org (tarek.ziade) Date: Sun, 30 May 2010 00:05:49 +0200 Subject: [Python-checkins] distutils2: Fixed test_find_packages failing when os.path.walk() returns dirs in a Message-ID: tarek.ziade pushed 30ad3af43b5f to distutils2: http://hg.python.org/distutils2/rev/30ad3af43b5f changeset: 160:30ad3af43b5f user: Nicolas Cadou date: Sat May 22 19:55:52 2010 -0400 summary: Fixed test_find_packages failing when os.path.walk() returns dirs in a different order. files: src/distutils2/tests/test_util.py diff --git a/src/distutils2/tests/test_util.py b/src/distutils2/tests/test_util.py --- a/src/distutils2/tests/test_util.py +++ b/src/distutils2/tests/test_util.py @@ -294,7 +294,7 @@ self.write_file(os.path.join(pkg5, '__init__.py')) res = find_packages([root], ['pkg1.pkg2']) - self.assertEquals(res, ['pkg1', 'pkg5', 'pkg1.pkg3', 'pkg1.pkg3.pkg6']) + self.assertEquals(set(res), set(['pkg1', 'pkg5', 'pkg1.pkg3', 'pkg1.pkg3.pkg6'])) def test_suite(): -- Repository URL: http://hg.python.org/distutils2 From python-checkins at python.org Sun May 30 00:05:49 2010 From: python-checkins at python.org (tarek.ziade) Date: Sun, 30 May 2010 00:05:49 +0200 Subject: [Python-checkins] distutils2: update the main function to match those found in the other test Message-ID: tarek.ziade pushed 18aa8268fd52 to distutils2: http://hg.python.org/distutils2/rev/18aa8268fd52 changeset: 166:18aa8268fd52 parent: 164:21e3531cc3ed parent: 165:20e8c8d265b7 user: George Peristerakis date: Sat May 22 20:44:51 2010 -0400 summary: update the main function to match those found in the other test files: diff --git a/src/distutils2/tests/test_converter.py b/src/distutils2/tests/test_converter.py --- a/src/distutils2/tests/test_converter.py +++ b/src/distutils2/tests/test_converter.py @@ -36,4 +36,4 @@ return unittest2.makeSuite(ConverterTestCase) if __name__ == '__main__': - run_unittest(test_suite()) + unittest2.main(defaultTest="test_suite") -- Repository URL: http://hg.python.org/distutils2 From python-checkins at python.org Sun May 30 00:05:49 2010 From: python-checkins at python.org (tarek.ziade) Date: Sun, 30 May 2010 00:05:49 +0200 Subject: [Python-checkins] distutils2: fixed pytree.Base.next_sibling() lib2to3 backward-compatibility with python < Message-ID: tarek.ziade pushed 315d3560785f to distutils2: http://hg.python.org/distutils2/rev/315d3560785f changeset: 163:315d3560785f user: Nicolas Cadou date: Sat May 22 20:22:04 2010 -0400 summary: fixed pytree.Base.next_sibling() lib2to3 backward-compatibility with python < 2.6.5 files: src/distutils2/converter/fixers/fix_setup_options.py diff --git a/src/distutils2/converter/fixers/fix_setup_options.py b/src/distutils2/converter/fixers/fix_setup_options.py --- a/src/distutils2/converter/fixers/fix_setup_options.py +++ b/src/distutils2/converter/fixers/fix_setup_options.py @@ -43,7 +43,7 @@ name = argument.children[0] if not hasattr(name, "next_sibling"): - name.next_sibling = name.get_next_sibling + name.next_sibling = name.get_next_sibling() sibling = name.next_sibling if sibling is None or sibling.type != token.EQUAL: -- Repository URL: http://hg.python.org/distutils2 From python-checkins at python.org Sun May 30 00:05:49 2010 From: python-checkins at python.org (tarek.ziade) Date: Sun, 30 May 2010 00:05:49 +0200 Subject: [Python-checkins] distutils2: updated the main function to work with unittest2 Message-ID: tarek.ziade pushed 20e8c8d265b7 to distutils2: http://hg.python.org/distutils2/rev/20e8c8d265b7 changeset: 165:20e8c8d265b7 parent: 163:315d3560785f user: George Peristerakis date: Sat May 22 20:37:05 2010 -0400 summary: updated the main function to work with unittest2 files: src/distutils2/tests/test_converter.py diff --git a/src/distutils2/tests/test_converter.py b/src/distutils2/tests/test_converter.py --- a/src/distutils2/tests/test_converter.py +++ b/src/distutils2/tests/test_converter.py @@ -36,4 +36,4 @@ return unittest2.makeSuite(ConverterTestCase) if __name__ == '__main__': - run_unittest(test_suite()) + unittest2.main(defaultTest="test_suite") -- Repository URL: http://hg.python.org/distutils2 From python-checkins at python.org Sun May 30 00:05:49 2010 From: python-checkins at python.org (tarek.ziade) Date: Sun, 30 May 2010 00:05:49 +0200 Subject: [Python-checkins] distutils2: Automated merge with https://bitbucket.org/mtlpython/distutils2/ Message-ID: tarek.ziade pushed fa62924e8f37 to distutils2: http://hg.python.org/distutils2/rev/fa62924e8f37 changeset: 168:fa62924e8f37 parent: 166:18aa8268fd52 parent: 167:5594d05f391a user: Nicolas Cadou date: Sat May 22 21:34:06 2010 -0400 summary: Automated merge with https://bitbucket.org/mtlpython/distutils2/ files: diff --git a/src/distutils2/dist.py b/src/distutils2/dist.py --- a/src/distutils2/dist.py +++ b/src/distutils2/dist.py @@ -248,7 +248,7 @@ elif hasattr(self, key): setattr(self, key, val) else: - msg = "Unknown distribution option: %s" % repr(key) + msg = "Metadata option not defined in version 1.2 (PEP-345): %s" % repr(key) if warnings is not None: warnings.warn(msg) else: -- Repository URL: http://hg.python.org/distutils2 From python-checkins at python.org Sun May 30 00:05:49 2010 From: python-checkins at python.org (tarek.ziade) Date: Sun, 30 May 2010 00:05:49 +0200 Subject: [Python-checkins] distutils2: Changed unknown option warning to be more informative Message-ID: tarek.ziade pushed 5594d05f391a to distutils2: http://hg.python.org/distutils2/rev/5594d05f391a changeset: 167:5594d05f391a parent: 164:21e3531cc3ed user: Nicolas Cadou date: Sat May 22 21:33:38 2010 -0400 summary: Changed unknown option warning to be more informative files: src/distutils2/dist.py diff --git a/src/distutils2/dist.py b/src/distutils2/dist.py --- a/src/distutils2/dist.py +++ b/src/distutils2/dist.py @@ -248,7 +248,7 @@ elif hasattr(self, key): setattr(self, key, val) else: - msg = "Unknown distribution option: %s" % repr(key) + msg = "Metadata option not defined in version 1.2 (PEP-345): %s" % repr(key) if warnings is not None: warnings.warn(msg) else: -- Repository URL: http://hg.python.org/distutils2 From python-checkins at python.org Sun May 30 00:05:49 2010 From: python-checkins at python.org (tarek.ziade) Date: Sun, 30 May 2010 00:05:49 +0200 Subject: [Python-checkins] distutils2: reverted Nicolas change: an option is not necessarely a metadata, and in this Message-ID: tarek.ziade pushed 3d606161b7b7 to distutils2: http://hg.python.org/distutils2/rev/3d606161b7b7 changeset: 170:3d606161b7b7 user: Tarek Ziade date: Sat May 29 23:58:42 2010 +0200 summary: reverted Nicolas change: an option is not necessarely a metadata, and in this loop it can't be a metadata anyway (see if test) files: src/distutils2/dist.py diff --git a/src/distutils2/dist.py b/src/distutils2/dist.py --- a/src/distutils2/dist.py +++ b/src/distutils2/dist.py @@ -248,7 +248,7 @@ elif hasattr(self, key): setattr(self, key, val) else: - msg = "Metadata option not defined in version 1.2 (PEP-345): %s" % repr(key) + msg = "Unknown distribution option: %s" % repr(key) if warnings is not None: warnings.warn(msg) else: -- Repository URL: http://hg.python.org/distutils2 From python-checkins at python.org Sun May 30 00:05:49 2010 From: python-checkins at python.org (tarek.ziade) Date: Sun, 30 May 2010 00:05:49 +0200 Subject: [Python-checkins] distutils2: improved the test runner. Now handles the exit code and tries all supported Message-ID: tarek.ziade pushed db5be34ba98a to distutils2: http://hg.python.org/distutils2/rev/db5be34ba98a changeset: 171:db5be34ba98a tag: tip user: Tarek Ziade date: Sun May 30 00:05:27 2010 +0200 summary: improved the test runner. Now handles the exit code and tries all supported Python versions files: src/runtests.py, src/tests.sh diff --git a/src/runtests.py b/src/runtests.py --- a/src/runtests.py +++ b/src/runtests.py @@ -14,10 +14,15 @@ verbose = sys.argv[-1] != '-q' else: verbose = 1 - - run_unittest([distutils2.tests.test_suite(), btest_suite()], - verbose_=verbose) - reap_children() + try: + try: + run_unittest([distutils2.tests.test_suite(), btest_suite()], + verbose_=verbose) + return 0 + except TestFailed: + return 1 + finally: + reap_children() if __name__ == "__main__": try: @@ -26,4 +31,5 @@ print('!!! You need to install unittest2') sys.exit(1) - test_main() + sys.exit(test_main()) + diff --git a/src/tests.sh b/src/tests.sh --- a/src/tests.sh +++ b/src/tests.sh @@ -1,12 +1,28 @@ #!/bin/sh -echo Testing with Python 2.4.... -python2.4 runtests.py -q +echo -n "Running tests for Python 2.4..." +python2.4 runtests.py -q > /dev/null 2> /dev/null +if [ $? -ne 0 ];then + echo "Failed" + exit $1 +else + echo "Success" +fi -echo -echo Testing with Python 2.5.... -python2.5 runtests.py -q +echo -n "Running tests for Python 2.5..." +python2.5 runtests.py -q > /dev/null 2> /dev/null +if [ $? -ne 0 ];then + echo "Failed" + exit $1 +else + echo "Success" +fi -echo -echo Testing with Python 2.6.... -python2.6 runtests.py -q +echo -n "Running tests for Python 2.6..." +python2.6 runtests.py -q > /dev/null 2> /dev/null +if [ $? -ne 0 ];then + echo "Failed" + exit $1 +else + echo "Success" +fi -- Repository URL: http://hg.python.org/distutils2 From python-checkins at python.org Sun May 30 00:05:49 2010 From: python-checkins at python.org (tarek.ziade) Date: Sun, 30 May 2010 00:05:49 +0200 Subject: [Python-checkins] distutils2: improved test coverage Message-ID: tarek.ziade pushed 7527c6f89b67 to distutils2: http://hg.python.org/distutils2/rev/7527c6f89b67 changeset: 169:7527c6f89b67 user: Yannick Gingras date: Sun May 23 02:14:41 2010 -0400 summary: improved test coverage files: src/distutils2/tests/test_core.py, src/distutils2/tests/test_version.py diff --git a/src/distutils2/tests/test_core.py b/src/distutils2/tests/test_core.py --- a/src/distutils2/tests/test_core.py +++ b/src/distutils2/tests/test_core.py @@ -60,6 +60,19 @@ distutils2.core.run_setup( self.write_setup(setup_using___file__)) + def test_run_setup_stop_after(self): + f = self.write_setup(setup_using___file__) + for s in ['init', 'config', 'commandline', 'run']: + distutils2.core.run_setup(f, stop_after=s) + self.assertRaises(ValueError, distutils2.core.run_setup, + f, stop_after='bob') + + def test_run_setup_args(self): + f = self.write_setup(setup_using___file__) + d = distutils2.core.run_setup(f, script_args=["--help"], + stop_after="init") + self.assertEqual(['--help'], d.script_args) + def test_run_setup_uses_current_dir(self): # This tests that the setup script is run with the current directory # as its own current directory; this was temporarily broken by a diff --git a/src/distutils2/tests/test_version.py b/src/distutils2/tests/test_version.py --- a/src/distutils2/tests/test_version.py +++ b/src/distutils2/tests/test_version.py @@ -4,7 +4,7 @@ import os from distutils2.version import NormalizedVersion as V -from distutils2.version import IrrationalVersionError +from distutils2.version import IrrationalVersionError, HugeMajorVersionNumError from distutils2.version import suggest_normalized_version as suggest from distutils2.version import VersionPredicate @@ -69,6 +69,9 @@ >>> V('1.0') < V('1.0.post456.dev623') True + >>> V('1.0.1') <= V('1.0') + False + >>> V('1.0.post456.dev623') < V('1.0.post456') < V('1.0.post1234') True @@ -97,6 +100,7 @@ def test_suggest_normalized_version(self): self.assertEquals(suggest('1.0'), '1.0') + self.assertEquals(suggest('v1.0'), '1.0') self.assertEquals(suggest('1.0-alpha1'), '1.0a1') self.assertEquals(suggest('1.0c2'), '1.0c2') self.assertEquals(suggest('walla walla washington'), None) @@ -125,6 +129,15 @@ # they us "p1" "p2" for post releases self.assertEquals(suggest('1.4p1'), '1.4.post1') + def test_error_on_major_version(self): + self.assertRaises(HugeMajorVersionNumError, V, '2001.1') + + def test_cannot_compare(self): + self.assertRaises(TypeError, V('1.1').__lt__, '1.1.1') + + def test_version_repr(self): + self.assertEquals("NormalizedVersion('1.1')", repr(V('1.1'))) + def test_predicate(self): # VersionPredicate knows how to parse stuff like: # @@ -146,7 +159,6 @@ assert VersionPredicate('Ho (<3.0,!=2.5)').match('2.6.0') assert not VersionPredicate('Ho (<3.0,!=2.6)').match('2.6.0') - # XXX need to silent the micro version in this case #assert not VersionPredicate('Ho (<3.0,!=2.6)').match('2.6.3') -- Repository URL: http://hg.python.org/distutils2 From python-checkins at python.org Sun May 30 00:33:51 2010 From: python-checkins at python.org (tarek.ziade) Date: Sun, 30 May 2010 00:33:51 +0200 Subject: [Python-checkins] distutils2: added a CONTRIBUTORS file Message-ID: tarek.ziade pushed e61f5048f759 to distutils2: http://hg.python.org/distutils2/rev/e61f5048f759 changeset: 172:e61f5048f759 user: Tarek Ziade date: Sun May 30 00:19:19 2010 +0200 summary: added a CONTRIBUTORS file files: src/CONTRIBUTORS.txt diff --git a/src/CONTRIBUTORS.txt b/src/CONTRIBUTORS.txt new file mode 100644 --- /dev/null +++ b/src/CONTRIBUTORS.txt @@ -0,0 +1,24 @@ +============ +Contributors +============ + +Distutils2 is a project that was started and that is maintained by +Tarek Ziad??, and many people are contributing to the project. + +If you did, please add your name below in alphabetical order ! + +Thanks to: + +- Pior Bastida +- Titus Brown +- Nicolas Cadou +- Yannick Gringas +- Carl Meyer +- Michael Mulich +- George Peris +- Sean Reifschneider +- Erik Rose +- Brian Rosner +- Alexandre Vassalotti +- Martin von L??wis + -- Repository URL: http://hg.python.org/distutils2 From python-checkins at python.org Sun May 30 00:33:51 2010 From: python-checkins at python.org (tarek.ziade) Date: Sun, 30 May 2010 00:33:51 +0200 Subject: [Python-checkins] distutils2: added a missing import Message-ID: tarek.ziade pushed 9f7e9fa6f762 to distutils2: http://hg.python.org/distutils2/rev/9f7e9fa6f762 changeset: 173:9f7e9fa6f762 user: Tarek Ziade date: Sun May 30 00:32:43 2010 +0200 summary: added a missing import files: src/runtests.py diff --git a/src/runtests.py b/src/runtests.py --- a/src/runtests.py +++ b/src/runtests.py @@ -6,7 +6,7 @@ def test_main(): import distutils2.tests - from distutils2.tests import run_unittest, reap_children + from distutils2.tests import run_unittest, reap_children, TestFailed from distutils2._backport.tests import test_suite as btest_suite # just supporting -q right now # to enable detailed/quiet output -- Repository URL: http://hg.python.org/distutils2 From python-checkins at python.org Sun May 30 00:33:51 2010 From: python-checkins at python.org (tarek.ziade) Date: Sun, 30 May 2010 00:33:51 +0200 Subject: [Python-checkins] distutils2: fixed filelist initialization in sdist Message-ID: tarek.ziade pushed 7394724dba67 to distutils2: http://hg.python.org/distutils2/rev/7394724dba67 changeset: 174:7394724dba67 tag: tip user: Tarek Ziade date: Sun May 30 00:33:40 2010 +0200 summary: fixed filelist initialization in sdist files: src/distutils2/command/sdist.py, src/distutils2/manifest.py, src/distutils2/tests/test_sdist.py diff --git a/src/distutils2/command/sdist.py b/src/distutils2/command/sdist.py --- a/src/distutils2/command/sdist.py +++ b/src/distutils2/command/sdist.py @@ -121,6 +121,7 @@ self.metadata_check = 1 self.owner = None self.group = None + self.filelist = None def _check_archive_formats(self, formats): supported_formats = [name for name, desc in get_archive_formats()] @@ -152,10 +153,14 @@ if self.dist_dir is None: self.dist_dir = "dist" + if self.filelist is None: + self.filelist = Manifest() + + def run(self): # 'filelist' contains the list of files that will make up the # manifest - self.filelist = Manifest() + self.filelist.clear() # Run sub commands for cmd_name in self.get_sub_commands(): @@ -200,7 +205,7 @@ if self.use_defaults: self.add_defaults() if template_exists: - self.read_template() + self.filelist.read_template(self.template) if self.prune: self.prune_file_list() diff --git a/src/distutils2/manifest.py b/src/distutils2/manifest.py --- a/src/distutils2/manifest.py +++ b/src/distutils2/manifest.py @@ -54,6 +54,12 @@ for sort_tuple in sortable_files: self.files.append(os.path.join(*sort_tuple)) + def clear(self): + """Clear all collected files.""" + self.files = [] + if self.allfiles is not None: + self.allfiles = [] + def remove_duplicates(self): # Assumes list has been sorted! for i in range(len(self.files) - 1, 0, -1): diff --git a/src/distutils2/tests/test_sdist.py b/src/distutils2/tests/test_sdist.py --- a/src/distutils2/tests/test_sdist.py +++ b/src/distutils2/tests/test_sdist.py @@ -343,6 +343,19 @@ finally: archive.close() + def test_get_file_list(self): + dist, cmd = self.get_cmd() + cmd.finalize_options() + cmd.template = os.path.join(self.tmp_dir, 'MANIFEST.in') + f = open(cmd.template, 'w') + try: + f.write('include MANIFEST.in\n') + finally: + f.close() + + cmd.get_file_list() + self.assertIn('MANIFEST.in', cmd.filelist.files) + def test_suite(): return unittest2.makeSuite(SDistTestCase) -- Repository URL: http://hg.python.org/distutils2 From python-checkins at python.org Sun May 30 00:38:18 2010 From: python-checkins at python.org (tarek.ziade) Date: Sun, 30 May 2010 00:38:18 +0200 Subject: [Python-checkins] distutils2: started development notes Message-ID: tarek.ziade pushed 644cf5550a05 to distutils2: http://hg.python.org/distutils2/rev/644cf5550a05 changeset: 175:644cf5550a05 tag: tip user: Tarek Ziade date: Sun May 30 00:38:10 2010 +0200 summary: started development notes files: src/DEVNOTES.txt diff --git a/src/DEVNOTES.txt b/src/DEVNOTES.txt new file mode 100644 --- /dev/null +++ b/src/DEVNOTES.txt @@ -0,0 +1,10 @@ +Notes for developers +==================== + +- Distutils2 runs from 2.4 to 3.2 (3.x not implemented yet), so + make sure you don't use a syntax that doesn't work under + a specific Python version. + +- Always run tests.sh before you push a change. This implies + that you have all Python versions installed. + -- Repository URL: http://hg.python.org/distutils2 From solipsis at pitrou.net Sun May 30 01:24:33 2010 From: solipsis at pitrou.net (solipsis at pitrou.net) Date: Sun, 30 May 2010 01:24:33 +0200 (CEST) Subject: [Python-checkins] Daily py3k reference leaks (r81604): sum=0 Message-ID: <20100529232433.5087F1770A@ns6635.ovh.net> py3k results for svn r81604 (hg cset 756be6214a32) -------------------------------------------------- Command line was: ['./python', '-m', 'test.regrtest', '-uall', '-R', '3:3:/home/antoine/py3k/refleaks/reflogS8gPEy', '-x'] From python-checkins at python.org Sun May 30 14:12:25 2010 From: python-checkins at python.org (mark.dickinson) Date: Sun, 30 May 2010 14:12:25 +0200 (CEST) Subject: [Python-checkins] r81606 - in python/trunk: Lib/test/test_complex.py Misc/NEWS Objects/complexobject.c Message-ID: <20100530121225.9C2E7EEB48@mail.python.org> Author: mark.dickinson Date: Sun May 30 14:12:25 2010 New Revision: 81606 Log: Issue #5211: Complete removal of implicit coercions for the complex type. Coercion for arithmetic operations was already removed in r78280, but that commit didn't remove coercion for rich comparisons. Modified: python/trunk/Lib/test/test_complex.py python/trunk/Misc/NEWS python/trunk/Objects/complexobject.c Modified: python/trunk/Lib/test/test_complex.py ============================================================================== --- python/trunk/Lib/test/test_complex.py (original) +++ python/trunk/Lib/test/test_complex.py Sun May 30 14:12:25 2010 @@ -115,6 +115,19 @@ def test_coerce(self): self.assertRaises(OverflowError, complex.__coerce__, 1+1j, 1L<<10000) + def test_no_implicit_coerce(self): + # Python 2.7 removed implicit coercion from the complex type + class A(object): + def __coerce__(self, other): + raise RuntimeError + __hash__ = None + def __cmp__(self, other): + return -1 + + a = A() + self.assertRaises(TypeError, lambda: a + 2.0j) + self.assertTrue(a < 2.0j) + def test_richcompare(self): self.assertRaises(OverflowError, complex.__eq__, 1+1j, 1L<<10000) self.assertEqual(complex.__lt__(1+1j, None), NotImplemented) Modified: python/trunk/Misc/NEWS ============================================================================== --- python/trunk/Misc/NEWS (original) +++ python/trunk/Misc/NEWS Sun May 30 14:12:25 2010 @@ -12,6 +12,10 @@ Core and Builtins ----------------- +- Issue #5211: Implicit coercion for the complex type is now completely + removed. (Coercion for arithmetic operations was already removed in 2.7 + alpha 4, but coercion for rich comparisons was accidentally left in.) + - Issue #3798: Write sys.exit() message to sys.stderr to use stderr encoding and error handler, instead of writing to the C stderr file in utf-8 Modified: python/trunk/Objects/complexobject.c ============================================================================== --- python/trunk/Objects/complexobject.c (original) +++ python/trunk/Objects/complexobject.c Sun May 30 14:12:25 2010 @@ -787,25 +787,8 @@ Py_complex i, j; PyObject *res; - c = PyNumber_CoerceEx(&v, &w); - if (c < 0) - return NULL; - if (c > 0) { - Py_INCREF(Py_NotImplemented); - return Py_NotImplemented; - } - /* Make sure both arguments are complex. */ - if (!(PyComplex_Check(v) && PyComplex_Check(w))) { - Py_DECREF(v); - Py_DECREF(w); - Py_INCREF(Py_NotImplemented); - return Py_NotImplemented; - } - - i = ((PyComplexObject *)v)->cval; - j = ((PyComplexObject *)w)->cval; - Py_DECREF(v); - Py_DECREF(w); + TO_COMPLEX(v, i); + TO_COMPLEX(w, j); if (op != Py_EQ && op != Py_NE) { PyErr_SetString(PyExc_TypeError, From python-checkins at python.org Sun May 30 14:12:56 2010 From: python-checkins at python.org (mark.dickinson) Date: Sun, 30 May 2010 14:12:56 +0200 (CEST) Subject: [Python-checkins] r81607 - python/branches/py3k Message-ID: <20100530121256.AAEFDEEB58@mail.python.org> Author: mark.dickinson Date: Sun May 30 14:12:56 2010 New Revision: 81607 Log: Blocked revisions 81606 via svnmerge ........ r81606 | mark.dickinson | 2010-05-30 13:12:25 +0100 (Sun, 30 May 2010) | 4 lines Issue #5211: Complete removal of implicit coercions for the complex type. Coercion for arithmetic operations was already removed in r78280, but that commit didn't remove coercion for rich comparisons. ........ Modified: python/branches/py3k/ (props changed) From python-checkins at python.org Sun May 30 14:17:13 2010 From: python-checkins at python.org (mark.dickinson) Date: Sun, 30 May 2010 14:17:13 +0200 (CEST) Subject: [Python-checkins] r81608 - python/trunk/Objects/complexobject.c Message-ID: <20100530121713.24855EEB4F@mail.python.org> Author: mark.dickinson Date: Sun May 30 14:17:11 2010 New Revision: 81608 Log: Remove declaration for unused variable. Modified: python/trunk/Objects/complexobject.c Modified: python/trunk/Objects/complexobject.c ============================================================================== --- python/trunk/Objects/complexobject.c (original) +++ python/trunk/Objects/complexobject.c Sun May 30 14:17:11 2010 @@ -783,7 +783,6 @@ static PyObject * complex_richcompare(PyObject *v, PyObject *w, int op) { - int c; Py_complex i, j; PyObject *res; From python-checkins at python.org Sun May 30 14:17:39 2010 From: python-checkins at python.org (mark.dickinson) Date: Sun, 30 May 2010 14:17:39 +0200 (CEST) Subject: [Python-checkins] r81609 - python/branches/py3k Message-ID: <20100530121739.60E3FEEB4F@mail.python.org> Author: mark.dickinson Date: Sun May 30 14:17:39 2010 New Revision: 81609 Log: Blocked revisions 81608 via svnmerge ........ r81608 | mark.dickinson | 2010-05-30 13:17:11 +0100 (Sun, 30 May 2010) | 1 line Remove declaration for unused variable. ........ Modified: python/branches/py3k/ (props changed) From python-checkins at python.org Sun May 30 15:18:10 2010 From: python-checkins at python.org (mark.dickinson) Date: Sun, 30 May 2010 15:18:10 +0200 (CEST) Subject: [Python-checkins] r81610 - in python/trunk: Lib/test/test_complex.py Misc/NEWS Objects/complexobject.c Message-ID: <20100530131810.4A5FFEE9B3@mail.python.org> Author: mark.dickinson Date: Sun May 30 15:18:10 2010 New Revision: 81610 Log: Issue #8748: Fix incorrect results from comparisons between an integer and a complex instance. Based on a patch by Meador Inge. Modified: python/trunk/Lib/test/test_complex.py python/trunk/Misc/NEWS python/trunk/Objects/complexobject.c Modified: python/trunk/Lib/test/test_complex.py ============================================================================== --- python/trunk/Lib/test/test_complex.py (original) +++ python/trunk/Lib/test/test_complex.py Sun May 30 15:18:10 2010 @@ -129,7 +129,7 @@ self.assertTrue(a < 2.0j) def test_richcompare(self): - self.assertRaises(OverflowError, complex.__eq__, 1+1j, 1L<<10000) + self.assertEqual(complex.__eq__(1+1j, 1L<<10000), False) self.assertEqual(complex.__lt__(1+1j, None), NotImplemented) self.assertIs(complex.__eq__(1+1j, 1+1j), True) self.assertIs(complex.__eq__(1+1j, 2+2j), False) @@ -140,6 +140,23 @@ self.assertRaises(TypeError, complex.__gt__, 1+1j, 2+2j) self.assertRaises(TypeError, complex.__ge__, 1+1j, 2+2j) + def test_richcompare_boundaries(self): + def check(n, deltas, is_equal, imag = 0.0): + for delta in deltas: + i = n + delta + z = complex(i, imag) + self.assertIs(complex.__eq__(z, i), is_equal(delta)) + self.assertIs(complex.__ne__(z, i), not is_equal(delta)) + # For IEEE-754 doubles the following should hold: + # x in [2 ** (52 + i), 2 ** (53 + i + 1)] -> x mod 2 ** i == 0 + # where the interval is representable, of course. + for i in range(1, 10): + pow = 52 + i + mult = 2 ** i + check(2 ** pow, range(1, 101), lambda delta: delta % mult == 0) + check(2 ** pow, range(1, 101), lambda delta: False, float(i)) + check(2 ** 53, range(-100, 0), lambda delta: True) + def test_mod(self): self.assertRaises(ZeroDivisionError, (1+1j).__mod__, 0+0j) Modified: python/trunk/Misc/NEWS ============================================================================== --- python/trunk/Misc/NEWS (original) +++ python/trunk/Misc/NEWS Sun May 30 15:18:10 2010 @@ -12,6 +12,13 @@ Core and Builtins ----------------- +- Issue #8748: Fix two issues with comparisons between complex and integer + objects. (1) The comparison could incorrectly return True in some cases + (2**53+1 == complex(2**53) == 2**53), breaking transivity of equality. + (2) The comparison raised an OverflowError for large integers, leading + to unpredictable exceptions when combining integers and complex objects + in sets or dicts. + - Issue #5211: Implicit coercion for the complex type is now completely removed. (Coercion for arithmetic operations was already removed in 2.7 alpha 4, but coercion for rich comparisons was accidentally left in.) Modified: python/trunk/Objects/complexobject.c ============================================================================== --- python/trunk/Objects/complexobject.c (original) +++ python/trunk/Objects/complexobject.c Sun May 30 15:18:10 2010 @@ -783,25 +783,70 @@ static PyObject * complex_richcompare(PyObject *v, PyObject *w, int op) { - Py_complex i, j; PyObject *res; + Py_complex i; + int equal; + if (op != Py_EQ && op != Py_NE) { + /* for backwards compatibility, comparisons with non-numbers return + * NotImplemented. Only comparisons with core numeric types raise + * TypeError. + */ + if (PyInt_Check(w) || PyLong_Check(w) || + PyFloat_Check(w) || PyComplex_Check(w)) { + PyErr_SetString(PyExc_TypeError, + "no ordering relation is defined " + "for complex numbers"); + return NULL; + } + goto Unimplemented; + } + + assert(PyComplex_Check(v)); TO_COMPLEX(v, i); - TO_COMPLEX(w, j); - if (op != Py_EQ && op != Py_NE) { - PyErr_SetString(PyExc_TypeError, - "no ordering relation is defined for complex numbers"); - return NULL; + if (PyInt_Check(w) || PyLong_Check(w)) { + /* Check for 0.0 imaginary part first to avoid the rich + * comparison when possible. + */ + if (i.imag == 0.0) { + PyObject *j, *sub_res; + j = PyFloat_FromDouble(i.real); + if (j == NULL) + return NULL; + + sub_res = PyObject_RichCompare(j, w, op); + Py_DECREF(j); + return sub_res; + } + else { + equal = 0; + } + } + else if (PyFloat_Check(w)) { + equal = (i.real == PyFloat_AsDouble(w) && i.imag == 0.0); + } + else if (PyComplex_Check(w)) { + Py_complex j; + + TO_COMPLEX(w, j); + equal = (i.real == j.real && i.imag == j.imag); + } + else { + goto Unimplemented; } - if ((i.real == j.real && i.imag == j.imag) == (op == Py_EQ)) - res = Py_True; + if (equal == (op == Py_EQ)) + res = Py_True; else - res = Py_False; + res = Py_False; Py_INCREF(res); return res; + + Unimplemented: + Py_INCREF(Py_NotImplemented); + return Py_NotImplemented; } static PyObject * From python-checkins at python.org Sun May 30 15:18:47 2010 From: python-checkins at python.org (mark.dickinson) Date: Sun, 30 May 2010 15:18:47 +0200 (CEST) Subject: [Python-checkins] r81611 - python/branches/py3k Message-ID: <20100530131847.9C465EEB6A@mail.python.org> Author: mark.dickinson Date: Sun May 30 15:18:47 2010 New Revision: 81611 Log: Recorded merge of revisions 81610 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r81610 | mark.dickinson | 2010-05-30 14:18:10 +0100 (Sun, 30 May 2010) | 3 lines Issue #8748: Fix incorrect results from comparisons between an integer and a complex instance. Based on a patch by Meador Inge. ........ Modified: python/branches/py3k/ (props changed) From python-checkins at python.org Sun May 30 16:49:32 2010 From: python-checkins at python.org (benjamin.peterson) Date: Sun, 30 May 2010 16:49:32 +0200 (CEST) Subject: [Python-checkins] r81612 - python/branches/py3k/Python/ceval.c Message-ID: <20100530144932.DD4ECEEB32@mail.python.org> Author: benjamin.peterson Date: Sun May 30 16:49:32 2010 New Revision: 81612 Log: use atomic structures in non-thread version Modified: python/branches/py3k/Python/ceval.c Modified: python/branches/py3k/Python/ceval.c ============================================================================== --- python/branches/py3k/Python/ceval.c (original) +++ python/branches/py3k/Python/ceval.c Sun May 30 16:49:32 2010 @@ -598,7 +598,7 @@ } pendingcalls[NPENDINGCALLS]; static volatile int pendingfirst = 0; static volatile int pendinglast = 0; -static volatile int pendingcalls_to_do = 0; +static _Py_atomic_int pendingcalls_to_do = {0}; int Py_AddPendingCall(int (*func)(void *), void *arg) From python-checkins at python.org Sun May 30 17:46:48 2010 From: python-checkins at python.org (ronald.oussoren) Date: Sun, 30 May 2010 17:46:48 +0200 (CEST) Subject: [Python-checkins] r81613 - python/branches/py3k/Lib/webbrowser.py Message-ID: <20100530154648.DA8B4EEA5A@mail.python.org> Author: ronald.oussoren Date: Sun May 30 17:46:48 2010 New Revision: 81613 Log: Remove conditional import of 'ic', that module was removed in the transition from python 2.x to python 3.x. Modified: python/branches/py3k/Lib/webbrowser.py Modified: python/branches/py3k/Lib/webbrowser.py ============================================================================== --- python/branches/py3k/Lib/webbrowser.py (original) +++ python/branches/py3k/Lib/webbrowser.py Sun May 30 17:46:48 2010 @@ -540,18 +540,6 @@ # Platform support for MacOS # -try: - import ic -except ImportError: - pass -else: - class InternetConfig(BaseBrowser): - def open(self, url, new=0, autoraise=True): - ic.launchurl(url) - return True # Any way to get status? - - register("internet-config", InternetConfig, update_tryorder=-1) - if sys.platform == 'darwin': # Adapted from patch submitted to SourceForge by Steven J. Burr class MacOSX(BaseBrowser): From python-checkins at python.org Sun May 30 23:24:44 2010 From: python-checkins at python.org (tarek.ziade) Date: Sun, 30 May 2010 23:24:44 +0200 (CEST) Subject: [Python-checkins] r81614 - peps/trunk/pep-0345.txt Message-ID: <20100530212444.11A9CEEA40@mail.python.org> Author: tarek.ziade Date: Sun May 30 23:24:43 2010 New Revision: 81614 Log: removed erroneous sentence Modified: peps/trunk/pep-0345.txt Modified: peps/trunk/pep-0345.txt ============================================================================== --- peps/trunk/pep-0345.txt (original) +++ peps/trunk/pep-0345.txt Sun May 30 23:24:43 2010 @@ -368,8 +368,6 @@ dependency, optionally followed by a version declaration within parentheses. -Version numbers must be in the format specified in `Version Specifiers`_. - Because they refer to non-Python software releases, version numbers for this field are **not** required to conform to the format specified in PEP 386: they should correspond to the From solipsis at pitrou.net Mon May 31 01:23:22 2010 From: solipsis at pitrou.net (solipsis at pitrou.net) Date: Mon, 31 May 2010 01:23:22 +0200 (CEST) Subject: [Python-checkins] Daily py3k reference leaks (r81613): sum=0 Message-ID: <20100530232322.66C3F1770A@ns6635.ovh.net> py3k results for svn r81613 (hg cset 5fff92e30a4c) -------------------------------------------------- Command line was: ['./python', '-m', 'test.regrtest', '-uall', '-R', '3:3:/home/antoine/py3k/refleaks/reflogvCT2tH', '-x'] From python-checkins at python.org Mon May 31 01:56:09 2010 From: python-checkins at python.org (tarek.ziade) Date: Mon, 31 May 2010 01:56:09 +0200 Subject: [Python-checkins] distutils2: basic implementation for the two missing functions from pep376 Message-ID: tarek.ziade pushed 7060eb528715 to distutils2: http://hg.python.org/distutils2/rev/7060eb528715 changeset: 176:7060eb528715 parent: 160:30ad3af43b5f user: Josip Djolonga date: Thu May 27 17:55:01 2010 +0200 summary: basic implementation for the two missing functions from pep376 files: src/distutils2/_backport/pkgutil.py diff --git a/src/distutils2/_backport/pkgutil.py b/src/distutils2/_backport/pkgutil.py --- a/src/distutils2/_backport/pkgutil.py +++ b/src/distutils2/_backport/pkgutil.py @@ -11,14 +11,14 @@ from types import ModuleType from distutils2.errors import DistutilsError from distutils2.metadata import DistributionMetadata -from distutils2.version import suggest_normalized_version +from distutils2.version import suggest_normalized_version, VersionPredicate __all__ = [ 'get_importer', 'iter_importers', 'get_loader', 'find_loader', 'walk_packages', 'iter_modules', 'ImpImporter', 'ImpLoader', 'read_code', 'extend_path', 'Distribution', 'distinfo_dirname', 'get_distributions', - 'get_distribution', 'get_file_users', + 'get_distribution', 'get_file_users', ] def read_code(stream): @@ -696,8 +696,8 @@ def get_distinfo_files(self, local=False): """ - Iterates over the RECORD entries and returns paths for each line if the - path is pointing to a file located in the ``.dist-info`` directory or + Iterates over the RECORD entries and returns paths for each line if the + path is pointing to a file located in the ``.dist-info`` directory or one of its subdirectories. :parameter local: If *local* is ``True``, each returned path is @@ -762,7 +762,7 @@ def get_distribution(name): """ Scans all elements in ``sys.path`` and looks for all directories ending with - ``.dist-info``. Returns a :class:`Distribution` corresponding to the + ``.dist-info``. Returns a :class:`Distribution` corresponding to the ``.dist-info`` directory that contains the METADATA that matches *name* for the *name* metadata. @@ -777,6 +777,77 @@ break return found +def obsoletes_distribution(name, version=None): + """ + Iterates over all distributions to find which distributions obsolete *name*. + If a *version* is provided, it will be used to filter the results. + + :type name: string + :type version: string + :parameter name: + """ + for dist in get_distributions(): + obsoleted = dist.metadata['Obsoletes-Dist'] + dist.metadata['Obsoletes'] + for obs in obsoleted: + o_components = obs.split(' ', 1) + if len(o_components) == 1: + if name == o_components[0]: + yield dist + break + else: + try: + predicate = VersionPredicate(obs) + except ValueError: + raise DistutilsError(('Distribution %s has ill formed' + + ' obsoletes field') % (dist.name,)) + if name == o_components[0] and predicate.match(version): + yield dist + break + +def provides_distribution(name, version=None): + """ + Iterates over all distributions to find which distributions provide *name*. + If a *version* is provided, it will be used to filter the results. Scans + all elements in ``sys.path`` and looks for all directories ending with + ``.dist-info``. Returns a :class:`Distribution` corresponding to the + ``.dist-info`` directory that contains a ``METADATA`` that matches *name* + for the name metadata. + + This function only returns the first result founded, since no more than + one values are expected. If the directory is not found, returns ``None``. + + :parameter version: a version specifier that indicates the version + required, conforming to the format in ``PEP-345`` + + :type name: string + :type version: string + """ + predicate = None + if not version is None: + try: + predicate = VersionPredicate(name + ' (' + version + ')') + except ValueErorr: + raise DistutilsError('Invalid name or version') + + for dist in get_distributions(): + provided = dist.metadata['Provides-Dist'] + dist.metadata['Provides'] + + for p in provided: + p_components = p.split(' ', 1) + if len(p_components) == 1 or predicate is None: + if name == p: + yield dist + break + else: + p_name, p_ver = p_components + if len(p_ver) < 2 or p_ver[0] != '(' or p_ver[-1] != ')': + raise DistutilsError(('Distribution %s has invalid ' + + 'provides field') % (dist.name,)) + p_ver = p_ver[1:-1] # trim off the parenthesis + if p_name == name and predicate.match(p_ver): + yield dist + break + def get_file_users(path): """ Iterates over all distributions to find out which distributions uses @@ -789,3 +860,4 @@ for dist in get_distributions(): if dist.uses(path): yield dist + -- Repository URL: http://hg.python.org/distutils2 From python-checkins at python.org Mon May 31 01:56:09 2010 From: python-checkins at python.org (tarek.ziade) Date: Mon, 31 May 2010 01:56:09 +0200 Subject: [Python-checkins] distutils2: fixed the test suite to use self.assert* instead of assert Message-ID: tarek.ziade pushed 199f80bb0a9c to distutils2: http://hg.python.org/distutils2/rev/199f80bb0a9c changeset: 179:199f80bb0a9c user: Josip Djolonga date: Fri May 28 22:48:57 2010 +0200 summary: fixed the test suite to use self.assert* instead of assert files: src/distutils2/tests/test_version.py diff --git a/src/distutils2/tests/test_version.py b/src/distutils2/tests/test_version.py --- a/src/distutils2/tests/test_version.py +++ b/src/distutils2/tests/test_version.py @@ -139,18 +139,17 @@ for predicate in predicates: v = VersionPredicate(predicate) - assert VersionPredicate('Hey (>=2.5,<2.7)').match('2.6') - assert VersionPredicate('Ho').match('2.6') - assert not VersionPredicate('Hey (>=2.5,!=2.6,<2.7)').match('2.6') - assert VersionPredicate('Ho (<3.0)').match('2.6') - assert VersionPredicate('Ho (<3.0,!=2.5)').match('2.6.0') - assert not VersionPredicate('Ho (<3.0,!=2.6)').match('2.6.0') - assert VersionPredicate('Ho (2.5)').match('2.5.4') - assert not VersionPredicate('Ho (!=2.5)').match('2.5.2') - assert VersionPredicate('Hey (<=2.5)').match('2.5.9') - assert not VersionPredicate('Hey (<=2.5)').match('2.6.0') - assert VersionPredicate('Hey (>=2.5)').match('2.5.1') - + self.assertTrue(VersionPredicate('Hey (>=2.5,<2.7)').match('2.6')) + self.assertTrue(VersionPredicate('Ho').match('2.6')) + self.assertFalse(VersionPredicate('Hey (>=2.5,!=2.6,<2.7)').match('2.6')) + self.assertTrue(VersionPredicate('Ho (<3.0)').match('2.6')) + self.assertTrue(VersionPredicate('Ho (<3.0,!=2.5)').match('2.6.0')) + self.assertFalse(VersionPredicate('Ho (<3.0,!=2.6)').match('2.6.0')) + self.assertTrue(VersionPredicate('Ho (2.5)').match('2.5.4')) + self.assertFalse(VersionPredicate('Ho (!=2.5)').match('2.5.2')) + self.assertTrue(VersionPredicate('Hey (<=2.5)').match('2.5.9')) + self.assertFalse(VersionPredicate('Hey (<=2.5)').match('2.6.0')) + self.assertTrue(VersionPredicate('Hey (>=2.5)').match('2.5.1')) # XXX need to silent the micro version in this case #assert not VersionPredicate('Ho (<3.0,!=2.6)').match('2.6.3') -- Repository URL: http://hg.python.org/distutils2 From python-checkins at python.org Mon May 31 01:56:09 2010 From: python-checkins at python.org (tarek.ziade) Date: Mon, 31 May 2010 01:56:09 +0200 Subject: [Python-checkins] distutils2: I managed to slip in a hardcoded path .. (thanks merwok) Message-ID: tarek.ziade pushed 53e9ad4305fd to distutils2: http://hg.python.org/distutils2/rev/53e9ad4305fd changeset: 180:53e9ad4305fd user: Josip Djolonga date: Sat May 29 17:00:00 2010 +0200 summary: I managed to slip in a hardcoded path .. (thanks merwok) files: src/distutils2/_backport/tests/test_pkgutil.py diff --git a/src/distutils2/_backport/tests/test_pkgutil.py b/src/distutils2/_backport/tests/test_pkgutil.py --- a/src/distutils2/_backport/tests/test_pkgutil.py +++ b/src/distutils2/_backport/tests/test_pkgutil.py @@ -9,8 +9,6 @@ except ImportError: from md5 import md5 -sys.path.append('/home/josip/dev/distutils2/src') - from test.test_support import run_unittest, TESTFN import distutils2._backport.pkgutil -- Repository URL: http://hg.python.org/distutils2 From python-checkins at python.org Mon May 31 01:56:09 2010 From: python-checkins at python.org (tarek.ziade) Date: Mon, 31 May 2010 01:56:09 +0200 Subject: [Python-checkins] distutils2: added tests that cover the bug Message-ID: tarek.ziade pushed e5c9c41d41f6 to distutils2: http://hg.python.org/distutils2/rev/e5c9c41d41f6 changeset: 178:e5c9c41d41f6 user: Josip Djolonga date: Thu May 27 20:51:47 2010 +0200 summary: added tests that cover the bug files: src/distutils2/tests/test_version.py diff --git a/src/distutils2/tests/test_version.py b/src/distutils2/tests/test_version.py --- a/src/distutils2/tests/test_version.py +++ b/src/distutils2/tests/test_version.py @@ -145,6 +145,11 @@ assert VersionPredicate('Ho (<3.0)').match('2.6') assert VersionPredicate('Ho (<3.0,!=2.5)').match('2.6.0') assert not VersionPredicate('Ho (<3.0,!=2.6)').match('2.6.0') + assert VersionPredicate('Ho (2.5)').match('2.5.4') + assert not VersionPredicate('Ho (!=2.5)').match('2.5.2') + assert VersionPredicate('Hey (<=2.5)').match('2.5.9') + assert not VersionPredicate('Hey (<=2.5)').match('2.6.0') + assert VersionPredicate('Hey (>=2.5)').match('2.5.1') # XXX need to silent the micro version in this case -- Repository URL: http://hg.python.org/distutils2 From python-checkins at python.org Mon May 31 01:56:09 2010 From: python-checkins at python.org (tarek.ziade) Date: Mon, 31 May 2010 01:56:09 +0200 Subject: [Python-checkins] distutils2: fixed version and the two added functions, added test cases Message-ID: tarek.ziade pushed 20ebf9c9da67 to distutils2: http://hg.python.org/distutils2/rev/20ebf9c9da67 changeset: 177:20ebf9c9da67 user: Josip Djolonga date: Thu May 27 20:45:49 2010 +0200 summary: fixed version and the two added functions, added test cases files: src/distutils2/_backport/pkgutil.py, src/distutils2/_backport/tests/fake_dists/choxie-2.0.0.9.dist-info/METADATA, src/distutils2/_backport/tests/fake_dists/towel_stuff-0.1.dist-info/METADATA, src/distutils2/_backport/tests/test_pkgutil.py, src/distutils2/version.py diff --git a/src/distutils2/_backport/pkgutil.py b/src/distutils2/_backport/pkgutil.py --- a/src/distutils2/_backport/pkgutil.py +++ b/src/distutils2/_backport/pkgutil.py @@ -790,7 +790,7 @@ obsoleted = dist.metadata['Obsoletes-Dist'] + dist.metadata['Obsoletes'] for obs in obsoleted: o_components = obs.split(' ', 1) - if len(o_components) == 1: + if len(o_components) == 1 or version is None: if name == o_components[0]: yield dist break @@ -826,7 +826,7 @@ if not version is None: try: predicate = VersionPredicate(name + ' (' + version + ')') - except ValueErorr: + except ValueError: raise DistutilsError('Invalid name or version') for dist in get_distributions(): @@ -835,7 +835,7 @@ for p in provided: p_components = p.split(' ', 1) if len(p_components) == 1 or predicate is None: - if name == p: + if name == p_components[0]: yield dist break else: diff --git a/src/distutils2/_backport/tests/fake_dists/choxie-2.0.0.9.dist-info/METADATA b/src/distutils2/_backport/tests/fake_dists/choxie-2.0.0.9.dist-info/METADATA --- a/src/distutils2/_backport/tests/fake_dists/choxie-2.0.0.9.dist-info/METADATA +++ b/src/distutils2/_backport/tests/fake_dists/choxie-2.0.0.9.dist-info/METADATA @@ -4,3 +4,5 @@ Summary: Chocolate with a kick! Requires-Dist: towel-stuff (0.1) Provides-Dist: truffles (1.0) +Obsoletes-Dist: truffles (<=0.8,>=0.5) +Obsoletes-Dist: truffles (<=0.9,>=0.6) diff --git a/src/distutils2/_backport/tests/fake_dists/towel_stuff-0.1.dist-info/METADATA b/src/distutils2/_backport/tests/fake_dists/towel_stuff-0.1.dist-info/METADATA --- a/src/distutils2/_backport/tests/fake_dists/towel_stuff-0.1.dist-info/METADATA +++ b/src/distutils2/_backport/tests/fake_dists/towel_stuff-0.1.dist-info/METADATA @@ -1,3 +1,5 @@ Metadata-Version: 1.2 Name: towel-stuff Version: 0.1 +Provides-Dist: truffles (1.1.2) +Obsoletes-Dist: truffles (!=0.8,<1.0) diff --git a/src/distutils2/_backport/tests/test_pkgutil.py b/src/distutils2/_backport/tests/test_pkgutil.py --- a/src/distutils2/_backport/tests/test_pkgutil.py +++ b/src/distutils2/_backport/tests/test_pkgutil.py @@ -9,6 +9,8 @@ except ImportError: from md5 import md5 +sys.path.append('/home/josip/dev/distutils2/src') + from test.test_support import run_unittest, TESTFN import distutils2._backport.pkgutil @@ -260,6 +262,52 @@ self.assertTrue(isinstance(dist, Distribution)) self.assertEqual(dist.name, name) + def test_provides(self): + """ Test for looking up distributions by what they provide """ + from distutils2._backport.pkgutil import provides_distribution + from distutils2.errors import DistutilsError + + l = [dist.name for dist in provides_distribution('truffles')] + self.assertListEqual(l, ['choxie', 'towel-stuff']) + + l = [dist.name for dist in provides_distribution('truffles', '1.0')] + self.assertListEqual(l, ['choxie']) + + l = [dist.name for dist in provides_distribution('truffles', '1.1.2')] + self.assertListEqual(l, ['towel-stuff']) + + l = [dist.name for dist in provides_distribution('truffles', '1.1')] + self.assertListEqual(l, ['towel-stuff']) + + l = [dist.name for dist in provides_distribution('truffles', '!=1.1,<=2.0')] + self.assertListEqual(l, ['choxie']) + + l = [dist.name for dist in provides_distribution('truffles', '>1.0')] + self.assertListEqual(l, ['towel-stuff']) + + l = [dist.name for dist in provides_distribution('truffles', '>=1.0')] + self.assertListEqual(l, ['choxie', 'towel-stuff']) + + def test_obsoletes(self): + """ Test looking for distributions based on what they obsolete """ + from distutils2._backport.pkgutil import obsoletes_distribution + from distutils2.errors import DistutilsError + + l = [dist.name for dist in obsoletes_distribution('truffles', '1.0')] + self.assertListEqual(l, []) + + l = [dist.name for dist in obsoletes_distribution('truffles', '0.8')] + self.assertListEqual(l, ['choxie']) + + l = [dist.name for dist in obsoletes_distribution('truffles', '0.9.6')] + self.assertListEqual(l, ['choxie', 'towel-stuff']) + + l = [dist.name for dist in obsoletes_distribution('truffles', '0.5.2.3')] + self.assertListEqual(l, ['choxie', 'towel-stuff']) + + l = [dist.name for dist in obsoletes_distribution('truffles', '0.2')] + self.assertListEqual(l, ['towel-stuff']) + def test_suite(): suite = unittest2.TestSuite() @@ -273,3 +321,16 @@ if __name__ == "__main__": test_main() + +def test_suite(): + suite = unittest2.TestSuite() + testcase_loader = unittest2.loader.defaultTestLoader.loadTestsFromTestCase + suite.addTest(testcase_loader(TestPkgUtilFunctions)) + suite.addTest(testcase_loader(TestPkgUtilDistribution)) + return suite + +def test_main(): + run_unittest(test_suite()) + +if __name__ == "__main__": + test_main() diff --git a/src/distutils2/version.py b/src/distutils2/version.py --- a/src/distutils2/version.py +++ b/src/distutils2/version.py @@ -330,10 +330,11 @@ _operators = {"<": lambda x, y: x < y, ">": lambda x, y: x > y, - "<=": lambda x, y: x <= y, - ">=": lambda x, y: x >= y, - "==": lambda x, y: x == y, - "!=": lambda x, y: x != y} + "<=": lambda x, y: str(x).startswith(str(y)) or x < y, + ">=": lambda x, y: str(x).startswith(str(y)) or x > y, + "==": lambda x, y: str(x).startswith(str(y)), + "!=": lambda x, y: not str(x).startswith(str(y)), + } def __init__(self, predicate): predicate = predicate.strip() -- Repository URL: http://hg.python.org/distutils2 From python-checkins at python.org Mon May 31 01:56:09 2010 From: python-checkins at python.org (tarek.ziade) Date: Mon, 31 May 2010 01:56:09 +0200 Subject: [Python-checkins] distutils2: test files for the suite Message-ID: tarek.ziade pushed 49a35354fb0d to distutils2: http://hg.python.org/distutils2/rev/49a35354fb0d changeset: 182:49a35354fb0d user: Josip Djolonga date: Sat May 29 18:05:43 2010 +0200 summary: test files for the suite files: src/distutils2/_backport/tests/fake_dists/bacon-0.1.egg-info/PKG-INFO, src/distutils2/_backport/tests/fake_dists/cheese-2.0.2.egg-info diff --git a/src/distutils2/_backport/tests/fake_dists/bacon-0.1.egg-info/PKG-INFO b/src/distutils2/_backport/tests/fake_dists/bacon-0.1.egg-info/PKG-INFO new file mode 100644 --- /dev/null +++ b/src/distutils2/_backport/tests/fake_dists/bacon-0.1.egg-info/PKG-INFO @@ -0,0 +1,5 @@ +Metadata-Version: 1.2 +Name: bacon +Version: 0.1 +Provides-Dist: truffles (2.0) +Obsoletes-Dist: truffles (>=0.9,<=1.5) diff --git a/src/distutils2/_backport/tests/fake_dists/cheese-2.0.2.egg-info b/src/distutils2/_backport/tests/fake_dists/cheese-2.0.2.egg-info new file mode 100644 --- /dev/null +++ b/src/distutils2/_backport/tests/fake_dists/cheese-2.0.2.egg-info @@ -0,0 +1,5 @@ +Metadata-Version: 1.2 +Name: cheese +Version: 2.0.2 +Provides-Dist: truffles (1.0.2) +Obsoletes-Dist: truffles (!=1.2,<=2.0) -- Repository URL: http://hg.python.org/distutils2 From python-checkins at python.org Mon May 31 01:56:09 2010 From: python-checkins at python.org (tarek.ziade) Date: Mon, 31 May 2010 01:56:09 +0200 Subject: [Python-checkins] distutils2: Added fallback support for .egg-info distributions Message-ID: tarek.ziade pushed a838155c9fe2 to distutils2: http://hg.python.org/distutils2/rev/a838155c9fe2 changeset: 181:a838155c9fe2 user: Josip Djolonga date: Sat May 29 18:02:57 2010 +0200 summary: Added fallback support for .egg-info distributions files: src/distutils2/_backport/pkgutil.py, src/distutils2/_backport/tests/test_pkgutil.py diff --git a/src/distutils2/_backport/pkgutil.py b/src/distutils2/_backport/pkgutil.py --- a/src/distutils2/_backport/pkgutil.py +++ b/src/distutils2/_backport/pkgutil.py @@ -17,8 +17,9 @@ 'get_importer', 'iter_importers', 'get_loader', 'find_loader', 'walk_packages', 'iter_modules', 'ImpImporter', 'ImpLoader', 'read_code', 'extend_path', - 'Distribution', 'distinfo_dirname', 'get_distributions', - 'get_distribution', 'get_file_users', + 'Distribution', 'EggInfoDistribution', 'distinfo_dirname', + 'get_distributions', 'get_distribution', 'get_file_users', + 'provides_distribution', 'obsoletes_distribution', ] def read_code(stream): @@ -604,7 +605,7 @@ name = '' """The name of the distribution.""" metadata = None - """A :class:`distutils2.metadata.DistributionMetadata` instance loaded with + """A :class:`distutils2.metadata.DistributionMetadata` instance loaded with the distribution's METADATA file.""" requested = False """A boolean that indicates whether the REQUESTED metadata file is present @@ -646,7 +647,7 @@ def uses(self, path): """ - Returns ``True`` if path is listed in RECORD. *path* can be a local + Returns ``True`` if path is listed in RECORD. *path* can be a local absolute path or a relative ``'/'``-separated path. :rtype: boolean @@ -709,6 +710,29 @@ for path, md5, size in self._get_records(local): yield path +class EggInfoDistribution: + """Created with the *path* of the ``.egg-info`` directory or file provided + to the constructor. It reads the metadata contained in the file itself, or + if the given path happens to be a directory, the metadata is read from the + file PKG-INFO under that directory.""" + + name = '' + """The name of the distribution.""" + metadata = None + """A :class:`distutils2.metadata.DistributionMetadata` instance loaded with + the distribution's METADATA file.""" + + def __init__(self, path): + if os.path.isdir(path): + path = os.path.join(path, 'PKG-INFO') + self.metadata = DistributionMetadata(path=path) + self.name = self.metadata['name'] + + def get_installed_files(self, local=False): + return [] + + def uses(self, path): + return False def _normalize_dist_name(name): """Returns a normalized name from the given *name*. @@ -719,7 +743,7 @@ """ The *name* and *version* parameters are converted into their filename-escaped form, i.e. any ``'-'`` characters are replaced with ``'_'`` - other than the one in ``'dist-info'`` and the one separating the name from + other than the one in ``'dist-info'`` and the one separating the name from the version number. :parameter name: is converted to a standard distribution name by replacing @@ -743,13 +767,15 @@ normalized_version = version return '-'.join([name, normalized_version]) + file_extension -def get_distributions(): +def get_distributions(use_egg_info = False): """ Provides an iterator that looks for ``.dist-info`` directories in ``sys.path`` and returns :class:`Distribution` instances for each one of - them. + them. If the parameters *use_egg_info* is ``True``, then the ``.egg-info`` + files and directores are iterated as well. - :rtype: iterator of :class:`Distribution` instances""" + :rtype: iterator of :class:`Distribution` and :class:`EggInfoDistribution` + instances""" for path in sys.path: realpath = os.path.realpath(path) if not os.path.isdir(realpath): @@ -758,35 +784,50 @@ if dir.endswith('.dist-info'): dist = Distribution(os.path.join(realpath, dir)) yield dist + elif use_egg_info and dir.endswith('.egg-info'): + dist = EggInfoDistribution(os.path.join(realpath, dir)) + yield dist -def get_distribution(name): +def get_distribution(name, use_egg_info = False): """ Scans all elements in ``sys.path`` and looks for all directories ending with ``.dist-info``. Returns a :class:`Distribution` corresponding to the ``.dist-info`` directory that contains the METADATA that matches *name* for - the *name* metadata. + the *name* metadata field. + If no distribution exists with the given *name* and the parameter + *use_egg_info* is set to ``True``, then all files and directories ending + with ``.egg-info`` are scanned. A :class:`EggInfoDistribution` instance is + returned if one is found that has metadata that matches *name* for the + *name* metadata field. This function only returns the first result founded, as no more than one value is expected. If the directory is not found, ``None`` is returned. - :rtype: :class:`Distribution` or None""" + :rtype: :class:`Distribution` or :class:`EggInfoDistribution: or None""" found = None for dist in get_distributions(): if dist.name == name: found = dist break + if use_egg_info: + for dist in get_distributions(True): + if dist.name == name: + found = dist + break return found -def obsoletes_distribution(name, version=None): +def obsoletes_distribution(name, version=None, use_egg_info = False): """ Iterates over all distributions to find which distributions obsolete *name*. If a *version* is provided, it will be used to filter the results. + If the argument *use_egg_info* is set to ``True``, then ``.egg-info`` + distributions will be considered as well. :type name: string :type version: string :parameter name: """ - for dist in get_distributions(): + for dist in get_distributions(use_egg_info): obsoleted = dist.metadata['Obsoletes-Dist'] + dist.metadata['Obsoletes'] for obs in obsoleted: o_components = obs.split(' ', 1) @@ -804,14 +845,16 @@ yield dist break -def provides_distribution(name, version=None): +def provides_distribution(name, version=None, use_egg_info = False): """ Iterates over all distributions to find which distributions provide *name*. If a *version* is provided, it will be used to filter the results. Scans all elements in ``sys.path`` and looks for all directories ending with ``.dist-info``. Returns a :class:`Distribution` corresponding to the ``.dist-info`` directory that contains a ``METADATA`` that matches *name* - for the name metadata. + for the name metadata. If the argument *use_egg_info* is set to ``True``, + then all files and directories ending with ``.egg-info`` are considered + as well and returns an :class:`EggInfoDistribution` instance. This function only returns the first result founded, since no more than one values are expected. If the directory is not found, returns ``None``. @@ -829,7 +872,7 @@ except ValueError: raise DistutilsError('Invalid name or version') - for dist in get_distributions(): + for dist in get_distributions(use_egg_info): provided = dist.metadata['Provides-Dist'] + dist.metadata['Provides'] for p in provided: diff --git a/src/distutils2/_backport/tests/test_pkgutil.py b/src/distutils2/_backport/tests/test_pkgutil.py --- a/src/distutils2/_backport/tests/test_pkgutil.py +++ b/src/distutils2/_backport/tests/test_pkgutil.py @@ -216,7 +216,9 @@ found_dists = [] # Import the function in question - from distutils2._backport.pkgutil import get_distributions, Distribution + from distutils2._backport.pkgutil import get_distributions, \ + Distribution, \ + EggInfoDistribution # Verify the fake dists have been found. dists = [ dist for dist in get_distributions() ] @@ -231,13 +233,31 @@ # Finally, test that we found all that we were looking for self.assertListEqual(sorted(found_dists), sorted(fake_dists)) + # Now, test if the egg-info distributions are found correctly as well + fake_dists += [('bacon', '0.1'), ('cheese', '2.0.2')] + found_dists = [] + + dists = [ dist for dist in get_distributions(use_egg_info=True) ] + for dist in dists: + if not (isinstance(dist, Distribution) or \ + isinstance(dist, EggInfoDistribution)): + self.fail("item received was not a Distribution or " + "EggInfoDistribution instance: %s" % type(dist)) + if dist.name in dict(fake_dists).keys(): + found_dists.append((dist.name, dist.metadata['version'])) + + self.assertListEqual(sorted(fake_dists), sorted(found_dists)) + + def test_get_distribution(self): """Test for looking up a distribution by name.""" # Test the lookup of the towel-stuff distribution name = 'towel-stuff' # Note: This is different from the directory name # Import the function in question - from distutils2._backport.pkgutil import get_distribution, Distribution + from distutils2._backport.pkgutil import get_distribution, \ + Distribution, \ + EggInfoDistribution # Lookup the distribution dist = get_distribution(name) @@ -250,6 +270,21 @@ # Verify partial name matching doesn't work self.assertEqual(None, get_distribution('towel')) + # Verify that it does not find egg-info distributions, when not + # instructed to + self.assertEqual(None, get_distribution('bacon')) + self.assertEqual(None, get_distribution('cheese')) + + # Now check that it works well in both situations, when egg-info + # is a file and directory respectively. + dist = get_distribution('cheese', use_egg_info=True) + self.assertTrue(isinstance(dist, EggInfoDistribution)) + self.assertEqual(dist.name, 'cheese') + + dist = get_distribution('bacon', use_egg_info=True) + self.assertTrue(isinstance(dist, EggInfoDistribution)) + self.assertEqual(dist.name, 'bacon') + def test_get_file_users(self): """Test the iteration of distributions that use a file.""" from distutils2._backport.pkgutil import get_file_users, Distribution @@ -265,46 +300,74 @@ from distutils2._backport.pkgutil import provides_distribution from distutils2.errors import DistutilsError + checkLists = lambda x,y: self.assertListEqual(sorted(x), sorted(y)) + l = [dist.name for dist in provides_distribution('truffles')] - self.assertListEqual(l, ['choxie', 'towel-stuff']) + checkLists(l, ['choxie', 'towel-stuff']) l = [dist.name for dist in provides_distribution('truffles', '1.0')] - self.assertListEqual(l, ['choxie']) + checkLists(l, ['choxie']) + + l = [dist.name for dist in provides_distribution('truffles', '1.0', + use_egg_info=True)] + checkLists(l, ['choxie', 'cheese']) l = [dist.name for dist in provides_distribution('truffles', '1.1.2')] - self.assertListEqual(l, ['towel-stuff']) + checkLists(l, ['towel-stuff']) l = [dist.name for dist in provides_distribution('truffles', '1.1')] - self.assertListEqual(l, ['towel-stuff']) + checkLists(l, ['towel-stuff']) l = [dist.name for dist in provides_distribution('truffles', '!=1.1,<=2.0')] - self.assertListEqual(l, ['choxie']) + checkLists(l, ['choxie']) + + l = [dist.name for dist in provides_distribution('truffles', '!=1.1,<=2.0', + use_egg_info=True)] + checkLists(l, ['choxie', 'bacon', 'cheese']) l = [dist.name for dist in provides_distribution('truffles', '>1.0')] - self.assertListEqual(l, ['towel-stuff']) + checkLists(l, ['towel-stuff']) + + l = [dist.name for dist in provides_distribution('truffles', '>1.5')] + checkLists(l, []) + + l = [dist.name for dist in provides_distribution('truffles', '>1.5', + use_egg_info=True)] + checkLists(l, ['bacon']) l = [dist.name for dist in provides_distribution('truffles', '>=1.0')] - self.assertListEqual(l, ['choxie', 'towel-stuff']) + checkLists(l, ['choxie', 'towel-stuff']) def test_obsoletes(self): """ Test looking for distributions based on what they obsolete """ from distutils2._backport.pkgutil import obsoletes_distribution from distutils2.errors import DistutilsError + checkLists = lambda x,y: self.assertListEqual(sorted(x), sorted(y)) + l = [dist.name for dist in obsoletes_distribution('truffles', '1.0')] - self.assertListEqual(l, []) + checkLists(l, []) + + l = [dist.name for dist in obsoletes_distribution('truffles', '1.0', + use_egg_info=True)] + checkLists(l, ['cheese', 'bacon']) + l = [dist.name for dist in obsoletes_distribution('truffles', '0.8')] - self.assertListEqual(l, ['choxie']) + checkLists(l, ['choxie']) + + l = [dist.name for dist in obsoletes_distribution('truffles', '0.8', + use_egg_info=True)] + checkLists(l, ['choxie', 'cheese']) l = [dist.name for dist in obsoletes_distribution('truffles', '0.9.6')] - self.assertListEqual(l, ['choxie', 'towel-stuff']) + checkLists(l, ['choxie', 'towel-stuff']) l = [dist.name for dist in obsoletes_distribution('truffles', '0.5.2.3')] - self.assertListEqual(l, ['choxie', 'towel-stuff']) + checkLists(l, ['choxie', 'towel-stuff']) l = [dist.name for dist in obsoletes_distribution('truffles', '0.2')] - self.assertListEqual(l, ['towel-stuff']) + checkLists(l, ['towel-stuff']) def test_suite(): -- Repository URL: http://hg.python.org/distutils2 From python-checkins at python.org Mon May 31 01:56:09 2010 From: python-checkins at python.org (tarek.ziade) Date: Mon, 31 May 2010 01:56:09 +0200 Subject: [Python-checkins] distutils2: basic dependency graph builder Message-ID: tarek.ziade pushed 97ff6c99d984 to distutils2: http://hg.python.org/distutils2/rev/97ff6c99d984 changeset: 183:97ff6c99d984 user: Josip Djolonga date: Sun May 30 05:09:35 2010 +0200 summary: basic dependency graph builder files: src/distutils2/_backport/tests/fake_dists/grammar-1.0a4.dist-info/METADATA, src/distutils2/depgraph.py diff --git a/src/distutils2/_backport/tests/fake_dists/grammar-1.0a4.dist-info/METADATA b/src/distutils2/_backport/tests/fake_dists/grammar-1.0a4.dist-info/METADATA --- a/src/distutils2/_backport/tests/fake_dists/grammar-1.0a4.dist-info/METADATA +++ b/src/distutils2/_backport/tests/fake_dists/grammar-1.0a4.dist-info/METADATA @@ -1,3 +1,4 @@ Metadata-Version: 1.2 Name: grammar Version: 1.0a4 +Requires-Dist: truffles (>=1.2) diff --git a/src/distutils2/depgraph.py b/src/distutils2/depgraph.py new file mode 100644 --- /dev/null +++ b/src/distutils2/depgraph.py @@ -0,0 +1,109 @@ +""" +A dependency graph generator. The graph is represented as an instance of +:class:`Graph`, and DOT output is possible as well. +""" + +from distutils2._backport import pkgutil +from distutils2.errors import DistutilsError +from distutils2.version import VersionPredicate + +class Graph: + nodes = [] + adjacency_list = {} + + def __init__(self): + self.nodes = [] + self.adjacency_list = {} + + def add_node(self, x): + self.nodes.append(x) + self.adjacency_list[x] = list() + + def add_edge(self, x, y, label=None): + self.adjacency_list[x].append((y, label)) + + def to_dot(self, f, skip_disconnected = True): + """ Writes a DOT output for the graph to the provided *file* """ + + def dot_escape(x): + return x + + if not isinstance(f, file): + raise TypeError('the argument has to be of type file') + + disconnected = [] + + f.write("digraph dependencies {\n") + for dist, adjs in self.adjacency_list.iteritems(): + if len(adjs) == 0 and not skip_disconnected: + disconnected.append(dist) + for (other, label) in adjs: + if not label is None: + f.write('"%s" -> "%s" [label="%s"]\n' % (dist.name, + other.name, label)) + else: + f.write('"%s" -> "%s"\n' % (dist.name, other.name)) + if not skip_disconnected and len(disconnected) > 0: + f.write('subgraph disconnected {\n') + f.write('label = "Disconnected"\n') + f.write('bgcolor = red\n') + + for dist in disconnected: + f.write('"%s"' % dist.name) + f.write('\n') + f.write('}\n') + f.write('}\n') + +def generate_graph(dists): + graph = Graph() + provided = {} # maps names to lists of (version, dist) tuples + + dists = list(dists) # maybe use generator_tools to copy generators in future + + # first, build the graph and find out the provides + for dist in dists: + graph.add_node(dist) + provides = dist.metadata['Provides-Dist'] + dist.metadata['Provides'] + + for p in provides: + comps = p.split(" ", 1) + name = comps[0] + version = None + if len(comps) == 2: + version = comps[1] + if len(version) < 3 or version[0] != '(' or version[-1] != ')': + raise DistutilsError('Distribution %s has ill formed' \ + 'provides field: %s' % (dist.name, p)) + version = version[1:-1] # trim off parenthesis + if not name in provided: + provided[name] = [] + provided[name].append((version, dist)) + + print provided.keys() + # now make the edges + for dist in dists: + requires = dist.metadata['Requires-Dist'] + dist.metadata['Requires'] + for req in requires: + predicate = VersionPredicate(req) + comps = req.split(" ", 1) + name = comps[0] + label = None # the label for the possible edge + if len(comps) == 2: + label = comps[1] + + if not name in provided: + print('Requirement %s for distribution %s is missing' % \ + (req, dist.name)) + else: + for (version, provider) in provided[name]: + if predicate.match(version): + graph.add_edge(dist, provider, label) + + return graph + +if __name__ == '__main__': + dists = pkgutil.get_distributions(use_egg_info=True) + graph = generate_graph(dists) + f = open('output.dot', 'w') + graph.to_dot(f, False) + -- Repository URL: http://hg.python.org/distutils2 From python-checkins at python.org Mon May 31 01:56:09 2010 From: python-checkins at python.org (tarek.ziade) Date: Mon, 31 May 2010 01:56:09 +0200 Subject: [Python-checkins] distutils2: merged with tarek's code Message-ID: tarek.ziade pushed 7df3a7ac7545 to distutils2: http://hg.python.org/distutils2/rev/7df3a7ac7545 changeset: 184:7df3a7ac7545 parent: 183:97ff6c99d984 parent: 175:644cf5550a05 user: Josip Djolonga date: Sun May 30 05:16:05 2010 +0200 summary: merged with tarek's code files: src/distutils2/tests/test_version.py diff --git a/src/CONTRIBUTORS.txt b/src/CONTRIBUTORS.txt new file mode 100644 --- /dev/null +++ b/src/CONTRIBUTORS.txt @@ -0,0 +1,24 @@ +============ +Contributors +============ + +Distutils2 is a project that was started and that is maintained by +Tarek Ziad??, and many people are contributing to the project. + +If you did, please add your name below in alphabetical order ! + +Thanks to: + +- Pior Bastida +- Titus Brown +- Nicolas Cadou +- Yannick Gringas +- Carl Meyer +- Michael Mulich +- George Peris +- Sean Reifschneider +- Erik Rose +- Brian Rosner +- Alexandre Vassalotti +- Martin von L??wis + diff --git a/src/DEVNOTES.txt b/src/DEVNOTES.txt new file mode 100644 --- /dev/null +++ b/src/DEVNOTES.txt @@ -0,0 +1,10 @@ +Notes for developers +==================== + +- Distutils2 runs from 2.4 to 3.2 (3.x not implemented yet), so + make sure you don't use a syntax that doesn't work under + a specific Python version. + +- Always run tests.sh before you push a change. This implies + that you have all Python versions installed. + diff --git a/src/distutils2/command/sdist.py b/src/distutils2/command/sdist.py --- a/src/distutils2/command/sdist.py +++ b/src/distutils2/command/sdist.py @@ -121,6 +121,7 @@ self.metadata_check = 1 self.owner = None self.group = None + self.filelist = None def _check_archive_formats(self, formats): supported_formats = [name for name, desc in get_archive_formats()] @@ -152,10 +153,14 @@ if self.dist_dir is None: self.dist_dir = "dist" + if self.filelist is None: + self.filelist = Manifest() + + def run(self): # 'filelist' contains the list of files that will make up the # manifest - self.filelist = Manifest() + self.filelist.clear() # Run sub commands for cmd_name in self.get_sub_commands(): @@ -200,7 +205,7 @@ if self.use_defaults: self.add_defaults() if template_exists: - self.read_template() + self.filelist.read_template(self.template) if self.prune: self.prune_file_list() diff --git a/src/distutils2/converter/fixers/fix_imports.py b/src/distutils2/converter/fixers/fix_imports.py --- a/src/distutils2/converter/fixers/fix_imports.py +++ b/src/distutils2/converter/fixers/fix_imports.py @@ -20,6 +20,9 @@ if node.type != syms.import_from: return + if not hasattr(imp, "next_sibling"): + imp.next_sibling = imp.get_next_sibling() + while not hasattr(imp, 'value'): imp = imp.children[0] @@ -34,6 +37,8 @@ next = imp.next_sibling while next is not None: pattern.append(next.value) + if not hasattr(next, "next_sibling"): + next.next_sibling = next.get_next_sibling() next = next.next_sibling if pattern == ['import', 'setup']: imp.value = 'distutils2.core' diff --git a/src/distutils2/converter/fixers/fix_setup_options.py b/src/distutils2/converter/fixers/fix_setup_options.py --- a/src/distutils2/converter/fixers/fix_setup_options.py +++ b/src/distutils2/converter/fixers/fix_setup_options.py @@ -41,6 +41,10 @@ def _fix_name(self, argument, remove_list): name = argument.children[0] + + if not hasattr(name, "next_sibling"): + name.next_sibling = name.get_next_sibling() + sibling = name.next_sibling if sibling is None or sibling.type != token.EQUAL: return False @@ -48,6 +52,8 @@ if name.value in _OLD_NAMES: name.value = _OLD_NAMES[name.value] if name.value in _SEQUENCE_NAMES: + if not hasattr(sibling, "next_sibling"): + sibling.next_sibling = sibling.get_next_sibling() right_operand = sibling.next_sibling # replacing string -> list[string] if right_operand.type == token.STRING: diff --git a/src/distutils2/manifest.py b/src/distutils2/manifest.py --- a/src/distutils2/manifest.py +++ b/src/distutils2/manifest.py @@ -54,6 +54,12 @@ for sort_tuple in sortable_files: self.files.append(os.path.join(*sort_tuple)) + def clear(self): + """Clear all collected files.""" + self.files = [] + if self.allfiles is not None: + self.allfiles = [] + def remove_duplicates(self): # Assumes list has been sorted! for i in range(len(self.files) - 1, 0, -1): diff --git a/src/distutils2/tests/test_converter.py b/src/distutils2/tests/test_converter.py --- a/src/distutils2/tests/test_converter.py +++ b/src/distutils2/tests/test_converter.py @@ -36,4 +36,4 @@ return unittest2.makeSuite(ConverterTestCase) if __name__ == '__main__': - run_unittest(test_suite()) + unittest2.main(defaultTest="test_suite") diff --git a/src/distutils2/tests/test_core.py b/src/distutils2/tests/test_core.py --- a/src/distutils2/tests/test_core.py +++ b/src/distutils2/tests/test_core.py @@ -60,6 +60,19 @@ distutils2.core.run_setup( self.write_setup(setup_using___file__)) + def test_run_setup_stop_after(self): + f = self.write_setup(setup_using___file__) + for s in ['init', 'config', 'commandline', 'run']: + distutils2.core.run_setup(f, stop_after=s) + self.assertRaises(ValueError, distutils2.core.run_setup, + f, stop_after='bob') + + def test_run_setup_args(self): + f = self.write_setup(setup_using___file__) + d = distutils2.core.run_setup(f, script_args=["--help"], + stop_after="init") + self.assertEqual(['--help'], d.script_args) + def test_run_setup_uses_current_dir(self): # This tests that the setup script is run with the current directory # as its own current directory; this was temporarily broken by a diff --git a/src/distutils2/tests/test_sdist.py b/src/distutils2/tests/test_sdist.py --- a/src/distutils2/tests/test_sdist.py +++ b/src/distutils2/tests/test_sdist.py @@ -343,6 +343,19 @@ finally: archive.close() + def test_get_file_list(self): + dist, cmd = self.get_cmd() + cmd.finalize_options() + cmd.template = os.path.join(self.tmp_dir, 'MANIFEST.in') + f = open(cmd.template, 'w') + try: + f.write('include MANIFEST.in\n') + finally: + f.close() + + cmd.get_file_list() + self.assertIn('MANIFEST.in', cmd.filelist.files) + def test_suite(): return unittest2.makeSuite(SDistTestCase) diff --git a/src/runtests.py b/src/runtests.py --- a/src/runtests.py +++ b/src/runtests.py @@ -6,7 +6,7 @@ def test_main(): import distutils2.tests - from distutils2.tests import run_unittest, reap_children + from distutils2.tests import run_unittest, reap_children, TestFailed from distutils2._backport.tests import test_suite as btest_suite # just supporting -q right now # to enable detailed/quiet output @@ -14,10 +14,15 @@ verbose = sys.argv[-1] != '-q' else: verbose = 1 - - run_unittest([distutils2.tests.test_suite(), btest_suite()], - verbose_=verbose) - reap_children() + try: + try: + run_unittest([distutils2.tests.test_suite(), btest_suite()], + verbose_=verbose) + return 0 + except TestFailed: + return 1 + finally: + reap_children() if __name__ == "__main__": try: @@ -26,4 +31,5 @@ print('!!! You need to install unittest2') sys.exit(1) - test_main() + sys.exit(test_main()) + diff --git a/src/tests.sh b/src/tests.sh --- a/src/tests.sh +++ b/src/tests.sh @@ -1,12 +1,28 @@ #!/bin/sh -echo Testing with Python 2.4.... -python2.4 runtests.py -q +echo -n "Running tests for Python 2.4..." +python2.4 runtests.py -q > /dev/null 2> /dev/null +if [ $? -ne 0 ];then + echo "Failed" + exit $1 +else + echo "Success" +fi -echo -echo Testing with Python 2.5.... -python2.5 runtests.py -q +echo -n "Running tests for Python 2.5..." +python2.5 runtests.py -q > /dev/null 2> /dev/null +if [ $? -ne 0 ];then + echo "Failed" + exit $1 +else + echo "Success" +fi -echo -echo Testing with Python 2.6.... -python2.6 runtests.py -q +echo -n "Running tests for Python 2.6..." +python2.6 runtests.py -q > /dev/null 2> /dev/null +if [ $? -ne 0 ];then + echo "Failed" + exit $1 +else + echo "Success" +fi -- Repository URL: http://hg.python.org/distutils2 From python-checkins at python.org Mon May 31 01:56:09 2010 From: python-checkins at python.org (tarek.ziade) Date: Mon, 31 May 2010 01:56:09 +0200 Subject: [Python-checkins] distutils2: added documentation Message-ID: tarek.ziade pushed 15bce7d7578b to distutils2: http://hg.python.org/distutils2/rev/15bce7d7578b changeset: 185:15bce7d7578b user: Josip Djolonga date: Mon May 31 00:17:50 2010 +0200 summary: added documentation files: src/distutils2/depgraph.py diff --git a/src/distutils2/depgraph.py b/src/distutils2/depgraph.py --- a/src/distutils2/depgraph.py +++ b/src/distutils2/depgraph.py @@ -1,33 +1,77 @@ """ A dependency graph generator. The graph is represented as an instance of -:class:`Graph`, and DOT output is possible as well. +:class:`DependencyGraph`, and DOT output is possible as well. """ from distutils2._backport import pkgutil from distutils2.errors import DistutilsError from distutils2.version import VersionPredicate -class Graph: - nodes = [] +__all__ = ['DependencyGraph', 'generate_graph'] + + +class DependencyGraph: + """ + Represents a dependency graph between distributions. + + The depedency relationships are stored in an *adjacency_list* that maps + distributions to a list of ``(other, label)`` tuples where ``other`` + is a distribution and the edge is labelled with ``label`` (i.e. the version + specifier, if such was provided). If any missing depencies are found, + they are stored in ``missing``. It maps distributions to a list of + requirements that were not provided by any other distributions. + """ + adjacency_list = {} + missing = {} # maps distributions to a list of unfulfilled requirements def __init__(self): - self.nodes = [] self.adjacency_list = {} + self.missing = {} - def add_node(self, x): - self.nodes.append(x) - self.adjacency_list[x] = list() + def add_distribution(self, distribution): + """ + Add distribution *x* to the graph. + + :type distribution: :class:`pkgutil.Distribution` or + :class:`pkgutil.EggInfoDistribution` + """ + self.adjacency_list[distribution] = list() + self.missing[distribution] = list() def add_edge(self, x, y, label=None): + """ + Add an edge from distribution *x* to distribution *y* with the given + *label*. + + + :type x: :class:`pkgutil.Distribution` or + :class:`pkgutil.EggInfoDistribution` + :type y: :class:`pkgutil.Distribution` or + :class:`pkgutil.EggInfoDistribution` + :type label: ``str`` or ``None`` + """ self.adjacency_list[x].append((y, label)) + def add_missing(self, distribution, requirement): + """ + Add a missing *requirement* for the given *distribution*. + + :type distribution: :class:`pkgutil.Distribution` or + :class:`pkgutil.EggInfoDistribution` + :type requirement: ``str`` + """ + self.missing[distribution].append(requirement) + def to_dot(self, f, skip_disconnected = True): - """ Writes a DOT output for the graph to the provided *file* """ + """ + Writes a DOT output for the graph to the provided *file*. + If *skip_disconnected* is set to ``True``, then all distributions + that are not dependent on any other distributions are skipped. - def dot_escape(x): - return x - + :type f: ``file`` + ;type skip_disconnected: ``bool`` + """ if not isinstance(f, file): raise TypeError('the argument has to be of type file') @@ -55,14 +99,24 @@ f.write('}\n') def generate_graph(dists): - graph = Graph() + """ + Generates a dependency graph from the given distributions. + + :parameter dists: a list of distributions + :type dists: list of :class:`pkgutil.Distribution` and + :class:`pkgutil.EggInfoDistribution` instances + :rtype: an :class:`DependencyGraph` instance + """ + graph = DependencyGraph() provided = {} # maps names to lists of (version, dist) tuples dists = list(dists) # maybe use generator_tools to copy generators in future + missing = [] # a list of (instance, requirement) tuples + # first, build the graph and find out the provides for dist in dists: - graph.add_node(dist) + graph.add_distribution(dist) provides = dist.metadata['Provides-Dist'] + dist.metadata['Provides'] for p in provides: @@ -79,7 +133,6 @@ provided[name] = [] provided[name].append((version, dist)) - print provided.keys() # now make the edges for dist in dists: requires = dist.metadata['Requires-Dist'] + dist.metadata['Requires'] @@ -87,23 +140,47 @@ predicate = VersionPredicate(req) comps = req.split(" ", 1) name = comps[0] - label = None # the label for the possible edge - if len(comps) == 2: - label = comps[1] if not name in provided: - print('Requirement %s for distribution %s is missing' % \ - (req, dist.name)) + graph.add_missing(dist, req) else: for (version, provider) in provided[name]: if predicate.match(version): - graph.add_edge(dist, provider, label) + graph.add_edge(dist, provider, req) return graph +def dependent_dists(dists, dist): + """ + Recursively generate a list of distributions from *dists* that are dependent + on *dist*. + + :param dists: a list of distributions + :param dist: a distribution, member of *dists* for which we are interested + """ + if not dist in dists: + raise ValueError('The given distribution is not a member of the list') + graph = generate_graph(dists) + + dep = [dist] + fringe = [dist] # list of nodes we should expand + while not len(fringe) == 0: + next = graph.adjacency_list[fringe.pop()] + for (dist, label) in next: + if not dist in dep: # avoid infinite loops + dep.append(dist) + fringe.append(dist) + + dep.pop() + return dep + if __name__ == '__main__': - dists = pkgutil.get_distributions(use_egg_info=True) + dists = list(pkgutil.get_distributions(use_egg_info=True)) graph = generate_graph(dists) + for dist, reqs in graph.missing.iteritems(): + if len(reqs) > 0: + print("Missing dependencies for %s: %s" % (dist.name, + ", ".join(reqs))) f = open('output.dot', 'w') - graph.to_dot(f, False) + graph.to_dot(f, True) -- Repository URL: http://hg.python.org/distutils2 From python-checkins at python.org Mon May 31 01:56:09 2010 From: python-checkins at python.org (tarek.ziade) Date: Mon, 31 May 2010 01:56:09 +0200 Subject: [Python-checkins] distutils2: added myself to the contributors list Message-ID: tarek.ziade pushed 48f3b9a445da to distutils2: http://hg.python.org/distutils2/rev/48f3b9a445da changeset: 187:48f3b9a445da user: Josip Djolonga date: Mon May 31 01:44:36 2010 +0200 summary: added myself to the contributors list files: src/CONTRIBUTORS.txt diff --git a/src/CONTRIBUTORS.txt b/src/CONTRIBUTORS.txt --- a/src/CONTRIBUTORS.txt +++ b/src/CONTRIBUTORS.txt @@ -12,6 +12,7 @@ - Pior Bastida - Titus Brown - Nicolas Cadou +- Josip Djolonga - Yannick Gringas - Carl Meyer - Michael Mulich -- Repository URL: http://hg.python.org/distutils2 From python-checkins at python.org Mon May 31 01:56:09 2010 From: python-checkins at python.org (tarek.ziade) Date: Mon, 31 May 2010 01:56:09 +0200 Subject: [Python-checkins] distutils2: removed unused variable Message-ID: tarek.ziade pushed b7fd258b33e7 to distutils2: http://hg.python.org/distutils2/rev/b7fd258b33e7 changeset: 188:b7fd258b33e7 tag: tip user: Tarek Ziade date: Mon May 31 01:55:09 2010 +0200 summary: removed unused variable files: src/distutils2/depgraph.py diff --git a/src/distutils2/depgraph.py b/src/distutils2/depgraph.py --- a/src/distutils2/depgraph.py +++ b/src/distutils2/depgraph.py @@ -107,11 +107,8 @@ """ graph = DependencyGraph() provided = {} # maps names to lists of (version, dist) tuples - dists = list(dists) # maybe use generator_tools in future - missing = [] # a list of (instance, requirement) tuples - # first, build the graph and find out the provides for dist in dists: graph.add_distribution(dist) -- Repository URL: http://hg.python.org/distutils2 From python-checkins at python.org Mon May 31 01:56:09 2010 From: python-checkins at python.org (tarek.ziade) Date: Mon, 31 May 2010 01:56:09 +0200 Subject: [Python-checkins] distutils2: small changes, PEP8 compliance Message-ID: tarek.ziade pushed f75c222e1b04 to distutils2: http://hg.python.org/distutils2/rev/f75c222e1b04 changeset: 186:f75c222e1b04 user: Josip Djolonga date: Mon May 31 01:43:44 2010 +0200 summary: small changes, PEP8 compliance files: src/distutils2/_backport/pkgutil.py, src/distutils2/depgraph.py diff --git a/src/distutils2/_backport/pkgutil.py b/src/distutils2/_backport/pkgutil.py --- a/src/distutils2/_backport/pkgutil.py +++ b/src/distutils2/_backport/pkgutil.py @@ -22,6 +22,7 @@ 'provides_distribution', 'obsoletes_distribution', ] + def read_code(stream): # This helper is needed in order for the PEP 302 emulation to # correctly handle compiled files @@ -38,6 +39,7 @@ def simplegeneric(func): """Make a trivial single-dispatch generic function""" registry = {} + def wrapper(*args, **kw): ob = args[0] try: @@ -48,6 +50,7 @@ mro = cls.__mro__ except AttributeError: try: + class cls(cls, object): pass mro = cls.__mro__[1:] @@ -129,7 +132,7 @@ # don't traverse path items we've seen before path = [p for p in path if not seen(p)] - for item in walk_packages(path, name+'.', onerror): + for item in walk_packages(path, name + '.', onerror): yield item @@ -207,7 +210,7 @@ for fn in filenames: modname = inspect.getmodulename(fn) - if modname=='__init__' or modname in yielded: + if modname == '__init__' or modname in yielded: continue path = os.path.join(self.path, fn) @@ -217,7 +220,7 @@ modname = fn for fn in os.listdir(path): subname = inspect.getmodulename(fn) - if subname=='__init__': + if subname == '__init__': ispkg = True break else: @@ -256,7 +259,7 @@ def _reopen(self): if self.file and self.file.closed: mod_type = self.etc[2] - if mod_type==imp.PY_SOURCE: + if mod_type == imp.PY_SOURCE: self.file = open(self.filename, 'rU') elif mod_type in (imp.PY_COMPILED, imp.C_EXTENSION): self.file = open(self.filename, 'rb') @@ -271,22 +274,22 @@ def is_package(self, fullname): fullname = self._fix_name(fullname) - return self.etc[2]==imp.PKG_DIRECTORY + return self.etc[2] == imp.PKG_DIRECTORY def get_code(self, fullname=None): fullname = self._fix_name(fullname) if self.code is None: mod_type = self.etc[2] - if mod_type==imp.PY_SOURCE: + if mod_type == imp.PY_SOURCE: source = self.get_source(fullname) self.code = compile(source, self.filename, 'exec') - elif mod_type==imp.PY_COMPILED: + elif mod_type == imp.PY_COMPILED: self._reopen() try: self.code = read_code(self.file) finally: self.file.close() - elif mod_type==imp.PKG_DIRECTORY: + elif mod_type == imp.PKG_DIRECTORY: self.code = self._get_delegate().get_code() return self.code @@ -294,29 +297,28 @@ fullname = self._fix_name(fullname) if self.source is None: mod_type = self.etc[2] - if mod_type==imp.PY_SOURCE: + if mod_type == imp.PY_SOURCE: self._reopen() try: self.source = self.file.read() finally: self.file.close() - elif mod_type==imp.PY_COMPILED: + elif mod_type == imp.PY_COMPILED: if os.path.exists(self.filename[:-1]): f = open(self.filename[:-1], 'rU') self.source = f.read() f.close() - elif mod_type==imp.PKG_DIRECTORY: + elif mod_type == imp.PKG_DIRECTORY: self.source = self._get_delegate().get_source() return self.source - def _get_delegate(self): return ImpImporter(self.filename).find_module('__init__') def get_filename(self, fullname=None): fullname = self._fix_name(fullname) mod_type = self.etc[2] - if self.etc[2]==imp.PKG_DIRECTORY: + if self.etc[2] == imp.PKG_DIRECTORY: return self._get_delegate().get_filename() elif self.etc[2] in (imp.PY_SOURCE, imp.PY_COMPILED, imp.C_EXTENSION): return self.filename @@ -340,16 +342,16 @@ fn = fn[plen:].split(os.sep) - if len(fn)==2 and fn[1].startswith('__init__.py'): + if len(fn) == 2 and fn[1].startswith('__init__.py'): if fn[0] not in yielded: yielded[fn[0]] = 1 yield fn[0], True - if len(fn)!=1: + if len(fn) != 1: continue modname = inspect.getmodulename(fn[0]) - if modname=='__init__': + if modname == '__init__': continue if modname and '.' not in modname and modname not in yielded: @@ -437,6 +439,7 @@ if '.' not in fullname: yield ImpImporter() + def get_loader(module_or_name): """Get a PEP 302 "loader" object for module_or_name @@ -462,6 +465,7 @@ fullname = module_or_name return find_loader(fullname) + def find_loader(fullname): """Find a PEP 302 "loader" object for fullname @@ -552,6 +556,7 @@ return path + def get_data(package, resource): """Get a resource from a package. @@ -595,6 +600,7 @@ DIST_FILES = ('INSTALLER', 'METADATA', 'RECORD', 'REQUESTED',) + class Distribution(object): """Created with the *path* of the ``.dist-info`` directory provided to the constructor. It reads the metadata contained in METADATA when it is @@ -621,7 +627,7 @@ RECORD = os.path.join(self.path, 'RECORD') record_reader = csv_reader(open(RECORD, 'rb'), delimiter=',') for row in record_reader: - path, md5, size = row[:] + [ None for i in xrange(len(row), 3) ] + path, md5, size = row[:] + [None for i in xrange(len(row), 3)] if local: path = path.replace('/', os.sep) path = os.path.join(sys.prefix, path) @@ -636,7 +642,6 @@ A local absolute path is an absolute path in which occurrences of ``'/'`` have been replaced by the system separator given by ``os.sep``. - :parameter local: flag to say if the path should be returned a local absolute path :type local: boolean @@ -644,7 +649,6 @@ """ return self._get_records(local) - def uses(self, path): """ Returns ``True`` if path is listed in RECORD. *path* can be a local @@ -664,8 +668,8 @@ ``file`` instance for the file pointed by *path*. :parameter path: a ``'/'``-separated path relative to the ``.dist-info`` - directory or an absolute path; If *path* is an absolute - path and doesn't start with the ``.dist-info`` + directory or an absolute path; If *path* is an + absolute path and doesn't start with the ``.dist-info`` directory path, a :class:`DistutilsError` is raised :type path: string :parameter binary: If *binary* is ``True``, opens the file in read-only @@ -710,7 +714,8 @@ for path, md5, size in self._get_records(local): yield path -class EggInfoDistribution: + +class EggInfoDistribution(object): """Created with the *path* of the ``.egg-info`` directory or file provided to the constructor. It reads the metadata contained in the file itself, or if the given path happens to be a directory, the metadata is read from the @@ -734,11 +739,13 @@ def uses(self, path): return False + def _normalize_dist_name(name): """Returns a normalized name from the given *name*. :rtype: string""" return name.replace('-', '_') + def distinfo_dirname(name, version): """ The *name* and *version* parameters are converted into their @@ -767,7 +774,8 @@ normalized_version = version return '-'.join([name, normalized_version]) + file_extension -def get_distributions(use_egg_info = False): + +def get_distributions(use_egg_info=False): """ Provides an iterator that looks for ``.dist-info`` directories in ``sys.path`` and returns :class:`Distribution` instances for each one of @@ -788,7 +796,8 @@ dist = EggInfoDistribution(os.path.join(realpath, dir)) yield dist -def get_distribution(name, use_egg_info = False): + +def get_distribution(name, use_egg_info=False): """ Scans all elements in ``sys.path`` and looks for all directories ending with ``.dist-info``. Returns a :class:`Distribution` corresponding to the @@ -816,7 +825,8 @@ break return found -def obsoletes_distribution(name, version=None, use_egg_info = False): + +def obsoletes_distribution(name, version=None, use_egg_info=False): """ Iterates over all distributions to find which distributions obsolete *name*. If a *version* is provided, it will be used to filter the results. @@ -845,7 +855,8 @@ yield dist break -def provides_distribution(name, version=None, use_egg_info = False): + +def provides_distribution(name, version=None, use_egg_info=False): """ Iterates over all distributions to find which distributions provide *name*. If a *version* is provided, it will be used to filter the results. Scans @@ -891,6 +902,7 @@ yield dist break + def get_file_users(path): """ Iterates over all distributions to find out which distributions uses @@ -903,4 +915,3 @@ for dist in get_distributions(): if dist.uses(path): yield dist - diff --git a/src/distutils2/depgraph.py b/src/distutils2/depgraph.py --- a/src/distutils2/depgraph.py +++ b/src/distutils2/depgraph.py @@ -10,7 +10,7 @@ __all__ = ['DependencyGraph', 'generate_graph'] -class DependencyGraph: +class DependencyGraph(object): """ Represents a dependency graph between distributions. @@ -22,9 +22,6 @@ requirements that were not provided by any other distributions. """ - adjacency_list = {} - missing = {} # maps distributions to a list of unfulfilled requirements - def __init__(self): self.adjacency_list = {} self.missing = {} @@ -63,7 +60,7 @@ """ self.missing[distribution].append(requirement) - def to_dot(self, f, skip_disconnected = True): + def to_dot(self, f, skip_disconnected=True): """ Writes a DOT output for the graph to the provided *file*. If *skip_disconnected* is set to ``True``, then all distributions @@ -83,8 +80,8 @@ disconnected.append(dist) for (other, label) in adjs: if not label is None: - f.write('"%s" -> "%s" [label="%s"]\n' % (dist.name, - other.name, label)) + f.write('"%s" -> "%s" [label="%s"]\n' % + (dist.name, other.name, label)) else: f.write('"%s" -> "%s"\n' % (dist.name, other.name)) if not skip_disconnected and len(disconnected) > 0: @@ -98,6 +95,7 @@ f.write('}\n') f.write('}\n') + def generate_graph(dists): """ Generates a dependency graph from the given distributions. @@ -110,7 +108,7 @@ graph = DependencyGraph() provided = {} # maps names to lists of (version, dist) tuples - dists = list(dists) # maybe use generator_tools to copy generators in future + dists = list(dists) # maybe use generator_tools in future missing = [] # a list of (instance, requirement) tuples @@ -150,10 +148,11 @@ return graph + def dependent_dists(dists, dist): """ - Recursively generate a list of distributions from *dists* that are dependent - on *dist*. + Recursively generate a list of distributions from *dists* that are + dependent on *dist*. :param dists: a list of distributions :param dist: a distribution, member of *dists* for which we are interested @@ -183,4 +182,3 @@ ", ".join(reqs))) f = open('output.dot', 'w') graph.to_dot(f, True) - -- Repository URL: http://hg.python.org/distutils2 From python-checkins at python.org Mon May 31 09:33:54 2010 From: python-checkins at python.org (martin.v.loewis) Date: Mon, 31 May 2010 09:33:54 +0200 (CEST) Subject: [Python-checkins] r81615 - peps/trunk/pep-0382.txt Message-ID: <20100531073354.25336EE98F@mail.python.org> Author: martin.v.loewis Date: Mon May 31 09:33:53 2010 New Revision: 81615 Log: Keep precedence for directories. Noticed by Brett Cannon. Modified: peps/trunk/pep-0382.txt Modified: peps/trunk/pep-0382.txt ============================================================================== --- peps/trunk/pep-0382.txt (original) +++ peps/trunk/pep-0382.txt Mon May 31 09:33:53 2010 @@ -119,7 +119,7 @@ this: 1. sys.path is search for a directory foo, or a file foo.. - If a file is found, it is treated as a module, and imported. + If a file is found and no directory, it is treated as a module, and imported. 2. if it is a directory, it checks for \*.pth files. If it finds any, a package is created, and its __path__ is extended. 3. The __init__ module is imported; this import will search the From python-checkins at python.org Mon May 31 09:47:31 2010 From: python-checkins at python.org (martin.v.loewis) Date: Mon, 31 May 2010 09:47:31 +0200 (CEST) Subject: [Python-checkins] r81616 - peps/trunk/pep-0382.txt Message-ID: <20100531074731.3B2B3EE98F@mail.python.org> Author: martin.v.loewis Date: Mon May 31 09:47:31 2010 New Revision: 81616 Log: Clarify * for subpackages. Modified: peps/trunk/pep-0382.txt Modified: peps/trunk/pep-0382.txt ============================================================================== --- peps/trunk/pep-0382.txt (original) +++ peps/trunk/pep-0382.txt Mon May 31 09:47:31 2010 @@ -102,7 +102,8 @@ In addition, the format of the ``*.pth`` file is extended: a line with the single character ``*`` indicates that the entire sys.path will be searched for portions of the namespace package at the time the -namespace packages is imported. +namespace packages is imported. For a sub-package, the package's +__path__ is searched (instead of sys.path). Importing a package will immediately compute the package's __path__; the ``*.pth`` files are not considered anymore after the initial From python-checkins at python.org Mon May 31 15:45:53 2010 From: python-checkins at python.org (tarek.ziade) Date: Mon, 31 May 2010 15:45:53 +0200 (CEST) Subject: [Python-checkins] r81617 - peps/trunk/pep-0345.txt Message-ID: <20100531134553.C612FEE9FB@mail.python.org> Author: tarek.ziade Date: Mon May 31 15:45:53 2010 New Revision: 81617 Log: make sure Name (Version) is what is added in Provides-Dist Modified: peps/trunk/pep-0345.txt Modified: peps/trunk/pep-0345.txt ============================================================================== --- peps/trunk/pep-0345.txt (original) +++ peps/trunk/pep-0345.txt Mon May 31 15:45:53 2010 @@ -291,7 +291,8 @@ Each entry contains a string naming a Distutils project which is contained within this distribution. This field *must* include -the project identified in the ``Name`` field. +the project identified in the ``Name`` field, followed by the +version : Name (Version). A distribution may provide additional names, e.g. to indicate that multiple projects have been bundled together. For instance, source From python-checkins at python.org Mon May 31 18:00:35 2010 From: python-checkins at python.org (alexander.belopolsky) Date: Mon, 31 May 2010 18:00:35 +0200 (CEST) Subject: [Python-checkins] r81618 - in python/branches/release26-maint: Lib/test/test_datetime.py Message-ID: <20100531160035.0FD33EF32@mail.python.org> Author: alexander.belopolsky Date: Mon May 31 18:00:34 2010 New Revision: 81618 Log: Merged revisions 81555 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r81555 | alexander.belopolsky | 2010-05-26 15:43:16 -0400 (Wed, 26 May 2010) | 3 lines Issue #7879: Do not test negative timestamps on any Windows platform including Windows CE. ........ Modified: python/branches/release26-maint/ (props changed) python/branches/release26-maint/Lib/test/test_datetime.py Modified: python/branches/release26-maint/Lib/test/test_datetime.py ============================================================================== --- python/branches/release26-maint/Lib/test/test_datetime.py (original) +++ python/branches/release26-maint/Lib/test/test_datetime.py Mon May 31 18:00:34 2010 @@ -3,7 +3,7 @@ See http://www.zope.org/Members/fdrake/DateTimeWiki/TestCases """ -import os +import sys import pickle import cPickle import unittest @@ -1503,7 +1503,7 @@ def test_negative_float_fromtimestamp(self): # Windows doesn't accept negative timestamps - if os.name == "nt": + if sys.platform == "win32": return # The result is tz-dependent; at least test that this doesn't # fail (like it did before bug 1646728 was fixed). @@ -1511,7 +1511,7 @@ def test_negative_float_utcfromtimestamp(self): # Windows doesn't accept negative timestamps - if os.name == "nt": + if sys.platform == "win32": return d = self.theclass.utcfromtimestamp(-1.05) self.assertEquals(d, self.theclass(1969, 12, 31, 23, 59, 58, 950000)) From python-checkins at python.org Mon May 31 18:11:22 2010 From: python-checkins at python.org (alexander.belopolsky) Date: Mon, 31 May 2010 18:11:22 +0200 (CEST) Subject: [Python-checkins] r81619 - in python/branches/release31-maint: Lib/test/test_datetime.py Message-ID: <20100531161122.14E05EE983@mail.python.org> Author: alexander.belopolsky Date: Mon May 31 18:11:21 2010 New Revision: 81619 Log: Merged revisions 81556 via svnmerge from svn+ssh://pythondev at svn.python.org/python/branches/py3k ................ r81556 | alexander.belopolsky | 2010-05-26 16:00:12 -0400 (Wed, 26 May 2010) | 10 lines Merged revisions 81555 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r81555 | alexander.belopolsky | 2010-05-26 15:43:16 -0400 (Wed, 26 May 2010) | 3 lines Issue #7879: Do not test negative timestamps on any Windows platform including Windows CE. ........ ................ Modified: python/branches/release31-maint/ (props changed) python/branches/release31-maint/Lib/test/test_datetime.py Modified: python/branches/release31-maint/Lib/test/test_datetime.py ============================================================================== --- python/branches/release31-maint/Lib/test/test_datetime.py (original) +++ python/branches/release31-maint/Lib/test/test_datetime.py Mon May 31 18:11:21 2010 @@ -3,7 +3,7 @@ See http://www.zope.org/Members/fdrake/DateTimeWiki/TestCases """ -import os +import sys import pickle import unittest @@ -1496,7 +1496,7 @@ def test_negative_float_fromtimestamp(self): # Windows doesn't accept negative timestamps - if os.name == "nt": + if sys.platform == "win32": return # The result is tz-dependent; at least test that this doesn't # fail (like it did before bug 1646728 was fixed). @@ -1504,7 +1504,7 @@ def test_negative_float_utcfromtimestamp(self): # Windows doesn't accept negative timestamps - if os.name == "nt": + if sys.platform == "win32": return d = self.theclass.utcfromtimestamp(-1.05) self.assertEquals(d, self.theclass(1969, 12, 31, 23, 59, 58, 950000)) From python-checkins at python.org Mon May 31 18:21:02 2010 From: python-checkins at python.org (alexander.belopolsky) Date: Mon, 31 May 2010 18:21:02 +0200 (CEST) Subject: [Python-checkins] r81620 - in python/branches/release31-maint: Lib/test/test_datetime.py Message-ID: <20100531162102.538EAEEB31@mail.python.org> Author: alexander.belopolsky Date: Mon May 31 18:21:02 2010 New Revision: 81620 Log: Merged revisions 81560 via svnmerge from svn+ssh://pythondev at svn.python.org/python/branches/py3k ................ r81560 | alexander.belopolsky | 2010-05-26 16:48:30 -0400 (Wed, 26 May 2010) | 10 lines Merged revisions 81559 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r81559 | alexander.belopolsky | 2010-05-26 16:45:37 -0400 (Wed, 26 May 2010) | 3 lines Issue #7879: Skip negative timestamps test on any Windows platform using unittest.skipIf decorator. ........ ................ Modified: python/branches/release31-maint/ (props changed) python/branches/release31-maint/Lib/test/test_datetime.py Modified: python/branches/release31-maint/Lib/test/test_datetime.py ============================================================================== --- python/branches/release31-maint/Lib/test/test_datetime.py (original) +++ python/branches/release31-maint/Lib/test/test_datetime.py Mon May 31 18:21:02 2010 @@ -1493,19 +1493,14 @@ for insane in -1e200, 1e200: self.assertRaises(ValueError, self.theclass.utcfromtimestamp, insane) - + @unittest.skipIf(sys.platform == "win32", "Windows doesn't accept negative timestamps") def test_negative_float_fromtimestamp(self): - # Windows doesn't accept negative timestamps - if sys.platform == "win32": - return # The result is tz-dependent; at least test that this doesn't # fail (like it did before bug 1646728 was fixed). self.theclass.fromtimestamp(-1.05) + @unittest.skipIf(sys.platform == "win32", "Windows doesn't accept negative timestamps") def test_negative_float_utcfromtimestamp(self): - # Windows doesn't accept negative timestamps - if sys.platform == "win32": - return d = self.theclass.utcfromtimestamp(-1.05) self.assertEquals(d, self.theclass(1969, 12, 31, 23, 59, 58, 950000)) From python-checkins at python.org Mon May 31 19:01:01 2010 From: python-checkins at python.org (antoine.pitrou) Date: Mon, 31 May 2010 19:01:01 +0200 (CEST) Subject: [Python-checkins] r81621 - python/trunk/Doc/library/socket.rst Message-ID: <20100531170101.911FFEE9AA@mail.python.org> Author: antoine.pitrou Date: Mon May 31 19:01:01 2010 New Revision: 81621 Log: Improve documentation for getaddrinfo() (part of #8857) Modified: python/trunk/Doc/library/socket.rst Modified: python/trunk/Doc/library/socket.rst ============================================================================== --- python/trunk/Doc/library/socket.rst (original) +++ python/trunk/Doc/library/socket.rst Mon May 31 19:01:01 2010 @@ -223,26 +223,44 @@ *source_address* was added. -.. function:: getaddrinfo(host, port[, family[, socktype[, proto[, flags]]]]) +.. function:: getaddrinfo(host, port, family=0, socktype=0, proto=0, flags=0) - Resolves the *host*/*port* argument, into a sequence of 5-tuples that contain - all the necessary arguments for creating the corresponding socket. *host* is a domain - name, a string representation of an IPv4/v6 address or ``None``. *port* is a string - service name such as ``'http'``, a numeric port number or ``None``. - The rest of the arguments are optional and must be numeric if specified. - By passing ``None`` as the value of *host* and *port*, , you can pass ``NULL`` to the C API. + Translate the *host*/*port* argument into a sequence of 5-tuples that contain + all the necessary arguments for creating a socket connected to that service. + *host* is a domain name, a string representation of an IPv4/v6 address + or ``None``. *port* is a string service name such as ``'http'``, a numeric + port number or ``None``. By passing ``None`` as the value of *host* + and *port*, you can pass ``NULL`` to the underlying C API. + + The *family*, *socktype* and *proto* arguments can be optionally specified + in order to narrow the list of addresses returned. Passing zero as a + value for each of these arguments selects the full range of results. + The *flags* argument can be one or several of the ``AI_*`` constants, + and will influence how results are computed and returned. + For example, :const:`AI_NUMERICHOST` will disable domain name resolution + and will raise an error if *host* is a domain name. - The :func:`getaddrinfo` function returns a list of 5-tuples with the following - structure: + The function returns a list of 5-tuples with the following structure: ``(family, socktype, proto, canonname, sockaddr)`` - *family*, *socktype*, *proto* are all integers and are meant to be passed to the - :func:`socket` function. *canonname* is a string representing the canonical name - of the *host*. It can be a numeric IPv4/v6 address when :const:`AI_CANONNAME` is - specified for a numeric *host*. *sockaddr* is a tuple describing a socket - address, as described above. See the source for :mod:`socket` and other - library modules for a typical usage of the function. + In these tuples, *family*, *socktype*, *proto* are all integers and are + meant to be passed to the :func:`socket` function. *canonname* will be + a string representing the canonical name of the *host* if + :const:`AI_CANONNAME` is part of the *flags* argument; else *canonname* + will be empty. *sockaddr* is a tuple describing a socket address, whose + format depends on the returned *family* (a ``(address, port)`` 2-tuple for + :const:`AF_INET`, a ``(address, port, flow info, scope id)`` 4-tuple for + :const:`AF_INET6`), and is meant to be passed to the :meth:`socket.connect` + method. + + The following example fetches address information for a hypothetical TCP + connection to ``www.python.org`` on port 80 (results may differ on your + system if IPv6 isn't enabled):: + + >>> socket.getaddrinfo("www.python.org", 80, 0, 0, socket.SOL_TCP) + [(2, 1, 6, '', ('82.94.164.162', 80)), + (10, 1, 6, '', ('2001:888:2000:d::a2', 80, 0, 0))] .. versionadded:: 2.2 From python-checkins at python.org Mon May 31 19:02:35 2010 From: python-checkins at python.org (antoine.pitrou) Date: Mon, 31 May 2010 19:02:35 +0200 (CEST) Subject: [Python-checkins] r81622 - in python/branches/release26-maint: Doc/library/socket.rst Message-ID: <20100531170235.B0C22EE9C3@mail.python.org> Author: antoine.pitrou Date: Mon May 31 19:02:35 2010 New Revision: 81622 Log: Merged revisions 81621 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r81621 | antoine.pitrou | 2010-05-31 19:01:01 +0200 (lun., 31 mai 2010) | 4 lines Improve documentation for getaddrinfo() (part of #8857) ........ Modified: python/branches/release26-maint/ (props changed) python/branches/release26-maint/Doc/library/socket.rst Modified: python/branches/release26-maint/Doc/library/socket.rst ============================================================================== --- python/branches/release26-maint/Doc/library/socket.rst (original) +++ python/branches/release26-maint/Doc/library/socket.rst Mon May 31 19:02:35 2010 @@ -216,26 +216,44 @@ .. versionadded:: 2.6 -.. function:: getaddrinfo(host, port[, family[, socktype[, proto[, flags]]]]) +.. function:: getaddrinfo(host, port, family=0, socktype=0, proto=0, flags=0) - Resolves the *host*/*port* argument, into a sequence of 5-tuples that contain - all the necessary arguments for creating the corresponding socket. *host* is a domain - name, a string representation of an IPv4/v6 address or ``None``. *port* is a string - service name such as ``'http'``, a numeric port number or ``None``. - The rest of the arguments are optional and must be numeric if specified. - By passing ``None`` as the value of *host* and *port*, , you can pass ``NULL`` to the C API. + Translate the *host*/*port* argument into a sequence of 5-tuples that contain + all the necessary arguments for creating a socket connected to that service. + *host* is a domain name, a string representation of an IPv4/v6 address + or ``None``. *port* is a string service name such as ``'http'``, a numeric + port number or ``None``. By passing ``None`` as the value of *host* + and *port*, you can pass ``NULL`` to the underlying C API. + + The *family*, *socktype* and *proto* arguments can be optionally specified + in order to narrow the list of addresses returned. Passing zero as a + value for each of these arguments selects the full range of results. + The *flags* argument can be one or several of the ``AI_*`` constants, + and will influence how results are computed and returned. + For example, :const:`AI_NUMERICHOST` will disable domain name resolution + and will raise an error if *host* is a domain name. - The :func:`getaddrinfo` function returns a list of 5-tuples with the following - structure: + The function returns a list of 5-tuples with the following structure: ``(family, socktype, proto, canonname, sockaddr)`` - *family*, *socktype*, *proto* are all integers and are meant to be passed to the - :func:`socket` function. *canonname* is a string representing the canonical name - of the *host*. It can be a numeric IPv4/v6 address when :const:`AI_CANONNAME` is - specified for a numeric *host*. *sockaddr* is a tuple describing a socket - address, as described above. See the source for :mod:`socket` and other - library modules for a typical usage of the function. + In these tuples, *family*, *socktype*, *proto* are all integers and are + meant to be passed to the :func:`socket` function. *canonname* will be + a string representing the canonical name of the *host* if + :const:`AI_CANONNAME` is part of the *flags* argument; else *canonname* + will be empty. *sockaddr* is a tuple describing a socket address, whose + format depends on the returned *family* (a ``(address, port)`` 2-tuple for + :const:`AF_INET`, a ``(address, port, flow info, scope id)`` 4-tuple for + :const:`AF_INET6`), and is meant to be passed to the :meth:`socket.connect` + method. + + The following example fetches address information for a hypothetical TCP + connection to ``www.python.org`` on port 80 (results may differ on your + system if IPv6 isn't enabled):: + + >>> socket.getaddrinfo("www.python.org", 80, 0, 0, socket.SOL_TCP) + [(2, 1, 6, '', ('82.94.164.162', 80)), + (10, 1, 6, '', ('2001:888:2000:d::a2', 80, 0, 0))] .. versionadded:: 2.2 From python-checkins at python.org Mon May 31 19:04:40 2010 From: python-checkins at python.org (antoine.pitrou) Date: Mon, 31 May 2010 19:04:40 +0200 (CEST) Subject: [Python-checkins] r81623 - in python/branches/py3k: Doc/library/socket.rst Message-ID: <20100531170440.42724EE9AA@mail.python.org> Author: antoine.pitrou Date: Mon May 31 19:04:40 2010 New Revision: 81623 Log: Merged revisions 81621 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r81621 | antoine.pitrou | 2010-05-31 19:01:01 +0200 (lun., 31 mai 2010) | 4 lines Improve documentation for getaddrinfo() (part of #8857) ........ Modified: python/branches/py3k/ (props changed) python/branches/py3k/Doc/library/socket.rst Modified: python/branches/py3k/Doc/library/socket.rst ============================================================================== --- python/branches/py3k/Doc/library/socket.rst (original) +++ python/branches/py3k/Doc/library/socket.rst Mon May 31 19:04:40 2010 @@ -211,27 +211,44 @@ *source_address* was added. -.. function:: getaddrinfo(host, port[, family[, socktype[, proto[, flags]]]]) +.. function:: getaddrinfo(host, port, family=0, socktype=0, proto=0, flags=0) - Resolves the *host*/*port* argument, into a sequence of 5-tuples that contain - all the necessary arguments for creating the corresponding socket. *host* is a domain - name, a string representation of an IPv4/v6 address or ``None``. *port* is a string - service name such as ``'http'``, a numeric port number or ``None``. - The rest of the arguments are optional and must be numeric if specified. - By passing ``None`` as the value of *host* and *port*, , you can pass ``NULL`` to the C API. + Translate the *host*/*port* argument into a sequence of 5-tuples that contain + all the necessary arguments for creating a socket connected to that service. + *host* is a domain name, a string representation of an IPv4/v6 address + or ``None``. *port* is a string service name such as ``'http'``, a numeric + port number or ``None``. By passing ``None`` as the value of *host* + and *port*, you can pass ``NULL`` to the underlying C API. + + The *family*, *socktype* and *proto* arguments can be optionally specified + in order to narrow the list of addresses returned. Passing zero as a + value for each of these arguments selects the full range of results. + The *flags* argument can be one or several of the ``AI_*`` constants, + and will influence how results are computed and returned. + For example, :const:`AI_NUMERICHOST` will disable domain name resolution + and will raise an error if *host* is a domain name. - The :func:`getaddrinfo` function returns a list of 5-tuples with the following - structure: + The function returns a list of 5-tuples with the following structure: ``(family, socktype, proto, canonname, sockaddr)`` - *family*, *socktype*, *proto* are all integers and are meant to be passed to the - :func:`socket` function. *canonname* is a string representing the canonical name - of the *host*. It can be a numeric IPv4/v6 address when :const:`AI_CANONNAME` is - specified for a numeric *host*. *sockaddr* is a tuple describing a socket - address, as described above. See the source for :mod:`socket` and other - library modules for a typical usage of the function. - + In these tuples, *family*, *socktype*, *proto* are all integers and are + meant to be passed to the :func:`socket` function. *canonname* will be + a string representing the canonical name of the *host* if + :const:`AI_CANONNAME` is part of the *flags* argument; else *canonname* + will be empty. *sockaddr* is a tuple describing a socket address, whose + format depends on the returned *family* (a ``(address, port)`` 2-tuple for + :const:`AF_INET`, a ``(address, port, flow info, scope id)`` 4-tuple for + :const:`AF_INET6`), and is meant to be passed to the :meth:`socket.connect` + method. + + The following example fetches address information for a hypothetical TCP + connection to ``www.python.org`` on port 80 (results may differ on your + system if IPv6 isn't enabled):: + + >>> socket.getaddrinfo("www.python.org", 80, 0, 0, socket.SOL_TCP) + [(2, 1, 6, '', ('82.94.164.162', 80)), + (10, 1, 6, '', ('2001:888:2000:d::a2', 80, 0, 0))] .. function:: getfqdn([name]) From python-checkins at python.org Mon May 31 19:06:44 2010 From: python-checkins at python.org (antoine.pitrou) Date: Mon, 31 May 2010 19:06:44 +0200 (CEST) Subject: [Python-checkins] r81624 - in python/branches/release31-maint: Doc/library/socket.rst Message-ID: <20100531170644.E07E4EEC1B@mail.python.org> Author: antoine.pitrou Date: Mon May 31 19:06:44 2010 New Revision: 81624 Log: Merged revisions 81623 via svnmerge from svn+ssh://pythondev at svn.python.org/python/branches/py3k ................ r81623 | antoine.pitrou | 2010-05-31 19:04:40 +0200 (lun., 31 mai 2010) | 9 lines Merged revisions 81621 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r81621 | antoine.pitrou | 2010-05-31 19:01:01 +0200 (lun., 31 mai 2010) | 4 lines Improve documentation for getaddrinfo() (part of #8857) ........ ................ Modified: python/branches/release31-maint/ (props changed) python/branches/release31-maint/Doc/library/socket.rst Modified: python/branches/release31-maint/Doc/library/socket.rst ============================================================================== --- python/branches/release31-maint/Doc/library/socket.rst (original) +++ python/branches/release31-maint/Doc/library/socket.rst Mon May 31 19:06:44 2010 @@ -205,27 +205,44 @@ :func:`getdefaulttimeout` is used. -.. function:: getaddrinfo(host, port[, family[, socktype[, proto[, flags]]]]) +.. function:: getaddrinfo(host, port, family=0, socktype=0, proto=0, flags=0) - Resolves the *host*/*port* argument, into a sequence of 5-tuples that contain - all the necessary arguments for creating the corresponding socket. *host* is a domain - name, a string representation of an IPv4/v6 address or ``None``. *port* is a string - service name such as ``'http'``, a numeric port number or ``None``. - The rest of the arguments are optional and must be numeric if specified. - By passing ``None`` as the value of *host* and *port*, , you can pass ``NULL`` to the C API. + Translate the *host*/*port* argument into a sequence of 5-tuples that contain + all the necessary arguments for creating a socket connected to that service. + *host* is a domain name, a string representation of an IPv4/v6 address + or ``None``. *port* is a string service name such as ``'http'``, a numeric + port number or ``None``. By passing ``None`` as the value of *host* + and *port*, you can pass ``NULL`` to the underlying C API. + + The *family*, *socktype* and *proto* arguments can be optionally specified + in order to narrow the list of addresses returned. Passing zero as a + value for each of these arguments selects the full range of results. + The *flags* argument can be one or several of the ``AI_*`` constants, + and will influence how results are computed and returned. + For example, :const:`AI_NUMERICHOST` will disable domain name resolution + and will raise an error if *host* is a domain name. - The :func:`getaddrinfo` function returns a list of 5-tuples with the following - structure: + The function returns a list of 5-tuples with the following structure: ``(family, socktype, proto, canonname, sockaddr)`` - *family*, *socktype*, *proto* are all integers and are meant to be passed to the - :func:`socket` function. *canonname* is a string representing the canonical name - of the *host*. It can be a numeric IPv4/v6 address when :const:`AI_CANONNAME` is - specified for a numeric *host*. *sockaddr* is a tuple describing a socket - address, as described above. See the source for :mod:`socket` and other - library modules for a typical usage of the function. - + In these tuples, *family*, *socktype*, *proto* are all integers and are + meant to be passed to the :func:`socket` function. *canonname* will be + a string representing the canonical name of the *host* if + :const:`AI_CANONNAME` is part of the *flags* argument; else *canonname* + will be empty. *sockaddr* is a tuple describing a socket address, whose + format depends on the returned *family* (a ``(address, port)`` 2-tuple for + :const:`AF_INET`, a ``(address, port, flow info, scope id)`` 4-tuple for + :const:`AF_INET6`), and is meant to be passed to the :meth:`socket.connect` + method. + + The following example fetches address information for a hypothetical TCP + connection to ``www.python.org`` on port 80 (results may differ on your + system if IPv6 isn't enabled):: + + >>> socket.getaddrinfo("www.python.org", 80, 0, 0, socket.SOL_TCP) + [(2, 1, 6, '', ('82.94.164.162', 80)), + (10, 1, 6, '', ('2001:888:2000:d::a2', 80, 0, 0))] .. function:: getfqdn([name]) From python-checkins at python.org Mon May 31 19:33:47 2010 From: python-checkins at python.org (alexander.belopolsky) Date: Mon, 31 May 2010 19:33:47 +0200 (CEST) Subject: [Python-checkins] r81625 - in python/branches/py3k: Doc/library/datetime.rst Lib/test/test_datetime.py Misc/NEWS Modules/datetimemodule.c Message-ID: <20100531173347.C67E4EE9E9@mail.python.org> Author: alexander.belopolsky Date: Mon May 31 19:33:47 2010 New Revision: 81625 Log: Issue #1289118: datetime.timedelta objects can now be multiplied by float and divided by float and int objects. Modified: python/branches/py3k/Doc/library/datetime.rst python/branches/py3k/Lib/test/test_datetime.py python/branches/py3k/Misc/NEWS python/branches/py3k/Modules/datetimemodule.c Modified: python/branches/py3k/Doc/library/datetime.rst ============================================================================== --- python/branches/py3k/Doc/library/datetime.rst (original) +++ python/branches/py3k/Doc/library/datetime.rst Mon May 31 19:33:47 2010 @@ -220,12 +220,20 @@ | | In general, *t1* \* i == *t1* \* (i-1) + *t1* | | | is true. (1) | +--------------------------------+-----------------------------------------------+ +| ``t1 = t2 * f or t1 = f * t2`` | Delta multiplied by a float. The result is | +| | rounded to the nearest multiple of | +| | timedelta.resolution using round-half-to-even.| ++--------------------------------+-----------------------------------------------+ | ``f = t2 / t3`` | Division (3) of *t2* by *t3*. Returns a | | | :class:`float` object. | +--------------------------------+-----------------------------------------------+ +| ``t1 = t2 / f or t1 = t2 / i`` | Delta divided by a float or an int. The result| +| | is rounded to the nearest multiple of | +| | timedelta.resolution using round-half-to-even.| ++--------------------------------+-----------------------------------------------+ | ``t1 = t2 // i`` or | The floor is computed and the remainder (if | | ``t1 = t2 // t3`` | any) is thrown away. In the second case, an | -| | integer is returned (3) | +| | integer is returned. (3) | +--------------------------------+-----------------------------------------------+ | ``t1 = t2 % t3`` | The remainder is computed as a | | | :class:`timedelta` object. (3) | @@ -267,7 +275,9 @@ .. versionadded:: 3.2 Floor division and true division of a :class:`timedelta` object by another :class:`timedelta` object are now supported, as are - remainder operations and the :func:`divmod` function. + remainder operations and the :func:`divmod` function. True + division and multiplication of a :class:`timedelta` object by + a :class:`float` object are now supported. Comparisons of :class:`timedelta` objects are supported with the Modified: python/branches/py3k/Lib/test/test_datetime.py ============================================================================== --- python/branches/py3k/Lib/test/test_datetime.py (original) +++ python/branches/py3k/Lib/test/test_datetime.py Mon May 31 19:33:47 2010 @@ -25,6 +25,16 @@ OTHERSTUFF = (10, 34.5, "abc", {}, [], ()) +# XXX Copied from test_float. +INF = float("inf") +NAN = float("nan") + +# decorator for skipping tests on non-IEEE 754 platforms +requires_IEEE_754 = unittest.skipUnless( + float.__getformat__("double").startswith("IEEE"), + "test requires IEEE 754 doubles") + + ############################################################################# # module tests @@ -225,6 +235,36 @@ eq(c//1000, td(0, 0, 1)) eq(a//10, td(0, 7*24*360)) eq(a//3600000, td(0, 0, 7*24*1000)) + eq(a/0.5, td(14)) + eq(b/0.5, td(0, 120)) + eq(a/7, td(1)) + eq(b/10, td(0, 6)) + eq(c/1000, td(0, 0, 1)) + eq(a/10, td(0, 7*24*360)) + eq(a/3600000, td(0, 0, 7*24*1000)) + + # Multiplication by float + us = td(microseconds=1) + eq((3*us) * 0.5, 2*us) + eq((5*us) * 0.5, 2*us) + eq(0.5 * (3*us), 2*us) + eq(0.5 * (5*us), 2*us) + eq((-3*us) * 0.5, -2*us) + eq((-5*us) * 0.5, -2*us) + + # Division by int and float + eq((3*us) / 2, 2*us) + eq((5*us) / 2, 2*us) + eq((-3*us) / 2.0, -2*us) + eq((-5*us) / 2.0, -2*us) + eq((3*us) / -2, -2*us) + eq((5*us) / -2, -2*us) + eq((3*us) / -2.0, -2*us) + eq((5*us) / -2.0, -2*us) + for i in range(-10, 10): + eq((i*us/3)//us, round(i/3)) + for i in range(-10, 10): + eq((i*us/-3)//us, round(i/-3)) def test_disallowed_computations(self): a = timedelta(42) @@ -236,20 +276,19 @@ self.assertRaises(TypeError, lambda: i+a) self.assertRaises(TypeError, lambda: i-a) - # Mul/div by float isn't supported. - x = 2.3 - self.assertRaises(TypeError, lambda: a*x) - self.assertRaises(TypeError, lambda: x*a) - self.assertRaises(TypeError, lambda: a/x) - self.assertRaises(TypeError, lambda: x/a) - self.assertRaises(TypeError, lambda: a // x) - self.assertRaises(TypeError, lambda: x // a) - # Division of int by timedelta doesn't make sense. # Division by zero doesn't make sense. zero = 0 self.assertRaises(TypeError, lambda: zero // a) self.assertRaises(ZeroDivisionError, lambda: a // zero) + self.assertRaises(ZeroDivisionError, lambda: a / zero) + self.assertRaises(ZeroDivisionError, lambda: a / 0.0) + + @requires_IEEE_754 + def test_disallowed_special(self): + a = timedelta(42) + self.assertRaises(ValueError, a.__mul__, NAN) + self.assertRaises(ValueError, a.__truediv__, NAN) def test_basic_attributes(self): days, seconds, us = 1, 7, 31 @@ -410,6 +449,19 @@ self.assertRaises(OverflowError, lambda: -timedelta.max) + day = timedelta(1) + self.assertRaises(OverflowError, day.__mul__, 10**9) + self.assertRaises(OverflowError, day.__mul__, 1e9) + self.assertRaises(OverflowError, day.__truediv__, 1e-20) + self.assertRaises(OverflowError, day.__truediv__, 1e-10) + self.assertRaises(OverflowError, day.__truediv__, 9e-10) + + @requires_IEEE_754 + def _test_overflow_special(self): + day = timedelta(1) + self.assertRaises(OverflowError, day.__mul__, INF) + self.assertRaises(OverflowError, day.__mul__, -INF) + def test_microsecond_rounding(self): td = timedelta eq = self.assertEqual @@ -489,7 +541,7 @@ self.assertRaises(ZeroDivisionError, truediv, t, zerotd) self.assertRaises(ZeroDivisionError, floordiv, t, zerotd) - self.assertRaises(TypeError, truediv, t, 2) + # self.assertRaises(TypeError, truediv, t, 2) # note: floor division of a timedelta by an integer *is* # currently permitted. Modified: python/branches/py3k/Misc/NEWS ============================================================================== --- python/branches/py3k/Misc/NEWS (original) +++ python/branches/py3k/Misc/NEWS Mon May 31 19:33:47 2010 @@ -398,6 +398,11 @@ Library ------- +- Issue #1289118: datetime.timedelta objects can now be multiplied by float + and divided by float and int objects. Results are rounded to the nearest + multiple of timedelta.resolution with ties resolved using round-half-to-even + method. + - Issue #7150: Raise OverflowError if the result of adding or subtracting timedelta from date or datetime falls outside of the MINYEAR:MAXYEAR range. Modified: python/branches/py3k/Modules/datetimemodule.c ============================================================================== --- python/branches/py3k/Modules/datetimemodule.c (original) +++ python/branches/py3k/Modules/datetimemodule.c Mon May 31 19:33:47 2010 @@ -152,6 +152,25 @@ return (long)x; } +/* Nearest integer to m / n for integers m and n. Half-integer results + * are rounded to even. + */ +static PyObject * +divide_nearest(PyObject *m, PyObject *n) +{ + PyObject *result; + PyObject *temp; + + temp = _PyLong_Divmod_Near(m, n); + if (temp == NULL) + return NULL; + result = PyTuple_GET_ITEM(temp, 0); + Py_INCREF(result); + Py_DECREF(temp); + + return result; +} + /* --------------------------------------------------------------------------- * General calendrical helper functions */ @@ -1648,6 +1667,37 @@ } static PyObject * +multiply_float_timedelta(PyObject *floatobj, PyDateTime_Delta *delta) +{ + PyObject *result = NULL; + PyObject *pyus_in = NULL, *temp, *pyus_out; + PyObject *ratio = NULL; + + pyus_in = delta_to_microseconds(delta); + if (pyus_in == NULL) + return NULL; + ratio = PyObject_CallMethod(floatobj, "as_integer_ratio", NULL); + if (ratio == NULL) + goto error; + temp = PyNumber_Multiply(pyus_in, PyTuple_GET_ITEM(ratio, 0)); + Py_DECREF(pyus_in); + pyus_in = NULL; + if (temp == NULL) + goto error; + pyus_out = divide_nearest(temp, PyTuple_GET_ITEM(ratio, 1)); + Py_DECREF(temp); + if (pyus_out == NULL) + goto error; + result = microseconds_to_delta(pyus_out); + Py_DECREF(pyus_out); + error: + Py_XDECREF(pyus_in); + Py_XDECREF(ratio); + + return result; +} + +static PyObject * divide_timedelta_int(PyDateTime_Delta *delta, PyObject *intobj) { PyObject *pyus_in; @@ -1715,6 +1765,55 @@ } static PyObject * +truedivide_timedelta_float(PyDateTime_Delta *delta, PyObject *f) +{ + PyObject *result = NULL; + PyObject *pyus_in = NULL, *temp, *pyus_out; + PyObject *ratio = NULL; + + pyus_in = delta_to_microseconds(delta); + if (pyus_in == NULL) + return NULL; + ratio = PyObject_CallMethod(f, "as_integer_ratio", NULL); + if (ratio == NULL) + goto error; + temp = PyNumber_Multiply(pyus_in, PyTuple_GET_ITEM(ratio, 1)); + Py_DECREF(pyus_in); + pyus_in = NULL; + if (temp == NULL) + goto error; + pyus_out = divide_nearest(temp, PyTuple_GET_ITEM(ratio, 0)); + Py_DECREF(temp); + if (pyus_out == NULL) + goto error; + result = microseconds_to_delta(pyus_out); + Py_DECREF(pyus_out); + error: + Py_XDECREF(pyus_in); + Py_XDECREF(ratio); + + return result; +} + +static PyObject * +truedivide_timedelta_int(PyDateTime_Delta *delta, PyObject *i) +{ + PyObject *result; + PyObject *pyus_in, *pyus_out; + pyus_in = delta_to_microseconds(delta); + if (pyus_in == NULL) + return NULL; + pyus_out = divide_nearest(pyus_in, i); + Py_DECREF(pyus_in); + if (pyus_out == NULL) + return NULL; + result = microseconds_to_delta(pyus_out); + Py_DECREF(pyus_out); + + return result; +} + +static PyObject * delta_add(PyObject *left, PyObject *right) { PyObject *result = Py_NotImplemented; @@ -1838,10 +1937,16 @@ if (PyLong_Check(right)) result = multiply_int_timedelta(right, (PyDateTime_Delta *) left); + else if (PyFloat_Check(right)) + result = multiply_float_timedelta(right, + (PyDateTime_Delta *) left); } else if (PyLong_Check(left)) result = multiply_int_timedelta(left, - (PyDateTime_Delta *) right); + (PyDateTime_Delta *) right); + else if (PyFloat_Check(left)) + result = multiply_float_timedelta(left, + (PyDateTime_Delta *) right); if (result == Py_NotImplemented) Py_INCREF(result); @@ -1880,6 +1985,12 @@ result = truedivide_timedelta_timedelta( (PyDateTime_Delta *)left, (PyDateTime_Delta *)right); + else if (PyFloat_Check(right)) + result = truedivide_timedelta_float( + (PyDateTime_Delta *)left, right); + else if (PyLong_Check(right)) + result = truedivide_timedelta_int( + (PyDateTime_Delta *)left, right); } if (result == Py_NotImplemented)